aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorzakk <zakk@edf5b092-35ff-0310-97b2-ce42778d08ea>2005-08-26 04:48:05 +0000
committerzakk <zakk@edf5b092-35ff-0310-97b2-ce42778d08ea>2005-08-26 04:48:05 +0000
commit952c5c128f9efaea89d41d882c4ea3ade7df4591 (patch)
tree91b84d9be7afad7e99ac64a640a65b6cb5081900
parentc2c2e0d25d6cdb7d42d7dc981a863f65f94f281d (diff)
downloadioquake3-aero-952c5c128f9efaea89d41d882c4ea3ade7df4591.tar.gz
ioquake3-aero-952c5c128f9efaea89d41d882c4ea3ade7df4591.zip
Itsa me, quake3io!
git-svn-id: svn://svn.icculus.org/quake3/trunk@2 edf5b092-35ff-0310-97b2-ce42778d08ea
-rwxr-xr-xCOPYING.txt281
-rwxr-xr-xREADME.txt193
-rwxr-xr-xcode/Construct431
-rwxr-xr-xcode/Makefile3
-rwxr-xr-xcode/botlib/aasfile.h267
-rwxr-xr-xcode/botlib/be_aas_bsp.h89
-rwxr-xr-xcode/botlib/be_aas_bspq3.c487
-rwxr-xr-xcode/botlib/be_aas_cluster.c1545
-rwxr-xr-xcode/botlib/be_aas_cluster.h38
-rwxr-xr-xcode/botlib/be_aas_debug.c777
-rwxr-xr-xcode/botlib/be_aas_debug.h62
-rwxr-xr-xcode/botlib/be_aas_def.h306
-rwxr-xr-xcode/botlib/be_aas_entity.c437
-rwxr-xr-xcode/botlib/be_aas_entity.h63
-rwxr-xr-xcode/botlib/be_aas_file.c582
-rwxr-xr-xcode/botlib/be_aas_file.h42
-rwxr-xr-xcode/botlib/be_aas_funcs.h47
-rwxr-xr-xcode/botlib/be_aas_main.c429
-rwxr-xr-xcode/botlib/be_aas_main.h61
-rwxr-xr-xcode/botlib/be_aas_move.c1101
-rwxr-xr-xcode/botlib/be_aas_move.h71
-rwxr-xr-xcode/botlib/be_aas_optimize.c312
-rwxr-xr-xcode/botlib/be_aas_optimize.h33
-rwxr-xr-xcode/botlib/be_aas_reach.c4547
-rwxr-xr-xcode/botlib/be_aas_reach.h68
-rwxr-xr-xcode/botlib/be_aas_route.c2209
-rwxr-xr-xcode/botlib/be_aas_route.h67
-rwxr-xr-xcode/botlib/be_aas_routealt.c240
-rwxr-xr-xcode/botlib/be_aas_routealt.h40
-rwxr-xr-xcode/botlib/be_aas_sample.c1394
-rwxr-xr-xcode/botlib/be_aas_sample.h69
-rwxr-xr-xcode/botlib/be_ai_char.c790
-rwxr-xr-xcode/botlib/be_ai_chat.c3017
-rwxr-xr-xcode/botlib/be_ai_gen.c134
-rwxr-xr-xcode/botlib/be_ai_goal.c1821
-rwxr-xr-xcode/botlib/be_ai_move.c3610
-rwxr-xr-xcode/botlib/be_ai_weap.c543
-rwxr-xr-xcode/botlib/be_ai_weight.c912
-rwxr-xr-xcode/botlib/be_ai_weight.h83
-rwxr-xr-xcode/botlib/be_ea.c508
-rwxr-xr-xcode/botlib/be_interface.c881
-rwxr-xr-xcode/botlib/be_interface.h57
-rwxr-xr-xcode/botlib/botlib.vcproj1559
-rwxr-xr-xcode/botlib/l_crc.c151
-rwxr-xr-xcode/botlib/l_crc.h29
-rwxr-xr-xcode/botlib/l_libvar.c294
-rwxr-xr-xcode/botlib/l_libvar.h63
-rwxr-xr-xcode/botlib/l_log.c169
-rwxr-xr-xcode/botlib/l_log.h46
-rwxr-xr-xcode/botlib/l_memory.c463
-rwxr-xr-xcode/botlib/l_memory.h76
-rwxr-xr-xcode/botlib/l_precomp.c3228
-rwxr-xr-xcode/botlib/l_precomp.h180
-rwxr-xr-xcode/botlib/l_script.c1433
-rwxr-xr-xcode/botlib/l_script.h247
-rwxr-xr-xcode/botlib/l_struct.c462
-rwxr-xr-xcode/botlib/l_struct.h75
-rwxr-xr-xcode/botlib/l_utils.h35
-rwxr-xr-xcode/botlib/lcc.mak55
-rwxr-xr-xcode/botlib/linux-i386.mak92
-rwxr-xr-xcode/bspc/Conscript75
-rwxr-xr-xcode/bspc/Makefile114
-rwxr-xr-xcode/bspc/_files.c63
-rwxr-xr-xcode/bspc/aas_areamerging.c390
-rwxr-xr-xcode/bspc/aas_areamerging.h24
-rwxr-xr-xcode/bspc/aas_cfg.c252
-rwxr-xr-xcode/bspc/aas_cfg.h73
-rwxr-xr-xcode/bspc/aas_create.c1142
-rwxr-xr-xcode/bspc/aas_create.h136
-rwxr-xr-xcode/bspc/aas_edgemelting.c108
-rwxr-xr-xcode/bspc/aas_edgemelting.h24
-rwxr-xr-xcode/bspc/aas_facemerging.c282
-rwxr-xr-xcode/bspc/aas_facemerging.h24
-rwxr-xr-xcode/bspc/aas_file.c549
-rwxr-xr-xcode/bspc/aas_file.h25
-rwxr-xr-xcode/bspc/aas_gsubdiv.c656
-rwxr-xr-xcode/bspc/aas_gsubdiv.h25
-rwxr-xr-xcode/bspc/aas_map.c849
-rwxr-xr-xcode/bspc/aas_map.h23
-rwxr-xr-xcode/bspc/aas_prunenodes.c89
-rwxr-xr-xcode/bspc/aas_prunenodes.h24
-rwxr-xr-xcode/bspc/aas_store.c1082
-rwxr-xr-xcode/bspc/aas_store.h107
-rwxr-xr-xcode/bspc/aasfile.h252
-rwxr-xr-xcode/bspc/be_aas_bspc.c292
-rwxr-xr-xcode/bspc/be_aas_bspc.h23
-rwxr-xr-xcode/bspc/brushbsp.c1871
-rwxr-xr-xcode/bspc/bspc.c991
-rwxr-xr-xcode/bspc/bspc.sln28
-rwxr-xr-xcode/bspc/bspc.vcproj1381
-rwxr-xr-xcode/bspc/cfgq3.c84
-rwxr-xr-xcode/bspc/csg.c1005
-rwxr-xr-xcode/bspc/faces.c978
-rwxr-xr-xcode/bspc/gldraw.c232
-rwxr-xr-xcode/bspc/glfile.c149
-rwxr-xr-xcode/bspc/l_bsp_ent.c180
-rwxr-xr-xcode/bspc/l_bsp_ent.h58
-rwxr-xr-xcode/bspc/l_bsp_hl.c888
-rwxr-xr-xcode/bspc/l_bsp_hl.h314
-rwxr-xr-xcode/bspc/l_bsp_q1.c620
-rwxr-xr-xcode/bspc/l_bsp_q1.h275
-rwxr-xr-xcode/bspc/l_bsp_q2.c1134
-rwxr-xr-xcode/bspc/l_bsp_q2.h98
-rwxr-xr-xcode/bspc/l_bsp_q3.c824
-rwxr-xr-xcode/bspc/l_bsp_q3.h81
-rwxr-xr-xcode/bspc/l_bsp_sin.c1186
-rwxr-xr-xcode/bspc/l_bsp_sin.h106
-rwxr-xr-xcode/bspc/l_cmd.c1230
-rwxr-xr-xcode/bspc/l_cmd.h157
-rwxr-xr-xcode/bspc/l_log.c215
-rwxr-xr-xcode/bspc/l_log.h42
-rwxr-xr-xcode/bspc/l_math.c289
-rwxr-xr-xcode/bspc/l_math.h93
-rwxr-xr-xcode/bspc/l_mem.c441
-rwxr-xr-xcode/bspc/l_mem.h51
-rwxr-xr-xcode/bspc/l_poly.c1411
-rwxr-xr-xcode/bspc/l_poly.h120
-rwxr-xr-xcode/bspc/l_qfiles.c663
-rwxr-xr-xcode/bspc/l_qfiles.h91
-rwxr-xr-xcode/bspc/l_threads.c1510
-rwxr-xr-xcode/bspc/l_threads.h45
-rwxr-xr-xcode/bspc/l_utils.c259
-rwxr-xr-xcode/bspc/l_utils.h79
-rwxr-xr-xcode/bspc/lcc.mak61
-rwxr-xr-xcode/bspc/leakfile.c101
-rwxr-xr-xcode/bspc/linux-i386.mak109
-rwxr-xr-xcode/bspc/map.c1267
-rwxr-xr-xcode/bspc/map_hl.c1114
-rwxr-xr-xcode/bspc/map_q1.c1174
-rwxr-xr-xcode/bspc/map_q2.c1162
-rwxr-xr-xcode/bspc/map_q3.c681
-rwxr-xr-xcode/bspc/map_sin.c1211
-rwxr-xr-xcode/bspc/nodraw.c47
-rwxr-xr-xcode/bspc/portals.c1297
-rwxr-xr-xcode/bspc/prtfile.c287
-rwxr-xr-xcode/bspc/q2files.h487
-rwxr-xr-xcode/bspc/q3files.h374
-rwxr-xr-xcode/bspc/qbsp.h477
-rwxr-xr-xcode/bspc/qfiles.h487
-rwxr-xr-xcode/bspc/sinfiles.h365
-rwxr-xr-xcode/bspc/tetrahedron.c1389
-rwxr-xr-xcode/bspc/tetrahedron.h24
-rwxr-xr-xcode/bspc/textures.c228
-rwxr-xr-xcode/bspc/tree.c283
-rwxr-xr-xcode/bspc/writebsp.c595
-rwxr-xr-xcode/cgame.lnt25
-rwxr-xr-xcode/cgame/Conscript138
-rwxr-xr-xcode/cgame/cg_consolecmds.c578
-rwxr-xr-xcode/cgame/cg_draw.c2659
-rwxr-xr-xcode/cgame/cg_drawtools.c824
-rwxr-xr-xcode/cgame/cg_effects.c718
-rwxr-xr-xcode/cgame/cg_ents.c1037
-rwxr-xr-xcode/cgame/cg_event.c1205
-rwxr-xr-xcode/cgame/cg_info.c297
-rwxr-xr-xcode/cgame/cg_local.h1669
-rwxr-xr-xcode/cgame/cg_localents.c886
-rwxr-xr-xcode/cgame/cg_main.c1997
-rwxr-xr-xcode/cgame/cg_marks.c2274
-rwxr-xr-xcode/cgame/cg_newdraw.c1852
-rwxr-xr-xcode/cgame/cg_particles.c2018
-rwxr-xr-xcode/cgame/cg_players.c2619
-rwxr-xr-xcode/cgame/cg_playerstate.c526
-rwxr-xr-xcode/cgame/cg_predict.c628
-rwxr-xr-xcode/cgame/cg_public.h238
-rwxr-xr-xcode/cgame/cg_scoreboard.c534
-rwxr-xr-xcode/cgame/cg_servercmds.c1098
-rwxr-xr-xcode/cgame/cg_snapshot.c403
-rwxr-xr-xcode/cgame/cg_syscalls.asm106
-rwxr-xr-xcode/cgame/cg_syscalls.c445
-rwxr-xr-xcode/cgame/cg_view.c876
-rwxr-xr-xcode/cgame/cg_weapons.c2277
-rwxr-xr-xcode/cgame/cgame.bat63
-rwxr-xr-xcode/cgame/cgame.def3
-rwxr-xr-xcode/cgame/cgame.plg124
-rwxr-xr-xcode/cgame/cgame.q3asm26
-rwxr-xr-xcode/cgame/cgame.sh36
-rwxr-xr-xcode/cgame/cgame.vcproj1221
-rwxr-xr-xcode/cgame/cgame_ta.bat65
-rwxr-xr-xcode/cgame/cgame_ta.q3asm28
-rwxr-xr-xcode/cgame/cgame_ta.sh38
-rwxr-xr-xcode/cgame/tr_types.h229
-rwxr-xr-xcode/clean.bat61
-rwxr-xr-xcode/client/cl_cgame.c1029
-rwxr-xr-xcode/client/cl_cin.c1740
-rwxr-xr-xcode/client/cl_console.c786
-rwxr-xr-xcode/client/cl_input.c901
-rwxr-xr-xcode/client/cl_keys.c1252
-rwxr-xr-xcode/client/cl_main.c3324
-rwxr-xr-xcode/client/cl_net_chan.c167
-rwxr-xr-xcode/client/cl_parse.c655
-rwxr-xr-xcode/client/cl_scrn.c547
-rwxr-xr-xcode/client/cl_ui.c1200
-rwxr-xr-xcode/client/client.h519
-rwxr-xr-xcode/client/keys.h57
-rwxr-xr-xcode/client/snd_adpcm.c330
-rwxr-xr-xcode/client/snd_dma.c1636
-rwxr-xr-xcode/client/snd_local.h204
-rwxr-xr-xcode/client/snd_mem.c404
-rwxr-xr-xcode/client/snd_mix.c681
-rwxr-xr-xcode/client/snd_public.h72
-rwxr-xr-xcode/client/snd_wavelet.c253
-rwxr-xr-xcode/game.lnt35
-rwxr-xr-xcode/game/Conscript140
-rwxr-xr-xcode/game/ai_chat.c1226
-rwxr-xr-xcode/game/ai_chat.h61
-rwxr-xr-xcode/game/ai_cmd.c1992
-rwxr-xr-xcode/game/ai_cmd.h37
-rwxr-xr-xcode/game/ai_dmnet.c2610
-rwxr-xr-xcode/game/ai_dmnet.h61
-rwxr-xr-xcode/game/ai_dmq3.c5461
-rwxr-xr-xcode/game/ai_dmq3.h206
-rwxr-xr-xcode/game/ai_main.c1695
-rwxr-xr-xcode/game/ai_main.h299
-rwxr-xr-xcode/game/ai_team.c2080
-rwxr-xr-xcode/game/ai_team.h39
-rwxr-xr-xcode/game/ai_vcmd.c550
-rwxr-xr-xcode/game/ai_vcmd.h36
-rwxr-xr-xcode/game/be_aas.h221
-rwxr-xr-xcode/game/be_ai_char.h48
-rwxr-xr-xcode/game/be_ai_chat.h113
-rwxr-xr-xcode/game/be_ai_gen.h33
-rwxr-xr-xcode/game/be_ai_goal.h118
-rwxr-xr-xcode/game/be_ai_move.h142
-rwxr-xr-xcode/game/be_ai_weap.h104
-rwxr-xr-xcode/game/be_ea.h66
-rwxr-xr-xcode/game/bg_lib.c1324
-rwxr-xr-xcode/game/bg_lib.h91
-rwxr-xr-xcode/game/bg_local.h83
-rwxr-xr-xcode/game/bg_misc.c1604
-rwxr-xr-xcode/game/bg_pmove.c2069
-rwxr-xr-xcode/game/bg_public.h738
-rwxr-xr-xcode/game/bg_slidemove.c325
-rwxr-xr-xcode/game/botlib.h516
-rwxr-xr-xcode/game/chars.h134
-rwxr-xr-xcode/game/g_active.c1191
-rwxr-xr-xcode/game/g_arenas.c376
-rwxr-xr-xcode/game/g_bot.c1017
-rwxr-xr-xcode/game/g_client.c1344
-rwxr-xr-xcode/game/g_cmds.c1701
-rwxr-xr-xcode/game/g_combat.c1195
-rwxr-xr-xcode/game/g_items.c1010
-rwxr-xr-xcode/game/g_local.h971
-rwxr-xr-xcode/game/g_main.c1832
-rwxr-xr-xcode/game/g_mem.c61
-rwxr-xr-xcode/game/g_misc.c482
-rwxr-xr-xcode/game/g_missile.c808
-rwxr-xr-xcode/game/g_mover.c1612
-rwxr-xr-xcode/game/g_public.h429
-rwxr-xr-xcode/game/g_rankings.c1135
-rwxr-xr-xcode/game/g_rankings.h396
-rwxr-xr-xcode/game/g_session.c193
-rwxr-xr-xcode/game/g_spawn.c643
-rwxr-xr-xcode/game/g_svcmds.c508
-rwxr-xr-xcode/game/g_syscalls.asm225
-rwxr-xr-xcode/game/g_syscalls.c790
-rwxr-xr-xcode/game/g_target.c467
-rwxr-xr-xcode/game/g_team.c1483
-rwxr-xr-xcode/game/g_team.h88
-rwxr-xr-xcode/game/g_trigger.c465
-rwxr-xr-xcode/game/g_utils.c666
-rwxr-xr-xcode/game/g_weapon.c1145
-rwxr-xr-xcode/game/game.bat85
-rwxr-xr-xcode/game/game.def3
-rwxr-xr-xcode/game/game.q3asm35
-rwxr-xr-xcode/game/game.sh48
-rwxr-xr-xcode/game/game.vcproj2132
-rwxr-xr-xcode/game/game_ta.bat86
-rwxr-xr-xcode/game/game_ta.q3asm35
-rwxr-xr-xcode/game/game_ta.sh48
-rwxr-xr-xcode/game/inv.h166
-rwxr-xr-xcode/game/match.h134
-rwxr-xr-xcode/game/q_math.c1308
-rwxr-xr-xcode/game/q_shared.c1258
-rwxr-xr-xcode/game/q_shared.h1432
-rwxr-xr-xcode/game/surfaceflags.h80
-rwxr-xr-xcode/game/syn.h34
-rwxr-xr-xcode/installdebug.bat6
-rwxr-xr-xcode/installrelease.bat14
-rwxr-xr-xcode/installvms.bat7
-rwxr-xr-xcode/jpeg-6/README385
-rwxr-xr-xcode/jpeg-6/jcapimin.c228
-rwxr-xr-xcode/jpeg-6/jcapistd.c161
-rwxr-xr-xcode/jpeg-6/jccoefct.c448
-rwxr-xr-xcode/jpeg-6/jccolor.c459
-rwxr-xr-xcode/jpeg-6/jcdctmgr.c391
-rwxr-xr-xcode/jpeg-6/jchuff.c846
-rwxr-xr-xcode/jpeg-6/jchuff.h34
-rwxr-xr-xcode/jpeg-6/jcinit.c72
-rwxr-xr-xcode/jpeg-6/jcmainct.c296
-rwxr-xr-xcode/jpeg-6/jcmarker.c639
-rwxr-xr-xcode/jpeg-6/jcmaster.c578
-rwxr-xr-xcode/jpeg-6/jcomapi.c94
-rwxr-xr-xcode/jpeg-6/jconfig.h41
-rwxr-xr-xcode/jpeg-6/jcparam.c575
-rwxr-xr-xcode/jpeg-6/jcphuff.c829
-rwxr-xr-xcode/jpeg-6/jcprepct.c371
-rwxr-xr-xcode/jpeg-6/jcsample.c519
-rwxr-xr-xcode/jpeg-6/jctrans.c371
-rwxr-xr-xcode/jpeg-6/jdapimin.c398
-rwxr-xr-xcode/jpeg-6/jdapistd.c275
-rwxr-xr-xcode/jpeg-6/jdatadst.c151
-rwxr-xr-xcode/jpeg-6/jdatasrc.c204
-rwxr-xr-xcode/jpeg-6/jdcoefct.c725
-rwxr-xr-xcode/jpeg-6/jdcolor.c367
-rwxr-xr-xcode/jpeg-6/jdct.h176
-rwxr-xr-xcode/jpeg-6/jddctmgr.c270
-rwxr-xr-xcode/jpeg-6/jdhuff.c574
-rwxr-xr-xcode/jpeg-6/jdhuff.h202
-rwxr-xr-xcode/jpeg-6/jdinput.c381
-rwxr-xr-xcode/jpeg-6/jdmainct.c520
-rwxr-xr-xcode/jpeg-6/jdmarker.c1052
-rwxr-xr-xcode/jpeg-6/jdmaster.c557
-rwxr-xr-xcode/jpeg-6/jdmerge.c400
-rwxr-xr-xcode/jpeg-6/jdphuff.c642
-rwxr-xr-xcode/jpeg-6/jdpostct.c290
-rwxr-xr-xcode/jpeg-6/jdsample.c478
-rwxr-xr-xcode/jpeg-6/jdtrans.c122
-rwxr-xr-xcode/jpeg-6/jerror.c232
-rwxr-xr-xcode/jpeg-6/jerror.h273
-rwxr-xr-xcode/jpeg-6/jfdctflt.c168
-rwxr-xr-xcode/jpeg-6/jfdctfst.c224
-rwxr-xr-xcode/jpeg-6/jfdctint.c283
-rwxr-xr-xcode/jpeg-6/jidctflt.c241
-rwxr-xr-xcode/jpeg-6/jidctfst.c367
-rwxr-xr-xcode/jpeg-6/jidctint.c388
-rwxr-xr-xcode/jpeg-6/jidctred.c397
-rwxr-xr-xcode/jpeg-6/jinclude.h116
-rwxr-xr-xcode/jpeg-6/jload.c145
-rwxr-xr-xcode/jpeg-6/jmemansi.c167
-rwxr-xr-xcode/jpeg-6/jmemdos.c634
-rwxr-xr-xcode/jpeg-6/jmemmgr.c1115
-rwxr-xr-xcode/jpeg-6/jmemname.c271
-rwxr-xr-xcode/jpeg-6/jmemnobs.c105
-rwxr-xr-xcode/jpeg-6/jmemsys.h182
-rwxr-xr-xcode/jpeg-6/jmorecfg.h348
-rwxr-xr-xcode/jpeg-6/jpegint.h388
-rwxr-xr-xcode/jpeg-6/jpeglib.h1051
-rwxr-xr-xcode/jpeg-6/jpegtran.c370
-rwxr-xr-xcode/jpeg-6/jquant1.c856
-rwxr-xr-xcode/jpeg-6/jquant2.c1310
-rwxr-xr-xcode/jpeg-6/jutils.c175
-rwxr-xr-xcode/jpeg-6/jversion.h14
-rwxr-xr-xcode/macosx/BuildRelease17
-rwxr-xr-xcode/macosx/CGMouseDeltaFix.h27
-rwxr-xr-xcode/macosx/CGMouseDeltaFix.m131
-rwxr-xr-xcode/macosx/CGPrivateAPI.h185
-rwxr-xr-xcode/macosx/GenerateQGL.pl146
-rwxr-xr-xcode/macosx/Performance.rtf114
-rwxr-xr-xcode/macosx/Q3Controller.h40
-rwxr-xr-xcode/macosx/Q3Controller.m435
-rwxr-xr-xcode/macosx/Quake3.icnsbin0 -> 35224 bytes
-rwxr-xr-xcode/macosx/Quake3.nib/classes.nib18
-rwxr-xr-xcode/macosx/Quake3.nib/info.nib19
-rwxr-xr-xcode/macosx/Quake3.nib/objects.nibbin0 -> 765 bytes
-rwxr-xr-xcode/macosx/Quake3.pbproj/apple.pbxuser563
-rwxr-xr-xcode/macosx/Quake3.pbproj/project.pbxproj11802
-rwxr-xr-xcode/macosx/RecordDemo.zsh9
-rwxr-xr-xcode/macosx/banner.jpgbin0 -> 55841 bytes
-rwxr-xr-xcode/macosx/botlib.log196
-rwxr-xr-xcode/macosx/macosx_display.h38
-rwxr-xr-xcode/macosx/macosx_display.m373
-rwxr-xr-xcode/macosx/macosx_glimp.h37
-rwxr-xr-xcode/macosx/macosx_glimp.m1114
-rwxr-xr-xcode/macosx/macosx_glsmp_mutex.m176
-rwxr-xr-xcode/macosx/macosx_glsmp_null.m46
-rwxr-xr-xcode/macosx/macosx_glsmp_ports.m425
-rwxr-xr-xcode/macosx/macosx_input.m916
-rwxr-xr-xcode/macosx/macosx_local.h129
-rwxr-xr-xcode/macosx/macosx_qgl.h5095
-rwxr-xr-xcode/macosx/macosx_sndcore.m325
-rwxr-xr-xcode/macosx/macosx_snddma.m205
-rwxr-xr-xcode/macosx/macosx_sys.m537
-rwxr-xr-xcode/macosx/macosx_timers.h56
-rwxr-xr-xcode/macosx/macosx_timers.m75
-rwxr-xr-xcode/macosx/timedemo.zsh26
-rwxr-xr-xcode/null/mac_net.c65
-rwxr-xr-xcode/null/null_client.c91
-rwxr-xr-xcode/null/null_glimp.c56
-rwxr-xr-xcode/null/null_input.c35
-rwxr-xr-xcode/null/null_main.c116
-rwxr-xr-xcode/null/null_net.c64
-rwxr-xr-xcode/null/null_snddma.c60
-rwxr-xr-xcode/opts.lnt26
-rwxr-xr-xcode/q3_ui/Conscript93
-rwxr-xr-xcode/q3_ui/compile.bat2
-rwxr-xr-xcode/q3_ui/keycodes.h163
-rwxr-xr-xcode/q3_ui/q3_ui.bat100
-rwxr-xr-xcode/q3_ui/q3_ui.q3asm43
-rwxr-xr-xcode/q3_ui/q3_ui.sh55
-rwxr-xr-xcode/q3_ui/q3_ui.vcproj2008
-rwxr-xr-xcode/q3_ui/ui.def3
-rwxr-xr-xcode/q3_ui/ui.q3asm45
-rwxr-xr-xcode/q3_ui/ui_addbots.c412
-rwxr-xr-xcode/q3_ui/ui_atoms.c1267
-rwxr-xr-xcode/q3_ui/ui_cdkey.c291
-rwxr-xr-xcode/q3_ui/ui_cinematics.c350
-rwxr-xr-xcode/q3_ui/ui_confirm.c293
-rwxr-xr-xcode/q3_ui/ui_connect.c282
-rwxr-xr-xcode/q3_ui/ui_controls2.c1667
-rwxr-xr-xcode/q3_ui/ui_credits.c129
-rwxr-xr-xcode/q3_ui/ui_demo2.c291
-rwxr-xr-xcode/q3_ui/ui_display.c265
-rwxr-xr-xcode/q3_ui/ui_gameinfo.c820
-rwxr-xr-xcode/q3_ui/ui_ingame.c349
-rwxr-xr-xcode/q3_ui/ui_loadconfig.c274
-rwxr-xr-xcode/q3_ui/ui_local.h800
-rwxr-xr-xcode/q3_ui/ui_login.c208
-rwxr-xr-xcode/q3_ui/ui_main.c249
-rwxr-xr-xcode/q3_ui/ui_menu.c419
-rwxr-xr-xcode/q3_ui/ui_mfield.c439
-rwxr-xr-xcode/q3_ui/ui_mods.c283
-rwxr-xr-xcode/q3_ui/ui_network.c281
-rwxr-xr-xcode/q3_ui/ui_options.c229
-rwxr-xr-xcode/q3_ui/ui_playermodel.c731
-rwxr-xr-xcode/q3_ui/ui_players.c1248
-rwxr-xr-xcode/q3_ui/ui_playersettings.c513
-rwxr-xr-xcode/q3_ui/ui_preferences.c419
-rwxr-xr-xcode/q3_ui/ui_qmenu.c1746
-rwxr-xr-xcode/q3_ui/ui_rankings.c420
-rwxr-xr-xcode/q3_ui/ui_rankstatus.c209
-rwxr-xr-xcode/q3_ui/ui_removebots.c342
-rwxr-xr-xcode/q3_ui/ui_saveconfig.c212
-rwxr-xr-xcode/q3_ui/ui_serverinfo.c272
-rwxr-xr-xcode/q3_ui/ui_servers2.c1640
-rwxr-xr-xcode/q3_ui/ui_setup.c327
-rwxr-xr-xcode/q3_ui/ui_signup.c286
-rwxr-xr-xcode/q3_ui/ui_sound.c316
-rwxr-xr-xcode/q3_ui/ui_sparena.c50
-rwxr-xr-xcode/q3_ui/ui_specifyleague.c333
-rwxr-xr-xcode/q3_ui/ui_specifyserver.c213
-rwxr-xr-xcode/q3_ui/ui_splevel.c1008
-rwxr-xr-xcode/q3_ui/ui_sppostgame.c644
-rwxr-xr-xcode/q3_ui/ui_spreset.c194
-rwxr-xr-xcode/q3_ui/ui_spskill.c329
-rwxr-xr-xcode/q3_ui/ui_startserver.c1968
-rwxr-xr-xcode/q3_ui/ui_team.c210
-rwxr-xr-xcode/q3_ui/ui_teamorders.c449
-rwxr-xr-xcode/q3_ui/ui_video.c1070
-rwxr-xr-xcode/qcommon/cm_load.c839
-rwxr-xr-xcode/qcommon/cm_local.h194
-rwxr-xr-xcode/qcommon/cm_patch.c1771
-rwxr-xr-xcode/qcommon/cm_patch.h103
-rwxr-xr-xcode/qcommon/cm_polylib.c737
-rwxr-xr-xcode/qcommon/cm_polylib.h68
-rwxr-xr-xcode/qcommon/cm_public.h76
-rwxr-xr-xcode/qcommon/cm_test.c478
-rwxr-xr-xcode/qcommon/cm_trace.c1471
-rwxr-xr-xcode/qcommon/cmd.c715
-rwxr-xr-xcode/qcommon/cmd.c.save636
-rwxr-xr-xcode/qcommon/common.c3317
-rwxr-xr-xcode/qcommon/cvar.c906
-rwxr-xr-xcode/qcommon/files.c3419
-rwxr-xr-xcode/qcommon/huffman.c437
-rwxr-xr-xcode/qcommon/md4.c299
-rwxr-xr-xcode/qcommon/msg.c1757
-rwxr-xr-xcode/qcommon/net_chan.c742
-rwxr-xr-xcode/qcommon/qcommon.h1067
-rwxr-xr-xcode/qcommon/qfiles.h488
-rwxr-xr-xcode/qcommon/unzip.c4299
-rwxr-xr-xcode/qcommon/unzip.h336
-rwxr-xr-xcode/qcommon/vm.c835
-rwxr-xr-xcode/qcommon/vm_interpreted.c889
-rwxr-xr-xcode/qcommon/vm_local.h180
-rwxr-xr-xcode/qcommon/vm_ppc.c1479
-rwxr-xr-xcode/qcommon/vm_ppc_new.c2119
-rwxr-xr-xcode/qcommon/vm_x86.c1196
-rwxr-xr-xcode/quake3.sln145
-rwxr-xr-xcode/quake3.vcproj3463
-rwxr-xr-xcode/renderer.lnt27
-rwxr-xr-xcode/renderer/qgl.h572
-rwxr-xr-xcode/renderer/qgl_linked.h357
-rwxr-xr-xcode/renderer/ref_trin.def2
-rwxr-xr-xcode/renderer/renderer.vcproj6112
-rwxr-xr-xcode/renderer/tr_animation.c171
-rwxr-xr-xcode/renderer/tr_backend.c1143
-rwxr-xr-xcode/renderer/tr_bsp.c1862
-rwxr-xr-xcode/renderer/tr_cmds.c447
-rwxr-xr-xcode/renderer/tr_curve.c624
-rwxr-xr-xcode/renderer/tr_flares.c447
-rwxr-xr-xcode/renderer/tr_font.c542
-rwxr-xr-xcode/renderer/tr_image.c2520
-rwxr-xr-xcode/renderer/tr_init.c1217
-rwxr-xr-xcode/renderer/tr_light.c395
-rwxr-xr-xcode/renderer/tr_local.h1609
-rwxr-xr-xcode/renderer/tr_main.c1485
-rwxr-xr-xcode/renderer/tr_marks.c443
-rwxr-xr-xcode/renderer/tr_mesh.c397
-rwxr-xr-xcode/renderer/tr_model.c700
-rwxr-xr-xcode/renderer/tr_noise.c95
-rwxr-xr-xcode/renderer/tr_public.h167
-rwxr-xr-xcode/renderer/tr_scene.c409
-rwxr-xr-xcode/renderer/tr_shade.c1361
-rwxr-xr-xcode/renderer/tr_shade_calc.c1205
-rwxr-xr-xcode/renderer/tr_shader.c3013
-rwxr-xr-xcode/renderer/tr_shadows.c341
-rwxr-xr-xcode/renderer/tr_sky.c845
-rwxr-xr-xcode/renderer/tr_surface.c1215
-rwxr-xr-xcode/renderer/tr_world.c668
-rwxr-xr-xcode/run.bat1
-rwxr-xr-xcode/runrelease.bat1
-rwxr-xr-xcode/server/server.h404
-rwxr-xr-xcode/server/sv_bot.c635
-rwxr-xr-xcode/server/sv_ccmds.c762
-rwxr-xr-xcode/server/sv_client.c1531
-rwxr-xr-xcode/server/sv_game.c981
-rwxr-xr-xcode/server/sv_init.c695
-rwxr-xr-xcode/server/sv_main.c855
-rwxr-xr-xcode/server/sv_net_chan.c207
-rwxr-xr-xcode/server/sv_rankings.c1537
-rwxr-xr-xcode/server/sv_snapshot.c682
-rwxr-xr-xcode/server/sv_world.c691
-rwxr-xr-xcode/splines/Splines.vcproj296
-rwxr-xr-xcode/splines/math_angles.cpp150
-rwxr-xr-xcode/splines/math_angles.h195
-rwxr-xr-xcode/splines/math_matrix.cpp134
-rwxr-xr-xcode/splines/math_matrix.h223
-rwxr-xr-xcode/splines/math_quaternion.cpp78
-rwxr-xr-xcode/splines/math_quaternion.h190
-rwxr-xr-xcode/splines/math_vector.cpp144
-rwxr-xr-xcode/splines/math_vector.h574
-rwxr-xr-xcode/splines/q_parse.cpp535
-rwxr-xr-xcode/splines/q_shared.cpp976
-rwxr-xr-xcode/splines/q_shared.h810
-rwxr-xr-xcode/splines/q_shared.hpp810
-rwxr-xr-xcode/splines/splines.cpp1250
-rwxr-xr-xcode/splines/splines.h1075
-rwxr-xr-xcode/splines/util_list.h346
-rwxr-xr-xcode/splines/util_str.cpp620
-rwxr-xr-xcode/splines/util_str.h817
-rwxr-xr-xcode/ui/Conscript62
-rwxr-xr-xcode/ui/compile.bat2
-rwxr-xr-xcode/ui/keycodes.h163
-rwxr-xr-xcode/ui/ui.bat33
-rwxr-xr-xcode/ui/ui.def3
-rwxr-xr-xcode/ui/ui.q3asm12
-rwxr-xr-xcode/ui/ui.vcproj1008
-rwxr-xr-xcode/ui/ui_atoms.c520
-rwxr-xr-xcode/ui/ui_gameinfo.c324
-rwxr-xr-xcode/ui/ui_local.h1136
-rwxr-xr-xcode/ui/ui_main.c5997
-rwxr-xr-xcode/ui/ui_players.c1378
-rwxr-xr-xcode/ui/ui_public.h191
-rwxr-xr-xcode/ui/ui_shared.c5785
-rwxr-xr-xcode/ui/ui_shared.h450
-rwxr-xr-xcode/ui/ui_syscalls.asm101
-rwxr-xr-xcode/ui/ui_syscalls.c401
-rwxr-xr-xcode/ui/ui_util.c29
-rwxr-xr-xcode/unix/ChangeLog2981
-rwxr-xr-xcode/unix/Cons_gcc.pm47
-rwxr-xr-xcode/unix/Conscript-client265
-rwxr-xr-xcode/unix/Conscript-dedicated115
-rwxr-xr-xcode/unix/Conscript-pk3135
-rwxr-xr-xcode/unix/Conscript-sdk122
-rwxr-xr-xcode/unix/Conscript-setup33
-rwxr-xr-xcode/unix/LinuxSupport/CHANGES-1.32.txt150
-rwxr-xr-xcode/unix/LinuxSupport/INSTALL52
-rwxr-xr-xcode/unix/LinuxSupport/index.html283
-rwxr-xr-xcode/unix/LinuxSupport/udp_wide_README.txt20
-rwxr-xr-xcode/unix/LinuxSupport/udp_wide_broadcast.patch57
-rwxr-xr-xcode/unix/Makefile2119
-rwxr-xr-xcode/unix/Makefile.Game285
-rwxr-xr-xcode/unix/Quake3.kdelnk12
-rwxr-xr-xcode/unix/README.EULA184
-rwxr-xr-xcode/unix/README.Linux352
-rwxr-xr-xcode/unix/README.Q3Test306
-rwxr-xr-xcode/unix/build_setup.sh125
-rwxr-xr-xcode/unix/cons6828
-rwxr-xr-xcode/unix/extract_ver.pl9
-rwxr-xr-xcode/unix/ftol.nasm151
-rwxr-xr-xcode/unix/linux_common.c344
-rwxr-xr-xcode/unix/linux_glimp.c1780
-rwxr-xr-xcode/unix/linux_joystick.c207
-rwxr-xr-xcode/unix/linux_local.h49
-rwxr-xr-xcode/unix/linux_qgl.c4153
-rwxr-xr-xcode/unix/linux_signals.c61
-rwxr-xr-xcode/unix/linux_snd.c293
-rwxr-xr-xcode/unix/matha.s425
-rwxr-xr-xcode/unix/pcons-2.3.17911
-rwxr-xr-xcode/unix/q3test.spec.sh52
-rwxr-xr-xcode/unix/qasm.h480
-rwxr-xr-xcode/unix/quake3.gifbin0 -> 1378 bytes
-rwxr-xr-xcode/unix/quake3.xpm161
-rwxr-xr-xcode/unix/run-target.sh12
-rwxr-xr-xcode/unix/snapvector.nasm95
-rwxr-xr-xcode/unix/snd_mixa.s217
-rwxr-xr-xcode/unix/sys_dosa.s115
-rwxr-xr-xcode/unix/unix_glw.h38
-rwxr-xr-xcode/unix/unix_main.c1273
-rwxr-xr-xcode/unix/unix_net.c616
-rwxr-xr-xcode/unix/unix_shared.c435
-rwxr-xr-xcode/unix/vm_x86.c29
-rwxr-xr-xcode/unix/vm_x86a.s462
-rwxr-xr-xcode/win32/background.bmpbin0 -> 197688 bytes
-rwxr-xr-xcode/win32/clear.bmpbin0 -> 5174 bytes
-rwxr-xr-xcode/win32/glw_win.h51
-rwxr-xr-xcode/win32/icon2.icobin0 -> 766 bytes
-rwxr-xr-xcode/win32/mod-sdk-setup/GameSource.VCTbin0 -> 628735 bytes
-rwxr-xr-xcode/win32/mod-sdk-setup/QIIIA Game Source License.docbin0 -> 34304 bytes
-rwxr-xr-xcode/win32/mod-sdk-setup/bin/lcc.exebin0 -> 135223 bytes
-rwxr-xr-xcode/win32/mod-sdk-setup/bin/q3asm.exebin0 -> 69632 bytes
-rwxr-xr-xcode/win32/mod-sdk-setup/bin/q3cpp.exebin0 -> 159801 bytes
-rwxr-xr-xcode/win32/mod-sdk-setup/bin/q3rcc.exebin0 -> 847929 bytes
-rwxr-xr-xcode/win32/qe3.icobin0 -> 766 bytes
-rwxr-xr-xcode/win32/resource.h44
-rwxr-xr-xcode/win32/win_gamma.c214
-rwxr-xr-xcode/win32/win_glimp.c1658
-rwxr-xr-xcode/win32/win_input.c1149
-rwxr-xr-xcode/win32/win_local.h95
-rwxr-xr-xcode/win32/win_main.c1253
-rwxr-xr-xcode/win32/win_net.c1031
-rwxr-xr-xcode/win32/win_qgl.c4374
-rwxr-xr-xcode/win32/win_shared.c306
-rwxr-xr-xcode/win32/win_snd.c388
-rwxr-xr-xcode/win32/win_syscon.c596
-rwxr-xr-xcode/win32/win_wndproc.c456
-rwxr-xr-xcode/win32/winquake.rc71
-rwxr-xr-xcommon/aselib.c933
-rwxr-xr-xcommon/aselib.h31
-rwxr-xr-xcommon/bspfile.c564
-rwxr-xr-xcommon/bspfile.h118
-rwxr-xr-xcommon/cmdlib.c1201
-rwxr-xr-xcommon/cmdlib.h160
-rwxr-xr-xcommon/imagelib.c1164
-rwxr-xr-xcommon/imagelib.h44
-rwxr-xr-xcommon/l3dslib.c300
-rwxr-xr-xcommon/l3dslib.h26
-rwxr-xr-xcommon/mathlib.c434
-rwxr-xr-xcommon/mathlib.h96
-rwxr-xr-xcommon/md4.c277
-rwxr-xr-xcommon/mutex.c197
-rwxr-xr-xcommon/mutex.h28
-rwxr-xr-xcommon/polylib.c740
-rwxr-xr-xcommon/polylib.h57
-rwxr-xr-xcommon/polyset.h51
-rwxr-xr-xcommon/qfiles.h489
-rwxr-xr-xcommon/scriplib.c375
-rwxr-xr-xcommon/scriplib.h55
-rwxr-xr-xcommon/surfaceflags.h72
-rwxr-xr-xcommon/threads.c441
-rwxr-xr-xcommon/threads.h31
-rwxr-xr-xcommon/trilib.c231
-rwxr-xr-xcommon/trilib.h26
-rwxr-xr-xlcc/COPYRIGHT61
-rwxr-xr-xlcc/LOG91
-rwxr-xr-xlcc/README21
-rwxr-xr-xlcc/README.id3
-rwxr-xr-xlcc/alpha/osf/tst/8q.1bk92
-rwxr-xr-xlcc/alpha/osf/tst/8q.2bk2
-rwxr-xr-xlcc/alpha/osf/tst/8q.sbk193
-rwxr-xr-xlcc/alpha/osf/tst/array.1bk4
-rwxr-xr-xlcc/alpha/osf/tst/array.2bk2
-rwxr-xr-xlcc/alpha/osf/tst/array.sbk260
-rwxr-xr-xlcc/alpha/osf/tst/cf.1bk51
-rwxr-xr-xlcc/alpha/osf/tst/cf.2bk0
-rwxr-xr-xlcc/alpha/osf/tst/cf.sbk170
-rwxr-xr-xlcc/alpha/osf/tst/cq.1bk45
-rwxr-xr-xlcc/alpha/osf/tst/cq.2bk4
-rwxr-xr-xlcc/alpha/osf/tst/cq.sbk16904
-rwxr-xr-xlcc/alpha/osf/tst/cvt.1bk11
-rwxr-xr-xlcc/alpha/osf/tst/cvt.2bk2
-rwxr-xr-xlcc/alpha/osf/tst/cvt.sbk744
-rwxr-xr-xlcc/alpha/osf/tst/fields.1bk5
-rwxr-xr-xlcc/alpha/osf/tst/fields.2bk4
-rwxr-xr-xlcc/alpha/osf/tst/fields.sbk325
-rwxr-xr-xlcc/alpha/osf/tst/front.2bk29
-rwxr-xr-xlcc/alpha/osf/tst/front.sbk380
-rwxr-xr-xlcc/alpha/osf/tst/incr.1bk0
-rwxr-xr-xlcc/alpha/osf/tst/incr.2bk9
-rwxr-xr-xlcc/alpha/osf/tst/incr.sbk151
-rwxr-xr-xlcc/alpha/osf/tst/init.1bk16
-rwxr-xr-xlcc/alpha/osf/tst/init.2bk3
-rwxr-xr-xlcc/alpha/osf/tst/init.sbk333
-rwxr-xr-xlcc/alpha/osf/tst/limits.1bk14
-rwxr-xr-xlcc/alpha/osf/tst/limits.2bk0
-rwxr-xr-xlcc/alpha/osf/tst/limits.sbk405
-rwxr-xr-xlcc/alpha/osf/tst/paranoia.1bk195
-rwxr-xr-xlcc/alpha/osf/tst/paranoia.2bk16
-rwxr-xr-xlcc/alpha/osf/tst/paranoia.sbk19291
-rwxr-xr-xlcc/alpha/osf/tst/sort.1bk20
-rwxr-xr-xlcc/alpha/osf/tst/sort.2bk5
-rwxr-xr-xlcc/alpha/osf/tst/sort.sbk323
-rwxr-xr-xlcc/alpha/osf/tst/spill.1bk0
-rwxr-xr-xlcc/alpha/osf/tst/spill.2bk6
-rwxr-xr-xlcc/alpha/osf/tst/spill.sbk272
-rwxr-xr-xlcc/alpha/osf/tst/stdarg.1bk6
-rwxr-xr-xlcc/alpha/osf/tst/stdarg.2bk1
-rwxr-xr-xlcc/alpha/osf/tst/stdarg.sbk430
-rwxr-xr-xlcc/alpha/osf/tst/struct.1bk5
-rwxr-xr-xlcc/alpha/osf/tst/struct.2bk2
-rwxr-xr-xlcc/alpha/osf/tst/struct.sbk443
-rwxr-xr-xlcc/alpha/osf/tst/switch.1bk76
-rwxr-xr-xlcc/alpha/osf/tst/switch.2bk7
-rwxr-xr-xlcc/alpha/osf/tst/switch.sbk903
-rwxr-xr-xlcc/alpha/osf/tst/wf1.1bk74
-rwxr-xr-xlcc/alpha/osf/tst/wf1.2bk2
-rwxr-xr-xlcc/alpha/osf/tst/wf1.sbk400
-rwxr-xr-xlcc/alpha/osf/tst/yacc.1bk10
-rwxr-xr-xlcc/alpha/osf/tst/yacc.2bk3
-rwxr-xr-xlcc/alpha/osf/tst/yacc.sbk2402
-rwxr-xr-xlcc/bin/lcc.exebin0 -> 135223 bytes
-rwxr-xr-xlcc/bin/q3cpp.exebin0 -> 159801 bytes
-rwxr-xr-xlcc/bin/q3rcc.exebin0 -> 847929 bytes
-rwxr-xr-xlcc/buildnt.bat3
-rwxr-xr-xlcc/buildnt.sh4
-rwxr-xr-xlcc/cpp/cpp.c322
-rwxr-xr-xlcc/cpp/cpp.h163
-rwxr-xr-xlcc/cpp/eval.c520
-rwxr-xr-xlcc/cpp/getopt.c52
-rwxr-xr-xlcc/cpp/hideset.c112
-rwxr-xr-xlcc/cpp/include.c122
-rwxr-xr-xlcc/cpp/lex.c581
-rwxr-xr-xlcc/cpp/macro.c515
-rwxr-xr-xlcc/cpp/nlist.c104
-rwxr-xr-xlcc/cpp/tokens.c370
-rwxr-xr-xlcc/cpp/unix.c116
-rwxr-xr-xlcc/custom.mk1
-rwxr-xr-xlcc/doc/4.html754
-rwxr-xr-xlcc/doc/bprint.183
-rwxr-xr-xlcc/doc/bprint.pdfbin0 -> 4963 bytes
-rwxr-xr-xlcc/doc/install.html796
-rwxr-xr-xlcc/doc/lcc.1605
-rwxr-xr-xlcc/doc/lcc.pdfbin0 -> 16421 bytes
-rwxr-xr-xlcc/etc/bprint.c475
-rwxr-xr-xlcc/etc/gcc-solaris.c50
-rwxr-xr-xlcc/etc/irix.c64
-rwxr-xr-xlcc/etc/lcc.c793
-rwxr-xr-xlcc/etc/linux.c74
-rwxr-xr-xlcc/etc/ops.c190
-rwxr-xr-xlcc/etc/osf.c53
-rwxr-xr-xlcc/etc/solaris.c50
-rwxr-xr-xlcc/etc/win32.c43
-rwxr-xr-xlcc/include/alpha/osf/assert.h14
-rwxr-xr-xlcc/include/alpha/osf/ctype.h25
-rwxr-xr-xlcc/include/alpha/osf/errno.h8
-rwxr-xr-xlcc/include/alpha/osf/float.h37
-rwxr-xr-xlcc/include/alpha/osf/limits.h24
-rwxr-xr-xlcc/include/alpha/osf/locale.h36
-rwxr-xr-xlcc/include/alpha/osf/math.h29
-rwxr-xr-xlcc/include/alpha/osf/setjmp.h10
-rwxr-xr-xlcc/include/alpha/osf/signal.h20
-rwxr-xr-xlcc/include/alpha/osf/stdarg.h28
-rwxr-xr-xlcc/include/alpha/osf/stddef.h22
-rwxr-xr-xlcc/include/alpha/osf/stdio.h113
-rwxr-xr-xlcc/include/alpha/osf/stdlib.h54
-rwxr-xr-xlcc/include/alpha/osf/string.h35
-rwxr-xr-xlcc/include/alpha/osf/time.h50
-rwxr-xr-xlcc/include/mips/irix/assert.h14
-rwxr-xr-xlcc/include/mips/irix/ctype.h40
-rwxr-xr-xlcc/include/mips/irix/errno.h8
-rwxr-xr-xlcc/include/mips/irix/float.h37
-rwxr-xr-xlcc/include/mips/irix/limits.h24
-rwxr-xr-xlcc/include/mips/irix/locale.h36
-rwxr-xr-xlcc/include/mips/irix/math.h29
-rwxr-xr-xlcc/include/mips/irix/setjmp.h10
-rwxr-xr-xlcc/include/mips/irix/signal.h20
-rwxr-xr-xlcc/include/mips/irix/stdarg.h22
-rwxr-xr-xlcc/include/mips/irix/stddef.h22
-rwxr-xr-xlcc/include/mips/irix/stdio.h103
-rwxr-xr-xlcc/include/mips/irix/stdlib.h54
-rwxr-xr-xlcc/include/mips/irix/string.h35
-rwxr-xr-xlcc/include/mips/irix/time.h48
-rwxr-xr-xlcc/include/sparc/solaris/assert.h14
-rwxr-xr-xlcc/include/sparc/solaris/ctype.h46
-rwxr-xr-xlcc/include/sparc/solaris/errno.h8
-rwxr-xr-xlcc/include/sparc/solaris/float.h37
-rwxr-xr-xlcc/include/sparc/solaris/limits.h24
-rwxr-xr-xlcc/include/sparc/solaris/locale.h36
-rwxr-xr-xlcc/include/sparc/solaris/math.h30
-rwxr-xr-xlcc/include/sparc/solaris/setjmp.h10
-rwxr-xr-xlcc/include/sparc/solaris/signal.h20
-rwxr-xr-xlcc/include/sparc/solaris/stdarg.h22
-rwxr-xr-xlcc/include/sparc/solaris/stddef.h22
-rwxr-xr-xlcc/include/sparc/solaris/stdio.h104
-rwxr-xr-xlcc/include/sparc/solaris/stdlib.h54
-rwxr-xr-xlcc/include/sparc/solaris/string.h35
-rwxr-xr-xlcc/include/sparc/solaris/time.h48
-rwxr-xr-xlcc/include/x86/linux/assert.h14
-rwxr-xr-xlcc/include/x86/linux/float.h37
-rwxr-xr-xlcc/include/x86/linux/stdarg.h21
-rwxr-xr-xlcc/lburg/gram.c680
-rwxr-xr-xlcc/lburg/gram.y202
-rwxr-xr-xlcc/lburg/lburg.1179
-rwxr-xr-xlcc/lburg/lburg.c671
-rwxr-xr-xlcc/lburg/lburg.h65
-rwxr-xr-xlcc/lib/assert.c15
-rwxr-xr-xlcc/lib/bbexit.c123
-rwxr-xr-xlcc/lib/yynull.c12
-rwxr-xr-xlcc/makefile310
-rwxr-xr-xlcc/makefile.nt383
-rwxr-xr-xlcc/mips/irix/tst/8q.1bk92
-rwxr-xr-xlcc/mips/irix/tst/8q.2bk2
-rwxr-xr-xlcc/mips/irix/tst/8q.sbk169
-rwxr-xr-xlcc/mips/irix/tst/array.1bk4
-rwxr-xr-xlcc/mips/irix/tst/array.2bk2
-rwxr-xr-xlcc/mips/irix/tst/array.sbk235
-rwxr-xr-xlcc/mips/irix/tst/cf.1bk51
-rwxr-xr-xlcc/mips/irix/tst/cf.2bk0
-rwxr-xr-xlcc/mips/irix/tst/cf.sbk153
-rwxr-xr-xlcc/mips/irix/tst/cq.1bk48
-rwxr-xr-xlcc/mips/irix/tst/cq.2bk25
-rwxr-xr-xlcc/mips/irix/tst/cq.sbk13620
-rwxr-xr-xlcc/mips/irix/tst/cvt.1bk11
-rwxr-xr-xlcc/mips/irix/tst/cvt.2bk2
-rwxr-xr-xlcc/mips/irix/tst/cvt.sbk557
-rwxr-xr-xlcc/mips/irix/tst/fields.1bk5
-rwxr-xr-xlcc/mips/irix/tst/fields.2bk4
-rwxr-xr-xlcc/mips/irix/tst/fields.sbk304
-rwxr-xr-xlcc/mips/irix/tst/front.2bk29
-rwxr-xr-xlcc/mips/irix/tst/front.sbk416
-rwxr-xr-xlcc/mips/irix/tst/incr.2bk9
-rwxr-xr-xlcc/mips/irix/tst/incr.sbk149
-rwxr-xr-xlcc/mips/irix/tst/init.1bk16
-rwxr-xr-xlcc/mips/irix/tst/init.2bk3
-rwxr-xr-xlcc/mips/irix/tst/init.sbk325
-rwxr-xr-xlcc/mips/irix/tst/limits.1bk14
-rwxr-xr-xlcc/mips/irix/tst/limits.2bk0
-rwxr-xr-xlcc/mips/irix/tst/limits.sbk396
-rwxr-xr-xlcc/mips/irix/tst/paranoia.1bk178
-rwxr-xr-xlcc/mips/irix/tst/paranoia.2bk16
-rwxr-xr-xlcc/mips/irix/tst/paranoia.sbk18657
-rwxr-xr-xlcc/mips/irix/tst/sort.1bk20
-rwxr-xr-xlcc/mips/irix/tst/sort.2bk5
-rwxr-xr-xlcc/mips/irix/tst/sort.sbk308
-rwxr-xr-xlcc/mips/irix/tst/spill.2bk6
-rwxr-xr-xlcc/mips/irix/tst/spill.sbk271
-rwxr-xr-xlcc/mips/irix/tst/stdarg.1bk6
-rwxr-xr-xlcc/mips/irix/tst/stdarg.2bk1
-rwxr-xr-xlcc/mips/irix/tst/stdarg.sbk395
-rwxr-xr-xlcc/mips/irix/tst/struct.1bk5
-rwxr-xr-xlcc/mips/irix/tst/struct.2bk2
-rwxr-xr-xlcc/mips/irix/tst/struct.sbk485
-rwxr-xr-xlcc/mips/irix/tst/switch.1bk76
-rwxr-xr-xlcc/mips/irix/tst/switch.2bk5
-rwxr-xr-xlcc/mips/irix/tst/switch.sbk836
-rwxr-xr-xlcc/mips/irix/tst/wf1.1bk74
-rwxr-xr-xlcc/mips/irix/tst/wf1.2bk2
-rwxr-xr-xlcc/mips/irix/tst/wf1.sbk378
-rwxr-xr-xlcc/mips/irix/tst/yacc.1bk10
-rwxr-xr-xlcc/mips/irix/tst/yacc.2bk3
-rwxr-xr-xlcc/mips/irix/tst/yacc.sbk2236
-rwxr-xr-xlcc/msdev/rcc.dsp240
-rwxr-xr-xlcc/msdev/rcc.dsw29
-rwxr-xr-xlcc/packing.lst432
-rwxr-xr-xlcc/sparc/solaris/tst/8q.1bk92
-rwxr-xr-xlcc/sparc/solaris/tst/8q.2bk2
-rwxr-xr-xlcc/sparc/solaris/tst/8q.sbk144
-rwxr-xr-xlcc/sparc/solaris/tst/array.1bk4
-rwxr-xr-xlcc/sparc/solaris/tst/array.2bk2
-rwxr-xr-xlcc/sparc/solaris/tst/array.sbk172
-rwxr-xr-xlcc/sparc/solaris/tst/cf.1bk51
-rwxr-xr-xlcc/sparc/solaris/tst/cf.2bk0
-rwxr-xr-xlcc/sparc/solaris/tst/cf.sbk143
-rwxr-xr-xlcc/sparc/solaris/tst/cq.1bk48
-rwxr-xr-xlcc/sparc/solaris/tst/cq.2bk25
-rwxr-xr-xlcc/sparc/solaris/tst/cq.sbk13322
-rwxr-xr-xlcc/sparc/solaris/tst/cvt.1bk11
-rwxr-xr-xlcc/sparc/solaris/tst/cvt.2bk2
-rwxr-xr-xlcc/sparc/solaris/tst/cvt.sbk715
-rwxr-xr-xlcc/sparc/solaris/tst/fields.1bk5
-rwxr-xr-xlcc/sparc/solaris/tst/fields.2bk4
-rwxr-xr-xlcc/sparc/solaris/tst/fields.sbk309
-rwxr-xr-xlcc/sparc/solaris/tst/front.2bk29
-rwxr-xr-xlcc/sparc/solaris/tst/front.sbk260
-rwxr-xr-xlcc/sparc/solaris/tst/incr.1bk0
-rwxr-xr-xlcc/sparc/solaris/tst/incr.2bk9
-rwxr-xr-xlcc/sparc/solaris/tst/incr.sbk107
-rwxr-xr-xlcc/sparc/solaris/tst/init.1bk16
-rwxr-xr-xlcc/sparc/solaris/tst/init.2bk3
-rwxr-xr-xlcc/sparc/solaris/tst/init.sbk277
-rwxr-xr-xlcc/sparc/solaris/tst/limits.1bk14
-rwxr-xr-xlcc/sparc/solaris/tst/limits.2bk0
-rwxr-xr-xlcc/sparc/solaris/tst/limits.sbk384
-rwxr-xr-xlcc/sparc/solaris/tst/paranoia.1bk178
-rwxr-xr-xlcc/sparc/solaris/tst/paranoia.2bk16
-rwxr-xr-xlcc/sparc/solaris/tst/paranoia.sbk21068
-rwxr-xr-xlcc/sparc/solaris/tst/sort.1bk20
-rwxr-xr-xlcc/sparc/solaris/tst/sort.2bk5
-rwxr-xr-xlcc/sparc/solaris/tst/sort.sbk202
-rwxr-xr-xlcc/sparc/solaris/tst/spill.1bk0
-rwxr-xr-xlcc/sparc/solaris/tst/spill.2bk6
-rwxr-xr-xlcc/sparc/solaris/tst/spill.sbk207
-rwxr-xr-xlcc/sparc/solaris/tst/stdarg.1bk6
-rwxr-xr-xlcc/sparc/solaris/tst/stdarg.2bk1
-rwxr-xr-xlcc/sparc/solaris/tst/stdarg.sbk376
-rwxr-xr-xlcc/sparc/solaris/tst/struct.1bk5
-rwxr-xr-xlcc/sparc/solaris/tst/struct.2bk2
-rwxr-xr-xlcc/sparc/solaris/tst/struct.sbk377
-rwxr-xr-xlcc/sparc/solaris/tst/switch.1bk76
-rwxr-xr-xlcc/sparc/solaris/tst/switch.2bk5
-rwxr-xr-xlcc/sparc/solaris/tst/switch.sbk713
-rwxr-xr-xlcc/sparc/solaris/tst/wf1.1bk74
-rwxr-xr-xlcc/sparc/solaris/tst/wf1.2bk2
-rwxr-xr-xlcc/sparc/solaris/tst/wf1.sbk311
-rwxr-xr-xlcc/sparc/solaris/tst/yacc.1bk10
-rwxr-xr-xlcc/sparc/solaris/tst/yacc.2bk3
-rwxr-xr-xlcc/sparc/solaris/tst/yacc.sbk2247
-rwxr-xr-xlcc/src/2html.c555
-rwxr-xr-xlcc/src/alloc.c94
-rwxr-xr-xlcc/src/alpha.md1192
-rwxr-xr-xlcc/src/asdl.c399
-rwxr-xr-xlcc/src/bind.c23
-rwxr-xr-xlcc/src/bytecode.c365
-rwxr-xr-xlcc/src/c.h723
-rwxr-xr-xlcc/src/config.h102
-rwxr-xr-xlcc/src/dag.c735
-rwxr-xr-xlcc/src/dagcheck.md210
-rwxr-xr-xlcc/src/decl.c1160
-rwxr-xr-xlcc/src/enode.c543
-rwxr-xr-xlcc/src/error.c137
-rwxr-xr-xlcc/src/event.c28
-rwxr-xr-xlcc/src/expr.c709
-rwxr-xr-xlcc/src/gen.c830
-rwxr-xr-xlcc/src/init.c318
-rwxr-xr-xlcc/src/inits.c8
-rwxr-xr-xlcc/src/input.c134
-rwxr-xr-xlcc/src/lex.c922
-rwxr-xr-xlcc/src/list.c56
-rwxr-xr-xlcc/src/main.c225
-rwxr-xr-xlcc/src/mips.md1120
-rwxr-xr-xlcc/src/null.c74
-rwxr-xr-xlcc/src/output.c134
-rwxr-xr-xlcc/src/pass2.c665
-rwxr-xr-xlcc/src/prof.c227
-rwxr-xr-xlcc/src/profio.c276
-rwxr-xr-xlcc/src/rcc.asdl70
-rwxr-xr-xlcc/src/run.sh51
-rwxr-xr-xlcc/src/simp.c587
-rwxr-xr-xlcc/src/sparc.md1163
-rwxr-xr-xlcc/src/stab.c330
-rwxr-xr-xlcc/src/stab.h113
-rwxr-xr-xlcc/src/stmt.c697
-rwxr-xr-xlcc/src/string.c122
-rwxr-xr-xlcc/src/sym.c315
-rwxr-xr-xlcc/src/symbolic.c494
-rwxr-xr-xlcc/src/token.h133
-rwxr-xr-xlcc/src/trace.c180
-rwxr-xr-xlcc/src/tree.c223
-rwxr-xr-xlcc/src/types.c748
-rwxr-xr-xlcc/src/x86.md998
-rwxr-xr-xlcc/src/x86linux.md1081
-rwxr-xr-xlcc/tst/8q.00
-rwxr-xr-xlcc/tst/8q.c39
-rwxr-xr-xlcc/tst/array.00
-rwxr-xr-xlcc/tst/array.c48
-rwxr-xr-xlcc/tst/cf.032
-rwxr-xr-xlcc/tst/cf.c32
-rwxr-xr-xlcc/tst/cq.00
-rwxr-xr-xlcc/tst/cq.c5316
-rwxr-xr-xlcc/tst/cvt.00
-rwxr-xr-xlcc/tst/cvt.c35
-rwxr-xr-xlcc/tst/fields.00
-rwxr-xr-xlcc/tst/fields.c34
-rwxr-xr-xlcc/tst/front.00
-rwxr-xr-xlcc/tst/front.c120
-rwxr-xr-xlcc/tst/incr.00
-rwxr-xr-xlcc/tst/incr.c39
-rwxr-xr-xlcc/tst/init.00
-rwxr-xr-xlcc/tst/init.c59
-rwxr-xr-xlcc/tst/limits.00
-rwxr-xr-xlcc/tst/limits.c19
-rwxr-xr-xlcc/tst/paranoia.00
-rwxr-xr-xlcc/tst/paranoia.c2203
-rwxr-xr-xlcc/tst/sort.00
-rwxr-xr-xlcc/tst/sort.c65
-rwxr-xr-xlcc/tst/spill.00
-rwxr-xr-xlcc/tst/spill.c17
-rwxr-xr-xlcc/tst/stdarg.00
-rwxr-xr-xlcc/tst/stdarg.c51
-rwxr-xr-xlcc/tst/struct.00
-rwxr-xr-xlcc/tst/struct.c69
-rwxr-xr-xlcc/tst/switch.00
-rwxr-xr-xlcc/tst/switch.c137
-rwxr-xr-xlcc/tst/wf1.0115
-rwxr-xr-xlcc/tst/wf1.c101
-rwxr-xr-xlcc/tst/yacc.01
-rwxr-xr-xlcc/tst/yacc.c591
-rwxr-xr-xlcc/x86/linux/tst/8q.1bk92
-rwxr-xr-xlcc/x86/linux/tst/8q.2bk2
-rwxr-xr-xlcc/x86/linux/tst/8q.sbk180
-rwxr-xr-xlcc/x86/linux/tst/array.1bk4
-rwxr-xr-xlcc/x86/linux/tst/array.2bk2
-rwxr-xr-xlcc/x86/linux/tst/array.sbk235
-rwxr-xr-xlcc/x86/linux/tst/cf.1bk51
-rwxr-xr-xlcc/x86/linux/tst/cf.2bk0
-rwxr-xr-xlcc/x86/linux/tst/cf.sbk161
-rwxr-xr-xlcc/x86/linux/tst/cq.1bk48
-rwxr-xr-xlcc/x86/linux/tst/cq.2bk25
-rwxr-xr-xlcc/x86/linux/tst/cq.sbk15756
-rwxr-xr-xlcc/x86/linux/tst/cvt.1bk11
-rwxr-xr-xlcc/x86/linux/tst/cvt.2bk2
-rwxr-xr-xlcc/x86/linux/tst/cvt.sbk792
-rwxr-xr-xlcc/x86/linux/tst/fields.1bk5
-rwxr-xr-xlcc/x86/linux/tst/fields.2bk4
-rwxr-xr-xlcc/x86/linux/tst/fields.sbk321
-rwxr-xr-xlcc/x86/linux/tst/front.2bk29
-rwxr-xr-xlcc/x86/linux/tst/front.sbk530
-rwxr-xr-xlcc/x86/linux/tst/incr.1bk0
-rwxr-xr-xlcc/x86/linux/tst/incr.2bk9
-rwxr-xr-xlcc/x86/linux/tst/incr.sbk181
-rwxr-xr-xlcc/x86/linux/tst/init.1bk16
-rwxr-xr-xlcc/x86/linux/tst/init.2bk3
-rwxr-xr-xlcc/x86/linux/tst/init.sbk336
-rwxr-xr-xlcc/x86/linux/tst/limits.1bk14
-rwxr-xr-xlcc/x86/linux/tst/limits.2bk0
-rwxr-xr-xlcc/x86/linux/tst/limits.sbk396
-rwxr-xr-xlcc/x86/linux/tst/paranoia.1bk183
-rwxr-xr-xlcc/x86/linux/tst/paranoia.2bk16
-rwxr-xr-xlcc/x86/linux/tst/paranoia.sbk20248
-rwxr-xr-xlcc/x86/linux/tst/sort.1bk20
-rwxr-xr-xlcc/x86/linux/tst/sort.2bk5
-rwxr-xr-xlcc/x86/linux/tst/sort.sbk330
-rwxr-xr-xlcc/x86/linux/tst/spill.1bk0
-rwxr-xr-xlcc/x86/linux/tst/spill.2bk6
-rwxr-xr-xlcc/x86/linux/tst/spill.sbk282
-rwxr-xr-xlcc/x86/linux/tst/stdarg.1bk6
-rwxr-xr-xlcc/x86/linux/tst/stdarg.2bk1
-rwxr-xr-xlcc/x86/linux/tst/stdarg.sbk395
-rwxr-xr-xlcc/x86/linux/tst/struct.1bk5
-rwxr-xr-xlcc/x86/linux/tst/struct.2bk2
-rwxr-xr-xlcc/x86/linux/tst/struct.sbk477
-rwxr-xr-xlcc/x86/linux/tst/switch.1bk76
-rwxr-xr-xlcc/x86/linux/tst/switch.2bk5
-rwxr-xr-xlcc/x86/linux/tst/switch.sbk899
-rwxr-xr-xlcc/x86/linux/tst/wf1.1bk74
-rwxr-xr-xlcc/x86/linux/tst/wf1.2bk2
-rwxr-xr-xlcc/x86/linux/tst/wf1.sbk437
-rwxr-xr-xlcc/x86/linux/tst/yacc.1bk10
-rwxr-xr-xlcc/x86/linux/tst/yacc.2bk3
-rwxr-xr-xlcc/x86/linux/tst/yacc.sbk2526
-rwxr-xr-xlcc/x86/win32/tst/8q.1bk92
-rwxr-xr-xlcc/x86/win32/tst/8q.2bk2
-rwxr-xr-xlcc/x86/win32/tst/8q.sbk176
-rwxr-xr-xlcc/x86/win32/tst/array.1bk4
-rwxr-xr-xlcc/x86/win32/tst/array.2bk2
-rwxr-xr-xlcc/x86/win32/tst/array.sbk240
-rwxr-xr-xlcc/x86/win32/tst/cf.1bk51
-rwxr-xr-xlcc/x86/win32/tst/cf.2bk0
-rwxr-xr-xlcc/x86/win32/tst/cf.sbk185
-rwxr-xr-xlcc/x86/win32/tst/cq.1bk48
-rwxr-xr-xlcc/x86/win32/tst/cq.2bk25
-rwxr-xr-xlcc/x86/win32/tst/cq.sbk16642
-rwxr-xr-xlcc/x86/win32/tst/cvt.1bk11
-rwxr-xr-xlcc/x86/win32/tst/cvt.2bk2
-rwxr-xr-xlcc/x86/win32/tst/cvt.sbk742
-rwxr-xr-xlcc/x86/win32/tst/fields.1bk5
-rwxr-xr-xlcc/x86/win32/tst/fields.2bk4
-rwxr-xr-xlcc/x86/win32/tst/fields.sbk323
-rwxr-xr-xlcc/x86/win32/tst/front.2bk29
-rwxr-xr-xlcc/x86/win32/tst/front.sbk436
-rwxr-xr-xlcc/x86/win32/tst/incr.1bk0
-rwxr-xr-xlcc/x86/win32/tst/incr.2bk9
-rwxr-xr-xlcc/x86/win32/tst/incr.sbk166
-rwxr-xr-xlcc/x86/win32/tst/init.1bk16
-rwxr-xr-xlcc/x86/win32/tst/init.2bk3
-rwxr-xr-xlcc/x86/win32/tst/init.sbk336
-rwxr-xr-xlcc/x86/win32/tst/limits.1bk14
-rwxr-xr-xlcc/x86/win32/tst/limits.2bk0
-rwxr-xr-xlcc/x86/win32/tst/limits.sbk414
-rwxr-xr-xlcc/x86/win32/tst/paranoia.1bk179
-rwxr-xr-xlcc/x86/win32/tst/paranoia.2bk16
-rwxr-xr-xlcc/x86/win32/tst/paranoia.sbk20480
-rwxr-xr-xlcc/x86/win32/tst/sort.1bk20
-rwxr-xr-xlcc/x86/win32/tst/sort.2bk5
-rwxr-xr-xlcc/x86/win32/tst/sort.sbk324
-rwxr-xr-xlcc/x86/win32/tst/spill.1bk0
-rwxr-xr-xlcc/x86/win32/tst/spill.2bk6
-rwxr-xr-xlcc/x86/win32/tst/spill.sbk259
-rwxr-xr-xlcc/x86/win32/tst/stdarg.1bk6
-rwxr-xr-xlcc/x86/win32/tst/stdarg.2bk1
-rwxr-xr-xlcc/x86/win32/tst/stdarg.sbk415
-rwxr-xr-xlcc/x86/win32/tst/struct.1bk5
-rwxr-xr-xlcc/x86/win32/tst/struct.2bk2
-rwxr-xr-xlcc/x86/win32/tst/struct.sbk453
-rwxr-xr-xlcc/x86/win32/tst/switch.1bk76
-rwxr-xr-xlcc/x86/win32/tst/switch.2bk5
-rwxr-xr-xlcc/x86/win32/tst/switch.sbk960
-rwxr-xr-xlcc/x86/win32/tst/wf1.1bk74
-rwxr-xr-xlcc/x86/win32/tst/wf1.2bk2
-rwxr-xr-xlcc/x86/win32/tst/wf1.sbk451
-rwxr-xr-xlcc/x86/win32/tst/yacc.1bk10
-rwxr-xr-xlcc/x86/win32/tst/yacc.2bk3
-rwxr-xr-xlcc/x86/win32/tst/yacc.sbk2489
-rwxr-xr-xlibs/cmdlib.h97
-rwxr-xr-xlibs/cmdlib/cmdlib.cpp550
-rwxr-xr-xlibs/cmdlib/cmdlib.vcproj156
-rwxr-xr-xlibs/jpeg6/README385
-rwxr-xr-xlibs/jpeg6/jchuff.h34
-rwxr-xr-xlibs/jpeg6/jcomapi.cpp94
-rwxr-xr-xlibs/jpeg6/jconfig.h41
-rwxr-xr-xlibs/jpeg6/jdapimin.cpp400
-rwxr-xr-xlibs/jpeg6/jdapistd.cpp275
-rwxr-xr-xlibs/jpeg6/jdatasrc.cpp204
-rwxr-xr-xlibs/jpeg6/jdcoefct.cpp725
-rwxr-xr-xlibs/jpeg6/jdcolor.cpp367
-rwxr-xr-xlibs/jpeg6/jdct.h176
-rwxr-xr-xlibs/jpeg6/jddctmgr.cpp270
-rwxr-xr-xlibs/jpeg6/jdhuff.cpp574
-rwxr-xr-xlibs/jpeg6/jdhuff.h202
-rwxr-xr-xlibs/jpeg6/jdinput.cpp381
-rwxr-xr-xlibs/jpeg6/jdmainct.cpp512
-rwxr-xr-xlibs/jpeg6/jdmarker.cpp1052
-rwxr-xr-xlibs/jpeg6/jdmaster.cpp557
-rwxr-xr-xlibs/jpeg6/jdpostct.cpp290
-rwxr-xr-xlibs/jpeg6/jdsample.cpp478
-rwxr-xr-xlibs/jpeg6/jdtrans.cpp122
-rwxr-xr-xlibs/jpeg6/jerror.cpp231
-rwxr-xr-xlibs/jpeg6/jerror.h273
-rwxr-xr-xlibs/jpeg6/jfdctflt.cpp168
-rwxr-xr-xlibs/jpeg6/jidctflt.cpp241
-rwxr-xr-xlibs/jpeg6/jinclude.h91
-rwxr-xr-xlibs/jpeg6/jmemmgr.cpp1115
-rwxr-xr-xlibs/jpeg6/jmemnobs.cpp103
-rwxr-xr-xlibs/jpeg6/jmemsys.h182
-rwxr-xr-xlibs/jpeg6/jmorecfg.h346
-rwxr-xr-xlibs/jpeg6/jpeg6.vcproj603
-rwxr-xr-xlibs/jpeg6/jpegint.h388
-rwxr-xr-xlibs/jpeg6/jpgload.cpp142
-rwxr-xr-xlibs/jpeg6/jutils.cpp175
-rwxr-xr-xlibs/jpeg6/jversion.h14
-rwxr-xr-xlibs/jpeglib.h1087
-rwxr-xr-xlibs/pak/pak.vcproj173
-rwxr-xr-xlibs/pak/pakstuff.cpp1209
-rwxr-xr-xlibs/pak/unzip.cpp4546
-rwxr-xr-xlibs/pak/unzip.h300
-rwxr-xr-xlibs/pakstuff.h141
-rwxr-xr-xlibs/str.h214
-rwxr-xr-xq3asm/Makefile13
-rwxr-xr-xq3asm/README.Id10
-rwxr-xr-xq3asm/cmdlib.c1206
-rwxr-xr-xq3asm/cmdlib.h160
-rwxr-xr-xq3asm/lib.txt31
-rwxr-xr-xq3asm/mathlib.h94
-rwxr-xr-xq3asm/notes.txt16
-rwxr-xr-xq3asm/ops.txt132
-rwxr-xr-xq3asm/opstrings.h175
-rwxr-xr-xq3asm/q3asm.c1047
-rwxr-xr-xq3asm/q3asm.sln28
-rwxr-xr-xq3asm/q3asm.vcproj195
-rwxr-xr-xq3asm/qfiles.h485
-rwxr-xr-xq3map/brush.c861
-rwxr-xr-xq3map/brush_primit.c52
-rwxr-xr-xq3map/bsp.c605
-rwxr-xr-xq3map/facebsp.c379
-rwxr-xr-xq3map/fog.c554
-rwxr-xr-xq3map/gldraw.c232
-rwxr-xr-xq3map/glfile.c148
-rwxr-xr-xq3map/leakfile.c100
-rwxr-xr-xq3map/light.c2149
-rwxr-xr-xq3map/light.h151
-rwxr-xr-xq3map/light_trace.c944
-rwxr-xr-xq3map/lightmaps.c395
-rwxr-xr-xq3map/lightv.c5748
-rwxr-xr-xq3map/makefile148
-rwxr-xr-xq3map/map.c1251
-rwxr-xr-xq3map/mesh.c682
-rwxr-xr-xq3map/mesh.h48
-rwxr-xr-xq3map/misc_model.c472
-rwxr-xr-xq3map/nodraw.c47
-rwxr-xr-xq3map/patch.c286
-rwxr-xr-xq3map/portals.c843
-rwxr-xr-xq3map/prtfile.c272
-rwxr-xr-xq3map/q3map.sln56
-rwxr-xr-xq3map/q3map.vcproj1606
-rwxr-xr-xq3map/qbsp.h455
-rwxr-xr-xq3map/shaders.c608
-rwxr-xr-xq3map/shaders.h71
-rwxr-xr-xq3map/soundv.c5742
-rwxr-xr-xq3map/surface.c1158
-rwxr-xr-xq3map/terrain.c1255
-rwxr-xr-xq3map/tjunction.c551
-rwxr-xr-xq3map/tree.c146
-rwxr-xr-xq3map/vis.c1197
-rwxr-xr-xq3map/vis.h162
-rwxr-xr-xq3map/visflow.c1657
-rwxr-xr-xq3map/writebsp.c418
-rwxr-xr-xq3radiant/BMP.H101
-rwxr-xr-xq3radiant/BRUSH.H124
-rwxr-xr-xq3radiant/BSInput.cpp115
-rwxr-xr-xq3radiant/BSInput.h76
-rwxr-xr-xq3radiant/BSPFILE.H379
-rwxr-xr-xq3radiant/Bmp.cpp417
-rwxr-xr-xq3radiant/Brush.cpp4595
-rwxr-xr-xq3radiant/BrushScript.cpp672
-rwxr-xr-xq3radiant/CAMERA.H51
-rwxr-xr-xq3radiant/CSG.CPP686
-rwxr-xr-xq3radiant/CamWnd.cpp1165
-rwxr-xr-xq3radiant/CamWnd.h120
-rwxr-xr-xq3radiant/CapDialog.cpp64
-rwxr-xr-xq3radiant/CapDialog.h69
-rwxr-xr-xq3radiant/CharBuffer.h109
-rwxr-xr-xq3radiant/ChildFrm.cpp86
-rwxr-xr-xq3radiant/ChildFrm.h73
-rwxr-xr-xq3radiant/CommandsDlg.cpp109
-rwxr-xr-xq3radiant/CommandsDlg.h67
-rwxr-xr-xq3radiant/DRAG.CPP828
-rwxr-xr-xq3radiant/DialogInfo.cpp94
-rwxr-xr-xq3radiant/DialogInfo.h69
-rwxr-xr-xq3radiant/DialogTextures.cpp89
-rwxr-xr-xq3radiant/DialogTextures.h69
-rwxr-xr-xq3radiant/DialogThick.cpp66
-rwxr-xr-xq3radiant/DialogThick.h68
-rwxr-xr-xq3radiant/DlgEvent.cpp65
-rwxr-xr-xq3radiant/DlgEvent.h69
-rwxr-xr-xq3radiant/ECLASS.CPP932
-rwxr-xr-xq3radiant/ENTITY.CPP933
-rwxr-xr-xq3radiant/ENTITY.H76
-rwxr-xr-xq3radiant/ENTITYW.H68
-rwxr-xr-xq3radiant/EPAIRS.H1402
-rwxr-xr-xq3radiant/EditWnd.cpp61
-rwxr-xr-xq3radiant/EditWnd.h71
-rwxr-xr-xq3radiant/EntityListDlg.cpp152
-rwxr-xr-xq3radiant/EntityListDlg.h72
-rwxr-xr-xq3radiant/EpairsWrapper.h63
-rwxr-xr-xq3radiant/FNMATCH.CPP87
-rwxr-xr-xq3radiant/FNMATCH.H27
-rwxr-xr-xq3radiant/FindTextureDlg.cpp175
-rwxr-xr-xq3radiant/FindTextureDlg.h83
-rwxr-xr-xq3radiant/GLINGR.H97
-rwxr-xr-xq3radiant/GLInterface.cpp93
-rwxr-xr-xq3radiant/GLW_WIN.H49
-rwxr-xr-xq3radiant/GroupBar.cpp84
-rwxr-xr-xq3radiant/GroupBar.h69
-rwxr-xr-xq3radiant/GroupDlg.cpp655
-rwxr-xr-xq3radiant/GroupDlg.h90
-rwxr-xr-xq3radiant/IBSPFrontend.h101
-rwxr-xr-xq3radiant/ICON1.ICObin0 -> 766 bytes
-rwxr-xr-xq3radiant/IEpairs.cpp185
-rwxr-xr-xq3radiant/IEpairs.h83
-rwxr-xr-xq3radiant/IMessaging.h119
-rwxr-xr-xq3radiant/IPluginEntities.h105
-rwxr-xr-xq3radiant/ISelectedFace.h113
-rwxr-xr-xq3radiant/IShaders.cpp86
-rwxr-xr-xq3radiant/IShaders.h79
-rwxr-xr-xq3radiant/LBMLIB.CPP1329
-rwxr-xr-xq3radiant/LBMLIB.H40
-rwxr-xr-xq3radiant/LstToolBar.cpp59
-rwxr-xr-xq3radiant/LstToolBar.h69
-rwxr-xr-xq3radiant/MAP.CPP1062
-rwxr-xr-xq3radiant/MAP.H59
-rwxr-xr-xq3radiant/MATHLIB.CPP311
-rwxr-xr-xq3radiant/MATHLIB.H86
-rwxr-xr-xq3radiant/MRU.CPP671
-rwxr-xr-xq3radiant/MRU.H100
-rwxr-xr-xq3radiant/MainFrm.cpp5224
-rwxr-xr-xq3radiant/MainFrm.h504
-rwxr-xr-xq3radiant/MapInfo.cpp114
-rwxr-xr-xq3radiant/MapInfo.h70
-rwxr-xr-xq3radiant/Messaging.cpp137
-rwxr-xr-xq3radiant/Messaging.h46
-rwxr-xr-xq3radiant/NameDlg.cpp79
-rwxr-xr-xq3radiant/NameDlg.h69
-rwxr-xr-xq3radiant/NewProjDlg.cpp64
-rwxr-xr-xq3radiant/NewProjDlg.h67
-rwxr-xr-xq3radiant/PARSE.CPP148
-rwxr-xr-xq3radiant/PARSE.H34
-rwxr-xr-xq3radiant/PMESH.CPP5136
-rwxr-xr-xq3radiant/PMESH.H21
-rwxr-xr-xq3radiant/POINTS.CPP156
-rwxr-xr-xq3radiant/PatchDensityDlg.cpp89
-rwxr-xr-xq3radiant/PatchDensityDlg.h69
-rwxr-xr-xq3radiant/PatchDialog.cpp354
-rwxr-xr-xq3radiant/PatchDialog.h102
-rwxr-xr-xq3radiant/PlugIn.cpp297
-rwxr-xr-xq3radiant/PlugIn.h82
-rwxr-xr-xq3radiant/PlugInManager.cpp1665
-rwxr-xr-xq3radiant/PlugInManager.h100
-rwxr-xr-xq3radiant/PluginEntities.cpp101
-rwxr-xr-xq3radiant/PrefsDlg.cpp578
-rwxr-xr-xq3radiant/PrefsDlg.h161
-rwxr-xr-xq3radiant/QE3.CPP751
-rwxr-xr-xq3radiant/QE3.H669
-rwxr-xr-xq3radiant/QEDEFS.H164
-rwxr-xr-xq3radiant/QERTYPES.H454
-rwxr-xr-xq3radiant/QFILES.H481
-rwxr-xr-xq3radiant/QGL.H456
-rwxr-xr-xq3radiant/QGL_WIN.C1230
-rwxr-xr-xq3radiant/QGL_WIN.CPP1520
-rwxr-xr-xq3radiant/RADBSP.CPP77
-rwxr-xr-xq3radiant/RADEditView.cpp84
-rwxr-xr-xq3radiant/RADEditView.h75
-rwxr-xr-xq3radiant/RADEditWnd.cpp75
-rwxr-xr-xq3radiant/RADEditWnd.h73
-rwxr-xr-xq3radiant/RADKEYS.INI67
-rwxr-xr-xq3radiant/Radiant.clw1957
-rwxr-xr-xq3radiant/Radiant.cpp261
-rwxr-xr-xq3radiant/Radiant.h71
-rwxr-xr-xq3radiant/Radiant.rc2838
-rwxr-xr-xq3radiant/Radiant.sln95
-rwxr-xr-xq3radiant/Radiant.vcproj3381
-rwxr-xr-xq3radiant/RadiantDoc.cpp105
-rwxr-xr-xq3radiant/RadiantDoc.h78
-rwxr-xr-xq3radiant/RadiantView.cpp126
-rwxr-xr-xq3radiant/RadiantView.h87
-rwxr-xr-xq3radiant/RotateDlg.cpp130
-rwxr-xr-xq3radiant/RotateDlg.h78
-rwxr-xr-xq3radiant/SELECT.CPP1800
-rwxr-xr-xq3radiant/SELECT.H91
-rwxr-xr-xq3radiant/ScaleDialog.cpp68
-rwxr-xr-xq3radiant/ScaleDialog.h69
-rwxr-xr-xq3radiant/ScriptDlg.cpp103
-rwxr-xr-xq3radiant/ScriptDlg.h70
-rwxr-xr-xq3radiant/SelectedFace.cpp136
-rwxr-xr-xq3radiant/ShaderEdit.cpp66
-rwxr-xr-xq3radiant/ShaderEdit.h70
-rwxr-xr-xq3radiant/ShaderInfo.cpp69
-rwxr-xr-xq3radiant/ShaderInfo.h55
-rwxr-xr-xq3radiant/StdAfx.cpp27
-rwxr-xr-xq3radiant/StdAfx.h154
-rwxr-xr-xq3radiant/SurfaceDlg.cpp983
-rwxr-xr-xq3radiant/SurfaceDlg.h107
-rwxr-xr-xq3radiant/SurfacePlugin.cpp82
-rwxr-xr-xq3radiant/TexEdit.cpp85
-rwxr-xr-xq3radiant/TexEdit.h76
-rwxr-xr-xq3radiant/TexWnd.cpp3186
-rwxr-xr-xq3radiant/TexWnd.h88
-rwxr-xr-xq3radiant/TextureBar.cpp208
-rwxr-xr-xq3radiant/TextureBar.h85
-rwxr-xr-xq3radiant/TextureLayout.cpp80
-rwxr-xr-xq3radiant/TextureLayout.h69
-rwxr-xr-xq3radiant/TextureLoad.cpp80
-rwxr-xr-xq3radiant/TextureLoad.h68
-rwxr-xr-xq3radiant/Textures.h96
-rwxr-xr-xq3radiant/ToolWnd.cpp55
-rwxr-xr-xq3radiant/ToolWnd.h68
-rwxr-xr-xq3radiant/Undo.cpp884
-rwxr-xr-xq3radiant/Undo.h64
-rwxr-xr-xq3radiant/VERTSEL.CPP372
-rwxr-xr-xq3radiant/VIEW.H53
-rwxr-xr-xq3radiant/WIN_CAM.CPP274
-rwxr-xr-xq3radiant/WIN_DLG.CPP616
-rwxr-xr-xq3radiant/WIN_QE3.CPP753
-rwxr-xr-xq3radiant/WIN_QE3.RC2693
-rwxr-xr-xq3radiant/WIN_XY.CPP310
-rwxr-xr-xq3radiant/WIN_Z.CPP192
-rwxr-xr-xq3radiant/WaveOpen.cpp98
-rwxr-xr-xq3radiant/WaveOpen.h58
-rwxr-xr-xq3radiant/Win_ent.cpp1411
-rwxr-xr-xq3radiant/Win_main.cpp1085
-rwxr-xr-xq3radiant/Winding.cpp817
-rwxr-xr-xq3radiant/Winding.h70
-rwxr-xr-xq3radiant/XY.H39
-rwxr-xr-xq3radiant/XYWnd.cpp3629
-rwxr-xr-xq3radiant/XYWnd.h219
-rwxr-xr-xq3radiant/Z.CPP431
-rwxr-xr-xq3radiant/Z.H42
-rwxr-xr-xq3radiant/ZView.cpp163
-rwxr-xr-xq3radiant/ZView.h83
-rwxr-xr-xq3radiant/ZWnd.cpp264
-rwxr-xr-xq3radiant/ZWnd.h90
-rwxr-xr-xq3radiant/brush_primit.cpp461
-rwxr-xr-xq3radiant/cameratargetdlg.cpp71
-rwxr-xr-xq3radiant/cameratargetdlg.h68
-rwxr-xr-xq3radiant/cbrushstub.cpp76
-rwxr-xr-xq3radiant/dlgcamera.cpp395
-rwxr-xr-xq3radiant/dlgcamera.h98
-rwxr-xr-xq3radiant/igl.h261
-rwxr-xr-xq3radiant/iscriplib.h87
-rwxr-xr-xq3radiant/isurfaceplugin.h216
-rwxr-xr-xq3radiant/qerplugin.h566
-rwxr-xr-xq3radiant/res/BEVEL.BMPbin0 -> 486 bytes
-rwxr-xr-xq3radiant/res/BITMAP2.BMPbin0 -> 614 bytes
-rwxr-xr-xq3radiant/res/BMP00001.BMPbin0 -> 614 bytes
-rwxr-xr-xq3radiant/res/BMP00002.BMPbin0 -> 4198 bytes
-rwxr-xr-xq3radiant/res/BMP0002.BMPbin0 -> 4078 bytes
-rwxr-xr-xq3radiant/res/DEFTEX.WALbin0 -> 5540 bytes
-rwxr-xr-xq3radiant/res/ENDCAP.BMPbin0 -> 486 bytes
-rwxr-xr-xq3radiant/res/IBEVEL.BMPbin0 -> 486 bytes
-rwxr-xr-xq3radiant/res/IENDCAP.BMPbin0 -> 486 bytes
-rwxr-xr-xq3radiant/res/Q.BMPbin0 -> 47936 bytes
-rwxr-xr-xq3radiant/res/RADIANT3.GIFbin0 -> 19737 bytes
-rwxr-xr-xq3radiant/res/Radiant.icobin0 -> 1078 bytes
-rwxr-xr-xq3radiant/res/Radiant.rc213
-rwxr-xr-xq3radiant/res/RadiantDoc.icobin0 -> 1078 bytes
-rwxr-xr-xq3radiant/res/TOOLBAR1.BMPbin0 -> 2878 bytes
-rwxr-xr-xq3radiant/res/TOOLBAR2.BMPbin0 -> 478 bytes
-rwxr-xr-xq3radiant/res/Toolbar.bmpbin0 -> 718 bytes
-rwxr-xr-xq3radiant/res/VIEWDEFA.BMPbin0 -> 614 bytes
-rwxr-xr-xq3radiant/res/VIEWOPPO.BMPbin0 -> 614 bytes
-rwxr-xr-xq3radiant/res/bmp00003.bmpbin0 -> 1014 bytes
-rwxr-xr-xq3radiant/res/icon2.icobin0 -> 766 bytes
-rwxr-xr-xq3radiant/res/logo_sm3dfx.bmpbin0 -> 4918 bytes
-rwxr-xr-xq3radiant/res/shaderbar.bmpbin0 -> 1198 bytes
-rwxr-xr-xq3radiant/res/shaderdoc.icobin0 -> 1078 bytes
-rwxr-xr-xq3radiant/res/shaderframe.icobin0 -> 1078 bytes
-rwxr-xr-xq3radiant/resource.h840
-rwxr-xr-xq3radiant/splines/Splines.vcproj296
-rwxr-xr-xq3radiant/splines/math_angles.cpp150
-rwxr-xr-xq3radiant/splines/math_angles.h195
-rwxr-xr-xq3radiant/splines/math_matrix.cpp134
-rwxr-xr-xq3radiant/splines/math_matrix.h223
-rwxr-xr-xq3radiant/splines/math_quaternion.cpp78
-rwxr-xr-xq3radiant/splines/math_quaternion.h190
-rwxr-xr-xq3radiant/splines/math_vector.cpp144
-rwxr-xr-xq3radiant/splines/math_vector.h572
-rwxr-xr-xq3radiant/splines/q_parse.cpp535
-rwxr-xr-xq3radiant/splines/q_shared.cpp976
-rwxr-xr-xq3radiant/splines/q_shared.h798
-rwxr-xr-xq3radiant/splines/splines.cpp1244
-rwxr-xr-xq3radiant/splines/splines.h1080
-rwxr-xr-xq3radiant/splines/util_list.h346
-rwxr-xr-xq3radiant/splines/util_str.cpp618
-rwxr-xr-xq3radiant/splines/util_str.h817
-rwxr-xr-xq3radiant/terrain.cpp1735
-rwxr-xr-xq3radiant/terrain.h75
-rwxr-xr-xui/hud.txt7
-rwxr-xr-xui/hud2.txt7
-rwxr-xr-xui/ingame.txt16
-rwxr-xr-xui/menudef.h308
-rwxr-xr-xui/menus.txt39
1409 files changed, 806066 insertions, 0 deletions
diff --git a/COPYING.txt b/COPYING.txt
new file mode 100755
index 0000000..98443f3
--- /dev/null
+++ b/COPYING.txt
@@ -0,0 +1,281 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+ 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
diff --git a/README.txt b/README.txt
new file mode 100755
index 0000000..0dcc701
--- /dev/null
+++ b/README.txt
@@ -0,0 +1,193 @@
+Quake III Arena GPL source release
+==================================
+
+This file contains the following sections:
+
+LICENSE
+GENERAL NOTES
+COMPILING ON WIN32
+COMPILING ON GNU/LINUX
+COMPILING ON MAC
+
+LICENSE
+=======
+
+See COPYING.txt for the GNU GENERAL PUBLIC LICENSE
+
+Some source code in this release is not covered by the GPL:
+
+IO on .zip files using portions of zlib
+-----------------------------------------------------------------------------
+lines file(s)
+4299 code/qcommon/unzip.c
+4546 libs/pak/unzip.cpp
+Copyright (C) 1998 Gilles Vollant
+zlib is Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler
+
+ This software is provided 'as-is', without any express or implied
+ warranty. In no event will the authors be held liable for any damages
+ arising from the use of this software.
+
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
+
+MD4 Message-Digest Algorithm
+-----------------------------------------------------------------------------
+lines file(s)
+299 code/qcommon/md4.c
+277 common/md4.c
+Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All rights reserved.
+
+License to copy and use this software is granted provided that it is identified
+as the <93>RSA Data Security, Inc. MD4 Message-Digest Algorithm<94> in all mater
+ial mentioning or referencing this software or this function.
+License is also granted to make and use derivative works provided that such work
+s are identified as <93>derived from the RSA Data Security, Inc. MD4 Message-Dig
+est Algorithm<94> in all material mentioning or referencing the derived work.
+RSA Data Security, Inc. makes no representations concerning either the merchanta
+bility of this software or the suitability of this software for any particular p
+urpose. It is provided <93>as is<94> without express or implied warranty of any
+kind.
+
+checksums are used to validate pak files
+
+standard C library replacement routines
+-----------------------------------------------------------------------------
+lines file(s)
+1324 code/game/bg_lib.c
+Copyright (c) 1992, 1993
+The Regents of the University of California. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+3. All advertising materials mentioning features or use of this software
+ must display the following acknowledgement:
+ This product includes software developed by the University of
+ California, Berkeley and its contributors.
+4. Neither the name of the University nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGE.
+
+ADPCM coder/decoder
+-----------------------------------------------------------------------------
+lines file(s)
+330 code/client/snd_adpcm.c
+Copyright 1992 by Stichting Mathematisch Centrum, Amsterdam, The
+Netherlands.
+
+ All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and its
+documentation for any purpose and without fee is hereby granted,
+provided that the above copyright notice appear in all copies and that
+both that copyright notice and this permission notice appear in
+supporting documentation, and that the names of Stichting Mathematisch
+Centrum or CWI not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior permission.
+
+STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
+THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
+FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+JPEG library
+-----------------------------------------------------------------------------
+code/jpeg-6
+libs/jpeg6
+Copyright (C) 1991-1995, Thomas G. Lane
+
+Permission is hereby granted to use, copy, modify, and distribute this
+software (or portions thereof) for any purpose, without fee, subject to these
+conditions:
+(1) If any part of the source code for this software is distributed, then this
+README file must be included, with this copyright and no-warranty notice
+unaltered; and any additions, deletions, or changes to the original files
+must be clearly indicated in accompanying documentation.
+(2) If only executable code is distributed, then the accompanying
+documentation must state that "this software is based in part on the work of
+the Independent JPEG Group".
+(3) Permission for use of this software is granted only if the user accepts
+full responsibility for any undesirable consequences; the authors accept
+NO LIABILITY for damages of any kind.
+
+These conditions apply to any software derived from or based on the IJG code,
+not just to the unmodified library. If you use our work, you ought to
+acknowledge us.
+
+NOTE: unfortunately the README that came with our copy of the library has
+been lost, so the one from release 6b is included instead. There are a few
+'glue type' modifications to the library to make it easier to use from
+the engine, but otherwise the dependency can be easily cleaned up to a
+better release of the library.
+
+
+GENERAL NOTES
+=============
+
+A short summary of the file layout:
+
+code/ Quake III Arena source code ( renderer, game code, OS layer etc. )
+code/bspc bot routes compiler source code
+lcc/ the retargetable C compiler ( produces assembly to be turned into qvm bytecode by q3asm )
+q3asm/ assembly to qvm bytecode compiler
+q3map/ map compiler ( .map -> .bsp ) - this is the version that comes with Q3Radiant 200f
+q3radiant/ Q3Radiant map editor build 200f ( common/ and libs/ are support dirs for radiant )
+
+While we made sure we were still able to compile the game on Windows, GNU/Linux and Mac, this build didn't get any kind of extensive testing so it may not work completely right. Whenever an id game is released under GPL, several projects start making the source code more friendly to nowaday's compilers and environements. If you are picking up this release weeks/months/years after we uploaded it, you probably want to look around on the net for cleaned up versions of this codebase as well.
+
+COMPILING ON WIN32
+==================
+
+VC7 / Visual C++ 2003 project files are provided:
+code/quake3.sln
+q3radiant/Radiant.sln
+
+To compile the qvms, you need to run some batch files:
+you will need to have lcc.exe q3cpp.exe q3rcc.exe and q3asm.exe in your path
+( some precompiled binaries are provided in lcc/bin and code/win32/mod-sdk-setup/bin )
+the qvm batch files are in code/game code/cgame code/q3_ui code/ui ..
+
+COMPILING ON GNU/LINUX
+==================
+
+the build system using cons, which may be known as scons's perl ancestor now
+you don't have to track it down though, the build script is provided in the tree
+you will need nasm and gcc 2.95
+make sure you have the X Direct Graphics Access and X Video Mode extensions headers for your X11
+a typical compile command goes like this:
+[..]/code$ ./unix/cons -- gcc=gcc-2.95 g++=g++-2.95
+
+COMPILING ON MAC
+================
+
+project file for OSX compile is in code/macosx/Quake3.pbproj
diff --git a/code/Construct b/code/Construct
new file mode 100755
index 0000000..ad9bc3c
--- /dev/null
+++ b/code/Construct
@@ -0,0 +1,431 @@
+# -*- mode: perl -*-
+# cons script for cgame game q3_ui ui .so and .qvm builds
+#
+# Oct. 2001 TTimo <ttimo@idsoftware.com>
+#
+
+# the top directory is
+# <config>-<cpu>-<OS>-<libc version>
+# where:
+# <config> is "debug" or "release"
+# <cpu> is "x86" or "ppc"
+# <OS> is "Linux" "BSD" "IRIX" etc.
+# <libc version> is major.minor of libc config
+
+# source the compiler version utility
+BEGIN {
+ push @INC, './unix';
+}
+use Cons_gcc;
+
+# defaults
+$config = 'debug';
+$do_smp = 1;
+$do_masterserver = 0;
+$do_authserver = 0;
+$do_authport = 0;
+$do_setup = 0;
+$do_bspc = 0;
+$do_sdk = 0;
+$do_pk3 = 0;
+# those are exported
+$DO_WIN32 = 0;
+$NO_VM = 0;
+$NO_SO = 0;
+$CC='gcc';
+$CXX='g++';
+
+# detect an sdk build (don't attempt client build and other things)
+if ( -r 'unix/Conscript-client' )
+{
+ $no_core = 0;
+}
+else
+{
+ $no_core = 1;
+}
+
+# detection of CPU type
+$cpu = `uname -m`;
+chop ($cpu);
+if ($cpu +~ /i?86/)
+{
+ $cpu = 'x86';
+}
+# OS
+$OS = `uname`;
+chop ($OS);
+# hacky win32 detection and win32 specifics code
+if ($OS =~ CYGWIN)
+{
+ $DO_WIN32 = 1;
+}
+else
+{
+ # libc .. do the little magic!
+ $libc_cmd = '/lib/libc.so.6 |grep "GNU C "|grep version|awk -F "version " \'{ print $2 }\'|cut -b -3';
+ $libc = `$libc_cmd`;
+ chop ($libc);
+}
+
+if ($DO_WIN32 eq 1)
+{
+ print("Win32 build\n");
+
+ $config = $ARGV[0];
+
+ # TODO: option to override $Q3BASE from command line
+ $Q3BASE = $ENV{Q3BASE}; # FIXME: this doesn't play nice with cygwin path syntax
+ print("\$Q3BASE: $Q3BASE\n");
+
+ if($config eq 'debug')
+ {
+ $DIR = 'Debug';
+ system("cp -v $DIR/quake3.exe \$Q3BASE");
+ system("cp -v $DIR/cgamex86.dll $DIR/qagamex86.dll $DIR/uix86.dll \$Q3BASE/baseq3");
+ }
+ elsif ($config eq 'debug-TA')
+ {
+ $DIR = 'Debug_TA';
+ system("cp -v $DIR/quake3.exe \$Q3BASE");
+ system("cp -v $DIR/cgamex86.dll $DIR/qagamex86.dll $DIR/uix86.dll \$Q3BASE/missionpack");
+ }
+ elsif($config eq 'release-TA')
+ {
+ $DIR = 'Release_TA';
+ # spank!
+ system("./spank.sh");
+ system("cp -v $DIR/quake3.exe \$Q3BASE");
+ }
+ else
+ {
+ printf("ERROR: no config option (debug debug-TA release-TA)");
+ exit;
+ }
+
+ # copy selected stuff to shared media
+ $DESTDIR='/cygdrive/e/incoming/Id/q3-1.32';
+ system("cp -v $DIR/quake3.exe $DESTDIR");
+ system("cp -v /cygdrive/e/Q3SetupMedia/quake3/CHANGES-1.32.txt $DESTDIR");
+
+ exit;
+}
+
+if(@ARGV gt 0)
+{
+ foreach $cmdopt (@ARGV)
+ {
+ if(lc($cmdopt) eq 'release')
+ {
+ $config = 'release';
+ next;
+ }
+ elsif(lc($cmdopt) eq 'debug')
+ {
+ $config = 'debug';
+ next;
+ }
+ elsif(lc($cmdopt) eq 'novm')
+ {
+ $NO_VM = 1;
+ next;
+ }
+ elsif(lc($cmdopt) eq 'noso')
+ {
+ $NO_SO = 1;
+ next;
+ }
+ elsif(lc($cmdopt) eq 'nosmp')
+ {
+ $do_smp = 0;
+ next;
+ }
+ elsif(lc($cmdopt) =~ 'master_server=.*')
+ {
+ $do_masterserver = 1;
+ $master_server = lc($cmdopt);
+ $master_server =~ s/master_server=(.*)/\1/;
+ next;
+ }
+ elsif(lc($cmdopt) =~ 'auth_server=.*')
+ {
+ $do_authserver = 1;
+ $auth_server = lc($cmdopt);
+ $auth_server =~ s/auth_server=(.*)/\1/;
+ next;
+ }
+ elsif(lc($cmdopt) =~ 'auth_port=.*')
+ {
+ $do_authport = 1;
+ $auth_port = lc($cmdopt);
+ $auth_port =~ s/auth_port=(.*)/\1/;
+ next;
+ }
+ elsif(lc($cmdopt) =~ 'setup')
+ {
+ $do_setup = 1;
+ next;
+ }
+ elsif(lc($cmdopt) =~ 'bspc')
+ {
+ $do_bspc = 1;
+ next;
+ }
+ elsif(lc($cmdopt) =~ 'sdk')
+ {
+ $do_sdk = 1;
+ next;
+ }
+ elsif(lc($cmdopt) =~ 'pk3')
+ {
+ $do_pk3 = 1;
+ next;
+ }
+ elsif(lc($cmdopt) =~ 'gcc=.*')
+ {
+ $CC=lc($cmdopt);
+ $CC =~ s/gcc=(.*)/\1/;
+ next;
+ }
+ elsif(lc($cmdopt) =~ 'g\+\+=.*')
+ {
+ $CXX=lc($cmdopt);
+ $CXX=~s/g\+\+=(.*)/\1/;
+ next;
+ }
+ else
+ {
+ # output an error & exit
+ print("Error\n $0: Unknown command line option: [ $cmdopt ]\n");
+ system("cons -h");
+ exit;
+ }
+ }
+}
+
+if (($do_setup eq 1) && ($config ne 'release'))
+{
+ print("Error\n $0: 'setup' requires 'release'\n");
+ exit;
+}
+
+# sdk
+if ($do_sdk eq 1)
+{
+ # extract the Q3 version from q_shared.h
+ $line = `cat game/q_shared.h | grep Q3_VERSION`;
+ chomp $line;
+ $line =~ s/.*Q3\ (.*)\"/$1/;
+ $Q3_VER = $line;
+ $SDK_NAME = "linuxq3a-sdk-$Q3_VER.x86.run";
+ Default "unix/$SDK_NAME";
+ Export qw( SDK_NAME Q3_VER );
+ Build 'unix/Conscript-sdk';
+ return;
+}
+
+# build the config directory
+$CONFIG_DIR = $config . '-' . $cpu . '-' . $OS . '-' . $libc;
+
+$COMMON_CFLAGS = '-pipe -fsigned-char ';
+
+if ($config eq 'debug')
+{
+ # use -Werror for better QA
+ $BASE_CFLAGS = $COMMON_CFLAGS . '-g -Wall -Werror -O ';
+ $BSPC_BASE_CFLAGS = $COMMON_CFLAGS . '-g -O -DLINUX -DBSPC -Dstricmp=strcasecmp ';
+}
+else
+{
+ $BASE_CFLAGS = $COMMON_CFLAGS . '-DNDEBUG -O6 -mcpu=pentiumpro -march=pentium -fomit-frame-pointer -ffast-math -malign-loops=2 -malign-jumps=2 -malign-functions=2 -fno-strict-aliasing -fstrength-reduce ';
+ $BSPC_BASE_CFLAGS = $BASE_CFLAGS . '-DLINUX -DBSPC -Dstricmp=strcasecmp ';
+}
+
+if ($do_masterserver eq 1)
+{
+ $BASE_CFLAGS .= "-DMASTER_SERVER_NAME=\\\"$master_server\\\" ";
+}
+
+if ($do_authserver eq 1)
+{
+ $BASE_CFLAGS .= "-DAUTHORIZE_SERVER_NAME=\\\"$auth_server\\\" ";
+}
+
+if ($do_authport eq 1)
+{
+ $BASE_CFLAGS .= "-DPORT_AUTHORIZE=$auth_port ";
+}
+
+my @gcc_version = Cons_gcc::get_gcc_version($CC);
+print("GCC version: $gcc_version[1] - $gcc_version[2]\n");
+# with 2.95 you can link with gcc, this avoids nasty useless libstdc++ dependency
+if ($gcc_version[0] eq '2')
+{
+ $LINK = $CC;
+} else {
+ $LINK = $CXX;
+}
+
+my @ccache = Cons_gcc::get_ccache();
+if ($ccache[0] eq '1')
+{
+ $CC = $ccache[1] . " " . $CC;
+ $CXX = $ccache[1] . " " . $CXX;
+}
+
+print 'cpu : ' . $cpu . "\nOS : " . $OS . "\n";
+print "libc: " . $libc . "\n";
+print "configured for " . $config . " build\n";
+print 'CFLAGS: ' . $BASE_CFLAGS . "\n";
+
+# install config
+$INSTALL_BASEDIR='#install';
+
+Default $INSTALL_BASEDIR;
+
+sub build_tools {
+ system("mkdir qvmtools 2>/dev/null");
+ if (@_[0] eq 'q3lcc')
+ {
+ system("cd ../lcc ; make all ; cp /tmp/lcc ../code/qvmtools/q3lcc ; cp /tmp/rcc ../code/qvmtools/q3rcc ; cp /tmp/cpp ../code/qvmtools/q3cpp");
+ }
+ elsif (@_[0] eq 'q3asm')
+ {
+ system("cd ../q3asm ; make ; cp q3asm ../code/qvmtools");
+ }
+ else
+ {
+ printf("build_tools: @_[0] unrecognized command\n");
+ die;
+ }
+ return 1;
+}
+
+# build tools
+$env_tools = new cons();
+Command $env_tools 'qvmtools/q3lcc', '[perl] &build_tools(\'q3lcc\')';
+Command $env_tools 'qvmtools/q3asm', '[perl] &build_tools(\'q3asm\')';
+
+if ($do_bspc eq 1)
+{
+ # build bspc
+ $BUILD_DIR = $CONFIG_DIR . '/bspc';
+ Link $BUILD_DIR => '.';
+ $INSTALL_DIR = $INSTALL_BASEDIR . '/utils';
+ Export qw( BSPC_BASE_CFLAGS BUILD_DIR INSTALL_DIR CC CXX LINK );
+ Build $BUILD_DIR . '/bspc/Conscript';
+}
+
+# build vanilla Q3
+$TARGET_DIR='Q3';
+
+$INSTALL_DIR = $INSTALL_BASEDIR . '/baseq3';
+
+$BUILD_DIR = $CONFIG_DIR . '/' . $TARGET_DIR . '/cgame';
+Link $BUILD_DIR => '.';
+Export qw( BASE_CFLAGS TARGET_DIR INSTALL_DIR NO_VM NO_SO CC CXX LINK );
+Build $BUILD_DIR . '/cgame/Conscript';
+
+$BUILD_DIR = $CONFIG_DIR . '/' . $TARGET_DIR . '/game';
+Link $BUILD_DIR => '.';
+Export qw( BASE_CFLAGS TARGET_DIR INSTALL_DIR NO_VM NO_SO CC CXX LINK );
+Build $BUILD_DIR . '/game/Conscript';
+
+$BUILD_DIR = $CONFIG_DIR . '/' . $TARGET_DIR . '/q3_ui';
+Link $BUILD_DIR => '.';
+Export qw( BASE_CFLAGS TARGET_DIR INSTALL_DIR NO_VM NO_SO CC CXX LINK );
+Build $BUILD_DIR . '/q3_ui/Conscript';
+
+# build TA
+$TARGET_DIR='TA';
+
+$INSTALL_DIR = $INSTALL_BASEDIR . '/missionpack';
+
+$BUILD_DIR = $CONFIG_DIR . "/" . $TARGET_DIR . '/cgame';
+Link $BUILD_DIR => '.';
+Export qw( BASE_CFLAGS TARGET_DIR INSTALL_DIR NO_VM NO_SO CC CXX LINK );
+Build $BUILD_DIR . '/cgame/Conscript';
+
+$BUILD_DIR = $CONFIG_DIR . "/" . $TARGET_DIR . '/game';
+Link $BUILD_DIR => '.';
+Export qw( BASE_CFLAGS TARGET_DIR INSTALL_DIR NO_VM NO_SO CC CXX LINK );
+Build $BUILD_DIR . '/game/Conscript';
+
+$BUILD_DIR = $CONFIG_DIR . '/' . $TARGET_DIR . '/ui';
+Link $BUILD_DIR => '.';
+Export qw( BASE_CFLAGS TARGET_DIR INSTALL_DIR NO_VM NO_SO CC CXX LINK );
+Build $BUILD_DIR . '/ui/Conscript';
+
+# core
+if ($no_core eq 1)
+{
+ return;
+}
+
+$INSTALL_DIR = $INSTALL_BASEDIR;
+$BUILD_DIR = $CONFIG_DIR . '/core/dedicated';
+Link $BUILD_DIR => '.';
+$hack = $BASE_CFLAGS; # hit me!
+$BASE_CFLAGS .= '-DDEDICATED ';
+Export qw( BASE_CFLAGS BUILD_DIR INSTALL_DIR CC CXX LINK );
+Build $BUILD_DIR . '/unix/Conscript-dedicated';
+$BASE_CFLAGS = $hack;
+
+
+
+$TARGETNAME = 'linuxquake3';
+$BUILD_DIR = $CONFIG_DIR . '/core/client';
+$BASE_LDFLAGS = '';
+
+Link $BUILD_DIR => '.';
+Export qw( BASE_CFLAGS BASE_LDFLAGS BUILD_DIR INSTALL_DIR TARGETNAME CC CXX LINK );
+Build $BUILD_DIR . '/unix/Conscript-client';
+
+if ($do_smp eq 1)
+{
+ $TARGETNAME = 'linuxquake3-smp';
+ $BUILD_DIR = $CONFIG_DIR . '/core/client-smp';
+ $BASE_CFLAGS .= '-DSMP ';
+ $BASE_LDFLAGS = '-lpthread ';
+
+ Link $BUILD_DIR => '.';
+ Export qw( BASE_CFLAGS BASE_LDFLAGS BUILD_DIR INSTALL_DIR TARGETNAME CC CXX LINK );
+ Build $BUILD_DIR . '/unix/Conscript-client';
+}
+
+if ($NO_VM eq 0 && $do_pk3 eq 1)
+{
+ # build the PK3s
+ $INSTALL_DIR = $INSTALL_BASEDIR;
+ $BUILD_DIR = $CONFIG_DIR . '/pk3-builder';
+ Link $BUILD_DIR => 'unix';
+ Export qw( INSTALL_DIR BUILD_DIR CONFIG_DIR CC CXX LINK );
+ Build $BUILD_DIR . '/Conscript-pk3';
+}
+
+if ($do_setup eq 1)
+{
+ Link $CONFIG_DIR => '.';
+ Export qw( INSTALL_BASEDIR );
+ Build $CONFIG_DIR . '/unix/Conscript-setup';
+}
+
+Help
+"
+Usage: cons [-h] [ -- [release|debug] [novm] [noso] [nosmp] [master_server=<adr>] [auth_server=<adr>] [auth_port=<port>] [pk3] [bspc] [setup] [sdk]]
+Default build type is Debug, specifying '-- release' on the
+command line builds a Release version (NOTE that this option
+only affects the native libraries).
+
+novm: will not build the VMs
+noso: will not build the so
+
+below are for core builds only:
+
+nosmp : do not build the SMP-enabled version of the renderer
+pk3 : generate the pk3s on the fly (defined in unix/Conscript-pk3)
+bspc : build bspc
+setup : build setup
+sdk : build the mod sdk
+"
+;
diff --git a/code/Makefile b/code/Makefile
new file mode 100755
index 0000000..673b3ae
--- /dev/null
+++ b/code/Makefile
@@ -0,0 +1,3 @@
+# nasty ugly to get build system working from Anjuta
+all:
+ if [ `hostname` == sparkle ] ; then ./unix/pcons-2.3.1 -j4 -- novm noso ; else ./unix/cons ; fi
diff --git a/code/botlib/aasfile.h b/code/botlib/aasfile.h
new file mode 100755
index 0000000..5b37fbe
--- /dev/null
+++ b/code/botlib/aasfile.h
@@ -0,0 +1,267 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+
+//NOTE: int = default signed
+// default long
+
+#define AASID (('S'<<24)+('A'<<16)+('A'<<8)+'E')
+#define AASVERSION_OLD 4
+#define AASVERSION 5
+
+//presence types
+#define PRESENCE_NONE 1
+#define PRESENCE_NORMAL 2
+#define PRESENCE_CROUCH 4
+
+//travel types
+#define MAX_TRAVELTYPES 32
+#define TRAVEL_INVALID 1 //temporary not possible
+#define TRAVEL_WALK 2 //walking
+#define TRAVEL_CROUCH 3 //crouching
+#define TRAVEL_BARRIERJUMP 4 //jumping onto a barrier
+#define TRAVEL_JUMP 5 //jumping
+#define TRAVEL_LADDER 6 //climbing a ladder
+#define TRAVEL_WALKOFFLEDGE 7 //walking of a ledge
+#define TRAVEL_SWIM 8 //swimming
+#define TRAVEL_WATERJUMP 9 //jump out of the water
+#define TRAVEL_TELEPORT 10 //teleportation
+#define TRAVEL_ELEVATOR 11 //travel by elevator
+#define TRAVEL_ROCKETJUMP 12 //rocket jumping required for travel
+#define TRAVEL_BFGJUMP 13 //bfg jumping required for travel
+#define TRAVEL_GRAPPLEHOOK 14 //grappling hook required for travel
+#define TRAVEL_DOUBLEJUMP 15 //double jump
+#define TRAVEL_RAMPJUMP 16 //ramp jump
+#define TRAVEL_STRAFEJUMP 17 //strafe jump
+#define TRAVEL_JUMPPAD 18 //jump pad
+#define TRAVEL_FUNCBOB 19 //func bob
+
+//additional travel flags
+#define TRAVELTYPE_MASK 0xFFFFFF
+#define TRAVELFLAG_NOTTEAM1 (1 << 24)
+#define TRAVELFLAG_NOTTEAM2 (2 << 24)
+
+//face flags
+#define FACE_SOLID 1 //just solid at the other side
+#define FACE_LADDER 2 //ladder
+#define FACE_GROUND 4 //standing on ground when in this face
+#define FACE_GAP 8 //gap in the ground
+#define FACE_LIQUID 16 //face seperating two areas with liquid
+#define FACE_LIQUIDSURFACE 32 //face seperating liquid and air
+#define FACE_BRIDGE 64 //can walk over this face if bridge is closed
+
+//area contents
+#define AREACONTENTS_WATER 1
+#define AREACONTENTS_LAVA 2
+#define AREACONTENTS_SLIME 4
+#define AREACONTENTS_CLUSTERPORTAL 8
+#define AREACONTENTS_TELEPORTAL 16
+#define AREACONTENTS_ROUTEPORTAL 32
+#define AREACONTENTS_TELEPORTER 64
+#define AREACONTENTS_JUMPPAD 128
+#define AREACONTENTS_DONOTENTER 256
+#define AREACONTENTS_VIEWPORTAL 512
+#define AREACONTENTS_MOVER 1024
+#define AREACONTENTS_NOTTEAM1 2048
+#define AREACONTENTS_NOTTEAM2 4096
+//number of model of the mover inside this area
+#define AREACONTENTS_MODELNUMSHIFT 24
+#define AREACONTENTS_MAXMODELNUM 0xFF
+#define AREACONTENTS_MODELNUM (AREACONTENTS_MAXMODELNUM << AREACONTENTS_MODELNUMSHIFT)
+
+//area flags
+#define AREA_GROUNDED 1 //bot can stand on the ground
+#define AREA_LADDER 2 //area contains one or more ladder faces
+#define AREA_LIQUID 4 //area contains a liquid
+#define AREA_DISABLED 8 //area is disabled for routing when set
+#define AREA_BRIDGE 16 //area ontop of a bridge
+
+//aas file header lumps
+#define AAS_LUMPS 14
+#define AASLUMP_BBOXES 0
+#define AASLUMP_VERTEXES 1
+#define AASLUMP_PLANES 2
+#define AASLUMP_EDGES 3
+#define AASLUMP_EDGEINDEX 4
+#define AASLUMP_FACES 5
+#define AASLUMP_FACEINDEX 6
+#define AASLUMP_AREAS 7
+#define AASLUMP_AREASETTINGS 8
+#define AASLUMP_REACHABILITY 9
+#define AASLUMP_NODES 10
+#define AASLUMP_PORTALS 11
+#define AASLUMP_PORTALINDEX 12
+#define AASLUMP_CLUSTERS 13
+
+//========== bounding box =========
+
+//bounding box
+typedef struct aas_bbox_s
+{
+ int presencetype;
+ int flags;
+ vec3_t mins, maxs;
+} aas_bbox_t;
+
+//============ settings ===========
+
+//reachability to another area
+typedef struct aas_reachability_s
+{
+ int areanum; //number of the reachable area
+ int facenum; //number of the face towards the other area
+ int edgenum; //number of the edge towards the other area
+ vec3_t start; //start point of inter area movement
+ vec3_t end; //end point of inter area movement
+ int traveltype; //type of travel required to get to the area
+ unsigned short int traveltime;//travel time of the inter area movement
+} aas_reachability_t;
+
+//area settings
+typedef struct aas_areasettings_s
+{
+ //could also add all kind of statistic fields
+ int contents; //contents of the area
+ int areaflags; //several area flags
+ int presencetype; //how a bot can be present in this area
+ int cluster; //cluster the area belongs to, if negative it's a portal
+ int clusterareanum; //number of the area in the cluster
+ int numreachableareas; //number of reachable areas from this one
+ int firstreachablearea; //first reachable area in the reachable area index
+} aas_areasettings_t;
+
+//cluster portal
+typedef struct aas_portal_s
+{
+ int areanum; //area that is the actual portal
+ int frontcluster; //cluster at front of portal
+ int backcluster; //cluster at back of portal
+ int clusterareanum[2]; //number of the area in the front and back cluster
+} aas_portal_t;
+
+//cluster portal index
+typedef int aas_portalindex_t;
+
+//cluster
+typedef struct aas_cluster_s
+{
+ int numareas; //number of areas in the cluster
+ int numreachabilityareas; //number of areas with reachabilities
+ int numportals; //number of cluster portals
+ int firstportal; //first cluster portal in the index
+} aas_cluster_t;
+
+//============ 3d definition ============
+
+typedef vec3_t aas_vertex_t;
+
+//just a plane in the third dimension
+typedef struct aas_plane_s
+{
+ vec3_t normal; //normal vector of the plane
+ float dist; //distance of the plane (normal vector * distance = point in plane)
+ int type;
+} aas_plane_t;
+
+//edge
+typedef struct aas_edge_s
+{
+ int v[2]; //numbers of the vertexes of this edge
+} aas_edge_t;
+
+//edge index, negative if vertexes are reversed
+typedef int aas_edgeindex_t;
+
+//a face bounds an area, often it will also seperate two areas
+typedef struct aas_face_s
+{
+ int planenum; //number of the plane this face is in
+ int faceflags; //face flags (no use to create face settings for just this field)
+ int numedges; //number of edges in the boundary of the face
+ int firstedge; //first edge in the edge index
+ int frontarea; //area at the front of this face
+ int backarea; //area at the back of this face
+} aas_face_t;
+
+//face index, stores a negative index if backside of face
+typedef int aas_faceindex_t;
+
+//area with a boundary of faces
+typedef struct aas_area_s
+{
+ int areanum; //number of this area
+ //3d definition
+ int numfaces; //number of faces used for the boundary of the area
+ int firstface; //first face in the face index used for the boundary of the area
+ vec3_t mins; //mins of the area
+ vec3_t maxs; //maxs of the area
+ vec3_t center; //'center' of the area
+} aas_area_t;
+
+//nodes of the bsp tree
+typedef struct aas_node_s
+{
+ int planenum;
+ int children[2]; //child nodes of this node, or areas as leaves when negative
+ //when a child is zero it's a solid leaf
+} aas_node_t;
+
+//=========== aas file ===============
+
+//header lump
+typedef struct
+{
+ int fileofs;
+ int filelen;
+} aas_lump_t;
+
+//aas file header
+typedef struct aas_header_s
+{
+ int ident;
+ int version;
+ int bspchecksum;
+ //data entries
+ aas_lump_t lumps[AAS_LUMPS];
+} aas_header_t;
+
+
+//====== additional information ======
+/*
+
+- when a node child is a solid leaf the node child number is zero
+- two adjacent areas (sharing a plane at opposite sides) share a face
+ this face is a portal between the areas
+- when an area uses a face from the faceindex with a positive index
+ then the face plane normal points into the area
+- the face edges are stored counter clockwise using the edgeindex
+- two adjacent convex areas (sharing a face) only share One face
+ this is a simple result of the areas being convex
+- the areas can't have a mixture of ground and gap faces
+ other mixtures of faces in one area are allowed
+- areas with the AREACONTENTS_CLUSTERPORTAL in the settings have
+ the cluster number set to the negative portal number
+- edge zero is a dummy
+- face zero is a dummy
+- area zero is a dummy
+- node zero is a dummy
+*/
diff --git a/code/botlib/be_aas_bsp.h b/code/botlib/be_aas_bsp.h
new file mode 100755
index 0000000..d55353c
--- /dev/null
+++ b/code/botlib/be_aas_bsp.h
@@ -0,0 +1,89 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_bsp.h
+ *
+ * desc: AAS
+ *
+ * $Archive: /source/code/botlib/be_aas_bsp.h $
+ *
+ *****************************************************************************/
+
+#ifdef AASINTERN
+//loads the given BSP file
+int AAS_LoadBSPFile(void);
+//dump the loaded BSP data
+void AAS_DumpBSPData(void);
+//unlink the given entity from the bsp tree leaves
+void AAS_UnlinkFromBSPLeaves(bsp_link_t *leaves);
+//link the given entity to the bsp tree leaves of the given model
+bsp_link_t *AAS_BSPLinkEntity(vec3_t absmins,
+ vec3_t absmaxs,
+ int entnum,
+ int modelnum);
+
+//calculates collision with given entity
+qboolean AAS_EntityCollision(int entnum,
+ vec3_t start,
+ vec3_t boxmins,
+ vec3_t boxmaxs,
+ vec3_t end,
+ int contentmask,
+ bsp_trace_t *trace);
+//for debugging
+void AAS_PrintFreeBSPLinks(char *str);
+//
+#endif //AASINTERN
+
+#define MAX_EPAIRKEY 128
+
+//trace through the world
+bsp_trace_t AAS_Trace( vec3_t start,
+ vec3_t mins,
+ vec3_t maxs,
+ vec3_t end,
+ int passent,
+ int contentmask);
+//returns the contents at the given point
+int AAS_PointContents(vec3_t point);
+//returns true when p2 is in the PVS of p1
+qboolean AAS_inPVS(vec3_t p1, vec3_t p2);
+//returns true when p2 is in the PHS of p1
+qboolean AAS_inPHS(vec3_t p1, vec3_t p2);
+//returns true if the given areas are connected
+qboolean AAS_AreasConnected(int area1, int area2);
+//creates a list with entities totally or partly within the given box
+int AAS_BoxEntities(vec3_t absmins, vec3_t absmaxs, int *list, int maxcount);
+//gets the mins, maxs and origin of a BSP model
+void AAS_BSPModelMinsMaxsOrigin(int modelnum, vec3_t angles, vec3_t mins, vec3_t maxs, vec3_t origin);
+//handle to the next bsp entity
+int AAS_NextBSPEntity(int ent);
+//return the value of the BSP epair key
+int AAS_ValueForBSPEpairKey(int ent, char *key, char *value, int size);
+//get a vector for the BSP epair key
+int AAS_VectorForBSPEpairKey(int ent, char *key, vec3_t v);
+//get a float for the BSP epair key
+int AAS_FloatForBSPEpairKey(int ent, char *key, float *value);
+//get an integer for the BSP epair key
+int AAS_IntForBSPEpairKey(int ent, char *key, int *value);
+
diff --git a/code/botlib/be_aas_bspq3.c b/code/botlib/be_aas_bspq3.c
new file mode 100755
index 0000000..a5e0d44
--- /dev/null
+++ b/code/botlib/be_aas_bspq3.c
@@ -0,0 +1,487 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_bspq3.c
+ *
+ * desc: BSP, Environment Sampling
+ *
+ * $Archive: /MissionPack/code/botlib/be_aas_bspq3.c $
+ *
+ *****************************************************************************/
+
+#include "../game/q_shared.h"
+#include "l_memory.h"
+#include "l_script.h"
+#include "l_precomp.h"
+#include "l_struct.h"
+#include "aasfile.h"
+#include "../game/botlib.h"
+#include "../game/be_aas.h"
+#include "be_aas_funcs.h"
+#include "be_aas_def.h"
+
+extern botlib_import_t botimport;
+
+//#define TRACE_DEBUG
+
+#define ON_EPSILON 0.005
+//#define DEG2RAD( a ) (( a * M_PI ) / 180.0F)
+
+#define MAX_BSPENTITIES 2048
+
+typedef struct rgb_s
+{
+ int red;
+ int green;
+ int blue;
+} rgb_t;
+
+//bsp entity epair
+typedef struct bsp_epair_s
+{
+ char *key;
+ char *value;
+ struct bsp_epair_s *next;
+} bsp_epair_t;
+
+//bsp data entity
+typedef struct bsp_entity_s
+{
+ bsp_epair_t *epairs;
+} bsp_entity_t;
+
+//id Sofware BSP data
+typedef struct bsp_s
+{
+ //true when bsp file is loaded
+ int loaded;
+ //entity data
+ int entdatasize;
+ char *dentdata;
+ //bsp entities
+ int numentities;
+ bsp_entity_t entities[MAX_BSPENTITIES];
+} bsp_t;
+
+//global bsp
+bsp_t bspworld;
+
+
+#ifdef BSP_DEBUG
+typedef struct cname_s
+{
+ int value;
+ char *name;
+} cname_t;
+
+cname_t contentnames[] =
+{
+ {CONTENTS_SOLID,"CONTENTS_SOLID"},
+ {CONTENTS_WINDOW,"CONTENTS_WINDOW"},
+ {CONTENTS_AUX,"CONTENTS_AUX"},
+ {CONTENTS_LAVA,"CONTENTS_LAVA"},
+ {CONTENTS_SLIME,"CONTENTS_SLIME"},
+ {CONTENTS_WATER,"CONTENTS_WATER"},
+ {CONTENTS_MIST,"CONTENTS_MIST"},
+ {LAST_VISIBLE_CONTENTS,"LAST_VISIBLE_CONTENTS"},
+
+ {CONTENTS_AREAPORTAL,"CONTENTS_AREAPORTAL"},
+ {CONTENTS_PLAYERCLIP,"CONTENTS_PLAYERCLIP"},
+ {CONTENTS_MONSTERCLIP,"CONTENTS_MONSTERCLIP"},
+ {CONTENTS_CURRENT_0,"CONTENTS_CURRENT_0"},
+ {CONTENTS_CURRENT_90,"CONTENTS_CURRENT_90"},
+ {CONTENTS_CURRENT_180,"CONTENTS_CURRENT_180"},
+ {CONTENTS_CURRENT_270,"CONTENTS_CURRENT_270"},
+ {CONTENTS_CURRENT_UP,"CONTENTS_CURRENT_UP"},
+ {CONTENTS_CURRENT_DOWN,"CONTENTS_CURRENT_DOWN"},
+ {CONTENTS_ORIGIN,"CONTENTS_ORIGIN"},
+ {CONTENTS_MONSTER,"CONTENTS_MONSTER"},
+ {CONTENTS_DEADMONSTER,"CONTENTS_DEADMONSTER"},
+ {CONTENTS_DETAIL,"CONTENTS_DETAIL"},
+ {CONTENTS_TRANSLUCENT,"CONTENTS_TRANSLUCENT"},
+ {CONTENTS_LADDER,"CONTENTS_LADDER"},
+ {0, 0}
+};
+
+void PrintContents(int contents)
+{
+ int i;
+
+ for (i = 0; contentnames[i].value; i++)
+ {
+ if (contents & contentnames[i].value)
+ {
+ botimport.Print(PRT_MESSAGE, "%s\n", contentnames[i].name);
+ } //end if
+ } //end for
+} //end of the function PrintContents
+
+#endif // BSP_DEBUG
+//===========================================================================
+// traces axial boxes of any size through the world
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bsp_trace_t AAS_Trace(vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int passent, int contentmask)
+{
+ bsp_trace_t bsptrace;
+ botimport.Trace(&bsptrace, start, mins, maxs, end, passent, contentmask);
+ return bsptrace;
+} //end of the function AAS_Trace
+//===========================================================================
+// returns the contents at the given point
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_PointContents(vec3_t point)
+{
+ return botimport.PointContents(point);
+} //end of the function AAS_PointContents
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean AAS_EntityCollision(int entnum,
+ vec3_t start, vec3_t boxmins, vec3_t boxmaxs, vec3_t end,
+ int contentmask, bsp_trace_t *trace)
+{
+ bsp_trace_t enttrace;
+
+ botimport.EntityTrace(&enttrace, start, boxmins, boxmaxs, end, entnum, contentmask);
+ if (enttrace.fraction < trace->fraction)
+ {
+ Com_Memcpy(trace, &enttrace, sizeof(bsp_trace_t));
+ return qtrue;
+ } //end if
+ return qfalse;
+} //end of the function AAS_EntityCollision
+//===========================================================================
+// returns true if in Potentially Hearable Set
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean AAS_inPVS(vec3_t p1, vec3_t p2)
+{
+ return botimport.inPVS(p1, p2);
+} //end of the function AAS_InPVS
+//===========================================================================
+// returns true if in Potentially Visible Set
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean AAS_inPHS(vec3_t p1, vec3_t p2)
+{
+ return qtrue;
+} //end of the function AAS_inPHS
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_BSPModelMinsMaxsOrigin(int modelnum, vec3_t angles, vec3_t mins, vec3_t maxs, vec3_t origin)
+{
+ botimport.BSPModelMinsMaxsOrigin(modelnum, angles, mins, maxs, origin);
+} //end of the function AAS_BSPModelMinsMaxs
+//===========================================================================
+// unlinks the entity from all leaves
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_UnlinkFromBSPLeaves(bsp_link_t *leaves)
+{
+} //end of the function AAS_UnlinkFromBSPLeaves
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bsp_link_t *AAS_BSPLinkEntity(vec3_t absmins, vec3_t absmaxs, int entnum, int modelnum)
+{
+ return NULL;
+} //end of the function AAS_BSPLinkEntity
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_BoxEntities(vec3_t absmins, vec3_t absmaxs, int *list, int maxcount)
+{
+ return 0;
+} //end of the function AAS_BoxEntities
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_NextBSPEntity(int ent)
+{
+ ent++;
+ if (ent >= 1 && ent < bspworld.numentities) return ent;
+ return 0;
+} //end of the function AAS_NextBSPEntity
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_BSPEntityInRange(int ent)
+{
+ if (ent <= 0 || ent >= bspworld.numentities)
+ {
+ botimport.Print(PRT_MESSAGE, "bsp entity out of range\n");
+ return qfalse;
+ } //end if
+ return qtrue;
+} //end of the function AAS_BSPEntityInRange
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_ValueForBSPEpairKey(int ent, char *key, char *value, int size)
+{
+ bsp_epair_t *epair;
+
+ value[0] = '\0';
+ if (!AAS_BSPEntityInRange(ent)) return qfalse;
+ for (epair = bspworld.entities[ent].epairs; epair; epair = epair->next)
+ {
+ if (!strcmp(epair->key, key))
+ {
+ strncpy(value, epair->value, size-1);
+ value[size-1] = '\0';
+ return qtrue;
+ } //end if
+ } //end for
+ return qfalse;
+} //end of the function AAS_FindBSPEpair
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_VectorForBSPEpairKey(int ent, char *key, vec3_t v)
+{
+ char buf[MAX_EPAIRKEY];
+ double v1, v2, v3;
+
+ VectorClear(v);
+ if (!AAS_ValueForBSPEpairKey(ent, key, buf, MAX_EPAIRKEY)) return qfalse;
+ //scanf into doubles, then assign, so it is vec_t size independent
+ v1 = v2 = v3 = 0;
+ sscanf(buf, "%lf %lf %lf", &v1, &v2, &v3);
+ v[0] = v1;
+ v[1] = v2;
+ v[2] = v3;
+ return qtrue;
+} //end of the function AAS_VectorForBSPEpairKey
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_FloatForBSPEpairKey(int ent, char *key, float *value)
+{
+ char buf[MAX_EPAIRKEY];
+
+ *value = 0;
+ if (!AAS_ValueForBSPEpairKey(ent, key, buf, MAX_EPAIRKEY)) return qfalse;
+ *value = atof(buf);
+ return qtrue;
+} //end of the function AAS_FloatForBSPEpairKey
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_IntForBSPEpairKey(int ent, char *key, int *value)
+{
+ char buf[MAX_EPAIRKEY];
+
+ *value = 0;
+ if (!AAS_ValueForBSPEpairKey(ent, key, buf, MAX_EPAIRKEY)) return qfalse;
+ *value = atoi(buf);
+ return qtrue;
+} //end of the function AAS_IntForBSPEpairKey
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_FreeBSPEntities(void)
+{
+ int i;
+ bsp_entity_t *ent;
+ bsp_epair_t *epair, *nextepair;
+
+ for (i = 1; i < bspworld.numentities; i++)
+ {
+ ent = &bspworld.entities[i];
+ for (epair = ent->epairs; epair; epair = nextepair)
+ {
+ nextepair = epair->next;
+ //
+ if (epair->key) FreeMemory(epair->key);
+ if (epair->value) FreeMemory(epair->value);
+ FreeMemory(epair);
+ } //end for
+ } //end for
+ bspworld.numentities = 0;
+} //end of the function AAS_FreeBSPEntities
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ParseBSPEntities(void)
+{
+ script_t *script;
+ token_t token;
+ bsp_entity_t *ent;
+ bsp_epair_t *epair;
+
+ script = LoadScriptMemory(bspworld.dentdata, bspworld.entdatasize, "entdata");
+ SetScriptFlags(script, SCFL_NOSTRINGWHITESPACES|SCFL_NOSTRINGESCAPECHARS);//SCFL_PRIMITIVE);
+
+ bspworld.numentities = 1;
+
+ while(PS_ReadToken(script, &token))
+ {
+ if (strcmp(token.string, "{"))
+ {
+ ScriptError(script, "invalid %s\n", token.string);
+ AAS_FreeBSPEntities();
+ FreeScript(script);
+ return;
+ } //end if
+ if (bspworld.numentities >= MAX_BSPENTITIES)
+ {
+ botimport.Print(PRT_MESSAGE, "too many entities in BSP file\n");
+ break;
+ } //end if
+ ent = &bspworld.entities[bspworld.numentities];
+ bspworld.numentities++;
+ ent->epairs = NULL;
+ while(PS_ReadToken(script, &token))
+ {
+ if (!strcmp(token.string, "}")) break;
+ epair = (bsp_epair_t *) GetClearedHunkMemory(sizeof(bsp_epair_t));
+ epair->next = ent->epairs;
+ ent->epairs = epair;
+ if (token.type != TT_STRING)
+ {
+ ScriptError(script, "invalid %s\n", token.string);
+ AAS_FreeBSPEntities();
+ FreeScript(script);
+ return;
+ } //end if
+ StripDoubleQuotes(token.string);
+ epair->key = (char *) GetHunkMemory(strlen(token.string) + 1);
+ strcpy(epair->key, token.string);
+ if (!PS_ExpectTokenType(script, TT_STRING, 0, &token))
+ {
+ AAS_FreeBSPEntities();
+ FreeScript(script);
+ return;
+ } //end if
+ StripDoubleQuotes(token.string);
+ epair->value = (char *) GetHunkMemory(strlen(token.string) + 1);
+ strcpy(epair->value, token.string);
+ } //end while
+ if (strcmp(token.string, "}"))
+ {
+ ScriptError(script, "missing }\n");
+ AAS_FreeBSPEntities();
+ FreeScript(script);
+ return;
+ } //end if
+ } //end while
+ FreeScript(script);
+} //end of the function AAS_ParseBSPEntities
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_BSPTraceLight(vec3_t start, vec3_t end, vec3_t endpos, int *red, int *green, int *blue)
+{
+ return 0;
+} //end of the function AAS_BSPTraceLight
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_DumpBSPData(void)
+{
+ AAS_FreeBSPEntities();
+
+ if (bspworld.dentdata) FreeMemory(bspworld.dentdata);
+ bspworld.dentdata = NULL;
+ bspworld.entdatasize = 0;
+ //
+ bspworld.loaded = qfalse;
+ Com_Memset( &bspworld, 0, sizeof(bspworld) );
+} //end of the function AAS_DumpBSPData
+//===========================================================================
+// load an bsp file
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_LoadBSPFile(void)
+{
+ AAS_DumpBSPData();
+ bspworld.entdatasize = strlen(botimport.BSPEntityData()) + 1;
+ bspworld.dentdata = (char *) GetClearedHunkMemory(bspworld.entdatasize);
+ Com_Memcpy(bspworld.dentdata, botimport.BSPEntityData(), bspworld.entdatasize);
+ AAS_ParseBSPEntities();
+ bspworld.loaded = qtrue;
+ return BLERR_NOERROR;
+} //end of the function AAS_LoadBSPFile
diff --git a/code/botlib/be_aas_cluster.c b/code/botlib/be_aas_cluster.c
new file mode 100755
index 0000000..2fd569b
--- /dev/null
+++ b/code/botlib/be_aas_cluster.c
@@ -0,0 +1,1545 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_cluster.c
+ *
+ * desc: area clustering
+ *
+ * $Archive: /MissionPack/code/botlib/be_aas_cluster.c $
+ *
+ *****************************************************************************/
+
+#include "../game/q_shared.h"
+#include "l_memory.h"
+#include "l_script.h"
+#include "l_precomp.h"
+#include "l_struct.h"
+#include "l_log.h"
+#include "l_memory.h"
+#include "l_libvar.h"
+#include "aasfile.h"
+#include "../game/botlib.h"
+#include "../game/be_aas.h"
+#include "be_aas_funcs.h"
+#include "be_aas_def.h"
+
+extern botlib_import_t botimport;
+
+#define AAS_MAX_PORTALS 65536
+#define AAS_MAX_PORTALINDEXSIZE 65536
+#define AAS_MAX_CLUSTERS 65536
+//
+#define MAX_PORTALAREAS 1024
+
+// do not flood through area faces, only use reachabilities
+int nofaceflood = qtrue;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_RemoveClusterAreas(void)
+{
+ int i;
+
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ aasworld.areasettings[i].cluster = 0;
+ } //end for
+} //end of the function AAS_RemoveClusterAreas
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ClearCluster(int clusternum)
+{
+ int i;
+
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ if (aasworld.areasettings[i].cluster == clusternum)
+ {
+ aasworld.areasettings[i].cluster = 0;
+ } //end if
+ } //end for
+} //end of the function AAS_ClearCluster
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_RemovePortalsClusterReference(int clusternum)
+{
+ int portalnum;
+
+ for (portalnum = 1; portalnum < aasworld.numportals; portalnum++)
+ {
+ if (aasworld.portals[portalnum].frontcluster == clusternum)
+ {
+ aasworld.portals[portalnum].frontcluster = 0;
+ } //end if
+ if (aasworld.portals[portalnum].backcluster == clusternum)
+ {
+ aasworld.portals[portalnum].backcluster = 0;
+ } //end if
+ } //end for
+} //end of the function AAS_RemovePortalsClusterReference
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_UpdatePortal(int areanum, int clusternum)
+{
+ int portalnum;
+ aas_portal_t *portal;
+ aas_cluster_t *cluster;
+
+ //find the portal of the area
+ for (portalnum = 1; portalnum < aasworld.numportals; portalnum++)
+ {
+ if (aasworld.portals[portalnum].areanum == areanum) break;
+ } //end for
+ //
+ if (portalnum == aasworld.numportals)
+ {
+ AAS_Error("no portal of area %d", areanum);
+ return qtrue;
+ } //end if
+ //
+ portal = &aasworld.portals[portalnum];
+ //if the portal is already fully updated
+ if (portal->frontcluster == clusternum) return qtrue;
+ if (portal->backcluster == clusternum) return qtrue;
+ //if the portal has no front cluster yet
+ if (!portal->frontcluster)
+ {
+ portal->frontcluster = clusternum;
+ } //end if
+ //if the portal has no back cluster yet
+ else if (!portal->backcluster)
+ {
+ portal->backcluster = clusternum;
+ } //end else if
+ else
+ {
+ //remove the cluster portal flag contents
+ aasworld.areasettings[areanum].contents &= ~AREACONTENTS_CLUSTERPORTAL;
+ Log_Write("portal area %d is seperating more than two clusters\r\n", areanum);
+ return qfalse;
+ } //end else
+ if (aasworld.portalindexsize >= AAS_MAX_PORTALINDEXSIZE)
+ {
+ AAS_Error("AAS_MAX_PORTALINDEXSIZE");
+ return qtrue;
+ } //end if
+ //set the area cluster number to the negative portal number
+ aasworld.areasettings[areanum].cluster = -portalnum;
+ //add the portal to the cluster using the portal index
+ cluster = &aasworld.clusters[clusternum];
+ aasworld.portalindex[cluster->firstportal + cluster->numportals] = portalnum;
+ aasworld.portalindexsize++;
+ cluster->numportals++;
+ return qtrue;
+} //end of the function AAS_UpdatePortal
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_FloodClusterAreas_r(int areanum, int clusternum)
+{
+ aas_area_t *area;
+ aas_face_t *face;
+ int facenum, i;
+
+ //
+ if (areanum <= 0 || areanum >= aasworld.numareas)
+ {
+ AAS_Error("AAS_FloodClusterAreas_r: areanum out of range");
+ return qfalse;
+ } //end if
+ //if the area is already part of a cluster
+ if (aasworld.areasettings[areanum].cluster > 0)
+ {
+ if (aasworld.areasettings[areanum].cluster == clusternum) return qtrue;
+ //
+ //there's a reachability going from one cluster to another only in one direction
+ //
+ AAS_Error("cluster %d touched cluster %d at area %d\r\n",
+ clusternum, aasworld.areasettings[areanum].cluster, areanum);
+ return qfalse;
+ } //end if
+ //don't add the cluster portal areas to the clusters
+ if (aasworld.areasettings[areanum].contents & AREACONTENTS_CLUSTERPORTAL)
+ {
+ return AAS_UpdatePortal(areanum, clusternum);
+ } //end if
+ //set the area cluster number
+ aasworld.areasettings[areanum].cluster = clusternum;
+ aasworld.areasettings[areanum].clusterareanum =
+ aasworld.clusters[clusternum].numareas;
+ //the cluster has an extra area
+ aasworld.clusters[clusternum].numareas++;
+
+ area = &aasworld.areas[areanum];
+ //use area faces to flood into adjacent areas
+ if (!nofaceflood)
+ {
+ for (i = 0; i < area->numfaces; i++)
+ {
+ facenum = abs(aasworld.faceindex[area->firstface + i]);
+ face = &aasworld.faces[facenum];
+ if (face->frontarea == areanum)
+ {
+ if (face->backarea) if (!AAS_FloodClusterAreas_r(face->backarea, clusternum)) return qfalse;
+ } //end if
+ else
+ {
+ if (face->frontarea) if (!AAS_FloodClusterAreas_r(face->frontarea, clusternum)) return qfalse;
+ } //end else
+ } //end for
+ } //end if
+ //use the reachabilities to flood into other areas
+ for (i = 0; i < aasworld.areasettings[areanum].numreachableareas; i++)
+ {
+ if (!aasworld.reachability[
+ aasworld.areasettings[areanum].firstreachablearea + i].areanum)
+ {
+ continue;
+ } //end if
+ if (!AAS_FloodClusterAreas_r(aasworld.reachability[
+ aasworld.areasettings[areanum].firstreachablearea + i].areanum, clusternum)) return qfalse;
+ } //end for
+ return qtrue;
+} //end of the function AAS_FloodClusterAreas_r
+//===========================================================================
+// try to flood from all areas without cluster into areas with a cluster set
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_FloodClusterAreasUsingReachabilities(int clusternum)
+{
+ int i, j, areanum;
+
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ //if this area already has a cluster set
+ if (aasworld.areasettings[i].cluster)
+ continue;
+ //if this area is a cluster portal
+ if (aasworld.areasettings[i].contents & AREACONTENTS_CLUSTERPORTAL)
+ continue;
+ //loop over the reachable areas from this area
+ for (j = 0; j < aasworld.areasettings[i].numreachableareas; j++)
+ {
+ //the reachable area
+ areanum = aasworld.reachability[aasworld.areasettings[i].firstreachablearea + j].areanum;
+ //if this area is a cluster portal
+ if (aasworld.areasettings[areanum].contents & AREACONTENTS_CLUSTERPORTAL)
+ continue;
+ //if this area has a cluster set
+ if (aasworld.areasettings[areanum].cluster)
+ {
+ if (!AAS_FloodClusterAreas_r(i, clusternum))
+ return qfalse;
+ i = 0;
+ break;
+ } //end if
+ } //end for
+ } //end for
+ return qtrue;
+} //end of the function AAS_FloodClusterAreasUsingReachabilities
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_NumberClusterPortals(int clusternum)
+{
+ int i, portalnum;
+ aas_cluster_t *cluster;
+ aas_portal_t *portal;
+
+ cluster = &aasworld.clusters[clusternum];
+ for (i = 0; i < cluster->numportals; i++)
+ {
+ portalnum = aasworld.portalindex[cluster->firstportal + i];
+ portal = &aasworld.portals[portalnum];
+ if (portal->frontcluster == clusternum)
+ {
+ portal->clusterareanum[0] = cluster->numareas++;
+ } //end if
+ else
+ {
+ portal->clusterareanum[1] = cluster->numareas++;
+ } //end else
+ } //end for
+} //end of the function AAS_NumberClusterPortals
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_NumberClusterAreas(int clusternum)
+{
+ int i, portalnum;
+ aas_cluster_t *cluster;
+ aas_portal_t *portal;
+
+ aasworld.clusters[clusternum].numareas = 0;
+ aasworld.clusters[clusternum].numreachabilityareas = 0;
+ //number all areas in this cluster WITH reachabilities
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ //
+ if (aasworld.areasettings[i].cluster != clusternum) continue;
+ //
+ if (!AAS_AreaReachability(i)) continue;
+ //
+ aasworld.areasettings[i].clusterareanum = aasworld.clusters[clusternum].numareas;
+ //the cluster has an extra area
+ aasworld.clusters[clusternum].numareas++;
+ aasworld.clusters[clusternum].numreachabilityareas++;
+ } //end for
+ //number all portals in this cluster WITH reachabilities
+ cluster = &aasworld.clusters[clusternum];
+ for (i = 0; i < cluster->numportals; i++)
+ {
+ portalnum = aasworld.portalindex[cluster->firstportal + i];
+ portal = &aasworld.portals[portalnum];
+ if (!AAS_AreaReachability(portal->areanum)) continue;
+ if (portal->frontcluster == clusternum)
+ {
+ portal->clusterareanum[0] = cluster->numareas++;
+ aasworld.clusters[clusternum].numreachabilityareas++;
+ } //end if
+ else
+ {
+ portal->clusterareanum[1] = cluster->numareas++;
+ aasworld.clusters[clusternum].numreachabilityareas++;
+ } //end else
+ } //end for
+ //number all areas in this cluster WITHOUT reachabilities
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ //
+ if (aasworld.areasettings[i].cluster != clusternum) continue;
+ //
+ if (AAS_AreaReachability(i)) continue;
+ //
+ aasworld.areasettings[i].clusterareanum = aasworld.clusters[clusternum].numareas;
+ //the cluster has an extra area
+ aasworld.clusters[clusternum].numareas++;
+ } //end for
+ //number all portals in this cluster WITHOUT reachabilities
+ cluster = &aasworld.clusters[clusternum];
+ for (i = 0; i < cluster->numportals; i++)
+ {
+ portalnum = aasworld.portalindex[cluster->firstportal + i];
+ portal = &aasworld.portals[portalnum];
+ if (AAS_AreaReachability(portal->areanum)) continue;
+ if (portal->frontcluster == clusternum)
+ {
+ portal->clusterareanum[0] = cluster->numareas++;
+ } //end if
+ else
+ {
+ portal->clusterareanum[1] = cluster->numareas++;
+ } //end else
+ } //end for
+} //end of the function AAS_NumberClusterAreas
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_FindClusters(void)
+{
+ int i;
+ aas_cluster_t *cluster;
+
+ AAS_RemoveClusterAreas();
+ //
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ //if the area is already part of a cluster
+ if (aasworld.areasettings[i].cluster)
+ continue;
+ // if not flooding through faces only use areas that have reachabilities
+ if (nofaceflood)
+ {
+ if (!aasworld.areasettings[i].numreachableareas)
+ continue;
+ } //end if
+ //if the area is a cluster portal
+ if (aasworld.areasettings[i].contents & AREACONTENTS_CLUSTERPORTAL)
+ continue;
+ if (aasworld.numclusters >= AAS_MAX_CLUSTERS)
+ {
+ AAS_Error("AAS_MAX_CLUSTERS");
+ return qfalse;
+ } //end if
+ cluster = &aasworld.clusters[aasworld.numclusters];
+ cluster->numareas = 0;
+ cluster->numreachabilityareas = 0;
+ cluster->firstportal = aasworld.portalindexsize;
+ cluster->numportals = 0;
+ //flood the areas in this cluster
+ if (!AAS_FloodClusterAreas_r(i, aasworld.numclusters))
+ return qfalse;
+ if (!AAS_FloodClusterAreasUsingReachabilities(aasworld.numclusters))
+ return qfalse;
+ //number the cluster areas
+ //AAS_NumberClusterPortals(aasworld.numclusters);
+ AAS_NumberClusterAreas(aasworld.numclusters);
+ //Log_Write("cluster %d has %d areas\r\n", aasworld.numclusters, cluster->numareas);
+ aasworld.numclusters++;
+ } //end for
+ return qtrue;
+} //end of the function AAS_FindClusters
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_CreatePortals(void)
+{
+ int i;
+ aas_portal_t *portal;
+
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ //if the area is a cluster portal
+ if (aasworld.areasettings[i].contents & AREACONTENTS_CLUSTERPORTAL)
+ {
+ if (aasworld.numportals >= AAS_MAX_PORTALS)
+ {
+ AAS_Error("AAS_MAX_PORTALS");
+ return;
+ } //end if
+ portal = &aasworld.portals[aasworld.numportals];
+ portal->areanum = i;
+ portal->frontcluster = 0;
+ portal->backcluster = 0;
+ aasworld.numportals++;
+ } //end if
+ } //end for
+} //end of the function AAS_CreatePortals
+/*
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_MapContainsTeleporters(void)
+{
+ bsp_entity_t *entities, *ent;
+ char *classname;
+
+ entities = AAS_ParseBSPEntities();
+
+ for (ent = entities; ent; ent = ent->next)
+ {
+ classname = AAS_ValueForBSPEpairKey(ent, "classname");
+ if (classname && !strcmp(classname, "misc_teleporter"))
+ {
+ AAS_FreeBSPEntities(entities);
+ return qtrue;
+ } //end if
+ } //end for
+ return qfalse;
+} //end of the function AAS_MapContainsTeleporters
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_NonConvexFaces(aas_face_t *face1, aas_face_t *face2, int side1, int side2)
+{
+ int i, j, edgenum;
+ aas_plane_t *plane1, *plane2;
+ aas_edge_t *edge;
+
+
+ plane1 = &aasworld.planes[face1->planenum ^ side1];
+ plane2 = &aasworld.planes[face2->planenum ^ side2];
+
+ //check if one of the points of face1 is at the back of the plane of face2
+ for (i = 0; i < face1->numedges; i++)
+ {
+ edgenum = abs(aasworld.edgeindex[face1->firstedge + i]);
+ edge = &aasworld.edges[edgenum];
+ for (j = 0; j < 2; j++)
+ {
+ if (DotProduct(plane2->normal, aasworld.vertexes[edge->v[j]]) -
+ plane2->dist < -0.01) return qtrue;
+ } //end for
+ } //end for
+ for (i = 0; i < face2->numedges; i++)
+ {
+ edgenum = abs(aasworld.edgeindex[face2->firstedge + i]);
+ edge = &aasworld.edges[edgenum];
+ for (j = 0; j < 2; j++)
+ {
+ if (DotProduct(plane1->normal, aasworld.vertexes[edge->v[j]]) -
+ plane1->dist < -0.01) return qtrue;
+ } //end for
+ } //end for
+
+ return qfalse;
+} //end of the function AAS_NonConvexFaces
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean AAS_CanMergeAreas(int *areanums, int numareas)
+{
+ int i, j, s, face1num, face2num, side1, side2, fn1, fn2;
+ aas_face_t *face1, *face2;
+ aas_area_t *area1, *area2;
+
+ for (i = 0; i < numareas; i++)
+ {
+ area1 = &aasworld.areas[areanums[i]];
+ for (fn1 = 0; fn1 < area1->numfaces; fn1++)
+ {
+ face1num = abs(aasworld.faceindex[area1->firstface + fn1]);
+ face1 = &aasworld.faces[face1num];
+ side1 = face1->frontarea != areanums[i];
+ //check if the face isn't a shared one with one of the other areas
+ for (s = 0; s < numareas; s++)
+ {
+ if (s == i) continue;
+ if (face1->frontarea == s || face1->backarea == s) break;
+ } //end for
+ //if the face was a shared one
+ if (s != numareas) continue;
+ //
+ for (j = 0; j < numareas; j++)
+ {
+ if (j == i) continue;
+ area2 = &aasworld.areas[areanums[j]];
+ for (fn2 = 0; fn2 < area2->numfaces; fn2++)
+ {
+ face2num = abs(aasworld.faceindex[area2->firstface + fn2]);
+ face2 = &aasworld.faces[face2num];
+ side2 = face2->frontarea != areanums[j];
+ //check if the face isn't a shared one with one of the other areas
+ for (s = 0; s < numareas; s++)
+ {
+ if (s == j) continue;
+ if (face2->frontarea == s || face2->backarea == s) break;
+ } //end for
+ //if the face was a shared one
+ if (s != numareas) continue;
+ //
+ if (AAS_NonConvexFaces(face1, face2, side1, side2)) return qfalse;
+ } //end for
+ } //end for
+ } //end for
+ } //end for
+ return qtrue;
+} //end of the function AAS_CanMergeAreas
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean AAS_NonConvexEdges(aas_edge_t *edge1, aas_edge_t *edge2, int side1, int side2, int planenum)
+{
+ int i;
+ vec3_t edgevec1, edgevec2, normal1, normal2;
+ float dist1, dist2;
+ aas_plane_t *plane;
+
+ plane = &aasworld.planes[planenum];
+ VectorSubtract(aasworld.vertexes[edge1->v[1]], aasworld.vertexes[edge1->v[0]], edgevec1);
+ VectorSubtract(aasworld.vertexes[edge2->v[1]], aasworld.vertexes[edge2->v[0]], edgevec2);
+ if (side1) VectorInverse(edgevec1);
+ if (side2) VectorInverse(edgevec2);
+ //
+ CrossProduct(edgevec1, plane->normal, normal1);
+ dist1 = DotProduct(normal1, aasworld.vertexes[edge1->v[0]]);
+ CrossProduct(edgevec2, plane->normal, normal2);
+ dist2 = DotProduct(normal2, aasworld.vertexes[edge2->v[0]]);
+
+ for (i = 0; i < 2; i++)
+ {
+ if (DotProduct(aasworld.vertexes[edge1->v[i]], normal2) - dist2 < -0.01) return qfalse;
+ } //end for
+ for (i = 0; i < 2; i++)
+ {
+ if (DotProduct(aasworld.vertexes[edge2->v[i]], normal1) - dist1 < -0.01) return qfalse;
+ } //end for
+ return qtrue;
+} //end of the function AAS_NonConvexEdges
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean AAS_CanMergeFaces(int *facenums, int numfaces, int planenum)
+{
+ int i, j, s, edgenum1, edgenum2, side1, side2, en1, en2, ens;
+ aas_face_t *face1, *face2, *otherface;
+ aas_edge_t *edge1, *edge2;
+
+ for (i = 0; i < numfaces; i++)
+ {
+ face1 = &aasworld.faces[facenums[i]];
+ for (en1 = 0; en1 < face1->numedges; en1++)
+ {
+ edgenum1 = aasworld.edgeindex[face1->firstedge + en1];
+ side1 = (edgenum1 < 0) ^ (face1->planenum != planenum);
+ edgenum1 = abs(edgenum1);
+ edge1 = &aasworld.edges[edgenum1];
+ //check if the edge is shared with another face
+ for (s = 0; s < numfaces; s++)
+ {
+ if (s == i) continue;
+ otherface = &aasworld.faces[facenums[s]];
+ for (ens = 0; ens < otherface->numedges; ens++)
+ {
+ if (edgenum1 == abs(aasworld.edgeindex[otherface->firstedge + ens])) break;
+ } //end for
+ if (ens != otherface->numedges) break;
+ } //end for
+ //if the edge was shared
+ if (s != numfaces) continue;
+ //
+ for (j = 0; j < numfaces; j++)
+ {
+ if (j == i) continue;
+ face2 = &aasworld.faces[facenums[j]];
+ for (en2 = 0; en2 < face2->numedges; en2++)
+ {
+ edgenum2 = aasworld.edgeindex[face2->firstedge + en2];
+ side2 = (edgenum2 < 0) ^ (face2->planenum != planenum);
+ edgenum2 = abs(edgenum2);
+ edge2 = &aasworld.edges[edgenum2];
+ //check if the edge is shared with another face
+ for (s = 0; s < numfaces; s++)
+ {
+ if (s == i) continue;
+ otherface = &aasworld.faces[facenums[s]];
+ for (ens = 0; ens < otherface->numedges; ens++)
+ {
+ if (edgenum2 == abs(aasworld.edgeindex[otherface->firstedge + ens])) break;
+ } //end for
+ if (ens != otherface->numedges) break;
+ } //end for
+ //if the edge was shared
+ if (s != numfaces) continue;
+ //
+ if (AAS_NonConvexEdges(edge1, edge2, side1, side2, planenum)) return qfalse;
+ } //end for
+ } //end for
+ } //end for
+ } //end for
+ return qtrue;
+} //end of the function AAS_CanMergeFaces*/
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ConnectedAreas_r(int *areanums, int numareas, int *connectedareas, int curarea)
+{
+ int i, j, otherareanum, facenum;
+ aas_area_t *area;
+ aas_face_t *face;
+
+ connectedareas[curarea] = qtrue;
+ area = &aasworld.areas[areanums[curarea]];
+ for (i = 0; i < area->numfaces; i++)
+ {
+ facenum = abs(aasworld.faceindex[area->firstface + i]);
+ face = &aasworld.faces[facenum];
+ //if the face is solid
+ if (face->faceflags & FACE_SOLID) continue;
+ //get the area at the other side of the face
+ if (face->frontarea != areanums[curarea]) otherareanum = face->frontarea;
+ else otherareanum = face->backarea;
+ //check if the face is leading to one of the other areas
+ for (j = 0; j < numareas; j++)
+ {
+ if (areanums[j] == otherareanum) break;
+ } //end for
+ //if the face isn't leading to one of the other areas
+ if (j == numareas) continue;
+ //if the other area is already connected
+ if (connectedareas[j]) continue;
+ //recursively proceed with the other area
+ AAS_ConnectedAreas_r(areanums, numareas, connectedareas, j);
+ } //end for
+} //end of the function AAS_ConnectedAreas_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean AAS_ConnectedAreas(int *areanums, int numareas)
+{
+ int connectedareas[MAX_PORTALAREAS], i;
+
+ Com_Memset(connectedareas, 0, sizeof(connectedareas));
+ if (numareas < 1) return qfalse;
+ if (numareas == 1) return qtrue;
+ AAS_ConnectedAreas_r(areanums, numareas, connectedareas, 0);
+ for (i = 0; i < numareas; i++)
+ {
+ if (!connectedareas[i]) return qfalse;
+ } //end for
+ return qtrue;
+} //end of the function AAS_ConnectedAreas
+//===========================================================================
+// gets adjacent areas with less presence types recursively
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_GetAdjacentAreasWithLessPresenceTypes_r(int *areanums, int numareas, int curareanum)
+{
+ int i, j, presencetype, otherpresencetype, otherareanum, facenum;
+ aas_area_t *area;
+ aas_face_t *face;
+
+ areanums[numareas++] = curareanum;
+ area = &aasworld.areas[curareanum];
+ presencetype = aasworld.areasettings[curareanum].presencetype;
+ for (i = 0; i < area->numfaces; i++)
+ {
+ facenum = abs(aasworld.faceindex[area->firstface + i]);
+ face = &aasworld.faces[facenum];
+ //if the face is solid
+ if (face->faceflags & FACE_SOLID) continue;
+ //the area at the other side of the face
+ if (face->frontarea != curareanum) otherareanum = face->frontarea;
+ else otherareanum = face->backarea;
+ //
+ otherpresencetype = aasworld.areasettings[otherareanum].presencetype;
+ //if the other area has less presence types
+ if ((presencetype & ~otherpresencetype) &&
+ !(otherpresencetype & ~presencetype))
+ {
+ //check if the other area isn't already in the list
+ for (j = 0; j < numareas; j++)
+ {
+ if (otherareanum == areanums[j]) break;
+ } //end for
+ //if the other area isn't already in the list
+ if (j == numareas)
+ {
+ if (numareas >= MAX_PORTALAREAS)
+ {
+ AAS_Error("MAX_PORTALAREAS");
+ return numareas;
+ } //end if
+ numareas = AAS_GetAdjacentAreasWithLessPresenceTypes_r(areanums, numareas, otherareanum);
+ } //end if
+ } //end if
+ } //end for
+ return numareas;
+} //end of the function AAS_GetAdjacentAreasWithLessPresenceTypes_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_CheckAreaForPossiblePortals(int areanum)
+{
+ int i, j, k, fen, ben, frontedgenum, backedgenum, facenum;
+ int areanums[MAX_PORTALAREAS], numareas, otherareanum;
+ int numareafrontfaces[MAX_PORTALAREAS], numareabackfaces[MAX_PORTALAREAS];
+ int frontfacenums[MAX_PORTALAREAS], backfacenums[MAX_PORTALAREAS];
+ int numfrontfaces, numbackfaces;
+ int frontareanums[MAX_PORTALAREAS], backareanums[MAX_PORTALAREAS];
+ int numfrontareas, numbackareas;
+ int frontplanenum, backplanenum, faceplanenum;
+ aas_area_t *area;
+ aas_face_t *frontface, *backface, *face;
+
+ //if it isn't already a portal
+ if (aasworld.areasettings[areanum].contents & AREACONTENTS_CLUSTERPORTAL) return 0;
+ //it must be a grounded area
+ if (!(aasworld.areasettings[areanum].areaflags & AREA_GROUNDED)) return 0;
+ //
+ Com_Memset(numareafrontfaces, 0, sizeof(numareafrontfaces));
+ Com_Memset(numareabackfaces, 0, sizeof(numareabackfaces));
+ numareas = numfrontfaces = numbackfaces = 0;
+ numfrontareas = numbackareas = 0;
+ frontplanenum = backplanenum = -1;
+ //add any adjacent areas with less presence types
+ numareas = AAS_GetAdjacentAreasWithLessPresenceTypes_r(areanums, 0, areanum);
+ //
+ for (i = 0; i < numareas; i++)
+ {
+ area = &aasworld.areas[areanums[i]];
+ for (j = 0; j < area->numfaces; j++)
+ {
+ facenum = abs(aasworld.faceindex[area->firstface + j]);
+ face = &aasworld.faces[facenum];
+ //if the face is solid
+ if (face->faceflags & FACE_SOLID) continue;
+ //check if the face is shared with one of the other areas
+ for (k = 0; k < numareas; k++)
+ {
+ if (k == i) continue;
+ if (face->frontarea == areanums[k] || face->backarea == areanums[k]) break;
+ } //end for
+ //if the face is shared
+ if (k != numareas) continue;
+ //the number of the area at the other side of the face
+ if (face->frontarea == areanums[i]) otherareanum = face->backarea;
+ else otherareanum = face->frontarea;
+ //if the other area already is a cluter portal
+ if (aasworld.areasettings[otherareanum].contents & AREACONTENTS_CLUSTERPORTAL) return 0;
+ //number of the plane of the area
+ faceplanenum = face->planenum & ~1;
+ //
+ if (frontplanenum < 0 || faceplanenum == frontplanenum)
+ {
+ frontplanenum = faceplanenum;
+ frontfacenums[numfrontfaces++] = facenum;
+ for (k = 0; k < numfrontareas; k++)
+ {
+ if (frontareanums[k] == otherareanum) break;
+ } //end for
+ if (k == numfrontareas) frontareanums[numfrontareas++] = otherareanum;
+ numareafrontfaces[i]++;
+ } //end if
+ else if (backplanenum < 0 || faceplanenum == backplanenum)
+ {
+ backplanenum = faceplanenum;
+ backfacenums[numbackfaces++] = facenum;
+ for (k = 0; k < numbackareas; k++)
+ {
+ if (backareanums[k] == otherareanum) break;
+ } //end for
+ if (k == numbackareas) backareanums[numbackareas++] = otherareanum;
+ numareabackfaces[i]++;
+ } //end else
+ else
+ {
+ return 0;
+ } //end else
+ } //end for
+ } //end for
+ //every area should have at least one front face and one back face
+ for (i = 0; i < numareas; i++)
+ {
+ if (!numareafrontfaces[i] || !numareabackfaces[i]) return 0;
+ } //end for
+ //the front areas should all be connected
+ if (!AAS_ConnectedAreas(frontareanums, numfrontareas)) return 0;
+ //the back areas should all be connected
+ if (!AAS_ConnectedAreas(backareanums, numbackareas)) return 0;
+ //none of the front faces should have a shared edge with a back face
+ for (i = 0; i < numfrontfaces; i++)
+ {
+ frontface = &aasworld.faces[frontfacenums[i]];
+ for (fen = 0; fen < frontface->numedges; fen++)
+ {
+ frontedgenum = abs(aasworld.edgeindex[frontface->firstedge + fen]);
+ for (j = 0; j < numbackfaces; j++)
+ {
+ backface = &aasworld.faces[backfacenums[j]];
+ for (ben = 0; ben < backface->numedges; ben++)
+ {
+ backedgenum = abs(aasworld.edgeindex[backface->firstedge + ben]);
+ if (frontedgenum == backedgenum) break;
+ } //end for
+ if (ben != backface->numedges) break;
+ } //end for
+ if (j != numbackfaces) break;
+ } //end for
+ if (fen != frontface->numedges) break;
+ } //end for
+ if (i != numfrontfaces) return 0;
+ //set the cluster portal contents
+ for (i = 0; i < numareas; i++)
+ {
+ aasworld.areasettings[areanums[i]].contents |= AREACONTENTS_CLUSTERPORTAL;
+ //this area can be used as a route portal
+ aasworld.areasettings[areanums[i]].contents |= AREACONTENTS_ROUTEPORTAL;
+ Log_Write("possible portal: %d\r\n", areanums[i]);
+ } //end for
+ //
+ return numareas;
+} //end of the function AAS_CheckAreaForPossiblePortals
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_FindPossiblePortals(void)
+{
+ int i, numpossibleportals;
+
+ numpossibleportals = 0;
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ numpossibleportals += AAS_CheckAreaForPossiblePortals(i);
+ } //end for
+ botimport.Print(PRT_MESSAGE, "\r%6d possible portal areas\n", numpossibleportals);
+} //end of the function AAS_FindPossiblePortals
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_RemoveAllPortals(void)
+{
+ int i;
+
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ aasworld.areasettings[i].contents &= ~AREACONTENTS_CLUSTERPORTAL;
+ } //end for
+} //end of the function AAS_RemoveAllPortals
+
+#if 0
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_FloodCluster_r(int areanum, int clusternum)
+{
+ int i, otherareanum;
+ aas_face_t *face;
+ aas_area_t *area;
+
+ //set cluster mark
+ aasworld.areasettings[areanum].cluster = clusternum;
+ //if the area is a portal
+ //if (aasworld.areasettings[areanum].contents & AREACONTENTS_CLUSTERPORTAL) return;
+ //
+ area = &aasworld.areas[areanum];
+ //use area faces to flood into adjacent areas
+ for (i = 0; i < area->numfaces; i++)
+ {
+ face = &aasworld.faces[abs(aasworld.faceindex[area->firstface + i])];
+ //
+ if (face->frontarea != areanum) otherareanum = face->frontarea;
+ else otherareanum = face->backarea;
+ //if there's no area at the other side
+ if (!otherareanum) continue;
+ //if the area is a portal
+ if (aasworld.areasettings[otherareanum].contents & AREACONTENTS_CLUSTERPORTAL) continue;
+ //if the area is already marked
+ if (aasworld.areasettings[otherareanum].cluster) continue;
+ //
+ AAS_FloodCluster_r(otherareanum, clusternum);
+ } //end for
+ //use the reachabilities to flood into other areas
+ for (i = 0; i < aasworld.areasettings[areanum].numreachableareas; i++)
+ {
+ otherareanum = aasworld.reachability[
+ aasworld.areasettings[areanum].firstreachablearea + i].areanum;
+ if (!otherareanum)
+ {
+ continue;
+ AAS_Error("reachability %d has zero area\n", aasworld.areasettings[areanum].firstreachablearea + i);
+ } //end if
+ //if the area is a portal
+ if (aasworld.areasettings[otherareanum].contents & AREACONTENTS_CLUSTERPORTAL) continue;
+ //if the area is already marked
+ if (aasworld.areasettings[otherareanum].cluster) continue;
+ //
+ AAS_FloodCluster_r(otherareanum, clusternum);
+ } //end for
+} //end of the function AAS_FloodCluster_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_RemoveTeleporterPortals(void)
+{
+ int i, j, areanum;
+
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ for (j = 0; j < aasworld.areasettings[i].numreachableareas; j++)
+ {
+ areanum = aasworld.reachability[aasworld.areasettings[i].firstreachablearea + j].areanum;
+ if (aasworld.reachability[aasworld.areasettings[i].firstreachablearea + j].traveltype == TRAVEL_TELEPORT)
+ {
+ aasworld.areasettings[i].contents &= ~AREACONTENTS_CLUSTERPORTAL;
+ aasworld.areasettings[areanum].contents &= ~AREACONTENTS_CLUSTERPORTAL;
+ break;
+ } //end if
+ } //end for
+ } //end for
+} //end of the function AAS_RemoveTeleporterPortals
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_FloodClusterReachabilities(int clusternum)
+{
+ int i, j, areanum;
+
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ //if this area already has a cluster set
+ if (aasworld.areasettings[i].cluster) continue;
+ //if this area is a cluster portal
+ if (aasworld.areasettings[i].contents & AREACONTENTS_CLUSTERPORTAL) continue;
+ //loop over the reachable areas from this area
+ for (j = 0; j < aasworld.areasettings[i].numreachableareas; j++)
+ {
+ //the reachable area
+ areanum = aasworld.reachability[aasworld.areasettings[i].firstreachablearea + j].areanum;
+ //if this area is a cluster portal
+ if (aasworld.areasettings[areanum].contents & AREACONTENTS_CLUSTERPORTAL) continue;
+ //if this area has a cluster set
+ if (aasworld.areasettings[areanum].cluster == clusternum)
+ {
+ AAS_FloodCluster_r(i, clusternum);
+ i = 0;
+ break;
+ } //end if
+ } //end for
+ } //end for
+} //end of the function AAS_FloodClusterReachabilities
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_RemoveNotClusterClosingPortals(void)
+{
+ int i, j, k, facenum, otherareanum, nonclosingportals;
+ aas_area_t *area;
+ aas_face_t *face;
+
+ AAS_RemoveTeleporterPortals();
+ //
+ nonclosingportals = 0;
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ if (!(aasworld.areasettings[i].contents & AREACONTENTS_CLUSTERPORTAL)) continue;
+ //find a non-portal area adjacent to the portal area and flood
+ //the cluster from there
+ area = &aasworld.areas[i];
+ for (j = 0; j < area->numfaces; j++)
+ {
+ facenum = abs(aasworld.faceindex[area->firstface + j]);
+ face = &aasworld.faces[facenum];
+ //
+ if (face->frontarea != i) otherareanum = face->frontarea;
+ else otherareanum = face->backarea;
+ //
+ if (!otherareanum) continue;
+ //
+ if (aasworld.areasettings[otherareanum].contents & AREACONTENTS_CLUSTERPORTAL)
+ {
+ continue;
+ } //end if
+ //reset all cluster fields
+ AAS_RemoveClusterAreas();
+ //
+ AAS_FloodCluster_r(otherareanum, 1);
+ AAS_FloodClusterReachabilities(1);
+ //check if all adjacent non-portal areas have a cluster set
+ for (k = 0; k < area->numfaces; k++)
+ {
+ facenum = abs(aasworld.faceindex[area->firstface + k]);
+ face = &aasworld.faces[facenum];
+ //
+ if (face->frontarea != i) otherareanum = face->frontarea;
+ else otherareanum = face->backarea;
+ //
+ if (!otherareanum) continue;
+ //
+ if (aasworld.areasettings[otherareanum].contents & AREACONTENTS_CLUSTERPORTAL)
+ {
+ continue;
+ } //end if
+ //
+ if (!aasworld.areasettings[otherareanum].cluster) break;
+ } //end for
+ //if all adjacent non-portal areas have a cluster set then the portal
+ //didn't seal a cluster
+ if (k >= area->numfaces)
+ {
+ aasworld.areasettings[i].contents &= ~AREACONTENTS_CLUSTERPORTAL;
+ nonclosingportals++;
+ //recheck all the other portals again
+ i = 0;
+ break;
+ } //end if
+ } //end for
+ } //end for
+ botimport.Print(PRT_MESSAGE, "\r%6d non closing portals removed\n", nonclosingportals);
+} //end of the function AAS_RemoveNotClusterClosingPortals
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+
+void AAS_RemoveNotClusterClosingPortals(void)
+{
+ int i, j, facenum, otherareanum, nonclosingportals, numseperatedclusters;
+ aas_area_t *area;
+ aas_face_t *face;
+
+ AAS_RemoveTeleporterPortals();
+ //
+ nonclosingportals = 0;
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ if (!(aasworld.areasettings[i].contents & AREACONTENTS_CLUSTERPORTAL)) continue;
+ //
+ numseperatedclusters = 0;
+ //reset all cluster fields
+ AAS_RemoveClusterAreas();
+ //find a non-portal area adjacent to the portal area and flood
+ //the cluster from there
+ area = &aasworld.areas[i];
+ for (j = 0; j < area->numfaces; j++)
+ {
+ facenum = abs(aasworld.faceindex[area->firstface + j]);
+ face = &aasworld.faces[facenum];
+ //
+ if (face->frontarea != i) otherareanum = face->frontarea;
+ else otherareanum = face->backarea;
+ //if not solid at the other side of the face
+ if (!otherareanum) continue;
+ //don't flood into other portals
+ if (aasworld.areasettings[otherareanum].contents & AREACONTENTS_CLUSTERPORTAL) continue;
+ //if the area already has a cluster set
+ if (aasworld.areasettings[otherareanum].cluster) continue;
+ //another cluster is seperated by this portal
+ numseperatedclusters++;
+ //flood the cluster
+ AAS_FloodCluster_r(otherareanum, numseperatedclusters);
+ AAS_FloodClusterReachabilities(numseperatedclusters);
+ } //end for
+ //use the reachabilities to flood into other areas
+ for (j = 0; j < aasworld.areasettings[i].numreachableareas; j++)
+ {
+ otherareanum = aasworld.reachability[
+ aasworld.areasettings[i].firstreachablearea + j].areanum;
+ //this should never be qtrue but we check anyway
+ if (!otherareanum) continue;
+ //don't flood into other portals
+ if (aasworld.areasettings[otherareanum].contents & AREACONTENTS_CLUSTERPORTAL) continue;
+ //if the area already has a cluster set
+ if (aasworld.areasettings[otherareanum].cluster) continue;
+ //another cluster is seperated by this portal
+ numseperatedclusters++;
+ //flood the cluster
+ AAS_FloodCluster_r(otherareanum, numseperatedclusters);
+ AAS_FloodClusterReachabilities(numseperatedclusters);
+ } //end for
+ //a portal must seperate no more and no less than 2 clusters
+ if (numseperatedclusters != 2)
+ {
+ aasworld.areasettings[i].contents &= ~AREACONTENTS_CLUSTERPORTAL;
+ nonclosingportals++;
+ //recheck all the other portals again
+ i = 0;
+ } //end if
+ } //end for
+ botimport.Print(PRT_MESSAGE, "\r%6d non closing portals removed\n", nonclosingportals);
+} //end of the function AAS_RemoveNotClusterClosingPortals
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+
+void AAS_AddTeleporterPortals(void)
+{
+ int j, area2num, facenum, otherareanum;
+ char *target, *targetname, *classname;
+ bsp_entity_t *entities, *ent, *dest;
+ vec3_t origin, destorigin, mins, maxs, end;
+ vec3_t bbmins, bbmaxs;
+ aas_area_t *area;
+ aas_face_t *face;
+ aas_trace_t trace;
+ aas_link_t *areas, *link;
+
+ entities = AAS_ParseBSPEntities();
+
+ for (ent = entities; ent; ent = ent->next)
+ {
+ classname = AAS_ValueForBSPEpairKey(ent, "classname");
+ if (classname && !strcmp(classname, "misc_teleporter"))
+ {
+ if (!AAS_VectorForBSPEpairKey(ent, "origin", origin))
+ {
+ botimport.Print(PRT_ERROR, "teleporter (%s) without origin\n", target);
+ continue;
+ } //end if
+ //
+ target = AAS_ValueForBSPEpairKey(ent, "target");
+ if (!target)
+ {
+ botimport.Print(PRT_ERROR, "teleporter (%s) without target\n", target);
+ continue;
+ } //end if
+ for (dest = entities; dest; dest = dest->next)
+ {
+ classname = AAS_ValueForBSPEpairKey(dest, "classname");
+ if (classname && !strcmp(classname, "misc_teleporter_dest"))
+ {
+ targetname = AAS_ValueForBSPEpairKey(dest, "targetname");
+ if (targetname && !strcmp(targetname, target))
+ {
+ break;
+ } //end if
+ } //end if
+ } //end for
+ if (!dest)
+ {
+ botimport.Print(PRT_ERROR, "teleporter without destination (%s)\n", target);
+ continue;
+ } //end if
+ if (!AAS_VectorForBSPEpairKey(dest, "origin", destorigin))
+ {
+ botimport.Print(PRT_ERROR, "teleporter destination (%s) without origin\n", target);
+ continue;
+ } //end if
+ destorigin[2] += 24; //just for q2e1m2, the dork has put the telepads in the ground
+ VectorCopy(destorigin, end);
+ end[2] -= 100;
+ trace = AAS_TraceClientBBox(destorigin, end, PRESENCE_CROUCH, -1);
+ if (trace.startsolid)
+ {
+ botimport.Print(PRT_ERROR, "teleporter destination (%s) in solid\n", target);
+ continue;
+ } //end if
+ VectorCopy(trace.endpos, destorigin);
+ area2num = AAS_PointAreaNum(destorigin);
+ //reset all cluster fields
+ for (j = 0; j < aasworld.numareas; j++)
+ {
+ aasworld.areasettings[j].cluster = 0;
+ } //end for
+ //
+ VectorSet(mins, -8, -8, 8);
+ VectorSet(maxs, 8, 8, 24);
+ //
+ AAS_PresenceTypeBoundingBox(PRESENCE_CROUCH, bbmins, bbmaxs);
+ //
+ VectorAdd(origin, mins, mins);
+ VectorAdd(origin, maxs, maxs);
+ //add bounding box size
+ VectorSubtract(mins, bbmaxs, mins);
+ VectorSubtract(maxs, bbmins, maxs);
+ //link an invalid (-1) entity
+ areas = AAS_AASLinkEntity(mins, maxs, -1);
+ //
+ for (link = areas; link; link = link->next_area)
+ {
+ if (!AAS_AreaGrounded(link->areanum)) continue;
+ //add the teleporter portal mark
+ aasworld.areasettings[link->areanum].contents |= AREACONTENTS_CLUSTERPORTAL |
+ AREACONTENTS_TELEPORTAL;
+ } //end for
+ //
+ for (link = areas; link; link = link->next_area)
+ {
+ if (!AAS_AreaGrounded(link->areanum)) continue;
+ //find a non-portal area adjacent to the portal area and flood
+ //the cluster from there
+ area = &aasworld.areas[link->areanum];
+ for (j = 0; j < area->numfaces; j++)
+ {
+ facenum = abs(aasworld.faceindex[area->firstface + j]);
+ face = &aasworld.faces[facenum];
+ //
+ if (face->frontarea != link->areanum) otherareanum = face->frontarea;
+ else otherareanum = face->backarea;
+ //
+ if (!otherareanum) continue;
+ //
+ if (aasworld.areasettings[otherareanum].contents & AREACONTENTS_CLUSTERPORTAL)
+ {
+ continue;
+ } //end if
+ //
+ AAS_FloodCluster_r(otherareanum, 1);
+ } //end for
+ } //end for
+ //if the teleport destination IS in the same cluster
+ if (aasworld.areasettings[area2num].cluster)
+ {
+ for (link = areas; link; link = link->next_area)
+ {
+ if (!AAS_AreaGrounded(link->areanum)) continue;
+ //add the teleporter portal mark
+ aasworld.areasettings[link->areanum].contents &= ~(AREACONTENTS_CLUSTERPORTAL |
+ AREACONTENTS_TELEPORTAL);
+ } //end for
+ } //end if
+ } //end if
+ } //end for
+ AAS_FreeBSPEntities(entities);
+} //end of the function AAS_AddTeleporterPortals
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_AddTeleporterPortals(void)
+{
+ int i, j, areanum;
+
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ for (j = 0; j < aasworld.areasettings[i].numreachableareas; j++)
+ {
+ if (aasworld.reachability[aasworld.areasettings[i].firstreachablearea + j].traveltype != TRAVEL_TELEPORT) continue;
+ areanum = aasworld.reachability[aasworld.areasettings[i].firstreachablearea + j].areanum;
+ aasworld.areasettings[areanum].contents |= AREACONTENTS_CLUSTERPORTAL;
+ } //end for
+ } //end for
+} //end of the function AAS_AddTeleporterPortals
+
+#endif
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_TestPortals(void)
+{
+ int i;
+ aas_portal_t *portal;
+
+ for (i = 1; i < aasworld.numportals; i++)
+ {
+ portal = &aasworld.portals[i];
+ if (!portal->frontcluster)
+ {
+ aasworld.areasettings[portal->areanum].contents &= ~AREACONTENTS_CLUSTERPORTAL;
+ Log_Write("portal area %d has no front cluster\r\n", portal->areanum);
+ return qfalse;
+ } //end if
+ if (!portal->backcluster)
+ {
+ aasworld.areasettings[portal->areanum].contents &= ~AREACONTENTS_CLUSTERPORTAL;
+ Log_Write("portal area %d has no back cluster\r\n", portal->areanum);
+ return qfalse;
+ } //end if
+ } //end for
+ return qtrue;
+} //end of the function
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_CountForcedClusterPortals(void)
+{
+ int num, i;
+
+ num = 0;
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ if (aasworld.areasettings[i].contents & AREACONTENTS_CLUSTERPORTAL)
+ {
+ Log_Write("area %d is a forced portal area\r\n", i);
+ num++;
+ } //end if
+ } //end for
+ botimport.Print(PRT_MESSAGE, "%6d forced portal areas\n", num);
+} //end of the function AAS_CountForcedClusterPortals
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_CreateViewPortals(void)
+{
+ int i;
+
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ if (aasworld.areasettings[i].contents & AREACONTENTS_CLUSTERPORTAL)
+ {
+ aasworld.areasettings[i].contents |= AREACONTENTS_VIEWPORTAL;
+ } //end if
+ } //end for
+} //end of the function AAS_CreateViewPortals
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_SetViewPortalsAsClusterPortals(void)
+{
+ int i;
+
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ if (aasworld.areasettings[i].contents & AREACONTENTS_VIEWPORTAL)
+ {
+ aasworld.areasettings[i].contents |= AREACONTENTS_CLUSTERPORTAL;
+ } //end if
+ } //end for
+} //end of the function AAS_SetViewPortalsAsClusterPortals
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_InitClustering(void)
+{
+ int i, removedPortalAreas;
+ int n, total, numreachabilityareas;
+
+ if (!aasworld.loaded) return;
+ //if there are clusters
+ if (aasworld.numclusters >= 1)
+ {
+#ifndef BSPC
+ //if clustering isn't forced
+ if (!((int)LibVarGetValue("forceclustering")) &&
+ !((int)LibVarGetValue("forcereachability"))) return;
+#endif
+ } //end if
+ //set all view portals as cluster portals in case we re-calculate the reachabilities and clusters (with -reach)
+ AAS_SetViewPortalsAsClusterPortals();
+ //count the number of forced cluster portals
+ AAS_CountForcedClusterPortals();
+ //remove all area cluster marks
+ AAS_RemoveClusterAreas();
+ //find possible cluster portals
+ AAS_FindPossiblePortals();
+ //craete portals to for the bot view
+ AAS_CreateViewPortals();
+ //remove all portals that are not closing a cluster
+ //AAS_RemoveNotClusterClosingPortals();
+ //initialize portal memory
+ if (aasworld.portals) FreeMemory(aasworld.portals);
+ aasworld.portals = (aas_portal_t *) GetClearedMemory(AAS_MAX_PORTALS * sizeof(aas_portal_t));
+ //initialize portal index memory
+ if (aasworld.portalindex) FreeMemory(aasworld.portalindex);
+ aasworld.portalindex = (aas_portalindex_t *) GetClearedMemory(AAS_MAX_PORTALINDEXSIZE * sizeof(aas_portalindex_t));
+ //initialize cluster memory
+ if (aasworld.clusters) FreeMemory(aasworld.clusters);
+ aasworld.clusters = (aas_cluster_t *) GetClearedMemory(AAS_MAX_CLUSTERS * sizeof(aas_cluster_t));
+ //
+ removedPortalAreas = 0;
+ botimport.Print(PRT_MESSAGE, "\r%6d removed portal areas", removedPortalAreas);
+ while(1)
+ {
+ botimport.Print(PRT_MESSAGE, "\r%6d", removedPortalAreas);
+ //initialize the number of portals and clusters
+ aasworld.numportals = 1; //portal 0 is a dummy
+ aasworld.portalindexsize = 0;
+ aasworld.numclusters = 1; //cluster 0 is a dummy
+ //create the portals from the portal areas
+ AAS_CreatePortals();
+ //
+ removedPortalAreas++;
+ //find the clusters
+ if (!AAS_FindClusters())
+ continue;
+ //test the portals
+ if (!AAS_TestPortals())
+ continue;
+ //
+ break;
+ } //end while
+ botimport.Print(PRT_MESSAGE, "\n");
+ //the AAS file should be saved
+ aasworld.savefile = qtrue;
+ //write the portal areas to the log file
+ for (i = 1; i < aasworld.numportals; i++)
+ {
+ Log_Write("portal %d: area %d\r\n", i, aasworld.portals[i].areanum);
+ } //end for
+ // report cluster info
+ botimport.Print(PRT_MESSAGE, "%6d portals created\n", aasworld.numportals);
+ botimport.Print(PRT_MESSAGE, "%6d clusters created\n", aasworld.numclusters);
+ for (i = 1; i < aasworld.numclusters; i++)
+ {
+ botimport.Print(PRT_MESSAGE, "cluster %d has %d reachability areas\n", i,
+ aasworld.clusters[i].numreachabilityareas);
+ } //end for
+ // report AAS file efficiency
+ numreachabilityareas = 0;
+ total = 0;
+ for (i = 0; i < aasworld.numclusters; i++) {
+ n = aasworld.clusters[i].numreachabilityareas;
+ numreachabilityareas += n;
+ total += n * n;
+ }
+ total += numreachabilityareas * aasworld.numportals;
+ //
+ botimport.Print(PRT_MESSAGE, "%6i total reachability areas\n", numreachabilityareas);
+ botimport.Print(PRT_MESSAGE, "%6i AAS memory/CPU usage (the lower the better)\n", total * 3);
+} //end of the function AAS_InitClustering
diff --git a/code/botlib/be_aas_cluster.h b/code/botlib/be_aas_cluster.h
new file mode 100755
index 0000000..3f52a46
--- /dev/null
+++ b/code/botlib/be_aas_cluster.h
@@ -0,0 +1,38 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_cluster.h
+ *
+ * desc: AAS
+ *
+ * $Archive: /source/code/botlib/be_aas_cluster.h $
+ *
+ *****************************************************************************/
+
+#ifdef AASINTERN
+//initialize the AAS clustering
+void AAS_InitClustering(void);
+//
+void AAS_SetViewPortalsAsClusterPortals(void);
+#endif //AASINTERN
+
diff --git a/code/botlib/be_aas_debug.c b/code/botlib/be_aas_debug.c
new file mode 100755
index 0000000..6271677
--- /dev/null
+++ b/code/botlib/be_aas_debug.c
@@ -0,0 +1,777 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_debug.c
+ *
+ * desc: AAS debug code
+ *
+ * $Archive: /MissionPack/code/botlib/be_aas_debug.c $
+ *
+ *****************************************************************************/
+
+#include "../game/q_shared.h"
+#include "l_memory.h"
+#include "l_script.h"
+#include "l_precomp.h"
+#include "l_struct.h"
+#include "l_libvar.h"
+#include "aasfile.h"
+#include "../game/botlib.h"
+#include "../game/be_aas.h"
+#include "be_interface.h"
+#include "be_aas_funcs.h"
+#include "be_aas_def.h"
+
+#define MAX_DEBUGLINES 1024
+#define MAX_DEBUGPOLYGONS 8192
+
+int debuglines[MAX_DEBUGLINES];
+int debuglinevisible[MAX_DEBUGLINES];
+int numdebuglines;
+
+static int debugpolygons[MAX_DEBUGPOLYGONS];
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ClearShownPolygons(void)
+{
+ int i;
+//*
+ for (i = 0; i < MAX_DEBUGPOLYGONS; i++)
+ {
+ if (debugpolygons[i]) botimport.DebugPolygonDelete(debugpolygons[i]);
+ debugpolygons[i] = 0;
+ } //end for
+//*/
+/*
+ for (i = 0; i < MAX_DEBUGPOLYGONS; i++)
+ {
+ botimport.DebugPolygonDelete(i);
+ debugpolygons[i] = 0;
+ } //end for
+*/
+} //end of the function AAS_ClearShownPolygons
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ShowPolygon(int color, int numpoints, vec3_t *points)
+{
+ int i;
+
+ for (i = 0; i < MAX_DEBUGPOLYGONS; i++)
+ {
+ if (!debugpolygons[i])
+ {
+ debugpolygons[i] = botimport.DebugPolygonCreate(color, numpoints, points);
+ break;
+ } //end if
+ } //end for
+} //end of the function AAS_ShowPolygon
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ClearShownDebugLines(void)
+{
+ int i;
+
+ //make all lines invisible
+ for (i = 0; i < MAX_DEBUGLINES; i++)
+ {
+ if (debuglines[i])
+ {
+ //botimport.DebugLineShow(debuglines[i], NULL, NULL, LINECOLOR_NONE);
+ botimport.DebugLineDelete(debuglines[i]);
+ debuglines[i] = 0;
+ debuglinevisible[i] = qfalse;
+ } //end if
+ } //end for
+} //end of the function AAS_ClearShownDebugLines
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_DebugLine(vec3_t start, vec3_t end, int color)
+{
+ int line;
+
+ for (line = 0; line < MAX_DEBUGLINES; line++)
+ {
+ if (!debuglines[line])
+ {
+ debuglines[line] = botimport.DebugLineCreate();
+ debuglinevisible[line] = qfalse;
+ numdebuglines++;
+ } //end if
+ if (!debuglinevisible[line])
+ {
+ botimport.DebugLineShow(debuglines[line], start, end, color);
+ debuglinevisible[line] = qtrue;
+ return;
+ } //end else
+ } //end for
+} //end of the function AAS_DebugLine
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_PermanentLine(vec3_t start, vec3_t end, int color)
+{
+ int line;
+
+ line = botimport.DebugLineCreate();
+ botimport.DebugLineShow(line, start, end, color);
+} //end of the function AAS_PermenentLine
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_DrawPermanentCross(vec3_t origin, float size, int color)
+{
+ int i, debugline;
+ vec3_t start, end;
+
+ for (i = 0; i < 3; i++)
+ {
+ VectorCopy(origin, start);
+ start[i] += size;
+ VectorCopy(origin, end);
+ end[i] -= size;
+ AAS_DebugLine(start, end, color);
+ debugline = botimport.DebugLineCreate();
+ botimport.DebugLineShow(debugline, start, end, color);
+ } //end for
+} //end of the function AAS_DrawPermanentCross
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_DrawPlaneCross(vec3_t point, vec3_t normal, float dist, int type, int color)
+{
+ int n0, n1, n2, j, line, lines[2];
+ vec3_t start1, end1, start2, end2;
+
+ //make a cross in the hit plane at the hit point
+ VectorCopy(point, start1);
+ VectorCopy(point, end1);
+ VectorCopy(point, start2);
+ VectorCopy(point, end2);
+
+ n0 = type % 3;
+ n1 = (type + 1) % 3;
+ n2 = (type + 2) % 3;
+ start1[n1] -= 6;
+ start1[n2] -= 6;
+ end1[n1] += 6;
+ end1[n2] += 6;
+ start2[n1] += 6;
+ start2[n2] -= 6;
+ end2[n1] -= 6;
+ end2[n2] += 6;
+
+ start1[n0] = (dist - (start1[n1] * normal[n1] +
+ start1[n2] * normal[n2])) / normal[n0];
+ end1[n0] = (dist - (end1[n1] * normal[n1] +
+ end1[n2] * normal[n2])) / normal[n0];
+ start2[n0] = (dist - (start2[n1] * normal[n1] +
+ start2[n2] * normal[n2])) / normal[n0];
+ end2[n0] = (dist - (end2[n1] * normal[n1] +
+ end2[n2] * normal[n2])) / normal[n0];
+
+ for (j = 0, line = 0; j < 2 && line < MAX_DEBUGLINES; line++)
+ {
+ if (!debuglines[line])
+ {
+ debuglines[line] = botimport.DebugLineCreate();
+ lines[j++] = debuglines[line];
+ debuglinevisible[line] = qtrue;
+ numdebuglines++;
+ } //end if
+ else if (!debuglinevisible[line])
+ {
+ lines[j++] = debuglines[line];
+ debuglinevisible[line] = qtrue;
+ } //end else
+ } //end for
+ botimport.DebugLineShow(lines[0], start1, end1, color);
+ botimport.DebugLineShow(lines[1], start2, end2, color);
+} //end of the function AAS_DrawPlaneCross
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ShowBoundingBox(vec3_t origin, vec3_t mins, vec3_t maxs)
+{
+ vec3_t bboxcorners[8];
+ int lines[3];
+ int i, j, line;
+
+ //upper corners
+ bboxcorners[0][0] = origin[0] + maxs[0];
+ bboxcorners[0][1] = origin[1] + maxs[1];
+ bboxcorners[0][2] = origin[2] + maxs[2];
+ //
+ bboxcorners[1][0] = origin[0] + mins[0];
+ bboxcorners[1][1] = origin[1] + maxs[1];
+ bboxcorners[1][2] = origin[2] + maxs[2];
+ //
+ bboxcorners[2][0] = origin[0] + mins[0];
+ bboxcorners[2][1] = origin[1] + mins[1];
+ bboxcorners[2][2] = origin[2] + maxs[2];
+ //
+ bboxcorners[3][0] = origin[0] + maxs[0];
+ bboxcorners[3][1] = origin[1] + mins[1];
+ bboxcorners[3][2] = origin[2] + maxs[2];
+ //lower corners
+ Com_Memcpy(bboxcorners[4], bboxcorners[0], sizeof(vec3_t) * 4);
+ for (i = 0; i < 4; i++) bboxcorners[4 + i][2] = origin[2] + mins[2];
+ //draw bounding box
+ for (i = 0; i < 4; i++)
+ {
+ for (j = 0, line = 0; j < 3 && line < MAX_DEBUGLINES; line++)
+ {
+ if (!debuglines[line])
+ {
+ debuglines[line] = botimport.DebugLineCreate();
+ lines[j++] = debuglines[line];
+ debuglinevisible[line] = qtrue;
+ numdebuglines++;
+ } //end if
+ else if (!debuglinevisible[line])
+ {
+ lines[j++] = debuglines[line];
+ debuglinevisible[line] = qtrue;
+ } //end else
+ } //end for
+ //top plane
+ botimport.DebugLineShow(lines[0], bboxcorners[i],
+ bboxcorners[(i+1)&3], LINECOLOR_RED);
+ //bottom plane
+ botimport.DebugLineShow(lines[1], bboxcorners[4+i],
+ bboxcorners[4+((i+1)&3)], LINECOLOR_RED);
+ //vertical lines
+ botimport.DebugLineShow(lines[2], bboxcorners[i],
+ bboxcorners[4+i], LINECOLOR_RED);
+ } //end for
+} //end of the function AAS_ShowBoundingBox
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ShowFace(int facenum)
+{
+ int i, color, edgenum;
+ aas_edge_t *edge;
+ aas_face_t *face;
+ aas_plane_t *plane;
+ vec3_t start, end;
+
+ color = LINECOLOR_YELLOW;
+ //check if face number is in range
+ if (facenum >= aasworld.numfaces)
+ {
+ botimport.Print(PRT_ERROR, "facenum %d out of range\n", facenum);
+ } //end if
+ face = &aasworld.faces[facenum];
+ //walk through the edges of the face
+ for (i = 0; i < face->numedges; i++)
+ {
+ //edge number
+ edgenum = abs(aasworld.edgeindex[face->firstedge + i]);
+ //check if edge number is in range
+ if (edgenum >= aasworld.numedges)
+ {
+ botimport.Print(PRT_ERROR, "edgenum %d out of range\n", edgenum);
+ } //end if
+ edge = &aasworld.edges[edgenum];
+ if (color == LINECOLOR_RED) color = LINECOLOR_GREEN;
+ else if (color == LINECOLOR_GREEN) color = LINECOLOR_BLUE;
+ else if (color == LINECOLOR_BLUE) color = LINECOLOR_YELLOW;
+ else color = LINECOLOR_RED;
+ AAS_DebugLine(aasworld.vertexes[edge->v[0]],
+ aasworld.vertexes[edge->v[1]],
+ color);
+ } //end for
+ plane = &aasworld.planes[face->planenum];
+ edgenum = abs(aasworld.edgeindex[face->firstedge]);
+ edge = &aasworld.edges[edgenum];
+ VectorCopy(aasworld.vertexes[edge->v[0]], start);
+ VectorMA(start, 20, plane->normal, end);
+ AAS_DebugLine(start, end, LINECOLOR_RED);
+} //end of the function AAS_ShowFace
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ShowFacePolygon(int facenum, int color, int flip)
+{
+ int i, edgenum, numpoints;
+ vec3_t points[128];
+ aas_edge_t *edge;
+ aas_face_t *face;
+
+ //check if face number is in range
+ if (facenum >= aasworld.numfaces)
+ {
+ botimport.Print(PRT_ERROR, "facenum %d out of range\n", facenum);
+ } //end if
+ face = &aasworld.faces[facenum];
+ //walk through the edges of the face
+ numpoints = 0;
+ if (flip)
+ {
+ for (i = face->numedges-1; i >= 0; i--)
+ {
+ //edge number
+ edgenum = aasworld.edgeindex[face->firstedge + i];
+ edge = &aasworld.edges[abs(edgenum)];
+ VectorCopy(aasworld.vertexes[edge->v[edgenum < 0]], points[numpoints]);
+ numpoints++;
+ } //end for
+ } //end if
+ else
+ {
+ for (i = 0; i < face->numedges; i++)
+ {
+ //edge number
+ edgenum = aasworld.edgeindex[face->firstedge + i];
+ edge = &aasworld.edges[abs(edgenum)];
+ VectorCopy(aasworld.vertexes[edge->v[edgenum < 0]], points[numpoints]);
+ numpoints++;
+ } //end for
+ } //end else
+ AAS_ShowPolygon(color, numpoints, points);
+} //end of the function AAS_ShowFacePolygon
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ShowArea(int areanum, int groundfacesonly)
+{
+ int areaedges[MAX_DEBUGLINES];
+ int numareaedges, i, j, n, color = 0, line;
+ int facenum, edgenum;
+ aas_area_t *area;
+ aas_face_t *face;
+ aas_edge_t *edge;
+
+ //
+ numareaedges = 0;
+ //
+ if (areanum < 0 || areanum >= aasworld.numareas)
+ {
+ botimport.Print(PRT_ERROR, "area %d out of range [0, %d]\n",
+ areanum, aasworld.numareas);
+ return;
+ } //end if
+ //pointer to the convex area
+ area = &aasworld.areas[areanum];
+ //walk through the faces of the area
+ for (i = 0; i < area->numfaces; i++)
+ {
+ facenum = abs(aasworld.faceindex[area->firstface + i]);
+ //check if face number is in range
+ if (facenum >= aasworld.numfaces)
+ {
+ botimport.Print(PRT_ERROR, "facenum %d out of range\n", facenum);
+ } //end if
+ face = &aasworld.faces[facenum];
+ //ground faces only
+ if (groundfacesonly)
+ {
+ if (!(face->faceflags & (FACE_GROUND | FACE_LADDER))) continue;
+ } //end if
+ //walk through the edges of the face
+ for (j = 0; j < face->numedges; j++)
+ {
+ //edge number
+ edgenum = abs(aasworld.edgeindex[face->firstedge + j]);
+ //check if edge number is in range
+ if (edgenum >= aasworld.numedges)
+ {
+ botimport.Print(PRT_ERROR, "edgenum %d out of range\n", edgenum);
+ } //end if
+ //check if the edge is stored already
+ for (n = 0; n < numareaedges; n++)
+ {
+ if (areaedges[n] == edgenum) break;
+ } //end for
+ if (n == numareaedges && numareaedges < MAX_DEBUGLINES)
+ {
+ areaedges[numareaedges++] = edgenum;
+ } //end if
+ } //end for
+ //AAS_ShowFace(facenum);
+ } //end for
+ //draw all the edges
+ for (n = 0; n < numareaedges; n++)
+ {
+ for (line = 0; line < MAX_DEBUGLINES; line++)
+ {
+ if (!debuglines[line])
+ {
+ debuglines[line] = botimport.DebugLineCreate();
+ debuglinevisible[line] = qfalse;
+ numdebuglines++;
+ } //end if
+ if (!debuglinevisible[line])
+ {
+ break;
+ } //end else
+ } //end for
+ if (line >= MAX_DEBUGLINES) return;
+ edge = &aasworld.edges[areaedges[n]];
+ if (color == LINECOLOR_RED) color = LINECOLOR_BLUE;
+ else if (color == LINECOLOR_BLUE) color = LINECOLOR_GREEN;
+ else if (color == LINECOLOR_GREEN) color = LINECOLOR_YELLOW;
+ else color = LINECOLOR_RED;
+ botimport.DebugLineShow(debuglines[line],
+ aasworld.vertexes[edge->v[0]],
+ aasworld.vertexes[edge->v[1]],
+ color);
+ debuglinevisible[line] = qtrue;
+ } //end for*/
+} //end of the function AAS_ShowArea
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ShowAreaPolygons(int areanum, int color, int groundfacesonly)
+{
+ int i, facenum;
+ aas_area_t *area;
+ aas_face_t *face;
+
+ //
+ if (areanum < 0 || areanum >= aasworld.numareas)
+ {
+ botimport.Print(PRT_ERROR, "area %d out of range [0, %d]\n",
+ areanum, aasworld.numareas);
+ return;
+ } //end if
+ //pointer to the convex area
+ area = &aasworld.areas[areanum];
+ //walk through the faces of the area
+ for (i = 0; i < area->numfaces; i++)
+ {
+ facenum = abs(aasworld.faceindex[area->firstface + i]);
+ //check if face number is in range
+ if (facenum >= aasworld.numfaces)
+ {
+ botimport.Print(PRT_ERROR, "facenum %d out of range\n", facenum);
+ } //end if
+ face = &aasworld.faces[facenum];
+ //ground faces only
+ if (groundfacesonly)
+ {
+ if (!(face->faceflags & (FACE_GROUND | FACE_LADDER))) continue;
+ } //end if
+ AAS_ShowFacePolygon(facenum, color, face->frontarea != areanum);
+ } //end for
+} //end of the function AAS_ShowAreaPolygons
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_DrawCross(vec3_t origin, float size, int color)
+{
+ int i;
+ vec3_t start, end;
+
+ for (i = 0; i < 3; i++)
+ {
+ VectorCopy(origin, start);
+ start[i] += size;
+ VectorCopy(origin, end);
+ end[i] -= size;
+ AAS_DebugLine(start, end, color);
+ } //end for
+} //end of the function AAS_DrawCross
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_PrintTravelType(int traveltype)
+{
+#ifdef DEBUG
+ char *str;
+ //
+ switch(traveltype & TRAVELTYPE_MASK)
+ {
+ case TRAVEL_INVALID: str = "TRAVEL_INVALID"; break;
+ case TRAVEL_WALK: str = "TRAVEL_WALK"; break;
+ case TRAVEL_CROUCH: str = "TRAVEL_CROUCH"; break;
+ case TRAVEL_BARRIERJUMP: str = "TRAVEL_BARRIERJUMP"; break;
+ case TRAVEL_JUMP: str = "TRAVEL_JUMP"; break;
+ case TRAVEL_LADDER: str = "TRAVEL_LADDER"; break;
+ case TRAVEL_WALKOFFLEDGE: str = "TRAVEL_WALKOFFLEDGE"; break;
+ case TRAVEL_SWIM: str = "TRAVEL_SWIM"; break;
+ case TRAVEL_WATERJUMP: str = "TRAVEL_WATERJUMP"; break;
+ case TRAVEL_TELEPORT: str = "TRAVEL_TELEPORT"; break;
+ case TRAVEL_ELEVATOR: str = "TRAVEL_ELEVATOR"; break;
+ case TRAVEL_ROCKETJUMP: str = "TRAVEL_ROCKETJUMP"; break;
+ case TRAVEL_BFGJUMP: str = "TRAVEL_BFGJUMP"; break;
+ case TRAVEL_GRAPPLEHOOK: str = "TRAVEL_GRAPPLEHOOK"; break;
+ case TRAVEL_JUMPPAD: str = "TRAVEL_JUMPPAD"; break;
+ case TRAVEL_FUNCBOB: str = "TRAVEL_FUNCBOB"; break;
+ default: str = "UNKNOWN TRAVEL TYPE"; break;
+ } //end switch
+ botimport.Print(PRT_MESSAGE, "%s", str);
+#endif
+} //end of the function AAS_PrintTravelType
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_DrawArrow(vec3_t start, vec3_t end, int linecolor, int arrowcolor)
+{
+ vec3_t dir, cross, p1, p2, up = {0, 0, 1};
+ float dot;
+
+ VectorSubtract(end, start, dir);
+ VectorNormalize(dir);
+ dot = DotProduct(dir, up);
+ if (dot > 0.99 || dot < -0.99) VectorSet(cross, 1, 0, 0);
+ else CrossProduct(dir, up, cross);
+
+ VectorMA(end, -6, dir, p1);
+ VectorCopy(p1, p2);
+ VectorMA(p1, 6, cross, p1);
+ VectorMA(p2, -6, cross, p2);
+
+ AAS_DebugLine(start, end, linecolor);
+ AAS_DebugLine(p1, end, arrowcolor);
+ AAS_DebugLine(p2, end, arrowcolor);
+} //end of the function AAS_DrawArrow
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ShowReachability(aas_reachability_t *reach)
+{
+ vec3_t dir, cmdmove, velocity;
+ float speed, zvel;
+ aas_clientmove_t move;
+
+ AAS_ShowAreaPolygons(reach->areanum, 5, qtrue);
+ //AAS_ShowArea(reach->areanum, qtrue);
+ AAS_DrawArrow(reach->start, reach->end, LINECOLOR_BLUE, LINECOLOR_YELLOW);
+ //
+ if ((reach->traveltype & TRAVELTYPE_MASK) == TRAVEL_JUMP ||
+ (reach->traveltype & TRAVELTYPE_MASK) == TRAVEL_WALKOFFLEDGE)
+ {
+ AAS_HorizontalVelocityForJump(aassettings.phys_jumpvel, reach->start, reach->end, &speed);
+ //
+ VectorSubtract(reach->end, reach->start, dir);
+ dir[2] = 0;
+ VectorNormalize(dir);
+ //set the velocity
+ VectorScale(dir, speed, velocity);
+ //set the command movement
+ VectorClear(cmdmove);
+ cmdmove[2] = aassettings.phys_jumpvel;
+ //
+ AAS_PredictClientMovement(&move, -1, reach->start, PRESENCE_NORMAL, qtrue,
+ velocity, cmdmove, 3, 30, 0.1f,
+ SE_HITGROUND|SE_ENTERWATER|SE_ENTERSLIME|
+ SE_ENTERLAVA|SE_HITGROUNDDAMAGE, 0, qtrue);
+ //
+ if ((reach->traveltype & TRAVELTYPE_MASK) == TRAVEL_JUMP)
+ {
+ AAS_JumpReachRunStart(reach, dir);
+ AAS_DrawCross(dir, 4, LINECOLOR_BLUE);
+ } //end if
+ } //end if
+ else if ((reach->traveltype & TRAVELTYPE_MASK) == TRAVEL_ROCKETJUMP)
+ {
+ zvel = AAS_RocketJumpZVelocity(reach->start);
+ AAS_HorizontalVelocityForJump(zvel, reach->start, reach->end, &speed);
+ //
+ VectorSubtract(reach->end, reach->start, dir);
+ dir[2] = 0;
+ VectorNormalize(dir);
+ //get command movement
+ VectorScale(dir, speed, cmdmove);
+ VectorSet(velocity, 0, 0, zvel);
+ //
+ AAS_PredictClientMovement(&move, -1, reach->start, PRESENCE_NORMAL, qtrue,
+ velocity, cmdmove, 30, 30, 0.1f,
+ SE_ENTERWATER|SE_ENTERSLIME|
+ SE_ENTERLAVA|SE_HITGROUNDDAMAGE|
+ SE_TOUCHJUMPPAD|SE_HITGROUNDAREA, reach->areanum, qtrue);
+ } //end else if
+ else if ((reach->traveltype & TRAVELTYPE_MASK) == TRAVEL_JUMPPAD)
+ {
+ VectorSet(cmdmove, 0, 0, 0);
+ //
+ VectorSubtract(reach->end, reach->start, dir);
+ dir[2] = 0;
+ VectorNormalize(dir);
+ //set the velocity
+ //NOTE: the edgenum is the horizontal velocity
+ VectorScale(dir, reach->edgenum, velocity);
+ //NOTE: the facenum is the Z velocity
+ velocity[2] = reach->facenum;
+ //
+ AAS_PredictClientMovement(&move, -1, reach->start, PRESENCE_NORMAL, qtrue,
+ velocity, cmdmove, 30, 30, 0.1f,
+ SE_ENTERWATER|SE_ENTERSLIME|
+ SE_ENTERLAVA|SE_HITGROUNDDAMAGE|
+ SE_TOUCHJUMPPAD|SE_HITGROUNDAREA, reach->areanum, qtrue);
+ } //end else if
+} //end of the function AAS_ShowReachability
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ShowReachableAreas(int areanum)
+{
+ aas_areasettings_t *settings;
+ static aas_reachability_t reach;
+ static int index, lastareanum;
+ static float lasttime;
+
+ if (areanum != lastareanum)
+ {
+ index = 0;
+ lastareanum = areanum;
+ } //end if
+ settings = &aasworld.areasettings[areanum];
+ //
+ if (!settings->numreachableareas) return;
+ //
+ if (index >= settings->numreachableareas) index = 0;
+ //
+ if (AAS_Time() - lasttime > 1.5)
+ {
+ Com_Memcpy(&reach, &aasworld.reachability[settings->firstreachablearea + index], sizeof(aas_reachability_t));
+ index++;
+ lasttime = AAS_Time();
+ AAS_PrintTravelType(reach.traveltype & TRAVELTYPE_MASK);
+ botimport.Print(PRT_MESSAGE, "\n");
+ } //end if
+ AAS_ShowReachability(&reach);
+} //end of the function ShowReachableAreas
+
+void AAS_FloodAreas_r(int areanum, int cluster, int *done)
+{
+ int nextareanum, i, facenum;
+ aas_area_t *area;
+ aas_face_t *face;
+ aas_areasettings_t *settings;
+ aas_reachability_t *reach;
+
+ AAS_ShowAreaPolygons(areanum, 1, qtrue);
+ //pointer to the convex area
+ area = &aasworld.areas[areanum];
+ settings = &aasworld.areasettings[areanum];
+ //walk through the faces of the area
+ for (i = 0; i < area->numfaces; i++)
+ {
+ facenum = abs(aasworld.faceindex[area->firstface + i]);
+ face = &aasworld.faces[facenum];
+ if (face->frontarea == areanum)
+ nextareanum = face->backarea;
+ else
+ nextareanum = face->frontarea;
+ if (!nextareanum)
+ continue;
+ if (done[nextareanum])
+ continue;
+ done[nextareanum] = qtrue;
+ if (aasworld.areasettings[nextareanum].contents & AREACONTENTS_VIEWPORTAL)
+ continue;
+ if (AAS_AreaCluster(nextareanum) != cluster)
+ continue;
+ AAS_FloodAreas_r(nextareanum, cluster, done);
+ } //end for
+ //
+ for (i = 0; i < settings->numreachableareas; i++)
+ {
+ reach = &aasworld.reachability[settings->firstreachablearea + i];
+ nextareanum = reach->areanum;
+ if (!nextareanum)
+ continue;
+ if (done[nextareanum])
+ continue;
+ done[nextareanum] = qtrue;
+ if (aasworld.areasettings[nextareanum].contents & AREACONTENTS_VIEWPORTAL)
+ continue;
+ if (AAS_AreaCluster(nextareanum) != cluster)
+ continue;
+ /*
+ if ((reach->traveltype & TRAVELTYPE_MASK) == TRAVEL_WALKOFFLEDGE)
+ {
+ AAS_DebugLine(reach->start, reach->end, 1);
+ }
+ */
+ AAS_FloodAreas_r(nextareanum, cluster, done);
+ }
+}
+
+void AAS_FloodAreas(vec3_t origin)
+{
+ int areanum, cluster, *done;
+
+ done = (int *) GetClearedMemory(aasworld.numareas * sizeof(int));
+ areanum = AAS_PointAreaNum(origin);
+ cluster = AAS_AreaCluster(areanum);
+ AAS_FloodAreas_r(areanum, cluster, done);
+}
diff --git a/code/botlib/be_aas_debug.h b/code/botlib/be_aas_debug.h
new file mode 100755
index 0000000..f0147c1
--- /dev/null
+++ b/code/botlib/be_aas_debug.h
@@ -0,0 +1,62 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_debug.h
+ *
+ * desc: AAS
+ *
+ * $Archive: /source/code/botlib/be_aas_debug.h $
+ *
+ *****************************************************************************/
+
+//clear the shown debug lines
+void AAS_ClearShownDebugLines(void);
+//
+void AAS_ClearShownPolygons(void);
+//show a debug line
+void AAS_DebugLine(vec3_t start, vec3_t end, int color);
+//show a permenent line
+void AAS_PermanentLine(vec3_t start, vec3_t end, int color);
+//show a permanent cross
+void AAS_DrawPermanentCross(vec3_t origin, float size, int color);
+//draw a cross in the plane
+void AAS_DrawPlaneCross(vec3_t point, vec3_t normal, float dist, int type, int color);
+//show a bounding box
+void AAS_ShowBoundingBox(vec3_t origin, vec3_t mins, vec3_t maxs);
+//show a face
+void AAS_ShowFace(int facenum);
+//show an area
+void AAS_ShowArea(int areanum, int groundfacesonly);
+//
+void AAS_ShowAreaPolygons(int areanum, int color, int groundfacesonly);
+//draw a cros
+void AAS_DrawCross(vec3_t origin, float size, int color);
+//print the travel type
+void AAS_PrintTravelType(int traveltype);
+//draw an arrow
+void AAS_DrawArrow(vec3_t start, vec3_t end, int linecolor, int arrowcolor);
+//visualize the given reachability
+void AAS_ShowReachability(struct aas_reachability_s *reach);
+//show the reachable areas from the given area
+void AAS_ShowReachableAreas(int areanum);
+
diff --git a/code/botlib/be_aas_def.h b/code/botlib/be_aas_def.h
new file mode 100755
index 0000000..22ebbc5
--- /dev/null
+++ b/code/botlib/be_aas_def.h
@@ -0,0 +1,306 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_def.h
+ *
+ * desc: AAS
+ *
+ * $Archive: /source/code/botlib/be_aas_def.h $
+ *
+ *****************************************************************************/
+
+//debugging on
+#define AAS_DEBUG
+
+#define MAX_CLIENTS 64
+#define MAX_MODELS 256 // these are sent over the net as 8 bits
+#define MAX_SOUNDS 256 // so they cannot be blindly increased
+#define MAX_CONFIGSTRINGS 1024
+
+#define CS_SCORES 32
+#define CS_MODELS (CS_SCORES+MAX_CLIENTS)
+#define CS_SOUNDS (CS_MODELS+MAX_MODELS)
+
+#define DF_AASENTNUMBER(x) (x - aasworld.entities)
+#define DF_NUMBERAASENT(x) (&aasworld.entities[x])
+#define DF_AASENTCLIENT(x) (x - aasworld.entities - 1)
+#define DF_CLIENTAASENT(x) (&aasworld.entities[x + 1])
+
+#ifndef MAX_PATH
+ #define MAX_PATH MAX_QPATH
+#endif
+
+//string index (for model, sound and image index)
+typedef struct aas_stringindex_s
+{
+ int numindexes;
+ char **index;
+} aas_stringindex_t;
+
+//structure to link entities to areas and areas to entities
+typedef struct aas_link_s
+{
+ int entnum;
+ int areanum;
+ struct aas_link_s *next_ent, *prev_ent;
+ struct aas_link_s *next_area, *prev_area;
+} aas_link_t;
+
+//structure to link entities to leaves and leaves to entities
+typedef struct bsp_link_s
+{
+ int entnum;
+ int leafnum;
+ struct bsp_link_s *next_ent, *prev_ent;
+ struct bsp_link_s *next_leaf, *prev_leaf;
+} bsp_link_t;
+
+typedef struct bsp_entdata_s
+{
+ vec3_t origin;
+ vec3_t angles;
+ vec3_t absmins;
+ vec3_t absmaxs;
+ int solid;
+ int modelnum;
+} bsp_entdata_t;
+
+//entity
+typedef struct aas_entity_s
+{
+ //entity info
+ aas_entityinfo_t i;
+ //links into the AAS areas
+ aas_link_t *areas;
+ //links into the BSP leaves
+ bsp_link_t *leaves;
+} aas_entity_t;
+
+typedef struct aas_settings_s
+{
+ vec3_t phys_gravitydirection;
+ float phys_friction;
+ float phys_stopspeed;
+ float phys_gravity;
+ float phys_waterfriction;
+ float phys_watergravity;
+ float phys_maxvelocity;
+ float phys_maxwalkvelocity;
+ float phys_maxcrouchvelocity;
+ float phys_maxswimvelocity;
+ float phys_walkaccelerate;
+ float phys_airaccelerate;
+ float phys_swimaccelerate;
+ float phys_maxstep;
+ float phys_maxsteepness;
+ float phys_maxwaterjump;
+ float phys_maxbarrier;
+ float phys_jumpvel;
+ float phys_falldelta5;
+ float phys_falldelta10;
+ float rs_waterjump;
+ float rs_teleport;
+ float rs_barrierjump;
+ float rs_startcrouch;
+ float rs_startgrapple;
+ float rs_startwalkoffledge;
+ float rs_startjump;
+ float rs_rocketjump;
+ float rs_bfgjump;
+ float rs_jumppad;
+ float rs_aircontrolledjumppad;
+ float rs_funcbob;
+ float rs_startelevator;
+ float rs_falldamage5;
+ float rs_falldamage10;
+ float rs_maxfallheight;
+ float rs_maxjumpfallheight;
+} aas_settings_t;
+
+#define CACHETYPE_PORTAL 0
+#define CACHETYPE_AREA 1
+
+//routing cache
+typedef struct aas_routingcache_s
+{
+ byte type; //portal or area cache
+ float time; //last time accessed or updated
+ int size; //size of the routing cache
+ int cluster; //cluster the cache is for
+ int areanum; //area the cache is created for
+ vec3_t origin; //origin within the area
+ float starttraveltime; //travel time to start with
+ int travelflags; //combinations of the travel flags
+ struct aas_routingcache_s *prev, *next;
+ struct aas_routingcache_s *time_prev, *time_next;
+ unsigned char *reachabilities; //reachabilities used for routing
+ unsigned short int traveltimes[1]; //travel time for every area (variable sized)
+} aas_routingcache_t;
+
+//fields for the routing algorithm
+typedef struct aas_routingupdate_s
+{
+ int cluster;
+ int areanum; //area number of the update
+ vec3_t start; //start point the area was entered
+ unsigned short int tmptraveltime; //temporary travel time
+ unsigned short int *areatraveltimes; //travel times within the area
+ qboolean inlist; //true if the update is in the list
+ struct aas_routingupdate_s *next;
+ struct aas_routingupdate_s *prev;
+} aas_routingupdate_t;
+
+//reversed reachability link
+typedef struct aas_reversedlink_s
+{
+ int linknum; //the aas_areareachability_t
+ int areanum; //reachable from this area
+ struct aas_reversedlink_s *next; //next link
+} aas_reversedlink_t;
+
+//reversed area reachability
+typedef struct aas_reversedreachability_s
+{
+ int numlinks;
+ aas_reversedlink_t *first;
+} aas_reversedreachability_t;
+
+//areas a reachability goes through
+typedef struct aas_reachabilityareas_s
+{
+ int firstarea, numareas;
+} aas_reachabilityareas_t;
+
+typedef struct aas_s
+{
+ int loaded; //true when an AAS file is loaded
+ int initialized; //true when AAS has been initialized
+ int savefile; //set true when file should be saved
+ int bspchecksum;
+ //current time
+ float time;
+ int numframes;
+ //name of the aas file
+ char filename[MAX_PATH];
+ char mapname[MAX_PATH];
+ //bounding boxes
+ int numbboxes;
+ aas_bbox_t *bboxes;
+ //vertexes
+ int numvertexes;
+ aas_vertex_t *vertexes;
+ //planes
+ int numplanes;
+ aas_plane_t *planes;
+ //edges
+ int numedges;
+ aas_edge_t *edges;
+ //edge index
+ int edgeindexsize;
+ aas_edgeindex_t *edgeindex;
+ //faces
+ int numfaces;
+ aas_face_t *faces;
+ //face index
+ int faceindexsize;
+ aas_faceindex_t *faceindex;
+ //convex areas
+ int numareas;
+ aas_area_t *areas;
+ //convex area settings
+ int numareasettings;
+ aas_areasettings_t *areasettings;
+ //reachablity list
+ int reachabilitysize;
+ aas_reachability_t *reachability;
+ //nodes of the bsp tree
+ int numnodes;
+ aas_node_t *nodes;
+ //cluster portals
+ int numportals;
+ aas_portal_t *portals;
+ //cluster portal index
+ int portalindexsize;
+ aas_portalindex_t *portalindex;
+ //clusters
+ int numclusters;
+ aas_cluster_t *clusters;
+ //
+ int numreachabilityareas;
+ float reachabilitytime;
+ //enities linked in the areas
+ aas_link_t *linkheap; //heap with link structures
+ int linkheapsize; //size of the link heap
+ aas_link_t *freelinks; //first free link
+ aas_link_t **arealinkedentities; //entities linked into areas
+ //entities
+ int maxentities;
+ int maxclients;
+ aas_entity_t *entities;
+ //string indexes
+ char *configstrings[MAX_CONFIGSTRINGS];
+ int indexessetup;
+ //index to retrieve travel flag for a travel type
+ int travelflagfortype[MAX_TRAVELTYPES];
+ //travel flags for each area based on contents
+ int *areacontentstravelflags;
+ //routing update
+ aas_routingupdate_t *areaupdate;
+ aas_routingupdate_t *portalupdate;
+ //number of routing updates during a frame (reset every frame)
+ int frameroutingupdates;
+ //reversed reachability links
+ aas_reversedreachability_t *reversedreachability;
+ //travel times within the areas
+ unsigned short ***areatraveltimes;
+ //array of size numclusters with cluster cache
+ aas_routingcache_t ***clusterareacache;
+ aas_routingcache_t **portalcache;
+ //cache list sorted on time
+ aas_routingcache_t *oldestcache; // start of cache list sorted on time
+ aas_routingcache_t *newestcache; // end of cache list sorted on time
+ //maximum travel time through portal areas
+ int *portalmaxtraveltimes;
+ //areas the reachabilities go through
+ int *reachabilityareaindex;
+ aas_reachabilityareas_t *reachabilityareas;
+} aas_t;
+
+#define AASINTERN
+
+#ifndef BSPCINCLUDE
+
+#include "be_aas_main.h"
+#include "be_aas_entity.h"
+#include "be_aas_sample.h"
+#include "be_aas_cluster.h"
+#include "be_aas_reach.h"
+#include "be_aas_route.h"
+#include "be_aas_routealt.h"
+#include "be_aas_debug.h"
+#include "be_aas_file.h"
+#include "be_aas_optimize.h"
+#include "be_aas_bsp.h"
+#include "be_aas_move.h"
+
+#endif //BSPCINCLUDE
diff --git a/code/botlib/be_aas_entity.c b/code/botlib/be_aas_entity.c
new file mode 100755
index 0000000..e3ed85e
--- /dev/null
+++ b/code/botlib/be_aas_entity.c
@@ -0,0 +1,437 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_entity.c
+ *
+ * desc: AAS entities
+ *
+ * $Archive: /MissionPack/code/botlib/be_aas_entity.c $
+ *
+ *****************************************************************************/
+
+#include "../game/q_shared.h"
+#include "l_memory.h"
+#include "l_script.h"
+#include "l_precomp.h"
+#include "l_struct.h"
+#include "l_utils.h"
+#include "l_log.h"
+#include "aasfile.h"
+#include "../game/botlib.h"
+#include "../game/be_aas.h"
+#include "be_aas_funcs.h"
+#include "be_interface.h"
+#include "be_aas_def.h"
+
+#define MASK_SOLID CONTENTS_PLAYERCLIP
+
+//FIXME: these might change
+enum {
+ ET_GENERAL,
+ ET_PLAYER,
+ ET_ITEM,
+ ET_MISSILE,
+ ET_MOVER
+};
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_UpdateEntity(int entnum, bot_entitystate_t *state)
+{
+ int relink;
+ aas_entity_t *ent;
+ vec3_t absmins, absmaxs;
+
+ if (!aasworld.loaded)
+ {
+ botimport.Print(PRT_MESSAGE, "AAS_UpdateEntity: not loaded\n");
+ return BLERR_NOAASFILE;
+ } //end if
+
+ ent = &aasworld.entities[entnum];
+
+ if (!state) {
+ //unlink the entity
+ AAS_UnlinkFromAreas(ent->areas);
+ //unlink the entity from the BSP leaves
+ AAS_UnlinkFromBSPLeaves(ent->leaves);
+ //
+ ent->areas = NULL;
+ //
+ ent->leaves = NULL;
+ return BLERR_NOERROR;
+ }
+
+ ent->i.update_time = AAS_Time() - ent->i.ltime;
+ ent->i.type = state->type;
+ ent->i.flags = state->flags;
+ ent->i.ltime = AAS_Time();
+ VectorCopy(ent->i.origin, ent->i.lastvisorigin);
+ VectorCopy(state->old_origin, ent->i.old_origin);
+ ent->i.solid = state->solid;
+ ent->i.groundent = state->groundent;
+ ent->i.modelindex = state->modelindex;
+ ent->i.modelindex2 = state->modelindex2;
+ ent->i.frame = state->frame;
+ ent->i.event = state->event;
+ ent->i.eventParm = state->eventParm;
+ ent->i.powerups = state->powerups;
+ ent->i.weapon = state->weapon;
+ ent->i.legsAnim = state->legsAnim;
+ ent->i.torsoAnim = state->torsoAnim;
+ //number of the entity
+ ent->i.number = entnum;
+ //updated so set valid flag
+ ent->i.valid = qtrue;
+ //link everything the first frame
+ if (aasworld.numframes == 1) relink = qtrue;
+ else relink = qfalse;
+ //
+ if (ent->i.solid == SOLID_BSP)
+ {
+ //if the angles of the model changed
+ if (!VectorCompare(state->angles, ent->i.angles))
+ {
+ VectorCopy(state->angles, ent->i.angles);
+ relink = qtrue;
+ } //end if
+ //get the mins and maxs of the model
+ //FIXME: rotate mins and maxs
+ AAS_BSPModelMinsMaxsOrigin(ent->i.modelindex, ent->i.angles, ent->i.mins, ent->i.maxs, NULL);
+ } //end if
+ else if (ent->i.solid == SOLID_BBOX)
+ {
+ //if the bounding box size changed
+ if (!VectorCompare(state->mins, ent->i.mins) ||
+ !VectorCompare(state->maxs, ent->i.maxs))
+ {
+ VectorCopy(state->mins, ent->i.mins);
+ VectorCopy(state->maxs, ent->i.maxs);
+ relink = qtrue;
+ } //end if
+ VectorCopy(state->angles, ent->i.angles);
+ } //end if
+ //if the origin changed
+ if (!VectorCompare(state->origin, ent->i.origin))
+ {
+ VectorCopy(state->origin, ent->i.origin);
+ relink = qtrue;
+ } //end if
+ //if the entity should be relinked
+ if (relink)
+ {
+ //don't link the world model
+ if (entnum != ENTITYNUM_WORLD)
+ {
+ //absolute mins and maxs
+ VectorAdd(ent->i.mins, ent->i.origin, absmins);
+ VectorAdd(ent->i.maxs, ent->i.origin, absmaxs);
+ //unlink the entity
+ AAS_UnlinkFromAreas(ent->areas);
+ //relink the entity to the AAS areas (use the larges bbox)
+ ent->areas = AAS_LinkEntityClientBBox(absmins, absmaxs, entnum, PRESENCE_NORMAL);
+ //unlink the entity from the BSP leaves
+ AAS_UnlinkFromBSPLeaves(ent->leaves);
+ //link the entity to the world BSP tree
+ ent->leaves = AAS_BSPLinkEntity(absmins, absmaxs, entnum, 0);
+ } //end if
+ } //end if
+ return BLERR_NOERROR;
+} //end of the function AAS_UpdateEntity
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_EntityInfo(int entnum, aas_entityinfo_t *info)
+{
+ if (!aasworld.initialized)
+ {
+ botimport.Print(PRT_FATAL, "AAS_EntityInfo: aasworld not initialized\n");
+ Com_Memset(info, 0, sizeof(aas_entityinfo_t));
+ return;
+ } //end if
+
+ if (entnum < 0 || entnum >= aasworld.maxentities)
+ {
+ botimport.Print(PRT_FATAL, "AAS_EntityInfo: entnum %d out of range\n", entnum);
+ Com_Memset(info, 0, sizeof(aas_entityinfo_t));
+ return;
+ } //end if
+
+ Com_Memcpy(info, &aasworld.entities[entnum].i, sizeof(aas_entityinfo_t));
+} //end of the function AAS_EntityInfo
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_EntityOrigin(int entnum, vec3_t origin)
+{
+ if (entnum < 0 || entnum >= aasworld.maxentities)
+ {
+ botimport.Print(PRT_FATAL, "AAS_EntityOrigin: entnum %d out of range\n", entnum);
+ VectorClear(origin);
+ return;
+ } //end if
+
+ VectorCopy(aasworld.entities[entnum].i.origin, origin);
+} //end of the function AAS_EntityOrigin
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_EntityModelindex(int entnum)
+{
+ if (entnum < 0 || entnum >= aasworld.maxentities)
+ {
+ botimport.Print(PRT_FATAL, "AAS_EntityModelindex: entnum %d out of range\n", entnum);
+ return 0;
+ } //end if
+ return aasworld.entities[entnum].i.modelindex;
+} //end of the function AAS_EntityModelindex
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_EntityType(int entnum)
+{
+ if (!aasworld.initialized) return 0;
+
+ if (entnum < 0 || entnum >= aasworld.maxentities)
+ {
+ botimport.Print(PRT_FATAL, "AAS_EntityType: entnum %d out of range\n", entnum);
+ return 0;
+ } //end if
+ return aasworld.entities[entnum].i.type;
+} //end of the AAS_EntityType
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_EntityModelNum(int entnum)
+{
+ if (!aasworld.initialized) return 0;
+
+ if (entnum < 0 || entnum >= aasworld.maxentities)
+ {
+ botimport.Print(PRT_FATAL, "AAS_EntityModelNum: entnum %d out of range\n", entnum);
+ return 0;
+ } //end if
+ return aasworld.entities[entnum].i.modelindex;
+} //end of the function AAS_EntityModelNum
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_OriginOfMoverWithModelNum(int modelnum, vec3_t origin)
+{
+ int i;
+ aas_entity_t *ent;
+
+ for (i = 0; i < aasworld.maxentities; i++)
+ {
+ ent = &aasworld.entities[i];
+ if (ent->i.type == ET_MOVER)
+ {
+ if (ent->i.modelindex == modelnum)
+ {
+ VectorCopy(ent->i.origin, origin);
+ return qtrue;
+ } //end if
+ } //end if
+ } //end for
+ return qfalse;
+} //end of the function AAS_OriginOfMoverWithModelNum
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_EntitySize(int entnum, vec3_t mins, vec3_t maxs)
+{
+ aas_entity_t *ent;
+
+ if (!aasworld.initialized) return;
+
+ if (entnum < 0 || entnum >= aasworld.maxentities)
+ {
+ botimport.Print(PRT_FATAL, "AAS_EntitySize: entnum %d out of range\n", entnum);
+ return;
+ } //end if
+
+ ent = &aasworld.entities[entnum];
+ VectorCopy(ent->i.mins, mins);
+ VectorCopy(ent->i.maxs, maxs);
+} //end of the function AAS_EntitySize
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_EntityBSPData(int entnum, bsp_entdata_t *entdata)
+{
+ aas_entity_t *ent;
+
+ ent = &aasworld.entities[entnum];
+ VectorCopy(ent->i.origin, entdata->origin);
+ VectorCopy(ent->i.angles, entdata->angles);
+ VectorAdd(ent->i.origin, ent->i.mins, entdata->absmins);
+ VectorAdd(ent->i.origin, ent->i.maxs, entdata->absmaxs);
+ entdata->solid = ent->i.solid;
+ entdata->modelnum = ent->i.modelindex - 1;
+} //end of the function AAS_EntityBSPData
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ResetEntityLinks(void)
+{
+ int i;
+ for (i = 0; i < aasworld.maxentities; i++)
+ {
+ aasworld.entities[i].areas = NULL;
+ aasworld.entities[i].leaves = NULL;
+ } //end for
+} //end of the function AAS_ResetEntityLinks
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_InvalidateEntities(void)
+{
+ int i;
+ for (i = 0; i < aasworld.maxentities; i++)
+ {
+ aasworld.entities[i].i.valid = qfalse;
+ aasworld.entities[i].i.number = i;
+ } //end for
+} //end of the function AAS_InvalidateEntities
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_UnlinkInvalidEntities(void)
+{
+ int i;
+ aas_entity_t *ent;
+
+ for (i = 0; i < aasworld.maxentities; i++)
+ {
+ ent = &aasworld.entities[i];
+ if (!ent->i.valid)
+ {
+ AAS_UnlinkFromAreas( ent->areas );
+ ent->areas = NULL;
+ AAS_UnlinkFromBSPLeaves( ent->leaves );
+ ent->leaves = NULL;
+ } //end for
+ } //end for
+} //end of the function AAS_UnlinkInvalidEntities
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_NearestEntity(vec3_t origin, int modelindex)
+{
+ int i, bestentnum;
+ float dist, bestdist;
+ aas_entity_t *ent;
+ vec3_t dir;
+
+ bestentnum = 0;
+ bestdist = 99999;
+ for (i = 0; i < aasworld.maxentities; i++)
+ {
+ ent = &aasworld.entities[i];
+ if (ent->i.modelindex != modelindex) continue;
+ VectorSubtract(ent->i.origin, origin, dir);
+ if (abs(dir[0]) < 40)
+ {
+ if (abs(dir[1]) < 40)
+ {
+ dist = VectorLength(dir);
+ if (dist < bestdist)
+ {
+ bestdist = dist;
+ bestentnum = i;
+ } //end if
+ } //end if
+ } //end if
+ } //end for
+ return bestentnum;
+} //end of the function AAS_NearestEntity
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_BestReachableEntityArea(int entnum)
+{
+ aas_entity_t *ent;
+
+ ent = &aasworld.entities[entnum];
+ return AAS_BestReachableLinkArea(ent->areas);
+} //end of the function AAS_BestReachableEntityArea
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_NextEntity(int entnum)
+{
+ if (!aasworld.loaded) return 0;
+
+ if (entnum < 0) entnum = -1;
+ while(++entnum < aasworld.maxentities)
+ {
+ if (aasworld.entities[entnum].i.valid) return entnum;
+ } //end while
+ return 0;
+} //end of the function AAS_NextEntity
diff --git a/code/botlib/be_aas_entity.h b/code/botlib/be_aas_entity.h
new file mode 100755
index 0000000..f5286dd
--- /dev/null
+++ b/code/botlib/be_aas_entity.h
@@ -0,0 +1,63 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_entity.h
+ *
+ * desc: AAS
+ *
+ * $Archive: /source/code/botlib/be_aas_entity.h $
+ *
+ *****************************************************************************/
+
+#ifdef AASINTERN
+//invalidates all entity infos
+void AAS_InvalidateEntities(void);
+//unlink not updated entities
+void AAS_UnlinkInvalidEntities(void);
+//resets the entity AAS and BSP links (sets areas and leaves pointers to NULL)
+void AAS_ResetEntityLinks(void);
+//updates an entity
+int AAS_UpdateEntity(int ent, bot_entitystate_t *state);
+//gives the entity data used for collision detection
+void AAS_EntityBSPData(int entnum, bsp_entdata_t *entdata);
+#endif //AASINTERN
+
+//returns the size of the entity bounding box in mins and maxs
+void AAS_EntitySize(int entnum, vec3_t mins, vec3_t maxs);
+//returns the BSP model number of the entity
+int AAS_EntityModelNum(int entnum);
+//returns the origin of an entity with the given model number
+int AAS_OriginOfMoverWithModelNum(int modelnum, vec3_t origin);
+//returns the best reachable area the entity is situated in
+int AAS_BestReachableEntityArea(int entnum);
+//returns the info of the given entity
+void AAS_EntityInfo(int entnum, aas_entityinfo_t *info);
+//returns the next entity
+int AAS_NextEntity(int entnum);
+//returns the origin of the entity
+void AAS_EntityOrigin(int entnum, vec3_t origin);
+//returns the entity type
+int AAS_EntityType(int entnum);
+//returns the model index of the entity
+int AAS_EntityModelindex(int entnum);
+
diff --git a/code/botlib/be_aas_file.c b/code/botlib/be_aas_file.c
new file mode 100755
index 0000000..35147fc
--- /dev/null
+++ b/code/botlib/be_aas_file.c
@@ -0,0 +1,582 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_file.c
+ *
+ * desc: AAS file loading/writing
+ *
+ * $Archive: /MissionPack/code/botlib/be_aas_file.c $
+ *
+ *****************************************************************************/
+
+#include "../game/q_shared.h"
+#include "l_memory.h"
+#include "l_script.h"
+#include "l_precomp.h"
+#include "l_struct.h"
+#include "l_libvar.h"
+#include "l_utils.h"
+#include "aasfile.h"
+#include "../game/botlib.h"
+#include "../game/be_aas.h"
+#include "be_aas_funcs.h"
+#include "be_interface.h"
+#include "be_aas_def.h"
+
+//#define AASFILEDEBUG
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_SwapAASData(void)
+{
+ int i, j;
+ //bounding boxes
+ for (i = 0; i < aasworld.numbboxes; i++)
+ {
+ aasworld.bboxes[i].presencetype = LittleLong(aasworld.bboxes[i].presencetype);
+ aasworld.bboxes[i].flags = LittleLong(aasworld.bboxes[i].flags);
+ for (j = 0; j < 3; j++)
+ {
+ aasworld.bboxes[i].mins[j] = LittleLong(aasworld.bboxes[i].mins[j]);
+ aasworld.bboxes[i].maxs[j] = LittleLong(aasworld.bboxes[i].maxs[j]);
+ } //end for
+ } //end for
+ //vertexes
+ for (i = 0; i < aasworld.numvertexes; i++)
+ {
+ for (j = 0; j < 3; j++)
+ aasworld.vertexes[i][j] = LittleFloat(aasworld.vertexes[i][j]);
+ } //end for
+ //planes
+ for (i = 0; i < aasworld.numplanes; i++)
+ {
+ for (j = 0; j < 3; j++)
+ aasworld.planes[i].normal[j] = LittleFloat(aasworld.planes[i].normal[j]);
+ aasworld.planes[i].dist = LittleFloat(aasworld.planes[i].dist);
+ aasworld.planes[i].type = LittleLong(aasworld.planes[i].type);
+ } //end for
+ //edges
+ for (i = 0; i < aasworld.numedges; i++)
+ {
+ aasworld.edges[i].v[0] = LittleLong(aasworld.edges[i].v[0]);
+ aasworld.edges[i].v[1] = LittleLong(aasworld.edges[i].v[1]);
+ } //end for
+ //edgeindex
+ for (i = 0; i < aasworld.edgeindexsize; i++)
+ {
+ aasworld.edgeindex[i] = LittleLong(aasworld.edgeindex[i]);
+ } //end for
+ //faces
+ for (i = 0; i < aasworld.numfaces; i++)
+ {
+ aasworld.faces[i].planenum = LittleLong(aasworld.faces[i].planenum);
+ aasworld.faces[i].faceflags = LittleLong(aasworld.faces[i].faceflags);
+ aasworld.faces[i].numedges = LittleLong(aasworld.faces[i].numedges);
+ aasworld.faces[i].firstedge = LittleLong(aasworld.faces[i].firstedge);
+ aasworld.faces[i].frontarea = LittleLong(aasworld.faces[i].frontarea);
+ aasworld.faces[i].backarea = LittleLong(aasworld.faces[i].backarea);
+ } //end for
+ //face index
+ for (i = 0; i < aasworld.faceindexsize; i++)
+ {
+ aasworld.faceindex[i] = LittleLong(aasworld.faceindex[i]);
+ } //end for
+ //convex areas
+ for (i = 0; i < aasworld.numareas; i++)
+ {
+ aasworld.areas[i].areanum = LittleLong(aasworld.areas[i].areanum);
+ aasworld.areas[i].numfaces = LittleLong(aasworld.areas[i].numfaces);
+ aasworld.areas[i].firstface = LittleLong(aasworld.areas[i].firstface);
+ for (j = 0; j < 3; j++)
+ {
+ aasworld.areas[i].mins[j] = LittleFloat(aasworld.areas[i].mins[j]);
+ aasworld.areas[i].maxs[j] = LittleFloat(aasworld.areas[i].maxs[j]);
+ aasworld.areas[i].center[j] = LittleFloat(aasworld.areas[i].center[j]);
+ } //end for
+ } //end for
+ //area settings
+ for (i = 0; i < aasworld.numareasettings; i++)
+ {
+ aasworld.areasettings[i].contents = LittleLong(aasworld.areasettings[i].contents);
+ aasworld.areasettings[i].areaflags = LittleLong(aasworld.areasettings[i].areaflags);
+ aasworld.areasettings[i].presencetype = LittleLong(aasworld.areasettings[i].presencetype);
+ aasworld.areasettings[i].cluster = LittleLong(aasworld.areasettings[i].cluster);
+ aasworld.areasettings[i].clusterareanum = LittleLong(aasworld.areasettings[i].clusterareanum);
+ aasworld.areasettings[i].numreachableareas = LittleLong(aasworld.areasettings[i].numreachableareas);
+ aasworld.areasettings[i].firstreachablearea = LittleLong(aasworld.areasettings[i].firstreachablearea);
+ } //end for
+ //area reachability
+ for (i = 0; i < aasworld.reachabilitysize; i++)
+ {
+ aasworld.reachability[i].areanum = LittleLong(aasworld.reachability[i].areanum);
+ aasworld.reachability[i].facenum = LittleLong(aasworld.reachability[i].facenum);
+ aasworld.reachability[i].edgenum = LittleLong(aasworld.reachability[i].edgenum);
+ for (j = 0; j < 3; j++)
+ {
+ aasworld.reachability[i].start[j] = LittleFloat(aasworld.reachability[i].start[j]);
+ aasworld.reachability[i].end[j] = LittleFloat(aasworld.reachability[i].end[j]);
+ } //end for
+ aasworld.reachability[i].traveltype = LittleLong(aasworld.reachability[i].traveltype);
+ aasworld.reachability[i].traveltime = LittleShort(aasworld.reachability[i].traveltime);
+ } //end for
+ //nodes
+ for (i = 0; i < aasworld.numnodes; i++)
+ {
+ aasworld.nodes[i].planenum = LittleLong(aasworld.nodes[i].planenum);
+ aasworld.nodes[i].children[0] = LittleLong(aasworld.nodes[i].children[0]);
+ aasworld.nodes[i].children[1] = LittleLong(aasworld.nodes[i].children[1]);
+ } //end for
+ //cluster portals
+ for (i = 0; i < aasworld.numportals; i++)
+ {
+ aasworld.portals[i].areanum = LittleLong(aasworld.portals[i].areanum);
+ aasworld.portals[i].frontcluster = LittleLong(aasworld.portals[i].frontcluster);
+ aasworld.portals[i].backcluster = LittleLong(aasworld.portals[i].backcluster);
+ aasworld.portals[i].clusterareanum[0] = LittleLong(aasworld.portals[i].clusterareanum[0]);
+ aasworld.portals[i].clusterareanum[1] = LittleLong(aasworld.portals[i].clusterareanum[1]);
+ } //end for
+ //cluster portal index
+ for (i = 0; i < aasworld.portalindexsize; i++)
+ {
+ aasworld.portalindex[i] = LittleLong(aasworld.portalindex[i]);
+ } //end for
+ //cluster
+ for (i = 0; i < aasworld.numclusters; i++)
+ {
+ aasworld.clusters[i].numareas = LittleLong(aasworld.clusters[i].numareas);
+ aasworld.clusters[i].numreachabilityareas = LittleLong(aasworld.clusters[i].numreachabilityareas);
+ aasworld.clusters[i].numportals = LittleLong(aasworld.clusters[i].numportals);
+ aasworld.clusters[i].firstportal = LittleLong(aasworld.clusters[i].firstportal);
+ } //end for
+} //end of the function AAS_SwapAASData
+//===========================================================================
+// dump the current loaded aas file
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_DumpAASData(void)
+{
+ aasworld.numbboxes = 0;
+ if (aasworld.bboxes) FreeMemory(aasworld.bboxes);
+ aasworld.bboxes = NULL;
+ aasworld.numvertexes = 0;
+ if (aasworld.vertexes) FreeMemory(aasworld.vertexes);
+ aasworld.vertexes = NULL;
+ aasworld.numplanes = 0;
+ if (aasworld.planes) FreeMemory(aasworld.planes);
+ aasworld.planes = NULL;
+ aasworld.numedges = 0;
+ if (aasworld.edges) FreeMemory(aasworld.edges);
+ aasworld.edges = NULL;
+ aasworld.edgeindexsize = 0;
+ if (aasworld.edgeindex) FreeMemory(aasworld.edgeindex);
+ aasworld.edgeindex = NULL;
+ aasworld.numfaces = 0;
+ if (aasworld.faces) FreeMemory(aasworld.faces);
+ aasworld.faces = NULL;
+ aasworld.faceindexsize = 0;
+ if (aasworld.faceindex) FreeMemory(aasworld.faceindex);
+ aasworld.faceindex = NULL;
+ aasworld.numareas = 0;
+ if (aasworld.areas) FreeMemory(aasworld.areas);
+ aasworld.areas = NULL;
+ aasworld.numareasettings = 0;
+ if (aasworld.areasettings) FreeMemory(aasworld.areasettings);
+ aasworld.areasettings = NULL;
+ aasworld.reachabilitysize = 0;
+ if (aasworld.reachability) FreeMemory(aasworld.reachability);
+ aasworld.reachability = NULL;
+ aasworld.numnodes = 0;
+ if (aasworld.nodes) FreeMemory(aasworld.nodes);
+ aasworld.nodes = NULL;
+ aasworld.numportals = 0;
+ if (aasworld.portals) FreeMemory(aasworld.portals);
+ aasworld.portals = NULL;
+ aasworld.numportals = 0;
+ if (aasworld.portalindex) FreeMemory(aasworld.portalindex);
+ aasworld.portalindex = NULL;
+ aasworld.portalindexsize = 0;
+ if (aasworld.clusters) FreeMemory(aasworld.clusters);
+ aasworld.clusters = NULL;
+ aasworld.numclusters = 0;
+ //
+ aasworld.loaded = qfalse;
+ aasworld.initialized = qfalse;
+ aasworld.savefile = qfalse;
+} //end of the function AAS_DumpAASData
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+#ifdef AASFILEDEBUG
+void AAS_FileInfo(void)
+{
+ int i, n, optimized;
+
+ botimport.Print(PRT_MESSAGE, "version = %d\n", AASVERSION);
+ botimport.Print(PRT_MESSAGE, "numvertexes = %d\n", aasworld.numvertexes);
+ botimport.Print(PRT_MESSAGE, "numplanes = %d\n", aasworld.numplanes);
+ botimport.Print(PRT_MESSAGE, "numedges = %d\n", aasworld.numedges);
+ botimport.Print(PRT_MESSAGE, "edgeindexsize = %d\n", aasworld.edgeindexsize);
+ botimport.Print(PRT_MESSAGE, "numfaces = %d\n", aasworld.numfaces);
+ botimport.Print(PRT_MESSAGE, "faceindexsize = %d\n", aasworld.faceindexsize);
+ botimport.Print(PRT_MESSAGE, "numareas = %d\n", aasworld.numareas);
+ botimport.Print(PRT_MESSAGE, "numareasettings = %d\n", aasworld.numareasettings);
+ botimport.Print(PRT_MESSAGE, "reachabilitysize = %d\n", aasworld.reachabilitysize);
+ botimport.Print(PRT_MESSAGE, "numnodes = %d\n", aasworld.numnodes);
+ botimport.Print(PRT_MESSAGE, "numportals = %d\n", aasworld.numportals);
+ botimport.Print(PRT_MESSAGE, "portalindexsize = %d\n", aasworld.portalindexsize);
+ botimport.Print(PRT_MESSAGE, "numclusters = %d\n", aasworld.numclusters);
+ //
+ for (n = 0, i = 0; i < aasworld.numareasettings; i++)
+ {
+ if (aasworld.areasettings[i].areaflags & AREA_GROUNDED) n++;
+ } //end for
+ botimport.Print(PRT_MESSAGE, "num grounded areas = %d\n", n);
+ //
+ botimport.Print(PRT_MESSAGE, "planes size %d bytes\n", aasworld.numplanes * sizeof(aas_plane_t));
+ botimport.Print(PRT_MESSAGE, "areas size %d bytes\n", aasworld.numareas * sizeof(aas_area_t));
+ botimport.Print(PRT_MESSAGE, "areasettings size %d bytes\n", aasworld.numareasettings * sizeof(aas_areasettings_t));
+ botimport.Print(PRT_MESSAGE, "nodes size %d bytes\n", aasworld.numnodes * sizeof(aas_node_t));
+ botimport.Print(PRT_MESSAGE, "reachability size %d bytes\n", aasworld.reachabilitysize * sizeof(aas_reachability_t));
+ botimport.Print(PRT_MESSAGE, "portals size %d bytes\n", aasworld.numportals * sizeof(aas_portal_t));
+ botimport.Print(PRT_MESSAGE, "clusters size %d bytes\n", aasworld.numclusters * sizeof(aas_cluster_t));
+
+ optimized = aasworld.numplanes * sizeof(aas_plane_t) +
+ aasworld.numareas * sizeof(aas_area_t) +
+ aasworld.numareasettings * sizeof(aas_areasettings_t) +
+ aasworld.numnodes * sizeof(aas_node_t) +
+ aasworld.reachabilitysize * sizeof(aas_reachability_t) +
+ aasworld.numportals * sizeof(aas_portal_t) +
+ aasworld.numclusters * sizeof(aas_cluster_t);
+ botimport.Print(PRT_MESSAGE, "optimzed size %d KB\n", optimized >> 10);
+} //end of the function AAS_FileInfo
+#endif //AASFILEDEBUG
+//===========================================================================
+// allocate memory and read a lump of a AAS file
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+char *AAS_LoadAASLump(fileHandle_t fp, int offset, int length, int *lastoffset, int size)
+{
+ char *buf;
+ //
+ if (!length)
+ {
+ //just alloc a dummy
+ return (char *) GetClearedHunkMemory(size+1);
+ } //end if
+ //seek to the data
+ if (offset != *lastoffset)
+ {
+ botimport.Print(PRT_WARNING, "AAS file not sequentially read\n");
+ if (botimport.FS_Seek(fp, offset, FS_SEEK_SET))
+ {
+ AAS_Error("can't seek to aas lump\n");
+ AAS_DumpAASData();
+ botimport.FS_FCloseFile(fp);
+ return 0;
+ } //end if
+ } //end if
+ //allocate memory
+ buf = (char *) GetClearedHunkMemory(length+1);
+ //read the data
+ if (length)
+ {
+ botimport.FS_Read(buf, length, fp );
+ *lastoffset += length;
+ } //end if
+ return buf;
+} //end of the function AAS_LoadAASLump
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_DData(unsigned char *data, int size)
+{
+ int i;
+
+ for (i = 0; i < size; i++)
+ {
+ data[i] ^= (unsigned char) i * 119;
+ } //end for
+} //end of the function AAS_DData
+//===========================================================================
+// load an aas file
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_LoadAASFile(char *filename)
+{
+ fileHandle_t fp;
+ aas_header_t header;
+ int offset, length, lastoffset;
+
+ botimport.Print(PRT_MESSAGE, "trying to load %s\n", filename);
+ //dump current loaded aas file
+ AAS_DumpAASData();
+ //open the file
+ botimport.FS_FOpenFile( filename, &fp, FS_READ );
+ if (!fp)
+ {
+ AAS_Error("can't open %s\n", filename);
+ return BLERR_CANNOTOPENAASFILE;
+ } //end if
+ //read the header
+ botimport.FS_Read(&header, sizeof(aas_header_t), fp );
+ lastoffset = sizeof(aas_header_t);
+ //check header identification
+ header.ident = LittleLong(header.ident);
+ if (header.ident != AASID)
+ {
+ AAS_Error("%s is not an AAS file\n", filename);
+ botimport.FS_FCloseFile(fp);
+ return BLERR_WRONGAASFILEID;
+ } //end if
+ //check the version
+ header.version = LittleLong(header.version);
+ //
+ if (header.version != AASVERSION_OLD && header.version != AASVERSION)
+ {
+ AAS_Error("aas file %s is version %i, not %i\n", filename, header.version, AASVERSION);
+ botimport.FS_FCloseFile(fp);
+ return BLERR_WRONGAASFILEVERSION;
+ } //end if
+ //
+ if (header.version == AASVERSION)
+ {
+ AAS_DData((unsigned char *) &header + 8, sizeof(aas_header_t) - 8);
+ } //end if
+ //
+ aasworld.bspchecksum = atoi(LibVarGetString( "sv_mapChecksum"));
+ if (LittleLong(header.bspchecksum) != aasworld.bspchecksum)
+ {
+ AAS_Error("aas file %s is out of date\n", filename);
+ botimport.FS_FCloseFile(fp);
+ return BLERR_WRONGAASFILEVERSION;
+ } //end if
+ //load the lumps:
+ //bounding boxes
+ offset = LittleLong(header.lumps[AASLUMP_BBOXES].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_BBOXES].filelen);
+ aasworld.bboxes = (aas_bbox_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_bbox_t));
+ aasworld.numbboxes = length / sizeof(aas_bbox_t);
+ if (aasworld.numbboxes && !aasworld.bboxes) return BLERR_CANNOTREADAASLUMP;
+ //vertexes
+ offset = LittleLong(header.lumps[AASLUMP_VERTEXES].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_VERTEXES].filelen);
+ aasworld.vertexes = (aas_vertex_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_vertex_t));
+ aasworld.numvertexes = length / sizeof(aas_vertex_t);
+ if (aasworld.numvertexes && !aasworld.vertexes) return BLERR_CANNOTREADAASLUMP;
+ //planes
+ offset = LittleLong(header.lumps[AASLUMP_PLANES].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_PLANES].filelen);
+ aasworld.planes = (aas_plane_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_plane_t));
+ aasworld.numplanes = length / sizeof(aas_plane_t);
+ if (aasworld.numplanes && !aasworld.planes) return BLERR_CANNOTREADAASLUMP;
+ //edges
+ offset = LittleLong(header.lumps[AASLUMP_EDGES].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_EDGES].filelen);
+ aasworld.edges = (aas_edge_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_edge_t));
+ aasworld.numedges = length / sizeof(aas_edge_t);
+ if (aasworld.numedges && !aasworld.edges) return BLERR_CANNOTREADAASLUMP;
+ //edgeindex
+ offset = LittleLong(header.lumps[AASLUMP_EDGEINDEX].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_EDGEINDEX].filelen);
+ aasworld.edgeindex = (aas_edgeindex_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_edgeindex_t));
+ aasworld.edgeindexsize = length / sizeof(aas_edgeindex_t);
+ if (aasworld.edgeindexsize && !aasworld.edgeindex) return BLERR_CANNOTREADAASLUMP;
+ //faces
+ offset = LittleLong(header.lumps[AASLUMP_FACES].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_FACES].filelen);
+ aasworld.faces = (aas_face_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_face_t));
+ aasworld.numfaces = length / sizeof(aas_face_t);
+ if (aasworld.numfaces && !aasworld.faces) return BLERR_CANNOTREADAASLUMP;
+ //faceindex
+ offset = LittleLong(header.lumps[AASLUMP_FACEINDEX].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_FACEINDEX].filelen);
+ aasworld.faceindex = (aas_faceindex_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_faceindex_t));
+ aasworld.faceindexsize = length / sizeof(aas_faceindex_t);
+ if (aasworld.faceindexsize && !aasworld.faceindex) return BLERR_CANNOTREADAASLUMP;
+ //convex areas
+ offset = LittleLong(header.lumps[AASLUMP_AREAS].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_AREAS].filelen);
+ aasworld.areas = (aas_area_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_area_t));
+ aasworld.numareas = length / sizeof(aas_area_t);
+ if (aasworld.numareas && !aasworld.areas) return BLERR_CANNOTREADAASLUMP;
+ //area settings
+ offset = LittleLong(header.lumps[AASLUMP_AREASETTINGS].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_AREASETTINGS].filelen);
+ aasworld.areasettings = (aas_areasettings_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_areasettings_t));
+ aasworld.numareasettings = length / sizeof(aas_areasettings_t);
+ if (aasworld.numareasettings && !aasworld.areasettings) return BLERR_CANNOTREADAASLUMP;
+ //reachability list
+ offset = LittleLong(header.lumps[AASLUMP_REACHABILITY].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_REACHABILITY].filelen);
+ aasworld.reachability = (aas_reachability_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_reachability_t));
+ aasworld.reachabilitysize = length / sizeof(aas_reachability_t);
+ if (aasworld.reachabilitysize && !aasworld.reachability) return BLERR_CANNOTREADAASLUMP;
+ //nodes
+ offset = LittleLong(header.lumps[AASLUMP_NODES].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_NODES].filelen);
+ aasworld.nodes = (aas_node_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_node_t));
+ aasworld.numnodes = length / sizeof(aas_node_t);
+ if (aasworld.numnodes && !aasworld.nodes) return BLERR_CANNOTREADAASLUMP;
+ //cluster portals
+ offset = LittleLong(header.lumps[AASLUMP_PORTALS].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_PORTALS].filelen);
+ aasworld.portals = (aas_portal_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_portal_t));
+ aasworld.numportals = length / sizeof(aas_portal_t);
+ if (aasworld.numportals && !aasworld.portals) return BLERR_CANNOTREADAASLUMP;
+ //cluster portal index
+ offset = LittleLong(header.lumps[AASLUMP_PORTALINDEX].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_PORTALINDEX].filelen);
+ aasworld.portalindex = (aas_portalindex_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_portalindex_t));
+ aasworld.portalindexsize = length / sizeof(aas_portalindex_t);
+ if (aasworld.portalindexsize && !aasworld.portalindex) return BLERR_CANNOTREADAASLUMP;
+ //clusters
+ offset = LittleLong(header.lumps[AASLUMP_CLUSTERS].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_CLUSTERS].filelen);
+ aasworld.clusters = (aas_cluster_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_cluster_t));
+ aasworld.numclusters = length / sizeof(aas_cluster_t);
+ if (aasworld.numclusters && !aasworld.clusters) return BLERR_CANNOTREADAASLUMP;
+ //swap everything
+ AAS_SwapAASData();
+ //aas file is loaded
+ aasworld.loaded = qtrue;
+ //close the file
+ botimport.FS_FCloseFile(fp);
+ //
+#ifdef AASFILEDEBUG
+ AAS_FileInfo();
+#endif //AASFILEDEBUG
+ //
+ return BLERR_NOERROR;
+} //end of the function AAS_LoadAASFile
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+static int AAS_WriteAASLump_offset;
+
+int AAS_WriteAASLump(fileHandle_t fp, aas_header_t *h, int lumpnum, void *data, int length)
+{
+ aas_lump_t *lump;
+
+ lump = &h->lumps[lumpnum];
+
+ lump->fileofs = LittleLong(AAS_WriteAASLump_offset); //LittleLong(ftell(fp));
+ lump->filelen = LittleLong(length);
+
+ if (length > 0)
+ {
+ botimport.FS_Write(data, length, fp );
+ } //end if
+
+ AAS_WriteAASLump_offset += length;
+
+ return qtrue;
+} //end of the function AAS_WriteAASLump
+//===========================================================================
+// aas data is useless after writing to file because it is byte swapped
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean AAS_WriteAASFile(char *filename)
+{
+ aas_header_t header;
+ fileHandle_t fp;
+
+ botimport.Print(PRT_MESSAGE, "writing %s\n", filename);
+ //swap the aas data
+ AAS_SwapAASData();
+ //initialize the file header
+ Com_Memset(&header, 0, sizeof(aas_header_t));
+ header.ident = LittleLong(AASID);
+ header.version = LittleLong(AASVERSION);
+ header.bspchecksum = LittleLong(aasworld.bspchecksum);
+ //open a new file
+ botimport.FS_FOpenFile( filename, &fp, FS_WRITE );
+ if (!fp)
+ {
+ botimport.Print(PRT_ERROR, "error opening %s\n", filename);
+ return qfalse;
+ } //end if
+ //write the header
+ botimport.FS_Write(&header, sizeof(aas_header_t), fp);
+ AAS_WriteAASLump_offset = sizeof(aas_header_t);
+ //add the data lumps to the file
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_BBOXES, aasworld.bboxes,
+ aasworld.numbboxes * sizeof(aas_bbox_t))) return qfalse;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_VERTEXES, aasworld.vertexes,
+ aasworld.numvertexes * sizeof(aas_vertex_t))) return qfalse;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_PLANES, aasworld.planes,
+ aasworld.numplanes * sizeof(aas_plane_t))) return qfalse;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_EDGES, aasworld.edges,
+ aasworld.numedges * sizeof(aas_edge_t))) return qfalse;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_EDGEINDEX, aasworld.edgeindex,
+ aasworld.edgeindexsize * sizeof(aas_edgeindex_t))) return qfalse;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_FACES, aasworld.faces,
+ aasworld.numfaces * sizeof(aas_face_t))) return qfalse;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_FACEINDEX, aasworld.faceindex,
+ aasworld.faceindexsize * sizeof(aas_faceindex_t))) return qfalse;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_AREAS, aasworld.areas,
+ aasworld.numareas * sizeof(aas_area_t))) return qfalse;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_AREASETTINGS, aasworld.areasettings,
+ aasworld.numareasettings * sizeof(aas_areasettings_t))) return qfalse;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_REACHABILITY, aasworld.reachability,
+ aasworld.reachabilitysize * sizeof(aas_reachability_t))) return qfalse;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_NODES, aasworld.nodes,
+ aasworld.numnodes * sizeof(aas_node_t))) return qfalse;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_PORTALS, aasworld.portals,
+ aasworld.numportals * sizeof(aas_portal_t))) return qfalse;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_PORTALINDEX, aasworld.portalindex,
+ aasworld.portalindexsize * sizeof(aas_portalindex_t))) return qfalse;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_CLUSTERS, aasworld.clusters,
+ aasworld.numclusters * sizeof(aas_cluster_t))) return qfalse;
+ //rewrite the header with the added lumps
+ botimport.FS_Seek(fp, 0, FS_SEEK_SET);
+ AAS_DData((unsigned char *) &header + 8, sizeof(aas_header_t) - 8);
+ botimport.FS_Write(&header, sizeof(aas_header_t), fp);
+ //close the file
+ botimport.FS_FCloseFile(fp);
+ return qtrue;
+} //end of the function AAS_WriteAASFile
diff --git a/code/botlib/be_aas_file.h b/code/botlib/be_aas_file.h
new file mode 100755
index 0000000..87a38d0
--- /dev/null
+++ b/code/botlib/be_aas_file.h
@@ -0,0 +1,42 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_file.h
+ *
+ * desc: AAS
+ *
+ * $Archive: /source/code/botlib/be_aas_file.h $
+ *
+ *****************************************************************************/
+
+#ifdef AASINTERN
+//loads the AAS file with the given name
+int AAS_LoadAASFile(char *filename);
+//writes an AAS file with the given name
+qboolean AAS_WriteAASFile(char *filename);
+//dumps the loaded AAS data
+void AAS_DumpAASData(void);
+//print AAS file information
+void AAS_FileInfo(void);
+#endif //AASINTERN
+
diff --git a/code/botlib/be_aas_funcs.h b/code/botlib/be_aas_funcs.h
new file mode 100755
index 0000000..4dd37e9
--- /dev/null
+++ b/code/botlib/be_aas_funcs.h
@@ -0,0 +1,47 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_funcs.h
+ *
+ * desc: AAS
+ *
+ * $Archive: /source/code/botlib/be_aas_funcs.h $
+ *
+ *****************************************************************************/
+
+#ifndef BSPCINCLUDE
+
+#include "be_aas_main.h"
+#include "be_aas_entity.h"
+#include "be_aas_sample.h"
+#include "be_aas_cluster.h"
+#include "be_aas_reach.h"
+#include "be_aas_route.h"
+#include "be_aas_routealt.h"
+#include "be_aas_debug.h"
+#include "be_aas_file.h"
+#include "be_aas_optimize.h"
+#include "be_aas_bsp.h"
+#include "be_aas_move.h"
+
+#endif //BSPCINCLUDE
diff --git a/code/botlib/be_aas_main.c b/code/botlib/be_aas_main.c
new file mode 100755
index 0000000..45a9dc3
--- /dev/null
+++ b/code/botlib/be_aas_main.c
@@ -0,0 +1,429 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_main.c
+ *
+ * desc: AAS
+ *
+ * $Archive: /MissionPack/code/botlib/be_aas_main.c $
+ *
+ *****************************************************************************/
+
+#include "../game/q_shared.h"
+#include "l_memory.h"
+#include "l_libvar.h"
+#include "l_utils.h"
+#include "l_script.h"
+#include "l_precomp.h"
+#include "l_struct.h"
+#include "l_log.h"
+#include "aasfile.h"
+#include "../game/botlib.h"
+#include "../game/be_aas.h"
+#include "be_aas_funcs.h"
+#include "be_interface.h"
+#include "be_aas_def.h"
+
+aas_t aasworld;
+
+libvar_t *saveroutingcache;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void QDECL AAS_Error(char *fmt, ...)
+{
+ char str[1024];
+ va_list arglist;
+
+ va_start(arglist, fmt);
+ vsprintf(str, fmt, arglist);
+ va_end(arglist);
+ botimport.Print(PRT_FATAL, str);
+} //end of the function AAS_Error
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+char *AAS_StringFromIndex(char *indexname, char *stringindex[], int numindexes, int index)
+{
+ if (!aasworld.indexessetup)
+ {
+ botimport.Print(PRT_ERROR, "%s: index %d not setup\n", indexname, index);
+ return "";
+ } //end if
+ if (index < 0 || index >= numindexes)
+ {
+ botimport.Print(PRT_ERROR, "%s: index %d out of range\n", indexname, index);
+ return "";
+ } //end if
+ if (!stringindex[index])
+ {
+ if (index)
+ {
+ botimport.Print(PRT_ERROR, "%s: reference to unused index %d\n", indexname, index);
+ } //end if
+ return "";
+ } //end if
+ return stringindex[index];
+} //end of the function AAS_StringFromIndex
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_IndexFromString(char *indexname, char *stringindex[], int numindexes, char *string)
+{
+ int i;
+ if (!aasworld.indexessetup)
+ {
+ botimport.Print(PRT_ERROR, "%s: index not setup \"%s\"\n", indexname, string);
+ return 0;
+ } //end if
+ for (i = 0; i < numindexes; i++)
+ {
+ if (!stringindex[i]) continue;
+ if (!Q_stricmp(stringindex[i], string)) return i;
+ } //end for
+ return 0;
+} //end of the function AAS_IndexFromString
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+char *AAS_ModelFromIndex(int index)
+{
+ return AAS_StringFromIndex("ModelFromIndex", &aasworld.configstrings[CS_MODELS], MAX_MODELS, index);
+} //end of the function AAS_ModelFromIndex
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_IndexFromModel(char *modelname)
+{
+ return AAS_IndexFromString("IndexFromModel", &aasworld.configstrings[CS_MODELS], MAX_MODELS, modelname);
+} //end of the function AAS_IndexFromModel
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_UpdateStringIndexes(int numconfigstrings, char *configstrings[])
+{
+ int i;
+ //set string pointers and copy the strings
+ for (i = 0; i < numconfigstrings; i++)
+ {
+ if (configstrings[i])
+ {
+ //if (aasworld.configstrings[i]) FreeMemory(aasworld.configstrings[i]);
+ aasworld.configstrings[i] = (char *) GetMemory(strlen(configstrings[i]) + 1);
+ strcpy(aasworld.configstrings[i], configstrings[i]);
+ } //end if
+ } //end for
+ aasworld.indexessetup = qtrue;
+} //end of the function AAS_UpdateStringIndexes
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_Loaded(void)
+{
+ return aasworld.loaded;
+} //end of the function AAS_Loaded
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_Initialized(void)
+{
+ return aasworld.initialized;
+} //end of the function AAS_Initialized
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_SetInitialized(void)
+{
+ aasworld.initialized = qtrue;
+ botimport.Print(PRT_MESSAGE, "AAS initialized.\n");
+#ifdef DEBUG
+ //create all the routing cache
+ //AAS_CreateAllRoutingCache();
+ //
+ //AAS_RoutingInfo();
+#endif
+} //end of the function AAS_SetInitialized
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ContinueInit(float time)
+{
+ //if no AAS file loaded
+ if (!aasworld.loaded) return;
+ //if AAS is already initialized
+ if (aasworld.initialized) return;
+ //calculate reachability, if not finished return
+ if (AAS_ContinueInitReachability(time)) return;
+ //initialize clustering for the new map
+ AAS_InitClustering();
+ //if reachability has been calculated and an AAS file should be written
+ //or there is a forced data optimization
+ if (aasworld.savefile || ((int)LibVarGetValue("forcewrite")))
+ {
+ //optimize the AAS data
+ if ((int)LibVarValue("aasoptimize", "0")) AAS_Optimize();
+ //save the AAS file
+ if (AAS_WriteAASFile(aasworld.filename))
+ {
+ botimport.Print(PRT_MESSAGE, "%s written succesfully\n", aasworld.filename);
+ } //end if
+ else
+ {
+ botimport.Print(PRT_ERROR, "couldn't write %s\n", aasworld.filename);
+ } //end else
+ } //end if
+ //initialize the routing
+ AAS_InitRouting();
+ //at this point AAS is initialized
+ AAS_SetInitialized();
+} //end of the function AAS_ContinueInit
+//===========================================================================
+// called at the start of every frame
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_StartFrame(float time)
+{
+ aasworld.time = time;
+ //unlink all entities that were not updated last frame
+ AAS_UnlinkInvalidEntities();
+ //invalidate the entities
+ AAS_InvalidateEntities();
+ //initialize AAS
+ AAS_ContinueInit(time);
+ //
+ aasworld.frameroutingupdates = 0;
+ //
+ if (bot_developer)
+ {
+ if (LibVarGetValue("showcacheupdates"))
+ {
+ AAS_RoutingInfo();
+ LibVarSet("showcacheupdates", "0");
+ } //end if
+ if (LibVarGetValue("showmemoryusage"))
+ {
+ PrintUsedMemorySize();
+ LibVarSet("showmemoryusage", "0");
+ } //end if
+ if (LibVarGetValue("memorydump"))
+ {
+ PrintMemoryLabels();
+ LibVarSet("memorydump", "0");
+ } //end if
+ } //end if
+ //
+ if (saveroutingcache->value)
+ {
+ AAS_WriteRouteCache();
+ LibVarSet("saveroutingcache", "0");
+ } //end if
+ //
+ aasworld.numframes++;
+ return BLERR_NOERROR;
+} //end of the function AAS_StartFrame
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float AAS_Time(void)
+{
+ return aasworld.time;
+} //end of the function AAS_Time
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ProjectPointOntoVector( vec3_t point, vec3_t vStart, vec3_t vEnd, vec3_t vProj )
+{
+ vec3_t pVec, vec;
+
+ VectorSubtract( point, vStart, pVec );
+ VectorSubtract( vEnd, vStart, vec );
+ VectorNormalize( vec );
+ // project onto the directional vector for this segment
+ VectorMA( vStart, DotProduct( pVec, vec ), vec, vProj );
+} //end of the function AAS_ProjectPointOntoVector
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_LoadFiles(const char *mapname)
+{
+ int errnum;
+ char aasfile[MAX_PATH];
+// char bspfile[MAX_PATH];
+
+ strcpy(aasworld.mapname, mapname);
+ //NOTE: first reset the entity links into the AAS areas and BSP leaves
+ // the AAS link heap and BSP link heap are reset after respectively the
+ // AAS file and BSP file are loaded
+ AAS_ResetEntityLinks();
+ // load bsp info
+ AAS_LoadBSPFile();
+
+ //load the aas file
+ Com_sprintf(aasfile, MAX_PATH, "maps/%s.aas", mapname);
+ errnum = AAS_LoadAASFile(aasfile);
+ if (errnum != BLERR_NOERROR)
+ return errnum;
+
+ botimport.Print(PRT_MESSAGE, "loaded %s\n", aasfile);
+ strncpy(aasworld.filename, aasfile, MAX_PATH);
+ return BLERR_NOERROR;
+} //end of the function AAS_LoadFiles
+//===========================================================================
+// called everytime a map changes
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_LoadMap(const char *mapname)
+{
+ int errnum;
+
+ //if no mapname is provided then the string indexes are updated
+ if (!mapname)
+ {
+ return 0;
+ } //end if
+ //
+ aasworld.initialized = qfalse;
+ //NOTE: free the routing caches before loading a new map because
+ // to free the caches the old number of areas, number of clusters
+ // and number of areas in a clusters must be available
+ AAS_FreeRoutingCaches();
+ //load the map
+ errnum = AAS_LoadFiles(mapname);
+ if (errnum != BLERR_NOERROR)
+ {
+ aasworld.loaded = qfalse;
+ return errnum;
+ } //end if
+ //
+ AAS_InitSettings();
+ //initialize the AAS link heap for the new map
+ AAS_InitAASLinkHeap();
+ //initialize the AAS linked entities for the new map
+ AAS_InitAASLinkedEntities();
+ //initialize reachability for the new map
+ AAS_InitReachability();
+ //initialize the alternative routing
+ AAS_InitAlternativeRouting();
+ //everything went ok
+ return 0;
+} //end of the function AAS_LoadMap
+//===========================================================================
+// called when the library is first loaded
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_Setup(void)
+{
+ aasworld.maxclients = (int) LibVarValue("maxclients", "128");
+ aasworld.maxentities = (int) LibVarValue("maxentities", "1024");
+ // as soon as it's set to 1 the routing cache will be saved
+ saveroutingcache = LibVar("saveroutingcache", "0");
+ //allocate memory for the entities
+ if (aasworld.entities) FreeMemory(aasworld.entities);
+ aasworld.entities = (aas_entity_t *) GetClearedHunkMemory(aasworld.maxentities * sizeof(aas_entity_t));
+ //invalidate all the entities
+ AAS_InvalidateEntities();
+ //force some recalculations
+ //LibVarSet("forceclustering", "1"); //force clustering calculation
+ //LibVarSet("forcereachability", "1"); //force reachability calculation
+ aasworld.numframes = 0;
+ return BLERR_NOERROR;
+} //end of the function AAS_Setup
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_Shutdown(void)
+{
+ AAS_ShutdownAlternativeRouting();
+ //
+ AAS_DumpBSPData();
+ //free routing caches
+ AAS_FreeRoutingCaches();
+ //free aas link heap
+ AAS_FreeAASLinkHeap();
+ //free aas linked entities
+ AAS_FreeAASLinkedEntities();
+ //free the aas data
+ AAS_DumpAASData();
+ //free the entities
+ if (aasworld.entities) FreeMemory(aasworld.entities);
+ //clear the aasworld structure
+ Com_Memset(&aasworld, 0, sizeof(aas_t));
+ //aas has not been initialized
+ aasworld.initialized = qfalse;
+ //NOTE: as soon as a new .bsp file is loaded the .bsp file memory is
+ // freed an reallocated, so there's no need to free that memory here
+ //print shutdown
+ botimport.Print(PRT_MESSAGE, "AAS shutdown.\n");
+} //end of the function AAS_Shutdown
diff --git a/code/botlib/be_aas_main.h b/code/botlib/be_aas_main.h
new file mode 100755
index 0000000..13564a9
--- /dev/null
+++ b/code/botlib/be_aas_main.h
@@ -0,0 +1,61 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_main.h
+ *
+ * desc: AAS
+ *
+ * $Archive: /source/code/botlib/be_aas_main.h $
+ *
+ *****************************************************************************/
+
+#ifdef AASINTERN
+
+extern aas_t aasworld;
+
+//AAS error message
+void QDECL AAS_Error(char *fmt, ...);
+//set AAS initialized
+void AAS_SetInitialized(void);
+//setup AAS with the given number of entities and clients
+int AAS_Setup(void);
+//shutdown AAS
+void AAS_Shutdown(void);
+//start a new map
+int AAS_LoadMap(const char *mapname);
+//start a new time frame
+int AAS_StartFrame(float time);
+#endif //AASINTERN
+
+//returns true if AAS is initialized
+int AAS_Initialized(void);
+//returns true if the AAS file is loaded
+int AAS_Loaded(void);
+//returns the model name from the given index
+char *AAS_ModelFromIndex(int index);
+//returns the index from the given model name
+int AAS_IndexFromModel(char *modelname);
+//returns the current time
+float AAS_Time(void);
+//
+void AAS_ProjectPointOntoVector( vec3_t point, vec3_t vStart, vec3_t vEnd, vec3_t vProj );
diff --git a/code/botlib/be_aas_move.c b/code/botlib/be_aas_move.c
new file mode 100755
index 0000000..d8b6cfd
--- /dev/null
+++ b/code/botlib/be_aas_move.c
@@ -0,0 +1,1101 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_move.c
+ *
+ * desc: AAS
+ *
+ * $Archive: /MissionPack/code/botlib/be_aas_move.c $
+ *
+ *****************************************************************************/
+
+#include "../game/q_shared.h"
+#include "l_memory.h"
+#include "l_script.h"
+#include "l_precomp.h"
+#include "l_struct.h"
+#include "l_libvar.h"
+#include "aasfile.h"
+#include "../game/botlib.h"
+#include "../game/be_aas.h"
+#include "be_aas_funcs.h"
+#include "be_aas_def.h"
+
+extern botlib_import_t botimport;
+
+aas_settings_t aassettings;
+
+//#define AAS_MOVE_DEBUG
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_DropToFloor(vec3_t origin, vec3_t mins, vec3_t maxs)
+{
+ vec3_t end;
+ bsp_trace_t trace;
+
+ VectorCopy(origin, end);
+ end[2] -= 100;
+ trace = AAS_Trace(origin, mins, maxs, end, 0, CONTENTS_SOLID);
+ if (trace.startsolid) return qfalse;
+ VectorCopy(trace.endpos, origin);
+ return qtrue;
+} //end of the function AAS_DropToFloor
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_InitSettings(void)
+{
+ aassettings.phys_gravitydirection[0] = 0;
+ aassettings.phys_gravitydirection[1] = 0;
+ aassettings.phys_gravitydirection[2] = -1;
+ aassettings.phys_friction = LibVarValue("phys_friction", "6");
+ aassettings.phys_stopspeed = LibVarValue("phys_stopspeed", "100");
+ aassettings.phys_gravity = LibVarValue("phys_gravity", "800");
+ aassettings.phys_waterfriction = LibVarValue("phys_waterfriction", "1");
+ aassettings.phys_watergravity = LibVarValue("phys_watergravity", "400");
+ aassettings.phys_maxvelocity = LibVarValue("phys_maxvelocity", "320");
+ aassettings.phys_maxwalkvelocity = LibVarValue("phys_maxwalkvelocity", "320");
+ aassettings.phys_maxcrouchvelocity = LibVarValue("phys_maxcrouchvelocity", "100");
+ aassettings.phys_maxswimvelocity = LibVarValue("phys_maxswimvelocity", "150");
+ aassettings.phys_walkaccelerate = LibVarValue("phys_walkaccelerate", "10");
+ aassettings.phys_airaccelerate = LibVarValue("phys_airaccelerate", "1");
+ aassettings.phys_swimaccelerate = LibVarValue("phys_swimaccelerate", "4");
+ aassettings.phys_maxstep = LibVarValue("phys_maxstep", "19");
+ aassettings.phys_maxsteepness = LibVarValue("phys_maxsteepness", "0.7");
+ aassettings.phys_maxwaterjump = LibVarValue("phys_maxwaterjump", "18");
+ aassettings.phys_maxbarrier = LibVarValue("phys_maxbarrier", "33");
+ aassettings.phys_jumpvel = LibVarValue("phys_jumpvel", "270");
+ aassettings.phys_falldelta5 = LibVarValue("phys_falldelta5", "40");
+ aassettings.phys_falldelta10 = LibVarValue("phys_falldelta10", "60");
+ aassettings.rs_waterjump = LibVarValue("rs_waterjump", "400");
+ aassettings.rs_teleport = LibVarValue("rs_teleport", "50");
+ aassettings.rs_barrierjump = LibVarValue("rs_barrierjump", "100");
+ aassettings.rs_startcrouch = LibVarValue("rs_startcrouch", "300");
+ aassettings.rs_startgrapple = LibVarValue("rs_startgrapple", "500");
+ aassettings.rs_startwalkoffledge = LibVarValue("rs_startwalkoffledge", "70");
+ aassettings.rs_startjump = LibVarValue("rs_startjump", "300");
+ aassettings.rs_rocketjump = LibVarValue("rs_rocketjump", "500");
+ aassettings.rs_bfgjump = LibVarValue("rs_bfgjump", "500");
+ aassettings.rs_jumppad = LibVarValue("rs_jumppad", "250");
+ aassettings.rs_aircontrolledjumppad = LibVarValue("rs_aircontrolledjumppad", "300");
+ aassettings.rs_funcbob = LibVarValue("rs_funcbob", "300");
+ aassettings.rs_startelevator = LibVarValue("rs_startelevator", "50");
+ aassettings.rs_falldamage5 = LibVarValue("rs_falldamage5", "300");
+ aassettings.rs_falldamage10 = LibVarValue("rs_falldamage10", "500");
+ aassettings.rs_maxfallheight = LibVarValue("rs_maxfallheight", "0");
+ aassettings.rs_maxjumpfallheight = LibVarValue("rs_maxjumpfallheight", "450");
+} //end of the function AAS_InitSettings
+//===========================================================================
+// returns qtrue if the bot is against a ladder
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_AgainstLadder(vec3_t origin)
+{
+ int areanum, i, facenum, side;
+ vec3_t org;
+ aas_plane_t *plane;
+ aas_face_t *face;
+ aas_area_t *area;
+
+ VectorCopy(origin, org);
+ areanum = AAS_PointAreaNum(org);
+ if (!areanum)
+ {
+ org[0] += 1;
+ areanum = AAS_PointAreaNum(org);
+ if (!areanum)
+ {
+ org[1] += 1;
+ areanum = AAS_PointAreaNum(org);
+ if (!areanum)
+ {
+ org[0] -= 2;
+ areanum = AAS_PointAreaNum(org);
+ if (!areanum)
+ {
+ org[1] -= 2;
+ areanum = AAS_PointAreaNum(org);
+ } //end if
+ } //end if
+ } //end if
+ } //end if
+ //if in solid... wrrr shouldn't happen
+ if (!areanum) return qfalse;
+ //if not in a ladder area
+ if (!(aasworld.areasettings[areanum].areaflags & AREA_LADDER)) return qfalse;
+ //if a crouch only area
+ if (!(aasworld.areasettings[areanum].presencetype & PRESENCE_NORMAL)) return qfalse;
+ //
+ area = &aasworld.areas[areanum];
+ for (i = 0; i < area->numfaces; i++)
+ {
+ facenum = aasworld.faceindex[area->firstface + i];
+ side = facenum < 0;
+ face = &aasworld.faces[abs(facenum)];
+ //if the face isn't a ladder face
+ if (!(face->faceflags & FACE_LADDER)) continue;
+ //get the plane the face is in
+ plane = &aasworld.planes[face->planenum ^ side];
+ //if the origin is pretty close to the plane
+ if (abs(DotProduct(plane->normal, origin) - plane->dist) < 3)
+ {
+ if (AAS_PointInsideFace(abs(facenum), origin, 0.1f)) return qtrue;
+ } //end if
+ } //end for
+ return qfalse;
+} //end of the function AAS_AgainstLadder
+//===========================================================================
+// returns qtrue if the bot is on the ground
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_OnGround(vec3_t origin, int presencetype, int passent)
+{
+ aas_trace_t trace;
+ vec3_t end, up = {0, 0, 1};
+ aas_plane_t *plane;
+
+ VectorCopy(origin, end);
+ end[2] -= 10;
+
+ trace = AAS_TraceClientBBox(origin, end, presencetype, passent);
+
+ //if in solid
+ if (trace.startsolid) return qfalse;
+ //if nothing hit at all
+ if (trace.fraction >= 1.0) return qfalse;
+ //if too far from the hit plane
+ if (origin[2] - trace.endpos[2] > 10) return qfalse;
+ //check if the plane isn't too steep
+ plane = AAS_PlaneFromNum(trace.planenum);
+ if (DotProduct(plane->normal, up) < aassettings.phys_maxsteepness) return qfalse;
+ //the bot is on the ground
+ return qtrue;
+} //end of the function AAS_OnGround
+//===========================================================================
+// returns qtrue if a bot at the given position is swimming
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_Swimming(vec3_t origin)
+{
+ vec3_t testorg;
+
+ VectorCopy(origin, testorg);
+ testorg[2] -= 2;
+ if (AAS_PointContents(testorg) & (CONTENTS_LAVA|CONTENTS_SLIME|CONTENTS_WATER)) return qtrue;
+ return qfalse;
+} //end of the function AAS_Swimming
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+static vec3_t VEC_UP = {0, -1, 0};
+static vec3_t MOVEDIR_UP = {0, 0, 1};
+static vec3_t VEC_DOWN = {0, -2, 0};
+static vec3_t MOVEDIR_DOWN = {0, 0, -1};
+
+void AAS_SetMovedir(vec3_t angles, vec3_t movedir)
+{
+ if (VectorCompare(angles, VEC_UP))
+ {
+ VectorCopy(MOVEDIR_UP, movedir);
+ } //end if
+ else if (VectorCompare(angles, VEC_DOWN))
+ {
+ VectorCopy(MOVEDIR_DOWN, movedir);
+ } //end else if
+ else
+ {
+ AngleVectors(angles, movedir, NULL, NULL);
+ } //end else
+} //end of the function AAS_SetMovedir
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_JumpReachRunStart(aas_reachability_t *reach, vec3_t runstart)
+{
+ vec3_t hordir, start, cmdmove;
+ aas_clientmove_t move;
+
+ //
+ hordir[0] = reach->start[0] - reach->end[0];
+ hordir[1] = reach->start[1] - reach->end[1];
+ hordir[2] = 0;
+ VectorNormalize(hordir);
+ //start point
+ VectorCopy(reach->start, start);
+ start[2] += 1;
+ //get command movement
+ VectorScale(hordir, 400, cmdmove);
+ //
+ AAS_PredictClientMovement(&move, -1, start, PRESENCE_NORMAL, qtrue,
+ vec3_origin, cmdmove, 1, 2, 0.1f,
+ SE_ENTERWATER|SE_ENTERSLIME|SE_ENTERLAVA|
+ SE_HITGROUNDDAMAGE|SE_GAP, 0, qfalse);
+ VectorCopy(move.endpos, runstart);
+ //don't enter slime or lava and don't fall from too high
+ if (move.stopevent & (SE_ENTERSLIME|SE_ENTERLAVA|SE_HITGROUNDDAMAGE))
+ {
+ VectorCopy(start, runstart);
+ } //end if
+} //end of the function AAS_JumpReachRunStart
+//===========================================================================
+// returns the Z velocity when rocket jumping at the origin
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float AAS_WeaponJumpZVelocity(vec3_t origin, float radiusdamage)
+{
+ vec3_t kvel, v, start, end, forward, right, viewangles, dir;
+ float mass, knockback, points;
+ vec3_t rocketoffset = {8, 8, -8};
+ vec3_t botmins = {-16, -16, -24};
+ vec3_t botmaxs = {16, 16, 32};
+ bsp_trace_t bsptrace;
+
+ //look down (90 degrees)
+ viewangles[PITCH] = 90;
+ viewangles[YAW] = 0;
+ viewangles[ROLL] = 0;
+ //get the start point shooting from
+ VectorCopy(origin, start);
+ start[2] += 8; //view offset Z
+ AngleVectors(viewangles, forward, right, NULL);
+ start[0] += forward[0] * rocketoffset[0] + right[0] * rocketoffset[1];
+ start[1] += forward[1] * rocketoffset[0] + right[1] * rocketoffset[1];
+ start[2] += forward[2] * rocketoffset[0] + right[2] * rocketoffset[1] + rocketoffset[2];
+ //end point of the trace
+ VectorMA(start, 500, forward, end);
+ //trace a line to get the impact point
+ bsptrace = AAS_Trace(start, NULL, NULL, end, 1, CONTENTS_SOLID);
+ //calculate the damage the bot will get from the rocket impact
+ VectorAdd(botmins, botmaxs, v);
+ VectorMA(origin, 0.5, v, v);
+ VectorSubtract(bsptrace.endpos, v, v);
+ //
+ points = radiusdamage - 0.5 * VectorLength(v);
+ if (points < 0) points = 0;
+ //the owner of the rocket gets half the damage
+ points *= 0.5;
+ //mass of the bot (p_client.c: PutClientInServer)
+ mass = 200;
+ //knockback is the same as the damage points
+ knockback = points;
+ //direction of the damage (from trace.endpos to bot origin)
+ VectorSubtract(origin, bsptrace.endpos, dir);
+ VectorNormalize(dir);
+ //damage velocity
+ VectorScale(dir, 1600.0 * (float)knockback / mass, kvel); //the rocket jump hack...
+ //rocket impact velocity + jump velocity
+ return kvel[2] + aassettings.phys_jumpvel;
+} //end of the function AAS_WeaponJumpZVelocity
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float AAS_RocketJumpZVelocity(vec3_t origin)
+{
+ //rocket radius damage is 120 (p_weapon.c: Weapon_RocketLauncher_Fire)
+ return AAS_WeaponJumpZVelocity(origin, 120);
+} //end of the function AAS_RocketJumpZVelocity
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float AAS_BFGJumpZVelocity(vec3_t origin)
+{
+ //bfg radius damage is 1000 (p_weapon.c: weapon_bfg_fire)
+ return AAS_WeaponJumpZVelocity(origin, 120);
+} //end of the function AAS_BFGJumpZVelocity
+//===========================================================================
+// applies ground friction to the given velocity
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_Accelerate(vec3_t velocity, float frametime, vec3_t wishdir, float wishspeed, float accel)
+{
+ // q2 style
+ int i;
+ float addspeed, accelspeed, currentspeed;
+
+ currentspeed = DotProduct(velocity, wishdir);
+ addspeed = wishspeed - currentspeed;
+ if (addspeed <= 0) {
+ return;
+ }
+ accelspeed = accel*frametime*wishspeed;
+ if (accelspeed > addspeed) {
+ accelspeed = addspeed;
+ }
+
+ for (i=0 ; i<3 ; i++) {
+ velocity[i] += accelspeed*wishdir[i];
+ }
+} //end of the function AAS_Accelerate
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_AirControl(vec3_t start, vec3_t end, vec3_t velocity, vec3_t cmdmove)
+{
+ vec3_t dir;
+
+ VectorSubtract(end, start, dir);
+} //end of the function AAS_AirControl
+//===========================================================================
+// applies ground friction to the given velocity
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ApplyFriction(vec3_t vel, float friction, float stopspeed,
+ float frametime)
+{
+ float speed, control, newspeed;
+
+ //horizontal speed
+ speed = sqrt(vel[0] * vel[0] + vel[1] * vel[1]);
+ if (speed)
+ {
+ control = speed < stopspeed ? stopspeed : speed;
+ newspeed = speed - frametime * control * friction;
+ if (newspeed < 0) newspeed = 0;
+ newspeed /= speed;
+ vel[0] *= newspeed;
+ vel[1] *= newspeed;
+ } //end if
+} //end of the function AAS_ApplyFriction
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_ClipToBBox(aas_trace_t *trace, vec3_t start, vec3_t end, int presencetype, vec3_t mins, vec3_t maxs)
+{
+ int i, j, side;
+ float front, back, frac, planedist;
+ vec3_t bboxmins, bboxmaxs, absmins, absmaxs, dir, mid;
+
+ AAS_PresenceTypeBoundingBox(presencetype, bboxmins, bboxmaxs);
+ VectorSubtract(mins, bboxmaxs, absmins);
+ VectorSubtract(maxs, bboxmins, absmaxs);
+ //
+ VectorCopy(end, trace->endpos);
+ trace->fraction = 1;
+ for (i = 0; i < 3; i++)
+ {
+ if (start[i] < absmins[i] && end[i] < absmins[i]) return qfalse;
+ if (start[i] > absmaxs[i] && end[i] > absmaxs[i]) return qfalse;
+ } //end for
+ //check bounding box collision
+ VectorSubtract(end, start, dir);
+ frac = 1;
+ for (i = 0; i < 3; i++)
+ {
+ //get plane to test collision with for the current axis direction
+ if (dir[i] > 0) planedist = absmins[i];
+ else planedist = absmaxs[i];
+ //calculate collision fraction
+ front = start[i] - planedist;
+ back = end[i] - planedist;
+ frac = front / (front-back);
+ //check if between bounding planes of next axis
+ side = i + 1;
+ if (side > 2) side = 0;
+ mid[side] = start[side] + dir[side] * frac;
+ if (mid[side] > absmins[side] && mid[side] < absmaxs[side])
+ {
+ //check if between bounding planes of next axis
+ side++;
+ if (side > 2) side = 0;
+ mid[side] = start[side] + dir[side] * frac;
+ if (mid[side] > absmins[side] && mid[side] < absmaxs[side])
+ {
+ mid[i] = planedist;
+ break;
+ } //end if
+ } //end if
+ } //end for
+ //if there was a collision
+ if (i != 3)
+ {
+ trace->startsolid = qfalse;
+ trace->fraction = frac;
+ trace->ent = 0;
+ trace->planenum = 0;
+ trace->area = 0;
+ trace->lastarea = 0;
+ //trace endpos
+ for (j = 0; j < 3; j++) trace->endpos[j] = start[j] + dir[j] * frac;
+ return qtrue;
+ } //end if
+ return qfalse;
+} //end of the function AAS_ClipToBBox
+//===========================================================================
+// predicts the movement
+// assumes regular bounding box sizes
+// NOTE: out of water jumping is not included
+// NOTE: grappling hook is not included
+//
+// Parameter: origin : origin to start with
+// presencetype : presence type to start with
+// velocity : velocity to start with
+// cmdmove : client command movement
+// cmdframes : number of frame cmdmove is valid
+// maxframes : maximum number of predicted frames
+// frametime : duration of one predicted frame
+// stopevent : events that stop the prediction
+// stopareanum : stop as soon as entered this area
+// Returns: aas_clientmove_t
+// Changes Globals: -
+//===========================================================================
+int AAS_ClientMovementPrediction(struct aas_clientmove_s *move,
+ int entnum, vec3_t origin,
+ int presencetype, int onground,
+ vec3_t velocity, vec3_t cmdmove,
+ int cmdframes,
+ int maxframes, float frametime,
+ int stopevent, int stopareanum,
+ vec3_t mins, vec3_t maxs, int visualize)
+{
+ float phys_friction, phys_stopspeed, phys_gravity, phys_waterfriction;
+ float phys_watergravity;
+ float phys_walkaccelerate, phys_airaccelerate, phys_swimaccelerate;
+ float phys_maxwalkvelocity, phys_maxcrouchvelocity, phys_maxswimvelocity;
+ float phys_maxstep, phys_maxsteepness, phys_jumpvel, friction;
+ float gravity, delta, maxvel, wishspeed, accelerate;
+ //float velchange, newvel;
+ int n, i, j, pc, step, swimming, ax, crouch, event, jump_frame, areanum;
+ int areas[20], numareas;
+ vec3_t points[20];
+ vec3_t org, end, feet, start, stepend, lastorg, wishdir;
+ vec3_t frame_test_vel, old_frame_test_vel, left_test_vel;
+ vec3_t up = {0, 0, 1};
+ aas_plane_t *plane, *plane2;
+ aas_trace_t trace, steptrace;
+
+ if (frametime <= 0) frametime = 0.1f;
+ //
+ phys_friction = aassettings.phys_friction;
+ phys_stopspeed = aassettings.phys_stopspeed;
+ phys_gravity = aassettings.phys_gravity;
+ phys_waterfriction = aassettings.phys_waterfriction;
+ phys_watergravity = aassettings.phys_watergravity;
+ phys_maxwalkvelocity = aassettings.phys_maxwalkvelocity;// * frametime;
+ phys_maxcrouchvelocity = aassettings.phys_maxcrouchvelocity;// * frametime;
+ phys_maxswimvelocity = aassettings.phys_maxswimvelocity;// * frametime;
+ phys_walkaccelerate = aassettings.phys_walkaccelerate;
+ phys_airaccelerate = aassettings.phys_airaccelerate;
+ phys_swimaccelerate = aassettings.phys_swimaccelerate;
+ phys_maxstep = aassettings.phys_maxstep;
+ phys_maxsteepness = aassettings.phys_maxsteepness;
+ phys_jumpvel = aassettings.phys_jumpvel * frametime;
+ //
+ Com_Memset(move, 0, sizeof(aas_clientmove_t));
+ Com_Memset(&trace, 0, sizeof(aas_trace_t));
+ //start at the current origin
+ VectorCopy(origin, org);
+ org[2] += 0.25;
+ //velocity to test for the first frame
+ VectorScale(velocity, frametime, frame_test_vel);
+ //
+ jump_frame = -1;
+ //predict a maximum of 'maxframes' ahead
+ for (n = 0; n < maxframes; n++)
+ {
+ swimming = AAS_Swimming(org);
+ //get gravity depending on swimming or not
+ gravity = swimming ? phys_watergravity : phys_gravity;
+ //apply gravity at the START of the frame
+ frame_test_vel[2] = frame_test_vel[2] - (gravity * 0.1 * frametime);
+ //if on the ground or swimming
+ if (onground || swimming)
+ {
+ friction = swimming ? phys_friction : phys_waterfriction;
+ //apply friction
+ VectorScale(frame_test_vel, 1/frametime, frame_test_vel);
+ AAS_ApplyFriction(frame_test_vel, friction, phys_stopspeed, frametime);
+ VectorScale(frame_test_vel, frametime, frame_test_vel);
+ } //end if
+ crouch = qfalse;
+ //apply command movement
+ if (n < cmdframes)
+ {
+ ax = 0;
+ maxvel = phys_maxwalkvelocity;
+ accelerate = phys_airaccelerate;
+ VectorCopy(cmdmove, wishdir);
+ if (onground)
+ {
+ if (cmdmove[2] < -300)
+ {
+ crouch = qtrue;
+ maxvel = phys_maxcrouchvelocity;
+ } //end if
+ //if not swimming and upmove is positive then jump
+ if (!swimming && cmdmove[2] > 1)
+ {
+ //jump velocity minus the gravity for one frame + 5 for safety
+ frame_test_vel[2] = phys_jumpvel - (gravity * 0.1 * frametime) + 5;
+ jump_frame = n;
+ //jumping so air accelerate
+ accelerate = phys_airaccelerate;
+ } //end if
+ else
+ {
+ accelerate = phys_walkaccelerate;
+ } //end else
+ ax = 2;
+ } //end if
+ if (swimming)
+ {
+ maxvel = phys_maxswimvelocity;
+ accelerate = phys_swimaccelerate;
+ ax = 3;
+ } //end if
+ else
+ {
+ wishdir[2] = 0;
+ } //end else
+ //
+ wishspeed = VectorNormalize(wishdir);
+ if (wishspeed > maxvel) wishspeed = maxvel;
+ VectorScale(frame_test_vel, 1/frametime, frame_test_vel);
+ AAS_Accelerate(frame_test_vel, frametime, wishdir, wishspeed, accelerate);
+ VectorScale(frame_test_vel, frametime, frame_test_vel);
+ /*
+ for (i = 0; i < ax; i++)
+ {
+ velchange = (cmdmove[i] * frametime) - frame_test_vel[i];
+ if (velchange > phys_maxacceleration) velchange = phys_maxacceleration;
+ else if (velchange < -phys_maxacceleration) velchange = -phys_maxacceleration;
+ newvel = frame_test_vel[i] + velchange;
+ //
+ if (frame_test_vel[i] <= maxvel && newvel > maxvel) frame_test_vel[i] = maxvel;
+ else if (frame_test_vel[i] >= -maxvel && newvel < -maxvel) frame_test_vel[i] = -maxvel;
+ else frame_test_vel[i] = newvel;
+ } //end for
+ */
+ } //end if
+ if (crouch)
+ {
+ presencetype = PRESENCE_CROUCH;
+ } //end if
+ else if (presencetype == PRESENCE_CROUCH)
+ {
+ if (AAS_PointPresenceType(org) & PRESENCE_NORMAL)
+ {
+ presencetype = PRESENCE_NORMAL;
+ } //end if
+ } //end else
+ //save the current origin
+ VectorCopy(org, lastorg);
+ //move linear during one frame
+ VectorCopy(frame_test_vel, left_test_vel);
+ j = 0;
+ do
+ {
+ VectorAdd(org, left_test_vel, end);
+ //trace a bounding box
+ trace = AAS_TraceClientBBox(org, end, presencetype, entnum);
+ //
+//#ifdef AAS_MOVE_DEBUG
+ if (visualize)
+ {
+ if (trace.startsolid) botimport.Print(PRT_MESSAGE, "PredictMovement: start solid\n");
+ AAS_DebugLine(org, trace.endpos, LINECOLOR_RED);
+ } //end if
+//#endif //AAS_MOVE_DEBUG
+ //
+ if (stopevent & (SE_ENTERAREA|SE_TOUCHJUMPPAD|SE_TOUCHTELEPORTER|SE_TOUCHCLUSTERPORTAL))
+ {
+ numareas = AAS_TraceAreas(org, trace.endpos, areas, points, 20);
+ for (i = 0; i < numareas; i++)
+ {
+ if (stopevent & SE_ENTERAREA)
+ {
+ if (areas[i] == stopareanum)
+ {
+ VectorCopy(points[i], move->endpos);
+ VectorScale(frame_test_vel, 1/frametime, move->velocity);
+ move->endarea = areas[i];
+ move->trace = trace;
+ move->stopevent = SE_ENTERAREA;
+ move->presencetype = presencetype;
+ move->endcontents = 0;
+ move->time = n * frametime;
+ move->frames = n;
+ return qtrue;
+ } //end if
+ } //end if
+ //NOTE: if not the first frame
+ if ((stopevent & SE_TOUCHJUMPPAD) && n)
+ {
+ if (aasworld.areasettings[areas[i]].contents & AREACONTENTS_JUMPPAD)
+ {
+ VectorCopy(points[i], move->endpos);
+ VectorScale(frame_test_vel, 1/frametime, move->velocity);
+ move->endarea = areas[i];
+ move->trace = trace;
+ move->stopevent = SE_TOUCHJUMPPAD;
+ move->presencetype = presencetype;
+ move->endcontents = 0;
+ move->time = n * frametime;
+ move->frames = n;
+ return qtrue;
+ } //end if
+ } //end if
+ if (stopevent & SE_TOUCHTELEPORTER)
+ {
+ if (aasworld.areasettings[areas[i]].contents & AREACONTENTS_TELEPORTER)
+ {
+ VectorCopy(points[i], move->endpos);
+ move->endarea = areas[i];
+ VectorScale(frame_test_vel, 1/frametime, move->velocity);
+ move->trace = trace;
+ move->stopevent = SE_TOUCHTELEPORTER;
+ move->presencetype = presencetype;
+ move->endcontents = 0;
+ move->time = n * frametime;
+ move->frames = n;
+ return qtrue;
+ } //end if
+ } //end if
+ if (stopevent & SE_TOUCHCLUSTERPORTAL)
+ {
+ if (aasworld.areasettings[areas[i]].contents & AREACONTENTS_CLUSTERPORTAL)
+ {
+ VectorCopy(points[i], move->endpos);
+ move->endarea = areas[i];
+ VectorScale(frame_test_vel, 1/frametime, move->velocity);
+ move->trace = trace;
+ move->stopevent = SE_TOUCHCLUSTERPORTAL;
+ move->presencetype = presencetype;
+ move->endcontents = 0;
+ move->time = n * frametime;
+ move->frames = n;
+ return qtrue;
+ } //end if
+ } //end if
+ } //end for
+ } //end if
+ //
+ if (stopevent & SE_HITBOUNDINGBOX)
+ {
+ if (AAS_ClipToBBox(&trace, org, trace.endpos, presencetype, mins, maxs))
+ {
+ VectorCopy(trace.endpos, move->endpos);
+ move->endarea = AAS_PointAreaNum(move->endpos);
+ VectorScale(frame_test_vel, 1/frametime, move->velocity);
+ move->trace = trace;
+ move->stopevent = SE_HITBOUNDINGBOX;
+ move->presencetype = presencetype;
+ move->endcontents = 0;
+ move->time = n * frametime;
+ move->frames = n;
+ return qtrue;
+ } //end if
+ } //end if
+ //move the entity to the trace end point
+ VectorCopy(trace.endpos, org);
+ //if there was a collision
+ if (trace.fraction < 1.0)
+ {
+ //get the plane the bounding box collided with
+ plane = AAS_PlaneFromNum(trace.planenum);
+ //
+ if (stopevent & SE_HITGROUNDAREA)
+ {
+ if (DotProduct(plane->normal, up) > phys_maxsteepness)
+ {
+ VectorCopy(org, start);
+ start[2] += 0.5;
+ if (AAS_PointAreaNum(start) == stopareanum)
+ {
+ VectorCopy(start, move->endpos);
+ move->endarea = stopareanum;
+ VectorScale(frame_test_vel, 1/frametime, move->velocity);
+ move->trace = trace;
+ move->stopevent = SE_HITGROUNDAREA;
+ move->presencetype = presencetype;
+ move->endcontents = 0;
+ move->time = n * frametime;
+ move->frames = n;
+ return qtrue;
+ } //end if
+ } //end if
+ } //end if
+ //assume there's no step
+ step = qfalse;
+ //if it is a vertical plane and the bot didn't jump recently
+ if (plane->normal[2] == 0 && (jump_frame < 0 || n - jump_frame > 2))
+ {
+ //check for a step
+ VectorMA(org, -0.25, plane->normal, start);
+ VectorCopy(start, stepend);
+ start[2] += phys_maxstep;
+ steptrace = AAS_TraceClientBBox(start, stepend, presencetype, entnum);
+ //
+ if (!steptrace.startsolid)
+ {
+ plane2 = AAS_PlaneFromNum(steptrace.planenum);
+ if (DotProduct(plane2->normal, up) > phys_maxsteepness)
+ {
+ VectorSubtract(end, steptrace.endpos, left_test_vel);
+ left_test_vel[2] = 0;
+ frame_test_vel[2] = 0;
+//#ifdef AAS_MOVE_DEBUG
+ if (visualize)
+ {
+ if (steptrace.endpos[2] - org[2] > 0.125)
+ {
+ VectorCopy(org, start);
+ start[2] = steptrace.endpos[2];
+ AAS_DebugLine(org, start, LINECOLOR_BLUE);
+ } //end if
+ } //end if
+//#endif //AAS_MOVE_DEBUG
+ org[2] = steptrace.endpos[2];
+ step = qtrue;
+ } //end if
+ } //end if
+ } //end if
+ //
+ if (!step)
+ {
+ //velocity left to test for this frame is the projection
+ //of the current test velocity into the hit plane
+ VectorMA(left_test_vel, -DotProduct(left_test_vel, plane->normal),
+ plane->normal, left_test_vel);
+ //store the old velocity for landing check
+ VectorCopy(frame_test_vel, old_frame_test_vel);
+ //test velocity for the next frame is the projection
+ //of the velocity of the current frame into the hit plane
+ VectorMA(frame_test_vel, -DotProduct(frame_test_vel, plane->normal),
+ plane->normal, frame_test_vel);
+ //check for a landing on an almost horizontal floor
+ if (DotProduct(plane->normal, up) > phys_maxsteepness)
+ {
+ onground = qtrue;
+ } //end if
+ if (stopevent & SE_HITGROUNDDAMAGE)
+ {
+ delta = 0;
+ if (old_frame_test_vel[2] < 0 &&
+ frame_test_vel[2] > old_frame_test_vel[2] &&
+ !onground)
+ {
+ delta = old_frame_test_vel[2];
+ } //end if
+ else if (onground)
+ {
+ delta = frame_test_vel[2] - old_frame_test_vel[2];
+ } //end else
+ if (delta)
+ {
+ delta = delta * 10;
+ delta = delta * delta * 0.0001;
+ if (swimming) delta = 0;
+ // never take falling damage if completely underwater
+ /*
+ if (ent->waterlevel == 3) return;
+ if (ent->waterlevel == 2) delta *= 0.25;
+ if (ent->waterlevel == 1) delta *= 0.5;
+ */
+ if (delta > 40)
+ {
+ VectorCopy(org, move->endpos);
+ move->endarea = AAS_PointAreaNum(org);
+ VectorCopy(frame_test_vel, move->velocity);
+ move->trace = trace;
+ move->stopevent = SE_HITGROUNDDAMAGE;
+ move->presencetype = presencetype;
+ move->endcontents = 0;
+ move->time = n * frametime;
+ move->frames = n;
+ return qtrue;
+ } //end if
+ } //end if
+ } //end if
+ } //end if
+ } //end if
+ //extra check to prevent endless loop
+ if (++j > 20) return qfalse;
+ //while there is a plane hit
+ } while(trace.fraction < 1.0);
+ //if going down
+ if (frame_test_vel[2] <= 10)
+ {
+ //check for a liquid at the feet of the bot
+ VectorCopy(org, feet);
+ feet[2] -= 22;
+ pc = AAS_PointContents(feet);
+ //get event from pc
+ event = SE_NONE;
+ if (pc & CONTENTS_LAVA) event |= SE_ENTERLAVA;
+ if (pc & CONTENTS_SLIME) event |= SE_ENTERSLIME;
+ if (pc & CONTENTS_WATER) event |= SE_ENTERWATER;
+ //
+ areanum = AAS_PointAreaNum(org);
+ if (aasworld.areasettings[areanum].contents & AREACONTENTS_LAVA)
+ event |= SE_ENTERLAVA;
+ if (aasworld.areasettings[areanum].contents & AREACONTENTS_SLIME)
+ event |= SE_ENTERSLIME;
+ if (aasworld.areasettings[areanum].contents & AREACONTENTS_WATER)
+ event |= SE_ENTERWATER;
+ //if in lava or slime
+ if (event & stopevent)
+ {
+ VectorCopy(org, move->endpos);
+ move->endarea = areanum;
+ VectorScale(frame_test_vel, 1/frametime, move->velocity);
+ move->stopevent = event & stopevent;
+ move->presencetype = presencetype;
+ move->endcontents = pc;
+ move->time = n * frametime;
+ move->frames = n;
+ return qtrue;
+ } //end if
+ } //end if
+ //
+ onground = AAS_OnGround(org, presencetype, entnum);
+ //if onground and on the ground for at least one whole frame
+ if (onground)
+ {
+ if (stopevent & SE_HITGROUND)
+ {
+ VectorCopy(org, move->endpos);
+ move->endarea = AAS_PointAreaNum(org);
+ VectorScale(frame_test_vel, 1/frametime, move->velocity);
+ move->trace = trace;
+ move->stopevent = SE_HITGROUND;
+ move->presencetype = presencetype;
+ move->endcontents = 0;
+ move->time = n * frametime;
+ move->frames = n;
+ return qtrue;
+ } //end if
+ } //end if
+ else if (stopevent & SE_LEAVEGROUND)
+ {
+ VectorCopy(org, move->endpos);
+ move->endarea = AAS_PointAreaNum(org);
+ VectorScale(frame_test_vel, 1/frametime, move->velocity);
+ move->trace = trace;
+ move->stopevent = SE_LEAVEGROUND;
+ move->presencetype = presencetype;
+ move->endcontents = 0;
+ move->time = n * frametime;
+ move->frames = n;
+ return qtrue;
+ } //end else if
+ else if (stopevent & SE_GAP)
+ {
+ aas_trace_t gaptrace;
+
+ VectorCopy(org, start);
+ VectorCopy(start, end);
+ end[2] -= 48 + aassettings.phys_maxbarrier;
+ gaptrace = AAS_TraceClientBBox(start, end, PRESENCE_CROUCH, -1);
+ //if solid is found the bot cannot walk any further and will not fall into a gap
+ if (!gaptrace.startsolid)
+ {
+ //if it is a gap (lower than one step height)
+ if (gaptrace.endpos[2] < org[2] - aassettings.phys_maxstep - 1)
+ {
+ if (!(AAS_PointContents(end) & CONTENTS_WATER))
+ {
+ VectorCopy(lastorg, move->endpos);
+ move->endarea = AAS_PointAreaNum(lastorg);
+ VectorScale(frame_test_vel, 1/frametime, move->velocity);
+ move->trace = trace;
+ move->stopevent = SE_GAP;
+ move->presencetype = presencetype;
+ move->endcontents = 0;
+ move->time = n * frametime;
+ move->frames = n;
+ return qtrue;
+ } //end if
+ } //end if
+ } //end if
+ } //end else if
+ } //end for
+ //
+ VectorCopy(org, move->endpos);
+ move->endarea = AAS_PointAreaNum(org);
+ VectorScale(frame_test_vel, 1/frametime, move->velocity);
+ move->stopevent = SE_NONE;
+ move->presencetype = presencetype;
+ move->endcontents = 0;
+ move->time = n * frametime;
+ move->frames = n;
+ //
+ return qtrue;
+} //end of the function AAS_ClientMovementPrediction
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_PredictClientMovement(struct aas_clientmove_s *move,
+ int entnum, vec3_t origin,
+ int presencetype, int onground,
+ vec3_t velocity, vec3_t cmdmove,
+ int cmdframes,
+ int maxframes, float frametime,
+ int stopevent, int stopareanum, int visualize)
+{
+ vec3_t mins, maxs;
+ return AAS_ClientMovementPrediction(move, entnum, origin, presencetype, onground,
+ velocity, cmdmove, cmdframes, maxframes,
+ frametime, stopevent, stopareanum,
+ mins, maxs, visualize);
+} //end of the function AAS_PredictClientMovement
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_ClientMovementHitBBox(struct aas_clientmove_s *move,
+ int entnum, vec3_t origin,
+ int presencetype, int onground,
+ vec3_t velocity, vec3_t cmdmove,
+ int cmdframes,
+ int maxframes, float frametime,
+ vec3_t mins, vec3_t maxs, int visualize)
+{
+ return AAS_ClientMovementPrediction(move, entnum, origin, presencetype, onground,
+ velocity, cmdmove, cmdframes, maxframes,
+ frametime, SE_HITBOUNDINGBOX, 0,
+ mins, maxs, visualize);
+} //end of the function AAS_ClientMovementHitBBox
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_TestMovementPrediction(int entnum, vec3_t origin, vec3_t dir)
+{
+ vec3_t velocity, cmdmove;
+ aas_clientmove_t move;
+
+ VectorClear(velocity);
+ if (!AAS_Swimming(origin)) dir[2] = 0;
+ VectorNormalize(dir);
+ VectorScale(dir, 400, cmdmove);
+ cmdmove[2] = 224;
+ AAS_ClearShownDebugLines();
+ AAS_PredictClientMovement(&move, entnum, origin, PRESENCE_NORMAL, qtrue,
+ velocity, cmdmove, 13, 13, 0.1f, SE_HITGROUND, 0, qtrue);//SE_LEAVEGROUND);
+ if (move.stopevent & SE_LEAVEGROUND)
+ {
+ botimport.Print(PRT_MESSAGE, "leave ground\n");
+ } //end if
+} //end of the function TestMovementPrediction
+//===========================================================================
+// calculates the horizontal velocity needed to perform a jump from start
+// to end
+//
+// Parameter: zvel : z velocity for jump
+// start : start position of jump
+// end : end position of jump
+// *speed : returned speed for jump
+// Returns: qfalse if too high or too far from start to end
+// Changes Globals: -
+//===========================================================================
+int AAS_HorizontalVelocityForJump(float zvel, vec3_t start, vec3_t end, float *velocity)
+{
+ float phys_gravity, phys_maxvelocity;
+ float maxjump, height2fall, t, top;
+ vec3_t dir;
+
+ phys_gravity = aassettings.phys_gravity;
+ phys_maxvelocity = aassettings.phys_maxvelocity;
+
+ //maximum height a player can jump with the given initial z velocity
+ maxjump = 0.5 * phys_gravity * (zvel / phys_gravity) * (zvel / phys_gravity);
+ //top of the parabolic jump
+ top = start[2] + maxjump;
+ //height the bot will fall from the top
+ height2fall = top - end[2];
+ //if the goal is to high to jump to
+ if (height2fall < 0)
+ {
+ *velocity = phys_maxvelocity;
+ return 0;
+ } //end if
+ //time a player takes to fall the height
+ t = sqrt(height2fall / (0.5 * phys_gravity));
+ //direction from start to end
+ VectorSubtract(end, start, dir);
+ //
+ if ( (t + zvel / phys_gravity) == 0.0f ) {
+ *velocity = phys_maxvelocity;
+ return 0;
+ }
+ //calculate horizontal speed
+ *velocity = sqrt(dir[0]*dir[0] + dir[1]*dir[1]) / (t + zvel / phys_gravity);
+ //the horizontal speed must be lower than the max speed
+ if (*velocity > phys_maxvelocity)
+ {
+ *velocity = phys_maxvelocity;
+ return 0;
+ } //end if
+ return 1;
+} //end of the function AAS_HorizontalVelocityForJump
diff --git a/code/botlib/be_aas_move.h b/code/botlib/be_aas_move.h
new file mode 100755
index 0000000..5b491a4
--- /dev/null
+++ b/code/botlib/be_aas_move.h
@@ -0,0 +1,71 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_move.h
+ *
+ * desc: AAS
+ *
+ * $Archive: /source/code/botlib/be_aas_move.h $
+ *
+ *****************************************************************************/
+
+#ifdef AASINTERN
+extern aas_settings_t aassettings;
+#endif //AASINTERN
+
+//movement prediction
+int AAS_PredictClientMovement(struct aas_clientmove_s *move,
+ int entnum, vec3_t origin,
+ int presencetype, int onground,
+ vec3_t velocity, vec3_t cmdmove,
+ int cmdframes,
+ int maxframes, float frametime,
+ int stopevent, int stopareanum, int visualize);
+//predict movement until bounding box is hit
+int AAS_ClientMovementHitBBox(struct aas_clientmove_s *move,
+ int entnum, vec3_t origin,
+ int presencetype, int onground,
+ vec3_t velocity, vec3_t cmdmove,
+ int cmdframes,
+ int maxframes, float frametime,
+ vec3_t mins, vec3_t maxs, int visualize);
+//returns true if on the ground at the given origin
+int AAS_OnGround(vec3_t origin, int presencetype, int passent);
+//returns true if swimming at the given origin
+int AAS_Swimming(vec3_t origin);
+//returns the jump reachability run start point
+void AAS_JumpReachRunStart(struct aas_reachability_s *reach, vec3_t runstart);
+//returns true if against a ladder at the given origin
+int AAS_AgainstLadder(vec3_t origin);
+//rocket jump Z velocity when rocket-jumping at origin
+float AAS_RocketJumpZVelocity(vec3_t origin);
+//bfg jump Z velocity when bfg-jumping at origin
+float AAS_BFGJumpZVelocity(vec3_t origin);
+//calculates the horizontal velocity needed for a jump and returns true this velocity could be calculated
+int AAS_HorizontalVelocityForJump(float zvel, vec3_t start, vec3_t end, float *velocity);
+//
+void AAS_SetMovedir(vec3_t angles, vec3_t movedir);
+//
+int AAS_DropToFloor(vec3_t origin, vec3_t mins, vec3_t maxs);
+//
+void AAS_InitSettings(void);
diff --git a/code/botlib/be_aas_optimize.c b/code/botlib/be_aas_optimize.c
new file mode 100755
index 0000000..f420fd1
--- /dev/null
+++ b/code/botlib/be_aas_optimize.c
@@ -0,0 +1,312 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_optimize.c
+ *
+ * desc: decreases the .aas file size after the reachabilities have
+ * been calculated, just dumps all the faces, edges and vertexes
+ *
+ * $Archive: /MissionPack/code/botlib/be_aas_optimize.c $
+ *
+ *****************************************************************************/
+
+#include "../game/q_shared.h"
+#include "l_libvar.h"
+#include "l_memory.h"
+#include "l_script.h"
+#include "l_precomp.h"
+#include "l_struct.h"
+#include "aasfile.h"
+#include "../game/botlib.h"
+#include "../game/be_aas.h"
+#include "be_aas_funcs.h"
+#include "be_interface.h"
+#include "be_aas_def.h"
+
+typedef struct optimized_s
+{
+ //vertexes
+ int numvertexes;
+ aas_vertex_t *vertexes;
+ //edges
+ int numedges;
+ aas_edge_t *edges;
+ //edge index
+ int edgeindexsize;
+ aas_edgeindex_t *edgeindex;
+ //faces
+ int numfaces;
+ aas_face_t *faces;
+ //face index
+ int faceindexsize;
+ aas_faceindex_t *faceindex;
+ //convex areas
+ int numareas;
+ aas_area_t *areas;
+ //
+ int *vertexoptimizeindex;
+ int *edgeoptimizeindex;
+ int *faceoptimizeindex;
+} optimized_t;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_KeepEdge(aas_edge_t *edge)
+{
+ return 1;
+} //end of the function AAS_KeepFace
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_OptimizeEdge(optimized_t *optimized, int edgenum)
+{
+ int i, optedgenum;
+ aas_edge_t *edge, *optedge;
+
+ edge = &aasworld.edges[abs(edgenum)];
+ if (!AAS_KeepEdge(edge)) return 0;
+
+ optedgenum = optimized->edgeoptimizeindex[abs(edgenum)];
+ if (optedgenum)
+ {
+ //keep the edge reversed sign
+ if (edgenum > 0) return optedgenum;
+ else return -optedgenum;
+ } //end if
+
+ optedge = &optimized->edges[optimized->numedges];
+
+ for (i = 0; i < 2; i++)
+ {
+ if (optimized->vertexoptimizeindex[edge->v[i]])
+ {
+ optedge->v[i] = optimized->vertexoptimizeindex[edge->v[i]];
+ } //end if
+ else
+ {
+ VectorCopy(aasworld.vertexes[edge->v[i]], optimized->vertexes[optimized->numvertexes]);
+ optedge->v[i] = optimized->numvertexes;
+ optimized->vertexoptimizeindex[edge->v[i]] = optimized->numvertexes;
+ optimized->numvertexes++;
+ } //end else
+ } //end for
+ optimized->edgeoptimizeindex[abs(edgenum)] = optimized->numedges;
+ optedgenum = optimized->numedges;
+ optimized->numedges++;
+ //keep the edge reversed sign
+ if (edgenum > 0) return optedgenum;
+ else return -optedgenum;
+} //end of the function AAS_OptimizeEdge
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_KeepFace(aas_face_t *face)
+{
+ if (!(face->faceflags & FACE_LADDER)) return 0;
+ else return 1;
+} //end of the function AAS_KeepFace
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_OptimizeFace(optimized_t *optimized, int facenum)
+{
+ int i, edgenum, optedgenum, optfacenum;
+ aas_face_t *face, *optface;
+
+ face = &aasworld.faces[abs(facenum)];
+ if (!AAS_KeepFace(face)) return 0;
+
+ optfacenum = optimized->faceoptimizeindex[abs(facenum)];
+ if (optfacenum)
+ {
+ //keep the face side sign
+ if (facenum > 0) return optfacenum;
+ else return -optfacenum;
+ } //end if
+
+ optface = &optimized->faces[optimized->numfaces];
+ Com_Memcpy(optface, face, sizeof(aas_face_t));
+
+ optface->numedges = 0;
+ optface->firstedge = optimized->edgeindexsize;
+ for (i = 0; i < face->numedges; i++)
+ {
+ edgenum = aasworld.edgeindex[face->firstedge + i];
+ optedgenum = AAS_OptimizeEdge(optimized, edgenum);
+ if (optedgenum)
+ {
+ optimized->edgeindex[optface->firstedge + optface->numedges] = optedgenum;
+ optface->numedges++;
+ optimized->edgeindexsize++;
+ } //end if
+ } //end for
+ optimized->faceoptimizeindex[abs(facenum)] = optimized->numfaces;
+ optfacenum = optimized->numfaces;
+ optimized->numfaces++;
+ //keep the face side sign
+ if (facenum > 0) return optfacenum;
+ else return -optfacenum;
+} //end of the function AAS_OptimizeFace
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_OptimizeArea(optimized_t *optimized, int areanum)
+{
+ int i, facenum, optfacenum;
+ aas_area_t *area, *optarea;
+
+ area = &aasworld.areas[areanum];
+ optarea = &optimized->areas[areanum];
+ Com_Memcpy(optarea, area, sizeof(aas_area_t));
+
+ optarea->numfaces = 0;
+ optarea->firstface = optimized->faceindexsize;
+ for (i = 0; i < area->numfaces; i++)
+ {
+ facenum = aasworld.faceindex[area->firstface + i];
+ optfacenum = AAS_OptimizeFace(optimized, facenum);
+ if (optfacenum)
+ {
+ optimized->faceindex[optarea->firstface + optarea->numfaces] = optfacenum;
+ optarea->numfaces++;
+ optimized->faceindexsize++;
+ } //end if
+ } //end for
+} //end of the function AAS_OptimizeArea
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_OptimizeAlloc(optimized_t *optimized)
+{
+ optimized->vertexes = (aas_vertex_t *) GetClearedMemory(aasworld.numvertexes * sizeof(aas_vertex_t));
+ optimized->numvertexes = 0;
+ optimized->edges = (aas_edge_t *) GetClearedMemory(aasworld.numedges * sizeof(aas_edge_t));
+ optimized->numedges = 1; //edge zero is a dummy
+ optimized->edgeindex = (aas_edgeindex_t *) GetClearedMemory(aasworld.edgeindexsize * sizeof(aas_edgeindex_t));
+ optimized->edgeindexsize = 0;
+ optimized->faces = (aas_face_t *) GetClearedMemory(aasworld.numfaces * sizeof(aas_face_t));
+ optimized->numfaces = 1; //face zero is a dummy
+ optimized->faceindex = (aas_faceindex_t *) GetClearedMemory(aasworld.faceindexsize * sizeof(aas_faceindex_t));
+ optimized->faceindexsize = 0;
+ optimized->areas = (aas_area_t *) GetClearedMemory(aasworld.numareas * sizeof(aas_area_t));
+ optimized->numareas = aasworld.numareas;
+ //
+ optimized->vertexoptimizeindex = (int *) GetClearedMemory(aasworld.numvertexes * sizeof(int));
+ optimized->edgeoptimizeindex = (int *) GetClearedMemory(aasworld.numedges * sizeof(int));
+ optimized->faceoptimizeindex = (int *) GetClearedMemory(aasworld.numfaces * sizeof(int));
+} //end of the function AAS_OptimizeAlloc
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_OptimizeStore(optimized_t *optimized)
+{
+ //store the optimized vertexes
+ if (aasworld.vertexes) FreeMemory(aasworld.vertexes);
+ aasworld.vertexes = optimized->vertexes;
+ aasworld.numvertexes = optimized->numvertexes;
+ //store the optimized edges
+ if (aasworld.edges) FreeMemory(aasworld.edges);
+ aasworld.edges = optimized->edges;
+ aasworld.numedges = optimized->numedges;
+ //store the optimized edge index
+ if (aasworld.edgeindex) FreeMemory(aasworld.edgeindex);
+ aasworld.edgeindex = optimized->edgeindex;
+ aasworld.edgeindexsize = optimized->edgeindexsize;
+ //store the optimized faces
+ if (aasworld.faces) FreeMemory(aasworld.faces);
+ aasworld.faces = optimized->faces;
+ aasworld.numfaces = optimized->numfaces;
+ //store the optimized face index
+ if (aasworld.faceindex) FreeMemory(aasworld.faceindex);
+ aasworld.faceindex = optimized->faceindex;
+ aasworld.faceindexsize = optimized->faceindexsize;
+ //store the optimized areas
+ if (aasworld.areas) FreeMemory(aasworld.areas);
+ aasworld.areas = optimized->areas;
+ aasworld.numareas = optimized->numareas;
+ //free optimize indexes
+ FreeMemory(optimized->vertexoptimizeindex);
+ FreeMemory(optimized->edgeoptimizeindex);
+ FreeMemory(optimized->faceoptimizeindex);
+} //end of the function AAS_OptimizeStore
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_Optimize(void)
+{
+ int i, sign;
+ optimized_t optimized;
+
+ AAS_OptimizeAlloc(&optimized);
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ AAS_OptimizeArea(&optimized, i);
+ } //end for
+ //reset the reachability face pointers
+ for (i = 0; i < aasworld.reachabilitysize; i++)
+ {
+ //NOTE: for TRAVEL_ELEVATOR the facenum is the model number of
+ // the elevator
+ if ((aasworld.reachability[i].traveltype & TRAVELTYPE_MASK) == TRAVEL_ELEVATOR) continue;
+ //NOTE: for TRAVEL_JUMPPAD the facenum is the Z velocity and the edgenum is the hor velocity
+ if ((aasworld.reachability[i].traveltype & TRAVELTYPE_MASK) == TRAVEL_JUMPPAD) continue;
+ //NOTE: for TRAVEL_FUNCBOB the facenum and edgenum contain other coded information
+ if ((aasworld.reachability[i].traveltype & TRAVELTYPE_MASK) == TRAVEL_FUNCBOB) continue;
+ //
+ sign = aasworld.reachability[i].facenum;
+ aasworld.reachability[i].facenum = optimized.faceoptimizeindex[abs(aasworld.reachability[i].facenum)];
+ if (sign < 0) aasworld.reachability[i].facenum = -aasworld.reachability[i].facenum;
+ sign = aasworld.reachability[i].edgenum;
+ aasworld.reachability[i].edgenum = optimized.edgeoptimizeindex[abs(aasworld.reachability[i].edgenum)];
+ if (sign < 0) aasworld.reachability[i].edgenum = -aasworld.reachability[i].edgenum;
+ } //end for
+ //store the optimized AAS data into aasworld
+ AAS_OptimizeStore(&optimized);
+ //print some nice stuff :)
+ botimport.Print(PRT_MESSAGE, "AAS data optimized.\n");
+} //end of the function AAS_Optimize
diff --git a/code/botlib/be_aas_optimize.h b/code/botlib/be_aas_optimize.h
new file mode 100755
index 0000000..15e44e6
--- /dev/null
+++ b/code/botlib/be_aas_optimize.h
@@ -0,0 +1,33 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_optimize.h
+ *
+ * desc: AAS
+ *
+ * $Archive: /source/code/botlib/be_aas_optimize.h $
+ *
+ *****************************************************************************/
+
+void AAS_Optimize(void);
+
diff --git a/code/botlib/be_aas_reach.c b/code/botlib/be_aas_reach.c
new file mode 100755
index 0000000..465da80
--- /dev/null
+++ b/code/botlib/be_aas_reach.c
@@ -0,0 +1,4547 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_reach.c
+ *
+ * desc: reachability calculations
+ *
+ * $Archive: /MissionPack/code/botlib/be_aas_reach.c $
+ *
+ *****************************************************************************/
+
+#include "../game/q_shared.h"
+#include "l_log.h"
+#include "l_memory.h"
+#include "l_script.h"
+#include "l_libvar.h"
+#include "l_precomp.h"
+#include "l_struct.h"
+#include "aasfile.h"
+#include "../game/botlib.h"
+#include "../game/be_aas.h"
+#include "be_aas_funcs.h"
+#include "be_aas_def.h"
+
+extern int Sys_MilliSeconds(void);
+
+
+extern botlib_import_t botimport;
+
+//#define REACH_DEBUG
+
+//NOTE: all travel times are in hundreth of a second
+//maximum number of reachability links
+#define AAS_MAX_REACHABILITYSIZE 65536
+//number of areas reachability is calculated for each frame
+#define REACHABILITYAREASPERCYCLE 15
+//number of units reachability points are placed inside the areas
+#define INSIDEUNITS 2
+#define INSIDEUNITS_WALKEND 5
+#define INSIDEUNITS_WALKSTART 0.1
+#define INSIDEUNITS_WATERJUMP 15
+//area flag used for weapon jumping
+#define AREA_WEAPONJUMP 8192 //valid area to weapon jump to
+//number of reachabilities of each type
+int reach_swim; //swim
+int reach_equalfloor; //walk on floors with equal height
+int reach_step; //step up
+int reach_walk; //walk of step
+int reach_barrier; //jump up to a barrier
+int reach_waterjump; //jump out of water
+int reach_walkoffledge; //walk of a ledge
+int reach_jump; //jump
+int reach_ladder; //climb or descent a ladder
+int reach_teleport; //teleport
+int reach_elevator; //use an elevator
+int reach_funcbob; //use a func bob
+int reach_grapple; //grapple hook
+int reach_doublejump; //double jump
+int reach_rampjump; //ramp jump
+int reach_strafejump; //strafe jump (just normal jump but further)
+int reach_rocketjump; //rocket jump
+int reach_bfgjump; //bfg jump
+int reach_jumppad; //jump pads
+//if true grapple reachabilities are skipped
+int calcgrapplereach;
+//linked reachability
+typedef struct aas_lreachability_s
+{
+ int areanum; //number of the reachable area
+ int facenum; //number of the face towards the other area
+ int edgenum; //number of the edge towards the other area
+ vec3_t start; //start point of inter area movement
+ vec3_t end; //end point of inter area movement
+ int traveltype; //type of travel required to get to the area
+ unsigned short int traveltime; //travel time of the inter area movement
+ //
+ struct aas_lreachability_s *next;
+} aas_lreachability_t;
+//temporary reachabilities
+aas_lreachability_t *reachabilityheap; //heap with reachabilities
+aas_lreachability_t *nextreachability; //next free reachability from the heap
+aas_lreachability_t **areareachability; //reachability links for every area
+int numlreachabilities;
+
+//===========================================================================
+// returns the surface area of the given face
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float AAS_FaceArea(aas_face_t *face)
+{
+ int i, edgenum, side;
+ float total;
+ vec_t *v;
+ vec3_t d1, d2, cross;
+ aas_edge_t *edge;
+
+ edgenum = aasworld.edgeindex[face->firstedge];
+ side = edgenum < 0;
+ edge = &aasworld.edges[abs(edgenum)];
+ v = aasworld.vertexes[edge->v[side]];
+
+ total = 0;
+ for (i = 1; i < face->numedges - 1; i++)
+ {
+ edgenum = aasworld.edgeindex[face->firstedge + i];
+ side = edgenum < 0;
+ edge = &aasworld.edges[abs(edgenum)];
+ VectorSubtract(aasworld.vertexes[edge->v[side]], v, d1);
+ VectorSubtract(aasworld.vertexes[edge->v[!side]], v, d2);
+ CrossProduct(d1, d2, cross);
+ total += 0.5 * VectorLength(cross);
+ } //end for
+ return total;
+} //end of the function AAS_FaceArea
+//===========================================================================
+// returns the volume of an area
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float AAS_AreaVolume(int areanum)
+{
+ int i, edgenum, facenum, side;
+ vec_t d, a, volume;
+ vec3_t corner;
+ aas_plane_t *plane;
+ aas_edge_t *edge;
+ aas_face_t *face;
+ aas_area_t *area;
+
+ area = &aasworld.areas[areanum];
+ facenum = aasworld.faceindex[area->firstface];
+ face = &aasworld.faces[abs(facenum)];
+ edgenum = aasworld.edgeindex[face->firstedge];
+ edge = &aasworld.edges[abs(edgenum)];
+ //
+ VectorCopy(aasworld.vertexes[edge->v[0]], corner);
+
+ //make tetrahedrons to all other faces
+ volume = 0;
+ for (i = 0; i < area->numfaces; i++)
+ {
+ facenum = abs(aasworld.faceindex[area->firstface + i]);
+ face = &aasworld.faces[facenum];
+ side = face->backarea != areanum;
+ plane = &aasworld.planes[face->planenum ^ side];
+ d = -(DotProduct (corner, plane->normal) - plane->dist);
+ a = AAS_FaceArea(face);
+ volume += d * a;
+ } //end for
+
+ volume /= 3;
+ return volume;
+} //end of the function AAS_AreaVolume
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_BestReachableLinkArea(aas_link_t *areas)
+{
+ aas_link_t *link;
+
+ for (link = areas; link; link = link->next_area)
+ {
+ if (AAS_AreaGrounded(link->areanum) || AAS_AreaSwim(link->areanum))
+ {
+ return link->areanum;
+ } //end if
+ } //end for
+ //
+ for (link = areas; link; link = link->next_area)
+ {
+ if (link->areanum) return link->areanum;
+ //FIXME: this is a bad idea when the reachability is not yet
+ // calculated when the level items are loaded
+ if (AAS_AreaReachability(link->areanum))
+ return link->areanum;
+ } //end for
+ return 0;
+} //end of the function AAS_BestReachableLinkArea
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_GetJumpPadInfo(int ent, vec3_t areastart, vec3_t absmins, vec3_t absmaxs, vec3_t velocity)
+{
+ int modelnum, ent2;
+ float speed, height, gravity, time, dist, forward;
+ vec3_t origin, angles, teststart, ent2origin;
+ aas_trace_t trace;
+ char model[MAX_EPAIRKEY];
+ char target[MAX_EPAIRKEY], targetname[MAX_EPAIRKEY];
+
+ //
+ AAS_FloatForBSPEpairKey(ent, "speed", &speed);
+ if (!speed) speed = 1000;
+ VectorClear(angles);
+ //get the mins, maxs and origin of the model
+ AAS_ValueForBSPEpairKey(ent, "model", model, MAX_EPAIRKEY);
+ if (model[0]) modelnum = atoi(model+1);
+ else modelnum = 0;
+ AAS_BSPModelMinsMaxsOrigin(modelnum, angles, absmins, absmaxs, origin);
+ VectorAdd(origin, absmins, absmins);
+ VectorAdd(origin, absmaxs, absmaxs);
+ VectorAdd(absmins, absmaxs, origin);
+ VectorScale (origin, 0.5, origin);
+
+ //get the start areas
+ VectorCopy(origin, teststart);
+ teststart[2] += 64;
+ trace = AAS_TraceClientBBox(teststart, origin, PRESENCE_CROUCH, -1);
+ if (trace.startsolid)
+ {
+ botimport.Print(PRT_MESSAGE, "trigger_push start solid\n");
+ VectorCopy(origin, areastart);
+ } //end if
+ else
+ {
+ VectorCopy(trace.endpos, areastart);
+ } //end else
+ areastart[2] += 0.125;
+ //
+ //AAS_DrawPermanentCross(origin, 4, 4);
+ //get the target entity
+ AAS_ValueForBSPEpairKey(ent, "target", target, MAX_EPAIRKEY);
+ for (ent2 = AAS_NextBSPEntity(0); ent2; ent2 = AAS_NextBSPEntity(ent2))
+ {
+ if (!AAS_ValueForBSPEpairKey(ent2, "targetname", targetname, MAX_EPAIRKEY)) continue;
+ if (!strcmp(targetname, target)) break;
+ } //end for
+ if (!ent2)
+ {
+ botimport.Print(PRT_MESSAGE, "trigger_push without target entity %s\n", target);
+ return qfalse;
+ } //end if
+ AAS_VectorForBSPEpairKey(ent2, "origin", ent2origin);
+ //
+ height = ent2origin[2] - origin[2];
+ gravity = aassettings.phys_gravity;
+ time = sqrt( height / ( 0.5 * gravity ) );
+ if (!time)
+ {
+ botimport.Print(PRT_MESSAGE, "trigger_push without time\n");
+ return qfalse;
+ } //end if
+ // set s.origin2 to the push velocity
+ VectorSubtract ( ent2origin, origin, velocity);
+ dist = VectorNormalize( velocity);
+ forward = dist / time;
+ //FIXME: why multiply by 1.1
+ forward *= 1.1f;
+ VectorScale(velocity, forward, velocity);
+ velocity[2] = time * gravity;
+ return qtrue;
+} //end of the function AAS_GetJumpPadInfo
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_BestReachableFromJumpPadArea(vec3_t origin, vec3_t mins, vec3_t maxs)
+{
+ int area2num, ent, bot_visualizejumppads, bestareanum;
+ float volume, bestareavolume;
+ vec3_t areastart, cmdmove, bboxmins, bboxmaxs;
+ vec3_t absmins, absmaxs, velocity;
+ aas_clientmove_t move;
+ aas_link_t *areas, *link;
+ char classname[MAX_EPAIRKEY];
+
+#ifdef BSPC
+ bot_visualizejumppads = 0;
+#else
+ bot_visualizejumppads = LibVarValue("bot_visualizejumppads", "0");
+#endif
+ VectorAdd(origin, mins, bboxmins);
+ VectorAdd(origin, maxs, bboxmaxs);
+ for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent))
+ {
+ if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) continue;
+ if (strcmp(classname, "trigger_push")) continue;
+ //
+ if (!AAS_GetJumpPadInfo(ent, areastart, absmins, absmaxs, velocity)) continue;
+ //get the areas the jump pad brush is in
+ areas = AAS_LinkEntityClientBBox(absmins, absmaxs, -1, PRESENCE_CROUCH);
+ for (link = areas; link; link = link->next_area)
+ {
+ if (AAS_AreaJumpPad(link->areanum)) break;
+ } //end for
+ if (!link)
+ {
+ botimport.Print(PRT_MESSAGE, "trigger_push not in any jump pad area\n");
+ AAS_UnlinkFromAreas(areas);
+ continue;
+ } //end if
+ //
+ //botimport.Print(PRT_MESSAGE, "found a trigger_push with velocity %f %f %f\n", velocity[0], velocity[1], velocity[2]);
+ //
+ VectorSet(cmdmove, 0, 0, 0);
+ Com_Memset(&move, 0, sizeof(aas_clientmove_t));
+ area2num = 0;
+ AAS_ClientMovementHitBBox(&move, -1, areastart, PRESENCE_NORMAL, qfalse,
+ velocity, cmdmove, 0, 30, 0.1f, bboxmins, bboxmaxs, bot_visualizejumppads);
+ if (move.frames < 30)
+ {
+ bestareanum = 0;
+ bestareavolume = 0;
+ for (link = areas; link; link = link->next_area)
+ {
+ if (!AAS_AreaJumpPad(link->areanum)) continue;
+ volume = AAS_AreaVolume(link->areanum);
+ if (volume >= bestareavolume)
+ {
+ bestareanum = link->areanum;
+ bestareavolume = volume;
+ } //end if
+ } //end if
+ AAS_UnlinkFromAreas(areas);
+ return bestareanum;
+ } //end if
+ AAS_UnlinkFromAreas(areas);
+ } //end for
+ return 0;
+} //end of the function AAS_BestReachableFromJumpPadArea
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_BestReachableArea(vec3_t origin, vec3_t mins, vec3_t maxs, vec3_t goalorigin)
+{
+ int areanum, i, j, k, l;
+ aas_link_t *areas;
+ vec3_t absmins, absmaxs;
+ //vec3_t bbmins, bbmaxs;
+ vec3_t start, end;
+ aas_trace_t trace;
+
+ if (!aasworld.loaded)
+ {
+ botimport.Print(PRT_ERROR, "AAS_BestReachableArea: aas not loaded\n");
+ return 0;
+ } //end if
+ //find a point in an area
+ VectorCopy(origin, start);
+ areanum = AAS_PointAreaNum(start);
+ //while no area found fudge around a little
+ for (i = 0; i < 5 && !areanum; i++)
+ {
+ for (j = 0; j < 5 && !areanum; j++)
+ {
+ for (k = -1; k <= 1 && !areanum; k++)
+ {
+ for (l = -1; l <= 1 && !areanum; l++)
+ {
+ VectorCopy(origin, start);
+ start[0] += (float) j * 4 * k;
+ start[1] += (float) j * 4 * l;
+ start[2] += (float) i * 4;
+ areanum = AAS_PointAreaNum(start);
+ } //end for
+ } //end for
+ } //end for
+ } //end for
+ //if an area was found
+ if (areanum)
+ {
+ //drop client bbox down and try again
+ VectorCopy(start, end);
+ start[2] += 0.25;
+ end[2] -= 50;
+ trace = AAS_TraceClientBBox(start, end, PRESENCE_CROUCH, -1);
+ if (!trace.startsolid)
+ {
+ areanum = AAS_PointAreaNum(trace.endpos);
+ VectorCopy(trace.endpos, goalorigin);
+ //FIXME: cannot enable next line right now because the reachability
+ // does not have to be calculated when the level items are loaded
+ //if the origin is in an area with reachability
+ //if (AAS_AreaReachability(areanum)) return areanum;
+ if (areanum) return areanum;
+ } //end if
+ else
+ {
+ //it can very well happen that the AAS_PointAreaNum function tells that
+ //a point is in an area and that starting a AAS_TraceClientBBox from that
+ //point will return trace.startsolid qtrue
+#if 0
+ if (AAS_PointAreaNum(start))
+ {
+ Log_Write("point %f %f %f in area %d but trace startsolid", start[0], start[1], start[2], areanum);
+ AAS_DrawPermanentCross(start, 4, LINECOLOR_RED);
+ } //end if
+ botimport.Print(PRT_MESSAGE, "AAS_BestReachableArea: start solid\n");
+#endif
+ VectorCopy(start, goalorigin);
+ return areanum;
+ } //end else
+ } //end if
+ //
+ //AAS_PresenceTypeBoundingBox(PRESENCE_CROUCH, bbmins, bbmaxs);
+ //NOTE: the goal origin does not have to be in the goal area
+ // because the bot will have to move towards the item origin anyway
+ VectorCopy(origin, goalorigin);
+ //
+ VectorAdd(origin, mins, absmins);
+ VectorAdd(origin, maxs, absmaxs);
+ //add bounding box size
+ //VectorSubtract(absmins, bbmaxs, absmins);
+ //VectorSubtract(absmaxs, bbmins, absmaxs);
+ //link an invalid (-1) entity
+ areas = AAS_LinkEntityClientBBox(absmins, absmaxs, -1, PRESENCE_CROUCH);
+ //get the reachable link arae
+ areanum = AAS_BestReachableLinkArea(areas);
+ //unlink the invalid entity
+ AAS_UnlinkFromAreas(areas);
+ //
+ return areanum;
+} //end of the function AAS_BestReachableArea
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_SetupReachabilityHeap(void)
+{
+ int i;
+
+ reachabilityheap = (aas_lreachability_t *) GetClearedMemory(
+ AAS_MAX_REACHABILITYSIZE * sizeof(aas_lreachability_t));
+ for (i = 0; i < AAS_MAX_REACHABILITYSIZE-1; i++)
+ {
+ reachabilityheap[i].next = &reachabilityheap[i+1];
+ } //end for
+ reachabilityheap[AAS_MAX_REACHABILITYSIZE-1].next = NULL;
+ nextreachability = reachabilityheap;
+ numlreachabilities = 0;
+} //end of the function AAS_InitReachabilityHeap
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ShutDownReachabilityHeap(void)
+{
+ FreeMemory(reachabilityheap);
+ numlreachabilities = 0;
+} //end of the function AAS_ShutDownReachabilityHeap
+//===========================================================================
+// returns a reachability link
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+aas_lreachability_t *AAS_AllocReachability(void)
+{
+ aas_lreachability_t *r;
+
+ if (!nextreachability) return NULL;
+ //make sure the error message only shows up once
+ if (!nextreachability->next) AAS_Error("AAS_MAX_REACHABILITYSIZE");
+ //
+ r = nextreachability;
+ nextreachability = nextreachability->next;
+ numlreachabilities++;
+ return r;
+} //end of the function AAS_AllocReachability
+//===========================================================================
+// frees a reachability link
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_FreeReachability(aas_lreachability_t *lreach)
+{
+ Com_Memset(lreach, 0, sizeof(aas_lreachability_t));
+
+ lreach->next = nextreachability;
+ nextreachability = lreach;
+ numlreachabilities--;
+} //end of the function AAS_FreeReachability
+//===========================================================================
+// returns qtrue if the area has reachability links
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_AreaReachability(int areanum)
+{
+ if (areanum < 0 || areanum >= aasworld.numareas)
+ {
+ AAS_Error("AAS_AreaReachability: areanum %d out of range", areanum);
+ return 0;
+ } //end if
+ return aasworld.areasettings[areanum].numreachableareas;
+} //end of the function AAS_AreaReachability
+//===========================================================================
+// returns the surface area of all ground faces together of the area
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float AAS_AreaGroundFaceArea(int areanum)
+{
+ int i;
+ float total;
+ aas_area_t *area;
+ aas_face_t *face;
+
+ total = 0;
+ area = &aasworld.areas[areanum];
+ for (i = 0; i < area->numfaces; i++)
+ {
+ face = &aasworld.faces[abs(aasworld.faceindex[area->firstface + i])];
+ if (!(face->faceflags & FACE_GROUND)) continue;
+ //
+ total += AAS_FaceArea(face);
+ } //end for
+ return total;
+} //end of the function AAS_AreaGroundFaceArea
+//===========================================================================
+// returns the center of a face
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_FaceCenter(int facenum, vec3_t center)
+{
+ int i;
+ float scale;
+ aas_face_t *face;
+ aas_edge_t *edge;
+
+ face = &aasworld.faces[facenum];
+
+ VectorClear(center);
+ for (i = 0; i < face->numedges; i++)
+ {
+ edge = &aasworld.edges[abs(aasworld.edgeindex[face->firstedge + i])];
+ VectorAdd(center, aasworld.vertexes[edge->v[0]], center);
+ VectorAdd(center, aasworld.vertexes[edge->v[1]], center);
+ } //end for
+ scale = 0.5 / face->numedges;
+ VectorScale(center, scale, center);
+} //end of the function AAS_FaceCenter
+//===========================================================================
+// returns the maximum distance a player can fall before being damaged
+// damage = deltavelocity*deltavelocity * 0.0001
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_FallDamageDistance(void)
+{
+ float maxzvelocity, gravity, t;
+
+ maxzvelocity = sqrt(30 * 10000);
+ gravity = aassettings.phys_gravity;
+ t = maxzvelocity / gravity;
+ return 0.5 * gravity * t * t;
+} //end of the function AAS_FallDamageDistance
+//===========================================================================
+// distance = 0.5 * gravity * t * t
+// vel = t * gravity
+// damage = vel * vel * 0.0001
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float AAS_FallDelta(float distance)
+{
+ float t, delta, gravity;
+
+ gravity = aassettings.phys_gravity;
+ t = sqrt(fabs(distance) * 2 / gravity);
+ delta = t * gravity;
+ return delta * delta * 0.0001;
+} //end of the function AAS_FallDelta
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float AAS_MaxJumpHeight(float phys_jumpvel)
+{
+ float phys_gravity;
+
+ phys_gravity = aassettings.phys_gravity;
+ //maximum height a player can jump with the given initial z velocity
+ return 0.5 * phys_gravity * (phys_jumpvel / phys_gravity) * (phys_jumpvel / phys_gravity);
+} //end of the function MaxJumpHeight
+//===========================================================================
+// returns true if a player can only crouch in the area
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float AAS_MaxJumpDistance(float phys_jumpvel)
+{
+ float phys_gravity, phys_maxvelocity, t;
+
+ phys_gravity = aassettings.phys_gravity;
+ phys_maxvelocity = aassettings.phys_maxvelocity;
+ //time a player takes to fall the height
+ t = sqrt(aassettings.rs_maxjumpfallheight / (0.5 * phys_gravity));
+ //maximum distance
+ return phys_maxvelocity * (t + phys_jumpvel / phys_gravity);
+} //end of the function AAS_MaxJumpDistance
+//===========================================================================
+// returns true if a player can only crouch in the area
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_AreaCrouch(int areanum)
+{
+ if (!(aasworld.areasettings[areanum].presencetype & PRESENCE_NORMAL)) return qtrue;
+ else return qfalse;
+} //end of the function AAS_AreaCrouch
+//===========================================================================
+// returns qtrue if it is possible to swim in the area
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_AreaSwim(int areanum)
+{
+ if (aasworld.areasettings[areanum].areaflags & AREA_LIQUID) return qtrue;
+ else return qfalse;
+} //end of the function AAS_AreaSwim
+//===========================================================================
+// returns qtrue if the area contains a liquid
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_AreaLiquid(int areanum)
+{
+ if (aasworld.areasettings[areanum].areaflags & AREA_LIQUID) return qtrue;
+ else return qfalse;
+} //end of the function AAS_AreaLiquid
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_AreaLava(int areanum)
+{
+ return (aasworld.areasettings[areanum].contents & AREACONTENTS_LAVA);
+} //end of the function AAS_AreaLava
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_AreaSlime(int areanum)
+{
+ return (aasworld.areasettings[areanum].contents & AREACONTENTS_SLIME);
+} //end of the function AAS_AreaSlime
+//===========================================================================
+// returns qtrue if the area contains ground faces
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_AreaGrounded(int areanum)
+{
+ return (aasworld.areasettings[areanum].areaflags & AREA_GROUNDED);
+} //end of the function AAS_AreaGround
+//===========================================================================
+// returns true if the area contains ladder faces
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_AreaLadder(int areanum)
+{
+ return (aasworld.areasettings[areanum].areaflags & AREA_LADDER);
+} //end of the function AAS_AreaLadder
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_AreaJumpPad(int areanum)
+{
+ return (aasworld.areasettings[areanum].contents & AREACONTENTS_JUMPPAD);
+} //end of the function AAS_AreaJumpPad
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_AreaTeleporter(int areanum)
+{
+ return (aasworld.areasettings[areanum].contents & AREACONTENTS_TELEPORTER);
+} //end of the function AAS_AreaTeleporter
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_AreaClusterPortal(int areanum)
+{
+ return (aasworld.areasettings[areanum].contents & AREACONTENTS_CLUSTERPORTAL);
+} //end of the function AAS_AreaClusterPortal
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_AreaDoNotEnter(int areanum)
+{
+ return (aasworld.areasettings[areanum].contents & AREACONTENTS_DONOTENTER);
+} //end of the function AAS_AreaDoNotEnter
+//===========================================================================
+// returns the time it takes perform a barrier jump
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+unsigned short int AAS_BarrierJumpTravelTime(void)
+{
+ return aassettings.phys_jumpvel / (aassettings.phys_gravity * 0.1);
+} //end op the function AAS_BarrierJumpTravelTime
+//===========================================================================
+// returns true if there already exists a reachability from area1 to area2
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean AAS_ReachabilityExists(int area1num, int area2num)
+{
+ aas_lreachability_t *r;
+
+ for (r = areareachability[area1num]; r; r = r->next)
+ {
+ if (r->areanum == area2num) return qtrue;
+ } //end for
+ return qfalse;
+} //end of the function AAS_ReachabilityExists
+//===========================================================================
+// returns true if there is a solid just after the end point when going
+// from start to end
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_NearbySolidOrGap(vec3_t start, vec3_t end)
+{
+ vec3_t dir, testpoint;
+ int areanum;
+
+ VectorSubtract(end, start, dir);
+ dir[2] = 0;
+ VectorNormalize(dir);
+ VectorMA(end, 48, dir, testpoint);
+
+ areanum = AAS_PointAreaNum(testpoint);
+ if (!areanum)
+ {
+ testpoint[2] += 16;
+ areanum = AAS_PointAreaNum(testpoint);
+ if (!areanum) return qtrue;
+ } //end if
+ VectorMA(end, 64, dir, testpoint);
+ areanum = AAS_PointAreaNum(testpoint);
+ if (areanum)
+ {
+ if (!AAS_AreaSwim(areanum) && !AAS_AreaGrounded(areanum)) return qtrue;
+ } //end if
+ return qfalse;
+} //end of the function AAS_SolidGapTime
+//===========================================================================
+// searches for swim reachabilities between adjacent areas
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_Reachability_Swim(int area1num, int area2num)
+{
+ int i, j, face1num, face2num, side1;
+ aas_area_t *area1, *area2;
+ aas_areasettings_t *areasettings;
+ aas_lreachability_t *lreach;
+ aas_face_t *face1;
+ aas_plane_t *plane;
+ vec3_t start;
+
+ if (!AAS_AreaSwim(area1num) || !AAS_AreaSwim(area2num)) return qfalse;
+ //if the second area is crouch only
+ if (!(aasworld.areasettings[area2num].presencetype & PRESENCE_NORMAL)) return qfalse;
+
+ area1 = &aasworld.areas[area1num];
+ area2 = &aasworld.areas[area2num];
+
+ //if the areas are not near anough
+ for (i = 0; i < 3; i++)
+ {
+ if (area1->mins[i] > area2->maxs[i] + 10) return qfalse;
+ if (area1->maxs[i] < area2->mins[i] - 10) return qfalse;
+ } //end for
+ //find a shared face and create a reachability link
+ for (i = 0; i < area1->numfaces; i++)
+ {
+ face1num = aasworld.faceindex[area1->firstface + i];
+ side1 = face1num < 0;
+ face1num = abs(face1num);
+ //
+ for (j = 0; j < area2->numfaces; j++)
+ {
+ face2num = abs(aasworld.faceindex[area2->firstface + j]);
+ //
+ if (face1num == face2num)
+ {
+ AAS_FaceCenter(face1num, start);
+ //
+ if (AAS_PointContents(start) & (CONTENTS_LAVA|CONTENTS_SLIME|CONTENTS_WATER))
+ {
+ //
+ face1 = &aasworld.faces[face1num];
+ areasettings = &aasworld.areasettings[area1num];
+ //create a new reachability link
+ lreach = AAS_AllocReachability();
+ if (!lreach) return qfalse;
+ lreach->areanum = area2num;
+ lreach->facenum = face1num;
+ lreach->edgenum = 0;
+ VectorCopy(start, lreach->start);
+ plane = &aasworld.planes[face1->planenum ^ side1];
+ VectorMA(lreach->start, -INSIDEUNITS, plane->normal, lreach->end);
+ lreach->traveltype = TRAVEL_SWIM;
+ lreach->traveltime = 1;
+ //if the volume of the area is rather small
+ if (AAS_AreaVolume(area2num) < 800)
+ lreach->traveltime += 200;
+ //if (!(AAS_PointContents(start) & MASK_WATER)) lreach->traveltime += 500;
+ //link the reachability
+ lreach->next = areareachability[area1num];
+ areareachability[area1num] = lreach;
+ reach_swim++;
+ return qtrue;
+ } //end if
+ } //end if
+ } //end for
+ } //end for
+ return qfalse;
+} //end of the function AAS_Reachability_Swim
+//===========================================================================
+// searches for reachabilities between adjacent areas with equal floor
+// heights
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_Reachability_EqualFloorHeight(int area1num, int area2num)
+{
+ int i, j, edgenum, edgenum1, edgenum2, foundreach, side;
+ float height, bestheight, length, bestlength;
+ vec3_t dir, start, end, normal, invgravity, gravitydirection = {0, 0, -1};
+ vec3_t edgevec;
+ aas_area_t *area1, *area2;
+ aas_face_t *face1, *face2;
+ aas_edge_t *edge;
+ aas_plane_t *plane2;
+ aas_lreachability_t lr, *lreach;
+
+ if (!AAS_AreaGrounded(area1num) || !AAS_AreaGrounded(area2num)) return qfalse;
+
+ area1 = &aasworld.areas[area1num];
+ area2 = &aasworld.areas[area2num];
+ //if the areas are not near anough in the x-y direction
+ for (i = 0; i < 2; i++)
+ {
+ if (area1->mins[i] > area2->maxs[i] + 10) return qfalse;
+ if (area1->maxs[i] < area2->mins[i] - 10) return qfalse;
+ } //end for
+ //if area 2 is too high above area 1
+ if (area2->mins[2] > area1->maxs[2]) return qfalse;
+ //
+ VectorCopy(gravitydirection, invgravity);
+ VectorInverse(invgravity);
+ //
+ bestheight = 99999;
+ bestlength = 0;
+ foundreach = qfalse;
+ Com_Memset(&lr, 0, sizeof(aas_lreachability_t)); //make the compiler happy
+ //
+ //check if the areas have ground faces with a common edge
+ //if existing use the lowest common edge for a reachability link
+ for (i = 0; i < area1->numfaces; i++)
+ {
+ face1 = &aasworld.faces[abs(aasworld.faceindex[area1->firstface + i])];
+ if (!(face1->faceflags & FACE_GROUND)) continue;
+ //
+ for (j = 0; j < area2->numfaces; j++)
+ {
+ face2 = &aasworld.faces[abs(aasworld.faceindex[area2->firstface + j])];
+ if (!(face2->faceflags & FACE_GROUND)) continue;
+ //if there is a common edge
+ for (edgenum1 = 0; edgenum1 < face1->numedges; edgenum1++)
+ {
+ for (edgenum2 = 0; edgenum2 < face2->numedges; edgenum2++)
+ {
+ if (abs(aasworld.edgeindex[face1->firstedge + edgenum1]) !=
+ abs(aasworld.edgeindex[face2->firstedge + edgenum2]))
+ continue;
+ edgenum = aasworld.edgeindex[face1->firstedge + edgenum1];
+ side = edgenum < 0;
+ edge = &aasworld.edges[abs(edgenum)];
+ //get the length of the edge
+ VectorSubtract(aasworld.vertexes[edge->v[1]],
+ aasworld.vertexes[edge->v[0]], dir);
+ length = VectorLength(dir);
+ //get the start point
+ VectorAdd(aasworld.vertexes[edge->v[0]],
+ aasworld.vertexes[edge->v[1]], start);
+ VectorScale(start, 0.5, start);
+ VectorCopy(start, end);
+ //get the end point several units inside area2
+ //and the start point several units inside area1
+ //NOTE: normal is pointing into area2 because the
+ //face edges are stored counter clockwise
+ VectorSubtract(aasworld.vertexes[edge->v[side]],
+ aasworld.vertexes[edge->v[!side]], edgevec);
+ plane2 = &aasworld.planes[face2->planenum];
+ CrossProduct(edgevec, plane2->normal, normal);
+ VectorNormalize(normal);
+ //
+ //VectorMA(start, -1, normal, start);
+ VectorMA(end, INSIDEUNITS_WALKEND, normal, end);
+ VectorMA(start, INSIDEUNITS_WALKSTART, normal, start);
+ end[2] += 0.125;
+ //
+ height = DotProduct(invgravity, start);
+ //NOTE: if there's nearby solid or a gap area after this area
+ //disabled this crap
+ //if (AAS_NearbySolidOrGap(start, end)) height += 200;
+ //NOTE: disabled because it disables reachabilities to very small areas
+ //if (AAS_PointAreaNum(end) != area2num) continue;
+ //get the longest lowest edge
+ if (height < bestheight ||
+ (height < bestheight + 1 && length > bestlength))
+ {
+ bestheight = height;
+ bestlength = length;
+ //create a new reachability link
+ lr.areanum = area2num;
+ lr.facenum = 0;
+ lr.edgenum = edgenum;
+ VectorCopy(start, lr.start);
+ VectorCopy(end, lr.end);
+ lr.traveltype = TRAVEL_WALK;
+ lr.traveltime = 1;
+ foundreach = qtrue;
+ } //end if
+ } //end for
+ } //end for
+ } //end for
+ } //end for
+ if (foundreach)
+ {
+ //create a new reachability link
+ lreach = AAS_AllocReachability();
+ if (!lreach) return qfalse;
+ lreach->areanum = lr.areanum;
+ lreach->facenum = lr.facenum;
+ lreach->edgenum = lr.edgenum;
+ VectorCopy(lr.start, lreach->start);
+ VectorCopy(lr.end, lreach->end);
+ lreach->traveltype = lr.traveltype;
+ lreach->traveltime = lr.traveltime;
+ lreach->next = areareachability[area1num];
+ areareachability[area1num] = lreach;
+ //if going into a crouch area
+ if (!AAS_AreaCrouch(area1num) && AAS_AreaCrouch(area2num))
+ {
+ lreach->traveltime += aassettings.rs_startcrouch;
+ } //end if
+ /*
+ //NOTE: if there's nearby solid or a gap area after this area
+ if (!AAS_NearbySolidOrGap(lreach->start, lreach->end))
+ {
+ lreach->traveltime += 100;
+ } //end if
+ */
+ //avoid rather small areas
+ //if (AAS_AreaGroundFaceArea(lreach->areanum) < 500) lreach->traveltime += 100;
+ //
+ reach_equalfloor++;
+ return qtrue;
+ } //end if
+ return qfalse;
+} //end of the function AAS_Reachability_EqualFloorHeight
+//===========================================================================
+// searches step, barrier, waterjump and walk off ledge reachabilities
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_Reachability_Step_Barrier_WaterJump_WalkOffLedge(int area1num, int area2num)
+{
+ int i, j, k, l, edge1num, edge2num, areas[10], numareas;
+ int ground_bestarea2groundedgenum, ground_foundreach;
+ int water_bestarea2groundedgenum, water_foundreach;
+ int side1, area1swim, faceside1, groundface1num;
+ float dist, dist1, dist2, diff, invgravitydot, ortdot;
+ float x1, x2, x3, x4, y1, y2, y3, y4, tmp, y;
+ float length, ground_bestlength, water_bestlength, ground_bestdist, water_bestdist;
+ vec3_t v1, v2, v3, v4, tmpv, p1area1, p1area2, p2area1, p2area2;
+ vec3_t normal, ort, edgevec, start, end, dir;
+ vec3_t ground_beststart, ground_bestend, ground_bestnormal;
+ vec3_t water_beststart, water_bestend, water_bestnormal;
+ vec3_t invgravity = {0, 0, 1};
+ vec3_t testpoint;
+ aas_plane_t *plane;
+ aas_area_t *area1, *area2;
+ aas_face_t *groundface1, *groundface2, *ground_bestface1, *water_bestface1;
+ aas_edge_t *edge1, *edge2;
+ aas_lreachability_t *lreach;
+ aas_trace_t trace;
+
+ //must be able to walk or swim in the first area
+ if (!AAS_AreaGrounded(area1num) && !AAS_AreaSwim(area1num)) return qfalse;
+ //
+ if (!AAS_AreaGrounded(area2num) && !AAS_AreaSwim(area2num)) return qfalse;
+ //
+ area1 = &aasworld.areas[area1num];
+ area2 = &aasworld.areas[area2num];
+ //if the first area contains a liquid
+ area1swim = AAS_AreaSwim(area1num);
+ //if the areas are not near anough in the x-y direction
+ for (i = 0; i < 2; i++)
+ {
+ if (area1->mins[i] > area2->maxs[i] + 10) return qfalse;
+ if (area1->maxs[i] < area2->mins[i] - 10) return qfalse;
+ } //end for
+ //
+ ground_foundreach = qfalse;
+ ground_bestdist = 99999;
+ ground_bestlength = 0;
+ ground_bestarea2groundedgenum = 0;
+ //
+ water_foundreach = qfalse;
+ water_bestdist = 99999;
+ water_bestlength = 0;
+ water_bestarea2groundedgenum = 0;
+ //
+ for (i = 0; i < area1->numfaces; i++)
+ {
+ groundface1num = aasworld.faceindex[area1->firstface + i];
+ faceside1 = groundface1num < 0;
+ groundface1 = &aasworld.faces[abs(groundface1num)];
+ //if this isn't a ground face
+ if (!(groundface1->faceflags & FACE_GROUND))
+ {
+ //if we can swim in the first area
+ if (area1swim)
+ {
+ //face plane must be more or less horizontal
+ plane = &aasworld.planes[groundface1->planenum ^ (!faceside1)];
+ if (DotProduct(plane->normal, invgravity) < 0.7) continue;
+ } //end if
+ else
+ {
+ //if we can't swim in the area it must be a ground face
+ continue;
+ } //end else
+ } //end if
+ //
+ for (k = 0; k < groundface1->numedges; k++)
+ {
+ edge1num = aasworld.edgeindex[groundface1->firstedge + k];
+ side1 = (edge1num < 0);
+ //NOTE: for water faces we must take the side area 1 is
+ // on into account because the face is shared and doesn't
+ // have to be oriented correctly
+ if (!(groundface1->faceflags & FACE_GROUND)) side1 = (side1 == faceside1);
+ edge1num = abs(edge1num);
+ edge1 = &aasworld.edges[edge1num];
+ //vertexes of the edge
+ VectorCopy(aasworld.vertexes[edge1->v[!side1]], v1);
+ VectorCopy(aasworld.vertexes[edge1->v[side1]], v2);
+ //get a vertical plane through the edge
+ //NOTE: normal is pointing into area 2 because the
+ //face edges are stored counter clockwise
+ VectorSubtract(v2, v1, edgevec);
+ CrossProduct(edgevec, invgravity, normal);
+ VectorNormalize(normal);
+ dist = DotProduct(normal, v1);
+ //check the faces from the second area
+ for (j = 0; j < area2->numfaces; j++)
+ {
+ groundface2 = &aasworld.faces[abs(aasworld.faceindex[area2->firstface + j])];
+ //must be a ground face
+ if (!(groundface2->faceflags & FACE_GROUND)) continue;
+ //check the edges of this ground face
+ for (l = 0; l < groundface2->numedges; l++)
+ {
+ edge2num = abs(aasworld.edgeindex[groundface2->firstedge + l]);
+ edge2 = &aasworld.edges[edge2num];
+ //vertexes of the edge
+ VectorCopy(aasworld.vertexes[edge2->v[0]], v3);
+ VectorCopy(aasworld.vertexes[edge2->v[1]], v4);
+ //check the distance between the two points and the vertical plane
+ //through the edge of area1
+ diff = DotProduct(normal, v3) - dist;
+ if (diff < -0.1 || diff > 0.1) continue;
+ diff = DotProduct(normal, v4) - dist;
+ if (diff < -0.1 || diff > 0.1) continue;
+ //
+ //project the two ground edges into the step side plane
+ //and calculate the shortest distance between the two
+ //edges if they overlap in the direction orthogonal to
+ //the gravity direction
+ CrossProduct(invgravity, normal, ort);
+ invgravitydot = DotProduct(invgravity, invgravity);
+ ortdot = DotProduct(ort, ort);
+ //projection into the step plane
+ //NOTE: since gravity is vertical this is just the z coordinate
+ y1 = v1[2];//DotProduct(v1, invgravity) / invgravitydot;
+ y2 = v2[2];//DotProduct(v2, invgravity) / invgravitydot;
+ y3 = v3[2];//DotProduct(v3, invgravity) / invgravitydot;
+ y4 = v4[2];//DotProduct(v4, invgravity) / invgravitydot;
+ //
+ x1 = DotProduct(v1, ort) / ortdot;
+ x2 = DotProduct(v2, ort) / ortdot;
+ x3 = DotProduct(v3, ort) / ortdot;
+ x4 = DotProduct(v4, ort) / ortdot;
+ //
+ if (x1 > x2)
+ {
+ tmp = x1; x1 = x2; x2 = tmp;
+ tmp = y1; y1 = y2; y2 = tmp;
+ VectorCopy(v1, tmpv); VectorCopy(v2, v1); VectorCopy(tmpv, v2);
+ } //end if
+ if (x3 > x4)
+ {
+ tmp = x3; x3 = x4; x4 = tmp;
+ tmp = y3; y3 = y4; y4 = tmp;
+ VectorCopy(v3, tmpv); VectorCopy(v4, v3); VectorCopy(tmpv, v4);
+ } //end if
+ //if the two projected edge lines have no overlap
+ if (x2 <= x3 || x4 <= x1)
+ {
+// Log_Write("lines no overlap: from area %d to %d\r\n", area1num, area2num);
+ continue;
+ } //end if
+ //if the two lines fully overlap
+ if ((x1 - 0.5 < x3 && x4 < x2 + 0.5) &&
+ (x3 - 0.5 < x1 && x2 < x4 + 0.5))
+ {
+ dist1 = y3 - y1;
+ dist2 = y4 - y2;
+ VectorCopy(v1, p1area1);
+ VectorCopy(v2, p2area1);
+ VectorCopy(v3, p1area2);
+ VectorCopy(v4, p2area2);
+ } //end if
+ else
+ {
+ //if the points are equal
+ if (x1 > x3 - 0.1 && x1 < x3 + 0.1)
+ {
+ dist1 = y3 - y1;
+ VectorCopy(v1, p1area1);
+ VectorCopy(v3, p1area2);
+ } //end if
+ else if (x1 < x3)
+ {
+ y = y1 + (x3 - x1) * (y2 - y1) / (x2 - x1);
+ dist1 = y3 - y;
+ VectorCopy(v3, p1area1);
+ p1area1[2] = y;
+ VectorCopy(v3, p1area2);
+ } //end if
+ else
+ {
+ y = y3 + (x1 - x3) * (y4 - y3) / (x4 - x3);
+ dist1 = y - y1;
+ VectorCopy(v1, p1area1);
+ VectorCopy(v1, p1area2);
+ p1area2[2] = y;
+ } //end if
+ //if the points are equal
+ if (x2 > x4 - 0.1 && x2 < x4 + 0.1)
+ {
+ dist2 = y4 - y2;
+ VectorCopy(v2, p2area1);
+ VectorCopy(v4, p2area2);
+ } //end if
+ else if (x2 < x4)
+ {
+ y = y3 + (x2 - x3) * (y4 - y3) / (x4 - x3);
+ dist2 = y - y2;
+ VectorCopy(v2, p2area1);
+ VectorCopy(v2, p2area2);
+ p2area2[2] = y;
+ } //end if
+ else
+ {
+ y = y1 + (x4 - x1) * (y2 - y1) / (x2 - x1);
+ dist2 = y4 - y;
+ VectorCopy(v4, p2area1);
+ p2area1[2] = y;
+ VectorCopy(v4, p2area2);
+ } //end else
+ } //end else
+ //if both distances are pretty much equal
+ //then we take the middle of the points
+ if (dist1 > dist2 - 1 && dist1 < dist2 + 1)
+ {
+ dist = dist1;
+ VectorAdd(p1area1, p2area1, start);
+ VectorScale(start, 0.5, start);
+ VectorAdd(p1area2, p2area2, end);
+ VectorScale(end, 0.5, end);
+ } //end if
+ else if (dist1 < dist2)
+ {
+ dist = dist1;
+ VectorCopy(p1area1, start);
+ VectorCopy(p1area2, end);
+ } //end else if
+ else
+ {
+ dist = dist2;
+ VectorCopy(p2area1, start);
+ VectorCopy(p2area2, end);
+ } //end else
+ //get the length of the overlapping part of the edges of the two areas
+ VectorSubtract(p2area2, p1area2, dir);
+ length = VectorLength(dir);
+ //
+ if (groundface1->faceflags & FACE_GROUND)
+ {
+ //if the vertical distance is smaller
+ if (dist < ground_bestdist ||
+ //or the vertical distance is pretty much the same
+ //but the overlapping part of the edges is longer
+ (dist < ground_bestdist + 1 && length > ground_bestlength))
+ {
+ ground_bestdist = dist;
+ ground_bestlength = length;
+ ground_foundreach = qtrue;
+ ground_bestarea2groundedgenum = edge1num;
+ ground_bestface1 = groundface1;
+ //best point towards area1
+ VectorCopy(start, ground_beststart);
+ //normal is pointing into area2
+ VectorCopy(normal, ground_bestnormal);
+ //best point towards area2
+ VectorCopy(end, ground_bestend);
+ } //end if
+ } //end if
+ else
+ {
+ //if the vertical distance is smaller
+ if (dist < water_bestdist ||
+ //or the vertical distance is pretty much the same
+ //but the overlapping part of the edges is longer
+ (dist < water_bestdist + 1 && length > water_bestlength))
+ {
+ water_bestdist = dist;
+ water_bestlength = length;
+ water_foundreach = qtrue;
+ water_bestarea2groundedgenum = edge1num;
+ water_bestface1 = groundface1;
+ //best point towards area1
+ VectorCopy(start, water_beststart);
+ //normal is pointing into area2
+ VectorCopy(normal, water_bestnormal);
+ //best point towards area2
+ VectorCopy(end, water_bestend);
+ } //end if
+ } //end else
+ } //end for
+ } //end for
+ } //end for
+ } //end for
+ //
+ // NOTE: swim reachabilities are already filtered out
+ //
+ // Steps
+ //
+ // ---------
+ // | step height -> TRAVEL_WALK
+ //--------|
+ //
+ // ---------
+ //~~~~~~~~| step height and low water -> TRAVEL_WALK
+ //--------|
+ //
+ //~~~~~~~~~~~~~~~~~~
+ // ---------
+ // | step height and low water up to the step -> TRAVEL_WALK
+ //--------|
+ //
+ //check for a step reachability
+ if (ground_foundreach)
+ {
+ //if area2 is higher but lower than the maximum step height
+ //NOTE: ground_bestdist >= 0 also catches equal floor reachabilities
+ if (ground_bestdist >= 0 && ground_bestdist < aassettings.phys_maxstep)
+ {
+ //create walk reachability from area1 to area2
+ lreach = AAS_AllocReachability();
+ if (!lreach) return qfalse;
+ lreach->areanum = area2num;
+ lreach->facenum = 0;
+ lreach->edgenum = ground_bestarea2groundedgenum;
+ VectorMA(ground_beststart, INSIDEUNITS_WALKSTART, ground_bestnormal, lreach->start);
+ VectorMA(ground_bestend, INSIDEUNITS_WALKEND, ground_bestnormal, lreach->end);
+ lreach->traveltype = TRAVEL_WALK;
+ lreach->traveltime = 0;//1;
+ //if going into a crouch area
+ if (!AAS_AreaCrouch(area1num) && AAS_AreaCrouch(area2num))
+ {
+ lreach->traveltime += aassettings.rs_startcrouch;
+ } //end if
+ lreach->next = areareachability[area1num];
+ areareachability[area1num] = lreach;
+ //NOTE: if there's nearby solid or a gap area after this area
+ /*
+ if (!AAS_NearbySolidOrGap(lreach->start, lreach->end))
+ {
+ lreach->traveltime += 100;
+ } //end if
+ */
+ //avoid rather small areas
+ //if (AAS_AreaGroundFaceArea(lreach->areanum) < 500) lreach->traveltime += 100;
+ //
+ reach_step++;
+ return qtrue;
+ } //end if
+ } //end if
+ //
+ // Water Jumps
+ //
+ // ---------
+ // |
+ //~~~~~~~~|
+ // |
+ // | higher than step height and water up to waterjump height -> TRAVEL_WATERJUMP
+ //--------|
+ //
+ //~~~~~~~~~~~~~~~~~~
+ // ---------
+ // |
+ // |
+ // |
+ // | higher than step height and low water up to the step -> TRAVEL_WATERJUMP
+ //--------|
+ //
+ //check for a waterjump reachability
+ if (water_foundreach)
+ {
+ //get a test point a little bit towards area1
+ VectorMA(water_bestend, -INSIDEUNITS, water_bestnormal, testpoint);
+ //go down the maximum waterjump height
+ testpoint[2] -= aassettings.phys_maxwaterjump;
+ //if there IS water the sv_maxwaterjump height below the bestend point
+ if (aasworld.areasettings[AAS_PointAreaNum(testpoint)].areaflags & AREA_LIQUID)
+ {
+ //don't create rediculous water jump reachabilities from areas very far below
+ //the water surface
+ if (water_bestdist < aassettings.phys_maxwaterjump + 24)
+ {
+ //waterjumping from or towards a crouch only area is not possible in Quake2
+ if ((aasworld.areasettings[area1num].presencetype & PRESENCE_NORMAL) &&
+ (aasworld.areasettings[area2num].presencetype & PRESENCE_NORMAL))
+ {
+ //create water jump reachability from area1 to area2
+ lreach = AAS_AllocReachability();
+ if (!lreach) return qfalse;
+ lreach->areanum = area2num;
+ lreach->facenum = 0;
+ lreach->edgenum = water_bestarea2groundedgenum;
+ VectorCopy(water_beststart, lreach->start);
+ VectorMA(water_bestend, INSIDEUNITS_WATERJUMP, water_bestnormal, lreach->end);
+ lreach->traveltype = TRAVEL_WATERJUMP;
+ lreach->traveltime = aassettings.rs_waterjump;
+ lreach->next = areareachability[area1num];
+ areareachability[area1num] = lreach;
+ //we've got another waterjump reachability
+ reach_waterjump++;
+ return qtrue;
+ } //end if
+ } //end if
+ } //end if
+ } //end if
+ //
+ // Barrier Jumps
+ //
+ // ---------
+ // |
+ // |
+ // |
+ // | higher than step height lower than barrier height -> TRAVEL_BARRIERJUMP
+ //--------|
+ //
+ // ---------
+ // |
+ // |
+ // |
+ //~~~~~~~~| higher than step height lower than barrier height
+ //--------| and a thin layer of water in the area to jump from -> TRAVEL_BARRIERJUMP
+ //
+ //check for a barrier jump reachability
+ if (ground_foundreach)
+ {
+ //if area2 is higher but lower than the maximum barrier jump height
+ if (ground_bestdist > 0 && ground_bestdist < aassettings.phys_maxbarrier)
+ {
+ //if no water in area1 or a very thin layer of water on the ground
+ if (!water_foundreach || (ground_bestdist - water_bestdist < 16))
+ {
+ //cannot perform a barrier jump towards or from a crouch area in Quake2
+ if (!AAS_AreaCrouch(area1num) && !AAS_AreaCrouch(area2num))
+ {
+ //create barrier jump reachability from area1 to area2
+ lreach = AAS_AllocReachability();
+ if (!lreach) return qfalse;
+ lreach->areanum = area2num;
+ lreach->facenum = 0;
+ lreach->edgenum = ground_bestarea2groundedgenum;
+ VectorMA(ground_beststart, INSIDEUNITS_WALKSTART, ground_bestnormal, lreach->start);
+ VectorMA(ground_bestend, INSIDEUNITS_WALKEND, ground_bestnormal, lreach->end);
+ lreach->traveltype = TRAVEL_BARRIERJUMP;
+ lreach->traveltime = aassettings.rs_barrierjump;//AAS_BarrierJumpTravelTime();
+ lreach->next = areareachability[area1num];
+ areareachability[area1num] = lreach;
+ //we've got another barrierjump reachability
+ reach_barrier++;
+ return qtrue;
+ } //end if
+ } //end if
+ } //end if
+ } //end if
+ //
+ // Walk and Walk Off Ledge
+ //
+ //--------|
+ // | can walk or step back -> TRAVEL_WALK
+ // ---------
+ //
+ //--------|
+ // |
+ // |
+ // |
+ // | cannot walk/step back -> TRAVEL_WALKOFFLEDGE
+ // ---------
+ //
+ //--------|
+ // |
+ // |~~~~~~~~
+ // |
+ // | cannot step back but can waterjump back -> TRAVEL_WALKOFFLEDGE
+ // --------- FIXME: create TRAVEL_WALK reach??
+ //
+ //check for a walk or walk off ledge reachability
+ if (ground_foundreach)
+ {
+ if (ground_bestdist < 0)
+ {
+ if (ground_bestdist > -aassettings.phys_maxstep)
+ {
+ //create walk reachability from area1 to area2
+ lreach = AAS_AllocReachability();
+ if (!lreach) return qfalse;
+ lreach->areanum = area2num;
+ lreach->facenum = 0;
+ lreach->edgenum = ground_bestarea2groundedgenum;
+ VectorMA(ground_beststart, INSIDEUNITS_WALKSTART, ground_bestnormal, lreach->start);
+ VectorMA(ground_bestend, INSIDEUNITS_WALKEND, ground_bestnormal, lreach->end);
+ lreach->traveltype = TRAVEL_WALK;
+ lreach->traveltime = 1;
+ lreach->next = areareachability[area1num];
+ areareachability[area1num] = lreach;
+ //we've got another walk reachability
+ reach_walk++;
+ return qtrue;
+ } //end if
+ // if no maximum fall height set or less than the max
+ if (!aassettings.rs_maxfallheight || fabs(ground_bestdist) < aassettings.rs_maxfallheight) {
+ //trace a bounding box vertically to check for solids
+ VectorMA(ground_bestend, INSIDEUNITS, ground_bestnormal, ground_bestend);
+ VectorCopy(ground_bestend, start);
+ start[2] = ground_beststart[2];
+ VectorCopy(ground_bestend, end);
+ end[2] += 4;
+ trace = AAS_TraceClientBBox(start, end, PRESENCE_NORMAL, -1);
+ //if no solids were found
+ if (!trace.startsolid && trace.fraction >= 1.0)
+ {
+ //the trace end point must be in the goal area
+ trace.endpos[2] += 1;
+ if (AAS_PointAreaNum(trace.endpos) == area2num)
+ {
+ //if not going through a cluster portal
+ numareas = AAS_TraceAreas(start, end, areas, NULL, sizeof(areas) / sizeof(int));
+ for (i = 0; i < numareas; i++)
+ if (AAS_AreaClusterPortal(areas[i]))
+ break;
+ if (i >= numareas)
+ {
+ //create a walk off ledge reachability from area1 to area2
+ lreach = AAS_AllocReachability();
+ if (!lreach) return qfalse;
+ lreach->areanum = area2num;
+ lreach->facenum = 0;
+ lreach->edgenum = ground_bestarea2groundedgenum;
+ VectorCopy(ground_beststart, lreach->start);
+ VectorCopy(ground_bestend, lreach->end);
+ lreach->traveltype = TRAVEL_WALKOFFLEDGE;
+ lreach->traveltime = aassettings.rs_startwalkoffledge + fabs(ground_bestdist) * 50 / aassettings.phys_gravity;
+ //if falling from too high and not falling into water
+ if (!AAS_AreaSwim(area2num) && !AAS_AreaJumpPad(area2num))
+ {
+ if (AAS_FallDelta(ground_bestdist) > aassettings.phys_falldelta5)
+ {
+ lreach->traveltime += aassettings.rs_falldamage5;
+ } //end if
+ if (AAS_FallDelta(ground_bestdist) > aassettings.phys_falldelta10)
+ {
+ lreach->traveltime += aassettings.rs_falldamage10;
+ } //end if
+ } //end if
+ lreach->next = areareachability[area1num];
+ areareachability[area1num] = lreach;
+ //
+ reach_walkoffledge++;
+ //NOTE: don't create a weapon (rl, bfg) jump reachability here
+ //because it interferes with other reachabilities
+ //like the ladder reachability
+ return qtrue;
+ } //end if
+ } //end if
+ } //end if
+ } //end if
+ } //end else
+ } //end if
+ return qfalse;
+} //end of the function AAS_Reachability_Step_Barrier_WaterJump_WalkOffLedge
+//===========================================================================
+// returns the distance between the two vectors
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float VectorDistance(vec3_t v1, vec3_t v2)
+{
+ vec3_t dir;
+
+ VectorSubtract(v2, v1, dir);
+ return VectorLength(dir);
+} //end of the function VectorDistance
+//===========================================================================
+// returns true if the first vector is between the last two vectors
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int VectorBetweenVectors(vec3_t v, vec3_t v1, vec3_t v2)
+{
+ vec3_t dir1, dir2;
+
+ VectorSubtract(v, v1, dir1);
+ VectorSubtract(v, v2, dir2);
+ return (DotProduct(dir1, dir2) <= 0);
+} //end of the function VectorBetweenVectors
+//===========================================================================
+// returns the mid point between the two vectors
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void VectorMiddle(vec3_t v1, vec3_t v2, vec3_t middle)
+{
+ VectorAdd(v1, v2, middle);
+ VectorScale(middle, 0.5, middle);
+} //end of the function VectorMiddle
+//===========================================================================
+// calculate a range of points closest to each other on both edges
+//
+// Parameter: beststart1 start of the range of points on edge v1-v2
+// beststart2 end of the range of points on edge v1-v2
+// bestend1 start of the range of points on edge v3-v4
+// bestend2 end of the range of points on edge v3-v4
+// bestdist best distance so far
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+/*
+float AAS_ClosestEdgePoints(vec3_t v1, vec3_t v2, vec3_t v3, vec3_t v4,
+ aas_plane_t *plane1, aas_plane_t *plane2,
+ vec3_t beststart, vec3_t bestend, float bestdist)
+{
+ vec3_t dir1, dir2, p1, p2, p3, p4;
+ float a1, a2, b1, b2, dist;
+ int founddist;
+
+ //edge vectors
+ VectorSubtract(v2, v1, dir1);
+ VectorSubtract(v4, v3, dir2);
+ //get the horizontal directions
+ dir1[2] = 0;
+ dir2[2] = 0;
+ //
+ // p1 = point on an edge vector of area2 closest to v1
+ // p2 = point on an edge vector of area2 closest to v2
+ // p3 = point on an edge vector of area1 closest to v3
+ // p4 = point on an edge vector of area1 closest to v4
+ //
+ if (dir2[0])
+ {
+ a2 = dir2[1] / dir2[0];
+ b2 = v3[1] - a2 * v3[0];
+ //point on the edge vector of area2 closest to v1
+ p1[0] = (DotProduct(v1, dir2) - (a2 * dir2[0] + b2 * dir2[1])) / dir2[0];
+ p1[1] = a2 * p1[0] + b2;
+ //point on the edge vector of area2 closest to v2
+ p2[0] = (DotProduct(v2, dir2) - (a2 * dir2[0] + b2 * dir2[1])) / dir2[0];
+ p2[1] = a2 * p2[0] + b2;
+ } //end if
+ else
+ {
+ //point on the edge vector of area2 closest to v1
+ p1[0] = v3[0];
+ p1[1] = v1[1];
+ //point on the edge vector of area2 closest to v2
+ p2[0] = v3[0];
+ p2[1] = v2[1];
+ } //end else
+ //
+ if (dir1[0])
+ {
+ //
+ a1 = dir1[1] / dir1[0];
+ b1 = v1[1] - a1 * v1[0];
+ //point on the edge vector of area1 closest to v3
+ p3[0] = (DotProduct(v3, dir1) - (a1 * dir1[0] + b1 * dir1[1])) / dir1[0];
+ p3[1] = a1 * p3[0] + b1;
+ //point on the edge vector of area1 closest to v4
+ p4[0] = (DotProduct(v4, dir1) - (a1 * dir1[0] + b1 * dir1[1])) / dir1[0];
+ p4[1] = a1 * p4[0] + b1;
+ } //end if
+ else
+ {
+ //point on the edge vector of area1 closest to v3
+ p3[0] = v1[0];
+ p3[1] = v3[1];
+ //point on the edge vector of area1 closest to v4
+ p4[0] = v1[0];
+ p4[1] = v4[1];
+ } //end else
+ //start with zero z-coordinates
+ p1[2] = 0;
+ p2[2] = 0;
+ p3[2] = 0;
+ p4[2] = 0;
+ //calculate the z-coordinates from the ground planes
+ p1[2] = (plane2->dist - DotProduct(plane2->normal, p1)) / plane2->normal[2];
+ p2[2] = (plane2->dist - DotProduct(plane2->normal, p2)) / plane2->normal[2];
+ p3[2] = (plane1->dist - DotProduct(plane1->normal, p3)) / plane1->normal[2];
+ p4[2] = (plane1->dist - DotProduct(plane1->normal, p4)) / plane1->normal[2];
+ //
+ founddist = qfalse;
+ //
+ if (VectorBetweenVectors(p1, v3, v4))
+ {
+ dist = VectorDistance(v1, p1);
+ if (dist > bestdist - 0.5 && dist < bestdist + 0.5)
+ {
+ VectorMiddle(beststart, v1, beststart);
+ VectorMiddle(bestend, p1, bestend);
+ } //end if
+ else if (dist < bestdist)
+ {
+ bestdist = dist;
+ VectorCopy(v1, beststart);
+ VectorCopy(p1, bestend);
+ } //end if
+ founddist = qtrue;
+ } //end if
+ if (VectorBetweenVectors(p2, v3, v4))
+ {
+ dist = VectorDistance(v2, p2);
+ if (dist > bestdist - 0.5 && dist < bestdist + 0.5)
+ {
+ VectorMiddle(beststart, v2, beststart);
+ VectorMiddle(bestend, p2, bestend);
+ } //end if
+ else if (dist < bestdist)
+ {
+ bestdist = dist;
+ VectorCopy(v2, beststart);
+ VectorCopy(p2, bestend);
+ } //end if
+ founddist = qtrue;
+ } //end else if
+ if (VectorBetweenVectors(p3, v1, v2))
+ {
+ dist = VectorDistance(v3, p3);
+ if (dist > bestdist - 0.5 && dist < bestdist + 0.5)
+ {
+ VectorMiddle(beststart, p3, beststart);
+ VectorMiddle(bestend, v3, bestend);
+ } //end if
+ else if (dist < bestdist)
+ {
+ bestdist = dist;
+ VectorCopy(p3, beststart);
+ VectorCopy(v3, bestend);
+ } //end if
+ founddist = qtrue;
+ } //end else if
+ if (VectorBetweenVectors(p4, v1, v2))
+ {
+ dist = VectorDistance(v4, p4);
+ if (dist > bestdist - 0.5 && dist < bestdist + 0.5)
+ {
+ VectorMiddle(beststart, p4, beststart);
+ VectorMiddle(bestend, v4, bestend);
+ } //end if
+ else if (dist < bestdist)
+ {
+ bestdist = dist;
+ VectorCopy(p4, beststart);
+ VectorCopy(v4, bestend);
+ } //end if
+ founddist = qtrue;
+ } //end else if
+ //if no shortest distance was found the shortest distance
+ //is between one of the vertexes of edge1 and one of edge2
+ if (!founddist)
+ {
+ dist = VectorDistance(v1, v3);
+ if (dist < bestdist)
+ {
+ bestdist = dist;
+ VectorCopy(v1, beststart);
+ VectorCopy(v3, bestend);
+ } //end if
+ dist = VectorDistance(v1, v4);
+ if (dist < bestdist)
+ {
+ bestdist = dist;
+ VectorCopy(v1, beststart);
+ VectorCopy(v4, bestend);
+ } //end if
+ dist = VectorDistance(v2, v3);
+ if (dist < bestdist)
+ {
+ bestdist = dist;
+ VectorCopy(v2, beststart);
+ VectorCopy(v3, bestend);
+ } //end if
+ dist = VectorDistance(v2, v4);
+ if (dist < bestdist)
+ {
+ bestdist = dist;
+ VectorCopy(v2, beststart);
+ VectorCopy(v4, bestend);
+ } //end if
+ } //end if
+ return bestdist;
+} //end of the function AAS_ClosestEdgePoints*/
+
+float AAS_ClosestEdgePoints(vec3_t v1, vec3_t v2, vec3_t v3, vec3_t v4,
+ aas_plane_t *plane1, aas_plane_t *plane2,
+ vec3_t beststart1, vec3_t bestend1,
+ vec3_t beststart2, vec3_t bestend2, float bestdist)
+{
+ vec3_t dir1, dir2, p1, p2, p3, p4;
+ float a1, a2, b1, b2, dist, dist1, dist2;
+ int founddist;
+
+ //edge vectors
+ VectorSubtract(v2, v1, dir1);
+ VectorSubtract(v4, v3, dir2);
+ //get the horizontal directions
+ dir1[2] = 0;
+ dir2[2] = 0;
+ //
+ // p1 = point on an edge vector of area2 closest to v1
+ // p2 = point on an edge vector of area2 closest to v2
+ // p3 = point on an edge vector of area1 closest to v3
+ // p4 = point on an edge vector of area1 closest to v4
+ //
+ if (dir2[0])
+ {
+ a2 = dir2[1] / dir2[0];
+ b2 = v3[1] - a2 * v3[0];
+ //point on the edge vector of area2 closest to v1
+ p1[0] = (DotProduct(v1, dir2) - (a2 * dir2[0] + b2 * dir2[1])) / dir2[0];
+ p1[1] = a2 * p1[0] + b2;
+ //point on the edge vector of area2 closest to v2
+ p2[0] = (DotProduct(v2, dir2) - (a2 * dir2[0] + b2 * dir2[1])) / dir2[0];
+ p2[1] = a2 * p2[0] + b2;
+ } //end if
+ else
+ {
+ //point on the edge vector of area2 closest to v1
+ p1[0] = v3[0];
+ p1[1] = v1[1];
+ //point on the edge vector of area2 closest to v2
+ p2[0] = v3[0];
+ p2[1] = v2[1];
+ } //end else
+ //
+ if (dir1[0])
+ {
+ //
+ a1 = dir1[1] / dir1[0];
+ b1 = v1[1] - a1 * v1[0];
+ //point on the edge vector of area1 closest to v3
+ p3[0] = (DotProduct(v3, dir1) - (a1 * dir1[0] + b1 * dir1[1])) / dir1[0];
+ p3[1] = a1 * p3[0] + b1;
+ //point on the edge vector of area1 closest to v4
+ p4[0] = (DotProduct(v4, dir1) - (a1 * dir1[0] + b1 * dir1[1])) / dir1[0];
+ p4[1] = a1 * p4[0] + b1;
+ } //end if
+ else
+ {
+ //point on the edge vector of area1 closest to v3
+ p3[0] = v1[0];
+ p3[1] = v3[1];
+ //point on the edge vector of area1 closest to v4
+ p4[0] = v1[0];
+ p4[1] = v4[1];
+ } //end else
+ //start with zero z-coordinates
+ p1[2] = 0;
+ p2[2] = 0;
+ p3[2] = 0;
+ p4[2] = 0;
+ //calculate the z-coordinates from the ground planes
+ p1[2] = (plane2->dist - DotProduct(plane2->normal, p1)) / plane2->normal[2];
+ p2[2] = (plane2->dist - DotProduct(plane2->normal, p2)) / plane2->normal[2];
+ p3[2] = (plane1->dist - DotProduct(plane1->normal, p3)) / plane1->normal[2];
+ p4[2] = (plane1->dist - DotProduct(plane1->normal, p4)) / plane1->normal[2];
+ //
+ founddist = qfalse;
+ //
+ if (VectorBetweenVectors(p1, v3, v4))
+ {
+ dist = VectorDistance(v1, p1);
+ if (dist > bestdist - 0.5 && dist < bestdist + 0.5)
+ {
+ dist1 = VectorDistance(beststart1, v1);
+ dist2 = VectorDistance(beststart2, v1);
+ if (dist1 > dist2)
+ {
+ if (dist1 > VectorDistance(beststart1, beststart2)) VectorCopy(v1, beststart2);
+ } //end if
+ else
+ {
+ if (dist2 > VectorDistance(beststart1, beststart2)) VectorCopy(v1, beststart1);
+ } //end else
+ dist1 = VectorDistance(bestend1, p1);
+ dist2 = VectorDistance(bestend2, p1);
+ if (dist1 > dist2)
+ {
+ if (dist1 > VectorDistance(bestend1, bestend2)) VectorCopy(p1, bestend2);
+ } //end if
+ else
+ {
+ if (dist2 > VectorDistance(bestend1, bestend2)) VectorCopy(p1, bestend1);
+ } //end else
+ } //end if
+ else if (dist < bestdist)
+ {
+ bestdist = dist;
+ VectorCopy(v1, beststart1);
+ VectorCopy(v1, beststart2);
+ VectorCopy(p1, bestend1);
+ VectorCopy(p1, bestend2);
+ } //end if
+ founddist = qtrue;
+ } //end if
+ if (VectorBetweenVectors(p2, v3, v4))
+ {
+ dist = VectorDistance(v2, p2);
+ if (dist > bestdist - 0.5 && dist < bestdist + 0.5)
+ {
+ dist1 = VectorDistance(beststart1, v2);
+ dist2 = VectorDistance(beststart2, v2);
+ if (dist1 > dist2)
+ {
+ if (dist1 > VectorDistance(beststart1, beststart2)) VectorCopy(v2, beststart2);
+ } //end if
+ else
+ {
+ if (dist2 > VectorDistance(beststart1, beststart2)) VectorCopy(v2, beststart1);
+ } //end else
+ dist1 = VectorDistance(bestend1, p2);
+ dist2 = VectorDistance(bestend2, p2);
+ if (dist1 > dist2)
+ {
+ if (dist1 > VectorDistance(bestend1, bestend2)) VectorCopy(p2, bestend2);
+ } //end if
+ else
+ {
+ if (dist2 > VectorDistance(bestend1, bestend2)) VectorCopy(p2, bestend1);
+ } //end else
+ } //end if
+ else if (dist < bestdist)
+ {
+ bestdist = dist;
+ VectorCopy(v2, beststart1);
+ VectorCopy(v2, beststart2);
+ VectorCopy(p2, bestend1);
+ VectorCopy(p2, bestend2);
+ } //end if
+ founddist = qtrue;
+ } //end else if
+ if (VectorBetweenVectors(p3, v1, v2))
+ {
+ dist = VectorDistance(v3, p3);
+ if (dist > bestdist - 0.5 && dist < bestdist + 0.5)
+ {
+ dist1 = VectorDistance(beststart1, p3);
+ dist2 = VectorDistance(beststart2, p3);
+ if (dist1 > dist2)
+ {
+ if (dist1 > VectorDistance(beststart1, beststart2)) VectorCopy(p3, beststart2);
+ } //end if
+ else
+ {
+ if (dist2 > VectorDistance(beststart1, beststart2)) VectorCopy(p3, beststart1);
+ } //end else
+ dist1 = VectorDistance(bestend1, v3);
+ dist2 = VectorDistance(bestend2, v3);
+ if (dist1 > dist2)
+ {
+ if (dist1 > VectorDistance(bestend1, bestend2)) VectorCopy(v3, bestend2);
+ } //end if
+ else
+ {
+ if (dist2 > VectorDistance(bestend1, bestend2)) VectorCopy(v3, bestend1);
+ } //end else
+ } //end if
+ else if (dist < bestdist)
+ {
+ bestdist = dist;
+ VectorCopy(p3, beststart1);
+ VectorCopy(p3, beststart2);
+ VectorCopy(v3, bestend1);
+ VectorCopy(v3, bestend2);
+ } //end if
+ founddist = qtrue;
+ } //end else if
+ if (VectorBetweenVectors(p4, v1, v2))
+ {
+ dist = VectorDistance(v4, p4);
+ if (dist > bestdist - 0.5 && dist < bestdist + 0.5)
+ {
+ dist1 = VectorDistance(beststart1, p4);
+ dist2 = VectorDistance(beststart2, p4);
+ if (dist1 > dist2)
+ {
+ if (dist1 > VectorDistance(beststart1, beststart2)) VectorCopy(p4, beststart2);
+ } //end if
+ else
+ {
+ if (dist2 > VectorDistance(beststart1, beststart2)) VectorCopy(p4, beststart1);
+ } //end else
+ dist1 = VectorDistance(bestend1, v4);
+ dist2 = VectorDistance(bestend2, v4);
+ if (dist1 > dist2)
+ {
+ if (dist1 > VectorDistance(bestend1, bestend2)) VectorCopy(v4, bestend2);
+ } //end if
+ else
+ {
+ if (dist2 > VectorDistance(bestend1, bestend2)) VectorCopy(v4, bestend1);
+ } //end else
+ } //end if
+ else if (dist < bestdist)
+ {
+ bestdist = dist;
+ VectorCopy(p4, beststart1);
+ VectorCopy(p4, beststart2);
+ VectorCopy(v4, bestend1);
+ VectorCopy(v4, bestend2);
+ } //end if
+ founddist = qtrue;
+ } //end else if
+ //if no shortest distance was found the shortest distance
+ //is between one of the vertexes of edge1 and one of edge2
+ if (!founddist)
+ {
+ dist = VectorDistance(v1, v3);
+ if (dist < bestdist)
+ {
+ bestdist = dist;
+ VectorCopy(v1, beststart1);
+ VectorCopy(v1, beststart2);
+ VectorCopy(v3, bestend1);
+ VectorCopy(v3, bestend2);
+ } //end if
+ dist = VectorDistance(v1, v4);
+ if (dist < bestdist)
+ {
+ bestdist = dist;
+ VectorCopy(v1, beststart1);
+ VectorCopy(v1, beststart2);
+ VectorCopy(v4, bestend1);
+ VectorCopy(v4, bestend2);
+ } //end if
+ dist = VectorDistance(v2, v3);
+ if (dist < bestdist)
+ {
+ bestdist = dist;
+ VectorCopy(v2, beststart1);
+ VectorCopy(v2, beststart2);
+ VectorCopy(v3, bestend1);
+ VectorCopy(v3, bestend2);
+ } //end if
+ dist = VectorDistance(v2, v4);
+ if (dist < bestdist)
+ {
+ bestdist = dist;
+ VectorCopy(v2, beststart1);
+ VectorCopy(v2, beststart2);
+ VectorCopy(v4, bestend1);
+ VectorCopy(v4, bestend2);
+ } //end if
+ } //end if
+ return bestdist;
+} //end of the function AAS_ClosestEdgePoints
+//===========================================================================
+// creates possible jump reachabilities between the areas
+//
+// The two closest points on the ground of the areas are calculated
+// One of the points will be on an edge of a ground face of area1 and
+// one on an edge of a ground face of area2.
+// If there is a range of closest points the point in the middle of this range
+// is selected.
+// Between these two points there must be one or more gaps.
+// If the gaps exist a potential jump is predicted.
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_Reachability_Jump(int area1num, int area2num)
+{
+ int i, j, k, l, face1num, face2num, edge1num, edge2num, traveltype;
+ int stopevent, areas[10], numareas;
+ float phys_jumpvel, maxjumpdistance, maxjumpheight, height, bestdist, speed;
+ vec_t *v1, *v2, *v3, *v4;
+ vec3_t beststart, beststart2, bestend, bestend2;
+ vec3_t teststart, testend, dir, velocity, cmdmove, up = {0, 0, 1}, sidewards;
+ aas_area_t *area1, *area2;
+ aas_face_t *face1, *face2;
+ aas_edge_t *edge1, *edge2;
+ aas_plane_t *plane1, *plane2, *plane;
+ aas_trace_t trace;
+ aas_clientmove_t move;
+ aas_lreachability_t *lreach;
+
+ if (!AAS_AreaGrounded(area1num) || !AAS_AreaGrounded(area2num)) return qfalse;
+ //cannot jump from or to a crouch area
+ if (AAS_AreaCrouch(area1num) || AAS_AreaCrouch(area2num)) return qfalse;
+ //
+ area1 = &aasworld.areas[area1num];
+ area2 = &aasworld.areas[area2num];
+ //
+ phys_jumpvel = aassettings.phys_jumpvel;
+ //maximum distance a player can jump
+ maxjumpdistance = 2 * AAS_MaxJumpDistance(phys_jumpvel);
+ //maximum height a player can jump with the given initial z velocity
+ maxjumpheight = AAS_MaxJumpHeight(phys_jumpvel);
+
+ //if the areas are not near anough in the x-y direction
+ for (i = 0; i < 2; i++)
+ {
+ if (area1->mins[i] > area2->maxs[i] + maxjumpdistance) return qfalse;
+ if (area1->maxs[i] < area2->mins[i] - maxjumpdistance) return qfalse;
+ } //end for
+ //if area2 is way to high to jump up to
+ if (area2->mins[2] > area1->maxs[2] + maxjumpheight) return qfalse;
+ //
+ bestdist = 999999;
+ //
+ for (i = 0; i < area1->numfaces; i++)
+ {
+ face1num = aasworld.faceindex[area1->firstface + i];
+ face1 = &aasworld.faces[abs(face1num)];
+ //if not a ground face
+ if (!(face1->faceflags & FACE_GROUND)) continue;
+ //
+ for (j = 0; j < area2->numfaces; j++)
+ {
+ face2num = aasworld.faceindex[area2->firstface + j];
+ face2 = &aasworld.faces[abs(face2num)];
+ //if not a ground face
+ if (!(face2->faceflags & FACE_GROUND)) continue;
+ //
+ for (k = 0; k < face1->numedges; k++)
+ {
+ edge1num = abs(aasworld.edgeindex[face1->firstedge + k]);
+ edge1 = &aasworld.edges[edge1num];
+ for (l = 0; l < face2->numedges; l++)
+ {
+ edge2num = abs(aasworld.edgeindex[face2->firstedge + l]);
+ edge2 = &aasworld.edges[edge2num];
+ //calculate the minimum distance between the two edges
+ v1 = aasworld.vertexes[edge1->v[0]];
+ v2 = aasworld.vertexes[edge1->v[1]];
+ v3 = aasworld.vertexes[edge2->v[0]];
+ v4 = aasworld.vertexes[edge2->v[1]];
+ //get the ground planes
+ plane1 = &aasworld.planes[face1->planenum];
+ plane2 = &aasworld.planes[face2->planenum];
+ //
+ bestdist = AAS_ClosestEdgePoints(v1, v2, v3, v4, plane1, plane2,
+ beststart, bestend,
+ beststart2, bestend2, bestdist);
+ } //end for
+ } //end for
+ } //end for
+ } //end for
+ VectorMiddle(beststart, beststart2, beststart);
+ VectorMiddle(bestend, bestend2, bestend);
+ if (bestdist > 4 && bestdist < maxjumpdistance)
+ {
+// Log_Write("shortest distance between %d and %d is %f\r\n", area1num, area2num, bestdist);
+ // if very close and almost no height difference then the bot can walk
+ if (bestdist <= 48 && fabs(beststart[2] - bestend[2]) < 8)
+ {
+ speed = 400;
+ traveltype = TRAVEL_WALKOFFLEDGE;
+ } //end if
+ else if (AAS_HorizontalVelocityForJump(0, beststart, bestend, &speed))
+ {
+ //FIXME: why multiply with 1.2???
+ speed *= 1.2f;
+ traveltype = TRAVEL_WALKOFFLEDGE;
+ } //end else if
+ else
+ {
+ //get the horizontal speed for the jump, if it isn't possible to calculate this
+ //speed (the jump is not possible) then there's no jump reachability created
+ if (!AAS_HorizontalVelocityForJump(phys_jumpvel, beststart, bestend, &speed))
+ return qfalse;
+ speed *= 1.05f;
+ traveltype = TRAVEL_JUMP;
+ //
+ //NOTE: test if the horizontal distance isn't too small
+ VectorSubtract(bestend, beststart, dir);
+ dir[2] = 0;
+ if (VectorLength(dir) < 10)
+ return qfalse;
+ } //end if
+ //
+ VectorSubtract(bestend, beststart, dir);
+ VectorNormalize(dir);
+ VectorMA(beststart, 1, dir, teststart);
+ //
+ VectorCopy(teststart, testend);
+ testend[2] -= 100;
+ trace = AAS_TraceClientBBox(teststart, testend, PRESENCE_NORMAL, -1);
+ //
+ if (trace.startsolid)
+ return qfalse;
+ if (trace.fraction < 1)
+ {
+ plane = &aasworld.planes[trace.planenum];
+ // if the bot can stand on the surface
+ if (DotProduct(plane->normal, up) >= 0.7)
+ {
+ // if no lava or slime below
+ if (!(AAS_PointContents(trace.endpos) & (CONTENTS_LAVA|CONTENTS_SLIME)))
+ {
+ if (teststart[2] - trace.endpos[2] <= aassettings.phys_maxbarrier)
+ return qfalse;
+ } //end if
+ } //end if
+ } //end if
+ //
+ VectorMA(bestend, -1, dir, teststart);
+ //
+ VectorCopy(teststart, testend);
+ testend[2] -= 100;
+ trace = AAS_TraceClientBBox(teststart, testend, PRESENCE_NORMAL, -1);
+ //
+ if (trace.startsolid)
+ return qfalse;
+ if (trace.fraction < 1)
+ {
+ plane = &aasworld.planes[trace.planenum];
+ // if the bot can stand on the surface
+ if (DotProduct(plane->normal, up) >= 0.7)
+ {
+ // if no lava or slime below
+ if (!(AAS_PointContents(trace.endpos) & (CONTENTS_LAVA|CONTENTS_SLIME)))
+ {
+ if (teststart[2] - trace.endpos[2] <= aassettings.phys_maxbarrier)
+ return qfalse;
+ } //end if
+ } //end if
+ } //end if
+ //
+ // get command movement
+ VectorClear(cmdmove);
+ if ((traveltype & TRAVELTYPE_MASK) == TRAVEL_JUMP)
+ cmdmove[2] = aassettings.phys_jumpvel;
+ else
+ cmdmove[2] = 0;
+ //
+ VectorSubtract(bestend, beststart, dir);
+ dir[2] = 0;
+ VectorNormalize(dir);
+ CrossProduct(dir, up, sidewards);
+ //
+ stopevent = SE_HITGROUND|SE_ENTERWATER|SE_ENTERSLIME|SE_ENTERLAVA|SE_HITGROUNDDAMAGE;
+ if (!AAS_AreaClusterPortal(area1num) && !AAS_AreaClusterPortal(area2num))
+ stopevent |= SE_TOUCHCLUSTERPORTAL;
+ //
+ for (i = 0; i < 3; i++)
+ {
+ //
+ if (i == 1)
+ VectorAdd(testend, sidewards, testend);
+ else if (i == 2)
+ VectorSubtract(bestend, sidewards, testend);
+ else
+ VectorCopy(bestend, testend);
+ VectorSubtract(testend, beststart, dir);
+ dir[2] = 0;
+ VectorNormalize(dir);
+ VectorScale(dir, speed, velocity);
+ //
+ AAS_PredictClientMovement(&move, -1, beststart, PRESENCE_NORMAL, qtrue,
+ velocity, cmdmove, 3, 30, 0.1f,
+ stopevent, 0, qfalse);
+ // if prediction time wasn't enough to fully predict the movement
+ if (move.frames >= 30)
+ return qfalse;
+ // don't enter slime or lava and don't fall from too high
+ if (move.stopevent & (SE_ENTERSLIME|SE_ENTERLAVA))
+ return qfalse;
+ // never jump or fall through a cluster portal
+ if (move.stopevent & SE_TOUCHCLUSTERPORTAL)
+ return qfalse;
+ //the end position should be in area2, also test a little bit back
+ //because the predicted jump could have rushed through the area
+ VectorMA(move.endpos, -64, dir, teststart);
+ teststart[2] += 1;
+ numareas = AAS_TraceAreas(move.endpos, teststart, areas, NULL, sizeof(areas) / sizeof(int));
+ for (j = 0; j < numareas; j++)
+ {
+ if (areas[j] == area2num)
+ break;
+ } //end for
+ if (j < numareas)
+ break;
+ }
+ if (i >= 3)
+ return qfalse;
+ //
+#ifdef REACH_DEBUG
+ //create the reachability
+ Log_Write("jump reachability between %d and %d\r\n", area1num, area2num);
+#endif //REACH_DEBUG
+ //create a new reachability link
+ lreach = AAS_AllocReachability();
+ if (!lreach) return qfalse;
+ lreach->areanum = area2num;
+ lreach->facenum = 0;
+ lreach->edgenum = 0;
+ VectorCopy(beststart, lreach->start);
+ VectorCopy(bestend, lreach->end);
+ lreach->traveltype = traveltype;
+
+ VectorSubtract(bestend, beststart, dir);
+ height = dir[2];
+ dir[2] = 0;
+ if ((traveltype & TRAVELTYPE_MASK) == TRAVEL_WALKOFFLEDGE && height > VectorLength(dir))
+ {
+ lreach->traveltime = aassettings.rs_startwalkoffledge + height * 50 / aassettings.phys_gravity;
+ }
+ else
+ {
+ lreach->traveltime = aassettings.rs_startjump + VectorDistance(bestend, beststart) * 240 / aassettings.phys_maxwalkvelocity;
+ } //end if
+ //
+ if (!AAS_AreaJumpPad(area2num))
+ {
+ if (AAS_FallDelta(beststart[2] - bestend[2]) > aassettings.phys_falldelta5)
+ {
+ lreach->traveltime += aassettings.rs_falldamage5;
+ } //end if
+ else if (AAS_FallDelta(beststart[2] - bestend[2]) > aassettings.phys_falldelta10)
+ {
+ lreach->traveltime += aassettings.rs_falldamage10;
+ } //end if
+ } //end if
+ lreach->next = areareachability[area1num];
+ areareachability[area1num] = lreach;
+ //
+ if ((traveltype & TRAVELTYPE_MASK) == TRAVEL_JUMP)
+ reach_jump++;
+ else
+ reach_walkoffledge++;
+ } //end if
+ return qfalse;
+} //end of the function AAS_Reachability_Jump
+//===========================================================================
+// create a possible ladder reachability from area1 to area2
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_Reachability_Ladder(int area1num, int area2num)
+{
+ int i, j, k, l, edge1num, edge2num, sharededgenum, lowestedgenum;
+ int face1num, face2num, ladderface1num, ladderface2num;
+ int ladderface1vertical, ladderface2vertical, firstv;
+ float face1area, face2area, bestface1area, bestface2area;
+ float phys_jumpvel, maxjumpheight;
+ vec3_t area1point, area2point, v1, v2, up = {0, 0, 1};
+ vec3_t mid, lowestpoint, start, end, sharededgevec, dir;
+ aas_area_t *area1, *area2;
+ aas_face_t *face1, *face2, *ladderface1, *ladderface2;
+ aas_plane_t *plane1, *plane2;
+ aas_edge_t *sharededge, *edge1;
+ aas_lreachability_t *lreach;
+ aas_trace_t trace;
+
+ if (!AAS_AreaLadder(area1num) || !AAS_AreaLadder(area2num)) return qfalse;
+ //
+ phys_jumpvel = aassettings.phys_jumpvel;
+ //maximum height a player can jump with the given initial z velocity
+ maxjumpheight = AAS_MaxJumpHeight(phys_jumpvel);
+
+ area1 = &aasworld.areas[area1num];
+ area2 = &aasworld.areas[area2num];
+ //
+ ladderface1 = NULL;
+ ladderface2 = NULL;
+ ladderface1num = 0; //make compiler happy
+ ladderface2num = 0; //make compiler happy
+ bestface1area = -9999;
+ bestface2area = -9999;
+ sharededgenum = 0; //make compiler happy
+ lowestedgenum = 0; //make compiler happy
+ //
+ for (i = 0; i < area1->numfaces; i++)
+ {
+ face1num = aasworld.faceindex[area1->firstface + i];
+ face1 = &aasworld.faces[abs(face1num)];
+ //if not a ladder face
+ if (!(face1->faceflags & FACE_LADDER)) continue;
+ //
+ for (j = 0; j < area2->numfaces; j++)
+ {
+ face2num = aasworld.faceindex[area2->firstface + j];
+ face2 = &aasworld.faces[abs(face2num)];
+ //if not a ladder face
+ if (!(face2->faceflags & FACE_LADDER)) continue;
+ //check if the faces share an edge
+ for (k = 0; k < face1->numedges; k++)
+ {
+ edge1num = aasworld.edgeindex[face1->firstedge + k];
+ for (l = 0; l < face2->numedges; l++)
+ {
+ edge2num = aasworld.edgeindex[face2->firstedge + l];
+ if (abs(edge1num) == abs(edge2num))
+ {
+ //get the face with the largest area
+ face1area = AAS_FaceArea(face1);
+ face2area = AAS_FaceArea(face2);
+ if (face1area > bestface1area && face2area > bestface2area)
+ {
+ bestface1area = face1area;
+ bestface2area = face2area;
+ ladderface1 = face1;
+ ladderface2 = face2;
+ ladderface1num = face1num;
+ ladderface2num = face2num;
+ sharededgenum = edge1num;
+ } //end if
+ break;
+ } //end if
+ } //end for
+ if (l != face2->numedges) break;
+ } //end for
+ } //end for
+ } //end for
+ //
+ if (ladderface1 && ladderface2)
+ {
+ //get the middle of the shared edge
+ sharededge = &aasworld.edges[abs(sharededgenum)];
+ firstv = sharededgenum < 0;
+ //
+ VectorCopy(aasworld.vertexes[sharededge->v[firstv]], v1);
+ VectorCopy(aasworld.vertexes[sharededge->v[!firstv]], v2);
+ VectorAdd(v1, v2, area1point);
+ VectorScale(area1point, 0.5, area1point);
+ VectorCopy(area1point, area2point);
+ //
+ //if the face plane in area 1 is pretty much vertical
+ plane1 = &aasworld.planes[ladderface1->planenum ^ (ladderface1num < 0)];
+ plane2 = &aasworld.planes[ladderface2->planenum ^ (ladderface2num < 0)];
+ //
+ //get the points really into the areas
+ VectorSubtract(v2, v1, sharededgevec);
+ CrossProduct(plane1->normal, sharededgevec, dir);
+ VectorNormalize(dir);
+ //NOTE: 32 because that's larger than 16 (bot bbox x,y)
+ VectorMA(area1point, -32, dir, area1point);
+ VectorMA(area2point, 32, dir, area2point);
+ //
+ ladderface1vertical = abs(DotProduct(plane1->normal, up)) < 0.1;
+ ladderface2vertical = abs(DotProduct(plane2->normal, up)) < 0.1;
+ //there's only reachability between vertical ladder faces
+ if (!ladderface1vertical && !ladderface2vertical) return qfalse;
+ //if both vertical ladder faces
+ if (ladderface1vertical && ladderface2vertical
+ //and the ladder faces do not make a sharp corner
+ && DotProduct(plane1->normal, plane2->normal) > 0.7
+ //and the shared edge is not too vertical
+ && abs(DotProduct(sharededgevec, up)) < 0.7)
+ {
+ //create a new reachability link
+ lreach = AAS_AllocReachability();
+ if (!lreach) return qfalse;
+ lreach->areanum = area2num;
+ lreach->facenum = ladderface1num;
+ lreach->edgenum = abs(sharededgenum);
+ VectorCopy(area1point, lreach->start);
+ //VectorCopy(area2point, lreach->end);
+ VectorMA(area2point, -3, plane1->normal, lreach->end);
+ lreach->traveltype = TRAVEL_LADDER;
+ lreach->traveltime = 10;
+ lreach->next = areareachability[area1num];
+ areareachability[area1num] = lreach;
+ //
+ reach_ladder++;
+ //create a new reachability link
+ lreach = AAS_AllocReachability();
+ if (!lreach) return qfalse;
+ lreach->areanum = area1num;
+ lreach->facenum = ladderface2num;
+ lreach->edgenum = abs(sharededgenum);
+ VectorCopy(area2point, lreach->start);
+ //VectorCopy(area1point, lreach->end);
+ VectorMA(area1point, -3, plane1->normal, lreach->end);
+ lreach->traveltype = TRAVEL_LADDER;
+ lreach->traveltime = 10;
+ lreach->next = areareachability[area2num];
+ areareachability[area2num] = lreach;
+ //
+ reach_ladder++;
+ //
+ return qtrue;
+ } //end if
+ //if the second ladder face is also a ground face
+ //create ladder end (just ladder) reachability and
+ //walk off a ladder (ledge) reachability
+ if (ladderface1vertical && (ladderface2->faceflags & FACE_GROUND))
+ {
+ //create a new reachability link
+ lreach = AAS_AllocReachability();
+ if (!lreach) return qfalse;
+ lreach->areanum = area2num;
+ lreach->facenum = ladderface1num;
+ lreach->edgenum = abs(sharededgenum);
+ VectorCopy(area1point, lreach->start);
+ VectorCopy(area2point, lreach->end);
+ lreach->end[2] += 16;
+ VectorMA(lreach->end, -15, plane1->normal, lreach->end);
+ lreach->traveltype = TRAVEL_LADDER;
+ lreach->traveltime = 10;
+ lreach->next = areareachability[area1num];
+ areareachability[area1num] = lreach;
+ //
+ reach_ladder++;
+ //create a new reachability link
+ lreach = AAS_AllocReachability();
+ if (!lreach) return qfalse;
+ lreach->areanum = area1num;
+ lreach->facenum = ladderface2num;
+ lreach->edgenum = abs(sharededgenum);
+ VectorCopy(area2point, lreach->start);
+ VectorCopy(area1point, lreach->end);
+ lreach->traveltype = TRAVEL_WALKOFFLEDGE;
+ lreach->traveltime = 10;
+ lreach->next = areareachability[area2num];
+ areareachability[area2num] = lreach;
+ //
+ reach_walkoffledge++;
+ //
+ return qtrue;
+ } //end if
+ //
+ if (ladderface1vertical)
+ {
+ //find lowest edge of the ladder face
+ lowestpoint[2] = 99999;
+ for (i = 0; i < ladderface1->numedges; i++)
+ {
+ edge1num = abs(aasworld.edgeindex[ladderface1->firstedge + i]);
+ edge1 = &aasworld.edges[edge1num];
+ //
+ VectorCopy(aasworld.vertexes[edge1->v[0]], v1);
+ VectorCopy(aasworld.vertexes[edge1->v[1]], v2);
+ //
+ VectorAdd(v1, v2, mid);
+ VectorScale(mid, 0.5, mid);
+ //
+ if (mid[2] < lowestpoint[2])
+ {
+ VectorCopy(mid, lowestpoint);
+ lowestedgenum = edge1num;
+ } //end if
+ } //end for
+ //
+ plane1 = &aasworld.planes[ladderface1->planenum];
+ //trace down in the middle of this edge
+ VectorMA(lowestpoint, 5, plane1->normal, start);
+ VectorCopy(start, end);
+ start[2] += 5;
+ end[2] -= 100;
+ //trace without entity collision
+ trace = AAS_TraceClientBBox(start, end, PRESENCE_NORMAL, -1);
+ //
+ //
+#ifdef REACH_DEBUG
+ if (trace.startsolid)
+ {
+ Log_Write("trace from area %d started in solid\r\n", area1num);
+ } //end if
+#endif //REACH_DEBUG
+ //
+ trace.endpos[2] += 1;
+ area2num = AAS_PointAreaNum(trace.endpos);
+ //
+ area2 = &aasworld.areas[area2num];
+ for (i = 0; i < area2->numfaces; i++)
+ {
+ face2num = aasworld.faceindex[area2->firstface + i];
+ face2 = &aasworld.faces[abs(face2num)];
+ //
+ if (face2->faceflags & FACE_LADDER)
+ {
+ plane2 = &aasworld.planes[face2->planenum];
+ if (abs(DotProduct(plane2->normal, up)) < 0.1) break;
+ } //end if
+ } //end for
+ //if from another area without vertical ladder faces
+ if (i >= area2->numfaces && area2num != area1num &&
+ //the reachabilities shouldn't exist already
+ !AAS_ReachabilityExists(area1num, area2num) &&
+ !AAS_ReachabilityExists(area2num, area1num))
+ {
+ //if the height is jumpable
+ if (start[2] - trace.endpos[2] < maxjumpheight)
+ {
+ //create a new reachability link
+ lreach = AAS_AllocReachability();
+ if (!lreach) return qfalse;
+ lreach->areanum = area2num;
+ lreach->facenum = ladderface1num;
+ lreach->edgenum = lowestedgenum;
+ VectorCopy(lowestpoint, lreach->start);
+ VectorCopy(trace.endpos, lreach->end);
+ lreach->traveltype = TRAVEL_LADDER;
+ lreach->traveltime = 10;
+ lreach->next = areareachability[area1num];
+ areareachability[area1num] = lreach;
+ //
+ reach_ladder++;
+ //create a new reachability link
+ lreach = AAS_AllocReachability();
+ if (!lreach) return qfalse;
+ lreach->areanum = area1num;
+ lreach->facenum = ladderface1num;
+ lreach->edgenum = lowestedgenum;
+ VectorCopy(trace.endpos, lreach->start);
+ //get the end point a little bit into the ladder
+ VectorMA(lowestpoint, -5, plane1->normal, lreach->end);
+ //get the end point a little higher
+ lreach->end[2] += 10;
+ lreach->traveltype = TRAVEL_JUMP;
+ lreach->traveltime = 10;
+ lreach->next = areareachability[area2num];
+ areareachability[area2num] = lreach;
+ //
+ reach_jump++;
+ //
+ return qtrue;
+#ifdef REACH_DEBUG
+ Log_Write("jump up to ladder reach between %d and %d\r\n", area2num, area1num);
+#endif //REACH_DEBUG
+ } //end if
+#ifdef REACH_DEBUG
+ else Log_Write("jump too high between area %d and %d\r\n", area2num, area1num);
+#endif //REACH_DEBUG
+ } //end if
+ /*//if slime or lava below the ladder
+ //try jump reachability from far towards the ladder
+ if (aasworld.areasettings[area2num].contents & (AREACONTENTS_SLIME
+ | AREACONTENTS_LAVA))
+ {
+ for (i = 20; i <= 120; i += 20)
+ {
+ //trace down in the middle of this edge
+ VectorMA(lowestpoint, i, plane1->normal, start);
+ VectorCopy(start, end);
+ start[2] += 5;
+ end[2] -= 100;
+ //trace without entity collision
+ trace = AAS_TraceClientBBox(start, end, PRESENCE_NORMAL, -1);
+ //
+ if (trace.startsolid) break;
+ trace.endpos[2] += 1;
+ area2num = AAS_PointAreaNum(trace.endpos);
+ if (area2num == area1num) continue;
+ //
+ if (start[2] - trace.endpos[2] > maxjumpheight) continue;
+ if (aasworld.areasettings[area2num].contents & (AREACONTENTS_SLIME
+ | AREACONTENTS_LAVA)) continue;
+ //
+ //create a new reachability link
+ lreach = AAS_AllocReachability();
+ if (!lreach) return qfalse;
+ lreach->areanum = area1num;
+ lreach->facenum = ladderface1num;
+ lreach->edgenum = lowestedgenum;
+ VectorCopy(trace.endpos, lreach->start);
+ VectorCopy(lowestpoint, lreach->end);
+ lreach->end[2] += 5;
+ lreach->traveltype = TRAVEL_JUMP;
+ lreach->traveltime = 10;
+ lreach->next = areareachability[area2num];
+ areareachability[area2num] = lreach;
+ //
+ reach_jump++;
+ //
+ Log_Write("jump far to ladder reach between %d and %d\r\n", area2num, area1num);
+ //
+ break;
+ } //end for
+ } //end if*/
+ } //end if
+ } //end if
+ return qfalse;
+} //end of the function AAS_Reachability_Ladder
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_TravelFlagsForTeam(int ent)
+{
+ int notteam;
+
+ if (!AAS_IntForBSPEpairKey(ent, "bot_notteam", &notteam))
+ return 0;
+ if (notteam == 1)
+ return TRAVELFLAG_NOTTEAM1;
+ if (notteam == 2)
+ return TRAVELFLAG_NOTTEAM2;
+ return 0;
+} //end of the function AAS_TravelFlagsForTeam
+//===========================================================================
+// create possible teleporter reachabilities
+// this is very game dependent.... :(
+//
+// classname = trigger_multiple or trigger_teleport
+// target = "t1"
+//
+// classname = target_teleporter
+// targetname = "t1"
+// target = "t2"
+//
+// classname = misc_teleporter_dest
+// targetname = "t2"
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_Reachability_Teleport(void)
+{
+ int area1num, area2num;
+ char target[MAX_EPAIRKEY], targetname[MAX_EPAIRKEY];
+ char classname[MAX_EPAIRKEY], model[MAX_EPAIRKEY];
+ int ent, dest;
+ float angle;
+ vec3_t origin, destorigin, mins, maxs, end, angles;
+ vec3_t mid, velocity, cmdmove;
+ aas_lreachability_t *lreach;
+ aas_clientmove_t move;
+ aas_trace_t trace;
+ aas_link_t *areas, *link;
+
+ for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent))
+ {
+ if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) continue;
+ if (!strcmp(classname, "trigger_multiple"))
+ {
+ AAS_ValueForBSPEpairKey(ent, "model", model, MAX_EPAIRKEY);
+//#ifdef REACH_DEBUG
+ botimport.Print(PRT_MESSAGE, "trigger_multiple model = \"%s\"\n", model);
+//#endif REACH_DEBUG
+ VectorClear(angles);
+ AAS_BSPModelMinsMaxsOrigin(atoi(model+1), angles, mins, maxs, origin);
+ //
+ if (!AAS_ValueForBSPEpairKey(ent, "target", target, MAX_EPAIRKEY))
+ {
+ botimport.Print(PRT_ERROR, "trigger_multiple at %1.0f %1.0f %1.0f without target\n",
+ origin[0], origin[1], origin[2]);
+ continue;
+ } //end if
+ for (dest = AAS_NextBSPEntity(0); dest; dest = AAS_NextBSPEntity(dest))
+ {
+ if (!AAS_ValueForBSPEpairKey(dest, "classname", classname, MAX_EPAIRKEY)) continue;
+ if (!strcmp(classname, "target_teleporter"))
+ {
+ if (!AAS_ValueForBSPEpairKey(dest, "targetname", targetname, MAX_EPAIRKEY)) continue;
+ if (!strcmp(targetname, target))
+ {
+ break;
+ } //end if
+ } //end if
+ } //end for
+ if (!dest)
+ {
+ continue;
+ } //end if
+ if (!AAS_ValueForBSPEpairKey(dest, "target", target, MAX_EPAIRKEY))
+ {
+ botimport.Print(PRT_ERROR, "target_teleporter without target\n");
+ continue;
+ } //end if
+ } //end else
+ else if (!strcmp(classname, "trigger_teleport"))
+ {
+ AAS_ValueForBSPEpairKey(ent, "model", model, MAX_EPAIRKEY);
+//#ifdef REACH_DEBUG
+ botimport.Print(PRT_MESSAGE, "trigger_teleport model = \"%s\"\n", model);
+//#endif REACH_DEBUG
+ VectorClear(angles);
+ AAS_BSPModelMinsMaxsOrigin(atoi(model+1), angles, mins, maxs, origin);
+ //
+ if (!AAS_ValueForBSPEpairKey(ent, "target", target, MAX_EPAIRKEY))
+ {
+ botimport.Print(PRT_ERROR, "trigger_teleport at %1.0f %1.0f %1.0f without target\n",
+ origin[0], origin[1], origin[2]);
+ continue;
+ } //end if
+ } //end if
+ else
+ {
+ continue;
+ } //end else
+ //
+ for (dest = AAS_NextBSPEntity(0); dest; dest = AAS_NextBSPEntity(dest))
+ {
+ //classname should be misc_teleporter_dest
+ //but I've also seen target_position and actually any
+ //entity could be used... burp
+ if (AAS_ValueForBSPEpairKey(dest, "targetname", targetname, MAX_EPAIRKEY))
+ {
+ if (!strcmp(targetname, target))
+ {
+ break;
+ } //end if
+ } //end if
+ } //end for
+ if (!dest)
+ {
+ botimport.Print(PRT_ERROR, "teleporter without misc_teleporter_dest (%s)\n", target);
+ continue;
+ } //end if
+ if (!AAS_VectorForBSPEpairKey(dest, "origin", destorigin))
+ {
+ botimport.Print(PRT_ERROR, "teleporter destination (%s) without origin\n", target);
+ continue;
+ } //end if
+ //
+ area2num = AAS_PointAreaNum(destorigin);
+ //if not teleported into a teleporter or into a jumppad
+ if (!AAS_AreaTeleporter(area2num) && !AAS_AreaJumpPad(area2num))
+ {
+ VectorCopy(destorigin, end);
+ end[2] -= 64;
+ trace = AAS_TraceClientBBox(destorigin, end, PRESENCE_CROUCH, -1);
+ if (trace.startsolid)
+ {
+ botimport.Print(PRT_ERROR, "teleporter destination (%s) in solid\n", target);
+ continue;
+ } //end if
+ area2num = AAS_PointAreaNum(trace.endpos);
+ //
+ /*
+ if (!AAS_AreaTeleporter(area2num) &&
+ !AAS_AreaJumpPad(area2num) &&
+ !AAS_AreaGrounded(area2num))
+ {
+ VectorCopy(trace.endpos, destorigin);
+ }
+ else*/
+ {
+ //predict where you'll end up
+ AAS_FloatForBSPEpairKey(dest, "angle", &angle);
+ if (angle)
+ {
+ VectorSet(angles, 0, angle, 0);
+ AngleVectors(angles, velocity, NULL, NULL);
+ VectorScale(velocity, 400, velocity);
+ } //end if
+ else
+ {
+ VectorClear(velocity);
+ } //end else
+ VectorClear(cmdmove);
+ AAS_PredictClientMovement(&move, -1, destorigin, PRESENCE_NORMAL, qfalse,
+ velocity, cmdmove, 0, 30, 0.1f,
+ SE_HITGROUND|SE_ENTERWATER|SE_ENTERSLIME|
+ SE_ENTERLAVA|SE_HITGROUNDDAMAGE|SE_TOUCHJUMPPAD|SE_TOUCHTELEPORTER, 0, qfalse); //qtrue);
+ area2num = AAS_PointAreaNum(move.endpos);
+ if (move.stopevent & (SE_ENTERSLIME|SE_ENTERLAVA))
+ {
+ botimport.Print(PRT_WARNING, "teleported into slime or lava at dest %s\n", target);
+ } //end if
+ VectorCopy(move.endpos, destorigin);
+ } //end else
+ } //end if
+ //
+ //botimport.Print(PRT_MESSAGE, "teleporter brush origin at %f %f %f\n", origin[0], origin[1], origin[2]);
+ //botimport.Print(PRT_MESSAGE, "teleporter brush mins = %f %f %f\n", mins[0], mins[1], mins[2]);
+ //botimport.Print(PRT_MESSAGE, "teleporter brush maxs = %f %f %f\n", maxs[0], maxs[1], maxs[2]);
+ VectorAdd(origin, mins, mins);
+ VectorAdd(origin, maxs, maxs);
+ //
+ VectorAdd(mins, maxs, mid);
+ VectorScale(mid, 0.5, mid);
+ //link an invalid (-1) entity
+ areas = AAS_LinkEntityClientBBox(mins, maxs, -1, PRESENCE_CROUCH);
+ if (!areas) botimport.Print(PRT_MESSAGE, "trigger_multiple not in any area\n");
+ //
+ for (link = areas; link; link = link->next_area)
+ {
+ //if (!AAS_AreaGrounded(link->areanum)) continue;
+ if (!AAS_AreaTeleporter(link->areanum)) continue;
+ //
+ area1num = link->areanum;
+ //create a new reachability link
+ lreach = AAS_AllocReachability();
+ if (!lreach) break;
+ lreach->areanum = area2num;
+ lreach->facenum = 0;
+ lreach->edgenum = 0;
+ VectorCopy(mid, lreach->start);
+ VectorCopy(destorigin, lreach->end);
+ lreach->traveltype = TRAVEL_TELEPORT;
+ lreach->traveltype |= AAS_TravelFlagsForTeam(ent);
+ lreach->traveltime = aassettings.rs_teleport;
+ lreach->next = areareachability[area1num];
+ areareachability[area1num] = lreach;
+ //
+ reach_teleport++;
+ } //end for
+ //unlink the invalid entity
+ AAS_UnlinkFromAreas(areas);
+ } //end for
+} //end of the function AAS_Reachability_Teleport
+//===========================================================================
+// create possible elevator (func_plat) reachabilities
+// this is very game dependent.... :(
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_Reachability_Elevator(void)
+{
+ int area1num, area2num, modelnum, i, j, k, l, n, p;
+ float lip, height, speed;
+ char model[MAX_EPAIRKEY], classname[MAX_EPAIRKEY];
+ int ent;
+ vec3_t mins, maxs, origin, angles = {0, 0, 0};
+ vec3_t pos1, pos2, mids, platbottom, plattop;
+ vec3_t bottomorg, toporg, start, end, dir;
+ vec_t xvals[8], yvals[8], xvals_top[8], yvals_top[8];
+ aas_lreachability_t *lreach;
+ aas_trace_t trace;
+
+#ifdef REACH_DEBUG
+ Log_Write("AAS_Reachability_Elevator\r\n");
+#endif //REACH_DEBUG
+ for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent))
+ {
+ if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) continue;
+ if (!strcmp(classname, "func_plat"))
+ {
+#ifdef REACH_DEBUG
+ Log_Write("found func plat\r\n");
+#endif //REACH_DEBUG
+ if (!AAS_ValueForBSPEpairKey(ent, "model", model, MAX_EPAIRKEY))
+ {
+ botimport.Print(PRT_ERROR, "func_plat without model\n");
+ continue;
+ } //end if
+ //get the model number, and skip the leading *
+ modelnum = atoi(model+1);
+ if (modelnum <= 0)
+ {
+ botimport.Print(PRT_ERROR, "func_plat with invalid model number\n");
+ continue;
+ } //end if
+ //get the mins, maxs and origin of the model
+ //NOTE: the origin is usually (0,0,0) and the mins and maxs
+ // are the absolute mins and maxs
+ AAS_BSPModelMinsMaxsOrigin(modelnum, angles, mins, maxs, origin);
+ //
+ AAS_VectorForBSPEpairKey(ent, "origin", origin);
+ //pos1 is the top position, pos2 is the bottom
+ VectorCopy(origin, pos1);
+ VectorCopy(origin, pos2);
+ //get the lip of the plat
+ AAS_FloatForBSPEpairKey(ent, "lip", &lip);
+ if (!lip) lip = 8;
+ //get the movement height of the plat
+ AAS_FloatForBSPEpairKey(ent, "height", &height);
+ if (!height) height = (maxs[2] - mins[2]) - lip;
+ //get the speed of the plat
+ AAS_FloatForBSPEpairKey(ent, "speed", &speed);
+ if (!speed) speed = 200;
+ //get bottom position below pos1
+ pos2[2] -= height;
+ //
+ //get a point just above the plat in the bottom position
+ VectorAdd(mins, maxs, mids);
+ VectorMA(pos2, 0.5, mids, platbottom);
+ platbottom[2] = maxs[2] - (pos1[2] - pos2[2]) + 2;
+ //get a point just above the plat in the top position
+ VectorAdd(mins, maxs, mids);
+ VectorMA(pos2, 0.5, mids, plattop);
+ plattop[2] = maxs[2] + 2;
+ //
+ /*if (!area1num)
+ {
+ Log_Write("no grounded area near plat bottom\r\n");
+ continue;
+ } //end if*/
+ //get the mins and maxs a little larger
+ for (i = 0; i < 3; i++)
+ {
+ mins[i] -= 1;
+ maxs[i] += 1;
+ } //end for
+ //
+ //botimport.Print(PRT_MESSAGE, "platbottom[2] = %1.1f plattop[2] = %1.1f\n", platbottom[2], plattop[2]);
+ //
+ VectorAdd(mins, maxs, mids);
+ VectorScale(mids, 0.5, mids);
+ //
+ xvals[0] = mins[0]; xvals[1] = mids[0]; xvals[2] = maxs[0]; xvals[3] = mids[0];
+ yvals[0] = mids[1]; yvals[1] = maxs[1]; yvals[2] = mids[1]; yvals[3] = mins[1];
+ //
+ xvals[4] = mins[0]; xvals[5] = maxs[0]; xvals[6] = maxs[0]; xvals[7] = mins[0];
+ yvals[4] = maxs[1]; yvals[5] = maxs[1]; yvals[6] = mins[1]; yvals[7] = mins[1];
+ //find adjacent areas around the bottom of the plat
+ for (i = 0; i < 9; i++)
+ {
+ if (i < 8) //check at the sides of the plat
+ {
+ bottomorg[0] = origin[0] + xvals[i];
+ bottomorg[1] = origin[1] + yvals[i];
+ bottomorg[2] = platbottom[2] + 16;
+ //get a grounded or swim area near the plat in the bottom position
+ area1num = AAS_PointAreaNum(bottomorg);
+ for (k = 0; k < 16; k++)
+ {
+ if (area1num)
+ {
+ if (AAS_AreaGrounded(area1num) || AAS_AreaSwim(area1num)) break;
+ } //end if
+ bottomorg[2] += 4;
+ area1num = AAS_PointAreaNum(bottomorg);
+ } //end if
+ //if in solid
+ if (k >= 16)
+ {
+ continue;
+ } //end if
+ } //end if
+ else //at the middle of the plat
+ {
+ VectorCopy(plattop, bottomorg);
+ bottomorg[2] += 24;
+ area1num = AAS_PointAreaNum(bottomorg);
+ if (!area1num) continue;
+ VectorCopy(platbottom, bottomorg);
+ bottomorg[2] += 24;
+ } //end else
+ //look at adjacent areas around the top of the plat
+ //make larger steps to outside the plat everytime
+ for (n = 0; n < 3; n++)
+ {
+ for (k = 0; k < 3; k++)
+ {
+ mins[k] -= 4;
+ maxs[k] += 4;
+ } //end for
+ xvals_top[0] = mins[0]; xvals_top[1] = mids[0]; xvals_top[2] = maxs[0]; xvals_top[3] = mids[0];
+ yvals_top[0] = mids[1]; yvals_top[1] = maxs[1]; yvals_top[2] = mids[1]; yvals_top[3] = mins[1];
+ //
+ xvals_top[4] = mins[0]; xvals_top[5] = maxs[0]; xvals_top[6] = maxs[0]; xvals_top[7] = mins[0];
+ yvals_top[4] = maxs[1]; yvals_top[5] = maxs[1]; yvals_top[6] = mins[1]; yvals_top[7] = mins[1];
+ //
+ for (j = 0; j < 8; j++)
+ {
+ toporg[0] = origin[0] + xvals_top[j];
+ toporg[1] = origin[1] + yvals_top[j];
+ toporg[2] = plattop[2] + 16;
+ //get a grounded or swim area near the plat in the top position
+ area2num = AAS_PointAreaNum(toporg);
+ for (l = 0; l < 16; l++)
+ {
+ if (area2num)
+ {
+ if (AAS_AreaGrounded(area2num) || AAS_AreaSwim(area2num))
+ {
+ VectorCopy(plattop, start);
+ start[2] += 32;
+ VectorCopy(toporg, end);
+ end[2] += 1;
+ trace = AAS_TraceClientBBox(start, end, PRESENCE_CROUCH, -1);
+ if (trace.fraction >= 1) break;
+ } //end if
+ } //end if
+ toporg[2] += 4;
+ area2num = AAS_PointAreaNum(toporg);
+ } //end if
+ //if in solid
+ if (l >= 16) continue;
+ //never create a reachability in the same area
+ if (area2num == area1num) continue;
+ //if the area isn't grounded
+ if (!AAS_AreaGrounded(area2num)) continue;
+ //if there already exists reachability between the areas
+ if (AAS_ReachabilityExists(area1num, area2num)) continue;
+ //if the reachability start is within the elevator bounding box
+ VectorSubtract(bottomorg, platbottom, dir);
+ VectorNormalize(dir);
+ dir[0] = bottomorg[0] + 24 * dir[0];
+ dir[1] = bottomorg[1] + 24 * dir[1];
+ dir[2] = bottomorg[2];
+ //
+ for (p = 0; p < 3; p++)
+ if (dir[p] < origin[p] + mins[p] || dir[p] > origin[p] + maxs[p]) break;
+ if (p >= 3) continue;
+ //create a new reachability link
+ lreach = AAS_AllocReachability();
+ if (!lreach) continue;
+ lreach->areanum = area2num;
+ //the facenum is the model number
+ lreach->facenum = modelnum;
+ //the edgenum is the height
+ lreach->edgenum = (int) height;
+ //
+ VectorCopy(dir, lreach->start);
+ VectorCopy(toporg, lreach->end);
+ lreach->traveltype = TRAVEL_ELEVATOR;
+ lreach->traveltype |= AAS_TravelFlagsForTeam(ent);
+ lreach->traveltime = aassettings.rs_startelevator + height * 100 / speed;
+ lreach->next = areareachability[area1num];
+ areareachability[area1num] = lreach;
+ //don't go any further to the outside
+ n = 9999;
+ //
+#ifdef REACH_DEBUG
+ Log_Write("elevator reach from %d to %d\r\n", area1num, area2num);
+#endif //REACH_DEBUG
+ //
+ reach_elevator++;
+ } //end for
+ } //end for
+ } //end for
+ } //end if
+ } //end for
+} //end of the function AAS_Reachability_Elevator
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+aas_lreachability_t *AAS_FindFaceReachabilities(vec3_t *facepoints, int numpoints, aas_plane_t *plane, int towardsface)
+{
+ int i, j, k, l;
+ int facenum, edgenum, bestfacenum;
+ float *v1, *v2, *v3, *v4;
+ float bestdist, speed, hordist, dist;
+ vec3_t beststart, beststart2, bestend, bestend2, tmp, hordir, testpoint;
+ aas_lreachability_t *lreach, *lreachabilities;
+ aas_area_t *area;
+ aas_face_t *face;
+ aas_edge_t *edge;
+ aas_plane_t *faceplane, *bestfaceplane;
+
+ //
+ lreachabilities = NULL;
+ bestfacenum = 0;
+ bestfaceplane = NULL;
+ //
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ area = &aasworld.areas[i];
+ // get the shortest distance between one of the func_bob start edges and
+ // one of the face edges of area1
+ bestdist = 999999;
+ for (j = 0; j < area->numfaces; j++)
+ {
+ facenum = aasworld.faceindex[area->firstface + j];
+ face = &aasworld.faces[abs(facenum)];
+ //if not a ground face
+ if (!(face->faceflags & FACE_GROUND)) continue;
+ //get the ground planes
+ faceplane = &aasworld.planes[face->planenum];
+ //
+ for (k = 0; k < face->numedges; k++)
+ {
+ edgenum = abs(aasworld.edgeindex[face->firstedge + k]);
+ edge = &aasworld.edges[edgenum];
+ //calculate the minimum distance between the two edges
+ v1 = aasworld.vertexes[edge->v[0]];
+ v2 = aasworld.vertexes[edge->v[1]];
+ //
+ for (l = 0; l < numpoints; l++)
+ {
+ v3 = facepoints[l];
+ v4 = facepoints[(l+1) % numpoints];
+ dist = AAS_ClosestEdgePoints(v1, v2, v3, v4, faceplane, plane,
+ beststart, bestend,
+ beststart2, bestend2, bestdist);
+ if (dist < bestdist)
+ {
+ bestfacenum = facenum;
+ bestfaceplane = faceplane;
+ bestdist = dist;
+ } //end if
+ } //end for
+ } //end for
+ } //end for
+ //
+ if (bestdist > 192) continue;
+ //
+ VectorMiddle(beststart, beststart2, beststart);
+ VectorMiddle(bestend, bestend2, bestend);
+ //
+ if (!towardsface)
+ {
+ VectorCopy(beststart, tmp);
+ VectorCopy(bestend, beststart);
+ VectorCopy(tmp, bestend);
+ } //end if
+ //
+ VectorSubtract(bestend, beststart, hordir);
+ hordir[2] = 0;
+ hordist = VectorLength(hordir);
+ //
+ if (hordist > 2 * AAS_MaxJumpDistance(aassettings.phys_jumpvel)) continue;
+ //the end point should not be significantly higher than the start point
+ if (bestend[2] - 32 > beststart[2]) continue;
+ //don't fall down too far
+ if (bestend[2] < beststart[2] - 128) continue;
+ //the distance should not be too far
+ if (hordist > 32)
+ {
+ //check for walk off ledge
+ if (!AAS_HorizontalVelocityForJump(0, beststart, bestend, &speed)) continue;
+ } //end if
+ //
+ beststart[2] += 1;
+ bestend[2] += 1;
+ //
+ if (towardsface) VectorCopy(bestend, testpoint);
+ else VectorCopy(beststart, testpoint);
+ testpoint[2] = 0;
+ testpoint[2] = (bestfaceplane->dist - DotProduct(bestfaceplane->normal, testpoint)) / bestfaceplane->normal[2];
+ //
+ if (!AAS_PointInsideFace(bestfacenum, testpoint, 0.1f))
+ {
+ //if the faces are not overlapping then only go down
+ if (bestend[2] - 16 > beststart[2]) continue;
+ } //end if
+ lreach = AAS_AllocReachability();
+ if (!lreach) return lreachabilities;
+ lreach->areanum = i;
+ lreach->facenum = 0;
+ lreach->edgenum = 0;
+ VectorCopy(beststart, lreach->start);
+ VectorCopy(bestend, lreach->end);
+ lreach->traveltype = 0;
+ lreach->traveltime = 0;
+ lreach->next = lreachabilities;
+ lreachabilities = lreach;
+#ifndef BSPC
+ if (towardsface) AAS_PermanentLine(lreach->start, lreach->end, 1);
+ else AAS_PermanentLine(lreach->start, lreach->end, 2);
+#endif
+ } //end for
+ return lreachabilities;
+} //end of the function AAS_FindFaceReachabilities
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_Reachability_FuncBobbing(void)
+{
+ int ent, spawnflags, modelnum, axis;
+ int i, numareas, areas[10];
+ char classname[MAX_EPAIRKEY], model[MAX_EPAIRKEY];
+ vec3_t origin, move_end, move_start, move_start_top, move_end_top;
+ vec3_t mins, maxs, angles = {0, 0, 0};
+ vec3_t start_edgeverts[4], end_edgeverts[4], mid;
+ vec3_t org, start, end, dir, points[10];
+ float height;
+ aas_plane_t start_plane, end_plane;
+ aas_lreachability_t *startreach, *endreach, *nextstartreach, *nextendreach, *lreach;
+ aas_lreachability_t *firststartreach, *firstendreach;
+
+ for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent))
+ {
+ if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) continue;
+ if (strcmp(classname, "func_bobbing")) continue;
+ AAS_FloatForBSPEpairKey(ent, "height", &height);
+ if (!height) height = 32;
+ //
+ if (!AAS_ValueForBSPEpairKey(ent, "model", model, MAX_EPAIRKEY))
+ {
+ botimport.Print(PRT_ERROR, "func_bobbing without model\n");
+ continue;
+ } //end if
+ //get the model number, and skip the leading *
+ modelnum = atoi(model+1);
+ if (modelnum <= 0)
+ {
+ botimport.Print(PRT_ERROR, "func_bobbing with invalid model number\n");
+ continue;
+ } //end if
+ //if the entity has an origin set then use it
+ if (!AAS_VectorForBSPEpairKey(ent, "origin", origin))
+ VectorSet(origin, 0, 0, 0);
+ //
+ AAS_BSPModelMinsMaxsOrigin(modelnum, angles, mins, maxs, NULL);
+ //
+ VectorAdd(mins, origin, mins);
+ VectorAdd(maxs, origin, maxs);
+ //
+ VectorAdd(mins, maxs, mid);
+ VectorScale(mid, 0.5, mid);
+ VectorCopy(mid, origin);
+ //
+ VectorCopy(origin, move_end);
+ VectorCopy(origin, move_start);
+ //
+ AAS_IntForBSPEpairKey(ent, "spawnflags", &spawnflags);
+ // set the axis of bobbing
+ if (spawnflags & 1) axis = 0;
+ else if (spawnflags & 2) axis = 1;
+ else axis = 2;
+ //
+ move_start[axis] -= height;
+ move_end[axis] += height;
+ //
+ Log_Write("funcbob model %d, start = {%1.1f, %1.1f, %1.1f} end = {%1.1f, %1.1f, %1.1f}\n",
+ modelnum, move_start[0], move_start[1], move_start[2], move_end[0], move_end[1], move_end[2]);
+ //
+#ifndef BSPC
+ /*
+ AAS_DrawPermanentCross(move_start, 4, 1);
+ AAS_DrawPermanentCross(move_end, 4, 2);
+ */
+#endif
+ //
+ for (i = 0; i < 4; i++)
+ {
+ VectorCopy(move_start, start_edgeverts[i]);
+ start_edgeverts[i][2] += maxs[2] - mid[2]; //+ bbox maxs z
+ start_edgeverts[i][2] += 24; //+ player origin to ground dist
+ } //end for
+ start_edgeverts[0][0] += maxs[0] - mid[0];
+ start_edgeverts[0][1] += maxs[1] - mid[1];
+ start_edgeverts[1][0] += maxs[0] - mid[0];
+ start_edgeverts[1][1] += mins[1] - mid[1];
+ start_edgeverts[2][0] += mins[0] - mid[0];
+ start_edgeverts[2][1] += mins[1] - mid[1];
+ start_edgeverts[3][0] += mins[0] - mid[0];
+ start_edgeverts[3][1] += maxs[1] - mid[1];
+ //
+ start_plane.dist = start_edgeverts[0][2];
+ VectorSet(start_plane.normal, 0, 0, 1);
+ //
+ for (i = 0; i < 4; i++)
+ {
+ VectorCopy(move_end, end_edgeverts[i]);
+ end_edgeverts[i][2] += maxs[2] - mid[2]; //+ bbox maxs z
+ end_edgeverts[i][2] += 24; //+ player origin to ground dist
+ } //end for
+ end_edgeverts[0][0] += maxs[0] - mid[0];
+ end_edgeverts[0][1] += maxs[1] - mid[1];
+ end_edgeverts[1][0] += maxs[0] - mid[0];
+ end_edgeverts[1][1] += mins[1] - mid[1];
+ end_edgeverts[2][0] += mins[0] - mid[0];
+ end_edgeverts[2][1] += mins[1] - mid[1];
+ end_edgeverts[3][0] += mins[0] - mid[0];
+ end_edgeverts[3][1] += maxs[1] - mid[1];
+ //
+ end_plane.dist = end_edgeverts[0][2];
+ VectorSet(end_plane.normal, 0, 0, 1);
+ //
+#ifndef BSPC
+#if 0
+ for (i = 0; i < 4; i++)
+ {
+ AAS_PermanentLine(start_edgeverts[i], start_edgeverts[(i+1)%4], 1);
+ AAS_PermanentLine(end_edgeverts[i], end_edgeverts[(i+1)%4], 1);
+ } //end for
+#endif
+#endif
+ VectorCopy(move_start, move_start_top);
+ move_start_top[2] += maxs[2] - mid[2] + 24; //+ bbox maxs z
+ VectorCopy(move_end, move_end_top);
+ move_end_top[2] += maxs[2] - mid[2] + 24; //+ bbox maxs z
+ //
+ if (!AAS_PointAreaNum(move_start_top)) continue;
+ if (!AAS_PointAreaNum(move_end_top)) continue;
+ //
+ for (i = 0; i < 2; i++)
+ {
+ firststartreach = firstendreach = NULL;
+ //
+ if (i == 0)
+ {
+ firststartreach = AAS_FindFaceReachabilities(start_edgeverts, 4, &start_plane, qtrue);
+ firstendreach = AAS_FindFaceReachabilities(end_edgeverts, 4, &end_plane, qfalse);
+ } //end if
+ else
+ {
+ firststartreach = AAS_FindFaceReachabilities(end_edgeverts, 4, &end_plane, qtrue);
+ firstendreach = AAS_FindFaceReachabilities(start_edgeverts, 4, &start_plane, qfalse);
+ } //end else
+ //
+ //create reachabilities from start to end
+ for (startreach = firststartreach; startreach; startreach = nextstartreach)
+ {
+ nextstartreach = startreach->next;
+ //
+ //trace = AAS_TraceClientBBox(startreach->start, move_start_top, PRESENCE_NORMAL, -1);
+ //if (trace.fraction < 1) continue;
+ //
+ for (endreach = firstendreach; endreach; endreach = nextendreach)
+ {
+ nextendreach = endreach->next;
+ //
+ //trace = AAS_TraceClientBBox(endreach->end, move_end_top, PRESENCE_NORMAL, -1);
+ //if (trace.fraction < 1) continue;
+ //
+ Log_Write("funcbob reach from area %d to %d\n", startreach->areanum, endreach->areanum);
+ //
+ //
+ if (i == 0) VectorCopy(move_start_top, org);
+ else VectorCopy(move_end_top, org);
+ VectorSubtract(startreach->start, org, dir);
+ dir[2] = 0;
+ VectorNormalize(dir);
+ VectorCopy(startreach->start, start);
+ VectorMA(startreach->start, 1, dir, start);
+ start[2] += 1;
+ VectorMA(startreach->start, 16, dir, end);
+ end[2] += 1;
+ //
+ numareas = AAS_TraceAreas(start, end, areas, points, 10);
+ if (numareas <= 0) continue;
+ if (numareas > 1) VectorCopy(points[1], startreach->start);
+ else VectorCopy(end, startreach->start);
+ //
+ if (!AAS_PointAreaNum(startreach->start)) continue;
+ if (!AAS_PointAreaNum(endreach->end)) continue;
+ //
+ lreach = AAS_AllocReachability();
+ lreach->areanum = endreach->areanum;
+ if (i == 0) lreach->edgenum = ((int)move_start[axis] << 16) | ((int) move_end[axis] & 0x0000ffff);
+ else lreach->edgenum = ((int)move_end[axis] << 16) | ((int) move_start[axis] & 0x0000ffff);
+ lreach->facenum = (spawnflags << 16) | modelnum;
+ VectorCopy(startreach->start, lreach->start);
+ VectorCopy(endreach->end, lreach->end);
+#ifndef BSPC
+// AAS_DrawArrow(lreach->start, lreach->end, LINECOLOR_BLUE, LINECOLOR_YELLOW);
+// AAS_PermanentLine(lreach->start, lreach->end, 1);
+#endif
+ lreach->traveltype = TRAVEL_FUNCBOB;
+ lreach->traveltype |= AAS_TravelFlagsForTeam(ent);
+ lreach->traveltime = aassettings.rs_funcbob;
+ reach_funcbob++;
+ lreach->next = areareachability[startreach->areanum];
+ areareachability[startreach->areanum] = lreach;
+ //
+ } //end for
+ } //end for
+ for (startreach = firststartreach; startreach; startreach = nextstartreach)
+ {
+ nextstartreach = startreach->next;
+ AAS_FreeReachability(startreach);
+ } //end for
+ for (endreach = firstendreach; endreach; endreach = nextendreach)
+ {
+ nextendreach = endreach->next;
+ AAS_FreeReachability(endreach);
+ } //end for
+ //only go up with func_bobbing entities that go up and down
+ if (!(spawnflags & 1) && !(spawnflags & 2)) break;
+ } //end for
+ } //end for
+} //end of the function AAS_Reachability_FuncBobbing
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_Reachability_JumpPad(void)
+{
+ int face2num, i, ret, area2num, visualize, ent, bot_visualizejumppads;
+ //int modelnum, ent2;
+ //float dist, time, height, gravity, forward;
+ float speed, zvel, hordist;
+ aas_face_t *face2;
+ aas_area_t *area2;
+ aas_lreachability_t *lreach;
+ vec3_t areastart, facecenter, dir, cmdmove;
+ vec3_t velocity, absmins, absmaxs;
+ //vec3_t origin, ent2origin, angles, teststart;
+ aas_clientmove_t move;
+ //aas_trace_t trace;
+ aas_link_t *areas, *link;
+ //char target[MAX_EPAIRKEY], targetname[MAX_EPAIRKEY], model[MAX_EPAIRKEY];
+ char classname[MAX_EPAIRKEY];
+
+#ifdef BSPC
+ bot_visualizejumppads = 0;
+#else
+ bot_visualizejumppads = LibVarValue("bot_visualizejumppads", "0");
+#endif
+ for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent))
+ {
+ if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) continue;
+ if (strcmp(classname, "trigger_push")) continue;
+ //
+ if (!AAS_GetJumpPadInfo(ent, areastart, absmins, absmaxs, velocity)) continue;
+ /*
+ //
+ AAS_FloatForBSPEpairKey(ent, "speed", &speed);
+ if (!speed) speed = 1000;
+// AAS_VectorForBSPEpairKey(ent, "angles", angles);
+// AAS_SetMovedir(angles, velocity);
+// VectorScale(velocity, speed, velocity);
+ VectorClear(angles);
+ //get the mins, maxs and origin of the model
+ AAS_ValueForBSPEpairKey(ent, "model", model, MAX_EPAIRKEY);
+ if (model[0]) modelnum = atoi(model+1);
+ else modelnum = 0;
+ AAS_BSPModelMinsMaxsOrigin(modelnum, angles, absmins, absmaxs, origin);
+ VectorAdd(origin, absmins, absmins);
+ VectorAdd(origin, absmaxs, absmaxs);
+ //
+#ifdef REACH_DEBUG
+ botimport.Print(PRT_MESSAGE, "absmins = %f %f %f\n", absmins[0], absmins[1], absmins[2]);
+ botimport.Print(PRT_MESSAGE, "absmaxs = %f %f %f\n", absmaxs[0], absmaxs[1], absmaxs[2]);
+#endif REACH_DEBUG
+ VectorAdd(absmins, absmaxs, origin);
+ VectorScale (origin, 0.5, origin);
+
+ //get the start areas
+ VectorCopy(origin, teststart);
+ teststart[2] += 64;
+ trace = AAS_TraceClientBBox(teststart, origin, PRESENCE_CROUCH, -1);
+ if (trace.startsolid)
+ {
+ botimport.Print(PRT_MESSAGE, "trigger_push start solid\n");
+ VectorCopy(origin, areastart);
+ } //end if
+ else
+ {
+ VectorCopy(trace.endpos, areastart);
+ } //end else
+ areastart[2] += 0.125;
+ //
+ //AAS_DrawPermanentCross(origin, 4, 4);
+ //get the target entity
+ AAS_ValueForBSPEpairKey(ent, "target", target, MAX_EPAIRKEY);
+ for (ent2 = AAS_NextBSPEntity(0); ent2; ent2 = AAS_NextBSPEntity(ent2))
+ {
+ if (!AAS_ValueForBSPEpairKey(ent2, "targetname", targetname, MAX_EPAIRKEY)) continue;
+ if (!strcmp(targetname, target)) break;
+ } //end for
+ if (!ent2)
+ {
+ botimport.Print(PRT_MESSAGE, "trigger_push without target entity %s\n", target);
+ continue;
+ } //end if
+ AAS_VectorForBSPEpairKey(ent2, "origin", ent2origin);
+ //
+ height = ent2origin[2] - origin[2];
+ gravity = aassettings.sv_gravity;
+ time = sqrt( height / ( 0.5 * gravity ) );
+ if (!time)
+ {
+ botimport.Print(PRT_MESSAGE, "trigger_push without time\n");
+ continue;
+ } //end if
+ // set s.origin2 to the push velocity
+ VectorSubtract ( ent2origin, origin, velocity);
+ dist = VectorNormalize( velocity);
+ forward = dist / time;
+ //FIXME: why multiply by 1.1
+ forward *= 1.1;
+ VectorScale(velocity, forward, velocity);
+ velocity[2] = time * gravity;
+ */
+ //get the areas the jump pad brush is in
+ areas = AAS_LinkEntityClientBBox(absmins, absmaxs, -1, PRESENCE_CROUCH);
+ /*
+ for (link = areas; link; link = link->next_area)
+ {
+ if (link->areanum == 563)
+ {
+ ret = qfalse;
+ }
+ }
+ */
+ for (link = areas; link; link = link->next_area)
+ {
+ if (AAS_AreaJumpPad(link->areanum)) break;
+ } //end for
+ if (!link)
+ {
+ botimport.Print(PRT_MESSAGE, "trigger_push not in any jump pad area\n");
+ AAS_UnlinkFromAreas(areas);
+ continue;
+ } //end if
+ //
+ botimport.Print(PRT_MESSAGE, "found a trigger_push with velocity %f %f %f\n", velocity[0], velocity[1], velocity[2]);
+ //if there is a horizontal velocity check for a reachability without air control
+ if (velocity[0] || velocity[1])
+ {
+ VectorSet(cmdmove, 0, 0, 0);
+ //VectorCopy(velocity, cmdmove);
+ //cmdmove[2] = 0;
+ Com_Memset(&move, 0, sizeof(aas_clientmove_t));
+ area2num = 0;
+ for (i = 0; i < 20; i++)
+ {
+ AAS_PredictClientMovement(&move, -1, areastart, PRESENCE_NORMAL, qfalse,
+ velocity, cmdmove, 0, 30, 0.1f,
+ SE_HITGROUND|SE_ENTERWATER|SE_ENTERSLIME|
+ SE_ENTERLAVA|SE_HITGROUNDDAMAGE|SE_TOUCHJUMPPAD|SE_TOUCHTELEPORTER, 0, bot_visualizejumppads);
+ area2num = move.endarea;
+ for (link = areas; link; link = link->next_area)
+ {
+ if (!AAS_AreaJumpPad(link->areanum)) continue;
+ if (link->areanum == area2num) break;
+ } //end if
+ if (!link) break;
+ VectorCopy(move.endpos, areastart);
+ VectorCopy(move.velocity, velocity);
+ } //end for
+ if (area2num && i < 20)
+ {
+ for (link = areas; link; link = link->next_area)
+ {
+ if (!AAS_AreaJumpPad(link->areanum)) continue;
+ if (AAS_ReachabilityExists(link->areanum, area2num)) continue;
+ //create a rocket or bfg jump reachability from area1 to area2
+ lreach = AAS_AllocReachability();
+ if (!lreach)
+ {
+ AAS_UnlinkFromAreas(areas);
+ return;
+ } //end if
+ lreach->areanum = area2num;
+ //NOTE: the facenum is the Z velocity
+ lreach->facenum = velocity[2];
+ //NOTE: the edgenum is the horizontal velocity
+ lreach->edgenum = sqrt(velocity[0] * velocity[0] + velocity[1] * velocity[1]);
+ VectorCopy(areastart, lreach->start);
+ VectorCopy(move.endpos, lreach->end);
+ lreach->traveltype = TRAVEL_JUMPPAD;
+ lreach->traveltype |= AAS_TravelFlagsForTeam(ent);
+ lreach->traveltime = aassettings.rs_jumppad;
+ lreach->next = areareachability[link->areanum];
+ areareachability[link->areanum] = lreach;
+ //
+ reach_jumppad++;
+ } //end for
+ } //end if
+ } //end if
+ //
+ if (fabs(velocity[0]) > 100 || fabs(velocity[1]) > 100) continue;
+ //check for areas we can reach with air control
+ for (area2num = 1; area2num < aasworld.numareas; area2num++)
+ {
+ visualize = qfalse;
+ /*
+ if (area2num == 3568)
+ {
+ for (link = areas; link; link = link->next_area)
+ {
+ if (link->areanum == 3380)
+ {
+ visualize = qtrue;
+ botimport.Print(PRT_MESSAGE, "bah\n");
+ } //end if
+ } //end for
+ } //end if*/
+ //never try to go back to one of the original jumppad areas
+ //and don't create reachabilities if they already exist
+ for (link = areas; link; link = link->next_area)
+ {
+ if (AAS_ReachabilityExists(link->areanum, area2num)) break;
+ if (AAS_AreaJumpPad(link->areanum))
+ {
+ if (link->areanum == area2num) break;
+ } //end if
+ } //end if
+ if (link) continue;
+ //
+ area2 = &aasworld.areas[area2num];
+ for (i = 0; i < area2->numfaces; i++)
+ {
+ face2num = aasworld.faceindex[area2->firstface + i];
+ face2 = &aasworld.faces[abs(face2num)];
+ //if it is not a ground face
+ if (!(face2->faceflags & FACE_GROUND)) continue;
+ //get the center of the face
+ AAS_FaceCenter(face2num, facecenter);
+ //only go higher up
+ if (facecenter[2] < areastart[2]) continue;
+ //get the jumppad jump z velocity
+ zvel = velocity[2];
+ //get the horizontal speed for the jump, if it isn't possible to calculate this
+ //speed
+ ret = AAS_HorizontalVelocityForJump(zvel, areastart, facecenter, &speed);
+ if (ret && speed < 150)
+ {
+ //direction towards the face center
+ VectorSubtract(facecenter, areastart, dir);
+ dir[2] = 0;
+ hordist = VectorNormalize(dir);
+ //if (hordist < 1.6 * facecenter[2] - areastart[2])
+ {
+ //get command movement
+ VectorScale(dir, speed, cmdmove);
+ //
+ AAS_PredictClientMovement(&move, -1, areastart, PRESENCE_NORMAL, qfalse,
+ velocity, cmdmove, 30, 30, 0.1f,
+ SE_ENTERWATER|SE_ENTERSLIME|
+ SE_ENTERLAVA|SE_HITGROUNDDAMAGE|
+ SE_TOUCHJUMPPAD|SE_TOUCHTELEPORTER|SE_HITGROUNDAREA, area2num, visualize);
+ //if prediction time wasn't enough to fully predict the movement
+ //don't enter slime or lava and don't fall from too high
+ if (move.frames < 30 &&
+ !(move.stopevent & (SE_ENTERSLIME|SE_ENTERLAVA|SE_HITGROUNDDAMAGE))
+ && (move.stopevent & (SE_HITGROUNDAREA|SE_TOUCHJUMPPAD|SE_TOUCHTELEPORTER)))
+ {
+ //never go back to the same jumppad
+ for (link = areas; link; link = link->next_area)
+ {
+ if (link->areanum == move.endarea) break;
+ }
+ if (!link)
+ {
+ for (link = areas; link; link = link->next_area)
+ {
+ if (!AAS_AreaJumpPad(link->areanum)) continue;
+ if (AAS_ReachabilityExists(link->areanum, area2num)) continue;
+ //create a jumppad reachability from area1 to area2
+ lreach = AAS_AllocReachability();
+ if (!lreach)
+ {
+ AAS_UnlinkFromAreas(areas);
+ return;
+ } //end if
+ lreach->areanum = move.endarea;
+ //NOTE: the facenum is the Z velocity
+ lreach->facenum = velocity[2];
+ //NOTE: the edgenum is the horizontal velocity
+ lreach->edgenum = sqrt(cmdmove[0] * cmdmove[0] + cmdmove[1] * cmdmove[1]);
+ VectorCopy(areastart, lreach->start);
+ VectorCopy(facecenter, lreach->end);
+ lreach->traveltype = TRAVEL_JUMPPAD;
+ lreach->traveltype |= AAS_TravelFlagsForTeam(ent);
+ lreach->traveltime = aassettings.rs_aircontrolledjumppad;
+ lreach->next = areareachability[link->areanum];
+ areareachability[link->areanum] = lreach;
+ //
+ reach_jumppad++;
+ } //end for
+ }
+ } //end if
+ } //end if
+ } //end for
+ } //end for
+ } //end for
+ AAS_UnlinkFromAreas(areas);
+ } //end for
+} //end of the function AAS_Reachability_JumpPad
+//===========================================================================
+// never point at ground faces
+// always a higher and pretty far area
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_Reachability_Grapple(int area1num, int area2num)
+{
+ int face2num, i, j, areanum, numareas, areas[20];
+ float mingrappleangle, z, hordist;
+ bsp_trace_t bsptrace;
+ aas_trace_t trace;
+ aas_face_t *face2;
+ aas_area_t *area1, *area2;
+ aas_lreachability_t *lreach;
+ vec3_t areastart, facecenter, start, end, dir, down = {0, 0, -1};
+ vec_t *v;
+
+ //only grapple when on the ground or swimming
+ if (!AAS_AreaGrounded(area1num) && !AAS_AreaSwim(area1num)) return qfalse;
+ //don't grapple from a crouch area
+ if (!(AAS_AreaPresenceType(area1num) & PRESENCE_NORMAL)) return qfalse;
+ //NOTE: disabled area swim it doesn't work right
+ if (AAS_AreaSwim(area1num)) return qfalse;
+ //
+ area1 = &aasworld.areas[area1num];
+ area2 = &aasworld.areas[area2num];
+ //don't grapple towards way lower areas
+ if (area2->maxs[2] < area1->mins[2]) return qfalse;
+ //
+ VectorCopy(aasworld.areas[area1num].center, start);
+ //if not a swim area
+ if (!AAS_AreaSwim(area1num))
+ {
+ if (!AAS_PointAreaNum(start)) Log_Write("area %d center %f %f %f in solid?\r\n", area1num,
+ start[0], start[1], start[2]);
+ VectorCopy(start, end);
+ end[2] -= 1000;
+ trace = AAS_TraceClientBBox(start, end, PRESENCE_CROUCH, -1);
+ if (trace.startsolid) return qfalse;
+ VectorCopy(trace.endpos, areastart);
+ } //end if
+ else
+ {
+ if (!(AAS_PointContents(start) & (CONTENTS_LAVA|CONTENTS_SLIME|CONTENTS_WATER))) return qfalse;
+ } //end else
+ //
+ //start is now the start point
+ //
+ for (i = 0; i < area2->numfaces; i++)
+ {
+ face2num = aasworld.faceindex[area2->firstface + i];
+ face2 = &aasworld.faces[abs(face2num)];
+ //if it is not a solid face
+ if (!(face2->faceflags & FACE_SOLID)) continue;
+ //direction towards the first vertex of the face
+ v = aasworld.vertexes[aasworld.edges[abs(aasworld.edgeindex[face2->firstedge])].v[0]];
+ VectorSubtract(v, areastart, dir);
+ //if the face plane is facing away
+ if (DotProduct(aasworld.planes[face2->planenum].normal, dir) > 0) continue;
+ //get the center of the face
+ AAS_FaceCenter(face2num, facecenter);
+ //only go higher up with the grapple
+ if (facecenter[2] < areastart[2] + 64) continue;
+ //only use vertical faces or downward facing faces
+ if (DotProduct(aasworld.planes[face2->planenum].normal, down) < 0) continue;
+ //direction towards the face center
+ VectorSubtract(facecenter, areastart, dir);
+ //
+ z = dir[2];
+ dir[2] = 0;
+ hordist = VectorLength(dir);
+ if (!hordist) continue;
+ //if too far
+ if (hordist > 2000) continue;
+ //check the minimal angle of the movement
+ mingrappleangle = 15; //15 degrees
+ if (z / hordist < tan(2 * M_PI * mingrappleangle / 360)) continue;
+ //
+ VectorCopy(facecenter, start);
+ VectorMA(facecenter, -500, aasworld.planes[face2->planenum].normal, end);
+ //
+ bsptrace = AAS_Trace(start, NULL, NULL, end, 0, CONTENTS_SOLID);
+ //the grapple won't stick to the sky and the grapple point should be near the AAS wall
+ if ((bsptrace.surface.flags & SURF_SKY) || (bsptrace.fraction * 500 > 32)) continue;
+ //trace a full bounding box from the area center on the ground to
+ //the center of the face
+ VectorSubtract(facecenter, areastart, dir);
+ VectorNormalize(dir);
+ VectorMA(areastart, 4, dir, start);
+ VectorCopy(bsptrace.endpos, end);
+ trace = AAS_TraceClientBBox(start, end, PRESENCE_NORMAL, -1);
+ VectorSubtract(trace.endpos, facecenter, dir);
+ if (VectorLength(dir) > 24) continue;
+ //
+ VectorCopy(trace.endpos, start);
+ VectorCopy(trace.endpos, end);
+ end[2] -= AAS_FallDamageDistance();
+ trace = AAS_TraceClientBBox(start, end, PRESENCE_NORMAL, -1);
+ if (trace.fraction >= 1) continue;
+ //area to end in
+ areanum = AAS_PointAreaNum(trace.endpos);
+ //if not in lava or slime
+ if (aasworld.areasettings[areanum].contents & (AREACONTENTS_SLIME|AREACONTENTS_LAVA))
+ {
+ continue;
+ } //end if
+ //do not go the the source area
+ if (areanum == area1num) continue;
+ //don't create reachabilities if they already exist
+ if (AAS_ReachabilityExists(area1num, areanum)) continue;
+ //only end in areas we can stand
+ if (!AAS_AreaGrounded(areanum)) continue;
+ //never go through cluster portals!!
+ numareas = AAS_TraceAreas(areastart, bsptrace.endpos, areas, NULL, 20);
+ if (numareas >= 20) continue;
+ for (j = 0; j < numareas; j++)
+ {
+ if (aasworld.areasettings[areas[j]].contents & AREACONTENTS_CLUSTERPORTAL) break;
+ } //end for
+ if (j < numareas) continue;
+ //create a new reachability link
+ lreach = AAS_AllocReachability();
+ if (!lreach) return qfalse;
+ lreach->areanum = areanum;
+ lreach->facenum = face2num;
+ lreach->edgenum = 0;
+ VectorCopy(areastart, lreach->start);
+ //VectorCopy(facecenter, lreach->end);
+ VectorCopy(bsptrace.endpos, lreach->end);
+ lreach->traveltype = TRAVEL_GRAPPLEHOOK;
+ VectorSubtract(lreach->end, lreach->start, dir);
+ lreach->traveltime = aassettings.rs_startgrapple + VectorLength(dir) * 0.25;
+ lreach->next = areareachability[area1num];
+ areareachability[area1num] = lreach;
+ //
+ reach_grapple++;
+ } //end for
+ //
+ return qfalse;
+} //end of the function AAS_Reachability_Grapple
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_SetWeaponJumpAreaFlags(void)
+{
+ int ent, i;
+ vec3_t mins = {-15, -15, -15}, maxs = {15, 15, 15};
+ vec3_t origin;
+ int areanum, weaponjumpareas, spawnflags;
+ char classname[MAX_EPAIRKEY];
+
+ weaponjumpareas = 0;
+ for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent))
+ {
+ if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) continue;
+ if (
+ !strcmp(classname, "item_armor_body") ||
+ !strcmp(classname, "item_armor_combat") ||
+ !strcmp(classname, "item_health_mega") ||
+ !strcmp(classname, "weapon_grenadelauncher") ||
+ !strcmp(classname, "weapon_rocketlauncher") ||
+ !strcmp(classname, "weapon_lightning") ||
+ !strcmp(classname, "weapon_plasmagun") ||
+ !strcmp(classname, "weapon_railgun") ||
+ !strcmp(classname, "weapon_bfg") ||
+ !strcmp(classname, "item_quad") ||
+ !strcmp(classname, "item_regen") ||
+ !strcmp(classname, "item_invulnerability"))
+ {
+ if (AAS_VectorForBSPEpairKey(ent, "origin", origin))
+ {
+ spawnflags = 0;
+ AAS_IntForBSPEpairKey(ent, "spawnflags", &spawnflags);
+ //if not a stationary item
+ if (!(spawnflags & 1))
+ {
+ if (!AAS_DropToFloor(origin, mins, maxs))
+ {
+ botimport.Print(PRT_MESSAGE, "%s in solid at (%1.1f %1.1f %1.1f)\n",
+ classname, origin[0], origin[1], origin[2]);
+ } //end if
+ } //end if
+ //areanum = AAS_PointAreaNum(origin);
+ areanum = AAS_BestReachableArea(origin, mins, maxs, origin);
+ //the bot may rocket jump towards this area
+ aasworld.areasettings[areanum].areaflags |= AREA_WEAPONJUMP;
+ //
+ //if (!AAS_AreaGrounded(areanum))
+ // botimport.Print(PRT_MESSAGE, "area not grounded\n");
+ //
+ weaponjumpareas++;
+ } //end if
+ } //end if
+ } //end for
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ if (aasworld.areasettings[i].contents & AREACONTENTS_JUMPPAD)
+ {
+ aasworld.areasettings[i].areaflags |= AREA_WEAPONJUMP;
+ weaponjumpareas++;
+ } //end if
+ } //end for
+ botimport.Print(PRT_MESSAGE, "%d weapon jump areas\n", weaponjumpareas);
+} //end of the function AAS_SetWeaponJumpAreaFlags
+//===========================================================================
+// create a possible weapon jump reachability from area1 to area2
+//
+// check if there's a cool item in the second area
+// check if area1 is lower than area2
+// check if the bot can rocketjump from area1 to area2
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_Reachability_WeaponJump(int area1num, int area2num)
+{
+ int face2num, i, n, ret, visualize;
+ float speed, zvel, hordist;
+ aas_face_t *face2;
+ aas_area_t *area1, *area2;
+ aas_lreachability_t *lreach;
+ vec3_t areastart, facecenter, start, end, dir, cmdmove;// teststart;
+ vec3_t velocity;
+ aas_clientmove_t move;
+ aas_trace_t trace;
+
+ visualize = qfalse;
+// if (area1num == 4436 && area2num == 4318)
+// {
+// visualize = qtrue;
+// }
+ if (!AAS_AreaGrounded(area1num) || AAS_AreaSwim(area1num)) return qfalse;
+ if (!AAS_AreaGrounded(area2num)) return qfalse;
+ //NOTE: only weapon jump towards areas with an interesting item in it??
+ if (!(aasworld.areasettings[area2num].areaflags & AREA_WEAPONJUMP)) return qfalse;
+ //
+ area1 = &aasworld.areas[area1num];
+ area2 = &aasworld.areas[area2num];
+ //don't weapon jump towards way lower areas
+ if (area2->maxs[2] < area1->mins[2]) return qfalse;
+ //
+ VectorCopy(aasworld.areas[area1num].center, start);
+ //if not a swim area
+ if (!AAS_PointAreaNum(start)) Log_Write("area %d center %f %f %f in solid?\r\n", area1num,
+ start[0], start[1], start[2]);
+ VectorCopy(start, end);
+ end[2] -= 1000;
+ trace = AAS_TraceClientBBox(start, end, PRESENCE_CROUCH, -1);
+ if (trace.startsolid) return qfalse;
+ VectorCopy(trace.endpos, areastart);
+ //
+ //areastart is now the start point
+ //
+ for (i = 0; i < area2->numfaces; i++)
+ {
+ face2num = aasworld.faceindex[area2->firstface + i];
+ face2 = &aasworld.faces[abs(face2num)];
+ //if it is not a solid face
+ if (!(face2->faceflags & FACE_GROUND)) continue;
+ //get the center of the face
+ AAS_FaceCenter(face2num, facecenter);
+ //only go higher up with weapon jumps
+ if (facecenter[2] < areastart[2] + 64) continue;
+ //NOTE: set to 2 to allow bfg jump reachabilities
+ for (n = 0; n < 1/*2*/; n++)
+ {
+ //get the rocket jump z velocity
+ if (n) zvel = AAS_BFGJumpZVelocity(areastart);
+ else zvel = AAS_RocketJumpZVelocity(areastart);
+ //get the horizontal speed for the jump, if it isn't possible to calculate this
+ //speed (the jump is not possible) then there's no jump reachability created
+ ret = AAS_HorizontalVelocityForJump(zvel, areastart, facecenter, &speed);
+ if (ret && speed < 300)
+ {
+ //direction towards the face center
+ VectorSubtract(facecenter, areastart, dir);
+ dir[2] = 0;
+ hordist = VectorNormalize(dir);
+ //if (hordist < 1.6 * (facecenter[2] - areastart[2]))
+ {
+ //get command movement
+ VectorScale(dir, speed, cmdmove);
+ VectorSet(velocity, 0, 0, zvel);
+ /*
+ //get command movement
+ VectorScale(dir, speed, velocity);
+ velocity[2] = zvel;
+ VectorSet(cmdmove, 0, 0, 0);
+ */
+ //
+ AAS_PredictClientMovement(&move, -1, areastart, PRESENCE_NORMAL, qtrue,
+ velocity, cmdmove, 30, 30, 0.1f,
+ SE_ENTERWATER|SE_ENTERSLIME|
+ SE_ENTERLAVA|SE_HITGROUNDDAMAGE|
+ SE_TOUCHJUMPPAD|SE_HITGROUND|SE_HITGROUNDAREA, area2num, visualize);
+ //if prediction time wasn't enough to fully predict the movement
+ //don't enter slime or lava and don't fall from too high
+ if (move.frames < 30 &&
+ !(move.stopevent & (SE_ENTERSLIME|SE_ENTERLAVA|SE_HITGROUNDDAMAGE))
+ && (move.stopevent & (SE_HITGROUNDAREA|SE_TOUCHJUMPPAD)))
+ {
+ //create a rocket or bfg jump reachability from area1 to area2
+ lreach = AAS_AllocReachability();
+ if (!lreach) return qfalse;
+ lreach->areanum = area2num;
+ lreach->facenum = 0;
+ lreach->edgenum = 0;
+ VectorCopy(areastart, lreach->start);
+ VectorCopy(facecenter, lreach->end);
+ if (n)
+ {
+ lreach->traveltype = TRAVEL_BFGJUMP;
+ lreach->traveltime = aassettings.rs_bfgjump;
+ } //end if
+ else
+ {
+ lreach->traveltype = TRAVEL_ROCKETJUMP;
+ lreach->traveltime = aassettings.rs_rocketjump;
+ } //end else
+ lreach->next = areareachability[area1num];
+ areareachability[area1num] = lreach;
+ //
+ reach_rocketjump++;
+ return qtrue;
+ } //end if
+ } //end if
+ } //end if
+ } //end for
+ } //end for
+ //
+ return qfalse;
+} //end of the function AAS_Reachability_WeaponJump
+//===========================================================================
+// calculates additional walk off ledge reachabilities for the given area
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_Reachability_WalkOffLedge(int areanum)
+{
+ int i, j, k, l, m, n, p, areas[10], numareas;
+ int face1num, face2num, face3num, edge1num, edge2num, edge3num;
+ int otherareanum, gap, reachareanum, side;
+ aas_area_t *area, *area2;
+ aas_face_t *face1, *face2, *face3;
+ aas_edge_t *edge;
+ aas_plane_t *plane;
+ vec_t *v1, *v2;
+ vec3_t sharededgevec, mid, dir, testend;
+ aas_lreachability_t *lreach;
+ aas_trace_t trace;
+
+ if (!AAS_AreaGrounded(areanum) || AAS_AreaSwim(areanum)) return;
+ //
+ area = &aasworld.areas[areanum];
+ //
+ for (i = 0; i < area->numfaces; i++)
+ {
+ face1num = aasworld.faceindex[area->firstface + i];
+ face1 = &aasworld.faces[abs(face1num)];
+ //face 1 must be a ground face
+ if (!(face1->faceflags & FACE_GROUND)) continue;
+ //go through all the edges of this ground face
+ for (k = 0; k < face1->numedges; k++)
+ {
+ edge1num = aasworld.edgeindex[face1->firstedge + k];
+ //find another not ground face using this same edge
+ for (j = 0; j < area->numfaces; j++)
+ {
+ face2num = aasworld.faceindex[area->firstface + j];
+ face2 = &aasworld.faces[abs(face2num)];
+ //face 2 may not be a ground face
+ if (face2->faceflags & FACE_GROUND) continue;
+ //compare all the edges
+ for (l = 0; l < face2->numedges; l++)
+ {
+ edge2num = aasworld.edgeindex[face2->firstedge + l];
+ if (abs(edge1num) == abs(edge2num))
+ {
+ //get the area at the other side of the face
+ if (face2->frontarea == areanum) otherareanum = face2->backarea;
+ else otherareanum = face2->frontarea;
+ //
+ area2 = &aasworld.areas[otherareanum];
+ //if the other area is grounded!
+ if (aasworld.areasettings[otherareanum].areaflags & AREA_GROUNDED)
+ {
+ //check for a possible gap
+ gap = qfalse;
+ for (n = 0; n < area2->numfaces; n++)
+ {
+ face3num = aasworld.faceindex[area2->firstface + n];
+ //may not be the shared face of the two areas
+ if (abs(face3num) == abs(face2num)) continue;
+ //
+ face3 = &aasworld.faces[abs(face3num)];
+ //find an edge shared by all three faces
+ for (m = 0; m < face3->numedges; m++)
+ {
+ edge3num = aasworld.edgeindex[face3->firstedge + m];
+ //but the edge should be shared by all three faces
+ if (abs(edge3num) == abs(edge1num))
+ {
+ if (!(face3->faceflags & FACE_SOLID))
+ {
+ gap = qtrue;
+ break;
+ } //end if
+ //
+ if (face3->faceflags & FACE_GROUND)
+ {
+ gap = qfalse;
+ break;
+ } //end if
+ //FIXME: there are more situations to be handled
+ gap = qtrue;
+ break;
+ } //end if
+ } //end for
+ if (m < face3->numedges) break;
+ } //end for
+ if (!gap) break;
+ } //end if
+ //check for a walk off ledge reachability
+ edge = &aasworld.edges[abs(edge1num)];
+ side = edge1num < 0;
+ //
+ v1 = aasworld.vertexes[edge->v[side]];
+ v2 = aasworld.vertexes[edge->v[!side]];
+ //
+ plane = &aasworld.planes[face1->planenum];
+ //get the points really into the areas
+ VectorSubtract(v2, v1, sharededgevec);
+ CrossProduct(plane->normal, sharededgevec, dir);
+ VectorNormalize(dir);
+ //
+ VectorAdd(v1, v2, mid);
+ VectorScale(mid, 0.5, mid);
+ VectorMA(mid, 8, dir, mid);
+ //
+ VectorCopy(mid, testend);
+ testend[2] -= 1000;
+ trace = AAS_TraceClientBBox(mid, testend, PRESENCE_CROUCH, -1);
+ //
+ if (trace.startsolid)
+ {
+ //Log_Write("area %d: trace.startsolid\r\n", areanum);
+ break;
+ } //end if
+ reachareanum = AAS_PointAreaNum(trace.endpos);
+ if (reachareanum == areanum)
+ {
+ //Log_Write("area %d: same area\r\n", areanum);
+ break;
+ } //end if
+ if (AAS_ReachabilityExists(areanum, reachareanum))
+ {
+ //Log_Write("area %d: reachability already exists\r\n", areanum);
+ break;
+ } //end if
+ if (!AAS_AreaGrounded(reachareanum) && !AAS_AreaSwim(reachareanum))
+ {
+ //Log_Write("area %d, reach area %d: not grounded and not swim\r\n", areanum, reachareanum);
+ break;
+ } //end if
+ //
+ if (aasworld.areasettings[reachareanum].contents & (AREACONTENTS_SLIME
+ | AREACONTENTS_LAVA))
+ {
+ //Log_Write("area %d, reach area %d: lava or slime\r\n", areanum, reachareanum);
+ break;
+ } //end if
+ //if not going through a cluster portal
+ numareas = AAS_TraceAreas(mid, testend, areas, NULL, sizeof(areas) / sizeof(int));
+ for (p = 0; p < numareas; p++)
+ if (AAS_AreaClusterPortal(areas[p]))
+ break;
+ if (p < numareas)
+ break;
+ // if a maximum fall height is set and the bot would fall down further
+ if (aassettings.rs_maxfallheight && fabs(mid[2] - trace.endpos[2]) > aassettings.rs_maxfallheight)
+ break;
+ //
+ lreach = AAS_AllocReachability();
+ if (!lreach) break;
+ lreach->areanum = reachareanum;
+ lreach->facenum = 0;
+ lreach->edgenum = edge1num;
+ VectorCopy(mid, lreach->start);
+ VectorCopy(trace.endpos, lreach->end);
+ lreach->traveltype = TRAVEL_WALKOFFLEDGE;
+ lreach->traveltime = aassettings.rs_startwalkoffledge + fabs(mid[2] - trace.endpos[2]) * 50 / aassettings.phys_gravity;
+ if (!AAS_AreaSwim(reachareanum) && !AAS_AreaJumpPad(reachareanum))
+ {
+ if (AAS_FallDelta(mid[2] - trace.endpos[2]) > aassettings.phys_falldelta5)
+ {
+ lreach->traveltime += aassettings.rs_falldamage5;
+ } //end if
+ else if (AAS_FallDelta(mid[2] - trace.endpos[2]) > aassettings.phys_falldelta10)
+ {
+ lreach->traveltime += aassettings.rs_falldamage10;
+ } //end if
+ } //end if
+ lreach->next = areareachability[areanum];
+ areareachability[areanum] = lreach;
+ //we've got another walk off ledge reachability
+ reach_walkoffledge++;
+ } //end if
+ } //end for
+ } //end for
+ } //end for
+ } //end for
+} //end of the function AAS_Reachability_WalkOffLedge
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_StoreReachability(void)
+{
+ int i;
+ aas_areasettings_t *areasettings;
+ aas_lreachability_t *lreach;
+ aas_reachability_t *reach;
+
+ if (aasworld.reachability) FreeMemory(aasworld.reachability);
+ aasworld.reachability = (aas_reachability_t *) GetClearedMemory((numlreachabilities + 10) * sizeof(aas_reachability_t));
+ aasworld.reachabilitysize = 1;
+ for (i = 0; i < aasworld.numareas; i++)
+ {
+ areasettings = &aasworld.areasettings[i];
+ areasettings->firstreachablearea = aasworld.reachabilitysize;
+ areasettings->numreachableareas = 0;
+ for (lreach = areareachability[i]; lreach; lreach = lreach->next)
+ {
+ reach = &aasworld.reachability[areasettings->firstreachablearea +
+ areasettings->numreachableareas];
+ reach->areanum = lreach->areanum;
+ reach->facenum = lreach->facenum;
+ reach->edgenum = lreach->edgenum;
+ VectorCopy(lreach->start, reach->start);
+ VectorCopy(lreach->end, reach->end);
+ reach->traveltype = lreach->traveltype;
+ reach->traveltime = lreach->traveltime;
+ //
+ areasettings->numreachableareas++;
+ } //end for
+ aasworld.reachabilitysize += areasettings->numreachableareas;
+ } //end for
+} //end of the function AAS_StoreReachability
+//===========================================================================
+//
+// TRAVEL_WALK 100% equal floor height + steps
+// TRAVEL_CROUCH 100%
+// TRAVEL_BARRIERJUMP 100%
+// TRAVEL_JUMP 80%
+// TRAVEL_LADDER 100% + fall down from ladder + jump up to ladder
+// TRAVEL_WALKOFFLEDGE 90% walk off very steep walls?
+// TRAVEL_SWIM 100%
+// TRAVEL_WATERJUMP 100%
+// TRAVEL_TELEPORT 100%
+// TRAVEL_ELEVATOR 100%
+// TRAVEL_GRAPPLEHOOK 100%
+// TRAVEL_DOUBLEJUMP 0%
+// TRAVEL_RAMPJUMP 0%
+// TRAVEL_STRAFEJUMP 0%
+// TRAVEL_ROCKETJUMP 100% (currently limited towards areas with items)
+// TRAVEL_BFGJUMP 0% (currently disabled)
+// TRAVEL_JUMPPAD 100%
+// TRAVEL_FUNCBOB 100%
+//
+// Parameter: -
+// Returns: true if NOT finished
+// Changes Globals: -
+//===========================================================================
+int AAS_ContinueInitReachability(float time)
+{
+ int i, j, todo, start_time;
+ static float framereachability, reachability_delay;
+ static int lastpercentage;
+
+ if (!aasworld.loaded) return qfalse;
+ //if reachability is calculated for all areas
+ if (aasworld.numreachabilityareas >= aasworld.numareas + 2) return qfalse;
+ //if starting with area 1 (area 0 is a dummy)
+ if (aasworld.numreachabilityareas == 1)
+ {
+ botimport.Print(PRT_MESSAGE, "calculating reachability...\n");
+ lastpercentage = 0;
+ framereachability = 2000;
+ reachability_delay = 1000;
+ } //end if
+ //number of areas to calculate reachability for this cycle
+ todo = aasworld.numreachabilityareas + (int) framereachability;
+ start_time = Sys_MilliSeconds();
+ //loop over the areas
+ for (i = aasworld.numreachabilityareas; i < aasworld.numareas && i < todo; i++)
+ {
+ aasworld.numreachabilityareas++;
+ //only create jumppad reachabilities from jumppad areas
+ if (aasworld.areasettings[i].contents & AREACONTENTS_JUMPPAD)
+ {
+ continue;
+ } //end if
+ //loop over the areas
+ for (j = 1; j < aasworld.numareas; j++)
+ {
+ if (i == j) continue;
+ //never create reachabilities from teleporter or jumppad areas to regular areas
+ if (aasworld.areasettings[i].contents & (AREACONTENTS_TELEPORTER|AREACONTENTS_JUMPPAD))
+ {
+ if (!(aasworld.areasettings[j].contents & (AREACONTENTS_TELEPORTER|AREACONTENTS_JUMPPAD)))
+ {
+ continue;
+ } //end if
+ } //end if
+ //if there already is a reachability link from area i to j
+ if (AAS_ReachabilityExists(i, j)) continue;
+ //check for a swim reachability
+ if (AAS_Reachability_Swim(i, j)) continue;
+ //check for a simple walk on equal floor height reachability
+ if (AAS_Reachability_EqualFloorHeight(i, j)) continue;
+ //check for step, barrier, waterjump and walk off ledge reachabilities
+ if (AAS_Reachability_Step_Barrier_WaterJump_WalkOffLedge(i, j)) continue;
+ //check for ladder reachabilities
+ if (AAS_Reachability_Ladder(i, j)) continue;
+ //check for a jump reachability
+ if (AAS_Reachability_Jump(i, j)) continue;
+ } //end for
+ //never create these reachabilities from teleporter or jumppad areas
+ if (aasworld.areasettings[i].contents & (AREACONTENTS_TELEPORTER|AREACONTENTS_JUMPPAD))
+ {
+ continue;
+ } //end if
+ //loop over the areas
+ for (j = 1; j < aasworld.numareas; j++)
+ {
+ if (i == j) continue;
+ //
+ if (AAS_ReachabilityExists(i, j)) continue;
+ //check for a grapple hook reachability
+ if (calcgrapplereach) AAS_Reachability_Grapple(i, j);
+ //check for a weapon jump reachability
+ AAS_Reachability_WeaponJump(i, j);
+ } //end for
+ //if the calculation took more time than the max reachability delay
+ if (Sys_MilliSeconds() - start_time > (int) reachability_delay) break;
+ //
+ if (aasworld.numreachabilityareas * 1000 / aasworld.numareas > lastpercentage) break;
+ } //end for
+ //
+ if (aasworld.numreachabilityareas == aasworld.numareas)
+ {
+ botimport.Print(PRT_MESSAGE, "\r%6.1f%%", (float) 100.0);
+ botimport.Print(PRT_MESSAGE, "\nplease wait while storing reachability...\n");
+ aasworld.numreachabilityareas++;
+ } //end if
+ //if this is the last step in the reachability calculations
+ else if (aasworld.numreachabilityareas == aasworld.numareas + 1)
+ {
+ //create additional walk off ledge reachabilities for every area
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ //only create jumppad reachabilities from jumppad areas
+ if (aasworld.areasettings[i].contents & AREACONTENTS_JUMPPAD)
+ {
+ continue;
+ } //end if
+ AAS_Reachability_WalkOffLedge(i);
+ } //end for
+ //create jump pad reachabilities
+ AAS_Reachability_JumpPad();
+ //create teleporter reachabilities
+ AAS_Reachability_Teleport();
+ //create elevator (func_plat) reachabilities
+ AAS_Reachability_Elevator();
+ //create func_bobbing reachabilities
+ AAS_Reachability_FuncBobbing();
+ //
+#ifdef DEBUG
+ botimport.Print(PRT_MESSAGE, "%6d reach swim\n", reach_swim);
+ botimport.Print(PRT_MESSAGE, "%6d reach equal floor\n", reach_equalfloor);
+ botimport.Print(PRT_MESSAGE, "%6d reach step\n", reach_step);
+ botimport.Print(PRT_MESSAGE, "%6d reach barrier\n", reach_barrier);
+ botimport.Print(PRT_MESSAGE, "%6d reach waterjump\n", reach_waterjump);
+ botimport.Print(PRT_MESSAGE, "%6d reach walkoffledge\n", reach_walkoffledge);
+ botimport.Print(PRT_MESSAGE, "%6d reach jump\n", reach_jump);
+ botimport.Print(PRT_MESSAGE, "%6d reach ladder\n", reach_ladder);
+ botimport.Print(PRT_MESSAGE, "%6d reach walk\n", reach_walk);
+ botimport.Print(PRT_MESSAGE, "%6d reach teleport\n", reach_teleport);
+ botimport.Print(PRT_MESSAGE, "%6d reach funcbob\n", reach_funcbob);
+ botimport.Print(PRT_MESSAGE, "%6d reach elevator\n", reach_elevator);
+ botimport.Print(PRT_MESSAGE, "%6d reach grapple\n", reach_grapple);
+ botimport.Print(PRT_MESSAGE, "%6d reach rocketjump\n", reach_rocketjump);
+ botimport.Print(PRT_MESSAGE, "%6d reach jumppad\n", reach_jumppad);
+#endif
+ //*/
+ //store all the reachabilities
+ AAS_StoreReachability();
+ //free the reachability link heap
+ AAS_ShutDownReachabilityHeap();
+ //
+ FreeMemory(areareachability);
+ //
+ aasworld.numreachabilityareas++;
+ //
+ botimport.Print(PRT_MESSAGE, "calculating clusters...\n");
+ } //end if
+ else
+ {
+ lastpercentage = aasworld.numreachabilityareas * 1000 / aasworld.numareas;
+ botimport.Print(PRT_MESSAGE, "\r%6.1f%%", (float) lastpercentage / 10);
+ } //end else
+ //not yet finished
+ return qtrue;
+} //end of the function AAS_ContinueInitReachability
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_InitReachability(void)
+{
+ if (!aasworld.loaded) return;
+
+ if (aasworld.reachabilitysize)
+ {
+#ifndef BSPC
+ if (!((int)LibVarGetValue("forcereachability")))
+ {
+ aasworld.numreachabilityareas = aasworld.numareas + 2;
+ return;
+ } //end if
+#else
+ aasworld.numreachabilityareas = aasworld.numareas + 2;
+ return;
+#endif //BSPC
+ } //end if
+#ifndef BSPC
+ calcgrapplereach = LibVarGetValue("grapplereach");
+#endif
+ aasworld.savefile = qtrue;
+ //start with area 1 because area zero is a dummy
+ aasworld.numreachabilityareas = 1;
+ ////aasworld.numreachabilityareas = aasworld.numareas + 1; //only calculate entity reachabilities
+ //setup the heap with reachability links
+ AAS_SetupReachabilityHeap();
+ //allocate area reachability link array
+ areareachability = (aas_lreachability_t **) GetClearedMemory(
+ aasworld.numareas * sizeof(aas_lreachability_t *));
+ //
+ AAS_SetWeaponJumpAreaFlags();
+} //end of the function AAS_InitReachable
diff --git a/code/botlib/be_aas_reach.h b/code/botlib/be_aas_reach.h
new file mode 100755
index 0000000..e4b5ef2
--- /dev/null
+++ b/code/botlib/be_aas_reach.h
@@ -0,0 +1,68 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_reach.h
+ *
+ * desc: AAS
+ *
+ * $Archive: /source/code/botlib/be_aas_reach.h $
+ *
+ *****************************************************************************/
+
+#ifdef AASINTERN
+//initialize calculating the reachabilities
+void AAS_InitReachability(void);
+//continue calculating the reachabilities
+int AAS_ContinueInitReachability(float time);
+//
+int AAS_BestReachableLinkArea(aas_link_t *areas);
+#endif //AASINTERN
+
+//returns true if the are has reachabilities to other areas
+int AAS_AreaReachability(int areanum);
+//returns the best reachable area and goal origin for a bounding box at the given origin
+int AAS_BestReachableArea(vec3_t origin, vec3_t mins, vec3_t maxs, vec3_t goalorigin);
+//returns the best jumppad area from which the bbox at origin is reachable
+int AAS_BestReachableFromJumpPadArea(vec3_t origin, vec3_t mins, vec3_t maxs);
+//returns the next reachability using the given model
+int AAS_NextModelReachability(int num, int modelnum);
+//returns the total area of the ground faces of the given area
+float AAS_AreaGroundFaceArea(int areanum);
+//returns true if the area is crouch only
+int AAS_AreaCrouch(int areanum);
+//returns true if a player can swim in this area
+int AAS_AreaSwim(int areanum);
+//returns true if the area is filled with a liquid
+int AAS_AreaLiquid(int areanum);
+//returns true if the area contains lava
+int AAS_AreaLava(int areanum);
+//returns true if the area contains slime
+int AAS_AreaSlime(int areanum);
+//returns true if the area has one or more ground faces
+int AAS_AreaGrounded(int areanum);
+//returns true if the area has one or more ladder faces
+int AAS_AreaLadder(int areanum);
+//returns true if the area is a jump pad
+int AAS_AreaJumpPad(int areanum);
+//returns true if the area is donotenter
+int AAS_AreaDoNotEnter(int areanum);
diff --git a/code/botlib/be_aas_route.c b/code/botlib/be_aas_route.c
new file mode 100755
index 0000000..441984d
--- /dev/null
+++ b/code/botlib/be_aas_route.c
@@ -0,0 +1,2209 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_route.c
+ *
+ * desc: AAS
+ *
+ * $Archive: /MissionPack/code/botlib/be_aas_route.c $
+ *
+ *****************************************************************************/
+
+#include "../game/q_shared.h"
+#include "l_utils.h"
+#include "l_memory.h"
+#include "l_log.h"
+#include "l_crc.h"
+#include "l_libvar.h"
+#include "l_script.h"
+#include "l_precomp.h"
+#include "l_struct.h"
+#include "aasfile.h"
+#include "../game/botlib.h"
+#include "../game/be_aas.h"
+#include "be_aas_funcs.h"
+#include "be_interface.h"
+#include "be_aas_def.h"
+
+#define ROUTING_DEBUG
+
+//travel time in hundreths of a second = distance * 100 / speed
+#define DISTANCEFACTOR_CROUCH 1.3f //crouch speed = 100
+#define DISTANCEFACTOR_SWIM 1 //should be 0.66, swim speed = 150
+#define DISTANCEFACTOR_WALK 0.33f //walk speed = 300
+
+//cache refresh time
+#define CACHE_REFRESHTIME 15.0f //15 seconds refresh time
+
+//maximum number of routing updates each frame
+#define MAX_FRAMEROUTINGUPDATES 10
+
+
+/*
+
+ area routing cache:
+ stores the distances within one cluster to a specific goal area
+ this goal area is in this same cluster and could be a cluster portal
+ for every cluster there's a list with routing cache for every area
+ in that cluster (including the portals of that cluster)
+ area cache stores aasworld.clusters[?].numreachabilityareas travel times
+
+ portal routing cache:
+ stores the distances of all portals to a specific goal area
+ this goal area could be in any cluster and could also be a cluster portal
+ for every area (aasworld.numareas) the portal cache stores
+ aasworld.numportals travel times
+
+*/
+
+#ifdef ROUTING_DEBUG
+int numareacacheupdates;
+int numportalcacheupdates;
+#endif //ROUTING_DEBUG
+
+int routingcachesize;
+int max_routingcachesize;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+#ifdef ROUTING_DEBUG
+void AAS_RoutingInfo(void)
+{
+ botimport.Print(PRT_MESSAGE, "%d area cache updates\n", numareacacheupdates);
+ botimport.Print(PRT_MESSAGE, "%d portal cache updates\n", numportalcacheupdates);
+ botimport.Print(PRT_MESSAGE, "%d bytes routing cache\n", routingcachesize);
+} //end of the function AAS_RoutingInfo
+#endif //ROUTING_DEBUG
+//===========================================================================
+// returns the number of the area in the cluster
+// assumes the given area is in the given cluster or a portal of the cluster
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+__inline int AAS_ClusterAreaNum(int cluster, int areanum)
+{
+ int side, areacluster;
+
+ areacluster = aasworld.areasettings[areanum].cluster;
+ if (areacluster > 0) return aasworld.areasettings[areanum].clusterareanum;
+ else
+ {
+/*#ifdef ROUTING_DEBUG
+ if (aasworld.portals[-areacluster].frontcluster != cluster &&
+ aasworld.portals[-areacluster].backcluster != cluster)
+ {
+ botimport.Print(PRT_ERROR, "portal %d: does not belong to cluster %d\n"
+ , -areacluster, cluster);
+ } //end if
+#endif //ROUTING_DEBUG*/
+ side = aasworld.portals[-areacluster].frontcluster != cluster;
+ return aasworld.portals[-areacluster].clusterareanum[side];
+ } //end else
+} //end of the function AAS_ClusterAreaNum
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_InitTravelFlagFromType(void)
+{
+ int i;
+
+ for (i = 0; i < MAX_TRAVELTYPES; i++)
+ {
+ aasworld.travelflagfortype[i] = TFL_INVALID;
+ } //end for
+ aasworld.travelflagfortype[TRAVEL_INVALID] = TFL_INVALID;
+ aasworld.travelflagfortype[TRAVEL_WALK] = TFL_WALK;
+ aasworld.travelflagfortype[TRAVEL_CROUCH] = TFL_CROUCH;
+ aasworld.travelflagfortype[TRAVEL_BARRIERJUMP] = TFL_BARRIERJUMP;
+ aasworld.travelflagfortype[TRAVEL_JUMP] = TFL_JUMP;
+ aasworld.travelflagfortype[TRAVEL_LADDER] = TFL_LADDER;
+ aasworld.travelflagfortype[TRAVEL_WALKOFFLEDGE] = TFL_WALKOFFLEDGE;
+ aasworld.travelflagfortype[TRAVEL_SWIM] = TFL_SWIM;
+ aasworld.travelflagfortype[TRAVEL_WATERJUMP] = TFL_WATERJUMP;
+ aasworld.travelflagfortype[TRAVEL_TELEPORT] = TFL_TELEPORT;
+ aasworld.travelflagfortype[TRAVEL_ELEVATOR] = TFL_ELEVATOR;
+ aasworld.travelflagfortype[TRAVEL_ROCKETJUMP] = TFL_ROCKETJUMP;
+ aasworld.travelflagfortype[TRAVEL_BFGJUMP] = TFL_BFGJUMP;
+ aasworld.travelflagfortype[TRAVEL_GRAPPLEHOOK] = TFL_GRAPPLEHOOK;
+ aasworld.travelflagfortype[TRAVEL_DOUBLEJUMP] = TFL_DOUBLEJUMP;
+ aasworld.travelflagfortype[TRAVEL_RAMPJUMP] = TFL_RAMPJUMP;
+ aasworld.travelflagfortype[TRAVEL_STRAFEJUMP] = TFL_STRAFEJUMP;
+ aasworld.travelflagfortype[TRAVEL_JUMPPAD] = TFL_JUMPPAD;
+ aasworld.travelflagfortype[TRAVEL_FUNCBOB] = TFL_FUNCBOB;
+} //end of the function AAS_InitTravelFlagFromType
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+__inline int AAS_TravelFlagForType_inline(int traveltype)
+{
+ int tfl;
+
+ tfl = 0;
+ if (tfl & TRAVELFLAG_NOTTEAM1)
+ tfl |= TFL_NOTTEAM1;
+ if (tfl & TRAVELFLAG_NOTTEAM2)
+ tfl |= TFL_NOTTEAM2;
+ traveltype &= TRAVELTYPE_MASK;
+ if (traveltype < 0 || traveltype >= MAX_TRAVELTYPES)
+ return TFL_INVALID;
+ tfl |= aasworld.travelflagfortype[traveltype];
+ return tfl;
+} //end of the function AAS_TravelFlagForType_inline
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_TravelFlagForType(int traveltype)
+{
+ return AAS_TravelFlagForType_inline(traveltype);
+} //end of the function AAS_TravelFlagForType_inline
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_UnlinkCache(aas_routingcache_t *cache)
+{
+ if (cache->time_next) cache->time_next->time_prev = cache->time_prev;
+ else aasworld.newestcache = cache->time_prev;
+ if (cache->time_prev) cache->time_prev->time_next = cache->time_next;
+ else aasworld.oldestcache = cache->time_next;
+ cache->time_next = NULL;
+ cache->time_prev = NULL;
+} //end of the function AAS_UnlinkCache
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_LinkCache(aas_routingcache_t *cache)
+{
+ if (aasworld.newestcache)
+ {
+ aasworld.newestcache->time_next = cache;
+ cache->time_prev = aasworld.newestcache;
+ } //end if
+ else
+ {
+ aasworld.oldestcache = cache;
+ cache->time_prev = NULL;
+ } //end else
+ cache->time_next = NULL;
+ aasworld.newestcache = cache;
+} //end of the function AAS_LinkCache
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_FreeRoutingCache(aas_routingcache_t *cache)
+{
+ AAS_UnlinkCache(cache);
+ routingcachesize -= cache->size;
+ FreeMemory(cache);
+} //end of the function AAS_FreeRoutingCache
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_RemoveRoutingCacheInCluster( int clusternum )
+{
+ int i;
+ aas_routingcache_t *cache, *nextcache;
+ aas_cluster_t *cluster;
+
+ if (!aasworld.clusterareacache)
+ return;
+ cluster = &aasworld.clusters[clusternum];
+ for (i = 0; i < cluster->numareas; i++)
+ {
+ for (cache = aasworld.clusterareacache[clusternum][i]; cache; cache = nextcache)
+ {
+ nextcache = cache->next;
+ AAS_FreeRoutingCache(cache);
+ } //end for
+ aasworld.clusterareacache[clusternum][i] = NULL;
+ } //end for
+} //end of the function AAS_RemoveRoutingCacheInCluster
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_RemoveRoutingCacheUsingArea( int areanum )
+{
+ int i, clusternum;
+ aas_routingcache_t *cache, *nextcache;
+
+ clusternum = aasworld.areasettings[areanum].cluster;
+ if (clusternum > 0)
+ {
+ //remove all the cache in the cluster the area is in
+ AAS_RemoveRoutingCacheInCluster( clusternum );
+ } //end if
+ else
+ {
+ // if this is a portal remove all cache in both the front and back cluster
+ AAS_RemoveRoutingCacheInCluster( aasworld.portals[-clusternum].frontcluster );
+ AAS_RemoveRoutingCacheInCluster( aasworld.portals[-clusternum].backcluster );
+ } //end else
+ // remove all portal cache
+ for (i = 0; i < aasworld.numareas; i++)
+ {
+ //refresh portal cache
+ for (cache = aasworld.portalcache[i]; cache; cache = nextcache)
+ {
+ nextcache = cache->next;
+ AAS_FreeRoutingCache(cache);
+ } //end for
+ aasworld.portalcache[i] = NULL;
+ } //end for
+} //end of the function AAS_RemoveRoutingCacheUsingArea
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_EnableRoutingArea(int areanum, int enable)
+{
+ int flags;
+
+ if (areanum <= 0 || areanum >= aasworld.numareas)
+ {
+ if (bot_developer)
+ {
+ botimport.Print(PRT_ERROR, "AAS_EnableRoutingArea: areanum %d out of range\n", areanum);
+ } //end if
+ return 0;
+ } //end if
+ flags = aasworld.areasettings[areanum].areaflags & AREA_DISABLED;
+ if (enable < 0)
+ return !flags;
+
+ if (enable)
+ aasworld.areasettings[areanum].areaflags &= ~AREA_DISABLED;
+ else
+ aasworld.areasettings[areanum].areaflags |= AREA_DISABLED;
+ // if the status of the area changed
+ if ( (flags & AREA_DISABLED) != (aasworld.areasettings[areanum].areaflags & AREA_DISABLED) )
+ {
+ //remove all routing cache involving this area
+ AAS_RemoveRoutingCacheUsingArea( areanum );
+ } //end if
+ return !flags;
+} //end of the function AAS_EnableRoutingArea
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+__inline float AAS_RoutingTime(void)
+{
+ return AAS_Time();
+} //end of the function AAS_RoutingTime
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_GetAreaContentsTravelFlags(int areanum)
+{
+ int contents, tfl;
+
+ contents = aasworld.areasettings[areanum].contents;
+ tfl = 0;
+ if (contents & AREACONTENTS_WATER)
+ tfl |= TFL_WATER;
+ else if (contents & AREACONTENTS_SLIME)
+ tfl |= TFL_SLIME;
+ else if (contents & AREACONTENTS_LAVA)
+ tfl |= TFL_LAVA;
+ else
+ tfl |= TFL_AIR;
+ if (contents & AREACONTENTS_DONOTENTER)
+ tfl |= TFL_DONOTENTER;
+ if (contents & AREACONTENTS_NOTTEAM1)
+ tfl |= TFL_NOTTEAM1;
+ if (contents & AREACONTENTS_NOTTEAM2)
+ tfl |= TFL_NOTTEAM2;
+ if (aasworld.areasettings[areanum].areaflags & AREA_BRIDGE)
+ tfl |= TFL_BRIDGE;
+ return tfl;
+} //end of the function AAS_GetAreaContentsTravelFlags
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+__inline int AAS_AreaContentsTravelFlags_inline(int areanum)
+{
+ return aasworld.areacontentstravelflags[areanum];
+} //end of the function AAS_AreaContentsTravelFlags
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_AreaContentsTravelFlags(int areanum)
+{
+ return aasworld.areacontentstravelflags[areanum];
+} //end of the function AAS_AreaContentsTravelFlags
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_InitAreaContentsTravelFlags(void)
+{
+ int i;
+
+ if (aasworld.areacontentstravelflags) FreeMemory(aasworld.areacontentstravelflags);
+ aasworld.areacontentstravelflags = (int *) GetClearedMemory(aasworld.numareas * sizeof(int));
+ //
+ for (i = 0; i < aasworld.numareas; i++) {
+ aasworld.areacontentstravelflags[i] = AAS_GetAreaContentsTravelFlags(i);
+ }
+} //end of the function AAS_InitAreaContentsTravelFlags
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_CreateReversedReachability(void)
+{
+ int i, n;
+ aas_reversedlink_t *revlink;
+ aas_reachability_t *reach;
+ aas_areasettings_t *settings;
+ char *ptr;
+#ifdef DEBUG
+ int starttime;
+
+ starttime = Sys_MilliSeconds();
+#endif
+ //free reversed links that have already been created
+ if (aasworld.reversedreachability) FreeMemory(aasworld.reversedreachability);
+ //allocate memory for the reversed reachability links
+ ptr = (char *) GetClearedMemory(aasworld.numareas * sizeof(aas_reversedreachability_t) +
+ aasworld.reachabilitysize * sizeof(aas_reversedlink_t));
+ //
+ aasworld.reversedreachability = (aas_reversedreachability_t *) ptr;
+ //pointer to the memory for the reversed links
+ ptr += aasworld.numareas * sizeof(aas_reversedreachability_t);
+ //check all reachabilities of all areas
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ //settings of the area
+ settings = &aasworld.areasettings[i];
+ //
+ if (settings->numreachableareas >= 128)
+ botimport.Print(PRT_WARNING, "area %d has more than 128 reachabilities\n", i);
+ //create reversed links for the reachabilities
+ for (n = 0; n < settings->numreachableareas && n < 128; n++)
+ {
+ //reachability link
+ reach = &aasworld.reachability[settings->firstreachablearea + n];
+ //
+ revlink = (aas_reversedlink_t *) ptr;
+ ptr += sizeof(aas_reversedlink_t);
+ //
+ revlink->areanum = i;
+ revlink->linknum = settings->firstreachablearea + n;
+ revlink->next = aasworld.reversedreachability[reach->areanum].first;
+ aasworld.reversedreachability[reach->areanum].first = revlink;
+ aasworld.reversedreachability[reach->areanum].numlinks++;
+ } //end for
+ } //end for
+#ifdef DEBUG
+ botimport.Print(PRT_MESSAGE, "reversed reachability %d msec\n", Sys_MilliSeconds() - starttime);
+#endif
+} //end of the function AAS_CreateReversedReachability
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+unsigned short int AAS_AreaTravelTime(int areanum, vec3_t start, vec3_t end)
+{
+ int intdist;
+ float dist;
+ vec3_t dir;
+
+ VectorSubtract(start, end, dir);
+ dist = VectorLength(dir);
+ //if crouch only area
+ if (AAS_AreaCrouch(areanum)) dist *= DISTANCEFACTOR_CROUCH;
+ //if swim area
+ else if (AAS_AreaSwim(areanum)) dist *= DISTANCEFACTOR_SWIM;
+ //normal walk area
+ else dist *= DISTANCEFACTOR_WALK;
+ //
+ intdist = (int) dist;
+ //make sure the distance isn't zero
+ if (intdist <= 0) intdist = 1;
+ return intdist;
+} //end of the function AAS_AreaTravelTime
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_CalculateAreaTravelTimes(void)
+{
+ int i, l, n, size;
+ char *ptr;
+ vec3_t end;
+ aas_reversedreachability_t *revreach;
+ aas_reversedlink_t *revlink;
+ aas_reachability_t *reach;
+ aas_areasettings_t *settings;
+ int starttime;
+
+ starttime = Sys_MilliSeconds();
+ //if there are still area travel times, free the memory
+ if (aasworld.areatraveltimes) FreeMemory(aasworld.areatraveltimes);
+ //get the total size of all the area travel times
+ size = aasworld.numareas * sizeof(unsigned short **);
+ for (i = 0; i < aasworld.numareas; i++)
+ {
+ revreach = &aasworld.reversedreachability[i];
+ //settings of the area
+ settings = &aasworld.areasettings[i];
+ //
+ size += settings->numreachableareas * sizeof(unsigned short *);
+ //
+ size += settings->numreachableareas * revreach->numlinks * sizeof(unsigned short);
+ } //end for
+ //allocate memory for the area travel times
+ ptr = (char *) GetClearedMemory(size);
+ aasworld.areatraveltimes = (unsigned short ***) ptr;
+ ptr += aasworld.numareas * sizeof(unsigned short **);
+ //calcluate the travel times for all the areas
+ for (i = 0; i < aasworld.numareas; i++)
+ {
+ //reversed reachabilities of this area
+ revreach = &aasworld.reversedreachability[i];
+ //settings of the area
+ settings = &aasworld.areasettings[i];
+ //
+ aasworld.areatraveltimes[i] = (unsigned short **) ptr;
+ ptr += settings->numreachableareas * sizeof(unsigned short *);
+ //
+ for (l = 0; l < settings->numreachableareas; l++)
+ {
+ aasworld.areatraveltimes[i][l] = (unsigned short *) ptr;
+ ptr += revreach->numlinks * sizeof(unsigned short);
+ //reachability link
+ reach = &aasworld.reachability[settings->firstreachablearea + l];
+ //
+ for (n = 0, revlink = revreach->first; revlink; revlink = revlink->next, n++)
+ {
+ VectorCopy(aasworld.reachability[revlink->linknum].end, end);
+ //
+ aasworld.areatraveltimes[i][l][n] = AAS_AreaTravelTime(i, end, reach->start);
+ } //end for
+ } //end for
+ } //end for
+#ifdef DEBUG
+ botimport.Print(PRT_MESSAGE, "area travel times %d msec\n", Sys_MilliSeconds() - starttime);
+#endif
+} //end of the function AAS_CalculateAreaTravelTimes
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_PortalMaxTravelTime(int portalnum)
+{
+ int l, n, t, maxt;
+ aas_portal_t *portal;
+ aas_reversedreachability_t *revreach;
+ aas_reversedlink_t *revlink;
+ aas_areasettings_t *settings;
+
+ portal = &aasworld.portals[portalnum];
+ //reversed reachabilities of this portal area
+ revreach = &aasworld.reversedreachability[portal->areanum];
+ //settings of the portal area
+ settings = &aasworld.areasettings[portal->areanum];
+ //
+ maxt = 0;
+ for (l = 0; l < settings->numreachableareas; l++)
+ {
+ for (n = 0, revlink = revreach->first; revlink; revlink = revlink->next, n++)
+ {
+ t = aasworld.areatraveltimes[portal->areanum][l][n];
+ if (t > maxt)
+ {
+ maxt = t;
+ } //end if
+ } //end for
+ } //end for
+ return maxt;
+} //end of the function AAS_PortalMaxTravelTime
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_InitPortalMaxTravelTimes(void)
+{
+ int i;
+
+ if (aasworld.portalmaxtraveltimes) FreeMemory(aasworld.portalmaxtraveltimes);
+
+ aasworld.portalmaxtraveltimes = (int *) GetClearedMemory(aasworld.numportals * sizeof(int));
+
+ for (i = 0; i < aasworld.numportals; i++)
+ {
+ aasworld.portalmaxtraveltimes[i] = AAS_PortalMaxTravelTime(i);
+ //botimport.Print(PRT_MESSAGE, "portal %d max tt = %d\n", i, aasworld.portalmaxtraveltimes[i]);
+ } //end for
+} //end of the function AAS_InitPortalMaxTravelTimes
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+/*
+int AAS_FreeOldestCache(void)
+{
+ int i, j, bestcluster, bestarea, freed;
+ float besttime;
+ aas_routingcache_t *cache, *bestcache;
+
+ freed = qfalse;
+ besttime = 999999999;
+ bestcache = NULL;
+ bestcluster = 0;
+ bestarea = 0;
+ //refresh cluster cache
+ for (i = 0; i < aasworld.numclusters; i++)
+ {
+ for (j = 0; j < aasworld.clusters[i].numareas; j++)
+ {
+ for (cache = aasworld.clusterareacache[i][j]; cache; cache = cache->next)
+ {
+ //never remove cache leading towards a portal
+ if (aasworld.areasettings[cache->areanum].cluster < 0) continue;
+ //if this cache is older than the cache we found so far
+ if (cache->time < besttime)
+ {
+ bestcache = cache;
+ bestcluster = i;
+ bestarea = j;
+ besttime = cache->time;
+ } //end if
+ } //end for
+ } //end for
+ } //end for
+ if (bestcache)
+ {
+ cache = bestcache;
+ if (cache->prev) cache->prev->next = cache->next;
+ else aasworld.clusterareacache[bestcluster][bestarea] = cache->next;
+ if (cache->next) cache->next->prev = cache->prev;
+ AAS_FreeRoutingCache(cache);
+ freed = qtrue;
+ } //end if
+ besttime = 999999999;
+ bestcache = NULL;
+ bestarea = 0;
+ for (i = 0; i < aasworld.numareas; i++)
+ {
+ //refresh portal cache
+ for (cache = aasworld.portalcache[i]; cache; cache = cache->next)
+ {
+ if (cache->time < besttime)
+ {
+ bestcache = cache;
+ bestarea = i;
+ besttime = cache->time;
+ } //end if
+ } //end for
+ } //end for
+ if (bestcache)
+ {
+ cache = bestcache;
+ if (cache->prev) cache->prev->next = cache->next;
+ else aasworld.portalcache[bestarea] = cache->next;
+ if (cache->next) cache->next->prev = cache->prev;
+ AAS_FreeRoutingCache(cache);
+ freed = qtrue;
+ } //end if
+ return freed;
+} //end of the function AAS_FreeOldestCache
+*/
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_FreeOldestCache(void)
+{
+ int clusterareanum;
+ aas_routingcache_t *cache;
+
+ for (cache = aasworld.oldestcache; cache; cache = cache->time_next) {
+ // never free area cache leading towards a portal
+ if (cache->type == CACHETYPE_AREA && aasworld.areasettings[cache->areanum].cluster < 0) {
+ continue;
+ }
+ break;
+ }
+ if (cache) {
+ // unlink the cache
+ if (cache->type == CACHETYPE_AREA) {
+ //number of the area in the cluster
+ clusterareanum = AAS_ClusterAreaNum(cache->cluster, cache->areanum);
+ // unlink from cluster area cache
+ if (cache->prev) cache->prev->next = cache->next;
+ else aasworld.clusterareacache[cache->cluster][clusterareanum] = cache->next;
+ if (cache->next) cache->next->prev = cache->prev;
+ }
+ else {
+ // unlink from portal cache
+ if (cache->prev) cache->prev->next = cache->next;
+ else aasworld.portalcache[cache->areanum] = cache->next;
+ if (cache->next) cache->next->prev = cache->prev;
+ }
+ AAS_FreeRoutingCache(cache);
+ return qtrue;
+ }
+ return qfalse;
+} //end of the function AAS_FreeOldestCache
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+aas_routingcache_t *AAS_AllocRoutingCache(int numtraveltimes)
+{
+ aas_routingcache_t *cache;
+ int size;
+
+ //
+ size = sizeof(aas_routingcache_t)
+ + numtraveltimes * sizeof(unsigned short int)
+ + numtraveltimes * sizeof(unsigned char);
+ //
+ routingcachesize += size;
+ //
+ cache = (aas_routingcache_t *) GetClearedMemory(size);
+ cache->reachabilities = (unsigned char *) cache + sizeof(aas_routingcache_t)
+ + numtraveltimes * sizeof(unsigned short int);
+ cache->size = size;
+ return cache;
+} //end of the function AAS_AllocRoutingCache
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_FreeAllClusterAreaCache(void)
+{
+ int i, j;
+ aas_routingcache_t *cache, *nextcache;
+ aas_cluster_t *cluster;
+
+ //free all cluster cache if existing
+ if (!aasworld.clusterareacache) return;
+ //free caches
+ for (i = 0; i < aasworld.numclusters; i++)
+ {
+ cluster = &aasworld.clusters[i];
+ for (j = 0; j < cluster->numareas; j++)
+ {
+ for (cache = aasworld.clusterareacache[i][j]; cache; cache = nextcache)
+ {
+ nextcache = cache->next;
+ AAS_FreeRoutingCache(cache);
+ } //end for
+ aasworld.clusterareacache[i][j] = NULL;
+ } //end for
+ } //end for
+ //free the cluster cache array
+ FreeMemory(aasworld.clusterareacache);
+ aasworld.clusterareacache = NULL;
+} //end of the function AAS_FreeAllClusterAreaCache
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_InitClusterAreaCache(void)
+{
+ int i, size;
+ char *ptr;
+
+ //
+ for (size = 0, i = 0; i < aasworld.numclusters; i++)
+ {
+ size += aasworld.clusters[i].numareas;
+ } //end for
+ //two dimensional array with pointers for every cluster to routing cache
+ //for every area in that cluster
+ ptr = (char *) GetClearedMemory(
+ aasworld.numclusters * sizeof(aas_routingcache_t **) +
+ size * sizeof(aas_routingcache_t *));
+ aasworld.clusterareacache = (aas_routingcache_t ***) ptr;
+ ptr += aasworld.numclusters * sizeof(aas_routingcache_t **);
+ for (i = 0; i < aasworld.numclusters; i++)
+ {
+ aasworld.clusterareacache[i] = (aas_routingcache_t **) ptr;
+ ptr += aasworld.clusters[i].numareas * sizeof(aas_routingcache_t *);
+ } //end for
+} //end of the function AAS_InitClusterAreaCache
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_FreeAllPortalCache(void)
+{
+ int i;
+ aas_routingcache_t *cache, *nextcache;
+
+ //free all portal cache if existing
+ if (!aasworld.portalcache) return;
+ //free portal caches
+ for (i = 0; i < aasworld.numareas; i++)
+ {
+ for (cache = aasworld.portalcache[i]; cache; cache = nextcache)
+ {
+ nextcache = cache->next;
+ AAS_FreeRoutingCache(cache);
+ } //end for
+ aasworld.portalcache[i] = NULL;
+ } //end for
+ FreeMemory(aasworld.portalcache);
+ aasworld.portalcache = NULL;
+} //end of the function AAS_FreeAllPortalCache
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_InitPortalCache(void)
+{
+ //
+ aasworld.portalcache = (aas_routingcache_t **) GetClearedMemory(
+ aasworld.numareas * sizeof(aas_routingcache_t *));
+} //end of the function AAS_InitPortalCache
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_InitRoutingUpdate(void)
+{
+ int i, maxreachabilityareas;
+
+ //free routing update fields if already existing
+ if (aasworld.areaupdate) FreeMemory(aasworld.areaupdate);
+ //
+ maxreachabilityareas = 0;
+ for (i = 0; i < aasworld.numclusters; i++)
+ {
+ if (aasworld.clusters[i].numreachabilityareas > maxreachabilityareas)
+ {
+ maxreachabilityareas = aasworld.clusters[i].numreachabilityareas;
+ } //end if
+ } //end for
+ //allocate memory for the routing update fields
+ aasworld.areaupdate = (aas_routingupdate_t *) GetClearedMemory(
+ maxreachabilityareas * sizeof(aas_routingupdate_t));
+ //
+ if (aasworld.portalupdate) FreeMemory(aasworld.portalupdate);
+ //allocate memory for the portal update fields
+ aasworld.portalupdate = (aas_routingupdate_t *) GetClearedMemory(
+ (aasworld.numportals+1) * sizeof(aas_routingupdate_t));
+} //end of the function AAS_InitRoutingUpdate
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_CreateAllRoutingCache(void)
+{
+ int i, j, t;
+
+ aasworld.initialized = qtrue;
+ botimport.Print(PRT_MESSAGE, "AAS_CreateAllRoutingCache\n");
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ if (!AAS_AreaReachability(i)) continue;
+ for (j = 1; j < aasworld.numareas; j++)
+ {
+ if (i == j) continue;
+ if (!AAS_AreaReachability(j)) continue;
+ t = AAS_AreaTravelTimeToGoalArea(i, aasworld.areas[i].center, j, TFL_DEFAULT);
+ //Log_Write("traveltime from %d to %d is %d", i, j, t);
+ } //end for
+ } //end for
+ aasworld.initialized = qfalse;
+} //end of the function AAS_CreateAllRoutingCache
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+
+//the route cache header
+//this header is followed by numportalcache + numareacache aas_routingcache_t
+//structures that store routing cache
+typedef struct routecacheheader_s
+{
+ int ident;
+ int version;
+ int numareas;
+ int numclusters;
+ int areacrc;
+ int clustercrc;
+ int numportalcache;
+ int numareacache;
+} routecacheheader_t;
+
+#define RCID (('C'<<24)+('R'<<16)+('E'<<8)+'M')
+#define RCVERSION 2
+
+//void AAS_DecompressVis(byte *in, int numareas, byte *decompressed);
+//int AAS_CompressVis(byte *vis, int numareas, byte *dest);
+
+void AAS_WriteRouteCache(void)
+{
+ int i, j, numportalcache, numareacache, totalsize;
+ aas_routingcache_t *cache;
+ aas_cluster_t *cluster;
+ fileHandle_t fp;
+ char filename[MAX_QPATH];
+ routecacheheader_t routecacheheader;
+
+ numportalcache = 0;
+ for (i = 0; i < aasworld.numareas; i++)
+ {
+ for (cache = aasworld.portalcache[i]; cache; cache = cache->next)
+ {
+ numportalcache++;
+ } //end for
+ } //end for
+ numareacache = 0;
+ for (i = 0; i < aasworld.numclusters; i++)
+ {
+ cluster = &aasworld.clusters[i];
+ for (j = 0; j < cluster->numareas; j++)
+ {
+ for (cache = aasworld.clusterareacache[i][j]; cache; cache = cache->next)
+ {
+ numareacache++;
+ } //end for
+ } //end for
+ } //end for
+ // open the file for writing
+ Com_sprintf(filename, MAX_QPATH, "maps/%s.rcd", aasworld.mapname);
+ botimport.FS_FOpenFile( filename, &fp, FS_WRITE );
+ if (!fp)
+ {
+ AAS_Error("Unable to open file: %s\n", filename);
+ return;
+ } //end if
+ //create the header
+ routecacheheader.ident = RCID;
+ routecacheheader.version = RCVERSION;
+ routecacheheader.numareas = aasworld.numareas;
+ routecacheheader.numclusters = aasworld.numclusters;
+ routecacheheader.areacrc = CRC_ProcessString( (unsigned char *)aasworld.areas, sizeof(aas_area_t) * aasworld.numareas );
+ routecacheheader.clustercrc = CRC_ProcessString( (unsigned char *)aasworld.clusters, sizeof(aas_cluster_t) * aasworld.numclusters );
+ routecacheheader.numportalcache = numportalcache;
+ routecacheheader.numareacache = numareacache;
+ //write the header
+ botimport.FS_Write(&routecacheheader, sizeof(routecacheheader_t), fp);
+ //
+ totalsize = 0;
+ //write all the cache
+ for (i = 0; i < aasworld.numareas; i++)
+ {
+ for (cache = aasworld.portalcache[i]; cache; cache = cache->next)
+ {
+ botimport.FS_Write(cache, cache->size, fp);
+ totalsize += cache->size;
+ } //end for
+ } //end for
+ for (i = 0; i < aasworld.numclusters; i++)
+ {
+ cluster = &aasworld.clusters[i];
+ for (j = 0; j < cluster->numareas; j++)
+ {
+ for (cache = aasworld.clusterareacache[i][j]; cache; cache = cache->next)
+ {
+ botimport.FS_Write(cache, cache->size, fp);
+ totalsize += cache->size;
+ } //end for
+ } //end for
+ } //end for
+ // write the visareas
+ /*
+ for (i = 0; i < aasworld.numareas; i++)
+ {
+ if (!aasworld.areavisibility[i]) {
+ size = 0;
+ botimport.FS_Write(&size, sizeof(int), fp);
+ continue;
+ }
+ AAS_DecompressVis( aasworld.areavisibility[i], aasworld.numareas, aasworld.decompressedvis );
+ size = AAS_CompressVis( aasworld.decompressedvis, aasworld.numareas, aasworld.decompressedvis );
+ botimport.FS_Write(&size, sizeof(int), fp);
+ botimport.FS_Write(aasworld.decompressedvis, size, fp);
+ }
+ */
+ //
+ botimport.FS_FCloseFile(fp);
+ botimport.Print(PRT_MESSAGE, "\nroute cache written to %s\n", filename);
+ botimport.Print(PRT_MESSAGE, "written %d bytes of routing cache\n", totalsize);
+} //end of the function AAS_WriteRouteCache
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+aas_routingcache_t *AAS_ReadCache(fileHandle_t fp)
+{
+ int size;
+ aas_routingcache_t *cache;
+
+ botimport.FS_Read(&size, sizeof(size), fp);
+ cache = (aas_routingcache_t *) GetMemory(size);
+ cache->size = size;
+ botimport.FS_Read((unsigned char *)cache + sizeof(size), size - sizeof(size), fp);
+ cache->reachabilities = (unsigned char *) cache + sizeof(aas_routingcache_t) - sizeof(unsigned short) +
+ (size - sizeof(aas_routingcache_t) + sizeof(unsigned short)) / 3 * 2;
+ return cache;
+} //end of the function AAS_ReadCache
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_ReadRouteCache(void)
+{
+ int i, clusterareanum;//, size;
+ fileHandle_t fp;
+ char filename[MAX_QPATH];
+ routecacheheader_t routecacheheader;
+ aas_routingcache_t *cache;
+
+ Com_sprintf(filename, MAX_QPATH, "maps/%s.rcd", aasworld.mapname);
+ botimport.FS_FOpenFile( filename, &fp, FS_READ );
+ if (!fp)
+ {
+ return qfalse;
+ } //end if
+ botimport.FS_Read(&routecacheheader, sizeof(routecacheheader_t), fp );
+ if (routecacheheader.ident != RCID)
+ {
+ AAS_Error("%s is not a route cache dump\n");
+ return qfalse;
+ } //end if
+ if (routecacheheader.version != RCVERSION)
+ {
+ AAS_Error("route cache dump has wrong version %d, should be %d", routecacheheader.version, RCVERSION);
+ return qfalse;
+ } //end if
+ if (routecacheheader.numareas != aasworld.numareas)
+ {
+ //AAS_Error("route cache dump has wrong number of areas\n");
+ return qfalse;
+ } //end if
+ if (routecacheheader.numclusters != aasworld.numclusters)
+ {
+ //AAS_Error("route cache dump has wrong number of clusters\n");
+ return qfalse;
+ } //end if
+ if (routecacheheader.areacrc !=
+ CRC_ProcessString( (unsigned char *)aasworld.areas, sizeof(aas_area_t) * aasworld.numareas ))
+ {
+ //AAS_Error("route cache dump area CRC incorrect\n");
+ return qfalse;
+ } //end if
+ if (routecacheheader.clustercrc !=
+ CRC_ProcessString( (unsigned char *)aasworld.clusters, sizeof(aas_cluster_t) * aasworld.numclusters ))
+ {
+ //AAS_Error("route cache dump cluster CRC incorrect\n");
+ return qfalse;
+ } //end if
+ //read all the portal cache
+ for (i = 0; i < routecacheheader.numportalcache; i++)
+ {
+ cache = AAS_ReadCache(fp);
+ cache->next = aasworld.portalcache[cache->areanum];
+ cache->prev = NULL;
+ if (aasworld.portalcache[cache->areanum])
+ aasworld.portalcache[cache->areanum]->prev = cache;
+ aasworld.portalcache[cache->areanum] = cache;
+ } //end for
+ //read all the cluster area cache
+ for (i = 0; i < routecacheheader.numareacache; i++)
+ {
+ cache = AAS_ReadCache(fp);
+ clusterareanum = AAS_ClusterAreaNum(cache->cluster, cache->areanum);
+ cache->next = aasworld.clusterareacache[cache->cluster][clusterareanum];
+ cache->prev = NULL;
+ if (aasworld.clusterareacache[cache->cluster][clusterareanum])
+ aasworld.clusterareacache[cache->cluster][clusterareanum]->prev = cache;
+ aasworld.clusterareacache[cache->cluster][clusterareanum] = cache;
+ } //end for
+ // read the visareas
+ /*
+ aasworld.areavisibility = (byte **) GetClearedMemory(aasworld.numareas * sizeof(byte *));
+ aasworld.decompressedvis = (byte *) GetClearedMemory(aasworld.numareas * sizeof(byte));
+ for (i = 0; i < aasworld.numareas; i++)
+ {
+ botimport.FS_Read(&size, sizeof(size), fp );
+ if (size) {
+ aasworld.areavisibility[i] = (byte *) GetMemory(size);
+ botimport.FS_Read(aasworld.areavisibility[i], size, fp );
+ }
+ }
+ */
+ //
+ botimport.FS_FCloseFile(fp);
+ return qtrue;
+} //end of the function AAS_ReadRouteCache
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+#define MAX_REACHABILITYPASSAREAS 32
+
+void AAS_InitReachabilityAreas(void)
+{
+ int i, j, numareas, areas[MAX_REACHABILITYPASSAREAS];
+ int numreachareas;
+ aas_reachability_t *reach;
+ vec3_t start, end;
+
+ if (aasworld.reachabilityareas)
+ FreeMemory(aasworld.reachabilityareas);
+ if (aasworld.reachabilityareaindex)
+ FreeMemory(aasworld.reachabilityareaindex);
+
+ aasworld.reachabilityareas = (aas_reachabilityareas_t *)
+ GetClearedMemory(aasworld.reachabilitysize * sizeof(aas_reachabilityareas_t));
+ aasworld.reachabilityareaindex = (int *)
+ GetClearedMemory(aasworld.reachabilitysize * MAX_REACHABILITYPASSAREAS * sizeof(int));
+ numreachareas = 0;
+ for (i = 0; i < aasworld.reachabilitysize; i++)
+ {
+ reach = &aasworld.reachability[i];
+ numareas = 0;
+ switch(reach->traveltype & TRAVELTYPE_MASK)
+ {
+ //trace areas from start to end
+ case TRAVEL_BARRIERJUMP:
+ case TRAVEL_WATERJUMP:
+ VectorCopy(reach->start, end);
+ end[2] = reach->end[2];
+ numareas = AAS_TraceAreas(reach->start, end, areas, NULL, MAX_REACHABILITYPASSAREAS);
+ break;
+ case TRAVEL_WALKOFFLEDGE:
+ VectorCopy(reach->end, start);
+ start[2] = reach->start[2];
+ numareas = AAS_TraceAreas(start, reach->end, areas, NULL, MAX_REACHABILITYPASSAREAS);
+ break;
+ case TRAVEL_GRAPPLEHOOK:
+ numareas = AAS_TraceAreas(reach->start, reach->end, areas, NULL, MAX_REACHABILITYPASSAREAS);
+ break;
+
+ //trace arch
+ case TRAVEL_JUMP: break;
+ case TRAVEL_ROCKETJUMP: break;
+ case TRAVEL_BFGJUMP: break;
+ case TRAVEL_JUMPPAD: break;
+
+ //trace from reach->start to entity center, along entity movement
+ //and from entity center to reach->end
+ case TRAVEL_ELEVATOR: break;
+ case TRAVEL_FUNCBOB: break;
+
+ //no areas in between
+ case TRAVEL_WALK: break;
+ case TRAVEL_CROUCH: break;
+ case TRAVEL_LADDER: break;
+ case TRAVEL_SWIM: break;
+ case TRAVEL_TELEPORT: break;
+ default: break;
+ } //end switch
+ aasworld.reachabilityareas[i].firstarea = numreachareas;
+ aasworld.reachabilityareas[i].numareas = numareas;
+ for (j = 0; j < numareas; j++)
+ {
+ aasworld.reachabilityareaindex[numreachareas++] = areas[j];
+ } //end for
+ } //end for
+} //end of the function AAS_InitReachabilityAreas
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_InitRouting(void)
+{
+ AAS_InitTravelFlagFromType();
+ //
+ AAS_InitAreaContentsTravelFlags();
+ //initialize the routing update fields
+ AAS_InitRoutingUpdate();
+ //create reversed reachability links used by the routing update algorithm
+ AAS_CreateReversedReachability();
+ //initialize the cluster cache
+ AAS_InitClusterAreaCache();
+ //initialize portal cache
+ AAS_InitPortalCache();
+ //initialize the area travel times
+ AAS_CalculateAreaTravelTimes();
+ //calculate the maximum travel times through portals
+ AAS_InitPortalMaxTravelTimes();
+ //get the areas reachabilities go through
+ AAS_InitReachabilityAreas();
+ //
+#ifdef ROUTING_DEBUG
+ numareacacheupdates = 0;
+ numportalcacheupdates = 0;
+#endif //ROUTING_DEBUG
+ //
+ routingcachesize = 0;
+ max_routingcachesize = 1024 * (int) LibVarValue("max_routingcache", "4096");
+ // read any routing cache if available
+ AAS_ReadRouteCache();
+} //end of the function AAS_InitRouting
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_FreeRoutingCaches(void)
+{
+ // free all the existing cluster area cache
+ AAS_FreeAllClusterAreaCache();
+ // free all the existing portal cache
+ AAS_FreeAllPortalCache();
+ // free cached travel times within areas
+ if (aasworld.areatraveltimes) FreeMemory(aasworld.areatraveltimes);
+ aasworld.areatraveltimes = NULL;
+ // free cached maximum travel time through cluster portals
+ if (aasworld.portalmaxtraveltimes) FreeMemory(aasworld.portalmaxtraveltimes);
+ aasworld.portalmaxtraveltimes = NULL;
+ // free reversed reachability links
+ if (aasworld.reversedreachability) FreeMemory(aasworld.reversedreachability);
+ aasworld.reversedreachability = NULL;
+ // free routing algorithm memory
+ if (aasworld.areaupdate) FreeMemory(aasworld.areaupdate);
+ aasworld.areaupdate = NULL;
+ if (aasworld.portalupdate) FreeMemory(aasworld.portalupdate);
+ aasworld.portalupdate = NULL;
+ // free lists with areas the reachabilities go through
+ if (aasworld.reachabilityareas) FreeMemory(aasworld.reachabilityareas);
+ aasworld.reachabilityareas = NULL;
+ // free the reachability area index
+ if (aasworld.reachabilityareaindex) FreeMemory(aasworld.reachabilityareaindex);
+ aasworld.reachabilityareaindex = NULL;
+ // free area contents travel flags look up table
+ if (aasworld.areacontentstravelflags) FreeMemory(aasworld.areacontentstravelflags);
+ aasworld.areacontentstravelflags = NULL;
+} //end of the function AAS_FreeRoutingCaches
+//===========================================================================
+// update the given routing cache
+//
+// Parameter: areacache : routing cache to update
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_UpdateAreaRoutingCache(aas_routingcache_t *areacache)
+{
+ int i, nextareanum, cluster, badtravelflags, clusterareanum, linknum;
+ int numreachabilityareas;
+ unsigned short int t, startareatraveltimes[128]; //NOTE: not more than 128 reachabilities per area allowed
+ aas_routingupdate_t *updateliststart, *updatelistend, *curupdate, *nextupdate;
+ aas_reachability_t *reach;
+ aas_reversedreachability_t *revreach;
+ aas_reversedlink_t *revlink;
+
+#ifdef ROUTING_DEBUG
+ numareacacheupdates++;
+#endif //ROUTING_DEBUG
+ //number of reachability areas within this cluster
+ numreachabilityareas = aasworld.clusters[areacache->cluster].numreachabilityareas;
+ //
+ aasworld.frameroutingupdates++;
+ //clear the routing update fields
+// Com_Memset(aasworld.areaupdate, 0, aasworld.numareas * sizeof(aas_routingupdate_t));
+ //
+ badtravelflags = ~areacache->travelflags;
+ //
+ clusterareanum = AAS_ClusterAreaNum(areacache->cluster, areacache->areanum);
+ if (clusterareanum >= numreachabilityareas) return;
+ //
+ Com_Memset(startareatraveltimes, 0, sizeof(startareatraveltimes));
+ //
+ curupdate = &aasworld.areaupdate[clusterareanum];
+ curupdate->areanum = areacache->areanum;
+ //VectorCopy(areacache->origin, curupdate->start);
+ curupdate->areatraveltimes = startareatraveltimes;
+ curupdate->tmptraveltime = areacache->starttraveltime;
+ //
+ areacache->traveltimes[clusterareanum] = areacache->starttraveltime;
+ //put the area to start with in the current read list
+ curupdate->next = NULL;
+ curupdate->prev = NULL;
+ updateliststart = curupdate;
+ updatelistend = curupdate;
+ //while there are updates in the current list
+ while (updateliststart)
+ {
+ curupdate = updateliststart;
+ //
+ if (curupdate->next) curupdate->next->prev = NULL;
+ else updatelistend = NULL;
+ updateliststart = curupdate->next;
+ //
+ curupdate->inlist = qfalse;
+ //check all reversed reachability links
+ revreach = &aasworld.reversedreachability[curupdate->areanum];
+ //
+ for (i = 0, revlink = revreach->first; revlink; revlink = revlink->next, i++)
+ {
+ linknum = revlink->linknum;
+ reach = &aasworld.reachability[linknum];
+ //if there is used an undesired travel type
+ if (AAS_TravelFlagForType_inline(reach->traveltype) & badtravelflags) continue;
+ //if not allowed to enter the next area
+ if (aasworld.areasettings[reach->areanum].areaflags & AREA_DISABLED) continue;
+ //if the next area has a not allowed travel flag
+ if (AAS_AreaContentsTravelFlags_inline(reach->areanum) & badtravelflags) continue;
+ //number of the area the reversed reachability leads to
+ nextareanum = revlink->areanum;
+ //get the cluster number of the area
+ cluster = aasworld.areasettings[nextareanum].cluster;
+ //don't leave the cluster
+ if (cluster > 0 && cluster != areacache->cluster) continue;
+ //get the number of the area in the cluster
+ clusterareanum = AAS_ClusterAreaNum(areacache->cluster, nextareanum);
+ if (clusterareanum >= numreachabilityareas) continue;
+ //time already travelled plus the traveltime through
+ //the current area plus the travel time from the reachability
+ t = curupdate->tmptraveltime +
+ //AAS_AreaTravelTime(curupdate->areanum, curupdate->start, reach->end) +
+ curupdate->areatraveltimes[i] +
+ reach->traveltime;
+ //
+ if (!areacache->traveltimes[clusterareanum] ||
+ areacache->traveltimes[clusterareanum] > t)
+ {
+ areacache->traveltimes[clusterareanum] = t;
+ areacache->reachabilities[clusterareanum] = linknum - aasworld.areasettings[nextareanum].firstreachablearea;
+ nextupdate = &aasworld.areaupdate[clusterareanum];
+ nextupdate->areanum = nextareanum;
+ nextupdate->tmptraveltime = t;
+ //VectorCopy(reach->start, nextupdate->start);
+ nextupdate->areatraveltimes = aasworld.areatraveltimes[nextareanum][linknum -
+ aasworld.areasettings[nextareanum].firstreachablearea];
+ if (!nextupdate->inlist)
+ {
+ // we add the update to the end of the list
+ // we could also use a B+ tree to have a real sorted list
+ // on travel time which makes for faster routing updates
+ nextupdate->next = NULL;
+ nextupdate->prev = updatelistend;
+ if (updatelistend) updatelistend->next = nextupdate;
+ else updateliststart = nextupdate;
+ updatelistend = nextupdate;
+ nextupdate->inlist = qtrue;
+ } //end if
+ } //end if
+ } //end for
+ } //end while
+} //end of the function AAS_UpdateAreaRoutingCache
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+aas_routingcache_t *AAS_GetAreaRoutingCache(int clusternum, int areanum, int travelflags)
+{
+ int clusterareanum;
+ aas_routingcache_t *cache, *clustercache;
+
+ //number of the area in the cluster
+ clusterareanum = AAS_ClusterAreaNum(clusternum, areanum);
+ //pointer to the cache for the area in the cluster
+ clustercache = aasworld.clusterareacache[clusternum][clusterareanum];
+ //find the cache without undesired travel flags
+ for (cache = clustercache; cache; cache = cache->next)
+ {
+ //if there aren't used any undesired travel types for the cache
+ if (cache->travelflags == travelflags) break;
+ } //end for
+ //if there was no cache
+ if (!cache)
+ {
+ cache = AAS_AllocRoutingCache(aasworld.clusters[clusternum].numreachabilityareas);
+ cache->cluster = clusternum;
+ cache->areanum = areanum;
+ VectorCopy(aasworld.areas[areanum].center, cache->origin);
+ cache->starttraveltime = 1;
+ cache->travelflags = travelflags;
+ cache->prev = NULL;
+ cache->next = clustercache;
+ if (clustercache) clustercache->prev = cache;
+ aasworld.clusterareacache[clusternum][clusterareanum] = cache;
+ AAS_UpdateAreaRoutingCache(cache);
+ } //end if
+ else
+ {
+ AAS_UnlinkCache(cache);
+ } //end else
+ //the cache has been accessed
+ cache->time = AAS_RoutingTime();
+ cache->type = CACHETYPE_AREA;
+ AAS_LinkCache(cache);
+ return cache;
+} //end of the function AAS_GetAreaRoutingCache
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_UpdatePortalRoutingCache(aas_routingcache_t *portalcache)
+{
+ int i, portalnum, clusterareanum, clusternum;
+ unsigned short int t;
+ aas_portal_t *portal;
+ aas_cluster_t *cluster;
+ aas_routingcache_t *cache;
+ aas_routingupdate_t *updateliststart, *updatelistend, *curupdate, *nextupdate;
+
+#ifdef ROUTING_DEBUG
+ numportalcacheupdates++;
+#endif //ROUTING_DEBUG
+ //clear the routing update fields
+// Com_Memset(aasworld.portalupdate, 0, (aasworld.numportals+1) * sizeof(aas_routingupdate_t));
+ //
+ curupdate = &aasworld.portalupdate[aasworld.numportals];
+ curupdate->cluster = portalcache->cluster;
+ curupdate->areanum = portalcache->areanum;
+ curupdate->tmptraveltime = portalcache->starttraveltime;
+ //if the start area is a cluster portal, store the travel time for that portal
+ clusternum = aasworld.areasettings[portalcache->areanum].cluster;
+ if (clusternum < 0)
+ {
+ portalcache->traveltimes[-clusternum] = portalcache->starttraveltime;
+ } //end if
+ //put the area to start with in the current read list
+ curupdate->next = NULL;
+ curupdate->prev = NULL;
+ updateliststart = curupdate;
+ updatelistend = curupdate;
+ //while there are updates in the current list
+ while (updateliststart)
+ {
+ curupdate = updateliststart;
+ //remove the current update from the list
+ if (curupdate->next) curupdate->next->prev = NULL;
+ else updatelistend = NULL;
+ updateliststart = curupdate->next;
+ //current update is removed from the list
+ curupdate->inlist = qfalse;
+ //
+ cluster = &aasworld.clusters[curupdate->cluster];
+ //
+ cache = AAS_GetAreaRoutingCache(curupdate->cluster,
+ curupdate->areanum, portalcache->travelflags);
+ //take all portals of the cluster
+ for (i = 0; i < cluster->numportals; i++)
+ {
+ portalnum = aasworld.portalindex[cluster->firstportal + i];
+ portal = &aasworld.portals[portalnum];
+ //if this is the portal of the current update continue
+ if (portal->areanum == curupdate->areanum) continue;
+ //
+ clusterareanum = AAS_ClusterAreaNum(curupdate->cluster, portal->areanum);
+ if (clusterareanum >= cluster->numreachabilityareas) continue;
+ //
+ t = cache->traveltimes[clusterareanum];
+ if (!t) continue;
+ t += curupdate->tmptraveltime;
+ //
+ if (!portalcache->traveltimes[portalnum] ||
+ portalcache->traveltimes[portalnum] > t)
+ {
+ portalcache->traveltimes[portalnum] = t;
+ nextupdate = &aasworld.portalupdate[portalnum];
+ if (portal->frontcluster == curupdate->cluster)
+ {
+ nextupdate->cluster = portal->backcluster;
+ } //end if
+ else
+ {
+ nextupdate->cluster = portal->frontcluster;
+ } //end else
+ nextupdate->areanum = portal->areanum;
+ //add travel time through the actual portal area for the next update
+ nextupdate->tmptraveltime = t + aasworld.portalmaxtraveltimes[portalnum];
+ if (!nextupdate->inlist)
+ {
+ // we add the update to the end of the list
+ // we could also use a B+ tree to have a real sorted list
+ // on travel time which makes for faster routing updates
+ nextupdate->next = NULL;
+ nextupdate->prev = updatelistend;
+ if (updatelistend) updatelistend->next = nextupdate;
+ else updateliststart = nextupdate;
+ updatelistend = nextupdate;
+ nextupdate->inlist = qtrue;
+ } //end if
+ } //end if
+ } //end for
+ } //end while
+} //end of the function AAS_UpdatePortalRoutingCache
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+aas_routingcache_t *AAS_GetPortalRoutingCache(int clusternum, int areanum, int travelflags)
+{
+ aas_routingcache_t *cache;
+
+ //find the cached portal routing if existing
+ for (cache = aasworld.portalcache[areanum]; cache; cache = cache->next)
+ {
+ if (cache->travelflags == travelflags) break;
+ } //end for
+ //if the portal routing isn't cached
+ if (!cache)
+ {
+ cache = AAS_AllocRoutingCache(aasworld.numportals);
+ cache->cluster = clusternum;
+ cache->areanum = areanum;
+ VectorCopy(aasworld.areas[areanum].center, cache->origin);
+ cache->starttraveltime = 1;
+ cache->travelflags = travelflags;
+ //add the cache to the cache list
+ cache->prev = NULL;
+ cache->next = aasworld.portalcache[areanum];
+ if (aasworld.portalcache[areanum]) aasworld.portalcache[areanum]->prev = cache;
+ aasworld.portalcache[areanum] = cache;
+ //update the cache
+ AAS_UpdatePortalRoutingCache(cache);
+ } //end if
+ else
+ {
+ AAS_UnlinkCache(cache);
+ } //end else
+ //the cache has been accessed
+ cache->time = AAS_RoutingTime();
+ cache->type = CACHETYPE_PORTAL;
+ AAS_LinkCache(cache);
+ return cache;
+} //end of the function AAS_GetPortalRoutingCache
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_AreaRouteToGoalArea(int areanum, vec3_t origin, int goalareanum, int travelflags, int *traveltime, int *reachnum)
+{
+ int clusternum, goalclusternum, portalnum, i, clusterareanum, bestreachnum;
+ unsigned short int t, besttime;
+ aas_portal_t *portal;
+ aas_cluster_t *cluster;
+ aas_routingcache_t *areacache, *portalcache;
+ aas_reachability_t *reach;
+
+ if (!aasworld.initialized) return qfalse;
+
+ if (areanum == goalareanum)
+ {
+ *traveltime = 1;
+ *reachnum = 0;
+ return qtrue;
+ }
+ //
+ if (areanum <= 0 || areanum >= aasworld.numareas)
+ {
+ if (bot_developer)
+ {
+ botimport.Print(PRT_ERROR, "AAS_AreaTravelTimeToGoalArea: areanum %d out of range\n", areanum);
+ } //end if
+ return qfalse;
+ } //end if
+ if (goalareanum <= 0 || goalareanum >= aasworld.numareas)
+ {
+ if (bot_developer)
+ {
+ botimport.Print(PRT_ERROR, "AAS_AreaTravelTimeToGoalArea: goalareanum %d out of range\n", goalareanum);
+ } //end if
+ return qfalse;
+ } //end if
+ // make sure the routing cache doesn't grow to large
+ while(AvailableMemory() < 1 * 1024 * 1024) {
+ if (!AAS_FreeOldestCache()) break;
+ }
+ //
+ if (AAS_AreaDoNotEnter(areanum) || AAS_AreaDoNotEnter(goalareanum))
+ {
+ travelflags |= TFL_DONOTENTER;
+ } //end if
+ //NOTE: the number of routing updates is limited per frame
+ /*
+ if (aasworld.frameroutingupdates > MAX_FRAMEROUTINGUPDATES)
+ {
+#ifdef DEBUG
+ //Log_Write("WARNING: AAS_AreaTravelTimeToGoalArea: frame routing updates overflowed");
+#endif
+ return 0;
+ } //end if
+ */
+ //
+ clusternum = aasworld.areasettings[areanum].cluster;
+ goalclusternum = aasworld.areasettings[goalareanum].cluster;
+ //check if the area is a portal of the goal area cluster
+ if (clusternum < 0 && goalclusternum > 0)
+ {
+ portal = &aasworld.portals[-clusternum];
+ if (portal->frontcluster == goalclusternum ||
+ portal->backcluster == goalclusternum)
+ {
+ clusternum = goalclusternum;
+ } //end if
+ } //end if
+ //check if the goalarea is a portal of the area cluster
+ else if (clusternum > 0 && goalclusternum < 0)
+ {
+ portal = &aasworld.portals[-goalclusternum];
+ if (portal->frontcluster == clusternum ||
+ portal->backcluster == clusternum)
+ {
+ goalclusternum = clusternum;
+ } //end if
+ } //end if
+ //if both areas are in the same cluster
+ //NOTE: there might be a shorter route via another cluster!!! but we don't care
+ if (clusternum > 0 && goalclusternum > 0 && clusternum == goalclusternum)
+ {
+ //
+ areacache = AAS_GetAreaRoutingCache(clusternum, goalareanum, travelflags);
+ //the number of the area in the cluster
+ clusterareanum = AAS_ClusterAreaNum(clusternum, areanum);
+ //the cluster the area is in
+ cluster = &aasworld.clusters[clusternum];
+ //if the area is NOT a reachability area
+ if (clusterareanum >= cluster->numreachabilityareas) return 0;
+ //if it is possible to travel to the goal area through this cluster
+ if (areacache->traveltimes[clusterareanum] != 0)
+ {
+ *reachnum = aasworld.areasettings[areanum].firstreachablearea +
+ areacache->reachabilities[clusterareanum];
+ if (!origin) {
+ *traveltime = areacache->traveltimes[clusterareanum];
+ return qtrue;
+ }
+ reach = &aasworld.reachability[*reachnum];
+ *traveltime = areacache->traveltimes[clusterareanum] +
+ AAS_AreaTravelTime(areanum, origin, reach->start);
+ //
+ return qtrue;
+ } //end if
+ } //end if
+ //
+ clusternum = aasworld.areasettings[areanum].cluster;
+ goalclusternum = aasworld.areasettings[goalareanum].cluster;
+ //if the goal area is a portal
+ if (goalclusternum < 0)
+ {
+ //just assume the goal area is part of the front cluster
+ portal = &aasworld.portals[-goalclusternum];
+ goalclusternum = portal->frontcluster;
+ } //end if
+ //get the portal routing cache
+ portalcache = AAS_GetPortalRoutingCache(goalclusternum, goalareanum, travelflags);
+ //if the area is a cluster portal, read directly from the portal cache
+ if (clusternum < 0)
+ {
+ *traveltime = portalcache->traveltimes[-clusternum];
+ *reachnum = aasworld.areasettings[areanum].firstreachablearea +
+ portalcache->reachabilities[-clusternum];
+ return qtrue;
+ } //end if
+ //
+ besttime = 0;
+ bestreachnum = -1;
+ //the cluster the area is in
+ cluster = &aasworld.clusters[clusternum];
+ //find the portal of the area cluster leading towards the goal area
+ for (i = 0; i < cluster->numportals; i++)
+ {
+ portalnum = aasworld.portalindex[cluster->firstportal + i];
+ //if the goal area isn't reachable from the portal
+ if (!portalcache->traveltimes[portalnum]) continue;
+ //
+ portal = &aasworld.portals[portalnum];
+ //get the cache of the portal area
+ areacache = AAS_GetAreaRoutingCache(clusternum, portal->areanum, travelflags);
+ //current area inside the current cluster
+ clusterareanum = AAS_ClusterAreaNum(clusternum, areanum);
+ //if the area is NOT a reachability area
+ if (clusterareanum >= cluster->numreachabilityareas) continue;
+ //if the portal is NOT reachable from this area
+ if (!areacache->traveltimes[clusterareanum]) continue;
+ //total travel time is the travel time the portal area is from
+ //the goal area plus the travel time towards the portal area
+ t = portalcache->traveltimes[portalnum] + areacache->traveltimes[clusterareanum];
+ //FIXME: add the exact travel time through the actual portal area
+ //NOTE: for now we just add the largest travel time through the portal area
+ // because we can't directly calculate the exact travel time
+ // to be more specific we don't know which reachability was used to travel
+ // into the portal area
+ t += aasworld.portalmaxtraveltimes[portalnum];
+ //
+ if (origin)
+ {
+ *reachnum = aasworld.areasettings[areanum].firstreachablearea +
+ areacache->reachabilities[clusterareanum];
+ reach = aasworld.reachability + *reachnum;
+ t += AAS_AreaTravelTime(areanum, origin, reach->start);
+ } //end if
+ //if the time is better than the one already found
+ if (!besttime || t < besttime)
+ {
+ bestreachnum = *reachnum;
+ besttime = t;
+ } //end if
+ } //end for
+ if (bestreachnum < 0) {
+ return qfalse;
+ }
+ *reachnum = bestreachnum;
+ *traveltime = besttime;
+ return qtrue;
+} //end of the function AAS_AreaRouteToGoalArea
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_AreaTravelTimeToGoalArea(int areanum, vec3_t origin, int goalareanum, int travelflags)
+{
+ int traveltime, reachnum;
+
+ if (AAS_AreaRouteToGoalArea(areanum, origin, goalareanum, travelflags, &traveltime, &reachnum))
+ {
+ return traveltime;
+ }
+ return 0;
+} //end of the function AAS_AreaTravelTimeToGoalArea
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_AreaReachabilityToGoalArea(int areanum, vec3_t origin, int goalareanum, int travelflags)
+{
+ int traveltime, reachnum;
+
+ if (AAS_AreaRouteToGoalArea(areanum, origin, goalareanum, travelflags, &traveltime, &reachnum))
+ {
+ return reachnum;
+ }
+ return 0;
+} //end of the function AAS_AreaReachabilityToGoalArea
+//===========================================================================
+// predict the route and stop on one of the stop events
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_PredictRoute(struct aas_predictroute_s *route, int areanum, vec3_t origin,
+ int goalareanum, int travelflags, int maxareas, int maxtime,
+ int stopevent, int stopcontents, int stoptfl, int stopareanum)
+{
+ int curareanum, reachnum, i, j, testareanum;
+ vec3_t curorigin;
+ aas_reachability_t *reach;
+ aas_reachabilityareas_t *reachareas;
+
+ //init output
+ route->stopevent = RSE_NONE;
+ route->endarea = goalareanum;
+ route->endcontents = 0;
+ route->endtravelflags = 0;
+ VectorCopy(origin, route->endpos);
+ route->time = 0;
+
+ curareanum = areanum;
+ VectorCopy(origin, curorigin);
+
+ for (i = 0; curareanum != goalareanum && (!maxareas || i < maxareas) && i < aasworld.numareas; i++)
+ {
+ reachnum = AAS_AreaReachabilityToGoalArea(curareanum, curorigin, goalareanum, travelflags);
+ if (!reachnum)
+ {
+ route->stopevent = RSE_NOROUTE;
+ return qfalse;
+ } //end if
+ reach = &aasworld.reachability[reachnum];
+ //
+ if (stopevent & RSE_USETRAVELTYPE)
+ {
+ if (AAS_TravelFlagForType_inline(reach->traveltype) & stoptfl)
+ {
+ route->stopevent = RSE_USETRAVELTYPE;
+ route->endarea = curareanum;
+ route->endcontents = aasworld.areasettings[curareanum].contents;
+ route->endtravelflags = AAS_TravelFlagForType_inline(reach->traveltype);
+ VectorCopy(reach->start, route->endpos);
+ return qtrue;
+ } //end if
+ if (AAS_AreaContentsTravelFlags_inline(reach->areanum) & stoptfl)
+ {
+ route->stopevent = RSE_USETRAVELTYPE;
+ route->endarea = reach->areanum;
+ route->endcontents = aasworld.areasettings[reach->areanum].contents;
+ route->endtravelflags = AAS_AreaContentsTravelFlags_inline(reach->areanum);
+ VectorCopy(reach->end, route->endpos);
+ route->time += AAS_AreaTravelTime(areanum, origin, reach->start);
+ route->time += reach->traveltime;
+ return qtrue;
+ } //end if
+ } //end if
+ reachareas = &aasworld.reachabilityareas[reachnum];
+ for (j = 0; j < reachareas->numareas + 1; j++)
+ {
+ if (j >= reachareas->numareas)
+ testareanum = reach->areanum;
+ else
+ testareanum = aasworld.reachabilityareaindex[reachareas->firstarea + j];
+ if (stopevent & RSE_ENTERCONTENTS)
+ {
+ if (aasworld.areasettings[testareanum].contents & stopcontents)
+ {
+ route->stopevent = RSE_ENTERCONTENTS;
+ route->endarea = testareanum;
+ route->endcontents = aasworld.areasettings[testareanum].contents;
+ VectorCopy(reach->end, route->endpos);
+ route->time += AAS_AreaTravelTime(areanum, origin, reach->start);
+ route->time += reach->traveltime;
+ return qtrue;
+ } //end if
+ } //end if
+ if (stopevent & RSE_ENTERAREA)
+ {
+ if (testareanum == stopareanum)
+ {
+ route->stopevent = RSE_ENTERAREA;
+ route->endarea = testareanum;
+ route->endcontents = aasworld.areasettings[testareanum].contents;
+ VectorCopy(reach->start, route->endpos);
+ return qtrue;
+ } //end if
+ } //end if
+ } //end for
+
+ route->time += AAS_AreaTravelTime(areanum, origin, reach->start);
+ route->time += reach->traveltime;
+ route->endarea = reach->areanum;
+ route->endcontents = aasworld.areasettings[reach->areanum].contents;
+ route->endtravelflags = AAS_TravelFlagForType_inline(reach->traveltype);
+ VectorCopy(reach->end, route->endpos);
+ //
+ curareanum = reach->areanum;
+ VectorCopy(reach->end, curorigin);
+ //
+ if (maxtime && route->time > maxtime)
+ break;
+ } //end while
+ if (curareanum != goalareanum)
+ return qfalse;
+ return qtrue;
+} //end of the function AAS_PredictRoute
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_BridgeWalkable(int areanum)
+{
+ return qfalse;
+} //end of the function AAS_BridgeWalkable
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ReachabilityFromNum(int num, struct aas_reachability_s *reach)
+{
+ if (!aasworld.initialized)
+ {
+ Com_Memset(reach, 0, sizeof(aas_reachability_t));
+ return;
+ } //end if
+ if (num < 0 || num >= aasworld.reachabilitysize)
+ {
+ Com_Memset(reach, 0, sizeof(aas_reachability_t));
+ return;
+ } //end if
+ Com_Memcpy(reach, &aasworld.reachability[num], sizeof(aas_reachability_t));;
+} //end of the function AAS_ReachabilityFromNum
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_NextAreaReachability(int areanum, int reachnum)
+{
+ aas_areasettings_t *settings;
+
+ if (!aasworld.initialized) return 0;
+
+ if (areanum <= 0 || areanum >= aasworld.numareas)
+ {
+ botimport.Print(PRT_ERROR, "AAS_NextAreaReachability: areanum %d out of range\n", areanum);
+ return 0;
+ } //end if
+
+ settings = &aasworld.areasettings[areanum];
+ if (!reachnum)
+ {
+ return settings->firstreachablearea;
+ } //end if
+ if (reachnum < settings->firstreachablearea)
+ {
+ botimport.Print(PRT_FATAL, "AAS_NextAreaReachability: reachnum < settings->firstreachableara");
+ return 0;
+ } //end if
+ reachnum++;
+ if (reachnum >= settings->firstreachablearea + settings->numreachableareas)
+ {
+ return 0;
+ } //end if
+ return reachnum;
+} //end of the function AAS_NextAreaReachability
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_NextModelReachability(int num, int modelnum)
+{
+ int i;
+
+ if (num <= 0) num = 1;
+ else if (num >= aasworld.reachabilitysize) return 0;
+ else num++;
+ //
+ for (i = num; i < aasworld.reachabilitysize; i++)
+ {
+ if ((aasworld.reachability[i].traveltype & TRAVELTYPE_MASK) == TRAVEL_ELEVATOR)
+ {
+ if (aasworld.reachability[i].facenum == modelnum) return i;
+ } //end if
+ else if ((aasworld.reachability[i].traveltype & TRAVELTYPE_MASK) == TRAVEL_FUNCBOB)
+ {
+ if ((aasworld.reachability[i].facenum & 0x0000FFFF) == modelnum) return i;
+ } //end if
+ } //end for
+ return 0;
+} //end of the function AAS_NextModelReachability
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_RandomGoalArea(int areanum, int travelflags, int *goalareanum, vec3_t goalorigin)
+{
+ int i, n, t;
+ vec3_t start, end;
+ aas_trace_t trace;
+
+ //if the area has no reachabilities
+ if (!AAS_AreaReachability(areanum)) return qfalse;
+ //
+ n = aasworld.numareas * random();
+ for (i = 0; i < aasworld.numareas; i++)
+ {
+ if (n <= 0) n = 1;
+ if (n >= aasworld.numareas) n = 1;
+ if (AAS_AreaReachability(n))
+ {
+ t = AAS_AreaTravelTimeToGoalArea(areanum, aasworld.areas[areanum].center, n, travelflags);
+ //if the goal is reachable
+ if (t > 0)
+ {
+ if (AAS_AreaSwim(n))
+ {
+ *goalareanum = n;
+ VectorCopy(aasworld.areas[n].center, goalorigin);
+ //botimport.Print(PRT_MESSAGE, "found random goal area %d\n", *goalareanum);
+ return qtrue;
+ } //end if
+ VectorCopy(aasworld.areas[n].center, start);
+ if (!AAS_PointAreaNum(start))
+ Log_Write("area %d center %f %f %f in solid?", n, start[0], start[1], start[2]);
+ VectorCopy(start, end);
+ end[2] -= 300;
+ trace = AAS_TraceClientBBox(start, end, PRESENCE_CROUCH, -1);
+ if (!trace.startsolid && trace.fraction < 1 && AAS_PointAreaNum(trace.endpos) == n)
+ {
+ if (AAS_AreaGroundFaceArea(n) > 300)
+ {
+ *goalareanum = n;
+ VectorCopy(trace.endpos, goalorigin);
+ //botimport.Print(PRT_MESSAGE, "found random goal area %d\n", *goalareanum);
+ return qtrue;
+ } //end if
+ } //end if
+ } //end if
+ } //end if
+ n++;
+ } //end for
+ return qfalse;
+} //end of the function AAS_RandomGoalArea
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_AreaVisible(int srcarea, int destarea)
+{
+ return qfalse;
+} //end of the function AAS_AreaVisible
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float DistancePointToLine(vec3_t v1, vec3_t v2, vec3_t point)
+{
+ vec3_t vec, p2;
+
+ AAS_ProjectPointOntoVector(point, v1, v2, p2);
+ VectorSubtract(point, p2, vec);
+ return VectorLength(vec);
+} //end of the function DistancePointToLine
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_NearestHideArea(int srcnum, vec3_t origin, int areanum, int enemynum, vec3_t enemyorigin, int enemyareanum, int travelflags)
+{
+ int i, j, nextareanum, badtravelflags, numreach, bestarea;
+ unsigned short int t, besttraveltime;
+ static unsigned short int *hidetraveltimes;
+ aas_routingupdate_t *updateliststart, *updatelistend, *curupdate, *nextupdate;
+ aas_reachability_t *reach;
+ float dist1, dist2;
+ vec3_t v1, v2, p;
+ qboolean startVisible;
+
+ //
+ if (!hidetraveltimes)
+ {
+ hidetraveltimes = (unsigned short int *) GetClearedMemory(aasworld.numareas * sizeof(unsigned short int));
+ } //end if
+ else
+ {
+ Com_Memset(hidetraveltimes, 0, aasworld.numareas * sizeof(unsigned short int));
+ } //end else
+ besttraveltime = 0;
+ bestarea = 0;
+ //assume visible
+ startVisible = qtrue;
+ //
+ badtravelflags = ~travelflags;
+ //
+ curupdate = &aasworld.areaupdate[areanum];
+ curupdate->areanum = areanum;
+ VectorCopy(origin, curupdate->start);
+ curupdate->areatraveltimes = aasworld.areatraveltimes[areanum][0];
+ curupdate->tmptraveltime = 0;
+ //put the area to start with in the current read list
+ curupdate->next = NULL;
+ curupdate->prev = NULL;
+ updateliststart = curupdate;
+ updatelistend = curupdate;
+ //while there are updates in the list
+ while (updateliststart)
+ {
+ curupdate = updateliststart;
+ //
+ if (curupdate->next) curupdate->next->prev = NULL;
+ else updatelistend = NULL;
+ updateliststart = curupdate->next;
+ //
+ curupdate->inlist = qfalse;
+ //check all reversed reachability links
+ numreach = aasworld.areasettings[curupdate->areanum].numreachableareas;
+ reach = &aasworld.reachability[aasworld.areasettings[curupdate->areanum].firstreachablearea];
+ //
+ for (i = 0; i < numreach; i++, reach++)
+ {
+ //if an undesired travel type is used
+ if (AAS_TravelFlagForType_inline(reach->traveltype) & badtravelflags) continue;
+ //
+ if (AAS_AreaContentsTravelFlags_inline(reach->areanum) & badtravelflags) continue;
+ //number of the area the reachability leads to
+ nextareanum = reach->areanum;
+ // if this moves us into the enemies area, skip it
+ if (nextareanum == enemyareanum) continue;
+ //time already travelled plus the traveltime through
+ //the current area plus the travel time from the reachability
+ t = curupdate->tmptraveltime +
+ AAS_AreaTravelTime(curupdate->areanum, curupdate->start, reach->start) +
+ reach->traveltime;
+
+ //avoid going near the enemy
+ AAS_ProjectPointOntoVector(enemyorigin, curupdate->start, reach->end, p);
+ for (j = 0; j < 3; j++)
+ if ((p[j] > curupdate->start[j] && p[j] > reach->end[j]) ||
+ (p[j] < curupdate->start[j] && p[j] < reach->end[j]))
+ break;
+ if (j < 3)
+ {
+ VectorSubtract(enemyorigin, reach->end, v2);
+ } //end if
+ else
+ {
+ VectorSubtract(enemyorigin, p, v2);
+ } //end else
+ dist2 = VectorLength(v2);
+ //never go through the enemy
+ if (dist2 < 40) continue;
+ //
+ VectorSubtract(enemyorigin, curupdate->start, v1);
+ dist1 = VectorLength(v1);
+ //
+ if (dist2 < dist1)
+ {
+ t += (dist1 - dist2) * 10;
+ }
+ // if we weren't visible when starting, make sure we don't move into their view
+ if (!startVisible && AAS_AreaVisible(enemyareanum, nextareanum)) {
+ continue;
+ }
+ //
+ if (besttraveltime && t >= besttraveltime) continue;
+ //
+ if (!hidetraveltimes[nextareanum] ||
+ hidetraveltimes[nextareanum] > t)
+ {
+ //if the nextarea is not visible from the enemy area
+ if (!AAS_AreaVisible(enemyareanum, nextareanum))
+ {
+ besttraveltime = t;
+ bestarea = nextareanum;
+ } //end if
+ hidetraveltimes[nextareanum] = t;
+ nextupdate = &aasworld.areaupdate[nextareanum];
+ nextupdate->areanum = nextareanum;
+ nextupdate->tmptraveltime = t;
+ //remember where we entered this area
+ VectorCopy(reach->end, nextupdate->start);
+ //if this update is not in the list yet
+ if (!nextupdate->inlist)
+ {
+ //add the new update to the end of the list
+ nextupdate->next = NULL;
+ nextupdate->prev = updatelistend;
+ if (updatelistend) updatelistend->next = nextupdate;
+ else updateliststart = nextupdate;
+ updatelistend = nextupdate;
+ nextupdate->inlist = qtrue;
+ } //end if
+ } //end if
+ } //end for
+ } //end while
+ return bestarea;
+} //end of the function AAS_NearestHideArea
diff --git a/code/botlib/be_aas_route.h b/code/botlib/be_aas_route.h
new file mode 100755
index 0000000..8b92ac1
--- /dev/null
+++ b/code/botlib/be_aas_route.h
@@ -0,0 +1,67 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_route.h
+ *
+ * desc: AAS
+ *
+ * $Archive: /source/code/botlib/be_aas_route.h $
+ *
+ *****************************************************************************/
+
+#ifdef AASINTERN
+//initialize the AAS routing
+void AAS_InitRouting(void);
+//free the AAS routing caches
+void AAS_FreeRoutingCaches(void);
+//returns the travel time from start to end in the given area
+unsigned short int AAS_AreaTravelTime(int areanum, vec3_t start, vec3_t end);
+//
+void AAS_CreateAllRoutingCache(void);
+void AAS_WriteRouteCache(void);
+//
+void AAS_RoutingInfo(void);
+#endif //AASINTERN
+
+//returns the travel flag for the given travel type
+int AAS_TravelFlagForType(int traveltype);
+//return the travel flag(s) for traveling through this area
+int AAS_AreaContentsTravelFlags(int areanum);
+//returns the index of the next reachability for the given area
+int AAS_NextAreaReachability(int areanum, int reachnum);
+//returns the reachability with the given index
+void AAS_ReachabilityFromNum(int num, struct aas_reachability_s *reach);
+//returns a random goal area and goal origin
+int AAS_RandomGoalArea(int areanum, int travelflags, int *goalareanum, vec3_t goalorigin);
+//enable or disable an area for routing
+int AAS_EnableRoutingArea(int areanum, int enable);
+//returns the travel time within the given area from start to end
+unsigned short int AAS_AreaTravelTime(int areanum, vec3_t start, vec3_t end);
+//returns the travel time from the area to the goal area using the given travel flags
+int AAS_AreaTravelTimeToGoalArea(int areanum, vec3_t origin, int goalareanum, int travelflags);
+//predict a route up to a stop event
+int AAS_PredictRoute(struct aas_predictroute_s *route, int areanum, vec3_t origin,
+ int goalareanum, int travelflags, int maxareas, int maxtime,
+ int stopevent, int stopcontents, int stoptfl, int stopareanum);
+
+
diff --git a/code/botlib/be_aas_routealt.c b/code/botlib/be_aas_routealt.c
new file mode 100755
index 0000000..fd7cb8d
--- /dev/null
+++ b/code/botlib/be_aas_routealt.c
@@ -0,0 +1,240 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_routealt.c
+ *
+ * desc: AAS
+ *
+ * $Archive: /MissionPack/code/botlib/be_aas_routealt.c $
+ *
+ *****************************************************************************/
+
+#include "../game/q_shared.h"
+#include "l_utils.h"
+#include "l_memory.h"
+#include "l_log.h"
+#include "l_script.h"
+#include "l_precomp.h"
+#include "l_struct.h"
+#include "aasfile.h"
+#include "../game/botlib.h"
+#include "../game/be_aas.h"
+#include "be_aas_funcs.h"
+#include "be_interface.h"
+#include "be_aas_def.h"
+
+#define ENABLE_ALTROUTING
+//#define ALTROUTE_DEBUG
+
+typedef struct midrangearea_s
+{
+ int valid;
+ unsigned short starttime;
+ unsigned short goaltime;
+} midrangearea_t;
+
+midrangearea_t *midrangeareas;
+int *clusterareas;
+int numclusterareas;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_AltRoutingFloodCluster_r(int areanum)
+{
+ int i, otherareanum;
+ aas_area_t *area;
+ aas_face_t *face;
+
+ //add the current area to the areas of the current cluster
+ clusterareas[numclusterareas] = areanum;
+ numclusterareas++;
+ //remove the area from the mid range areas
+ midrangeareas[areanum].valid = qfalse;
+ //flood to other areas through the faces of this area
+ area = &aasworld.areas[areanum];
+ for (i = 0; i < area->numfaces; i++)
+ {
+ face = &aasworld.faces[abs(aasworld.faceindex[area->firstface + i])];
+ //get the area at the other side of the face
+ if (face->frontarea == areanum) otherareanum = face->backarea;
+ else otherareanum = face->frontarea;
+ //if there is an area at the other side of this face
+ if (!otherareanum) continue;
+ //if the other area is not a midrange area
+ if (!midrangeareas[otherareanum].valid) continue;
+ //
+ AAS_AltRoutingFloodCluster_r(otherareanum);
+ } //end for
+} //end of the function AAS_AltRoutingFloodCluster_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_AlternativeRouteGoals(vec3_t start, int startareanum, vec3_t goal, int goalareanum, int travelflags,
+ aas_altroutegoal_t *altroutegoals, int maxaltroutegoals,
+ int type)
+{
+#ifndef ENABLE_ALTROUTING
+ return 0;
+#else
+ int i, j, bestareanum;
+ int numaltroutegoals, nummidrangeareas;
+ int starttime, goaltime, goaltraveltime;
+ float dist, bestdist;
+ vec3_t mid, dir;
+#ifdef ALTROUTE_DEBUG
+ int startmillisecs;
+
+ startmillisecs = Sys_MilliSeconds();
+#endif
+
+ if (!startareanum || !goalareanum)
+ return 0;
+ //travel time towards the goal area
+ goaltraveltime = AAS_AreaTravelTimeToGoalArea(startareanum, start, goalareanum, travelflags);
+ //clear the midrange areas
+ Com_Memset(midrangeareas, 0, aasworld.numareas * sizeof(midrangearea_t));
+ numaltroutegoals = 0;
+ //
+ nummidrangeareas = 0;
+ //
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ //
+ if (!(type & ALTROUTEGOAL_ALL))
+ {
+ if (!(type & ALTROUTEGOAL_CLUSTERPORTALS && (aasworld.areasettings[i].contents & AREACONTENTS_CLUSTERPORTAL)))
+ {
+ if (!(type & ALTROUTEGOAL_VIEWPORTALS && (aasworld.areasettings[i].contents & AREACONTENTS_VIEWPORTAL)))
+ {
+ continue;
+ } //end if
+ } //end if
+ } //end if
+ //if the area has no reachabilities
+ if (!AAS_AreaReachability(i)) continue;
+ //tavel time from the area to the start area
+ starttime = AAS_AreaTravelTimeToGoalArea(startareanum, start, i, travelflags);
+ if (!starttime) continue;
+ //if the travel time from the start to the area is greater than the shortest goal travel time
+ if (starttime > (float) 1.1 * goaltraveltime) continue;
+ //travel time from the area to the goal area
+ goaltime = AAS_AreaTravelTimeToGoalArea(i, NULL, goalareanum, travelflags);
+ if (!goaltime) continue;
+ //if the travel time from the area to the goal is greater than the shortest goal travel time
+ if (goaltime > (float) 0.8 * goaltraveltime) continue;
+ //this is a mid range area
+ midrangeareas[i].valid = qtrue;
+ midrangeareas[i].starttime = starttime;
+ midrangeareas[i].goaltime = goaltime;
+ Log_Write("%d midrange area %d", nummidrangeareas, i);
+ nummidrangeareas++;
+ } //end for
+ //
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ if (!midrangeareas[i].valid) continue;
+ //get the areas in one cluster
+ numclusterareas = 0;
+ AAS_AltRoutingFloodCluster_r(i);
+ //now we've got a cluster with areas through which an alternative route could go
+ //get the 'center' of the cluster
+ VectorClear(mid);
+ for (j = 0; j < numclusterareas; j++)
+ {
+ VectorAdd(mid, aasworld.areas[clusterareas[j]].center, mid);
+ } //end for
+ VectorScale(mid, 1.0 / numclusterareas, mid);
+ //get the area closest to the center of the cluster
+ bestdist = 999999;
+ bestareanum = 0;
+ for (j = 0; j < numclusterareas; j++)
+ {
+ VectorSubtract(mid, aasworld.areas[clusterareas[j]].center, dir);
+ dist = VectorLength(dir);
+ if (dist < bestdist)
+ {
+ bestdist = dist;
+ bestareanum = clusterareas[j];
+ } //end if
+ } //end for
+ //now we've got an area for an alternative route
+ //FIXME: add alternative goal origin
+ VectorCopy(aasworld.areas[bestareanum].center, altroutegoals[numaltroutegoals].origin);
+ altroutegoals[numaltroutegoals].areanum = bestareanum;
+ altroutegoals[numaltroutegoals].starttraveltime = midrangeareas[bestareanum].starttime;
+ altroutegoals[numaltroutegoals].goaltraveltime = midrangeareas[bestareanum].goaltime;
+ altroutegoals[numaltroutegoals].extratraveltime =
+ (midrangeareas[bestareanum].starttime + midrangeareas[bestareanum].goaltime) -
+ goaltraveltime;
+ numaltroutegoals++;
+ //
+#ifdef ALTROUTE_DEBUG
+ AAS_ShowAreaPolygons(bestareanum, 1, qtrue);
+#endif
+ //don't return more than the maximum alternative route goals
+ if (numaltroutegoals >= maxaltroutegoals) break;
+ } //end for
+#ifdef ALTROUTE_DEBUG
+ botimport.Print(PRT_MESSAGE, "alternative route goals in %d msec\n", Sys_MilliSeconds() - startmillisecs);
+#endif
+ return numaltroutegoals;
+#endif
+} //end of the function AAS_AlternativeRouteGoals
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_InitAlternativeRouting(void)
+{
+#ifdef ENABLE_ALTROUTING
+ if (midrangeareas) FreeMemory(midrangeareas);
+ midrangeareas = (midrangearea_t *) GetMemory(aasworld.numareas * sizeof(midrangearea_t));
+ if (clusterareas) FreeMemory(clusterareas);
+ clusterareas = (int *) GetMemory(aasworld.numareas * sizeof(int));
+#endif
+} //end of the function AAS_InitAlternativeRouting
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ShutdownAlternativeRouting(void)
+{
+#ifdef ENABLE_ALTROUTING
+ if (midrangeareas) FreeMemory(midrangeareas);
+ midrangeareas = NULL;
+ if (clusterareas) FreeMemory(clusterareas);
+ clusterareas = NULL;
+ numclusterareas = 0;
+#endif
+} //end of the function AAS_ShutdownAlternativeRouting
diff --git a/code/botlib/be_aas_routealt.h b/code/botlib/be_aas_routealt.h
new file mode 100755
index 0000000..da4ef67
--- /dev/null
+++ b/code/botlib/be_aas_routealt.h
@@ -0,0 +1,40 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_routealt.h
+ *
+ * desc: AAS
+ *
+ * $Archive: /source/code/botlib/be_aas_routealt.h $
+ *
+ *****************************************************************************/
+
+#ifdef AASINTERN
+void AAS_InitAlternativeRouting(void);
+void AAS_ShutdownAlternativeRouting(void);
+#endif //AASINTERN
+
+
+int AAS_AlternativeRouteGoals(vec3_t start, int startareanum, vec3_t goal, int goalareanum, int travelflags,
+ aas_altroutegoal_t *altroutegoals, int maxaltroutegoals,
+ int type);
diff --git a/code/botlib/be_aas_sample.c b/code/botlib/be_aas_sample.c
new file mode 100755
index 0000000..c0adb47
--- /dev/null
+++ b/code/botlib/be_aas_sample.c
@@ -0,0 +1,1394 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_sample.c
+ *
+ * desc: AAS environment sampling
+ *
+ * $Archive: /MissionPack/code/botlib/be_aas_sample.c $
+ *
+ *****************************************************************************/
+
+#include "../game/q_shared.h"
+#include "l_memory.h"
+#include "l_script.h"
+#include "l_precomp.h"
+#include "l_struct.h"
+#ifndef BSPC
+#include "l_libvar.h"
+#endif
+#include "aasfile.h"
+#include "../game/botlib.h"
+#include "../game/be_aas.h"
+#include "be_interface.h"
+#include "be_aas_funcs.h"
+#include "be_aas_def.h"
+
+extern botlib_import_t botimport;
+
+//#define AAS_SAMPLE_DEBUG
+
+#define BBOX_NORMAL_EPSILON 0.001
+
+#define ON_EPSILON 0 //0.0005
+
+#define TRACEPLANE_EPSILON 0.125
+
+typedef struct aas_tracestack_s
+{
+ vec3_t start; //start point of the piece of line to trace
+ vec3_t end; //end point of the piece of line to trace
+ int planenum; //last plane used as splitter
+ int nodenum; //node found after splitting with planenum
+} aas_tracestack_t;
+
+int numaaslinks;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_PresenceTypeBoundingBox(int presencetype, vec3_t mins, vec3_t maxs)
+{
+ int index;
+ //bounding box size for each presence type
+ vec3_t boxmins[3] = {{0, 0, 0}, {-15, -15, -24}, {-15, -15, -24}};
+ vec3_t boxmaxs[3] = {{0, 0, 0}, { 15, 15, 32}, { 15, 15, 8}};
+
+ if (presencetype == PRESENCE_NORMAL) index = 1;
+ else if (presencetype == PRESENCE_CROUCH) index = 2;
+ else
+ {
+ botimport.Print(PRT_FATAL, "AAS_PresenceTypeBoundingBox: unknown presence type\n");
+ index = 2;
+ } //end if
+ VectorCopy(boxmins[index], mins);
+ VectorCopy(boxmaxs[index], maxs);
+} //end of the function AAS_PresenceTypeBoundingBox
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_InitAASLinkHeap(void)
+{
+ int i, max_aaslinks;
+
+ max_aaslinks = aasworld.linkheapsize;
+ //if there's no link heap present
+ if (!aasworld.linkheap)
+ {
+#ifdef BSPC
+ max_aaslinks = 6144;
+#else
+ max_aaslinks = (int) LibVarValue("max_aaslinks", "6144");
+#endif
+ if (max_aaslinks < 0) max_aaslinks = 0;
+ aasworld.linkheapsize = max_aaslinks;
+ aasworld.linkheap = (aas_link_t *) GetHunkMemory(max_aaslinks * sizeof(aas_link_t));
+ } //end if
+ //link the links on the heap
+ aasworld.linkheap[0].prev_ent = NULL;
+ aasworld.linkheap[0].next_ent = &aasworld.linkheap[1];
+ for (i = 1; i < max_aaslinks-1; i++)
+ {
+ aasworld.linkheap[i].prev_ent = &aasworld.linkheap[i - 1];
+ aasworld.linkheap[i].next_ent = &aasworld.linkheap[i + 1];
+ } //end for
+ aasworld.linkheap[max_aaslinks-1].prev_ent = &aasworld.linkheap[max_aaslinks-2];
+ aasworld.linkheap[max_aaslinks-1].next_ent = NULL;
+ //pointer to the first free link
+ aasworld.freelinks = &aasworld.linkheap[0];
+ //
+ numaaslinks = max_aaslinks;
+} //end of the function AAS_InitAASLinkHeap
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_FreeAASLinkHeap(void)
+{
+ if (aasworld.linkheap) FreeMemory(aasworld.linkheap);
+ aasworld.linkheap = NULL;
+ aasworld.linkheapsize = 0;
+} //end of the function AAS_FreeAASLinkHeap
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+aas_link_t *AAS_AllocAASLink(void)
+{
+ aas_link_t *link;
+
+ link = aasworld.freelinks;
+ if (!link)
+ {
+#ifndef BSPC
+ if (bot_developer)
+#endif
+ {
+ botimport.Print(PRT_FATAL, "empty aas link heap\n");
+ } //end if
+ return NULL;
+ } //end if
+ if (aasworld.freelinks) aasworld.freelinks = aasworld.freelinks->next_ent;
+ if (aasworld.freelinks) aasworld.freelinks->prev_ent = NULL;
+ numaaslinks--;
+ return link;
+} //end of the function AAS_AllocAASLink
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_DeAllocAASLink(aas_link_t *link)
+{
+ if (aasworld.freelinks) aasworld.freelinks->prev_ent = link;
+ link->prev_ent = NULL;
+ link->next_ent = aasworld.freelinks;
+ link->prev_area = NULL;
+ link->next_area = NULL;
+ aasworld.freelinks = link;
+ numaaslinks++;
+} //end of the function AAS_DeAllocAASLink
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_InitAASLinkedEntities(void)
+{
+ if (!aasworld.loaded) return;
+ if (aasworld.arealinkedentities) FreeMemory(aasworld.arealinkedentities);
+ aasworld.arealinkedentities = (aas_link_t **) GetClearedHunkMemory(
+ aasworld.numareas * sizeof(aas_link_t *));
+} //end of the function AAS_InitAASLinkedEntities
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_FreeAASLinkedEntities(void)
+{
+ if (aasworld.arealinkedentities) FreeMemory(aasworld.arealinkedentities);
+ aasworld.arealinkedentities = NULL;
+} //end of the function AAS_InitAASLinkedEntities
+//===========================================================================
+// returns the AAS area the point is in
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_PointAreaNum(vec3_t point)
+{
+ int nodenum;
+ vec_t dist;
+ aas_node_t *node;
+ aas_plane_t *plane;
+
+ if (!aasworld.loaded)
+ {
+ botimport.Print(PRT_ERROR, "AAS_PointAreaNum: aas not loaded\n");
+ return 0;
+ } //end if
+
+ //start with node 1 because node zero is a dummy used for solid leafs
+ nodenum = 1;
+ while (nodenum > 0)
+ {
+// botimport.Print(PRT_MESSAGE, "[%d]", nodenum);
+#ifdef AAS_SAMPLE_DEBUG
+ if (nodenum >= aasworld.numnodes)
+ {
+ botimport.Print(PRT_ERROR, "nodenum = %d >= aasworld.numnodes = %d\n", nodenum, aasworld.numnodes);
+ return 0;
+ } //end if
+#endif //AAS_SAMPLE_DEBUG
+ node = &aasworld.nodes[nodenum];
+#ifdef AAS_SAMPLE_DEBUG
+ if (node->planenum < 0 || node->planenum >= aasworld.numplanes)
+ {
+ botimport.Print(PRT_ERROR, "node->planenum = %d >= aasworld.numplanes = %d\n", node->planenum, aasworld.numplanes);
+ return 0;
+ } //end if
+#endif //AAS_SAMPLE_DEBUG
+ plane = &aasworld.planes[node->planenum];
+ dist = DotProduct(point, plane->normal) - plane->dist;
+ if (dist > 0) nodenum = node->children[0];
+ else nodenum = node->children[1];
+ } //end while
+ if (!nodenum)
+ {
+#ifdef AAS_SAMPLE_DEBUG
+ botimport.Print(PRT_MESSAGE, "in solid\n");
+#endif //AAS_SAMPLE_DEBUG
+ return 0;
+ } //end if
+ return -nodenum;
+} //end of the function AAS_PointAreaNum
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_PointReachabilityAreaIndex( vec3_t origin )
+{
+ int areanum, cluster, i, index;
+
+ if (!aasworld.initialized)
+ return 0;
+
+ if ( !origin )
+ {
+ index = 0;
+ for (i = 0; i < aasworld.numclusters; i++)
+ {
+ index += aasworld.clusters[i].numreachabilityareas;
+ } //end for
+ return index;
+ } //end if
+
+ areanum = AAS_PointAreaNum( origin );
+ if ( !areanum || !AAS_AreaReachability(areanum) )
+ return 0;
+ cluster = aasworld.areasettings[areanum].cluster;
+ areanum = aasworld.areasettings[areanum].clusterareanum;
+ if (cluster < 0)
+ {
+ cluster = aasworld.portals[-cluster].frontcluster;
+ areanum = aasworld.portals[-cluster].clusterareanum[0];
+ } //end if
+
+ index = 0;
+ for (i = 0; i < cluster; i++)
+ {
+ index += aasworld.clusters[i].numreachabilityareas;
+ } //end for
+ index += areanum;
+ return index;
+} //end of the function AAS_PointReachabilityAreaIndex
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_AreaCluster(int areanum)
+{
+ if (areanum <= 0 || areanum >= aasworld.numareas)
+ {
+ botimport.Print(PRT_ERROR, "AAS_AreaCluster: invalid area number\n");
+ return 0;
+ } //end if
+ return aasworld.areasettings[areanum].cluster;
+} //end of the function AAS_AreaCluster
+//===========================================================================
+// returns the presence types of the given area
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_AreaPresenceType(int areanum)
+{
+ if (!aasworld.loaded) return 0;
+ if (areanum <= 0 || areanum >= aasworld.numareas)
+ {
+ botimport.Print(PRT_ERROR, "AAS_AreaPresenceType: invalid area number\n");
+ return 0;
+ } //end if
+ return aasworld.areasettings[areanum].presencetype;
+} //end of the function AAS_AreaPresenceType
+//===========================================================================
+// returns the presence type at the given point
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_PointPresenceType(vec3_t point)
+{
+ int areanum;
+
+ if (!aasworld.loaded) return 0;
+
+ areanum = AAS_PointAreaNum(point);
+ if (!areanum) return PRESENCE_NONE;
+ return aasworld.areasettings[areanum].presencetype;
+} //end of the function AAS_PointPresenceType
+//===========================================================================
+// calculates the minimum distance between the origin of the box and the
+// given plane when both will collide on the given side of the plane
+//
+// normal = normal vector of plane to calculate distance from
+// mins = minimums of box relative to origin
+// maxs = maximums of box relative to origin
+// side = side of the plane we want to calculate the distance from
+// 0 normal vector side
+// 1 not normal vector side
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+vec_t AAS_BoxOriginDistanceFromPlane(vec3_t normal, vec3_t mins, vec3_t maxs, int side)
+{
+ vec3_t v1, v2;
+ int i;
+
+ //swap maxs and mins when on the other side of the plane
+ if (side)
+ {
+ //get a point of the box that would be one of the first
+ //to collide with the plane
+ for (i = 0; i < 3; i++)
+ {
+ if (normal[i] > BBOX_NORMAL_EPSILON) v1[i] = maxs[i];
+ else if (normal[i] < -BBOX_NORMAL_EPSILON) v1[i] = mins[i];
+ else v1[i] = 0;
+ } //end for
+ } //end if
+ else
+ {
+ //get a point of the box that would be one of the first
+ //to collide with the plane
+ for (i = 0; i < 3; i++)
+ {
+ if (normal[i] > BBOX_NORMAL_EPSILON) v1[i] = mins[i];
+ else if (normal[i] < -BBOX_NORMAL_EPSILON) v1[i] = maxs[i];
+ else v1[i] = 0;
+ } //end for
+ } //end else
+ //
+ VectorCopy(normal, v2);
+ VectorInverse(v2);
+// VectorNegate(normal, v2);
+ return DotProduct(v1, v2);
+} //end of the function AAS_BoxOriginDistanceFromPlane
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean AAS_AreaEntityCollision(int areanum, vec3_t start, vec3_t end,
+ int presencetype, int passent, aas_trace_t *trace)
+{
+ int collision;
+ vec3_t boxmins, boxmaxs;
+ aas_link_t *link;
+ bsp_trace_t bsptrace;
+
+ AAS_PresenceTypeBoundingBox(presencetype, boxmins, boxmaxs);
+
+ Com_Memset(&bsptrace, 0, sizeof(bsp_trace_t)); //make compiler happy
+ //assume no collision
+ bsptrace.fraction = 1;
+ collision = qfalse;
+ for (link = aasworld.arealinkedentities[areanum]; link; link = link->next_ent)
+ {
+ //ignore the pass entity
+ if (link->entnum == passent) continue;
+ //
+ if (AAS_EntityCollision(link->entnum, start, boxmins, boxmaxs, end,
+ CONTENTS_SOLID|CONTENTS_PLAYERCLIP, &bsptrace))
+ {
+ collision = qtrue;
+ } //end if
+ } //end for
+ if (collision)
+ {
+ trace->startsolid = bsptrace.startsolid;
+ trace->ent = bsptrace.ent;
+ VectorCopy(bsptrace.endpos, trace->endpos);
+ trace->area = 0;
+ trace->planenum = 0;
+ return qtrue;
+ } //end if
+ return qfalse;
+} //end of the function AAS_AreaEntityCollision
+//===========================================================================
+// recursive subdivision of the line by the BSP tree.
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+aas_trace_t AAS_TraceClientBBox(vec3_t start, vec3_t end, int presencetype,
+ int passent)
+{
+ int side, nodenum, tmpplanenum;
+ float front, back, frac;
+ vec3_t cur_start, cur_end, cur_mid, v1, v2;
+ aas_tracestack_t tracestack[127];
+ aas_tracestack_t *tstack_p;
+ aas_node_t *aasnode;
+ aas_plane_t *plane;
+ aas_trace_t trace;
+
+ //clear the trace structure
+ Com_Memset(&trace, 0, sizeof(aas_trace_t));
+
+ if (!aasworld.loaded) return trace;
+
+ tstack_p = tracestack;
+ //we start with the whole line on the stack
+ VectorCopy(start, tstack_p->start);
+ VectorCopy(end, tstack_p->end);
+ tstack_p->planenum = 0;
+ //start with node 1 because node zero is a dummy for a solid leaf
+ tstack_p->nodenum = 1; //starting at the root of the tree
+ tstack_p++;
+
+ while (1)
+ {
+ //pop up the stack
+ tstack_p--;
+ //if the trace stack is empty (ended up with a piece of the
+ //line to be traced in an area)
+ if (tstack_p < tracestack)
+ {
+ tstack_p++;
+ //nothing was hit
+ trace.startsolid = qfalse;
+ trace.fraction = 1.0;
+ //endpos is the end of the line
+ VectorCopy(end, trace.endpos);
+ //nothing hit
+ trace.ent = 0;
+ trace.area = 0;
+ trace.planenum = 0;
+ return trace;
+ } //end if
+ //number of the current node to test the line against
+ nodenum = tstack_p->nodenum;
+ //if it is an area
+ if (nodenum < 0)
+ {
+#ifdef AAS_SAMPLE_DEBUG
+ if (-nodenum > aasworld.numareasettings)
+ {
+ botimport.Print(PRT_ERROR, "AAS_TraceBoundingBox: -nodenum out of range\n");
+ return trace;
+ } //end if
+#endif //AAS_SAMPLE_DEBUG
+ //botimport.Print(PRT_MESSAGE, "areanum = %d, must be %d\n", -nodenum, AAS_PointAreaNum(start));
+ //if can't enter the area because it hasn't got the right presence type
+ if (!(aasworld.areasettings[-nodenum].presencetype & presencetype))
+ {
+ //if the start point is still the initial start point
+ //NOTE: no need for epsilons because the points will be
+ //exactly the same when they're both the start point
+ if (tstack_p->start[0] == start[0] &&
+ tstack_p->start[1] == start[1] &&
+ tstack_p->start[2] == start[2])
+ {
+ trace.startsolid = qtrue;
+ trace.fraction = 0.0;
+ VectorClear(v1);
+ } //end if
+ else
+ {
+ trace.startsolid = qfalse;
+ VectorSubtract(end, start, v1);
+ VectorSubtract(tstack_p->start, start, v2);
+ trace.fraction = VectorLength(v2) / VectorNormalize(v1);
+ VectorMA(tstack_p->start, -0.125, v1, tstack_p->start);
+ } //end else
+ VectorCopy(tstack_p->start, trace.endpos);
+ trace.ent = 0;
+ trace.area = -nodenum;
+// VectorSubtract(end, start, v1);
+ trace.planenum = tstack_p->planenum;
+ //always take the plane with normal facing towards the trace start
+ plane = &aasworld.planes[trace.planenum];
+ if (DotProduct(v1, plane->normal) > 0) trace.planenum ^= 1;
+ return trace;
+ } //end if
+ else
+ {
+ if (passent >= 0)
+ {
+ if (AAS_AreaEntityCollision(-nodenum, tstack_p->start,
+ tstack_p->end, presencetype, passent,
+ &trace))
+ {
+ if (!trace.startsolid)
+ {
+ VectorSubtract(end, start, v1);
+ VectorSubtract(trace.endpos, start, v2);
+ trace.fraction = VectorLength(v2) / VectorLength(v1);
+ } //end if
+ return trace;
+ } //end if
+ } //end if
+ } //end else
+ trace.lastarea = -nodenum;
+ continue;
+ } //end if
+ //if it is a solid leaf
+ if (!nodenum)
+ {
+ //if the start point is still the initial start point
+ //NOTE: no need for epsilons because the points will be
+ //exactly the same when they're both the start point
+ if (tstack_p->start[0] == start[0] &&
+ tstack_p->start[1] == start[1] &&
+ tstack_p->start[2] == start[2])
+ {
+ trace.startsolid = qtrue;
+ trace.fraction = 0.0;
+ VectorClear(v1);
+ } //end if
+ else
+ {
+ trace.startsolid = qfalse;
+ VectorSubtract(end, start, v1);
+ VectorSubtract(tstack_p->start, start, v2);
+ trace.fraction = VectorLength(v2) / VectorNormalize(v1);
+ VectorMA(tstack_p->start, -0.125, v1, tstack_p->start);
+ } //end else
+ VectorCopy(tstack_p->start, trace.endpos);
+ trace.ent = 0;
+ trace.area = 0; //hit solid leaf
+// VectorSubtract(end, start, v1);
+ trace.planenum = tstack_p->planenum;
+ //always take the plane with normal facing towards the trace start
+ plane = &aasworld.planes[trace.planenum];
+ if (DotProduct(v1, plane->normal) > 0) trace.planenum ^= 1;
+ return trace;
+ } //end if
+#ifdef AAS_SAMPLE_DEBUG
+ if (nodenum > aasworld.numnodes)
+ {
+ botimport.Print(PRT_ERROR, "AAS_TraceBoundingBox: nodenum out of range\n");
+ return trace;
+ } //end if
+#endif //AAS_SAMPLE_DEBUG
+ //the node to test against
+ aasnode = &aasworld.nodes[nodenum];
+ //start point of current line to test against node
+ VectorCopy(tstack_p->start, cur_start);
+ //end point of the current line to test against node
+ VectorCopy(tstack_p->end, cur_end);
+ //the current node plane
+ plane = &aasworld.planes[aasnode->planenum];
+
+ switch(plane->type)
+ {/*FIXME: wtf doesn't this work? obviously the axial node planes aren't always facing positive!!!
+ //check for axial planes
+ case PLANE_X:
+ {
+ front = cur_start[0] - plane->dist;
+ back = cur_end[0] - plane->dist;
+ break;
+ } //end case
+ case PLANE_Y:
+ {
+ front = cur_start[1] - plane->dist;
+ back = cur_end[1] - plane->dist;
+ break;
+ } //end case
+ case PLANE_Z:
+ {
+ front = cur_start[2] - plane->dist;
+ back = cur_end[2] - plane->dist;
+ break;
+ } //end case*/
+ default: //gee it's not an axial plane
+ {
+ front = DotProduct(cur_start, plane->normal) - plane->dist;
+ back = DotProduct(cur_end, plane->normal) - plane->dist;
+ break;
+ } //end default
+ } //end switch
+ // bk010221 - old location of FPE hack and divide by zero expression
+ //if the whole to be traced line is totally at the front of this node
+ //only go down the tree with the front child
+ if ((front >= -ON_EPSILON && back >= -ON_EPSILON))
+ {
+ //keep the current start and end point on the stack
+ //and go down the tree with the front child
+ tstack_p->nodenum = aasnode->children[0];
+ tstack_p++;
+ if (tstack_p >= &tracestack[127])
+ {
+ botimport.Print(PRT_ERROR, "AAS_TraceBoundingBox: stack overflow\n");
+ return trace;
+ } //end if
+ } //end if
+ //if the whole to be traced line is totally at the back of this node
+ //only go down the tree with the back child
+ else if ((front < ON_EPSILON && back < ON_EPSILON))
+ {
+ //keep the current start and end point on the stack
+ //and go down the tree with the back child
+ tstack_p->nodenum = aasnode->children[1];
+ tstack_p++;
+ if (tstack_p >= &tracestack[127])
+ {
+ botimport.Print(PRT_ERROR, "AAS_TraceBoundingBox: stack overflow\n");
+ return trace;
+ } //end if
+ } //end if
+ //go down the tree both at the front and back of the node
+ else
+ {
+ tmpplanenum = tstack_p->planenum;
+ // bk010221 - new location of divide by zero (see above)
+ if ( front == back ) front -= 0.001f; // bk0101022 - hack/FPE
+ //calculate the hitpoint with the node (split point of the line)
+ //put the crosspoint TRACEPLANE_EPSILON pixels on the near side
+ if (front < 0) frac = (front + TRACEPLANE_EPSILON)/(front-back);
+ else frac = (front - TRACEPLANE_EPSILON)/(front-back); // bk010221
+ //
+ if (frac < 0)
+ frac = 0.001f; //0
+ else if (frac > 1)
+ frac = 0.999f; //1
+ //frac = front / (front-back);
+ //
+ cur_mid[0] = cur_start[0] + (cur_end[0] - cur_start[0]) * frac;
+ cur_mid[1] = cur_start[1] + (cur_end[1] - cur_start[1]) * frac;
+ cur_mid[2] = cur_start[2] + (cur_end[2] - cur_start[2]) * frac;
+
+// AAS_DrawPlaneCross(cur_mid, plane->normal, plane->dist, plane->type, LINECOLOR_RED);
+ //side the front part of the line is on
+ side = front < 0;
+ //first put the end part of the line on the stack (back side)
+ VectorCopy(cur_mid, tstack_p->start);
+ //not necesary to store because still on stack
+ //VectorCopy(cur_end, tstack_p->end);
+ tstack_p->planenum = aasnode->planenum;
+ tstack_p->nodenum = aasnode->children[!side];
+ tstack_p++;
+ if (tstack_p >= &tracestack[127])
+ {
+ botimport.Print(PRT_ERROR, "AAS_TraceBoundingBox: stack overflow\n");
+ return trace;
+ } //end if
+ //now put the part near the start of the line on the stack so we will
+ //continue with thats part first. This way we'll find the first
+ //hit of the bbox
+ VectorCopy(cur_start, tstack_p->start);
+ VectorCopy(cur_mid, tstack_p->end);
+ tstack_p->planenum = tmpplanenum;
+ tstack_p->nodenum = aasnode->children[side];
+ tstack_p++;
+ if (tstack_p >= &tracestack[127])
+ {
+ botimport.Print(PRT_ERROR, "AAS_TraceBoundingBox: stack overflow\n");
+ return trace;
+ } //end if
+ } //end else
+ } //end while
+// return trace;
+} //end of the function AAS_TraceClientBBox
+//===========================================================================
+// recursive subdivision of the line by the BSP tree.
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_TraceAreas(vec3_t start, vec3_t end, int *areas, vec3_t *points, int maxareas)
+{
+ int side, nodenum, tmpplanenum;
+ int numareas;
+ float front, back, frac;
+ vec3_t cur_start, cur_end, cur_mid;
+ aas_tracestack_t tracestack[127];
+ aas_tracestack_t *tstack_p;
+ aas_node_t *aasnode;
+ aas_plane_t *plane;
+
+ numareas = 0;
+ areas[0] = 0;
+ if (!aasworld.loaded) return numareas;
+
+ tstack_p = tracestack;
+ //we start with the whole line on the stack
+ VectorCopy(start, tstack_p->start);
+ VectorCopy(end, tstack_p->end);
+ tstack_p->planenum = 0;
+ //start with node 1 because node zero is a dummy for a solid leaf
+ tstack_p->nodenum = 1; //starting at the root of the tree
+ tstack_p++;
+
+ while (1)
+ {
+ //pop up the stack
+ tstack_p--;
+ //if the trace stack is empty (ended up with a piece of the
+ //line to be traced in an area)
+ if (tstack_p < tracestack)
+ {
+ return numareas;
+ } //end if
+ //number of the current node to test the line against
+ nodenum = tstack_p->nodenum;
+ //if it is an area
+ if (nodenum < 0)
+ {
+#ifdef AAS_SAMPLE_DEBUG
+ if (-nodenum > aasworld.numareasettings)
+ {
+ botimport.Print(PRT_ERROR, "AAS_TraceAreas: -nodenum = %d out of range\n", -nodenum);
+ return numareas;
+ } //end if
+#endif //AAS_SAMPLE_DEBUG
+ //botimport.Print(PRT_MESSAGE, "areanum = %d, must be %d\n", -nodenum, AAS_PointAreaNum(start));
+ areas[numareas] = -nodenum;
+ if (points) VectorCopy(tstack_p->start, points[numareas]);
+ numareas++;
+ if (numareas >= maxareas) return numareas;
+ continue;
+ } //end if
+ //if it is a solid leaf
+ if (!nodenum)
+ {
+ continue;
+ } //end if
+#ifdef AAS_SAMPLE_DEBUG
+ if (nodenum > aasworld.numnodes)
+ {
+ botimport.Print(PRT_ERROR, "AAS_TraceAreas: nodenum out of range\n");
+ return numareas;
+ } //end if
+#endif //AAS_SAMPLE_DEBUG
+ //the node to test against
+ aasnode = &aasworld.nodes[nodenum];
+ //start point of current line to test against node
+ VectorCopy(tstack_p->start, cur_start);
+ //end point of the current line to test against node
+ VectorCopy(tstack_p->end, cur_end);
+ //the current node plane
+ plane = &aasworld.planes[aasnode->planenum];
+
+ switch(plane->type)
+ {/*FIXME: wtf doesn't this work? obviously the node planes aren't always facing positive!!!
+ //check for axial planes
+ case PLANE_X:
+ {
+ front = cur_start[0] - plane->dist;
+ back = cur_end[0] - plane->dist;
+ break;
+ } //end case
+ case PLANE_Y:
+ {
+ front = cur_start[1] - plane->dist;
+ back = cur_end[1] - plane->dist;
+ break;
+ } //end case
+ case PLANE_Z:
+ {
+ front = cur_start[2] - plane->dist;
+ back = cur_end[2] - plane->dist;
+ break;
+ } //end case*/
+ default: //gee it's not an axial plane
+ {
+ front = DotProduct(cur_start, plane->normal) - plane->dist;
+ back = DotProduct(cur_end, plane->normal) - plane->dist;
+ break;
+ } //end default
+ } //end switch
+
+ //if the whole to be traced line is totally at the front of this node
+ //only go down the tree with the front child
+ if (front > 0 && back > 0)
+ {
+ //keep the current start and end point on the stack
+ //and go down the tree with the front child
+ tstack_p->nodenum = aasnode->children[0];
+ tstack_p++;
+ if (tstack_p >= &tracestack[127])
+ {
+ botimport.Print(PRT_ERROR, "AAS_TraceAreas: stack overflow\n");
+ return numareas;
+ } //end if
+ } //end if
+ //if the whole to be traced line is totally at the back of this node
+ //only go down the tree with the back child
+ else if (front <= 0 && back <= 0)
+ {
+ //keep the current start and end point on the stack
+ //and go down the tree with the back child
+ tstack_p->nodenum = aasnode->children[1];
+ tstack_p++;
+ if (tstack_p >= &tracestack[127])
+ {
+ botimport.Print(PRT_ERROR, "AAS_TraceAreas: stack overflow\n");
+ return numareas;
+ } //end if
+ } //end if
+ //go down the tree both at the front and back of the node
+ else
+ {
+ tmpplanenum = tstack_p->planenum;
+ //calculate the hitpoint with the node (split point of the line)
+ //put the crosspoint TRACEPLANE_EPSILON pixels on the near side
+ if (front < 0) frac = (front)/(front-back);
+ else frac = (front)/(front-back);
+ if (frac < 0) frac = 0;
+ else if (frac > 1) frac = 1;
+ //frac = front / (front-back);
+ //
+ cur_mid[0] = cur_start[0] + (cur_end[0] - cur_start[0]) * frac;
+ cur_mid[1] = cur_start[1] + (cur_end[1] - cur_start[1]) * frac;
+ cur_mid[2] = cur_start[2] + (cur_end[2] - cur_start[2]) * frac;
+
+// AAS_DrawPlaneCross(cur_mid, plane->normal, plane->dist, plane->type, LINECOLOR_RED);
+ //side the front part of the line is on
+ side = front < 0;
+ //first put the end part of the line on the stack (back side)
+ VectorCopy(cur_mid, tstack_p->start);
+ //not necesary to store because still on stack
+ //VectorCopy(cur_end, tstack_p->end);
+ tstack_p->planenum = aasnode->planenum;
+ tstack_p->nodenum = aasnode->children[!side];
+ tstack_p++;
+ if (tstack_p >= &tracestack[127])
+ {
+ botimport.Print(PRT_ERROR, "AAS_TraceAreas: stack overflow\n");
+ return numareas;
+ } //end if
+ //now put the part near the start of the line on the stack so we will
+ //continue with thats part first. This way we'll find the first
+ //hit of the bbox
+ VectorCopy(cur_start, tstack_p->start);
+ VectorCopy(cur_mid, tstack_p->end);
+ tstack_p->planenum = tmpplanenum;
+ tstack_p->nodenum = aasnode->children[side];
+ tstack_p++;
+ if (tstack_p >= &tracestack[127])
+ {
+ botimport.Print(PRT_ERROR, "AAS_TraceAreas: stack overflow\n");
+ return numareas;
+ } //end if
+ } //end else
+ } //end while
+// return numareas;
+} //end of the function AAS_TraceAreas
+//===========================================================================
+// a simple cross product
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+// void AAS_OrthogonalToVectors(vec3_t v1, vec3_t v2, vec3_t res)
+#define AAS_OrthogonalToVectors(v1, v2, res) \
+ (res)[0] = ((v1)[1] * (v2)[2]) - ((v1)[2] * (v2)[1]);\
+ (res)[1] = ((v1)[2] * (v2)[0]) - ((v1)[0] * (v2)[2]);\
+ (res)[2] = ((v1)[0] * (v2)[1]) - ((v1)[1] * (v2)[0]);
+//===========================================================================
+// tests if the given point is within the face boundaries
+//
+// Parameter: face : face to test if the point is in it
+// pnormal : normal of the plane to use for the face
+// point : point to test if inside face boundaries
+// Returns: qtrue if the point is within the face boundaries
+// Changes Globals: -
+//===========================================================================
+qboolean AAS_InsideFace(aas_face_t *face, vec3_t pnormal, vec3_t point, float epsilon)
+{
+ int i, firstvertex, edgenum;
+ vec3_t v0;
+ vec3_t edgevec, pointvec, sepnormal;
+ aas_edge_t *edge;
+#ifdef AAS_SAMPLE_DEBUG
+ int lastvertex = 0;
+#endif //AAS_SAMPLE_DEBUG
+
+ if (!aasworld.loaded) return qfalse;
+
+ for (i = 0; i < face->numedges; i++)
+ {
+ edgenum = aasworld.edgeindex[face->firstedge + i];
+ edge = &aasworld.edges[abs(edgenum)];
+ //get the first vertex of the edge
+ firstvertex = edgenum < 0;
+ VectorCopy(aasworld.vertexes[edge->v[firstvertex]], v0);
+ //edge vector
+ VectorSubtract(aasworld.vertexes[edge->v[!firstvertex]], v0, edgevec);
+ //
+#ifdef AAS_SAMPLE_DEBUG
+ if (lastvertex && lastvertex != edge->v[firstvertex])
+ {
+ botimport.Print(PRT_MESSAGE, "winding not counter clockwise\n");
+ } //end if
+ lastvertex = edge->v[!firstvertex];
+#endif //AAS_SAMPLE_DEBUG
+ //vector from first edge point to point possible in face
+ VectorSubtract(point, v0, pointvec);
+ //get a vector pointing inside the face orthogonal to both the
+ //edge vector and the normal vector of the plane the face is in
+ //this vector defines a plane through the origin (first vertex of
+ //edge) and through both the edge vector and the normal vector
+ //of the plane
+ AAS_OrthogonalToVectors(edgevec, pnormal, sepnormal);
+ //check on wich side of the above plane the point is
+ //this is done by checking the sign of the dot product of the
+ //vector orthogonal vector from above and the vector from the
+ //origin (first vertex of edge) to the point
+ //if the dotproduct is smaller than zero the point is outside the face
+ if (DotProduct(pointvec, sepnormal) < -epsilon) return qfalse;
+ } //end for
+ return qtrue;
+} //end of the function AAS_InsideFace
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean AAS_PointInsideFace(int facenum, vec3_t point, float epsilon)
+{
+ int i, firstvertex, edgenum;
+ vec_t *v1, *v2;
+ vec3_t edgevec, pointvec, sepnormal;
+ aas_edge_t *edge;
+ aas_plane_t *plane;
+ aas_face_t *face;
+
+ if (!aasworld.loaded) return qfalse;
+
+ face = &aasworld.faces[facenum];
+ plane = &aasworld.planes[face->planenum];
+ //
+ for (i = 0; i < face->numedges; i++)
+ {
+ edgenum = aasworld.edgeindex[face->firstedge + i];
+ edge = &aasworld.edges[abs(edgenum)];
+ //get the first vertex of the edge
+ firstvertex = edgenum < 0;
+ v1 = aasworld.vertexes[edge->v[firstvertex]];
+ v2 = aasworld.vertexes[edge->v[!firstvertex]];
+ //edge vector
+ VectorSubtract(v2, v1, edgevec);
+ //vector from first edge point to point possible in face
+ VectorSubtract(point, v1, pointvec);
+ //
+ CrossProduct(edgevec, plane->normal, sepnormal);
+ //
+ if (DotProduct(pointvec, sepnormal) < -epsilon) return qfalse;
+ } //end for
+ return qtrue;
+} //end of the function AAS_PointInsideFace
+//===========================================================================
+// returns the ground face the given point is above in the given area
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+aas_face_t *AAS_AreaGroundFace(int areanum, vec3_t point)
+{
+ int i, facenum;
+ vec3_t up = {0, 0, 1};
+ vec3_t normal;
+ aas_area_t *area;
+ aas_face_t *face;
+
+ if (!aasworld.loaded) return NULL;
+
+ area = &aasworld.areas[areanum];
+ for (i = 0; i < area->numfaces; i++)
+ {
+ facenum = aasworld.faceindex[area->firstface + i];
+ face = &aasworld.faces[abs(facenum)];
+ //if this is a ground face
+ if (face->faceflags & FACE_GROUND)
+ {
+ //get the up or down normal
+ if (aasworld.planes[face->planenum].normal[2] < 0) VectorNegate(up, normal);
+ else VectorCopy(up, normal);
+ //check if the point is in the face
+ if (AAS_InsideFace(face, normal, point, 0.01f)) return face;
+ } //end if
+ } //end for
+ return NULL;
+} //end of the function AAS_AreaGroundFace
+//===========================================================================
+// returns the face the trace end position is situated in
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_FacePlane(int facenum, vec3_t normal, float *dist)
+{
+ aas_plane_t *plane;
+
+ plane = &aasworld.planes[aasworld.faces[facenum].planenum];
+ VectorCopy(plane->normal, normal);
+ *dist = plane->dist;
+} //end of the function AAS_FacePlane
+//===========================================================================
+// returns the face the trace end position is situated in
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+aas_face_t *AAS_TraceEndFace(aas_trace_t *trace)
+{
+ int i, facenum;
+ aas_area_t *area;
+ aas_face_t *face, *firstface = NULL;
+
+ if (!aasworld.loaded) return NULL;
+
+ //if started in solid no face was hit
+ if (trace->startsolid) return NULL;
+ //trace->lastarea is the last area the trace was in
+ area = &aasworld.areas[trace->lastarea];
+ //check which face the trace.endpos was in
+ for (i = 0; i < area->numfaces; i++)
+ {
+ facenum = aasworld.faceindex[area->firstface + i];
+ face = &aasworld.faces[abs(facenum)];
+ //if the face is in the same plane as the trace end point
+ if ((face->planenum & ~1) == (trace->planenum & ~1))
+ {
+ //firstface is used for optimization, if theres only one
+ //face in the plane then it has to be the good one
+ //if there are more faces in the same plane then always
+ //check the one with the fewest edges first
+/* if (firstface)
+ {
+ if (firstface->numedges < face->numedges)
+ {
+ if (AAS_InsideFace(firstface,
+ aasworld.planes[face->planenum].normal, trace->endpos))
+ {
+ return firstface;
+ } //end if
+ firstface = face;
+ } //end if
+ else
+ {
+ if (AAS_InsideFace(face,
+ aasworld.planes[face->planenum].normal, trace->endpos))
+ {
+ return face;
+ } //end if
+ } //end else
+ } //end if
+ else
+ {
+ firstface = face;
+ } //end else*/
+ if (AAS_InsideFace(face,
+ aasworld.planes[face->planenum].normal, trace->endpos, 0.01f)) return face;
+ } //end if
+ } //end for
+ return firstface;
+} //end of the function AAS_TraceEndFace
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_BoxOnPlaneSide2(vec3_t absmins, vec3_t absmaxs, aas_plane_t *p)
+{
+ int i, sides;
+ float dist1, dist2;
+ vec3_t corners[2];
+
+ for (i = 0; i < 3; i++)
+ {
+ if (p->normal[i] < 0)
+ {
+ corners[0][i] = absmins[i];
+ corners[1][i] = absmaxs[i];
+ } //end if
+ else
+ {
+ corners[1][i] = absmins[i];
+ corners[0][i] = absmaxs[i];
+ } //end else
+ } //end for
+ dist1 = DotProduct(p->normal, corners[0]) - p->dist;
+ dist2 = DotProduct(p->normal, corners[1]) - p->dist;
+ sides = 0;
+ if (dist1 >= 0) sides = 1;
+ if (dist2 < 0) sides |= 2;
+
+ return sides;
+} //end of the function AAS_BoxOnPlaneSide2
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+//int AAS_BoxOnPlaneSide(vec3_t absmins, vec3_t absmaxs, aas_plane_t *p)
+#define AAS_BoxOnPlaneSide(absmins, absmaxs, p) (\
+ ( (p)->type < 3) ?\
+ (\
+ ( (p)->dist <= (absmins)[(p)->type]) ?\
+ (\
+ 1\
+ )\
+ :\
+ (\
+ ( (p)->dist >= (absmaxs)[(p)->type]) ?\
+ (\
+ 2\
+ )\
+ :\
+ (\
+ 3\
+ )\
+ )\
+ )\
+ :\
+ (\
+ AAS_BoxOnPlaneSide2((absmins), (absmaxs), (p))\
+ )\
+) //end of the function AAS_BoxOnPlaneSide
+//===========================================================================
+// remove the links to this entity from all areas
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_UnlinkFromAreas(aas_link_t *areas)
+{
+ aas_link_t *link, *nextlink;
+
+ for (link = areas; link; link = nextlink)
+ {
+ //next area the entity is linked in
+ nextlink = link->next_area;
+ //remove the entity from the linked list of this area
+ if (link->prev_ent) link->prev_ent->next_ent = link->next_ent;
+ else aasworld.arealinkedentities[link->areanum] = link->next_ent;
+ if (link->next_ent) link->next_ent->prev_ent = link->prev_ent;
+ //deallocate the link structure
+ AAS_DeAllocAASLink(link);
+ } //end for
+} //end of the function AAS_UnlinkFromAreas
+//===========================================================================
+// link the entity to the areas the bounding box is totally or partly
+// situated in. This is done with recursion down the tree using the
+// bounding box to test for plane sides
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+
+typedef struct
+{
+ int nodenum; //node found after splitting
+} aas_linkstack_t;
+
+aas_link_t *AAS_AASLinkEntity(vec3_t absmins, vec3_t absmaxs, int entnum)
+{
+ int side, nodenum;
+ aas_linkstack_t linkstack[128];
+ aas_linkstack_t *lstack_p;
+ aas_node_t *aasnode;
+ aas_plane_t *plane;
+ aas_link_t *link, *areas;
+
+ if (!aasworld.loaded)
+ {
+ botimport.Print(PRT_ERROR, "AAS_LinkEntity: aas not loaded\n");
+ return NULL;
+ } //end if
+
+ areas = NULL;
+ //
+ lstack_p = linkstack;
+ //we start with the whole line on the stack
+ //start with node 1 because node zero is a dummy used for solid leafs
+ lstack_p->nodenum = 1; //starting at the root of the tree
+ lstack_p++;
+
+ while (1)
+ {
+ //pop up the stack
+ lstack_p--;
+ //if the trace stack is empty (ended up with a piece of the
+ //line to be traced in an area)
+ if (lstack_p < linkstack) break;
+ //number of the current node to test the line against
+ nodenum = lstack_p->nodenum;
+ //if it is an area
+ if (nodenum < 0)
+ {
+ //NOTE: the entity might have already been linked into this area
+ // because several node children can point to the same area
+ for (link = aasworld.arealinkedentities[-nodenum]; link; link = link->next_ent)
+ {
+ if (link->entnum == entnum) break;
+ } //end for
+ if (link) continue;
+ //
+ link = AAS_AllocAASLink();
+ if (!link) return areas;
+ link->entnum = entnum;
+ link->areanum = -nodenum;
+ //put the link into the double linked area list of the entity
+ link->prev_area = NULL;
+ link->next_area = areas;
+ if (areas) areas->prev_area = link;
+ areas = link;
+ //put the link into the double linked entity list of the area
+ link->prev_ent = NULL;
+ link->next_ent = aasworld.arealinkedentities[-nodenum];
+ if (aasworld.arealinkedentities[-nodenum])
+ aasworld.arealinkedentities[-nodenum]->prev_ent = link;
+ aasworld.arealinkedentities[-nodenum] = link;
+ //
+ continue;
+ } //end if
+ //if solid leaf
+ if (!nodenum) continue;
+ //the node to test against
+ aasnode = &aasworld.nodes[nodenum];
+ //the current node plane
+ plane = &aasworld.planes[aasnode->planenum];
+ //get the side(s) the box is situated relative to the plane
+ side = AAS_BoxOnPlaneSide2(absmins, absmaxs, plane);
+ //if on the front side of the node
+ if (side & 1)
+ {
+ lstack_p->nodenum = aasnode->children[0];
+ lstack_p++;
+ } //end if
+ if (lstack_p >= &linkstack[127])
+ {
+ botimport.Print(PRT_ERROR, "AAS_LinkEntity: stack overflow\n");
+ break;
+ } //end if
+ //if on the back side of the node
+ if (side & 2)
+ {
+ lstack_p->nodenum = aasnode->children[1];
+ lstack_p++;
+ } //end if
+ if (lstack_p >= &linkstack[127])
+ {
+ botimport.Print(PRT_ERROR, "AAS_LinkEntity: stack overflow\n");
+ break;
+ } //end if
+ } //end while
+ return areas;
+} //end of the function AAS_AASLinkEntity
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+aas_link_t *AAS_LinkEntityClientBBox(vec3_t absmins, vec3_t absmaxs, int entnum, int presencetype)
+{
+ vec3_t mins, maxs;
+ vec3_t newabsmins, newabsmaxs;
+
+ AAS_PresenceTypeBoundingBox(presencetype, mins, maxs);
+ VectorSubtract(absmins, maxs, newabsmins);
+ VectorSubtract(absmaxs, mins, newabsmaxs);
+ //relink the entity
+ return AAS_AASLinkEntity(newabsmins, newabsmaxs, entnum);
+} //end of the function AAS_LinkEntityClientBBox
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_BBoxAreas(vec3_t absmins, vec3_t absmaxs, int *areas, int maxareas)
+{
+ aas_link_t *linkedareas, *link;
+ int num;
+
+ linkedareas = AAS_AASLinkEntity(absmins, absmaxs, -1);
+ num = 0;
+ for (link = linkedareas; link; link = link->next_area)
+ {
+ areas[num] = link->areanum;
+ num++;
+ if (num >= maxareas)
+ break;
+ } //end for
+ AAS_UnlinkFromAreas(linkedareas);
+ return num;
+} //end of the function AAS_BBoxAreas
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_AreaInfo( int areanum, aas_areainfo_t *info )
+{
+ aas_areasettings_t *settings;
+ if (!info)
+ return 0;
+ if (areanum <= 0 || areanum >= aasworld.numareas)
+ {
+ botimport.Print(PRT_ERROR, "AAS_AreaInfo: areanum %d out of range\n", areanum);
+ return 0;
+ } //end if
+ settings = &aasworld.areasettings[areanum];
+ info->cluster = settings->cluster;
+ info->contents = settings->contents;
+ info->flags = settings->areaflags;
+ info->presencetype = settings->presencetype;
+ VectorCopy(aasworld.areas[areanum].mins, info->mins);
+ VectorCopy(aasworld.areas[areanum].maxs, info->maxs);
+ VectorCopy(aasworld.areas[areanum].center, info->center);
+ return sizeof(aas_areainfo_t);
+} //end of the function AAS_AreaInfo
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+aas_plane_t *AAS_PlaneFromNum(int planenum)
+{
+ if (!aasworld.loaded) return 0;
+
+ return &aasworld.planes[planenum];
+} //end of the function AAS_PlaneFromNum
diff --git a/code/botlib/be_aas_sample.h b/code/botlib/be_aas_sample.h
new file mode 100755
index 0000000..6c2fc7e
--- /dev/null
+++ b/code/botlib/be_aas_sample.h
@@ -0,0 +1,69 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_aas_sample.h
+ *
+ * desc: AAS
+ *
+ * $Archive: /source/code/botlib/be_aas_sample.h $
+ *
+ *****************************************************************************/
+
+#ifdef AASINTERN
+void AAS_InitAASLinkHeap(void);
+void AAS_InitAASLinkedEntities(void);
+void AAS_FreeAASLinkHeap(void);
+void AAS_FreeAASLinkedEntities(void);
+aas_face_t *AAS_AreaGroundFace(int areanum, vec3_t point);
+aas_face_t *AAS_TraceEndFace(aas_trace_t *trace);
+aas_plane_t *AAS_PlaneFromNum(int planenum);
+aas_link_t *AAS_AASLinkEntity(vec3_t absmins, vec3_t absmaxs, int entnum);
+aas_link_t *AAS_LinkEntityClientBBox(vec3_t absmins, vec3_t absmaxs, int entnum, int presencetype);
+qboolean AAS_PointInsideFace(int facenum, vec3_t point, float epsilon);
+qboolean AAS_InsideFace(aas_face_t *face, vec3_t pnormal, vec3_t point, float epsilon);
+void AAS_UnlinkFromAreas(aas_link_t *areas);
+#endif //AASINTERN
+
+//returns the mins and maxs of the bounding box for the given presence type
+void AAS_PresenceTypeBoundingBox(int presencetype, vec3_t mins, vec3_t maxs);
+//returns the cluster the area is in (negative portal number if the area is a portal)
+int AAS_AreaCluster(int areanum);
+//returns the presence type(s) of the area
+int AAS_AreaPresenceType(int areanum);
+//returns the presence type(s) at the given point
+int AAS_PointPresenceType(vec3_t point);
+//returns the result of the trace of a client bbox
+aas_trace_t AAS_TraceClientBBox(vec3_t start, vec3_t end, int presencetype, int passent);
+//stores the areas the trace went through and returns the number of passed areas
+int AAS_TraceAreas(vec3_t start, vec3_t end, int *areas, vec3_t *points, int maxareas);
+//returns the areas the bounding box is in
+int AAS_BBoxAreas(vec3_t absmins, vec3_t absmaxs, int *areas, int maxareas);
+//return area information
+int AAS_AreaInfo( int areanum, aas_areainfo_t *info );
+//returns the area the point is in
+int AAS_PointAreaNum(vec3_t point);
+//
+int AAS_PointReachabilityAreaIndex( vec3_t point );
+//returns the plane the given face is in
+void AAS_FacePlane(int facenum, vec3_t normal, float *dist);
+
diff --git a/code/botlib/be_ai_char.c b/code/botlib/be_ai_char.c
new file mode 100755
index 0000000..042adb4
--- /dev/null
+++ b/code/botlib/be_ai_char.c
@@ -0,0 +1,790 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_ai_char.c
+ *
+ * desc: bot characters
+ *
+ * $Archive: /MissionPack/code/botlib/be_ai_char.c $
+ *
+ *****************************************************************************/
+
+#include "../game/q_shared.h"
+#include "l_log.h"
+#include "l_memory.h"
+#include "l_utils.h"
+#include "l_script.h"
+#include "l_precomp.h"
+#include "l_struct.h"
+#include "l_libvar.h"
+#include "aasfile.h"
+#include "../game/botlib.h"
+#include "../game/be_aas.h"
+#include "be_aas_funcs.h"
+#include "be_interface.h"
+#include "../game/be_ai_char.h"
+
+#define MAX_CHARACTERISTICS 80
+
+#define CT_INTEGER 1
+#define CT_FLOAT 2
+#define CT_STRING 3
+
+#define DEFAULT_CHARACTER "bots/default_c.c"
+
+//characteristic value
+union cvalue
+{
+ int integer;
+ float _float;
+ char *string;
+};
+//a characteristic
+typedef struct bot_characteristic_s
+{
+ char type; //characteristic type
+ union cvalue value; //characteristic value
+} bot_characteristic_t;
+
+//a bot character
+typedef struct bot_character_s
+{
+ char filename[MAX_QPATH];
+ float skill;
+ bot_characteristic_t c[1]; //variable sized
+} bot_character_t;
+
+bot_character_t *botcharacters[MAX_CLIENTS + 1];
+
+//========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//========================================================================
+bot_character_t *BotCharacterFromHandle(int handle)
+{
+ if (handle <= 0 || handle > MAX_CLIENTS)
+ {
+ botimport.Print(PRT_FATAL, "character handle %d out of range\n", handle);
+ return NULL;
+ } //end if
+ if (!botcharacters[handle])
+ {
+ botimport.Print(PRT_FATAL, "invalid character %d\n", handle);
+ return NULL;
+ } //end if
+ return botcharacters[handle];
+} //end of the function BotCharacterFromHandle
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotDumpCharacter(bot_character_t *ch)
+{
+ int i;
+
+ Log_Write("%s", ch->filename);
+ Log_Write("skill %d\n", ch->skill);
+ Log_Write("{\n");
+ for (i = 0; i < MAX_CHARACTERISTICS; i++)
+ {
+ switch(ch->c[i].type)
+ {
+ case CT_INTEGER: Log_Write(" %4d %d\n", i, ch->c[i].value.integer); break;
+ case CT_FLOAT: Log_Write(" %4d %f\n", i, ch->c[i].value._float); break;
+ case CT_STRING: Log_Write(" %4d %s\n", i, ch->c[i].value.string); break;
+ } //end case
+ } //end for
+ Log_Write("}\n");
+} //end of the function BotDumpCharacter
+//========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//========================================================================
+void BotFreeCharacterStrings(bot_character_t *ch)
+{
+ int i;
+
+ for (i = 0; i < MAX_CHARACTERISTICS; i++)
+ {
+ if (ch->c[i].type == CT_STRING)
+ {
+ FreeMemory(ch->c[i].value.string);
+ } //end if
+ } //end for
+} //end of the function BotFreeCharacterStrings
+//========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//========================================================================
+void BotFreeCharacter2(int handle)
+{
+ if (handle <= 0 || handle > MAX_CLIENTS)
+ {
+ botimport.Print(PRT_FATAL, "character handle %d out of range\n", handle);
+ return;
+ } //end if
+ if (!botcharacters[handle])
+ {
+ botimport.Print(PRT_FATAL, "invalid character %d\n", handle);
+ return;
+ } //end if
+ BotFreeCharacterStrings(botcharacters[handle]);
+ FreeMemory(botcharacters[handle]);
+ botcharacters[handle] = NULL;
+} //end of the function BotFreeCharacter2
+//========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//========================================================================
+void BotFreeCharacter(int handle)
+{
+ if (!LibVarGetValue("bot_reloadcharacters")) return;
+ BotFreeCharacter2(handle);
+} //end of the function BotFreeCharacter
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotDefaultCharacteristics(bot_character_t *ch, bot_character_t *defaultch)
+{
+ int i;
+
+ for (i = 0; i < MAX_CHARACTERISTICS; i++)
+ {
+ if (ch->c[i].type) continue;
+ //
+ if (defaultch->c[i].type == CT_FLOAT)
+ {
+ ch->c[i].type = CT_FLOAT;
+ ch->c[i].value._float = defaultch->c[i].value._float;
+ } //end if
+ else if (defaultch->c[i].type == CT_INTEGER)
+ {
+ ch->c[i].type = CT_INTEGER;
+ ch->c[i].value.integer = defaultch->c[i].value.integer;
+ } //end else if
+ else if (defaultch->c[i].type == CT_STRING)
+ {
+ ch->c[i].type = CT_STRING;
+ ch->c[i].value.string = (char *) GetMemory(strlen(defaultch->c[i].value.string)+1);
+ strcpy(ch->c[i].value.string, defaultch->c[i].value.string);
+ } //end else if
+ } //end for
+} //end of the function BotDefaultCharacteristics
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_character_t *BotLoadCharacterFromFile(char *charfile, int skill)
+{
+ int indent, index, foundcharacter;
+ bot_character_t *ch;
+ source_t *source;
+ token_t token;
+
+ foundcharacter = qfalse;
+ //a bot character is parsed in two phases
+ PC_SetBaseFolder(BOTFILESBASEFOLDER);
+ source = LoadSourceFile(charfile);
+ if (!source)
+ {
+ botimport.Print(PRT_ERROR, "counldn't load %s\n", charfile);
+ return NULL;
+ } //end if
+ ch = (bot_character_t *) GetClearedMemory(sizeof(bot_character_t) +
+ MAX_CHARACTERISTICS * sizeof(bot_characteristic_t));
+ strcpy(ch->filename, charfile);
+ while(PC_ReadToken(source, &token))
+ {
+ if (!strcmp(token.string, "skill"))
+ {
+ if (!PC_ExpectTokenType(source, TT_NUMBER, 0, &token))
+ {
+ FreeSource(source);
+ BotFreeCharacterStrings(ch);
+ FreeMemory(ch);
+ return NULL;
+ } //end if
+ if (!PC_ExpectTokenString(source, "{"))
+ {
+ FreeSource(source);
+ BotFreeCharacterStrings(ch);
+ FreeMemory(ch);
+ return NULL;
+ } //end if
+ //if it's the correct skill
+ if (skill < 0 || token.intvalue == skill)
+ {
+ foundcharacter = qtrue;
+ ch->skill = token.intvalue;
+ while(PC_ExpectAnyToken(source, &token))
+ {
+ if (!strcmp(token.string, "}")) break;
+ if (token.type != TT_NUMBER || !(token.subtype & TT_INTEGER))
+ {
+ SourceError(source, "expected integer index, found %s\n", token.string);
+ FreeSource(source);
+ BotFreeCharacterStrings(ch);
+ FreeMemory(ch);
+ return NULL;
+ } //end if
+ index = token.intvalue;
+ if (index < 0 || index > MAX_CHARACTERISTICS)
+ {
+ SourceError(source, "characteristic index out of range [0, %d]\n", MAX_CHARACTERISTICS);
+ FreeSource(source);
+ BotFreeCharacterStrings(ch);
+ FreeMemory(ch);
+ return NULL;
+ } //end if
+ if (ch->c[index].type)
+ {
+ SourceError(source, "characteristic %d already initialized\n", index);
+ FreeSource(source);
+ BotFreeCharacterStrings(ch);
+ FreeMemory(ch);
+ return NULL;
+ } //end if
+ if (!PC_ExpectAnyToken(source, &token))
+ {
+ FreeSource(source);
+ BotFreeCharacterStrings(ch);
+ FreeMemory(ch);
+ return NULL;
+ } //end if
+ if (token.type == TT_NUMBER)
+ {
+ if (token.subtype & TT_FLOAT)
+ {
+ ch->c[index].value._float = token.floatvalue;
+ ch->c[index].type = CT_FLOAT;
+ } //end if
+ else
+ {
+ ch->c[index].value.integer = token.intvalue;
+ ch->c[index].type = CT_INTEGER;
+ } //end else
+ } //end if
+ else if (token.type == TT_STRING)
+ {
+ StripDoubleQuotes(token.string);
+ ch->c[index].value.string = GetMemory(strlen(token.string)+1);
+ strcpy(ch->c[index].value.string, token.string);
+ ch->c[index].type = CT_STRING;
+ } //end else if
+ else
+ {
+ SourceError(source, "expected integer, float or string, found %s\n", token.string);
+ FreeSource(source);
+ BotFreeCharacterStrings(ch);
+ FreeMemory(ch);
+ return NULL;
+ } //end else
+ } //end if
+ break;
+ } //end if
+ else
+ {
+ indent = 1;
+ while(indent)
+ {
+ if (!PC_ExpectAnyToken(source, &token))
+ {
+ FreeSource(source);
+ BotFreeCharacterStrings(ch);
+ FreeMemory(ch);
+ return NULL;
+ } //end if
+ if (!strcmp(token.string, "{")) indent++;
+ else if (!strcmp(token.string, "}")) indent--;
+ } //end while
+ } //end else
+ } //end if
+ else
+ {
+ SourceError(source, "unknown definition %s\n", token.string);
+ FreeSource(source);
+ BotFreeCharacterStrings(ch);
+ FreeMemory(ch);
+ return NULL;
+ } //end else
+ } //end while
+ FreeSource(source);
+ //
+ if (!foundcharacter)
+ {
+ BotFreeCharacterStrings(ch);
+ FreeMemory(ch);
+ return NULL;
+ } //end if
+ return ch;
+} //end of the function BotLoadCharacterFromFile
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotFindCachedCharacter(char *charfile, float skill)
+{
+ int handle;
+
+ for (handle = 1; handle <= MAX_CLIENTS; handle++)
+ {
+ if ( !botcharacters[handle] ) continue;
+ if ( strcmp( botcharacters[handle]->filename, charfile ) == 0 &&
+ (skill < 0 || fabs(botcharacters[handle]->skill - skill) < 0.01) )
+ {
+ return handle;
+ } //end if
+ } //end for
+ return 0;
+} //end of the function BotFindCachedCharacter
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotLoadCachedCharacter(char *charfile, float skill, int reload)
+{
+ int handle, cachedhandle, intskill;
+ bot_character_t *ch = NULL;
+#ifdef DEBUG
+ int starttime;
+
+ starttime = Sys_MilliSeconds();
+#endif //DEBUG
+
+ //find a free spot for a character
+ for (handle = 1; handle <= MAX_CLIENTS; handle++)
+ {
+ if (!botcharacters[handle]) break;
+ } //end for
+ if (handle > MAX_CLIENTS) return 0;
+ //try to load a cached character with the given skill
+ if (!reload)
+ {
+ cachedhandle = BotFindCachedCharacter(charfile, skill);
+ if (cachedhandle)
+ {
+ botimport.Print(PRT_MESSAGE, "loaded cached skill %f from %s\n", skill, charfile);
+ return cachedhandle;
+ } //end if
+ } //end else
+ //
+ intskill = (int) (skill + 0.5);
+ //try to load the character with the given skill
+ ch = BotLoadCharacterFromFile(charfile, intskill);
+ if (ch)
+ {
+ botcharacters[handle] = ch;
+ //
+ botimport.Print(PRT_MESSAGE, "loaded skill %d from %s\n", intskill, charfile);
+#ifdef DEBUG
+ if (bot_developer)
+ {
+ botimport.Print(PRT_MESSAGE, "skill %d loaded in %d msec from %s\n", intskill, Sys_MilliSeconds() - starttime, charfile);
+ } //end if
+#endif //DEBUG
+ return handle;
+ } //end if
+ //
+ botimport.Print(PRT_WARNING, "couldn't find skill %d in %s\n", intskill, charfile);
+ //
+ if (!reload)
+ {
+ //try to load a cached default character with the given skill
+ cachedhandle = BotFindCachedCharacter(DEFAULT_CHARACTER, skill);
+ if (cachedhandle)
+ {
+ botimport.Print(PRT_MESSAGE, "loaded cached default skill %d from %s\n", intskill, charfile);
+ return cachedhandle;
+ } //end if
+ } //end if
+ //try to load the default character with the given skill
+ ch = BotLoadCharacterFromFile(DEFAULT_CHARACTER, intskill);
+ if (ch)
+ {
+ botcharacters[handle] = ch;
+ botimport.Print(PRT_MESSAGE, "loaded default skill %d from %s\n", intskill, charfile);
+ return handle;
+ } //end if
+ //
+ if (!reload)
+ {
+ //try to load a cached character with any skill
+ cachedhandle = BotFindCachedCharacter(charfile, -1);
+ if (cachedhandle)
+ {
+ botimport.Print(PRT_MESSAGE, "loaded cached skill %f from %s\n", botcharacters[cachedhandle]->skill, charfile);
+ return cachedhandle;
+ } //end if
+ } //end if
+ //try to load a character with any skill
+ ch = BotLoadCharacterFromFile(charfile, -1);
+ if (ch)
+ {
+ botcharacters[handle] = ch;
+ botimport.Print(PRT_MESSAGE, "loaded skill %f from %s\n", ch->skill, charfile);
+ return handle;
+ } //end if
+ //
+ if (!reload)
+ {
+ //try to load a cached character with any skill
+ cachedhandle = BotFindCachedCharacter(DEFAULT_CHARACTER, -1);
+ if (cachedhandle)
+ {
+ botimport.Print(PRT_MESSAGE, "loaded cached default skill %f from %s\n", botcharacters[cachedhandle]->skill, charfile);
+ return cachedhandle;
+ } //end if
+ } //end if
+ //try to load a character with any skill
+ ch = BotLoadCharacterFromFile(DEFAULT_CHARACTER, -1);
+ if (ch)
+ {
+ botcharacters[handle] = ch;
+ botimport.Print(PRT_MESSAGE, "loaded default skill %f from %s\n", ch->skill, charfile);
+ return handle;
+ } //end if
+ //
+ botimport.Print(PRT_WARNING, "couldn't load any skill from %s\n", charfile);
+ //couldn't load any character
+ return 0;
+} //end of the function BotLoadCachedCharacter
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotLoadCharacterSkill(char *charfile, float skill)
+{
+ int ch, defaultch;
+
+ defaultch = BotLoadCachedCharacter(DEFAULT_CHARACTER, skill, qfalse);
+ ch = BotLoadCachedCharacter(charfile, skill, LibVarGetValue("bot_reloadcharacters"));
+
+ if (defaultch && ch)
+ {
+ BotDefaultCharacteristics(botcharacters[ch], botcharacters[defaultch]);
+ } //end if
+
+ return ch;
+} //end of the function BotLoadCharacterSkill
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotInterpolateCharacters(int handle1, int handle2, float desiredskill)
+{
+ bot_character_t *ch1, *ch2, *out;
+ int i, handle;
+ float scale;
+
+ ch1 = BotCharacterFromHandle(handle1);
+ ch2 = BotCharacterFromHandle(handle2);
+ if (!ch1 || !ch2)
+ return 0;
+ //find a free spot for a character
+ for (handle = 1; handle <= MAX_CLIENTS; handle++)
+ {
+ if (!botcharacters[handle]) break;
+ } //end for
+ if (handle > MAX_CLIENTS) return 0;
+ out = (bot_character_t *) GetClearedMemory(sizeof(bot_character_t) +
+ MAX_CHARACTERISTICS * sizeof(bot_characteristic_t));
+ out->skill = desiredskill;
+ strcpy(out->filename, ch1->filename);
+ botcharacters[handle] = out;
+
+ scale = (float) (desiredskill - ch1->skill) / (ch2->skill - ch1->skill);
+ for (i = 0; i < MAX_CHARACTERISTICS; i++)
+ {
+ //
+ if (ch1->c[i].type == CT_FLOAT && ch2->c[i].type == CT_FLOAT)
+ {
+ out->c[i].type = CT_FLOAT;
+ out->c[i].value._float = ch1->c[i].value._float +
+ (ch2->c[i].value._float - ch1->c[i].value._float) * scale;
+ } //end if
+ else if (ch1->c[i].type == CT_INTEGER)
+ {
+ out->c[i].type = CT_INTEGER;
+ out->c[i].value.integer = ch1->c[i].value.integer;
+ } //end else if
+ else if (ch1->c[i].type == CT_STRING)
+ {
+ out->c[i].type = CT_STRING;
+ out->c[i].value.string = (char *) GetMemory(strlen(ch1->c[i].value.string)+1);
+ strcpy(out->c[i].value.string, ch1->c[i].value.string);
+ } //end else if
+ } //end for
+ return handle;
+} //end of the function BotInterpolateCharacters
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotLoadCharacter(char *charfile, float skill)
+{
+ int firstskill, secondskill, handle;
+
+ //make sure the skill is in the valid range
+ if (skill < 1.0) skill = 1.0;
+ else if (skill > 5.0) skill = 5.0;
+ //skill 1, 4 and 5 should be available in the character files
+ if (skill == 1.0 || skill == 4.0 || skill == 5.0)
+ {
+ return BotLoadCharacterSkill(charfile, skill);
+ } //end if
+ //check if there's a cached skill
+ handle = BotFindCachedCharacter(charfile, skill);
+ if (handle)
+ {
+ botimport.Print(PRT_MESSAGE, "loaded cached skill %f from %s\n", skill, charfile);
+ return handle;
+ } //end if
+ if (skill < 4.0)
+ {
+ //load skill 1 and 4
+ firstskill = BotLoadCharacterSkill(charfile, 1);
+ if (!firstskill) return 0;
+ secondskill = BotLoadCharacterSkill(charfile, 4);
+ if (!secondskill) return firstskill;
+ } //end if
+ else
+ {
+ //load skill 4 and 5
+ firstskill = BotLoadCharacterSkill(charfile, 4);
+ if (!firstskill) return 0;
+ secondskill = BotLoadCharacterSkill(charfile, 5);
+ if (!secondskill) return firstskill;
+ } //end else
+ //interpolate between the two skills
+ handle = BotInterpolateCharacters(firstskill, secondskill, skill);
+ if (!handle) return 0;
+ //write the character to the log file
+ BotDumpCharacter(botcharacters[handle]);
+ //
+ return handle;
+} //end of the function BotLoadCharacter
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int CheckCharacteristicIndex(int character, int index)
+{
+ bot_character_t *ch;
+
+ ch = BotCharacterFromHandle(character);
+ if (!ch) return qfalse;
+ if (index < 0 || index >= MAX_CHARACTERISTICS)
+ {
+ botimport.Print(PRT_ERROR, "characteristic %d does not exist\n", index);
+ return qfalse;
+ } //end if
+ if (!ch->c[index].type)
+ {
+ botimport.Print(PRT_ERROR, "characteristic %d is not initialized\n", index);
+ return qfalse;
+ } //end if
+ return qtrue;
+} //end of the function CheckCharacteristicIndex
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float Characteristic_Float(int character, int index)
+{
+ bot_character_t *ch;
+
+ ch = BotCharacterFromHandle(character);
+ if (!ch) return 0;
+ //check if the index is in range
+ if (!CheckCharacteristicIndex(character, index)) return 0;
+ //an integer will be converted to a float
+ if (ch->c[index].type == CT_INTEGER)
+ {
+ return (float) ch->c[index].value.integer;
+ } //end if
+ //floats are just returned
+ else if (ch->c[index].type == CT_FLOAT)
+ {
+ return ch->c[index].value._float;
+ } //end else if
+ //cannot convert a string pointer to a float
+ else
+ {
+ botimport.Print(PRT_ERROR, "characteristic %d is not a float\n", index);
+ return 0;
+ } //end else if
+// return 0;
+} //end of the function Characteristic_Float
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float Characteristic_BFloat(int character, int index, float min, float max)
+{
+ float value;
+ bot_character_t *ch;
+
+ ch = BotCharacterFromHandle(character);
+ if (!ch) return 0;
+ if (min > max)
+ {
+ botimport.Print(PRT_ERROR, "cannot bound characteristic %d between %f and %f\n", index, min, max);
+ return 0;
+ } //end if
+ value = Characteristic_Float(character, index);
+ if (value < min) return min;
+ if (value > max) return max;
+ return value;
+} //end of the function Characteristic_BFloat
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int Characteristic_Integer(int character, int index)
+{
+ bot_character_t *ch;
+
+ ch = BotCharacterFromHandle(character);
+ if (!ch) return 0;
+ //check if the index is in range
+ if (!CheckCharacteristicIndex(character, index)) return 0;
+ //an integer will just be returned
+ if (ch->c[index].type == CT_INTEGER)
+ {
+ return ch->c[index].value.integer;
+ } //end if
+ //floats are casted to integers
+ else if (ch->c[index].type == CT_FLOAT)
+ {
+ return (int) ch->c[index].value._float;
+ } //end else if
+ else
+ {
+ botimport.Print(PRT_ERROR, "characteristic %d is not a integer\n", index);
+ return 0;
+ } //end else if
+// return 0;
+} //end of the function Characteristic_Integer
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int Characteristic_BInteger(int character, int index, int min, int max)
+{
+ int value;
+ bot_character_t *ch;
+
+ ch = BotCharacterFromHandle(character);
+ if (!ch) return 0;
+ if (min > max)
+ {
+ botimport.Print(PRT_ERROR, "cannot bound characteristic %d between %d and %d\n", index, min, max);
+ return 0;
+ } //end if
+ value = Characteristic_Integer(character, index);
+ if (value < min) return min;
+ if (value > max) return max;
+ return value;
+} //end of the function Characteristic_BInteger
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Characteristic_String(int character, int index, char *buf, int size)
+{
+ bot_character_t *ch;
+
+ ch = BotCharacterFromHandle(character);
+ if (!ch) return;
+ //check if the index is in range
+ if (!CheckCharacteristicIndex(character, index)) return;
+ //an integer will be converted to a float
+ if (ch->c[index].type == CT_STRING)
+ {
+ strncpy(buf, ch->c[index].value.string, size-1);
+ buf[size-1] = '\0';
+ return;
+ } //end if
+ else
+ {
+ botimport.Print(PRT_ERROR, "characteristic %d is not a string\n", index);
+ return;
+ } //end else if
+ return;
+} //end of the function Characteristic_String
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotShutdownCharacters(void)
+{
+ int handle;
+
+ for (handle = 1; handle <= MAX_CLIENTS; handle++)
+ {
+ if (botcharacters[handle])
+ {
+ BotFreeCharacter2(handle);
+ } //end if
+ } //end for
+} //end of the function BotShutdownCharacters
+
diff --git a/code/botlib/be_ai_chat.c b/code/botlib/be_ai_chat.c
new file mode 100755
index 0000000..9483e9b
--- /dev/null
+++ b/code/botlib/be_ai_chat.c
@@ -0,0 +1,3017 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_ai_chat.c
+ *
+ * desc: bot chat AI
+ *
+ * $Archive: /MissionPack/code/botlib/be_ai_chat.c $
+ *
+ *****************************************************************************/
+
+#include "../game/q_shared.h"
+#include "l_memory.h"
+#include "l_libvar.h"
+#include "l_script.h"
+#include "l_precomp.h"
+#include "l_struct.h"
+#include "l_utils.h"
+#include "l_log.h"
+#include "aasfile.h"
+#include "../game/botlib.h"
+#include "../game/be_aas.h"
+#include "be_aas_funcs.h"
+#include "be_interface.h"
+#include "../game/be_ea.h"
+#include "../game/be_ai_chat.h"
+
+
+//escape character
+#define ESCAPE_CHAR 0x01 //'_'
+//
+// "hi ", people, " ", 0, " entered the game"
+//becomes:
+// "hi _rpeople_ _v0_ entered the game"
+//
+
+//match piece types
+#define MT_VARIABLE 1 //variable match piece
+#define MT_STRING 2 //string match piece
+//reply chat key flags
+#define RCKFL_AND 1 //key must be present
+#define RCKFL_NOT 2 //key must be absent
+#define RCKFL_NAME 4 //name of bot must be present
+#define RCKFL_STRING 8 //key is a string
+#define RCKFL_VARIABLES 16 //key is a match template
+#define RCKFL_BOTNAMES 32 //key is a series of botnames
+#define RCKFL_GENDERFEMALE 64 //bot must be female
+#define RCKFL_GENDERMALE 128 //bot must be male
+#define RCKFL_GENDERLESS 256 //bot must be genderless
+//time to ignore a chat message after using it
+#define CHATMESSAGE_RECENTTIME 20
+
+//the actuall chat messages
+typedef struct bot_chatmessage_s
+{
+ char *chatmessage; //chat message string
+ float time; //last time used
+ struct bot_chatmessage_s *next; //next chat message in a list
+} bot_chatmessage_t;
+//bot chat type with chat lines
+typedef struct bot_chattype_s
+{
+ char name[MAX_CHATTYPE_NAME];
+ int numchatmessages;
+ bot_chatmessage_t *firstchatmessage;
+ struct bot_chattype_s *next;
+} bot_chattype_t;
+//bot chat lines
+typedef struct bot_chat_s
+{
+ bot_chattype_t *types;
+} bot_chat_t;
+
+//random string
+typedef struct bot_randomstring_s
+{
+ char *string;
+ struct bot_randomstring_s *next;
+} bot_randomstring_t;
+//list with random strings
+typedef struct bot_randomlist_s
+{
+ char *string;
+ int numstrings;
+ bot_randomstring_t *firstrandomstring;
+ struct bot_randomlist_s *next;
+} bot_randomlist_t;
+
+//synonym
+typedef struct bot_synonym_s
+{
+ char *string;
+ float weight;
+ struct bot_synonym_s *next;
+} bot_synonym_t;
+//list with synonyms
+typedef struct bot_synonymlist_s
+{
+ unsigned long int context;
+ float totalweight;
+ bot_synonym_t *firstsynonym;
+ struct bot_synonymlist_s *next;
+} bot_synonymlist_t;
+
+//fixed match string
+typedef struct bot_matchstring_s
+{
+ char *string;
+ struct bot_matchstring_s *next;
+} bot_matchstring_t;
+
+//piece of a match template
+typedef struct bot_matchpiece_s
+{
+ int type;
+ bot_matchstring_t *firststring;
+ int variable;
+ struct bot_matchpiece_s *next;
+} bot_matchpiece_t;
+//match template
+typedef struct bot_matchtemplate_s
+{
+ unsigned long int context;
+ int type;
+ int subtype;
+ bot_matchpiece_t *first;
+ struct bot_matchtemplate_s *next;
+} bot_matchtemplate_t;
+
+//reply chat key
+typedef struct bot_replychatkey_s
+{
+ int flags;
+ char *string;
+ bot_matchpiece_t *match;
+ struct bot_replychatkey_s *next;
+} bot_replychatkey_t;
+//reply chat
+typedef struct bot_replychat_s
+{
+ bot_replychatkey_t *keys;
+ float priority;
+ int numchatmessages;
+ bot_chatmessage_t *firstchatmessage;
+ struct bot_replychat_s *next;
+} bot_replychat_t;
+
+//string list
+typedef struct bot_stringlist_s
+{
+ char *string;
+ struct bot_stringlist_s *next;
+} bot_stringlist_t;
+
+//chat state of a bot
+typedef struct bot_chatstate_s
+{
+ int gender; //0=it, 1=female, 2=male
+ int client; //client number
+ char name[32]; //name of the bot
+ char chatmessage[MAX_MESSAGE_SIZE];
+ int handle;
+ //the console messages visible to the bot
+ bot_consolemessage_t *firstmessage; //first message is the first typed message
+ bot_consolemessage_t *lastmessage; //last message is the last typed message, bottom of console
+ //number of console messages stored in the state
+ int numconsolemessages;
+ //the bot chat lines
+ bot_chat_t *chat;
+} bot_chatstate_t;
+
+typedef struct {
+ bot_chat_t *chat;
+ char filename[MAX_QPATH];
+ char chatname[MAX_QPATH];
+} bot_ichatdata_t;
+
+bot_ichatdata_t *ichatdata[MAX_CLIENTS];
+
+bot_chatstate_t *botchatstates[MAX_CLIENTS+1];
+//console message heap
+bot_consolemessage_t *consolemessageheap = NULL;
+bot_consolemessage_t *freeconsolemessages = NULL;
+//list with match strings
+bot_matchtemplate_t *matchtemplates = NULL;
+//list with synonyms
+bot_synonymlist_t *synonyms = NULL;
+//list with random strings
+bot_randomlist_t *randomstrings = NULL;
+//reply chats
+bot_replychat_t *replychats = NULL;
+
+//========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//========================================================================
+bot_chatstate_t *BotChatStateFromHandle(int handle)
+{
+ if (handle <= 0 || handle > MAX_CLIENTS)
+ {
+ botimport.Print(PRT_FATAL, "chat state handle %d out of range\n", handle);
+ return NULL;
+ } //end if
+ if (!botchatstates[handle])
+ {
+ botimport.Print(PRT_FATAL, "invalid chat state %d\n", handle);
+ return NULL;
+ } //end if
+ return botchatstates[handle];
+} //end of the function BotChatStateFromHandle
+//===========================================================================
+// initialize the heap with unused console messages
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void InitConsoleMessageHeap(void)
+{
+ int i, max_messages;
+
+ if (consolemessageheap) FreeMemory(consolemessageheap);
+ //
+ max_messages = (int) LibVarValue("max_messages", "1024");
+ consolemessageheap = (bot_consolemessage_t *) GetClearedHunkMemory(max_messages *
+ sizeof(bot_consolemessage_t));
+ consolemessageheap[0].prev = NULL;
+ consolemessageheap[0].next = &consolemessageheap[1];
+ for (i = 1; i < max_messages-1; i++)
+ {
+ consolemessageheap[i].prev = &consolemessageheap[i - 1];
+ consolemessageheap[i].next = &consolemessageheap[i + 1];
+ } //end for
+ consolemessageheap[max_messages-1].prev = &consolemessageheap[max_messages-2];
+ consolemessageheap[max_messages-1].next = NULL;
+ //pointer to the free console messages
+ freeconsolemessages = consolemessageheap;
+} //end of the function InitConsoleMessageHeap
+//===========================================================================
+// allocate one console message from the heap
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_consolemessage_t *AllocConsoleMessage(void)
+{
+ bot_consolemessage_t *message;
+ message = freeconsolemessages;
+ if (freeconsolemessages) freeconsolemessages = freeconsolemessages->next;
+ if (freeconsolemessages) freeconsolemessages->prev = NULL;
+ return message;
+} //end of the function AllocConsoleMessage
+//===========================================================================
+// deallocate one console message from the heap
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void FreeConsoleMessage(bot_consolemessage_t *message)
+{
+ if (freeconsolemessages) freeconsolemessages->prev = message;
+ message->prev = NULL;
+ message->next = freeconsolemessages;
+ freeconsolemessages = message;
+} //end of the function FreeConsoleMessage
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotRemoveConsoleMessage(int chatstate, int handle)
+{
+ bot_consolemessage_t *m, *nextm;
+ bot_chatstate_t *cs;
+
+ cs = BotChatStateFromHandle(chatstate);
+ if (!cs) return;
+
+ for (m = cs->firstmessage; m; m = nextm)
+ {
+ nextm = m->next;
+ if (m->handle == handle)
+ {
+ if (m->next) m->next->prev = m->prev;
+ else cs->lastmessage = m->prev;
+ if (m->prev) m->prev->next = m->next;
+ else cs->firstmessage = m->next;
+
+ FreeConsoleMessage(m);
+ cs->numconsolemessages--;
+ break;
+ } //end if
+ } //end for
+} //end of the function BotRemoveConsoleMessage
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotQueueConsoleMessage(int chatstate, int type, char *message)
+{
+ bot_consolemessage_t *m;
+ bot_chatstate_t *cs;
+
+ cs = BotChatStateFromHandle(chatstate);
+ if (!cs) return;
+
+ m = AllocConsoleMessage();
+ if (!m)
+ {
+ botimport.Print(PRT_ERROR, "empty console message heap\n");
+ return;
+ } //end if
+ cs->handle++;
+ if (cs->handle <= 0 || cs->handle > 8192) cs->handle = 1;
+ m->handle = cs->handle;
+ m->time = AAS_Time();
+ m->type = type;
+ strncpy(m->message, message, MAX_MESSAGE_SIZE);
+ m->next = NULL;
+ if (cs->lastmessage)
+ {
+ cs->lastmessage->next = m;
+ m->prev = cs->lastmessage;
+ cs->lastmessage = m;
+ } //end if
+ else
+ {
+ cs->lastmessage = m;
+ cs->firstmessage = m;
+ m->prev = NULL;
+ } //end if
+ cs->numconsolemessages++;
+} //end of the function BotQueueConsoleMessage
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotNextConsoleMessage(int chatstate, bot_consolemessage_t *cm)
+{
+ bot_chatstate_t *cs;
+
+ cs = BotChatStateFromHandle(chatstate);
+ if (!cs) return 0;
+ if (cs->firstmessage)
+ {
+ Com_Memcpy(cm, cs->firstmessage, sizeof(bot_consolemessage_t));
+ cm->next = cm->prev = NULL;
+ return cm->handle;
+ } //end if
+ return 0;
+} //end of the function BotConsoleMessage
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotNumConsoleMessages(int chatstate)
+{
+ bot_chatstate_t *cs;
+
+ cs = BotChatStateFromHandle(chatstate);
+ if (!cs) return 0;
+ return cs->numconsolemessages;
+} //end of the function BotNumConsoleMessages
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int IsWhiteSpace(char c)
+{
+ if ((c >= 'a' && c <= 'z')
+ || (c >= 'A' && c <= 'Z')
+ || (c >= '0' && c <= '9')
+ || c == '(' || c == ')'
+ || c == '?' || c == ':'
+ || c == '\''|| c == '/'
+ || c == ',' || c == '.'
+ || c == '[' || c == ']'
+ || c == '-' || c == '_'
+ || c == '+' || c == '=') return qfalse;
+ return qtrue;
+} //end of the function IsWhiteSpace
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotRemoveTildes(char *message)
+{
+ int i;
+
+ //remove all tildes from the chat message
+ for (i = 0; message[i]; i++)
+ {
+ if (message[i] == '~')
+ {
+ memmove(&message[i], &message[i+1], strlen(&message[i+1])+1);
+ } //end if
+ } //end for
+} //end of the function BotRemoveTildes
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void UnifyWhiteSpaces(char *string)
+{
+ char *ptr, *oldptr;
+
+ for (ptr = oldptr = string; *ptr; oldptr = ptr)
+ {
+ while(*ptr && IsWhiteSpace(*ptr)) ptr++;
+ if (ptr > oldptr)
+ {
+ //if not at the start and not at the end of the string
+ //write only one space
+ if (oldptr > string && *ptr) *oldptr++ = ' ';
+ //remove all other white spaces
+ if (ptr > oldptr) memmove(oldptr, ptr, strlen(ptr)+1);
+ } //end if
+ while(*ptr && !IsWhiteSpace(*ptr)) ptr++;
+ } //end while
+} //end of the function UnifyWhiteSpaces
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int StringContains(char *str1, char *str2, int casesensitive)
+{
+ int len, i, j, index;
+
+ if (str1 == NULL || str2 == NULL) return -1;
+
+ len = strlen(str1) - strlen(str2);
+ index = 0;
+ for (i = 0; i <= len; i++, str1++, index++)
+ {
+ for (j = 0; str2[j]; j++)
+ {
+ if (casesensitive)
+ {
+ if (str1[j] != str2[j]) break;
+ } //end if
+ else
+ {
+ if (toupper(str1[j]) != toupper(str2[j])) break;
+ } //end else
+ } //end for
+ if (!str2[j]) return index;
+ } //end for
+ return -1;
+} //end of the function StringContains
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+char *StringContainsWord(char *str1, char *str2, int casesensitive)
+{
+ int len, i, j;
+
+ len = strlen(str1) - strlen(str2);
+ for (i = 0; i <= len; i++, str1++)
+ {
+ //if not at the start of the string
+ if (i)
+ {
+ //skip to the start of the next word
+ while(*str1 && *str1 != ' ' && *str1 != '.' && *str1 != ',' && *str1 != '!') str1++;
+ if (!*str1) break;
+ str1++;
+ } //end for
+ //compare the word
+ for (j = 0; str2[j]; j++)
+ {
+ if (casesensitive)
+ {
+ if (str1[j] != str2[j]) break;
+ } //end if
+ else
+ {
+ if (toupper(str1[j]) != toupper(str2[j])) break;
+ } //end else
+ } //end for
+ //if there was a word match
+ if (!str2[j])
+ {
+ //if the first string has an end of word
+ if (!str1[j] || str1[j] == ' ' || str1[j] == '.' || str1[j] == ',' || str1[j] == '!') return str1;
+ } //end if
+ } //end for
+ return NULL;
+} //end of the function StringContainsWord
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void StringReplaceWords(char *string, char *synonym, char *replacement)
+{
+ char *str, *str2;
+
+ //find the synonym in the string
+ str = StringContainsWord(string, synonym, qfalse);
+ //if the synonym occured in the string
+ while(str)
+ {
+ //if the synonym isn't part of the replacement which is already in the string
+ //usefull for abreviations
+ str2 = StringContainsWord(string, replacement, qfalse);
+ while(str2)
+ {
+ if (str2 <= str && str < str2 + strlen(replacement)) break;
+ str2 = StringContainsWord(str2+1, replacement, qfalse);
+ } //end while
+ if (!str2)
+ {
+ memmove(str + strlen(replacement), str+strlen(synonym), strlen(str+strlen(synonym))+1);
+ //append the synonum replacement
+ Com_Memcpy(str, replacement, strlen(replacement));
+ } //end if
+ //find the next synonym in the string
+ str = StringContainsWord(str+strlen(replacement), synonym, qfalse);
+ } //end if
+} //end of the function StringReplaceWords
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotDumpSynonymList(bot_synonymlist_t *synlist)
+{
+ FILE *fp;
+ bot_synonymlist_t *syn;
+ bot_synonym_t *synonym;
+
+ fp = Log_FilePointer();
+ if (!fp) return;
+ for (syn = synlist; syn; syn = syn->next)
+ {
+ fprintf(fp, "%ld : [", syn->context);
+ for (synonym = syn->firstsynonym; synonym; synonym = synonym->next)
+ {
+ fprintf(fp, "(\"%s\", %1.2f)", synonym->string, synonym->weight);
+ if (synonym->next) fprintf(fp, ", ");
+ } //end for
+ fprintf(fp, "]\n");
+ } //end for
+} //end of the function BotDumpSynonymList
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_synonymlist_t *BotLoadSynonyms(char *filename)
+{
+ int pass, size, contextlevel, numsynonyms;
+ unsigned long int context, contextstack[32];
+ char *ptr = NULL;
+ source_t *source;
+ token_t token;
+ bot_synonymlist_t *synlist, *lastsyn, *syn;
+ bot_synonym_t *synonym, *lastsynonym;
+
+ size = 0;
+ synlist = NULL; //make compiler happy
+ syn = NULL; //make compiler happy
+ synonym = NULL; //make compiler happy
+ //the synonyms are parsed in two phases
+ for (pass = 0; pass < 2; pass++)
+ {
+ //
+ if (pass && size) ptr = (char *) GetClearedHunkMemory(size);
+ //
+ PC_SetBaseFolder(BOTFILESBASEFOLDER);
+ source = LoadSourceFile(filename);
+ if (!source)
+ {
+ botimport.Print(PRT_ERROR, "counldn't load %s\n", filename);
+ return NULL;
+ } //end if
+ //
+ context = 0;
+ contextlevel = 0;
+ synlist = NULL; //list synonyms
+ lastsyn = NULL; //last synonym in the list
+ //
+ while(PC_ReadToken(source, &token))
+ {
+ if (token.type == TT_NUMBER)
+ {
+ context |= token.intvalue;
+ contextstack[contextlevel] = token.intvalue;
+ contextlevel++;
+ if (contextlevel >= 32)
+ {
+ SourceError(source, "more than 32 context levels");
+ FreeSource(source);
+ return NULL;
+ } //end if
+ if (!PC_ExpectTokenString(source, "{"))
+ {
+ FreeSource(source);
+ return NULL;
+ } //end if
+ } //end if
+ else if (token.type == TT_PUNCTUATION)
+ {
+ if (!strcmp(token.string, "}"))
+ {
+ contextlevel--;
+ if (contextlevel < 0)
+ {
+ SourceError(source, "too many }");
+ FreeSource(source);
+ return NULL;
+ } //end if
+ context &= ~contextstack[contextlevel];
+ } //end if
+ else if (!strcmp(token.string, "["))
+ {
+ size += sizeof(bot_synonymlist_t);
+ if (pass)
+ {
+ syn = (bot_synonymlist_t *) ptr;
+ ptr += sizeof(bot_synonymlist_t);
+ syn->context = context;
+ syn->firstsynonym = NULL;
+ syn->next = NULL;
+ if (lastsyn) lastsyn->next = syn;
+ else synlist = syn;
+ lastsyn = syn;
+ } //end if
+ numsynonyms = 0;
+ lastsynonym = NULL;
+ while(1)
+ {
+ if (!PC_ExpectTokenString(source, "(") ||
+ !PC_ExpectTokenType(source, TT_STRING, 0, &token))
+ {
+ FreeSource(source);
+ return NULL;
+ } //end if
+ StripDoubleQuotes(token.string);
+ if (strlen(token.string) <= 0)
+ {
+ SourceError(source, "empty string", token.string);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ size += sizeof(bot_synonym_t) + strlen(token.string) + 1;
+ if (pass)
+ {
+ synonym = (bot_synonym_t *) ptr;
+ ptr += sizeof(bot_synonym_t);
+ synonym->string = ptr;
+ ptr += strlen(token.string) + 1;
+ strcpy(synonym->string, token.string);
+ //
+ if (lastsynonym) lastsynonym->next = synonym;
+ else syn->firstsynonym = synonym;
+ lastsynonym = synonym;
+ } //end if
+ numsynonyms++;
+ if (!PC_ExpectTokenString(source, ",") ||
+ !PC_ExpectTokenType(source, TT_NUMBER, 0, &token) ||
+ !PC_ExpectTokenString(source, ")"))
+ {
+ FreeSource(source);
+ return NULL;
+ } //end if
+ if (pass)
+ {
+ synonym->weight = token.floatvalue;
+ syn->totalweight += synonym->weight;
+ } //end if
+ if (PC_CheckTokenString(source, "]")) break;
+ if (!PC_ExpectTokenString(source, ","))
+ {
+ FreeSource(source);
+ return NULL;
+ } //end if
+ } //end while
+ if (numsynonyms < 2)
+ {
+ SourceError(source, "synonym must have at least two entries\n");
+ FreeSource(source);
+ return NULL;
+ } //end if
+ } //end else
+ else
+ {
+ SourceError(source, "unexpected %s", token.string);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ } //end else if
+ } //end while
+ //
+ FreeSource(source);
+ //
+ if (contextlevel > 0)
+ {
+ SourceError(source, "missing }");
+ return NULL;
+ } //end if
+ } //end for
+ botimport.Print(PRT_MESSAGE, "loaded %s\n", filename);
+ //
+ //BotDumpSynonymList(synlist);
+ //
+ return synlist;
+} //end of the function BotLoadSynonyms
+//===========================================================================
+// replace all the synonyms in the string
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotReplaceSynonyms(char *string, unsigned long int context)
+{
+ bot_synonymlist_t *syn;
+ bot_synonym_t *synonym;
+
+ for (syn = synonyms; syn; syn = syn->next)
+ {
+ if (!(syn->context & context)) continue;
+ for (synonym = syn->firstsynonym->next; synonym; synonym = synonym->next)
+ {
+ StringReplaceWords(string, synonym->string, syn->firstsynonym->string);
+ } //end for
+ } //end for
+} //end of the function BotReplaceSynonyms
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotReplaceWeightedSynonyms(char *string, unsigned long int context)
+{
+ bot_synonymlist_t *syn;
+ bot_synonym_t *synonym, *replacement;
+ float weight, curweight;
+
+ for (syn = synonyms; syn; syn = syn->next)
+ {
+ if (!(syn->context & context)) continue;
+ //choose a weighted random replacement synonym
+ weight = random() * syn->totalweight;
+ if (!weight) continue;
+ curweight = 0;
+ for (replacement = syn->firstsynonym; replacement; replacement = replacement->next)
+ {
+ curweight += replacement->weight;
+ if (weight < curweight) break;
+ } //end for
+ if (!replacement) continue;
+ //replace all synonyms with the replacement
+ for (synonym = syn->firstsynonym; synonym; synonym = synonym->next)
+ {
+ if (synonym == replacement) continue;
+ StringReplaceWords(string, synonym->string, replacement->string);
+ } //end for
+ } //end for
+} //end of the function BotReplaceWeightedSynonyms
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotReplaceReplySynonyms(char *string, unsigned long int context)
+{
+ char *str1, *str2, *replacement;
+ bot_synonymlist_t *syn;
+ bot_synonym_t *synonym;
+
+ for (str1 = string; *str1; )
+ {
+ //go to the start of the next word
+ while(*str1 && *str1 <= ' ') str1++;
+ if (!*str1) break;
+ //
+ for (syn = synonyms; syn; syn = syn->next)
+ {
+ if (!(syn->context & context)) continue;
+ for (synonym = syn->firstsynonym->next; synonym; synonym = synonym->next)
+ {
+ str2 = synonym->string;
+ //if the synonym is not at the front of the string continue
+ str2 = StringContainsWord(str1, synonym->string, qfalse);
+ if (!str2 || str2 != str1) continue;
+ //
+ replacement = syn->firstsynonym->string;
+ //if the replacement IS in front of the string continue
+ str2 = StringContainsWord(str1, replacement, qfalse);
+ if (str2 && str2 == str1) continue;
+ //
+ memmove(str1 + strlen(replacement), str1+strlen(synonym->string),
+ strlen(str1+strlen(synonym->string)) + 1);
+ //append the synonum replacement
+ Com_Memcpy(str1, replacement, strlen(replacement));
+ //
+ break;
+ } //end for
+ //if a synonym has been replaced
+ if (synonym) break;
+ } //end for
+ //skip over this word
+ while(*str1 && *str1 > ' ') str1++;
+ if (!*str1) break;
+ } //end while
+} //end of the function BotReplaceReplySynonyms
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotLoadChatMessage(source_t *source, char *chatmessagestring)
+{
+ char *ptr;
+ token_t token;
+
+ ptr = chatmessagestring;
+ *ptr = 0;
+ //
+ while(1)
+ {
+ if (!PC_ExpectAnyToken(source, &token)) return qfalse;
+ //fixed string
+ if (token.type == TT_STRING)
+ {
+ StripDoubleQuotes(token.string);
+ if (strlen(ptr) + strlen(token.string) + 1 > MAX_MESSAGE_SIZE)
+ {
+ SourceError(source, "chat message too long\n");
+ return qfalse;
+ } //end if
+ strcat(ptr, token.string);
+ } //end else if
+ //variable string
+ else if (token.type == TT_NUMBER && (token.subtype & TT_INTEGER))
+ {
+ if (strlen(ptr) + 7 > MAX_MESSAGE_SIZE)
+ {
+ SourceError(source, "chat message too long\n");
+ return qfalse;
+ } //end if
+ sprintf(&ptr[strlen(ptr)], "%cv%ld%c", ESCAPE_CHAR, token.intvalue, ESCAPE_CHAR);
+ } //end if
+ //random string
+ else if (token.type == TT_NAME)
+ {
+ if (strlen(ptr) + 7 > MAX_MESSAGE_SIZE)
+ {
+ SourceError(source, "chat message too long\n");
+ return qfalse;
+ } //end if
+ sprintf(&ptr[strlen(ptr)], "%cr%s%c", ESCAPE_CHAR, token.string, ESCAPE_CHAR);
+ } //end else if
+ else
+ {
+ SourceError(source, "unknown message component %s\n", token.string);
+ return qfalse;
+ } //end else
+ if (PC_CheckTokenString(source, ";")) break;
+ if (!PC_ExpectTokenString(source, ",")) return qfalse;
+ } //end while
+ //
+ return qtrue;
+} //end of the function BotLoadChatMessage
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotDumpRandomStringList(bot_randomlist_t *randomlist)
+{
+ FILE *fp;
+ bot_randomlist_t *random;
+ bot_randomstring_t *rs;
+
+ fp = Log_FilePointer();
+ if (!fp) return;
+ for (random = randomlist; random; random = random->next)
+ {
+ fprintf(fp, "%s = {", random->string);
+ for (rs = random->firstrandomstring; rs; rs = rs->next)
+ {
+ fprintf(fp, "\"%s\"", rs->string);
+ if (rs->next) fprintf(fp, ", ");
+ else fprintf(fp, "}\n");
+ } //end for
+ } //end for
+} //end of the function BotDumpRandomStringList
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_randomlist_t *BotLoadRandomStrings(char *filename)
+{
+ int pass, size;
+ char *ptr = NULL, chatmessagestring[MAX_MESSAGE_SIZE];
+ source_t *source;
+ token_t token;
+ bot_randomlist_t *randomlist, *lastrandom, *random;
+ bot_randomstring_t *randomstring;
+
+#ifdef DEBUG
+ int starttime = Sys_MilliSeconds();
+#endif //DEBUG
+
+ size = 0;
+ randomlist = NULL;
+ random = NULL;
+ //the synonyms are parsed in two phases
+ for (pass = 0; pass < 2; pass++)
+ {
+ //
+ if (pass && size) ptr = (char *) GetClearedHunkMemory(size);
+ //
+ PC_SetBaseFolder(BOTFILESBASEFOLDER);
+ source = LoadSourceFile(filename);
+ if (!source)
+ {
+ botimport.Print(PRT_ERROR, "counldn't load %s\n", filename);
+ return NULL;
+ } //end if
+ //
+ randomlist = NULL; //list
+ lastrandom = NULL; //last
+ //
+ while(PC_ReadToken(source, &token))
+ {
+ if (token.type != TT_NAME)
+ {
+ SourceError(source, "unknown random %s", token.string);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ size += sizeof(bot_randomlist_t) + strlen(token.string) + 1;
+ if (pass)
+ {
+ random = (bot_randomlist_t *) ptr;
+ ptr += sizeof(bot_randomlist_t);
+ random->string = ptr;
+ ptr += strlen(token.string) + 1;
+ strcpy(random->string, token.string);
+ random->firstrandomstring = NULL;
+ random->numstrings = 0;
+ //
+ if (lastrandom) lastrandom->next = random;
+ else randomlist = random;
+ lastrandom = random;
+ } //end if
+ if (!PC_ExpectTokenString(source, "=") ||
+ !PC_ExpectTokenString(source, "{"))
+ {
+ FreeSource(source);
+ return NULL;
+ } //end if
+ while(!PC_CheckTokenString(source, "}"))
+ {
+ if (!BotLoadChatMessage(source, chatmessagestring))
+ {
+ FreeSource(source);
+ return NULL;
+ } //end if
+ size += sizeof(bot_randomstring_t) + strlen(chatmessagestring) + 1;
+ if (pass)
+ {
+ randomstring = (bot_randomstring_t *) ptr;
+ ptr += sizeof(bot_randomstring_t);
+ randomstring->string = ptr;
+ ptr += strlen(chatmessagestring) + 1;
+ strcpy(randomstring->string, chatmessagestring);
+ //
+ random->numstrings++;
+ randomstring->next = random->firstrandomstring;
+ random->firstrandomstring = randomstring;
+ } //end if
+ } //end while
+ } //end while
+ //free the source after one pass
+ FreeSource(source);
+ } //end for
+ botimport.Print(PRT_MESSAGE, "loaded %s\n", filename);
+ //
+#ifdef DEBUG
+ botimport.Print(PRT_MESSAGE, "random strings %d msec\n", Sys_MilliSeconds() - starttime);
+ //BotDumpRandomStringList(randomlist);
+#endif //DEBUG
+ //
+ return randomlist;
+} //end of the function BotLoadRandomStrings
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+char *RandomString(char *name)
+{
+ bot_randomlist_t *random;
+ bot_randomstring_t *rs;
+ int i;
+
+ for (random = randomstrings; random; random = random->next)
+ {
+ if (!strcmp(random->string, name))
+ {
+ i = random() * random->numstrings;
+ for (rs = random->firstrandomstring; rs; rs = rs->next)
+ {
+ if (--i < 0) break;
+ } //end for
+ if (rs)
+ {
+ return rs->string;
+ } //end if
+ } //end for
+ } //end for
+ return NULL;
+} //end of the function RandomString
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotDumpMatchTemplates(bot_matchtemplate_t *matches)
+{
+ FILE *fp;
+ bot_matchtemplate_t *mt;
+ bot_matchpiece_t *mp;
+ bot_matchstring_t *ms;
+
+ fp = Log_FilePointer();
+ if (!fp) return;
+ for (mt = matches; mt; mt = mt->next)
+ {
+ fprintf(fp, "{ " );
+ for (mp = mt->first; mp; mp = mp->next)
+ {
+ if (mp->type == MT_STRING)
+ {
+ for (ms = mp->firststring; ms; ms = ms->next)
+ {
+ fprintf(fp, "\"%s\"", ms->string);
+ if (ms->next) fprintf(fp, "|");
+ } //end for
+ } //end if
+ else if (mp->type == MT_VARIABLE)
+ {
+ fprintf(fp, "%d", mp->variable);
+ } //end else if
+ if (mp->next) fprintf(fp, ", ");
+ } //end for
+ fprintf(fp, " = (%d, %d);}\n", mt->type, mt->subtype);
+ } //end for
+} //end of the function BotDumpMatchTemplates
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotFreeMatchPieces(bot_matchpiece_t *matchpieces)
+{
+ bot_matchpiece_t *mp, *nextmp;
+ bot_matchstring_t *ms, *nextms;
+
+ for (mp = matchpieces; mp; mp = nextmp)
+ {
+ nextmp = mp->next;
+ if (mp->type == MT_STRING)
+ {
+ for (ms = mp->firststring; ms; ms = nextms)
+ {
+ nextms = ms->next;
+ FreeMemory(ms);
+ } //end for
+ } //end if
+ FreeMemory(mp);
+ } //end for
+} //end of the function BotFreeMatchPieces
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_matchpiece_t *BotLoadMatchPieces(source_t *source, char *endtoken)
+{
+ int lastwasvariable, emptystring;
+ token_t token;
+ bot_matchpiece_t *matchpiece, *firstpiece, *lastpiece;
+ bot_matchstring_t *matchstring, *lastmatchstring;
+
+ firstpiece = NULL;
+ lastpiece = NULL;
+ //
+ lastwasvariable = qfalse;
+ //
+ while(PC_ReadToken(source, &token))
+ {
+ if (token.type == TT_NUMBER && (token.subtype & TT_INTEGER))
+ {
+ if (token.intvalue < 0 || token.intvalue >= MAX_MATCHVARIABLES)
+ {
+ SourceError(source, "can't have more than %d match variables\n", MAX_MATCHVARIABLES);
+ FreeSource(source);
+ BotFreeMatchPieces(firstpiece);
+ return NULL;
+ } //end if
+ if (lastwasvariable)
+ {
+ SourceError(source, "not allowed to have adjacent variables\n");
+ FreeSource(source);
+ BotFreeMatchPieces(firstpiece);
+ return NULL;
+ } //end if
+ lastwasvariable = qtrue;
+ //
+ matchpiece = (bot_matchpiece_t *) GetClearedHunkMemory(sizeof(bot_matchpiece_t));
+ matchpiece->type = MT_VARIABLE;
+ matchpiece->variable = token.intvalue;
+ matchpiece->next = NULL;
+ if (lastpiece) lastpiece->next = matchpiece;
+ else firstpiece = matchpiece;
+ lastpiece = matchpiece;
+ } //end if
+ else if (token.type == TT_STRING)
+ {
+ //
+ matchpiece = (bot_matchpiece_t *) GetClearedHunkMemory(sizeof(bot_matchpiece_t));
+ matchpiece->firststring = NULL;
+ matchpiece->type = MT_STRING;
+ matchpiece->variable = 0;
+ matchpiece->next = NULL;
+ if (lastpiece) lastpiece->next = matchpiece;
+ else firstpiece = matchpiece;
+ lastpiece = matchpiece;
+ //
+ lastmatchstring = NULL;
+ emptystring = qfalse;
+ //
+ do
+ {
+ if (matchpiece->firststring)
+ {
+ if (!PC_ExpectTokenType(source, TT_STRING, 0, &token))
+ {
+ FreeSource(source);
+ BotFreeMatchPieces(firstpiece);
+ return NULL;
+ } //end if
+ } //end if
+ StripDoubleQuotes(token.string);
+ matchstring = (bot_matchstring_t *) GetClearedHunkMemory(sizeof(bot_matchstring_t) + strlen(token.string) + 1);
+ matchstring->string = (char *) matchstring + sizeof(bot_matchstring_t);
+ strcpy(matchstring->string, token.string);
+ if (!strlen(token.string)) emptystring = qtrue;
+ matchstring->next = NULL;
+ if (lastmatchstring) lastmatchstring->next = matchstring;
+ else matchpiece->firststring = matchstring;
+ lastmatchstring = matchstring;
+ } while(PC_CheckTokenString(source, "|"));
+ //if there was no empty string found
+ if (!emptystring) lastwasvariable = qfalse;
+ } //end if
+ else
+ {
+ SourceError(source, "invalid token %s\n", token.string);
+ FreeSource(source);
+ BotFreeMatchPieces(firstpiece);
+ return NULL;
+ } //end else
+ if (PC_CheckTokenString(source, endtoken)) break;
+ if (!PC_ExpectTokenString(source, ","))
+ {
+ FreeSource(source);
+ BotFreeMatchPieces(firstpiece);
+ return NULL;
+ } //end if
+ } //end while
+ return firstpiece;
+} //end of the function BotLoadMatchPieces
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotFreeMatchTemplates(bot_matchtemplate_t *mt)
+{
+ bot_matchtemplate_t *nextmt;
+
+ for (; mt; mt = nextmt)
+ {
+ nextmt = mt->next;
+ BotFreeMatchPieces(mt->first);
+ FreeMemory(mt);
+ } //end for
+} //end of the function BotFreeMatchTemplates
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_matchtemplate_t *BotLoadMatchTemplates(char *matchfile)
+{
+ source_t *source;
+ token_t token;
+ bot_matchtemplate_t *matchtemplate, *matches, *lastmatch;
+ unsigned long int context;
+
+ PC_SetBaseFolder(BOTFILESBASEFOLDER);
+ source = LoadSourceFile(matchfile);
+ if (!source)
+ {
+ botimport.Print(PRT_ERROR, "counldn't load %s\n", matchfile);
+ return NULL;
+ } //end if
+ //
+ matches = NULL; //list with matches
+ lastmatch = NULL; //last match in the list
+
+ while(PC_ReadToken(source, &token))
+ {
+ if (token.type != TT_NUMBER || !(token.subtype & TT_INTEGER))
+ {
+ SourceError(source, "expected integer, found %s\n", token.string);
+ BotFreeMatchTemplates(matches);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ //the context
+ context = token.intvalue;
+ //
+ if (!PC_ExpectTokenString(source, "{"))
+ {
+ BotFreeMatchTemplates(matches);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ //
+ while(PC_ReadToken(source, &token))
+ {
+ if (!strcmp(token.string, "}")) break;
+ //
+ PC_UnreadLastToken(source);
+ //
+ matchtemplate = (bot_matchtemplate_t *) GetClearedHunkMemory(sizeof(bot_matchtemplate_t));
+ matchtemplate->context = context;
+ matchtemplate->next = NULL;
+ //add the match template to the list
+ if (lastmatch) lastmatch->next = matchtemplate;
+ else matches = matchtemplate;
+ lastmatch = matchtemplate;
+ //load the match template
+ matchtemplate->first = BotLoadMatchPieces(source, "=");
+ if (!matchtemplate->first)
+ {
+ BotFreeMatchTemplates(matches);
+ return NULL;
+ } //end if
+ //read the match type
+ if (!PC_ExpectTokenString(source, "(") ||
+ !PC_ExpectTokenType(source, TT_NUMBER, TT_INTEGER, &token))
+ {
+ BotFreeMatchTemplates(matches);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ matchtemplate->type = token.intvalue;
+ //read the match subtype
+ if (!PC_ExpectTokenString(source, ",") ||
+ !PC_ExpectTokenType(source, TT_NUMBER, TT_INTEGER, &token))
+ {
+ BotFreeMatchTemplates(matches);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ matchtemplate->subtype = token.intvalue;
+ //read trailing punctuations
+ if (!PC_ExpectTokenString(source, ")") ||
+ !PC_ExpectTokenString(source, ";"))
+ {
+ BotFreeMatchTemplates(matches);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ } //end while
+ } //end while
+ //free the source
+ FreeSource(source);
+ botimport.Print(PRT_MESSAGE, "loaded %s\n", matchfile);
+ //
+ //BotDumpMatchTemplates(matches);
+ //
+ return matches;
+} //end of the function BotLoadMatchTemplates
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int StringsMatch(bot_matchpiece_t *pieces, bot_match_t *match)
+{
+ int lastvariable, index;
+ char *strptr, *newstrptr;
+ bot_matchpiece_t *mp;
+ bot_matchstring_t *ms;
+
+ //no last variable
+ lastvariable = -1;
+ //pointer to the string to compare the match string with
+ strptr = match->string;
+ //Log_Write("match: %s", strptr);
+ //compare the string with the current match string
+ for (mp = pieces; mp; mp = mp->next)
+ {
+ //if it is a piece of string
+ if (mp->type == MT_STRING)
+ {
+ newstrptr = NULL;
+ for (ms = mp->firststring; ms; ms = ms->next)
+ {
+ if (!strlen(ms->string))
+ {
+ newstrptr = strptr;
+ break;
+ } //end if
+ //Log_Write("MT_STRING: %s", mp->string);
+ index = StringContains(strptr, ms->string, qfalse);
+ if (index >= 0)
+ {
+ newstrptr = strptr + index;
+ if (lastvariable >= 0)
+ {
+ match->variables[lastvariable].length =
+ (newstrptr - match->string) - match->variables[lastvariable].offset;
+ //newstrptr - match->variables[lastvariable].ptr;
+ lastvariable = -1;
+ break;
+ } //end if
+ else if (index == 0)
+ {
+ break;
+ } //end else
+ newstrptr = NULL;
+ } //end if
+ } //end for
+ if (!newstrptr) return qfalse;
+ strptr = newstrptr + strlen(ms->string);
+ } //end if
+ //if it is a variable piece of string
+ else if (mp->type == MT_VARIABLE)
+ {
+ //Log_Write("MT_VARIABLE");
+ match->variables[mp->variable].offset = strptr - match->string;
+ lastvariable = mp->variable;
+ } //end else if
+ } //end for
+ //if a match was found
+ if (!mp && (lastvariable >= 0 || !strlen(strptr)))
+ {
+ //if the last piece was a variable string
+ if (lastvariable >= 0)
+ {
+ assert( match->variables[lastvariable].offset >= 0 ); // bk001204
+ match->variables[lastvariable].length =
+ strlen(&match->string[ (int) match->variables[lastvariable].offset]);
+ } //end if
+ return qtrue;
+ } //end if
+ return qfalse;
+} //end of the function StringsMatch
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotFindMatch(char *str, bot_match_t *match, unsigned long int context)
+{
+ int i;
+ bot_matchtemplate_t *ms;
+
+ strncpy(match->string, str, MAX_MESSAGE_SIZE);
+ //remove any trailing enters
+ while(strlen(match->string) &&
+ match->string[strlen(match->string)-1] == '\n')
+ {
+ match->string[strlen(match->string)-1] = '\0';
+ } //end while
+ //compare the string with all the match strings
+ for (ms = matchtemplates; ms; ms = ms->next)
+ {
+ if (!(ms->context & context)) continue;
+ //reset the match variable offsets
+ for (i = 0; i < MAX_MATCHVARIABLES; i++) match->variables[i].offset = -1;
+ //
+ if (StringsMatch(ms->first, match))
+ {
+ match->type = ms->type;
+ match->subtype = ms->subtype;
+ return qtrue;
+ } //end if
+ } //end for
+ return qfalse;
+} //end of the function BotFindMatch
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotMatchVariable(bot_match_t *match, int variable, char *buf, int size)
+{
+ if (variable < 0 || variable >= MAX_MATCHVARIABLES)
+ {
+ botimport.Print(PRT_FATAL, "BotMatchVariable: variable out of range\n");
+ strcpy(buf, "");
+ return;
+ } //end if
+
+ if (match->variables[variable].offset >= 0)
+ {
+ if (match->variables[variable].length < size)
+ size = match->variables[variable].length+1;
+ assert( match->variables[variable].offset >= 0 ); // bk001204
+ strncpy(buf, &match->string[ (int) match->variables[variable].offset], size-1);
+ buf[size-1] = '\0';
+ } //end if
+ else
+ {
+ strcpy(buf, "");
+ } //end else
+ return;
+} //end of the function BotMatchVariable
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_stringlist_t *BotFindStringInList(bot_stringlist_t *list, char *string)
+{
+ bot_stringlist_t *s;
+
+ for (s = list; s; s = s->next)
+ {
+ if (!strcmp(s->string, string)) return s;
+ } //end for
+ return NULL;
+} //end of the function BotFindStringInList
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_stringlist_t *BotCheckChatMessageIntegrety(char *message, bot_stringlist_t *stringlist)
+{
+ int i;
+ char *msgptr;
+ char temp[MAX_MESSAGE_SIZE];
+ bot_stringlist_t *s;
+
+ msgptr = message;
+ //
+ while(*msgptr)
+ {
+ if (*msgptr == ESCAPE_CHAR)
+ {
+ msgptr++;
+ switch(*msgptr)
+ {
+ case 'v': //variable
+ {
+ //step over the 'v'
+ msgptr++;
+ while(*msgptr && *msgptr != ESCAPE_CHAR) msgptr++;
+ //step over the trailing escape char
+ if (*msgptr) msgptr++;
+ break;
+ } //end case
+ case 'r': //random
+ {
+ //step over the 'r'
+ msgptr++;
+ for (i = 0; (*msgptr && *msgptr != ESCAPE_CHAR); i++)
+ {
+ temp[i] = *msgptr++;
+ } //end while
+ temp[i] = '\0';
+ //step over the trailing escape char
+ if (*msgptr) msgptr++;
+ //find the random keyword
+ if (!RandomString(temp))
+ {
+ if (!BotFindStringInList(stringlist, temp))
+ {
+ Log_Write("%s = {\"%s\"} //MISSING RANDOM\r\n", temp, temp);
+ s = GetClearedMemory(sizeof(bot_stringlist_t) + strlen(temp) + 1);
+ s->string = (char *) s + sizeof(bot_stringlist_t);
+ strcpy(s->string, temp);
+ s->next = stringlist;
+ stringlist = s;
+ } //end if
+ } //end if
+ break;
+ } //end case
+ default:
+ {
+ botimport.Print(PRT_FATAL, "BotCheckChatMessageIntegrety: message \"%s\" invalid escape char\n", message);
+ break;
+ } //end default
+ } //end switch
+ } //end if
+ else
+ {
+ msgptr++;
+ } //end else
+ } //end while
+ return stringlist;
+} //end of the function BotCheckChatMessageIntegrety
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotCheckInitialChatIntegrety(bot_chat_t *chat)
+{
+ bot_chattype_t *t;
+ bot_chatmessage_t *cm;
+ bot_stringlist_t *stringlist, *s, *nexts;
+
+ stringlist = NULL;
+ for (t = chat->types; t; t = t->next)
+ {
+ for (cm = t->firstchatmessage; cm; cm = cm->next)
+ {
+ stringlist = BotCheckChatMessageIntegrety(cm->chatmessage, stringlist);
+ } //end for
+ } //end for
+ for (s = stringlist; s; s = nexts)
+ {
+ nexts = s->next;
+ FreeMemory(s);
+ } //end for
+} //end of the function BotCheckInitialChatIntegrety
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotCheckReplyChatIntegrety(bot_replychat_t *replychat)
+{
+ bot_replychat_t *rp;
+ bot_chatmessage_t *cm;
+ bot_stringlist_t *stringlist, *s, *nexts;
+
+ stringlist = NULL;
+ for (rp = replychat; rp; rp = rp->next)
+ {
+ for (cm = rp->firstchatmessage; cm; cm = cm->next)
+ {
+ stringlist = BotCheckChatMessageIntegrety(cm->chatmessage, stringlist);
+ } //end for
+ } //end for
+ for (s = stringlist; s; s = nexts)
+ {
+ nexts = s->next;
+ FreeMemory(s);
+ } //end for
+} //end of the function BotCheckReplyChatIntegrety
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotDumpReplyChat(bot_replychat_t *replychat)
+{
+ FILE *fp;
+ bot_replychat_t *rp;
+ bot_replychatkey_t *key;
+ bot_chatmessage_t *cm;
+ bot_matchpiece_t *mp;
+
+ fp = Log_FilePointer();
+ if (!fp) return;
+ fprintf(fp, "BotDumpReplyChat:\n");
+ for (rp = replychat; rp; rp = rp->next)
+ {
+ fprintf(fp, "[");
+ for (key = rp->keys; key; key = key->next)
+ {
+ if (key->flags & RCKFL_AND) fprintf(fp, "&");
+ else if (key->flags & RCKFL_NOT) fprintf(fp, "!");
+ //
+ if (key->flags & RCKFL_NAME) fprintf(fp, "name");
+ else if (key->flags & RCKFL_GENDERFEMALE) fprintf(fp, "female");
+ else if (key->flags & RCKFL_GENDERMALE) fprintf(fp, "male");
+ else if (key->flags & RCKFL_GENDERLESS) fprintf(fp, "it");
+ else if (key->flags & RCKFL_VARIABLES)
+ {
+ fprintf(fp, "(");
+ for (mp = key->match; mp; mp = mp->next)
+ {
+ if (mp->type == MT_STRING) fprintf(fp, "\"%s\"", mp->firststring->string);
+ else fprintf(fp, "%d", mp->variable);
+ if (mp->next) fprintf(fp, ", ");
+ } //end for
+ fprintf(fp, ")");
+ } //end if
+ else if (key->flags & RCKFL_STRING)
+ {
+ fprintf(fp, "\"%s\"", key->string);
+ } //end if
+ if (key->next) fprintf(fp, ", ");
+ else fprintf(fp, "] = %1.0f\n", rp->priority);
+ } //end for
+ fprintf(fp, "{\n");
+ for (cm = rp->firstchatmessage; cm; cm = cm->next)
+ {
+ fprintf(fp, "\t\"%s\";\n", cm->chatmessage);
+ } //end for
+ fprintf(fp, "}\n");
+ } //end for
+} //end of the function BotDumpReplyChat
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotFreeReplyChat(bot_replychat_t *replychat)
+{
+ bot_replychat_t *rp, *nextrp;
+ bot_replychatkey_t *key, *nextkey;
+ bot_chatmessage_t *cm, *nextcm;
+
+ for (rp = replychat; rp; rp = nextrp)
+ {
+ nextrp = rp->next;
+ for (key = rp->keys; key; key = nextkey)
+ {
+ nextkey = key->next;
+ if (key->match) BotFreeMatchPieces(key->match);
+ if (key->string) FreeMemory(key->string);
+ FreeMemory(key);
+ } //end for
+ for (cm = rp->firstchatmessage; cm; cm = nextcm)
+ {
+ nextcm = cm->next;
+ FreeMemory(cm);
+ } //end for
+ FreeMemory(rp);
+ } //end for
+} //end of the function BotFreeReplyChat
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotCheckValidReplyChatKeySet(source_t *source, bot_replychatkey_t *keys)
+{
+ int allprefixed, hasvariableskey, hasstringkey;
+ bot_matchpiece_t *m;
+ bot_matchstring_t *ms;
+ bot_replychatkey_t *key, *key2;
+
+ //
+ allprefixed = qtrue;
+ hasvariableskey = hasstringkey = qfalse;
+ for (key = keys; key; key = key->next)
+ {
+ if (!(key->flags & (RCKFL_AND|RCKFL_NOT)))
+ {
+ allprefixed = qfalse;
+ if (key->flags & RCKFL_VARIABLES)
+ {
+ for (m = key->match; m; m = m->next)
+ {
+ if (m->type == MT_VARIABLE) hasvariableskey = qtrue;
+ } //end for
+ } //end if
+ else if (key->flags & RCKFL_STRING)
+ {
+ hasstringkey = qtrue;
+ } //end else if
+ } //end if
+ else if ((key->flags & RCKFL_AND) && (key->flags & RCKFL_STRING))
+ {
+ for (key2 = keys; key2; key2 = key2->next)
+ {
+ if (key2 == key) continue;
+ if (key2->flags & RCKFL_NOT) continue;
+ if (key2->flags & RCKFL_VARIABLES)
+ {
+ for (m = key2->match; m; m = m->next)
+ {
+ if (m->type == MT_STRING)
+ {
+ for (ms = m->firststring; ms; ms = ms->next)
+ {
+ if (StringContains(ms->string, key->string, qfalse) != -1)
+ {
+ break;
+ } //end if
+ } //end for
+ if (ms) break;
+ } //end if
+ else if (m->type == MT_VARIABLE)
+ {
+ break;
+ } //end if
+ } //end for
+ if (!m)
+ {
+ SourceWarning(source, "one of the match templates does not "
+ "leave space for the key %s with the & prefix", key->string);
+ } //end if
+ } //end if
+ } //end for
+ } //end else
+ if ((key->flags & RCKFL_NOT) && (key->flags & RCKFL_STRING))
+ {
+ for (key2 = keys; key2; key2 = key2->next)
+ {
+ if (key2 == key) continue;
+ if (key2->flags & RCKFL_NOT) continue;
+ if (key2->flags & RCKFL_STRING)
+ {
+ if (StringContains(key2->string, key->string, qfalse) != -1)
+ {
+ SourceWarning(source, "the key %s with prefix ! is inside the key %s", key->string, key2->string);
+ } //end if
+ } //end if
+ else if (key2->flags & RCKFL_VARIABLES)
+ {
+ for (m = key2->match; m; m = m->next)
+ {
+ if (m->type == MT_STRING)
+ {
+ for (ms = m->firststring; ms; ms = ms->next)
+ {
+ if (StringContains(ms->string, key->string, qfalse) != -1)
+ {
+ SourceWarning(source, "the key %s with prefix ! is inside "
+ "the match template string %s", key->string, ms->string);
+ } //end if
+ } //end for
+ } //end if
+ } //end for
+ } //end else if
+ } //end for
+ } //end if
+ } //end for
+ if (allprefixed) SourceWarning(source, "all keys have a & or ! prefix");
+ if (hasvariableskey && hasstringkey)
+ {
+ SourceWarning(source, "variables from the match template(s) could be "
+ "invalid when outputting one of the chat messages");
+ } //end if
+} //end of the function BotCheckValidReplyChatKeySet
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_replychat_t *BotLoadReplyChat(char *filename)
+{
+ char chatmessagestring[MAX_MESSAGE_SIZE];
+ char namebuffer[MAX_MESSAGE_SIZE];
+ source_t *source;
+ token_t token;
+ bot_chatmessage_t *chatmessage = NULL;
+ bot_replychat_t *replychat, *replychatlist;
+ bot_replychatkey_t *key;
+
+ PC_SetBaseFolder(BOTFILESBASEFOLDER);
+ source = LoadSourceFile(filename);
+ if (!source)
+ {
+ botimport.Print(PRT_ERROR, "counldn't load %s\n", filename);
+ return NULL;
+ } //end if
+ //
+ replychatlist = NULL;
+ //
+ while(PC_ReadToken(source, &token))
+ {
+ if (strcmp(token.string, "["))
+ {
+ SourceError(source, "expected [, found %s", token.string);
+ BotFreeReplyChat(replychatlist);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ //
+ replychat = GetClearedHunkMemory(sizeof(bot_replychat_t));
+ replychat->keys = NULL;
+ replychat->next = replychatlist;
+ replychatlist = replychat;
+ //read the keys, there must be at least one key
+ do
+ {
+ //allocate a key
+ key = (bot_replychatkey_t *) GetClearedHunkMemory(sizeof(bot_replychatkey_t));
+ key->flags = 0;
+ key->string = NULL;
+ key->match = NULL;
+ key->next = replychat->keys;
+ replychat->keys = key;
+ //check for MUST BE PRESENT and MUST BE ABSENT keys
+ if (PC_CheckTokenString(source, "&")) key->flags |= RCKFL_AND;
+ else if (PC_CheckTokenString(source, "!")) key->flags |= RCKFL_NOT;
+ //special keys
+ if (PC_CheckTokenString(source, "name")) key->flags |= RCKFL_NAME;
+ else if (PC_CheckTokenString(source, "female")) key->flags |= RCKFL_GENDERFEMALE;
+ else if (PC_CheckTokenString(source, "male")) key->flags |= RCKFL_GENDERMALE;
+ else if (PC_CheckTokenString(source, "it")) key->flags |= RCKFL_GENDERLESS;
+ else if (PC_CheckTokenString(source, "(")) //match key
+ {
+ key->flags |= RCKFL_VARIABLES;
+ key->match = BotLoadMatchPieces(source, ")");
+ if (!key->match)
+ {
+ BotFreeReplyChat(replychatlist);
+ return NULL;
+ } //end if
+ } //end else if
+ else if (PC_CheckTokenString(source, "<")) //bot names
+ {
+ key->flags |= RCKFL_BOTNAMES;
+ strcpy(namebuffer, "");
+ do
+ {
+ if (!PC_ExpectTokenType(source, TT_STRING, 0, &token))
+ {
+ BotFreeReplyChat(replychatlist);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ StripDoubleQuotes(token.string);
+ if (strlen(namebuffer)) strcat(namebuffer, "\\");
+ strcat(namebuffer, token.string);
+ } while(PC_CheckTokenString(source, ","));
+ if (!PC_ExpectTokenString(source, ">"))
+ {
+ BotFreeReplyChat(replychatlist);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ key->string = (char *) GetClearedHunkMemory(strlen(namebuffer) + 1);
+ strcpy(key->string, namebuffer);
+ } //end else if
+ else //normal string key
+ {
+ key->flags |= RCKFL_STRING;
+ if (!PC_ExpectTokenType(source, TT_STRING, 0, &token))
+ {
+ BotFreeReplyChat(replychatlist);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ StripDoubleQuotes(token.string);
+ key->string = (char *) GetClearedHunkMemory(strlen(token.string) + 1);
+ strcpy(key->string, token.string);
+ } //end else
+ //
+ PC_CheckTokenString(source, ",");
+ } while(!PC_CheckTokenString(source, "]"));
+ //
+ BotCheckValidReplyChatKeySet(source, replychat->keys);
+ //read the = sign and the priority
+ if (!PC_ExpectTokenString(source, "=") ||
+ !PC_ExpectTokenType(source, TT_NUMBER, 0, &token))
+ {
+ BotFreeReplyChat(replychatlist);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ replychat->priority = token.floatvalue;
+ //read the leading {
+ if (!PC_ExpectTokenString(source, "{"))
+ {
+ BotFreeReplyChat(replychatlist);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ replychat->numchatmessages = 0;
+ //while the trailing } is not found
+ while(!PC_CheckTokenString(source, "}"))
+ {
+ if (!BotLoadChatMessage(source, chatmessagestring))
+ {
+ BotFreeReplyChat(replychatlist);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ chatmessage = (bot_chatmessage_t *) GetClearedHunkMemory(sizeof(bot_chatmessage_t) + strlen(chatmessagestring) + 1);
+ chatmessage->chatmessage = (char *) chatmessage + sizeof(bot_chatmessage_t);
+ strcpy(chatmessage->chatmessage, chatmessagestring);
+ chatmessage->time = -2*CHATMESSAGE_RECENTTIME;
+ chatmessage->next = replychat->firstchatmessage;
+ //add the chat message to the reply chat
+ replychat->firstchatmessage = chatmessage;
+ replychat->numchatmessages++;
+ } //end while
+ } //end while
+ FreeSource(source);
+ botimport.Print(PRT_MESSAGE, "loaded %s\n", filename);
+ //
+ //BotDumpReplyChat(replychatlist);
+ if (bot_developer)
+ {
+ BotCheckReplyChatIntegrety(replychatlist);
+ } //end if
+ //
+ if (!replychatlist) botimport.Print(PRT_MESSAGE, "no rchats\n");
+ //
+ return replychatlist;
+} //end of the function BotLoadReplyChat
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotDumpInitialChat(bot_chat_t *chat)
+{
+ bot_chattype_t *t;
+ bot_chatmessage_t *m;
+
+ Log_Write("{");
+ for (t = chat->types; t; t = t->next)
+ {
+ Log_Write(" type \"%s\"", t->name);
+ Log_Write(" {");
+ Log_Write(" numchatmessages = %d", t->numchatmessages);
+ for (m = t->firstchatmessage; m; m = m->next)
+ {
+ Log_Write(" \"%s\"", m->chatmessage);
+ } //end for
+ Log_Write(" }");
+ } //end for
+ Log_Write("}");
+} //end of the function BotDumpInitialChat
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_chat_t *BotLoadInitialChat(char *chatfile, char *chatname)
+{
+ int pass, foundchat, indent, size;
+ char *ptr = NULL;
+ char chatmessagestring[MAX_MESSAGE_SIZE];
+ source_t *source;
+ token_t token;
+ bot_chat_t *chat = NULL;
+ bot_chattype_t *chattype = NULL;
+ bot_chatmessage_t *chatmessage = NULL;
+#ifdef DEBUG
+ int starttime;
+
+ starttime = Sys_MilliSeconds();
+#endif //DEBUG
+ //
+ size = 0;
+ foundchat = qfalse;
+ //a bot chat is parsed in two phases
+ for (pass = 0; pass < 2; pass++)
+ {
+ //allocate memory
+ if (pass && size) ptr = (char *) GetClearedMemory(size);
+ //load the source file
+ PC_SetBaseFolder(BOTFILESBASEFOLDER);
+ source = LoadSourceFile(chatfile);
+ if (!source)
+ {
+ botimport.Print(PRT_ERROR, "counldn't load %s\n", chatfile);
+ return NULL;
+ } //end if
+ //chat structure
+ if (pass)
+ {
+ chat = (bot_chat_t *) ptr;
+ ptr += sizeof(bot_chat_t);
+ } //end if
+ size = sizeof(bot_chat_t);
+ //
+ while(PC_ReadToken(source, &token))
+ {
+ if (!strcmp(token.string, "chat"))
+ {
+ if (!PC_ExpectTokenType(source, TT_STRING, 0, &token))
+ {
+ FreeSource(source);
+ return NULL;
+ } //end if
+ StripDoubleQuotes(token.string);
+ //after the chat name we expect a opening brace
+ if (!PC_ExpectTokenString(source, "{"))
+ {
+ FreeSource(source);
+ return NULL;
+ } //end if
+ //if the chat name is found
+ if (!Q_stricmp(token.string, chatname))
+ {
+ foundchat = qtrue;
+ //read the chat types
+ while(1)
+ {
+ if (!PC_ExpectAnyToken(source, &token))
+ {
+ FreeSource(source);
+ return NULL;
+ } //end if
+ if (!strcmp(token.string, "}")) break;
+ if (strcmp(token.string, "type"))
+ {
+ SourceError(source, "expected type found %s\n", token.string);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ //expect the chat type name
+ if (!PC_ExpectTokenType(source, TT_STRING, 0, &token) ||
+ !PC_ExpectTokenString(source, "{"))
+ {
+ FreeSource(source);
+ return NULL;
+ } //end if
+ StripDoubleQuotes(token.string);
+ if (pass)
+ {
+ chattype = (bot_chattype_t *) ptr;
+ strncpy(chattype->name, token.string, MAX_CHATTYPE_NAME);
+ chattype->firstchatmessage = NULL;
+ //add the chat type to the chat
+ chattype->next = chat->types;
+ chat->types = chattype;
+ //
+ ptr += sizeof(bot_chattype_t);
+ } //end if
+ size += sizeof(bot_chattype_t);
+ //read the chat messages
+ while(!PC_CheckTokenString(source, "}"))
+ {
+ if (!BotLoadChatMessage(source, chatmessagestring))
+ {
+ FreeSource(source);
+ return NULL;
+ } //end if
+ if (pass)
+ {
+ chatmessage = (bot_chatmessage_t *) ptr;
+ chatmessage->time = -2*CHATMESSAGE_RECENTTIME;
+ //put the chat message in the list
+ chatmessage->next = chattype->firstchatmessage;
+ chattype->firstchatmessage = chatmessage;
+ //store the chat message
+ ptr += sizeof(bot_chatmessage_t);
+ chatmessage->chatmessage = ptr;
+ strcpy(chatmessage->chatmessage, chatmessagestring);
+ ptr += strlen(chatmessagestring) + 1;
+ //the number of chat messages increased
+ chattype->numchatmessages++;
+ } //end if
+ size += sizeof(bot_chatmessage_t) + strlen(chatmessagestring) + 1;
+ } //end if
+ } //end while
+ } //end if
+ else //skip the bot chat
+ {
+ indent = 1;
+ while(indent)
+ {
+ if (!PC_ExpectAnyToken(source, &token))
+ {
+ FreeSource(source);
+ return NULL;
+ } //end if
+ if (!strcmp(token.string, "{")) indent++;
+ else if (!strcmp(token.string, "}")) indent--;
+ } //end while
+ } //end else
+ } //end if
+ else
+ {
+ SourceError(source, "unknown definition %s\n", token.string);
+ FreeSource(source);
+ return NULL;
+ } //end else
+ } //end while
+ //free the source
+ FreeSource(source);
+ //if the requested character is not found
+ if (!foundchat)
+ {
+ botimport.Print(PRT_ERROR, "couldn't find chat %s in %s\n", chatname, chatfile);
+ return NULL;
+ } //end if
+ } //end for
+ //
+ botimport.Print(PRT_MESSAGE, "loaded %s from %s\n", chatname, chatfile);
+ //
+ //BotDumpInitialChat(chat);
+ if (bot_developer)
+ {
+ BotCheckInitialChatIntegrety(chat);
+ } //end if
+#ifdef DEBUG
+ botimport.Print(PRT_MESSAGE, "initial chats loaded in %d msec\n", Sys_MilliSeconds() - starttime);
+#endif //DEBUG
+ //character was read succesfully
+ return chat;
+} //end of the function BotLoadInitialChat
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotFreeChatFile(int chatstate)
+{
+ bot_chatstate_t *cs;
+
+ cs = BotChatStateFromHandle(chatstate);
+ if (!cs) return;
+ if (cs->chat) FreeMemory(cs->chat);
+ cs->chat = NULL;
+} //end of the function BotFreeChatFile
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotLoadChatFile(int chatstate, char *chatfile, char *chatname)
+{
+ bot_chatstate_t *cs;
+ int n, avail = 0;
+
+ cs = BotChatStateFromHandle(chatstate);
+ if (!cs) return BLERR_CANNOTLOADICHAT;
+ BotFreeChatFile(chatstate);
+
+ if (!LibVarGetValue("bot_reloadcharacters"))
+ {
+ avail = -1;
+ for( n = 0; n < MAX_CLIENTS; n++ ) {
+ if( !ichatdata[n] ) {
+ if( avail == -1 ) {
+ avail = n;
+ }
+ continue;
+ }
+ if( strcmp( chatfile, ichatdata[n]->filename ) != 0 ) {
+ continue;
+ }
+ if( strcmp( chatname, ichatdata[n]->chatname ) != 0 ) {
+ continue;
+ }
+ cs->chat = ichatdata[n]->chat;
+ // botimport.Print( PRT_MESSAGE, "retained %s from %s\n", chatname, chatfile );
+ return BLERR_NOERROR;
+ }
+
+ if( avail == -1 ) {
+ botimport.Print(PRT_FATAL, "ichatdata table full; couldn't load chat %s from %s\n", chatname, chatfile);
+ return BLERR_CANNOTLOADICHAT;
+ }
+ }
+
+ cs->chat = BotLoadInitialChat(chatfile, chatname);
+ if (!cs->chat)
+ {
+ botimport.Print(PRT_FATAL, "couldn't load chat %s from %s\n", chatname, chatfile);
+ return BLERR_CANNOTLOADICHAT;
+ } //end if
+ if (!LibVarGetValue("bot_reloadcharacters"))
+ {
+ ichatdata[avail] = GetClearedMemory( sizeof(bot_ichatdata_t) );
+ ichatdata[avail]->chat = cs->chat;
+ Q_strncpyz( ichatdata[avail]->chatname, chatname, sizeof(ichatdata[avail]->chatname) );
+ Q_strncpyz( ichatdata[avail]->filename, chatfile, sizeof(ichatdata[avail]->filename) );
+ } //end if
+
+ return BLERR_NOERROR;
+} //end of the function BotLoadChatFile
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotExpandChatMessage(char *outmessage, char *message, unsigned long mcontext,
+ bot_match_t *match, unsigned long vcontext, int reply)
+{
+ int num, len, i, expansion;
+ char *outputbuf, *ptr, *msgptr;
+ char temp[MAX_MESSAGE_SIZE];
+
+ expansion = qfalse;
+ msgptr = message;
+ outputbuf = outmessage;
+ len = 0;
+ //
+ while(*msgptr)
+ {
+ if (*msgptr == ESCAPE_CHAR)
+ {
+ msgptr++;
+ switch(*msgptr)
+ {
+ case 'v': //variable
+ {
+ msgptr++;
+ num = 0;
+ while(*msgptr && *msgptr != ESCAPE_CHAR)
+ {
+ num = num * 10 + (*msgptr++) - '0';
+ } //end while
+ //step over the trailing escape char
+ if (*msgptr) msgptr++;
+ if (num > MAX_MATCHVARIABLES)
+ {
+ botimport.Print(PRT_ERROR, "BotConstructChat: message %s variable %d out of range\n", message, num);
+ return qfalse;
+ } //end if
+ if (match->variables[num].offset >= 0)
+ {
+ assert( match->variables[num].offset >= 0 ); // bk001204
+ ptr = &match->string[ (int) match->variables[num].offset];
+ for (i = 0; i < match->variables[num].length; i++)
+ {
+ temp[i] = ptr[i];
+ } //end for
+ temp[i] = 0;
+ //if it's a reply message
+ if (reply)
+ {
+ //replace the reply synonyms in the variables
+ BotReplaceReplySynonyms(temp, vcontext);
+ } //end if
+ else
+ {
+ //replace synonyms in the variable context
+ BotReplaceSynonyms(temp, vcontext);
+ } //end else
+ //
+ if (len + strlen(temp) >= MAX_MESSAGE_SIZE)
+ {
+ botimport.Print(PRT_ERROR, "BotConstructChat: message %s too long\n", message);
+ return qfalse;
+ } //end if
+ strcpy(&outputbuf[len], temp);
+ len += strlen(temp);
+ } //end if
+ break;
+ } //end case
+ case 'r': //random
+ {
+ msgptr++;
+ for (i = 0; (*msgptr && *msgptr != ESCAPE_CHAR); i++)
+ {
+ temp[i] = *msgptr++;
+ } //end while
+ temp[i] = '\0';
+ //step over the trailing escape char
+ if (*msgptr) msgptr++;
+ //find the random keyword
+ ptr = RandomString(temp);
+ if (!ptr)
+ {
+ botimport.Print(PRT_ERROR, "BotConstructChat: unknown random string %s\n", temp);
+ return qfalse;
+ } //end if
+ if (len + strlen(ptr) >= MAX_MESSAGE_SIZE)
+ {
+ botimport.Print(PRT_ERROR, "BotConstructChat: message \"%s\" too long\n", message);
+ return qfalse;
+ } //end if
+ strcpy(&outputbuf[len], ptr);
+ len += strlen(ptr);
+ expansion = qtrue;
+ break;
+ } //end case
+ default:
+ {
+ botimport.Print(PRT_FATAL, "BotConstructChat: message \"%s\" invalid escape char\n", message);
+ break;
+ } //end default
+ } //end switch
+ } //end if
+ else
+ {
+ outputbuf[len++] = *msgptr++;
+ if (len >= MAX_MESSAGE_SIZE)
+ {
+ botimport.Print(PRT_ERROR, "BotConstructChat: message \"%s\" too long\n", message);
+ break;
+ } //end if
+ } //end else
+ } //end while
+ outputbuf[len] = '\0';
+ //replace synonyms weighted in the message context
+ BotReplaceWeightedSynonyms(outputbuf, mcontext);
+ //return true if a random was expanded
+ return expansion;
+} //end of the function BotExpandChatMessage
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotConstructChatMessage(bot_chatstate_t *chatstate, char *message, unsigned long mcontext,
+ bot_match_t *match, unsigned long vcontext, int reply)
+{
+ int i;
+ char srcmessage[MAX_MESSAGE_SIZE];
+
+ strcpy(srcmessage, message);
+ for (i = 0; i < 10; i++)
+ {
+ if (!BotExpandChatMessage(chatstate->chatmessage, srcmessage, mcontext, match, vcontext, reply))
+ {
+ break;
+ } //end if
+ strcpy(srcmessage, chatstate->chatmessage);
+ } //end for
+ if (i >= 10)
+ {
+ botimport.Print(PRT_WARNING, "too many expansions in chat message\n");
+ botimport.Print(PRT_WARNING, "%s\n", chatstate->chatmessage);
+ } //end if
+} //end of the function BotConstructChatMessage
+//===========================================================================
+// randomly chooses one of the chat message of the given type
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+char *BotChooseInitialChatMessage(bot_chatstate_t *cs, char *type)
+{
+ int n, numchatmessages;
+ float besttime;
+ bot_chattype_t *t;
+ bot_chatmessage_t *m, *bestchatmessage;
+ bot_chat_t *chat;
+
+ chat = cs->chat;
+ for (t = chat->types; t; t = t->next)
+ {
+ if (!Q_stricmp(t->name, type))
+ {
+ numchatmessages = 0;
+ for (m = t->firstchatmessage; m; m = m->next)
+ {
+ if (m->time > AAS_Time()) continue;
+ numchatmessages++;
+ } //end if
+ //if all chat messages have been used recently
+ if (numchatmessages <= 0)
+ {
+ besttime = 0;
+ bestchatmessage = NULL;
+ for (m = t->firstchatmessage; m; m = m->next)
+ {
+ if (!besttime || m->time < besttime)
+ {
+ bestchatmessage = m;
+ besttime = m->time;
+ } //end if
+ } //end for
+ if (bestchatmessage) return bestchatmessage->chatmessage;
+ } //end if
+ else //choose a chat message randomly
+ {
+ n = random() * numchatmessages;
+ for (m = t->firstchatmessage; m; m = m->next)
+ {
+ if (m->time > AAS_Time()) continue;
+ if (--n < 0)
+ {
+ m->time = AAS_Time() + CHATMESSAGE_RECENTTIME;
+ return m->chatmessage;
+ } //end if
+ } //end for
+ } //end else
+ return NULL;
+ } //end if
+ } //end for
+ return NULL;
+} //end of the function BotChooseInitialChatMessage
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotNumInitialChats(int chatstate, char *type)
+{
+ bot_chatstate_t *cs;
+ bot_chattype_t *t;
+
+ cs = BotChatStateFromHandle(chatstate);
+ if (!cs) return 0;
+
+ for (t = cs->chat->types; t; t = t->next)
+ {
+ if (!Q_stricmp(t->name, type))
+ {
+ if (LibVarGetValue("bot_testichat")) {
+ botimport.Print(PRT_MESSAGE, "%s has %d chat lines\n", type, t->numchatmessages);
+ botimport.Print(PRT_MESSAGE, "-------------------\n");
+ }
+ return t->numchatmessages;
+ } //end if
+ } //end for
+ return 0;
+} //end of the function BotNumInitialChats
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotInitialChat(int chatstate, char *type, int mcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7)
+{
+ char *message;
+ int index;
+ bot_match_t match;
+ bot_chatstate_t *cs;
+
+ cs = BotChatStateFromHandle(chatstate);
+ if (!cs) return;
+ //if no chat file is loaded
+ if (!cs->chat) return;
+ //choose a chat message randomly of the given type
+ message = BotChooseInitialChatMessage(cs, type);
+ //if there's no message of the given type
+ if (!message)
+ {
+#ifdef DEBUG
+ botimport.Print(PRT_MESSAGE, "no chat messages of type %s\n", type);
+#endif //DEBUG
+ return;
+ } //end if
+ //
+ Com_Memset(&match, 0, sizeof(match));
+ index = 0;
+ if( var0 ) {
+ strcat(match.string, var0);
+ match.variables[0].offset = index;
+ match.variables[0].length = strlen(var0);
+ index += strlen(var0);
+ }
+ if( var1 ) {
+ strcat(match.string, var1);
+ match.variables[1].offset = index;
+ match.variables[1].length = strlen(var1);
+ index += strlen(var1);
+ }
+ if( var2 ) {
+ strcat(match.string, var2);
+ match.variables[2].offset = index;
+ match.variables[2].length = strlen(var2);
+ index += strlen(var2);
+ }
+ if( var3 ) {
+ strcat(match.string, var3);
+ match.variables[3].offset = index;
+ match.variables[3].length = strlen(var3);
+ index += strlen(var3);
+ }
+ if( var4 ) {
+ strcat(match.string, var4);
+ match.variables[4].offset = index;
+ match.variables[4].length = strlen(var4);
+ index += strlen(var4);
+ }
+ if( var5 ) {
+ strcat(match.string, var5);
+ match.variables[5].offset = index;
+ match.variables[5].length = strlen(var5);
+ index += strlen(var5);
+ }
+ if( var6 ) {
+ strcat(match.string, var6);
+ match.variables[6].offset = index;
+ match.variables[6].length = strlen(var6);
+ index += strlen(var6);
+ }
+ if( var7 ) {
+ strcat(match.string, var7);
+ match.variables[7].offset = index;
+ match.variables[7].length = strlen(var7);
+ index += strlen(var7);
+ }
+ //
+ BotConstructChatMessage(cs, message, mcontext, &match, 0, qfalse);
+} //end of the function BotInitialChat
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotPrintReplyChatKeys(bot_replychat_t *replychat)
+{
+ bot_replychatkey_t *key;
+ bot_matchpiece_t *mp;
+
+ botimport.Print(PRT_MESSAGE, "[");
+ for (key = replychat->keys; key; key = key->next)
+ {
+ if (key->flags & RCKFL_AND) botimport.Print(PRT_MESSAGE, "&");
+ else if (key->flags & RCKFL_NOT) botimport.Print(PRT_MESSAGE, "!");
+ //
+ if (key->flags & RCKFL_NAME) botimport.Print(PRT_MESSAGE, "name");
+ else if (key->flags & RCKFL_GENDERFEMALE) botimport.Print(PRT_MESSAGE, "female");
+ else if (key->flags & RCKFL_GENDERMALE) botimport.Print(PRT_MESSAGE, "male");
+ else if (key->flags & RCKFL_GENDERLESS) botimport.Print(PRT_MESSAGE, "it");
+ else if (key->flags & RCKFL_VARIABLES)
+ {
+ botimport.Print(PRT_MESSAGE, "(");
+ for (mp = key->match; mp; mp = mp->next)
+ {
+ if (mp->type == MT_STRING) botimport.Print(PRT_MESSAGE, "\"%s\"", mp->firststring->string);
+ else botimport.Print(PRT_MESSAGE, "%d", mp->variable);
+ if (mp->next) botimport.Print(PRT_MESSAGE, ", ");
+ } //end for
+ botimport.Print(PRT_MESSAGE, ")");
+ } //end if
+ else if (key->flags & RCKFL_STRING)
+ {
+ botimport.Print(PRT_MESSAGE, "\"%s\"", key->string);
+ } //end if
+ if (key->next) botimport.Print(PRT_MESSAGE, ", ");
+ else botimport.Print(PRT_MESSAGE, "] = %1.0f\n", replychat->priority);
+ } //end for
+ botimport.Print(PRT_MESSAGE, "{\n");
+} //end of the function BotPrintReplyChatKeys
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotReplyChat(int chatstate, char *message, int mcontext, int vcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7)
+{
+ bot_replychat_t *rchat, *bestrchat;
+ bot_replychatkey_t *key;
+ bot_chatmessage_t *m, *bestchatmessage;
+ bot_match_t match, bestmatch;
+ int bestpriority, num, found, res, numchatmessages, index;
+ bot_chatstate_t *cs;
+
+ cs = BotChatStateFromHandle(chatstate);
+ if (!cs) return qfalse;
+ Com_Memset(&match, 0, sizeof(bot_match_t));
+ strcpy(match.string, message);
+ bestpriority = -1;
+ bestchatmessage = NULL;
+ bestrchat = NULL;
+ //go through all the reply chats
+ for (rchat = replychats; rchat; rchat = rchat->next)
+ {
+ found = qfalse;
+ for (key = rchat->keys; key; key = key->next)
+ {
+ res = qfalse;
+ //get the match result
+ if (key->flags & RCKFL_NAME) res = (StringContains(message, cs->name, qfalse) != -1);
+ else if (key->flags & RCKFL_BOTNAMES) res = (StringContains(key->string, cs->name, qfalse) != -1);
+ else if (key->flags & RCKFL_GENDERFEMALE) res = (cs->gender == CHAT_GENDERFEMALE);
+ else if (key->flags & RCKFL_GENDERMALE) res = (cs->gender == CHAT_GENDERMALE);
+ else if (key->flags & RCKFL_GENDERLESS) res = (cs->gender == CHAT_GENDERLESS);
+ else if (key->flags & RCKFL_VARIABLES) res = StringsMatch(key->match, &match);
+ else if (key->flags & RCKFL_STRING) res = (StringContainsWord(message, key->string, qfalse) != NULL);
+ //if the key must be present
+ if (key->flags & RCKFL_AND)
+ {
+ if (!res)
+ {
+ found = qfalse;
+ break;
+ } //end if
+ } //end else if
+ //if the key must be absent
+ else if (key->flags & RCKFL_NOT)
+ {
+ if (res)
+ {
+ found = qfalse;
+ break;
+ } //end if
+ } //end if
+ else if (res)
+ {
+ found = qtrue;
+ } //end else
+ } //end for
+ //
+ if (found)
+ {
+ if (rchat->priority > bestpriority)
+ {
+ numchatmessages = 0;
+ for (m = rchat->firstchatmessage; m; m = m->next)
+ {
+ if (m->time > AAS_Time()) continue;
+ numchatmessages++;
+ } //end if
+ num = random() * numchatmessages;
+ for (m = rchat->firstchatmessage; m; m = m->next)
+ {
+ if (--num < 0) break;
+ if (m->time > AAS_Time()) continue;
+ } //end for
+ //if the reply chat has a message
+ if (m)
+ {
+ Com_Memcpy(&bestmatch, &match, sizeof(bot_match_t));
+ bestchatmessage = m;
+ bestrchat = rchat;
+ bestpriority = rchat->priority;
+ } //end if
+ } //end if
+ } //end if
+ } //end for
+ if (bestchatmessage)
+ {
+ index = strlen(bestmatch.string);
+ if( var0 ) {
+ strcat(bestmatch.string, var0);
+ bestmatch.variables[0].offset = index;
+ bestmatch.variables[0].length = strlen(var0);
+ index += strlen(var0);
+ }
+ if( var1 ) {
+ strcat(bestmatch.string, var1);
+ bestmatch.variables[1].offset = index;
+ bestmatch.variables[1].length = strlen(var1);
+ index += strlen(var1);
+ }
+ if( var2 ) {
+ strcat(bestmatch.string, var2);
+ bestmatch.variables[2].offset = index;
+ bestmatch.variables[2].length = strlen(var2);
+ index += strlen(var2);
+ }
+ if( var3 ) {
+ strcat(bestmatch.string, var3);
+ bestmatch.variables[3].offset = index;
+ bestmatch.variables[3].length = strlen(var3);
+ index += strlen(var3);
+ }
+ if( var4 ) {
+ strcat(bestmatch.string, var4);
+ bestmatch.variables[4].offset = index;
+ bestmatch.variables[4].length = strlen(var4);
+ index += strlen(var4);
+ }
+ if( var5 ) {
+ strcat(bestmatch.string, var5);
+ bestmatch.variables[5].offset = index;
+ bestmatch.variables[5].length = strlen(var5);
+ index += strlen(var5);
+ }
+ if( var6 ) {
+ strcat(bestmatch.string, var6);
+ bestmatch.variables[6].offset = index;
+ bestmatch.variables[6].length = strlen(var6);
+ index += strlen(var6);
+ }
+ if( var7 ) {
+ strcat(bestmatch.string, var7);
+ bestmatch.variables[7].offset = index;
+ bestmatch.variables[7].length = strlen(var7);
+ index += strlen(var7);
+ }
+ if (LibVarGetValue("bot_testrchat"))
+ {
+ for (m = bestrchat->firstchatmessage; m; m = m->next)
+ {
+ BotConstructChatMessage(cs, m->chatmessage, mcontext, &bestmatch, vcontext, qtrue);
+ BotRemoveTildes(cs->chatmessage);
+ botimport.Print(PRT_MESSAGE, "%s\n", cs->chatmessage);
+ } //end if
+ } //end if
+ else
+ {
+ bestchatmessage->time = AAS_Time() + CHATMESSAGE_RECENTTIME;
+ BotConstructChatMessage(cs, bestchatmessage->chatmessage, mcontext, &bestmatch, vcontext, qtrue);
+ } //end else
+ return qtrue;
+ } //end if
+ return qfalse;
+} //end of the function BotReplyChat
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotChatLength(int chatstate)
+{
+ bot_chatstate_t *cs;
+
+ cs = BotChatStateFromHandle(chatstate);
+ if (!cs) return 0;
+ return strlen(cs->chatmessage);
+} //end of the function BotChatLength
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotEnterChat(int chatstate, int clientto, int sendto)
+{
+ bot_chatstate_t *cs;
+
+ cs = BotChatStateFromHandle(chatstate);
+ if (!cs) return;
+
+ if (strlen(cs->chatmessage))
+ {
+ BotRemoveTildes(cs->chatmessage);
+ if (LibVarGetValue("bot_testichat")) {
+ botimport.Print(PRT_MESSAGE, "%s\n", cs->chatmessage);
+ }
+ else {
+ switch(sendto) {
+ case CHAT_TEAM:
+ EA_Command(cs->client, va("say_team %s", cs->chatmessage));
+ break;
+ case CHAT_TELL:
+ EA_Command(cs->client, va("tell %d %s", clientto, cs->chatmessage));
+ break;
+ default: //CHAT_ALL
+ EA_Command(cs->client, va("say %s", cs->chatmessage));
+ break;
+ }
+ }
+ //clear the chat message from the state
+ strcpy(cs->chatmessage, "");
+ } //end if
+} //end of the function BotEnterChat
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotGetChatMessage(int chatstate, char *buf, int size)
+{
+ bot_chatstate_t *cs;
+
+ cs = BotChatStateFromHandle(chatstate);
+ if (!cs) return;
+
+ BotRemoveTildes(cs->chatmessage);
+ strncpy(buf, cs->chatmessage, size-1);
+ buf[size-1] = '\0';
+ //clear the chat message from the state
+ strcpy(cs->chatmessage, "");
+} //end of the function BotGetChatMessage
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotSetChatGender(int chatstate, int gender)
+{
+ bot_chatstate_t *cs;
+
+ cs = BotChatStateFromHandle(chatstate);
+ if (!cs) return;
+ switch(gender)
+ {
+ case CHAT_GENDERFEMALE: cs->gender = CHAT_GENDERFEMALE; break;
+ case CHAT_GENDERMALE: cs->gender = CHAT_GENDERMALE; break;
+ default: cs->gender = CHAT_GENDERLESS; break;
+ } //end switch
+} //end of the function BotSetChatGender
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotSetChatName(int chatstate, char *name, int client)
+{
+ bot_chatstate_t *cs;
+
+ cs = BotChatStateFromHandle(chatstate);
+ if (!cs) return;
+ cs->client = client;
+ Com_Memset(cs->name, 0, sizeof(cs->name));
+ strncpy(cs->name, name, sizeof(cs->name));
+ cs->name[sizeof(cs->name)-1] = '\0';
+} //end of the function BotSetChatName
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotResetChatAI(void)
+{
+ bot_replychat_t *rchat;
+ bot_chatmessage_t *m;
+
+ for (rchat = replychats; rchat; rchat = rchat->next)
+ {
+ for (m = rchat->firstchatmessage; m; m = m->next)
+ {
+ m->time = 0;
+ } //end for
+ } //end for
+} //end of the function BotResetChatAI
+//========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//========================================================================
+int BotAllocChatState(void)
+{
+ int i;
+
+ for (i = 1; i <= MAX_CLIENTS; i++)
+ {
+ if (!botchatstates[i])
+ {
+ botchatstates[i] = GetClearedMemory(sizeof(bot_chatstate_t));
+ return i;
+ } //end if
+ } //end for
+ return 0;
+} //end of the function BotAllocChatState
+//========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//========================================================================
+void BotFreeChatState(int handle)
+{
+ bot_chatstate_t *cs;
+ bot_consolemessage_t m;
+ int h;
+
+ if (handle <= 0 || handle > MAX_CLIENTS)
+ {
+ botimport.Print(PRT_FATAL, "chat state handle %d out of range\n", handle);
+ return;
+ } //end if
+ if (!botchatstates[handle])
+ {
+ botimport.Print(PRT_FATAL, "invalid chat state %d\n", handle);
+ return;
+ } //end if
+ cs = botchatstates[handle];
+ if (LibVarGetValue("bot_reloadcharacters"))
+ {
+ BotFreeChatFile(handle);
+ } //end if
+ //free all the console messages left in the chat state
+ for (h = BotNextConsoleMessage(handle, &m); h; h = BotNextConsoleMessage(handle, &m))
+ {
+ //remove the console message
+ BotRemoveConsoleMessage(handle, h);
+ } //end for
+ FreeMemory(botchatstates[handle]);
+ botchatstates[handle] = NULL;
+} //end of the function BotFreeChatState
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotSetupChatAI(void)
+{
+ char *file;
+
+#ifdef DEBUG
+ int starttime = Sys_MilliSeconds();
+#endif //DEBUG
+
+ file = LibVarString("synfile", "syn.c");
+ synonyms = BotLoadSynonyms(file);
+ file = LibVarString("rndfile", "rnd.c");
+ randomstrings = BotLoadRandomStrings(file);
+ file = LibVarString("matchfile", "match.c");
+ matchtemplates = BotLoadMatchTemplates(file);
+ //
+ if (!LibVarValue("nochat", "0"))
+ {
+ file = LibVarString("rchatfile", "rchat.c");
+ replychats = BotLoadReplyChat(file);
+ } //end if
+
+ InitConsoleMessageHeap();
+
+#ifdef DEBUG
+ botimport.Print(PRT_MESSAGE, "setup chat AI %d msec\n", Sys_MilliSeconds() - starttime);
+#endif //DEBUG
+ return BLERR_NOERROR;
+} //end of the function BotSetupChatAI
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotShutdownChatAI(void)
+{
+ int i;
+
+ //free all remaining chat states
+ for(i = 0; i < MAX_CLIENTS; i++)
+ {
+ if (botchatstates[i])
+ {
+ BotFreeChatState(i);
+ } //end if
+ } //end for
+ //free all cached chats
+ for(i = 0; i < MAX_CLIENTS; i++)
+ {
+ if (ichatdata[i])
+ {
+ FreeMemory(ichatdata[i]->chat);
+ FreeMemory(ichatdata[i]);
+ ichatdata[i] = NULL;
+ } //end if
+ } //end for
+ if (consolemessageheap) FreeMemory(consolemessageheap);
+ consolemessageheap = NULL;
+ if (matchtemplates) BotFreeMatchTemplates(matchtemplates);
+ matchtemplates = NULL;
+ if (randomstrings) FreeMemory(randomstrings);
+ randomstrings = NULL;
+ if (synonyms) FreeMemory(synonyms);
+ synonyms = NULL;
+ if (replychats) BotFreeReplyChat(replychats);
+ replychats = NULL;
+} //end of the function BotShutdownChatAI
diff --git a/code/botlib/be_ai_gen.c b/code/botlib/be_ai_gen.c
new file mode 100755
index 0000000..510d6b0
--- /dev/null
+++ b/code/botlib/be_ai_gen.c
@@ -0,0 +1,134 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_ai_gen.c
+ *
+ * desc: genetic selection
+ *
+ * $Archive: /MissionPack/code/botlib/be_ai_gen.c $
+ *
+ *****************************************************************************/
+
+#include "../game/q_shared.h"
+#include "l_memory.h"
+#include "l_log.h"
+#include "l_utils.h"
+#include "l_script.h"
+#include "l_precomp.h"
+#include "l_struct.h"
+#include "aasfile.h"
+#include "../game/botlib.h"
+#include "../game/be_aas.h"
+#include "be_aas_funcs.h"
+#include "be_interface.h"
+#include "../game/be_ai_gen.h"
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int GeneticSelection(int numranks, float *rankings)
+{
+ float sum, select;
+ int i, index;
+
+ sum = 0;
+ for (i = 0; i < numranks; i++)
+ {
+ if (rankings[i] < 0) continue;
+ sum += rankings[i];
+ } //end for
+ if (sum > 0)
+ {
+ //select a bot where the ones with the higest rankings have
+ //the highest chance of being selected
+ select = random() * sum;
+ for (i = 0; i < numranks; i++)
+ {
+ if (rankings[i] < 0) continue;
+ sum -= rankings[i];
+ if (sum <= 0) return i;
+ } //end for
+ } //end if
+ //select a bot randomly
+ index = random() * numranks;
+ for (i = 0; i < numranks; i++)
+ {
+ if (rankings[index] >= 0) return index;
+ index = (index + 1) % numranks;
+ } //end for
+ return 0;
+} //end of the function GeneticSelection
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int GeneticParentsAndChildSelection(int numranks, float *ranks, int *parent1, int *parent2, int *child)
+{
+ float rankings[256], max;
+ int i;
+
+ if (numranks > 256)
+ {
+ botimport.Print(PRT_WARNING, "GeneticParentsAndChildSelection: too many bots\n");
+ *parent1 = *parent2 = *child = 0;
+ return qfalse;
+ } //end if
+ for (max = 0, i = 0; i < numranks; i++)
+ {
+ if (ranks[i] < 0) continue;
+ max++;
+ } //end for
+ if (max < 3)
+ {
+ botimport.Print(PRT_WARNING, "GeneticParentsAndChildSelection: too few valid bots\n");
+ *parent1 = *parent2 = *child = 0;
+ return qfalse;
+ } //end if
+ Com_Memcpy(rankings, ranks, sizeof(float) * numranks);
+ //select first parent
+ *parent1 = GeneticSelection(numranks, rankings);
+ rankings[*parent1] = -1;
+ //select second parent
+ *parent2 = GeneticSelection(numranks, rankings);
+ rankings[*parent2] = -1;
+ //reverse the rankings
+ max = 0;
+ for (i = 0; i < numranks; i++)
+ {
+ if (rankings[i] < 0) continue;
+ if (rankings[i] > max) max = rankings[i];
+ } //end for
+ for (i = 0; i < numranks; i++)
+ {
+ if (rankings[i] < 0) continue;
+ rankings[i] = max - rankings[i];
+ } //end for
+ //select child
+ *child = GeneticSelection(numranks, rankings);
+ return qtrue;
+} //end of the function GeneticParentsAndChildSelection
diff --git a/code/botlib/be_ai_goal.c b/code/botlib/be_ai_goal.c
new file mode 100755
index 0000000..2735c57
--- /dev/null
+++ b/code/botlib/be_ai_goal.c
@@ -0,0 +1,1821 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_ai_goal.c
+ *
+ * desc: goal AI
+ *
+ * $Archive: /MissionPack/code/botlib/be_ai_goal.c $
+ *
+ *****************************************************************************/
+
+#include "../game/q_shared.h"
+#include "l_utils.h"
+#include "l_libvar.h"
+#include "l_memory.h"
+#include "l_log.h"
+#include "l_script.h"
+#include "l_precomp.h"
+#include "l_struct.h"
+#include "aasfile.h"
+#include "../game/botlib.h"
+#include "../game/be_aas.h"
+#include "be_aas_funcs.h"
+#include "be_interface.h"
+#include "be_ai_weight.h"
+#include "../game/be_ai_goal.h"
+#include "../game/be_ai_move.h"
+
+//#define DEBUG_AI_GOAL
+#ifdef RANDOMIZE
+#define UNDECIDEDFUZZY
+#endif //RANDOMIZE
+#define DROPPEDWEIGHT
+//minimum avoid goal time
+#define AVOID_MINIMUM_TIME 10
+//default avoid goal time
+#define AVOID_DEFAULT_TIME 30
+//avoid dropped goal time
+#define AVOID_DROPPED_TIME 10
+//
+#define TRAVELTIME_SCALE 0.01
+//item flags
+#define IFL_NOTFREE 1 //not in free for all
+#define IFL_NOTTEAM 2 //not in team play
+#define IFL_NOTSINGLE 4 //not in single player
+#define IFL_NOTBOT 8 //bot should never go for this
+#define IFL_ROAM 16 //bot roam goal
+
+//location in the map "target_location"
+typedef struct maplocation_s
+{
+ vec3_t origin;
+ int areanum;
+ char name[MAX_EPAIRKEY];
+ struct maplocation_s *next;
+} maplocation_t;
+
+//camp spots "info_camp"
+typedef struct campspot_s
+{
+ vec3_t origin;
+ int areanum;
+ char name[MAX_EPAIRKEY];
+ float range;
+ float weight;
+ float wait;
+ float random;
+ struct campspot_s *next;
+} campspot_t;
+
+//FIXME: these are game specific
+typedef enum {
+ GT_FFA, // free for all
+ GT_TOURNAMENT, // one on one tournament
+ GT_SINGLE_PLAYER, // single player tournament
+
+ //-- team games go after this --
+
+ GT_TEAM, // team deathmatch
+ GT_CTF, // capture the flag
+#ifdef MISSIONPACK
+ GT_1FCTF,
+ GT_OBELISK,
+ GT_HARVESTER,
+#endif
+ GT_MAX_GAME_TYPE
+} gametype_t;
+
+typedef struct levelitem_s
+{
+ int number; //number of the level item
+ int iteminfo; //index into the item info
+ int flags; //item flags
+ float weight; //fixed roam weight
+ vec3_t origin; //origin of the item
+ int goalareanum; //area the item is in
+ vec3_t goalorigin; //goal origin within the area
+ int entitynum; //entity number
+ float timeout; //item is removed after this time
+ struct levelitem_s *prev, *next;
+} levelitem_t;
+
+typedef struct iteminfo_s
+{
+ char classname[32]; //classname of the item
+ char name[MAX_STRINGFIELD]; //name of the item
+ char model[MAX_STRINGFIELD]; //model of the item
+ int modelindex; //model index
+ int type; //item type
+ int index; //index in the inventory
+ float respawntime; //respawn time
+ vec3_t mins; //mins of the item
+ vec3_t maxs; //maxs of the item
+ int number; //number of the item info
+} iteminfo_t;
+
+#define ITEMINFO_OFS(x) (int)&(((iteminfo_t *)0)->x)
+
+fielddef_t iteminfo_fields[] =
+{
+{"name", ITEMINFO_OFS(name), FT_STRING},
+{"model", ITEMINFO_OFS(model), FT_STRING},
+{"modelindex", ITEMINFO_OFS(modelindex), FT_INT},
+{"type", ITEMINFO_OFS(type), FT_INT},
+{"index", ITEMINFO_OFS(index), FT_INT},
+{"respawntime", ITEMINFO_OFS(respawntime), FT_FLOAT},
+{"mins", ITEMINFO_OFS(mins), FT_FLOAT|FT_ARRAY, 3},
+{"maxs", ITEMINFO_OFS(maxs), FT_FLOAT|FT_ARRAY, 3},
+{0, 0, 0}
+};
+
+structdef_t iteminfo_struct =
+{
+ sizeof(iteminfo_t), iteminfo_fields
+};
+
+typedef struct itemconfig_s
+{
+ int numiteminfo;
+ iteminfo_t *iteminfo;
+} itemconfig_t;
+
+//goal state
+typedef struct bot_goalstate_s
+{
+ struct weightconfig_s *itemweightconfig; //weight config
+ int *itemweightindex; //index from item to weight
+ //
+ int client; //client using this goal state
+ int lastreachabilityarea; //last area with reachabilities the bot was in
+ //
+ bot_goal_t goalstack[MAX_GOALSTACK]; //goal stack
+ int goalstacktop; //the top of the goal stack
+ //
+ int avoidgoals[MAX_AVOIDGOALS]; //goals to avoid
+ float avoidgoaltimes[MAX_AVOIDGOALS]; //times to avoid the goals
+} bot_goalstate_t;
+
+bot_goalstate_t *botgoalstates[MAX_CLIENTS + 1]; // bk001206 - FIXME: init?
+//item configuration
+itemconfig_t *itemconfig = NULL; // bk001206 - init
+//level items
+levelitem_t *levelitemheap = NULL; // bk001206 - init
+levelitem_t *freelevelitems = NULL; // bk001206 - init
+levelitem_t *levelitems = NULL; // bk001206 - init
+int numlevelitems = 0;
+//map locations
+maplocation_t *maplocations = NULL; // bk001206 - init
+//camp spots
+campspot_t *campspots = NULL; // bk001206 - init
+//the game type
+int g_gametype = 0; // bk001206 - init
+//additional dropped item weight
+libvar_t *droppedweight = NULL; // bk001206 - init
+
+//========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//========================================================================
+bot_goalstate_t *BotGoalStateFromHandle(int handle)
+{
+ if (handle <= 0 || handle > MAX_CLIENTS)
+ {
+ botimport.Print(PRT_FATAL, "goal state handle %d out of range\n", handle);
+ return NULL;
+ } //end if
+ if (!botgoalstates[handle])
+ {
+ botimport.Print(PRT_FATAL, "invalid goal state %d\n", handle);
+ return NULL;
+ } //end if
+ return botgoalstates[handle];
+} //end of the function BotGoalStateFromHandle
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotInterbreedGoalFuzzyLogic(int parent1, int parent2, int child)
+{
+ bot_goalstate_t *p1, *p2, *c;
+
+ p1 = BotGoalStateFromHandle(parent1);
+ p2 = BotGoalStateFromHandle(parent2);
+ c = BotGoalStateFromHandle(child);
+
+ InterbreedWeightConfigs(p1->itemweightconfig, p2->itemweightconfig,
+ c->itemweightconfig);
+} //end of the function BotInterbreedingGoalFuzzyLogic
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotSaveGoalFuzzyLogic(int goalstate, char *filename)
+{
+ bot_goalstate_t *gs;
+
+ gs = BotGoalStateFromHandle(goalstate);
+
+ //WriteWeightConfig(filename, gs->itemweightconfig);
+} //end of the function BotSaveGoalFuzzyLogic
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotMutateGoalFuzzyLogic(int goalstate, float range)
+{
+ bot_goalstate_t *gs;
+
+ gs = BotGoalStateFromHandle(goalstate);
+
+ EvolveWeightConfig(gs->itemweightconfig);
+} //end of the function BotMutateGoalFuzzyLogic
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+itemconfig_t *LoadItemConfig(char *filename)
+{
+ int max_iteminfo;
+ token_t token;
+ char path[MAX_PATH];
+ source_t *source;
+ itemconfig_t *ic;
+ iteminfo_t *ii;
+
+ max_iteminfo = (int) LibVarValue("max_iteminfo", "256");
+ if (max_iteminfo < 0)
+ {
+ botimport.Print(PRT_ERROR, "max_iteminfo = %d\n", max_iteminfo);
+ max_iteminfo = 256;
+ LibVarSet( "max_iteminfo", "256" );
+ }
+
+ strncpy( path, filename, MAX_PATH );
+ PC_SetBaseFolder(BOTFILESBASEFOLDER);
+ source = LoadSourceFile( path );
+ if( !source ) {
+ botimport.Print( PRT_ERROR, "counldn't load %s\n", path );
+ return NULL;
+ } //end if
+ //initialize item config
+ ic = (itemconfig_t *) GetClearedHunkMemory(sizeof(itemconfig_t) +
+ max_iteminfo * sizeof(iteminfo_t));
+ ic->iteminfo = (iteminfo_t *) ((char *) ic + sizeof(itemconfig_t));
+ ic->numiteminfo = 0;
+ //parse the item config file
+ while(PC_ReadToken(source, &token))
+ {
+ if (!strcmp(token.string, "iteminfo"))
+ {
+ if (ic->numiteminfo >= max_iteminfo)
+ {
+ SourceError(source, "more than %d item info defined\n", max_iteminfo);
+ FreeMemory(ic);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ ii = &ic->iteminfo[ic->numiteminfo];
+ Com_Memset(ii, 0, sizeof(iteminfo_t));
+ if (!PC_ExpectTokenType(source, TT_STRING, 0, &token))
+ {
+ FreeMemory(ic);
+ FreeMemory(source);
+ return NULL;
+ } //end if
+ StripDoubleQuotes(token.string);
+ strncpy(ii->classname, token.string, sizeof(ii->classname)-1);
+ if (!ReadStructure(source, &iteminfo_struct, (char *) ii))
+ {
+ FreeMemory(ic);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ ii->number = ic->numiteminfo;
+ ic->numiteminfo++;
+ } //end if
+ else
+ {
+ SourceError(source, "unknown definition %s\n", token.string);
+ FreeMemory(ic);
+ FreeSource(source);
+ return NULL;
+ } //end else
+ } //end while
+ FreeSource(source);
+ //
+ if (!ic->numiteminfo) botimport.Print(PRT_WARNING, "no item info loaded\n");
+ botimport.Print(PRT_MESSAGE, "loaded %s\n", path);
+ return ic;
+} //end of the function LoadItemConfig
+//===========================================================================
+// index to find the weight function of an iteminfo
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int *ItemWeightIndex(weightconfig_t *iwc, itemconfig_t *ic)
+{
+ int *index, i;
+
+ //initialize item weight index
+ index = (int *) GetClearedMemory(sizeof(int) * ic->numiteminfo);
+
+ for (i = 0; i < ic->numiteminfo; i++)
+ {
+ index[i] = FindFuzzyWeight(iwc, ic->iteminfo[i].classname);
+ if (index[i] < 0)
+ {
+ Log_Write("item info %d \"%s\" has no fuzzy weight\r\n", i, ic->iteminfo[i].classname);
+ } //end if
+ } //end for
+ return index;
+} //end of the function ItemWeightIndex
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void InitLevelItemHeap(void)
+{
+ int i, max_levelitems;
+
+ if (levelitemheap) FreeMemory(levelitemheap);
+
+ max_levelitems = (int) LibVarValue("max_levelitems", "256");
+ levelitemheap = (levelitem_t *) GetClearedMemory(max_levelitems * sizeof(levelitem_t));
+
+ for (i = 0; i < max_levelitems-1; i++)
+ {
+ levelitemheap[i].next = &levelitemheap[i + 1];
+ } //end for
+ levelitemheap[max_levelitems-1].next = NULL;
+ //
+ freelevelitems = levelitemheap;
+} //end of the function InitLevelItemHeap
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+levelitem_t *AllocLevelItem(void)
+{
+ levelitem_t *li;
+
+ li = freelevelitems;
+ if (!li)
+ {
+ botimport.Print(PRT_FATAL, "out of level items\n");
+ return NULL;
+ } //end if
+ //
+ freelevelitems = freelevelitems->next;
+ Com_Memset(li, 0, sizeof(levelitem_t));
+ return li;
+} //end of the function AllocLevelItem
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void FreeLevelItem(levelitem_t *li)
+{
+ li->next = freelevelitems;
+ freelevelitems = li;
+} //end of the function FreeLevelItem
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AddLevelItemToList(levelitem_t *li)
+{
+ if (levelitems) levelitems->prev = li;
+ li->prev = NULL;
+ li->next = levelitems;
+ levelitems = li;
+} //end of the function AddLevelItemToList
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void RemoveLevelItemFromList(levelitem_t *li)
+{
+ if (li->prev) li->prev->next = li->next;
+ else levelitems = li->next;
+ if (li->next) li->next->prev = li->prev;
+} //end of the function RemoveLevelItemFromList
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotFreeInfoEntities(void)
+{
+ maplocation_t *ml, *nextml;
+ campspot_t *cs, *nextcs;
+
+ for (ml = maplocations; ml; ml = nextml)
+ {
+ nextml = ml->next;
+ FreeMemory(ml);
+ } //end for
+ maplocations = NULL;
+ for (cs = campspots; cs; cs = nextcs)
+ {
+ nextcs = cs->next;
+ FreeMemory(cs);
+ } //end for
+ campspots = NULL;
+} //end of the function BotFreeInfoEntities
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotInitInfoEntities(void)
+{
+ char classname[MAX_EPAIRKEY];
+ maplocation_t *ml;
+ campspot_t *cs;
+ int ent, numlocations, numcampspots;
+
+ BotFreeInfoEntities();
+ //
+ numlocations = 0;
+ numcampspots = 0;
+ for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent))
+ {
+ if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) continue;
+
+ //map locations
+ if (!strcmp(classname, "target_location"))
+ {
+ ml = (maplocation_t *) GetClearedMemory(sizeof(maplocation_t));
+ AAS_VectorForBSPEpairKey(ent, "origin", ml->origin);
+ AAS_ValueForBSPEpairKey(ent, "message", ml->name, sizeof(ml->name));
+ ml->areanum = AAS_PointAreaNum(ml->origin);
+ ml->next = maplocations;
+ maplocations = ml;
+ numlocations++;
+ } //end if
+ //camp spots
+ else if (!strcmp(classname, "info_camp"))
+ {
+ cs = (campspot_t *) GetClearedMemory(sizeof(campspot_t));
+ AAS_VectorForBSPEpairKey(ent, "origin", cs->origin);
+ //cs->origin[2] += 16;
+ AAS_ValueForBSPEpairKey(ent, "message", cs->name, sizeof(cs->name));
+ AAS_FloatForBSPEpairKey(ent, "range", &cs->range);
+ AAS_FloatForBSPEpairKey(ent, "weight", &cs->weight);
+ AAS_FloatForBSPEpairKey(ent, "wait", &cs->wait);
+ AAS_FloatForBSPEpairKey(ent, "random", &cs->random);
+ cs->areanum = AAS_PointAreaNum(cs->origin);
+ if (!cs->areanum)
+ {
+ botimport.Print(PRT_MESSAGE, "camp spot at %1.1f %1.1f %1.1f in solid\n", cs->origin[0], cs->origin[1], cs->origin[2]);
+ FreeMemory(cs);
+ continue;
+ } //end if
+ cs->next = campspots;
+ campspots = cs;
+ //AAS_DrawPermanentCross(cs->origin, 4, LINECOLOR_YELLOW);
+ numcampspots++;
+ } //end else if
+ } //end for
+ if (bot_developer)
+ {
+ botimport.Print(PRT_MESSAGE, "%d map locations\n", numlocations);
+ botimport.Print(PRT_MESSAGE, "%d camp spots\n", numcampspots);
+ } //end if
+} //end of the function BotInitInfoEntities
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotInitLevelItems(void)
+{
+ int i, spawnflags, value;
+ char classname[MAX_EPAIRKEY];
+ vec3_t origin, end;
+ int ent, goalareanum;
+ itemconfig_t *ic;
+ levelitem_t *li;
+ bsp_trace_t trace;
+
+ //initialize the map locations and camp spots
+ BotInitInfoEntities();
+
+ //initialize the level item heap
+ InitLevelItemHeap();
+ levelitems = NULL;
+ numlevelitems = 0;
+ //
+ ic = itemconfig;
+ if (!ic) return;
+
+ //if there's no AAS file loaded
+ if (!AAS_Loaded()) return;
+
+ //update the modelindexes of the item info
+ for (i = 0; i < ic->numiteminfo; i++)
+ {
+ //ic->iteminfo[i].modelindex = AAS_IndexFromModel(ic->iteminfo[i].model);
+ if (!ic->iteminfo[i].modelindex)
+ {
+ Log_Write("item %s has modelindex 0", ic->iteminfo[i].classname);
+ } //end if
+ } //end for
+
+ for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent))
+ {
+ if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) continue;
+ //
+ spawnflags = 0;
+ AAS_IntForBSPEpairKey(ent, "spawnflags", &spawnflags);
+ //
+ for (i = 0; i < ic->numiteminfo; i++)
+ {
+ if (!strcmp(classname, ic->iteminfo[i].classname)) break;
+ } //end for
+ if (i >= ic->numiteminfo)
+ {
+ Log_Write("entity %s unknown item\r\n", classname);
+ continue;
+ } //end if
+ //get the origin of the item
+ if (!AAS_VectorForBSPEpairKey(ent, "origin", origin))
+ {
+ botimport.Print(PRT_ERROR, "item %s without origin\n", classname);
+ continue;
+ } //end else
+ //
+ goalareanum = 0;
+ //if it is a floating item
+ if (spawnflags & 1)
+ {
+ //if the item is not floating in water
+ if (!(AAS_PointContents(origin) & CONTENTS_WATER))
+ {
+ VectorCopy(origin, end);
+ end[2] -= 32;
+ trace = AAS_Trace(origin, ic->iteminfo[i].mins, ic->iteminfo[i].maxs, end, -1, CONTENTS_SOLID|CONTENTS_PLAYERCLIP);
+ //if the item not near the ground
+ if (trace.fraction >= 1)
+ {
+ //if the item is not reachable from a jumppad
+ goalareanum = AAS_BestReachableFromJumpPadArea(origin, ic->iteminfo[i].mins, ic->iteminfo[i].maxs);
+ Log_Write("item %s reachable from jumppad area %d\r\n", ic->iteminfo[i].classname, goalareanum);
+ //botimport.Print(PRT_MESSAGE, "item %s reachable from jumppad area %d\r\n", ic->iteminfo[i].classname, goalareanum);
+ if (!goalareanum) continue;
+ } //end if
+ } //end if
+ } //end if
+
+ li = AllocLevelItem();
+ if (!li) return;
+ //
+ li->number = ++numlevelitems;
+ li->timeout = 0;
+ li->entitynum = 0;
+ //
+ li->flags = 0;
+ AAS_IntForBSPEpairKey(ent, "notfree", &value);
+ if (value) li->flags |= IFL_NOTFREE;
+ AAS_IntForBSPEpairKey(ent, "notteam", &value);
+ if (value) li->flags |= IFL_NOTTEAM;
+ AAS_IntForBSPEpairKey(ent, "notsingle", &value);
+ if (value) li->flags |= IFL_NOTSINGLE;
+ AAS_IntForBSPEpairKey(ent, "notbot", &value);
+ if (value) li->flags |= IFL_NOTBOT;
+ if (!strcmp(classname, "item_botroam"))
+ {
+ li->flags |= IFL_ROAM;
+ AAS_FloatForBSPEpairKey(ent, "weight", &li->weight);
+ } //end if
+ //if not a stationary item
+ if (!(spawnflags & 1))
+ {
+ if (!AAS_DropToFloor(origin, ic->iteminfo[i].mins, ic->iteminfo[i].maxs))
+ {
+ botimport.Print(PRT_MESSAGE, "%s in solid at (%1.1f %1.1f %1.1f)\n",
+ classname, origin[0], origin[1], origin[2]);
+ } //end if
+ } //end if
+ //item info of the level item
+ li->iteminfo = i;
+ //origin of the item
+ VectorCopy(origin, li->origin);
+ //
+ if (goalareanum)
+ {
+ li->goalareanum = goalareanum;
+ VectorCopy(origin, li->goalorigin);
+ } //end if
+ else
+ {
+ //get the item goal area and goal origin
+ li->goalareanum = AAS_BestReachableArea(origin,
+ ic->iteminfo[i].mins, ic->iteminfo[i].maxs,
+ li->goalorigin);
+ if (!li->goalareanum)
+ {
+ botimport.Print(PRT_MESSAGE, "%s not reachable for bots at (%1.1f %1.1f %1.1f)\n",
+ classname, origin[0], origin[1], origin[2]);
+ } //end if
+ } //end else
+ //
+ AddLevelItemToList(li);
+ } //end for
+ botimport.Print(PRT_MESSAGE, "found %d level items\n", numlevelitems);
+} //end of the function BotInitLevelItems
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotGoalName(int number, char *name, int size)
+{
+ levelitem_t *li;
+
+ if (!itemconfig) return;
+ //
+ for (li = levelitems; li; li = li->next)
+ {
+ if (li->number == number)
+ {
+ strncpy(name, itemconfig->iteminfo[li->iteminfo].name, size-1);
+ name[size-1] = '\0';
+ return;
+ } //end for
+ } //end for
+ strcpy(name, "");
+ return;
+} //end of the function BotGoalName
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotResetAvoidGoals(int goalstate)
+{
+ bot_goalstate_t *gs;
+
+ gs = BotGoalStateFromHandle(goalstate);
+ if (!gs) return;
+ Com_Memset(gs->avoidgoals, 0, MAX_AVOIDGOALS * sizeof(int));
+ Com_Memset(gs->avoidgoaltimes, 0, MAX_AVOIDGOALS * sizeof(float));
+} //end of the function BotResetAvoidGoals
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotDumpAvoidGoals(int goalstate)
+{
+ int i;
+ bot_goalstate_t *gs;
+ char name[32];
+
+ gs = BotGoalStateFromHandle(goalstate);
+ if (!gs) return;
+ for (i = 0; i < MAX_AVOIDGOALS; i++)
+ {
+ if (gs->avoidgoaltimes[i] >= AAS_Time())
+ {
+ BotGoalName(gs->avoidgoals[i], name, 32);
+ Log_Write("avoid goal %s, number %d for %f seconds", name,
+ gs->avoidgoals[i], gs->avoidgoaltimes[i] - AAS_Time());
+ } //end if
+ } //end for
+} //end of the function BotDumpAvoidGoals
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotAddToAvoidGoals(bot_goalstate_t *gs, int number, float avoidtime)
+{
+ int i;
+
+ for (i = 0; i < MAX_AVOIDGOALS; i++)
+ {
+ //if the avoid goal is already stored
+ if (gs->avoidgoals[i] == number)
+ {
+ gs->avoidgoals[i] = number;
+ gs->avoidgoaltimes[i] = AAS_Time() + avoidtime;
+ return;
+ } //end if
+ } //end for
+
+ for (i = 0; i < MAX_AVOIDGOALS; i++)
+ {
+ //if this avoid goal has expired
+ if (gs->avoidgoaltimes[i] < AAS_Time())
+ {
+ gs->avoidgoals[i] = number;
+ gs->avoidgoaltimes[i] = AAS_Time() + avoidtime;
+ return;
+ } //end if
+ } //end for
+} //end of the function BotAddToAvoidGoals
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotRemoveFromAvoidGoals(int goalstate, int number)
+{
+ int i;
+ bot_goalstate_t *gs;
+
+ gs = BotGoalStateFromHandle(goalstate);
+ if (!gs) return;
+ //don't use the goals the bot wants to avoid
+ for (i = 0; i < MAX_AVOIDGOALS; i++)
+ {
+ if (gs->avoidgoals[i] == number && gs->avoidgoaltimes[i] >= AAS_Time())
+ {
+ gs->avoidgoaltimes[i] = 0;
+ return;
+ } //end if
+ } //end for
+} //end of the function BotRemoveFromAvoidGoals
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float BotAvoidGoalTime(int goalstate, int number)
+{
+ int i;
+ bot_goalstate_t *gs;
+
+ gs = BotGoalStateFromHandle(goalstate);
+ if (!gs) return 0;
+ //don't use the goals the bot wants to avoid
+ for (i = 0; i < MAX_AVOIDGOALS; i++)
+ {
+ if (gs->avoidgoals[i] == number && gs->avoidgoaltimes[i] >= AAS_Time())
+ {
+ return gs->avoidgoaltimes[i] - AAS_Time();
+ } //end if
+ } //end for
+ return 0;
+} //end of the function BotAvoidGoalTime
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotSetAvoidGoalTime(int goalstate, int number, float avoidtime)
+{
+ bot_goalstate_t *gs;
+ levelitem_t *li;
+
+ gs = BotGoalStateFromHandle(goalstate);
+ if (!gs)
+ return;
+ if (avoidtime < 0)
+ {
+ if (!itemconfig)
+ return;
+ //
+ for (li = levelitems; li; li = li->next)
+ {
+ if (li->number == number)
+ {
+ avoidtime = itemconfig->iteminfo[li->iteminfo].respawntime;
+ if (!avoidtime)
+ avoidtime = AVOID_DEFAULT_TIME;
+ if (avoidtime < AVOID_MINIMUM_TIME)
+ avoidtime = AVOID_MINIMUM_TIME;
+ BotAddToAvoidGoals(gs, number, avoidtime);
+ return;
+ } //end for
+ } //end for
+ return;
+ } //end if
+ else
+ {
+ BotAddToAvoidGoals(gs, number, avoidtime);
+ } //end else
+} //end of the function BotSetAvoidGoalTime
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotGetLevelItemGoal(int index, char *name, bot_goal_t *goal)
+{
+ levelitem_t *li;
+
+ if (!itemconfig) return -1;
+ li = levelitems;
+ if (index >= 0)
+ {
+ for (; li; li = li->next)
+ {
+ if (li->number == index)
+ {
+ li = li->next;
+ break;
+ } //end if
+ } //end for
+ } //end for
+ for (; li; li = li->next)
+ {
+ //
+ if (g_gametype == GT_SINGLE_PLAYER) {
+ if (li->flags & IFL_NOTSINGLE) continue;
+ }
+ else if (g_gametype >= GT_TEAM) {
+ if (li->flags & IFL_NOTTEAM) continue;
+ }
+ else {
+ if (li->flags & IFL_NOTFREE) continue;
+ }
+ if (li->flags & IFL_NOTBOT) continue;
+ //
+ if (!Q_stricmp(name, itemconfig->iteminfo[li->iteminfo].name))
+ {
+ goal->areanum = li->goalareanum;
+ VectorCopy(li->goalorigin, goal->origin);
+ goal->entitynum = li->entitynum;
+ VectorCopy(itemconfig->iteminfo[li->iteminfo].mins, goal->mins);
+ VectorCopy(itemconfig->iteminfo[li->iteminfo].maxs, goal->maxs);
+ goal->number = li->number;
+ goal->flags = GFL_ITEM;
+ if (li->timeout) goal->flags |= GFL_DROPPED;
+ //botimport.Print(PRT_MESSAGE, "found li %s\n", itemconfig->iteminfo[li->iteminfo].name);
+ return li->number;
+ } //end if
+ } //end for
+ return -1;
+} //end of the function BotGetLevelItemGoal
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotGetMapLocationGoal(char *name, bot_goal_t *goal)
+{
+ maplocation_t *ml;
+ vec3_t mins = {-8, -8, -8}, maxs = {8, 8, 8};
+
+ for (ml = maplocations; ml; ml = ml->next)
+ {
+ if (!Q_stricmp(ml->name, name))
+ {
+ goal->areanum = ml->areanum;
+ VectorCopy(ml->origin, goal->origin);
+ goal->entitynum = 0;
+ VectorCopy(mins, goal->mins);
+ VectorCopy(maxs, goal->maxs);
+ return qtrue;
+ } //end if
+ } //end for
+ return qfalse;
+} //end of the function BotGetMapLocationGoal
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotGetNextCampSpotGoal(int num, bot_goal_t *goal)
+{
+ int i;
+ campspot_t *cs;
+ vec3_t mins = {-8, -8, -8}, maxs = {8, 8, 8};
+
+ if (num < 0) num = 0;
+ i = num;
+ for (cs = campspots; cs; cs = cs->next)
+ {
+ if (--i < 0)
+ {
+ goal->areanum = cs->areanum;
+ VectorCopy(cs->origin, goal->origin);
+ goal->entitynum = 0;
+ VectorCopy(mins, goal->mins);
+ VectorCopy(maxs, goal->maxs);
+ return num+1;
+ } //end if
+ } //end for
+ return 0;
+} //end of the function BotGetNextCampSpotGoal
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotFindEntityForLevelItem(levelitem_t *li)
+{
+ int ent, modelindex;
+ itemconfig_t *ic;
+ aas_entityinfo_t entinfo;
+ vec3_t dir;
+
+ ic = itemconfig;
+ if (!itemconfig) return;
+ for (ent = AAS_NextEntity(0); ent; ent = AAS_NextEntity(ent))
+ {
+ //get the model index of the entity
+ modelindex = AAS_EntityModelindex(ent);
+ //
+ if (!modelindex) continue;
+ //get info about the entity
+ AAS_EntityInfo(ent, &entinfo);
+ //if the entity is still moving
+ if (entinfo.origin[0] != entinfo.lastvisorigin[0] ||
+ entinfo.origin[1] != entinfo.lastvisorigin[1] ||
+ entinfo.origin[2] != entinfo.lastvisorigin[2]) continue;
+ //
+ if (ic->iteminfo[li->iteminfo].modelindex == modelindex)
+ {
+ //check if the entity is very close
+ VectorSubtract(li->origin, entinfo.origin, dir);
+ if (VectorLength(dir) < 30)
+ {
+ //found an entity for this level item
+ li->entitynum = ent;
+ } //end if
+ } //end if
+ } //end for
+} //end of the function BotFindEntityForLevelItem
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+
+//NOTE: enum entityType_t in bg_public.h
+#define ET_ITEM 2
+
+void BotUpdateEntityItems(void)
+{
+ int ent, i, modelindex;
+ vec3_t dir;
+ levelitem_t *li, *nextli;
+ aas_entityinfo_t entinfo;
+ itemconfig_t *ic;
+
+ //timeout current entity items if necessary
+ for (li = levelitems; li; li = nextli)
+ {
+ nextli = li->next;
+ //if it is a item that will time out
+ if (li->timeout)
+ {
+ //timeout the item
+ if (li->timeout < AAS_Time())
+ {
+ RemoveLevelItemFromList(li);
+ FreeLevelItem(li);
+ } //end if
+ } //end if
+ } //end for
+ //find new entity items
+ ic = itemconfig;
+ if (!itemconfig) return;
+ //
+ for (ent = AAS_NextEntity(0); ent; ent = AAS_NextEntity(ent))
+ {
+ if (AAS_EntityType(ent) != ET_ITEM) continue;
+ //get the model index of the entity
+ modelindex = AAS_EntityModelindex(ent);
+ //
+ if (!modelindex) continue;
+ //get info about the entity
+ AAS_EntityInfo(ent, &entinfo);
+ //FIXME: don't do this
+ //skip all floating items for now
+ //if (entinfo.groundent != ENTITYNUM_WORLD) continue;
+ //if the entity is still moving
+ if (entinfo.origin[0] != entinfo.lastvisorigin[0] ||
+ entinfo.origin[1] != entinfo.lastvisorigin[1] ||
+ entinfo.origin[2] != entinfo.lastvisorigin[2]) continue;
+ //check if the entity is already stored as a level item
+ for (li = levelitems; li; li = li->next)
+ {
+ //if the level item is linked to an entity
+ if (li->entitynum && li->entitynum == ent)
+ {
+ //the entity is re-used if the models are different
+ if (ic->iteminfo[li->iteminfo].modelindex != modelindex)
+ {
+ //remove this level item
+ RemoveLevelItemFromList(li);
+ FreeLevelItem(li);
+ li = NULL;
+ break;
+ } //end if
+ else
+ {
+ if (entinfo.origin[0] != li->origin[0] ||
+ entinfo.origin[1] != li->origin[1] ||
+ entinfo.origin[2] != li->origin[2])
+ {
+ VectorCopy(entinfo.origin, li->origin);
+ //also update the goal area number
+ li->goalareanum = AAS_BestReachableArea(li->origin,
+ ic->iteminfo[li->iteminfo].mins, ic->iteminfo[li->iteminfo].maxs,
+ li->goalorigin);
+ } //end if
+ break;
+ } //end else
+ } //end if
+ } //end for
+ if (li) continue;
+ //try to link the entity to a level item
+ for (li = levelitems; li; li = li->next)
+ {
+ //if this level item is already linked
+ if (li->entitynum) continue;
+ //
+ if (g_gametype == GT_SINGLE_PLAYER) {
+ if (li->flags & IFL_NOTSINGLE) continue;
+ }
+ else if (g_gametype >= GT_TEAM) {
+ if (li->flags & IFL_NOTTEAM) continue;
+ }
+ else {
+ if (li->flags & IFL_NOTFREE) continue;
+ }
+ //if the model of the level item and the entity are the same
+ if (ic->iteminfo[li->iteminfo].modelindex == modelindex)
+ {
+ //check if the entity is very close
+ VectorSubtract(li->origin, entinfo.origin, dir);
+ if (VectorLength(dir) < 30)
+ {
+ //found an entity for this level item
+ li->entitynum = ent;
+ //if the origin is different
+ if (entinfo.origin[0] != li->origin[0] ||
+ entinfo.origin[1] != li->origin[1] ||
+ entinfo.origin[2] != li->origin[2])
+ {
+ //update the level item origin
+ VectorCopy(entinfo.origin, li->origin);
+ //also update the goal area number
+ li->goalareanum = AAS_BestReachableArea(li->origin,
+ ic->iteminfo[li->iteminfo].mins, ic->iteminfo[li->iteminfo].maxs,
+ li->goalorigin);
+ } //end if
+#ifdef DEBUG
+ Log_Write("linked item %s to an entity", ic->iteminfo[li->iteminfo].classname);
+#endif //DEBUG
+ break;
+ } //end if
+ } //end else
+ } //end for
+ if (li) continue;
+ //check if the model is from a known item
+ for (i = 0; i < ic->numiteminfo; i++)
+ {
+ if (ic->iteminfo[i].modelindex == modelindex)
+ {
+ break;
+ } //end if
+ } //end for
+ //if the model is not from a known item
+ if (i >= ic->numiteminfo) continue;
+ //allocate a new level item
+ li = AllocLevelItem();
+ //
+ if (!li) continue;
+ //entity number of the level item
+ li->entitynum = ent;
+ //number for the level item
+ li->number = numlevelitems + ent;
+ //set the item info index for the level item
+ li->iteminfo = i;
+ //origin of the item
+ VectorCopy(entinfo.origin, li->origin);
+ //get the item goal area and goal origin
+ li->goalareanum = AAS_BestReachableArea(li->origin,
+ ic->iteminfo[i].mins, ic->iteminfo[i].maxs,
+ li->goalorigin);
+ //never go for items dropped into jumppads
+ if (AAS_AreaJumpPad(li->goalareanum))
+ {
+ FreeLevelItem(li);
+ continue;
+ } //end if
+ //time this item out after 30 seconds
+ //dropped items disappear after 30 seconds
+ li->timeout = AAS_Time() + 30;
+ //add the level item to the list
+ AddLevelItemToList(li);
+ //botimport.Print(PRT_MESSAGE, "found new level item %s\n", ic->iteminfo[i].classname);
+ } //end for
+ /*
+ for (li = levelitems; li; li = li->next)
+ {
+ if (!li->entitynum)
+ {
+ BotFindEntityForLevelItem(li);
+ } //end if
+ } //end for*/
+} //end of the function BotUpdateEntityItems
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotDumpGoalStack(int goalstate)
+{
+ int i;
+ bot_goalstate_t *gs;
+ char name[32];
+
+ gs = BotGoalStateFromHandle(goalstate);
+ if (!gs) return;
+ for (i = 1; i <= gs->goalstacktop; i++)
+ {
+ BotGoalName(gs->goalstack[i].number, name, 32);
+ Log_Write("%d: %s", i, name);
+ } //end for
+} //end of the function BotDumpGoalStack
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotPushGoal(int goalstate, bot_goal_t *goal)
+{
+ bot_goalstate_t *gs;
+
+ gs = BotGoalStateFromHandle(goalstate);
+ if (!gs) return;
+ if (gs->goalstacktop >= MAX_GOALSTACK-1)
+ {
+ botimport.Print(PRT_ERROR, "goal heap overflow\n");
+ BotDumpGoalStack(goalstate);
+ return;
+ } //end if
+ gs->goalstacktop++;
+ Com_Memcpy(&gs->goalstack[gs->goalstacktop], goal, sizeof(bot_goal_t));
+} //end of the function BotPushGoal
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotPopGoal(int goalstate)
+{
+ bot_goalstate_t *gs;
+
+ gs = BotGoalStateFromHandle(goalstate);
+ if (!gs) return;
+ if (gs->goalstacktop > 0) gs->goalstacktop--;
+} //end of the function BotPopGoal
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotEmptyGoalStack(int goalstate)
+{
+ bot_goalstate_t *gs;
+
+ gs = BotGoalStateFromHandle(goalstate);
+ if (!gs) return;
+ gs->goalstacktop = 0;
+} //end of the function BotEmptyGoalStack
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotGetTopGoal(int goalstate, bot_goal_t *goal)
+{
+ bot_goalstate_t *gs;
+
+ gs = BotGoalStateFromHandle(goalstate);
+ if (!gs) return qfalse;
+ if (!gs->goalstacktop) return qfalse;
+ Com_Memcpy(goal, &gs->goalstack[gs->goalstacktop], sizeof(bot_goal_t));
+ return qtrue;
+} //end of the function BotGetTopGoal
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotGetSecondGoal(int goalstate, bot_goal_t *goal)
+{
+ bot_goalstate_t *gs;
+
+ gs = BotGoalStateFromHandle(goalstate);
+ if (!gs) return qfalse;
+ if (gs->goalstacktop <= 1) return qfalse;
+ Com_Memcpy(goal, &gs->goalstack[gs->goalstacktop-1], sizeof(bot_goal_t));
+ return qtrue;
+} //end of the function BotGetSecondGoal
+//===========================================================================
+// pops a new long term goal on the goal stack in the goalstate
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotChooseLTGItem(int goalstate, vec3_t origin, int *inventory, int travelflags)
+{
+ int areanum, t, weightnum;
+ float weight, bestweight, avoidtime;
+ iteminfo_t *iteminfo;
+ itemconfig_t *ic;
+ levelitem_t *li, *bestitem;
+ bot_goal_t goal;
+ bot_goalstate_t *gs;
+
+ gs = BotGoalStateFromHandle(goalstate);
+ if (!gs)
+ return qfalse;
+ if (!gs->itemweightconfig)
+ return qfalse;
+ //get the area the bot is in
+ areanum = BotReachabilityArea(origin, gs->client);
+ //if the bot is in solid or if the area the bot is in has no reachability links
+ if (!areanum || !AAS_AreaReachability(areanum))
+ {
+ //use the last valid area the bot was in
+ areanum = gs->lastreachabilityarea;
+ } //end if
+ //remember the last area with reachabilities the bot was in
+ gs->lastreachabilityarea = areanum;
+ //if still in solid
+ if (!areanum)
+ return qfalse;
+ //the item configuration
+ ic = itemconfig;
+ if (!itemconfig)
+ return qfalse;
+ //best weight and item so far
+ bestweight = 0;
+ bestitem = NULL;
+ Com_Memset(&goal, 0, sizeof(bot_goal_t));
+ //go through the items in the level
+ for (li = levelitems; li; li = li->next)
+ {
+ if (g_gametype == GT_SINGLE_PLAYER) {
+ if (li->flags & IFL_NOTSINGLE)
+ continue;
+ }
+ else if (g_gametype >= GT_TEAM) {
+ if (li->flags & IFL_NOTTEAM)
+ continue;
+ }
+ else {
+ if (li->flags & IFL_NOTFREE)
+ continue;
+ }
+ if (li->flags & IFL_NOTBOT)
+ continue;
+ //if the item is not in a possible goal area
+ if (!li->goalareanum)
+ continue;
+ //FIXME: is this a good thing? added this for items that never spawned into the game (f.i. CTF flags in obelisk)
+ if (!li->entitynum && !(li->flags & IFL_ROAM))
+ continue;
+ //get the fuzzy weight function for this item
+ iteminfo = &ic->iteminfo[li->iteminfo];
+ weightnum = gs->itemweightindex[iteminfo->number];
+ if (weightnum < 0)
+ continue;
+
+#ifdef UNDECIDEDFUZZY
+ weight = FuzzyWeightUndecided(inventory, gs->itemweightconfig, weightnum);
+#else
+ weight = FuzzyWeight(inventory, gs->itemweightconfig, weightnum);
+#endif //UNDECIDEDFUZZY
+#ifdef DROPPEDWEIGHT
+ //HACK: to make dropped items more attractive
+ if (li->timeout)
+ weight += droppedweight->value;
+#endif //DROPPEDWEIGHT
+ //use weight scale for item_botroam
+ if (li->flags & IFL_ROAM) weight *= li->weight;
+ //
+ if (weight > 0)
+ {
+ //get the travel time towards the goal area
+ t = AAS_AreaTravelTimeToGoalArea(areanum, origin, li->goalareanum, travelflags);
+ //if the goal is reachable
+ if (t > 0)
+ {
+ //if this item won't respawn before we get there
+ avoidtime = BotAvoidGoalTime(goalstate, li->number);
+ if (avoidtime - t * 0.009 > 0)
+ continue;
+ //
+ weight /= (float) t * TRAVELTIME_SCALE;
+ //
+ if (weight > bestweight)
+ {
+ bestweight = weight;
+ bestitem = li;
+ } //end if
+ } //end if
+ } //end if
+ } //end for
+ //if no goal item found
+ if (!bestitem)
+ {
+ /*
+ //if not in lava or slime
+ if (!AAS_AreaLava(areanum) && !AAS_AreaSlime(areanum))
+ {
+ if (AAS_RandomGoalArea(areanum, travelflags, &goal.areanum, goal.origin))
+ {
+ VectorSet(goal.mins, -15, -15, -15);
+ VectorSet(goal.maxs, 15, 15, 15);
+ goal.entitynum = 0;
+ goal.number = 0;
+ goal.flags = GFL_ROAM;
+ goal.iteminfo = 0;
+ //push the goal on the stack
+ BotPushGoal(goalstate, &goal);
+ //
+#ifdef DEBUG
+ botimport.Print(PRT_MESSAGE, "chosen roam goal area %d\n", goal.areanum);
+#endif //DEBUG
+ return qtrue;
+ } //end if
+ } //end if
+ */
+ return qfalse;
+ } //end if
+ //create a bot goal for this item
+ iteminfo = &ic->iteminfo[bestitem->iteminfo];
+ VectorCopy(bestitem->goalorigin, goal.origin);
+ VectorCopy(iteminfo->mins, goal.mins);
+ VectorCopy(iteminfo->maxs, goal.maxs);
+ goal.areanum = bestitem->goalareanum;
+ goal.entitynum = bestitem->entitynum;
+ goal.number = bestitem->number;
+ goal.flags = GFL_ITEM;
+ if (bestitem->timeout)
+ goal.flags |= GFL_DROPPED;
+ if (bestitem->flags & IFL_ROAM)
+ goal.flags |= GFL_ROAM;
+ goal.iteminfo = bestitem->iteminfo;
+ //if it's a dropped item
+ if (bestitem->timeout)
+ {
+ avoidtime = AVOID_DROPPED_TIME;
+ } //end if
+ else
+ {
+ avoidtime = iteminfo->respawntime;
+ if (!avoidtime)
+ avoidtime = AVOID_DEFAULT_TIME;
+ if (avoidtime < AVOID_MINIMUM_TIME)
+ avoidtime = AVOID_MINIMUM_TIME;
+ } //end else
+ //add the chosen goal to the goals to avoid for a while
+ BotAddToAvoidGoals(gs, bestitem->number, avoidtime);
+ //push the goal on the stack
+ BotPushGoal(goalstate, &goal);
+ //
+ return qtrue;
+} //end of the function BotChooseLTGItem
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotChooseNBGItem(int goalstate, vec3_t origin, int *inventory, int travelflags,
+ bot_goal_t *ltg, float maxtime)
+{
+ int areanum, t, weightnum, ltg_time;
+ float weight, bestweight, avoidtime;
+ iteminfo_t *iteminfo;
+ itemconfig_t *ic;
+ levelitem_t *li, *bestitem;
+ bot_goal_t goal;
+ bot_goalstate_t *gs;
+
+ gs = BotGoalStateFromHandle(goalstate);
+ if (!gs)
+ return qfalse;
+ if (!gs->itemweightconfig)
+ return qfalse;
+ //get the area the bot is in
+ areanum = BotReachabilityArea(origin, gs->client);
+ //if the bot is in solid or if the area the bot is in has no reachability links
+ if (!areanum || !AAS_AreaReachability(areanum))
+ {
+ //use the last valid area the bot was in
+ areanum = gs->lastreachabilityarea;
+ } //end if
+ //remember the last area with reachabilities the bot was in
+ gs->lastreachabilityarea = areanum;
+ //if still in solid
+ if (!areanum)
+ return qfalse;
+ //
+ if (ltg) ltg_time = AAS_AreaTravelTimeToGoalArea(areanum, origin, ltg->areanum, travelflags);
+ else ltg_time = 99999;
+ //the item configuration
+ ic = itemconfig;
+ if (!itemconfig)
+ return qfalse;
+ //best weight and item so far
+ bestweight = 0;
+ bestitem = NULL;
+ Com_Memset(&goal, 0, sizeof(bot_goal_t));
+ //go through the items in the level
+ for (li = levelitems; li; li = li->next)
+ {
+ if (g_gametype == GT_SINGLE_PLAYER) {
+ if (li->flags & IFL_NOTSINGLE)
+ continue;
+ }
+ else if (g_gametype >= GT_TEAM) {
+ if (li->flags & IFL_NOTTEAM)
+ continue;
+ }
+ else {
+ if (li->flags & IFL_NOTFREE)
+ continue;
+ }
+ if (li->flags & IFL_NOTBOT)
+ continue;
+ //if the item is in a possible goal area
+ if (!li->goalareanum)
+ continue;
+ //FIXME: is this a good thing? added this for items that never spawned into the game (f.i. CTF flags in obelisk)
+ if (!li->entitynum && !(li->flags & IFL_ROAM))
+ continue;
+ //get the fuzzy weight function for this item
+ iteminfo = &ic->iteminfo[li->iteminfo];
+ weightnum = gs->itemweightindex[iteminfo->number];
+ if (weightnum < 0)
+ continue;
+ //
+#ifdef UNDECIDEDFUZZY
+ weight = FuzzyWeightUndecided(inventory, gs->itemweightconfig, weightnum);
+#else
+ weight = FuzzyWeight(inventory, gs->itemweightconfig, weightnum);
+#endif //UNDECIDEDFUZZY
+#ifdef DROPPEDWEIGHT
+ //HACK: to make dropped items more attractive
+ if (li->timeout)
+ weight += droppedweight->value;
+#endif //DROPPEDWEIGHT
+ //use weight scale for item_botroam
+ if (li->flags & IFL_ROAM) weight *= li->weight;
+ //
+ if (weight > 0)
+ {
+ //get the travel time towards the goal area
+ t = AAS_AreaTravelTimeToGoalArea(areanum, origin, li->goalareanum, travelflags);
+ //if the goal is reachable
+ if (t > 0 && t < maxtime)
+ {
+ //if this item won't respawn before we get there
+ avoidtime = BotAvoidGoalTime(goalstate, li->number);
+ if (avoidtime - t * 0.009 > 0)
+ continue;
+ //
+ weight /= (float) t * TRAVELTIME_SCALE;
+ //
+ if (weight > bestweight)
+ {
+ t = 0;
+ if (ltg && !li->timeout)
+ {
+ //get the travel time from the goal to the long term goal
+ t = AAS_AreaTravelTimeToGoalArea(li->goalareanum, li->goalorigin, ltg->areanum, travelflags);
+ } //end if
+ //if the travel back is possible and doesn't take too long
+ if (t <= ltg_time)
+ {
+ bestweight = weight;
+ bestitem = li;
+ } //end if
+ } //end if
+ } //end if
+ } //end if
+ } //end for
+ //if no goal item found
+ if (!bestitem)
+ return qfalse;
+ //create a bot goal for this item
+ iteminfo = &ic->iteminfo[bestitem->iteminfo];
+ VectorCopy(bestitem->goalorigin, goal.origin);
+ VectorCopy(iteminfo->mins, goal.mins);
+ VectorCopy(iteminfo->maxs, goal.maxs);
+ goal.areanum = bestitem->goalareanum;
+ goal.entitynum = bestitem->entitynum;
+ goal.number = bestitem->number;
+ goal.flags = GFL_ITEM;
+ if (bestitem->timeout)
+ goal.flags |= GFL_DROPPED;
+ if (bestitem->flags & IFL_ROAM)
+ goal.flags |= GFL_ROAM;
+ goal.iteminfo = bestitem->iteminfo;
+ //if it's a dropped item
+ if (bestitem->timeout)
+ {
+ avoidtime = AVOID_DROPPED_TIME;
+ } //end if
+ else
+ {
+ avoidtime = iteminfo->respawntime;
+ if (!avoidtime)
+ avoidtime = AVOID_DEFAULT_TIME;
+ if (avoidtime < AVOID_MINIMUM_TIME)
+ avoidtime = AVOID_MINIMUM_TIME;
+ } //end else
+ //add the chosen goal to the goals to avoid for a while
+ BotAddToAvoidGoals(gs, bestitem->number, avoidtime);
+ //push the goal on the stack
+ BotPushGoal(goalstate, &goal);
+ //
+ return qtrue;
+} //end of the function BotChooseNBGItem
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotTouchingGoal(vec3_t origin, bot_goal_t *goal)
+{
+ int i;
+ vec3_t boxmins, boxmaxs;
+ vec3_t absmins, absmaxs;
+ vec3_t safety_maxs = {0, 0, 0}; //{4, 4, 10};
+ vec3_t safety_mins = {0, 0, 0}; //{-4, -4, 0};
+
+ AAS_PresenceTypeBoundingBox(PRESENCE_NORMAL, boxmins, boxmaxs);
+ VectorSubtract(goal->mins, boxmaxs, absmins);
+ VectorSubtract(goal->maxs, boxmins, absmaxs);
+ VectorAdd(absmins, goal->origin, absmins);
+ VectorAdd(absmaxs, goal->origin, absmaxs);
+ //make the box a little smaller for safety
+ VectorSubtract(absmaxs, safety_maxs, absmaxs);
+ VectorSubtract(absmins, safety_mins, absmins);
+
+ for (i = 0; i < 3; i++)
+ {
+ if (origin[i] < absmins[i] || origin[i] > absmaxs[i]) return qfalse;
+ } //end for
+ return qtrue;
+} //end of the function BotTouchingGoal
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotItemGoalInVisButNotVisible(int viewer, vec3_t eye, vec3_t viewangles, bot_goal_t *goal)
+{
+ aas_entityinfo_t entinfo;
+ bsp_trace_t trace;
+ vec3_t middle;
+
+ if (!(goal->flags & GFL_ITEM)) return qfalse;
+ //
+ VectorAdd(goal->mins, goal->mins, middle);
+ VectorScale(middle, 0.5, middle);
+ VectorAdd(goal->origin, middle, middle);
+ //
+ trace = AAS_Trace(eye, NULL, NULL, middle, viewer, CONTENTS_SOLID);
+ //if the goal middle point is visible
+ if (trace.fraction >= 1)
+ {
+ //the goal entity number doesn't have to be valid
+ //just assume it's valid
+ if (goal->entitynum <= 0)
+ return qfalse;
+ //
+ //if the entity data isn't valid
+ AAS_EntityInfo(goal->entitynum, &entinfo);
+ //NOTE: for some wacko reason entities are sometimes
+ // not updated
+ //if (!entinfo.valid) return qtrue;
+ if (entinfo.ltime < AAS_Time() - 0.5)
+ return qtrue;
+ } //end if
+ return qfalse;
+} //end of the function BotItemGoalInVisButNotVisible
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotResetGoalState(int goalstate)
+{
+ bot_goalstate_t *gs;
+
+ gs = BotGoalStateFromHandle(goalstate);
+ if (!gs) return;
+ Com_Memset(gs->goalstack, 0, MAX_GOALSTACK * sizeof(bot_goal_t));
+ gs->goalstacktop = 0;
+ BotResetAvoidGoals(goalstate);
+} //end of the function BotResetGoalState
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotLoadItemWeights(int goalstate, char *filename)
+{
+ bot_goalstate_t *gs;
+
+ gs = BotGoalStateFromHandle(goalstate);
+ if (!gs) return BLERR_CANNOTLOADITEMWEIGHTS;
+ //load the weight configuration
+ gs->itemweightconfig = ReadWeightConfig(filename);
+ if (!gs->itemweightconfig)
+ {
+ botimport.Print(PRT_FATAL, "couldn't load weights\n");
+ return BLERR_CANNOTLOADITEMWEIGHTS;
+ } //end if
+ //if there's no item configuration
+ if (!itemconfig) return BLERR_CANNOTLOADITEMWEIGHTS;
+ //create the item weight index
+ gs->itemweightindex = ItemWeightIndex(gs->itemweightconfig, itemconfig);
+ //everything went ok
+ return BLERR_NOERROR;
+} //end of the function BotLoadItemWeights
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotFreeItemWeights(int goalstate)
+{
+ bot_goalstate_t *gs;
+
+ gs = BotGoalStateFromHandle(goalstate);
+ if (!gs) return;
+ if (gs->itemweightconfig) FreeWeightConfig(gs->itemweightconfig);
+ if (gs->itemweightindex) FreeMemory(gs->itemweightindex);
+} //end of the function BotFreeItemWeights
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotAllocGoalState(int client)
+{
+ int i;
+
+ for (i = 1; i <= MAX_CLIENTS; i++)
+ {
+ if (!botgoalstates[i])
+ {
+ botgoalstates[i] = GetClearedMemory(sizeof(bot_goalstate_t));
+ botgoalstates[i]->client = client;
+ return i;
+ } //end if
+ } //end for
+ return 0;
+} //end of the function BotAllocGoalState
+//========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//========================================================================
+void BotFreeGoalState(int handle)
+{
+ if (handle <= 0 || handle > MAX_CLIENTS)
+ {
+ botimport.Print(PRT_FATAL, "goal state handle %d out of range\n", handle);
+ return;
+ } //end if
+ if (!botgoalstates[handle])
+ {
+ botimport.Print(PRT_FATAL, "invalid goal state handle %d\n", handle);
+ return;
+ } //end if
+ BotFreeItemWeights(handle);
+ FreeMemory(botgoalstates[handle]);
+ botgoalstates[handle] = NULL;
+} //end of the function BotFreeGoalState
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotSetupGoalAI(void)
+{
+ char *filename;
+
+ //check if teamplay is on
+ g_gametype = LibVarValue("g_gametype", "0");
+ //item configuration file
+ filename = LibVarString("itemconfig", "items.c");
+ //load the item configuration
+ itemconfig = LoadItemConfig(filename);
+ if (!itemconfig)
+ {
+ botimport.Print(PRT_FATAL, "couldn't load item config\n");
+ return BLERR_CANNOTLOADITEMCONFIG;
+ } //end if
+ //
+ droppedweight = LibVar("droppedweight", "1000");
+ //everything went ok
+ return BLERR_NOERROR;
+} //end of the function BotSetupGoalAI
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotShutdownGoalAI(void)
+{
+ int i;
+
+ if (itemconfig) FreeMemory(itemconfig);
+ itemconfig = NULL;
+ if (levelitemheap) FreeMemory(levelitemheap);
+ levelitemheap = NULL;
+ freelevelitems = NULL;
+ levelitems = NULL;
+ numlevelitems = 0;
+
+ BotFreeInfoEntities();
+
+ for (i = 1; i <= MAX_CLIENTS; i++)
+ {
+ if (botgoalstates[i])
+ {
+ BotFreeGoalState(i);
+ } //end if
+ } //end for
+} //end of the function BotShutdownGoalAI
diff --git a/code/botlib/be_ai_move.c b/code/botlib/be_ai_move.c
new file mode 100755
index 0000000..210d4d9
--- /dev/null
+++ b/code/botlib/be_ai_move.c
@@ -0,0 +1,3610 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_ai_move.c
+ *
+ * desc: bot movement AI
+ *
+ * $Archive: /MissionPack/code/botlib/be_ai_move.c $
+ *
+ *****************************************************************************/
+
+#include "../game/q_shared.h"
+#include "l_memory.h"
+#include "l_libvar.h"
+#include "l_utils.h"
+#include "l_script.h"
+#include "l_precomp.h"
+#include "l_struct.h"
+#include "aasfile.h"
+#include "../game/botlib.h"
+#include "../game/be_aas.h"
+#include "be_aas_funcs.h"
+#include "be_interface.h"
+
+#include "../game/be_ea.h"
+#include "../game/be_ai_goal.h"
+#include "../game/be_ai_move.h"
+
+
+//#define DEBUG_AI_MOVE
+//#define DEBUG_ELEVATOR
+//#define DEBUG_GRAPPLE
+
+// bk001204 - redundant bot_avoidspot_t, see ../game/be_ai_move.h
+
+//movement state
+//NOTE: the moveflags MFL_ONGROUND, MFL_TELEPORTED, MFL_WATERJUMP and
+// MFL_GRAPPLEPULL must be set outside the movement code
+typedef struct bot_movestate_s
+{
+ //input vars (all set outside the movement code)
+ vec3_t origin; //origin of the bot
+ vec3_t velocity; //velocity of the bot
+ vec3_t viewoffset; //view offset
+ int entitynum; //entity number of the bot
+ int client; //client number of the bot
+ float thinktime; //time the bot thinks
+ int presencetype; //presencetype of the bot
+ vec3_t viewangles; //view angles of the bot
+ //state vars
+ int areanum; //area the bot is in
+ int lastareanum; //last area the bot was in
+ int lastgoalareanum; //last goal area number
+ int lastreachnum; //last reachability number
+ vec3_t lastorigin; //origin previous cycle
+ int reachareanum; //area number of the reachabilty
+ int moveflags; //movement flags
+ int jumpreach; //set when jumped
+ float grapplevisible_time; //last time the grapple was visible
+ float lastgrappledist; //last distance to the grapple end
+ float reachability_time; //time to use current reachability
+ int avoidreach[MAX_AVOIDREACH]; //reachabilities to avoid
+ float avoidreachtimes[MAX_AVOIDREACH]; //times to avoid the reachabilities
+ int avoidreachtries[MAX_AVOIDREACH]; //number of tries before avoiding
+ //
+ bot_avoidspot_t avoidspots[MAX_AVOIDSPOTS]; //spots to avoid
+ int numavoidspots;
+} bot_movestate_t;
+
+//used to avoid reachability links for some time after being used
+#define AVOIDREACH
+#define AVOIDREACH_TIME 6 //avoid links for 6 seconds after use
+#define AVOIDREACH_TRIES 4
+//prediction times
+#define PREDICTIONTIME_JUMP 3 //in seconds
+#define PREDICTIONTIME_MOVE 2 //in seconds
+//weapon indexes for weapon jumping
+#define WEAPONINDEX_ROCKET_LAUNCHER 5
+#define WEAPONINDEX_BFG 9
+
+#define MODELTYPE_FUNC_PLAT 1
+#define MODELTYPE_FUNC_BOB 2
+#define MODELTYPE_FUNC_DOOR 3
+#define MODELTYPE_FUNC_STATIC 4
+
+libvar_t *sv_maxstep;
+libvar_t *sv_maxbarrier;
+libvar_t *sv_gravity;
+libvar_t *weapindex_rocketlauncher;
+libvar_t *weapindex_bfg10k;
+libvar_t *weapindex_grapple;
+libvar_t *entitytypemissile;
+libvar_t *offhandgrapple;
+libvar_t *cmd_grappleoff;
+libvar_t *cmd_grappleon;
+//type of model, func_plat or func_bobbing
+int modeltypes[MAX_MODELS];
+
+bot_movestate_t *botmovestates[MAX_CLIENTS+1];
+
+//========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//========================================================================
+int BotAllocMoveState(void)
+{
+ int i;
+
+ for (i = 1; i <= MAX_CLIENTS; i++)
+ {
+ if (!botmovestates[i])
+ {
+ botmovestates[i] = GetClearedMemory(sizeof(bot_movestate_t));
+ return i;
+ } //end if
+ } //end for
+ return 0;
+} //end of the function BotAllocMoveState
+//========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//========================================================================
+void BotFreeMoveState(int handle)
+{
+ if (handle <= 0 || handle > MAX_CLIENTS)
+ {
+ botimport.Print(PRT_FATAL, "move state handle %d out of range\n", handle);
+ return;
+ } //end if
+ if (!botmovestates[handle])
+ {
+ botimport.Print(PRT_FATAL, "invalid move state %d\n", handle);
+ return;
+ } //end if
+ FreeMemory(botmovestates[handle]);
+ botmovestates[handle] = NULL;
+} //end of the function BotFreeMoveState
+//========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//========================================================================
+bot_movestate_t *BotMoveStateFromHandle(int handle)
+{
+ if (handle <= 0 || handle > MAX_CLIENTS)
+ {
+ botimport.Print(PRT_FATAL, "move state handle %d out of range\n", handle);
+ return NULL;
+ } //end if
+ if (!botmovestates[handle])
+ {
+ botimport.Print(PRT_FATAL, "invalid move state %d\n", handle);
+ return NULL;
+ } //end if
+ return botmovestates[handle];
+} //end of the function BotMoveStateFromHandle
+//========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//========================================================================
+void BotInitMoveState(int handle, bot_initmove_t *initmove)
+{
+ bot_movestate_t *ms;
+
+ ms = BotMoveStateFromHandle(handle);
+ if (!ms) return;
+ VectorCopy(initmove->origin, ms->origin);
+ VectorCopy(initmove->velocity, ms->velocity);
+ VectorCopy(initmove->viewoffset, ms->viewoffset);
+ ms->entitynum = initmove->entitynum;
+ ms->client = initmove->client;
+ ms->thinktime = initmove->thinktime;
+ ms->presencetype = initmove->presencetype;
+ VectorCopy(initmove->viewangles, ms->viewangles);
+ //
+ ms->moveflags &= ~MFL_ONGROUND;
+ if (initmove->or_moveflags & MFL_ONGROUND) ms->moveflags |= MFL_ONGROUND;
+ ms->moveflags &= ~MFL_TELEPORTED;
+ if (initmove->or_moveflags & MFL_TELEPORTED) ms->moveflags |= MFL_TELEPORTED;
+ ms->moveflags &= ~MFL_WATERJUMP;
+ if (initmove->or_moveflags & MFL_WATERJUMP) ms->moveflags |= MFL_WATERJUMP;
+ ms->moveflags &= ~MFL_WALK;
+ if (initmove->or_moveflags & MFL_WALK) ms->moveflags |= MFL_WALK;
+ ms->moveflags &= ~MFL_GRAPPLEPULL;
+ if (initmove->or_moveflags & MFL_GRAPPLEPULL) ms->moveflags |= MFL_GRAPPLEPULL;
+} //end of the function BotInitMoveState
+//========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//========================================================================
+float AngleDiff(float ang1, float ang2)
+{
+ float diff;
+
+ diff = ang1 - ang2;
+ if (ang1 > ang2)
+ {
+ if (diff > 180.0) diff -= 360.0;
+ } //end if
+ else
+ {
+ if (diff < -180.0) diff += 360.0;
+ } //end else
+ return diff;
+} //end of the function AngleDiff
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotFuzzyPointReachabilityArea(vec3_t origin)
+{
+ int firstareanum, j, x, y, z;
+ int areas[10], numareas, areanum, bestareanum;
+ float dist, bestdist;
+ vec3_t points[10], v, end;
+
+ firstareanum = 0;
+ areanum = AAS_PointAreaNum(origin);
+ if (areanum)
+ {
+ firstareanum = areanum;
+ if (AAS_AreaReachability(areanum)) return areanum;
+ } //end if
+ VectorCopy(origin, end);
+ end[2] += 4;
+ numareas = AAS_TraceAreas(origin, end, areas, points, 10);
+ for (j = 0; j < numareas; j++)
+ {
+ if (AAS_AreaReachability(areas[j])) return areas[j];
+ } //end for
+ bestdist = 999999;
+ bestareanum = 0;
+ for (z = 1; z >= -1; z -= 1)
+ {
+ for (x = 1; x >= -1; x -= 1)
+ {
+ for (y = 1; y >= -1; y -= 1)
+ {
+ VectorCopy(origin, end);
+ end[0] += x * 8;
+ end[1] += y * 8;
+ end[2] += z * 12;
+ numareas = AAS_TraceAreas(origin, end, areas, points, 10);
+ for (j = 0; j < numareas; j++)
+ {
+ if (AAS_AreaReachability(areas[j]))
+ {
+ VectorSubtract(points[j], origin, v);
+ dist = VectorLength(v);
+ if (dist < bestdist)
+ {
+ bestareanum = areas[j];
+ bestdist = dist;
+ } //end if
+ } //end if
+ if (!firstareanum) firstareanum = areas[j];
+ } //end for
+ } //end for
+ } //end for
+ if (bestareanum) return bestareanum;
+ } //end for
+ return firstareanum;
+} //end of the function BotFuzzyPointReachabilityArea
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotReachabilityArea(vec3_t origin, int client)
+{
+ int modelnum, modeltype, reachnum, areanum;
+ aas_reachability_t reach;
+ vec3_t org, end, mins, maxs, up = {0, 0, 1};
+ bsp_trace_t bsptrace;
+ aas_trace_t trace;
+
+ //check if the bot is standing on something
+ AAS_PresenceTypeBoundingBox(PRESENCE_CROUCH, mins, maxs);
+ VectorMA(origin, -3, up, end);
+ bsptrace = AAS_Trace(origin, mins, maxs, end, client, CONTENTS_SOLID|CONTENTS_PLAYERCLIP);
+ if (!bsptrace.startsolid && bsptrace.fraction < 1 && bsptrace.ent != ENTITYNUM_NONE)
+ {
+ //if standing on the world the bot should be in a valid area
+ if (bsptrace.ent == ENTITYNUM_WORLD)
+ {
+ return BotFuzzyPointReachabilityArea(origin);
+ } //end if
+
+ modelnum = AAS_EntityModelindex(bsptrace.ent);
+ modeltype = modeltypes[modelnum];
+
+ //if standing on a func_plat or func_bobbing then the bot is assumed to be
+ //in the area the reachability points to
+ if (modeltype == MODELTYPE_FUNC_PLAT || modeltype == MODELTYPE_FUNC_BOB)
+ {
+ reachnum = AAS_NextModelReachability(0, modelnum);
+ if (reachnum)
+ {
+ AAS_ReachabilityFromNum(reachnum, &reach);
+ return reach.areanum;
+ } //end if
+ } //end else if
+
+ //if the bot is swimming the bot should be in a valid area
+ if (AAS_Swimming(origin))
+ {
+ return BotFuzzyPointReachabilityArea(origin);
+ } //end if
+ //
+ areanum = BotFuzzyPointReachabilityArea(origin);
+ //if the bot is in an area with reachabilities
+ if (areanum && AAS_AreaReachability(areanum)) return areanum;
+ //trace down till the ground is hit because the bot is standing on some other entity
+ VectorCopy(origin, org);
+ VectorCopy(org, end);
+ end[2] -= 800;
+ trace = AAS_TraceClientBBox(org, end, PRESENCE_CROUCH, -1);
+ if (!trace.startsolid)
+ {
+ VectorCopy(trace.endpos, org);
+ } //end if
+ //
+ return BotFuzzyPointReachabilityArea(org);
+ } //end if
+ //
+ return BotFuzzyPointReachabilityArea(origin);
+} //end of the function BotReachabilityArea
+//===========================================================================
+// returns the reachability area the bot is in
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+/*
+int BotReachabilityArea(vec3_t origin, int testground)
+{
+ int firstareanum, i, j, x, y, z;
+ int areas[10], numareas, areanum, bestareanum;
+ float dist, bestdist;
+ vec3_t org, end, points[10], v;
+ aas_trace_t trace;
+
+ firstareanum = 0;
+ for (i = 0; i < 2; i++)
+ {
+ VectorCopy(origin, org);
+ //if test at the ground (used when bot is standing on an entity)
+ if (i > 0)
+ {
+ VectorCopy(origin, end);
+ end[2] -= 800;
+ trace = AAS_TraceClientBBox(origin, end, PRESENCE_CROUCH, -1);
+ if (!trace.startsolid)
+ {
+ VectorCopy(trace.endpos, org);
+ } //end if
+ } //end if
+
+ firstareanum = 0;
+ areanum = AAS_PointAreaNum(org);
+ if (areanum)
+ {
+ firstareanum = areanum;
+ if (AAS_AreaReachability(areanum)) return areanum;
+ } //end if
+ bestdist = 999999;
+ bestareanum = 0;
+ for (z = 1; z >= -1; z -= 1)
+ {
+ for (x = 1; x >= -1; x -= 1)
+ {
+ for (y = 1; y >= -1; y -= 1)
+ {
+ VectorCopy(org, end);
+ end[0] += x * 8;
+ end[1] += y * 8;
+ end[2] += z * 12;
+ numareas = AAS_TraceAreas(org, end, areas, points, 10);
+ for (j = 0; j < numareas; j++)
+ {
+ if (AAS_AreaReachability(areas[j]))
+ {
+ VectorSubtract(points[j], org, v);
+ dist = VectorLength(v);
+ if (dist < bestdist)
+ {
+ bestareanum = areas[j];
+ bestdist = dist;
+ } //end if
+ } //end if
+ } //end for
+ } //end for
+ } //end for
+ if (bestareanum) return bestareanum;
+ } //end for
+ if (!testground) break;
+ } //end for
+//#ifdef DEBUG
+ //botimport.Print(PRT_MESSAGE, "no reachability area\n");
+//#endif //DEBUG
+ return firstareanum;
+} //end of the function BotReachabilityArea*/
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotOnMover(vec3_t origin, int entnum, aas_reachability_t *reach)
+{
+ int i, modelnum;
+ vec3_t mins, maxs, modelorigin, org, end;
+ vec3_t angles = {0, 0, 0};
+ vec3_t boxmins = {-16, -16, -8}, boxmaxs = {16, 16, 8};
+ bsp_trace_t trace;
+
+ modelnum = reach->facenum & 0x0000FFFF;
+ //get some bsp model info
+ AAS_BSPModelMinsMaxsOrigin(modelnum, angles, mins, maxs, NULL);
+ //
+ if (!AAS_OriginOfMoverWithModelNum(modelnum, modelorigin))
+ {
+ botimport.Print(PRT_MESSAGE, "no entity with model %d\n", modelnum);
+ return qfalse;
+ } //end if
+ //
+ for (i = 0; i < 2; i++)
+ {
+ if (origin[i] > modelorigin[i] + maxs[i] + 16) return qfalse;
+ if (origin[i] < modelorigin[i] + mins[i] - 16) return qfalse;
+ } //end for
+ //
+ VectorCopy(origin, org);
+ org[2] += 24;
+ VectorCopy(origin, end);
+ end[2] -= 48;
+ //
+ trace = AAS_Trace(org, boxmins, boxmaxs, end, entnum, CONTENTS_SOLID|CONTENTS_PLAYERCLIP);
+ if (!trace.startsolid && !trace.allsolid)
+ {
+ //NOTE: the reachability face number is the model number of the elevator
+ if (trace.ent != ENTITYNUM_NONE && AAS_EntityModelNum(trace.ent) == modelnum)
+ {
+ return qtrue;
+ } //end if
+ } //end if
+ return qfalse;
+} //end of the function BotOnMover
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int MoverDown(aas_reachability_t *reach)
+{
+ int modelnum;
+ vec3_t mins, maxs, origin;
+ vec3_t angles = {0, 0, 0};
+
+ modelnum = reach->facenum & 0x0000FFFF;
+ //get some bsp model info
+ AAS_BSPModelMinsMaxsOrigin(modelnum, angles, mins, maxs, origin);
+ //
+ if (!AAS_OriginOfMoverWithModelNum(modelnum, origin))
+ {
+ botimport.Print(PRT_MESSAGE, "no entity with model %d\n", modelnum);
+ return qfalse;
+ } //end if
+ //if the top of the plat is below the reachability start point
+ if (origin[2] + maxs[2] < reach->start[2]) return qtrue;
+ return qfalse;
+} //end of the function MoverDown
+//========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//========================================================================
+void BotSetBrushModelTypes(void)
+{
+ int ent, modelnum;
+ char classname[MAX_EPAIRKEY], model[MAX_EPAIRKEY];
+
+ Com_Memset(modeltypes, 0, MAX_MODELS * sizeof(int));
+ //
+ for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent))
+ {
+ if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) continue;
+ if (!AAS_ValueForBSPEpairKey(ent, "model", model, MAX_EPAIRKEY)) continue;
+ if (model[0]) modelnum = atoi(model+1);
+ else modelnum = 0;
+
+ if (modelnum < 0 || modelnum > MAX_MODELS)
+ {
+ botimport.Print(PRT_MESSAGE, "entity %s model number out of range\n", classname);
+ continue;
+ } //end if
+
+ if (!Q_stricmp(classname, "func_bobbing"))
+ modeltypes[modelnum] = MODELTYPE_FUNC_BOB;
+ else if (!Q_stricmp(classname, "func_plat"))
+ modeltypes[modelnum] = MODELTYPE_FUNC_PLAT;
+ else if (!Q_stricmp(classname, "func_door"))
+ modeltypes[modelnum] = MODELTYPE_FUNC_DOOR;
+ else if (!Q_stricmp(classname, "func_static"))
+ modeltypes[modelnum] = MODELTYPE_FUNC_STATIC;
+ } //end for
+} //end of the function BotSetBrushModelTypes
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotOnTopOfEntity(bot_movestate_t *ms)
+{
+ vec3_t mins, maxs, end, up = {0, 0, 1};
+ bsp_trace_t trace;
+
+ AAS_PresenceTypeBoundingBox(ms->presencetype, mins, maxs);
+ VectorMA(ms->origin, -3, up, end);
+ trace = AAS_Trace(ms->origin, mins, maxs, end, ms->entitynum, CONTENTS_SOLID|CONTENTS_PLAYERCLIP);
+ if (!trace.startsolid && (trace.ent != ENTITYNUM_WORLD && trace.ent != ENTITYNUM_NONE) )
+ {
+ return trace.ent;
+ } //end if
+ return -1;
+} //end of the function BotOnTopOfEntity
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotValidTravel(vec3_t origin, aas_reachability_t *reach, int travelflags)
+{
+ //if the reachability uses an unwanted travel type
+ if (AAS_TravelFlagForType(reach->traveltype) & ~travelflags) return qfalse;
+ //don't go into areas with bad travel types
+ if (AAS_AreaContentsTravelFlags(reach->areanum) & ~travelflags) return qfalse;
+ return qtrue;
+} //end of the function BotValidTravel
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotAddToAvoidReach(bot_movestate_t *ms, int number, float avoidtime)
+{
+ int i;
+
+ for (i = 0; i < MAX_AVOIDREACH; i++)
+ {
+ if (ms->avoidreach[i] == number)
+ {
+ if (ms->avoidreachtimes[i] > AAS_Time()) ms->avoidreachtries[i]++;
+ else ms->avoidreachtries[i] = 1;
+ ms->avoidreachtimes[i] = AAS_Time() + avoidtime;
+ return;
+ } //end if
+ } //end for
+ //add the reachability to the reachabilities to avoid for a while
+ for (i = 0; i < MAX_AVOIDREACH; i++)
+ {
+ if (ms->avoidreachtimes[i] < AAS_Time())
+ {
+ ms->avoidreach[i] = number;
+ ms->avoidreachtimes[i] = AAS_Time() + avoidtime;
+ ms->avoidreachtries[i] = 1;
+ return;
+ } //end if
+ } //end for
+} //end of the function BotAddToAvoidReach
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float DistanceFromLineSquared(vec3_t p, vec3_t lp1, vec3_t lp2)
+{
+ vec3_t proj, dir;
+ int j;
+
+ AAS_ProjectPointOntoVector(p, lp1, lp2, proj);
+ for (j = 0; j < 3; j++)
+ if ((proj[j] > lp1[j] && proj[j] > lp2[j]) ||
+ (proj[j] < lp1[j] && proj[j] < lp2[j]))
+ break;
+ if (j < 3) {
+ if (fabs(proj[j] - lp1[j]) < fabs(proj[j] - lp2[j]))
+ VectorSubtract(p, lp1, dir);
+ else
+ VectorSubtract(p, lp2, dir);
+ return VectorLengthSquared(dir);
+ }
+ VectorSubtract(p, proj, dir);
+ return VectorLengthSquared(dir);
+} //end of the function DistanceFromLineSquared
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float VectorDistanceSquared(vec3_t p1, vec3_t p2)
+{
+ vec3_t dir;
+ VectorSubtract(p2, p1, dir);
+ return VectorLengthSquared(dir);
+} //end of the function VectorDistanceSquared
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotAvoidSpots(vec3_t origin, aas_reachability_t *reach, bot_avoidspot_t *avoidspots, int numavoidspots)
+{
+ int checkbetween, i, type;
+ float squareddist, squaredradius;
+
+ switch(reach->traveltype & TRAVELTYPE_MASK)
+ {
+ case TRAVEL_WALK: checkbetween = qtrue; break;
+ case TRAVEL_CROUCH: checkbetween = qtrue; break;
+ case TRAVEL_BARRIERJUMP: checkbetween = qtrue; break;
+ case TRAVEL_LADDER: checkbetween = qtrue; break;
+ case TRAVEL_WALKOFFLEDGE: checkbetween = qfalse; break;
+ case TRAVEL_JUMP: checkbetween = qfalse; break;
+ case TRAVEL_SWIM: checkbetween = qtrue; break;
+ case TRAVEL_WATERJUMP: checkbetween = qtrue; break;
+ case TRAVEL_TELEPORT: checkbetween = qfalse; break;
+ case TRAVEL_ELEVATOR: checkbetween = qfalse; break;
+ case TRAVEL_GRAPPLEHOOK: checkbetween = qfalse; break;
+ case TRAVEL_ROCKETJUMP: checkbetween = qfalse; break;
+ case TRAVEL_BFGJUMP: checkbetween = qfalse; break;
+ case TRAVEL_JUMPPAD: checkbetween = qfalse; break;
+ case TRAVEL_FUNCBOB: checkbetween = qfalse; break;
+ default: checkbetween = qtrue; break;
+ } //end switch
+
+ type = AVOID_CLEAR;
+ for (i = 0; i < numavoidspots; i++)
+ {
+ squaredradius = Square(avoidspots[i].radius);
+ squareddist = DistanceFromLineSquared(avoidspots[i].origin, origin, reach->start);
+ // if moving towards the avoid spot
+ if (squareddist < squaredradius &&
+ VectorDistanceSquared(avoidspots[i].origin, origin) > squareddist)
+ {
+ type = avoidspots[i].type;
+ } //end if
+ else if (checkbetween) {
+ squareddist = DistanceFromLineSquared(avoidspots[i].origin, reach->start, reach->end);
+ // if moving towards the avoid spot
+ if (squareddist < squaredradius &&
+ VectorDistanceSquared(avoidspots[i].origin, reach->start) > squareddist)
+ {
+ type = avoidspots[i].type;
+ } //end if
+ } //end if
+ else
+ {
+ VectorDistanceSquared(avoidspots[i].origin, reach->end);
+ // if the reachability leads closer to the avoid spot
+ if (squareddist < squaredradius &&
+ VectorDistanceSquared(avoidspots[i].origin, reach->start) > squareddist)
+ {
+ type = avoidspots[i].type;
+ } //end if
+ } //end else
+ if (type == AVOID_ALWAYS)
+ return type;
+ } //end for
+ return type;
+} //end of the function BotAvoidSpots
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotAddAvoidSpot(int movestate, vec3_t origin, float radius, int type)
+{
+ bot_movestate_t *ms;
+
+ ms = BotMoveStateFromHandle(movestate);
+ if (!ms) return;
+ if (type == AVOID_CLEAR)
+ {
+ ms->numavoidspots = 0;
+ return;
+ } //end if
+
+ if (ms->numavoidspots >= MAX_AVOIDSPOTS)
+ return;
+ VectorCopy(origin, ms->avoidspots[ms->numavoidspots].origin);
+ ms->avoidspots[ms->numavoidspots].radius = radius;
+ ms->avoidspots[ms->numavoidspots].type = type;
+ ms->numavoidspots++;
+} //end of the function BotAddAvoidSpot
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotGetReachabilityToGoal(vec3_t origin, int areanum,
+ int lastgoalareanum, int lastareanum,
+ int *avoidreach, float *avoidreachtimes, int *avoidreachtries,
+ bot_goal_t *goal, int travelflags, int movetravelflags,
+ struct bot_avoidspot_s *avoidspots, int numavoidspots, int *flags)
+{
+ int i, t, besttime, bestreachnum, reachnum;
+ aas_reachability_t reach;
+
+ //if not in a valid area
+ if (!areanum) return 0;
+ //
+ if (AAS_AreaDoNotEnter(areanum) || AAS_AreaDoNotEnter(goal->areanum))
+ {
+ travelflags |= TFL_DONOTENTER;
+ movetravelflags |= TFL_DONOTENTER;
+ } //end if
+ //use the routing to find the next area to go to
+ besttime = 0;
+ bestreachnum = 0;
+ //
+ for (reachnum = AAS_NextAreaReachability(areanum, 0); reachnum;
+ reachnum = AAS_NextAreaReachability(areanum, reachnum))
+ {
+#ifdef AVOIDREACH
+ //check if it isn't an reachability to avoid
+ for (i = 0; i < MAX_AVOIDREACH; i++)
+ {
+ if (avoidreach[i] == reachnum && avoidreachtimes[i] >= AAS_Time()) break;
+ } //end for
+ if (i != MAX_AVOIDREACH && avoidreachtries[i] > AVOIDREACH_TRIES)
+ {
+#ifdef DEBUG
+ if (bot_developer)
+ {
+ botimport.Print(PRT_MESSAGE, "avoiding reachability %d\n", avoidreach[i]);
+ } //end if
+#endif //DEBUG
+ continue;
+ } //end if
+#endif //AVOIDREACH
+ //get the reachability from the number
+ AAS_ReachabilityFromNum(reachnum, &reach);
+ //NOTE: do not go back to the previous area if the goal didn't change
+ //NOTE: is this actually avoidance of local routing minima between two areas???
+ if (lastgoalareanum == goal->areanum && reach.areanum == lastareanum) continue;
+ //if (AAS_AreaContentsTravelFlags(reach.areanum) & ~travelflags) continue;
+ //if the travel isn't valid
+ if (!BotValidTravel(origin, &reach, movetravelflags)) continue;
+ //get the travel time
+ t = AAS_AreaTravelTimeToGoalArea(reach.areanum, reach.end, goal->areanum, travelflags);
+ //if the goal area isn't reachable from the reachable area
+ if (!t) continue;
+ //if the bot should not use this reachability to avoid bad spots
+ if (BotAvoidSpots(origin, &reach, avoidspots, numavoidspots)) {
+ if (flags) {
+ *flags |= MOVERESULT_BLOCKEDBYAVOIDSPOT;
+ }
+ continue;
+ }
+ //add the travel time towards the area
+ t += reach.traveltime;// + AAS_AreaTravelTime(areanum, origin, reach.start);
+ //if the travel time is better than the ones already found
+ if (!besttime || t < besttime)
+ {
+ besttime = t;
+ bestreachnum = reachnum;
+ } //end if
+ } //end for
+ //
+ return bestreachnum;
+} //end of the function BotGetReachabilityToGoal
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotAddToTarget(vec3_t start, vec3_t end, float maxdist, float *dist, vec3_t target)
+{
+ vec3_t dir;
+ float curdist;
+
+ VectorSubtract(end, start, dir);
+ curdist = VectorNormalize(dir);
+ if (*dist + curdist < maxdist)
+ {
+ VectorCopy(end, target);
+ *dist += curdist;
+ return qfalse;
+ } //end if
+ else
+ {
+ VectorMA(start, maxdist - *dist, dir, target);
+ *dist = maxdist;
+ return qtrue;
+ } //end else
+} //end of the function BotAddToTarget
+
+int BotMovementViewTarget(int movestate, bot_goal_t *goal, int travelflags, float lookahead, vec3_t target)
+{
+ aas_reachability_t reach;
+ int reachnum, lastareanum;
+ bot_movestate_t *ms;
+ vec3_t end;
+ float dist;
+
+ ms = BotMoveStateFromHandle(movestate);
+ if (!ms) return qfalse;
+ reachnum = 0;
+ //if the bot has no goal or no last reachability
+ if (!ms->lastreachnum || !goal) return qfalse;
+
+ reachnum = ms->lastreachnum;
+ VectorCopy(ms->origin, end);
+ lastareanum = ms->lastareanum;
+ dist = 0;
+ while(reachnum && dist < lookahead)
+ {
+ AAS_ReachabilityFromNum(reachnum, &reach);
+ if (BotAddToTarget(end, reach.start, lookahead, &dist, target)) return qtrue;
+ //never look beyond teleporters
+ if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_TELEPORT) return qtrue;
+ //never look beyond the weapon jump point
+ if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_ROCKETJUMP) return qtrue;
+ if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_BFGJUMP) return qtrue;
+ //don't add jump pad distances
+ if ((reach.traveltype & TRAVELTYPE_MASK) != TRAVEL_JUMPPAD &&
+ (reach.traveltype & TRAVELTYPE_MASK) != TRAVEL_ELEVATOR &&
+ (reach.traveltype & TRAVELTYPE_MASK) != TRAVEL_FUNCBOB)
+ {
+ if (BotAddToTarget(reach.start, reach.end, lookahead, &dist, target)) return qtrue;
+ } //end if
+ reachnum = BotGetReachabilityToGoal(reach.end, reach.areanum,
+ ms->lastgoalareanum, lastareanum,
+ ms->avoidreach, ms->avoidreachtimes, ms->avoidreachtries,
+ goal, travelflags, travelflags, NULL, 0, NULL);
+ VectorCopy(reach.end, end);
+ lastareanum = reach.areanum;
+ if (lastareanum == goal->areanum)
+ {
+ BotAddToTarget(reach.end, goal->origin, lookahead, &dist, target);
+ return qtrue;
+ } //end if
+ } //end while
+ //
+ return qfalse;
+} //end of the function BotMovementViewTarget
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotVisible(int ent, vec3_t eye, vec3_t target)
+{
+ bsp_trace_t trace;
+
+ trace = AAS_Trace(eye, NULL, NULL, target, ent, CONTENTS_SOLID|CONTENTS_PLAYERCLIP);
+ if (trace.fraction >= 1) return qtrue;
+ return qfalse;
+} //end of the function BotVisible
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotPredictVisiblePosition(vec3_t origin, int areanum, bot_goal_t *goal, int travelflags, vec3_t target)
+{
+ aas_reachability_t reach;
+ int reachnum, lastgoalareanum, lastareanum, i;
+ int avoidreach[MAX_AVOIDREACH];
+ float avoidreachtimes[MAX_AVOIDREACH];
+ int avoidreachtries[MAX_AVOIDREACH];
+ vec3_t end;
+
+ //if the bot has no goal or no last reachability
+ if (!goal) return qfalse;
+ //if the areanum is not valid
+ if (!areanum) return qfalse;
+ //if the goal areanum is not valid
+ if (!goal->areanum) return qfalse;
+
+ Com_Memset(avoidreach, 0, MAX_AVOIDREACH * sizeof(int));
+ lastgoalareanum = goal->areanum;
+ lastareanum = areanum;
+ VectorCopy(origin, end);
+ //only do 20 hops
+ for (i = 0; i < 20 && (areanum != goal->areanum); i++)
+ {
+ //
+ reachnum = BotGetReachabilityToGoal(end, areanum,
+ lastgoalareanum, lastareanum,
+ avoidreach, avoidreachtimes, avoidreachtries,
+ goal, travelflags, travelflags, NULL, 0, NULL);
+ if (!reachnum) return qfalse;
+ AAS_ReachabilityFromNum(reachnum, &reach);
+ //
+ if (BotVisible(goal->entitynum, goal->origin, reach.start))
+ {
+ VectorCopy(reach.start, target);
+ return qtrue;
+ } //end if
+ //
+ if (BotVisible(goal->entitynum, goal->origin, reach.end))
+ {
+ VectorCopy(reach.end, target);
+ return qtrue;
+ } //end if
+ //
+ if (reach.areanum == goal->areanum)
+ {
+ VectorCopy(reach.end, target);
+ return qtrue;
+ } //end if
+ //
+ lastareanum = areanum;
+ areanum = reach.areanum;
+ VectorCopy(reach.end, end);
+ //
+ } //end while
+ //
+ return qfalse;
+} //end of the function BotPredictVisiblePosition
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void MoverBottomCenter(aas_reachability_t *reach, vec3_t bottomcenter)
+{
+ int modelnum;
+ vec3_t mins, maxs, origin, mids;
+ vec3_t angles = {0, 0, 0};
+
+ modelnum = reach->facenum & 0x0000FFFF;
+ //get some bsp model info
+ AAS_BSPModelMinsMaxsOrigin(modelnum, angles, mins, maxs, origin);
+ //
+ if (!AAS_OriginOfMoverWithModelNum(modelnum, origin))
+ {
+ botimport.Print(PRT_MESSAGE, "no entity with model %d\n", modelnum);
+ } //end if
+ //get a point just above the plat in the bottom position
+ VectorAdd(mins, maxs, mids);
+ VectorMA(origin, 0.5, mids, bottomcenter);
+ bottomcenter[2] = reach->start[2];
+} //end of the function MoverBottomCenter
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float BotGapDistance(vec3_t origin, vec3_t hordir, int entnum)
+{
+ float dist, startz;
+ vec3_t start, end;
+ aas_trace_t trace;
+
+ //do gap checking
+ startz = origin[2];
+ //this enables walking down stairs more fluidly
+ {
+ VectorCopy(origin, start);
+ VectorCopy(origin, end);
+ end[2] -= 60;
+ trace = AAS_TraceClientBBox(start, end, PRESENCE_CROUCH, entnum);
+ if (trace.fraction >= 1) return 1;
+ startz = trace.endpos[2] + 1;
+ }
+ //
+ for (dist = 8; dist <= 100; dist += 8)
+ {
+ VectorMA(origin, dist, hordir, start);
+ start[2] = startz + 24;
+ VectorCopy(start, end);
+ end[2] -= 48 + sv_maxbarrier->value;
+ trace = AAS_TraceClientBBox(start, end, PRESENCE_CROUCH, entnum);
+ //if solid is found the bot can't walk any further and fall into a gap
+ if (!trace.startsolid)
+ {
+ //if it is a gap
+ if (trace.endpos[2] < startz - sv_maxstep->value - 8)
+ {
+ VectorCopy(trace.endpos, end);
+ end[2] -= 20;
+ if (AAS_PointContents(end) & CONTENTS_WATER) break;
+ //if a gap is found slow down
+ //botimport.Print(PRT_MESSAGE, "gap at %f\n", dist);
+ return dist;
+ } //end if
+ startz = trace.endpos[2];
+ } //end if
+ } //end for
+ return 0;
+} //end of the function BotGapDistance
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotCheckBarrierJump(bot_movestate_t *ms, vec3_t dir, float speed)
+{
+ vec3_t start, hordir, end;
+ aas_trace_t trace;
+
+ VectorCopy(ms->origin, end);
+ end[2] += sv_maxbarrier->value;
+ //trace right up
+ trace = AAS_TraceClientBBox(ms->origin, end, PRESENCE_NORMAL, ms->entitynum);
+ //this shouldn't happen... but we check anyway
+ if (trace.startsolid) return qfalse;
+ //if very low ceiling it isn't possible to jump up to a barrier
+ if (trace.endpos[2] - ms->origin[2] < sv_maxstep->value) return qfalse;
+ //
+ hordir[0] = dir[0];
+ hordir[1] = dir[1];
+ hordir[2] = 0;
+ VectorNormalize(hordir);
+ VectorMA(ms->origin, ms->thinktime * speed * 0.5, hordir, end);
+ VectorCopy(trace.endpos, start);
+ end[2] = trace.endpos[2];
+ //trace from previous trace end pos horizontally in the move direction
+ trace = AAS_TraceClientBBox(start, end, PRESENCE_NORMAL, ms->entitynum);
+ //again this shouldn't happen
+ if (trace.startsolid) return qfalse;
+ //
+ VectorCopy(trace.endpos, start);
+ VectorCopy(trace.endpos, end);
+ end[2] = ms->origin[2];
+ //trace down from the previous trace end pos
+ trace = AAS_TraceClientBBox(start, end, PRESENCE_NORMAL, ms->entitynum);
+ //if solid
+ if (trace.startsolid) return qfalse;
+ //if no obstacle at all
+ if (trace.fraction >= 1.0) return qfalse;
+ //if less than the maximum step height
+ if (trace.endpos[2] - ms->origin[2] < sv_maxstep->value) return qfalse;
+ //
+ EA_Jump(ms->client);
+ EA_Move(ms->client, hordir, speed);
+ ms->moveflags |= MFL_BARRIERJUMP;
+ //there is a barrier
+ return qtrue;
+} //end of the function BotCheckBarrierJump
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotSwimInDirection(bot_movestate_t *ms, vec3_t dir, float speed, int type)
+{
+ vec3_t normdir;
+
+ VectorCopy(dir, normdir);
+ VectorNormalize(normdir);
+ EA_Move(ms->client, normdir, speed);
+ return qtrue;
+} //end of the function BotSwimInDirection
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotWalkInDirection(bot_movestate_t *ms, vec3_t dir, float speed, int type)
+{
+ vec3_t hordir, cmdmove, velocity, tmpdir, origin;
+ int presencetype, maxframes, cmdframes, stopevent;
+ aas_clientmove_t move;
+ float dist;
+
+ if (AAS_OnGround(ms->origin, ms->presencetype, ms->entitynum)) ms->moveflags |= MFL_ONGROUND;
+ //if the bot is on the ground
+ if (ms->moveflags & MFL_ONGROUND)
+ {
+ //if there is a barrier the bot can jump on
+ if (BotCheckBarrierJump(ms, dir, speed)) return qtrue;
+ //remove barrier jump flag
+ ms->moveflags &= ~MFL_BARRIERJUMP;
+ //get the presence type for the movement
+ if ((type & MOVE_CROUCH) && !(type & MOVE_JUMP)) presencetype = PRESENCE_CROUCH;
+ else presencetype = PRESENCE_NORMAL;
+ //horizontal direction
+ hordir[0] = dir[0];
+ hordir[1] = dir[1];
+ hordir[2] = 0;
+ VectorNormalize(hordir);
+ //if the bot is not supposed to jump
+ if (!(type & MOVE_JUMP))
+ {
+ //if there is a gap, try to jump over it
+ if (BotGapDistance(ms->origin, hordir, ms->entitynum) > 0) type |= MOVE_JUMP;
+ } //end if
+ //get command movement
+ VectorScale(hordir, speed, cmdmove);
+ VectorCopy(ms->velocity, velocity);
+ //
+ if (type & MOVE_JUMP)
+ {
+ //botimport.Print(PRT_MESSAGE, "trying jump\n");
+ cmdmove[2] = 400;
+ maxframes = PREDICTIONTIME_JUMP / 0.1;
+ cmdframes = 1;
+ stopevent = SE_HITGROUND|SE_HITGROUNDDAMAGE|
+ SE_ENTERWATER|SE_ENTERSLIME|SE_ENTERLAVA;
+ } //end if
+ else
+ {
+ maxframes = 2;
+ cmdframes = 2;
+ stopevent = SE_HITGROUNDDAMAGE|
+ SE_ENTERWATER|SE_ENTERSLIME|SE_ENTERLAVA;
+ } //end else
+ //AAS_ClearShownDebugLines();
+ //
+ VectorCopy(ms->origin, origin);
+ origin[2] += 0.5;
+ AAS_PredictClientMovement(&move, ms->entitynum, origin, presencetype, qtrue,
+ velocity, cmdmove, cmdframes, maxframes, 0.1f,
+ stopevent, 0, qfalse);//qtrue);
+ //if prediction time wasn't enough to fully predict the movement
+ if (move.frames >= maxframes && (type & MOVE_JUMP))
+ {
+ //botimport.Print(PRT_MESSAGE, "client %d: max prediction frames\n", ms->client);
+ return qfalse;
+ } //end if
+ //don't enter slime or lava and don't fall from too high
+ if (move.stopevent & (SE_ENTERSLIME|SE_ENTERLAVA|SE_HITGROUNDDAMAGE))
+ {
+ //botimport.Print(PRT_MESSAGE, "client %d: would be hurt ", ms->client);
+ //if (move.stopevent & SE_ENTERSLIME) botimport.Print(PRT_MESSAGE, "slime\n");
+ //if (move.stopevent & SE_ENTERLAVA) botimport.Print(PRT_MESSAGE, "lava\n");
+ //if (move.stopevent & SE_HITGROUNDDAMAGE) botimport.Print(PRT_MESSAGE, "hitground\n");
+ return qfalse;
+ } //end if
+ //if ground was hit
+ if (move.stopevent & SE_HITGROUND)
+ {
+ //check for nearby gap
+ VectorNormalize2(move.velocity, tmpdir);
+ dist = BotGapDistance(move.endpos, tmpdir, ms->entitynum);
+ if (dist > 0) return qfalse;
+ //
+ dist = BotGapDistance(move.endpos, hordir, ms->entitynum);
+ if (dist > 0) return qfalse;
+ } //end if
+ //get horizontal movement
+ tmpdir[0] = move.endpos[0] - ms->origin[0];
+ tmpdir[1] = move.endpos[1] - ms->origin[1];
+ tmpdir[2] = 0;
+ //
+ //AAS_DrawCross(move.endpos, 4, LINECOLOR_BLUE);
+ //the bot is blocked by something
+ if (VectorLength(tmpdir) < speed * ms->thinktime * 0.5) return qfalse;
+ //perform the movement
+ if (type & MOVE_JUMP) EA_Jump(ms->client);
+ if (type & MOVE_CROUCH) EA_Crouch(ms->client);
+ EA_Move(ms->client, hordir, speed);
+ //movement was succesfull
+ return qtrue;
+ } //end if
+ else
+ {
+ if (ms->moveflags & MFL_BARRIERJUMP)
+ {
+ //if near the top or going down
+ if (ms->velocity[2] < 50)
+ {
+ EA_Move(ms->client, dir, speed);
+ } //end if
+ } //end if
+ //FIXME: do air control to avoid hazards
+ return qtrue;
+ } //end else
+} //end of the function BotWalkInDirection
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotMoveInDirection(int movestate, vec3_t dir, float speed, int type)
+{
+ bot_movestate_t *ms;
+
+ ms = BotMoveStateFromHandle(movestate);
+ if (!ms) return qfalse;
+ //if swimming
+ if (AAS_Swimming(ms->origin))
+ {
+ return BotSwimInDirection(ms, dir, speed, type);
+ } //end if
+ else
+ {
+ return BotWalkInDirection(ms, dir, speed, type);
+ } //end else
+} //end of the function BotMoveInDirection
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int Intersection(vec2_t p1, vec2_t p2, vec2_t p3, vec2_t p4, vec2_t out)
+{
+ float x1, dx1, dy1, x2, dx2, dy2, d;
+
+ dx1 = p2[0] - p1[0];
+ dy1 = p2[1] - p1[1];
+ dx2 = p4[0] - p3[0];
+ dy2 = p4[1] - p3[1];
+
+ d = dy1 * dx2 - dx1 * dy2;
+ if (d != 0)
+ {
+ x1 = p1[1] * dx1 - p1[0] * dy1;
+ x2 = p3[1] * dx2 - p3[0] * dy2;
+ out[0] = (int) ((dx1 * x2 - dx2 * x1) / d);
+ out[1] = (int) ((dy1 * x2 - dy2 * x1) / d);
+ return qtrue;
+ } //end if
+ else
+ {
+ return qfalse;
+ } //end else
+} //end of the function Intersection
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotCheckBlocked(bot_movestate_t *ms, vec3_t dir, int checkbottom, bot_moveresult_t *result)
+{
+ vec3_t mins, maxs, end, up = {0, 0, 1};
+ bsp_trace_t trace;
+
+ //test for entities obstructing the bot's path
+ AAS_PresenceTypeBoundingBox(ms->presencetype, mins, maxs);
+ //
+ if (fabs(DotProduct(dir, up)) < 0.7)
+ {
+ mins[2] += sv_maxstep->value; //if the bot can step on
+ maxs[2] -= 10; //a little lower to avoid low ceiling
+ } //end if
+ VectorMA(ms->origin, 3, dir, end);
+ trace = AAS_Trace(ms->origin, mins, maxs, end, ms->entitynum, CONTENTS_SOLID|CONTENTS_PLAYERCLIP|CONTENTS_BODY);
+ //if not started in solid and not hitting the world entity
+ if (!trace.startsolid && (trace.ent != ENTITYNUM_WORLD && trace.ent != ENTITYNUM_NONE) )
+ {
+ result->blocked = qtrue;
+ result->blockentity = trace.ent;
+#ifdef DEBUG
+ //botimport.Print(PRT_MESSAGE, "%d: BotCheckBlocked: I'm blocked\n", ms->client);
+#endif //DEBUG
+ } //end if
+ //if not in an area with reachability
+ else if (checkbottom && !AAS_AreaReachability(ms->areanum))
+ {
+ //check if the bot is standing on something
+ AAS_PresenceTypeBoundingBox(ms->presencetype, mins, maxs);
+ VectorMA(ms->origin, -3, up, end);
+ trace = AAS_Trace(ms->origin, mins, maxs, end, ms->entitynum, CONTENTS_SOLID|CONTENTS_PLAYERCLIP);
+ if (!trace.startsolid && (trace.ent != ENTITYNUM_WORLD && trace.ent != ENTITYNUM_NONE) )
+ {
+ result->blocked = qtrue;
+ result->blockentity = trace.ent;
+ result->flags |= MOVERESULT_ONTOPOFOBSTACLE;
+#ifdef DEBUG
+ //botimport.Print(PRT_MESSAGE, "%d: BotCheckBlocked: I'm blocked\n", ms->client);
+#endif //DEBUG
+ } //end if
+ } //end else
+} //end of the function BotCheckBlocked
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotClearMoveResult(bot_moveresult_t *moveresult)
+{
+ moveresult->failure = qfalse;
+ moveresult->type = 0;
+ moveresult->blocked = qfalse;
+ moveresult->blockentity = 0;
+ moveresult->traveltype = 0;
+ moveresult->flags = 0;
+} //end of the function BotClearMoveResult
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_moveresult_t BotTravel_Walk(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ float dist, speed;
+ vec3_t hordir;
+ bot_moveresult_t result;
+
+ BotClearMoveResult(&result);
+ //first walk straight to the reachability start
+ hordir[0] = reach->start[0] - ms->origin[0];
+ hordir[1] = reach->start[1] - ms->origin[1];
+ hordir[2] = 0;
+ dist = VectorNormalize(hordir);
+ //
+ BotCheckBlocked(ms, hordir, qtrue, &result);
+ //
+ if (dist < 10)
+ {
+ //walk straight to the reachability end
+ hordir[0] = reach->end[0] - ms->origin[0];
+ hordir[1] = reach->end[1] - ms->origin[1];
+ hordir[2] = 0;
+ dist = VectorNormalize(hordir);
+ } //end if
+ //if going towards a crouch area
+ if (!(AAS_AreaPresenceType(reach->areanum) & PRESENCE_NORMAL))
+ {
+ //if pretty close to the reachable area
+ if (dist < 20) EA_Crouch(ms->client);
+ } //end if
+ //
+ dist = BotGapDistance(ms->origin, hordir, ms->entitynum);
+ //
+ if (ms->moveflags & MFL_WALK)
+ {
+ if (dist > 0) speed = 200 - (180 - 1 * dist);
+ else speed = 200;
+ EA_Walk(ms->client);
+ } //end if
+ else
+ {
+ if (dist > 0) speed = 400 - (360 - 2 * dist);
+ else speed = 400;
+ } //end else
+ //elemantary action move in direction
+ EA_Move(ms->client, hordir, speed);
+ VectorCopy(hordir, result.movedir);
+ //
+ return result;
+} //end of the function BotTravel_Walk
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_moveresult_t BotFinishTravel_Walk(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ vec3_t hordir;
+ float dist, speed;
+ bot_moveresult_t result;
+
+ BotClearMoveResult(&result);
+ //if not on the ground and changed areas... don't walk back!!
+ //(doesn't seem to help)
+ /*
+ ms->areanum = BotFuzzyPointReachabilityArea(ms->origin);
+ if (ms->areanum == reach->areanum)
+ {
+#ifdef DEBUG
+ botimport.Print(PRT_MESSAGE, "BotFinishTravel_Walk: already in reach area\n");
+#endif //DEBUG
+ return result;
+ } //end if*/
+ //go straight to the reachability end
+ hordir[0] = reach->end[0] - ms->origin[0];
+ hordir[1] = reach->end[1] - ms->origin[1];
+ hordir[2] = 0;
+ dist = VectorNormalize(hordir);
+ //
+ if (dist > 100) dist = 100;
+ speed = 400 - (400 - 3 * dist);
+ //
+ EA_Move(ms->client, hordir, speed);
+ VectorCopy(hordir, result.movedir);
+ //
+ return result;
+} //end of the function BotFinishTravel_Walk
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_moveresult_t BotTravel_Crouch(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ float speed;
+ vec3_t hordir;
+ bot_moveresult_t result;
+
+ BotClearMoveResult(&result);
+ //
+ speed = 400;
+ //walk straight to reachability end
+ hordir[0] = reach->end[0] - ms->origin[0];
+ hordir[1] = reach->end[1] - ms->origin[1];
+ hordir[2] = 0;
+ VectorNormalize(hordir);
+ //
+ BotCheckBlocked(ms, hordir, qtrue, &result);
+ //elemantary actions
+ EA_Crouch(ms->client);
+ EA_Move(ms->client, hordir, speed);
+ //
+ VectorCopy(hordir, result.movedir);
+ //
+ return result;
+} //end of the function BotTravel_Crouch
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_moveresult_t BotTravel_BarrierJump(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ float dist, speed;
+ vec3_t hordir;
+ bot_moveresult_t result;
+
+ BotClearMoveResult(&result);
+ //walk straight to reachability start
+ hordir[0] = reach->start[0] - ms->origin[0];
+ hordir[1] = reach->start[1] - ms->origin[1];
+ hordir[2] = 0;
+ dist = VectorNormalize(hordir);
+ //
+ BotCheckBlocked(ms, hordir, qtrue, &result);
+ //if pretty close to the barrier
+ if (dist < 9)
+ {
+ EA_Jump(ms->client);
+ } //end if
+ else
+ {
+ if (dist > 60) dist = 60;
+ speed = 360 - (360 - 6 * dist);
+ EA_Move(ms->client, hordir, speed);
+ } //end else
+ VectorCopy(hordir, result.movedir);
+ //
+ return result;
+} //end of the function BotTravel_BarrierJump
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_moveresult_t BotFinishTravel_BarrierJump(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ float dist;
+ vec3_t hordir;
+ bot_moveresult_t result;
+
+ BotClearMoveResult(&result);
+ //if near the top or going down
+ if (ms->velocity[2] < 250)
+ {
+ hordir[0] = reach->end[0] - ms->origin[0];
+ hordir[1] = reach->end[1] - ms->origin[1];
+ hordir[2] = 0;
+ dist = VectorNormalize(hordir);
+ //
+ BotCheckBlocked(ms, hordir, qtrue, &result);
+ //
+ EA_Move(ms->client, hordir, 400);
+ VectorCopy(hordir, result.movedir);
+ } //end if
+ //
+ return result;
+} //end of the function BotFinishTravel_BarrierJump
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_moveresult_t BotTravel_Swim(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ vec3_t dir;
+ bot_moveresult_t result;
+
+ BotClearMoveResult(&result);
+ //swim straight to reachability end
+ VectorSubtract(reach->start, ms->origin, dir);
+ VectorNormalize(dir);
+ //
+ BotCheckBlocked(ms, dir, qtrue, &result);
+ //elemantary actions
+ EA_Move(ms->client, dir, 400);
+ //
+ VectorCopy(dir, result.movedir);
+ Vector2Angles(dir, result.ideal_viewangles);
+ result.flags |= MOVERESULT_SWIMVIEW;
+ //
+ return result;
+} //end of the function BotTravel_Swim
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_moveresult_t BotTravel_WaterJump(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ vec3_t dir, hordir;
+ float dist;
+ bot_moveresult_t result;
+
+ BotClearMoveResult(&result);
+ //swim straight to reachability end
+ VectorSubtract(reach->end, ms->origin, dir);
+ VectorCopy(dir, hordir);
+ hordir[2] = 0;
+ dir[2] += 15 + crandom() * 40;
+ //botimport.Print(PRT_MESSAGE, "BotTravel_WaterJump: dir[2] = %f\n", dir[2]);
+ VectorNormalize(dir);
+ dist = VectorNormalize(hordir);
+ //elemantary actions
+ //EA_Move(ms->client, dir, 400);
+ EA_MoveForward(ms->client);
+ //move up if close to the actual out of water jump spot
+ if (dist < 40) EA_MoveUp(ms->client);
+ //set the ideal view angles
+ Vector2Angles(dir, result.ideal_viewangles);
+ result.flags |= MOVERESULT_MOVEMENTVIEW;
+ //
+ VectorCopy(dir, result.movedir);
+ //
+ return result;
+} //end of the function BotTravel_WaterJump
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_moveresult_t BotFinishTravel_WaterJump(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ vec3_t dir, pnt;
+ float dist;
+ bot_moveresult_t result;
+
+ //botimport.Print(PRT_MESSAGE, "BotFinishTravel_WaterJump\n");
+ BotClearMoveResult(&result);
+ //if waterjumping there's nothing to do
+ if (ms->moveflags & MFL_WATERJUMP) return result;
+ //if not touching any water anymore don't do anything
+ //otherwise the bot sometimes keeps jumping?
+ VectorCopy(ms->origin, pnt);
+ pnt[2] -= 32; //extra for q2dm4 near red armor/mega health
+ if (!(AAS_PointContents(pnt) & (CONTENTS_LAVA|CONTENTS_SLIME|CONTENTS_WATER))) return result;
+ //swim straight to reachability end
+ VectorSubtract(reach->end, ms->origin, dir);
+ dir[0] += crandom() * 10;
+ dir[1] += crandom() * 10;
+ dir[2] += 70 + crandom() * 10;
+ dist = VectorNormalize(dir);
+ //elemantary actions
+ EA_Move(ms->client, dir, 400);
+ //set the ideal view angles
+ Vector2Angles(dir, result.ideal_viewangles);
+ result.flags |= MOVERESULT_MOVEMENTVIEW;
+ //
+ VectorCopy(dir, result.movedir);
+ //
+ return result;
+} //end of the function BotFinishTravel_WaterJump
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_moveresult_t BotTravel_WalkOffLedge(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ vec3_t hordir, dir;
+ float dist, speed, reachhordist;
+ bot_moveresult_t result;
+
+ BotClearMoveResult(&result);
+ //check if the bot is blocked by anything
+ VectorSubtract(reach->start, ms->origin, dir);
+ VectorNormalize(dir);
+ BotCheckBlocked(ms, dir, qtrue, &result);
+ //if the reachability start and end are practially above each other
+ VectorSubtract(reach->end, reach->start, dir);
+ dir[2] = 0;
+ reachhordist = VectorLength(dir);
+ //walk straight to the reachability start
+ hordir[0] = reach->start[0] - ms->origin[0];
+ hordir[1] = reach->start[1] - ms->origin[1];
+ hordir[2] = 0;
+ dist = VectorNormalize(hordir);
+ //if pretty close to the start focus on the reachability end
+ if (dist < 48)
+ {
+ hordir[0] = reach->end[0] - ms->origin[0];
+ hordir[1] = reach->end[1] - ms->origin[1];
+ hordir[2] = 0;
+ VectorNormalize(hordir);
+ //
+ if (reachhordist < 20)
+ {
+ speed = 100;
+ } //end if
+ else if (!AAS_HorizontalVelocityForJump(0, reach->start, reach->end, &speed))
+ {
+ speed = 400;
+ } //end if
+ } //end if
+ else
+ {
+ if (reachhordist < 20)
+ {
+ if (dist > 64) dist = 64;
+ speed = 400 - (256 - 4 * dist);
+ } //end if
+ else
+ {
+ speed = 400;
+ } //end else
+ } //end else
+ //
+ BotCheckBlocked(ms, hordir, qtrue, &result);
+ //elemantary action
+ EA_Move(ms->client, hordir, speed);
+ VectorCopy(hordir, result.movedir);
+ //
+ return result;
+} //end of the function BotTravel_WalkOffLedge
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotAirControl(vec3_t origin, vec3_t velocity, vec3_t goal, vec3_t dir, float *speed)
+{
+ vec3_t org, vel;
+ float dist;
+ int i;
+
+ VectorCopy(origin, org);
+ VectorScale(velocity, 0.1, vel);
+ for (i = 0; i < 50; i++)
+ {
+ vel[2] -= sv_gravity->value * 0.01;
+ //if going down and next position would be below the goal
+ if (vel[2] < 0 && org[2] + vel[2] < goal[2])
+ {
+ VectorScale(vel, (goal[2] - org[2]) / vel[2], vel);
+ VectorAdd(org, vel, org);
+ VectorSubtract(goal, org, dir);
+ dist = VectorNormalize(dir);
+ if (dist > 32) dist = 32;
+ *speed = 400 - (400 - 13 * dist);
+ return qtrue;
+ } //end if
+ else
+ {
+ VectorAdd(org, vel, org);
+ } //end else
+ } //end for
+ VectorSet(dir, 0, 0, 0);
+ *speed = 400;
+ return qfalse;
+} //end of the function BotAirControl
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_moveresult_t BotFinishTravel_WalkOffLedge(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ vec3_t dir, hordir, end, v;
+ float dist, speed;
+ bot_moveresult_t result;
+
+ BotClearMoveResult(&result);
+ //
+ VectorSubtract(reach->end, ms->origin, dir);
+ BotCheckBlocked(ms, dir, qtrue, &result);
+ //
+ VectorSubtract(reach->end, ms->origin, v);
+ v[2] = 0;
+ dist = VectorNormalize(v);
+ if (dist > 16) VectorMA(reach->end, 16, v, end);
+ else VectorCopy(reach->end, end);
+ //
+ if (!BotAirControl(ms->origin, ms->velocity, end, hordir, &speed))
+ {
+ //go straight to the reachability end
+ VectorCopy(dir, hordir);
+ hordir[2] = 0;
+ //
+ dist = VectorNormalize(hordir);
+ speed = 400;
+ } //end if
+ //
+ EA_Move(ms->client, hordir, speed);
+ VectorCopy(hordir, result.movedir);
+ //
+ return result;
+} //end of the function BotFinishTravel_WalkOffLedge
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+/*
+bot_moveresult_t BotTravel_Jump(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ vec3_t hordir;
+ float dist, gapdist, speed, horspeed, sv_jumpvel;
+ bot_moveresult_t result;
+
+ BotClearMoveResult(&result);
+ //
+ sv_jumpvel = botlibglobals.sv_jumpvel->value;
+ //walk straight to the reachability start
+ hordir[0] = reach->start[0] - ms->origin[0];
+ hordir[1] = reach->start[1] - ms->origin[1];
+ hordir[2] = 0;
+ dist = VectorNormalize(hordir);
+ //
+ speed = 350;
+ //
+ gapdist = BotGapDistance(ms, hordir, ms->entitynum);
+ //if pretty close to the start focus on the reachability end
+ if (dist < 50 || (gapdist && gapdist < 50))
+ {
+ //NOTE: using max speed (400) works best
+ //if (AAS_HorizontalVelocityForJump(sv_jumpvel, ms->origin, reach->end, &horspeed))
+ //{
+ // speed = horspeed * 400 / botlibglobals.sv_maxwalkvelocity->value;
+ //} //end if
+ hordir[0] = reach->end[0] - ms->origin[0];
+ hordir[1] = reach->end[1] - ms->origin[1];
+ VectorNormalize(hordir);
+ //elemantary action jump
+ EA_Jump(ms->client);
+ //
+ ms->jumpreach = ms->lastreachnum;
+ speed = 600;
+ } //end if
+ else
+ {
+ if (AAS_HorizontalVelocityForJump(sv_jumpvel, reach->start, reach->end, &horspeed))
+ {
+ speed = horspeed * 400 / botlibglobals.sv_maxwalkvelocity->value;
+ } //end if
+ } //end else
+ //elemantary action
+ EA_Move(ms->client, hordir, speed);
+ VectorCopy(hordir, result.movedir);
+ //
+ return result;
+} //end of the function BotTravel_Jump*/
+/*
+bot_moveresult_t BotTravel_Jump(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ vec3_t hordir, dir1, dir2, mins, maxs, start, end;
+ float dist1, dist2, speed;
+ bot_moveresult_t result;
+ bsp_trace_t trace;
+
+ BotClearMoveResult(&result);
+ //
+ hordir[0] = reach->start[0] - reach->end[0];
+ hordir[1] = reach->start[1] - reach->end[1];
+ hordir[2] = 0;
+ VectorNormalize(hordir);
+ //
+ VectorCopy(reach->start, start);
+ start[2] += 1;
+ //minus back the bouding box size plus 16
+ VectorMA(reach->start, 80, hordir, end);
+ //
+ AAS_PresenceTypeBoundingBox(PRESENCE_NORMAL, mins, maxs);
+ //check for solids
+ trace = AAS_Trace(start, mins, maxs, end, ms->entitynum, MASK_PLAYERSOLID);
+ if (trace.startsolid) VectorCopy(start, trace.endpos);
+ //check for a gap
+ for (dist1 = 0; dist1 < 80; dist1 += 10)
+ {
+ VectorMA(start, dist1+10, hordir, end);
+ end[2] += 1;
+ if (AAS_PointAreaNum(end) != ms->reachareanum) break;
+ } //end for
+ if (dist1 < 80) VectorMA(reach->start, dist1, hordir, trace.endpos);
+// dist1 = BotGapDistance(start, hordir, ms->entitynum);
+// if (dist1 && dist1 <= trace.fraction * 80) VectorMA(reach->start, dist1-20, hordir, trace.endpos);
+ //
+ VectorSubtract(ms->origin, reach->start, dir1);
+ dir1[2] = 0;
+ dist1 = VectorNormalize(dir1);
+ VectorSubtract(ms->origin, trace.endpos, dir2);
+ dir2[2] = 0;
+ dist2 = VectorNormalize(dir2);
+ //if just before the reachability start
+ if (DotProduct(dir1, dir2) < -0.8 || dist2 < 5)
+ {
+ //botimport.Print(PRT_MESSAGE, "between jump start and run to point\n");
+ hordir[0] = reach->end[0] - ms->origin[0];
+ hordir[1] = reach->end[1] - ms->origin[1];
+ hordir[2] = 0;
+ VectorNormalize(hordir);
+ //elemantary action jump
+ if (dist1 < 24) EA_Jump(ms->client);
+ else if (dist1 < 32) EA_DelayedJump(ms->client);
+ EA_Move(ms->client, hordir, 600);
+ //
+ ms->jumpreach = ms->lastreachnum;
+ } //end if
+ else
+ {
+ //botimport.Print(PRT_MESSAGE, "going towards run to point\n");
+ hordir[0] = trace.endpos[0] - ms->origin[0];
+ hordir[1] = trace.endpos[1] - ms->origin[1];
+ hordir[2] = 0;
+ VectorNormalize(hordir);
+ //
+ if (dist2 > 80) dist2 = 80;
+ speed = 400 - (400 - 5 * dist2);
+ EA_Move(ms->client, hordir, speed);
+ } //end else
+ VectorCopy(hordir, result.movedir);
+ //
+ return result;
+} //end of the function BotTravel_Jump*/
+//*
+bot_moveresult_t BotTravel_Jump(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ vec3_t hordir, dir1, dir2, start, end, runstart;
+// vec3_t runstart, dir1, dir2, hordir;
+ float dist1, dist2, speed;
+ bot_moveresult_t result;
+
+ BotClearMoveResult(&result);
+ //
+ AAS_JumpReachRunStart(reach, runstart);
+ //*
+ hordir[0] = runstart[0] - reach->start[0];
+ hordir[1] = runstart[1] - reach->start[1];
+ hordir[2] = 0;
+ VectorNormalize(hordir);
+ //
+ VectorCopy(reach->start, start);
+ start[2] += 1;
+ VectorMA(reach->start, 80, hordir, runstart);
+ //check for a gap
+ for (dist1 = 0; dist1 < 80; dist1 += 10)
+ {
+ VectorMA(start, dist1+10, hordir, end);
+ end[2] += 1;
+ if (AAS_PointAreaNum(end) != ms->reachareanum) break;
+ } //end for
+ if (dist1 < 80) VectorMA(reach->start, dist1, hordir, runstart);
+ //
+ VectorSubtract(ms->origin, reach->start, dir1);
+ dir1[2] = 0;
+ dist1 = VectorNormalize(dir1);
+ VectorSubtract(ms->origin, runstart, dir2);
+ dir2[2] = 0;
+ dist2 = VectorNormalize(dir2);
+ //if just before the reachability start
+ if (DotProduct(dir1, dir2) < -0.8 || dist2 < 5)
+ {
+// botimport.Print(PRT_MESSAGE, "between jump start and run start point\n");
+ hordir[0] = reach->end[0] - ms->origin[0];
+ hordir[1] = reach->end[1] - ms->origin[1];
+ hordir[2] = 0;
+ VectorNormalize(hordir);
+ //elemantary action jump
+ if (dist1 < 24) EA_Jump(ms->client);
+ else if (dist1 < 32) EA_DelayedJump(ms->client);
+ EA_Move(ms->client, hordir, 600);
+ //
+ ms->jumpreach = ms->lastreachnum;
+ } //end if
+ else
+ {
+// botimport.Print(PRT_MESSAGE, "going towards run start point\n");
+ hordir[0] = runstart[0] - ms->origin[0];
+ hordir[1] = runstart[1] - ms->origin[1];
+ hordir[2] = 0;
+ VectorNormalize(hordir);
+ //
+ if (dist2 > 80) dist2 = 80;
+ speed = 400 - (400 - 5 * dist2);
+ EA_Move(ms->client, hordir, speed);
+ } //end else
+ VectorCopy(hordir, result.movedir);
+ //
+ return result;
+} //end of the function BotTravel_Jump*/
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_moveresult_t BotFinishTravel_Jump(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ vec3_t hordir, hordir2;
+ float speed, dist;
+ bot_moveresult_t result;
+
+ BotClearMoveResult(&result);
+ //if not jumped yet
+ if (!ms->jumpreach) return result;
+ //go straight to the reachability end
+ hordir[0] = reach->end[0] - ms->origin[0];
+ hordir[1] = reach->end[1] - ms->origin[1];
+ hordir[2] = 0;
+ dist = VectorNormalize(hordir);
+ //
+ hordir2[0] = reach->end[0] - reach->start[0];
+ hordir2[1] = reach->end[1] - reach->start[1];
+ hordir2[2] = 0;
+ VectorNormalize(hordir2);
+ //
+ if (DotProduct(hordir, hordir2) < -0.5 && dist < 24) return result;
+ //always use max speed when traveling through the air
+ speed = 800;
+ //
+ EA_Move(ms->client, hordir, speed);
+ VectorCopy(hordir, result.movedir);
+ //
+ return result;
+} //end of the function BotFinishTravel_Jump
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_moveresult_t BotTravel_Ladder(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ //float dist, speed;
+ vec3_t dir, viewdir;//, hordir;
+ vec3_t origin = {0, 0, 0};
+// vec3_t up = {0, 0, 1};
+ bot_moveresult_t result;
+
+ BotClearMoveResult(&result);
+ //
+// if ((ms->moveflags & MFL_AGAINSTLADDER))
+ //NOTE: not a good idea for ladders starting in water
+ // || !(ms->moveflags & MFL_ONGROUND))
+ {
+ //botimport.Print(PRT_MESSAGE, "against ladder or not on ground\n");
+ VectorSubtract(reach->end, ms->origin, dir);
+ VectorNormalize(dir);
+ //set the ideal view angles, facing the ladder up or down
+ viewdir[0] = dir[0];
+ viewdir[1] = dir[1];
+ viewdir[2] = 3 * dir[2];
+ Vector2Angles(viewdir, result.ideal_viewangles);
+ //elemantary action
+ EA_Move(ms->client, origin, 0);
+ EA_MoveForward(ms->client);
+ //set movement view flag so the AI can see the view is focussed
+ result.flags |= MOVERESULT_MOVEMENTVIEW;
+ } //end if
+/* else
+ {
+ //botimport.Print(PRT_MESSAGE, "moving towards ladder\n");
+ VectorSubtract(reach->end, ms->origin, dir);
+ //make sure the horizontal movement is large anough
+ VectorCopy(dir, hordir);
+ hordir[2] = 0;
+ dist = VectorNormalize(hordir);
+ //
+ dir[0] = hordir[0];
+ dir[1] = hordir[1];
+ if (dir[2] > 0) dir[2] = 1;
+ else dir[2] = -1;
+ if (dist > 50) dist = 50;
+ speed = 400 - (200 - 4 * dist);
+ EA_Move(ms->client, dir, speed);
+ } //end else*/
+ //save the movement direction
+ VectorCopy(dir, result.movedir);
+ //
+ return result;
+} //end of the function BotTravel_Ladder
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_moveresult_t BotTravel_Teleport(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ vec3_t hordir;
+ float dist;
+ bot_moveresult_t result;
+
+ BotClearMoveResult(&result);
+ //if the bot is being teleported
+ if (ms->moveflags & MFL_TELEPORTED) return result;
+
+ //walk straight to center of the teleporter
+ VectorSubtract(reach->start, ms->origin, hordir);
+ if (!(ms->moveflags & MFL_SWIMMING)) hordir[2] = 0;
+ dist = VectorNormalize(hordir);
+ //
+ BotCheckBlocked(ms, hordir, qtrue, &result);
+
+ if (dist < 30) EA_Move(ms->client, hordir, 200);
+ else EA_Move(ms->client, hordir, 400);
+
+ if (ms->moveflags & MFL_SWIMMING) result.flags |= MOVERESULT_SWIMVIEW;
+
+ VectorCopy(hordir, result.movedir);
+ return result;
+} //end of the function BotTravel_Teleport
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_moveresult_t BotTravel_Elevator(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ vec3_t dir, dir1, dir2, hordir, bottomcenter;
+ float dist, dist1, dist2, speed;
+ bot_moveresult_t result;
+
+ BotClearMoveResult(&result);
+ //if standing on the plat
+ if (BotOnMover(ms->origin, ms->entitynum, reach))
+ {
+#ifdef DEBUG_ELEVATOR
+ botimport.Print(PRT_MESSAGE, "bot on elevator\n");
+#endif //DEBUG_ELEVATOR
+ //if vertically not too far from the end point
+ if (abs(ms->origin[2] - reach->end[2]) < sv_maxbarrier->value)
+ {
+#ifdef DEBUG_ELEVATOR
+ botimport.Print(PRT_MESSAGE, "bot moving to end\n");
+#endif //DEBUG_ELEVATOR
+ //move to the end point
+ VectorSubtract(reach->end, ms->origin, hordir);
+ hordir[2] = 0;
+ VectorNormalize(hordir);
+ if (!BotCheckBarrierJump(ms, hordir, 100))
+ {
+ EA_Move(ms->client, hordir, 400);
+ } //end if
+ VectorCopy(hordir, result.movedir);
+ } //end else
+ //if not really close to the center of the elevator
+ else
+ {
+ MoverBottomCenter(reach, bottomcenter);
+ VectorSubtract(bottomcenter, ms->origin, hordir);
+ hordir[2] = 0;
+ dist = VectorNormalize(hordir);
+ //
+ if (dist > 10)
+ {
+#ifdef DEBUG_ELEVATOR
+ botimport.Print(PRT_MESSAGE, "bot moving to center\n");
+#endif //DEBUG_ELEVATOR
+ //move to the center of the plat
+ if (dist > 100) dist = 100;
+ speed = 400 - (400 - 4 * dist);
+ //
+ EA_Move(ms->client, hordir, speed);
+ VectorCopy(hordir, result.movedir);
+ } //end if
+ } //end else
+ } //end if
+ else
+ {
+#ifdef DEBUG_ELEVATOR
+ botimport.Print(PRT_MESSAGE, "bot not on elevator\n");
+#endif //DEBUG_ELEVATOR
+ //if very near the reachability end
+ VectorSubtract(reach->end, ms->origin, dir);
+ dist = VectorLength(dir);
+ if (dist < 64)
+ {
+ if (dist > 60) dist = 60;
+ speed = 360 - (360 - 6 * dist);
+ //
+ if ((ms->moveflags & MFL_SWIMMING) || !BotCheckBarrierJump(ms, dir, 50))
+ {
+ if (speed > 5) EA_Move(ms->client, dir, speed);
+ } //end if
+ VectorCopy(dir, result.movedir);
+ //
+ if (ms->moveflags & MFL_SWIMMING) result.flags |= MOVERESULT_SWIMVIEW;
+ //stop using this reachability
+ ms->reachability_time = 0;
+ return result;
+ } //end if
+ //get direction and distance to reachability start
+ VectorSubtract(reach->start, ms->origin, dir1);
+ if (!(ms->moveflags & MFL_SWIMMING)) dir1[2] = 0;
+ dist1 = VectorNormalize(dir1);
+ //if the elevator isn't down
+ if (!MoverDown(reach))
+ {
+#ifdef DEBUG_ELEVATOR
+ botimport.Print(PRT_MESSAGE, "elevator not down\n");
+#endif //DEBUG_ELEVATOR
+ dist = dist1;
+ VectorCopy(dir1, dir);
+ //
+ BotCheckBlocked(ms, dir, qfalse, &result);
+ //
+ if (dist > 60) dist = 60;
+ speed = 360 - (360 - 6 * dist);
+ //
+ if (!(ms->moveflags & MFL_SWIMMING) && !BotCheckBarrierJump(ms, dir, 50))
+ {
+ if (speed > 5) EA_Move(ms->client, dir, speed);
+ } //end if
+ VectorCopy(dir, result.movedir);
+ //
+ if (ms->moveflags & MFL_SWIMMING) result.flags |= MOVERESULT_SWIMVIEW;
+ //this isn't a failure... just wait till the elevator comes down
+ result.type = RESULTTYPE_ELEVATORUP;
+ result.flags |= MOVERESULT_WAITING;
+ return result;
+ } //end if
+ //get direction and distance to elevator bottom center
+ MoverBottomCenter(reach, bottomcenter);
+ VectorSubtract(bottomcenter, ms->origin, dir2);
+ if (!(ms->moveflags & MFL_SWIMMING)) dir2[2] = 0;
+ dist2 = VectorNormalize(dir2);
+ //if very close to the reachability start or
+ //closer to the elevator center or
+ //between reachability start and elevator center
+ if (dist1 < 20 || dist2 < dist1 || DotProduct(dir1, dir2) < 0)
+ {
+#ifdef DEBUG_ELEVATOR
+ botimport.Print(PRT_MESSAGE, "bot moving to center\n");
+#endif //DEBUG_ELEVATOR
+ dist = dist2;
+ VectorCopy(dir2, dir);
+ } //end if
+ else //closer to the reachability start
+ {
+#ifdef DEBUG_ELEVATOR
+ botimport.Print(PRT_MESSAGE, "bot moving to start\n");
+#endif //DEBUG_ELEVATOR
+ dist = dist1;
+ VectorCopy(dir1, dir);
+ } //end else
+ //
+ BotCheckBlocked(ms, dir, qfalse, &result);
+ //
+ if (dist > 60) dist = 60;
+ speed = 400 - (400 - 6 * dist);
+ //
+ if (!(ms->moveflags & MFL_SWIMMING) && !BotCheckBarrierJump(ms, dir, 50))
+ {
+ EA_Move(ms->client, dir, speed);
+ } //end if
+ VectorCopy(dir, result.movedir);
+ //
+ if (ms->moveflags & MFL_SWIMMING) result.flags |= MOVERESULT_SWIMVIEW;
+ } //end else
+ return result;
+} //end of the function BotTravel_Elevator
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_moveresult_t BotFinishTravel_Elevator(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ vec3_t bottomcenter, bottomdir, topdir;
+ bot_moveresult_t result;
+
+ BotClearMoveResult(&result);
+ //
+ MoverBottomCenter(reach, bottomcenter);
+ VectorSubtract(bottomcenter, ms->origin, bottomdir);
+ //
+ VectorSubtract(reach->end, ms->origin, topdir);
+ //
+ if (fabs(bottomdir[2]) < fabs(topdir[2]))
+ {
+ VectorNormalize(bottomdir);
+ EA_Move(ms->client, bottomdir, 300);
+ } //end if
+ else
+ {
+ VectorNormalize(topdir);
+ EA_Move(ms->client, topdir, 300);
+ } //end else
+ return result;
+} //end of the function BotFinishTravel_Elevator
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotFuncBobStartEnd(aas_reachability_t *reach, vec3_t start, vec3_t end, vec3_t origin)
+{
+ int spawnflags, modelnum;
+ vec3_t mins, maxs, mid, angles = {0, 0, 0};
+ int num0, num1;
+
+ modelnum = reach->facenum & 0x0000FFFF;
+ if (!AAS_OriginOfMoverWithModelNum(modelnum, origin))
+ {
+ botimport.Print(PRT_MESSAGE, "BotFuncBobStartEnd: no entity with model %d\n", modelnum);
+ VectorSet(start, 0, 0, 0);
+ VectorSet(end, 0, 0, 0);
+ return;
+ } //end if
+ AAS_BSPModelMinsMaxsOrigin(modelnum, angles, mins, maxs, NULL);
+ VectorAdd(mins, maxs, mid);
+ VectorScale(mid, 0.5, mid);
+ VectorCopy(mid, start);
+ VectorCopy(mid, end);
+ spawnflags = reach->facenum >> 16;
+ num0 = reach->edgenum >> 16;
+ if (num0 > 0x00007FFF) num0 |= 0xFFFF0000;
+ num1 = reach->edgenum & 0x0000FFFF;
+ if (num1 > 0x00007FFF) num1 |= 0xFFFF0000;
+ if (spawnflags & 1)
+ {
+ start[0] = num0;
+ end[0] = num1;
+ //
+ origin[0] += mid[0];
+ origin[1] = mid[1];
+ origin[2] = mid[2];
+ } //end if
+ else if (spawnflags & 2)
+ {
+ start[1] = num0;
+ end[1] = num1;
+ //
+ origin[0] = mid[0];
+ origin[1] += mid[1];
+ origin[2] = mid[2];
+ } //end else if
+ else
+ {
+ start[2] = num0;
+ end[2] = num1;
+ //
+ origin[0] = mid[0];
+ origin[1] = mid[1];
+ origin[2] += mid[2];
+ } //end else
+} //end of the function BotFuncBobStartEnd
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_moveresult_t BotTravel_FuncBobbing(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ vec3_t dir, dir1, dir2, hordir, bottomcenter, bob_start, bob_end, bob_origin;
+ float dist, dist1, dist2, speed;
+ bot_moveresult_t result;
+
+ BotClearMoveResult(&result);
+ //
+ BotFuncBobStartEnd(reach, bob_start, bob_end, bob_origin);
+ //if standing ontop of the func_bobbing
+ if (BotOnMover(ms->origin, ms->entitynum, reach))
+ {
+#ifdef DEBUG_FUNCBOB
+ botimport.Print(PRT_MESSAGE, "bot on func_bobbing\n");
+#endif
+ //if near end point of reachability
+ VectorSubtract(bob_origin, bob_end, dir);
+ if (VectorLength(dir) < 24)
+ {
+#ifdef DEBUG_FUNCBOB
+ botimport.Print(PRT_MESSAGE, "bot moving to reachability end\n");
+#endif
+ //move to the end point
+ VectorSubtract(reach->end, ms->origin, hordir);
+ hordir[2] = 0;
+ VectorNormalize(hordir);
+ if (!BotCheckBarrierJump(ms, hordir, 100))
+ {
+ EA_Move(ms->client, hordir, 400);
+ } //end if
+ VectorCopy(hordir, result.movedir);
+ } //end else
+ //if not really close to the center of the elevator
+ else
+ {
+ MoverBottomCenter(reach, bottomcenter);
+ VectorSubtract(bottomcenter, ms->origin, hordir);
+ hordir[2] = 0;
+ dist = VectorNormalize(hordir);
+ //
+ if (dist > 10)
+ {
+#ifdef DEBUG_FUNCBOB
+ botimport.Print(PRT_MESSAGE, "bot moving to func_bobbing center\n");
+#endif
+ //move to the center of the plat
+ if (dist > 100) dist = 100;
+ speed = 400 - (400 - 4 * dist);
+ //
+ EA_Move(ms->client, hordir, speed);
+ VectorCopy(hordir, result.movedir);
+ } //end if
+ } //end else
+ } //end if
+ else
+ {
+#ifdef DEBUG_FUNCBOB
+ botimport.Print(PRT_MESSAGE, "bot not ontop of func_bobbing\n");
+#endif
+ //if very near the reachability end
+ VectorSubtract(reach->end, ms->origin, dir);
+ dist = VectorLength(dir);
+ if (dist < 64)
+ {
+#ifdef DEBUG_FUNCBOB
+ botimport.Print(PRT_MESSAGE, "bot moving to end\n");
+#endif
+ if (dist > 60) dist = 60;
+ speed = 360 - (360 - 6 * dist);
+ //if swimming or no barrier jump
+ if ((ms->moveflags & MFL_SWIMMING) || !BotCheckBarrierJump(ms, dir, 50))
+ {
+ if (speed > 5) EA_Move(ms->client, dir, speed);
+ } //end if
+ VectorCopy(dir, result.movedir);
+ //
+ if (ms->moveflags & MFL_SWIMMING) result.flags |= MOVERESULT_SWIMVIEW;
+ //stop using this reachability
+ ms->reachability_time = 0;
+ return result;
+ } //end if
+ //get direction and distance to reachability start
+ VectorSubtract(reach->start, ms->origin, dir1);
+ if (!(ms->moveflags & MFL_SWIMMING)) dir1[2] = 0;
+ dist1 = VectorNormalize(dir1);
+ //if func_bobbing is Not it's start position
+ VectorSubtract(bob_origin, bob_start, dir);
+ if (VectorLength(dir) > 16)
+ {
+#ifdef DEBUG_FUNCBOB
+ botimport.Print(PRT_MESSAGE, "func_bobbing not at start\n");
+#endif
+ dist = dist1;
+ VectorCopy(dir1, dir);
+ //
+ BotCheckBlocked(ms, dir, qfalse, &result);
+ //
+ if (dist > 60) dist = 60;
+ speed = 360 - (360 - 6 * dist);
+ //
+ if (!(ms->moveflags & MFL_SWIMMING) && !BotCheckBarrierJump(ms, dir, 50))
+ {
+ if (speed > 5) EA_Move(ms->client, dir, speed);
+ } //end if
+ VectorCopy(dir, result.movedir);
+ //
+ if (ms->moveflags & MFL_SWIMMING) result.flags |= MOVERESULT_SWIMVIEW;
+ //this isn't a failure... just wait till the func_bobbing arrives
+ result.type = RESULTTYPE_WAITFORFUNCBOBBING;
+ result.flags |= MOVERESULT_WAITING;
+ return result;
+ } //end if
+ //get direction and distance to func_bob bottom center
+ MoverBottomCenter(reach, bottomcenter);
+ VectorSubtract(bottomcenter, ms->origin, dir2);
+ if (!(ms->moveflags & MFL_SWIMMING)) dir2[2] = 0;
+ dist2 = VectorNormalize(dir2);
+ //if very close to the reachability start or
+ //closer to the elevator center or
+ //between reachability start and func_bobbing center
+ if (dist1 < 20 || dist2 < dist1 || DotProduct(dir1, dir2) < 0)
+ {
+#ifdef DEBUG_FUNCBOB
+ botimport.Print(PRT_MESSAGE, "bot moving to func_bobbing center\n");
+#endif
+ dist = dist2;
+ VectorCopy(dir2, dir);
+ } //end if
+ else //closer to the reachability start
+ {
+#ifdef DEBUG_FUNCBOB
+ botimport.Print(PRT_MESSAGE, "bot moving to reachability start\n");
+#endif
+ dist = dist1;
+ VectorCopy(dir1, dir);
+ } //end else
+ //
+ BotCheckBlocked(ms, dir, qfalse, &result);
+ //
+ if (dist > 60) dist = 60;
+ speed = 400 - (400 - 6 * dist);
+ //
+ if (!(ms->moveflags & MFL_SWIMMING) && !BotCheckBarrierJump(ms, dir, 50))
+ {
+ EA_Move(ms->client, dir, speed);
+ } //end if
+ VectorCopy(dir, result.movedir);
+ //
+ if (ms->moveflags & MFL_SWIMMING) result.flags |= MOVERESULT_SWIMVIEW;
+ } //end else
+ return result;
+} //end of the function BotTravel_FuncBobbing
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_moveresult_t BotFinishTravel_FuncBobbing(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ vec3_t bob_origin, bob_start, bob_end, dir, hordir, bottomcenter;
+ bot_moveresult_t result;
+ float dist, speed;
+
+ BotClearMoveResult(&result);
+ //
+ BotFuncBobStartEnd(reach, bob_start, bob_end, bob_origin);
+ //
+ VectorSubtract(bob_origin, bob_end, dir);
+ dist = VectorLength(dir);
+ //if the func_bobbing is near the end
+ if (dist < 16)
+ {
+ VectorSubtract(reach->end, ms->origin, hordir);
+ if (!(ms->moveflags & MFL_SWIMMING)) hordir[2] = 0;
+ dist = VectorNormalize(hordir);
+ //
+ if (dist > 60) dist = 60;
+ speed = 360 - (360 - 6 * dist);
+ //
+ if (speed > 5) EA_Move(ms->client, dir, speed);
+ VectorCopy(dir, result.movedir);
+ //
+ if (ms->moveflags & MFL_SWIMMING) result.flags |= MOVERESULT_SWIMVIEW;
+ } //end if
+ else
+ {
+ MoverBottomCenter(reach, bottomcenter);
+ VectorSubtract(bottomcenter, ms->origin, hordir);
+ if (!(ms->moveflags & MFL_SWIMMING)) hordir[2] = 0;
+ dist = VectorNormalize(hordir);
+ //
+ if (dist > 5)
+ {
+ //move to the center of the plat
+ if (dist > 100) dist = 100;
+ speed = 400 - (400 - 4 * dist);
+ //
+ EA_Move(ms->client, hordir, speed);
+ VectorCopy(hordir, result.movedir);
+ } //end if
+ } //end else
+ return result;
+} //end of the function BotFinishTravel_FuncBobbing
+//===========================================================================
+// 0 no valid grapple hook visible
+// 1 the grapple hook is still flying
+// 2 the grapple hooked into a wall
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int GrappleState(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ int i;
+ aas_entityinfo_t entinfo;
+
+ //if the grapple hook is pulling
+ if (ms->moveflags & MFL_GRAPPLEPULL)
+ return 2;
+ //check for a visible grapple missile entity
+ //or visible grapple entity
+ for (i = AAS_NextEntity(0); i; i = AAS_NextEntity(i))
+ {
+ if (AAS_EntityType(i) == (int) entitytypemissile->value)
+ {
+ AAS_EntityInfo(i, &entinfo);
+ if (entinfo.weapon == (int) weapindex_grapple->value)
+ {
+ return 1;
+ } //end if
+ } //end if
+ } //end for
+ //no valid grapple at all
+ return 0;
+} //end of the function GrappleState
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotResetGrapple(bot_movestate_t *ms)
+{
+ aas_reachability_t reach;
+
+ AAS_ReachabilityFromNum(ms->lastreachnum, &reach);
+ //if not using the grapple hook reachability anymore
+ if ((reach.traveltype & TRAVELTYPE_MASK) != TRAVEL_GRAPPLEHOOK)
+ {
+ if ((ms->moveflags & MFL_ACTIVEGRAPPLE) || ms->grapplevisible_time)
+ {
+ if (offhandgrapple->value)
+ EA_Command(ms->client, cmd_grappleoff->string);
+ ms->moveflags &= ~MFL_ACTIVEGRAPPLE;
+ ms->grapplevisible_time = 0;
+#ifdef DEBUG_GRAPPLE
+ botimport.Print(PRT_MESSAGE, "reset grapple\n");
+#endif //DEBUG_GRAPPLE
+ } //end if
+ } //end if
+} //end of the function BotResetGrapple
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_moveresult_t BotTravel_Grapple(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ bot_moveresult_t result;
+ float dist, speed;
+ vec3_t dir, viewdir, org;
+ int state, areanum;
+ bsp_trace_t trace;
+
+#ifdef DEBUG_GRAPPLE
+ static int debugline;
+ if (!debugline) debugline = botimport.DebugLineCreate();
+ botimport.DebugLineShow(debugline, reach->start, reach->end, LINECOLOR_BLUE);
+#endif //DEBUG_GRAPPLE
+
+ BotClearMoveResult(&result);
+ //
+ if (ms->moveflags & MFL_GRAPPLERESET)
+ {
+ if (offhandgrapple->value)
+ EA_Command(ms->client, cmd_grappleoff->string);
+ ms->moveflags &= ~MFL_ACTIVEGRAPPLE;
+ return result;
+ } //end if
+ //
+ if (!(int) offhandgrapple->value)
+ {
+ result.weapon = weapindex_grapple->value;
+ result.flags |= MOVERESULT_MOVEMENTWEAPON;
+ } //end if
+ //
+ if (ms->moveflags & MFL_ACTIVEGRAPPLE)
+ {
+#ifdef DEBUG_GRAPPLE
+ botimport.Print(PRT_MESSAGE, "BotTravel_Grapple: active grapple\n");
+#endif //DEBUG_GRAPPLE
+ //
+ state = GrappleState(ms, reach);
+ //
+ VectorSubtract(reach->end, ms->origin, dir);
+ dir[2] = 0;
+ dist = VectorLength(dir);
+ //if very close to the grapple end or the grappled is hooked and
+ //the bot doesn't get any closer
+ if (state && dist < 48)
+ {
+ if (ms->lastgrappledist - dist < 1)
+ {
+#ifdef DEBUG_GRAPPLE
+ botimport.Print(PRT_ERROR, "grapple normal end\n");
+#endif //DEBUG_GRAPPLE
+ if (offhandgrapple->value)
+ EA_Command(ms->client, cmd_grappleoff->string);
+ ms->moveflags &= ~MFL_ACTIVEGRAPPLE;
+ ms->moveflags |= MFL_GRAPPLERESET;
+ ms->reachability_time = 0; //end the reachability
+ return result;
+ } //end if
+ } //end if
+ //if no valid grapple at all, or the grapple hooked and the bot
+ //isn't moving anymore
+ else if (!state || (state == 2 && dist > ms->lastgrappledist - 2))
+ {
+ if (ms->grapplevisible_time < AAS_Time() - 0.4)
+ {
+#ifdef DEBUG_GRAPPLE
+ botimport.Print(PRT_ERROR, "grapple not visible\n");
+#endif //DEBUG_GRAPPLE
+ if (offhandgrapple->value)
+ EA_Command(ms->client, cmd_grappleoff->string);
+ ms->moveflags &= ~MFL_ACTIVEGRAPPLE;
+ ms->moveflags |= MFL_GRAPPLERESET;
+ ms->reachability_time = 0; //end the reachability
+ return result;
+ } //end if
+ } //end if
+ else
+ {
+ ms->grapplevisible_time = AAS_Time();
+ } //end else
+ //
+ if (!(int) offhandgrapple->value)
+ {
+ EA_Attack(ms->client);
+ } //end if
+ //remember the current grapple distance
+ ms->lastgrappledist = dist;
+ } //end if
+ else
+ {
+#ifdef DEBUG_GRAPPLE
+ botimport.Print(PRT_MESSAGE, "BotTravel_Grapple: inactive grapple\n");
+#endif //DEBUG_GRAPPLE
+ //
+ ms->grapplevisible_time = AAS_Time();
+ //
+ VectorSubtract(reach->start, ms->origin, dir);
+ if (!(ms->moveflags & MFL_SWIMMING)) dir[2] = 0;
+ VectorAdd(ms->origin, ms->viewoffset, org);
+ VectorSubtract(reach->end, org, viewdir);
+ //
+ dist = VectorNormalize(dir);
+ Vector2Angles(viewdir, result.ideal_viewangles);
+ result.flags |= MOVERESULT_MOVEMENTVIEW;
+ //
+ if (dist < 5 &&
+ fabs(AngleDiff(result.ideal_viewangles[0], ms->viewangles[0])) < 2 &&
+ fabs(AngleDiff(result.ideal_viewangles[1], ms->viewangles[1])) < 2)
+ {
+#ifdef DEBUG_GRAPPLE
+ botimport.Print(PRT_MESSAGE, "BotTravel_Grapple: activating grapple\n");
+#endif //DEBUG_GRAPPLE
+ //check if the grapple missile path is clear
+ VectorAdd(ms->origin, ms->viewoffset, org);
+ trace = AAS_Trace(org, NULL, NULL, reach->end, ms->entitynum, CONTENTS_SOLID);
+ VectorSubtract(reach->end, trace.endpos, dir);
+ if (VectorLength(dir) > 16)
+ {
+ result.failure = qtrue;
+ return result;
+ } //end if
+ //activate the grapple
+ if (offhandgrapple->value)
+ {
+ EA_Command(ms->client, cmd_grappleon->string);
+ } //end if
+ else
+ {
+ EA_Attack(ms->client);
+ } //end else
+ ms->moveflags |= MFL_ACTIVEGRAPPLE;
+ ms->lastgrappledist = 999999;
+ } //end if
+ else
+ {
+ if (dist < 70) speed = 300 - (300 - 4 * dist);
+ else speed = 400;
+ //
+ BotCheckBlocked(ms, dir, qtrue, &result);
+ //elemantary action move in direction
+ EA_Move(ms->client, dir, speed);
+ VectorCopy(dir, result.movedir);
+ } //end else
+ //if in another area before actually grappling
+ areanum = AAS_PointAreaNum(ms->origin);
+ if (areanum && areanum != ms->reachareanum) ms->reachability_time = 0;
+ } //end else
+ return result;
+} //end of the function BotTravel_Grapple
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_moveresult_t BotTravel_RocketJump(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ vec3_t hordir;
+ float dist, speed;
+ bot_moveresult_t result;
+
+ //botimport.Print(PRT_MESSAGE, "BotTravel_RocketJump: bah\n");
+ BotClearMoveResult(&result);
+ //
+ hordir[0] = reach->start[0] - ms->origin[0];
+ hordir[1] = reach->start[1] - ms->origin[1];
+ hordir[2] = 0;
+ //
+ dist = VectorNormalize(hordir);
+ //look in the movement direction
+ Vector2Angles(hordir, result.ideal_viewangles);
+ //look straight down
+ result.ideal_viewangles[PITCH] = 90;
+ //
+ if (dist < 5 &&
+ fabs(AngleDiff(result.ideal_viewangles[0], ms->viewangles[0])) < 5 &&
+ fabs(AngleDiff(result.ideal_viewangles[1], ms->viewangles[1])) < 5)
+ {
+ //botimport.Print(PRT_MESSAGE, "between jump start and run start point\n");
+ hordir[0] = reach->end[0] - ms->origin[0];
+ hordir[1] = reach->end[1] - ms->origin[1];
+ hordir[2] = 0;
+ VectorNormalize(hordir);
+ //elemantary action jump
+ EA_Jump(ms->client);
+ EA_Attack(ms->client);
+ EA_Move(ms->client, hordir, 800);
+ //
+ ms->jumpreach = ms->lastreachnum;
+ } //end if
+ else
+ {
+ if (dist > 80) dist = 80;
+ speed = 400 - (400 - 5 * dist);
+ EA_Move(ms->client, hordir, speed);
+ } //end else
+ //look in the movement direction
+ Vector2Angles(hordir, result.ideal_viewangles);
+ //look straight down
+ result.ideal_viewangles[PITCH] = 90;
+ //set the view angles directly
+ EA_View(ms->client, result.ideal_viewangles);
+ //view is important for the movment
+ result.flags |= MOVERESULT_MOVEMENTVIEWSET;
+ //select the rocket launcher
+ EA_SelectWeapon(ms->client, (int) weapindex_rocketlauncher->value);
+ //weapon is used for movement
+ result.weapon = (int) weapindex_rocketlauncher->value;
+ result.flags |= MOVERESULT_MOVEMENTWEAPON;
+ //
+ VectorCopy(hordir, result.movedir);
+ //
+ return result;
+} //end of the function BotTravel_RocketJump
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_moveresult_t BotTravel_BFGJump(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ vec3_t hordir;
+ float dist, speed;
+ bot_moveresult_t result;
+
+ //botimport.Print(PRT_MESSAGE, "BotTravel_BFGJump: bah\n");
+ BotClearMoveResult(&result);
+ //
+ hordir[0] = reach->start[0] - ms->origin[0];
+ hordir[1] = reach->start[1] - ms->origin[1];
+ hordir[2] = 0;
+ //
+ dist = VectorNormalize(hordir);
+ //
+ if (dist < 5 &&
+ fabs(AngleDiff(result.ideal_viewangles[0], ms->viewangles[0])) < 5 &&
+ fabs(AngleDiff(result.ideal_viewangles[1], ms->viewangles[1])) < 5)
+ {
+ //botimport.Print(PRT_MESSAGE, "between jump start and run start point\n");
+ hordir[0] = reach->end[0] - ms->origin[0];
+ hordir[1] = reach->end[1] - ms->origin[1];
+ hordir[2] = 0;
+ VectorNormalize(hordir);
+ //elemantary action jump
+ EA_Jump(ms->client);
+ EA_Attack(ms->client);
+ EA_Move(ms->client, hordir, 800);
+ //
+ ms->jumpreach = ms->lastreachnum;
+ } //end if
+ else
+ {
+ if (dist > 80) dist = 80;
+ speed = 400 - (400 - 5 * dist);
+ EA_Move(ms->client, hordir, speed);
+ } //end else
+ //look in the movement direction
+ Vector2Angles(hordir, result.ideal_viewangles);
+ //look straight down
+ result.ideal_viewangles[PITCH] = 90;
+ //set the view angles directly
+ EA_View(ms->client, result.ideal_viewangles);
+ //view is important for the movment
+ result.flags |= MOVERESULT_MOVEMENTVIEWSET;
+ //select the rocket launcher
+ EA_SelectWeapon(ms->client, (int) weapindex_bfg10k->value);
+ //weapon is used for movement
+ result.weapon = (int) weapindex_bfg10k->value;
+ result.flags |= MOVERESULT_MOVEMENTWEAPON;
+ //
+ VectorCopy(hordir, result.movedir);
+ //
+ return result;
+} //end of the function BotTravel_BFGJump
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_moveresult_t BotFinishTravel_WeaponJump(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ vec3_t hordir;
+ float speed;
+ bot_moveresult_t result;
+
+ BotClearMoveResult(&result);
+ //if not jumped yet
+ if (!ms->jumpreach) return result;
+ /*
+ //go straight to the reachability end
+ hordir[0] = reach->end[0] - ms->origin[0];
+ hordir[1] = reach->end[1] - ms->origin[1];
+ hordir[2] = 0;
+ VectorNormalize(hordir);
+ //always use max speed when traveling through the air
+ EA_Move(ms->client, hordir, 800);
+ VectorCopy(hordir, result.movedir);
+ */
+ //
+ if (!BotAirControl(ms->origin, ms->velocity, reach->end, hordir, &speed))
+ {
+ //go straight to the reachability end
+ VectorSubtract(reach->end, ms->origin, hordir);
+ hordir[2] = 0;
+ VectorNormalize(hordir);
+ speed = 400;
+ } //end if
+ //
+ EA_Move(ms->client, hordir, speed);
+ VectorCopy(hordir, result.movedir);
+ //
+ return result;
+} //end of the function BotFinishTravel_WeaponJump
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_moveresult_t BotTravel_JumpPad(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ float dist, speed;
+ vec3_t hordir;
+ bot_moveresult_t result;
+
+ BotClearMoveResult(&result);
+ //first walk straight to the reachability start
+ hordir[0] = reach->start[0] - ms->origin[0];
+ hordir[1] = reach->start[1] - ms->origin[1];
+ hordir[2] = 0;
+ dist = VectorNormalize(hordir);
+ //
+ BotCheckBlocked(ms, hordir, qtrue, &result);
+ speed = 400;
+ //elemantary action move in direction
+ EA_Move(ms->client, hordir, speed);
+ VectorCopy(hordir, result.movedir);
+ //
+ return result;
+} //end of the function BotTravel_JumpPad
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_moveresult_t BotFinishTravel_JumpPad(bot_movestate_t *ms, aas_reachability_t *reach)
+{
+ float speed;
+ vec3_t hordir;
+ bot_moveresult_t result;
+
+ BotClearMoveResult(&result);
+ if (!BotAirControl(ms->origin, ms->velocity, reach->end, hordir, &speed))
+ {
+ hordir[0] = reach->end[0] - ms->origin[0];
+ hordir[1] = reach->end[1] - ms->origin[1];
+ hordir[2] = 0;
+ VectorNormalize(hordir);
+ speed = 400;
+ } //end if
+ BotCheckBlocked(ms, hordir, qtrue, &result);
+ //elemantary action move in direction
+ EA_Move(ms->client, hordir, speed);
+ VectorCopy(hordir, result.movedir);
+ //
+ return result;
+} //end of the function BotFinishTravel_JumpPad
+//===========================================================================
+// time before the reachability times out
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotReachabilityTime(aas_reachability_t *reach)
+{
+ switch(reach->traveltype & TRAVELTYPE_MASK)
+ {
+ case TRAVEL_WALK: return 5;
+ case TRAVEL_CROUCH: return 5;
+ case TRAVEL_BARRIERJUMP: return 5;
+ case TRAVEL_LADDER: return 6;
+ case TRAVEL_WALKOFFLEDGE: return 5;
+ case TRAVEL_JUMP: return 5;
+ case TRAVEL_SWIM: return 5;
+ case TRAVEL_WATERJUMP: return 5;
+ case TRAVEL_TELEPORT: return 5;
+ case TRAVEL_ELEVATOR: return 10;
+ case TRAVEL_GRAPPLEHOOK: return 8;
+ case TRAVEL_ROCKETJUMP: return 6;
+ case TRAVEL_BFGJUMP: return 6;
+ case TRAVEL_JUMPPAD: return 10;
+ case TRAVEL_FUNCBOB: return 10;
+ default:
+ {
+ botimport.Print(PRT_ERROR, "travel type %d not implemented yet\n", reach->traveltype);
+ return 8;
+ } //end case
+ } //end switch
+} //end of the function BotReachabilityTime
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bot_moveresult_t BotMoveInGoalArea(bot_movestate_t *ms, bot_goal_t *goal)
+{
+ bot_moveresult_t result;
+ vec3_t dir;
+ float dist, speed;
+
+#ifdef DEBUG
+ //botimport.Print(PRT_MESSAGE, "%s: moving straight to goal\n", ClientName(ms->entitynum-1));
+ //AAS_ClearShownDebugLines();
+ //AAS_DebugLine(ms->origin, goal->origin, LINECOLOR_RED);
+#endif //DEBUG
+ BotClearMoveResult(&result);
+ //walk straight to the goal origin
+ dir[0] = goal->origin[0] - ms->origin[0];
+ dir[1] = goal->origin[1] - ms->origin[1];
+ if (ms->moveflags & MFL_SWIMMING)
+ {
+ dir[2] = goal->origin[2] - ms->origin[2];
+ result.traveltype = TRAVEL_SWIM;
+ } //end if
+ else
+ {
+ dir[2] = 0;
+ result.traveltype = TRAVEL_WALK;
+ } //endif
+ //
+ dist = VectorNormalize(dir);
+ if (dist > 100) dist = 100;
+ speed = 400 - (400 - 4 * dist);
+ if (speed < 10) speed = 0;
+ //
+ BotCheckBlocked(ms, dir, qtrue, &result);
+ //elemantary action move in direction
+ EA_Move(ms->client, dir, speed);
+ VectorCopy(dir, result.movedir);
+ //
+ if (ms->moveflags & MFL_SWIMMING)
+ {
+ Vector2Angles(dir, result.ideal_viewangles);
+ result.flags |= MOVERESULT_SWIMVIEW;
+ } //end if
+ //if (!debugline) debugline = botimport.DebugLineCreate();
+ //botimport.DebugLineShow(debugline, ms->origin, goal->origin, LINECOLOR_BLUE);
+ //
+ ms->lastreachnum = 0;
+ ms->lastareanum = 0;
+ ms->lastgoalareanum = goal->areanum;
+ VectorCopy(ms->origin, ms->lastorigin);
+ //
+ return result;
+} //end of the function BotMoveInGoalArea
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotMoveToGoal(bot_moveresult_t *result, int movestate, bot_goal_t *goal, int travelflags)
+{
+ int reachnum, lastreachnum, foundjumppad, ent, resultflags;
+ aas_reachability_t reach, lastreach;
+ bot_movestate_t *ms;
+ //vec3_t mins, maxs, up = {0, 0, 1};
+ //bsp_trace_t trace;
+ //static int debugline;
+
+
+ BotClearMoveResult(result);
+ //
+ ms = BotMoveStateFromHandle(movestate);
+ if (!ms) return;
+ //reset the grapple before testing if the bot has a valid goal
+ //because the bot could loose all it's goals when stuck to a wall
+ BotResetGrapple(ms);
+ //
+ if (!goal)
+ {
+#ifdef DEBUG
+ botimport.Print(PRT_MESSAGE, "client %d: movetogoal -> no goal\n", ms->client);
+#endif //DEBUG
+ result->failure = qtrue;
+ return;
+ } //end if
+ //botimport.Print(PRT_MESSAGE, "numavoidreach = %d\n", ms->numavoidreach);
+ //remove some of the move flags
+ ms->moveflags &= ~(MFL_SWIMMING|MFL_AGAINSTLADDER);
+ //set some of the move flags
+ //NOTE: the MFL_ONGROUND flag is also set in the higher AI
+ if (AAS_OnGround(ms->origin, ms->presencetype, ms->entitynum)) ms->moveflags |= MFL_ONGROUND;
+ //
+ if (ms->moveflags & MFL_ONGROUND)
+ {
+ int modeltype, modelnum;
+
+ ent = BotOnTopOfEntity(ms);
+
+ if (ent != -1)
+ {
+ modelnum = AAS_EntityModelindex(ent);
+ if (modelnum >= 0 && modelnum < MAX_MODELS)
+ {
+ modeltype = modeltypes[modelnum];
+
+ if (modeltype == MODELTYPE_FUNC_PLAT)
+ {
+ AAS_ReachabilityFromNum(ms->lastreachnum, &reach);
+ //if the bot is Not using the elevator
+ if ((reach.traveltype & TRAVELTYPE_MASK) != TRAVEL_ELEVATOR ||
+ //NOTE: the face number is the plat model number
+ (reach.facenum & 0x0000FFFF) != modelnum)
+ {
+ reachnum = AAS_NextModelReachability(0, modelnum);
+ if (reachnum)
+ {
+ //botimport.Print(PRT_MESSAGE, "client %d: accidentally ended up on func_plat\n", ms->client);
+ AAS_ReachabilityFromNum(reachnum, &reach);
+ ms->lastreachnum = reachnum;
+ ms->reachability_time = AAS_Time() + BotReachabilityTime(&reach);
+ } //end if
+ else
+ {
+ if (bot_developer)
+ {
+ botimport.Print(PRT_MESSAGE, "client %d: on func_plat without reachability\n", ms->client);
+ } //end if
+ result->blocked = qtrue;
+ result->blockentity = ent;
+ result->flags |= MOVERESULT_ONTOPOFOBSTACLE;
+ return;
+ } //end else
+ } //end if
+ result->flags |= MOVERESULT_ONTOPOF_ELEVATOR;
+ } //end if
+ else if (modeltype == MODELTYPE_FUNC_BOB)
+ {
+ AAS_ReachabilityFromNum(ms->lastreachnum, &reach);
+ //if the bot is Not using the func bobbing
+ if ((reach.traveltype & TRAVELTYPE_MASK) != TRAVEL_FUNCBOB ||
+ //NOTE: the face number is the func_bobbing model number
+ (reach.facenum & 0x0000FFFF) != modelnum)
+ {
+ reachnum = AAS_NextModelReachability(0, modelnum);
+ if (reachnum)
+ {
+ //botimport.Print(PRT_MESSAGE, "client %d: accidentally ended up on func_bobbing\n", ms->client);
+ AAS_ReachabilityFromNum(reachnum, &reach);
+ ms->lastreachnum = reachnum;
+ ms->reachability_time = AAS_Time() + BotReachabilityTime(&reach);
+ } //end if
+ else
+ {
+ if (bot_developer)
+ {
+ botimport.Print(PRT_MESSAGE, "client %d: on func_bobbing without reachability\n", ms->client);
+ } //end if
+ result->blocked = qtrue;
+ result->blockentity = ent;
+ result->flags |= MOVERESULT_ONTOPOFOBSTACLE;
+ return;
+ } //end else
+ } //end if
+ result->flags |= MOVERESULT_ONTOPOF_FUNCBOB;
+ } //end if
+ else if (modeltype == MODELTYPE_FUNC_STATIC || modeltype == MODELTYPE_FUNC_DOOR)
+ {
+ // check if ontop of a door bridge ?
+ ms->areanum = BotFuzzyPointReachabilityArea(ms->origin);
+ // if not in a reachability area
+ if (!AAS_AreaReachability(ms->areanum))
+ {
+ result->blocked = qtrue;
+ result->blockentity = ent;
+ result->flags |= MOVERESULT_ONTOPOFOBSTACLE;
+ return;
+ } //end if
+ } //end else if
+ else
+ {
+ result->blocked = qtrue;
+ result->blockentity = ent;
+ result->flags |= MOVERESULT_ONTOPOFOBSTACLE;
+ return;
+ } //end else
+ } //end if
+ } //end if
+ } //end if
+ //if swimming
+ if (AAS_Swimming(ms->origin)) ms->moveflags |= MFL_SWIMMING;
+ //if against a ladder
+ if (AAS_AgainstLadder(ms->origin)) ms->moveflags |= MFL_AGAINSTLADDER;
+ //if the bot is on the ground, swimming or against a ladder
+ if (ms->moveflags & (MFL_ONGROUND|MFL_SWIMMING|MFL_AGAINSTLADDER))
+ {
+ //botimport.Print(PRT_MESSAGE, "%s: onground, swimming or against ladder\n", ClientName(ms->entitynum-1));
+ //
+ AAS_ReachabilityFromNum(ms->lastreachnum, &lastreach);
+ //reachability area the bot is in
+ //ms->areanum = BotReachabilityArea(ms->origin, ((lastreach.traveltype & TRAVELTYPE_MASK) != TRAVEL_ELEVATOR));
+ ms->areanum = BotFuzzyPointReachabilityArea(ms->origin);
+ //
+ if ( !ms->areanum )
+ {
+ result->failure = qtrue;
+ result->blocked = qtrue;
+ result->blockentity = 0;
+ result->type = RESULTTYPE_INSOLIDAREA;
+ return;
+ } //end if
+ //if the bot is in the goal area
+ if (ms->areanum == goal->areanum)
+ {
+ *result = BotMoveInGoalArea(ms, goal);
+ return;
+ } //end if
+ //assume we can use the reachability from the last frame
+ reachnum = ms->lastreachnum;
+ //if there is a last reachability
+ if (reachnum)
+ {
+ AAS_ReachabilityFromNum(reachnum, &reach);
+ //check if the reachability is still valid
+ if (!(AAS_TravelFlagForType(reach.traveltype) & travelflags))
+ {
+ reachnum = 0;
+ } //end if
+ //special grapple hook case
+ else if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_GRAPPLEHOOK)
+ {
+ if (ms->reachability_time < AAS_Time() ||
+ (ms->moveflags & MFL_GRAPPLERESET))
+ {
+ reachnum = 0;
+ } //end if
+ } //end if
+ //special elevator case
+ else if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_ELEVATOR ||
+ (reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_FUNCBOB)
+ {
+ if ((result->flags & MOVERESULT_ONTOPOF_FUNCBOB) ||
+ (result->flags & MOVERESULT_ONTOPOF_FUNCBOB))
+ {
+ ms->reachability_time = AAS_Time() + 5;
+ } //end if
+ //if the bot was going for an elevator and reached the reachability area
+ if (ms->areanum == reach.areanum ||
+ ms->reachability_time < AAS_Time())
+ {
+ reachnum = 0;
+ } //end if
+ } //end if
+ else
+ {
+#ifdef DEBUG
+ if (bot_developer)
+ {
+ if (ms->reachability_time < AAS_Time())
+ {
+ botimport.Print(PRT_MESSAGE, "client %d: reachability timeout in ", ms->client);
+ AAS_PrintTravelType(reach.traveltype & TRAVELTYPE_MASK);
+ botimport.Print(PRT_MESSAGE, "\n");
+ } //end if
+ /*
+ if (ms->lastareanum != ms->areanum)
+ {
+ botimport.Print(PRT_MESSAGE, "changed from area %d to %d\n", ms->lastareanum, ms->areanum);
+ } //end if*/
+ } //end if
+#endif //DEBUG
+ //if the goal area changed or the reachability timed out
+ //or the area changed
+ if (ms->lastgoalareanum != goal->areanum ||
+ ms->reachability_time < AAS_Time() ||
+ ms->lastareanum != ms->areanum)
+ {
+ reachnum = 0;
+ //botimport.Print(PRT_MESSAGE, "area change or timeout\n");
+ } //end else if
+ } //end else
+ } //end if
+ resultflags = 0;
+ //if the bot needs a new reachability
+ if (!reachnum)
+ {
+ //if the area has no reachability links
+ if (!AAS_AreaReachability(ms->areanum))
+ {
+#ifdef DEBUG
+ if (bot_developer)
+ {
+ botimport.Print(PRT_MESSAGE, "area %d no reachability\n", ms->areanum);
+ } //end if
+#endif //DEBUG
+ } //end if
+ //get a new reachability leading towards the goal
+ reachnum = BotGetReachabilityToGoal(ms->origin, ms->areanum,
+ ms->lastgoalareanum, ms->lastareanum,
+ ms->avoidreach, ms->avoidreachtimes, ms->avoidreachtries,
+ goal, travelflags, travelflags,
+ ms->avoidspots, ms->numavoidspots, &resultflags);
+ //the area number the reachability starts in
+ ms->reachareanum = ms->areanum;
+ //reset some state variables
+ ms->jumpreach = 0; //for TRAVEL_JUMP
+ ms->moveflags &= ~MFL_GRAPPLERESET; //for TRAVEL_GRAPPLEHOOK
+ //if there is a reachability to the goal
+ if (reachnum)
+ {
+ AAS_ReachabilityFromNum(reachnum, &reach);
+ //set a timeout for this reachability
+ ms->reachability_time = AAS_Time() + BotReachabilityTime(&reach);
+ //
+#ifdef AVOIDREACH
+ //add the reachability to the reachabilities to avoid for a while
+ BotAddToAvoidReach(ms, reachnum, AVOIDREACH_TIME);
+#endif //AVOIDREACH
+ } //end if
+#ifdef DEBUG
+
+ else if (bot_developer)
+ {
+ botimport.Print(PRT_MESSAGE, "goal not reachable\n");
+ Com_Memset(&reach, 0, sizeof(aas_reachability_t)); //make compiler happy
+ } //end else
+ if (bot_developer)
+ {
+ //if still going for the same goal
+ if (ms->lastgoalareanum == goal->areanum)
+ {
+ if (ms->lastareanum == reach.areanum)
+ {
+ botimport.Print(PRT_MESSAGE, "same goal, going back to previous area\n");
+ } //end if
+ } //end if
+ } //end if
+#endif //DEBUG
+ } //end else
+ //
+ ms->lastreachnum = reachnum;
+ ms->lastgoalareanum = goal->areanum;
+ ms->lastareanum = ms->areanum;
+ //if the bot has a reachability
+ if (reachnum)
+ {
+ //get the reachability from the number
+ AAS_ReachabilityFromNum(reachnum, &reach);
+ result->traveltype = reach.traveltype;
+ //
+#ifdef DEBUG_AI_MOVE
+ AAS_ClearShownDebugLines();
+ AAS_PrintTravelType(reach.traveltype & TRAVELTYPE_MASK);
+ AAS_ShowReachability(&reach);
+#endif //DEBUG_AI_MOVE
+ //
+#ifdef DEBUG
+ //botimport.Print(PRT_MESSAGE, "client %d: ", ms->client);
+ //AAS_PrintTravelType(reach.traveltype);
+ //botimport.Print(PRT_MESSAGE, "\n");
+#endif //DEBUG
+ switch(reach.traveltype & TRAVELTYPE_MASK)
+ {
+ case TRAVEL_WALK: *result = BotTravel_Walk(ms, &reach); break;
+ case TRAVEL_CROUCH: *result = BotTravel_Crouch(ms, &reach); break;
+ case TRAVEL_BARRIERJUMP: *result = BotTravel_BarrierJump(ms, &reach); break;
+ case TRAVEL_LADDER: *result = BotTravel_Ladder(ms, &reach); break;
+ case TRAVEL_WALKOFFLEDGE: *result = BotTravel_WalkOffLedge(ms, &reach); break;
+ case TRAVEL_JUMP: *result = BotTravel_Jump(ms, &reach); break;
+ case TRAVEL_SWIM: *result = BotTravel_Swim(ms, &reach); break;
+ case TRAVEL_WATERJUMP: *result = BotTravel_WaterJump(ms, &reach); break;
+ case TRAVEL_TELEPORT: *result = BotTravel_Teleport(ms, &reach); break;
+ case TRAVEL_ELEVATOR: *result = BotTravel_Elevator(ms, &reach); break;
+ case TRAVEL_GRAPPLEHOOK: *result = BotTravel_Grapple(ms, &reach); break;
+ case TRAVEL_ROCKETJUMP: *result = BotTravel_RocketJump(ms, &reach); break;
+ case TRAVEL_BFGJUMP: *result = BotTravel_BFGJump(ms, &reach); break;
+ case TRAVEL_JUMPPAD: *result = BotTravel_JumpPad(ms, &reach); break;
+ case TRAVEL_FUNCBOB: *result = BotTravel_FuncBobbing(ms, &reach); break;
+ default:
+ {
+ botimport.Print(PRT_FATAL, "travel type %d not implemented yet\n", (reach.traveltype & TRAVELTYPE_MASK));
+ break;
+ } //end case
+ } //end switch
+ result->traveltype = reach.traveltype;
+ result->flags |= resultflags;
+ } //end if
+ else
+ {
+ result->failure = qtrue;
+ result->flags |= resultflags;
+ Com_Memset(&reach, 0, sizeof(aas_reachability_t));
+ } //end else
+#ifdef DEBUG
+ if (bot_developer)
+ {
+ if (result->failure)
+ {
+ botimport.Print(PRT_MESSAGE, "client %d: movement failure in ", ms->client);
+ AAS_PrintTravelType(reach.traveltype & TRAVELTYPE_MASK);
+ botimport.Print(PRT_MESSAGE, "\n");
+ } //end if
+ } //end if
+#endif //DEBUG
+ } //end if
+ else
+ {
+ int i, numareas, areas[16];
+ vec3_t end;
+
+ //special handling of jump pads when the bot uses a jump pad without knowing it
+ foundjumppad = qfalse;
+ VectorMA(ms->origin, -2 * ms->thinktime, ms->velocity, end);
+ numareas = AAS_TraceAreas(ms->origin, end, areas, NULL, 16);
+ for (i = numareas-1; i >= 0; i--)
+ {
+ if (AAS_AreaJumpPad(areas[i]))
+ {
+ //botimport.Print(PRT_MESSAGE, "client %d used a jumppad without knowing, area %d\n", ms->client, areas[i]);
+ foundjumppad = qtrue;
+ lastreachnum = BotGetReachabilityToGoal(end, areas[i],
+ ms->lastgoalareanum, ms->lastareanum,
+ ms->avoidreach, ms->avoidreachtimes, ms->avoidreachtries,
+ goal, travelflags, TFL_JUMPPAD, ms->avoidspots, ms->numavoidspots, NULL);
+ if (lastreachnum)
+ {
+ ms->lastreachnum = lastreachnum;
+ ms->lastareanum = areas[i];
+ //botimport.Print(PRT_MESSAGE, "found jumppad reachability\n");
+ break;
+ } //end if
+ else
+ {
+ for (lastreachnum = AAS_NextAreaReachability(areas[i], 0); lastreachnum;
+ lastreachnum = AAS_NextAreaReachability(areas[i], lastreachnum))
+ {
+ //get the reachability from the number
+ AAS_ReachabilityFromNum(lastreachnum, &reach);
+ if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_JUMPPAD)
+ {
+ ms->lastreachnum = lastreachnum;
+ ms->lastareanum = areas[i];
+ //botimport.Print(PRT_MESSAGE, "found jumppad reachability hard!!\n");
+ break;
+ } //end if
+ } //end for
+ if (lastreachnum) break;
+ } //end else
+ } //end if
+ } //end for
+ if (bot_developer)
+ {
+ //if a jumppad is found with the trace but no reachability is found
+ if (foundjumppad && !ms->lastreachnum)
+ {
+ botimport.Print(PRT_MESSAGE, "client %d didn't find jumppad reachability\n", ms->client);
+ } //end if
+ } //end if
+ //
+ if (ms->lastreachnum)
+ {
+ //botimport.Print(PRT_MESSAGE, "%s: NOT onground, swimming or against ladder\n", ClientName(ms->entitynum-1));
+ AAS_ReachabilityFromNum(ms->lastreachnum, &reach);
+ result->traveltype = reach.traveltype;
+#ifdef DEBUG
+ //botimport.Print(PRT_MESSAGE, "client %d finish: ", ms->client);
+ //AAS_PrintTravelType(reach.traveltype & TRAVELTYPE_MASK);
+ //botimport.Print(PRT_MESSAGE, "\n");
+#endif //DEBUG
+ //
+ switch(reach.traveltype & TRAVELTYPE_MASK)
+ {
+ case TRAVEL_WALK: *result = BotTravel_Walk(ms, &reach); break;//BotFinishTravel_Walk(ms, &reach); break;
+ case TRAVEL_CROUCH: /*do nothing*/ break;
+ case TRAVEL_BARRIERJUMP: *result = BotFinishTravel_BarrierJump(ms, &reach); break;
+ case TRAVEL_LADDER: *result = BotTravel_Ladder(ms, &reach); break;
+ case TRAVEL_WALKOFFLEDGE: *result = BotFinishTravel_WalkOffLedge(ms, &reach); break;
+ case TRAVEL_JUMP: *result = BotFinishTravel_Jump(ms, &reach); break;
+ case TRAVEL_SWIM: *result = BotTravel_Swim(ms, &reach); break;
+ case TRAVEL_WATERJUMP: *result = BotFinishTravel_WaterJump(ms, &reach); break;
+ case TRAVEL_TELEPORT: /*do nothing*/ break;
+ case TRAVEL_ELEVATOR: *result = BotFinishTravel_Elevator(ms, &reach); break;
+ case TRAVEL_GRAPPLEHOOK: *result = BotTravel_Grapple(ms, &reach); break;
+ case TRAVEL_ROCKETJUMP:
+ case TRAVEL_BFGJUMP: *result = BotFinishTravel_WeaponJump(ms, &reach); break;
+ case TRAVEL_JUMPPAD: *result = BotFinishTravel_JumpPad(ms, &reach); break;
+ case TRAVEL_FUNCBOB: *result = BotFinishTravel_FuncBobbing(ms, &reach); break;
+ default:
+ {
+ botimport.Print(PRT_FATAL, "(last) travel type %d not implemented yet\n", (reach.traveltype & TRAVELTYPE_MASK));
+ break;
+ } //end case
+ } //end switch
+ result->traveltype = reach.traveltype;
+#ifdef DEBUG
+ if (bot_developer)
+ {
+ if (result->failure)
+ {
+ botimport.Print(PRT_MESSAGE, "client %d: movement failure in finish ", ms->client);
+ AAS_PrintTravelType(reach.traveltype & TRAVELTYPE_MASK);
+ botimport.Print(PRT_MESSAGE, "\n");
+ } //end if
+ } //end if
+#endif //DEBUG
+ } //end if
+ } //end else
+ //FIXME: is it right to do this here?
+ if (result->blocked) ms->reachability_time -= 10 * ms->thinktime;
+ //copy the last origin
+ VectorCopy(ms->origin, ms->lastorigin);
+ //return the movement result
+ return;
+} //end of the function BotMoveToGoal
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotResetAvoidReach(int movestate)
+{
+ bot_movestate_t *ms;
+
+ ms = BotMoveStateFromHandle(movestate);
+ if (!ms) return;
+ Com_Memset(ms->avoidreach, 0, MAX_AVOIDREACH * sizeof(int));
+ Com_Memset(ms->avoidreachtimes, 0, MAX_AVOIDREACH * sizeof(float));
+ Com_Memset(ms->avoidreachtries, 0, MAX_AVOIDREACH * sizeof(int));
+} //end of the function BotResetAvoidReach
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotResetLastAvoidReach(int movestate)
+{
+ int i, latest;
+ float latesttime;
+ bot_movestate_t *ms;
+
+ ms = BotMoveStateFromHandle(movestate);
+ if (!ms) return;
+ latesttime = 0;
+ latest = 0;
+ for (i = 0; i < MAX_AVOIDREACH; i++)
+ {
+ if (ms->avoidreachtimes[i] > latesttime)
+ {
+ latesttime = ms->avoidreachtimes[i];
+ latest = i;
+ } //end if
+ } //end for
+ if (latesttime)
+ {
+ ms->avoidreachtimes[latest] = 0;
+ if (ms->avoidreachtries[i] > 0) ms->avoidreachtries[latest]--;
+ } //end if
+} //end of the function BotResetLastAvoidReach
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotResetMoveState(int movestate)
+{
+ bot_movestate_t *ms;
+
+ ms = BotMoveStateFromHandle(movestate);
+ if (!ms) return;
+ Com_Memset(ms, 0, sizeof(bot_movestate_t));
+} //end of the function BotResetMoveState
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotSetupMoveAI(void)
+{
+ BotSetBrushModelTypes();
+ sv_maxstep = LibVar("sv_step", "18");
+ sv_maxbarrier = LibVar("sv_maxbarrier", "32");
+ sv_gravity = LibVar("sv_gravity", "800");
+ weapindex_rocketlauncher = LibVar("weapindex_rocketlauncher", "5");
+ weapindex_bfg10k = LibVar("weapindex_bfg10k", "9");
+ weapindex_grapple = LibVar("weapindex_grapple", "10");
+ entitytypemissile = LibVar("entitytypemissile", "3");
+ offhandgrapple = LibVar("offhandgrapple", "0");
+ cmd_grappleon = LibVar("cmd_grappleon", "grappleon");
+ cmd_grappleoff = LibVar("cmd_grappleoff", "grappleoff");
+ return BLERR_NOERROR;
+} //end of the function BotSetupMoveAI
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotShutdownMoveAI(void)
+{
+ int i;
+
+ for (i = 1; i <= MAX_CLIENTS; i++)
+ {
+ if (botmovestates[i])
+ {
+ FreeMemory(botmovestates[i]);
+ botmovestates[i] = NULL;
+ } //end if
+ } //end for
+} //end of the function BotShutdownMoveAI
+
+
diff --git a/code/botlib/be_ai_weap.c b/code/botlib/be_ai_weap.c
new file mode 100755
index 0000000..435292d
--- /dev/null
+++ b/code/botlib/be_ai_weap.c
@@ -0,0 +1,543 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_ai_weap.c
+ *
+ * desc: weapon AI
+ *
+ * $Archive: /MissionPack/code/botlib/be_ai_weap.c $
+ *
+ *****************************************************************************/
+
+#include "../game/q_shared.h"
+#include "l_libvar.h"
+#include "l_log.h"
+#include "l_memory.h"
+#include "l_utils.h"
+#include "l_script.h"
+#include "l_precomp.h"
+#include "l_struct.h"
+#include "aasfile.h"
+#include "../game/botlib.h"
+#include "../game/be_aas.h"
+#include "be_aas_funcs.h"
+#include "be_interface.h"
+#include "be_ai_weight.h" //fuzzy weights
+#include "../game/be_ai_weap.h"
+
+//#define DEBUG_AI_WEAP
+
+//structure field offsets
+#define WEAPON_OFS(x) (int)&(((weaponinfo_t *)0)->x)
+#define PROJECTILE_OFS(x) (int)&(((projectileinfo_t *)0)->x)
+
+//weapon definition // bk001212 - static
+static fielddef_t weaponinfo_fields[] =
+{
+{"number", WEAPON_OFS(number), FT_INT}, //weapon number
+{"name", WEAPON_OFS(name), FT_STRING}, //name of the weapon
+{"level", WEAPON_OFS(level), FT_INT},
+{"model", WEAPON_OFS(model), FT_STRING}, //model of the weapon
+{"weaponindex", WEAPON_OFS(weaponindex), FT_INT}, //index of weapon in inventory
+{"flags", WEAPON_OFS(flags), FT_INT}, //special flags
+{"projectile", WEAPON_OFS(projectile), FT_STRING}, //projectile used by the weapon
+{"numprojectiles", WEAPON_OFS(numprojectiles), FT_INT}, //number of projectiles
+{"hspread", WEAPON_OFS(hspread), FT_FLOAT}, //horizontal spread of projectiles (degrees from middle)
+{"vspread", WEAPON_OFS(vspread), FT_FLOAT}, //vertical spread of projectiles (degrees from middle)
+{"speed", WEAPON_OFS(speed), FT_FLOAT}, //speed of the projectile (0 = instant hit)
+{"acceleration", WEAPON_OFS(acceleration), FT_FLOAT}, //"acceleration" * time (in seconds) + "speed" = projectile speed
+{"recoil", WEAPON_OFS(recoil), FT_FLOAT|FT_ARRAY, 3}, //amount of recoil the player gets from the weapon
+{"offset", WEAPON_OFS(offset), FT_FLOAT|FT_ARRAY, 3}, //projectile start offset relative to eye and view angles
+{"angleoffset", WEAPON_OFS(angleoffset), FT_FLOAT|FT_ARRAY, 3},//offset of the shoot angles relative to the view angles
+{"extrazvelocity", WEAPON_OFS(extrazvelocity), FT_FLOAT},//extra z velocity the projectile gets
+{"ammoamount", WEAPON_OFS(ammoamount), FT_INT}, //ammo amount used per shot
+{"ammoindex", WEAPON_OFS(ammoindex), FT_INT}, //index of ammo in inventory
+{"activate", WEAPON_OFS(activate), FT_FLOAT}, //time it takes to select the weapon
+{"reload", WEAPON_OFS(reload), FT_FLOAT}, //time it takes to reload the weapon
+{"spinup", WEAPON_OFS(spinup), FT_FLOAT}, //time it takes before first shot
+{"spindown", WEAPON_OFS(spindown), FT_FLOAT}, //time it takes before weapon stops firing
+{NULL, 0, 0, 0}
+};
+
+//projectile definition
+static fielddef_t projectileinfo_fields[] =
+{
+{"name", PROJECTILE_OFS(name), FT_STRING}, //name of the projectile
+{"model", WEAPON_OFS(model), FT_STRING}, //model of the projectile
+{"flags", PROJECTILE_OFS(flags), FT_INT}, //special flags
+{"gravity", PROJECTILE_OFS(gravity), FT_FLOAT}, //amount of gravity applied to the projectile [0,1]
+{"damage", PROJECTILE_OFS(damage), FT_INT}, //damage of the projectile
+{"radius", PROJECTILE_OFS(radius), FT_FLOAT}, //radius of damage
+{"visdamage", PROJECTILE_OFS(visdamage), FT_INT}, //damage of the projectile to visible entities
+{"damagetype", PROJECTILE_OFS(damagetype), FT_INT}, //type of damage (combination of the DAMAGETYPE_? flags)
+{"healthinc", PROJECTILE_OFS(healthinc), FT_INT}, //health increase the owner gets
+{"push", PROJECTILE_OFS(push), FT_FLOAT}, //amount a player is pushed away from the projectile impact
+{"detonation", PROJECTILE_OFS(detonation), FT_FLOAT}, //time before projectile explodes after fire pressed
+{"bounce", PROJECTILE_OFS(bounce), FT_FLOAT}, //amount the projectile bounces
+{"bouncefric", PROJECTILE_OFS(bouncefric), FT_FLOAT}, //amount the bounce decreases per bounce
+{"bouncestop", PROJECTILE_OFS(bouncestop), FT_FLOAT}, //minimum bounce value before bouncing stops
+//recurive projectile definition??
+{NULL, 0, 0, 0}
+};
+
+static structdef_t weaponinfo_struct =
+{
+ sizeof(weaponinfo_t), weaponinfo_fields
+};
+static structdef_t projectileinfo_struct =
+{
+ sizeof(projectileinfo_t), projectileinfo_fields
+};
+
+//weapon configuration: set of weapons with projectiles
+typedef struct weaponconfig_s
+{
+ int numweapons;
+ int numprojectiles;
+ projectileinfo_t *projectileinfo;
+ weaponinfo_t *weaponinfo;
+} weaponconfig_t;
+
+//the bot weapon state
+typedef struct bot_weaponstate_s
+{
+ struct weightconfig_s *weaponweightconfig; //weapon weight configuration
+ int *weaponweightindex; //weapon weight index
+} bot_weaponstate_t;
+
+static bot_weaponstate_t *botweaponstates[MAX_CLIENTS+1];
+static weaponconfig_t *weaponconfig;
+
+//========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//========================================================================
+int BotValidWeaponNumber(int weaponnum)
+{
+ if (weaponnum <= 0 || weaponnum > weaponconfig->numweapons)
+ {
+ botimport.Print(PRT_ERROR, "weapon number out of range\n");
+ return qfalse;
+ } //end if
+ return qtrue;
+} //end of the function BotValidWeaponNumber
+//========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//========================================================================
+bot_weaponstate_t *BotWeaponStateFromHandle(int handle)
+{
+ if (handle <= 0 || handle > MAX_CLIENTS)
+ {
+ botimport.Print(PRT_FATAL, "move state handle %d out of range\n", handle);
+ return NULL;
+ } //end if
+ if (!botweaponstates[handle])
+ {
+ botimport.Print(PRT_FATAL, "invalid move state %d\n", handle);
+ return NULL;
+ } //end if
+ return botweaponstates[handle];
+} //end of the function BotWeaponStateFromHandle
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+#ifdef DEBUG_AI_WEAP
+void DumpWeaponConfig(weaponconfig_t *wc)
+{
+ FILE *fp;
+ int i;
+
+ fp = Log_FileStruct();
+ if (!fp) return;
+ for (i = 0; i < wc->numprojectiles; i++)
+ {
+ WriteStructure(fp, &projectileinfo_struct, (char *) &wc->projectileinfo[i]);
+ Log_Flush();
+ } //end for
+ for (i = 0; i < wc->numweapons; i++)
+ {
+ WriteStructure(fp, &weaponinfo_struct, (char *) &wc->weaponinfo[i]);
+ Log_Flush();
+ } //end for
+} //end of the function DumpWeaponConfig
+#endif //DEBUG_AI_WEAP
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+weaponconfig_t *LoadWeaponConfig(char *filename)
+{
+ int max_weaponinfo, max_projectileinfo;
+ token_t token;
+ char path[MAX_PATH];
+ int i, j;
+ source_t *source;
+ weaponconfig_t *wc;
+ weaponinfo_t weaponinfo;
+
+ max_weaponinfo = (int) LibVarValue("max_weaponinfo", "32");
+ if (max_weaponinfo < 0)
+ {
+ botimport.Print(PRT_ERROR, "max_weaponinfo = %d\n", max_weaponinfo);
+ max_weaponinfo = 32;
+ LibVarSet("max_weaponinfo", "32");
+ } //end if
+ max_projectileinfo = (int) LibVarValue("max_projectileinfo", "32");
+ if (max_projectileinfo < 0)
+ {
+ botimport.Print(PRT_ERROR, "max_projectileinfo = %d\n", max_projectileinfo);
+ max_projectileinfo = 32;
+ LibVarSet("max_projectileinfo", "32");
+ } //end if
+ strncpy(path, filename, MAX_PATH);
+ PC_SetBaseFolder(BOTFILESBASEFOLDER);
+ source = LoadSourceFile(path);
+ if (!source)
+ {
+ botimport.Print(PRT_ERROR, "counldn't load %s\n", path);
+ return NULL;
+ } //end if
+ //initialize weapon config
+ wc = (weaponconfig_t *) GetClearedHunkMemory(sizeof(weaponconfig_t) +
+ max_weaponinfo * sizeof(weaponinfo_t) +
+ max_projectileinfo * sizeof(projectileinfo_t));
+ wc->weaponinfo = (weaponinfo_t *) ((char *) wc + sizeof(weaponconfig_t));
+ wc->projectileinfo = (projectileinfo_t *) ((char *) wc->weaponinfo +
+ max_weaponinfo * sizeof(weaponinfo_t));
+ wc->numweapons = max_weaponinfo;
+ wc->numprojectiles = 0;
+ //parse the source file
+ while(PC_ReadToken(source, &token))
+ {
+ if (!strcmp(token.string, "weaponinfo"))
+ {
+ Com_Memset(&weaponinfo, 0, sizeof(weaponinfo_t));
+ if (!ReadStructure(source, &weaponinfo_struct, (char *) &weaponinfo))
+ {
+ FreeMemory(wc);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ if (weaponinfo.number < 0 || weaponinfo.number >= max_weaponinfo)
+ {
+ botimport.Print(PRT_ERROR, "weapon info number %d out of range in %s\n", weaponinfo.number, path);
+ FreeMemory(wc);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ Com_Memcpy(&wc->weaponinfo[weaponinfo.number], &weaponinfo, sizeof(weaponinfo_t));
+ wc->weaponinfo[weaponinfo.number].valid = qtrue;
+ } //end if
+ else if (!strcmp(token.string, "projectileinfo"))
+ {
+ if (wc->numprojectiles >= max_projectileinfo)
+ {
+ botimport.Print(PRT_ERROR, "more than %d projectiles defined in %s\n", max_projectileinfo, path);
+ FreeMemory(wc);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ Com_Memset(&wc->projectileinfo[wc->numprojectiles], 0, sizeof(projectileinfo_t));
+ if (!ReadStructure(source, &projectileinfo_struct, (char *) &wc->projectileinfo[wc->numprojectiles]))
+ {
+ FreeMemory(wc);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ wc->numprojectiles++;
+ } //end if
+ else
+ {
+ botimport.Print(PRT_ERROR, "unknown definition %s in %s\n", token.string, path);
+ FreeMemory(wc);
+ FreeSource(source);
+ return NULL;
+ } //end else
+ } //end while
+ FreeSource(source);
+ //fix up weapons
+ for (i = 0; i < wc->numweapons; i++)
+ {
+ if (!wc->weaponinfo[i].valid) continue;
+ if (!wc->weaponinfo[i].name[0])
+ {
+ botimport.Print(PRT_ERROR, "weapon %d has no name in %s\n", i, path);
+ FreeMemory(wc);
+ return NULL;
+ } //end if
+ if (!wc->weaponinfo[i].projectile[0])
+ {
+ botimport.Print(PRT_ERROR, "weapon %s has no projectile in %s\n", wc->weaponinfo[i].name, path);
+ FreeMemory(wc);
+ return NULL;
+ } //end if
+ //find the projectile info and copy it to the weapon info
+ for (j = 0; j < wc->numprojectiles; j++)
+ {
+ if (!strcmp(wc->projectileinfo[j].name, wc->weaponinfo[i].projectile))
+ {
+ Com_Memcpy(&wc->weaponinfo[i].proj, &wc->projectileinfo[j], sizeof(projectileinfo_t));
+ break;
+ } //end if
+ } //end for
+ if (j == wc->numprojectiles)
+ {
+ botimport.Print(PRT_ERROR, "weapon %s uses undefined projectile in %s\n", wc->weaponinfo[i].name, path);
+ FreeMemory(wc);
+ return NULL;
+ } //end if
+ } //end for
+ if (!wc->numweapons) botimport.Print(PRT_WARNING, "no weapon info loaded\n");
+ botimport.Print(PRT_MESSAGE, "loaded %s\n", path);
+ return wc;
+} //end of the function LoadWeaponConfig
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int *WeaponWeightIndex(weightconfig_t *wwc, weaponconfig_t *wc)
+{
+ int *index, i;
+
+ //initialize item weight index
+ index = (int *) GetClearedMemory(sizeof(int) * wc->numweapons);
+
+ for (i = 0; i < wc->numweapons; i++)
+ {
+ index[i] = FindFuzzyWeight(wwc, wc->weaponinfo[i].name);
+ } //end for
+ return index;
+} //end of the function WeaponWeightIndex
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotFreeWeaponWeights(int weaponstate)
+{
+ bot_weaponstate_t *ws;
+
+ ws = BotWeaponStateFromHandle(weaponstate);
+ if (!ws) return;
+ if (ws->weaponweightconfig) FreeWeightConfig(ws->weaponweightconfig);
+ if (ws->weaponweightindex) FreeMemory(ws->weaponweightindex);
+} //end of the function BotFreeWeaponWeights
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotLoadWeaponWeights(int weaponstate, char *filename)
+{
+ bot_weaponstate_t *ws;
+
+ ws = BotWeaponStateFromHandle(weaponstate);
+ if (!ws) return BLERR_CANNOTLOADWEAPONWEIGHTS;
+ BotFreeWeaponWeights(weaponstate);
+ //
+ ws->weaponweightconfig = ReadWeightConfig(filename);
+ if (!ws->weaponweightconfig)
+ {
+ botimport.Print(PRT_FATAL, "couldn't load weapon config %s\n", filename);
+ return BLERR_CANNOTLOADWEAPONWEIGHTS;
+ } //end if
+ if (!weaponconfig) return BLERR_CANNOTLOADWEAPONCONFIG;
+ ws->weaponweightindex = WeaponWeightIndex(ws->weaponweightconfig, weaponconfig);
+ return BLERR_NOERROR;
+} //end of the function BotLoadWeaponWeights
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotGetWeaponInfo(int weaponstate, int weapon, weaponinfo_t *weaponinfo)
+{
+ bot_weaponstate_t *ws;
+
+ if (!BotValidWeaponNumber(weapon)) return;
+ ws = BotWeaponStateFromHandle(weaponstate);
+ if (!ws) return;
+ if (!weaponconfig) return;
+ Com_Memcpy(weaponinfo, &weaponconfig->weaponinfo[weapon], sizeof(weaponinfo_t));
+} //end of the function BotGetWeaponInfo
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotChooseBestFightWeapon(int weaponstate, int *inventory)
+{
+ int i, index, bestweapon;
+ float weight, bestweight;
+ weaponconfig_t *wc;
+ bot_weaponstate_t *ws;
+
+ ws = BotWeaponStateFromHandle(weaponstate);
+ if (!ws) return 0;
+ wc = weaponconfig;
+ if (!weaponconfig) return 0;
+
+ //if the bot has no weapon weight configuration
+ if (!ws->weaponweightconfig) return 0;
+
+ bestweight = 0;
+ bestweapon = 0;
+ for (i = 0; i < wc->numweapons; i++)
+ {
+ if (!wc->weaponinfo[i].valid) continue;
+ index = ws->weaponweightindex[i];
+ if (index < 0) continue;
+ weight = FuzzyWeight(inventory, ws->weaponweightconfig, index);
+ if (weight > bestweight)
+ {
+ bestweight = weight;
+ bestweapon = i;
+ } //end if
+ } //end for
+ return bestweapon;
+} //end of the function BotChooseBestFightWeapon
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotResetWeaponState(int weaponstate)
+{
+ struct weightconfig_s *weaponweightconfig;
+ int *weaponweightindex;
+ bot_weaponstate_t *ws;
+
+ ws = BotWeaponStateFromHandle(weaponstate);
+ if (!ws) return;
+ weaponweightconfig = ws->weaponweightconfig;
+ weaponweightindex = ws->weaponweightindex;
+
+ //Com_Memset(ws, 0, sizeof(bot_weaponstate_t));
+ ws->weaponweightconfig = weaponweightconfig;
+ ws->weaponweightindex = weaponweightindex;
+} //end of the function BotResetWeaponState
+//========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//========================================================================
+int BotAllocWeaponState(void)
+{
+ int i;
+
+ for (i = 1; i <= MAX_CLIENTS; i++)
+ {
+ if (!botweaponstates[i])
+ {
+ botweaponstates[i] = GetClearedMemory(sizeof(bot_weaponstate_t));
+ return i;
+ } //end if
+ } //end for
+ return 0;
+} //end of the function BotAllocWeaponState
+//========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//========================================================================
+void BotFreeWeaponState(int handle)
+{
+ if (handle <= 0 || handle > MAX_CLIENTS)
+ {
+ botimport.Print(PRT_FATAL, "move state handle %d out of range\n", handle);
+ return;
+ } //end if
+ if (!botweaponstates[handle])
+ {
+ botimport.Print(PRT_FATAL, "invalid move state %d\n", handle);
+ return;
+ } //end if
+ BotFreeWeaponWeights(handle);
+ FreeMemory(botweaponstates[handle]);
+ botweaponstates[handle] = NULL;
+} //end of the function BotFreeWeaponState
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotSetupWeaponAI(void)
+{
+ char *file;
+
+ file = LibVarString("weaponconfig", "weapons.c");
+ weaponconfig = LoadWeaponConfig(file);
+ if (!weaponconfig)
+ {
+ botimport.Print(PRT_FATAL, "couldn't load the weapon config\n");
+ return BLERR_CANNOTLOADWEAPONCONFIG;
+ } //end if
+
+#ifdef DEBUG_AI_WEAP
+ DumpWeaponConfig(weaponconfig);
+#endif //DEBUG_AI_WEAP
+ //
+ return BLERR_NOERROR;
+} //end of the function BotSetupWeaponAI
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotShutdownWeaponAI(void)
+{
+ int i;
+
+ if (weaponconfig) FreeMemory(weaponconfig);
+ weaponconfig = NULL;
+
+ for (i = 1; i <= MAX_CLIENTS; i++)
+ {
+ if (botweaponstates[i])
+ {
+ BotFreeWeaponState(i);
+ } //end if
+ } //end for
+} //end of the function BotShutdownWeaponAI
+
diff --git a/code/botlib/be_ai_weight.c b/code/botlib/be_ai_weight.c
new file mode 100755
index 0000000..c501593
--- /dev/null
+++ b/code/botlib/be_ai_weight.c
@@ -0,0 +1,912 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_ai_weight.c
+ *
+ * desc: fuzzy logic
+ *
+ * $Archive: /MissionPack/code/botlib/be_ai_weight.c $
+ *
+ *****************************************************************************/
+
+#include "../game/q_shared.h"
+#include "l_memory.h"
+#include "l_log.h"
+#include "l_utils.h"
+#include "l_script.h"
+#include "l_precomp.h"
+#include "l_struct.h"
+#include "l_libvar.h"
+#include "aasfile.h"
+#include "../game/botlib.h"
+#include "../game/be_aas.h"
+#include "be_aas_funcs.h"
+#include "be_interface.h"
+#include "be_ai_weight.h"
+
+#define MAX_INVENTORYVALUE 999999
+#define EVALUATERECURSIVELY
+
+#define MAX_WEIGHT_FILES 128
+weightconfig_t *weightFileList[MAX_WEIGHT_FILES];
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int ReadValue(source_t *source, float *value)
+{
+ token_t token;
+
+ if (!PC_ExpectAnyToken(source, &token)) return qfalse;
+ if (!strcmp(token.string, "-"))
+ {
+ SourceWarning(source, "negative value set to zero\n");
+ if (!PC_ExpectTokenType(source, TT_NUMBER, 0, &token)) return qfalse;
+ } //end if
+ if (token.type != TT_NUMBER)
+ {
+ SourceError(source, "invalid return value %s\n", token.string);
+ return qfalse;
+ } //end if
+ *value = token.floatvalue;
+ return qtrue;
+} //end of the function ReadValue
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int ReadFuzzyWeight(source_t *source, fuzzyseperator_t *fs)
+{
+ if (PC_CheckTokenString(source, "balance"))
+ {
+ fs->type = WT_BALANCE;
+ if (!PC_ExpectTokenString(source, "(")) return qfalse;
+ if (!ReadValue(source, &fs->weight)) return qfalse;
+ if (!PC_ExpectTokenString(source, ",")) return qfalse;
+ if (!ReadValue(source, &fs->minweight)) return qfalse;
+ if (!PC_ExpectTokenString(source, ",")) return qfalse;
+ if (!ReadValue(source, &fs->maxweight)) return qfalse;
+ if (!PC_ExpectTokenString(source, ")")) return qfalse;
+ } //end if
+ else
+ {
+ fs->type = 0;
+ if (!ReadValue(source, &fs->weight)) return qfalse;
+ fs->minweight = fs->weight;
+ fs->maxweight = fs->weight;
+ } //end if
+ if (!PC_ExpectTokenString(source, ";")) return qfalse;
+ return qtrue;
+} //end of the function ReadFuzzyWeight
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void FreeFuzzySeperators_r(fuzzyseperator_t *fs)
+{
+ if (!fs) return;
+ if (fs->child) FreeFuzzySeperators_r(fs->child);
+ if (fs->next) FreeFuzzySeperators_r(fs->next);
+ FreeMemory(fs);
+} //end of the function FreeFuzzySeperators
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void FreeWeightConfig2(weightconfig_t *config)
+{
+ int i;
+
+ for (i = 0; i < config->numweights; i++)
+ {
+ FreeFuzzySeperators_r(config->weights[i].firstseperator);
+ if (config->weights[i].name) FreeMemory(config->weights[i].name);
+ } //end for
+ FreeMemory(config);
+} //end of the function FreeWeightConfig2
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void FreeWeightConfig(weightconfig_t *config)
+{
+ if (!LibVarGetValue("bot_reloadcharacters")) return;
+ FreeWeightConfig2(config);
+} //end of the function FreeWeightConfig
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+fuzzyseperator_t *ReadFuzzySeperators_r(source_t *source)
+{
+ int newindent, index, def, founddefault;
+ token_t token;
+ fuzzyseperator_t *fs, *lastfs, *firstfs;
+
+ founddefault = qfalse;
+ firstfs = NULL;
+ lastfs = NULL;
+ if (!PC_ExpectTokenString(source, "(")) return NULL;
+ if (!PC_ExpectTokenType(source, TT_NUMBER, TT_INTEGER, &token)) return NULL;
+ index = token.intvalue;
+ if (!PC_ExpectTokenString(source, ")")) return NULL;
+ if (!PC_ExpectTokenString(source, "{")) return NULL;
+ if (!PC_ExpectAnyToken(source, &token)) return NULL;
+ do
+ {
+ def = !strcmp(token.string, "default");
+ if (def || !strcmp(token.string, "case"))
+ {
+ fs = (fuzzyseperator_t *) GetClearedMemory(sizeof(fuzzyseperator_t));
+ fs->index = index;
+ if (lastfs) lastfs->next = fs;
+ else firstfs = fs;
+ lastfs = fs;
+ if (def)
+ {
+ if (founddefault)
+ {
+ SourceError(source, "switch already has a default\n");
+ FreeFuzzySeperators_r(firstfs);
+ return NULL;
+ } //end if
+ fs->value = MAX_INVENTORYVALUE;
+ founddefault = qtrue;
+ } //end if
+ else
+ {
+ if (!PC_ExpectTokenType(source, TT_NUMBER, TT_INTEGER, &token))
+ {
+ FreeFuzzySeperators_r(firstfs);
+ return NULL;
+ } //end if
+ fs->value = token.intvalue;
+ } //end else
+ if (!PC_ExpectTokenString(source, ":") || !PC_ExpectAnyToken(source, &token))
+ {
+ FreeFuzzySeperators_r(firstfs);
+ return NULL;
+ } //end if
+ newindent = qfalse;
+ if (!strcmp(token.string, "{"))
+ {
+ newindent = qtrue;
+ if (!PC_ExpectAnyToken(source, &token))
+ {
+ FreeFuzzySeperators_r(firstfs);
+ return NULL;
+ } //end if
+ } //end if
+ if (!strcmp(token.string, "return"))
+ {
+ if (!ReadFuzzyWeight(source, fs))
+ {
+ FreeFuzzySeperators_r(firstfs);
+ return NULL;
+ } //end if
+ } //end if
+ else if (!strcmp(token.string, "switch"))
+ {
+ fs->child = ReadFuzzySeperators_r(source);
+ if (!fs->child)
+ {
+ FreeFuzzySeperators_r(firstfs);
+ return NULL;
+ } //end if
+ } //end else if
+ else
+ {
+ SourceError(source, "invalid name %s\n", token.string);
+ return NULL;
+ } //end else
+ if (newindent)
+ {
+ if (!PC_ExpectTokenString(source, "}"))
+ {
+ FreeFuzzySeperators_r(firstfs);
+ return NULL;
+ } //end if
+ } //end if
+ } //end if
+ else
+ {
+ FreeFuzzySeperators_r(firstfs);
+ SourceError(source, "invalid name %s\n", token.string);
+ return NULL;
+ } //end else
+ if (!PC_ExpectAnyToken(source, &token))
+ {
+ FreeFuzzySeperators_r(firstfs);
+ return NULL;
+ } //end if
+ } while(strcmp(token.string, "}"));
+ //
+ if (!founddefault)
+ {
+ SourceWarning(source, "switch without default\n");
+ fs = (fuzzyseperator_t *) GetClearedMemory(sizeof(fuzzyseperator_t));
+ fs->index = index;
+ fs->value = MAX_INVENTORYVALUE;
+ fs->weight = 0;
+ fs->next = NULL;
+ fs->child = NULL;
+ if (lastfs) lastfs->next = fs;
+ else firstfs = fs;
+ lastfs = fs;
+ } //end if
+ //
+ return firstfs;
+} //end of the function ReadFuzzySeperators_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+weightconfig_t *ReadWeightConfig(char *filename)
+{
+ int newindent, avail = 0, n;
+ token_t token;
+ source_t *source;
+ fuzzyseperator_t *fs;
+ weightconfig_t *config = NULL;
+#ifdef DEBUG
+ int starttime;
+
+ starttime = Sys_MilliSeconds();
+#endif //DEBUG
+
+ if (!LibVarGetValue("bot_reloadcharacters"))
+ {
+ avail = -1;
+ for( n = 0; n < MAX_WEIGHT_FILES; n++ )
+ {
+ config = weightFileList[n];
+ if( !config )
+ {
+ if( avail == -1 )
+ {
+ avail = n;
+ } //end if
+ continue;
+ } //end if
+ if( strcmp( filename, config->filename ) == 0 )
+ {
+ //botimport.Print( PRT_MESSAGE, "retained %s\n", filename );
+ return config;
+ } //end if
+ } //end for
+
+ if( avail == -1 )
+ {
+ botimport.Print( PRT_ERROR, "weightFileList was full trying to load %s\n", filename );
+ return NULL;
+ } //end if
+ } //end if
+
+ PC_SetBaseFolder(BOTFILESBASEFOLDER);
+ source = LoadSourceFile(filename);
+ if (!source)
+ {
+ botimport.Print(PRT_ERROR, "counldn't load %s\n", filename);
+ return NULL;
+ } //end if
+ //
+ config = (weightconfig_t *) GetClearedMemory(sizeof(weightconfig_t));
+ config->numweights = 0;
+ Q_strncpyz( config->filename, filename, sizeof(config->filename) );
+ //parse the item config file
+ while(PC_ReadToken(source, &token))
+ {
+ if (!strcmp(token.string, "weight"))
+ {
+ if (config->numweights >= MAX_WEIGHTS)
+ {
+ SourceWarning(source, "too many fuzzy weights\n");
+ break;
+ } //end if
+ if (!PC_ExpectTokenType(source, TT_STRING, 0, &token))
+ {
+ FreeWeightConfig(config);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ StripDoubleQuotes(token.string);
+ config->weights[config->numweights].name = (char *) GetClearedMemory(strlen(token.string) + 1);
+ strcpy(config->weights[config->numweights].name, token.string);
+ if (!PC_ExpectAnyToken(source, &token))
+ {
+ FreeWeightConfig(config);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ newindent = qfalse;
+ if (!strcmp(token.string, "{"))
+ {
+ newindent = qtrue;
+ if (!PC_ExpectAnyToken(source, &token))
+ {
+ FreeWeightConfig(config);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ } //end if
+ if (!strcmp(token.string, "switch"))
+ {
+ fs = ReadFuzzySeperators_r(source);
+ if (!fs)
+ {
+ FreeWeightConfig(config);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ config->weights[config->numweights].firstseperator = fs;
+ } //end if
+ else if (!strcmp(token.string, "return"))
+ {
+ fs = (fuzzyseperator_t *) GetClearedMemory(sizeof(fuzzyseperator_t));
+ fs->index = 0;
+ fs->value = MAX_INVENTORYVALUE;
+ fs->next = NULL;
+ fs->child = NULL;
+ if (!ReadFuzzyWeight(source, fs))
+ {
+ FreeMemory(fs);
+ FreeWeightConfig(config);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ config->weights[config->numweights].firstseperator = fs;
+ } //end else if
+ else
+ {
+ SourceError(source, "invalid name %s\n", token.string);
+ FreeWeightConfig(config);
+ FreeSource(source);
+ return NULL;
+ } //end else
+ if (newindent)
+ {
+ if (!PC_ExpectTokenString(source, "}"))
+ {
+ FreeWeightConfig(config);
+ FreeSource(source);
+ return NULL;
+ } //end if
+ } //end if
+ config->numweights++;
+ } //end if
+ else
+ {
+ SourceError(source, "invalid name %s\n", token.string);
+ FreeWeightConfig(config);
+ FreeSource(source);
+ return NULL;
+ } //end else
+ } //end while
+ //free the source at the end of a pass
+ FreeSource(source);
+ //if the file was located in a pak file
+ botimport.Print(PRT_MESSAGE, "loaded %s\n", filename);
+#ifdef DEBUG
+ if (bot_developer)
+ {
+ botimport.Print(PRT_MESSAGE, "weights loaded in %d msec\n", Sys_MilliSeconds() - starttime);
+ } //end if
+#endif //DEBUG
+ //
+ if (!LibVarGetValue("bot_reloadcharacters"))
+ {
+ weightFileList[avail] = config;
+ } //end if
+ //
+ return config;
+} //end of the function ReadWeightConfig
+#if 0
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean WriteFuzzyWeight(FILE *fp, fuzzyseperator_t *fs)
+{
+ if (fs->type == WT_BALANCE)
+ {
+ if (fprintf(fp, " return balance(") < 0) return qfalse;
+ if (!WriteFloat(fp, fs->weight)) return qfalse;
+ if (fprintf(fp, ",") < 0) return qfalse;
+ if (!WriteFloat(fp, fs->minweight)) return qfalse;
+ if (fprintf(fp, ",") < 0) return qfalse;
+ if (!WriteFloat(fp, fs->maxweight)) return qfalse;
+ if (fprintf(fp, ");\n") < 0) return qfalse;
+ } //end if
+ else
+ {
+ if (fprintf(fp, " return ") < 0) return qfalse;
+ if (!WriteFloat(fp, fs->weight)) return qfalse;
+ if (fprintf(fp, ";\n") < 0) return qfalse;
+ } //end else
+ return qtrue;
+} //end of the function WriteFuzzyWeight
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean WriteFuzzySeperators_r(FILE *fp, fuzzyseperator_t *fs, int indent)
+{
+ if (!WriteIndent(fp, indent)) return qfalse;
+ if (fprintf(fp, "switch(%d)\n", fs->index) < 0) return qfalse;
+ if (!WriteIndent(fp, indent)) return qfalse;
+ if (fprintf(fp, "{\n") < 0) return qfalse;
+ indent++;
+ do
+ {
+ if (!WriteIndent(fp, indent)) return qfalse;
+ if (fs->next)
+ {
+ if (fprintf(fp, "case %d:", fs->value) < 0) return qfalse;
+ } //end if
+ else
+ {
+ if (fprintf(fp, "default:") < 0) return qfalse;
+ } //end else
+ if (fs->child)
+ {
+ if (fprintf(fp, "\n") < 0) return qfalse;
+ if (!WriteIndent(fp, indent)) return qfalse;
+ if (fprintf(fp, "{\n") < 0) return qfalse;
+ if (!WriteFuzzySeperators_r(fp, fs->child, indent + 1)) return qfalse;
+ if (!WriteIndent(fp, indent)) return qfalse;
+ if (fs->next)
+ {
+ if (fprintf(fp, "} //end case\n") < 0) return qfalse;
+ } //end if
+ else
+ {
+ if (fprintf(fp, "} //end default\n") < 0) return qfalse;
+ } //end else
+ } //end if
+ else
+ {
+ if (!WriteFuzzyWeight(fp, fs)) return qfalse;
+ } //end else
+ fs = fs->next;
+ } while(fs);
+ indent--;
+ if (!WriteIndent(fp, indent)) return qfalse;
+ if (fprintf(fp, "} //end switch\n") < 0) return qfalse;
+ return qtrue;
+} //end of the function WriteItemFuzzyWeights_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean WriteWeightConfig(char *filename, weightconfig_t *config)
+{
+ int i;
+ FILE *fp;
+ weight_t *ifw;
+
+ fp = fopen(filename, "wb");
+ if (!fp) return qfalse;
+
+ for (i = 0; i < config->numweights; i++)
+ {
+ ifw = &config->weights[i];
+ if (fprintf(fp, "\nweight \"%s\"\n", ifw->name) < 0) return qfalse;
+ if (fprintf(fp, "{\n") < 0) return qfalse;
+ if (ifw->firstseperator->index > 0)
+ {
+ if (!WriteFuzzySeperators_r(fp, ifw->firstseperator, 1)) return qfalse;
+ } //end if
+ else
+ {
+ if (!WriteIndent(fp, 1)) return qfalse;
+ if (!WriteFuzzyWeight(fp, ifw->firstseperator)) return qfalse;
+ } //end else
+ if (fprintf(fp, "} //end weight\n") < 0) return qfalse;
+ } //end for
+ fclose(fp);
+ return qtrue;
+} //end of the function WriteWeightConfig
+#endif
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int FindFuzzyWeight(weightconfig_t *wc, char *name)
+{
+ int i;
+
+ for (i = 0; i < wc->numweights; i++)
+ {
+ if (!strcmp(wc->weights[i].name, name))
+ {
+ return i;
+ } //end if
+ } //end if
+ return -1;
+} //end of the function FindFuzzyWeight
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float FuzzyWeight_r(int *inventory, fuzzyseperator_t *fs)
+{
+ float scale, w1, w2;
+
+ if (inventory[fs->index] < fs->value)
+ {
+ if (fs->child) return FuzzyWeight_r(inventory, fs->child);
+ else return fs->weight;
+ } //end if
+ else if (fs->next)
+ {
+ if (inventory[fs->index] < fs->next->value)
+ {
+ //first weight
+ if (fs->child) w1 = FuzzyWeight_r(inventory, fs->child);
+ else w1 = fs->weight;
+ //second weight
+ if (fs->next->child) w2 = FuzzyWeight_r(inventory, fs->next->child);
+ else w2 = fs->next->weight;
+ //the scale factor
+ scale = (inventory[fs->index] - fs->value) / (fs->next->value - fs->value);
+ //scale between the two weights
+ return scale * w1 + (1 - scale) * w2;
+ } //end if
+ return FuzzyWeight_r(inventory, fs->next);
+ } //end else if
+ return fs->weight;
+} //end of the function FuzzyWeight_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float FuzzyWeightUndecided_r(int *inventory, fuzzyseperator_t *fs)
+{
+ float scale, w1, w2;
+
+ if (inventory[fs->index] < fs->value)
+ {
+ if (fs->child) return FuzzyWeightUndecided_r(inventory, fs->child);
+ else return fs->minweight + random() * (fs->maxweight - fs->minweight);
+ } //end if
+ else if (fs->next)
+ {
+ if (inventory[fs->index] < fs->next->value)
+ {
+ //first weight
+ if (fs->child) w1 = FuzzyWeightUndecided_r(inventory, fs->child);
+ else w1 = fs->minweight + random() * (fs->maxweight - fs->minweight);
+ //second weight
+ if (fs->next->child) w2 = FuzzyWeight_r(inventory, fs->next->child);
+ else w2 = fs->next->minweight + random() * (fs->next->maxweight - fs->next->minweight);
+ //the scale factor
+ scale = (inventory[fs->index] - fs->value) / (fs->next->value - fs->value);
+ //scale between the two weights
+ return scale * w1 + (1 - scale) * w2;
+ } //end if
+ return FuzzyWeightUndecided_r(inventory, fs->next);
+ } //end else if
+ return fs->weight;
+} //end of the function FuzzyWeightUndecided_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float FuzzyWeight(int *inventory, weightconfig_t *wc, int weightnum)
+{
+#ifdef EVALUATERECURSIVELY
+ return FuzzyWeight_r(inventory, wc->weights[weightnum].firstseperator);
+#else
+ fuzzyseperator_t *s;
+
+ s = wc->weights[weightnum].firstseperator;
+ if (!s) return 0;
+ while(1)
+ {
+ if (inventory[s->index] < s->value)
+ {
+ if (s->child) s = s->child;
+ else return s->weight;
+ } //end if
+ else
+ {
+ if (s->next) s = s->next;
+ else return s->weight;
+ } //end else
+ } //end if
+ return 0;
+#endif
+} //end of the function FuzzyWeight
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float FuzzyWeightUndecided(int *inventory, weightconfig_t *wc, int weightnum)
+{
+#ifdef EVALUATERECURSIVELY
+ return FuzzyWeightUndecided_r(inventory, wc->weights[weightnum].firstseperator);
+#else
+ fuzzyseperator_t *s;
+
+ s = wc->weights[weightnum].firstseperator;
+ if (!s) return 0;
+ while(1)
+ {
+ if (inventory[s->index] < s->value)
+ {
+ if (s->child) s = s->child;
+ else return s->minweight + random() * (s->maxweight - s->minweight);
+ } //end if
+ else
+ {
+ if (s->next) s = s->next;
+ else return s->minweight + random() * (s->maxweight - s->minweight);
+ } //end else
+ } //end if
+ return 0;
+#endif
+} //end of the function FuzzyWeightUndecided
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EvolveFuzzySeperator_r(fuzzyseperator_t *fs)
+{
+ if (fs->child)
+ {
+ EvolveFuzzySeperator_r(fs->child);
+ } //end if
+ else if (fs->type == WT_BALANCE)
+ {
+ //every once in a while an evolution leap occurs, mutation
+ if (random() < 0.01) fs->weight += crandom() * (fs->maxweight - fs->minweight);
+ else fs->weight += crandom() * (fs->maxweight - fs->minweight) * 0.5;
+ //modify bounds if necesary because of mutation
+ if (fs->weight < fs->minweight) fs->minweight = fs->weight;
+ else if (fs->weight > fs->maxweight) fs->maxweight = fs->weight;
+ } //end else if
+ if (fs->next) EvolveFuzzySeperator_r(fs->next);
+} //end of the function EvolveFuzzySeperator_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EvolveWeightConfig(weightconfig_t *config)
+{
+ int i;
+
+ for (i = 0; i < config->numweights; i++)
+ {
+ EvolveFuzzySeperator_r(config->weights[i].firstseperator);
+ } //end for
+} //end of the function EvolveWeightConfig
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ScaleFuzzySeperator_r(fuzzyseperator_t *fs, float scale)
+{
+ if (fs->child)
+ {
+ ScaleFuzzySeperator_r(fs->child, scale);
+ } //end if
+ else if (fs->type == WT_BALANCE)
+ {
+ //
+ fs->weight = (fs->maxweight + fs->minweight) * scale;
+ //get the weight between bounds
+ if (fs->weight < fs->minweight) fs->weight = fs->minweight;
+ else if (fs->weight > fs->maxweight) fs->weight = fs->maxweight;
+ } //end else if
+ if (fs->next) ScaleFuzzySeperator_r(fs->next, scale);
+} //end of the function ScaleFuzzySeperator_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ScaleWeight(weightconfig_t *config, char *name, float scale)
+{
+ int i;
+
+ if (scale < 0) scale = 0;
+ else if (scale > 1) scale = 1;
+ for (i = 0; i < config->numweights; i++)
+ {
+ if (!strcmp(name, config->weights[i].name))
+ {
+ ScaleFuzzySeperator_r(config->weights[i].firstseperator, scale);
+ break;
+ } //end if
+ } //end for
+} //end of the function ScaleWeight
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ScaleFuzzySeperatorBalanceRange_r(fuzzyseperator_t *fs, float scale)
+{
+ if (fs->child)
+ {
+ ScaleFuzzySeperatorBalanceRange_r(fs->child, scale);
+ } //end if
+ else if (fs->type == WT_BALANCE)
+ {
+ float mid = (fs->minweight + fs->maxweight) * 0.5;
+ //get the weight between bounds
+ fs->maxweight = mid + (fs->maxweight - mid) * scale;
+ fs->minweight = mid + (fs->minweight - mid) * scale;
+ if (fs->maxweight < fs->minweight)
+ {
+ fs->maxweight = fs->minweight;
+ } //end if
+ } //end else if
+ if (fs->next) ScaleFuzzySeperatorBalanceRange_r(fs->next, scale);
+} //end of the function ScaleFuzzySeperatorBalanceRange_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ScaleFuzzyBalanceRange(weightconfig_t *config, float scale)
+{
+ int i;
+
+ if (scale < 0) scale = 0;
+ else if (scale > 100) scale = 100;
+ for (i = 0; i < config->numweights; i++)
+ {
+ ScaleFuzzySeperatorBalanceRange_r(config->weights[i].firstseperator, scale);
+ } //end for
+} //end of the function ScaleFuzzyBalanceRange
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int InterbreedFuzzySeperator_r(fuzzyseperator_t *fs1, fuzzyseperator_t *fs2,
+ fuzzyseperator_t *fsout)
+{
+ if (fs1->child)
+ {
+ if (!fs2->child || !fsout->child)
+ {
+ botimport.Print(PRT_ERROR, "cannot interbreed weight configs, unequal child\n");
+ return qfalse;
+ } //end if
+ if (!InterbreedFuzzySeperator_r(fs2->child, fs2->child, fsout->child))
+ {
+ return qfalse;
+ } //end if
+ } //end if
+ else if (fs1->type == WT_BALANCE)
+ {
+ if (fs2->type != WT_BALANCE || fsout->type != WT_BALANCE)
+ {
+ botimport.Print(PRT_ERROR, "cannot interbreed weight configs, unequal balance\n");
+ return qfalse;
+ } //end if
+ fsout->weight = (fs1->weight + fs2->weight) / 2;
+ if (fsout->weight > fsout->maxweight) fsout->maxweight = fsout->weight;
+ if (fsout->weight > fsout->minweight) fsout->minweight = fsout->weight;
+ } //end else if
+ if (fs1->next)
+ {
+ if (!fs2->next || !fsout->next)
+ {
+ botimport.Print(PRT_ERROR, "cannot interbreed weight configs, unequal next\n");
+ return qfalse;
+ } //end if
+ if (!InterbreedFuzzySeperator_r(fs1->next, fs2->next, fsout->next))
+ {
+ return qfalse;
+ } //end if
+ } //end if
+ return qtrue;
+} //end of the function InterbreedFuzzySeperator_r
+//===========================================================================
+// config1 and config2 are interbreeded and stored in configout
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void InterbreedWeightConfigs(weightconfig_t *config1, weightconfig_t *config2,
+ weightconfig_t *configout)
+{
+ int i;
+
+ if (config1->numweights != config2->numweights ||
+ config1->numweights != configout->numweights)
+ {
+ botimport.Print(PRT_ERROR, "cannot interbreed weight configs, unequal numweights\n");
+ return;
+ } //end if
+ for (i = 0; i < config1->numweights; i++)
+ {
+ InterbreedFuzzySeperator_r(config1->weights[i].firstseperator,
+ config2->weights[i].firstseperator,
+ configout->weights[i].firstseperator);
+ } //end for
+} //end of the function InterbreedWeightConfigs
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotShutdownWeights(void)
+{
+ int i;
+
+ for( i = 0; i < MAX_WEIGHT_FILES; i++ )
+ {
+ if (weightFileList[i])
+ {
+ FreeWeightConfig2(weightFileList[i]);
+ weightFileList[i] = NULL;
+ } //end if
+ } //end for
+} //end of the function BotShutdownWeights
diff --git a/code/botlib/be_ai_weight.h b/code/botlib/be_ai_weight.h
new file mode 100755
index 0000000..4fc2f6b
--- /dev/null
+++ b/code/botlib/be_ai_weight.h
@@ -0,0 +1,83 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_ai_weight.h
+ *
+ * desc: fuzzy weights
+ *
+ * $Archive: /source/code/botlib/be_ai_weight.h $
+ *
+ *****************************************************************************/
+
+#define WT_BALANCE 1
+#define MAX_WEIGHTS 128
+
+//fuzzy seperator
+typedef struct fuzzyseperator_s
+{
+ int index;
+ int value;
+ int type;
+ float weight;
+ float minweight;
+ float maxweight;
+ struct fuzzyseperator_s *child;
+ struct fuzzyseperator_s *next;
+} fuzzyseperator_t;
+
+//fuzzy weight
+typedef struct weight_s
+{
+ char *name;
+ struct fuzzyseperator_s *firstseperator;
+} weight_t;
+
+//weight configuration
+typedef struct weightconfig_s
+{
+ int numweights;
+ weight_t weights[MAX_WEIGHTS];
+ char filename[MAX_QPATH];
+} weightconfig_t;
+
+//reads a weight configuration
+weightconfig_t *ReadWeightConfig(char *filename);
+//free a weight configuration
+void FreeWeightConfig(weightconfig_t *config);
+//writes a weight configuration, returns true if successfull
+qboolean WriteWeightConfig(char *filename, weightconfig_t *config);
+//find the fuzzy weight with the given name
+int FindFuzzyWeight(weightconfig_t *wc, char *name);
+//returns the fuzzy weight for the given inventory and weight
+float FuzzyWeight(int *inventory, weightconfig_t *wc, int weightnum);
+float FuzzyWeightUndecided(int *inventory, weightconfig_t *wc, int weightnum);
+//scales the weight with the given name
+void ScaleWeight(weightconfig_t *config, char *name, float scale);
+//scale the balance range
+void ScaleBalanceRange(weightconfig_t *config, float scale);
+//evolves the weight configuration
+void EvolveWeightConfig(weightconfig_t *config);
+//interbreed the weight configurations and stores the interbreeded one in configout
+void InterbreedWeightConfigs(weightconfig_t *config1, weightconfig_t *config2, weightconfig_t *configout);
+//frees cached weight configurations
+void BotShutdownWeights(void);
diff --git a/code/botlib/be_ea.c b/code/botlib/be_ea.c
new file mode 100755
index 0000000..2c57099
--- /dev/null
+++ b/code/botlib/be_ea.c
@@ -0,0 +1,508 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_ea.c
+ *
+ * desc: elementary actions
+ *
+ * $Archive: /MissionPack/code/botlib/be_ea.c $
+ *
+ *****************************************************************************/
+
+#include "../game/q_shared.h"
+#include "l_memory.h"
+#include "l_script.h"
+#include "l_precomp.h"
+#include "l_struct.h"
+#include "../game/botlib.h"
+#include "be_interface.h"
+
+#define MAX_USERMOVE 400
+#define MAX_COMMANDARGUMENTS 10
+#define ACTION_JUMPEDLASTFRAME 128
+
+bot_input_t *botinputs;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_Say(int client, char *str)
+{
+ botimport.BotClientCommand(client, va("say %s", str) );
+} //end of the function EA_Say
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_SayTeam(int client, char *str)
+{
+ botimport.BotClientCommand(client, va("say_team %s", str));
+} //end of the function EA_SayTeam
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_Tell(int client, int clientto, char *str)
+{
+ botimport.BotClientCommand(client, va("tell %d, %s", clientto, str));
+} //end of the function EA_SayTeam
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_UseItem(int client, char *it)
+{
+ botimport.BotClientCommand(client, va("use %s", it));
+} //end of the function EA_UseItem
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_DropItem(int client, char *it)
+{
+ botimport.BotClientCommand(client, va("drop %s", it));
+} //end of the function EA_DropItem
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_UseInv(int client, char *inv)
+{
+ botimport.BotClientCommand(client, va("invuse %s", inv));
+} //end of the function EA_UseInv
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_DropInv(int client, char *inv)
+{
+ botimport.BotClientCommand(client, va("invdrop %s", inv));
+} //end of the function EA_DropInv
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_Gesture(int client)
+{
+ bot_input_t *bi;
+
+ bi = &botinputs[client];
+
+ bi->actionflags |= ACTION_GESTURE;
+} //end of the function EA_Gesture
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_Command(int client, char *command)
+{
+ botimport.BotClientCommand(client, command);
+} //end of the function EA_Command
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_SelectWeapon(int client, int weapon)
+{
+ bot_input_t *bi;
+
+ bi = &botinputs[client];
+
+ bi->weapon = weapon;
+} //end of the function EA_SelectWeapon
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_Attack(int client)
+{
+ bot_input_t *bi;
+
+ bi = &botinputs[client];
+
+ bi->actionflags |= ACTION_ATTACK;
+} //end of the function EA_Attack
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_Talk(int client)
+{
+ bot_input_t *bi;
+
+ bi = &botinputs[client];
+
+ bi->actionflags |= ACTION_TALK;
+} //end of the function EA_Talk
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_Use(int client)
+{
+ bot_input_t *bi;
+
+ bi = &botinputs[client];
+
+ bi->actionflags |= ACTION_USE;
+} //end of the function EA_Use
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_Respawn(int client)
+{
+ bot_input_t *bi;
+
+ bi = &botinputs[client];
+
+ bi->actionflags |= ACTION_RESPAWN;
+} //end of the function EA_Respawn
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_Jump(int client)
+{
+ bot_input_t *bi;
+
+ bi = &botinputs[client];
+
+ if (bi->actionflags & ACTION_JUMPEDLASTFRAME)
+ {
+ bi->actionflags &= ~ACTION_JUMP;
+ } //end if
+ else
+ {
+ bi->actionflags |= ACTION_JUMP;
+ } //end if
+} //end of the function EA_Jump
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_DelayedJump(int client)
+{
+ bot_input_t *bi;
+
+ bi = &botinputs[client];
+
+ if (bi->actionflags & ACTION_JUMPEDLASTFRAME)
+ {
+ bi->actionflags &= ~ACTION_DELAYEDJUMP;
+ } //end if
+ else
+ {
+ bi->actionflags |= ACTION_DELAYEDJUMP;
+ } //end if
+} //end of the function EA_DelayedJump
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_Crouch(int client)
+{
+ bot_input_t *bi;
+
+ bi = &botinputs[client];
+
+ bi->actionflags |= ACTION_CROUCH;
+} //end of the function EA_Crouch
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_Walk(int client)
+{
+ bot_input_t *bi;
+
+ bi = &botinputs[client];
+
+ bi->actionflags |= ACTION_WALK;
+} //end of the function EA_Walk
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_Action(int client, int action)
+{
+ bot_input_t *bi;
+
+ bi = &botinputs[client];
+
+ bi->actionflags |= action;
+} //end of function EA_Action
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_MoveUp(int client)
+{
+ bot_input_t *bi;
+
+ bi = &botinputs[client];
+
+ bi->actionflags |= ACTION_MOVEUP;
+} //end of the function EA_MoveUp
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_MoveDown(int client)
+{
+ bot_input_t *bi;
+
+ bi = &botinputs[client];
+
+ bi->actionflags |= ACTION_MOVEDOWN;
+} //end of the function EA_MoveDown
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_MoveForward(int client)
+{
+ bot_input_t *bi;
+
+ bi = &botinputs[client];
+
+ bi->actionflags |= ACTION_MOVEFORWARD;
+} //end of the function EA_MoveForward
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_MoveBack(int client)
+{
+ bot_input_t *bi;
+
+ bi = &botinputs[client];
+
+ bi->actionflags |= ACTION_MOVEBACK;
+} //end of the function EA_MoveBack
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_MoveLeft(int client)
+{
+ bot_input_t *bi;
+
+ bi = &botinputs[client];
+
+ bi->actionflags |= ACTION_MOVELEFT;
+} //end of the function EA_MoveLeft
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_MoveRight(int client)
+{
+ bot_input_t *bi;
+
+ bi = &botinputs[client];
+
+ bi->actionflags |= ACTION_MOVERIGHT;
+} //end of the function EA_MoveRight
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_Move(int client, vec3_t dir, float speed)
+{
+ bot_input_t *bi;
+
+ bi = &botinputs[client];
+
+ VectorCopy(dir, bi->dir);
+ //cap speed
+ if (speed > MAX_USERMOVE) speed = MAX_USERMOVE;
+ else if (speed < -MAX_USERMOVE) speed = -MAX_USERMOVE;
+ bi->speed = speed;
+} //end of the function EA_Move
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_View(int client, vec3_t viewangles)
+{
+ bot_input_t *bi;
+
+ bi = &botinputs[client];
+
+ VectorCopy(viewangles, bi->viewangles);
+} //end of the function EA_View
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_EndRegular(int client, float thinktime)
+{
+/*
+ bot_input_t *bi;
+ int jumped = qfalse;
+
+ bi = &botinputs[client];
+
+ bi->actionflags &= ~ACTION_JUMPEDLASTFRAME;
+
+ bi->thinktime = thinktime;
+ botimport.BotInput(client, bi);
+
+ bi->thinktime = 0;
+ VectorClear(bi->dir);
+ bi->speed = 0;
+ jumped = bi->actionflags & ACTION_JUMP;
+ bi->actionflags = 0;
+ if (jumped) bi->actionflags |= ACTION_JUMPEDLASTFRAME;
+*/
+} //end of the function EA_EndRegular
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_GetInput(int client, float thinktime, bot_input_t *input)
+{
+ bot_input_t *bi;
+// int jumped = qfalse;
+
+ bi = &botinputs[client];
+
+// bi->actionflags &= ~ACTION_JUMPEDLASTFRAME;
+
+ bi->thinktime = thinktime;
+ Com_Memcpy(input, bi, sizeof(bot_input_t));
+
+ /*
+ bi->thinktime = 0;
+ VectorClear(bi->dir);
+ bi->speed = 0;
+ jumped = bi->actionflags & ACTION_JUMP;
+ bi->actionflags = 0;
+ if (jumped) bi->actionflags |= ACTION_JUMPEDLASTFRAME;
+ */
+} //end of the function EA_GetInput
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_ResetInput(int client)
+{
+ bot_input_t *bi;
+ int jumped = qfalse;
+
+ bi = &botinputs[client];
+ bi->actionflags &= ~ACTION_JUMPEDLASTFRAME;
+
+ bi->thinktime = 0;
+ VectorClear(bi->dir);
+ bi->speed = 0;
+ jumped = bi->actionflags & ACTION_JUMP;
+ bi->actionflags = 0;
+ if (jumped) bi->actionflags |= ACTION_JUMPEDLASTFRAME;
+} //end of the function EA_ResetInput
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int EA_Setup(void)
+{
+ //initialize the bot inputs
+ botinputs = (bot_input_t *) GetClearedHunkMemory(
+ botlibglobals.maxclients * sizeof(bot_input_t));
+ return BLERR_NOERROR;
+} //end of the function EA_Setup
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void EA_Shutdown(void)
+{
+ FreeMemory(botinputs);
+ botinputs = NULL;
+} //end of the function EA_Shutdown
diff --git a/code/botlib/be_interface.c b/code/botlib/be_interface.c
new file mode 100755
index 0000000..b5a022b
--- /dev/null
+++ b/code/botlib/be_interface.c
@@ -0,0 +1,881 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_interface.c // bk010221 - FIXME - DEAD code elimination
+ *
+ * desc: bot library interface
+ *
+ * $Archive: /MissionPack/code/botlib/be_interface.c $
+ *
+ *****************************************************************************/
+
+#include "../game/q_shared.h"
+#include "l_memory.h"
+#include "l_log.h"
+#include "l_libvar.h"
+#include "l_script.h"
+#include "l_precomp.h"
+#include "l_struct.h"
+#include "aasfile.h"
+#include "../game/botlib.h"
+#include "../game/be_aas.h"
+#include "be_aas_funcs.h"
+#include "be_aas_def.h"
+#include "be_interface.h"
+
+#include "../game/be_ea.h"
+#include "be_ai_weight.h"
+#include "../game/be_ai_goal.h"
+#include "../game/be_ai_move.h"
+#include "../game/be_ai_weap.h"
+#include "../game/be_ai_chat.h"
+#include "../game/be_ai_char.h"
+#include "../game/be_ai_gen.h"
+
+//library globals in a structure
+botlib_globals_t botlibglobals;
+
+botlib_export_t be_botlib_export;
+botlib_import_t botimport;
+//
+int bot_developer;
+//qtrue if the library is setup
+int botlibsetup = qfalse;
+
+//===========================================================================
+//
+// several functions used by the exported functions
+//
+//===========================================================================
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int Sys_MilliSeconds(void)
+{
+ return clock() * 1000 / CLOCKS_PER_SEC;
+} //end of the function Sys_MilliSeconds
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean ValidClientNumber(int num, char *str)
+{
+ if (num < 0 || num > botlibglobals.maxclients)
+ {
+ //weird: the disabled stuff results in a crash
+ botimport.Print(PRT_ERROR, "%s: invalid client number %d, [0, %d]\n",
+ str, num, botlibglobals.maxclients);
+ return qfalse;
+ } //end if
+ return qtrue;
+} //end of the function BotValidateClientNumber
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean ValidEntityNumber(int num, char *str)
+{
+ if (num < 0 || num > botlibglobals.maxentities)
+ {
+ botimport.Print(PRT_ERROR, "%s: invalid entity number %d, [0, %d]\n",
+ str, num, botlibglobals.maxentities);
+ return qfalse;
+ } //end if
+ return qtrue;
+} //end of the function BotValidateClientNumber
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean BotLibSetup(char *str)
+{
+ if (!botlibglobals.botlibsetup)
+ {
+ botimport.Print(PRT_ERROR, "%s: bot library used before being setup\n", str);
+ return qfalse;
+ } //end if
+ return qtrue;
+} //end of the function BotLibSetup
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int Export_BotLibSetup(void)
+{
+ int errnum;
+
+ bot_developer = LibVarGetValue("bot_developer");
+ memset( &botlibglobals, 0, sizeof(botlibglobals) ); // bk001207 - init
+ //initialize byte swapping (litte endian etc.)
+// Swap_Init();
+ Log_Open("botlib.log");
+ //
+ botimport.Print(PRT_MESSAGE, "------- BotLib Initialization -------\n");
+ //
+ botlibglobals.maxclients = (int) LibVarValue("maxclients", "128");
+ botlibglobals.maxentities = (int) LibVarValue("maxentities", "1024");
+
+ errnum = AAS_Setup(); //be_aas_main.c
+ if (errnum != BLERR_NOERROR) return errnum;
+ errnum = EA_Setup(); //be_ea.c
+ if (errnum != BLERR_NOERROR) return errnum;
+ errnum = BotSetupWeaponAI(); //be_ai_weap.c
+ if (errnum != BLERR_NOERROR)return errnum;
+ errnum = BotSetupGoalAI(); //be_ai_goal.c
+ if (errnum != BLERR_NOERROR) return errnum;
+ errnum = BotSetupChatAI(); //be_ai_chat.c
+ if (errnum != BLERR_NOERROR) return errnum;
+ errnum = BotSetupMoveAI(); //be_ai_move.c
+ if (errnum != BLERR_NOERROR) return errnum;
+
+ botlibsetup = qtrue;
+ botlibglobals.botlibsetup = qtrue;
+
+ return BLERR_NOERROR;
+} //end of the function Export_BotLibSetup
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int Export_BotLibShutdown(void)
+{
+ if (!BotLibSetup("BotLibShutdown")) return BLERR_LIBRARYNOTSETUP;
+#ifndef DEMO
+ //DumpFileCRCs();
+#endif //DEMO
+ //
+ BotShutdownChatAI(); //be_ai_chat.c
+ BotShutdownMoveAI(); //be_ai_move.c
+ BotShutdownGoalAI(); //be_ai_goal.c
+ BotShutdownWeaponAI(); //be_ai_weap.c
+ BotShutdownWeights(); //be_ai_weight.c
+ BotShutdownCharacters(); //be_ai_char.c
+ //shud down aas
+ AAS_Shutdown();
+ //shut down bot elemantary actions
+ EA_Shutdown();
+ //free all libvars
+ LibVarDeAllocAll();
+ //remove all global defines from the pre compiler
+ PC_RemoveAllGlobalDefines();
+
+ //dump all allocated memory
+// DumpMemory();
+#ifdef DEBUG
+ PrintMemoryLabels();
+#endif
+ //shut down library log file
+ Log_Shutdown();
+ //
+ botlibsetup = qfalse;
+ botlibglobals.botlibsetup = qfalse;
+ // print any files still open
+ PC_CheckOpenSourceHandles();
+ //
+ return BLERR_NOERROR;
+} //end of the function Export_BotLibShutdown
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int Export_BotLibVarSet(char *var_name, char *value)
+{
+ LibVarSet(var_name, value);
+ return BLERR_NOERROR;
+} //end of the function Export_BotLibVarSet
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int Export_BotLibVarGet(char *var_name, char *value, int size)
+{
+ char *varvalue;
+
+ varvalue = LibVarGetString(var_name);
+ strncpy(value, varvalue, size-1);
+ value[size-1] = '\0';
+ return BLERR_NOERROR;
+} //end of the function Export_BotLibVarGet
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int Export_BotLibStartFrame(float time)
+{
+ if (!BotLibSetup("BotStartFrame")) return BLERR_LIBRARYNOTSETUP;
+ return AAS_StartFrame(time);
+} //end of the function Export_BotLibStartFrame
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int Export_BotLibLoadMap(const char *mapname)
+{
+#ifdef DEBUG
+ int starttime = Sys_MilliSeconds();
+#endif
+ int errnum;
+
+ if (!BotLibSetup("BotLoadMap")) return BLERR_LIBRARYNOTSETUP;
+ //
+ botimport.Print(PRT_MESSAGE, "------------ Map Loading ------------\n");
+ //startup AAS for the current map, model and sound index
+ errnum = AAS_LoadMap(mapname);
+ if (errnum != BLERR_NOERROR) return errnum;
+ //initialize the items in the level
+ BotInitLevelItems(); //be_ai_goal.h
+ BotSetBrushModelTypes(); //be_ai_move.h
+ //
+ botimport.Print(PRT_MESSAGE, "-------------------------------------\n");
+#ifdef DEBUG
+ botimport.Print(PRT_MESSAGE, "map loaded in %d msec\n", Sys_MilliSeconds() - starttime);
+#endif
+ //
+ return BLERR_NOERROR;
+} //end of the function Export_BotLibLoadMap
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int Export_BotLibUpdateEntity(int ent, bot_entitystate_t *state)
+{
+ if (!BotLibSetup("BotUpdateEntity")) return BLERR_LIBRARYNOTSETUP;
+ if (!ValidEntityNumber(ent, "BotUpdateEntity")) return BLERR_INVALIDENTITYNUMBER;
+
+ return AAS_UpdateEntity(ent, state);
+} //end of the function Export_BotLibUpdateEntity
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_TestMovementPrediction(int entnum, vec3_t origin, vec3_t dir);
+void ElevatorBottomCenter(aas_reachability_t *reach, vec3_t bottomcenter);
+int BotGetReachabilityToGoal(vec3_t origin, int areanum,
+ int lastgoalareanum, int lastareanum,
+ int *avoidreach, float *avoidreachtimes, int *avoidreachtries,
+ bot_goal_t *goal, int travelflags, int movetravelflags,
+ struct bot_avoidspot_s *avoidspots, int numavoidspots, int *flags);
+
+int AAS_PointLight(vec3_t origin, int *red, int *green, int *blue);
+
+int AAS_TraceAreas(vec3_t start, vec3_t end, int *areas, vec3_t *points, int maxareas);
+
+int AAS_Reachability_WeaponJump(int area1num, int area2num);
+
+int BotFuzzyPointReachabilityArea(vec3_t origin);
+
+float BotGapDistance(vec3_t origin, vec3_t hordir, int entnum);
+
+void AAS_FloodAreas(vec3_t origin);
+
+int BotExportTest(int parm0, char *parm1, vec3_t parm2, vec3_t parm3)
+{
+
+// return AAS_PointLight(parm2, NULL, NULL, NULL);
+
+#ifdef DEBUG
+ static int area = -1;
+ static int line[2];
+ int newarea, i, highlightarea, flood;
+// int reachnum;
+ vec3_t eye, forward, right, end, origin;
+// vec3_t bottomcenter;
+// aas_trace_t trace;
+// aas_face_t *face;
+// aas_entity_t *ent;
+// bsp_trace_t bsptrace;
+// aas_reachability_t reach;
+// bot_goal_t goal;
+
+ // clock_t start_time, end_time;
+ vec3_t mins = {-16, -16, -24};
+ vec3_t maxs = {16, 16, 32};
+
+// int areas[10], numareas;
+
+
+ //return 0;
+
+ if (!aasworld.loaded) return 0;
+
+ /*
+ if (parm0 & 1)
+ {
+ AAS_ClearShownPolygons();
+ AAS_FloodAreas(parm2);
+ } //end if
+ return 0;
+ */
+ for (i = 0; i < 2; i++) if (!line[i]) line[i] = botimport.DebugLineCreate();
+
+// AAS_ClearShownDebugLines();
+
+ //if (AAS_AgainstLadder(parm2)) botimport.Print(PRT_MESSAGE, "against ladder\n");
+ //BotOnGround(parm2, PRESENCE_NORMAL, 1, &newarea, &newarea);
+ //botimport.Print(PRT_MESSAGE, "%f %f %f\n", parm2[0], parm2[1], parm2[2]);
+ //*
+ highlightarea = LibVarGetValue("bot_highlightarea");
+ if (highlightarea > 0)
+ {
+ newarea = highlightarea;
+ } //end if
+ else
+ {
+ VectorCopy(parm2, origin);
+ origin[2] += 0.5;
+ //newarea = AAS_PointAreaNum(origin);
+ newarea = BotFuzzyPointReachabilityArea(origin);
+ } //end else
+
+ botimport.Print(PRT_MESSAGE, "\rtravel time to goal (%d) = %d ", botlibglobals.goalareanum,
+ AAS_AreaTravelTimeToGoalArea(newarea, origin, botlibglobals.goalareanum, TFL_DEFAULT));
+ //newarea = BotReachabilityArea(origin, qtrue);
+ if (newarea != area)
+ {
+ botimport.Print(PRT_MESSAGE, "origin = %f, %f, %f\n", origin[0], origin[1], origin[2]);
+ area = newarea;
+ botimport.Print(PRT_MESSAGE, "new area %d, cluster %d, presence type %d\n",
+ area, AAS_AreaCluster(area), AAS_PointPresenceType(origin));
+ botimport.Print(PRT_MESSAGE, "area contents: ");
+ if (aasworld.areasettings[area].contents & AREACONTENTS_WATER)
+ {
+ botimport.Print(PRT_MESSAGE, "water &");
+ } //end if
+ if (aasworld.areasettings[area].contents & AREACONTENTS_LAVA)
+ {
+ botimport.Print(PRT_MESSAGE, "lava &");
+ } //end if
+ if (aasworld.areasettings[area].contents & AREACONTENTS_SLIME)
+ {
+ botimport.Print(PRT_MESSAGE, "slime &");
+ } //end if
+ if (aasworld.areasettings[area].contents & AREACONTENTS_JUMPPAD)
+ {
+ botimport.Print(PRT_MESSAGE, "jump pad &");
+ } //end if
+ if (aasworld.areasettings[area].contents & AREACONTENTS_CLUSTERPORTAL)
+ {
+ botimport.Print(PRT_MESSAGE, "cluster portal &");
+ } //end if
+ if (aasworld.areasettings[area].contents & AREACONTENTS_VIEWPORTAL)
+ {
+ botimport.Print(PRT_MESSAGE, "view portal &");
+ } //end if
+ if (aasworld.areasettings[area].contents & AREACONTENTS_DONOTENTER)
+ {
+ botimport.Print(PRT_MESSAGE, "do not enter &");
+ } //end if
+ if (aasworld.areasettings[area].contents & AREACONTENTS_MOVER)
+ {
+ botimport.Print(PRT_MESSAGE, "mover &");
+ } //end if
+ if (!aasworld.areasettings[area].contents)
+ {
+ botimport.Print(PRT_MESSAGE, "empty");
+ } //end if
+ botimport.Print(PRT_MESSAGE, "\n");
+ botimport.Print(PRT_MESSAGE, "travel time to goal (%d) = %d\n", botlibglobals.goalareanum,
+ AAS_AreaTravelTimeToGoalArea(newarea, origin, botlibglobals.goalareanum, TFL_DEFAULT|TFL_ROCKETJUMP));
+ /*
+ VectorCopy(origin, end);
+ end[2] += 5;
+ numareas = AAS_TraceAreas(origin, end, areas, NULL, 10);
+ AAS_TraceClientBBox(origin, end, PRESENCE_CROUCH, -1);
+ botimport.Print(PRT_MESSAGE, "num areas = %d, area = %d\n", numareas, areas[0]);
+ */
+ /*
+ botlibglobals.goalareanum = newarea;
+ VectorCopy(parm2, botlibglobals.goalorigin);
+ botimport.Print(PRT_MESSAGE, "new goal %2.1f %2.1f %2.1f area %d\n",
+ origin[0], origin[1], origin[2], newarea);
+ */
+ } //end if
+ //*
+ flood = LibVarGetValue("bot_flood");
+ if (parm0 & 1)
+ {
+ if (flood)
+ {
+ AAS_ClearShownPolygons();
+ AAS_ClearShownDebugLines();
+ AAS_FloodAreas(parm2);
+ }
+ else
+ {
+ botlibglobals.goalareanum = newarea;
+ VectorCopy(parm2, botlibglobals.goalorigin);
+ botimport.Print(PRT_MESSAGE, "new goal %2.1f %2.1f %2.1f area %d\n",
+ origin[0], origin[1], origin[2], newarea);
+ }
+ } //end if*/
+ if (flood)
+ return 0;
+// if (parm0 & BUTTON_USE)
+// {
+// botlibglobals.runai = !botlibglobals.runai;
+// if (botlibglobals.runai) botimport.Print(PRT_MESSAGE, "started AI\n");
+// else botimport.Print(PRT_MESSAGE, "stopped AI\n");
+ //* /
+ /*
+ goal.areanum = botlibglobals.goalareanum;
+ reachnum = BotGetReachabilityToGoal(parm2, newarea, 1,
+ ms.avoidreach, ms.avoidreachtimes,
+ &goal, TFL_DEFAULT);
+ if (!reachnum)
+ {
+ botimport.Print(PRT_MESSAGE, "goal not reachable\n");
+ } //end if
+ else
+ {
+ AAS_ReachabilityFromNum(reachnum, &reach);
+ AAS_ClearShownDebugLines();
+ AAS_ShowArea(area, qtrue);
+ AAS_ShowArea(reach.areanum, qtrue);
+ AAS_DrawCross(reach.start, 6, LINECOLOR_BLUE);
+ AAS_DrawCross(reach.end, 6, LINECOLOR_RED);
+ //
+ if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_ELEVATOR)
+ {
+ ElevatorBottomCenter(&reach, bottomcenter);
+ AAS_DrawCross(bottomcenter, 10, LINECOLOR_GREEN);
+ } //end if
+ } //end else*/
+// botimport.Print(PRT_MESSAGE, "travel time to goal = %d\n",
+// AAS_AreaTravelTimeToGoalArea(area, origin, botlibglobals.goalareanum, TFL_DEFAULT));
+// botimport.Print(PRT_MESSAGE, "test rj from 703 to 716\n");
+// AAS_Reachability_WeaponJump(703, 716);
+// } //end if*/
+
+/* face = AAS_AreaGroundFace(newarea, parm2);
+ if (face)
+ {
+ AAS_ShowFace(face - aasworld.faces);
+ } //end if*/
+ /*
+ AAS_ClearShownDebugLines();
+ AAS_ShowArea(newarea, parm0 & BUTTON_USE);
+ AAS_ShowReachableAreas(area);
+ */
+ AAS_ClearShownPolygons();
+ AAS_ClearShownDebugLines();
+ AAS_ShowAreaPolygons(newarea, 1, parm0 & 4);
+ if (parm0 & 2) AAS_ShowReachableAreas(area);
+ else
+ {
+ static int lastgoalareanum, lastareanum;
+ static int avoidreach[MAX_AVOIDREACH];
+ static float avoidreachtimes[MAX_AVOIDREACH];
+ static int avoidreachtries[MAX_AVOIDREACH];
+ int reachnum, resultFlags;
+ bot_goal_t goal;
+ aas_reachability_t reach;
+
+ /*
+ goal.areanum = botlibglobals.goalareanum;
+ VectorCopy(botlibglobals.goalorigin, goal.origin);
+ reachnum = BotGetReachabilityToGoal(origin, newarea,
+ lastgoalareanum, lastareanum,
+ avoidreach, avoidreachtimes, avoidreachtries,
+ &goal, TFL_DEFAULT|TFL_FUNCBOB|TFL_ROCKETJUMP, TFL_DEFAULT|TFL_FUNCBOB|TFL_ROCKETJUMP,
+ NULL, 0, &resultFlags);
+ AAS_ReachabilityFromNum(reachnum, &reach);
+ AAS_ShowReachability(&reach);
+ */
+ int curarea;
+ vec3_t curorigin;
+
+ goal.areanum = botlibglobals.goalareanum;
+ VectorCopy(botlibglobals.goalorigin, goal.origin);
+ VectorCopy(origin, curorigin);
+ curarea = newarea;
+ for ( i = 0; i < 100; i++ ) {
+ if ( curarea == goal.areanum ) {
+ break;
+ }
+ reachnum = BotGetReachabilityToGoal(curorigin, curarea,
+ lastgoalareanum, lastareanum,
+ avoidreach, avoidreachtimes, avoidreachtries,
+ &goal, TFL_DEFAULT|TFL_FUNCBOB|TFL_ROCKETJUMP, TFL_DEFAULT|TFL_FUNCBOB|TFL_ROCKETJUMP,
+ NULL, 0, &resultFlags);
+ AAS_ReachabilityFromNum(reachnum, &reach);
+ AAS_ShowReachability(&reach);
+ VectorCopy(reach.end, origin);
+ lastareanum = curarea;
+ curarea = reach.areanum;
+ }
+ } //end else
+ VectorClear(forward);
+ //BotGapDistance(origin, forward, 0);
+ /*
+ if (parm0 & BUTTON_USE)
+ {
+ botimport.Print(PRT_MESSAGE, "test rj from 703 to 716\n");
+ AAS_Reachability_WeaponJump(703, 716);
+ } //end if*/
+
+ AngleVectors(parm3, forward, right, NULL);
+ //get the eye 16 units to the right of the origin
+ VectorMA(parm2, 8, right, eye);
+ //get the eye 24 units up
+ eye[2] += 24;
+ //get the end point for the line to be traced
+ VectorMA(eye, 800, forward, end);
+
+// AAS_TestMovementPrediction(1, parm2, forward);
+/*
+ //trace the line to find the hit point
+ trace = AAS_TraceClientBBox(eye, end, PRESENCE_NORMAL, 1);
+ if (!line[0]) line[0] = botimport.DebugLineCreate();
+ botimport.DebugLineShow(line[0], eye, trace.endpos, LINECOLOR_BLUE);
+ //
+ AAS_ClearShownDebugLines();
+ if (trace.ent)
+ {
+ ent = &aasworld.entities[trace.ent];
+ AAS_ShowBoundingBox(ent->origin, ent->mins, ent->maxs);
+ } //end if
+*/
+
+/*
+ start_time = clock();
+ for (i = 0; i < 2000; i++)
+ {
+ AAS_Trace2(eye, mins, maxs, end, 1, MASK_PLAYERSOLID);
+// AAS_TraceClientBBox(eye, end, PRESENCE_NORMAL, 1);
+ } //end for
+ end_time = clock();
+ botimport.Print(PRT_MESSAGE, "me %lu clocks, %lu CLOCKS_PER_SEC\n", end_time - start_time, CLOCKS_PER_SEC);
+ start_time = clock();
+ for (i = 0; i < 2000; i++)
+ {
+ AAS_Trace(eye, mins, maxs, end, 1, MASK_PLAYERSOLID);
+ } //end for
+ end_time = clock();
+ botimport.Print(PRT_MESSAGE, "id %lu clocks, %lu CLOCKS_PER_SEC\n", end_time - start_time, CLOCKS_PER_SEC);
+*/
+
+ // TTimo: nested comments are BAD for gcc -Werror, use #if 0 instead..
+#if 0
+ AAS_ClearShownDebugLines();
+ //bsptrace = AAS_Trace(eye, NULL, NULL, end, 1, MASK_PLAYERSOLID);
+ bsptrace = AAS_Trace(eye, mins, maxs, end, 1, MASK_PLAYERSOLID);
+ if (!line[0]) line[0] = botimport.DebugLineCreate();
+ botimport.DebugLineShow(line[0], eye, bsptrace.endpos, LINECOLOR_YELLOW);
+ if (bsptrace.fraction < 1.0)
+ {
+ face = AAS_TraceEndFace(&trace);
+ if (face)
+ {
+ AAS_ShowFace(face - aasworld.faces);
+ } //end if
+
+ AAS_DrawPlaneCross(bsptrace.endpos,
+ bsptrace.plane.normal,
+ bsptrace.plane.dist + bsptrace.exp_dist,
+ bsptrace.plane.type, LINECOLOR_GREEN);
+ if (trace.ent)
+ {
+ ent = &aasworld.entities[trace.ent];
+ AAS_ShowBoundingBox(ent->origin, ent->mins, ent->maxs);
+ } //end if
+ } //end if
+ //bsptrace = AAS_Trace2(eye, NULL, NULL, end, 1, MASK_PLAYERSOLID);
+ bsptrace = AAS_Trace2(eye, mins, maxs, end, 1, MASK_PLAYERSOLID);
+ botimport.DebugLineShow(line[1], eye, bsptrace.endpos, LINECOLOR_BLUE);
+ if (bsptrace.fraction < 1.0)
+ {
+ AAS_DrawPlaneCross(bsptrace.endpos,
+ bsptrace.plane.normal,
+ bsptrace.plane.dist,// + bsptrace.exp_dist,
+ bsptrace.plane.type, LINECOLOR_RED);
+ if (bsptrace.ent)
+ {
+ ent = &aasworld.entities[bsptrace.ent];
+ AAS_ShowBoundingBox(ent->origin, ent->mins, ent->maxs);
+ } //end if
+ } //end if
+#endif
+#endif
+ return 0;
+} //end of the function BotExportTest
+
+
+/*
+============
+Init_AAS_Export
+============
+*/
+static void Init_AAS_Export( aas_export_t *aas ) {
+ //--------------------------------------------
+ // be_aas_entity.c
+ //--------------------------------------------
+ aas->AAS_EntityInfo = AAS_EntityInfo;
+ //--------------------------------------------
+ // be_aas_main.c
+ //--------------------------------------------
+ aas->AAS_Initialized = AAS_Initialized;
+ aas->AAS_PresenceTypeBoundingBox = AAS_PresenceTypeBoundingBox;
+ aas->AAS_Time = AAS_Time;
+ //--------------------------------------------
+ // be_aas_sample.c
+ //--------------------------------------------
+ aas->AAS_PointAreaNum = AAS_PointAreaNum;
+ aas->AAS_PointReachabilityAreaIndex = AAS_PointReachabilityAreaIndex;
+ aas->AAS_TraceAreas = AAS_TraceAreas;
+ aas->AAS_BBoxAreas = AAS_BBoxAreas;
+ aas->AAS_AreaInfo = AAS_AreaInfo;
+ //--------------------------------------------
+ // be_aas_bspq3.c
+ //--------------------------------------------
+ aas->AAS_PointContents = AAS_PointContents;
+ aas->AAS_NextBSPEntity = AAS_NextBSPEntity;
+ aas->AAS_ValueForBSPEpairKey = AAS_ValueForBSPEpairKey;
+ aas->AAS_VectorForBSPEpairKey = AAS_VectorForBSPEpairKey;
+ aas->AAS_FloatForBSPEpairKey = AAS_FloatForBSPEpairKey;
+ aas->AAS_IntForBSPEpairKey = AAS_IntForBSPEpairKey;
+ //--------------------------------------------
+ // be_aas_reach.c
+ //--------------------------------------------
+ aas->AAS_AreaReachability = AAS_AreaReachability;
+ //--------------------------------------------
+ // be_aas_route.c
+ //--------------------------------------------
+ aas->AAS_AreaTravelTimeToGoalArea = AAS_AreaTravelTimeToGoalArea;
+ aas->AAS_EnableRoutingArea = AAS_EnableRoutingArea;
+ aas->AAS_PredictRoute = AAS_PredictRoute;
+ //--------------------------------------------
+ // be_aas_altroute.c
+ //--------------------------------------------
+ aas->AAS_AlternativeRouteGoals = AAS_AlternativeRouteGoals;
+ //--------------------------------------------
+ // be_aas_move.c
+ //--------------------------------------------
+ aas->AAS_Swimming = AAS_Swimming;
+ aas->AAS_PredictClientMovement = AAS_PredictClientMovement;
+}
+
+
+/*
+============
+Init_EA_Export
+============
+*/
+static void Init_EA_Export( ea_export_t *ea ) {
+ //ClientCommand elementary actions
+ ea->EA_Command = EA_Command;
+ ea->EA_Say = EA_Say;
+ ea->EA_SayTeam = EA_SayTeam;
+
+ ea->EA_Action = EA_Action;
+ ea->EA_Gesture = EA_Gesture;
+ ea->EA_Talk = EA_Talk;
+ ea->EA_Attack = EA_Attack;
+ ea->EA_Use = EA_Use;
+ ea->EA_Respawn = EA_Respawn;
+ ea->EA_Crouch = EA_Crouch;
+ ea->EA_MoveUp = EA_MoveUp;
+ ea->EA_MoveDown = EA_MoveDown;
+ ea->EA_MoveForward = EA_MoveForward;
+ ea->EA_MoveBack = EA_MoveBack;
+ ea->EA_MoveLeft = EA_MoveLeft;
+ ea->EA_MoveRight = EA_MoveRight;
+
+ ea->EA_SelectWeapon = EA_SelectWeapon;
+ ea->EA_Jump = EA_Jump;
+ ea->EA_DelayedJump = EA_DelayedJump;
+ ea->EA_Move = EA_Move;
+ ea->EA_View = EA_View;
+ ea->EA_GetInput = EA_GetInput;
+ ea->EA_EndRegular = EA_EndRegular;
+ ea->EA_ResetInput = EA_ResetInput;
+}
+
+
+/*
+============
+Init_AI_Export
+============
+*/
+static void Init_AI_Export( ai_export_t *ai ) {
+ //-----------------------------------
+ // be_ai_char.h
+ //-----------------------------------
+ ai->BotLoadCharacter = BotLoadCharacter;
+ ai->BotFreeCharacter = BotFreeCharacter;
+ ai->Characteristic_Float = Characteristic_Float;
+ ai->Characteristic_BFloat = Characteristic_BFloat;
+ ai->Characteristic_Integer = Characteristic_Integer;
+ ai->Characteristic_BInteger = Characteristic_BInteger;
+ ai->Characteristic_String = Characteristic_String;
+ //-----------------------------------
+ // be_ai_chat.h
+ //-----------------------------------
+ ai->BotAllocChatState = BotAllocChatState;
+ ai->BotFreeChatState = BotFreeChatState;
+ ai->BotQueueConsoleMessage = BotQueueConsoleMessage;
+ ai->BotRemoveConsoleMessage = BotRemoveConsoleMessage;
+ ai->BotNextConsoleMessage = BotNextConsoleMessage;
+ ai->BotNumConsoleMessages = BotNumConsoleMessages;
+ ai->BotInitialChat = BotInitialChat;
+ ai->BotNumInitialChats = BotNumInitialChats;
+ ai->BotReplyChat = BotReplyChat;
+ ai->BotChatLength = BotChatLength;
+ ai->BotEnterChat = BotEnterChat;
+ ai->BotGetChatMessage = BotGetChatMessage;
+ ai->StringContains = StringContains;
+ ai->BotFindMatch = BotFindMatch;
+ ai->BotMatchVariable = BotMatchVariable;
+ ai->UnifyWhiteSpaces = UnifyWhiteSpaces;
+ ai->BotReplaceSynonyms = BotReplaceSynonyms;
+ ai->BotLoadChatFile = BotLoadChatFile;
+ ai->BotSetChatGender = BotSetChatGender;
+ ai->BotSetChatName = BotSetChatName;
+ //-----------------------------------
+ // be_ai_goal.h
+ //-----------------------------------
+ ai->BotResetGoalState = BotResetGoalState;
+ ai->BotResetAvoidGoals = BotResetAvoidGoals;
+ ai->BotRemoveFromAvoidGoals = BotRemoveFromAvoidGoals;
+ ai->BotPushGoal = BotPushGoal;
+ ai->BotPopGoal = BotPopGoal;
+ ai->BotEmptyGoalStack = BotEmptyGoalStack;
+ ai->BotDumpAvoidGoals = BotDumpAvoidGoals;
+ ai->BotDumpGoalStack = BotDumpGoalStack;
+ ai->BotGoalName = BotGoalName;
+ ai->BotGetTopGoal = BotGetTopGoal;
+ ai->BotGetSecondGoal = BotGetSecondGoal;
+ ai->BotChooseLTGItem = BotChooseLTGItem;
+ ai->BotChooseNBGItem = BotChooseNBGItem;
+ ai->BotTouchingGoal = BotTouchingGoal;
+ ai->BotItemGoalInVisButNotVisible = BotItemGoalInVisButNotVisible;
+ ai->BotGetLevelItemGoal = BotGetLevelItemGoal;
+ ai->BotGetNextCampSpotGoal = BotGetNextCampSpotGoal;
+ ai->BotGetMapLocationGoal = BotGetMapLocationGoal;
+ ai->BotAvoidGoalTime = BotAvoidGoalTime;
+ ai->BotSetAvoidGoalTime = BotSetAvoidGoalTime;
+ ai->BotInitLevelItems = BotInitLevelItems;
+ ai->BotUpdateEntityItems = BotUpdateEntityItems;
+ ai->BotLoadItemWeights = BotLoadItemWeights;
+ ai->BotFreeItemWeights = BotFreeItemWeights;
+ ai->BotInterbreedGoalFuzzyLogic = BotInterbreedGoalFuzzyLogic;
+ ai->BotSaveGoalFuzzyLogic = BotSaveGoalFuzzyLogic;
+ ai->BotMutateGoalFuzzyLogic = BotMutateGoalFuzzyLogic;
+ ai->BotAllocGoalState = BotAllocGoalState;
+ ai->BotFreeGoalState = BotFreeGoalState;
+ //-----------------------------------
+ // be_ai_move.h
+ //-----------------------------------
+ ai->BotResetMoveState = BotResetMoveState;
+ ai->BotMoveToGoal = BotMoveToGoal;
+ ai->BotMoveInDirection = BotMoveInDirection;
+ ai->BotResetAvoidReach = BotResetAvoidReach;
+ ai->BotResetLastAvoidReach = BotResetLastAvoidReach;
+ ai->BotReachabilityArea = BotReachabilityArea;
+ ai->BotMovementViewTarget = BotMovementViewTarget;
+ ai->BotPredictVisiblePosition = BotPredictVisiblePosition;
+ ai->BotAllocMoveState = BotAllocMoveState;
+ ai->BotFreeMoveState = BotFreeMoveState;
+ ai->BotInitMoveState = BotInitMoveState;
+ ai->BotAddAvoidSpot = BotAddAvoidSpot;
+ //-----------------------------------
+ // be_ai_weap.h
+ //-----------------------------------
+ ai->BotChooseBestFightWeapon = BotChooseBestFightWeapon;
+ ai->BotGetWeaponInfo = BotGetWeaponInfo;
+ ai->BotLoadWeaponWeights = BotLoadWeaponWeights;
+ ai->BotAllocWeaponState = BotAllocWeaponState;
+ ai->BotFreeWeaponState = BotFreeWeaponState;
+ ai->BotResetWeaponState = BotResetWeaponState;
+ //-----------------------------------
+ // be_ai_gen.h
+ //-----------------------------------
+ ai->GeneticParentsAndChildSelection = GeneticParentsAndChildSelection;
+}
+
+
+/*
+============
+GetBotLibAPI
+============
+*/
+botlib_export_t *GetBotLibAPI(int apiVersion, botlib_import_t *import) {
+ assert(import); // bk001129 - this wasn't set for baseq3/
+ botimport = *import;
+ assert(botimport.Print); // bk001129 - pars pro toto
+
+ Com_Memset( &be_botlib_export, 0, sizeof( be_botlib_export ) );
+
+ if ( apiVersion != BOTLIB_API_VERSION ) {
+ botimport.Print( PRT_ERROR, "Mismatched BOTLIB_API_VERSION: expected %i, got %i\n", BOTLIB_API_VERSION, apiVersion );
+ return NULL;
+ }
+
+ Init_AAS_Export(&be_botlib_export.aas);
+ Init_EA_Export(&be_botlib_export.ea);
+ Init_AI_Export(&be_botlib_export.ai);
+
+ be_botlib_export.BotLibSetup = Export_BotLibSetup;
+ be_botlib_export.BotLibShutdown = Export_BotLibShutdown;
+ be_botlib_export.BotLibVarSet = Export_BotLibVarSet;
+ be_botlib_export.BotLibVarGet = Export_BotLibVarGet;
+
+ be_botlib_export.PC_AddGlobalDefine = PC_AddGlobalDefine;
+ be_botlib_export.PC_LoadSourceHandle = PC_LoadSourceHandle;
+ be_botlib_export.PC_FreeSourceHandle = PC_FreeSourceHandle;
+ be_botlib_export.PC_ReadTokenHandle = PC_ReadTokenHandle;
+ be_botlib_export.PC_SourceFileAndLine = PC_SourceFileAndLine;
+
+ be_botlib_export.BotLibStartFrame = Export_BotLibStartFrame;
+ be_botlib_export.BotLibLoadMap = Export_BotLibLoadMap;
+ be_botlib_export.BotLibUpdateEntity = Export_BotLibUpdateEntity;
+ be_botlib_export.Test = BotExportTest;
+
+ return &be_botlib_export;
+}
diff --git a/code/botlib/be_interface.h b/code/botlib/be_interface.h
new file mode 100755
index 0000000..a9f6347
--- /dev/null
+++ b/code/botlib/be_interface.h
@@ -0,0 +1,57 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: be_interface.h
+ *
+ * desc: botlib interface
+ *
+ * $Archive: /source/code/botlib/be_interface.h $
+ *
+ *****************************************************************************/
+
+//#define DEBUG //debug code
+#define RANDOMIZE //randomize bot behaviour
+
+//FIXME: get rid of this global structure
+typedef struct botlib_globals_s
+{
+ int botlibsetup; //true when the bot library has been setup
+ int maxentities; //maximum number of entities
+ int maxclients; //maximum number of clients
+ float time; //the global time
+#ifdef DEBUG
+ qboolean debug; //true if debug is on
+ int goalareanum;
+ vec3_t goalorigin;
+ int runai;
+#endif
+} botlib_globals_t;
+
+
+extern botlib_globals_t botlibglobals;
+extern botlib_import_t botimport;
+extern int bot_developer; //true if developer is on
+
+//
+int Sys_MilliSeconds(void);
+
diff --git a/code/botlib/botlib.vcproj b/code/botlib/botlib.vcproj
new file mode 100755
index 0000000..e544a14
--- /dev/null
+++ b/code/botlib/botlib.vcproj
@@ -0,0 +1,1559 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+ ProjectType="Visual C++"
+ Version="7.10"
+ Name="botlib"
+ SccProjectName="&quot;$/MissionPack/code/botlib&quot;, HBAAAAAA"
+ SccLocalPath=".">
+ <Platforms>
+ <Platform
+ Name="Win32"/>
+ </Platforms>
+ <Configurations>
+ <Configuration
+ Name="Debug TA|Win32"
+ OutputDirectory=".\Debug_TA"
+ IntermediateDirectory=".\Debug_TA"
+ ConfigurationType="4"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ OptimizeForProcessor="1"
+ PreprocessorDefinitions="WIN32;_DEBUG;_LIB;BOTLIB;DEBUG"
+ BasicRuntimeChecks="3"
+ RuntimeLibrary="1"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Debug_TA/botlib.pch"
+ AssemblerListingLocation=".\Debug_TA/"
+ ObjectFile=".\Debug_TA/"
+ ProgramDataBaseFileName=".\Debug_TA/"
+ BrowseInformation="1"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile=".\Debug_TA\botlib.lib"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCMIDLTool"/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Release|Win32"
+ OutputDirectory=".\Release"
+ IntermediateDirectory=".\Release"
+ ConfigurationType="4"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ OptimizeForProcessor="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_LIB;BOTLIB"
+ StringPooling="TRUE"
+ RuntimeLibrary="4"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Release/botlib.pch"
+ AssemblerListingLocation=".\Release/"
+ ObjectFile=".\Release/"
+ ProgramDataBaseFileName=".\Release/"
+ WarningLevel="4"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile=".\Release\botlib.lib"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCMIDLTool"/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="vector|Win32"
+ OutputDirectory=".\botlib___Win32_vector0"
+ IntermediateDirectory=".\botlib___Win32_vector0"
+ ConfigurationType="4"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalOptions="/vec /vec:stats /vec:pii /vec:o10 /vec:yes "
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ OptimizeForProcessor="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_LIB;BOTLIB"
+ StringPooling="TRUE"
+ RuntimeLibrary="4"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\botlib___Win32_vector0/botlib.pch"
+ AssemblerListingLocation=".\botlib___Win32_vector0/"
+ ObjectFile=".\botlib___Win32_vector0/"
+ ProgramDataBaseFileName=".\botlib___Win32_vector0/"
+ WarningLevel="4"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile=".\botlib___Win32_vector0\botlib.lib"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCMIDLTool"/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Debug|Win32"
+ OutputDirectory=".\Debug"
+ IntermediateDirectory=".\Debug"
+ ConfigurationType="4"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ OptimizeForProcessor="1"
+ PreprocessorDefinitions="WIN32;_DEBUG;_LIB;BOTLIB;DEBUG"
+ BasicRuntimeChecks="3"
+ RuntimeLibrary="1"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Debug/botlib.pch"
+ AssemblerListingLocation=".\Debug/"
+ ObjectFile=".\Debug/"
+ ProgramDataBaseFileName=".\Debug/"
+ BrowseInformation="1"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile=".\Debug\botlib.lib"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCMIDLTool"/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Release TA|Win32"
+ OutputDirectory=".\Release_TA"
+ IntermediateDirectory=".\Release_TA"
+ ConfigurationType="4"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ OptimizeForProcessor="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_LIB;BOTLIB"
+ StringPooling="TRUE"
+ RuntimeLibrary="4"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Release_TA/botlib.pch"
+ AssemblerListingLocation=".\Release_TA/"
+ ObjectFile=".\Release_TA/"
+ ProgramDataBaseFileName=".\Release_TA/"
+ WarningLevel="4"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile=".\Release_TA\botlib.lib"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCMIDLTool"/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ </Configurations>
+ <References>
+ </References>
+ <Files>
+ <Filter
+ Name="Source Files"
+ Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat">
+ <File
+ RelativePath="be_aas_bspq3.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="be_aas_cluster.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="be_aas_debug.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="be_aas_entity.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="be_aas_file.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="be_aas_main.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="be_aas_move.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="be_aas_optimize.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="be_aas_reach.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="be_aas_route.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="be_aas_routealt.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="be_aas_sample.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="be_ai_char.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="be_ai_chat.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="be_ai_gen.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="be_ai_goal.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="be_ai_move.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="be_ai_weap.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="be_ai_weight.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="be_ea.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="be_interface.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="l_crc.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="l_libvar.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="l_log.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="l_memory.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="l_precomp.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="l_script.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="l_struct.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <Filter
+ Name="Header Files"
+ Filter="h;hpp;hxx;hm;inl">
+ <File
+ RelativePath="aasfile.h">
+ </File>
+ <File
+ RelativePath="be_aas_bsp.h">
+ </File>
+ <File
+ RelativePath="be_aas_cluster.h">
+ </File>
+ <File
+ RelativePath="be_aas_debug.h">
+ </File>
+ <File
+ RelativePath="be_aas_def.h">
+ </File>
+ <File
+ RelativePath="be_aas_entity.h">
+ </File>
+ <File
+ RelativePath="be_aas_file.h">
+ </File>
+ <File
+ RelativePath="be_aas_funcs.h">
+ </File>
+ <File
+ RelativePath="be_aas_main.h">
+ </File>
+ <File
+ RelativePath="be_aas_move.h">
+ </File>
+ <File
+ RelativePath="be_aas_optimize.h">
+ </File>
+ <File
+ RelativePath="be_aas_reach.h">
+ </File>
+ <File
+ RelativePath="be_aas_route.h">
+ </File>
+ <File
+ RelativePath="be_aas_routealt.h">
+ </File>
+ <File
+ RelativePath="be_aas_sample.h">
+ </File>
+ <File
+ RelativePath="be_ai_weight.h">
+ </File>
+ <File
+ RelativePath="be_interface.h">
+ </File>
+ <File
+ RelativePath="..\game\bg_public.h">
+ </File>
+ <File
+ RelativePath="..\qcommon\cm_public.h">
+ </File>
+ <File
+ RelativePath="..\game\g_public.h">
+ </File>
+ <File
+ RelativePath="l_crc.h">
+ </File>
+ <File
+ RelativePath="l_libvar.h">
+ </File>
+ <File
+ RelativePath="l_log.h">
+ </File>
+ <File
+ RelativePath="l_memory.h">
+ </File>
+ <File
+ RelativePath="l_precomp.h">
+ </File>
+ <File
+ RelativePath="l_script.h">
+ </File>
+ <File
+ RelativePath="l_struct.h">
+ </File>
+ <File
+ RelativePath="l_utils.h">
+ </File>
+ <File
+ RelativePath="..\game\q_shared.h">
+ </File>
+ <File
+ RelativePath="..\qcommon\qcommon.h">
+ </File>
+ <File
+ RelativePath="..\qcommon\qfiles.h">
+ </File>
+ <File
+ RelativePath="..\server\server.h">
+ </File>
+ <File
+ RelativePath="..\game\surfaceflags.h">
+ </File>
+ </Filter>
+ </Files>
+ <Globals>
+ </Globals>
+</VisualStudioProject>
diff --git a/code/botlib/l_crc.c b/code/botlib/l_crc.c
new file mode 100755
index 0000000..9a945f5
--- /dev/null
+++ b/code/botlib/l_crc.c
@@ -0,0 +1,151 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: l_crc.c
+ *
+ * desc: CRC calculation
+ *
+ * $Archive: /MissionPack/CODE/botlib/l_crc.c $
+ *
+ *****************************************************************************/
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "../game/q_shared.h"
+#include "../game/botlib.h"
+#include "be_interface.h" //for botimport.Print
+
+
+// FIXME: byte swap?
+
+// this is a 16 bit, non-reflected CRC using the polynomial 0x1021
+// and the initial and final xor values shown below... in other words, the
+// CCITT standard CRC used by XMODEM
+
+#define CRC_INIT_VALUE 0xffff
+#define CRC_XOR_VALUE 0x0000
+
+unsigned short crctable[257] =
+{
+ 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
+ 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
+ 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
+ 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
+ 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
+ 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
+ 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
+ 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
+ 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
+ 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
+ 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
+ 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
+ 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
+ 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
+ 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
+ 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
+ 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
+ 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
+ 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
+ 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
+ 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
+ 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
+ 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
+ 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
+ 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
+ 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
+ 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
+ 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
+ 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
+ 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
+ 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
+ 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0
+};
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void CRC_Init(unsigned short *crcvalue)
+{
+ *crcvalue = CRC_INIT_VALUE;
+} //end of the function CRC_Init
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void CRC_ProcessByte(unsigned short *crcvalue, byte data)
+{
+ *crcvalue = (*crcvalue << 8) ^ crctable[(*crcvalue >> 8) ^ data];
+} //end of the function CRC_ProcessByte
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+unsigned short CRC_Value(unsigned short crcvalue)
+{
+ return crcvalue ^ CRC_XOR_VALUE;
+} //end of the function CRC_Value
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+unsigned short CRC_ProcessString(unsigned char *data, int length)
+{
+ unsigned short crcvalue;
+ int i, ind;
+
+ CRC_Init(&crcvalue);
+
+ for (i = 0; i < length; i++)
+ {
+ ind = (crcvalue >> 8) ^ data[i];
+ if (ind < 0 || ind > 256) ind = 0;
+ crcvalue = (crcvalue << 8) ^ crctable[ind];
+ } //end for
+ return CRC_Value(crcvalue);
+} //end of the function CRC_ProcessString
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void CRC_ContinueProcessString(unsigned short *crc, char *data, int length)
+{
+ int i;
+
+ for (i = 0; i < length; i++)
+ {
+ *crc = (*crc << 8) ^ crctable[(*crc >> 8) ^ data[i]];
+ } //end for
+} //end of the function CRC_ProcessString
diff --git a/code/botlib/l_crc.h b/code/botlib/l_crc.h
new file mode 100755
index 0000000..3f37cd4
--- /dev/null
+++ b/code/botlib/l_crc.h
@@ -0,0 +1,29 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+typedef unsigned short crc_t;
+
+void CRC_Init(unsigned short *crcvalue);
+void CRC_ProcessByte(unsigned short *crcvalue, byte data);
+unsigned short CRC_Value(unsigned short crcvalue);
+unsigned short CRC_ProcessString(unsigned char *data, int length);
+void CRC_ContinueProcessString(unsigned short *crc, char *data, int length);
diff --git a/code/botlib/l_libvar.c b/code/botlib/l_libvar.c
new file mode 100755
index 0000000..d7ac798
--- /dev/null
+++ b/code/botlib/l_libvar.c
@@ -0,0 +1,294 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: l_libvar.c
+ *
+ * desc: bot library variables
+ *
+ * $Archive: /MissionPack/code/botlib/l_libvar.c $
+ *
+ *****************************************************************************/
+
+#include "../game/q_shared.h"
+#include "l_memory.h"
+#include "l_libvar.h"
+
+//list with library variables
+libvar_t *libvarlist;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float LibVarStringValue(char *string)
+{
+ int dotfound = 0;
+ float value = 0;
+
+ while(*string)
+ {
+ if (*string < '0' || *string > '9')
+ {
+ if (dotfound || *string != '.')
+ {
+ return 0;
+ } //end if
+ else
+ {
+ dotfound = 10;
+ string++;
+ } //end if
+ } //end if
+ if (dotfound)
+ {
+ value = value + (float) (*string - '0') / (float) dotfound;
+ dotfound *= 10;
+ } //end if
+ else
+ {
+ value = value * 10.0 + (float) (*string - '0');
+ } //end else
+ string++;
+ } //end while
+ return value;
+} //end of the function LibVarStringValue
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+libvar_t *LibVarAlloc(char *var_name)
+{
+ libvar_t *v;
+
+ v = (libvar_t *) GetMemory(sizeof(libvar_t) + strlen(var_name) + 1);
+ Com_Memset(v, 0, sizeof(libvar_t));
+ v->name = (char *) v + sizeof(libvar_t);
+ strcpy(v->name, var_name);
+ //add the variable in the list
+ v->next = libvarlist;
+ libvarlist = v;
+ return v;
+} //end of the function LibVarAlloc
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void LibVarDeAlloc(libvar_t *v)
+{
+ if (v->string) FreeMemory(v->string);
+ FreeMemory(v);
+} //end of the function LibVarDeAlloc
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void LibVarDeAllocAll(void)
+{
+ libvar_t *v;
+
+ for (v = libvarlist; v; v = libvarlist)
+ {
+ libvarlist = libvarlist->next;
+ LibVarDeAlloc(v);
+ } //end for
+ libvarlist = NULL;
+} //end of the function LibVarDeAllocAll
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+libvar_t *LibVarGet(char *var_name)
+{
+ libvar_t *v;
+
+ for (v = libvarlist; v; v = v->next)
+ {
+ if (!Q_stricmp(v->name, var_name))
+ {
+ return v;
+ } //end if
+ } //end for
+ return NULL;
+} //end of the function LibVarGet
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+char *LibVarGetString(char *var_name)
+{
+ libvar_t *v;
+
+ v = LibVarGet(var_name);
+ if (v)
+ {
+ return v->string;
+ } //end if
+ else
+ {
+ return "";
+ } //end else
+} //end of the function LibVarGetString
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float LibVarGetValue(char *var_name)
+{
+ libvar_t *v;
+
+ v = LibVarGet(var_name);
+ if (v)
+ {
+ return v->value;
+ } //end if
+ else
+ {
+ return 0;
+ } //end else
+} //end of the function LibVarGetValue
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+libvar_t *LibVar(char *var_name, char *value)
+{
+ libvar_t *v;
+ v = LibVarGet(var_name);
+ if (v) return v;
+ //create new variable
+ v = LibVarAlloc(var_name);
+ //variable string
+ v->string = (char *) GetMemory(strlen(value) + 1);
+ strcpy(v->string, value);
+ //the value
+ v->value = LibVarStringValue(v->string);
+ //variable is modified
+ v->modified = qtrue;
+ //
+ return v;
+} //end of the function LibVar
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+char *LibVarString(char *var_name, char *value)
+{
+ libvar_t *v;
+
+ v = LibVar(var_name, value);
+ return v->string;
+} //end of the function LibVarString
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float LibVarValue(char *var_name, char *value)
+{
+ libvar_t *v;
+
+ v = LibVar(var_name, value);
+ return v->value;
+} //end of the function LibVarValue
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void LibVarSet(char *var_name, char *value)
+{
+ libvar_t *v;
+
+ v = LibVarGet(var_name);
+ if (v)
+ {
+ FreeMemory(v->string);
+ } //end if
+ else
+ {
+ v = LibVarAlloc(var_name);
+ } //end else
+ //variable string
+ v->string = (char *) GetMemory(strlen(value) + 1);
+ strcpy(v->string, value);
+ //the value
+ v->value = LibVarStringValue(v->string);
+ //variable is modified
+ v->modified = qtrue;
+} //end of the function LibVarSet
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean LibVarChanged(char *var_name)
+{
+ libvar_t *v;
+
+ v = LibVarGet(var_name);
+ if (v)
+ {
+ return v->modified;
+ } //end if
+ else
+ {
+ return qfalse;
+ } //end else
+} //end of the function LibVarChanged
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void LibVarSetNotModified(char *var_name)
+{
+ libvar_t *v;
+
+ v = LibVarGet(var_name);
+ if (v)
+ {
+ v->modified = qfalse;
+ } //end if
+} //end of the function LibVarSetNotModified
diff --git a/code/botlib/l_libvar.h b/code/botlib/l_libvar.h
new file mode 100755
index 0000000..79fc65e
--- /dev/null
+++ b/code/botlib/l_libvar.h
@@ -0,0 +1,63 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: l_libvar.h
+ *
+ * desc: botlib vars
+ *
+ * $Archive: /source/code/botlib/l_libvar.h $
+ *
+ *****************************************************************************/
+
+//library variable
+typedef struct libvar_s
+{
+ char *name;
+ char *string;
+ int flags;
+ qboolean modified; // set each time the cvar is changed
+ float value;
+ struct libvar_s *next;
+} libvar_t;
+
+//removes all library variables
+void LibVarDeAllocAll(void);
+//gets the library variable with the given name
+libvar_t *LibVarGet(char *var_name);
+//gets the string of the library variable with the given name
+char *LibVarGetString(char *var_name);
+//gets the value of the library variable with the given name
+float LibVarGetValue(char *var_name);
+//creates the library variable if not existing already and returns it
+libvar_t *LibVar(char *var_name, char *value);
+//creates the library variable if not existing already and returns the value
+float LibVarValue(char *var_name, char *value);
+//creates the library variable if not existing already and returns the value string
+char *LibVarString(char *var_name, char *value);
+//sets the library variable
+void LibVarSet(char *var_name, char *value);
+//returns true if the library variable has been modified
+qboolean LibVarChanged(char *var_name);
+//sets the library variable to unmodified
+void LibVarSetNotModified(char *var_name);
+
diff --git a/code/botlib/l_log.c b/code/botlib/l_log.c
new file mode 100755
index 0000000..d532c8c
--- /dev/null
+++ b/code/botlib/l_log.c
@@ -0,0 +1,169 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: l_log.c
+ *
+ * desc: log file
+ *
+ * $Archive: /MissionPack/CODE/botlib/l_log.c $
+ *
+ *****************************************************************************/
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "../game/q_shared.h"
+#include "../game/botlib.h"
+#include "be_interface.h" //for botimport.Print
+#include "l_libvar.h"
+
+#define MAX_LOGFILENAMESIZE 1024
+
+typedef struct logfile_s
+{
+ char filename[MAX_LOGFILENAMESIZE];
+ FILE *fp;
+ int numwrites;
+} logfile_t;
+
+static logfile_t logfile;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Log_Open(char *filename)
+{
+ if (!LibVarValue("log", "0")) return;
+ if (!filename || !strlen(filename))
+ {
+ botimport.Print(PRT_MESSAGE, "openlog <filename>\n");
+ return;
+ } //end if
+ if (logfile.fp)
+ {
+ botimport.Print(PRT_ERROR, "log file %s is already opened\n", logfile.filename);
+ return;
+ } //end if
+ logfile.fp = fopen(filename, "wb");
+ if (!logfile.fp)
+ {
+ botimport.Print(PRT_ERROR, "can't open the log file %s\n", filename);
+ return;
+ } //end if
+ strncpy(logfile.filename, filename, MAX_LOGFILENAMESIZE);
+ botimport.Print(PRT_MESSAGE, "Opened log %s\n", logfile.filename);
+} //end of the function Log_Create
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Log_Close(void)
+{
+ if (!logfile.fp) return;
+ if (fclose(logfile.fp))
+ {
+ botimport.Print(PRT_ERROR, "can't close log file %s\n", logfile.filename);
+ return;
+ } //end if
+ logfile.fp = NULL;
+ botimport.Print(PRT_MESSAGE, "Closed log %s\n", logfile.filename);
+} //end of the function Log_Close
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Log_Shutdown(void)
+{
+ if (logfile.fp) Log_Close();
+} //end of the function Log_Shutdown
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void QDECL Log_Write(char *fmt, ...)
+{
+ va_list ap;
+
+ if (!logfile.fp) return;
+ va_start(ap, fmt);
+ vfprintf(logfile.fp, fmt, ap);
+ va_end(ap);
+ //fprintf(logfile.fp, "\r\n");
+ fflush(logfile.fp);
+} //end of the function Log_Write
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void QDECL Log_WriteTimeStamped(char *fmt, ...)
+{
+ va_list ap;
+
+ if (!logfile.fp) return;
+ fprintf(logfile.fp, "%d %02d:%02d:%02d:%02d ",
+ logfile.numwrites,
+ (int) (botlibglobals.time / 60 / 60),
+ (int) (botlibglobals.time / 60),
+ (int) (botlibglobals.time),
+ (int) ((int) (botlibglobals.time * 100)) -
+ ((int) botlibglobals.time) * 100);
+ va_start(ap, fmt);
+ vfprintf(logfile.fp, fmt, ap);
+ va_end(ap);
+ fprintf(logfile.fp, "\r\n");
+ logfile.numwrites++;
+ fflush(logfile.fp);
+} //end of the function Log_Write
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+FILE *Log_FilePointer(void)
+{
+ return logfile.fp;
+} //end of the function Log_FilePointer
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Log_Flush(void)
+{
+ if (logfile.fp) fflush(logfile.fp);
+} //end of the function Log_Flush
+
diff --git a/code/botlib/l_log.h b/code/botlib/l_log.h
new file mode 100755
index 0000000..2d07f9e
--- /dev/null
+++ b/code/botlib/l_log.h
@@ -0,0 +1,46 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: l_log.h
+ *
+ * desc: log file
+ *
+ * $Archive: /source/code/botlib/l_log.h $
+ *
+ *****************************************************************************/
+
+//open a log file
+void Log_Open(char *filename);
+//close the current log file
+void Log_Close(void);
+//close log file if present
+void Log_Shutdown(void);
+//write to the current opened log file
+void QDECL Log_Write(char *fmt, ...);
+//write to the current opened log file with a time stamp
+void QDECL Log_WriteTimeStamped(char *fmt, ...);
+//returns a pointer to the log file
+FILE *Log_FilePointer(void);
+//flush log file
+void Log_Flush(void);
+
diff --git a/code/botlib/l_memory.c b/code/botlib/l_memory.c
new file mode 100755
index 0000000..68928ab
--- /dev/null
+++ b/code/botlib/l_memory.c
@@ -0,0 +1,463 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: l_memory.c
+ *
+ * desc: memory allocation
+ *
+ * $Archive: /MissionPack/code/botlib/l_memory.c $
+ *
+ *****************************************************************************/
+
+#include "../game/q_shared.h"
+#include "../game/botlib.h"
+#include "l_log.h"
+#include "be_interface.h"
+
+//#define MEMDEBUG
+//#define MEMORYMANEGER
+
+#define MEM_ID 0x12345678l
+#define HUNK_ID 0x87654321l
+
+int allocatedmemory;
+int totalmemorysize;
+int numblocks;
+
+#ifdef MEMORYMANEGER
+
+typedef struct memoryblock_s
+{
+ unsigned long int id;
+ void *ptr;
+ int size;
+#ifdef MEMDEBUG
+ char *label;
+ char *file;
+ int line;
+#endif //MEMDEBUG
+ struct memoryblock_s *prev, *next;
+} memoryblock_t;
+
+memoryblock_t *memory;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void LinkMemoryBlock(memoryblock_t *block)
+{
+ block->prev = NULL;
+ block->next = memory;
+ if (memory) memory->prev = block;
+ memory = block;
+} //end of the function LinkMemoryBlock
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void UnlinkMemoryBlock(memoryblock_t *block)
+{
+ if (block->prev) block->prev->next = block->next;
+ else memory = block->next;
+ if (block->next) block->next->prev = block->prev;
+} //end of the function UnlinkMemoryBlock
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+#ifdef MEMDEBUG
+void *GetMemoryDebug(unsigned long size, char *label, char *file, int line)
+#else
+void *GetMemory(unsigned long size)
+#endif //MEMDEBUG
+{
+ void *ptr;
+ memoryblock_t *block;
+ assert(botimport.GetMemory); // bk001129 - was NULL'ed
+ ptr = botimport.GetMemory(size + sizeof(memoryblock_t));
+ block = (memoryblock_t *) ptr;
+ block->id = MEM_ID;
+ block->ptr = (char *) ptr + sizeof(memoryblock_t);
+ block->size = size + sizeof(memoryblock_t);
+#ifdef MEMDEBUG
+ block->label = label;
+ block->file = file;
+ block->line = line;
+#endif //MEMDEBUG
+ LinkMemoryBlock(block);
+ allocatedmemory += block->size;
+ totalmemorysize += block->size + sizeof(memoryblock_t);
+ numblocks++;
+ return block->ptr;
+} //end of the function GetMemoryDebug
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+#ifdef MEMDEBUG
+void *GetClearedMemoryDebug(unsigned long size, char *label, char *file, int line)
+#else
+void *GetClearedMemory(unsigned long size)
+#endif //MEMDEBUG
+{
+ void *ptr;
+#ifdef MEMDEBUG
+ ptr = GetMemoryDebug(size, label, file, line);
+#else
+ ptr = GetMemory(size);
+#endif //MEMDEBUG
+ Com_Memset(ptr, 0, size);
+ return ptr;
+} //end of the function GetClearedMemory
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+#ifdef MEMDEBUG
+void *GetHunkMemoryDebug(unsigned long size, char *label, char *file, int line)
+#else
+void *GetHunkMemory(unsigned long size)
+#endif //MEMDEBUG
+{
+ void *ptr;
+ memoryblock_t *block;
+
+ ptr = botimport.HunkAlloc(size + sizeof(memoryblock_t));
+ block = (memoryblock_t *) ptr;
+ block->id = HUNK_ID;
+ block->ptr = (char *) ptr + sizeof(memoryblock_t);
+ block->size = size + sizeof(memoryblock_t);
+#ifdef MEMDEBUG
+ block->label = label;
+ block->file = file;
+ block->line = line;
+#endif //MEMDEBUG
+ LinkMemoryBlock(block);
+ allocatedmemory += block->size;
+ totalmemorysize += block->size + sizeof(memoryblock_t);
+ numblocks++;
+ return block->ptr;
+} //end of the function GetHunkMemoryDebug
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+#ifdef MEMDEBUG
+void *GetClearedHunkMemoryDebug(unsigned long size, char *label, char *file, int line)
+#else
+void *GetClearedHunkMemory(unsigned long size)
+#endif //MEMDEBUG
+{
+ void *ptr;
+#ifdef MEMDEBUG
+ ptr = GetHunkMemoryDebug(size, label, file, line);
+#else
+ ptr = GetHunkMemory(size);
+#endif //MEMDEBUG
+ Com_Memset(ptr, 0, size);
+ return ptr;
+} //end of the function GetClearedHunkMemory
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+memoryblock_t *BlockFromPointer(void *ptr, char *str)
+{
+ memoryblock_t *block;
+
+ if (!ptr)
+ {
+#ifdef MEMDEBUG
+ //char *crash = (char *) NULL;
+ //crash[0] = 1;
+ botimport.Print(PRT_FATAL, "%s: NULL pointer\n", str);
+#endif // MEMDEBUG
+ return NULL;
+ } //end if
+ block = (memoryblock_t *) ((char *) ptr - sizeof(memoryblock_t));
+ if (block->id != MEM_ID && block->id != HUNK_ID)
+ {
+ botimport.Print(PRT_FATAL, "%s: invalid memory block\n", str);
+ return NULL;
+ } //end if
+ if (block->ptr != ptr)
+ {
+ botimport.Print(PRT_FATAL, "%s: memory block pointer invalid\n", str);
+ return NULL;
+ } //end if
+ return block;
+} //end of the function BlockFromPointer
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void FreeMemory(void *ptr)
+{
+ memoryblock_t *block;
+
+ block = BlockFromPointer(ptr, "FreeMemory");
+ if (!block) return;
+ UnlinkMemoryBlock(block);
+ allocatedmemory -= block->size;
+ totalmemorysize -= block->size + sizeof(memoryblock_t);
+ numblocks--;
+ //
+ if (block->id == MEM_ID)
+ {
+ botimport.FreeMemory(block);
+ } //end if
+} //end of the function FreeMemory
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AvailableMemory(void)
+{
+ return botimport.AvailableMemory();
+} //end of the function AvailableMemory
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int MemoryByteSize(void *ptr)
+{
+ memoryblock_t *block;
+
+ block = BlockFromPointer(ptr, "MemoryByteSize");
+ if (!block) return 0;
+ return block->size;
+} //end of the function MemoryByteSize
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void PrintUsedMemorySize(void)
+{
+ botimport.Print(PRT_MESSAGE, "total allocated memory: %d KB\n", allocatedmemory >> 10);
+ botimport.Print(PRT_MESSAGE, "total botlib memory: %d KB\n", totalmemorysize >> 10);
+ botimport.Print(PRT_MESSAGE, "total memory blocks: %d\n", numblocks);
+} //end of the function PrintUsedMemorySize
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void PrintMemoryLabels(void)
+{
+ memoryblock_t *block;
+ int i;
+
+ PrintUsedMemorySize();
+ i = 0;
+ Log_Write("============= Botlib memory log ==============\r\n");
+ Log_Write("\r\n");
+ for (block = memory; block; block = block->next)
+ {
+#ifdef MEMDEBUG
+ if (block->id == HUNK_ID)
+ {
+ Log_Write("%6d, hunk %p, %8d: %24s line %6d: %s\r\n", i, block->ptr, block->size, block->file, block->line, block->label);
+ } //end if
+ else
+ {
+ Log_Write("%6d, %p, %8d: %24s line %6d: %s\r\n", i, block->ptr, block->size, block->file, block->line, block->label);
+ } //end else
+#endif //MEMDEBUG
+ i++;
+ } //end for
+} //end of the function PrintMemoryLabels
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void DumpMemory(void)
+{
+ memoryblock_t *block;
+
+ for (block = memory; block; block = memory)
+ {
+ FreeMemory(block->ptr);
+ } //end for
+ totalmemorysize = 0;
+ allocatedmemory = 0;
+} //end of the function DumpMemory
+
+#else
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+#ifdef MEMDEBUG
+void *GetMemoryDebug(unsigned long size, char *label, char *file, int line)
+#else
+void *GetMemory(unsigned long size)
+#endif //MEMDEBUG
+{
+ void *ptr;
+ unsigned long int *memid;
+
+ ptr = botimport.GetMemory(size + sizeof(unsigned long int));
+ if (!ptr) return NULL;
+ memid = (unsigned long int *) ptr;
+ *memid = MEM_ID;
+ return (unsigned long int *) ((char *) ptr + sizeof(unsigned long int));
+} //end of the function GetMemory
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+#ifdef MEMDEBUG
+void *GetClearedMemoryDebug(unsigned long size, char *label, char *file, int line)
+#else
+void *GetClearedMemory(unsigned long size)
+#endif //MEMDEBUG
+{
+ void *ptr;
+#ifdef MEMDEBUG
+ ptr = GetMemoryDebug(size, label, file, line);
+#else
+ ptr = GetMemory(size);
+#endif //MEMDEBUG
+ Com_Memset(ptr, 0, size);
+ return ptr;
+} //end of the function GetClearedMemory
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+#ifdef MEMDEBUG
+void *GetHunkMemoryDebug(unsigned long size, char *label, char *file, int line)
+#else
+void *GetHunkMemory(unsigned long size)
+#endif //MEMDEBUG
+{
+ void *ptr;
+ unsigned long int *memid;
+
+ ptr = botimport.HunkAlloc(size + sizeof(unsigned long int));
+ if (!ptr) return NULL;
+ memid = (unsigned long int *) ptr;
+ *memid = HUNK_ID;
+ return (unsigned long int *) ((char *) ptr + sizeof(unsigned long int));
+} //end of the function GetHunkMemory
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+#ifdef MEMDEBUG
+void *GetClearedHunkMemoryDebug(unsigned long size, char *label, char *file, int line)
+#else
+void *GetClearedHunkMemory(unsigned long size)
+#endif //MEMDEBUG
+{
+ void *ptr;
+#ifdef MEMDEBUG
+ ptr = GetHunkMemoryDebug(size, label, file, line);
+#else
+ ptr = GetHunkMemory(size);
+#endif //MEMDEBUG
+ Com_Memset(ptr, 0, size);
+ return ptr;
+} //end of the function GetClearedHunkMemory
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void FreeMemory(void *ptr)
+{
+ unsigned long int *memid;
+
+ memid = (unsigned long int *) ((char *) ptr - sizeof(unsigned long int));
+
+ if (*memid == MEM_ID)
+ {
+ botimport.FreeMemory(memid);
+ } //end if
+} //end of the function FreeMemory
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AvailableMemory(void)
+{
+ return botimport.AvailableMemory();
+} //end of the function AvailableMemory
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void PrintUsedMemorySize(void)
+{
+} //end of the function PrintUsedMemorySize
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void PrintMemoryLabels(void)
+{
+} //end of the function PrintMemoryLabels
+
+#endif
diff --git a/code/botlib/l_memory.h b/code/botlib/l_memory.h
new file mode 100755
index 0000000..d0cfbb4
--- /dev/null
+++ b/code/botlib/l_memory.h
@@ -0,0 +1,76 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: l_memory.h
+ *
+ * desc: memory management
+ *
+ * $Archive: /source/code/botlib/l_memory.h $
+ *
+ *****************************************************************************/
+
+//#define MEMDEBUG
+
+#ifdef MEMDEBUG
+#define GetMemory(size) GetMemoryDebug(size, #size, __FILE__, __LINE__);
+#define GetClearedMemory(size) GetClearedMemoryDebug(size, #size, __FILE__, __LINE__);
+//allocate a memory block of the given size
+void *GetMemoryDebug(unsigned long size, char *label, char *file, int line);
+//allocate a memory block of the given size and clear it
+void *GetClearedMemoryDebug(unsigned long size, char *label, char *file, int line);
+//
+#define GetHunkMemory(size) GetHunkMemoryDebug(size, #size, __FILE__, __LINE__);
+#define GetClearedHunkMemory(size) GetClearedHunkMemoryDebug(size, #size, __FILE__, __LINE__);
+//allocate a memory block of the given size
+void *GetHunkMemoryDebug(unsigned long size, char *label, char *file, int line);
+//allocate a memory block of the given size and clear it
+void *GetClearedHunkMemoryDebug(unsigned long size, char *label, char *file, int line);
+#else
+//allocate a memory block of the given size
+void *GetMemory(unsigned long size);
+//allocate a memory block of the given size and clear it
+void *GetClearedMemory(unsigned long size);
+//
+#ifdef BSPC
+#define GetHunkMemory GetMemory
+#define GetClearedHunkMemory GetClearedMemory
+#else
+//allocate a memory block of the given size
+void *GetHunkMemory(unsigned long size);
+//allocate a memory block of the given size and clear it
+void *GetClearedHunkMemory(unsigned long size);
+#endif
+#endif
+
+//free the given memory block
+void FreeMemory(void *ptr);
+//returns the amount available memory
+int AvailableMemory(void);
+//prints the total used memory size
+void PrintUsedMemorySize(void);
+//print all memory blocks with label
+void PrintMemoryLabels(void);
+//returns the size of the memory block in bytes
+int MemoryByteSize(void *ptr);
+//free all allocated memory
+void DumpMemory(void);
diff --git a/code/botlib/l_precomp.c b/code/botlib/l_precomp.c
new file mode 100755
index 0000000..4fa708b
--- /dev/null
+++ b/code/botlib/l_precomp.c
@@ -0,0 +1,3228 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+/*****************************************************************************
+ * name: l_precomp.c
+ *
+ * desc: pre compiler
+ *
+ * $Archive: /MissionPack/code/botlib/l_precomp.c $
+ *
+ *****************************************************************************/
+
+//Notes: fix: PC_StringizeTokens
+
+//#define SCREWUP
+//#define BOTLIB
+//#define QUAKE
+//#define QUAKEC
+//#define MEQCC
+
+#ifdef SCREWUP
+#include <stdio.h>
+#include <stdlib.h>
+#include <limits.h>
+#include <string.h>
+#include <stdarg.h>
+#include <time.h>
+#include "l_memory.h"
+#include "l_script.h"
+#include "l_precomp.h"
+
+typedef enum {qfalse, qtrue} qboolean;
+#endif //SCREWUP
+
+#ifdef BOTLIB
+#include "../game/q_shared.h"
+#include "../game/botlib.h"
+#include "be_interface.h"
+#include "l_memory.h"
+#include "l_script.h"
+#include "l_precomp.h"
+#include "l_log.h"
+#endif //BOTLIB
+
+#ifdef MEQCC
+#include "qcc.h"
+#include "time.h" //time & ctime
+#include "math.h" //fabs
+#include "l_memory.h"
+#include "l_script.h"
+#include "l_precomp.h"
+#include "l_log.h"
+
+#define qtrue true
+#define qfalse false
+#endif //MEQCC
+
+#ifdef BSPC
+//include files for usage in the BSP Converter
+#include "../bspc/qbsp.h"
+#include "../bspc/l_log.h"
+#include "../bspc/l_mem.h"
+#include "l_precomp.h"
+
+#define qtrue true
+#define qfalse false
+#define Q_stricmp stricmp
+
+#endif //BSPC
+
+#if defined(QUAKE) && !defined(BSPC)
+#include "l_utils.h"
+#endif //QUAKE
+
+//#define DEBUG_EVAL
+
+#define MAX_DEFINEPARMS 128
+
+#define DEFINEHASHING 1
+
+//directive name with parse function
+typedef struct directive_s
+{
+ char *name;
+ int (*func)(source_t *source);
+} directive_t;
+
+#define DEFINEHASHSIZE 1024
+
+#define TOKEN_HEAP_SIZE 4096
+
+int numtokens;
+/*
+int tokenheapinitialized; //true when the token heap is initialized
+token_t token_heap[TOKEN_HEAP_SIZE]; //heap with tokens
+token_t *freetokens; //free tokens from the heap
+*/
+
+//list with global defines added to every source loaded
+define_t *globaldefines;
+
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void QDECL SourceError(source_t *source, char *str, ...)
+{
+ char text[1024];
+ va_list ap;
+
+ va_start(ap, str);
+ vsprintf(text, str, ap);
+ va_end(ap);
+#ifdef BOTLIB
+ botimport.Print(PRT_ERROR, "file %s, line %d: %s\n", source->scriptstack->filename, source->scriptstack->line, text);
+#endif //BOTLIB
+#ifdef MEQCC
+ printf("error: file %s, line %d: %s\n", source->scriptstack->filename, source->scriptstack->line, text);
+#endif //MEQCC
+#ifdef BSPC
+ Log_Print("error: file %s, line %d: %s\n", source->scriptstack->filename, source->scriptstack->line, text);
+#endif //BSPC
+} //end of the function SourceError
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void QDECL SourceWarning(source_t *source, char *str, ...)
+{
+ char text[1024];
+ va_list ap;
+
+ va_start(ap, str);
+ vsprintf(text, str, ap);
+ va_end(ap);
+#ifdef BOTLIB
+ botimport.Print(PRT_WARNING, "file %s, line %d: %s\n", source->scriptstack->filename, source->scriptstack->line, text);
+#endif //BOTLIB
+#ifdef MEQCC
+ printf("warning: file %s, line %d: %s\n", source->scriptstack->filename, source->scriptstack->line, text);
+#endif //MEQCC
+#ifdef BSPC
+ Log_Print("warning: file %s, line %d: %s\n", source->scriptstack->filename, source->scriptstack->line, text);
+#endif //BSPC
+} //end of the function ScriptWarning
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void PC_PushIndent(source_t *source, int type, int skip)
+{
+ indent_t *indent;
+
+ indent = (indent_t *) GetMemory(sizeof(indent_t));
+ indent->type = type;
+ indent->script = source->scriptstack;
+ indent->skip = (skip != 0);
+ source->skip += indent->skip;
+ indent->next = source->indentstack;
+ source->indentstack = indent;
+} //end of the function PC_PushIndent
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void PC_PopIndent(source_t *source, int *type, int *skip)
+{
+ indent_t *indent;
+
+ *type = 0;
+ *skip = 0;
+
+ indent = source->indentstack;
+ if (!indent) return;
+
+ //must be an indent from the current script
+ if (source->indentstack->script != source->scriptstack) return;
+
+ *type = indent->type;
+ *skip = indent->skip;
+ source->indentstack = source->indentstack->next;
+ source->skip -= indent->skip;
+ FreeMemory(indent);
+} //end of the function PC_PopIndent
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void PC_PushScript(source_t *source, script_t *script)
+{
+ script_t *s;
+
+ for (s = source->scriptstack; s; s = s->next)
+ {
+ if (!Q_stricmp(s->filename, script->filename))
+ {
+ SourceError(source, "%s recursively included", script->filename);
+ return;
+ } //end if
+ } //end for
+ //push the script on the script stack
+ script->next = source->scriptstack;
+ source->scriptstack = script;
+} //end of the function PC_PushScript
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void PC_InitTokenHeap(void)
+{
+ /*
+ int i;
+
+ if (tokenheapinitialized) return;
+ freetokens = NULL;
+ for (i = 0; i < TOKEN_HEAP_SIZE; i++)
+ {
+ token_heap[i].next = freetokens;
+ freetokens = &token_heap[i];
+ } //end for
+ tokenheapinitialized = qtrue;
+ */
+} //end of the function PC_InitTokenHeap
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+token_t *PC_CopyToken(token_t *token)
+{
+ token_t *t;
+
+// t = (token_t *) malloc(sizeof(token_t));
+ t = (token_t *) GetMemory(sizeof(token_t));
+// t = freetokens;
+ if (!t)
+ {
+#ifdef BSPC
+ Error("out of token space\n");
+#else
+ Com_Error(ERR_FATAL, "out of token space\n");
+#endif
+ return NULL;
+ } //end if
+// freetokens = freetokens->next;
+ Com_Memcpy(t, token, sizeof(token_t));
+ t->next = NULL;
+ numtokens++;
+ return t;
+} //end of the function PC_CopyToken
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void PC_FreeToken(token_t *token)
+{
+ //free(token);
+ FreeMemory(token);
+// token->next = freetokens;
+// freetokens = token;
+ numtokens--;
+} //end of the function PC_FreeToken
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_ReadSourceToken(source_t *source, token_t *token)
+{
+ token_t *t;
+ script_t *script;
+ int type, skip;
+
+ //if there's no token already available
+ while(!source->tokens)
+ {
+ //if there's a token to read from the script
+ if (PS_ReadToken(source->scriptstack, token)) return qtrue;
+ //if at the end of the script
+ if (EndOfScript(source->scriptstack))
+ {
+ //remove all indents of the script
+ while(source->indentstack &&
+ source->indentstack->script == source->scriptstack)
+ {
+ SourceWarning(source, "missing #endif");
+ PC_PopIndent(source, &type, &skip);
+ } //end if
+ } //end if
+ //if this was the initial script
+ if (!source->scriptstack->next) return qfalse;
+ //remove the script and return to the last one
+ script = source->scriptstack;
+ source->scriptstack = source->scriptstack->next;
+ FreeScript(script);
+ } //end while
+ //copy the already available token
+ Com_Memcpy(token, source->tokens, sizeof(token_t));
+ //free the read token
+ t = source->tokens;
+ source->tokens = source->tokens->next;
+ PC_FreeToken(t);
+ return qtrue;
+} //end of the function PC_ReadSourceToken
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_UnreadSourceToken(source_t *source, token_t *token)
+{
+ token_t *t;
+
+ t = PC_CopyToken(token);
+ t->next = source->tokens;
+ source->tokens = t;
+ return qtrue;
+} //end of the function PC_UnreadSourceToken
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_ReadDefineParms(source_t *source, define_t *define, token_t **parms, int maxparms)
+{
+ token_t token, *t, *last;
+ int i, done, lastcomma, numparms, indent;
+
+ if (!PC_ReadSourceToken(source, &token))
+ {
+ SourceError(source, "define %s missing parms", define->name);
+ return qfalse;
+ } //end if
+ //
+ if (define->numparms > maxparms)
+ {
+ SourceError(source, "define with more than %d parameters", maxparms);
+ return qfalse;
+ } //end if
+ //
+ for (i = 0; i < define->numparms; i++) parms[i] = NULL;
+ //if no leading "("
+ if (strcmp(token.string, "("))
+ {
+ PC_UnreadSourceToken(source, &token);
+ SourceError(source, "define %s missing parms", define->name);
+ return qfalse;
+ } //end if
+ //read the define parameters
+ for (done = 0, numparms = 0, indent = 0; !done;)
+ {
+ if (numparms >= maxparms)
+ {
+ SourceError(source, "define %s with too many parms", define->name);
+ return qfalse;
+ } //end if
+ if (numparms >= define->numparms)
+ {
+ SourceWarning(source, "define %s has too many parms", define->name);
+ return qfalse;
+ } //end if
+ parms[numparms] = NULL;
+ lastcomma = 1;
+ last = NULL;
+ while(!done)
+ {
+ //
+ if (!PC_ReadSourceToken(source, &token))
+ {
+ SourceError(source, "define %s incomplete", define->name);
+ return qfalse;
+ } //end if
+ //
+ if (!strcmp(token.string, ","))
+ {
+ if (indent <= 0)
+ {
+ if (lastcomma) SourceWarning(source, "too many comma's");
+ lastcomma = 1;
+ break;
+ } //end if
+ } //end if
+ lastcomma = 0;
+ //
+ if (!strcmp(token.string, "("))
+ {
+ indent++;
+ continue;
+ } //end if
+ else if (!strcmp(token.string, ")"))
+ {
+ if (--indent <= 0)
+ {
+ if (!parms[define->numparms-1])
+ {
+ SourceWarning(source, "too few define parms");
+ } //end if
+ done = 1;
+ break;
+ } //end if
+ } //end if
+ //
+ if (numparms < define->numparms)
+ {
+ //
+ t = PC_CopyToken(&token);
+ t->next = NULL;
+ if (last) last->next = t;
+ else parms[numparms] = t;
+ last = t;
+ } //end if
+ } //end while
+ numparms++;
+ } //end for
+ return qtrue;
+} //end of the function PC_ReadDefineParms
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_StringizeTokens(token_t *tokens, token_t *token)
+{
+ token_t *t;
+
+ token->type = TT_STRING;
+ token->whitespace_p = NULL;
+ token->endwhitespace_p = NULL;
+ token->string[0] = '\0';
+ strcat(token->string, "\"");
+ for (t = tokens; t; t = t->next)
+ {
+ strncat(token->string, t->string, MAX_TOKEN - strlen(token->string));
+ } //end for
+ strncat(token->string, "\"", MAX_TOKEN - strlen(token->string));
+ return qtrue;
+} //end of the function PC_StringizeTokens
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_MergeTokens(token_t *t1, token_t *t2)
+{
+ //merging of a name with a name or number
+ if (t1->type == TT_NAME && (t2->type == TT_NAME || t2->type == TT_NUMBER))
+ {
+ strcat(t1->string, t2->string);
+ return qtrue;
+ } //end if
+ //merging of two strings
+ if (t1->type == TT_STRING && t2->type == TT_STRING)
+ {
+ //remove trailing double quote
+ t1->string[strlen(t1->string)-1] = '\0';
+ //concat without leading double quote
+ strcat(t1->string, &t2->string[1]);
+ return qtrue;
+ } //end if
+ //FIXME: merging of two number of the same sub type
+ return qfalse;
+} //end of the function PC_MergeTokens
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+/*
+void PC_PrintDefine(define_t *define)
+{
+ printf("define->name = %s\n", define->name);
+ printf("define->flags = %d\n", define->flags);
+ printf("define->builtin = %d\n", define->builtin);
+ printf("define->numparms = %d\n", define->numparms);
+// token_t *parms; //define parameters
+// token_t *tokens; //macro tokens (possibly containing parm tokens)
+// struct define_s *next; //next defined macro in a list
+} //end of the function PC_PrintDefine*/
+#if DEFINEHASHING
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void PC_PrintDefineHashTable(define_t **definehash)
+{
+ int i;
+ define_t *d;
+
+ for (i = 0; i < DEFINEHASHSIZE; i++)
+ {
+ Log_Write("%4d:", i);
+ for (d = definehash[i]; d; d = d->hashnext)
+ {
+ Log_Write(" %s", d->name);
+ } //end for
+ Log_Write("\n");
+ } //end for
+} //end of the function PC_PrintDefineHashTable
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+//char primes[16] = {1, 3, 5, 7, 11, 13, 17, 19, 23, 27, 29, 31, 37, 41, 43, 47};
+
+int PC_NameHash(char *name)
+{
+ int register hash, i;
+
+ hash = 0;
+ for (i = 0; name[i] != '\0'; i++)
+ {
+ hash += name[i] * (119 + i);
+ //hash += (name[i] << 7) + i;
+ //hash += (name[i] << (i&15));
+ } //end while
+ hash = (hash ^ (hash >> 10) ^ (hash >> 20)) & (DEFINEHASHSIZE-1);
+ return hash;
+} //end of the function PC_NameHash
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void PC_AddDefineToHash(define_t *define, define_t **definehash)
+{
+ int hash;
+
+ hash = PC_NameHash(define->name);
+ define->hashnext = definehash[hash];
+ definehash[hash] = define;
+} //end of the function PC_AddDefineToHash
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+define_t *PC_FindHashedDefine(define_t **definehash, char *name)
+{
+ define_t *d;
+ int hash;
+
+ hash = PC_NameHash(name);
+ for (d = definehash[hash]; d; d = d->hashnext)
+ {
+ if (!strcmp(d->name, name)) return d;
+ } //end for
+ return NULL;
+} //end of the function PC_FindHashedDefine
+#endif //DEFINEHASHING
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+define_t *PC_FindDefine(define_t *defines, char *name)
+{
+ define_t *d;
+
+ for (d = defines; d; d = d->next)
+ {
+ if (!strcmp(d->name, name)) return d;
+ } //end for
+ return NULL;
+} //end of the function PC_FindDefine
+//============================================================================
+//
+// Parameter: -
+// Returns: number of the parm
+// if no parm found with the given name -1 is returned
+// Changes Globals: -
+//============================================================================
+int PC_FindDefineParm(define_t *define, char *name)
+{
+ token_t *p;
+ int i;
+
+ i = 0;
+ for (p = define->parms; p; p = p->next)
+ {
+ if (!strcmp(p->string, name)) return i;
+ i++;
+ } //end for
+ return -1;
+} //end of the function PC_FindDefineParm
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void PC_FreeDefine(define_t *define)
+{
+ token_t *t, *next;
+
+ //free the define parameters
+ for (t = define->parms; t; t = next)
+ {
+ next = t->next;
+ PC_FreeToken(t);
+ } //end for
+ //free the define tokens
+ for (t = define->tokens; t; t = next)
+ {
+ next = t->next;
+ PC_FreeToken(t);
+ } //end for
+ //free the define
+ FreeMemory(define);
+} //end of the function PC_FreeDefine
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void PC_AddBuiltinDefines(source_t *source)
+{
+ int i;
+ define_t *define;
+ struct builtin
+ {
+ char *string;
+ int builtin;
+ } builtin[] = { // bk001204 - brackets
+ { "__LINE__", BUILTIN_LINE },
+ { "__FILE__", BUILTIN_FILE },
+ { "__DATE__", BUILTIN_DATE },
+ { "__TIME__", BUILTIN_TIME },
+// { "__STDC__", BUILTIN_STDC },
+ { NULL, 0 }
+ };
+
+ for (i = 0; builtin[i].string; i++)
+ {
+ define = (define_t *) GetMemory(sizeof(define_t) + strlen(builtin[i].string) + 1);
+ Com_Memset(define, 0, sizeof(define_t));
+ define->name = (char *) define + sizeof(define_t);
+ strcpy(define->name, builtin[i].string);
+ define->flags |= DEFINE_FIXED;
+ define->builtin = builtin[i].builtin;
+ //add the define to the source
+#if DEFINEHASHING
+ PC_AddDefineToHash(define, source->definehash);
+#else
+ define->next = source->defines;
+ source->defines = define;
+#endif //DEFINEHASHING
+ } //end for
+} //end of the function PC_AddBuiltinDefines
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_ExpandBuiltinDefine(source_t *source, token_t *deftoken, define_t *define,
+ token_t **firsttoken, token_t **lasttoken)
+{
+ token_t *token;
+ unsigned long t; // time_t t; //to prevent LCC warning
+ char *curtime;
+
+ token = PC_CopyToken(deftoken);
+ switch(define->builtin)
+ {
+ case BUILTIN_LINE:
+ {
+ sprintf(token->string, "%d", deftoken->line);
+#ifdef NUMBERVALUE
+ token->intvalue = deftoken->line;
+ token->floatvalue = deftoken->line;
+#endif //NUMBERVALUE
+ token->type = TT_NUMBER;
+ token->subtype = TT_DECIMAL | TT_INTEGER;
+ *firsttoken = token;
+ *lasttoken = token;
+ break;
+ } //end case
+ case BUILTIN_FILE:
+ {
+ strcpy(token->string, source->scriptstack->filename);
+ token->type = TT_NAME;
+ token->subtype = strlen(token->string);
+ *firsttoken = token;
+ *lasttoken = token;
+ break;
+ } //end case
+ case BUILTIN_DATE:
+ {
+ t = time(NULL);
+ curtime = ctime(&t);
+ strcpy(token->string, "\"");
+ strncat(token->string, curtime+4, 7);
+ strncat(token->string+7, curtime+20, 4);
+ strcat(token->string, "\"");
+ free(curtime);
+ token->type = TT_NAME;
+ token->subtype = strlen(token->string);
+ *firsttoken = token;
+ *lasttoken = token;
+ break;
+ } //end case
+ case BUILTIN_TIME:
+ {
+ t = time(NULL);
+ curtime = ctime(&t);
+ strcpy(token->string, "\"");
+ strncat(token->string, curtime+11, 8);
+ strcat(token->string, "\"");
+ free(curtime);
+ token->type = TT_NAME;
+ token->subtype = strlen(token->string);
+ *firsttoken = token;
+ *lasttoken = token;
+ break;
+ } //end case
+ case BUILTIN_STDC:
+ default:
+ {
+ *firsttoken = NULL;
+ *lasttoken = NULL;
+ break;
+ } //end case
+ } //end switch
+ return qtrue;
+} //end of the function PC_ExpandBuiltinDefine
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_ExpandDefine(source_t *source, token_t *deftoken, define_t *define,
+ token_t **firsttoken, token_t **lasttoken)
+{
+ token_t *parms[MAX_DEFINEPARMS], *dt, *pt, *t;
+ token_t *t1, *t2, *first, *last, *nextpt, token;
+ int parmnum, i;
+
+ //if it is a builtin define
+ if (define->builtin)
+ {
+ return PC_ExpandBuiltinDefine(source, deftoken, define, firsttoken, lasttoken);
+ } //end if
+ //if the define has parameters
+ if (define->numparms)
+ {
+ if (!PC_ReadDefineParms(source, define, parms, MAX_DEFINEPARMS)) return qfalse;
+#ifdef DEBUG_EVAL
+ for (i = 0; i < define->numparms; i++)
+ {
+ Log_Write("define parms %d:", i);
+ for (pt = parms[i]; pt; pt = pt->next)
+ {
+ Log_Write("%s", pt->string);
+ } //end for
+ } //end for
+#endif //DEBUG_EVAL
+ } //end if
+ //empty list at first
+ first = NULL;
+ last = NULL;
+ //create a list with tokens of the expanded define
+ for (dt = define->tokens; dt; dt = dt->next)
+ {
+ parmnum = -1;
+ //if the token is a name, it could be a define parameter
+ if (dt->type == TT_NAME)
+ {
+ parmnum = PC_FindDefineParm(define, dt->string);
+ } //end if
+ //if it is a define parameter
+ if (parmnum >= 0)
+ {
+ for (pt = parms[parmnum]; pt; pt = pt->next)
+ {
+ t = PC_CopyToken(pt);
+ //add the token to the list
+ t->next = NULL;
+ if (last) last->next = t;
+ else first = t;
+ last = t;
+ } //end for
+ } //end if
+ else
+ {
+ //if stringizing operator
+ if (dt->string[0] == '#' && dt->string[1] == '\0')
+ {
+ //the stringizing operator must be followed by a define parameter
+ if (dt->next) parmnum = PC_FindDefineParm(define, dt->next->string);
+ else parmnum = -1;
+ //
+ if (parmnum >= 0)
+ {
+ //step over the stringizing operator
+ dt = dt->next;
+ //stringize the define parameter tokens
+ if (!PC_StringizeTokens(parms[parmnum], &token))
+ {
+ SourceError(source, "can't stringize tokens");
+ return qfalse;
+ } //end if
+ t = PC_CopyToken(&token);
+ } //end if
+ else
+ {
+ SourceWarning(source, "stringizing operator without define parameter");
+ continue;
+ } //end if
+ } //end if
+ else
+ {
+ t = PC_CopyToken(dt);
+ } //end else
+ //add the token to the list
+ t->next = NULL;
+ if (last) last->next = t;
+ else first = t;
+ last = t;
+ } //end else
+ } //end for
+ //check for the merging operator
+ for (t = first; t; )
+ {
+ if (t->next)
+ {
+ //if the merging operator
+ if (t->next->string[0] == '#' && t->next->string[1] == '#')
+ {
+ t1 = t;
+ t2 = t->next->next;
+ if (t2)
+ {
+ if (!PC_MergeTokens(t1, t2))
+ {
+ SourceError(source, "can't merge %s with %s", t1->string, t2->string);
+ return qfalse;
+ } //end if
+ PC_FreeToken(t1->next);
+ t1->next = t2->next;
+ if (t2 == last) last = t1;
+ PC_FreeToken(t2);
+ continue;
+ } //end if
+ } //end if
+ } //end if
+ t = t->next;
+ } //end for
+ //store the first and last token of the list
+ *firsttoken = first;
+ *lasttoken = last;
+ //free all the parameter tokens
+ for (i = 0; i < define->numparms; i++)
+ {
+ for (pt = parms[i]; pt; pt = nextpt)
+ {
+ nextpt = pt->next;
+ PC_FreeToken(pt);
+ } //end for
+ } //end for
+ //
+ return qtrue;
+} //end of the function PC_ExpandDefine
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_ExpandDefineIntoSource(source_t *source, token_t *deftoken, define_t *define)
+{
+ token_t *firsttoken, *lasttoken;
+
+ if (!PC_ExpandDefine(source, deftoken, define, &firsttoken, &lasttoken)) return qfalse;
+
+ if (firsttoken && lasttoken)
+ {
+ lasttoken->next = source->tokens;
+ source->tokens = firsttoken;
+ return qtrue;
+ } //end if
+ return qfalse;
+} //end of the function PC_ExpandDefineIntoSource
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void PC_ConvertPath(char *path)
+{
+ char *ptr;
+
+ //remove double path seperators
+ for (ptr = path; *ptr;)
+ {
+ if ((*ptr == '\\' || *ptr == '/') &&
+ (*(ptr+1) == '\\' || *(ptr+1) == '/'))
+ {
+ strcpy(ptr, ptr+1);
+ } //end if
+ else
+ {
+ ptr++;
+ } //end else
+ } //end while
+ //set OS dependent path seperators
+ for (ptr = path; *ptr;)
+ {
+ if (*ptr == '/' || *ptr == '\\') *ptr = PATHSEPERATOR_CHAR;
+ ptr++;
+ } //end while
+} //end of the function PC_ConvertPath
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_Directive_include(source_t *source)
+{
+ script_t *script;
+ token_t token;
+ char path[MAX_PATH];
+#ifdef QUAKE
+ foundfile_t file;
+#endif //QUAKE
+
+ if (source->skip > 0) return qtrue;
+ //
+ if (!PC_ReadSourceToken(source, &token))
+ {
+ SourceError(source, "#include without file name");
+ return qfalse;
+ } //end if
+ if (token.linescrossed > 0)
+ {
+ SourceError(source, "#include without file name");
+ return qfalse;
+ } //end if
+ if (token.type == TT_STRING)
+ {
+ StripDoubleQuotes(token.string);
+ PC_ConvertPath(token.string);
+ script = LoadScriptFile(token.string);
+ if (!script)
+ {
+ strcpy(path, source->includepath);
+ strcat(path, token.string);
+ script = LoadScriptFile(path);
+ } //end if
+ } //end if
+ else if (token.type == TT_PUNCTUATION && *token.string == '<')
+ {
+ strcpy(path, source->includepath);
+ while(PC_ReadSourceToken(source, &token))
+ {
+ if (token.linescrossed > 0)
+ {
+ PC_UnreadSourceToken(source, &token);
+ break;
+ } //end if
+ if (token.type == TT_PUNCTUATION && *token.string == '>') break;
+ strncat(path, token.string, MAX_PATH);
+ } //end while
+ if (*token.string != '>')
+ {
+ SourceWarning(source, "#include missing trailing >");
+ } //end if
+ if (!strlen(path))
+ {
+ SourceError(source, "#include without file name between < >");
+ return qfalse;
+ } //end if
+ PC_ConvertPath(path);
+ script = LoadScriptFile(path);
+ } //end if
+ else
+ {
+ SourceError(source, "#include without file name");
+ return qfalse;
+ } //end else
+#ifdef QUAKE
+ if (!script)
+ {
+ Com_Memset(&file, 0, sizeof(foundfile_t));
+ script = LoadScriptFile(path);
+ if (script) strncpy(script->filename, path, MAX_PATH);
+ } //end if
+#endif //QUAKE
+ if (!script)
+ {
+#ifdef SCREWUP
+ SourceWarning(source, "file %s not found", path);
+ return qtrue;
+#else
+ SourceError(source, "file %s not found", path);
+ return qfalse;
+#endif //SCREWUP
+ } //end if
+ PC_PushScript(source, script);
+ return qtrue;
+} //end of the function PC_Directive_include
+//============================================================================
+// reads a token from the current line, continues reading on the next
+// line only if a backslash '\' is encountered.
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_ReadLine(source_t *source, token_t *token)
+{
+ int crossline;
+
+ crossline = 0;
+ do
+ {
+ if (!PC_ReadSourceToken(source, token)) return qfalse;
+
+ if (token->linescrossed > crossline)
+ {
+ PC_UnreadSourceToken(source, token);
+ return qfalse;
+ } //end if
+ crossline = 1;
+ } while(!strcmp(token->string, "\\"));
+ return qtrue;
+} //end of the function PC_ReadLine
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_WhiteSpaceBeforeToken(token_t *token)
+{
+ return token->endwhitespace_p - token->whitespace_p > 0;
+} //end of the function PC_WhiteSpaceBeforeToken
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void PC_ClearTokenWhiteSpace(token_t *token)
+{
+ token->whitespace_p = NULL;
+ token->endwhitespace_p = NULL;
+ token->linescrossed = 0;
+} //end of the function PC_ClearTokenWhiteSpace
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_Directive_undef(source_t *source)
+{
+ token_t token;
+ define_t *define, *lastdefine;
+ int hash;
+
+ if (source->skip > 0) return qtrue;
+ //
+ if (!PC_ReadLine(source, &token))
+ {
+ SourceError(source, "undef without name");
+ return qfalse;
+ } //end if
+ if (token.type != TT_NAME)
+ {
+ PC_UnreadSourceToken(source, &token);
+ SourceError(source, "expected name, found %s", token.string);
+ return qfalse;
+ } //end if
+#if DEFINEHASHING
+
+ hash = PC_NameHash(token.string);
+ for (lastdefine = NULL, define = source->definehash[hash]; define; define = define->hashnext)
+ {
+ if (!strcmp(define->name, token.string))
+ {
+ if (define->flags & DEFINE_FIXED)
+ {
+ SourceWarning(source, "can't undef %s", token.string);
+ } //end if
+ else
+ {
+ if (lastdefine) lastdefine->hashnext = define->hashnext;
+ else source->definehash[hash] = define->hashnext;
+ PC_FreeDefine(define);
+ } //end else
+ break;
+ } //end if
+ lastdefine = define;
+ } //end for
+#else //DEFINEHASHING
+ for (lastdefine = NULL, define = source->defines; define; define = define->next)
+ {
+ if (!strcmp(define->name, token.string))
+ {
+ if (define->flags & DEFINE_FIXED)
+ {
+ SourceWarning(source, "can't undef %s", token.string);
+ } //end if
+ else
+ {
+ if (lastdefine) lastdefine->next = define->next;
+ else source->defines = define->next;
+ PC_FreeDefine(define);
+ } //end else
+ break;
+ } //end if
+ lastdefine = define;
+ } //end for
+#endif //DEFINEHASHING
+ return qtrue;
+} //end of the function PC_Directive_undef
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_Directive_define(source_t *source)
+{
+ token_t token, *t, *last;
+ define_t *define;
+
+ if (source->skip > 0) return qtrue;
+ //
+ if (!PC_ReadLine(source, &token))
+ {
+ SourceError(source, "#define without name");
+ return qfalse;
+ } //end if
+ if (token.type != TT_NAME)
+ {
+ PC_UnreadSourceToken(source, &token);
+ SourceError(source, "expected name after #define, found %s", token.string);
+ return qfalse;
+ } //end if
+ //check if the define already exists
+#if DEFINEHASHING
+ define = PC_FindHashedDefine(source->definehash, token.string);
+#else
+ define = PC_FindDefine(source->defines, token.string);
+#endif //DEFINEHASHING
+ if (define)
+ {
+ if (define->flags & DEFINE_FIXED)
+ {
+ SourceError(source, "can't redefine %s", token.string);
+ return qfalse;
+ } //end if
+ SourceWarning(source, "redefinition of %s", token.string);
+ //unread the define name before executing the #undef directive
+ PC_UnreadSourceToken(source, &token);
+ if (!PC_Directive_undef(source)) return qfalse;
+ //if the define was not removed (define->flags & DEFINE_FIXED)
+#if DEFINEHASHING
+ define = PC_FindHashedDefine(source->definehash, token.string);
+#else
+ define = PC_FindDefine(source->defines, token.string);
+#endif //DEFINEHASHING
+ } //end if
+ //allocate define
+ define = (define_t *) GetMemory(sizeof(define_t) + strlen(token.string) + 1);
+ Com_Memset(define, 0, sizeof(define_t));
+ define->name = (char *) define + sizeof(define_t);
+ strcpy(define->name, token.string);
+ //add the define to the source
+#if DEFINEHASHING
+ PC_AddDefineToHash(define, source->definehash);
+#else //DEFINEHASHING
+ define->next = source->defines;
+ source->defines = define;
+#endif //DEFINEHASHING
+ //if nothing is defined, just return
+ if (!PC_ReadLine(source, &token)) return qtrue;
+ //if it is a define with parameters
+ if (!PC_WhiteSpaceBeforeToken(&token) && !strcmp(token.string, "("))
+ {
+ //read the define parameters
+ last = NULL;
+ if (!PC_CheckTokenString(source, ")"))
+ {
+ while(1)
+ {
+ if (!PC_ReadLine(source, &token))
+ {
+ SourceError(source, "expected define parameter");
+ return qfalse;
+ } //end if
+ //if it isn't a name
+ if (token.type != TT_NAME)
+ {
+ SourceError(source, "invalid define parameter");
+ return qfalse;
+ } //end if
+ //
+ if (PC_FindDefineParm(define, token.string) >= 0)
+ {
+ SourceError(source, "two the same define parameters");
+ return qfalse;
+ } //end if
+ //add the define parm
+ t = PC_CopyToken(&token);
+ PC_ClearTokenWhiteSpace(t);
+ t->next = NULL;
+ if (last) last->next = t;
+ else define->parms = t;
+ last = t;
+ define->numparms++;
+ //read next token
+ if (!PC_ReadLine(source, &token))
+ {
+ SourceError(source, "define parameters not terminated");
+ return qfalse;
+ } //end if
+ //
+ if (!strcmp(token.string, ")")) break;
+ //then it must be a comma
+ if (strcmp(token.string, ","))
+ {
+ SourceError(source, "define not terminated");
+ return qfalse;
+ } //end if
+ } //end while
+ } //end if
+ if (!PC_ReadLine(source, &token)) return qtrue;
+ } //end if
+ //read the defined stuff
+ last = NULL;
+ do
+ {
+ t = PC_CopyToken(&token);
+ if (t->type == TT_NAME && !strcmp(t->string, define->name))
+ {
+ SourceError(source, "recursive define (removed recursion)");
+ continue;
+ } //end if
+ PC_ClearTokenWhiteSpace(t);
+ t->next = NULL;
+ if (last) last->next = t;
+ else define->tokens = t;
+ last = t;
+ } while(PC_ReadLine(source, &token));
+ //
+ if (last)
+ {
+ //check for merge operators at the beginning or end
+ if (!strcmp(define->tokens->string, "##") ||
+ !strcmp(last->string, "##"))
+ {
+ SourceError(source, "define with misplaced ##");
+ return qfalse;
+ } //end if
+ } //end if
+ return qtrue;
+} //end of the function PC_Directive_define
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+define_t *PC_DefineFromString(char *string)
+{
+ script_t *script;
+ source_t src;
+ token_t *t;
+ int res, i;
+ define_t *def;
+
+ PC_InitTokenHeap();
+
+ script = LoadScriptMemory(string, strlen(string), "*extern");
+ //create a new source
+ Com_Memset(&src, 0, sizeof(source_t));
+ strncpy(src.filename, "*extern", MAX_PATH);
+ src.scriptstack = script;
+#if DEFINEHASHING
+ src.definehash = GetClearedMemory(DEFINEHASHSIZE * sizeof(define_t *));
+#endif //DEFINEHASHING
+ //create a define from the source
+ res = PC_Directive_define(&src);
+ //free any tokens if left
+ for (t = src.tokens; t; t = src.tokens)
+ {
+ src.tokens = src.tokens->next;
+ PC_FreeToken(t);
+ } //end for
+#ifdef DEFINEHASHING
+ def = NULL;
+ for (i = 0; i < DEFINEHASHSIZE; i++)
+ {
+ if (src.definehash[i])
+ {
+ def = src.definehash[i];
+ break;
+ } //end if
+ } //end for
+#else
+ def = src.defines;
+#endif //DEFINEHASHING
+ //
+#if DEFINEHASHING
+ FreeMemory(src.definehash);
+#endif //DEFINEHASHING
+ //
+ FreeScript(script);
+ //if the define was created succesfully
+ if (res > 0) return def;
+ //free the define is created
+ if (src.defines) PC_FreeDefine(def);
+ //
+ return NULL;
+} //end of the function PC_DefineFromString
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_AddDefine(source_t *source, char *string)
+{
+ define_t *define;
+
+ define = PC_DefineFromString(string);
+ if (!define) return qfalse;
+#if DEFINEHASHING
+ PC_AddDefineToHash(define, source->definehash);
+#else //DEFINEHASHING
+ define->next = source->defines;
+ source->defines = define;
+#endif //DEFINEHASHING
+ return qtrue;
+} //end of the function PC_AddDefine
+//============================================================================
+// add a globals define that will be added to all opened sources
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_AddGlobalDefine(char *string)
+{
+ define_t *define;
+
+ define = PC_DefineFromString(string);
+ if (!define) return qfalse;
+ define->next = globaldefines;
+ globaldefines = define;
+ return qtrue;
+} //end of the function PC_AddGlobalDefine
+//============================================================================
+// remove the given global define
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_RemoveGlobalDefine(char *name)
+{
+ define_t *define;
+
+ define = PC_FindDefine(globaldefines, name);
+ if (define)
+ {
+ PC_FreeDefine(define);
+ return qtrue;
+ } //end if
+ return qfalse;
+} //end of the function PC_RemoveGlobalDefine
+//============================================================================
+// remove all globals defines
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void PC_RemoveAllGlobalDefines(void)
+{
+ define_t *define;
+
+ for (define = globaldefines; define; define = globaldefines)
+ {
+ globaldefines = globaldefines->next;
+ PC_FreeDefine(define);
+ } //end for
+} //end of the function PC_RemoveAllGlobalDefines
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+define_t *PC_CopyDefine(source_t *source, define_t *define)
+{
+ define_t *newdefine;
+ token_t *token, *newtoken, *lasttoken;
+
+ newdefine = (define_t *) GetMemory(sizeof(define_t) + strlen(define->name) + 1);
+ //copy the define name
+ newdefine->name = (char *) newdefine + sizeof(define_t);
+ strcpy(newdefine->name, define->name);
+ newdefine->flags = define->flags;
+ newdefine->builtin = define->builtin;
+ newdefine->numparms = define->numparms;
+ //the define is not linked
+ newdefine->next = NULL;
+ newdefine->hashnext = NULL;
+ //copy the define tokens
+ newdefine->tokens = NULL;
+ for (lasttoken = NULL, token = define->tokens; token; token = token->next)
+ {
+ newtoken = PC_CopyToken(token);
+ newtoken->next = NULL;
+ if (lasttoken) lasttoken->next = newtoken;
+ else newdefine->tokens = newtoken;
+ lasttoken = newtoken;
+ } //end for
+ //copy the define parameters
+ newdefine->parms = NULL;
+ for (lasttoken = NULL, token = define->parms; token; token = token->next)
+ {
+ newtoken = PC_CopyToken(token);
+ newtoken->next = NULL;
+ if (lasttoken) lasttoken->next = newtoken;
+ else newdefine->parms = newtoken;
+ lasttoken = newtoken;
+ } //end for
+ return newdefine;
+} //end of the function PC_CopyDefine
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void PC_AddGlobalDefinesToSource(source_t *source)
+{
+ define_t *define, *newdefine;
+
+ for (define = globaldefines; define; define = define->next)
+ {
+ newdefine = PC_CopyDefine(source, define);
+#if DEFINEHASHING
+ PC_AddDefineToHash(newdefine, source->definehash);
+#else //DEFINEHASHING
+ newdefine->next = source->defines;
+ source->defines = newdefine;
+#endif //DEFINEHASHING
+ } //end for
+} //end of the function PC_AddGlobalDefinesToSource
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_Directive_if_def(source_t *source, int type)
+{
+ token_t token;
+ define_t *d;
+ int skip;
+
+ if (!PC_ReadLine(source, &token))
+ {
+ SourceError(source, "#ifdef without name");
+ return qfalse;
+ } //end if
+ if (token.type != TT_NAME)
+ {
+ PC_UnreadSourceToken(source, &token);
+ SourceError(source, "expected name after #ifdef, found %s", token.string);
+ return qfalse;
+ } //end if
+#if DEFINEHASHING
+ d = PC_FindHashedDefine(source->definehash, token.string);
+#else
+ d = PC_FindDefine(source->defines, token.string);
+#endif //DEFINEHASHING
+ skip = (type == INDENT_IFDEF) == (d == NULL);
+ PC_PushIndent(source, type, skip);
+ return qtrue;
+} //end of the function PC_Directiveif_def
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_Directive_ifdef(source_t *source)
+{
+ return PC_Directive_if_def(source, INDENT_IFDEF);
+} //end of the function PC_Directive_ifdef
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_Directive_ifndef(source_t *source)
+{
+ return PC_Directive_if_def(source, INDENT_IFNDEF);
+} //end of the function PC_Directive_ifndef
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_Directive_else(source_t *source)
+{
+ int type, skip;
+
+ PC_PopIndent(source, &type, &skip);
+ if (!type)
+ {
+ SourceError(source, "misplaced #else");
+ return qfalse;
+ } //end if
+ if (type == INDENT_ELSE)
+ {
+ SourceError(source, "#else after #else");
+ return qfalse;
+ } //end if
+ PC_PushIndent(source, INDENT_ELSE, !skip);
+ return qtrue;
+} //end of the function PC_Directive_else
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_Directive_endif(source_t *source)
+{
+ int type, skip;
+
+ PC_PopIndent(source, &type, &skip);
+ if (!type)
+ {
+ SourceError(source, "misplaced #endif");
+ return qfalse;
+ } //end if
+ return qtrue;
+} //end of the function PC_Directive_endif
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+typedef struct operator_s
+{
+ int operator;
+ int priority;
+ int parentheses;
+ struct operator_s *prev, *next;
+} operator_t;
+
+typedef struct value_s
+{
+ signed long int intvalue;
+ double floatvalue;
+ int parentheses;
+ struct value_s *prev, *next;
+} value_t;
+
+int PC_OperatorPriority(int op)
+{
+ switch(op)
+ {
+ case P_MUL: return 15;
+ case P_DIV: return 15;
+ case P_MOD: return 15;
+ case P_ADD: return 14;
+ case P_SUB: return 14;
+
+ case P_LOGIC_AND: return 7;
+ case P_LOGIC_OR: return 6;
+ case P_LOGIC_GEQ: return 12;
+ case P_LOGIC_LEQ: return 12;
+ case P_LOGIC_EQ: return 11;
+ case P_LOGIC_UNEQ: return 11;
+
+ case P_LOGIC_NOT: return 16;
+ case P_LOGIC_GREATER: return 12;
+ case P_LOGIC_LESS: return 12;
+
+ case P_RSHIFT: return 13;
+ case P_LSHIFT: return 13;
+
+ case P_BIN_AND: return 10;
+ case P_BIN_OR: return 8;
+ case P_BIN_XOR: return 9;
+ case P_BIN_NOT: return 16;
+
+ case P_COLON: return 5;
+ case P_QUESTIONMARK: return 5;
+ } //end switch
+ return qfalse;
+} //end of the function PC_OperatorPriority
+
+//#define AllocValue() GetClearedMemory(sizeof(value_t));
+//#define FreeValue(val) FreeMemory(val)
+//#define AllocOperator(op) op = (operator_t *) GetClearedMemory(sizeof(operator_t));
+//#define FreeOperator(op) FreeMemory(op);
+
+#define MAX_VALUES 64
+#define MAX_OPERATORS 64
+#define AllocValue(val) \
+ if (numvalues >= MAX_VALUES) { \
+ SourceError(source, "out of value space\n"); \
+ error = 1; \
+ break; \
+ } \
+ else \
+ val = &value_heap[numvalues++];
+#define FreeValue(val)
+//
+#define AllocOperator(op) \
+ if (numoperators >= MAX_OPERATORS) { \
+ SourceError(source, "out of operator space\n"); \
+ error = 1; \
+ break; \
+ } \
+ else \
+ op = &operator_heap[numoperators++];
+#define FreeOperator(op)
+
+int PC_EvaluateTokens(source_t *source, token_t *tokens, signed long int *intvalue,
+ double *floatvalue, int integer)
+{
+ operator_t *o, *firstoperator, *lastoperator;
+ value_t *v, *firstvalue, *lastvalue, *v1, *v2;
+ token_t *t;
+ int brace = 0;
+ int parentheses = 0;
+ int error = 0;
+ int lastwasvalue = 0;
+ int negativevalue = 0;
+ int questmarkintvalue = 0;
+ double questmarkfloatvalue = 0;
+ int gotquestmarkvalue = qfalse;
+ int lastoperatortype = 0;
+ //
+ operator_t operator_heap[MAX_OPERATORS];
+ int numoperators = 0;
+ value_t value_heap[MAX_VALUES];
+ int numvalues = 0;
+
+ firstoperator = lastoperator = NULL;
+ firstvalue = lastvalue = NULL;
+ if (intvalue) *intvalue = 0;
+ if (floatvalue) *floatvalue = 0;
+ for (t = tokens; t; t = t->next)
+ {
+ switch(t->type)
+ {
+ case TT_NAME:
+ {
+ if (lastwasvalue || negativevalue)
+ {
+ SourceError(source, "syntax error in #if/#elif");
+ error = 1;
+ break;
+ } //end if
+ if (strcmp(t->string, "defined"))
+ {
+ SourceError(source, "undefined name %s in #if/#elif", t->string);
+ error = 1;
+ break;
+ } //end if
+ t = t->next;
+ if (!strcmp(t->string, "("))
+ {
+ brace = qtrue;
+ t = t->next;
+ } //end if
+ if (!t || t->type != TT_NAME)
+ {
+ SourceError(source, "defined without name in #if/#elif");
+ error = 1;
+ break;
+ } //end if
+ //v = (value_t *) GetClearedMemory(sizeof(value_t));
+ AllocValue(v);
+#if DEFINEHASHING
+ if (PC_FindHashedDefine(source->definehash, t->string))
+#else
+ if (PC_FindDefine(source->defines, t->string))
+#endif //DEFINEHASHING
+ {
+ v->intvalue = 1;
+ v->floatvalue = 1;
+ } //end if
+ else
+ {
+ v->intvalue = 0;
+ v->floatvalue = 0;
+ } //end else
+ v->parentheses = parentheses;
+ v->next = NULL;
+ v->prev = lastvalue;
+ if (lastvalue) lastvalue->next = v;
+ else firstvalue = v;
+ lastvalue = v;
+ if (brace)
+ {
+ t = t->next;
+ if (!t || strcmp(t->string, ")"))
+ {
+ SourceError(source, "defined without ) in #if/#elif");
+ error = 1;
+ break;
+ } //end if
+ } //end if
+ brace = qfalse;
+ // defined() creates a value
+ lastwasvalue = 1;
+ break;
+ } //end case
+ case TT_NUMBER:
+ {
+ if (lastwasvalue)
+ {
+ SourceError(source, "syntax error in #if/#elif");
+ error = 1;
+ break;
+ } //end if
+ //v = (value_t *) GetClearedMemory(sizeof(value_t));
+ AllocValue(v);
+ if (negativevalue)
+ {
+ v->intvalue = - (signed int) t->intvalue;
+ v->floatvalue = - t->floatvalue;
+ } //end if
+ else
+ {
+ v->intvalue = t->intvalue;
+ v->floatvalue = t->floatvalue;
+ } //end else
+ v->parentheses = parentheses;
+ v->next = NULL;
+ v->prev = lastvalue;
+ if (lastvalue) lastvalue->next = v;
+ else firstvalue = v;
+ lastvalue = v;
+ //last token was a value
+ lastwasvalue = 1;
+ //
+ negativevalue = 0;
+ break;
+ } //end case
+ case TT_PUNCTUATION:
+ {
+ if (negativevalue)
+ {
+ SourceError(source, "misplaced minus sign in #if/#elif");
+ error = 1;
+ break;
+ } //end if
+ if (t->subtype == P_PARENTHESESOPEN)
+ {
+ parentheses++;
+ break;
+ } //end if
+ else if (t->subtype == P_PARENTHESESCLOSE)
+ {
+ parentheses--;
+ if (parentheses < 0)
+ {
+ SourceError(source, "too many ) in #if/#elsif");
+ error = 1;
+ } //end if
+ break;
+ } //end else if
+ //check for invalid operators on floating point values
+ if (!integer)
+ {
+ if (t->subtype == P_BIN_NOT || t->subtype == P_MOD ||
+ t->subtype == P_RSHIFT || t->subtype == P_LSHIFT ||
+ t->subtype == P_BIN_AND || t->subtype == P_BIN_OR ||
+ t->subtype == P_BIN_XOR)
+ {
+ SourceError(source, "illigal operator %s on floating point operands\n", t->string);
+ error = 1;
+ break;
+ } //end if
+ } //end if
+ switch(t->subtype)
+ {
+ case P_LOGIC_NOT:
+ case P_BIN_NOT:
+ {
+ if (lastwasvalue)
+ {
+ SourceError(source, "! or ~ after value in #if/#elif");
+ error = 1;
+ break;
+ } //end if
+ break;
+ } //end case
+ case P_INC:
+ case P_DEC:
+ {
+ SourceError(source, "++ or -- used in #if/#elif");
+ break;
+ } //end case
+ case P_SUB:
+ {
+ if (!lastwasvalue)
+ {
+ negativevalue = 1;
+ break;
+ } //end if
+ } //end case
+
+ case P_MUL:
+ case P_DIV:
+ case P_MOD:
+ case P_ADD:
+
+ case P_LOGIC_AND:
+ case P_LOGIC_OR:
+ case P_LOGIC_GEQ:
+ case P_LOGIC_LEQ:
+ case P_LOGIC_EQ:
+ case P_LOGIC_UNEQ:
+
+ case P_LOGIC_GREATER:
+ case P_LOGIC_LESS:
+
+ case P_RSHIFT:
+ case P_LSHIFT:
+
+ case P_BIN_AND:
+ case P_BIN_OR:
+ case P_BIN_XOR:
+
+ case P_COLON:
+ case P_QUESTIONMARK:
+ {
+ if (!lastwasvalue)
+ {
+ SourceError(source, "operator %s after operator in #if/#elif", t->string);
+ error = 1;
+ break;
+ } //end if
+ break;
+ } //end case
+ default:
+ {
+ SourceError(source, "invalid operator %s in #if/#elif", t->string);
+ error = 1;
+ break;
+ } //end default
+ } //end switch
+ if (!error && !negativevalue)
+ {
+ //o = (operator_t *) GetClearedMemory(sizeof(operator_t));
+ AllocOperator(o);
+ o->operator = t->subtype;
+ o->priority = PC_OperatorPriority(t->subtype);
+ o->parentheses = parentheses;
+ o->next = NULL;
+ o->prev = lastoperator;
+ if (lastoperator) lastoperator->next = o;
+ else firstoperator = o;
+ lastoperator = o;
+ lastwasvalue = 0;
+ } //end if
+ break;
+ } //end case
+ default:
+ {
+ SourceError(source, "unknown %s in #if/#elif", t->string);
+ error = 1;
+ break;
+ } //end default
+ } //end switch
+ if (error) break;
+ } //end for
+ if (!error)
+ {
+ if (!lastwasvalue)
+ {
+ SourceError(source, "trailing operator in #if/#elif");
+ error = 1;
+ } //end if
+ else if (parentheses)
+ {
+ SourceError(source, "too many ( in #if/#elif");
+ error = 1;
+ } //end else if
+ } //end if
+ //
+ gotquestmarkvalue = qfalse;
+ questmarkintvalue = 0;
+ questmarkfloatvalue = 0;
+ //while there are operators
+ while(!error && firstoperator)
+ {
+ v = firstvalue;
+ for (o = firstoperator; o->next; o = o->next)
+ {
+ //if the current operator is nested deeper in parentheses
+ //than the next operator
+ if (o->parentheses > o->next->parentheses) break;
+ //if the current and next operator are nested equally deep in parentheses
+ if (o->parentheses == o->next->parentheses)
+ {
+ //if the priority of the current operator is equal or higher
+ //than the priority of the next operator
+ if (o->priority >= o->next->priority) break;
+ } //end if
+ //if the arity of the operator isn't equal to 1
+ if (o->operator != P_LOGIC_NOT
+ && o->operator != P_BIN_NOT) v = v->next;
+ //if there's no value or no next value
+ if (!v)
+ {
+ SourceError(source, "mising values in #if/#elif");
+ error = 1;
+ break;
+ } //end if
+ } //end for
+ if (error) break;
+ v1 = v;
+ v2 = v->next;
+#ifdef DEBUG_EVAL
+ if (integer)
+ {
+ Log_Write("operator %s, value1 = %d", PunctuationFromNum(source->scriptstack, o->operator), v1->intvalue);
+ if (v2) Log_Write("value2 = %d", v2->intvalue);
+ } //end if
+ else
+ {
+ Log_Write("operator %s, value1 = %f", PunctuationFromNum(source->scriptstack, o->operator), v1->floatvalue);
+ if (v2) Log_Write("value2 = %f", v2->floatvalue);
+ } //end else
+#endif //DEBUG_EVAL
+ switch(o->operator)
+ {
+ case P_LOGIC_NOT: v1->intvalue = !v1->intvalue;
+ v1->floatvalue = !v1->floatvalue; break;
+ case P_BIN_NOT: v1->intvalue = ~v1->intvalue;
+ break;
+ case P_MUL: v1->intvalue *= v2->intvalue;
+ v1->floatvalue *= v2->floatvalue; break;
+ case P_DIV: if (!v2->intvalue || !v2->floatvalue)
+ {
+ SourceError(source, "divide by zero in #if/#elif\n");
+ error = 1;
+ break;
+ }
+ v1->intvalue /= v2->intvalue;
+ v1->floatvalue /= v2->floatvalue; break;
+ case P_MOD: if (!v2->intvalue)
+ {
+ SourceError(source, "divide by zero in #if/#elif\n");
+ error = 1;
+ break;
+ }
+ v1->intvalue %= v2->intvalue; break;
+ case P_ADD: v1->intvalue += v2->intvalue;
+ v1->floatvalue += v2->floatvalue; break;
+ case P_SUB: v1->intvalue -= v2->intvalue;
+ v1->floatvalue -= v2->floatvalue; break;
+ case P_LOGIC_AND: v1->intvalue = v1->intvalue && v2->intvalue;
+ v1->floatvalue = v1->floatvalue && v2->floatvalue; break;
+ case P_LOGIC_OR: v1->intvalue = v1->intvalue || v2->intvalue;
+ v1->floatvalue = v1->floatvalue || v2->floatvalue; break;
+ case P_LOGIC_GEQ: v1->intvalue = v1->intvalue >= v2->intvalue;
+ v1->floatvalue = v1->floatvalue >= v2->floatvalue; break;
+ case P_LOGIC_LEQ: v1->intvalue = v1->intvalue <= v2->intvalue;
+ v1->floatvalue = v1->floatvalue <= v2->floatvalue; break;
+ case P_LOGIC_EQ: v1->intvalue = v1->intvalue == v2->intvalue;
+ v1->floatvalue = v1->floatvalue == v2->floatvalue; break;
+ case P_LOGIC_UNEQ: v1->intvalue = v1->intvalue != v2->intvalue;
+ v1->floatvalue = v1->floatvalue != v2->floatvalue; break;
+ case P_LOGIC_GREATER: v1->intvalue = v1->intvalue > v2->intvalue;
+ v1->floatvalue = v1->floatvalue > v2->floatvalue; break;
+ case P_LOGIC_LESS: v1->intvalue = v1->intvalue < v2->intvalue;
+ v1->floatvalue = v1->floatvalue < v2->floatvalue; break;
+ case P_RSHIFT: v1->intvalue >>= v2->intvalue;
+ break;
+ case P_LSHIFT: v1->intvalue <<= v2->intvalue;
+ break;
+ case P_BIN_AND: v1->intvalue &= v2->intvalue;
+ break;
+ case P_BIN_OR: v1->intvalue |= v2->intvalue;
+ break;
+ case P_BIN_XOR: v1->intvalue ^= v2->intvalue;
+ break;
+ case P_COLON:
+ {
+ if (!gotquestmarkvalue)
+ {
+ SourceError(source, ": without ? in #if/#elif");
+ error = 1;
+ break;
+ } //end if
+ if (integer)
+ {
+ if (!questmarkintvalue) v1->intvalue = v2->intvalue;
+ } //end if
+ else
+ {
+ if (!questmarkfloatvalue) v1->floatvalue = v2->floatvalue;
+ } //end else
+ gotquestmarkvalue = qfalse;
+ break;
+ } //end case
+ case P_QUESTIONMARK:
+ {
+ if (gotquestmarkvalue)
+ {
+ SourceError(source, "? after ? in #if/#elif");
+ error = 1;
+ break;
+ } //end if
+ questmarkintvalue = v1->intvalue;
+ questmarkfloatvalue = v1->floatvalue;
+ gotquestmarkvalue = qtrue;
+ break;
+ } //end if
+ } //end switch
+#ifdef DEBUG_EVAL
+ if (integer) Log_Write("result value = %d", v1->intvalue);
+ else Log_Write("result value = %f", v1->floatvalue);
+#endif //DEBUG_EVAL
+ if (error) break;
+ lastoperatortype = o->operator;
+ //if not an operator with arity 1
+ if (o->operator != P_LOGIC_NOT
+ && o->operator != P_BIN_NOT)
+ {
+ //remove the second value if not question mark operator
+ if (o->operator != P_QUESTIONMARK) v = v->next;
+ //
+ if (v->prev) v->prev->next = v->next;
+ else firstvalue = v->next;
+ if (v->next) v->next->prev = v->prev;
+ else lastvalue = v->prev;
+ //FreeMemory(v);
+ FreeValue(v);
+ } //end if
+ //remove the operator
+ if (o->prev) o->prev->next = o->next;
+ else firstoperator = o->next;
+ if (o->next) o->next->prev = o->prev;
+ else lastoperator = o->prev;
+ //FreeMemory(o);
+ FreeOperator(o);
+ } //end while
+ if (firstvalue)
+ {
+ if (intvalue) *intvalue = firstvalue->intvalue;
+ if (floatvalue) *floatvalue = firstvalue->floatvalue;
+ } //end if
+ for (o = firstoperator; o; o = lastoperator)
+ {
+ lastoperator = o->next;
+ //FreeMemory(o);
+ FreeOperator(o);
+ } //end for
+ for (v = firstvalue; v; v = lastvalue)
+ {
+ lastvalue = v->next;
+ //FreeMemory(v);
+ FreeValue(v);
+ } //end for
+ if (!error) return qtrue;
+ if (intvalue) *intvalue = 0;
+ if (floatvalue) *floatvalue = 0;
+ return qfalse;
+} //end of the function PC_EvaluateTokens
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_Evaluate(source_t *source, signed long int *intvalue,
+ double *floatvalue, int integer)
+{
+ token_t token, *firsttoken, *lasttoken;
+ token_t *t, *nexttoken;
+ define_t *define;
+ int defined = qfalse;
+
+ if (intvalue) *intvalue = 0;
+ if (floatvalue) *floatvalue = 0;
+ //
+ if (!PC_ReadLine(source, &token))
+ {
+ SourceError(source, "no value after #if/#elif");
+ return qfalse;
+ } //end if
+ firsttoken = NULL;
+ lasttoken = NULL;
+ do
+ {
+ //if the token is a name
+ if (token.type == TT_NAME)
+ {
+ if (defined)
+ {
+ defined = qfalse;
+ t = PC_CopyToken(&token);
+ t->next = NULL;
+ if (lasttoken) lasttoken->next = t;
+ else firsttoken = t;
+ lasttoken = t;
+ } //end if
+ else if (!strcmp(token.string, "defined"))
+ {
+ defined = qtrue;
+ t = PC_CopyToken(&token);
+ t->next = NULL;
+ if (lasttoken) lasttoken->next = t;
+ else firsttoken = t;
+ lasttoken = t;
+ } //end if
+ else
+ {
+ //then it must be a define
+#if DEFINEHASHING
+ define = PC_FindHashedDefine(source->definehash, token.string);
+#else
+ define = PC_FindDefine(source->defines, token.string);
+#endif //DEFINEHASHING
+ if (!define)
+ {
+ SourceError(source, "can't evaluate %s, not defined", token.string);
+ return qfalse;
+ } //end if
+ if (!PC_ExpandDefineIntoSource(source, &token, define)) return qfalse;
+ } //end else
+ } //end if
+ //if the token is a number or a punctuation
+ else if (token.type == TT_NUMBER || token.type == TT_PUNCTUATION)
+ {
+ t = PC_CopyToken(&token);
+ t->next = NULL;
+ if (lasttoken) lasttoken->next = t;
+ else firsttoken = t;
+ lasttoken = t;
+ } //end else
+ else //can't evaluate the token
+ {
+ SourceError(source, "can't evaluate %s", token.string);
+ return qfalse;
+ } //end else
+ } while(PC_ReadLine(source, &token));
+ //
+ if (!PC_EvaluateTokens(source, firsttoken, intvalue, floatvalue, integer)) return qfalse;
+ //
+#ifdef DEBUG_EVAL
+ Log_Write("eval:");
+#endif //DEBUG_EVAL
+ for (t = firsttoken; t; t = nexttoken)
+ {
+#ifdef DEBUG_EVAL
+ Log_Write(" %s", t->string);
+#endif //DEBUG_EVAL
+ nexttoken = t->next;
+ PC_FreeToken(t);
+ } //end for
+#ifdef DEBUG_EVAL
+ if (integer) Log_Write("eval result: %d", *intvalue);
+ else Log_Write("eval result: %f", *floatvalue);
+#endif //DEBUG_EVAL
+ //
+ return qtrue;
+} //end of the function PC_Evaluate
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_DollarEvaluate(source_t *source, signed long int *intvalue,
+ double *floatvalue, int integer)
+{
+ int indent, defined = qfalse;
+ token_t token, *firsttoken, *lasttoken;
+ token_t *t, *nexttoken;
+ define_t *define;
+
+ if (intvalue) *intvalue = 0;
+ if (floatvalue) *floatvalue = 0;
+ //
+ if (!PC_ReadSourceToken(source, &token))
+ {
+ SourceError(source, "no leading ( after $evalint/$evalfloat");
+ return qfalse;
+ } //end if
+ if (!PC_ReadSourceToken(source, &token))
+ {
+ SourceError(source, "nothing to evaluate");
+ return qfalse;
+ } //end if
+ indent = 1;
+ firsttoken = NULL;
+ lasttoken = NULL;
+ do
+ {
+ //if the token is a name
+ if (token.type == TT_NAME)
+ {
+ if (defined)
+ {
+ defined = qfalse;
+ t = PC_CopyToken(&token);
+ t->next = NULL;
+ if (lasttoken) lasttoken->next = t;
+ else firsttoken = t;
+ lasttoken = t;
+ } //end if
+ else if (!strcmp(token.string, "defined"))
+ {
+ defined = qtrue;
+ t = PC_CopyToken(&token);
+ t->next = NULL;
+ if (lasttoken) lasttoken->next = t;
+ else firsttoken = t;
+ lasttoken = t;
+ } //end if
+ else
+ {
+ //then it must be a define
+#if DEFINEHASHING
+ define = PC_FindHashedDefine(source->definehash, token.string);
+#else
+ define = PC_FindDefine(source->defines, token.string);
+#endif //DEFINEHASHING
+ if (!define)
+ {
+ SourceError(source, "can't evaluate %s, not defined", token.string);
+ return qfalse;
+ } //end if
+ if (!PC_ExpandDefineIntoSource(source, &token, define)) return qfalse;
+ } //end else
+ } //end if
+ //if the token is a number or a punctuation
+ else if (token.type == TT_NUMBER || token.type == TT_PUNCTUATION)
+ {
+ if (*token.string == '(') indent++;
+ else if (*token.string == ')') indent--;
+ if (indent <= 0) break;
+ t = PC_CopyToken(&token);
+ t->next = NULL;
+ if (lasttoken) lasttoken->next = t;
+ else firsttoken = t;
+ lasttoken = t;
+ } //end else
+ else //can't evaluate the token
+ {
+ SourceError(source, "can't evaluate %s", token.string);
+ return qfalse;
+ } //end else
+ } while(PC_ReadSourceToken(source, &token));
+ //
+ if (!PC_EvaluateTokens(source, firsttoken, intvalue, floatvalue, integer)) return qfalse;
+ //
+#ifdef DEBUG_EVAL
+ Log_Write("$eval:");
+#endif //DEBUG_EVAL
+ for (t = firsttoken; t; t = nexttoken)
+ {
+#ifdef DEBUG_EVAL
+ Log_Write(" %s", t->string);
+#endif //DEBUG_EVAL
+ nexttoken = t->next;
+ PC_FreeToken(t);
+ } //end for
+#ifdef DEBUG_EVAL
+ if (integer) Log_Write("$eval result: %d", *intvalue);
+ else Log_Write("$eval result: %f", *floatvalue);
+#endif //DEBUG_EVAL
+ //
+ return qtrue;
+} //end of the function PC_DollarEvaluate
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_Directive_elif(source_t *source)
+{
+ signed long int value;
+ int type, skip;
+
+ PC_PopIndent(source, &type, &skip);
+ if (!type || type == INDENT_ELSE)
+ {
+ SourceError(source, "misplaced #elif");
+ return qfalse;
+ } //end if
+ if (!PC_Evaluate(source, &value, NULL, qtrue)) return qfalse;
+ skip = (value == 0);
+ PC_PushIndent(source, INDENT_ELIF, skip);
+ return qtrue;
+} //end of the function PC_Directive_elif
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_Directive_if(source_t *source)
+{
+ signed long int value;
+ int skip;
+
+ if (!PC_Evaluate(source, &value, NULL, qtrue)) return qfalse;
+ skip = (value == 0);
+ PC_PushIndent(source, INDENT_IF, skip);
+ return qtrue;
+} //end of the function PC_Directive
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_Directive_line(source_t *source)
+{
+ SourceError(source, "#line directive not supported");
+ return qfalse;
+} //end of the function PC_Directive_line
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_Directive_error(source_t *source)
+{
+ token_t token;
+
+ strcpy(token.string, "");
+ PC_ReadSourceToken(source, &token);
+ SourceError(source, "#error directive: %s", token.string);
+ return qfalse;
+} //end of the function PC_Directive_error
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_Directive_pragma(source_t *source)
+{
+ token_t token;
+
+ SourceWarning(source, "#pragma directive not supported");
+ while(PC_ReadLine(source, &token)) ;
+ return qtrue;
+} //end of the function PC_Directive_pragma
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void UnreadSignToken(source_t *source)
+{
+ token_t token;
+
+ token.line = source->scriptstack->line;
+ token.whitespace_p = source->scriptstack->script_p;
+ token.endwhitespace_p = source->scriptstack->script_p;
+ token.linescrossed = 0;
+ strcpy(token.string, "-");
+ token.type = TT_PUNCTUATION;
+ token.subtype = P_SUB;
+ PC_UnreadSourceToken(source, &token);
+} //end of the function UnreadSignToken
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_Directive_eval(source_t *source)
+{
+ signed long int value;
+ token_t token;
+
+ if (!PC_Evaluate(source, &value, NULL, qtrue)) return qfalse;
+ //
+ token.line = source->scriptstack->line;
+ token.whitespace_p = source->scriptstack->script_p;
+ token.endwhitespace_p = source->scriptstack->script_p;
+ token.linescrossed = 0;
+ sprintf(token.string, "%d", abs(value));
+ token.type = TT_NUMBER;
+ token.subtype = TT_INTEGER|TT_LONG|TT_DECIMAL;
+ PC_UnreadSourceToken(source, &token);
+ if (value < 0) UnreadSignToken(source);
+ return qtrue;
+} //end of the function PC_Directive_eval
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_Directive_evalfloat(source_t *source)
+{
+ double value;
+ token_t token;
+
+ if (!PC_Evaluate(source, NULL, &value, qfalse)) return qfalse;
+ token.line = source->scriptstack->line;
+ token.whitespace_p = source->scriptstack->script_p;
+ token.endwhitespace_p = source->scriptstack->script_p;
+ token.linescrossed = 0;
+ sprintf(token.string, "%1.2f", fabs(value));
+ token.type = TT_NUMBER;
+ token.subtype = TT_FLOAT|TT_LONG|TT_DECIMAL;
+ PC_UnreadSourceToken(source, &token);
+ if (value < 0) UnreadSignToken(source);
+ return qtrue;
+} //end of the function PC_Directive_evalfloat
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+directive_t directives[20] =
+{
+ {"if", PC_Directive_if},
+ {"ifdef", PC_Directive_ifdef},
+ {"ifndef", PC_Directive_ifndef},
+ {"elif", PC_Directive_elif},
+ {"else", PC_Directive_else},
+ {"endif", PC_Directive_endif},
+ {"include", PC_Directive_include},
+ {"define", PC_Directive_define},
+ {"undef", PC_Directive_undef},
+ {"line", PC_Directive_line},
+ {"error", PC_Directive_error},
+ {"pragma", PC_Directive_pragma},
+ {"eval", PC_Directive_eval},
+ {"evalfloat", PC_Directive_evalfloat},
+ {NULL, NULL}
+};
+
+int PC_ReadDirective(source_t *source)
+{
+ token_t token;
+ int i;
+
+ //read the directive name
+ if (!PC_ReadSourceToken(source, &token))
+ {
+ SourceError(source, "found # without name");
+ return qfalse;
+ } //end if
+ //directive name must be on the same line
+ if (token.linescrossed > 0)
+ {
+ PC_UnreadSourceToken(source, &token);
+ SourceError(source, "found # at end of line");
+ return qfalse;
+ } //end if
+ //if if is a name
+ if (token.type == TT_NAME)
+ {
+ //find the precompiler directive
+ for (i = 0; directives[i].name; i++)
+ {
+ if (!strcmp(directives[i].name, token.string))
+ {
+ return directives[i].func(source);
+ } //end if
+ } //end for
+ } //end if
+ SourceError(source, "unknown precompiler directive %s", token.string);
+ return qfalse;
+} //end of the function PC_ReadDirective
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_DollarDirective_evalint(source_t *source)
+{
+ signed long int value;
+ token_t token;
+
+ if (!PC_DollarEvaluate(source, &value, NULL, qtrue)) return qfalse;
+ //
+ token.line = source->scriptstack->line;
+ token.whitespace_p = source->scriptstack->script_p;
+ token.endwhitespace_p = source->scriptstack->script_p;
+ token.linescrossed = 0;
+ sprintf(token.string, "%d", abs(value));
+ token.type = TT_NUMBER;
+ token.subtype = TT_INTEGER|TT_LONG|TT_DECIMAL;
+#ifdef NUMBERVALUE
+ token.intvalue = value;
+ token.floatvalue = value;
+#endif //NUMBERVALUE
+ PC_UnreadSourceToken(source, &token);
+ if (value < 0) UnreadSignToken(source);
+ return qtrue;
+} //end of the function PC_DollarDirective_evalint
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_DollarDirective_evalfloat(source_t *source)
+{
+ double value;
+ token_t token;
+
+ if (!PC_DollarEvaluate(source, NULL, &value, qfalse)) return qfalse;
+ token.line = source->scriptstack->line;
+ token.whitespace_p = source->scriptstack->script_p;
+ token.endwhitespace_p = source->scriptstack->script_p;
+ token.linescrossed = 0;
+ sprintf(token.string, "%1.2f", fabs(value));
+ token.type = TT_NUMBER;
+ token.subtype = TT_FLOAT|TT_LONG|TT_DECIMAL;
+#ifdef NUMBERVALUE
+ token.intvalue = (unsigned long) value;
+ token.floatvalue = value;
+#endif //NUMBERVALUE
+ PC_UnreadSourceToken(source, &token);
+ if (value < 0) UnreadSignToken(source);
+ return qtrue;
+} //end of the function PC_DollarDirective_evalfloat
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+directive_t dollardirectives[20] =
+{
+ {"evalint", PC_DollarDirective_evalint},
+ {"evalfloat", PC_DollarDirective_evalfloat},
+ {NULL, NULL}
+};
+
+int PC_ReadDollarDirective(source_t *source)
+{
+ token_t token;
+ int i;
+
+ //read the directive name
+ if (!PC_ReadSourceToken(source, &token))
+ {
+ SourceError(source, "found $ without name");
+ return qfalse;
+ } //end if
+ //directive name must be on the same line
+ if (token.linescrossed > 0)
+ {
+ PC_UnreadSourceToken(source, &token);
+ SourceError(source, "found $ at end of line");
+ return qfalse;
+ } //end if
+ //if if is a name
+ if (token.type == TT_NAME)
+ {
+ //find the precompiler directive
+ for (i = 0; dollardirectives[i].name; i++)
+ {
+ if (!strcmp(dollardirectives[i].name, token.string))
+ {
+ return dollardirectives[i].func(source);
+ } //end if
+ } //end for
+ } //end if
+ PC_UnreadSourceToken(source, &token);
+ SourceError(source, "unknown precompiler directive %s", token.string);
+ return qfalse;
+} //end of the function PC_ReadDirective
+
+#ifdef QUAKEC
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int BuiltinFunction(source_t *source)
+{
+ token_t token;
+
+ if (!PC_ReadSourceToken(source, &token)) return qfalse;
+ if (token.type == TT_NUMBER)
+ {
+ PC_UnreadSourceToken(source, &token);
+ return qtrue;
+ } //end if
+ else
+ {
+ PC_UnreadSourceToken(source, &token);
+ return qfalse;
+ } //end else
+} //end of the function BuiltinFunction
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int QuakeCMacro(source_t *source)
+{
+ int i;
+ token_t token;
+
+ if (!PC_ReadSourceToken(source, &token)) return qtrue;
+ if (token.type != TT_NAME)
+ {
+ PC_UnreadSourceToken(source, &token);
+ return qtrue;
+ } //end if
+ //find the precompiler directive
+ for (i = 0; dollardirectives[i].name; i++)
+ {
+ if (!strcmp(dollardirectives[i].name, token.string))
+ {
+ PC_UnreadSourceToken(source, &token);
+ return qfalse;
+ } //end if
+ } //end for
+ PC_UnreadSourceToken(source, &token);
+ return qtrue;
+} //end of the function QuakeCMacro
+#endif //QUAKEC
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_ReadToken(source_t *source, token_t *token)
+{
+ define_t *define;
+
+ while(1)
+ {
+ if (!PC_ReadSourceToken(source, token)) return qfalse;
+ //check for precompiler directives
+ if (token->type == TT_PUNCTUATION && *token->string == '#')
+ {
+#ifdef QUAKEC
+ if (!BuiltinFunction(source))
+#endif //QUAKC
+ {
+ //read the precompiler directive
+ if (!PC_ReadDirective(source)) return qfalse;
+ continue;
+ } //end if
+ } //end if
+ if (token->type == TT_PUNCTUATION && *token->string == '$')
+ {
+#ifdef QUAKEC
+ if (!QuakeCMacro(source))
+#endif //QUAKEC
+ {
+ //read the precompiler directive
+ if (!PC_ReadDollarDirective(source)) return qfalse;
+ continue;
+ } //end if
+ } //end if
+ // recursively concatenate strings that are behind each other still resolving defines
+ if (token->type == TT_STRING)
+ {
+ token_t newtoken;
+ if (PC_ReadToken(source, &newtoken))
+ {
+ if (newtoken.type == TT_STRING)
+ {
+ token->string[strlen(token->string)-1] = '\0';
+ if (strlen(token->string) + strlen(newtoken.string+1) + 1 >= MAX_TOKEN)
+ {
+ SourceError(source, "string longer than MAX_TOKEN %d\n", MAX_TOKEN);
+ return qfalse;
+ }
+ strcat(token->string, newtoken.string+1);
+ }
+ else
+ {
+ PC_UnreadToken(source, &newtoken);
+ }
+ }
+ } //end if
+ //if skipping source because of conditional compilation
+ if (source->skip) continue;
+ //if the token is a name
+ if (token->type == TT_NAME)
+ {
+ //check if the name is a define macro
+#if DEFINEHASHING
+ define = PC_FindHashedDefine(source->definehash, token->string);
+#else
+ define = PC_FindDefine(source->defines, token->string);
+#endif //DEFINEHASHING
+ //if it is a define macro
+ if (define)
+ {
+ //expand the defined macro
+ if (!PC_ExpandDefineIntoSource(source, token, define)) return qfalse;
+ continue;
+ } //end if
+ } //end if
+ //copy token for unreading
+ Com_Memcpy(&source->token, token, sizeof(token_t));
+ //found a token
+ return qtrue;
+ } //end while
+} //end of the function PC_ReadToken
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_ExpectTokenString(source_t *source, char *string)
+{
+ token_t token;
+
+ if (!PC_ReadToken(source, &token))
+ {
+ SourceError(source, "couldn't find expected %s", string);
+ return qfalse;
+ } //end if
+
+ if (strcmp(token.string, string))
+ {
+ SourceError(source, "expected %s, found %s", string, token.string);
+ return qfalse;
+ } //end if
+ return qtrue;
+} //end of the function PC_ExpectTokenString
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_ExpectTokenType(source_t *source, int type, int subtype, token_t *token)
+{
+ char str[MAX_TOKEN];
+
+ if (!PC_ReadToken(source, token))
+ {
+ SourceError(source, "couldn't read expected token");
+ return qfalse;
+ } //end if
+
+ if (token->type != type)
+ {
+ strcpy(str, "");
+ if (type == TT_STRING) strcpy(str, "string");
+ if (type == TT_LITERAL) strcpy(str, "literal");
+ if (type == TT_NUMBER) strcpy(str, "number");
+ if (type == TT_NAME) strcpy(str, "name");
+ if (type == TT_PUNCTUATION) strcpy(str, "punctuation");
+ SourceError(source, "expected a %s, found %s", str, token->string);
+ return qfalse;
+ } //end if
+ if (token->type == TT_NUMBER)
+ {
+ if ((token->subtype & subtype) != subtype)
+ {
+ if (subtype & TT_DECIMAL) strcpy(str, "decimal");
+ if (subtype & TT_HEX) strcpy(str, "hex");
+ if (subtype & TT_OCTAL) strcpy(str, "octal");
+ if (subtype & TT_BINARY) strcpy(str, "binary");
+ if (subtype & TT_LONG) strcat(str, " long");
+ if (subtype & TT_UNSIGNED) strcat(str, " unsigned");
+ if (subtype & TT_FLOAT) strcat(str, " float");
+ if (subtype & TT_INTEGER) strcat(str, " integer");
+ SourceError(source, "expected %s, found %s", str, token->string);
+ return qfalse;
+ } //end if
+ } //end if
+ else if (token->type == TT_PUNCTUATION)
+ {
+ if (token->subtype != subtype)
+ {
+ SourceError(source, "found %s", token->string);
+ return qfalse;
+ } //end if
+ } //end else if
+ return qtrue;
+} //end of the function PC_ExpectTokenType
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_ExpectAnyToken(source_t *source, token_t *token)
+{
+ if (!PC_ReadToken(source, token))
+ {
+ SourceError(source, "couldn't read expected token");
+ return qfalse;
+ } //end if
+ else
+ {
+ return qtrue;
+ } //end else
+} //end of the function PC_ExpectAnyToken
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_CheckTokenString(source_t *source, char *string)
+{
+ token_t tok;
+
+ if (!PC_ReadToken(source, &tok)) return qfalse;
+ //if the token is available
+ if (!strcmp(tok.string, string)) return qtrue;
+ //
+ PC_UnreadSourceToken(source, &tok);
+ return qfalse;
+} //end of the function PC_CheckTokenString
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_CheckTokenType(source_t *source, int type, int subtype, token_t *token)
+{
+ token_t tok;
+
+ if (!PC_ReadToken(source, &tok)) return qfalse;
+ //if the type matches
+ if (tok.type == type &&
+ (tok.subtype & subtype) == subtype)
+ {
+ Com_Memcpy(token, &tok, sizeof(token_t));
+ return qtrue;
+ } //end if
+ //
+ PC_UnreadSourceToken(source, &tok);
+ return qfalse;
+} //end of the function PC_CheckTokenType
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_SkipUntilString(source_t *source, char *string)
+{
+ token_t token;
+
+ while(PC_ReadToken(source, &token))
+ {
+ if (!strcmp(token.string, string)) return qtrue;
+ } //end while
+ return qfalse;
+} //end of the function PC_SkipUntilString
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void PC_UnreadLastToken(source_t *source)
+{
+ PC_UnreadSourceToken(source, &source->token);
+} //end of the function PC_UnreadLastToken
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void PC_UnreadToken(source_t *source, token_t *token)
+{
+ PC_UnreadSourceToken(source, token);
+} //end of the function PC_UnreadToken
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void PC_SetIncludePath(source_t *source, char *path)
+{
+ strncpy(source->includepath, path, MAX_PATH);
+ //add trailing path seperator
+ if (source->includepath[strlen(source->includepath)-1] != '\\' &&
+ source->includepath[strlen(source->includepath)-1] != '/')
+ {
+ strcat(source->includepath, PATHSEPERATOR_STR);
+ } //end if
+} //end of the function PC_SetIncludePath
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void PC_SetPunctuations(source_t *source, punctuation_t *p)
+{
+ source->punctuations = p;
+} //end of the function PC_SetPunctuations
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+source_t *LoadSourceFile(const char *filename)
+{
+ source_t *source;
+ script_t *script;
+
+ PC_InitTokenHeap();
+
+ script = LoadScriptFile(filename);
+ if (!script) return NULL;
+
+ script->next = NULL;
+
+ source = (source_t *) GetMemory(sizeof(source_t));
+ Com_Memset(source, 0, sizeof(source_t));
+
+ strncpy(source->filename, filename, MAX_PATH);
+ source->scriptstack = script;
+ source->tokens = NULL;
+ source->defines = NULL;
+ source->indentstack = NULL;
+ source->skip = 0;
+
+#if DEFINEHASHING
+ source->definehash = GetClearedMemory(DEFINEHASHSIZE * sizeof(define_t *));
+#endif //DEFINEHASHING
+ PC_AddGlobalDefinesToSource(source);
+ return source;
+} //end of the function LoadSourceFile
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+source_t *LoadSourceMemory(char *ptr, int length, char *name)
+{
+ source_t *source;
+ script_t *script;
+
+ PC_InitTokenHeap();
+
+ script = LoadScriptMemory(ptr, length, name);
+ if (!script) return NULL;
+ script->next = NULL;
+
+ source = (source_t *) GetMemory(sizeof(source_t));
+ Com_Memset(source, 0, sizeof(source_t));
+
+ strncpy(source->filename, name, MAX_PATH);
+ source->scriptstack = script;
+ source->tokens = NULL;
+ source->defines = NULL;
+ source->indentstack = NULL;
+ source->skip = 0;
+
+#if DEFINEHASHING
+ source->definehash = GetClearedMemory(DEFINEHASHSIZE * sizeof(define_t *));
+#endif //DEFINEHASHING
+ PC_AddGlobalDefinesToSource(source);
+ return source;
+} //end of the function LoadSourceMemory
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void FreeSource(source_t *source)
+{
+ script_t *script;
+ token_t *token;
+ define_t *define;
+ indent_t *indent;
+ int i;
+
+ //PC_PrintDefineHashTable(source->definehash);
+ //free all the scripts
+ while(source->scriptstack)
+ {
+ script = source->scriptstack;
+ source->scriptstack = source->scriptstack->next;
+ FreeScript(script);
+ } //end for
+ //free all the tokens
+ while(source->tokens)
+ {
+ token = source->tokens;
+ source->tokens = source->tokens->next;
+ PC_FreeToken(token);
+ } //end for
+#if DEFINEHASHING
+ for (i = 0; i < DEFINEHASHSIZE; i++)
+ {
+ while(source->definehash[i])
+ {
+ define = source->definehash[i];
+ source->definehash[i] = source->definehash[i]->hashnext;
+ PC_FreeDefine(define);
+ } //end while
+ } //end for
+#else //DEFINEHASHING
+ //free all defines
+ while(source->defines)
+ {
+ define = source->defines;
+ source->defines = source->defines->next;
+ PC_FreeDefine(define);
+ } //end for
+#endif //DEFINEHASHING
+ //free all indents
+ while(source->indentstack)
+ {
+ indent = source->indentstack;
+ source->indentstack = source->indentstack->next;
+ FreeMemory(indent);
+ } //end for
+#if DEFINEHASHING
+ //
+ if (source->definehash) FreeMemory(source->definehash);
+#endif //DEFINEHASHING
+ //free the source itself
+ FreeMemory(source);
+} //end of the function FreeSource
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+
+#define MAX_SOURCEFILES 64
+
+source_t *sourceFiles[MAX_SOURCEFILES];
+
+int PC_LoadSourceHandle(const char *filename)
+{
+ source_t *source;
+ int i;
+
+ for (i = 1; i < MAX_SOURCEFILES; i++)
+ {
+ if (!sourceFiles[i])
+ break;
+ } //end for
+ if (i >= MAX_SOURCEFILES)
+ return 0;
+ PS_SetBaseFolder("");
+ source = LoadSourceFile(filename);
+ if (!source)
+ return 0;
+ sourceFiles[i] = source;
+ return i;
+} //end of the function PC_LoadSourceHandle
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_FreeSourceHandle(int handle)
+{
+ if (handle < 1 || handle >= MAX_SOURCEFILES)
+ return qfalse;
+ if (!sourceFiles[handle])
+ return qfalse;
+
+ FreeSource(sourceFiles[handle]);
+ sourceFiles[handle] = NULL;
+ return qtrue;
+} //end of the function PC_FreeSourceHandle
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_ReadTokenHandle(int handle, pc_token_t *pc_token)
+{
+ token_t token;
+ int ret;
+
+ if (handle < 1 || handle >= MAX_SOURCEFILES)
+ return 0;
+ if (!sourceFiles[handle])
+ return 0;
+
+ ret = PC_ReadToken(sourceFiles[handle], &token);
+ strcpy(pc_token->string, token.string);
+ pc_token->type = token.type;
+ pc_token->subtype = token.subtype;
+ pc_token->intvalue = token.intvalue;
+ pc_token->floatvalue = token.floatvalue;
+ if (pc_token->type == TT_STRING)
+ StripDoubleQuotes(pc_token->string);
+ return ret;
+} //end of the function PC_ReadTokenHandle
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PC_SourceFileAndLine(int handle, char *filename, int *line)
+{
+ if (handle < 1 || handle >= MAX_SOURCEFILES)
+ return qfalse;
+ if (!sourceFiles[handle])
+ return qfalse;
+
+ strcpy(filename, sourceFiles[handle]->filename);
+ if (sourceFiles[handle]->scriptstack)
+ *line = sourceFiles[handle]->scriptstack->line;
+ else
+ *line = 0;
+ return qtrue;
+} //end of the function PC_SourceFileAndLine
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void PC_SetBaseFolder(char *path)
+{
+ PS_SetBaseFolder(path);
+} //end of the function PC_SetBaseFolder
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void PC_CheckOpenSourceHandles(void)
+{
+ int i;
+
+ for (i = 1; i < MAX_SOURCEFILES; i++)
+ {
+ if (sourceFiles[i])
+ {
+#ifdef BOTLIB
+ botimport.Print(PRT_ERROR, "file %s still open in precompiler\n", sourceFiles[i]->scriptstack->filename);
+#endif //BOTLIB
+ } //end if
+ } //end for
+} //end of the function PC_CheckOpenSourceHandles
+
diff --git a/code/botlib/l_precomp.h b/code/botlib/l_precomp.h
new file mode 100755
index 0000000..b2da94f
--- /dev/null
+++ b/code/botlib/l_precomp.h
@@ -0,0 +1,180 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: l_precomp.h
+ *
+ * desc: pre compiler
+ *
+ * $Archive: /source/code/botlib/l_precomp.h $
+ *
+ *****************************************************************************/
+
+#ifndef MAX_PATH
+ #define MAX_PATH MAX_QPATH
+#endif
+
+#ifndef PATH_SEPERATORSTR
+ #if defined(WIN32)|defined(_WIN32)|defined(__NT__)|defined(__WINDOWS__)|defined(__WINDOWS_386__)
+ #define PATHSEPERATOR_STR "\\"
+ #else
+ #define PATHSEPERATOR_STR "/"
+ #endif
+#endif
+#ifndef PATH_SEPERATORCHAR
+ #if defined(WIN32)|defined(_WIN32)|defined(__NT__)|defined(__WINDOWS__)|defined(__WINDOWS_386__)
+ #define PATHSEPERATOR_CHAR '\\'
+ #else
+ #define PATHSEPERATOR_CHAR '/'
+ #endif
+#endif
+
+#if defined(BSPC) && !defined(QDECL)
+#define QDECL
+#endif
+
+
+#define DEFINE_FIXED 0x0001
+
+#define BUILTIN_LINE 1
+#define BUILTIN_FILE 2
+#define BUILTIN_DATE 3
+#define BUILTIN_TIME 4
+#define BUILTIN_STDC 5
+
+#define INDENT_IF 0x0001
+#define INDENT_ELSE 0x0002
+#define INDENT_ELIF 0x0004
+#define INDENT_IFDEF 0x0008
+#define INDENT_IFNDEF 0x0010
+
+//macro definitions
+typedef struct define_s
+{
+ char *name; //define name
+ int flags; //define flags
+ int builtin; // > 0 if builtin define
+ int numparms; //number of define parameters
+ token_t *parms; //define parameters
+ token_t *tokens; //macro tokens (possibly containing parm tokens)
+ struct define_s *next; //next defined macro in a list
+ struct define_s *hashnext; //next define in the hash chain
+} define_t;
+
+//indents
+//used for conditional compilation directives:
+//#if, #else, #elif, #ifdef, #ifndef
+typedef struct indent_s
+{
+ int type; //indent type
+ int skip; //true if skipping current indent
+ script_t *script; //script the indent was in
+ struct indent_s *next; //next indent on the indent stack
+} indent_t;
+
+//source file
+typedef struct source_s
+{
+ char filename[1024]; //file name of the script
+ char includepath[1024]; //path to include files
+ punctuation_t *punctuations; //punctuations to use
+ script_t *scriptstack; //stack with scripts of the source
+ token_t *tokens; //tokens to read first
+ define_t *defines; //list with macro definitions
+ define_t **definehash; //hash chain with defines
+ indent_t *indentstack; //stack with indents
+ int skip; // > 0 if skipping conditional code
+ token_t token; //last read token
+} source_t;
+
+
+//read a token from the source
+int PC_ReadToken(source_t *source, token_t *token);
+//expect a certain token
+int PC_ExpectTokenString(source_t *source, char *string);
+//expect a certain token type
+int PC_ExpectTokenType(source_t *source, int type, int subtype, token_t *token);
+//expect a token
+int PC_ExpectAnyToken(source_t *source, token_t *token);
+//returns true when the token is available
+int PC_CheckTokenString(source_t *source, char *string);
+//returns true an reads the token when a token with the given type is available
+int PC_CheckTokenType(source_t *source, int type, int subtype, token_t *token);
+//skip tokens until the given token string is read
+int PC_SkipUntilString(source_t *source, char *string);
+//unread the last token read from the script
+void PC_UnreadLastToken(source_t *source);
+//unread the given token
+void PC_UnreadToken(source_t *source, token_t *token);
+//read a token only if on the same line, lines are concatenated with a slash
+int PC_ReadLine(source_t *source, token_t *token);
+//returns true if there was a white space in front of the token
+int PC_WhiteSpaceBeforeToken(token_t *token);
+//add a define to the source
+int PC_AddDefine(source_t *source, char *string);
+//add a globals define that will be added to all opened sources
+int PC_AddGlobalDefine(char *string);
+//remove the given global define
+int PC_RemoveGlobalDefine(char *name);
+//remove all globals defines
+void PC_RemoveAllGlobalDefines(void);
+//add builtin defines
+void PC_AddBuiltinDefines(source_t *source);
+//set the source include path
+void PC_SetIncludePath(source_t *source, char *path);
+//set the punction set
+void PC_SetPunctuations(source_t *source, punctuation_t *p);
+//set the base folder to load files from
+void PC_SetBaseFolder(char *path);
+//load a source file
+source_t *LoadSourceFile(const char *filename);
+//load a source from memory
+source_t *LoadSourceMemory(char *ptr, int length, char *name);
+//free the given source
+void FreeSource(source_t *source);
+//print a source error
+void QDECL SourceError(source_t *source, char *str, ...);
+//print a source warning
+void QDECL SourceWarning(source_t *source, char *str, ...);
+
+#ifdef BSPC
+// some of BSPC source does include game/q_shared.h and some does not
+// we define pc_token_s pc_token_t if needed (yes, it's ugly)
+#ifndef __Q_SHARED_H
+#define MAX_TOKENLENGTH 1024
+typedef struct pc_token_s
+{
+ int type;
+ int subtype;
+ int intvalue;
+ float floatvalue;
+ char string[MAX_TOKENLENGTH];
+} pc_token_t;
+#endif //!_Q_SHARED_H
+#endif //BSPC
+
+//
+int PC_LoadSourceHandle(const char *filename);
+int PC_FreeSourceHandle(int handle);
+int PC_ReadTokenHandle(int handle, pc_token_t *pc_token);
+int PC_SourceFileAndLine(int handle, char *filename, int *line);
+void PC_CheckOpenSourceHandles(void);
diff --git a/code/botlib/l_script.c b/code/botlib/l_script.c
new file mode 100755
index 0000000..2f1e4fa
--- /dev/null
+++ b/code/botlib/l_script.c
@@ -0,0 +1,1433 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: l_script.c
+ *
+ * desc: lexicographical parser
+ *
+ * $Archive: /MissionPack/code/botlib/l_script.c $
+ *
+ *****************************************************************************/
+
+//#define SCREWUP
+//#define BOTLIB
+//#define MEQCC
+//#define BSPC
+
+#ifdef SCREWUP
+#include <stdio.h>
+#include <stdlib.h>
+#include <limits.h>
+#include <string.h>
+#include <stdarg.h>
+#include "l_memory.h"
+#include "l_script.h"
+
+typedef enum {qfalse, qtrue} qboolean;
+
+#endif //SCREWUP
+
+#ifdef BOTLIB
+//include files for usage in the bot library
+#include "../game/q_shared.h"
+#include "../game/botlib.h"
+#include "be_interface.h"
+#include "l_script.h"
+#include "l_memory.h"
+#include "l_log.h"
+#include "l_libvar.h"
+#endif //BOTLIB
+
+#ifdef MEQCC
+//include files for usage in MrElusive's QuakeC Compiler
+#include "qcc.h"
+#include "l_script.h"
+#include "l_memory.h"
+#include "l_log.h"
+
+#define qtrue true
+#define qfalse false
+#endif //MEQCC
+
+#ifdef BSPC
+//include files for usage in the BSP Converter
+#include "../bspc/qbsp.h"
+#include "../bspc/l_log.h"
+#include "../bspc/l_mem.h"
+
+#define qtrue true
+#define qfalse false
+#endif //BSPC
+
+
+#define PUNCTABLE
+
+//longer punctuations first
+punctuation_t default_punctuations[] =
+{
+ //binary operators
+ {">>=",P_RSHIFT_ASSIGN, NULL},
+ {"<<=",P_LSHIFT_ASSIGN, NULL},
+ //
+ {"...",P_PARMS, NULL},
+ //define merge operator
+ {"##",P_PRECOMPMERGE, NULL},
+ //logic operators
+ {"&&",P_LOGIC_AND, NULL},
+ {"||",P_LOGIC_OR, NULL},
+ {">=",P_LOGIC_GEQ, NULL},
+ {"<=",P_LOGIC_LEQ, NULL},
+ {"==",P_LOGIC_EQ, NULL},
+ {"!=",P_LOGIC_UNEQ, NULL},
+ //arithmatic operators
+ {"*=",P_MUL_ASSIGN, NULL},
+ {"/=",P_DIV_ASSIGN, NULL},
+ {"%=",P_MOD_ASSIGN, NULL},
+ {"+=",P_ADD_ASSIGN, NULL},
+ {"-=",P_SUB_ASSIGN, NULL},
+ {"++",P_INC, NULL},
+ {"--",P_DEC, NULL},
+ //binary operators
+ {"&=",P_BIN_AND_ASSIGN, NULL},
+ {"|=",P_BIN_OR_ASSIGN, NULL},
+ {"^=",P_BIN_XOR_ASSIGN, NULL},
+ {">>",P_RSHIFT, NULL},
+ {"<<",P_LSHIFT, NULL},
+ //reference operators
+ {"->",P_POINTERREF, NULL},
+ //C++
+ {"::",P_CPP1, NULL},
+ {".*",P_CPP2, NULL},
+ //arithmatic operators
+ {"*",P_MUL, NULL},
+ {"/",P_DIV, NULL},
+ {"%",P_MOD, NULL},
+ {"+",P_ADD, NULL},
+ {"-",P_SUB, NULL},
+ {"=",P_ASSIGN, NULL},
+ //binary operators
+ {"&",P_BIN_AND, NULL},
+ {"|",P_BIN_OR, NULL},
+ {"^",P_BIN_XOR, NULL},
+ {"~",P_BIN_NOT, NULL},
+ //logic operators
+ {"!",P_LOGIC_NOT, NULL},
+ {">",P_LOGIC_GREATER, NULL},
+ {"<",P_LOGIC_LESS, NULL},
+ //reference operator
+ {".",P_REF, NULL},
+ //seperators
+ {",",P_COMMA, NULL},
+ {";",P_SEMICOLON, NULL},
+ //label indication
+ {":",P_COLON, NULL},
+ //if statement
+ {"?",P_QUESTIONMARK, NULL},
+ //embracements
+ {"(",P_PARENTHESESOPEN, NULL},
+ {")",P_PARENTHESESCLOSE, NULL},
+ {"{",P_BRACEOPEN, NULL},
+ {"}",P_BRACECLOSE, NULL},
+ {"[",P_SQBRACKETOPEN, NULL},
+ {"]",P_SQBRACKETCLOSE, NULL},
+ //
+ {"\\",P_BACKSLASH, NULL},
+ //precompiler operator
+ {"#",P_PRECOMP, NULL},
+#ifdef DOLLAR
+ {"$",P_DOLLAR, NULL},
+#endif //DOLLAR
+ {NULL, 0}
+};
+
+#ifdef BSPC
+char basefolder[MAX_PATH];
+#else
+char basefolder[MAX_QPATH];
+#endif
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void PS_CreatePunctuationTable(script_t *script, punctuation_t *punctuations)
+{
+ int i;
+ punctuation_t *p, *lastp, *newp;
+
+ //get memory for the table
+ if (!script->punctuationtable) script->punctuationtable = (punctuation_t **)
+ GetMemory(256 * sizeof(punctuation_t *));
+ Com_Memset(script->punctuationtable, 0, 256 * sizeof(punctuation_t *));
+ //add the punctuations in the list to the punctuation table
+ for (i = 0; punctuations[i].p; i++)
+ {
+ newp = &punctuations[i];
+ lastp = NULL;
+ //sort the punctuations in this table entry on length (longer punctuations first)
+ for (p = script->punctuationtable[(unsigned int) newp->p[0]]; p; p = p->next)
+ {
+ if (strlen(p->p) < strlen(newp->p))
+ {
+ newp->next = p;
+ if (lastp) lastp->next = newp;
+ else script->punctuationtable[(unsigned int) newp->p[0]] = newp;
+ break;
+ } //end if
+ lastp = p;
+ } //end for
+ if (!p)
+ {
+ newp->next = NULL;
+ if (lastp) lastp->next = newp;
+ else script->punctuationtable[(unsigned int) newp->p[0]] = newp;
+ } //end if
+ } //end for
+} //end of the function PS_CreatePunctuationTable
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+char *PunctuationFromNum(script_t *script, int num)
+{
+ int i;
+
+ for (i = 0; script->punctuations[i].p; i++)
+ {
+ if (script->punctuations[i].n == num) return script->punctuations[i].p;
+ } //end for
+ return "unkown punctuation";
+} //end of the function PunctuationFromNum
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void QDECL ScriptError(script_t *script, char *str, ...)
+{
+ char text[1024];
+ va_list ap;
+
+ if (script->flags & SCFL_NOERRORS) return;
+
+ va_start(ap, str);
+ vsprintf(text, str, ap);
+ va_end(ap);
+#ifdef BOTLIB
+ botimport.Print(PRT_ERROR, "file %s, line %d: %s\n", script->filename, script->line, text);
+#endif //BOTLIB
+#ifdef MEQCC
+ printf("error: file %s, line %d: %s\n", script->filename, script->line, text);
+#endif //MEQCC
+#ifdef BSPC
+ Log_Print("error: file %s, line %d: %s\n", script->filename, script->line, text);
+#endif //BSPC
+} //end of the function ScriptError
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void QDECL ScriptWarning(script_t *script, char *str, ...)
+{
+ char text[1024];
+ va_list ap;
+
+ if (script->flags & SCFL_NOWARNINGS) return;
+
+ va_start(ap, str);
+ vsprintf(text, str, ap);
+ va_end(ap);
+#ifdef BOTLIB
+ botimport.Print(PRT_WARNING, "file %s, line %d: %s\n", script->filename, script->line, text);
+#endif //BOTLIB
+#ifdef MEQCC
+ printf("warning: file %s, line %d: %s\n", script->filename, script->line, text);
+#endif //MEQCC
+#ifdef BSPC
+ Log_Print("warning: file %s, line %d: %s\n", script->filename, script->line, text);
+#endif //BSPC
+} //end of the function ScriptWarning
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void SetScriptPunctuations(script_t *script, punctuation_t *p)
+{
+#ifdef PUNCTABLE
+ if (p) PS_CreatePunctuationTable(script, p);
+ else PS_CreatePunctuationTable(script, default_punctuations);
+#endif //PUNCTABLE
+ if (p) script->punctuations = p;
+ else script->punctuations = default_punctuations;
+} //end of the function SetScriptPunctuations
+//============================================================================
+// Reads spaces, tabs, C-like comments etc.
+// When a newline character is found the scripts line counter is increased.
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PS_ReadWhiteSpace(script_t *script)
+{
+ while(1)
+ {
+ //skip white space
+ while(*script->script_p <= ' ')
+ {
+ if (!*script->script_p) return 0;
+ if (*script->script_p == '\n') script->line++;
+ script->script_p++;
+ } //end while
+ //skip comments
+ if (*script->script_p == '/')
+ {
+ //comments //
+ if (*(script->script_p+1) == '/')
+ {
+ script->script_p++;
+ do
+ {
+ script->script_p++;
+ if (!*script->script_p) return 0;
+ } //end do
+ while(*script->script_p != '\n');
+ script->line++;
+ script->script_p++;
+ if (!*script->script_p) return 0;
+ continue;
+ } //end if
+ //comments /* */
+ else if (*(script->script_p+1) == '*')
+ {
+ script->script_p++;
+ do
+ {
+ script->script_p++;
+ if (!*script->script_p) return 0;
+ if (*script->script_p == '\n') script->line++;
+ } //end do
+ while(!(*script->script_p == '*' && *(script->script_p+1) == '/'));
+ script->script_p++;
+ if (!*script->script_p) return 0;
+ script->script_p++;
+ if (!*script->script_p) return 0;
+ continue;
+ } //end if
+ } //end if
+ break;
+ } //end while
+ return 1;
+} //end of the function PS_ReadWhiteSpace
+//============================================================================
+// Reads an escape character.
+//
+// Parameter: script : script to read from
+// ch : place to store the read escape character
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PS_ReadEscapeCharacter(script_t *script, char *ch)
+{
+ int c, val, i;
+
+ //step over the leading '\\'
+ script->script_p++;
+ //determine the escape character
+ switch(*script->script_p)
+ {
+ case '\\': c = '\\'; break;
+ case 'n': c = '\n'; break;
+ case 'r': c = '\r'; break;
+ case 't': c = '\t'; break;
+ case 'v': c = '\v'; break;
+ case 'b': c = '\b'; break;
+ case 'f': c = '\f'; break;
+ case 'a': c = '\a'; break;
+ case '\'': c = '\''; break;
+ case '\"': c = '\"'; break;
+ case '\?': c = '\?'; break;
+ case 'x':
+ {
+ script->script_p++;
+ for (i = 0, val = 0; ; i++, script->script_p++)
+ {
+ c = *script->script_p;
+ if (c >= '0' && c <= '9') c = c - '0';
+ else if (c >= 'A' && c <= 'Z') c = c - 'A' + 10;
+ else if (c >= 'a' && c <= 'z') c = c - 'a' + 10;
+ else break;
+ val = (val << 4) + c;
+ } //end for
+ script->script_p--;
+ if (val > 0xFF)
+ {
+ ScriptWarning(script, "too large value in escape character");
+ val = 0xFF;
+ } //end if
+ c = val;
+ break;
+ } //end case
+ default: //NOTE: decimal ASCII code, NOT octal
+ {
+ if (*script->script_p < '0' || *script->script_p > '9') ScriptError(script, "unknown escape char");
+ for (i = 0, val = 0; ; i++, script->script_p++)
+ {
+ c = *script->script_p;
+ if (c >= '0' && c <= '9') c = c - '0';
+ else break;
+ val = val * 10 + c;
+ } //end for
+ script->script_p--;
+ if (val > 0xFF)
+ {
+ ScriptWarning(script, "too large value in escape character");
+ val = 0xFF;
+ } //end if
+ c = val;
+ break;
+ } //end default
+ } //end switch
+ //step over the escape character or the last digit of the number
+ script->script_p++;
+ //store the escape character
+ *ch = c;
+ //succesfully read escape character
+ return 1;
+} //end of the function PS_ReadEscapeCharacter
+//============================================================================
+// Reads C-like string. Escape characters are interpretted.
+// Quotes are included with the string.
+// Reads two strings with a white space between them as one string.
+//
+// Parameter: script : script to read from
+// token : buffer to store the string
+// Returns: qtrue when a string was read succesfully
+// Changes Globals: -
+//============================================================================
+int PS_ReadString(script_t *script, token_t *token, int quote)
+{
+ int len, tmpline;
+ char *tmpscript_p;
+
+ if (quote == '\"') token->type = TT_STRING;
+ else token->type = TT_LITERAL;
+
+ len = 0;
+ //leading quote
+ token->string[len++] = *script->script_p++;
+ //
+ while(1)
+ {
+ //minus 2 because trailing double quote and zero have to be appended
+ if (len >= MAX_TOKEN - 2)
+ {
+ ScriptError(script, "string longer than MAX_TOKEN = %d", MAX_TOKEN);
+ return 0;
+ } //end if
+ //if there is an escape character and
+ //if escape characters inside a string are allowed
+ if (*script->script_p == '\\' && !(script->flags & SCFL_NOSTRINGESCAPECHARS))
+ {
+ if (!PS_ReadEscapeCharacter(script, &token->string[len]))
+ {
+ token->string[len] = 0;
+ return 0;
+ } //end if
+ len++;
+ } //end if
+ //if a trailing quote
+ else if (*script->script_p == quote)
+ {
+ //step over the double quote
+ script->script_p++;
+ //if white spaces in a string are not allowed
+ if (script->flags & SCFL_NOSTRINGWHITESPACES) break;
+ //
+ tmpscript_p = script->script_p;
+ tmpline = script->line;
+ //read unusefull stuff between possible two following strings
+ if (!PS_ReadWhiteSpace(script))
+ {
+ script->script_p = tmpscript_p;
+ script->line = tmpline;
+ break;
+ } //end if
+ //if there's no leading double qoute
+ if (*script->script_p != quote)
+ {
+ script->script_p = tmpscript_p;
+ script->line = tmpline;
+ break;
+ } //end if
+ //step over the new leading double quote
+ script->script_p++;
+ } //end if
+ else
+ {
+ if (*script->script_p == '\0')
+ {
+ token->string[len] = 0;
+ ScriptError(script, "missing trailing quote");
+ return 0;
+ } //end if
+ if (*script->script_p == '\n')
+ {
+ token->string[len] = 0;
+ ScriptError(script, "newline inside string %s", token->string);
+ return 0;
+ } //end if
+ token->string[len++] = *script->script_p++;
+ } //end else
+ } //end while
+ //trailing quote
+ token->string[len++] = quote;
+ //end string with a zero
+ token->string[len] = '\0';
+ //the sub type is the length of the string
+ token->subtype = len;
+ return 1;
+} //end of the function PS_ReadString
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PS_ReadName(script_t *script, token_t *token)
+{
+ int len = 0;
+ char c;
+
+ token->type = TT_NAME;
+ do
+ {
+ token->string[len++] = *script->script_p++;
+ if (len >= MAX_TOKEN)
+ {
+ ScriptError(script, "name longer than MAX_TOKEN = %d", MAX_TOKEN);
+ return 0;
+ } //end if
+ c = *script->script_p;
+ } while ((c >= 'a' && c <= 'z') ||
+ (c >= 'A' && c <= 'Z') ||
+ (c >= '0' && c <= '9') ||
+ c == '_');
+ token->string[len] = '\0';
+ //the sub type is the length of the name
+ token->subtype = len;
+ return 1;
+} //end of the function PS_ReadName
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void NumberValue(char *string, int subtype, unsigned long int *intvalue,
+ long double *floatvalue)
+{
+ unsigned long int dotfound = 0;
+
+ *intvalue = 0;
+ *floatvalue = 0;
+ //floating point number
+ if (subtype & TT_FLOAT)
+ {
+ while(*string)
+ {
+ if (*string == '.')
+ {
+ if (dotfound) return;
+ dotfound = 10;
+ string++;
+ } //end if
+ if (dotfound)
+ {
+ *floatvalue = *floatvalue + (long double) (*string - '0') /
+ (long double) dotfound;
+ dotfound *= 10;
+ } //end if
+ else
+ {
+ *floatvalue = *floatvalue * 10.0 + (long double) (*string - '0');
+ } //end else
+ string++;
+ } //end while
+ *intvalue = (unsigned long) *floatvalue;
+ } //end if
+ else if (subtype & TT_DECIMAL)
+ {
+ while(*string) *intvalue = *intvalue * 10 + (*string++ - '0');
+ *floatvalue = *intvalue;
+ } //end else if
+ else if (subtype & TT_HEX)
+ {
+ //step over the leading 0x or 0X
+ string += 2;
+ while(*string)
+ {
+ *intvalue <<= 4;
+ if (*string >= 'a' && *string <= 'f') *intvalue += *string - 'a' + 10;
+ else if (*string >= 'A' && *string <= 'F') *intvalue += *string - 'A' + 10;
+ else *intvalue += *string - '0';
+ string++;
+ } //end while
+ *floatvalue = *intvalue;
+ } //end else if
+ else if (subtype & TT_OCTAL)
+ {
+ //step over the first zero
+ string += 1;
+ while(*string) *intvalue = (*intvalue << 3) + (*string++ - '0');
+ *floatvalue = *intvalue;
+ } //end else if
+ else if (subtype & TT_BINARY)
+ {
+ //step over the leading 0b or 0B
+ string += 2;
+ while(*string) *intvalue = (*intvalue << 1) + (*string++ - '0');
+ *floatvalue = *intvalue;
+ } //end else if
+} //end of the function NumberValue
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PS_ReadNumber(script_t *script, token_t *token)
+{
+ int len = 0, i;
+ int octal, dot;
+ char c;
+// unsigned long int intvalue = 0;
+// long double floatvalue = 0;
+
+ token->type = TT_NUMBER;
+ //check for a hexadecimal number
+ if (*script->script_p == '0' &&
+ (*(script->script_p + 1) == 'x' ||
+ *(script->script_p + 1) == 'X'))
+ {
+ token->string[len++] = *script->script_p++;
+ token->string[len++] = *script->script_p++;
+ c = *script->script_p;
+ //hexadecimal
+ while((c >= '0' && c <= '9') ||
+ (c >= 'a' && c <= 'f') ||
+ (c >= 'A' && c <= 'A'))
+ {
+ token->string[len++] = *script->script_p++;
+ if (len >= MAX_TOKEN)
+ {
+ ScriptError(script, "hexadecimal number longer than MAX_TOKEN = %d", MAX_TOKEN);
+ return 0;
+ } //end if
+ c = *script->script_p;
+ } //end while
+ token->subtype |= TT_HEX;
+ } //end if
+#ifdef BINARYNUMBERS
+ //check for a binary number
+ else if (*script->script_p == '0' &&
+ (*(script->script_p + 1) == 'b' ||
+ *(script->script_p + 1) == 'B'))
+ {
+ token->string[len++] = *script->script_p++;
+ token->string[len++] = *script->script_p++;
+ c = *script->script_p;
+ //binary
+ while(c == '0' || c == '1')
+ {
+ token->string[len++] = *script->script_p++;
+ if (len >= MAX_TOKEN)
+ {
+ ScriptError(script, "binary number longer than MAX_TOKEN = %d", MAX_TOKEN);
+ return 0;
+ } //end if
+ c = *script->script_p;
+ } //end while
+ token->subtype |= TT_BINARY;
+ } //end if
+#endif //BINARYNUMBERS
+ else //decimal or octal integer or floating point number
+ {
+ octal = qfalse;
+ dot = qfalse;
+ if (*script->script_p == '0') octal = qtrue;
+ while(1)
+ {
+ c = *script->script_p;
+ if (c == '.') dot = qtrue;
+ else if (c == '8' || c == '9') octal = qfalse;
+ else if (c < '0' || c > '9') break;
+ token->string[len++] = *script->script_p++;
+ if (len >= MAX_TOKEN - 1)
+ {
+ ScriptError(script, "number longer than MAX_TOKEN = %d", MAX_TOKEN);
+ return 0;
+ } //end if
+ } //end while
+ if (octal) token->subtype |= TT_OCTAL;
+ else token->subtype |= TT_DECIMAL;
+ if (dot) token->subtype |= TT_FLOAT;
+ } //end else
+ for (i = 0; i < 2; i++)
+ {
+ c = *script->script_p;
+ //check for a LONG number
+ if ( (c == 'l' || c == 'L') // bk001204 - brackets
+ && !(token->subtype & TT_LONG))
+ {
+ script->script_p++;
+ token->subtype |= TT_LONG;
+ } //end if
+ //check for an UNSIGNED number
+ else if ( (c == 'u' || c == 'U') // bk001204 - brackets
+ && !(token->subtype & (TT_UNSIGNED | TT_FLOAT)))
+ {
+ script->script_p++;
+ token->subtype |= TT_UNSIGNED;
+ } //end if
+ } //end for
+ token->string[len] = '\0';
+#ifdef NUMBERVALUE
+ NumberValue(token->string, token->subtype, &token->intvalue, &token->floatvalue);
+#endif //NUMBERVALUE
+ if (!(token->subtype & TT_FLOAT)) token->subtype |= TT_INTEGER;
+ return 1;
+} //end of the function PS_ReadNumber
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PS_ReadLiteral(script_t *script, token_t *token)
+{
+ token->type = TT_LITERAL;
+ //first quote
+ token->string[0] = *script->script_p++;
+ //check for end of file
+ if (!*script->script_p)
+ {
+ ScriptError(script, "end of file before trailing \'");
+ return 0;
+ } //end if
+ //if it is an escape character
+ if (*script->script_p == '\\')
+ {
+ if (!PS_ReadEscapeCharacter(script, &token->string[1])) return 0;
+ } //end if
+ else
+ {
+ token->string[1] = *script->script_p++;
+ } //end else
+ //check for trailing quote
+ if (*script->script_p != '\'')
+ {
+ ScriptWarning(script, "too many characters in literal, ignored");
+ while(*script->script_p &&
+ *script->script_p != '\'' &&
+ *script->script_p != '\n')
+ {
+ script->script_p++;
+ } //end while
+ if (*script->script_p == '\'') script->script_p++;
+ } //end if
+ //store the trailing quote
+ token->string[2] = *script->script_p++;
+ //store trailing zero to end the string
+ token->string[3] = '\0';
+ //the sub type is the integer literal value
+ token->subtype = token->string[1];
+ //
+ return 1;
+} //end of the function PS_ReadLiteral
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PS_ReadPunctuation(script_t *script, token_t *token)
+{
+ int len;
+ char *p;
+ punctuation_t *punc;
+
+#ifdef PUNCTABLE
+ for (punc = script->punctuationtable[(unsigned int)*script->script_p]; punc; punc = punc->next)
+ {
+#else
+ int i;
+
+ for (i = 0; script->punctuations[i].p; i++)
+ {
+ punc = &script->punctuations[i];
+#endif //PUNCTABLE
+ p = punc->p;
+ len = strlen(p);
+ //if the script contains at least as much characters as the punctuation
+ if (script->script_p + len <= script->end_p)
+ {
+ //if the script contains the punctuation
+ if (!strncmp(script->script_p, p, len))
+ {
+ strncpy(token->string, p, MAX_TOKEN);
+ script->script_p += len;
+ token->type = TT_PUNCTUATION;
+ //sub type is the number of the punctuation
+ token->subtype = punc->n;
+ return 1;
+ } //end if
+ } //end if
+ } //end for
+ return 0;
+} //end of the function PS_ReadPunctuation
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PS_ReadPrimitive(script_t *script, token_t *token)
+{
+ int len;
+
+ len = 0;
+ while(*script->script_p > ' ' && *script->script_p != ';')
+ {
+ if (len >= MAX_TOKEN)
+ {
+ ScriptError(script, "primitive token longer than MAX_TOKEN = %d", MAX_TOKEN);
+ return 0;
+ } //end if
+ token->string[len++] = *script->script_p++;
+ } //end while
+ token->string[len] = 0;
+ //copy the token into the script structure
+ Com_Memcpy(&script->token, token, sizeof(token_t));
+ //primitive reading successfull
+ return 1;
+} //end of the function PS_ReadPrimitive
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PS_ReadToken(script_t *script, token_t *token)
+{
+ //if there is a token available (from UnreadToken)
+ if (script->tokenavailable)
+ {
+ script->tokenavailable = 0;
+ Com_Memcpy(token, &script->token, sizeof(token_t));
+ return 1;
+ } //end if
+ //save script pointer
+ script->lastscript_p = script->script_p;
+ //save line counter
+ script->lastline = script->line;
+ //clear the token stuff
+ Com_Memset(token, 0, sizeof(token_t));
+ //start of the white space
+ script->whitespace_p = script->script_p;
+ token->whitespace_p = script->script_p;
+ //read unusefull stuff
+ if (!PS_ReadWhiteSpace(script)) return 0;
+ //end of the white space
+ script->endwhitespace_p = script->script_p;
+ token->endwhitespace_p = script->script_p;
+ //line the token is on
+ token->line = script->line;
+ //number of lines crossed before token
+ token->linescrossed = script->line - script->lastline;
+ //if there is a leading double quote
+ if (*script->script_p == '\"')
+ {
+ if (!PS_ReadString(script, token, '\"')) return 0;
+ } //end if
+ //if an literal
+ else if (*script->script_p == '\'')
+ {
+ //if (!PS_ReadLiteral(script, token)) return 0;
+ if (!PS_ReadString(script, token, '\'')) return 0;
+ } //end if
+ //if there is a number
+ else if ((*script->script_p >= '0' && *script->script_p <= '9') ||
+ (*script->script_p == '.' &&
+ (*(script->script_p + 1) >= '0' && *(script->script_p + 1) <= '9')))
+ {
+ if (!PS_ReadNumber(script, token)) return 0;
+ } //end if
+ //if this is a primitive script
+ else if (script->flags & SCFL_PRIMITIVE)
+ {
+ return PS_ReadPrimitive(script, token);
+ } //end else if
+ //if there is a name
+ else if ((*script->script_p >= 'a' && *script->script_p <= 'z') ||
+ (*script->script_p >= 'A' && *script->script_p <= 'Z') ||
+ *script->script_p == '_')
+ {
+ if (!PS_ReadName(script, token)) return 0;
+ } //end if
+ //check for punctuations
+ else if (!PS_ReadPunctuation(script, token))
+ {
+ ScriptError(script, "can't read token");
+ return 0;
+ } //end if
+ //copy the token into the script structure
+ Com_Memcpy(&script->token, token, sizeof(token_t));
+ //succesfully read a token
+ return 1;
+} //end of the function PS_ReadToken
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PS_ExpectTokenString(script_t *script, char *string)
+{
+ token_t token;
+
+ if (!PS_ReadToken(script, &token))
+ {
+ ScriptError(script, "couldn't find expected %s", string);
+ return 0;
+ } //end if
+
+ if (strcmp(token.string, string))
+ {
+ ScriptError(script, "expected %s, found %s", string, token.string);
+ return 0;
+ } //end if
+ return 1;
+} //end of the function PS_ExpectToken
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PS_ExpectTokenType(script_t *script, int type, int subtype, token_t *token)
+{
+ char str[MAX_TOKEN];
+
+ if (!PS_ReadToken(script, token))
+ {
+ ScriptError(script, "couldn't read expected token");
+ return 0;
+ } //end if
+
+ if (token->type != type)
+ {
+ if (type == TT_STRING) strcpy(str, "string");
+ if (type == TT_LITERAL) strcpy(str, "literal");
+ if (type == TT_NUMBER) strcpy(str, "number");
+ if (type == TT_NAME) strcpy(str, "name");
+ if (type == TT_PUNCTUATION) strcpy(str, "punctuation");
+ ScriptError(script, "expected a %s, found %s", str, token->string);
+ return 0;
+ } //end if
+ if (token->type == TT_NUMBER)
+ {
+ if ((token->subtype & subtype) != subtype)
+ {
+ if (subtype & TT_DECIMAL) strcpy(str, "decimal");
+ if (subtype & TT_HEX) strcpy(str, "hex");
+ if (subtype & TT_OCTAL) strcpy(str, "octal");
+ if (subtype & TT_BINARY) strcpy(str, "binary");
+ if (subtype & TT_LONG) strcat(str, " long");
+ if (subtype & TT_UNSIGNED) strcat(str, " unsigned");
+ if (subtype & TT_FLOAT) strcat(str, " float");
+ if (subtype & TT_INTEGER) strcat(str, " integer");
+ ScriptError(script, "expected %s, found %s", str, token->string);
+ return 0;
+ } //end if
+ } //end if
+ else if (token->type == TT_PUNCTUATION)
+ {
+ if (subtype < 0)
+ {
+ ScriptError(script, "BUG: wrong punctuation subtype");
+ return 0;
+ } //end if
+ if (token->subtype != subtype)
+ {
+ ScriptError(script, "expected %s, found %s",
+ script->punctuations[subtype], token->string);
+ return 0;
+ } //end if
+ } //end else if
+ return 1;
+} //end of the function PS_ExpectTokenType
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PS_ExpectAnyToken(script_t *script, token_t *token)
+{
+ if (!PS_ReadToken(script, token))
+ {
+ ScriptError(script, "couldn't read expected token");
+ return 0;
+ } //end if
+ else
+ {
+ return 1;
+ } //end else
+} //end of the function PS_ExpectAnyToken
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PS_CheckTokenString(script_t *script, char *string)
+{
+ token_t tok;
+
+ if (!PS_ReadToken(script, &tok)) return 0;
+ //if the token is available
+ if (!strcmp(tok.string, string)) return 1;
+ //token not available
+ script->script_p = script->lastscript_p;
+ return 0;
+} //end of the function PS_CheckTokenString
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PS_CheckTokenType(script_t *script, int type, int subtype, token_t *token)
+{
+ token_t tok;
+
+ if (!PS_ReadToken(script, &tok)) return 0;
+ //if the type matches
+ if (tok.type == type &&
+ (tok.subtype & subtype) == subtype)
+ {
+ Com_Memcpy(token, &tok, sizeof(token_t));
+ return 1;
+ } //end if
+ //token is not available
+ script->script_p = script->lastscript_p;
+ return 0;
+} //end of the function PS_CheckTokenType
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int PS_SkipUntilString(script_t *script, char *string)
+{
+ token_t token;
+
+ while(PS_ReadToken(script, &token))
+ {
+ if (!strcmp(token.string, string)) return 1;
+ } //end while
+ return 0;
+} //end of the function PS_SkipUntilString
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void PS_UnreadLastToken(script_t *script)
+{
+ script->tokenavailable = 1;
+} //end of the function UnreadLastToken
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void PS_UnreadToken(script_t *script, token_t *token)
+{
+ Com_Memcpy(&script->token, token, sizeof(token_t));
+ script->tokenavailable = 1;
+} //end of the function UnreadToken
+//============================================================================
+// returns the next character of the read white space, returns NULL if none
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+char PS_NextWhiteSpaceChar(script_t *script)
+{
+ if (script->whitespace_p != script->endwhitespace_p)
+ {
+ return *script->whitespace_p++;
+ } //end if
+ else
+ {
+ return 0;
+ } //end else
+} //end of the function PS_NextWhiteSpaceChar
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void StripDoubleQuotes(char *string)
+{
+ if (*string == '\"')
+ {
+ strcpy(string, string+1);
+ } //end if
+ if (string[strlen(string)-1] == '\"')
+ {
+ string[strlen(string)-1] = '\0';
+ } //end if
+} //end of the function StripDoubleQuotes
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void StripSingleQuotes(char *string)
+{
+ if (*string == '\'')
+ {
+ strcpy(string, string+1);
+ } //end if
+ if (string[strlen(string)-1] == '\'')
+ {
+ string[strlen(string)-1] = '\0';
+ } //end if
+} //end of the function StripSingleQuotes
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+long double ReadSignedFloat(script_t *script)
+{
+ token_t token;
+ long double sign = 1;
+
+ PS_ExpectAnyToken(script, &token);
+ if (!strcmp(token.string, "-"))
+ {
+ sign = -1;
+ PS_ExpectTokenType(script, TT_NUMBER, 0, &token);
+ } //end if
+ else if (token.type != TT_NUMBER)
+ {
+ ScriptError(script, "expected float value, found %s\n", token.string);
+ } //end else if
+ return sign * token.floatvalue;
+} //end of the function ReadSignedFloat
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+signed long int ReadSignedInt(script_t *script)
+{
+ token_t token;
+ signed long int sign = 1;
+
+ PS_ExpectAnyToken(script, &token);
+ if (!strcmp(token.string, "-"))
+ {
+ sign = -1;
+ PS_ExpectTokenType(script, TT_NUMBER, TT_INTEGER, &token);
+ } //end if
+ else if (token.type != TT_NUMBER || token.subtype == TT_FLOAT)
+ {
+ ScriptError(script, "expected integer value, found %s\n", token.string);
+ } //end else if
+ return sign * token.intvalue;
+} //end of the function ReadSignedInt
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void SetScriptFlags(script_t *script, int flags)
+{
+ script->flags = flags;
+} //end of the function SetScriptFlags
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int GetScriptFlags(script_t *script)
+{
+ return script->flags;
+} //end of the function GetScriptFlags
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void ResetScript(script_t *script)
+{
+ //pointer in script buffer
+ script->script_p = script->buffer;
+ //pointer in script buffer before reading token
+ script->lastscript_p = script->buffer;
+ //begin of white space
+ script->whitespace_p = NULL;
+ //end of white space
+ script->endwhitespace_p = NULL;
+ //set if there's a token available in script->token
+ script->tokenavailable = 0;
+ //
+ script->line = 1;
+ script->lastline = 1;
+ //clear the saved token
+ Com_Memset(&script->token, 0, sizeof(token_t));
+} //end of the function ResetScript
+//============================================================================
+// returns true if at the end of the script
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int EndOfScript(script_t *script)
+{
+ return script->script_p >= script->end_p;
+} //end of the function EndOfScript
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int NumLinesCrossed(script_t *script)
+{
+ return script->line - script->lastline;
+} //end of the function NumLinesCrossed
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int ScriptSkipTo(script_t *script, char *value)
+{
+ int len;
+ char firstchar;
+
+ firstchar = *value;
+ len = strlen(value);
+ do
+ {
+ if (!PS_ReadWhiteSpace(script)) return 0;
+ if (*script->script_p == firstchar)
+ {
+ if (!strncmp(script->script_p, value, len))
+ {
+ return 1;
+ } //end if
+ } //end if
+ script->script_p++;
+ } while(1);
+} //end of the function ScriptSkipTo
+#ifndef BOTLIB
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+int FileLength(FILE *fp)
+{
+ int pos;
+ int end;
+
+ pos = ftell(fp);
+ fseek(fp, 0, SEEK_END);
+ end = ftell(fp);
+ fseek(fp, pos, SEEK_SET);
+
+ return end;
+} //end of the function FileLength
+#endif
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+script_t *LoadScriptFile(const char *filename)
+{
+#ifdef BOTLIB
+ fileHandle_t fp;
+ char pathname[MAX_QPATH];
+#else
+ FILE *fp;
+#endif
+ int length;
+ void *buffer;
+ script_t *script;
+
+#ifdef BOTLIB
+ if (strlen(basefolder))
+ Com_sprintf(pathname, sizeof(pathname), "%s/%s", basefolder, filename);
+ else
+ Com_sprintf(pathname, sizeof(pathname), "%s", filename);
+ length = botimport.FS_FOpenFile( pathname, &fp, FS_READ );
+ if (!fp) return NULL;
+#else
+ fp = fopen(filename, "rb");
+ if (!fp) return NULL;
+
+ length = FileLength(fp);
+#endif
+
+ buffer = GetClearedMemory(sizeof(script_t) + length + 1);
+ script = (script_t *) buffer;
+ Com_Memset(script, 0, sizeof(script_t));
+ strcpy(script->filename, filename);
+ script->buffer = (char *) buffer + sizeof(script_t);
+ script->buffer[length] = 0;
+ script->length = length;
+ //pointer in script buffer
+ script->script_p = script->buffer;
+ //pointer in script buffer before reading token
+ script->lastscript_p = script->buffer;
+ //pointer to end of script buffer
+ script->end_p = &script->buffer[length];
+ //set if there's a token available in script->token
+ script->tokenavailable = 0;
+ //
+ script->line = 1;
+ script->lastline = 1;
+ //
+ SetScriptPunctuations(script, NULL);
+ //
+#ifdef BOTLIB
+ botimport.FS_Read(script->buffer, length, fp);
+ botimport.FS_FCloseFile(fp);
+#else
+ if (fread(script->buffer, length, 1, fp) != 1)
+ {
+ FreeMemory(buffer);
+ script = NULL;
+ } //end if
+ fclose(fp);
+#endif
+ //
+ script->length = COM_Compress(script->buffer);
+
+ return script;
+} //end of the function LoadScriptFile
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+script_t *LoadScriptMemory(char *ptr, int length, char *name)
+{
+ void *buffer;
+ script_t *script;
+
+ buffer = GetClearedMemory(sizeof(script_t) + length + 1);
+ script = (script_t *) buffer;
+ Com_Memset(script, 0, sizeof(script_t));
+ strcpy(script->filename, name);
+ script->buffer = (char *) buffer + sizeof(script_t);
+ script->buffer[length] = 0;
+ script->length = length;
+ //pointer in script buffer
+ script->script_p = script->buffer;
+ //pointer in script buffer before reading token
+ script->lastscript_p = script->buffer;
+ //pointer to end of script buffer
+ script->end_p = &script->buffer[length];
+ //set if there's a token available in script->token
+ script->tokenavailable = 0;
+ //
+ script->line = 1;
+ script->lastline = 1;
+ //
+ SetScriptPunctuations(script, NULL);
+ //
+ Com_Memcpy(script->buffer, ptr, length);
+ //
+ return script;
+} //end of the function LoadScriptMemory
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void FreeScript(script_t *script)
+{
+#ifdef PUNCTABLE
+ if (script->punctuationtable) FreeMemory(script->punctuationtable);
+#endif //PUNCTABLE
+ FreeMemory(script);
+} //end of the function FreeScript
+//============================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//============================================================================
+void PS_SetBaseFolder(char *path)
+{
+#ifdef BSPC
+ sprintf(basefolder, path);
+#else
+ Com_sprintf(basefolder, sizeof(basefolder), path);
+#endif
+} //end of the function PS_SetBaseFolder
diff --git a/code/botlib/l_script.h b/code/botlib/l_script.h
new file mode 100755
index 0000000..2317907
--- /dev/null
+++ b/code/botlib/l_script.h
@@ -0,0 +1,247 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: l_script.h
+ *
+ * desc: lexicographical parser
+ *
+ * $Archive: /source/code/botlib/l_script.h $
+ *
+ *****************************************************************************/
+
+//undef if binary numbers of the form 0b... or 0B... are not allowed
+#define BINARYNUMBERS
+//undef if not using the token.intvalue and token.floatvalue
+#define NUMBERVALUE
+//use dollar sign also as punctuation
+#define DOLLAR
+
+//maximum token length
+#define MAX_TOKEN 1024
+
+#if defined(BSPC) && !defined(QDECL)
+#define QDECL
+#endif
+
+
+//script flags
+#define SCFL_NOERRORS 0x0001
+#define SCFL_NOWARNINGS 0x0002
+#define SCFL_NOSTRINGWHITESPACES 0x0004
+#define SCFL_NOSTRINGESCAPECHARS 0x0008
+#define SCFL_PRIMITIVE 0x0010
+#define SCFL_NOBINARYNUMBERS 0x0020
+#define SCFL_NONUMBERVALUES 0x0040
+
+//token types
+#define TT_STRING 1 // string
+#define TT_LITERAL 2 // literal
+#define TT_NUMBER 3 // number
+#define TT_NAME 4 // name
+#define TT_PUNCTUATION 5 // punctuation
+
+//string sub type
+//---------------
+// the length of the string
+//literal sub type
+//----------------
+// the ASCII code of the literal
+//number sub type
+//---------------
+#define TT_DECIMAL 0x0008 // decimal number
+#define TT_HEX 0x0100 // hexadecimal number
+#define TT_OCTAL 0x0200 // octal number
+#ifdef BINARYNUMBERS
+#define TT_BINARY 0x0400 // binary number
+#endif //BINARYNUMBERS
+#define TT_FLOAT 0x0800 // floating point number
+#define TT_INTEGER 0x1000 // integer number
+#define TT_LONG 0x2000 // long number
+#define TT_UNSIGNED 0x4000 // unsigned number
+//punctuation sub type
+//--------------------
+#define P_RSHIFT_ASSIGN 1
+#define P_LSHIFT_ASSIGN 2
+#define P_PARMS 3
+#define P_PRECOMPMERGE 4
+
+#define P_LOGIC_AND 5
+#define P_LOGIC_OR 6
+#define P_LOGIC_GEQ 7
+#define P_LOGIC_LEQ 8
+#define P_LOGIC_EQ 9
+#define P_LOGIC_UNEQ 10
+
+#define P_MUL_ASSIGN 11
+#define P_DIV_ASSIGN 12
+#define P_MOD_ASSIGN 13
+#define P_ADD_ASSIGN 14
+#define P_SUB_ASSIGN 15
+#define P_INC 16
+#define P_DEC 17
+
+#define P_BIN_AND_ASSIGN 18
+#define P_BIN_OR_ASSIGN 19
+#define P_BIN_XOR_ASSIGN 20
+#define P_RSHIFT 21
+#define P_LSHIFT 22
+
+#define P_POINTERREF 23
+#define P_CPP1 24
+#define P_CPP2 25
+#define P_MUL 26
+#define P_DIV 27
+#define P_MOD 28
+#define P_ADD 29
+#define P_SUB 30
+#define P_ASSIGN 31
+
+#define P_BIN_AND 32
+#define P_BIN_OR 33
+#define P_BIN_XOR 34
+#define P_BIN_NOT 35
+
+#define P_LOGIC_NOT 36
+#define P_LOGIC_GREATER 37
+#define P_LOGIC_LESS 38
+
+#define P_REF 39
+#define P_COMMA 40
+#define P_SEMICOLON 41
+#define P_COLON 42
+#define P_QUESTIONMARK 43
+
+#define P_PARENTHESESOPEN 44
+#define P_PARENTHESESCLOSE 45
+#define P_BRACEOPEN 46
+#define P_BRACECLOSE 47
+#define P_SQBRACKETOPEN 48
+#define P_SQBRACKETCLOSE 49
+#define P_BACKSLASH 50
+
+#define P_PRECOMP 51
+#define P_DOLLAR 52
+//name sub type
+//-------------
+// the length of the name
+
+//punctuation
+typedef struct punctuation_s
+{
+ char *p; //punctuation character(s)
+ int n; //punctuation indication
+ struct punctuation_s *next; //next punctuation
+} punctuation_t;
+
+//token
+typedef struct token_s
+{
+ char string[MAX_TOKEN]; //available token
+ int type; //last read token type
+ int subtype; //last read token sub type
+#ifdef NUMBERVALUE
+ unsigned long int intvalue; //integer value
+ long double floatvalue; //floating point value
+#endif //NUMBERVALUE
+ char *whitespace_p; //start of white space before token
+ char *endwhitespace_p; //start of white space before token
+ int line; //line the token was on
+ int linescrossed; //lines crossed in white space
+ struct token_s *next; //next token in chain
+} token_t;
+
+//script file
+typedef struct script_s
+{
+ char filename[1024]; //file name of the script
+ char *buffer; //buffer containing the script
+ char *script_p; //current pointer in the script
+ char *end_p; //pointer to the end of the script
+ char *lastscript_p; //script pointer before reading token
+ char *whitespace_p; //begin of the white space
+ char *endwhitespace_p; //end of the white space
+ int length; //length of the script in bytes
+ int line; //current line in script
+ int lastline; //line before reading token
+ int tokenavailable; //set by UnreadLastToken
+ int flags; //several script flags
+ punctuation_t *punctuations; //the punctuations used in the script
+ punctuation_t **punctuationtable;
+ token_t token; //available token
+ struct script_s *next; //next script in a chain
+} script_t;
+
+//read a token from the script
+int PS_ReadToken(script_t *script, token_t *token);
+//expect a certain token
+int PS_ExpectTokenString(script_t *script, char *string);
+//expect a certain token type
+int PS_ExpectTokenType(script_t *script, int type, int subtype, token_t *token);
+//expect a token
+int PS_ExpectAnyToken(script_t *script, token_t *token);
+//returns true when the token is available
+int PS_CheckTokenString(script_t *script, char *string);
+//returns true an reads the token when a token with the given type is available
+int PS_CheckTokenType(script_t *script, int type, int subtype, token_t *token);
+//skip tokens until the given token string is read
+int PS_SkipUntilString(script_t *script, char *string);
+//unread the last token read from the script
+void PS_UnreadLastToken(script_t *script);
+//unread the given token
+void PS_UnreadToken(script_t *script, token_t *token);
+//returns the next character of the read white space, returns NULL if none
+char PS_NextWhiteSpaceChar(script_t *script);
+//remove any leading and trailing double quotes from the token
+void StripDoubleQuotes(char *string);
+//remove any leading and trailing single quotes from the token
+void StripSingleQuotes(char *string);
+//read a possible signed integer
+signed long int ReadSignedInt(script_t *script);
+//read a possible signed floating point number
+long double ReadSignedFloat(script_t *script);
+//set an array with punctuations, NULL restores default C/C++ set
+void SetScriptPunctuations(script_t *script, punctuation_t *p);
+//set script flags
+void SetScriptFlags(script_t *script, int flags);
+//get script flags
+int GetScriptFlags(script_t *script);
+//reset a script
+void ResetScript(script_t *script);
+//returns true if at the end of the script
+int EndOfScript(script_t *script);
+//returns a pointer to the punctuation with the given number
+char *PunctuationFromNum(script_t *script, int num);
+//load a script from the given file at the given offset with the given length
+script_t *LoadScriptFile(const char *filename);
+//load a script from the given memory with the given length
+script_t *LoadScriptMemory(char *ptr, int length, char *name);
+//free a script
+void FreeScript(script_t *script);
+//set the base folder to load files from
+void PS_SetBaseFolder(char *path);
+//print a script error with filename and line number
+void QDECL ScriptError(script_t *script, char *str, ...);
+//print a script warning with filename and line number
+void QDECL ScriptWarning(script_t *script, char *str, ...);
+
+
diff --git a/code/botlib/l_struct.c b/code/botlib/l_struct.c
new file mode 100755
index 0000000..dea3b20
--- /dev/null
+++ b/code/botlib/l_struct.c
@@ -0,0 +1,462 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: l_struct.c
+ *
+ * desc: structure reading / writing
+ *
+ * $Archive: /MissionPack/CODE/botlib/l_struct.c $
+ *
+ *****************************************************************************/
+
+#ifdef BOTLIB
+#include "../game/q_shared.h"
+#include "../game/botlib.h" //for the include of be_interface.h
+#include "l_script.h"
+#include "l_precomp.h"
+#include "l_struct.h"
+#include "l_utils.h"
+#include "be_interface.h"
+#endif //BOTLIB
+
+#ifdef BSPC
+//include files for usage in the BSP Converter
+#include "../bspc/qbsp.h"
+#include "../bspc/l_log.h"
+#include "../bspc/l_mem.h"
+#include "l_precomp.h"
+#include "l_struct.h"
+
+#define qtrue true
+#define qfalse false
+#endif //BSPC
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+fielddef_t *FindField(fielddef_t *defs, char *name)
+{
+ int i;
+
+ for (i = 0; defs[i].name; i++)
+ {
+ if (!strcmp(defs[i].name, name)) return &defs[i];
+ } //end for
+ return NULL;
+} //end of the function FindField
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean ReadNumber(source_t *source, fielddef_t *fd, void *p)
+{
+ token_t token;
+ int negative = qfalse;
+ long int intval, intmin = 0, intmax = 0;
+ double floatval;
+
+ if (!PC_ExpectAnyToken(source, &token)) return 0;
+
+ //check for minus sign
+ if (token.type == TT_PUNCTUATION)
+ {
+ if (fd->type & FT_UNSIGNED)
+ {
+ SourceError(source, "expected unsigned value, found %s", token.string);
+ return 0;
+ } //end if
+ //if not a minus sign
+ if (strcmp(token.string, "-"))
+ {
+ SourceError(source, "unexpected punctuation %s", token.string);
+ return 0;
+ } //end if
+ negative = qtrue;
+ //read the number
+ if (!PC_ExpectAnyToken(source, &token)) return 0;
+ } //end if
+ //check if it is a number
+ if (token.type != TT_NUMBER)
+ {
+ SourceError(source, "expected number, found %s", token.string);
+ return 0;
+ } //end if
+ //check for a float value
+ if (token.subtype & TT_FLOAT)
+ {
+ if ((fd->type & FT_TYPE) != FT_FLOAT)
+ {
+ SourceError(source, "unexpected float");
+ return 0;
+ } //end if
+ floatval = token.floatvalue;
+ if (negative) floatval = -floatval;
+ if (fd->type & FT_BOUNDED)
+ {
+ if (floatval < fd->floatmin || floatval > fd->floatmax)
+ {
+ SourceError(source, "float out of range [%f, %f]", fd->floatmin, fd->floatmax);
+ return 0;
+ } //end if
+ } //end if
+ *(float *) p = (float) floatval;
+ return 1;
+ } //end if
+ //
+ intval = token.intvalue;
+ if (negative) intval = -intval;
+ //check bounds
+ if ((fd->type & FT_TYPE) == FT_CHAR)
+ {
+ if (fd->type & FT_UNSIGNED) {intmin = 0; intmax = 255;}
+ else {intmin = -128; intmax = 127;}
+ } //end if
+ if ((fd->type & FT_TYPE) == FT_INT)
+ {
+ if (fd->type & FT_UNSIGNED) {intmin = 0; intmax = 65535;}
+ else {intmin = -32768; intmax = 32767;}
+ } //end else if
+ if ((fd->type & FT_TYPE) == FT_CHAR || (fd->type & FT_TYPE) == FT_INT)
+ {
+ if (fd->type & FT_BOUNDED)
+ {
+ intmin = Maximum(intmin, fd->floatmin);
+ intmax = Minimum(intmax, fd->floatmax);
+ } //end if
+ if (intval < intmin || intval > intmax)
+ {
+ SourceError(source, "value %d out of range [%d, %d]", intval, intmin, intmax);
+ return 0;
+ } //end if
+ } //end if
+ else if ((fd->type & FT_TYPE) == FT_FLOAT)
+ {
+ if (fd->type & FT_BOUNDED)
+ {
+ if (intval < fd->floatmin || intval > fd->floatmax)
+ {
+ SourceError(source, "value %d out of range [%f, %f]", intval, fd->floatmin, fd->floatmax);
+ return 0;
+ } //end if
+ } //end if
+ } //end else if
+ //store the value
+ if ((fd->type & FT_TYPE) == FT_CHAR)
+ {
+ if (fd->type & FT_UNSIGNED) *(unsigned char *) p = (unsigned char) intval;
+ else *(char *) p = (char) intval;
+ } //end if
+ else if ((fd->type & FT_TYPE) == FT_INT)
+ {
+ if (fd->type & FT_UNSIGNED) *(unsigned int *) p = (unsigned int) intval;
+ else *(int *) p = (int) intval;
+ } //end else
+ else if ((fd->type & FT_TYPE) == FT_FLOAT)
+ {
+ *(float *) p = (float) intval;
+ } //end else
+ return 1;
+} //end of the function ReadNumber
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean ReadChar(source_t *source, fielddef_t *fd, void *p)
+{
+ token_t token;
+
+ if (!PC_ExpectAnyToken(source, &token)) return 0;
+
+ //take literals into account
+ if (token.type == TT_LITERAL)
+ {
+ StripSingleQuotes(token.string);
+ *(char *) p = token.string[0];
+ } //end if
+ else
+ {
+ PC_UnreadLastToken(source);
+ if (!ReadNumber(source, fd, p)) return 0;
+ } //end if
+ return 1;
+} //end of the function ReadChar
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int ReadString(source_t *source, fielddef_t *fd, void *p)
+{
+ token_t token;
+
+ if (!PC_ExpectTokenType(source, TT_STRING, 0, &token)) return 0;
+ //remove the double quotes
+ StripDoubleQuotes(token.string);
+ //copy the string
+ strncpy((char *) p, token.string, MAX_STRINGFIELD);
+ //make sure the string is closed with a zero
+ ((char *)p)[MAX_STRINGFIELD-1] = '\0';
+ //
+ return 1;
+} //end of the function ReadString
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int ReadStructure(source_t *source, structdef_t *def, char *structure)
+{
+ token_t token;
+ fielddef_t *fd;
+ void *p;
+ int num;
+
+ if (!PC_ExpectTokenString(source, "{")) return 0;
+ while(1)
+ {
+ if (!PC_ExpectAnyToken(source, &token)) return qfalse;
+ //if end of structure
+ if (!strcmp(token.string, "}")) break;
+ //find the field with the name
+ fd = FindField(def->fields, token.string);
+ if (!fd)
+ {
+ SourceError(source, "unknown structure field %s", token.string);
+ return qfalse;
+ } //end if
+ if (fd->type & FT_ARRAY)
+ {
+ num = fd->maxarray;
+ if (!PC_ExpectTokenString(source, "{")) return qfalse;
+ } //end if
+ else
+ {
+ num = 1;
+ } //end else
+ p = (void *)(structure + fd->offset);
+ while (num-- > 0)
+ {
+ if (fd->type & FT_ARRAY)
+ {
+ if (PC_CheckTokenString(source, "}")) break;
+ } //end if
+ switch(fd->type & FT_TYPE)
+ {
+ case FT_CHAR:
+ {
+ if (!ReadChar(source, fd, p)) return qfalse;
+ p = (char *) p + sizeof(char);
+ break;
+ } //end case
+ case FT_INT:
+ {
+ if (!ReadNumber(source, fd, p)) return qfalse;
+ p = (char *) p + sizeof(int);
+ break;
+ } //end case
+ case FT_FLOAT:
+ {
+ if (!ReadNumber(source, fd, p)) return qfalse;
+ p = (char *) p + sizeof(float);
+ break;
+ } //end case
+ case FT_STRING:
+ {
+ if (!ReadString(source, fd, p)) return qfalse;
+ p = (char *) p + MAX_STRINGFIELD;
+ break;
+ } //end case
+ case FT_STRUCT:
+ {
+ if (!fd->substruct)
+ {
+ SourceError(source, "BUG: no sub structure defined");
+ return qfalse;
+ } //end if
+ ReadStructure(source, fd->substruct, (char *) p);
+ p = (char *) p + fd->substruct->size;
+ break;
+ } //end case
+ } //end switch
+ if (fd->type & FT_ARRAY)
+ {
+ if (!PC_ExpectAnyToken(source, &token)) return qfalse;
+ if (!strcmp(token.string, "}")) break;
+ if (strcmp(token.string, ","))
+ {
+ SourceError(source, "expected a comma, found %s", token.string);
+ return qfalse;
+ } //end if
+ } //end if
+ } //end while
+ } //end while
+ return qtrue;
+} //end of the function ReadStructure
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int WriteIndent(FILE *fp, int indent)
+{
+ while(indent-- > 0)
+ {
+ if (fprintf(fp, "\t") < 0) return qfalse;
+ } //end while
+ return qtrue;
+} //end of the function WriteIndent
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int WriteFloat(FILE *fp, float value)
+{
+ char buf[128];
+ int l;
+
+ sprintf(buf, "%f", value);
+ l = strlen(buf);
+ //strip any trailing zeros
+ while(l-- > 1)
+ {
+ if (buf[l] != '0' && buf[l] != '.') break;
+ if (buf[l] == '.')
+ {
+ buf[l] = 0;
+ break;
+ } //end if
+ buf[l] = 0;
+ } //end while
+ //write the float to file
+ if (fprintf(fp, "%s", buf) < 0) return 0;
+ return 1;
+} //end of the function WriteFloat
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int WriteStructWithIndent(FILE *fp, structdef_t *def, char *structure, int indent)
+{
+ int i, num;
+ void *p;
+ fielddef_t *fd;
+
+ if (!WriteIndent(fp, indent)) return qfalse;
+ if (fprintf(fp, "{\r\n") < 0) return qfalse;
+
+ indent++;
+ for (i = 0; def->fields[i].name; i++)
+ {
+ fd = &def->fields[i];
+ if (!WriteIndent(fp, indent)) return qfalse;
+ if (fprintf(fp, "%s\t", fd->name) < 0) return qfalse;
+ p = (void *)(structure + fd->offset);
+ if (fd->type & FT_ARRAY)
+ {
+ num = fd->maxarray;
+ if (fprintf(fp, "{") < 0) return qfalse;
+ } //end if
+ else
+ {
+ num = 1;
+ } //end else
+ while(num-- > 0)
+ {
+ switch(fd->type & FT_TYPE)
+ {
+ case FT_CHAR:
+ {
+ if (fprintf(fp, "%d", *(char *) p) < 0) return qfalse;
+ p = (char *) p + sizeof(char);
+ break;
+ } //end case
+ case FT_INT:
+ {
+ if (fprintf(fp, "%d", *(int *) p) < 0) return qfalse;
+ p = (char *) p + sizeof(int);
+ break;
+ } //end case
+ case FT_FLOAT:
+ {
+ if (!WriteFloat(fp, *(float *)p)) return qfalse;
+ p = (char *) p + sizeof(float);
+ break;
+ } //end case
+ case FT_STRING:
+ {
+ if (fprintf(fp, "\"%s\"", (char *) p) < 0) return qfalse;
+ p = (char *) p + MAX_STRINGFIELD;
+ break;
+ } //end case
+ case FT_STRUCT:
+ {
+ if (!WriteStructWithIndent(fp, fd->substruct, structure, indent)) return qfalse;
+ p = (char *) p + fd->substruct->size;
+ break;
+ } //end case
+ } //end switch
+ if (fd->type & FT_ARRAY)
+ {
+ if (num > 0)
+ {
+ if (fprintf(fp, ",") < 0) return qfalse;
+ } //end if
+ else
+ {
+ if (fprintf(fp, "}") < 0) return qfalse;
+ } //end else
+ } //end if
+ } //end while
+ if (fprintf(fp, "\r\n") < 0) return qfalse;
+ } //end for
+ indent--;
+
+ if (!WriteIndent(fp, indent)) return qfalse;
+ if (fprintf(fp, "}\r\n") < 0) return qfalse;
+ return qtrue;
+} //end of the function WriteStructWithIndent
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int WriteStructure(FILE *fp, structdef_t *def, char *structure)
+{
+ return WriteStructWithIndent(fp, def, structure, 0);
+} //end of the function WriteStructure
+
diff --git a/code/botlib/l_struct.h b/code/botlib/l_struct.h
new file mode 100755
index 0000000..66ac035
--- /dev/null
+++ b/code/botlib/l_struct.h
@@ -0,0 +1,75 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: l_struct.h
+ *
+ * desc: structure reading/writing
+ *
+ * $Archive: /source/code/botlib/l_struct.h $
+ *
+ *****************************************************************************/
+
+
+#define MAX_STRINGFIELD 80
+//field types
+#define FT_CHAR 1 // char
+#define FT_INT 2 // int
+#define FT_FLOAT 3 // float
+#define FT_STRING 4 // char [MAX_STRINGFIELD]
+#define FT_STRUCT 6 // struct (sub structure)
+//type only mask
+#define FT_TYPE 0x00FF // only type, clear subtype
+//sub types
+#define FT_ARRAY 0x0100 // array of type
+#define FT_BOUNDED 0x0200 // bounded value
+#define FT_UNSIGNED 0x0400
+
+//structure field definition
+typedef struct fielddef_s
+{
+ char *name; //name of the field
+ int offset; //offset in the structure
+ int type; //type of the field
+ //type specific fields
+ int maxarray; //maximum array size
+ float floatmin, floatmax; //float min and max
+ struct structdef_s *substruct; //sub structure
+} fielddef_t;
+
+//structure definition
+typedef struct structdef_s
+{
+ int size;
+ fielddef_t *fields;
+} structdef_t;
+
+//read a structure from a script
+int ReadStructure(source_t *source, structdef_t *def, char *structure);
+//write a structure to a file
+int WriteStructure(FILE *fp, structdef_t *def, char *structure);
+//writes indents
+int WriteIndent(FILE *fp, int indent);
+//writes a float without traling zeros
+int WriteFloat(FILE *fp, float value);
+
+
diff --git a/code/botlib/l_utils.h b/code/botlib/l_utils.h
new file mode 100755
index 0000000..04bcc6a
--- /dev/null
+++ b/code/botlib/l_utils.h
@@ -0,0 +1,35 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: l_util.h
+ *
+ * desc: utils
+ *
+ * $Archive: /source/code/botlib/l_util.h $
+ *
+ *****************************************************************************/
+
+#define Vector2Angles(v,a) vectoangles(v,a)
+#define MAX_PATH MAX_QPATH
+#define Maximum(x,y) (x > y ? x : y)
+#define Minimum(x,y) (x < y ? x : y)
diff --git a/code/botlib/lcc.mak b/code/botlib/lcc.mak
new file mode 100755
index 0000000..6de559e
--- /dev/null
+++ b/code/botlib/lcc.mak
@@ -0,0 +1,55 @@
+#
+# Makefile for Gladiator Bot library: gladiator.dll
+# Intended for LCC-Win32
+#
+
+CC=lcc
+CFLAGS=-DC_ONLY -o
+OBJS= be_aas_bspq2.obj \
+ be_aas_bsphl.obj \
+ be_aas_cluster.obj \
+ be_aas_debug.obj \
+ be_aas_entity.obj \
+ be_aas_file.obj \
+ be_aas_light.obj \
+ be_aas_main.obj \
+ be_aas_move.obj \
+ be_aas_optimize.obj \
+ be_aas_reach.obj \
+ be_aas_route.obj \
+ be_aas_routealt.obj \
+ be_aas_sample.obj \
+ be_aas_sound.obj \
+ be_ai2_dm.obj \
+ be_ai2_dmnet.obj \
+ be_ai2_main.obj \
+ be_ai_char.obj \
+ be_ai_chat.obj \
+ be_ai_goal.obj \
+ be_ai_load.obj \
+ be_ai_move.obj \
+ be_ai_weap.obj \
+ be_ai_weight.obj \
+ be_ea.obj \
+ be_interface.obj \
+ l_crc.obj \
+ l_libvar.obj \
+ l_log.obj \
+ l_memory.obj \
+ l_precomp.obj \
+ l_script.obj \
+ l_struct.obj \
+ l_utils.obj \
+ q_shared.obj
+
+all: gladiator.dll
+
+gladiator.dll: $(OBJS)
+ lcclnk -dll -entry GetBotAPI *.obj botlib.def -o gladiator.dll
+
+clean:
+ del *.obj gladiator.dll
+
+%.obj: %.c
+ $(CC) $(CFLAGS) $<
+
diff --git a/code/botlib/linux-i386.mak b/code/botlib/linux-i386.mak
new file mode 100755
index 0000000..db6ee20
--- /dev/null
+++ b/code/botlib/linux-i386.mak
@@ -0,0 +1,92 @@
+#
+# Makefile for Gladiator Bot library: gladiator.so
+# Intended for gcc/Linux
+#
+
+ARCH=i386
+CC=gcc
+BASE_CFLAGS=-Dstricmp=strcasecmp
+
+#use these cflags to optimize it
+CFLAGS=$(BASE_CFLAGS) -m486 -O6 -ffast-math -funroll-loops \
+ -fomit-frame-pointer -fexpensive-optimizations -malign-loops=2 \
+ -malign-jumps=2 -malign-functions=2
+#use these when debugging
+#CFLAGS=$(BASE_CFLAGS) -g
+
+LDFLAGS=-ldl -lm
+SHLIBEXT=so
+SHLIBCFLAGS=-fPIC
+SHLIBLDFLAGS=-shared
+
+DO_CC=$(CC) $(CFLAGS) $(SHLIBCFLAGS) -o $@ -c $<
+
+#############################################################################
+# SETUP AND BUILD
+# GLADIATOR BOT
+#############################################################################
+
+.c.o:
+ $(DO_CC)
+
+GAME_OBJS = \
+ be_aas_bsphl.o\
+ be_aas_bspq2.o\
+ be_aas_cluster.o\
+ be_aas_debug.o\
+ be_aas_entity.o\
+ be_aas_file.o\
+ be_aas_light.o\
+ be_aas_main.o\
+ be_aas_move.o\
+ be_aas_optimize.o\
+ be_aas_reach.o\
+ be_aas_route.o\
+ be_aas_routealt.o\
+ be_aas_sample.o\
+ be_aas_sound.o\
+ be_ai2_dmq2.o\
+ be_ai2_dmhl.o\
+ be_ai2_dmnet.o\
+ be_ai2_main.o\
+ be_ai_char.o\
+ be_ai_chat.o\
+ be_ai_goal.o\
+ be_ai_load.o\
+ be_ai_move.o\
+ be_ai_weap.o\
+ be_ai_weight.o\
+ be_ea.o\
+ be_interface.o\
+ l_crc.o\
+ l_libvar.o\
+ l_log.o\
+ l_memory.o\
+ l_precomp.o\
+ l_script.o\
+ l_struct.o\
+ l_utils.o\
+ q_shared.o
+
+glad$(ARCH).$(SHLIBEXT) : $(GAME_OBJS)
+ $(CC) $(CFLAGS) $(SHLIBLDFLAGS) -o $@ $(GAME_OBJS)
+
+
+#############################################################################
+# MISC
+#############################################################################
+
+clean:
+ -rm -f $(GAME_OBJS)
+
+depend:
+ gcc -MM $(GAME_OBJS:.o=.c)
+
+
+install:
+ cp gladiator.so ..
+
+#
+# From "make depend"
+#
+
diff --git a/code/bspc/Conscript b/code/bspc/Conscript
new file mode 100755
index 0000000..08487ab
--- /dev/null
+++ b/code/bspc/Conscript
@@ -0,0 +1,75 @@
+# bspc compile
+
+Import qw( BSPC_BASE_CFLAGS BUILD_DIR INSTALL_DIR CC CXX LINK );
+
+@BSPC_FILES = qw(
+ aas_areamerging.c
+ aas_cfg.c
+ aas_create.c
+ aas_edgemelting.c
+ aas_facemerging.c
+ aas_file.c
+ aas_gsubdiv.c
+ aas_map.c
+ aas_prunenodes.c
+ aas_store.c
+ be_aas_bspc.c
+ ../botlib/be_aas_bspq3.c
+ ../botlib/be_aas_cluster.c
+ ../botlib/be_aas_move.c
+ ../botlib/be_aas_optimize.c
+ ../botlib/be_aas_reach.c
+ ../botlib/be_aas_sample.c
+ brushbsp.c
+ bspc.c
+ ../qcommon/cm_load.c
+ ../qcommon/cm_patch.c
+ ../qcommon/cm_test.c
+ ../qcommon/cm_trace.c
+ csg.c
+ glfile.c
+ l_bsp_ent.c
+ l_bsp_hl.c
+ l_bsp_q1.c
+ l_bsp_q2.c
+ l_bsp_q3.c
+ l_bsp_sin.c
+ l_cmd.c
+ ../botlib/l_libvar.c
+ l_log.c
+ l_math.c
+ l_mem.c
+ l_poly.c
+ ../botlib/l_precomp.c
+ l_qfiles.c
+ ../botlib/l_script.c
+ ../botlib/l_struct.c
+ l_threads.c
+ l_utils.c
+ leakfile.c
+ map.c
+ map_hl.c
+ map_q1.c
+ map_q2.c
+ map_q3.c
+ map_sin.c
+ ../qcommon/md4.c
+ nodraw.c
+ portals.c
+ textures.c
+ tree.c
+ ../qcommon/unzip.c
+ );
+$BSPC_REF = \@BSPC_FILES;
+
+$env = new cons(
+ CC => $CC,
+ CXX => $CXX,
+ LINK => $LINK,
+ CFLAGS => $BSPC_BASE_CFLAGS,
+ LIBS => '-ldl -lm -lpthread'
+);
+
+Program $env 'bspc', @$BSPC_REF;
+# this should install to Q3 or something?
+Install $env $INSTALL_DIR, 'bspc';
diff --git a/code/bspc/Makefile b/code/bspc/Makefile
new file mode 100755
index 0000000..2f16169
--- /dev/null
+++ b/code/bspc/Makefile
@@ -0,0 +1,114 @@
+#
+# Makefile for the BSPC tool for the Gladiator Bot
+# Intended for gcc/Linux
+#
+# TTimo 5/15/2001
+# some cleanup .. only used on i386 for GtkRadiant setups AFAIK .. removing the i386 tag
+# TODO: the intermediate object files should go into their own directory
+# specially for ../botlib and ../qcommon, the compilation flags on those might not be what you expect
+
+#ARCH=i386
+CC=gcc
+BASE_CFLAGS=-Dstricmp=strcasecmp
+
+#use these cflags to optimize it
+CFLAGS=$(BASE_CFLAGS) -m486 -O6 -ffast-math -funroll-loops \
+ -fomit-frame-pointer -fexpensive-optimizations -malign-loops=2 \
+ -malign-jumps=2 -malign-functions=2 -DLINUX -DBSPC
+#use these when debugging
+#CFLAGS=$(BASE_CFLAGS) -g
+
+LDFLAGS=-ldl -lm -lpthread
+
+DO_CC=$(CC) $(CFLAGS) -o $@ -c $<
+
+#############################################################################
+# SETUP AND BUILD BSPC
+#############################################################################
+
+.c.o:
+ $(DO_CC)
+
+GAME_OBJS = \
+ _files.o\
+ aas_areamerging.o\
+ aas_cfg.o\
+ aas_create.o\
+ aas_edgemelting.o\
+ aas_facemerging.o\
+ aas_file.o\
+ aas_gsubdiv.o\
+ aas_map.o\
+ aas_prunenodes.o\
+ aas_store.o\
+ be_aas_bspc.o\
+ ../botlib/be_aas_bspq3.o\
+ ../botlib/be_aas_cluster.o\
+ ../botlib/be_aas_move.o\
+ ../botlib/be_aas_optimize.o\
+ ../botlib/be_aas_reach.o\
+ ../botlib/be_aas_sample.o\
+ brushbsp.o\
+ bspc.o\
+ ../qcommon/cm_load.o\
+ ../qcommon/cm_patch.o\
+ ../qcommon/cm_test.o\
+ ../qcommon/cm_trace.o\
+ csg.o\
+ glfile.o\
+ l_bsp_ent.o\
+ l_bsp_hl.o\
+ l_bsp_q1.o\
+ l_bsp_q2.o\
+ l_bsp_q3.o\
+ l_bsp_sin.o\
+ l_cmd.o\
+ ../botlib/l_libvar.o\
+ l_log.o\
+ l_math.o\
+ l_mem.o\
+ l_poly.o\
+ ../botlib/l_precomp.o\
+ l_qfiles.o\
+ ../botlib/l_script.o\
+ ../botlib/l_struct.o\
+ l_threads.o\
+ l_utils.o\
+ leakfile.o\
+ map.o\
+ map_hl.o\
+ map_q1.o\
+ map_q2.o\
+ map_q3.o\
+ map_sin.o\
+ ../qcommon/md4.o\
+ nodraw.o\
+ portals.o\
+ textures.o\
+ tree.o\
+ ../qcommon/unzip.o
+
+ #tetrahedron.o
+
+bspc : $(GAME_OBJS)
+ $(CC) $(CFLAGS) -o $@ $(GAME_OBJS) $(LDFLAGS)
+ strip $@
+
+
+#############################################################################
+# MISC
+#############################################################################
+
+clean:
+ -rm -f $(GAME_OBJS)
+
+depend:
+ gcc -MM $(GAME_OBJS:.o=.c)
+
+#install:
+# cp bspci386 ..
+
+#
+# From "make depend"
+#
+
diff --git a/code/bspc/_files.c b/code/bspc/_files.c
new file mode 100755
index 0000000..8f4fcff
--- /dev/null
+++ b/code/bspc/_files.c
@@ -0,0 +1,63 @@
+//===========================================================================
+//
+// Name: _files.c
+// Function:
+// Programmer: Mr Elusive
+// Last update: 1999-12-02
+// Tab Size: 4
+//===========================================================================
+
+/*
+
+aas_areamerging.c //AAS area merging
+aas_cfg.c //AAS configuration for different games
+aas_create.c //AAS creating
+aas_edgemelting.c //AAS edge melting
+aas_facemerging.c //AAS face merging
+aas_file.c //AAS file writing
+aas_gsubdiv.c //AAS gravitational and ladder subdivision
+aas_map.c //AAS map brush creation
+aas_prunenodes.c //AAS node pruning
+aas_store.c //AAS file storing
+
+map.c //map file loading and writing
+map_hl.c //Half-Life map loading
+map_q1.c //Quake1 map loading
+map_q2.c //Quake2 map loading
+map_q3.c //Quake3 map loading
+map_sin.c //Sin map loading
+tree.c //BSP tree management + node pruning (*)
+brushbsp.c //brush bsp creation (*)
+portals.c //BSP portal creation and leaf filling (*)
+csg.c //Constructive Solid Geometry brush chopping (*)
+leakfile.c //leak file writing (*)
+textures.c //Quake2 BSP textures (*)
+
+l_bsp_ent.c //BSP entity parsing
+l_bsp_hl.c //Half-Life BSP loading and writing
+l_bsp_q1.c //Quake1 BSP loading and writing
+l_bsp_q2.c //Quake2 BSP loading and writing
+l_bsp_q3.c //Quake2 BSP loading and writing
+l_bsp_sin.c //Sin BSP loading and writing
+l_cmd.c //cmd library
+l_log.c //log file library
+l_math.c //math library
+l_mem.c //memory management library
+l_poly.c //polygon (winding) library
+l_script.c //script file parsing library
+l_threads.c //multi-threading library
+l_utils.c //utility library
+l_qfiles.c //loading of quake files
+
+gldraw.c //GL drawing (*)
+glfile.c //GL file writing (*)
+nodraw.c //no draw module (*)
+
+bspc.c //BSPC Win32 console version
+winbspc.c //WinBSPC Win32 GUI version
+win32_terminal.c //Win32 terminal output
+win32_qfiles.c //Win32 game file management (also .pak .sin)
+win32_font.c //Win32 fonts
+win32_folder.c //Win32 folder dialogs
+
+*/
diff --git a/code/bspc/aas_areamerging.c b/code/bspc/aas_areamerging.c
new file mode 100755
index 0000000..c5f82d2
--- /dev/null
+++ b/code/bspc/aas_areamerging.c
@@ -0,0 +1,390 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+#include "../botlib/aasfile.h"
+#include "aas_create.h"
+#include "aas_store.h"
+
+#define CONVEX_EPSILON 0.3
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+tmp_node_t *AAS_RefreshMergedTree_r(tmp_node_t *tmpnode)
+{
+ tmp_area_t *tmparea;
+
+ //if this is a solid leaf
+ if (!tmpnode) return NULL;
+ //if this is an area leaf
+ if (tmpnode->tmparea)
+ {
+ tmparea = tmpnode->tmparea;
+ while(tmparea->mergedarea) tmparea = tmparea->mergedarea;
+ tmpnode->tmparea = tmparea;
+ return tmpnode;
+ } //end if
+ //do the children recursively
+ tmpnode->children[0] = AAS_RefreshMergedTree_r(tmpnode->children[0]);
+ tmpnode->children[1] = AAS_RefreshMergedTree_r(tmpnode->children[1]);
+ return tmpnode;
+} //end of the function AAS_RefreshMergedTree_r
+//===========================================================================
+// returns true if the two given faces would create a non-convex area at
+// the given sides, otherwise false is returned
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int NonConvex(tmp_face_t *face1, tmp_face_t *face2, int side1, int side2)
+{
+ int i;
+ winding_t *w1, *w2;
+ plane_t *plane1, *plane2;
+
+ w1 = face1->winding;
+ w2 = face2->winding;
+
+ plane1 = &mapplanes[face1->planenum ^ side1];
+ plane2 = &mapplanes[face2->planenum ^ side2];
+
+ //check if one of the points of face1 is at the back of the plane of face2
+ for (i = 0; i < w1->numpoints; i++)
+ {
+ if (DotProduct(plane2->normal, w1->p[i]) - plane2->dist < -CONVEX_EPSILON) return true;
+ } //end for
+ //check if one of the points of face2 is at the back of the plane of face1
+ for (i = 0; i < w2->numpoints; i++)
+ {
+ if (DotProduct(plane1->normal, w2->p[i]) - plane1->dist < -CONVEX_EPSILON) return true;
+ } //end for
+
+ return false;
+} //end of the function NonConvex
+//===========================================================================
+// try to merge the areas at both sides of the given face
+//
+// Parameter: seperatingface : face that seperates two areas
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_TryMergeFaceAreas(tmp_face_t *seperatingface)
+{
+ int side1, side2, area1faceflags, area2faceflags;
+ tmp_area_t *tmparea1, *tmparea2, *newarea;
+ tmp_face_t *face1, *face2, *nextface1, *nextface2;
+
+ tmparea1 = seperatingface->frontarea;
+ tmparea2 = seperatingface->backarea;
+
+ //areas must have the same presence type
+ if (tmparea1->presencetype != tmparea2->presencetype) return false;
+ //areas must have the same area contents
+ if (tmparea1->contents != tmparea2->contents) return false;
+ //areas must have the same bsp model inside (or both none)
+ if (tmparea1->modelnum != tmparea2->modelnum) return false;
+
+ area1faceflags = 0;
+ area2faceflags = 0;
+ for (face1 = tmparea1->tmpfaces; face1; face1 = face1->next[side1])
+ {
+ side1 = (face1->frontarea != tmparea1);
+ //debug: check if the area belongs to the area
+ if (face1->frontarea != tmparea1 &&
+ face1->backarea != tmparea1) Error("face does not belong to area1");
+ //just continue if the face is seperating the two areas
+ //NOTE: a result of this is that ground and gap areas can
+ // be merged if the seperating face is the gap
+ if ((face1->frontarea == tmparea1 &&
+ face1->backarea == tmparea2) ||
+ (face1->frontarea == tmparea2 &&
+ face1->backarea == tmparea1)) continue;
+ //get area1 face flags
+ area1faceflags |= face1->faceflags;
+ if (AAS_GapFace(face1, side1)) area1faceflags |= FACE_GAP;
+ //
+ for (face2 = tmparea2->tmpfaces; face2; face2 = face2->next[side2])
+ {
+ side2 = (face2->frontarea != tmparea2);
+ //debug: check if the area belongs to the area
+ if (face2->frontarea != tmparea2 &&
+ face2->backarea != tmparea2) Error("face does not belong to area2");
+ //just continue if the face is seperating the two areas
+ //NOTE: a result of this is that ground and gap areas can
+ // be merged if the seperating face is the gap
+ if ((face2->frontarea == tmparea1 &&
+ face2->backarea == tmparea2) ||
+ (face2->frontarea == tmparea2 &&
+ face2->backarea == tmparea1)) continue;
+ //get area2 face flags
+ area2faceflags |= face2->faceflags;
+ if (AAS_GapFace(face2, side2)) area2faceflags |= FACE_GAP;
+ //if the two faces would create a non-convex area
+ if (NonConvex(face1, face2, side1, side2)) return false;
+ } //end for
+ } //end for
+ //if one area has gap faces (that aren't seperating the two areas)
+ //and the other has ground faces (that aren't seperating the two areas),
+ //the areas can't be merged
+ if (((area1faceflags & FACE_GROUND) && (area2faceflags & FACE_GAP)) ||
+ ((area2faceflags & FACE_GROUND) && (area1faceflags & FACE_GAP)))
+ {
+// Log_Print(" can't merge: ground/gap\n");
+ return false;
+ } //end if
+
+// Log_Print("merged area %d & %d to %d with %d faces\n", tmparea1->areanum, tmparea2->areanum, newarea->areanum, numfaces);
+// return false;
+ //
+ //AAS_CheckArea(tmparea1);
+ //AAS_CheckArea(tmparea2);
+ //create the new area
+ newarea = AAS_AllocTmpArea();
+ newarea->presencetype = tmparea1->presencetype;
+ newarea->contents = tmparea1->contents;
+ newarea->modelnum = tmparea1->modelnum;
+ newarea->tmpfaces = NULL;
+
+ //add all the faces (except the seperating ones) from the first area
+ //to the new area
+ for (face1 = tmparea1->tmpfaces; face1; face1 = nextface1)
+ {
+ side1 = (face1->frontarea != tmparea1);
+ nextface1 = face1->next[side1];
+ //don't add seperating faces
+ if ((face1->frontarea == tmparea1 &&
+ face1->backarea == tmparea2) ||
+ (face1->frontarea == tmparea2 &&
+ face1->backarea == tmparea1))
+ {
+ continue;
+ } //end if
+ //
+ AAS_RemoveFaceFromArea(face1, tmparea1);
+ AAS_AddFaceSideToArea(face1, side1, newarea);
+ } //end for
+ //add all the faces (except the seperating ones) from the second area
+ //to the new area
+ for (face2 = tmparea2->tmpfaces; face2; face2 = nextface2)
+ {
+ side2 = (face2->frontarea != tmparea2);
+ nextface2 = face2->next[side2];
+ //don't add seperating faces
+ if ((face2->frontarea == tmparea1 &&
+ face2->backarea == tmparea2) ||
+ (face2->frontarea == tmparea2 &&
+ face2->backarea == tmparea1))
+ {
+ continue;
+ } //end if
+ //
+ AAS_RemoveFaceFromArea(face2, tmparea2);
+ AAS_AddFaceSideToArea(face2, side2, newarea);
+ } //end for
+ //free all shared faces
+ for (face1 = tmparea1->tmpfaces; face1; face1 = nextface1)
+ {
+ side1 = (face1->frontarea != tmparea1);
+ nextface1 = face1->next[side1];
+ //
+ AAS_RemoveFaceFromArea(face1, face1->frontarea);
+ AAS_RemoveFaceFromArea(face1, face1->backarea);
+ AAS_FreeTmpFace(face1);
+ } //end for
+ //
+ tmparea1->mergedarea = newarea;
+ tmparea1->invalid = true;
+ tmparea2->mergedarea = newarea;
+ tmparea2->invalid = true;
+ //
+ AAS_CheckArea(newarea);
+ AAS_FlipAreaFaces(newarea);
+// Log_Print("merged area %d & %d to %d with %d faces\n", tmparea1->areanum, tmparea2->areanum, newarea->areanum);
+ return true;
+} //end of the function AAS_TryMergeFaceAreas
+//===========================================================================
+// try to merge areas
+// merged areas are added to the end of the convex area list so merging
+// will be tried for those areas as well
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: tmpaasworld
+//===========================================================================
+/*
+void AAS_MergeAreas(void)
+{
+ int side, nummerges;
+ tmp_area_t *tmparea, *othertmparea;
+ tmp_face_t *face;
+
+ nummerges = 0;
+ Log_Write("AAS_MergeAreas\r\n");
+ qprintf("%6d areas merged", 1);
+ //first merge grounded areas only
+ //NOTE: this is useless because the area settings aren't available yet
+ for (tmparea = tmpaasworld.areas; tmparea; tmparea = tmparea->l_next)
+ {
+// Log_Print("checking area %d\n", i);
+ //if the area is invalid
+ if (tmparea->invalid)
+ {
+// Log_Print(" area invalid\n");
+ continue;
+ } //end if
+ //
+// if (!(tmparea->settings->areaflags & AREA_GROUNDED)) continue;
+ //
+ for (face = tmparea->tmpfaces; face; face = face->next[side])
+ {
+ side = (face->frontarea != tmparea);
+ //if the face has both a front and back area
+ if (face->frontarea && face->backarea)
+ {
+ //
+ if (face->frontarea == tmparea) othertmparea = face->backarea;
+ else othertmparea = face->frontarea;
+// if (!(othertmparea->settings->areaflags & AREA_GROUNDED)) continue;
+// Log_Print(" checking area %d with %d\n", face->frontarea, face->backarea);
+ if (AAS_TryMergeFaceAreas(face))
+ {
+ qprintf("\r%6d", ++nummerges);
+ break;
+ } //end if
+ } //end if
+ } //end for
+ } //end for
+ //merge all areas
+ for (tmparea = tmpaasworld.areas; tmparea; tmparea = tmparea->l_next)
+ {
+// Log_Print("checking area %d\n", i);
+ //if the area is invalid
+ if (tmparea->invalid)
+ {
+// Log_Print(" area invalid\n");
+ continue;
+ } //end if
+ //
+ for (face = tmparea->tmpfaces; face; face = face->next[side])
+ {
+ side = (face->frontarea != tmparea);
+ //if the face has both a front and back area
+ if (face->frontarea && face->backarea)
+ {
+// Log_Print(" checking area %d with %d\n", face->frontarea, face->backarea);
+ if (AAS_TryMergeFaceAreas(face))
+ {
+ qprintf("\r%6d", ++nummerges);
+ break;
+ } //end if
+ } //end if
+ } //end for
+ } //end for
+ Log_Print("\r%6d areas merged\n", nummerges);
+ //refresh the merged tree
+ AAS_RefreshMergedTree_r(tmpaasworld.nodes);
+} //end of the function AAS_MergeAreas*/
+
+int AAS_GroundArea(tmp_area_t *tmparea)
+{
+ tmp_face_t *face;
+ int side;
+
+ for (face = tmparea->tmpfaces; face; face = face->next[side])
+ {
+ side = (face->frontarea != tmparea);
+ if (face->faceflags & FACE_GROUND) return true;
+ } //end for
+ return false;
+} //end of the function AAS_GroundArea
+
+void AAS_MergeAreas(void)
+{
+ int side, nummerges, merges, groundfirst;
+ tmp_area_t *tmparea, *othertmparea;
+ tmp_face_t *face;
+
+ nummerges = 0;
+ Log_Write("AAS_MergeAreas\r\n");
+ qprintf("%6d areas merged", 1);
+ //
+ groundfirst = true;
+ //for (i = 0; i < 4 || merges; i++)
+ while(1)
+ {
+ //if (i < 2) groundfirst = true;
+ //else groundfirst = false;
+ //
+ merges = 0;
+ //first merge grounded areas only
+ for (tmparea = tmpaasworld.areas; tmparea; tmparea = tmparea->l_next)
+ {
+ //if the area is invalid
+ if (tmparea->invalid)
+ {
+ continue;
+ } //end if
+ //
+ if (groundfirst)
+ {
+ if (!AAS_GroundArea(tmparea)) continue;
+ } //end if
+ //
+ for (face = tmparea->tmpfaces; face; face = face->next[side])
+ {
+ side = (face->frontarea != tmparea);
+ //if the face has both a front and back area
+ if (face->frontarea && face->backarea)
+ {
+ //
+ if (face->frontarea == tmparea) othertmparea = face->backarea;
+ else othertmparea = face->frontarea;
+ //
+ if (groundfirst)
+ {
+ if (!AAS_GroundArea(othertmparea)) continue;
+ } //end if
+ if (AAS_TryMergeFaceAreas(face))
+ {
+ qprintf("\r%6d", ++nummerges);
+ merges++;
+ break;
+ } //end if
+ } //end if
+ } //end for
+ } //end for
+ if (!merges)
+ {
+ if (groundfirst) groundfirst = false;
+ else break;
+ } //end if
+ } //end for
+ qprintf("\n");
+ Log_Write("%6d areas merged\r\n", nummerges);
+ //refresh the merged tree
+ AAS_RefreshMergedTree_r(tmpaasworld.nodes);
+} //end of the function AAS_MergeAreas
diff --git a/code/bspc/aas_areamerging.h b/code/bspc/aas_areamerging.h
new file mode 100755
index 0000000..c0b39a4
--- /dev/null
+++ b/code/bspc/aas_areamerging.h
@@ -0,0 +1,24 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+void AAS_MergeAreas(void);
+
diff --git a/code/bspc/aas_cfg.c b/code/bspc/aas_cfg.c
new file mode 100755
index 0000000..3aeb569
--- /dev/null
+++ b/code/bspc/aas_cfg.c
@@ -0,0 +1,252 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+#include "float.h"
+#include "../botlib/aasfile.h"
+#include "aas_store.h"
+#include "aas_cfg.h"
+#include "../botlib/l_precomp.h"
+#include "../botlib/l_struct.h"
+#include "../botlib/l_libvar.h"
+
+//structure field offsets
+#define BBOX_OFS(x) (int)&(((aas_bbox_t *)0)->x)
+#define CFG_OFS(x) (int)&(((cfg_t *)0)->x)
+
+//bounding box definition
+fielddef_t bbox_fields[] =
+{
+ {"presencetype", BBOX_OFS(presencetype), FT_INT},
+ {"flags", BBOX_OFS(flags), FT_INT},
+ {"mins", BBOX_OFS(mins), FT_FLOAT|FT_ARRAY, 3},
+ {"maxs", BBOX_OFS(maxs), FT_FLOAT|FT_ARRAY, 3},
+ {NULL, 0, 0, 0}
+};
+
+fielddef_t cfg_fields[] =
+{
+ {"phys_gravitydirection", CFG_OFS(phys_gravitydirection), FT_FLOAT|FT_ARRAY, 3},
+ {"phys_friction", CFG_OFS(phys_friction), FT_FLOAT},
+ {"phys_stopspeed", CFG_OFS(phys_stopspeed), FT_FLOAT},
+ {"phys_gravity", CFG_OFS(phys_gravity), FT_FLOAT},
+ {"phys_waterfriction", CFG_OFS(phys_waterfriction), FT_FLOAT},
+ {"phys_watergravity", CFG_OFS(phys_watergravity), FT_FLOAT},
+ {"phys_maxvelocity", CFG_OFS(phys_maxvelocity), FT_FLOAT},
+ {"phys_maxwalkvelocity", CFG_OFS(phys_maxwalkvelocity), FT_FLOAT},
+ {"phys_maxcrouchvelocity", CFG_OFS(phys_maxcrouchvelocity), FT_FLOAT},
+ {"phys_maxswimvelocity", CFG_OFS(phys_maxswimvelocity), FT_FLOAT},
+ {"phys_walkaccelerate", CFG_OFS(phys_walkaccelerate), FT_FLOAT},
+ {"phys_airaccelerate", CFG_OFS(phys_airaccelerate), FT_FLOAT},
+ {"phys_swimaccelerate", CFG_OFS(phys_swimaccelerate), FT_FLOAT},
+ {"phys_maxstep", CFG_OFS(phys_maxstep), FT_FLOAT},
+ {"phys_maxsteepness", CFG_OFS(phys_maxsteepness), FT_FLOAT},
+ {"phys_maxwaterjump", CFG_OFS(phys_maxwaterjump), FT_FLOAT},
+ {"phys_maxbarrier", CFG_OFS(phys_maxbarrier), FT_FLOAT},
+ {"phys_jumpvel", CFG_OFS(phys_jumpvel), FT_FLOAT},
+ {"phys_falldelta5", CFG_OFS(phys_falldelta5), FT_FLOAT},
+ {"phys_falldelta10", CFG_OFS(phys_falldelta10), FT_FLOAT},
+ {"rs_waterjump", CFG_OFS(rs_waterjump), FT_FLOAT},
+ {"rs_teleport", CFG_OFS(rs_teleport), FT_FLOAT},
+ {"rs_barrierjump", CFG_OFS(rs_barrierjump), FT_FLOAT},
+ {"rs_startcrouch", CFG_OFS(rs_startcrouch), FT_FLOAT},
+ {"rs_startgrapple", CFG_OFS(rs_startgrapple), FT_FLOAT},
+ {"rs_startwalkoffledge", CFG_OFS(rs_startwalkoffledge), FT_FLOAT},
+ {"rs_startjump", CFG_OFS(rs_startjump), FT_FLOAT},
+ {"rs_rocketjump", CFG_OFS(rs_rocketjump), FT_FLOAT},
+ {"rs_bfgjump", CFG_OFS(rs_bfgjump), FT_FLOAT},
+ {"rs_jumppad", CFG_OFS(rs_jumppad), FT_FLOAT},
+ {"rs_aircontrolledjumppad", CFG_OFS(rs_aircontrolledjumppad), FT_FLOAT},
+ {"rs_funcbob", CFG_OFS(rs_funcbob), FT_FLOAT},
+ {"rs_startelevator", CFG_OFS(rs_startelevator), FT_FLOAT},
+ {"rs_falldamage5", CFG_OFS(rs_falldamage5), FT_FLOAT},
+ {"rs_falldamage10", CFG_OFS(rs_falldamage10), FT_FLOAT},
+ {"rs_maxjumpfallheight", CFG_OFS(rs_maxjumpfallheight), FT_FLOAT},
+ {NULL, 0, 0, 0}
+};
+
+structdef_t bbox_struct =
+{
+ sizeof(aas_bbox_t), bbox_fields
+};
+structdef_t cfg_struct =
+{
+ sizeof(cfg_t), cfg_fields
+};
+
+//global cfg
+cfg_t cfg;
+
+//===========================================================================
+// the default Q3A configuration
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void DefaultCfg(void)
+{
+ int i;
+
+ // default all float values to infinite
+ for (i = 0; cfg_fields[i].name; i++)
+ {
+ if ((cfg_fields[i].type & FT_TYPE) == FT_FLOAT)
+ *(float *)( ((char*)&cfg) + cfg_fields[i].offset ) = FLT_MAX;
+ } //end for
+ //
+ cfg.numbboxes = 2;
+ //bbox 0
+ cfg.bboxes[0].presencetype = PRESENCE_NORMAL;
+ cfg.bboxes[0].flags = 0;
+ cfg.bboxes[0].mins[0] = -15;
+ cfg.bboxes[0].mins[1] = -15;
+ cfg.bboxes[0].mins[2] = -24;
+ cfg.bboxes[0].maxs[0] = 15;
+ cfg.bboxes[0].maxs[1] = 15;
+ cfg.bboxes[0].maxs[2] = 32;
+ //bbox 1
+ cfg.bboxes[1].presencetype = PRESENCE_CROUCH;
+ cfg.bboxes[1].flags = 1;
+ cfg.bboxes[1].mins[0] = -15;
+ cfg.bboxes[1].mins[1] = -15;
+ cfg.bboxes[1].mins[2] = -24;
+ cfg.bboxes[1].maxs[0] = 15;
+ cfg.bboxes[1].maxs[1] = 15;
+ cfg.bboxes[1].maxs[2] = 16;
+ //
+ cfg.allpresencetypes = PRESENCE_NORMAL|PRESENCE_CROUCH;
+ cfg.phys_gravitydirection[0] = 0;
+ cfg.phys_gravitydirection[1] = 0;
+ cfg.phys_gravitydirection[2] = -1;
+ cfg.phys_maxsteepness = 0.7;
+} //end of the function DefaultCfg
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+char * QDECL va( char *format, ... )
+{
+ va_list argptr;
+ static char string[2][32000]; // in case va is called by nested functions
+ static int index = 0;
+ char *buf;
+
+ buf = string[index & 1];
+ index++;
+
+ va_start (argptr, format);
+ vsprintf (buf, format,argptr);
+ va_end (argptr);
+
+ return buf;
+} //end of the function va
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void SetCfgLibVars(void)
+{
+ int i;
+ float value;
+
+ for (i = 0; cfg_fields[i].name; i++)
+ {
+ if ((cfg_fields[i].type & FT_TYPE) == FT_FLOAT)
+ {
+ value = *(float *)(((char*)&cfg) + cfg_fields[i].offset);
+ if (value != FLT_MAX)
+ {
+ LibVarSet(cfg_fields[i].name, va("%f", value));
+ } //end if
+ } //end if
+ } //end for
+} //end of the function SetCfgLibVars
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int LoadCfgFile(char *filename)
+{
+ source_t *source;
+ token_t token;
+ int settingsdefined;
+
+ source = LoadSourceFile(filename);
+ if (!source)
+ {
+ Log_Print("couldn't open cfg file %s\n", filename);
+ return false;
+ } //end if
+
+ settingsdefined = false;
+ memset(&cfg, 0, sizeof(cfg_t));
+
+ while(PC_ReadToken(source, &token))
+ {
+ if (!stricmp(token.string, "bbox"))
+ {
+ if (cfg.numbboxes >= AAS_MAX_BBOXES)
+ {
+ SourceError(source, "too many bounding box volumes defined");
+ } //end if
+ if (!ReadStructure(source, &bbox_struct, (char *) &cfg.bboxes[cfg.numbboxes]))
+ {
+ FreeSource(source);
+ return false;
+ } //end if
+ cfg.allpresencetypes |= cfg.bboxes[cfg.numbboxes].presencetype;
+ cfg.numbboxes++;
+ } //end if
+ else if (!stricmp(token.string, "settings"))
+ {
+ if (settingsdefined)
+ {
+ SourceWarning(source, "settings already defined\n");
+ } //end if
+ settingsdefined = true;
+ if (!ReadStructure(source, &cfg_struct, (char *) &cfg))
+ {
+ FreeSource(source);
+ return false;
+ } //end if
+ } //end else if
+ } //end while
+ if (VectorLength(cfg.phys_gravitydirection) < 0.9 || VectorLength(cfg.phys_gravitydirection) > 1.1)
+ {
+ SourceError(source, "invalid gravity direction specified");
+ } //end if
+ if (cfg.numbboxes <= 0)
+ {
+ SourceError(source, "no bounding volumes specified");
+ } //end if
+ FreeSource(source);
+ SetCfgLibVars();
+ Log_Print("using cfg file %s\n", filename);
+ return true;
+} //end of the function LoadCfgFile
diff --git a/code/bspc/aas_cfg.h b/code/bspc/aas_cfg.h
new file mode 100755
index 0000000..25537c6
--- /dev/null
+++ b/code/bspc/aas_cfg.h
@@ -0,0 +1,73 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#define BBOXFL_GROUNDED 1 //bounding box only valid when on ground
+#define BBOXFL_NOTGROUNDED 2 //bounding box only valid when NOT on ground
+
+typedef struct cfg_s
+{
+ int numbboxes; //number of bounding boxes
+ aas_bbox_t bboxes[AAS_MAX_BBOXES]; //all the bounding boxes
+ int allpresencetypes; //or of all presence types
+ // aas settings
+ vec3_t phys_gravitydirection;
+ float phys_friction;
+ float phys_stopspeed;
+ float phys_gravity;
+ float phys_waterfriction;
+ float phys_watergravity;
+ float phys_maxvelocity;
+ float phys_maxwalkvelocity;
+ float phys_maxcrouchvelocity;
+ float phys_maxswimvelocity;
+ float phys_walkaccelerate;
+ float phys_airaccelerate;
+ float phys_swimaccelerate;
+ float phys_maxstep;
+ float phys_maxsteepness;
+ float phys_maxwaterjump;
+ float phys_maxbarrier;
+ float phys_jumpvel;
+ float phys_falldelta5;
+ float phys_falldelta10;
+ float rs_waterjump;
+ float rs_teleport;
+ float rs_barrierjump;
+ float rs_startcrouch;
+ float rs_startgrapple;
+ float rs_startwalkoffledge;
+ float rs_startjump;
+ float rs_rocketjump;
+ float rs_bfgjump;
+ float rs_jumppad;
+ float rs_aircontrolledjumppad;
+ float rs_funcbob;
+ float rs_startelevator;
+ float rs_falldamage5;
+ float rs_falldamage10;
+ float rs_maxjumpfallheight;
+} cfg_t;
+
+extern cfg_t cfg;
+
+void DefaultCfg(void);
+int LoadCfgFile(char *filename);
diff --git a/code/bspc/aas_create.c b/code/bspc/aas_create.c
new file mode 100755
index 0000000..914b25b
--- /dev/null
+++ b/code/bspc/aas_create.c
@@ -0,0 +1,1142 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+#include "../botlib/aasfile.h"
+#include "aas_create.h"
+#include "aas_store.h"
+#include "aas_gsubdiv.h"
+#include "aas_facemerging.h"
+#include "aas_areamerging.h"
+#include "aas_edgemelting.h"
+#include "aas_prunenodes.h"
+#include "aas_cfg.h"
+#include "../game/surfaceflags.h"
+
+//#define AW_DEBUG
+//#define L_DEBUG
+
+#define AREAONFACESIDE(face, area) (face->frontarea != area)
+
+tmp_aas_t tmpaasworld;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_InitTmpAAS(void)
+{
+ //tmp faces
+ tmpaasworld.numfaces = 0;
+ tmpaasworld.facenum = 0;
+ tmpaasworld.faces = NULL;
+ //tmp convex areas
+ tmpaasworld.numareas = 0;
+ tmpaasworld.areanum = 0;
+ tmpaasworld.areas = NULL;
+ //tmp nodes
+ tmpaasworld.numnodes = 0;
+ tmpaasworld.nodes = NULL;
+ //
+ tmpaasworld.nodebuffer = NULL;
+} //end of the function AAS_InitTmpAAS
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_FreeTmpAAS(void)
+{
+ tmp_face_t *f, *nextf;
+ tmp_area_t *a, *nexta;
+ tmp_nodebuf_t *nb, *nextnb;
+
+ //free all the faces
+ for (f = tmpaasworld.faces; f; f = nextf)
+ {
+ nextf = f->l_next;
+ if (f->winding) FreeWinding(f->winding);
+ FreeMemory(f);
+ } //end if
+ //free all tmp areas
+ for (a = tmpaasworld.areas; a; a = nexta)
+ {
+ nexta = a->l_next;
+ if (a->settings) FreeMemory(a->settings);
+ FreeMemory(a);
+ } //end for
+ //free all the tmp nodes
+ for (nb = tmpaasworld.nodebuffer; nb; nb = nextnb)
+ {
+ nextnb = nb->next;
+ FreeMemory(nb);
+ } //end for
+} //end of the function AAS_FreeTmpAAS
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+tmp_face_t *AAS_AllocTmpFace(void)
+{
+ tmp_face_t *tmpface;
+
+ tmpface = (tmp_face_t *) GetClearedMemory(sizeof(tmp_face_t));
+ tmpface->num = tmpaasworld.facenum++;
+ tmpface->l_prev = NULL;
+ tmpface->l_next = tmpaasworld.faces;
+ if (tmpaasworld.faces) tmpaasworld.faces->l_prev = tmpface;
+ tmpaasworld.faces = tmpface;
+ tmpaasworld.numfaces++;
+ return tmpface;
+} //end of the function AAS_AllocTmpFace
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_FreeTmpFace(tmp_face_t *tmpface)
+{
+ if (tmpface->l_next) tmpface->l_next->l_prev = tmpface->l_prev;
+ if (tmpface->l_prev) tmpface->l_prev->l_next = tmpface->l_next;
+ else tmpaasworld.faces = tmpface->l_next;
+ //free the winding
+ if (tmpface->winding) FreeWinding(tmpface->winding);
+ //free the face
+ FreeMemory(tmpface);
+ tmpaasworld.numfaces--;
+} //end of the function AAS_FreeTmpFace
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+tmp_area_t *AAS_AllocTmpArea(void)
+{
+ tmp_area_t *tmparea;
+
+ tmparea = (tmp_area_t *) GetClearedMemory(sizeof(tmp_area_t));
+ tmparea->areanum = tmpaasworld.areanum++;
+ tmparea->l_prev = NULL;
+ tmparea->l_next = tmpaasworld.areas;
+ if (tmpaasworld.areas) tmpaasworld.areas->l_prev = tmparea;
+ tmpaasworld.areas = tmparea;
+ tmpaasworld.numareas++;
+ return tmparea;
+} //end of the function AAS_AllocTmpArea
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_FreeTmpArea(tmp_area_t *tmparea)
+{
+ if (tmparea->l_next) tmparea->l_next->l_prev = tmparea->l_prev;
+ if (tmparea->l_prev) tmparea->l_prev->l_next = tmparea->l_next;
+ else tmpaasworld.areas = tmparea->l_next;
+ if (tmparea->settings) FreeMemory(tmparea->settings);
+ FreeMemory(tmparea);
+ tmpaasworld.numareas--;
+} //end of the function AAS_FreeTmpArea
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+tmp_node_t *AAS_AllocTmpNode(void)
+{
+ tmp_nodebuf_t *nodebuf;
+
+ if (!tmpaasworld.nodebuffer ||
+ tmpaasworld.nodebuffer->numnodes >= NODEBUF_SIZE)
+ {
+ nodebuf = (tmp_nodebuf_t *) GetClearedMemory(sizeof(tmp_nodebuf_t));
+ nodebuf->next = tmpaasworld.nodebuffer;
+ nodebuf->numnodes = 0;
+ tmpaasworld.nodebuffer = nodebuf;
+ } //end if
+ tmpaasworld.numnodes++;
+ return &tmpaasworld.nodebuffer->nodes[tmpaasworld.nodebuffer->numnodes++];
+} //end of the function AAS_AllocTmpNode
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_FreeTmpNode(tmp_node_t *tmpnode)
+{
+ tmpaasworld.numnodes--;
+} //end of the function AAS_FreeTmpNode
+//===========================================================================
+// returns true if the face is a gap from the given side
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_GapFace(tmp_face_t *tmpface, int side)
+{
+ vec3_t invgravity;
+
+ //if the face is a solid or ground face it can't be a gap
+ if (tmpface->faceflags & (FACE_GROUND | FACE_SOLID)) return 0;
+
+ VectorCopy(cfg.phys_gravitydirection, invgravity);
+ VectorInverse(invgravity);
+
+ return (DotProduct(invgravity, mapplanes[tmpface->planenum ^ side].normal) > cfg.phys_maxsteepness);
+} //end of the function AAS_GapFace
+//===========================================================================
+// returns true if the face is a ground face
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_GroundFace(tmp_face_t *tmpface)
+{
+ vec3_t invgravity;
+
+ //must be a solid face
+ if (!(tmpface->faceflags & FACE_SOLID)) return 0;
+
+ VectorCopy(cfg.phys_gravitydirection, invgravity);
+ VectorInverse(invgravity);
+
+ return (DotProduct(invgravity, mapplanes[tmpface->planenum].normal) > cfg.phys_maxsteepness);
+} //end of the function AAS_GroundFace
+//===========================================================================
+// adds the side of a face to an area
+//
+// side : 0 = front side
+// 1 = back side
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_AddFaceSideToArea(tmp_face_t *tmpface, int side, tmp_area_t *tmparea)
+{
+ int tmpfaceside;
+
+ if (side)
+ {
+ if (tmpface->backarea) Error("AAS_AddFaceSideToArea: already a back area\n");
+ } //end if
+ else
+ {
+ if (tmpface->frontarea) Error("AAS_AddFaceSideToArea: already a front area\n");
+ } //end else
+
+ if (side) tmpface->backarea = tmparea;
+ else tmpface->frontarea = tmparea;
+
+ if (tmparea->tmpfaces)
+ {
+ tmpfaceside = tmparea->tmpfaces->frontarea != tmparea;
+ tmparea->tmpfaces->prev[tmpfaceside] = tmpface;
+ } //end if
+ tmpface->next[side] = tmparea->tmpfaces;
+ tmpface->prev[side] = NULL;
+ tmparea->tmpfaces = tmpface;
+} //end of the function AAS_AddFaceSideToArea
+//===========================================================================
+// remove (a side of) a face from an area
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_RemoveFaceFromArea(tmp_face_t *tmpface, tmp_area_t *tmparea)
+{
+ int side, prevside, nextside;
+
+ if (tmpface->frontarea != tmparea &&
+ tmpface->backarea != tmparea)
+ {
+ Error("AAS_RemoveFaceFromArea: face not part of the area");
+ } //end if
+ side = tmpface->frontarea != tmparea;
+ if (tmpface->prev[side])
+ {
+ prevside = tmpface->prev[side]->frontarea != tmparea;
+ tmpface->prev[side]->next[prevside] = tmpface->next[side];
+ } //end if
+ else
+ {
+ tmparea->tmpfaces = tmpface->next[side];
+ } //end else
+ if (tmpface->next[side])
+ {
+ nextside = tmpface->next[side]->frontarea != tmparea;
+ tmpface->next[side]->prev[nextside] = tmpface->prev[side];
+ } //end if
+ //remove the area number from the face depending on the side
+ if (side) tmpface->backarea = NULL;
+ else tmpface->frontarea = NULL;
+ tmpface->prev[side] = NULL;
+ tmpface->next[side] = NULL;
+} //end of the function AAS_RemoveFaceFromArea
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_CheckArea(tmp_area_t *tmparea)
+{
+ int side;
+ tmp_face_t *face;
+ plane_t *plane;
+ vec3_t wcenter, acenter = {0, 0, 0};
+ vec3_t normal;
+ float n, dist;
+
+ if (tmparea->invalid) Log_Print("AAS_CheckArea: invalid area\n");
+ for (n = 0, face = tmparea->tmpfaces; face; face = face->next[side])
+ {
+ //side of the face the area is on
+ side = face->frontarea != tmparea;
+ WindingCenter(face->winding, wcenter);
+ VectorAdd(acenter, wcenter, acenter);
+ n++;
+ } //end for
+ n = 1 / n;
+ VectorScale(acenter, n, acenter);
+ for (face = tmparea->tmpfaces; face; face = face->next[side])
+ {
+ //side of the face the area is on
+ side = face->frontarea != tmparea;
+
+#ifdef L_DEBUG
+ if (WindingError(face->winding))
+ {
+ Log_Write("AAS_CheckArea: area %d face %d: %s\r\n", tmparea->areanum,
+ face->num, WindingErrorString());
+ } //end if
+#endif L_DEBUG
+
+ plane = &mapplanes[face->planenum ^ side];
+
+ if (DotProduct(plane->normal, acenter) - plane->dist < 0)
+ {
+ Log_Print("AAS_CheckArea: area %d face %d is flipped\n", tmparea->areanum, face->num);
+ Log_Print("AAS_CheckArea: area %d center is %f %f %f\n", tmparea->areanum, acenter[0], acenter[1], acenter[2]);
+ } //end if
+ //check if the winding plane is the same as the face plane
+ WindingPlane(face->winding, normal, &dist);
+ plane = &mapplanes[face->planenum];
+#ifdef L_DEBUG
+ if (fabs(dist - plane->dist) > 0.4 ||
+ fabs(normal[0] - plane->normal[0]) > 0.0001 ||
+ fabs(normal[1] - plane->normal[1]) > 0.0001 ||
+ fabs(normal[2] - plane->normal[2]) > 0.0001)
+ {
+ Log_Write("AAS_CheckArea: area %d face %d winding plane unequal to face plane\r\n",
+ tmparea->areanum, face->num);
+ } //end if
+#endif L_DEBUG
+ } //end for
+} //end of the function AAS_CheckArea
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_CheckFaceWindingPlane(tmp_face_t *face)
+{
+ float dist, sign1, sign2;
+ vec3_t normal;
+ plane_t *plane;
+ winding_t *w;
+
+ //check if the winding plane is the same as the face plane
+ WindingPlane(face->winding, normal, &dist);
+ plane = &mapplanes[face->planenum];
+ //
+ sign1 = DotProduct(plane->normal, normal);
+ //
+ if (fabs(dist - plane->dist) > 0.4 ||
+ fabs(normal[0] - plane->normal[0]) > 0.0001 ||
+ fabs(normal[1] - plane->normal[1]) > 0.0001 ||
+ fabs(normal[2] - plane->normal[2]) > 0.0001)
+ {
+ VectorInverse(normal);
+ dist = -dist;
+ if (fabs(dist - plane->dist) > 0.4 ||
+ fabs(normal[0] - plane->normal[0]) > 0.0001 ||
+ fabs(normal[1] - plane->normal[1]) > 0.0001 ||
+ fabs(normal[2] - plane->normal[2]) > 0.0001)
+ {
+ Log_Write("AAS_CheckFaceWindingPlane: face %d winding plane unequal to face plane\r\n",
+ face->num);
+ //
+ sign2 = DotProduct(plane->normal, normal);
+ if ((sign1 < 0 && sign2 > 0) ||
+ (sign1 > 0 && sign2 < 0))
+ {
+ Log_Write("AAS_CheckFaceWindingPlane: face %d winding reversed\r\n",
+ face->num);
+ w = face->winding;
+ face->winding = ReverseWinding(w);
+ FreeWinding(w);
+ } //end if
+ } //end if
+ else
+ {
+ Log_Write("AAS_CheckFaceWindingPlane: face %d winding reversed\r\n",
+ face->num);
+ w = face->winding;
+ face->winding = ReverseWinding(w);
+ FreeWinding(w);
+ } //end else
+ } //end if
+} //end of the function AAS_CheckFaceWindingPlane
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_CheckAreaWindingPlanes(void)
+{
+ int side;
+ tmp_area_t *tmparea;
+ tmp_face_t *face;
+
+ Log_Write("AAS_CheckAreaWindingPlanes:\r\n");
+ for (tmparea = tmpaasworld.areas; tmparea; tmparea = tmparea->l_next)
+ {
+ if (tmparea->invalid) continue;
+ for (face = tmparea->tmpfaces; face; face = face->next[side])
+ {
+ side = face->frontarea != tmparea;
+ AAS_CheckFaceWindingPlane(face);
+ } //end for
+ } //end for
+} //end of the function AAS_CheckAreaWindingPlanes
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_FlipAreaFaces(tmp_area_t *tmparea)
+{
+ int side;
+ tmp_face_t *face;
+ plane_t *plane;
+ vec3_t wcenter, acenter = {0, 0, 0};
+ //winding_t *w;
+ float n;
+
+ for (n = 0, face = tmparea->tmpfaces; face; face = face->next[side])
+ {
+ if (!face->frontarea) Error("face %d has no front area\n", face->num);
+ //side of the face the area is on
+ side = face->frontarea != tmparea;
+ WindingCenter(face->winding, wcenter);
+ VectorAdd(acenter, wcenter, acenter);
+ n++;
+ } //end for
+ n = 1 / n;
+ VectorScale(acenter, n, acenter);
+ for (face = tmparea->tmpfaces; face; face = face->next[side])
+ {
+ //side of the face the area is on
+ side = face->frontarea != tmparea;
+
+ plane = &mapplanes[face->planenum ^ side];
+
+ if (DotProduct(plane->normal, acenter) - plane->dist < 0)
+ {
+ Log_Print("area %d face %d flipped: front area %d, back area %d\n", tmparea->areanum, face->num,
+ face->frontarea ? face->frontarea->areanum : 0,
+ face->backarea ? face->backarea->areanum : 0);
+ /*
+ face->planenum = face->planenum ^ 1;
+ w = face->winding;
+ face->winding = ReverseWinding(w);
+ FreeWinding(w);
+ */
+ } //end if
+#ifdef L_DEBUG
+ {
+ float dist;
+ vec3_t normal;
+
+ //check if the winding plane is the same as the face plane
+ WindingPlane(face->winding, normal, &dist);
+ plane = &mapplanes[face->planenum];
+ if (fabs(dist - plane->dist) > 0.4 ||
+ fabs(normal[0] - plane->normal[0]) > 0.0001 ||
+ fabs(normal[1] - plane->normal[1]) > 0.0001 ||
+ fabs(normal[2] - plane->normal[2]) > 0.0001)
+ {
+ Log_Write("area %d face %d winding plane unequal to face plane\r\n",
+ tmparea->areanum, face->num);
+ } //end if
+ }
+#endif
+ } //end for
+} //end of the function AAS_FlipAreaFaces
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_RemoveAreaFaceColinearPoints(void)
+{
+ int side;
+ tmp_face_t *face;
+ tmp_area_t *tmparea;
+
+ //FIXME: loop over the faces instead of area->faces
+ for (tmparea = tmpaasworld.areas; tmparea; tmparea = tmparea->l_next)
+ {
+ for (face = tmparea->tmpfaces; face; face = face->next[side])
+ {
+ side = face->frontarea != tmparea;
+ RemoveColinearPoints(face->winding);
+// RemoveEqualPoints(face->winding, 0.1);
+ } //end for
+ } //end for
+} //end of the function AAS_RemoveAreaFaceColinearPoints
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_RemoveTinyFaces(void)
+{
+ int side, num;
+ tmp_face_t *face, *nextface;
+ tmp_area_t *tmparea;
+
+ //FIXME: loop over the faces instead of area->faces
+ Log_Write("AAS_RemoveTinyFaces\r\n");
+ num = 0;
+ for (tmparea = tmpaasworld.areas; tmparea; tmparea = tmparea->l_next)
+ {
+ for (face = tmparea->tmpfaces; face; face = nextface)
+ {
+ side = face->frontarea != tmparea;
+ nextface = face->next[side];
+ //
+ if (WindingArea(face->winding) < 1)
+ {
+ if (face->frontarea) AAS_RemoveFaceFromArea(face, face->frontarea);
+ if (face->backarea) AAS_RemoveFaceFromArea(face, face->backarea);
+ AAS_FreeTmpFace(face);
+ //Log_Write("area %d face %d is tiny\r\n", tmparea->areanum, face->num);
+ num++;
+ } //end if
+ } //end for
+ } //end for
+ Log_Write("%d tiny faces removed\r\n", num);
+} //end of the function AAS_RemoveTinyFaces
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_CreateAreaSettings(void)
+{
+ int i, flags, side, numgrounded, numladderareas, numliquidareas;
+ tmp_face_t *face;
+ tmp_area_t *tmparea;
+
+ numgrounded = 0;
+ numladderareas = 0;
+ numliquidareas = 0;
+ Log_Write("AAS_CreateAreaSettings\r\n");
+ i = 0;
+ qprintf("%6d areas provided with settings", i);
+ for (tmparea = tmpaasworld.areas; tmparea; tmparea = tmparea->l_next)
+ {
+ //if the area is invalid there no need to create settings for it
+ if (tmparea->invalid) continue;
+
+ tmparea->settings = (tmp_areasettings_t *) GetClearedMemory(sizeof(tmp_areasettings_t));
+ tmparea->settings->contents = tmparea->contents;
+ tmparea->settings->modelnum = tmparea->modelnum;
+ flags = 0;
+ for (face = tmparea->tmpfaces; face; face = face->next[side])
+ {
+ side = face->frontarea != tmparea;
+ flags |= face->faceflags;
+ } //end for
+ tmparea->settings->areaflags = 0;
+ if (flags & FACE_GROUND)
+ {
+ tmparea->settings->areaflags |= AREA_GROUNDED;
+ numgrounded++;
+ } //end if
+ if (flags & FACE_LADDER)
+ {
+ tmparea->settings->areaflags |= AREA_LADDER;
+ numladderareas++;
+ } //end if
+ if (tmparea->contents & (AREACONTENTS_WATER |
+ AREACONTENTS_SLIME |
+ AREACONTENTS_LAVA))
+ {
+ tmparea->settings->areaflags |= AREA_LIQUID;
+ numliquidareas++;
+ } //end if
+ //presence type of the area
+ tmparea->settings->presencetype = tmparea->presencetype;
+ //
+ qprintf("\r%6d", ++i);
+ } //end for
+ qprintf("\n");
+#ifdef AASINFO
+ Log_Print("%6d grounded areas\n", numgrounded);
+ Log_Print("%6d ladder areas\n", numladderareas);
+ Log_Print("%6d liquid areas\n", numliquidareas);
+#endif //AASINFO
+} //end of the function AAS_CreateAreaSettings
+//===========================================================================
+// create a tmp AAS area from a leaf node
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+tmp_node_t *AAS_CreateArea(node_t *node)
+{
+ int pside;
+ int areafaceflags;
+ portal_t *p;
+ tmp_face_t *tmpface;
+ tmp_area_t *tmparea;
+ tmp_node_t *tmpnode;
+ vec3_t up = {0, 0, 1};
+
+ //create an area from this leaf
+ tmparea = AAS_AllocTmpArea();
+ tmparea->tmpfaces = NULL;
+ //clear the area face flags
+ areafaceflags = 0;
+ //make aas faces from the portals
+ for (p = node->portals; p; p = p->next[pside])
+ {
+ pside = (p->nodes[1] == node);
+ //don't create faces from very small portals
+// if (WindingArea(p->winding) < 1) continue;
+ //if there's already a face created for this portal
+ if (p->tmpface)
+ {
+ //add the back side of the face to the area
+ AAS_AddFaceSideToArea(p->tmpface, 1, tmparea);
+ } //end if
+ else
+ {
+ tmpface = AAS_AllocTmpFace();
+ //set the face pointer at the portal so we can see from
+ //the portal there's a face created for it
+ p->tmpface = tmpface;
+ //FIXME: test this change
+ //tmpface->planenum = (p->planenum & ~1) | pside;
+ tmpface->planenum = p->planenum ^ pside;
+ if (pside) tmpface->winding = ReverseWinding(p->winding);
+ else tmpface->winding = CopyWinding(p->winding);
+#ifdef L_DEBUG
+ //
+ AAS_CheckFaceWindingPlane(tmpface);
+#endif //L_DEBUG
+ //if there's solid at the other side of the portal
+ if (p->nodes[!pside]->contents & (CONTENTS_SOLID | CONTENTS_PLAYERCLIP))
+ {
+ tmpface->faceflags |= FACE_SOLID;
+ } //end if
+ //else there is no solid at the other side and if there
+ //is a liquid at this side
+ else if (node->contents & (CONTENTS_WATER|CONTENTS_SLIME|CONTENTS_LAVA))
+ {
+ tmpface->faceflags |= FACE_LIQUID;
+ //if there's no liquid at the other side
+ if (!(p->nodes[!pside]->contents & (CONTENTS_WATER|CONTENTS_SLIME|CONTENTS_LAVA)))
+ {
+ tmpface->faceflags |= FACE_LIQUIDSURFACE;
+ } //end if
+ } //end else
+ //if there's ladder contents at other side of the portal
+ if ((p->nodes[pside]->contents & CONTENTS_LADDER) ||
+ (p->nodes[!pside]->contents & CONTENTS_LADDER))
+ {
+
+ //NOTE: doesn't have to be solid at the other side because
+ // when standing one can use a crouch area (which is not solid)
+ // as a ladder
+ // imagine a ladder one can walk underthrough,
+ // under the ladder against the ladder is a crouch area
+ // the (vertical) sides of this crouch area area also used as
+ // ladder sides when standing (not crouched)
+ tmpface->faceflags |= FACE_LADDER;
+ } //end if
+ //if it is possible to stand on the face
+ if (AAS_GroundFace(tmpface))
+ {
+ tmpface->faceflags |= FACE_GROUND;
+ } //end if
+ //
+ areafaceflags |= tmpface->faceflags;
+ //no aas face number yet (zero is a dummy in the aasworld faces)
+ tmpface->aasfacenum = 0;
+ //add the front side of the face to the area
+ AAS_AddFaceSideToArea(tmpface, 0, tmparea);
+ } //end else
+ } //end for
+ qprintf("\r%6d", tmparea->areanum);
+ //presence type in the area
+ tmparea->presencetype = ~node->expansionbboxes & cfg.allpresencetypes;
+ //
+ tmparea->contents = 0;
+ if (node->contents & CONTENTS_CLUSTERPORTAL) tmparea->contents |= AREACONTENTS_CLUSTERPORTAL;
+ if (node->contents & CONTENTS_MOVER) tmparea->contents |= AREACONTENTS_MOVER;
+ if (node->contents & CONTENTS_TELEPORTER) tmparea->contents |= AREACONTENTS_TELEPORTER;
+ if (node->contents & CONTENTS_JUMPPAD) tmparea->contents |= AREACONTENTS_JUMPPAD;
+ if (node->contents & CONTENTS_DONOTENTER) tmparea->contents |= AREACONTENTS_DONOTENTER;
+ if (node->contents & CONTENTS_WATER) tmparea->contents |= AREACONTENTS_WATER;
+ if (node->contents & CONTENTS_LAVA) tmparea->contents |= AREACONTENTS_LAVA;
+ if (node->contents & CONTENTS_SLIME) tmparea->contents |= AREACONTENTS_SLIME;
+ if (node->contents & CONTENTS_NOTTEAM1) tmparea->contents |= AREACONTENTS_NOTTEAM1;
+ if (node->contents & CONTENTS_NOTTEAM2) tmparea->contents |= AREACONTENTS_NOTTEAM2;
+
+ //store the bsp model that's inside this node
+ tmparea->modelnum = node->modelnum;
+ //sorta check for flipped area faces (remove??)
+ AAS_FlipAreaFaces(tmparea);
+ //check if the area is ok (remove??)
+ AAS_CheckArea(tmparea);
+ //
+ tmpnode = AAS_AllocTmpNode();
+ tmpnode->planenum = 0;
+ tmpnode->children[0] = 0;
+ tmpnode->children[1] = 0;
+ tmpnode->tmparea = tmparea;
+ //
+ return tmpnode;
+} //end of the function AAS_CreateArea
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+tmp_node_t *AAS_CreateAreas_r(node_t *node)
+{
+ tmp_node_t *tmpnode;
+
+ //recurse down to leafs
+ if (node->planenum != PLANENUM_LEAF)
+ {
+ //the first tmp node is a dummy
+ tmpnode = AAS_AllocTmpNode();
+ tmpnode->planenum = node->planenum;
+ tmpnode->children[0] = AAS_CreateAreas_r(node->children[0]);
+ tmpnode->children[1] = AAS_CreateAreas_r(node->children[1]);
+ return tmpnode;
+ } //end if
+ //areas won't be created for solid leafs
+ if (node->contents & CONTENTS_SOLID)
+ {
+ //just return zero for a solid leaf (in tmp AAS NULL is a solid leaf)
+ return NULL;
+ } //end if
+
+ return AAS_CreateArea(node);
+} //end of the function AAS_CreateAreas_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_CreateAreas(node_t *node)
+{
+ Log_Write("AAS_CreateAreas\r\n");
+ qprintf("%6d areas created", 0);
+ tmpaasworld.nodes = AAS_CreateAreas_r(node);
+ qprintf("\n");
+ Log_Write("%6d areas created\r\n", tmpaasworld.numareas);
+} //end of the function AAS_CreateAreas
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_PrintNumGroundFaces(void)
+{
+ tmp_face_t *tmpface;
+ int numgroundfaces = 0;
+
+ for (tmpface = tmpaasworld.faces; tmpface; tmpface = tmpface->l_next)
+ {
+ if (tmpface->faceflags & FACE_GROUND)
+ {
+ numgroundfaces++;
+ } //end if
+ } //end for
+ qprintf("%6d ground faces\n", numgroundfaces);
+} //end of the function AAS_PrintNumGroundFaces
+//===========================================================================
+// checks the number of shared faces between the given two areas
+// since areas are convex they should only have ONE shared face
+// however due to crappy face merging there are sometimes several
+// shared faces
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_CheckAreaSharedFaces(tmp_area_t *tmparea1, tmp_area_t *tmparea2)
+{
+ int numsharedfaces, side;
+ tmp_face_t *face1, *sharedface;
+
+ if (tmparea1->invalid || tmparea2->invalid) return;
+
+ sharedface = NULL;
+ numsharedfaces = 0;
+ for (face1 = tmparea1->tmpfaces; face1; face1 = face1->next[side])
+ {
+ side = face1->frontarea != tmparea1;
+ if (face1->backarea == tmparea2 || face1->frontarea == tmparea2)
+ {
+ sharedface = face1;
+ numsharedfaces++;
+ } //end if
+ } //end if
+ if (!sharedface) return;
+ //the areas should only have one shared face
+ if (numsharedfaces > 1)
+ {
+ Log_Write("---- tmp area %d and %d have %d shared faces\r\n",
+ tmparea1->areanum, tmparea2->areanum, numsharedfaces);
+ for (face1 = tmparea1->tmpfaces; face1; face1 = face1->next[side])
+ {
+ side = face1->frontarea != tmparea1;
+ if (face1->backarea == tmparea2 || face1->frontarea == tmparea2)
+ {
+ Log_Write("face %d, planenum = %d, face->frontarea = %d face->backarea = %d\r\n",
+ face1->num, face1->planenum, face1->frontarea->areanum, face1->backarea->areanum);
+ } //end if
+ } //end if
+ } //end if
+} //end of the function AAS_CheckAreaSharedFaces
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_CheckSharedFaces(void)
+{
+ tmp_area_t *tmparea1, *tmparea2;
+
+ for (tmparea1 = tmpaasworld.areas; tmparea1; tmparea1 = tmparea1->l_next)
+ {
+ for (tmparea2 = tmpaasworld.areas; tmparea2; tmparea2 = tmparea2->l_next)
+ {
+ if (tmparea1 == tmparea2) continue;
+ AAS_CheckAreaSharedFaces(tmparea1, tmparea2);
+ } //end for
+ } //end for
+} //end of the function AAS_CheckSharedFaces
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_FlipFace(tmp_face_t *face)
+{
+ tmp_area_t *frontarea, *backarea;
+ winding_t *w;
+
+ frontarea = face->frontarea;
+ backarea = face->backarea;
+ //must have an area at both sides before flipping is allowed
+ if (!frontarea || !backarea) return;
+ //flip the face winding
+ w = face->winding;
+ face->winding = ReverseWinding(w);
+ FreeWinding(w);
+ //flip the face plane
+ face->planenum ^= 1;
+ //flip the face areas
+ AAS_RemoveFaceFromArea(face, frontarea);
+ AAS_RemoveFaceFromArea(face, backarea);
+ AAS_AddFaceSideToArea(face, 1, frontarea);
+ AAS_AddFaceSideToArea(face, 0, backarea);
+} //end of the function AAS_FlipFace
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+/*
+void AAS_FlipAreaSharedFaces(tmp_area_t *tmparea1, tmp_area_t *tmparea2)
+{
+ int numsharedfaces, side, area1facing, area2facing;
+ tmp_face_t *face1, *sharedface;
+
+ if (tmparea1->invalid || tmparea2->invalid) return;
+
+ sharedface = NULL;
+ numsharedfaces = 0;
+ area1facing = 0; //number of shared faces facing towards area 1
+ area2facing = 0; //number of shared faces facing towards area 2
+ for (face1 = tmparea1->tmpfaces; face1; face1 = face1->next[side])
+ {
+ side = face1->frontarea != tmparea1;
+ if (face1->backarea == tmparea2 || face1->frontarea == tmparea2)
+ {
+ sharedface = face1;
+ numsharedfaces++;
+ if (face1->frontarea == tmparea1) area1facing++;
+ else area2facing++;
+ } //end if
+ } //end if
+ if (!sharedface) return;
+ //if there's only one shared face
+ if (numsharedfaces <= 1) return;
+ //if all the shared faces are facing to the same area
+ if (numsharedfaces == area1facing || numsharedfaces == area2facing) return;
+ //
+ do
+ {
+ for (face1 = tmparea1->tmpfaces; face1; face1 = face1->next[side])
+ {
+ side = face1->frontarea != tmparea1;
+ if (face1->backarea == tmparea2 || face1->frontarea == tmparea2)
+ {
+ if (face1->frontarea != tmparea1)
+ {
+ AAS_FlipFace(face1);
+ break;
+ } //end if
+ } //end if
+ } //end for
+ } while(face1);
+} //end of the function AAS_FlipAreaSharedFaces
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_FlipSharedFaces(void)
+{
+ int i;
+ tmp_area_t *tmparea1, *tmparea2;
+
+ i = 0;
+ qprintf("%6d areas checked for shared face flipping", i);
+ for (tmparea1 = tmpaasworld.areas; tmparea1; tmparea1 = tmparea1->l_next)
+ {
+ if (tmparea1->invalid) continue;
+ for (tmparea2 = tmpaasworld.areas; tmparea2; tmparea2 = tmparea2->l_next)
+ {
+ if (tmparea2->invalid) continue;
+ if (tmparea1 == tmparea2) continue;
+ AAS_FlipAreaSharedFaces(tmparea1, tmparea2);
+ } //end for
+ qprintf("\r%6d", ++i);
+ } //end for
+ Log_Print("\r%6d areas checked for shared face flipping\n", i);
+} //end of the function AAS_FlipSharedFaces
+*/
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_FlipSharedFaces(void)
+{
+ int i, side1, side2;
+ tmp_area_t *tmparea1;
+ tmp_face_t *face1, *face2;
+
+ i = 0;
+ qprintf("%6d areas checked for shared face flipping", i);
+ for (tmparea1 = tmpaasworld.areas; tmparea1; tmparea1 = tmparea1->l_next)
+ {
+ if (tmparea1->invalid) continue;
+ for (face1 = tmparea1->tmpfaces; face1; face1 = face1->next[side1])
+ {
+ side1 = face1->frontarea != tmparea1;
+ if (!face1->frontarea || !face1->backarea) continue;
+ //
+ for (face2 = face1->next[side1]; face2; face2 = face2->next[side2])
+ {
+ side2 = face2->frontarea != tmparea1;
+ if (!face2->frontarea || !face2->backarea) continue;
+ //
+ if (face1->frontarea == face2->backarea &&
+ face1->backarea == face2->frontarea)
+ {
+ AAS_FlipFace(face2);
+ } //end if
+ //recheck side
+ side2 = face2->frontarea != tmparea1;
+ } //end for
+ } //end for
+ qprintf("\r%6d", ++i);
+ } //end for
+ qprintf("\n");
+ Log_Write("%6d areas checked for shared face flipping\r\n", i);
+} //end of the function AAS_FlipSharedFaces
+//===========================================================================
+// creates an .AAS file with the given name
+// a MAP should be loaded before calling this
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_Create(char *aasfile)
+{
+ entity_t *e;
+ tree_t *tree;
+ double start_time;
+
+ //for a possible leak file
+ strcpy(source, aasfile);
+ StripExtension(source);
+ //the time started
+ start_time = I_FloatTime();
+ //set the default number of threads (depends on number of processors)
+ ThreadSetDefault();
+ //set the global entity number to the world model
+ entity_num = 0;
+ //the world entity
+ e = &entities[entity_num];
+ //process the whole world
+ tree = ProcessWorldBrushes(e->firstbrush, e->firstbrush + e->numbrushes);
+ //if the conversion is cancelled
+ if (cancelconversion)
+ {
+ Tree_Free(tree);
+ return;
+ } //end if
+ //display BSP tree creation time
+ Log_Print("BSP tree created in %5.0f seconds\n", I_FloatTime() - start_time);
+ //prune the bsp tree
+ Tree_PruneNodes(tree->headnode);
+ //if the conversion is cancelled
+ if (cancelconversion)
+ {
+ Tree_Free(tree);
+ return;
+ } //end if
+ //create the tree portals
+ MakeTreePortals(tree);
+ //if the conversion is cancelled
+ if (cancelconversion)
+ {
+ Tree_Free(tree);
+ return;
+ } //end if
+ //Marks all nodes that can be reached by entites
+ if (FloodEntities(tree))
+ {
+ //fill out nodes that can't be reached
+ FillOutside(tree->headnode);
+ } //end if
+ else
+ {
+ LeakFile(tree);
+ Error("**** leaked ****\n");
+ return;
+ } //end else
+ //create AAS from the BSP tree
+ //==========================================
+ //initialize tmp aas
+ AAS_InitTmpAAS();
+ //create the convex areas from the leaves
+ AAS_CreateAreas(tree->headnode);
+ //free the BSP tree because it isn't used anymore
+ if (freetree) Tree_Free(tree);
+ //try to merge area faces
+ AAS_MergeAreaFaces();
+ //do gravitational subdivision
+ AAS_GravitationalSubdivision();
+ //merge faces if possible
+ AAS_MergeAreaFaces();
+ AAS_RemoveAreaFaceColinearPoints();
+ //merge areas if possible
+ AAS_MergeAreas();
+ //NOTE: prune nodes directly after area merging
+ AAS_PruneNodes();
+ //flip shared faces so they are all facing to the same area
+ AAS_FlipSharedFaces();
+ AAS_RemoveAreaFaceColinearPoints();
+ //merge faces if possible
+ AAS_MergeAreaFaces();
+ //merge area faces in the same plane
+ AAS_MergeAreaPlaneFaces();
+ //do ladder subdivision
+ AAS_LadderSubdivision();
+ //FIXME: melting is buggy
+ AAS_MeltAreaFaceWindings();
+ //remove tiny faces
+ AAS_RemoveTinyFaces();
+ //create area settings
+ AAS_CreateAreaSettings();
+ //check if the winding plane is equal to the face plane
+ //AAS_CheckAreaWindingPlanes();
+ //
+ //AAS_CheckSharedFaces();
+ //==========================================
+ //if the conversion is cancelled
+ if (cancelconversion)
+ {
+ Tree_Free(tree);
+ AAS_FreeTmpAAS();
+ return;
+ } //end if
+ //store the created AAS stuff in the AAS file format and write the file
+ AAS_StoreFile(aasfile);
+ //free the temporary AAS memory
+ AAS_FreeTmpAAS();
+ //display creation time
+ Log_Print("\nAAS created in %5.0f seconds\n", I_FloatTime() - start_time);
+} //end of the function AAS_Create
diff --git a/code/bspc/aas_create.h b/code/bspc/aas_create.h
new file mode 100755
index 0000000..cc5693c
--- /dev/null
+++ b/code/bspc/aas_create.h
@@ -0,0 +1,136 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#define AREA_PORTAL 1
+
+//temporary AAS face
+typedef struct tmp_face_s
+{
+ int num; //face number
+ int planenum; //number of the plane the face is in
+ winding_t *winding; //winding of the face
+ struct tmp_area_s *frontarea; //area at the front of the face
+ struct tmp_area_s *backarea; //area at the back of the face
+ int faceflags; //flags of this face
+ int aasfacenum; //the number of the aas face used for this face
+ //double link list pointers for front and back area
+ struct tmp_face_s *prev[2], *next[2];
+ //links in the list with faces
+ struct tmp_face_s *l_prev, *l_next;
+} tmp_face_t;
+
+//temporary AAS area settings
+typedef struct tmp_areasettings_s
+{
+ //could also add all kind of statistic fields
+ int contents; //contents of the area
+ int modelnum; //bsp model inside this area
+ int areaflags; //area flags
+ int presencetype; //how a bot can be present in this area
+ int numreachableareas; //number of reachable areas from this one
+ int firstreachablearea; //first reachable area in the reachable area index
+} tmp_areasettings_t;
+
+//temporary AAS area
+typedef struct tmp_area_s
+{
+ int areanum; //number of the area
+ struct tmp_face_s *tmpfaces; //the faces of the area
+ int presencetype; //presence type of the area
+ int contents; //area contents
+ int modelnum; //bsp model inside this area
+ int invalid; //true if the area is invalid
+ tmp_areasettings_t *settings; //area settings
+ struct tmp_area_s *mergedarea; //points to the new area after merging
+ //when mergedarea != 0 the area has only the
+ //seperating face of the merged areas
+ int aasareanum; //number of the aas area created for this tmp area
+ //links in the list with areas
+ struct tmp_area_s *l_prev, *l_next;
+} tmp_area_t;
+
+//temporary AAS node
+typedef struct tmp_node_s
+{
+ int planenum; //node plane number
+ struct tmp_area_s *tmparea; //points to an area if this node is an area
+ struct tmp_node_s *children[2]; //child nodes of this node
+} tmp_node_t;
+
+#define NODEBUF_SIZE 128
+//node buffer
+typedef struct tmp_nodebuf_s
+{
+ int numnodes;
+ struct tmp_nodebuf_s *next;
+ tmp_node_t nodes[NODEBUF_SIZE];
+} tmp_nodebuf_t;
+
+//the whole temorary AAS
+typedef struct tmp_aas_s
+{
+ //faces
+ int numfaces;
+ int facenum;
+ tmp_face_t *faces;
+ //areas
+ int numareas;
+ int areanum;
+ tmp_area_t *areas;
+ //area settings
+ int numareasettings;
+ tmp_areasettings_t *areasettings;
+ //nodes
+ int numnodes;
+ tmp_node_t *nodes;
+ //node buffer
+ tmp_nodebuf_t *nodebuffer;
+} tmp_aas_t;
+
+extern tmp_aas_t tmpaasworld;
+
+//creates a .AAS file with the given name from an already loaded map
+void AAS_Create(char *aasfile);
+//adds a face side to an area
+void AAS_AddFaceSideToArea(tmp_face_t *tmpface, int side, tmp_area_t *tmparea);
+//remvoes a face from an area
+void AAS_RemoveFaceFromArea(tmp_face_t *tmpface, tmp_area_t *tmparea);
+//allocate a tmp face
+tmp_face_t *AAS_AllocTmpFace(void);
+//free the tmp face
+void AAS_FreeTmpFace(tmp_face_t *tmpface);
+//allocate a tmp area
+tmp_area_t *AAS_AllocTmpArea(void);
+//free a tmp area
+void AAS_FreeTmpArea(tmp_area_t *tmparea);
+//allocate a tmp node
+tmp_node_t *AAS_AllocTmpNode(void);
+//free a tmp node
+void AAS_FreeTmpNode(tmp_node_t *node);
+//checks if an area is ok
+void AAS_CheckArea(tmp_area_t *tmparea);
+//flips the area faces where needed
+void AAS_FlipAreaFaces(tmp_area_t *tmparea);
+//returns true if the face is a gap seen from the given side
+int AAS_GapFace(tmp_face_t *tmpface, int side);
+//returns true if the face is a ground face
+int AAS_GroundFace(tmp_face_t *tmpface);
diff --git a/code/bspc/aas_edgemelting.c b/code/bspc/aas_edgemelting.c
new file mode 100755
index 0000000..e84f48b
--- /dev/null
+++ b/code/bspc/aas_edgemelting.c
@@ -0,0 +1,108 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+#include "../botlib/aasfile.h"
+#include "aas_create.h"
+
+//===========================================================================
+// try to melt the windings of the two faces
+// FIXME: this is buggy
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_MeltFaceWinding(tmp_face_t *face1, tmp_face_t *face2)
+{
+ int i, n;
+ int splits = 0;
+ winding_t *w2, *neww;
+ plane_t *plane1;
+
+#ifdef DEBUG
+ if (!face1->winding) Error("face1 %d without winding", face1->num);
+ if (!face2->winding) Error("face2 %d without winding", face2->num);
+#endif //DEBUG
+ w2 = face2->winding;
+ plane1 = &mapplanes[face1->planenum];
+ for (i = 0; i < w2->numpoints; i++)
+ {
+ if (PointOnWinding(face1->winding, plane1->normal, plane1->dist, w2->p[i], &n))
+ {
+ neww = AddWindingPoint(face1->winding, w2->p[i], n);
+ FreeWinding(face1->winding);
+ face1->winding = neww;
+
+ splits++;
+ } //end if
+ } //end for
+ return splits;
+} //end of the function AAS_MeltFaceWinding
+//===========================================================================
+// melt the windings of the area faces
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_MeltFaceWindingsOfArea(tmp_area_t *tmparea)
+{
+ int side1, side2, num_windingsplits = 0;
+ tmp_face_t *face1, *face2;
+
+ for (face1 = tmparea->tmpfaces; face1; face1 = face1->next[side1])
+ {
+ side1 = face1->frontarea != tmparea;
+ for (face2 = tmparea->tmpfaces; face2; face2 = face2->next[side2])
+ {
+ side2 = face2->frontarea != tmparea;
+ if (face1 == face2) continue;
+ num_windingsplits += AAS_MeltFaceWinding(face1, face2);
+ } //end for
+ } //end for
+ return num_windingsplits;
+} //end of the function AAS_MeltFaceWindingsOfArea
+//===========================================================================
+// melt the windings of the faces of all areas
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_MeltAreaFaceWindings(void)
+{
+ tmp_area_t *tmparea;
+ int num_windingsplits = 0;
+
+ Log_Write("AAS_MeltAreaFaceWindings\r\n");
+ qprintf("%6d edges melted", num_windingsplits);
+ //NOTE: first convex area (zero) is a dummy
+ for (tmparea = tmpaasworld.areas; tmparea; tmparea = tmparea->l_next)
+ {
+ num_windingsplits += AAS_MeltFaceWindingsOfArea(tmparea);
+ qprintf("\r%6d", num_windingsplits);
+ } //end for
+ qprintf("\n");
+ Log_Write("%6d edges melted\r\n", num_windingsplits);
+} //end of the function AAS_MeltAreaFaceWindings
+
diff --git a/code/bspc/aas_edgemelting.h b/code/bspc/aas_edgemelting.h
new file mode 100755
index 0000000..4c03e97
--- /dev/null
+++ b/code/bspc/aas_edgemelting.h
@@ -0,0 +1,24 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+void AAS_MeltAreaFaceWindings(void);
+
diff --git a/code/bspc/aas_facemerging.c b/code/bspc/aas_facemerging.c
new file mode 100755
index 0000000..bf170de
--- /dev/null
+++ b/code/bspc/aas_facemerging.c
@@ -0,0 +1,282 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+#include "../botlib/aasfile.h"
+#include "aas_create.h"
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_TryMergeFaces(tmp_face_t *face1, tmp_face_t *face2)
+{
+ winding_t *neww;
+
+#ifdef DEBUG
+ if (!face1->winding) Error("face1 %d without winding", face1->num);
+ if (!face2->winding) Error("face2 %d without winding", face2->num);
+#endif //DEBUG
+ //
+ if (face1->faceflags != face2->faceflags) return false;
+ //NOTE: if the front or back area is zero this doesn't mean there's
+ //a real area. It means there's solid at that side of the face
+ //if both faces have the same front area
+ if (face1->frontarea == face2->frontarea)
+ {
+ //if both faces have the same back area
+ if (face1->backarea == face2->backarea)
+ {
+ //if the faces are in the same plane
+ if (face1->planenum == face2->planenum)
+ {
+ //if they have both a front and a back area (no solid on either side)
+ if (face1->frontarea && face1->backarea)
+ {
+ neww = MergeWindings(face1->winding, face2->winding,
+ mapplanes[face1->planenum].normal);
+ } //end if
+ else
+ {
+ //this function is to be found in l_poly.c
+ neww = TryMergeWinding(face1->winding, face2->winding,
+ mapplanes[face1->planenum].normal);
+ } //end else
+ if (neww)
+ {
+ FreeWinding(face1->winding);
+ face1->winding = neww;
+ if (face2->frontarea) AAS_RemoveFaceFromArea(face2, face2->frontarea);
+ if (face2->backarea) AAS_RemoveFaceFromArea(face2, face2->backarea);
+ AAS_FreeTmpFace(face2);
+ return true;
+ } //end if
+ } //end if
+ else if ((face1->planenum & ~1) == (face2->planenum & ~1))
+ {
+ Log_Write("face %d and %d, same front and back area but flipped planes\r\n",
+ face1->num, face2->num);
+ } //end if
+ } //end if
+ } //end if
+ return false;
+} //end of the function AAS_TryMergeFaces
+/*
+int AAS_TryMergeFaces(tmp_face_t *face1, tmp_face_t *face2)
+{
+ winding_t *neww;
+
+#ifdef DEBUG
+ if (!face1->winding) Error("face1 %d without winding", face1->num);
+ if (!face2->winding) Error("face2 %d without winding", face2->num);
+#endif //DEBUG
+ //if the faces are in the same plane
+ if ((face1->planenum & ~1) != (face2->planenum & ~1)) return false;
+// if (face1->planenum != face2->planenum) return false;
+ //NOTE: if the front or back area is zero this doesn't mean there's
+ //a real area. It means there's solid at that side of the face
+ //if both faces have the same front area
+ if (face1->frontarea != face2->frontarea ||
+ face1->backarea != face2->backarea)
+ {
+ if (!face1->frontarea || !face1->backarea ||
+ !face2->frontarea || !face2->backarea) return false;
+ else if (face1->frontarea != face2->backarea ||
+ face1->backarea != face2->frontarea) return false;
+// return false;
+ } //end if
+ //this function is to be found in l_poly.c
+ neww = TryMergeWinding(face1->winding, face2->winding,
+ mapplanes[face1->planenum].normal);
+ if (!neww) return false;
+ //
+ FreeWinding(face1->winding);
+ face1->winding = neww;
+ //remove face2
+ if (face2->frontarea)
+ AAS_RemoveFaceFromArea(face2, &tmpaasworld.areas[face2->frontarea]);
+ if (face2->backarea)
+ AAS_RemoveFaceFromArea(face2, &tmpaasworld.areas[face2->backarea]);
+ return true;
+} //end of the function AAS_TryMergeFaces*/
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_MergeAreaFaces(void)
+{
+ int num_facemerges = 0;
+ int side1, side2, restart;
+ tmp_area_t *tmparea, *lasttmparea;
+ tmp_face_t *face1, *face2;
+
+ Log_Write("AAS_MergeAreaFaces\r\n");
+ qprintf("%6d face merges", num_facemerges);
+ //NOTE: first convex area is a dummy
+ lasttmparea = tmpaasworld.areas;
+ for (tmparea = tmpaasworld.areas; tmparea; tmparea = tmparea->l_next)
+ {
+ restart = false;
+ //
+ if (tmparea->invalid) continue;
+ //
+ for (face1 = tmparea->tmpfaces; face1; face1 = face1->next[side1])
+ {
+ side1 = face1->frontarea != tmparea;
+ for (face2 = face1->next[side1]; face2; face2 = face2->next[side2])
+ {
+ side2 = face2->frontarea != tmparea;
+ //if succesfully merged
+ if (AAS_TryMergeFaces(face1, face2))
+ {
+ //start over again after merging two faces
+ restart = true;
+ num_facemerges++;
+ qprintf("\r%6d", num_facemerges);
+ AAS_CheckArea(tmparea);
+ break;
+ } //end if
+ } //end for
+ if (restart)
+ {
+ tmparea = lasttmparea;
+ break;
+ } //end if
+ } //end for
+ lasttmparea = tmparea;
+ } //end for
+ qprintf("\n");
+ Log_Write("%6d face merges\r\n", num_facemerges);
+} //end of the function AAS_MergeAreaFaces
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_MergePlaneFaces(tmp_area_t *tmparea, int planenum)
+{
+ tmp_face_t *face1, *face2, *nextface2;
+ winding_t *neww;
+ int side1, side2;
+
+ for (face1 = tmparea->tmpfaces; face1; face1 = face1->next[side1])
+ {
+ side1 = face1->frontarea != tmparea;
+ if (face1->planenum != planenum) continue;
+ //
+ for (face2 = face1->next[side1]; face2; face2 = nextface2)
+ {
+ side2 = face2->frontarea != tmparea;
+ nextface2 = face2->next[side2];
+ //
+ if ((face2->planenum & ~1) != (planenum & ~1)) continue;
+ //
+ neww = MergeWindings(face1->winding, face2->winding,
+ mapplanes[face1->planenum].normal);
+ FreeWinding(face1->winding);
+ face1->winding = neww;
+ if (face2->frontarea) AAS_RemoveFaceFromArea(face2, face2->frontarea);
+ if (face2->backarea) AAS_RemoveFaceFromArea(face2, face2->backarea);
+ AAS_FreeTmpFace(face2);
+ //
+ nextface2 = face1->next[side1];
+ } //end for
+ } //end for
+} //end of the function AAS_MergePlaneFaces
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_CanMergePlaneFaces(tmp_area_t *tmparea, int planenum)
+{
+ tmp_area_t *frontarea, *backarea;
+ tmp_face_t *face1;
+ int side1, merge, faceflags;
+
+ frontarea = backarea = NULL;
+ merge = false;
+ for (face1 = tmparea->tmpfaces; face1; face1 = face1->next[side1])
+ {
+ side1 = face1->frontarea != tmparea;
+ if ((face1->planenum & ~1) != (planenum & ~1)) continue;
+ if (!frontarea && !backarea)
+ {
+ frontarea = face1->frontarea;
+ backarea = face1->backarea;
+ faceflags = face1->faceflags;
+ } //end if
+ else
+ {
+ if (frontarea != face1->frontarea) return false;
+ if (backarea != face1->backarea) return false;
+ if (faceflags != face1->faceflags) return false;
+ merge = true;
+ } //end else
+ } //end for
+ return merge;
+} //end of the function AAS_CanMergePlaneFaces
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_MergeAreaPlaneFaces(void)
+{
+ int num_facemerges = 0;
+ int side1;
+ tmp_area_t *tmparea, *nexttmparea;
+ tmp_face_t *face1;
+
+ Log_Write("AAS_MergePlaneFaces\r\n");
+ qprintf("%6d plane face merges", num_facemerges);
+ //NOTE: first convex area is a dummy
+ for (tmparea = tmpaasworld.areas; tmparea; tmparea = nexttmparea)
+ {
+ nexttmparea = tmparea->l_next;
+ //
+ if (tmparea->invalid) continue;
+ //
+ for (face1 = tmparea->tmpfaces; face1; face1 = face1->next[side1])
+ {
+ side1 = face1->frontarea != tmparea;
+ //
+ if (AAS_CanMergePlaneFaces(tmparea, face1->planenum))
+ {
+ AAS_MergePlaneFaces(tmparea, face1->planenum);
+ nexttmparea = tmparea;
+ num_facemerges++;
+ qprintf("\r%6d", num_facemerges);
+ break;
+ } //end if
+ } //end for
+ } //end for
+ qprintf("\n");
+ Log_Write("%6d plane face merges\r\n", num_facemerges);
+} //end of the function AAS_MergeAreaPlaneFaces
diff --git a/code/bspc/aas_facemerging.h b/code/bspc/aas_facemerging.h
new file mode 100755
index 0000000..5a81735
--- /dev/null
+++ b/code/bspc/aas_facemerging.h
@@ -0,0 +1,24 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+void AAS_MergeAreaFaces(void);
+void AAS_MergeAreaPlaneFaces(void);
diff --git a/code/bspc/aas_file.c b/code/bspc/aas_file.c
new file mode 100755
index 0000000..9f41639
--- /dev/null
+++ b/code/bspc/aas_file.c
@@ -0,0 +1,549 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+#include "../botlib/aasfile.h"
+#include "aas_file.h"
+#include "aas_store.h"
+#include "aas_create.h"
+
+#define AAS_Error Error
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_SwapAASData(void)
+{
+ int i, j;
+ //bounding boxes
+ for (i = 0; i < aasworld.numbboxes; i++)
+ {
+ aasworld.bboxes[i].presencetype = LittleLong(aasworld.bboxes[i].presencetype);
+ aasworld.bboxes[i].flags = LittleLong(aasworld.bboxes[i].flags);
+ for (j = 0; j < 3; j++)
+ {
+ aasworld.bboxes[i].mins[j] = LittleLong(aasworld.bboxes[i].mins[j]);
+ aasworld.bboxes[i].maxs[j] = LittleLong(aasworld.bboxes[i].maxs[j]);
+ } //end for
+ } //end for
+ //vertexes
+ for (i = 0; i < aasworld.numvertexes; i++)
+ {
+ for (j = 0; j < 3; j++)
+ aasworld.vertexes[i][j] = LittleFloat(aasworld.vertexes[i][j]);
+ } //end for
+ //planes
+ for (i = 0; i < aasworld.numplanes; i++)
+ {
+ for (j = 0; j < 3; j++)
+ aasworld.planes[i].normal[j] = LittleFloat(aasworld.planes[i].normal[j]);
+ aasworld.planes[i].dist = LittleFloat(aasworld.planes[i].dist);
+ aasworld.planes[i].type = LittleLong(aasworld.planes[i].type);
+ } //end for
+ //edges
+ for (i = 0; i < aasworld.numedges; i++)
+ {
+ aasworld.edges[i].v[0] = LittleLong(aasworld.edges[i].v[0]);
+ aasworld.edges[i].v[1] = LittleLong(aasworld.edges[i].v[1]);
+ } //end for
+ //edgeindex
+ for (i = 0; i < aasworld.edgeindexsize; i++)
+ {
+ aasworld.edgeindex[i] = LittleLong(aasworld.edgeindex[i]);
+ } //end for
+ //faces
+ for (i = 0; i < aasworld.numfaces; i++)
+ {
+ aasworld.faces[i].planenum = LittleLong(aasworld.faces[i].planenum);
+ aasworld.faces[i].faceflags = LittleLong(aasworld.faces[i].faceflags);
+ aasworld.faces[i].numedges = LittleLong(aasworld.faces[i].numedges);
+ aasworld.faces[i].firstedge = LittleLong(aasworld.faces[i].firstedge);
+ aasworld.faces[i].frontarea = LittleLong(aasworld.faces[i].frontarea);
+ aasworld.faces[i].backarea = LittleLong(aasworld.faces[i].backarea);
+ } //end for
+ //face index
+ for (i = 0; i < aasworld.faceindexsize; i++)
+ {
+ aasworld.faceindex[i] = LittleLong(aasworld.faceindex[i]);
+ } //end for
+ //convex areas
+ for (i = 0; i < aasworld.numareas; i++)
+ {
+ aasworld.areas[i].areanum = LittleLong(aasworld.areas[i].areanum);
+ aasworld.areas[i].numfaces = LittleLong(aasworld.areas[i].numfaces);
+ aasworld.areas[i].firstface = LittleLong(aasworld.areas[i].firstface);
+ for (j = 0; j < 3; j++)
+ {
+ aasworld.areas[i].mins[j] = LittleFloat(aasworld.areas[i].mins[j]);
+ aasworld.areas[i].maxs[j] = LittleFloat(aasworld.areas[i].maxs[j]);
+ aasworld.areas[i].center[j] = LittleFloat(aasworld.areas[i].center[j]);
+ } //end for
+ } //end for
+ //area settings
+ for (i = 0; i < aasworld.numareasettings; i++)
+ {
+ aasworld.areasettings[i].contents = LittleLong(aasworld.areasettings[i].contents);
+ aasworld.areasettings[i].areaflags = LittleLong(aasworld.areasettings[i].areaflags);
+ aasworld.areasettings[i].presencetype = LittleLong(aasworld.areasettings[i].presencetype);
+ aasworld.areasettings[i].cluster = LittleLong(aasworld.areasettings[i].cluster);
+ aasworld.areasettings[i].clusterareanum = LittleLong(aasworld.areasettings[i].clusterareanum);
+ aasworld.areasettings[i].numreachableareas = LittleLong(aasworld.areasettings[i].numreachableareas);
+ aasworld.areasettings[i].firstreachablearea = LittleLong(aasworld.areasettings[i].firstreachablearea);
+ } //end for
+ //area reachability
+ for (i = 0; i < aasworld.reachabilitysize; i++)
+ {
+ aasworld.reachability[i].areanum = LittleLong(aasworld.reachability[i].areanum);
+ aasworld.reachability[i].facenum = LittleLong(aasworld.reachability[i].facenum);
+ aasworld.reachability[i].edgenum = LittleLong(aasworld.reachability[i].edgenum);
+ for (j = 0; j < 3; j++)
+ {
+ aasworld.reachability[i].start[j] = LittleFloat(aasworld.reachability[i].start[j]);
+ aasworld.reachability[i].end[j] = LittleFloat(aasworld.reachability[i].end[j]);
+ } //end for
+ aasworld.reachability[i].traveltype = LittleLong(aasworld.reachability[i].traveltype);
+ aasworld.reachability[i].traveltime = LittleShort(aasworld.reachability[i].traveltime);
+ } //end for
+ //nodes
+ for (i = 0; i < aasworld.numnodes; i++)
+ {
+ aasworld.nodes[i].planenum = LittleLong(aasworld.nodes[i].planenum);
+ aasworld.nodes[i].children[0] = LittleLong(aasworld.nodes[i].children[0]);
+ aasworld.nodes[i].children[1] = LittleLong(aasworld.nodes[i].children[1]);
+ } //end for
+ //cluster portals
+ for (i = 0; i < aasworld.numportals; i++)
+ {
+ aasworld.portals[i].areanum = LittleLong(aasworld.portals[i].areanum);
+ aasworld.portals[i].frontcluster = LittleLong(aasworld.portals[i].frontcluster);
+ aasworld.portals[i].backcluster = LittleLong(aasworld.portals[i].backcluster);
+ aasworld.portals[i].clusterareanum[0] = LittleLong(aasworld.portals[i].clusterareanum[0]);
+ aasworld.portals[i].clusterareanum[1] = LittleLong(aasworld.portals[i].clusterareanum[1]);
+ } //end for
+ //cluster portal index
+ for (i = 0; i < aasworld.portalindexsize; i++)
+ {
+ aasworld.portalindex[i] = LittleLong(aasworld.portalindex[i]);
+ } //end for
+ //cluster
+ for (i = 0; i < aasworld.numclusters; i++)
+ {
+ aasworld.clusters[i].numareas = LittleLong(aasworld.clusters[i].numareas);
+ aasworld.clusters[i].numportals = LittleLong(aasworld.clusters[i].numportals);
+ aasworld.clusters[i].firstportal = LittleLong(aasworld.clusters[i].firstportal);
+ } //end for
+} //end of the function AAS_SwapAASData
+//===========================================================================
+// dump the current loaded aas file
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_DumpAASData(void)
+{
+ /*
+ if (aasworld.vertexes) FreeMemory(aasworld.vertexes);
+ aasworld.vertexes = NULL;
+ if (aasworld.planes) FreeMemory(aasworld.planes);
+ aasworld.planes = NULL;
+ if (aasworld.edges) FreeMemory(aasworld.edges);
+ aasworld.edges = NULL;
+ if (aasworld.edgeindex) FreeMemory(aasworld.edgeindex);
+ aasworld.edgeindex = NULL;
+ if (aasworld.faces) FreeMemory(aasworld.faces);
+ aasworld.faces = NULL;
+ if (aasworld.faceindex) FreeMemory(aasworld.faceindex);
+ aasworld.faceindex = NULL;
+ if (aasworld.areas) FreeMemory(aasworld.areas);
+ aasworld.areas = NULL;
+ if (aasworld.areasettings) FreeMemory(aasworld.areasettings);
+ aasworld.areasettings = NULL;
+ if (aasworld.reachability) FreeMemory(aasworld.reachability);
+ aasworld.reachability = NULL;
+ */
+ aasworld.loaded = false;
+} //end of the function AAS_DumpAASData
+//===========================================================================
+// allocate memory and read a lump of a AAS file
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+char *AAS_LoadAASLump(FILE *fp, int offset, int length, void *buf)
+{
+ if (!length)
+ {
+ printf("lump size 0\n");
+ return buf;
+ } //end if
+ //seek to the data
+ if (fseek(fp, offset, SEEK_SET))
+ {
+ AAS_Error("can't seek to lump\n");
+ AAS_DumpAASData();
+ fclose(fp);
+ return 0;
+ } //end if
+ //allocate memory
+ if (!buf) buf = (void *) GetClearedMemory(length);
+ //read the data
+ if (fread((char *) buf, 1, length, fp) != length)
+ {
+ AAS_Error("can't read lump\n");
+ FreeMemory(buf);
+ AAS_DumpAASData();
+ fclose(fp);
+ return NULL;
+ } //end if
+ return buf;
+} //end of the function AAS_LoadAASLump
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_DData(unsigned char *data, int size)
+{
+ int i;
+
+ for (i = 0; i < size; i++)
+ {
+ data[i] ^= (unsigned char) i * 119;
+ } //end for
+} //end of the function AAS_DData
+//===========================================================================
+// load an aas file
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean AAS_LoadAASFile(char *filename, int fpoffset, int fplength)
+{
+ FILE *fp;
+ aas_header_t header;
+ int offset, length;
+
+ //dump current loaded aas file
+ AAS_DumpAASData();
+ //open the file
+ fp = fopen(filename, "rb");
+ if (!fp)
+ {
+ AAS_Error("can't open %s\n", filename);
+ return false;
+ } //end if
+ //seek to the correct position (in the pak file)
+ if (fseek(fp, fpoffset, SEEK_SET))
+ {
+ AAS_Error("can't seek to file %s\n");
+ fclose(fp);
+ return false;
+ } //end if
+ //read the header
+ if (fread(&header, sizeof(aas_header_t), 1, fp) != 1)
+ {
+ AAS_Error("can't read header of file %s\n", filename);
+ fclose(fp);
+ return false;
+ } //end if
+ //check header identification
+ header.ident = LittleLong(header.ident);
+ if (header.ident != AASID)
+ {
+ AAS_Error("%s is not an AAS file\n", filename);
+ fclose(fp);
+ return false;
+ } //end if
+ //check the version
+ header.version = LittleLong(header.version);
+ if (header.version != AASVERSION_OLD && header.version != AASVERSION)
+ {
+ AAS_Error("%s is version %i, not %i\n", filename, header.version, AASVERSION);
+ fclose(fp);
+ return false;
+ } //end if
+ //
+ if (header.version == AASVERSION)
+ {
+ AAS_DData((unsigned char *) &header + 8, sizeof(aas_header_t) - 8);
+ } //end if
+ aasworld.bspchecksum = LittleLong(header.bspchecksum);
+ //load the lumps:
+ //bounding boxes
+ offset = fpoffset + LittleLong(header.lumps[AASLUMP_BBOXES].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_BBOXES].filelen);
+ aasworld.bboxes = (aas_bbox_t *) AAS_LoadAASLump(fp, offset, length, aasworld.bboxes);
+ if (!aasworld.bboxes) return false;
+ aasworld.numbboxes = length / sizeof(aas_bbox_t);
+ //vertexes
+ offset = fpoffset + LittleLong(header.lumps[AASLUMP_VERTEXES].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_VERTEXES].filelen);
+ aasworld.vertexes = (aas_vertex_t *) AAS_LoadAASLump(fp, offset, length, aasworld.vertexes);
+ if (!aasworld.vertexes) return false;
+ aasworld.numvertexes = length / sizeof(aas_vertex_t);
+ //planes
+ offset = fpoffset + LittleLong(header.lumps[AASLUMP_PLANES].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_PLANES].filelen);
+ aasworld.planes = (aas_plane_t *) AAS_LoadAASLump(fp, offset, length, aasworld.planes);
+ if (!aasworld.planes) return false;
+ aasworld.numplanes = length / sizeof(aas_plane_t);
+ //edges
+ offset = fpoffset + LittleLong(header.lumps[AASLUMP_EDGES].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_EDGES].filelen);
+ aasworld.edges = (aas_edge_t *) AAS_LoadAASLump(fp, offset, length, aasworld.edges);
+ if (!aasworld.edges) return false;
+ aasworld.numedges = length / sizeof(aas_edge_t);
+ //edgeindex
+ offset = fpoffset + LittleLong(header.lumps[AASLUMP_EDGEINDEX].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_EDGEINDEX].filelen);
+ aasworld.edgeindex = (aas_edgeindex_t *) AAS_LoadAASLump(fp, offset, length, aasworld.edgeindex);
+ if (!aasworld.edgeindex) return false;
+ aasworld.edgeindexsize = length / sizeof(aas_edgeindex_t);
+ //faces
+ offset = fpoffset + LittleLong(header.lumps[AASLUMP_FACES].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_FACES].filelen);
+ aasworld.faces = (aas_face_t *) AAS_LoadAASLump(fp, offset, length, aasworld.faces);
+ if (!aasworld.faces) return false;
+ aasworld.numfaces = length / sizeof(aas_face_t);
+ //faceindex
+ offset = fpoffset + LittleLong(header.lumps[AASLUMP_FACEINDEX].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_FACEINDEX].filelen);
+ aasworld.faceindex = (aas_faceindex_t *) AAS_LoadAASLump(fp, offset, length, aasworld.faceindex);
+ if (!aasworld.faceindex) return false;
+ aasworld.faceindexsize = length / sizeof(int);
+ //convex areas
+ offset = fpoffset + LittleLong(header.lumps[AASLUMP_AREAS].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_AREAS].filelen);
+ aasworld.areas = (aas_area_t *) AAS_LoadAASLump(fp, offset, length, aasworld.areas);
+ if (!aasworld.areas) return false;
+ aasworld.numareas = length / sizeof(aas_area_t);
+ //area settings
+ offset = fpoffset + LittleLong(header.lumps[AASLUMP_AREASETTINGS].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_AREASETTINGS].filelen);
+ aasworld.areasettings = (aas_areasettings_t *) AAS_LoadAASLump(fp, offset, length, aasworld.areasettings);
+ if (!aasworld.areasettings) return false;
+ aasworld.numareasettings = length / sizeof(aas_areasettings_t);
+ //reachability list
+ offset = fpoffset + LittleLong(header.lumps[AASLUMP_REACHABILITY].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_REACHABILITY].filelen);
+ aasworld.reachability = (aas_reachability_t *) AAS_LoadAASLump(fp, offset, length, aasworld.reachability);
+ if (length && !aasworld.reachability) return false;
+ aasworld.reachabilitysize = length / sizeof(aas_reachability_t);
+ //nodes
+ offset = fpoffset + LittleLong(header.lumps[AASLUMP_NODES].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_NODES].filelen);
+ aasworld.nodes = (aas_node_t *) AAS_LoadAASLump(fp, offset, length, aasworld.nodes);
+ if (!aasworld.nodes) return false;
+ aasworld.numnodes = length / sizeof(aas_node_t);
+ //cluster portals
+ offset = fpoffset + LittleLong(header.lumps[AASLUMP_PORTALS].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_PORTALS].filelen);
+ aasworld.portals = (aas_portal_t *) AAS_LoadAASLump(fp, offset, length, aasworld.portals);
+ if (length && !aasworld.portals) return false;
+ aasworld.numportals = length / sizeof(aas_portal_t);
+ //cluster portal index
+ offset = fpoffset + LittleLong(header.lumps[AASLUMP_PORTALINDEX].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_PORTALINDEX].filelen);
+ aasworld.portalindex = (aas_portalindex_t *) AAS_LoadAASLump(fp, offset, length, aasworld.portalindex);
+ if (length && !aasworld.portalindex) return false;
+ aasworld.portalindexsize = length / sizeof(aas_portalindex_t);
+ //clusters
+ offset = fpoffset + LittleLong(header.lumps[AASLUMP_CLUSTERS].fileofs);
+ length = LittleLong(header.lumps[AASLUMP_CLUSTERS].filelen);
+ aasworld.clusters = (aas_cluster_t *) AAS_LoadAASLump(fp, offset, length, aasworld.clusters);
+ if (length && !aasworld.clusters) return false;
+ aasworld.numclusters = length / sizeof(aas_cluster_t);
+ //swap everything
+ AAS_SwapAASData();
+ //aas file is loaded
+ aasworld.loaded = true;
+ //close the file
+ fclose(fp);
+ return true;
+} //end of the function AAS_LoadAASFile
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_WriteAASLump(FILE *fp, aas_header_t *h, int lumpnum, void *data, int length)
+{
+ aas_lump_t *lump;
+
+ lump = &h->lumps[lumpnum];
+
+ lump->fileofs = LittleLong(ftell(fp));
+ lump->filelen = LittleLong(length);
+
+ if (length > 0)
+ {
+ if (fwrite(data, length, 1, fp) < 1)
+ {
+ Log_Print("error writing lump %s\n", lumpnum);
+ fclose(fp);
+ return false;
+ } //end if
+ } //end if
+ return true;
+} //end of the function AAS_WriteAASLump
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ShowNumReachabilities(int tt, char *name)
+{
+ int i, num;
+
+ num = 0;
+ for (i = 0; i < aasworld.reachabilitysize; i++)
+ {
+ if ((aasworld.reachability[i].traveltype & TRAVELTYPE_MASK) == tt)
+ num++;
+ } //end for
+ Log_Print("%6d %s\n", num, name);
+} //end of the function AAS_ShowNumReachabilities
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ShowTotals(void)
+{
+ Log_Print("numvertexes = %d\r\n", aasworld.numvertexes);
+ Log_Print("numplanes = %d\r\n", aasworld.numplanes);
+ Log_Print("numedges = %d\r\n", aasworld.numedges);
+ Log_Print("edgeindexsize = %d\r\n", aasworld.edgeindexsize);
+ Log_Print("numfaces = %d\r\n", aasworld.numfaces);
+ Log_Print("faceindexsize = %d\r\n", aasworld.faceindexsize);
+ Log_Print("numareas = %d\r\n", aasworld.numareas);
+ Log_Print("numareasettings = %d\r\n", aasworld.numareasettings);
+ Log_Print("reachabilitysize = %d\r\n", aasworld.reachabilitysize);
+ Log_Print("numnodes = %d\r\n", aasworld.numnodes);
+ Log_Print("numportals = %d\r\n", aasworld.numportals);
+ Log_Print("portalindexsize = %d\r\n", aasworld.portalindexsize);
+ Log_Print("numclusters = %d\r\n", aasworld.numclusters);
+ AAS_ShowNumReachabilities(TRAVEL_WALK, "walk");
+ AAS_ShowNumReachabilities(TRAVEL_CROUCH, "crouch");
+ AAS_ShowNumReachabilities(TRAVEL_BARRIERJUMP, "barrier jump");
+ AAS_ShowNumReachabilities(TRAVEL_JUMP, "jump");
+ AAS_ShowNumReachabilities(TRAVEL_LADDER, "ladder");
+ AAS_ShowNumReachabilities(TRAVEL_WALKOFFLEDGE, "walk off ledge");
+ AAS_ShowNumReachabilities(TRAVEL_SWIM, "swim");
+ AAS_ShowNumReachabilities(TRAVEL_WATERJUMP, "water jump");
+ AAS_ShowNumReachabilities(TRAVEL_TELEPORT, "teleport");
+ AAS_ShowNumReachabilities(TRAVEL_ELEVATOR, "elevator");
+ AAS_ShowNumReachabilities(TRAVEL_ROCKETJUMP, "rocket jump");
+ AAS_ShowNumReachabilities(TRAVEL_BFGJUMP, "bfg jump");
+ AAS_ShowNumReachabilities(TRAVEL_GRAPPLEHOOK, "grapple hook");
+ AAS_ShowNumReachabilities(TRAVEL_DOUBLEJUMP, "double jump");
+ AAS_ShowNumReachabilities(TRAVEL_RAMPJUMP, "ramp jump");
+ AAS_ShowNumReachabilities(TRAVEL_STRAFEJUMP, "strafe jump");
+ AAS_ShowNumReachabilities(TRAVEL_JUMPPAD, "jump pad");
+ AAS_ShowNumReachabilities(TRAVEL_FUNCBOB, "func bob");
+} //end of the function AAS_ShowTotals
+//===========================================================================
+// aas data is useless after writing to file because it is byte swapped
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean AAS_WriteAASFile(char *filename)
+{
+ aas_header_t header;
+ FILE *fp;
+
+ Log_Print("writing %s\n", filename);
+ AAS_ShowTotals();
+ //swap the aas data
+ AAS_SwapAASData();
+ //initialize the file header
+ memset(&header, 0, sizeof(aas_header_t));
+ header.ident = LittleLong(AASID);
+ header.version = LittleLong(AASVERSION);
+ header.bspchecksum = LittleLong(aasworld.bspchecksum);
+ //open a new file
+ fp = fopen(filename, "wb");
+ if (!fp)
+ {
+ Log_Print("error opening %s\n", filename);
+ return false;
+ } //end if
+ //write the header
+ if (fwrite(&header, sizeof(aas_header_t), 1, fp) < 1)
+ {
+ fclose(fp);
+ return false;
+ } //end if
+ //add the data lumps to the file
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_BBOXES, aasworld.bboxes,
+ aasworld.numbboxes * sizeof(aas_bbox_t))) return false;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_VERTEXES, aasworld.vertexes,
+ aasworld.numvertexes * sizeof(aas_vertex_t))) return false;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_PLANES, aasworld.planes,
+ aasworld.numplanes * sizeof(aas_plane_t))) return false;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_EDGES, aasworld.edges,
+ aasworld.numedges * sizeof(aas_edge_t))) return false;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_EDGEINDEX, aasworld.edgeindex,
+ aasworld.edgeindexsize * sizeof(aas_edgeindex_t))) return false;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_FACES, aasworld.faces,
+ aasworld.numfaces * sizeof(aas_face_t))) return false;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_FACEINDEX, aasworld.faceindex,
+ aasworld.faceindexsize * sizeof(aas_faceindex_t))) return false;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_AREAS, aasworld.areas,
+ aasworld.numareas * sizeof(aas_area_t))) return false;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_AREASETTINGS, aasworld.areasettings,
+ aasworld.numareasettings * sizeof(aas_areasettings_t))) return false;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_REACHABILITY, aasworld.reachability,
+ aasworld.reachabilitysize * sizeof(aas_reachability_t))) return false;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_NODES, aasworld.nodes,
+ aasworld.numnodes * sizeof(aas_node_t))) return false;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_PORTALS, aasworld.portals,
+ aasworld.numportals * sizeof(aas_portal_t))) return false;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_PORTALINDEX, aasworld.portalindex,
+ aasworld.portalindexsize * sizeof(aas_portalindex_t))) return false;
+ if (!AAS_WriteAASLump(fp, &header, AASLUMP_CLUSTERS, aasworld.clusters,
+ aasworld.numclusters * sizeof(aas_cluster_t))) return false;
+ //rewrite the header with the added lumps
+ fseek(fp, 0, SEEK_SET);
+ AAS_DData((unsigned char *) &header + 8, sizeof(aas_header_t) - 8);
+ if (fwrite(&header, sizeof(aas_header_t), 1, fp) < 1)
+ {
+ fclose(fp);
+ return false;
+ } //end if
+ //close the file
+ fclose(fp);
+ return true;
+} //end of the function AAS_WriteAASFile
+
diff --git a/code/bspc/aas_file.h b/code/bspc/aas_file.h
new file mode 100755
index 0000000..5176461
--- /dev/null
+++ b/code/bspc/aas_file.h
@@ -0,0 +1,25 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+qboolean AAS_WriteAASFile(char *filename);
+qboolean AAS_LoadAASFile(char *filename, int fpoffset, int fplength);
+
diff --git a/code/bspc/aas_gsubdiv.c b/code/bspc/aas_gsubdiv.c
new file mode 100755
index 0000000..d9ba597
--- /dev/null
+++ b/code/bspc/aas_gsubdiv.c
@@ -0,0 +1,656 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+#include "../botlib/aasfile.h"
+#include "aas_create.h"
+#include "aas_store.h"
+#include "aas_cfg.h"
+
+#define FACECLIP_EPSILON 0.2
+#define FACE_EPSILON 1.0
+
+int numgravitationalsubdivisions = 0;
+int numladdersubdivisions = 0;
+
+//NOTE: only do gravitational subdivision BEFORE area merging!!!!!!!
+// because the bsp tree isn't refreshes like with ladder subdivision
+
+//===========================================================================
+// NOTE: the original face is invalid after splitting
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_SplitFace(tmp_face_t *face, vec3_t normal, float dist,
+ tmp_face_t **frontface, tmp_face_t **backface)
+{
+ winding_t *frontw, *backw;
+
+ //
+ *frontface = *backface = NULL;
+
+ ClipWindingEpsilon(face->winding, normal, dist, FACECLIP_EPSILON, &frontw, &backw);
+
+#ifdef DEBUG
+ //
+ if (frontw)
+ {
+ if (WindingIsTiny(frontw))
+ {
+ Log_Write("AAS_SplitFace: tiny back face\r\n");
+ FreeWinding(frontw);
+ frontw = NULL;
+ } //end if
+ } //end if
+ if (backw)
+ {
+ if (WindingIsTiny(backw))
+ {
+ Log_Write("AAS_SplitFace: tiny back face\r\n");
+ FreeWinding(backw);
+ backw = NULL;
+ } //end if
+ } //end if
+#endif //DEBUG
+ //if the winding was split
+ if (frontw)
+ {
+ //check bounds
+ (*frontface) = AAS_AllocTmpFace();
+ (*frontface)->planenum = face->planenum;
+ (*frontface)->winding = frontw;
+ (*frontface)->faceflags = face->faceflags;
+ } //end if
+ if (backw)
+ {
+ //check bounds
+ (*backface) = AAS_AllocTmpFace();
+ (*backface)->planenum = face->planenum;
+ (*backface)->winding = backw;
+ (*backface)->faceflags = face->faceflags;
+ } //end if
+} //end of the function AAS_SplitFace
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+winding_t *AAS_SplitWinding(tmp_area_t *tmparea, int planenum)
+{
+ tmp_face_t *face;
+ plane_t *plane;
+ int side;
+ winding_t *splitwinding;
+
+ //
+ plane = &mapplanes[planenum];
+ //create a split winding, first base winding for plane
+ splitwinding = BaseWindingForPlane(plane->normal, plane->dist);
+ //chop with all the faces of the area
+ for (face = tmparea->tmpfaces; face && splitwinding; face = face->next[side])
+ {
+ //side of the face the original area was on
+ side = face->frontarea != tmparea;
+ plane = &mapplanes[face->planenum ^ side];
+ ChopWindingInPlace(&splitwinding, plane->normal, plane->dist, 0); // PLANESIDE_EPSILON);
+ } //end for
+ return splitwinding;
+} //end of the function AAS_SplitWinding
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_TestSplitPlane(tmp_area_t *tmparea, vec3_t normal, float dist,
+ int *facesplits, int *groundsplits, int *epsilonfaces)
+{
+ int j, side, front, back, planenum;
+ float d, d_front, d_back;
+ tmp_face_t *face;
+ winding_t *w;
+
+ *facesplits = *groundsplits = *epsilonfaces = 0;
+
+ planenum = FindFloatPlane(normal, dist);
+
+ w = AAS_SplitWinding(tmparea, planenum);
+ if (!w) return false;
+ FreeWinding(w);
+ //
+ for (face = tmparea->tmpfaces; face; face = face->next[side])
+ {
+ //side of the face the area is on
+ side = face->frontarea != tmparea;
+
+ if ((face->planenum & ~1) == (planenum & ~1))
+ {
+ Log_Print("AAS_TestSplitPlane: tried face plane as splitter\n");
+ return false;
+ } //end if
+ w = face->winding;
+ //reset distance at front and back side of plane
+ d_front = d_back = 0;
+ //reset front and back flags
+ front = back = 0;
+ for (j = 0; j < w->numpoints; j++)
+ {
+ d = DotProduct(w->p[j], normal) - dist;
+ if (d > d_front) d_front = d;
+ if (d < d_back) d_back = d;
+
+ if (d > 0.4) // PLANESIDE_EPSILON)
+ front = 1;
+ if (d < -0.4) // PLANESIDE_EPSILON)
+ back = 1;
+ } //end for
+ //check for an epsilon face
+ if ( (d_front > FACECLIP_EPSILON && d_front < FACE_EPSILON)
+ || (d_back < -FACECLIP_EPSILON && d_back > -FACE_EPSILON) )
+ {
+ (*epsilonfaces)++;
+ } //end if
+ //if the face has points at both sides of the plane
+ if (front && back)
+ {
+ (*facesplits)++;
+ if (face->faceflags & FACE_GROUND)
+ {
+ (*groundsplits)++;
+ } //end if
+ } //end if
+ } //end for
+ return true;
+} //end of the function AAS_TestSplitPlane
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_SplitArea(tmp_area_t *tmparea, int planenum, tmp_area_t **frontarea, tmp_area_t **backarea)
+{
+ int side;
+ tmp_area_t *facefrontarea, *facebackarea, *faceotherarea;
+ tmp_face_t *face, *frontface, *backface, *splitface, *nextface;
+ winding_t *splitwinding;
+ plane_t *splitplane;
+
+/*
+#ifdef AW_DEBUG
+ int facesplits, groundsplits, epsilonface;
+ Log_Print("\n----------------------\n");
+ Log_Print("splitting area %d\n", areanum);
+ Log_Print("with normal = \'%f %f %f\', dist = %f\n", normal[0], normal[1], normal[2], dist);
+ AAS_TestSplitPlane(areanum, normal, dist,
+ &facesplits, &groundsplits, &epsilonface);
+ Log_Print("face splits = %d\nground splits = %d\n", facesplits, groundsplits);
+ if (epsilonface) Log_Print("aaahh epsilon face\n");
+#endif //AW_DEBUG*/
+ //the original area
+
+ AAS_FlipAreaFaces(tmparea);
+ AAS_CheckArea(tmparea);
+ //
+ splitplane = &mapplanes[planenum];
+/* //create a split winding, first base winding for plane
+ splitwinding = BaseWindingForPlane(splitplane->normal, splitplane->dist);
+ //chop with all the faces of the area
+ for (face = tmparea->tmpfaces; face && splitwinding; face = face->next[side])
+ {
+ //side of the face the original area was on
+ side = face->frontarea != tmparea->areanum;
+ plane = &mapplanes[face->planenum ^ side];
+ ChopWindingInPlace(&splitwinding, plane->normal, plane->dist, 0); // PLANESIDE_EPSILON);
+ } //end for*/
+ splitwinding = AAS_SplitWinding(tmparea, planenum);
+ if (!splitwinding)
+ {
+/*
+#ifdef DEBUG
+ AAS_TestSplitPlane(areanum, normal, dist,
+ &facesplits, &groundsplits, &epsilonface);
+ Log_Print("\nface splits = %d\nground splits = %d\n", facesplits, groundsplits);
+ if (epsilonface) Log_Print("aaahh epsilon face\n");
+#endif //DEBUG*/
+ Error("AAS_SplitArea: no split winding when splitting area %d\n", tmparea->areanum);
+ } //end if
+ //create a split face
+ splitface = AAS_AllocTmpFace();
+ //get the map plane
+ splitface->planenum = planenum;
+ //store the split winding
+ splitface->winding = splitwinding;
+ //the new front area
+ (*frontarea) = AAS_AllocTmpArea();
+ (*frontarea)->presencetype = tmparea->presencetype;
+ (*frontarea)->contents = tmparea->contents;
+ (*frontarea)->modelnum = tmparea->modelnum;
+ (*frontarea)->tmpfaces = NULL;
+ //the new back area
+ (*backarea) = AAS_AllocTmpArea();
+ (*backarea)->presencetype = tmparea->presencetype;
+ (*backarea)->contents = tmparea->contents;
+ (*backarea)->modelnum = tmparea->modelnum;
+ (*backarea)->tmpfaces = NULL;
+ //add the split face to the new areas
+ AAS_AddFaceSideToArea(splitface, 0, (*frontarea));
+ AAS_AddFaceSideToArea(splitface, 1, (*backarea));
+
+ //split all the faces of the original area
+ for (face = tmparea->tmpfaces; face; face = nextface)
+ {
+ //side of the face the original area was on
+ side = face->frontarea != tmparea;
+ //next face of the original area
+ nextface = face->next[side];
+ //front area of the face
+ facefrontarea = face->frontarea;
+ //back area of the face
+ facebackarea = face->backarea;
+ //remove the face from both the front and back areas
+ if (facefrontarea) AAS_RemoveFaceFromArea(face, facefrontarea);
+ if (facebackarea) AAS_RemoveFaceFromArea(face, facebackarea);
+ //split the face
+ AAS_SplitFace(face, splitplane->normal, splitplane->dist, &frontface, &backface);
+ //free the original face
+ AAS_FreeTmpFace(face);
+ //get the number of the area at the other side of the face
+ if (side) faceotherarea = facefrontarea;
+ else faceotherarea = facebackarea;
+ //if there is an area at the other side of the original face
+ if (faceotherarea)
+ {
+ if (frontface) AAS_AddFaceSideToArea(frontface, !side, faceotherarea);
+ if (backface) AAS_AddFaceSideToArea(backface, !side, faceotherarea);
+ } //end if
+ //add the front and back part left after splitting the original face to the new areas
+ if (frontface) AAS_AddFaceSideToArea(frontface, side, (*frontarea));
+ if (backface) AAS_AddFaceSideToArea(backface, side, (*backarea));
+ } //end for
+
+ if (!(*frontarea)->tmpfaces) Log_Print("AAS_SplitArea: front area without faces\n");
+ if (!(*backarea)->tmpfaces) Log_Print("AAS_SplitArea: back area without faces\n");
+
+ tmparea->invalid = true;
+/*
+#ifdef AW_DEBUG
+ for (i = 0, face = frontarea->tmpfaces; face; face = face->next[side])
+ {
+ side = face->frontarea != frontarea->areanum;
+ i++;
+ } //end for
+ Log_Print("created front area %d with %d faces\n", frontarea->areanum, i);
+
+ for (i = 0, face = backarea->tmpfaces; face; face = face->next[side])
+ {
+ side = face->frontarea != backarea->areanum;
+ i++;
+ } //end for
+ Log_Print("created back area %d with %d faces\n", backarea->areanum, i);
+#endif //AW_DEBUG*/
+
+ AAS_FlipAreaFaces((*frontarea));
+ AAS_FlipAreaFaces((*backarea));
+ //
+ AAS_CheckArea((*frontarea));
+ AAS_CheckArea((*backarea));
+} //end of the function AAS_SplitArea
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_FindBestAreaSplitPlane(tmp_area_t *tmparea, vec3_t normal, float *dist)
+{
+ int side1, side2;
+ int foundsplitter, facesplits, groundsplits, epsilonfaces, bestepsilonfaces;
+ float bestvalue, value;
+ tmp_face_t *face1, *face2;
+ vec3_t tmpnormal, invgravity;
+ float tmpdist;
+
+ //get inverse of gravity direction
+ VectorCopy(cfg.phys_gravitydirection, invgravity);
+ VectorInverse(invgravity);
+
+ foundsplitter = false;
+ bestvalue = -999999;
+ bestepsilonfaces = 0;
+ //
+#ifdef AW_DEBUG
+ Log_Print("finding split plane for area %d\n", tmparea->areanum);
+#endif //AW_DEBUG
+ for (face1 = tmparea->tmpfaces; face1; face1 = face1->next[side1])
+ {
+ //side of the face the area is on
+ side1 = face1->frontarea != tmparea;
+ //
+ if (WindingIsTiny(face1->winding))
+ {
+ Log_Write("gsubdiv: area %d has a tiny winding\r\n", tmparea->areanum);
+ continue;
+ } //end if
+ //if the face isn't a gap or ground there's no split edge
+ if (!(face1->faceflags & FACE_GROUND) && !AAS_GapFace(face1, side1)) continue;
+ //
+ for (face2 = face1->next[side1]; face2; face2 = face2->next[side2])
+ {
+ //side of the face the area is on
+ side2 = face2->frontarea != tmparea;
+ //
+ if (WindingIsTiny(face1->winding))
+ {
+ Log_Write("gsubdiv: area %d has a tiny winding\r\n", tmparea->areanum);
+ continue;
+ } //end if
+ //if the face isn't a gap or ground there's no split edge
+ if (!(face2->faceflags & FACE_GROUND) && !AAS_GapFace(face2, side2)) continue;
+ //only split between gaps and ground
+ if (!(((face1->faceflags & FACE_GROUND) && AAS_GapFace(face2, side2)) ||
+ ((face2->faceflags & FACE_GROUND) && AAS_GapFace(face1, side1)))) continue;
+ //find a plane seperating the windings of the faces
+ if (!FindPlaneSeperatingWindings(face1->winding, face2->winding, invgravity,
+ tmpnormal, &tmpdist)) continue;
+#ifdef AW_DEBUG
+ Log_Print("normal = \'%f %f %f\', dist = %f\n",
+ tmpnormal[0], tmpnormal[1], tmpnormal[2], tmpdist);
+#endif //AW_DEBUG
+ //get metrics for this vertical plane
+ if (!AAS_TestSplitPlane(tmparea, tmpnormal, tmpdist,
+ &facesplits, &groundsplits, &epsilonfaces))
+ {
+ continue;
+ } //end if
+#ifdef AW_DEBUG
+ Log_Print("face splits = %d\nground splits = %d\n",
+ facesplits, groundsplits);
+#endif //AW_DEBUG
+ value = 100 - facesplits - 2 * groundsplits;
+ //avoid epsilon faces
+ value += epsilonfaces * -1000;
+ if (value > bestvalue)
+ {
+ VectorCopy(tmpnormal, normal);
+ *dist = tmpdist;
+ bestvalue = value;
+ bestepsilonfaces = epsilonfaces;
+ foundsplitter = true;
+ } //end if
+ } //end for
+ } //end for
+ if (bestepsilonfaces)
+ {
+ Log_Write("found %d epsilon faces trying to split area %d\r\n",
+ epsilonfaces, tmparea->areanum);
+ } //end else
+ return foundsplitter;
+} //end of the function AAS_FindBestAreaSplitPlane
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+tmp_node_t *AAS_SubdivideArea_r(tmp_node_t *tmpnode)
+{
+ int planenum;
+ tmp_area_t *frontarea, *backarea;
+ tmp_node_t *tmpnode1, *tmpnode2;
+ vec3_t normal;
+ float dist;
+
+ if (AAS_FindBestAreaSplitPlane(tmpnode->tmparea, normal, &dist))
+ {
+ qprintf("\r%6d", ++numgravitationalsubdivisions);
+ //
+ planenum = FindFloatPlane(normal, dist);
+ //split the area
+ AAS_SplitArea(tmpnode->tmparea, planenum, &frontarea, &backarea);
+ //
+ tmpnode->tmparea = NULL;
+ tmpnode->planenum = FindFloatPlane(normal, dist);
+ //
+ tmpnode1 = AAS_AllocTmpNode();
+ tmpnode1->planenum = 0;
+ tmpnode1->tmparea = frontarea;
+ //
+ tmpnode2 = AAS_AllocTmpNode();
+ tmpnode2->planenum = 0;
+ tmpnode2->tmparea = backarea;
+ //subdivide the areas created by splitting recursively
+ tmpnode->children[0] = AAS_SubdivideArea_r(tmpnode1);
+ tmpnode->children[1] = AAS_SubdivideArea_r(tmpnode2);
+ } //end if
+ return tmpnode;
+} //end of the function AAS_SubdivideArea_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+tmp_node_t *AAS_GravitationalSubdivision_r(tmp_node_t *tmpnode)
+{
+ //if this is a solid leaf
+ if (!tmpnode) return NULL;
+ //negative so it's an area
+ if (tmpnode->tmparea) return AAS_SubdivideArea_r(tmpnode);
+ //do the children recursively
+ tmpnode->children[0] = AAS_GravitationalSubdivision_r(tmpnode->children[0]);
+ tmpnode->children[1] = AAS_GravitationalSubdivision_r(tmpnode->children[1]);
+ return tmpnode;
+} //end of the function AAS_GravitationalSubdivision_r
+//===========================================================================
+// NOTE: merge faces and melt edges first
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_GravitationalSubdivision(void)
+{
+ Log_Write("AAS_GravitationalSubdivision\r\n");
+ numgravitationalsubdivisions = 0;
+ qprintf("%6i gravitational subdivisions", numgravitationalsubdivisions);
+ //start with the head node
+ AAS_GravitationalSubdivision_r(tmpaasworld.nodes);
+ qprintf("\n");
+ Log_Write("%6i gravitational subdivisions\r\n", numgravitationalsubdivisions);
+} //end of the function AAS_GravitationalSubdivision
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+tmp_node_t *AAS_RefreshLadderSubdividedTree_r(tmp_node_t *tmpnode, tmp_area_t *tmparea,
+ tmp_node_t *tmpnode1, tmp_node_t *tmpnode2, int planenum)
+{
+ //if this is a solid leaf
+ if (!tmpnode) return NULL;
+ //negative so it's an area
+ if (tmpnode->tmparea)
+ {
+ if (tmpnode->tmparea == tmparea)
+ {
+ tmpnode->tmparea = NULL;
+ tmpnode->planenum = planenum;
+ tmpnode->children[0] = tmpnode1;
+ tmpnode->children[1] = tmpnode2;
+ } //end if
+ return tmpnode;
+ } //end if
+ //do the children recursively
+ tmpnode->children[0] = AAS_RefreshLadderSubdividedTree_r(tmpnode->children[0],
+ tmparea, tmpnode1, tmpnode2, planenum);
+ tmpnode->children[1] = AAS_RefreshLadderSubdividedTree_r(tmpnode->children[1],
+ tmparea, tmpnode1, tmpnode2, planenum);
+ return tmpnode;
+} //end of the function AAS_RefreshLadderSubdividedTree_r
+//===========================================================================
+// find an area with ladder faces and ground faces that are not connected
+// split the area with a horizontal plane at the lowest vertex of all
+// ladder faces in the area
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+tmp_node_t *AAS_LadderSubdivideArea_r(tmp_node_t *tmpnode)
+{
+ int side1, i, planenum;
+ int foundladderface, foundgroundface;
+ float dist;
+ tmp_area_t *tmparea, *frontarea, *backarea;
+ tmp_face_t *face1;
+ tmp_node_t *tmpnode1, *tmpnode2;
+ vec3_t lowestpoint, normal = {0, 0, 1};
+ plane_t *plane;
+ winding_t *w;
+
+ tmparea = tmpnode->tmparea;
+ //skip areas with a liquid
+ if (tmparea->contents & (AREACONTENTS_WATER
+ | AREACONTENTS_LAVA
+ | AREACONTENTS_SLIME)) return tmpnode;
+ //must be possible to stand in the area
+ if (!(tmparea->presencetype & PRESENCE_NORMAL)) return tmpnode;
+ //
+ foundladderface = false;
+ foundgroundface = false;
+ lowestpoint[2] = 99999;
+ //
+ for (face1 = tmparea->tmpfaces; face1; face1 = face1->next[side1])
+ {
+ //side of the face the area is on
+ side1 = face1->frontarea != tmparea;
+ //if the face is a ladder face
+ if (face1->faceflags & FACE_LADDER)
+ {
+ plane = &mapplanes[face1->planenum];
+ //the ladder face plane should be pretty much vertical
+ if (DotProduct(plane->normal, normal) > -0.1)
+ {
+ foundladderface = true;
+ //find lowest point
+ for (i = 0; i < face1->winding->numpoints; i++)
+ {
+ if (face1->winding->p[i][2] < lowestpoint[2])
+ {
+ VectorCopy(face1->winding->p[i], lowestpoint);
+ } //end if
+ } //end for
+ } //end if
+ } //end if
+ else if (face1->faceflags & FACE_GROUND)
+ {
+ foundgroundface = true;
+ } //end else if
+ } //end for
+ //
+ if ((!foundladderface) || (!foundgroundface)) return tmpnode;
+ //
+ for (face1 = tmparea->tmpfaces; face1; face1 = face1->next[side1])
+ {
+ //side of the face the area is on
+ side1 = face1->frontarea != tmparea;
+ //if the face isn't a ground face
+ if (!(face1->faceflags & FACE_GROUND)) continue;
+ //the ground plane
+ plane = &mapplanes[face1->planenum];
+ //get the difference between the ground plane and the lowest point
+ dist = DotProduct(plane->normal, lowestpoint) - plane->dist;
+ //if the lowest point is very near one of the ground planes
+ if (dist > -1 && dist < 1)
+ {
+ return tmpnode;
+ } //end if
+ } //end for
+ //
+ dist = DotProduct(normal, lowestpoint);
+ planenum = FindFloatPlane(normal, dist);
+ //
+ w = AAS_SplitWinding(tmparea, planenum);
+ if (!w) return tmpnode;
+ FreeWinding(w);
+ //split the area with a horizontal plane through the lowest point
+ qprintf("\r%6d", ++numladdersubdivisions);
+ //
+ AAS_SplitArea(tmparea, planenum, &frontarea, &backarea);
+ //
+ tmpnode->tmparea = NULL;
+ tmpnode->planenum = planenum;
+ //
+ tmpnode1 = AAS_AllocTmpNode();
+ tmpnode1->planenum = 0;
+ tmpnode1->tmparea = frontarea;
+ //
+ tmpnode2 = AAS_AllocTmpNode();
+ tmpnode2->planenum = 0;
+ tmpnode2->tmparea = backarea;
+ //subdivide the areas created by splitting recursively
+ tmpnode->children[0] = AAS_LadderSubdivideArea_r(tmpnode1);
+ tmpnode->children[1] = AAS_LadderSubdivideArea_r(tmpnode2);
+ //refresh the tree
+ AAS_RefreshLadderSubdividedTree_r(tmpaasworld.nodes, tmparea, tmpnode1, tmpnode2, planenum);
+ //
+ return tmpnode;
+} //end of the function AAS_LadderSubdivideArea_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+tmp_node_t *AAS_LadderSubdivision_r(tmp_node_t *tmpnode)
+{
+ //if this is a solid leaf
+ if (!tmpnode) return 0;
+ //negative so it's an area
+ if (tmpnode->tmparea) return AAS_LadderSubdivideArea_r(tmpnode);
+ //do the children recursively
+ tmpnode->children[0] = AAS_LadderSubdivision_r(tmpnode->children[0]);
+ tmpnode->children[1] = AAS_LadderSubdivision_r(tmpnode->children[1]);
+ return tmpnode;
+} //end of the function AAS_LadderSubdivision_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_LadderSubdivision(void)
+{
+ Log_Write("AAS_LadderSubdivision\r\n");
+ numladdersubdivisions = 0;
+ qprintf("%6i ladder subdivisions", numladdersubdivisions);
+ //start with the head node
+ AAS_LadderSubdivision_r(tmpaasworld.nodes);
+ //
+ qprintf("\n");
+ Log_Write("%6i ladder subdivisions\r\n", numladdersubdivisions);
+} //end of the function AAS_LadderSubdivision
diff --git a/code/bspc/aas_gsubdiv.h b/code/bspc/aas_gsubdiv.h
new file mode 100755
index 0000000..0156a9a
--- /dev/null
+++ b/code/bspc/aas_gsubdiv.h
@@ -0,0 +1,25 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+//works with the global tmpaasworld
+void AAS_GravitationalSubdivision(void);
+void AAS_LadderSubdivision(void);
diff --git a/code/bspc/aas_map.c b/code/bspc/aas_map.c
new file mode 100755
index 0000000..da16d1b
--- /dev/null
+++ b/code/bspc/aas_map.c
@@ -0,0 +1,849 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+#include "l_mem.h"
+#include "../botlib/aasfile.h" //aas_bbox_t
+#include "aas_store.h" //AAS_MAX_BBOXES
+#include "aas_cfg.h"
+#include "../game/surfaceflags.h"
+
+#define SPAWNFLAG_NOT_EASY 0x00000100
+#define SPAWNFLAG_NOT_MEDIUM 0x00000200
+#define SPAWNFLAG_NOT_HARD 0x00000400
+#define SPAWNFLAG_NOT_DEATHMATCH 0x00000800
+#define SPAWNFLAG_NOT_COOP 0x00001000
+
+#define STATE_TOP 0
+#define STATE_BOTTOM 1
+#define STATE_UP 2
+#define STATE_DOWN 3
+
+#define DOOR_START_OPEN 1
+#define DOOR_REVERSE 2
+#define DOOR_CRUSHER 4
+#define DOOR_NOMONSTER 8
+#define DOOR_TOGGLE 32
+#define DOOR_X_AXIS 64
+#define DOOR_Y_AXIS 128
+
+#define BBOX_NORMAL_EPSILON 0.0001
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+vec_t BoxOriginDistanceFromPlane(vec3_t normal, vec3_t mins, vec3_t maxs, int side)
+{
+ vec3_t v1, v2;
+ int i;
+
+ if (side)
+ {
+ for (i = 0; i < 3; i++)
+ {
+ if (normal[i] > BBOX_NORMAL_EPSILON) v1[i] = maxs[i];
+ else if (normal[i] < -BBOX_NORMAL_EPSILON) v1[i] = mins[i];
+ else v1[i] = 0;
+ } //end for
+ } //end if
+ else
+ {
+ for (i = 0; i < 3; i++)
+ {
+ if (normal[i] > BBOX_NORMAL_EPSILON) v1[i] = mins[i];
+ else if (normal[i] < -BBOX_NORMAL_EPSILON) v1[i] = maxs[i];
+ else v1[i] = 0;
+ } //end for
+ } //end else
+ VectorCopy(normal, v2);
+ VectorInverse(v2);
+ return DotProduct(v1, v2);
+} //end of the function BoxOriginDistanceFromPlane
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+vec_t CapsuleOriginDistanceFromPlane(vec3_t normal, vec3_t mins, vec3_t maxs)
+{
+ float offset_up, offset_down, width, radius;
+
+ width = maxs[0] - mins[0];
+ // if the box is less high then it is wide
+ if (maxs[2] - mins[2] < width) {
+ width = maxs[2] - mins[2];
+ }
+ radius = width * 0.5;
+ // offset to upper and lower sphere
+ offset_up = maxs[2] - radius;
+ offset_down = -mins[2] - radius;
+
+ // if normal points upward
+ if ( normal[2] > 0 ) {
+ // touches lower sphere first
+ return normal[2] * offset_down + radius;
+ }
+ else {
+ // touched upper sphere first
+ return -normal[2] * offset_up + radius;
+ }
+}
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ExpandMapBrush(mapbrush_t *brush, vec3_t mins, vec3_t maxs)
+{
+ int sn;
+ float dist;
+ side_t *s;
+ plane_t *plane;
+
+ for (sn = 0; sn < brush->numsides; sn++)
+ {
+ s = brush->original_sides + sn;
+ plane = &mapplanes[s->planenum];
+ dist = plane->dist;
+ if (capsule_collision) {
+ dist += CapsuleOriginDistanceFromPlane(plane->normal, mins, maxs);
+ }
+ else {
+ dist += BoxOriginDistanceFromPlane(plane->normal, mins, maxs, 0);
+ }
+ s->planenum = FindFloatPlane(plane->normal, dist);
+ //the side isn't a bevel after expanding
+ s->flags &= ~SFL_BEVEL;
+ //don't skip the surface
+ s->surf &= ~SURF_SKIP;
+ //make sure the texinfo is not TEXINFO_NODE
+ //when player clip contents brushes are read from the bsp tree
+ //they have the texinfo field set to TEXINFO_NODE
+ //s->texinfo = 0;
+ } //end for
+} //end of the function AAS_ExpandMapBrush
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_SetTexinfo(mapbrush_t *brush)
+{
+ int n;
+ side_t *side;
+
+ if (brush->contents & (CONTENTS_LADDER
+ | CONTENTS_AREAPORTAL
+ | CONTENTS_CLUSTERPORTAL
+ | CONTENTS_TELEPORTER
+ | CONTENTS_JUMPPAD
+ | CONTENTS_DONOTENTER
+ | CONTENTS_WATER
+ | CONTENTS_LAVA
+ | CONTENTS_SLIME
+ | CONTENTS_WINDOW
+ | CONTENTS_PLAYERCLIP))
+ {
+ //we just set texinfo to 0 because these brush sides MUST be used as
+ //bsp splitters textured or not textured
+ for (n = 0; n < brush->numsides; n++)
+ {
+ side = brush->original_sides + n;
+ //side->flags |= SFL_TEXTURED|SFL_VISIBLE;
+ side->texinfo = 0;
+ } //end for
+ } //end if
+ else
+ {
+ //only use brush sides as splitters if they are textured
+ //texinfo of non-textured sides will be set to TEXINFO_NODE
+ for (n = 0; n < brush->numsides; n++)
+ {
+ side = brush->original_sides + n;
+ //don't use side as splitter (set texinfo to TEXINFO_NODE) if not textured
+ if (side->flags & (SFL_TEXTURED|SFL_BEVEL)) side->texinfo = 0;
+ else side->texinfo = TEXINFO_NODE;
+ } //end for
+ } //end else
+} //end of the function AAS_SetTexinfo
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void FreeBrushWindings(mapbrush_t *brush)
+{
+ int n;
+ side_t *side;
+ //
+ for (n = 0; n < brush->numsides; n++)
+ {
+ side = brush->original_sides + n;
+ //
+ if (side->winding) FreeWinding(side->winding);
+ } //end for
+} //end of the function FreeBrushWindings
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_AddMapBrushSide(mapbrush_t *brush, int planenum)
+{
+ side_t *side;
+ //
+ if (nummapbrushsides >= MAX_MAPFILE_BRUSHSIDES)
+ Error ("MAX_MAPFILE_BRUSHSIDES");
+ //
+ side = brush->original_sides + brush->numsides;
+ side->original = NULL;
+ side->winding = NULL;
+ side->contents = brush->contents;
+ side->flags &= ~(SFL_BEVEL|SFL_VISIBLE);
+ side->surf = 0;
+ side->planenum = planenum;
+ side->texinfo = 0;
+ //
+ nummapbrushsides++;
+ brush->numsides++;
+} //end of the function AAS_AddMapBrushSide
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_FixMapBrush(mapbrush_t *brush)
+{
+ int i, j, planenum;
+ float dist;
+ winding_t *w;
+ plane_t *plane, *plane1, *plane2;
+ side_t *side;
+ vec3_t normal;
+
+ //calculate the brush bounds
+ ClearBounds(brush->mins, brush->maxs);
+ for (i = 0; i < brush->numsides; i++)
+ {
+ plane = &mapplanes[brush->original_sides[i].planenum];
+ w = BaseWindingForPlane(plane->normal, plane->dist);
+ for (j = 0; j < brush->numsides && w; j++)
+ {
+ if (i == j) continue;
+ //there are no brush bevels marked but who cares :)
+ if (brush->original_sides[j].flags & SFL_BEVEL) continue;
+ plane = &mapplanes[brush->original_sides[j].planenum^1];
+ ChopWindingInPlace(&w, plane->normal, plane->dist, 0); //CLIP_EPSILON);
+ } //end for
+
+ side = &brush->original_sides[i];
+ side->winding = w;
+ if (w)
+ {
+ for (j = 0; j < w->numpoints; j++)
+ {
+ AddPointToBounds(w->p[j], brush->mins, brush->maxs);
+ } //end for
+ } //end if
+ } //end for
+ //
+ for (i = 0; i < brush->numsides; i++)
+ {
+ for (j = 0; j < brush->numsides; j++)
+ {
+ if (i == j) continue;
+ plane1 = &mapplanes[brush->original_sides[i].planenum];
+ plane2 = &mapplanes[brush->original_sides[j].planenum];
+ if (WindingsNonConvex(brush->original_sides[i].winding,
+ brush->original_sides[j].winding,
+ plane1->normal, plane2->normal,
+ plane1->dist, plane2->dist))
+ {
+ Log_Print("non convex brush");
+ } //end if
+ } //end for
+ } //end for
+
+ //NOW close the fucking brush!!
+ for (i = 0; i < 3; i++)
+ {
+ if (brush->mins[i] < -MAX_MAP_BOUNDS)
+ {
+ VectorClear(normal);
+ normal[i] = -1;
+ dist = MAX_MAP_BOUNDS - 10;
+ planenum = FindFloatPlane(normal, dist);
+ //
+ Log_Print("mins out of range: added extra brush side\n");
+ AAS_AddMapBrushSide(brush, planenum);
+ } //end if
+ if (brush->maxs[i] > MAX_MAP_BOUNDS)
+ {
+ VectorClear(normal);
+ normal[i] = 1;
+ dist = MAX_MAP_BOUNDS - 10;
+ planenum = FindFloatPlane(normal, dist);
+ //
+ Log_Print("maxs out of range: added extra brush side\n");
+ AAS_AddMapBrushSide(brush, planenum);
+ } //end if
+ if (brush->mins[i] > MAX_MAP_BOUNDS || brush->maxs[i] < -MAX_MAP_BOUNDS)
+ {
+ Log_Print("entity %i, brush %i: no visible sides on brush\n", brush->entitynum, brush->brushnum);
+ } //end if
+ } //end for
+ //free all the windings
+ FreeBrushWindings(brush);
+} //end of the function AAS_FixMapBrush
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean AAS_MakeBrushWindings(mapbrush_t *ob)
+{
+ int i, j;
+ winding_t *w;
+ side_t *side;
+ plane_t *plane, *plane1, *plane2;
+
+ ClearBounds (ob->mins, ob->maxs);
+
+ for (i = 0; i < ob->numsides; i++)
+ {
+ plane = &mapplanes[ob->original_sides[i].planenum];
+ w = BaseWindingForPlane(plane->normal, plane->dist);
+ for (j = 0; j <ob->numsides && w; j++)
+ {
+ if (i == j) continue;
+ if (ob->original_sides[j].flags & SFL_BEVEL) continue;
+ plane = &mapplanes[ob->original_sides[j].planenum^1];
+ ChopWindingInPlace(&w, plane->normal, plane->dist, 0); //CLIP_EPSILON);
+ }
+
+ side = &ob->original_sides[i];
+ side->winding = w;
+ if (w)
+ {
+ side->flags |= SFL_VISIBLE;
+ for (j = 0; j < w->numpoints; j++)
+ AddPointToBounds (w->p[j], ob->mins, ob->maxs);
+ }
+ }
+ //check if the brush is convex
+ for (i = 0; i < ob->numsides; i++)
+ {
+ for (j = 0; j < ob->numsides; j++)
+ {
+ if (i == j) continue;
+ plane1 = &mapplanes[ob->original_sides[i].planenum];
+ plane2 = &mapplanes[ob->original_sides[j].planenum];
+ if (WindingsNonConvex(ob->original_sides[i].winding,
+ ob->original_sides[j].winding,
+ plane1->normal, plane2->normal,
+ plane1->dist, plane2->dist))
+ {
+ Log_Print("non convex brush");
+ } //end if
+ } //end for
+ } //end for
+ //check for out of bound brushes
+ for (i = 0; i < 3; i++)
+ {
+ //IDBUG: all the indexes into the mins and maxs were zero (not using i)
+ if (ob->mins[i] < -MAX_MAP_BOUNDS || ob->maxs[i] > MAX_MAP_BOUNDS)
+ {
+ Log_Print("entity %i, brush %i: bounds out of range\n", ob->entitynum, ob->brushnum);
+ Log_Print("ob->mins[%d] = %f, ob->maxs[%d] = %f\n", i, ob->mins[i], i, ob->maxs[i]);
+ ob->numsides = 0; //remove the brush
+ break;
+ } //end if
+ if (ob->mins[i] > MAX_MAP_BOUNDS || ob->maxs[i] < -MAX_MAP_BOUNDS)
+ {
+ Log_Print("entity %i, brush %i: no visible sides on brush\n", ob->entitynum, ob->brushnum);
+ Log_Print("ob->mins[%d] = %f, ob->maxs[%d] = %f\n", i, ob->mins[i], i, ob->maxs[i]);
+ ob->numsides = 0; //remove the brush
+ break;
+ } //end if
+ } //end for
+ return true;
+} //end of the function AAS_MakeBrushWindings
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+mapbrush_t *AAS_CopyMapBrush(mapbrush_t *brush, entity_t *mapent)
+{
+ int n;
+ mapbrush_t *newbrush;
+ side_t *side, *newside;
+
+ if (nummapbrushes >= MAX_MAPFILE_BRUSHES)
+ Error ("MAX_MAPFILE_BRUSHES");
+
+ newbrush = &mapbrushes[nummapbrushes];
+ newbrush->original_sides = &brushsides[nummapbrushsides];
+ newbrush->entitynum = brush->entitynum;
+ newbrush->brushnum = nummapbrushes - mapent->firstbrush;
+ newbrush->numsides = brush->numsides;
+ newbrush->contents = brush->contents;
+
+ //copy the sides
+ for (n = 0; n < brush->numsides; n++)
+ {
+ if (nummapbrushsides >= MAX_MAPFILE_BRUSHSIDES)
+ Error ("MAX_MAPFILE_BRUSHSIDES");
+ side = brush->original_sides + n;
+
+ newside = newbrush->original_sides + n;
+ newside->original = NULL;
+ newside->winding = NULL;
+ newside->contents = side->contents;
+ newside->flags = side->flags;
+ newside->surf = side->surf;
+ newside->planenum = side->planenum;
+ newside->texinfo = side->texinfo;
+ nummapbrushsides++;
+ } //end for
+ //
+ nummapbrushes++;
+ mapent->numbrushes++;
+ return newbrush;
+} //end of the function AAS_CopyMapBrush
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int mark_entities[MAX_MAP_ENTITIES];
+
+int AAS_AlwaysTriggered_r(char *targetname)
+{
+ int i;
+
+ if (!strlen(targetname)) {
+ return false;
+ }
+ //
+ for (i = 0; i < num_entities; i++) {
+ // if the entity will activate the given targetname
+ if ( !strcmp(targetname, ValueForKey(&entities[i], "target")) ) {
+ // if this activator is present in deathmatch
+ if (!(atoi(ValueForKey(&entities[i], "spawnflags")) & SPAWNFLAG_NOT_DEATHMATCH)) {
+ // if it is a trigger_always entity
+ if (!strcmp("trigger_always", ValueForKey(&entities[i], "classname"))) {
+ return true;
+ }
+ // check for possible trigger_always entities activating this entity
+ if ( mark_entities[i] ) {
+ Warning( "entity %d, classname %s has recursive targetname %s\n", i,
+ ValueForKey(&entities[i], "classname"), targetname );
+ return false;
+ }
+ mark_entities[i] = true;
+ if ( AAS_AlwaysTriggered_r(ValueForKey(&entities[i], "targetname")) ) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+}
+
+int AAS_AlwaysTriggered(char *targetname) {
+ memset( mark_entities, 0, sizeof(mark_entities) );
+ return AAS_AlwaysTriggered_r( targetname );
+}
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_ValidEntity(entity_t *mapent)
+{
+ int i;
+ char target[1024];
+
+ //all world brushes are used for AAS
+ if (mapent == &entities[0])
+ {
+ return true;
+ } //end if
+ //some of the func_wall brushes are also used for AAS
+ else if (!strcmp("func_wall", ValueForKey(mapent, "classname")))
+ {
+ //Log_Print("found func_wall entity %d\n", mapent - entities);
+ //if the func wall is used in deathmatch
+ if (!(atoi(ValueForKey(mapent, "spawnflags")) & SPAWNFLAG_NOT_DEATHMATCH))
+ {
+ //Log_Print("func_wall USED in deathmatch mode %d\n", atoi(ValueForKey(mapent, "spawnflags")));
+ return true;
+ } //end if
+ } //end else if
+ else if (!strcmp("func_door_rotating", ValueForKey(mapent, "classname")))
+ {
+ //if the func_door_rotating is present in deathmatch
+ if (!(atoi(ValueForKey(mapent, "spawnflags")) & SPAWNFLAG_NOT_DEATHMATCH))
+ {
+ //if the func_door_rotating is always activated in deathmatch
+ if (AAS_AlwaysTriggered(ValueForKey(mapent, "targetname")))
+ {
+ //Log_Print("found func_door_rotating in deathmatch\ntargetname %s\n", ValueForKey(mapent, "targetname"));
+ return true;
+ } //end if
+ } //end if
+ } //end else if
+ else if (!strcmp("trigger_hurt", ValueForKey(mapent, "classname")))
+ {
+ //"dmg" is the damage, for instance: "dmg" "666"
+ return true;
+ } //end else if
+ else if (!strcmp("trigger_push", ValueForKey(mapent, "classname")))
+ {
+ return true;
+ } //end else if
+ else if (!strcmp("trigger_multiple", ValueForKey(mapent, "classname")))
+ {
+ //find out if the trigger_multiple is pointing to a target_teleporter
+ strcpy(target, ValueForKey(mapent, "target"));
+ for (i = 0; i < num_entities; i++)
+ {
+ //if the entity will activate the given targetname
+ if (!strcmp(target, ValueForKey(&entities[i], "targetname")))
+ {
+ if (!strcmp("target_teleporter", ValueForKey(&entities[i], "classname")))
+ {
+ return true;
+ } //end if
+ } //end if
+ } //end for
+ } //end else if
+ else if (!strcmp("trigger_teleport", ValueForKey(mapent, "classname")))
+ {
+ return true;
+ } //end else if
+ else if (!strcmp("func_static", ValueForKey(mapent, "classname")))
+ {
+ //FIXME: easy/medium/hard/deathmatch specific?
+ return true;
+ } //end else if
+ else if (!strcmp("func_door", ValueForKey(mapent, "classname")))
+ {
+ return true;
+ } //end else if
+ return false;
+} //end of the function AAS_ValidEntity
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_TransformPlane(int planenum, vec3_t origin, vec3_t angles)
+{
+ float newdist, matrix[3][3];
+ vec3_t normal;
+
+ //rotate the node plane
+ VectorCopy(mapplanes[planenum].normal, normal);
+ CreateRotationMatrix(angles, matrix);
+ RotatePoint(normal, matrix);
+ newdist = mapplanes[planenum].dist + DotProduct(normal, origin);
+ return FindFloatPlane(normal, newdist);
+} //end of the function AAS_TransformPlane
+//===========================================================================
+// this function sets the func_rotating_door in it's final position
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_PositionFuncRotatingBrush(entity_t *mapent, mapbrush_t *brush)
+{
+ int spawnflags, i;
+ float distance;
+ vec3_t movedir, angles, pos1, pos2;
+ side_t *s;
+
+ spawnflags = FloatForKey(mapent, "spawnflags");
+ VectorClear(movedir);
+ if (spawnflags & DOOR_X_AXIS)
+ movedir[2] = 1.0; //roll
+ else if (spawnflags & DOOR_Y_AXIS)
+ movedir[0] = 1.0; //pitch
+ else // Z_AXIS
+ movedir[1] = 1.0; //yaw
+
+ // check for reverse rotation
+ if (spawnflags & DOOR_REVERSE)
+ VectorInverse(movedir);
+
+ distance = FloatForKey(mapent, "distance");
+ if (!distance) distance = 90;
+
+ GetVectorForKey(mapent, "angles", angles);
+ VectorCopy(angles, pos1);
+ VectorMA(angles, -distance, movedir, pos2);
+ // if it starts open, switch the positions
+ if (spawnflags & DOOR_START_OPEN)
+ {
+ VectorCopy(pos2, angles);
+ VectorCopy(pos1, pos2);
+ VectorCopy(angles, pos1);
+ VectorInverse(movedir);
+ } //end if
+ //
+ for (i = 0; i < brush->numsides; i++)
+ {
+ s = &brush->original_sides[i];
+ s->planenum = AAS_TransformPlane(s->planenum, mapent->origin, pos2);
+ } //end for
+ //
+ FreeBrushWindings(brush);
+ AAS_MakeBrushWindings(brush);
+ AddBrushBevels(brush);
+ FreeBrushWindings(brush);
+} //end of the function AAS_PositionFuncRotatingBrush
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_PositionBrush(entity_t *mapent, mapbrush_t *brush)
+{
+ side_t *s;
+ float newdist;
+ int i, notteam;
+ char *model;
+
+ if (!strcmp(ValueForKey(mapent, "classname"), "func_door_rotating"))
+ {
+ AAS_PositionFuncRotatingBrush(mapent, brush);
+ } //end if
+ else
+ {
+ if (mapent->origin[0] || mapent->origin[1] || mapent->origin[2])
+ {
+ for (i = 0; i < brush->numsides; i++)
+ {
+ s = &brush->original_sides[i];
+ newdist = mapplanes[s->planenum].dist +
+ DotProduct(mapplanes[s->planenum].normal, mapent->origin);
+ s->planenum = FindFloatPlane(mapplanes[s->planenum].normal, newdist);
+ } //end for
+ } //end if
+ //if it's a trigger hurt
+ if (!strcmp("trigger_hurt", ValueForKey(mapent, "classname")))
+ {
+ notteam = FloatForKey(mapent, "bot_notteam");
+ if ( notteam == 1 ) {
+ brush->contents |= CONTENTS_NOTTEAM1;
+ }
+ else if ( notteam == 2 ) {
+ brush->contents |= CONTENTS_NOTTEAM2;
+ }
+ else {
+ // always avoid so set lava contents
+ brush->contents |= CONTENTS_LAVA;
+ }
+ } //end if
+ //
+ else if (!strcmp("trigger_push", ValueForKey(mapent, "classname")))
+ {
+ //set the jumppad contents
+ brush->contents = CONTENTS_JUMPPAD;
+ //Log_Print("found trigger_push brush\n");
+ } //end if
+ //
+ else if (!strcmp("trigger_multiple", ValueForKey(mapent, "classname")))
+ {
+ //set teleporter contents
+ brush->contents = CONTENTS_TELEPORTER;
+ //Log_Print("found trigger_multiple teleporter brush\n");
+ } //end if
+ //
+ else if (!strcmp("trigger_teleport", ValueForKey(mapent, "classname")))
+ {
+ //set teleporter contents
+ brush->contents = CONTENTS_TELEPORTER;
+ //Log_Print("found trigger_teleport teleporter brush\n");
+ } //end if
+ else if (!strcmp("func_door", ValueForKey(mapent, "classname")))
+ {
+ //set mover contents
+ brush->contents = CONTENTS_MOVER;
+ //get the model number
+ model = ValueForKey(mapent, "model");
+ brush->modelnum = atoi(model+1);
+ } //end if
+ } //end else
+} //end of the function AAS_PositionBrush
+//===========================================================================
+// uses the global cfg_t cfg
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_CreateMapBrushes(mapbrush_t *brush, entity_t *mapent, int addbevels)
+{
+ int i;
+ //side_t *s;
+ mapbrush_t *bboxbrushes[16];
+
+ //if the brushes are not from an entity used for AAS
+ if (!AAS_ValidEntity(mapent))
+ {
+ nummapbrushsides -= brush->numsides;
+ brush->numsides = 0;
+ return;
+ } //end if
+ //
+ AAS_PositionBrush(mapent, brush);
+ //from all normal solid brushes only the textured brush sides will
+ //be used as bsp splitters, so set the right texinfo reference here
+ AAS_SetTexinfo(brush);
+ //remove contents detail flag, otherwise player clip contents won't be
+ //bsped correctly for AAS!
+ brush->contents &= ~CONTENTS_DETAIL;
+ //if the brush has contents area portal it should be the only contents
+ if (brush->contents & (CONTENTS_AREAPORTAL|CONTENTS_CLUSTERPORTAL))
+ {
+ brush->contents = CONTENTS_CLUSTERPORTAL;
+ brush->leafnum = -1;
+ } //end if
+ //window and playerclip are used for player clipping, make them solid
+ if (brush->contents & (CONTENTS_WINDOW | CONTENTS_PLAYERCLIP))
+ {
+ //
+ brush->contents &= ~(CONTENTS_WINDOW | CONTENTS_PLAYERCLIP);
+ brush->contents |= CONTENTS_SOLID;
+ brush->leafnum = -1;
+ } //end if
+ //
+ if (brush->contents & CONTENTS_BOTCLIP)
+ {
+ brush->contents = CONTENTS_SOLID;
+ brush->leafnum = -1;
+ } //end if
+ //
+ //Log_Write("brush %d contents = ", brush->brushnum);
+ //PrintContents(brush->contents);
+ //Log_Write("\r\n");
+ //if not one of the following brushes then the brush is NOT used for AAS
+ if (!(brush->contents & (CONTENTS_SOLID
+ | CONTENTS_LADDER
+ | CONTENTS_CLUSTERPORTAL
+ | CONTENTS_DONOTENTER
+ | CONTENTS_TELEPORTER
+ | CONTENTS_JUMPPAD
+ | CONTENTS_WATER
+ | CONTENTS_LAVA
+ | CONTENTS_SLIME
+ | CONTENTS_MOVER
+ )))
+ {
+ nummapbrushsides -= brush->numsides;
+ brush->numsides = 0;
+ return;
+ } //end if
+ //fix the map brush
+ //AAS_FixMapBrush(brush);
+ //if brush bevels should be added (for real map brushes, not bsp map brushes)
+ if (addbevels)
+ {
+ //NOTE: we first have to get the mins and maxs of the brush before
+ // creating the brush bevels... the mins and maxs are used to
+ // create them. so we call MakeBrushWindings to get the mins
+ // and maxs and then after creating the bevels we free the
+ // windings because they are created for all sides (including
+ // bevels) a little later
+ AAS_MakeBrushWindings(brush);
+ AddBrushBevels(brush);
+ FreeBrushWindings(brush);
+ } //end if
+ //NOTE: add the brush to the WORLD entity!!!
+ mapent = &entities[0];
+ //there's at least one new brush for now
+ nummapbrushes++;
+ mapent->numbrushes++;
+ //liquid brushes are expanded for the maximum possible bounding box
+ if (brush->contents & (CONTENTS_WATER
+ | CONTENTS_LAVA
+ | CONTENTS_SLIME
+ | CONTENTS_TELEPORTER
+ | CONTENTS_JUMPPAD
+ | CONTENTS_DONOTENTER
+ | CONTENTS_MOVER
+ ))
+ {
+ brush->expansionbbox = 0;
+ //NOTE: the first bounding box is the max
+ //FIXME: use max bounding box created from all bboxes
+ AAS_ExpandMapBrush(brush, cfg.bboxes[0].mins, cfg.bboxes[0].maxs);
+ AAS_MakeBrushWindings(brush);
+ } //end if
+ //area portal brushes are NOT expanded
+ else if (brush->contents & CONTENTS_CLUSTERPORTAL)
+ {
+ brush->expansionbbox = 0;
+ //NOTE: the first bounding box is the max
+ //FIXME: use max bounding box created from all bboxes
+ AAS_ExpandMapBrush(brush, cfg.bboxes[0].mins, cfg.bboxes[0].maxs);
+ AAS_MakeBrushWindings(brush);
+ } //end if
+ //all solid brushes are expanded for all bounding boxes
+ else if (brush->contents & (CONTENTS_SOLID
+ | CONTENTS_LADDER
+ ))
+ {
+ //brush for the first bounding box
+ bboxbrushes[0] = brush;
+ //make a copy for the other bounding boxes
+ for (i = 1; i < cfg.numbboxes; i++)
+ {
+ bboxbrushes[i] = AAS_CopyMapBrush(brush, mapent);
+ } //end for
+ //expand every brush for it's bounding box and create windings
+ for (i = 0; i < cfg.numbboxes; i++)
+ {
+ AAS_ExpandMapBrush(bboxbrushes[i], cfg.bboxes[i].mins, cfg.bboxes[i].maxs);
+ bboxbrushes[i]->expansionbbox = cfg.bboxes[i].presencetype;
+ AAS_MakeBrushWindings(bboxbrushes[i]);
+ } //end for
+ } //end else
+} //end of the function AAS_CreateMapBrushes
diff --git a/code/bspc/aas_map.h b/code/bspc/aas_map.h
new file mode 100755
index 0000000..601cdfb
--- /dev/null
+++ b/code/bspc/aas_map.h
@@ -0,0 +1,23 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+void AAS_CreateMapBrushes(mapbrush_t *brush, entity_t *mapent, int addbevels);
diff --git a/code/bspc/aas_prunenodes.c b/code/bspc/aas_prunenodes.c
new file mode 100755
index 0000000..a03e9d2
--- /dev/null
+++ b/code/bspc/aas_prunenodes.c
@@ -0,0 +1,89 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+#include "../botlib/aasfile.h"
+#include "aas_create.h"
+
+int c_numprunes;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+tmp_node_t *AAS_PruneNodes_r(tmp_node_t *tmpnode)
+{
+ tmp_area_t *tmparea1, *tmparea2;
+
+ //if it is a solid leaf
+ if (!tmpnode) return NULL;
+ //
+ if (tmpnode->tmparea) return tmpnode;
+ //process the children first
+ tmpnode->children[0] = AAS_PruneNodes_r(tmpnode->children[0]);
+ tmpnode->children[1] = AAS_PruneNodes_r(tmpnode->children[1]);
+ //if both children are areas
+ if (tmpnode->children[0] && tmpnode->children[1] &&
+ tmpnode->children[0]->tmparea && tmpnode->children[1]->tmparea)
+ {
+ tmparea1 = tmpnode->children[0]->tmparea;
+ while(tmparea1->mergedarea) tmparea1 = tmparea1->mergedarea;
+
+ tmparea2 = tmpnode->children[1]->tmparea;
+ while(tmparea2->mergedarea) tmparea2 = tmparea2->mergedarea;
+
+ if (tmparea1 == tmparea2)
+ {
+ c_numprunes++;
+ tmpnode->tmparea = tmparea1;
+ tmpnode->planenum = 0;
+ AAS_FreeTmpNode(tmpnode->children[0]);
+ AAS_FreeTmpNode(tmpnode->children[1]);
+ tmpnode->children[0] = NULL;
+ tmpnode->children[1] = NULL;
+ return tmpnode;
+ } //end if
+ } //end if
+ //if both solid leafs
+ if (!tmpnode->children[0] && !tmpnode->children[1])
+ {
+ c_numprunes++;
+ AAS_FreeTmpNode(tmpnode);
+ return NULL;
+ } //end if
+ //
+ return tmpnode;
+} //end of the function AAS_PruneNodes_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_PruneNodes(void)
+{
+ Log_Write("AAS_PruneNodes\r\n");
+ AAS_PruneNodes_r(tmpaasworld.nodes);
+ Log_Print("%6d nodes pruned\r\n", c_numprunes);
+} //end of the function AAS_PruneNodes
diff --git a/code/bspc/aas_prunenodes.h b/code/bspc/aas_prunenodes.h
new file mode 100755
index 0000000..36989ad
--- /dev/null
+++ b/code/bspc/aas_prunenodes.h
@@ -0,0 +1,24 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+void AAS_PruneNodes(void);
+
diff --git a/code/bspc/aas_store.c b/code/bspc/aas_store.c
new file mode 100755
index 0000000..4836d51
--- /dev/null
+++ b/code/bspc/aas_store.c
@@ -0,0 +1,1082 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+#include "../botlib/aasfile.h"
+#include "aas_file.h"
+#include "aas_store.h"
+#include "aas_create.h"
+#include "aas_cfg.h"
+
+
+//#define NOTHREEVERTEXFACES
+
+#define STOREPLANESDOUBLE
+
+#define VERTEX_EPSILON 0.1 //NOTE: changed from 0.5
+#define DIST_EPSILON 0.05 //NOTE: changed from 0.9
+#define NORMAL_EPSILON 0.0001 //NOTE: changed from 0.005
+#define INTEGRAL_EPSILON 0.01
+
+#define VERTEX_HASHING
+#define VERTEX_HASH_SHIFT 7
+#define VERTEX_HASH_SIZE ((MAX_MAP_BOUNDS>>(VERTEX_HASH_SHIFT-1))+1) //was 64
+//
+#define PLANE_HASHING
+#define PLANE_HASH_SIZE 1024 //must be power of 2
+//
+#define EDGE_HASHING
+#define EDGE_HASH_SIZE 1024 //must be power of 2
+
+aas_t aasworld;
+
+//vertex hash
+int *aas_vertexchain; // the next vertex in a hash chain
+int aas_hashverts[VERTEX_HASH_SIZE*VERTEX_HASH_SIZE]; // a vertex number, or 0 for no verts
+//plane hash
+int *aas_planechain;
+int aas_hashplanes[PLANE_HASH_SIZE];
+//edge hash
+int *aas_edgechain;
+int aas_hashedges[EDGE_HASH_SIZE];
+
+int allocatedaasmem = 0;
+
+int groundfacesonly = false;//true;
+//
+typedef struct max_aas_s
+{
+ int max_bboxes;
+ int max_vertexes;
+ int max_planes;
+ int max_edges;
+ int max_edgeindexsize;
+ int max_faces;
+ int max_faceindexsize;
+ int max_areas;
+ int max_areasettings;
+ int max_reachabilitysize;
+ int max_nodes;
+ int max_portals;
+ int max_portalindexsize;
+ int max_clusters;
+} max_aas_t;
+//maximums of everything
+max_aas_t max_aas;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_CountTmpNodes(tmp_node_t *tmpnode)
+{
+ if (!tmpnode) return 0;
+ return AAS_CountTmpNodes(tmpnode->children[0]) +
+ AAS_CountTmpNodes(tmpnode->children[1]) + 1;
+} //end of the function AAS_CountTmpNodes
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_InitMaxAAS(void)
+{
+ int numfaces, numpoints, numareas;
+ tmp_face_t *f;
+ tmp_area_t *a;
+
+ numpoints = 0;
+ numfaces = 0;
+ for (f = tmpaasworld.faces; f; f = f->l_next)
+ {
+ numfaces++;
+ if (f->winding) numpoints += f->winding->numpoints;
+ } //end for
+ //
+ numareas = 0;
+ for (a = tmpaasworld.areas; a; a = a->l_next)
+ {
+ numareas++;
+ } //end for
+ max_aas.max_bboxes = AAS_MAX_BBOXES;
+ max_aas.max_vertexes = numpoints + 1;
+ max_aas.max_planes = nummapplanes;
+ max_aas.max_edges = numpoints + 1;
+ max_aas.max_edgeindexsize = (numpoints + 1) * 3;
+ max_aas.max_faces = numfaces + 10;
+ max_aas.max_faceindexsize = (numfaces + 10) * 2;
+ max_aas.max_areas = numareas + 10;
+ max_aas.max_areasettings = numareas + 10;
+ max_aas.max_reachabilitysize = 0;
+ max_aas.max_nodes = AAS_CountTmpNodes(tmpaasworld.nodes) + 10;
+ max_aas.max_portals = 0;
+ max_aas.max_portalindexsize = 0;
+ max_aas.max_clusters = 0;
+} //end of the function AAS_InitMaxAAS
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_AllocMaxAAS(void)
+{
+ int i;
+
+ AAS_InitMaxAAS();
+ //bounding boxes
+ aasworld.numbboxes = 0;
+ aasworld.bboxes = (aas_bbox_t *) GetClearedMemory(max_aas.max_bboxes * sizeof(aas_bbox_t));
+ allocatedaasmem += max_aas.max_bboxes * sizeof(aas_bbox_t);
+ //vertexes
+ aasworld.numvertexes = 0;
+ aasworld.vertexes = (aas_vertex_t *) GetClearedMemory(max_aas.max_vertexes * sizeof(aas_vertex_t));
+ allocatedaasmem += max_aas.max_vertexes * sizeof(aas_vertex_t);
+ //planes
+ aasworld.numplanes = 0;
+ aasworld.planes = (aas_plane_t *) GetClearedMemory(max_aas.max_planes * sizeof(aas_plane_t));
+ allocatedaasmem += max_aas.max_planes * sizeof(aas_plane_t);
+ //edges
+ aasworld.numedges = 0;
+ aasworld.edges = (aas_edge_t *) GetClearedMemory(max_aas.max_edges * sizeof(aas_edge_t));
+ allocatedaasmem += max_aas.max_edges * sizeof(aas_edge_t);
+ //edge index
+ aasworld.edgeindexsize = 0;
+ aasworld.edgeindex = (aas_edgeindex_t *) GetClearedMemory(max_aas.max_edgeindexsize * sizeof(aas_edgeindex_t));
+ allocatedaasmem += max_aas.max_edgeindexsize * sizeof(aas_edgeindex_t);
+ //faces
+ aasworld.numfaces = 0;
+ aasworld.faces = (aas_face_t *) GetClearedMemory(max_aas.max_faces * sizeof(aas_face_t));
+ allocatedaasmem += max_aas.max_faces * sizeof(aas_face_t);
+ //face index
+ aasworld.faceindexsize = 0;
+ aasworld.faceindex = (aas_faceindex_t *) GetClearedMemory(max_aas.max_faceindexsize * sizeof(aas_faceindex_t));
+ allocatedaasmem += max_aas.max_faceindexsize * sizeof(aas_faceindex_t);
+ //convex areas
+ aasworld.numareas = 0;
+ aasworld.areas = (aas_area_t *) GetClearedMemory(max_aas.max_areas * sizeof(aas_area_t));
+ allocatedaasmem += max_aas.max_areas * sizeof(aas_area_t);
+ //convex area settings
+ aasworld.numareasettings = 0;
+ aasworld.areasettings = (aas_areasettings_t *) GetClearedMemory(max_aas.max_areasettings * sizeof(aas_areasettings_t));
+ allocatedaasmem += max_aas.max_areasettings * sizeof(aas_areasettings_t);
+ //reachablity list
+ aasworld.reachabilitysize = 0;
+ aasworld.reachability = (aas_reachability_t *) GetClearedMemory(max_aas.max_reachabilitysize * sizeof(aas_reachability_t));
+ allocatedaasmem += max_aas.max_reachabilitysize * sizeof(aas_reachability_t);
+ //nodes of the bsp tree
+ aasworld.numnodes = 0;
+ aasworld.nodes = (aas_node_t *) GetClearedMemory(max_aas.max_nodes * sizeof(aas_node_t));
+ allocatedaasmem += max_aas.max_nodes * sizeof(aas_node_t);
+ //cluster portals
+ aasworld.numportals = 0;
+ aasworld.portals = (aas_portal_t *) GetClearedMemory(max_aas.max_portals * sizeof(aas_portal_t));
+ allocatedaasmem += max_aas.max_portals * sizeof(aas_portal_t);
+ //cluster portal index
+ aasworld.portalindexsize = 0;
+ aasworld.portalindex = (aas_portalindex_t *) GetClearedMemory(max_aas.max_portalindexsize * sizeof(aas_portalindex_t));
+ allocatedaasmem += max_aas.max_portalindexsize * sizeof(aas_portalindex_t);
+ //cluster
+ aasworld.numclusters = 0;
+ aasworld.clusters = (aas_cluster_t *) GetClearedMemory(max_aas.max_clusters * sizeof(aas_cluster_t));
+ allocatedaasmem += max_aas.max_clusters * sizeof(aas_cluster_t);
+ //
+ Log_Print("allocated ");
+ PrintMemorySize(allocatedaasmem);
+ Log_Print(" of AAS memory\n");
+ //reset the has stuff
+ aas_vertexchain = (int *) GetClearedMemory(max_aas.max_vertexes * sizeof(int));
+ aas_planechain = (int *) GetClearedMemory(max_aas.max_planes * sizeof(int));
+ aas_edgechain = (int *) GetClearedMemory(max_aas.max_edges * sizeof(int));
+ //
+ for (i = 0; i < max_aas.max_vertexes; i++) aas_vertexchain[i] = -1;
+ for (i = 0; i < VERTEX_HASH_SIZE * VERTEX_HASH_SIZE; i++) aas_hashverts[i] = -1;
+ //
+ for (i = 0; i < max_aas.max_planes; i++) aas_planechain[i] = -1;
+ for (i = 0; i < PLANE_HASH_SIZE; i++) aas_hashplanes[i] = -1;
+ //
+ for (i = 0; i < max_aas.max_edges; i++) aas_edgechain[i] = -1;
+ for (i = 0; i < EDGE_HASH_SIZE; i++) aas_hashedges[i] = -1;
+} //end of the function AAS_AllocMaxAAS
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_FreeMaxAAS(void)
+{
+ //bounding boxes
+ if (aasworld.bboxes) FreeMemory(aasworld.bboxes);
+ aasworld.bboxes = NULL;
+ aasworld.numbboxes = 0;
+ //vertexes
+ if (aasworld.vertexes) FreeMemory(aasworld.vertexes);
+ aasworld.vertexes = NULL;
+ aasworld.numvertexes = 0;
+ //planes
+ if (aasworld.planes) FreeMemory(aasworld.planes);
+ aasworld.planes = NULL;
+ aasworld.numplanes = 0;
+ //edges
+ if (aasworld.edges) FreeMemory(aasworld.edges);
+ aasworld.edges = NULL;
+ aasworld.numedges = 0;
+ //edge index
+ if (aasworld.edgeindex) FreeMemory(aasworld.edgeindex);
+ aasworld.edgeindex = NULL;
+ aasworld.edgeindexsize = 0;
+ //faces
+ if (aasworld.faces) FreeMemory(aasworld.faces);
+ aasworld.faces = NULL;
+ aasworld.numfaces = 0;
+ //face index
+ if (aasworld.faceindex) FreeMemory(aasworld.faceindex);
+ aasworld.faceindex = NULL;
+ aasworld.faceindexsize = 0;
+ //convex areas
+ if (aasworld.areas) FreeMemory(aasworld.areas);
+ aasworld.areas = NULL;
+ aasworld.numareas = 0;
+ //convex area settings
+ if (aasworld.areasettings) FreeMemory(aasworld.areasettings);
+ aasworld.areasettings = NULL;
+ aasworld.numareasettings = 0;
+ //reachablity list
+ if (aasworld.reachability) FreeMemory(aasworld.reachability);
+ aasworld.reachability = NULL;
+ aasworld.reachabilitysize = 0;
+ //nodes of the bsp tree
+ if (aasworld.nodes) FreeMemory(aasworld.nodes);
+ aasworld.nodes = NULL;
+ aasworld.numnodes = 0;
+ //cluster portals
+ if (aasworld.portals) FreeMemory(aasworld.portals);
+ aasworld.portals = NULL;
+ aasworld.numportals = 0;
+ //cluster portal index
+ if (aasworld.portalindex) FreeMemory(aasworld.portalindex);
+ aasworld.portalindex = NULL;
+ aasworld.portalindexsize = 0;
+ //clusters
+ if (aasworld.clusters) FreeMemory(aasworld.clusters);
+ aasworld.clusters = NULL;
+ aasworld.numclusters = 0;
+
+ Log_Print("freed ");
+ PrintMemorySize(allocatedaasmem);
+ Log_Print(" of AAS memory\n");
+ allocatedaasmem = 0;
+ //
+ if (aas_vertexchain) FreeMemory(aas_vertexchain);
+ aas_vertexchain = NULL;
+ if (aas_planechain) FreeMemory(aas_planechain);
+ aas_planechain = NULL;
+ if (aas_edgechain) FreeMemory(aas_edgechain);
+ aas_edgechain = NULL;
+} //end of the function AAS_FreeMaxAAS
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+unsigned AAS_HashVec(vec3_t vec)
+{
+ int x, y;
+
+ x = (MAX_MAP_BOUNDS + (int)(vec[0]+0.5)) >> VERTEX_HASH_SHIFT;
+ y = (MAX_MAP_BOUNDS + (int)(vec[1]+0.5)) >> VERTEX_HASH_SHIFT;
+
+ if (x < 0 || x >= VERTEX_HASH_SIZE || y < 0 || y >= VERTEX_HASH_SIZE)
+ {
+ Log_Print("WARNING! HashVec: point %f %f %f outside valid range\n", vec[0], vec[1], vec[2]);
+ Log_Print("This should never happen!\n");
+ return -1;
+ } //end if
+
+ return y*VERTEX_HASH_SIZE + x;
+} //end of the function AAS_HashVec
+//===========================================================================
+// returns true if the vertex was found in the list
+// stores the vertex number in *vnum
+// stores a new vertex if not stored already
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean AAS_GetVertex(vec3_t v, int *vnum)
+{
+ int i;
+#ifndef VERTEX_HASHING
+ float diff;
+#endif //VERTEX_HASHING
+
+#ifdef VERTEX_HASHING
+ int h, vn;
+ vec3_t vert;
+
+ for (i = 0; i < 3; i++)
+ {
+ if ( fabs(v[i] - Q_rint(v[i])) < INTEGRAL_EPSILON)
+ vert[i] = Q_rint(v[i]);
+ else
+ vert[i] = v[i];
+ } //end for
+
+ h = AAS_HashVec(vert);
+ //if the vertex was outside the valid range
+ if (h == -1)
+ {
+ *vnum = -1;
+ return true;
+ } //end if
+
+ for (vn = aas_hashverts[h]; vn >= 0; vn = aas_vertexchain[vn])
+ {
+ if (fabs(aasworld.vertexes[vn][0] - vert[0]) < VERTEX_EPSILON
+ && fabs(aasworld.vertexes[vn][1] - vert[1]) < VERTEX_EPSILON
+ && fabs(aasworld.vertexes[vn][2] - vert[2]) < VERTEX_EPSILON)
+ {
+ *vnum = vn;
+ return true;
+ } //end if
+ } //end for
+#else //VERTEX_HASHING
+ //check if the vertex is already stored
+ //stupid linear search
+ for (i = 0; i < aasworld.numvertexes; i++)
+ {
+ diff = vert[0] - aasworld.vertexes[i][0];
+ if (diff < VERTEX_EPSILON && diff > -VERTEX_EPSILON)
+ {
+ diff = vert[1] - aasworld.vertexes[i][1];
+ if (diff < VERTEX_EPSILON && diff > -VERTEX_EPSILON)
+ {
+ diff = vert[2] - aasworld.vertexes[i][2];
+ if (diff < VERTEX_EPSILON && diff > -VERTEX_EPSILON)
+ {
+ *vnum = i;
+ return true;
+ } //end if
+ } //end if
+ } //end if
+ } //end for
+#endif //VERTEX_HASHING
+
+ if (aasworld.numvertexes >= max_aas.max_vertexes)
+ {
+ Error("AAS_MAX_VERTEXES = %d", max_aas.max_vertexes);
+ } //end if
+ VectorCopy(vert, aasworld.vertexes[aasworld.numvertexes]);
+ *vnum = aasworld.numvertexes;
+
+#ifdef VERTEX_HASHING
+ aas_vertexchain[aasworld.numvertexes] = aas_hashverts[h];
+ aas_hashverts[h] = aasworld.numvertexes;
+#endif //VERTEX_HASHING
+
+ aasworld.numvertexes++;
+ return false;
+} //end of the function AAS_GetVertex
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+unsigned AAS_HashEdge(int v1, int v2)
+{
+ int vnum1, vnum2;
+ //
+ if (v1 < v2)
+ {
+ vnum1 = v1;
+ vnum2 = v2;
+ } //end if
+ else
+ {
+ vnum1 = v2;
+ vnum2 = v1;
+ } //end else
+ return (vnum1 + vnum2) & (EDGE_HASH_SIZE-1);
+} //end of the function AAS_HashVec
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_AddEdgeToHash(int edgenum)
+{
+ int hash;
+ aas_edge_t *edge;
+
+ edge = &aasworld.edges[edgenum];
+
+ hash = AAS_HashEdge(edge->v[0], edge->v[1]);
+
+ aas_edgechain[edgenum] = aas_hashedges[hash];
+ aas_hashedges[hash] = edgenum;
+} //end of the function AAS_AddEdgeToHash
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean AAS_FindHashedEdge(int v1num, int v2num, int *edgenum)
+{
+ int e, hash;
+ aas_edge_t *edge;
+
+ hash = AAS_HashEdge(v1num, v2num);
+ for (e = aas_hashedges[hash]; e >= 0; e = aas_edgechain[e])
+ {
+ edge = &aasworld.edges[e];
+ if (edge->v[0] == v1num)
+ {
+ if (edge->v[1] == v2num)
+ {
+ *edgenum = e;
+ return true;
+ } //end if
+ } //end if
+ else if (edge->v[1] == v1num)
+ {
+ if (edge->v[0] == v2num)
+ {
+ //negative for a reversed edge
+ *edgenum = -e;
+ return true;
+ } //end if
+ } //end else
+ } //end for
+ return false;
+} //end of the function AAS_FindHashedPlane
+//===========================================================================
+// returns true if the edge was found
+// stores the edge number in *edgenum (negative if reversed edge)
+// stores new edge if not stored already
+// returns zero when the edge is degenerate
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean AAS_GetEdge(vec3_t v1, vec3_t v2, int *edgenum)
+{
+ int v1num, v2num;
+ qboolean found;
+
+ //the first edge is a dummy
+ if (aasworld.numedges == 0) aasworld.numedges = 1;
+
+ found = AAS_GetVertex(v1, &v1num);
+ found &= AAS_GetVertex(v2, &v2num);
+ //if one of the vertexes was outside the valid range
+ if (v1num == -1 || v2num == -1)
+ {
+ *edgenum = 0;
+ return true;
+ } //end if
+ //if both vertexes are the same or snapped onto each other
+ if (v1num == v2num)
+ {
+ *edgenum = 0;
+ return true;
+ } //end if
+ //if both vertexes where already stored
+ if (found)
+ {
+#ifdef EDGE_HASHING
+ if (AAS_FindHashedEdge(v1num, v2num, edgenum)) return true;
+#else
+ int i;
+ for (i = 1; i < aasworld.numedges; i++)
+ {
+ if (aasworld.edges[i].v[0] == v1num)
+ {
+ if (aasworld.edges[i].v[1] == v2num)
+ {
+ *edgenum = i;
+ return true;
+ } //end if
+ } //end if
+ else if (aasworld.edges[i].v[1] == v1num)
+ {
+ if (aasworld.edges[i].v[0] == v2num)
+ {
+ //negative for a reversed edge
+ *edgenum = -i;
+ return true;
+ } //end if
+ } //end else
+ } //end for
+#endif //EDGE_HASHING
+ } //end if
+ if (aasworld.numedges >= max_aas.max_edges)
+ {
+ Error("AAS_MAX_EDGES = %d", max_aas.max_edges);
+ } //end if
+ aasworld.edges[aasworld.numedges].v[0] = v1num;
+ aasworld.edges[aasworld.numedges].v[1] = v2num;
+ *edgenum = aasworld.numedges;
+#ifdef EDGE_HASHING
+ AAS_AddEdgeToHash(*edgenum);
+#endif //EDGE_HASHING
+ aasworld.numedges++;
+ return false;
+} //end of the function AAS_GetEdge
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_PlaneTypeForNormal(vec3_t normal)
+{
+ vec_t ax, ay, az;
+
+ //NOTE: epsilon used
+ if ( (normal[0] >= 1.0 -NORMAL_EPSILON) ||
+ (normal[0] <= -1.0 + NORMAL_EPSILON)) return PLANE_X;
+ if ( (normal[1] >= 1.0 -NORMAL_EPSILON) ||
+ (normal[1] <= -1.0 + NORMAL_EPSILON)) return PLANE_Y;
+ if ( (normal[2] >= 1.0 -NORMAL_EPSILON) ||
+ (normal[2] <= -1.0 + NORMAL_EPSILON)) return PLANE_Z;
+
+ ax = fabs(normal[0]);
+ ay = fabs(normal[1]);
+ az = fabs(normal[2]);
+
+ if (ax >= ay && ax >= az) return PLANE_ANYX;
+ if (ay >= ax && ay >= az) return PLANE_ANYY;
+ return PLANE_ANYZ;
+} //end of the function AAS_PlaneTypeForNormal
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_AddPlaneToHash(int planenum)
+{
+ int hash;
+ aas_plane_t *plane;
+
+ plane = &aasworld.planes[planenum];
+
+ hash = (int)fabs(plane->dist) / 8;
+ hash &= (PLANE_HASH_SIZE-1);
+
+ aas_planechain[planenum] = aas_hashplanes[hash];
+ aas_hashplanes[hash] = planenum;
+} //end of the function AAS_AddPlaneToHash
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_PlaneEqual(vec3_t normal, float dist, int planenum)
+{
+ float diff;
+
+ diff = dist - aasworld.planes[planenum].dist;
+ if (diff > -DIST_EPSILON && diff < DIST_EPSILON)
+ {
+ diff = normal[0] - aasworld.planes[planenum].normal[0];
+ if (diff > -NORMAL_EPSILON && diff < NORMAL_EPSILON)
+ {
+ diff = normal[1] - aasworld.planes[planenum].normal[1];
+ if (diff > -NORMAL_EPSILON && diff < NORMAL_EPSILON)
+ {
+ diff = normal[2] - aasworld.planes[planenum].normal[2];
+ if (diff > -NORMAL_EPSILON && diff < NORMAL_EPSILON)
+ {
+ return true;
+ } //end if
+ } //end if
+ } //end if
+ } //end if
+ return false;
+} //end of the function AAS_PlaneEqual
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean AAS_FindPlane(vec3_t normal, float dist, int *planenum)
+{
+ int i;
+
+ for (i = 0; i < aasworld.numplanes; i++)
+ {
+ if (AAS_PlaneEqual(normal, dist, i))
+ {
+ *planenum = i;
+ return true;
+ } //end if
+ } //end for
+ return false;
+} //end of the function AAS_FindPlane
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean AAS_FindHashedPlane(vec3_t normal, float dist, int *planenum)
+{
+ int i, p;
+ aas_plane_t *plane;
+ int hash, h;
+
+ hash = (int)fabs(dist) / 8;
+ hash &= (PLANE_HASH_SIZE-1);
+
+ //search the border bins as well
+ for (i = -1; i <= 1; i++)
+ {
+ h = (hash+i)&(PLANE_HASH_SIZE-1);
+ for (p = aas_hashplanes[h]; p >= 0; p = aas_planechain[p])
+ {
+ plane = &aasworld.planes[p];
+ if (AAS_PlaneEqual(normal, dist, p))
+ {
+ *planenum = p;
+ return true;
+ } //end if
+ } //end for
+ } //end for
+ return false;
+} //end of the function AAS_FindHashedPlane
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean AAS_GetPlane(vec3_t normal, vec_t dist, int *planenum)
+{
+ aas_plane_t *plane, temp;
+
+ //if (AAS_FindPlane(normal, dist, planenum)) return true;
+ if (AAS_FindHashedPlane(normal, dist, planenum)) return true;
+
+ if (aasworld.numplanes >= max_aas.max_planes-1)
+ {
+ Error("AAS_MAX_PLANES = %d", max_aas.max_planes);
+ } //end if
+
+#ifdef STOREPLANESDOUBLE
+ plane = &aasworld.planes[aasworld.numplanes];
+ VectorCopy(normal, plane->normal);
+ plane->dist = dist;
+ plane->type = (plane+1)->type = PlaneTypeForNormal(plane->normal);
+
+ VectorCopy(normal, (plane+1)->normal);
+ VectorNegate((plane+1)->normal, (plane+1)->normal);
+ (plane+1)->dist = -dist;
+
+ aasworld.numplanes += 2;
+
+ //allways put axial planes facing positive first
+ if (plane->type < 3)
+ {
+ if (plane->normal[0] < 0 || plane->normal[1] < 0 || plane->normal[2] < 0)
+ {
+ // flip order
+ temp = *plane;
+ *plane = *(plane+1);
+ *(plane+1) = temp;
+ *planenum = aasworld.numplanes - 1;
+ return false;
+ } //end if
+ } //end if
+ *planenum = aasworld.numplanes - 2;
+ //add the planes to the hash
+ AAS_AddPlaneToHash(aasworld.numplanes - 1);
+ AAS_AddPlaneToHash(aasworld.numplanes - 2);
+ return false;
+#else
+ plane = &aasworld.planes[aasworld.numplanes];
+ VectorCopy(normal, plane->normal);
+ plane->dist = dist;
+ plane->type = AAS_PlaneTypeForNormal(normal);
+
+ *planenum = aasworld.numplanes;
+ aasworld.numplanes++;
+ //add the plane to the hash
+ AAS_AddPlaneToHash(aasworld.numplanes - 1);
+ return false;
+#endif //STOREPLANESDOUBLE
+} //end of the function AAS_GetPlane
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean AAS_GetFace(winding_t *w, plane_t *p, int side, int *facenum)
+{
+ int edgenum, i, j;
+ aas_face_t *face;
+
+ //face zero is a dummy, because of the face index with negative numbers
+ if (aasworld.numfaces == 0) aasworld.numfaces = 1;
+
+ if (aasworld.numfaces >= max_aas.max_faces)
+ {
+ Error("AAS_MAX_FACES = %d", max_aas.max_faces);
+ } //end if
+ face = &aasworld.faces[aasworld.numfaces];
+ AAS_GetPlane(p->normal, p->dist, &face->planenum);
+ face->faceflags = 0;
+ face->firstedge = aasworld.edgeindexsize;
+ face->frontarea = 0;
+ face->backarea = 0;
+ face->numedges = 0;
+ for (i = 0; i < w->numpoints; i++)
+ {
+ if (aasworld.edgeindexsize >= max_aas.max_edgeindexsize)
+ {
+ Error("AAS_MAX_EDGEINDEXSIZE = %d", max_aas.max_edgeindexsize);
+ } //end if
+ j = (i+1) % w->numpoints;
+ AAS_GetEdge(w->p[i], w->p[j], &edgenum);
+ //if the edge wasn't degenerate
+ if (edgenum)
+ {
+ aasworld.edgeindex[aasworld.edgeindexsize++] = edgenum;
+ face->numedges++;
+ } //end if
+ else if (verbose)
+ {
+ Log_Write("AAS_GetFace: face %d had degenerate edge %d-%d\r\n",
+ aasworld.numfaces, i, j);
+ } //end else
+ } //end for
+ if (face->numedges < 1
+#ifdef NOTHREEVERTEXFACES
+ || face->numedges < 3
+#endif //NOTHREEVERTEXFACES
+ )
+ {
+ memset(&aasworld.faces[aasworld.numfaces], 0, sizeof(aas_face_t));
+ Log_Write("AAS_GetFace: face %d was tiny\r\n", aasworld.numfaces);
+ return false;
+ } //end if
+ *facenum = aasworld.numfaces;
+ aasworld.numfaces++;
+ return true;
+} //end of the function AAS_GetFace
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+/*
+qboolean AAS_GetFace(winding_t *w, plane_t *p, int side, int *facenum)
+{
+ aas_edgeindex_t edges[1024];
+ int planenum, numedges, i;
+ int j, edgenum;
+ qboolean foundplane, foundedges;
+ aas_face_t *face;
+
+ //face zero is a dummy, because of the face index with negative numbers
+ if (aasworld.numfaces == 0) aasworld.numfaces = 1;
+
+ foundplane = AAS_GetPlane(p->normal, p->dist, &planenum);
+
+ foundedges = true;
+ numedges = w->numpoints;
+ for (i = 0; i < w->numpoints; i++)
+ {
+ if (i >= 1024) Error("AAS_GetFace: more than %d edges\n", 1024);
+ foundedges &= AAS_GetEdge(w->p[i], w->p[(i+1 >= w->numpoints ? 0 : i+1)], &edges[i]);
+ } //end for
+
+ //FIXME: use portal number instead of a search
+ //if the plane and all edges already existed
+ if (foundplane && foundedges)
+ {
+ for (i = 0; i < aasworld.numfaces; i++)
+ {
+ face = &aasworld.faces[i];
+ if (planenum == face->planenum)
+ {
+ if (numedges == face->numedges)
+ {
+ for (j = 0; j < numedges; j++)
+ {
+ edgenum = abs(aasworld.edgeindex[face->firstedge + j]);
+ if (abs(edges[i]) != edgenum) break;
+ } //end for
+ if (j == numedges)
+ {
+ //jippy found the face
+ *facenum = -i;
+ return true;
+ } //end if
+ } //end if
+ } //end if
+ } //end for
+ } //end if
+ if (aasworld.numfaces >= max_aas.max_faces)
+ {
+ Error("AAS_MAX_FACES = %d", max_aas.max_faces);
+ } //end if
+ face = &aasworld.faces[aasworld.numfaces];
+ face->planenum = planenum;
+ face->faceflags = 0;
+ face->numedges = numedges;
+ face->firstedge = aasworld.edgeindexsize;
+ face->frontarea = 0;
+ face->backarea = 0;
+ for (i = 0; i < numedges; i++)
+ {
+ if (aasworld.edgeindexsize >= max_aas.max_edgeindexsize)
+ {
+ Error("AAS_MAX_EDGEINDEXSIZE = %d", max_aas.max_edgeindexsize);
+ } //end if
+ aasworld.edgeindex[aasworld.edgeindexsize++] = edges[i];
+ } //end for
+ *facenum = aasworld.numfaces;
+ aasworld.numfaces++;
+ return false;
+} //end of the function AAS_GetFace*/
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_StoreAreaSettings(tmp_areasettings_t *tmpareasettings)
+{
+ aas_areasettings_t *areasettings;
+
+ if (aasworld.numareasettings == 0) aasworld.numareasettings = 1;
+ areasettings = &aasworld.areasettings[aasworld.numareasettings++];
+ areasettings->areaflags = tmpareasettings->areaflags;
+ areasettings->presencetype = tmpareasettings->presencetype;
+ areasettings->contents = tmpareasettings->contents;
+ if (tmpareasettings->modelnum > AREACONTENTS_MAXMODELNUM)
+ Log_Print("WARNING: more than %d mover models\n", AREACONTENTS_MAXMODELNUM);
+ areasettings->contents |= (tmpareasettings->modelnum & AREACONTENTS_MAXMODELNUM) << AREACONTENTS_MODELNUMSHIFT;
+} //end of the function AAS_StoreAreaSettings
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_StoreArea(tmp_area_t *tmparea)
+{
+ int side, edgenum, i;
+ plane_t *plane;
+ tmp_face_t *tmpface;
+ aas_area_t *aasarea;
+ aas_edge_t *edge;
+ aas_face_t *aasface;
+ aas_faceindex_t aasfacenum;
+ vec3_t facecenter;
+ winding_t *w;
+
+ //when the area is merged go to the merged area
+ //FIXME: this isn't necessary anymore because the tree
+ // is refreshed after area merging
+ while(tmparea->mergedarea) tmparea = tmparea->mergedarea;
+ //
+ if (tmparea->invalid) Error("AAS_StoreArea: tried to store invalid area");
+ //if there is an aas area already stored for this tmp area
+ if (tmparea->aasareanum) return -tmparea->aasareanum;
+ //
+ if (aasworld.numareas >= max_aas.max_areas)
+ {
+ Error("AAS_MAX_AREAS = %d", max_aas.max_areas);
+ } //end if
+ //area zero is a dummy
+ if (aasworld.numareas == 0) aasworld.numareas = 1;
+ //create an area from this leaf
+ aasarea = &aasworld.areas[aasworld.numareas];
+ aasarea->areanum = aasworld.numareas;
+ aasarea->numfaces = 0;
+ aasarea->firstface = aasworld.faceindexsize;
+ ClearBounds(aasarea->mins, aasarea->maxs);
+ VectorClear(aasarea->center);
+ //
+// Log_Write("tmparea %d became aasarea %d\r\n", tmparea->areanum, aasarea->areanum);
+ //store the aas area number at the tmp area
+ tmparea->aasareanum = aasarea->areanum;
+ //
+ for (tmpface = tmparea->tmpfaces; tmpface; tmpface = tmpface->next[side])
+ {
+ side = tmpface->frontarea != tmparea;
+ //if there's an aas face created for the tmp face already
+ if (tmpface->aasfacenum)
+ {
+ //we're at the back of the face so use a negative index
+ aasfacenum = -tmpface->aasfacenum;
+#ifdef DEBUG
+ if (tmpface->aasfacenum < 0 || tmpface->aasfacenum > max_aas.max_faces)
+ {
+ Error("AAS_CreateTree_r: face number out of range");
+ } //end if
+#endif //DEBUG
+ aasface = &aasworld.faces[tmpface->aasfacenum];
+ aasface->backarea = aasarea->areanum;
+ } //end if
+ else
+ {
+ plane = &mapplanes[tmpface->planenum ^ side];
+ if (side)
+ {
+ w = tmpface->winding;
+ tmpface->winding = ReverseWinding(tmpface->winding);
+ } //end if
+ if (!AAS_GetFace(tmpface->winding, plane, 0, &aasfacenum)) continue;
+ if (side)
+ {
+ FreeWinding(tmpface->winding);
+ tmpface->winding = w;
+ } //end if
+ aasface = &aasworld.faces[aasfacenum];
+ aasface->frontarea = aasarea->areanum;
+ aasface->backarea = 0;
+ aasface->faceflags = tmpface->faceflags;
+ //set the face number at the tmp face
+ tmpface->aasfacenum = aasfacenum;
+ } //end else
+ //add face points to the area bounds and
+ //calculate the face 'center'
+ VectorClear(facecenter);
+ for (edgenum = 0; edgenum < aasface->numedges; edgenum++)
+ {
+ edge = &aasworld.edges[abs(aasworld.edgeindex[aasface->firstedge + edgenum])];
+ for (i = 0; i < 2; i++)
+ {
+ AddPointToBounds(aasworld.vertexes[edge->v[i]], aasarea->mins, aasarea->maxs);
+ VectorAdd(aasworld.vertexes[edge->v[i]], facecenter, facecenter);
+ } //end for
+ } //end for
+ VectorScale(facecenter, 1.0 / (aasface->numedges * 2.0), facecenter);
+ //add the face 'center' to the area 'center'
+ VectorAdd(aasarea->center, facecenter, aasarea->center);
+ //
+ if (aasworld.faceindexsize >= max_aas.max_faceindexsize)
+ {
+ Error("AAS_MAX_FACEINDEXSIZE = %d", max_aas.max_faceindexsize);
+ } //end if
+ aasworld.faceindex[aasworld.faceindexsize++] = aasfacenum;
+ aasarea->numfaces++;
+ } //end for
+ //if the area has no faces at all (return 0, = solid leaf)
+ if (!aasarea->numfaces) return 0;
+ //
+ VectorScale(aasarea->center, 1.0 / aasarea->numfaces, aasarea->center);
+ //Log_Write("area %d center %f %f %f\r\n", aasworld.numareas,
+ // aasarea->center[0], aasarea->center[1], aasarea->center[2]);
+ //store the area settings
+ AAS_StoreAreaSettings(tmparea->settings);
+ //
+ //Log_Write("tmp area %d became aas area %d\r\n", tmpareanum, aasarea->areanum);
+ qprintf("\r%6d", aasarea->areanum);
+ //
+ aasworld.numareas++;
+ return -(aasworld.numareas - 1);
+} //end of the function AAS_StoreArea
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int AAS_StoreTree_r(tmp_node_t *tmpnode)
+{
+ int aasnodenum;
+ plane_t *plane;
+ aas_node_t *aasnode;
+
+ //if it is a solid leaf
+ if (!tmpnode) return 0;
+ //negative so it's an area
+ if (tmpnode->tmparea) return AAS_StoreArea(tmpnode->tmparea);
+ //it's another node
+ //the first node is a dummy
+ if (aasworld.numnodes == 0) aasworld.numnodes = 1;
+ if (aasworld.numnodes >= max_aas.max_nodes)
+ {
+ Error("AAS_MAX_NODES = %d", max_aas.max_nodes);
+ } //end if
+ aasnodenum = aasworld.numnodes;
+ aasnode = &aasworld.nodes[aasworld.numnodes++];
+ plane = &mapplanes[tmpnode->planenum];
+ AAS_GetPlane(plane->normal, plane->dist, &aasnode->planenum);
+ aasnode->children[0] = AAS_StoreTree_r(tmpnode->children[0]);
+ aasnode->children[1] = AAS_StoreTree_r(tmpnode->children[1]);
+ return aasnodenum;
+} //end of the function AAS_StoreTree_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_StoreBoundingBoxes(void)
+{
+ if (cfg.numbboxes > max_aas.max_bboxes)
+ {
+ Error("more than %d bounding boxes", max_aas.max_bboxes);
+ } //end if
+ aasworld.numbboxes = cfg.numbboxes;
+ memcpy(aasworld.bboxes, cfg.bboxes, cfg.numbboxes * sizeof(aas_bbox_t));
+} //end of the function AAS_StoreBoundingBoxes
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_StoreFile(char *filename)
+{
+ AAS_AllocMaxAAS();
+
+ Log_Write("AAS_StoreFile\r\n");
+ //
+ AAS_StoreBoundingBoxes();
+ //
+ qprintf("%6d areas stored", 0);
+ //start with node 1 because node zero is a dummy
+ AAS_StoreTree_r(tmpaasworld.nodes);
+ qprintf("\n");
+ Log_Write("%6d areas stored\r\n", aasworld.numareas);
+ aasworld.loaded = true;
+} //end of the function AAS_StoreFile
diff --git a/code/bspc/aas_store.h b/code/bspc/aas_store.h
new file mode 100755
index 0000000..26957e4
--- /dev/null
+++ b/code/bspc/aas_store.h
@@ -0,0 +1,107 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#define AAS_MAX_BBOXES 5
+#define AAS_MAX_VERTEXES 512000
+#define AAS_MAX_PLANES 65536
+#define AAS_MAX_EDGES 512000
+#define AAS_MAX_EDGEINDEXSIZE 512000
+#define AAS_MAX_FACES 512000
+#define AAS_MAX_FACEINDEXSIZE 512000
+#define AAS_MAX_AREAS 65536
+#define AAS_MAX_AREASETTINGS 65536
+#define AAS_MAX_REACHABILITYSIZE 65536
+#define AAS_MAX_NODES 256000
+#define AAS_MAX_PORTALS 65536
+#define AAS_MAX_PORTALINDEXSIZE 65536
+#define AAS_MAX_CLUSTERS 65536
+
+#define BSPCINCLUDE
+#include "../game/be_aas.h"
+#include "../botlib/be_aas_def.h"
+
+/*
+typedef struct bspc_aas_s
+{
+ int loaded;
+ int initialized; //true when AAS has been initialized
+ int savefile; //set true when file should be saved
+ //bounding boxes
+ int numbboxes;
+ aas_bbox_t *bboxes;
+ //vertexes
+ int numvertexes;
+ aas_vertex_t *vertexes;
+ //planes
+ int numplanes;
+ aas_plane_t *planes;
+ //edges
+ int numedges;
+ aas_edge_t *edges;
+ //edge index
+ int edgeindexsize;
+ aas_edgeindex_t *edgeindex;
+ //faces
+ int numfaces;
+ aas_face_t *faces;
+ //face index
+ int faceindexsize;
+ aas_faceindex_t *faceindex;
+ //convex areas
+ int numareas;
+ aas_area_t *areas;
+ //convex area settings
+ int numareasettings;
+ aas_areasettings_t *areasettings;
+ //reachablity list
+ int reachabilitysize;
+ aas_reachability_t *reachability;
+ //nodes of the bsp tree
+ int numnodes;
+ aas_node_t *nodes;
+ //cluster portals
+ int numportals;
+ aas_portal_t *portals;
+ //cluster portal index
+ int portalindexsize;
+ aas_portalindex_t *portalindex;
+ //clusters
+ int numclusters;
+ aas_cluster_t *clusters;
+ //
+ int numreachabilityareas;
+ float reachabilitytime;
+} bspc_aas_t;
+
+extern bspc_aas_t aasworld;
+//*/
+
+extern aas_t aasworld;
+
+//stores the AAS file from the temporary AAS
+void AAS_StoreFile(char *filename);
+//returns a number of the given plane
+qboolean AAS_FindPlane(vec3_t normal, float dist, int *planenum);
+//allocates the maximum AAS memory for storage
+void AAS_AllocMaxAAS(void);
+//frees the maximum AAS memory for storage
+void AAS_FreeMaxAAS(void);
diff --git a/code/bspc/aasfile.h b/code/bspc/aasfile.h
new file mode 100755
index 0000000..7ed8677
--- /dev/null
+++ b/code/bspc/aasfile.h
@@ -0,0 +1,252 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+
+//NOTE: int = default signed
+// default long
+
+#define AASID (('S'<<24)+('A'<<16)+('A'<<8)+'E')
+#define AASVERSION_OLD 4
+#define AASVERSION 5
+
+//presence types
+#define PRESENCE_NONE 1
+#define PRESENCE_NORMAL 2
+#define PRESENCE_CROUCH 4
+
+//travel types
+#define MAX_TRAVELTYPES 32
+#define TRAVEL_INVALID 1 //temporary not possible
+#define TRAVEL_WALK 2 //walking
+#define TRAVEL_CROUCH 3 //crouching
+#define TRAVEL_BARRIERJUMP 4 //jumping onto a barrier
+#define TRAVEL_JUMP 5 //jumping
+#define TRAVEL_LADDER 6 //climbing a ladder
+#define TRAVEL_WALKOFFLEDGE 7 //walking of a ledge
+#define TRAVEL_SWIM 8 //swimming
+#define TRAVEL_WATERJUMP 9 //jump out of the water
+#define TRAVEL_TELEPORT 10 //teleportation
+#define TRAVEL_ELEVATOR 11 //travel by elevator
+#define TRAVEL_ROCKETJUMP 12 //rocket jumping required for travel
+#define TRAVEL_BFGJUMP 13 //bfg jumping required for travel
+#define TRAVEL_GRAPPLEHOOK 14 //grappling hook required for travel
+#define TRAVEL_DOUBLEJUMP 15 //double jump
+#define TRAVEL_RAMPJUMP 16 //ramp jump
+#define TRAVEL_STRAFEJUMP 17 //strafe jump
+#define TRAVEL_JUMPPAD 18 //jump pad
+#define TRAVEL_FUNCBOB 19 //func bob
+
+//face flags
+#define FACE_SOLID 1 //just solid at the other side
+#define FACE_LADDER 2 //ladder
+#define FACE_GROUND 4 //standing on ground when in this face
+#define FACE_GAP 8 //gap in the ground
+#define FACE_LIQUID 16
+#define FACE_LIQUIDSURFACE 32
+
+//area contents
+#define AREACONTENTS_WATER 1
+#define AREACONTENTS_LAVA 2
+#define AREACONTENTS_SLIME 4
+#define AREACONTENTS_CLUSTERPORTAL 8
+#define AREACONTENTS_TELEPORTAL 16
+#define AREACONTENTS_ROUTEPORTAL 32
+#define AREACONTENTS_TELEPORTER 64
+#define AREACONTENTS_JUMPPAD 128
+#define AREACONTENTS_DONOTENTER 256
+#define AREACONTENTS_VIEWPORTAL 512
+
+//area flags
+#define AREA_GROUNDED 1 //bot can stand on the ground
+#define AREA_LADDER 2 //area contains one or more ladder faces
+#define AREA_LIQUID 4 //area contains a liquid
+
+//aas file header lumps
+#define AAS_LUMPS 14
+#define AASLUMP_BBOXES 0
+#define AASLUMP_VERTEXES 1
+#define AASLUMP_PLANES 2
+#define AASLUMP_EDGES 3
+#define AASLUMP_EDGEINDEX 4
+#define AASLUMP_FACES 5
+#define AASLUMP_FACEINDEX 6
+#define AASLUMP_AREAS 7
+#define AASLUMP_AREASETTINGS 8
+#define AASLUMP_REACHABILITY 9
+#define AASLUMP_NODES 10
+#define AASLUMP_PORTALS 11
+#define AASLUMP_PORTALINDEX 12
+#define AASLUMP_CLUSTERS 13
+
+//========== bounding box =========
+
+//bounding box
+typedef struct aas_bbox_s
+{
+ int presencetype;
+ int flags;
+ vec3_t mins, maxs;
+} aas_bbox_t;
+
+//============ settings ===========
+
+//reachability to another area
+typedef struct aas_reachability_s
+{
+ int areanum; //number of the reachable area
+ int facenum; //number of the face towards the other area
+ int edgenum; //number of the edge towards the other area
+ vec3_t start; //start point of inter area movement
+ vec3_t end; //end point of inter area movement
+ int traveltype; //type of travel required to get to the area
+ unsigned short int traveltime;//travel time of the inter area movement
+} aas_reachability_t;
+
+//area settings
+typedef struct aas_areasettings_s
+{
+ //could also add all kind of statistic fields
+ int contents; //contents of the convex area
+ int areaflags; //several area flags
+ int presencetype; //how a bot can be present in this convex area
+ int cluster; //cluster the area belongs to, if negative it's a portal
+ int clusterareanum; //number of the area in the cluster
+ int numreachableareas; //number of reachable areas from this one
+ int firstreachablearea; //first reachable area in the reachable area index
+} aas_areasettings_t;
+
+//cluster portal
+typedef struct aas_portal_s
+{
+ int areanum; //area that is the actual portal
+ int frontcluster; //cluster at front of portal
+ int backcluster; //cluster at back of portal
+ int clusterareanum[2]; //number of the area in the front and back cluster
+} aas_portal_t;
+
+//cluster portal index
+typedef int aas_portalindex_t;
+
+//cluster
+typedef struct aas_cluster_s
+{
+ int numareas; //number of areas in the cluster
+ int numreachabilityareas; //number of areas with reachabilities
+ int numportals; //number of cluster portals
+ int firstportal; //first cluster portal in the index
+} aas_cluster_t;
+
+//============ 3d definition ============
+
+typedef vec3_t aas_vertex_t;
+
+//just a plane in the third dimension
+typedef struct aas_plane_s
+{
+ vec3_t normal; //normal vector of the plane
+ float dist; //distance of the plane (normal vector * distance = point in plane)
+ int type;
+} aas_plane_t;
+
+//edge
+typedef struct aas_edge_s
+{
+ int v[2]; //numbers of the vertexes of this edge
+} aas_edge_t;
+
+//edge index, negative if vertexes are reversed
+typedef int aas_edgeindex_t;
+
+//a face bounds a convex area, often it will also seperate two convex areas
+typedef struct aas_face_s
+{
+ int planenum; //number of the plane this face is in
+ int faceflags; //face flags (no use to create face settings for just this field)
+ int numedges; //number of edges in the boundary of the face
+ int firstedge; //first edge in the edge index
+ int frontarea; //convex area at the front of this face
+ int backarea; //convex area at the back of this face
+} aas_face_t;
+
+//face index, stores a negative index if backside of face
+typedef int aas_faceindex_t;
+
+//convex area with a boundary of faces
+typedef struct aas_area_s
+{
+ int areanum; //number of this area
+ //3d definition
+ int numfaces; //number of faces used for the boundary of the convex area
+ int firstface; //first face in the face index used for the boundary of the convex area
+ vec3_t mins; //mins of the convex area
+ vec3_t maxs; //maxs of the convex area
+ vec3_t center; //'center' of the convex area
+} aas_area_t;
+
+//nodes of the bsp tree
+typedef struct aas_node_s
+{
+ int planenum;
+ int children[2]; //child nodes of this node, or convex areas as leaves when negative
+ //when a child is zero it's a solid leaf
+} aas_node_t;
+
+//=========== aas file ===============
+
+//header lump
+typedef struct
+{
+ int fileofs;
+ int filelen;
+} aas_lump_t;
+
+//aas file header
+typedef struct aas_header_s
+{
+ int ident;
+ int version;
+ int bspchecksum;
+ //data entries
+ aas_lump_t lumps[AAS_LUMPS];
+} aas_header_t;
+
+
+//====== additional information ======
+/*
+
+- when a node child is a solid leaf the node child number is zero
+- two adjacent areas (sharing a plane at opposite sides) share a face
+ this face is a portal between the areas
+- when an area uses a face from the faceindex with a positive index
+ then the face plane normal points into the area
+- the face edges are stored counter clockwise using the edgeindex
+- two adjacent convex areas (sharing a face) only share One face
+ this is a simple result of the areas being convex
+- the convex areas can't have a mixture of ground and gap faces
+ other mixtures of faces in one area are allowed
+- areas with the AREACONTENTS_CLUSTERPORTAL in the settings have
+ cluster number zero
+- edge zero is a dummy
+- face zero is a dummy
+- area zero is a dummy
+- node zero is a dummy
+*/
diff --git a/code/bspc/be_aas_bspc.c b/code/bspc/be_aas_bspc.c
new file mode 100755
index 0000000..127549c
--- /dev/null
+++ b/code/bspc/be_aas_bspc.c
@@ -0,0 +1,292 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "../game/q_shared.h"
+#include "../bspc/l_log.h"
+#include "../bspc/l_qfiles.h"
+#include "../botlib/l_memory.h"
+#include "../botlib/l_script.h"
+#include "../botlib/l_precomp.h"
+#include "../botlib/l_struct.h"
+#include "../botlib/aasfile.h"
+#include "../game/botlib.h"
+#include "../game/be_aas.h"
+#include "../botlib/be_aas_def.h"
+#include "../qcommon/cm_public.h"
+
+//#define BSPC
+
+extern botlib_import_t botimport;
+extern qboolean capsule_collision;
+
+botlib_import_t botimport;
+clipHandle_t worldmodel;
+
+void Error (char *error, ...);
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_Error(char *fmt, ...)
+{
+ va_list argptr;
+ char text[1024];
+
+ va_start(argptr, fmt);
+ vsprintf(text, fmt, argptr);
+ va_end(argptr);
+
+ Error(text);
+} //end of the function AAS_Error
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int Sys_MilliSeconds(void)
+{
+ return clock() * 1000 / CLOCKS_PER_SEC;
+} //end of the function Sys_MilliSeconds
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_DebugLine(vec3_t start, vec3_t end, int color)
+{
+} //end of the function AAS_DebugLine
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ClearShownDebugLines(void)
+{
+} //end of the function AAS_ClearShownDebugLines
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+char *BotImport_BSPEntityData(void)
+{
+ return CM_EntityString();
+} //end of the function AAS_GetEntityData
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotImport_Trace(bsp_trace_t *bsptrace, vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int passent, int contentmask)
+{
+ trace_t result;
+
+ CM_BoxTrace(&result, start, end, mins, maxs, worldmodel, contentmask, capsule_collision);
+
+ bsptrace->allsolid = result.allsolid;
+ bsptrace->contents = result.contents;
+ VectorCopy(result.endpos, bsptrace->endpos);
+ bsptrace->ent = result.entityNum;
+ bsptrace->fraction = result.fraction;
+ bsptrace->exp_dist = 0;
+ bsptrace->plane.dist = result.plane.dist;
+ VectorCopy(result.plane.normal, bsptrace->plane.normal);
+ bsptrace->plane.signbits = result.plane.signbits;
+ bsptrace->plane.type = result.plane.type;
+ bsptrace->sidenum = 0;
+ bsptrace->startsolid = result.startsolid;
+ bsptrace->surface.flags = result.surfaceFlags;
+} //end of the function BotImport_Trace
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BotImport_PointContents(vec3_t p)
+{
+ return CM_PointContents(p, worldmodel);
+} //end of the function BotImport_PointContents
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void *BotImport_GetMemory(int size)
+{
+ return GetMemory(size);
+} //end of the function BotImport_GetMemory
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotImport_Print(int type, char *fmt, ...)
+{
+ va_list argptr;
+ char buf[1024];
+
+ va_start(argptr, fmt);
+ vsprintf(buf, fmt, argptr);
+ printf(buf);
+ if (buf[0] != '\r') Log_Write(buf);
+ va_end(argptr);
+} //end of the function BotImport_Print
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BotImport_BSPModelMinsMaxsOrigin(int modelnum, vec3_t angles, vec3_t outmins, vec3_t outmaxs, vec3_t origin)
+{
+ clipHandle_t h;
+ vec3_t mins, maxs;
+ float max;
+ int i;
+
+ h = CM_InlineModel(modelnum);
+ CM_ModelBounds(h, mins, maxs);
+ //if the model is rotated
+ if ((angles[0] || angles[1] || angles[2]))
+ { // expand for rotation
+
+ max = RadiusFromBounds(mins, maxs);
+ for (i = 0; i < 3; i++)
+ {
+ mins[i] = (mins[i] + maxs[i]) * 0.5 - max;
+ maxs[i] = (mins[i] + maxs[i]) * 0.5 + max;
+ } //end for
+ } //end if
+ if (outmins) VectorCopy(mins, outmins);
+ if (outmaxs) VectorCopy(maxs, outmaxs);
+ if (origin) VectorClear(origin);
+} //end of the function BotImport_BSPModelMinsMaxsOrigin
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Com_DPrintf(char *fmt, ...)
+{
+ va_list argptr;
+ char buf[1024];
+
+ va_start(argptr, fmt);
+ vsprintf(buf, fmt, argptr);
+ printf(buf);
+ if (buf[0] != '\r') Log_Write(buf);
+ va_end(argptr);
+} //end of the function Com_DPrintf
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int COM_Compress( char *data_p ) {
+ return strlen(data_p);
+}
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Com_Memset (void* dest, const int val, const size_t count) {
+ memset(dest, val, count);
+}
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Com_Memcpy (void* dest, const void* src, const size_t count) {
+ memcpy(dest, src, count);
+}
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_InitBotImport(void)
+{
+ botimport.BSPEntityData = BotImport_BSPEntityData;
+ botimport.GetMemory = BotImport_GetMemory;
+ botimport.FreeMemory = FreeMemory;
+ botimport.Trace = BotImport_Trace;
+ botimport.PointContents = BotImport_PointContents;
+ botimport.Print = BotImport_Print;
+ botimport.BSPModelMinsMaxsOrigin = BotImport_BSPModelMinsMaxsOrigin;
+} //end of the function AAS_InitBotImport
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_CalcReachAndClusters(struct quakefile_s *qf)
+{
+ float time;
+
+ Log_Print("loading collision map...\n");
+ //
+ if (!qf->pakfile[0]) strcpy(qf->pakfile, qf->filename);
+ //load the map
+ CM_LoadMap((char *) qf, qfalse, &aasworld.bspchecksum);
+ //get a handle to the world model
+ worldmodel = CM_InlineModel(0); // 0 = world, 1 + are bmodels
+ //initialize bot import structure
+ AAS_InitBotImport();
+ //load the BSP entity string
+ AAS_LoadBSPFile();
+ //init physics settings
+ AAS_InitSettings();
+ //initialize AAS link heap
+ AAS_InitAASLinkHeap();
+ //initialize the AAS linked entities for the new map
+ AAS_InitAASLinkedEntities();
+ //reset all reachabilities and clusters
+ aasworld.reachabilitysize = 0;
+ aasworld.numclusters = 0;
+ //set all view portals as cluster portals in case we re-calculate the reachabilities and clusters (with -reach)
+ AAS_SetViewPortalsAsClusterPortals();
+ //calculate reachabilities
+ AAS_InitReachability();
+ time = 0;
+ while(AAS_ContinueInitReachability(time)) time++;
+ //calculate clusters
+ AAS_InitClustering();
+} //end of the function AAS_CalcReachAndClusters
diff --git a/code/bspc/be_aas_bspc.h b/code/bspc/be_aas_bspc.h
new file mode 100755
index 0000000..72e488a
--- /dev/null
+++ b/code/bspc/be_aas_bspc.h
@@ -0,0 +1,23 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+void AAS_CalcReachAndClusters(struct quakefile_s *qf);
diff --git a/code/bspc/brushbsp.c b/code/bspc/brushbsp.c
new file mode 100755
index 0000000..22cb0dd
--- /dev/null
+++ b/code/bspc/brushbsp.c
@@ -0,0 +1,1871 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+#include "l_mem.h"
+#include "../botlib/aasfile.h"
+#include "aas_store.h"
+#include "aas_cfg.h"
+
+#include <assert.h>
+
+/*
+each side has a count of the other sides it splits
+
+the best split will be the one that minimizes the total split counts
+of all remaining sides
+
+precalc side on plane table
+
+evaluate split side
+{
+cost = 0
+for all sides
+ for all sides
+ get
+ if side splits side and splitside is on same child
+ cost++;
+}
+*/
+
+int c_nodes;
+int c_nonvis;
+int c_active_brushes;
+int c_solidleafnodes;
+int c_totalsides;
+int c_brushmemory;
+int c_peak_brushmemory;
+int c_nodememory;
+int c_peak_totalbspmemory;
+
+// if a brush just barely pokes onto the other side,
+// let it slide by without chopping
+#define PLANESIDE_EPSILON 0.001
+//0.1
+
+//#ifdef DEBUG
+typedef struct cname_s
+{
+ int value;
+ char *name;
+} cname_t;
+
+cname_t contentnames[] =
+{
+ {CONTENTS_SOLID,"CONTENTS_SOLID"},
+ {CONTENTS_WINDOW,"CONTENTS_WINDOW"},
+ {CONTENTS_AUX,"CONTENTS_AUX"},
+ {CONTENTS_LAVA,"CONTENTS_LAVA"},
+ {CONTENTS_SLIME,"CONTENTS_SLIME"},
+ {CONTENTS_WATER,"CONTENTS_WATER"},
+ {CONTENTS_MIST,"CONTENTS_MIST"},
+ {LAST_VISIBLE_CONTENTS,"LAST_VISIBLE_CONTENTS"},
+
+ {CONTENTS_AREAPORTAL,"CONTENTS_AREAPORTAL"},
+ {CONTENTS_PLAYERCLIP,"CONTENTS_PLAYERCLIP"},
+ {CONTENTS_MONSTERCLIP,"CONTENTS_MONSTERCLIP"},
+ {CONTENTS_CURRENT_0,"CONTENTS_CURRENT_0"},
+ {CONTENTS_CURRENT_90,"CONTENTS_CURRENT_90"},
+ {CONTENTS_CURRENT_180,"CONTENTS_CURRENT_180"},
+ {CONTENTS_CURRENT_270,"CONTENTS_CURRENT_270"},
+ {CONTENTS_CURRENT_UP,"CONTENTS_CURRENT_UP"},
+ {CONTENTS_CURRENT_DOWN,"CONTENTS_CURRENT_DOWN"},
+ {CONTENTS_ORIGIN,"CONTENTS_ORIGIN"},
+ {CONTENTS_MONSTER,"CONTENTS_MONSTER"},
+ {CONTENTS_DEADMONSTER,"CONTENTS_DEADMONSTER"},
+ {CONTENTS_DETAIL,"CONTENTS_DETAIL"},
+ {CONTENTS_Q2TRANSLUCENT,"CONTENTS_TRANSLUCENT"},
+ {CONTENTS_LADDER,"CONTENTS_LADDER"},
+ {0, 0}
+};
+
+void PrintContents(int contents)
+{
+ int i;
+
+ for (i = 0; contentnames[i].value; i++)
+ {
+ if (contents & contentnames[i].value)
+ {
+ Log_Write("%s,", contentnames[i].name);
+ } //end if
+ } //end for
+} //end of the function PrintContents
+
+//#endif DEBUG
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ResetBrushBSP(void)
+{
+ c_nodes = 0;
+ c_nonvis = 0;
+ c_active_brushes = 0;
+ c_solidleafnodes = 0;
+ c_totalsides = 0;
+ c_brushmemory = 0;
+ c_peak_brushmemory = 0;
+ c_nodememory = 0;
+ c_peak_totalbspmemory = 0;
+} //end of the function ResetBrushBSP
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void FindBrushInTree (node_t *node, int brushnum)
+{
+ bspbrush_t *b;
+
+ if (node->planenum == PLANENUM_LEAF)
+ {
+ for (b=node->brushlist ; b ; b=b->next)
+ if (b->original->brushnum == brushnum)
+ Log_Print ("here\n");
+ return;
+ }
+ FindBrushInTree(node->children[0], brushnum);
+ FindBrushInTree(node->children[1], brushnum);
+} //end of the function FindBrushInTree
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void DrawBrushList (bspbrush_t *brush, node_t *node)
+{
+ int i;
+ side_t *s;
+
+ GLS_BeginScene ();
+ for ( ; brush ; brush=brush->next)
+ {
+ for (i=0 ; i<brush->numsides ; i++)
+ {
+ s = &brush->sides[i];
+ if (!s->winding)
+ continue;
+ if (s->texinfo == TEXINFO_NODE)
+ GLS_Winding (s->winding, 1);
+ else if (!(s->flags & SFL_VISIBLE))
+ GLS_Winding (s->winding, 2);
+ else
+ GLS_Winding (s->winding, 0);
+ }
+ }
+ GLS_EndScene ();
+} //end of the function DrawBrushList
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void WriteBrushList (char *name, bspbrush_t *brush, qboolean onlyvis)
+{
+ int i;
+ side_t *s;
+ FILE *f;
+
+ qprintf ("writing %s\n", name);
+ f = SafeOpenWrite (name);
+
+ for ( ; brush ; brush=brush->next)
+ {
+ for (i=0 ; i<brush->numsides ; i++)
+ {
+ s = &brush->sides[i];
+ if (!s->winding)
+ continue;
+ if (onlyvis && !(s->flags & SFL_VISIBLE))
+ continue;
+ OutputWinding (brush->sides[i].winding, f);
+ }
+ }
+
+ fclose (f);
+} //end of the function WriteBrushList
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void PrintBrush (bspbrush_t *brush)
+{
+ int i;
+
+ printf ("brush: %p\n", brush);
+ for (i=0;i<brush->numsides ; i++)
+ {
+ pw(brush->sides[i].winding);
+ printf ("\n");
+ } //end for
+} //end of the function PrintBrush
+//===========================================================================
+// Sets the mins/maxs based on the windings
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BoundBrush (bspbrush_t *brush)
+{
+ int i, j;
+ winding_t *w;
+
+ ClearBounds (brush->mins, brush->maxs);
+ for (i=0 ; i<brush->numsides ; i++)
+ {
+ w = brush->sides[i].winding;
+ if (!w)
+ continue;
+ for (j=0 ; j<w->numpoints ; j++)
+ AddPointToBounds (w->p[j], brush->mins, brush->maxs);
+ }
+} //end of the function BoundBrush
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void CreateBrushWindings (bspbrush_t *brush)
+{
+ int i, j;
+ winding_t *w;
+ side_t *side;
+ plane_t *plane;
+
+ for (i=0 ; i<brush->numsides ; i++)
+ {
+ side = &brush->sides[i];
+ plane = &mapplanes[side->planenum];
+ w = BaseWindingForPlane (plane->normal, plane->dist);
+ for (j=0 ; j<brush->numsides && w; j++)
+ {
+ if (i == j)
+ continue;
+ if (brush->sides[j].flags & SFL_BEVEL)
+ continue;
+ plane = &mapplanes[brush->sides[j].planenum^1];
+ ChopWindingInPlace (&w, plane->normal, plane->dist, 0); //CLIP_EPSILON);
+ }
+
+ side->winding = w;
+ }
+
+ BoundBrush (brush);
+} //end of the function CreateBrushWindings
+//===========================================================================
+// Creates a new axial brush
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bspbrush_t *BrushFromBounds (vec3_t mins, vec3_t maxs)
+{
+ bspbrush_t *b;
+ int i;
+ vec3_t normal;
+ vec_t dist;
+
+ b = AllocBrush (6);
+ b->numsides = 6;
+ for (i=0 ; i<3 ; i++)
+ {
+ VectorClear (normal);
+ normal[i] = 1;
+ dist = maxs[i];
+ b->sides[i].planenum = FindFloatPlane (normal, dist);
+
+ normal[i] = -1;
+ dist = -mins[i];
+ b->sides[3+i].planenum = FindFloatPlane (normal, dist);
+ }
+
+ CreateBrushWindings (b);
+
+ return b;
+} //end of the function BrushFromBounds
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BrushOutOfBounds(bspbrush_t *brush, vec3_t mins, vec3_t maxs, float epsilon)
+{
+ int i, j, n;
+ winding_t *w;
+ side_t *side;
+
+ for (i = 0; i < brush->numsides; i++)
+ {
+ side = &brush->sides[i];
+ w = side->winding;
+ for (j = 0; j < w->numpoints; j++)
+ {
+ for (n = 0; n < 3; n++)
+ {
+ if (w->p[j][n] < (mins[n] + epsilon) || w->p[j][n] > (maxs[n] - epsilon)) return true;
+ } //end for
+ } //end for
+ } //end for
+ return false;
+} //end of the function BrushOutOfBounds
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+vec_t BrushVolume (bspbrush_t *brush)
+{
+ int i;
+ winding_t *w;
+ vec3_t corner;
+ vec_t d, area, volume;
+ plane_t *plane;
+
+ if (!brush) return 0;
+
+ // grab the first valid point as the corner
+ w = NULL;
+ for (i = 0; i < brush->numsides; i++)
+ {
+ w = brush->sides[i].winding;
+ if (w) break;
+ } //end for
+ if (!w) return 0;
+ VectorCopy (w->p[0], corner);
+
+ // make tetrahedrons to all other faces
+ volume = 0;
+ for ( ; i < brush->numsides; i++)
+ {
+ w = brush->sides[i].winding;
+ if (!w) continue;
+ plane = &mapplanes[brush->sides[i].planenum];
+ d = -(DotProduct (corner, plane->normal) - plane->dist);
+ area = WindingArea(w);
+ volume += d * area;
+ } //end for
+
+ volume /= 3;
+ return volume;
+} //end of the function BrushVolume
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int CountBrushList (bspbrush_t *brushes)
+{
+ int c;
+
+ c = 0;
+ for ( ; brushes; brushes = brushes->next) c++;
+ return c;
+} //end of the function CountBrushList
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+node_t *AllocNode (void)
+{
+ node_t *node;
+
+ node = GetMemory(sizeof(*node));
+ memset (node, 0, sizeof(*node));
+ if (numthreads == 1)
+ {
+ c_nodememory += MemorySize(node);
+ } //end if
+ return node;
+} //end of the function AllocNode
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bspbrush_t *AllocBrush (int numsides)
+{
+ bspbrush_t *bb;
+ int c;
+
+ c = (int)&(((bspbrush_t *)0)->sides[numsides]);
+ bb = GetMemory(c);
+ memset (bb, 0, c);
+ if (numthreads == 1)
+ {
+ c_active_brushes++;
+ c_brushmemory += MemorySize(bb);
+ if (c_brushmemory > c_peak_brushmemory)
+ c_peak_brushmemory = c_brushmemory;
+ } //end if
+ return bb;
+} //end of the function AllocBrush
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void FreeBrush (bspbrush_t *brushes)
+{
+ int i;
+
+ for (i=0 ; i<brushes->numsides ; i++)
+ if (brushes->sides[i].winding)
+ FreeWinding(brushes->sides[i].winding);
+ if (numthreads == 1)
+ {
+ c_active_brushes--;
+ c_brushmemory -= MemorySize(brushes);
+ if (c_brushmemory < 0) c_brushmemory = 0;
+ } //end if
+ FreeMemory(brushes);
+} //end of the function FreeBrush
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void FreeBrushList (bspbrush_t *brushes)
+{
+ bspbrush_t *next;
+
+ for ( ; brushes; brushes = next)
+ {
+ next = brushes->next;
+
+ FreeBrush(brushes);
+ } //end for
+} //end of the function FreeBrushList
+//===========================================================================
+// Duplicates the brush, the sides, and the windings
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bspbrush_t *CopyBrush (bspbrush_t *brush)
+{
+ bspbrush_t *newbrush;
+ int size;
+ int i;
+
+ size = (int)&(((bspbrush_t *)0)->sides[brush->numsides]);
+
+ newbrush = AllocBrush (brush->numsides);
+ memcpy (newbrush, brush, size);
+
+ for (i=0 ; i<brush->numsides ; i++)
+ {
+ if (brush->sides[i].winding)
+ newbrush->sides[i].winding = CopyWinding (brush->sides[i].winding);
+ }
+
+ return newbrush;
+} //end of the function CopyBrush
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+node_t *PointInLeaf (node_t *node, vec3_t point)
+{
+ vec_t d;
+ plane_t *plane;
+
+ while (node->planenum != PLANENUM_LEAF)
+ {
+ plane = &mapplanes[node->planenum];
+ d = DotProduct (point, plane->normal) - plane->dist;
+ if (d > 0)
+ node = node->children[0];
+ else
+ node = node->children[1];
+ }
+
+ return node;
+} //end of the function PointInLeaf
+//===========================================================================
+// Returns PSIDE_FRONT, PSIDE_BACK, or PSIDE_BOTH
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+#if 0
+int BoxOnPlaneSide (vec3_t mins, vec3_t maxs, plane_t *plane)
+{
+ int side;
+ int i;
+ vec3_t corners[2];
+ vec_t dist1, dist2;
+
+ // axial planes are easy
+ if (plane->type < 3)
+ {
+ side = 0;
+ if (maxs[plane->type] > plane->dist+PLANESIDE_EPSILON)
+ side |= PSIDE_FRONT;
+ if (mins[plane->type] < plane->dist-PLANESIDE_EPSILON)
+ side |= PSIDE_BACK;
+ return side;
+ }
+
+ // create the proper leading and trailing verts for the box
+
+ for (i=0 ; i<3 ; i++)
+ {
+ if (plane->normal[i] < 0)
+ {
+ corners[0][i] = mins[i];
+ corners[1][i] = maxs[i];
+ }
+ else
+ {
+ corners[1][i] = mins[i];
+ corners[0][i] = maxs[i];
+ }
+ }
+
+ dist1 = DotProduct (plane->normal, corners[0]) - plane->dist;
+ dist2 = DotProduct (plane->normal, corners[1]) - plane->dist;
+ side = 0;
+ if (dist1 >= PLANESIDE_EPSILON)
+ side = PSIDE_FRONT;
+ if (dist2 < PLANESIDE_EPSILON)
+ side |= PSIDE_BACK;
+
+ return side;
+}
+#else
+int BoxOnPlaneSide (vec3_t emins, vec3_t emaxs, plane_t *p)
+{
+ float dist1, dist2;
+ int sides;
+
+ // axial planes are easy
+ if (p->type < 3)
+ {
+ sides = 0;
+ if (emaxs[p->type] > p->dist+PLANESIDE_EPSILON) sides |= PSIDE_FRONT;
+ if (emins[p->type] < p->dist-PLANESIDE_EPSILON) sides |= PSIDE_BACK;
+ return sides;
+ } //end if
+
+// general case
+ switch (p->signbits)
+ {
+ case 0:
+ dist1 = p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2];
+ dist2 = p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2];
+ break;
+ case 1:
+ dist1 = p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2];
+ dist2 = p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2];
+ break;
+ case 2:
+ dist1 = p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2];
+ dist2 = p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2];
+ break;
+ case 3:
+ dist1 = p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2];
+ dist2 = p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2];
+ break;
+ case 4:
+ dist1 = p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2];
+ dist2 = p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2];
+ break;
+ case 5:
+ dist1 = p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2];
+ dist2 = p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2];
+ break;
+ case 6:
+ dist1 = p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2];
+ dist2 = p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2];
+ break;
+ case 7:
+ dist1 = p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2];
+ dist2 = p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2];
+ break;
+ default:
+ dist1 = dist2 = 0; // shut up compiler
+// assert( 0 );
+ break;
+ }
+
+ sides = 0;
+ if (dist1 - p->dist >= PLANESIDE_EPSILON) sides = PSIDE_FRONT;
+ if (dist2 - p->dist < PLANESIDE_EPSILON) sides |= PSIDE_BACK;
+
+// assert(sides != 0);
+
+ return sides;
+}
+#endif
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int QuickTestBrushToPlanenum (bspbrush_t *brush, int planenum, int *numsplits)
+{
+ int i, num;
+ plane_t *plane;
+ int s;
+
+ *numsplits = 0;
+
+ plane = &mapplanes[planenum];
+
+#ifdef ME
+ //fast axial cases
+ if (plane->type < 3)
+ {
+ if (plane->dist + PLANESIDE_EPSILON < brush->mins[plane->type])
+ return PSIDE_FRONT;
+ if (plane->dist - PLANESIDE_EPSILON > brush->maxs[plane->type])
+ return PSIDE_BACK;
+ } //end if
+#endif //ME*/
+
+ // if the brush actually uses the planenum,
+ // we can tell the side for sure
+ for (i = 0; i < brush->numsides; i++)
+ {
+ num = brush->sides[i].planenum;
+ if (num >= MAX_MAPFILE_PLANES)
+ Error ("bad planenum");
+ if (num == planenum)
+ return PSIDE_BACK|PSIDE_FACING;
+ if (num == (planenum ^ 1) )
+ return PSIDE_FRONT|PSIDE_FACING;
+
+ }
+
+ // box on plane side
+ s = BoxOnPlaneSide (brush->mins, brush->maxs, plane);
+
+ // if both sides, count the visible faces split
+ if (s == PSIDE_BOTH)
+ {
+ *numsplits += 3;
+ }
+
+ return s;
+} //end of the function QuickTestBrushToPlanenum
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TestBrushToPlanenum (bspbrush_t *brush, int planenum,
+ int *numsplits, qboolean *hintsplit, int *epsilonbrush)
+{
+ int i, j, num;
+ plane_t *plane;
+ int s = 0;
+ winding_t *w;
+ vec_t d, d_front, d_back;
+ int front, back;
+ int type;
+ float dist;
+
+ *numsplits = 0;
+ *hintsplit = false;
+
+ plane = &mapplanes[planenum];
+
+#ifdef ME
+ //fast axial cases
+ type = plane->type;
+ if (type < 3)
+ {
+ dist = plane->dist;
+ if (dist + PLANESIDE_EPSILON < brush->mins[type]) return PSIDE_FRONT;
+ if (dist - PLANESIDE_EPSILON > brush->maxs[type]) return PSIDE_BACK;
+ if (brush->mins[type] < dist - PLANESIDE_EPSILON &&
+ brush->maxs[type] > dist + PLANESIDE_EPSILON) s = PSIDE_BOTH;
+ } //end if
+
+ if (s != PSIDE_BOTH)
+#endif //ME
+ {
+ // if the brush actually uses the planenum,
+ // we can tell the side for sure
+ for (i = 0; i < brush->numsides; i++)
+ {
+ num = brush->sides[i].planenum;
+ if (num >= MAX_MAPFILE_PLANES) Error ("bad planenum");
+ if (num == planenum)
+ {
+ //we don't need to test this side plane again
+ brush->sides[i].flags |= SFL_TESTED;
+ return PSIDE_BACK|PSIDE_FACING;
+ } //end if
+ if (num == (planenum ^ 1) )
+ {
+ //we don't need to test this side plane again
+ brush->sides[i].flags |= SFL_TESTED;
+ return PSIDE_FRONT|PSIDE_FACING;
+ } //end if
+ } //end for
+
+ // box on plane side
+ s = BoxOnPlaneSide (brush->mins, brush->maxs, plane);
+
+ if (s != PSIDE_BOTH) return s;
+ } //end if
+
+ // if both sides, count the visible faces split
+ d_front = d_back = 0;
+
+ for (i = 0; i < brush->numsides; i++)
+ {
+ if (brush->sides[i].texinfo == TEXINFO_NODE)
+ continue; // on node, don't worry about splits
+ if (!(brush->sides[i].flags & SFL_VISIBLE))
+ continue; // we don't care about non-visible
+ w = brush->sides[i].winding;
+ if (!w) continue;
+ front = back = 0;
+ for (j = 0; j < w->numpoints; j++)
+ {
+ d = DotProduct(w->p[j], plane->normal) - plane->dist;
+ if (d > d_front) d_front = d;
+ if (d < d_back) d_back = d;
+ if (d > 0.1) // PLANESIDE_EPSILON)
+ front = 1;
+ if (d < -0.1) // PLANESIDE_EPSILON)
+ back = 1;
+ } //end for
+ if (front && back)
+ {
+ if ( !(brush->sides[i].surf & SURF_SKIP) )
+ {
+ (*numsplits)++;
+ if (brush->sides[i].surf & SURF_HINT)
+ {
+ *hintsplit = true;
+ } //end if
+ } //end if
+ } //end if
+ } //end for
+
+ if ( (d_front > 0.0 && d_front < 1.0)
+ || (d_back < 0.0 && d_back > -1.0) )
+ (*epsilonbrush)++;
+
+#if 0
+ if (*numsplits == 0)
+ { // didn't really need to be split
+ if (front) s = PSIDE_FRONT;
+ else if (back) s = PSIDE_BACK;
+ else s = 0;
+ }
+#endif
+
+ return s;
+} //end of the function TestBrushToPlanenum
+//===========================================================================
+// Returns true if the winding would be crunched out of
+// existance by the vertex snapping.
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+#define EDGE_LENGTH 0.2
+qboolean WindingIsTiny (winding_t *w)
+{
+#if 0
+ if (WindingArea (w) < 1)
+ return true;
+ return false;
+#else
+ int i, j;
+ vec_t len;
+ vec3_t delta;
+ int edges;
+
+ edges = 0;
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ j = i == w->numpoints - 1 ? 0 : i+1;
+ VectorSubtract (w->p[j], w->p[i], delta);
+ len = VectorLength (delta);
+ if (len > EDGE_LENGTH)
+ {
+ if (++edges == 3)
+ return false;
+ }
+ }
+ return true;
+#endif
+} //end of the function WindingIsTiny
+//===========================================================================
+// Returns true if the winding still has one of the points
+// from basewinding for plane
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean WindingIsHuge (winding_t *w)
+{
+ int i, j;
+
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ for (j=0 ; j<3 ; j++)
+ if (w->p[i][j] < -BOGUS_RANGE+1 || w->p[i][j] > BOGUS_RANGE-1)
+ return true;
+ }
+ return false;
+} //end of the function WindingIsHuge
+//===========================================================================
+// creates a leaf out of the given nodes with the given brushes
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void LeafNode(node_t *node, bspbrush_t *brushes)
+{
+ bspbrush_t *b;
+ int i;
+
+ node->side = NULL;
+ node->planenum = PLANENUM_LEAF;
+ node->contents = 0;
+
+ for (b = brushes; b; b = b->next)
+ {
+ // if the brush is solid and all of its sides are on nodes,
+ // it eats everything
+ if (b->original->contents & CONTENTS_SOLID)
+ {
+ for (i=0 ; i<b->numsides ; i++)
+ if (b->sides[i].texinfo != TEXINFO_NODE)
+ break;
+ if (i == b->numsides)
+ {
+ node->contents = CONTENTS_SOLID;
+ break;
+ } //end if
+ } //end if
+ node->contents |= b->original->contents;
+ } //end for
+
+ if (create_aas)
+ {
+ node->expansionbboxes = 0;
+ node->contents = 0;
+ for (b = brushes; b; b = b->next)
+ {
+ node->expansionbboxes |= b->original->expansionbbox;
+ node->contents |= b->original->contents;
+ if (b->original->modelnum)
+ node->modelnum = b->original->modelnum;
+ } //end for
+ if (node->contents & CONTENTS_SOLID)
+ {
+ if (node->expansionbboxes != cfg.allpresencetypes)
+ {
+ node->contents &= ~CONTENTS_SOLID;
+ } //end if
+ } //end if
+ } //end if
+
+ node->brushlist = brushes;
+} //end of the function LeafNode
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void CheckPlaneAgainstParents (int pnum, node_t *node)
+{
+ node_t *p;
+
+ for (p = node->parent; p; p = p->parent)
+ {
+ if (p->planenum == pnum) Error("Tried parent");
+ } //end for
+} //end of the function CheckPlaneAgainstParants
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean CheckPlaneAgainstVolume (int pnum, node_t *node)
+{
+ bspbrush_t *front, *back;
+ qboolean good;
+
+ SplitBrush (node->volume, pnum, &front, &back);
+
+ good = (front && back);
+
+ if (front) FreeBrush (front);
+ if (back) FreeBrush (back);
+
+ return good;
+} //end of the function CheckPlaneAgaintsVolume
+//===========================================================================
+// Using a hueristic, choses one of the sides out of the brushlist
+// to partition the brushes with.
+// Returns NULL if there are no valid planes to split with..
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+side_t *SelectSplitSide (bspbrush_t *brushes, node_t *node)
+{
+ int value, bestvalue;
+ bspbrush_t *brush, *test;
+ side_t *side, *bestside;
+ int i, pass, numpasses;
+ int pnum;
+ int s;
+ int front, back, both, facing, splits;
+ int bsplits;
+ int bestsplits;
+ int epsilonbrush;
+ qboolean hintsplit = false;
+
+ bestside = NULL;
+ bestvalue = -99999;
+ bestsplits = 0;
+
+ // the search order goes: visible-structural, visible-detail,
+ // nonvisible-structural, nonvisible-detail.
+ // If any valid plane is available in a pass, no further
+ // passes will be tried.
+ numpasses = 2;
+ for (pass = 0; pass < numpasses; pass++)
+ {
+ for (brush = brushes; brush; brush = brush->next)
+ {
+ // only check detail the second pass
+// if ( (pass & 1) && !(brush->original->contents & CONTENTS_DETAIL) )
+// continue;
+// if ( !(pass & 1) && (brush->original->contents & CONTENTS_DETAIL) )
+// continue;
+ for (i = 0; i < brush->numsides; i++)
+ {
+ side = brush->sides + i;
+// if (side->flags & SFL_BEVEL)
+// continue; // never use a bevel as a spliter
+ if (!side->winding)
+ continue; // nothing visible, so it can't split
+ if (side->texinfo == TEXINFO_NODE)
+ continue; // allready a node splitter
+ if (side->flags & SFL_TESTED)
+ continue; // we allready have metrics for this plane
+// if (side->surf & SURF_SKIP)
+// continue; // skip surfaces are never chosen
+
+// if (!(side->flags & SFL_VISIBLE) && (pass < 2))
+// continue; // only check visible faces on first pass
+
+ if ((side->flags & SFL_CURVE) && (pass < 1))
+ continue; // only check curves the second pass
+
+ pnum = side->planenum;
+ pnum &= ~1; // allways use positive facing plane
+
+ CheckPlaneAgainstParents (pnum, node);
+
+ if (!CheckPlaneAgainstVolume (pnum, node))
+ continue; // would produce a tiny volume
+
+ front = 0;
+ back = 0;
+ both = 0;
+ facing = 0;
+ splits = 0;
+ epsilonbrush = 0;
+
+ //inner loop: optimize
+ for (test = brushes; test; test = test->next)
+ {
+ s = TestBrushToPlanenum (test, pnum, &bsplits, &hintsplit, &epsilonbrush);
+
+ splits += bsplits;
+// if (bsplits && (s&PSIDE_FACING) )
+// Error ("PSIDE_FACING with splits");
+
+ test->testside = s;
+ //
+ if (s & PSIDE_FACING) facing++;
+ if (s & PSIDE_FRONT) front++;
+ if (s & PSIDE_BACK) back++;
+ if (s == PSIDE_BOTH) both++;
+ } //end for
+
+ // give a value estimate for using this plane
+ value = 5*facing - 5*splits - abs(front-back);
+// value = -5*splits;
+// value = 5*facing - 5*splits;
+ if (mapplanes[pnum].type < 3)
+ value+=5; // axial is better
+
+ value -= epsilonbrush * 1000; // avoid!
+
+ // never split a hint side except with another hint
+ if (hintsplit && !(side->surf & SURF_HINT) )
+ value = -9999999;
+
+ // save off the side test so we don't need
+ // to recalculate it when we actually seperate
+ // the brushes
+ if (value > bestvalue)
+ {
+ bestvalue = value;
+ bestside = side;
+ bestsplits = splits;
+ for (test = brushes; test ; test = test->next)
+ test->side = test->testside;
+ } //end if
+ } //end for
+ } //end for (brush = brushes;
+
+ // if we found a good plane, don't bother trying any
+ // other passes
+ if (bestside)
+ {
+ if (pass > 1)
+ {
+ if (numthreads == 1) c_nonvis++;
+ }
+ if (pass > 0) node->detail_seperator = true; // not needed for vis
+ break;
+ } //end if
+ } //end for (pass = 0;
+
+ //
+ // clear all the tested flags we set
+ //
+ for (brush = brushes ; brush ; brush=brush->next)
+ {
+ for (i = 0; i < brush->numsides; i++)
+ {
+ brush->sides[i].flags &= ~SFL_TESTED;
+ } //end for
+ } //end for
+
+ return bestside;
+} //end of the function SelectSplitSide
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BrushMostlyOnSide (bspbrush_t *brush, plane_t *plane)
+{
+ int i, j;
+ winding_t *w;
+ vec_t d, max;
+ int side;
+
+ max = 0;
+ side = PSIDE_FRONT;
+ for (i=0 ; i<brush->numsides ; i++)
+ {
+ w = brush->sides[i].winding;
+ if (!w)
+ continue;
+ for (j=0 ; j<w->numpoints ; j++)
+ {
+ d = DotProduct (w->p[j], plane->normal) - plane->dist;
+ if (d > max)
+ {
+ max = d;
+ side = PSIDE_FRONT;
+ }
+ if (-d > max)
+ {
+ max = -d;
+ side = PSIDE_BACK;
+ }
+ }
+ }
+ return side;
+} //end of the function BrushMostlyOnSide
+//===========================================================================
+// Generates two new brushes, leaving the original
+// unchanged
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void SplitBrush (bspbrush_t *brush, int planenum,
+ bspbrush_t **front, bspbrush_t **back)
+{
+ bspbrush_t *b[2];
+ int i, j;
+ winding_t *w, *cw[2], *midwinding;
+ plane_t *plane, *plane2;
+ side_t *s, *cs;
+ float d, d_front, d_back;
+
+ *front = *back = NULL;
+ plane = &mapplanes[planenum];
+
+ // check all points
+ d_front = d_back = 0;
+ for (i=0 ; i<brush->numsides ; i++)
+ {
+ w = brush->sides[i].winding;
+ if (!w)
+ continue;
+ for (j=0 ; j<w->numpoints ; j++)
+ {
+ d = DotProduct (w->p[j], plane->normal) - plane->dist;
+ if (d > 0 && d > d_front)
+ d_front = d;
+ if (d < 0 && d < d_back)
+ d_back = d;
+ }
+ }
+
+ if (d_front < 0.2) // PLANESIDE_EPSILON)
+ { // only on back
+ *back = CopyBrush (brush);
+ return;
+ }
+ if (d_back > -0.2) // PLANESIDE_EPSILON)
+ { // only on front
+ *front = CopyBrush (brush);
+ return;
+ }
+
+ // create a new winding from the split plane
+
+ w = BaseWindingForPlane (plane->normal, plane->dist);
+ for (i=0 ; i<brush->numsides && w ; i++)
+ {
+ plane2 = &mapplanes[brush->sides[i].planenum ^ 1];
+ ChopWindingInPlace (&w, plane2->normal, plane2->dist, 0); // PLANESIDE_EPSILON);
+ }
+
+ if (!w || WindingIsTiny(w))
+ { // the brush isn't really split
+ int side;
+
+ side = BrushMostlyOnSide (brush, plane);
+ if (side == PSIDE_FRONT)
+ *front = CopyBrush (brush);
+ if (side == PSIDE_BACK)
+ *back = CopyBrush (brush);
+ //free a possible winding
+ if (w) FreeWinding(w);
+ return;
+ }
+
+ if (WindingIsHuge (w))
+ {
+ Log_Write("WARNING: huge winding\n");
+ }
+
+ midwinding = w;
+
+ // split it for real
+
+ for (i=0 ; i<2 ; i++)
+ {
+ b[i] = AllocBrush (brush->numsides+1);
+ b[i]->original = brush->original;
+ }
+
+ // split all the current windings
+
+ for (i=0 ; i<brush->numsides ; i++)
+ {
+ s = &brush->sides[i];
+ w = s->winding;
+ if (!w)
+ continue;
+ ClipWindingEpsilon (w, plane->normal, plane->dist,
+ 0 /*PLANESIDE_EPSILON*/, &cw[0], &cw[1]);
+ for (j=0 ; j<2 ; j++)
+ {
+ if (!cw[j])
+ continue;
+#if 0
+ if (WindingIsTiny (cw[j]))
+ {
+ FreeWinding (cw[j]);
+ continue;
+ }
+#endif
+ cs = &b[j]->sides[b[j]->numsides];
+ b[j]->numsides++;
+ *cs = *s;
+// cs->planenum = s->planenum;
+// cs->texinfo = s->texinfo;
+// cs->original = s->original;
+ cs->winding = cw[j];
+ cs->flags &= ~SFL_TESTED;
+ }
+ }
+
+
+ // see if we have valid polygons on both sides
+
+ for (i=0 ; i<2 ; i++)
+ {
+ BoundBrush (b[i]);
+ for (j=0 ; j<3 ; j++)
+ {
+ if (b[i]->mins[j] < -MAX_MAP_BOUNDS || b[i]->maxs[j] > MAX_MAP_BOUNDS)
+ {
+ Log_Write("bogus brush after clip");
+ break;
+ }
+ }
+
+ if (b[i]->numsides < 3 || j < 3)
+ {
+ FreeBrush (b[i]);
+ b[i] = NULL;
+ }
+ }
+
+ if ( !(b[0] && b[1]) )
+ {
+ if (!b[0] && !b[1])
+ Log_Write("split removed brush\r\n");
+ else
+ Log_Write("split not on both sides\r\n");
+ if (b[0])
+ {
+ FreeBrush (b[0]);
+ *front = CopyBrush (brush);
+ }
+ if (b[1])
+ {
+ FreeBrush (b[1]);
+ *back = CopyBrush (brush);
+ }
+ return;
+ }
+
+ // add the midwinding to both sides
+ for (i=0 ; i<2 ; i++)
+ {
+ cs = &b[i]->sides[b[i]->numsides];
+ b[i]->numsides++;
+
+ cs->planenum = planenum^i^1;
+ cs->texinfo = TEXINFO_NODE; //never use these sides as splitters
+ cs->flags &= ~SFL_VISIBLE;
+ cs->flags &= ~SFL_TESTED;
+ if (i==0)
+ cs->winding = CopyWinding (midwinding);
+ else
+ cs->winding = midwinding;
+ }
+
+{
+ vec_t v1;
+ int i;
+
+ for (i = 0; i < 2; i++)
+ {
+ v1 = BrushVolume (b[i]);
+ if (v1 < 1.0)
+ {
+ FreeBrush(b[i]);
+ b[i] = NULL;
+ //Log_Write("tiny volume after clip");
+ }
+ }
+ if (!b[0] && !b[1])
+ {
+ Log_Write("two tiny brushes\r\n");
+ } //end if
+}
+
+ *front = b[0];
+ *back = b[1];
+} //end of the function SplitBrush
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void SplitBrushList (bspbrush_t *brushes,
+ node_t *node, bspbrush_t **front, bspbrush_t **back)
+{
+ bspbrush_t *brush, *newbrush, *newbrush2;
+ side_t *side;
+ int sides;
+ int i;
+
+ *front = *back = NULL;
+
+ for (brush = brushes; brush; brush = brush->next)
+ {
+ sides = brush->side;
+
+ if (sides == PSIDE_BOTH)
+ { // split into two brushes
+ SplitBrush (brush, node->planenum, &newbrush, &newbrush2);
+ if (newbrush)
+ {
+ newbrush->next = *front;
+ *front = newbrush;
+ } //end if
+ if (newbrush2)
+ {
+ newbrush2->next = *back;
+ *back = newbrush2;
+ } //end if
+ continue;
+ } //end if
+
+ newbrush = CopyBrush (brush);
+
+ // if the planenum is actualy a part of the brush
+ // find the plane and flag it as used so it won't be tried
+ // as a splitter again
+ if (sides & PSIDE_FACING)
+ {
+ for (i=0 ; i<newbrush->numsides ; i++)
+ {
+ side = newbrush->sides + i;
+ if ( (side->planenum& ~1) == node->planenum)
+ side->texinfo = TEXINFO_NODE;
+ } //end for
+ } //end if
+ if (sides & PSIDE_FRONT)
+ {
+ newbrush->next = *front;
+ *front = newbrush;
+ continue;
+ } //end if
+ if (sides & PSIDE_BACK)
+ {
+ newbrush->next = *back;
+ *back = newbrush;
+ continue;
+ } //end if
+ } //end for
+} //end of the function SplitBrushList
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void CheckBrushLists(bspbrush_t *brushlist1, bspbrush_t *brushlist2)
+{
+ bspbrush_t *brush1, *brush2;
+
+ for (brush1 = brushlist1; brush1; brush1 = brush1->next)
+ {
+ for (brush2 = brushlist2; brush2; brush2 = brush2->next)
+ {
+ assert(brush1 != brush2);
+ } //end for
+ } //end for
+} //end of the function CheckBrushLists
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int numrecurse = 0;
+
+node_t *BuildTree_r (node_t *node, bspbrush_t *brushes)
+{
+ node_t *newnode;
+ side_t *bestside;
+ int i, totalmem;
+ bspbrush_t *children[2];
+
+ qprintf("\r%6d", numrecurse);
+ numrecurse++;
+
+ if (numthreads == 1)
+ {
+ totalmem = WindingMemory() + c_nodememory + c_brushmemory;
+ if (totalmem > c_peak_totalbspmemory)
+ c_peak_totalbspmemory = totalmem;
+ c_nodes++;
+ } //endif
+
+ if (drawflag)
+ DrawBrushList(brushes, node);
+
+ // find the best plane to use as a splitter
+ bestside = SelectSplitSide (brushes, node);
+ if (!bestside)
+ {
+ // leaf node
+ node->side = NULL;
+ node->planenum = -1;
+ LeafNode(node, brushes);
+ if (node->contents & CONTENTS_SOLID) c_solidleafnodes++;
+ if (create_aas)
+ {
+ //free up memory!!!
+ FreeBrushList(node->brushlist);
+ node->brushlist = NULL;
+ //free the node volume brush
+ if (node->volume)
+ {
+ FreeBrush(node->volume);
+ node->volume = NULL;
+ } //end if
+ } //end if
+ return node;
+ } //end if
+
+ // this is a splitplane node
+ node->side = bestside;
+ node->planenum = bestside->planenum & ~1; // always use front facing
+
+ //split the brush list in two for both children
+ SplitBrushList (brushes, node, &children[0], &children[1]);
+ //free the old brush list
+ FreeBrushList (brushes);
+
+ // allocate children before recursing
+ for (i = 0; i < 2; i++)
+ {
+ newnode = AllocNode ();
+ newnode->parent = node;
+ node->children[i] = newnode;
+ } //end for
+
+ //split the volume brush of the node for the children
+ SplitBrush (node->volume, node->planenum, &node->children[0]->volume,
+ &node->children[1]->volume);
+
+ if (create_aas)
+ {
+ //free the volume brush
+ if (node->volume)
+ {
+ FreeBrush(node->volume);
+ node->volume = NULL;
+ } //end if
+ } //end if
+ // recursively process children
+ for (i = 0; i < 2; i++)
+ {
+ node->children[i] = BuildTree_r(node->children[i], children[i]);
+ } //end for
+
+ return node;
+} //end of the function BuildTree_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+node_t *firstnode; //first node in the list
+node_t *lastnode; //last node in the list
+int nodelistsize; //number of nodes in the list
+int use_nodequeue = 0; //use nodequeue, otherwise a node stack is used
+int numwaiting = 0;
+
+void (*AddNodeToList)(node_t *node);
+
+//add the node to the front of the node list
+//(effectively using a node stack)
+void AddNodeToStack(node_t *node)
+{
+ ThreadLock();
+
+ node->next = firstnode;
+ firstnode = node;
+ if (!lastnode) lastnode = node;
+ nodelistsize++;
+
+ ThreadUnlock();
+ //
+ ThreadSemaphoreIncrease(1);
+} //end of the function AddNodeToStack
+//add the node to the end of the node list
+//(effectively using a node queue)
+void AddNodeToQueue(node_t *node)
+{
+ ThreadLock();
+
+ node->next = NULL;
+ if (lastnode) lastnode->next = node;
+ else firstnode = node;
+ lastnode = node;
+ nodelistsize++;
+
+ ThreadUnlock();
+ //
+ ThreadSemaphoreIncrease(1);
+} //end of the function AddNodeToQueue
+//get the first node from the front of the node list
+node_t *NextNodeFromList(void)
+{
+ node_t *node;
+
+ ThreadLock();
+ numwaiting++;
+ if (!firstnode)
+ {
+ if (numwaiting >= GetNumThreads()) ThreadSemaphoreIncrease(GetNumThreads());
+ } //end if
+ ThreadUnlock();
+
+ ThreadSemaphoreWait();
+
+ ThreadLock();
+
+ numwaiting--;
+
+ node = firstnode;
+ if (firstnode)
+ {
+ firstnode = firstnode->next;
+ nodelistsize--;
+ } //end if
+ if (!firstnode) lastnode = NULL;
+
+ ThreadUnlock();
+
+ return node;
+} //end of the function NextNodeFromList
+//returns the size of the node list
+int NodeListSize(void)
+{
+ int size;
+
+ ThreadLock();
+ size = nodelistsize;
+ ThreadUnlock();
+
+ return size;
+} //end of the function NodeListSize
+//
+void IncreaseNodeCounter(void)
+{
+ ThreadLock();
+ //if (verbose) printf("\r%6d", numrecurse++);
+ qprintf("\r%6d", numrecurse++);
+ //qprintf("\r%6d %d, %5d ", numrecurse++, GetNumThreads(), nodelistsize);
+ ThreadUnlock();
+} //end of the function IncreaseNodeCounter
+//thread function, gets nodes from the nodelist and processes them
+void BuildTreeThread(int threadid)
+{
+ node_t *newnode, *node;
+ side_t *bestside;
+ int i, totalmem;
+ bspbrush_t *brushes;
+
+ for (node = NextNodeFromList(); node; )
+ {
+ //if the nodelist isn't empty try to add another thread
+ //if (NodeListSize() > 10) AddThread(BuildTreeThread);
+ //display the number of nodes processed so far
+ if (numthreads == 1)
+ IncreaseNodeCounter();
+
+ brushes = node->brushlist;
+
+ if (numthreads == 1)
+ {
+ totalmem = WindingMemory() + c_nodememory + c_brushmemory;
+ if (totalmem > c_peak_totalbspmemory)
+ {
+ c_peak_totalbspmemory = totalmem;
+ } //end if
+ c_nodes++;
+ } //endif
+
+ if (drawflag)
+ {
+ DrawBrushList(brushes, node);
+ } //end if
+
+ if (cancelconversion)
+ {
+ bestside = NULL;
+ } //end if
+ else
+ {
+ // find the best plane to use as a splitter
+ bestside = SelectSplitSide(brushes, node);
+ } //end else
+ //if there's no split side left
+ if (!bestside)
+ {
+ //create a leaf out of the node
+ LeafNode(node, brushes);
+ if (node->contents & CONTENTS_SOLID) c_solidleafnodes++;
+ if (create_aas)
+ {
+ //free up memory!!!
+ FreeBrushList(node->brushlist);
+ node->brushlist = NULL;
+ } //end if
+ //free the node volume brush (it is not used anymore)
+ if (node->volume)
+ {
+ FreeBrush(node->volume);
+ node->volume = NULL;
+ } //end if
+ node = NextNodeFromList();
+ continue;
+ } //end if
+
+ // this is a splitplane node
+ node->side = bestside;
+ node->planenum = bestside->planenum & ~1; //always use front facing
+
+ //allocate children
+ for (i = 0; i < 2; i++)
+ {
+ newnode = AllocNode();
+ newnode->parent = node;
+ node->children[i] = newnode;
+ } //end for
+
+ //split the brush list in two for both children
+ SplitBrushList(brushes, node, &node->children[0]->brushlist, &node->children[1]->brushlist);
+
+ CheckBrushLists(node->children[0]->brushlist, node->children[1]->brushlist);
+ //free the old brush list
+ FreeBrushList(brushes);
+ node->brushlist = NULL;
+
+ //split the volume brush of the node for the children
+ SplitBrush(node->volume, node->planenum, &node->children[0]->volume,
+ &node->children[1]->volume);
+
+ if (!node->children[0]->volume || !node->children[1]->volume)
+ {
+ Error("child without volume brush");
+ } //end if
+
+ //free the volume brush
+ if (node->volume)
+ {
+ FreeBrush(node->volume);
+ node->volume = NULL;
+ } //end if
+ //add both children to the node list
+ //AddNodeToList(node->children[0]);
+ AddNodeToList(node->children[1]);
+ node = node->children[0];
+ } //end while
+ RemoveThread(threadid);
+} //end of the function BuildTreeThread
+//===========================================================================
+// build the bsp tree using a node list
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BuildTree(tree_t *tree)
+{
+ int i;
+
+ firstnode = NULL;
+ lastnode = NULL;
+ //use a node queue or node stack
+ if (use_nodequeue) AddNodeToList = AddNodeToQueue;
+ else AddNodeToList = AddNodeToStack;
+ //setup thread locking
+ ThreadSetupLock();
+ ThreadSetupSemaphore();
+ numwaiting = 0;
+ //
+ Log_Print("%6d threads max\n", numthreads);
+ if (use_nodequeue) Log_Print("breadth first bsp building\n");
+ else Log_Print("depth first bsp building\n");
+ qprintf("%6d splits", 0);
+ //add the first node to the list
+ AddNodeToList(tree->headnode);
+ //start the threads
+ for (i = 0; i < numthreads; i++)
+ AddThread(BuildTreeThread);
+ //wait for all added threads to be finished
+ WaitForAllThreadsFinished();
+ //shutdown the thread locking
+ ThreadShutdownLock();
+ ThreadShutdownSemaphore();
+} //end of the function BuildTree
+//===========================================================================
+// The incoming brush list will be freed before exiting
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+tree_t *BrushBSP(bspbrush_t *brushlist, vec3_t mins, vec3_t maxs)
+{
+ int i, c_faces, c_nonvisfaces, c_brushes;
+ bspbrush_t *b;
+ node_t *node;
+ tree_t *tree;
+ vec_t volume;
+// vec3_t point;
+
+ Log_Print("-------- Brush BSP ---------\n");
+
+ tree = Tree_Alloc();
+
+ c_faces = 0;
+ c_nonvisfaces = 0;
+ c_brushes = 0;
+ c_totalsides = 0;
+ for (b = brushlist; b; b = b->next)
+ {
+ c_brushes++;
+
+ volume = BrushVolume(b);
+ if (volume < microvolume)
+ {
+ Log_Print("WARNING: entity %i, brush %i: microbrush\n",
+ b->original->entitynum, b->original->brushnum);
+ } //end if
+
+ for (i=0 ; i<b->numsides ; i++)
+ {
+ if (b->sides[i].flags & SFL_BEVEL)
+ continue;
+ if (!b->sides[i].winding)
+ continue;
+ if (b->sides[i].texinfo == TEXINFO_NODE)
+ continue;
+ if (b->sides[i].flags & SFL_VISIBLE)
+ {
+ c_faces++;
+ } //end if
+ else
+ {
+ c_nonvisfaces++;
+ //if (create_aas) b->sides[i].texinfo = TEXINFO_NODE;
+ } //end if
+ } //end for
+ c_totalsides += b->numsides;
+
+ AddPointToBounds (b->mins, tree->mins, tree->maxs);
+ AddPointToBounds (b->maxs, tree->mins, tree->maxs);
+ } //end for
+
+ Log_Print("%6i brushes\n", c_brushes);
+ Log_Print("%6i visible faces\n", c_faces);
+ Log_Print("%6i nonvisible faces\n", c_nonvisfaces);
+ Log_Print("%6i total sides\n", c_totalsides);
+
+ c_active_brushes = c_brushes;
+ c_nodememory = 0;
+ c_brushmemory = 0;
+ c_peak_brushmemory = 0;
+
+ c_nodes = 0;
+ c_nonvis = 0;
+ node = AllocNode ();
+
+ //volume of first node (head node)
+ node->volume = BrushFromBounds (mins, maxs);
+ //
+ tree->headnode = node;
+ //just get some statistics and the mins/maxs of the node
+ numrecurse = 0;
+// qprintf("%6d splits", numrecurse);
+
+ tree->headnode->brushlist = brushlist;
+ BuildTree(tree);
+
+ //build the bsp tree with the start node from the brushlist
+// node = BuildTree_r(node, brushlist);
+
+ //if the conversion is cancelled
+ if (cancelconversion) return tree;
+
+ qprintf("\n");
+ Log_Write("%6d splits\r\n", numrecurse);
+// Log_Print("%6i visible nodes\n", c_nodes/2 - c_nonvis);
+// Log_Print("%6i nonvis nodes\n", c_nonvis);
+// Log_Print("%6i leaves\n", (c_nodes+1)/2);
+// Log_Print("%6i solid leaf nodes\n", c_solidleafnodes);
+// Log_Print("%6i active brushes\n", c_active_brushes);
+ if (numthreads == 1)
+ {
+// Log_Print("%6i KB of node memory\n", c_nodememory >> 10);
+// Log_Print("%6i KB of brush memory\n", c_brushmemory >> 10);
+// Log_Print("%6i KB of peak brush memory\n", c_peak_brushmemory >> 10);
+// Log_Print("%6i KB of winding memory\n", WindingMemory() >> 10);
+// Log_Print("%6i KB of peak winding memory\n", WindingPeakMemory() >> 10);
+ Log_Print("%6i KB of peak total bsp memory\n", c_peak_totalbspmemory >> 10);
+ } //end if
+
+ /*
+ point[0] = 1485;
+ point[1] = 956.125;
+ point[2] = 352.125;
+ node = PointInLeaf(tree->headnode, point);
+ if (node->planenum != PLANENUM_LEAF)
+ {
+ Log_Print("node not a leaf\n");
+ } //end if
+ Log_Print("at %f %f %f:\n", point[0], point[1], point[2]);
+ PrintContents(node->contents);
+ Log_Print("node->expansionbboxes = %d\n", node->expansionbboxes);
+ //*/
+ return tree;
+} //end of the function BrushBSP
+
diff --git a/code/bspc/bspc.c b/code/bspc/bspc.c
new file mode 100755
index 0000000..4f58b53
--- /dev/null
+++ b/code/bspc/bspc.c
@@ -0,0 +1,991 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#if defined(WIN32) || defined(_WIN32)
+#include <direct.h>
+#include <windows.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#else
+#include <unistd.h>
+#include <glob.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#endif
+#include "qbsp.h"
+#include "l_mem.h"
+#include "../botlib/aasfile.h"
+#include "../botlib/be_aas_cluster.h"
+#include "../botlib/be_aas_optimize.h"
+#include "aas_create.h"
+#include "aas_store.h"
+#include "aas_file.h"
+#include "aas_cfg.h"
+#include "be_aas_bspc.h"
+
+extern int use_nodequeue; //brushbsp.c
+extern int calcgrapplereach; //be_aas_reach.c
+
+float subdivide_size = 240;
+char source[1024];
+char name[1024];
+vec_t microvolume = 1.0;
+char outbase[32];
+int entity_num;
+aas_settings_t aassettings;
+
+qboolean noprune; //don't prune nodes (bspc.c)
+qboolean glview; //create a gl view
+qboolean nodetail; //don't use detail brushes (map.c)
+qboolean fulldetail; //use but don't mark detail brushes (map.c)
+qboolean onlyents; //only process the entities (bspc.c)
+qboolean nomerge; //don't merge bsp node faces (faces.c)
+qboolean nowater; //don't use the water brushes (map.c)
+qboolean nocsg; //don't carve intersecting brushes (bspc.c)
+qboolean noweld; //use unique face vertexes (faces.c)
+qboolean noshare; //don't share bsp edges (faces.c)
+qboolean nosubdiv; //don't subdivide bsp node faces (faces.c)
+qboolean notjunc; //don't create tjunctions (edge melting) (faces.c)
+qboolean optimize; //enable optimisation
+qboolean leaktest; //perform a leak test
+qboolean verboseentities;
+qboolean freetree; //free the bsp tree when not needed anymore
+qboolean create_aas; //create an .AAS file
+qboolean nobrushmerge; //don't merge brushes
+qboolean lessbrushes; //create less brushes instead of correct texture placement
+qboolean cancelconversion; //true if the conversion is being cancelled
+qboolean noliquids; //no liquids when writing map file
+qboolean forcesidesvisible; //force all brush sides to be visible when loaded from bsp
+qboolean capsule_collision = 0;
+
+/*
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ProcessWorldModel (void)
+{
+ entity_t *e;
+ tree_t *tree;
+ qboolean leaked;
+ int brush_start, brush_end;
+
+ e = &entities[entity_num];
+
+ brush_start = e->firstbrush;
+ brush_end = brush_start + e->numbrushes;
+ leaked = false;
+
+ //process the whole world in one time
+ tree = ProcessWorldBrushes(brush_start, brush_end);
+ //create the bsp tree portals
+ MakeTreePortals(tree);
+ //mark all leafs that can be reached by entities
+ if (FloodEntities(tree))
+ {
+ FillOutside(tree->headnode);
+ } //end if
+ else
+ {
+ Log_Print("**** leaked ****\n");
+ leaked = true;
+ LeakFile(tree);
+ if (leaktest)
+ {
+ Log_Print("--- MAP LEAKED ---\n");
+ exit(0);
+ } //end if
+ } //end else
+
+ MarkVisibleSides (tree, brush_start, brush_end);
+
+ FloodAreas (tree);
+
+#ifndef ME
+ if (glview) WriteGLView(tree, source);
+#endif
+ MakeFaces(tree->headnode);
+ FixTjuncs(tree->headnode);
+
+ //NOTE: Never prune the nodes because the portals
+ // are screwed when prunning is done and as
+ // a result portal writing will crash
+ //if (!noprune) PruneNodes(tree->headnode);
+
+ WriteBSP(tree->headnode);
+
+ if (!leaked) WritePortalFile(tree);
+
+ Tree_Free(tree);
+} //end of the function ProcessWorldModel
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ProcessSubModel (void)
+{
+ entity_t *e;
+ int start, end;
+ tree_t *tree;
+ bspbrush_t *list;
+ vec3_t mins, maxs;
+
+ e = &entities[entity_num];
+
+ start = e->firstbrush;
+ end = start + e->numbrushes;
+
+ mins[0] = mins[1] = mins[2] = -4096;
+ maxs[0] = maxs[1] = maxs[2] = 4096;
+ list = MakeBspBrushList(start, end, mins, maxs);
+ if (!nocsg) list = ChopBrushes (list);
+ tree = BrushBSP (list, mins, maxs);
+ MakeTreePortals (tree);
+ MarkVisibleSides (tree, start, end);
+ MakeFaces (tree->headnode);
+ FixTjuncs (tree->headnode);
+ WriteBSP (tree->headnode);
+ Tree_Free(tree);
+} //end of the function ProcessSubModel
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ProcessModels (void)
+{
+ BeginBSPFile();
+
+ for (entity_num = 0; entity_num < num_entities; entity_num++)
+ {
+ if (!entities[entity_num].numbrushes)
+ continue;
+
+ Log_Print("############### model %i ###############\n", nummodels);
+ BeginModel();
+ if (entity_num == 0) ProcessWorldModel();
+ else ProcessSubModel();
+ EndModel();
+
+ if (!verboseentities)
+ verbose = false; // don't bother printing submodels
+ } //end for
+ EndBSPFile();
+} //end of the function ProcessModels
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Win_Map2Bsp(char *bspfilename)
+{
+ double start, end;
+ char path[1024];
+
+ start = I_FloatTime();
+
+ ThreadSetDefault();
+ //yeah sure Carmack
+ //numthreads = 1; // multiple threads aren't helping...
+
+ strcpy(source, ExpandArg(bspfilename));
+ StripExtension(source);
+
+ //delete portal and line files
+ sprintf(path, "%s.prt", source);
+ remove(path);
+ sprintf(path, "%s.lin", source);
+ remove(path);
+
+ strcpy(name, ExpandArg(bspfilename));
+ DefaultExtension(name, ".map"); // might be .reg
+
+ Q2_AllocMaxBSP();
+ //
+ SetModelNumbers();
+ SetLightStyles();
+ ProcessModels();
+ //write the BSP
+ Q2_WriteBSPFile(bspfilename);
+
+ Q2_FreeMaxBSP();
+
+ end = I_FloatTime();
+ Log_Print("%5.0f seconds elapsed\n", end-start);
+} //end of the function Win_Map2Bsp
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Map2Bsp(char *mapfilename, char *outputfilename)
+{
+ double start, end;
+ char path[1024];
+
+ start = I_FloatTime ();
+
+ ThreadSetDefault ();
+ //yeah sure Carmack
+ //numthreads = 1; //multiple threads aren't helping...
+ //SetQdirFromPath(bspfilename);
+
+ strcpy(source, ExpandArg(mapfilename));
+ StripExtension(source);
+
+ // delete portal and line files
+ sprintf(path, "%s.prt", source);
+ remove(path);
+ sprintf(path, "%s.lin", source);
+ remove(path);
+
+ strcpy(name, ExpandArg(mapfilename));
+ DefaultExtension(name, ".map"); // might be .reg
+
+ //
+ // if onlyents, just grab the entites and resave
+ //
+ if (onlyents)
+ {
+ char out[1024];
+
+ Q2_AllocMaxBSP();
+ sprintf (out, "%s.bsp", source);
+ Q2_LoadBSPFile(out, 0, 0);
+ num_entities = 0;
+
+ Q2_LoadMapFile(name);
+ SetModelNumbers();
+ SetLightStyles();
+
+ Q2_UnparseEntities();
+
+ Q2_WriteBSPFile(out);
+ //
+ Q2_FreeMaxBSP();
+ } //end if
+ else
+ {
+ //
+ // start from scratch
+ //
+ Q2_AllocMaxBSP();
+ //load the map
+ Q2_LoadMapFile(name);
+ //create the .bsp file
+ SetModelNumbers();
+ SetLightStyles();
+ ProcessModels();
+ //write the BSP
+ Q2_WriteBSPFile(outputfilename);
+ //
+ Q2_FreeMaxBSP();
+ } //end else
+
+ end = I_FloatTime();
+ Log_Print("%5.0f seconds elapsed\n", end-start);
+} //end of the function Map2Bsp
+*/
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AASOuputFile(quakefile_t *qf, char *outputpath, char *filename)
+{
+ char ext[MAX_PATH];
+
+ //
+ if (strlen(outputpath))
+ {
+ strcpy(filename, outputpath);
+ //append the bsp file base
+ AppendPathSeperator(filename, MAX_PATH);
+ ExtractFileBase(qf->origname, &filename[strlen(filename)]);
+ //append .aas
+ strcat(filename, ".aas");
+ return;
+ } //end if
+ //
+ ExtractFileExtension(qf->filename, ext);
+ if (!stricmp(ext, "pk3") || !stricmp(ext, "pak") || !stricmp(ext, "sin"))
+ {
+ strcpy(filename, qf->filename);
+ while(strlen(filename) &&
+ filename[strlen(filename)-1] != '\\' &&
+ filename[strlen(filename)-1] != '/')
+ {
+ filename[strlen(filename)-1] = '\0';
+ } //end while
+ strcat(filename, "maps");
+ if (access(filename, 0x04)) CreatePath(filename);
+ //append the bsp file base
+ AppendPathSeperator(filename, MAX_PATH);
+ ExtractFileBase(qf->origname, &filename[strlen(filename)]);
+ //append .aas
+ strcat(filename, ".aas");
+ } //end if
+ else
+ {
+ strcpy(filename, qf->filename);
+ while(strlen(filename) &&
+ filename[strlen(filename)-1] != '.')
+ {
+ filename[strlen(filename)-1] = '\0';
+ } //end while
+ strcat(filename, "aas");
+ } //end else
+} //end of the function AASOutputFile
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void CreateAASFilesForAllBSPFiles(char *quakepath)
+{
+#if defined(WIN32)|defined(_WIN32)
+ WIN32_FIND_DATA filedata;
+ HWND handle;
+ struct _stat statbuf;
+#else
+ glob_t globbuf;
+ struct stat statbuf;
+ int j;
+#endif
+ int done;
+ char filter[_MAX_PATH], bspfilter[_MAX_PATH], aasfilter[_MAX_PATH];
+ char aasfile[_MAX_PATH], buf[_MAX_PATH], foldername[_MAX_PATH];
+ quakefile_t *qf, *qf2, *files, *bspfiles, *aasfiles;
+
+ strcpy(filter, quakepath);
+ AppendPathSeperator(filter, sizeof(filter));
+ strcat(filter, "*");
+
+#if defined(WIN32)|defined(_WIN32)
+ handle = FindFirstFile(filter, &filedata);
+ done = (handle == INVALID_HANDLE_VALUE);
+ while(!done)
+ {
+ _splitpath(filter, foldername, NULL, NULL, NULL);
+ _splitpath(filter, NULL, &foldername[strlen(foldername)], NULL, NULL);
+ AppendPathSeperator(foldername, _MAX_PATH);
+ strcat(foldername, filedata.cFileName);
+ _stat(foldername, &statbuf);
+#else
+ glob(filter, 0, NULL, &globbuf);
+ for (j = 0; j < globbuf.gl_pathc; j++)
+ {
+ strcpy(foldername, globbuf.gl_pathv[j]);
+ stat(foldername, &statbuf);
+#endif
+ //if it is a folder
+ if (statbuf.st_mode & S_IFDIR)
+ {
+ //
+ AppendPathSeperator(foldername, sizeof(foldername));
+ //get all the bsp files
+ strcpy(bspfilter, foldername);
+ strcat(bspfilter, "maps/*.bsp");
+ files = FindQuakeFiles(bspfilter);
+ strcpy(bspfilter, foldername);
+ strcat(bspfilter, "*.pk3/maps/*.bsp");
+ bspfiles = FindQuakeFiles(bspfilter);
+ for (qf = bspfiles; qf; qf = qf->next) if (!qf->next) break;
+ if (qf) qf->next = files;
+ else bspfiles = files;
+ //get all the aas files
+ strcpy(aasfilter, foldername);
+ strcat(aasfilter, "maps/*.aas");
+ files = FindQuakeFiles(aasfilter);
+ strcpy(aasfilter, foldername);
+ strcat(aasfilter, "*.pk3/maps/*.aas");
+ aasfiles = FindQuakeFiles(aasfilter);
+ for (qf = aasfiles; qf; qf = qf->next) if (!qf->next) break;
+ if (qf) qf->next = files;
+ else aasfiles = files;
+ //
+ for (qf = bspfiles; qf; qf = qf->next)
+ {
+ sprintf(aasfile, "%s/%s", qf->pakfile, qf->origname);
+ Log_Print("found %s\n", aasfile);
+ strcpy(&aasfile[strlen(aasfile)-strlen(".bsp")], ".aas");
+ for (qf2 = aasfiles; qf2; qf2 = qf2->next)
+ {
+ sprintf(buf, "%s/%s", qf2->pakfile, qf2->origname);
+ if (!stricmp(aasfile, buf))
+ {
+ Log_Print("found %s\n", buf);
+ break;
+ } //end if
+ } //end for
+ } //end for
+ } //end if
+#if defined(WIN32)|defined(_WIN32)
+ //find the next file
+ done = !FindNextFile(handle, &filedata);
+ } //end while
+#else
+ } //end for
+ globfree(&globbuf);
+#endif
+} //end of the function CreateAASFilesForAllBSPFiles
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+quakefile_t *GetArgumentFiles(int argc, char *argv[], int *i, char *ext)
+{
+ quakefile_t *qfiles, *lastqf, *qf;
+ int j;
+ char buf[1024];
+
+ qfiles = NULL;
+ lastqf = NULL;
+ for (; (*i)+1 < argc && argv[(*i)+1][0] != '-'; (*i)++)
+ {
+ strcpy(buf, argv[(*i)+1]);
+ for (j = strlen(buf)-1; j >= strlen(buf)-4; j--)
+ if (buf[j] == '.') break;
+ if (j >= strlen(buf)-4)
+ strcpy(&buf[j+1], ext);
+ qf = FindQuakeFiles(buf);
+ if (!qf) continue;
+ if (lastqf) lastqf->next = qf;
+ else qfiles = qf;
+ lastqf = qf;
+ while(lastqf->next) lastqf = lastqf->next;
+ } //end for
+ return qfiles;
+} //end of the function GetArgumentFiles
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+
+#define COMP_BSP2MAP 1
+#define COMP_BSP2AAS 2
+#define COMP_REACH 3
+#define COMP_CLUSTER 4
+#define COMP_AASOPTIMIZE 5
+#define COMP_AASINFO 6
+
+int main (int argc, char **argv)
+{
+ int i, comp = 0;
+ char outputpath[MAX_PATH] = "";
+ char filename[MAX_PATH] = "unknown";
+ quakefile_t *qfiles, *qf;
+ double start_time;
+
+ myargc = argc;
+ myargv = argv;
+
+ start_time = I_FloatTime();
+
+ Log_Open("bspc.log"); //open a log file
+ Log_Print("BSPC version "BSPC_VERSION", %s %s\n", __DATE__, __TIME__);
+
+ DefaultCfg();
+ for (i = 1; i < argc; i++)
+ {
+ if (!stricmp(argv[i],"-threads"))
+ {
+ if (i + 1 >= argc) {i = 0; break;}
+ numthreads = atoi(argv[++i]);
+ Log_Print("threads = %d\n", numthreads);
+ } //end if
+ else if (!stricmp(argv[i], "-noverbose"))
+ {
+ Log_Print("verbose = false\n");
+ verbose = false;
+ } //end else if
+ else if (!stricmp(argv[i], "-nocsg"))
+ {
+ Log_Print("nocsg = true\n");
+ nocsg = true;
+ } //end else if
+ else if (!stricmp(argv[i], "-optimize"))
+ {
+ Log_Print("optimize = true\n");
+ optimize = true;
+ } //end else if
+ /*
+ else if (!stricmp(argv[i],"-glview"))
+ {
+ glview = true;
+ } //end else if
+ else if (!stricmp(argv[i], "-draw"))
+ {
+ Log_Print("drawflag = true\n");
+ drawflag = true;
+ } //end else if
+ else if (!stricmp(argv[i], "-noweld"))
+ {
+ Log_Print("noweld = true\n");
+ noweld = true;
+ } //end else if
+ else if (!stricmp(argv[i], "-noshare"))
+ {
+ Log_Print("noshare = true\n");
+ noshare = true;
+ } //end else if
+ else if (!stricmp(argv[i], "-notjunc"))
+ {
+ Log_Print("notjunc = true\n");
+ notjunc = true;
+ } //end else if
+ else if (!stricmp(argv[i], "-nowater"))
+ {
+ Log_Print("nowater = true\n");
+ nowater = true;
+ } //end else if
+ else if (!stricmp(argv[i], "-noprune"))
+ {
+ Log_Print("noprune = true\n");
+ noprune = true;
+ } //end else if
+ else if (!stricmp(argv[i], "-nomerge"))
+ {
+ Log_Print("nomerge = true\n");
+ nomerge = true;
+ } //end else if
+ else if (!stricmp(argv[i], "-nosubdiv"))
+ {
+ Log_Print("nosubdiv = true\n");
+ nosubdiv = true;
+ } //end else if
+ else if (!stricmp(argv[i], "-nodetail"))
+ {
+ Log_Print("nodetail = true\n");
+ nodetail = true;
+ } //end else if
+ else if (!stricmp(argv[i], "-fulldetail"))
+ {
+ Log_Print("fulldetail = true\n");
+ fulldetail = true;
+ } //end else if
+ else if (!stricmp(argv[i], "-onlyents"))
+ {
+ Log_Print("onlyents = true\n");
+ onlyents = true;
+ } //end else if
+ else if (!stricmp(argv[i], "-micro"))
+ {
+ if (i + 1 >= argc) {i = 0; break;}
+ microvolume = atof(argv[++i]);
+ Log_Print("microvolume = %f\n", microvolume);
+ } //end else if
+ else if (!stricmp(argv[i], "-leaktest"))
+ {
+ Log_Print("leaktest = true\n");
+ leaktest = true;
+ } //end else if
+ else if (!stricmp(argv[i], "-verboseentities"))
+ {
+ Log_Print("verboseentities = true\n");
+ verboseentities = true;
+ } //end else if
+ else if (!stricmp(argv[i], "-chop"))
+ {
+ if (i + 1 >= argc) {i = 0; break;}
+ subdivide_size = atof(argv[++i]);
+ Log_Print("subdivide_size = %f\n", subdivide_size);
+ } //end else if
+ else if (!stricmp (argv[i], "-tmpout"))
+ {
+ strcpy (outbase, "/tmp");
+ Log_Print("temp output\n");
+ } //end else if
+ */
+#ifdef ME
+ else if (!stricmp(argv[i], "-freetree"))
+ {
+ freetree = true;
+ Log_Print("freetree = true\n");
+ } //end else if
+ else if (!stricmp(argv[i], "-grapplereach"))
+ {
+ calcgrapplereach = true;
+ Log_Print("grapplereach = true\n");
+ } //end else if
+ else if (!stricmp(argv[i], "-nobrushmerge"))
+ {
+ nobrushmerge = true;
+ Log_Print("nobrushmerge = true\n");
+ } //end else if
+ else if (!stricmp(argv[i], "-noliquids"))
+ {
+ noliquids = true;
+ Log_Print("noliquids = true\n");
+ } //end else if
+ else if (!stricmp(argv[i], "-forcesidesvisible"))
+ {
+ forcesidesvisible = true;
+ Log_Print("forcesidesvisible = true\n");
+ } //end else if
+ else if (!stricmp(argv[i], "-output"))
+ {
+ if (i + 1 >= argc) {i = 0; break;}
+ if (access(argv[i+1], 0x04)) Warning("the folder %s does not exist", argv[i+1]);
+ strcpy(outputpath, argv[++i]);
+ } //end else if
+ else if (!stricmp(argv[i], "-breadthfirst"))
+ {
+ use_nodequeue = true;
+ Log_Print("breadthfirst = true\n");
+ } //end else if
+ else if (!stricmp(argv[i], "-capsule"))
+ {
+ capsule_collision = true;
+ Log_Print("capsule_collision = true\n");
+ } //end else if
+ else if (!stricmp(argv[i], "-cfg"))
+ {
+ if (i + 1 >= argc) {i = 0; break;}
+ if (!LoadCfgFile(argv[++i]))
+ exit(0);
+ } //end else if
+ else if (!stricmp(argv[i], "-bsp2map"))
+ {
+ if (i + 1 >= argc) {i = 0; break;}
+ comp = COMP_BSP2MAP;
+ qfiles = GetArgumentFiles(argc, argv, &i, "bsp");
+ } //end else if
+ else if (!stricmp(argv[i], "-bsp2aas"))
+ {
+ if (i + 1 >= argc) {i = 0; break;}
+ comp = COMP_BSP2AAS;
+ qfiles = GetArgumentFiles(argc, argv, &i, "bsp");
+ } //end else if
+ else if (!stricmp(argv[i], "-aasall"))
+ {
+ if (i + 1 >= argc) {i = 0; break;}
+ CreateAASFilesForAllBSPFiles(argv[++i]);
+ } //end else if
+ else if (!stricmp(argv[i], "-reach"))
+ {
+ if (i + 1 >= argc) {i = 0; break;}
+ comp = COMP_REACH;
+ qfiles = GetArgumentFiles(argc, argv, &i, "bsp");
+ } //end else if
+ else if (!stricmp(argv[i], "-cluster"))
+ {
+ if (i + 1 >= argc) {i = 0; break;}
+ comp = COMP_CLUSTER;
+ qfiles = GetArgumentFiles(argc, argv, &i, "bsp");
+ } //end else if
+ else if (!stricmp(argv[i], "-aasinfo"))
+ {
+ if (i + 1 >= argc) {i = 0; break;}
+ comp = COMP_AASINFO;
+ qfiles = GetArgumentFiles(argc, argv, &i, "aas");
+ } //end else if
+ else if (!stricmp(argv[i], "-aasopt"))
+ {
+ if (i + 1 >= argc) {i = 0; break;}
+ comp = COMP_AASOPTIMIZE;
+ qfiles = GetArgumentFiles(argc, argv, &i, "aas");
+ } //end else if
+#endif //ME
+ else
+ {
+ Log_Print("unknown parameter %s\n", argv[i]);
+ break;
+ } //end else
+ } //end for
+
+ //if there are parameters and there's no mismatch in one of the parameters
+ if (argc > 1 && i == argc)
+ {
+ switch(comp)
+ {
+ case COMP_BSP2MAP:
+ {
+ if (!qfiles) Log_Print("no files found\n");
+ for (qf = qfiles; qf; qf = qf->next)
+ {
+ //copy the output path
+ strcpy(filename, outputpath);
+ //append the bsp file base
+ AppendPathSeperator(filename, MAX_PATH);
+ ExtractFileBase(qf->origname, &filename[strlen(filename)]);
+ //append .map
+ strcat(filename, ".map");
+ //
+ Log_Print("bsp2map: %s to %s\n", qf->origname, filename);
+ if (qf->type != QFILETYPE_BSP) Warning("%s is probably not a BSP file\n", qf->origname);
+ //
+ LoadMapFromBSP(qf);
+ //write the map file
+ WriteMapFile(filename);
+ } //end for
+ break;
+ } //end case
+ case COMP_BSP2AAS:
+ {
+ if (!qfiles) Log_Print("no files found\n");
+ for (qf = qfiles; qf; qf = qf->next)
+ {
+ AASOuputFile(qf, outputpath, filename);
+ //
+ Log_Print("bsp2aas: %s to %s\n", qf->origname, filename);
+ if (qf->type != QFILETYPE_BSP) Warning("%s is probably not a BSP file\n", qf->origname);
+ //set before map loading
+ create_aas = 1;
+ LoadMapFromBSP(qf);
+ //create the AAS file
+ AAS_Create(filename);
+ //if it's a Quake3 map calculate the reachabilities and clusters
+ if (loadedmaptype == MAPTYPE_QUAKE3) AAS_CalcReachAndClusters(qf);
+ //
+ if (optimize) AAS_Optimize();
+ //
+ //write out the stored AAS file
+ if (!AAS_WriteAASFile(filename))
+ {
+ Error("error writing %s\n", filename);
+ } //end if
+ //deallocate memory
+ AAS_FreeMaxAAS();
+ } //end for
+ break;
+ } //end case
+ case COMP_REACH:
+ {
+ if (!qfiles) Log_Print("no files found\n");
+ for (qf = qfiles; qf; qf = qf->next)
+ {
+ AASOuputFile(qf, outputpath, filename);
+ //
+ Log_Print("reach: %s to %s\n", qf->origname, filename);
+ if (qf->type != QFILETYPE_BSP) Warning("%s is probably not a BSP file\n", qf->origname);
+ //if the AAS file exists in the output directory
+ if (!access(filename, 0x04))
+ {
+ if (!AAS_LoadAASFile(filename, 0, 0))
+ {
+ Error("error loading aas file %s\n", filename);
+ } //end if
+ //assume it's a Quake3 BSP file
+ loadedmaptype = MAPTYPE_QUAKE3;
+ } //end if
+ else
+ {
+ Warning("AAS file %s not found in output folder\n", filename);
+ Log_Print("creating %s...\n", filename);
+ //set before map loading
+ create_aas = 1;
+ LoadMapFromBSP(qf);
+ //create the AAS file
+ AAS_Create(filename);
+ } //end else
+ //if it's a Quake3 map calculate the reachabilities and clusters
+ if (loadedmaptype == MAPTYPE_QUAKE3)
+ {
+ AAS_CalcReachAndClusters(qf);
+ } //end if
+ //
+ if (optimize) AAS_Optimize();
+ //write out the stored AAS file
+ if (!AAS_WriteAASFile(filename))
+ {
+ Error("error writing %s\n", filename);
+ } //end if
+ //deallocate memory
+ AAS_FreeMaxAAS();
+ } //end for
+ break;
+ } //end case
+ case COMP_CLUSTER:
+ {
+ if (!qfiles) Log_Print("no files found\n");
+ for (qf = qfiles; qf; qf = qf->next)
+ {
+ AASOuputFile(qf, outputpath, filename);
+ //
+ Log_Print("cluster: %s to %s\n", qf->origname, filename);
+ if (qf->type != QFILETYPE_BSP) Warning("%s is probably not a BSP file\n", qf->origname);
+ //if the AAS file exists in the output directory
+ if (!access(filename, 0x04))
+ {
+ if (!AAS_LoadAASFile(filename, 0, 0))
+ {
+ Error("error loading aas file %s\n", filename);
+ } //end if
+ //assume it's a Quake3 BSP file
+ loadedmaptype = MAPTYPE_QUAKE3;
+ //if it's a Quake3 map calculate the clusters
+ if (loadedmaptype == MAPTYPE_QUAKE3)
+ {
+ aasworld.numclusters = 0;
+ AAS_InitBotImport();
+ AAS_InitClustering();
+ } //end if
+ } //end if
+ else
+ {
+ Warning("AAS file %s not found in output folder\n", filename);
+ Log_Print("creating %s...\n", filename);
+ //set before map loading
+ create_aas = 1;
+ LoadMapFromBSP(qf);
+ //create the AAS file
+ AAS_Create(filename);
+ //if it's a Quake3 map calculate the reachabilities and clusters
+ if (loadedmaptype == MAPTYPE_QUAKE3) AAS_CalcReachAndClusters(qf);
+ } //end else
+ //
+ if (optimize) AAS_Optimize();
+ //write out the stored AAS file
+ if (!AAS_WriteAASFile(filename))
+ {
+ Error("error writing %s\n", filename);
+ } //end if
+ //deallocate memory
+ AAS_FreeMaxAAS();
+ } //end for
+ break;
+ } //end case
+ case COMP_AASOPTIMIZE:
+ {
+ if (!qfiles) Log_Print("no files found\n");
+ for (qf = qfiles; qf; qf = qf->next)
+ {
+ AASOuputFile(qf, outputpath, filename);
+ //
+ Log_Print("optimizing: %s to %s\n", qf->origname, filename);
+ if (qf->type != QFILETYPE_AAS) Warning("%s is probably not a AAS file\n", qf->origname);
+ //
+ AAS_InitBotImport();
+ //
+ if (!AAS_LoadAASFile(qf->filename, qf->offset, qf->length))
+ {
+ Error("error loading aas file %s\n", qf->filename);
+ } //end if
+ AAS_Optimize();
+ //write out the stored AAS file
+ if (!AAS_WriteAASFile(filename))
+ {
+ Error("error writing %s\n", filename);
+ } //end if
+ //deallocate memory
+ AAS_FreeMaxAAS();
+ } //end for
+ break;
+ } //end case
+ case COMP_AASINFO:
+ {
+ if (!qfiles) Log_Print("no files found\n");
+ for (qf = qfiles; qf; qf = qf->next)
+ {
+ AASOuputFile(qf, outputpath, filename);
+ //
+ Log_Print("aas info for: %s\n", filename);
+ if (qf->type != QFILETYPE_AAS) Warning("%s is probably not a AAS file\n", qf->origname);
+ //
+ AAS_InitBotImport();
+ //
+ if (!AAS_LoadAASFile(qf->filename, qf->offset, qf->length))
+ {
+ Error("error loading aas file %s\n", qf->filename);
+ } //end if
+ AAS_ShowTotals();
+ } //end for
+ } //end case
+ default:
+ {
+ Log_Print("don't know what to do\n");
+ break;
+ } //end default
+ } //end switch
+ } //end if
+ else
+ {
+ Log_Print("Usage: bspc [-<switch> [-<switch> ...]]\n"
+#if defined(WIN32) || defined(_WIN32)
+ "Example 1: bspc -bsp2aas d:\\quake3\\baseq3\\maps\\mymap?.bsp\n"
+ "Example 2: bspc -bsp2aas d:\\quake3\\baseq3\\pak0.pk3\\maps/q3dm*.bsp\n"
+#else
+ "Example 1: bspc -bsp2aas /quake3/baseq3/maps/mymap?.bsp\n"
+ "Example 2: bspc -bsp2aas /quake3/baseq3/pak0.pk3/maps/q3dm*.bsp\n"
+#endif
+ "\n"
+ "Switches:\n"
+ //" bsp2map <[pakfilter/]filter.bsp> = convert BSP to MAP\n"
+ //" aasall <quake3folder> = create AAS files for all BSPs\n"
+ " bsp2aas <[pakfilter/]filter.bsp> = convert BSP to AAS\n"
+ " reach <filter.bsp> = compute reachability & clusters\n"
+ " cluster <filter.aas> = compute clusters\n"
+ " aasopt <filter.aas> = optimize aas file\n"
+ " aasinfo <filter.aas> = show AAS file info\n"
+ " output <output path> = set output path\n"
+ " threads <X> = set number of threads to X\n"
+ " cfg <filename> = use this cfg file\n"
+ " optimize = enable optimization\n"
+ " noverbose = disable verbose output\n"
+ " breadthfirst = breadth first bsp building\n"
+ " nobrushmerge = don't merge brushes\n"
+ " noliquids = don't write liquids to map\n"
+ " freetree = free the bsp tree\n"
+ " nocsg = disables brush chopping\n"
+ " forcesidesvisible = force all sides to be visible\n"
+ " grapplereach = calculate grapple reachabilities\n"
+
+/* " glview = output a GL view\n"
+ " draw = enables drawing\n"
+ " noweld = disables weld\n"
+ " noshare = disables sharing\n"
+ " notjunc = disables juncs\n"
+ " nowater = disables water brushes\n"
+ " noprune = disables node prunes\n"
+ " nomerge = disables face merging\n"
+ " nosubdiv = disables subdeviding\n"
+ " nodetail = disables detail brushes\n"
+ " fulldetail = enables full detail\n"
+ " onlyents = only compile entities with bsp\n"
+ " micro <volume>\n"
+ " = sets the micro volume to the given float\n"
+ " leaktest = perform a leak test\n"
+ " verboseentities\n"
+ " = enable entity verbose mode\n"
+ " chop <subdivide_size>\n"
+ " = sets the subdivide size to the given float\n"*/
+ "\n");
+ } //end else
+ Log_Print("BSPC run time is %5.0f seconds\n", I_FloatTime() - start_time);
+ Log_Close(); //close the log file
+ return 0;
+} //end of the function main
+
diff --git a/code/bspc/bspc.sln b/code/bspc/bspc.sln
new file mode 100755
index 0000000..79dc8ae
--- /dev/null
+++ b/code/bspc/bspc.sln
@@ -0,0 +1,28 @@
+Microsoft Visual Studio Solution File, Format Version 8.00
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "bspc", "bspc.vcproj", "{4E4EBC16-F345-4667-84E1-86633BAFDAE6}"
+ ProjectSection(ProjectDependencies) = postProject
+ EndProjectSection
+EndProject
+Global
+ GlobalSection(SourceCodeControl) = preSolution
+ SccNumberOfProjects = 1
+ SccProjectUniqueName0 = bspc.vcproj
+ SccProjectName0 = \u0022$/source/code/bspc\u0022,\u0020IGAAAAAA
+ SccLocalPath0 = .
+ SccProvider0 = MSSCCI:Perforce\u0020SCM
+ EndGlobalSection
+ GlobalSection(SolutionConfiguration) = preSolution
+ Debug = Debug
+ Release = Release
+ EndGlobalSection
+ GlobalSection(ProjectConfiguration) = postSolution
+ {4E4EBC16-F345-4667-84E1-86633BAFDAE6}.Debug.ActiveCfg = Debug|Win32
+ {4E4EBC16-F345-4667-84E1-86633BAFDAE6}.Debug.Build.0 = Debug|Win32
+ {4E4EBC16-F345-4667-84E1-86633BAFDAE6}.Release.ActiveCfg = Release|Win32
+ {4E4EBC16-F345-4667-84E1-86633BAFDAE6}.Release.Build.0 = Release|Win32
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ EndGlobalSection
+ GlobalSection(ExtensibilityAddIns) = postSolution
+ EndGlobalSection
+EndGlobal
diff --git a/code/bspc/bspc.vcproj b/code/bspc/bspc.vcproj
new file mode 100755
index 0000000..6171e1a
--- /dev/null
+++ b/code/bspc/bspc.vcproj
@@ -0,0 +1,1381 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+ ProjectType="Visual C++"
+ Version="7.10"
+ Name="bspc"
+ SccProjectName="&quot;$/source/code/bspc&quot;, IGAAAAAA"
+ SccLocalPath=".">
+ <Platforms>
+ <Platform
+ Name="Win32"/>
+ </Platforms>
+ <Configurations>
+ <Configuration
+ Name="Debug|Win32"
+ OutputDirectory=".\Debug"
+ IntermediateDirectory=".\Debug"
+ ConfigurationType="1"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;BSPC"
+ BasicRuntimeChecks="3"
+ RuntimeLibrary="1"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Debug/bspc.pch"
+ AssemblerListingLocation=".\Debug/"
+ ObjectFile=".\Debug/"
+ ProgramDataBaseFileName=".\Debug/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ OutputFile="..\Debug\bspc.exe"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile=".\Debug/bspc.pdb"
+ SubSystem="1"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ TypeLibraryName=".\Debug/bspc.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Release|Win32"
+ OutputDirectory=".\Release"
+ IntermediateDirectory=".\Release"
+ ConfigurationType="1"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;BSPC"
+ StringPooling="TRUE"
+ RuntimeLibrary="0"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Release/bspc.pch"
+ AssemblerListingLocation=".\Release/"
+ ObjectFile=".\Release/"
+ ProgramDataBaseFileName=".\Release/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ OutputFile="..\Release\bspc.exe"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ ProgramDatabaseFile=".\Release/bspc.pdb"
+ SubSystem="1"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ TypeLibraryName=".\Release/bspc.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ </Configurations>
+ <References>
+ </References>
+ <Files>
+ <Filter
+ Name="Source Files"
+ Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat">
+ <File
+ RelativePath="_files.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="aas_areamerging.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="aas_cfg.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="aas_create.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="aas_edgemelting.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="aas_facemerging.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="aas_file.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="aas_gsubdiv.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="aas_map.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="aas_prunenodes.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="aas_store.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="be_aas_bspc.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\botlib\be_aas_bspq3.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\botlib\be_aas_cluster.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\botlib\be_aas_move.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\botlib\be_aas_optimize.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\botlib\be_aas_reach.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\botlib\be_aas_sample.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="brushbsp.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="bspc.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\qcommon\cm_load.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\qcommon\cm_patch.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\qcommon\cm_test.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\qcommon\cm_trace.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="csg.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="glfile.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="l_bsp_ent.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="l_bsp_hl.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="l_bsp_q1.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="l_bsp_q2.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="l_bsp_q3.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="l_bsp_sin.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="l_cmd.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\botlib\l_libvar.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="l_log.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="l_math.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="l_mem.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="l_poly.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\botlib\l_precomp.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="l_qfiles.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\botlib\l_script.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\botlib\l_struct.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="l_threads.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="l_utils.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="leakfile.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="map.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="map_hl.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="map_q1.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="map_q2.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="map_q3.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="map_sin.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\qcommon\md4.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="nodraw.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="portals.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="textures.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tree.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\qcommon\unzip.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <Filter
+ Name="Header Files"
+ Filter="h;hpp;hxx;hm;inl">
+ <File
+ RelativePath="aas_areamerging.h">
+ </File>
+ <File
+ RelativePath="aas_cfg.h">
+ </File>
+ <File
+ RelativePath="aas_create.h">
+ </File>
+ <File
+ RelativePath="aas_edgemelting.h">
+ </File>
+ <File
+ RelativePath="aas_facemerging.h">
+ </File>
+ <File
+ RelativePath="aas_file.h">
+ </File>
+ <File
+ RelativePath="aas_gsubdiv.h">
+ </File>
+ <File
+ RelativePath="aas_map.h">
+ </File>
+ <File
+ RelativePath="aas_prunenodes.h">
+ </File>
+ <File
+ RelativePath="aas_store.h">
+ </File>
+ <File
+ RelativePath="..\botlib\aasfile.h">
+ </File>
+ <File
+ RelativePath="..\botlib\be_aas_bsp.h">
+ </File>
+ <File
+ RelativePath="be_aas_bspc.h">
+ </File>
+ <File
+ RelativePath="..\botlib\be_aas_cluster.h">
+ </File>
+ <File
+ RelativePath="..\botlib\be_aas_debug.h">
+ </File>
+ <File
+ RelativePath="..\botlib\be_aas_def.h">
+ </File>
+ <File
+ RelativePath="..\botlib\be_aas_entity.h">
+ </File>
+ <File
+ RelativePath="..\botlib\be_aas_file.h">
+ </File>
+ <File
+ RelativePath="..\botlib\be_aas_funcs.h">
+ </File>
+ <File
+ RelativePath="..\botlib\be_aas_main.h">
+ </File>
+ <File
+ RelativePath="..\botlib\be_aas_move.h">
+ </File>
+ <File
+ RelativePath="..\botlib\be_aas_optimize.h">
+ </File>
+ <File
+ RelativePath="..\botlib\be_aas_reach.h">
+ </File>
+ <File
+ RelativePath="..\botlib\be_aas_route.h">
+ </File>
+ <File
+ RelativePath="..\botlib\be_aas_routealt.h">
+ </File>
+ <File
+ RelativePath="..\botlib\be_aas_sample.h">
+ </File>
+ <File
+ RelativePath="..\botlib\be_interface.h">
+ </File>
+ <File
+ RelativePath="..\game\bg_public.h">
+ </File>
+ <File
+ RelativePath="..\cgame\cg_public.h">
+ </File>
+ <File
+ RelativePath="..\client\client.h">
+ </File>
+ <File
+ RelativePath="..\qcommon\cm_local.h">
+ </File>
+ <File
+ RelativePath="..\qcommon\cm_patch.h">
+ </File>
+ <File
+ RelativePath="..\qcommon\cm_polylib.h">
+ </File>
+ <File
+ RelativePath="..\qcommon\cm_public.h">
+ </File>
+ <File
+ RelativePath="..\ui\keycodes.h">
+ </File>
+ <File
+ RelativePath="..\client\keys.h">
+ </File>
+ <File
+ RelativePath="l_bsp_ent.h">
+ </File>
+ <File
+ RelativePath="l_bsp_hl.h">
+ </File>
+ <File
+ RelativePath="l_bsp_q1.h">
+ </File>
+ <File
+ RelativePath="l_bsp_q2.h">
+ </File>
+ <File
+ RelativePath="l_bsp_q3.h">
+ </File>
+ <File
+ RelativePath="l_bsp_sin.h">
+ </File>
+ <File
+ RelativePath="l_cmd.h">
+ </File>
+ <File
+ RelativePath="..\botlib\l_libvar.h">
+ </File>
+ <File
+ RelativePath="l_log.h">
+ </File>
+ <File
+ RelativePath="..\botlib\l_log.h">
+ </File>
+ <File
+ RelativePath="l_math.h">
+ </File>
+ <File
+ RelativePath="l_mem.h">
+ </File>
+ <File
+ RelativePath="..\botlib\l_memory.h">
+ </File>
+ <File
+ RelativePath="l_poly.h">
+ </File>
+ <File
+ RelativePath="..\botlib\l_precomp.h">
+ </File>
+ <File
+ RelativePath="l_qfiles.h">
+ </File>
+ <File
+ RelativePath="..\botlib\l_script.h">
+ </File>
+ <File
+ RelativePath="..\botlib\l_struct.h">
+ </File>
+ <File
+ RelativePath="l_threads.h">
+ </File>
+ <File
+ RelativePath="l_utils.h">
+ </File>
+ <File
+ RelativePath="q2files.h">
+ </File>
+ <File
+ RelativePath="q3files.h">
+ </File>
+ <File
+ RelativePath="..\game\q_shared.h">
+ </File>
+ <File
+ RelativePath="qbsp.h">
+ </File>
+ <File
+ RelativePath="..\qcommon\qcommon.h">
+ </File>
+ <File
+ RelativePath="..\qcommon\qfiles.h">
+ </File>
+ <File
+ RelativePath="sinfiles.h">
+ </File>
+ <File
+ RelativePath="..\client\snd_public.h">
+ </File>
+ <File
+ RelativePath="..\game\surfaceflags.h">
+ </File>
+ <File
+ RelativePath="..\renderer\tr_public.h">
+ </File>
+ <File
+ RelativePath="..\cgame\tr_types.h">
+ </File>
+ <File
+ RelativePath="..\ui\ui_public.h">
+ </File>
+ <File
+ RelativePath="..\qcommon\unzip.h">
+ </File>
+ </Filter>
+ <Filter
+ Name="Resource Files"
+ Filter="ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe">
+ </Filter>
+ </Files>
+ <Globals>
+ </Globals>
+</VisualStudioProject>
diff --git a/code/bspc/cfgq3.c b/code/bspc/cfgq3.c
new file mode 100755
index 0000000..588509c
--- /dev/null
+++ b/code/bspc/cfgq3.c
@@ -0,0 +1,84 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//===========================================================================
+// BSPC configuration file
+// Quake3
+//===========================================================================
+
+#define PRESENCE_NONE 1
+#define PRESENCE_NORMAL 2
+#define PRESENCE_CROUCH 4
+
+bbox //30x30x56
+{
+ presencetype PRESENCE_NORMAL
+ flags 0x0000
+ mins {-15, -15, -24}
+ maxs {15, 15, 32}
+} //end bbox
+
+bbox //30x30x40
+{
+ presencetype PRESENCE_CROUCH
+ flags 0x0001
+ mins {-15, -15, -24}
+ maxs {15, 15, 16}
+} //end bbox
+
+settings
+{
+ phys_gravitydirection {0, 0, -1}
+ phys_friction 6
+ phys_stopspeed 100
+ phys_gravity 800
+ phys_waterfriction 1
+ phys_watergravity 400
+ phys_maxvelocity 320
+ phys_maxwalkvelocity 320
+ phys_maxcrouchvelocity 100
+ phys_maxswimvelocity 150
+ phys_maxacceleration 2200
+ phys_airaccelerate 0
+ phys_maxstep 18
+ phys_maxsteepness 0.7
+ phys_maxwaterjump 19
+ phys_maxbarrier 33
+ phys_jumpvel 270
+ phys_falldelta5 40
+ phys_falldelta10 60
+ rs_waterjump 400
+ rs_teleport 50
+ rs_barrierjump 100
+ rs_startcrouch 300
+ rs_startgrapple 500
+ rs_startwalkoffledge 70
+ rs_startjump 300
+ rs_rocketjump 500
+ rs_bfgjump 500
+ rs_jumppad 250
+ rs_aircontrolledjumppad 300
+ rs_funcbob 300
+ rs_startelevator 50
+ rs_falldamage5 300
+ rs_falldamage10 500
+ rs_maxjumpfallheight 450
+} //end settings
diff --git a/code/bspc/csg.c b/code/bspc/csg.c
new file mode 100755
index 0000000..c141075
--- /dev/null
+++ b/code/bspc/csg.c
@@ -0,0 +1,1005 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+
+/*
+
+tag all brushes with original contents
+brushes may contain multiple contents
+there will be no brush overlap after csg phase
+
+*/
+
+int minplanenums[3];
+int maxplanenums[3];
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void CheckBSPBrush(bspbrush_t *brush)
+{
+ int i, j;
+ plane_t *plane1, *plane2;
+
+ //check if the brush is convex... flipped planes make a brush non-convex
+ for (i = 0; i < brush->numsides; i++)
+ {
+ for (j = 0; j < brush->numsides; j++)
+ {
+ if (i == j) continue;
+ plane1 = &mapplanes[brush->sides[i].planenum];
+ plane2 = &mapplanes[brush->sides[j].planenum];
+ //
+ if (WindingsNonConvex(brush->sides[i].winding,
+ brush->sides[j].winding,
+ plane1->normal, plane2->normal,
+ plane1->dist, plane2->dist))
+ {
+ Log_Print("non convex brush");
+ break;
+ } //end if
+ } //end for
+ } //end for
+ BoundBrush(brush);
+ //check for out of bound brushes
+ for (i = 0; i < 3; i++)
+ {
+ if (brush->mins[i] < -MAX_MAP_BOUNDS || brush->maxs[i] > MAX_MAP_BOUNDS)
+ {
+ Log_Print("brush: bounds out of range\n");
+ Log_Print("ob->mins[%d] = %f, ob->maxs[%d] = %f\n", i, brush->mins[i], i, brush->maxs[i]);
+ break;
+ } //end if
+ if (brush->mins[i] > MAX_MAP_BOUNDS || brush->maxs[i] < -MAX_MAP_BOUNDS)
+ {
+ Log_Print("brush: no visible sides on brush\n");
+ Log_Print("ob->mins[%d] = %f, ob->maxs[%d] = %f\n", i, brush->mins[i], i, brush->maxs[i]);
+ break;
+ } //end if
+ } //end for
+} //end of the function CheckBSPBrush
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void BSPBrushWindings(bspbrush_t *brush)
+{
+ int i, j;
+ winding_t *w;
+ plane_t *plane;
+
+ for (i = 0; i < brush->numsides; i++)
+ {
+ plane = &mapplanes[brush->sides[i].planenum];
+ w = BaseWindingForPlane(plane->normal, plane->dist);
+ for (j = 0; j < brush->numsides && w; j++)
+ {
+ if (i == j) continue;
+ plane = &mapplanes[brush->sides[j].planenum^1];
+ ChopWindingInPlace(&w, plane->normal, plane->dist, 0); //CLIP_EPSILON);
+ } //end for
+ brush->sides[i].winding = w;
+ } //end for
+} //end of the function BSPBrushWindings
+//===========================================================================
+// NOTE: can't keep brush->original intact
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bspbrush_t *TryMergeBrushes(bspbrush_t *brush1, bspbrush_t *brush2)
+{
+ int i, j, k, n, shared;
+ side_t *side1, *side2, *cs;
+ plane_t *plane1, *plane2;
+ bspbrush_t *newbrush;
+
+ //check for bounding box overlapp
+ for (i = 0; i < 3; i++)
+ {
+ if (brush1->mins[i] > brush2->maxs[i] + 2
+ || brush1->maxs[i] < brush2->mins[i] - 2)
+ {
+ return NULL;
+ } //end if
+ } //end for
+ //
+ shared = 0;
+ //check if the brush is convex... flipped planes make a brush non-convex
+ for (i = 0; i < brush1->numsides; i++)
+ {
+ side1 = &brush1->sides[i];
+ //don't check the "shared" sides
+ for (k = 0; k < brush2->numsides; k++)
+ {
+ side2 = &brush2->sides[k];
+ if (side1->planenum == (side2->planenum^1))
+ {
+ shared++;
+ //there may only be ONE shared side
+ if (shared > 1) return NULL;
+ break;
+ } //end if
+ } //end for
+ if (k < brush2->numsides) continue;
+ //
+ for (j = 0; j < brush2->numsides; j++)
+ {
+ side2 = &brush2->sides[j];
+ //don't check the "shared" sides
+ for (n = 0; n < brush1->numsides; n++)
+ {
+ side1 = &brush1->sides[n];
+ if (side1->planenum == (side2->planenum^1)) break;
+ } //end for
+ if (n < brush1->numsides) continue;
+ //
+ side1 = &brush1->sides[i];
+ //if the side is in the same plane
+ //*
+ if (side1->planenum == side2->planenum)
+ {
+ if (side1->texinfo != TEXINFO_NODE &&
+ side2->texinfo != TEXINFO_NODE &&
+ side1->texinfo != side2->texinfo) return NULL;
+ continue;
+ } //end if
+ //
+ plane1 = &mapplanes[side1->planenum];
+ plane2 = &mapplanes[side2->planenum];
+ //
+ if (WindingsNonConvex(side1->winding, side2->winding,
+ plane1->normal, plane2->normal,
+ plane1->dist, plane2->dist))
+ {
+ return NULL;
+ } //end if
+ } //end for
+ } //end for
+ newbrush = AllocBrush(brush1->numsides + brush2->numsides);
+ newbrush->original = brush1->original;
+ newbrush->numsides = 0;
+ //newbrush->side = brush1->side; //brush contents
+ //fix texinfos for sides lying in the same plane
+ for (i = 0; i < brush1->numsides; i++)
+ {
+ side1 = &brush1->sides[i];
+ //
+ for (n = 0; n < brush2->numsides; n++)
+ {
+ side2 = &brush2->sides[n];
+ //if both sides are in the same plane get the texinfo right
+ if (side1->planenum == side2->planenum)
+ {
+ if (side1->texinfo == TEXINFO_NODE) side1->texinfo = side2->texinfo;
+ if (side2->texinfo == TEXINFO_NODE) side2->texinfo = side1->texinfo;
+ } //end if
+ } //end for
+ } //end for
+ //
+ for (i = 0; i < brush1->numsides; i++)
+ {
+ side1 = &brush1->sides[i];
+ //don't add the "shared" sides
+ for (n = 0; n < brush2->numsides; n++)
+ {
+ side2 = &brush2->sides[n];
+ if (side1->planenum == (side2->planenum ^ 1)) break;
+ } //end for
+ if (n < brush2->numsides) continue;
+ //
+ for (n = 0; n < newbrush->numsides; n++)
+ {
+ cs = &newbrush->sides[n];
+ if (cs->planenum == side1->planenum)
+ {
+ Log_Print("brush duplicate plane\n");
+ break;
+ } //end if
+ } //end if
+ if (n < newbrush->numsides) continue;
+ //add this side
+ cs = &newbrush->sides[newbrush->numsides];
+ newbrush->numsides++;
+ *cs = *side1;
+ } //end for
+ for (j = 0; j < brush2->numsides; j++)
+ {
+ side2 = &brush2->sides[j];
+ for (n = 0; n < brush1->numsides; n++)
+ {
+ side1 = &brush1->sides[n];
+ //if the side is in the same plane
+ if (side2->planenum == side1->planenum) break;
+ //don't add the "shared" sides
+ if (side2->planenum == (side1->planenum ^ 1)) break;
+ } //end for
+ if (n < brush1->numsides) continue;
+ //
+ for (n = 0; n < newbrush->numsides; n++)
+ {
+ cs = &newbrush->sides[n];
+ if (cs->planenum == side2->planenum)
+ {
+ Log_Print("brush duplicate plane\n");
+ break;
+ } //end if
+ } //end if
+ if (n < newbrush->numsides) continue;
+ //add this side
+ cs = &newbrush->sides[newbrush->numsides];
+ newbrush->numsides++;
+ *cs = *side2;
+ } //end for
+ BSPBrushWindings(newbrush);
+ BoundBrush(newbrush);
+ CheckBSPBrush(newbrush);
+ return newbrush;
+} //end of the function TryMergeBrushes
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bspbrush_t *MergeBrushes(bspbrush_t *brushlist)
+{
+ int nummerges, merged;
+ bspbrush_t *b1, *b2, *tail, *newbrush, *newbrushlist;
+ bspbrush_t *lastb2;
+
+ if (!brushlist) return NULL;
+
+ qprintf("%5d brushes merged", nummerges = 0);
+ do
+ {
+ for (tail = brushlist; tail; tail = tail->next)
+ {
+ if (!tail->next) break;
+ } //end for
+ merged = 0;
+ newbrushlist = NULL;
+ for (b1 = brushlist; b1; b1 = brushlist)
+ {
+ lastb2 = b1;
+ for (b2 = b1->next; b2; b2 = b2->next)
+ {
+ //if the brushes don't have the same contents
+ if (b1->original->contents != b2->original->contents ||
+ b1->original->expansionbbox != b2->original->expansionbbox) newbrush = NULL;
+ else newbrush = TryMergeBrushes(b1, b2);
+ if (newbrush)
+ {
+ tail->next = newbrush;
+ lastb2->next = b2->next;
+ brushlist = brushlist->next;
+ FreeBrush(b1);
+ FreeBrush(b2);
+ for (tail = brushlist; tail; tail = tail->next)
+ {
+ if (!tail->next) break;
+ } //end for
+ merged++;
+ qprintf("\r%5d", nummerges++);
+ break;
+ } //end if
+ lastb2 = b2;
+ } //end for
+ //if b1 can't be merged with any of the other brushes
+ if (!b2)
+ {
+ brushlist = brushlist->next;
+ //keep b1
+ b1->next = newbrushlist;
+ newbrushlist = b1;
+ } //end else
+ } //end for
+ brushlist = newbrushlist;
+ } while(merged);
+ qprintf("\n");
+ return newbrushlist;
+} //end of the function MergeBrushes
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void SplitBrush2 (bspbrush_t *brush, int planenum,
+ bspbrush_t **front, bspbrush_t **back)
+{
+ SplitBrush (brush, planenum, front, back);
+#if 0
+ if (*front && (*front)->sides[(*front)->numsides-1].texinfo == -1)
+ (*front)->sides[(*front)->numsides-1].texinfo = (*front)->sides[0].texinfo; // not -1
+ if (*back && (*back)->sides[(*back)->numsides-1].texinfo == -1)
+ (*back)->sides[(*back)->numsides-1].texinfo = (*back)->sides[0].texinfo; // not -1
+#endif
+} //end of the function SplitBrush2
+//===========================================================================
+// Returns a list of brushes that remain after B is subtracted from A.
+// May by empty if A is contained inside B.
+// The originals are undisturbed.
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bspbrush_t *SubtractBrush (bspbrush_t *a, bspbrush_t *b)
+{ // a - b = out (list)
+ int i;
+ bspbrush_t *front, *back;
+ bspbrush_t *out, *in;
+
+ in = a;
+ out = NULL;
+ for (i = 0; i < b->numsides && in; i++)
+ {
+ SplitBrush2(in, b->sides[i].planenum, &front, &back);
+ if (in != a) FreeBrush(in);
+ if (front)
+ { // add to list
+ front->next = out;
+ out = front;
+ } //end if
+ in = back;
+ } //end for
+ if (in)
+ {
+ FreeBrush (in);
+ } //end if
+ else
+ { // didn't really intersect
+ FreeBrushList (out);
+ return a;
+ } //end else
+ return out;
+} //end of the function SubtractBrush
+//===========================================================================
+// Returns a single brush made up by the intersection of the
+// two provided brushes, or NULL if they are disjoint.
+//
+// The originals are undisturbed.
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bspbrush_t *IntersectBrush (bspbrush_t *a, bspbrush_t *b)
+{
+ int i;
+ bspbrush_t *front, *back;
+ bspbrush_t *in;
+
+ in = a;
+ for (i=0 ; i<b->numsides && in ; i++)
+ {
+ SplitBrush2(in, b->sides[i].planenum, &front, &back);
+ if (in != a) FreeBrush(in);
+ if (front) FreeBrush(front);
+ in = back;
+ } //end for
+
+ if (in == a) return NULL;
+
+ in->next = NULL;
+ return in;
+} //end of the function IntersectBrush
+//===========================================================================
+// Returns true if the two brushes definately do not intersect.
+// There will be false negatives for some non-axial combinations.
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean BrushesDisjoint (bspbrush_t *a, bspbrush_t *b)
+{
+ int i, j;
+
+ // check bounding boxes
+ for (i=0 ; i<3 ; i++)
+ if (a->mins[i] >= b->maxs[i]
+ || a->maxs[i] <= b->mins[i])
+ return true; // bounding boxes don't overlap
+
+ // check for opposing planes
+ for (i=0 ; i<a->numsides ; i++)
+ {
+ for (j=0 ; j<b->numsides ; j++)
+ {
+ if (a->sides[i].planenum ==
+ (b->sides[j].planenum^1) )
+ return true; // opposite planes, so not touching
+ }
+ }
+
+ return false; // might intersect
+} //end of the function BrushesDisjoint
+//===========================================================================
+// Returns a content word for the intersection of two brushes.
+// Some combinations will generate a combination (water + clip),
+// but most will be the stronger of the two contents.
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int IntersectionContents (int c1, int c2)
+{
+ int out;
+
+ out = c1 | c2;
+
+ if (out & CONTENTS_SOLID) out = CONTENTS_SOLID;
+
+ return out;
+} //end of the function IntersectionContents
+//===========================================================================
+// Any planes shared with the box edge will be set to no texinfo
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bspbrush_t *ClipBrushToBox(bspbrush_t *brush, vec3_t clipmins, vec3_t clipmaxs)
+{
+ int i, j;
+ bspbrush_t *front, *back;
+ int p;
+
+ for (j=0 ; j<2 ; j++)
+ {
+ if (brush->maxs[j] > clipmaxs[j])
+ {
+ SplitBrush (brush, maxplanenums[j], &front, &back);
+ if (front)
+ FreeBrush (front);
+ brush = back;
+ if (!brush)
+ return NULL;
+ }
+ if (brush->mins[j] < clipmins[j])
+ {
+ SplitBrush (brush, minplanenums[j], &front, &back);
+ if (back)
+ FreeBrush (back);
+ brush = front;
+ if (!brush)
+ return NULL;
+ }
+ }
+
+ // remove any colinear faces
+
+ for (i=0 ; i<brush->numsides ; i++)
+ {
+ p = brush->sides[i].planenum & ~1;
+ if (p == maxplanenums[0] || p == maxplanenums[1]
+ || p == minplanenums[0] || p == minplanenums[1])
+ {
+ brush->sides[i].texinfo = TEXINFO_NODE;
+ brush->sides[i].flags &= ~SFL_VISIBLE;
+ }
+ }
+ return brush;
+} //end of the function ClipBrushToBox
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bspbrush_t *MakeBspBrushList(int startbrush, int endbrush,
+ vec3_t clipmins, vec3_t clipmaxs)
+{
+ mapbrush_t *mb;
+ bspbrush_t *brushlist, *newbrush;
+ int i, j;
+ int c_faces;
+ int c_brushes;
+ int numsides;
+ int vis;
+ vec3_t normal;
+ float dist;
+
+ for (i=0 ; i<2 ; i++)
+ {
+ VectorClear (normal);
+ normal[i] = 1;
+ dist = clipmaxs[i];
+ maxplanenums[i] = FindFloatPlane(normal, dist);
+ dist = clipmins[i];
+ minplanenums[i] = FindFloatPlane(normal, dist);
+ }
+
+ brushlist = NULL;
+ c_faces = 0;
+ c_brushes = 0;
+
+ for (i=startbrush ; i<endbrush ; i++)
+ {
+ mb = &mapbrushes[i];
+
+ numsides = mb->numsides;
+ if (!numsides)
+ continue;
+
+ // make sure the brush has at least one face showing
+ vis = 0;
+ for (j=0 ; j<numsides ; j++)
+ if ((mb->original_sides[j].flags & SFL_VISIBLE) && mb->original_sides[j].winding)
+ vis++;
+#if 0
+ if (!vis)
+ continue; // no faces at all
+#endif
+ // if the brush is outside the clip area, skip it
+ for (j=0 ; j<3 ; j++)
+ if (mb->mins[j] >= clipmaxs[j]
+ || mb->maxs[j] <= clipmins[j])
+ break;
+ if (j != 3)
+ continue;
+
+ //
+ // make a copy of the brush
+ //
+ newbrush = AllocBrush (mb->numsides);
+ newbrush->original = mb;
+ newbrush->numsides = mb->numsides;
+ memcpy (newbrush->sides, mb->original_sides, numsides*sizeof(side_t));
+ for (j=0 ; j<numsides ; j++)
+ {
+ if (newbrush->sides[j].winding)
+ newbrush->sides[j].winding = CopyWinding (newbrush->sides[j].winding);
+ if (newbrush->sides[j].surf & SURF_HINT)
+ newbrush->sides[j].flags |= SFL_VISIBLE; // hints are always visible
+ }
+ VectorCopy (mb->mins, newbrush->mins);
+ VectorCopy (mb->maxs, newbrush->maxs);
+
+ //
+ // carve off anything outside the clip box
+ //
+ newbrush = ClipBrushToBox (newbrush, clipmins, clipmaxs);
+ if (!newbrush)
+ continue;
+
+ c_faces += vis;
+ c_brushes++;
+
+ newbrush->next = brushlist;
+ brushlist = newbrush;
+ }
+
+ return brushlist;
+} //end of the function MakeBspBrushList
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bspbrush_t *AddBrushListToTail (bspbrush_t *list, bspbrush_t *tail)
+{
+ bspbrush_t *walk, *next;
+
+ for (walk=list ; walk ; walk=next)
+ { // add to end of list
+ next = walk->next;
+ walk->next = NULL;
+ tail->next = walk;
+ tail = walk;
+ } //end for
+ return tail;
+} //end of the function AddBrushListToTail
+//===========================================================================
+// Builds a new list that doesn't hold the given brush
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bspbrush_t *CullList(bspbrush_t *list, bspbrush_t *skip1)
+{
+ bspbrush_t *newlist;
+ bspbrush_t *next;
+
+ newlist = NULL;
+
+ for ( ; list ; list = next)
+ {
+ next = list->next;
+ if (list == skip1)
+ {
+ FreeBrush (list);
+ continue;
+ }
+ list->next = newlist;
+ newlist = list;
+ }
+ return newlist;
+} //end of the function CullList
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+/*
+void WriteBrushMap(char *name, bspbrush_t *list)
+{
+ FILE *f;
+ side_t *s;
+ int i;
+ winding_t *w;
+
+ Log_Print("writing %s\n", name);
+ f = fopen (name, "wb");
+ if (!f)
+ Error ("Can't write %s\b", name);
+
+ fprintf (f, "{\n\"classname\" \"worldspawn\"\n");
+
+ for ( ; list ; list=list->next )
+ {
+ fprintf (f, "{\n");
+ for (i=0,s=list->sides ; i<list->numsides ; i++,s++)
+ {
+ w = BaseWindingForPlane (mapplanes[s->planenum].normal, mapplanes[s->planenum].dist);
+
+ fprintf (f,"( %i %i %i ) ", (int)w->p[0][0], (int)w->p[0][1], (int)w->p[0][2]);
+ fprintf (f,"( %i %i %i ) ", (int)w->p[1][0], (int)w->p[1][1], (int)w->p[1][2]);
+ fprintf (f,"( %i %i %i ) ", (int)w->p[2][0], (int)w->p[2][1], (int)w->p[2][2]);
+
+ fprintf (f, "%s 0 0 0 1 1\n", texinfo[s->texinfo].texture);
+ FreeWinding (w);
+ }
+ fprintf (f, "}\n");
+ }
+ fprintf (f, "}\n");
+
+ fclose (f);
+} //end of the function WriteBrushMap
+*/
+//===========================================================================
+// Returns true if b1 is allowed to bite b2
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean BrushGE (bspbrush_t *b1, bspbrush_t *b2)
+{
+#ifdef ME
+ if (create_aas)
+ {
+ if (b1->original->expansionbbox != b2->original->expansionbbox)
+ {
+ return false;
+ } //end if
+ //never have something else bite a ladder brush
+ //never have a ladder brush bite something else
+ if ( (b1->original->contents & CONTENTS_LADDER)
+ && !(b2->original->contents & CONTENTS_LADDER))
+ {
+ return false;
+ } //end if
+ } //end if
+#endif //ME
+ // detail brushes never bite structural brushes
+ if ( (b1->original->contents & CONTENTS_DETAIL)
+ && !(b2->original->contents & CONTENTS_DETAIL) )
+ {
+ return false;
+ } //end if
+ if (b1->original->contents & CONTENTS_SOLID)
+ {
+ return true;
+ } //end if
+ return false;
+} //end of the function BrushGE
+//===========================================================================
+// Carves any intersecting solid brushes into the minimum number
+// of non-intersecting brushes.
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bspbrush_t *ChopBrushes (bspbrush_t *head)
+{
+ bspbrush_t *b1, *b2, *next;
+ bspbrush_t *tail;
+ bspbrush_t *keep;
+ bspbrush_t *sub, *sub2;
+ int c1, c2;
+ int num_csg_iterations;
+
+ Log_Print("-------- Brush CSG ---------\n");
+ Log_Print("%6d original brushes\n", CountBrushList (head));
+
+ num_csg_iterations = 0;
+ qprintf("%6d output brushes", num_csg_iterations);
+
+#if 0
+ if (startbrush == 0)
+ WriteBrushList ("before.gl", head, false);
+#endif
+ keep = NULL;
+
+newlist:
+ // find tail
+ if (!head) return NULL;
+
+ for (tail = head; tail->next; tail = tail->next)
+ ;
+
+ for (b1=head ; b1 ; b1=next)
+ {
+ next = b1->next;
+
+ //if the conversion is cancelled
+ if (cancelconversion)
+ {
+ b1->next = keep;
+ keep = b1;
+ continue;
+ } //end if
+
+ for (b2 = b1->next; b2; b2 = b2->next)
+ {
+ if (BrushesDisjoint (b1, b2))
+ continue;
+
+ sub = NULL;
+ sub2 = NULL;
+ c1 = 999999;
+ c2 = 999999;
+
+ if (BrushGE (b2, b1))
+ {
+ sub = SubtractBrush (b1, b2);
+ if (sub == b1)
+ {
+ continue; // didn't really intersect
+ } //end if
+ if (!sub)
+ { // b1 is swallowed by b2
+ head = CullList (b1, b1);
+ goto newlist;
+ }
+ c1 = CountBrushList (sub);
+ }
+
+ if ( BrushGE (b1, b2) )
+ {
+ sub2 = SubtractBrush (b2, b1);
+ if (sub2 == b2)
+ continue; // didn't really intersect
+ if (!sub2)
+ { // b2 is swallowed by b1
+ FreeBrushList (sub);
+ head = CullList (b1, b2);
+ goto newlist;
+ }
+ c2 = CountBrushList (sub2);
+ }
+
+ if (!sub && !sub2)
+ continue; // neither one can bite
+
+ // only accept if it didn't fragment
+ // (commenting this out allows full fragmentation)
+ if (c1 > 1 && c2 > 1)
+ {
+ if (sub2)
+ FreeBrushList (sub2);
+ if (sub)
+ FreeBrushList (sub);
+ continue;
+ }
+
+ if (c1 < c2)
+ {
+ if (sub2) FreeBrushList (sub2);
+ tail = AddBrushListToTail (sub, tail);
+ head = CullList (b1, b1);
+ goto newlist;
+ } //end if
+ else
+ {
+ if (sub) FreeBrushList (sub);
+ tail = AddBrushListToTail (sub2, tail);
+ head = CullList (b1, b2);
+ goto newlist;
+ } //end else
+ } //end for
+
+ if (!b2)
+ { // b1 is no longer intersecting anything, so keep it
+ b1->next = keep;
+ keep = b1;
+ } //end if
+ num_csg_iterations++;
+ qprintf("\r%6d", num_csg_iterations);
+ } //end for
+
+ if (cancelconversion) return keep;
+ //
+ qprintf("\n");
+ Log_Write("%6d output brushes\r\n", num_csg_iterations);
+
+#if 0
+ {
+ WriteBrushList ("after.gl", keep, false);
+ WriteBrushMap ("after.map", keep);
+ }
+#endif
+
+ return keep;
+} //end of the function ChopBrushes
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bspbrush_t *InitialBrushList (bspbrush_t *list)
+{
+ bspbrush_t *b;
+ bspbrush_t *out, *newb;
+ int i;
+
+ // only return brushes that have visible faces
+ out = NULL;
+ for (b=list ; b ; b=b->next)
+ {
+#if 0
+ for (i=0 ; i<b->numsides ; i++)
+ if (b->sides[i].flags & SFL_VISIBLE)
+ break;
+ if (i == b->numsides)
+ continue;
+#endif
+ newb = CopyBrush (b);
+ newb->next = out;
+ out = newb;
+
+ // clear visible, so it must be set by MarkVisibleFaces_r
+ // to be used in the optimized list
+ for (i=0 ; i<b->numsides ; i++)
+ {
+ newb->sides[i].original = &b->sides[i];
+// newb->sides[i].visible = true;
+ b->sides[i].flags &= ~SFL_VISIBLE;
+ }
+ }
+
+ return out;
+} //end of the function InitialBrushList
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bspbrush_t *OptimizedBrushList (bspbrush_t *list)
+{
+ bspbrush_t *b;
+ bspbrush_t *out, *newb;
+ int i;
+
+ // only return brushes that have visible faces
+ out = NULL;
+ for (b=list ; b ; b=b->next)
+ {
+ for (i=0 ; i<b->numsides ; i++)
+ if (b->sides[i].flags & SFL_VISIBLE)
+ break;
+ if (i == b->numsides)
+ continue;
+ newb = CopyBrush (b);
+ newb->next = out;
+ out = newb;
+ } //end for
+
+// WriteBrushList ("vis.gl", out, true);
+ return out;
+} //end of the function OptimizeBrushList
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+tree_t *ProcessWorldBrushes(int brush_start, int brush_end)
+{
+ bspbrush_t *brushes;
+ tree_t *tree;
+ node_t *node;
+ vec3_t mins, maxs;
+
+ //take the whole world
+ mins[0] = map_mins[0] - 8;
+ mins[1] = map_mins[1] - 8;
+ mins[2] = map_mins[2] - 8;
+
+ maxs[0] = map_maxs[0] + 8;
+ maxs[1] = map_maxs[1] + 8;
+ maxs[2] = map_maxs[2] + 8;
+
+ //reset the brush bsp
+ ResetBrushBSP();
+
+ // the makelist and chopbrushes could be cached between the passes...
+
+ //create a list with brushes that are within the given mins/maxs
+ //some brushes will be cut and only the part that falls within the
+ //mins/maxs will be in the bush list
+ brushes = MakeBspBrushList(brush_start, brush_end, mins, maxs);
+ //
+
+ if (!brushes)
+ {
+ node = AllocNode ();
+ node->planenum = PLANENUM_LEAF;
+ node->contents = CONTENTS_SOLID;
+
+ tree = Tree_Alloc();
+ tree->headnode = node;
+ VectorCopy(mins, tree->mins);
+ VectorCopy(maxs, tree->maxs);
+ } //end if
+ else
+ {
+ //Carves any intersecting solid brushes into the minimum number
+ //of non-intersecting brushes.
+ if (!nocsg)
+ {
+ brushes = ChopBrushes(brushes);
+ /*
+ if (create_aas)
+ {
+ brushes = MergeBrushes(brushes);
+ } //end if*/
+ } //end if
+ //if the conversion is cancelled
+ if (cancelconversion)
+ {
+ FreeBrushList(brushes);
+ return NULL;
+ } //end if
+ //create the actual bsp tree
+ tree = BrushBSP(brushes, mins, maxs);
+ } //end else
+ //return the tree
+ return tree;
+} //end of the function ProcessWorldBrushes
diff --git a/code/bspc/faces.c b/code/bspc/faces.c
new file mode 100755
index 0000000..bcd3ef9
--- /dev/null
+++ b/code/bspc/faces.c
@@ -0,0 +1,978 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// faces.c
+
+#include "qbsp.h"
+#include "l_mem.h"
+
+/*
+
+ some faces will be removed before saving, but still form nodes:
+
+ the insides of sky volumes
+ meeting planes of different water current volumes
+
+*/
+
+// undefine for dumb linear searches
+#define USE_HASHING
+
+#define INTEGRAL_EPSILON 0.01
+#define POINT_EPSILON 0.5
+#define OFF_EPSILON 0.5
+
+int c_merge;
+int c_subdivide;
+
+int c_totalverts;
+int c_uniqueverts;
+int c_degenerate;
+int c_tjunctions;
+int c_faceoverflows;
+int c_facecollapse;
+int c_badstartverts;
+
+#define MAX_SUPERVERTS 512
+int superverts[MAX_SUPERVERTS];
+int numsuperverts;
+
+face_t *edgefaces[MAX_MAP_EDGES][2];
+int firstmodeledge = 1;
+int firstmodelface;
+
+int c_tryedges;
+
+vec3_t edge_dir;
+vec3_t edge_start;
+vec_t edge_len;
+
+int num_edge_verts;
+int edge_verts[MAX_MAP_VERTS];
+
+face_t *NewFaceFromFace (face_t *f);
+
+//===========================================================================
+
+typedef struct hashvert_s
+{
+ struct hashvert_s *next;
+ int num;
+} hashvert_t;
+
+
+#define HASH_SIZE 64
+
+
+int vertexchain[MAX_MAP_VERTS]; // the next vertex in a hash chain
+int hashverts[HASH_SIZE*HASH_SIZE]; // a vertex number, or 0 for no verts
+
+face_t *edgefaces[MAX_MAP_EDGES][2];
+
+//============================================================================
+
+
+unsigned HashVec (vec3_t vec)
+{
+ int x, y;
+
+ x = (4096 + (int)(vec[0]+0.5)) >> 7;
+ y = (4096 + (int)(vec[1]+0.5)) >> 7;
+
+ if ( x < 0 || x >= HASH_SIZE || y < 0 || y >= HASH_SIZE )
+ Error ("HashVec: point outside valid range");
+
+ return y*HASH_SIZE + x;
+}
+
+#ifdef USE_HASHING
+/*
+=============
+GetVertex
+
+Uses hashing
+=============
+*/
+int GetVertexnum (vec3_t in)
+{
+ int h;
+ int i;
+ float *p;
+ vec3_t vert;
+ int vnum;
+
+ c_totalverts++;
+
+ for (i=0 ; i<3 ; i++)
+ {
+ if ( fabs(in[i] - Q_rint(in[i])) < INTEGRAL_EPSILON)
+ vert[i] = Q_rint(in[i]);
+ else
+ vert[i] = in[i];
+ }
+
+ h = HashVec (vert);
+
+ for (vnum=hashverts[h] ; vnum ; vnum=vertexchain[vnum])
+ {
+ p = dvertexes[vnum].point;
+ if ( fabs(p[0]-vert[0])<POINT_EPSILON
+ && fabs(p[1]-vert[1])<POINT_EPSILON
+ && fabs(p[2]-vert[2])<POINT_EPSILON )
+ return vnum;
+ }
+
+// emit a vertex
+ if (numvertexes == MAX_MAP_VERTS)
+ Error ("numvertexes == MAX_MAP_VERTS");
+
+ dvertexes[numvertexes].point[0] = vert[0];
+ dvertexes[numvertexes].point[1] = vert[1];
+ dvertexes[numvertexes].point[2] = vert[2];
+
+ vertexchain[numvertexes] = hashverts[h];
+ hashverts[h] = numvertexes;
+
+ c_uniqueverts++;
+
+ numvertexes++;
+
+ return numvertexes-1;
+}
+#else
+/*
+==================
+GetVertexnum
+
+Dumb linear search
+==================
+*/
+int GetVertexnum (vec3_t v)
+{
+ int i, j;
+ dvertex_t *dv;
+ vec_t d;
+
+ c_totalverts++;
+
+ // make really close values exactly integral
+ for (i=0 ; i<3 ; i++)
+ {
+ if ( fabs(v[i] - (int)(v[i]+0.5)) < INTEGRAL_EPSILON )
+ v[i] = (int)(v[i]+0.5);
+ if (v[i] < -4096 || v[i] > 4096)
+ Error ("GetVertexnum: outside +/- 4096");
+ }
+
+ // search for an existing vertex match
+ for (i=0, dv=dvertexes ; i<numvertexes ; i++, dv++)
+ {
+ for (j=0 ; j<3 ; j++)
+ {
+ d = v[j] - dv->point[j];
+ if ( d > POINT_EPSILON || d < -POINT_EPSILON)
+ break;
+ }
+ if (j == 3)
+ return i; // a match
+ }
+
+ // new point
+ if (numvertexes == MAX_MAP_VERTS)
+ Error ("MAX_MAP_VERTS");
+ VectorCopy (v, dv->point);
+ numvertexes++;
+ c_uniqueverts++;
+
+ return numvertexes-1;
+}
+#endif
+
+
+/*
+==================
+FaceFromSuperverts
+
+The faces vertexes have been added to the superverts[] array,
+and there may be more there than can be held in a face (MAXEDGES).
+
+If less, the faces vertexnums[] will be filled in, otherwise
+face will reference a tree of split[] faces until all of the
+vertexnums can be added.
+
+superverts[base] will become face->vertexnums[0], and the others
+will be circularly filled in.
+==================
+*/
+void FaceFromSuperverts (node_t *node, face_t *f, int base)
+{
+ face_t *newf;
+ int remaining;
+ int i;
+
+ remaining = numsuperverts;
+ while (remaining > MAXEDGES)
+ { // must split into two faces, because of vertex overload
+ c_faceoverflows++;
+
+ newf = f->split[0] = NewFaceFromFace (f);
+ newf = f->split[0];
+ newf->next = node->faces;
+ node->faces = newf;
+
+ newf->numpoints = MAXEDGES;
+ for (i=0 ; i<MAXEDGES ; i++)
+ newf->vertexnums[i] = superverts[(i+base)%numsuperverts];
+
+ f->split[1] = NewFaceFromFace (f);
+ f = f->split[1];
+ f->next = node->faces;
+ node->faces = f;
+
+ remaining -= (MAXEDGES-2);
+ base = (base+MAXEDGES-1)%numsuperverts;
+ }
+
+ // copy the vertexes back to the face
+ f->numpoints = remaining;
+ for (i=0 ; i<remaining ; i++)
+ f->vertexnums[i] = superverts[(i+base)%numsuperverts];
+}
+
+
+/*
+==================
+EmitFaceVertexes
+==================
+*/
+void EmitFaceVertexes (node_t *node, face_t *f)
+{
+ winding_t *w;
+ int i;
+
+ if (f->merged || f->split[0] || f->split[1])
+ return;
+
+ w = f->w;
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ if (noweld)
+ { // make every point unique
+ if (numvertexes == MAX_MAP_VERTS)
+ Error ("MAX_MAP_VERTS");
+ superverts[i] = numvertexes;
+ VectorCopy (w->p[i], dvertexes[numvertexes].point);
+ numvertexes++;
+ c_uniqueverts++;
+ c_totalverts++;
+ }
+ else
+ superverts[i] = GetVertexnum (w->p[i]);
+ }
+ numsuperverts = w->numpoints;
+
+ // this may fragment the face if > MAXEDGES
+ FaceFromSuperverts (node, f, 0);
+}
+
+/*
+==================
+EmitVertexes_r
+==================
+*/
+void EmitVertexes_r (node_t *node)
+{
+ int i;
+ face_t *f;
+
+ if (node->planenum == PLANENUM_LEAF)
+ return;
+
+ for (f=node->faces ; f ; f=f->next)
+ {
+ EmitFaceVertexes (node, f);
+ }
+
+ for (i=0 ; i<2 ; i++)
+ EmitVertexes_r (node->children[i]);
+}
+
+
+#ifdef USE_HASHING
+/*
+==========
+FindEdgeVerts
+
+Uses the hash tables to cut down to a small number
+==========
+*/
+void FindEdgeVerts (vec3_t v1, vec3_t v2)
+{
+ int x1, x2, y1, y2, t;
+ int x, y;
+ int vnum;
+
+#if 0
+{
+ int i;
+ num_edge_verts = numvertexes-1;
+ for (i=0 ; i<numvertexes-1 ; i++)
+ edge_verts[i] = i+1;
+}
+#endif
+
+ x1 = (4096 + (int)(v1[0]+0.5)) >> 7;
+ y1 = (4096 + (int)(v1[1]+0.5)) >> 7;
+ x2 = (4096 + (int)(v2[0]+0.5)) >> 7;
+ y2 = (4096 + (int)(v2[1]+0.5)) >> 7;
+
+ if (x1 > x2)
+ {
+ t = x1;
+ x1 = x2;
+ x2 = t;
+ }
+ if (y1 > y2)
+ {
+ t = y1;
+ y1 = y2;
+ y2 = t;
+ }
+#if 0
+ x1--;
+ x2++;
+ y1--;
+ y2++;
+ if (x1 < 0)
+ x1 = 0;
+ if (x2 >= HASH_SIZE)
+ x2 = HASH_SIZE;
+ if (y1 < 0)
+ y1 = 0;
+ if (y2 >= HASH_SIZE)
+ y2 = HASH_SIZE;
+#endif
+ num_edge_verts = 0;
+ for (x=x1 ; x <= x2 ; x++)
+ {
+ for (y=y1 ; y <= y2 ; y++)
+ {
+ for (vnum=hashverts[y*HASH_SIZE+x] ; vnum ; vnum=vertexchain[vnum])
+ {
+ edge_verts[num_edge_verts++] = vnum;
+ }
+ }
+ }
+}
+
+#else
+/*
+==========
+FindEdgeVerts
+
+Forced a dumb check of everything
+==========
+*/
+void FindEdgeVerts (vec3_t v1, vec3_t v2)
+{
+ int i;
+
+ num_edge_verts = numvertexes-1;
+ for (i=0 ; i<num_edge_verts ; i++)
+ edge_verts[i] = i+1;
+}
+#endif
+
+/*
+==========
+TestEdge
+
+Can be recursively reentered
+==========
+*/
+void TestEdge (vec_t start, vec_t end, int p1, int p2, int startvert)
+{
+ int j, k;
+ vec_t dist;
+ vec3_t delta;
+ vec3_t exact;
+ vec3_t off;
+ vec_t error;
+ vec3_t p;
+
+ if (p1 == p2)
+ {
+ c_degenerate++;
+ return; // degenerate edge
+ }
+
+ for (k=startvert ; k<num_edge_verts ; k++)
+ {
+ j = edge_verts[k];
+ if (j==p1 || j == p2)
+ continue;
+
+ VectorCopy (dvertexes[j].point, p);
+
+ VectorSubtract (p, edge_start, delta);
+ dist = DotProduct (delta, edge_dir);
+ if (dist <=start || dist >= end)
+ continue; // off an end
+ VectorMA (edge_start, dist, edge_dir, exact);
+ VectorSubtract (p, exact, off);
+ error = VectorLength (off);
+
+ if (fabs(error) > OFF_EPSILON)
+ continue; // not on the edge
+
+ // break the edge
+ c_tjunctions++;
+ TestEdge (start, dist, p1, j, k+1);
+ TestEdge (dist, end, j, p2, k+1);
+ return;
+ }
+
+ // the edge p1 to p2 is now free of tjunctions
+ if (numsuperverts >= MAX_SUPERVERTS)
+ Error ("MAX_SUPERVERTS");
+ superverts[numsuperverts] = p1;
+ numsuperverts++;
+}
+
+/*
+==================
+FixFaceEdges
+
+==================
+*/
+void FixFaceEdges (node_t *node, face_t *f)
+{
+ int p1, p2;
+ int i;
+ vec3_t e2;
+ vec_t len;
+ int count[MAX_SUPERVERTS], start[MAX_SUPERVERTS];
+ int base;
+
+ if (f->merged || f->split[0] || f->split[1])
+ return;
+
+ numsuperverts = 0;
+
+ for (i=0 ; i<f->numpoints ; i++)
+ {
+ p1 = f->vertexnums[i];
+ p2 = f->vertexnums[(i+1)%f->numpoints];
+
+ VectorCopy (dvertexes[p1].point, edge_start);
+ VectorCopy (dvertexes[p2].point, e2);
+
+ FindEdgeVerts (edge_start, e2);
+
+ VectorSubtract (e2, edge_start, edge_dir);
+ len = VectorNormalize(edge_dir);
+
+ start[i] = numsuperverts;
+ TestEdge (0, len, p1, p2, 0);
+
+ count[i] = numsuperverts - start[i];
+ }
+
+ if (numsuperverts < 3)
+ { // entire face collapsed
+ f->numpoints = 0;
+ c_facecollapse++;
+ return;
+ }
+
+ // we want to pick a vertex that doesn't have tjunctions
+ // on either side, which can cause artifacts on trifans,
+ // especially underwater
+ for (i=0 ; i<f->numpoints ; i++)
+ {
+ if (count[i] == 1 && count[(i+f->numpoints-1)%f->numpoints] == 1)
+ break;
+ }
+ if (i == f->numpoints)
+ {
+ f->badstartvert = true;
+ c_badstartverts++;
+ base = 0;
+ }
+ else
+ { // rotate the vertex order
+ base = start[i];
+ }
+
+ // this may fragment the face if > MAXEDGES
+ FaceFromSuperverts (node, f, base);
+}
+
+/*
+==================
+FixEdges_r
+==================
+*/
+void FixEdges_r (node_t *node)
+{
+ int i;
+ face_t *f;
+
+ if (node->planenum == PLANENUM_LEAF)
+ return;
+
+ for (f=node->faces ; f ; f=f->next)
+ FixFaceEdges (node, f);
+
+ for (i=0 ; i<2 ; i++)
+ FixEdges_r (node->children[i]);
+}
+
+/*
+===========
+FixTjuncs
+
+===========
+*/
+void FixTjuncs (node_t *headnode)
+{
+ // snap and merge all vertexes
+ qprintf ("---- snap verts ----\n");
+ memset (hashverts, 0, sizeof(hashverts));
+ c_totalverts = 0;
+ c_uniqueverts = 0;
+ c_faceoverflows = 0;
+ EmitVertexes_r (headnode);
+ qprintf ("%i unique from %i\n", c_uniqueverts, c_totalverts);
+
+ // break edges on tjunctions
+ qprintf ("---- tjunc ----\n");
+ c_tryedges = 0;
+ c_degenerate = 0;
+ c_facecollapse = 0;
+ c_tjunctions = 0;
+ if (!notjunc)
+ FixEdges_r (headnode);
+ qprintf ("%5i edges degenerated\n", c_degenerate);
+ qprintf ("%5i faces degenerated\n", c_facecollapse);
+ qprintf ("%5i edges added by tjunctions\n", c_tjunctions);
+ qprintf ("%5i faces added by tjunctions\n", c_faceoverflows);
+ qprintf ("%5i bad start verts\n", c_badstartverts);
+}
+
+
+//========================================================
+
+int c_faces;
+
+face_t *AllocFace (void)
+{
+ face_t *f;
+
+ f = GetMemory(sizeof(*f));
+ memset (f, 0, sizeof(*f));
+ c_faces++;
+
+ return f;
+}
+
+face_t *NewFaceFromFace (face_t *f)
+{
+ face_t *newf;
+
+ newf = AllocFace ();
+ *newf = *f;
+ newf->merged = NULL;
+ newf->split[0] = newf->split[1] = NULL;
+ newf->w = NULL;
+ return newf;
+}
+
+void FreeFace (face_t *f)
+{
+ if (f->w)
+ FreeWinding (f->w);
+ FreeMemory(f);
+ c_faces--;
+}
+
+//========================================================
+
+/*
+==================
+GetEdge
+
+Called by writebsp.
+Don't allow four way edges
+==================
+*/
+int GetEdge2 (int v1, int v2, face_t *f)
+{
+ dedge_t *edge;
+ int i;
+
+ c_tryedges++;
+
+ if (!noshare)
+ {
+ for (i=firstmodeledge ; i < numedges ; i++)
+ {
+ edge = &dedges[i];
+ if (v1 == edge->v[1] && v2 == edge->v[0]
+ && edgefaces[i][0]->contents == f->contents)
+ {
+ if (edgefaces[i][1])
+ // printf ("WARNING: multiple backward edge\n");
+ continue;
+ edgefaces[i][1] = f;
+ return -i;
+ }
+ #if 0
+ if (v1 == edge->v[0] && v2 == edge->v[1])
+ {
+ printf ("WARNING: multiple forward edge\n");
+ return i;
+ }
+ #endif
+ }
+ }
+
+// emit an edge
+ if (numedges >= MAX_MAP_EDGES)
+ Error ("numedges == MAX_MAP_EDGES");
+ edge = &dedges[numedges];
+ numedges++;
+ edge->v[0] = v1;
+ edge->v[1] = v2;
+ edgefaces[numedges-1][0] = f;
+
+ return numedges-1;
+}
+
+/*
+===========================================================================
+
+FACE MERGING
+
+===========================================================================
+*/
+
+/*
+=============
+TryMerge
+
+If two polygons share a common edge and the edges that meet at the
+common points are both inside the other polygons, merge them
+
+Returns NULL if the faces couldn't be merged, or the new face.
+The originals will NOT be freed.
+=============
+*/
+face_t *TryMerge (face_t *f1, face_t *f2, vec3_t planenormal)
+{
+ face_t *newf;
+ winding_t *nw;
+
+ if (!f1->w || !f2->w)
+ return NULL;
+ if (f1->texinfo != f2->texinfo)
+ return NULL;
+ if (f1->planenum != f2->planenum) // on front and back sides
+ return NULL;
+ if (f1->contents != f2->contents)
+ return NULL;
+
+
+ nw = TryMergeWinding (f1->w, f2->w, planenormal);
+ if (!nw)
+ return NULL;
+
+ c_merge++;
+ newf = NewFaceFromFace (f1);
+ newf->w = nw;
+
+ f1->merged = newf;
+ f2->merged = newf;
+
+ return newf;
+}
+
+/*
+===============
+MergeNodeFaces
+===============
+*/
+void MergeNodeFaces (node_t *node)
+{
+ face_t *f1, *f2, *end;
+ face_t *merged;
+ plane_t *plane;
+
+ plane = &mapplanes[node->planenum];
+ merged = NULL;
+
+ for (f1 = node->faces ; f1 ; f1 = f1->next)
+ {
+ if (f1->merged || f1->split[0] || f1->split[1])
+ continue;
+
+ for (f2 = node->faces ; f2 != f1 ; f2=f2->next)
+ {
+ if (f2->merged || f2->split[0] || f2->split[1])
+ continue;
+
+ //IDBUG: always passes the face's node's normal to TryMerge()
+ //regardless of which side the face is on. Approximately 50% of
+ //the time the face will be on the other side of node, and thus
+ //the result of the convex/concave test in TryMergeWinding(),
+ //which depends on the normal, is flipped. This causes faces
+ //that shouldn't be merged to be merged and faces that
+ //should be merged to not be merged.
+ //the following added line fixes this bug
+ //thanks to: Alexander Malmberg <alexander@malmberg.org>
+ plane = &mapplanes[f1->planenum];
+ //
+ merged = TryMerge (f1, f2, plane->normal);
+ if (!merged)
+ continue;
+
+ // add merged to the end of the node face list
+ // so it will be checked against all the faces again
+ for (end = node->faces ; end->next ; end = end->next)
+ ;
+ merged->next = NULL;
+ end->next = merged;
+ break;
+ }
+ }
+}
+
+//=====================================================================
+
+/*
+===============
+SubdivideFace
+
+Chop up faces that are larger than we want in the surface cache
+===============
+*/
+void SubdivideFace (node_t *node, face_t *f)
+{
+ float mins, maxs;
+ vec_t v;
+ int axis, i;
+ texinfo_t *tex;
+ vec3_t temp;
+ vec_t dist;
+ winding_t *w, *frontw, *backw;
+
+ if (f->merged)
+ return;
+
+// special (non-surface cached) faces don't need subdivision
+ tex = &texinfo[f->texinfo];
+
+ if ( tex->flags & (SURF_WARP|SURF_SKY) )
+ {
+ return;
+ }
+
+ for (axis = 0 ; axis < 2 ; axis++)
+ {
+ while (1)
+ {
+ mins = 999999;
+ maxs = -999999;
+
+ VectorCopy (tex->vecs[axis], temp);
+ w = f->w;
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ v = DotProduct (w->p[i], temp);
+ if (v < mins)
+ mins = v;
+ if (v > maxs)
+ maxs = v;
+ }
+#if 0
+ if (maxs - mins <= 0)
+ Error ("zero extents");
+#endif
+ if (axis == 2)
+ { // allow double high walls
+ if (maxs - mins <= subdivide_size/* *2 */)
+ break;
+ }
+ else if (maxs - mins <= subdivide_size)
+ break;
+
+ // split it
+ c_subdivide++;
+
+ v = VectorNormalize (temp);
+
+ dist = (mins + subdivide_size - 16)/v;
+
+ ClipWindingEpsilon (w, temp, dist, ON_EPSILON, &frontw, &backw);
+ if (!frontw || !backw)
+ Error ("SubdivideFace: didn't split the polygon");
+
+ f->split[0] = NewFaceFromFace (f);
+ f->split[0]->w = frontw;
+ f->split[0]->next = node->faces;
+ node->faces = f->split[0];
+
+ f->split[1] = NewFaceFromFace (f);
+ f->split[1]->w = backw;
+ f->split[1]->next = node->faces;
+ node->faces = f->split[1];
+
+ SubdivideFace (node, f->split[0]);
+ SubdivideFace (node, f->split[1]);
+ return;
+ }
+ }
+}
+
+void SubdivideNodeFaces (node_t *node)
+{
+ face_t *f;
+
+ for (f = node->faces ; f ; f=f->next)
+ {
+ SubdivideFace (node, f);
+ }
+}
+
+//===========================================================================
+
+int c_nodefaces;
+
+
+/*
+============
+FaceFromPortal
+
+============
+*/
+face_t *FaceFromPortal (portal_t *p, int pside)
+{
+ face_t *f;
+ side_t *side;
+
+ side = p->side;
+ if (!side)
+ return NULL; // portal does not bridge different visible contents
+
+ f = AllocFace ();
+
+ f->texinfo = side->texinfo;
+ f->planenum = (side->planenum & ~1) | pside;
+ f->portal = p;
+
+ if ( (p->nodes[pside]->contents & CONTENTS_WINDOW)
+ && VisibleContents(p->nodes[!pside]->contents^p->nodes[pside]->contents) == CONTENTS_WINDOW )
+ return NULL; // don't show insides of windows
+
+ if (pside)
+ {
+ f->w = ReverseWinding(p->winding);
+ f->contents = p->nodes[1]->contents;
+ }
+ else
+ {
+ f->w = CopyWinding(p->winding);
+ f->contents = p->nodes[0]->contents;
+ }
+ return f;
+}
+
+
+/*
+===============
+MakeFaces_r
+
+If a portal will make a visible face,
+mark the side that originally created it
+
+ solid / empty : solid
+ solid / water : solid
+ water / empty : water
+ water / water : none
+===============
+*/
+void MakeFaces_r (node_t *node)
+{
+ portal_t *p;
+ int s;
+
+ // recurse down to leafs
+ if (node->planenum != PLANENUM_LEAF)
+ {
+ MakeFaces_r (node->children[0]);
+ MakeFaces_r (node->children[1]);
+
+ // merge together all visible faces on the node
+ if (!nomerge)
+ MergeNodeFaces (node);
+ if (!nosubdiv)
+ SubdivideNodeFaces (node);
+
+ return;
+ }
+
+ // solid leafs never have visible faces
+ if (node->contents & CONTENTS_SOLID)
+ return;
+
+ // see which portals are valid
+ for (p=node->portals ; p ; p = p->next[s])
+ {
+ s = (p->nodes[1] == node);
+
+ p->face[s] = FaceFromPortal (p, s);
+ if (p->face[s])
+ {
+ c_nodefaces++;
+ p->face[s]->next = p->onnode->faces;
+ p->onnode->faces = p->face[s];
+ }
+ }
+}
+
+/*
+============
+MakeFaces
+============
+*/
+void MakeFaces (node_t *node)
+{
+ qprintf ("--- MakeFaces ---\n");
+ c_merge = 0;
+ c_subdivide = 0;
+ c_nodefaces = 0;
+
+ MakeFaces_r (node);
+
+ qprintf ("%5i makefaces\n", c_nodefaces);
+ qprintf ("%5i merged\n", c_merge);
+ qprintf ("%5i subdivided\n", c_subdivide);
+}
diff --git a/code/bspc/gldraw.c b/code/bspc/gldraw.c
new file mode 100755
index 0000000..9f7d6f7
--- /dev/null
+++ b/code/bspc/gldraw.c
@@ -0,0 +1,232 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include <windows.h>
+#include <GL/gl.h>
+#include <GL/glu.h>
+#include <GL/glaux.h>
+
+#include "qbsp.h"
+
+// can't use the glvertex3fv functions, because the vec3_t fields
+// could be either floats or doubles, depending on DOUBLEVEC_T
+
+qboolean drawflag;
+vec3_t draw_mins, draw_maxs;
+
+
+#define WIN_SIZE 512
+
+void InitWindow (void)
+{
+ auxInitDisplayMode (AUX_SINGLE | AUX_RGB);
+ auxInitPosition (0, 0, WIN_SIZE, WIN_SIZE);
+ auxInitWindow ("qcsg");
+}
+
+void Draw_ClearWindow (void)
+{
+ static int init;
+ int w, h, g;
+ vec_t mx, my;
+
+ if (!drawflag)
+ return;
+
+ if (!init)
+ {
+ init = true;
+ InitWindow ();
+ }
+
+ glClearColor (1,0.8,0.8,0);
+ glClear (GL_COLOR_BUFFER_BIT);
+
+ w = (draw_maxs[0] - draw_mins[0]);
+ h = (draw_maxs[1] - draw_mins[1]);
+
+ mx = draw_mins[0] + w/2;
+ my = draw_mins[1] + h/2;
+
+ g = w > h ? w : h;
+
+ glLoadIdentity ();
+ gluPerspective (90, 1, 2, 16384);
+ gluLookAt (mx, my, draw_maxs[2] + g/2, mx , my, draw_maxs[2], 0, 1, 0);
+
+ glColor3f (0,0,0);
+// glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
+ glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
+ glDisable (GL_DEPTH_TEST);
+ glEnable (GL_BLEND);
+ glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+
+#if 0
+ glColor4f (1,0,0,0.5);
+ glBegin (GL_POLYGON);
+
+ glVertex3f (0, 500, 0);
+ glVertex3f (0, 900, 0);
+ glVertex3f (0, 900, 100);
+ glVertex3f (0, 500, 100);
+
+ glEnd ();
+#endif
+
+ glFlush ();
+
+}
+
+void Draw_SetRed (void)
+{
+ if (!drawflag)
+ return;
+
+ glColor3f (1,0,0);
+}
+
+void Draw_SetGrey (void)
+{
+ if (!drawflag)
+ return;
+
+ glColor3f (0.5,0.5,0.5);
+}
+
+void Draw_SetBlack (void)
+{
+ if (!drawflag)
+ return;
+
+ glColor3f (0,0,0);
+}
+
+void DrawWinding (winding_t *w)
+{
+ int i;
+
+ if (!drawflag)
+ return;
+
+ glColor4f (0,0,0,0.5);
+ glBegin (GL_LINE_LOOP);
+ for (i=0 ; i<w->numpoints ; i++)
+ glVertex3f (w->p[i][0],w->p[i][1],w->p[i][2] );
+ glEnd ();
+
+ glColor4f (0,1,0,0.3);
+ glBegin (GL_POLYGON);
+ for (i=0 ; i<w->numpoints ; i++)
+ glVertex3f (w->p[i][0],w->p[i][1],w->p[i][2] );
+ glEnd ();
+
+ glFlush ();
+}
+
+void DrawAuxWinding (winding_t *w)
+{
+ int i;
+
+ if (!drawflag)
+ return;
+
+ glColor4f (0,0,0,0.5);
+ glBegin (GL_LINE_LOOP);
+ for (i=0 ; i<w->numpoints ; i++)
+ glVertex3f (w->p[i][0],w->p[i][1],w->p[i][2] );
+ glEnd ();
+
+ glColor4f (1,0,0,0.3);
+ glBegin (GL_POLYGON);
+ for (i=0 ; i<w->numpoints ; i++)
+ glVertex3f (w->p[i][0],w->p[i][1],w->p[i][2] );
+ glEnd ();
+
+ glFlush ();
+}
+
+//============================================================
+
+#define GLSERV_PORT 25001
+
+qboolean wins_init;
+int draw_socket;
+
+void GLS_BeginScene (void)
+{
+ WSADATA winsockdata;
+ WORD wVersionRequested;
+ struct sockaddr_in address;
+ int r;
+
+ if (!wins_init)
+ {
+ wins_init = true;
+
+ wVersionRequested = MAKEWORD(1, 1);
+
+ r = WSAStartup (MAKEWORD(1, 1), &winsockdata);
+
+ if (r)
+ Error ("Winsock initialization failed.");
+
+ }
+
+ // connect a socket to the server
+
+ draw_socket = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
+ if (draw_socket == -1)
+ Error ("draw_socket failed");
+
+ address.sin_family = AF_INET;
+ address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+ address.sin_port = GLSERV_PORT;
+ r = connect (draw_socket, (struct sockaddr *)&address, sizeof(address));
+ if (r == -1)
+ {
+ closesocket (draw_socket);
+ draw_socket = 0;
+ }
+}
+
+void GLS_Winding (winding_t *w, int code)
+{
+ byte buf[1024];
+ int i, j;
+
+ if (!draw_socket)
+ return;
+
+ ((int *)buf)[0] = w->numpoints;
+ ((int *)buf)[1] = code;
+ for (i=0 ; i<w->numpoints ; i++)
+ for (j=0 ; j<3 ; j++)
+ ((float *)buf)[2+i*3+j] = w->p[i][j];
+
+ send (draw_socket, buf, w->numpoints*12+8, 0);
+}
+
+void GLS_EndScene (void)
+{
+ closesocket (draw_socket);
+ draw_socket = 0;
+}
diff --git a/code/bspc/glfile.c b/code/bspc/glfile.c
new file mode 100755
index 0000000..179a836
--- /dev/null
+++ b/code/bspc/glfile.c
@@ -0,0 +1,149 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+
+int c_glfaces;
+
+int PortalVisibleSides (portal_t *p)
+{
+ int fcon, bcon;
+
+ if (!p->onnode)
+ return 0; // outside
+
+ fcon = p->nodes[0]->contents;
+ bcon = p->nodes[1]->contents;
+
+ // same contents never create a face
+ if (fcon == bcon)
+ return 0;
+
+ // FIXME: is this correct now?
+ if (!fcon)
+ return 1;
+ if (!bcon)
+ return 2;
+ return 0;
+}
+
+void OutputWinding (winding_t *w, FILE *glview)
+{
+ static int level = 128;
+ vec_t light;
+ int i;
+
+ fprintf (glview, "%i\n", w->numpoints);
+ level+=28;
+ light = (level&255)/255.0;
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ fprintf (glview, "%6.3f %6.3f %6.3f %6.3f %6.3f %6.3f\n",
+ w->p[i][0],
+ w->p[i][1],
+ w->p[i][2],
+ light,
+ light,
+ light);
+ }
+ fprintf (glview, "\n");
+}
+
+/*
+=============
+OutputPortal
+=============
+*/
+void OutputPortal (portal_t *p, FILE *glview)
+{
+ winding_t *w;
+ int sides;
+
+ sides = PortalVisibleSides (p);
+ if (!sides)
+ return;
+
+ c_glfaces++;
+
+ w = p->winding;
+
+ if (sides == 2) // back side
+ w = ReverseWinding (w);
+
+ OutputWinding (w, glview);
+
+ if (sides == 2)
+ FreeWinding(w);
+}
+
+/*
+=============
+WriteGLView_r
+=============
+*/
+void WriteGLView_r (node_t *node, FILE *glview)
+{
+ portal_t *p, *nextp;
+
+ if (node->planenum != PLANENUM_LEAF)
+ {
+ WriteGLView_r (node->children[0], glview);
+ WriteGLView_r (node->children[1], glview);
+ return;
+ }
+
+ // write all the portals
+ for (p=node->portals ; p ; p=nextp)
+ {
+ if (p->nodes[0] == node)
+ {
+ OutputPortal (p, glview);
+ nextp = p->next[0];
+ }
+ else
+ nextp = p->next[1];
+ }
+}
+
+/*
+=============
+WriteGLView
+=============
+*/
+void WriteGLView (tree_t *tree, char *source)
+{
+ char name[1024];
+ FILE *glview;
+
+ c_glfaces = 0;
+ sprintf (name, "%s%s.gl",outbase, source);
+ printf ("Writing %s\n", name);
+
+ glview = fopen (name, "w");
+ if (!glview)
+ Error ("Couldn't open %s", name);
+ WriteGLView_r (tree->headnode, glview);
+ fclose (glview);
+
+ printf ("%5i c_glfaces\n", c_glfaces);
+}
+
diff --git a/code/bspc/l_bsp_ent.c b/code/bspc/l_bsp_ent.c
new file mode 100755
index 0000000..8260179
--- /dev/null
+++ b/code/bspc/l_bsp_ent.c
@@ -0,0 +1,180 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "l_cmd.h"
+#include "l_math.h"
+#include "l_mem.h"
+#include "l_log.h"
+#include "../botlib/l_script.h"
+#include "l_bsp_ent.h"
+
+#define MAX_KEY 32
+#define MAX_VALUE 1024
+
+int num_entities;
+entity_t entities[MAX_MAP_ENTITIES];
+
+void StripTrailing(char *e)
+{
+ char *s;
+
+ s = e + strlen(e)-1;
+ while (s >= e && *s <= 32)
+ {
+ *s = 0;
+ s--;
+ }
+}
+
+/*
+=================
+ParseEpair
+=================
+*/
+epair_t *ParseEpair(script_t *script)
+{
+ epair_t *e;
+ token_t token;
+
+ e = GetMemory(sizeof(epair_t));
+ memset (e, 0, sizeof(epair_t));
+
+ PS_ExpectAnyToken(script, &token);
+ StripDoubleQuotes(token.string);
+ if (strlen(token.string) >= MAX_KEY-1)
+ Error ("ParseEpair: token %s too long", token.string);
+ e->key = copystring(token.string);
+ PS_ExpectAnyToken(script, &token);
+ StripDoubleQuotes(token.string);
+ if (strlen(token.string) >= MAX_VALUE-1)
+ Error ("ParseEpair: token %s too long", token.string);
+ e->value = copystring(token.string);
+
+ // strip trailing spaces
+ StripTrailing(e->key);
+ StripTrailing(e->value);
+
+ return e;
+} //end of the function ParseEpair
+
+
+/*
+================
+ParseEntity
+================
+*/
+qboolean ParseEntity(script_t *script)
+{
+ epair_t *e;
+ entity_t *mapent;
+ token_t token;
+
+ if (!PS_ReadToken(script, &token))
+ return false;
+
+ if (strcmp(token.string, "{"))
+ Error ("ParseEntity: { not found");
+
+ if (num_entities == MAX_MAP_ENTITIES)
+ Error ("num_entities == MAX_MAP_ENTITIES");
+
+ mapent = &entities[num_entities];
+ num_entities++;
+
+ do
+ {
+ if (!PS_ReadToken(script, &token))
+ Error ("ParseEntity: EOF without closing brace");
+ if (!strcmp(token.string, "}") )
+ break;
+ PS_UnreadLastToken(script);
+ e = ParseEpair(script);
+ e->next = mapent->epairs;
+ mapent->epairs = e;
+ } while (1);
+
+ return true;
+} //end of the function ParseEntity
+
+void PrintEntity (entity_t *ent)
+{
+ epair_t *ep;
+
+ printf ("------- entity %p -------\n", ent);
+ for (ep=ent->epairs ; ep ; ep=ep->next)
+ {
+ printf ("%s = %s\n", ep->key, ep->value);
+ }
+
+}
+
+void SetKeyValue (entity_t *ent, char *key, char *value)
+{
+ epair_t *ep;
+
+ for (ep=ent->epairs ; ep ; ep=ep->next)
+ if (!strcmp (ep->key, key) )
+ {
+ FreeMemory(ep->value);
+ ep->value = copystring(value);
+ return;
+ }
+ ep = GetMemory(sizeof(*ep));
+ ep->next = ent->epairs;
+ ent->epairs = ep;
+ ep->key = copystring(key);
+ ep->value = copystring(value);
+}
+
+char *ValueForKey (entity_t *ent, char *key)
+{
+ epair_t *ep;
+
+ for (ep=ent->epairs ; ep ; ep=ep->next)
+ if (!strcmp (ep->key, key) )
+ return ep->value;
+ return "";
+}
+
+vec_t FloatForKey (entity_t *ent, char *key)
+{
+ char *k;
+
+ k = ValueForKey (ent, key);
+ return atof(k);
+}
+
+void GetVectorForKey (entity_t *ent, char *key, vec3_t vec)
+{
+ char *k;
+ double v1, v2, v3;
+
+ k = ValueForKey (ent, key);
+// scanf into doubles, then assign, so it is vec_t size independent
+ v1 = v2 = v3 = 0;
+ sscanf (k, "%lf %lf %lf", &v1, &v2, &v3);
+ vec[0] = v1;
+ vec[1] = v2;
+ vec[2] = v3;
+}
+
+
diff --git a/code/bspc/l_bsp_ent.h b/code/bspc/l_bsp_ent.h
new file mode 100755
index 0000000..05dd162
--- /dev/null
+++ b/code/bspc/l_bsp_ent.h
@@ -0,0 +1,58 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#ifndef MAX_MAP_ENTITIES
+#define MAX_MAP_ENTITIES 2048
+#endif
+
+typedef struct epair_s
+{
+ struct epair_s *next;
+ char *key;
+ char *value;
+} epair_t;
+
+typedef struct
+{
+ vec3_t origin;
+ int firstbrush;
+ int numbrushes;
+ epair_t *epairs;
+ // only valid for func_areaportals
+ int areaportalnum;
+ int portalareas[2];
+ int modelnum; //for bsp 2 map conversion
+ qboolean wasdetail; //for SIN
+} entity_t;
+
+extern int num_entities;
+extern entity_t entities[MAX_MAP_ENTITIES];
+
+void StripTrailing(char *e);
+void SetKeyValue(entity_t *ent, char *key, char *value);
+char *ValueForKey(entity_t *ent, char *key); // will return "" if not present
+vec_t FloatForKey(entity_t *ent, char *key);
+void GetVectorForKey(entity_t *ent, char *key, vec3_t vec);
+qboolean ParseEntity(script_t *script);
+epair_t *ParseEpair(script_t *script);
+void PrintEntity(entity_t *ent);
+
diff --git a/code/bspc/l_bsp_hl.c b/code/bspc/l_bsp_hl.c
new file mode 100755
index 0000000..5b922b5
--- /dev/null
+++ b/code/bspc/l_bsp_hl.c
@@ -0,0 +1,888 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "l_cmd.h"
+#include "l_math.h"
+#include "l_mem.h"
+#include "l_log.h"
+#include "../botlib/l_script.h"
+#include "l_bsp_hl.h"
+#include "l_bsp_ent.h"
+
+//=============================================================================
+
+int hl_nummodels;
+hl_dmodel_t *hl_dmodels;//[HL_MAX_MAP_MODELS];
+int hl_dmodels_checksum;
+
+int hl_visdatasize;
+byte *hl_dvisdata;//[HL_MAX_MAP_VISIBILITY];
+int hl_dvisdata_checksum;
+
+int hl_lightdatasize;
+byte *hl_dlightdata;//[HL_MAX_MAP_LIGHTING];
+int hl_dlightdata_checksum;
+
+int hl_texdatasize;
+byte *hl_dtexdata;//[HL_MAX_MAP_MIPTEX]; // (dmiptexlump_t)
+int hl_dtexdata_checksum;
+
+int hl_entdatasize;
+char *hl_dentdata;//[HL_MAX_MAP_ENTSTRING];
+int hl_dentdata_checksum;
+
+int hl_numleafs;
+hl_dleaf_t *hl_dleafs;//[HL_MAX_MAP_LEAFS];
+int hl_dleafs_checksum;
+
+int hl_numplanes;
+hl_dplane_t *hl_dplanes;//[HL_MAX_MAP_PLANES];
+int hl_dplanes_checksum;
+
+int hl_numvertexes;
+hl_dvertex_t *hl_dvertexes;//[HL_MAX_MAP_VERTS];
+int hl_dvertexes_checksum;
+
+int hl_numnodes;
+hl_dnode_t *hl_dnodes;//[HL_MAX_MAP_NODES];
+int hl_dnodes_checksum;
+
+int hl_numtexinfo;
+hl_texinfo_t *hl_texinfo;//[HL_MAX_MAP_TEXINFO];
+int hl_texinfo_checksum;
+
+int hl_numfaces;
+hl_dface_t *hl_dfaces;//[HL_MAX_MAP_FACES];
+int hl_dfaces_checksum;
+
+int hl_numclipnodes;
+hl_dclipnode_t *hl_dclipnodes;//[HL_MAX_MAP_CLIPNODES];
+int hl_dclipnodes_checksum;
+
+int hl_numedges;
+hl_dedge_t *hl_dedges;//[HL_MAX_MAP_EDGES];
+int hl_dedges_checksum;
+
+int hl_nummarksurfaces;
+unsigned short *hl_dmarksurfaces;//[HL_MAX_MAP_MARKSURFACES];
+int hl_dmarksurfaces_checksum;
+
+int hl_numsurfedges;
+int *hl_dsurfedges;//[HL_MAX_MAP_SURFEDGES];
+int hl_dsurfedges_checksum;
+
+//int num_entities;
+//entity_t entities[HL_MAX_MAP_ENTITIES];
+
+
+//#ifdef //ME
+
+int hl_bspallocated = false;
+int hl_allocatedbspmem = 0;
+
+void HL_AllocMaxBSP(void)
+{
+ //models
+ hl_nummodels = 0;
+ hl_dmodels = (hl_dmodel_t *) GetMemory(HL_MAX_MAP_MODELS * sizeof(hl_dmodel_t));
+ hl_allocatedbspmem = HL_MAX_MAP_MODELS * sizeof(hl_dmodel_t);
+ //visibility
+ hl_visdatasize = 0;
+ hl_dvisdata = (byte *) GetMemory(HL_MAX_MAP_VISIBILITY * sizeof(byte));
+ hl_allocatedbspmem += HL_MAX_MAP_VISIBILITY * sizeof(byte);
+ //light data
+ hl_lightdatasize = 0;
+ hl_dlightdata = (byte *) GetMemory(HL_MAX_MAP_LIGHTING * sizeof(byte));
+ hl_allocatedbspmem += HL_MAX_MAP_LIGHTING * sizeof(byte);
+ //texture data
+ hl_texdatasize = 0;
+ hl_dtexdata = (byte *) GetMemory(HL_MAX_MAP_MIPTEX * sizeof(byte)); // (dmiptexlump_t)
+ hl_allocatedbspmem += HL_MAX_MAP_MIPTEX * sizeof(byte);
+ //entities
+ hl_entdatasize = 0;
+ hl_dentdata = (char *) GetMemory(HL_MAX_MAP_ENTSTRING * sizeof(char));
+ hl_allocatedbspmem += HL_MAX_MAP_ENTSTRING * sizeof(char);
+ //leaves
+ hl_numleafs = 0;
+ hl_dleafs = (hl_dleaf_t *) GetMemory(HL_MAX_MAP_LEAFS * sizeof(hl_dleaf_t));
+ hl_allocatedbspmem += HL_MAX_MAP_LEAFS * sizeof(hl_dleaf_t);
+ //planes
+ hl_numplanes = 0;
+ hl_dplanes = (hl_dplane_t *) GetMemory(HL_MAX_MAP_PLANES * sizeof(hl_dplane_t));
+ hl_allocatedbspmem += HL_MAX_MAP_PLANES * sizeof(hl_dplane_t);
+ //vertexes
+ hl_numvertexes = 0;
+ hl_dvertexes = (hl_dvertex_t *) GetMemory(HL_MAX_MAP_VERTS * sizeof(hl_dvertex_t));
+ hl_allocatedbspmem += HL_MAX_MAP_VERTS * sizeof(hl_dvertex_t);
+ //nodes
+ hl_numnodes = 0;
+ hl_dnodes = (hl_dnode_t *) GetMemory(HL_MAX_MAP_NODES * sizeof(hl_dnode_t));
+ hl_allocatedbspmem += HL_MAX_MAP_NODES * sizeof(hl_dnode_t);
+ //texture info
+ hl_numtexinfo = 0;
+ hl_texinfo = (hl_texinfo_t *) GetMemory(HL_MAX_MAP_TEXINFO * sizeof(hl_texinfo_t));
+ hl_allocatedbspmem += HL_MAX_MAP_TEXINFO * sizeof(hl_texinfo_t);
+ //faces
+ hl_numfaces = 0;
+ hl_dfaces = (hl_dface_t *) GetMemory(HL_MAX_MAP_FACES * sizeof(hl_dface_t));
+ hl_allocatedbspmem += HL_MAX_MAP_FACES * sizeof(hl_dface_t);
+ //clip nodes
+ hl_numclipnodes = 0;
+ hl_dclipnodes = (hl_dclipnode_t *) GetMemory(HL_MAX_MAP_CLIPNODES * sizeof(hl_dclipnode_t));
+ hl_allocatedbspmem += HL_MAX_MAP_CLIPNODES * sizeof(hl_dclipnode_t);
+ //edges
+ hl_numedges = 0;
+ hl_dedges = (hl_dedge_t *) GetMemory(HL_MAX_MAP_EDGES * sizeof(hl_dedge_t));
+ hl_allocatedbspmem += HL_MAX_MAP_EDGES, sizeof(hl_dedge_t);
+ //mark surfaces
+ hl_nummarksurfaces = 0;
+ hl_dmarksurfaces = (unsigned short *) GetMemory(HL_MAX_MAP_MARKSURFACES * sizeof(unsigned short));
+ hl_allocatedbspmem += HL_MAX_MAP_MARKSURFACES * sizeof(unsigned short);
+ //surface edges
+ hl_numsurfedges = 0;
+ hl_dsurfedges = (int *) GetMemory(HL_MAX_MAP_SURFEDGES * sizeof(int));
+ hl_allocatedbspmem += HL_MAX_MAP_SURFEDGES * sizeof(int);
+ //print allocated memory
+ Log_Print("allocated ");
+ PrintMemorySize(hl_allocatedbspmem);
+ Log_Print(" of BSP memory\n");
+} //end of the function HL_AllocMaxBSP
+
+void HL_FreeMaxBSP(void)
+{
+ //models
+ hl_nummodels = 0;
+ FreeMemory(hl_dmodels);
+ hl_dmodels = NULL;
+ //visibility
+ hl_visdatasize = 0;
+ FreeMemory(hl_dvisdata);
+ hl_dvisdata = NULL;
+ //light data
+ hl_lightdatasize = 0;
+ FreeMemory(hl_dlightdata);
+ hl_dlightdata = NULL;
+ //texture data
+ hl_texdatasize = 0;
+ FreeMemory(hl_dtexdata);
+ hl_dtexdata = NULL;
+ //entities
+ hl_entdatasize = 0;
+ FreeMemory(hl_dentdata);
+ hl_dentdata = NULL;
+ //leaves
+ hl_numleafs = 0;
+ FreeMemory(hl_dleafs);
+ hl_dleafs = NULL;
+ //planes
+ hl_numplanes = 0;
+ FreeMemory(hl_dplanes);
+ hl_dplanes = NULL;
+ //vertexes
+ hl_numvertexes = 0;
+ FreeMemory(hl_dvertexes);
+ hl_dvertexes = NULL;
+ //nodes
+ hl_numnodes = 0;
+ FreeMemory(hl_dnodes);
+ hl_dnodes = NULL;
+ //texture info
+ hl_numtexinfo = 0;
+ FreeMemory(hl_texinfo);
+ hl_texinfo = NULL;
+ //faces
+ hl_numfaces = 0;
+ FreeMemory(hl_dfaces);
+ hl_dfaces = NULL;
+ //clip nodes
+ hl_numclipnodes = 0;
+ FreeMemory(hl_dclipnodes);
+ hl_dclipnodes = NULL;
+ //edges
+ hl_numedges = 0;
+ FreeMemory(hl_dedges);
+ hl_dedges = NULL;
+ //mark surfaces
+ hl_nummarksurfaces = 0;
+ FreeMemory(hl_dmarksurfaces);
+ hl_dmarksurfaces = NULL;
+ //surface edges
+ hl_numsurfedges = 0;
+ FreeMemory(hl_dsurfedges);
+ hl_dsurfedges = NULL;
+ //
+ Log_Print("freed ");
+ PrintMemorySize(hl_allocatedbspmem);
+ Log_Print(" of BSP memory\n");
+ hl_allocatedbspmem = 0;
+} //end of the function HL_FreeMaxBSP
+//#endif //ME
+
+/*
+===============
+FastChecksum
+===============
+*/
+
+int FastChecksum(void *buffer, int bytes)
+{
+ int checksum = 0;
+
+ while( bytes-- )
+ checksum = (checksum << 4) ^ *((char *)buffer)++;
+
+ return checksum;
+}
+
+/*
+===============
+HL_CompressVis
+===============
+*/
+int HL_CompressVis(byte *vis, byte *dest)
+{
+ int j;
+ int rep;
+ int visrow;
+ byte *dest_p;
+
+ dest_p = dest;
+ visrow = (hl_numleafs + 7)>>3;
+
+ for (j=0 ; j<visrow ; j++)
+ {
+ *dest_p++ = vis[j];
+ if (vis[j])
+ continue;
+
+ rep = 1;
+ for ( j++; j<visrow ; j++)
+ if (vis[j] || rep == 255)
+ break;
+ else
+ rep++;
+ *dest_p++ = rep;
+ j--;
+ }
+
+ return dest_p - dest;
+}
+
+
+/*
+===================
+HL_DecompressVis
+===================
+*/
+void HL_DecompressVis (byte *in, byte *decompressed)
+{
+ int c;
+ byte *out;
+ int row;
+
+ row = (hl_numleafs+7)>>3;
+ out = decompressed;
+
+ do
+ {
+ if (*in)
+ {
+ *out++ = *in++;
+ continue;
+ }
+
+ c = in[1];
+ in += 2;
+ while (c)
+ {
+ *out++ = 0;
+ c--;
+ }
+ } while (out - decompressed < row);
+}
+
+//=============================================================================
+
+/*
+=============
+HL_SwapBSPFile
+
+Byte swaps all data in a bsp file.
+=============
+*/
+void HL_SwapBSPFile (qboolean todisk)
+{
+ int i, j, c;
+ hl_dmodel_t *d;
+ hl_dmiptexlump_t *mtl;
+
+
+// models
+ for (i = 0; i < hl_nummodels; i++)
+ {
+ d = &hl_dmodels[i];
+
+ for (j = 0; j < HL_MAX_MAP_HULLS; j++)
+ d->headnode[j] = LittleLong(d->headnode[j]);
+
+ d->visleafs = LittleLong(d->visleafs);
+ d->firstface = LittleLong(d->firstface);
+ d->numfaces = LittleLong(d->numfaces);
+
+ for (j = 0; j < 3; j++)
+ {
+ d->mins[j] = LittleFloat(d->mins[j]);
+ d->maxs[j] = LittleFloat(d->maxs[j]);
+ d->origin[j] = LittleFloat(d->origin[j]);
+ }
+ }
+
+//
+// vertexes
+//
+ for (i = 0; i < hl_numvertexes; i++)
+ {
+ for (j = 0; j < 3; j++)
+ hl_dvertexes[i].point[j] = LittleFloat (hl_dvertexes[i].point[j]);
+ }
+
+//
+// planes
+//
+ for (i=0 ; i<hl_numplanes ; i++)
+ {
+ for (j=0 ; j<3 ; j++)
+ hl_dplanes[i].normal[j] = LittleFloat (hl_dplanes[i].normal[j]);
+ hl_dplanes[i].dist = LittleFloat (hl_dplanes[i].dist);
+ hl_dplanes[i].type = LittleLong (hl_dplanes[i].type);
+ }
+
+//
+// texinfos
+//
+ for (i=0 ; i<hl_numtexinfo ; i++)
+ {
+ for (j=0 ; j<8 ; j++)
+ hl_texinfo[i].vecs[0][j] = LittleFloat (hl_texinfo[i].vecs[0][j]);
+ hl_texinfo[i].miptex = LittleLong (hl_texinfo[i].miptex);
+ hl_texinfo[i].flags = LittleLong (hl_texinfo[i].flags);
+ }
+
+//
+// faces
+//
+ for (i=0 ; i<hl_numfaces ; i++)
+ {
+ hl_dfaces[i].texinfo = LittleShort (hl_dfaces[i].texinfo);
+ hl_dfaces[i].planenum = LittleShort (hl_dfaces[i].planenum);
+ hl_dfaces[i].side = LittleShort (hl_dfaces[i].side);
+ hl_dfaces[i].lightofs = LittleLong (hl_dfaces[i].lightofs);
+ hl_dfaces[i].firstedge = LittleLong (hl_dfaces[i].firstedge);
+ hl_dfaces[i].numedges = LittleShort (hl_dfaces[i].numedges);
+ }
+
+//
+// nodes
+//
+ for (i=0 ; i<hl_numnodes ; i++)
+ {
+ hl_dnodes[i].planenum = LittleLong (hl_dnodes[i].planenum);
+ for (j=0 ; j<3 ; j++)
+ {
+ hl_dnodes[i].mins[j] = LittleShort (hl_dnodes[i].mins[j]);
+ hl_dnodes[i].maxs[j] = LittleShort (hl_dnodes[i].maxs[j]);
+ }
+ hl_dnodes[i].children[0] = LittleShort (hl_dnodes[i].children[0]);
+ hl_dnodes[i].children[1] = LittleShort (hl_dnodes[i].children[1]);
+ hl_dnodes[i].firstface = LittleShort (hl_dnodes[i].firstface);
+ hl_dnodes[i].numfaces = LittleShort (hl_dnodes[i].numfaces);
+ }
+
+//
+// leafs
+//
+ for (i=0 ; i<hl_numleafs ; i++)
+ {
+ hl_dleafs[i].contents = LittleLong (hl_dleafs[i].contents);
+ for (j=0 ; j<3 ; j++)
+ {
+ hl_dleafs[i].mins[j] = LittleShort (hl_dleafs[i].mins[j]);
+ hl_dleafs[i].maxs[j] = LittleShort (hl_dleafs[i].maxs[j]);
+ }
+
+ hl_dleafs[i].firstmarksurface = LittleShort (hl_dleafs[i].firstmarksurface);
+ hl_dleafs[i].nummarksurfaces = LittleShort (hl_dleafs[i].nummarksurfaces);
+ hl_dleafs[i].visofs = LittleLong (hl_dleafs[i].visofs);
+ }
+
+//
+// clipnodes
+//
+ for (i=0 ; i<hl_numclipnodes ; i++)
+ {
+ hl_dclipnodes[i].planenum = LittleLong (hl_dclipnodes[i].planenum);
+ hl_dclipnodes[i].children[0] = LittleShort (hl_dclipnodes[i].children[0]);
+ hl_dclipnodes[i].children[1] = LittleShort (hl_dclipnodes[i].children[1]);
+ }
+
+//
+// miptex
+//
+ if (hl_texdatasize)
+ {
+ mtl = (hl_dmiptexlump_t *)hl_dtexdata;
+ if (todisk)
+ c = mtl->nummiptex;
+ else
+ c = LittleLong(mtl->nummiptex);
+ mtl->nummiptex = LittleLong (mtl->nummiptex);
+ for (i=0 ; i<c ; i++)
+ mtl->dataofs[i] = LittleLong(mtl->dataofs[i]);
+ }
+
+//
+// marksurfaces
+//
+ for (i=0 ; i<hl_nummarksurfaces ; i++)
+ hl_dmarksurfaces[i] = LittleShort (hl_dmarksurfaces[i]);
+
+//
+// surfedges
+//
+ for (i=0 ; i<hl_numsurfedges ; i++)
+ hl_dsurfedges[i] = LittleLong (hl_dsurfedges[i]);
+
+//
+// edges
+//
+ for (i=0 ; i<hl_numedges ; i++)
+ {
+ hl_dedges[i].v[0] = LittleShort (hl_dedges[i].v[0]);
+ hl_dedges[i].v[1] = LittleShort (hl_dedges[i].v[1]);
+ }
+} //end of the function HL_SwapBSPFile
+
+
+hl_dheader_t *hl_header;
+int hl_fileLength;
+
+int HL_CopyLump (int lump, void *dest, int size, int maxsize)
+{
+ int length, ofs;
+
+ length = hl_header->lumps[lump].filelen;
+ ofs = hl_header->lumps[lump].fileofs;
+
+ if (length % size) {
+ Error ("LoadBSPFile: odd lump size");
+ }
+ // somehow things got out of range
+ if ((length/size) > maxsize) {
+ printf("WARNING: exceeded max size for lump %d size %d > maxsize %d\n", lump, (length/size), maxsize);
+ length = maxsize * size;
+ }
+ if ( ofs + length > hl_fileLength ) {
+ printf("WARNING: exceeded file length for lump %d\n", lump);
+ length = hl_fileLength - ofs;
+ if ( length <= 0 ) {
+ return 0;
+ }
+ }
+
+ memcpy (dest, (byte *)hl_header + ofs, length);
+
+ return length / size;
+}
+
+/*
+=============
+HL_LoadBSPFile
+=============
+*/
+void HL_LoadBSPFile (char *filename, int offset, int length)
+{
+ int i;
+
+//
+// load the file header
+//
+ hl_fileLength = LoadFile (filename, (void **)&hl_header, offset, length);
+
+// swap the header
+ for (i=0 ; i< sizeof(hl_dheader_t)/4 ; i++)
+ ((int *)hl_header)[i] = LittleLong ( ((int *)hl_header)[i]);
+
+ if (hl_header->version != HL_BSPVERSION)
+ Error ("%s is version %i, not %i", filename, hl_header->version, HL_BSPVERSION);
+
+ hl_nummodels = HL_CopyLump (HL_LUMP_MODELS, hl_dmodels, sizeof(hl_dmodel_t), HL_MAX_MAP_MODELS );
+ hl_numvertexes = HL_CopyLump (HL_LUMP_VERTEXES, hl_dvertexes, sizeof(hl_dvertex_t), HL_MAX_MAP_VERTS );
+ hl_numplanes = HL_CopyLump (HL_LUMP_PLANES, hl_dplanes, sizeof(hl_dplane_t), HL_MAX_MAP_PLANES );
+ hl_numleafs = HL_CopyLump (HL_LUMP_LEAFS, hl_dleafs, sizeof(hl_dleaf_t), HL_MAX_MAP_LEAFS );
+ hl_numnodes = HL_CopyLump (HL_LUMP_NODES, hl_dnodes, sizeof(hl_dnode_t), HL_MAX_MAP_NODES );
+ hl_numtexinfo = HL_CopyLump (HL_LUMP_TEXINFO, hl_texinfo, sizeof(hl_texinfo_t), HL_MAX_MAP_TEXINFO );
+ hl_numclipnodes = HL_CopyLump (HL_LUMP_CLIPNODES, hl_dclipnodes, sizeof(hl_dclipnode_t), HL_MAX_MAP_CLIPNODES );
+ hl_numfaces = HL_CopyLump (HL_LUMP_FACES, hl_dfaces, sizeof(hl_dface_t), HL_MAX_MAP_FACES );
+ hl_nummarksurfaces = HL_CopyLump (HL_LUMP_MARKSURFACES, hl_dmarksurfaces, sizeof(hl_dmarksurfaces[0]), HL_MAX_MAP_MARKSURFACES );
+ hl_numsurfedges = HL_CopyLump (HL_LUMP_SURFEDGES, hl_dsurfedges, sizeof(hl_dsurfedges[0]), HL_MAX_MAP_SURFEDGES );
+ hl_numedges = HL_CopyLump (HL_LUMP_EDGES, hl_dedges, sizeof(hl_dedge_t), HL_MAX_MAP_EDGES );
+
+ hl_texdatasize = HL_CopyLump (HL_LUMP_TEXTURES, hl_dtexdata, 1, HL_MAX_MAP_MIPTEX );
+ hl_visdatasize = HL_CopyLump (HL_LUMP_VISIBILITY, hl_dvisdata, 1, HL_MAX_MAP_VISIBILITY );
+ hl_lightdatasize = HL_CopyLump (HL_LUMP_LIGHTING, hl_dlightdata, 1, HL_MAX_MAP_LIGHTING );
+ hl_entdatasize = HL_CopyLump (HL_LUMP_ENTITIES, hl_dentdata, 1, HL_MAX_MAP_ENTSTRING );
+
+ FreeMemory(hl_header); // everything has been copied out
+
+//
+// swap everything
+//
+ HL_SwapBSPFile (false);
+
+ hl_dmodels_checksum = FastChecksum( hl_dmodels, hl_nummodels*sizeof(hl_dmodels[0]) );
+ hl_dvertexes_checksum = FastChecksum( hl_dvertexes, hl_numvertexes*sizeof(hl_dvertexes[0]) );
+ hl_dplanes_checksum = FastChecksum( hl_dplanes, hl_numplanes*sizeof(hl_dplanes[0]) );
+ hl_dleafs_checksum = FastChecksum( hl_dleafs, hl_numleafs*sizeof(hl_dleafs[0]) );
+ hl_dnodes_checksum = FastChecksum( hl_dnodes, hl_numnodes*sizeof(hl_dnodes[0]) );
+ hl_texinfo_checksum = FastChecksum( hl_texinfo, hl_numtexinfo*sizeof(hl_texinfo[0]) );
+ hl_dclipnodes_checksum = FastChecksum( hl_dclipnodes, hl_numclipnodes*sizeof(hl_dclipnodes[0]) );
+ hl_dfaces_checksum = FastChecksum( hl_dfaces, hl_numfaces*sizeof(hl_dfaces[0]) );
+ hl_dmarksurfaces_checksum = FastChecksum( hl_dmarksurfaces, hl_nummarksurfaces*sizeof(hl_dmarksurfaces[0]) );
+ hl_dsurfedges_checksum = FastChecksum( hl_dsurfedges, hl_numsurfedges*sizeof(hl_dsurfedges[0]) );
+ hl_dedges_checksum = FastChecksum( hl_dedges, hl_numedges*sizeof(hl_dedges[0]) );
+ hl_dtexdata_checksum = FastChecksum( hl_dtexdata, hl_numedges*sizeof(hl_dtexdata[0]) );
+ hl_dvisdata_checksum = FastChecksum( hl_dvisdata, hl_visdatasize*sizeof(hl_dvisdata[0]) );
+ hl_dlightdata_checksum = FastChecksum( hl_dlightdata, hl_lightdatasize*sizeof(hl_dlightdata[0]) );
+ hl_dentdata_checksum = FastChecksum( hl_dentdata, hl_entdatasize*sizeof(hl_dentdata[0]) );
+
+}
+
+//============================================================================
+
+FILE *wadfile;
+hl_dheader_t outheader;
+
+void HL_AddLump (int lumpnum, void *data, int len)
+{
+ hl_lump_t *lump;
+
+ lump = &hl_header->lumps[lumpnum];
+
+ lump->fileofs = LittleLong( ftell(wadfile) );
+ lump->filelen = LittleLong(len);
+ SafeWrite (wadfile, data, (len+3)&~3);
+}
+
+/*
+=============
+HL_WriteBSPFile
+
+Swaps the bsp file in place, so it should not be referenced again
+=============
+*/
+void HL_WriteBSPFile (char *filename)
+{
+ hl_header = &outheader;
+ memset (hl_header, 0, sizeof(hl_dheader_t));
+
+ HL_SwapBSPFile (true);
+
+ hl_header->version = LittleLong (HL_BSPVERSION);
+
+ wadfile = SafeOpenWrite (filename);
+ SafeWrite (wadfile, hl_header, sizeof(hl_dheader_t)); // overwritten later
+
+ HL_AddLump (HL_LUMP_PLANES, hl_dplanes, hl_numplanes*sizeof(hl_dplane_t));
+ HL_AddLump (HL_LUMP_LEAFS, hl_dleafs, hl_numleafs*sizeof(hl_dleaf_t));
+ HL_AddLump (HL_LUMP_VERTEXES, hl_dvertexes, hl_numvertexes*sizeof(hl_dvertex_t));
+ HL_AddLump (HL_LUMP_NODES, hl_dnodes, hl_numnodes*sizeof(hl_dnode_t));
+ HL_AddLump (HL_LUMP_TEXINFO, hl_texinfo, hl_numtexinfo*sizeof(hl_texinfo_t));
+ HL_AddLump (HL_LUMP_FACES, hl_dfaces, hl_numfaces*sizeof(hl_dface_t));
+ HL_AddLump (HL_LUMP_CLIPNODES, hl_dclipnodes, hl_numclipnodes*sizeof(hl_dclipnode_t));
+ HL_AddLump (HL_LUMP_MARKSURFACES, hl_dmarksurfaces, hl_nummarksurfaces*sizeof(hl_dmarksurfaces[0]));
+ HL_AddLump (HL_LUMP_SURFEDGES, hl_dsurfedges, hl_numsurfedges*sizeof(hl_dsurfedges[0]));
+ HL_AddLump (HL_LUMP_EDGES, hl_dedges, hl_numedges*sizeof(hl_dedge_t));
+ HL_AddLump (HL_LUMP_MODELS, hl_dmodels, hl_nummodels*sizeof(hl_dmodel_t));
+
+ HL_AddLump (HL_LUMP_LIGHTING, hl_dlightdata, hl_lightdatasize);
+ HL_AddLump (HL_LUMP_VISIBILITY, hl_dvisdata, hl_visdatasize);
+ HL_AddLump (HL_LUMP_ENTITIES, hl_dentdata, hl_entdatasize);
+ HL_AddLump (HL_LUMP_TEXTURES, hl_dtexdata, hl_texdatasize);
+
+ fseek (wadfile, 0, SEEK_SET);
+ SafeWrite (wadfile, hl_header, sizeof(hl_dheader_t));
+ fclose (wadfile);
+}
+
+//============================================================================
+
+#define ENTRIES(a) (sizeof(a)/sizeof(*(a)))
+#define ENTRYSIZE(a) (sizeof(*(a)))
+
+ArrayUsage( char *szItem, int items, int maxitems, int itemsize )
+{
+ float percentage = maxitems ? items * 100.0 / maxitems : 0.0;
+
+ qprintf("%-12s %7i/%-7i %7i/%-7i (%4.1f%%)",
+ szItem, items, maxitems, items * itemsize, maxitems * itemsize, percentage );
+ if ( percentage > 80.0 )
+ qprintf( "VERY FULL!\n" );
+ else if ( percentage > 95.0 )
+ qprintf( "SIZE DANGER!\n" );
+ else if ( percentage > 99.9 )
+ qprintf( "SIZE OVERFLOW!!!\n" );
+ else
+ qprintf( "\n" );
+ return items * itemsize;
+}
+
+GlobUsage( char *szItem, int itemstorage, int maxstorage )
+{
+ float percentage = maxstorage ? itemstorage * 100.0 / maxstorage : 0.0;
+
+ qprintf("%-12s [variable] %7i/%-7i (%4.1f%%)",
+ szItem, itemstorage, maxstorage, percentage );
+ if ( percentage > 80.0 )
+ qprintf( "VERY FULL!\n" );
+ else if ( percentage > 95.0 )
+ qprintf( "SIZE DANGER!\n" );
+ else if ( percentage > 99.9 )
+ qprintf( "SIZE OVERFLOW!!!\n" );
+ else
+ qprintf( "\n" );
+ return itemstorage;
+}
+
+/*
+=============
+HL_PrintBSPFileSizes
+
+Dumps info about current file
+=============
+*/
+void HL_PrintBSPFileSizes(void)
+{
+ int numtextures = hl_texdatasize ? ((hl_dmiptexlump_t*)hl_dtexdata)->nummiptex : 0;
+ int totalmemory = 0;
+
+ qprintf("\n");
+ qprintf("Object names Objects/Maxobjs Memory / Maxmem Fullness\n" );
+ qprintf("------------ --------------- --------------- --------\n" );
+
+ totalmemory += ArrayUsage( "models", hl_nummodels, ENTRIES(hl_dmodels), ENTRYSIZE(hl_dmodels) );
+ totalmemory += ArrayUsage( "planes", hl_numplanes, ENTRIES(hl_dplanes), ENTRYSIZE(hl_dplanes) );
+ totalmemory += ArrayUsage( "vertexes", hl_numvertexes, ENTRIES(hl_dvertexes), ENTRYSIZE(hl_dvertexes) );
+ totalmemory += ArrayUsage( "nodes", hl_numnodes, ENTRIES(hl_dnodes), ENTRYSIZE(hl_dnodes) );
+ totalmemory += ArrayUsage( "texinfos", hl_numtexinfo, ENTRIES(hl_texinfo), ENTRYSIZE(hl_texinfo) );
+ totalmemory += ArrayUsage( "faces", hl_numfaces, ENTRIES(hl_dfaces), ENTRYSIZE(hl_dfaces) );
+ totalmemory += ArrayUsage( "clipnodes", hl_numclipnodes, ENTRIES(hl_dclipnodes), ENTRYSIZE(hl_dclipnodes) );
+ totalmemory += ArrayUsage( "leaves", hl_numleafs, ENTRIES(hl_dleafs), ENTRYSIZE(hl_dleafs) );
+ totalmemory += ArrayUsage( "marksurfaces",hl_nummarksurfaces,ENTRIES(hl_dmarksurfaces),ENTRYSIZE(hl_dmarksurfaces) );
+ totalmemory += ArrayUsage( "surfedges", hl_numsurfedges, ENTRIES(hl_dsurfedges), ENTRYSIZE(hl_dsurfedges) );
+ totalmemory += ArrayUsage( "edges", hl_numedges, ENTRIES(hl_dedges), ENTRYSIZE(hl_dedges) );
+
+ totalmemory += GlobUsage( "texdata", hl_texdatasize, sizeof(hl_dtexdata) );
+ totalmemory += GlobUsage( "lightdata", hl_lightdatasize, sizeof(hl_dlightdata) );
+ totalmemory += GlobUsage( "visdata", hl_visdatasize, sizeof(hl_dvisdata) );
+ totalmemory += GlobUsage( "entdata", hl_entdatasize, sizeof(hl_dentdata) );
+
+ qprintf( "=== Total BSP file data space used: %d bytes ===\n\n", totalmemory );
+}
+
+
+
+/*
+=================
+ParseEpair
+=================
+* /
+epair_t *ParseEpair (void)
+{
+ epair_t *e;
+
+ e = malloc (sizeof(epair_t));
+ memset (e, 0, sizeof(epair_t));
+
+ if (strlen(token) >= MAX_KEY-1)
+ Error ("ParseEpar: token too long");
+ e->key = copystring(token);
+ GetToken (false);
+ if (strlen(token) >= MAX_VALUE-1)
+ Error ("ParseEpar: token too long");
+ e->value = copystring(token);
+
+ return e;
+} //*/
+
+
+/*
+================
+ParseEntity
+================
+* /
+qboolean ParseEntity (void)
+{
+ epair_t *e;
+ entity_t *mapent;
+
+ if (!GetToken (true))
+ return false;
+
+ if (strcmp (token, "{") )
+ Error ("ParseEntity: { not found");
+
+ if (num_entities == HL_MAX_MAP_ENTITIES)
+ Error ("num_entities == HL_MAX_MAP_ENTITIES");
+
+ mapent = &entities[num_entities];
+ num_entities++;
+
+ do
+ {
+ if (!GetToken (true))
+ Error ("ParseEntity: EOF without closing brace");
+ if (!strcmp (token, "}") )
+ break;
+ e = ParseEpair ();
+ e->next = mapent->epairs;
+ mapent->epairs = e;
+ } while (1);
+
+ return true;
+} //*/
+
+/*
+================
+ParseEntities
+
+Parses the dentdata string into entities
+================
+*/
+void HL_ParseEntities (void)
+{
+ script_t *script;
+
+ num_entities = 0;
+ script = LoadScriptMemory(hl_dentdata, hl_entdatasize, "*Half-Life bsp file");
+ SetScriptFlags(script, SCFL_NOSTRINGWHITESPACES |
+ SCFL_NOSTRINGESCAPECHARS);
+
+ while(ParseEntity(script))
+ {
+ } //end while
+
+ FreeScript(script);
+} //end of the function HL_ParseEntities
+
+
+/*
+================
+UnparseEntities
+
+Generates the dentdata string from all the entities
+================
+*/
+void HL_UnparseEntities (void)
+{
+ char *buf, *end;
+ epair_t *ep;
+ char line[2048];
+ int i;
+
+ buf = hl_dentdata;
+ end = buf;
+ *end = 0;
+
+ for (i=0 ; i<num_entities ; i++)
+ {
+ ep = entities[i].epairs;
+ if (!ep)
+ continue; // ent got removed
+
+ strcat (end,"{\n");
+ end += 2;
+
+ for (ep = entities[i].epairs ; ep ; ep=ep->next)
+ {
+ sprintf (line, "\"%s\" \"%s\"\n", ep->key, ep->value);
+ strcat (end, line);
+ end += strlen(line);
+ }
+ strcat (end,"}\n");
+ end += 2;
+
+ if (end > buf + HL_MAX_MAP_ENTSTRING)
+ Error ("Entity text too long");
+ }
+ hl_entdatasize = end - buf + 1;
+} //end of the function HL_UnparseEntities
+
+
+/*
+void SetKeyValue (entity_t *ent, char *key, char *value)
+{
+ epair_t *ep;
+
+ for (ep=ent->epairs ; ep ; ep=ep->next)
+ if (!strcmp (ep->key, key) )
+ {
+ free (ep->value);
+ ep->value = copystring(value);
+ return;
+ }
+ ep = malloc (sizeof(*ep));
+ ep->next = ent->epairs;
+ ent->epairs = ep;
+ ep->key = copystring(key);
+ ep->value = copystring(value);
+}
+
+char *ValueForKey (entity_t *ent, char *key)
+{
+ epair_t *ep;
+
+ for (ep=ent->epairs ; ep ; ep=ep->next)
+ if (!strcmp (ep->key, key) )
+ return ep->value;
+ return "";
+}
+
+vec_t FloatForKey (entity_t *ent, char *key)
+{
+ char *k;
+
+ k = ValueForKey (ent, key);
+ return atof(k);
+}
+
+void GetVectorForKey (entity_t *ent, char *key, vec3_t vec)
+{
+ char *k;
+ double v1, v2, v3;
+
+ k = ValueForKey (ent, key);
+// scanf into doubles, then assign, so it is vec_t size independent
+ v1 = v2 = v3 = 0;
+ sscanf (k, "%lf %lf %lf", &v1, &v2, &v3);
+ vec[0] = v1;
+ vec[1] = v2;
+ vec[2] = v3;
+} //*/
diff --git a/code/bspc/l_bsp_hl.h b/code/bspc/l_bsp_hl.h
new file mode 100755
index 0000000..0089b1e
--- /dev/null
+++ b/code/bspc/l_bsp_hl.h
@@ -0,0 +1,314 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// upper design bounds
+
+#define HL_MAX_MAP_HULLS 4
+
+#define HL_MAX_MAP_MODELS 400
+#define HL_MAX_MAP_BRUSHES 4096
+#define HL_MAX_MAP_ENTITIES 1024
+#define HL_MAX_MAP_ENTSTRING (128*1024)
+
+#define HL_MAX_MAP_PLANES 32767
+#define HL_MAX_MAP_NODES 32767 // because negative shorts are contents
+#define HL_MAX_MAP_CLIPNODES 32767 //
+#define HL_MAX_MAP_LEAFS 8192
+#define HL_MAX_MAP_VERTS 65535
+#define HL_MAX_MAP_FACES 65535
+#define HL_MAX_MAP_MARKSURFACES 65535
+#define HL_MAX_MAP_TEXINFO 8192
+#define HL_MAX_MAP_EDGES 256000
+#define HL_MAX_MAP_SURFEDGES 512000
+#define HL_MAX_MAP_TEXTURES 512
+#define HL_MAX_MAP_MIPTEX 0x200000
+#define HL_MAX_MAP_LIGHTING 0x200000
+#define HL_MAX_MAP_VISIBILITY 0x200000
+
+#define HL_MAX_MAP_PORTALS 65536
+
+// key / value pair sizes
+
+#define MAX_KEY 32
+#define MAX_VALUE 1024
+
+//=============================================================================
+
+
+#define HL_BSPVERSION 30
+#define HL_TOOLVERSION 2
+
+
+typedef struct
+{
+ int fileofs, filelen;
+} hl_lump_t;
+
+#define HL_LUMP_ENTITIES 0
+#define HL_LUMP_PLANES 1
+#define HL_LUMP_TEXTURES 2
+#define HL_LUMP_VERTEXES 3
+#define HL_LUMP_VISIBILITY 4
+#define HL_LUMP_NODES 5
+#define HL_LUMP_TEXINFO 6
+#define HL_LUMP_FACES 7
+#define HL_LUMP_LIGHTING 8
+#define HL_LUMP_CLIPNODES 9
+#define HL_LUMP_LEAFS 10
+#define HL_LUMP_MARKSURFACES 11
+#define HL_LUMP_EDGES 12
+#define HL_LUMP_SURFEDGES 13
+#define HL_LUMP_MODELS 14
+
+#define HL_HEADER_LUMPS 15
+
+typedef struct
+{
+ float mins[3], maxs[3];
+ float origin[3];
+ int headnode[HL_MAX_MAP_HULLS];
+ int visleafs; // not including the solid leaf 0
+ int firstface, numfaces;
+} hl_dmodel_t;
+
+typedef struct
+{
+ int version;
+ hl_lump_t lumps[HL_HEADER_LUMPS];
+} hl_dheader_t;
+
+typedef struct
+{
+ int nummiptex;
+ int dataofs[4]; // [nummiptex]
+} hl_dmiptexlump_t;
+
+#define MIPLEVELS 4
+typedef struct hl_miptex_s
+{
+ char name[16];
+ unsigned width, height;
+ unsigned offsets[MIPLEVELS]; // four mip maps stored
+} hl_miptex_t;
+
+
+typedef struct
+{
+ float point[3];
+} hl_dvertex_t;
+
+
+// 0-2 are axial planes
+#define PLANE_X 0
+#define PLANE_Y 1
+#define PLANE_Z 2
+
+// 3-5 are non-axial planes snapped to the nearest
+#define PLANE_ANYX 3
+#define PLANE_ANYY 4
+#define PLANE_ANYZ 5
+
+typedef struct
+{
+ float normal[3];
+ float dist;
+ int type; // PLANE_X - PLANE_ANYZ ?remove? trivial to regenerate
+} hl_dplane_t;
+
+
+
+#define HL_CONTENTS_EMPTY -1
+#define HL_CONTENTS_SOLID -2
+#define HL_CONTENTS_WATER -3
+#define HL_CONTENTS_SLIME -4
+#define HL_CONTENTS_LAVA -5
+#define HL_CONTENTS_SKY -6
+#define HL_CONTENTS_ORIGIN -7 // removed at csg time
+#define HL_CONTENTS_CLIP -8 // changed to contents_solid
+
+#define HL_CONTENTS_CURRENT_0 -9
+#define HL_CONTENTS_CURRENT_90 -10
+#define HL_CONTENTS_CURRENT_180 -11
+#define HL_CONTENTS_CURRENT_270 -12
+#define HL_CONTENTS_CURRENT_UP -13
+#define HL_CONTENTS_CURRENT_DOWN -14
+
+#define HL_CONTENTS_TRANSLUCENT -15
+
+// !!! if this is changed, it must be changed in asm_i386.h too !!!
+typedef struct
+{
+ int planenum;
+ short children[2]; // negative numbers are -(leafs+1), not nodes
+ short mins[3]; // for sphere culling
+ short maxs[3];
+ unsigned short firstface;
+ unsigned short numfaces; // counting both sides
+} hl_dnode_t;
+
+typedef struct
+{
+ int planenum;
+ short children[2]; // negative numbers are contents
+} hl_dclipnode_t;
+
+
+typedef struct hl_texinfo_s
+{
+ float vecs[2][4]; // [s/t][xyz offset]
+ int miptex;
+ int flags;
+} hl_texinfo_t;
+#define TEX_SPECIAL 1 // sky or slime, no lightmap or 256 subdivision
+
+// note that edge 0 is never used, because negative edge nums are used for
+// counterclockwise use of the edge in a face
+typedef struct
+{
+ unsigned short v[2]; // vertex numbers
+} hl_dedge_t;
+
+#define MAXLIGHTMAPS 4
+typedef struct
+{
+ short planenum;
+ short side;
+
+ int firstedge; // we must support > 64k edges
+ short numedges;
+ short texinfo;
+
+// lighting info
+ byte styles[MAXLIGHTMAPS];
+ int lightofs; // start of [numstyles*surfsize] samples
+} hl_dface_t;
+
+
+#define AMBIENT_WATER 0
+#define AMBIENT_SKY 1
+#define AMBIENT_SLIME 2
+#define AMBIENT_LAVA 3
+
+#define NUM_AMBIENTS 4 // automatic ambient sounds
+
+// leaf 0 is the generic HL_CONTENTS_SOLID leaf, used for all solid areas
+// all other leafs need visibility info
+typedef struct
+{
+ int contents;
+ int visofs; // -1 = no visibility info
+
+ short mins[3]; // for frustum culling
+ short maxs[3];
+
+ unsigned short firstmarksurface;
+ unsigned short nummarksurfaces;
+
+ byte ambient_level[NUM_AMBIENTS];
+} hl_dleaf_t;
+
+
+//============================================================================
+
+#ifndef QUAKE_GAME
+
+#define ANGLE_UP -1
+#define ANGLE_DOWN -2
+
+
+// the utilities get to be lazy and just use large static arrays
+
+extern int hl_nummodels;
+extern hl_dmodel_t *hl_dmodels;//[MAX_MAP_MODELS];
+extern int hl_dmodels_checksum;
+
+extern int hl_visdatasize;
+extern byte *hl_dvisdata;//[MAX_MAP_VISIBILITY];
+extern int hl_dvisdata_checksum;
+
+extern int hl_lightdatasize;
+extern byte *hl_dlightdata;//[MAX_MAP_LIGHTING];
+extern int hl_dlightdata_checksum;
+
+extern int hl_texdatasize;
+extern byte *hl_dtexdata;//[MAX_MAP_MIPTEX]; // (dmiptexlump_t)
+extern int hl_dtexdata_checksum;
+
+extern int hl_entdatasize;
+extern char *hl_dentdata;//[MAX_MAP_ENTSTRING];
+extern int hl_dentdata_checksum;
+
+extern int hl_numleafs;
+extern hl_dleaf_t *hl_dleafs;//[MAX_MAP_LEAFS];
+extern int hl_dleafs_checksum;
+
+extern int hl_numplanes;
+extern hl_dplane_t *hl_dplanes;//[MAX_MAP_PLANES];
+extern int hl_dplanes_checksum;
+
+extern int hl_numvertexes;
+extern hl_dvertex_t *hl_dvertexes;//[MAX_MAP_VERTS];
+extern int hl_dvertexes_checksum;
+
+extern int hl_numnodes;
+extern hl_dnode_t *hl_dnodes;//[MAX_MAP_NODES];
+extern int hl_dnodes_checksum;
+
+extern int hl_numtexinfo;
+extern hl_texinfo_t *hl_texinfo;//[MAX_MAP_TEXINFO];
+extern int hl_texinfo_checksum;
+
+extern int hl_numfaces;
+extern hl_dface_t *hl_dfaces;//[MAX_MAP_FACES];
+extern int hl_dfaces_checksum;
+
+extern int hl_numclipnodes;
+extern hl_dclipnode_t *hl_dclipnodes;//[MAX_MAP_CLIPNODES];
+extern int hl_dclipnodes_checksum;
+
+extern int hl_numedges;
+extern hl_dedge_t *hl_dedges;//[MAX_MAP_EDGES];
+extern int hl_dedges_checksum;
+
+extern int hl_nummarksurfaces;
+extern unsigned short *hl_dmarksurfaces;//[MAX_MAP_MARKSURFACES];
+extern int hl_dmarksurfaces_checksum;
+
+extern int hl_numsurfedges;
+extern int *hl_dsurfedges;//[MAX_MAP_SURFEDGES];
+extern int hl_dsurfedges_checksum;
+
+int FastChecksum(void *buffer, int bytes);
+
+void HL_AllocMaxBSP(void);
+void HL_FreeMaxBSP(void);
+
+void HL_DecompressVis(byte *in, byte *decompressed);
+int HL_CompressVis(byte *vis, byte *dest);
+
+void HL_LoadBSPFile(char *filename, int offset, int length);
+void HL_WriteBSPFile(char *filename);
+void HL_PrintBSPFileSizes(void);
+void HL_PrintBSPFileSizes(void);
+void HL_ParseEntities(void);
+void HL_UnparseEntities(void);
+
+#endif
diff --git a/code/bspc/l_bsp_q1.c b/code/bspc/l_bsp_q1.c
new file mode 100755
index 0000000..c68b5c8
--- /dev/null
+++ b/code/bspc/l_bsp_q1.c
@@ -0,0 +1,620 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "l_cmd.h"
+#include "l_math.h"
+#include "l_mem.h"
+#include "l_log.h"
+#include "../botlib/l_script.h"
+#include "l_bsp_q1.h"
+#include "l_bsp_ent.h"
+
+//=============================================================================
+
+int q1_nummodels;
+q1_dmodel_t *q1_dmodels;//[MAX_MAP_MODELS];
+
+int q1_visdatasize;
+byte *q1_dvisdata;//[MAX_MAP_VISIBILITY];
+
+int q1_lightdatasize;
+byte *q1_dlightdata;//[MAX_MAP_LIGHTING];
+
+int q1_texdatasize;
+byte *q1_dtexdata;//[MAX_MAP_MIPTEX]; // (dmiptexlump_t)
+
+int q1_entdatasize;
+char *q1_dentdata;//[MAX_MAP_ENTSTRING];
+
+int q1_numleafs;
+q1_dleaf_t *q1_dleafs;//[MAX_MAP_LEAFS];
+
+int q1_numplanes;
+q1_dplane_t *q1_dplanes;//[MAX_MAP_PLANES];
+
+int q1_numvertexes;
+q1_dvertex_t *q1_dvertexes;//[MAX_MAP_VERTS];
+
+int q1_numnodes;
+q1_dnode_t *q1_dnodes;//[MAX_MAP_NODES];
+
+int q1_numtexinfo;
+q1_texinfo_t *q1_texinfo;//[MAX_MAP_TEXINFO];
+
+int q1_numfaces;
+q1_dface_t *q1_dfaces;//[MAX_MAP_FACES];
+
+int q1_numclipnodes;
+q1_dclipnode_t *q1_dclipnodes;//[MAX_MAP_CLIPNODES];
+
+int q1_numedges;
+q1_dedge_t *q1_dedges;//[MAX_MAP_EDGES];
+
+int q1_nummarksurfaces;
+unsigned short *q1_dmarksurfaces;//[MAX_MAP_MARKSURFACES];
+
+int q1_numsurfedges;
+int *q1_dsurfedges;//[MAX_MAP_SURFEDGES];
+
+//=============================================================================
+
+int q1_bspallocated = false;
+int q1_allocatedbspmem = 0;
+
+void Q1_AllocMaxBSP(void)
+{
+ //models
+ q1_nummodels = 0;
+ q1_dmodels = (q1_dmodel_t *) GetMemory(Q1_MAX_MAP_MODELS * sizeof(q1_dmodel_t));
+ q1_allocatedbspmem = Q1_MAX_MAP_MODELS * sizeof(q1_dmodel_t);
+ //visibility
+ q1_visdatasize = 0;
+ q1_dvisdata = (byte *) GetMemory(Q1_MAX_MAP_VISIBILITY * sizeof(byte));
+ q1_allocatedbspmem += Q1_MAX_MAP_VISIBILITY * sizeof(byte);
+ //light data
+ q1_lightdatasize = 0;
+ q1_dlightdata = (byte *) GetMemory(Q1_MAX_MAP_LIGHTING * sizeof(byte));
+ q1_allocatedbspmem += Q1_MAX_MAP_LIGHTING * sizeof(byte);
+ //texture data
+ q1_texdatasize = 0;
+ q1_dtexdata = (byte *) GetMemory(Q1_MAX_MAP_MIPTEX * sizeof(byte)); // (dmiptexlump_t)
+ q1_allocatedbspmem += Q1_MAX_MAP_MIPTEX * sizeof(byte);
+ //entities
+ q1_entdatasize = 0;
+ q1_dentdata = (char *) GetMemory(Q1_MAX_MAP_ENTSTRING * sizeof(char));
+ q1_allocatedbspmem += Q1_MAX_MAP_ENTSTRING * sizeof(char);
+ //leaves
+ q1_numleafs = 0;
+ q1_dleafs = (q1_dleaf_t *) GetMemory(Q1_MAX_MAP_LEAFS * sizeof(q1_dleaf_t));
+ q1_allocatedbspmem += Q1_MAX_MAP_LEAFS * sizeof(q1_dleaf_t);
+ //planes
+ q1_numplanes = 0;
+ q1_dplanes = (q1_dplane_t *) GetMemory(Q1_MAX_MAP_PLANES * sizeof(q1_dplane_t));
+ q1_allocatedbspmem += Q1_MAX_MAP_PLANES * sizeof(q1_dplane_t);
+ //vertexes
+ q1_numvertexes = 0;
+ q1_dvertexes = (q1_dvertex_t *) GetMemory(Q1_MAX_MAP_VERTS * sizeof(q1_dvertex_t));
+ q1_allocatedbspmem += Q1_MAX_MAP_VERTS * sizeof(q1_dvertex_t);
+ //nodes
+ q1_numnodes = 0;
+ q1_dnodes = (q1_dnode_t *) GetMemory(Q1_MAX_MAP_NODES * sizeof(q1_dnode_t));
+ q1_allocatedbspmem += Q1_MAX_MAP_NODES * sizeof(q1_dnode_t);
+ //texture info
+ q1_numtexinfo = 0;
+ q1_texinfo = (q1_texinfo_t *) GetMemory(Q1_MAX_MAP_TEXINFO * sizeof(q1_texinfo_t));
+ q1_allocatedbspmem += Q1_MAX_MAP_TEXINFO * sizeof(q1_texinfo_t);
+ //faces
+ q1_numfaces = 0;
+ q1_dfaces = (q1_dface_t *) GetMemory(Q1_MAX_MAP_FACES * sizeof(q1_dface_t));
+ q1_allocatedbspmem += Q1_MAX_MAP_FACES * sizeof(q1_dface_t);
+ //clip nodes
+ q1_numclipnodes = 0;
+ q1_dclipnodes = (q1_dclipnode_t *) GetMemory(Q1_MAX_MAP_CLIPNODES * sizeof(q1_dclipnode_t));
+ q1_allocatedbspmem += Q1_MAX_MAP_CLIPNODES * sizeof(q1_dclipnode_t);
+ //edges
+ q1_numedges = 0;
+ q1_dedges = (q1_dedge_t *) GetMemory(Q1_MAX_MAP_EDGES * sizeof(q1_dedge_t));
+ q1_allocatedbspmem += Q1_MAX_MAP_EDGES, sizeof(q1_dedge_t);
+ //mark surfaces
+ q1_nummarksurfaces = 0;
+ q1_dmarksurfaces = (unsigned short *) GetMemory(Q1_MAX_MAP_MARKSURFACES * sizeof(unsigned short));
+ q1_allocatedbspmem += Q1_MAX_MAP_MARKSURFACES * sizeof(unsigned short);
+ //surface edges
+ q1_numsurfedges = 0;
+ q1_dsurfedges = (int *) GetMemory(Q1_MAX_MAP_SURFEDGES * sizeof(int));
+ q1_allocatedbspmem += Q1_MAX_MAP_SURFEDGES * sizeof(int);
+ //print allocated memory
+ Log_Print("allocated ");
+ PrintMemorySize(q1_allocatedbspmem);
+ Log_Print(" of BSP memory\n");
+} //end of the function Q1_AllocMaxBSP
+
+void Q1_FreeMaxBSP(void)
+{
+ //models
+ q1_nummodels = 0;
+ FreeMemory(q1_dmodels);
+ q1_dmodels = NULL;
+ //visibility
+ q1_visdatasize = 0;
+ FreeMemory(q1_dvisdata);
+ q1_dvisdata = NULL;
+ //light data
+ q1_lightdatasize = 0;
+ FreeMemory(q1_dlightdata);
+ q1_dlightdata = NULL;
+ //texture data
+ q1_texdatasize = 0;
+ FreeMemory(q1_dtexdata);
+ q1_dtexdata = NULL;
+ //entities
+ q1_entdatasize = 0;
+ FreeMemory(q1_dentdata);
+ q1_dentdata = NULL;
+ //leaves
+ q1_numleafs = 0;
+ FreeMemory(q1_dleafs);
+ q1_dleafs = NULL;
+ //planes
+ q1_numplanes = 0;
+ FreeMemory(q1_dplanes);
+ q1_dplanes = NULL;
+ //vertexes
+ q1_numvertexes = 0;
+ FreeMemory(q1_dvertexes);
+ q1_dvertexes = NULL;
+ //nodes
+ q1_numnodes = 0;
+ FreeMemory(q1_dnodes);
+ q1_dnodes = NULL;
+ //texture info
+ q1_numtexinfo = 0;
+ FreeMemory(q1_texinfo);
+ q1_texinfo = NULL;
+ //faces
+ q1_numfaces = 0;
+ FreeMemory(q1_dfaces);
+ q1_dfaces = NULL;
+ //clip nodes
+ q1_numclipnodes = 0;
+ FreeMemory(q1_dclipnodes);
+ q1_dclipnodes = NULL;
+ //edges
+ q1_numedges = 0;
+ FreeMemory(q1_dedges);
+ q1_dedges = NULL;
+ //mark surfaces
+ q1_nummarksurfaces = 0;
+ FreeMemory(q1_dmarksurfaces);
+ q1_dmarksurfaces = NULL;
+ //surface edges
+ q1_numsurfedges = 0;
+ FreeMemory(q1_dsurfedges);
+ q1_dsurfedges = NULL;
+ //
+ Log_Print("freed ");
+ PrintMemorySize(q1_allocatedbspmem);
+ Log_Print(" of BSP memory\n");
+ q1_allocatedbspmem = 0;
+} //end of the function Q1_FreeMaxBSP
+//#endif //ME
+
+/*
+=============
+Q1_SwapBSPFile
+
+Byte swaps all data in a bsp file.
+=============
+*/
+void Q1_SwapBSPFile (qboolean todisk)
+{
+ int i, j, c;
+ q1_dmodel_t *d;
+ q1_dmiptexlump_t *mtl;
+
+
+// models
+ for (i=0 ; i<q1_nummodels ; i++)
+ {
+ d = &q1_dmodels[i];
+
+ for (j=0 ; j<Q1_MAX_MAP_HULLS ; j++)
+ d->headnode[j] = LittleLong (d->headnode[j]);
+
+ d->visleafs = LittleLong (d->visleafs);
+ d->firstface = LittleLong (d->firstface);
+ d->numfaces = LittleLong (d->numfaces);
+
+ for (j=0 ; j<3 ; j++)
+ {
+ d->mins[j] = LittleFloat(d->mins[j]);
+ d->maxs[j] = LittleFloat(d->maxs[j]);
+ d->origin[j] = LittleFloat(d->origin[j]);
+ }
+ }
+
+//
+// vertexes
+//
+ for (i=0 ; i<q1_numvertexes ; i++)
+ {
+ for (j=0 ; j<3 ; j++)
+ q1_dvertexes[i].point[j] = LittleFloat(q1_dvertexes[i].point[j]);
+ }
+
+//
+// planes
+//
+ for (i=0 ; i<q1_numplanes ; i++)
+ {
+ for (j=0 ; j<3 ; j++)
+ q1_dplanes[i].normal[j] = LittleFloat(q1_dplanes[i].normal[j]);
+ q1_dplanes[i].dist = LittleFloat(q1_dplanes[i].dist);
+ q1_dplanes[i].type = LittleLong(q1_dplanes[i].type);
+ }
+
+//
+// texinfos
+//
+ for (i=0 ; i<q1_numtexinfo ; i++)
+ {
+ for (j=0 ; j<8 ; j++)
+ q1_texinfo[i].vecs[0][j] = LittleFloat(q1_texinfo[i].vecs[0][j]);
+ q1_texinfo[i].miptex = LittleLong(q1_texinfo[i].miptex);
+ q1_texinfo[i].flags = LittleLong(q1_texinfo[i].flags);
+ }
+
+//
+// faces
+//
+ for (i=0 ; i<q1_numfaces ; i++)
+ {
+ q1_dfaces[i].texinfo = LittleShort(q1_dfaces[i].texinfo);
+ q1_dfaces[i].planenum = LittleShort(q1_dfaces[i].planenum);
+ q1_dfaces[i].side = LittleShort(q1_dfaces[i].side);
+ q1_dfaces[i].lightofs = LittleLong(q1_dfaces[i].lightofs);
+ q1_dfaces[i].firstedge = LittleLong(q1_dfaces[i].firstedge);
+ q1_dfaces[i].numedges = LittleShort(q1_dfaces[i].numedges);
+ }
+
+//
+// nodes
+//
+ for (i=0 ; i<q1_numnodes ; i++)
+ {
+ q1_dnodes[i].planenum = LittleLong(q1_dnodes[i].planenum);
+ for (j=0 ; j<3 ; j++)
+ {
+ q1_dnodes[i].mins[j] = LittleShort(q1_dnodes[i].mins[j]);
+ q1_dnodes[i].maxs[j] = LittleShort(q1_dnodes[i].maxs[j]);
+ }
+ q1_dnodes[i].children[0] = LittleShort(q1_dnodes[i].children[0]);
+ q1_dnodes[i].children[1] = LittleShort(q1_dnodes[i].children[1]);
+ q1_dnodes[i].firstface = LittleShort(q1_dnodes[i].firstface);
+ q1_dnodes[i].numfaces = LittleShort(q1_dnodes[i].numfaces);
+ }
+
+//
+// leafs
+//
+ for (i=0 ; i<q1_numleafs ; i++)
+ {
+ q1_dleafs[i].contents = LittleLong(q1_dleafs[i].contents);
+ for (j=0 ; j<3 ; j++)
+ {
+ q1_dleafs[i].mins[j] = LittleShort(q1_dleafs[i].mins[j]);
+ q1_dleafs[i].maxs[j] = LittleShort(q1_dleafs[i].maxs[j]);
+ }
+
+ q1_dleafs[i].firstmarksurface = LittleShort(q1_dleafs[i].firstmarksurface);
+ q1_dleafs[i].nummarksurfaces = LittleShort(q1_dleafs[i].nummarksurfaces);
+ q1_dleafs[i].visofs = LittleLong(q1_dleafs[i].visofs);
+ }
+
+//
+// clipnodes
+//
+ for (i=0 ; i<q1_numclipnodes ; i++)
+ {
+ q1_dclipnodes[i].planenum = LittleLong(q1_dclipnodes[i].planenum);
+ q1_dclipnodes[i].children[0] = LittleShort(q1_dclipnodes[i].children[0]);
+ q1_dclipnodes[i].children[1] = LittleShort(q1_dclipnodes[i].children[1]);
+ }
+
+//
+// miptex
+//
+ if (q1_texdatasize)
+ {
+ mtl = (q1_dmiptexlump_t *)q1_dtexdata;
+ if (todisk)
+ c = mtl->nummiptex;
+ else
+ c = LittleLong(mtl->nummiptex);
+ mtl->nummiptex = LittleLong (mtl->nummiptex);
+ for (i=0 ; i<c ; i++)
+ mtl->dataofs[i] = LittleLong(mtl->dataofs[i]);
+ }
+
+//
+// marksurfaces
+//
+ for (i=0 ; i<q1_nummarksurfaces ; i++)
+ q1_dmarksurfaces[i] = LittleShort(q1_dmarksurfaces[i]);
+
+//
+// surfedges
+//
+ for (i=0 ; i<q1_numsurfedges ; i++)
+ q1_dsurfedges[i] = LittleLong(q1_dsurfedges[i]);
+
+//
+// edges
+//
+ for (i=0 ; i<q1_numedges ; i++)
+ {
+ q1_dedges[i].v[0] = LittleShort(q1_dedges[i].v[0]);
+ q1_dedges[i].v[1] = LittleShort(q1_dedges[i].v[1]);
+ }
+}
+
+
+q1_dheader_t *q1_header;
+int q1_fileLength;
+
+int Q1_CopyLump (int lump, void *dest, int size, int maxsize)
+{
+ int length, ofs;
+
+ length = q1_header->lumps[lump].filelen;
+ ofs = q1_header->lumps[lump].fileofs;
+
+ if (length % size) {
+ Error ("LoadBSPFile: odd lump size");
+ }
+ // somehow things got out of range
+ if ((length/size) > maxsize) {
+ printf("WARNING: exceeded max size for lump %d size %d > maxsize %d\n", lump, (length/size), maxsize);
+ length = maxsize * size;
+ }
+ if ( ofs + length > q1_fileLength ) {
+ printf("WARNING: exceeded file length for lump %d\n", lump);
+ length = q1_fileLength - ofs;
+ if ( length <= 0 ) {
+ return 0;
+ }
+ }
+
+ memcpy (dest, (byte *)q1_header + ofs, length);
+
+ return length / size;
+}
+
+/*
+=============
+Q1_LoadBSPFile
+=============
+*/
+void Q1_LoadBSPFile(char *filename, int offset, int length)
+{
+ int i;
+
+//
+// load the file header
+//
+ q1_fileLength = LoadFile(filename, (void **)&q1_header, offset, length);
+
+// swap the header
+ for (i=0 ; i< sizeof(q1_dheader_t)/4 ; i++)
+ ((int *)q1_header)[i] = LittleLong ( ((int *)q1_header)[i]);
+
+ if (q1_header->version != Q1_BSPVERSION)
+ Error ("%s is version %i, not %i", filename, i, Q1_BSPVERSION);
+
+ q1_nummodels = Q1_CopyLump (Q1_LUMP_MODELS, q1_dmodels, sizeof(q1_dmodel_t), Q1_MAX_MAP_MODELS );
+ q1_numvertexes = Q1_CopyLump (Q1_LUMP_VERTEXES, q1_dvertexes, sizeof(q1_dvertex_t), Q1_MAX_MAP_VERTS );
+ q1_numplanes = Q1_CopyLump (Q1_LUMP_PLANES, q1_dplanes, sizeof(q1_dplane_t), Q1_MAX_MAP_PLANES );
+ q1_numleafs = Q1_CopyLump (Q1_LUMP_LEAFS, q1_dleafs, sizeof(q1_dleaf_t), Q1_MAX_MAP_LEAFS );
+ q1_numnodes = Q1_CopyLump (Q1_LUMP_NODES, q1_dnodes, sizeof(q1_dnode_t), Q1_MAX_MAP_NODES );
+ q1_numtexinfo = Q1_CopyLump (Q1_LUMP_TEXINFO, q1_texinfo, sizeof(q1_texinfo_t), Q1_MAX_MAP_TEXINFO );
+ q1_numclipnodes = Q1_CopyLump (Q1_LUMP_CLIPNODES, q1_dclipnodes, sizeof(q1_dclipnode_t), Q1_MAX_MAP_CLIPNODES );
+ q1_numfaces = Q1_CopyLump (Q1_LUMP_FACES, q1_dfaces, sizeof(q1_dface_t), Q1_MAX_MAP_FACES );
+ q1_nummarksurfaces = Q1_CopyLump (Q1_LUMP_MARKSURFACES, q1_dmarksurfaces, sizeof(q1_dmarksurfaces[0]), Q1_MAX_MAP_MARKSURFACES );
+ q1_numsurfedges = Q1_CopyLump (Q1_LUMP_SURFEDGES, q1_dsurfedges, sizeof(q1_dsurfedges[0]), Q1_MAX_MAP_SURFEDGES );
+ q1_numedges = Q1_CopyLump (Q1_LUMP_EDGES, q1_dedges, sizeof(q1_dedge_t), Q1_MAX_MAP_EDGES );
+
+ q1_texdatasize = Q1_CopyLump (Q1_LUMP_TEXTURES, q1_dtexdata, 1, Q1_MAX_MAP_MIPTEX );
+ q1_visdatasize = Q1_CopyLump (Q1_LUMP_VISIBILITY, q1_dvisdata, 1, Q1_MAX_MAP_VISIBILITY );
+ q1_lightdatasize = Q1_CopyLump (Q1_LUMP_LIGHTING, q1_dlightdata, 1, Q1_MAX_MAP_LIGHTING );
+ q1_entdatasize = Q1_CopyLump (Q1_LUMP_ENTITIES, q1_dentdata, 1, Q1_MAX_MAP_ENTSTRING );
+
+ FreeMemory(q1_header); // everything has been copied out
+
+//
+// swap everything
+//
+ Q1_SwapBSPFile (false);
+}
+
+//============================================================================
+
+FILE *q1_wadfile;
+q1_dheader_t q1_outheader;
+
+void Q1_AddLump (int lumpnum, void *data, int len)
+{
+ q1_lump_t *lump;
+
+ lump = &q1_header->lumps[lumpnum];
+
+ lump->fileofs = LittleLong(ftell(q1_wadfile));
+ lump->filelen = LittleLong(len);
+ SafeWrite(q1_wadfile, data, (len+3)&~3);
+}
+
+/*
+=============
+Q1_WriteBSPFile
+
+Swaps the bsp file in place, so it should not be referenced again
+=============
+*/
+void Q1_WriteBSPFile (char *filename)
+{
+ q1_header = &q1_outheader;
+ memset (q1_header, 0, sizeof(q1_dheader_t));
+
+ Q1_SwapBSPFile (true);
+
+ q1_header->version = LittleLong (Q1_BSPVERSION);
+
+ q1_wadfile = SafeOpenWrite (filename);
+ SafeWrite (q1_wadfile, q1_header, sizeof(q1_dheader_t)); // overwritten later
+
+ Q1_AddLump (Q1_LUMP_PLANES, q1_dplanes, q1_numplanes*sizeof(q1_dplane_t));
+ Q1_AddLump (Q1_LUMP_LEAFS, q1_dleafs, q1_numleafs*sizeof(q1_dleaf_t));
+ Q1_AddLump (Q1_LUMP_VERTEXES, q1_dvertexes, q1_numvertexes*sizeof(q1_dvertex_t));
+ Q1_AddLump (Q1_LUMP_NODES, q1_dnodes, q1_numnodes*sizeof(q1_dnode_t));
+ Q1_AddLump (Q1_LUMP_TEXINFO, q1_texinfo, q1_numtexinfo*sizeof(q1_texinfo_t));
+ Q1_AddLump (Q1_LUMP_FACES, q1_dfaces, q1_numfaces*sizeof(q1_dface_t));
+ Q1_AddLump (Q1_LUMP_CLIPNODES, q1_dclipnodes, q1_numclipnodes*sizeof(q1_dclipnode_t));
+ Q1_AddLump (Q1_LUMP_MARKSURFACES, q1_dmarksurfaces, q1_nummarksurfaces*sizeof(q1_dmarksurfaces[0]));
+ Q1_AddLump (Q1_LUMP_SURFEDGES, q1_dsurfedges, q1_numsurfedges*sizeof(q1_dsurfedges[0]));
+ Q1_AddLump (Q1_LUMP_EDGES, q1_dedges, q1_numedges*sizeof(q1_dedge_t));
+ Q1_AddLump (Q1_LUMP_MODELS, q1_dmodels, q1_nummodels*sizeof(q1_dmodel_t));
+
+ Q1_AddLump (Q1_LUMP_LIGHTING, q1_dlightdata, q1_lightdatasize);
+ Q1_AddLump (Q1_LUMP_VISIBILITY, q1_dvisdata, q1_visdatasize);
+ Q1_AddLump (Q1_LUMP_ENTITIES, q1_dentdata, q1_entdatasize);
+ Q1_AddLump (Q1_LUMP_TEXTURES, q1_dtexdata, q1_texdatasize);
+
+ fseek (q1_wadfile, 0, SEEK_SET);
+ SafeWrite (q1_wadfile, q1_header, sizeof(q1_dheader_t));
+ fclose (q1_wadfile);
+}
+
+//============================================================================
+
+/*
+=============
+Q1_PrintBSPFileSizes
+
+Dumps info about current file
+=============
+*/
+void Q1_PrintBSPFileSizes (void)
+{
+ printf ("%5i planes %6i\n"
+ ,q1_numplanes, (int)(q1_numplanes*sizeof(q1_dplane_t)));
+ printf ("%5i vertexes %6i\n"
+ ,q1_numvertexes, (int)(q1_numvertexes*sizeof(q1_dvertex_t)));
+ printf ("%5i nodes %6i\n"
+ ,q1_numnodes, (int)(q1_numnodes*sizeof(q1_dnode_t)));
+ printf ("%5i texinfo %6i\n"
+ ,q1_numtexinfo, (int)(q1_numtexinfo*sizeof(q1_texinfo_t)));
+ printf ("%5i faces %6i\n"
+ ,q1_numfaces, (int)(q1_numfaces*sizeof(q1_dface_t)));
+ printf ("%5i clipnodes %6i\n"
+ ,q1_numclipnodes, (int)(q1_numclipnodes*sizeof(q1_dclipnode_t)));
+ printf ("%5i leafs %6i\n"
+ ,q1_numleafs, (int)(q1_numleafs*sizeof(q1_dleaf_t)));
+ printf ("%5i marksurfaces %6i\n"
+ ,q1_nummarksurfaces, (int)(q1_nummarksurfaces*sizeof(q1_dmarksurfaces[0])));
+ printf ("%5i surfedges %6i\n"
+ ,q1_numsurfedges, (int)(q1_numsurfedges*sizeof(q1_dmarksurfaces[0])));
+ printf ("%5i edges %6i\n"
+ ,q1_numedges, (int)(q1_numedges*sizeof(q1_dedge_t)));
+ if (!q1_texdatasize)
+ printf (" 0 textures 0\n");
+ else
+ printf ("%5i textures %6i\n",((q1_dmiptexlump_t*)q1_dtexdata)->nummiptex, q1_texdatasize);
+ printf (" lightdata %6i\n", q1_lightdatasize);
+ printf (" visdata %6i\n", q1_visdatasize);
+ printf (" entdata %6i\n", q1_entdatasize);
+} //end of the function Q1_PrintBSPFileSizes
+
+
+/*
+================
+Q1_ParseEntities
+
+Parses the dentdata string into entities
+================
+*/
+void Q1_ParseEntities (void)
+{
+ script_t *script;
+
+ num_entities = 0;
+ script = LoadScriptMemory(q1_dentdata, q1_entdatasize, "*Quake1 bsp file");
+ SetScriptFlags(script, SCFL_NOSTRINGWHITESPACES |
+ SCFL_NOSTRINGESCAPECHARS);
+
+ while(ParseEntity(script))
+ {
+ } //end while
+
+ FreeScript(script);
+} //end of the function Q1_ParseEntities
+
+
+/*
+================
+Q1_UnparseEntities
+
+Generates the dentdata string from all the entities
+================
+*/
+void Q1_UnparseEntities (void)
+{
+ char *buf, *end;
+ epair_t *ep;
+ char line[2048];
+ int i;
+
+ buf = q1_dentdata;
+ end = buf;
+ *end = 0;
+
+ for (i=0 ; i<num_entities ; i++)
+ {
+ ep = entities[i].epairs;
+ if (!ep)
+ continue; // ent got removed
+
+ strcat (end,"{\n");
+ end += 2;
+
+ for (ep = entities[i].epairs ; ep ; ep=ep->next)
+ {
+ sprintf (line, "\"%s\" \"%s\"\n", ep->key, ep->value);
+ strcat (end, line);
+ end += strlen(line);
+ }
+ strcat (end,"}\n");
+ end += 2;
+
+ if (end > buf + Q1_MAX_MAP_ENTSTRING)
+ Error ("Entity text too long");
+ }
+ q1_entdatasize = end - buf + 1;
+} //end of the function Q1_UnparseEntities
diff --git a/code/bspc/l_bsp_q1.h b/code/bspc/l_bsp_q1.h
new file mode 100755
index 0000000..1c2cd92
--- /dev/null
+++ b/code/bspc/l_bsp_q1.h
@@ -0,0 +1,275 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+
+// upper design bounds
+
+#define Q1_MAX_MAP_HULLS 4
+
+#define Q1_MAX_MAP_MODELS 256
+#define Q1_MAX_MAP_BRUSHES 4096
+#define Q1_MAX_MAP_ENTITIES 1024
+#define Q1_MAX_MAP_ENTSTRING 65536
+
+#define Q1_MAX_MAP_PLANES 8192
+#define Q1_MAX_MAP_NODES 32767 // because negative shorts are contents
+#define Q1_MAX_MAP_CLIPNODES 32767 //
+#define Q1_MAX_MAP_LEAFS 32767 //
+#define Q1_MAX_MAP_VERTS 65535
+#define Q1_MAX_MAP_FACES 65535
+#define Q1_MAX_MAP_MARKSURFACES 65535
+#define Q1_MAX_MAP_TEXINFO 4096
+#define Q1_MAX_MAP_EDGES 256000
+#define Q1_MAX_MAP_SURFEDGES 512000
+#define Q1_MAX_MAP_MIPTEX 0x200000
+#define Q1_MAX_MAP_LIGHTING 0x100000
+#define Q1_MAX_MAP_VISIBILITY 0x100000
+
+// key / value pair sizes
+
+#define MAX_KEY 32
+#define MAX_VALUE 1024
+
+//=============================================================================
+
+
+#define Q1_BSPVERSION 29
+
+typedef struct
+{
+ int fileofs, filelen;
+} q1_lump_t;
+
+#define Q1_LUMP_ENTITIES 0
+#define Q1_LUMP_PLANES 1
+#define Q1_LUMP_TEXTURES 2
+#define Q1_LUMP_VERTEXES 3
+#define Q1_LUMP_VISIBILITY 4
+#define Q1_LUMP_NODES 5
+#define Q1_LUMP_TEXINFO 6
+#define Q1_LUMP_FACES 7
+#define Q1_LUMP_LIGHTING 8
+#define Q1_LUMP_CLIPNODES 9
+#define Q1_LUMP_LEAFS 10
+#define Q1_LUMP_MARKSURFACES 11
+#define Q1_LUMP_EDGES 12
+#define Q1_LUMP_SURFEDGES 13
+#define Q1_LUMP_MODELS 14
+
+#define Q1_HEADER_LUMPS 15
+
+typedef struct
+{
+ float mins[3], maxs[3];
+ float origin[3];
+ int headnode[Q1_MAX_MAP_HULLS];
+ int visleafs; // not including the solid leaf 0
+ int firstface, numfaces;
+} q1_dmodel_t;
+
+typedef struct
+{
+ int version;
+ q1_lump_t lumps[Q1_HEADER_LUMPS];
+} q1_dheader_t;
+
+typedef struct
+{
+ int nummiptex;
+ int dataofs[4]; // [nummiptex]
+} q1_dmiptexlump_t;
+
+#define MIPLEVELS 4
+typedef struct q1_miptex_s
+{
+ char name[16];
+ unsigned width, height;
+ unsigned offsets[MIPLEVELS]; // four mip maps stored
+} q1_miptex_t;
+
+
+typedef struct
+{
+ float point[3];
+} q1_dvertex_t;
+
+
+// 0-2 are axial planes
+#define PLANE_X 0
+#define PLANE_Y 1
+#define PLANE_Z 2
+
+// 3-5 are non-axial planes snapped to the nearest
+#define PLANE_ANYX 3
+#define PLANE_ANYY 4
+#define PLANE_ANYZ 5
+
+typedef struct
+{
+ float normal[3];
+ float dist;
+ int type; // PLANE_X - PLANE_ANYZ ?remove? trivial to regenerate
+} q1_dplane_t;
+
+
+
+#define Q1_CONTENTS_EMPTY -1
+#define Q1_CONTENTS_SOLID -2
+#define Q1_CONTENTS_WATER -3
+#define Q1_CONTENTS_SLIME -4
+#define Q1_CONTENTS_LAVA -5
+#define Q1_CONTENTS_SKY -6
+
+// !!! if this is changed, it must be changed in asm_i386.h too !!!
+typedef struct
+{
+ int planenum;
+ short children[2]; // negative numbers are -(leafs+1), not nodes
+ short mins[3]; // for sphere culling
+ short maxs[3];
+ unsigned short firstface;
+ unsigned short numfaces; // counting both sides
+} q1_dnode_t;
+
+typedef struct
+{
+ int planenum;
+ short children[2]; // negative numbers are contents
+} q1_dclipnode_t;
+
+
+typedef struct q1_texinfo_s
+{
+ float vecs[2][4]; // [s/t][xyz offset]
+ int miptex;
+ int flags;
+} q1_texinfo_t;
+#define TEX_SPECIAL 1 // sky or slime, no lightmap or 256 subdivision
+
+// note that edge 0 is never used, because negative edge nums are used for
+// counterclockwise use of the edge in a face
+typedef struct
+{
+ unsigned short v[2]; // vertex numbers
+} q1_dedge_t;
+
+#define MAXLIGHTMAPS 4
+typedef struct
+{
+ short planenum;
+ short side;
+
+ int firstedge; // we must support > 64k edges
+ short numedges;
+ short texinfo;
+
+// lighting info
+ byte styles[MAXLIGHTMAPS];
+ int lightofs; // start of [numstyles*surfsize] samples
+} q1_dface_t;
+
+
+
+#define AMBIENT_WATER 0
+#define AMBIENT_SKY 1
+#define AMBIENT_SLIME 2
+#define AMBIENT_LAVA 3
+
+#define NUM_AMBIENTS 4 // automatic ambient sounds
+
+// leaf 0 is the generic Q1_CONTENTS_SOLID leaf, used for all solid areas
+// all other leafs need visibility info
+typedef struct
+{
+ int contents;
+ int visofs; // -1 = no visibility info
+
+ short mins[3]; // for frustum culling
+ short maxs[3];
+
+ unsigned short firstmarksurface;
+ unsigned short nummarksurfaces;
+
+ byte ambient_level[NUM_AMBIENTS];
+} q1_dleaf_t;
+
+//============================================================================
+
+#ifndef QUAKE_GAME
+
+// the utilities get to be lazy and just use large static arrays
+
+extern int q1_nummodels;
+extern q1_dmodel_t *q1_dmodels;//[MAX_MAP_MODELS];
+
+extern int q1_visdatasize;
+extern byte *q1_dvisdata;//[MAX_MAP_VISIBILITY];
+
+extern int q1_lightdatasize;
+extern byte *q1_dlightdata;//[MAX_MAP_LIGHTING];
+
+extern int q1_texdatasize;
+extern byte *q1_dtexdata;//[MAX_MAP_MIPTEX]; // (dmiptexlump_t)
+
+extern int q1_entdatasize;
+extern char *q1_dentdata;//[MAX_MAP_ENTSTRING];
+
+extern int q1_numleafs;
+extern q1_dleaf_t *q1_dleafs;//[MAX_MAP_LEAFS];
+
+extern int q1_numplanes;
+extern q1_dplane_t *q1_dplanes;//[MAX_MAP_PLANES];
+
+extern int q1_numvertexes;
+extern q1_dvertex_t *q1_dvertexes;//[MAX_MAP_VERTS];
+
+extern int q1_numnodes;
+extern q1_dnode_t *q1_dnodes;//[MAX_MAP_NODES];
+
+extern int q1_numtexinfo;
+extern q1_texinfo_t *q1_texinfo;//[MAX_MAP_TEXINFO];
+
+extern int q1_numfaces;
+extern q1_dface_t *q1_dfaces;//[MAX_MAP_FACES];
+
+extern int q1_numclipnodes;
+extern q1_dclipnode_t *q1_dclipnodes;//[MAX_MAP_CLIPNODES];
+
+extern int q1_numedges;
+extern q1_dedge_t *q1_dedges;//[MAX_MAP_EDGES];
+
+extern int q1_nummarksurfaces;
+extern unsigned short *q1_dmarksurfaces;//[MAX_MAP_MARKSURFACES];
+
+extern int q1_numsurfedges;
+extern int *q1_dsurfedges;//[MAX_MAP_SURFEDGES];
+
+
+void Q1_AllocMaxBSP(void);
+void Q1_FreeMaxBSP(void);
+void Q1_LoadBSPFile(char *filename, int offset, int length);
+void Q1_WriteBSPFile(char *filename);
+void Q1_PrintBSPFileSizes(void);
+void Q1_ParseEntities(void);
+void Q1_UnparseEntities(void);
+
+#endif
diff --git a/code/bspc/l_bsp_q2.c b/code/bspc/l_bsp_q2.c
new file mode 100755
index 0000000..d5e9844
--- /dev/null
+++ b/code/bspc/l_bsp_q2.c
@@ -0,0 +1,1134 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "l_cmd.h"
+#include "l_math.h"
+#include "l_mem.h"
+#include "l_log.h"
+#include "l_poly.h"
+#include "../botlib/l_script.h"
+#include "q2files.h"
+#include "l_bsp_q2.h"
+#include "l_bsp_ent.h"
+
+#define q2_dmodel_t dmodel_t
+#define q2_lump_t lump_t
+#define q2_dheader_t dheader_t
+#define q2_dmodel_t dmodel_t
+#define q2_dvertex_t dvertex_t
+#define q2_dplane_t dplane_t
+#define q2_dnode_t dnode_t
+#define q2_texinfo_t texinfo_t
+#define q2_dedge_t dedge_t
+#define q2_dface_t dface_t
+#define q2_dleaf_t dleaf_t
+#define q2_dbrushside_t dbrushside_t
+#define q2_dbrush_t dbrush_t
+#define q2_dvis_t dvis_t
+#define q2_dareaportal_t dareaportal_t
+#define q2_darea_t darea_t
+
+#define q2_nummodels nummodels
+#define q2_dmodels dmodels
+#define q2_numleafs numleafs
+#define q2_dleafs dleafs
+#define q2_numplanes numplanes
+#define q2_dplanes dplanes
+#define q2_numvertexes numvertexes
+#define q2_dvertexes dvertexes
+#define q2_numnodes numnodes
+#define q2_dnodes dnodes
+#define q2_numtexinfo numtexinfo
+#define q2_texinfo texinfo
+#define q2_numfaces numfaces
+#define q2_dfaces dfaces
+#define q2_numedges numedges
+#define q2_dedges dedges
+#define q2_numleaffaces numleaffaces
+#define q2_dleaffaces dleaffaces
+#define q2_numleafbrushes numleafbrushes
+#define q2_dleafbrushes dleafbrushes
+#define q2_dsurfedges dsurfedges
+#define q2_numbrushes numbrushes
+#define q2_dbrushes dbrushes
+#define q2_numbrushsides numbrushsides
+#define q2_dbrushsides dbrushsides
+#define q2_numareas numareas
+#define q2_dareas dareas
+#define q2_numareaportals numareaportals
+#define q2_dareaportals dareaportals
+
+void GetLeafNums (void);
+
+//=============================================================================
+
+int nummodels;
+dmodel_t *dmodels;//[MAX_MAP_MODELS];
+
+int visdatasize;
+byte *dvisdata;//[MAX_MAP_VISIBILITY];
+dvis_t *dvis;// = (dvis_t *)dvisdata;
+
+int lightdatasize;
+byte *dlightdata;//[MAX_MAP_LIGHTING];
+
+int entdatasize;
+char *dentdata;//[MAX_MAP_ENTSTRING];
+
+int numleafs;
+dleaf_t *dleafs;//[MAX_MAP_LEAFS];
+
+int numplanes;
+dplane_t *dplanes;//[MAX_MAP_PLANES];
+
+int numvertexes;
+dvertex_t *dvertexes;//[MAX_MAP_VERTS];
+
+int numnodes;
+dnode_t *dnodes;//[MAX_MAP_NODES];
+
+//NOTE: must be static for q2 .map to q2 .bsp
+int numtexinfo;
+texinfo_t texinfo[MAX_MAP_TEXINFO];
+
+int numfaces;
+dface_t *dfaces;//[MAX_MAP_FACES];
+
+int numedges;
+dedge_t *dedges;//[MAX_MAP_EDGES];
+
+int numleaffaces;
+unsigned short *dleaffaces;//[MAX_MAP_LEAFFACES];
+
+int numleafbrushes;
+unsigned short *dleafbrushes;//[MAX_MAP_LEAFBRUSHES];
+
+int numsurfedges;
+int *dsurfedges;//[MAX_MAP_SURFEDGES];
+
+int numbrushes;
+dbrush_t *dbrushes;//[MAX_MAP_BRUSHES];
+
+int numbrushsides;
+dbrushside_t *dbrushsides;//[MAX_MAP_BRUSHSIDES];
+
+int numareas;
+darea_t *dareas;//[MAX_MAP_AREAS];
+
+int numareaportals;
+dareaportal_t *dareaportals;//[MAX_MAP_AREAPORTALS];
+
+#define MAX_MAP_DPOP 256
+byte dpop[MAX_MAP_DPOP];
+
+//
+char brushsidetextured[MAX_MAP_BRUSHSIDES];
+
+//#ifdef ME
+
+int bspallocated = false;
+int allocatedbspmem = 0;
+
+void Q2_AllocMaxBSP(void)
+{
+ //models
+ nummodels = 0;
+ dmodels = (dmodel_t *) GetClearedMemory(MAX_MAP_MODELS * sizeof(dmodel_t));
+ allocatedbspmem += MAX_MAP_MODELS * sizeof(dmodel_t);
+ //vis data
+ visdatasize = 0;
+ dvisdata = (byte *) GetClearedMemory(MAX_MAP_VISIBILITY * sizeof(byte));
+ dvis = (dvis_t *) dvisdata;
+ allocatedbspmem += MAX_MAP_VISIBILITY * sizeof(byte);
+ //light data
+ lightdatasize = 0;
+ dlightdata = (byte *) GetClearedMemory(MAX_MAP_LIGHTING * sizeof(byte));
+ allocatedbspmem += MAX_MAP_LIGHTING * sizeof(byte);
+ //entity data
+ entdatasize = 0;
+ dentdata = (char *) GetClearedMemory(MAX_MAP_ENTSTRING * sizeof(char));
+ allocatedbspmem += MAX_MAP_ENTSTRING * sizeof(char);
+ //leafs
+ numleafs = 0;
+ dleafs = (dleaf_t *) GetClearedMemory(MAX_MAP_LEAFS * sizeof(dleaf_t));
+ allocatedbspmem += MAX_MAP_LEAFS * sizeof(dleaf_t);
+ //planes
+ numplanes = 0;
+ dplanes = (dplane_t *) GetClearedMemory(MAX_MAP_PLANES * sizeof(dplane_t));
+ allocatedbspmem += MAX_MAP_PLANES * sizeof(dplane_t);
+ //vertexes
+ numvertexes = 0;
+ dvertexes = (dvertex_t *) GetClearedMemory(MAX_MAP_VERTS * sizeof(dvertex_t));
+ allocatedbspmem += MAX_MAP_VERTS * sizeof(dvertex_t);
+ //nodes
+ numnodes = 0;
+ dnodes = (dnode_t *) GetClearedMemory(MAX_MAP_NODES * sizeof(dnode_t));
+ allocatedbspmem += MAX_MAP_NODES * sizeof(dnode_t);
+ /*
+ //texture info
+ numtexinfo = 0;
+ texinfo = (texinfo_t *) GetClearedMemory(MAX_MAP_TEXINFO * sizeof(texinfo_t));
+ allocatedbspmem += MAX_MAP_TEXINFO * sizeof(texinfo_t);
+ //*/
+ //faces
+ numfaces = 0;
+ dfaces = (dface_t *) GetClearedMemory(MAX_MAP_FACES * sizeof(dface_t));
+ allocatedbspmem += MAX_MAP_FACES * sizeof(dface_t);
+ //edges
+ numedges = 0;
+ dedges = (dedge_t *) GetClearedMemory(MAX_MAP_EDGES * sizeof(dedge_t));
+ allocatedbspmem += MAX_MAP_EDGES * sizeof(dedge_t);
+ //leaf faces
+ numleaffaces = 0;
+ dleaffaces = (unsigned short *) GetClearedMemory(MAX_MAP_LEAFFACES * sizeof(unsigned short));
+ allocatedbspmem += MAX_MAP_LEAFFACES * sizeof(unsigned short);
+ //leaf brushes
+ numleafbrushes = 0;
+ dleafbrushes = (unsigned short *) GetClearedMemory(MAX_MAP_LEAFBRUSHES * sizeof(unsigned short));
+ allocatedbspmem += MAX_MAP_LEAFBRUSHES * sizeof(unsigned short);
+ //surface edges
+ numsurfedges = 0;
+ dsurfedges = (int *) GetClearedMemory(MAX_MAP_SURFEDGES * sizeof(int));
+ allocatedbspmem += MAX_MAP_SURFEDGES * sizeof(int);
+ //brushes
+ numbrushes = 0;
+ dbrushes = (dbrush_t *) GetClearedMemory(MAX_MAP_BRUSHES * sizeof(dbrush_t));
+ allocatedbspmem += MAX_MAP_BRUSHES * sizeof(dbrush_t);
+ //brushsides
+ numbrushsides = 0;
+ dbrushsides = (dbrushside_t *) GetClearedMemory(MAX_MAP_BRUSHSIDES * sizeof(dbrushside_t));
+ allocatedbspmem += MAX_MAP_BRUSHSIDES * sizeof(dbrushside_t);
+ //areas
+ numareas = 0;
+ dareas = (darea_t *) GetClearedMemory(MAX_MAP_AREAS * sizeof(darea_t));
+ allocatedbspmem += MAX_MAP_AREAS * sizeof(darea_t);
+ //area portals
+ numareaportals = 0;
+ dareaportals = (dareaportal_t *) GetClearedMemory(MAX_MAP_AREAPORTALS * sizeof(dareaportal_t));
+ allocatedbspmem += MAX_MAP_AREAPORTALS * sizeof(dareaportal_t);
+ //print allocated memory
+ Log_Print("allocated ");
+ PrintMemorySize(allocatedbspmem);
+ Log_Print(" of BSP memory\n");
+} //end of the function Q2_AllocMaxBSP
+
+void Q2_FreeMaxBSP(void)
+{
+ //models
+ nummodels = 0;
+ FreeMemory(dmodels);
+ dmodels = NULL;
+ //vis data
+ visdatasize = 0;
+ FreeMemory(dvisdata);
+ dvisdata = NULL;
+ dvis = NULL;
+ //light data
+ lightdatasize = 0;
+ FreeMemory(dlightdata);
+ dlightdata = NULL;
+ //entity data
+ entdatasize = 0;
+ FreeMemory(dentdata);
+ dentdata = NULL;
+ //leafs
+ numleafs = 0;
+ FreeMemory(dleafs);
+ dleafs = NULL;
+ //planes
+ numplanes = 0;
+ FreeMemory(dplanes);
+ dplanes = NULL;
+ //vertexes
+ numvertexes = 0;
+ FreeMemory(dvertexes);
+ dvertexes = NULL;
+ //nodes
+ numnodes = 0;
+ FreeMemory(dnodes);
+ dnodes = NULL;
+ /*
+ //texture info
+ numtexinfo = 0;
+ FreeMemory(texinfo);
+ texinfo = NULL;
+ //*/
+ //faces
+ numfaces = 0;
+ FreeMemory(dfaces);
+ dfaces = NULL;
+ //edges
+ numedges = 0;
+ FreeMemory(dedges);
+ dedges = NULL;
+ //leaf faces
+ numleaffaces = 0;
+ FreeMemory(dleaffaces);
+ dleaffaces = NULL;
+ //leaf brushes
+ numleafbrushes = 0;
+ FreeMemory(dleafbrushes);
+ dleafbrushes = NULL;
+ //surface edges
+ numsurfedges = 0;
+ FreeMemory(dsurfedges);
+ dsurfedges = NULL;
+ //brushes
+ numbrushes = 0;
+ FreeMemory(dbrushes);
+ dbrushes = NULL;
+ //brushsides
+ numbrushsides = 0;
+ FreeMemory(dbrushsides);
+ dbrushsides = NULL;
+ //areas
+ numareas = 0;
+ FreeMemory(dareas);
+ dareas = NULL;
+ //area portals
+ numareaportals = 0;
+ FreeMemory(dareaportals);
+ dareaportals = NULL;
+ //
+ Log_Print("freed ");
+ PrintMemorySize(allocatedbspmem);
+ Log_Print(" of BSP memory\n");
+ allocatedbspmem = 0;
+} //end of the function Q2_FreeMaxBSP
+
+#define WCONVEX_EPSILON 0.5
+
+int InsideWinding(winding_t *w, vec3_t point, int planenum)
+{
+ int i;
+ float dist;
+ vec_t *v1, *v2;
+ vec3_t normal, edgevec;
+ dplane_t *plane;
+
+ for (i = 1; i <= w->numpoints; i++)
+ {
+ v1 = w->p[i % w->numpoints];
+ v2 = w->p[(i + 1) % w->numpoints];
+
+ VectorSubtract(v2, v1, edgevec);
+ plane = &dplanes[planenum];
+ CrossProduct(plane->normal, edgevec, normal);
+ VectorNormalize(normal);
+ dist = DotProduct(normal, v1);
+ //
+ if (DotProduct(normal, point) - dist > WCONVEX_EPSILON) return false;
+ } //end for
+ return true;
+} //end of the function InsideWinding
+
+int InsideFace(dface_t *face, vec3_t point)
+{
+ int i, edgenum, side;
+ float dist;
+ vec_t *v1, *v2;
+ vec3_t normal, edgevec;
+ dplane_t *plane;
+
+ for (i = 0; i < face->numedges; i++)
+ {
+ //get the first and second vertex of the edge
+ edgenum = dsurfedges[face->firstedge + i];
+ side = edgenum < 0;
+ v1 = dvertexes[dedges[abs(edgenum)].v[side]].point;
+ v2 = dvertexes[dedges[abs(edgenum)].v[!side]].point;
+ //create a plane through the edge vector, orthogonal to the face plane
+ //and with the normal vector pointing out of the face
+ VectorSubtract(v1, v2, edgevec);
+ plane = &dplanes[face->planenum];
+ CrossProduct(plane->normal, edgevec, normal);
+ VectorNormalize(normal);
+ dist = DotProduct(normal, v1);
+ //
+ if (DotProduct(normal, point) - dist > WCONVEX_EPSILON) return false;
+ } //end for
+ return true;
+} //end of the function InsideFace
+//===========================================================================
+// returns the amount the face and the winding overlap
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float Q2_FaceOnWinding(q2_dface_t *face, winding_t *winding)
+{
+ int i, edgenum, side;
+ float dist, area;
+ q2_dplane_t plane;
+ vec_t *v1, *v2;
+ vec3_t normal, edgevec;
+ winding_t *w;
+
+ //
+ w = CopyWinding(winding);
+ memcpy(&plane, &q2_dplanes[face->planenum], sizeof(q2_dplane_t));
+ //check on which side of the plane the face is
+ if (face->side)
+ {
+ VectorNegate(plane.normal, plane.normal);
+ plane.dist = -plane.dist;
+ } //end if
+ for (i = 0; i < face->numedges && w; i++)
+ {
+ //get the first and second vertex of the edge
+ edgenum = q2_dsurfedges[face->firstedge + i];
+ side = edgenum > 0;
+ //if the face plane is flipped
+ v1 = q2_dvertexes[q2_dedges[abs(edgenum)].v[side]].point;
+ v2 = q2_dvertexes[q2_dedges[abs(edgenum)].v[!side]].point;
+ //create a plane through the edge vector, orthogonal to the face plane
+ //and with the normal vector pointing inward
+ VectorSubtract(v1, v2, edgevec);
+ CrossProduct(edgevec, plane.normal, normal);
+ VectorNormalize(normal);
+ dist = DotProduct(normal, v1);
+ //
+ ChopWindingInPlace(&w, normal, dist, -0.1); //CLIP_EPSILON
+ } //end for
+ if (w)
+ {
+ area = WindingArea(w);
+ FreeWinding(w);
+ return area;
+ } //end if
+ return 0;
+} //end of the function Q2_FaceOnWinding
+//===========================================================================
+// creates a winding for the given brush side on the given brush
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+winding_t *Q2_BrushSideWinding(dbrush_t *brush, dbrushside_t *baseside)
+{
+ int i;
+ dplane_t *baseplane, *plane;
+ winding_t *w;
+ dbrushside_t *side;
+
+ //create a winding for the brush side with the given planenumber
+ baseplane = &dplanes[baseside->planenum];
+ w = BaseWindingForPlane(baseplane->normal, baseplane->dist);
+ for (i = 0; i < brush->numsides && w; i++)
+ {
+ side = &dbrushsides[brush->firstside + i];
+ //don't chop with the base plane
+ if (side->planenum == baseside->planenum) continue;
+ //also don't use planes that are almost equal
+ plane = &dplanes[side->planenum];
+ if (DotProduct(baseplane->normal, plane->normal) > 0.999
+ && fabs(baseplane->dist - plane->dist) < 0.01) continue;
+ //
+ plane = &dplanes[side->planenum^1];
+ ChopWindingInPlace(&w, plane->normal, plane->dist, -0.1); //CLIP_EPSILON);
+ } //end for
+ return w;
+} //end of the function Q2_BrushSideWinding
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int Q2_HintSkipBrush(dbrush_t *brush)
+{
+ int j;
+ dbrushside_t *brushside;
+
+ for (j = 0; j < brush->numsides; j++)
+ {
+ brushside = &dbrushsides[brush->firstside + j];
+ if (brushside->texinfo > 0)
+ {
+ if (texinfo[brushside->texinfo].flags & (SURF_SKIP|SURF_HINT))
+ {
+ return true;
+ } //end if
+ } //end if
+ } //end for
+ return false;
+} //end of the function Q2_HintSkipBrush
+//===========================================================================
+// fix screwed brush texture references
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean WindingIsTiny(winding_t *w);
+
+void Q2_FixTextureReferences(void)
+{
+ int i, j, k, we;
+ dbrushside_t *brushside;
+ dbrush_t *brush;
+ dface_t *face;
+ winding_t *w;
+
+ memset(brushsidetextured, false, MAX_MAP_BRUSHSIDES);
+ //go over all the brushes
+ for (i = 0; i < numbrushes; i++)
+ {
+ brush = &dbrushes[i];
+ //hint brushes are not textured
+ if (Q2_HintSkipBrush(brush)) continue;
+ //go over all the sides of the brush
+ for (j = 0; j < brush->numsides; j++)
+ {
+ brushside = &dbrushsides[brush->firstside + j];
+ //
+ w = Q2_BrushSideWinding(brush, brushside);
+ if (!w)
+ {
+ brushsidetextured[brush->firstside + j] = true;
+ continue;
+ } //end if
+ else
+ {
+ //RemoveEqualPoints(w, 0.2);
+ if (WindingIsTiny(w))
+ {
+ FreeWinding(w);
+ brushsidetextured[brush->firstside + j] = true;
+ continue;
+ } //end if
+ else
+ {
+ we = WindingError(w);
+ if (we == WE_NOTENOUGHPOINTS
+ || we == WE_SMALLAREA
+ || we == WE_POINTBOGUSRANGE
+// || we == WE_NONCONVEX
+ )
+ {
+ FreeWinding(w);
+ brushsidetextured[brush->firstside + j] = true;
+ continue;
+ } //end if
+ } //end else
+ } //end else
+ if (WindingArea(w) < 20)
+ {
+ brushsidetextured[brush->firstside + j] = true;
+ } //end if
+ //find a face for texturing this brush
+ for (k = 0; k < numfaces; k++)
+ {
+ face = &dfaces[k];
+ //if the face is in the same plane as the brush side
+ if ((face->planenum&~1) != (brushside->planenum&~1)) continue;
+ //if the face is partly or totally on the brush side
+ if (Q2_FaceOnWinding(face, w))
+ {
+ brushside->texinfo = face->texinfo;
+ brushsidetextured[brush->firstside + j] = true;
+ break;
+ } //end if
+ } //end for
+ FreeWinding(w);
+ } //end for
+ } //end for
+} //end of the function Q2_FixTextureReferences*/
+
+//#endif //ME
+
+
+/*
+===============
+CompressVis
+
+===============
+*/
+int Q2_CompressVis (byte *vis, byte *dest)
+{
+ int j;
+ int rep;
+ int visrow;
+ byte *dest_p;
+
+ dest_p = dest;
+// visrow = (r_numvisleafs + 7)>>3;
+ visrow = (dvis->numclusters + 7)>>3;
+
+ for (j=0 ; j<visrow ; j++)
+ {
+ *dest_p++ = vis[j];
+ if (vis[j])
+ continue;
+
+ rep = 1;
+ for ( j++; j<visrow ; j++)
+ if (vis[j] || rep == 255)
+ break;
+ else
+ rep++;
+ *dest_p++ = rep;
+ j--;
+ }
+
+ return dest_p - dest;
+}
+
+
+/*
+===================
+DecompressVis
+===================
+*/
+void Q2_DecompressVis (byte *in, byte *decompressed)
+{
+ int c;
+ byte *out;
+ int row;
+
+// row = (r_numvisleafs+7)>>3;
+ row = (dvis->numclusters+7)>>3;
+ out = decompressed;
+
+ do
+ {
+ if (*in)
+ {
+ *out++ = *in++;
+ continue;
+ }
+
+ c = in[1];
+ if (!c)
+ Error ("DecompressVis: 0 repeat");
+ in += 2;
+ while (c)
+ {
+ *out++ = 0;
+ c--;
+ }
+ } while (out - decompressed < row);
+}
+
+//=============================================================================
+
+/*
+=============
+SwapBSPFile
+
+Byte swaps all data in a bsp file.
+=============
+*/
+void Q2_SwapBSPFile (qboolean todisk)
+{
+ int i, j;
+ dmodel_t *d;
+
+
+// models
+ for (i=0 ; i<nummodels ; i++)
+ {
+ d = &dmodels[i];
+
+ d->firstface = LittleLong (d->firstface);
+ d->numfaces = LittleLong (d->numfaces);
+ d->headnode = LittleLong (d->headnode);
+
+ for (j=0 ; j<3 ; j++)
+ {
+ d->mins[j] = LittleFloat(d->mins[j]);
+ d->maxs[j] = LittleFloat(d->maxs[j]);
+ d->origin[j] = LittleFloat(d->origin[j]);
+ }
+ }
+
+//
+// vertexes
+//
+ for (i=0 ; i<numvertexes ; i++)
+ {
+ for (j=0 ; j<3 ; j++)
+ dvertexes[i].point[j] = LittleFloat (dvertexes[i].point[j]);
+ }
+
+//
+// planes
+//
+ for (i=0 ; i<numplanes ; i++)
+ {
+ for (j=0 ; j<3 ; j++)
+ dplanes[i].normal[j] = LittleFloat (dplanes[i].normal[j]);
+ dplanes[i].dist = LittleFloat (dplanes[i].dist);
+ dplanes[i].type = LittleLong (dplanes[i].type);
+ }
+
+//
+// texinfos
+//
+ for (i=0 ; i<numtexinfo ; i++)
+ {
+ for (j=0 ; j<8 ; j++)
+ texinfo[i].vecs[0][j] = LittleFloat (texinfo[i].vecs[0][j]);
+ texinfo[i].flags = LittleLong (texinfo[i].flags);
+ texinfo[i].value = LittleLong (texinfo[i].value);
+ texinfo[i].nexttexinfo = LittleLong (texinfo[i].nexttexinfo);
+ }
+
+//
+// faces
+//
+ for (i=0 ; i<numfaces ; i++)
+ {
+ dfaces[i].texinfo = LittleShort (dfaces[i].texinfo);
+ dfaces[i].planenum = LittleShort (dfaces[i].planenum);
+ dfaces[i].side = LittleShort (dfaces[i].side);
+ dfaces[i].lightofs = LittleLong (dfaces[i].lightofs);
+ dfaces[i].firstedge = LittleLong (dfaces[i].firstedge);
+ dfaces[i].numedges = LittleShort (dfaces[i].numedges);
+ }
+
+//
+// nodes
+//
+ for (i=0 ; i<numnodes ; i++)
+ {
+ dnodes[i].planenum = LittleLong (dnodes[i].planenum);
+ for (j=0 ; j<3 ; j++)
+ {
+ dnodes[i].mins[j] = LittleShort (dnodes[i].mins[j]);
+ dnodes[i].maxs[j] = LittleShort (dnodes[i].maxs[j]);
+ }
+ dnodes[i].children[0] = LittleLong (dnodes[i].children[0]);
+ dnodes[i].children[1] = LittleLong (dnodes[i].children[1]);
+ dnodes[i].firstface = LittleShort (dnodes[i].firstface);
+ dnodes[i].numfaces = LittleShort (dnodes[i].numfaces);
+ }
+
+//
+// leafs
+//
+ for (i=0 ; i<numleafs ; i++)
+ {
+ dleafs[i].contents = LittleLong (dleafs[i].contents);
+ dleafs[i].cluster = LittleShort (dleafs[i].cluster);
+ dleafs[i].area = LittleShort (dleafs[i].area);
+ for (j=0 ; j<3 ; j++)
+ {
+ dleafs[i].mins[j] = LittleShort (dleafs[i].mins[j]);
+ dleafs[i].maxs[j] = LittleShort (dleafs[i].maxs[j]);
+ }
+
+ dleafs[i].firstleafface = LittleShort (dleafs[i].firstleafface);
+ dleafs[i].numleaffaces = LittleShort (dleafs[i].numleaffaces);
+ dleafs[i].firstleafbrush = LittleShort (dleafs[i].firstleafbrush);
+ dleafs[i].numleafbrushes = LittleShort (dleafs[i].numleafbrushes);
+ }
+
+//
+// leaffaces
+//
+ for (i=0 ; i<numleaffaces ; i++)
+ dleaffaces[i] = LittleShort (dleaffaces[i]);
+
+//
+// leafbrushes
+//
+ for (i=0 ; i<numleafbrushes ; i++)
+ dleafbrushes[i] = LittleShort (dleafbrushes[i]);
+
+//
+// surfedges
+//
+ for (i=0 ; i<numsurfedges ; i++)
+ dsurfedges[i] = LittleLong (dsurfedges[i]);
+
+//
+// edges
+//
+ for (i=0 ; i<numedges ; i++)
+ {
+ dedges[i].v[0] = LittleShort (dedges[i].v[0]);
+ dedges[i].v[1] = LittleShort (dedges[i].v[1]);
+ }
+
+//
+// brushes
+//
+ for (i=0 ; i<numbrushes ; i++)
+ {
+ dbrushes[i].firstside = LittleLong (dbrushes[i].firstside);
+ dbrushes[i].numsides = LittleLong (dbrushes[i].numsides);
+ dbrushes[i].contents = LittleLong (dbrushes[i].contents);
+ }
+
+//
+// areas
+//
+ for (i=0 ; i<numareas ; i++)
+ {
+ dareas[i].numareaportals = LittleLong (dareas[i].numareaportals);
+ dareas[i].firstareaportal = LittleLong (dareas[i].firstareaportal);
+ }
+
+//
+// areasportals
+//
+ for (i=0 ; i<numareaportals ; i++)
+ {
+ dareaportals[i].portalnum = LittleLong (dareaportals[i].portalnum);
+ dareaportals[i].otherarea = LittleLong (dareaportals[i].otherarea);
+ }
+
+//
+// brushsides
+//
+ for (i=0 ; i<numbrushsides ; i++)
+ {
+ dbrushsides[i].planenum = LittleShort (dbrushsides[i].planenum);
+ dbrushsides[i].texinfo = LittleShort (dbrushsides[i].texinfo);
+ }
+
+//
+// visibility
+//
+ if (todisk)
+ j = dvis->numclusters;
+ else
+ j = LittleLong(dvis->numclusters);
+ dvis->numclusters = LittleLong (dvis->numclusters);
+ for (i=0 ; i<j ; i++)
+ {
+ dvis->bitofs[i][0] = LittleLong (dvis->bitofs[i][0]);
+ dvis->bitofs[i][1] = LittleLong (dvis->bitofs[i][1]);
+ }
+} //end of the function Q2_SwapBSPFile
+
+
+dheader_t *header;
+
+int Q2_CopyLump (int lump, void *dest, int size, int maxsize)
+{
+ int length, ofs;
+
+ length = header->lumps[lump].filelen;
+ ofs = header->lumps[lump].fileofs;
+
+ if (length % size)
+ Error ("LoadBSPFile: odd lump size");
+
+ if ((length/size) > maxsize)
+ Error ("Q2_LoadBSPFile: exceeded max size for lump %d size %d > maxsize %d\n", lump, (length/size), maxsize);
+
+ memcpy (dest, (byte *)header + ofs, length);
+
+ return length / size;
+} //end of the function Q2_CopyLump
+
+/*
+=============
+LoadBSPFile
+=============
+*/
+void Q2_LoadBSPFile(char *filename, int offset, int length)
+{
+ int i;
+
+//
+// load the file header
+//
+ LoadFile (filename, (void **)&header, offset, length);
+
+// swap the header
+ for (i=0 ; i< sizeof(dheader_t)/4 ; i++)
+ ((int *)header)[i] = LittleLong ( ((int *)header)[i]);
+
+ if (header->ident != IDBSPHEADER)
+ Error ("%s is not a IBSP file", filename);
+ if (header->version != BSPVERSION)
+ Error ("%s is version %i, not %i", filename, header->version, BSPVERSION);
+
+ nummodels = Q2_CopyLump (LUMP_MODELS, dmodels, sizeof(dmodel_t), MAX_MAP_MODELS);
+ numvertexes = Q2_CopyLump (LUMP_VERTEXES, dvertexes, sizeof(dvertex_t), MAX_MAP_VERTS);
+ numplanes = Q2_CopyLump (LUMP_PLANES, dplanes, sizeof(dplane_t), MAX_MAP_PLANES);
+ numleafs = Q2_CopyLump (LUMP_LEAFS, dleafs, sizeof(dleaf_t), MAX_MAP_LEAFS);
+ numnodes = Q2_CopyLump (LUMP_NODES, dnodes, sizeof(dnode_t), MAX_MAP_NODES);
+ numtexinfo = Q2_CopyLump (LUMP_TEXINFO, texinfo, sizeof(texinfo_t), MAX_MAP_TEXINFO);
+ numfaces = Q2_CopyLump (LUMP_FACES, dfaces, sizeof(dface_t), MAX_MAP_FACES);
+ numleaffaces = Q2_CopyLump (LUMP_LEAFFACES, dleaffaces, sizeof(dleaffaces[0]), MAX_MAP_LEAFFACES);
+ numleafbrushes = Q2_CopyLump (LUMP_LEAFBRUSHES, dleafbrushes, sizeof(dleafbrushes[0]), MAX_MAP_LEAFBRUSHES);
+ numsurfedges = Q2_CopyLump (LUMP_SURFEDGES, dsurfedges, sizeof(dsurfedges[0]), MAX_MAP_SURFEDGES);
+ numedges = Q2_CopyLump (LUMP_EDGES, dedges, sizeof(dedge_t), MAX_MAP_EDGES);
+ numbrushes = Q2_CopyLump (LUMP_BRUSHES, dbrushes, sizeof(dbrush_t), MAX_MAP_BRUSHES);
+ numbrushsides = Q2_CopyLump (LUMP_BRUSHSIDES, dbrushsides, sizeof(dbrushside_t), MAX_MAP_BRUSHSIDES);
+ numareas = Q2_CopyLump (LUMP_AREAS, dareas, sizeof(darea_t), MAX_MAP_AREAS);
+ numareaportals = Q2_CopyLump (LUMP_AREAPORTALS, dareaportals, sizeof(dareaportal_t), MAX_MAP_AREAPORTALS);
+
+ visdatasize = Q2_CopyLump (LUMP_VISIBILITY, dvisdata, 1, MAX_MAP_VISIBILITY);
+ lightdatasize = Q2_CopyLump (LUMP_LIGHTING, dlightdata, 1, MAX_MAP_LIGHTING);
+ entdatasize = Q2_CopyLump (LUMP_ENTITIES, dentdata, 1, MAX_MAP_ENTSTRING);
+
+ Q2_CopyLump (LUMP_POP, dpop, 1, MAX_MAP_DPOP);
+
+ FreeMemory(header); // everything has been copied out
+
+//
+// swap everything
+//
+ Q2_SwapBSPFile (false);
+
+ Q2_FixTextureReferences();
+} //end of the function Q2_LoadBSPFile
+
+
+/*
+=============
+LoadBSPFileTexinfo
+
+Only loads the texinfo lump, so qdata can scan for textures
+=============
+*/
+void Q2_LoadBSPFileTexinfo (char *filename)
+{
+ int i;
+ FILE *f;
+ int length, ofs;
+
+ header = GetMemory(sizeof(dheader_t));
+
+ f = fopen (filename, "rb");
+ fread (header, sizeof(dheader_t), 1, f);
+
+// swap the header
+ for (i=0 ; i< sizeof(dheader_t)/4 ; i++)
+ ((int *)header)[i] = LittleLong ( ((int *)header)[i]);
+
+ if (header->ident != IDBSPHEADER)
+ Error ("%s is not a IBSP file", filename);
+ if (header->version != BSPVERSION)
+ Error ("%s is version %i, not %i", filename, header->version, BSPVERSION);
+
+
+ length = header->lumps[LUMP_TEXINFO].filelen;
+ ofs = header->lumps[LUMP_TEXINFO].fileofs;
+
+ fseek (f, ofs, SEEK_SET);
+ fread (texinfo, length, 1, f);
+ fclose (f);
+
+ numtexinfo = length / sizeof(texinfo_t);
+
+ FreeMemory(header); // everything has been copied out
+
+ Q2_SwapBSPFile (false);
+} //end of the function Q2_LoadBSPFileTexinfo
+
+
+//============================================================================
+
+FILE *wadfile;
+dheader_t outheader;
+
+void Q2_AddLump (int lumpnum, void *data, int len)
+{
+ lump_t *lump;
+
+ lump = &header->lumps[lumpnum];
+
+ lump->fileofs = LittleLong( ftell(wadfile) );
+ lump->filelen = LittleLong(len);
+ SafeWrite (wadfile, data, (len+3)&~3);
+} //end of the function Q2_AddLump
+
+/*
+=============
+WriteBSPFile
+
+Swaps the bsp file in place, so it should not be referenced again
+=============
+*/
+void Q2_WriteBSPFile (char *filename)
+{
+ header = &outheader;
+ memset (header, 0, sizeof(dheader_t));
+
+ Q2_SwapBSPFile (true);
+
+ header->ident = LittleLong (IDBSPHEADER);
+ header->version = LittleLong (BSPVERSION);
+
+ wadfile = SafeOpenWrite (filename);
+ SafeWrite (wadfile, header, sizeof(dheader_t)); // overwritten later
+
+ Q2_AddLump (LUMP_PLANES, dplanes, numplanes*sizeof(dplane_t));
+ Q2_AddLump (LUMP_LEAFS, dleafs, numleafs*sizeof(dleaf_t));
+ Q2_AddLump (LUMP_VERTEXES, dvertexes, numvertexes*sizeof(dvertex_t));
+ Q2_AddLump (LUMP_NODES, dnodes, numnodes*sizeof(dnode_t));
+ Q2_AddLump (LUMP_TEXINFO, texinfo, numtexinfo*sizeof(texinfo_t));
+ Q2_AddLump (LUMP_FACES, dfaces, numfaces*sizeof(dface_t));
+ Q2_AddLump (LUMP_BRUSHES, dbrushes, numbrushes*sizeof(dbrush_t));
+ Q2_AddLump (LUMP_BRUSHSIDES, dbrushsides, numbrushsides*sizeof(dbrushside_t));
+ Q2_AddLump (LUMP_LEAFFACES, dleaffaces, numleaffaces*sizeof(dleaffaces[0]));
+ Q2_AddLump (LUMP_LEAFBRUSHES, dleafbrushes, numleafbrushes*sizeof(dleafbrushes[0]));
+ Q2_AddLump (LUMP_SURFEDGES, dsurfedges, numsurfedges*sizeof(dsurfedges[0]));
+ Q2_AddLump (LUMP_EDGES, dedges, numedges*sizeof(dedge_t));
+ Q2_AddLump (LUMP_MODELS, dmodels, nummodels*sizeof(dmodel_t));
+ Q2_AddLump (LUMP_AREAS, dareas, numareas*sizeof(darea_t));
+ Q2_AddLump (LUMP_AREAPORTALS, dareaportals, numareaportals*sizeof(dareaportal_t));
+
+ Q2_AddLump (LUMP_LIGHTING, dlightdata, lightdatasize);
+ Q2_AddLump (LUMP_VISIBILITY, dvisdata, visdatasize);
+ Q2_AddLump (LUMP_ENTITIES, dentdata, entdatasize);
+ Q2_AddLump (LUMP_POP, dpop, sizeof(dpop));
+
+ fseek (wadfile, 0, SEEK_SET);
+ SafeWrite (wadfile, header, sizeof(dheader_t));
+ fclose (wadfile);
+} //end of the function Q2_WriteBSPFile
+
+//============================================================================
+
+/*
+=============
+PrintBSPFileSizes
+
+Dumps info about current file
+=============
+*/
+void Q2_PrintBSPFileSizes (void)
+{
+ if (!num_entities)
+ Q2_ParseEntities();
+
+ printf ("%6i models %7i\n"
+ ,nummodels, (int)(nummodels*sizeof(dmodel_t)));
+ printf ("%6i brushes %7i\n"
+ ,numbrushes, (int)(numbrushes*sizeof(dbrush_t)));
+ printf ("%6i brushsides %7i\n"
+ ,numbrushsides, (int)(numbrushsides*sizeof(dbrushside_t)));
+ printf ("%6i planes %7i\n"
+ ,numplanes, (int)(numplanes*sizeof(dplane_t)));
+ printf ("%6i texinfo %7i\n"
+ ,numtexinfo, (int)(numtexinfo*sizeof(texinfo_t)));
+ printf ("%6i entdata %7i\n", num_entities, entdatasize);
+
+ printf ("\n");
+
+ printf ("%6i vertexes %7i\n"
+ ,numvertexes, (int)(numvertexes*sizeof(dvertex_t)));
+ printf ("%6i nodes %7i\n"
+ ,numnodes, (int)(numnodes*sizeof(dnode_t)));
+ printf ("%6i faces %7i\n"
+ ,numfaces, (int)(numfaces*sizeof(dface_t)));
+ printf ("%6i leafs %7i\n"
+ ,numleafs, (int)(numleafs*sizeof(dleaf_t)));
+ printf ("%6i leaffaces %7i\n"
+ ,numleaffaces, (int)(numleaffaces*sizeof(dleaffaces[0])));
+ printf ("%6i leafbrushes %7i\n"
+ ,numleafbrushes, (int)(numleafbrushes*sizeof(dleafbrushes[0])));
+ printf ("%6i surfedges %7i\n"
+ ,numsurfedges, (int)(numsurfedges*sizeof(dsurfedges[0])));
+ printf ("%6i edges %7i\n"
+ ,numedges, (int)(numedges*sizeof(dedge_t)));
+//NEW
+ printf ("%6i areas %7i\n"
+ ,numareas, (int)(numareas*sizeof(darea_t)));
+ printf ("%6i areaportals %7i\n"
+ ,numareaportals, (int)(numareaportals*sizeof(dareaportal_t)));
+//ENDNEW
+ printf (" lightdata %7i\n", lightdatasize);
+ printf (" visdata %7i\n", visdatasize);
+} //end of the function Q2_PrintBSPFileSizes
+
+/*
+================
+ParseEntities
+
+Parses the dentdata string into entities
+================
+*/
+void Q2_ParseEntities (void)
+{
+ script_t *script;
+
+ num_entities = 0;
+ script = LoadScriptMemory(dentdata, entdatasize, "*Quake2 bsp file");
+ SetScriptFlags(script, SCFL_NOSTRINGWHITESPACES |
+ SCFL_NOSTRINGESCAPECHARS);
+
+ while(ParseEntity(script))
+ {
+ } //end while
+
+ FreeScript(script);
+} //end of the function Q2_ParseEntities
+
+
+/*
+================
+UnparseEntities
+
+Generates the dentdata string from all the entities
+================
+*/
+void Q2_UnparseEntities (void)
+{
+ char *buf, *end;
+ epair_t *ep;
+ char line[2048];
+ int i;
+ char key[1024], value[1024];
+
+ buf = dentdata;
+ end = buf;
+ *end = 0;
+
+ for (i=0 ; i<num_entities ; i++)
+ {
+ ep = entities[i].epairs;
+ if (!ep)
+ continue; // ent got removed
+
+ strcat (end,"{\n");
+ end += 2;
+
+ for (ep = entities[i].epairs ; ep ; ep=ep->next)
+ {
+ strcpy (key, ep->key);
+ StripTrailing (key);
+ strcpy (value, ep->value);
+ StripTrailing (value);
+
+ sprintf (line, "\"%s\" \"%s\"\n", key, value);
+ strcat (end, line);
+ end += strlen(line);
+ }
+ strcat (end,"}\n");
+ end += 2;
+
+ if (end > buf + MAX_MAP_ENTSTRING)
+ Error ("Entity text too long");
+ }
+ entdatasize = end - buf + 1;
+} //end of the function Q2_UnparseEntities
+
diff --git a/code/bspc/l_bsp_q2.h b/code/bspc/l_bsp_q2.h
new file mode 100755
index 0000000..8d937a8
--- /dev/null
+++ b/code/bspc/l_bsp_q2.h
@@ -0,0 +1,98 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#ifndef ME
+#define ME
+#endif //ME
+
+extern int nummodels;
+extern dmodel_t *dmodels;//[MAX_MAP_MODELS];
+
+extern int visdatasize;
+extern byte *dvisdata;//[MAX_MAP_VISIBILITY];
+extern dvis_t *dvis;
+
+extern int lightdatasize;
+extern byte *dlightdata;//[MAX_MAP_LIGHTING];
+
+extern int entdatasize;
+extern char *dentdata;//[MAX_MAP_ENTSTRING];
+
+extern int numleafs;
+extern dleaf_t *dleafs;//[MAX_MAP_LEAFS];
+
+extern int numplanes;
+extern dplane_t *dplanes;//[MAX_MAP_PLANES];
+
+extern int numvertexes;
+extern dvertex_t *dvertexes;//[MAX_MAP_VERTS];
+
+extern int numnodes;
+extern dnode_t *dnodes;//[MAX_MAP_NODES];
+
+extern int numtexinfo;
+extern texinfo_t texinfo[MAX_MAP_TEXINFO];
+
+extern int numfaces;
+extern dface_t *dfaces;//[MAX_MAP_FACES];
+
+extern int numedges;
+extern dedge_t *dedges;//[MAX_MAP_EDGES];
+
+extern int numleaffaces;
+extern unsigned short *dleaffaces;//[MAX_MAP_LEAFFACES];
+
+extern int numleafbrushes;
+extern unsigned short *dleafbrushes;//[MAX_MAP_LEAFBRUSHES];
+
+extern int numsurfedges;
+extern int *dsurfedges;//[MAX_MAP_SURFEDGES];
+
+extern int numareas;
+extern darea_t *dareas;//[MAX_MAP_AREAS];
+
+extern int numareaportals;
+extern dareaportal_t *dareaportals;//[MAX_MAP_AREAPORTALS];
+
+extern int numbrushes;
+extern dbrush_t *dbrushes;//[MAX_MAP_BRUSHES];
+
+extern int numbrushsides;
+extern dbrushside_t *dbrushsides;//[MAX_MAP_BRUSHSIDES];
+
+extern byte dpop[256];
+
+extern char brushsidetextured[MAX_MAP_BRUSHSIDES];
+
+void Q2_AllocMaxBSP(void);
+void Q2_FreeMaxBSP(void);
+
+void Q2_DecompressVis(byte *in, byte *decompressed);
+int Q2_CompressVis(byte *vis, byte *dest);
+
+void Q2_LoadBSPFile(char *filename, int offset, int length);
+void Q2_LoadBSPFileTexinfo(char *filename); // just for qdata
+void Q2_WriteBSPFile(char *filename);
+void Q2_PrintBSPFileSizes(void);
+void Q2_ParseEntities(void);
+void Q2_UnparseEntities(void);
+
diff --git a/code/bspc/l_bsp_q3.c b/code/bspc/l_bsp_q3.c
new file mode 100755
index 0000000..19a3941
--- /dev/null
+++ b/code/bspc/l_bsp_q3.c
@@ -0,0 +1,824 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "l_cmd.h"
+#include "l_math.h"
+#include "l_mem.h"
+#include "l_log.h"
+#include "l_poly.h"
+#include "../botlib/l_script.h"
+#include "l_qfiles.h"
+#include "l_bsp_q3.h"
+#include "l_bsp_ent.h"
+
+void Q3_ParseEntities (void);
+void Q3_PrintBSPFileSizes(void);
+
+void GetLeafNums (void);
+
+//=============================================================================
+
+#define WCONVEX_EPSILON 0.5
+
+
+int q3_nummodels;
+q3_dmodel_t *q3_dmodels;//[MAX_MAP_MODELS];
+
+int q3_numShaders;
+q3_dshader_t *q3_dshaders;//[Q3_MAX_MAP_SHADERS];
+
+int q3_entdatasize;
+char *q3_dentdata;//[Q3_MAX_MAP_ENTSTRING];
+
+int q3_numleafs;
+q3_dleaf_t *q3_dleafs;//[Q3_MAX_MAP_LEAFS];
+
+int q3_numplanes;
+q3_dplane_t *q3_dplanes;//[Q3_MAX_MAP_PLANES];
+
+int q3_numnodes;
+q3_dnode_t *q3_dnodes;//[Q3_MAX_MAP_NODES];
+
+int q3_numleafsurfaces;
+int *q3_dleafsurfaces;//[Q3_MAX_MAP_LEAFFACES];
+
+int q3_numleafbrushes;
+int *q3_dleafbrushes;//[Q3_MAX_MAP_LEAFBRUSHES];
+
+int q3_numbrushes;
+q3_dbrush_t *q3_dbrushes;//[Q3_MAX_MAP_BRUSHES];
+
+int q3_numbrushsides;
+q3_dbrushside_t *q3_dbrushsides;//[Q3_MAX_MAP_BRUSHSIDES];
+
+int q3_numLightBytes;
+byte *q3_lightBytes;//[Q3_MAX_MAP_LIGHTING];
+
+int q3_numGridPoints;
+byte *q3_gridData;//[Q3_MAX_MAP_LIGHTGRID];
+
+int q3_numVisBytes;
+byte *q3_visBytes;//[Q3_MAX_MAP_VISIBILITY];
+
+int q3_numDrawVerts;
+q3_drawVert_t *q3_drawVerts;//[Q3_MAX_MAP_DRAW_VERTS];
+
+int q3_numDrawIndexes;
+int *q3_drawIndexes;//[Q3_MAX_MAP_DRAW_INDEXES];
+
+int q3_numDrawSurfaces;
+q3_dsurface_t *q3_drawSurfaces;//[Q3_MAX_MAP_DRAW_SURFS];
+
+int q3_numFogs;
+q3_dfog_t *q3_dfogs;//[Q3_MAX_MAP_FOGS];
+
+char q3_dbrushsidetextured[Q3_MAX_MAP_BRUSHSIDES];
+
+extern qboolean forcesidesvisible;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Q3_FreeMaxBSP(void)
+{
+ if (q3_dmodels) FreeMemory(q3_dmodels);
+ q3_dmodels = NULL;
+ q3_nummodels = 0;
+ if (q3_dshaders) FreeMemory(q3_dshaders);
+ q3_dshaders = NULL;
+ q3_numShaders = 0;
+ if (q3_dentdata) FreeMemory(q3_dentdata);
+ q3_dentdata = NULL;
+ q3_entdatasize = 0;
+ if (q3_dleafs) FreeMemory(q3_dleafs);
+ q3_dleafs = NULL;
+ q3_numleafs = 0;
+ if (q3_dplanes) FreeMemory(q3_dplanes);
+ q3_dplanes = NULL;
+ q3_numplanes = 0;
+ if (q3_dnodes) FreeMemory(q3_dnodes);
+ q3_dnodes = NULL;
+ q3_numnodes = 0;
+ if (q3_dleafsurfaces) FreeMemory(q3_dleafsurfaces);
+ q3_dleafsurfaces = NULL;
+ q3_numleafsurfaces = 0;
+ if (q3_dleafbrushes) FreeMemory(q3_dleafbrushes);
+ q3_dleafbrushes = NULL;
+ q3_numleafbrushes = 0;
+ if (q3_dbrushes) FreeMemory(q3_dbrushes);
+ q3_dbrushes = NULL;
+ q3_numbrushes = 0;
+ if (q3_dbrushsides) FreeMemory(q3_dbrushsides);
+ q3_dbrushsides = NULL;
+ q3_numbrushsides = 0;
+ if (q3_lightBytes) FreeMemory(q3_lightBytes);
+ q3_lightBytes = NULL;
+ q3_numLightBytes = 0;
+ if (q3_gridData) FreeMemory(q3_gridData);
+ q3_gridData = NULL;
+ q3_numGridPoints = 0;
+ if (q3_visBytes) FreeMemory(q3_visBytes);
+ q3_visBytes = NULL;
+ q3_numVisBytes = 0;
+ if (q3_drawVerts) FreeMemory(q3_drawVerts);
+ q3_drawVerts = NULL;
+ q3_numDrawVerts = 0;
+ if (q3_drawIndexes) FreeMemory(q3_drawIndexes);
+ q3_drawIndexes = NULL;
+ q3_numDrawIndexes = 0;
+ if (q3_drawSurfaces) FreeMemory(q3_drawSurfaces);
+ q3_drawSurfaces = NULL;
+ q3_numDrawSurfaces = 0;
+ if (q3_dfogs) FreeMemory(q3_dfogs);
+ q3_dfogs = NULL;
+ q3_numFogs = 0;
+} //end of the function Q3_FreeMaxBSP
+
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Q3_PlaneFromPoints(vec3_t p0, vec3_t p1, vec3_t p2, vec3_t normal, float *dist)
+{
+ vec3_t t1, t2;
+
+ VectorSubtract(p0, p1, t1);
+ VectorSubtract(p2, p1, t2);
+ CrossProduct(t1, t2, normal);
+ VectorNormalize(normal);
+
+ *dist = DotProduct(p0, normal);
+} //end of the function PlaneFromPoints
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Q3_SurfacePlane(q3_dsurface_t *surface, vec3_t normal, float *dist)
+{
+ int i;
+ float *p0, *p1, *p2;
+ vec3_t t1, t2;
+
+ p0 = q3_drawVerts[surface->firstVert].xyz;
+ for (i = 1; i < surface->numVerts-1; i++)
+ {
+ p1 = q3_drawVerts[surface->firstVert + ((i) % surface->numVerts)].xyz;
+ p2 = q3_drawVerts[surface->firstVert + ((i+1) % surface->numVerts)].xyz;
+ VectorSubtract(p0, p1, t1);
+ VectorSubtract(p2, p1, t2);
+ CrossProduct(t1, t2, normal);
+ VectorNormalize(normal);
+ if (VectorLength(normal)) break;
+ } //end for*/
+/*
+ float dot;
+ for (i = 0; i < surface->numVerts; i++)
+ {
+ p0 = q3_drawVerts[surface->firstVert + ((i) % surface->numVerts)].xyz;
+ p1 = q3_drawVerts[surface->firstVert + ((i+1) % surface->numVerts)].xyz;
+ p2 = q3_drawVerts[surface->firstVert + ((i+2) % surface->numVerts)].xyz;
+ VectorSubtract(p0, p1, t1);
+ VectorSubtract(p2, p1, t2);
+ VectorNormalize(t1);
+ VectorNormalize(t2);
+ dot = DotProduct(t1, t2);
+ if (dot > -0.9 && dot < 0.9 &&
+ VectorLength(t1) > 0.1 && VectorLength(t2) > 0.1) break;
+ } //end for
+ CrossProduct(t1, t2, normal);
+ VectorNormalize(normal);
+*/
+ if (VectorLength(normal) < 0.9)
+ {
+ printf("surface %d bogus normal vector %f %f %f\n", surface - q3_drawSurfaces, normal[0], normal[1], normal[2]);
+ printf("t1 = %f %f %f, t2 = %f %f %f\n", t1[0], t1[1], t1[2], t2[0], t2[1], t2[2]);
+ for (i = 0; i < surface->numVerts; i++)
+ {
+ p1 = q3_drawVerts[surface->firstVert + ((i) % surface->numVerts)].xyz;
+ Log_Print("p%d = %f %f %f\n", i, p1[0], p1[1], p1[2]);
+ } //end for
+ } //end if
+ *dist = DotProduct(p0, normal);
+} //end of the function Q3_SurfacePlane
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+q3_dplane_t *q3_surfaceplanes;
+
+void Q3_CreatePlanarSurfacePlanes(void)
+{
+ int i;
+ q3_dsurface_t *surface;
+
+ Log_Print("creating planar surface planes...\n");
+ q3_surfaceplanes = (q3_dplane_t *) GetClearedMemory(q3_numDrawSurfaces * sizeof(q3_dplane_t));
+
+ for (i = 0; i < q3_numDrawSurfaces; i++)
+ {
+ surface = &q3_drawSurfaces[i];
+ if (surface->surfaceType != MST_PLANAR) continue;
+ Q3_SurfacePlane(surface, q3_surfaceplanes[i].normal, &q3_surfaceplanes[i].dist);
+ //Log_Print("normal = %f %f %f, dist = %f\n", q3_surfaceplanes[i].normal[0],
+ // q3_surfaceplanes[i].normal[1],
+ // q3_surfaceplanes[i].normal[2], q3_surfaceplanes[i].dist);
+ } //end for
+} //end of the function Q3_CreatePlanarSurfacePlanes
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+/*
+void Q3_SurfacePlane(q3_dsurface_t *surface, vec3_t normal, float *dist)
+{
+ //take the plane information from the lightmap vector
+ //VectorCopy(surface->lightmapVecs[2], normal);
+ //calculate plane dist with first surface vertex
+ //*dist = DotProduct(q3_drawVerts[surface->firstVert].xyz, normal);
+ Q3_PlaneFromPoints(q3_drawVerts[surface->firstVert].xyz,
+ q3_drawVerts[surface->firstVert+1].xyz,
+ q3_drawVerts[surface->firstVert+2].xyz, normal, dist);
+} //end of the function Q3_SurfacePlane*/
+//===========================================================================
+// returns the amount the face and the winding overlap
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float Q3_FaceOnWinding(q3_dsurface_t *surface, winding_t *winding)
+{
+ int i;
+ float dist, area;
+ q3_dplane_t plane;
+ vec_t *v1, *v2;
+ vec3_t normal, edgevec;
+ winding_t *w;
+
+ //copy the winding before chopping
+ w = CopyWinding(winding);
+ //retrieve the surface plane
+ Q3_SurfacePlane(surface, plane.normal, &plane.dist);
+ //chop the winding with the surface edge planes
+ for (i = 0; i < surface->numVerts && w; i++)
+ {
+ v1 = q3_drawVerts[surface->firstVert + ((i) % surface->numVerts)].xyz;
+ v2 = q3_drawVerts[surface->firstVert + ((i+1) % surface->numVerts)].xyz;
+ //create a plane through the edge from v1 to v2, orthogonal to the
+ //surface plane and with the normal vector pointing inward
+ VectorSubtract(v2, v1, edgevec);
+ CrossProduct(edgevec, plane.normal, normal);
+ VectorNormalize(normal);
+ dist = DotProduct(normal, v1);
+ //
+ ChopWindingInPlace(&w, normal, dist, -0.1); //CLIP_EPSILON
+ } //end for
+ if (w)
+ {
+ area = WindingArea(w);
+ FreeWinding(w);
+ return area;
+ } //end if
+ return 0;
+} //end of the function Q3_FaceOnWinding
+//===========================================================================
+// creates a winding for the given brush side on the given brush
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+winding_t *Q3_BrushSideWinding(q3_dbrush_t *brush, q3_dbrushside_t *baseside)
+{
+ int i;
+ q3_dplane_t *baseplane, *plane;
+ winding_t *w;
+ q3_dbrushside_t *side;
+
+ //create a winding for the brush side with the given planenumber
+ baseplane = &q3_dplanes[baseside->planeNum];
+ w = BaseWindingForPlane(baseplane->normal, baseplane->dist);
+ for (i = 0; i < brush->numSides && w; i++)
+ {
+ side = &q3_dbrushsides[brush->firstSide + i];
+ //don't chop with the base plane
+ if (side->planeNum == baseside->planeNum) continue;
+ //also don't use planes that are almost equal
+ plane = &q3_dplanes[side->planeNum];
+ if (DotProduct(baseplane->normal, plane->normal) > 0.999
+ && fabs(baseplane->dist - plane->dist) < 0.01) continue;
+ //
+ plane = &q3_dplanes[side->planeNum^1];
+ ChopWindingInPlace(&w, plane->normal, plane->dist, -0.1); //CLIP_EPSILON);
+ } //end for
+ return w;
+} //end of the function Q3_BrushSideWinding
+//===========================================================================
+// fix screwed brush texture references
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean WindingIsTiny(winding_t *w);
+
+void Q3_FindVisibleBrushSides(void)
+{
+ int i, j, k, we, numtextured, numsides;
+ float dot;
+ q3_dplane_t *plane;
+ q3_dbrushside_t *brushside;
+ q3_dbrush_t *brush;
+ q3_dsurface_t *surface;
+ winding_t *w;
+
+ memset(q3_dbrushsidetextured, false, Q3_MAX_MAP_BRUSHSIDES);
+ //
+ numsides = 0;
+ //create planes for the planar surfaces
+ Q3_CreatePlanarSurfacePlanes();
+ Log_Print("searching visible brush sides...\n");
+ Log_Print("%6d brush sides", numsides);
+ //go over all the brushes
+ for (i = 0; i < q3_numbrushes; i++)
+ {
+ brush = &q3_dbrushes[i];
+ //go over all the sides of the brush
+ for (j = 0; j < brush->numSides; j++)
+ {
+ qprintf("\r%6d", numsides++);
+ brushside = &q3_dbrushsides[brush->firstSide + j];
+ //
+ w = Q3_BrushSideWinding(brush, brushside);
+ if (!w)
+ {
+ q3_dbrushsidetextured[brush->firstSide + j] = true;
+ continue;
+ } //end if
+ else
+ {
+ //RemoveEqualPoints(w, 0.2);
+ if (WindingIsTiny(w))
+ {
+ FreeWinding(w);
+ q3_dbrushsidetextured[brush->firstSide + j] = true;
+ continue;
+ } //end if
+ else
+ {
+ we = WindingError(w);
+ if (we == WE_NOTENOUGHPOINTS
+ || we == WE_SMALLAREA
+ || we == WE_POINTBOGUSRANGE
+// || we == WE_NONCONVEX
+ )
+ {
+ FreeWinding(w);
+ q3_dbrushsidetextured[brush->firstSide + j] = true;
+ continue;
+ } //end if
+ } //end else
+ } //end else
+ if (WindingArea(w) < 20)
+ {
+ q3_dbrushsidetextured[brush->firstSide + j] = true;
+ continue;
+ } //end if
+ //find a face for texturing this brush
+ for (k = 0; k < q3_numDrawSurfaces; k++)
+ {
+ surface = &q3_drawSurfaces[k];
+ if (surface->surfaceType != MST_PLANAR) continue;
+ //
+ //Q3_SurfacePlane(surface, plane.normal, &plane.dist);
+ plane = &q3_surfaceplanes[k];
+ //the surface plane and the brush side plane should be pretty much the same
+ if (fabs(fabs(plane->dist) - fabs(q3_dplanes[brushside->planeNum].dist)) > 5) continue;
+ dot = DotProduct(plane->normal, q3_dplanes[brushside->planeNum].normal);
+ if (dot > -0.9 && dot < 0.9) continue;
+ //if the face is partly or totally on the brush side
+ if (Q3_FaceOnWinding(surface, w))
+ {
+ q3_dbrushsidetextured[brush->firstSide + j] = true;
+ //Log_Write("Q3_FaceOnWinding");
+ break;
+ } //end if
+ } //end for
+ FreeWinding(w);
+ } //end for
+ } //end for
+ qprintf("\r%6d brush sides\n", numsides);
+ numtextured = 0;
+ for (i = 0; i < q3_numbrushsides; i++)
+ {
+ if (forcesidesvisible) q3_dbrushsidetextured[i] = true;
+ if (q3_dbrushsidetextured[i]) numtextured++;
+ } //end for
+ Log_Print("%d brush sides textured out of %d\n", numtextured, q3_numbrushsides);
+} //end of the function Q3_FindVisibleBrushSides
+
+/*
+=============
+Q3_SwapBlock
+
+If all values are 32 bits, this can be used to swap everything
+=============
+*/
+void Q3_SwapBlock( int *block, int sizeOfBlock ) {
+ int i;
+
+ sizeOfBlock >>= 2;
+ for ( i = 0 ; i < sizeOfBlock ; i++ ) {
+ block[i] = LittleLong( block[i] );
+ }
+} //end of the function Q3_SwapBlock
+
+/*
+=============
+Q3_SwapBSPFile
+
+Byte swaps all data in a bsp file.
+=============
+*/
+void Q3_SwapBSPFile( void ) {
+ int i;
+
+ // models
+ Q3_SwapBlock( (int *)q3_dmodels, q3_nummodels * sizeof( q3_dmodels[0] ) );
+
+ // shaders (don't swap the name)
+ for ( i = 0 ; i < q3_numShaders ; i++ ) {
+ q3_dshaders[i].contentFlags = LittleLong( q3_dshaders[i].contentFlags );
+ q3_dshaders[i].surfaceFlags = LittleLong( q3_dshaders[i].surfaceFlags );
+ }
+
+ // planes
+ Q3_SwapBlock( (int *)q3_dplanes, q3_numplanes * sizeof( q3_dplanes[0] ) );
+
+ // nodes
+ Q3_SwapBlock( (int *)q3_dnodes, q3_numnodes * sizeof( q3_dnodes[0] ) );
+
+ // leafs
+ Q3_SwapBlock( (int *)q3_dleafs, q3_numleafs * sizeof( q3_dleafs[0] ) );
+
+ // leaffaces
+ Q3_SwapBlock( (int *)q3_dleafsurfaces, q3_numleafsurfaces * sizeof( q3_dleafsurfaces[0] ) );
+
+ // leafbrushes
+ Q3_SwapBlock( (int *)q3_dleafbrushes, q3_numleafbrushes * sizeof( q3_dleafbrushes[0] ) );
+
+ // brushes
+ Q3_SwapBlock( (int *)q3_dbrushes, q3_numbrushes * sizeof( q3_dbrushes[0] ) );
+
+ // brushsides
+ Q3_SwapBlock( (int *)q3_dbrushsides, q3_numbrushsides * sizeof( q3_dbrushsides[0] ) );
+
+ // vis
+ ((int *)&q3_visBytes)[0] = LittleLong( ((int *)&q3_visBytes)[0] );
+ ((int *)&q3_visBytes)[1] = LittleLong( ((int *)&q3_visBytes)[1] );
+
+ // drawverts (don't swap colors )
+ for ( i = 0 ; i < q3_numDrawVerts ; i++ ) {
+ q3_drawVerts[i].lightmap[0] = LittleFloat( q3_drawVerts[i].lightmap[0] );
+ q3_drawVerts[i].lightmap[1] = LittleFloat( q3_drawVerts[i].lightmap[1] );
+ q3_drawVerts[i].st[0] = LittleFloat( q3_drawVerts[i].st[0] );
+ q3_drawVerts[i].st[1] = LittleFloat( q3_drawVerts[i].st[1] );
+ q3_drawVerts[i].xyz[0] = LittleFloat( q3_drawVerts[i].xyz[0] );
+ q3_drawVerts[i].xyz[1] = LittleFloat( q3_drawVerts[i].xyz[1] );
+ q3_drawVerts[i].xyz[2] = LittleFloat( q3_drawVerts[i].xyz[2] );
+ q3_drawVerts[i].normal[0] = LittleFloat( q3_drawVerts[i].normal[0] );
+ q3_drawVerts[i].normal[1] = LittleFloat( q3_drawVerts[i].normal[1] );
+ q3_drawVerts[i].normal[2] = LittleFloat( q3_drawVerts[i].normal[2] );
+ }
+
+ // drawindexes
+ Q3_SwapBlock( (int *)q3_drawIndexes, q3_numDrawIndexes * sizeof( q3_drawIndexes[0] ) );
+
+ // drawsurfs
+ Q3_SwapBlock( (int *)q3_drawSurfaces, q3_numDrawSurfaces * sizeof( q3_drawSurfaces[0] ) );
+
+ // fogs
+ for ( i = 0 ; i < q3_numFogs ; i++ ) {
+ q3_dfogs[i].brushNum = LittleLong( q3_dfogs[i].brushNum );
+ }
+}
+
+
+
+/*
+=============
+Q3_CopyLump
+=============
+*/
+int Q3_CopyLump( q3_dheader_t *header, int lump, void **dest, int size ) {
+ int length, ofs;
+
+ length = header->lumps[lump].filelen;
+ ofs = header->lumps[lump].fileofs;
+
+ if ( length % size ) {
+ Error ("Q3_LoadBSPFile: odd lump size");
+ }
+
+ *dest = GetMemory(length);
+
+ memcpy( *dest, (byte *)header + ofs, length );
+
+ return length / size;
+}
+
+/*
+=============
+CountTriangles
+=============
+*/
+void CountTriangles( void ) {
+ int i, numTris, numPatchTris;
+ q3_dsurface_t *surface;
+
+ numTris = numPatchTris = 0;
+ for ( i = 0; i < q3_numDrawSurfaces; i++ ) {
+ surface = &q3_drawSurfaces[i];
+
+ numTris += surface->numIndexes / 3;
+
+ if ( surface->patchWidth ) {
+ numPatchTris += surface->patchWidth * surface->patchHeight * 2;
+ }
+ }
+
+ Log_Print( "%6d triangles\n", numTris );
+ Log_Print( "%6d patch tris\n", numPatchTris );
+}
+
+/*
+=============
+Q3_LoadBSPFile
+=============
+*/
+void Q3_LoadBSPFile(struct quakefile_s *qf)
+{
+ q3_dheader_t *header;
+
+ // load the file header
+ //LoadFile(filename, (void **)&header, offset, length);
+ //
+ LoadQuakeFile(qf, (void **)&header);
+
+ // swap the header
+ Q3_SwapBlock( (int *)header, sizeof(*header) );
+
+ if ( header->ident != Q3_BSP_IDENT ) {
+ Error( "%s is not a IBSP file", qf->filename );
+ }
+ if ( header->version != Q3_BSP_VERSION ) {
+ Error( "%s is version %i, not %i", qf->filename, header->version, Q3_BSP_VERSION );
+ }
+
+ q3_numShaders = Q3_CopyLump( header, Q3_LUMP_SHADERS, (void *) &q3_dshaders, sizeof(q3_dshader_t) );
+ q3_nummodels = Q3_CopyLump( header, Q3_LUMP_MODELS, (void *) &q3_dmodels, sizeof(q3_dmodel_t) );
+ q3_numplanes = Q3_CopyLump( header, Q3_LUMP_PLANES, (void *) &q3_dplanes, sizeof(q3_dplane_t) );
+ q3_numleafs = Q3_CopyLump( header, Q3_LUMP_LEAFS, (void *) &q3_dleafs, sizeof(q3_dleaf_t) );
+ q3_numnodes = Q3_CopyLump( header, Q3_LUMP_NODES, (void *) &q3_dnodes, sizeof(q3_dnode_t) );
+ q3_numleafsurfaces = Q3_CopyLump( header, Q3_LUMP_LEAFSURFACES, (void *) &q3_dleafsurfaces, sizeof(q3_dleafsurfaces[0]) );
+ q3_numleafbrushes = Q3_CopyLump( header, Q3_LUMP_LEAFBRUSHES, (void *) &q3_dleafbrushes, sizeof(q3_dleafbrushes[0]) );
+ q3_numbrushes = Q3_CopyLump( header, Q3_LUMP_BRUSHES, (void *) &q3_dbrushes, sizeof(q3_dbrush_t) );
+ q3_numbrushsides = Q3_CopyLump( header, Q3_LUMP_BRUSHSIDES, (void *) &q3_dbrushsides, sizeof(q3_dbrushside_t) );
+ q3_numDrawVerts = Q3_CopyLump( header, Q3_LUMP_DRAWVERTS, (void *) &q3_drawVerts, sizeof(q3_drawVert_t) );
+ q3_numDrawSurfaces = Q3_CopyLump( header, Q3_LUMP_SURFACES, (void *) &q3_drawSurfaces, sizeof(q3_dsurface_t) );
+ q3_numFogs = Q3_CopyLump( header, Q3_LUMP_FOGS, (void *) &q3_dfogs, sizeof(q3_dfog_t) );
+ q3_numDrawIndexes = Q3_CopyLump( header, Q3_LUMP_DRAWINDEXES, (void *) &q3_drawIndexes, sizeof(q3_drawIndexes[0]) );
+
+ q3_numVisBytes = Q3_CopyLump( header, Q3_LUMP_VISIBILITY, (void *) &q3_visBytes, 1 );
+ q3_numLightBytes = Q3_CopyLump( header, Q3_LUMP_LIGHTMAPS, (void *) &q3_lightBytes, 1 );
+ q3_entdatasize = Q3_CopyLump( header, Q3_LUMP_ENTITIES, (void *) &q3_dentdata, 1);
+
+ q3_numGridPoints = Q3_CopyLump( header, Q3_LUMP_LIGHTGRID, (void *) &q3_gridData, 8 );
+
+ CountTriangles();
+
+ FreeMemory( header ); // everything has been copied out
+
+ // swap everything
+ Q3_SwapBSPFile();
+
+ Q3_FindVisibleBrushSides();
+
+ //Q3_PrintBSPFileSizes();
+}
+
+
+//============================================================================
+
+/*
+=============
+Q3_AddLump
+=============
+*/
+void Q3_AddLump( FILE *bspfile, q3_dheader_t *header, int lumpnum, void *data, int len ) {
+ q3_lump_t *lump;
+
+ lump = &header->lumps[lumpnum];
+
+ lump->fileofs = LittleLong( ftell(bspfile) );
+ lump->filelen = LittleLong( len );
+ SafeWrite( bspfile, data, (len+3)&~3 );
+}
+
+/*
+=============
+Q3_WriteBSPFile
+
+Swaps the bsp file in place, so it should not be referenced again
+=============
+*/
+void Q3_WriteBSPFile( char *filename )
+{
+ q3_dheader_t outheader, *header;
+ FILE *bspfile;
+
+ header = &outheader;
+ memset( header, 0, sizeof(q3_dheader_t) );
+
+ Q3_SwapBSPFile();
+
+ header->ident = LittleLong( Q3_BSP_IDENT );
+ header->version = LittleLong( Q3_BSP_VERSION );
+
+ bspfile = SafeOpenWrite( filename );
+ SafeWrite( bspfile, header, sizeof(q3_dheader_t) ); // overwritten later
+
+ Q3_AddLump( bspfile, header, Q3_LUMP_SHADERS, q3_dshaders, q3_numShaders*sizeof(q3_dshader_t) );
+ Q3_AddLump( bspfile, header, Q3_LUMP_PLANES, q3_dplanes, q3_numplanes*sizeof(q3_dplane_t) );
+ Q3_AddLump( bspfile, header, Q3_LUMP_LEAFS, q3_dleafs, q3_numleafs*sizeof(q3_dleaf_t) );
+ Q3_AddLump( bspfile, header, Q3_LUMP_NODES, q3_dnodes, q3_numnodes*sizeof(q3_dnode_t) );
+ Q3_AddLump( bspfile, header, Q3_LUMP_BRUSHES, q3_dbrushes, q3_numbrushes*sizeof(q3_dbrush_t) );
+ Q3_AddLump( bspfile, header, Q3_LUMP_BRUSHSIDES, q3_dbrushsides, q3_numbrushsides*sizeof(q3_dbrushside_t) );
+ Q3_AddLump( bspfile, header, Q3_LUMP_LEAFSURFACES, q3_dleafsurfaces, q3_numleafsurfaces*sizeof(q3_dleafsurfaces[0]) );
+ Q3_AddLump( bspfile, header, Q3_LUMP_LEAFBRUSHES, q3_dleafbrushes, q3_numleafbrushes*sizeof(q3_dleafbrushes[0]) );
+ Q3_AddLump( bspfile, header, Q3_LUMP_MODELS, q3_dmodels, q3_nummodels*sizeof(q3_dmodel_t) );
+ Q3_AddLump( bspfile, header, Q3_LUMP_DRAWVERTS, q3_drawVerts, q3_numDrawVerts*sizeof(q3_drawVert_t) );
+ Q3_AddLump( bspfile, header, Q3_LUMP_SURFACES, q3_drawSurfaces, q3_numDrawSurfaces*sizeof(q3_dsurface_t) );
+ Q3_AddLump( bspfile, header, Q3_LUMP_VISIBILITY, q3_visBytes, q3_numVisBytes );
+ Q3_AddLump( bspfile, header, Q3_LUMP_LIGHTMAPS, q3_lightBytes, q3_numLightBytes );
+ Q3_AddLump( bspfile, header, Q3_LUMP_LIGHTGRID, q3_gridData, 8 * q3_numGridPoints );
+ Q3_AddLump( bspfile, header, Q3_LUMP_ENTITIES, q3_dentdata, q3_entdatasize );
+ Q3_AddLump( bspfile, header, Q3_LUMP_FOGS, q3_dfogs, q3_numFogs * sizeof(q3_dfog_t) );
+ Q3_AddLump( bspfile, header, Q3_LUMP_DRAWINDEXES, q3_drawIndexes, q3_numDrawIndexes * sizeof(q3_drawIndexes[0]) );
+
+ fseek (bspfile, 0, SEEK_SET);
+ SafeWrite (bspfile, header, sizeof(q3_dheader_t));
+ fclose (bspfile);
+}
+
+//============================================================================
+
+/*
+=============
+Q3_PrintBSPFileSizes
+
+Dumps info about current file
+=============
+*/
+void Q3_PrintBSPFileSizes( void )
+{
+ if ( !num_entities )
+ {
+ Q3_ParseEntities();
+ }
+
+ Log_Print ("%6i models %7i\n"
+ ,q3_nummodels, (int)(q3_nummodels*sizeof(q3_dmodel_t)));
+ Log_Print ("%6i shaders %7i\n"
+ ,q3_numShaders, (int)(q3_numShaders*sizeof(q3_dshader_t)));
+ Log_Print ("%6i brushes %7i\n"
+ ,q3_numbrushes, (int)(q3_numbrushes*sizeof(q3_dbrush_t)));
+ Log_Print ("%6i brushsides %7i\n"
+ ,q3_numbrushsides, (int)(q3_numbrushsides*sizeof(q3_dbrushside_t)));
+ Log_Print ("%6i fogs %7i\n"
+ ,q3_numFogs, (int)(q3_numFogs*sizeof(q3_dfog_t)));
+ Log_Print ("%6i planes %7i\n"
+ ,q3_numplanes, (int)(q3_numplanes*sizeof(q3_dplane_t)));
+ Log_Print ("%6i entdata %7i\n", num_entities, q3_entdatasize);
+
+ Log_Print ("\n");
+
+ Log_Print ("%6i nodes %7i\n"
+ ,q3_numnodes, (int)(q3_numnodes*sizeof(q3_dnode_t)));
+ Log_Print ("%6i leafs %7i\n"
+ ,q3_numleafs, (int)(q3_numleafs*sizeof(q3_dleaf_t)));
+ Log_Print ("%6i leafsurfaces %7i\n"
+ ,q3_numleafsurfaces, (int)(q3_numleafsurfaces*sizeof(q3_dleafsurfaces[0])));
+ Log_Print ("%6i leafbrushes %7i\n"
+ ,q3_numleafbrushes, (int)(q3_numleafbrushes*sizeof(q3_dleafbrushes[0])));
+ Log_Print ("%6i drawverts %7i\n"
+ ,q3_numDrawVerts, (int)(q3_numDrawVerts*sizeof(q3_drawVerts[0])));
+ Log_Print ("%6i drawindexes %7i\n"
+ ,q3_numDrawIndexes, (int)(q3_numDrawIndexes*sizeof(q3_drawIndexes[0])));
+ Log_Print ("%6i drawsurfaces %7i\n"
+ ,q3_numDrawSurfaces, (int)(q3_numDrawSurfaces*sizeof(q3_drawSurfaces[0])));
+
+ Log_Print ("%6i lightmaps %7i\n"
+ ,q3_numLightBytes / (LIGHTMAP_WIDTH*LIGHTMAP_HEIGHT*3), q3_numLightBytes );
+ Log_Print (" visibility %7i\n"
+ , q3_numVisBytes );
+}
+
+/*
+================
+Q3_ParseEntities
+
+Parses the q3_dentdata string into entities
+================
+*/
+void Q3_ParseEntities (void)
+{
+ script_t *script;
+
+ num_entities = 0;
+ script = LoadScriptMemory(q3_dentdata, q3_entdatasize, "*Quake3 bsp file");
+ SetScriptFlags(script, SCFL_NOSTRINGWHITESPACES |
+ SCFL_NOSTRINGESCAPECHARS);
+
+ while(ParseEntity(script))
+ {
+ } //end while
+
+ FreeScript(script);
+} //end of the function Q3_ParseEntities
+
+
+/*
+================
+Q3_UnparseEntities
+
+Generates the q3_dentdata string from all the entities
+================
+*/
+void Q3_UnparseEntities (void)
+{
+ char *buf, *end;
+ epair_t *ep;
+ char line[2048];
+ int i;
+
+ buf = q3_dentdata;
+ end = buf;
+ *end = 0;
+
+ for (i=0 ; i<num_entities ; i++)
+ {
+ ep = entities[i].epairs;
+ if (!ep)
+ continue; // ent got removed
+
+ strcat (end,"{\n");
+ end += 2;
+
+ for (ep = entities[i].epairs ; ep ; ep=ep->next)
+ {
+ sprintf (line, "\"%s\" \"%s\"\n", ep->key, ep->value);
+ strcat (end, line);
+ end += strlen(line);
+ }
+ strcat (end,"}\n");
+ end += 2;
+
+ if (end > buf + Q3_MAX_MAP_ENTSTRING)
+ Error ("Entity text too long");
+ }
+ q3_entdatasize = end - buf + 1;
+} //end of the function Q3_UnparseEntities
+
+
diff --git a/code/bspc/l_bsp_q3.h b/code/bspc/l_bsp_q3.h
new file mode 100755
index 0000000..6ac175c
--- /dev/null
+++ b/code/bspc/l_bsp_q3.h
@@ -0,0 +1,81 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "q3files.h"
+//#include "surfaceflags.h"
+
+extern int q3_nummodels;
+extern q3_dmodel_t *q3_dmodels;//[MAX_MAP_MODELS];
+
+extern int q3_numShaders;
+extern q3_dshader_t *q3_dshaders;//[Q3_MAX_MAP_SHADERS];
+
+extern int q3_entdatasize;
+extern char *q3_dentdata;//[Q3_MAX_MAP_ENTSTRING];
+
+extern int q3_numleafs;
+extern q3_dleaf_t *q3_dleafs;//[Q3_MAX_MAP_LEAFS];
+
+extern int q3_numplanes;
+extern q3_dplane_t *q3_dplanes;//[Q3_MAX_MAP_PLANES];
+
+extern int q3_numnodes;
+extern q3_dnode_t *q3_dnodes;//[Q3_MAX_MAP_NODES];
+
+extern int q3_numleafsurfaces;
+extern int *q3_dleafsurfaces;//[Q3_MAX_MAP_LEAFFACES];
+
+extern int q3_numleafbrushes;
+extern int *q3_dleafbrushes;//[Q3_MAX_MAP_LEAFBRUSHES];
+
+extern int q3_numbrushes;
+extern q3_dbrush_t *q3_dbrushes;//[Q3_MAX_MAP_BRUSHES];
+
+extern int q3_numbrushsides;
+extern q3_dbrushside_t *q3_dbrushsides;//[Q3_MAX_MAP_BRUSHSIDES];
+
+extern int q3_numLightBytes;
+extern byte *q3_lightBytes;//[Q3_MAX_MAP_LIGHTING];
+
+extern int q3_numGridPoints;
+extern byte *q3_gridData;//[Q3_MAX_MAP_LIGHTGRID];
+
+extern int q3_numVisBytes;
+extern byte *q3_visBytes;//[Q3_MAX_MAP_VISIBILITY];
+
+extern int q3_numDrawVerts;
+extern q3_drawVert_t *q3_drawVerts;//[Q3_MAX_MAP_DRAW_VERTS];
+
+extern int q3_numDrawIndexes;
+extern int *q3_drawIndexes;//[Q3_MAX_MAP_DRAW_INDEXES];
+
+extern int q3_numDrawSurfaces;
+extern q3_dsurface_t *q3_drawSurfaces;//[Q3_MAX_MAP_DRAW_SURFS];
+
+extern int q3_numFogs;
+extern q3_dfog_t *q3_dfogs;//[Q3_MAX_MAP_FOGS];
+
+extern char q3_dbrushsidetextured[Q3_MAX_MAP_BRUSHSIDES];
+
+void Q3_LoadBSPFile(struct quakefile_s *qf);
+void Q3_FreeMaxBSP(void);
+void Q3_ParseEntities (void);
diff --git a/code/bspc/l_bsp_sin.c b/code/bspc/l_bsp_sin.c
new file mode 100755
index 0000000..de51528
--- /dev/null
+++ b/code/bspc/l_bsp_sin.c
@@ -0,0 +1,1186 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "l_cmd.h"
+#include "l_math.h"
+#include "l_mem.h"
+#include "l_log.h"
+#include "l_poly.h"
+#include "../botlib/l_script.h"
+#include "l_bsp_ent.h"
+#include "l_bsp_sin.h"
+
+void GetLeafNums (void);
+
+//=============================================================================
+
+int sin_nummodels;
+sin_dmodel_t *sin_dmodels;//[SIN_MAX_MAP_MODELS];
+
+int sin_visdatasize;
+byte *sin_dvisdata;//[SIN_MAX_MAP_VISIBILITY];
+sin_dvis_t *sin_dvis;// = (sin_dvis_t *)sin_sin_dvisdata;
+
+int sin_lightdatasize;
+byte *sin_dlightdata;//[SIN_MAX_MAP_LIGHTING];
+
+int sin_entdatasize;
+char *sin_dentdata;//[SIN_MAX_MAP_ENTSTRING];
+
+int sin_numleafs;
+sin_dleaf_t *sin_dleafs;//[SIN_MAX_MAP_LEAFS];
+
+int sin_numplanes;
+sin_dplane_t *sin_dplanes;//[SIN_MAX_MAP_PLANES];
+
+int sin_numvertexes;
+sin_dvertex_t *sin_dvertexes;//[SIN_MAX_MAP_VERTS];
+
+int sin_numnodes;
+sin_dnode_t *sin_dnodes;//[SIN_MAX_MAP_NODES];
+
+int sin_numtexinfo;
+sin_texinfo_t *sin_texinfo;//[SIN_MAX_MAP_sin_texinfo];
+
+int sin_numfaces;
+sin_dface_t *sin_dfaces;//[SIN_MAX_MAP_FACES];
+
+int sin_numedges;
+sin_dedge_t *sin_dedges;//[SIN_MAX_MAP_EDGES];
+
+int sin_numleaffaces;
+unsigned short *sin_dleaffaces;//[SIN_MAX_MAP_LEAFFACES];
+
+int sin_numleafbrushes;
+unsigned short *sin_dleafbrushes;//[SIN_MAX_MAP_LEAFBRUSHES];
+
+int sin_numsurfedges;
+int *sin_dsurfedges;//[SIN_MAX_MAP_SURFEDGES];
+
+int sin_numbrushes;
+sin_dbrush_t *sin_dbrushes;//[SIN_MAX_MAP_BRUSHES];
+
+int sin_numbrushsides;
+sin_dbrushside_t *sin_dbrushsides;//[SIN_MAX_MAP_BRUSHSIDES];
+
+int sin_numareas;
+sin_darea_t *sin_dareas;//[SIN_MAX_MAP_AREAS];
+
+int sin_numareaportals;
+sin_dareaportal_t *sin_dareaportals;//[SIN_MAX_MAP_AREAPORTALS];
+
+int sin_numlightinfo;
+sin_lightvalue_t *sin_lightinfo;//[SIN_MAX_MAP_LIGHTINFO];
+
+byte sin_dpop[256];
+
+char sin_dbrushsidetextured[SIN_MAX_MAP_BRUSHSIDES];
+
+int sin_bspallocated = false;
+int sin_allocatedbspmem = 0;
+
+void Sin_AllocMaxBSP(void)
+{
+ //models
+ sin_nummodels = 0;
+ sin_dmodels = (sin_dmodel_t *) GetClearedMemory(SIN_MAX_MAP_MODELS * sizeof(sin_dmodel_t));
+ sin_allocatedbspmem += SIN_MAX_MAP_MODELS * sizeof(sin_dmodel_t);
+ //vis data
+ sin_visdatasize = 0;
+ sin_dvisdata = (byte *) GetClearedMemory(SIN_MAX_MAP_VISIBILITY * sizeof(byte));
+ sin_dvis = (sin_dvis_t *) sin_dvisdata;
+ sin_allocatedbspmem += SIN_MAX_MAP_VISIBILITY * sizeof(byte);
+ //light data
+ sin_lightdatasize = 0;
+ sin_dlightdata = (byte *) GetClearedMemory(SIN_MAX_MAP_LIGHTING * sizeof(byte));
+ sin_allocatedbspmem += SIN_MAX_MAP_LIGHTING * sizeof(byte);
+ //entity data
+ sin_entdatasize = 0;
+ sin_dentdata = (char *) GetClearedMemory(SIN_MAX_MAP_ENTSTRING * sizeof(char));
+ sin_allocatedbspmem += SIN_MAX_MAP_ENTSTRING * sizeof(char);
+ //leafs
+ sin_numleafs = 0;
+ sin_dleafs = (sin_dleaf_t *) GetClearedMemory(SIN_MAX_MAP_LEAFS * sizeof(sin_dleaf_t));
+ sin_allocatedbspmem += SIN_MAX_MAP_LEAFS * sizeof(sin_dleaf_t);
+ //planes
+ sin_numplanes = 0;
+ sin_dplanes = (sin_dplane_t *) GetClearedMemory(SIN_MAX_MAP_PLANES * sizeof(sin_dplane_t));
+ sin_allocatedbspmem += SIN_MAX_MAP_PLANES * sizeof(sin_dplane_t);
+ //vertexes
+ sin_numvertexes = 0;
+ sin_dvertexes = (sin_dvertex_t *) GetClearedMemory(SIN_MAX_MAP_VERTS * sizeof(sin_dvertex_t));
+ sin_allocatedbspmem += SIN_MAX_MAP_VERTS * sizeof(sin_dvertex_t);
+ //nodes
+ sin_numnodes = 0;
+ sin_dnodes = (sin_dnode_t *) GetClearedMemory(SIN_MAX_MAP_NODES * sizeof(sin_dnode_t));
+ sin_allocatedbspmem += SIN_MAX_MAP_NODES * sizeof(sin_dnode_t);
+ //texture info
+ sin_numtexinfo = 0;
+ sin_texinfo = (sin_texinfo_t *) GetClearedMemory(SIN_MAX_MAP_TEXINFO * sizeof(sin_texinfo_t));
+ sin_allocatedbspmem += SIN_MAX_MAP_TEXINFO * sizeof(sin_texinfo_t);
+ //faces
+ sin_numfaces = 0;
+ sin_dfaces = (sin_dface_t *) GetClearedMemory(SIN_MAX_MAP_FACES * sizeof(sin_dface_t));
+ sin_allocatedbspmem += SIN_MAX_MAP_FACES * sizeof(sin_dface_t);
+ //edges
+ sin_numedges = 0;
+ sin_dedges = (sin_dedge_t *) GetClearedMemory(SIN_MAX_MAP_EDGES * sizeof(sin_dedge_t));
+ sin_allocatedbspmem += SIN_MAX_MAP_EDGES * sizeof(sin_dedge_t);
+ //leaf faces
+ sin_numleaffaces = 0;
+ sin_dleaffaces = (unsigned short *) GetClearedMemory(SIN_MAX_MAP_LEAFFACES * sizeof(unsigned short));
+ sin_allocatedbspmem += SIN_MAX_MAP_LEAFFACES * sizeof(unsigned short);
+ //leaf brushes
+ sin_numleafbrushes = 0;
+ sin_dleafbrushes = (unsigned short *) GetClearedMemory(SIN_MAX_MAP_LEAFBRUSHES * sizeof(unsigned short));
+ sin_allocatedbspmem += SIN_MAX_MAP_LEAFBRUSHES * sizeof(unsigned short);
+ //surface edges
+ sin_numsurfedges = 0;
+ sin_dsurfedges = (int *) GetClearedMemory(SIN_MAX_MAP_SURFEDGES * sizeof(int));
+ sin_allocatedbspmem += SIN_MAX_MAP_SURFEDGES * sizeof(int);
+ //brushes
+ sin_numbrushes = 0;
+ sin_dbrushes = (sin_dbrush_t *) GetClearedMemory(SIN_MAX_MAP_BRUSHES * sizeof(sin_dbrush_t));
+ sin_allocatedbspmem += SIN_MAX_MAP_BRUSHES * sizeof(sin_dbrush_t);
+ //brushsides
+ sin_numbrushsides = 0;
+ sin_dbrushsides = (sin_dbrushside_t *) GetClearedMemory(SIN_MAX_MAP_BRUSHSIDES * sizeof(sin_dbrushside_t));
+ sin_allocatedbspmem += SIN_MAX_MAP_BRUSHSIDES * sizeof(sin_dbrushside_t);
+ //areas
+ sin_numareas = 0;
+ sin_dareas = (sin_darea_t *) GetClearedMemory(SIN_MAX_MAP_AREAS * sizeof(sin_darea_t));
+ sin_allocatedbspmem += SIN_MAX_MAP_AREAS * sizeof(sin_darea_t);
+ //area portals
+ sin_numareaportals = 0;
+ sin_dareaportals = (sin_dareaportal_t *) GetClearedMemory(SIN_MAX_MAP_AREAPORTALS * sizeof(sin_dareaportal_t));
+ sin_allocatedbspmem += SIN_MAX_MAP_AREAPORTALS * sizeof(sin_dareaportal_t);
+ //light info
+ sin_numlightinfo = 0;
+ sin_lightinfo = (sin_lightvalue_t *) GetClearedMemory(SIN_MAX_MAP_LIGHTINFO * sizeof(sin_lightvalue_t));
+ sin_allocatedbspmem += SIN_MAX_MAP_LIGHTINFO * sizeof(sin_lightvalue_t);
+ //print allocated memory
+ Log_Print("allocated ");
+ PrintMemorySize(sin_allocatedbspmem);
+ Log_Print(" of BSP memory\n");
+} //end of the function Sin_AllocMaxBSP
+
+void Sin_FreeMaxBSP(void)
+{
+ //models
+ sin_nummodels = 0;
+ FreeMemory(sin_dmodels);
+ sin_dmodels = NULL;
+ //vis data
+ sin_visdatasize = 0;
+ FreeMemory(sin_dvisdata);
+ sin_dvisdata = NULL;
+ sin_dvis = NULL;
+ //light data
+ sin_lightdatasize = 0;
+ FreeMemory(sin_dlightdata);
+ sin_dlightdata = NULL;
+ //entity data
+ sin_entdatasize = 0;
+ FreeMemory(sin_dentdata);
+ sin_dentdata = NULL;
+ //leafs
+ sin_numleafs = 0;
+ FreeMemory(sin_dleafs);
+ sin_dleafs = NULL;
+ //planes
+ sin_numplanes = 0;
+ FreeMemory(sin_dplanes);
+ sin_dplanes = NULL;
+ //vertexes
+ sin_numvertexes = 0;
+ FreeMemory(sin_dvertexes);
+ sin_dvertexes = NULL;
+ //nodes
+ sin_numnodes = 0;
+ FreeMemory(sin_dnodes);
+ sin_dnodes = NULL;
+ //texture info
+ sin_numtexinfo = 0;
+ FreeMemory(sin_texinfo);
+ sin_texinfo = NULL;
+ //faces
+ sin_numfaces = 0;
+ FreeMemory(sin_dfaces);
+ sin_dfaces = NULL;
+ //edges
+ sin_numedges = 0;
+ FreeMemory(sin_dedges);
+ sin_dedges = NULL;
+ //leaf faces
+ sin_numleaffaces = 0;
+ FreeMemory(sin_dleaffaces);
+ sin_dleaffaces = NULL;
+ //leaf brushes
+ sin_numleafbrushes = 0;
+ FreeMemory(sin_dleafbrushes);
+ sin_dleafbrushes = NULL;
+ //surface edges
+ sin_numsurfedges = 0;
+ FreeMemory(sin_dsurfedges);
+ sin_dsurfedges = NULL;
+ //brushes
+ sin_numbrushes = 0;
+ FreeMemory(sin_dbrushes);
+ sin_dbrushes = NULL;
+ //brushsides
+ sin_numbrushsides = 0;
+ FreeMemory(sin_dbrushsides);
+ sin_dbrushsides = NULL;
+ //areas
+ sin_numareas = 0;
+ FreeMemory(sin_dareas);
+ sin_dareas = NULL;
+ //area portals
+ sin_numareaportals = 0;
+ FreeMemory(sin_dareaportals);
+ sin_dareaportals = NULL;
+ //light info
+ sin_numlightinfo = 0;
+ FreeMemory(sin_lightinfo);
+ sin_lightinfo = NULL;
+ //
+ Log_Print("freed ");
+ PrintMemorySize(sin_allocatedbspmem);
+ Log_Print(" of BSP memory\n");
+ sin_allocatedbspmem = 0;
+} //end of the function Sin_FreeMaxBSP
+
+#define WCONVEX_EPSILON 0.5
+
+//===========================================================================
+// returns the amount the face and the winding overlap
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float Sin_FaceOnWinding(sin_dface_t *face, winding_t *winding)
+{
+ int i, edgenum, side;
+ float dist, area;
+ sin_dplane_t plane;
+ vec_t *v1, *v2;
+ vec3_t normal, edgevec;
+ winding_t *w;
+
+ //
+ w = CopyWinding(winding);
+ memcpy(&plane, &sin_dplanes[face->planenum], sizeof(sin_dplane_t));
+ //check on which side of the plane the face is
+ if (face->side)
+ {
+ VectorNegate(plane.normal, plane.normal);
+ plane.dist = -plane.dist;
+ } //end if
+ for (i = 0; i < face->numedges && w; i++)
+ {
+ //get the first and second vertex of the edge
+ edgenum = sin_dsurfedges[face->firstedge + i];
+ side = edgenum > 0;
+ //if the face plane is flipped
+ v1 = sin_dvertexes[sin_dedges[abs(edgenum)].v[side]].point;
+ v2 = sin_dvertexes[sin_dedges[abs(edgenum)].v[!side]].point;
+ //create a plane through the edge vector, orthogonal to the face plane
+ //and with the normal vector pointing out of the face
+ VectorSubtract(v1, v2, edgevec);
+ CrossProduct(edgevec, plane.normal, normal);
+ VectorNormalize(normal);
+ dist = DotProduct(normal, v1);
+ //
+ ChopWindingInPlace(&w, normal, dist, 0.9); //CLIP_EPSILON
+ } //end for
+ if (w)
+ {
+ area = WindingArea(w);
+ FreeWinding(w);
+ return area;
+ } //end if
+ return 0;
+} //end of the function Sin_FaceOnWinding
+//===========================================================================
+// creates a winding for the given brush side on the given brush
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+winding_t *Sin_BrushSideWinding(sin_dbrush_t *brush, sin_dbrushside_t *baseside)
+{
+ int i;
+ sin_dplane_t *baseplane, *plane;
+ sin_dbrushside_t *side;
+ winding_t *w;
+
+ //create a winding for the brush side with the given planenumber
+ baseplane = &sin_dplanes[baseside->planenum];
+ w = BaseWindingForPlane(baseplane->normal, baseplane->dist);
+ for (i = 0; i < brush->numsides && w; i++)
+ {
+ side = &sin_dbrushsides[brush->firstside + i];
+ //don't chop with the base plane
+ if (side->planenum == baseside->planenum) continue;
+ //also don't use planes that are almost equal
+ plane = &sin_dplanes[side->planenum];
+ if (DotProduct(baseplane->normal, plane->normal) > 0.999
+ && fabs(baseplane->dist - plane->dist) < 0.01) continue;
+ //
+ plane = &sin_dplanes[side->planenum^1];
+ ChopWindingInPlace(&w, plane->normal, plane->dist, 0); //CLIP_EPSILON);
+ } //end for
+ return w;
+} //end of the function Sin_BrushSideWinding
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int Sin_HintSkipBrush(sin_dbrush_t *brush)
+{
+ int j;
+ sin_dbrushside_t *brushside;
+
+ for (j = 0; j < brush->numsides; j++)
+ {
+ brushside = &sin_dbrushsides[brush->firstside + j];
+ if (brushside->texinfo > 0)
+ {
+ if (sin_texinfo[brushside->texinfo].flags & (SURF_SKIP|SURF_HINT))
+ {
+ return true;
+ } //end if
+ } //end if
+ } //end for
+ return false;
+} //end of the function Sin_HintSkipBrush
+//===========================================================================
+// fix screwed brush texture references
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean WindingIsTiny(winding_t *w);
+
+void Sin_FixTextureReferences(void)
+{
+ int i, j, k, we;
+ sin_dbrushside_t *brushside;
+ sin_dbrush_t *brush;
+ sin_dface_t *face;
+ winding_t *w;
+
+ memset(sin_dbrushsidetextured, false, SIN_MAX_MAP_BRUSHSIDES);
+ //go over all the brushes
+ for (i = 0; i < sin_numbrushes; i++)
+ {
+ brush = &sin_dbrushes[i];
+ //hint brushes are not textured
+ if (Sin_HintSkipBrush(brush)) continue;
+ //go over all the sides of the brush
+ for (j = 0; j < brush->numsides; j++)
+ {
+ brushside = &sin_dbrushsides[brush->firstside + j];
+ //
+ w = Sin_BrushSideWinding(brush, brushside);
+ if (!w)
+ {
+ sin_dbrushsidetextured[brush->firstside + j] = true;
+ continue;
+ } //end if
+ else
+ {
+ //RemoveEqualPoints(w, 0.2);
+ if (WindingIsTiny(w))
+ {
+ FreeWinding(w);
+ sin_dbrushsidetextured[brush->firstside + j] = true;
+ continue;
+ } //end if
+ else
+ {
+ we = WindingError(w);
+ if (we == WE_NOTENOUGHPOINTS
+ || we == WE_SMALLAREA
+ || we == WE_POINTBOGUSRANGE
+// || we == WE_NONCONVEX
+ )
+ {
+ FreeWinding(w);
+ sin_dbrushsidetextured[brush->firstside + j] = true;
+ continue;
+ } //end if
+ } //end else
+ } //end else
+ if (WindingArea(w) < 20)
+ {
+ sin_dbrushsidetextured[brush->firstside + j] = true;
+ } //end if
+ //find a face for texturing this brush
+ for (k = 0; k < sin_numfaces; k++)
+ {
+ face = &sin_dfaces[k];
+ //if the face is in the same plane as the brush side
+ if ((face->planenum&~1) != (brushside->planenum&~1)) continue;
+ //if the face is partly or totally on the brush side
+ if (Sin_FaceOnWinding(face, w))
+ {
+ brushside->texinfo = face->texinfo;
+ sin_dbrushsidetextured[brush->firstside + j] = true;
+ break;
+ } //end if
+ } //end for
+ FreeWinding(w);
+ } //end for
+ } //end for
+} //end of the function Sin_FixTextureReferences*/
+
+/*
+===============
+CompressVis
+
+===============
+*/
+int Sin_CompressVis (byte *vis, byte *dest)
+{
+ int j;
+ int rep;
+ int visrow;
+ byte *dest_p;
+
+ dest_p = dest;
+// visrow = (r_numvisleafs + 7)>>3;
+ visrow = (sin_dvis->numclusters + 7)>>3;
+
+ for (j=0 ; j<visrow ; j++)
+ {
+ *dest_p++ = vis[j];
+ if (vis[j])
+ continue;
+
+ rep = 1;
+ for ( j++; j<visrow ; j++)
+ if (vis[j] || rep == 255)
+ break;
+ else
+ rep++;
+ *dest_p++ = rep;
+ j--;
+ }
+
+ return dest_p - dest;
+} //end of the function Sin_CompressVis
+
+
+/*
+===================
+DecompressVis
+===================
+*/
+void Sin_DecompressVis (byte *in, byte *decompressed)
+{
+ int c;
+ byte *out;
+ int row;
+
+// row = (r_numvisleafs+7)>>3;
+ row = (sin_dvis->numclusters+7)>>3;
+ out = decompressed;
+
+ do
+ {
+ if (*in)
+ {
+ *out++ = *in++;
+ continue;
+ }
+
+ c = in[1];
+ if (!c)
+ Error ("DecompressVis: 0 repeat");
+ in += 2;
+ while (c)
+ {
+ *out++ = 0;
+ c--;
+ }
+ } while (out - decompressed < row);
+} //end of the function Sin_DecompressVis
+
+//=============================================================================
+
+/*
+=============
+Sin_SwapBSPFile
+
+Byte swaps all data in a bsp file.
+=============
+*/
+void Sin_SwapBSPFile (qboolean todisk)
+{
+ int i, j;
+ sin_dmodel_t *d;
+
+
+// models
+ for (i=0 ; i<sin_nummodels ; i++)
+ {
+ d = &sin_dmodels[i];
+
+ d->firstface = LittleLong (d->firstface);
+ d->numfaces = LittleLong (d->numfaces);
+ d->headnode = LittleLong (d->headnode);
+
+ for (j=0 ; j<3 ; j++)
+ {
+ d->mins[j] = LittleFloat(d->mins[j]);
+ d->maxs[j] = LittleFloat(d->maxs[j]);
+ d->origin[j] = LittleFloat(d->origin[j]);
+ }
+ }
+
+//
+// vertexes
+//
+ for (i=0 ; i<sin_numvertexes ; i++)
+ {
+ for (j=0 ; j<3 ; j++)
+ sin_dvertexes[i].point[j] = LittleFloat (sin_dvertexes[i].point[j]);
+ }
+
+//
+// planes
+//
+ for (i=0 ; i<sin_numplanes ; i++)
+ {
+ for (j=0 ; j<3 ; j++)
+ sin_dplanes[i].normal[j] = LittleFloat (sin_dplanes[i].normal[j]);
+ sin_dplanes[i].dist = LittleFloat (sin_dplanes[i].dist);
+ sin_dplanes[i].type = LittleLong (sin_dplanes[i].type);
+ }
+
+//
+// sin_texinfos
+//
+ for (i = 0; i < sin_numtexinfo; i++)
+ {
+ for (j=0 ; j<8 ; j++)
+ sin_texinfo[i].vecs[0][j] = LittleFloat (sin_texinfo[i].vecs[0][j]);
+#ifdef SIN
+ sin_texinfo[i].trans_mag = LittleFloat( sin_texinfo[i].trans_mag );
+ sin_texinfo[i].trans_angle = LittleLong( sin_texinfo[i].trans_angle );
+ sin_texinfo[i].animtime = LittleFloat( sin_texinfo[i].animtime );
+ sin_texinfo[i].nonlit = LittleFloat( sin_texinfo[i].nonlit );
+ sin_texinfo[i].translucence = LittleFloat( sin_texinfo[i].translucence );
+ sin_texinfo[i].friction = LittleFloat( sin_texinfo[i].friction );
+ sin_texinfo[i].restitution = LittleFloat( sin_texinfo[i].restitution );
+ sin_texinfo[i].flags = LittleUnsigned (sin_texinfo[i].flags);
+#else
+ sin_texinfo[i].value = LittleLong (sin_texinfo[i].value);
+ sin_texinfo[i].flags = LittleLong (sin_texinfo[i].flags);
+#endif
+ sin_texinfo[i].nexttexinfo = LittleLong (sin_texinfo[i].nexttexinfo);
+ }
+
+#ifdef SIN
+//
+// lightinfos
+//
+ for (i = 0; i < sin_numlightinfo; i++)
+ {
+ for (j=0 ; j<3 ; j++)
+ {
+ sin_lightinfo[i].color[j] = LittleFloat (sin_lightinfo[i].color[j]);
+ }
+ sin_lightinfo[i].value = LittleLong (sin_lightinfo[i].value);
+ sin_lightinfo[i].direct = LittleFloat( sin_lightinfo[i].direct );
+ sin_lightinfo[i].directangle = LittleFloat( sin_lightinfo[i].directangle );
+ sin_lightinfo[i].directstyle = LittleFloat( sin_lightinfo[i].directstyle );
+ }
+#endif
+
+//
+// faces
+//
+ for (i=0 ; i<sin_numfaces ; i++)
+ {
+ sin_dfaces[i].texinfo = LittleShort (sin_dfaces[i].texinfo);
+#ifdef SIN
+ sin_dfaces[i].lightinfo = LittleLong (sin_dfaces[i].lightinfo);
+ sin_dfaces[i].planenum = LittleUnsignedShort (sin_dfaces[i].planenum);
+#else
+ sin_dfaces[i].planenum = LittleShort (sin_dfaces[i].planenum);
+#endif
+ sin_dfaces[i].side = LittleShort (sin_dfaces[i].side);
+ sin_dfaces[i].lightofs = LittleLong (sin_dfaces[i].lightofs);
+ sin_dfaces[i].firstedge = LittleLong (sin_dfaces[i].firstedge);
+ sin_dfaces[i].numedges = LittleShort (sin_dfaces[i].numedges);
+ }
+
+//
+// nodes
+//
+ for (i=0 ; i<sin_numnodes ; i++)
+ {
+ sin_dnodes[i].planenum = LittleLong (sin_dnodes[i].planenum);
+ for (j=0 ; j<3 ; j++)
+ {
+ sin_dnodes[i].mins[j] = LittleShort (sin_dnodes[i].mins[j]);
+ sin_dnodes[i].maxs[j] = LittleShort (sin_dnodes[i].maxs[j]);
+ }
+ sin_dnodes[i].children[0] = LittleLong (sin_dnodes[i].children[0]);
+ sin_dnodes[i].children[1] = LittleLong (sin_dnodes[i].children[1]);
+#ifdef SIN
+ sin_dnodes[i].firstface = LittleUnsignedShort (sin_dnodes[i].firstface);
+ sin_dnodes[i].numfaces = LittleUnsignedShort (sin_dnodes[i].numfaces);
+#else
+ sin_dnodes[i].firstface = LittleShort (sin_dnodes[i].firstface);
+ sin_dnodes[i].numfaces = LittleShort (sin_dnodes[i].numfaces);
+#endif
+ }
+
+//
+// leafs
+//
+ for (i=0 ; i<sin_numleafs ; i++)
+ {
+ sin_dleafs[i].contents = LittleLong (sin_dleafs[i].contents);
+ sin_dleafs[i].cluster = LittleShort (sin_dleafs[i].cluster);
+ sin_dleafs[i].area = LittleShort (sin_dleafs[i].area);
+ for (j=0 ; j<3 ; j++)
+ {
+ sin_dleafs[i].mins[j] = LittleShort (sin_dleafs[i].mins[j]);
+ sin_dleafs[i].maxs[j] = LittleShort (sin_dleafs[i].maxs[j]);
+ }
+#ifdef SIN
+ sin_dleafs[i].firstleafface = LittleUnsignedShort (sin_dleafs[i].firstleafface);
+ sin_dleafs[i].numleaffaces = LittleUnsignedShort (sin_dleafs[i].numleaffaces);
+ sin_dleafs[i].firstleafbrush = LittleUnsignedShort (sin_dleafs[i].firstleafbrush);
+ sin_dleafs[i].numleafbrushes = LittleUnsignedShort (sin_dleafs[i].numleafbrushes);
+#else
+ sin_dleafs[i].firstleafface = LittleShort (sin_dleafs[i].firstleafface);
+ sin_dleafs[i].numleaffaces = LittleShort (sin_dleafs[i].numleaffaces);
+ sin_dleafs[i].firstleafbrush = LittleShort (sin_dleafs[i].firstleafbrush);
+ sin_dleafs[i].numleafbrushes = LittleShort (sin_dleafs[i].numleafbrushes);
+#endif
+ }
+
+//
+// leaffaces
+//
+ for (i=0 ; i<sin_numleaffaces ; i++)
+ sin_dleaffaces[i] = LittleShort (sin_dleaffaces[i]);
+
+//
+// leafbrushes
+//
+ for (i=0 ; i<sin_numleafbrushes ; i++)
+ sin_dleafbrushes[i] = LittleShort (sin_dleafbrushes[i]);
+
+//
+// surfedges
+//
+ for (i=0 ; i<sin_numsurfedges ; i++)
+ sin_dsurfedges[i] = LittleLong (sin_dsurfedges[i]);
+
+//
+// edges
+//
+ for (i=0 ; i<sin_numedges ; i++)
+ {
+#ifdef SIN
+ sin_dedges[i].v[0] = LittleUnsignedShort (sin_dedges[i].v[0]);
+ sin_dedges[i].v[1] = LittleUnsignedShort (sin_dedges[i].v[1]);
+#else
+ sin_dedges[i].v[0] = LittleShort (sin_dedges[i].v[0]);
+ sin_dedges[i].v[1] = LittleShort (sin_dedges[i].v[1]);
+#endif
+ }
+
+//
+// brushes
+//
+ for (i=0 ; i<sin_numbrushes ; i++)
+ {
+ sin_dbrushes[i].firstside = LittleLong (sin_dbrushes[i].firstside);
+ sin_dbrushes[i].numsides = LittleLong (sin_dbrushes[i].numsides);
+ sin_dbrushes[i].contents = LittleLong (sin_dbrushes[i].contents);
+ }
+
+//
+// areas
+//
+ for (i=0 ; i<sin_numareas ; i++)
+ {
+ sin_dareas[i].numareaportals = LittleLong (sin_dareas[i].numareaportals);
+ sin_dareas[i].firstareaportal = LittleLong (sin_dareas[i].firstareaportal);
+ }
+
+//
+// areasportals
+//
+ for (i=0 ; i<sin_numareaportals ; i++)
+ {
+ sin_dareaportals[i].portalnum = LittleLong (sin_dareaportals[i].portalnum);
+ sin_dareaportals[i].otherarea = LittleLong (sin_dareaportals[i].otherarea);
+ }
+
+//
+// brushsides
+//
+ for (i=0 ; i<sin_numbrushsides ; i++)
+ {
+#ifdef SIN
+ sin_dbrushsides[i].planenum = LittleUnsignedShort (sin_dbrushsides[i].planenum);
+#else
+ sin_dbrushsides[i].planenum = LittleShort (sin_dbrushsides[i].planenum);
+#endif
+ sin_dbrushsides[i].texinfo = LittleShort (sin_dbrushsides[i].texinfo);
+#ifdef SIN
+ sin_dbrushsides[i].lightinfo = LittleLong (sin_dbrushsides[i].lightinfo);
+#endif
+ }
+
+//
+// visibility
+//
+ if (todisk)
+ j = sin_dvis->numclusters;
+ else
+ j = LittleLong(sin_dvis->numclusters);
+ sin_dvis->numclusters = LittleLong (sin_dvis->numclusters);
+ for (i=0 ; i<j ; i++)
+ {
+ sin_dvis->bitofs[i][0] = LittleLong (sin_dvis->bitofs[i][0]);
+ sin_dvis->bitofs[i][1] = LittleLong (sin_dvis->bitofs[i][1]);
+ }
+} //end of the function Sin_SwapBSPFile
+
+
+sin_dheader_t *header;
+#ifdef SIN
+int Sin_CopyLump (int lump, void *dest, int size, int maxsize)
+{
+ int length, ofs;
+
+ length = header->lumps[lump].filelen;
+ ofs = header->lumps[lump].fileofs;
+
+ if (length % size)
+ Error ("Sin_LoadBSPFile: odd lump size");
+
+ if ((length/size) > maxsize)
+ Error ("Sin_LoadBSPFile: exceeded max size for lump %d size %d > maxsize %d\n", lump, (length/size), maxsize );
+
+ memcpy (dest, (byte *)header + ofs, length);
+
+ return length / size;
+}
+#else
+int Sin_CopyLump (int lump, void *dest, int size)
+{
+ int length, ofs;
+
+ length = header->lumps[lump].filelen;
+ ofs = header->lumps[lump].fileofs;
+
+ if (length % size)
+ Error ("Sin_LoadBSPFile: odd lump size");
+
+ memcpy (dest, (byte *)header + ofs, length);
+
+ return length / size;
+}
+#endif
+
+/*
+=============
+Sin_LoadBSPFile
+=============
+*/
+void Sin_LoadBSPFile(char *filename, int offset, int length)
+{
+ int i;
+
+//
+// load the file header
+//
+ LoadFile (filename, (void **)&header, offset, length);
+
+// swap the header
+ for (i=0 ; i< sizeof(sin_dheader_t)/4 ; i++)
+ ((int *)header)[i] = LittleLong ( ((int *)header)[i]);
+
+ if (header->ident != SIN_BSPHEADER && header->ident != SINGAME_BSPHEADER)
+ Error ("%s is not a IBSP file", filename);
+ if (header->version != SIN_BSPVERSION && header->version != SINGAME_BSPVERSION)
+ Error ("%s is version %i, not %i", filename, header->version, SIN_BSPVERSION);
+
+#ifdef SIN
+ sin_nummodels = Sin_CopyLump (SIN_LUMP_MODELS, sin_dmodels, sizeof(sin_dmodel_t), SIN_MAX_MAP_MODELS);
+ sin_numvertexes = Sin_CopyLump (SIN_LUMP_VERTEXES, sin_dvertexes, sizeof(sin_dvertex_t), SIN_MAX_MAP_VERTS);
+ sin_numplanes = Sin_CopyLump (SIN_LUMP_PLANES, sin_dplanes, sizeof(sin_dplane_t), SIN_MAX_MAP_PLANES);
+ sin_numleafs = Sin_CopyLump (SIN_LUMP_LEAFS, sin_dleafs, sizeof(sin_dleaf_t), SIN_MAX_MAP_LEAFS);
+ sin_numnodes = Sin_CopyLump (SIN_LUMP_NODES, sin_dnodes, sizeof(sin_dnode_t), SIN_MAX_MAP_NODES);
+ sin_numtexinfo = Sin_CopyLump (SIN_LUMP_TEXINFO, sin_texinfo, sizeof(sin_texinfo_t), SIN_MAX_MAP_TEXINFO);
+ sin_numfaces = Sin_CopyLump (SIN_LUMP_FACES, sin_dfaces, sizeof(sin_dface_t), SIN_MAX_MAP_FACES);
+ sin_numleaffaces = Sin_CopyLump (SIN_LUMP_LEAFFACES, sin_dleaffaces, sizeof(sin_dleaffaces[0]), SIN_MAX_MAP_LEAFFACES);
+ sin_numleafbrushes = Sin_CopyLump (SIN_LUMP_LEAFBRUSHES, sin_dleafbrushes, sizeof(sin_dleafbrushes[0]), SIN_MAX_MAP_LEAFBRUSHES);
+ sin_numsurfedges = Sin_CopyLump (SIN_LUMP_SURFEDGES, sin_dsurfedges, sizeof(sin_dsurfedges[0]), SIN_MAX_MAP_SURFEDGES);
+ sin_numedges = Sin_CopyLump (SIN_LUMP_EDGES, sin_dedges, sizeof(sin_dedge_t), SIN_MAX_MAP_EDGES);
+ sin_numbrushes = Sin_CopyLump (SIN_LUMP_BRUSHES, sin_dbrushes, sizeof(sin_dbrush_t), SIN_MAX_MAP_BRUSHES);
+ sin_numbrushsides = Sin_CopyLump (SIN_LUMP_BRUSHSIDES, sin_dbrushsides, sizeof(sin_dbrushside_t), SIN_MAX_MAP_BRUSHSIDES);
+ sin_numareas = Sin_CopyLump (SIN_LUMP_AREAS, sin_dareas, sizeof(sin_darea_t), SIN_MAX_MAP_AREAS);
+ sin_numareaportals = Sin_CopyLump (SIN_LUMP_AREAPORTALS, sin_dareaportals, sizeof(sin_dareaportal_t), SIN_MAX_MAP_AREAPORTALS);
+ sin_numlightinfo = Sin_CopyLump (SIN_LUMP_LIGHTINFO, sin_lightinfo, sizeof(sin_lightvalue_t), SIN_MAX_MAP_LIGHTINFO);
+
+ sin_visdatasize = Sin_CopyLump (SIN_LUMP_VISIBILITY, sin_dvisdata, 1, SIN_MAX_MAP_VISIBILITY);
+ sin_lightdatasize = Sin_CopyLump (SIN_LUMP_LIGHTING, sin_dlightdata, 1, SIN_MAX_MAP_LIGHTING);
+ sin_entdatasize = Sin_CopyLump (SIN_LUMP_ENTITIES, sin_dentdata, 1, SIN_MAX_MAP_ENTSTRING);
+
+ Sin_CopyLump (SIN_LUMP_POP, sin_dpop, 1, sizeof(sin_dpop));
+#else
+ sin_nummodels = Sin_CopyLump (SIN_LUMP_MODELS, sin_dmodels, sizeof(sin_dmodel_t));
+ sin_numvertexes = Sin_CopyLump (SIN_LUMP_VERTEXES, sin_dvertexes, sizeof(sin_dvertex_t));
+ sin_numplanes = Sin_CopyLump (SIN_LUMP_PLANES, sin_dplanes, sizeof(sin_dplane_t));
+ sin_numleafs = Sin_CopyLump (SIN_LUMP_LEAFS, sin_dleafs, sizeof(sin_dleaf_t));
+ sin_numnodes = Sin_CopyLump (SIN_LUMP_NODES, sin_dnodes, sizeof(sin_dnode_t));
+ sin_numtexinfo = Sin_CopyLump (SIN_LUMP_TEXINFO, sin_texinfo, sizeof(sin_texinfo_t));
+ sin_numfaces = Sin_CopyLump (SIN_LUMP_FACES, sin_dfaces, sizeof(sin_dface_t));
+ sin_numleaffaces = Sin_CopyLump (SIN_LUMP_LEAFFACES, sin_dleaffaces, sizeof(sin_dleaffaces[0]));
+ sin_numleafbrushes = Sin_CopyLump (SIN_LUMP_LEAFBRUSHES, sin_dleafbrushes, sizeof(sin_dleafbrushes[0]));
+ sin_numsurfedges = Sin_CopyLump (SIN_LUMP_SURFEDGES, sin_dsurfedges, sizeof(sin_dsurfedges[0]));
+ sin_numedges = Sin_CopyLump (SIN_LUMP_EDGES, sin_dedges, sizeof(sin_dedge_t));
+ sin_numbrushes = Sin_CopyLump (SIN_LUMP_BRUSHES, sin_dbrushes, sizeof(sin_dbrush_t));
+ sin_numbrushsides = Sin_CopyLump (SIN_LUMP_BRUSHSIDES, sin_dbrushsides, sizeof(sin_dbrushside_t));
+ sin_numareas = Sin_CopyLump (SIN_LUMP_AREAS, sin_dareas, sizeof(sin_darea_t));
+ sin_numareaportals = Sin_CopyLump (SIN_LUMP_AREAPORTALS, sin_dareaportals, sizeof(sin_dareaportal_t));
+
+ sin_visdatasize = Sin_CopyLump (SIN_LUMP_VISIBILITY, sin_dvisdata, 1);
+ sin_lightdatasize = Sin_CopyLump (SIN_LUMP_LIGHTING, sin_dlightdata, 1);
+ sin_entdatasize = Sin_CopyLump (SIN_LUMP_ENTITIES, sin_dentdata, 1);
+
+ Sin_CopyLump (SIN_LUMP_POP, sin_dpop, 1);
+#endif
+
+ FreeMemory(header); // everything has been copied out
+
+//
+// swap everything
+//
+ Sin_SwapBSPFile (false);
+} //end of the function Sin_LoadBSPFile
+
+/*
+=============
+Sin_LoadBSPFilesTexinfo
+
+Only loads the sin_texinfo lump, so qdata can scan for textures
+=============
+*/
+void Sin_LoadBSPFileTexinfo (char *filename)
+{
+ int i;
+ FILE *f;
+ int length, ofs;
+
+ header = GetMemory(sizeof(sin_dheader_t));
+
+ f = fopen (filename, "rb");
+ fread (header, sizeof(sin_dheader_t), 1, f);
+
+// swap the header
+ for (i=0 ; i< sizeof(sin_dheader_t)/4 ; i++)
+ ((int *)header)[i] = LittleLong ( ((int *)header)[i]);
+
+ if (header->ident != SIN_BSPHEADER && header->ident != SINGAME_BSPHEADER)
+ Error ("%s is not a IBSP file", filename);
+ if (header->version != SIN_BSPVERSION && header->version != SINGAME_BSPVERSION)
+ Error ("%s is version %i, not %i", filename, header->version, SIN_BSPVERSION);
+
+
+ length = header->lumps[SIN_LUMP_TEXINFO].filelen;
+ ofs = header->lumps[SIN_LUMP_TEXINFO].fileofs;
+
+ fseek (f, ofs, SEEK_SET);
+ fread (sin_texinfo, length, 1, f);
+ fclose (f);
+
+ sin_numtexinfo = length / sizeof(sin_texinfo_t);
+
+ FreeMemory(header); // everything has been copied out
+
+ Sin_SwapBSPFile (false);
+} //end of the function Sin_LoadBSPFilesTexinfo
+
+
+//============================================================================
+
+FILE *wadfile;
+sin_dheader_t outheader;
+
+#ifdef SIN
+void Sin_AddLump (int lumpnum, void *data, int len, int size, int maxsize)
+{
+ sin_lump_t *lump;
+ int totallength;
+
+ totallength = len*size;
+
+ if (len > maxsize)
+ Error ("Sin_WriteBSPFile: exceeded max size for lump %d size %d > maxsize %d\n", lumpnum, len, maxsize );
+
+ lump = &header->lumps[lumpnum];
+
+ lump->fileofs = LittleLong( ftell(wadfile) );
+ lump->filelen = LittleLong(totallength);
+ SafeWrite (wadfile, data, (totallength+3)&~3);
+}
+#else
+void Sin_AddLump (int lumpnum, void *data, int len)
+{
+ sin_lump_t *lump;
+
+ lump = &header->lumps[lumpnum];
+
+ lump->fileofs = LittleLong( ftell(wadfile) );
+ lump->filelen = LittleLong(len);
+ SafeWrite (wadfile, data, (len+3)&~3);
+}
+#endif
+/*
+=============
+Sin_WriteBSPFile
+
+Swaps the bsp file in place, so it should not be referenced again
+=============
+*/
+void Sin_WriteBSPFile (char *filename)
+{
+ header = &outheader;
+ memset (header, 0, sizeof(sin_dheader_t));
+
+ Sin_SwapBSPFile (true);
+
+ header->ident = LittleLong (SIN_BSPHEADER);
+ header->version = LittleLong (SIN_BSPVERSION);
+
+ wadfile = SafeOpenWrite (filename);
+ SafeWrite (wadfile, header, sizeof(sin_dheader_t)); // overwritten later
+
+#ifdef SIN
+ Sin_AddLump (SIN_LUMP_PLANES, sin_dplanes, sin_numplanes, sizeof(sin_dplane_t), SIN_MAX_MAP_PLANES);
+ Sin_AddLump (SIN_LUMP_LEAFS, sin_dleafs, sin_numleafs, sizeof(sin_dleaf_t), SIN_MAX_MAP_LEAFS);
+ Sin_AddLump (SIN_LUMP_VERTEXES, sin_dvertexes, sin_numvertexes, sizeof(sin_dvertex_t), SIN_MAX_MAP_VERTS);
+ Sin_AddLump (SIN_LUMP_NODES, sin_dnodes, sin_numnodes, sizeof(sin_dnode_t), SIN_MAX_MAP_NODES);
+ Sin_AddLump (SIN_LUMP_TEXINFO, sin_texinfo, sin_numtexinfo, sizeof(sin_texinfo_t), SIN_MAX_MAP_TEXINFO);
+ Sin_AddLump (SIN_LUMP_FACES, sin_dfaces, sin_numfaces, sizeof(sin_dface_t), SIN_MAX_MAP_FACES);
+ Sin_AddLump (SIN_LUMP_BRUSHES, sin_dbrushes, sin_numbrushes, sizeof(sin_dbrush_t), SIN_MAX_MAP_BRUSHES);
+ Sin_AddLump (SIN_LUMP_BRUSHSIDES, sin_dbrushsides, sin_numbrushsides, sizeof(sin_dbrushside_t), SIN_MAX_MAP_BRUSHSIDES);
+ Sin_AddLump (SIN_LUMP_LEAFFACES, sin_dleaffaces, sin_numleaffaces, sizeof(sin_dleaffaces[0]), SIN_MAX_MAP_LEAFFACES);
+ Sin_AddLump (SIN_LUMP_LEAFBRUSHES, sin_dleafbrushes, sin_numleafbrushes, sizeof(sin_dleafbrushes[0]), SIN_MAX_MAP_LEAFBRUSHES);
+ Sin_AddLump (SIN_LUMP_SURFEDGES, sin_dsurfedges, sin_numsurfedges, sizeof(sin_dsurfedges[0]), SIN_MAX_MAP_SURFEDGES);
+ Sin_AddLump (SIN_LUMP_EDGES, sin_dedges, sin_numedges, sizeof(sin_dedge_t), SIN_MAX_MAP_EDGES);
+ Sin_AddLump (SIN_LUMP_MODELS, sin_dmodels, sin_nummodels, sizeof(sin_dmodel_t), SIN_MAX_MAP_MODELS);
+ Sin_AddLump (SIN_LUMP_AREAS, sin_dareas, sin_numareas, sizeof(sin_darea_t), SIN_MAX_MAP_AREAS);
+ Sin_AddLump (SIN_LUMP_AREAPORTALS, sin_dareaportals, sin_numareaportals, sizeof(sin_dareaportal_t), SIN_MAX_MAP_AREAPORTALS);
+ Sin_AddLump (SIN_LUMP_LIGHTINFO, sin_lightinfo, sin_numlightinfo, sizeof(sin_lightvalue_t), SIN_MAX_MAP_LIGHTINFO);
+
+ Sin_AddLump (SIN_LUMP_LIGHTING, sin_dlightdata, sin_lightdatasize, 1, SIN_MAX_MAP_LIGHTING);
+ Sin_AddLump (SIN_LUMP_VISIBILITY, sin_dvisdata, sin_visdatasize, 1, SIN_MAX_MAP_VISIBILITY);
+ Sin_AddLump (SIN_LUMP_ENTITIES, sin_dentdata, sin_entdatasize, 1, SIN_MAX_MAP_ENTSTRING);
+ Sin_AddLump (SIN_LUMP_POP, sin_dpop, sizeof(sin_dpop), 1, sizeof(sin_dpop));
+#else
+ Sin_AddLump (SIN_LUMP_PLANES, sin_dplanes, sin_numplanes*sizeof(sin_dplane_t));
+ Sin_AddLump (SIN_LUMP_LEAFS, sin_dleafs, sin_numleafs*sizeof(sin_dleaf_t));
+ Sin_AddLump (SIN_LUMP_VERTEXES, sin_dvertexes, sin_numvertexes*sizeof(sin_dvertex_t));
+ Sin_AddLump (SIN_LUMP_NODES, sin_dnodes, sin_numnodes*sizeof(sin_dnode_t));
+ Sin_AddLump (SIN_LUMP_TEXINFO, sin_texinfo, sin_numtexinfo*sizeof(sin_texinfo_t));
+ Sin_AddLump (SIN_LUMP_FACES, sin_dfaces, sin_numfaces*sizeof(sin_dface_t));
+ Sin_AddLump (SIN_LUMP_BRUSHES, sin_dbrushes, sin_numbrushes*sizeof(sin_dbrush_t));
+ Sin_AddLump (SIN_LUMP_BRUSHSIDES, sin_dbrushsides, sin_numbrushsides*sizeof(sin_dbrushside_t));
+ Sin_AddLump (SIN_LUMP_LEAFFACES, sin_dleaffaces, sin_numleaffaces*sizeof(sin_dleaffaces[0]));
+ Sin_AddLump (SIN_LUMP_LEAFBRUSHES, sin_dleafbrushes, sin_numleafbrushes*sizeof(sin_dleafbrushes[0]));
+ Sin_AddLump (SIN_LUMP_SURFEDGES, sin_dsurfedges, sin_numsurfedges*sizeof(sin_dsurfedges[0]));
+ Sin_AddLump (SIN_LUMP_EDGES, sin_dedges, sin_numedges*sizeof(sin_dedge_t));
+ Sin_AddLump (SIN_LUMP_MODELS, sin_dmodels, sin_nummodels*sizeof(sin_dmodel_t));
+ Sin_AddLump (SIN_LUMP_AREAS, sin_dareas, sin_numareas*sizeof(sin_darea_t));
+ Sin_AddLump (SIN_LUMP_AREAPORTALS, sin_dareaportals, sin_numareaportals*sizeof(sin_dareaportal_t));
+
+ Sin_AddLump (SIN_LUMP_LIGHTING, sin_dlightdata, sin_lightdatasize);
+ Sin_AddLump (SIN_LUMP_VISIBILITY, sin_dvisdata, sin_visdatasize);
+ Sin_AddLump (SIN_LUMP_ENTITIES, sin_dentdata, sin_entdatasize);
+ Sin_AddLump (SIN_LUMP_POP, sin_dpop, sizeof(sin_dpop));
+#endif
+
+ fseek (wadfile, 0, SEEK_SET);
+ SafeWrite (wadfile, header, sizeof(sin_dheader_t));
+ fclose (wadfile);
+}
+
+//============================================================================
+
+
+//============================================
+
+/*
+================
+ParseEntities
+
+Parses the sin_dentdata string into entities
+================
+*/
+void Sin_ParseEntities (void)
+{
+ script_t *script;
+
+ num_entities = 0;
+ script = LoadScriptMemory(sin_dentdata, sin_entdatasize, "*sin bsp file");
+ SetScriptFlags(script, SCFL_NOSTRINGWHITESPACES |
+ SCFL_NOSTRINGESCAPECHARS);
+
+ while(ParseEntity(script))
+ {
+ } //end while
+
+ FreeScript(script);
+} //end of the function Sin_ParseEntities
+
+
+/*
+================
+UnparseEntities
+
+Generates the sin_dentdata string from all the entities
+================
+*/
+void Sin_UnparseEntities (void)
+{
+ char *buf, *end;
+ epair_t *ep;
+ char line[2048];
+ int i;
+ char key[1024], value[1024];
+
+ buf = sin_dentdata;
+ end = buf;
+ *end = 0;
+
+ for (i=0 ; i<num_entities ; i++)
+ {
+ ep = entities[i].epairs;
+ if (!ep)
+ continue; // ent got removed
+
+ strcat (end,"{\n");
+ end += 2;
+
+ for (ep = entities[i].epairs ; ep ; ep=ep->next)
+ {
+ strcpy (key, ep->key);
+ StripTrailing (key);
+ strcpy (value, ep->value);
+ StripTrailing (value);
+
+ sprintf (line, "\"%s\" \"%s\"\n", key, value);
+ strcat (end, line);
+ end += strlen(line);
+ }
+ strcat (end,"}\n");
+ end += 2;
+
+ if (end > buf + SIN_MAX_MAP_ENTSTRING)
+ Error ("Entity text too long");
+ }
+ sin_entdatasize = end - buf + 1;
+} //end of the function Sin_UnparseEntities
+
+#ifdef SIN
+void FreeValueKeys(entity_t *ent)
+{
+ epair_t *ep,*next;
+
+ for (ep=ent->epairs ; ep ; ep=next)
+ {
+ next = ep->next;
+ FreeMemory(ep->value);
+ FreeMemory(ep->key);
+ FreeMemory(ep);
+ }
+ ent->epairs = NULL;
+}
+#endif
+
+/*
+=============
+Sin_PrintBSPFileSizes
+
+Dumps info about current file
+=============
+*/
+void Sin_PrintBSPFileSizes (void)
+{
+ if (!num_entities)
+ Sin_ParseEntities ();
+
+ Log_Print("%6i models %7i\n"
+ ,sin_nummodels, (int)(sin_nummodels*sizeof(sin_dmodel_t)));
+ Log_Print("%6i brushes %7i\n"
+ ,sin_numbrushes, (int)(sin_numbrushes*sizeof(sin_dbrush_t)));
+ Log_Print("%6i brushsides %7i\n"
+ ,sin_numbrushsides, (int)(sin_numbrushsides*sizeof(sin_dbrushside_t)));
+ Log_Print("%6i planes %7i\n"
+ ,sin_numplanes, (int)(sin_numplanes*sizeof(sin_dplane_t)));
+ Log_Print("%6i texinfo %7i\n"
+ ,sin_numtexinfo, (int)(sin_numtexinfo*sizeof(sin_texinfo_t)));
+#ifdef SIN
+ Log_Print("%6i lightinfo %7i\n"
+ ,sin_numlightinfo, (int)(sin_numlightinfo*sizeof(sin_lightvalue_t)));
+#endif
+ Log_Print("%6i entdata %7i\n", num_entities, sin_entdatasize);
+
+ Log_Print("\n");
+
+ Log_Print("%6i vertexes %7i\n"
+ ,sin_numvertexes, (int)(sin_numvertexes*sizeof(sin_dvertex_t)));
+ Log_Print("%6i nodes %7i\n"
+ ,sin_numnodes, (int)(sin_numnodes*sizeof(sin_dnode_t)));
+ Log_Print("%6i faces %7i\n"
+ ,sin_numfaces, (int)(sin_numfaces*sizeof(sin_dface_t)));
+ Log_Print("%6i leafs %7i\n"
+ ,sin_numleafs, (int)(sin_numleafs*sizeof(sin_dleaf_t)));
+ Log_Print("%6i leaffaces %7i\n"
+ ,sin_numleaffaces, (int)(sin_numleaffaces*sizeof(sin_dleaffaces[0])));
+ Log_Print("%6i leafbrushes %7i\n"
+ ,sin_numleafbrushes, (int)(sin_numleafbrushes*sizeof(sin_dleafbrushes[0])));
+ Log_Print("%6i surfedges %7i\n"
+ ,sin_numsurfedges, (int)(sin_numsurfedges*sizeof(sin_dsurfedges[0])));
+ Log_Print("%6i edges %7i\n"
+ ,sin_numedges, (int)(sin_numedges*sizeof(sin_dedge_t)));
+ Log_Print(" lightdata %7i\n", sin_lightdatasize);
+ Log_Print(" visdata %7i\n", sin_visdatasize);
+}
diff --git a/code/bspc/l_bsp_sin.h b/code/bspc/l_bsp_sin.h
new file mode 100755
index 0000000..93cb69f
--- /dev/null
+++ b/code/bspc/l_bsp_sin.h
@@ -0,0 +1,106 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "sinfiles.h"
+
+#define SINGAME_BSPHEADER (('P'<<24)+('S'<<16)+('B'<<8)+'R') //RBSP
+#define SINGAME_BSPVERSION 1
+
+#define SIN_BSPHEADER (('P'<<24)+('S'<<16)+('B'<<8)+'I') //IBSP
+#define SIN_BSPVERSION 41
+
+
+extern int sin_nummodels;
+extern sin_dmodel_t *sin_dmodels;//[MAX_MAP_MODELS];
+
+extern int sin_visdatasize;
+extern byte *sin_dvisdata;//[MAX_MAP_VISIBILITY];
+extern sin_dvis_t *sin_dvis;// = (dvis_t *)sin_sin_dvisdata;
+
+extern int sin_lightdatasize;
+extern byte *sin_dlightdata;//[MAX_MAP_LIGHTING];
+
+extern int sin_entdatasize;
+extern char *sin_dentdata;//[MAX_MAP_ENTSTRING];
+
+extern int sin_numleafs;
+extern sin_dleaf_t *sin_dleafs;//[MAX_MAP_LEAFS];
+
+extern int sin_numplanes;
+extern sin_dplane_t *sin_dplanes;//[MAX_MAP_PLANES];
+
+extern int sin_numvertexes;
+extern sin_dvertex_t *sin_dvertexes;//[MAX_MAP_VERTS];
+
+extern int sin_numnodes;
+extern sin_dnode_t *sin_dnodes;//[MAX_MAP_NODES];
+
+extern int sin_numtexinfo;
+extern sin_texinfo_t *sin_texinfo;//[MAX_MAP_sin_texinfo];
+
+extern int sin_numfaces;
+extern sin_dface_t *sin_dfaces;//[MAX_MAP_FACES];
+
+extern int sin_numedges;
+extern sin_dedge_t *sin_dedges;//[MAX_MAP_EDGES];
+
+extern int sin_numleaffaces;
+extern unsigned short *sin_dleaffaces;//[MAX_MAP_LEAFFACES];
+
+extern int sin_numleafbrushes;
+extern unsigned short *sin_dleafbrushes;//[MAX_MAP_LEAFBRUSHES];
+
+extern int sin_numsurfedges;
+extern int *sin_dsurfedges;//[MAX_MAP_SURFEDGES];
+
+extern int sin_numbrushes;
+extern sin_dbrush_t *sin_dbrushes;//[MAX_MAP_BRUSHES];
+
+extern int sin_numbrushsides;
+extern sin_dbrushside_t *sin_dbrushsides;//[MAX_MAP_BRUSHSIDES];
+
+extern int sin_numareas;
+extern sin_darea_t *sin_dareas;//[MAX_MAP_AREAS];
+
+extern int sin_numareaportals;
+extern sin_dareaportal_t *sin_dareaportals;//[MAX_MAP_AREAPORTALS];
+
+extern int sin_numlightinfo;
+extern sin_lightvalue_t *sin_lightinfo;//[MAX_MAP_LIGHTINFO];
+
+extern byte sin_dpop[256];
+
+extern char sin_dbrushsidetextured[SIN_MAX_MAP_BRUSHSIDES];
+
+void Sin_AllocMaxBSP(void);
+void Sin_FreeMaxBSP(void);
+
+void Sin_DecompressVis(byte *in, byte *decompressed);
+int Sin_CompressVis(byte *vis, byte *dest);
+
+void Sin_LoadBSPFile (char *filename, int offset, int length);
+void Sin_LoadBSPFileTexinfo (char *filename); // just for qdata
+void Sin_WriteBSPFile (char *filename);
+void Sin_PrintBSPFileSizes (void);
+void Sin_ParseEntities(void);
+void Sin_UnparseEntities(void);
+
diff --git a/code/bspc/l_cmd.c b/code/bspc/l_cmd.c
new file mode 100755
index 0000000..35fef7b
--- /dev/null
+++ b/code/bspc/l_cmd.c
@@ -0,0 +1,1230 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+// cmdlib.c
+
+#include "l_cmd.h"
+#include "l_log.h"
+#include "l_mem.h"
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#ifndef SIN
+#define SIN
+#endif //SIN
+
+#if defined(WIN32) || defined(_WIN32)
+#include <direct.h>
+#else
+#include <unistd.h>
+#endif
+
+#ifdef NeXT
+#include <libc.h>
+#endif
+
+#define BASEDIRNAME "quake2"
+#define PATHSEPERATOR '/'
+
+// set these before calling CheckParm
+int myargc;
+char **myargv;
+
+char com_token[1024];
+qboolean com_eof;
+
+qboolean archive;
+char archivedir[1024];
+
+
+/*
+===================
+ExpandWildcards
+
+Mimic unix command line expansion
+===================
+*/
+#define MAX_EX_ARGC 1024
+int ex_argc;
+char *ex_argv[MAX_EX_ARGC];
+#ifdef _WIN32
+#include "io.h"
+void ExpandWildcards (int *argc, char ***argv)
+{
+ struct _finddata_t fileinfo;
+ int handle;
+ int i;
+ char filename[1024];
+ char filebase[1024];
+ char *path;
+
+ ex_argc = 0;
+ for (i=0 ; i<*argc ; i++)
+ {
+ path = (*argv)[i];
+ if ( path[0] == '-'
+ || ( !strstr(path, "*") && !strstr(path, "?") ) )
+ {
+ ex_argv[ex_argc++] = path;
+ continue;
+ }
+
+ handle = _findfirst (path, &fileinfo);
+ if (handle == -1)
+ return;
+
+ ExtractFilePath (path, filebase);
+
+ do
+ {
+ sprintf (filename, "%s%s", filebase, fileinfo.name);
+ ex_argv[ex_argc++] = copystring (filename);
+ } while (_findnext( handle, &fileinfo ) != -1);
+
+ _findclose (handle);
+ }
+
+ *argc = ex_argc;
+ *argv = ex_argv;
+}
+#else
+void ExpandWildcards (int *argc, char ***argv)
+{
+}
+#endif
+
+#ifdef WINBSPC
+
+#include <windows.h>
+
+HWND program_hwnd;
+
+void SetProgramHandle(HWND hwnd)
+{
+ program_hwnd = hwnd;
+} //end of the function SetProgramHandle
+
+/*
+=================
+Error
+
+For abnormal program terminations in windowed apps
+=================
+*/
+void Error (char *error, ...)
+{
+ va_list argptr;
+ char text[1024];
+ char text2[1024];
+ int err;
+
+ err = GetLastError ();
+
+ va_start(argptr, error);
+ vsprintf(text, error, argptr);
+ va_end(argptr);
+
+ sprintf(text2, "%s\nGetLastError() = %i", text, err);
+ MessageBox(program_hwnd, text2, "Error", 0 /* MB_OK */ );
+
+ Log_Write(text);
+ Log_Close();
+
+ exit(1);
+} //end of the function Error
+
+void Warning(char *szFormat, ...)
+{
+ char szBuffer[256];
+ va_list argptr;
+
+ va_start (argptr, szFormat);
+ vsprintf(szBuffer, szFormat, argptr);
+ va_end (argptr);
+
+ MessageBox(program_hwnd, szBuffer, "Warning", MB_OK);
+
+ Log_Write(szBuffer);
+} //end of the function Warning
+
+
+#else
+/*
+=================
+Error
+
+For abnormal program terminations in console apps
+=================
+*/
+void Error (char *error, ...)
+{
+ va_list argptr;
+ char text[1024];
+
+ va_start(argptr, error);
+ vsprintf(text, error, argptr);
+ va_end(argptr);
+ printf("ERROR: %s\n", text);
+
+ Log_Write(text);
+ Log_Close();
+
+ exit (1);
+} //end of the function Error
+
+void Warning(char *warning, ...)
+{
+ va_list argptr;
+ char text[1024];
+
+ va_start(argptr, warning);
+ vsprintf(text, warning, argptr);
+ va_end(argptr);
+ printf("WARNING: %s\n", text);
+
+ Log_Write(text);
+} //end of the function Warning
+
+#endif
+
+//only printf if in verbose mode
+qboolean verbose = true;
+
+void qprintf(char *format, ...)
+{
+ va_list argptr;
+#ifdef WINBSPC
+ char buf[2048];
+#endif //WINBSPC
+
+ if (!verbose)
+ return;
+
+ va_start(argptr,format);
+#ifdef WINBSPC
+ vsprintf(buf, format, argptr);
+ WinBSPCPrint(buf);
+#else
+ vprintf(format, argptr);
+#endif //WINBSPC
+ va_end(argptr);
+} //end of the function qprintf
+
+void Com_Error(int level, char *error, ...)
+{
+ va_list argptr;
+ char text[1024];
+
+ va_start(argptr, error);
+ vsprintf(text, error, argptr);
+ va_end(argptr);
+ Error(text);
+} //end of the funcion Com_Error
+
+void Com_Printf( const char *fmt, ... )
+{
+ va_list argptr;
+ char text[1024];
+
+ va_start(argptr, fmt);
+ vsprintf(text, fmt, argptr);
+ va_end(argptr);
+ Log_Print(text);
+} //end of the funcion Com_Printf
+
+/*
+
+qdir will hold the path up to the quake directory, including the slash
+
+ f:\quake\
+ /raid/quake/
+
+gamedir will hold qdir + the game directory (id1, id2, etc)
+
+ */
+
+char qdir[1024];
+char gamedir[1024];
+
+void SetQdirFromPath (char *path)
+{
+ char temp[1024];
+ char *c;
+ int len;
+
+ if (!(path[0] == '/' || path[0] == '\\' || path[1] == ':'))
+ { // path is partial
+ Q_getwd (temp);
+ strcat (temp, path);
+ path = temp;
+ }
+
+ // search for "quake2" in path
+
+ len = strlen(BASEDIRNAME);
+ for (c=path+strlen(path)-1 ; c != path ; c--)
+ if (!Q_strncasecmp (c, BASEDIRNAME, len))
+ {
+ strncpy (qdir, path, c+len+1-path);
+ qprintf ("qdir: %s\n", qdir);
+ c += len+1;
+ while (*c)
+ {
+ if (*c == '/' || *c == '\\')
+ {
+ strncpy (gamedir, path, c+1-path);
+ qprintf ("gamedir: %s\n", gamedir);
+ return;
+ }
+ c++;
+ }
+ Error ("No gamedir in %s", path);
+ return;
+ }
+ Error ("SetQdirFromPath: no '%s' in %s", BASEDIRNAME, path);
+}
+
+char *ExpandArg (char *path)
+{
+ static char full[1024];
+
+ if (path[0] != '/' && path[0] != '\\' && path[1] != ':')
+ {
+ Q_getwd (full);
+ strcat (full, path);
+ }
+ else
+ strcpy (full, path);
+ return full;
+}
+
+char *ExpandPath (char *path)
+{
+ static char full[1024];
+ if (!qdir)
+ Error ("ExpandPath called without qdir set");
+ if (path[0] == '/' || path[0] == '\\' || path[1] == ':')
+ return path;
+ sprintf (full, "%s%s", qdir, path);
+ return full;
+}
+
+char *ExpandPathAndArchive (char *path)
+{
+ char *expanded;
+ char archivename[1024];
+
+ expanded = ExpandPath (path);
+
+ if (archive)
+ {
+ sprintf (archivename, "%s/%s", archivedir, path);
+ QCopyFile (expanded, archivename);
+ }
+ return expanded;
+}
+
+
+char *copystring(char *s)
+{
+ char *b;
+ b = GetMemory(strlen(s)+1);
+ strcpy (b, s);
+ return b;
+}
+
+
+
+/*
+================
+I_FloatTime
+================
+*/
+double I_FloatTime (void)
+{
+ time_t t;
+
+ time (&t);
+
+ return t;
+#if 0
+// more precise, less portable
+ struct timeval tp;
+ struct timezone tzp;
+ static int secbase;
+
+ gettimeofday(&tp, &tzp);
+
+ if (!secbase)
+ {
+ secbase = tp.tv_sec;
+ return tp.tv_usec/1000000.0;
+ }
+
+ return (tp.tv_sec - secbase) + tp.tv_usec/1000000.0;
+#endif
+}
+
+void Q_getwd (char *out)
+{
+#if defined(WIN32) || defined(_WIN32)
+ getcwd (out, 256);
+ strcat (out, "\\");
+#else
+ getwd(out);
+ strcat(out, "/");
+#endif
+}
+
+
+void Q_mkdir (char *path)
+{
+#ifdef WIN32
+ if (_mkdir (path) != -1)
+ return;
+#else
+ if (mkdir (path, 0777) != -1)
+ return;
+#endif
+ if (errno != EEXIST)
+ Error ("mkdir %s: %s",path, strerror(errno));
+}
+
+/*
+============
+FileTime
+
+returns -1 if not present
+============
+*/
+int FileTime (char *path)
+{
+ struct stat buf;
+
+ if (stat (path,&buf) == -1)
+ return -1;
+
+ return buf.st_mtime;
+}
+
+
+
+/*
+==============
+COM_Parse
+
+Parse a token out of a string
+==============
+*/
+char *COM_Parse (char *data)
+{
+ int c;
+ int len;
+
+ len = 0;
+ com_token[0] = 0;
+
+ if (!data)
+ return NULL;
+
+// skip whitespace
+skipwhite:
+ while ( (c = *data) <= ' ')
+ {
+ if (c == 0)
+ {
+ com_eof = true;
+ return NULL; // end of file;
+ }
+ data++;
+ }
+
+// skip // comments
+ if (c=='/' && data[1] == '/')
+ {
+ while (*data && *data != '\n')
+ data++;
+ goto skipwhite;
+ }
+
+
+// handle quoted strings specially
+ if (c == '\"')
+ {
+ data++;
+ do
+ {
+ c = *data++;
+ if (c=='\"')
+ {
+ com_token[len] = 0;
+ return data;
+ }
+ com_token[len] = c;
+ len++;
+ } while (1);
+ }
+
+// parse single characters
+ if (c=='{' || c=='}'|| c==')'|| c=='(' || c=='\'' || c==':')
+ {
+ com_token[len] = c;
+ len++;
+ com_token[len] = 0;
+ return data+1;
+ }
+
+// parse a regular word
+ do
+ {
+ com_token[len] = c;
+ data++;
+ len++;
+ c = *data;
+ if (c=='{' || c=='}'|| c==')'|| c=='(' || c=='\'' || c==':')
+ break;
+ } while (c>32);
+
+ com_token[len] = 0;
+ return data;
+}
+
+
+int Q_strncasecmp (char *s1, char *s2, int n)
+{
+ int c1, c2;
+
+ do
+ {
+ c1 = *s1++;
+ c2 = *s2++;
+
+ if (!n--)
+ return 0; // strings are equal until end point
+
+ if (c1 != c2)
+ {
+ if (c1 >= 'a' && c1 <= 'z')
+ c1 -= ('a' - 'A');
+ if (c2 >= 'a' && c2 <= 'z')
+ c2 -= ('a' - 'A');
+ if (c1 != c2)
+ return -1; // strings not equal
+ }
+ } while (c1);
+
+ return 0; // strings are equal
+}
+
+int Q_strcasecmp (char *s1, char *s2)
+{
+ return Q_strncasecmp (s1, s2, 99999);
+}
+
+int Q_stricmp (char *s1, char *s2)
+{
+ return Q_strncasecmp (s1, s2, 99999);
+}
+
+void Q_strncpyz( char *dest, const char *src, int destsize ) {
+ strncpy( dest, src, destsize-1 );
+ dest[destsize-1] = 0;
+}
+
+char *strupr (char *start)
+{
+ char *in;
+ in = start;
+ while (*in)
+ {
+ *in = toupper(*in);
+ in++;
+ }
+ return start;
+}
+
+char *strlower (char *start)
+{
+ char *in;
+ in = start;
+ while (*in)
+ {
+ *in = tolower(*in);
+ in++;
+ }
+ return start;
+}
+
+
+/*
+=============================================================================
+
+ MISC FUNCTIONS
+
+=============================================================================
+*/
+
+
+/*
+=================
+CheckParm
+
+Checks for the given parameter in the program's command line arguments
+Returns the argument number (1 to argc-1) or 0 if not present
+=================
+*/
+int CheckParm (char *check)
+{
+ int i;
+
+ for (i = 1;i<myargc;i++)
+ {
+ if ( !Q_strcasecmp(check, myargv[i]) )
+ return i;
+ }
+
+ return 0;
+}
+
+
+
+/*
+================
+Q_filelength
+================
+*/
+int Q_filelength (FILE *f)
+{
+ int pos;
+ int end;
+
+ pos = ftell (f);
+ fseek (f, 0, SEEK_END);
+ end = ftell (f);
+ fseek (f, pos, SEEK_SET);
+
+ return end;
+}
+
+
+FILE *SafeOpenWrite (char *filename)
+{
+ FILE *f;
+
+ f = fopen(filename, "wb");
+
+ if (!f)
+ Error ("Error opening %s: %s",filename,strerror(errno));
+
+ return f;
+}
+
+FILE *SafeOpenRead (char *filename)
+{
+ FILE *f;
+
+ f = fopen(filename, "rb");
+
+ if (!f)
+ Error ("Error opening %s: %s",filename,strerror(errno));
+
+ return f;
+}
+
+
+void SafeRead (FILE *f, void *buffer, int count)
+{
+ if ( fread (buffer, 1, count, f) != (size_t)count)
+ Error ("File read failure");
+}
+
+
+void SafeWrite (FILE *f, void *buffer, int count)
+{
+ if (fwrite (buffer, 1, count, f) != (size_t)count)
+ Error ("File write failure");
+}
+
+
+/*
+==============
+FileExists
+==============
+*/
+qboolean FileExists (char *filename)
+{
+ FILE *f;
+
+ f = fopen (filename, "r");
+ if (!f)
+ return false;
+ fclose (f);
+ return true;
+}
+
+/*
+==============
+LoadFile
+==============
+*/
+int LoadFile (char *filename, void **bufferptr, int offset, int length)
+{
+ FILE *f;
+ void *buffer;
+
+ f = SafeOpenRead(filename);
+ fseek(f, offset, SEEK_SET);
+ if (!length) length = Q_filelength(f);
+ buffer = GetMemory(length+1);
+ ((char *)buffer)[length] = 0;
+ SafeRead(f, buffer, length);
+ fclose(f);
+
+ *bufferptr = buffer;
+ return length;
+}
+
+
+/*
+==============
+TryLoadFile
+
+Allows failure
+==============
+*/
+int TryLoadFile (char *filename, void **bufferptr)
+{
+ FILE *f;
+ int length;
+ void *buffer;
+
+ *bufferptr = NULL;
+
+ f = fopen (filename, "rb");
+ if (!f)
+ return -1;
+ length = Q_filelength (f);
+ buffer = GetMemory(length+1);
+ ((char *)buffer)[length] = 0;
+ SafeRead (f, buffer, length);
+ fclose (f);
+
+ *bufferptr = buffer;
+ return length;
+}
+
+
+/*
+==============
+SaveFile
+==============
+*/
+void SaveFile (char *filename, void *buffer, int count)
+{
+ FILE *f;
+
+ f = SafeOpenWrite (filename);
+ SafeWrite (f, buffer, count);
+ fclose (f);
+}
+
+
+
+void DefaultExtension (char *path, char *extension)
+{
+ char *src;
+//
+// if path doesnt have a .EXT, append extension
+// (extension should include the .)
+//
+ src = path + strlen(path) - 1;
+
+ while (*src != PATHSEPERATOR && src != path)
+ {
+ if (*src == '.')
+ return; // it has an extension
+ src--;
+ }
+
+ strcat (path, extension);
+}
+
+
+void DefaultPath (char *path, char *basepath)
+{
+ char temp[128];
+
+ if (path[0] == PATHSEPERATOR)
+ return; // absolute path location
+ strcpy (temp,path);
+ strcpy (path,basepath);
+ strcat (path,temp);
+}
+
+
+void StripFilename (char *path)
+{
+ int length;
+
+ length = strlen(path)-1;
+ while (length > 0 && path[length] != PATHSEPERATOR)
+ length--;
+ path[length] = 0;
+}
+
+void StripExtension (char *path)
+{
+ int length;
+
+ length = strlen(path)-1;
+ while (length > 0 && path[length] != '.')
+ {
+ length--;
+ if (path[length] == '/')
+ return; // no extension
+ }
+ if (length)
+ path[length] = 0;
+}
+
+
+/*
+====================
+Extract file parts
+====================
+*/
+// FIXME: should include the slash, otherwise
+// backing to an empty path will be wrong when appending a slash
+void ExtractFilePath (char *path, char *dest)
+{
+ char *src;
+
+ src = path + strlen(path) - 1;
+
+//
+// back up until a \ or the start
+//
+ while (src != path && *(src-1) != '\\' && *(src-1) != '/')
+ src--;
+
+ memcpy (dest, path, src-path);
+ dest[src-path] = 0;
+}
+
+void ExtractFileBase (char *path, char *dest)
+{
+ char *src;
+
+ src = path + strlen(path) - 1;
+
+//
+// back up until a \ or the start
+//
+ while (src != path && *(src-1) != '\\' && *(src-1) != '/')
+ src--;
+
+ while (*src && *src != '.')
+ {
+ *dest++ = *src++;
+ }
+ *dest = 0;
+}
+
+void ExtractFileExtension (char *path, char *dest)
+{
+ char *src;
+
+ src = path + strlen(path) - 1;
+
+//
+// back up until a . or the start
+//
+ while (src != path && *(src-1) != '.')
+ src--;
+ if (src == path)
+ {
+ *dest = 0; // no extension
+ return;
+ }
+
+ strcpy (dest,src);
+}
+
+
+/*
+==============
+ParseNum / ParseHex
+==============
+*/
+int ParseHex (char *hex)
+{
+ char *str;
+ int num;
+
+ num = 0;
+ str = hex;
+
+ while (*str)
+ {
+ num <<= 4;
+ if (*str >= '0' && *str <= '9')
+ num += *str-'0';
+ else if (*str >= 'a' && *str <= 'f')
+ num += 10 + *str-'a';
+ else if (*str >= 'A' && *str <= 'F')
+ num += 10 + *str-'A';
+ else
+ Error ("Bad hex number: %s",hex);
+ str++;
+ }
+
+ return num;
+}
+
+
+int ParseNum (char *str)
+{
+ if (str[0] == '$')
+ return ParseHex (str+1);
+ if (str[0] == '0' && str[1] == 'x')
+ return ParseHex (str+2);
+ return atol (str);
+}
+
+
+
+/*
+============================================================================
+
+ BYTE ORDER FUNCTIONS
+
+============================================================================
+*/
+
+#ifdef _SGI_SOURCE
+#define __BIG_ENDIAN__
+#endif
+
+#ifdef __BIG_ENDIAN__
+
+short LittleShort (short l)
+{
+ byte b1,b2;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+
+ return (b1<<8) + b2;
+}
+
+short BigShort (short l)
+{
+ return l;
+}
+
+
+int LittleLong (int l)
+{
+ byte b1,b2,b3,b4;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+ b3 = (l>>16)&255;
+ b4 = (l>>24)&255;
+
+ return ((int)b1<<24) + ((int)b2<<16) + ((int)b3<<8) + b4;
+}
+
+int BigLong (int l)
+{
+ return l;
+}
+
+
+float LittleFloat (float l)
+{
+ union {byte b[4]; float f;} in, out;
+
+ in.f = l;
+ out.b[0] = in.b[3];
+ out.b[1] = in.b[2];
+ out.b[2] = in.b[1];
+ out.b[3] = in.b[0];
+
+ return out.f;
+}
+
+float BigFloat (float l)
+{
+ return l;
+}
+
+#ifdef SIN
+unsigned short LittleUnsignedShort (unsigned short l)
+{
+ byte b1,b2;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+
+ return (b1<<8) + b2;
+}
+
+unsigned short BigUnsignedShort (unsigned short l)
+{
+ return l;
+}
+
+unsigned LittleUnsigned (unsigned l)
+{
+ byte b1,b2,b3,b4;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+ b3 = (l>>16)&255;
+ b4 = (l>>24)&255;
+
+ return ((unsigned)b1<<24) + ((unsigned)b2<<16) + ((unsigned)b3<<8) + b4;
+}
+
+unsigned BigUnsigned (unsigned l)
+{
+ return l;
+}
+#endif
+
+
+#else
+
+
+short BigShort (short l)
+{
+ byte b1,b2;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+
+ return (b1<<8) + b2;
+}
+
+short LittleShort (short l)
+{
+ return l;
+}
+
+
+int BigLong (int l)
+{
+ byte b1,b2,b3,b4;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+ b3 = (l>>16)&255;
+ b4 = (l>>24)&255;
+
+ return ((int)b1<<24) + ((int)b2<<16) + ((int)b3<<8) + b4;
+}
+
+int LittleLong (int l)
+{
+ return l;
+}
+
+float BigFloat (float l)
+{
+ union {byte b[4]; float f;} in, out;
+
+ in.f = l;
+ out.b[0] = in.b[3];
+ out.b[1] = in.b[2];
+ out.b[2] = in.b[1];
+ out.b[3] = in.b[0];
+
+ return out.f;
+}
+
+float LittleFloat (float l)
+{
+ return l;
+}
+
+#ifdef SIN
+unsigned short BigUnsignedShort (unsigned short l)
+{
+ byte b1,b2;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+
+ return (b1<<8) + b2;
+}
+
+unsigned short LittleUnsignedShort (unsigned short l)
+{
+ return l;
+}
+
+
+unsigned BigUnsigned (unsigned l)
+{
+ byte b1,b2,b3,b4;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+ b3 = (l>>16)&255;
+ b4 = (l>>24)&255;
+
+ return ((unsigned)b1<<24) + ((unsigned)b2<<16) + ((unsigned)b3<<8) + b4;
+}
+
+unsigned LittleUnsigned (unsigned l)
+{
+ return l;
+}
+#endif
+
+
+#endif
+
+
+//=======================================================
+
+
+// FIXME: byte swap?
+
+// this is a 16 bit, non-reflected CRC using the polynomial 0x1021
+// and the initial and final xor values shown below... in other words, the
+// CCITT standard CRC used by XMODEM
+
+#define CRC_INIT_VALUE 0xffff
+#define CRC_XOR_VALUE 0x0000
+
+static unsigned short crctable[256] =
+{
+ 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
+ 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
+ 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
+ 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
+ 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
+ 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
+ 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
+ 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
+ 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
+ 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
+ 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
+ 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
+ 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
+ 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
+ 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
+ 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
+ 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
+ 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
+ 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
+ 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
+ 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
+ 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
+ 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
+ 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
+ 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
+ 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
+ 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
+ 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
+ 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
+ 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
+ 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
+ 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0
+};
+
+void CRC_Init(unsigned short *crcvalue)
+{
+ *crcvalue = CRC_INIT_VALUE;
+}
+
+void CRC_ProcessByte(unsigned short *crcvalue, byte data)
+{
+ *crcvalue = (*crcvalue << 8) ^ crctable[(*crcvalue >> 8) ^ data];
+}
+
+unsigned short CRC_Value(unsigned short crcvalue)
+{
+ return crcvalue ^ CRC_XOR_VALUE;
+}
+//=============================================================================
+
+/*
+============
+CreatePath
+============
+*/
+void CreatePath (char *path)
+{
+ char *ofs, c;
+
+ if (path[1] == ':')
+ path += 2;
+
+ for (ofs = path+1 ; *ofs ; ofs++)
+ {
+ c = *ofs;
+ if (c == '/' || c == '\\')
+ { // create the directory
+ *ofs = 0;
+ Q_mkdir (path);
+ *ofs = c;
+ }
+ }
+}
+
+
+/*
+============
+QCopyFile
+
+ Used to archive source files
+============
+*/
+void QCopyFile (char *from, char *to)
+{
+ void *buffer;
+ int length;
+
+ length = LoadFile (from, &buffer, 0, 0);
+ CreatePath (to);
+ SaveFile (to, buffer, length);
+ FreeMemory(buffer);
+}
+
+void FS_FreeFile(void *buf)
+{
+ FreeMemory(buf);
+} //end of the function FS_FreeFile
+
+int FS_ReadFileAndCache(const char *qpath, void **buffer)
+{
+ return LoadFile((char *) qpath, buffer, 0, 0);
+} //end of the function FS_ReadFileAndCache
+
+int FS_FOpenFileRead( const char *filename, FILE **file, qboolean uniqueFILE )
+{
+ *file = fopen(filename, "rb");
+ return (*file != NULL);
+} //end of the function FS_FOpenFileRead
diff --git a/code/bspc/l_cmd.h b/code/bspc/l_cmd.h
new file mode 100755
index 0000000..b5497b4
--- /dev/null
+++ b/code/bspc/l_cmd.h
@@ -0,0 +1,157 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// cmdlib.h
+
+#ifndef SIN
+#define SIN
+#endif //SIN
+
+#ifndef __CMDLIB__
+#define __CMDLIB__
+
+#ifdef _WIN32
+#pragma warning(disable : 4244) // MIPS
+#pragma warning(disable : 4136) // X86
+#pragma warning(disable : 4051) // ALPHA
+
+#pragma warning(disable : 4018) // signed/unsigned mismatch
+#pragma warning(disable : 4305) // truncate from double to float
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <ctype.h>
+#include <time.h>
+#include <stdarg.h>
+
+#ifndef __BYTEBOOL__
+#define __BYTEBOOL__
+typedef enum {false, true} qboolean;
+typedef unsigned char byte;
+#endif
+
+// the dec offsetof macro doesnt work very well...
+#define myoffsetof(type,identifier) ((size_t)&((type *)0)->identifier)
+
+
+// set these before calling CheckParm
+extern int myargc;
+extern char **myargv;
+
+char *strupr (char *in);
+char *strlower (char *in);
+int Q_strncasecmp (char *s1, char *s2, int n);
+int Q_strcasecmp (char *s1, char *s2);
+void Q_getwd (char *out);
+
+int Q_filelength (FILE *f);
+int FileTime (char *path);
+
+void Q_mkdir (char *path);
+
+extern char qdir[1024];
+extern char gamedir[1024];
+void SetQdirFromPath (char *path);
+char *ExpandArg (char *path); // from cmd line
+char *ExpandPath (char *path); // from scripts
+char *ExpandPathAndArchive (char *path);
+
+
+double I_FloatTime (void);
+
+void Error(char *error, ...);
+void Warning(char *warning, ...);
+
+int CheckParm (char *check);
+
+FILE *SafeOpenWrite (char *filename);
+FILE *SafeOpenRead (char *filename);
+void SafeRead (FILE *f, void *buffer, int count);
+void SafeWrite (FILE *f, void *buffer, int count);
+
+int LoadFile (char *filename, void **bufferptr, int offset, int length);
+int TryLoadFile (char *filename, void **bufferptr);
+void SaveFile (char *filename, void *buffer, int count);
+qboolean FileExists (char *filename);
+
+void DefaultExtension (char *path, char *extension);
+void DefaultPath (char *path, char *basepath);
+void StripFilename (char *path);
+void StripExtension (char *path);
+
+void ExtractFilePath (char *path, char *dest);
+void ExtractFileBase (char *path, char *dest);
+void ExtractFileExtension (char *path, char *dest);
+
+int ParseNum (char *str);
+
+short BigShort (short l);
+short LittleShort (short l);
+int BigLong (int l);
+int LittleLong (int l);
+float BigFloat (float l);
+float LittleFloat (float l);
+
+#ifdef SIN
+unsigned short BigUnsignedShort (unsigned short l);
+unsigned short LittleUnsignedShort (unsigned short l);
+unsigned BigUnsigned (unsigned l);
+unsigned LittleUnsigned (unsigned l);
+#endif
+
+
+char *COM_Parse (char *data);
+
+extern char com_token[1024];
+extern qboolean com_eof;
+
+char *copystring(char *s);
+
+
+void CRC_Init(unsigned short *crcvalue);
+void CRC_ProcessByte(unsigned short *crcvalue, byte data);
+unsigned short CRC_Value(unsigned short crcvalue);
+
+void CreatePath (char *path);
+void QCopyFile (char *from, char *to);
+
+extern qboolean archive;
+extern char archivedir[1024];
+
+
+extern qboolean verbose;
+void qprintf (char *format, ...);
+
+void ExpandWildcards (int *argc, char ***argv);
+
+
+// for compression routines
+typedef struct
+{
+ byte *data;
+ int count;
+} cblock_t;
+
+#endif
+
diff --git a/code/bspc/l_log.c b/code/bspc/l_log.c
new file mode 100755
index 0000000..b685ed3
--- /dev/null
+++ b/code/bspc/l_log.c
@@ -0,0 +1,215 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "qbsp.h"
+
+#define MAX_LOGFILENAMESIZE 1024
+
+typedef struct logfile_s
+{
+ char filename[MAX_LOGFILENAMESIZE];
+ FILE *fp;
+ int numwrites;
+} logfile_t;
+
+logfile_t logfile;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Log_Open(char *filename)
+{
+ if (!filename || !strlen(filename))
+ {
+ printf("openlog <filename>\n");
+ return;
+ } //end if
+ if (logfile.fp)
+ {
+ printf("log file %s is already opened\n", logfile.filename);
+ return;
+ } //end if
+ logfile.fp = fopen(filename, "wb");
+ if (!logfile.fp)
+ {
+ printf("can't open the log file %s\n", filename);
+ return;
+ } //end if
+ strncpy(logfile.filename, filename, MAX_LOGFILENAMESIZE);
+ printf("Opened log %s\n", logfile.filename);
+} //end of the function Log_Create
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Log_Close(void)
+{
+ if (!logfile.fp)
+ {
+ printf("no log file to close\n");
+ return;
+ } //end if
+ if (fclose(logfile.fp))
+ {
+ printf("can't close log file %s\n", logfile.filename);
+ return;
+ } //end if
+ logfile.fp = NULL;
+ printf("Closed log %s\n", logfile.filename);
+} //end of the function Log_Close
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Log_Shutdown(void)
+{
+ if (logfile.fp) Log_Close();
+} //end of the function Log_Shutdown
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Log_UnifyEndOfLine(char *buf)
+{
+ int i;
+
+ for (i = 0; buf[i]; i++)
+ {
+ if (buf[i] == '\n')
+ {
+ if (i <= 0 || buf[i-1] != '\r')
+ {
+ memmove(&buf[i+1], &buf[i], strlen(&buf[i])+1);
+ buf[i] = '\r';
+ i++;
+ } //end if
+ } //end if
+ } //end for
+} //end of the function Log_UnifyEndOfLine
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Log_Print(char *fmt, ...)
+{
+ va_list ap;
+ char buf[2048];
+
+ va_start(ap, fmt);
+ vsprintf(buf, fmt, ap);
+ va_end(ap);
+
+ if (verbose)
+ {
+#ifdef WINBSPC
+ WinBSPCPrint(buf);
+#else
+ printf("%s", buf);
+#endif //WINBSPS
+ } //end if
+
+ if (logfile.fp)
+ {
+ Log_UnifyEndOfLine(buf);
+ fprintf(logfile.fp, "%s", buf);
+ fflush(logfile.fp);
+ } //end if
+} //end of the function Log_Print
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Log_Write(char *fmt, ...)
+{
+ va_list ap;
+ char buf[2048];
+
+ if (!logfile.fp) return;
+ va_start(ap, fmt);
+ vsprintf(buf, fmt, ap);
+ va_end(ap);
+ Log_UnifyEndOfLine(buf);
+ fprintf(logfile.fp, "%s", buf);
+ fflush(logfile.fp);
+} //end of the function Log_Write
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Log_WriteTimeStamped(char *fmt, ...)
+{
+ va_list ap;
+
+ if (!logfile.fp) return;
+/* fprintf(logfile.fp, "%d %02d:%02d:%02d:%02d ",
+ logfile.numwrites,
+ (int) (botlibglobals.time / 60 / 60),
+ (int) (botlibglobals.time / 60),
+ (int) (botlibglobals.time),
+ (int) ((int) (botlibglobals.time * 100)) -
+ ((int) botlibglobals.time) * 100);*/
+ va_start(ap, fmt);
+ vfprintf(logfile.fp, fmt, ap);
+ va_end(ap);
+ logfile.numwrites++;
+ fflush(logfile.fp);
+} //end of the function Log_Write
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+FILE *Log_FileStruct(void)
+{
+ return logfile.fp;
+} //end of the function Log_FileStruct
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Log_Flush(void)
+{
+ if (logfile.fp) fflush(logfile.fp);
+} //end of the function Log_Flush
+
diff --git a/code/bspc/l_log.h b/code/bspc/l_log.h
new file mode 100755
index 0000000..eff7bf6
--- /dev/null
+++ b/code/bspc/l_log.h
@@ -0,0 +1,42 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+//open a log file
+void Log_Open(char *filename);
+//close the current log file
+void Log_Close(void);
+//close log file if present
+void Log_Shutdown(void);
+//print on stdout and write to the current opened log file
+void Log_Print(char *fmt, ...);
+//write to the current opened log file
+void Log_Write(char *fmt, ...);
+//write to the current opened log file with a time stamp
+void Log_WriteTimeStamped(char *fmt, ...);
+//returns the log file structure
+FILE *Log_FileStruct(void);
+//flush log file
+void Log_Flush(void);
+
+#ifdef WINBSPC
+void WinBSPCPrint(char *str);
+#endif //WINBSPC
diff --git a/code/bspc/l_math.c b/code/bspc/l_math.c
new file mode 100755
index 0000000..caf3419
--- /dev/null
+++ b/code/bspc/l_math.c
@@ -0,0 +1,289 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// mathlib.c -- math primitives
+
+#include "l_cmd.h"
+#include "l_math.h"
+
+vec3_t vec3_origin = {0,0,0};
+
+void AngleVectors (const vec3_t angles, vec3_t forward, vec3_t right, vec3_t up)
+{
+ float angle;
+ static float sr, sp, sy, cr, cp, cy;
+ // static to help MS compiler fp bugs
+
+ angle = angles[YAW] * (M_PI*2 / 360);
+ sy = sin(angle);
+ cy = cos(angle);
+ angle = angles[PITCH] * (M_PI*2 / 360);
+ sp = sin(angle);
+ cp = cos(angle);
+ angle = angles[ROLL] * (M_PI*2 / 360);
+ sr = sin(angle);
+ cr = cos(angle);
+
+ if (forward)
+ {
+ forward[0] = cp*cy;
+ forward[1] = cp*sy;
+ forward[2] = -sp;
+ }
+ if (right)
+ {
+ right[0] = (-1*sr*sp*cy+-1*cr*-sy);
+ right[1] = (-1*sr*sp*sy+-1*cr*cy);
+ right[2] = -1*sr*cp;
+ }
+ if (up)
+ {
+ up[0] = (cr*sp*cy+-sr*-sy);
+ up[1] = (cr*sp*sy+-sr*cy);
+ up[2] = cr*cp;
+ }
+}
+
+/*
+=================
+RadiusFromBounds
+=================
+*/
+float RadiusFromBounds( const vec3_t mins, const vec3_t maxs ) {
+ int i;
+ vec3_t corner;
+ float a, b;
+
+ for (i=0 ; i<3 ; i++) {
+ a = fabs( mins[i] );
+ b = fabs( maxs[i] );
+ corner[i] = a > b ? a : b;
+ }
+
+ return VectorLength (corner);
+}
+
+/*
+================
+R_ConcatRotations
+================
+*/
+void R_ConcatRotations (float in1[3][3], float in2[3][3], float out[3][3])
+{
+ out[0][0] = in1[0][0] * in2[0][0] + in1[0][1] * in2[1][0] +
+ in1[0][2] * in2[2][0];
+ out[0][1] = in1[0][0] * in2[0][1] + in1[0][1] * in2[1][1] +
+ in1[0][2] * in2[2][1];
+ out[0][2] = in1[0][0] * in2[0][2] + in1[0][1] * in2[1][2] +
+ in1[0][2] * in2[2][2];
+ out[1][0] = in1[1][0] * in2[0][0] + in1[1][1] * in2[1][0] +
+ in1[1][2] * in2[2][0];
+ out[1][1] = in1[1][0] * in2[0][1] + in1[1][1] * in2[1][1] +
+ in1[1][2] * in2[2][1];
+ out[1][2] = in1[1][0] * in2[0][2] + in1[1][1] * in2[1][2] +
+ in1[1][2] * in2[2][2];
+ out[2][0] = in1[2][0] * in2[0][0] + in1[2][1] * in2[1][0] +
+ in1[2][2] * in2[2][0];
+ out[2][1] = in1[2][0] * in2[0][1] + in1[2][1] * in2[1][1] +
+ in1[2][2] * in2[2][1];
+ out[2][2] = in1[2][0] * in2[0][2] + in1[2][1] * in2[1][2] +
+ in1[2][2] * in2[2][2];
+}
+
+void AxisClear( vec3_t axis[3] ) {
+ axis[0][0] = 1;
+ axis[0][1] = 0;
+ axis[0][2] = 0;
+ axis[1][0] = 0;
+ axis[1][1] = 1;
+ axis[1][2] = 0;
+ axis[2][0] = 0;
+ axis[2][1] = 0;
+ axis[2][2] = 1;
+}
+
+float VectorLengthSquared(vec3_t v) {
+ return DotProduct(v, v);
+}
+
+double VectorLength(vec3_t v)
+{
+ int i;
+ double length;
+
+ length = 0;
+ for (i=0 ; i< 3 ; i++)
+ length += v[i]*v[i];
+ length = sqrt (length); // FIXME
+
+ return length;
+}
+
+qboolean VectorCompare (vec3_t v1, vec3_t v2)
+{
+ int i;
+
+ for (i=0 ; i<3 ; i++)
+ if (fabs(v1[i]-v2[i]) > EQUAL_EPSILON)
+ return false;
+
+ return true;
+}
+
+vec_t Q_rint (vec_t in)
+{
+ return floor(in + 0.5);
+}
+
+void CrossProduct (const vec3_t v1, const vec3_t v2, vec3_t cross)
+{
+ cross[0] = v1[1]*v2[2] - v1[2]*v2[1];
+ cross[1] = v1[2]*v2[0] - v1[0]*v2[2];
+ cross[2] = v1[0]*v2[1] - v1[1]*v2[0];
+}
+
+void _VectorMA (vec3_t va, double scale, vec3_t vb, vec3_t vc)
+{
+ vc[0] = va[0] + scale*vb[0];
+ vc[1] = va[1] + scale*vb[1];
+ vc[2] = va[2] + scale*vb[2];
+}
+
+vec_t _DotProduct (vec3_t v1, vec3_t v2)
+{
+ return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2];
+}
+
+void _VectorSubtract (vec3_t va, vec3_t vb, vec3_t out)
+{
+ out[0] = va[0]-vb[0];
+ out[1] = va[1]-vb[1];
+ out[2] = va[2]-vb[2];
+}
+
+void _VectorAdd (vec3_t va, vec3_t vb, vec3_t out)
+{
+ out[0] = va[0]+vb[0];
+ out[1] = va[1]+vb[1];
+ out[2] = va[2]+vb[2];
+}
+
+void _VectorCopy (vec3_t in, vec3_t out)
+{
+ out[0] = in[0];
+ out[1] = in[1];
+ out[2] = in[2];
+}
+
+void _VectorScale (vec3_t v, vec_t scale, vec3_t out)
+{
+ out[0] = v[0] * scale;
+ out[1] = v[1] * scale;
+ out[2] = v[2] * scale;
+}
+
+vec_t VectorNormalize(vec3_t inout)
+{
+ vec_t length, ilength;
+
+ length = sqrt (inout[0]*inout[0] + inout[1]*inout[1] + inout[2]*inout[2]);
+ if (length == 0)
+ {
+ VectorClear (inout);
+ return 0;
+ }
+
+ ilength = 1.0/length;
+ inout[0] = inout[0]*ilength;
+ inout[1] = inout[1]*ilength;
+ inout[2] = inout[2]*ilength;
+
+ return length;
+}
+
+vec_t VectorNormalize2(const vec3_t in, vec3_t out)
+{
+ vec_t length, ilength;
+
+ length = sqrt (in[0]*in[0] + in[1]*in[1] + in[2]*in[2]);
+ if (length == 0)
+ {
+ VectorClear (out);
+ return 0;
+ }
+
+ ilength = 1.0/length;
+ out[0] = in[0]*ilength;
+ out[1] = in[1]*ilength;
+ out[2] = in[2]*ilength;
+
+ return length;
+}
+
+vec_t ColorNormalize (vec3_t in, vec3_t out)
+{
+ float max, scale;
+
+ max = in[0];
+ if (in[1] > max)
+ max = in[1];
+ if (in[2] > max)
+ max = in[2];
+
+ if (max == 0)
+ return 0;
+
+ scale = 1.0 / max;
+
+ VectorScale (in, scale, out);
+
+ return max;
+}
+
+
+
+void VectorInverse (vec3_t v)
+{
+ v[0] = -v[0];
+ v[1] = -v[1];
+ v[2] = -v[2];
+}
+
+void ClearBounds(vec3_t mins, vec3_t maxs)
+{
+ mins[0] = mins[1] = mins[2] = 99999;
+ maxs[0] = maxs[1] = maxs[2] = -99999;
+}
+
+void AddPointToBounds(const vec3_t v, vec3_t mins, vec3_t maxs)
+{
+ int i;
+ vec_t val;
+
+ for (i=0 ; i<3 ; i++)
+ {
+ val = v[i];
+ if (val < mins[i])
+ mins[i] = val;
+ if (val > maxs[i])
+ maxs[i] = val;
+ }
+}
diff --git a/code/bspc/l_math.h b/code/bspc/l_math.h
new file mode 100755
index 0000000..1df7b61
--- /dev/null
+++ b/code/bspc/l_math.h
@@ -0,0 +1,93 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __MATHLIB__
+#define __MATHLIB__
+
+// mathlib.h
+
+#include <math.h>
+
+#ifdef DOUBLEVEC_T
+typedef double vec_t;
+#else
+typedef float vec_t;
+#endif
+typedef vec_t vec3_t[3];
+typedef vec_t vec4_t[4];
+
+#define SIDE_FRONT 0
+#define SIDE_ON 2
+#define SIDE_BACK 1
+#define SIDE_CROSS -2
+
+#define PITCH 0
+#define YAW 1
+#define ROLL 2
+
+#define Q_PI 3.14159265358979323846
+
+#define DEG2RAD( a ) ( a * M_PI ) / 180.0F
+
+#ifndef M_PI
+#define M_PI 3.14159265358979323846 // matches value in gcc v2 math.h
+#endif
+
+extern vec3_t vec3_origin;
+
+#define EQUAL_EPSILON 0.001
+
+qboolean VectorCompare (vec3_t v1, vec3_t v2);
+
+#define DotProduct(x,y) (x[0]*y[0]+x[1]*y[1]+x[2]*y[2])
+#define VectorSubtract(a,b,c) {c[0]=a[0]-b[0];c[1]=a[1]-b[1];c[2]=a[2]-b[2];}
+#define VectorAdd(a,b,c) {c[0]=a[0]+b[0];c[1]=a[1]+b[1];c[2]=a[2]+b[2];}
+#define VectorCopy(a,b) {b[0]=a[0];b[1]=a[1];b[2]=a[2];}
+#define Vector4Copy(a,b) {b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];}
+#define VectorScale(v, s, o) ((o)[0]=(v)[0]*(s),(o)[1]=(v)[1]*(s),(o)[2]=(v)[2]*(s))
+#define VectorClear(x) {x[0] = x[1] = x[2] = 0;}
+#define VectorNegate(x, y) {y[0]=-x[0];y[1]=-x[1];y[2]=-x[2];}
+#define VectorMA(v, s, b, o) ((o)[0]=(v)[0]+(b)[0]*(s),(o)[1]=(v)[1]+(b)[1]*(s),(o)[2]=(v)[2]+(b)[2]*(s))
+
+vec_t Q_rint (vec_t in);
+vec_t _DotProduct (vec3_t v1, vec3_t v2);
+void _VectorSubtract (vec3_t va, vec3_t vb, vec3_t out);
+void _VectorAdd (vec3_t va, vec3_t vb, vec3_t out);
+void _VectorCopy (vec3_t in, vec3_t out);
+void _VectorScale (vec3_t v, vec_t scale, vec3_t out);
+void _VectorMA(vec3_t va, double scale, vec3_t vb, vec3_t vc);
+
+double VectorLength(vec3_t v);
+void CrossProduct(const vec3_t v1, const vec3_t v2, vec3_t cross);
+vec_t VectorNormalize(vec3_t inout);
+vec_t ColorNormalize(vec3_t in, vec3_t out);
+vec_t VectorNormalize2(const vec3_t v, vec3_t out);
+void VectorInverse (vec3_t v);
+
+void ClearBounds (vec3_t mins, vec3_t maxs);
+void AddPointToBounds (const vec3_t v, vec3_t mins, vec3_t maxs);
+
+void AngleVectors (const vec3_t angles, vec3_t forward, vec3_t right, vec3_t up);
+void R_ConcatRotations (float in1[3][3], float in2[3][3], float out[3][3]);
+void RotatePoint(vec3_t point, float matrix[3][3]);
+void CreateRotationMatrix(vec3_t angles, float matrix[3][3]);
+
+#endif
diff --git a/code/bspc/l_mem.c b/code/bspc/l_mem.c
new file mode 100755
index 0000000..831543e
--- /dev/null
+++ b/code/bspc/l_mem.c
@@ -0,0 +1,441 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+#include "l_log.h"
+
+int allocedmemory;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void PrintMemorySize(unsigned long size)
+{
+ unsigned long number1, number2, number3;
+ number1 = size >> 20;
+ number2 = (size & 0xFFFFF) >> 10;
+ number3 = (size & 0x3FF);
+ if (number1) Log_Print("%ld MB", number1);
+ if (number1 && number2) Log_Print(" and ");
+ if (number2) Log_Print("%ld KB", number2);
+ if (number2 && number3) Log_Print(" and ");
+ if (number3) Log_Print("%ld bytes", number3);
+} //end of the function PrintFileSize
+
+#ifndef MEMDEBUG
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int MemorySize(void *ptr)
+{
+#if defined(WIN32) || defined(_WIN32)
+ #ifdef __WATCOMC__
+ //Intel 32 bits memory addressing, 16 bytes aligned
+ return (_msize(ptr) + 15) >> 4 << 4;
+ #else
+ return _msize(ptr);
+ #endif
+#else
+ return 0;
+#endif
+} //end of the function MemorySize
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void *GetClearedMemory(int size)
+{
+ void *ptr;
+
+ ptr = (void *) malloc(size);
+ if (!ptr) Error("out of memory");
+ memset(ptr, 0, size);
+ allocedmemory += MemorySize(ptr);
+ return ptr;
+} //end of the function GetClearedMemory
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void *GetMemory(unsigned long size)
+{
+ void *ptr;
+ ptr = malloc(size);
+ if (!ptr) Error("out of memory");
+ allocedmemory += MemorySize(ptr);
+ return ptr;
+} //end of the function GetMemory
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void FreeMemory(void *ptr)
+{
+ allocedmemory -= MemorySize(ptr);
+ free(ptr);
+} //end of the function FreeMemory
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TotalAllocatedMemory(void)
+{
+ return allocedmemory;
+} //end of the function TotalAllocatedMemory
+
+#else
+
+#define MEM_ID 0x12345678l
+
+int totalmemorysize;
+int numblocks;
+
+typedef struct memoryblock_s
+{
+ unsigned long int id;
+ void *ptr;
+ int size;
+#ifdef MEMDEBUG
+ char *label;
+ char *file;
+ int line;
+#endif //MEMDEBUG
+ struct memoryblock_s *prev, *next;
+} memoryblock_t;
+
+memoryblock_t *memory;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void LinkMemoryBlock(memoryblock_t *block)
+{
+ block->prev = NULL;
+ block->next = memory;
+ if (memory) memory->prev = block;
+ memory = block;
+} //end of the function LinkMemoryBlock
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void UnlinkMemoryBlock(memoryblock_t *block)
+{
+ if (block->prev) block->prev->next = block->next;
+ else memory = block->next;
+ if (block->next) block->next->prev = block->prev;
+} //end of the function UnlinkMemoryBlock
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+#ifdef MEMDEBUG
+void *GetMemoryDebug(unsigned long size, char *label, char *file, int line)
+#else
+void *GetMemory(unsigned long size)
+#endif //MEMDEBUG
+{
+ void *ptr;
+ memoryblock_t *block;
+
+ ptr = malloc(size + sizeof(memoryblock_t));
+ block = (memoryblock_t *) ptr;
+ block->id = MEM_ID;
+ block->ptr = (char *) ptr + sizeof(memoryblock_t);
+ block->size = size + sizeof(memoryblock_t);
+#ifdef MEMDEBUG
+ block->label = label;
+ block->file = file;
+ block->line = line;
+#endif //MEMDEBUG
+ LinkMemoryBlock(block);
+ totalmemorysize += block->size;
+ numblocks++;
+ return block->ptr;
+} //end of the function GetMemoryDebug
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+#ifdef MEMDEBUG
+void *GetClearedMemoryDebug(unsigned long size, char *label, char *file, int line)
+#else
+void *GetClearedMemory(unsigned long size)
+#endif //MEMDEBUG
+{
+ void *ptr;
+#ifdef MEMDEBUG
+ ptr = GetMemoryDebug(size, label, file, line);
+#else
+ ptr = GetMemory(size);
+#endif //MEMDEBUG
+ memset(ptr, 0, size);
+ return ptr;
+} //end of the function GetClearedMemoryLabelled
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void *GetClearedHunkMemory(unsigned long size)
+{
+ return GetClearedMemory(size);
+} //end of the function GetClearedHunkMemory
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void *GetHunkMemory(unsigned long size)
+{
+ return GetMemory(size);
+} //end of the function GetHunkMemory
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+memoryblock_t *BlockFromPointer(void *ptr, char *str)
+{
+ memoryblock_t *block;
+
+ if (!ptr)
+ {
+#ifdef MEMDEBUG
+ //char *crash = (char *) NULL;
+ //crash[0] = 1;
+ Error("%s: NULL pointer\n", str);
+#endif MEMDEBUG
+ return NULL;
+ } //end if
+ block = (memoryblock_t *) ((char *) ptr - sizeof(memoryblock_t));
+ if (block->id != MEM_ID)
+ {
+ Error("%s: invalid memory block\n", str);
+ } //end if
+ if (block->ptr != ptr)
+ {
+
+ Error("%s: memory block pointer invalid\n", str);
+ } //end if
+ return block;
+} //end of the function BlockFromPointer
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void FreeMemory(void *ptr)
+{
+ memoryblock_t *block;
+
+ block = BlockFromPointer(ptr, "FreeMemory");
+ if (!block) return;
+ UnlinkMemoryBlock(block);
+ totalmemorysize -= block->size;
+ numblocks--;
+ //
+ free(block);
+} //end of the function FreeMemory
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int MemoryByteSize(void *ptr)
+{
+ memoryblock_t *block;
+
+ block = BlockFromPointer(ptr, "MemoryByteSize");
+ if (!block) return 0;
+ return block->size;
+} //end of the function MemoryByteSize
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int MemorySize(void *ptr)
+{
+ return MemoryByteSize(ptr);
+} //end of the function MemorySize
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void PrintUsedMemorySize(void)
+{
+ printf("total botlib memory: %d KB\n", totalmemorysize >> 10);
+ printf("total memory blocks: %d\n", numblocks);
+} //end of the function PrintUsedMemorySize
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void PrintMemoryLabels(void)
+{
+ memoryblock_t *block;
+ int i;
+
+ PrintUsedMemorySize();
+ i = 0;
+ for (block = memory; block; block = block->next)
+ {
+#ifdef MEMDEBUG
+ Log_Write("%6d, %p, %8d: %24s line %6d: %s", i, block->ptr, block->size, block->file, block->line, block->label);
+#endif //MEMDEBUG
+ i++;
+ } //end for
+} //end of the function PrintMemoryLabels
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void DumpMemory(void)
+{
+ memoryblock_t *block;
+
+ for (block = memory; block; block = memory)
+ {
+ FreeMemory(block->ptr);
+ } //end for
+ totalmemorysize = 0;
+} //end of the function DumpMemory
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TotalAllocatedMemory(void)
+{
+ return totalmemorysize;
+} //end of the function TotalAllocatedMemory
+#endif
+
+//===========================================================================
+// Q3 Hunk and Z_ memory management
+//===========================================================================
+
+typedef struct memhunk_s
+{
+ void *ptr;
+ struct memhunk_s *next;
+} memhunk_t;
+
+memhunk_t *memhunk_high;
+memhunk_t *memhunk_low;
+int memhunk_high_size = 16 * 1024 * 1024;
+int memhunk_low_size = 0;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Hunk_ClearHigh(void)
+{
+ memhunk_t *h, *nexth;
+
+ for (h = memhunk_high; h; h = nexth)
+ {
+ nexth = h->next;
+ FreeMemory(h);
+ } //end for
+ memhunk_high = NULL;
+ memhunk_high_size = 16 * 1024 * 1024;
+} //end of the function Hunk_ClearHigh
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void *Hunk_Alloc(int size)
+{
+ memhunk_t *h;
+
+ if (!size) return (void *) memhunk_high_size;
+ //
+ h = GetClearedMemory(size + sizeof(memhunk_t));
+ h->ptr = (char *) h + sizeof(memhunk_t);
+ h->next = memhunk_high;
+ memhunk_high = h;
+ memhunk_high_size -= size;
+ return h->ptr;
+} //end of the function Hunk_Alloc
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void *Z_Malloc(int size)
+{
+ return GetClearedMemory(size);
+} //end of the function Z_Malloc
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Z_Free (void *ptr)
+{
+ FreeMemory(ptr);
+} //end of the function Z_Free
diff --git a/code/bspc/l_mem.h b/code/bspc/l_mem.h
new file mode 100755
index 0000000..d517743
--- /dev/null
+++ b/code/bspc/l_mem.h
@@ -0,0 +1,51 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+
+//=============================================================================
+
+// memory.h
+//#define MEMDEBUG
+#undef MEMDEBUG
+
+#ifndef MEMDEBUG
+
+void *GetClearedMemory(int size);
+void *GetMemory(unsigned long size);
+
+#else
+
+#define GetMemory(size) GetMemoryDebug(size, #size, __FILE__, __LINE__);
+#define GetClearedMemory(size) GetClearedMemoryDebug(size, #size, __FILE__, __LINE__);
+//allocate a memory block of the given size
+void *GetMemoryDebug(unsigned long size, char *label, char *file, int line);
+//allocate a memory block of the given size and clear it
+void *GetClearedMemoryDebug(unsigned long size, char *label, char *file, int line);
+//
+void PrintMemoryLabels(void);
+#endif //MEMDEBUG
+
+void FreeMemory(void *ptr);
+int MemorySize(void *ptr);
+void PrintMemorySize(unsigned long size);
+int TotalAllocatedMemory(void);
+
diff --git a/code/bspc/l_poly.c b/code/bspc/l_poly.c
new file mode 100755
index 0000000..fea2bef
--- /dev/null
+++ b/code/bspc/l_poly.c
@@ -0,0 +1,1411 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include <malloc.h>
+#include "l_cmd.h"
+#include "l_math.h"
+#include "l_poly.h"
+#include "l_log.h"
+#include "l_mem.h"
+
+#define BOGUS_RANGE 65535
+
+extern int numthreads;
+
+// counters are only bumped when running single threaded,
+// because they are an awefull coherence problem
+int c_active_windings;
+int c_peak_windings;
+int c_winding_allocs;
+int c_winding_points;
+int c_windingmemory;
+int c_peak_windingmemory;
+
+char windingerror[1024];
+
+void pw(winding_t *w)
+{
+ int i;
+ for (i=0 ; i<w->numpoints ; i++)
+ printf ("(%5.3f, %5.3f, %5.3f)\n",w->p[i][0], w->p[i][1],w->p[i][2]);
+}
+
+
+void ResetWindings(void)
+{
+ c_active_windings = 0;
+ c_peak_windings = 0;
+ c_winding_allocs = 0;
+ c_winding_points = 0;
+ c_windingmemory = 0;
+ c_peak_windingmemory = 0;
+
+ strcpy(windingerror, "");
+} //end of the function ResetWindings
+/*
+=============
+AllocWinding
+=============
+*/
+winding_t *AllocWinding (int points)
+{
+ winding_t *w;
+ int s;
+
+ s = sizeof(vec_t)*3*points + sizeof(int);
+ w = GetMemory(s);
+ memset(w, 0, s);
+
+ if (numthreads == 1)
+ {
+ c_winding_allocs++;
+ c_winding_points += points;
+ c_active_windings++;
+ if (c_active_windings > c_peak_windings)
+ c_peak_windings = c_active_windings;
+ c_windingmemory += MemorySize(w);
+ if (c_windingmemory > c_peak_windingmemory)
+ c_peak_windingmemory = c_windingmemory;
+ } //end if
+ return w;
+} //end of the function AllocWinding
+
+void FreeWinding (winding_t *w)
+{
+ if (*(unsigned *)w == 0xdeaddead)
+ Error ("FreeWinding: freed a freed winding");
+
+ if (numthreads == 1)
+ {
+ c_active_windings--;
+ c_windingmemory -= MemorySize(w);
+ } //end if
+
+ *(unsigned *)w = 0xdeaddead;
+
+ FreeMemory(w);
+} //end of the function FreeWinding
+
+int WindingMemory(void)
+{
+ return c_windingmemory;
+} //end of the function WindingMemory
+
+int WindingPeakMemory(void)
+{
+ return c_peak_windingmemory;
+} //end of the function WindingPeakMemory
+
+int ActiveWindings(void)
+{
+ return c_active_windings;
+} //end of the function ActiveWindings
+/*
+============
+RemoveColinearPoints
+============
+*/
+int c_removed;
+
+void RemoveColinearPoints (winding_t *w)
+{
+ int i, j, k;
+ vec3_t v1, v2;
+ int nump;
+ vec3_t p[MAX_POINTS_ON_WINDING];
+
+ nump = 0;
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ j = (i+1)%w->numpoints;
+ k = (i+w->numpoints-1)%w->numpoints;
+ VectorSubtract (w->p[j], w->p[i], v1);
+ VectorSubtract (w->p[i], w->p[k], v2);
+ VectorNormalize(v1);
+ VectorNormalize(v2);
+ if (DotProduct(v1, v2) < 0.999)
+ {
+ if (nump >= MAX_POINTS_ON_WINDING)
+ Error("RemoveColinearPoints: MAX_POINTS_ON_WINDING");
+ VectorCopy (w->p[i], p[nump]);
+ nump++;
+ }
+ }
+
+ if (nump == w->numpoints)
+ return;
+
+ if (numthreads == 1)
+ c_removed += w->numpoints - nump;
+ w->numpoints = nump;
+ memcpy (w->p, p, nump*sizeof(p[0]));
+}
+
+/*
+============
+WindingPlane
+============
+*/
+void WindingPlane (winding_t *w, vec3_t normal, vec_t *dist)
+{
+ vec3_t v1, v2;
+ int i;
+
+ //find two vectors each longer than 0.5 units
+ for (i = 0; i < w->numpoints; i++)
+ {
+ VectorSubtract(w->p[(i+1) % w->numpoints], w->p[i], v1);
+ VectorSubtract(w->p[(i+2) % w->numpoints], w->p[i], v2);
+ if (VectorLength(v1) > 0.5 && VectorLength(v2) > 0.5) break;
+ } //end for
+ CrossProduct(v2, v1, normal);
+ VectorNormalize(normal);
+ *dist = DotProduct(w->p[0], normal);
+} //end of the function WindingPlane
+
+/*
+=============
+WindingArea
+=============
+*/
+vec_t WindingArea (winding_t *w)
+{
+ int i;
+ vec3_t d1, d2, cross;
+ vec_t total;
+
+ total = 0;
+ for (i=2 ; i<w->numpoints ; i++)
+ {
+ VectorSubtract (w->p[i-1], w->p[0], d1);
+ VectorSubtract (w->p[i], w->p[0], d2);
+ CrossProduct (d1, d2, cross);
+ total += 0.5 * VectorLength ( cross );
+ }
+ return total;
+}
+
+void WindingBounds (winding_t *w, vec3_t mins, vec3_t maxs)
+{
+ vec_t v;
+ int i,j;
+
+ mins[0] = mins[1] = mins[2] = 99999;
+ maxs[0] = maxs[1] = maxs[2] = -99999;
+
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ for (j=0 ; j<3 ; j++)
+ {
+ v = w->p[i][j];
+ if (v < mins[j])
+ mins[j] = v;
+ if (v > maxs[j])
+ maxs[j] = v;
+ }
+ }
+}
+
+/*
+=============
+WindingCenter
+=============
+*/
+void WindingCenter (winding_t *w, vec3_t center)
+{
+ int i;
+ float scale;
+
+ VectorCopy (vec3_origin, center);
+ for (i=0 ; i<w->numpoints ; i++)
+ VectorAdd (w->p[i], center, center);
+
+ scale = 1.0/w->numpoints;
+ VectorScale (center, scale, center);
+}
+
+/*
+=================
+BaseWindingForPlane
+=================
+*/
+winding_t *BaseWindingForPlane (vec3_t normal, vec_t dist)
+{
+ int i, x;
+ vec_t max, v;
+ vec3_t org, vright, vup;
+ winding_t *w;
+
+// find the major axis
+
+ max = -BOGUS_RANGE;
+ x = -1;
+ for (i=0 ; i<3; i++)
+ {
+ v = fabs(normal[i]);
+ if (v > max)
+ {
+ x = i;
+ max = v;
+ }
+ }
+ if (x==-1)
+ Error ("BaseWindingForPlane: no axis found");
+
+ VectorCopy (vec3_origin, vup);
+ switch (x)
+ {
+ case 0:
+ case 1:
+ vup[2] = 1;
+ break;
+ case 2:
+ vup[0] = 1;
+ break;
+ }
+
+ v = DotProduct (vup, normal);
+ VectorMA (vup, -v, normal, vup);
+ VectorNormalize (vup);
+
+ VectorScale (normal, dist, org);
+
+ CrossProduct (vup, normal, vright);
+
+ VectorScale (vup, BOGUS_RANGE, vup);
+ VectorScale (vright, BOGUS_RANGE, vright);
+
+// project a really big axis aligned box onto the plane
+ w = AllocWinding (4);
+
+ VectorSubtract (org, vright, w->p[0]);
+ VectorAdd (w->p[0], vup, w->p[0]);
+
+ VectorAdd (org, vright, w->p[1]);
+ VectorAdd (w->p[1], vup, w->p[1]);
+
+ VectorAdd (org, vright, w->p[2]);
+ VectorSubtract (w->p[2], vup, w->p[2]);
+
+ VectorSubtract (org, vright, w->p[3]);
+ VectorSubtract (w->p[3], vup, w->p[3]);
+
+ w->numpoints = 4;
+
+ return w;
+}
+
+/*
+==================
+CopyWinding
+==================
+*/
+winding_t *CopyWinding (winding_t *w)
+{
+ int size;
+ winding_t *c;
+
+ c = AllocWinding (w->numpoints);
+ size = (int)((winding_t *)0)->p[w->numpoints];
+ memcpy (c, w, size);
+ return c;
+}
+
+/*
+==================
+ReverseWinding
+==================
+*/
+winding_t *ReverseWinding (winding_t *w)
+{
+ int i;
+ winding_t *c;
+
+ c = AllocWinding (w->numpoints);
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ VectorCopy (w->p[w->numpoints-1-i], c->p[i]);
+ }
+ c->numpoints = w->numpoints;
+ return c;
+}
+
+
+/*
+=============
+ClipWindingEpsilon
+=============
+*/
+void ClipWindingEpsilon (winding_t *in, vec3_t normal, vec_t dist,
+ vec_t epsilon, winding_t **front, winding_t **back)
+{
+ vec_t dists[MAX_POINTS_ON_WINDING+4];
+ int sides[MAX_POINTS_ON_WINDING+4];
+ int counts[3];
+ //MrElusive: DOH can't use statics when unsing multithreading!!!
+ vec_t dot; // VC 4.2 optimizer bug if not static
+ int i, j;
+ vec_t *p1, *p2;
+ vec3_t mid;
+ winding_t *f, *b;
+ int maxpts;
+
+ counts[0] = counts[1] = counts[2] = 0;
+
+// determine sides for each point
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ dot = DotProduct (in->p[i], normal);
+ dot -= dist;
+ dists[i] = dot;
+ if (dot > epsilon)
+ sides[i] = SIDE_FRONT;
+ else if (dot < -epsilon)
+ sides[i] = SIDE_BACK;
+ else
+ {
+ sides[i] = SIDE_ON;
+ }
+ counts[sides[i]]++;
+ }
+ sides[i] = sides[0];
+ dists[i] = dists[0];
+
+ *front = *back = NULL;
+
+ if (!counts[0])
+ {
+ *back = CopyWinding (in);
+ return;
+ }
+ if (!counts[1])
+ {
+ *front = CopyWinding (in);
+ return;
+ }
+
+ maxpts = in->numpoints+4; // cant use counts[0]+2 because
+ // of fp grouping errors
+
+ *front = f = AllocWinding (maxpts);
+ *back = b = AllocWinding (maxpts);
+
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ p1 = in->p[i];
+
+ if (sides[i] == SIDE_ON)
+ {
+ VectorCopy (p1, f->p[f->numpoints]);
+ f->numpoints++;
+ VectorCopy (p1, b->p[b->numpoints]);
+ b->numpoints++;
+ continue;
+ }
+
+ if (sides[i] == SIDE_FRONT)
+ {
+ VectorCopy (p1, f->p[f->numpoints]);
+ f->numpoints++;
+ }
+ if (sides[i] == SIDE_BACK)
+ {
+ VectorCopy (p1, b->p[b->numpoints]);
+ b->numpoints++;
+ }
+
+ if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i])
+ continue;
+
+ // generate a split point
+ p2 = in->p[(i+1)%in->numpoints];
+
+ dot = dists[i] / (dists[i]-dists[i+1]);
+ for (j=0 ; j<3 ; j++)
+ { // avoid round off error when possible
+ if (normal[j] == 1)
+ mid[j] = dist;
+ else if (normal[j] == -1)
+ mid[j] = -dist;
+ else
+ mid[j] = p1[j] + dot*(p2[j]-p1[j]);
+ }
+
+ VectorCopy (mid, f->p[f->numpoints]);
+ f->numpoints++;
+ VectorCopy (mid, b->p[b->numpoints]);
+ b->numpoints++;
+ }
+
+ if (f->numpoints > maxpts || b->numpoints > maxpts)
+ Error ("ClipWinding: points exceeded estimate");
+ if (f->numpoints > MAX_POINTS_ON_WINDING || b->numpoints > MAX_POINTS_ON_WINDING)
+ Error ("ClipWinding: MAX_POINTS_ON_WINDING");
+}
+
+
+/*
+=============
+ChopWindingInPlace
+=============
+*/
+void ChopWindingInPlace (winding_t **inout, vec3_t normal, vec_t dist, vec_t epsilon)
+{
+ winding_t *in;
+ vec_t dists[MAX_POINTS_ON_WINDING+4];
+ int sides[MAX_POINTS_ON_WINDING+4];
+ int counts[3];
+ //MrElusive: DOH can't use statics when unsing multithreading!!!
+ vec_t dot; // VC 4.2 optimizer bug if not static
+ int i, j;
+ vec_t *p1, *p2;
+ vec3_t mid;
+ winding_t *f;
+ int maxpts;
+
+ in = *inout;
+ counts[0] = counts[1] = counts[2] = 0;
+
+// determine sides for each point
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ dot = DotProduct (in->p[i], normal);
+ dot -= dist;
+ dists[i] = dot;
+ if (dot > epsilon)
+ sides[i] = SIDE_FRONT;
+ else if (dot < -epsilon)
+ sides[i] = SIDE_BACK;
+ else
+ {
+ sides[i] = SIDE_ON;
+ }
+ counts[sides[i]]++;
+ }
+ sides[i] = sides[0];
+ dists[i] = dists[0];
+
+ if (!counts[0])
+ {
+ FreeWinding (in);
+ *inout = NULL;
+ return;
+ }
+ if (!counts[1])
+ return; // inout stays the same
+
+ maxpts = in->numpoints+4; // cant use counts[0]+2 because
+ // of fp grouping errors
+
+ f = AllocWinding (maxpts);
+
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ p1 = in->p[i];
+
+ if (sides[i] == SIDE_ON)
+ {
+ VectorCopy (p1, f->p[f->numpoints]);
+ f->numpoints++;
+ continue;
+ }
+
+ if (sides[i] == SIDE_FRONT)
+ {
+ VectorCopy (p1, f->p[f->numpoints]);
+ f->numpoints++;
+ }
+
+ if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i])
+ continue;
+
+ // generate a split point
+ p2 = in->p[(i+1)%in->numpoints];
+
+ dot = dists[i] / (dists[i]-dists[i+1]);
+ for (j=0 ; j<3 ; j++)
+ { // avoid round off error when possible
+ if (normal[j] == 1)
+ mid[j] = dist;
+ else if (normal[j] == -1)
+ mid[j] = -dist;
+ else
+ mid[j] = p1[j] + dot*(p2[j]-p1[j]);
+ }
+
+ VectorCopy (mid, f->p[f->numpoints]);
+ f->numpoints++;
+ }
+
+ if (f->numpoints > maxpts)
+ Error ("ClipWinding: points exceeded estimate");
+ if (f->numpoints > MAX_POINTS_ON_WINDING)
+ Error ("ClipWinding: MAX_POINTS_ON_WINDING");
+
+ FreeWinding (in);
+ *inout = f;
+}
+
+
+/*
+=================
+ChopWinding
+
+Returns the fragment of in that is on the front side
+of the cliping plane. The original is freed.
+=================
+*/
+winding_t *ChopWinding (winding_t *in, vec3_t normal, vec_t dist)
+{
+ winding_t *f, *b;
+
+ ClipWindingEpsilon (in, normal, dist, ON_EPSILON, &f, &b);
+ FreeWinding (in);
+ if (b)
+ FreeWinding (b);
+ return f;
+}
+
+
+/*
+=================
+CheckWinding
+
+=================
+*/
+void CheckWinding (winding_t *w)
+{
+ int i, j;
+ vec_t *p1, *p2;
+ vec_t d, edgedist;
+ vec3_t dir, edgenormal, facenormal;
+ vec_t area;
+ vec_t facedist;
+
+ if (w->numpoints < 3)
+ Error ("CheckWinding: %i points",w->numpoints);
+
+ area = WindingArea(w);
+ if (area < 1)
+ Error ("CheckWinding: %f area", area);
+
+ WindingPlane (w, facenormal, &facedist);
+
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ p1 = w->p[i];
+
+ for (j=0 ; j<3 ; j++)
+ if (p1[j] > BOGUS_RANGE || p1[j] < -BOGUS_RANGE)
+ Error ("CheckWinding: BUGUS_RANGE: %f",p1[j]);
+
+ j = i+1 == w->numpoints ? 0 : i+1;
+
+ // check the point is on the face plane
+ d = DotProduct (p1, facenormal) - facedist;
+ if (d < -ON_EPSILON || d > ON_EPSILON)
+ Error ("CheckWinding: point off plane");
+
+ // check the edge isnt degenerate
+ p2 = w->p[j];
+ VectorSubtract (p2, p1, dir);
+
+ if (VectorLength (dir) < ON_EPSILON)
+ Error ("CheckWinding: degenerate edge");
+
+ CrossProduct (facenormal, dir, edgenormal);
+ VectorNormalize (edgenormal);
+ edgedist = DotProduct (p1, edgenormal);
+ edgedist += ON_EPSILON;
+
+ // all other points must be on front side
+ for (j=0 ; j<w->numpoints ; j++)
+ {
+ if (j == i)
+ continue;
+ d = DotProduct (w->p[j], edgenormal);
+ if (d > edgedist)
+ Error ("CheckWinding: non-convex");
+ }
+ }
+}
+
+
+/*
+============
+WindingOnPlaneSide
+============
+*/
+int WindingOnPlaneSide (winding_t *w, vec3_t normal, vec_t dist)
+{
+ qboolean front, back;
+ int i;
+ vec_t d;
+
+ front = false;
+ back = false;
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ d = DotProduct (w->p[i], normal) - dist;
+ if (d < -ON_EPSILON)
+ {
+ if (front)
+ return SIDE_CROSS;
+ back = true;
+ continue;
+ }
+ if (d > ON_EPSILON)
+ {
+ if (back)
+ return SIDE_CROSS;
+ front = true;
+ continue;
+ }
+ }
+
+ if (back)
+ return SIDE_BACK;
+ if (front)
+ return SIDE_FRONT;
+ return SIDE_ON;
+}
+
+//#ifdef ME
+ #define CONTINUOUS_EPSILON 0.005
+//#else
+// #define CONTINUOUS_EPSILON 0.001
+//#endif
+
+/*
+=============
+TryMergeWinding
+
+If two polygons share a common edge and the edges that meet at the
+common points are both inside the other polygons, merge them
+
+Returns NULL if the faces couldn't be merged, or the new face.
+The originals will NOT be freed.
+=============
+*/
+
+winding_t *TryMergeWinding (winding_t *f1, winding_t *f2, vec3_t planenormal)
+{
+ vec_t *p1, *p2, *p3, *p4, *back;
+ winding_t *newf;
+ int i, j, k, l;
+ vec3_t normal, delta;
+ vec_t dot;
+ qboolean keep1, keep2;
+
+
+ //
+ // find a common edge
+ //
+ p1 = p2 = NULL; // stop compiler warning
+ j = 0; //
+
+ for (i = 0; i < f1->numpoints; i++)
+ {
+ p1 = f1->p[i];
+ p2 = f1->p[(i+1) % f1->numpoints];
+ for (j = 0; j < f2->numpoints; j++)
+ {
+ p3 = f2->p[j];
+ p4 = f2->p[(j+1) % f2->numpoints];
+ for (k = 0; k < 3; k++)
+ {
+ if (fabs(p1[k] - p4[k]) > 0.1)//EQUAL_EPSILON) //ME
+ break;
+ if (fabs(p2[k] - p3[k]) > 0.1)//EQUAL_EPSILON) //ME
+ break;
+ } //end for
+ if (k==3)
+ break;
+ } //end for
+ if (j < f2->numpoints)
+ break;
+ } //end for
+
+ if (i == f1->numpoints)
+ return NULL; // no matching edges
+
+ //
+ // check slope of connected lines
+ // if the slopes are colinear, the point can be removed
+ //
+ back = f1->p[(i+f1->numpoints-1)%f1->numpoints];
+ VectorSubtract (p1, back, delta);
+ CrossProduct (planenormal, delta, normal);
+ VectorNormalize (normal);
+
+ back = f2->p[(j+2)%f2->numpoints];
+ VectorSubtract (back, p1, delta);
+ dot = DotProduct (delta, normal);
+ if (dot > CONTINUOUS_EPSILON)
+ return NULL; // not a convex polygon
+ keep1 = (qboolean)(dot < -CONTINUOUS_EPSILON);
+
+ back = f1->p[(i+2)%f1->numpoints];
+ VectorSubtract (back, p2, delta);
+ CrossProduct (planenormal, delta, normal);
+ VectorNormalize (normal);
+
+ back = f2->p[(j+f2->numpoints-1)%f2->numpoints];
+ VectorSubtract (back, p2, delta);
+ dot = DotProduct (delta, normal);
+ if (dot > CONTINUOUS_EPSILON)
+ return NULL; // not a convex polygon
+ keep2 = (qboolean)(dot < -CONTINUOUS_EPSILON);
+
+ //
+ // build the new polygon
+ //
+ newf = AllocWinding (f1->numpoints + f2->numpoints);
+
+ // copy first polygon
+ for (k=(i+1)%f1->numpoints ; k != i ; k=(k+1)%f1->numpoints)
+ {
+ if (k==(i+1)%f1->numpoints && !keep2)
+ continue;
+
+ VectorCopy (f1->p[k], newf->p[newf->numpoints]);
+ newf->numpoints++;
+ }
+
+ // copy second polygon
+ for (l= (j+1)%f2->numpoints ; l != j ; l=(l+1)%f2->numpoints)
+ {
+ if (l==(j+1)%f2->numpoints && !keep1)
+ continue;
+ VectorCopy (f2->p[l], newf->p[newf->numpoints]);
+ newf->numpoints++;
+ }
+
+ return newf;
+}
+
+//#ifdef ME
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+winding_t *MergeWindings(winding_t *w1, winding_t *w2, vec3_t planenormal)
+{
+ winding_t *neww;
+ float dist;
+ int i, j, n, found, insertafter;
+ int sides[MAX_POINTS_ON_WINDING+4];
+ vec3_t newp[MAX_POINTS_ON_WINDING+4];
+ int numpoints;
+ vec3_t edgevec, sepnormal, v;
+
+ RemoveEqualPoints(w1, 0.2);
+ numpoints = w1->numpoints;
+ memcpy(newp, w1->p, w1->numpoints * sizeof(vec3_t));
+ //
+ for (i = 0; i < w2->numpoints; i++)
+ {
+ VectorCopy(w2->p[i], v);
+ for (j = 0; j < numpoints; j++)
+ {
+ VectorSubtract(newp[(j+1)%numpoints],
+ newp[(j)%numpoints], edgevec);
+ CrossProduct(edgevec, planenormal, sepnormal);
+ VectorNormalize(sepnormal);
+ if (VectorLength(sepnormal) < 0.9)
+ {
+ //remove the point from the new winding
+ for (n = j; n < numpoints-1; n++)
+ {
+ VectorCopy(newp[n+1], newp[n]);
+ sides[n] = sides[n+1];
+ } //end for
+ numpoints--;
+ j--;
+ Log_Print("MergeWindings: degenerate edge on winding %f %f %f\n", sepnormal[0],
+ sepnormal[1],
+ sepnormal[2]);
+ continue;
+ } //end if
+ dist = DotProduct(newp[(j)%numpoints], sepnormal);
+ if (DotProduct(v, sepnormal) - dist < -0.1) sides[j] = SIDE_BACK;
+ else sides[j] = SIDE_FRONT;
+ } //end for
+ //remove all unnecesary points
+ for (j = 0; j < numpoints;)
+ {
+ if (sides[j] == SIDE_BACK
+ && sides[(j+1)%numpoints] == SIDE_BACK)
+ {
+ //remove the point from the new winding
+ for (n = (j+1)%numpoints; n < numpoints-1; n++)
+ {
+ VectorCopy(newp[n+1], newp[n]);
+ sides[n] = sides[n+1];
+ } //end for
+ numpoints--;
+ } //end if
+ else
+ {
+ j++;
+ } //end else
+ } //end for
+ //
+ found = false;
+ for (j = 0; j < numpoints; j++)
+ {
+ if (sides[j] == SIDE_FRONT
+ && sides[(j+1)%numpoints] == SIDE_BACK)
+ {
+ if (found) Log_Print("Warning: MergeWindings: front to back found twice\n");
+ found = true;
+ } //end if
+ } //end for
+ //
+ for (j = 0; j < numpoints; j++)
+ {
+ if (sides[j] == SIDE_FRONT
+ && sides[(j+1)%numpoints] == SIDE_BACK)
+ {
+ insertafter = (j+1)%numpoints;
+ //insert the new point after j+1
+ for (n = numpoints-1; n > insertafter; n--)
+ {
+ VectorCopy(newp[n], newp[n+1]);
+ } //end for
+ numpoints++;
+ VectorCopy(v, newp[(insertafter+1)%numpoints]);
+ break;
+ } //end if
+ } //end for
+ } //end for
+ neww = AllocWinding(numpoints);
+ neww->numpoints = numpoints;
+ memcpy(neww->p, newp, numpoints * sizeof(vec3_t));
+ RemoveColinearPoints(neww);
+ return neww;
+} //end of the function MergeWindings
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+char *WindingErrorString(void)
+{
+ return windingerror;
+} //end of the function WindingErrorString
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int WindingError(winding_t *w)
+{
+ int i, j;
+ vec_t *p1, *p2;
+ vec_t d, edgedist;
+ vec3_t dir, edgenormal, facenormal;
+ vec_t area;
+ vec_t facedist;
+
+ if (w->numpoints < 3)
+ {
+ sprintf(windingerror, "winding %i points", w->numpoints);
+ return WE_NOTENOUGHPOINTS;
+ } //end if
+
+ area = WindingArea(w);
+ if (area < 1)
+ {
+ sprintf(windingerror, "winding %f area", area);
+ return WE_SMALLAREA;
+ } //end if
+
+ WindingPlane (w, facenormal, &facedist);
+
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ p1 = w->p[i];
+
+ for (j=0 ; j<3 ; j++)
+ {
+ if (p1[j] > BOGUS_RANGE || p1[j] < -BOGUS_RANGE)
+ {
+ sprintf(windingerror, "winding point %d BUGUS_RANGE \'%f %f %f\'", j, p1[0], p1[1], p1[2]);
+ return WE_POINTBOGUSRANGE;
+ } //end if
+ } //end for
+
+ j = i+1 == w->numpoints ? 0 : i+1;
+
+ // check the point is on the face plane
+ d = DotProduct (p1, facenormal) - facedist;
+ if (d < -ON_EPSILON || d > ON_EPSILON)
+ {
+ sprintf(windingerror, "winding point %d off plane", i);
+ return WE_POINTOFFPLANE;
+ } //end if
+
+ // check the edge isnt degenerate
+ p2 = w->p[j];
+ VectorSubtract (p2, p1, dir);
+
+ if (VectorLength (dir) < ON_EPSILON)
+ {
+ sprintf(windingerror, "winding degenerate edge %d-%d", i, j);
+ return WE_DEGENERATEEDGE;
+ } //end if
+
+ CrossProduct (facenormal, dir, edgenormal);
+ VectorNormalize (edgenormal);
+ edgedist = DotProduct (p1, edgenormal);
+ edgedist += ON_EPSILON;
+
+ // all other points must be on front side
+ for (j=0 ; j<w->numpoints ; j++)
+ {
+ if (j == i)
+ continue;
+ d = DotProduct (w->p[j], edgenormal);
+ if (d > edgedist)
+ {
+ sprintf(windingerror, "winding non-convex");
+ return WE_NONCONVEX;
+ } //end if
+ } //end for
+ } //end for
+ return WE_NONE;
+} //end of the function WindingError
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void RemoveEqualPoints(winding_t *w, float epsilon)
+{
+ int i, nump;
+ vec3_t v;
+ vec3_t p[MAX_POINTS_ON_WINDING];
+
+ VectorCopy(w->p[0], p[0]);
+ nump = 1;
+ for (i = 1; i < w->numpoints; i++)
+ {
+ VectorSubtract(w->p[i], p[nump-1], v);
+ if (VectorLength(v) > epsilon)
+ {
+ if (nump >= MAX_POINTS_ON_WINDING)
+ Error("RemoveColinearPoints: MAX_POINTS_ON_WINDING");
+ VectorCopy (w->p[i], p[nump]);
+ nump++;
+ } //end if
+ } //end for
+
+ if (nump == w->numpoints)
+ return;
+
+ w->numpoints = nump;
+ memcpy(w->p, p, nump * sizeof(p[0]));
+} //end of the function RemoveEqualPoints
+//===========================================================================
+// adds the given point to a winding at the given spot
+// (for instance when spot is zero then the point is added at position zero)
+// the original winding is NOT freed
+//
+// Parameter: -
+// Returns: the new winding with the added point
+// Changes Globals: -
+//===========================================================================
+winding_t *AddWindingPoint(winding_t *w, vec3_t point, int spot)
+{
+ int i, j;
+ winding_t *neww;
+
+ if (spot > w->numpoints)
+ {
+ Error("AddWindingPoint: num > w->numpoints");
+ } //end if
+ if (spot < 0)
+ {
+ Error("AddWindingPoint: num < 0");
+ } //end if
+ neww = AllocWinding(w->numpoints + 1);
+ neww->numpoints = w->numpoints + 1;
+ for (i = 0, j = 0; i < neww->numpoints; i++)
+ {
+ if (i == spot)
+ {
+ VectorCopy(point, neww->p[i]);
+ } //end if
+ else
+ {
+ VectorCopy(w->p[j], neww->p[i]);
+ j++;
+ } //end else
+ } //end for
+ return neww;
+} //end of the function AddWindingPoint
+//===========================================================================
+// the position where the new point should be added in the winding is
+// stored in *spot
+//
+// Parameter: -
+// Returns: true if the point is on the winding
+// Changes Globals: -
+//===========================================================================
+#define MELT_ON_EPSILON 0.2
+
+int PointOnWinding(winding_t *w, vec3_t normal, float dist, vec3_t point, int *spot)
+{
+ int i, j;
+ vec3_t v1, v2;
+ vec3_t edgenormal, edgevec;
+ float edgedist, dot;
+
+ *spot = 0;
+ //the point must be on the winding plane
+ dot = DotProduct(point, normal) - dist;
+ if (dot < -MELT_ON_EPSILON || dot > MELT_ON_EPSILON) return false;
+ //
+ for (i = 0; i < w->numpoints; i++)
+ {
+ j = (i+1) % w->numpoints;
+ //get a plane orthogonal to the winding plane through the edge
+ VectorSubtract(w->p[j], w->p[i], edgevec);
+ CrossProduct(normal, edgevec, edgenormal);
+ VectorNormalize(edgenormal);
+ edgedist = DotProduct(edgenormal, w->p[i]);
+ //point must be not too far from the plane
+ dot = DotProduct(point, edgenormal) - edgedist;
+ if (dot < -MELT_ON_EPSILON || dot > MELT_ON_EPSILON) continue;
+ //vector from first point of winding to the point to test
+ VectorSubtract(point, w->p[i], v1);
+ //vector from second point of winding to the point to test
+ VectorSubtract(point, w->p[j], v2);
+ //if the length of the vector is not larger than 0.5 units then
+ //the point is assumend to be the same as one of the winding points
+ if (VectorNormalize(v1) < 0.5) return false;
+ if (VectorNormalize(v2) < 0.5) return false;
+ //point must be between the two winding points
+ //(the two vectors must be directed towards each other, and on the
+ //same straight line)
+ if (DotProduct(v1, v2) < -0.99)
+ {
+ *spot = i + 1;
+ return true;
+ } //end if
+ } //end for
+ return false;
+} //end of the function PointOnWinding
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int FindPlaneSeperatingWindings(winding_t *w1, winding_t *w2, vec3_t dir,
+ vec3_t normal, float *dist)
+{
+ int i, i2, j, j2, n;
+ int sides1[3], sides2[3];
+ float dist1, dist2, dot, diff;
+ vec3_t normal1, normal2;
+ vec3_t v1, v2;
+
+ for (i = 0; i < w1->numpoints; i++)
+ {
+ i2 = (i+1) % w1->numpoints;
+ //
+ VectorSubtract(w1->p[i2], w1->p[i], v1);
+ if (VectorLength(v1) < 0.1)
+ {
+ //Log_Write("FindPlaneSeperatingWindings: winding1 with degenerate edge\r\n");
+ continue;
+ } //end if
+ CrossProduct(v1, dir, normal1);
+ VectorNormalize(normal1);
+ dist1 = DotProduct(normal1, w1->p[i]);
+ //
+ for (j = 0; j < w2->numpoints; j++)
+ {
+ j2 = (j+1) % w2->numpoints;
+ //
+ VectorSubtract(w2->p[j2], w2->p[j], v2);
+ if (VectorLength(v2) < 0.1)
+ {
+ //Log_Write("FindPlaneSeperatingWindings: winding2 with degenerate edge\r\n");
+ continue;
+ } //end if
+ CrossProduct(v2, dir, normal2);
+ VectorNormalize(normal2);
+ dist2 = DotProduct(normal2, w2->p[j]);
+ //
+ diff = dist1 - dist2;
+ if (diff < -0.1 || diff > 0.1)
+ {
+ dist2 = -dist2;
+ VectorNegate(normal2, normal2);
+ diff = dist1 - dist2;
+ if (diff < -0.1 || diff > 0.1) continue;
+ } //end if
+ //check if the normal vectors are equal
+ for (n = 0; n < 3; n++)
+ {
+ diff = normal1[n] - normal2[n];
+ if (diff < -0.0001 || diff > 0.0001) break;
+ } //end for
+ if (n != 3) continue;
+ //check on which side of the seperating plane the points of
+ //the first winding are
+ sides1[0] = sides1[1] = sides1[2] = 0;
+ for (n = 0; n < w1->numpoints; n++)
+ {
+ dot = DotProduct(w1->p[n], normal1) - dist1;
+ if (dot > 0.1) sides1[0]++;
+ else if (dot < -0.1) sides1[1]++;
+ else sides1[2]++;
+ } //end for
+ //check on which side of the seperating plane the points of
+ //the second winding are
+ sides2[0] = sides2[1] = sides2[2] = 0;
+ for (n = 0; n < w2->numpoints; n++)
+ {
+ //used normal1 and dist1 (they are equal to normal2 and dist2)
+ dot = DotProduct(w2->p[n], normal1) - dist1;
+ if (dot > 0.1) sides2[0]++;
+ else if (dot < -0.1) sides2[1]++;
+ else sides2[2]++;
+ } //end for
+ //if the first winding has points at both sides
+ if (sides1[0] && sides1[1])
+ {
+ Log_Write("FindPlaneSeperatingWindings: winding1 non-convex\r\n");
+ continue;
+ } //end if
+ //if the second winding has points at both sides
+ if (sides2[0] && sides2[1])
+ {
+ Log_Write("FindPlaneSeperatingWindings: winding2 non-convex\r\n");
+ continue;
+ } //end if
+ //
+ if ((!sides1[0] && !sides1[1]) || (!sides2[0] && !sides2[1]))
+ {
+ //don't use one of the winding planes as the seperating plane
+ continue;
+ } //end if
+ //the windings must be at different sides of the seperating plane
+ if ((!sides1[0] && !sides2[1]) || (!sides1[1] && !sides2[0]))
+ {
+ VectorCopy(normal1, normal);
+ *dist = dist1;
+ return true;
+ } //end if
+ } //end for
+ } //end for
+ return false;
+} //end of the function FindPlaneSeperatingWindings
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+#define WCONVEX_EPSILON 0.2
+
+int WindingsNonConvex(winding_t *w1, winding_t *w2,
+ vec3_t normal1, vec3_t normal2,
+ float dist1, float dist2)
+{
+ int i;
+
+ if (!w1 || !w2) return false;
+
+ //check if one of the points of face1 is at the back of the plane of face2
+ for (i = 0; i < w1->numpoints; i++)
+ {
+ if (DotProduct(normal2, w1->p[i]) - dist2 > WCONVEX_EPSILON) return true;
+ } //end for
+ //check if one of the points of face2 is at the back of the plane of face1
+ for (i = 0; i < w2->numpoints; i++)
+ {
+ if (DotProduct(normal1, w2->p[i]) - dist1 > WCONVEX_EPSILON) return true;
+ } //end for
+
+ return false;
+} //end of the function WindingsNonConvex
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+/*
+#define VERTEX_EPSILON 0.5
+
+qboolean EqualVertexes(vec3_t v1, vec3_t v2)
+{
+ float diff;
+
+ diff = v1[0] - v2[0];
+ if (diff > -VERTEX_EPSILON && diff < VERTEX_EPSILON)
+ {
+ diff = v1[1] - v2[1];
+ if (diff > -VERTEX_EPSILON && diff < VERTEX_EPSILON)
+ {
+ diff = v1[2] - v2[2];
+ if (diff > -VERTEX_EPSILON && diff < VERTEX_EPSILON)
+ {
+ return true;
+ } //end if
+ } //end if
+ } //end if
+ return false;
+} //end of the function EqualVertexes
+
+#define CONTINUOUS_EPSILON 0.001
+
+winding_t *AAS_MergeWindings(winding_t *w1, winding_t *w2, vec3_t windingnormal)
+{
+ int n, i, k;
+ vec3_t normal, delta;
+ winding_t *winding, *neww;
+ float dist, dot;
+ int p1, p2;
+ int points[2][64];
+ int numpoints[2] = {0, 0};
+ int newnumpoints;
+ int keep[2];
+
+ if (!FindPlaneSeperatingWindings(w1, w2, windingnormal, normal, &dist)) return NULL;
+
+ //for both windings
+ for (n = 0; n < 2; n++)
+ {
+ if (n == 0) winding = w1;
+ else winding = w2;
+ //get the points of the winding which are on the seperating plane
+ for (i = 0; i < winding->numpoints; i++)
+ {
+ dot = DotProduct(winding->p[i], normal) - dist;
+ if (dot > -ON_EPSILON && dot < ON_EPSILON)
+ {
+ //don't allow more than 64 points on the seperating plane
+ if (numpoints[n] >= 64) Error("AAS_MergeWindings: more than 64 points on seperating plane\n");
+ points[n][numpoints[n]++] = i;
+ } //end if
+ } //end for
+ //there must be at least two points of each winding on the seperating plane
+ if (numpoints[n] < 2) return NULL;
+ } //end for
+
+ //if the first point of winding1 (which is on the seperating plane) is unequal
+ //to the last point of winding2 (which is on the seperating plane)
+ if (!EqualVertexes(w1->p[points[0][0]], w2->p[points[1][numpoints[1]-1]]))
+ {
+ return NULL;
+ } //end if
+ //if the last point of winding1 (which is on the seperating plane) is unequal
+ //to the first point of winding2 (which is on the seperating plane)
+ if (!EqualVertexes(w1->p[points[0][numpoints[0]-1]], w2->p[points[1][0]]))
+ {
+ return NULL;
+ } //end if
+ //
+ // check slope of connected lines
+ // if the slopes are colinear, the point can be removed
+ //
+ //first point of winding1 which is on the seperating plane
+ p1 = points[0][0];
+ //point before p1
+ p2 = (p1 + w1->numpoints - 1) % w1->numpoints;
+ VectorSubtract(w1->p[p1], w1->p[p2], delta);
+ CrossProduct(windingnormal, delta, normal);
+ VectorNormalize(normal, normal);
+
+ //last point of winding2 which is on the seperating plane
+ p1 = points[1][numpoints[1]-1];
+ //point after p1
+ p2 = (p1 + 1) % w2->numpoints;
+ VectorSubtract(w2->p[p2], w2->p[p1], delta);
+ dot = DotProduct(delta, normal);
+ if (dot > CONTINUOUS_EPSILON) return NULL; //merging would create a non-convex polygon
+ keep[0] = (qboolean)(dot < -CONTINUOUS_EPSILON);
+
+ //first point of winding2 which is on the seperating plane
+ p1 = points[1][0];
+ //point before p1
+ p2 = (p1 + w2->numpoints - 1) % w2->numpoints;
+ VectorSubtract(w2->p[p1], w2->p[p2], delta);
+ CrossProduct(windingnormal, delta, normal);
+ VectorNormalize(normal, normal);
+
+ //last point of winding1 which is on the seperating plane
+ p1 = points[0][numpoints[0]-1];
+ //point after p1
+ p2 = (p1 + 1) % w1->numpoints;
+ VectorSubtract(w1->p[p2], w1->p[p1], delta);
+ dot = DotProduct(delta, normal);
+ if (dot > CONTINUOUS_EPSILON) return NULL; //merging would create a non-convex polygon
+ keep[1] = (qboolean)(dot < -CONTINUOUS_EPSILON);
+
+ //number of points on the new winding
+ newnumpoints = w1->numpoints - numpoints[0] + w2->numpoints - numpoints[1] + 2;
+ //allocate the winding
+ neww = AllocWinding(newnumpoints);
+ neww->numpoints = newnumpoints;
+ //copy all the points
+ k = 0;
+ //for both windings
+ for (n = 0; n < 2; n++)
+ {
+ if (n == 0) winding = w1;
+ else winding = w2;
+ //copy the points of the winding starting with the last point on the
+ //seperating plane and ending before the first point on the seperating plane
+ for (i = points[n][numpoints[n]-1]; i != points[n][0]; i = (i+1)%winding->numpoints)
+ {
+ if (k >= newnumpoints)
+ {
+ Log_Print("numpoints[0] = %d\n", numpoints[0]);
+ Log_Print("numpoints[1] = %d\n", numpoints[1]);
+ Error("AAS_MergeWindings: k = %d >= newnumpoints = %d\n", k, newnumpoints);
+ } //end if
+ VectorCopy(winding->p[i], neww->p[k]);
+ k++;
+ } //end for
+ } //end for
+ RemoveEqualPoints(neww);
+ if (!WindingIsOk(neww, 1))
+ {
+ Log_Print("AAS_MergeWindings: winding not ok after merging\n");
+ FreeWinding(neww);
+ return NULL;
+ } //end if
+ return neww;
+} //end of the function AAS_MergeWindings*/
+//#endif //ME
diff --git a/code/bspc/l_poly.h b/code/bspc/l_poly.h
new file mode 100755
index 0000000..a14b834
--- /dev/null
+++ b/code/bspc/l_poly.h
@@ -0,0 +1,120 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+//a winding gives the bounding points of a convex polygon
+typedef struct
+{
+ int numpoints;
+ vec3_t p[4]; //variable sized
+} winding_t;
+
+#define MAX_POINTS_ON_WINDING 96
+
+//you can define on_epsilon in the makefile as tighter
+#ifndef ON_EPSILON
+#define ON_EPSILON 0.1
+#endif
+//winding errors
+#define WE_NONE 0
+#define WE_NOTENOUGHPOINTS 1
+#define WE_SMALLAREA 2
+#define WE_POINTBOGUSRANGE 3
+#define WE_POINTOFFPLANE 4
+#define WE_DEGENERATEEDGE 5
+#define WE_NONCONVEX 6
+
+//allocates a winding
+winding_t *AllocWinding (int points);
+//returns the area of the winding
+vec_t WindingArea (winding_t *w);
+//gives the center of the winding
+void WindingCenter (winding_t *w, vec3_t center);
+//clips the given winding to the given plane and gives the front
+//and back part of the clipped winding
+void ClipWindingEpsilon (winding_t *in, vec3_t normal, vec_t dist,
+ vec_t epsilon, winding_t **front, winding_t **back);
+//returns the fragment of the given winding that is on the front
+//side of the cliping plane. The original is freed.
+winding_t *ChopWinding (winding_t *in, vec3_t normal, vec_t dist);
+//returns a copy of the given winding
+winding_t *CopyWinding (winding_t *w);
+//returns the reversed winding of the given one
+winding_t *ReverseWinding (winding_t *w);
+//returns a base winding for the given plane
+winding_t *BaseWindingForPlane (vec3_t normal, vec_t dist);
+//checks the winding for errors
+void CheckWinding (winding_t *w);
+//returns the plane normal and dist the winding is in
+void WindingPlane(winding_t *w, vec3_t normal, vec_t *dist);
+//removes colinear points from the winding
+void RemoveColinearPoints(winding_t *w);
+//returns on which side of the plane the winding is situated
+int WindingOnPlaneSide(winding_t *w, vec3_t normal, vec_t dist);
+//frees the winding
+void FreeWinding(winding_t *w);
+//gets the bounds of the winding
+void WindingBounds(winding_t *w, vec3_t mins, vec3_t maxs);
+//chops the winding with the given plane, the original winding is freed if clipped
+void ChopWindingInPlace (winding_t **w, vec3_t normal, vec_t dist, vec_t epsilon);
+//prints the winding points on STDOUT
+void pw(winding_t *w);
+//try to merge the two windings which are in the given plane
+//the original windings are undisturbed
+//the merged winding is returned when merging was possible
+//NULL is returned otherwise
+winding_t *TryMergeWinding (winding_t *f1, winding_t *f2, vec3_t planenormal);
+//brute force winding merging... creates a convex winding out of
+//the two whatsoever
+winding_t *MergeWindings(winding_t *w1, winding_t *w2, vec3_t planenormal);
+
+//#ifdef ME
+void ResetWindings(void);
+//returns the amount of winding memory
+int WindingMemory(void);
+int WindingPeakMemory(void);
+int ActiveWindings(void);
+//returns the winding error string
+char *WindingErrorString(void);
+//returns one of the WE_ flags when the winding has errors
+int WindingError(winding_t *w);
+//removes equal points from the winding
+void RemoveEqualPoints(winding_t *w, float epsilon);
+//returns a winding with a point added at the given spot to the
+//given winding, original winding is NOT freed
+winding_t *AddWindingPoint(winding_t *w, vec3_t point, int spot);
+//returns true if the point is on one of the winding 'edges'
+//when the point is on one of the edged the number of the first
+//point of the edge is stored in 'spot'
+int PointOnWinding(winding_t *w, vec3_t normal, float dist, vec3_t point, int *spot);
+//find a plane seperating the two windings
+//true is returned when the windings area adjacent
+//the seperating plane normal and distance area stored in 'normal' and 'dist'
+//this plane will contain both the piece of common edge of the two windings
+//and the vector 'dir'
+int FindPlaneSeperatingWindings(winding_t *w1, winding_t *w2, vec3_t dir,
+ vec3_t normal, float *dist);
+//
+int WindingsNonConvex(winding_t *w1, winding_t *w2,
+ vec3_t normal1, vec3_t normal2,
+ float dist1, float dist2);
+//#endif //ME
+
diff --git a/code/bspc/l_qfiles.c b/code/bspc/l_qfiles.c
new file mode 100755
index 0000000..32cb6de
--- /dev/null
+++ b/code/bspc/l_qfiles.c
@@ -0,0 +1,663 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#if defined(WIN32)|defined(_WIN32)
+#include <windows.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#else
+#include <glob.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#endif
+
+#include "qbsp.h"
+
+//file extensions with their type
+typedef struct qfile_exttype_s
+{
+ char *extension;
+ int type;
+} qfile_exttyp_t;
+
+qfile_exttyp_t quakefiletypes[] =
+{
+ {QFILEEXT_UNKNOWN, QFILETYPE_UNKNOWN},
+ {QFILEEXT_PAK, QFILETYPE_PAK},
+ {QFILEEXT_PK3, QFILETYPE_PK3},
+ {QFILEEXT_SIN, QFILETYPE_PAK},
+ {QFILEEXT_BSP, QFILETYPE_BSP},
+ {QFILEEXT_MAP, QFILETYPE_MAP},
+ {QFILEEXT_MDL, QFILETYPE_MDL},
+ {QFILEEXT_MD2, QFILETYPE_MD2},
+ {QFILEEXT_MD3, QFILETYPE_MD3},
+ {QFILEEXT_WAL, QFILETYPE_WAL},
+ {QFILEEXT_WAV, QFILETYPE_WAV},
+ {QFILEEXT_AAS, QFILETYPE_AAS},
+ {NULL, 0}
+};
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int QuakeFileExtensionType(char *extension)
+{
+ int i;
+
+ for (i = 0; quakefiletypes[i].extension; i++)
+ {
+ if (!stricmp(extension, quakefiletypes[i].extension))
+ {
+ return quakefiletypes[i].type;
+ } //end if
+ } //end for
+ return QFILETYPE_UNKNOWN;
+} //end of the function QuakeFileExtensionType
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+char *QuakeFileTypeExtension(int type)
+{
+ int i;
+
+ for (i = 0; quakefiletypes[i].extension; i++)
+ {
+ if (quakefiletypes[i].type == type)
+ {
+ return quakefiletypes[i].extension;
+ } //end if
+ } //end for
+ return QFILEEXT_UNKNOWN;
+} //end of the function QuakeFileExtension
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int QuakeFileType(char *filename)
+{
+ char ext[_MAX_PATH] = ".";
+
+ ExtractFileExtension(filename, ext+1);
+ return QuakeFileExtensionType(ext);
+} //end of the function QuakeFileTypeFromFileName
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+char *StringContains(char *str1, char *str2, int casesensitive)
+{
+ int len, i, j;
+
+ len = strlen(str1) - strlen(str2);
+ for (i = 0; i <= len; i++, str1++)
+ {
+ for (j = 0; str2[j]; j++)
+ {
+ if (casesensitive)
+ {
+ if (str1[j] != str2[j]) break;
+ } //end if
+ else
+ {
+ if (toupper(str1[j]) != toupper(str2[j])) break;
+ } //end else
+ } //end for
+ if (!str2[j]) return str1;
+ } //end for
+ return NULL;
+} //end of the function StringContains
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int FileFilter(char *filter, char *filename, int casesensitive)
+{
+ char buf[1024];
+ char *ptr;
+ int i, found;
+
+ while(*filter)
+ {
+ if (*filter == '*')
+ {
+ filter++;
+ for (i = 0; *filter; i++)
+ {
+ if (*filter == '*' || *filter == '?') break;
+ buf[i] = *filter;
+ filter++;
+ } //end for
+ buf[i] = '\0';
+ if (strlen(buf))
+ {
+ ptr = StringContains(filename, buf, casesensitive);
+ if (!ptr) return false;
+ filename = ptr + strlen(buf);
+ } //end if
+ } //end if
+ else if (*filter == '?')
+ {
+ filter++;
+ filename++;
+ } //end else if
+ else if (*filter == '[' && *(filter+1) == '[')
+ {
+ filter++;
+ } //end if
+ else if (*filter == '[')
+ {
+ filter++;
+ found = false;
+ while(*filter && !found)
+ {
+ if (*filter == ']' && *(filter+1) != ']') break;
+ if (*(filter+1) == '-' && *(filter+2) && (*(filter+2) != ']' || *(filter+3) == ']'))
+ {
+ if (casesensitive)
+ {
+ if (*filename >= *filter && *filename <= *(filter+2)) found = true;
+ } //end if
+ else
+ {
+ if (toupper(*filename) >= toupper(*filter) &&
+ toupper(*filename) <= toupper(*(filter+2))) found = true;
+ } //end else
+ filter += 3;
+ } //end if
+ else
+ {
+ if (casesensitive)
+ {
+ if (*filter == *filename) found = true;
+ } //end if
+ else
+ {
+ if (toupper(*filter) == toupper(*filename)) found = true;
+ } //end else
+ filter++;
+ } //end else
+ } //end while
+ if (!found) return false;
+ while(*filter)
+ {
+ if (*filter == ']' && *(filter+1) != ']') break;
+ filter++;
+ } //end while
+ filter++;
+ filename++;
+ } //end else if
+ else
+ {
+ if (casesensitive)
+ {
+ if (*filter != *filename) return false;
+ } //end if
+ else
+ {
+ if (toupper(*filter) != toupper(*filename)) return false;
+ } //end else
+ filter++;
+ filename++;
+ } //end else
+ } //end while
+ return true;
+} //end of the function FileFilter
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+quakefile_t *FindQuakeFilesInZip(char *zipfile, char *filter)
+{
+ unzFile uf;
+ int err;
+ unz_global_info gi;
+ char filename_inzip[MAX_PATH];
+ unz_file_info file_info;
+ int i;
+ quakefile_t *qfiles, *lastqf, *qf;
+
+ uf = unzOpen(zipfile);
+ err = unzGetGlobalInfo(uf, &gi);
+
+ if (err != UNZ_OK) return NULL;
+
+ unzGoToFirstFile(uf);
+
+ qfiles = NULL;
+ lastqf = NULL;
+ for (i = 0; i < gi.number_entry; i++)
+ {
+ err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL,0,NULL,0);
+ if (err != UNZ_OK) break;
+
+ ConvertPath(filename_inzip);
+ if (FileFilter(filter, filename_inzip, false))
+ {
+ qf = malloc(sizeof(quakefile_t));
+ if (!qf) Error("out of memory");
+ memset(qf, 0, sizeof(quakefile_t));
+ strcpy(qf->pakfile, zipfile);
+ strcpy(qf->filename, zipfile);
+ strcpy(qf->origname, filename_inzip);
+ qf->zipfile = true;
+ //memcpy( &buildBuffer[i].zipfileinfo, (unz_s*)uf, sizeof(unz_s));
+ memcpy(&qf->zipinfo, (unz_s*)uf, sizeof(unz_s));
+ qf->offset = 0;
+ qf->length = file_info.uncompressed_size;
+ qf->type = QuakeFileType(filename_inzip);
+ //add the file ot the list
+ qf->next = NULL;
+ if (lastqf) lastqf->next = qf;
+ else qfiles = qf;
+ lastqf = qf;
+ } //end if
+ unzGoToNextFile(uf);
+ } //end for
+
+ unzClose(uf);
+
+ return qfiles;
+} //end of the function FindQuakeFilesInZip
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+quakefile_t *FindQuakeFilesInPak(char *pakfile, char *filter)
+{
+ FILE *fp;
+ dpackheader_t packheader;
+ dsinpackfile_t *packfiles;
+ dpackfile_t *idpackfiles;
+ quakefile_t *qfiles, *lastqf, *qf;
+ int numpackdirs, i;
+
+ qfiles = NULL;
+ lastqf = NULL;
+ //open the pak file
+ fp = fopen(pakfile, "rb");
+ if (!fp)
+ {
+ Warning("can't open pak file %s", pakfile);
+ return NULL;
+ } //end if
+ //read pak header, check for valid pak id and seek to the dir entries
+ if ((fread(&packheader, 1, sizeof(dpackheader_t), fp) != sizeof(dpackheader_t))
+ || (packheader.ident != IDPAKHEADER && packheader.ident != SINPAKHEADER)
+ || (fseek(fp, LittleLong(packheader.dirofs), SEEK_SET))
+ )
+ {
+ fclose(fp);
+ Warning("invalid pak file %s", pakfile);
+ return NULL;
+ } //end if
+ //if it is a pak file from id software
+ if (packheader.ident == IDPAKHEADER)
+ {
+ //number of dir entries in the pak file
+ numpackdirs = LittleLong(packheader.dirlen) / sizeof(dpackfile_t);
+ idpackfiles = (dpackfile_t *) malloc(numpackdirs * sizeof(dpackfile_t));
+ if (!idpackfiles) Error("out of memory");
+ //read the dir entry
+ if (fread(idpackfiles, sizeof(dpackfile_t), numpackdirs, fp) != numpackdirs)
+ {
+ fclose(fp);
+ free(idpackfiles);
+ Warning("can't read the Quake pak file dir entries from %s", pakfile);
+ return NULL;
+ } //end if
+ fclose(fp);
+ //convert to sin pack files
+ packfiles = (dsinpackfile_t *) malloc(numpackdirs * sizeof(dsinpackfile_t));
+ if (!packfiles) Error("out of memory");
+ for (i = 0; i < numpackdirs; i++)
+ {
+ strcpy(packfiles[i].name, idpackfiles[i].name);
+ packfiles[i].filepos = LittleLong(idpackfiles[i].filepos);
+ packfiles[i].filelen = LittleLong(idpackfiles[i].filelen);
+ } //end for
+ free(idpackfiles);
+ } //end if
+ else //its a Sin pack file
+ {
+ //number of dir entries in the pak file
+ numpackdirs = LittleLong(packheader.dirlen) / sizeof(dsinpackfile_t);
+ packfiles = (dsinpackfile_t *) malloc(numpackdirs * sizeof(dsinpackfile_t));
+ if (!packfiles) Error("out of memory");
+ //read the dir entry
+ if (fread(packfiles, sizeof(dsinpackfile_t), numpackdirs, fp) != numpackdirs)
+ {
+ fclose(fp);
+ free(packfiles);
+ Warning("can't read the Sin pak file dir entries from %s", pakfile);
+ return NULL;
+ } //end if
+ fclose(fp);
+ for (i = 0; i < numpackdirs; i++)
+ {
+ packfiles[i].filepos = LittleLong(packfiles[i].filepos);
+ packfiles[i].filelen = LittleLong(packfiles[i].filelen);
+ } //end for
+ } //end else
+ //
+ for (i = 0; i < numpackdirs; i++)
+ {
+ ConvertPath(packfiles[i].name);
+ if (FileFilter(filter, packfiles[i].name, false))
+ {
+ qf = malloc(sizeof(quakefile_t));
+ if (!qf) Error("out of memory");
+ memset(qf, 0, sizeof(quakefile_t));
+ strcpy(qf->pakfile, pakfile);
+ strcpy(qf->filename, pakfile);
+ strcpy(qf->origname, packfiles[i].name);
+ qf->zipfile = false;
+ qf->offset = packfiles[i].filepos;
+ qf->length = packfiles[i].filelen;
+ qf->type = QuakeFileType(packfiles[i].name);
+ //add the file ot the list
+ qf->next = NULL;
+ if (lastqf) lastqf->next = qf;
+ else qfiles = qf;
+ lastqf = qf;
+ } //end if
+ } //end for
+ free(packfiles);
+ return qfiles;
+} //end of the function FindQuakeFilesInPak
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+quakefile_t *FindQuakeFilesWithPakFilter(char *pakfilter, char *filter)
+{
+#if defined(WIN32)|defined(_WIN32)
+ WIN32_FIND_DATA filedata;
+ HWND handle;
+ struct _stat statbuf;
+#else
+ glob_t globbuf;
+ struct stat statbuf;
+ int j;
+#endif
+ quakefile_t *qfiles, *lastqf, *qf;
+ char pakfile[_MAX_PATH], filename[_MAX_PATH], *str;
+ int done;
+
+ qfiles = NULL;
+ lastqf = NULL;
+ if (pakfilter && strlen(pakfilter))
+ {
+#if defined(WIN32)|defined(_WIN32)
+ handle = FindFirstFile(pakfilter, &filedata);
+ done = (handle == INVALID_HANDLE_VALUE);
+ while(!done)
+ {
+ _splitpath(pakfilter, pakfile, NULL, NULL, NULL);
+ _splitpath(pakfilter, NULL, &pakfile[strlen(pakfile)], NULL, NULL);
+ AppendPathSeperator(pakfile, _MAX_PATH);
+ strcat(pakfile, filedata.cFileName);
+ _stat(pakfile, &statbuf);
+#else
+ glob(pakfilter, 0, NULL, &globbuf);
+ for (j = 0; j < globbuf.gl_pathc; j++)
+ {
+ strcpy(pakfile, globbuf.gl_pathv[j]);
+ stat(pakfile, &statbuf);
+#endif
+ //if the file with .pak or .pk3 is a folder
+ if (statbuf.st_mode & S_IFDIR)
+ {
+ strcpy(filename, pakfilter);
+ AppendPathSeperator(filename, _MAX_PATH);
+ strcat(filename, filter);
+ qf = FindQuakeFilesWithPakFilter(NULL, filename);
+ if (lastqf) lastqf->next = qf;
+ else qfiles = qf;
+ lastqf = qf;
+ while(lastqf->next) lastqf = lastqf->next;
+ } //end if
+ else
+ {
+#if defined(WIN32)|defined(_WIN32)
+ str = StringContains(pakfile, ".pk3", false);
+#else
+ str = StringContains(pakfile, ".pk3", true);
+#endif
+ if (str && str == pakfile + strlen(pakfile) - strlen(".pk3"))
+ {
+ qf = FindQuakeFilesInZip(pakfile, filter);
+ } //end if
+ else
+ {
+ qf = FindQuakeFilesInPak(pakfile, filter);
+ } //end else
+ //
+ if (qf)
+ {
+ if (lastqf) lastqf->next = qf;
+ else qfiles = qf;
+ lastqf = qf;
+ while(lastqf->next) lastqf = lastqf->next;
+ } //end if
+ } //end else
+ //
+#if defined(WIN32)|defined(_WIN32)
+ //find the next file
+ done = !FindNextFile(handle, &filedata);
+ } //end while
+#else
+ } //end for
+ globfree(&globbuf);
+#endif
+ } //end if
+ else
+ {
+#if defined(WIN32)|defined(_WIN32)
+ handle = FindFirstFile(filter, &filedata);
+ done = (handle == INVALID_HANDLE_VALUE);
+ while(!done)
+ {
+ _splitpath(filter, filename, NULL, NULL, NULL);
+ _splitpath(filter, NULL, &filename[strlen(filename)], NULL, NULL);
+ AppendPathSeperator(filename, _MAX_PATH);
+ strcat(filename, filedata.cFileName);
+#else
+ glob(filter, 0, NULL, &globbuf);
+ for (j = 0; j < globbuf.gl_pathc; j++)
+ {
+ strcpy(filename, globbuf.gl_pathv[j]);
+#endif
+ //
+ qf = malloc(sizeof(quakefile_t));
+ if (!qf) Error("out of memory");
+ memset(qf, 0, sizeof(quakefile_t));
+ strcpy(qf->pakfile, "");
+ strcpy(qf->filename, filename);
+ strcpy(qf->origname, filename);
+ qf->offset = 0;
+ qf->length = 0;
+ qf->type = QuakeFileType(filename);
+ //add the file ot the list
+ qf->next = NULL;
+ if (lastqf) lastqf->next = qf;
+ else qfiles = qf;
+ lastqf = qf;
+#if defined(WIN32)|defined(_WIN32)
+ //find the next file
+ done = !FindNextFile(handle, &filedata);
+ } //end while
+#else
+ } //end for
+ globfree(&globbuf);
+#endif
+ } //end else
+ return qfiles;
+} //end of the function FindQuakeFilesWithPakFilter
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+quakefile_t *FindQuakeFiles(char *filter)
+{
+ char *str;
+ char newfilter[_MAX_PATH];
+ char pakfilter[_MAX_PATH];
+ char filefilter[_MAX_PATH];
+
+ strcpy(newfilter, filter);
+ ConvertPath(newfilter);
+ strcpy(pakfilter, newfilter);
+
+ str = StringContains(pakfilter, ".pak", false);
+ if (!str) str = StringContains(pakfilter, ".pk3", false);
+
+ if (str)
+ {
+ str += strlen(".pak");
+ if (*str)
+ {
+ *str++ = '\0';
+ while(*str == '\\' || *str == '/') str++;
+ strcpy(filefilter, str);
+ return FindQuakeFilesWithPakFilter(pakfilter, filefilter);
+ } //end if
+ } //end else
+ return FindQuakeFilesWithPakFilter(NULL, newfilter);
+} //end of the function FindQuakeFiles
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int LoadQuakeFile(quakefile_t *qf, void **bufferptr)
+{
+ FILE *fp;
+ void *buffer;
+ int length;
+ unzFile zf;
+
+ if (qf->zipfile)
+ {
+ //open the zip file
+ zf = unzOpen(qf->pakfile);
+ //set the file pointer
+ qf->zipinfo.file = ((unz_s *) zf)->file;
+ //open the Quake file in the zip file
+ unzOpenCurrentFile(&qf->zipinfo);
+ //allocate memory for the buffer
+ length = qf->length;
+ buffer = GetMemory(length+1);
+ //read the Quake file from the zip file
+ length = unzReadCurrentFile(&qf->zipinfo, buffer, length);
+ //close the Quake file in the zip file
+ unzCloseCurrentFile(&qf->zipinfo);
+ //close the zip file
+ unzClose(zf);
+
+ *bufferptr = buffer;
+ return length;
+ } //end if
+ else
+ {
+ fp = SafeOpenRead(qf->filename);
+ if (qf->offset) fseek(fp, qf->offset, SEEK_SET);
+ length = qf->length;
+ if (!length) length = Q_filelength(fp);
+ buffer = GetMemory(length+1);
+ ((char *)buffer)[length] = 0;
+ SafeRead(fp, buffer, length);
+ fclose(fp);
+
+ *bufferptr = buffer;
+ return length;
+ } //end else
+} //end of the function LoadQuakeFile
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int ReadQuakeFile(quakefile_t *qf, void *buffer, int offset, int length)
+{
+ FILE *fp;
+ int read;
+ unzFile zf;
+ char tmpbuf[1024];
+
+ if (qf->zipfile)
+ {
+ //open the zip file
+ zf = unzOpen(qf->pakfile);
+ //set the file pointer
+ qf->zipinfo.file = ((unz_s *) zf)->file;
+ //open the Quake file in the zip file
+ unzOpenCurrentFile(&qf->zipinfo);
+ //
+ while(offset > 0)
+ {
+ read = offset;
+ if (read > sizeof(tmpbuf)) read = sizeof(tmpbuf);
+ unzReadCurrentFile(&qf->zipinfo, tmpbuf, read);
+ offset -= read;
+ } //end while
+ //read the Quake file from the zip file
+ length = unzReadCurrentFile(&qf->zipinfo, buffer, length);
+ //close the Quake file in the zip file
+ unzCloseCurrentFile(&qf->zipinfo);
+ //close the zip file
+ unzClose(zf);
+
+ return length;
+ } //end if
+ else
+ {
+ fp = SafeOpenRead(qf->filename);
+ if (qf->offset) fseek(fp, qf->offset, SEEK_SET);
+ if (offset) fseek(fp, offset, SEEK_CUR);
+ SafeRead(fp, buffer, length);
+ fclose(fp);
+
+ return length;
+ } //end else
+} //end of the function ReadQuakeFile
diff --git a/code/bspc/l_qfiles.h b/code/bspc/l_qfiles.h
new file mode 100755
index 0000000..308c608
--- /dev/null
+++ b/code/bspc/l_qfiles.h
@@ -0,0 +1,91 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "../qcommon/unzip.h"
+
+#define QFILETYPE_UNKNOWN 0x8000
+#define QFILETYPE_PAK 0x0001
+#define QFILETYPE_PK3 0x0002
+#define QFILETYPE_BSP 0x0004
+#define QFILETYPE_MAP 0x0008
+#define QFILETYPE_MDL 0x0010
+#define QFILETYPE_MD2 0x0020
+#define QFILETYPE_MD3 0x0040
+#define QFILETYPE_WAL 0x0080
+#define QFILETYPE_WAV 0x0100
+#define QFILETYPE_AAS 0x4000
+
+#define QFILEEXT_UNKNOWN ""
+#define QFILEEXT_PAK ".PAK"
+#define QFILEEXT_PK3 ".PK3"
+#define QFILEEXT_SIN ".SIN"
+#define QFILEEXT_BSP ".BSP"
+#define QFILEEXT_MAP ".MAP"
+#define QFILEEXT_MDL ".MDL"
+#define QFILEEXT_MD2 ".MD2"
+#define QFILEEXT_MD3 ".MD3"
+#define QFILEEXT_WAL ".WAL"
+#define QFILEEXT_WAV ".WAV"
+#define QFILEEXT_AAS ".AAS"
+
+//maximum path length
+#ifndef _MAX_PATH
+ #define _MAX_PATH 1024
+#endif
+
+//for Sin packs
+#define MAX_PAK_FILENAME_LENGTH 120
+#define SINPAKHEADER (('K'<<24)+('A'<<16)+('P'<<8)+'S')
+
+typedef struct
+{
+ char name[MAX_PAK_FILENAME_LENGTH];
+ int filepos, filelen;
+} dsinpackfile_t;
+
+typedef struct quakefile_s
+{
+ char pakfile[_MAX_PATH];
+ char filename[_MAX_PATH];
+ char origname[_MAX_PATH];
+ int zipfile;
+ int type;
+ int offset;
+ int length;
+ unz_s zipinfo;
+ struct quakefile_s *next;
+} quakefile_t;
+
+//returns the file extension for the given type
+char *QuakeFileTypeExtension(int type);
+//returns the file type for the given extension
+int QuakeFileExtensionType(char *extension);
+//return the Quake file type for the given file
+int QuakeFileType(char *filename);
+//returns true if the filename complies to the filter
+int FileFilter(char *filter, char *filename, int casesensitive);
+//find Quake files using the given filter
+quakefile_t *FindQuakeFiles(char *filter);
+//load the given Quake file, returns the length of the file
+int LoadQuakeFile(quakefile_t *qf, void **bufferptr);
+//read part of a Quake file into the buffer
+int ReadQuakeFile(quakefile_t *qf, void *buffer, int offset, int length);
diff --git a/code/bspc/l_threads.c b/code/bspc/l_threads.c
new file mode 100755
index 0000000..bc4b998
--- /dev/null
+++ b/code/bspc/l_threads.c
@@ -0,0 +1,1510 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "l_cmd.h"
+#include "l_threads.h"
+#include "l_log.h"
+#include "l_mem.h"
+
+#define MAX_THREADS 64
+
+//#define THREAD_DEBUG
+
+int dispatch;
+int workcount;
+int oldf;
+qboolean pacifier;
+qboolean threaded;
+void (*workfunction) (int);
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int GetThreadWork(void)
+{
+ int r;
+ int f;
+
+ ThreadLock();
+
+ if (dispatch == workcount)
+ {
+ ThreadUnlock ();
+ return -1;
+ }
+
+ f = 10*dispatch / workcount;
+ if (f != oldf)
+ {
+ oldf = f;
+ if (pacifier)
+ printf ("%i...", f);
+ } //end if
+
+ r = dispatch;
+ dispatch++;
+ ThreadUnlock ();
+
+ return r;
+} //end of the function GetThreadWork
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadWorkerFunction(int threadnum)
+{
+ int work;
+
+ while(1)
+ {
+ work = GetThreadWork ();
+ if (work == -1)
+ break;
+//printf ("thread %i, work %i\n", threadnum, work);
+ workfunction(work);
+ } //end while
+} //end of the function ThreadWorkerFunction
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void RunThreadsOnIndividual (int workcnt, qboolean showpacifier, void(*func)(int))
+{
+ if (numthreads == -1)
+ ThreadSetDefault ();
+ workfunction = func;
+ RunThreadsOn (workcnt, showpacifier, ThreadWorkerFunction);
+} //end of the function RunThreadsOnIndividual
+
+
+//===================================================================
+//
+// WIN32
+//
+//===================================================================
+
+#if defined(WIN32) || defined(_WIN32)
+
+#define USED
+
+#include <windows.h>
+
+typedef struct thread_s
+{
+ HANDLE handle;
+ int threadid;
+ int id;
+ struct thread_s *next;
+} thread_t;
+
+thread_t *firstthread;
+thread_t *lastthread;
+int currentnumthreads;
+int currentthreadid;
+
+int numthreads = 1;
+CRITICAL_SECTION crit;
+HANDLE semaphore;
+static int enter;
+static int numwaitingthreads = 0;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadSetDefault(void)
+{
+ SYSTEM_INFO info;
+
+ if (numthreads == -1) // not set manually
+ {
+ GetSystemInfo (&info);
+ numthreads = info.dwNumberOfProcessors;
+ if (numthreads < 1 || numthreads > 32)
+ numthreads = 1;
+ } //end if
+ qprintf ("%i threads\n", numthreads);
+} //end of the function ThreadSetDefault
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadLock(void)
+{
+ if (!threaded)
+ {
+ Error("ThreadLock: !threaded");
+ return;
+ } //end if
+ EnterCriticalSection(&crit);
+ if (enter)
+ Error("Recursive ThreadLock\n");
+ enter = 1;
+} //end of the function ThreadLock
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadUnlock (void)
+{
+ if (!threaded)
+ {
+ Error("ThreadUnlock: !threaded");
+ return;
+ } //end if
+ if (!enter)
+ Error("ThreadUnlock without lock\n");
+ enter = 0;
+ LeaveCriticalSection(&crit);
+} //end of the function ThreadUnlock
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadSetupLock(void)
+{
+ Log_Print("Win32 multi-threading\n");
+ InitializeCriticalSection(&crit);
+ threaded = true; //Stupid me... forgot this!!!
+ currentnumthreads = 0;
+ currentthreadid = 0;
+} //end of the function ThreadInitLock
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadShutdownLock(void)
+{
+ DeleteCriticalSection(&crit);
+ threaded = false; //Stupid me... forgot this!!!
+} //end of the function ThreadShutdownLock
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadSetupSemaphore(void)
+{
+ semaphore = CreateSemaphore(NULL, 0, 99999999, "bspc");
+} //end of the function ThreadSetupSemaphore
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadShutdownSemaphore(void)
+{
+} //end of the function ThreadShutdownSemaphore
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadSemaphoreWait(void)
+{
+ WaitForSingleObject(semaphore, INFINITE);
+} //end of the function ThreadSemaphoreWait
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadSemaphoreIncrease(int count)
+{
+ ReleaseSemaphore(semaphore, count, NULL);
+} //end of the function ThreadSemaphoreIncrease
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void RunThreadsOn(int workcnt, qboolean showpacifier, void(*func)(int))
+{
+ int threadid[MAX_THREADS];
+ HANDLE threadhandle[MAX_THREADS];
+ int i;
+ int start, end;
+
+ Log_Print("Win32 multi-threading\n");
+ start = I_FloatTime ();
+ dispatch = 0;
+ workcount = workcnt;
+ oldf = -1;
+ pacifier = showpacifier;
+ threaded = true;
+
+ if (numthreads == -1)
+ ThreadSetDefault ();
+
+ if (numthreads < 1 || numthreads > MAX_THREADS) numthreads = 1;
+ //
+ // run threads in parallel
+ //
+ InitializeCriticalSection (&crit);
+
+ numwaitingthreads = 0;
+
+ if (numthreads == 1)
+ { // use same thread
+ func (0);
+ } //end if
+ else
+ {
+// printf("starting %d threads\n", numthreads);
+ for (i = 0; i < numthreads; i++)
+ {
+ threadhandle[i] = CreateThread(
+ NULL, // LPSECURITY_ATTRIBUTES lpsa,
+ 0, // DWORD cbStack,
+ (LPTHREAD_START_ROUTINE)func, // LPTHREAD_START_ROUTINE lpStartAddr,
+ (LPVOID)i, // LPVOID lpvThreadParm,
+ 0, // DWORD fdwCreate,
+ &threadid[i]);
+// printf("started thread %d\n", i);
+ } //end for
+
+ for (i = 0; i < numthreads; i++)
+ WaitForSingleObject (threadhandle[i], INFINITE);
+ } //end else
+ DeleteCriticalSection (&crit);
+
+ threaded = false;
+ end = I_FloatTime ();
+ if (pacifier) printf (" (%i)\n", end-start);
+} //end of the function RunThreadsOn
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AddThread(void (*func)(int))
+{
+ thread_t *thread;
+
+ if (numthreads == 1)
+ {
+ if (currentnumthreads >= numthreads) return;
+ currentnumthreads++;
+ func(-1);
+ currentnumthreads--;
+ } //end if
+ else
+ {
+ ThreadLock();
+ if (currentnumthreads >= numthreads)
+ {
+ ThreadUnlock();
+ return;
+ } //end if
+ //allocate new thread
+ thread = GetMemory(sizeof(thread_t));
+ if (!thread) Error("can't allocate memory for thread\n");
+
+ //
+ thread->threadid = currentthreadid;
+ thread->handle = CreateThread(
+ NULL, // LPSECURITY_ATTRIBUTES lpsa,
+ 0, // DWORD cbStack,
+ (LPTHREAD_START_ROUTINE)func, // LPTHREAD_START_ROUTINE lpStartAddr,
+ (LPVOID) thread->threadid, // LPVOID lpvThreadParm,
+ 0, // DWORD fdwCreate,
+ &thread->id);
+
+ //add the thread to the end of the list
+ thread->next = NULL;
+ if (lastthread) lastthread->next = thread;
+ else firstthread = thread;
+ lastthread = thread;
+ //
+#ifdef THREAD_DEBUG
+ qprintf("added thread with id %d\n", thread->threadid);
+#endif //THREAD_DEBUG
+ //
+ currentnumthreads++;
+ currentthreadid++;
+ //
+ ThreadUnlock();
+ } //end else
+} //end of the function AddThread
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void RemoveThread(int threadid)
+{
+ thread_t *thread, *last;
+
+ //if a single thread
+ if (threadid == -1) return;
+ //
+ ThreadLock();
+ last = NULL;
+ for (thread = firstthread; thread; thread = thread->next)
+ {
+ if (thread->threadid == threadid)
+ {
+ if (last) last->next = thread->next;
+ else firstthread = thread->next;
+ if (!thread->next) lastthread = last;
+ //
+ FreeMemory(thread);
+ currentnumthreads--;
+#ifdef THREAD_DEBUG
+ qprintf("removed thread with id %d\n", threadid);
+#endif //THREAD_DEBUG
+ break;
+ } //end if
+ last = thread;
+ } //end if
+ if (!thread) Error("couldn't find thread with id %d", threadid);
+ ThreadUnlock();
+} //end of the function RemoveThread
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void WaitForAllThreadsFinished(void)
+{
+ HANDLE handle;
+
+ ThreadLock();
+ while(firstthread)
+ {
+ handle = firstthread->handle;
+ ThreadUnlock();
+
+ WaitForSingleObject(handle, INFINITE);
+
+ ThreadLock();
+ } //end while
+ ThreadUnlock();
+} //end of the function WaitForAllThreadsFinished
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int GetNumThreads(void)
+{
+ return currentnumthreads;
+} //end of the function GetNumThreads
+
+#endif
+
+
+//===================================================================
+//
+// OSF1
+//
+//===================================================================
+
+#if defined(__osf__)
+
+#define USED
+
+#include <pthread.h>
+
+typedef struct thread_s
+{
+ pthread_t thread;
+ int threadid;
+ int id;
+ struct thread_s *next;
+} thread_t;
+
+thread_t *firstthread;
+thread_t *lastthread;
+int currentnumthreads;
+int currentthreadid;
+
+int numthreads = 1;
+pthread_mutex_t my_mutex;
+pthread_attr_t attrib;
+static int enter;
+static int numwaitingthreads = 0;
+
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadSetDefault(void)
+{
+ if (numthreads == -1) // not set manually
+ {
+ numthreads = 1;
+ } //end if
+ qprintf("%i threads\n", numthreads);
+} //end of the function ThreadSetDefault
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadLock(void)
+{
+ if (!threaded)
+ {
+ Error("ThreadLock: !threaded");
+ return;
+ } //end if
+ if (my_mutex)
+ {
+ pthread_mutex_lock(my_mutex);
+ } //end if
+ if (enter)
+ Error("Recursive ThreadLock\n");
+ enter = 1;
+} //end of the function ThreadLock
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadUnlock(void)
+{
+ if (!threaded)
+ {
+ Error("ThreadUnlock: !threaded");
+ return;
+ } //end if
+ if (!enter)
+ Error("ThreadUnlock without lock\n");
+ enter = 0;
+ if (my_mutex)
+ {
+ pthread_mutex_unlock(my_mutex);
+ } //end if
+} //end of the function ThreadUnlock
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadSetupLock(void)
+{
+ pthread_mutexattr_t mattrib;
+
+ Log_Print("pthread multi-threading\n");
+
+ if (!my_mutex)
+ {
+ my_mutex = GetMemory(sizeof(*my_mutex));
+ if (pthread_mutexattr_create (&mattrib) == -1)
+ Error ("pthread_mutex_attr_create failed");
+ if (pthread_mutexattr_setkind_np (&mattrib, MUTEX_FAST_NP) == -1)
+ Error ("pthread_mutexattr_setkind_np failed");
+ if (pthread_mutex_init (my_mutex, mattrib) == -1)
+ Error ("pthread_mutex_init failed");
+ }
+
+ if (pthread_attr_create (&attrib) == -1)
+ Error ("pthread_attr_create failed");
+ if (pthread_attr_setstacksize (&attrib, 0x100000) == -1)
+ Error ("pthread_attr_setstacksize failed");
+
+ threaded = true;
+ currentnumthreads = 0;
+ currentthreadid = 0;
+} //end of the function ThreadInitLock
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadShutdownLock(void)
+{
+ threaded = false;
+} //end of the function ThreadShutdownLock
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void RunThreadsOn(int workcnt, qboolean showpacifier, void(*func)(int))
+{
+ int i;
+ pthread_t work_threads[MAX_THREADS];
+ pthread_addr_t status;
+ pthread_attr_t attrib;
+ pthread_mutexattr_t mattrib;
+ int start, end;
+
+ Log_Print("pthread multi-threading\n");
+
+ start = I_FloatTime ();
+ dispatch = 0;
+ workcount = workcnt;
+ oldf = -1;
+ pacifier = showpacifier;
+ threaded = true;
+
+ if (numthreads < 1 || numthreads > MAX_THREADS) numthreads = 1;
+
+ if (pacifier)
+ setbuf (stdout, NULL);
+
+ if (!my_mutex)
+ {
+ my_mutex = GetMemory(sizeof(*my_mutex));
+ if (pthread_mutexattr_create (&mattrib) == -1)
+ Error ("pthread_mutex_attr_create failed");
+ if (pthread_mutexattr_setkind_np (&mattrib, MUTEX_FAST_NP) == -1)
+ Error ("pthread_mutexattr_setkind_np failed");
+ if (pthread_mutex_init (my_mutex, mattrib) == -1)
+ Error ("pthread_mutex_init failed");
+ }
+
+ if (pthread_attr_create (&attrib) == -1)
+ Error ("pthread_attr_create failed");
+ if (pthread_attr_setstacksize (&attrib, 0x100000) == -1)
+ Error ("pthread_attr_setstacksize failed");
+
+ for (i=0 ; i<numthreads ; i++)
+ {
+ if (pthread_create(&work_threads[i], attrib
+ , (pthread_startroutine_t)func, (pthread_addr_t)i) == -1)
+ Error ("pthread_create failed");
+ }
+
+ for (i=0 ; i<numthreads ; i++)
+ {
+ if (pthread_join (work_threads[i], &status) == -1)
+ Error ("pthread_join failed");
+ }
+
+ threaded = false;
+
+ end = I_FloatTime ();
+ if (pacifier)
+ printf (" (%i)\n", end-start);
+} //end of the function RunThreadsOn
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AddThread(void (*func)(int))
+{
+ thread_t *thread;
+
+ if (numthreads == 1)
+ {
+ if (currentnumthreads >= numthreads) return;
+ currentnumthreads++;
+ func(-1);
+ currentnumthreads--;
+ } //end if
+ else
+ {
+ ThreadLock();
+ if (currentnumthreads >= numthreads)
+ {
+ ThreadUnlock();
+ return;
+ } //end if
+ //allocate new thread
+ thread = GetMemory(sizeof(thread_t));
+ if (!thread) Error("can't allocate memory for thread\n");
+ //
+ thread->threadid = currentthreadid;
+
+ if (pthread_create(&thread->thread, attrib, (pthread_startroutine_t)func, (pthread_addr_t)thread->threadid) == -1)
+ Error ("pthread_create failed");
+
+ //add the thread to the end of the list
+ thread->next = NULL;
+ if (lastthread) lastthread->next = thread;
+ else firstthread = thread;
+ lastthread = thread;
+ //
+#ifdef THREAD_DEBUG
+ qprintf("added thread with id %d\n", thread->threadid);
+#endif //THREAD_DEBUG
+ //
+ currentnumthreads++;
+ currentthreadid++;
+ //
+ ThreadUnlock();
+ } //end else
+} //end of the function AddThread
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void RemoveThread(int threadid)
+{
+ thread_t *thread, *last;
+
+ //if a single thread
+ if (threadid == -1) return;
+ //
+ ThreadLock();
+ last = NULL;
+ for (thread = firstthread; thread; thread = thread->next)
+ {
+ if (thread->threadid == threadid)
+ {
+ if (last) last->next = thread->next;
+ else firstthread = thread->next;
+ if (!thread->next) lastthread = last;
+ //
+ FreeMemory(thread);
+ currentnumthreads--;
+#ifdef THREAD_DEBUG
+ qprintf("removed thread with id %d\n", threadid);
+#endif //THREAD_DEBUG
+ break;
+ } //end if
+ last = thread;
+ } //end if
+ if (!thread) Error("couldn't find thread with id %d", threadid);
+ ThreadUnlock();
+} //end of the function RemoveThread
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void WaitForAllThreadsFinished(void)
+{
+ pthread_t *thread;
+ pthread_addr_t status;
+
+ ThreadLock();
+ while(firstthread)
+ {
+ thread = &firstthread->thread;
+ ThreadUnlock();
+
+ if (pthread_join(*thread, &status) == -1)
+ Error("pthread_join failed");
+
+ ThreadLock();
+ } //end while
+ ThreadUnlock();
+} //end of the function WaitForAllThreadsFinished
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int GetNumThreads(void)
+{
+ return currentnumthreads;
+} //end of the function GetNumThreads
+
+#endif
+
+//===================================================================
+//
+// LINUX
+//
+//===================================================================
+
+#if defined(LINUX)
+
+#define USED
+
+#include <pthread.h>
+#include <semaphore.h>
+
+typedef struct thread_s
+{
+ pthread_t thread;
+ int threadid;
+ int id;
+ struct thread_s *next;
+} thread_t;
+
+thread_t *firstthread;
+thread_t *lastthread;
+int currentnumthreads;
+int currentthreadid;
+
+int numthreads = 1;
+pthread_mutex_t my_mutex = PTHREAD_MUTEX_INITIALIZER;
+pthread_attr_t attrib;
+sem_t semaphore;
+static int enter;
+static int numwaitingthreads = 0;
+
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadSetDefault(void)
+{
+ if (numthreads == -1) // not set manually
+ {
+ numthreads = 1;
+ } //end if
+ qprintf("%i threads\n", numthreads);
+} //end of the function ThreadSetDefault
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadLock(void)
+{
+ if (!threaded)
+ {
+ Error("ThreadLock: !threaded");
+ return;
+ } //end if
+ pthread_mutex_lock(&my_mutex);
+ if (enter)
+ Error("Recursive ThreadLock\n");
+ enter = 1;
+} //end of the function ThreadLock
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadUnlock(void)
+{
+ if (!threaded)
+ {
+ Error("ThreadUnlock: !threaded");
+ return;
+ } //end if
+ if (!enter)
+ Error("ThreadUnlock without lock\n");
+ enter = 0;
+ pthread_mutex_unlock(&my_mutex);
+} //end of the function ThreadUnlock
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadSetupLock(void)
+{
+ pthread_mutexattr_t mattrib;
+
+ Log_Print("pthread multi-threading\n");
+
+ threaded = true;
+ currentnumthreads = 0;
+ currentthreadid = 0;
+} //end of the function ThreadInitLock
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadShutdownLock(void)
+{
+ threaded = false;
+} //end of the function ThreadShutdownLock
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadSetupSemaphore(void)
+{
+ sem_init(&semaphore, 0, 0);
+} //end of the function ThreadSetupSemaphore
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadShutdownSemaphore(void)
+{
+ sem_destroy(&semaphore);
+} //end of the function ThreadShutdownSemaphore
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadSemaphoreWait(void)
+{
+ sem_wait(&semaphore);
+} //end of the function ThreadSemaphoreWait
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadSemaphoreIncrease(int count)
+{
+ int i;
+
+ for (i = 0; i < count; i++)
+ {
+ sem_post(&semaphore);
+ } //end for
+} //end of the function ThreadSemaphoreIncrease
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void RunThreadsOn(int workcnt, qboolean showpacifier, void(*func)(int))
+{
+ int i;
+ pthread_t work_threads[MAX_THREADS];
+ void *pthread_return;
+ pthread_attr_t attrib;
+ pthread_mutexattr_t mattrib;
+ int start, end;
+
+ Log_Print("pthread multi-threading\n");
+
+ start = I_FloatTime ();
+ dispatch = 0;
+ workcount = workcnt;
+ oldf = -1;
+ pacifier = showpacifier;
+ threaded = true;
+
+ if (numthreads < 1 || numthreads > MAX_THREADS) numthreads = 1;
+
+ if (pacifier)
+ setbuf (stdout, NULL);
+
+ for (i=0 ; i<numthreads ; i++)
+ {
+ if (pthread_create(&work_threads[i], NULL, (void *)func, (void *)i) == -1)
+ Error ("pthread_create failed");
+ }
+
+ for (i=0 ; i<numthreads ; i++)
+ {
+ if (pthread_join(work_threads[i], &pthread_return) == -1)
+ Error ("pthread_join failed");
+ }
+
+ threaded = false;
+
+ end = I_FloatTime ();
+ if (pacifier)
+ printf (" (%i)\n", end-start);
+} //end of the function RunThreadsOn
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AddThread(void (*func)(int))
+{
+ thread_t *thread;
+
+ if (numthreads == 1)
+ {
+ if (currentnumthreads >= numthreads) return;
+ currentnumthreads++;
+ func(-1);
+ currentnumthreads--;
+ } //end if
+ else
+ {
+ ThreadLock();
+ if (currentnumthreads >= numthreads)
+ {
+ ThreadUnlock();
+ return;
+ } //end if
+ //allocate new thread
+ thread = GetMemory(sizeof(thread_t));
+ if (!thread) Error("can't allocate memory for thread\n");
+ //
+ thread->threadid = currentthreadid;
+
+ if (pthread_create(&thread->thread, NULL, (void *)func, (void *)thread->threadid) == -1)
+ Error ("pthread_create failed");
+
+ //add the thread to the end of the list
+ thread->next = NULL;
+ if (lastthread) lastthread->next = thread;
+ else firstthread = thread;
+ lastthread = thread;
+ //
+#ifdef THREAD_DEBUG
+ qprintf("added thread with id %d\n", thread->threadid);
+#endif //THREAD_DEBUG
+ //
+ currentnumthreads++;
+ currentthreadid++;
+ //
+ ThreadUnlock();
+ } //end else
+} //end of the function AddThread
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void RemoveThread(int threadid)
+{
+ thread_t *thread, *last;
+
+ //if a single thread
+ if (threadid == -1) return;
+ //
+ ThreadLock();
+ last = NULL;
+ for (thread = firstthread; thread; thread = thread->next)
+ {
+ if (thread->threadid == threadid)
+ {
+ if (last) last->next = thread->next;
+ else firstthread = thread->next;
+ if (!thread->next) lastthread = last;
+ //
+ FreeMemory(thread);
+ currentnumthreads--;
+#ifdef THREAD_DEBUG
+ qprintf("removed thread with id %d\n", threadid);
+#endif //THREAD_DEBUG
+ break;
+ } //end if
+ last = thread;
+ } //end if
+ if (!thread) Error("couldn't find thread with id %d", threadid);
+ ThreadUnlock();
+} //end of the function RemoveThread
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void WaitForAllThreadsFinished(void)
+{
+ pthread_t *thread;
+ void *pthread_return;
+
+ ThreadLock();
+ while(firstthread)
+ {
+ thread = &firstthread->thread;
+ ThreadUnlock();
+
+ if (pthread_join(*thread, &pthread_return) == -1)
+ Error("pthread_join failed");
+
+ ThreadLock();
+ } //end while
+ ThreadUnlock();
+} //end of the function WaitForAllThreadsFinished
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int GetNumThreads(void)
+{
+ return currentnumthreads;
+} //end of the function GetNumThreads
+
+#endif //LINUX
+
+
+//===================================================================
+//
+// IRIX
+//
+//===================================================================
+
+#ifdef _MIPS_ISA
+
+#define USED
+
+#include <task.h>
+#include <abi_mutex.h>
+#include <sys/types.h>
+#include <sys/prctl.h>
+
+typedef struct thread_s
+{
+ int threadid;
+ int id;
+ struct thread_s *next;
+} thread_t;
+
+thread_t *firstthread;
+thread_t *lastthread;
+int currentnumthreads;
+int currentthreadid;
+
+int numthreads = 1;
+static int enter;
+static int numwaitingthreads = 0;
+
+abilock_t lck;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadSetDefault (void)
+{
+ if (numthreads == -1)
+ numthreads = prctl(PR_MAXPPROCS);
+ printf ("%i threads\n", numthreads);
+//@@
+ usconfig (CONF_INITUSERS, numthreads);
+} //end of the function ThreadSetDefault
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadLock (void)
+{
+ spin_lock (&lck);
+} //end of the function ThreadLock
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadUnlock (void)
+{
+ release_lock(&lck);
+} //end of the function ThreadUnlock
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadSetupLock(void)
+{
+ init_lock (&lck);
+
+ Log_Print("IRIX multi-threading\n");
+
+ threaded = true;
+ currentnumthreads = 0;
+ currentthreadid = 0;
+} //end of the function ThreadInitLock
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadShutdownLock(void)
+{
+ threaded = false;
+} //end of the function ThreadShutdownLock
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void RunThreadsOn (int workcnt, qboolean showpacifier, void(*func)(int))
+{
+ int i;
+ int pid[MAX_THREADS];
+ int start, end;
+
+ start = I_FloatTime ();
+ dispatch = 0;
+ workcount = workcnt;
+ oldf = -1;
+ pacifier = showpacifier;
+ threaded = true;
+
+ if (numthreads < 1 || numthreads > MAX_THREADS) numthreads = 1;
+
+ if (pacifier)
+ setbuf (stdout, NULL);
+
+ init_lock (&lck);
+
+ for (i=0 ; i<numthreads-1 ; i++)
+ {
+ pid[i] = sprocsp ( (void (*)(void *, size_t))func, PR_SALL, (void *)i
+ , NULL, 0x100000);
+// pid[i] = sprocsp ( (void (*)(void *, size_t))func, PR_SALL, (void *)i
+// , NULL, 0x80000);
+ if (pid[i] == -1)
+ {
+ perror ("sproc");
+ Error ("sproc failed");
+ }
+ }
+
+ func(i);
+
+ for (i=0 ; i<numthreads-1 ; i++)
+ wait (NULL);
+
+ threaded = false;
+
+ end = I_FloatTime ();
+ if (pacifier)
+ printf (" (%i)\n", end-start);
+} //end of the function RunThreadsOn
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AddThread(void (*func)(int))
+{
+ thread_t *thread;
+
+ if (numthreads == 1)
+ {
+ if (currentnumthreads >= numthreads) return;
+ currentnumthreads++;
+ func(-1);
+ currentnumthreads--;
+ } //end if
+ else
+ {
+ ThreadLock();
+ if (currentnumthreads >= numthreads)
+ {
+ ThreadUnlock();
+ return;
+ } //end if
+ //allocate new thread
+ thread = GetMemory(sizeof(thread_t));
+ if (!thread) Error("can't allocate memory for thread\n");
+ //
+ thread->threadid = currentthreadid;
+
+ thread->id = sprocsp ( (void (*)(void *, size_t))func, PR_SALL, (void *)thread->threadid, NULL, 0x100000);
+ if (thread->id == -1)
+ {
+ perror ("sproc");
+ Error ("sproc failed");
+ }
+
+ //add the thread to the end of the list
+ thread->next = NULL;
+ if (lastthread) lastthread->next = thread;
+ else firstthread = thread;
+ lastthread = thread;
+ //
+#ifdef THREAD_DEBUG
+ qprintf("added thread with id %d\n", thread->threadid);
+#endif //THREAD_DEBUG
+ //
+ currentnumthreads++;
+ currentthreadid++;
+ //
+ ThreadUnlock();
+ } //end else
+} //end of the function AddThread
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void RemoveThread(int threadid)
+{
+ thread_t *thread, *last;
+
+ //if a single thread
+ if (threadid == -1) return;
+ //
+ ThreadLock();
+ last = NULL;
+ for (thread = firstthread; thread; thread = thread->next)
+ {
+ if (thread->threadid == threadid)
+ {
+ if (last) last->next = thread->next;
+ else firstthread = thread->next;
+ if (!thread->next) lastthread = last;
+ //
+ FreeMemory(thread);
+ currentnumthreads--;
+#ifdef THREAD_DEBUG
+ qprintf("removed thread with id %d\n", threadid);
+#endif //THREAD_DEBUG
+ break;
+ } //end if
+ last = thread;
+ } //end if
+ if (!thread) Error("couldn't find thread with id %d", threadid);
+ ThreadUnlock();
+} //end of the function RemoveThread
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void WaitForAllThreadsFinished(void)
+{
+ ThreadLock();
+ while(firstthread)
+ {
+ ThreadUnlock();
+
+ //wait (NULL);
+
+ ThreadLock();
+ } //end while
+ ThreadUnlock();
+} //end of the function WaitForAllThreadsFinished
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int GetNumThreads(void)
+{
+ return currentnumthreads;
+} //end of the function GetNumThreads
+
+#endif //_MIPS_ISA
+
+
+//=======================================================================
+//
+// SINGLE THREAD
+//
+//=======================================================================
+
+#ifndef USED
+
+int numthreads = 1;
+int currentnumthreads = 0;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadSetDefault(void)
+{
+ numthreads = 1;
+} //end of the function ThreadSetDefault
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadLock(void)
+{
+} //end of the function ThreadLock
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadUnlock(void)
+{
+} //end of the function ThreadUnlock
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadSetupLock(void)
+{
+ Log_Print("no multi-threading\n");
+} //end of the function ThreadInitLock
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadShutdownLock(void)
+{
+} //end of the function ThreadShutdownLock
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadSetupSemaphore(void)
+{
+} //end of the function ThreadSetupSemaphore
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadShutdownSemaphore(void)
+{
+} //end of the function ThreadShutdownSemaphore
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadSemaphoreWait(void)
+{
+} //end of the function ThreadSemaphoreWait
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ThreadSemaphoreIncrease(int count)
+{
+} //end of the function ThreadSemaphoreIncrease
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void RunThreadsOn(int workcnt, qboolean showpacifier, void(*func)(int))
+{
+ int start, end;
+
+ Log_Print("no multi-threading\n");
+ dispatch = 0;
+ workcount = workcnt;
+ oldf = -1;
+ pacifier = showpacifier;
+ start = I_FloatTime ();
+#ifdef NeXT
+ if (pacifier)
+ setbuf (stdout, NULL);
+#endif
+ func(0);
+
+ end = I_FloatTime ();
+ if (pacifier)
+ printf (" (%i)\n", end-start);
+} //end of the function RunThreadsOn
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AddThread(void (*func)(int))
+{
+ if (currentnumthreads >= numthreads) return;
+ currentnumthreads++;
+ func(-1);
+ currentnumthreads--;
+} //end of the function AddThread
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void RemoveThread(int threadid)
+{
+} //end of the function RemoveThread
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void WaitForAllThreadsFinished(void)
+{
+} //end of the function WaitForAllThreadsFinished
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int GetNumThreads(void)
+{
+ return currentnumthreads;
+} //end of the function GetNumThreads
+
+#endif //USED
diff --git a/code/bspc/l_threads.h b/code/bspc/l_threads.h
new file mode 100755
index 0000000..2c6d8df
--- /dev/null
+++ b/code/bspc/l_threads.h
@@ -0,0 +1,45 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+extern int numthreads;
+
+void ThreadSetDefault (void);
+int GetThreadWork (void);
+void RunThreadsOnIndividual (int workcnt, qboolean showpacifier, void(*func)(int));
+void RunThreadsOn (int workcnt, qboolean showpacifier, void(*func)(int));
+
+//mutex
+void ThreadSetupLock(void);
+void ThreadShutdownLock(void);
+void ThreadLock (void);
+void ThreadUnlock (void);
+//semaphore
+void ThreadSetupSemaphore(void);
+void ThreadShutdownSemaphore(void);
+void ThreadSemaphoreWait(void);
+void ThreadSemaphoreIncrease(int count);
+//add/remove threads
+void AddThread(void (*func)(int));
+void RemoveThread(int threadid);
+void WaitForAllThreadsFinished(void);
+int GetNumThreads(void);
+
diff --git a/code/bspc/l_utils.c b/code/bspc/l_utils.c
new file mode 100755
index 0000000..f9d6d5f
--- /dev/null
+++ b/code/bspc/l_utils.c
@@ -0,0 +1,259 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+//#ifndef BOTLIB
+//#define BOTLIB
+//#endif //BOTLIB
+
+#ifdef BOTLIB
+#include "q_shared.h"
+#include "qfiles.h"
+#include "botlib.h"
+#include "l_log.h"
+#include "l_libvar.h"
+#include "l_memory.h"
+//#include "l_utils.h"
+#include "be_interface.h"
+#else //BOTLIB
+#include "qbsp.h"
+#include "l_mem.h"
+#endif //BOTLIB
+
+#ifdef BOTLIB
+//========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//========================================================================
+void Vector2Angles(vec3_t value1, vec3_t angles)
+{
+ float forward;
+ float yaw, pitch;
+
+ if (value1[1] == 0 && value1[0] == 0)
+ {
+ yaw = 0;
+ if (value1[2] > 0) pitch = 90;
+ else pitch = 270;
+ } //end if
+ else
+ {
+ yaw = (int) (atan2(value1[1], value1[0]) * 180 / M_PI);
+ if (yaw < 0) yaw += 360;
+
+ forward = sqrt (value1[0]*value1[0] + value1[1]*value1[1]);
+ pitch = (int) (atan2(value1[2], forward) * 180 / M_PI);
+ if (pitch < 0) pitch += 360;
+ } //end else
+
+ angles[PITCH] = -pitch;
+ angles[YAW] = yaw;
+ angles[ROLL] = 0;
+} //end of the function Vector2Angles
+#endif //BOTLIB
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ConvertPath(char *path)
+{
+ while(*path)
+ {
+ if (*path == '/' || *path == '\\') *path = PATHSEPERATOR_CHAR;
+ path++;
+ } //end while
+} //end of the function ConvertPath
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AppendPathSeperator(char *path, int length)
+{
+ int pathlen = strlen(path);
+
+ if (strlen(path) && length-pathlen > 1 && path[pathlen-1] != '/' && path[pathlen-1] != '\\')
+ {
+ path[pathlen] = PATHSEPERATOR_CHAR;
+ path[pathlen+1] = '\0';
+ } //end if
+} //end of the function AppenPathSeperator
+
+#if 0
+//===========================================================================
+// returns pointer to file handle
+// sets offset to and length of 'filename' in the pak file
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean FindFileInPak(char *pakfile, char *filename, foundfile_t *file)
+{
+ FILE *fp;
+ dpackheader_t packheader;
+ dpackfile_t *packfiles;
+ int numdirs, i;
+ char path[MAX_PATH];
+
+ //open the pak file
+ fp = fopen(pakfile, "rb");
+ if (!fp)
+ {
+ return false;
+ } //end if
+ //read pak header, check for valid pak id and seek to the dir entries
+ if ((fread(&packheader, 1, sizeof(dpackheader_t), fp) != sizeof(dpackheader_t))
+ || (packheader.ident != IDPAKHEADER)
+ || (fseek(fp, LittleLong(packheader.dirofs), SEEK_SET))
+ )
+ {
+ fclose(fp);
+ return false;
+ } //end if
+ //number of dir entries in the pak file
+ numdirs = LittleLong(packheader.dirlen) / sizeof(dpackfile_t);
+ packfiles = (dpackfile_t *) GetMemory(numdirs * sizeof(dpackfile_t));
+ //read the dir entry
+ if (fread(packfiles, sizeof(dpackfile_t), numdirs, fp) != numdirs)
+ {
+ fclose(fp);
+ FreeMemory(packfiles);
+ return false;
+ } //end if
+ fclose(fp);
+ //
+ strcpy(path, filename);
+ ConvertPath(path);
+ //find the dir entry in the pak file
+ for (i = 0; i < numdirs; i++)
+ {
+ //convert the dir entry name
+ ConvertPath(packfiles[i].name);
+ //compare the dir entry name with the filename
+ if (Q_strcasecmp(packfiles[i].name, path) == 0)
+ {
+ strcpy(file->filename, pakfile);
+ file->offset = LittleLong(packfiles[i].filepos);
+ file->length = LittleLong(packfiles[i].filelen);
+ FreeMemory(packfiles);
+ return true;
+ } //end if
+ } //end for
+ FreeMemory(packfiles);
+ return false;
+} //end of the function FindFileInPak
+//===========================================================================
+// find a Quake2 file
+// returns full path in 'filename'
+// sets offset and length of the file
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean FindQuakeFile2(char *basedir, char *gamedir, char *filename, foundfile_t *file)
+{
+ int dir, i;
+ //NOTE: 3 is necessary (LCC bug???)
+ char gamedirs[3][MAX_PATH] = {"","",""};
+ char filedir[MAX_PATH] = "";
+
+ //
+ if (gamedir) strncpy(gamedirs[0], gamedir, MAX_PATH);
+ strncpy(gamedirs[1], "baseq2", MAX_PATH);
+ //
+ //find the file in the two game directories
+ for (dir = 0; dir < 2; dir++)
+ {
+ //check if the file is in a directory
+ filedir[0] = 0;
+ if (basedir && strlen(basedir))
+ {
+ strncpy(filedir, basedir, MAX_PATH);
+ AppendPathSeperator(filedir, MAX_PATH);
+ } //end if
+ if (strlen(gamedirs[dir]))
+ {
+ strncat(filedir, gamedirs[dir], MAX_PATH - strlen(filedir));
+ AppendPathSeperator(filedir, MAX_PATH);
+ } //end if
+ strncat(filedir, filename, MAX_PATH - strlen(filedir));
+ ConvertPath(filedir);
+ Log_Write("accessing %s", filedir);
+ if (!access(filedir, 0x04))
+ {
+ strcpy(file->filename, filedir);
+ file->length = 0;
+ file->offset = 0;
+ return true;
+ } //end if
+ //check if the file is in a pak?.pak
+ for (i = 0; i < 10; i++)
+ {
+ filedir[0] = 0;
+ if (basedir && strlen(basedir))
+ {
+ strncpy(filedir, basedir, MAX_PATH);
+ AppendPathSeperator(filedir, MAX_PATH);
+ } //end if
+ if (strlen(gamedirs[dir]))
+ {
+ strncat(filedir, gamedirs[dir], MAX_PATH - strlen(filedir));
+ AppendPathSeperator(filedir, MAX_PATH);
+ } //end if
+ sprintf(&filedir[strlen(filedir)], "pak%d.pak\0", i);
+ if (!access(filedir, 0x04))
+ {
+ Log_Write("searching %s in %s", filename, filedir);
+ if (FindFileInPak(filedir, filename, file)) return true;
+ } //end if
+ } //end for
+ } //end for
+ file->offset = 0;
+ file->length = 0;
+ return false;
+} //end of the function FindQuakeFile2
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+#ifdef BOTLIB
+qboolean FindQuakeFile(char *filename, foundfile_t *file)
+{
+ return FindQuakeFile2(LibVarGetString("basedir"),
+ LibVarGetString("gamedir"), filename, file);
+} //end of the function FindQuakeFile
+#else //BOTLIB
+qboolean FindQuakeFile(char *basedir, char *gamedir, char *filename, foundfile_t *file)
+{
+ return FindQuakeFile2(basedir, gamedir, filename, file);
+} //end of the function FindQuakeFile
+#endif //BOTLIB
+
+#endif
diff --git a/code/bspc/l_utils.h b/code/bspc/l_utils.h
new file mode 100755
index 0000000..2ef9161
--- /dev/null
+++ b/code/bspc/l_utils.h
@@ -0,0 +1,79 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#ifndef MAX_PATH
+ #define MAX_PATH 64
+#endif
+
+#ifndef PATH_SEPERATORSTR
+ #if defined(WIN32)|defined(_WIN32)|defined(__NT__)|defined(__WINDOWS__)|defined(__WINDOWS_386__)
+ #define PATHSEPERATOR_STR "\\"
+ #else
+ #define PATHSEPERATOR_STR "/"
+ #endif
+#endif
+#ifndef PATH_SEPERATORCHAR
+ #if defined(WIN32)|defined(_WIN32)|defined(__NT__)|defined(__WINDOWS__)|defined(__WINDOWS_386__)
+ #define PATHSEPERATOR_CHAR '\\'
+ #else
+ #define PATHSEPERATOR_CHAR '/'
+ #endif
+#endif
+
+//random in the range [0, 1]
+#define random() ((rand () & 0x7fff) / ((float)0x7fff))
+//random in the range [-1, 1]
+#define crandom() (2.0 * (random() - 0.5))
+//min and max
+#define Maximum(x,y) (x > y ? x : y)
+#define Minimum(x,y) (x < y ? x : y)
+//absolute value
+#define FloatAbs(x) (*(float *) &((* (int *) &(x)) & 0x7FFFFFFF))
+#define IntAbs(x) (~(x))
+//coordinates
+#define _X 0
+#define _Y 1
+#define _Z 2
+
+typedef struct foundfile_s
+{
+ int offset;
+ int length;
+ char filename[MAX_PATH]; //screw LCC, array must be at end of struct
+} foundfile_t;
+
+void Vector2Angles(vec3_t value1, vec3_t angles);
+//set the correct path seperators
+void ConvertPath(char *path);
+//append a path seperator to the given path not exceeding the length
+void AppendPathSeperator(char *path, int length);
+//find a file in a pak file
+qboolean FindFileInPak(char *pakfile, char *filename, foundfile_t *file);
+//find a quake file
+#ifdef BOTLIB
+qboolean FindQuakeFile(char *filename, foundfile_t *file);
+#else //BOTLIB
+qboolean FindQuakeFile(char *basedir, char *gamedir, char *filename, foundfile_t *file);
+#endif //BOTLIB
+
+
+
diff --git a/code/bspc/lcc.mak b/code/bspc/lcc.mak
new file mode 100755
index 0000000..d74adce
--- /dev/null
+++ b/code/bspc/lcc.mak
@@ -0,0 +1,61 @@
+#
+# Makefile for the BSPC tool for the Gladiator Bot
+# Intended for LCC-Win32
+#
+
+CC=lcc
+CFLAGS=-DC_ONLY -o
+OBJS= _files.obj\
+ aas_areamerging.obj\
+ aas_cfg.obj\
+ aas_create.obj\
+ aas_edgemelting.obj\
+ aas_facemerging.obj\
+ aas_file.obj\
+ aas_gsubdiv.obj\
+ aas_map.obj\
+ aas_prunenodes.obj\
+ aas_store.obj\
+ brushbsp.obj\
+ bspc.obj\
+ csg.obj\
+ faces.obj\
+ glfile.obj\
+ l_bsp_hl.obj\
+ l_bsp_q1.obj\
+ l_bsp_q2.obj\
+ l_bsp_sin.obj\
+ l_cmd.obj\
+ l_log.obj\
+ l_math.obj\
+ l_mem.obj\
+ l_poly.obj\
+ l_qfiles.obj\
+ l_script.obj\
+ l_threads.obj\
+ l_utils.obj\
+ leakfile.obj\
+ map.obj\
+ map_hl.obj\
+ map_q1.obj\
+ map_q2.obj\
+ map_q2_new.obj\
+ map_sin.obj\
+ nodraw.obj\
+ portals.obj\
+ prtfile.obj\
+ textures.obj\
+ tree.obj\
+ writebsp.obj
+
+all: bspc.exe
+
+bspc.exe: $(OBJS)
+ lcclnk
+
+clean:
+ del *.obj bspc.exe
+
+%.obj: %.c
+ $(CC) $(CFLAGS) $<
+
diff --git a/code/bspc/leakfile.c b/code/bspc/leakfile.c
new file mode 100755
index 0000000..7118759
--- /dev/null
+++ b/code/bspc/leakfile.c
@@ -0,0 +1,101 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+
+/*
+==============================================================================
+
+LEAF FILE GENERATION
+
+Save out name.line for qe3 to read
+==============================================================================
+*/
+
+
+/*
+=============
+LeakFile
+
+Finds the shortest possible chain of portals
+that leads from the outside leaf to a specifically
+occupied leaf
+=============
+*/
+void LeakFile (tree_t *tree)
+{
+ vec3_t mid;
+ FILE *linefile;
+ char filename[1024];
+ node_t *node;
+ int count;
+
+ if (!tree->outside_node.occupied)
+ return;
+
+ qprintf ("--- LeakFile ---\n");
+
+ //
+ // write the points to the file
+ //
+ sprintf (filename, "%s.lin", source);
+ qprintf ("%s\n", filename);
+ linefile = fopen (filename, "w");
+ if (!linefile)
+ Error ("Couldn't open %s\n", filename);
+
+ count = 0;
+ node = &tree->outside_node;
+ while (node->occupied > 1)
+ {
+ int next;
+ portal_t *p, *nextportal;
+ node_t *nextnode;
+ int s;
+
+ // find the best portal exit
+ next = node->occupied;
+ for (p=node->portals ; p ; p = p->next[!s])
+ {
+ s = (p->nodes[0] == node);
+ if (p->nodes[s]->occupied
+ && p->nodes[s]->occupied < next)
+ {
+ nextportal = p;
+ nextnode = p->nodes[s];
+ next = nextnode->occupied;
+ }
+ }
+ node = nextnode;
+ WindingCenter (nextportal->winding, mid);
+ fprintf (linefile, "%f %f %f\n", mid[0], mid[1], mid[2]);
+ count++;
+ }
+ // add the occupant center
+ GetVectorForKey (node->occupant, "origin", mid);
+
+ fprintf (linefile, "%f %f %f\n", mid[0], mid[1], mid[2]);
+ qprintf ("%5i point linefile\n", count+1);
+
+ fclose (linefile);
+}
+
diff --git a/code/bspc/linux-i386.mak b/code/bspc/linux-i386.mak
new file mode 100755
index 0000000..00a261d
--- /dev/null
+++ b/code/bspc/linux-i386.mak
@@ -0,0 +1,109 @@
+#
+# Makefile for the BSPC tool for the Gladiator Bot
+# Intended for gcc/Linux
+#
+
+ARCH=i386
+CC=gcc
+BASE_CFLAGS=-Dstricmp=strcasecmp
+
+#use these cflags to optimize it
+CFLAGS=$(BASE_CFLAGS) -m486 -O6 -ffast-math -funroll-loops \
+ -fomit-frame-pointer -fexpensive-optimizations -malign-loops=2 \
+ -malign-jumps=2 -malign-functions=2 -DLINUX -DBSPC
+#use these when debugging
+#CFLAGS=$(BASE_CFLAGS) -g
+
+LDFLAGS=-ldl -lm -lpthread
+
+DO_CC=$(CC) $(CFLAGS) -o $@ -c $<
+
+#############################################################################
+# SETUP AND BUILD BSPC
+#############################################################################
+
+.c.o:
+ $(DO_CC)
+
+GAME_OBJS = \
+ _files.o\
+ aas_areamerging.o\
+ aas_cfg.o\
+ aas_create.o\
+ aas_edgemelting.o\
+ aas_facemerging.o\
+ aas_file.o\
+ aas_gsubdiv.o\
+ aas_map.o\
+ aas_prunenodes.o\
+ aas_store.o\
+ be_aas_bspc.o\
+ ../botlib/be_aas_bspq3.o\
+ ../botlib/be_aas_cluster.o\
+ ../botlib/be_aas_move.o\
+ ../botlib/be_aas_optimize.o\
+ ../botlib/be_aas_reach.o\
+ ../botlib/be_aas_sample.o\
+ brushbsp.o\
+ bspc.o\
+ ../qcommon/cm_load.o\
+ ../qcommon/cm_patch.o\
+ ../qcommon/cm_test.o\
+ ../qcommon/cm_trace.o\
+ csg.o\
+ glfile.o\
+ l_bsp_ent.o\
+ l_bsp_hl.o\
+ l_bsp_q1.o\
+ l_bsp_q2.o\
+ l_bsp_q3.o\
+ l_bsp_sin.o\
+ l_cmd.o\
+ ../botlib/l_libvar.o\
+ l_log.o\
+ l_math.o\
+ l_mem.o\
+ l_poly.o\
+ ../botlib/l_precomp.o\
+ l_qfiles.o\
+ ../botlib/l_script.o\
+ ../botlib/l_struct.o\
+ l_threads.o\
+ l_utils.o\
+ leakfile.o\
+ map.o\
+ map_hl.o\
+ map_q1.o\
+ map_q2.o\
+ map_q3.o\
+ map_sin.o\
+ ../qcommon/md4.o\
+ nodraw.o\
+ portals.o\
+ tetrahedron.o\
+ textures.o\
+ tree.o\
+ ../qcommon/unzip.o
+
+bspc$(ARCH) : $(GAME_OBJS)
+ $(CC) $(CFLAGS) -o $@ $(GAME_OBJS) $(LDFLAGS)
+
+
+#############################################################################
+# MISC
+#############################################################################
+
+clean:
+ -rm -f $(GAME_OBJS)
+
+depend:
+ gcc -MM $(GAME_OBJS:.o=.c)
+
+
+install:
+ cp bspci386 ..
+
+#
+# From "make depend"
+#
+
diff --git a/code/bspc/map.c b/code/bspc/map.c
new file mode 100755
index 0000000..613c234
--- /dev/null
+++ b/code/bspc/map.c
@@ -0,0 +1,1267 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+#include "l_bsp_hl.h"
+#include "l_bsp_q1.h"
+#include "l_bsp_q2.h"
+#include "l_bsp_q3.h"
+#include "l_bsp_sin.h"
+#include "l_mem.h"
+#include "../botlib/aasfile.h" //aas_bbox_t
+#include "aas_store.h" //AAS_MAX_BBOXES
+#include "aas_cfg.h"
+
+#define Sign(x) (x < 0 ? 1 : 0)
+
+int nummapbrushes;
+mapbrush_t mapbrushes[MAX_MAPFILE_BRUSHES];
+
+int nummapbrushsides;
+side_t brushsides[MAX_MAPFILE_BRUSHSIDES];
+brush_texture_t side_brushtextures[MAX_MAPFILE_BRUSHSIDES];
+
+int nummapplanes;
+plane_t mapplanes[MAX_MAPFILE_PLANES];
+int mapplaneusers[MAX_MAPFILE_PLANES];
+
+#define PLANE_HASHES 1024
+plane_t *planehash[PLANE_HASHES];
+vec3_t map_mins, map_maxs;
+
+#ifdef SIN
+textureref_t side_newrefs[MAX_MAPFILE_BRUSHSIDES];
+#endif
+
+map_texinfo_t map_texinfo[MAX_MAPFILE_TEXINFO];
+int map_numtexinfo;
+int loadedmaptype; //loaded map type
+
+// undefine to make plane finding use linear sort
+#define USE_HASHING
+
+int c_boxbevels;
+int c_edgebevels;
+int c_areaportals;
+int c_clipbrushes;
+int c_squattbrushes;
+int c_writtenbrushes;
+
+/*
+=============================================================================
+
+PLANE FINDING
+
+=============================================================================
+*/
+
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int PlaneSignBits(vec3_t normal)
+{
+ int i, signbits;
+
+ signbits = 0;
+ for (i = 2; i >= 0; i--)
+ {
+ signbits = (signbits << 1) + Sign(normal[i]);
+ } //end for
+ return signbits;
+} //end of the function PlaneSignBits
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int PlaneTypeForNormal(vec3_t normal)
+{
+ vec_t ax, ay, az;
+
+// NOTE: should these have an epsilon around 1.0?
+ if (normal[0] == 1.0 || normal[0] == -1.0)
+ return PLANE_X;
+ if (normal[1] == 1.0 || normal[1] == -1.0)
+ return PLANE_Y;
+ if (normal[2] == 1.0 || normal[2] == -1.0)
+ return PLANE_Z;
+
+ ax = fabs(normal[0]);
+ ay = fabs(normal[1]);
+ az = fabs(normal[2]);
+
+ if (ax >= ay && ax >= az)
+ return PLANE_ANYX;
+ if (ay >= ax && ay >= az)
+ return PLANE_ANYY;
+ return PLANE_ANYZ;
+} //end of the function PlaneTypeForNormal
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+//ME NOTE: changed from 0.00001
+#define NORMAL_EPSILON 0.0001
+//ME NOTE: changed from 0.01
+#define DIST_EPSILON 0.02
+qboolean PlaneEqual(plane_t *p, vec3_t normal, vec_t dist)
+{
+#if 1
+ if (
+ fabs(p->normal[0] - normal[0]) < NORMAL_EPSILON
+ && fabs(p->normal[1] - normal[1]) < NORMAL_EPSILON
+ && fabs(p->normal[2] - normal[2]) < NORMAL_EPSILON
+ && fabs(p->dist - dist) < DIST_EPSILON )
+ return true;
+#else
+ if (p->normal[0] == normal[0]
+ && p->normal[1] == normal[1]
+ && p->normal[2] == normal[2]
+ && p->dist == dist)
+ return true;
+#endif
+ return false;
+} //end of the function PlaneEqual
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AddPlaneToHash(plane_t *p)
+{
+ int hash;
+
+ hash = (int)fabs(p->dist) / 8;
+ hash &= (PLANE_HASHES-1);
+
+ p->hash_chain = planehash[hash];
+ planehash[hash] = p;
+} //end of the function AddPlaneToHash
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int CreateNewFloatPlane (vec3_t normal, vec_t dist)
+{
+ plane_t *p, temp;
+
+ if (VectorLength(normal) < 0.5)
+ Error ("FloatPlane: bad normal");
+ // create a new plane
+ if (nummapplanes+2 > MAX_MAPFILE_PLANES)
+ Error ("MAX_MAPFILE_PLANES");
+
+ p = &mapplanes[nummapplanes];
+ VectorCopy (normal, p->normal);
+ p->dist = dist;
+ p->type = (p+1)->type = PlaneTypeForNormal (p->normal);
+ p->signbits = PlaneSignBits(p->normal);
+
+ VectorSubtract (vec3_origin, normal, (p+1)->normal);
+ (p+1)->dist = -dist;
+ (p+1)->signbits = PlaneSignBits((p+1)->normal);
+
+ nummapplanes += 2;
+
+ // allways put axial planes facing positive first
+ if (p->type < 3)
+ {
+ if (p->normal[0] < 0 || p->normal[1] < 0 || p->normal[2] < 0)
+ {
+ // flip order
+ temp = *p;
+ *p = *(p+1);
+ *(p+1) = temp;
+
+ AddPlaneToHash (p);
+ AddPlaneToHash (p+1);
+ return nummapplanes - 1;
+ }
+ }
+
+ AddPlaneToHash (p);
+ AddPlaneToHash (p+1);
+ return nummapplanes - 2;
+} //end of the function CreateNewFloatPlane
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void SnapVector(vec3_t normal)
+{
+ int i;
+
+ for (i=0 ; i<3 ; i++)
+ {
+ if ( fabs(normal[i] - 1) < NORMAL_EPSILON )
+ {
+ VectorClear (normal);
+ normal[i] = 1;
+ break;
+ }
+ if ( fabs(normal[i] - -1) < NORMAL_EPSILON )
+ {
+ VectorClear (normal);
+ normal[i] = -1;
+ break;
+ }
+ }
+} //end of the function SnapVector
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void SnapPlane(vec3_t normal, vec_t *dist)
+{
+ SnapVector(normal);
+
+ if (fabs(*dist-Q_rint(*dist)) < DIST_EPSILON)
+ *dist = Q_rint(*dist);
+} //end of the function SnapPlane
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+#ifndef USE_HASHING
+int FindFloatPlane(vec3_t normal, vec_t dist)
+{
+ int i;
+ plane_t *p;
+
+ SnapPlane(normal, &dist);
+ for (i = 0, p = mapplanes; i < nummapplanes; i++, p++)
+ {
+ if (PlaneEqual (p, normal, dist))
+ {
+ mapplaneusers[i]++;
+ return i;
+ } //end if
+ } //end for
+ i = CreateNewFloatPlane (normal, dist);
+ mapplaneusers[i]++;
+ return i;
+} //end of the function FindFloatPlane
+#else
+int FindFloatPlane (vec3_t normal, vec_t dist)
+{
+ int i;
+ plane_t *p;
+ int hash, h;
+
+ SnapPlane (normal, &dist);
+ hash = (int)fabs(dist) / 8;
+ hash &= (PLANE_HASHES-1);
+
+ // search the border bins as well
+ for (i = -1; i <= 1; i++)
+ {
+ h = (hash+i)&(PLANE_HASHES-1);
+ for (p = planehash[h]; p; p = p->hash_chain)
+ {
+ if (PlaneEqual(p, normal, dist))
+ {
+ mapplaneusers[p-mapplanes]++;
+ return p - mapplanes;
+ } //end if
+ } //end for
+ } //end for
+ i = CreateNewFloatPlane (normal, dist);
+ mapplaneusers[i]++;
+ return i;
+} //end of the function FindFloatPlane
+#endif
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int PlaneFromPoints (int *p0, int *p1, int *p2)
+{
+ vec3_t t1, t2, normal;
+ vec_t dist;
+
+ VectorSubtract (p0, p1, t1);
+ VectorSubtract (p2, p1, t2);
+ CrossProduct (t1, t2, normal);
+ VectorNormalize (normal);
+
+ dist = DotProduct (p0, normal);
+
+ return FindFloatPlane (normal, dist);
+} //end of the function PlaneFromPoints
+//===========================================================================
+// Adds any additional planes necessary to allow the brush to be expanded
+// against axial bounding boxes
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AddBrushBevels (mapbrush_t *b)
+{
+ int axis, dir;
+ int i, j, k, l, order;
+ side_t sidetemp;
+ brush_texture_t tdtemp;
+#ifdef SIN
+ textureref_t trtemp;
+#endif
+ side_t *s, *s2;
+ vec3_t normal;
+ float dist;
+ winding_t *w, *w2;
+ vec3_t vec, vec2;
+ float d;
+
+ //
+ // add the axial planes
+ //
+ order = 0;
+ for (axis=0 ; axis <3 ; axis++)
+ {
+ for (dir=-1 ; dir <= 1 ; dir+=2, order++)
+ {
+ // see if the plane is allready present
+ for (i=0, s=b->original_sides ; i<b->numsides ; i++,s++)
+ {
+ if (mapplanes[s->planenum].normal[axis] == dir)
+ break;
+ }
+
+ if (i == b->numsides)
+ { // add a new side
+ if (nummapbrushsides == MAX_MAP_BRUSHSIDES)
+ Error ("MAX_MAP_BRUSHSIDES");
+ nummapbrushsides++;
+ b->numsides++;
+ VectorClear (normal);
+ normal[axis] = dir;
+ if (dir == 1)
+ dist = b->maxs[axis];
+ else
+ dist = -b->mins[axis];
+ s->planenum = FindFloatPlane (normal, dist);
+ s->texinfo = b->original_sides[0].texinfo;
+#ifdef SIN
+ s->lightinfo = b->original_sides[0].lightinfo;
+#endif
+ s->contents = b->original_sides[0].contents;
+ s->flags |= SFL_BEVEL;
+ c_boxbevels++;
+ }
+
+ // if the plane is not in it canonical order, swap it
+ if (i != order)
+ {
+ sidetemp = b->original_sides[order];
+ b->original_sides[order] = b->original_sides[i];
+ b->original_sides[i] = sidetemp;
+
+ j = b->original_sides - brushsides;
+ tdtemp = side_brushtextures[j+order];
+ side_brushtextures[j+order] = side_brushtextures[j+i];
+ side_brushtextures[j+i] = tdtemp;
+
+#ifdef SIN
+ trtemp = side_newrefs[j+order];
+ side_newrefs[j+order] = side_newrefs[j+i];
+ side_newrefs[j+i] = trtemp;
+#endif
+ }
+ }
+ }
+
+ //
+ // add the edge bevels
+ //
+ if (b->numsides == 6)
+ return; // pure axial
+
+ // test the non-axial plane edges
+ for (i=6 ; i<b->numsides ; i++)
+ {
+ s = b->original_sides + i;
+ w = s->winding;
+ if (!w)
+ continue;
+ for (j=0 ; j<w->numpoints ; j++)
+ {
+ k = (j+1)%w->numpoints;
+ VectorSubtract (w->p[j], w->p[k], vec);
+ if (VectorNormalize (vec) < 0.5)
+ continue;
+ SnapVector (vec);
+ for (k=0 ; k<3 ; k++)
+ if ( vec[k] == -1 || vec[k] == 1)
+ break; // axial
+ if (k != 3)
+ continue; // only test non-axial edges
+
+ // try the six possible slanted axials from this edge
+ for (axis=0 ; axis <3 ; axis++)
+ {
+ for (dir=-1 ; dir <= 1 ; dir+=2)
+ {
+ // construct a plane
+ VectorClear (vec2);
+ vec2[axis] = dir;
+ CrossProduct (vec, vec2, normal);
+ if (VectorNormalize (normal) < 0.5)
+ continue;
+ dist = DotProduct (w->p[j], normal);
+
+ // if all the points on all the sides are
+ // behind this plane, it is a proper edge bevel
+ for (k=0 ; k<b->numsides ; k++)
+ {
+ // if this plane has allready been used, skip it
+ if (PlaneEqual (&mapplanes[b->original_sides[k].planenum]
+ , normal, dist) )
+ break;
+
+ w2 = b->original_sides[k].winding;
+ if (!w2)
+ continue;
+ for (l=0 ; l<w2->numpoints ; l++)
+ {
+ d = DotProduct (w2->p[l], normal) - dist;
+ if (d > 0.1)
+ break; // point in front
+ }
+ if (l != w2->numpoints)
+ break;
+ }
+
+ if (k != b->numsides)
+ continue; // wasn't part of the outer hull
+ // add this plane
+ if (nummapbrushsides == MAX_MAP_BRUSHSIDES)
+ Error ("MAX_MAP_BRUSHSIDES");
+ nummapbrushsides++;
+ s2 = &b->original_sides[b->numsides];
+ s2->planenum = FindFloatPlane (normal, dist);
+ s2->texinfo = b->original_sides[0].texinfo;
+#ifdef SIN
+ s2->lightinfo = b->original_sides[0].lightinfo;
+#endif
+ s2->contents = b->original_sides[0].contents;
+ s2->flags |= SFL_BEVEL;
+ c_edgebevels++;
+ b->numsides++;
+ }
+ }
+ }
+ }
+} //end of the function AddBrushBevels
+//===========================================================================
+// creates windigs for sides and mins / maxs for the brush
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean MakeBrushWindings(mapbrush_t *ob)
+{
+ int i, j;
+ winding_t *w;
+ side_t *side;
+ plane_t *plane;
+
+ ClearBounds (ob->mins, ob->maxs);
+
+ for (i = 0; i < ob->numsides; i++)
+ {
+ plane = &mapplanes[ob->original_sides[i].planenum];
+ w = BaseWindingForPlane(plane->normal, plane->dist);
+ for (j = 0; j <ob->numsides && w; j++)
+ {
+ if (i == j) continue;
+ if (ob->original_sides[j].flags & SFL_BEVEL) continue;
+ plane = &mapplanes[ob->original_sides[j].planenum^1];
+ ChopWindingInPlace(&w, plane->normal, plane->dist, 0); //CLIP_EPSILON);
+ }
+
+ side = &ob->original_sides[i];
+ side->winding = w;
+ if (w)
+ {
+ side->flags |= SFL_VISIBLE;
+ for (j = 0; j < w->numpoints; j++)
+ AddPointToBounds (w->p[j], ob->mins, ob->maxs);
+ }
+ }
+
+ for (i = 0; i < 3; i++)
+ {
+ //IDBUG: all the indexes into the mins and maxs were zero (not using i)
+ if (ob->mins[i] < -MAX_MAP_BOUNDS || ob->maxs[i] > MAX_MAP_BOUNDS)
+ {
+ Log_Print("entity %i, brush %i: bounds out of range\n", ob->entitynum, ob->brushnum);
+ ob->numsides = 0; //remove the brush
+ break;
+ } //end if
+ if (ob->mins[i] > MAX_MAP_BOUNDS || ob->maxs[i] < -MAX_MAP_BOUNDS)
+ {
+ Log_Print("entity %i, brush %i: no visible sides on brush\n", ob->entitynum, ob->brushnum);
+ ob->numsides = 0; //remove the brush
+ break;
+ } //end if
+ } //end for
+ return true;
+} //end of the function MakeBrushWindings
+//===========================================================================
+// FIXME: currently doesn't mark all bevels
+// NOTE: when one brush bevel is found the remaining sides of the brush
+// are bevels as well (when the brush isn't expanded for AAS :))
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void MarkBrushBevels(mapbrush_t *brush)
+{
+ int i;
+ int we;
+ side_t *s;
+
+ //check all the sides of the brush
+ for (i = 0; i < brush->numsides; i++)
+ {
+ s = brush->original_sides + i;
+ //if the side has no winding
+ if (!s->winding)
+ {
+ Log_Write("MarkBrushBevels: brush %d no winding", brush->brushnum);
+ s->flags |= SFL_BEVEL;
+ } //end if
+ //if the winding is tiny
+ else if (WindingIsTiny(s->winding))
+ {
+ s->flags |= SFL_BEVEL;
+ Log_Write("MarkBrushBevels: brush %d tiny winding", brush->brushnum);
+ } //end else if
+ //if the winding has errors
+ else
+ {
+ we = WindingError(s->winding);
+ if (we == WE_NOTENOUGHPOINTS
+ || we == WE_SMALLAREA
+ || we == WE_POINTBOGUSRANGE
+// || we == WE_NONCONVEX
+ )
+ {
+ Log_Write("MarkBrushBevels: brush %d %s", brush->brushnum, WindingErrorString());
+ s->flags |= SFL_BEVEL;
+ } //end else if
+ } //end else
+ if (s->flags & SFL_BEVEL)
+ {
+ s->flags &= ~SFL_VISIBLE;
+ //if the side has a valid plane
+ if (s->planenum > 0 && s->planenum < nummapplanes)
+ {
+ //if it is an axial plane
+ if (mapplanes[s->planenum].type < 3) c_boxbevels++;
+ else c_edgebevels++;
+ } //end if
+ } //end if
+ } //end for
+} //end of the function MarkBrushBevels
+//===========================================================================
+// returns true if the map brush already exists
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int BrushExists(mapbrush_t *brush)
+{
+ int i, s1, s2;
+ side_t *side1, *side2;
+ mapbrush_t *brush1, *brush2;
+
+ for (i = 0; i < nummapbrushes; i++)
+ {
+ brush1 = brush;
+ brush2 = &mapbrushes[i];
+ //compare the brushes
+ if (brush1->entitynum != brush2->entitynum) continue;
+ //if (brush1->contents != brush2->contents) continue;
+ if (brush1->numsides != brush2->numsides) continue;
+ for (s1 = 0; s1 < brush1->numsides; s1++)
+ {
+ side1 = brush1->original_sides + s1;
+ //
+ for (s2 = 0; s2 < brush2->numsides; s2++)
+ {
+ side2 = brush2->original_sides + s2;
+ //
+ if ((side1->planenum & ~1) == (side2->planenum & ~1)
+// && side1->texinfo == side2->texinfo
+// && side1->contents == side2->contents
+// && side1->surf == side2->surf
+ ) break;
+ } //end if
+ if (s2 >= brush2->numsides) break;
+ } //end for
+ if (s1 >= brush1->numsides) return true;
+ } //end for
+ return false;
+} //end of the function BrushExists
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean WriteMapBrush(FILE *fp, mapbrush_t *brush, vec3_t origin)
+{
+ int sn, rotate, shift[2], sv, tv, planenum, p1, i, j;
+ float scale[2], originshift[2], ang1, ang2, newdist;
+ vec3_t vecs[2], axis[2];
+ map_texinfo_t *ti;
+ winding_t *w;
+ side_t *s;
+ plane_t *plane;
+
+ if (noliquids)
+ {
+ if (brush->contents & (CONTENTS_WATER|CONTENTS_SLIME|CONTENTS_LAVA))
+ {
+ return true;
+ } //end if
+ } //end if
+ //if the brush has no contents
+ if (!brush->contents) return true;
+ //print the leading {
+ if (fprintf(fp, " { //brush %d\n", brush->brushnum) < 0) return false;
+ //write brush sides
+ for (sn = 0; sn < brush->numsides; sn++)
+ {
+ s = brush->original_sides + sn;
+ //don't write out bevels
+ if (!(s->flags & SFL_BEVEL))
+ {
+ //if the entity has an origin set
+ if (origin[0] || origin[1] || origin[2])
+ {
+ newdist = mapplanes[s->planenum].dist +
+ DotProduct(mapplanes[s->planenum].normal, origin);
+ planenum = FindFloatPlane(mapplanes[s->planenum].normal, newdist);
+ } //end if
+ else
+ {
+ planenum = s->planenum;
+ } //end else
+ //always take the first plane, then flip the points if necesary
+ plane = &mapplanes[planenum & ~1];
+ w = BaseWindingForPlane(plane->normal, plane->dist);
+ //
+ for (i = 0; i < 3; i++)
+ {
+ for (j = 0; j < 3; j++)
+ {
+ if (fabs(w->p[i][j]) < 0.2) w->p[i][j] = 0;
+ else if (fabs((int)w->p[i][j] - w->p[i][j]) < 0.3) w->p[i][j] = (int) w->p[i][j];
+ //w->p[i][j] = (int) (w->p[i][j] + 0.2);
+ } //end for
+ } //end for
+ //three non-colinear points to define the plane
+ if (planenum & 1) p1 = 1;
+ else p1 = 0;
+ if (fprintf(fp," ( %5i %5i %5i ) ", (int)w->p[p1][0], (int)w->p[p1][1], (int)w->p[p1][2]) < 0) return false;
+ if (fprintf(fp,"( %5i %5i %5i ) ", (int)w->p[!p1][0], (int)w->p[!p1][1], (int)w->p[!p1][2]) < 0) return false;
+ if (fprintf(fp,"( %5i %5i %5i ) ", (int)w->p[2][0], (int)w->p[2][1], (int)w->p[2][2]) < 0) return false;
+ //free the winding
+ FreeWinding(w);
+ //
+ if (s->texinfo == TEXINFO_NODE)
+ {
+ if (brush->contents & CONTENTS_PLAYERCLIP)
+ {
+ //player clip
+ if (loadedmaptype == MAPTYPE_SIN)
+ {
+ if (fprintf(fp, "generic/misc/clip 0 0 0 1 1") < 0) return false;
+ } //end if
+ else if (loadedmaptype == MAPTYPE_QUAKE2)
+ { //FIXME: don't always use e1u1
+ if (fprintf(fp, "e1u1/clip 0 0 0 1 1") < 0) return false;
+ } //end else
+ else if (loadedmaptype == MAPTYPE_QUAKE3)
+ {
+ if (fprintf(fp, "e1u1/clip 0 0 0 1 1") < 0) return false;
+ } //end else if
+ else
+ {
+ if (fprintf(fp, "clip 0 0 0 1 1") < 0) return false;
+ } //end else
+ } //end if
+ else if (brush->contents == CONTENTS_MONSTERCLIP)
+ {
+ //monster clip
+ if (loadedmaptype == MAPTYPE_SIN)
+ {
+ if (fprintf(fp, "generic/misc/monster 0 0 0 1 1") < 0) return false;
+ } //end if
+ else if (loadedmaptype == MAPTYPE_QUAKE2)
+ {
+ if (fprintf(fp, "e1u1/clip_mon 0 0 0 1 1") < 0) return false;
+ } //end else
+ else
+ {
+ if (fprintf(fp, "clip 0 0 0 1 1") < 0) return false;
+ } //end else
+ } //end else
+ else
+ {
+ if (fprintf(fp, "clip 0 0 0 1 1") < 0) return false;
+ Log_Write("brush->contents = %d\n", brush->contents);
+ } //end else
+ } //end if
+ else if (loadedmaptype == MAPTYPE_SIN && s->texinfo == 0)
+ {
+ if (brush->contents & CONTENTS_DUMMYFENCE)
+ {
+ if (fprintf(fp, "generic/misc/fence 0 0 0 1 1") < 0) return false;
+ } //end if
+ else if (brush->contents & CONTENTS_MIST)
+ {
+ if (fprintf(fp, "generic/misc/volumetric_base 0 0 0 1 1") < 0) return false;
+ } //end if
+ else //unknown so far
+ {
+ if (fprintf(fp, "generic/misc/red 0 0 0 1 1") < 0) return false;
+ } //end else
+ } //end if
+ else if (loadedmaptype == MAPTYPE_QUAKE3)
+ {
+ //always use the same texture
+ if (fprintf(fp, "e2u3/floor1_2 0 0 0 1 1 1 0 0") < 0) return false;
+ } //end else if
+ else
+ {
+ //*
+ ti = &map_texinfo[s->texinfo];
+ //the scaling of the texture
+ scale[0] = 1 / VectorNormalize2(ti->vecs[0], vecs[0]);
+ scale[1] = 1 / VectorNormalize2(ti->vecs[1], vecs[1]);
+ //
+ TextureAxisFromPlane(plane, axis[0], axis[1]);
+ //calculate texture shift done by entity origin
+ originshift[0] = DotProduct(origin, axis[0]);
+ originshift[1] = DotProduct(origin, axis[1]);
+ //the texture shift without origin shift
+ shift[0] = ti->vecs[0][3] - originshift[0];
+ shift[1] = ti->vecs[1][3] - originshift[1];
+ //
+ if (axis[0][0]) sv = 0;
+ else if (axis[0][1]) sv = 1;
+ else sv = 2;
+ if (axis[1][0]) tv = 0;
+ else if (axis[1][1]) tv = 1;
+ else tv = 2;
+ //calculate rotation of texture
+ if (vecs[0][tv] == 0) ang1 = vecs[0][sv] > 0 ? 90.0 : -90.0;
+ else ang1 = atan2(vecs[0][sv], vecs[0][tv]) * 180 / Q_PI;
+ if (ang1 < 0) ang1 += 360;
+ if (ang1 >= 360) ang1 -= 360;
+ if (axis[0][tv] == 0) ang2 = axis[0][sv] > 0 ? 90.0 : -90.0;
+ else ang2 = atan2(axis[0][sv], axis[0][tv]) * 180 / Q_PI;
+ if (ang2 < 0) ang2 += 360;
+ if (ang2 >= 360) ang2 -= 360;
+ rotate = ang2 - ang1;
+ if (rotate < 0) rotate += 360;
+ if (rotate >= 360) rotate -= 360;
+ //write the texture info
+ if (fprintf(fp, "%s %d %d %d", ti->texture, shift[0], shift[1], rotate) < 0) return false;
+ if (fabs(scale[0] - ((int) scale[0])) < 0.001)
+ {
+ if (fprintf(fp, " %d", (int) scale[0]) < 0) return false;
+ } //end if
+ else
+ {
+ if (fprintf(fp, " %4f", scale[0]) < 0) return false;
+ } //end if
+ if (fabs(scale[1] - ((int) scale[1])) < 0.001)
+ {
+ if (fprintf(fp, " %d", (int) scale[1]) < 0) return false;
+ } //end if
+ else
+ {
+ if (fprintf(fp, " %4f", scale[1]) < 0) return false;
+ } //end else
+ //write the extra brush side info
+ if (loadedmaptype == MAPTYPE_QUAKE2)
+ {
+ if (fprintf(fp, " %ld %ld %ld", s->contents, ti->flags, ti->value) < 0) return false;
+ } //end if
+ //*/
+ } //end else
+ if (fprintf(fp, "\n") < 0) return false;
+ } //end if
+ } //end if
+ if (fprintf(fp, " }\n") < 0) return false;
+ c_writtenbrushes++;
+ return true;
+} //end of the function WriteMapBrush
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean WriteOriginBrush(FILE *fp, vec3_t origin)
+{
+ vec3_t normal;
+ float dist;
+ int i, s;
+ winding_t *w;
+
+ if (fprintf(fp, " {\n") < 0) return false;
+ //
+ for (i = 0; i < 3; i++)
+ {
+ for (s = -1; s <= 1; s += 2)
+ {
+ //
+ VectorClear(normal);
+ normal[i] = s;
+ dist = origin[i] * s + 16;
+ //
+ w = BaseWindingForPlane(normal, dist);
+ //three non-colinear points to define the plane
+ if (fprintf(fp," ( %5i %5i %5i ) ", (int)w->p[0][0], (int)w->p[0][1], (int)w->p[0][2]) < 0) return false;
+ if (fprintf(fp,"( %5i %5i %5i ) ", (int)w->p[1][0], (int)w->p[1][1], (int)w->p[1][2]) < 0) return false;
+ if (fprintf(fp,"( %5i %5i %5i ) ", (int)w->p[2][0], (int)w->p[2][1], (int)w->p[2][2]) < 0) return false;
+ //free the winding
+ FreeWinding(w);
+ //write origin texture:
+ // CONTENTS_ORIGIN = 16777216
+ // SURF_NODRAW = 128
+ if (loadedmaptype == MAPTYPE_SIN)
+ {
+ if (fprintf(fp, "generic/misc/origin 0 0 0 1 1") < 0) return false;
+ } //end if
+ else if (loadedmaptype == MAPTYPE_HALFLIFE)
+ {
+ if (fprintf(fp, "origin 0 0 0 1 1") < 0) return false;
+ } //end if
+ else
+ {
+ if (fprintf(fp, "e1u1/origin 0 0 0 1 1") < 0) return false;
+ } //end else
+ //Quake2 extra brush side info
+ if (loadedmaptype == MAPTYPE_QUAKE2)
+ {
+ //if (fprintf(fp, " 16777216 128 0") < 0) return false;
+ } //end if
+ if (fprintf(fp, "\n") < 0) return false;
+ } //end for
+ } //end for
+ if (fprintf(fp, " }\n") < 0) return false;
+ c_writtenbrushes++;
+ return true;
+} //end of the function WriteOriginBrush
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+mapbrush_t *GetAreaPortalBrush(entity_t *mapent)
+{
+ int portalnum, bn;
+ mapbrush_t *brush;
+
+ //the area portal number
+ portalnum = mapent->areaportalnum;
+ //find the area portal brush in the world brushes
+ for (bn = 0; bn < nummapbrushes && portalnum; bn++)
+ {
+ brush = &mapbrushes[bn];
+ //must be in world entity
+ if (brush->entitynum == 0)
+ {
+ if (brush->contents & CONTENTS_AREAPORTAL)
+ {
+ portalnum--;
+ } //end if
+ } //end if
+ } //end for
+ if (bn < nummapbrushes)
+ {
+ return brush;
+ } //end if
+ else
+ {
+ Log_Print("area portal %d brush not found\n", mapent->areaportalnum);
+ return NULL;
+ } //end else
+} //end of the function GetAreaPortalBrush
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean WriteMapFileSafe(FILE *fp)
+{
+ char key[1024], value[1024];
+ int i, bn, entitybrushes;
+ epair_t *ep;
+ mapbrush_t *brush;
+ entity_t *mapent;
+ //vec3_t vec_origin = {0, 0, 0};
+
+ //
+ if (fprintf(fp,"//=====================================================\n"
+ "//\n"
+ "// map file created with BSPC "BSPC_VERSION"\n"
+ "//\n"
+ "// BSPC is designed to decompile material in which you own the copyright\n"
+ "// or have obtained permission to decompile from the copyright owner. Unless\n"
+ "// you own the copyright or have permission to decompile from the copyright\n"
+ "// owner, you may be violating copyright law and be subject to payment of\n"
+ "// damages and other remedies. If you are uncertain about your rights, contact\n"
+ "// your legal advisor.\n"
+ "//\n") < 0) return false;
+ if (loadedmaptype == MAPTYPE_SIN)
+ {
+ if (fprintf(fp,
+ "// generic/misc/red is used for unknown textures\n") < 0) return false;
+ } //end if
+ if (fprintf(fp,"//\n"
+ "//=====================================================\n") < 0) return false;
+ //write out all the entities
+ for (i = 0; i < num_entities; i++)
+ {
+ mapent = &entities[i];
+ if (!mapent->epairs)
+ {
+ continue;
+ } //end if
+ if (fprintf(fp, "{\n") < 0) return false;
+ //
+ if (loadedmaptype == MAPTYPE_QUAKE3)
+ {
+ if (!stricmp(ValueForKey(mapent, "classname"), "light"))
+ {
+ SetKeyValue(mapent, "light", "10000");
+ } //end if
+ } //end if
+ //write epairs
+ for (ep = mapent->epairs; ep; ep = ep->next)
+ {
+ strcpy(key, ep->key);
+ StripTrailing (key);
+ strcpy(value, ep->value);
+ StripTrailing(value);
+ //
+ if (loadedmaptype == MAPTYPE_QUAKE2 ||
+ loadedmaptype == MAPTYPE_SIN)
+ {
+ //don't write an origin for BSP models
+ if (mapent->modelnum >= 0 && !strcmp(key, "origin")) continue;
+ } //end if
+ //don't write BSP model numbers
+ if (mapent->modelnum >= 0 && !strcmp(key, "model") && value[0] == '*') continue;
+ //
+ if (fprintf(fp, " \"%s\" \"%s\"\n", key, value) < 0) return false;
+ } //end for
+ //
+ if (ValueForKey(mapent, "origin")) GetVectorForKey(mapent, "origin", mapent->origin);
+ else mapent->origin[0] = mapent->origin[1] = mapent->origin[2] = 0;
+ //if this is an area portal entity
+ if (!strcmp("func_areaportal", ValueForKey(mapent, "classname")))
+ {
+ brush = GetAreaPortalBrush(mapent);
+ if (!brush) return false;
+ if (!WriteMapBrush(fp, brush, mapent->origin)) return false;
+ } //end if
+ else
+ {
+ entitybrushes = false;
+ //write brushes
+ for (bn = 0; bn < nummapbrushes; bn++)
+ {
+ brush = &mapbrushes[bn];
+ //if the brush is part of this entity
+ if (brush->entitynum == i)
+ {
+ //don't write out area portal brushes in the world
+ if (!((brush->contents & CONTENTS_AREAPORTAL) && brush->entitynum == 0))
+ {
+ /*
+ if (!strcmp("func_door_rotating", ValueForKey(mapent, "classname")))
+ {
+ AAS_PositionFuncRotatingBrush(mapent, brush);
+ if (!WriteMapBrush(fp, brush, vec_origin)) return false;
+ } //end if
+ else //*/
+ {
+ if (!WriteMapBrush(fp, brush, mapent->origin)) return false;
+ } //end else
+ entitybrushes = true;
+ } //end if
+ } //end if
+ } //end for
+ //if the entity had brushes
+ if (entitybrushes)
+ {
+ //if the entity has an origin set
+ if (mapent->origin[0] || mapent->origin[1] || mapent->origin[2])
+ {
+ if (!WriteOriginBrush(fp, mapent->origin)) return false;
+ } //end if
+ } //end if
+ } //end else
+ if (fprintf(fp, "}\n") < 0) return false;
+ } //end for
+ if (fprintf(fp, "//total of %d brushes\n", c_writtenbrushes) < 0) return false;
+ return true;
+} //end of the function WriteMapFileSafe
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void WriteMapFile(char *filename)
+{
+ FILE *fp;
+ double start_time;
+
+ c_writtenbrushes = 0;
+ //the time started
+ start_time = I_FloatTime();
+ //
+ Log_Print("writing %s\n", filename);
+ fp = fopen(filename, "wb");
+ if (!fp)
+ {
+ Log_Print("can't open %s\n", filename);
+ return;
+ } //end if
+ if (!WriteMapFileSafe(fp))
+ {
+ fclose(fp);
+ Log_Print("error writing map file %s\n", filename);
+ return;
+ } //end if
+ fclose(fp);
+ //display creation time
+ Log_Print("written %d brushes\n", c_writtenbrushes);
+ Log_Print("map file written in %5.0f seconds\n", I_FloatTime() - start_time);
+} //end of the function WriteMapFile
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void PrintMapInfo(void)
+{
+ Log_Print("\n");
+ Log_Print("%6i brushes\n", nummapbrushes);
+ Log_Print("%6i brush sides\n", nummapbrushsides);
+// Log_Print("%6i clipbrushes\n", c_clipbrushes);
+// Log_Print("%6i total sides\n", nummapbrushsides);
+// Log_Print("%6i boxbevels\n", c_boxbevels);
+// Log_Print("%6i edgebevels\n", c_edgebevels);
+// Log_Print("%6i entities\n", num_entities);
+// Log_Print("%6i planes\n", nummapplanes);
+// Log_Print("%6i areaportals\n", c_areaportals);
+// Log_Print("%6i squatt brushes\n", c_squattbrushes);
+// Log_Print("size: %5.0f,%5.0f,%5.0f to %5.0f,%5.0f,%5.0f\n", map_mins[0],map_mins[1],map_mins[2],
+// map_maxs[0],map_maxs[1],map_maxs[2]);
+} //end of the function PrintMapInfo
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void ResetMapLoading(void)
+{
+ int i;
+ epair_t *ep, *nextep;
+
+ Q2_ResetMapLoading();
+ Sin_ResetMapLoading();
+
+ //free all map brush side windings
+ for (i = 0; i < nummapbrushsides; i++)
+ {
+ if (brushsides[i].winding)
+ {
+ FreeWinding(brushsides[i].winding);
+ } //end for
+ } //end for
+
+ //reset regular stuff
+ nummapbrushes = 0;
+ memset(mapbrushes, 0, MAX_MAPFILE_BRUSHES * sizeof(mapbrush_t));
+ //
+ nummapbrushsides = 0;
+ memset(brushsides, 0, MAX_MAPFILE_BRUSHSIDES * sizeof(side_t));
+ memset(side_brushtextures, 0, MAX_MAPFILE_BRUSHSIDES * sizeof(brush_texture_t));
+ //
+ nummapplanes = 0;
+ memset(mapplanes, 0, MAX_MAPFILE_PLANES * sizeof(plane_t));
+ //
+ memset(planehash, 0, PLANE_HASHES * sizeof(plane_t *));
+ //
+ memset(map_texinfo, 0, MAX_MAPFILE_TEXINFO * sizeof(map_texinfo_t));
+ map_numtexinfo = 0;
+ //
+ VectorClear(map_mins);
+ VectorClear(map_maxs);
+ //
+ c_boxbevels = 0;
+ c_edgebevels = 0;
+ c_areaportals = 0;
+ c_clipbrushes = 0;
+ c_writtenbrushes = 0;
+ //clear the entities
+ for (i = 0; i < num_entities; i++)
+ {
+ for (ep = entities[i].epairs; ep; ep = nextep)
+ {
+ nextep = ep->next;
+ FreeMemory(ep->key);
+ FreeMemory(ep->value);
+ FreeMemory(ep);
+ } //end for
+ } //end for
+ num_entities = 0;
+ memset(entities, 0, MAX_MAP_ENTITIES * sizeof(entity_t));
+} //end of the function ResetMapLoading
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+#ifndef Q1_BSPVERSION
+#define Q1_BSPVERSION 29
+#endif
+#ifndef HL_BSPVERSION
+#define HL_BSPVERSION 30
+#endif
+
+#define Q2_BSPHEADER (('P'<<24)+('S'<<16)+('B'<<8)+'I') //IBSP
+#define Q2_BSPVERSION 38
+
+#define SINGAME_BSPHEADER (('P'<<24)+('S'<<16)+('B'<<8)+'R') //RBSP
+#define SINGAME_BSPVERSION 1
+
+#define SIN_BSPHEADER (('P'<<24)+('S'<<16)+('B'<<8)+'I') //IBSP
+#define SIN_BSPVERSION 41
+
+typedef struct
+{
+ int ident;
+ int version;
+} idheader_t;
+
+int LoadMapFromBSP(struct quakefile_s *qf)
+{
+ idheader_t idheader;
+
+ if (ReadQuakeFile(qf, &idheader, 0, sizeof(idheader_t)) != sizeof(idheader_t))
+ {
+ return false;
+ } //end if
+
+ idheader.ident = LittleLong(idheader.ident);
+ idheader.version = LittleLong(idheader.version);
+ //Quake3 BSP file
+ if (idheader.ident == Q3_BSP_IDENT && idheader.version == Q3_BSP_VERSION)
+ {
+ ResetMapLoading();
+ Q3_LoadMapFromBSP(qf);
+ Q3_FreeMaxBSP();
+ } //end if
+ //Quake2 BSP file
+ else if (idheader.ident == Q2_BSPHEADER && idheader.version == Q2_BSPVERSION)
+ {
+ ResetMapLoading();
+ Q2_AllocMaxBSP();
+ Q2_LoadMapFromBSP(qf->filename, qf->offset, qf->length);
+ Q2_FreeMaxBSP();
+ } //endif
+ //Sin BSP file
+ else if ((idheader.ident == SIN_BSPHEADER && idheader.version == SIN_BSPVERSION) ||
+ //the dorks gave the same format another ident and verions
+ (idheader.ident == SINGAME_BSPHEADER && idheader.version == SINGAME_BSPVERSION))
+ {
+ ResetMapLoading();
+ Sin_AllocMaxBSP();
+ Sin_LoadMapFromBSP(qf->filename, qf->offset, qf->length);
+ Sin_FreeMaxBSP();
+ } //end if
+ //the Quake1 bsp files don't have a ident only a version
+ else if (idheader.ident == Q1_BSPVERSION)
+ {
+ ResetMapLoading();
+ Q1_AllocMaxBSP();
+ Q1_LoadMapFromBSP(qf->filename, qf->offset, qf->length);
+ Q1_FreeMaxBSP();
+ } //end if
+ //Half-Life also only uses a version number
+ else if (idheader.ident == HL_BSPVERSION)
+ {
+ ResetMapLoading();
+ HL_AllocMaxBSP();
+ HL_LoadMapFromBSP(qf->filename, qf->offset, qf->length);
+ HL_FreeMaxBSP();
+ } //end if
+ else
+ {
+ Error("unknown BSP format %c%c%c%c, version %d\n",
+ (idheader.ident & 0xFF),
+ ((idheader.ident >> 8) & 0xFF),
+ ((idheader.ident >> 16) & 0xFF),
+ ((idheader.ident >> 24) & 0xFF), idheader.version);
+ return false;
+ } //end if
+ //
+ return true;
+} //end of the function LoadMapFromBSP
diff --git a/code/bspc/map_hl.c b/code/bspc/map_hl.c
new file mode 100755
index 0000000..7e6037b
--- /dev/null
+++ b/code/bspc/map_hl.c
@@ -0,0 +1,1114 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+#include "l_bsp_hl.h"
+#include "aas_map.h" //AAS_CreateMapBrushes
+
+int hl_numbrushes;
+int hl_numclipbrushes;
+
+//#define HL_PRINT
+#define HLCONTENTS
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int HL_TextureContents(char *name)
+{
+ if (!Q_strncasecmp (name, "sky",3))
+ return CONTENTS_SOLID;
+
+ if (!Q_strncasecmp(name+1,"!lava",5))
+ return CONTENTS_LAVA;
+
+ if (!Q_strncasecmp(name+1,"!slime",6))
+ return CONTENTS_SLIME;
+
+ /*
+ if (!Q_strncasecmp (name, "!cur_90",7))
+ return CONTENTS_CURRENT_90;
+ if (!Q_strncasecmp (name, "!cur_0",6))
+ return CONTENTS_CURRENT_0;
+ if (!Q_strncasecmp (name, "!cur_270",8))
+ return CONTENTS_CURRENT_270;
+ if (!Q_strncasecmp (name, "!cur_180",8))
+ return CONTENTS_CURRENT_180;
+ if (!Q_strncasecmp (name, "!cur_up",7))
+ return CONTENTS_CURRENT_UP;
+ if (!Q_strncasecmp (name, "!cur_dwn",8))
+ return CONTENTS_CURRENT_DOWN;
+ //*/
+ if (name[0] == '!')
+ return CONTENTS_WATER;
+ /*
+ if (!Q_strncasecmp (name, "origin",6))
+ return CONTENTS_ORIGIN;
+ if (!Q_strncasecmp (name, "clip",4))
+ return CONTENTS_CLIP;
+ if( !Q_strncasecmp( name, "translucent", 11 ) )
+ return CONTENTS_TRANSLUCENT;
+ if( name[0] == '@' )
+ return CONTENTS_TRANSLUCENT;
+ //*/
+
+ return CONTENTS_SOLID;
+} //end of the function HL_TextureContents
+//===========================================================================
+// Generates two new brushes, leaving the original
+// unchanged
+//
+// modified for Half-Life because there are quite a lot of tiny node leaves
+// in the Half-Life bsps
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void HL_SplitBrush(bspbrush_t *brush, int planenum, int nodenum,
+ bspbrush_t **front, bspbrush_t **back)
+{
+ bspbrush_t *b[2];
+ int i, j;
+ winding_t *w, *cw[2], *midwinding;
+ plane_t *plane, *plane2;
+ side_t *s, *cs;
+ float d, d_front, d_back;
+
+ *front = *back = NULL;
+ plane = &mapplanes[planenum];
+
+ // check all points
+ d_front = d_back = 0;
+ for (i=0 ; i<brush->numsides ; i++)
+ {
+ w = brush->sides[i].winding;
+ if (!w)
+ continue;
+ for (j=0 ; j<w->numpoints ; j++)
+ {
+ d = DotProduct (w->p[j], plane->normal) - plane->dist;
+ if (d > 0 && d > d_front)
+ d_front = d;
+ if (d < 0 && d < d_back)
+ d_back = d;
+ } //end for
+ } //end for
+
+ if (d_front < 0.1) // PLANESIDE_EPSILON)
+ { // only on back
+ *back = CopyBrush (brush);
+ Log_Print("HL_SplitBrush: only on back\n");
+ return;
+ } //end if
+ if (d_back > -0.1) // PLANESIDE_EPSILON)
+ { // only on front
+ *front = CopyBrush (brush);
+ Log_Print("HL_SplitBrush: only on front\n");
+ return;
+ } //end if
+
+ // create a new winding from the split plane
+
+ w = BaseWindingForPlane (plane->normal, plane->dist);
+ for (i = 0; i < brush->numsides && w; i++)
+ {
+ plane2 = &mapplanes[brush->sides[i].planenum ^ 1];
+ ChopWindingInPlace(&w, plane2->normal, plane2->dist, 0); // PLANESIDE_EPSILON);
+ } //end for
+
+ if (!w || WindingIsTiny(w))
+ { // the brush isn't really split
+ int side;
+
+ Log_Print("HL_SplitBrush: no split winding\n");
+ side = BrushMostlyOnSide (brush, plane);
+ if (side == PSIDE_FRONT)
+ *front = CopyBrush (brush);
+ if (side == PSIDE_BACK)
+ *back = CopyBrush (brush);
+ return;
+ }
+
+ if (WindingIsHuge(w))
+ {
+ Log_Print("HL_SplitBrush: WARNING huge split winding\n");
+ } //end of
+
+ midwinding = w;
+
+ // split it for real
+
+ for (i = 0; i < 2; i++)
+ {
+ b[i] = AllocBrush (brush->numsides+1);
+ b[i]->original = brush->original;
+ } //end for
+
+ // split all the current windings
+
+ for (i=0 ; i<brush->numsides ; i++)
+ {
+ s = &brush->sides[i];
+ w = s->winding;
+ if (!w)
+ continue;
+ ClipWindingEpsilon (w, plane->normal, plane->dist,
+ 0 /*PLANESIDE_EPSILON*/, &cw[0], &cw[1]);
+ for (j=0 ; j<2 ; j++)
+ {
+ if (!cw[j])
+ continue;
+#if 0
+ if (WindingIsTiny (cw[j]))
+ {
+ FreeWinding (cw[j]);
+ continue;
+ }
+#endif
+ cs = &b[j]->sides[b[j]->numsides];
+ b[j]->numsides++;
+ *cs = *s;
+// cs->planenum = s->planenum;
+// cs->texinfo = s->texinfo;
+// cs->visible = s->visible;
+// cs->original = s->original;
+ cs->winding = cw[j];
+ cs->flags &= ~SFL_TESTED;
+ } //end for
+ } //end for
+
+
+ // see if we have valid polygons on both sides
+
+ for (i=0 ; i<2 ; i++)
+ {
+ BoundBrush (b[i]);
+ for (j=0 ; j<3 ; j++)
+ {
+ if (b[i]->mins[j] < -4096 || b[i]->maxs[j] > 4096)
+ {
+ Log_Print("HL_SplitBrush: bogus brush after clip\n");
+ break;
+ } //end if
+ } //end for
+
+ if (b[i]->numsides < 3 || j < 3)
+ {
+ FreeBrush (b[i]);
+ b[i] = NULL;
+ Log_Print("HL_SplitBrush: numsides < 3\n");
+ } //end if
+ } //end for
+
+ if ( !(b[0] && b[1]) )
+ {
+ if (!b[0] && !b[1])
+ Log_Print("HL_SplitBrush: split removed brush\n");
+ else
+ Log_Print("HL_SplitBrush: split not on both sides\n");
+ if (b[0])
+ {
+ FreeBrush (b[0]);
+ *front = CopyBrush (brush);
+ } //end if
+ if (b[1])
+ {
+ FreeBrush (b[1]);
+ *back = CopyBrush (brush);
+ } //end if
+ return;
+ } //end if
+
+ // add the midwinding to both sides
+ for (i = 0; i < 2; i++)
+ {
+ cs = &b[i]->sides[b[i]->numsides];
+ b[i]->numsides++;
+
+ cs->planenum = planenum^i^1;
+ cs->texinfo = 0;
+ //store the node number in the surf to find the texinfo later on
+ cs->surf = nodenum;
+ //
+ cs->flags &= ~SFL_VISIBLE;
+ cs->flags &= ~SFL_TESTED;
+ if (i==0)
+ cs->winding = CopyWinding (midwinding);
+ else
+ cs->winding = midwinding;
+ } //end for
+
+
+{
+ vec_t v1;
+ int i;
+
+ for (i=0 ; i<2 ; i++)
+ {
+ v1 = BrushVolume (b[i]);
+ if (v1 < 1)
+ {
+ FreeBrush (b[i]);
+ b[i] = NULL;
+ Log_Print("HL_SplitBrush: tiny volume after clip\n");
+ } //end if
+ } //end for
+} //*/
+
+ *front = b[0];
+ *back = b[1];
+} //end of the function HL_SplitBrush
+//===========================================================================
+// returns true if the tree starting at nodenum has only solid leaves
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int HL_SolidTree_r(int nodenum)
+{
+ if (nodenum < 0)
+ {
+ switch(hl_dleafs[(-nodenum) - 1].contents)
+ {
+ case HL_CONTENTS_EMPTY:
+ {
+ return false;
+ } //end case
+ case HL_CONTENTS_SOLID:
+#ifdef HLCONTENTS
+ case HL_CONTENTS_CLIP:
+#endif //HLCONTENTS
+ case HL_CONTENTS_SKY:
+#ifdef HLCONTENTS
+ case HL_CONTENTS_TRANSLUCENT:
+#endif //HLCONTENTS
+ {
+ return true;
+ } //end case
+ case HL_CONTENTS_WATER:
+ case HL_CONTENTS_SLIME:
+ case HL_CONTENTS_LAVA:
+#ifdef HLCONTENTS
+ //these contents should not be found in the BSP
+ case HL_CONTENTS_ORIGIN:
+ case HL_CONTENTS_CURRENT_0:
+ case HL_CONTENTS_CURRENT_90:
+ case HL_CONTENTS_CURRENT_180:
+ case HL_CONTENTS_CURRENT_270:
+ case HL_CONTENTS_CURRENT_UP:
+ case HL_CONTENTS_CURRENT_DOWN:
+#endif //HLCONTENTS
+ default:
+ {
+ return false;
+ } //end default
+ } //end switch
+ return false;
+ } //end if
+ if (!HL_SolidTree_r(hl_dnodes[nodenum].children[0])) return false;
+ if (!HL_SolidTree_r(hl_dnodes[nodenum].children[1])) return false;
+ return true;
+} //end of the function HL_SolidTree_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bspbrush_t *HL_CreateBrushes_r(bspbrush_t *brush, int nodenum)
+{
+ int planenum;
+ bspbrush_t *front, *back;
+ hl_dleaf_t *leaf;
+
+ //if it is a leaf
+ if (nodenum < 0)
+ {
+ leaf = &hl_dleafs[(-nodenum) - 1];
+ if (leaf->contents != HL_CONTENTS_EMPTY)
+ {
+#ifdef HL_PRINT
+ qprintf("\r%5i", ++hl_numbrushes);
+#endif //HL_PRINT
+ } //end if
+ switch(leaf->contents)
+ {
+ case HL_CONTENTS_EMPTY:
+ {
+ FreeBrush(brush);
+ return NULL;
+ } //end case
+ case HL_CONTENTS_SOLID:
+#ifdef HLCONTENTS
+ case HL_CONTENTS_CLIP:
+#endif //HLCONTENTS
+ case HL_CONTENTS_SKY:
+#ifdef HLCONTENTS
+ case HL_CONTENTS_TRANSLUCENT:
+#endif //HLCONTENTS
+ {
+ brush->side = CONTENTS_SOLID;
+ return brush;
+ } //end case
+ case HL_CONTENTS_WATER:
+ {
+ brush->side = CONTENTS_WATER;
+ return brush;
+ } //end case
+ case HL_CONTENTS_SLIME:
+ {
+ brush->side = CONTENTS_SLIME;
+ return brush;
+ } //end case
+ case HL_CONTENTS_LAVA:
+ {
+ brush->side = CONTENTS_LAVA;
+ return brush;
+ } //end case
+#ifdef HLCONTENTS
+ //these contents should not be found in the BSP
+ case HL_CONTENTS_ORIGIN:
+ case HL_CONTENTS_CURRENT_0:
+ case HL_CONTENTS_CURRENT_90:
+ case HL_CONTENTS_CURRENT_180:
+ case HL_CONTENTS_CURRENT_270:
+ case HL_CONTENTS_CURRENT_UP:
+ case HL_CONTENTS_CURRENT_DOWN:
+ {
+ Error("HL_CreateBrushes_r: found contents %d in Half-Life BSP", leaf->contents);
+ return NULL;
+ } //end case
+#endif //HLCONTENTS
+ default:
+ {
+ Error("HL_CreateBrushes_r: unknown contents %d in Half-Life BSP", leaf->contents);
+ return NULL;
+ } //end default
+ } //end switch
+ return NULL;
+ } //end if
+ //if the rest of the tree is solid
+ /*if (HL_SolidTree_r(nodenum))
+ {
+ brush->side = CONTENTS_SOLID;
+ return brush;
+ } //end if*/
+ //
+ planenum = hl_dnodes[nodenum].planenum;
+ planenum = FindFloatPlane(hl_dplanes[planenum].normal, hl_dplanes[planenum].dist);
+ //split the brush with the node plane
+ HL_SplitBrush(brush, planenum, nodenum, &front, &back);
+ //free the original brush
+ FreeBrush(brush);
+ //every node must split the brush in two
+ if (!front || !back)
+ {
+ Log_Print("HL_CreateBrushes_r: WARNING node not splitting brush\n");
+ //return NULL;
+ } //end if
+ //create brushes recursively
+ if (front) front = HL_CreateBrushes_r(front, hl_dnodes[nodenum].children[0]);
+ if (back) back = HL_CreateBrushes_r(back, hl_dnodes[nodenum].children[1]);
+ //link the brushes if possible and return them
+ if (front)
+ {
+ for (brush = front; brush->next; brush = brush->next);
+ brush->next = back;
+ return front;
+ } //end if
+ else
+ {
+ return back;
+ } //end else
+} //end of the function HL_CreateBrushes_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bspbrush_t *HL_CreateBrushesFromBSP(int modelnum)
+{
+ bspbrush_t *brushlist;
+ bspbrush_t *brush;
+ hl_dnode_t *headnode;
+ vec3_t mins, maxs;
+ int i;
+
+ //
+ headnode = &hl_dnodes[hl_dmodels[modelnum].headnode[0]];
+ //get the mins and maxs of the world
+ VectorCopy(headnode->mins, mins);
+ VectorCopy(headnode->maxs, maxs);
+ //enlarge these mins and maxs
+ for (i = 0; i < 3; i++)
+ {
+ mins[i] -= 8;
+ maxs[i] += 8;
+ } //end for
+ //NOTE: have to add the BSP tree mins and maxs to the MAP mins and maxs
+ AddPointToBounds(mins, map_mins, map_maxs);
+ AddPointToBounds(maxs, map_mins, map_maxs);
+ //
+ if (!modelnum)
+ {
+ Log_Print("brush size: %5.0f,%5.0f,%5.0f to %5.0f,%5.0f,%5.0f\n",
+ map_mins[0], map_mins[1], map_mins[2],
+ map_maxs[0], map_maxs[1], map_maxs[2]);
+ } //end if
+ //create one huge brush containing the whole world
+ brush = BrushFromBounds(mins, maxs);
+ VectorCopy(mins, brush->mins);
+ VectorCopy(maxs, brush->maxs);
+ //
+#ifdef HL_PRINT
+ qprintf("creating Half-Life brushes\n");
+ qprintf("%5d brushes", hl_numbrushes = 0);
+#endif //HL_PRINT
+ //create the brushes
+ brushlist = HL_CreateBrushes_r(brush, hl_dmodels[modelnum].headnode[0]);
+ //
+#ifdef HL_PRINT
+ qprintf("\n");
+#endif //HL_PRINT
+ //now we've got a list with brushes!
+ return brushlist;
+} //end of the function HL_CreateBrushesFromBSP
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bspbrush_t *HL_MergeBrushes(bspbrush_t *brushlist, int modelnum)
+{
+ int nummerges, merged;
+ bspbrush_t *b1, *b2, *tail, *newbrush, *newbrushlist;
+ bspbrush_t *lastb2;
+
+ if (!brushlist) return NULL;
+
+ if (!modelnum) qprintf("%5d brushes merged", nummerges = 0);
+ do
+ {
+ for (tail = brushlist; tail; tail = tail->next)
+ {
+ if (!tail->next) break;
+ } //end for
+ merged = 0;
+ newbrushlist = NULL;
+ for (b1 = brushlist; b1; b1 = brushlist)
+ {
+ lastb2 = b1;
+ for (b2 = b1->next; b2; b2 = b2->next)
+ {
+ //can't merge brushes with different contents
+ if (b1->side != b2->side) newbrush = NULL;
+ else newbrush = TryMergeBrushes(b1, b2);
+ //if a merged brush is created
+ if (newbrush)
+ {
+ //copy the brush contents
+ newbrush->side = b1->side;
+ //add the new brush to the end of the list
+ tail->next = newbrush;
+ //remove the second brush from the list
+ lastb2->next = b2->next;
+ //remove the first brush from the list
+ brushlist = brushlist->next;
+ //free the merged brushes
+ FreeBrush(b1);
+ FreeBrush(b2);
+ //get a new tail brush
+ for (tail = brushlist; tail; tail = tail->next)
+ {
+ if (!tail->next) break;
+ } //end for
+ merged++;
+ if (!modelnum) qprintf("\r%5d", nummerges++);
+ break;
+ } //end if
+ lastb2 = b2;
+ } //end for
+ //if b1 can't be merged with any of the other brushes
+ if (!b2)
+ {
+ brushlist = brushlist->next;
+ //keep b1
+ b1->next = newbrushlist;
+ newbrushlist = b1;
+ } //end else
+ } //end for
+ brushlist = newbrushlist;
+ } while(merged);
+ if (!modelnum) qprintf("\n");
+ return newbrushlist;
+} //end of the function HL_MergeBrushes
+//===========================================================================
+// returns the amount the face and the winding have overlap
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float HL_FaceOnWinding(hl_dface_t *face, winding_t *winding)
+{
+ int i, edgenum, side;
+ float dist, area;
+ hl_dplane_t plane;
+ vec_t *v1, *v2;
+ vec3_t normal, edgevec;
+ winding_t *w;
+
+ //
+ w = CopyWinding(winding);
+ memcpy(&plane, &hl_dplanes[face->planenum], sizeof(hl_dplane_t));
+ //check on which side of the plane the face is
+ if (face->side)
+ {
+ VectorNegate(plane.normal, plane.normal);
+ plane.dist = -plane.dist;
+ } //end if
+ for (i = 0; i < face->numedges && w; i++)
+ {
+ //get the first and second vertex of the edge
+ edgenum = hl_dsurfedges[face->firstedge + i];
+ side = edgenum > 0;
+ //if the face plane is flipped
+ v1 = hl_dvertexes[hl_dedges[abs(edgenum)].v[side]].point;
+ v2 = hl_dvertexes[hl_dedges[abs(edgenum)].v[!side]].point;
+ //create a plane through the edge vector, orthogonal to the face plane
+ //and with the normal vector pointing out of the face
+ VectorSubtract(v1, v2, edgevec);
+ CrossProduct(edgevec, plane.normal, normal);
+ VectorNormalize(normal);
+ dist = DotProduct(normal, v1);
+ //
+ ChopWindingInPlace(&w, normal, dist, 0.9); //CLIP_EPSILON
+ } //end for
+ if (w)
+ {
+ area = WindingArea(w);
+ FreeWinding(w);
+ return area;
+ } //end if
+ return 0;
+} //end of the function HL_FaceOnWinding
+//===========================================================================
+// returns a list with brushes created by splitting the given brush with
+// planes that go through the face edges and are orthogonal to the face plane
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bspbrush_t *HL_SplitBrushWithFace(bspbrush_t *brush, hl_dface_t *face)
+{
+ int i, edgenum, side, planenum, splits;
+ float dist;
+ hl_dplane_t plane;
+ vec_t *v1, *v2;
+ vec3_t normal, edgevec;
+ bspbrush_t *front, *back, *brushlist;
+
+ memcpy(&plane, &hl_dplanes[face->planenum], sizeof(hl_dplane_t));
+ //check on which side of the plane the face is
+ if (face->side)
+ {
+ VectorNegate(plane.normal, plane.normal);
+ plane.dist = -plane.dist;
+ } //end if
+ splits = 0;
+ brushlist = NULL;
+ for (i = 0; i < face->numedges; i++)
+ {
+ //get the first and second vertex of the edge
+ edgenum = hl_dsurfedges[face->firstedge + i];
+ side = edgenum > 0;
+ //if the face plane is flipped
+ v1 = hl_dvertexes[hl_dedges[abs(edgenum)].v[side]].point;
+ v2 = hl_dvertexes[hl_dedges[abs(edgenum)].v[!side]].point;
+ //create a plane through the edge vector, orthogonal to the face plane
+ //and with the normal vector pointing out of the face
+ VectorSubtract(v1, v2, edgevec);
+ CrossProduct(edgevec, plane.normal, normal);
+ VectorNormalize(normal);
+ dist = DotProduct(normal, v1);
+ //
+ planenum = FindFloatPlane(normal, dist);
+ //split the current brush
+ SplitBrush(brush, planenum, &front, &back);
+ //if there is a back brush just put it in the list
+ if (back)
+ {
+ //copy the brush contents
+ back->side = brush->side;
+ //
+ back->next = brushlist;
+ brushlist = back;
+ splits++;
+ } //end if
+ if (!front)
+ {
+ Log_Print("HL_SplitBrushWithFace: no new brush\n");
+ FreeBrushList(brushlist);
+ return NULL;
+ } //end if
+ //copy the brush contents
+ front->side = brush->side;
+ //continue splitting the front brush
+ brush = front;
+ } //end for
+ if (!splits)
+ {
+ FreeBrush(front);
+ return NULL;
+ } //end if
+ front->next = brushlist;
+ brushlist = front;
+ return brushlist;
+} //end of the function HL_SplitBrushWithFace
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bspbrush_t *HL_TextureBrushes(bspbrush_t *brushlist, int modelnum)
+{
+ float area, largestarea;
+ int i, n, texinfonum, sn, numbrushes, ofs;
+ int bestfacenum, sidenodenum;
+ side_t *side;
+ hl_dmiptexlump_t *miptexlump;
+ hl_miptex_t *miptex;
+ bspbrush_t *brush, *nextbrush, *prevbrush, *newbrushes, *brushlistend;
+ vec_t defaultvec[4] = {1, 0, 0, 0};
+
+ if (!modelnum) qprintf("texturing brushes\n");
+ if (!modelnum) qprintf("%5d brushes", numbrushes = 0);
+ //get a pointer to the last brush in the list
+ for (brushlistend = brushlist; brushlistend; brushlistend = brushlistend->next)
+ {
+ if (!brushlistend->next) break;
+ } //end for
+ //there's no previous brush when at the start of the list
+ prevbrush = NULL;
+ //go over the brush list
+ for (brush = brushlist; brush; brush = nextbrush)
+ {
+ nextbrush = brush->next;
+ //find a texinfo for every brush side
+ for (sn = 0; sn < brush->numsides; sn++)
+ {
+ side = &brush->sides[sn];
+ //
+ if (side->flags & SFL_TEXTURED) continue;
+ //number of the node that created this brush side
+ sidenodenum = side->surf; //see midwinding in HL_SplitBrush
+ //no face found yet
+ bestfacenum = -1;
+ //minimum face size
+ largestarea = 1;
+ //if optimizing the texture placement and not going for the
+ //least number of brushes
+ if (!lessbrushes)
+ {
+ for (i = 0; i < hl_numfaces; i++)
+ {
+ //the face must be in the same plane as the node plane that created
+ //this brush side
+ if (hl_dfaces[i].planenum == hl_dnodes[sidenodenum].planenum)
+ {
+ //get the area the face and the brush side overlap
+ area = HL_FaceOnWinding(&hl_dfaces[i], side->winding);
+ //if this face overlaps the brush side winding more than previous faces
+ if (area > largestarea)
+ {
+ //if there already was a face for texturing this brush side with
+ //a different texture
+ if (bestfacenum >= 0 &&
+ (hl_dfaces[bestfacenum].texinfo != hl_dfaces[i].texinfo))
+ {
+ //split the brush to fit the texture
+ newbrushes = HL_SplitBrushWithFace(brush, &hl_dfaces[i]);
+ //if new brushes where created
+ if (newbrushes)
+ {
+ //remove the current brush from the list
+ if (prevbrush) prevbrush->next = brush->next;
+ else brushlist = brush->next;
+ if (brushlistend == brush)
+ {
+ brushlistend = prevbrush;
+ nextbrush = newbrushes;
+ } //end if
+ //add the new brushes to the end of the list
+ if (brushlistend) brushlistend->next = newbrushes;
+ else brushlist = newbrushes;
+ //free the current brush
+ FreeBrush(brush);
+ //don't forget about the prevbrush pointer at the bottom of
+ //the outer loop
+ brush = prevbrush;
+ //find the end of the list
+ for (brushlistend = brushlist; brushlistend; brushlistend = brushlistend->next)
+ {
+ if (!brushlistend->next) break;
+ } //end for
+ break;
+ } //end if
+ else
+ {
+ Log_Write("brush %d: no real texture split", numbrushes);
+ } //end else
+ } //end if
+ else
+ {
+ //best face for texturing this brush side
+ bestfacenum = i;
+ } //end else
+ } //end if
+ } //end if
+ } //end for
+ //if the brush was split the original brush is removed
+ //and we just continue with the next one in the list
+ if (i < hl_numfaces) break;
+ } //end if
+ else
+ {
+ //find the face with the largest overlap with this brush side
+ //for texturing the brush side
+ for (i = 0; i < hl_numfaces; i++)
+ {
+ //the face must be in the same plane as the node plane that created
+ //this brush side
+ if (hl_dfaces[i].planenum == hl_dnodes[sidenodenum].planenum)
+ {
+ //get the area the face and the brush side overlap
+ area = HL_FaceOnWinding(&hl_dfaces[i], side->winding);
+ //if this face overlaps the brush side winding more than previous faces
+ if (area > largestarea)
+ {
+ largestarea = area;
+ bestfacenum = i;
+ } //end if
+ } //end if
+ } //end for
+ } //end else
+ //if a face was found for texturing this brush side
+ if (bestfacenum >= 0)
+ {
+ //set the MAP texinfo values
+ texinfonum = hl_dfaces[bestfacenum].texinfo;
+ for (n = 0; n < 4; n++)
+ {
+ map_texinfo[texinfonum].vecs[0][n] = hl_texinfo[texinfonum].vecs[0][n];
+ map_texinfo[texinfonum].vecs[1][n] = hl_texinfo[texinfonum].vecs[1][n];
+ } //end for
+ //make sure the two vectors aren't of zero length otherwise use the default
+ //vector to prevent a divide by zero in the map writing
+ if (VectorLength(map_texinfo[texinfonum].vecs[0]) < 0.01)
+ memcpy(map_texinfo[texinfonum].vecs[0], defaultvec, sizeof(defaultvec));
+ if (VectorLength(map_texinfo[texinfonum].vecs[1]) < 0.01)
+ memcpy(map_texinfo[texinfonum].vecs[1], defaultvec, sizeof(defaultvec));
+ //
+ map_texinfo[texinfonum].flags = hl_texinfo[texinfonum].flags;
+ map_texinfo[texinfonum].value = 0; //HL_ and HL texinfos don't have a value
+ //the mip texture
+ miptexlump = (hl_dmiptexlump_t *) hl_dtexdata;
+ ofs = miptexlump->dataofs[hl_texinfo[texinfonum].miptex];
+ if ( ofs > hl_texdatasize ) {
+ ofs = miptexlump->dataofs[0];
+ }
+ miptex = (hl_miptex_t *)((byte *)miptexlump + ofs );
+ //get the mip texture name
+ strcpy(map_texinfo[texinfonum].texture, miptex->name);
+ //no animations in Quake1 and Half-Life mip textures
+ map_texinfo[texinfonum].nexttexinfo = -1;
+ //store the texinfo number
+ side->texinfo = texinfonum;
+ //
+ if (texinfonum > map_numtexinfo) map_numtexinfo = texinfonum;
+ //this side is textured
+ side->flags |= SFL_TEXTURED;
+ } //end if
+ else
+ {
+ //no texture for this side
+ side->texinfo = TEXINFO_NODE;
+ //this side is textured
+ side->flags |= SFL_TEXTURED;
+ } //end if
+ } //end for
+ //
+ if (!modelnum && prevbrush != brush) qprintf("\r%5d", ++numbrushes);
+ //previous brush in the list
+ prevbrush = brush;
+ } //end for
+ if (!modelnum) qprintf("\n");
+ //return the new list with brushes
+ return brushlist;
+} //end of the function HL_TextureBrushes
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void HL_FixContentsTextures(bspbrush_t *brushlist)
+{
+ int i, texinfonum;
+ bspbrush_t *brush;
+
+ for (brush = brushlist; brush; brush = brush->next)
+ {
+ //only fix the textures of water, slime and lava brushes
+ if (brush->side != CONTENTS_WATER &&
+ brush->side != CONTENTS_SLIME &&
+ brush->side != CONTENTS_LAVA) continue;
+ //
+ for (i = 0; i < brush->numsides; i++)
+ {
+ texinfonum = brush->sides[i].texinfo;
+ if (HL_TextureContents(map_texinfo[texinfonum].texture) == brush->side) break;
+ } //end for
+ //if no specific contents texture was found
+ if (i >= brush->numsides)
+ {
+ texinfonum = -1;
+ for (i = 0; i < map_numtexinfo; i++)
+ {
+ if (HL_TextureContents(map_texinfo[i].texture) == brush->side)
+ {
+ texinfonum = i;
+ break;
+ } //end if
+ } //end for
+ } //end if
+ //
+ if (texinfonum >= 0)
+ {
+ //give all the brush sides this contents texture
+ for (i = 0; i < brush->numsides; i++)
+ {
+ brush->sides[i].texinfo = texinfonum;
+ } //end for
+ } //end if
+ else Log_Print("brush contents %d with wrong textures\n", brush->side);
+ //
+ } //end for
+ /*
+ for (brush = brushlist; brush; brush = brush->next)
+ {
+ //give all the brush sides this contents texture
+ for (i = 0; i < brush->numsides; i++)
+ {
+ if (HL_TextureContents(map_texinfo[texinfonum].texture) != brush->side)
+ {
+ Error("brush contents %d with wrong contents textures %s\n", brush->side,
+ HL_TextureContents(map_texinfo[texinfonum].texture));
+ } //end if
+ } //end for
+ } //end for*/
+} //end of the function HL_FixContentsTextures
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void HL_BSPBrushToMapBrush(bspbrush_t *bspbrush, entity_t *mapent)
+{
+ mapbrush_t *mapbrush;
+ side_t *side;
+ int i, besttexinfo;
+
+ if (nummapbrushes >= MAX_MAPFILE_BRUSHES)
+ Error ("nummapbrushes == MAX_MAPFILE_BRUSHES");
+
+ mapbrush = &mapbrushes[nummapbrushes];
+ mapbrush->original_sides = &brushsides[nummapbrushsides];
+ mapbrush->entitynum = mapent - entities;
+ mapbrush->brushnum = nummapbrushes - mapent->firstbrush;
+ mapbrush->leafnum = -1;
+ mapbrush->numsides = 0;
+
+ besttexinfo = TEXINFO_NODE;
+ for (i = 0; i < bspbrush->numsides; i++)
+ {
+ if (!bspbrush->sides[i].winding) continue;
+ //
+ if (nummapbrushsides >= MAX_MAPFILE_BRUSHSIDES)
+ Error ("MAX_MAPFILE_BRUSHSIDES");
+ side = &brushsides[nummapbrushsides];
+ //the contents of the bsp brush is stored in the side variable
+ side->contents = bspbrush->side;
+ side->surf = 0;
+ side->planenum = bspbrush->sides[i].planenum;
+ side->texinfo = bspbrush->sides[i].texinfo;
+ if (side->texinfo != TEXINFO_NODE)
+ {
+ //this brush side is textured
+ side->flags |= SFL_TEXTURED;
+ besttexinfo = side->texinfo;
+ } //end if
+ //
+ nummapbrushsides++;
+ mapbrush->numsides++;
+ } //end for
+ //
+ if (besttexinfo == TEXINFO_NODE)
+ {
+ mapbrush->numsides = 0;
+ hl_numclipbrushes++;
+ return;
+ } //end if
+ //set the texinfo for all the brush sides without texture
+ for (i = 0; i < mapbrush->numsides; i++)
+ {
+ if (mapbrush->original_sides[i].texinfo == TEXINFO_NODE)
+ {
+ mapbrush->original_sides[i].texinfo = besttexinfo;
+ } //end if
+ } //end for
+ //contents of the brush
+ mapbrush->contents = bspbrush->side;
+ //
+ if (create_aas)
+ {
+ //create the AAS brushes from this brush, add brush bevels
+ AAS_CreateMapBrushes(mapbrush, mapent, true);
+ return;
+ } //end if
+ //create windings for sides and bounds for brush
+ MakeBrushWindings(mapbrush);
+ //add brush bevels
+ AddBrushBevels(mapbrush);
+ //a new brush has been created
+ nummapbrushes++;
+ mapent->numbrushes++;
+} //end of the function HL_BSPBrushToMapBrush
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void HL_CreateMapBrushes(entity_t *mapent, int modelnum)
+{
+ bspbrush_t *brushlist, *brush, *nextbrush;
+ int i;
+
+ //create brushes from the model BSP tree
+ brushlist = HL_CreateBrushesFromBSP(modelnum);
+ //texture the brushes and split them when necesary
+ brushlist = HL_TextureBrushes(brushlist, modelnum);
+ //fix the contents textures of all brushes
+ HL_FixContentsTextures(brushlist);
+ //
+ if (!nobrushmerge)
+ {
+ brushlist = HL_MergeBrushes(brushlist, modelnum);
+ //brushlist = HL_MergeBrushes(brushlist, modelnum);
+ } //end if
+ //
+ if (!modelnum) qprintf("converting brushes to map brushes\n");
+ if (!modelnum) qprintf("%5d brushes", i = 0);
+ for (brush = brushlist; brush; brush = nextbrush)
+ {
+ nextbrush = brush->next;
+ HL_BSPBrushToMapBrush(brush, mapent);
+ brush->next = NULL;
+ FreeBrush(brush);
+ if (!modelnum) qprintf("\r%5d", ++i);
+ } //end for
+ if (!modelnum) qprintf("\n");
+} //end of the function HL_CreateMapBrushes
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void HL_ResetMapLoading(void)
+{
+} //end of the function HL_ResetMapLoading
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void HL_LoadMapFromBSP(char *filename, int offset, int length)
+{
+ int i, modelnum;
+ char *model, *classname;
+
+ Log_Print("-- HL_LoadMapFromBSP --\n");
+ //loaded map type
+ loadedmaptype = MAPTYPE_HALFLIFE;
+ //
+ qprintf("loading map from %s at %d\n", filename, offset);
+ //load the Half-Life BSP file
+ HL_LoadBSPFile(filename, offset, length);
+ //
+ hl_numclipbrushes = 0;
+ //parse the entities from the BSP
+ HL_ParseEntities();
+ //clear the map mins and maxs
+ ClearBounds(map_mins, map_maxs);
+ //
+ qprintf("creating Half-Life brushes\n");
+ if (lessbrushes) qprintf("creating minimum number of brushes\n");
+ else qprintf("placing textures correctly\n");
+ //
+ for (i = 0; i < num_entities; i++)
+ {
+ entities[i].firstbrush = nummapbrushes;
+ entities[i].numbrushes = 0;
+ //
+ classname = ValueForKey(&entities[i], "classname");
+ if (classname && !strcmp(classname, "worldspawn"))
+ {
+ modelnum = 0;
+ } //end if
+ else
+ {
+ //
+ model = ValueForKey(&entities[i], "model");
+ if (!model || *model != '*') continue;
+ model++;
+ modelnum = atoi(model);
+ } //end else
+ //create map brushes for the entity
+ HL_CreateMapBrushes(&entities[i], modelnum);
+ } //end for
+ //
+ qprintf("%5d map brushes\n", nummapbrushes);
+ qprintf("%5d clip brushes\n", hl_numclipbrushes);
+} //end of the function HL_LoadMapFromBSP
diff --git a/code/bspc/map_q1.c b/code/bspc/map_q1.c
new file mode 100755
index 0000000..772a358
--- /dev/null
+++ b/code/bspc/map_q1.c
@@ -0,0 +1,1174 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+#include "l_bsp_q1.h"
+#include "aas_map.h" //AAS_CreateMapBrushes
+
+int q1_numbrushes;
+int q1_numclipbrushes;
+
+//#define Q1_PRINT
+
+//===========================================================================
+// water, slime and lava brush textures names always start with a *
+// followed by the type: "slime", "lava" or otherwise water
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int Q1_TextureContents(char *name)
+{
+ if (!Q_strcasecmp(name, "clip")) return CONTENTS_SOLID;
+ if (name[0] == '*')
+ {
+ if (!Q_strncasecmp(name+1,"lava",4)) return CONTENTS_LAVA;
+ else if (!Q_strncasecmp(name+1,"slime",5)) return CONTENTS_SLIME;
+ else return CONTENTS_WATER;
+ } //end if
+ else if (!Q_strncasecmp(name, "sky", 3)) return CONTENTS_SOLID;
+ else return CONTENTS_SOLID;
+} //end of the function Q1_TextureContents
+//===========================================================================
+// Generates two new brushes, leaving the original
+// unchanged
+//
+// modified for Half-Life because there are quite a lot of tiny node leaves
+// in the Half-Life bsps
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Q1_SplitBrush(bspbrush_t *brush, int planenum, int nodenum,
+ bspbrush_t **front, bspbrush_t **back)
+{
+ bspbrush_t *b[2];
+ int i, j;
+ winding_t *w, *cw[2], *midwinding;
+ plane_t *plane, *plane2;
+ side_t *s, *cs;
+ float d, d_front, d_back;
+
+ *front = *back = NULL;
+ plane = &mapplanes[planenum];
+
+ // check all points
+ d_front = d_back = 0;
+ for (i=0 ; i<brush->numsides ; i++)
+ {
+ w = brush->sides[i].winding;
+ if (!w)
+ continue;
+ for (j=0 ; j<w->numpoints ; j++)
+ {
+ d = DotProduct (w->p[j], plane->normal) - plane->dist;
+ if (d > 0 && d > d_front)
+ d_front = d;
+ if (d < 0 && d < d_back)
+ d_back = d;
+ } //end for
+ } //end for
+
+ if (d_front < 0.1) // PLANESIDE_EPSILON)
+ { // only on back
+ *back = CopyBrush (brush);
+ Log_Print("Q1_SplitBrush: only on back\n");
+ return;
+ } //end if
+ if (d_back > -0.1) // PLANESIDE_EPSILON)
+ { // only on front
+ *front = CopyBrush (brush);
+ Log_Print("Q1_SplitBrush: only on front\n");
+ return;
+ } //end if
+
+ // create a new winding from the split plane
+
+ w = BaseWindingForPlane (plane->normal, plane->dist);
+ for (i = 0; i < brush->numsides && w; i++)
+ {
+ plane2 = &mapplanes[brush->sides[i].planenum ^ 1];
+ ChopWindingInPlace(&w, plane2->normal, plane2->dist, 0); // PLANESIDE_EPSILON);
+ } //end for
+
+ if (!w || WindingIsTiny(w))
+ { // the brush isn't really split
+ int side;
+
+ Log_Print("Q1_SplitBrush: no split winding\n");
+ side = BrushMostlyOnSide (brush, plane);
+ if (side == PSIDE_FRONT)
+ *front = CopyBrush (brush);
+ if (side == PSIDE_BACK)
+ *back = CopyBrush (brush);
+ return;
+ }
+
+ if (WindingIsHuge(w))
+ {
+ Log_Print("Q1_SplitBrush: WARNING huge split winding\n");
+ } //end of
+
+ midwinding = w;
+
+ // split it for real
+
+ for (i = 0; i < 2; i++)
+ {
+ b[i] = AllocBrush (brush->numsides+1);
+ b[i]->original = brush->original;
+ } //end for
+
+ // split all the current windings
+
+ for (i=0 ; i<brush->numsides ; i++)
+ {
+ s = &brush->sides[i];
+ w = s->winding;
+ if (!w)
+ continue;
+ ClipWindingEpsilon (w, plane->normal, plane->dist,
+ 0 /*PLANESIDE_EPSILON*/, &cw[0], &cw[1]);
+ for (j=0 ; j<2 ; j++)
+ {
+ if (!cw[j])
+ continue;
+#if 0
+ if (WindingIsTiny (cw[j]))
+ {
+ FreeWinding (cw[j]);
+ continue;
+ }
+#endif
+ cs = &b[j]->sides[b[j]->numsides];
+ b[j]->numsides++;
+ *cs = *s;
+// cs->planenum = s->planenum;
+// cs->texinfo = s->texinfo;
+// cs->visible = s->visible;
+// cs->original = s->original;
+ cs->winding = cw[j];
+ cs->flags &= ~SFL_TESTED;
+ } //end for
+ } //end for
+
+
+ // see if we have valid polygons on both sides
+
+ for (i=0 ; i<2 ; i++)
+ {
+ BoundBrush (b[i]);
+ for (j=0 ; j<3 ; j++)
+ {
+ if (b[i]->mins[j] < -4096 || b[i]->maxs[j] > 4096)
+ {
+ Log_Print("Q1_SplitBrush: bogus brush after clip\n");
+ break;
+ } //end if
+ } //end for
+
+ if (b[i]->numsides < 3 || j < 3)
+ {
+ FreeBrush (b[i]);
+ b[i] = NULL;
+ Log_Print("Q1_SplitBrush: numsides < 3\n");
+ } //end if
+ } //end for
+
+ if ( !(b[0] && b[1]) )
+ {
+ if (!b[0] && !b[1])
+ Log_Print("Q1_SplitBrush: split removed brush\n");
+ else
+ Log_Print("Q1_SplitBrush: split not on both sides\n");
+ if (b[0])
+ {
+ FreeBrush (b[0]);
+ *front = CopyBrush (brush);
+ } //end if
+ if (b[1])
+ {
+ FreeBrush (b[1]);
+ *back = CopyBrush (brush);
+ } //end if
+ return;
+ } //end if
+
+ // add the midwinding to both sides
+ for (i = 0; i < 2; i++)
+ {
+ cs = &b[i]->sides[b[i]->numsides];
+ b[i]->numsides++;
+
+ cs->planenum = planenum^i^1;
+ cs->texinfo = 0;
+ //store the node number in the surf to find the texinfo later on
+ cs->surf = nodenum;
+ //
+ cs->flags &= ~SFL_VISIBLE;
+ cs->flags &= ~SFL_TESTED;
+ cs->flags &= ~SFL_TEXTURED;
+ if (i==0)
+ cs->winding = CopyWinding (midwinding);
+ else
+ cs->winding = midwinding;
+ } //end for
+
+
+{
+ vec_t v1;
+ int i;
+
+ for (i=0 ; i<2 ; i++)
+ {
+ v1 = BrushVolume (b[i]);
+ if (v1 < 1)
+ {
+ FreeBrush (b[i]);
+ b[i] = NULL;
+ Log_Print("Q1_SplitBrush: tiny volume after clip\n");
+ } //end if
+ } //end for
+} //*/
+
+ *front = b[0];
+ *back = b[1];
+} //end of the function Q1_SplitBrush
+//===========================================================================
+// returns true if the tree starting at nodenum has only solid leaves
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int Q1_SolidTree_r(int nodenum)
+{
+ if (nodenum < 0)
+ {
+ switch(q1_dleafs[(-nodenum) - 1].contents)
+ {
+ case Q1_CONTENTS_EMPTY:
+ {
+ return false;
+ } //end case
+ case Q1_CONTENTS_SOLID:
+#ifdef HLCONTENTS
+ case Q1_CONTENTS_CLIP:
+#endif HLCONTENTS
+ case Q1_CONTENTS_SKY:
+#ifdef HLCONTENTS
+ case Q1_CONTENTS_TRANSLUCENT:
+#endif HLCONTENTS
+ {
+ return true;
+ } //end case
+ case Q1_CONTENTS_WATER:
+ case Q1_CONTENTS_SLIME:
+ case Q1_CONTENTS_LAVA:
+#ifdef HLCONTENTS
+ //these contents should not be found in the BSP
+ case Q1_CONTENTS_ORIGIN:
+ case Q1_CONTENTS_CURRENT_0:
+ case Q1_CONTENTS_CURRENT_90:
+ case Q1_CONTENTS_CURRENT_180:
+ case Q1_CONTENTS_CURRENT_270:
+ case Q1_CONTENTS_CURRENT_UP:
+ case Q1_CONTENTS_CURRENT_DOWN:
+#endif HLCONTENTS
+ default:
+ {
+ return false;
+ } //end default
+ } //end switch
+ return false;
+ } //end if
+ if (!Q1_SolidTree_r(q1_dnodes[nodenum].children[0])) return false;
+ if (!Q1_SolidTree_r(q1_dnodes[nodenum].children[1])) return false;
+ return true;
+} //end of the function Q1_SolidTree_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bspbrush_t *Q1_CreateBrushes_r(bspbrush_t *brush, int nodenum)
+{
+ int planenum;
+ bspbrush_t *front, *back;
+ q1_dleaf_t *leaf;
+
+ //if it is a leaf
+ if (nodenum < 0)
+ {
+ leaf = &q1_dleafs[(-nodenum) - 1];
+ if (leaf->contents != Q1_CONTENTS_EMPTY)
+ {
+#ifdef Q1_PRINT
+ qprintf("\r%5i", ++q1_numbrushes);
+#endif //Q1_PRINT
+ } //end if
+ switch(leaf->contents)
+ {
+ case Q1_CONTENTS_EMPTY:
+ {
+ FreeBrush(brush);
+ return NULL;
+ } //end case
+ case Q1_CONTENTS_SOLID:
+#ifdef HLCONTENTS
+ case Q1_CONTENTS_CLIP:
+#endif HLCONTENTS
+ case Q1_CONTENTS_SKY:
+#ifdef HLCONTENTS
+ case Q1_CONTENTS_TRANSLUCENT:
+#endif HLCONTENTS
+ {
+ brush->side = CONTENTS_SOLID;
+ return brush;
+ } //end case
+ case Q1_CONTENTS_WATER:
+ {
+ brush->side = CONTENTS_WATER;
+ return brush;
+ } //end case
+ case Q1_CONTENTS_SLIME:
+ {
+ brush->side = CONTENTS_SLIME;
+ return brush;
+ } //end case
+ case Q1_CONTENTS_LAVA:
+ {
+ brush->side = CONTENTS_LAVA;
+ return brush;
+ } //end case
+#ifdef HLCONTENTS
+ //these contents should not be found in the BSP
+ case Q1_CONTENTS_ORIGIN:
+ case Q1_CONTENTS_CURRENT_0:
+ case Q1_CONTENTS_CURRENT_90:
+ case Q1_CONTENTS_CURRENT_180:
+ case Q1_CONTENTS_CURRENT_270:
+ case Q1_CONTENTS_CURRENT_UP:
+ case Q1_CONTENTS_CURRENT_DOWN:
+ {
+ Error("Q1_CreateBrushes_r: found contents %d in Half-Life BSP", leaf->contents);
+ return NULL;
+ } //end case
+#endif HLCONTENTS
+ default:
+ {
+ Error("Q1_CreateBrushes_r: unknown contents %d in Half-Life BSP", leaf->contents);
+ return NULL;
+ } //end default
+ } //end switch
+ return NULL;
+ } //end if
+ //if the rest of the tree is solid
+ /*if (Q1_SolidTree_r(nodenum))
+ {
+ brush->side = CONTENTS_SOLID;
+ return brush;
+ } //end if*/
+ //
+ planenum = q1_dnodes[nodenum].planenum;
+ planenum = FindFloatPlane(q1_dplanes[planenum].normal, q1_dplanes[planenum].dist);
+ //split the brush with the node plane
+ Q1_SplitBrush(brush, planenum, nodenum, &front, &back);
+ //free the original brush
+ FreeBrush(brush);
+ //every node must split the brush in two
+ if (!front || !back)
+ {
+ Log_Print("Q1_CreateBrushes_r: WARNING node not splitting brush\n");
+ //return NULL;
+ } //end if
+ //create brushes recursively
+ if (front) front = Q1_CreateBrushes_r(front, q1_dnodes[nodenum].children[0]);
+ if (back) back = Q1_CreateBrushes_r(back, q1_dnodes[nodenum].children[1]);
+ //link the brushes if possible and return them
+ if (front)
+ {
+ for (brush = front; brush->next; brush = brush->next);
+ brush->next = back;
+ return front;
+ } //end if
+ else
+ {
+ return back;
+ } //end else
+} //end of the function Q1_CreateBrushes_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bspbrush_t *Q1_CreateBrushesFromBSP(int modelnum)
+{
+ bspbrush_t *brushlist;
+ bspbrush_t *brush;
+ q1_dnode_t *headnode;
+ vec3_t mins, maxs;
+ int i;
+
+ //
+ headnode = &q1_dnodes[q1_dmodels[modelnum].headnode[0]];
+ //get the mins and maxs of the world
+ VectorCopy(headnode->mins, mins);
+ VectorCopy(headnode->maxs, maxs);
+ //enlarge these mins and maxs
+ for (i = 0; i < 3; i++)
+ {
+ mins[i] -= 8;
+ maxs[i] += 8;
+ } //end for
+ //NOTE: have to add the BSP tree mins and maxs to the MAP mins and maxs
+ AddPointToBounds(mins, map_mins, map_maxs);
+ AddPointToBounds(maxs, map_mins, map_maxs);
+ //
+ if (!modelnum)
+ {
+ Log_Print("brush size: %5.0f,%5.0f,%5.0f to %5.0f,%5.0f,%5.0f\n",
+ map_mins[0], map_mins[1], map_mins[2],
+ map_maxs[0], map_maxs[1], map_maxs[2]);
+ } //end if
+ //create one huge brush containing the whole world
+ brush = BrushFromBounds(mins, maxs);
+ VectorCopy(mins, brush->mins);
+ VectorCopy(maxs, brush->maxs);
+ //
+#ifdef Q1_PRINT
+ qprintf("creating Quake brushes\n");
+ qprintf("%5d brushes", q1_numbrushes = 0);
+#endif //Q1_PRINT
+ //create the brushes
+ brushlist = Q1_CreateBrushes_r(brush, q1_dmodels[modelnum].headnode[0]);
+ //
+#ifdef Q1_PRINT
+ qprintf("\n");
+#endif //Q1_PRINT
+ //now we've got a list with brushes!
+ return brushlist;
+} //end of the function Q1_CreateBrushesFromBSP
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+q1_dleaf_t *Q1_PointInLeaf(int startnode, vec3_t point)
+{
+ int nodenum;
+ vec_t dist;
+ q1_dnode_t *node;
+ q1_dplane_t *plane;
+
+ nodenum = startnode;
+ while (nodenum >= 0)
+ {
+ node = &q1_dnodes[nodenum];
+ plane = &q1_dplanes[node->planenum];
+ dist = DotProduct(point, plane->normal) - plane->dist;
+ if (dist > 0)
+ nodenum = node->children[0];
+ else
+ nodenum = node->children[1];
+ } //end while
+
+ return &q1_dleafs[-nodenum - 1];
+} //end of the function Q1_PointInLeaf
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float Q1_FaceArea(q1_dface_t *face)
+{
+ int i;
+ float total;
+ vec_t *v;
+ vec3_t d1, d2, cross;
+ q1_dedge_t *edge;
+
+ edge = &q1_dedges[face->firstedge];
+ v = q1_dvertexes[edge->v[0]].point;
+
+ total = 0;
+ for (i = 1; i < face->numedges - 1; i++)
+ {
+ edge = &q1_dedges[face->firstedge + i];
+ VectorSubtract(q1_dvertexes[edge->v[0]].point, v, d1);
+ VectorSubtract(q1_dvertexes[edge->v[1]].point, v, d2);
+ CrossProduct(d1, d2, cross);
+ total += 0.5 * VectorLength(cross);
+ } //end for
+ return total;
+} //end of the function AAS_FaceArea
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Q1_FacePlane(q1_dface_t *face, vec3_t normal, float *dist)
+{
+ vec_t *v1, *v2, *v3;
+ vec3_t vec1, vec2;
+ int side, edgenum;
+
+ edgenum = q1_dsurfedges[face->firstedge];
+ side = edgenum < 0;
+ v1 = q1_dvertexes[q1_dedges[abs(edgenum)].v[side]].point;
+ v2 = q1_dvertexes[q1_dedges[abs(edgenum)].v[!side]].point;
+ edgenum = q1_dsurfedges[face->firstedge+1];
+ side = edgenum < 0;
+ v3 = q1_dvertexes[q1_dedges[abs(edgenum)].v[!side]].point;
+ //
+ VectorSubtract(v2, v1, vec1);
+ VectorSubtract(v3, v1, vec2);
+
+ CrossProduct(vec1, vec2, normal);
+ VectorNormalize(normal);
+ *dist = DotProduct(v1, normal);
+} //end of the function Q1_FacePlane
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bspbrush_t *Q1_MergeBrushes(bspbrush_t *brushlist, int modelnum)
+{
+ int nummerges, merged;
+ bspbrush_t *b1, *b2, *tail, *newbrush, *newbrushlist;
+ bspbrush_t *lastb2;
+
+ if (!brushlist) return NULL;
+
+ if (!modelnum) qprintf("%5d brushes merged", nummerges = 0);
+ do
+ {
+ for (tail = brushlist; tail; tail = tail->next)
+ {
+ if (!tail->next) break;
+ } //end for
+ merged = 0;
+ newbrushlist = NULL;
+ for (b1 = brushlist; b1; b1 = brushlist)
+ {
+ lastb2 = b1;
+ for (b2 = b1->next; b2; b2 = b2->next)
+ {
+ //can't merge brushes with different contents
+ if (b1->side != b2->side) newbrush = NULL;
+ else newbrush = TryMergeBrushes(b1, b2);
+ //if a merged brush is created
+ if (newbrush)
+ {
+ //copy the brush contents
+ newbrush->side = b1->side;
+ //add the new brush to the end of the list
+ tail->next = newbrush;
+ //remove the second brush from the list
+ lastb2->next = b2->next;
+ //remove the first brush from the list
+ brushlist = brushlist->next;
+ //free the merged brushes
+ FreeBrush(b1);
+ FreeBrush(b2);
+ //get a new tail brush
+ for (tail = brushlist; tail; tail = tail->next)
+ {
+ if (!tail->next) break;
+ } //end for
+ merged++;
+ if (!modelnum) qprintf("\r%5d", nummerges++);
+ break;
+ } //end if
+ lastb2 = b2;
+ } //end for
+ //if b1 can't be merged with any of the other brushes
+ if (!b2)
+ {
+ brushlist = brushlist->next;
+ //keep b1
+ b1->next = newbrushlist;
+ newbrushlist = b1;
+ } //end else
+ } //end for
+ brushlist = newbrushlist;
+ } while(merged);
+ if (!modelnum) qprintf("\n");
+ return newbrushlist;
+} //end of the function Q1_MergeBrushes
+//===========================================================================
+// returns the amount the face and the winding overlap
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float Q1_FaceOnWinding(q1_dface_t *face, winding_t *winding)
+{
+ int i, edgenum, side;
+ float dist, area;
+ q1_dplane_t plane;
+ vec_t *v1, *v2;
+ vec3_t normal, edgevec;
+ winding_t *w;
+
+ //
+ w = CopyWinding(winding);
+ memcpy(&plane, &q1_dplanes[face->planenum], sizeof(q1_dplane_t));
+ //check on which side of the plane the face is
+ if (face->side)
+ {
+ VectorNegate(plane.normal, plane.normal);
+ plane.dist = -plane.dist;
+ } //end if
+ for (i = 0; i < face->numedges && w; i++)
+ {
+ //get the first and second vertex of the edge
+ edgenum = q1_dsurfedges[face->firstedge + i];
+ side = edgenum > 0;
+ //if the face plane is flipped
+ v1 = q1_dvertexes[q1_dedges[abs(edgenum)].v[side]].point;
+ v2 = q1_dvertexes[q1_dedges[abs(edgenum)].v[!side]].point;
+ //create a plane through the edge vector, orthogonal to the face plane
+ //and with the normal vector pointing out of the face
+ VectorSubtract(v1, v2, edgevec);
+ CrossProduct(edgevec, plane.normal, normal);
+ VectorNormalize(normal);
+ dist = DotProduct(normal, v1);
+ //
+ ChopWindingInPlace(&w, normal, dist, 0.9); //CLIP_EPSILON
+ } //end for
+ if (w)
+ {
+ area = WindingArea(w);
+ FreeWinding(w);
+ return area;
+ } //end if
+ return 0;
+} //end of the function Q1_FaceOnWinding
+//===========================================================================
+// returns a list with brushes created by splitting the given brush with
+// planes that go through the face edges and are orthogonal to the face plane
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bspbrush_t *Q1_SplitBrushWithFace(bspbrush_t *brush, q1_dface_t *face)
+{
+ int i, edgenum, side, planenum, splits;
+ float dist;
+ q1_dplane_t plane;
+ vec_t *v1, *v2;
+ vec3_t normal, edgevec;
+ bspbrush_t *front, *back, *brushlist;
+
+ memcpy(&plane, &q1_dplanes[face->planenum], sizeof(q1_dplane_t));
+ //check on which side of the plane the face is
+ if (face->side)
+ {
+ VectorNegate(plane.normal, plane.normal);
+ plane.dist = -plane.dist;
+ } //end if
+ splits = 0;
+ brushlist = NULL;
+ for (i = 0; i < face->numedges; i++)
+ {
+ //get the first and second vertex of the edge
+ edgenum = q1_dsurfedges[face->firstedge + i];
+ side = edgenum > 0;
+ //if the face plane is flipped
+ v1 = q1_dvertexes[q1_dedges[abs(edgenum)].v[side]].point;
+ v2 = q1_dvertexes[q1_dedges[abs(edgenum)].v[!side]].point;
+ //create a plane through the edge vector, orthogonal to the face plane
+ //and with the normal vector pointing out of the face
+ VectorSubtract(v1, v2, edgevec);
+ CrossProduct(edgevec, plane.normal, normal);
+ VectorNormalize(normal);
+ dist = DotProduct(normal, v1);
+ //
+ planenum = FindFloatPlane(normal, dist);
+ //split the current brush
+ SplitBrush(brush, planenum, &front, &back);
+ //if there is a back brush just put it in the list
+ if (back)
+ {
+ //copy the brush contents
+ back->side = brush->side;
+ //
+ back->next = brushlist;
+ brushlist = back;
+ splits++;
+ } //end if
+ if (!front)
+ {
+ Log_Print("Q1_SplitBrushWithFace: no new brush\n");
+ FreeBrushList(brushlist);
+ return NULL;
+ } //end if
+ //copy the brush contents
+ front->side = brush->side;
+ //continue splitting the front brush
+ brush = front;
+ } //end for
+ if (!splits)
+ {
+ FreeBrush(front);
+ return NULL;
+ } //end if
+ front->next = brushlist;
+ brushlist = front;
+ return brushlist;
+} //end of the function Q1_SplitBrushWithFace
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+bspbrush_t *Q1_TextureBrushes(bspbrush_t *brushlist, int modelnum)
+{
+ float area, largestarea;
+ int i, n, texinfonum, sn, numbrushes, ofs;
+ int bestfacenum, sidenodenum;
+ side_t *side;
+ q1_dmiptexlump_t *miptexlump;
+ q1_miptex_t *miptex;
+ bspbrush_t *brush, *nextbrush, *prevbrush, *newbrushes, *brushlistend;
+ vec_t defaultvec[4] = {1, 0, 0, 0};
+
+ if (!modelnum) qprintf("texturing brushes\n");
+ if (!modelnum) qprintf("%5d brushes", numbrushes = 0);
+ //get a pointer to the last brush in the list
+ for (brushlistend = brushlist; brushlistend; brushlistend = brushlistend->next)
+ {
+ if (!brushlistend->next) break;
+ } //end for
+ //there's no previous brush when at the start of the list
+ prevbrush = NULL;
+ //go over the brush list
+ for (brush = brushlist; brush; brush = nextbrush)
+ {
+ nextbrush = brush->next;
+ //find a texinfo for every brush side
+ for (sn = 0; sn < brush->numsides; sn++)
+ {
+ side = &brush->sides[sn];
+ //
+ if (side->flags & SFL_TEXTURED) continue;
+ //number of the node that created this brush side
+ sidenodenum = side->surf; //see midwinding in Q1_SplitBrush
+ //no face found yet
+ bestfacenum = -1;
+ //minimum face size
+ largestarea = 1;
+ //if optimizing the texture placement and not going for the
+ //least number of brushes
+ if (!lessbrushes)
+ {
+ for (i = 0; i < q1_numfaces; i++)
+ {
+ //the face must be in the same plane as the node plane that created
+ //this brush side
+ if (q1_dfaces[i].planenum == q1_dnodes[sidenodenum].planenum)
+ {
+ //get the area the face and the brush side overlap
+ area = Q1_FaceOnWinding(&q1_dfaces[i], side->winding);
+ //if this face overlaps the brush side winding more than previous faces
+ if (area > largestarea)
+ {
+ //if there already was a face for texturing this brush side with
+ //a different texture
+ if (bestfacenum >= 0 &&
+ (q1_dfaces[bestfacenum].texinfo != q1_dfaces[i].texinfo))
+ {
+ //split the brush to fit the texture
+ newbrushes = Q1_SplitBrushWithFace(brush, &q1_dfaces[i]);
+ //if new brushes where created
+ if (newbrushes)
+ {
+ //remove the current brush from the list
+ if (prevbrush) prevbrush->next = brush->next;
+ else brushlist = brush->next;
+ if (brushlistend == brush)
+ {
+ brushlistend = prevbrush;
+ nextbrush = newbrushes;
+ } //end if
+ //add the new brushes to the end of the list
+ if (brushlistend) brushlistend->next = newbrushes;
+ else brushlist = newbrushes;
+ //free the current brush
+ FreeBrush(brush);
+ //don't forget about the prevbrush pointer at the bottom of
+ //the outer loop
+ brush = prevbrush;
+ //find the end of the list
+ for (brushlistend = brushlist; brushlistend; brushlistend = brushlistend->next)
+ {
+ if (!brushlistend->next) break;
+ } //end for
+ break;
+ } //end if
+ else
+ {
+ Log_Write("brush %d: no real texture split", numbrushes);
+ } //end else
+ } //end if
+ else
+ {
+ //best face for texturing this brush side
+ bestfacenum = i;
+ } //end else
+ } //end if
+ } //end if
+ } //end for
+ //if the brush was split the original brush is removed
+ //and we just continue with the next one in the list
+ if (i < q1_numfaces) break;
+ } //end if
+ else
+ {
+ //find the face with the largest overlap with this brush side
+ //for texturing the brush side
+ for (i = 0; i < q1_numfaces; i++)
+ {
+ //the face must be in the same plane as the node plane that created
+ //this brush side
+ if (q1_dfaces[i].planenum == q1_dnodes[sidenodenum].planenum)
+ {
+ //get the area the face and the brush side overlap
+ area = Q1_FaceOnWinding(&q1_dfaces[i], side->winding);
+ //if this face overlaps the brush side winding more than previous faces
+ if (area > largestarea)
+ {
+ largestarea = area;
+ bestfacenum = i;
+ } //end if
+ } //end if
+ } //end for
+ } //end else
+ //if a face was found for texturing this brush side
+ if (bestfacenum >= 0)
+ {
+ //set the MAP texinfo values
+ texinfonum = q1_dfaces[bestfacenum].texinfo;
+ for (n = 0; n < 4; n++)
+ {
+ map_texinfo[texinfonum].vecs[0][n] = q1_texinfo[texinfonum].vecs[0][n];
+ map_texinfo[texinfonum].vecs[1][n] = q1_texinfo[texinfonum].vecs[1][n];
+ } //end for
+ //make sure the two vectors aren't of zero length otherwise use the default
+ //vector to prevent a divide by zero in the map writing
+ if (VectorLength(map_texinfo[texinfonum].vecs[0]) < 0.01)
+ memcpy(map_texinfo[texinfonum].vecs[0], defaultvec, sizeof(defaultvec));
+ if (VectorLength(map_texinfo[texinfonum].vecs[1]) < 0.01)
+ memcpy(map_texinfo[texinfonum].vecs[1], defaultvec, sizeof(defaultvec));
+ //
+ map_texinfo[texinfonum].flags = q1_texinfo[texinfonum].flags;
+ map_texinfo[texinfonum].value = 0; //Q1 and HL texinfos don't have a value
+ //the mip texture
+ miptexlump = (q1_dmiptexlump_t *) q1_dtexdata;
+ ofs = miptexlump->dataofs[q1_texinfo[texinfonum].miptex];
+ if ( ofs > q1_texdatasize ) {
+ ofs = miptexlump->dataofs[0];
+ }
+ miptex = (q1_miptex_t *)((byte *)miptexlump + ofs);
+ //get the mip texture name
+ strcpy(map_texinfo[texinfonum].texture, miptex->name);
+ //no animations in Quake1 and Half-Life mip textures
+ map_texinfo[texinfonum].nexttexinfo = -1;
+ //store the texinfo number
+ side->texinfo = texinfonum;
+ //
+ if (texinfonum > map_numtexinfo) map_numtexinfo = texinfonum;
+ //this side is textured
+ side->flags |= SFL_TEXTURED;
+ } //end if
+ else
+ {
+ //no texture for this side
+ side->texinfo = TEXINFO_NODE;
+ //this side is textured
+ side->flags |= SFL_TEXTURED;
+ } //end if
+ } //end for
+ //
+ if (!modelnum && prevbrush != brush) qprintf("\r%5d", ++numbrushes);
+ //previous brush in the list
+ prevbrush = brush;
+ } //end for
+ if (!modelnum) qprintf("\n");
+ //return the new list with brushes
+ return brushlist;
+} //end of the function Q1_TextureBrushes
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Q1_FixContentsTextures(bspbrush_t *brushlist)
+{
+ int i, texinfonum;
+ bspbrush_t *brush;
+
+ for (brush = brushlist; brush; brush = brush->next)
+ {
+ //only fix the textures of water, slime and lava brushes
+ if (brush->side != CONTENTS_WATER &&
+ brush->side != CONTENTS_SLIME &&
+ brush->side != CONTENTS_LAVA) continue;
+ //
+ for (i = 0; i < brush->numsides; i++)
+ {
+ texinfonum = brush->sides[i].texinfo;
+ if (Q1_TextureContents(map_texinfo[texinfonum].texture) == brush->side) break;
+ } //end for
+ //if no specific contents texture was found
+ if (i >= brush->numsides)
+ {
+ texinfonum = -1;
+ for (i = 0; i < map_numtexinfo; i++)
+ {
+ if (Q1_TextureContents(map_texinfo[i].texture) == brush->side)
+ {
+ texinfonum = i;
+ break;
+ } //end if
+ } //end for
+ } //end if
+ //
+ if (texinfonum >= 0)
+ {
+ //give all the brush sides this contents texture
+ for (i = 0; i < brush->numsides; i++)
+ {
+ brush->sides[i].texinfo = texinfonum;
+ } //end for
+ } //end if
+ else Log_Print("brush contents %d with wrong textures\n", brush->side);
+ //
+ } //end for
+ /*
+ for (brush = brushlist; brush; brush = brush->next)
+ {
+ //give all the brush sides this contents texture
+ for (i = 0; i < brush->numsides; i++)
+ {
+ if (Q1_TextureContents(map_texinfo[texinfonum].texture) != brush->side)
+ {
+ Error("brush contents %d with wrong contents textures %s\n", brush->side,
+ Q1_TextureContents(map_texinfo[texinfonum].texture));
+ } //end if
+ } //end for
+ } //end for*/
+} //end of the function Q1_FixContentsTextures
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Q1_BSPBrushToMapBrush(bspbrush_t *bspbrush, entity_t *mapent)
+{
+ mapbrush_t *mapbrush;
+ side_t *side;
+ int i, besttexinfo;
+
+ CheckBSPBrush(bspbrush);
+
+ if (nummapbrushes >= MAX_MAPFILE_BRUSHES)
+ Error ("nummapbrushes == MAX_MAPFILE_BRUSHES");
+
+ mapbrush = &mapbrushes[nummapbrushes];
+ mapbrush->original_sides = &brushsides[nummapbrushsides];
+ mapbrush->entitynum = mapent - entities;
+ mapbrush->brushnum = nummapbrushes - mapent->firstbrush;
+ mapbrush->leafnum = -1;
+ mapbrush->numsides = 0;
+
+ besttexinfo = TEXINFO_NODE;
+ for (i = 0; i < bspbrush->numsides; i++)
+ {
+ if (!bspbrush->sides[i].winding) continue;
+ //
+ if (nummapbrushsides >= MAX_MAPFILE_BRUSHSIDES)
+ Error ("MAX_MAPFILE_BRUSHSIDES");
+ side = &brushsides[nummapbrushsides];
+ //the contents of the bsp brush is stored in the side variable
+ side->contents = bspbrush->side;
+ side->surf = 0;
+ side->planenum = bspbrush->sides[i].planenum;
+ side->texinfo = bspbrush->sides[i].texinfo;
+ if (side->texinfo != TEXINFO_NODE)
+ {
+ //this brush side is textured
+ side->flags |= SFL_TEXTURED;
+ besttexinfo = side->texinfo;
+ } //end if
+ //
+ nummapbrushsides++;
+ mapbrush->numsides++;
+ } //end for
+ //
+ if (besttexinfo == TEXINFO_NODE)
+ {
+ mapbrush->numsides = 0;
+ q1_numclipbrushes++;
+ return;
+ } //end if
+ //set the texinfo for all the brush sides without texture
+ for (i = 0; i < mapbrush->numsides; i++)
+ {
+ if (mapbrush->original_sides[i].texinfo == TEXINFO_NODE)
+ {
+ mapbrush->original_sides[i].texinfo = besttexinfo;
+ } //end if
+ } //end for
+ //contents of the brush
+ mapbrush->contents = bspbrush->side;
+ //
+ if (create_aas)
+ {
+ //create the AAS brushes from this brush, add brush bevels
+ AAS_CreateMapBrushes(mapbrush, mapent, true);
+ return;
+ } //end if
+ //create windings for sides and bounds for brush
+ MakeBrushWindings(mapbrush);
+ //add brush bevels
+ AddBrushBevels(mapbrush);
+ //a new brush has been created
+ nummapbrushes++;
+ mapent->numbrushes++;
+} //end of the function Q1_BSPBrushToMapBrush
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Q1_CreateMapBrushes(entity_t *mapent, int modelnum)
+{
+ bspbrush_t *brushlist, *brush, *nextbrush;
+ int i;
+
+ //create brushes from the model BSP tree
+ brushlist = Q1_CreateBrushesFromBSP(modelnum);
+ //texture the brushes and split them when necesary
+ brushlist = Q1_TextureBrushes(brushlist, modelnum);
+ //fix the contents textures of all brushes
+ Q1_FixContentsTextures(brushlist);
+ //
+ if (!nobrushmerge)
+ {
+ brushlist = Q1_MergeBrushes(brushlist, modelnum);
+ //brushlist = Q1_MergeBrushes(brushlist, modelnum);
+ } //end if
+ //
+ if (!modelnum) qprintf("converting brushes to map brushes\n");
+ if (!modelnum) qprintf("%5d brushes", i = 0);
+ for (brush = brushlist; brush; brush = nextbrush)
+ {
+ nextbrush = brush->next;
+ Q1_BSPBrushToMapBrush(brush, mapent);
+ brush->next = NULL;
+ FreeBrush(brush);
+ if (!modelnum) qprintf("\r%5d", ++i);
+ } //end for
+ if (!modelnum) qprintf("\n");
+} //end of the function Q1_CreateMapBrushes
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Q1_ResetMapLoading(void)
+{
+} //end of the function Q1_ResetMapLoading
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Q1_LoadMapFromBSP(char *filename, int offset, int length)
+{
+ int i, modelnum;
+ char *model, *classname;
+
+ Log_Print("-- Q1_LoadMapFromBSP --\n");
+ //the loaded map type
+ loadedmaptype = MAPTYPE_QUAKE1;
+ //
+ qprintf("loading map from %s at %d\n", filename, offset);
+ //load the Half-Life BSP file
+ Q1_LoadBSPFile(filename, offset, length);
+ //
+ q1_numclipbrushes = 0;
+ //CreatePath(path);
+ //Q1_CreateQ2WALFiles(path);
+ //parse the entities from the BSP
+ Q1_ParseEntities();
+ //clear the map mins and maxs
+ ClearBounds(map_mins, map_maxs);
+ //
+ qprintf("creating Quake1 brushes\n");
+ if (lessbrushes) qprintf("creating minimum number of brushes\n");
+ else qprintf("placing textures correctly\n");
+ //
+ for (i = 0; i < num_entities; i++)
+ {
+ entities[i].firstbrush = nummapbrushes;
+ entities[i].numbrushes = 0;
+ //
+ classname = ValueForKey(&entities[i], "classname");
+ if (classname && !strcmp(classname, "worldspawn"))
+ {
+ modelnum = 0;
+ } //end if
+ else
+ {
+ //
+ model = ValueForKey(&entities[i], "model");
+ if (!model || *model != '*') continue;
+ model++;
+ modelnum = atoi(model);
+ } //end else
+ //create map brushes for the entity
+ Q1_CreateMapBrushes(&entities[i], modelnum);
+ } //end for
+ //
+ qprintf("%5d map brushes\n", nummapbrushes);
+ qprintf("%5d clip brushes\n", q1_numclipbrushes);
+} //end of the function Q1_LoadMapFromBSP
diff --git a/code/bspc/map_q2.c b/code/bspc/map_q2.c
new file mode 100755
index 0000000..0f15216
--- /dev/null
+++ b/code/bspc/map_q2.c
@@ -0,0 +1,1162 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+//===========================================================================
+// ANSI, Area Navigational System Interface
+// AAS, Area Awareness System
+//===========================================================================
+
+#include "qbsp.h"
+#include "l_mem.h"
+#include "../botlib/aasfile.h" //aas_bbox_t
+#include "aas_store.h" //AAS_MAX_BBOXES
+#include "aas_cfg.h"
+#include "aas_map.h" //AAS_CreateMapBrushes
+#include "l_bsp_q2.h"
+
+
+#ifdef ME
+
+#define NODESTACKSIZE 1024
+
+int nodestack[NODESTACKSIZE];
+int *nodestackptr;
+int nodestacksize = 0;
+int brushmodelnumbers[MAX_MAPFILE_BRUSHES];
+int dbrushleafnums[MAX_MAPFILE_BRUSHES];
+int dplanes2mapplanes[MAX_MAPFILE_PLANES];
+
+#endif //ME
+
+//====================================================================
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Q2_CreateMapTexinfo(void)
+{
+ int i;
+
+ for (i = 0; i < numtexinfo; i++)
+ {
+ memcpy(map_texinfo[i].vecs, texinfo[i].vecs, sizeof(float) * 2 * 4);
+ map_texinfo[i].flags = texinfo[i].flags;
+ map_texinfo[i].value = texinfo[i].value;
+ strcpy(map_texinfo[i].texture, texinfo[i].texture);
+ map_texinfo[i].nexttexinfo = 0;
+ } //end for
+} //end of the function Q2_CreateMapTexinfo
+
+/*
+===========
+Q2_BrushContents
+===========
+*/
+int Q2_BrushContents (mapbrush_t *b)
+{
+ int contents;
+ side_t *s;
+ int i;
+ int trans;
+
+ s = &b->original_sides[0];
+ contents = s->contents;
+ trans = texinfo[s->texinfo].flags;
+ for (i = 1; i < b->numsides; i++, s++)
+ {
+ s = &b->original_sides[i];
+ trans |= texinfo[s->texinfo].flags;
+ if (s->contents != contents)
+ {
+ Log_Print("Entity %i, Brush %i: mixed face contents\n"
+ , b->entitynum, b->brushnum);
+ Log_Print("texture name = %s\n", texinfo[s->texinfo].texture);
+ break;
+ }
+ }
+
+ // if any side is translucent, mark the contents
+ // and change solid to window
+ if ( trans & (SURF_TRANS33|SURF_TRANS66) )
+ {
+ contents |= CONTENTS_Q2TRANSLUCENT;
+ if (contents & CONTENTS_SOLID)
+ {
+ contents &= ~CONTENTS_SOLID;
+ contents |= CONTENTS_WINDOW;
+ }
+ }
+
+ return contents;
+}
+
+#ifdef ME
+
+#define BBOX_NORMAL_EPSILON 0.0001
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void MakeAreaPortalBrush(mapbrush_t *brush)
+{
+ int sn;
+ side_t *s;
+
+ brush->contents = CONTENTS_AREAPORTAL;
+
+ for (sn = 0; sn < brush->numsides; sn++)
+ {
+ s = brush->original_sides + sn;
+ //make sure the surfaces are not hint or skip
+ s->surf &= ~(SURF_HINT|SURF_SKIP);
+ //
+ s->texinfo = 0;
+ s->contents = CONTENTS_AREAPORTAL;
+ } //end for
+} //end of the function MakeAreaPortalBrush
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void DPlanes2MapPlanes(void)
+{
+ int i;
+
+ for (i = 0; i < numplanes; i++)
+ {
+ dplanes2mapplanes[i] = FindFloatPlane(dplanes[i].normal, dplanes[i].dist);
+ } //end for
+} //end of the function DPlanes2MapPlanes
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void MarkVisibleBrushSides(mapbrush_t *brush)
+{
+ int n, i, planenum;
+ side_t *side;
+ dface_t *face;
+ //
+ for (n = 0; n < brush->numsides; n++)
+ {
+ side = brush->original_sides + n;
+ //if this side is a bevel or the leaf number of the brush is unknown
+ if ((side->flags & SFL_BEVEL) || brush->leafnum < 0)
+ {
+ //this side is a valid splitter
+ side->flags |= SFL_VISIBLE;
+ continue;
+ } //end if
+ //assum this side will not be used as a splitter
+ side->flags &= ~SFL_VISIBLE;
+ //check if the side plane is used by a visible face
+ for (i = 0; i < numfaces; i++)
+ {
+ face = &dfaces[i];
+ planenum = dplanes2mapplanes[face->planenum];
+ if ((planenum & ~1) == (side->planenum & ~1))
+ {
+ //this side is a valid splitter
+ side->flags |= SFL_VISIBLE;
+ } //end if
+ } //end for
+ } //end for
+} //end of the function MarkVisibleBrushSides
+
+#endif //ME
+
+/*
+=================
+Q2_ParseBrush
+=================
+*/
+void Q2_ParseBrush (script_t *script, entity_t *mapent)
+{
+ mapbrush_t *b;
+ int i, j, k;
+ int mt;
+ side_t *side, *s2;
+ int planenum;
+ brush_texture_t td;
+ int planepts[3][3];
+ token_t token;
+
+ if (nummapbrushes >= MAX_MAPFILE_BRUSHES)
+ Error ("nummapbrushes == MAX_MAPFILE_BRUSHES");
+
+ b = &mapbrushes[nummapbrushes];
+ b->original_sides = &brushsides[nummapbrushsides];
+ b->entitynum = num_entities-1;
+ b->brushnum = nummapbrushes - mapent->firstbrush;
+ b->leafnum = -1;
+
+ do
+ {
+ if (!PS_ReadToken(script, &token))
+ break;
+ if (!strcmp(token.string, "}") )
+ break;
+
+ //IDBUG: mixed use of MAX_MAPFILE_? and MAX_MAP_? this could
+ // lead to out of bound indexing of the arrays
+ if (nummapbrushsides >= MAX_MAPFILE_BRUSHSIDES)
+ Error ("MAX_MAPFILE_BRUSHSIDES");
+ side = &brushsides[nummapbrushsides];
+
+ //read the three point plane definition
+ for (i = 0; i < 3; i++)
+ {
+ if (i != 0) PS_ExpectTokenString(script, "(");
+ for (j = 0; j < 3; j++)
+ {
+ PS_ExpectAnyToken(script, &token);
+ planepts[i][j] = atof(token.string);
+ } //end for
+ PS_ExpectTokenString(script, ")");
+ } //end for
+
+ //
+ //read the texturedef
+ //
+ PS_ExpectAnyToken(script, &token);
+ strcpy(td.name, token.string);
+
+ PS_ExpectAnyToken(script, &token);
+ td.shift[0] = atol(token.string);
+ PS_ExpectAnyToken(script, &token);
+ td.shift[1] = atol(token.string);
+ PS_ExpectAnyToken(script, &token);
+ td.rotate = atol(token.string);
+ PS_ExpectAnyToken(script, &token);
+ td.scale[0] = atof(token.string);
+ PS_ExpectAnyToken(script, &token);
+ td.scale[1] = atof(token.string);
+
+ //find default flags and values
+ mt = FindMiptex (td.name);
+ td.flags = textureref[mt].flags;
+ td.value = textureref[mt].value;
+ side->contents = textureref[mt].contents;
+ side->surf = td.flags = textureref[mt].flags;
+
+ //check if there's a number available
+ if (PS_CheckTokenType(script, TT_NUMBER, 0, &token))
+ {
+ side->contents = token.intvalue;
+ PS_ExpectTokenType(script, TT_NUMBER, 0, &token);
+ side->surf = td.flags = token.intvalue;
+ PS_ExpectTokenType(script, TT_NUMBER, 0, &token);
+ td.value = token.intvalue;
+ }
+
+ // translucent objects are automatically classified as detail
+ if (side->surf & (SURF_TRANS33|SURF_TRANS66) )
+ side->contents |= CONTENTS_DETAIL;
+ if (side->contents & (CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP) )
+ side->contents |= CONTENTS_DETAIL;
+ if (fulldetail)
+ side->contents &= ~CONTENTS_DETAIL;
+ if (!(side->contents & ((LAST_VISIBLE_CONTENTS-1)
+ | CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP|CONTENTS_MIST) ) )
+ side->contents |= CONTENTS_SOLID;
+
+ // hints and skips are never detail, and have no content
+ if (side->surf & (SURF_HINT|SURF_SKIP) )
+ {
+ side->contents = 0;
+ side->surf &= ~CONTENTS_DETAIL;
+ }
+
+#ifdef ME
+ //for creating AAS... this side is textured
+ side->flags |= SFL_TEXTURED;
+#endif //ME
+ //
+ // find the plane number
+ //
+ planenum = PlaneFromPoints (planepts[0], planepts[1], planepts[2]);
+ if (planenum == -1)
+ {
+ Log_Print("Entity %i, Brush %i: plane with no normal\n"
+ , b->entitynum, b->brushnum);
+ continue;
+ }
+
+ //
+ // see if the plane has been used already
+ //
+ for (k=0 ; k<b->numsides ; k++)
+ {
+ s2 = b->original_sides + k;
+ if (s2->planenum == planenum)
+ {
+ Log_Print("Entity %i, Brush %i: duplicate plane\n"
+ , b->entitynum, b->brushnum);
+ break;
+ }
+ if ( s2->planenum == (planenum^1) )
+ {
+ Log_Print("Entity %i, Brush %i: mirrored plane\n"
+ , b->entitynum, b->brushnum);
+ break;
+ }
+ }
+ if (k != b->numsides)
+ continue; // duplicated
+
+ //
+ // keep this side
+ //
+
+ side = b->original_sides + b->numsides;
+ side->planenum = planenum;
+ side->texinfo = TexinfoForBrushTexture (&mapplanes[planenum],
+ &td, vec3_origin);
+
+ // save the td off in case there is an origin brush and we
+ // have to recalculate the texinfo
+ side_brushtextures[nummapbrushsides] = td;
+
+ nummapbrushsides++;
+ b->numsides++;
+ } while (1);
+
+ // get the content for the entire brush
+ b->contents = Q2_BrushContents (b);
+
+#ifdef ME
+ if (BrushExists(b))
+ {
+ c_squattbrushes++;
+ b->numsides = 0;
+ return;
+ } //end if
+
+ if (create_aas)
+ {
+ //create AAS brushes, and add brush bevels
+ AAS_CreateMapBrushes(b, mapent, true);
+ //NOTE: if we return here then duplicate plane errors occur for the non world entities
+ return;
+ } //end if
+#endif //ME
+
+ // allow detail brushes to be removed
+ if (nodetail && (b->contents & CONTENTS_DETAIL) )
+ {
+ b->numsides = 0;
+ return;
+ }
+
+ // allow water brushes to be removed
+ if (nowater && (b->contents & (CONTENTS_LAVA | CONTENTS_SLIME | CONTENTS_WATER)) )
+ {
+ b->numsides = 0;
+ return;
+ }
+
+ // create windings for sides and bounds for brush
+ MakeBrushWindings (b);
+
+ // brushes that will not be visible at all will never be
+ // used as bsp splitters
+ if (b->contents & (CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP) )
+ {
+ c_clipbrushes++;
+ for (i=0 ; i<b->numsides ; i++)
+ b->original_sides[i].texinfo = TEXINFO_NODE;
+ }
+
+ //
+ // origin brushes are removed, but they set
+ // the rotation origin for the rest of the brushes
+ // in the entity. After the entire entity is parsed,
+ // the planenums and texinfos will be adjusted for
+ // the origin brush
+ //
+ if (b->contents & CONTENTS_ORIGIN)
+ {
+ char string[32];
+ vec3_t origin;
+
+ if (num_entities == 1)
+ {
+ Error ("Entity %i, Brush %i: origin brushes not allowed in world"
+ , b->entitynum, b->brushnum);
+ return;
+ }
+
+ VectorAdd (b->mins, b->maxs, origin);
+ VectorScale (origin, 0.5, origin);
+
+ sprintf (string, "%i %i %i", (int)origin[0], (int)origin[1], (int)origin[2]);
+ SetKeyValue (&entities[b->entitynum], "origin", string);
+
+ VectorCopy (origin, entities[b->entitynum].origin);
+
+ // don't keep this brush
+ b->numsides = 0;
+
+ return;
+ }
+
+ AddBrushBevels(b);
+
+ nummapbrushes++;
+ mapent->numbrushes++;
+}
+
+/*
+================
+Q2_MoveBrushesToWorld
+
+Takes all of the brushes from the current entity and
+adds them to the world's brush list.
+
+Used by func_group and func_areaportal
+================
+*/
+void Q2_MoveBrushesToWorld (entity_t *mapent)
+{
+ int newbrushes;
+ int worldbrushes;
+ mapbrush_t *temp;
+ int i;
+
+ // this is pretty gross, because the brushes are expected to be
+ // in linear order for each entity
+
+ newbrushes = mapent->numbrushes;
+ worldbrushes = entities[0].numbrushes;
+
+ temp = GetMemory(newbrushes*sizeof(mapbrush_t));
+ memcpy (temp, mapbrushes + mapent->firstbrush, newbrushes*sizeof(mapbrush_t));
+
+#if 0 // let them keep their original brush numbers
+ for (i=0 ; i<newbrushes ; i++)
+ temp[i].entitynum = 0;
+#endif
+
+ // make space to move the brushes (overlapped copy)
+ memmove (mapbrushes + worldbrushes + newbrushes,
+ mapbrushes + worldbrushes,
+ sizeof(mapbrush_t) * (nummapbrushes - worldbrushes - newbrushes) );
+
+ // copy the new brushes down
+ memcpy (mapbrushes + worldbrushes, temp, sizeof(mapbrush_t) * newbrushes);
+
+ // fix up indexes
+ entities[0].numbrushes += newbrushes;
+ for (i=1 ; i<num_entities ; i++)
+ entities[i].firstbrush += newbrushes;
+ FreeMemory(temp);
+
+ mapent->numbrushes = 0;
+}
+
+/*
+================
+Q2_ParseMapEntity
+================
+*/
+qboolean Q2_ParseMapEntity(script_t *script)
+{
+ entity_t *mapent;
+ epair_t *e;
+ side_t *s;
+ int i, j;
+ int startbrush, startsides;
+ vec_t newdist;
+ mapbrush_t *b;
+ token_t token;
+
+ if (!PS_ReadToken(script, &token)) return false;
+
+ if (strcmp(token.string, "{") )
+ Error ("ParseEntity: { not found");
+
+ if (num_entities == MAX_MAP_ENTITIES)
+ Error ("num_entities == MAX_MAP_ENTITIES");
+
+ startbrush = nummapbrushes;
+ startsides = nummapbrushsides;
+
+ mapent = &entities[num_entities];
+ num_entities++;
+ memset (mapent, 0, sizeof(*mapent));
+ mapent->firstbrush = nummapbrushes;
+ mapent->numbrushes = 0;
+// mapent->portalareas[0] = -1;
+// mapent->portalareas[1] = -1;
+
+ do
+ {
+ if (!PS_ReadToken(script, &token))
+ {
+ Error("ParseEntity: EOF without closing brace");
+ } //end if
+ if (!strcmp(token.string, "}")) break;
+ if (!strcmp(token.string, "{"))
+ {
+ Q2_ParseBrush(script, mapent);
+ } //end if
+ else
+ {
+ PS_UnreadLastToken(script);
+ e = ParseEpair(script);
+ e->next = mapent->epairs;
+ mapent->epairs = e;
+ } //end else
+ } while(1);
+
+ GetVectorForKey(mapent, "origin", mapent->origin);
+
+ //
+ // if there was an origin brush, offset all of the planes and texinfo
+ //
+ if (mapent->origin[0] || mapent->origin[1] || mapent->origin[2])
+ {
+ for (i=0 ; i<mapent->numbrushes ; i++)
+ {
+ b = &mapbrushes[mapent->firstbrush + i];
+ for (j=0 ; j<b->numsides ; j++)
+ {
+ s = &b->original_sides[j];
+ newdist = mapplanes[s->planenum].dist -
+ DotProduct (mapplanes[s->planenum].normal, mapent->origin);
+ s->planenum = FindFloatPlane (mapplanes[s->planenum].normal, newdist);
+ s->texinfo = TexinfoForBrushTexture (&mapplanes[s->planenum],
+ &side_brushtextures[s-brushsides], mapent->origin);
+ }
+ MakeBrushWindings (b);
+ }
+ }
+
+ // group entities are just for editor convenience
+ // toss all brushes into the world entity
+ if (!strcmp ("func_group", ValueForKey (mapent, "classname")))
+ {
+ Q2_MoveBrushesToWorld (mapent);
+ mapent->numbrushes = 0;
+ return true;
+ }
+
+ // areaportal entities move their brushes, but don't eliminate
+ // the entity
+ if (!strcmp ("func_areaportal", ValueForKey (mapent, "classname")))
+ {
+ char str[128];
+
+ if (mapent->numbrushes != 1)
+ Error ("Entity %i: func_areaportal can only be a single brush", num_entities-1);
+
+ b = &mapbrushes[nummapbrushes-1];
+ b->contents = CONTENTS_AREAPORTAL;
+ c_areaportals++;
+ mapent->areaportalnum = c_areaportals;
+ // set the portal number as "style"
+ sprintf (str, "%i", c_areaportals);
+ SetKeyValue (mapent, "style", str);
+ Q2_MoveBrushesToWorld (mapent);
+ return true;
+ }
+
+ return true;
+}
+
+//===================================================================
+
+/*
+================
+LoadMapFile
+================
+*/
+void Q2_LoadMapFile(char *filename)
+{
+ int i;
+ script_t *script;
+
+ Log_Print("-- Q2_LoadMapFile --\n");
+#ifdef ME
+ //loaded map type
+ loadedmaptype = MAPTYPE_QUAKE2;
+ //reset the map loading
+ ResetMapLoading();
+#endif //ME
+
+ script = LoadScriptFile(filename);
+ if (!script)
+ {
+ Log_Print("couldn't open %s\n", filename);
+ return;
+ } //end if
+ //white spaces and escape characters inside a string are not allowed
+ SetScriptFlags(script, SCFL_NOSTRINGWHITESPACES |
+ SCFL_NOSTRINGESCAPECHARS |
+ SCFL_PRIMITIVE);
+
+ nummapbrushsides = 0;
+ num_entities = 0;
+
+ while (Q2_ParseMapEntity(script))
+ {
+ }
+
+ ClearBounds (map_mins, map_maxs);
+ for (i=0 ; i<entities[0].numbrushes ; i++)
+ {
+ if (mapbrushes[i].mins[0] > 4096)
+ continue; // no valid points
+ AddPointToBounds (mapbrushes[i].mins, map_mins, map_maxs);
+ AddPointToBounds (mapbrushes[i].maxs, map_mins, map_maxs);
+ } //end for
+
+ PrintMapInfo();
+
+ //free the script
+ FreeScript(script);
+// TestExpandBrushes ();
+ //
+ Q2_CreateMapTexinfo();
+} //end of the function Q2_LoadMapFile
+
+#ifdef ME //Begin MAP loading from BSP file
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Q2_SetLeafBrushesModelNumbers(int leafnum, int modelnum)
+{
+ int i, brushnum;
+ dleaf_t *leaf;
+
+ leaf = &dleafs[leafnum];
+ for (i = 0; i < leaf->numleafbrushes; i++)
+ {
+ brushnum = dleafbrushes[leaf->firstleafbrush + i];
+ brushmodelnumbers[brushnum] = modelnum;
+ dbrushleafnums[brushnum] = leafnum;
+ } //end for
+} //end of the function Q2_SetLeafBrushesModelNumbers
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Q2_InitNodeStack(void)
+{
+ nodestackptr = nodestack;
+ nodestacksize = 0;
+} //end of the function Q2_InitNodeStack
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Q2_PushNodeStack(int num)
+{
+ *nodestackptr = num;
+ nodestackptr++;
+ nodestacksize++;
+ //
+ if (nodestackptr >= &nodestack[NODESTACKSIZE])
+ {
+ Error("Q2_PushNodeStack: stack overflow\n");
+ } //end if
+} //end of the function Q2_PushNodeStack
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int Q2_PopNodeStack(void)
+{
+ //if the stack is empty
+ if (nodestackptr <= nodestack) return -1;
+ //decrease stack pointer
+ nodestackptr--;
+ nodestacksize--;
+ //return the top value from the stack
+ return *nodestackptr;
+} //end of the function Q2_PopNodeStack
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Q2_SetBrushModelNumbers(entity_t *mapent)
+{
+ int n, pn;
+ int leafnum;
+
+ //
+ Q2_InitNodeStack();
+ //head node (root) of the bsp tree
+ n = dmodels[mapent->modelnum].headnode;
+ pn = 0;
+
+ do
+ {
+ //if we are in a leaf (negative node number)
+ if (n < 0)
+ {
+ //number of the leaf
+ leafnum = (-n) - 1;
+ //set the brush numbers
+ Q2_SetLeafBrushesModelNumbers(leafnum, mapent->modelnum);
+ //walk back into the tree to find a second child to continue with
+ for (pn = Q2_PopNodeStack(); pn >= 0; n = pn, pn = Q2_PopNodeStack())
+ {
+ //if we took the first child at the parent node
+ if (dnodes[pn].children[0] == n) break;
+ } //end for
+ //if the stack wasn't empty (if not processed whole tree)
+ if (pn >= 0)
+ {
+ //push the parent node again
+ Q2_PushNodeStack(pn);
+ //we proceed with the second child of the parent node
+ n = dnodes[pn].children[1];
+ } //end if
+ } //end if
+ else
+ {
+ //push the current node onto the stack
+ Q2_PushNodeStack(n);
+ //walk forward into the tree to the first child
+ n = dnodes[n].children[0];
+ } //end else
+ } while(pn >= 0);
+} //end of the function Q2_SetBrushModelNumbers
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Q2_BSPBrushToMapBrush(dbrush_t *bspbrush, entity_t *mapent)
+{
+ mapbrush_t *b;
+ int i, k, n;
+ side_t *side, *s2;
+ int planenum;
+ dbrushside_t *bspbrushside;
+ dplane_t *bspplane;
+
+ if (nummapbrushes >= MAX_MAPFILE_BRUSHES)
+ Error ("nummapbrushes >= MAX_MAPFILE_BRUSHES");
+
+ b = &mapbrushes[nummapbrushes];
+ b->original_sides = &brushsides[nummapbrushsides];
+ b->entitynum = mapent-entities;
+ b->brushnum = nummapbrushes - mapent->firstbrush;
+ b->leafnum = dbrushleafnums[bspbrush - dbrushes];
+
+ for (n = 0; n < bspbrush->numsides; n++)
+ {
+ //pointer to the bsp brush side
+ bspbrushside = &dbrushsides[bspbrush->firstside + n];
+
+ if (nummapbrushsides >= MAX_MAPFILE_BRUSHSIDES)
+ {
+ Error ("MAX_MAPFILE_BRUSHSIDES");
+ } //end if
+ //pointer to the map brush side
+ side = &brushsides[nummapbrushsides];
+ //if the BSP brush side is textured
+ if (brushsidetextured[bspbrush->firstside + n]) side->flags |= SFL_TEXTURED;
+ else side->flags &= ~SFL_TEXTURED;
+ //ME: can get side contents and surf directly from BSP file
+ side->contents = bspbrush->contents;
+ //if the texinfo is TEXINFO_NODE
+ if (bspbrushside->texinfo < 0) side->surf = 0;
+ else side->surf = texinfo[bspbrushside->texinfo].flags;
+
+ // translucent objects are automatically classified as detail
+ if (side->surf & (SURF_TRANS33|SURF_TRANS66) )
+ side->contents |= CONTENTS_DETAIL;
+ if (side->contents & (CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP) )
+ side->contents |= CONTENTS_DETAIL;
+ if (fulldetail)
+ side->contents &= ~CONTENTS_DETAIL;
+ if (!(side->contents & ((LAST_VISIBLE_CONTENTS-1)
+ | CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP|CONTENTS_MIST) ) )
+ side->contents |= CONTENTS_SOLID;
+
+ // hints and skips are never detail, and have no content
+ if (side->surf & (SURF_HINT|SURF_SKIP) )
+ {
+ side->contents = 0;
+ side->surf &= ~CONTENTS_DETAIL;
+ }
+
+ //ME: get a plane for this side
+ bspplane = &dplanes[bspbrushside->planenum];
+ planenum = FindFloatPlane(bspplane->normal, bspplane->dist);
+ //
+ // see if the plane has been used already
+ //
+ //ME: this really shouldn't happen!!!
+ //ME: otherwise the bsp file is corrupted??
+ //ME: still it seems to happen, maybe Johny Boy's
+ //ME: brush bevel adding is crappy ?
+ for (k = 0; k < b->numsides; k++)
+ {
+ s2 = b->original_sides + k;
+// if (DotProduct (mapplanes[s2->planenum].normal, mapplanes[planenum].normal) > 0.999
+// && fabs(mapplanes[s2->planenum].dist - mapplanes[planenum].dist) < 0.01 )
+
+ if (s2->planenum == planenum)
+ {
+ Log_Print("Entity %i, Brush %i: duplicate plane\n"
+ , b->entitynum, b->brushnum);
+ break;
+ }
+ if ( s2->planenum == (planenum^1) )
+ {
+ Log_Print("Entity %i, Brush %i: mirrored plane\n"
+ , b->entitynum, b->brushnum);
+ break;
+ }
+ }
+ if (k != b->numsides)
+ continue; // duplicated
+
+ //
+ // keep this side
+ //
+ //ME: reset pointer to side, why? hell I dunno (pointer is set above already)
+ side = b->original_sides + b->numsides;
+ //ME: store the plane number
+ side->planenum = planenum;
+ //ME: texinfo is already stored when bsp is loaded
+ //NOTE: check for TEXINFO_NODE, otherwise crash in Q2_BrushContents
+ if (bspbrushside->texinfo < 0) side->texinfo = 0;
+ else side->texinfo = bspbrushside->texinfo;
+
+ // save the td off in case there is an origin brush and we
+ // have to recalculate the texinfo
+ // ME: don't need to recalculate because it's already done
+ // (for non-world entities) in the BSP file
+// side_brushtextures[nummapbrushsides] = td;
+
+ nummapbrushsides++;
+ b->numsides++;
+ } //end for
+
+ // get the content for the entire brush
+ b->contents = bspbrush->contents;
+ Q2_BrushContents(b);
+
+ if (BrushExists(b))
+ {
+ c_squattbrushes++;
+ b->numsides = 0;
+ return;
+ } //end if
+
+ //if we're creating AAS
+ if (create_aas)
+ {
+ //create the AAS brushes from this brush, don't add brush bevels
+ AAS_CreateMapBrushes(b, mapent, false);
+ return;
+ } //end if
+
+ // allow detail brushes to be removed
+ if (nodetail && (b->contents & CONTENTS_DETAIL) )
+ {
+ b->numsides = 0;
+ return;
+ } //end if
+
+ // allow water brushes to be removed
+ if (nowater && (b->contents & (CONTENTS_LAVA | CONTENTS_SLIME | CONTENTS_WATER)) )
+ {
+ b->numsides = 0;
+ return;
+ } //end if
+
+ // create windings for sides and bounds for brush
+ MakeBrushWindings(b);
+
+ //mark brushes without winding or with a tiny window as bevels
+ MarkBrushBevels(b);
+
+ // brushes that will not be visible at all will never be
+ // used as bsp splitters
+ if (b->contents & (CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP) )
+ {
+ c_clipbrushes++;
+ for (i = 0; i < b->numsides; i++)
+ b->original_sides[i].texinfo = TEXINFO_NODE;
+ } //end for
+
+ //
+ // origin brushes are removed, but they set
+ // the rotation origin for the rest of the brushes
+ // in the entity. After the entire entity is parsed,
+ // the planenums and texinfos will be adjusted for
+ // the origin brush
+ //
+ //ME: not needed because the entities in the BSP file already
+ // have an origin set
+// if (b->contents & CONTENTS_ORIGIN)
+// {
+// char string[32];
+// vec3_t origin;
+//
+// if (num_entities == 1)
+// {
+// Error ("Entity %i, Brush %i: origin brushes not allowed in world"
+// , b->entitynum, b->brushnum);
+// return;
+// }
+//
+// VectorAdd (b->mins, b->maxs, origin);
+// VectorScale (origin, 0.5, origin);
+//
+// sprintf (string, "%i %i %i", (int)origin[0], (int)origin[1], (int)origin[2]);
+// SetKeyValue (&entities[b->entitynum], "origin", string);
+//
+// VectorCopy (origin, entities[b->entitynum].origin);
+//
+// // don't keep this brush
+// b->numsides = 0;
+//
+// return;
+// }
+
+ //ME: the bsp brushes already have bevels, so we won't try to
+ // add them again (especially since Johny Boy's bevel adding might
+ // be crappy)
+// AddBrushBevels(b);
+
+ nummapbrushes++;
+ mapent->numbrushes++;
+} //end of the function Q2_BSPBrushToMapBrush
+//===========================================================================
+//===========================================================================
+void Q2_ParseBSPBrushes(entity_t *mapent)
+{
+ int i;
+
+ //give all the brushes that belong to this entity the number of the
+ //BSP model used by this entity
+ Q2_SetBrushModelNumbers(mapent);
+ //now parse all the brushes with the correct mapent->modelnum
+ for (i = 0; i < numbrushes; i++)
+ {
+ if (brushmodelnumbers[i] == mapent->modelnum)
+ {
+ Q2_BSPBrushToMapBrush(&dbrushes[i], mapent);
+ } //end if
+ } //end for
+} //end of the function Q2_ParseBSPBrushes
+//===========================================================================
+//===========================================================================
+qboolean Q2_ParseBSPEntity(int entnum)
+{
+ entity_t *mapent;
+ char *model;
+ int startbrush, startsides;
+
+ startbrush = nummapbrushes;
+ startsides = nummapbrushsides;
+
+ mapent = &entities[entnum];//num_entities];
+ mapent->firstbrush = nummapbrushes;
+ mapent->numbrushes = 0;
+ mapent->modelnum = -1; //-1 = no model
+
+ model = ValueForKey(mapent, "model");
+ if (model && strlen(model))
+ {
+ if (*model != '*')
+ {
+ Error("Q2_ParseBSPEntity: model number without leading *");
+ } //end if
+ //get the model number of this entity (skip the leading *)
+ mapent->modelnum = atoi(&model[1]);
+ } //end if
+
+ GetVectorForKey(mapent, "origin", mapent->origin);
+
+ //if this is the world entity it has model number zero
+ //the world entity has no model key
+ if (!strcmp("worldspawn", ValueForKey(mapent, "classname")))
+ {
+ mapent->modelnum = 0;
+ } //end if
+ //if the map entity has a BSP model (a modelnum of -1 is used for
+ //entities that aren't using a BSP model)
+ if (mapent->modelnum >= 0)
+ {
+ //parse the bsp brushes
+ Q2_ParseBSPBrushes(mapent);
+ } //end if
+ //
+ //the origin of the entity is already taken into account
+ //
+ //func_group entities can't be in the bsp file
+ //
+ //check out the func_areaportal entities
+ if (!strcmp ("func_areaportal", ValueForKey (mapent, "classname")))
+ {
+ c_areaportals++;
+ mapent->areaportalnum = c_areaportals;
+ return true;
+ } //end if
+ return true;
+} //end of the function Q2_ParseBSPEntity
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Q2_LoadMapFromBSP(char *filename, int offset, int length)
+{
+ int i;
+
+ Log_Print("-- Q2_LoadMapFromBSP --\n");
+ //loaded map type
+ loadedmaptype = MAPTYPE_QUAKE2;
+
+ Log_Print("Loading map from %s...\n", filename);
+ //load the bsp file
+ Q2_LoadBSPFile(filename, offset, length);
+
+ //create an index from bsp planes to map planes
+ //DPlanes2MapPlanes();
+ //clear brush model numbers
+ for (i = 0; i < MAX_MAPFILE_BRUSHES; i++)
+ brushmodelnumbers[i] = -1;
+
+ nummapbrushsides = 0;
+ num_entities = 0;
+
+ Q2_ParseEntities();
+ //
+ for (i = 0; i < num_entities; i++)
+ {
+ Q2_ParseBSPEntity(i);
+ } //end for
+
+ //get the map mins and maxs from the world model
+ ClearBounds(map_mins, map_maxs);
+ for (i = 0; i < entities[0].numbrushes; i++)
+ {
+ if (mapbrushes[i].mins[0] > 4096)
+ continue; //no valid points
+ AddPointToBounds (mapbrushes[i].mins, map_mins, map_maxs);
+ AddPointToBounds (mapbrushes[i].maxs, map_mins, map_maxs);
+ } //end for
+
+ PrintMapInfo();
+ //
+ Q2_CreateMapTexinfo();
+} //end of the function Q2_LoadMapFromBSP
+
+void Q2_ResetMapLoading(void)
+{
+ //reset for map loading from bsp
+ memset(nodestack, 0, NODESTACKSIZE * sizeof(int));
+ nodestackptr = NULL;
+ nodestacksize = 0;
+ memset(brushmodelnumbers, 0, MAX_MAPFILE_BRUSHES * sizeof(int));
+} //end of the function Q2_ResetMapLoading
+
+//End MAP loading from BSP file
+#endif //ME
+
+//====================================================================
+
+/*
+================
+TestExpandBrushes
+
+Expands all the brush planes and saves a new map out
+================
+*/
+void TestExpandBrushes (void)
+{
+ FILE *f;
+ side_t *s;
+ int i, j, bn;
+ winding_t *w;
+ char *name = "expanded.map";
+ mapbrush_t *brush;
+ vec_t dist;
+
+ Log_Print("writing %s\n", name);
+ f = fopen (name, "wb");
+ if (!f)
+ Error ("Can't write %s\n", name);
+
+ fprintf (f, "{\n\"classname\" \"worldspawn\"\n");
+
+ for (bn=0 ; bn<nummapbrushes ; bn++)
+ {
+ brush = &mapbrushes[bn];
+ fprintf (f, "{\n");
+ for (i=0 ; i<brush->numsides ; i++)
+ {
+ s = brush->original_sides + i;
+ dist = mapplanes[s->planenum].dist;
+ for (j=0 ; j<3 ; j++)
+ dist += fabs( 16 * mapplanes[s->planenum].normal[j] );
+
+ w = BaseWindingForPlane (mapplanes[s->planenum].normal, dist);
+
+ fprintf (f,"( %i %i %i ) ", (int)w->p[0][0], (int)w->p[0][1], (int)w->p[0][2]);
+ fprintf (f,"( %i %i %i ) ", (int)w->p[1][0], (int)w->p[1][1], (int)w->p[1][2]);
+ fprintf (f,"( %i %i %i ) ", (int)w->p[2][0], (int)w->p[2][1], (int)w->p[2][2]);
+
+ fprintf (f, "%s 0 0 0 1 1\n", texinfo[s->texinfo].texture);
+ FreeWinding (w);
+ }
+ fprintf (f, "}\n");
+ }
+ fprintf (f, "}\n");
+
+ fclose (f);
+
+ Error ("can't proceed after expanding brushes");
+} //end of the function TestExpandBrushes
+
diff --git a/code/bspc/map_q3.c b/code/bspc/map_q3.c
new file mode 100755
index 0000000..750b304
--- /dev/null
+++ b/code/bspc/map_q3.c
@@ -0,0 +1,681 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+#include "l_mem.h"
+#include "../botlib/aasfile.h" //aas_bbox_t
+#include "aas_store.h" //AAS_MAX_BBOXES
+#include "aas_cfg.h"
+#include "aas_map.h" //AAS_CreateMapBrushes
+#include "l_bsp_q3.h"
+#include "../qcommon/cm_patch.h"
+#include "../game/surfaceflags.h"
+
+#define NODESTACKSIZE 1024
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void PrintContents(int contents);
+
+int Q3_BrushContents(mapbrush_t *b)
+{
+ int contents, i, mixed, hint;
+ side_t *s;
+
+ s = &b->original_sides[0];
+ contents = s->contents;
+ //
+ mixed = false;
+ hint = false;
+ for (i = 1; i < b->numsides; i++)
+ {
+ s = &b->original_sides[i];
+ if (s->contents != contents) mixed = true;
+ if (s->surf & (SURF_HINT|SURF_SKIP)) hint = true;
+ contents |= s->contents;
+ } //end for
+ //
+ if (hint)
+ {
+ if (contents)
+ {
+ Log_Write("WARNING: hint brush with contents: ");
+ PrintContents(contents);
+ Log_Write("\r\n");
+ //
+ Log_Write("brush contents is: ");
+ PrintContents(b->contents);
+ Log_Write("\r\n");
+ } //end if
+ return 0;
+ } //end if
+ //Log_Write("brush %d contents ", nummapbrushes);
+ //PrintContents(contents);
+ //Log_Write("\r\n");
+ //remove ladder and fog contents
+ contents &= ~(CONTENTS_LADDER|CONTENTS_FOG);
+ //
+ if (mixed)
+ {
+ Log_Write("Entity %i, Brush %i: mixed face contents "
+ , b->entitynum, b->brushnum);
+ PrintContents(contents);
+ Log_Write("\r\n");
+ //
+ Log_Write("brush contents is: ");
+ PrintContents(b->contents);
+ Log_Write("\r\n");
+ //
+ if (contents & CONTENTS_DONOTENTER) return CONTENTS_DONOTENTER;//Log_Print("mixed contents with donotenter\n");
+ /*
+ Log_Print("contents:"); PrintContents(contents);
+ Log_Print("\ncontents:"); PrintContents(s->contents);
+ Log_Print("\n");
+ Log_Print("texture name = %s\n", texinfo[s->texinfo].texture);
+ */
+ //if liquid brush
+ if (contents & (CONTENTS_LAVA | CONTENTS_SLIME | CONTENTS_WATER))
+ {
+ return (contents & (CONTENTS_LAVA | CONTENTS_SLIME | CONTENTS_WATER));
+ } //end if
+ if (contents & CONTENTS_PLAYERCLIP) return (contents & CONTENTS_PLAYERCLIP);
+ return (contents & CONTENTS_SOLID);
+ } //end if
+ /*
+ if (contents & CONTENTS_AREAPORTAL)
+ {
+ static int num;
+ Log_Write("Entity %i, Brush %i: area portal %d\r\n", b->entitynum, b->brushnum, num++);
+ } //end if*/
+ if (contents == (contents & CONTENTS_STRUCTURAL))
+ {
+ //Log_Print("brush %i is only structural\n", b->brushnum);
+ contents = 0;
+ } //end if
+ if (contents & CONTENTS_DONOTENTER)
+ {
+ Log_Print("brush %i is a donotenter brush, c = %X\n", b->brushnum, contents);
+ } //end if
+ return contents;
+} //end of the function Q3_BrushContents
+#define BBOX_NORMAL_EPSILON 0.0001
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Q3_DPlanes2MapPlanes(void)
+{
+ int i;
+
+ for (i = 0; i < q3_numplanes; i++)
+ {
+ dplanes2mapplanes[i] = FindFloatPlane(q3_dplanes[i].normal, q3_dplanes[i].dist);
+ } //end for
+} //end of the function Q3_DPlanes2MapPlanes
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Q3_BSPBrushToMapBrush(q3_dbrush_t *bspbrush, entity_t *mapent)
+{
+ mapbrush_t *b;
+ int i, k, n;
+ side_t *side, *s2;
+ int planenum;
+ q3_dbrushside_t *bspbrushside;
+ q3_dplane_t *bspplane;
+
+ if (nummapbrushes >= MAX_MAPFILE_BRUSHES)
+ Error ("nummapbrushes >= MAX_MAPFILE_BRUSHES");
+
+ b = &mapbrushes[nummapbrushes];
+ b->original_sides = &brushsides[nummapbrushsides];
+ b->entitynum = mapent-entities;
+ b->brushnum = nummapbrushes - mapent->firstbrush;
+ b->leafnum = dbrushleafnums[bspbrush - q3_dbrushes];
+
+ for (n = 0; n < bspbrush->numSides; n++)
+ {
+ //pointer to the bsp brush side
+ bspbrushside = &q3_dbrushsides[bspbrush->firstSide + n];
+
+ if (nummapbrushsides >= MAX_MAPFILE_BRUSHSIDES)
+ {
+ Error ("MAX_MAPFILE_BRUSHSIDES");
+ } //end if
+ //pointer to the map brush side
+ side = &brushsides[nummapbrushsides];
+ //if the BSP brush side is textured
+ if (q3_dbrushsidetextured[bspbrush->firstSide + n]) side->flags |= SFL_TEXTURED|SFL_VISIBLE;
+ else side->flags &= ~SFL_TEXTURED;
+ //NOTE: all Quake3 sides are assumed textured
+ //side->flags |= SFL_TEXTURED|SFL_VISIBLE;
+ //
+ if (bspbrushside->shaderNum < 0)
+ {
+ side->contents = 0;
+ side->surf = 0;
+ } //end if
+ else
+ {
+ side->contents = q3_dshaders[bspbrushside->shaderNum].contentFlags;
+ side->surf = q3_dshaders[bspbrushside->shaderNum].surfaceFlags;
+ if (strstr(q3_dshaders[bspbrushside->shaderNum].shader, "common/hint"))
+ {
+ //Log_Print("found hint side\n");
+ side->surf |= SURF_HINT;
+ } //end if
+ } //end else
+ //
+ if (side->surf & SURF_NODRAW)
+ {
+ side->flags |= SFL_TEXTURED|SFL_VISIBLE;
+ } //end if
+ /*
+ if (side->contents & (CONTENTS_TRANSLUCENT|CONTENTS_STRUCTURAL))
+ {
+ side->flags |= SFL_TEXTURED|SFL_VISIBLE;
+ } //end if*/
+
+ // hints and skips are never detail, and have no content
+ if (side->surf & (SURF_HINT|SURF_SKIP) )
+ {
+ side->contents = 0;
+ //Log_Print("found hint brush side\n");
+ }
+ /*
+ if ((side->surf & SURF_NODRAW) && (side->surf & SURF_NOIMPACT))
+ {
+ side->contents = 0;
+ side->surf &= ~CONTENTS_DETAIL;
+ Log_Print("probably found hint brush in a BSP without hints being used\n");
+ } //end if*/
+
+ //ME: get a plane for this side
+ bspplane = &q3_dplanes[bspbrushside->planeNum];
+ planenum = FindFloatPlane(bspplane->normal, bspplane->dist);
+ //
+ // see if the plane has been used already
+ //
+ //ME: this really shouldn't happen!!!
+ //ME: otherwise the bsp file is corrupted??
+ //ME: still it seems to happen, maybe Johny Boy's
+ //ME: brush bevel adding is crappy ?
+ for (k = 0; k < b->numsides; k++)
+ {
+ s2 = b->original_sides + k;
+// if (DotProduct (mapplanes[s2->planenum].normal, mapplanes[planenum].normal) > 0.999
+// && fabs(mapplanes[s2->planenum].dist - mapplanes[planenum].dist) < 0.01 )
+
+ if (s2->planenum == planenum)
+ {
+ Log_Print("Entity %i, Brush %i: duplicate plane\n"
+ , b->entitynum, b->brushnum);
+ break;
+ }
+ if ( s2->planenum == (planenum^1) )
+ {
+ Log_Print("Entity %i, Brush %i: mirrored plane\n"
+ , b->entitynum, b->brushnum);
+ break;
+ }
+ }
+ if (k != b->numsides)
+ continue; // duplicated
+
+ //
+ // keep this side
+ //
+ //ME: reset pointer to side, why? hell I dunno (pointer is set above already)
+ side = b->original_sides + b->numsides;
+ //ME: store the plane number
+ side->planenum = planenum;
+ //ME: texinfo is already stored when bsp is loaded
+ //NOTE: check for TEXINFO_NODE, otherwise crash in Q3_BrushContents
+ //if (bspbrushside->texinfo < 0) side->texinfo = 0;
+ //else side->texinfo = bspbrushside->texinfo;
+
+ // save the td off in case there is an origin brush and we
+ // have to recalculate the texinfo
+ // ME: don't need to recalculate because it's already done
+ // (for non-world entities) in the BSP file
+// side_brushtextures[nummapbrushsides] = td;
+
+ nummapbrushsides++;
+ b->numsides++;
+ } //end for
+
+ // get the content for the entire brush
+ b->contents = q3_dshaders[bspbrush->shaderNum].contentFlags;
+ b->contents &= ~(CONTENTS_LADDER|CONTENTS_FOG|CONTENTS_STRUCTURAL);
+// b->contents = Q3_BrushContents(b);
+ //
+
+ if (BrushExists(b))
+ {
+ c_squattbrushes++;
+ b->numsides = 0;
+ return;
+ } //end if
+
+ //if we're creating AAS
+ if (create_aas)
+ {
+ //create the AAS brushes from this brush, don't add brush bevels
+ AAS_CreateMapBrushes(b, mapent, false);
+ return;
+ } //end if
+
+ // allow detail brushes to be removed
+ if (nodetail && (b->contents & CONTENTS_DETAIL) )
+ {
+ b->numsides = 0;
+ return;
+ } //end if
+
+ // allow water brushes to be removed
+ if (nowater && (b->contents & (CONTENTS_LAVA | CONTENTS_SLIME | CONTENTS_WATER)) )
+ {
+ b->numsides = 0;
+ return;
+ } //end if
+
+ // create windings for sides and bounds for brush
+ MakeBrushWindings(b);
+
+ //mark brushes without winding or with a tiny window as bevels
+ MarkBrushBevels(b);
+
+ // brushes that will not be visible at all will never be
+ // used as bsp splitters
+ if (b->contents & (CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP) )
+ {
+ c_clipbrushes++;
+ for (i = 0; i < b->numsides; i++)
+ b->original_sides[i].texinfo = TEXINFO_NODE;
+ } //end for
+
+ //
+ // origin brushes are removed, but they set
+ // the rotation origin for the rest of the brushes
+ // in the entity. After the entire entity is parsed,
+ // the planenums and texinfos will be adjusted for
+ // the origin brush
+ //
+ //ME: not needed because the entities in the BSP file already
+ // have an origin set
+// if (b->contents & CONTENTS_ORIGIN)
+// {
+// char string[32];
+// vec3_t origin;
+//
+// if (num_entities == 1)
+// {
+// Error ("Entity %i, Brush %i: origin brushes not allowed in world"
+// , b->entitynum, b->brushnum);
+// return;
+// }
+//
+// VectorAdd (b->mins, b->maxs, origin);
+// VectorScale (origin, 0.5, origin);
+//
+// sprintf (string, "%i %i %i", (int)origin[0], (int)origin[1], (int)origin[2]);
+// SetKeyValue (&entities[b->entitynum], "origin", string);
+//
+// VectorCopy (origin, entities[b->entitynum].origin);
+//
+// // don't keep this brush
+// b->numsides = 0;
+//
+// return;
+// }
+
+ //ME: the bsp brushes already have bevels, so we won't try to
+ // add them again (especially since Johny Boy's bevel adding might
+ // be crappy)
+// AddBrushBevels(b);
+
+ nummapbrushes++;
+ mapent->numbrushes++;
+} //end of the function Q3_BSPBrushToMapBrush
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Q3_ParseBSPBrushes(entity_t *mapent)
+{
+ int i;
+
+ for (i = 0; i < q3_dmodels[mapent->modelnum].numBrushes; i++)
+ {
+ Q3_BSPBrushToMapBrush(&q3_dbrushes[q3_dmodels[mapent->modelnum].firstBrush + i], mapent);
+ } //end for
+} //end of the function Q3_ParseBSPBrushes
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean Q3_ParseBSPEntity(int entnum)
+{
+ entity_t *mapent;
+ char *model;
+ int startbrush, startsides;
+
+ startbrush = nummapbrushes;
+ startsides = nummapbrushsides;
+
+ mapent = &entities[entnum];//num_entities];
+ mapent->firstbrush = nummapbrushes;
+ mapent->numbrushes = 0;
+ mapent->modelnum = -1; //-1 = no BSP model
+
+ model = ValueForKey(mapent, "model");
+ if (model && strlen(model))
+ {
+ if (*model == '*')
+ {
+ //get the model number of this entity (skip the leading *)
+ mapent->modelnum = atoi(&model[1]);
+ } //end if
+ } //end if
+
+ GetVectorForKey(mapent, "origin", mapent->origin);
+
+ //if this is the world entity it has model number zero
+ //the world entity has no model key
+ if (!strcmp("worldspawn", ValueForKey(mapent, "classname")))
+ {
+ mapent->modelnum = 0;
+ } //end if
+ //if the map entity has a BSP model (a modelnum of -1 is used for
+ //entities that aren't using a BSP model)
+ if (mapent->modelnum >= 0)
+ {
+ //parse the bsp brushes
+ Q3_ParseBSPBrushes(mapent);
+ } //end if
+ //
+ //the origin of the entity is already taken into account
+ //
+ //func_group entities can't be in the bsp file
+ //
+ //check out the func_areaportal entities
+ if (!strcmp ("func_areaportal", ValueForKey (mapent, "classname")))
+ {
+ c_areaportals++;
+ mapent->areaportalnum = c_areaportals;
+ return true;
+ } //end if
+ return true;
+} //end of the function Q3_ParseBSPEntity
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+#define MAX_PATCH_VERTS 1024
+
+void AAS_CreateCurveBrushes(void)
+{
+ int i, j, n, planenum, numcurvebrushes = 0;
+ q3_dsurface_t *surface;
+ q3_drawVert_t *dv_p;
+ vec3_t points[MAX_PATCH_VERTS];
+ int width, height, c;
+ patchCollide_t *pc;
+ facet_t *facet;
+ mapbrush_t *brush;
+ side_t *side;
+ entity_t *mapent;
+ winding_t *winding;
+
+ qprintf("nummapbrushsides = %d\n", nummapbrushsides);
+ mapent = &entities[0];
+ for (i = 0; i < q3_numDrawSurfaces; i++)
+ {
+ surface = &q3_drawSurfaces[i];
+ if ( ! surface->patchWidth ) continue;
+ // if the curve is not solid
+ if (!(q3_dshaders[surface->shaderNum].contentFlags & (CONTENTS_SOLID|CONTENTS_PLAYERCLIP)))
+ {
+ //Log_Print("skipped non-solid curve\n");
+ continue;
+ } //end if
+ // if this curve should not be used for AAS
+ if ( q3_dshaders[surface->shaderNum].contentFlags & CONTENTS_NOBOTCLIP ) {
+ continue;
+ }
+ //
+ width = surface->patchWidth;
+ height = surface->patchHeight;
+ c = width * height;
+ if (c > MAX_PATCH_VERTS)
+ {
+ Error("ParseMesh: MAX_PATCH_VERTS");
+ } //end if
+
+ dv_p = q3_drawVerts + surface->firstVert;
+ for ( j = 0 ; j < c ; j++, dv_p++ )
+ {
+ points[j][0] = dv_p->xyz[0];
+ points[j][1] = dv_p->xyz[1];
+ points[j][2] = dv_p->xyz[2];
+ } //end for
+ // create the internal facet structure
+ pc = CM_GeneratePatchCollide(width, height, points);
+ //
+ for (j = 0; j < pc->numFacets; j++)
+ {
+ facet = &pc->facets[j];
+ //
+ brush = &mapbrushes[nummapbrushes];
+ brush->original_sides = &brushsides[nummapbrushsides];
+ brush->entitynum = 0;
+ brush->brushnum = nummapbrushes - mapent->firstbrush;
+ //
+ brush->numsides = facet->numBorders + 2;
+ nummapbrushsides += brush->numsides;
+ brush->contents = CONTENTS_SOLID;
+ //
+ //qprintf("\r%6d curve brushes", nummapbrushsides);//++numcurvebrushes);
+ qprintf("\r%6d curve brushes", ++numcurvebrushes);
+ //
+ planenum = FindFloatPlane(pc->planes[facet->surfacePlane].plane, pc->planes[facet->surfacePlane].plane[3]);
+ //
+ side = &brush->original_sides[0];
+ side->planenum = planenum;
+ side->contents = CONTENTS_SOLID;
+ side->flags |= SFL_TEXTURED|SFL_VISIBLE|SFL_CURVE;
+ side->surf = 0;
+ //
+ side = &brush->original_sides[1];
+ if (create_aas)
+ {
+ //the plane is expanded later so it's not a problem that
+ //these first two opposite sides are coplanar
+ side->planenum = planenum ^ 1;
+ } //end if
+ else
+ {
+ side->planenum = FindFloatPlane(mapplanes[planenum^1].normal, mapplanes[planenum^1].dist + 1);
+ side->flags |= SFL_TEXTURED|SFL_VISIBLE;
+ } //end else
+ side->contents = CONTENTS_SOLID;
+ side->flags |= SFL_CURVE;
+ side->surf = 0;
+ //
+ winding = BaseWindingForPlane(mapplanes[side->planenum].normal, mapplanes[side->planenum].dist);
+ for (n = 0; n < facet->numBorders; n++)
+ {
+ //never use the surface plane as a border
+ if (facet->borderPlanes[n] == facet->surfacePlane) continue;
+ //
+ side = &brush->original_sides[2 + n];
+ side->planenum = FindFloatPlane(pc->planes[facet->borderPlanes[n]].plane, pc->planes[facet->borderPlanes[n]].plane[3]);
+ if (facet->borderInward[n]) side->planenum ^= 1;
+ side->contents = CONTENTS_SOLID;
+ side->flags |= SFL_TEXTURED|SFL_CURVE;
+ side->surf = 0;
+ //chop the winding in place
+ if (winding) ChopWindingInPlace(&winding, mapplanes[side->planenum^1].normal, mapplanes[side->planenum^1].dist, 0.1); //CLIP_EPSILON);
+ } //end for
+ //VectorCopy(pc->bounds[0], brush->mins);
+ //VectorCopy(pc->bounds[1], brush->maxs);
+ if (!winding)
+ {
+ Log_Print("WARNING: AAS_CreateCurveBrushes: no winding\n");
+ brush->numsides = 0;
+ continue;
+ } //end if
+ brush->original_sides[0].winding = winding;
+ WindingBounds(winding, brush->mins, brush->maxs);
+ for (n = 0; n < 3; n++)
+ {
+ //IDBUG: all the indexes into the mins and maxs were zero (not using i)
+ if (brush->mins[n] < -MAX_MAP_BOUNDS || brush->maxs[n] > MAX_MAP_BOUNDS)
+ {
+ Log_Print("entity %i, brush %i: bounds out of range\n", brush->entitynum, brush->brushnum);
+ Log_Print("brush->mins[%d] = %f, brush->maxs[%d] = %f\n", n, brush->mins[n], n, brush->maxs[n]);
+ brush->numsides = 0; //remove the brush
+ break;
+ } //end if
+ if (brush->mins[n] > MAX_MAP_BOUNDS || brush->maxs[n] < -MAX_MAP_BOUNDS)
+ {
+ Log_Print("entity %i, brush %i: no visible sides on brush\n", brush->entitynum, brush->brushnum);
+ Log_Print("brush->mins[%d] = %f, brush->maxs[%d] = %f\n", n, brush->mins[n], n, brush->maxs[n]);
+ brush->numsides = 0; //remove the brush
+ break;
+ } //end if
+ } //end for
+ if (create_aas)
+ {
+ //NOTE: brush bevels now already added
+ //AddBrushBevels(brush);
+ AAS_CreateMapBrushes(brush, mapent, false);
+ } //end if
+ else
+ {
+ // create windings for sides and bounds for brush
+ MakeBrushWindings(brush);
+ AddBrushBevels(brush);
+ nummapbrushes++;
+ mapent->numbrushes++;
+ } //end else
+ } //end for
+ } //end for
+ //qprintf("\r%6d curve brushes", nummapbrushsides);//++numcurvebrushes);
+ qprintf("\r%6d curve brushes\n", numcurvebrushes);
+} //end of the function AAS_CreateCurveBrushes
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AAS_ExpandMapBrush(mapbrush_t *brush, vec3_t mins, vec3_t maxs);
+
+void Q3_LoadMapFromBSP(struct quakefile_s *qf)
+{
+ int i;
+ vec3_t mins = {-1,-1,-1}, maxs = {1, 1, 1};
+
+ Log_Print("-- Q3_LoadMapFromBSP --\n");
+ //loaded map type
+ loadedmaptype = MAPTYPE_QUAKE3;
+
+ Log_Print("Loading map from %s...\n", qf->filename);
+ //load the bsp file
+ Q3_LoadBSPFile(qf);
+
+ //create an index from bsp planes to map planes
+ //DPlanes2MapPlanes();
+ //clear brush model numbers
+ for (i = 0; i < MAX_MAPFILE_BRUSHES; i++)
+ brushmodelnumbers[i] = -1;
+
+ nummapbrushsides = 0;
+ num_entities = 0;
+
+ Q3_ParseEntities();
+ //
+ for (i = 0; i < num_entities; i++)
+ {
+ Q3_ParseBSPEntity(i);
+ } //end for
+
+ AAS_CreateCurveBrushes();
+ //get the map mins and maxs from the world model
+ ClearBounds(map_mins, map_maxs);
+ for (i = 0; i < entities[0].numbrushes; i++)
+ {
+ if (mapbrushes[i].numsides <= 0)
+ continue;
+ AddPointToBounds (mapbrushes[i].mins, map_mins, map_maxs);
+ AddPointToBounds (mapbrushes[i].maxs, map_mins, map_maxs);
+ } //end for
+ /*/
+ for (i = 0; i < nummapbrushes; i++)
+ {
+ //if (!mapbrushes[i].original_sides) continue;
+ //AddBrushBevels(&mapbrushes[i]);
+ //AAS_ExpandMapBrush(&mapbrushes[i], mins, maxs);
+ } //end for*/
+ /*
+ for (i = 0; i < nummapbrushsides; i++)
+ {
+ Log_Write("side %d flags = %d", i, brushsides[i].flags);
+ } //end for
+ for (i = 0; i < nummapbrushes; i++)
+ {
+ Log_Write("brush contents: ");
+ PrintContents(mapbrushes[i].contents);
+ Log_Print("\n");
+ } //end for*/
+} //end of the function Q3_LoadMapFromBSP
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Q3_ResetMapLoading(void)
+{
+ //reset for map loading from bsp
+ memset(nodestack, 0, NODESTACKSIZE * sizeof(int));
+ nodestackptr = NULL;
+ nodestacksize = 0;
+ memset(brushmodelnumbers, 0, MAX_MAPFILE_BRUSHES * sizeof(int));
+} //end of the function Q3_ResetMapLoading
+
diff --git a/code/bspc/map_sin.c b/code/bspc/map_sin.c
new file mode 100755
index 0000000..7794b8c
--- /dev/null
+++ b/code/bspc/map_sin.c
@@ -0,0 +1,1211 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//-----------------------------------------------------------------------------
+//
+// $Logfile:: /MissionPack/code/bspc/map_sin.c $
+
+#include "qbsp.h"
+#include "l_bsp_sin.h"
+#include "aas_map.h" //AAS_CreateMapBrushes
+
+
+//====================================================================
+
+
+/*
+===========
+Sin_BrushContents
+===========
+*/
+
+int Sin_BrushContents(mapbrush_t *b)
+{
+ int contents;
+ side_t *s;
+ int i;
+#ifdef SIN
+ float trans = 0;
+#else
+ int trans;
+#endif
+
+ s = &b->original_sides[0];
+ contents = s->contents;
+
+#ifdef SIN
+ trans = sin_texinfo[s->texinfo].translucence;
+#else
+ trans = texinfo[s->texinfo].flags;
+#endif
+ for (i=1 ; i<b->numsides ; i++, s++)
+ {
+ s = &b->original_sides[i];
+#ifdef SIN
+ trans += sin_texinfo[s->texinfo].translucence;
+#else
+ trans |= texinfo[s->texinfo].flags;
+#endif
+ if (s->contents != contents)
+ {
+#ifdef SIN
+ if (
+ ( s->contents & CONTENTS_DETAIL && !(contents & CONTENTS_DETAIL) ) ||
+ ( !(s->contents & CONTENTS_DETAIL) && contents & CONTENTS_DETAIL )
+ )
+ {
+ s->contents |= CONTENTS_DETAIL;
+ contents |= CONTENTS_DETAIL;
+ continue;
+ }
+#endif
+ printf ("Entity %i, Brush %i: mixed face contents\n"
+ , b->entitynum, b->brushnum);
+ break;
+ }
+ }
+
+
+#ifdef SIN
+ if (contents & CONTENTS_FENCE)
+ {
+// contents |= CONTENTS_TRANSLUCENT;
+ contents |= CONTENTS_DETAIL;
+ contents |= CONTENTS_DUMMYFENCE;
+ contents &= ~CONTENTS_SOLID;
+ contents &= ~CONTENTS_FENCE;
+ contents |= CONTENTS_WINDOW;
+ }
+#endif
+
+ // if any side is translucent, mark the contents
+ // and change solid to window
+#ifdef SIN
+ if ( trans > 0 )
+#else
+ if ( trans & (SURF_TRANS33|SURF_TRANS66) )
+#endif
+ {
+ contents |= CONTENTS_Q2TRANSLUCENT;
+ if (contents & CONTENTS_SOLID)
+ {
+ contents &= ~CONTENTS_SOLID;
+ contents |= CONTENTS_WINDOW;
+ }
+ }
+
+ return contents;
+} //*/
+
+
+//============================================================================
+
+
+
+/*
+=================
+ParseBrush
+=================
+* /
+void ParseBrush (entity_t *mapent)
+{
+ mapbrush_t *b;
+ int i,j, k;
+ int mt;
+ side_t *side, *s2;
+ int planenum;
+ brush_texture_t td;
+#ifdef SIN
+ textureref_t newref;
+#endif
+ int planepts[3][3];
+
+ if (nummapbrushes == MAX_MAP_BRUSHES)
+ Error ("nummapbrushes == MAX_MAP_BRUSHES");
+
+ b = &mapbrushes[nummapbrushes];
+ b->original_sides = &brushsides[nummapbrushsides];
+ b->entitynum = num_entities-1;
+ b->brushnum = nummapbrushes - mapent->firstbrush;
+
+ do
+ {
+ if (!GetToken (true))
+ break;
+ if (!strcmp (token, "}") )
+ break;
+
+ if (nummapbrushsides == MAX_MAP_BRUSHSIDES)
+ Error ("MAX_MAP_BRUSHSIDES");
+ side = &brushsides[nummapbrushsides];
+
+ // read the three point plane definition
+ for (i=0 ; i<3 ; i++)
+ {
+ if (i != 0)
+ GetToken (true);
+ if (strcmp (token, "(") )
+ Error ("parsing brush");
+
+ for (j=0 ; j<3 ; j++)
+ {
+ GetToken (false);
+ planepts[i][j] = atoi(token);
+ }
+
+ GetToken (false);
+ if (strcmp (token, ")") )
+ Error ("parsing brush");
+
+ }
+
+
+ //
+ // read the texturedef
+ //
+ GetToken (false);
+ strcpy (td.name, token);
+
+ GetToken (false);
+ td.shift[0] = atoi(token);
+ GetToken (false);
+ td.shift[1] = atoi(token);
+ GetToken (false);
+#ifdef SIN
+ td.rotate = atof(token);
+#else
+ td.rotate = atoi(token);
+#endif
+ GetToken (false);
+ td.scale[0] = atof(token);
+ GetToken (false);
+ td.scale[1] = atof(token);
+
+ // find default flags and values
+ mt = FindMiptex (td.name);
+#ifdef SIN
+ // clear out the masks on newref
+ memset(&newref,0,sizeof(newref));
+ // copy over the name
+ strcpy( newref.name, td.name );
+
+ ParseSurfaceInfo( &newref );
+ MergeRefs( &bsp_textureref[mt], &newref, &td.tref );
+ side->contents = td.tref.contents;
+ side->surf = td.tref.flags;
+#else
+ td.flags = textureref[mt].flags;
+ td.value = textureref[mt].value;
+ side->contents = textureref[mt].contents;
+ side->surf = td.flags = textureref[mt].flags;
+
+ if (TokenAvailable())
+ {
+ GetToken (false);
+ side->contents = atoi(token);
+ GetToken (false);
+ side->surf = td.flags = atoi(token);
+ GetToken (false);
+ td.value = atoi(token);
+ }
+#endif
+
+ // translucent objects are automatically classified as detail
+#ifdef SIN
+ if ( td.tref.translucence > 0 )
+#else
+ if (side->surf & (SURF_TRANS33|SURF_TRANS66) )
+#endif
+ side->contents |= CONTENTS_DETAIL;
+ if (side->contents & (CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP) )
+ side->contents |= CONTENTS_DETAIL;
+ if (fulldetail)
+ side->contents &= ~CONTENTS_DETAIL;
+ if (!(side->contents & ((LAST_VISIBLE_CONTENTS-1)
+ | CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP|CONTENTS_MIST) ) )
+ side->contents |= CONTENTS_SOLID;
+
+ // hints and skips are never detail, and have no content
+ if (side->surf & (SURF_HINT|SURF_SKIP) )
+ {
+ side->contents = 0;
+#ifndef SIN // I think this is a bug of some kind
+ side->surf &= ~CONTENTS_DETAIL;
+#endif
+ }
+
+ //
+ // find the plane number
+ //
+ planenum = PlaneFromPoints (planepts[0], planepts[1], planepts[2]);
+ if (planenum == -1)
+ {
+ printf ("Entity %i, Brush %i: plane with no normal\n"
+ , b->entitynum, b->brushnum);
+ continue;
+ }
+
+ //
+ // see if the plane has been used already
+ //
+ for (k=0 ; k<b->numsides ; k++)
+ {
+ s2 = b->original_sides + k;
+ if (s2->planenum == planenum)
+ {
+ printf ("Entity %i, Brush %i: duplicate plane\n"
+ , b->entitynum, b->brushnum);
+ break;
+ }
+ if ( s2->planenum == (planenum^1) )
+ {
+ printf ("Entity %i, Brush %i: mirrored plane\n"
+ , b->entitynum, b->brushnum);
+ break;
+ }
+ }
+ if (k != b->numsides)
+ continue; // duplicated
+
+ //
+ // keep this side
+ //
+
+ side = b->original_sides + b->numsides;
+ side->planenum = planenum;
+#ifdef SIN
+ side->texinfo = TexinfoForBrushTexture (&mapplanes[planenum],
+ &td, vec3_origin, &newref);
+ //
+ // save off lightinfo
+ //
+ side->lightinfo = LightinfoForBrushTexture ( &td );
+#else
+ side->texinfo = TexinfoForBrushTexture (&mapplanes[planenum],
+ &td, vec3_origin);
+
+#endif
+
+ // save the td off in case there is an origin brush and we
+ // have to recalculate the texinfo
+ side_brushtextures[nummapbrushsides] = td;
+#ifdef SIN
+ // save off the merged tref for animating textures
+ side_newrefs[nummapbrushsides] = newref;
+#endif
+
+ nummapbrushsides++;
+ b->numsides++;
+ } while (1);
+
+ // get the content for the entire brush
+ b->contents = Sin_BrushContents (b);
+
+ // allow detail brushes to be removed
+ if (nodetail && (b->contents & CONTENTS_DETAIL) )
+ {
+ b->numsides = 0;
+ return;
+ }
+
+ // allow water brushes to be removed
+ if (nowater && (b->contents & (CONTENTS_LAVA | CONTENTS_SLIME | CONTENTS_WATER)) )
+ {
+ b->numsides = 0;
+ return;
+ }
+
+ // create windings for sides and bounds for brush
+ MakeBrushWindings (b);
+
+ // brushes that will not be visible at all will never be
+ // used as bsp splitters
+ if (b->contents & (CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP) )
+ {
+ c_clipbrushes++;
+ for (i=0 ; i<b->numsides ; i++)
+ b->original_sides[i].texinfo = TEXINFO_NODE;
+ }
+
+ //
+ // origin brushes are removed, but they set
+ // the rotation origin for the rest of the brushes
+ // in the entity. After the entire entity is parsed,
+ // the planenums and texinfos will be adjusted for
+ // the origin brush
+ //
+ if (b->contents & CONTENTS_ORIGIN)
+ {
+ char string[32];
+ vec3_t origin;
+
+ if (num_entities == 1)
+ {
+ Error ("Entity %i, Brush %i: origin brushes not allowed in world"
+ , b->entitynum, b->brushnum);
+ return;
+ }
+
+ VectorAdd (b->mins, b->maxs, origin);
+ VectorScale (origin, 0.5, origin);
+
+ sprintf (string, "%i %i %i", (int)origin[0], (int)origin[1], (int)origin[2]);
+ SetKeyValue (&entities[b->entitynum], "origin", string);
+
+ VectorCopy (origin, entities[b->entitynum].origin);
+
+ // don't keep this brush
+ b->numsides = 0;
+
+ return;
+ }
+
+ AddBrushBevels (b);
+
+ nummapbrushes++;
+ mapent->numbrushes++;
+} //*/
+
+/*
+================
+MoveBrushesToWorld
+
+Takes all of the brushes from the current entity and
+adds them to the world's brush list.
+
+Used by func_group and func_areaportal
+================
+* /
+void MoveBrushesToWorld (entity_t *mapent)
+{
+ int newbrushes;
+ int worldbrushes;
+ mapbrush_t *temp;
+ int i;
+
+ // this is pretty gross, because the brushes are expected to be
+ // in linear order for each entity
+
+ newbrushes = mapent->numbrushes;
+ worldbrushes = entities[0].numbrushes;
+
+ temp = malloc(newbrushes*sizeof(mapbrush_t));
+ memcpy (temp, mapbrushes + mapent->firstbrush, newbrushes*sizeof(mapbrush_t));
+
+#if 0 // let them keep their original brush numbers
+ for (i=0 ; i<newbrushes ; i++)
+ temp[i].entitynum = 0;
+#endif
+
+ // make space to move the brushes (overlapped copy)
+ memmove (mapbrushes + worldbrushes + newbrushes,
+ mapbrushes + worldbrushes,
+ sizeof(mapbrush_t) * (nummapbrushes - worldbrushes - newbrushes) );
+
+ // copy the new brushes down
+ memcpy (mapbrushes + worldbrushes, temp, sizeof(mapbrush_t) * newbrushes);
+
+ // fix up indexes
+ entities[0].numbrushes += newbrushes;
+ for (i=1 ; i<num_entities ; i++)
+ entities[i].firstbrush += newbrushes;
+ free (temp);
+
+ mapent->numbrushes = 0;
+} //*/
+
+/*
+================
+ParseMapEntity
+================
+* /
+qboolean Sin_ParseMapEntity (void)
+{
+ entity_t *mapent;
+ epair_t *e;
+ side_t *s;
+ int i, j;
+ int startbrush, startsides;
+ vec_t newdist;
+ mapbrush_t *b;
+
+ if (!GetToken (true))
+ return false;
+
+ if (strcmp (token, "{") )
+ Error ("ParseEntity: { not found");
+
+ if (num_entities == MAX_MAP_ENTITIES)
+ Error ("num_entities == MAX_MAP_ENTITIES");
+
+ startbrush = nummapbrushes;
+ startsides = nummapbrushsides;
+
+ mapent = &entities[num_entities];
+ num_entities++;
+ memset (mapent, 0, sizeof(*mapent));
+ mapent->firstbrush = nummapbrushes;
+ mapent->numbrushes = 0;
+// mapent->portalareas[0] = -1;
+// mapent->portalareas[1] = -1;
+
+ do
+ {
+ if (!GetToken (true))
+ Error ("ParseEntity: EOF without closing brace");
+ if (!strcmp (token, "}") )
+ break;
+ if (!strcmp (token, "{") )
+ ParseBrush (mapent);
+ else
+ {
+ e = ParseEpair ();
+#ifdef SIN
+ //HACK HACK HACK
+ // MED Gotta do this here
+ if ( !stricmp(e->key, "surfacefile") )
+ {
+ if (!surfacefile[0])
+ {
+ strcpy( surfacefile, e->value );
+ }
+ printf ("--- ParseSurfaceFile ---\n");
+ printf ("Surface script: %s\n", surfacefile);
+ if (!ParseSurfaceFile(surfacefile))
+ {
+ Error ("Script file not found: %s\n", surfacefile);
+ }
+ }
+#endif
+ e->next = mapent->epairs;
+ mapent->epairs = e;
+ }
+ } while (1);
+
+#ifdef SIN
+ if (!(strlen(ValueForKey(mapent, "origin"))) && ((num_entities-1) != 0))
+ {
+ mapbrush_t *brush;
+ vec3_t origin;
+ char string[32];
+ vec3_t mins, maxs;
+ int start, end;
+ // Calculate bounds
+
+ start = mapent->firstbrush;
+ end = start + mapent->numbrushes;
+ ClearBounds (mins, maxs);
+
+ for (j=start ; j<end ; j++)
+ {
+ brush = &mapbrushes[j];
+ if (!brush->numsides)
+ continue; // not a real brush (origin brush) - shouldn't happen
+ AddPointToBounds (brush->mins, mins, maxs);
+ AddPointToBounds (brush->maxs, mins, maxs);
+ }
+
+ // Set the origin to be the centroid of the entity.
+ VectorAdd ( mins, maxs, origin);
+ VectorScale( origin, 0.5f, origin );
+
+ sprintf (string, "%i %i %i", (int)origin[0], (int)origin[1], (int)origin[2]);
+ SetKeyValue ( mapent, "origin", string);
+// qprintf("Setting origin to %s\n",string);
+ }
+#endif
+
+ GetVectorForKey (mapent, "origin", mapent->origin);
+
+#ifdef SIN
+ if (
+ (!strcmp ("func_areaportal", ValueForKey (mapent, "classname"))) ||
+ (!strcmp ("func_group", ValueForKey (mapent, "classname"))) ||
+ (!strcmp ("detail", ValueForKey (mapent, "classname")) && !entitydetails)
+ )
+ {
+ VectorClear( mapent->origin );
+ }
+#endif
+
+ //
+ // if there was an origin brush, offset all of the planes and texinfo
+ //
+ if (mapent->origin[0] || mapent->origin[1] || mapent->origin[2])
+ {
+ for (i=0 ; i<mapent->numbrushes ; i++)
+ {
+ b = &mapbrushes[mapent->firstbrush + i];
+ for (j=0 ; j<b->numsides ; j++)
+ {
+ s = &b->original_sides[j];
+ newdist = mapplanes[s->planenum].dist -
+ DotProduct (mapplanes[s->planenum].normal, mapent->origin);
+ s->planenum = FindFloatPlane (mapplanes[s->planenum].normal, newdist);
+#ifdef SIN
+ s->texinfo = TexinfoForBrushTexture (&mapplanes[s->planenum],
+ &side_brushtextures[s-brushsides], mapent->origin, &side_newrefs[s-brushsides]);
+ //
+ // save off lightinfo
+ //
+ s->lightinfo = LightinfoForBrushTexture ( &side_brushtextures[s-brushsides] );
+#else
+ s->texinfo = TexinfoForBrushTexture (&mapplanes[s->planenum],
+ &side_brushtextures[s-brushsides], mapent->origin);
+#endif
+ }
+ MakeBrushWindings (b);
+ }
+ }
+
+ // group entities are just for editor convenience
+ // toss all brushes into the world entity
+ if (!strcmp ("func_group", ValueForKey (mapent, "classname")))
+ {
+ MoveBrushesToWorld (mapent);
+ mapent->numbrushes = 0;
+ mapent->wasdetail = true;
+ FreeValueKeys( mapent );
+ return true;
+ }
+#ifdef SIN
+ // detail entities are just for editor convenience
+ // toss all brushes into the world entity as detail brushes
+ if (!strcmp ("detail", ValueForKey (mapent, "classname")) && !entitydetails)
+ {
+ for (i=0 ; i<mapent->numbrushes ; i++)
+ {
+ int j;
+ side_t * s;
+ b = &mapbrushes[mapent->firstbrush + i];
+ if (nodetail)
+ {
+ b->numsides = 0;
+ continue;
+ }
+ if (!fulldetail)
+ {
+ // set the contents for the entire brush
+ b->contents |= CONTENTS_DETAIL;
+ // set the contents in the sides as well
+ for (j=0, s=b->original_sides ; j<b->numsides ; j++,s++)
+ {
+ s->contents |= CONTENTS_DETAIL;
+ }
+ }
+ else
+ {
+ // set the contents for the entire brush
+ b->contents |= CONTENTS_SOLID;
+ // set the contents in the sides as well
+ for (j=0, s=b->original_sides ; j<b->numsides ; j++,s++)
+ {
+ s->contents |= CONTENTS_SOLID;
+ }
+ }
+ }
+ MoveBrushesToWorld (mapent);
+ mapent->wasdetail = true;
+ FreeValueKeys( mapent );
+ // kill off the entity
+ // num_entities--;
+ return true;
+ }
+#endif
+
+ // areaportal entities move their brushes, but don't eliminate
+ // the entity
+ if (!strcmp ("func_areaportal", ValueForKey (mapent, "classname")))
+ {
+ char str[128];
+
+ if (mapent->numbrushes != 1)
+ Error ("Entity %i: func_areaportal can only be a single brush", num_entities-1);
+
+ b = &mapbrushes[nummapbrushes-1];
+ b->contents = CONTENTS_AREAPORTAL;
+ c_areaportals++;
+ mapent->areaportalnum = c_areaportals;
+ // set the portal number as "style"
+ sprintf (str, "%i", c_areaportals);
+ SetKeyValue (mapent, "style", str);
+ MoveBrushesToWorld (mapent);
+ return true;
+ }
+
+ return true;
+} //end of the function Sin_ParseMapEntity */
+
+//===================================================================
+
+/*
+================
+LoadMapFile
+================
+* /
+void Sin_LoadMapFile (char *filename)
+{
+ int i;
+#ifdef SIN
+ int num_detailsides=0;
+ int num_detailbrushes=0;
+ int num_worldsides=0;
+ int num_worldbrushes=0;
+ int j,k;
+#endif
+
+ qprintf ("--- LoadMapFile ---\n");
+
+ LoadScriptFile (filename);
+
+ nummapbrushsides = 0;
+ num_entities = 0;
+
+ while (ParseMapEntity ())
+ {
+ }
+
+ ClearBounds (map_mins, map_maxs);
+ for (i=0 ; i<entities[0].numbrushes ; i++)
+ {
+ if (mapbrushes[i].mins[0] > 4096)
+ continue; // no valid points
+ AddPointToBounds (mapbrushes[i].mins, map_mins, map_maxs);
+ AddPointToBounds (mapbrushes[i].maxs, map_mins, map_maxs);
+ }
+#ifdef SIN
+ for (j=0; j<num_entities; j++)
+ {
+ for (i=0 ; i<entities[j].numbrushes ; i++)
+ {
+ side_t * s;
+ mapbrush_t *b;
+ b = &mapbrushes[entities[j].firstbrush + i];
+ if (b->numsides && b->contents & CONTENTS_DETAIL)
+ num_detailbrushes++;
+ else if (b->numsides)
+ num_worldbrushes++;
+ for (k=0, s=b->original_sides ; k<b->numsides ; k++,s++)
+ {
+ if (s->contents & CONTENTS_DETAIL)
+ num_detailsides++;
+ else
+ num_worldsides++;
+ }
+ }
+ }
+#endif
+
+ qprintf ("%5i brushes\n", nummapbrushes);
+ qprintf ("%5i clipbrushes\n", c_clipbrushes);
+ qprintf ("%5i total sides\n", nummapbrushsides);
+ qprintf ("%5i boxbevels\n", c_boxbevels);
+ qprintf ("%5i edgebevels\n", c_edgebevels);
+ qprintf ("%5i entities\n", num_entities);
+ qprintf ("%5i planes\n", nummapplanes);
+ qprintf ("%5i areaportals\n", c_areaportals);
+ qprintf ("size: %5.0f,%5.0f,%5.0f to %5.0f,%5.0f,%5.0f\n", map_mins[0],map_mins[1],map_mins[2],
+ map_maxs[0],map_maxs[1],map_maxs[2]);
+#ifdef SIN
+ qprintf ("%5i detailbrushes\n", num_detailbrushes);
+ qprintf ("%5i worldbrushes\n", num_worldbrushes);
+ qprintf ("%5i detailsides\n", num_detailsides);
+ qprintf ("%5i worldsides\n", num_worldsides);
+#endif
+
+} //end of the function Sin_LoadMap */
+
+
+#ifdef ME //Begin MAP loading from BSP file
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Sin_CreateMapTexinfo(void)
+{
+ int i;
+ vec_t defaultvec[4] = {1, 0, 0, 0};
+
+ memcpy(map_texinfo[0].vecs[0], defaultvec, sizeof(defaultvec));
+ memcpy(map_texinfo[0].vecs[1], defaultvec, sizeof(defaultvec));
+ map_texinfo[0].flags = 0;
+ map_texinfo[0].value = 0;
+ strcpy(map_texinfo[0].texture, "generic/misc/red"); //no texture
+ map_texinfo[0].nexttexinfo = -1;
+ for (i = 1; i < sin_numtexinfo; i++)
+ {
+ memcpy(map_texinfo[i].vecs, sin_texinfo[i].vecs, sizeof(float) * 2 * 4);
+ map_texinfo[i].flags = sin_texinfo[i].flags;
+ map_texinfo[i].value = 0;
+ strcpy(map_texinfo[i].texture, sin_texinfo[i].texture);
+ map_texinfo[i].nexttexinfo = -1;
+ } //end for
+} //end of the function Sin_CreateMapTexinfo
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Sin_SetLeafBrushesModelNumbers(int leafnum, int modelnum)
+{
+ int i, brushnum;
+ sin_dleaf_t *leaf;
+
+ leaf = &sin_dleafs[leafnum];
+ for (i = 0; i < leaf->numleafbrushes; i++)
+ {
+ brushnum = sin_dleafbrushes[leaf->firstleafbrush + i];
+ brushmodelnumbers[brushnum] = modelnum;
+ dbrushleafnums[brushnum] = leafnum;
+ } //end for
+} //end of the function Sin_SetLeafBrushesModelNumbers
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Sin_InitNodeStack(void)
+{
+ nodestackptr = nodestack;
+ nodestacksize = 0;
+} //end of the function Sin_InitNodeStack
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Sin_PushNodeStack(int num)
+{
+ *nodestackptr = num;
+ nodestackptr++;
+ nodestacksize++;
+ //
+ if (nodestackptr >= &nodestack[NODESTACKSIZE])
+ {
+ Error("Sin_PushNodeStack: stack overflow\n");
+ } //end if
+} //end of the function Sin_PushNodeStack
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int Sin_PopNodeStack(void)
+{
+ //if the stack is empty
+ if (nodestackptr <= nodestack) return -1;
+ //decrease stack pointer
+ nodestackptr--;
+ nodestacksize--;
+ //return the top value from the stack
+ return *nodestackptr;
+} //end of the function Sin_PopNodeStack
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Sin_SetBrushModelNumbers(entity_t *mapent)
+{
+ int n, pn;
+ int leafnum;
+
+ //
+ Sin_InitNodeStack();
+ //head node (root) of the bsp tree
+ n = sin_dmodels[mapent->modelnum].headnode;
+ pn = 0;
+
+ do
+ {
+ //if we are in a leaf (negative node number)
+ if (n < 0)
+ {
+ //number of the leaf
+ leafnum = (-n) - 1;
+ //set the brush numbers
+ Sin_SetLeafBrushesModelNumbers(leafnum, mapent->modelnum);
+ //walk back into the tree to find a second child to continue with
+ for (pn = Sin_PopNodeStack(); pn >= 0; n = pn, pn = Sin_PopNodeStack())
+ {
+ //if we took the first child at the parent node
+ if (sin_dnodes[pn].children[0] == n) break;
+ } //end for
+ //if the stack wasn't empty (if not processed whole tree)
+ if (pn >= 0)
+ {
+ //push the parent node again
+ Sin_PushNodeStack(pn);
+ //we proceed with the second child of the parent node
+ n = sin_dnodes[pn].children[1];
+ } //end if
+ } //end if
+ else
+ {
+ //push the current node onto the stack
+ Sin_PushNodeStack(n);
+ //walk forward into the tree to the first child
+ n = sin_dnodes[n].children[0];
+ } //end else
+ } while(pn >= 0);
+} //end of the function Sin_SetBrushModelNumbers
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Sin_BSPBrushToMapBrush(sin_dbrush_t *bspbrush, entity_t *mapent)
+{
+ mapbrush_t *b;
+ int i, k, n;
+ side_t *side, *s2;
+ int planenum;
+ sin_dbrushside_t *bspbrushside;
+ sin_dplane_t *bspplane;
+
+ if (nummapbrushes >= MAX_MAPFILE_BRUSHES)
+ Error ("nummapbrushes >= MAX_MAPFILE_BRUSHES");
+
+ b = &mapbrushes[nummapbrushes];
+ b->original_sides = &brushsides[nummapbrushsides];
+ b->entitynum = mapent-entities;
+ b->brushnum = nummapbrushes - mapent->firstbrush;
+ b->leafnum = dbrushleafnums[bspbrush - sin_dbrushes];
+
+ for (n = 0; n < bspbrush->numsides; n++)
+ {
+ //pointer to the bsp brush side
+ bspbrushside = &sin_dbrushsides[bspbrush->firstside + n];
+
+ if (nummapbrushsides >= MAX_MAPFILE_BRUSHSIDES)
+ {
+ Error ("MAX_MAPFILE_BRUSHSIDES");
+ } //end if
+ //pointer to the map brush side
+ side = &brushsides[nummapbrushsides];
+ //if the BSP brush side is textured
+ if (sin_dbrushsidetextured[bspbrush->firstside + n]) side->flags |= SFL_TEXTURED;
+ else side->flags &= ~SFL_TEXTURED;
+ //ME: can get side contents and surf directly from BSP file
+ side->contents = bspbrush->contents;
+ //if the texinfo is TEXINFO_NODE
+ if (bspbrushside->texinfo < 0) side->surf = 0;
+ else side->surf = sin_texinfo[bspbrushside->texinfo].flags;
+
+ // translucent objects are automatically classified as detail
+ if (side->surf & (SURF_TRANS33|SURF_TRANS66) )
+ side->contents |= CONTENTS_DETAIL;
+ if (side->contents & (CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP) )
+ side->contents |= CONTENTS_DETAIL;
+ if (fulldetail)
+ side->contents &= ~CONTENTS_DETAIL;
+ if (!(side->contents & ((LAST_VISIBLE_CONTENTS-1)
+ | CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP|CONTENTS_MIST) ) )
+ side->contents |= CONTENTS_SOLID;
+
+ // hints and skips are never detail, and have no content
+ if (side->surf & (SURF_HINT|SURF_SKIP) )
+ {
+ side->contents = 0;
+ side->surf &= ~CONTENTS_DETAIL;
+ }
+
+ //ME: get a plane for this side
+ bspplane = &sin_dplanes[bspbrushside->planenum];
+ planenum = FindFloatPlane(bspplane->normal, bspplane->dist);
+ //
+ // see if the plane has been used already
+ //
+ //ME: this really shouldn't happen!!!
+ //ME: otherwise the bsp file is corrupted??
+ //ME: still it seems to happen, maybe Johny Boy's
+ //ME: brush bevel adding is crappy ?
+ for (k = 0; k < b->numsides; k++)
+ {
+ s2 = b->original_sides + k;
+ if (s2->planenum == planenum)
+ {
+ Log_Print("Entity %i, Brush %i: duplicate plane\n"
+ , b->entitynum, b->brushnum);
+ break;
+ }
+ if ( s2->planenum == (planenum^1) )
+ {
+ Log_Print("Entity %i, Brush %i: mirrored plane\n"
+ , b->entitynum, b->brushnum);
+ break;
+ }
+ }
+ if (k != b->numsides)
+ continue; // duplicated
+
+ //
+ // keep this side
+ //
+ //ME: reset pointer to side, why? hell I dunno (pointer is set above already)
+ side = b->original_sides + b->numsides;
+ //ME: store the plane number
+ side->planenum = planenum;
+ //ME: texinfo is already stored when bsp is loaded
+ //NOTE: check for TEXINFO_NODE, otherwise crash in Sin_BrushContents
+ if (bspbrushside->texinfo < 0) side->texinfo = 0;
+ else side->texinfo = bspbrushside->texinfo;
+
+ // save the td off in case there is an origin brush and we
+ // have to recalculate the texinfo
+ // ME: don't need to recalculate because it's already done
+ // (for non-world entities) in the BSP file
+// side_brushtextures[nummapbrushsides] = td;
+
+ nummapbrushsides++;
+ b->numsides++;
+ } //end for
+
+ // get the content for the entire brush
+ b->contents = bspbrush->contents;
+ Sin_BrushContents(b);
+
+ if (BrushExists(b))
+ {
+ c_squattbrushes++;
+ b->numsides = 0;
+ return;
+ } //end if
+
+ //if we're creating AAS
+ if (create_aas)
+ {
+ //create the AAS brushes from this brush, don't add brush bevels
+ AAS_CreateMapBrushes(b, mapent, false);
+ return;
+ } //end if
+
+ // allow detail brushes to be removed
+ if (nodetail && (b->contents & CONTENTS_DETAIL) )
+ {
+ b->numsides = 0;
+ return;
+ } //end if
+
+ // allow water brushes to be removed
+ if (nowater && (b->contents & (CONTENTS_LAVA | CONTENTS_SLIME | CONTENTS_WATER)) )
+ {
+ b->numsides = 0;
+ return;
+ } //end if
+
+ // create windings for sides and bounds for brush
+ MakeBrushWindings(b);
+
+ //mark brushes without winding or with a tiny window as bevels
+ MarkBrushBevels(b);
+
+ // brushes that will not be visible at all will never be
+ // used as bsp splitters
+ if (b->contents & (CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP) )
+ {
+ c_clipbrushes++;
+ for (i = 0; i < b->numsides; i++)
+ b->original_sides[i].texinfo = TEXINFO_NODE;
+ } //end for
+
+ //
+ // origin brushes are removed, but they set
+ // the rotation origin for the rest of the brushes
+ // in the entity. After the entire entity is parsed,
+ // the planenums and texinfos will be adjusted for
+ // the origin brush
+ //
+ //ME: not needed because the entities in the BSP file already
+ // have an origin set
+// if (b->contents & CONTENTS_ORIGIN)
+// {
+// char string[32];
+// vec3_t origin;
+//
+// if (num_entities == 1)
+// {
+// Error ("Entity %i, Brush %i: origin brushes not allowed in world"
+// , b->entitynum, b->brushnum);
+// return;
+// }
+//
+// VectorAdd (b->mins, b->maxs, origin);
+// VectorScale (origin, 0.5, origin);
+//
+// sprintf (string, "%i %i %i", (int)origin[0], (int)origin[1], (int)origin[2]);
+// SetKeyValue (&entities[b->entitynum], "origin", string);
+//
+// VectorCopy (origin, entities[b->entitynum].origin);
+//
+// // don't keep this brush
+// b->numsides = 0;
+//
+// return;
+// }
+
+ //ME: the bsp brushes already have bevels, so we won't try to
+ // add them again (especially since Johny Boy's bevel adding might
+ // be crappy)
+// AddBrushBevels(b);
+
+ nummapbrushes++;
+ mapent->numbrushes++;
+} //end of the function Sin_BSPBrushToMapBrush
+//===========================================================================
+//===========================================================================
+void Sin_ParseBSPBrushes(entity_t *mapent)
+{
+ int i, testnum = 0;
+
+ //give all the brushes that belong to this entity the number of the
+ //BSP model used by this entity
+ Sin_SetBrushModelNumbers(mapent);
+ //now parse all the brushes with the correct mapent->modelnum
+ for (i = 0; i < sin_numbrushes; i++)
+ {
+ if (brushmodelnumbers[i] == mapent->modelnum)
+ {
+ testnum++;
+ Sin_BSPBrushToMapBrush(&sin_dbrushes[i], mapent);
+ } //end if
+ } //end for
+} //end of the function Sin_ParseBSPBrushes
+//===========================================================================
+//===========================================================================
+qboolean Sin_ParseBSPEntity(int entnum)
+{
+ entity_t *mapent;
+ char *model;
+ int startbrush, startsides;
+
+ startbrush = nummapbrushes;
+ startsides = nummapbrushsides;
+
+ mapent = &entities[entnum];//num_entities];
+ mapent->firstbrush = nummapbrushes;
+ mapent->numbrushes = 0;
+ mapent->modelnum = -1; //-1 = no model
+
+ model = ValueForKey(mapent, "model");
+ if (model && *model == '*')
+ {
+ mapent->modelnum = atoi(&model[1]);
+ //Log_Print("model = %s\n", model);
+ //Log_Print("mapent->modelnum = %d\n", mapent->modelnum);
+ } //end if
+
+ GetVectorForKey(mapent, "origin", mapent->origin);
+
+ //if this is the world entity it has model number zero
+ //the world entity has no model key
+ if (!strcmp("worldspawn", ValueForKey(mapent, "classname")))
+ {
+ mapent->modelnum = 0;
+ } //end if
+ //if the map entity has a BSP model (a modelnum of -1 is used for
+ //entities that aren't using a BSP model)
+ if (mapent->modelnum >= 0)
+ {
+ //parse the bsp brushes
+ Sin_ParseBSPBrushes(mapent);
+ } //end if
+ //
+ //the origin of the entity is already taken into account
+ //
+ //func_group entities can't be in the bsp file
+ //
+ //check out the func_areaportal entities
+ if (!strcmp ("func_areaportal", ValueForKey (mapent, "classname")))
+ {
+ c_areaportals++;
+ mapent->areaportalnum = c_areaportals;
+ return true;
+ } //end if
+ return true;
+} //end of the function Sin_ParseBSPEntity
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Sin_LoadMapFromBSP(char *filename, int offset, int length)
+{
+ int i;
+
+ Log_Print("-- Sin_LoadMapFromBSP --\n");
+ //loaded map type
+ loadedmaptype = MAPTYPE_SIN;
+
+ Log_Print("Loading map from %s...\n", filename);
+ //load the bsp file
+ Sin_LoadBSPFile(filename, offset, length);
+
+ //create an index from bsp planes to map planes
+ //DPlanes2MapPlanes();
+ //clear brush model numbers
+ for (i = 0; i < MAX_MAPFILE_BRUSHES; i++)
+ brushmodelnumbers[i] = -1;
+
+ nummapbrushsides = 0;
+ num_entities = 0;
+
+ Sin_ParseEntities();
+ //
+ for (i = 0; i < num_entities; i++)
+ {
+ Sin_ParseBSPEntity(i);
+ } //end for
+
+ //get the map mins and maxs from the world model
+ ClearBounds(map_mins, map_maxs);
+ for (i = 0; i < entities[0].numbrushes; i++)
+ {
+ if (mapbrushes[i].mins[0] > 4096)
+ continue; //no valid points
+ AddPointToBounds (mapbrushes[i].mins, map_mins, map_maxs);
+ AddPointToBounds (mapbrushes[i].maxs, map_mins, map_maxs);
+ } //end for
+ //
+ Sin_CreateMapTexinfo();
+} //end of the function Sin_LoadMapFromBSP
+
+void Sin_ResetMapLoading(void)
+{
+ //reset for map loading from bsp
+ memset(nodestack, 0, NODESTACKSIZE * sizeof(int));
+ nodestackptr = NULL;
+ nodestacksize = 0;
+ memset(brushmodelnumbers, 0, MAX_MAPFILE_BRUSHES * sizeof(int));
+} //end of the function Sin_ResetMapLoading
+
+//End MAP loading from BSP file
+
+#endif //ME
diff --git a/code/bspc/nodraw.c b/code/bspc/nodraw.c
new file mode 100755
index 0000000..b5442dc
--- /dev/null
+++ b/code/bspc/nodraw.c
@@ -0,0 +1,47 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+
+vec3_t draw_mins, draw_maxs;
+qboolean drawflag;
+
+void Draw_ClearWindow (void)
+{
+}
+
+//============================================================
+
+#define GLSERV_PORT 25001
+
+
+void GLS_BeginScene (void)
+{
+}
+
+void GLS_Winding (winding_t *w, int code)
+{
+}
+
+void GLS_EndScene (void)
+{
+}
diff --git a/code/bspc/portals.c b/code/bspc/portals.c
new file mode 100755
index 0000000..3d3389d
--- /dev/null
+++ b/code/bspc/portals.c
@@ -0,0 +1,1297 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+#include "l_mem.h"
+
+int c_active_portals;
+int c_peak_portals;
+int c_boundary;
+int c_boundary_sides;
+int c_portalmemory;
+
+//portal_t *portallist = NULL;
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+portal_t *AllocPortal (void)
+{
+ portal_t *p;
+
+ p = GetMemory(sizeof(portal_t));
+ memset (p, 0, sizeof(portal_t));
+
+ if (numthreads == 1)
+ {
+ c_active_portals++;
+ if (c_active_portals > c_peak_portals)
+ {
+ c_peak_portals = c_active_portals;
+ } //end if
+ c_portalmemory += MemorySize(p);
+ } //end if
+
+// p->nextportal = portallist;
+// portallist = p;
+
+ return p;
+} //end of the function AllocPortal
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void FreePortal (portal_t *p)
+{
+ if (p->winding) FreeWinding(p->winding);
+ if (numthreads == 1)
+ {
+ c_active_portals--;
+ c_portalmemory -= MemorySize(p);
+ } //end if
+ FreeMemory(p);
+} //end of the function FreePortal
+//===========================================================================
+// Returns the single content bit of the
+// strongest visible content present
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int VisibleContents (int contents)
+{
+ int i;
+
+ for (i=1 ; i<=LAST_VISIBLE_CONTENTS ; i<<=1)
+ if (contents & i )
+ return i;
+
+ return 0;
+} //end of the function VisibleContents
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int ClusterContents (node_t *node)
+{
+ int c1, c2, c;
+
+ if (node->planenum == PLANENUM_LEAF)
+ return node->contents;
+
+ c1 = ClusterContents(node->children[0]);
+ c2 = ClusterContents(node->children[1]);
+ c = c1|c2;
+
+ // a cluster may include some solid detail areas, but
+ // still be seen into
+ if ( ! (c1&CONTENTS_SOLID) || ! (c2&CONTENTS_SOLID) )
+ c &= ~CONTENTS_SOLID;
+ return c;
+} //end of the function ClusterContents
+
+//===========================================================================
+// Returns true if the portal is empty or translucent, allowing
+// the PVS calculation to see through it.
+// The nodes on either side of the portal may actually be clusters,
+// not leaves, so all contents should be ored together
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean Portal_VisFlood (portal_t *p)
+{
+ int c1, c2;
+
+ if (!p->onnode)
+ return false; // to global outsideleaf
+
+ c1 = ClusterContents(p->nodes[0]);
+ c2 = ClusterContents(p->nodes[1]);
+
+ if (!VisibleContents (c1^c2))
+ return true;
+
+ if (c1 & (CONTENTS_Q2TRANSLUCENT|CONTENTS_DETAIL))
+ c1 = 0;
+ if (c2 & (CONTENTS_Q2TRANSLUCENT|CONTENTS_DETAIL))
+ c2 = 0;
+
+ if ( (c1|c2) & CONTENTS_SOLID )
+ return false; // can't see through solid
+
+ if (! (c1 ^ c2))
+ return true; // identical on both sides
+
+ if (!VisibleContents (c1^c2))
+ return true;
+ return false;
+} //end of the function Portal_VisFlood
+//===========================================================================
+// The entity flood determines which areas are
+// "outside" on the map, which are then filled in.
+// Flowing from side s to side !s
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean Portal_EntityFlood (portal_t *p, int s)
+{
+ if (p->nodes[0]->planenum != PLANENUM_LEAF
+ || p->nodes[1]->planenum != PLANENUM_LEAF)
+ Error ("Portal_EntityFlood: not a leaf");
+
+ // can never cross to a solid
+ if ( (p->nodes[0]->contents & CONTENTS_SOLID)
+ || (p->nodes[1]->contents & CONTENTS_SOLID) )
+ return false;
+
+ // can flood through everything else
+ return true;
+}
+
+
+//=============================================================================
+
+int c_tinyportals;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void AddPortalToNodes (portal_t *p, node_t *front, node_t *back)
+{
+ if (p->nodes[0] || p->nodes[1])
+ Error ("AddPortalToNode: allready included");
+
+ p->nodes[0] = front;
+ p->next[0] = front->portals;
+ front->portals = p;
+
+ p->nodes[1] = back;
+ p->next[1] = back->portals;
+ back->portals = p;
+} //end of the function AddPortalToNodes
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void RemovePortalFromNode (portal_t *portal, node_t *l)
+{
+ portal_t **pp, *t;
+
+ int s, i, n;
+ portal_t *p;
+ portal_t *portals[4096];
+
+// remove reference to the current portal
+ pp = &l->portals;
+ while (1)
+ {
+ t = *pp;
+ if (!t)
+ Error ("RemovePortalFromNode: portal not in leaf");
+
+ if ( t == portal )
+ break;
+
+ if (t->nodes[0] == l)
+ pp = &t->next[0];
+ else if (t->nodes[1] == l)
+ pp = &t->next[1];
+ else
+ Error ("RemovePortalFromNode: portal not bounding leaf");
+ }
+
+ if (portal->nodes[0] == l)
+ {
+ *pp = portal->next[0];
+ portal->nodes[0] = NULL;
+ } //end if
+ else if (portal->nodes[1] == l)
+ {
+ *pp = portal->next[1];
+ portal->nodes[1] = NULL;
+ } //end else if
+ else
+ {
+ Error("RemovePortalFromNode: mislinked portal");
+ } //end else
+//#ifdef ME
+ n = 0;
+ for (p = l->portals; p; p = p->next[s])
+ {
+ for (i = 0; i < n; i++)
+ {
+ if (p == portals[i]) Error("RemovePortalFromNode: circular linked\n");
+ } //end for
+ if (p->nodes[0] != l && p->nodes[1] != l)
+ {
+ Error("RemovePortalFromNodes: portal does not belong to node\n");
+ } //end if
+ portals[n] = p;
+ s = (p->nodes[1] == l);
+// if (++n >= 4096) Error("RemovePortalFromNode: more than 4096 portals\n");
+ } //end for
+//#endif
+} //end of the function RemovePortalFromNode
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void PrintPortal (portal_t *p)
+{
+ int i;
+ winding_t *w;
+
+ w = p->winding;
+ for (i=0 ; i<w->numpoints ; i++)
+ printf ("(%5.0f,%5.0f,%5.0f)\n",w->p[i][0]
+ , w->p[i][1], w->p[i][2]);
+} //end of the function PrintPortal
+//===========================================================================
+// The created portals will face the global outside_node
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+#define SIDESPACE 8
+
+void MakeHeadnodePortals (tree_t *tree)
+{
+ vec3_t bounds[2];
+ int i, j, n;
+ portal_t *p, *portals[6];
+ plane_t bplanes[6], *pl;
+ node_t *node;
+
+ node = tree->headnode;
+
+// pad with some space so there will never be null volume leaves
+ for (i=0 ; i<3 ; i++)
+ {
+ bounds[0][i] = tree->mins[i] - SIDESPACE;
+ bounds[1][i] = tree->maxs[i] + SIDESPACE;
+ if ( bounds[0][i] > bounds[1][i] ) {
+ Error("empty BSP tree");
+ }
+ }
+
+ tree->outside_node.planenum = PLANENUM_LEAF;
+ tree->outside_node.brushlist = NULL;
+ tree->outside_node.portals = NULL;
+ tree->outside_node.contents = 0;
+
+ for (i=0 ; i<3 ; i++)
+ for (j=0 ; j<2 ; j++)
+ {
+ n = j*3 + i;
+
+ p = AllocPortal ();
+ portals[n] = p;
+
+ pl = &bplanes[n];
+ memset (pl, 0, sizeof(*pl));
+ if (j)
+ {
+ pl->normal[i] = -1;
+ pl->dist = -bounds[j][i];
+ }
+ else
+ {
+ pl->normal[i] = 1;
+ pl->dist = bounds[j][i];
+ }
+ p->plane = *pl;
+ p->winding = BaseWindingForPlane (pl->normal, pl->dist);
+ AddPortalToNodes (p, node, &tree->outside_node);
+ }
+
+// clip the basewindings by all the other planes
+ for (i=0 ; i<6 ; i++)
+ {
+ for (j=0 ; j<6 ; j++)
+ {
+ if (j == i) continue;
+ ChopWindingInPlace (&portals[i]->winding, bplanes[j].normal, bplanes[j].dist, ON_EPSILON);
+ } //end for
+ } //end for
+} //end of the function MakeHeadNodePortals
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+#define BASE_WINDING_EPSILON 0.001
+#define SPLIT_WINDING_EPSILON 0.001
+
+winding_t *BaseWindingForNode (node_t *node)
+{
+ winding_t *w;
+ node_t *n;
+ plane_t *plane;
+ vec3_t normal;
+ vec_t dist;
+
+ w = BaseWindingForPlane (mapplanes[node->planenum].normal
+ , mapplanes[node->planenum].dist);
+
+ // clip by all the parents
+ for (n=node->parent ; n && w ; )
+ {
+ plane = &mapplanes[n->planenum];
+
+ if (n->children[0] == node)
+ { // take front
+ ChopWindingInPlace (&w, plane->normal, plane->dist, BASE_WINDING_EPSILON);
+ }
+ else
+ { // take back
+ VectorSubtract (vec3_origin, plane->normal, normal);
+ dist = -plane->dist;
+ ChopWindingInPlace (&w, normal, dist, BASE_WINDING_EPSILON);
+ }
+ node = n;
+ n = n->parent;
+ }
+
+ return w;
+} //end of the function BaseWindingForNode
+//===========================================================================
+// create the new portal by taking the full plane winding for the cutting
+// plane and clipping it by all of parents of this node
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean WindingIsTiny (winding_t *w);
+
+void MakeNodePortal (node_t *node)
+{
+ portal_t *new_portal, *p;
+ winding_t *w;
+ vec3_t normal;
+ float dist;
+ int side;
+
+ w = BaseWindingForNode (node);
+
+ // clip the portal by all the other portals in the node
+ for (p = node->portals; p && w; p = p->next[side])
+ {
+ if (p->nodes[0] == node)
+ {
+ side = 0;
+ VectorCopy (p->plane.normal, normal);
+ dist = p->plane.dist;
+ } //end if
+ else if (p->nodes[1] == node)
+ {
+ side = 1;
+ VectorSubtract (vec3_origin, p->plane.normal, normal);
+ dist = -p->plane.dist;
+ } //end else if
+ else
+ {
+ Error ("MakeNodePortal: mislinked portal");
+ } //end else
+ ChopWindingInPlace (&w, normal, dist, 0.1);
+ } //end for
+
+ if (!w)
+ {
+ return;
+ } //end if
+
+ if (WindingIsTiny (w))
+ {
+ c_tinyportals++;
+ FreeWinding(w);
+ return;
+ } //end if
+
+#ifdef DEBUG
+/* //NOTE: don't use this winding ok check
+ // all the invalid windings only have a degenerate edge
+ if (WindingError(w))
+ {
+ Log_Print("MakeNodePortal: %s\n", WindingErrorString());
+ FreeWinding(w);
+ return;
+ } //end if*/
+#endif //DEBUG
+
+
+ new_portal = AllocPortal();
+ new_portal->plane = mapplanes[node->planenum];
+
+#ifdef ME
+ new_portal->planenum = node->planenum;
+#endif //ME
+
+ new_portal->onnode = node;
+ new_portal->winding = w;
+ AddPortalToNodes (new_portal, node->children[0], node->children[1]);
+} //end of the function MakeNodePortal
+//===========================================================================
+// Move or split the portals that bound node so that the node's
+// children have portals instead of node.
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void SplitNodePortals (node_t *node)
+{
+ portal_t *p, *next_portal, *new_portal;
+ node_t *f, *b, *other_node;
+ int side;
+ plane_t *plane;
+ winding_t *frontwinding, *backwinding;
+
+ plane = &mapplanes[node->planenum];
+ f = node->children[0];
+ b = node->children[1];
+
+ for (p = node->portals ; p ; p = next_portal)
+ {
+ if (p->nodes[0] == node) side = 0;
+ else if (p->nodes[1] == node) side = 1;
+ else Error ("SplitNodePortals: mislinked portal");
+ next_portal = p->next[side];
+
+ other_node = p->nodes[!side];
+ RemovePortalFromNode (p, p->nodes[0]);
+ RemovePortalFromNode (p, p->nodes[1]);
+
+//
+// cut the portal into two portals, one on each side of the cut plane
+//
+ ClipWindingEpsilon (p->winding, plane->normal, plane->dist,
+ SPLIT_WINDING_EPSILON, &frontwinding, &backwinding);
+
+ if (frontwinding && WindingIsTiny(frontwinding))
+ {
+ FreeWinding (frontwinding);
+ frontwinding = NULL;
+ c_tinyportals++;
+ } //end if
+
+ if (backwinding && WindingIsTiny(backwinding))
+ {
+ FreeWinding (backwinding);
+ backwinding = NULL;
+ c_tinyportals++;
+ } //end if
+
+#ifdef DEBUG
+/* //NOTE: don't use this winding ok check
+ // all the invalid windings only have a degenerate edge
+ if (frontwinding && WindingError(frontwinding))
+ {
+ Log_Print("SplitNodePortals: front %s\n", WindingErrorString());
+ FreeWinding(frontwinding);
+ frontwinding = NULL;
+ } //end if
+ if (backwinding && WindingError(backwinding))
+ {
+ Log_Print("SplitNodePortals: back %s\n", WindingErrorString());
+ FreeWinding(backwinding);
+ backwinding = NULL;
+ } //end if*/
+#endif //DEBUG
+
+ if (!frontwinding && !backwinding)
+ { // tiny windings on both sides
+ continue;
+ }
+
+ if (!frontwinding)
+ {
+ FreeWinding (backwinding);
+ if (side == 0) AddPortalToNodes (p, b, other_node);
+ else AddPortalToNodes (p, other_node, b);
+ continue;
+ }
+ if (!backwinding)
+ {
+ FreeWinding (frontwinding);
+ if (side == 0) AddPortalToNodes (p, f, other_node);
+ else AddPortalToNodes (p, other_node, f);
+ continue;
+ }
+
+ // the winding is split
+ new_portal = AllocPortal();
+ *new_portal = *p;
+ new_portal->winding = backwinding;
+ FreeWinding (p->winding);
+ p->winding = frontwinding;
+
+ if (side == 0)
+ {
+ AddPortalToNodes (p, f, other_node);
+ AddPortalToNodes (new_portal, b, other_node);
+ } //end if
+ else
+ {
+ AddPortalToNodes (p, other_node, f);
+ AddPortalToNodes (new_portal, other_node, b);
+ } //end else
+ }
+
+ node->portals = NULL;
+} //end of the function SplitNodePortals
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void CalcNodeBounds (node_t *node)
+{
+ portal_t *p;
+ int s;
+ int i;
+
+ // calc mins/maxs for both leaves and nodes
+ ClearBounds (node->mins, node->maxs);
+ for (p = node->portals ; p ; p = p->next[s])
+ {
+ s = (p->nodes[1] == node);
+ for (i=0 ; i<p->winding->numpoints ; i++)
+ AddPointToBounds (p->winding->p[i], node->mins, node->maxs);
+ }
+} //end of the function CalcNodeBounds
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int c_numportalizednodes;
+
+void MakeTreePortals_r (node_t *node)
+{
+ int i;
+
+#ifdef ME
+ qprintf("\r%6d", ++c_numportalizednodes);
+ if (cancelconversion) return;
+#endif //ME
+
+ CalcNodeBounds (node);
+ if (node->mins[0] >= node->maxs[0])
+ {
+ Log_Print("WARNING: node without a volume\n");
+ }
+
+ for (i=0 ; i<3 ; i++)
+ {
+ if (node->mins[i] < -MAX_MAP_BOUNDS || node->maxs[i] > MAX_MAP_BOUNDS)
+ {
+ Log_Print("WARNING: node with unbounded volume\n");
+ break;
+ }
+ }
+ if (node->planenum == PLANENUM_LEAF)
+ return;
+
+ MakeNodePortal (node);
+ SplitNodePortals (node);
+
+ MakeTreePortals_r (node->children[0]);
+ MakeTreePortals_r (node->children[1]);
+} //end of the function MakeTreePortals_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void MakeTreePortals(tree_t *tree)
+{
+
+#ifdef ME
+ Log_Print("---- Node Portalization ----\n");
+ c_numportalizednodes = 0;
+ c_portalmemory = 0;
+ qprintf("%6d nodes portalized", c_numportalizednodes);
+#endif //ME
+
+ MakeHeadnodePortals(tree);
+ MakeTreePortals_r(tree->headnode);
+
+#ifdef ME
+ qprintf("\n");
+ Log_Write("%6d nodes portalized\r\n", c_numportalizednodes);
+ Log_Print("%6d tiny portals\r\n", c_tinyportals);
+ Log_Print("%6d KB of portal memory\r\n", c_portalmemory >> 10);
+ Log_Print("%6i KB of winding memory\r\n", WindingMemory() >> 10);
+#endif //ME
+} //end of the function MakeTreePortals
+
+/*
+=========================================================
+
+FLOOD ENTITIES
+
+=========================================================
+*/
+//#define P_NODESTACK
+
+node_t *p_firstnode;
+node_t *p_lastnode;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+#ifdef P_NODESTACK
+void P_AddNodeToList(node_t *node)
+{
+ node->next = p_firstnode;
+ p_firstnode = node;
+ if (!p_lastnode) p_lastnode = node;
+} //end of the function P_AddNodeToList
+#else //it's a node queue
+//add the node to the end of the node list
+void P_AddNodeToList(node_t *node)
+{
+ node->next = NULL;
+ if (p_lastnode) p_lastnode->next = node;
+ else p_firstnode = node;
+ p_lastnode = node;
+} //end of the function P_AddNodeToList
+#endif //P_NODESTACK
+//===========================================================================
+// get the first node from the front of the node list
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+node_t *P_NextNodeFromList(void)
+{
+ node_t *node;
+
+ node = p_firstnode;
+ if (p_firstnode) p_firstnode = p_firstnode->next;
+ if (!p_firstnode) p_lastnode = NULL;
+ return node;
+} //end of the function P_NextNodeFromList
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void FloodPortals(node_t *firstnode)
+{
+ node_t *node;
+ portal_t *p;
+ int s;
+
+ firstnode->occupied = 1;
+ P_AddNodeToList(firstnode);
+
+ for (node = P_NextNodeFromList(); node; node = P_NextNodeFromList())
+ {
+ for (p = node->portals; p; p = p->next[s])
+ {
+ s = (p->nodes[1] == node);
+ //if the node at the other side of the portal is occupied already
+ if (p->nodes[!s]->occupied) continue;
+ //if it isn't possible to flood through this portal
+ if (!Portal_EntityFlood(p, s)) continue;
+ //
+ p->nodes[!s]->occupied = node->occupied + 1;
+ //
+ P_AddNodeToList(p->nodes[!s]);
+ } //end for
+ } //end for
+} //end of the function FloodPortals
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int numrec;
+
+void FloodPortals_r (node_t *node, int dist)
+{
+ portal_t *p;
+ int s;
+// int i;
+
+ Log_Print("\r%6d", ++numrec);
+
+ if (node->occupied) Error("FloodPortals_r: node already occupied\n");
+ if (!node)
+ {
+ Error("FloodPortals_r: NULL node\n");
+ } //end if*/
+ node->occupied = dist;
+
+ for (p = node->portals; p; p = p->next[s])
+ {
+ s = (p->nodes[1] == node);
+ //if the node at the other side of the portal is occupied already
+ if (p->nodes[!s]->occupied) continue;
+ //if it isn't possible to flood through this portal
+ if (!Portal_EntityFlood(p, s)) continue;
+ //flood recursively through the current portal
+ FloodPortals_r(p->nodes[!s], dist+1);
+ } //end for
+ Log_Print("\r%6d", --numrec);
+} //end of the function FloodPortals_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean PlaceOccupant (node_t *headnode, vec3_t origin, entity_t *occupant)
+{
+ node_t *node;
+ vec_t d;
+ plane_t *plane;
+
+ //find the leaf to start in
+ node = headnode;
+ while(node->planenum != PLANENUM_LEAF)
+ {
+ if (node->planenum < 0 || node->planenum > nummapplanes)
+ {
+ Error("PlaceOccupant: invalid node->planenum\n");
+ } //end if
+ plane = &mapplanes[node->planenum];
+ d = DotProduct(origin, plane->normal) - plane->dist;
+ if (d >= 0) node = node->children[0];
+ else node = node->children[1];
+ if (!node)
+ {
+ Error("PlaceOccupant: invalid child %d\n", d < 0);
+ } //end if
+ } //end while
+ //don't start in solid
+// if (node->contents == CONTENTS_SOLID)
+ //ME: replaced because in LeafNode in brushbsp.c
+ // some nodes have contents solid with other contents
+ if (node->contents & CONTENTS_SOLID) return false;
+ //if the node is already occupied
+ if (node->occupied) return false;
+
+ //place the occupant in the first leaf
+ node->occupant = occupant;
+
+ numrec = 0;
+// Log_Print("%6d recurses", numrec);
+// FloodPortals_r(node, 1);
+// Log_Print("\n");
+ FloodPortals(node);
+
+ return true;
+} //end of the function PlaceOccupant
+//===========================================================================
+// Marks all nodes that can be reached by entites
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean FloodEntities (tree_t *tree)
+{
+ int i;
+ int x, y;
+ vec3_t origin;
+ char *cl;
+ qboolean inside;
+ node_t *headnode;
+
+ headnode = tree->headnode;
+ Log_Print("------ FloodEntities -------\n");
+ inside = false;
+ tree->outside_node.occupied = 0;
+
+ //start at entity 1 not the world ( = 0)
+ for (i = 1; i < num_entities; i++)
+ {
+ GetVectorForKey(&entities[i], "origin", origin);
+ if (VectorCompare(origin, vec3_origin)) continue;
+
+ cl = ValueForKey(&entities[i], "classname");
+ origin[2] += 1; //so objects on floor are ok
+
+// Log_Print("flooding from entity %d: %s\n", i, cl);
+ //nudge playerstart around if needed so clipping hulls allways
+ //have a valid point
+ if (!strcmp(cl, "info_player_start"))
+ {
+ for (x = -16; x <= 16; x += 16)
+ {
+ for (y = -16; y <= 16; y += 16)
+ {
+ origin[0] += x;
+ origin[1] += y;
+ if (PlaceOccupant(headnode, origin, &entities[i]))
+ {
+ inside = true;
+ x = 999; //stop for this info_player_start
+ break;
+ } //end if
+ origin[0] -= x;
+ origin[1] -= y;
+ } //end for
+ } //end for
+ } //end if
+ else
+ {
+ if (PlaceOccupant(headnode, origin, &entities[i]))
+ {
+ inside = true;
+ } //end if
+ } //end else
+ } //end for
+
+ if (!inside)
+ {
+ Log_Print("WARNING: no entities inside\n");
+ } //end if
+ else if (tree->outside_node.occupied)
+ {
+ Log_Print("WARNING: entity reached from outside\n");
+ } //end else if
+
+ return (qboolean)(inside && !tree->outside_node.occupied);
+} //end of the function FloodEntities
+
+/*
+=========================================================
+
+FILL OUTSIDE
+
+=========================================================
+*/
+
+int c_outside;
+int c_inside;
+int c_solid;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void FillOutside_r (node_t *node)
+{
+ if (node->planenum != PLANENUM_LEAF)
+ {
+ FillOutside_r (node->children[0]);
+ FillOutside_r (node->children[1]);
+ return;
+ } //end if
+ // anything not reachable by an entity
+ // can be filled away (by setting solid contents)
+ if (!node->occupied)
+ {
+ if (!(node->contents & CONTENTS_SOLID))
+ {
+ c_outside++;
+ node->contents |= CONTENTS_SOLID;
+ } //end if
+ else
+ {
+ c_solid++;
+ } //end else
+ } //end if
+ else
+ {
+ c_inside++;
+ } //end else
+} //end of the function FillOutside_r
+//===========================================================================
+// Fill all nodes that can't be reached by entities
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void FillOutside (node_t *headnode)
+{
+ c_outside = 0;
+ c_inside = 0;
+ c_solid = 0;
+ Log_Print("------- FillOutside --------\n");
+ FillOutside_r (headnode);
+ Log_Print("%5i solid leaves\n", c_solid);
+ Log_Print("%5i leaves filled\n", c_outside);
+ Log_Print("%5i inside leaves\n", c_inside);
+} //end of the function FillOutside
+
+/*
+=========================================================
+
+FLOOD AREAS
+
+=========================================================
+*/
+
+int c_areas;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void FloodAreas_r (node_t *node)
+{
+ portal_t *p;
+ int s;
+ bspbrush_t *b;
+ entity_t *e;
+
+ if (node->contents == CONTENTS_AREAPORTAL)
+ {
+ // this node is part of an area portal
+ b = node->brushlist;
+ e = &entities[b->original->entitynum];
+
+ // if the current area has allready touched this
+ // portal, we are done
+ if (e->portalareas[0] == c_areas || e->portalareas[1] == c_areas)
+ return;
+
+ // note the current area as bounding the portal
+ if (e->portalareas[1])
+ {
+ Log_Print("WARNING: areaportal entity %i touches > 2 areas\n", b->original->entitynum);
+ return;
+ }
+ if (e->portalareas[0])
+ e->portalareas[1] = c_areas;
+ else
+ e->portalareas[0] = c_areas;
+
+ return;
+ } //end if
+
+ if (node->area)
+ return; // allready got it
+ node->area = c_areas;
+
+ for (p=node->portals ; p ; p = p->next[s])
+ {
+ s = (p->nodes[1] == node);
+#if 0
+ if (p->nodes[!s]->occupied)
+ continue;
+#endif
+ if (!Portal_EntityFlood (p, s))
+ continue;
+
+ FloodAreas_r (p->nodes[!s]);
+ } //end for
+} //end of the function FloodAreas_r
+//===========================================================================
+// Just decend the tree, and for each node that hasn't had an
+// area set, flood fill out from there
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void FindAreas_r (node_t *node)
+{
+ if (node->planenum != PLANENUM_LEAF)
+ {
+ FindAreas_r (node->children[0]);
+ FindAreas_r (node->children[1]);
+ return;
+ }
+
+ if (node->area)
+ return; // allready got it
+
+ if (node->contents & CONTENTS_SOLID)
+ return;
+
+ if (!node->occupied)
+ return; // not reachable by entities
+
+ // area portals are allways only flooded into, never
+ // out of
+ if (node->contents == CONTENTS_AREAPORTAL)
+ return;
+
+ c_areas++;
+ FloodAreas_r (node);
+} //end of the function FindAreas_r
+//===========================================================================
+// Just decend the tree, and for each node that hasn't had an
+// area set, flood fill out from there
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void SetAreaPortalAreas_r (node_t *node)
+{
+ bspbrush_t *b;
+ entity_t *e;
+
+ if (node->planenum != PLANENUM_LEAF)
+ {
+ SetAreaPortalAreas_r (node->children[0]);
+ SetAreaPortalAreas_r (node->children[1]);
+ return;
+ } //end if
+
+ if (node->contents == CONTENTS_AREAPORTAL)
+ {
+ if (node->area)
+ return; // allready set
+
+ b = node->brushlist;
+ e = &entities[b->original->entitynum];
+ node->area = e->portalareas[0];
+ if (!e->portalareas[1])
+ {
+ Log_Print("WARNING: areaportal entity %i doesn't touch two areas\n", b->original->entitynum);
+ return;
+ } //end if
+ } //end if
+} //end of the function SetAreaPortalAreas_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+/*
+void EmitAreaPortals(node_t *headnode)
+{
+ int i, j;
+ entity_t *e;
+ dareaportal_t *dp;
+
+ if (c_areas > MAX_MAP_AREAS)
+ Error ("MAX_MAP_AREAS");
+ numareas = c_areas+1;
+ numareaportals = 1; // leave 0 as an error
+
+ for (i=1 ; i<=c_areas ; i++)
+ {
+ dareas[i].firstareaportal = numareaportals;
+ for (j=0 ; j<num_entities ; j++)
+ {
+ e = &entities[j];
+ if (!e->areaportalnum)
+ continue;
+ dp = &dareaportals[numareaportals];
+ if (e->portalareas[0] == i)
+ {
+ dp->portalnum = e->areaportalnum;
+ dp->otherarea = e->portalareas[1];
+ numareaportals++;
+ } //end if
+ else if (e->portalareas[1] == i)
+ {
+ dp->portalnum = e->areaportalnum;
+ dp->otherarea = e->portalareas[0];
+ numareaportals++;
+ } //end else if
+ } //end for
+ dareas[i].numareaportals = numareaportals - dareas[i].firstareaportal;
+ } //end for
+
+ Log_Print("%5i numareas\n", numareas);
+ Log_Print("%5i numareaportals\n", numareaportals);
+} //end of the function EmitAreaPortals
+*/
+//===========================================================================
+// Mark each leaf with an area, bounded by CONTENTS_AREAPORTAL
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void FloodAreas (tree_t *tree)
+{
+ Log_Print("--- FloodAreas ---\n");
+ FindAreas_r (tree->headnode);
+ SetAreaPortalAreas_r (tree->headnode);
+ Log_Print("%5i areas\n", c_areas);
+} //end of the function FloodAreas
+//===========================================================================
+// Finds a brush side to use for texturing the given portal
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void FindPortalSide (portal_t *p)
+{
+ int viscontents;
+ bspbrush_t *bb;
+ mapbrush_t *brush;
+ node_t *n;
+ int i,j;
+ int planenum;
+ side_t *side, *bestside;
+ float dot, bestdot;
+ plane_t *p1, *p2;
+
+ // decide which content change is strongest
+ // solid > lava > water, etc
+ viscontents = VisibleContents (p->nodes[0]->contents ^ p->nodes[1]->contents);
+ if (!viscontents)
+ return;
+
+ planenum = p->onnode->planenum;
+ bestside = NULL;
+ bestdot = 0;
+
+ for (j=0 ; j<2 ; j++)
+ {
+ n = p->nodes[j];
+ p1 = &mapplanes[p->onnode->planenum];
+ for (bb=n->brushlist ; bb ; bb=bb->next)
+ {
+ brush = bb->original;
+ if ( !(brush->contents & viscontents) )
+ continue;
+ for (i=0 ; i<brush->numsides ; i++)
+ {
+ side = &brush->original_sides[i];
+ if (side->flags & SFL_BEVEL)
+ continue;
+ if (side->texinfo == TEXINFO_NODE)
+ continue; // non-visible
+ if ((side->planenum&~1) == planenum)
+ { // exact match
+ bestside = &brush->original_sides[i];
+ goto gotit;
+ } //end if
+ // see how close the match is
+ p2 = &mapplanes[side->planenum&~1];
+ dot = DotProduct (p1->normal, p2->normal);
+ if (dot > bestdot)
+ {
+ bestdot = dot;
+ bestside = side;
+ } //end if
+ } //end for
+ } //end for
+ } //end for
+
+gotit:
+ if (!bestside)
+ Log_Print("WARNING: side not found for portal\n");
+
+ p->sidefound = true;
+ p->side = bestside;
+} //end of the function FindPortalSide
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void MarkVisibleSides_r (node_t *node)
+{
+ portal_t *p;
+ int s;
+
+ if (node->planenum != PLANENUM_LEAF)
+ {
+ MarkVisibleSides_r (node->children[0]);
+ MarkVisibleSides_r (node->children[1]);
+ return;
+ } //end if
+
+ // empty leaves are never boundary leaves
+ if (!node->contents) return;
+
+ // see if there is a visible face
+ for (p=node->portals ; p ; p = p->next[!s])
+ {
+ s = (p->nodes[0] == node);
+ if (!p->onnode)
+ continue; // edge of world
+ if (!p->sidefound)
+ FindPortalSide (p);
+ if (p->side)
+ p->side->flags |= SFL_VISIBLE;
+ } //end for
+} //end of the function MarkVisibleSides_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void MarkVisibleSides(tree_t *tree, int startbrush, int endbrush)
+{
+ int i, j;
+ mapbrush_t *mb;
+ int numsides;
+
+ Log_Print("--- MarkVisibleSides ---\n");
+
+ // clear all the visible flags
+ for (i=startbrush ; i<endbrush ; i++)
+ {
+ mb = &mapbrushes[i];
+
+ numsides = mb->numsides;
+ for (j=0 ; j<numsides ; j++)
+ mb->original_sides[j].flags &= ~SFL_VISIBLE;
+ }
+
+ // set visible flags on the sides that are used by portals
+ MarkVisibleSides_r (tree->headnode);
+} //end of the function MarkVisibleSides
+
diff --git a/code/bspc/prtfile.c b/code/bspc/prtfile.c
new file mode 100755
index 0000000..69834aa
--- /dev/null
+++ b/code/bspc/prtfile.c
@@ -0,0 +1,287 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+
+/*
+==============================================================================
+
+PORTAL FILE GENERATION
+
+Save out name.prt for qvis to read
+==============================================================================
+*/
+
+
+#define PORTALFILE "PRT1"
+
+FILE *pf;
+int num_visclusters; // clusters the player can be in
+int num_visportals;
+
+void WriteFloat2 (FILE *f, vec_t v)
+{
+ if ( fabs(v - Q_rint(v)) < 0.001 )
+ fprintf (f,"%i ",(int)Q_rint(v));
+ else
+ fprintf (f,"%f ",v);
+}
+
+/*
+=================
+WritePortalFile_r
+=================
+*/
+void WritePortalFile_r (node_t *node)
+{
+ int i, s;
+ portal_t *p;
+ winding_t *w;
+ vec3_t normal;
+ vec_t dist;
+
+ // decision node
+ if (node->planenum != PLANENUM_LEAF && !node->detail_seperator)
+ {
+ WritePortalFile_r (node->children[0]);
+ WritePortalFile_r (node->children[1]);
+ return;
+ }
+
+ if (node->contents & CONTENTS_SOLID)
+ return;
+
+ for (p = node->portals ; p ; p=p->next[s])
+ {
+ w = p->winding;
+ s = (p->nodes[1] == node);
+ if (w && p->nodes[0] == node)
+ {
+ if (!Portal_VisFlood (p))
+ continue;
+ // write out to the file
+
+ // sometimes planes get turned around when they are very near
+ // the changeover point between different axis. interpret the
+ // plane the same way vis will, and flip the side orders if needed
+ // FIXME: is this still relevent?
+ WindingPlane (w, normal, &dist);
+ if ( DotProduct (p->plane.normal, normal) < 0.99 )
+ { // backwards...
+ fprintf (pf,"%i %i %i ",w->numpoints, p->nodes[1]->cluster, p->nodes[0]->cluster);
+ }
+ else
+ fprintf (pf,"%i %i %i ",w->numpoints, p->nodes[0]->cluster, p->nodes[1]->cluster);
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ fprintf (pf,"(");
+ WriteFloat2 (pf, w->p[i][0]);
+ WriteFloat2 (pf, w->p[i][1]);
+ WriteFloat2 (pf, w->p[i][2]);
+ fprintf (pf,") ");
+ }
+ fprintf (pf,"\n");
+ }
+ }
+
+}
+
+/*
+================
+FillLeafNumbers_r
+
+All of the leafs under node will have the same cluster
+================
+*/
+void FillLeafNumbers_r (node_t *node, int num)
+{
+ if (node->planenum == PLANENUM_LEAF)
+ {
+ if (node->contents & CONTENTS_SOLID)
+ node->cluster = -1;
+ else
+ node->cluster = num;
+ return;
+ }
+ node->cluster = num;
+ FillLeafNumbers_r (node->children[0], num);
+ FillLeafNumbers_r (node->children[1], num);
+}
+
+/*
+================
+NumberLeafs_r
+================
+*/
+void NumberLeafs_r (node_t *node)
+{
+ portal_t *p;
+
+ if (node->planenum != PLANENUM_LEAF && !node->detail_seperator)
+ { // decision node
+ node->cluster = -99;
+ NumberLeafs_r (node->children[0]);
+ NumberLeafs_r (node->children[1]);
+ return;
+ }
+
+ // either a leaf or a detail cluster
+
+ if ( node->contents & CONTENTS_SOLID )
+ { // solid block, viewpoint never inside
+ node->cluster = -1;
+ return;
+ }
+
+ FillLeafNumbers_r (node, num_visclusters);
+ num_visclusters++;
+
+ // count the portals
+ for (p = node->portals ; p ; )
+ {
+ if (p->nodes[0] == node) // only write out from first leaf
+ {
+ if (Portal_VisFlood (p))
+ num_visportals++;
+ p = p->next[0];
+ }
+ else
+ p = p->next[1];
+ }
+
+}
+
+
+/*
+================
+CreateVisPortals_r
+================
+*/
+void CreateVisPortals_r (node_t *node)
+{
+ // stop as soon as we get to a detail_seperator, which
+ // means that everything below is in a single cluster
+ if (node->planenum == PLANENUM_LEAF || node->detail_seperator )
+ return;
+
+ MakeNodePortal (node);
+ SplitNodePortals (node);
+
+ CreateVisPortals_r (node->children[0]);
+ CreateVisPortals_r (node->children[1]);
+}
+
+/*
+================
+FinishVisPortals_r
+================
+*/
+void FinishVisPortals2_r (node_t *node)
+{
+ if (node->planenum == PLANENUM_LEAF)
+ return;
+
+ MakeNodePortal (node);
+ SplitNodePortals (node);
+
+ FinishVisPortals2_r (node->children[0]);
+ FinishVisPortals2_r (node->children[1]);
+}
+
+void FinishVisPortals_r (node_t *node)
+{
+ if (node->planenum == PLANENUM_LEAF)
+ return;
+
+ if (node->detail_seperator)
+ {
+ FinishVisPortals2_r (node);
+ return;
+ }
+
+ FinishVisPortals_r (node->children[0]);
+ FinishVisPortals_r (node->children[1]);
+}
+
+
+int clusterleaf;
+void SaveClusters_r (node_t *node)
+{
+ if (node->planenum == PLANENUM_LEAF)
+ {
+ dleafs[clusterleaf++].cluster = node->cluster;
+ return;
+ }
+ SaveClusters_r (node->children[0]);
+ SaveClusters_r (node->children[1]);
+}
+
+/*
+================
+WritePortalFile
+================
+*/
+void WritePortalFile (tree_t *tree)
+{
+ char filename[1024];
+ node_t *headnode;
+
+ qprintf ("--- WritePortalFile ---\n");
+
+ headnode = tree->headnode;
+ num_visclusters = 0;
+ num_visportals = 0;
+
+ Tree_FreePortals_r (headnode);
+
+ MakeHeadnodePortals (tree);
+
+ CreateVisPortals_r (headnode);
+
+// set the cluster field in every leaf and count the total number of portals
+
+ NumberLeafs_r (headnode);
+
+// write the file
+ sprintf (filename, "%s.prt", source);
+ printf ("writing %s\n", filename);
+ pf = fopen (filename, "w");
+ if (!pf)
+ Error ("Error opening %s", filename);
+
+ fprintf (pf, "%s\n", PORTALFILE);
+ fprintf (pf, "%i\n", num_visclusters);
+ fprintf (pf, "%i\n", num_visportals);
+
+ qprintf ("%5i visclusters\n", num_visclusters);
+ qprintf ("%5i visportals\n", num_visportals);
+
+ WritePortalFile_r (headnode);
+
+ fclose (pf);
+
+ // we need to store the clusters out now because ordering
+ // issues made us do this after writebsp...
+ clusterleaf = 1;
+ SaveClusters_r (headnode);
+}
+
diff --git a/code/bspc/q2files.h b/code/bspc/q2files.h
new file mode 100755
index 0000000..5ffea6e
--- /dev/null
+++ b/code/bspc/q2files.h
@@ -0,0 +1,487 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+//
+// qfiles.h: quake file formats
+// This file must be identical in the quake and utils directories
+//
+
+/*
+========================================================================
+
+The .pak files are just a linear collapse of a directory tree
+
+========================================================================
+*/
+
+#define IDPAKHEADER (('K'<<24)+('C'<<16)+('A'<<8)+'P')
+
+typedef struct
+{
+ char name[56];
+ int filepos, filelen;
+} dpackfile_t;
+
+typedef struct
+{
+ int ident; // == IDPAKHEADER
+ int dirofs;
+ int dirlen;
+} dpackheader_t;
+
+#define MAX_FILES_IN_PACK 4096
+
+
+/*
+========================================================================
+
+PCX files are used for as many images as possible
+
+========================================================================
+*/
+
+typedef struct
+{
+ char manufacturer;
+ char version;
+ char encoding;
+ char bits_per_pixel;
+ unsigned short xmin,ymin,xmax,ymax;
+ unsigned short hres,vres;
+ unsigned char palette[48];
+ char reserved;
+ char color_planes;
+ unsigned short bytes_per_line;
+ unsigned short palette_type;
+ char filler[58];
+ unsigned char data; // unbounded
+} pcx_t;
+
+
+/*
+========================================================================
+
+.MD2 triangle model file format
+
+========================================================================
+*/
+
+#define IDALIASHEADER (('2'<<24)+('P'<<16)+('D'<<8)+'I')
+#define ALIAS_VERSION 8
+
+#define MAX_TRIANGLES 4096
+#define MAX_VERTS 2048
+#define MAX_FRAMES 512
+#define MAX_MD2SKINS 32
+#define MAX_SKINNAME 64
+
+typedef struct
+{
+ short s;
+ short t;
+} dstvert_t;
+
+typedef struct
+{
+ short index_xyz[3];
+ short index_st[3];
+} dtriangle_t;
+
+typedef struct
+{
+ byte v[3]; // scaled byte to fit in frame mins/maxs
+ byte lightnormalindex;
+} dtrivertx_t;
+
+#define DTRIVERTX_V0 0
+#define DTRIVERTX_V1 1
+#define DTRIVERTX_V2 2
+#define DTRIVERTX_LNI 3
+#define DTRIVERTX_SIZE 4
+
+typedef struct
+{
+ float scale[3]; // multiply byte verts by this
+ float translate[3]; // then add this
+ char name[16]; // frame name from grabbing
+ dtrivertx_t verts[1]; // variable sized
+} daliasframe_t;
+
+
+// the glcmd format:
+// a positive integer starts a tristrip command, followed by that many
+// vertex structures.
+// a negative integer starts a trifan command, followed by -x vertexes
+// a zero indicates the end of the command list.
+// a vertex consists of a floating point s, a floating point t,
+// and an integer vertex index.
+
+
+typedef struct
+{
+ int ident;
+ int version;
+
+ int skinwidth;
+ int skinheight;
+ int framesize; // byte size of each frame
+
+ int num_skins;
+ int num_xyz;
+ int num_st; // greater than num_xyz for seams
+ int num_tris;
+ int num_glcmds; // dwords in strip/fan command list
+ int num_frames;
+
+ int ofs_skins; // each skin is a MAX_SKINNAME string
+ int ofs_st; // byte offset from start for stverts
+ int ofs_tris; // offset for dtriangles
+ int ofs_frames; // offset for first frame
+ int ofs_glcmds;
+ int ofs_end; // end of file
+
+} dmdl_t;
+
+/*
+========================================================================
+
+.SP2 sprite file format
+
+========================================================================
+*/
+
+#define IDSPRITEHEADER (('2'<<24)+('S'<<16)+('D'<<8)+'I')
+ // little-endian "IDS2"
+#define SPRITE_VERSION 2
+
+typedef struct
+{
+ int width, height;
+ int origin_x, origin_y; // raster coordinates inside pic
+ char name[MAX_SKINNAME]; // name of pcx file
+} dsprframe_t;
+
+typedef struct {
+ int ident;
+ int version;
+ int numframes;
+ dsprframe_t frames[1]; // variable sized
+} dsprite_t;
+
+/*
+==============================================================================
+
+ .WAL texture file format
+
+==============================================================================
+*/
+
+
+#define MIPLEVELS 4
+typedef struct miptex_s
+{
+ char name[32];
+ unsigned width, height;
+ unsigned offsets[MIPLEVELS]; // four mip maps stored
+ char animname[32]; // next frame in animation chain
+ int flags;
+ int contents;
+ int value;
+} miptex_t;
+
+
+
+/*
+==============================================================================
+
+ .BSP file format
+
+==============================================================================
+*/
+
+#define IDBSPHEADER (('P'<<24)+('S'<<16)+('B'<<8)+'I')
+ // little-endian "IBSP"
+
+#define BSPVERSION 38
+
+
+// upper design bounds
+// leaffaces, leafbrushes, planes, and verts are still bounded by
+// 16 bit short limits
+#define MAX_MAP_MODELS 1024
+#define MAX_MAP_BRUSHES 8192
+#define MAX_MAP_ENTITIES 2048
+#define MAX_MAP_ENTSTRING 0x40000
+#define MAX_MAP_TEXINFO 8192
+
+#define MAX_MAP_AREAS 256
+#define MAX_MAP_AREAPORTALS 1024
+#define MAX_MAP_PLANES 65536
+#define MAX_MAP_NODES 65536
+#define MAX_MAP_BRUSHSIDES 65536
+#define MAX_MAP_LEAFS 65536
+#define MAX_MAP_VERTS 65536
+#define MAX_MAP_FACES 65536
+#define MAX_MAP_LEAFFACES 65536
+#define MAX_MAP_LEAFBRUSHES 65536
+#define MAX_MAP_PORTALS 65536
+#define MAX_MAP_EDGES 128000
+#define MAX_MAP_SURFEDGES 256000
+#define MAX_MAP_LIGHTING 0x320000
+#define MAX_MAP_VISIBILITY 0x280000
+
+// key / value pair sizes
+
+#define MAX_KEY 32
+#define MAX_VALUE 1024
+
+//=============================================================================
+
+typedef struct
+{
+ int fileofs, filelen;
+} lump_t;
+
+#define LUMP_ENTITIES 0
+#define LUMP_PLANES 1
+#define LUMP_VERTEXES 2
+#define LUMP_VISIBILITY 3
+#define LUMP_NODES 4
+#define LUMP_TEXINFO 5
+#define LUMP_FACES 6
+#define LUMP_LIGHTING 7
+#define LUMP_LEAFS 8
+#define LUMP_LEAFFACES 9
+#define LUMP_LEAFBRUSHES 10
+#define LUMP_EDGES 11
+#define LUMP_SURFEDGES 12
+#define LUMP_MODELS 13
+#define LUMP_BRUSHES 14
+#define LUMP_BRUSHSIDES 15
+#define LUMP_POP 16
+#define LUMP_AREAS 17
+#define LUMP_AREAPORTALS 18
+#define HEADER_LUMPS 19
+
+typedef struct
+{
+ int ident;
+ int version;
+ lump_t lumps[HEADER_LUMPS];
+} dheader_t;
+
+typedef struct
+{
+ float mins[3], maxs[3];
+ float origin[3]; // for sounds or lights
+ int headnode;
+ int firstface, numfaces; // submodels just draw faces
+ // without walking the bsp tree
+} dmodel_t;
+
+
+typedef struct
+{
+ float point[3];
+} dvertex_t;
+
+
+// 0-2 are axial planes
+#define PLANE_X 0
+#define PLANE_Y 1
+#define PLANE_Z 2
+
+// 3-5 are non-axial planes snapped to the nearest
+#define PLANE_ANYX 3
+#define PLANE_ANYY 4
+#define PLANE_ANYZ 5
+
+// planes (x&~1) and (x&~1)+1 are allways opposites
+
+typedef struct
+{
+ float normal[3];
+ float dist;
+ int type; // PLANE_X - PLANE_ANYZ ?remove? trivial to regenerate
+} dplane_t;
+
+
+// contents flags are seperate bits
+// a given brush can contribute multiple content bits
+// multiple brushes can be in a single leaf
+
+// these definitions also need to be in q_shared.h!
+
+// lower bits are stronger, and will eat weaker brushes completely
+#define CONTENTS_SOLID 1 // an eye is never valid in a solid
+#define CONTENTS_WINDOW 2 // translucent, but not watery
+#define CONTENTS_AUX 4
+#define CONTENTS_LAVA 8
+#define CONTENTS_SLIME 16
+#define CONTENTS_WATER 32
+#define CONTENTS_MIST 64
+#define LAST_VISIBLE_CONTENTS 64
+
+// remaining contents are non-visible, and don't eat brushes
+
+#define CONTENTS_AREAPORTAL 0x8000
+
+#define CONTENTS_PLAYERCLIP 0x10000
+#define CONTENTS_MONSTERCLIP 0x20000
+
+// currents can be added to any other contents, and may be mixed
+#define CONTENTS_CURRENT_0 0x40000
+#define CONTENTS_CURRENT_90 0x80000
+#define CONTENTS_CURRENT_180 0x100000
+#define CONTENTS_CURRENT_270 0x200000
+#define CONTENTS_CURRENT_UP 0x400000
+#define CONTENTS_CURRENT_DOWN 0x800000
+
+#define CONTENTS_ORIGIN 0x1000000 // removed before bsping an entity
+
+#define CONTENTS_MONSTER 0x2000000 // should never be on a brush, only in game
+#define CONTENTS_DEADMONSTER 0x4000000
+#define CONTENTS_DETAIL 0x8000000 // brushes to be added after vis leafs
+//renamed because it's in conflict with the Q3A translucent contents
+#define CONTENTS_Q2TRANSLUCENT 0x10000000 // auto set if any surface has trans
+#define CONTENTS_LADDER 0x20000000
+
+
+
+#define SURF_LIGHT 0x1 // value will hold the light strength
+
+#define SURF_SLICK 0x2 // effects game physics
+
+#define SURF_SKY 0x4 // don't draw, but add to skybox
+#define SURF_WARP 0x8 // turbulent water warp
+#define SURF_TRANS33 0x10
+#define SURF_TRANS66 0x20
+#define SURF_FLOWING 0x40 // scroll towards angle
+#define SURF_NODRAW 0x80 // don't bother referencing the texture
+
+#define SURF_HINT 0x100 // make a primary bsp splitter
+#define SURF_SKIP 0x200 // completely ignore, allowing non-closed brushes
+
+
+
+typedef struct
+{
+ int planenum;
+ int children[2]; // negative numbers are -(leafs+1), not nodes
+ short mins[3]; // for frustom culling
+ short maxs[3];
+ unsigned short firstface;
+ unsigned short numfaces; // counting both sides
+} dnode_t;
+
+
+typedef struct texinfo_s
+{
+ float vecs[2][4]; // [s/t][xyz offset]
+ int flags; // miptex flags + overrides
+ int value; // light emission, etc
+ char texture[32]; // texture name (textures/*.wal)
+ int nexttexinfo; // for animations, -1 = end of chain
+} texinfo_t;
+
+
+// note that edge 0 is never used, because negative edge nums are used for
+// counterclockwise use of the edge in a face
+typedef struct
+{
+ unsigned short v[2]; // vertex numbers
+} dedge_t;
+
+#define MAXLIGHTMAPS 4
+typedef struct
+{
+ unsigned short planenum;
+ short side;
+
+ int firstedge; // we must support > 64k edges
+ short numedges;
+ short texinfo;
+
+// lighting info
+ byte styles[MAXLIGHTMAPS];
+ int lightofs; // start of [numstyles*surfsize] samples
+} dface_t;
+
+typedef struct
+{
+ int contents; // OR of all brushes (not needed?)
+
+ short cluster;
+ short area;
+
+ short mins[3]; // for frustum culling
+ short maxs[3];
+
+ unsigned short firstleafface;
+ unsigned short numleaffaces;
+
+ unsigned short firstleafbrush;
+ unsigned short numleafbrushes;
+} dleaf_t;
+
+typedef struct
+{
+ unsigned short planenum; // facing out of the leaf
+ short texinfo;
+} dbrushside_t;
+
+typedef struct
+{
+ int firstside;
+ int numsides;
+ int contents;
+} dbrush_t;
+
+#define ANGLE_UP -1
+#define ANGLE_DOWN -2
+
+
+// the visibility lump consists of a header with a count, then
+// byte offsets for the PVS and PHS of each cluster, then the raw
+// compressed bit vectors
+#define DVIS_PVS 0
+#define DVIS_PHS 1
+typedef struct
+{
+ int numclusters;
+ int bitofs[8][2]; // bitofs[numclusters][2]
+} dvis_t;
+
+// each area has a list of portals that lead into other areas
+// when portals are closed, other areas may not be visible or
+// hearable even if the vis info says that it should be
+typedef struct
+{
+ int portalnum;
+ int otherarea;
+} dareaportal_t;
+
+typedef struct
+{
+ int numareaportals;
+ int firstareaportal;
+} darea_t;
diff --git a/code/bspc/q3files.h b/code/bspc/q3files.h
new file mode 100755
index 0000000..b251cc0
--- /dev/null
+++ b/code/bspc/q3files.h
@@ -0,0 +1,374 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __QFILES_H__
+#define __QFILES_H__
+
+//
+// qfiles.h: quake file formats
+// This file must be identical in the quake and utils directories
+//
+
+// surface geometry should not exceed these limits
+#define SHADER_MAX_VERTEXES 1000
+#define SHADER_MAX_INDEXES (6*SHADER_MAX_VERTEXES)
+
+
+// the maximum size of game reletive pathnames
+#define MAX_QPATH 64
+
+
+/*
+========================================================================
+
+PCX files are used for 8 bit images
+
+========================================================================
+*
+
+typedef struct {
+ char manufacturer;
+ char version;
+ char encoding;
+ char bits_per_pixel;
+ unsigned short xmin,ymin,xmax,ymax;
+ unsigned short hres,vres;
+ unsigned char palette[48];
+ char reserved;
+ char color_planes;
+ unsigned short bytes_per_line;
+ unsigned short palette_type;
+ char filler[58];
+ unsigned char data; // unbounded
+} pcx_t;
+
+
+/*
+========================================================================
+
+TGA files are used for 24/32 bit images
+
+========================================================================
+*
+
+typedef struct _TargaHeader {
+ unsigned char id_length, colormap_type, image_type;
+ unsigned short colormap_index, colormap_length;
+ unsigned char colormap_size;
+ unsigned short x_origin, y_origin, width, height;
+ unsigned char pixel_size, attributes;
+} TargaHeader;
+
+
+*/
+
+/*
+========================================================================
+
+.MD3 triangle model file format
+
+========================================================================
+*/
+
+#define MD3_IDENT (('3'<<24)+('P'<<16)+('D'<<8)+'I')
+#define MD3_VERSION 15
+
+// limits
+#define MD3_MAX_LODS 4
+#define MD3_MAX_TRIANGLES 8192 // per surface
+#define MD3_MAX_VERTS 4096 // per surface
+#define MD3_MAX_SHADERS 256 // per surface
+#define MD3_MAX_FRAMES 1024 // per model
+#define MD3_MAX_SURFACES 32 // per model
+#define MD3_MAX_TAGS 16 // per frame
+
+// vertex scales
+#define MD3_XYZ_SCALE (1.0/64)
+
+typedef struct md3Frame_s {
+ vec3_t bounds[2];
+ vec3_t localOrigin;
+ float radius;
+ char name[16];
+} md3Frame_t;
+
+typedef struct md3Tag_s {
+ char name[MAX_QPATH]; // tag name
+ vec3_t origin;
+ vec3_t axis[3];
+} md3Tag_t;
+
+/*
+** md3Surface_t
+**
+** CHUNK SIZE
+** header sizeof( md3Surface_t )
+** shaders sizeof( md3Shader_t ) * numShaders
+** triangles[0] sizeof( md3Triangle_t ) * numTriangles
+** st sizeof( md3St_t ) * numVerts
+** XyzNormals sizeof( md3XyzNormal_t ) * numVerts * numFrames
+*/
+
+typedef struct {
+ int ident; //
+
+ char name[MAX_QPATH]; // polyset name
+
+ int flags;
+ int numFrames; // all surfaces in a model should have the same
+
+ int numShaders; // all surfaces in a model should have the same
+ int numVerts;
+
+ int numTriangles;
+ int ofsTriangles;
+
+ int ofsShaders; // offset from start of md3Surface_t
+ int ofsSt; // texture coords are common for all frames
+ int ofsXyzNormals; // numVerts * numFrames
+
+ int ofsEnd; // next surface follows
+} md3Surface_t;
+
+typedef struct {
+ char name[MAX_QPATH];
+ int shaderIndex; // for in-game use
+} md3Shader_t;
+
+typedef struct {
+ int indexes[3];
+} md3Triangle_t;
+
+typedef struct {
+ float st[2];
+} md3St_t;
+
+typedef struct {
+ short xyz[3];
+ short normal;
+} md3XyzNormal_t;
+
+typedef struct {
+ int ident;
+ int version;
+
+ char name[MAX_QPATH]; // model name
+
+ int flags;
+
+ int numFrames;
+ int numTags;
+ int numSurfaces;
+
+ int numSkins;
+
+ int ofsFrames; // offset for first frame
+ int ofsTags; // numFrames * numTags
+ int ofsSurfaces; // first surface, others follow
+
+ int ofsEnd; // end of file
+} md3Header_t;
+
+
+
+/*
+==============================================================================
+
+ .BSP file format
+
+==============================================================================
+*/
+
+
+#define Q3_BSP_IDENT (('P'<<24)+('S'<<16)+('B'<<8)+'I')
+ // little-endian "IBSP"
+
+#define Q3_BSP_VERSION 46
+
+
+// there shouldn't be any problem with increasing these values at the
+// expense of more memory allocation in the utilities
+#define Q3_MAX_MAP_MODELS 0x400
+#define Q3_MAX_MAP_BRUSHES 0x8000
+#define Q3_MAX_MAP_ENTITIES 0x800
+#define Q3_MAX_MAP_ENTSTRING 0x10000
+#define Q3_MAX_MAP_SHADERS 0x400
+
+#define Q3_MAX_MAP_AREAS 0x100 // MAX_MAP_AREA_BYTES in q_shared must match!
+#define Q3_MAX_MAP_FOGS 0x100
+#define Q3_MAX_MAP_PLANES 0x10000
+#define Q3_MAX_MAP_NODES 0x10000
+#define Q3_MAX_MAP_BRUSHSIDES 0x10000
+#define Q3_MAX_MAP_LEAFS 0x10000
+#define Q3_MAX_MAP_LEAFFACES 0x10000
+#define Q3_MAX_MAP_LEAFBRUSHES 0x10000
+#define Q3_MAX_MAP_PORTALS 0x10000
+#define Q3_MAX_MAP_LIGHTING 0x400000
+#define Q3_MAX_MAP_LIGHTGRID 0x400000
+#define Q3_MAX_MAP_VISIBILITY 0x200000
+
+#define Q3_MAX_MAP_DRAW_SURFS 0x20000
+#define Q3_MAX_MAP_DRAW_VERTS 0x80000
+#define Q3_MAX_MAP_DRAW_INDEXES 0x80000
+
+
+// key / value pair sizes in the entities lump
+#define Q3_MAX_KEY 32
+#define Q3_MAX_VALUE 1024
+
+// the editor uses these predefined yaw angles to orient entities up or down
+#define ANGLE_UP -1
+#define ANGLE_DOWN -2
+
+#define LIGHTMAP_WIDTH 128
+#define LIGHTMAP_HEIGHT 128
+
+
+//=============================================================================
+
+
+typedef struct {
+ int fileofs, filelen;
+} q3_lump_t;
+
+#define Q3_LUMP_ENTITIES 0
+#define Q3_LUMP_SHADERS 1
+#define Q3_LUMP_PLANES 2
+#define Q3_LUMP_NODES 3
+#define Q3_LUMP_LEAFS 4
+#define Q3_LUMP_LEAFSURFACES 5
+#define Q3_LUMP_LEAFBRUSHES 6
+#define Q3_LUMP_MODELS 7
+#define Q3_LUMP_BRUSHES 8
+#define Q3_LUMP_BRUSHSIDES 9
+#define Q3_LUMP_DRAWVERTS 10
+#define Q3_LUMP_DRAWINDEXES 11
+#define Q3_LUMP_FOGS 12
+#define Q3_LUMP_SURFACES 13
+#define Q3_LUMP_LIGHTMAPS 14
+#define Q3_LUMP_LIGHTGRID 15
+#define Q3_LUMP_VISIBILITY 16
+#define Q3_HEADER_LUMPS 17
+
+typedef struct {
+ int ident;
+ int version;
+
+ q3_lump_t lumps[Q3_HEADER_LUMPS];
+} q3_dheader_t;
+
+typedef struct {
+ float mins[3], maxs[3];
+ int firstSurface, numSurfaces;
+ int firstBrush, numBrushes;
+} q3_dmodel_t;
+
+typedef struct {
+ char shader[MAX_QPATH];
+ int surfaceFlags;
+ int contentFlags;
+} q3_dshader_t;
+
+// planes (x&~1) and (x&~1)+1 are allways opposites
+
+typedef struct {
+ float normal[3];
+ float dist;
+} q3_dplane_t;
+
+typedef struct {
+ int planeNum;
+ int children[2]; // negative numbers are -(leafs+1), not nodes
+ int mins[3]; // for frustom culling
+ int maxs[3];
+} q3_dnode_t;
+
+typedef struct {
+ int cluster; // -1 = opaque cluster (do I still store these?)
+ int area;
+
+ int mins[3]; // for frustum culling
+ int maxs[3];
+
+ int firstLeafSurface;
+ int numLeafSurfaces;
+
+ int firstLeafBrush;
+ int numLeafBrushes;
+} q3_dleaf_t;
+
+typedef struct {
+ int planeNum; // positive plane side faces out of the leaf
+ int shaderNum;
+} q3_dbrushside_t;
+
+typedef struct {
+ int firstSide;
+ int numSides;
+ int shaderNum; // the shader that determines the contents flags
+} q3_dbrush_t;
+
+typedef struct {
+ char shader[MAX_QPATH];
+ int brushNum;
+ int visibleSide; // the brush side that ray tests need to clip against (-1 == none)
+} q3_dfog_t;
+
+typedef struct {
+ vec3_t xyz;
+ float st[2];
+ float lightmap[2];
+ vec3_t normal;
+ byte color[4];
+} q3_drawVert_t;
+
+typedef enum {
+ MST_BAD,
+ MST_PLANAR,
+ MST_PATCH,
+ MST_TRIANGLE_SOUP,
+ MST_FLARE
+} q3_mapSurfaceType_t;
+
+typedef struct {
+ int shaderNum;
+ int fogNum;
+ int surfaceType;
+
+ int firstVert;
+ int numVerts;
+
+ int firstIndex;
+ int numIndexes;
+
+ int lightmapNum;
+ int lightmapX, lightmapY;
+ int lightmapWidth, lightmapHeight;
+
+ vec3_t lightmapOrigin;
+ vec3_t lightmapVecs[3]; // for patches, [0] and [1] are lodbounds
+
+ int patchWidth;
+ int patchHeight;
+} q3_dsurface_t;
+
+
+#endif
diff --git a/code/bspc/qbsp.h b/code/bspc/qbsp.h
new file mode 100755
index 0000000..7ebf9d4
--- /dev/null
+++ b/code/bspc/qbsp.h
@@ -0,0 +1,477 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+
+#if defined(WIN32) || defined(_WIN32)
+#include <io.h>
+#endif
+#include <malloc.h>
+#include "l_cmd.h"
+#include "l_math.h"
+#include "l_poly.h"
+#include "l_threads.h"
+#include "../botlib/l_script.h"
+#include "l_bsp_ent.h"
+#include "q2files.h"
+#include "l_mem.h"
+#include "l_utils.h"
+#include "l_log.h"
+#include "l_qfiles.h"
+
+#define BSPC_VERSION "2.1h"
+
+#define ME
+#define DEBUG
+#define NODELIST
+#define SIN
+
+#define MAX_BRUSH_SIDES 128 //maximum number of sides per brush
+#define CLIP_EPSILON 0.1
+#define MAX_MAP_BOUNDS 65535
+#define BOGUS_RANGE (MAX_MAP_BOUNDS+128) //somewhere outside the map
+#define TEXINFO_NODE -1 //side is allready on a node
+#define PLANENUM_LEAF -1 //used for leaf nodes
+#define MAXEDGES 20 //maximum number of face edges
+#define MAX_NODE_BRUSHES 8 //maximum brushes in a node
+//side flags
+#define SFL_TESTED 1
+#define SFL_VISIBLE 2
+#define SFL_BEVEL 4
+#define SFL_TEXTURED 8
+#define SFL_CURVE 16
+
+//map plane
+typedef struct plane_s
+{
+ vec3_t normal;
+ vec_t dist;
+ int type;
+ int signbits;
+ struct plane_s *hash_chain;
+} plane_t;
+//brush texture
+typedef struct
+{
+ vec_t shift[2];
+ vec_t rotate;
+ vec_t scale[2];
+ char name[32];
+ int flags;
+ int value;
+} brush_texture_t;
+//brush side
+typedef struct side_s
+{
+ int planenum; // map plane this side is in
+ int texinfo; // texture reference
+ winding_t *winding; // winding of this side
+ struct side_s *original; // bspbrush_t sides will reference the mapbrush_t sides
+ int lightinfo; // for SIN only
+ int contents; // from miptex
+ int surf; // from miptex
+ unsigned short flags; // side flags
+} side_t; //sizeof(side_t) = 36
+//map brush
+typedef struct mapbrush_s
+{
+ int entitynum;
+ int brushnum;
+
+ int contents;
+#ifdef ME
+ int expansionbbox; //bbox used for expansion of the brush
+ int leafnum;
+ int modelnum;
+#endif
+
+ vec3_t mins, maxs;
+
+ int numsides;
+ side_t *original_sides;
+} mapbrush_t;
+//bsp face
+typedef struct face_s
+{
+ struct face_s *next; // on node
+
+ // the chain of faces off of a node can be merged or split,
+ // but each face_t along the way will remain in the chain
+ // until the entire tree is freed
+ struct face_s *merged; // if set, this face isn't valid anymore
+ struct face_s *split[2]; // if set, this face isn't valid anymore
+
+ struct portal_s *portal;
+ int texinfo;
+#ifdef SIN
+ int lightinfo;
+#endif
+ int planenum;
+ int contents; // faces in different contents can't merge
+ int outputnumber;
+ winding_t *w;
+ int numpoints;
+ qboolean badstartvert; // tjunctions cannot be fixed without a midpoint vertex
+ int vertexnums[MAXEDGES];
+} face_t;
+//bsp brush
+typedef struct bspbrush_s
+{
+ struct bspbrush_s *next;
+ vec3_t mins, maxs;
+ int side, testside; // side of node during construction
+ mapbrush_t *original;
+ int numsides;
+ side_t sides[6]; // variably sized
+} bspbrush_t; //sizeof(bspbrush_t) = 44 + numsides * sizeof(side_t)
+//bsp node
+typedef struct node_s
+{
+ //both leafs and nodes
+ int planenum; // -1 = leaf node
+ struct node_s *parent;
+ vec3_t mins, maxs; // valid after portalization
+ bspbrush_t *volume; // one for each leaf/node
+
+ // nodes only
+ qboolean detail_seperator; // a detail brush caused the split
+ side_t *side; // the side that created the node
+ struct node_s *children[2];
+ face_t *faces;
+
+ // leafs only
+ bspbrush_t *brushlist; // fragments of all brushes in this leaf
+ int contents; // OR of all brush contents
+ int occupied; // 1 or greater can reach entity
+ entity_t *occupant; // for leak file testing
+ int cluster; // for portalfile writing
+ int area; // for areaportals
+ struct portal_s *portals; // also on nodes during construction
+#ifdef NODELIST
+ struct node_s *next; //next node in the nodelist
+#endif
+#ifdef ME
+ int expansionbboxes; //OR of all bboxes used for expansion of the brushes
+ int modelnum;
+#endif
+} node_t; //sizeof(node_t) = 80 bytes
+//bsp portal
+typedef struct portal_s
+{
+ plane_t plane;
+ node_t *onnode; // NULL = outside box
+ node_t *nodes[2]; // [0] = front side of plane
+ struct portal_s *next[2];
+ winding_t *winding;
+
+ qboolean sidefound; // false if ->side hasn't been checked
+ side_t *side; // NULL = non-visible
+ face_t *face[2]; // output face in bsp file
+#ifdef ME
+ struct tmp_face_s *tmpface; //pointer to the tmpface created for this portal
+ int planenum; //number of the map plane used by the portal
+#endif
+} portal_t;
+//bsp tree
+typedef struct
+{
+ node_t *headnode;
+ node_t outside_node;
+ vec3_t mins, maxs;
+} tree_t;
+
+//=============================================================================
+// bspc.c
+//=============================================================================
+
+extern qboolean noprune;
+extern qboolean nodetail;
+extern qboolean fulldetail;
+extern qboolean nomerge;
+extern qboolean nosubdiv;
+extern qboolean nowater;
+extern qboolean noweld;
+extern qboolean noshare;
+extern qboolean notjunc;
+extern qboolean onlyents;
+#ifdef ME
+extern qboolean nocsg;
+extern qboolean create_aas;
+extern qboolean freetree;
+extern qboolean lessbrushes;
+extern qboolean nobrushmerge;
+extern qboolean cancelconversion;
+extern qboolean noliquids;
+extern qboolean capsule_collision;
+#endif //ME
+
+extern float subdivide_size;
+extern vec_t microvolume;
+
+extern char outbase[32];
+extern char source[1024];
+
+//=============================================================================
+// map.c
+//=============================================================================
+
+#define MAX_MAPFILE_PLANES 256000
+#define MAX_MAPFILE_BRUSHES 65535
+#define MAX_MAPFILE_BRUSHSIDES (MAX_MAPFILE_BRUSHES*8)
+#define MAX_MAPFILE_TEXINFO 8192
+
+extern int entity_num;
+
+extern plane_t mapplanes[MAX_MAPFILE_PLANES];
+extern int nummapplanes;
+extern int mapplaneusers[MAX_MAPFILE_PLANES];
+
+extern int nummapbrushes;
+extern mapbrush_t mapbrushes[MAX_MAPFILE_BRUSHES];
+
+extern vec3_t map_mins, map_maxs;
+
+extern int nummapbrushsides;
+extern side_t brushsides[MAX_MAPFILE_BRUSHSIDES];
+extern brush_texture_t side_brushtextures[MAX_MAPFILE_BRUSHSIDES];
+
+#ifdef ME
+
+typedef struct
+{
+ float vecs[2][4]; // [s/t][xyz offset]
+ int flags; // miptex flags + overrides
+ int value;
+ char texture[64]; // texture name (textures/*.wal)
+ int nexttexinfo; // for animations, -1 = end of chain
+} map_texinfo_t;
+
+extern map_texinfo_t map_texinfo[MAX_MAPFILE_TEXINFO];
+extern int map_numtexinfo;
+#define NODESTACKSIZE 1024
+
+#define MAPTYPE_QUAKE1 1
+#define MAPTYPE_QUAKE2 2
+#define MAPTYPE_QUAKE3 3
+#define MAPTYPE_HALFLIFE 4
+#define MAPTYPE_SIN 5
+
+extern int nodestack[NODESTACKSIZE];
+extern int *nodestackptr;
+extern int nodestacksize;
+extern int brushmodelnumbers[MAX_MAPFILE_BRUSHES];
+extern int dbrushleafnums[MAX_MAPFILE_BRUSHES];
+extern int dplanes2mapplanes[MAX_MAPFILE_PLANES];
+
+extern int loadedmaptype;
+#endif //ME
+
+extern int c_boxbevels;
+extern int c_edgebevels;
+extern int c_areaportals;
+extern int c_clipbrushes;
+extern int c_squattbrushes;
+
+//finds a float plane for the given normal and distance
+int FindFloatPlane(vec3_t normal, vec_t dist);
+//returns the plane type for the given normal
+int PlaneTypeForNormal(vec3_t normal);
+//returns the plane defined by the three given points
+int PlaneFromPoints(int *p0, int *p1, int *p2);
+//add bevels to the map brush
+void AddBrushBevels(mapbrush_t *b);
+//makes brush side windings for the brush
+qboolean MakeBrushWindings(mapbrush_t *ob);
+//marks brush bevels of the brush as bevel
+void MarkBrushBevels(mapbrush_t *brush);
+//returns true if the map brush already exists
+int BrushExists(mapbrush_t *brush);
+//loads a map from a bsp file
+int LoadMapFromBSP(struct quakefile_s *qf);
+//resets map loading
+void ResetMapLoading(void);
+//print some map info
+void PrintMapInfo(void);
+//writes a map file (type depending on loaded map type)
+void WriteMapFile(char *filename);
+
+//=============================================================================
+// map_q2.c
+//=============================================================================
+
+void Q2_ResetMapLoading(void);
+//loads a Quake2 map file
+void Q2_LoadMapFile(char *filename);
+//loads a map from a Quake2 bsp file
+void Q2_LoadMapFromBSP(char *filename, int offset, int length);
+
+//=============================================================================
+// map_q1.c
+//=============================================================================
+
+void Q1_ResetMapLoading(void);
+//loads a Quake2 map file
+void Q1_LoadMapFile(char *filename);
+//loads a map from a Quake1 bsp file
+void Q1_LoadMapFromBSP(char *filename, int offset, int length);
+
+//=============================================================================
+// map_q3.c
+//=============================================================================
+void Q3_ResetMapLoading(void);
+//loads a map from a Quake3 bsp file
+void Q3_LoadMapFromBSP(struct quakefile_s *qf);
+
+//=============================================================================
+// map_sin.c
+//=============================================================================
+
+void Sin_ResetMapLoading(void);
+//loads a Sin map file
+void Sin_LoadMapFile(char *filename);
+//loads a map from a Sin bsp file
+void Sin_LoadMapFromBSP(char *filename, int offset, int length);
+
+//=============================================================================
+// map_hl.c
+//=============================================================================
+
+void HL_ResetMapLoading(void);
+//loads a Half-Life map file
+void HL_LoadMapFile(char *filename);
+//loads a map from a Half-Life bsp file
+void HL_LoadMapFromBSP(char *filename, int offset, int length);
+
+//=============================================================================
+// textures.c
+//=============================================================================
+
+typedef struct
+{
+ char name[64];
+ int flags;
+ int value;
+ int contents;
+ char animname[64];
+} textureref_t;
+
+#define MAX_MAP_TEXTURES 1024
+
+extern textureref_t textureref[MAX_MAP_TEXTURES];
+
+int FindMiptex(char *name);
+int TexinfoForBrushTexture(plane_t *plane, brush_texture_t *bt, vec3_t origin);
+void TextureAxisFromPlane(plane_t *pln, vec3_t xv, vec3_t yv);
+
+//=============================================================================
+// csg
+//=============================================================================
+
+bspbrush_t *MakeBspBrushList(int startbrush, int endbrush, vec3_t clipmins, vec3_t clipmaxs);
+bspbrush_t *ChopBrushes(bspbrush_t *head);
+bspbrush_t *InitialBrushList(bspbrush_t *list);
+bspbrush_t *OptimizedBrushList(bspbrush_t *list);
+void WriteBrushMap(char *name, bspbrush_t *list);
+void CheckBSPBrush(bspbrush_t *brush);
+void BSPBrushWindings(bspbrush_t *brush);
+bspbrush_t *TryMergeBrushes(bspbrush_t *brush1, bspbrush_t *brush2);
+tree_t *ProcessWorldBrushes(int brush_start, int brush_end);
+
+//=============================================================================
+// brushbsp
+//=============================================================================
+
+#define PSIDE_FRONT 1
+#define PSIDE_BACK 2
+#define PSIDE_BOTH (PSIDE_FRONT|PSIDE_BACK)
+#define PSIDE_FACING 4
+
+void WriteBrushList(char *name, bspbrush_t *brush, qboolean onlyvis);
+bspbrush_t *CopyBrush(bspbrush_t *brush);
+void SplitBrush(bspbrush_t *brush, int planenum, bspbrush_t **front, bspbrush_t **back);
+node_t *AllocNode(void);
+bspbrush_t *AllocBrush(int numsides);
+int CountBrushList(bspbrush_t *brushes);
+void FreeBrush(bspbrush_t *brushes);
+vec_t BrushVolume(bspbrush_t *brush);
+void BoundBrush(bspbrush_t *brush);
+void FreeBrushList(bspbrush_t *brushes);
+tree_t *BrushBSP(bspbrush_t *brushlist, vec3_t mins, vec3_t maxs);
+bspbrush_t *BrushFromBounds(vec3_t mins, vec3_t maxs);
+int BrushMostlyOnSide(bspbrush_t *brush, plane_t *plane);
+qboolean WindingIsHuge(winding_t *w);
+qboolean WindingIsTiny(winding_t *w);
+void ResetBrushBSP(void);
+
+//=============================================================================
+// portals.c
+//=============================================================================
+
+int VisibleContents (int contents);
+void MakeHeadnodePortals (tree_t *tree);
+void MakeNodePortal (node_t *node);
+void SplitNodePortals (node_t *node);
+qboolean Portal_VisFlood (portal_t *p);
+qboolean FloodEntities (tree_t *tree);
+void FillOutside (node_t *headnode);
+void FloodAreas (tree_t *tree);
+void MarkVisibleSides (tree_t *tree, int start, int end);
+void FreePortal (portal_t *p);
+void EmitAreaPortals (node_t *headnode);
+void MakeTreePortals (tree_t *tree);
+
+//=============================================================================
+// glfile.c
+//=============================================================================
+
+void OutputWinding(winding_t *w, FILE *glview);
+void WriteGLView(tree_t *tree, char *source);
+
+//=============================================================================
+// gldraw.c
+//=============================================================================
+
+extern vec3_t draw_mins, draw_maxs;
+extern qboolean drawflag;
+
+void Draw_ClearWindow (void);
+void DrawWinding (winding_t *w);
+void GLS_BeginScene (void);
+void GLS_Winding (winding_t *w, int code);
+void GLS_EndScene (void);
+
+//=============================================================================
+// leakfile.c
+//=============================================================================
+
+void LeakFile (tree_t *tree);
+
+//=============================================================================
+// tree.c
+//=============================================================================
+
+tree_t *Tree_Alloc(void);
+void Tree_Free(tree_t *tree);
+void Tree_Free_r(node_t *node);
+void Tree_Print_r(node_t *node, int depth);
+void Tree_FreePortals_r(node_t *node);
+void Tree_PruneNodes_r(node_t *node);
+void Tree_PruneNodes(node_t *node);
diff --git a/code/bspc/qfiles.h b/code/bspc/qfiles.h
new file mode 100755
index 0000000..5ffea6e
--- /dev/null
+++ b/code/bspc/qfiles.h
@@ -0,0 +1,487 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+//
+// qfiles.h: quake file formats
+// This file must be identical in the quake and utils directories
+//
+
+/*
+========================================================================
+
+The .pak files are just a linear collapse of a directory tree
+
+========================================================================
+*/
+
+#define IDPAKHEADER (('K'<<24)+('C'<<16)+('A'<<8)+'P')
+
+typedef struct
+{
+ char name[56];
+ int filepos, filelen;
+} dpackfile_t;
+
+typedef struct
+{
+ int ident; // == IDPAKHEADER
+ int dirofs;
+ int dirlen;
+} dpackheader_t;
+
+#define MAX_FILES_IN_PACK 4096
+
+
+/*
+========================================================================
+
+PCX files are used for as many images as possible
+
+========================================================================
+*/
+
+typedef struct
+{
+ char manufacturer;
+ char version;
+ char encoding;
+ char bits_per_pixel;
+ unsigned short xmin,ymin,xmax,ymax;
+ unsigned short hres,vres;
+ unsigned char palette[48];
+ char reserved;
+ char color_planes;
+ unsigned short bytes_per_line;
+ unsigned short palette_type;
+ char filler[58];
+ unsigned char data; // unbounded
+} pcx_t;
+
+
+/*
+========================================================================
+
+.MD2 triangle model file format
+
+========================================================================
+*/
+
+#define IDALIASHEADER (('2'<<24)+('P'<<16)+('D'<<8)+'I')
+#define ALIAS_VERSION 8
+
+#define MAX_TRIANGLES 4096
+#define MAX_VERTS 2048
+#define MAX_FRAMES 512
+#define MAX_MD2SKINS 32
+#define MAX_SKINNAME 64
+
+typedef struct
+{
+ short s;
+ short t;
+} dstvert_t;
+
+typedef struct
+{
+ short index_xyz[3];
+ short index_st[3];
+} dtriangle_t;
+
+typedef struct
+{
+ byte v[3]; // scaled byte to fit in frame mins/maxs
+ byte lightnormalindex;
+} dtrivertx_t;
+
+#define DTRIVERTX_V0 0
+#define DTRIVERTX_V1 1
+#define DTRIVERTX_V2 2
+#define DTRIVERTX_LNI 3
+#define DTRIVERTX_SIZE 4
+
+typedef struct
+{
+ float scale[3]; // multiply byte verts by this
+ float translate[3]; // then add this
+ char name[16]; // frame name from grabbing
+ dtrivertx_t verts[1]; // variable sized
+} daliasframe_t;
+
+
+// the glcmd format:
+// a positive integer starts a tristrip command, followed by that many
+// vertex structures.
+// a negative integer starts a trifan command, followed by -x vertexes
+// a zero indicates the end of the command list.
+// a vertex consists of a floating point s, a floating point t,
+// and an integer vertex index.
+
+
+typedef struct
+{
+ int ident;
+ int version;
+
+ int skinwidth;
+ int skinheight;
+ int framesize; // byte size of each frame
+
+ int num_skins;
+ int num_xyz;
+ int num_st; // greater than num_xyz for seams
+ int num_tris;
+ int num_glcmds; // dwords in strip/fan command list
+ int num_frames;
+
+ int ofs_skins; // each skin is a MAX_SKINNAME string
+ int ofs_st; // byte offset from start for stverts
+ int ofs_tris; // offset for dtriangles
+ int ofs_frames; // offset for first frame
+ int ofs_glcmds;
+ int ofs_end; // end of file
+
+} dmdl_t;
+
+/*
+========================================================================
+
+.SP2 sprite file format
+
+========================================================================
+*/
+
+#define IDSPRITEHEADER (('2'<<24)+('S'<<16)+('D'<<8)+'I')
+ // little-endian "IDS2"
+#define SPRITE_VERSION 2
+
+typedef struct
+{
+ int width, height;
+ int origin_x, origin_y; // raster coordinates inside pic
+ char name[MAX_SKINNAME]; // name of pcx file
+} dsprframe_t;
+
+typedef struct {
+ int ident;
+ int version;
+ int numframes;
+ dsprframe_t frames[1]; // variable sized
+} dsprite_t;
+
+/*
+==============================================================================
+
+ .WAL texture file format
+
+==============================================================================
+*/
+
+
+#define MIPLEVELS 4
+typedef struct miptex_s
+{
+ char name[32];
+ unsigned width, height;
+ unsigned offsets[MIPLEVELS]; // four mip maps stored
+ char animname[32]; // next frame in animation chain
+ int flags;
+ int contents;
+ int value;
+} miptex_t;
+
+
+
+/*
+==============================================================================
+
+ .BSP file format
+
+==============================================================================
+*/
+
+#define IDBSPHEADER (('P'<<24)+('S'<<16)+('B'<<8)+'I')
+ // little-endian "IBSP"
+
+#define BSPVERSION 38
+
+
+// upper design bounds
+// leaffaces, leafbrushes, planes, and verts are still bounded by
+// 16 bit short limits
+#define MAX_MAP_MODELS 1024
+#define MAX_MAP_BRUSHES 8192
+#define MAX_MAP_ENTITIES 2048
+#define MAX_MAP_ENTSTRING 0x40000
+#define MAX_MAP_TEXINFO 8192
+
+#define MAX_MAP_AREAS 256
+#define MAX_MAP_AREAPORTALS 1024
+#define MAX_MAP_PLANES 65536
+#define MAX_MAP_NODES 65536
+#define MAX_MAP_BRUSHSIDES 65536
+#define MAX_MAP_LEAFS 65536
+#define MAX_MAP_VERTS 65536
+#define MAX_MAP_FACES 65536
+#define MAX_MAP_LEAFFACES 65536
+#define MAX_MAP_LEAFBRUSHES 65536
+#define MAX_MAP_PORTALS 65536
+#define MAX_MAP_EDGES 128000
+#define MAX_MAP_SURFEDGES 256000
+#define MAX_MAP_LIGHTING 0x320000
+#define MAX_MAP_VISIBILITY 0x280000
+
+// key / value pair sizes
+
+#define MAX_KEY 32
+#define MAX_VALUE 1024
+
+//=============================================================================
+
+typedef struct
+{
+ int fileofs, filelen;
+} lump_t;
+
+#define LUMP_ENTITIES 0
+#define LUMP_PLANES 1
+#define LUMP_VERTEXES 2
+#define LUMP_VISIBILITY 3
+#define LUMP_NODES 4
+#define LUMP_TEXINFO 5
+#define LUMP_FACES 6
+#define LUMP_LIGHTING 7
+#define LUMP_LEAFS 8
+#define LUMP_LEAFFACES 9
+#define LUMP_LEAFBRUSHES 10
+#define LUMP_EDGES 11
+#define LUMP_SURFEDGES 12
+#define LUMP_MODELS 13
+#define LUMP_BRUSHES 14
+#define LUMP_BRUSHSIDES 15
+#define LUMP_POP 16
+#define LUMP_AREAS 17
+#define LUMP_AREAPORTALS 18
+#define HEADER_LUMPS 19
+
+typedef struct
+{
+ int ident;
+ int version;
+ lump_t lumps[HEADER_LUMPS];
+} dheader_t;
+
+typedef struct
+{
+ float mins[3], maxs[3];
+ float origin[3]; // for sounds or lights
+ int headnode;
+ int firstface, numfaces; // submodels just draw faces
+ // without walking the bsp tree
+} dmodel_t;
+
+
+typedef struct
+{
+ float point[3];
+} dvertex_t;
+
+
+// 0-2 are axial planes
+#define PLANE_X 0
+#define PLANE_Y 1
+#define PLANE_Z 2
+
+// 3-5 are non-axial planes snapped to the nearest
+#define PLANE_ANYX 3
+#define PLANE_ANYY 4
+#define PLANE_ANYZ 5
+
+// planes (x&~1) and (x&~1)+1 are allways opposites
+
+typedef struct
+{
+ float normal[3];
+ float dist;
+ int type; // PLANE_X - PLANE_ANYZ ?remove? trivial to regenerate
+} dplane_t;
+
+
+// contents flags are seperate bits
+// a given brush can contribute multiple content bits
+// multiple brushes can be in a single leaf
+
+// these definitions also need to be in q_shared.h!
+
+// lower bits are stronger, and will eat weaker brushes completely
+#define CONTENTS_SOLID 1 // an eye is never valid in a solid
+#define CONTENTS_WINDOW 2 // translucent, but not watery
+#define CONTENTS_AUX 4
+#define CONTENTS_LAVA 8
+#define CONTENTS_SLIME 16
+#define CONTENTS_WATER 32
+#define CONTENTS_MIST 64
+#define LAST_VISIBLE_CONTENTS 64
+
+// remaining contents are non-visible, and don't eat brushes
+
+#define CONTENTS_AREAPORTAL 0x8000
+
+#define CONTENTS_PLAYERCLIP 0x10000
+#define CONTENTS_MONSTERCLIP 0x20000
+
+// currents can be added to any other contents, and may be mixed
+#define CONTENTS_CURRENT_0 0x40000
+#define CONTENTS_CURRENT_90 0x80000
+#define CONTENTS_CURRENT_180 0x100000
+#define CONTENTS_CURRENT_270 0x200000
+#define CONTENTS_CURRENT_UP 0x400000
+#define CONTENTS_CURRENT_DOWN 0x800000
+
+#define CONTENTS_ORIGIN 0x1000000 // removed before bsping an entity
+
+#define CONTENTS_MONSTER 0x2000000 // should never be on a brush, only in game
+#define CONTENTS_DEADMONSTER 0x4000000
+#define CONTENTS_DETAIL 0x8000000 // brushes to be added after vis leafs
+//renamed because it's in conflict with the Q3A translucent contents
+#define CONTENTS_Q2TRANSLUCENT 0x10000000 // auto set if any surface has trans
+#define CONTENTS_LADDER 0x20000000
+
+
+
+#define SURF_LIGHT 0x1 // value will hold the light strength
+
+#define SURF_SLICK 0x2 // effects game physics
+
+#define SURF_SKY 0x4 // don't draw, but add to skybox
+#define SURF_WARP 0x8 // turbulent water warp
+#define SURF_TRANS33 0x10
+#define SURF_TRANS66 0x20
+#define SURF_FLOWING 0x40 // scroll towards angle
+#define SURF_NODRAW 0x80 // don't bother referencing the texture
+
+#define SURF_HINT 0x100 // make a primary bsp splitter
+#define SURF_SKIP 0x200 // completely ignore, allowing non-closed brushes
+
+
+
+typedef struct
+{
+ int planenum;
+ int children[2]; // negative numbers are -(leafs+1), not nodes
+ short mins[3]; // for frustom culling
+ short maxs[3];
+ unsigned short firstface;
+ unsigned short numfaces; // counting both sides
+} dnode_t;
+
+
+typedef struct texinfo_s
+{
+ float vecs[2][4]; // [s/t][xyz offset]
+ int flags; // miptex flags + overrides
+ int value; // light emission, etc
+ char texture[32]; // texture name (textures/*.wal)
+ int nexttexinfo; // for animations, -1 = end of chain
+} texinfo_t;
+
+
+// note that edge 0 is never used, because negative edge nums are used for
+// counterclockwise use of the edge in a face
+typedef struct
+{
+ unsigned short v[2]; // vertex numbers
+} dedge_t;
+
+#define MAXLIGHTMAPS 4
+typedef struct
+{
+ unsigned short planenum;
+ short side;
+
+ int firstedge; // we must support > 64k edges
+ short numedges;
+ short texinfo;
+
+// lighting info
+ byte styles[MAXLIGHTMAPS];
+ int lightofs; // start of [numstyles*surfsize] samples
+} dface_t;
+
+typedef struct
+{
+ int contents; // OR of all brushes (not needed?)
+
+ short cluster;
+ short area;
+
+ short mins[3]; // for frustum culling
+ short maxs[3];
+
+ unsigned short firstleafface;
+ unsigned short numleaffaces;
+
+ unsigned short firstleafbrush;
+ unsigned short numleafbrushes;
+} dleaf_t;
+
+typedef struct
+{
+ unsigned short planenum; // facing out of the leaf
+ short texinfo;
+} dbrushside_t;
+
+typedef struct
+{
+ int firstside;
+ int numsides;
+ int contents;
+} dbrush_t;
+
+#define ANGLE_UP -1
+#define ANGLE_DOWN -2
+
+
+// the visibility lump consists of a header with a count, then
+// byte offsets for the PVS and PHS of each cluster, then the raw
+// compressed bit vectors
+#define DVIS_PVS 0
+#define DVIS_PHS 1
+typedef struct
+{
+ int numclusters;
+ int bitofs[8][2]; // bitofs[numclusters][2]
+} dvis_t;
+
+// each area has a list of portals that lead into other areas
+// when portals are closed, other areas may not be visible or
+// hearable even if the vis info says that it should be
+typedef struct
+{
+ int portalnum;
+ int otherarea;
+} dareaportal_t;
+
+typedef struct
+{
+ int numareaportals;
+ int firstareaportal;
+} darea_t;
diff --git a/code/bspc/sinfiles.h b/code/bspc/sinfiles.h
new file mode 100755
index 0000000..31091c5
--- /dev/null
+++ b/code/bspc/sinfiles.h
@@ -0,0 +1,365 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*
+==============================================================================
+
+ .BSP file format
+
+==============================================================================
+*/
+
+#define SIN
+
+#define SINBSPVERSION 41
+
+// upper design bounds
+// leaffaces, leafbrushes, planes, and verts are still bounded by
+// 16 bit short limits
+#define SIN_MAX_MAP_MODELS 1024
+#define SIN_MAX_MAP_BRUSHES 8192
+#define SIN_MAX_MAP_ENTITIES 2048
+#define SIN_MAX_MAP_ENTSTRING 0x40000
+#define SIN_MAX_MAP_TEXINFO 8192
+
+#define SIN_MAX_MAP_AREAS 256
+#define SIN_MAX_MAP_AREAPORTALS 1024
+#define SIN_MAX_MAP_PLANES 65536
+#define SIN_MAX_MAP_NODES 65536
+#define SIN_MAX_MAP_BRUSHSIDES 65536
+#define SIN_MAX_MAP_LEAFS 65536
+#define SIN_MAX_MAP_VERTS 65536
+#define SIN_MAX_MAP_FACES 65536
+#define SIN_MAX_MAP_LEAFFACES 65536
+#define SIN_MAX_MAP_LEAFBRUSHES 65536
+#define SIN_MAX_MAP_PORTALS 65536
+#define SIN_MAX_MAP_EDGES 128000
+#define SIN_MAX_MAP_SURFEDGES 256000
+#define SIN_MAX_MAP_LIGHTING 0x320000
+#define SIN_MAX_MAP_VISIBILITY 0x280000
+
+#ifdef SIN
+#define SIN_MAX_MAP_LIGHTINFO 8192
+#endif
+
+#ifdef SIN
+#undef SIN_MAX_MAP_LIGHTING //undef the Quake2 bsp version
+#define SIN_MAX_MAP_LIGHTING 0x300000
+#endif
+
+#ifdef SIN
+#undef SIN_MAX_MAP_VISIBILITY //undef the Quake2 bsp version
+#define SIN_MAX_MAP_VISIBILITY 0x280000
+#endif
+
+//=============================================================================
+
+typedef struct
+{
+ int fileofs, filelen;
+} sin_lump_t;
+
+#define SIN_LUMP_ENTITIES 0
+#define SIN_LUMP_PLANES 1
+#define SIN_LUMP_VERTEXES 2
+#define SIN_LUMP_VISIBILITY 3
+#define SIN_LUMP_NODES 4
+#define SIN_LUMP_TEXINFO 5
+#define SIN_LUMP_FACES 6
+#define SIN_LUMP_LIGHTING 7
+#define SIN_LUMP_LEAFS 8
+#define SIN_LUMP_LEAFFACES 9
+#define SIN_LUMP_LEAFBRUSHES 10
+#define SIN_LUMP_EDGES 11
+#define SIN_LUMP_SURFEDGES 12
+#define SIN_LUMP_MODELS 13
+#define SIN_LUMP_BRUSHES 14
+#define SIN_LUMP_BRUSHSIDES 15
+#define SIN_LUMP_POP 16
+#define SIN_LUMP_AREAS 17
+#define SIN_LUMP_AREAPORTALS 18
+
+#ifdef SIN
+#define SIN_LUMP_LIGHTINFO 19
+#define SINHEADER_LUMPS 20
+#endif
+
+typedef struct
+{
+ int ident;
+ int version;
+ sin_lump_t lumps[SINHEADER_LUMPS];
+} sin_dheader_t;
+
+typedef struct
+{
+ float mins[3], maxs[3];
+ float origin[3]; // for sounds or lights
+ int headnode;
+ int firstface, numfaces; // submodels just draw faces
+ // without walking the bsp tree
+} sin_dmodel_t;
+
+typedef struct
+{
+ float point[3];
+} sin_dvertex_t;
+
+
+// 0-2 are axial planes
+#define PLANE_X 0
+#define PLANE_Y 1
+#define PLANE_Z 2
+
+// 3-5 are non-axial planes snapped to the nearest
+#define PLANE_ANYX 3
+#define PLANE_ANYY 4
+#define PLANE_ANYZ 5
+
+// planes (x&~1) and (x&~1)+1 are allways opposites
+
+typedef struct
+{
+ float normal[3];
+ float dist;
+ int type; // PLANE_X - PLANE_ANYZ ?remove? trivial to regenerate
+} sin_dplane_t;
+
+
+// contents flags are seperate bits
+// a given brush can contribute multiple content bits
+// multiple brushes can be in a single leaf
+
+// these definitions also need to be in q_shared.h!
+
+// lower bits are stronger, and will eat weaker brushes completely
+#ifdef SIN
+#define CONTENTS_FENCE 4
+#endif
+// remaining contents are non-visible, and don't eat brushes
+
+#ifdef SIN
+#define CONTENTS_DUMMYFENCE 0x1000
+#endif
+
+#ifdef SIN
+#define SURF_MASKED 0x2 // surface texture is masked
+#endif
+
+#define SURF_SKY 0x4 // don't draw, but add to skybox
+#define SURF_WARP 0x8 // turbulent water warp
+
+#ifdef SIN
+#define SURF_NONLIT 0x10 // surface is not lit
+#define SURF_NOFILTER 0x20 // surface is not bi-linear filtered
+#endif
+
+#define SURF_FLOWING 0x40 // scroll towards angle
+#define SURF_NODRAW 0x80 // don't bother referencing the texture
+
+#define SURF_HINT 0x100 // make a primary bsp splitter
+#define SURF_SKIP 0x200 // completely ignore, allowing non-closed brushes
+
+#ifdef SIN
+#define SURF_CONVEYOR 0x40 // surface is not lit
+#endif
+
+#ifdef SIN
+#define SURF_WAVY 0x400 // surface has waves
+#define SURF_RICOCHET 0x800 // projectiles bounce literally bounce off this surface
+#define SURF_PRELIT 0x1000 // surface has intensity information for pre-lighting
+#define SURF_MIRROR 0x2000 // surface is a mirror
+#define SURF_CONSOLE 0x4000 // surface is a console
+#define SURF_USECOLOR 0x8000 // surface is lit with non-lit * color
+#define SURF_HARDWAREONLY 0x10000 // surface has been damaged
+#define SURF_DAMAGE 0x20000 // surface can be damaged
+#define SURF_WEAK 0x40000 // surface has weak hit points
+#define SURF_NORMAL 0x80000 // surface has normal hit points
+#define SURF_ADD 0x100000 // surface will be additive
+#define SURF_ENVMAPPED 0x200000 // surface is envmapped
+#define SURF_RANDOMANIMATE 0x400000 // surface start animating on a random frame
+#define SURF_ANIMATE 0x800000 // surface animates
+#define SURF_RNDTIME 0x1000000 // time between animations is random
+#define SURF_TRANSLATE 0x2000000 // surface translates
+#define SURF_NOMERGE 0x4000000 // surface is not merged in csg phase
+#define SURF_TYPE_BIT0 0x8000000 // 0 bit of surface type
+#define SURF_TYPE_BIT1 0x10000000 // 1 bit of surface type
+#define SURF_TYPE_BIT2 0x20000000 // 2 bit of surface type
+#define SURF_TYPE_BIT3 0x40000000 // 3 bit of surface type
+
+#define SURF_START_BIT 27
+#define SURFACETYPE_FROM_FLAGS( x ) ( ( x >> (SURF_START_BIT) ) & 0xf )
+
+
+#define SURF_TYPE_SHIFT(x) ( (x) << (SURF_START_BIT) ) // macro for getting proper bit mask
+
+#define SURF_TYPE_NONE SURF_TYPE_SHIFT(0)
+#define SURF_TYPE_WOOD SURF_TYPE_SHIFT(1)
+#define SURF_TYPE_METAL SURF_TYPE_SHIFT(2)
+#define SURF_TYPE_STONE SURF_TYPE_SHIFT(3)
+#define SURF_TYPE_CONCRETE SURF_TYPE_SHIFT(4)
+#define SURF_TYPE_DIRT SURF_TYPE_SHIFT(5)
+#define SURF_TYPE_FLESH SURF_TYPE_SHIFT(6)
+#define SURF_TYPE_GRILL SURF_TYPE_SHIFT(7)
+#define SURF_TYPE_GLASS SURF_TYPE_SHIFT(8)
+#define SURF_TYPE_FABRIC SURF_TYPE_SHIFT(9)
+#define SURF_TYPE_MONITOR SURF_TYPE_SHIFT(10)
+#define SURF_TYPE_GRAVEL SURF_TYPE_SHIFT(11)
+#define SURF_TYPE_VEGETATION SURF_TYPE_SHIFT(12)
+#define SURF_TYPE_PAPER SURF_TYPE_SHIFT(13)
+#define SURF_TYPE_DUCT SURF_TYPE_SHIFT(14)
+#define SURF_TYPE_WATER SURF_TYPE_SHIFT(15)
+#endif
+
+
+typedef struct
+{
+ int planenum;
+ int children[2]; // negative numbers are -(leafs+1), not nodes
+ short mins[3]; // for frustom culling
+ short maxs[3];
+ unsigned short firstface;
+ unsigned short numfaces; // counting both sides
+} sin_dnode_t;
+
+#ifdef SIN
+
+typedef struct sin_lightvalue_s
+{
+ int value; // light emission, etc
+ vec3_t color;
+ float direct;
+ float directangle;
+ float directstyle;
+ char directstylename[32];
+} sin_lightvalue_t;
+
+typedef struct sin_texinfo_s
+{
+ float vecs[2][4]; // [s/t][xyz offset]
+ int flags; // miptex flags + overrides
+ char texture[64]; // texture name (textures/*.wal)
+ int nexttexinfo; // for animations, -1 = end of chain
+ float trans_mag;
+ int trans_angle;
+ int base_angle;
+ float animtime;
+ float nonlit;
+ float translucence;
+ float friction;
+ float restitution;
+ vec3_t color;
+ char groupname[32];
+} sin_texinfo_t;
+
+#endif //SIN
+
+// note that edge 0 is never used, because negative edge nums are used for
+// counterclockwise use of the edge in a face
+typedef struct
+{
+ unsigned short v[2]; // vertex numbers
+} sin_dedge_t;
+
+#ifdef MAXLIGHTMAPS
+#undef MAXLIGHTMAPS
+#endif
+#define MAXLIGHTMAPS 16
+typedef struct
+{
+ unsigned short planenum;
+ short side;
+
+ int firstedge; // we must support > 64k edges
+ short numedges;
+ short texinfo;
+
+// lighting info
+ byte styles[MAXLIGHTMAPS];
+ int lightofs; // start of [numstyles*surfsize] samples
+#ifdef SIN
+ int lightinfo;
+#endif
+} sin_dface_t;
+
+typedef struct
+{
+ int contents; // OR of all brushes (not needed?)
+
+ short cluster;
+ short area;
+
+ short mins[3]; // for frustum culling
+ short maxs[3];
+
+ unsigned short firstleafface;
+ unsigned short numleaffaces;
+
+ unsigned short firstleafbrush;
+ unsigned short numleafbrushes;
+} sin_dleaf_t;
+
+typedef struct
+{
+ unsigned short planenum; // facing out of the leaf
+ short texinfo;
+#ifdef SIN
+ int lightinfo;
+#endif
+} sin_dbrushside_t;
+
+typedef struct
+{
+ int firstside;
+ int numsides;
+ int contents;
+} sin_dbrush_t;
+
+#define ANGLE_UP -1
+#define ANGLE_DOWN -2
+
+
+// the visibility lump consists of a header with a count, then
+// byte offsets for the PVS and PHS of each cluster, then the raw
+// compressed bit vectors
+#define DVIS_PVS 0
+#define DVIS_PHS 1
+typedef struct
+{
+ int numclusters;
+ int bitofs[8][2]; // bitofs[numclusters][2]
+} sin_dvis_t;
+
+// each area has a list of portals that lead into other areas
+// when portals are closed, other areas may not be visible or
+// hearable even if the vis info says that it should be
+typedef struct
+{
+ int portalnum;
+ int otherarea;
+} sin_dareaportal_t;
+
+typedef struct
+{
+ int numareaportals;
+ int firstareaportal;
+} sin_darea_t;
diff --git a/code/bspc/tetrahedron.c b/code/bspc/tetrahedron.c
new file mode 100755
index 0000000..36c10af
--- /dev/null
+++ b/code/bspc/tetrahedron.c
@@ -0,0 +1,1389 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+#include "l_mem.h"
+#include "../botlib/aasfile.h"
+#include "aas_store.h"
+#include "aas_cfg.h"
+#include "aas_file.h"
+
+//
+// creating tetrahedrons from a arbitrary world bounded by triangles
+//
+// a triangle has 3 corners and 3 edges
+// a tetrahedron is build out of 4 triangles
+// a tetrahedron has 6 edges
+// we start with a world bounded by triangles, a side of a triangle facing
+// towards the oudside of the world is marked as part of tetrahedron -1
+//
+// a tetrahedron is defined by two non-coplanar triangles with a shared edge
+//
+// a tetrahedron is defined by one triangle and a vertex not in the triangle plane
+//
+// if all triangles using a specific vertex have tetrahedrons
+// at both sides then this vertex will never be part of a new tetrahedron
+//
+// if all triangles using a specific edge have tetrahedrons
+// at both sides then this vertex will never be part of a new tetrahedron
+//
+// each triangle can only be shared by two tetrahedrons
+// when all triangles have tetrahedrons at both sides then we're done
+//
+// if we cannot create any new tetrahedrons and there is at least one triangle
+// which has a tetrahedron only at one side then the world leaks
+//
+
+#define Sign(x) (x < 0 ? 1 : 0)
+
+#define MAX_TH_VERTEXES 128000
+#define MAX_TH_PLANES 128000
+#define MAX_TH_EDGES 512000
+#define MAX_TH_TRIANGLES 51200
+#define MAX_TH_TETRAHEDRONS 12800
+
+#define PLANEHASH_SIZE 1024
+#define EDGEHASH_SIZE 1024
+#define TRIANGLEHASH_SIZE 1024
+#define VERTEXHASH_SHIFT 7
+#define VERTEXHASH_SIZE ((MAX_MAP_BOUNDS>>(VERTEXHASH_SHIFT-1))+1) //was 64
+
+#define NORMAL_EPSILON 0.0001
+#define DIST_EPSILON 0.1
+#define VERTEX_EPSILON 0.01
+#define INTEGRAL_EPSILON 0.01
+
+
+//plane
+typedef struct th_plane_s
+{
+ vec3_t normal;
+ float dist;
+ int type;
+ int signbits;
+ struct th_plane_s *hashnext; //next plane in hash
+} th_plane_t;
+
+//vertex
+typedef struct th_vertex_s
+{
+ vec3_t v;
+ int usercount; //2x the number of to be processed
+ //triangles using this vertex
+ struct th_vertex_s *hashnext; //next vertex in hash
+} th_vertex_t;
+
+//edge
+typedef struct th_edge_s
+{
+ int v[2]; //vertex indexes
+ int usercount; //number of to be processed
+ //triangles using this edge
+ struct th_edge_s *hashnext; //next edge in hash
+} th_edge_t;
+
+//triangle
+typedef struct th_triangle_s
+{
+ int edges[3]; //negative if edge is flipped
+ th_plane_t planes[3]; //triangle bounding planes
+ int planenum; //plane the triangle is in
+ int front; //tetrahedron at the front
+ int back; //tetrahedron at the back
+ vec3_t mins, maxs; //triangle bounding box
+ struct th_triangle_s *prev, *next; //links in linked triangle lists
+ struct th_triangle_s *hashnext; //next triangle in hash
+} th_triangle_t;
+
+//tetrahedron
+typedef struct th_tetrahedron_s
+{
+ int triangles[4]; //negative if at backside of triangle
+ float volume; //tetrahedron volume
+} th_tetrahedron_t;
+
+typedef struct th_s
+{
+ //vertexes
+ int numvertexes;
+ th_vertex_t *vertexes;
+ th_vertex_t *vertexhash[VERTEXHASH_SIZE * VERTEXHASH_SIZE];
+ //planes
+ int numplanes;
+ th_plane_t *planes;
+ th_plane_t *planehash[PLANEHASH_SIZE];
+ //edges
+ int numedges;
+ th_edge_t *edges;
+ th_edge_t *edgehash[EDGEHASH_SIZE];
+ //triangles
+ int numtriangles;
+ th_triangle_t *triangles;
+ th_triangle_t *trianglehash[TRIANGLEHASH_SIZE];
+ //tetrahedrons
+ int numtetrahedrons;
+ th_tetrahedron_t *tetrahedrons;
+} th_t;
+
+th_t thworld;
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void TH_InitMaxTH(void)
+{
+ //get memory for the tetrahedron data
+ thworld.vertexes = (th_vertex_t *) GetClearedMemory(MAX_TH_VERTEXES * sizeof(th_vertex_t));
+ thworld.planes = (th_plane_t *) GetClearedMemory(MAX_TH_PLANES * sizeof(th_plane_t));
+ thworld.edges = (th_edge_t *) GetClearedMemory(MAX_TH_EDGES * sizeof(th_edge_t));
+ thworld.triangles = (th_triangle_t *) GetClearedMemory(MAX_TH_TRIANGLES * sizeof(th_triangle_t));
+ thworld.tetrahedrons = (th_tetrahedron_t *) GetClearedMemory(MAX_TH_TETRAHEDRONS * sizeof(th_tetrahedron_t));
+ //reset the hash tables
+ memset(thworld.vertexhash, 0, VERTEXHASH_SIZE * sizeof(th_vertex_t *));
+ memset(thworld.planehash, 0, PLANEHASH_SIZE * sizeof(th_plane_t *));
+ memset(thworld.edgehash, 0, EDGEHASH_SIZE * sizeof(th_edge_t *));
+ memset(thworld.trianglehash, 0, TRIANGLEHASH_SIZE * sizeof(th_triangle_t *));
+} //end of the function TH_InitMaxTH
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void TH_FreeMaxTH(void)
+{
+ if (thworld.vertexes) FreeMemory(thworld.vertexes);
+ thworld.vertexes = NULL;
+ thworld.numvertexes = 0;
+ if (thworld.planes) FreeMemory(thworld.planes);
+ thworld.planes = NULL;
+ thworld.numplanes = 0;
+ if (thworld.edges) FreeMemory(thworld.edges);
+ thworld.edges = NULL;
+ thworld.numedges = 0;
+ if (thworld.triangles) FreeMemory(thworld.triangles);
+ thworld.triangles = NULL;
+ thworld.numtriangles = 0;
+ if (thworld.tetrahedrons) FreeMemory(thworld.tetrahedrons);
+ thworld.tetrahedrons = NULL;
+ thworld.numtetrahedrons = 0;
+} //end of the function TH_FreeMaxTH
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float TH_TriangleArea(th_triangle_t *tri)
+{
+ return 0;
+} //end of the function TH_TriangleArea
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+float TH_TetrahedronVolume(th_tetrahedron_t *tetrahedron)
+{
+ int edgenum, verts[3], i, j, v2;
+ float volume, d;
+ th_triangle_t *tri, *tri2;
+ th_plane_t *plane;
+
+ tri = &thworld.triangles[abs(tetrahedron->triangles[0])];
+ for (i = 0; i < 3; i++)
+ {
+ edgenum = tri->edges[i];
+ if (edgenum < 0) verts[i] = thworld.edges[abs(edgenum)].v[1];
+ else verts[i] = thworld.edges[edgenum].v[0];
+ } //end for
+ //
+ tri2 = &thworld.triangles[abs(tetrahedron->triangles[1])];
+ for (j = 0; j < 3; j++)
+ {
+ edgenum = tri2->edges[i];
+ if (edgenum < 0) v2 = thworld.edges[abs(edgenum)].v[1];
+ else v2 = thworld.edges[edgenum].v[0];
+ if (v2 != verts[0] &&
+ v2 != verts[1] &&
+ v2 != verts[2]) break;
+ } //end for
+
+ plane = &thworld.planes[tri->planenum];
+ d = -(DotProduct (thworld.vertexes[v2].v, plane->normal) - plane->dist);
+ volume = TH_TriangleArea(tri) * d / 3;
+ return volume;
+} //end of the function TH_TetrahedronVolume
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TH_PlaneSignBits(vec3_t normal)
+{
+ int i, signbits;
+
+ signbits = 0;
+ for (i = 2; i >= 0; i--)
+ {
+ signbits = (signbits << 1) + Sign(normal[i]);
+ } //end for
+ return signbits;
+} //end of the function TH_PlaneSignBits
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TH_PlaneTypeForNormal(vec3_t normal)
+{
+ vec_t ax, ay, az;
+
+// NOTE: should these have an epsilon around 1.0?
+ if (normal[0] == 1.0 || normal[0] == -1.0)
+ return PLANE_X;
+ if (normal[1] == 1.0 || normal[1] == -1.0)
+ return PLANE_Y;
+ if (normal[2] == 1.0 || normal[2] == -1.0)
+ return PLANE_Z;
+
+ ax = fabs(normal[0]);
+ ay = fabs(normal[1]);
+ az = fabs(normal[2]);
+
+ if (ax >= ay && ax >= az)
+ return PLANE_ANYX;
+ if (ay >= ax && ay >= az)
+ return PLANE_ANYY;
+ return PLANE_ANYZ;
+} //end of the function TH_PlaneTypeForNormal
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+qboolean TH_PlaneEqual(th_plane_t *p, vec3_t normal, vec_t dist)
+{
+ if (
+ fabs(p->normal[0] - normal[0]) < NORMAL_EPSILON
+ && fabs(p->normal[1] - normal[1]) < NORMAL_EPSILON
+ && fabs(p->normal[2] - normal[2]) < NORMAL_EPSILON
+ && fabs(p->dist - dist) < DIST_EPSILON )
+ return true;
+ return false;
+} //end of the function TH_PlaneEqual
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void TH_AddPlaneToHash(th_plane_t *p)
+{
+ int hash;
+
+ hash = (int)fabs(p->dist) / 8;
+ hash &= (PLANEHASH_SIZE-1);
+
+ p->hashnext = thworld.planehash[hash];
+ thworld.planehash[hash] = p;
+} //end of the function TH_AddPlaneToHash
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TH_CreateFloatPlane(vec3_t normal, vec_t dist)
+{
+ th_plane_t *p, temp;
+
+ if (VectorLength(normal) < 0.5)
+ Error ("FloatPlane: bad normal");
+ // create a new plane
+ if (thworld.numplanes+2 > MAX_TH_PLANES)
+ Error ("MAX_TH_PLANES");
+
+ p = &thworld.planes[thworld.numplanes];
+ VectorCopy (normal, p->normal);
+ p->dist = dist;
+ p->type = (p+1)->type = TH_PlaneTypeForNormal (p->normal);
+ p->signbits = TH_PlaneSignBits(p->normal);
+
+ VectorSubtract (vec3_origin, normal, (p+1)->normal);
+ (p+1)->dist = -dist;
+ (p+1)->signbits = TH_PlaneSignBits((p+1)->normal);
+
+ thworld.numplanes += 2;
+
+ // allways put axial planes facing positive first
+ if (p->type < 3)
+ {
+ if (p->normal[0] < 0 || p->normal[1] < 0 || p->normal[2] < 0)
+ {
+ // flip order
+ temp = *p;
+ *p = *(p+1);
+ *(p+1) = temp;
+
+ TH_AddPlaneToHash(p);
+ TH_AddPlaneToHash(p+1);
+ return thworld.numplanes - 1;
+ } //end if
+ } //end if
+
+ TH_AddPlaneToHash(p);
+ TH_AddPlaneToHash(p+1);
+ return thworld.numplanes - 2;
+} //end of the function TH_CreateFloatPlane
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void TH_SnapVector(vec3_t normal)
+{
+ int i;
+
+ for (i = 0; i < 3; i++)
+ {
+ if ( fabs(normal[i] - 1) < NORMAL_EPSILON )
+ {
+ VectorClear (normal);
+ normal[i] = 1;
+ break;
+ } //end if
+ if ( fabs(normal[i] - -1) < NORMAL_EPSILON )
+ {
+ VectorClear (normal);
+ normal[i] = -1;
+ break;
+ } //end if
+ } //end for
+} //end of the function TH_SnapVector
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void TH_SnapPlane(vec3_t normal, vec_t *dist)
+{
+ TH_SnapVector(normal);
+
+ if (fabs(*dist-Q_rint(*dist)) < DIST_EPSILON)
+ *dist = Q_rint(*dist);
+} //end of the function TH_SnapPlane
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TH_FindFloatPlane(vec3_t normal, vec_t dist)
+{
+ int i;
+ th_plane_t *p;
+ int hash, h;
+
+ TH_SnapPlane (normal, &dist);
+ hash = (int)fabs(dist) / 8;
+ hash &= (PLANEHASH_SIZE-1);
+
+ // search the border bins as well
+ for (i = -1; i <= 1; i++)
+ {
+ h = (hash+i)&(PLANEHASH_SIZE-1);
+ for (p = thworld.planehash[h]; p; p = p->hashnext)
+ {
+ if (TH_PlaneEqual(p, normal, dist))
+ {
+ return p - thworld.planes;
+ } //end if
+ } //end for
+ } //end for
+ return TH_CreateFloatPlane(normal, dist);
+} //end of the function TH_FindFloatPlane
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TH_PlaneFromPoints(int v1, int v2, int v3)
+{
+ vec3_t t1, t2, normal;
+ vec_t dist;
+ float *p0, *p1, *p2;
+
+ p0 = thworld.vertexes[v1].v;
+ p1 = thworld.vertexes[v2].v;
+ p2 = thworld.vertexes[v3].v;
+
+ VectorSubtract(p0, p1, t1);
+ VectorSubtract(p2, p1, t2);
+ CrossProduct(t1, t2, normal);
+ VectorNormalize(normal);
+
+ dist = DotProduct(p0, normal);
+
+ return TH_FindFloatPlane(normal, dist);
+} //end of the function TH_PlaneFromPoints
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void TH_AddEdgeUser(int edgenum)
+{
+ th_edge_t *edge;
+
+ edge = &thworld.edges[abs(edgenum)];
+ //increase edge user count
+ edge->usercount++;
+ //increase vertex user count as well
+ thworld.vertexes[edge->v[0]].usercount++;
+ thworld.vertexes[edge->v[1]].usercount++;
+} //end of the function TH_AddEdgeUser
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void TH_RemoveEdgeUser(int edgenum)
+{
+ th_edge_t *edge;
+
+ edge = &thworld.edges[abs(edgenum)];
+ //decrease edge user count
+ edge->usercount--;
+ //decrease vertex user count as well
+ thworld.vertexes[edge->v[0]].usercount--;
+ thworld.vertexes[edge->v[1]].usercount--;
+} //end of the function TH_RemoveEdgeUser
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void TH_FreeTriangleEdges(th_triangle_t *tri)
+{
+ int i;
+
+ for (i = 0; i < 3; i++)
+ {
+ TH_RemoveEdgeUser(abs(tri->edges[i]));
+ } //end for
+} //end of the function TH_FreeTriangleEdges
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+unsigned TH_HashVec(vec3_t vec)
+{
+ int x, y;
+
+ x = (MAX_MAP_BOUNDS + (int)(vec[0]+0.5)) >> VERTEXHASH_SHIFT;
+ y = (MAX_MAP_BOUNDS + (int)(vec[1]+0.5)) >> VERTEXHASH_SHIFT;
+
+ if (x < 0 || x >= VERTEXHASH_SIZE || y < 0 || y >= VERTEXHASH_SIZE)
+ Error("HashVec: point %f %f %f outside valid range", vec[0], vec[1], vec[2]);
+
+ return y*VERTEXHASH_SIZE + x;
+} //end of the function TH_HashVec
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TH_FindVertex(vec3_t v)
+{
+ int i, h;
+ th_vertex_t *vertex;
+ vec3_t vert;
+
+ for (i = 0; i < 3; i++)
+ {
+ if ( fabs(v[i] - Q_rint(v[i])) < INTEGRAL_EPSILON)
+ vert[i] = Q_rint(v[i]);
+ else
+ vert[i] = v[i];
+ } //end for
+
+ h = TH_HashVec(vert);
+
+ for (vertex = thworld.vertexhash[h]; vertex; vertex = vertex->hashnext)
+ {
+ if (fabs(vertex->v[0] - vert[0]) < VERTEX_EPSILON &&
+ fabs(vertex->v[1] - vert[1]) < VERTEX_EPSILON &&
+ fabs(vertex->v[2] - vert[2]) < VERTEX_EPSILON)
+ {
+ return vertex - thworld.vertexes;
+ } //end if
+ } //end for
+ return 0;
+} //end of the function TH_FindVertex
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void TH_AddVertexToHash(th_vertex_t *vertex)
+{
+ int hashvalue;
+
+ hashvalue = TH_HashVec(vertex->v);
+ vertex->hashnext = thworld.vertexhash[hashvalue];
+ thworld.vertexhash[hashvalue] = vertex;
+} //end of the function TH_AddVertexToHash
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TH_CreateVertex(vec3_t v)
+{
+ if (thworld.numvertexes == 0) thworld.numvertexes = 1;
+ if (thworld.numvertexes >= MAX_TH_VERTEXES)
+ Error("MAX_TH_VERTEXES");
+ VectorCopy(v, thworld.vertexes[thworld.numvertexes].v);
+ thworld.vertexes[thworld.numvertexes].usercount = 0;
+ TH_AddVertexToHash(&thworld.vertexes[thworld.numvertexes]);
+ thworld.numvertexes++;
+ return thworld.numvertexes-1;
+} //end of the function TH_CreateVertex
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TH_FindOrCreateVertex(vec3_t v)
+{
+ int vertexnum;
+
+ vertexnum = TH_FindVertex(v);
+ if (!vertexnum) vertexnum = TH_CreateVertex(v);
+ return vertexnum;
+} //end of the function TH_FindOrCreateVertex
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TH_FindEdge(int v1, int v2)
+{
+ int hashvalue;
+ th_edge_t *edge;
+
+ hashvalue = (v1 + v2) & (EDGEHASH_SIZE-1);
+
+ for (edge = thworld.edgehash[hashvalue]; edge; edge = edge->hashnext)
+ {
+ if (edge->v[0] == v1 && edge->v[1] == v2) return edge - thworld.edges;
+ if (edge->v[1] == v1 && edge->v[0] == v2) return -(edge - thworld.edges);
+ } //end for
+ return 0;
+} //end of the function TH_FindEdge
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void TH_AddEdgeToHash(th_edge_t *edge)
+{
+ int hashvalue;
+
+ hashvalue = (edge->v[0] + edge->v[1]) & (EDGEHASH_SIZE-1);
+ edge->hashnext = thworld.edgehash[hashvalue];
+ thworld.edgehash[hashvalue] = edge;
+} //end of the function TH_AddEdgeToHash
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TH_CreateEdge(int v1, int v2)
+{
+ th_edge_t *edge;
+
+ if (thworld.numedges == 0) thworld.numedges = 1;
+ if (thworld.numedges >= MAX_TH_EDGES)
+ Error("MAX_TH_EDGES");
+ edge = &thworld.edges[thworld.numedges++];
+ edge->v[0] = v1;
+ edge->v[1] = v2;
+ TH_AddEdgeToHash(edge);
+ return thworld.numedges-1;
+} //end of the function TH_CreateEdge
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TH_FindOrCreateEdge(int v1, int v2)
+{
+ int edgenum;
+
+ edgenum = TH_FindEdge(v1, v2);
+ if (!edgenum) edgenum = TH_CreateEdge(v1, v2);
+ return edgenum;
+} //end of the function TH_FindOrCreateEdge
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TH_FindTriangle(int verts[3])
+{
+ int i, hashvalue, edges[3];
+ th_triangle_t *tri;
+
+ for (i = 0; i < 3; i++)
+ {
+ edges[i] = TH_FindEdge(verts[i], verts[(i+1)%3]);
+ if (!edges[i]) return false;
+ } //end for
+ hashvalue = (abs(edges[0]) + abs(edges[1]) + abs(edges[2])) & (TRIANGLEHASH_SIZE-1);
+ for (tri = thworld.trianglehash[hashvalue]; tri; tri = tri->next)
+ {
+ for (i = 0; i < 3; i++)
+ {
+ if (abs(tri->edges[i]) != abs(edges[0]) &&
+ abs(tri->edges[i]) != abs(edges[1]) &&
+ abs(tri->edges[i]) != abs(edges[2])) break;
+ } //end for
+ if (i >= 3) return tri - thworld.triangles;
+ } //end for
+ return 0;
+} //end of the function TH_FindTriangle
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void TH_AddTriangleToHash(th_triangle_t *tri)
+{
+ int hashvalue;
+
+ hashvalue = (abs(tri->edges[0]) + abs(tri->edges[1]) + abs(tri->edges[2])) & (TRIANGLEHASH_SIZE-1);
+ tri->hashnext = thworld.trianglehash[hashvalue];
+ thworld.trianglehash[hashvalue] = tri;
+} //end of the function TH_AddTriangleToHash
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void TH_CreateTrianglePlanes(int verts[3], th_plane_t *triplane, th_plane_t *planes)
+{
+ int i;
+ vec3_t dir;
+
+ for (i = 0; i < 3; i++)
+ {
+ VectorSubtract(thworld.vertexes[verts[(i+1)%3]].v, thworld.vertexes[verts[i]].v, dir);
+ CrossProduct(dir, triplane->normal, planes[i].normal);
+ VectorNormalize(planes[i].normal);
+ planes[i].dist = DotProduct(thworld.vertexes[verts[i]].v, planes[i].normal);
+ } //end for
+} //end of the function TH_CreateTrianglePlanes
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TH_CreateTriangle(int verts[3])
+{
+ th_triangle_t *tri;
+ int i;
+
+ if (thworld.numtriangles == 0) thworld.numtriangles = 1;
+ if (thworld.numtriangles >= MAX_TH_TRIANGLES)
+ Error("MAX_TH_TRIANGLES");
+ tri = &thworld.triangles[thworld.numtriangles++];
+ for (i = 0; i < 3; i++)
+ {
+ tri->edges[i] = TH_FindOrCreateEdge(verts[i], verts[(i+1)%3]);
+ TH_AddEdgeUser(abs(tri->edges[i]));
+ } //end for
+ tri->front = 0;
+ tri->back = 0;
+ tri->planenum = TH_PlaneFromPoints(verts[0], verts[1], verts[2]);
+ tri->prev = NULL;
+ tri->next = NULL;
+ tri->hashnext = NULL;
+ TH_CreateTrianglePlanes(verts, &thworld.planes[tri->planenum], tri->planes);
+ TH_AddTriangleToHash(tri);
+ ClearBounds(tri->mins, tri->maxs);
+ for (i = 0; i < 3; i++)
+ {
+ AddPointToBounds(thworld.vertexes[verts[i]].v, tri->mins, tri->maxs);
+ } //end for
+ return thworld.numtriangles-1;
+} //end of the function TH_CreateTriangle
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TH_CreateTetrahedron(int triangles[4])
+{
+ th_tetrahedron_t *tetrahedron;
+ int i;
+
+ if (thworld.numtetrahedrons == 0) thworld.numtetrahedrons = 1;
+ if (thworld.numtetrahedrons >= MAX_TH_TETRAHEDRONS)
+ Error("MAX_TH_TETRAHEDRONS");
+ tetrahedron = &thworld.tetrahedrons[thworld.numtetrahedrons++];
+ for (i = 0; i < 4; i++)
+ {
+ tetrahedron->triangles[i] = triangles[i];
+ if (thworld.triangles[abs(triangles[i])].front)
+ {
+ thworld.triangles[abs(triangles[i])].back = thworld.numtetrahedrons-1;
+ } //end if
+ else
+ {
+ thworld.triangles[abs(triangles[i])].front = thworld.numtetrahedrons-1;
+ } //end else
+ } //end for
+ tetrahedron->volume = 0;
+ return thworld.numtetrahedrons-1;
+} //end of the function TH_CreateTetrahedron
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TH_IntersectTrianglePlanes(int v1, int v2, th_plane_t *triplane, th_plane_t *planes)
+{
+ float *p1, *p2, front, back, frac, d;
+ int i, side, lastside;
+ vec3_t mid;
+
+ p1 = thworld.vertexes[v1].v;
+ p2 = thworld.vertexes[v2].v;
+
+ front = DotProduct(p1, triplane->normal) - triplane->dist;
+ back = DotProduct(p2, triplane->normal) - triplane->dist;
+ //if both points at the same side of the plane
+ if (front < 0.1 && back < 0.1) return false;
+ if (front > -0.1 && back > -0.1) return false;
+ //
+ frac = front/(front-back);
+ mid[0] = p1[0] + (p2[0] - p1[0]) * frac;
+ mid[1] = p1[1] + (p2[1] - p1[1]) * frac;
+ mid[2] = p1[2] + (p2[2] - p1[2]) * frac;
+ //if the mid point is at the same side of all the tri bounding planes
+ lastside = 0;
+ for (i = 0; i < 3; i++)
+ {
+ d = DotProduct(mid, planes[i].normal) - planes[i].dist;
+ side = d < 0;
+ if (i && side != lastside) return false;
+ lastside = side;
+ } //end for
+ return true;
+} //end of the function TH_IntersectTrianglePlanes
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TH_OutsideBoundingBox(int v1, int v2, vec3_t mins, vec3_t maxs)
+{
+ float *p1, *p2;
+ int i;
+
+ p1 = thworld.vertexes[v1].v;
+ p2 = thworld.vertexes[v2].v;
+ //if both points are at the outer side of one of the bounding box planes
+ for (i = 0; i < 3; i++)
+ {
+ if (p1[i] < mins[i] && p2[i] < mins[i]) return true;
+ if (p1[i] > maxs[i] && p2[i] > maxs[i]) return true;
+ } //end for
+ return false;
+} //end of the function TH_OutsideBoundingBox
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TH_TryEdge(int v1, int v2)
+{
+ int i, j, v;
+ th_plane_t *plane;
+ th_triangle_t *tri;
+
+ //if the edge already exists it must be valid
+ if (TH_FindEdge(v1, v2)) return true;
+ //test the edge with all existing triangles
+ for (i = 1; i < thworld.numtriangles; i++)
+ {
+ tri = &thworld.triangles[i];
+ //if triangle is enclosed by two tetrahedrons we don't have to test it
+ //because the edge always has to go through another triangle of those
+ //tetrahedrons first to reach the enclosed triangle
+ if (tri->front && tri->back) continue;
+ //if the edges is totally outside the triangle bounding box
+ if (TH_OutsideBoundingBox(v1, v2, tri->mins, tri->maxs)) continue;
+ //if one of the edge vertexes is used by this triangle
+ for (j = 0; j < 3; j++)
+ {
+ v = thworld.edges[abs(tri->edges[j])].v[tri->edges[j] < 0];
+ if (v == v1 || v == v2) break;
+ } //end for
+ if (j < 3) continue;
+ //get the triangle plane
+ plane = &thworld.planes[tri->planenum];
+ //if the edge intersects with a triangle then it's not valid
+ if (TH_IntersectTrianglePlanes(v1, v2, plane, tri->planes)) return false;
+ } //end for
+ return true;
+} //end of the function TH_TryEdge
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TH_TryTriangle(int verts[3])
+{
+ th_plane_t planes[3], triplane;
+ vec3_t t1, t2;
+ float *p0, *p1, *p2;
+ int i, j;
+
+ p0 = thworld.vertexes[verts[0]].v;
+ p1 = thworld.vertexes[verts[1]].v;
+ p2 = thworld.vertexes[verts[2]].v;
+
+ VectorSubtract(p0, p1, t1);
+ VectorSubtract(p2, p1, t2);
+ CrossProduct(t1, t2, triplane.normal);
+ VectorNormalize(triplane.normal);
+ triplane.dist = DotProduct(p0, triplane.normal);
+ //
+ TH_CreateTrianglePlanes(verts, &triplane, planes);
+ //test if any existing edge intersects with this triangle
+ for (i = 1; i < thworld.numedges; i++)
+ {
+ //if the edge is only used by triangles with tetrahedrons at both sides
+ if (!thworld.edges[i].usercount) continue;
+ //if one of the triangle vertexes is used by this edge
+ for (j = 0; j < 3; j++)
+ {
+ if (verts[j] == thworld.edges[j].v[0] ||
+ verts[j] == thworld.edges[j].v[1]) break;
+ } //end for
+ if (j < 3) continue;
+ //if this edge intersects with the triangle
+ if (TH_IntersectTrianglePlanes(thworld.edges[i].v[0], thworld.edges[i].v[1], &triplane, planes)) return false;
+ } //end for
+ return true;
+} //end of the function TH_TryTriangle
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void TH_AddTriangleToList(th_triangle_t **trianglelist, th_triangle_t *tri)
+{
+ tri->prev = NULL;
+ tri->next = *trianglelist;
+ if (*trianglelist) (*trianglelist)->prev = tri;
+ *trianglelist = tri;
+} //end of the function TH_AddTriangleToList
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void TH_RemoveTriangleFromList(th_triangle_t **trianglelist, th_triangle_t *tri)
+{
+ if (tri->next) tri->next->prev = tri->prev;
+ if (tri->prev) tri->prev->next = tri->next;
+ else *trianglelist = tri->next;
+} //end of the function TH_RemoveTriangleFromList
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TH_FindTetrahedron1(th_triangle_t *tri, int *triangles)
+{
+ int i, j, edgenum, side, v1, v2, v3, v4;
+ int verts1[3], verts2[3];
+ th_triangle_t *tri2;
+
+ //find another triangle with a shared edge
+ for (tri2 = tri->next; tri2; tri2 = tri2->next)
+ {
+ //if the triangles are in the same plane
+ if ((tri->planenum & ~1) == (tri2->planenum & ~1)) continue;
+ //try to find a shared edge
+ for (i = 0; i < 3; i++)
+ {
+ edgenum = abs(tri->edges[i]);
+ for (j = 0; j < 3; j++)
+ {
+ if (edgenum == abs(tri2->edges[j])) break;
+ } //end for
+ if (j < 3) break;
+ } //end for
+ //if the triangles have a shared edge
+ if (i < 3)
+ {
+ edgenum = tri->edges[(i+1)%3];
+ if (edgenum < 0) v1 = thworld.edges[abs(edgenum)].v[0];
+ else v1 = thworld.edges[edgenum].v[1];
+ edgenum = tri2->edges[(j+1)%3];
+ if (edgenum < 0) v2 = thworld.edges[abs(edgenum)].v[0];
+ else v2 = thworld.edges[edgenum].v[1];
+ //try the new edge
+ if (TH_TryEdge(v1, v2))
+ {
+ edgenum = tri->edges[i];
+ side = edgenum < 0;
+ //get the vertexes of the shared edge
+ v3 = thworld.edges[abs(edgenum)].v[side];
+ v4 = thworld.edges[abs(edgenum)].v[!side];
+ //try the two new triangles
+ verts1[0] = v1;
+ verts1[1] = v2;
+ verts1[2] = v3;
+ triangles[2] = TH_FindTriangle(verts1);
+ if (triangles[2] || TH_TryTriangle(verts1))
+ {
+ verts2[0] = v2;
+ verts2[1] = v1;
+ verts2[2] = v4;
+ triangles[3] = TH_FindTriangle(verts2);
+ if (triangles[3] || TH_TryTriangle(verts2))
+ {
+ triangles[0] = tri - thworld.triangles;
+ triangles[1] = tri2 - thworld.triangles;
+ if (!triangles[2]) triangles[2] = TH_CreateTriangle(verts1);
+ if (!triangles[3]) triangles[3] = TH_CreateTriangle(verts2);
+ return true;
+ } //end if
+ } //end if
+ } //end if
+ } //end if
+ } //end for
+ return false;
+} //end of the function TH_FindTetrahedron
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TH_FindTetrahedron2(th_triangle_t *tri, int *triangles)
+{
+ int i, edgenum, v1, verts[3], triverts[3];
+ float d;
+ th_plane_t *plane;
+
+ //get the verts of this triangle
+ for (i = 0; i < 3; i++)
+ {
+ edgenum = tri->edges[i];
+ if (edgenum < 0) verts[i] = thworld.edges[abs(edgenum)].v[1];
+ else verts[i] = thworld.edges[edgenum].v[0];
+ } //end for
+ //
+ plane = &thworld.planes[tri->planenum];
+ for (v1 = 0; v1 < thworld.numvertexes; v1++)
+ {
+ //if the vertex is only used by triangles with tetrahedrons at both sides
+ if (!thworld.vertexes[v1].usercount) continue;
+ //check if the vertex is not coplanar with the triangle
+ d = DotProduct(thworld.vertexes[v1].v, plane->normal) - plane->dist;
+ if (fabs(d) < 1) continue;
+ //check if we can create edges from the triangle towards this new vertex
+ for (i = 0; i < 3; i++)
+ {
+ if (v1 == verts[i]) break;
+ if (!TH_TryEdge(v1, verts[i])) break;
+ } //end for
+ if (i < 3) continue;
+ //check if the triangles are valid
+ for (i = 0; i < 3; i++)
+ {
+ triverts[0] = v1;
+ triverts[1] = verts[i];
+ triverts[2] = verts[(i+1)%3];
+ //if the triangle already exists then it is valid
+ triangles[i] = TH_FindTriangle(triverts);
+ if (!triangles[i])
+ {
+ if (!TH_TryTriangle(triverts)) break;
+ } //end if
+ } //end for
+ if (i < 3) continue;
+ //create the tetrahedron triangles using the new vertex
+ for (i = 0; i < 3; i++)
+ {
+ if (!triangles[i])
+ {
+ triverts[0] = v1;
+ triverts[1] = verts[i];
+ triverts[2] = verts[(i+1)%3];
+ triangles[i] = TH_CreateTriangle(triverts);
+ } //end if
+ } //end for
+ //add the existing triangle
+ triangles[3] = tri - thworld.triangles;
+ //
+ return true;
+ } //end for
+ return false;
+} //end of the function TH_FindTetrahedron2
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void TH_TetrahedralDecomposition(th_triangle_t *triangles)
+{
+ int i, thtriangles[4], numtriangles;
+ th_triangle_t *donetriangles, *tri;
+
+ donetriangles = NULL;
+
+ /*
+ numtriangles = 0;
+ qprintf("%6d triangles", numtriangles);
+ for (tri = triangles; tri; tri = triangles)
+ {
+ qprintf("\r%6d", numtriangles++);
+ if (!TH_FindTetrahedron1(tri, thtriangles))
+ {
+// if (!TH_FindTetrahedron2(tri, thtriangles))
+ {
+// Error("triangle without tetrahedron");
+ TH_RemoveTriangleFromList(&triangles, tri);
+ continue;
+ } //end if
+ } //end if
+ //create a tetrahedron from the triangles
+ TH_CreateTetrahedron(thtriangles);
+ //
+ for (i = 0; i < 4; i++)
+ {
+ if (thworld.triangles[abs(thtriangles[i])].front &&
+ thworld.triangles[abs(thtriangles[i])].back)
+ {
+ TH_RemoveTriangleFromList(&triangles, &thworld.triangles[abs(thtriangles[i])]);
+ TH_AddTriangleToList(&donetriangles, &thworld.triangles[abs(thtriangles[i])]);
+ TH_FreeTriangleEdges(&thworld.triangles[abs(thtriangles[i])]);
+ } //end if
+ else
+ {
+ TH_AddTriangleToList(&triangles, &thworld.triangles[abs(thtriangles[i])]);
+ } //end else
+ } //end for
+ } //end for*/
+ qprintf("%6d tetrahedrons", thworld.numtetrahedrons);
+ do
+ {
+ do
+ {
+ numtriangles = 0;
+ for (i = 1; i < thworld.numtriangles; i++)
+ {
+ tri = &thworld.triangles[i];
+ if (tri->front && tri->back) continue;
+ //qprintf("\r%6d", numtriangles++);
+ if (!TH_FindTetrahedron1(tri, thtriangles))
+ {
+// if (!TH_FindTetrahedron2(tri, thtriangles))
+ {
+ continue;
+ } //end if
+ } //end if
+ numtriangles++;
+ //create a tetrahedron from the triangles
+ TH_CreateTetrahedron(thtriangles);
+ qprintf("\r%6d", thworld.numtetrahedrons);
+ } //end for
+ } while(numtriangles);
+ for (i = 1; i < thworld.numtriangles; i++)
+ {
+ tri = &thworld.triangles[i];
+ if (tri->front && tri->back) continue;
+ //qprintf("\r%6d", numtriangles++);
+// if (!TH_FindTetrahedron1(tri, thtriangles))
+ {
+ if (!TH_FindTetrahedron2(tri, thtriangles))
+ {
+ continue;
+ } //end if
+ } //end if
+ numtriangles++;
+ //create a tetrahedron from the triangles
+ TH_CreateTetrahedron(thtriangles);
+ qprintf("\r%6d", thworld.numtetrahedrons);
+ } //end for
+ } while(numtriangles);
+ //
+ numtriangles = 0;
+ for (i = 1; i < thworld.numtriangles; i++)
+ {
+ tri = &thworld.triangles[i];
+ if (!tri->front && !tri->back) numtriangles++;
+ } //end for
+ Log_Print("\r%6d triangles with front only\n", numtriangles);
+ Log_Print("\r%6d tetrahedrons\n", thworld.numtetrahedrons-1);
+} //end of the function TH_TetrahedralDecomposition
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void TH_AASFaceVertex(aas_face_t *face, int index, vec3_t vertex)
+{
+ int edgenum, side;
+
+ edgenum = aasworld.edgeindex[face->firstedge + index];
+ side = edgenum < 0;
+ VectorCopy(aasworld.vertexes[aasworld.edges[abs(edgenum)].v[side]], vertex);
+} //end of the function TH_AASFaceVertex
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TH_Colinear(float *v0, float *v1, float *v2)
+{
+ vec3_t t1, t2, vcross;
+ float d;
+
+ VectorSubtract(v1, v0, t1);
+ VectorSubtract(v2, v0, t2);
+ CrossProduct (t1, t2, vcross);
+ d = VectorLength( vcross );
+
+ // if cross product is zero point is colinear
+ if (d < 10)
+ {
+ return true;
+ } //end if
+ return false;
+} //end of the function TH_Colinear
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void TH_FaceCenter(aas_face_t *face, vec3_t center)
+{
+ int i, edgenum, side;
+ aas_edge_t *edge;
+
+ VectorClear(center);
+ for (i = 0; i < face->numedges; i++)
+ {
+ edgenum = abs(aasworld.edgeindex[face->firstedge + i]);
+ side = edgenum < 0;
+ edge = &aasworld.edges[abs(edgenum)];
+ VectorAdd(aasworld.vertexes[edge->v[side]], center, center);
+ } //end for
+ VectorScale(center, 1.0 / face->numedges, center);
+} //end of the function TH_FaceCenter
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+th_triangle_t *TH_CreateAASFaceTriangles(aas_face_t *face)
+{
+ int i, first, verts[3], trinum;
+ vec3_t p0, p1, p2, p3, p4, center;
+ th_triangle_t *tri, *triangles;
+
+ triangles = NULL;
+ //find three points that are not colinear
+ for (i = 0; i < face->numedges; i++)
+ {
+ TH_AASFaceVertex(face, (face->numedges + i-2)%face->numedges, p0);
+ TH_AASFaceVertex(face, (face->numedges + i-1)%face->numedges, p1);
+ TH_AASFaceVertex(face, (i )%face->numedges, p2);
+ if (TH_Colinear(p2, p0, p1)) continue;
+ TH_AASFaceVertex(face, (i+1)%face->numedges, p3);
+ TH_AASFaceVertex(face, (i+2)%face->numedges, p4);
+ if (TH_Colinear(p2, p3, p4)) continue;
+ break;
+ } //end for
+ //if there are three points that are not colinear
+ if (i < face->numedges)
+ {
+ //normal triangulation
+ first = i; //left and right most point of three non-colinear points
+ TH_AASFaceVertex(face, first, p0);
+ verts[0] = TH_FindOrCreateVertex(p0);
+ for (i = 1; i < face->numedges-1; i++)
+ {
+ TH_AASFaceVertex(face, (first+i )%face->numedges, p1);
+ TH_AASFaceVertex(face, (first+i+1)%face->numedges, p2);
+ verts[1] = TH_FindOrCreateVertex(p1);
+ verts[2] = TH_FindOrCreateVertex(p2);
+ trinum = TH_CreateTriangle(verts);
+ tri = &thworld.triangles[trinum];
+ tri->front = -1;
+ TH_AddTriangleToList(&triangles, tri);
+ } //end for
+ } //end if
+ else
+ {
+ //fan triangulation
+ TH_FaceCenter(face, center);
+ //
+ verts[0] = TH_FindOrCreateVertex(center);
+ for (i = 0; i < face->numedges; i++)
+ {
+ TH_AASFaceVertex(face, (i )%face->numedges, p1);
+ TH_AASFaceVertex(face, (i+1)%face->numedges, p2);
+ if (TH_Colinear(center, p1, p2)) continue;
+ verts[1] = TH_FindOrCreateVertex(p1);
+ verts[2] = TH_FindOrCreateVertex(p2);
+ trinum = TH_CreateTriangle(verts);
+ tri = &thworld.triangles[trinum];
+ tri->front = -1;
+ TH_AddTriangleToList(&triangles, tri);
+ } //end for
+ } //end else
+ return triangles;
+} //end of the function TH_CreateAASFaceTriangles
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+th_triangle_t *TH_AASToTriangleMesh(void)
+{
+ int i, j, facenum, otherareanum;
+ aas_face_t *face;
+ th_triangle_t *tri, *nexttri, *triangles;
+
+ triangles = NULL;
+ for (i = 1; i < aasworld.numareas; i++)
+ {
+ //if (!(aasworld.areasettings[i].presencetype & PRESENCE_NORMAL)) continue;
+ for (j = 0; j < aasworld.areas[i].numfaces; j++)
+ {
+ facenum = abs(aasworld.faceindex[aasworld.areas[i].firstface + j]);
+ face = &aasworld.faces[facenum];
+ //only convert solid faces into triangles
+ if (!(face->faceflags & FACE_SOLID))
+ {
+ /*
+ if (face->frontarea == i) otherareanum = face->backarea;
+ else otherareanum = face->frontarea;
+ if (aasworld.areasettings[otherareanum].presencetype & PRESENCE_NORMAL) continue;
+ */
+ continue;
+ } //end if
+ //
+ tri = TH_CreateAASFaceTriangles(face);
+ for (; tri; tri = nexttri)
+ {
+ nexttri = tri->next;
+ TH_AddTriangleToList(&triangles, tri);
+ } //end for
+ } //end if
+ } //end for
+ return triangles;
+} //end of the function TH_AASToTriangleMesh
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void TH_AASToTetrahedrons(char *filename)
+{
+ th_triangle_t *triangles, *tri, *lasttri;
+ int cnt;
+
+ if (!AAS_LoadAASFile(filename, 0, 0))
+ Error("couldn't load %s\n", filename);
+
+ //
+ TH_InitMaxTH();
+ //create a triangle mesh from the solid faces in the AAS file
+ triangles = TH_AASToTriangleMesh();
+ //
+ cnt = 0;
+ lasttri = NULL;
+ for (tri = triangles; tri; tri = tri->next)
+ {
+ cnt++;
+ if (tri->prev != lasttri) Log_Print("BAH\n");
+ lasttri = tri;
+ } //end for
+ Log_Print("%6d triangles\n", cnt);
+ //create a tetrahedral decomposition of the world bounded by triangles
+ TH_TetrahedralDecomposition(triangles);
+ //
+ TH_FreeMaxTH();
+} //end of the function TH_AASToTetrahedrons
diff --git a/code/bspc/tetrahedron.h b/code/bspc/tetrahedron.h
new file mode 100755
index 0000000..89003f1
--- /dev/null
+++ b/code/bspc/tetrahedron.h
@@ -0,0 +1,24 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+void TH_AASToTetrahedrons(char *filename);
+
diff --git a/code/bspc/textures.c b/code/bspc/textures.c
new file mode 100755
index 0000000..ad6a8f5
--- /dev/null
+++ b/code/bspc/textures.c
@@ -0,0 +1,228 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+#include "l_bsp_q2.h"
+
+int nummiptex;
+textureref_t textureref[MAX_MAP_TEXTURES];
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int FindMiptex (char *name)
+{
+ int i;
+ char path[1024];
+ miptex_t *mt;
+
+ for (i = 0; i < nummiptex; i++)
+ {
+ if (!strcmp (name, textureref[i].name))
+ {
+ return i;
+ } //end if
+ } //end for
+ if (nummiptex == MAX_MAP_TEXTURES)
+ Error ("MAX_MAP_TEXTURES");
+ strcpy (textureref[i].name, name);
+
+ // load the miptex to get the flags and values
+ sprintf (path, "%stextures/%s.wal", gamedir, name);
+ if (TryLoadFile (path, (void **)&mt) != -1)
+ {
+ textureref[i].value = LittleLong (mt->value);
+ textureref[i].flags = LittleLong (mt->flags);
+ textureref[i].contents = LittleLong (mt->contents);
+ strcpy (textureref[i].animname, mt->animname);
+ FreeMemory(mt);
+ } //end if
+ nummiptex++;
+
+ if (textureref[i].animname[0])
+ FindMiptex (textureref[i].animname);
+
+ return i;
+} //end of the function FindMipTex
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+vec3_t baseaxis[18] =
+{
+{0,0,1}, {1,0,0}, {0,-1,0}, // floor
+{0,0,-1}, {1,0,0}, {0,-1,0}, // ceiling
+{1,0,0}, {0,1,0}, {0,0,-1}, // west wall
+{-1,0,0}, {0,1,0}, {0,0,-1}, // east wall
+{0,1,0}, {1,0,0}, {0,0,-1}, // south wall
+{0,-1,0}, {1,0,0}, {0,0,-1} // north wall
+};
+
+void TextureAxisFromPlane(plane_t *pln, vec3_t xv, vec3_t yv)
+{
+ int bestaxis;
+ vec_t dot,best;
+ int i;
+
+ best = 0;
+ bestaxis = 0;
+
+ for (i=0 ; i<6 ; i++)
+ {
+ dot = DotProduct (pln->normal, baseaxis[i*3]);
+ if (dot > best)
+ {
+ best = dot;
+ bestaxis = i;
+ }
+ }
+
+ VectorCopy (baseaxis[bestaxis*3+1], xv);
+ VectorCopy (baseaxis[bestaxis*3+2], yv);
+} //end of the function TextureAxisFromPlane
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+int TexinfoForBrushTexture(plane_t *plane, brush_texture_t *bt, vec3_t origin)
+{
+ vec3_t vecs[2];
+ int sv, tv;
+ vec_t ang, sinv, cosv;
+ vec_t ns, nt;
+ texinfo_t tx, *tc;
+ int i, j, k;
+ float shift[2];
+ brush_texture_t anim;
+ int mt;
+
+ if (!bt->name[0])
+ return 0;
+
+ memset (&tx, 0, sizeof(tx));
+ strcpy (tx.texture, bt->name);
+
+ TextureAxisFromPlane(plane, vecs[0], vecs[1]);
+
+ shift[0] = DotProduct (origin, vecs[0]);
+ shift[1] = DotProduct (origin, vecs[1]);
+
+ if (!bt->scale[0])
+ bt->scale[0] = 1;
+ if (!bt->scale[1])
+ bt->scale[1] = 1;
+
+
+// rotate axis
+ if (bt->rotate == 0)
+ { sinv = 0 ; cosv = 1; }
+ else if (bt->rotate == 90)
+ { sinv = 1 ; cosv = 0; }
+ else if (bt->rotate == 180)
+ { sinv = 0 ; cosv = -1; }
+ else if (bt->rotate == 270)
+ { sinv = -1 ; cosv = 0; }
+ else
+ {
+ ang = bt->rotate / 180 * Q_PI;
+ sinv = sin(ang);
+ cosv = cos(ang);
+ }
+
+ if (vecs[0][0])
+ sv = 0;
+ else if (vecs[0][1])
+ sv = 1;
+ else
+ sv = 2;
+
+ if (vecs[1][0])
+ tv = 0;
+ else if (vecs[1][1])
+ tv = 1;
+ else
+ tv = 2;
+
+ for (i=0 ; i<2 ; i++)
+ {
+ ns = cosv * vecs[i][sv] - sinv * vecs[i][tv];
+ nt = sinv * vecs[i][sv] + cosv * vecs[i][tv];
+ vecs[i][sv] = ns;
+ vecs[i][tv] = nt;
+ }
+
+ for (i=0 ; i<2 ; i++)
+ for (j=0 ; j<3 ; j++)
+ tx.vecs[i][j] = vecs[i][j] / bt->scale[i];
+
+ tx.vecs[0][3] = bt->shift[0] + shift[0];
+ tx.vecs[1][3] = bt->shift[1] + shift[1];
+ tx.flags = bt->flags;
+ tx.value = bt->value;
+
+ //
+ // find the texinfo
+ //
+ tc = texinfo;
+ for (i=0 ; i<numtexinfo ; i++, tc++)
+ {
+ if (tc->flags != tx.flags)
+ continue;
+ if (tc->value != tx.value)
+ continue;
+ for (j=0 ; j<2 ; j++)
+ {
+ if (strcmp (tc->texture, tx.texture))
+ goto skip;
+ for (k=0 ; k<4 ; k++)
+ {
+ if (tc->vecs[j][k] != tx.vecs[j][k])
+ goto skip;
+ }
+ }
+ return i;
+skip:;
+ }
+ *tc = tx;
+ numtexinfo++;
+
+ // load the next animation
+ mt = FindMiptex (bt->name);
+ if (textureref[mt].animname[0])
+ {
+ anim = *bt;
+ strcpy (anim.name, textureref[mt].animname);
+ tc->nexttexinfo = TexinfoForBrushTexture (plane, &anim, origin);
+ }
+ else
+ tc->nexttexinfo = -1;
+
+
+ return i;
+} //end of the function TexinfoForBrushTexture
diff --git a/code/bspc/tree.c b/code/bspc/tree.c
new file mode 100755
index 0000000..3d2ee9c
--- /dev/null
+++ b/code/bspc/tree.c
@@ -0,0 +1,283 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+
+extern int c_nodes;
+int c_pruned;
+int freedtreemem = 0;
+
+void RemovePortalFromNode (portal_t *portal, node_t *l);
+
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+node_t *NodeForPoint (node_t *node, vec3_t origin)
+{
+ plane_t *plane;
+ vec_t d;
+
+ while (node->planenum != PLANENUM_LEAF)
+ {
+ plane = &mapplanes[node->planenum];
+ d = DotProduct (origin, plane->normal) - plane->dist;
+ if (d >= 0)
+ node = node->children[0];
+ else
+ node = node->children[1];
+ }
+ return node;
+} //end of the function NodeForPoint
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Tree_FreePortals_r (node_t *node)
+{
+ portal_t *p, *nextp;
+ int s;
+
+ // free children
+ if (node->planenum != PLANENUM_LEAF)
+ {
+ Tree_FreePortals_r(node->children[0]);
+ Tree_FreePortals_r(node->children[1]);
+ }
+
+ // free portals
+ for (p = node->portals; p; p = nextp)
+ {
+ s = (p->nodes[1] == node);
+ nextp = p->next[s];
+
+ RemovePortalFromNode (p, p->nodes[!s]);
+#ifdef ME
+ if (p->winding) freedtreemem += MemorySize(p->winding);
+ freedtreemem += MemorySize(p);
+#endif //ME
+ FreePortal(p);
+ }
+ node->portals = NULL;
+} //end of the function Tree_FreePortals_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Tree_Free_r (node_t *node)
+{
+// face_t *f, *nextf;
+ bspbrush_t *brush, *nextbrush;
+
+ //free children
+ if (node->planenum != PLANENUM_LEAF)
+ {
+ Tree_Free_r (node->children[0]);
+ Tree_Free_r (node->children[1]);
+ } //end if
+ //free bspbrushes
+// FreeBrushList (node->brushlist);
+ for (brush = node->brushlist; brush; brush = nextbrush)
+ {
+ nextbrush = brush->next;
+#ifdef ME
+ freedtreemem += MemorySize(brush);
+#endif //ME
+ FreeBrush(brush);
+ } //end for
+ node->brushlist = NULL;
+
+ /*
+ NOTE: only used when creating Q2 bsp
+ // free faces
+ for (f = node->faces; f; f = nextf)
+ {
+ nextf = f->next;
+#ifdef ME
+ if (f->w) freedtreemem += MemorySize(f->w);
+ freedtreemem += sizeof(face_t);
+#endif //ME
+ FreeFace(f);
+ } //end for
+ */
+
+ // free the node
+ if (node->volume)
+ {
+#ifdef ME
+ freedtreemem += MemorySize(node->volume);
+#endif //ME
+ FreeBrush (node->volume);
+ } //end if
+
+ if (numthreads == 1) c_nodes--;
+#ifdef ME
+ freedtreemem += MemorySize(node);
+#endif //ME
+ FreeMemory(node);
+} //end of the function Tree_Free_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Tree_Free(tree_t *tree)
+{
+ //if no tree just return
+ if (!tree) return;
+ //
+ freedtreemem = 0;
+ //
+ Tree_FreePortals_r(tree->headnode);
+ Tree_Free_r(tree->headnode);
+#ifdef ME
+ freedtreemem += MemorySize(tree);
+#endif //ME
+ FreeMemory(tree);
+#ifdef ME
+ Log_Print("freed ");
+ PrintMemorySize(freedtreemem);
+ Log_Print(" of tree memory\n");
+#endif //ME
+} //end of the function Tree_Free
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+tree_t *Tree_Alloc(void)
+{
+ tree_t *tree;
+
+ tree = GetMemory(sizeof(*tree));
+ memset (tree, 0, sizeof(*tree));
+ ClearBounds (tree->mins, tree->maxs);
+
+ return tree;
+} //end of the function Tree_Alloc
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Tree_Print_r (node_t *node, int depth)
+{
+ int i;
+ plane_t *plane;
+ bspbrush_t *bb;
+
+ for (i=0 ; i<depth ; i++)
+ printf (" ");
+ if (node->planenum == PLANENUM_LEAF)
+ {
+ if (!node->brushlist)
+ printf ("NULL\n");
+ else
+ {
+ for (bb=node->brushlist ; bb ; bb=bb->next)
+ printf ("%i ", bb->original->brushnum);
+ printf ("\n");
+ }
+ return;
+ }
+
+ plane = &mapplanes[node->planenum];
+ printf ("#%i (%5.2f %5.2f %5.2f):%5.2f\n", node->planenum,
+ plane->normal[0], plane->normal[1], plane->normal[2],
+ plane->dist);
+ Tree_Print_r (node->children[0], depth+1);
+ Tree_Print_r (node->children[1], depth+1);
+} //end of the function Tree_Print_r
+//===========================================================================
+// NODES THAT DON'T SEPERATE DIFFERENT CONTENTS CAN BE PRUNED
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Tree_PruneNodes_r (node_t *node)
+{
+ bspbrush_t *b, *next;
+
+ if (node->planenum == PLANENUM_LEAF) return;
+
+ Tree_PruneNodes_r (node->children[0]);
+ Tree_PruneNodes_r (node->children[1]);
+
+ if (create_aas)
+ {
+ if ((node->children[0]->contents & CONTENTS_LADDER) ||
+ (node->children[1]->contents & CONTENTS_LADDER)) return;
+ }
+
+ if ((node->children[0]->contents & CONTENTS_SOLID)
+ && (node->children[1]->contents & CONTENTS_SOLID))
+ {
+ if (node->faces)
+ Error ("node->faces seperating CONTENTS_SOLID");
+ if (node->children[0]->faces || node->children[1]->faces)
+ Error ("!node->faces with children");
+ // FIXME: free stuff
+ node->planenum = PLANENUM_LEAF;
+ node->contents = CONTENTS_SOLID;
+ node->detail_seperator = false;
+
+ if (node->brushlist)
+ Error ("PruneNodes: node->brushlist");
+ // combine brush lists
+ node->brushlist = node->children[1]->brushlist;
+
+ for (b = node->children[0]->brushlist; b; b = next)
+ {
+ next = b->next;
+ b->next = node->brushlist;
+ node->brushlist = b;
+ } //end for
+ //free the child nodes
+ FreeMemory(node->children[0]);
+ FreeMemory(node->children[1]);
+ //two nodes are cut away
+ c_pruned += 2;
+ } //end if
+} //end of the function Tree_PruneNodes_r
+//===========================================================================
+//
+// Parameter: -
+// Returns: -
+// Changes Globals: -
+//===========================================================================
+void Tree_PruneNodes(node_t *node)
+{
+ Log_Print("------- Prune Nodes --------\n");
+ c_pruned = 0;
+ Tree_PruneNodes_r(node);
+ Log_Print("%5i pruned nodes\n", c_pruned);
+} //end of the function Tree_PruneNodes
diff --git a/code/bspc/writebsp.c b/code/bspc/writebsp.c
new file mode 100755
index 0000000..38e9980
--- /dev/null
+++ b/code/bspc/writebsp.c
@@ -0,0 +1,595 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "qbsp.h"
+
+int c_nofaces;
+int c_facenodes;
+
+
+/*
+=========================================================
+
+ONLY SAVE OUT PLANES THAT ARE ACTUALLY USED AS NODES
+
+=========================================================
+*/
+
+int planeused[MAX_MAP_PLANES];
+
+/*
+============
+EmitPlanes
+
+There is no oportunity to discard planes, because all of the original
+brushes will be saved in the map.
+============
+*/
+void EmitPlanes (void)
+{
+ int i;
+ dplane_t *dp;
+ plane_t *mp;
+ //ME: this causes a crash??
+// int planetranslate[MAX_MAP_PLANES];
+
+ mp = mapplanes;
+ for (i=0 ; i<nummapplanes ; i++, mp++)
+ {
+ dp = &dplanes[numplanes];
+// planetranslate[i] = numplanes;
+ VectorCopy ( mp->normal, dp->normal);
+ dp->dist = mp->dist;
+ dp->type = mp->type;
+ numplanes++;
+ if (numplanes >= MAX_MAP_PLANES)
+ Error("MAX_MAP_PLANES");
+ }
+}
+
+
+//========================================================
+
+void EmitMarkFace (dleaf_t *leaf_p, face_t *f)
+{
+ int i;
+ int facenum;
+
+ while (f->merged)
+ f = f->merged;
+
+ if (f->split[0])
+ {
+ EmitMarkFace (leaf_p, f->split[0]);
+ EmitMarkFace (leaf_p, f->split[1]);
+ return;
+ }
+
+ facenum = f->outputnumber;
+ if (facenum == -1)
+ return; // degenerate face
+
+ if (facenum < 0 || facenum >= numfaces)
+ Error ("Bad leafface");
+ for (i=leaf_p->firstleafface ; i<numleaffaces ; i++)
+ if (dleaffaces[i] == facenum)
+ break; // merged out face
+ if (i == numleaffaces)
+ {
+ if (numleaffaces >= MAX_MAP_LEAFFACES)
+ Error ("MAX_MAP_LEAFFACES");
+
+ dleaffaces[numleaffaces] = facenum;
+ numleaffaces++;
+ }
+
+}
+
+
+/*
+==================
+EmitLeaf
+==================
+*/
+void EmitLeaf (node_t *node)
+{
+ dleaf_t *leaf_p;
+ portal_t *p;
+ int s;
+ face_t *f;
+ bspbrush_t *b;
+ int i;
+ int brushnum;
+
+ // emit a leaf
+ if (numleafs >= MAX_MAP_LEAFS)
+ Error ("MAX_MAP_LEAFS");
+
+ leaf_p = &dleafs[numleafs];
+ numleafs++;
+
+ leaf_p->contents = node->contents;
+ leaf_p->cluster = node->cluster;
+ leaf_p->area = node->area;
+
+ //
+ // write bounding box info
+ //
+ VectorCopy (node->mins, leaf_p->mins);
+ VectorCopy (node->maxs, leaf_p->maxs);
+
+ //
+ // write the leafbrushes
+ //
+ leaf_p->firstleafbrush = numleafbrushes;
+ for (b=node->brushlist ; b ; b=b->next)
+ {
+ if (numleafbrushes >= MAX_MAP_LEAFBRUSHES)
+ Error ("MAX_MAP_LEAFBRUSHES");
+
+ brushnum = b->original - mapbrushes;
+ for (i=leaf_p->firstleafbrush ; i<numleafbrushes ; i++)
+ if (dleafbrushes[i] == brushnum)
+ break;
+ if (i == numleafbrushes)
+ {
+ dleafbrushes[numleafbrushes] = brushnum;
+ numleafbrushes++;
+ }
+ }
+ leaf_p->numleafbrushes = numleafbrushes - leaf_p->firstleafbrush;
+
+ //
+ // write the leaffaces
+ //
+ if (leaf_p->contents & CONTENTS_SOLID)
+ return; // no leaffaces in solids
+
+ leaf_p->firstleafface = numleaffaces;
+
+ for (p = node->portals ; p ; p = p->next[s])
+ {
+ s = (p->nodes[1] == node);
+ f = p->face[s];
+ if (!f)
+ continue; // not a visible portal
+
+ EmitMarkFace (leaf_p, f);
+ }
+
+ leaf_p->numleaffaces = numleaffaces - leaf_p->firstleafface;
+}
+
+
+/*
+==================
+EmitFace
+==================
+*/
+void EmitFace (face_t *f)
+{
+ dface_t *df;
+ int i;
+ int e;
+
+ f->outputnumber = -1;
+
+ if (f->numpoints < 3)
+ {
+ return; // degenerated
+ }
+ if (f->merged || f->split[0] || f->split[1])
+ {
+ return; // not a final face
+ }
+
+ // save output number so leaffaces can use
+ f->outputnumber = numfaces;
+
+ if (numfaces >= MAX_MAP_FACES)
+ Error ("numfaces == MAX_MAP_FACES");
+ df = &dfaces[numfaces];
+ numfaces++;
+
+ // planenum is used by qlight, but not quake
+ df->planenum = f->planenum & (~1);
+ df->side = f->planenum & 1;
+
+ df->firstedge = numsurfedges;
+ df->numedges = f->numpoints;
+ df->texinfo = f->texinfo;
+ for (i=0 ; i<f->numpoints ; i++)
+ {
+// e = GetEdge (f->pts[i], f->pts[(i+1)%f->numpoints], f);
+ e = GetEdge2 (f->vertexnums[i], f->vertexnums[(i+1)%f->numpoints], f);
+ if (numsurfedges >= MAX_MAP_SURFEDGES)
+ Error ("numsurfedges == MAX_MAP_SURFEDGES");
+ dsurfedges[numsurfedges] = e;
+ numsurfedges++;
+ }
+}
+
+/*
+============
+EmitDrawingNode_r
+============
+*/
+int EmitDrawNode_r (node_t *node)
+{
+ dnode_t *n;
+ face_t *f;
+ int i;
+
+ if (node->planenum == PLANENUM_LEAF)
+ {
+ EmitLeaf (node);
+ return -numleafs;
+ }
+
+ // emit a node
+ if (numnodes == MAX_MAP_NODES)
+ Error ("MAX_MAP_NODES");
+ n = &dnodes[numnodes];
+ numnodes++;
+
+ VectorCopy (node->mins, n->mins);
+ VectorCopy (node->maxs, n->maxs);
+
+ planeused[node->planenum]++;
+ planeused[node->planenum^1]++;
+
+ if (node->planenum & 1)
+ Error ("WriteDrawNodes_r: odd planenum");
+ n->planenum = node->planenum;
+ n->firstface = numfaces;
+
+ if (!node->faces)
+ c_nofaces++;
+ else
+ c_facenodes++;
+
+ for (f=node->faces ; f ; f=f->next)
+ EmitFace (f);
+
+ n->numfaces = numfaces - n->firstface;
+
+
+ //
+ // recursively output the other nodes
+ //
+ for (i=0 ; i<2 ; i++)
+ {
+ if (node->children[i]->planenum == PLANENUM_LEAF)
+ {
+ n->children[i] = -(numleafs + 1);
+ EmitLeaf (node->children[i]);
+ }
+ else
+ {
+ n->children[i] = numnodes;
+ EmitDrawNode_r (node->children[i]);
+ }
+ }
+
+ return n - dnodes;
+}
+
+//=========================================================
+
+
+/*
+============
+WriteBSP
+============
+*/
+void WriteBSP (node_t *headnode)
+{
+ int oldfaces;
+
+ c_nofaces = 0;
+ c_facenodes = 0;
+
+ qprintf ("--- WriteBSP ---\n");
+
+ oldfaces = numfaces;
+ dmodels[nummodels].headnode = EmitDrawNode_r (headnode);
+ EmitAreaPortals (headnode);
+
+ qprintf ("%5i nodes with faces\n", c_facenodes);
+ qprintf ("%5i nodes without faces\n", c_nofaces);
+ qprintf ("%5i faces\n", numfaces-oldfaces);
+}
+
+//===========================================================
+
+/*
+============
+SetModelNumbers
+============
+*/
+void SetModelNumbers (void)
+{
+ int i;
+ int models;
+ char value[10];
+
+ models = 1;
+ for (i=1 ; i<num_entities ; i++)
+ {
+ if (entities[i].numbrushes)
+ {
+ sprintf (value, "*%i", models);
+ models++;
+ SetKeyValue (&entities[i], "model", value);
+ }
+ }
+
+}
+
+/*
+============
+SetLightStyles
+============
+*/
+#define MAX_SWITCHED_LIGHTS 32
+void SetLightStyles (void)
+{
+ int stylenum;
+ char *t;
+ entity_t *e;
+ int i, j;
+ char value[10];
+ char lighttargets[MAX_SWITCHED_LIGHTS][64];
+
+
+ // any light that is controlled (has a targetname)
+ // must have a unique style number generated for it
+
+ stylenum = 0;
+ for (i=1 ; i<num_entities ; i++)
+ {
+ e = &entities[i];
+
+ t = ValueForKey (e, "classname");
+ if (Q_strncasecmp (t, "light", 5))
+ continue;
+ t = ValueForKey (e, "targetname");
+ if (!t[0])
+ continue;
+
+ // find this targetname
+ for (j=0 ; j<stylenum ; j++)
+ if (!strcmp (lighttargets[j], t))
+ break;
+ if (j == stylenum)
+ {
+ if (stylenum == MAX_SWITCHED_LIGHTS)
+ Error ("stylenum == MAX_SWITCHED_LIGHTS");
+ strcpy (lighttargets[j], t);
+ stylenum++;
+ }
+ sprintf (value, "%i", 32 + j);
+ SetKeyValue (e, "style", value);
+ }
+
+}
+
+//===========================================================
+
+/*
+============
+EmitBrushes
+============
+*/
+void EmitBrushes (void)
+{
+ int i, j, bnum, s, x;
+ dbrush_t *db;
+ mapbrush_t *b;
+ dbrushside_t *cp;
+ vec3_t normal;
+ vec_t dist;
+ int planenum;
+
+ numbrushsides = 0;
+ numbrushes = nummapbrushes;
+
+ for (bnum=0 ; bnum<nummapbrushes ; bnum++)
+ {
+ b = &mapbrushes[bnum];
+ db = &dbrushes[bnum];
+
+ db->contents = b->contents;
+ db->firstside = numbrushsides;
+ db->numsides = b->numsides;
+ for (j=0 ; j<b->numsides ; j++)
+ {
+ if (numbrushsides == MAX_MAP_BRUSHSIDES)
+ Error ("MAX_MAP_BRUSHSIDES");
+ cp = &dbrushsides[numbrushsides];
+ numbrushsides++;
+ cp->planenum = b->original_sides[j].planenum;
+ cp->texinfo = b->original_sides[j].texinfo;
+ }
+
+#ifdef ME
+ //for collision detection, bounding boxes are axial :)
+ //brushes are convex so just add dot or line touching planes on the sides of
+ //the brush parallell to the axis planes
+#endif
+ // add any axis planes not contained in the brush to bevel off corners
+ for (x=0 ; x<3 ; x++)
+ for (s=-1 ; s<=1 ; s+=2)
+ {
+ // add the plane
+ VectorCopy (vec3_origin, normal);
+ normal[x] = s;
+ if (s == -1)
+ dist = -b->mins[x];
+ else
+ dist = b->maxs[x];
+ planenum = FindFloatPlane (normal, dist);
+ for (i=0 ; i<b->numsides ; i++)
+ if (b->original_sides[i].planenum == planenum)
+ break;
+ if (i == b->numsides)
+ {
+ if (numbrushsides >= MAX_MAP_BRUSHSIDES)
+ Error ("MAX_MAP_BRUSHSIDES");
+
+ dbrushsides[numbrushsides].planenum = planenum;
+ dbrushsides[numbrushsides].texinfo =
+ dbrushsides[numbrushsides-1].texinfo;
+ numbrushsides++;
+ db->numsides++;
+ }
+ }
+
+ }
+
+}
+
+//===========================================================
+
+/*
+==================
+BeginBSPFile
+==================
+*/
+void BeginBSPFile (void)
+{
+ // these values may actually be initialized
+ // if the file existed when loaded, so clear them explicitly
+ nummodels = 0;
+ numfaces = 0;
+ numnodes = 0;
+ numbrushsides = 0;
+ numvertexes = 0;
+ numleaffaces = 0;
+ numleafbrushes = 0;
+ numsurfedges = 0;
+
+ // edge 0 is not used, because 0 can't be negated
+ numedges = 1;
+
+ // leave vertex 0 as an error
+ numvertexes = 1;
+
+ // leave leaf 0 as an error
+ numleafs = 1;
+ dleafs[0].contents = CONTENTS_SOLID;
+}
+
+
+/*
+============
+EndBSPFile
+============
+*/
+void EndBSPFile (void)
+{
+#if 0
+ char path[1024];
+ int len;
+ byte *buf;
+#endif
+
+
+ EmitBrushes ();
+ EmitPlanes ();
+ Q2_UnparseEntities ();
+
+ // load the pop
+#if 0
+ sprintf (path, "%s/pics/pop.lmp", gamedir);
+ len = LoadFile (path, &buf);
+ memcpy (dpop, buf, sizeof(dpop));
+ FreeMemory(buf);
+#endif
+}
+
+
+/*
+==================
+BeginModel
+==================
+*/
+int firstmodleaf;
+extern int firstmodeledge;
+extern int firstmodelface;
+void BeginModel (void)
+{
+ dmodel_t *mod;
+ int start, end;
+ mapbrush_t *b;
+ int j;
+ entity_t *e;
+ vec3_t mins, maxs;
+
+ if (nummodels == MAX_MAP_MODELS)
+ Error ("MAX_MAP_MODELS");
+ mod = &dmodels[nummodels];
+
+ mod->firstface = numfaces;
+
+ firstmodleaf = numleafs;
+ firstmodeledge = numedges;
+ firstmodelface = numfaces;
+
+ //
+ // bound the brushes
+ //
+ e = &entities[entity_num];
+
+ start = e->firstbrush;
+ end = start + e->numbrushes;
+ ClearBounds (mins, maxs);
+
+ for (j=start ; j<end ; j++)
+ {
+ b = &mapbrushes[j];
+ if (!b->numsides)
+ continue; // not a real brush (origin brush)
+ AddPointToBounds (b->mins, mins, maxs);
+ AddPointToBounds (b->maxs, mins, maxs);
+ }
+
+ VectorCopy (mins, mod->mins);
+ VectorCopy (maxs, mod->maxs);
+}
+
+
+/*
+==================
+EndModel
+==================
+*/
+void EndModel (void)
+{
+ dmodel_t *mod;
+
+ mod = &dmodels[nummodels];
+
+ mod->numfaces = numfaces - mod->firstface;
+
+ nummodels++;
+}
+
diff --git a/code/cgame.lnt b/code/cgame.lnt
new file mode 100755
index 0000000..e1801aa
--- /dev/null
+++ b/code/cgame.lnt
@@ -0,0 +1,25 @@
+opts.lnt
+
+game\bg_misc.c
+game\bg_pmove.c
+game\q_math.c
+game\q_shared.c
+cgame\cg_consolecmds.c
+cgame\cg_draw.c
+cgame\cg_drawtools.c
+cgame\cg_effects.c
+cgame\cg_ents.c
+cgame\cg_event.c
+cgame\cg_info.c
+cgame\cg_localents.c
+cgame\cg_main.c
+cgame\cg_marks.c
+cgame\cg_players.c
+cgame\cg_playerstate.c
+cgame\cg_predict.c
+cgame\cg_scoreboard.c
+cgame\cg_servercmds.c
+cgame\cg_snapshot.c
+cgame\cg_syscalls.c
+cgame\cg_view.c
+cgame\cg_weapons.c
diff --git a/code/cgame/Conscript b/code/cgame/Conscript
new file mode 100755
index 0000000..887a2a1
--- /dev/null
+++ b/code/cgame/Conscript
@@ -0,0 +1,138 @@
+# cgame building
+# builds the cgame for vanilla Q3 and TA
+
+# there are slight differences between Q3 and TA build:
+# -DMISSIONPACK
+# TA has cg_newdraw.c and ../ui/ui_shared.c
+# the config is passed in the imported variable TARGET_DIR
+
+# qvm building against native:
+# only native has cg_syscalls.c
+# only qvm has ../game/bg_lib.c
+# qvm uses a custom cg_syscalls.asm with equ stubs
+
+Import qw( BASE_CFLAGS TARGET_DIR INSTALL_DIR NO_VM NO_SO CC CXX LINK );
+
+$env = new cons(
+ # the code has the very bad habit of doing things like #include "../ui/ui_shared.h"
+ # this seems to confuse the dependency analysis, explicit toplevel includes seem to fix
+ CPPPATH => '#cgame:#game:#q3_ui',
+ CC => $CC,
+ CXX => $CXX,
+ LINK => $LINK,
+ ENV => { PATH => $ENV{PATH}, HOME => $ENV{HOME} },
+ CFLAGS => $BASE_CFLAGS . '-fPIC',
+ LDFLAGS => '-shared -ldl -lm'
+);
+
+# for TA, use -DMISSIONPACK
+%ta_env_hash = $env->copy(
+ CPPPATH => '#cgame:#game:#ui'
+ );
+$ta_env_hash{CFLAGS} = '-DMISSIONPACK ' . $ta_env_hash{CFLAGS};
+$ta_env = new cons(%ta_env_hash);
+
+# qvm building
+# we heavily customize the cons environment
+$vm_env = new cons(
+ # the code has the very bad habit of doing things like #include "../ui/ui_shared.h"
+ # this seems to confuse the dependency analysis, explicit toplevel includes seem to fix
+ CPPPATH => '#cgame:#game:#q3_ui',
+ CC => 'q3lcc',
+ CCCOM => '%CC %CFLAGS %_IFLAGS -c %< -o %>',
+ SUFOBJ => '.asm',
+ LINK => 'q3asm',
+ CFLAGS => '-DQ3_VM -DCGAME -S -Wf-target=bytecode -Wf-g',
+ # need to know where to find the compiler tools
+ ENV => { PATH => $ENV{PATH} . ":./qvmtools", },
+);
+
+# TA qvm building
+%vm_ta_env_hash = $vm_env->copy(
+ CPPPATH => '#cgame:#game:#ui'
+ );
+$vm_ta_env_hash{CFLAGS} = '-DMISSIONPACK ' . $vm_ta_env_hash{CFLAGS};
+$vm_ta_env = new cons(%vm_ta_env_hash);
+
+# the file with vmMain function MUST be the first one of the list
+@FILES = qw(
+ cg_main.c
+ ../game/bg_misc.c
+ ../game/bg_pmove.c
+ ../game/bg_slidemove.c
+ ../game/q_math.c
+ ../game/q_shared.c
+ cg_consolecmds.c
+ cg_draw.c
+ cg_drawtools.c
+ cg_effects.c
+ cg_ents.c
+ cg_event.c
+ cg_info.c
+ cg_localents.c
+ cg_marks.c
+ cg_players.c
+ cg_playerstate.c
+ cg_predict.c
+ cg_scoreboard.c
+ cg_servercmds.c
+ cg_snapshot.c
+ cg_view.c
+ cg_weapons.c
+ );
+$FILESREF = \@FILES;
+
+# only in .so
+# (VM uses a custom .asm with equ stubs)
+@SO_FILES = qw(
+ cg_syscalls.c
+ );
+$SO_FILESREF = \@SO_FILES;
+
+# only for VM
+@VM_FILES = qw(
+ ../game/bg_lib.c
+ cg_syscalls.asm
+ );
+$VM_FILESREF = \@VM_FILES;
+
+# common additionals for TA
+@TA_FILES = qw(
+ cg_newdraw.c
+ ../ui/ui_shared.c
+ );
+$TA_FILESREF = \@TA_FILES;
+
+# FIXME CPU string
+if ($TARGET_DIR eq 'Q3')
+{
+ if ($NO_SO eq 0)
+ {
+ Program $env 'cgamei386.so', @$FILESREF, @$SO_FILESREF;
+ Install $env $INSTALL_DIR, 'cgamei386.so';
+ }
+ if ($NO_VM eq 0)
+ {
+ Depends $vm_env 'cgame.qvm', '#qvmtools/q3lcc';
+ Depends $vm_env 'cgame.qvm', '#qvmtools/q3asm';
+ Program $vm_env 'cgame.qvm', @$FILESREF, @$VM_FILESREF;
+ Install $vm_env $INSTALL_DIR . '/vm', 'cgame.qvm';
+ }
+}
+else
+{
+ if ($NO_SO eq 0)
+ {
+ Program $ta_env 'cgamei386.so',
+ @$FILESREF, @$SO_FILESREF, @$TA_FILESREF;
+ Install $ta_env $INSTALL_DIR, 'cgamei386.so';
+ }
+ if ($NO_VM eq 0)
+ {
+ Depends $vm_env 'cgame.qvm', '#qvmtools/q3lcc';
+ Depends $vm_env 'cgame.qvm', '#qvmtools/q3asm';
+ Program $vm_ta_env 'cgame.qvm',
+ @$FILESREF, @$VM_FILESREF, @$TA_FILESREF;
+ Install $vm_ta_env $INSTALL_DIR . '/vm', 'cgame.qvm';
+ }
+}
diff --git a/code/cgame/cg_consolecmds.c b/code/cgame/cg_consolecmds.c
new file mode 100755
index 0000000..6f13a22
--- /dev/null
+++ b/code/cgame/cg_consolecmds.c
@@ -0,0 +1,578 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// cg_consolecmds.c -- text commands typed in at the local console, or
+// executed by a key binding
+
+#include "cg_local.h"
+#include "../ui/ui_shared.h"
+#ifdef MISSIONPACK
+extern menuDef_t *menuScoreboard;
+#endif
+
+
+
+void CG_TargetCommand_f( void ) {
+ int targetNum;
+ char test[4];
+
+ targetNum = CG_CrosshairPlayer();
+ if (!targetNum ) {
+ return;
+ }
+
+ trap_Argv( 1, test, 4 );
+ trap_SendConsoleCommand( va( "gc %i %i", targetNum, atoi( test ) ) );
+}
+
+
+
+/*
+=================
+CG_SizeUp_f
+
+Keybinding command
+=================
+*/
+static void CG_SizeUp_f (void) {
+ trap_Cvar_Set("cg_viewsize", va("%i",(int)(cg_viewsize.integer+10)));
+}
+
+
+/*
+=================
+CG_SizeDown_f
+
+Keybinding command
+=================
+*/
+static void CG_SizeDown_f (void) {
+ trap_Cvar_Set("cg_viewsize", va("%i",(int)(cg_viewsize.integer-10)));
+}
+
+
+/*
+=============
+CG_Viewpos_f
+
+Debugging command to print the current position
+=============
+*/
+static void CG_Viewpos_f (void) {
+ CG_Printf ("(%i %i %i) : %i\n", (int)cg.refdef.vieworg[0],
+ (int)cg.refdef.vieworg[1], (int)cg.refdef.vieworg[2],
+ (int)cg.refdefViewAngles[YAW]);
+}
+
+
+static void CG_ScoresDown_f( void ) {
+
+#ifdef MISSIONPACK
+ CG_BuildSpectatorString();
+#endif
+ if ( cg.scoresRequestTime + 2000 < cg.time ) {
+ // the scores are more than two seconds out of data,
+ // so request new ones
+ cg.scoresRequestTime = cg.time;
+ trap_SendClientCommand( "score" );
+
+ // leave the current scores up if they were already
+ // displayed, but if this is the first hit, clear them out
+ if ( !cg.showScores ) {
+ cg.showScores = qtrue;
+ cg.numScores = 0;
+ }
+ } else {
+ // show the cached contents even if they just pressed if it
+ // is within two seconds
+ cg.showScores = qtrue;
+ }
+}
+
+static void CG_ScoresUp_f( void ) {
+ if ( cg.showScores ) {
+ cg.showScores = qfalse;
+ cg.scoreFadeTime = cg.time;
+ }
+}
+
+#ifdef MISSIONPACK
+extern menuDef_t *menuScoreboard;
+void Menu_Reset(); // FIXME: add to right include file
+
+static void CG_LoadHud_f( void) {
+ char buff[1024];
+ const char *hudSet;
+ memset(buff, 0, sizeof(buff));
+
+ String_Init();
+ Menu_Reset();
+
+ trap_Cvar_VariableStringBuffer("cg_hudFiles", buff, sizeof(buff));
+ hudSet = buff;
+ if (hudSet[0] == '\0') {
+ hudSet = "ui/hud.txt";
+ }
+
+ CG_LoadMenus(hudSet);
+ menuScoreboard = NULL;
+}
+
+
+static void CG_scrollScoresDown_f( void) {
+ if (menuScoreboard && cg.scoreBoardShowing) {
+ Menu_ScrollFeeder(menuScoreboard, FEEDER_SCOREBOARD, qtrue);
+ Menu_ScrollFeeder(menuScoreboard, FEEDER_REDTEAM_LIST, qtrue);
+ Menu_ScrollFeeder(menuScoreboard, FEEDER_BLUETEAM_LIST, qtrue);
+ }
+}
+
+
+static void CG_scrollScoresUp_f( void) {
+ if (menuScoreboard && cg.scoreBoardShowing) {
+ Menu_ScrollFeeder(menuScoreboard, FEEDER_SCOREBOARD, qfalse);
+ Menu_ScrollFeeder(menuScoreboard, FEEDER_REDTEAM_LIST, qfalse);
+ Menu_ScrollFeeder(menuScoreboard, FEEDER_BLUETEAM_LIST, qfalse);
+ }
+}
+
+
+static void CG_spWin_f( void) {
+ trap_Cvar_Set("cg_cameraOrbit", "2");
+ trap_Cvar_Set("cg_cameraOrbitDelay", "35");
+ trap_Cvar_Set("cg_thirdPerson", "1");
+ trap_Cvar_Set("cg_thirdPersonAngle", "0");
+ trap_Cvar_Set("cg_thirdPersonRange", "100");
+ CG_AddBufferedSound(cgs.media.winnerSound);
+ //trap_S_StartLocalSound(cgs.media.winnerSound, CHAN_ANNOUNCER);
+ CG_CenterPrint("YOU WIN!", SCREEN_HEIGHT * .30, 0);
+}
+
+static void CG_spLose_f( void) {
+ trap_Cvar_Set("cg_cameraOrbit", "2");
+ trap_Cvar_Set("cg_cameraOrbitDelay", "35");
+ trap_Cvar_Set("cg_thirdPerson", "1");
+ trap_Cvar_Set("cg_thirdPersonAngle", "0");
+ trap_Cvar_Set("cg_thirdPersonRange", "100");
+ CG_AddBufferedSound(cgs.media.loserSound);
+ //trap_S_StartLocalSound(cgs.media.loserSound, CHAN_ANNOUNCER);
+ CG_CenterPrint("YOU LOSE...", SCREEN_HEIGHT * .30, 0);
+}
+
+#endif
+
+static void CG_TellTarget_f( void ) {
+ int clientNum;
+ char command[128];
+ char message[128];
+
+ clientNum = CG_CrosshairPlayer();
+ if ( clientNum == -1 ) {
+ return;
+ }
+
+ trap_Args( message, 128 );
+ Com_sprintf( command, 128, "tell %i %s", clientNum, message );
+ trap_SendClientCommand( command );
+}
+
+static void CG_TellAttacker_f( void ) {
+ int clientNum;
+ char command[128];
+ char message[128];
+
+ clientNum = CG_LastAttacker();
+ if ( clientNum == -1 ) {
+ return;
+ }
+
+ trap_Args( message, 128 );
+ Com_sprintf( command, 128, "tell %i %s", clientNum, message );
+ trap_SendClientCommand( command );
+}
+
+static void CG_VoiceTellTarget_f( void ) {
+ int clientNum;
+ char command[128];
+ char message[128];
+
+ clientNum = CG_CrosshairPlayer();
+ if ( clientNum == -1 ) {
+ return;
+ }
+
+ trap_Args( message, 128 );
+ Com_sprintf( command, 128, "vtell %i %s", clientNum, message );
+ trap_SendClientCommand( command );
+}
+
+static void CG_VoiceTellAttacker_f( void ) {
+ int clientNum;
+ char command[128];
+ char message[128];
+
+ clientNum = CG_LastAttacker();
+ if ( clientNum == -1 ) {
+ return;
+ }
+
+ trap_Args( message, 128 );
+ Com_sprintf( command, 128, "vtell %i %s", clientNum, message );
+ trap_SendClientCommand( command );
+}
+
+#ifdef MISSIONPACK
+static void CG_NextTeamMember_f( void ) {
+ CG_SelectNextPlayer();
+}
+
+static void CG_PrevTeamMember_f( void ) {
+ CG_SelectPrevPlayer();
+}
+
+// ASS U ME's enumeration order as far as task specific orders, OFFENSE is zero, CAMP is last
+//
+static void CG_NextOrder_f( void ) {
+ clientInfo_t *ci = cgs.clientinfo + cg.snap->ps.clientNum;
+ if (ci) {
+ if (!ci->teamLeader && sortedTeamPlayers[cg_currentSelectedPlayer.integer] != cg.snap->ps.clientNum) {
+ return;
+ }
+ }
+ if (cgs.currentOrder < TEAMTASK_CAMP) {
+ cgs.currentOrder++;
+
+ if (cgs.currentOrder == TEAMTASK_RETRIEVE) {
+ if (!CG_OtherTeamHasFlag()) {
+ cgs.currentOrder++;
+ }
+ }
+
+ if (cgs.currentOrder == TEAMTASK_ESCORT) {
+ if (!CG_YourTeamHasFlag()) {
+ cgs.currentOrder++;
+ }
+ }
+
+ } else {
+ cgs.currentOrder = TEAMTASK_OFFENSE;
+ }
+ cgs.orderPending = qtrue;
+ cgs.orderTime = cg.time + 3000;
+}
+
+
+static void CG_ConfirmOrder_f (void ) {
+ trap_SendConsoleCommand(va("cmd vtell %d %s\n", cgs.acceptLeader, VOICECHAT_YES));
+ trap_SendConsoleCommand("+button5; wait; -button5");
+ if (cg.time < cgs.acceptOrderTime) {
+ trap_SendClientCommand(va("teamtask %d\n", cgs.acceptTask));
+ cgs.acceptOrderTime = 0;
+ }
+}
+
+static void CG_DenyOrder_f (void ) {
+ trap_SendConsoleCommand(va("cmd vtell %d %s\n", cgs.acceptLeader, VOICECHAT_NO));
+ trap_SendConsoleCommand("+button6; wait; -button6");
+ if (cg.time < cgs.acceptOrderTime) {
+ cgs.acceptOrderTime = 0;
+ }
+}
+
+static void CG_TaskOffense_f (void ) {
+ if (cgs.gametype == GT_CTF || cgs.gametype == GT_1FCTF) {
+ trap_SendConsoleCommand(va("cmd vsay_team %s\n", VOICECHAT_ONGETFLAG));
+ } else {
+ trap_SendConsoleCommand(va("cmd vsay_team %s\n", VOICECHAT_ONOFFENSE));
+ }
+ trap_SendClientCommand(va("teamtask %d\n", TEAMTASK_OFFENSE));
+}
+
+static void CG_TaskDefense_f (void ) {
+ trap_SendConsoleCommand(va("cmd vsay_team %s\n", VOICECHAT_ONDEFENSE));
+ trap_SendClientCommand(va("teamtask %d\n", TEAMTASK_DEFENSE));
+}
+
+static void CG_TaskPatrol_f (void ) {
+ trap_SendConsoleCommand(va("cmd vsay_team %s\n", VOICECHAT_ONPATROL));
+ trap_SendClientCommand(va("teamtask %d\n", TEAMTASK_PATROL));
+}
+
+static void CG_TaskCamp_f (void ) {
+ trap_SendConsoleCommand(va("cmd vsay_team %s\n", VOICECHAT_ONCAMPING));
+ trap_SendClientCommand(va("teamtask %d\n", TEAMTASK_CAMP));
+}
+
+static void CG_TaskFollow_f (void ) {
+ trap_SendConsoleCommand(va("cmd vsay_team %s\n", VOICECHAT_ONFOLLOW));
+ trap_SendClientCommand(va("teamtask %d\n", TEAMTASK_FOLLOW));
+}
+
+static void CG_TaskRetrieve_f (void ) {
+ trap_SendConsoleCommand(va("cmd vsay_team %s\n", VOICECHAT_ONRETURNFLAG));
+ trap_SendClientCommand(va("teamtask %d\n", TEAMTASK_RETRIEVE));
+}
+
+static void CG_TaskEscort_f (void ) {
+ trap_SendConsoleCommand(va("cmd vsay_team %s\n", VOICECHAT_ONFOLLOWCARRIER));
+ trap_SendClientCommand(va("teamtask %d\n", TEAMTASK_ESCORT));
+}
+
+static void CG_TaskOwnFlag_f (void ) {
+ trap_SendConsoleCommand(va("cmd vsay_team %s\n", VOICECHAT_IHAVEFLAG));
+}
+
+static void CG_TauntKillInsult_f (void ) {
+ trap_SendConsoleCommand("cmd vsay kill_insult\n");
+}
+
+static void CG_TauntPraise_f (void ) {
+ trap_SendConsoleCommand("cmd vsay praise\n");
+}
+
+static void CG_TauntTaunt_f (void ) {
+ trap_SendConsoleCommand("cmd vtaunt\n");
+}
+
+static void CG_TauntDeathInsult_f (void ) {
+ trap_SendConsoleCommand("cmd vsay death_insult\n");
+}
+
+static void CG_TauntGauntlet_f (void ) {
+ trap_SendConsoleCommand("cmd vsay kill_guantlet\n");
+}
+
+static void CG_TaskSuicide_f (void ) {
+ int clientNum;
+ char command[128];
+
+ clientNum = CG_CrosshairPlayer();
+ if ( clientNum == -1 ) {
+ return;
+ }
+
+ Com_sprintf( command, 128, "tell %i suicide", clientNum );
+ trap_SendClientCommand( command );
+}
+
+
+
+/*
+==================
+CG_TeamMenu_f
+==================
+*/
+/*
+static void CG_TeamMenu_f( void ) {
+ if (trap_Key_GetCatcher() & KEYCATCH_CGAME) {
+ CG_EventHandling(CGAME_EVENT_NONE);
+ trap_Key_SetCatcher(0);
+ } else {
+ CG_EventHandling(CGAME_EVENT_TEAMMENU);
+ //trap_Key_SetCatcher(KEYCATCH_CGAME);
+ }
+}
+*/
+
+/*
+==================
+CG_EditHud_f
+==================
+*/
+/*
+static void CG_EditHud_f( void ) {
+ //cls.keyCatchers ^= KEYCATCH_CGAME;
+ //VM_Call (cgvm, CG_EVENT_HANDLING, (cls.keyCatchers & KEYCATCH_CGAME) ? CGAME_EVENT_EDITHUD : CGAME_EVENT_NONE);
+}
+*/
+
+#endif
+
+/*
+==================
+CG_StartOrbit_f
+==================
+*/
+
+static void CG_StartOrbit_f( void ) {
+ char var[MAX_TOKEN_CHARS];
+
+ trap_Cvar_VariableStringBuffer( "developer", var, sizeof( var ) );
+ if ( !atoi(var) ) {
+ return;
+ }
+ if (cg_cameraOrbit.value != 0) {
+ trap_Cvar_Set ("cg_cameraOrbit", "0");
+ trap_Cvar_Set("cg_thirdPerson", "0");
+ } else {
+ trap_Cvar_Set("cg_cameraOrbit", "5");
+ trap_Cvar_Set("cg_thirdPerson", "1");
+ trap_Cvar_Set("cg_thirdPersonAngle", "0");
+ trap_Cvar_Set("cg_thirdPersonRange", "100");
+ }
+}
+
+/*
+static void CG_Camera_f( void ) {
+ char name[1024];
+ trap_Argv( 1, name, sizeof(name));
+ if (trap_loadCamera(name)) {
+ cg.cameraMode = qtrue;
+ trap_startCamera(cg.time);
+ } else {
+ CG_Printf ("Unable to load camera %s\n",name);
+ }
+}
+*/
+
+
+typedef struct {
+ char *cmd;
+ void (*function)(void);
+} consoleCommand_t;
+
+static consoleCommand_t commands[] = {
+ { "testgun", CG_TestGun_f },
+ { "testmodel", CG_TestModel_f },
+ { "nextframe", CG_TestModelNextFrame_f },
+ { "prevframe", CG_TestModelPrevFrame_f },
+ { "nextskin", CG_TestModelNextSkin_f },
+ { "prevskin", CG_TestModelPrevSkin_f },
+ { "viewpos", CG_Viewpos_f },
+ { "+scores", CG_ScoresDown_f },
+ { "-scores", CG_ScoresUp_f },
+ { "+zoom", CG_ZoomDown_f },
+ { "-zoom", CG_ZoomUp_f },
+ { "sizeup", CG_SizeUp_f },
+ { "sizedown", CG_SizeDown_f },
+ { "weapnext", CG_NextWeapon_f },
+ { "weapprev", CG_PrevWeapon_f },
+ { "weapon", CG_Weapon_f },
+ { "tell_target", CG_TellTarget_f },
+ { "tell_attacker", CG_TellAttacker_f },
+ { "vtell_target", CG_VoiceTellTarget_f },
+ { "vtell_attacker", CG_VoiceTellAttacker_f },
+ { "tcmd", CG_TargetCommand_f },
+#ifdef MISSIONPACK
+ { "loadhud", CG_LoadHud_f },
+ { "nextTeamMember", CG_NextTeamMember_f },
+ { "prevTeamMember", CG_PrevTeamMember_f },
+ { "nextOrder", CG_NextOrder_f },
+ { "confirmOrder", CG_ConfirmOrder_f },
+ { "denyOrder", CG_DenyOrder_f },
+ { "taskOffense", CG_TaskOffense_f },
+ { "taskDefense", CG_TaskDefense_f },
+ { "taskPatrol", CG_TaskPatrol_f },
+ { "taskCamp", CG_TaskCamp_f },
+ { "taskFollow", CG_TaskFollow_f },
+ { "taskRetrieve", CG_TaskRetrieve_f },
+ { "taskEscort", CG_TaskEscort_f },
+ { "taskSuicide", CG_TaskSuicide_f },
+ { "taskOwnFlag", CG_TaskOwnFlag_f },
+ { "tauntKillInsult", CG_TauntKillInsult_f },
+ { "tauntPraise", CG_TauntPraise_f },
+ { "tauntTaunt", CG_TauntTaunt_f },
+ { "tauntDeathInsult", CG_TauntDeathInsult_f },
+ { "tauntGauntlet", CG_TauntGauntlet_f },
+ { "spWin", CG_spWin_f },
+ { "spLose", CG_spLose_f },
+ { "scoresDown", CG_scrollScoresDown_f },
+ { "scoresUp", CG_scrollScoresUp_f },
+#endif
+ { "startOrbit", CG_StartOrbit_f },
+ //{ "camera", CG_Camera_f },
+ { "loaddeferred", CG_LoadDeferredPlayers }
+};
+
+
+/*
+=================
+CG_ConsoleCommand
+
+The string has been tokenized and can be retrieved with
+Cmd_Argc() / Cmd_Argv()
+=================
+*/
+qboolean CG_ConsoleCommand( void ) {
+ const char *cmd;
+ int i;
+
+ cmd = CG_Argv(0);
+
+ for ( i = 0 ; i < sizeof( commands ) / sizeof( commands[0] ) ; i++ ) {
+ if ( !Q_stricmp( cmd, commands[i].cmd ) ) {
+ commands[i].function();
+ return qtrue;
+ }
+ }
+
+ return qfalse;
+}
+
+
+/*
+=================
+CG_InitConsoleCommands
+
+Let the client system know about all of our commands
+so it can perform tab completion
+=================
+*/
+void CG_InitConsoleCommands( void ) {
+ int i;
+
+ for ( i = 0 ; i < sizeof( commands ) / sizeof( commands[0] ) ; i++ ) {
+ trap_AddCommand( commands[i].cmd );
+ }
+
+ //
+ // the game server will interpret these commands, which will be automatically
+ // forwarded to the server after they are not recognized locally
+ //
+ trap_AddCommand ("kill");
+ trap_AddCommand ("say");
+ trap_AddCommand ("say_team");
+ trap_AddCommand ("tell");
+ trap_AddCommand ("vsay");
+ trap_AddCommand ("vsay_team");
+ trap_AddCommand ("vtell");
+ trap_AddCommand ("vtaunt");
+ trap_AddCommand ("vosay");
+ trap_AddCommand ("vosay_team");
+ trap_AddCommand ("votell");
+ trap_AddCommand ("give");
+ trap_AddCommand ("god");
+ trap_AddCommand ("notarget");
+ trap_AddCommand ("noclip");
+ trap_AddCommand ("team");
+ trap_AddCommand ("follow");
+ trap_AddCommand ("levelshot");
+ trap_AddCommand ("addbot");
+ trap_AddCommand ("setviewpos");
+ trap_AddCommand ("callvote");
+ trap_AddCommand ("vote");
+ trap_AddCommand ("callteamvote");
+ trap_AddCommand ("teamvote");
+ trap_AddCommand ("stats");
+ trap_AddCommand ("teamtask");
+ trap_AddCommand ("loaddefered"); // spelled wrong, but not changing for demo
+}
diff --git a/code/cgame/cg_draw.c b/code/cgame/cg_draw.c
new file mode 100755
index 0000000..e29c10f
--- /dev/null
+++ b/code/cgame/cg_draw.c
@@ -0,0 +1,2659 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// cg_draw.c -- draw all of the graphical elements during
+// active (after loading) gameplay
+
+#include "cg_local.h"
+
+#ifdef MISSIONPACK
+#include "../ui/ui_shared.h"
+
+// used for scoreboard
+extern displayContextDef_t cgDC;
+menuDef_t *menuScoreboard = NULL;
+#else
+int drawTeamOverlayModificationCount = -1;
+#endif
+
+int sortedTeamPlayers[TEAM_MAXOVERLAY];
+int numSortedTeamPlayers;
+
+char systemChat[256];
+char teamChat1[256];
+char teamChat2[256];
+
+#ifdef MISSIONPACK
+
+int CG_Text_Width(const char *text, float scale, int limit) {
+ int count,len;
+ float out;
+ glyphInfo_t *glyph;
+ float useScale;
+// FIXME: see ui_main.c, same problem
+// const unsigned char *s = text;
+ const char *s = text;
+ fontInfo_t *font = &cgDC.Assets.textFont;
+ if (scale <= cg_smallFont.value) {
+ font = &cgDC.Assets.smallFont;
+ } else if (scale > cg_bigFont.value) {
+ font = &cgDC.Assets.bigFont;
+ }
+ useScale = scale * font->glyphScale;
+ out = 0;
+ if (text) {
+ len = strlen(text);
+ if (limit > 0 && len > limit) {
+ len = limit;
+ }
+ count = 0;
+ while (s && *s && count < len) {
+ if ( Q_IsColorString(s) ) {
+ s += 2;
+ continue;
+ } else {
+ glyph = &font->glyphs[(int)*s]; // TTimo: FIXME: getting nasty warnings without the cast, hopefully this doesn't break the VM build
+ out += glyph->xSkip;
+ s++;
+ count++;
+ }
+ }
+ }
+ return out * useScale;
+}
+
+int CG_Text_Height(const char *text, float scale, int limit) {
+ int len, count;
+ float max;
+ glyphInfo_t *glyph;
+ float useScale;
+// TTimo: FIXME
+// const unsigned char *s = text;
+ const char *s = text;
+ fontInfo_t *font = &cgDC.Assets.textFont;
+ if (scale <= cg_smallFont.value) {
+ font = &cgDC.Assets.smallFont;
+ } else if (scale > cg_bigFont.value) {
+ font = &cgDC.Assets.bigFont;
+ }
+ useScale = scale * font->glyphScale;
+ max = 0;
+ if (text) {
+ len = strlen(text);
+ if (limit > 0 && len > limit) {
+ len = limit;
+ }
+ count = 0;
+ while (s && *s && count < len) {
+ if ( Q_IsColorString(s) ) {
+ s += 2;
+ continue;
+ } else {
+ glyph = &font->glyphs[(int)*s]; // TTimo: FIXME: getting nasty warnings without the cast, hopefully this doesn't break the VM build
+ if (max < glyph->height) {
+ max = glyph->height;
+ }
+ s++;
+ count++;
+ }
+ }
+ }
+ return max * useScale;
+}
+
+void CG_Text_PaintChar(float x, float y, float width, float height, float scale, float s, float t, float s2, float t2, qhandle_t hShader) {
+ float w, h;
+ w = width * scale;
+ h = height * scale;
+ CG_AdjustFrom640( &x, &y, &w, &h );
+ trap_R_DrawStretchPic( x, y, w, h, s, t, s2, t2, hShader );
+}
+
+void CG_Text_Paint(float x, float y, float scale, vec4_t color, const char *text, float adjust, int limit, int style) {
+ int len, count;
+ vec4_t newColor;
+ glyphInfo_t *glyph;
+ float useScale;
+ fontInfo_t *font = &cgDC.Assets.textFont;
+ if (scale <= cg_smallFont.value) {
+ font = &cgDC.Assets.smallFont;
+ } else if (scale > cg_bigFont.value) {
+ font = &cgDC.Assets.bigFont;
+ }
+ useScale = scale * font->glyphScale;
+ if (text) {
+// TTimo: FIXME
+// const unsigned char *s = text;
+ const char *s = text;
+ trap_R_SetColor( color );
+ memcpy(&newColor[0], &color[0], sizeof(vec4_t));
+ len = strlen(text);
+ if (limit > 0 && len > limit) {
+ len = limit;
+ }
+ count = 0;
+ while (s && *s && count < len) {
+ glyph = &font->glyphs[(int)*s]; // TTimo: FIXME: getting nasty warnings without the cast, hopefully this doesn't break the VM build
+ //int yadj = Assets.textFont.glyphs[text[i]].bottom + Assets.textFont.glyphs[text[i]].top;
+ //float yadj = scale * (Assets.textFont.glyphs[text[i]].imageHeight - Assets.textFont.glyphs[text[i]].height);
+ if ( Q_IsColorString( s ) ) {
+ memcpy( newColor, g_color_table[ColorIndex(*(s+1))], sizeof( newColor ) );
+ newColor[3] = color[3];
+ trap_R_SetColor( newColor );
+ s += 2;
+ continue;
+ } else {
+ float yadj = useScale * glyph->top;
+ if (style == ITEM_TEXTSTYLE_SHADOWED || style == ITEM_TEXTSTYLE_SHADOWEDMORE) {
+ int ofs = style == ITEM_TEXTSTYLE_SHADOWED ? 1 : 2;
+ colorBlack[3] = newColor[3];
+ trap_R_SetColor( colorBlack );
+ CG_Text_PaintChar(x + ofs, y - yadj + ofs,
+ glyph->imageWidth,
+ glyph->imageHeight,
+ useScale,
+ glyph->s,
+ glyph->t,
+ glyph->s2,
+ glyph->t2,
+ glyph->glyph);
+ colorBlack[3] = 1.0;
+ trap_R_SetColor( newColor );
+ }
+ CG_Text_PaintChar(x, y - yadj,
+ glyph->imageWidth,
+ glyph->imageHeight,
+ useScale,
+ glyph->s,
+ glyph->t,
+ glyph->s2,
+ glyph->t2,
+ glyph->glyph);
+ // CG_DrawPic(x, y - yadj, scale * cgDC.Assets.textFont.glyphs[text[i]].imageWidth, scale * cgDC.Assets.textFont.glyphs[text[i]].imageHeight, cgDC.Assets.textFont.glyphs[text[i]].glyph);
+ x += (glyph->xSkip * useScale) + adjust;
+ s++;
+ count++;
+ }
+ }
+ trap_R_SetColor( NULL );
+ }
+}
+
+
+#endif
+
+/*
+==============
+CG_DrawField
+
+Draws large numbers for status bar and powerups
+==============
+*/
+#ifndef MISSIONPACK
+static void CG_DrawField (int x, int y, int width, int value) {
+ char num[16], *ptr;
+ int l;
+ int frame;
+
+ if ( width < 1 ) {
+ return;
+ }
+
+ // draw number string
+ if ( width > 5 ) {
+ width = 5;
+ }
+
+ switch ( width ) {
+ case 1:
+ value = value > 9 ? 9 : value;
+ value = value < 0 ? 0 : value;
+ break;
+ case 2:
+ value = value > 99 ? 99 : value;
+ value = value < -9 ? -9 : value;
+ break;
+ case 3:
+ value = value > 999 ? 999 : value;
+ value = value < -99 ? -99 : value;
+ break;
+ case 4:
+ value = value > 9999 ? 9999 : value;
+ value = value < -999 ? -999 : value;
+ break;
+ }
+
+ Com_sprintf (num, sizeof(num), "%i", value);
+ l = strlen(num);
+ if (l > width)
+ l = width;
+ x += 2 + CHAR_WIDTH*(width - l);
+
+ ptr = num;
+ while (*ptr && l)
+ {
+ if (*ptr == '-')
+ frame = STAT_MINUS;
+ else
+ frame = *ptr -'0';
+
+ CG_DrawPic( x,y, CHAR_WIDTH, CHAR_HEIGHT, cgs.media.numberShaders[frame] );
+ x += CHAR_WIDTH;
+ ptr++;
+ l--;
+ }
+}
+#endif // MISSIONPACK
+
+/*
+================
+CG_Draw3DModel
+
+================
+*/
+void CG_Draw3DModel( float x, float y, float w, float h, qhandle_t model, qhandle_t skin, vec3_t origin, vec3_t angles ) {
+ refdef_t refdef;
+ refEntity_t ent;
+
+ if ( !cg_draw3dIcons.integer || !cg_drawIcons.integer ) {
+ return;
+ }
+
+ CG_AdjustFrom640( &x, &y, &w, &h );
+
+ memset( &refdef, 0, sizeof( refdef ) );
+
+ memset( &ent, 0, sizeof( ent ) );
+ AnglesToAxis( angles, ent.axis );
+ VectorCopy( origin, ent.origin );
+ ent.hModel = model;
+ ent.customSkin = skin;
+ ent.renderfx = RF_NOSHADOW; // no stencil shadows
+
+ refdef.rdflags = RDF_NOWORLDMODEL;
+
+ AxisClear( refdef.viewaxis );
+
+ refdef.fov_x = 30;
+ refdef.fov_y = 30;
+
+ refdef.x = x;
+ refdef.y = y;
+ refdef.width = w;
+ refdef.height = h;
+
+ refdef.time = cg.time;
+
+ trap_R_ClearScene();
+ trap_R_AddRefEntityToScene( &ent );
+ trap_R_RenderScene( &refdef );
+}
+
+/*
+================
+CG_DrawHead
+
+Used for both the status bar and the scoreboard
+================
+*/
+void CG_DrawHead( float x, float y, float w, float h, int clientNum, vec3_t headAngles ) {
+ clipHandle_t cm;
+ clientInfo_t *ci;
+ float len;
+ vec3_t origin;
+ vec3_t mins, maxs;
+
+ ci = &cgs.clientinfo[ clientNum ];
+
+ if ( cg_draw3dIcons.integer ) {
+ cm = ci->headModel;
+ if ( !cm ) {
+ return;
+ }
+
+ // offset the origin y and z to center the head
+ trap_R_ModelBounds( cm, mins, maxs );
+
+ origin[2] = -0.5 * ( mins[2] + maxs[2] );
+ origin[1] = 0.5 * ( mins[1] + maxs[1] );
+
+ // calculate distance so the head nearly fills the box
+ // assume heads are taller than wide
+ len = 0.7 * ( maxs[2] - mins[2] );
+ origin[0] = len / 0.268; // len / tan( fov/2 )
+
+ // allow per-model tweaking
+ VectorAdd( origin, ci->headOffset, origin );
+
+ CG_Draw3DModel( x, y, w, h, ci->headModel, ci->headSkin, origin, headAngles );
+ } else if ( cg_drawIcons.integer ) {
+ CG_DrawPic( x, y, w, h, ci->modelIcon );
+ }
+
+ // if they are deferred, draw a cross out
+ if ( ci->deferred ) {
+ CG_DrawPic( x, y, w, h, cgs.media.deferShader );
+ }
+}
+
+/*
+================
+CG_DrawFlagModel
+
+Used for both the status bar and the scoreboard
+================
+*/
+void CG_DrawFlagModel( float x, float y, float w, float h, int team, qboolean force2D ) {
+ qhandle_t cm;
+ float len;
+ vec3_t origin, angles;
+ vec3_t mins, maxs;
+ qhandle_t handle;
+
+ if ( !force2D && cg_draw3dIcons.integer ) {
+
+ VectorClear( angles );
+
+ cm = cgs.media.redFlagModel;
+
+ // offset the origin y and z to center the flag
+ trap_R_ModelBounds( cm, mins, maxs );
+
+ origin[2] = -0.5 * ( mins[2] + maxs[2] );
+ origin[1] = 0.5 * ( mins[1] + maxs[1] );
+
+ // calculate distance so the flag nearly fills the box
+ // assume heads are taller than wide
+ len = 0.5 * ( maxs[2] - mins[2] );
+ origin[0] = len / 0.268; // len / tan( fov/2 )
+
+ angles[YAW] = 60 * sin( cg.time / 2000.0 );;
+
+ if( team == TEAM_RED ) {
+ handle = cgs.media.redFlagModel;
+ } else if( team == TEAM_BLUE ) {
+ handle = cgs.media.blueFlagModel;
+ } else if( team == TEAM_FREE ) {
+ handle = cgs.media.neutralFlagModel;
+ } else {
+ return;
+ }
+ CG_Draw3DModel( x, y, w, h, handle, 0, origin, angles );
+ } else if ( cg_drawIcons.integer ) {
+ gitem_t *item;
+
+ if( team == TEAM_RED ) {
+ item = BG_FindItemForPowerup( PW_REDFLAG );
+ } else if( team == TEAM_BLUE ) {
+ item = BG_FindItemForPowerup( PW_BLUEFLAG );
+ } else if( team == TEAM_FREE ) {
+ item = BG_FindItemForPowerup( PW_NEUTRALFLAG );
+ } else {
+ return;
+ }
+ if (item) {
+ CG_DrawPic( x, y, w, h, cg_items[ ITEM_INDEX(item) ].icon );
+ }
+ }
+}
+
+/*
+================
+CG_DrawStatusBarHead
+
+================
+*/
+#ifndef MISSIONPACK
+
+static void CG_DrawStatusBarHead( float x ) {
+ vec3_t angles;
+ float size, stretch;
+ float frac;
+
+ VectorClear( angles );
+
+ if ( cg.damageTime && cg.time - cg.damageTime < DAMAGE_TIME ) {
+ frac = (float)(cg.time - cg.damageTime ) / DAMAGE_TIME;
+ size = ICON_SIZE * 1.25 * ( 1.5 - frac * 0.5 );
+
+ stretch = size - ICON_SIZE * 1.25;
+ // kick in the direction of damage
+ x -= stretch * 0.5 + cg.damageX * stretch * 0.5;
+
+ cg.headStartYaw = 180 + cg.damageX * 45;
+
+ cg.headEndYaw = 180 + 20 * cos( crandom()*M_PI );
+ cg.headEndPitch = 5 * cos( crandom()*M_PI );
+
+ cg.headStartTime = cg.time;
+ cg.headEndTime = cg.time + 100 + random() * 2000;
+ } else {
+ if ( cg.time >= cg.headEndTime ) {
+ // select a new head angle
+ cg.headStartYaw = cg.headEndYaw;
+ cg.headStartPitch = cg.headEndPitch;
+ cg.headStartTime = cg.headEndTime;
+ cg.headEndTime = cg.time + 100 + random() * 2000;
+
+ cg.headEndYaw = 180 + 20 * cos( crandom()*M_PI );
+ cg.headEndPitch = 5 * cos( crandom()*M_PI );
+ }
+
+ size = ICON_SIZE * 1.25;
+ }
+
+ // if the server was frozen for a while we may have a bad head start time
+ if ( cg.headStartTime > cg.time ) {
+ cg.headStartTime = cg.time;
+ }
+
+ frac = ( cg.time - cg.headStartTime ) / (float)( cg.headEndTime - cg.headStartTime );
+ frac = frac * frac * ( 3 - 2 * frac );
+ angles[YAW] = cg.headStartYaw + ( cg.headEndYaw - cg.headStartYaw ) * frac;
+ angles[PITCH] = cg.headStartPitch + ( cg.headEndPitch - cg.headStartPitch ) * frac;
+
+ CG_DrawHead( x, 480 - size, size, size,
+ cg.snap->ps.clientNum, angles );
+}
+#endif // MISSIONPACK
+
+/*
+================
+CG_DrawStatusBarFlag
+
+================
+*/
+#ifndef MISSIONPACK
+static void CG_DrawStatusBarFlag( float x, int team ) {
+ CG_DrawFlagModel( x, 480 - ICON_SIZE, ICON_SIZE, ICON_SIZE, team, qfalse );
+}
+#endif // MISSIONPACK
+
+/*
+================
+CG_DrawTeamBackground
+
+================
+*/
+void CG_DrawTeamBackground( int x, int y, int w, int h, float alpha, int team )
+{
+ vec4_t hcolor;
+
+ hcolor[3] = alpha;
+ if ( team == TEAM_RED ) {
+ hcolor[0] = 1;
+ hcolor[1] = 0;
+ hcolor[2] = 0;
+ } else if ( team == TEAM_BLUE ) {
+ hcolor[0] = 0;
+ hcolor[1] = 0;
+ hcolor[2] = 1;
+ } else {
+ return;
+ }
+ trap_R_SetColor( hcolor );
+ CG_DrawPic( x, y, w, h, cgs.media.teamStatusBar );
+ trap_R_SetColor( NULL );
+}
+
+/*
+================
+CG_DrawStatusBar
+
+================
+*/
+#ifndef MISSIONPACK
+static void CG_DrawStatusBar( void ) {
+ int color;
+ centity_t *cent;
+ playerState_t *ps;
+ int value;
+ vec4_t hcolor;
+ vec3_t angles;
+ vec3_t origin;
+#ifdef MISSIONPACK
+ qhandle_t handle;
+#endif
+ static float colors[4][4] = {
+// { 0.2, 1.0, 0.2, 1.0 } , { 1.0, 0.2, 0.2, 1.0 }, {0.5, 0.5, 0.5, 1} };
+ { 1.0f, 0.69f, 0.0f, 1.0f }, // normal
+ { 1.0f, 0.2f, 0.2f, 1.0f }, // low health
+ { 0.5f, 0.5f, 0.5f, 1.0f }, // weapon firing
+ { 1.0f, 1.0f, 1.0f, 1.0f } }; // health > 100
+
+ if ( cg_drawStatus.integer == 0 ) {
+ return;
+ }
+
+ // draw the team background
+ CG_DrawTeamBackground( 0, 420, 640, 60, 0.33f, cg.snap->ps.persistant[PERS_TEAM] );
+
+ cent = &cg_entities[cg.snap->ps.clientNum];
+ ps = &cg.snap->ps;
+
+ VectorClear( angles );
+
+ // draw any 3D icons first, so the changes back to 2D are minimized
+ if ( cent->currentState.weapon && cg_weapons[ cent->currentState.weapon ].ammoModel ) {
+ origin[0] = 70;
+ origin[1] = 0;
+ origin[2] = 0;
+ angles[YAW] = 90 + 20 * sin( cg.time / 1000.0 );
+ CG_Draw3DModel( CHAR_WIDTH*3 + TEXT_ICON_SPACE, 432, ICON_SIZE, ICON_SIZE,
+ cg_weapons[ cent->currentState.weapon ].ammoModel, 0, origin, angles );
+ }
+
+ CG_DrawStatusBarHead( 185 + CHAR_WIDTH*3 + TEXT_ICON_SPACE );
+
+ if( cg.predictedPlayerState.powerups[PW_REDFLAG] ) {
+ CG_DrawStatusBarFlag( 185 + CHAR_WIDTH*3 + TEXT_ICON_SPACE + ICON_SIZE, TEAM_RED );
+ } else if( cg.predictedPlayerState.powerups[PW_BLUEFLAG] ) {
+ CG_DrawStatusBarFlag( 185 + CHAR_WIDTH*3 + TEXT_ICON_SPACE + ICON_SIZE, TEAM_BLUE );
+ } else if( cg.predictedPlayerState.powerups[PW_NEUTRALFLAG] ) {
+ CG_DrawStatusBarFlag( 185 + CHAR_WIDTH*3 + TEXT_ICON_SPACE + ICON_SIZE, TEAM_FREE );
+ }
+
+ if ( ps->stats[ STAT_ARMOR ] ) {
+ origin[0] = 90;
+ origin[1] = 0;
+ origin[2] = -10;
+ angles[YAW] = ( cg.time & 2047 ) * 360 / 2048.0;
+ CG_Draw3DModel( 370 + CHAR_WIDTH*3 + TEXT_ICON_SPACE, 432, ICON_SIZE, ICON_SIZE,
+ cgs.media.armorModel, 0, origin, angles );
+ }
+#ifdef MISSIONPACK
+ if( cgs.gametype == GT_HARVESTER ) {
+ origin[0] = 90;
+ origin[1] = 0;
+ origin[2] = -10;
+ angles[YAW] = ( cg.time & 2047 ) * 360 / 2048.0;
+ if( cg.snap->ps.persistant[PERS_TEAM] == TEAM_BLUE ) {
+ handle = cgs.media.redCubeModel;
+ } else {
+ handle = cgs.media.blueCubeModel;
+ }
+ CG_Draw3DModel( 640 - (TEXT_ICON_SPACE + ICON_SIZE), 416, ICON_SIZE, ICON_SIZE, handle, 0, origin, angles );
+ }
+#endif
+ //
+ // ammo
+ //
+ if ( cent->currentState.weapon ) {
+ value = ps->ammo[cent->currentState.weapon];
+ if ( value > -1 ) {
+ if ( cg.predictedPlayerState.weaponstate == WEAPON_FIRING
+ && cg.predictedPlayerState.weaponTime > 100 ) {
+ // draw as dark grey when reloading
+ color = 2; // dark grey
+ } else {
+ if ( value >= 0 ) {
+ color = 0; // green
+ } else {
+ color = 1; // red
+ }
+ }
+ trap_R_SetColor( colors[color] );
+
+ CG_DrawField (0, 432, 3, value);
+ trap_R_SetColor( NULL );
+
+ // if we didn't draw a 3D icon, draw a 2D icon for ammo
+ if ( !cg_draw3dIcons.integer && cg_drawIcons.integer ) {
+ qhandle_t icon;
+
+ icon = cg_weapons[ cg.predictedPlayerState.weapon ].ammoIcon;
+ if ( icon ) {
+ CG_DrawPic( CHAR_WIDTH*3 + TEXT_ICON_SPACE, 432, ICON_SIZE, ICON_SIZE, icon );
+ }
+ }
+ }
+ }
+
+ //
+ // health
+ //
+ value = ps->stats[STAT_HEALTH];
+ if ( value > 100 ) {
+ trap_R_SetColor( colors[3] ); // white
+ } else if (value > 25) {
+ trap_R_SetColor( colors[0] ); // green
+ } else if (value > 0) {
+ color = (cg.time >> 8) & 1; // flash
+ trap_R_SetColor( colors[color] );
+ } else {
+ trap_R_SetColor( colors[1] ); // red
+ }
+
+ // stretch the health up when taking damage
+ CG_DrawField ( 185, 432, 3, value);
+ CG_ColorForHealth( hcolor );
+ trap_R_SetColor( hcolor );
+
+
+ //
+ // armor
+ //
+ value = ps->stats[STAT_ARMOR];
+ if (value > 0 ) {
+ trap_R_SetColor( colors[0] );
+ CG_DrawField (370, 432, 3, value);
+ trap_R_SetColor( NULL );
+ // if we didn't draw a 3D icon, draw a 2D icon for armor
+ if ( !cg_draw3dIcons.integer && cg_drawIcons.integer ) {
+ CG_DrawPic( 370 + CHAR_WIDTH*3 + TEXT_ICON_SPACE, 432, ICON_SIZE, ICON_SIZE, cgs.media.armorIcon );
+ }
+
+ }
+#ifdef MISSIONPACK
+ //
+ // cubes
+ //
+ if( cgs.gametype == GT_HARVESTER ) {
+ value = ps->generic1;
+ if( value > 99 ) {
+ value = 99;
+ }
+ trap_R_SetColor( colors[0] );
+ CG_DrawField (640 - (CHAR_WIDTH*2 + TEXT_ICON_SPACE + ICON_SIZE), 432, 2, value);
+ trap_R_SetColor( NULL );
+ // if we didn't draw a 3D icon, draw a 2D icon for armor
+ if ( !cg_draw3dIcons.integer && cg_drawIcons.integer ) {
+ if( cg.snap->ps.persistant[PERS_TEAM] == TEAM_BLUE ) {
+ handle = cgs.media.redCubeIcon;
+ } else {
+ handle = cgs.media.blueCubeIcon;
+ }
+ CG_DrawPic( 640 - (TEXT_ICON_SPACE + ICON_SIZE), 432, ICON_SIZE, ICON_SIZE, handle );
+ }
+ }
+#endif
+}
+#endif
+
+/*
+===========================================================================================
+
+ UPPER RIGHT CORNER
+
+===========================================================================================
+*/
+
+/*
+================
+CG_DrawAttacker
+
+================
+*/
+static float CG_DrawAttacker( float y ) {
+ int t;
+ float size;
+ vec3_t angles;
+ const char *info;
+ const char *name;
+ int clientNum;
+
+ if ( cg.predictedPlayerState.stats[STAT_HEALTH] <= 0 ) {
+ return y;
+ }
+
+ if ( !cg.attackerTime ) {
+ return y;
+ }
+
+ clientNum = cg.predictedPlayerState.persistant[PERS_ATTACKER];
+ if ( clientNum < 0 || clientNum >= MAX_CLIENTS || clientNum == cg.snap->ps.clientNum ) {
+ return y;
+ }
+
+ t = cg.time - cg.attackerTime;
+ if ( t > ATTACKER_HEAD_TIME ) {
+ cg.attackerTime = 0;
+ return y;
+ }
+
+ size = ICON_SIZE * 1.25;
+
+ angles[PITCH] = 0;
+ angles[YAW] = 180;
+ angles[ROLL] = 0;
+ CG_DrawHead( 640 - size, y, size, size, clientNum, angles );
+
+ info = CG_ConfigString( CS_PLAYERS + clientNum );
+ name = Info_ValueForKey( info, "n" );
+ y += size;
+ CG_DrawBigString( 640 - ( Q_PrintStrlen( name ) * BIGCHAR_WIDTH), y, name, 0.5 );
+
+ return y + BIGCHAR_HEIGHT + 2;
+}
+
+/*
+==================
+CG_DrawSnapshot
+==================
+*/
+static float CG_DrawSnapshot( float y ) {
+ char *s;
+ int w;
+
+ s = va( "time:%i snap:%i cmd:%i", cg.snap->serverTime,
+ cg.latestSnapshotNum, cgs.serverCommandSequence );
+ w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH;
+
+ CG_DrawBigString( 635 - w, y + 2, s, 1.0F);
+
+ return y + BIGCHAR_HEIGHT + 4;
+}
+
+/*
+==================
+CG_DrawFPS
+==================
+*/
+#define FPS_FRAMES 4
+static float CG_DrawFPS( float y ) {
+ char *s;
+ int w;
+ static int previousTimes[FPS_FRAMES];
+ static int index;
+ int i, total;
+ int fps;
+ static int previous;
+ int t, frameTime;
+
+ // don't use serverTime, because that will be drifting to
+ // correct for internet lag changes, timescales, timedemos, etc
+ t = trap_Milliseconds();
+ frameTime = t - previous;
+ previous = t;
+
+ previousTimes[index % FPS_FRAMES] = frameTime;
+ index++;
+ if ( index > FPS_FRAMES ) {
+ // average multiple frames together to smooth changes out a bit
+ total = 0;
+ for ( i = 0 ; i < FPS_FRAMES ; i++ ) {
+ total += previousTimes[i];
+ }
+ if ( !total ) {
+ total = 1;
+ }
+ fps = 1000 * FPS_FRAMES / total;
+
+ s = va( "%ifps", fps );
+ w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH;
+
+ CG_DrawBigString( 635 - w, y + 2, s, 1.0F);
+ }
+
+ return y + BIGCHAR_HEIGHT + 4;
+}
+
+/*
+=================
+CG_DrawTimer
+=================
+*/
+static float CG_DrawTimer( float y ) {
+ char *s;
+ int w;
+ int mins, seconds, tens;
+ int msec;
+
+ msec = cg.time - cgs.levelStartTime;
+
+ seconds = msec / 1000;
+ mins = seconds / 60;
+ seconds -= mins * 60;
+ tens = seconds / 10;
+ seconds -= tens * 10;
+
+ s = va( "%i:%i%i", mins, tens, seconds );
+ w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH;
+
+ CG_DrawBigString( 635 - w, y + 2, s, 1.0F);
+
+ return y + BIGCHAR_HEIGHT + 4;
+}
+
+
+/*
+=================
+CG_DrawTeamOverlay
+=================
+*/
+
+static float CG_DrawTeamOverlay( float y, qboolean right, qboolean upper ) {
+ int x, w, h, xx;
+ int i, j, len;
+ const char *p;
+ vec4_t hcolor;
+ int pwidth, lwidth;
+ int plyrs;
+ char st[16];
+ clientInfo_t *ci;
+ gitem_t *item;
+ int ret_y, count;
+
+ if ( !cg_drawTeamOverlay.integer ) {
+ return y;
+ }
+
+ if ( cg.snap->ps.persistant[PERS_TEAM] != TEAM_RED && cg.snap->ps.persistant[PERS_TEAM] != TEAM_BLUE ) {
+ return y; // Not on any team
+ }
+
+ plyrs = 0;
+
+ // max player name width
+ pwidth = 0;
+ count = (numSortedTeamPlayers > 8) ? 8 : numSortedTeamPlayers;
+ for (i = 0; i < count; i++) {
+ ci = cgs.clientinfo + sortedTeamPlayers[i];
+ if ( ci->infoValid && ci->team == cg.snap->ps.persistant[PERS_TEAM]) {
+ plyrs++;
+ len = CG_DrawStrlen(ci->name);
+ if (len > pwidth)
+ pwidth = len;
+ }
+ }
+
+ if (!plyrs)
+ return y;
+
+ if (pwidth > TEAM_OVERLAY_MAXNAME_WIDTH)
+ pwidth = TEAM_OVERLAY_MAXNAME_WIDTH;
+
+ // max location name width
+ lwidth = 0;
+ for (i = 1; i < MAX_LOCATIONS; i++) {
+ p = CG_ConfigString(CS_LOCATIONS + i);
+ if (p && *p) {
+ len = CG_DrawStrlen(p);
+ if (len > lwidth)
+ lwidth = len;
+ }
+ }
+
+ if (lwidth > TEAM_OVERLAY_MAXLOCATION_WIDTH)
+ lwidth = TEAM_OVERLAY_MAXLOCATION_WIDTH;
+
+ w = (pwidth + lwidth + 4 + 7) * TINYCHAR_WIDTH;
+
+ if ( right )
+ x = 640 - w;
+ else
+ x = 0;
+
+ h = plyrs * TINYCHAR_HEIGHT;
+
+ if ( upper ) {
+ ret_y = y + h;
+ } else {
+ y -= h;
+ ret_y = y;
+ }
+
+ if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_RED ) {
+ hcolor[0] = 1.0f;
+ hcolor[1] = 0.0f;
+ hcolor[2] = 0.0f;
+ hcolor[3] = 0.33f;
+ } else { // if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_BLUE )
+ hcolor[0] = 0.0f;
+ hcolor[1] = 0.0f;
+ hcolor[2] = 1.0f;
+ hcolor[3] = 0.33f;
+ }
+ trap_R_SetColor( hcolor );
+ CG_DrawPic( x, y, w, h, cgs.media.teamStatusBar );
+ trap_R_SetColor( NULL );
+
+ for (i = 0; i < count; i++) {
+ ci = cgs.clientinfo + sortedTeamPlayers[i];
+ if ( ci->infoValid && ci->team == cg.snap->ps.persistant[PERS_TEAM]) {
+
+ hcolor[0] = hcolor[1] = hcolor[2] = hcolor[3] = 1.0;
+
+ xx = x + TINYCHAR_WIDTH;
+
+ CG_DrawStringExt( xx, y,
+ ci->name, hcolor, qfalse, qfalse,
+ TINYCHAR_WIDTH, TINYCHAR_HEIGHT, TEAM_OVERLAY_MAXNAME_WIDTH);
+
+ if (lwidth) {
+ p = CG_ConfigString(CS_LOCATIONS + ci->location);
+ if (!p || !*p)
+ p = "unknown";
+ len = CG_DrawStrlen(p);
+ if (len > lwidth)
+ len = lwidth;
+
+// xx = x + TINYCHAR_WIDTH * 2 + TINYCHAR_WIDTH * pwidth +
+// ((lwidth/2 - len/2) * TINYCHAR_WIDTH);
+ xx = x + TINYCHAR_WIDTH * 2 + TINYCHAR_WIDTH * pwidth;
+ CG_DrawStringExt( xx, y,
+ p, hcolor, qfalse, qfalse, TINYCHAR_WIDTH, TINYCHAR_HEIGHT,
+ TEAM_OVERLAY_MAXLOCATION_WIDTH);
+ }
+
+ CG_GetColorForHealth( ci->health, ci->armor, hcolor );
+
+ Com_sprintf (st, sizeof(st), "%3i %3i", ci->health, ci->armor);
+
+ xx = x + TINYCHAR_WIDTH * 3 +
+ TINYCHAR_WIDTH * pwidth + TINYCHAR_WIDTH * lwidth;
+
+ CG_DrawStringExt( xx, y,
+ st, hcolor, qfalse, qfalse,
+ TINYCHAR_WIDTH, TINYCHAR_HEIGHT, 0 );
+
+ // draw weapon icon
+ xx += TINYCHAR_WIDTH * 3;
+
+ if ( cg_weapons[ci->curWeapon].weaponIcon ) {
+ CG_DrawPic( xx, y, TINYCHAR_WIDTH, TINYCHAR_HEIGHT,
+ cg_weapons[ci->curWeapon].weaponIcon );
+ } else {
+ CG_DrawPic( xx, y, TINYCHAR_WIDTH, TINYCHAR_HEIGHT,
+ cgs.media.deferShader );
+ }
+
+ // Draw powerup icons
+ if (right) {
+ xx = x;
+ } else {
+ xx = x + w - TINYCHAR_WIDTH;
+ }
+ for (j = 0; j <= PW_NUM_POWERUPS; j++) {
+ if (ci->powerups & (1 << j)) {
+
+ item = BG_FindItemForPowerup( j );
+
+ if (item) {
+ CG_DrawPic( xx, y, TINYCHAR_WIDTH, TINYCHAR_HEIGHT,
+ trap_R_RegisterShader( item->icon ) );
+ if (right) {
+ xx -= TINYCHAR_WIDTH;
+ } else {
+ xx += TINYCHAR_WIDTH;
+ }
+ }
+ }
+ }
+
+ y += TINYCHAR_HEIGHT;
+ }
+ }
+
+ return ret_y;
+//#endif
+}
+
+
+/*
+=====================
+CG_DrawUpperRight
+
+=====================
+*/
+static void CG_DrawUpperRight( void ) {
+ float y;
+
+ y = 0;
+
+ if ( cgs.gametype >= GT_TEAM && cg_drawTeamOverlay.integer == 1 ) {
+ y = CG_DrawTeamOverlay( y, qtrue, qtrue );
+ }
+ if ( cg_drawSnapshot.integer ) {
+ y = CG_DrawSnapshot( y );
+ }
+ if ( cg_drawFPS.integer ) {
+ y = CG_DrawFPS( y );
+ }
+ if ( cg_drawTimer.integer ) {
+ y = CG_DrawTimer( y );
+ }
+ if ( cg_drawAttacker.integer ) {
+ y = CG_DrawAttacker( y );
+ }
+
+}
+
+/*
+===========================================================================================
+
+ LOWER RIGHT CORNER
+
+===========================================================================================
+*/
+
+/*
+=================
+CG_DrawScores
+
+Draw the small two score display
+=================
+*/
+#ifndef MISSIONPACK
+static float CG_DrawScores( float y ) {
+ const char *s;
+ int s1, s2, score;
+ int x, w;
+ int v;
+ vec4_t color;
+ float y1;
+ gitem_t *item;
+
+ s1 = cgs.scores1;
+ s2 = cgs.scores2;
+
+ y -= BIGCHAR_HEIGHT + 8;
+
+ y1 = y;
+
+ // draw from the right side to left
+ if ( cgs.gametype >= GT_TEAM ) {
+ x = 640;
+ color[0] = 0.0f;
+ color[1] = 0.0f;
+ color[2] = 1.0f;
+ color[3] = 0.33f;
+ s = va( "%2i", s2 );
+ w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH + 8;
+ x -= w;
+ CG_FillRect( x, y-4, w, BIGCHAR_HEIGHT+8, color );
+ if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_BLUE ) {
+ CG_DrawPic( x, y-4, w, BIGCHAR_HEIGHT+8, cgs.media.selectShader );
+ }
+ CG_DrawBigString( x + 4, y, s, 1.0F);
+
+ if ( cgs.gametype == GT_CTF ) {
+ // Display flag status
+ item = BG_FindItemForPowerup( PW_BLUEFLAG );
+
+ if (item) {
+ y1 = y - BIGCHAR_HEIGHT - 8;
+ if( cgs.blueflag >= 0 && cgs.blueflag <= 2 ) {
+ CG_DrawPic( x, y1-4, w, BIGCHAR_HEIGHT+8, cgs.media.blueFlagShader[cgs.blueflag] );
+ }
+ }
+ }
+ color[0] = 1.0f;
+ color[1] = 0.0f;
+ color[2] = 0.0f;
+ color[3] = 0.33f;
+ s = va( "%2i", s1 );
+ w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH + 8;
+ x -= w;
+ CG_FillRect( x, y-4, w, BIGCHAR_HEIGHT+8, color );
+ if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_RED ) {
+ CG_DrawPic( x, y-4, w, BIGCHAR_HEIGHT+8, cgs.media.selectShader );
+ }
+ CG_DrawBigString( x + 4, y, s, 1.0F);
+
+ if ( cgs.gametype == GT_CTF ) {
+ // Display flag status
+ item = BG_FindItemForPowerup( PW_REDFLAG );
+
+ if (item) {
+ y1 = y - BIGCHAR_HEIGHT - 8;
+ if( cgs.redflag >= 0 && cgs.redflag <= 2 ) {
+ CG_DrawPic( x, y1-4, w, BIGCHAR_HEIGHT+8, cgs.media.redFlagShader[cgs.redflag] );
+ }
+ }
+ }
+
+#ifdef MISSIONPACK
+ if ( cgs.gametype == GT_1FCTF ) {
+ // Display flag status
+ item = BG_FindItemForPowerup( PW_NEUTRALFLAG );
+
+ if (item) {
+ y1 = y - BIGCHAR_HEIGHT - 8;
+ if( cgs.flagStatus >= 0 && cgs.flagStatus <= 3 ) {
+ CG_DrawPic( x, y1-4, w, BIGCHAR_HEIGHT+8, cgs.media.flagShader[cgs.flagStatus] );
+ }
+ }
+ }
+#endif
+ if ( cgs.gametype >= GT_CTF ) {
+ v = cgs.capturelimit;
+ } else {
+ v = cgs.fraglimit;
+ }
+ if ( v ) {
+ s = va( "%2i", v );
+ w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH + 8;
+ x -= w;
+ CG_DrawBigString( x + 4, y, s, 1.0F);
+ }
+
+ } else {
+ qboolean spectator;
+
+ x = 640;
+ score = cg.snap->ps.persistant[PERS_SCORE];
+ spectator = ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR );
+
+ // always show your score in the second box if not in first place
+ if ( s1 != score ) {
+ s2 = score;
+ }
+ if ( s2 != SCORE_NOT_PRESENT ) {
+ s = va( "%2i", s2 );
+ w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH + 8;
+ x -= w;
+ if ( !spectator && score == s2 && score != s1 ) {
+ color[0] = 1.0f;
+ color[1] = 0.0f;
+ color[2] = 0.0f;
+ color[3] = 0.33f;
+ CG_FillRect( x, y-4, w, BIGCHAR_HEIGHT+8, color );
+ CG_DrawPic( x, y-4, w, BIGCHAR_HEIGHT+8, cgs.media.selectShader );
+ } else {
+ color[0] = 0.5f;
+ color[1] = 0.5f;
+ color[2] = 0.5f;
+ color[3] = 0.33f;
+ CG_FillRect( x, y-4, w, BIGCHAR_HEIGHT+8, color );
+ }
+ CG_DrawBigString( x + 4, y, s, 1.0F);
+ }
+
+ // first place
+ if ( s1 != SCORE_NOT_PRESENT ) {
+ s = va( "%2i", s1 );
+ w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH + 8;
+ x -= w;
+ if ( !spectator && score == s1 ) {
+ color[0] = 0.0f;
+ color[1] = 0.0f;
+ color[2] = 1.0f;
+ color[3] = 0.33f;
+ CG_FillRect( x, y-4, w, BIGCHAR_HEIGHT+8, color );
+ CG_DrawPic( x, y-4, w, BIGCHAR_HEIGHT+8, cgs.media.selectShader );
+ } else {
+ color[0] = 0.5f;
+ color[1] = 0.5f;
+ color[2] = 0.5f;
+ color[3] = 0.33f;
+ CG_FillRect( x, y-4, w, BIGCHAR_HEIGHT+8, color );
+ }
+ CG_DrawBigString( x + 4, y, s, 1.0F);
+ }
+
+ if ( cgs.fraglimit ) {
+ s = va( "%2i", cgs.fraglimit );
+ w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH + 8;
+ x -= w;
+ CG_DrawBigString( x + 4, y, s, 1.0F);
+ }
+
+ }
+
+ return y1 - 8;
+}
+#endif // MISSIONPACK
+
+/*
+================
+CG_DrawPowerups
+================
+*/
+#ifndef MISSIONPACK
+static float CG_DrawPowerups( float y ) {
+ int sorted[MAX_POWERUPS];
+ int sortedTime[MAX_POWERUPS];
+ int i, j, k;
+ int active;
+ playerState_t *ps;
+ int t;
+ gitem_t *item;
+ int x;
+ int color;
+ float size;
+ float f;
+ static float colors[2][4] = {
+ { 0.2f, 1.0f, 0.2f, 1.0f } ,
+ { 1.0f, 0.2f, 0.2f, 1.0f }
+ };
+
+ ps = &cg.snap->ps;
+
+ if ( ps->stats[STAT_HEALTH] <= 0 ) {
+ return y;
+ }
+
+ // sort the list by time remaining
+ active = 0;
+ for ( i = 0 ; i < MAX_POWERUPS ; i++ ) {
+ if ( !ps->powerups[ i ] ) {
+ continue;
+ }
+ t = ps->powerups[ i ] - cg.time;
+ // ZOID--don't draw if the power up has unlimited time (999 seconds)
+ // This is true of the CTF flags
+ if ( t < 0 || t > 999000) {
+ continue;
+ }
+
+ // insert into the list
+ for ( j = 0 ; j < active ; j++ ) {
+ if ( sortedTime[j] >= t ) {
+ for ( k = active - 1 ; k >= j ; k-- ) {
+ sorted[k+1] = sorted[k];
+ sortedTime[k+1] = sortedTime[k];
+ }
+ break;
+ }
+ }
+ sorted[j] = i;
+ sortedTime[j] = t;
+ active++;
+ }
+
+ // draw the icons and timers
+ x = 640 - ICON_SIZE - CHAR_WIDTH * 2;
+ for ( i = 0 ; i < active ; i++ ) {
+ item = BG_FindItemForPowerup( sorted[i] );
+
+ if (item) {
+
+ color = 1;
+
+ y -= ICON_SIZE;
+
+ trap_R_SetColor( colors[color] );
+ CG_DrawField( x, y, 2, sortedTime[ i ] / 1000 );
+
+ t = ps->powerups[ sorted[i] ];
+ if ( t - cg.time >= POWERUP_BLINKS * POWERUP_BLINK_TIME ) {
+ trap_R_SetColor( NULL );
+ } else {
+ vec4_t modulate;
+
+ f = (float)( t - cg.time ) / POWERUP_BLINK_TIME;
+ f -= (int)f;
+ modulate[0] = modulate[1] = modulate[2] = modulate[3] = f;
+ trap_R_SetColor( modulate );
+ }
+
+ if ( cg.powerupActive == sorted[i] &&
+ cg.time - cg.powerupTime < PULSE_TIME ) {
+ f = 1.0 - ( ( (float)cg.time - cg.powerupTime ) / PULSE_TIME );
+ size = ICON_SIZE * ( 1.0 + ( PULSE_SCALE - 1.0 ) * f );
+ } else {
+ size = ICON_SIZE;
+ }
+
+ CG_DrawPic( 640 - size, y + ICON_SIZE / 2 - size / 2,
+ size, size, trap_R_RegisterShader( item->icon ) );
+ }
+ }
+ trap_R_SetColor( NULL );
+
+ return y;
+}
+#endif // MISSIONPACK
+
+/*
+=====================
+CG_DrawLowerRight
+
+=====================
+*/
+#ifndef MISSIONPACK
+static void CG_DrawLowerRight( void ) {
+ float y;
+
+ y = 480 - ICON_SIZE;
+
+ if ( cgs.gametype >= GT_TEAM && cg_drawTeamOverlay.integer == 2 ) {
+ y = CG_DrawTeamOverlay( y, qtrue, qfalse );
+ }
+
+ y = CG_DrawScores( y );
+ y = CG_DrawPowerups( y );
+}
+#endif // MISSIONPACK
+
+/*
+===================
+CG_DrawPickupItem
+===================
+*/
+#ifndef MISSIONPACK
+static int CG_DrawPickupItem( int y ) {
+ int value;
+ float *fadeColor;
+
+ if ( cg.snap->ps.stats[STAT_HEALTH] <= 0 ) {
+ return y;
+ }
+
+ y -= ICON_SIZE;
+
+ value = cg.itemPickup;
+ if ( value ) {
+ fadeColor = CG_FadeColor( cg.itemPickupTime, 3000 );
+ if ( fadeColor ) {
+ CG_RegisterItemVisuals( value );
+ trap_R_SetColor( fadeColor );
+ CG_DrawPic( 8, y, ICON_SIZE, ICON_SIZE, cg_items[ value ].icon );
+ CG_DrawBigString( ICON_SIZE + 16, y + (ICON_SIZE/2 - BIGCHAR_HEIGHT/2), bg_itemlist[ value ].pickup_name, fadeColor[0] );
+ trap_R_SetColor( NULL );
+ }
+ }
+
+ return y;
+}
+#endif // MISSIONPACK
+
+/*
+=====================
+CG_DrawLowerLeft
+
+=====================
+*/
+#ifndef MISSIONPACK
+static void CG_DrawLowerLeft( void ) {
+ float y;
+
+ y = 480 - ICON_SIZE;
+
+ if ( cgs.gametype >= GT_TEAM && cg_drawTeamOverlay.integer == 3 ) {
+ y = CG_DrawTeamOverlay( y, qfalse, qfalse );
+ }
+
+
+ y = CG_DrawPickupItem( y );
+}
+#endif // MISSIONPACK
+
+
+//===========================================================================================
+
+/*
+=================
+CG_DrawTeamInfo
+=================
+*/
+#ifndef MISSIONPACK
+static void CG_DrawTeamInfo( void ) {
+ int w, h;
+ int i, len;
+ vec4_t hcolor;
+ int chatHeight;
+
+#define CHATLOC_Y 420 // bottom end
+#define CHATLOC_X 0
+
+ if (cg_teamChatHeight.integer < TEAMCHAT_HEIGHT)
+ chatHeight = cg_teamChatHeight.integer;
+ else
+ chatHeight = TEAMCHAT_HEIGHT;
+ if (chatHeight <= 0)
+ return; // disabled
+
+ if (cgs.teamLastChatPos != cgs.teamChatPos) {
+ if (cg.time - cgs.teamChatMsgTimes[cgs.teamLastChatPos % chatHeight] > cg_teamChatTime.integer) {
+ cgs.teamLastChatPos++;
+ }
+
+ h = (cgs.teamChatPos - cgs.teamLastChatPos) * TINYCHAR_HEIGHT;
+
+ w = 0;
+
+ for (i = cgs.teamLastChatPos; i < cgs.teamChatPos; i++) {
+ len = CG_DrawStrlen(cgs.teamChatMsgs[i % chatHeight]);
+ if (len > w)
+ w = len;
+ }
+ w *= TINYCHAR_WIDTH;
+ w += TINYCHAR_WIDTH * 2;
+
+ if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_RED ) {
+ hcolor[0] = 1.0f;
+ hcolor[1] = 0.0f;
+ hcolor[2] = 0.0f;
+ hcolor[3] = 0.33f;
+ } else if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_BLUE ) {
+ hcolor[0] = 0.0f;
+ hcolor[1] = 0.0f;
+ hcolor[2] = 1.0f;
+ hcolor[3] = 0.33f;
+ } else {
+ hcolor[0] = 0.0f;
+ hcolor[1] = 1.0f;
+ hcolor[2] = 0.0f;
+ hcolor[3] = 0.33f;
+ }
+
+ trap_R_SetColor( hcolor );
+ CG_DrawPic( CHATLOC_X, CHATLOC_Y - h, 640, h, cgs.media.teamStatusBar );
+ trap_R_SetColor( NULL );
+
+ hcolor[0] = hcolor[1] = hcolor[2] = 1.0f;
+ hcolor[3] = 1.0f;
+
+ for (i = cgs.teamChatPos - 1; i >= cgs.teamLastChatPos; i--) {
+ CG_DrawStringExt( CHATLOC_X + TINYCHAR_WIDTH,
+ CHATLOC_Y - (cgs.teamChatPos - i)*TINYCHAR_HEIGHT,
+ cgs.teamChatMsgs[i % chatHeight], hcolor, qfalse, qfalse,
+ TINYCHAR_WIDTH, TINYCHAR_HEIGHT, 0 );
+ }
+ }
+}
+#endif // MISSIONPACK
+
+/*
+===================
+CG_DrawHoldableItem
+===================
+*/
+#ifndef MISSIONPACK
+static void CG_DrawHoldableItem( void ) {
+ int value;
+
+ value = cg.snap->ps.stats[STAT_HOLDABLE_ITEM];
+ if ( value ) {
+ CG_RegisterItemVisuals( value );
+ CG_DrawPic( 640-ICON_SIZE, (SCREEN_HEIGHT-ICON_SIZE)/2, ICON_SIZE, ICON_SIZE, cg_items[ value ].icon );
+ }
+
+}
+#endif // MISSIONPACK
+
+#ifdef MISSIONPACK
+/*
+===================
+CG_DrawPersistantPowerup
+===================
+*/
+#if 0 // sos001208 - DEAD
+static void CG_DrawPersistantPowerup( void ) {
+ int value;
+
+ value = cg.snap->ps.stats[STAT_PERSISTANT_POWERUP];
+ if ( value ) {
+ CG_RegisterItemVisuals( value );
+ CG_DrawPic( 640-ICON_SIZE, (SCREEN_HEIGHT-ICON_SIZE)/2 - ICON_SIZE, ICON_SIZE, ICON_SIZE, cg_items[ value ].icon );
+ }
+}
+#endif
+#endif // MISSIONPACK
+
+
+/*
+===================
+CG_DrawReward
+===================
+*/
+static void CG_DrawReward( void ) {
+ float *color;
+ int i, count;
+ float x, y;
+ char buf[32];
+
+ if ( !cg_drawRewards.integer ) {
+ return;
+ }
+
+ color = CG_FadeColor( cg.rewardTime, REWARD_TIME );
+ if ( !color ) {
+ if (cg.rewardStack > 0) {
+ for(i = 0; i < cg.rewardStack; i++) {
+ cg.rewardSound[i] = cg.rewardSound[i+1];
+ cg.rewardShader[i] = cg.rewardShader[i+1];
+ cg.rewardCount[i] = cg.rewardCount[i+1];
+ }
+ cg.rewardTime = cg.time;
+ cg.rewardStack--;
+ color = CG_FadeColor( cg.rewardTime, REWARD_TIME );
+ trap_S_StartLocalSound(cg.rewardSound[0], CHAN_ANNOUNCER);
+ } else {
+ return;
+ }
+ }
+
+ trap_R_SetColor( color );
+
+ /*
+ count = cg.rewardCount[0]/10; // number of big rewards to draw
+
+ if (count) {
+ y = 4;
+ x = 320 - count * ICON_SIZE;
+ for ( i = 0 ; i < count ; i++ ) {
+ CG_DrawPic( x, y, (ICON_SIZE*2)-4, (ICON_SIZE*2)-4, cg.rewardShader[0] );
+ x += (ICON_SIZE*2);
+ }
+ }
+
+ count = cg.rewardCount[0] - count*10; // number of small rewards to draw
+ */
+
+ if ( cg.rewardCount[0] >= 10 ) {
+ y = 56;
+ x = 320 - ICON_SIZE/2;
+ CG_DrawPic( x, y, ICON_SIZE-4, ICON_SIZE-4, cg.rewardShader[0] );
+ Com_sprintf(buf, sizeof(buf), "%d", cg.rewardCount[0]);
+ x = ( SCREEN_WIDTH - SMALLCHAR_WIDTH * CG_DrawStrlen( buf ) ) / 2;
+ CG_DrawStringExt( x, y+ICON_SIZE, buf, color, qfalse, qtrue,
+ SMALLCHAR_WIDTH, SMALLCHAR_HEIGHT, 0 );
+ }
+ else {
+
+ count = cg.rewardCount[0];
+
+ y = 56;
+ x = 320 - count * ICON_SIZE/2;
+ for ( i = 0 ; i < count ; i++ ) {
+ CG_DrawPic( x, y, ICON_SIZE-4, ICON_SIZE-4, cg.rewardShader[0] );
+ x += ICON_SIZE;
+ }
+ }
+ trap_R_SetColor( NULL );
+}
+
+
+/*
+===============================================================================
+
+LAGOMETER
+
+===============================================================================
+*/
+
+#define LAG_SAMPLES 128
+
+
+typedef struct {
+ int frameSamples[LAG_SAMPLES];
+ int frameCount;
+ int snapshotFlags[LAG_SAMPLES];
+ int snapshotSamples[LAG_SAMPLES];
+ int snapshotCount;
+} lagometer_t;
+
+lagometer_t lagometer;
+
+/*
+==============
+CG_AddLagometerFrameInfo
+
+Adds the current interpolate / extrapolate bar for this frame
+==============
+*/
+void CG_AddLagometerFrameInfo( void ) {
+ int offset;
+
+ offset = cg.time - cg.latestSnapshotTime;
+ lagometer.frameSamples[ lagometer.frameCount & ( LAG_SAMPLES - 1) ] = offset;
+ lagometer.frameCount++;
+}
+
+/*
+==============
+CG_AddLagometerSnapshotInfo
+
+Each time a snapshot is received, log its ping time and
+the number of snapshots that were dropped before it.
+
+Pass NULL for a dropped packet.
+==============
+*/
+void CG_AddLagometerSnapshotInfo( snapshot_t *snap ) {
+ // dropped packet
+ if ( !snap ) {
+ lagometer.snapshotSamples[ lagometer.snapshotCount & ( LAG_SAMPLES - 1) ] = -1;
+ lagometer.snapshotCount++;
+ return;
+ }
+
+ // add this snapshot's info
+ lagometer.snapshotSamples[ lagometer.snapshotCount & ( LAG_SAMPLES - 1) ] = snap->ping;
+ lagometer.snapshotFlags[ lagometer.snapshotCount & ( LAG_SAMPLES - 1) ] = snap->snapFlags;
+ lagometer.snapshotCount++;
+}
+
+/*
+==============
+CG_DrawDisconnect
+
+Should we draw something differnet for long lag vs no packets?
+==============
+*/
+static void CG_DrawDisconnect( void ) {
+ float x, y;
+ int cmdNum;
+ usercmd_t cmd;
+ const char *s;
+ int w; // bk010215 - FIXME char message[1024];
+
+ // draw the phone jack if we are completely past our buffers
+ cmdNum = trap_GetCurrentCmdNumber() - CMD_BACKUP + 1;
+ trap_GetUserCmd( cmdNum, &cmd );
+ if ( cmd.serverTime <= cg.snap->ps.commandTime
+ || cmd.serverTime > cg.time ) { // special check for map_restart // bk 0102165 - FIXME
+ return;
+ }
+
+ // also add text in center of screen
+ s = "Connection Interrupted"; // bk 010215 - FIXME
+ w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH;
+ CG_DrawBigString( 320 - w/2, 100, s, 1.0F);
+
+ // blink the icon
+ if ( ( cg.time >> 9 ) & 1 ) {
+ return;
+ }
+
+ x = 640 - 48;
+ y = 480 - 48;
+
+ CG_DrawPic( x, y, 48, 48, trap_R_RegisterShader("gfx/2d/net.tga" ) );
+}
+
+
+#define MAX_LAGOMETER_PING 900
+#define MAX_LAGOMETER_RANGE 300
+
+/*
+==============
+CG_DrawLagometer
+==============
+*/
+static void CG_DrawLagometer( void ) {
+ int a, x, y, i;
+ float v;
+ float ax, ay, aw, ah, mid, range;
+ int color;
+ float vscale;
+
+ if ( !cg_lagometer.integer || cgs.localServer ) {
+ CG_DrawDisconnect();
+ return;
+ }
+
+ //
+ // draw the graph
+ //
+#ifdef MISSIONPACK
+ x = 640 - 48;
+ y = 480 - 144;
+#else
+ x = 640 - 48;
+ y = 480 - 48;
+#endif
+
+ trap_R_SetColor( NULL );
+ CG_DrawPic( x, y, 48, 48, cgs.media.lagometerShader );
+
+ ax = x;
+ ay = y;
+ aw = 48;
+ ah = 48;
+ CG_AdjustFrom640( &ax, &ay, &aw, &ah );
+
+ color = -1;
+ range = ah / 3;
+ mid = ay + range;
+
+ vscale = range / MAX_LAGOMETER_RANGE;
+
+ // draw the frame interpoalte / extrapolate graph
+ for ( a = 0 ; a < aw ; a++ ) {
+ i = ( lagometer.frameCount - 1 - a ) & (LAG_SAMPLES - 1);
+ v = lagometer.frameSamples[i];
+ v *= vscale;
+ if ( v > 0 ) {
+ if ( color != 1 ) {
+ color = 1;
+ trap_R_SetColor( g_color_table[ColorIndex(COLOR_YELLOW)] );
+ }
+ if ( v > range ) {
+ v = range;
+ }
+ trap_R_DrawStretchPic ( ax + aw - a, mid - v, 1, v, 0, 0, 0, 0, cgs.media.whiteShader );
+ } else if ( v < 0 ) {
+ if ( color != 2 ) {
+ color = 2;
+ trap_R_SetColor( g_color_table[ColorIndex(COLOR_BLUE)] );
+ }
+ v = -v;
+ if ( v > range ) {
+ v = range;
+ }
+ trap_R_DrawStretchPic( ax + aw - a, mid, 1, v, 0, 0, 0, 0, cgs.media.whiteShader );
+ }
+ }
+
+ // draw the snapshot latency / drop graph
+ range = ah / 2;
+ vscale = range / MAX_LAGOMETER_PING;
+
+ for ( a = 0 ; a < aw ; a++ ) {
+ i = ( lagometer.snapshotCount - 1 - a ) & (LAG_SAMPLES - 1);
+ v = lagometer.snapshotSamples[i];
+ if ( v > 0 ) {
+ if ( lagometer.snapshotFlags[i] & SNAPFLAG_RATE_DELAYED ) {
+ if ( color != 5 ) {
+ color = 5; // YELLOW for rate delay
+ trap_R_SetColor( g_color_table[ColorIndex(COLOR_YELLOW)] );
+ }
+ } else {
+ if ( color != 3 ) {
+ color = 3;
+ trap_R_SetColor( g_color_table[ColorIndex(COLOR_GREEN)] );
+ }
+ }
+ v = v * vscale;
+ if ( v > range ) {
+ v = range;
+ }
+ trap_R_DrawStretchPic( ax + aw - a, ay + ah - v, 1, v, 0, 0, 0, 0, cgs.media.whiteShader );
+ } else if ( v < 0 ) {
+ if ( color != 4 ) {
+ color = 4; // RED for dropped snapshots
+ trap_R_SetColor( g_color_table[ColorIndex(COLOR_RED)] );
+ }
+ trap_R_DrawStretchPic( ax + aw - a, ay + ah - range, 1, range, 0, 0, 0, 0, cgs.media.whiteShader );
+ }
+ }
+
+ trap_R_SetColor( NULL );
+
+ if ( cg_nopredict.integer || cg_synchronousClients.integer ) {
+ CG_DrawBigString( ax, ay, "snc", 1.0 );
+ }
+
+ CG_DrawDisconnect();
+}
+
+
+
+/*
+===============================================================================
+
+CENTER PRINTING
+
+===============================================================================
+*/
+
+
+/*
+==============
+CG_CenterPrint
+
+Called for important messages that should stay in the center of the screen
+for a few moments
+==============
+*/
+void CG_CenterPrint( const char *str, int y, int charWidth ) {
+ char *s;
+
+ Q_strncpyz( cg.centerPrint, str, sizeof(cg.centerPrint) );
+
+ cg.centerPrintTime = cg.time;
+ cg.centerPrintY = y;
+ cg.centerPrintCharWidth = charWidth;
+
+ // count the number of lines for centering
+ cg.centerPrintLines = 1;
+ s = cg.centerPrint;
+ while( *s ) {
+ if (*s == '\n')
+ cg.centerPrintLines++;
+ s++;
+ }
+}
+
+
+/*
+===================
+CG_DrawCenterString
+===================
+*/
+static void CG_DrawCenterString( void ) {
+ char *start;
+ int l;
+ int x, y, w;
+#ifdef MISSIONPACK // bk010221 - unused else
+ int h;
+#endif
+ float *color;
+
+ if ( !cg.centerPrintTime ) {
+ return;
+ }
+
+ color = CG_FadeColor( cg.centerPrintTime, 1000 * cg_centertime.value );
+ if ( !color ) {
+ return;
+ }
+
+ trap_R_SetColor( color );
+
+ start = cg.centerPrint;
+
+ y = cg.centerPrintY - cg.centerPrintLines * BIGCHAR_HEIGHT / 2;
+
+ while ( 1 ) {
+ char linebuffer[1024];
+
+ for ( l = 0; l < 50; l++ ) {
+ if ( !start[l] || start[l] == '\n' ) {
+ break;
+ }
+ linebuffer[l] = start[l];
+ }
+ linebuffer[l] = 0;
+
+#ifdef MISSIONPACK
+ w = CG_Text_Width(linebuffer, 0.5, 0);
+ h = CG_Text_Height(linebuffer, 0.5, 0);
+ x = (SCREEN_WIDTH - w) / 2;
+ CG_Text_Paint(x, y + h, 0.5, color, linebuffer, 0, 0, ITEM_TEXTSTYLE_SHADOWEDMORE);
+ y += h + 6;
+#else
+ w = cg.centerPrintCharWidth * CG_DrawStrlen( linebuffer );
+
+ x = ( SCREEN_WIDTH - w ) / 2;
+
+ CG_DrawStringExt( x, y, linebuffer, color, qfalse, qtrue,
+ cg.centerPrintCharWidth, (int)(cg.centerPrintCharWidth * 1.5), 0 );
+
+ y += cg.centerPrintCharWidth * 1.5;
+#endif
+ while ( *start && ( *start != '\n' ) ) {
+ start++;
+ }
+ if ( !*start ) {
+ break;
+ }
+ start++;
+ }
+
+ trap_R_SetColor( NULL );
+}
+
+
+
+/*
+================================================================================
+
+CROSSHAIR
+
+================================================================================
+*/
+
+
+/*
+=================
+CG_DrawCrosshair
+=================
+*/
+static void CG_DrawCrosshair(void) {
+ float w, h;
+ qhandle_t hShader;
+ float f;
+ float x, y;
+ int ca;
+
+ if ( !cg_drawCrosshair.integer ) {
+ return;
+ }
+
+ if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR) {
+ return;
+ }
+
+ if ( cg.renderingThirdPerson ) {
+ return;
+ }
+
+ // set color based on health
+ if ( cg_crosshairHealth.integer ) {
+ vec4_t hcolor;
+
+ CG_ColorForHealth( hcolor );
+ trap_R_SetColor( hcolor );
+ } else {
+ trap_R_SetColor( NULL );
+ }
+
+ w = h = cg_crosshairSize.value;
+
+ // pulse the size of the crosshair when picking up items
+ f = cg.time - cg.itemPickupBlendTime;
+ if ( f > 0 && f < ITEM_BLOB_TIME ) {
+ f /= ITEM_BLOB_TIME;
+ w *= ( 1 + f );
+ h *= ( 1 + f );
+ }
+
+ x = cg_crosshairX.integer;
+ y = cg_crosshairY.integer;
+ CG_AdjustFrom640( &x, &y, &w, &h );
+
+ ca = cg_drawCrosshair.integer;
+ if (ca < 0) {
+ ca = 0;
+ }
+ hShader = cgs.media.crosshairShader[ ca % NUM_CROSSHAIRS ];
+
+ trap_R_DrawStretchPic( x + cg.refdef.x + 0.5 * (cg.refdef.width - w),
+ y + cg.refdef.y + 0.5 * (cg.refdef.height - h),
+ w, h, 0, 0, 1, 1, hShader );
+}
+
+
+
+/*
+=================
+CG_ScanForCrosshairEntity
+=================
+*/
+static void CG_ScanForCrosshairEntity( void ) {
+ trace_t trace;
+ vec3_t start, end;
+ int content;
+
+ VectorCopy( cg.refdef.vieworg, start );
+ VectorMA( start, 131072, cg.refdef.viewaxis[0], end );
+
+ CG_Trace( &trace, start, vec3_origin, vec3_origin, end,
+ cg.snap->ps.clientNum, CONTENTS_SOLID|CONTENTS_BODY );
+ if ( trace.entityNum >= MAX_CLIENTS ) {
+ return;
+ }
+
+ // if the player is in fog, don't show it
+ content = trap_CM_PointContents( trace.endpos, 0 );
+ if ( content & CONTENTS_FOG ) {
+ return;
+ }
+
+ // if the player is invisible, don't show it
+ if ( cg_entities[ trace.entityNum ].currentState.powerups & ( 1 << PW_INVIS ) ) {
+ return;
+ }
+
+ // update the fade timer
+ cg.crosshairClientNum = trace.entityNum;
+ cg.crosshairClientTime = cg.time;
+}
+
+
+/*
+=====================
+CG_DrawCrosshairNames
+=====================
+*/
+static void CG_DrawCrosshairNames( void ) {
+ float *color;
+ char *name;
+ float w;
+
+ if ( !cg_drawCrosshair.integer ) {
+ return;
+ }
+ if ( !cg_drawCrosshairNames.integer ) {
+ return;
+ }
+ if ( cg.renderingThirdPerson ) {
+ return;
+ }
+
+ // scan the known entities to see if the crosshair is sighted on one
+ CG_ScanForCrosshairEntity();
+
+ // draw the name of the player being looked at
+ color = CG_FadeColor( cg.crosshairClientTime, 1000 );
+ if ( !color ) {
+ trap_R_SetColor( NULL );
+ return;
+ }
+
+ name = cgs.clientinfo[ cg.crosshairClientNum ].name;
+#ifdef MISSIONPACK
+ color[3] *= 0.5f;
+ w = CG_Text_Width(name, 0.3f, 0);
+ CG_Text_Paint( 320 - w / 2, 190, 0.3f, color, name, 0, 0, ITEM_TEXTSTYLE_SHADOWED);
+#else
+ w = CG_DrawStrlen( name ) * BIGCHAR_WIDTH;
+ CG_DrawBigString( 320 - w / 2, 170, name, color[3] * 0.5f );
+#endif
+ trap_R_SetColor( NULL );
+}
+
+
+//==============================================================================
+
+/*
+=================
+CG_DrawSpectator
+=================
+*/
+static void CG_DrawSpectator(void) {
+ CG_DrawBigString(320 - 9 * 8, 440, "SPECTATOR", 1.0F);
+ if ( cgs.gametype == GT_TOURNAMENT ) {
+ CG_DrawBigString(320 - 15 * 8, 460, "waiting to play", 1.0F);
+ }
+ else if ( cgs.gametype >= GT_TEAM ) {
+ CG_DrawBigString(320 - 39 * 8, 460, "press ESC and use the JOIN menu to play", 1.0F);
+ }
+}
+
+/*
+=================
+CG_DrawVote
+=================
+*/
+static void CG_DrawVote(void) {
+ char *s;
+ int sec;
+
+ if ( !cgs.voteTime ) {
+ return;
+ }
+
+ // play a talk beep whenever it is modified
+ if ( cgs.voteModified ) {
+ cgs.voteModified = qfalse;
+ trap_S_StartLocalSound( cgs.media.talkSound, CHAN_LOCAL_SOUND );
+ }
+
+ sec = ( VOTE_TIME - ( cg.time - cgs.voteTime ) ) / 1000;
+ if ( sec < 0 ) {
+ sec = 0;
+ }
+#ifdef MISSIONPACK
+ s = va("VOTE(%i):%s yes:%i no:%i", sec, cgs.voteString, cgs.voteYes, cgs.voteNo);
+ CG_DrawSmallString( 0, 58, s, 1.0F );
+ s = "or press ESC then click Vote";
+ CG_DrawSmallString( 0, 58 + SMALLCHAR_HEIGHT + 2, s, 1.0F );
+#else
+ s = va("VOTE(%i):%s yes:%i no:%i", sec, cgs.voteString, cgs.voteYes, cgs.voteNo );
+ CG_DrawSmallString( 0, 58, s, 1.0F );
+#endif
+}
+
+/*
+=================
+CG_DrawTeamVote
+=================
+*/
+static void CG_DrawTeamVote(void) {
+ char *s;
+ int sec, cs_offset;
+
+ if ( cgs.clientinfo->team == TEAM_RED )
+ cs_offset = 0;
+ else if ( cgs.clientinfo->team == TEAM_BLUE )
+ cs_offset = 1;
+ else
+ return;
+
+ if ( !cgs.teamVoteTime[cs_offset] ) {
+ return;
+ }
+
+ // play a talk beep whenever it is modified
+ if ( cgs.teamVoteModified[cs_offset] ) {
+ cgs.teamVoteModified[cs_offset] = qfalse;
+ trap_S_StartLocalSound( cgs.media.talkSound, CHAN_LOCAL_SOUND );
+ }
+
+ sec = ( VOTE_TIME - ( cg.time - cgs.teamVoteTime[cs_offset] ) ) / 1000;
+ if ( sec < 0 ) {
+ sec = 0;
+ }
+ s = va("TEAMVOTE(%i):%s yes:%i no:%i", sec, cgs.teamVoteString[cs_offset],
+ cgs.teamVoteYes[cs_offset], cgs.teamVoteNo[cs_offset] );
+ CG_DrawSmallString( 0, 90, s, 1.0F );
+}
+
+
+static qboolean CG_DrawScoreboard() {
+#ifdef MISSIONPACK
+ static qboolean firstTime = qtrue;
+ float fade, *fadeColor;
+
+ if (menuScoreboard) {
+ menuScoreboard->window.flags &= ~WINDOW_FORCED;
+ }
+ if (cg_paused.integer) {
+ cg.deferredPlayerLoading = 0;
+ firstTime = qtrue;
+ return qfalse;
+ }
+
+ // should never happen in Team Arena
+ if (cgs.gametype == GT_SINGLE_PLAYER && cg.predictedPlayerState.pm_type == PM_INTERMISSION ) {
+ cg.deferredPlayerLoading = 0;
+ firstTime = qtrue;
+ return qfalse;
+ }
+
+ // don't draw scoreboard during death while warmup up
+ if ( cg.warmup && !cg.showScores ) {
+ return qfalse;
+ }
+
+ if ( cg.showScores || cg.predictedPlayerState.pm_type == PM_DEAD || cg.predictedPlayerState.pm_type == PM_INTERMISSION ) {
+ fade = 1.0;
+ fadeColor = colorWhite;
+ } else {
+ fadeColor = CG_FadeColor( cg.scoreFadeTime, FADE_TIME );
+ if ( !fadeColor ) {
+ // next time scoreboard comes up, don't print killer
+ cg.deferredPlayerLoading = 0;
+ cg.killerName[0] = 0;
+ firstTime = qtrue;
+ return qfalse;
+ }
+ fade = *fadeColor;
+ }
+
+
+ if (menuScoreboard == NULL) {
+ if ( cgs.gametype >= GT_TEAM ) {
+ menuScoreboard = Menus_FindByName("teamscore_menu");
+ } else {
+ menuScoreboard = Menus_FindByName("score_menu");
+ }
+ }
+
+ if (menuScoreboard) {
+ if (firstTime) {
+ CG_SetScoreSelection(menuScoreboard);
+ firstTime = qfalse;
+ }
+ Menu_Paint(menuScoreboard, qtrue);
+ }
+
+ // load any models that have been deferred
+ if ( ++cg.deferredPlayerLoading > 10 ) {
+ CG_LoadDeferredPlayers();
+ }
+
+ return qtrue;
+#else
+ return CG_DrawOldScoreboard();
+#endif
+}
+
+/*
+=================
+CG_DrawIntermission
+=================
+*/
+static void CG_DrawIntermission( void ) {
+// int key;
+#ifdef MISSIONPACK
+ //if (cg_singlePlayer.integer) {
+ // CG_DrawCenterString();
+ // return;
+ //}
+#else
+ if ( cgs.gametype == GT_SINGLE_PLAYER ) {
+ CG_DrawCenterString();
+ return;
+ }
+#endif
+ cg.scoreFadeTime = cg.time;
+ cg.scoreBoardShowing = CG_DrawScoreboard();
+}
+
+/*
+=================
+CG_DrawFollow
+=================
+*/
+static qboolean CG_DrawFollow( void ) {
+ float x;
+ vec4_t color;
+ const char *name;
+
+ if ( !(cg.snap->ps.pm_flags & PMF_FOLLOW) ) {
+ return qfalse;
+ }
+ color[0] = 1;
+ color[1] = 1;
+ color[2] = 1;
+ color[3] = 1;
+
+
+ CG_DrawBigString( 320 - 9 * 8, 24, "following", 1.0F );
+
+ name = cgs.clientinfo[ cg.snap->ps.clientNum ].name;
+
+ x = 0.5 * ( 640 - GIANT_WIDTH * CG_DrawStrlen( name ) );
+
+ CG_DrawStringExt( x, 40, name, color, qtrue, qtrue, GIANT_WIDTH, GIANT_HEIGHT, 0 );
+
+ return qtrue;
+}
+
+
+
+/*
+=================
+CG_DrawAmmoWarning
+=================
+*/
+static void CG_DrawAmmoWarning( void ) {
+ const char *s;
+ int w;
+
+ if ( cg_drawAmmoWarning.integer == 0 ) {
+ return;
+ }
+
+ if ( !cg.lowAmmoWarning ) {
+ return;
+ }
+
+ if ( cg.lowAmmoWarning == 2 ) {
+ s = "OUT OF AMMO";
+ } else {
+ s = "LOW AMMO WARNING";
+ }
+ w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH;
+ CG_DrawBigString(320 - w / 2, 64, s, 1.0F);
+}
+
+
+#ifdef MISSIONPACK
+/*
+=================
+CG_DrawProxWarning
+=================
+*/
+static void CG_DrawProxWarning( void ) {
+ char s [32];
+ int w;
+ static int proxTime;
+ static int proxCounter;
+ static int proxTick;
+
+ if( !(cg.snap->ps.eFlags & EF_TICKING ) ) {
+ proxTime = 0;
+ return;
+ }
+
+ if (proxTime == 0) {
+ proxTime = cg.time + 5000;
+ proxCounter = 5;
+ proxTick = 0;
+ }
+
+ if (cg.time > proxTime) {
+ proxTick = proxCounter--;
+ proxTime = cg.time + 1000;
+ }
+
+ if (proxTick != 0) {
+ Com_sprintf(s, sizeof(s), "INTERNAL COMBUSTION IN: %i", proxTick);
+ } else {
+ Com_sprintf(s, sizeof(s), "YOU HAVE BEEN MINED");
+ }
+
+ w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH;
+ CG_DrawBigStringColor( 320 - w / 2, 64 + BIGCHAR_HEIGHT, s, g_color_table[ColorIndex(COLOR_RED)] );
+}
+#endif
+
+
+/*
+=================
+CG_DrawWarmup
+=================
+*/
+static void CG_DrawWarmup( void ) {
+ int w;
+ int sec;
+ int i;
+ float scale;
+ clientInfo_t *ci1, *ci2;
+ int cw;
+ const char *s;
+
+ sec = cg.warmup;
+ if ( !sec ) {
+ return;
+ }
+
+ if ( sec < 0 ) {
+ s = "Waiting for players";
+ w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH;
+ CG_DrawBigString(320 - w / 2, 24, s, 1.0F);
+ cg.warmupCount = 0;
+ return;
+ }
+
+ if (cgs.gametype == GT_TOURNAMENT) {
+ // find the two active players
+ ci1 = NULL;
+ ci2 = NULL;
+ for ( i = 0 ; i < cgs.maxclients ; i++ ) {
+ if ( cgs.clientinfo[i].infoValid && cgs.clientinfo[i].team == TEAM_FREE ) {
+ if ( !ci1 ) {
+ ci1 = &cgs.clientinfo[i];
+ } else {
+ ci2 = &cgs.clientinfo[i];
+ }
+ }
+ }
+
+ if ( ci1 && ci2 ) {
+ s = va( "%s vs %s", ci1->name, ci2->name );
+#ifdef MISSIONPACK
+ w = CG_Text_Width(s, 0.6f, 0);
+ CG_Text_Paint(320 - w / 2, 60, 0.6f, colorWhite, s, 0, 0, ITEM_TEXTSTYLE_SHADOWEDMORE);
+#else
+ w = CG_DrawStrlen( s );
+ if ( w > 640 / GIANT_WIDTH ) {
+ cw = 640 / w;
+ } else {
+ cw = GIANT_WIDTH;
+ }
+ CG_DrawStringExt( 320 - w * cw/2, 20,s, colorWhite,
+ qfalse, qtrue, cw, (int)(cw * 1.5f), 0 );
+#endif
+ }
+ } else {
+ if ( cgs.gametype == GT_FFA ) {
+ s = "Free For All";
+ } else if ( cgs.gametype == GT_TEAM ) {
+ s = "Team Deathmatch";
+ } else if ( cgs.gametype == GT_CTF ) {
+ s = "Capture the Flag";
+#ifdef MISSIONPACK
+ } else if ( cgs.gametype == GT_1FCTF ) {
+ s = "One Flag CTF";
+ } else if ( cgs.gametype == GT_OBELISK ) {
+ s = "Overload";
+ } else if ( cgs.gametype == GT_HARVESTER ) {
+ s = "Harvester";
+#endif
+ } else {
+ s = "";
+ }
+#ifdef MISSIONPACK
+ w = CG_Text_Width(s, 0.6f, 0);
+ CG_Text_Paint(320 - w / 2, 90, 0.6f, colorWhite, s, 0, 0, ITEM_TEXTSTYLE_SHADOWEDMORE);
+#else
+ w = CG_DrawStrlen( s );
+ if ( w > 640 / GIANT_WIDTH ) {
+ cw = 640 / w;
+ } else {
+ cw = GIANT_WIDTH;
+ }
+ CG_DrawStringExt( 320 - w * cw/2, 25,s, colorWhite,
+ qfalse, qtrue, cw, (int)(cw * 1.1f), 0 );
+#endif
+ }
+
+ sec = ( sec - cg.time ) / 1000;
+ if ( sec < 0 ) {
+ cg.warmup = 0;
+ sec = 0;
+ }
+ s = va( "Starts in: %i", sec + 1 );
+ if ( sec != cg.warmupCount ) {
+ cg.warmupCount = sec;
+ switch ( sec ) {
+ case 0:
+ trap_S_StartLocalSound( cgs.media.count1Sound, CHAN_ANNOUNCER );
+ break;
+ case 1:
+ trap_S_StartLocalSound( cgs.media.count2Sound, CHAN_ANNOUNCER );
+ break;
+ case 2:
+ trap_S_StartLocalSound( cgs.media.count3Sound, CHAN_ANNOUNCER );
+ break;
+ default:
+ break;
+ }
+ }
+ scale = 0.45f;
+ switch ( cg.warmupCount ) {
+ case 0:
+ cw = 28;
+ scale = 0.54f;
+ break;
+ case 1:
+ cw = 24;
+ scale = 0.51f;
+ break;
+ case 2:
+ cw = 20;
+ scale = 0.48f;
+ break;
+ default:
+ cw = 16;
+ scale = 0.45f;
+ break;
+ }
+
+#ifdef MISSIONPACK
+ w = CG_Text_Width(s, scale, 0);
+ CG_Text_Paint(320 - w / 2, 125, scale, colorWhite, s, 0, 0, ITEM_TEXTSTYLE_SHADOWEDMORE);
+#else
+ w = CG_DrawStrlen( s );
+ CG_DrawStringExt( 320 - w * cw/2, 70, s, colorWhite,
+ qfalse, qtrue, cw, (int)(cw * 1.5), 0 );
+#endif
+}
+
+//==================================================================================
+#ifdef MISSIONPACK
+/*
+=================
+CG_DrawTimedMenus
+=================
+*/
+void CG_DrawTimedMenus() {
+ if (cg.voiceTime) {
+ int t = cg.time - cg.voiceTime;
+ if ( t > 2500 ) {
+ Menus_CloseByName("voiceMenu");
+ trap_Cvar_Set("cl_conXOffset", "0");
+ cg.voiceTime = 0;
+ }
+ }
+}
+#endif
+/*
+=================
+CG_Draw2D
+=================
+*/
+static void CG_Draw2D( void ) {
+#ifdef MISSIONPACK
+ if (cgs.orderPending && cg.time > cgs.orderTime) {
+ CG_CheckOrderPending();
+ }
+#endif
+ // if we are taking a levelshot for the menu, don't draw anything
+ if ( cg.levelShot ) {
+ return;
+ }
+
+ if ( cg_draw2D.integer == 0 ) {
+ return;
+ }
+
+ if ( cg.snap->ps.pm_type == PM_INTERMISSION ) {
+ CG_DrawIntermission();
+ return;
+ }
+
+/*
+ if (cg.cameraMode) {
+ return;
+ }
+*/
+ if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR ) {
+ CG_DrawSpectator();
+ CG_DrawCrosshair();
+ CG_DrawCrosshairNames();
+ } else {
+ // don't draw any status if dead or the scoreboard is being explicitly shown
+ if ( !cg.showScores && cg.snap->ps.stats[STAT_HEALTH] > 0 ) {
+
+#ifdef MISSIONPACK
+ if ( cg_drawStatus.integer ) {
+ Menu_PaintAll();
+ CG_DrawTimedMenus();
+ }
+#else
+ CG_DrawStatusBar();
+#endif
+
+ CG_DrawAmmoWarning();
+
+#ifdef MISSIONPACK
+ CG_DrawProxWarning();
+#endif
+ CG_DrawCrosshair();
+ CG_DrawCrosshairNames();
+ CG_DrawWeaponSelect();
+
+#ifndef MISSIONPACK
+ CG_DrawHoldableItem();
+#else
+ //CG_DrawPersistantPowerup();
+#endif
+ CG_DrawReward();
+ }
+
+ if ( cgs.gametype >= GT_TEAM ) {
+#ifndef MISSIONPACK
+ CG_DrawTeamInfo();
+#endif
+ }
+ }
+
+ CG_DrawVote();
+ CG_DrawTeamVote();
+
+ CG_DrawLagometer();
+
+#ifdef MISSIONPACK
+ if (!cg_paused.integer) {
+ CG_DrawUpperRight();
+ }
+#else
+ CG_DrawUpperRight();
+#endif
+
+#ifndef MISSIONPACK
+ CG_DrawLowerRight();
+ CG_DrawLowerLeft();
+#endif
+
+ if ( !CG_DrawFollow() ) {
+ CG_DrawWarmup();
+ }
+
+ // don't draw center string if scoreboard is up
+ cg.scoreBoardShowing = CG_DrawScoreboard();
+ if ( !cg.scoreBoardShowing) {
+ CG_DrawCenterString();
+ }
+}
+
+
+static void CG_DrawTourneyScoreboard() {
+#ifdef MISSIONPACK
+#else
+ CG_DrawOldTourneyScoreboard();
+#endif
+}
+
+/*
+=====================
+CG_DrawActive
+
+Perform all drawing needed to completely fill the screen
+=====================
+*/
+void CG_DrawActive( stereoFrame_t stereoView ) {
+ float separation;
+ vec3_t baseOrg;
+
+ // optionally draw the info screen instead
+ if ( !cg.snap ) {
+ CG_DrawInformation();
+ return;
+ }
+
+ // optionally draw the tournement scoreboard instead
+ if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR &&
+ ( cg.snap->ps.pm_flags & PMF_SCOREBOARD ) ) {
+ CG_DrawTourneyScoreboard();
+ return;
+ }
+
+ switch ( stereoView ) {
+ case STEREO_CENTER:
+ separation = 0;
+ break;
+ case STEREO_LEFT:
+ separation = -cg_stereoSeparation.value / 2;
+ break;
+ case STEREO_RIGHT:
+ separation = cg_stereoSeparation.value / 2;
+ break;
+ default:
+ separation = 0;
+ CG_Error( "CG_DrawActive: Undefined stereoView" );
+ }
+
+
+ // clear around the rendered view if sized down
+ CG_TileClear();
+
+ // offset vieworg appropriately if we're doing stereo separation
+ VectorCopy( cg.refdef.vieworg, baseOrg );
+ if ( separation != 0 ) {
+ VectorMA( cg.refdef.vieworg, -separation, cg.refdef.viewaxis[1], cg.refdef.vieworg );
+ }
+
+ // draw 3D view
+ trap_R_RenderScene( &cg.refdef );
+
+ // restore original viewpoint if running stereo
+ if ( separation != 0 ) {
+ VectorCopy( baseOrg, cg.refdef.vieworg );
+ }
+
+ // draw status bar and other floating elements
+ CG_Draw2D();
+}
+
+
+
diff --git a/code/cgame/cg_drawtools.c b/code/cgame/cg_drawtools.c
new file mode 100755
index 0000000..9c27606
--- /dev/null
+++ b/code/cgame/cg_drawtools.c
@@ -0,0 +1,824 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// cg_drawtools.c -- helper functions called by cg_draw, cg_scoreboard, cg_info, etc
+#include "cg_local.h"
+
+/*
+================
+CG_AdjustFrom640
+
+Adjusted for resolution and screen aspect ratio
+================
+*/
+void CG_AdjustFrom640( float *x, float *y, float *w, float *h ) {
+#if 0
+ // adjust for wide screens
+ if ( cgs.glconfig.vidWidth * 480 > cgs.glconfig.vidHeight * 640 ) {
+ *x += 0.5 * ( cgs.glconfig.vidWidth - ( cgs.glconfig.vidHeight * 640 / 480 ) );
+ }
+#endif
+ // scale for screen sizes
+ *x *= cgs.screenXScale;
+ *y *= cgs.screenYScale;
+ *w *= cgs.screenXScale;
+ *h *= cgs.screenYScale;
+}
+
+/*
+================
+CG_FillRect
+
+Coordinates are 640*480 virtual values
+=================
+*/
+void CG_FillRect( float x, float y, float width, float height, const float *color ) {
+ trap_R_SetColor( color );
+
+ CG_AdjustFrom640( &x, &y, &width, &height );
+ trap_R_DrawStretchPic( x, y, width, height, 0, 0, 0, 0, cgs.media.whiteShader );
+
+ trap_R_SetColor( NULL );
+}
+
+/*
+================
+CG_DrawSides
+
+Coords are virtual 640x480
+================
+*/
+void CG_DrawSides(float x, float y, float w, float h, float size) {
+ CG_AdjustFrom640( &x, &y, &w, &h );
+ size *= cgs.screenXScale;
+ trap_R_DrawStretchPic( x, y, size, h, 0, 0, 0, 0, cgs.media.whiteShader );
+ trap_R_DrawStretchPic( x + w - size, y, size, h, 0, 0, 0, 0, cgs.media.whiteShader );
+}
+
+void CG_DrawTopBottom(float x, float y, float w, float h, float size) {
+ CG_AdjustFrom640( &x, &y, &w, &h );
+ size *= cgs.screenYScale;
+ trap_R_DrawStretchPic( x, y, w, size, 0, 0, 0, 0, cgs.media.whiteShader );
+ trap_R_DrawStretchPic( x, y + h - size, w, size, 0, 0, 0, 0, cgs.media.whiteShader );
+}
+/*
+================
+UI_DrawRect
+
+Coordinates are 640*480 virtual values
+=================
+*/
+void CG_DrawRect( float x, float y, float width, float height, float size, const float *color ) {
+ trap_R_SetColor( color );
+
+ CG_DrawTopBottom(x, y, width, height, size);
+ CG_DrawSides(x, y, width, height, size);
+
+ trap_R_SetColor( NULL );
+}
+
+
+
+/*
+================
+CG_DrawPic
+
+Coordinates are 640*480 virtual values
+=================
+*/
+void CG_DrawPic( float x, float y, float width, float height, qhandle_t hShader ) {
+ CG_AdjustFrom640( &x, &y, &width, &height );
+ trap_R_DrawStretchPic( x, y, width, height, 0, 0, 1, 1, hShader );
+}
+
+
+
+/*
+===============
+CG_DrawChar
+
+Coordinates and size in 640*480 virtual screen size
+===============
+*/
+void CG_DrawChar( int x, int y, int width, int height, int ch ) {
+ int row, col;
+ float frow, fcol;
+ float size;
+ float ax, ay, aw, ah;
+
+ ch &= 255;
+
+ if ( ch == ' ' ) {
+ return;
+ }
+
+ ax = x;
+ ay = y;
+ aw = width;
+ ah = height;
+ CG_AdjustFrom640( &ax, &ay, &aw, &ah );
+
+ row = ch>>4;
+ col = ch&15;
+
+ frow = row*0.0625;
+ fcol = col*0.0625;
+ size = 0.0625;
+
+ trap_R_DrawStretchPic( ax, ay, aw, ah,
+ fcol, frow,
+ fcol + size, frow + size,
+ cgs.media.charsetShader );
+}
+
+
+/*
+==================
+CG_DrawStringExt
+
+Draws a multi-colored string with a drop shadow, optionally forcing
+to a fixed color.
+
+Coordinates are at 640 by 480 virtual resolution
+==================
+*/
+void CG_DrawStringExt( int x, int y, const char *string, const float *setColor,
+ qboolean forceColor, qboolean shadow, int charWidth, int charHeight, int maxChars ) {
+ vec4_t color;
+ const char *s;
+ int xx;
+ int cnt;
+
+ if (maxChars <= 0)
+ maxChars = 32767; // do them all!
+
+ // draw the drop shadow
+ if (shadow) {
+ color[0] = color[1] = color[2] = 0;
+ color[3] = setColor[3];
+ trap_R_SetColor( color );
+ s = string;
+ xx = x;
+ cnt = 0;
+ while ( *s && cnt < maxChars) {
+ if ( Q_IsColorString( s ) ) {
+ s += 2;
+ continue;
+ }
+ CG_DrawChar( xx + 2, y + 2, charWidth, charHeight, *s );
+ cnt++;
+ xx += charWidth;
+ s++;
+ }
+ }
+
+ // draw the colored text
+ s = string;
+ xx = x;
+ cnt = 0;
+ trap_R_SetColor( setColor );
+ while ( *s && cnt < maxChars) {
+ if ( Q_IsColorString( s ) ) {
+ if ( !forceColor ) {
+ memcpy( color, g_color_table[ColorIndex(*(s+1))], sizeof( color ) );
+ color[3] = setColor[3];
+ trap_R_SetColor( color );
+ }
+ s += 2;
+ continue;
+ }
+ CG_DrawChar( xx, y, charWidth, charHeight, *s );
+ xx += charWidth;
+ cnt++;
+ s++;
+ }
+ trap_R_SetColor( NULL );
+}
+
+void CG_DrawBigString( int x, int y, const char *s, float alpha ) {
+ float color[4];
+
+ color[0] = color[1] = color[2] = 1.0;
+ color[3] = alpha;
+ CG_DrawStringExt( x, y, s, color, qfalse, qtrue, BIGCHAR_WIDTH, BIGCHAR_HEIGHT, 0 );
+}
+
+void CG_DrawBigStringColor( int x, int y, const char *s, vec4_t color ) {
+ CG_DrawStringExt( x, y, s, color, qtrue, qtrue, BIGCHAR_WIDTH, BIGCHAR_HEIGHT, 0 );
+}
+
+void CG_DrawSmallString( int x, int y, const char *s, float alpha ) {
+ float color[4];
+
+ color[0] = color[1] = color[2] = 1.0;
+ color[3] = alpha;
+ CG_DrawStringExt( x, y, s, color, qfalse, qfalse, SMALLCHAR_WIDTH, SMALLCHAR_HEIGHT, 0 );
+}
+
+void CG_DrawSmallStringColor( int x, int y, const char *s, vec4_t color ) {
+ CG_DrawStringExt( x, y, s, color, qtrue, qfalse, SMALLCHAR_WIDTH, SMALLCHAR_HEIGHT, 0 );
+}
+
+/*
+=================
+CG_DrawStrlen
+
+Returns character count, skiping color escape codes
+=================
+*/
+int CG_DrawStrlen( const char *str ) {
+ const char *s = str;
+ int count = 0;
+
+ while ( *s ) {
+ if ( Q_IsColorString( s ) ) {
+ s += 2;
+ } else {
+ count++;
+ s++;
+ }
+ }
+
+ return count;
+}
+
+/*
+=============
+CG_TileClearBox
+
+This repeats a 64*64 tile graphic to fill the screen around a sized down
+refresh window.
+=============
+*/
+static void CG_TileClearBox( int x, int y, int w, int h, qhandle_t hShader ) {
+ float s1, t1, s2, t2;
+
+ s1 = x/64.0;
+ t1 = y/64.0;
+ s2 = (x+w)/64.0;
+ t2 = (y+h)/64.0;
+ trap_R_DrawStretchPic( x, y, w, h, s1, t1, s2, t2, hShader );
+}
+
+
+
+/*
+==============
+CG_TileClear
+
+Clear around a sized down screen
+==============
+*/
+void CG_TileClear( void ) {
+ int top, bottom, left, right;
+ int w, h;
+
+ w = cgs.glconfig.vidWidth;
+ h = cgs.glconfig.vidHeight;
+
+ if ( cg.refdef.x == 0 && cg.refdef.y == 0 &&
+ cg.refdef.width == w && cg.refdef.height == h ) {
+ return; // full screen rendering
+ }
+
+ top = cg.refdef.y;
+ bottom = top + cg.refdef.height-1;
+ left = cg.refdef.x;
+ right = left + cg.refdef.width-1;
+
+ // clear above view screen
+ CG_TileClearBox( 0, 0, w, top, cgs.media.backTileShader );
+
+ // clear below view screen
+ CG_TileClearBox( 0, bottom, w, h - bottom, cgs.media.backTileShader );
+
+ // clear left of view screen
+ CG_TileClearBox( 0, top, left, bottom - top + 1, cgs.media.backTileShader );
+
+ // clear right of view screen
+ CG_TileClearBox( right, top, w - right, bottom - top + 1, cgs.media.backTileShader );
+}
+
+
+
+/*
+================
+CG_FadeColor
+================
+*/
+float *CG_FadeColor( int startMsec, int totalMsec ) {
+ static vec4_t color;
+ int t;
+
+ if ( startMsec == 0 ) {
+ return NULL;
+ }
+
+ t = cg.time - startMsec;
+
+ if ( t >= totalMsec ) {
+ return NULL;
+ }
+
+ // fade out
+ if ( totalMsec - t < FADE_TIME ) {
+ color[3] = ( totalMsec - t ) * 1.0/FADE_TIME;
+ } else {
+ color[3] = 1.0;
+ }
+ color[0] = color[1] = color[2] = 1;
+
+ return color;
+}
+
+
+/*
+================
+CG_TeamColor
+================
+*/
+float *CG_TeamColor( int team ) {
+ static vec4_t red = {1, 0.2f, 0.2f, 1};
+ static vec4_t blue = {0.2f, 0.2f, 1, 1};
+ static vec4_t other = {1, 1, 1, 1};
+ static vec4_t spectator = {0.7f, 0.7f, 0.7f, 1};
+
+ switch ( team ) {
+ case TEAM_RED:
+ return red;
+ case TEAM_BLUE:
+ return blue;
+ case TEAM_SPECTATOR:
+ return spectator;
+ default:
+ return other;
+ }
+}
+
+
+
+/*
+=================
+CG_GetColorForHealth
+=================
+*/
+void CG_GetColorForHealth( int health, int armor, vec4_t hcolor ) {
+ int count;
+ int max;
+
+ // calculate the total points of damage that can
+ // be sustained at the current health / armor level
+ if ( health <= 0 ) {
+ VectorClear( hcolor ); // black
+ hcolor[3] = 1;
+ return;
+ }
+ count = armor;
+ max = health * ARMOR_PROTECTION / ( 1.0 - ARMOR_PROTECTION );
+ if ( max < count ) {
+ count = max;
+ }
+ health += count;
+
+ // set the color based on health
+ hcolor[0] = 1.0;
+ hcolor[3] = 1.0;
+ if ( health >= 100 ) {
+ hcolor[2] = 1.0;
+ } else if ( health < 66 ) {
+ hcolor[2] = 0;
+ } else {
+ hcolor[2] = ( health - 66 ) / 33.0;
+ }
+
+ if ( health > 60 ) {
+ hcolor[1] = 1.0;
+ } else if ( health < 30 ) {
+ hcolor[1] = 0;
+ } else {
+ hcolor[1] = ( health - 30 ) / 30.0;
+ }
+}
+
+/*
+=================
+CG_ColorForHealth
+=================
+*/
+void CG_ColorForHealth( vec4_t hcolor ) {
+
+ CG_GetColorForHealth( cg.snap->ps.stats[STAT_HEALTH],
+ cg.snap->ps.stats[STAT_ARMOR], hcolor );
+}
+
+
+
+
+// bk001205 - code below duplicated in q3_ui/ui-atoms.c
+// bk001205 - FIXME: does this belong in ui_shared.c?
+// bk001205 - FIXME: HARD_LINKED flags not visible here
+#ifndef Q3_STATIC // bk001205 - q_shared defines not visible here
+/*
+=================
+UI_DrawProportionalString2
+=================
+*/
+static int propMap[128][3] = {
+{0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1},
+{0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1},
+
+{0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1},
+{0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1},
+
+{0, 0, PROP_SPACE_WIDTH}, // SPACE
+{11, 122, 7}, // !
+{154, 181, 14}, // "
+{55, 122, 17}, // #
+{79, 122, 18}, // $
+{101, 122, 23}, // %
+{153, 122, 18}, // &
+{9, 93, 7}, // '
+{207, 122, 8}, // (
+{230, 122, 9}, // )
+{177, 122, 18}, // *
+{30, 152, 18}, // +
+{85, 181, 7}, // ,
+{34, 93, 11}, // -
+{110, 181, 6}, // .
+{130, 152, 14}, // /
+
+{22, 64, 17}, // 0
+{41, 64, 12}, // 1
+{58, 64, 17}, // 2
+{78, 64, 18}, // 3
+{98, 64, 19}, // 4
+{120, 64, 18}, // 5
+{141, 64, 18}, // 6
+{204, 64, 16}, // 7
+{162, 64, 17}, // 8
+{182, 64, 18}, // 9
+{59, 181, 7}, // :
+{35,181, 7}, // ;
+{203, 152, 14}, // <
+{56, 93, 14}, // =
+{228, 152, 14}, // >
+{177, 181, 18}, // ?
+
+{28, 122, 22}, // @
+{5, 4, 18}, // A
+{27, 4, 18}, // B
+{48, 4, 18}, // C
+{69, 4, 17}, // D
+{90, 4, 13}, // E
+{106, 4, 13}, // F
+{121, 4, 18}, // G
+{143, 4, 17}, // H
+{164, 4, 8}, // I
+{175, 4, 16}, // J
+{195, 4, 18}, // K
+{216, 4, 12}, // L
+{230, 4, 23}, // M
+{6, 34, 18}, // N
+{27, 34, 18}, // O
+
+{48, 34, 18}, // P
+{68, 34, 18}, // Q
+{90, 34, 17}, // R
+{110, 34, 18}, // S
+{130, 34, 14}, // T
+{146, 34, 18}, // U
+{166, 34, 19}, // V
+{185, 34, 29}, // W
+{215, 34, 18}, // X
+{234, 34, 18}, // Y
+{5, 64, 14}, // Z
+{60, 152, 7}, // [
+{106, 151, 13}, // '\'
+{83, 152, 7}, // ]
+{128, 122, 17}, // ^
+{4, 152, 21}, // _
+
+{134, 181, 5}, // '
+{5, 4, 18}, // A
+{27, 4, 18}, // B
+{48, 4, 18}, // C
+{69, 4, 17}, // D
+{90, 4, 13}, // E
+{106, 4, 13}, // F
+{121, 4, 18}, // G
+{143, 4, 17}, // H
+{164, 4, 8}, // I
+{175, 4, 16}, // J
+{195, 4, 18}, // K
+{216, 4, 12}, // L
+{230, 4, 23}, // M
+{6, 34, 18}, // N
+{27, 34, 18}, // O
+
+{48, 34, 18}, // P
+{68, 34, 18}, // Q
+{90, 34, 17}, // R
+{110, 34, 18}, // S
+{130, 34, 14}, // T
+{146, 34, 18}, // U
+{166, 34, 19}, // V
+{185, 34, 29}, // W
+{215, 34, 18}, // X
+{234, 34, 18}, // Y
+{5, 64, 14}, // Z
+{153, 152, 13}, // {
+{11, 181, 5}, // |
+{180, 152, 13}, // }
+{79, 93, 17}, // ~
+{0, 0, -1} // DEL
+};
+
+static int propMapB[26][3] = {
+{11, 12, 33},
+{49, 12, 31},
+{85, 12, 31},
+{120, 12, 30},
+{156, 12, 21},
+{183, 12, 21},
+{207, 12, 32},
+
+{13, 55, 30},
+{49, 55, 13},
+{66, 55, 29},
+{101, 55, 31},
+{135, 55, 21},
+{158, 55, 40},
+{204, 55, 32},
+
+{12, 97, 31},
+{48, 97, 31},
+{82, 97, 30},
+{118, 97, 30},
+{153, 97, 30},
+{185, 97, 25},
+{213, 97, 30},
+
+{11, 139, 32},
+{42, 139, 51},
+{93, 139, 32},
+{126, 139, 31},
+{158, 139, 25},
+};
+
+#define PROPB_GAP_WIDTH 4
+#define PROPB_SPACE_WIDTH 12
+#define PROPB_HEIGHT 36
+
+/*
+=================
+UI_DrawBannerString
+=================
+*/
+static void UI_DrawBannerString2( int x, int y, const char* str, vec4_t color )
+{
+ const char* s;
+ unsigned char ch; // bk001204 : array subscript
+ float ax;
+ float ay;
+ float aw;
+ float ah;
+ float frow;
+ float fcol;
+ float fwidth;
+ float fheight;
+
+ // draw the colored text
+ trap_R_SetColor( color );
+
+ ax = x * cgs.screenXScale + cgs.screenXBias;
+ ay = y * cgs.screenXScale;
+
+ s = str;
+ while ( *s )
+ {
+ ch = *s & 127;
+ if ( ch == ' ' ) {
+ ax += ((float)PROPB_SPACE_WIDTH + (float)PROPB_GAP_WIDTH)* cgs.screenXScale;
+ }
+ else if ( ch >= 'A' && ch <= 'Z' ) {
+ ch -= 'A';
+ fcol = (float)propMapB[ch][0] / 256.0f;
+ frow = (float)propMapB[ch][1] / 256.0f;
+ fwidth = (float)propMapB[ch][2] / 256.0f;
+ fheight = (float)PROPB_HEIGHT / 256.0f;
+ aw = (float)propMapB[ch][2] * cgs.screenXScale;
+ ah = (float)PROPB_HEIGHT * cgs.screenXScale;
+ trap_R_DrawStretchPic( ax, ay, aw, ah, fcol, frow, fcol+fwidth, frow+fheight, cgs.media.charsetPropB );
+ ax += (aw + (float)PROPB_GAP_WIDTH * cgs.screenXScale);
+ }
+ s++;
+ }
+
+ trap_R_SetColor( NULL );
+}
+
+void UI_DrawBannerString( int x, int y, const char* str, int style, vec4_t color ) {
+ const char * s;
+ int ch;
+ int width;
+ vec4_t drawcolor;
+
+ // find the width of the drawn text
+ s = str;
+ width = 0;
+ while ( *s ) {
+ ch = *s;
+ if ( ch == ' ' ) {
+ width += PROPB_SPACE_WIDTH;
+ }
+ else if ( ch >= 'A' && ch <= 'Z' ) {
+ width += propMapB[ch - 'A'][2] + PROPB_GAP_WIDTH;
+ }
+ s++;
+ }
+ width -= PROPB_GAP_WIDTH;
+
+ switch( style & UI_FORMATMASK ) {
+ case UI_CENTER:
+ x -= width / 2;
+ break;
+
+ case UI_RIGHT:
+ x -= width;
+ break;
+
+ case UI_LEFT:
+ default:
+ break;
+ }
+
+ if ( style & UI_DROPSHADOW ) {
+ drawcolor[0] = drawcolor[1] = drawcolor[2] = 0;
+ drawcolor[3] = color[3];
+ UI_DrawBannerString2( x+2, y+2, str, drawcolor );
+ }
+
+ UI_DrawBannerString2( x, y, str, color );
+}
+
+
+int UI_ProportionalStringWidth( const char* str ) {
+ const char * s;
+ int ch;
+ int charWidth;
+ int width;
+
+ s = str;
+ width = 0;
+ while ( *s ) {
+ ch = *s & 127;
+ charWidth = propMap[ch][2];
+ if ( charWidth != -1 ) {
+ width += charWidth;
+ width += PROP_GAP_WIDTH;
+ }
+ s++;
+ }
+
+ width -= PROP_GAP_WIDTH;
+ return width;
+}
+
+static void UI_DrawProportionalString2( int x, int y, const char* str, vec4_t color, float sizeScale, qhandle_t charset )
+{
+ const char* s;
+ unsigned char ch; // bk001204 - unsigned
+ float ax;
+ float ay;
+ float aw;
+ float ah;
+ float frow;
+ float fcol;
+ float fwidth;
+ float fheight;
+
+ // draw the colored text
+ trap_R_SetColor( color );
+
+ ax = x * cgs.screenXScale + cgs.screenXBias;
+ ay = y * cgs.screenXScale;
+
+ s = str;
+ while ( *s )
+ {
+ ch = *s & 127;
+ if ( ch == ' ' ) {
+ aw = (float)PROP_SPACE_WIDTH * cgs.screenXScale * sizeScale;
+ } else if ( propMap[ch][2] != -1 ) {
+ fcol = (float)propMap[ch][0] / 256.0f;
+ frow = (float)propMap[ch][1] / 256.0f;
+ fwidth = (float)propMap[ch][2] / 256.0f;
+ fheight = (float)PROP_HEIGHT / 256.0f;
+ aw = (float)propMap[ch][2] * cgs.screenXScale * sizeScale;
+ ah = (float)PROP_HEIGHT * cgs.screenXScale * sizeScale;
+ trap_R_DrawStretchPic( ax, ay, aw, ah, fcol, frow, fcol+fwidth, frow+fheight, charset );
+ } else {
+ aw = 0;
+ }
+
+ ax += (aw + (float)PROP_GAP_WIDTH * cgs.screenXScale * sizeScale);
+ s++;
+ }
+
+ trap_R_SetColor( NULL );
+}
+
+/*
+=================
+UI_ProportionalSizeScale
+=================
+*/
+float UI_ProportionalSizeScale( int style ) {
+ if( style & UI_SMALLFONT ) {
+ return 0.75;
+ }
+
+ return 1.00;
+}
+
+
+/*
+=================
+UI_DrawProportionalString
+=================
+*/
+void UI_DrawProportionalString( int x, int y, const char* str, int style, vec4_t color ) {
+ vec4_t drawcolor;
+ int width;
+ float sizeScale;
+
+ sizeScale = UI_ProportionalSizeScale( style );
+
+ switch( style & UI_FORMATMASK ) {
+ case UI_CENTER:
+ width = UI_ProportionalStringWidth( str ) * sizeScale;
+ x -= width / 2;
+ break;
+
+ case UI_RIGHT:
+ width = UI_ProportionalStringWidth( str ) * sizeScale;
+ x -= width;
+ break;
+
+ case UI_LEFT:
+ default:
+ break;
+ }
+
+ if ( style & UI_DROPSHADOW ) {
+ drawcolor[0] = drawcolor[1] = drawcolor[2] = 0;
+ drawcolor[3] = color[3];
+ UI_DrawProportionalString2( x+2, y+2, str, drawcolor, sizeScale, cgs.media.charsetProp );
+ }
+
+ if ( style & UI_INVERSE ) {
+ drawcolor[0] = color[0] * 0.8;
+ drawcolor[1] = color[1] * 0.8;
+ drawcolor[2] = color[2] * 0.8;
+ drawcolor[3] = color[3];
+ UI_DrawProportionalString2( x, y, str, drawcolor, sizeScale, cgs.media.charsetProp );
+ return;
+ }
+
+ if ( style & UI_PULSE ) {
+ drawcolor[0] = color[0] * 0.8;
+ drawcolor[1] = color[1] * 0.8;
+ drawcolor[2] = color[2] * 0.8;
+ drawcolor[3] = color[3];
+ UI_DrawProportionalString2( x, y, str, color, sizeScale, cgs.media.charsetProp );
+
+ drawcolor[0] = color[0];
+ drawcolor[1] = color[1];
+ drawcolor[2] = color[2];
+ drawcolor[3] = 0.5 + 0.5 * sin( cg.time / PULSE_DIVISOR );
+ UI_DrawProportionalString2( x, y, str, drawcolor, sizeScale, cgs.media.charsetPropGlow );
+ return;
+ }
+
+ UI_DrawProportionalString2( x, y, str, color, sizeScale, cgs.media.charsetProp );
+}
+#endif // Q3STATIC
diff --git a/code/cgame/cg_effects.c b/code/cgame/cg_effects.c
new file mode 100755
index 0000000..1ea447d
--- /dev/null
+++ b/code/cgame/cg_effects.c
@@ -0,0 +1,718 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// cg_effects.c -- these functions generate localentities, usually as a result
+// of event processing
+
+#include "cg_local.h"
+
+
+/*
+==================
+CG_BubbleTrail
+
+Bullets shot underwater
+==================
+*/
+void CG_BubbleTrail( vec3_t start, vec3_t end, float spacing ) {
+ vec3_t move;
+ vec3_t vec;
+ float len;
+ int i;
+
+ if ( cg_noProjectileTrail.integer ) {
+ return;
+ }
+
+ VectorCopy (start, move);
+ VectorSubtract (end, start, vec);
+ len = VectorNormalize (vec);
+
+ // advance a random amount first
+ i = rand() % (int)spacing;
+ VectorMA( move, i, vec, move );
+
+ VectorScale (vec, spacing, vec);
+
+ for ( ; i < len; i += spacing ) {
+ localEntity_t *le;
+ refEntity_t *re;
+
+ le = CG_AllocLocalEntity();
+ le->leFlags = LEF_PUFF_DONT_SCALE;
+ le->leType = LE_MOVE_SCALE_FADE;
+ le->startTime = cg.time;
+ le->endTime = cg.time + 1000 + random() * 250;
+ le->lifeRate = 1.0 / ( le->endTime - le->startTime );
+
+ re = &le->refEntity;
+ re->shaderTime = cg.time / 1000.0f;
+
+ re->reType = RT_SPRITE;
+ re->rotation = 0;
+ re->radius = 3;
+ re->customShader = cgs.media.waterBubbleShader;
+ re->shaderRGBA[0] = 0xff;
+ re->shaderRGBA[1] = 0xff;
+ re->shaderRGBA[2] = 0xff;
+ re->shaderRGBA[3] = 0xff;
+
+ le->color[3] = 1.0;
+
+ le->pos.trType = TR_LINEAR;
+ le->pos.trTime = cg.time;
+ VectorCopy( move, le->pos.trBase );
+ le->pos.trDelta[0] = crandom()*5;
+ le->pos.trDelta[1] = crandom()*5;
+ le->pos.trDelta[2] = crandom()*5 + 6;
+
+ VectorAdd (move, vec, move);
+ }
+}
+
+/*
+=====================
+CG_SmokePuff
+
+Adds a smoke puff or blood trail localEntity.
+=====================
+*/
+localEntity_t *CG_SmokePuff( const vec3_t p, const vec3_t vel,
+ float radius,
+ float r, float g, float b, float a,
+ float duration,
+ int startTime,
+ int fadeInTime,
+ int leFlags,
+ qhandle_t hShader ) {
+ static int seed = 0x92;
+ localEntity_t *le;
+ refEntity_t *re;
+// int fadeInTime = startTime + duration / 2;
+
+ le = CG_AllocLocalEntity();
+ le->leFlags = leFlags;
+ le->radius = radius;
+
+ re = &le->refEntity;
+ re->rotation = Q_random( &seed ) * 360;
+ re->radius = radius;
+ re->shaderTime = startTime / 1000.0f;
+
+ le->leType = LE_MOVE_SCALE_FADE;
+ le->startTime = startTime;
+ le->fadeInTime = fadeInTime;
+ le->endTime = startTime + duration;
+ if ( fadeInTime > startTime ) {
+ le->lifeRate = 1.0 / ( le->endTime - le->fadeInTime );
+ }
+ else {
+ le->lifeRate = 1.0 / ( le->endTime - le->startTime );
+ }
+ le->color[0] = r;
+ le->color[1] = g;
+ le->color[2] = b;
+ le->color[3] = a;
+
+
+ le->pos.trType = TR_LINEAR;
+ le->pos.trTime = startTime;
+ VectorCopy( vel, le->pos.trDelta );
+ VectorCopy( p, le->pos.trBase );
+
+ VectorCopy( p, re->origin );
+ re->customShader = hShader;
+
+ // rage pro can't alpha fade, so use a different shader
+ if ( cgs.glconfig.hardwareType == GLHW_RAGEPRO ) {
+ re->customShader = cgs.media.smokePuffRageProShader;
+ re->shaderRGBA[0] = 0xff;
+ re->shaderRGBA[1] = 0xff;
+ re->shaderRGBA[2] = 0xff;
+ re->shaderRGBA[3] = 0xff;
+ } else {
+ re->shaderRGBA[0] = le->color[0] * 0xff;
+ re->shaderRGBA[1] = le->color[1] * 0xff;
+ re->shaderRGBA[2] = le->color[2] * 0xff;
+ re->shaderRGBA[3] = 0xff;
+ }
+
+ re->reType = RT_SPRITE;
+ re->radius = le->radius;
+
+ return le;
+}
+
+/*
+==================
+CG_SpawnEffect
+
+Player teleporting in or out
+==================
+*/
+void CG_SpawnEffect( vec3_t org ) {
+ localEntity_t *le;
+ refEntity_t *re;
+
+ le = CG_AllocLocalEntity();
+ le->leFlags = 0;
+ le->leType = LE_FADE_RGB;
+ le->startTime = cg.time;
+ le->endTime = cg.time + 500;
+ le->lifeRate = 1.0 / ( le->endTime - le->startTime );
+
+ le->color[0] = le->color[1] = le->color[2] = le->color[3] = 1.0;
+
+ re = &le->refEntity;
+
+ re->reType = RT_MODEL;
+ re->shaderTime = cg.time / 1000.0f;
+
+#ifndef MISSIONPACK
+ re->customShader = cgs.media.teleportEffectShader;
+#endif
+ re->hModel = cgs.media.teleportEffectModel;
+ AxisClear( re->axis );
+
+ VectorCopy( org, re->origin );
+#ifdef MISSIONPACK
+ re->origin[2] += 16;
+#else
+ re->origin[2] -= 24;
+#endif
+}
+
+
+#ifdef MISSIONPACK
+/*
+===============
+CG_LightningBoltBeam
+===============
+*/
+void CG_LightningBoltBeam( vec3_t start, vec3_t end ) {
+ localEntity_t *le;
+ refEntity_t *beam;
+
+ le = CG_AllocLocalEntity();
+ le->leFlags = 0;
+ le->leType = LE_SHOWREFENTITY;
+ le->startTime = cg.time;
+ le->endTime = cg.time + 50;
+
+ beam = &le->refEntity;
+
+ VectorCopy( start, beam->origin );
+ // this is the end point
+ VectorCopy( end, beam->oldorigin );
+
+ beam->reType = RT_LIGHTNING;
+ beam->customShader = cgs.media.lightningShader;
+}
+
+/*
+==================
+CG_KamikazeEffect
+==================
+*/
+void CG_KamikazeEffect( vec3_t org ) {
+ localEntity_t *le;
+ refEntity_t *re;
+
+ le = CG_AllocLocalEntity();
+ le->leFlags = 0;
+ le->leType = LE_KAMIKAZE;
+ le->startTime = cg.time;
+ le->endTime = cg.time + 3000;//2250;
+ le->lifeRate = 1.0 / ( le->endTime - le->startTime );
+
+ le->color[0] = le->color[1] = le->color[2] = le->color[3] = 1.0;
+
+ VectorClear(le->angles.trBase);
+
+ re = &le->refEntity;
+
+ re->reType = RT_MODEL;
+ re->shaderTime = cg.time / 1000.0f;
+
+ re->hModel = cgs.media.kamikazeEffectModel;
+
+ VectorCopy( org, re->origin );
+
+}
+
+/*
+==================
+CG_ObeliskExplode
+==================
+*/
+void CG_ObeliskExplode( vec3_t org, int entityNum ) {
+ localEntity_t *le;
+ vec3_t origin;
+
+ // create an explosion
+ VectorCopy( org, origin );
+ origin[2] += 64;
+ le = CG_MakeExplosion( origin, vec3_origin,
+ cgs.media.dishFlashModel,
+ cgs.media.rocketExplosionShader,
+ 600, qtrue );
+ le->light = 300;
+ le->lightColor[0] = 1;
+ le->lightColor[1] = 0.75;
+ le->lightColor[2] = 0.0;
+}
+
+/*
+==================
+CG_ObeliskPain
+==================
+*/
+void CG_ObeliskPain( vec3_t org ) {
+ float r;
+ sfxHandle_t sfx;
+
+ // hit sound
+ r = rand() & 3;
+ if ( r < 2 ) {
+ sfx = cgs.media.obeliskHitSound1;
+ } else if ( r == 2 ) {
+ sfx = cgs.media.obeliskHitSound2;
+ } else {
+ sfx = cgs.media.obeliskHitSound3;
+ }
+ trap_S_StartSound ( org, ENTITYNUM_NONE, CHAN_BODY, sfx );
+}
+
+
+/*
+==================
+CG_InvulnerabilityImpact
+==================
+*/
+void CG_InvulnerabilityImpact( vec3_t org, vec3_t angles ) {
+ localEntity_t *le;
+ refEntity_t *re;
+ int r;
+ sfxHandle_t sfx;
+
+ le = CG_AllocLocalEntity();
+ le->leFlags = 0;
+ le->leType = LE_INVULIMPACT;
+ le->startTime = cg.time;
+ le->endTime = cg.time + 1000;
+ le->lifeRate = 1.0 / ( le->endTime - le->startTime );
+
+ le->color[0] = le->color[1] = le->color[2] = le->color[3] = 1.0;
+
+ re = &le->refEntity;
+
+ re->reType = RT_MODEL;
+ re->shaderTime = cg.time / 1000.0f;
+
+ re->hModel = cgs.media.invulnerabilityImpactModel;
+
+ VectorCopy( org, re->origin );
+ AnglesToAxis( angles, re->axis );
+
+ r = rand() & 3;
+ if ( r < 2 ) {
+ sfx = cgs.media.invulnerabilityImpactSound1;
+ } else if ( r == 2 ) {
+ sfx = cgs.media.invulnerabilityImpactSound2;
+ } else {
+ sfx = cgs.media.invulnerabilityImpactSound3;
+ }
+ trap_S_StartSound (org, ENTITYNUM_NONE, CHAN_BODY, sfx );
+}
+
+/*
+==================
+CG_InvulnerabilityJuiced
+==================
+*/
+void CG_InvulnerabilityJuiced( vec3_t org ) {
+ localEntity_t *le;
+ refEntity_t *re;
+ vec3_t angles;
+
+ le = CG_AllocLocalEntity();
+ le->leFlags = 0;
+ le->leType = LE_INVULJUICED;
+ le->startTime = cg.time;
+ le->endTime = cg.time + 10000;
+ le->lifeRate = 1.0 / ( le->endTime - le->startTime );
+
+ le->color[0] = le->color[1] = le->color[2] = le->color[3] = 1.0;
+
+ re = &le->refEntity;
+
+ re->reType = RT_MODEL;
+ re->shaderTime = cg.time / 1000.0f;
+
+ re->hModel = cgs.media.invulnerabilityJuicedModel;
+
+ VectorCopy( org, re->origin );
+ VectorClear(angles);
+ AnglesToAxis( angles, re->axis );
+
+ trap_S_StartSound (org, ENTITYNUM_NONE, CHAN_BODY, cgs.media.invulnerabilityJuicedSound );
+}
+
+#endif
+
+/*
+==================
+CG_ScorePlum
+==================
+*/
+void CG_ScorePlum( int client, vec3_t org, int score ) {
+ localEntity_t *le;
+ refEntity_t *re;
+ vec3_t angles;
+ static vec3_t lastPos;
+
+ // only visualize for the client that scored
+ if (client != cg.predictedPlayerState.clientNum || cg_scorePlum.integer == 0) {
+ return;
+ }
+
+ le = CG_AllocLocalEntity();
+ le->leFlags = 0;
+ le->leType = LE_SCOREPLUM;
+ le->startTime = cg.time;
+ le->endTime = cg.time + 4000;
+ le->lifeRate = 1.0 / ( le->endTime - le->startTime );
+
+
+ le->color[0] = le->color[1] = le->color[2] = le->color[3] = 1.0;
+ le->radius = score;
+
+ VectorCopy( org, le->pos.trBase );
+ if (org[2] >= lastPos[2] - 20 && org[2] <= lastPos[2] + 20) {
+ le->pos.trBase[2] -= 20;
+ }
+
+ //CG_Printf( "Plum origin %i %i %i -- %i\n", (int)org[0], (int)org[1], (int)org[2], (int)Distance(org, lastPos));
+ VectorCopy(org, lastPos);
+
+
+ re = &le->refEntity;
+
+ re->reType = RT_SPRITE;
+ re->radius = 16;
+
+ VectorClear(angles);
+ AnglesToAxis( angles, re->axis );
+}
+
+
+/*
+====================
+CG_MakeExplosion
+====================
+*/
+localEntity_t *CG_MakeExplosion( vec3_t origin, vec3_t dir,
+ qhandle_t hModel, qhandle_t shader,
+ int msec, qboolean isSprite ) {
+ float ang;
+ localEntity_t *ex;
+ int offset;
+ vec3_t tmpVec, newOrigin;
+
+ if ( msec <= 0 ) {
+ CG_Error( "CG_MakeExplosion: msec = %i", msec );
+ }
+
+ // skew the time a bit so they aren't all in sync
+ offset = rand() & 63;
+
+ ex = CG_AllocLocalEntity();
+ if ( isSprite ) {
+ ex->leType = LE_SPRITE_EXPLOSION;
+
+ // randomly rotate sprite orientation
+ ex->refEntity.rotation = rand() % 360;
+ VectorScale( dir, 16, tmpVec );
+ VectorAdd( tmpVec, origin, newOrigin );
+ } else {
+ ex->leType = LE_EXPLOSION;
+ VectorCopy( origin, newOrigin );
+
+ // set axis with random rotate
+ if ( !dir ) {
+ AxisClear( ex->refEntity.axis );
+ } else {
+ ang = rand() % 360;
+ VectorCopy( dir, ex->refEntity.axis[0] );
+ RotateAroundDirection( ex->refEntity.axis, ang );
+ }
+ }
+
+ ex->startTime = cg.time - offset;
+ ex->endTime = ex->startTime + msec;
+
+ // bias the time so all shader effects start correctly
+ ex->refEntity.shaderTime = ex->startTime / 1000.0f;
+
+ ex->refEntity.hModel = hModel;
+ ex->refEntity.customShader = shader;
+
+ // set origin
+ VectorCopy( newOrigin, ex->refEntity.origin );
+ VectorCopy( newOrigin, ex->refEntity.oldorigin );
+
+ ex->color[0] = ex->color[1] = ex->color[2] = 1.0;
+
+ return ex;
+}
+
+
+/*
+=================
+CG_Bleed
+
+This is the spurt of blood when a character gets hit
+=================
+*/
+void CG_Bleed( vec3_t origin, int entityNum ) {
+ localEntity_t *ex;
+
+ if ( !cg_blood.integer ) {
+ return;
+ }
+
+ ex = CG_AllocLocalEntity();
+ ex->leType = LE_EXPLOSION;
+
+ ex->startTime = cg.time;
+ ex->endTime = ex->startTime + 500;
+
+ VectorCopy ( origin, ex->refEntity.origin);
+ ex->refEntity.reType = RT_SPRITE;
+ ex->refEntity.rotation = rand() % 360;
+ ex->refEntity.radius = 24;
+
+ ex->refEntity.customShader = cgs.media.bloodExplosionShader;
+
+ // don't show player's own blood in view
+ if ( entityNum == cg.snap->ps.clientNum ) {
+ ex->refEntity.renderfx |= RF_THIRD_PERSON;
+ }
+}
+
+
+
+/*
+==================
+CG_LaunchGib
+==================
+*/
+void CG_LaunchGib( vec3_t origin, vec3_t velocity, qhandle_t hModel ) {
+ localEntity_t *le;
+ refEntity_t *re;
+
+ le = CG_AllocLocalEntity();
+ re = &le->refEntity;
+
+ le->leType = LE_FRAGMENT;
+ le->startTime = cg.time;
+ le->endTime = le->startTime + 5000 + random() * 3000;
+
+ VectorCopy( origin, re->origin );
+ AxisCopy( axisDefault, re->axis );
+ re->hModel = hModel;
+
+ le->pos.trType = TR_GRAVITY;
+ VectorCopy( origin, le->pos.trBase );
+ VectorCopy( velocity, le->pos.trDelta );
+ le->pos.trTime = cg.time;
+
+ le->bounceFactor = 0.6f;
+
+ le->leBounceSoundType = LEBS_BLOOD;
+ le->leMarkType = LEMT_BLOOD;
+}
+
+/*
+===================
+CG_GibPlayer
+
+Generated a bunch of gibs launching out from the bodies location
+===================
+*/
+#define GIB_VELOCITY 250
+#define GIB_JUMP 250
+void CG_GibPlayer( vec3_t playerOrigin ) {
+ vec3_t origin, velocity;
+
+ if ( !cg_blood.integer ) {
+ return;
+ }
+
+ VectorCopy( playerOrigin, origin );
+ velocity[0] = crandom()*GIB_VELOCITY;
+ velocity[1] = crandom()*GIB_VELOCITY;
+ velocity[2] = GIB_JUMP + crandom()*GIB_VELOCITY;
+ if ( rand() & 1 ) {
+ CG_LaunchGib( origin, velocity, cgs.media.gibSkull );
+ } else {
+ CG_LaunchGib( origin, velocity, cgs.media.gibBrain );
+ }
+
+ // allow gibs to be turned off for speed
+ if ( !cg_gibs.integer ) {
+ return;
+ }
+
+ VectorCopy( playerOrigin, origin );
+ velocity[0] = crandom()*GIB_VELOCITY;
+ velocity[1] = crandom()*GIB_VELOCITY;
+ velocity[2] = GIB_JUMP + crandom()*GIB_VELOCITY;
+ CG_LaunchGib( origin, velocity, cgs.media.gibAbdomen );
+
+ VectorCopy( playerOrigin, origin );
+ velocity[0] = crandom()*GIB_VELOCITY;
+ velocity[1] = crandom()*GIB_VELOCITY;
+ velocity[2] = GIB_JUMP + crandom()*GIB_VELOCITY;
+ CG_LaunchGib( origin, velocity, cgs.media.gibArm );
+
+ VectorCopy( playerOrigin, origin );
+ velocity[0] = crandom()*GIB_VELOCITY;
+ velocity[1] = crandom()*GIB_VELOCITY;
+ velocity[2] = GIB_JUMP + crandom()*GIB_VELOCITY;
+ CG_LaunchGib( origin, velocity, cgs.media.gibChest );
+
+ VectorCopy( playerOrigin, origin );
+ velocity[0] = crandom()*GIB_VELOCITY;
+ velocity[1] = crandom()*GIB_VELOCITY;
+ velocity[2] = GIB_JUMP + crandom()*GIB_VELOCITY;
+ CG_LaunchGib( origin, velocity, cgs.media.gibFist );
+
+ VectorCopy( playerOrigin, origin );
+ velocity[0] = crandom()*GIB_VELOCITY;
+ velocity[1] = crandom()*GIB_VELOCITY;
+ velocity[2] = GIB_JUMP + crandom()*GIB_VELOCITY;
+ CG_LaunchGib( origin, velocity, cgs.media.gibFoot );
+
+ VectorCopy( playerOrigin, origin );
+ velocity[0] = crandom()*GIB_VELOCITY;
+ velocity[1] = crandom()*GIB_VELOCITY;
+ velocity[2] = GIB_JUMP + crandom()*GIB_VELOCITY;
+ CG_LaunchGib( origin, velocity, cgs.media.gibForearm );
+
+ VectorCopy( playerOrigin, origin );
+ velocity[0] = crandom()*GIB_VELOCITY;
+ velocity[1] = crandom()*GIB_VELOCITY;
+ velocity[2] = GIB_JUMP + crandom()*GIB_VELOCITY;
+ CG_LaunchGib( origin, velocity, cgs.media.gibIntestine );
+
+ VectorCopy( playerOrigin, origin );
+ velocity[0] = crandom()*GIB_VELOCITY;
+ velocity[1] = crandom()*GIB_VELOCITY;
+ velocity[2] = GIB_JUMP + crandom()*GIB_VELOCITY;
+ CG_LaunchGib( origin, velocity, cgs.media.gibLeg );
+
+ VectorCopy( playerOrigin, origin );
+ velocity[0] = crandom()*GIB_VELOCITY;
+ velocity[1] = crandom()*GIB_VELOCITY;
+ velocity[2] = GIB_JUMP + crandom()*GIB_VELOCITY;
+ CG_LaunchGib( origin, velocity, cgs.media.gibLeg );
+}
+
+/*
+==================
+CG_LaunchGib
+==================
+*/
+void CG_LaunchExplode( vec3_t origin, vec3_t velocity, qhandle_t hModel ) {
+ localEntity_t *le;
+ refEntity_t *re;
+
+ le = CG_AllocLocalEntity();
+ re = &le->refEntity;
+
+ le->leType = LE_FRAGMENT;
+ le->startTime = cg.time;
+ le->endTime = le->startTime + 10000 + random() * 6000;
+
+ VectorCopy( origin, re->origin );
+ AxisCopy( axisDefault, re->axis );
+ re->hModel = hModel;
+
+ le->pos.trType = TR_GRAVITY;
+ VectorCopy( origin, le->pos.trBase );
+ VectorCopy( velocity, le->pos.trDelta );
+ le->pos.trTime = cg.time;
+
+ le->bounceFactor = 0.1f;
+
+ le->leBounceSoundType = LEBS_BRASS;
+ le->leMarkType = LEMT_NONE;
+}
+
+#define EXP_VELOCITY 100
+#define EXP_JUMP 150
+/*
+===================
+CG_GibPlayer
+
+Generated a bunch of gibs launching out from the bodies location
+===================
+*/
+void CG_BigExplode( vec3_t playerOrigin ) {
+ vec3_t origin, velocity;
+
+ if ( !cg_blood.integer ) {
+ return;
+ }
+
+ VectorCopy( playerOrigin, origin );
+ velocity[0] = crandom()*EXP_VELOCITY;
+ velocity[1] = crandom()*EXP_VELOCITY;
+ velocity[2] = EXP_JUMP + crandom()*EXP_VELOCITY;
+ CG_LaunchExplode( origin, velocity, cgs.media.smoke2 );
+
+ VectorCopy( playerOrigin, origin );
+ velocity[0] = crandom()*EXP_VELOCITY;
+ velocity[1] = crandom()*EXP_VELOCITY;
+ velocity[2] = EXP_JUMP + crandom()*EXP_VELOCITY;
+ CG_LaunchExplode( origin, velocity, cgs.media.smoke2 );
+
+ VectorCopy( playerOrigin, origin );
+ velocity[0] = crandom()*EXP_VELOCITY*1.5;
+ velocity[1] = crandom()*EXP_VELOCITY*1.5;
+ velocity[2] = EXP_JUMP + crandom()*EXP_VELOCITY;
+ CG_LaunchExplode( origin, velocity, cgs.media.smoke2 );
+
+ VectorCopy( playerOrigin, origin );
+ velocity[0] = crandom()*EXP_VELOCITY*2.0;
+ velocity[1] = crandom()*EXP_VELOCITY*2.0;
+ velocity[2] = EXP_JUMP + crandom()*EXP_VELOCITY;
+ CG_LaunchExplode( origin, velocity, cgs.media.smoke2 );
+
+ VectorCopy( playerOrigin, origin );
+ velocity[0] = crandom()*EXP_VELOCITY*2.5;
+ velocity[1] = crandom()*EXP_VELOCITY*2.5;
+ velocity[2] = EXP_JUMP + crandom()*EXP_VELOCITY;
+ CG_LaunchExplode( origin, velocity, cgs.media.smoke2 );
+}
+
diff --git a/code/cgame/cg_ents.c b/code/cgame/cg_ents.c
new file mode 100755
index 0000000..5855089
--- /dev/null
+++ b/code/cgame/cg_ents.c
@@ -0,0 +1,1037 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// cg_ents.c -- present snapshot entities, happens every single frame
+
+#include "cg_local.h"
+
+
+/*
+======================
+CG_PositionEntityOnTag
+
+Modifies the entities position and axis by the given
+tag location
+======================
+*/
+void CG_PositionEntityOnTag( refEntity_t *entity, const refEntity_t *parent,
+ qhandle_t parentModel, char *tagName ) {
+ int i;
+ orientation_t lerped;
+
+ // lerp the tag
+ trap_R_LerpTag( &lerped, parentModel, parent->oldframe, parent->frame,
+ 1.0 - parent->backlerp, tagName );
+
+ // FIXME: allow origin offsets along tag?
+ VectorCopy( parent->origin, entity->origin );
+ for ( i = 0 ; i < 3 ; i++ ) {
+ VectorMA( entity->origin, lerped.origin[i], parent->axis[i], entity->origin );
+ }
+
+ // had to cast away the const to avoid compiler problems...
+ MatrixMultiply( lerped.axis, ((refEntity_t *)parent)->axis, entity->axis );
+ entity->backlerp = parent->backlerp;
+}
+
+
+/*
+======================
+CG_PositionRotatedEntityOnTag
+
+Modifies the entities position and axis by the given
+tag location
+======================
+*/
+void CG_PositionRotatedEntityOnTag( refEntity_t *entity, const refEntity_t *parent,
+ qhandle_t parentModel, char *tagName ) {
+ int i;
+ orientation_t lerped;
+ vec3_t tempAxis[3];
+
+//AxisClear( entity->axis );
+ // lerp the tag
+ trap_R_LerpTag( &lerped, parentModel, parent->oldframe, parent->frame,
+ 1.0 - parent->backlerp, tagName );
+
+ // FIXME: allow origin offsets along tag?
+ VectorCopy( parent->origin, entity->origin );
+ for ( i = 0 ; i < 3 ; i++ ) {
+ VectorMA( entity->origin, lerped.origin[i], parent->axis[i], entity->origin );
+ }
+
+ // had to cast away the const to avoid compiler problems...
+ MatrixMultiply( entity->axis, lerped.axis, tempAxis );
+ MatrixMultiply( tempAxis, ((refEntity_t *)parent)->axis, entity->axis );
+}
+
+
+
+/*
+==========================================================================
+
+FUNCTIONS CALLED EACH FRAME
+
+==========================================================================
+*/
+
+/*
+======================
+CG_SetEntitySoundPosition
+
+Also called by event processing code
+======================
+*/
+void CG_SetEntitySoundPosition( centity_t *cent ) {
+ if ( cent->currentState.solid == SOLID_BMODEL ) {
+ vec3_t origin;
+ float *v;
+
+ v = cgs.inlineModelMidpoints[ cent->currentState.modelindex ];
+ VectorAdd( cent->lerpOrigin, v, origin );
+ trap_S_UpdateEntityPosition( cent->currentState.number, origin );
+ } else {
+ trap_S_UpdateEntityPosition( cent->currentState.number, cent->lerpOrigin );
+ }
+}
+
+/*
+==================
+CG_EntityEffects
+
+Add continuous entity effects, like local entity emission and lighting
+==================
+*/
+static void CG_EntityEffects( centity_t *cent ) {
+
+ // update sound origins
+ CG_SetEntitySoundPosition( cent );
+
+ // add loop sound
+ if ( cent->currentState.loopSound ) {
+ if (cent->currentState.eType != ET_SPEAKER) {
+ trap_S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin,
+ cgs.gameSounds[ cent->currentState.loopSound ] );
+ } else {
+ trap_S_AddRealLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin,
+ cgs.gameSounds[ cent->currentState.loopSound ] );
+ }
+ }
+
+
+ // constant light glow
+ if ( cent->currentState.constantLight ) {
+ int cl;
+ int i, r, g, b;
+
+ cl = cent->currentState.constantLight;
+ r = cl & 255;
+ g = ( cl >> 8 ) & 255;
+ b = ( cl >> 16 ) & 255;
+ i = ( ( cl >> 24 ) & 255 ) * 4;
+ trap_R_AddLightToScene( cent->lerpOrigin, i, r, g, b );
+ }
+
+}
+
+
+/*
+==================
+CG_General
+==================
+*/
+static void CG_General( centity_t *cent ) {
+ refEntity_t ent;
+ entityState_t *s1;
+
+ s1 = &cent->currentState;
+
+ // if set to invisible, skip
+ if (!s1->modelindex) {
+ return;
+ }
+
+ memset (&ent, 0, sizeof(ent));
+
+ // set frame
+
+ ent.frame = s1->frame;
+ ent.oldframe = ent.frame;
+ ent.backlerp = 0;
+
+ VectorCopy( cent->lerpOrigin, ent.origin);
+ VectorCopy( cent->lerpOrigin, ent.oldorigin);
+
+ ent.hModel = cgs.gameModels[s1->modelindex];
+
+ // player model
+ if (s1->number == cg.snap->ps.clientNum) {
+ ent.renderfx |= RF_THIRD_PERSON; // only draw from mirrors
+ }
+
+ // convert angles to axis
+ AnglesToAxis( cent->lerpAngles, ent.axis );
+
+ // add to refresh list
+ trap_R_AddRefEntityToScene (&ent);
+}
+
+/*
+==================
+CG_Speaker
+
+Speaker entities can automatically play sounds
+==================
+*/
+static void CG_Speaker( centity_t *cent ) {
+ if ( ! cent->currentState.clientNum ) { // FIXME: use something other than clientNum...
+ return; // not auto triggering
+ }
+
+ if ( cg.time < cent->miscTime ) {
+ return;
+ }
+
+ trap_S_StartSound (NULL, cent->currentState.number, CHAN_ITEM, cgs.gameSounds[cent->currentState.eventParm] );
+
+ // ent->s.frame = ent->wait * 10;
+ // ent->s.clientNum = ent->random * 10;
+ cent->miscTime = cg.time + cent->currentState.frame * 100 + cent->currentState.clientNum * 100 * crandom();
+}
+
+/*
+==================
+CG_Item
+==================
+*/
+static void CG_Item( centity_t *cent ) {
+ refEntity_t ent;
+ entityState_t *es;
+ gitem_t *item;
+ int msec;
+ float frac;
+ float scale;
+ weaponInfo_t *wi;
+
+ es = &cent->currentState;
+ if ( es->modelindex >= bg_numItems ) {
+ CG_Error( "Bad item index %i on entity", es->modelindex );
+ }
+
+ // if set to invisible, skip
+ if ( !es->modelindex || ( es->eFlags & EF_NODRAW ) ) {
+ return;
+ }
+
+ item = &bg_itemlist[ es->modelindex ];
+ if ( cg_simpleItems.integer && item->giType != IT_TEAM ) {
+ memset( &ent, 0, sizeof( ent ) );
+ ent.reType = RT_SPRITE;
+ VectorCopy( cent->lerpOrigin, ent.origin );
+ ent.radius = 14;
+ ent.customShader = cg_items[es->modelindex].icon;
+ ent.shaderRGBA[0] = 255;
+ ent.shaderRGBA[1] = 255;
+ ent.shaderRGBA[2] = 255;
+ ent.shaderRGBA[3] = 255;
+ trap_R_AddRefEntityToScene(&ent);
+ return;
+ }
+
+ // items bob up and down continuously
+ scale = 0.005 + cent->currentState.number * 0.00001;
+ cent->lerpOrigin[2] += 4 + cos( ( cg.time + 1000 ) * scale ) * 4;
+
+ memset (&ent, 0, sizeof(ent));
+
+ // autorotate at one of two speeds
+ if ( item->giType == IT_HEALTH ) {
+ VectorCopy( cg.autoAnglesFast, cent->lerpAngles );
+ AxisCopy( cg.autoAxisFast, ent.axis );
+ } else {
+ VectorCopy( cg.autoAngles, cent->lerpAngles );
+ AxisCopy( cg.autoAxis, ent.axis );
+ }
+
+ wi = NULL;
+ // the weapons have their origin where they attatch to player
+ // models, so we need to offset them or they will rotate
+ // eccentricly
+ if ( item->giType == IT_WEAPON ) {
+ wi = &cg_weapons[item->giTag];
+ cent->lerpOrigin[0] -=
+ wi->weaponMidpoint[0] * ent.axis[0][0] +
+ wi->weaponMidpoint[1] * ent.axis[1][0] +
+ wi->weaponMidpoint[2] * ent.axis[2][0];
+ cent->lerpOrigin[1] -=
+ wi->weaponMidpoint[0] * ent.axis[0][1] +
+ wi->weaponMidpoint[1] * ent.axis[1][1] +
+ wi->weaponMidpoint[2] * ent.axis[2][1];
+ cent->lerpOrigin[2] -=
+ wi->weaponMidpoint[0] * ent.axis[0][2] +
+ wi->weaponMidpoint[1] * ent.axis[1][2] +
+ wi->weaponMidpoint[2] * ent.axis[2][2];
+
+ cent->lerpOrigin[2] += 8; // an extra height boost
+ }
+
+ ent.hModel = cg_items[es->modelindex].models[0];
+
+ VectorCopy( cent->lerpOrigin, ent.origin);
+ VectorCopy( cent->lerpOrigin, ent.oldorigin);
+
+ ent.nonNormalizedAxes = qfalse;
+
+ // if just respawned, slowly scale up
+ msec = cg.time - cent->miscTime;
+ if ( msec >= 0 && msec < ITEM_SCALEUP_TIME ) {
+ frac = (float)msec / ITEM_SCALEUP_TIME;
+ VectorScale( ent.axis[0], frac, ent.axis[0] );
+ VectorScale( ent.axis[1], frac, ent.axis[1] );
+ VectorScale( ent.axis[2], frac, ent.axis[2] );
+ ent.nonNormalizedAxes = qtrue;
+ } else {
+ frac = 1.0;
+ }
+
+ // items without glow textures need to keep a minimum light value
+ // so they are always visible
+ if ( ( item->giType == IT_WEAPON ) ||
+ ( item->giType == IT_ARMOR ) ) {
+ ent.renderfx |= RF_MINLIGHT;
+ }
+
+ // increase the size of the weapons when they are presented as items
+ if ( item->giType == IT_WEAPON ) {
+ VectorScale( ent.axis[0], 1.5, ent.axis[0] );
+ VectorScale( ent.axis[1], 1.5, ent.axis[1] );
+ VectorScale( ent.axis[2], 1.5, ent.axis[2] );
+ ent.nonNormalizedAxes = qtrue;
+#ifdef MISSIONPACK
+ trap_S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin, cgs.media.weaponHoverSound );
+#endif
+ }
+
+#ifdef MISSIONPACK
+ if ( item->giType == IT_HOLDABLE && item->giTag == HI_KAMIKAZE ) {
+ VectorScale( ent.axis[0], 2, ent.axis[0] );
+ VectorScale( ent.axis[1], 2, ent.axis[1] );
+ VectorScale( ent.axis[2], 2, ent.axis[2] );
+ ent.nonNormalizedAxes = qtrue;
+ }
+#endif
+
+ // add to refresh list
+ trap_R_AddRefEntityToScene(&ent);
+
+#ifdef MISSIONPACK
+ if ( item->giType == IT_WEAPON && wi->barrelModel ) {
+ refEntity_t barrel;
+
+ memset( &barrel, 0, sizeof( barrel ) );
+
+ barrel.hModel = wi->barrelModel;
+
+ VectorCopy( ent.lightingOrigin, barrel.lightingOrigin );
+ barrel.shadowPlane = ent.shadowPlane;
+ barrel.renderfx = ent.renderfx;
+
+ CG_PositionRotatedEntityOnTag( &barrel, &ent, wi->weaponModel, "tag_barrel" );
+
+ AxisCopy( ent.axis, barrel.axis );
+ barrel.nonNormalizedAxes = ent.nonNormalizedAxes;
+
+ trap_R_AddRefEntityToScene( &barrel );
+ }
+#endif
+
+ // accompanying rings / spheres for powerups
+ if ( !cg_simpleItems.integer )
+ {
+ vec3_t spinAngles;
+
+ VectorClear( spinAngles );
+
+ if ( item->giType == IT_HEALTH || item->giType == IT_POWERUP )
+ {
+ if ( ( ent.hModel = cg_items[es->modelindex].models[1] ) != 0 )
+ {
+ if ( item->giType == IT_POWERUP )
+ {
+ ent.origin[2] += 12;
+ spinAngles[1] = ( cg.time & 1023 ) * 360 / -1024.0f;
+ }
+ AnglesToAxis( spinAngles, ent.axis );
+
+ // scale up if respawning
+ if ( frac != 1.0 ) {
+ VectorScale( ent.axis[0], frac, ent.axis[0] );
+ VectorScale( ent.axis[1], frac, ent.axis[1] );
+ VectorScale( ent.axis[2], frac, ent.axis[2] );
+ ent.nonNormalizedAxes = qtrue;
+ }
+ trap_R_AddRefEntityToScene( &ent );
+ }
+ }
+ }
+}
+
+//============================================================================
+
+/*
+===============
+CG_Missile
+===============
+*/
+static void CG_Missile( centity_t *cent ) {
+ refEntity_t ent;
+ entityState_t *s1;
+ const weaponInfo_t *weapon;
+// int col;
+
+ s1 = &cent->currentState;
+ if ( s1->weapon > WP_NUM_WEAPONS ) {
+ s1->weapon = 0;
+ }
+ weapon = &cg_weapons[s1->weapon];
+
+ // calculate the axis
+ VectorCopy( s1->angles, cent->lerpAngles);
+
+ // add trails
+ if ( weapon->missileTrailFunc )
+ {
+ weapon->missileTrailFunc( cent, weapon );
+ }
+/*
+ if ( cent->currentState.modelindex == TEAM_RED ) {
+ col = 1;
+ }
+ else if ( cent->currentState.modelindex == TEAM_BLUE ) {
+ col = 2;
+ }
+ else {
+ col = 0;
+ }
+
+ // add dynamic light
+ if ( weapon->missileDlight ) {
+ trap_R_AddLightToScene(cent->lerpOrigin, weapon->missileDlight,
+ weapon->missileDlightColor[col][0], weapon->missileDlightColor[col][1], weapon->missileDlightColor[col][2] );
+ }
+*/
+ // add dynamic light
+ if ( weapon->missileDlight ) {
+ trap_R_AddLightToScene(cent->lerpOrigin, weapon->missileDlight,
+ weapon->missileDlightColor[0], weapon->missileDlightColor[1], weapon->missileDlightColor[2] );
+ }
+
+ // add missile sound
+ if ( weapon->missileSound ) {
+ vec3_t velocity;
+
+ BG_EvaluateTrajectoryDelta( &cent->currentState.pos, cg.time, velocity );
+
+ trap_S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, velocity, weapon->missileSound );
+ }
+
+ // create the render entity
+ memset (&ent, 0, sizeof(ent));
+ VectorCopy( cent->lerpOrigin, ent.origin);
+ VectorCopy( cent->lerpOrigin, ent.oldorigin);
+
+ if ( cent->currentState.weapon == WP_PLASMAGUN ) {
+ ent.reType = RT_SPRITE;
+ ent.radius = 16;
+ ent.rotation = 0;
+ ent.customShader = cgs.media.plasmaBallShader;
+ trap_R_AddRefEntityToScene( &ent );
+ return;
+ }
+
+ // flicker between two skins
+ ent.skinNum = cg.clientFrame & 1;
+ ent.hModel = weapon->missileModel;
+ ent.renderfx = weapon->missileRenderfx | RF_NOSHADOW;
+
+#ifdef MISSIONPACK
+ if ( cent->currentState.weapon == WP_PROX_LAUNCHER ) {
+ if (s1->generic1 == TEAM_BLUE) {
+ ent.hModel = cgs.media.blueProxMine;
+ }
+ }
+#endif
+
+ // convert direction of travel into axis
+ if ( VectorNormalize2( s1->pos.trDelta, ent.axis[0] ) == 0 ) {
+ ent.axis[0][2] = 1;
+ }
+
+ // spin as it moves
+ if ( s1->pos.trType != TR_STATIONARY ) {
+ RotateAroundDirection( ent.axis, cg.time / 4 );
+ } else {
+#ifdef MISSIONPACK
+ if ( s1->weapon == WP_PROX_LAUNCHER ) {
+ AnglesToAxis( cent->lerpAngles, ent.axis );
+ }
+ else
+#endif
+ {
+ RotateAroundDirection( ent.axis, s1->time );
+ }
+ }
+
+ // add to refresh list, possibly with quad glow
+ CG_AddRefEntityWithPowerups( &ent, s1, TEAM_FREE );
+}
+
+/*
+===============
+CG_Grapple
+
+This is called when the grapple is sitting up against the wall
+===============
+*/
+static void CG_Grapple( centity_t *cent ) {
+ refEntity_t ent;
+ entityState_t *s1;
+ const weaponInfo_t *weapon;
+
+ s1 = &cent->currentState;
+ if ( s1->weapon > WP_NUM_WEAPONS ) {
+ s1->weapon = 0;
+ }
+ weapon = &cg_weapons[s1->weapon];
+
+ // calculate the axis
+ VectorCopy( s1->angles, cent->lerpAngles);
+
+#if 0 // FIXME add grapple pull sound here..?
+ // add missile sound
+ if ( weapon->missileSound ) {
+ trap_S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->missileSound );
+ }
+#endif
+
+ // Will draw cable if needed
+ CG_GrappleTrail ( cent, weapon );
+
+ // create the render entity
+ memset (&ent, 0, sizeof(ent));
+ VectorCopy( cent->lerpOrigin, ent.origin);
+ VectorCopy( cent->lerpOrigin, ent.oldorigin);
+
+ // flicker between two skins
+ ent.skinNum = cg.clientFrame & 1;
+ ent.hModel = weapon->missileModel;
+ ent.renderfx = weapon->missileRenderfx | RF_NOSHADOW;
+
+ // convert direction of travel into axis
+ if ( VectorNormalize2( s1->pos.trDelta, ent.axis[0] ) == 0 ) {
+ ent.axis[0][2] = 1;
+ }
+
+ trap_R_AddRefEntityToScene( &ent );
+}
+
+/*
+===============
+CG_Mover
+===============
+*/
+static void CG_Mover( centity_t *cent ) {
+ refEntity_t ent;
+ entityState_t *s1;
+
+ s1 = &cent->currentState;
+
+ // create the render entity
+ memset (&ent, 0, sizeof(ent));
+ VectorCopy( cent->lerpOrigin, ent.origin);
+ VectorCopy( cent->lerpOrigin, ent.oldorigin);
+ AnglesToAxis( cent->lerpAngles, ent.axis );
+
+ ent.renderfx = RF_NOSHADOW;
+
+ // flicker between two skins (FIXME?)
+ ent.skinNum = ( cg.time >> 6 ) & 1;
+
+ // get the model, either as a bmodel or a modelindex
+ if ( s1->solid == SOLID_BMODEL ) {
+ ent.hModel = cgs.inlineDrawModel[s1->modelindex];
+ } else {
+ ent.hModel = cgs.gameModels[s1->modelindex];
+ }
+
+ // add to refresh list
+ trap_R_AddRefEntityToScene(&ent);
+
+ // add the secondary model
+ if ( s1->modelindex2 ) {
+ ent.skinNum = 0;
+ ent.hModel = cgs.gameModels[s1->modelindex2];
+ trap_R_AddRefEntityToScene(&ent);
+ }
+
+}
+
+/*
+===============
+CG_Beam
+
+Also called as an event
+===============
+*/
+void CG_Beam( centity_t *cent ) {
+ refEntity_t ent;
+ entityState_t *s1;
+
+ s1 = &cent->currentState;
+
+ // create the render entity
+ memset (&ent, 0, sizeof(ent));
+ VectorCopy( s1->pos.trBase, ent.origin );
+ VectorCopy( s1->origin2, ent.oldorigin );
+ AxisClear( ent.axis );
+ ent.reType = RT_BEAM;
+
+ ent.renderfx = RF_NOSHADOW;
+
+ // add to refresh list
+ trap_R_AddRefEntityToScene(&ent);
+}
+
+
+/*
+===============
+CG_Portal
+===============
+*/
+static void CG_Portal( centity_t *cent ) {
+ refEntity_t ent;
+ entityState_t *s1;
+
+ s1 = &cent->currentState;
+
+ // create the render entity
+ memset (&ent, 0, sizeof(ent));
+ VectorCopy( cent->lerpOrigin, ent.origin );
+ VectorCopy( s1->origin2, ent.oldorigin );
+ ByteToDir( s1->eventParm, ent.axis[0] );
+ PerpendicularVector( ent.axis[1], ent.axis[0] );
+
+ // negating this tends to get the directions like they want
+ // we really should have a camera roll value
+ VectorSubtract( vec3_origin, ent.axis[1], ent.axis[1] );
+
+ CrossProduct( ent.axis[0], ent.axis[1], ent.axis[2] );
+ ent.reType = RT_PORTALSURFACE;
+ ent.oldframe = s1->powerups;
+ ent.frame = s1->frame; // rotation speed
+ ent.skinNum = s1->clientNum/256.0 * 360; // roll offset
+
+ // add to refresh list
+ trap_R_AddRefEntityToScene(&ent);
+}
+
+
+/*
+=========================
+CG_AdjustPositionForMover
+
+Also called by client movement prediction code
+=========================
+*/
+void CG_AdjustPositionForMover( const vec3_t in, int moverNum, int fromTime, int toTime, vec3_t out ) {
+ centity_t *cent;
+ vec3_t oldOrigin, origin, deltaOrigin;
+ vec3_t oldAngles, angles, deltaAngles;
+
+ if ( moverNum <= 0 || moverNum >= ENTITYNUM_MAX_NORMAL ) {
+ VectorCopy( in, out );
+ return;
+ }
+
+ cent = &cg_entities[ moverNum ];
+ if ( cent->currentState.eType != ET_MOVER ) {
+ VectorCopy( in, out );
+ return;
+ }
+
+ BG_EvaluateTrajectory( &cent->currentState.pos, fromTime, oldOrigin );
+ BG_EvaluateTrajectory( &cent->currentState.apos, fromTime, oldAngles );
+
+ BG_EvaluateTrajectory( &cent->currentState.pos, toTime, origin );
+ BG_EvaluateTrajectory( &cent->currentState.apos, toTime, angles );
+
+ VectorSubtract( origin, oldOrigin, deltaOrigin );
+ VectorSubtract( angles, oldAngles, deltaAngles );
+
+ VectorAdd( in, deltaOrigin, out );
+
+ // FIXME: origin change when on a rotating object
+}
+
+
+/*
+=============================
+CG_InterpolateEntityPosition
+=============================
+*/
+static void CG_InterpolateEntityPosition( centity_t *cent ) {
+ vec3_t current, next;
+ float f;
+
+ // it would be an internal error to find an entity that interpolates without
+ // a snapshot ahead of the current one
+ if ( cg.nextSnap == NULL ) {
+ CG_Error( "CG_InterpoateEntityPosition: cg.nextSnap == NULL" );
+ }
+
+ f = cg.frameInterpolation;
+
+ // this will linearize a sine or parabolic curve, but it is important
+ // to not extrapolate player positions if more recent data is available
+ BG_EvaluateTrajectory( &cent->currentState.pos, cg.snap->serverTime, current );
+ BG_EvaluateTrajectory( &cent->nextState.pos, cg.nextSnap->serverTime, next );
+
+ cent->lerpOrigin[0] = current[0] + f * ( next[0] - current[0] );
+ cent->lerpOrigin[1] = current[1] + f * ( next[1] - current[1] );
+ cent->lerpOrigin[2] = current[2] + f * ( next[2] - current[2] );
+
+ BG_EvaluateTrajectory( &cent->currentState.apos, cg.snap->serverTime, current );
+ BG_EvaluateTrajectory( &cent->nextState.apos, cg.nextSnap->serverTime, next );
+
+ cent->lerpAngles[0] = LerpAngle( current[0], next[0], f );
+ cent->lerpAngles[1] = LerpAngle( current[1], next[1], f );
+ cent->lerpAngles[2] = LerpAngle( current[2], next[2], f );
+
+}
+
+/*
+===============
+CG_CalcEntityLerpPositions
+
+===============
+*/
+static void CG_CalcEntityLerpPositions( centity_t *cent ) {
+
+ // if this player does not want to see extrapolated players
+ if ( !cg_smoothClients.integer ) {
+ // make sure the clients use TR_INTERPOLATE
+ if ( cent->currentState.number < MAX_CLIENTS ) {
+ cent->currentState.pos.trType = TR_INTERPOLATE;
+ cent->nextState.pos.trType = TR_INTERPOLATE;
+ }
+ }
+
+ if ( cent->interpolate && cent->currentState.pos.trType == TR_INTERPOLATE ) {
+ CG_InterpolateEntityPosition( cent );
+ return;
+ }
+
+ // first see if we can interpolate between two snaps for
+ // linear extrapolated clients
+ if ( cent->interpolate && cent->currentState.pos.trType == TR_LINEAR_STOP &&
+ cent->currentState.number < MAX_CLIENTS) {
+ CG_InterpolateEntityPosition( cent );
+ return;
+ }
+
+ // just use the current frame and evaluate as best we can
+ BG_EvaluateTrajectory( &cent->currentState.pos, cg.time, cent->lerpOrigin );
+ BG_EvaluateTrajectory( &cent->currentState.apos, cg.time, cent->lerpAngles );
+
+ // adjust for riding a mover if it wasn't rolled into the predicted
+ // player state
+ if ( cent != &cg.predictedPlayerEntity ) {
+ CG_AdjustPositionForMover( cent->lerpOrigin, cent->currentState.groundEntityNum,
+ cg.snap->serverTime, cg.time, cent->lerpOrigin );
+ }
+}
+
+/*
+===============
+CG_TeamBase
+===============
+*/
+static void CG_TeamBase( centity_t *cent ) {
+ refEntity_t model;
+#ifdef MISSIONPACK
+ vec3_t angles;
+ int t, h;
+ float c;
+
+ if ( cgs.gametype == GT_CTF || cgs.gametype == GT_1FCTF ) {
+#else
+ if ( cgs.gametype == GT_CTF) {
+#endif
+ // show the flag base
+ memset(&model, 0, sizeof(model));
+ model.reType = RT_MODEL;
+ VectorCopy( cent->lerpOrigin, model.lightingOrigin );
+ VectorCopy( cent->lerpOrigin, model.origin );
+ AnglesToAxis( cent->currentState.angles, model.axis );
+ if ( cent->currentState.modelindex == TEAM_RED ) {
+ model.hModel = cgs.media.redFlagBaseModel;
+ }
+ else if ( cent->currentState.modelindex == TEAM_BLUE ) {
+ model.hModel = cgs.media.blueFlagBaseModel;
+ }
+ else {
+ model.hModel = cgs.media.neutralFlagBaseModel;
+ }
+ trap_R_AddRefEntityToScene( &model );
+ }
+#ifdef MISSIONPACK
+ else if ( cgs.gametype == GT_OBELISK ) {
+ // show the obelisk
+ memset(&model, 0, sizeof(model));
+ model.reType = RT_MODEL;
+ VectorCopy( cent->lerpOrigin, model.lightingOrigin );
+ VectorCopy( cent->lerpOrigin, model.origin );
+ AnglesToAxis( cent->currentState.angles, model.axis );
+
+ model.hModel = cgs.media.overloadBaseModel;
+ trap_R_AddRefEntityToScene( &model );
+ // if hit
+ if ( cent->currentState.frame == 1) {
+ // show hit model
+ // modelindex2 is the health value of the obelisk
+ c = cent->currentState.modelindex2;
+ model.shaderRGBA[0] = 0xff;
+ model.shaderRGBA[1] = c;
+ model.shaderRGBA[2] = c;
+ model.shaderRGBA[3] = 0xff;
+ //
+ model.hModel = cgs.media.overloadEnergyModel;
+ trap_R_AddRefEntityToScene( &model );
+ }
+ // if respawning
+ if ( cent->currentState.frame == 2) {
+ if ( !cent->miscTime ) {
+ cent->miscTime = cg.time;
+ }
+ t = cg.time - cent->miscTime;
+ h = (cg_obeliskRespawnDelay.integer - 5) * 1000;
+ //
+ if (t > h) {
+ c = (float) (t - h) / h;
+ if (c > 1)
+ c = 1;
+ }
+ else {
+ c = 0;
+ }
+ // show the lights
+ AnglesToAxis( cent->currentState.angles, model.axis );
+ //
+ model.shaderRGBA[0] = c * 0xff;
+ model.shaderRGBA[1] = c * 0xff;
+ model.shaderRGBA[2] = c * 0xff;
+ model.shaderRGBA[3] = c * 0xff;
+
+ model.hModel = cgs.media.overloadLightsModel;
+ trap_R_AddRefEntityToScene( &model );
+ // show the target
+ if (t > h) {
+ if ( !cent->muzzleFlashTime ) {
+ trap_S_StartSound (cent->lerpOrigin, ENTITYNUM_NONE, CHAN_BODY, cgs.media.obeliskRespawnSound);
+ cent->muzzleFlashTime = 1;
+ }
+ VectorCopy(cent->currentState.angles, angles);
+ angles[YAW] += (float) 16 * acos(1-c) * 180 / M_PI;
+ AnglesToAxis( angles, model.axis );
+
+ VectorScale( model.axis[0], c, model.axis[0]);
+ VectorScale( model.axis[1], c, model.axis[1]);
+ VectorScale( model.axis[2], c, model.axis[2]);
+
+ model.shaderRGBA[0] = 0xff;
+ model.shaderRGBA[1] = 0xff;
+ model.shaderRGBA[2] = 0xff;
+ model.shaderRGBA[3] = 0xff;
+ //
+ model.origin[2] += 56;
+ model.hModel = cgs.media.overloadTargetModel;
+ trap_R_AddRefEntityToScene( &model );
+ }
+ else {
+ //FIXME: show animated smoke
+ }
+ }
+ else {
+ cent->miscTime = 0;
+ cent->muzzleFlashTime = 0;
+ // modelindex2 is the health value of the obelisk
+ c = cent->currentState.modelindex2;
+ model.shaderRGBA[0] = 0xff;
+ model.shaderRGBA[1] = c;
+ model.shaderRGBA[2] = c;
+ model.shaderRGBA[3] = 0xff;
+ // show the lights
+ model.hModel = cgs.media.overloadLightsModel;
+ trap_R_AddRefEntityToScene( &model );
+ // show the target
+ model.origin[2] += 56;
+ model.hModel = cgs.media.overloadTargetModel;
+ trap_R_AddRefEntityToScene( &model );
+ }
+ }
+ else if ( cgs.gametype == GT_HARVESTER ) {
+ // show harvester model
+ memset(&model, 0, sizeof(model));
+ model.reType = RT_MODEL;
+ VectorCopy( cent->lerpOrigin, model.lightingOrigin );
+ VectorCopy( cent->lerpOrigin, model.origin );
+ AnglesToAxis( cent->currentState.angles, model.axis );
+
+ if ( cent->currentState.modelindex == TEAM_RED ) {
+ model.hModel = cgs.media.harvesterModel;
+ model.customSkin = cgs.media.harvesterRedSkin;
+ }
+ else if ( cent->currentState.modelindex == TEAM_BLUE ) {
+ model.hModel = cgs.media.harvesterModel;
+ model.customSkin = cgs.media.harvesterBlueSkin;
+ }
+ else {
+ model.hModel = cgs.media.harvesterNeutralModel;
+ model.customSkin = 0;
+ }
+ trap_R_AddRefEntityToScene( &model );
+ }
+#endif
+}
+
+/*
+===============
+CG_AddCEntity
+
+===============
+*/
+static void CG_AddCEntity( centity_t *cent ) {
+ // event-only entities will have been dealt with already
+ if ( cent->currentState.eType >= ET_EVENTS ) {
+ return;
+ }
+
+ // calculate the current origin
+ CG_CalcEntityLerpPositions( cent );
+
+ // add automatic effects
+ CG_EntityEffects( cent );
+
+ switch ( cent->currentState.eType ) {
+ default:
+ CG_Error( "Bad entity type: %i\n", cent->currentState.eType );
+ break;
+ case ET_INVISIBLE:
+ case ET_PUSH_TRIGGER:
+ case ET_TELEPORT_TRIGGER:
+ break;
+ case ET_GENERAL:
+ CG_General( cent );
+ break;
+ case ET_PLAYER:
+ CG_Player( cent );
+ break;
+ case ET_ITEM:
+ CG_Item( cent );
+ break;
+ case ET_MISSILE:
+ CG_Missile( cent );
+ break;
+ case ET_MOVER:
+ CG_Mover( cent );
+ break;
+ case ET_BEAM:
+ CG_Beam( cent );
+ break;
+ case ET_PORTAL:
+ CG_Portal( cent );
+ break;
+ case ET_SPEAKER:
+ CG_Speaker( cent );
+ break;
+ case ET_GRAPPLE:
+ CG_Grapple( cent );
+ break;
+ case ET_TEAM:
+ CG_TeamBase( cent );
+ break;
+ }
+}
+
+/*
+===============
+CG_AddPacketEntities
+
+===============
+*/
+void CG_AddPacketEntities( void ) {
+ int num;
+ centity_t *cent;
+ playerState_t *ps;
+
+ // set cg.frameInterpolation
+ if ( cg.nextSnap ) {
+ int delta;
+
+ delta = (cg.nextSnap->serverTime - cg.snap->serverTime);
+ if ( delta == 0 ) {
+ cg.frameInterpolation = 0;
+ } else {
+ cg.frameInterpolation = (float)( cg.time - cg.snap->serverTime ) / delta;
+ }
+ } else {
+ cg.frameInterpolation = 0; // actually, it should never be used, because
+ // no entities should be marked as interpolating
+ }
+
+ // the auto-rotating items will all have the same axis
+ cg.autoAngles[0] = 0;
+ cg.autoAngles[1] = ( cg.time & 2047 ) * 360 / 2048.0;
+ cg.autoAngles[2] = 0;
+
+ cg.autoAnglesFast[0] = 0;
+ cg.autoAnglesFast[1] = ( cg.time & 1023 ) * 360 / 1024.0f;
+ cg.autoAnglesFast[2] = 0;
+
+ AnglesToAxis( cg.autoAngles, cg.autoAxis );
+ AnglesToAxis( cg.autoAnglesFast, cg.autoAxisFast );
+
+ // generate and add the entity from the playerstate
+ ps = &cg.predictedPlayerState;
+ BG_PlayerStateToEntityState( ps, &cg.predictedPlayerEntity.currentState, qfalse );
+ CG_AddCEntity( &cg.predictedPlayerEntity );
+
+ // lerp the non-predicted value for lightning gun origins
+ CG_CalcEntityLerpPositions( &cg_entities[ cg.snap->ps.clientNum ] );
+
+ // add each entity sent over by the server
+ for ( num = 0 ; num < cg.snap->numEntities ; num++ ) {
+ cent = &cg_entities[ cg.snap->entities[ num ].number ];
+ CG_AddCEntity( cent );
+ }
+}
+
diff --git a/code/cgame/cg_event.c b/code/cgame/cg_event.c
new file mode 100755
index 0000000..86167c6
--- /dev/null
+++ b/code/cgame/cg_event.c
@@ -0,0 +1,1205 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// cg_event.c -- handle entity events at snapshot or playerstate transitions
+
+#include "cg_local.h"
+
+// for the voice chats
+#ifdef MISSIONPACK // bk001205
+#include "../../ui/menudef.h"
+#endif
+//==========================================================================
+
+/*
+===================
+CG_PlaceString
+
+Also called by scoreboard drawing
+===================
+*/
+const char *CG_PlaceString( int rank ) {
+ static char str[64];
+ char *s, *t;
+
+ if ( rank & RANK_TIED_FLAG ) {
+ rank &= ~RANK_TIED_FLAG;
+ t = "Tied for ";
+ } else {
+ t = "";
+ }
+
+ if ( rank == 1 ) {
+ s = S_COLOR_BLUE "1st" S_COLOR_WHITE; // draw in blue
+ } else if ( rank == 2 ) {
+ s = S_COLOR_RED "2nd" S_COLOR_WHITE; // draw in red
+ } else if ( rank == 3 ) {
+ s = S_COLOR_YELLOW "3rd" S_COLOR_WHITE; // draw in yellow
+ } else if ( rank == 11 ) {
+ s = "11th";
+ } else if ( rank == 12 ) {
+ s = "12th";
+ } else if ( rank == 13 ) {
+ s = "13th";
+ } else if ( rank % 10 == 1 ) {
+ s = va("%ist", rank);
+ } else if ( rank % 10 == 2 ) {
+ s = va("%ind", rank);
+ } else if ( rank % 10 == 3 ) {
+ s = va("%ird", rank);
+ } else {
+ s = va("%ith", rank);
+ }
+
+ Com_sprintf( str, sizeof( str ), "%s%s", t, s );
+ return str;
+}
+
+/*
+=============
+CG_Obituary
+=============
+*/
+static void CG_Obituary( entityState_t *ent ) {
+ int mod;
+ int target, attacker;
+ char *message;
+ char *message2;
+ const char *targetInfo;
+ const char *attackerInfo;
+ char targetName[32];
+ char attackerName[32];
+ gender_t gender;
+ clientInfo_t *ci;
+
+ target = ent->otherEntityNum;
+ attacker = ent->otherEntityNum2;
+ mod = ent->eventParm;
+
+ if ( target < 0 || target >= MAX_CLIENTS ) {
+ CG_Error( "CG_Obituary: target out of range" );
+ }
+ ci = &cgs.clientinfo[target];
+
+ if ( attacker < 0 || attacker >= MAX_CLIENTS ) {
+ attacker = ENTITYNUM_WORLD;
+ attackerInfo = NULL;
+ } else {
+ attackerInfo = CG_ConfigString( CS_PLAYERS + attacker );
+ }
+
+ targetInfo = CG_ConfigString( CS_PLAYERS + target );
+ if ( !targetInfo ) {
+ return;
+ }
+ Q_strncpyz( targetName, Info_ValueForKey( targetInfo, "n" ), sizeof(targetName) - 2);
+ strcat( targetName, S_COLOR_WHITE );
+
+ message2 = "";
+
+ // check for single client messages
+
+ switch( mod ) {
+ case MOD_SUICIDE:
+ message = "suicides";
+ break;
+ case MOD_FALLING:
+ message = "cratered";
+ break;
+ case MOD_CRUSH:
+ message = "was squished";
+ break;
+ case MOD_WATER:
+ message = "sank like a rock";
+ break;
+ case MOD_SLIME:
+ message = "melted";
+ break;
+ case MOD_LAVA:
+ message = "does a back flip into the lava";
+ break;
+ case MOD_TARGET_LASER:
+ message = "saw the light";
+ break;
+ case MOD_TRIGGER_HURT:
+ message = "was in the wrong place";
+ break;
+ default:
+ message = NULL;
+ break;
+ }
+
+ if (attacker == target) {
+ gender = ci->gender;
+ switch (mod) {
+#ifdef MISSIONPACK
+ case MOD_KAMIKAZE:
+ message = "goes out with a bang";
+ break;
+#endif
+ case MOD_GRENADE_SPLASH:
+ if ( gender == GENDER_FEMALE )
+ message = "tripped on her own grenade";
+ else if ( gender == GENDER_NEUTER )
+ message = "tripped on its own grenade";
+ else
+ message = "tripped on his own grenade";
+ break;
+ case MOD_ROCKET_SPLASH:
+ if ( gender == GENDER_FEMALE )
+ message = "blew herself up";
+ else if ( gender == GENDER_NEUTER )
+ message = "blew itself up";
+ else
+ message = "blew himself up";
+ break;
+ case MOD_PLASMA_SPLASH:
+ if ( gender == GENDER_FEMALE )
+ message = "melted herself";
+ else if ( gender == GENDER_NEUTER )
+ message = "melted itself";
+ else
+ message = "melted himself";
+ break;
+ case MOD_BFG_SPLASH:
+ message = "should have used a smaller gun";
+ break;
+#ifdef MISSIONPACK
+ case MOD_PROXIMITY_MINE:
+ if( gender == GENDER_FEMALE ) {
+ message = "found her prox mine";
+ } else if ( gender == GENDER_NEUTER ) {
+ message = "found it's prox mine";
+ } else {
+ message = "found his prox mine";
+ }
+ break;
+#endif
+ default:
+ if ( gender == GENDER_FEMALE )
+ message = "killed herself";
+ else if ( gender == GENDER_NEUTER )
+ message = "killed itself";
+ else
+ message = "killed himself";
+ break;
+ }
+ }
+
+ if (message) {
+ CG_Printf( "%s %s.\n", targetName, message);
+ return;
+ }
+
+ // check for kill messages from the current clientNum
+ if ( attacker == cg.snap->ps.clientNum ) {
+ char *s;
+
+ if ( cgs.gametype < GT_TEAM ) {
+ s = va("You fragged %s\n%s place with %i", targetName,
+ CG_PlaceString( cg.snap->ps.persistant[PERS_RANK] + 1 ),
+ cg.snap->ps.persistant[PERS_SCORE] );
+ } else {
+ s = va("You fragged %s", targetName );
+ }
+#ifdef MISSIONPACK
+ if (!(cg_singlePlayerActive.integer && cg_cameraOrbit.integer)) {
+ CG_CenterPrint( s, SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH );
+ }
+#else
+ CG_CenterPrint( s, SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH );
+#endif
+
+ // print the text message as well
+ }
+
+ // check for double client messages
+ if ( !attackerInfo ) {
+ attacker = ENTITYNUM_WORLD;
+ strcpy( attackerName, "noname" );
+ } else {
+ Q_strncpyz( attackerName, Info_ValueForKey( attackerInfo, "n" ), sizeof(attackerName) - 2);
+ strcat( attackerName, S_COLOR_WHITE );
+ // check for kill messages about the current clientNum
+ if ( target == cg.snap->ps.clientNum ) {
+ Q_strncpyz( cg.killerName, attackerName, sizeof( cg.killerName ) );
+ }
+ }
+
+ if ( attacker != ENTITYNUM_WORLD ) {
+ switch (mod) {
+ case MOD_GRAPPLE:
+ message = "was caught by";
+ break;
+ case MOD_GAUNTLET:
+ message = "was pummeled by";
+ break;
+ case MOD_MACHINEGUN:
+ message = "was machinegunned by";
+ break;
+ case MOD_SHOTGUN:
+ message = "was gunned down by";
+ break;
+ case MOD_GRENADE:
+ message = "ate";
+ message2 = "'s grenade";
+ break;
+ case MOD_GRENADE_SPLASH:
+ message = "was shredded by";
+ message2 = "'s shrapnel";
+ break;
+ case MOD_ROCKET:
+ message = "ate";
+ message2 = "'s rocket";
+ break;
+ case MOD_ROCKET_SPLASH:
+ message = "almost dodged";
+ message2 = "'s rocket";
+ break;
+ case MOD_PLASMA:
+ message = "was melted by";
+ message2 = "'s plasmagun";
+ break;
+ case MOD_PLASMA_SPLASH:
+ message = "was melted by";
+ message2 = "'s plasmagun";
+ break;
+ case MOD_RAILGUN:
+ message = "was railed by";
+ break;
+ case MOD_LIGHTNING:
+ message = "was electrocuted by";
+ break;
+ case MOD_BFG:
+ case MOD_BFG_SPLASH:
+ message = "was blasted by";
+ message2 = "'s BFG";
+ break;
+#ifdef MISSIONPACK
+ case MOD_NAIL:
+ message = "was nailed by";
+ break;
+ case MOD_CHAINGUN:
+ message = "got lead poisoning from";
+ message2 = "'s Chaingun";
+ break;
+ case MOD_PROXIMITY_MINE:
+ message = "was too close to";
+ message2 = "'s Prox Mine";
+ break;
+ case MOD_KAMIKAZE:
+ message = "falls to";
+ message2 = "'s Kamikaze blast";
+ break;
+ case MOD_JUICED:
+ message = "was juiced by";
+ break;
+#endif
+ case MOD_TELEFRAG:
+ message = "tried to invade";
+ message2 = "'s personal space";
+ break;
+ default:
+ message = "was killed by";
+ break;
+ }
+
+ if (message) {
+ CG_Printf( "%s %s %s%s\n",
+ targetName, message, attackerName, message2);
+ return;
+ }
+ }
+
+ // we don't know what it was
+ CG_Printf( "%s died.\n", targetName );
+}
+
+//==========================================================================
+
+/*
+===============
+CG_UseItem
+===============
+*/
+static void CG_UseItem( centity_t *cent ) {
+ clientInfo_t *ci;
+ int itemNum, clientNum;
+ gitem_t *item;
+ entityState_t *es;
+
+ es = &cent->currentState;
+
+ itemNum = (es->event & ~EV_EVENT_BITS) - EV_USE_ITEM0;
+ if ( itemNum < 0 || itemNum > HI_NUM_HOLDABLE ) {
+ itemNum = 0;
+ }
+
+ // print a message if the local player
+ if ( es->number == cg.snap->ps.clientNum ) {
+ if ( !itemNum ) {
+ CG_CenterPrint( "No item to use", SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH );
+ } else {
+ item = BG_FindItemForHoldable( itemNum );
+ CG_CenterPrint( va("Use %s", item->pickup_name), SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH );
+ }
+ }
+
+ switch ( itemNum ) {
+ default:
+ case HI_NONE:
+ trap_S_StartSound (NULL, es->number, CHAN_BODY, cgs.media.useNothingSound );
+ break;
+
+ case HI_TELEPORTER:
+ break;
+
+ case HI_MEDKIT:
+ clientNum = cent->currentState.clientNum;
+ if ( clientNum >= 0 && clientNum < MAX_CLIENTS ) {
+ ci = &cgs.clientinfo[ clientNum ];
+ ci->medkitUsageTime = cg.time;
+ }
+ trap_S_StartSound (NULL, es->number, CHAN_BODY, cgs.media.medkitSound );
+ break;
+
+#ifdef MISSIONPACK
+ case HI_KAMIKAZE:
+ break;
+
+ case HI_PORTAL:
+ break;
+ case HI_INVULNERABILITY:
+ trap_S_StartSound (NULL, es->number, CHAN_BODY, cgs.media.useInvulnerabilitySound );
+ break;
+#endif
+ }
+
+}
+
+/*
+================
+CG_ItemPickup
+
+A new item was picked up this frame
+================
+*/
+static void CG_ItemPickup( int itemNum ) {
+ cg.itemPickup = itemNum;
+ cg.itemPickupTime = cg.time;
+ cg.itemPickupBlendTime = cg.time;
+ // see if it should be the grabbed weapon
+ if ( bg_itemlist[itemNum].giType == IT_WEAPON ) {
+ // select it immediately
+ if ( cg_autoswitch.integer && bg_itemlist[itemNum].giTag != WP_MACHINEGUN ) {
+ cg.weaponSelectTime = cg.time;
+ cg.weaponSelect = bg_itemlist[itemNum].giTag;
+ }
+ }
+
+}
+
+
+/*
+================
+CG_PainEvent
+
+Also called by playerstate transition
+================
+*/
+void CG_PainEvent( centity_t *cent, int health ) {
+ char *snd;
+
+ // don't do more than two pain sounds a second
+ if ( cg.time - cent->pe.painTime < 500 ) {
+ return;
+ }
+
+ if ( health < 25 ) {
+ snd = "*pain25_1.wav";
+ } else if ( health < 50 ) {
+ snd = "*pain50_1.wav";
+ } else if ( health < 75 ) {
+ snd = "*pain75_1.wav";
+ } else {
+ snd = "*pain100_1.wav";
+ }
+ trap_S_StartSound( NULL, cent->currentState.number, CHAN_VOICE,
+ CG_CustomSound( cent->currentState.number, snd ) );
+
+ // save pain time for programitic twitch animation
+ cent->pe.painTime = cg.time;
+ cent->pe.painDirection ^= 1;
+}
+
+
+
+/*
+==============
+CG_EntityEvent
+
+An entity has an event value
+also called by CG_CheckPlayerstateEvents
+==============
+*/
+#define DEBUGNAME(x) if(cg_debugEvents.integer){CG_Printf(x"\n");}
+void CG_EntityEvent( centity_t *cent, vec3_t position ) {
+ entityState_t *es;
+ int event;
+ vec3_t dir;
+ const char *s;
+ int clientNum;
+ clientInfo_t *ci;
+
+ es = &cent->currentState;
+ event = es->event & ~EV_EVENT_BITS;
+
+ if ( cg_debugEvents.integer ) {
+ CG_Printf( "ent:%3i event:%3i ", es->number, event );
+ }
+
+ if ( !event ) {
+ DEBUGNAME("ZEROEVENT");
+ return;
+ }
+
+ clientNum = es->clientNum;
+ if ( clientNum < 0 || clientNum >= MAX_CLIENTS ) {
+ clientNum = 0;
+ }
+ ci = &cgs.clientinfo[ clientNum ];
+
+ switch ( event ) {
+ //
+ // movement generated events
+ //
+ case EV_FOOTSTEP:
+ DEBUGNAME("EV_FOOTSTEP");
+ if (cg_footsteps.integer) {
+ trap_S_StartSound (NULL, es->number, CHAN_BODY,
+ cgs.media.footsteps[ ci->footsteps ][rand()&3] );
+ }
+ break;
+ case EV_FOOTSTEP_METAL:
+ DEBUGNAME("EV_FOOTSTEP_METAL");
+ if (cg_footsteps.integer) {
+ trap_S_StartSound (NULL, es->number, CHAN_BODY,
+ cgs.media.footsteps[ FOOTSTEP_METAL ][rand()&3] );
+ }
+ break;
+ case EV_FOOTSPLASH:
+ DEBUGNAME("EV_FOOTSPLASH");
+ if (cg_footsteps.integer) {
+ trap_S_StartSound (NULL, es->number, CHAN_BODY,
+ cgs.media.footsteps[ FOOTSTEP_SPLASH ][rand()&3] );
+ }
+ break;
+ case EV_FOOTWADE:
+ DEBUGNAME("EV_FOOTWADE");
+ if (cg_footsteps.integer) {
+ trap_S_StartSound (NULL, es->number, CHAN_BODY,
+ cgs.media.footsteps[ FOOTSTEP_SPLASH ][rand()&3] );
+ }
+ break;
+ case EV_SWIM:
+ DEBUGNAME("EV_SWIM");
+ if (cg_footsteps.integer) {
+ trap_S_StartSound (NULL, es->number, CHAN_BODY,
+ cgs.media.footsteps[ FOOTSTEP_SPLASH ][rand()&3] );
+ }
+ break;
+
+
+ case EV_FALL_SHORT:
+ DEBUGNAME("EV_FALL_SHORT");
+ trap_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.landSound );
+ if ( clientNum == cg.predictedPlayerState.clientNum ) {
+ // smooth landing z changes
+ cg.landChange = -8;
+ cg.landTime = cg.time;
+ }
+ break;
+ case EV_FALL_MEDIUM:
+ DEBUGNAME("EV_FALL_MEDIUM");
+ // use normal pain sound
+ trap_S_StartSound( NULL, es->number, CHAN_VOICE, CG_CustomSound( es->number, "*pain100_1.wav" ) );
+ if ( clientNum == cg.predictedPlayerState.clientNum ) {
+ // smooth landing z changes
+ cg.landChange = -16;
+ cg.landTime = cg.time;
+ }
+ break;
+ case EV_FALL_FAR:
+ DEBUGNAME("EV_FALL_FAR");
+ trap_S_StartSound (NULL, es->number, CHAN_AUTO, CG_CustomSound( es->number, "*fall1.wav" ) );
+ cent->pe.painTime = cg.time; // don't play a pain sound right after this
+ if ( clientNum == cg.predictedPlayerState.clientNum ) {
+ // smooth landing z changes
+ cg.landChange = -24;
+ cg.landTime = cg.time;
+ }
+ break;
+
+ case EV_STEP_4:
+ case EV_STEP_8:
+ case EV_STEP_12:
+ case EV_STEP_16: // smooth out step up transitions
+ DEBUGNAME("EV_STEP");
+ {
+ float oldStep;
+ int delta;
+ int step;
+
+ if ( clientNum != cg.predictedPlayerState.clientNum ) {
+ break;
+ }
+ // if we are interpolating, we don't need to smooth steps
+ if ( cg.demoPlayback || (cg.snap->ps.pm_flags & PMF_FOLLOW) ||
+ cg_nopredict.integer || cg_synchronousClients.integer ) {
+ break;
+ }
+ // check for stepping up before a previous step is completed
+ delta = cg.time - cg.stepTime;
+ if (delta < STEP_TIME) {
+ oldStep = cg.stepChange * (STEP_TIME - delta) / STEP_TIME;
+ } else {
+ oldStep = 0;
+ }
+
+ // add this amount
+ step = 4 * (event - EV_STEP_4 + 1 );
+ cg.stepChange = oldStep + step;
+ if ( cg.stepChange > MAX_STEP_CHANGE ) {
+ cg.stepChange = MAX_STEP_CHANGE;
+ }
+ cg.stepTime = cg.time;
+ break;
+ }
+
+ case EV_JUMP_PAD:
+ DEBUGNAME("EV_JUMP_PAD");
+// CG_Printf( "EV_JUMP_PAD w/effect #%i\n", es->eventParm );
+ {
+ localEntity_t *smoke;
+ vec3_t up = {0, 0, 1};
+
+
+ smoke = CG_SmokePuff( cent->lerpOrigin, up,
+ 32,
+ 1, 1, 1, 0.33f,
+ 1000,
+ cg.time, 0,
+ LEF_PUFF_DONT_SCALE,
+ cgs.media.smokePuffShader );
+ }
+
+ // boing sound at origin, jump sound on player
+ trap_S_StartSound ( cent->lerpOrigin, -1, CHAN_VOICE, cgs.media.jumpPadSound );
+ trap_S_StartSound (NULL, es->number, CHAN_VOICE, CG_CustomSound( es->number, "*jump1.wav" ) );
+ break;
+
+ case EV_JUMP:
+ DEBUGNAME("EV_JUMP");
+ trap_S_StartSound (NULL, es->number, CHAN_VOICE, CG_CustomSound( es->number, "*jump1.wav" ) );
+ break;
+ case EV_TAUNT:
+ DEBUGNAME("EV_TAUNT");
+ trap_S_StartSound (NULL, es->number, CHAN_VOICE, CG_CustomSound( es->number, "*taunt.wav" ) );
+ break;
+#ifdef MISSIONPACK
+ case EV_TAUNT_YES:
+ DEBUGNAME("EV_TAUNT_YES");
+ CG_VoiceChatLocal(SAY_TEAM, qfalse, es->number, COLOR_CYAN, VOICECHAT_YES);
+ break;
+ case EV_TAUNT_NO:
+ DEBUGNAME("EV_TAUNT_NO");
+ CG_VoiceChatLocal(SAY_TEAM, qfalse, es->number, COLOR_CYAN, VOICECHAT_NO);
+ break;
+ case EV_TAUNT_FOLLOWME:
+ DEBUGNAME("EV_TAUNT_FOLLOWME");
+ CG_VoiceChatLocal(SAY_TEAM, qfalse, es->number, COLOR_CYAN, VOICECHAT_FOLLOWME);
+ break;
+ case EV_TAUNT_GETFLAG:
+ DEBUGNAME("EV_TAUNT_GETFLAG");
+ CG_VoiceChatLocal(SAY_TEAM, qfalse, es->number, COLOR_CYAN, VOICECHAT_ONGETFLAG);
+ break;
+ case EV_TAUNT_GUARDBASE:
+ DEBUGNAME("EV_TAUNT_GUARDBASE");
+ CG_VoiceChatLocal(SAY_TEAM, qfalse, es->number, COLOR_CYAN, VOICECHAT_ONDEFENSE);
+ break;
+ case EV_TAUNT_PATROL:
+ DEBUGNAME("EV_TAUNT_PATROL");
+ CG_VoiceChatLocal(SAY_TEAM, qfalse, es->number, COLOR_CYAN, VOICECHAT_ONPATROL);
+ break;
+#endif
+ case EV_WATER_TOUCH:
+ DEBUGNAME("EV_WATER_TOUCH");
+ trap_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.watrInSound );
+ break;
+ case EV_WATER_LEAVE:
+ DEBUGNAME("EV_WATER_LEAVE");
+ trap_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.watrOutSound );
+ break;
+ case EV_WATER_UNDER:
+ DEBUGNAME("EV_WATER_UNDER");
+ trap_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.watrUnSound );
+ break;
+ case EV_WATER_CLEAR:
+ DEBUGNAME("EV_WATER_CLEAR");
+ trap_S_StartSound (NULL, es->number, CHAN_AUTO, CG_CustomSound( es->number, "*gasp.wav" ) );
+ break;
+
+ case EV_ITEM_PICKUP:
+ DEBUGNAME("EV_ITEM_PICKUP");
+ {
+ gitem_t *item;
+ int index;
+
+ index = es->eventParm; // player predicted
+
+ if ( index < 1 || index >= bg_numItems ) {
+ break;
+ }
+ item = &bg_itemlist[ index ];
+
+ // powerups and team items will have a separate global sound, this one
+ // will be played at prediction time
+ if ( item->giType == IT_POWERUP || item->giType == IT_TEAM) {
+ trap_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.n_healthSound );
+ } else if (item->giType == IT_PERSISTANT_POWERUP) {
+#ifdef MISSIONPACK
+ switch (item->giTag ) {
+ case PW_SCOUT:
+ trap_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.scoutSound );
+ break;
+ case PW_GUARD:
+ trap_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.guardSound );
+ break;
+ case PW_DOUBLER:
+ trap_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.doublerSound );
+ break;
+ case PW_AMMOREGEN:
+ trap_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.ammoregenSound );
+ break;
+ }
+#endif
+ } else {
+ trap_S_StartSound (NULL, es->number, CHAN_AUTO, trap_S_RegisterSound( item->pickup_sound, qfalse ) );
+ }
+
+ // show icon and name on status bar
+ if ( es->number == cg.snap->ps.clientNum ) {
+ CG_ItemPickup( index );
+ }
+ }
+ break;
+
+ case EV_GLOBAL_ITEM_PICKUP:
+ DEBUGNAME("EV_GLOBAL_ITEM_PICKUP");
+ {
+ gitem_t *item;
+ int index;
+
+ index = es->eventParm; // player predicted
+
+ if ( index < 1 || index >= bg_numItems ) {
+ break;
+ }
+ item = &bg_itemlist[ index ];
+ // powerup pickups are global
+ if( item->pickup_sound ) {
+ trap_S_StartSound (NULL, cg.snap->ps.clientNum, CHAN_AUTO, trap_S_RegisterSound( item->pickup_sound, qfalse ) );
+ }
+
+ // show icon and name on status bar
+ if ( es->number == cg.snap->ps.clientNum ) {
+ CG_ItemPickup( index );
+ }
+ }
+ break;
+
+ //
+ // weapon events
+ //
+ case EV_NOAMMO:
+ DEBUGNAME("EV_NOAMMO");
+// trap_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.noAmmoSound );
+ if ( es->number == cg.snap->ps.clientNum ) {
+ CG_OutOfAmmoChange();
+ }
+ break;
+ case EV_CHANGE_WEAPON:
+ DEBUGNAME("EV_CHANGE_WEAPON");
+ trap_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.selectSound );
+ break;
+ case EV_FIRE_WEAPON:
+ DEBUGNAME("EV_FIRE_WEAPON");
+ CG_FireWeapon( cent );
+ break;
+
+ case EV_USE_ITEM0:
+ DEBUGNAME("EV_USE_ITEM0");
+ CG_UseItem( cent );
+ break;
+ case EV_USE_ITEM1:
+ DEBUGNAME("EV_USE_ITEM1");
+ CG_UseItem( cent );
+ break;
+ case EV_USE_ITEM2:
+ DEBUGNAME("EV_USE_ITEM2");
+ CG_UseItem( cent );
+ break;
+ case EV_USE_ITEM3:
+ DEBUGNAME("EV_USE_ITEM3");
+ CG_UseItem( cent );
+ break;
+ case EV_USE_ITEM4:
+ DEBUGNAME("EV_USE_ITEM4");
+ CG_UseItem( cent );
+ break;
+ case EV_USE_ITEM5:
+ DEBUGNAME("EV_USE_ITEM5");
+ CG_UseItem( cent );
+ break;
+ case EV_USE_ITEM6:
+ DEBUGNAME("EV_USE_ITEM6");
+ CG_UseItem( cent );
+ break;
+ case EV_USE_ITEM7:
+ DEBUGNAME("EV_USE_ITEM7");
+ CG_UseItem( cent );
+ break;
+ case EV_USE_ITEM8:
+ DEBUGNAME("EV_USE_ITEM8");
+ CG_UseItem( cent );
+ break;
+ case EV_USE_ITEM9:
+ DEBUGNAME("EV_USE_ITEM9");
+ CG_UseItem( cent );
+ break;
+ case EV_USE_ITEM10:
+ DEBUGNAME("EV_USE_ITEM10");
+ CG_UseItem( cent );
+ break;
+ case EV_USE_ITEM11:
+ DEBUGNAME("EV_USE_ITEM11");
+ CG_UseItem( cent );
+ break;
+ case EV_USE_ITEM12:
+ DEBUGNAME("EV_USE_ITEM12");
+ CG_UseItem( cent );
+ break;
+ case EV_USE_ITEM13:
+ DEBUGNAME("EV_USE_ITEM13");
+ CG_UseItem( cent );
+ break;
+ case EV_USE_ITEM14:
+ DEBUGNAME("EV_USE_ITEM14");
+ CG_UseItem( cent );
+ break;
+
+ //=================================================================
+
+ //
+ // other events
+ //
+ case EV_PLAYER_TELEPORT_IN:
+ DEBUGNAME("EV_PLAYER_TELEPORT_IN");
+ trap_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.teleInSound );
+ CG_SpawnEffect( position);
+ break;
+
+ case EV_PLAYER_TELEPORT_OUT:
+ DEBUGNAME("EV_PLAYER_TELEPORT_OUT");
+ trap_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.teleOutSound );
+ CG_SpawnEffect( position);
+ break;
+
+ case EV_ITEM_POP:
+ DEBUGNAME("EV_ITEM_POP");
+ trap_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.respawnSound );
+ break;
+ case EV_ITEM_RESPAWN:
+ DEBUGNAME("EV_ITEM_RESPAWN");
+ cent->miscTime = cg.time; // scale up from this
+ trap_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.respawnSound );
+ break;
+
+ case EV_GRENADE_BOUNCE:
+ DEBUGNAME("EV_GRENADE_BOUNCE");
+ if ( rand() & 1 ) {
+ trap_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.hgrenb1aSound );
+ } else {
+ trap_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.hgrenb2aSound );
+ }
+ break;
+
+#ifdef MISSIONPACK
+ case EV_PROXIMITY_MINE_STICK:
+ DEBUGNAME("EV_PROXIMITY_MINE_STICK");
+ if( es->eventParm & SURF_FLESH ) {
+ trap_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.wstbimplSound );
+ } else if( es->eventParm & SURF_METALSTEPS ) {
+ trap_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.wstbimpmSound );
+ } else {
+ trap_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.wstbimpdSound );
+ }
+ break;
+
+ case EV_PROXIMITY_MINE_TRIGGER:
+ DEBUGNAME("EV_PROXIMITY_MINE_TRIGGER");
+ trap_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.wstbactvSound );
+ break;
+ case EV_KAMIKAZE:
+ DEBUGNAME("EV_KAMIKAZE");
+ CG_KamikazeEffect( cent->lerpOrigin );
+ break;
+ case EV_OBELISKEXPLODE:
+ DEBUGNAME("EV_OBELISKEXPLODE");
+ CG_ObeliskExplode( cent->lerpOrigin, es->eventParm );
+ break;
+ case EV_OBELISKPAIN:
+ DEBUGNAME("EV_OBELISKPAIN");
+ CG_ObeliskPain( cent->lerpOrigin );
+ break;
+ case EV_INVUL_IMPACT:
+ DEBUGNAME("EV_INVUL_IMPACT");
+ CG_InvulnerabilityImpact( cent->lerpOrigin, cent->currentState.angles );
+ break;
+ case EV_JUICED:
+ DEBUGNAME("EV_JUICED");
+ CG_InvulnerabilityJuiced( cent->lerpOrigin );
+ break;
+ case EV_LIGHTNINGBOLT:
+ DEBUGNAME("EV_LIGHTNINGBOLT");
+ CG_LightningBoltBeam(es->origin2, es->pos.trBase);
+ break;
+#endif
+ case EV_SCOREPLUM:
+ DEBUGNAME("EV_SCOREPLUM");
+ CG_ScorePlum( cent->currentState.otherEntityNum, cent->lerpOrigin, cent->currentState.time );
+ break;
+
+ //
+ // missile impacts
+ //
+ case EV_MISSILE_HIT:
+ DEBUGNAME("EV_MISSILE_HIT");
+ ByteToDir( es->eventParm, dir );
+ CG_MissileHitPlayer( es->weapon, position, dir, es->otherEntityNum );
+ break;
+
+ case EV_MISSILE_MISS:
+ DEBUGNAME("EV_MISSILE_MISS");
+ ByteToDir( es->eventParm, dir );
+ CG_MissileHitWall( es->weapon, 0, position, dir, IMPACTSOUND_DEFAULT );
+ break;
+
+ case EV_MISSILE_MISS_METAL:
+ DEBUGNAME("EV_MISSILE_MISS_METAL");
+ ByteToDir( es->eventParm, dir );
+ CG_MissileHitWall( es->weapon, 0, position, dir, IMPACTSOUND_METAL );
+ break;
+
+ case EV_RAILTRAIL:
+ DEBUGNAME("EV_RAILTRAIL");
+ cent->currentState.weapon = WP_RAILGUN;
+ // if the end was on a nomark surface, don't make an explosion
+ CG_RailTrail( ci, es->origin2, es->pos.trBase );
+ if ( es->eventParm != 255 ) {
+ ByteToDir( es->eventParm, dir );
+ CG_MissileHitWall( es->weapon, es->clientNum, position, dir, IMPACTSOUND_DEFAULT );
+ }
+ break;
+
+ case EV_BULLET_HIT_WALL:
+ DEBUGNAME("EV_BULLET_HIT_WALL");
+ ByteToDir( es->eventParm, dir );
+ CG_Bullet( es->pos.trBase, es->otherEntityNum, dir, qfalse, ENTITYNUM_WORLD );
+ break;
+
+ case EV_BULLET_HIT_FLESH:
+ DEBUGNAME("EV_BULLET_HIT_FLESH");
+ CG_Bullet( es->pos.trBase, es->otherEntityNum, dir, qtrue, es->eventParm );
+ break;
+
+ case EV_SHOTGUN:
+ DEBUGNAME("EV_SHOTGUN");
+ CG_ShotgunFire( es );
+ break;
+
+ case EV_GENERAL_SOUND:
+ DEBUGNAME("EV_GENERAL_SOUND");
+ if ( cgs.gameSounds[ es->eventParm ] ) {
+ trap_S_StartSound (NULL, es->number, CHAN_VOICE, cgs.gameSounds[ es->eventParm ] );
+ } else {
+ s = CG_ConfigString( CS_SOUNDS + es->eventParm );
+ trap_S_StartSound (NULL, es->number, CHAN_VOICE, CG_CustomSound( es->number, s ) );
+ }
+ break;
+
+ case EV_GLOBAL_SOUND: // play from the player's head so it never diminishes
+ DEBUGNAME("EV_GLOBAL_SOUND");
+ if ( cgs.gameSounds[ es->eventParm ] ) {
+ trap_S_StartSound (NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.gameSounds[ es->eventParm ] );
+ } else {
+ s = CG_ConfigString( CS_SOUNDS + es->eventParm );
+ trap_S_StartSound (NULL, cg.snap->ps.clientNum, CHAN_AUTO, CG_CustomSound( es->number, s ) );
+ }
+ break;
+
+ case EV_GLOBAL_TEAM_SOUND: // play from the player's head so it never diminishes
+ {
+ DEBUGNAME("EV_GLOBAL_TEAM_SOUND");
+ switch( es->eventParm ) {
+ case GTS_RED_CAPTURE: // CTF: red team captured the blue flag, 1FCTF: red team captured the neutral flag
+ if ( cgs.clientinfo[cg.clientNum].team == TEAM_RED )
+ CG_AddBufferedSound( cgs.media.captureYourTeamSound );
+ else
+ CG_AddBufferedSound( cgs.media.captureOpponentSound );
+ break;
+ case GTS_BLUE_CAPTURE: // CTF: blue team captured the red flag, 1FCTF: blue team captured the neutral flag
+ if ( cgs.clientinfo[cg.clientNum].team == TEAM_BLUE )
+ CG_AddBufferedSound( cgs.media.captureYourTeamSound );
+ else
+ CG_AddBufferedSound( cgs.media.captureOpponentSound );
+ break;
+ case GTS_RED_RETURN: // CTF: blue flag returned, 1FCTF: never used
+ if ( cgs.clientinfo[cg.clientNum].team == TEAM_RED )
+ CG_AddBufferedSound( cgs.media.returnYourTeamSound );
+ else
+ CG_AddBufferedSound( cgs.media.returnOpponentSound );
+ //
+ CG_AddBufferedSound( cgs.media.blueFlagReturnedSound );
+ break;
+ case GTS_BLUE_RETURN: // CTF red flag returned, 1FCTF: neutral flag returned
+ if ( cgs.clientinfo[cg.clientNum].team == TEAM_BLUE )
+ CG_AddBufferedSound( cgs.media.returnYourTeamSound );
+ else
+ CG_AddBufferedSound( cgs.media.returnOpponentSound );
+ //
+ CG_AddBufferedSound( cgs.media.redFlagReturnedSound );
+ break;
+
+ case GTS_RED_TAKEN: // CTF: red team took blue flag, 1FCTF: blue team took the neutral flag
+ // if this player picked up the flag then a sound is played in CG_CheckLocalSounds
+ if (cg.snap->ps.powerups[PW_BLUEFLAG] || cg.snap->ps.powerups[PW_NEUTRALFLAG]) {
+ }
+ else {
+ if (cgs.clientinfo[cg.clientNum].team == TEAM_BLUE) {
+#ifdef MISSIONPACK
+ if (cgs.gametype == GT_1FCTF)
+ CG_AddBufferedSound( cgs.media.yourTeamTookTheFlagSound );
+ else
+#endif
+ CG_AddBufferedSound( cgs.media.enemyTookYourFlagSound );
+ }
+ else if (cgs.clientinfo[cg.clientNum].team == TEAM_RED) {
+#ifdef MISSIONPACK
+ if (cgs.gametype == GT_1FCTF)
+ CG_AddBufferedSound( cgs.media.enemyTookTheFlagSound );
+ else
+#endif
+ CG_AddBufferedSound( cgs.media.yourTeamTookEnemyFlagSound );
+ }
+ }
+ break;
+ case GTS_BLUE_TAKEN: // CTF: blue team took the red flag, 1FCTF red team took the neutral flag
+ // if this player picked up the flag then a sound is played in CG_CheckLocalSounds
+ if (cg.snap->ps.powerups[PW_REDFLAG] || cg.snap->ps.powerups[PW_NEUTRALFLAG]) {
+ }
+ else {
+ if (cgs.clientinfo[cg.clientNum].team == TEAM_RED) {
+#ifdef MISSIONPACK
+ if (cgs.gametype == GT_1FCTF)
+ CG_AddBufferedSound( cgs.media.yourTeamTookTheFlagSound );
+ else
+#endif
+ CG_AddBufferedSound( cgs.media.enemyTookYourFlagSound );
+ }
+ else if (cgs.clientinfo[cg.clientNum].team == TEAM_BLUE) {
+#ifdef MISSIONPACK
+ if (cgs.gametype == GT_1FCTF)
+ CG_AddBufferedSound( cgs.media.enemyTookTheFlagSound );
+ else
+#endif
+ CG_AddBufferedSound( cgs.media.yourTeamTookEnemyFlagSound );
+ }
+ }
+ break;
+ case GTS_REDOBELISK_ATTACKED: // Overload: red obelisk is being attacked
+ if (cgs.clientinfo[cg.clientNum].team == TEAM_RED) {
+ CG_AddBufferedSound( cgs.media.yourBaseIsUnderAttackSound );
+ }
+ break;
+ case GTS_BLUEOBELISK_ATTACKED: // Overload: blue obelisk is being attacked
+ if (cgs.clientinfo[cg.clientNum].team == TEAM_BLUE) {
+ CG_AddBufferedSound( cgs.media.yourBaseIsUnderAttackSound );
+ }
+ break;
+
+ case GTS_REDTEAM_SCORED:
+ CG_AddBufferedSound(cgs.media.redScoredSound);
+ break;
+ case GTS_BLUETEAM_SCORED:
+ CG_AddBufferedSound(cgs.media.blueScoredSound);
+ break;
+ case GTS_REDTEAM_TOOK_LEAD:
+ CG_AddBufferedSound(cgs.media.redLeadsSound);
+ break;
+ case GTS_BLUETEAM_TOOK_LEAD:
+ CG_AddBufferedSound(cgs.media.blueLeadsSound);
+ break;
+ case GTS_TEAMS_ARE_TIED:
+ CG_AddBufferedSound( cgs.media.teamsTiedSound );
+ break;
+#ifdef MISSIONPACK
+ case GTS_KAMIKAZE:
+ trap_S_StartLocalSound(cgs.media.kamikazeFarSound, CHAN_ANNOUNCER);
+ break;
+#endif
+ default:
+ break;
+ }
+ break;
+ }
+
+ case EV_PAIN:
+ // local player sounds are triggered in CG_CheckLocalSounds,
+ // so ignore events on the player
+ DEBUGNAME("EV_PAIN");
+ if ( cent->currentState.number != cg.snap->ps.clientNum ) {
+ CG_PainEvent( cent, es->eventParm );
+ }
+ break;
+
+ case EV_DEATH1:
+ case EV_DEATH2:
+ case EV_DEATH3:
+ DEBUGNAME("EV_DEATHx");
+ trap_S_StartSound( NULL, es->number, CHAN_VOICE,
+ CG_CustomSound( es->number, va("*death%i.wav", event - EV_DEATH1 + 1) ) );
+ break;
+
+
+ case EV_OBITUARY:
+ DEBUGNAME("EV_OBITUARY");
+ CG_Obituary( es );
+ break;
+
+ //
+ // powerup events
+ //
+ case EV_POWERUP_QUAD:
+ DEBUGNAME("EV_POWERUP_QUAD");
+ if ( es->number == cg.snap->ps.clientNum ) {
+ cg.powerupActive = PW_QUAD;
+ cg.powerupTime = cg.time;
+ }
+ trap_S_StartSound (NULL, es->number, CHAN_ITEM, cgs.media.quadSound );
+ break;
+ case EV_POWERUP_BATTLESUIT:
+ DEBUGNAME("EV_POWERUP_BATTLESUIT");
+ if ( es->number == cg.snap->ps.clientNum ) {
+ cg.powerupActive = PW_BATTLESUIT;
+ cg.powerupTime = cg.time;
+ }
+ trap_S_StartSound (NULL, es->number, CHAN_ITEM, cgs.media.protectSound );
+ break;
+ case EV_POWERUP_REGEN:
+ DEBUGNAME("EV_POWERUP_REGEN");
+ if ( es->number == cg.snap->ps.clientNum ) {
+ cg.powerupActive = PW_REGEN;
+ cg.powerupTime = cg.time;
+ }
+ trap_S_StartSound (NULL, es->number, CHAN_ITEM, cgs.media.regenSound );
+ break;
+
+ case EV_GIB_PLAYER:
+ DEBUGNAME("EV_GIB_PLAYER");
+ // don't play gib sound when using the kamikaze because it interferes
+ // with the kamikaze sound, downside is that the gib sound will also
+ // not be played when someone is gibbed while just carrying the kamikaze
+ if ( !(es->eFlags & EF_KAMIKAZE) ) {
+ trap_S_StartSound( NULL, es->number, CHAN_BODY, cgs.media.gibSound );
+ }
+ CG_GibPlayer( cent->lerpOrigin );
+ break;
+
+ case EV_STOPLOOPINGSOUND:
+ DEBUGNAME("EV_STOPLOOPINGSOUND");
+ trap_S_StopLoopingSound( es->number );
+ es->loopSound = 0;
+ break;
+
+ case EV_DEBUG_LINE:
+ DEBUGNAME("EV_DEBUG_LINE");
+ CG_Beam( cent );
+ break;
+
+ default:
+ DEBUGNAME("UNKNOWN");
+ CG_Error( "Unknown event: %i", event );
+ break;
+ }
+
+}
+
+
+/*
+==============
+CG_CheckEvents
+
+==============
+*/
+void CG_CheckEvents( centity_t *cent ) {
+ // check for event-only entities
+ if ( cent->currentState.eType > ET_EVENTS ) {
+ if ( cent->previousEvent ) {
+ return; // already fired
+ }
+ // if this is a player event set the entity number of the client entity number
+ if ( cent->currentState.eFlags & EF_PLAYER_EVENT ) {
+ cent->currentState.number = cent->currentState.otherEntityNum;
+ }
+
+ cent->previousEvent = 1;
+
+ cent->currentState.event = cent->currentState.eType - ET_EVENTS;
+ } else {
+ // check for events riding with another entity
+ if ( cent->currentState.event == cent->previousEvent ) {
+ return;
+ }
+ cent->previousEvent = cent->currentState.event;
+ if ( ( cent->currentState.event & ~EV_EVENT_BITS ) == 0 ) {
+ return;
+ }
+ }
+
+ // calculate the position at exactly the frame time
+ BG_EvaluateTrajectory( &cent->currentState.pos, cg.snap->serverTime, cent->lerpOrigin );
+ CG_SetEntitySoundPosition( cent );
+
+ CG_EntityEvent( cent, cent->lerpOrigin );
+}
+
diff --git a/code/cgame/cg_info.c b/code/cgame/cg_info.c
new file mode 100755
index 0000000..04124d1
--- /dev/null
+++ b/code/cgame/cg_info.c
@@ -0,0 +1,297 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// cg_info.c -- display information while data is being loading
+
+#include "cg_local.h"
+
+#define MAX_LOADING_PLAYER_ICONS 16
+#define MAX_LOADING_ITEM_ICONS 26
+
+static int loadingPlayerIconCount;
+static int loadingItemIconCount;
+static qhandle_t loadingPlayerIcons[MAX_LOADING_PLAYER_ICONS];
+static qhandle_t loadingItemIcons[MAX_LOADING_ITEM_ICONS];
+
+
+/*
+===================
+CG_DrawLoadingIcons
+===================
+*/
+static void CG_DrawLoadingIcons( void ) {
+ int n;
+ int x, y;
+
+ for( n = 0; n < loadingPlayerIconCount; n++ ) {
+ x = 16 + n * 78;
+ y = 324-40;
+ CG_DrawPic( x, y, 64, 64, loadingPlayerIcons[n] );
+ }
+
+ for( n = 0; n < loadingItemIconCount; n++ ) {
+ y = 400-40;
+ if( n >= 13 ) {
+ y += 40;
+ }
+ x = 16 + n % 13 * 48;
+ CG_DrawPic( x, y, 32, 32, loadingItemIcons[n] );
+ }
+}
+
+
+/*
+======================
+CG_LoadingString
+
+======================
+*/
+void CG_LoadingString( const char *s ) {
+ Q_strncpyz( cg.infoScreenText, s, sizeof( cg.infoScreenText ) );
+
+ trap_UpdateScreen();
+}
+
+/*
+===================
+CG_LoadingItem
+===================
+*/
+void CG_LoadingItem( int itemNum ) {
+ gitem_t *item;
+
+ item = &bg_itemlist[itemNum];
+
+ if ( item->icon && loadingItemIconCount < MAX_LOADING_ITEM_ICONS ) {
+ loadingItemIcons[loadingItemIconCount++] = trap_R_RegisterShaderNoMip( item->icon );
+ }
+
+ CG_LoadingString( item->pickup_name );
+}
+
+/*
+===================
+CG_LoadingClient
+===================
+*/
+void CG_LoadingClient( int clientNum ) {
+ const char *info;
+ char *skin;
+ char personality[MAX_QPATH];
+ char model[MAX_QPATH];
+ char iconName[MAX_QPATH];
+
+ info = CG_ConfigString( CS_PLAYERS + clientNum );
+
+ if ( loadingPlayerIconCount < MAX_LOADING_PLAYER_ICONS ) {
+ Q_strncpyz( model, Info_ValueForKey( info, "model" ), sizeof( model ) );
+ skin = Q_strrchr( model, '/' );
+ if ( skin ) {
+ *skin++ = '\0';
+ } else {
+ skin = "default";
+ }
+
+ Com_sprintf( iconName, MAX_QPATH, "models/players/%s/icon_%s.tga", model, skin );
+
+ loadingPlayerIcons[loadingPlayerIconCount] = trap_R_RegisterShaderNoMip( iconName );
+ if ( !loadingPlayerIcons[loadingPlayerIconCount] ) {
+ Com_sprintf( iconName, MAX_QPATH, "models/players/characters/%s/icon_%s.tga", model, skin );
+ loadingPlayerIcons[loadingPlayerIconCount] = trap_R_RegisterShaderNoMip( iconName );
+ }
+ if ( !loadingPlayerIcons[loadingPlayerIconCount] ) {
+ Com_sprintf( iconName, MAX_QPATH, "models/players/%s/icon_%s.tga", DEFAULT_MODEL, "default" );
+ loadingPlayerIcons[loadingPlayerIconCount] = trap_R_RegisterShaderNoMip( iconName );
+ }
+ if ( loadingPlayerIcons[loadingPlayerIconCount] ) {
+ loadingPlayerIconCount++;
+ }
+ }
+
+ Q_strncpyz( personality, Info_ValueForKey( info, "n" ), sizeof(personality) );
+ Q_CleanStr( personality );
+
+ if( cgs.gametype == GT_SINGLE_PLAYER ) {
+ trap_S_RegisterSound( va( "sound/player/announce/%s.wav", personality ), qtrue );
+ }
+
+ CG_LoadingString( personality );
+}
+
+
+/*
+====================
+CG_DrawInformation
+
+Draw all the status / pacifier stuff during level loading
+====================
+*/
+void CG_DrawInformation( void ) {
+ const char *s;
+ const char *info;
+ const char *sysInfo;
+ int y;
+ int value;
+ qhandle_t levelshot;
+ qhandle_t detail;
+ char buf[1024];
+
+ info = CG_ConfigString( CS_SERVERINFO );
+ sysInfo = CG_ConfigString( CS_SYSTEMINFO );
+
+ s = Info_ValueForKey( info, "mapname" );
+ levelshot = trap_R_RegisterShaderNoMip( va( "levelshots/%s.tga", s ) );
+ if ( !levelshot ) {
+ levelshot = trap_R_RegisterShaderNoMip( "menu/art/unknownmap" );
+ }
+ trap_R_SetColor( NULL );
+ CG_DrawPic( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, levelshot );
+
+ // blend a detail texture over it
+ detail = trap_R_RegisterShader( "levelShotDetail" );
+ trap_R_DrawStretchPic( 0, 0, cgs.glconfig.vidWidth, cgs.glconfig.vidHeight, 0, 0, 2.5, 2, detail );
+
+ // draw the icons of things as they are loaded
+ CG_DrawLoadingIcons();
+
+ // the first 150 rows are reserved for the client connection
+ // screen to write into
+ if ( cg.infoScreenText[0] ) {
+ UI_DrawProportionalString( 320, 128-32, va("Loading... %s", cg.infoScreenText),
+ UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, colorWhite );
+ } else {
+ UI_DrawProportionalString( 320, 128-32, "Awaiting snapshot...",
+ UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, colorWhite );
+ }
+
+ // draw info string information
+
+ y = 180-32;
+
+ // don't print server lines if playing a local game
+ trap_Cvar_VariableStringBuffer( "sv_running", buf, sizeof( buf ) );
+ if ( !atoi( buf ) ) {
+ // server hostname
+ Q_strncpyz(buf, Info_ValueForKey( info, "sv_hostname" ), 1024);
+ Q_CleanStr(buf);
+ UI_DrawProportionalString( 320, y, buf,
+ UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, colorWhite );
+ y += PROP_HEIGHT;
+
+ // pure server
+ s = Info_ValueForKey( sysInfo, "sv_pure" );
+ if ( s[0] == '1' ) {
+ UI_DrawProportionalString( 320, y, "Pure Server",
+ UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, colorWhite );
+ y += PROP_HEIGHT;
+ }
+
+ // server-specific message of the day
+ s = CG_ConfigString( CS_MOTD );
+ if ( s[0] ) {
+ UI_DrawProportionalString( 320, y, s,
+ UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, colorWhite );
+ y += PROP_HEIGHT;
+ }
+
+ // some extra space after hostname and motd
+ y += 10;
+ }
+
+ // map-specific message (long map name)
+ s = CG_ConfigString( CS_MESSAGE );
+ if ( s[0] ) {
+ UI_DrawProportionalString( 320, y, s,
+ UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, colorWhite );
+ y += PROP_HEIGHT;
+ }
+
+ // cheats warning
+ s = Info_ValueForKey( sysInfo, "sv_cheats" );
+ if ( s[0] == '1' ) {
+ UI_DrawProportionalString( 320, y, "CHEATS ARE ENABLED",
+ UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, colorWhite );
+ y += PROP_HEIGHT;
+ }
+
+ // game type
+ switch ( cgs.gametype ) {
+ case GT_FFA:
+ s = "Free For All";
+ break;
+ case GT_SINGLE_PLAYER:
+ s = "Single Player";
+ break;
+ case GT_TOURNAMENT:
+ s = "Tournament";
+ break;
+ case GT_TEAM:
+ s = "Team Deathmatch";
+ break;
+ case GT_CTF:
+ s = "Capture The Flag";
+ break;
+#ifdef MISSIONPACK
+ case GT_1FCTF:
+ s = "One Flag CTF";
+ break;
+ case GT_OBELISK:
+ s = "Overload";
+ break;
+ case GT_HARVESTER:
+ s = "Harvester";
+ break;
+#endif
+ default:
+ s = "Unknown Gametype";
+ break;
+ }
+ UI_DrawProportionalString( 320, y, s,
+ UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, colorWhite );
+ y += PROP_HEIGHT;
+
+ value = atoi( Info_ValueForKey( info, "timelimit" ) );
+ if ( value ) {
+ UI_DrawProportionalString( 320, y, va( "timelimit %i", value ),
+ UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, colorWhite );
+ y += PROP_HEIGHT;
+ }
+
+ if (cgs.gametype < GT_CTF ) {
+ value = atoi( Info_ValueForKey( info, "fraglimit" ) );
+ if ( value ) {
+ UI_DrawProportionalString( 320, y, va( "fraglimit %i", value ),
+ UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, colorWhite );
+ y += PROP_HEIGHT;
+ }
+ }
+
+ if (cgs.gametype >= GT_CTF) {
+ value = atoi( Info_ValueForKey( info, "capturelimit" ) );
+ if ( value ) {
+ UI_DrawProportionalString( 320, y, va( "capturelimit %i", value ),
+ UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, colorWhite );
+ y += PROP_HEIGHT;
+ }
+ }
+}
+
diff --git a/code/cgame/cg_local.h b/code/cgame/cg_local.h
new file mode 100755
index 0000000..4dd5c9d
--- /dev/null
+++ b/code/cgame/cg_local.h
@@ -0,0 +1,1669 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#include "../game/q_shared.h"
+#include "tr_types.h"
+#include "../game/bg_public.h"
+#include "cg_public.h"
+
+
+// The entire cgame module is unloaded and reloaded on each level change,
+// so there is NO persistant data between levels on the client side.
+// If you absolutely need something stored, it can either be kept
+// by the server in the server stored userinfos, or stashed in a cvar.
+
+#ifdef MISSIONPACK
+#define CG_FONT_THRESHOLD 0.1
+#endif
+
+#define POWERUP_BLINKS 5
+
+#define POWERUP_BLINK_TIME 1000
+#define FADE_TIME 200
+#define PULSE_TIME 200
+#define DAMAGE_DEFLECT_TIME 100
+#define DAMAGE_RETURN_TIME 400
+#define DAMAGE_TIME 500
+#define LAND_DEFLECT_TIME 150
+#define LAND_RETURN_TIME 300
+#define STEP_TIME 200
+#define DUCK_TIME 100
+#define PAIN_TWITCH_TIME 200
+#define WEAPON_SELECT_TIME 1400
+#define ITEM_SCALEUP_TIME 1000
+#define ZOOM_TIME 150
+#define ITEM_BLOB_TIME 200
+#define MUZZLE_FLASH_TIME 20
+#define SINK_TIME 1000 // time for fragments to sink into ground before going away
+#define ATTACKER_HEAD_TIME 10000
+#define REWARD_TIME 3000
+
+#define PULSE_SCALE 1.5 // amount to scale up the icons when activating
+
+#define MAX_STEP_CHANGE 32
+
+#define MAX_VERTS_ON_POLY 10
+#define MAX_MARK_POLYS 256
+
+#define STAT_MINUS 10 // num frame for '-' stats digit
+
+#define ICON_SIZE 48
+#define CHAR_WIDTH 32
+#define CHAR_HEIGHT 48
+#define TEXT_ICON_SPACE 4
+
+#define TEAMCHAT_WIDTH 80
+#define TEAMCHAT_HEIGHT 8
+
+// very large characters
+#define GIANT_WIDTH 32
+#define GIANT_HEIGHT 48
+
+#define NUM_CROSSHAIRS 10
+
+#define TEAM_OVERLAY_MAXNAME_WIDTH 12
+#define TEAM_OVERLAY_MAXLOCATION_WIDTH 16
+
+#define DEFAULT_MODEL "sarge"
+#ifdef MISSIONPACK
+#define DEFAULT_TEAM_MODEL "james"
+#define DEFAULT_TEAM_HEAD "*james"
+#else
+#define DEFAULT_TEAM_MODEL "sarge"
+#define DEFAULT_TEAM_HEAD "sarge"
+#endif
+
+#define DEFAULT_REDTEAM_NAME "Stroggs"
+#define DEFAULT_BLUETEAM_NAME "Pagans"
+
+typedef enum {
+ FOOTSTEP_NORMAL,
+ FOOTSTEP_BOOT,
+ FOOTSTEP_FLESH,
+ FOOTSTEP_MECH,
+ FOOTSTEP_ENERGY,
+ FOOTSTEP_METAL,
+ FOOTSTEP_SPLASH,
+
+ FOOTSTEP_TOTAL
+} footstep_t;
+
+typedef enum {
+ IMPACTSOUND_DEFAULT,
+ IMPACTSOUND_METAL,
+ IMPACTSOUND_FLESH
+} impactSound_t;
+
+//=================================================
+
+// player entities need to track more information
+// than any other type of entity.
+
+// note that not every player entity is a client entity,
+// because corpses after respawn are outside the normal
+// client numbering range
+
+// when changing animation, set animationTime to frameTime + lerping time
+// The current lerp will finish out, then it will lerp to the new animation
+typedef struct {
+ int oldFrame;
+ int oldFrameTime; // time when ->oldFrame was exactly on
+
+ int frame;
+ int frameTime; // time when ->frame will be exactly on
+
+ float backlerp;
+
+ float yawAngle;
+ qboolean yawing;
+ float pitchAngle;
+ qboolean pitching;
+
+ int animationNumber; // may include ANIM_TOGGLEBIT
+ animation_t *animation;
+ int animationTime; // time when the first frame of the animation will be exact
+} lerpFrame_t;
+
+
+typedef struct {
+ lerpFrame_t legs, torso, flag;
+ int painTime;
+ int painDirection; // flip from 0 to 1
+ int lightningFiring;
+
+ // railgun trail spawning
+ vec3_t railgunImpact;
+ qboolean railgunFlash;
+
+ // machinegun spinning
+ float barrelAngle;
+ int barrelTime;
+ qboolean barrelSpinning;
+} playerEntity_t;
+
+//=================================================
+
+
+
+// centity_t have a direct corespondence with gentity_t in the game, but
+// only the entityState_t is directly communicated to the cgame
+typedef struct centity_s {
+ entityState_t currentState; // from cg.frame
+ entityState_t nextState; // from cg.nextFrame, if available
+ qboolean interpolate; // true if next is valid to interpolate to
+ qboolean currentValid; // true if cg.frame holds this entity
+
+ int muzzleFlashTime; // move to playerEntity?
+ int previousEvent;
+ int teleportFlag;
+
+ int trailTime; // so missile trails can handle dropped initial packets
+ int dustTrailTime;
+ int miscTime;
+
+ int snapShotTime; // last time this entity was found in a snapshot
+
+ playerEntity_t pe;
+
+ int errorTime; // decay the error from this time
+ vec3_t errorOrigin;
+ vec3_t errorAngles;
+
+ qboolean extrapolated; // false if origin / angles is an interpolation
+ vec3_t rawOrigin;
+ vec3_t rawAngles;
+
+ vec3_t beamEnd;
+
+ // exact interpolated position of entity on this frame
+ vec3_t lerpOrigin;
+ vec3_t lerpAngles;
+} centity_t;
+
+
+//======================================================================
+
+// local entities are created as a result of events or predicted actions,
+// and live independantly from all server transmitted entities
+
+typedef struct markPoly_s {
+ struct markPoly_s *prevMark, *nextMark;
+ int time;
+ qhandle_t markShader;
+ qboolean alphaFade; // fade alpha instead of rgb
+ float color[4];
+ poly_t poly;
+ polyVert_t verts[MAX_VERTS_ON_POLY];
+} markPoly_t;
+
+
+typedef enum {
+ LE_MARK,
+ LE_EXPLOSION,
+ LE_SPRITE_EXPLOSION,
+ LE_FRAGMENT,
+ LE_MOVE_SCALE_FADE,
+ LE_FALL_SCALE_FADE,
+ LE_FADE_RGB,
+ LE_SCALE_FADE,
+ LE_SCOREPLUM,
+#ifdef MISSIONPACK
+ LE_KAMIKAZE,
+ LE_INVULIMPACT,
+ LE_INVULJUICED,
+ LE_SHOWREFENTITY
+#endif
+} leType_t;
+
+typedef enum {
+ LEF_PUFF_DONT_SCALE = 0x0001, // do not scale size over time
+ LEF_TUMBLE = 0x0002, // tumble over time, used for ejecting shells
+ LEF_SOUND1 = 0x0004, // sound 1 for kamikaze
+ LEF_SOUND2 = 0x0008 // sound 2 for kamikaze
+} leFlag_t;
+
+typedef enum {
+ LEMT_NONE,
+ LEMT_BURN,
+ LEMT_BLOOD
+} leMarkType_t; // fragment local entities can leave marks on walls
+
+typedef enum {
+ LEBS_NONE,
+ LEBS_BLOOD,
+ LEBS_BRASS
+} leBounceSoundType_t; // fragment local entities can make sounds on impacts
+
+typedef struct localEntity_s {
+ struct localEntity_s *prev, *next;
+ leType_t leType;
+ int leFlags;
+
+ int startTime;
+ int endTime;
+ int fadeInTime;
+
+ float lifeRate; // 1.0 / (endTime - startTime)
+
+ trajectory_t pos;
+ trajectory_t angles;
+
+ float bounceFactor; // 0.0 = no bounce, 1.0 = perfect
+
+ float color[4];
+
+ float radius;
+
+ float light;
+ vec3_t lightColor;
+
+ leMarkType_t leMarkType; // mark to leave on fragment impact
+ leBounceSoundType_t leBounceSoundType;
+
+ refEntity_t refEntity;
+} localEntity_t;
+
+//======================================================================
+
+
+typedef struct {
+ int client;
+ int score;
+ int ping;
+ int time;
+ int scoreFlags;
+ int powerUps;
+ int accuracy;
+ int impressiveCount;
+ int excellentCount;
+ int guantletCount;
+ int defendCount;
+ int assistCount;
+ int captures;
+ qboolean perfect;
+ int team;
+} score_t;
+
+// each client has an associated clientInfo_t
+// that contains media references necessary to present the
+// client model and other color coded effects
+// this is regenerated each time a client's configstring changes,
+// usually as a result of a userinfo (name, model, etc) change
+#define MAX_CUSTOM_SOUNDS 32
+
+typedef struct {
+ qboolean infoValid;
+
+ char name[MAX_QPATH];
+ team_t team;
+
+ int botSkill; // 0 = not bot, 1-5 = bot
+
+ vec3_t color1;
+ vec3_t color2;
+
+ int score; // updated by score servercmds
+ int location; // location index for team mode
+ int health; // you only get this info about your teammates
+ int armor;
+ int curWeapon;
+
+ int handicap;
+ int wins, losses; // in tourney mode
+
+ int teamTask; // task in teamplay (offence/defence)
+ qboolean teamLeader; // true when this is a team leader
+
+ int powerups; // so can display quad/flag status
+
+ int medkitUsageTime;
+ int invulnerabilityStartTime;
+ int invulnerabilityStopTime;
+
+ int breathPuffTime;
+
+ // when clientinfo is changed, the loading of models/skins/sounds
+ // can be deferred until you are dead, to prevent hitches in
+ // gameplay
+ char modelName[MAX_QPATH];
+ char skinName[MAX_QPATH];
+ char headModelName[MAX_QPATH];
+ char headSkinName[MAX_QPATH];
+ char redTeam[MAX_TEAMNAME];
+ char blueTeam[MAX_TEAMNAME];
+ qboolean deferred;
+
+ qboolean newAnims; // true if using the new mission pack animations
+ qboolean fixedlegs; // true if legs yaw is always the same as torso yaw
+ qboolean fixedtorso; // true if torso never changes yaw
+
+ vec3_t headOffset; // move head in icon views
+ footstep_t footsteps;
+ gender_t gender; // from model
+
+ qhandle_t legsModel;
+ qhandle_t legsSkin;
+
+ qhandle_t torsoModel;
+ qhandle_t torsoSkin;
+
+ qhandle_t headModel;
+ qhandle_t headSkin;
+
+ qhandle_t modelIcon;
+
+ animation_t animations[MAX_TOTALANIMATIONS];
+
+ sfxHandle_t sounds[MAX_CUSTOM_SOUNDS];
+} clientInfo_t;
+
+
+// each WP_* weapon enum has an associated weaponInfo_t
+// that contains media references necessary to present the
+// weapon and its effects
+typedef struct weaponInfo_s {
+ qboolean registered;
+ gitem_t *item;
+
+ qhandle_t handsModel; // the hands don't actually draw, they just position the weapon
+ qhandle_t weaponModel;
+ qhandle_t barrelModel;
+ qhandle_t flashModel;
+
+ vec3_t weaponMidpoint; // so it will rotate centered instead of by tag
+
+ float flashDlight;
+ vec3_t flashDlightColor;
+ sfxHandle_t flashSound[4]; // fast firing weapons randomly choose
+
+ qhandle_t weaponIcon;
+ qhandle_t ammoIcon;
+
+ qhandle_t ammoModel;
+
+ qhandle_t missileModel;
+ sfxHandle_t missileSound;
+ void (*missileTrailFunc)( centity_t *, const struct weaponInfo_s *wi );
+ float missileDlight;
+ vec3_t missileDlightColor;
+ int missileRenderfx;
+
+ void (*ejectBrassFunc)( centity_t * );
+
+ float trailRadius;
+ float wiTrailTime;
+
+ sfxHandle_t readySound;
+ sfxHandle_t firingSound;
+ qboolean loopFireSound;
+} weaponInfo_t;
+
+
+// each IT_* item has an associated itemInfo_t
+// that constains media references necessary to present the
+// item and its effects
+typedef struct {
+ qboolean registered;
+ qhandle_t models[MAX_ITEM_MODELS];
+ qhandle_t icon;
+} itemInfo_t;
+
+
+typedef struct {
+ int itemNum;
+} powerupInfo_t;
+
+
+#define MAX_SKULLTRAIL 10
+
+typedef struct {
+ vec3_t positions[MAX_SKULLTRAIL];
+ int numpositions;
+} skulltrail_t;
+
+
+#define MAX_REWARDSTACK 10
+#define MAX_SOUNDBUFFER 20
+
+//======================================================================
+
+// all cg.stepTime, cg.duckTime, cg.landTime, etc are set to cg.time when the action
+// occurs, and they will have visible effects for #define STEP_TIME or whatever msec after
+
+#define MAX_PREDICTED_EVENTS 16
+
+typedef struct {
+ int clientFrame; // incremented each frame
+
+ int clientNum;
+
+ qboolean demoPlayback;
+ qboolean levelShot; // taking a level menu screenshot
+ int deferredPlayerLoading;
+ qboolean loading; // don't defer players at initial startup
+ qboolean intermissionStarted; // don't play voice rewards, because game will end shortly
+
+ // there are only one or two snapshot_t that are relevent at a time
+ int latestSnapshotNum; // the number of snapshots the client system has received
+ int latestSnapshotTime; // the time from latestSnapshotNum, so we don't need to read the snapshot yet
+
+ snapshot_t *snap; // cg.snap->serverTime <= cg.time
+ snapshot_t *nextSnap; // cg.nextSnap->serverTime > cg.time, or NULL
+ snapshot_t activeSnapshots[2];
+
+ float frameInterpolation; // (float)( cg.time - cg.frame->serverTime ) / (cg.nextFrame->serverTime - cg.frame->serverTime)
+
+ qboolean thisFrameTeleport;
+ qboolean nextFrameTeleport;
+
+ int frametime; // cg.time - cg.oldTime
+
+ int time; // this is the time value that the client
+ // is rendering at.
+ int oldTime; // time at last frame, used for missile trails and prediction checking
+
+ int physicsTime; // either cg.snap->time or cg.nextSnap->time
+
+ int timelimitWarnings; // 5 min, 1 min, overtime
+ int fraglimitWarnings;
+
+ qboolean mapRestart; // set on a map restart to set back the weapon
+
+ qboolean renderingThirdPerson; // during deaths, chasecams, etc
+
+ // prediction state
+ qboolean hyperspace; // true if prediction has hit a trigger_teleport
+ playerState_t predictedPlayerState;
+ centity_t predictedPlayerEntity;
+ qboolean validPPS; // clear until the first call to CG_PredictPlayerState
+ int predictedErrorTime;
+ vec3_t predictedError;
+
+ int eventSequence;
+ int predictableEvents[MAX_PREDICTED_EVENTS];
+
+ float stepChange; // for stair up smoothing
+ int stepTime;
+
+ float duckChange; // for duck viewheight smoothing
+ int duckTime;
+
+ float landChange; // for landing hard
+ int landTime;
+
+ // input state sent to server
+ int weaponSelect;
+
+ // auto rotating items
+ vec3_t autoAngles;
+ vec3_t autoAxis[3];
+ vec3_t autoAnglesFast;
+ vec3_t autoAxisFast[3];
+
+ // view rendering
+ refdef_t refdef;
+ vec3_t refdefViewAngles; // will be converted to refdef.viewaxis
+
+ // zoom key
+ qboolean zoomed;
+ int zoomTime;
+ float zoomSensitivity;
+
+ // information screen text during loading
+ char infoScreenText[MAX_STRING_CHARS];
+
+ // scoreboard
+ int scoresRequestTime;
+ int numScores;
+ int selectedScore;
+ int teamScores[2];
+ score_t scores[MAX_CLIENTS];
+ qboolean showScores;
+ qboolean scoreBoardShowing;
+ int scoreFadeTime;
+ char killerName[MAX_NAME_LENGTH];
+ char spectatorList[MAX_STRING_CHARS]; // list of names
+ int spectatorLen; // length of list
+ float spectatorWidth; // width in device units
+ int spectatorTime; // next time to offset
+ int spectatorPaintX; // current paint x
+ int spectatorPaintX2; // current paint x
+ int spectatorOffset; // current offset from start
+ int spectatorPaintLen; // current offset from start
+
+ // skull trails
+ skulltrail_t skulltrails[MAX_CLIENTS];
+
+ // centerprinting
+ int centerPrintTime;
+ int centerPrintCharWidth;
+ int centerPrintY;
+ char centerPrint[1024];
+ int centerPrintLines;
+
+ // low ammo warning state
+ int lowAmmoWarning; // 1 = low, 2 = empty
+
+ // kill timers for carnage reward
+ int lastKillTime;
+
+ // crosshair client ID
+ int crosshairClientNum;
+ int crosshairClientTime;
+
+ // powerup active flashing
+ int powerupActive;
+ int powerupTime;
+
+ // attacking player
+ int attackerTime;
+ int voiceTime;
+
+ // reward medals
+ int rewardStack;
+ int rewardTime;
+ int rewardCount[MAX_REWARDSTACK];
+ qhandle_t rewardShader[MAX_REWARDSTACK];
+ qhandle_t rewardSound[MAX_REWARDSTACK];
+
+ // sound buffer mainly for announcer sounds
+ int soundBufferIn;
+ int soundBufferOut;
+ int soundTime;
+ qhandle_t soundBuffer[MAX_SOUNDBUFFER];
+
+ // for voice chat buffer
+ int voiceChatTime;
+ int voiceChatBufferIn;
+ int voiceChatBufferOut;
+
+ // warmup countdown
+ int warmup;
+ int warmupCount;
+
+ //==========================
+
+ int itemPickup;
+ int itemPickupTime;
+ int itemPickupBlendTime; // the pulse around the crosshair is timed seperately
+
+ int weaponSelectTime;
+ int weaponAnimation;
+ int weaponAnimationTime;
+
+ // blend blobs
+ float damageTime;
+ float damageX, damageY, damageValue;
+
+ // status bar head
+ float headYaw;
+ float headEndPitch;
+ float headEndYaw;
+ int headEndTime;
+ float headStartPitch;
+ float headStartYaw;
+ int headStartTime;
+
+ // view movement
+ float v_dmg_time;
+ float v_dmg_pitch;
+ float v_dmg_roll;
+
+ vec3_t kick_angles; // weapon kicks
+ vec3_t kick_origin;
+
+ // temp working variables for player view
+ float bobfracsin;
+ int bobcycle;
+ float xyspeed;
+ int nextOrbitTime;
+
+ //qboolean cameraMode; // if rendering from a loaded camera
+
+
+ // development tool
+ refEntity_t testModelEntity;
+ char testModelName[MAX_QPATH];
+ qboolean testGun;
+
+} cg_t;
+
+
+// all of the model, shader, and sound references that are
+// loaded at gamestate time are stored in cgMedia_t
+// Other media that can be tied to clients, weapons, or items are
+// stored in the clientInfo_t, itemInfo_t, weaponInfo_t, and powerupInfo_t
+typedef struct {
+ qhandle_t charsetShader;
+ qhandle_t charsetProp;
+ qhandle_t charsetPropGlow;
+ qhandle_t charsetPropB;
+ qhandle_t whiteShader;
+
+ qhandle_t redCubeModel;
+ qhandle_t blueCubeModel;
+ qhandle_t redCubeIcon;
+ qhandle_t blueCubeIcon;
+ qhandle_t redFlagModel;
+ qhandle_t blueFlagModel;
+ qhandle_t neutralFlagModel;
+ qhandle_t redFlagShader[3];
+ qhandle_t blueFlagShader[3];
+ qhandle_t flagShader[4];
+
+ qhandle_t flagPoleModel;
+ qhandle_t flagFlapModel;
+
+ qhandle_t redFlagFlapSkin;
+ qhandle_t blueFlagFlapSkin;
+ qhandle_t neutralFlagFlapSkin;
+
+ qhandle_t redFlagBaseModel;
+ qhandle_t blueFlagBaseModel;
+ qhandle_t neutralFlagBaseModel;
+
+#ifdef MISSIONPACK
+ qhandle_t overloadBaseModel;
+ qhandle_t overloadTargetModel;
+ qhandle_t overloadLightsModel;
+ qhandle_t overloadEnergyModel;
+
+ qhandle_t harvesterModel;
+ qhandle_t harvesterRedSkin;
+ qhandle_t harvesterBlueSkin;
+ qhandle_t harvesterNeutralModel;
+#endif
+
+ qhandle_t armorModel;
+ qhandle_t armorIcon;
+
+ qhandle_t teamStatusBar;
+
+ qhandle_t deferShader;
+
+ // gib explosions
+ qhandle_t gibAbdomen;
+ qhandle_t gibArm;
+ qhandle_t gibChest;
+ qhandle_t gibFist;
+ qhandle_t gibFoot;
+ qhandle_t gibForearm;
+ qhandle_t gibIntestine;
+ qhandle_t gibLeg;
+ qhandle_t gibSkull;
+ qhandle_t gibBrain;
+
+ qhandle_t smoke2;
+
+ qhandle_t machinegunBrassModel;
+ qhandle_t shotgunBrassModel;
+
+ qhandle_t railRingsShader;
+ qhandle_t railCoreShader;
+
+ qhandle_t lightningShader;
+
+ qhandle_t friendShader;
+
+ qhandle_t balloonShader;
+ qhandle_t connectionShader;
+
+ qhandle_t selectShader;
+ qhandle_t viewBloodShader;
+ qhandle_t tracerShader;
+ qhandle_t crosshairShader[NUM_CROSSHAIRS];
+ qhandle_t lagometerShader;
+ qhandle_t backTileShader;
+ qhandle_t noammoShader;
+
+ qhandle_t smokePuffShader;
+ qhandle_t smokePuffRageProShader;
+ qhandle_t shotgunSmokePuffShader;
+ qhandle_t plasmaBallShader;
+ qhandle_t waterBubbleShader;
+ qhandle_t bloodTrailShader;
+#ifdef MISSIONPACK
+ qhandle_t nailPuffShader;
+ qhandle_t blueProxMine;
+#endif
+
+ qhandle_t numberShaders[11];
+
+ qhandle_t shadowMarkShader;
+
+ qhandle_t botSkillShaders[5];
+
+ // wall mark shaders
+ qhandle_t wakeMarkShader;
+ qhandle_t bloodMarkShader;
+ qhandle_t bulletMarkShader;
+ qhandle_t burnMarkShader;
+ qhandle_t holeMarkShader;
+ qhandle_t energyMarkShader;
+
+ // powerup shaders
+ qhandle_t quadShader;
+ qhandle_t redQuadShader;
+ qhandle_t quadWeaponShader;
+ qhandle_t invisShader;
+ qhandle_t regenShader;
+ qhandle_t battleSuitShader;
+ qhandle_t battleWeaponShader;
+ qhandle_t hastePuffShader;
+ qhandle_t redKamikazeShader;
+ qhandle_t blueKamikazeShader;
+
+ // weapon effect models
+ qhandle_t bulletFlashModel;
+ qhandle_t ringFlashModel;
+ qhandle_t dishFlashModel;
+ qhandle_t lightningExplosionModel;
+
+ // weapon effect shaders
+ qhandle_t railExplosionShader;
+ qhandle_t plasmaExplosionShader;
+ qhandle_t bulletExplosionShader;
+ qhandle_t rocketExplosionShader;
+ qhandle_t grenadeExplosionShader;
+ qhandle_t bfgExplosionShader;
+ qhandle_t bloodExplosionShader;
+
+ // special effects models
+ qhandle_t teleportEffectModel;
+ qhandle_t teleportEffectShader;
+#ifdef MISSIONPACK
+ qhandle_t kamikazeEffectModel;
+ qhandle_t kamikazeShockWave;
+ qhandle_t kamikazeHeadModel;
+ qhandle_t kamikazeHeadTrail;
+ qhandle_t guardPowerupModel;
+ qhandle_t scoutPowerupModel;
+ qhandle_t doublerPowerupModel;
+ qhandle_t ammoRegenPowerupModel;
+ qhandle_t invulnerabilityImpactModel;
+ qhandle_t invulnerabilityJuicedModel;
+ qhandle_t medkitUsageModel;
+ qhandle_t dustPuffShader;
+ qhandle_t heartShader;
+#endif
+ qhandle_t invulnerabilityPowerupModel;
+
+ // scoreboard headers
+ qhandle_t scoreboardName;
+ qhandle_t scoreboardPing;
+ qhandle_t scoreboardScore;
+ qhandle_t scoreboardTime;
+
+ // medals shown during gameplay
+ qhandle_t medalImpressive;
+ qhandle_t medalExcellent;
+ qhandle_t medalGauntlet;
+ qhandle_t medalDefend;
+ qhandle_t medalAssist;
+ qhandle_t medalCapture;
+
+ // sounds
+ sfxHandle_t quadSound;
+ sfxHandle_t tracerSound;
+ sfxHandle_t selectSound;
+ sfxHandle_t useNothingSound;
+ sfxHandle_t wearOffSound;
+ sfxHandle_t footsteps[FOOTSTEP_TOTAL][4];
+ sfxHandle_t sfx_lghit1;
+ sfxHandle_t sfx_lghit2;
+ sfxHandle_t sfx_lghit3;
+ sfxHandle_t sfx_ric1;
+ sfxHandle_t sfx_ric2;
+ sfxHandle_t sfx_ric3;
+ sfxHandle_t sfx_railg;
+ sfxHandle_t sfx_rockexp;
+ sfxHandle_t sfx_plasmaexp;
+#ifdef MISSIONPACK
+ sfxHandle_t sfx_proxexp;
+ sfxHandle_t sfx_nghit;
+ sfxHandle_t sfx_nghitflesh;
+ sfxHandle_t sfx_nghitmetal;
+ sfxHandle_t sfx_chghit;
+ sfxHandle_t sfx_chghitflesh;
+ sfxHandle_t sfx_chghitmetal;
+ sfxHandle_t kamikazeExplodeSound;
+ sfxHandle_t kamikazeImplodeSound;
+ sfxHandle_t kamikazeFarSound;
+ sfxHandle_t useInvulnerabilitySound;
+ sfxHandle_t invulnerabilityImpactSound1;
+ sfxHandle_t invulnerabilityImpactSound2;
+ sfxHandle_t invulnerabilityImpactSound3;
+ sfxHandle_t invulnerabilityJuicedSound;
+ sfxHandle_t obeliskHitSound1;
+ sfxHandle_t obeliskHitSound2;
+ sfxHandle_t obeliskHitSound3;
+ sfxHandle_t obeliskRespawnSound;
+ sfxHandle_t winnerSound;
+ sfxHandle_t loserSound;
+ sfxHandle_t youSuckSound;
+#endif
+ sfxHandle_t gibSound;
+ sfxHandle_t gibBounce1Sound;
+ sfxHandle_t gibBounce2Sound;
+ sfxHandle_t gibBounce3Sound;
+ sfxHandle_t teleInSound;
+ sfxHandle_t teleOutSound;
+ sfxHandle_t noAmmoSound;
+ sfxHandle_t respawnSound;
+ sfxHandle_t talkSound;
+ sfxHandle_t landSound;
+ sfxHandle_t fallSound;
+ sfxHandle_t jumpPadSound;
+
+ sfxHandle_t oneMinuteSound;
+ sfxHandle_t fiveMinuteSound;
+ sfxHandle_t suddenDeathSound;
+
+ sfxHandle_t threeFragSound;
+ sfxHandle_t twoFragSound;
+ sfxHandle_t oneFragSound;
+
+ sfxHandle_t hitSound;
+ sfxHandle_t hitSoundHighArmor;
+ sfxHandle_t hitSoundLowArmor;
+ sfxHandle_t hitTeamSound;
+ sfxHandle_t impressiveSound;
+ sfxHandle_t excellentSound;
+ sfxHandle_t deniedSound;
+ sfxHandle_t humiliationSound;
+ sfxHandle_t assistSound;
+ sfxHandle_t defendSound;
+ sfxHandle_t firstImpressiveSound;
+ sfxHandle_t firstExcellentSound;
+ sfxHandle_t firstHumiliationSound;
+
+ sfxHandle_t takenLeadSound;
+ sfxHandle_t tiedLeadSound;
+ sfxHandle_t lostLeadSound;
+
+ sfxHandle_t voteNow;
+ sfxHandle_t votePassed;
+ sfxHandle_t voteFailed;
+
+ sfxHandle_t watrInSound;
+ sfxHandle_t watrOutSound;
+ sfxHandle_t watrUnSound;
+
+ sfxHandle_t flightSound;
+ sfxHandle_t medkitSound;
+
+ sfxHandle_t weaponHoverSound;
+
+ // teamplay sounds
+ sfxHandle_t captureAwardSound;
+ sfxHandle_t redScoredSound;
+ sfxHandle_t blueScoredSound;
+ sfxHandle_t redLeadsSound;
+ sfxHandle_t blueLeadsSound;
+ sfxHandle_t teamsTiedSound;
+
+ sfxHandle_t captureYourTeamSound;
+ sfxHandle_t captureOpponentSound;
+ sfxHandle_t returnYourTeamSound;
+ sfxHandle_t returnOpponentSound;
+ sfxHandle_t takenYourTeamSound;
+ sfxHandle_t takenOpponentSound;
+
+ sfxHandle_t redFlagReturnedSound;
+ sfxHandle_t blueFlagReturnedSound;
+ sfxHandle_t neutralFlagReturnedSound;
+ sfxHandle_t enemyTookYourFlagSound;
+ sfxHandle_t enemyTookTheFlagSound;
+ sfxHandle_t yourTeamTookEnemyFlagSound;
+ sfxHandle_t yourTeamTookTheFlagSound;
+ sfxHandle_t youHaveFlagSound;
+ sfxHandle_t yourBaseIsUnderAttackSound;
+ sfxHandle_t holyShitSound;
+
+ // tournament sounds
+ sfxHandle_t count3Sound;
+ sfxHandle_t count2Sound;
+ sfxHandle_t count1Sound;
+ sfxHandle_t countFightSound;
+ sfxHandle_t countPrepareSound;
+
+#ifdef MISSIONPACK
+ // new stuff
+ qhandle_t patrolShader;
+ qhandle_t assaultShader;
+ qhandle_t campShader;
+ qhandle_t followShader;
+ qhandle_t defendShader;
+ qhandle_t teamLeaderShader;
+ qhandle_t retrieveShader;
+ qhandle_t escortShader;
+ qhandle_t flagShaders[3];
+ sfxHandle_t countPrepareTeamSound;
+
+ sfxHandle_t ammoregenSound;
+ sfxHandle_t doublerSound;
+ sfxHandle_t guardSound;
+ sfxHandle_t scoutSound;
+#endif
+ qhandle_t cursor;
+ qhandle_t selectCursor;
+ qhandle_t sizeCursor;
+
+ sfxHandle_t regenSound;
+ sfxHandle_t protectSound;
+ sfxHandle_t n_healthSound;
+ sfxHandle_t hgrenb1aSound;
+ sfxHandle_t hgrenb2aSound;
+ sfxHandle_t wstbimplSound;
+ sfxHandle_t wstbimpmSound;
+ sfxHandle_t wstbimpdSound;
+ sfxHandle_t wstbactvSound;
+
+} cgMedia_t;
+
+
+// The client game static (cgs) structure hold everything
+// loaded or calculated from the gamestate. It will NOT
+// be cleared when a tournement restart is done, allowing
+// all clients to begin playing instantly
+typedef struct {
+ gameState_t gameState; // gamestate from server
+ glconfig_t glconfig; // rendering configuration
+ float screenXScale; // derived from glconfig
+ float screenYScale;
+ float screenXBias;
+
+ int serverCommandSequence; // reliable command stream counter
+ int processedSnapshotNum;// the number of snapshots cgame has requested
+
+ qboolean localServer; // detected on startup by checking sv_running
+
+ // parsed from serverinfo
+ gametype_t gametype;
+ int dmflags;
+ int teamflags;
+ int fraglimit;
+ int capturelimit;
+ int timelimit;
+ int maxclients;
+ char mapname[MAX_QPATH];
+ char redTeam[MAX_QPATH];
+ char blueTeam[MAX_QPATH];
+
+ int voteTime;
+ int voteYes;
+ int voteNo;
+ qboolean voteModified; // beep whenever changed
+ char voteString[MAX_STRING_TOKENS];
+
+ int teamVoteTime[2];
+ int teamVoteYes[2];
+ int teamVoteNo[2];
+ qboolean teamVoteModified[2]; // beep whenever changed
+ char teamVoteString[2][MAX_STRING_TOKENS];
+
+ int levelStartTime;
+
+ int scores1, scores2; // from configstrings
+ int redflag, blueflag; // flag status from configstrings
+ int flagStatus;
+
+ qboolean newHud;
+
+ //
+ // locally derived information from gamestate
+ //
+ qhandle_t gameModels[MAX_MODELS];
+ sfxHandle_t gameSounds[MAX_SOUNDS];
+
+ int numInlineModels;
+ qhandle_t inlineDrawModel[MAX_MODELS];
+ vec3_t inlineModelMidpoints[MAX_MODELS];
+
+ clientInfo_t clientinfo[MAX_CLIENTS];
+
+ // teamchat width is *3 because of embedded color codes
+ char teamChatMsgs[TEAMCHAT_HEIGHT][TEAMCHAT_WIDTH*3+1];
+ int teamChatMsgTimes[TEAMCHAT_HEIGHT];
+ int teamChatPos;
+ int teamLastChatPos;
+
+ int cursorX;
+ int cursorY;
+ qboolean eventHandling;
+ qboolean mouseCaptured;
+ qboolean sizingHud;
+ void *capturedItem;
+ qhandle_t activeCursor;
+
+ // orders
+ int currentOrder;
+ qboolean orderPending;
+ int orderTime;
+ int currentVoiceClient;
+ int acceptOrderTime;
+ int acceptTask;
+ int acceptLeader;
+ char acceptVoice[MAX_NAME_LENGTH];
+
+ // media
+ cgMedia_t media;
+
+} cgs_t;
+
+//==============================================================================
+
+extern cgs_t cgs;
+extern cg_t cg;
+extern centity_t cg_entities[MAX_GENTITIES];
+extern weaponInfo_t cg_weapons[MAX_WEAPONS];
+extern itemInfo_t cg_items[MAX_ITEMS];
+extern markPoly_t cg_markPolys[MAX_MARK_POLYS];
+
+extern vmCvar_t cg_centertime;
+extern vmCvar_t cg_runpitch;
+extern vmCvar_t cg_runroll;
+extern vmCvar_t cg_bobup;
+extern vmCvar_t cg_bobpitch;
+extern vmCvar_t cg_bobroll;
+extern vmCvar_t cg_swingSpeed;
+extern vmCvar_t cg_shadows;
+extern vmCvar_t cg_gibs;
+extern vmCvar_t cg_drawTimer;
+extern vmCvar_t cg_drawFPS;
+extern vmCvar_t cg_drawSnapshot;
+extern vmCvar_t cg_draw3dIcons;
+extern vmCvar_t cg_drawIcons;
+extern vmCvar_t cg_drawAmmoWarning;
+extern vmCvar_t cg_drawCrosshair;
+extern vmCvar_t cg_drawCrosshairNames;
+extern vmCvar_t cg_drawRewards;
+extern vmCvar_t cg_drawTeamOverlay;
+extern vmCvar_t cg_teamOverlayUserinfo;
+extern vmCvar_t cg_crosshairX;
+extern vmCvar_t cg_crosshairY;
+extern vmCvar_t cg_crosshairSize;
+extern vmCvar_t cg_crosshairHealth;
+extern vmCvar_t cg_drawStatus;
+extern vmCvar_t cg_draw2D;
+extern vmCvar_t cg_animSpeed;
+extern vmCvar_t cg_debugAnim;
+extern vmCvar_t cg_debugPosition;
+extern vmCvar_t cg_debugEvents;
+extern vmCvar_t cg_railTrailTime;
+extern vmCvar_t cg_errorDecay;
+extern vmCvar_t cg_nopredict;
+extern vmCvar_t cg_noPlayerAnims;
+extern vmCvar_t cg_showmiss;
+extern vmCvar_t cg_footsteps;
+extern vmCvar_t cg_addMarks;
+extern vmCvar_t cg_brassTime;
+extern vmCvar_t cg_gun_frame;
+extern vmCvar_t cg_gun_x;
+extern vmCvar_t cg_gun_y;
+extern vmCvar_t cg_gun_z;
+extern vmCvar_t cg_drawGun;
+extern vmCvar_t cg_viewsize;
+extern vmCvar_t cg_tracerChance;
+extern vmCvar_t cg_tracerWidth;
+extern vmCvar_t cg_tracerLength;
+extern vmCvar_t cg_autoswitch;
+extern vmCvar_t cg_ignore;
+extern vmCvar_t cg_simpleItems;
+extern vmCvar_t cg_fov;
+extern vmCvar_t cg_zoomFov;
+extern vmCvar_t cg_thirdPersonRange;
+extern vmCvar_t cg_thirdPersonAngle;
+extern vmCvar_t cg_thirdPerson;
+extern vmCvar_t cg_stereoSeparation;
+extern vmCvar_t cg_lagometer;
+extern vmCvar_t cg_drawAttacker;
+extern vmCvar_t cg_synchronousClients;
+extern vmCvar_t cg_teamChatTime;
+extern vmCvar_t cg_teamChatHeight;
+extern vmCvar_t cg_stats;
+extern vmCvar_t cg_forceModel;
+extern vmCvar_t cg_buildScript;
+extern vmCvar_t cg_paused;
+extern vmCvar_t cg_blood;
+extern vmCvar_t cg_predictItems;
+extern vmCvar_t cg_deferPlayers;
+extern vmCvar_t cg_drawFriend;
+extern vmCvar_t cg_teamChatsOnly;
+extern vmCvar_t cg_noVoiceChats;
+extern vmCvar_t cg_noVoiceText;
+extern vmCvar_t cg_scorePlum;
+extern vmCvar_t cg_smoothClients;
+extern vmCvar_t pmove_fixed;
+extern vmCvar_t pmove_msec;
+//extern vmCvar_t cg_pmove_fixed;
+extern vmCvar_t cg_cameraOrbit;
+extern vmCvar_t cg_cameraOrbitDelay;
+extern vmCvar_t cg_timescaleFadeEnd;
+extern vmCvar_t cg_timescaleFadeSpeed;
+extern vmCvar_t cg_timescale;
+extern vmCvar_t cg_cameraMode;
+extern vmCvar_t cg_smallFont;
+extern vmCvar_t cg_bigFont;
+extern vmCvar_t cg_noTaunt;
+extern vmCvar_t cg_noProjectileTrail;
+extern vmCvar_t cg_oldRail;
+extern vmCvar_t cg_oldRocket;
+extern vmCvar_t cg_oldPlasma;
+extern vmCvar_t cg_trueLightning;
+#ifdef MISSIONPACK
+extern vmCvar_t cg_redTeamName;
+extern vmCvar_t cg_blueTeamName;
+extern vmCvar_t cg_currentSelectedPlayer;
+extern vmCvar_t cg_currentSelectedPlayerName;
+extern vmCvar_t cg_singlePlayer;
+extern vmCvar_t cg_enableDust;
+extern vmCvar_t cg_enableBreath;
+extern vmCvar_t cg_singlePlayerActive;
+extern vmCvar_t cg_recordSPDemo;
+extern vmCvar_t cg_recordSPDemoName;
+extern vmCvar_t cg_obeliskRespawnDelay;
+#endif
+
+//
+// cg_main.c
+//
+const char *CG_ConfigString( int index );
+const char *CG_Argv( int arg );
+
+void QDECL CG_Printf( const char *msg, ... );
+void QDECL CG_Error( const char *msg, ... );
+
+void CG_StartMusic( void );
+
+void CG_UpdateCvars( void );
+
+int CG_CrosshairPlayer( void );
+int CG_LastAttacker( void );
+void CG_LoadMenus(const char *menuFile);
+void CG_KeyEvent(int key, qboolean down);
+void CG_MouseEvent(int x, int y);
+void CG_EventHandling(int type);
+void CG_RankRunFrame( void );
+void CG_SetScoreSelection(void *menu);
+score_t *CG_GetSelectedScore();
+void CG_BuildSpectatorString();
+
+
+//
+// cg_view.c
+//
+void CG_TestModel_f (void);
+void CG_TestGun_f (void);
+void CG_TestModelNextFrame_f (void);
+void CG_TestModelPrevFrame_f (void);
+void CG_TestModelNextSkin_f (void);
+void CG_TestModelPrevSkin_f (void);
+void CG_ZoomDown_f( void );
+void CG_ZoomUp_f( void );
+void CG_AddBufferedSound( sfxHandle_t sfx);
+
+void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView, qboolean demoPlayback );
+
+
+//
+// cg_drawtools.c
+//
+void CG_AdjustFrom640( float *x, float *y, float *w, float *h );
+void CG_FillRect( float x, float y, float width, float height, const float *color );
+void CG_DrawPic( float x, float y, float width, float height, qhandle_t hShader );
+void CG_DrawString( float x, float y, const char *string,
+ float charWidth, float charHeight, const float *modulate );
+
+
+void CG_DrawStringExt( int x, int y, const char *string, const float *setColor,
+ qboolean forceColor, qboolean shadow, int charWidth, int charHeight, int maxChars );
+void CG_DrawBigString( int x, int y, const char *s, float alpha );
+void CG_DrawBigStringColor( int x, int y, const char *s, vec4_t color );
+void CG_DrawSmallString( int x, int y, const char *s, float alpha );
+void CG_DrawSmallStringColor( int x, int y, const char *s, vec4_t color );
+
+int CG_DrawStrlen( const char *str );
+
+float *CG_FadeColor( int startMsec, int totalMsec );
+float *CG_TeamColor( int team );
+void CG_TileClear( void );
+void CG_ColorForHealth( vec4_t hcolor );
+void CG_GetColorForHealth( int health, int armor, vec4_t hcolor );
+
+void UI_DrawProportionalString( int x, int y, const char* str, int style, vec4_t color );
+void CG_DrawRect( float x, float y, float width, float height, float size, const float *color );
+void CG_DrawSides(float x, float y, float w, float h, float size);
+void CG_DrawTopBottom(float x, float y, float w, float h, float size);
+
+
+//
+// cg_draw.c, cg_newDraw.c
+//
+extern int sortedTeamPlayers[TEAM_MAXOVERLAY];
+extern int numSortedTeamPlayers;
+extern int drawTeamOverlayModificationCount;
+extern char systemChat[256];
+extern char teamChat1[256];
+extern char teamChat2[256];
+
+void CG_AddLagometerFrameInfo( void );
+void CG_AddLagometerSnapshotInfo( snapshot_t *snap );
+void CG_CenterPrint( const char *str, int y, int charWidth );
+void CG_DrawHead( float x, float y, float w, float h, int clientNum, vec3_t headAngles );
+void CG_DrawActive( stereoFrame_t stereoView );
+void CG_DrawFlagModel( float x, float y, float w, float h, int team, qboolean force2D );
+void CG_DrawTeamBackground( int x, int y, int w, int h, float alpha, int team );
+void CG_OwnerDraw(float x, float y, float w, float h, float text_x, float text_y, int ownerDraw, int ownerDrawFlags, int align, float special, float scale, vec4_t color, qhandle_t shader, int textStyle);
+void CG_Text_Paint(float x, float y, float scale, vec4_t color, const char *text, float adjust, int limit, int style);
+int CG_Text_Width(const char *text, float scale, int limit);
+int CG_Text_Height(const char *text, float scale, int limit);
+void CG_SelectPrevPlayer();
+void CG_SelectNextPlayer();
+float CG_GetValue(int ownerDraw);
+qboolean CG_OwnerDrawVisible(int flags);
+void CG_RunMenuScript(char **args);
+void CG_ShowResponseHead();
+void CG_SetPrintString(int type, const char *p);
+void CG_InitTeamChat();
+void CG_GetTeamColor(vec4_t *color);
+const char *CG_GetGameStatusText();
+const char *CG_GetKillerText();
+void CG_Draw3DModel( float x, float y, float w, float h, qhandle_t model, qhandle_t skin, vec3_t origin, vec3_t angles );
+void CG_Text_PaintChar(float x, float y, float width, float height, float scale, float s, float t, float s2, float t2, qhandle_t hShader);
+void CG_CheckOrderPending();
+const char *CG_GameTypeString();
+qboolean CG_YourTeamHasFlag();
+qboolean CG_OtherTeamHasFlag();
+qhandle_t CG_StatusHandle(int task);
+
+
+
+//
+// cg_player.c
+//
+void CG_Player( centity_t *cent );
+void CG_ResetPlayerEntity( centity_t *cent );
+void CG_AddRefEntityWithPowerups( refEntity_t *ent, entityState_t *state, int team );
+void CG_NewClientInfo( int clientNum );
+sfxHandle_t CG_CustomSound( int clientNum, const char *soundName );
+
+//
+// cg_predict.c
+//
+void CG_BuildSolidList( void );
+int CG_PointContents( const vec3_t point, int passEntityNum );
+void CG_Trace( trace_t *result, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end,
+ int skipNumber, int mask );
+void CG_PredictPlayerState( void );
+void CG_LoadDeferredPlayers( void );
+
+
+//
+// cg_events.c
+//
+void CG_CheckEvents( centity_t *cent );
+const char *CG_PlaceString( int rank );
+void CG_EntityEvent( centity_t *cent, vec3_t position );
+void CG_PainEvent( centity_t *cent, int health );
+
+
+//
+// cg_ents.c
+//
+void CG_SetEntitySoundPosition( centity_t *cent );
+void CG_AddPacketEntities( void );
+void CG_Beam( centity_t *cent );
+void CG_AdjustPositionForMover( const vec3_t in, int moverNum, int fromTime, int toTime, vec3_t out );
+
+void CG_PositionEntityOnTag( refEntity_t *entity, const refEntity_t *parent,
+ qhandle_t parentModel, char *tagName );
+void CG_PositionRotatedEntityOnTag( refEntity_t *entity, const refEntity_t *parent,
+ qhandle_t parentModel, char *tagName );
+
+
+
+//
+// cg_weapons.c
+//
+void CG_NextWeapon_f( void );
+void CG_PrevWeapon_f( void );
+void CG_Weapon_f( void );
+
+void CG_RegisterWeapon( int weaponNum );
+void CG_RegisterItemVisuals( int itemNum );
+
+void CG_FireWeapon( centity_t *cent );
+void CG_MissileHitWall( int weapon, int clientNum, vec3_t origin, vec3_t dir, impactSound_t soundType );
+void CG_MissileHitPlayer( int weapon, vec3_t origin, vec3_t dir, int entityNum );
+void CG_ShotgunFire( entityState_t *es );
+void CG_Bullet( vec3_t origin, int sourceEntityNum, vec3_t normal, qboolean flesh, int fleshEntityNum );
+
+void CG_RailTrail( clientInfo_t *ci, vec3_t start, vec3_t end );
+void CG_GrappleTrail( centity_t *ent, const weaponInfo_t *wi );
+void CG_AddViewWeapon (playerState_t *ps);
+void CG_AddPlayerWeapon( refEntity_t *parent, playerState_t *ps, centity_t *cent, int team );
+void CG_DrawWeaponSelect( void );
+
+void CG_OutOfAmmoChange( void ); // should this be in pmove?
+
+//
+// cg_marks.c
+//
+void CG_InitMarkPolys( void );
+void CG_AddMarks( void );
+void CG_ImpactMark( qhandle_t markShader,
+ const vec3_t origin, const vec3_t dir,
+ float orientation,
+ float r, float g, float b, float a,
+ qboolean alphaFade,
+ float radius, qboolean temporary );
+
+//
+// cg_localents.c
+//
+void CG_InitLocalEntities( void );
+localEntity_t *CG_AllocLocalEntity( void );
+void CG_AddLocalEntities( void );
+
+//
+// cg_effects.c
+//
+localEntity_t *CG_SmokePuff( const vec3_t p,
+ const vec3_t vel,
+ float radius,
+ float r, float g, float b, float a,
+ float duration,
+ int startTime,
+ int fadeInTime,
+ int leFlags,
+ qhandle_t hShader );
+void CG_BubbleTrail( vec3_t start, vec3_t end, float spacing );
+void CG_SpawnEffect( vec3_t org );
+#ifdef MISSIONPACK
+void CG_KamikazeEffect( vec3_t org );
+void CG_ObeliskExplode( vec3_t org, int entityNum );
+void CG_ObeliskPain( vec3_t org );
+void CG_InvulnerabilityImpact( vec3_t org, vec3_t angles );
+void CG_InvulnerabilityJuiced( vec3_t org );
+void CG_LightningBoltBeam( vec3_t start, vec3_t end );
+#endif
+void CG_ScorePlum( int client, vec3_t org, int score );
+
+void CG_GibPlayer( vec3_t playerOrigin );
+void CG_BigExplode( vec3_t playerOrigin );
+
+void CG_Bleed( vec3_t origin, int entityNum );
+
+localEntity_t *CG_MakeExplosion( vec3_t origin, vec3_t dir,
+ qhandle_t hModel, qhandle_t shader, int msec,
+ qboolean isSprite );
+
+//
+// cg_snapshot.c
+//
+void CG_ProcessSnapshots( void );
+
+//
+// cg_info.c
+//
+void CG_LoadingString( const char *s );
+void CG_LoadingItem( int itemNum );
+void CG_LoadingClient( int clientNum );
+void CG_DrawInformation( void );
+
+//
+// cg_scoreboard.c
+//
+qboolean CG_DrawOldScoreboard( void );
+void CG_DrawOldTourneyScoreboard( void );
+
+//
+// cg_consolecmds.c
+//
+qboolean CG_ConsoleCommand( void );
+void CG_InitConsoleCommands( void );
+
+//
+// cg_servercmds.c
+//
+void CG_ExecuteNewServerCommands( int latestSequence );
+void CG_ParseServerinfo( void );
+void CG_SetConfigValues( void );
+void CG_LoadVoiceChats( void );
+void CG_ShaderStateChanged(void);
+void CG_VoiceChatLocal( int mode, qboolean voiceOnly, int clientNum, int color, const char *cmd );
+void CG_PlayBufferedVoiceChats( void );
+
+//
+// cg_playerstate.c
+//
+void CG_Respawn( void );
+void CG_TransitionPlayerState( playerState_t *ps, playerState_t *ops );
+void CG_CheckChangedPredictableEvents( playerState_t *ps );
+
+
+//===============================================
+
+//
+// system traps
+// These functions are how the cgame communicates with the main game system
+//
+
+// print message on the local console
+void trap_Print( const char *fmt );
+
+// abort the game
+void trap_Error( const char *fmt );
+
+// milliseconds should only be used for performance tuning, never
+// for anything game related. Get time from the CG_DrawActiveFrame parameter
+int trap_Milliseconds( void );
+
+// console variable interaction
+void trap_Cvar_Register( vmCvar_t *vmCvar, const char *varName, const char *defaultValue, int flags );
+void trap_Cvar_Update( vmCvar_t *vmCvar );
+void trap_Cvar_Set( const char *var_name, const char *value );
+void trap_Cvar_VariableStringBuffer( const char *var_name, char *buffer, int bufsize );
+
+// ServerCommand and ConsoleCommand parameter access
+int trap_Argc( void );
+void trap_Argv( int n, char *buffer, int bufferLength );
+void trap_Args( char *buffer, int bufferLength );
+
+// filesystem access
+// returns length of file
+int trap_FS_FOpenFile( const char *qpath, fileHandle_t *f, fsMode_t mode );
+void trap_FS_Read( void *buffer, int len, fileHandle_t f );
+void trap_FS_Write( const void *buffer, int len, fileHandle_t f );
+void trap_FS_FCloseFile( fileHandle_t f );
+int trap_FS_Seek( fileHandle_t f, long offset, int origin ); // fsOrigin_t
+
+// add commands to the local console as if they were typed in
+// for map changing, etc. The command is not executed immediately,
+// but will be executed in order the next time console commands
+// are processed
+void trap_SendConsoleCommand( const char *text );
+
+// register a command name so the console can perform command completion.
+// FIXME: replace this with a normal console command "defineCommand"?
+void trap_AddCommand( const char *cmdName );
+
+// send a string to the server over the network
+void trap_SendClientCommand( const char *s );
+
+// force a screen update, only used during gamestate load
+void trap_UpdateScreen( void );
+
+// model collision
+void trap_CM_LoadMap( const char *mapname );
+int trap_CM_NumInlineModels( void );
+clipHandle_t trap_CM_InlineModel( int index ); // 0 = world, 1+ = bmodels
+clipHandle_t trap_CM_TempBoxModel( const vec3_t mins, const vec3_t maxs );
+int trap_CM_PointContents( const vec3_t p, clipHandle_t model );
+int trap_CM_TransformedPointContents( const vec3_t p, clipHandle_t model, const vec3_t origin, const vec3_t angles );
+void trap_CM_BoxTrace( trace_t *results, const vec3_t start, const vec3_t end,
+ const vec3_t mins, const vec3_t maxs,
+ clipHandle_t model, int brushmask );
+void trap_CM_TransformedBoxTrace( trace_t *results, const vec3_t start, const vec3_t end,
+ const vec3_t mins, const vec3_t maxs,
+ clipHandle_t model, int brushmask,
+ const vec3_t origin, const vec3_t angles );
+
+// Returns the projection of a polygon onto the solid brushes in the world
+int trap_CM_MarkFragments( int numPoints, const vec3_t *points,
+ const vec3_t projection,
+ int maxPoints, vec3_t pointBuffer,
+ int maxFragments, markFragment_t *fragmentBuffer );
+
+// normal sounds will have their volume dynamically changed as their entity
+// moves and the listener moves
+void trap_S_StartSound( vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfx );
+void trap_S_StopLoopingSound(int entnum);
+
+// a local sound is always played full volume
+void trap_S_StartLocalSound( sfxHandle_t sfx, int channelNum );
+void trap_S_ClearLoopingSounds( qboolean killall );
+void trap_S_AddLoopingSound( int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx );
+void trap_S_AddRealLoopingSound( int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx );
+void trap_S_UpdateEntityPosition( int entityNum, const vec3_t origin );
+
+// respatialize recalculates the volumes of sound as they should be heard by the
+// given entityNum and position
+void trap_S_Respatialize( int entityNum, const vec3_t origin, vec3_t axis[3], int inwater );
+sfxHandle_t trap_S_RegisterSound( const char *sample, qboolean compressed ); // returns buzz if not found
+void trap_S_StartBackgroundTrack( const char *intro, const char *loop ); // empty name stops music
+void trap_S_StopBackgroundTrack( void );
+
+
+void trap_R_LoadWorldMap( const char *mapname );
+
+// all media should be registered during level startup to prevent
+// hitches during gameplay
+qhandle_t trap_R_RegisterModel( const char *name ); // returns rgb axis if not found
+qhandle_t trap_R_RegisterSkin( const char *name ); // returns all white if not found
+qhandle_t trap_R_RegisterShader( const char *name ); // returns all white if not found
+qhandle_t trap_R_RegisterShaderNoMip( const char *name ); // returns all white if not found
+
+// a scene is built up by calls to R_ClearScene and the various R_Add functions.
+// Nothing is drawn until R_RenderScene is called.
+void trap_R_ClearScene( void );
+void trap_R_AddRefEntityToScene( const refEntity_t *re );
+
+// polys are intended for simple wall marks, not really for doing
+// significant construction
+void trap_R_AddPolyToScene( qhandle_t hShader , int numVerts, const polyVert_t *verts );
+void trap_R_AddPolysToScene( qhandle_t hShader , int numVerts, const polyVert_t *verts, int numPolys );
+void trap_R_AddLightToScene( const vec3_t org, float intensity, float r, float g, float b );
+int trap_R_LightForPoint( vec3_t point, vec3_t ambientLight, vec3_t directedLight, vec3_t lightDir );
+void trap_R_RenderScene( const refdef_t *fd );
+void trap_R_SetColor( const float *rgba ); // NULL = 1,1,1,1
+void trap_R_DrawStretchPic( float x, float y, float w, float h,
+ float s1, float t1, float s2, float t2, qhandle_t hShader );
+void trap_R_ModelBounds( clipHandle_t model, vec3_t mins, vec3_t maxs );
+int trap_R_LerpTag( orientation_t *tag, clipHandle_t mod, int startFrame, int endFrame,
+ float frac, const char *tagName );
+void trap_R_RemapShader( const char *oldShader, const char *newShader, const char *timeOffset );
+
+// The glconfig_t will not change during the life of a cgame.
+// If it needs to change, the entire cgame will be restarted, because
+// all the qhandle_t are then invalid.
+void trap_GetGlconfig( glconfig_t *glconfig );
+
+// the gamestate should be grabbed at startup, and whenever a
+// configstring changes
+void trap_GetGameState( gameState_t *gamestate );
+
+// cgame will poll each frame to see if a newer snapshot has arrived
+// that it is interested in. The time is returned seperately so that
+// snapshot latency can be calculated.
+void trap_GetCurrentSnapshotNumber( int *snapshotNumber, int *serverTime );
+
+// a snapshot get can fail if the snapshot (or the entties it holds) is so
+// old that it has fallen out of the client system queue
+qboolean trap_GetSnapshot( int snapshotNumber, snapshot_t *snapshot );
+
+// retrieve a text command from the server stream
+// the current snapshot will hold the number of the most recent command
+// qfalse can be returned if the client system handled the command
+// argc() / argv() can be used to examine the parameters of the command
+qboolean trap_GetServerCommand( int serverCommandNumber );
+
+// returns the most recent command number that can be passed to GetUserCmd
+// this will always be at least one higher than the number in the current
+// snapshot, and it may be quite a few higher if it is a fast computer on
+// a lagged connection
+int trap_GetCurrentCmdNumber( void );
+
+qboolean trap_GetUserCmd( int cmdNumber, usercmd_t *ucmd );
+
+// used for the weapon select and zoom
+void trap_SetUserCmdValue( int stateValue, float sensitivityScale );
+
+// aids for VM testing
+void testPrintInt( char *string, int i );
+void testPrintFloat( char *string, float f );
+
+int trap_MemoryRemaining( void );
+void trap_R_RegisterFont(const char *fontName, int pointSize, fontInfo_t *font);
+qboolean trap_Key_IsDown( int keynum );
+int trap_Key_GetCatcher( void );
+void trap_Key_SetCatcher( int catcher );
+int trap_Key_GetKey( const char *binding );
+
+
+typedef enum {
+ SYSTEM_PRINT,
+ CHAT_PRINT,
+ TEAMCHAT_PRINT
+} q3print_t; // bk001201 - warning: useless keyword or type name in empty declaration
+
+
+int trap_CIN_PlayCinematic( const char *arg0, int xpos, int ypos, int width, int height, int bits);
+e_status trap_CIN_StopCinematic(int handle);
+e_status trap_CIN_RunCinematic (int handle);
+void trap_CIN_DrawCinematic (int handle);
+void trap_CIN_SetExtents (int handle, int x, int y, int w, int h);
+
+void trap_SnapVector( float *v );
+
+qboolean trap_loadCamera(const char *name);
+void trap_startCamera(int time);
+qboolean trap_getCameraInfo(int time, vec3_t *origin, vec3_t *angles);
+
+qboolean trap_GetEntityToken( char *buffer, int bufferSize );
+
+void CG_ClearParticles (void);
+void CG_AddParticles (void);
+void CG_ParticleSnow (qhandle_t pshader, vec3_t origin, vec3_t origin2, int turb, float range, int snum);
+void CG_ParticleSmoke (qhandle_t pshader, centity_t *cent);
+void CG_AddParticleShrapnel (localEntity_t *le);
+void CG_ParticleSnowFlurry (qhandle_t pshader, centity_t *cent);
+void CG_ParticleBulletDebris (vec3_t org, vec3_t vel, int duration);
+void CG_ParticleSparks (vec3_t org, vec3_t vel, int duration, float x, float y, float speed);
+void CG_ParticleDust (centity_t *cent, vec3_t origin, vec3_t dir);
+void CG_ParticleMisc (qhandle_t pshader, vec3_t origin, int size, int duration, float alpha);
+void CG_ParticleExplosion (char *animStr, vec3_t origin, vec3_t vel, int duration, int sizeStart, int sizeEnd);
+extern qboolean initparticles;
+int CG_NewParticleArea ( int num );
+
+
diff --git a/code/cgame/cg_localents.c b/code/cgame/cg_localents.c
new file mode 100755
index 0000000..534b147
--- /dev/null
+++ b/code/cgame/cg_localents.c
@@ -0,0 +1,886 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+// cg_localents.c -- every frame, generate renderer commands for locally
+// processed entities, like smoke puffs, gibs, shells, etc.
+
+#include "cg_local.h"
+
+#define MAX_LOCAL_ENTITIES 512
+localEntity_t cg_localEntities[MAX_LOCAL_ENTITIES];
+localEntity_t cg_activeLocalEntities; // double linked list
+localEntity_t *cg_freeLocalEntities; // single linked list
+
+/*
+===================
+CG_InitLocalEntities
+
+This is called at startup and for tournement restarts
+===================
+*/
+void CG_InitLocalEntities( void ) {
+ int i;
+
+ memset( cg_localEntities, 0, sizeof( cg_localEntities ) );
+ cg_activeLocalEntities.next = &cg_activeLocalEntities;
+ cg_activeLocalEntities.prev = &cg_activeLocalEntities;
+ cg_freeLocalEntities = cg_localEntities;
+ for ( i = 0 ; i < MAX_LOCAL_ENTITIES - 1 ; i++ ) {
+ cg_localEntities[i].next = &cg_localEntities[i+1];
+ }
+}
+
+
+/*
+==================
+CG_FreeLocalEntity
+==================
+*/
+void CG_FreeLocalEntity( localEntity_t *le ) {
+ if ( !le->prev ) {
+ CG_Error( "CG_FreeLocalEntity: not active" );
+ }
+
+ // remove from the doubly linked active list
+ le->prev->next = le->next;
+ le->next->prev = le->prev;
+
+ // the free list is only singly linked
+ le->next = cg_freeLocalEntities;
+ cg_freeLocalEntities = le;
+}
+
+/*
+===================
+CG_AllocLocalEntity
+
+Will allways succeed, even if it requires freeing an old active entity
+===================
+*/
+localEntity_t *CG_AllocLocalEntity( void ) {
+ localEntity_t *le;
+
+ if ( !cg_freeLocalEntities ) {
+ // no free entities, so free the one at the end of the chain
+ // remove the oldest active entity
+ CG_FreeLocalEntity( cg_activeLocalEntities.prev );
+ }
+
+ le = cg_freeLocalEntities;
+ cg_freeLocalEntities = cg_freeLocalEntities->next;
+
+ memset( le, 0, sizeof( *le ) );
+
+ // link into the active list
+ le->next = cg_activeLocalEntities.next;
+ le->prev = &cg_activeLocalEntities;
+ cg_activeLocalEntities.next->prev = le;
+ cg_activeLocalEntities.next = le;
+ return le;
+}
+
+
+/*
+====================================================================================
+
+FRAGMENT PROCESSING
+
+A fragment localentity interacts with the environment in some way (hitting walls),
+or generates more localentities along a trail.
+
+====================================================================================
+*/
+
+/*
+================
+CG_BloodTrail
+
+Leave expanding blood puffs behind gibs
+================
+*/
+void CG_BloodTrail( localEntity_t *le ) {
+ int t;
+ int t2;
+ int step;
+ vec3_t newOrigin;
+ localEntity_t *blood;
+
+ step = 150;
+ t = step * ( (cg.time - cg.frametime + step ) / step );
+ t2 = step * ( cg.time / step );
+
+ for ( ; t <= t2; t += step ) {
+ BG_EvaluateTrajectory( &le->pos, t, newOrigin );
+
+ blood = CG_SmokePuff( newOrigin, vec3_origin,
+ 20, // radius
+ 1, 1, 1, 1, // color
+ 2000, // trailTime
+ t, // startTime
+ 0, // fadeInTime
+ 0, // flags
+ cgs.media.bloodTrailShader );
+ // use the optimized version
+ blood->leType = LE_FALL_SCALE_FADE;
+ // drop a total of 40 units over its lifetime
+ blood->pos.trDelta[2] = 40;
+ }
+}
+
+
+/*
+================
+CG_FragmentBounceMark
+================
+*/
+void CG_FragmentBounceMark( localEntity_t *le, trace_t *trace ) {
+ int radius;
+
+ if ( le->leMarkType == LEMT_BLOOD ) {
+
+ radius = 16 + (rand()&31);
+ CG_ImpactMark( cgs.media.bloodMarkShader, trace->endpos, trace->plane.normal, random()*360,
+ 1,1,1,1, qtrue, radius, qfalse );
+ } else if ( le->leMarkType == LEMT_BURN ) {
+
+ radius = 8 + (rand()&15);
+ CG_ImpactMark( cgs.media.burnMarkShader, trace->endpos, trace->plane.normal, random()*360,
+ 1,1,1,1, qtrue, radius, qfalse );
+ }
+
+
+ // don't allow a fragment to make multiple marks, or they
+ // pile up while settling
+ le->leMarkType = LEMT_NONE;
+}
+
+/*
+================
+CG_FragmentBounceSound
+================
+*/
+void CG_FragmentBounceSound( localEntity_t *le, trace_t *trace ) {
+ if ( le->leBounceSoundType == LEBS_BLOOD ) {
+ // half the gibs will make splat sounds
+ if ( rand() & 1 ) {
+ int r = rand()&3;
+ sfxHandle_t s;
+
+ if ( r == 0 ) {
+ s = cgs.media.gibBounce1Sound;
+ } else if ( r == 1 ) {
+ s = cgs.media.gibBounce2Sound;
+ } else {
+ s = cgs.media.gibBounce3Sound;
+ }
+ trap_S_StartSound( trace->endpos, ENTITYNUM_WORLD, CHAN_AUTO, s );
+ }
+ } else if ( le->leBounceSoundType == LEBS_BRASS ) {
+
+ }
+
+ // don't allow a fragment to make multiple bounce sounds,
+ // or it gets too noisy as they settle
+ le->leBounceSoundType = LEBS_NONE;
+}
+
+
+/*
+================
+CG_ReflectVelocity
+================
+*/
+void CG_ReflectVelocity( localEntity_t *le, trace_t *trace ) {
+ vec3_t velocity;
+ float dot;
+ int hitTime;
+
+ // reflect the velocity on the trace plane
+ hitTime = cg.time - cg.frametime + cg.frametime * trace->fraction;
+ BG_EvaluateTrajectoryDelta( &le->pos, hitTime, velocity );
+ dot = DotProduct( velocity, trace->plane.normal );
+ VectorMA( velocity, -2*dot, trace->plane.normal, le->pos.trDelta );
+
+ VectorScale( le->pos.trDelta, le->bounceFactor, le->pos.trDelta );
+
+ VectorCopy( trace->endpos, le->pos.trBase );
+ le->pos.trTime = cg.time;
+
+
+ // check for stop, making sure that even on low FPS systems it doesn't bobble
+ if ( trace->allsolid ||
+ ( trace->plane.normal[2] > 0 &&
+ ( le->pos.trDelta[2] < 40 || le->pos.trDelta[2] < -cg.frametime * le->pos.trDelta[2] ) ) ) {
+ le->pos.trType = TR_STATIONARY;
+ } else {
+
+ }
+}
+
+/*
+================
+CG_AddFragment
+================
+*/
+void CG_AddFragment( localEntity_t *le ) {
+ vec3_t newOrigin;
+ trace_t trace;
+
+ if ( le->pos.trType == TR_STATIONARY ) {
+ // sink into the ground if near the removal time
+ int t;
+ float oldZ;
+
+ t = le->endTime - cg.time;
+ if ( t < SINK_TIME ) {
+ // we must use an explicit lighting origin, otherwise the
+ // lighting would be lost as soon as the origin went
+ // into the ground
+ VectorCopy( le->refEntity.origin, le->refEntity.lightingOrigin );
+ le->refEntity.renderfx |= RF_LIGHTING_ORIGIN;
+ oldZ = le->refEntity.origin[2];
+ le->refEntity.origin[2] -= 16 * ( 1.0 - (float)t / SINK_TIME );
+ trap_R_AddRefEntityToScene( &le->refEntity );
+ le->refEntity.origin[2] = oldZ;
+ } else {
+ trap_R_AddRefEntityToScene( &le->refEntity );
+ }
+
+ return;
+ }
+
+ // calculate new position
+ BG_EvaluateTrajectory( &le->pos, cg.time, newOrigin );
+
+ // trace a line from previous position to new position
+ CG_Trace( &trace, le->refEntity.origin, NULL, NULL, newOrigin, -1, CONTENTS_SOLID );
+ if ( trace.fraction == 1.0 ) {
+ // still in free fall
+ VectorCopy( newOrigin, le->refEntity.origin );
+
+ if ( le->leFlags & LEF_TUMBLE ) {
+ vec3_t angles;
+
+ BG_EvaluateTrajectory( &le->angles, cg.time, angles );
+ AnglesToAxis( angles, le->refEntity.axis );
+ }
+
+ trap_R_AddRefEntityToScene( &le->refEntity );
+
+ // add a blood trail
+ if ( le->leBounceSoundType == LEBS_BLOOD ) {
+ CG_BloodTrail( le );
+ }
+
+ return;
+ }
+
+ // if it is in a nodrop zone, remove it
+ // this keeps gibs from waiting at the bottom of pits of death
+ // and floating levels
+ if ( trap_CM_PointContents( trace.endpos, 0 ) & CONTENTS_NODROP ) {
+ CG_FreeLocalEntity( le );
+ return;
+ }
+
+ // leave a mark
+ CG_FragmentBounceMark( le, &trace );
+
+ // do a bouncy sound
+ CG_FragmentBounceSound( le, &trace );
+
+ // reflect the velocity on the trace plane
+ CG_ReflectVelocity( le, &trace );
+
+ trap_R_AddRefEntityToScene( &le->refEntity );
+}
+
+/*
+=====================================================================
+
+TRIVIAL LOCAL ENTITIES
+
+These only do simple scaling or modulation before passing to the renderer
+=====================================================================
+*/
+
+/*
+====================
+CG_AddFadeRGB
+====================
+*/
+void CG_AddFadeRGB( localEntity_t *le ) {
+ refEntity_t *re;
+ float c;
+
+ re = &le->refEntity;
+
+ c = ( le->endTime - cg.time ) * le->lifeRate;
+ c *= 0xff;
+
+ re->shaderRGBA[0] = le->color[0] * c;
+ re->shaderRGBA[1] = le->color[1] * c;
+ re->shaderRGBA[2] = le->color[2] * c;
+ re->shaderRGBA[3] = le->color[3] * c;
+
+ trap_R_AddRefEntityToScene( re );
+}
+
+/*
+==================
+CG_AddMoveScaleFade
+==================
+*/
+static void CG_AddMoveScaleFade( localEntity_t *le ) {
+ refEntity_t *re;
+ float c;
+ vec3_t delta;
+ float len;
+
+ re = &le->refEntity;
+
+ if ( le->fadeInTime > le->startTime && cg.time < le->fadeInTime ) {
+ // fade / grow time
+ c = 1.0 - (float) ( le->fadeInTime - cg.time ) / ( le->fadeInTime - le->startTime );
+ }
+ else {
+ // fade / grow time
+ c = ( le->endTime - cg.time ) * le->lifeRate;
+ }
+
+ re->shaderRGBA[3] = 0xff * c * le->color[3];
+
+ if ( !( le->leFlags & LEF_PUFF_DONT_SCALE ) ) {
+ re->radius = le->radius * ( 1.0 - c ) + 8;
+ }
+
+ BG_EvaluateTrajectory( &le->pos, cg.time, re->origin );
+
+ // if the view would be "inside" the sprite, kill the sprite
+ // so it doesn't add too much overdraw
+ VectorSubtract( re->origin, cg.refdef.vieworg, delta );
+ len = VectorLength( delta );
+ if ( len < le->radius ) {
+ CG_FreeLocalEntity( le );
+ return;
+ }
+
+ trap_R_AddRefEntityToScene( re );
+}
+
+
+/*
+===================
+CG_AddScaleFade
+
+For rocket smokes that hang in place, fade out, and are
+removed if the view passes through them.
+There are often many of these, so it needs to be simple.
+===================
+*/
+static void CG_AddScaleFade( localEntity_t *le ) {
+ refEntity_t *re;
+ float c;
+ vec3_t delta;
+ float len;
+
+ re = &le->refEntity;
+
+ // fade / grow time
+ c = ( le->endTime - cg.time ) * le->lifeRate;
+
+ re->shaderRGBA[3] = 0xff * c * le->color[3];
+ re->radius = le->radius * ( 1.0 - c ) + 8;
+
+ // if the view would be "inside" the sprite, kill the sprite
+ // so it doesn't add too much overdraw
+ VectorSubtract( re->origin, cg.refdef.vieworg, delta );
+ len = VectorLength( delta );
+ if ( len < le->radius ) {
+ CG_FreeLocalEntity( le );
+ return;
+ }
+
+ trap_R_AddRefEntityToScene( re );
+}
+
+
+/*
+=================
+CG_AddFallScaleFade
+
+This is just an optimized CG_AddMoveScaleFade
+For blood mists that drift down, fade out, and are
+removed if the view passes through them.
+There are often 100+ of these, so it needs to be simple.
+=================
+*/
+static void CG_AddFallScaleFade( localEntity_t *le ) {
+ refEntity_t *re;
+ float c;
+ vec3_t delta;
+ float len;
+
+ re = &le->refEntity;
+
+ // fade time
+ c = ( le->endTime - cg.time ) * le->lifeRate;
+
+ re->shaderRGBA[3] = 0xff * c * le->color[3];
+
+ re->origin[2] = le->pos.trBase[2] - ( 1.0 - c ) * le->pos.trDelta[2];
+
+ re->radius = le->radius * ( 1.0 - c ) + 16;
+
+ // if the view would be "inside" the sprite, kill the sprite
+ // so it doesn't add too much overdraw
+ VectorSubtract( re->origin, cg.refdef.vieworg, delta );
+ len = VectorLength( delta );
+ if ( len < le->radius ) {
+ CG_FreeLocalEntity( le );
+ return;
+ }
+
+ trap_R_AddRefEntityToScene( re );
+}
+
+
+
+/*
+================
+CG_AddExplosion
+================
+*/
+static void CG_AddExplosion( localEntity_t *ex ) {
+ refEntity_t *ent;
+
+ ent = &ex->refEntity;
+
+ // add the entity
+ trap_R_AddRefEntityToScene(ent);
+
+ // add the dlight
+ if ( ex->light ) {
+ float light;
+
+ light = (float)( cg.time - ex->startTime ) / ( ex->endTime - ex->startTime );
+ if ( light < 0.5 ) {
+ light = 1.0;
+ } else {
+ light = 1.0 - ( light - 0.5 ) * 2;
+ }
+ light = ex->light * light;
+ trap_R_AddLightToScene(ent->origin, light, ex->lightColor[0], ex->lightColor[1], ex->lightColor[2] );
+ }
+}
+
+/*
+================
+CG_AddSpriteExplosion
+================
+*/
+static void CG_AddSpriteExplosion( localEntity_t *le ) {
+ refEntity_t re;
+ float c;
+
+ re = le->refEntity;
+
+ c = ( le->endTime - cg.time ) / ( float ) ( le->endTime - le->startTime );
+ if ( c > 1 ) {
+ c = 1.0; // can happen during connection problems
+ }
+
+ re.shaderRGBA[0] = 0xff;
+ re.shaderRGBA[1] = 0xff;
+ re.shaderRGBA[2] = 0xff;
+ re.shaderRGBA[3] = 0xff * c * 0.33;
+
+ re.reType = RT_SPRITE;
+ re.radius = 42 * ( 1.0 - c ) + 30;
+
+ trap_R_AddRefEntityToScene( &re );
+
+ // add the dlight
+ if ( le->light ) {
+ float light;
+
+ light = (float)( cg.time - le->startTime ) / ( le->endTime - le->startTime );
+ if ( light < 0.5 ) {
+ light = 1.0;
+ } else {
+ light = 1.0 - ( light - 0.5 ) * 2;
+ }
+ light = le->light * light;
+ trap_R_AddLightToScene(re.origin, light, le->lightColor[0], le->lightColor[1], le->lightColor[2] );
+ }
+}
+
+
+#ifdef MISSIONPACK
+/*
+====================
+CG_AddKamikaze
+====================
+*/
+void CG_AddKamikaze( localEntity_t *le ) {
+ refEntity_t *re;
+ refEntity_t shockwave;
+ float c;
+ vec3_t test, axis[3];
+ int t;
+
+ re = &le->refEntity;
+
+ t = cg.time - le->startTime;
+ VectorClear( test );
+ AnglesToAxis( test, axis );
+
+ if (t > KAMI_SHOCKWAVE_STARTTIME && t < KAMI_SHOCKWAVE_ENDTIME) {
+
+ if (!(le->leFlags & LEF_SOUND1)) {
+// trap_S_StartSound (re->origin, ENTITYNUM_WORLD, CHAN_AUTO, cgs.media.kamikazeExplodeSound );
+ trap_S_StartLocalSound(cgs.media.kamikazeExplodeSound, CHAN_AUTO);
+ le->leFlags |= LEF_SOUND1;
+ }
+ // 1st kamikaze shockwave
+ memset(&shockwave, 0, sizeof(shockwave));
+ shockwave.hModel = cgs.media.kamikazeShockWave;
+ shockwave.reType = RT_MODEL;
+ shockwave.shaderTime = re->shaderTime;
+ VectorCopy(re->origin, shockwave.origin);
+
+ c = (float)(t - KAMI_SHOCKWAVE_STARTTIME) / (float)(KAMI_SHOCKWAVE_ENDTIME - KAMI_SHOCKWAVE_STARTTIME);
+ VectorScale( axis[0], c * KAMI_SHOCKWAVE_MAXRADIUS / KAMI_SHOCKWAVEMODEL_RADIUS, shockwave.axis[0] );
+ VectorScale( axis[1], c * KAMI_SHOCKWAVE_MAXRADIUS / KAMI_SHOCKWAVEMODEL_RADIUS, shockwave.axis[1] );
+ VectorScale( axis[2], c * KAMI_SHOCKWAVE_MAXRADIUS / KAMI_SHOCKWAVEMODEL_RADIUS, shockwave.axis[2] );
+ shockwave.nonNormalizedAxes = qtrue;
+
+ if (t > KAMI_SHOCKWAVEFADE_STARTTIME) {
+ c = (float)(t - KAMI_SHOCKWAVEFADE_STARTTIME) / (float)(KAMI_SHOCKWAVE_ENDTIME - KAMI_SHOCKWAVEFADE_STARTTIME);
+ }
+ else {
+ c = 0;
+ }
+ c *= 0xff;
+ shockwave.shaderRGBA[0] = 0xff - c;
+ shockwave.shaderRGBA[1] = 0xff - c;
+ shockwave.shaderRGBA[2] = 0xff - c;
+ shockwave.shaderRGBA[3] = 0xff - c;
+
+ trap_R_AddRefEntityToScene( &shockwave );
+ }
+
+ if (t > KAMI_EXPLODE_STARTTIME && t < KAMI_IMPLODE_ENDTIME) {
+ // explosion and implosion
+ c = ( le->endTime - cg.time ) * le->lifeRate;
+ c *= 0xff;
+ re->shaderRGBA[0] = le->color[0] * c;
+ re->shaderRGBA[1] = le->color[1] * c;
+ re->shaderRGBA[2] = le->color[2] * c;
+ re->shaderRGBA[3] = le->color[3] * c;
+
+ if( t < KAMI_IMPLODE_STARTTIME ) {
+ c = (float)(t - KAMI_EXPLODE_STARTTIME) / (float)(KAMI_IMPLODE_STARTTIME - KAMI_EXPLODE_STARTTIME);
+ }
+ else {
+ if (!(le->leFlags & LEF_SOUND2)) {
+// trap_S_StartSound (re->origin, ENTITYNUM_WORLD, CHAN_AUTO, cgs.media.kamikazeImplodeSound );
+ trap_S_StartLocalSound(cgs.media.kamikazeImplodeSound, CHAN_AUTO);
+ le->leFlags |= LEF_SOUND2;
+ }
+ c = (float)(KAMI_IMPLODE_ENDTIME - t) / (float) (KAMI_IMPLODE_ENDTIME - KAMI_IMPLODE_STARTTIME);
+ }
+ VectorScale( axis[0], c * KAMI_BOOMSPHERE_MAXRADIUS / KAMI_BOOMSPHEREMODEL_RADIUS, re->axis[0] );
+ VectorScale( axis[1], c * KAMI_BOOMSPHERE_MAXRADIUS / KAMI_BOOMSPHEREMODEL_RADIUS, re->axis[1] );
+ VectorScale( axis[2], c * KAMI_BOOMSPHERE_MAXRADIUS / KAMI_BOOMSPHEREMODEL_RADIUS, re->axis[2] );
+ re->nonNormalizedAxes = qtrue;
+
+ trap_R_AddRefEntityToScene( re );
+ // add the dlight
+ trap_R_AddLightToScene( re->origin, c * 1000.0, 1.0, 1.0, c );
+ }
+
+ if (t > KAMI_SHOCKWAVE2_STARTTIME && t < KAMI_SHOCKWAVE2_ENDTIME) {
+ // 2nd kamikaze shockwave
+ if (le->angles.trBase[0] == 0 &&
+ le->angles.trBase[1] == 0 &&
+ le->angles.trBase[2] == 0) {
+ le->angles.trBase[0] = random() * 360;
+ le->angles.trBase[1] = random() * 360;
+ le->angles.trBase[2] = random() * 360;
+ }
+ else {
+ c = 0;
+ }
+ memset(&shockwave, 0, sizeof(shockwave));
+ shockwave.hModel = cgs.media.kamikazeShockWave;
+ shockwave.reType = RT_MODEL;
+ shockwave.shaderTime = re->shaderTime;
+ VectorCopy(re->origin, shockwave.origin);
+
+ test[0] = le->angles.trBase[0];
+ test[1] = le->angles.trBase[1];
+ test[2] = le->angles.trBase[2];
+ AnglesToAxis( test, axis );
+
+ c = (float)(t - KAMI_SHOCKWAVE2_STARTTIME) / (float)(KAMI_SHOCKWAVE2_ENDTIME - KAMI_SHOCKWAVE2_STARTTIME);
+ VectorScale( axis[0], c * KAMI_SHOCKWAVE2_MAXRADIUS / KAMI_SHOCKWAVEMODEL_RADIUS, shockwave.axis[0] );
+ VectorScale( axis[1], c * KAMI_SHOCKWAVE2_MAXRADIUS / KAMI_SHOCKWAVEMODEL_RADIUS, shockwave.axis[1] );
+ VectorScale( axis[2], c * KAMI_SHOCKWAVE2_MAXRADIUS / KAMI_SHOCKWAVEMODEL_RADIUS, shockwave.axis[2] );
+ shockwave.nonNormalizedAxes = qtrue;
+
+ if (t > KAMI_SHOCKWAVE2FADE_STARTTIME) {
+ c = (float)(t - KAMI_SHOCKWAVE2FADE_STARTTIME) / (float)(KAMI_SHOCKWAVE2_ENDTIME - KAMI_SHOCKWAVE2FADE_STARTTIME);
+ }
+ else {
+ c = 0;
+ }
+ c *= 0xff;
+ shockwave.shaderRGBA[0] = 0xff - c;
+ shockwave.shaderRGBA[1] = 0xff - c;
+ shockwave.shaderRGBA[2] = 0xff - c;
+ shockwave.shaderRGBA[3] = 0xff - c;
+
+ trap_R_AddRefEntityToScene( &shockwave );
+ }
+}
+
+/*
+===================
+CG_AddInvulnerabilityImpact
+===================
+*/
+void CG_AddInvulnerabilityImpact( localEntity_t *le ) {
+ trap_R_AddRefEntityToScene( &le->refEntity );
+}
+
+/*
+===================
+CG_AddInvulnerabilityJuiced
+===================
+*/
+void CG_AddInvulnerabilityJuiced( localEntity_t *le ) {
+ int t;
+
+ t = cg.time - le->startTime;
+ if ( t > 3000 ) {
+ le->refEntity.axis[0][0] = (float) 1.0 + 0.3 * (t - 3000) / 2000;
+ le->refEntity.axis[1][1] = (float) 1.0 + 0.3 * (t - 3000) / 2000;
+ le->refEntity.axis[2][2] = (float) 0.7 + 0.3 * (2000 - (t - 3000)) / 2000;
+ }
+ if ( t > 5000 ) {
+ le->endTime = 0;
+ CG_GibPlayer( le->refEntity.origin );
+ }
+ else {
+ trap_R_AddRefEntityToScene( &le->refEntity );
+ }
+}
+
+/*
+===================
+CG_AddRefEntity
+===================
+*/
+void CG_AddRefEntity( localEntity_t *le ) {
+ if (le->endTime < cg.time) {
+ CG_FreeLocalEntity( le );
+ return;
+ }
+ trap_R_AddRefEntityToScene( &le->refEntity );
+}
+
+#endif
+/*
+===================
+CG_AddScorePlum
+===================
+*/
+#define NUMBER_SIZE 8
+
+void CG_AddScorePlum( localEntity_t *le ) {
+ refEntity_t *re;
+ vec3_t origin, delta, dir, vec, up = {0, 0, 1};
+ float c, len;
+ int i, score, digits[10], numdigits, negative;
+
+ re = &le->refEntity;
+
+ c = ( le->endTime - cg.time ) * le->lifeRate;
+
+ score = le->radius;
+ if (score < 0) {
+ re->shaderRGBA[0] = 0xff;
+ re->shaderRGBA[1] = 0x11;
+ re->shaderRGBA[2] = 0x11;
+ }
+ else {
+ re->shaderRGBA[0] = 0xff;
+ re->shaderRGBA[1] = 0xff;
+ re->shaderRGBA[2] = 0xff;
+ if (score >= 50) {
+ re->shaderRGBA[1] = 0;
+ } else if (score >= 20) {
+ re->shaderRGBA[0] = re->shaderRGBA[1] = 0;
+ } else if (score >= 10) {
+ re->shaderRGBA[2] = 0;
+ } else if (score >= 2) {
+ re->shaderRGBA[0] = re->shaderRGBA[2] = 0;
+ }
+
+ }
+ if (c < 0.25)
+ re->shaderRGBA[3] = 0xff * 4 * c;
+ else
+ re->shaderRGBA[3] = 0xff;
+
+ re->radius = NUMBER_SIZE / 2;
+
+ VectorCopy(le->pos.trBase, origin);
+ origin[2] += 110 - c * 100;
+
+ VectorSubtract(cg.refdef.vieworg, origin, dir);
+ CrossProduct(dir, up, vec);
+ VectorNormalize(vec);
+
+ VectorMA(origin, -10 + 20 * sin(c * 2 * M_PI), vec, origin);
+
+ // if the view would be "inside" the sprite, kill the sprite
+ // so it doesn't add too much overdraw
+ VectorSubtract( origin, cg.refdef.vieworg, delta );
+ len = VectorLength( delta );
+ if ( len < 20 ) {
+ CG_FreeLocalEntity( le );
+ return;
+ }
+
+ negative = qfalse;
+ if (score < 0) {
+ negative = qtrue;
+ score = -score;
+ }
+
+ for (numdigits = 0; !(numdigits && !score); numdigits++) {
+ digits[numdigits] = score % 10;
+ score = score / 10;
+ }
+
+ if (negative) {
+ digits[numdigits] = 10;
+ numdigits++;
+ }
+
+ for (i = 0; i < numdigits; i++) {
+ VectorMA(origin, (float) (((float) numdigits / 2) - i) * NUMBER_SIZE, vec, re->origin);
+ re->customShader = cgs.media.numberShaders[digits[numdigits-1-i]];
+ trap_R_AddRefEntityToScene( re );
+ }
+}
+
+
+
+
+//==============================================================================
+
+/*
+===================
+CG_AddLocalEntities
+
+===================
+*/
+void CG_AddLocalEntities( void ) {
+ localEntity_t *le, *next;
+
+ // walk the list backwards, so any new local entities generated
+ // (trails, marks, etc) will be present this frame
+ le = cg_activeLocalEntities.prev;
+ for ( ; le != &cg_activeLocalEntities ; le = next ) {
+ // grab next now, so if the local entity is freed we
+ // still have it
+ next = le->prev;
+
+ if ( cg.time >= le->endTime ) {
+ CG_FreeLocalEntity( le );
+ continue;
+ }
+ switch ( le->leType ) {
+ default:
+ CG_Error( "Bad leType: %i", le->leType );
+ break;
+
+ case LE_MARK:
+ break;
+
+ case LE_SPRITE_EXPLOSION:
+ CG_AddSpriteExplosion( le );
+ break;
+
+ case LE_EXPLOSION:
+ CG_AddExplosion( le );
+ break;
+
+ case LE_FRAGMENT: // gibs and brass
+ CG_AddFragment( le );
+ break;
+
+ case LE_MOVE_SCALE_FADE: // water bubbles
+ CG_AddMoveScaleFade( le );
+ break;
+
+ case LE_FADE_RGB: // teleporters, railtrails
+ CG_AddFadeRGB( le );
+ break;
+
+ case LE_FALL_SCALE_FADE: // gib blood trails
+ CG_AddFallScaleFade( le );
+ break;
+
+ case LE_SCALE_FADE: // rocket trails
+ CG_AddScaleFade( le );
+ break;
+
+ case LE_SCOREPLUM:
+ CG_AddScorePlum( le );
+ break;
+
+#ifdef MISSIONPACK
+ case LE_KAMIKAZE:
+ CG_AddKamikaze( le );
+ break;
+ case LE_INVULIMPACT:
+ CG_AddInvulnerabilityImpact( le );
+ break;
+ case LE_INVULJUICED:
+ CG_AddInvulnerabilityJuiced( le );
+ break;
+ case LE_SHOWREFENTITY:
+ CG_AddRefEntity( le );
+ break;
+#endif
+ }
+ }
+}
+
+
+
+
diff --git a/code/cgame/cg_main.c b/code/cgame/cg_main.c
new file mode 100755
index 0000000..aa9ec27
--- /dev/null
+++ b/code/cgame/cg_main.c
@@ -0,0 +1,1997 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// cg_main.c -- initialization and primary entry point for cgame
+#include "cg_local.h"
+
+#ifdef MISSIONPACK
+#include "../ui/ui_shared.h"
+// display context for new ui stuff
+displayContextDef_t cgDC;
+#endif
+
+int forceModelModificationCount = -1;
+
+void CG_Init( int serverMessageNum, int serverCommandSequence, int clientNum );
+void CG_Shutdown( void );
+
+
+/*
+================
+vmMain
+
+This is the only way control passes into the module.
+This must be the very first function compiled into the .q3vm file
+================
+*/
+int vmMain( int command, int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11 ) {
+
+ switch ( command ) {
+ case CG_INIT:
+ CG_Init( arg0, arg1, arg2 );
+ return 0;
+ case CG_SHUTDOWN:
+ CG_Shutdown();
+ return 0;
+ case CG_CONSOLE_COMMAND:
+ return CG_ConsoleCommand();
+ case CG_DRAW_ACTIVE_FRAME:
+ CG_DrawActiveFrame( arg0, arg1, arg2 );
+ return 0;
+ case CG_CROSSHAIR_PLAYER:
+ return CG_CrosshairPlayer();
+ case CG_LAST_ATTACKER:
+ return CG_LastAttacker();
+ case CG_KEY_EVENT:
+ CG_KeyEvent(arg0, arg1);
+ return 0;
+ case CG_MOUSE_EVENT:
+#ifdef MISSIONPACK
+ cgDC.cursorx = cgs.cursorX;
+ cgDC.cursory = cgs.cursorY;
+#endif
+ CG_MouseEvent(arg0, arg1);
+ return 0;
+ case CG_EVENT_HANDLING:
+ CG_EventHandling(arg0);
+ return 0;
+ default:
+ CG_Error( "vmMain: unknown command %i", command );
+ break;
+ }
+ return -1;
+}
+
+
+cg_t cg;
+cgs_t cgs;
+centity_t cg_entities[MAX_GENTITIES];
+weaponInfo_t cg_weapons[MAX_WEAPONS];
+itemInfo_t cg_items[MAX_ITEMS];
+
+
+vmCvar_t cg_railTrailTime;
+vmCvar_t cg_centertime;
+vmCvar_t cg_runpitch;
+vmCvar_t cg_runroll;
+vmCvar_t cg_bobup;
+vmCvar_t cg_bobpitch;
+vmCvar_t cg_bobroll;
+vmCvar_t cg_swingSpeed;
+vmCvar_t cg_shadows;
+vmCvar_t cg_gibs;
+vmCvar_t cg_drawTimer;
+vmCvar_t cg_drawFPS;
+vmCvar_t cg_drawSnapshot;
+vmCvar_t cg_draw3dIcons;
+vmCvar_t cg_drawIcons;
+vmCvar_t cg_drawAmmoWarning;
+vmCvar_t cg_drawCrosshair;
+vmCvar_t cg_drawCrosshairNames;
+vmCvar_t cg_drawRewards;
+vmCvar_t cg_crosshairSize;
+vmCvar_t cg_crosshairX;
+vmCvar_t cg_crosshairY;
+vmCvar_t cg_crosshairHealth;
+vmCvar_t cg_draw2D;
+vmCvar_t cg_drawStatus;
+vmCvar_t cg_animSpeed;
+vmCvar_t cg_debugAnim;
+vmCvar_t cg_debugPosition;
+vmCvar_t cg_debugEvents;
+vmCvar_t cg_errorDecay;
+vmCvar_t cg_nopredict;
+vmCvar_t cg_noPlayerAnims;
+vmCvar_t cg_showmiss;
+vmCvar_t cg_footsteps;
+vmCvar_t cg_addMarks;
+vmCvar_t cg_brassTime;
+vmCvar_t cg_viewsize;
+vmCvar_t cg_drawGun;
+vmCvar_t cg_gun_frame;
+vmCvar_t cg_gun_x;
+vmCvar_t cg_gun_y;
+vmCvar_t cg_gun_z;
+vmCvar_t cg_tracerChance;
+vmCvar_t cg_tracerWidth;
+vmCvar_t cg_tracerLength;
+vmCvar_t cg_autoswitch;
+vmCvar_t cg_ignore;
+vmCvar_t cg_simpleItems;
+vmCvar_t cg_fov;
+vmCvar_t cg_zoomFov;
+vmCvar_t cg_thirdPerson;
+vmCvar_t cg_thirdPersonRange;
+vmCvar_t cg_thirdPersonAngle;
+vmCvar_t cg_stereoSeparation;
+vmCvar_t cg_lagometer;
+vmCvar_t cg_drawAttacker;
+vmCvar_t cg_synchronousClients;
+vmCvar_t cg_teamChatTime;
+vmCvar_t cg_teamChatHeight;
+vmCvar_t cg_stats;
+vmCvar_t cg_buildScript;
+vmCvar_t cg_forceModel;
+vmCvar_t cg_paused;
+vmCvar_t cg_blood;
+vmCvar_t cg_predictItems;
+vmCvar_t cg_deferPlayers;
+vmCvar_t cg_drawTeamOverlay;
+vmCvar_t cg_teamOverlayUserinfo;
+vmCvar_t cg_drawFriend;
+vmCvar_t cg_teamChatsOnly;
+vmCvar_t cg_noVoiceChats;
+vmCvar_t cg_noVoiceText;
+vmCvar_t cg_hudFiles;
+vmCvar_t cg_scorePlum;
+vmCvar_t cg_smoothClients;
+vmCvar_t pmove_fixed;
+//vmCvar_t cg_pmove_fixed;
+vmCvar_t pmove_msec;
+vmCvar_t cg_pmove_msec;
+vmCvar_t cg_cameraMode;
+vmCvar_t cg_cameraOrbit;
+vmCvar_t cg_cameraOrbitDelay;
+vmCvar_t cg_timescaleFadeEnd;
+vmCvar_t cg_timescaleFadeSpeed;
+vmCvar_t cg_timescale;
+vmCvar_t cg_smallFont;
+vmCvar_t cg_bigFont;
+vmCvar_t cg_noTaunt;
+vmCvar_t cg_noProjectileTrail;
+vmCvar_t cg_oldRail;
+vmCvar_t cg_oldRocket;
+vmCvar_t cg_oldPlasma;
+vmCvar_t cg_trueLightning;
+
+#ifdef MISSIONPACK
+vmCvar_t cg_redTeamName;
+vmCvar_t cg_blueTeamName;
+vmCvar_t cg_currentSelectedPlayer;
+vmCvar_t cg_currentSelectedPlayerName;
+vmCvar_t cg_singlePlayer;
+vmCvar_t cg_enableDust;
+vmCvar_t cg_enableBreath;
+vmCvar_t cg_singlePlayerActive;
+vmCvar_t cg_recordSPDemo;
+vmCvar_t cg_recordSPDemoName;
+vmCvar_t cg_obeliskRespawnDelay;
+#endif
+
+typedef struct {
+ vmCvar_t *vmCvar;
+ char *cvarName;
+ char *defaultString;
+ int cvarFlags;
+} cvarTable_t;
+
+static cvarTable_t cvarTable[] = { // bk001129
+ { &cg_ignore, "cg_ignore", "0", 0 }, // used for debugging
+ { &cg_autoswitch, "cg_autoswitch", "1", CVAR_ARCHIVE },
+ { &cg_drawGun, "cg_drawGun", "1", CVAR_ARCHIVE },
+ { &cg_zoomFov, "cg_zoomfov", "22.5", CVAR_ARCHIVE },
+ { &cg_fov, "cg_fov", "90", CVAR_ARCHIVE },
+ { &cg_viewsize, "cg_viewsize", "100", CVAR_ARCHIVE },
+ { &cg_stereoSeparation, "cg_stereoSeparation", "0.4", CVAR_ARCHIVE },
+ { &cg_shadows, "cg_shadows", "1", CVAR_ARCHIVE },
+ { &cg_gibs, "cg_gibs", "1", CVAR_ARCHIVE },
+ { &cg_draw2D, "cg_draw2D", "1", CVAR_ARCHIVE },
+ { &cg_drawStatus, "cg_drawStatus", "1", CVAR_ARCHIVE },
+ { &cg_drawTimer, "cg_drawTimer", "0", CVAR_ARCHIVE },
+ { &cg_drawFPS, "cg_drawFPS", "0", CVAR_ARCHIVE },
+ { &cg_drawSnapshot, "cg_drawSnapshot", "0", CVAR_ARCHIVE },
+ { &cg_draw3dIcons, "cg_draw3dIcons", "1", CVAR_ARCHIVE },
+ { &cg_drawIcons, "cg_drawIcons", "1", CVAR_ARCHIVE },
+ { &cg_drawAmmoWarning, "cg_drawAmmoWarning", "1", CVAR_ARCHIVE },
+ { &cg_drawAttacker, "cg_drawAttacker", "1", CVAR_ARCHIVE },
+ { &cg_drawCrosshair, "cg_drawCrosshair", "4", CVAR_ARCHIVE },
+ { &cg_drawCrosshairNames, "cg_drawCrosshairNames", "1", CVAR_ARCHIVE },
+ { &cg_drawRewards, "cg_drawRewards", "1", CVAR_ARCHIVE },
+ { &cg_crosshairSize, "cg_crosshairSize", "24", CVAR_ARCHIVE },
+ { &cg_crosshairHealth, "cg_crosshairHealth", "1", CVAR_ARCHIVE },
+ { &cg_crosshairX, "cg_crosshairX", "0", CVAR_ARCHIVE },
+ { &cg_crosshairY, "cg_crosshairY", "0", CVAR_ARCHIVE },
+ { &cg_brassTime, "cg_brassTime", "2500", CVAR_ARCHIVE },
+ { &cg_simpleItems, "cg_simpleItems", "0", CVAR_ARCHIVE },
+ { &cg_addMarks, "cg_marks", "1", CVAR_ARCHIVE },
+ { &cg_lagometer, "cg_lagometer", "1", CVAR_ARCHIVE },
+ { &cg_railTrailTime, "cg_railTrailTime", "400", CVAR_ARCHIVE },
+ { &cg_gun_x, "cg_gunX", "0", CVAR_CHEAT },
+ { &cg_gun_y, "cg_gunY", "0", CVAR_CHEAT },
+ { &cg_gun_z, "cg_gunZ", "0", CVAR_CHEAT },
+ { &cg_centertime, "cg_centertime", "3", CVAR_CHEAT },
+ { &cg_runpitch, "cg_runpitch", "0.002", CVAR_ARCHIVE},
+ { &cg_runroll, "cg_runroll", "0.005", CVAR_ARCHIVE },
+ { &cg_bobup , "cg_bobup", "0.005", CVAR_CHEAT },
+ { &cg_bobpitch, "cg_bobpitch", "0.002", CVAR_ARCHIVE },
+ { &cg_bobroll, "cg_bobroll", "0.002", CVAR_ARCHIVE },
+ { &cg_swingSpeed, "cg_swingSpeed", "0.3", CVAR_CHEAT },
+ { &cg_animSpeed, "cg_animspeed", "1", CVAR_CHEAT },
+ { &cg_debugAnim, "cg_debuganim", "0", CVAR_CHEAT },
+ { &cg_debugPosition, "cg_debugposition", "0", CVAR_CHEAT },
+ { &cg_debugEvents, "cg_debugevents", "0", CVAR_CHEAT },
+ { &cg_errorDecay, "cg_errordecay", "100", 0 },
+ { &cg_nopredict, "cg_nopredict", "0", 0 },
+ { &cg_noPlayerAnims, "cg_noplayeranims", "0", CVAR_CHEAT },
+ { &cg_showmiss, "cg_showmiss", "0", 0 },
+ { &cg_footsteps, "cg_footsteps", "1", CVAR_CHEAT },
+ { &cg_tracerChance, "cg_tracerchance", "0.4", CVAR_CHEAT },
+ { &cg_tracerWidth, "cg_tracerwidth", "1", CVAR_CHEAT },
+ { &cg_tracerLength, "cg_tracerlength", "100", CVAR_CHEAT },
+ { &cg_thirdPersonRange, "cg_thirdPersonRange", "40", CVAR_CHEAT },
+ { &cg_thirdPersonAngle, "cg_thirdPersonAngle", "0", CVAR_CHEAT },
+ { &cg_thirdPerson, "cg_thirdPerson", "0", 0 },
+ { &cg_teamChatTime, "cg_teamChatTime", "3000", CVAR_ARCHIVE },
+ { &cg_teamChatHeight, "cg_teamChatHeight", "0", CVAR_ARCHIVE },
+ { &cg_forceModel, "cg_forceModel", "0", CVAR_ARCHIVE },
+ { &cg_predictItems, "cg_predictItems", "1", CVAR_ARCHIVE },
+#ifdef MISSIONPACK
+ { &cg_deferPlayers, "cg_deferPlayers", "0", CVAR_ARCHIVE },
+#else
+ { &cg_deferPlayers, "cg_deferPlayers", "1", CVAR_ARCHIVE },
+#endif
+ { &cg_drawTeamOverlay, "cg_drawTeamOverlay", "0", CVAR_ARCHIVE },
+ { &cg_teamOverlayUserinfo, "teamoverlay", "0", CVAR_ROM | CVAR_USERINFO },
+ { &cg_stats, "cg_stats", "0", 0 },
+ { &cg_drawFriend, "cg_drawFriend", "1", CVAR_ARCHIVE },
+ { &cg_teamChatsOnly, "cg_teamChatsOnly", "0", CVAR_ARCHIVE },
+ { &cg_noVoiceChats, "cg_noVoiceChats", "0", CVAR_ARCHIVE },
+ { &cg_noVoiceText, "cg_noVoiceText", "0", CVAR_ARCHIVE },
+ // the following variables are created in other parts of the system,
+ // but we also reference them here
+ { &cg_buildScript, "com_buildScript", "0", 0 }, // force loading of all possible data amd error on failures
+ { &cg_paused, "cl_paused", "0", CVAR_ROM },
+ { &cg_blood, "com_blood", "1", CVAR_ARCHIVE },
+ { &cg_synchronousClients, "g_synchronousClients", "0", 0 }, // communicated by systeminfo
+#ifdef MISSIONPACK
+ { &cg_redTeamName, "g_redteam", DEFAULT_REDTEAM_NAME, CVAR_ARCHIVE | CVAR_SERVERINFO | CVAR_USERINFO },
+ { &cg_blueTeamName, "g_blueteam", DEFAULT_BLUETEAM_NAME, CVAR_ARCHIVE | CVAR_SERVERINFO | CVAR_USERINFO },
+ { &cg_currentSelectedPlayer, "cg_currentSelectedPlayer", "0", CVAR_ARCHIVE},
+ { &cg_currentSelectedPlayerName, "cg_currentSelectedPlayerName", "", CVAR_ARCHIVE},
+ { &cg_singlePlayer, "ui_singlePlayerActive", "0", CVAR_USERINFO},
+ { &cg_enableDust, "g_enableDust", "0", CVAR_SERVERINFO},
+ { &cg_enableBreath, "g_enableBreath", "0", CVAR_SERVERINFO},
+ { &cg_singlePlayerActive, "ui_singlePlayerActive", "0", CVAR_USERINFO},
+ { &cg_recordSPDemo, "ui_recordSPDemo", "0", CVAR_ARCHIVE},
+ { &cg_recordSPDemoName, "ui_recordSPDemoName", "", CVAR_ARCHIVE},
+ { &cg_obeliskRespawnDelay, "g_obeliskRespawnDelay", "10", CVAR_SERVERINFO},
+ { &cg_hudFiles, "cg_hudFiles", "ui/hud.txt", CVAR_ARCHIVE},
+#endif
+ { &cg_cameraOrbit, "cg_cameraOrbit", "0", CVAR_CHEAT},
+ { &cg_cameraOrbitDelay, "cg_cameraOrbitDelay", "50", CVAR_ARCHIVE},
+ { &cg_timescaleFadeEnd, "cg_timescaleFadeEnd", "1", 0},
+ { &cg_timescaleFadeSpeed, "cg_timescaleFadeSpeed", "0", 0},
+ { &cg_timescale, "timescale", "1", 0},
+ { &cg_scorePlum, "cg_scorePlums", "1", CVAR_USERINFO | CVAR_ARCHIVE},
+ { &cg_smoothClients, "cg_smoothClients", "0", CVAR_USERINFO | CVAR_ARCHIVE},
+ { &cg_cameraMode, "com_cameraMode", "0", CVAR_CHEAT},
+
+ { &pmove_fixed, "pmove_fixed", "0", 0},
+ { &pmove_msec, "pmove_msec", "8", 0},
+ { &cg_noTaunt, "cg_noTaunt", "0", CVAR_ARCHIVE},
+ { &cg_noProjectileTrail, "cg_noProjectileTrail", "0", CVAR_ARCHIVE},
+ { &cg_smallFont, "ui_smallFont", "0.25", CVAR_ARCHIVE},
+ { &cg_bigFont, "ui_bigFont", "0.4", CVAR_ARCHIVE},
+ { &cg_oldRail, "cg_oldRail", "1", CVAR_ARCHIVE},
+ { &cg_oldRocket, "cg_oldRocket", "1", CVAR_ARCHIVE},
+ { &cg_oldPlasma, "cg_oldPlasma", "1", CVAR_ARCHIVE},
+ { &cg_trueLightning, "cg_trueLightning", "0.0", CVAR_ARCHIVE}
+// { &cg_pmove_fixed, "cg_pmove_fixed", "0", CVAR_USERINFO | CVAR_ARCHIVE }
+};
+
+static int cvarTableSize = sizeof( cvarTable ) / sizeof( cvarTable[0] );
+
+/*
+=================
+CG_RegisterCvars
+=================
+*/
+void CG_RegisterCvars( void ) {
+ int i;
+ cvarTable_t *cv;
+ char var[MAX_TOKEN_CHARS];
+
+ for ( i = 0, cv = cvarTable ; i < cvarTableSize ; i++, cv++ ) {
+ trap_Cvar_Register( cv->vmCvar, cv->cvarName,
+ cv->defaultString, cv->cvarFlags );
+ }
+
+ // see if we are also running the server on this machine
+ trap_Cvar_VariableStringBuffer( "sv_running", var, sizeof( var ) );
+ cgs.localServer = atoi( var );
+
+ forceModelModificationCount = cg_forceModel.modificationCount;
+
+ trap_Cvar_Register(NULL, "model", DEFAULT_MODEL, CVAR_USERINFO | CVAR_ARCHIVE );
+ trap_Cvar_Register(NULL, "headmodel", DEFAULT_MODEL, CVAR_USERINFO | CVAR_ARCHIVE );
+ trap_Cvar_Register(NULL, "team_model", DEFAULT_TEAM_MODEL, CVAR_USERINFO | CVAR_ARCHIVE );
+ trap_Cvar_Register(NULL, "team_headmodel", DEFAULT_TEAM_HEAD, CVAR_USERINFO | CVAR_ARCHIVE );
+}
+
+/*
+===================
+CG_ForceModelChange
+===================
+*/
+static void CG_ForceModelChange( void ) {
+ int i;
+
+ for (i=0 ; i<MAX_CLIENTS ; i++) {
+ const char *clientInfo;
+
+ clientInfo = CG_ConfigString( CS_PLAYERS+i );
+ if ( !clientInfo[0] ) {
+ continue;
+ }
+ CG_NewClientInfo( i );
+ }
+}
+
+/*
+=================
+CG_UpdateCvars
+=================
+*/
+void CG_UpdateCvars( void ) {
+ int i;
+ cvarTable_t *cv;
+
+ for ( i = 0, cv = cvarTable ; i < cvarTableSize ; i++, cv++ ) {
+ trap_Cvar_Update( cv->vmCvar );
+ }
+
+ // check for modications here
+
+ // If team overlay is on, ask for updates from the server. If its off,
+ // let the server know so we don't receive it
+ if ( drawTeamOverlayModificationCount != cg_drawTeamOverlay.modificationCount ) {
+ drawTeamOverlayModificationCount = cg_drawTeamOverlay.modificationCount;
+
+ if ( cg_drawTeamOverlay.integer > 0 ) {
+ trap_Cvar_Set( "teamoverlay", "1" );
+ } else {
+ trap_Cvar_Set( "teamoverlay", "0" );
+ }
+ // FIXME E3 HACK
+ trap_Cvar_Set( "teamoverlay", "1" );
+ }
+
+ // if force model changed
+ if ( forceModelModificationCount != cg_forceModel.modificationCount ) {
+ forceModelModificationCount = cg_forceModel.modificationCount;
+ CG_ForceModelChange();
+ }
+}
+
+int CG_CrosshairPlayer( void ) {
+ if ( cg.time > ( cg.crosshairClientTime + 1000 ) ) {
+ return -1;
+ }
+ return cg.crosshairClientNum;
+}
+
+int CG_LastAttacker( void ) {
+ if ( !cg.attackerTime ) {
+ return -1;
+ }
+ return cg.snap->ps.persistant[PERS_ATTACKER];
+}
+
+void QDECL CG_Printf( const char *msg, ... ) {
+ va_list argptr;
+ char text[1024];
+
+ va_start (argptr, msg);
+ vsprintf (text, msg, argptr);
+ va_end (argptr);
+
+ trap_Print( text );
+}
+
+void QDECL CG_Error( const char *msg, ... ) {
+ va_list argptr;
+ char text[1024];
+
+ va_start (argptr, msg);
+ vsprintf (text, msg, argptr);
+ va_end (argptr);
+
+ trap_Error( text );
+}
+
+#ifndef CGAME_HARD_LINKED
+// this is only here so the functions in q_shared.c and bg_*.c can link (FIXME)
+
+void QDECL Com_Error( int level, const char *error, ... ) {
+ va_list argptr;
+ char text[1024];
+
+ va_start (argptr, error);
+ vsprintf (text, error, argptr);
+ va_end (argptr);
+
+ CG_Error( "%s", text);
+}
+
+void QDECL Com_Printf( const char *msg, ... ) {
+ va_list argptr;
+ char text[1024];
+
+ va_start (argptr, msg);
+ vsprintf (text, msg, argptr);
+ va_end (argptr);
+
+ CG_Printf ("%s", text);
+}
+
+#endif
+
+/*
+================
+CG_Argv
+================
+*/
+const char *CG_Argv( int arg ) {
+ static char buffer[MAX_STRING_CHARS];
+
+ trap_Argv( arg, buffer, sizeof( buffer ) );
+
+ return buffer;
+}
+
+
+//========================================================================
+
+/*
+=================
+CG_RegisterItemSounds
+
+The server says this item is used on this level
+=================
+*/
+static void CG_RegisterItemSounds( int itemNum ) {
+ gitem_t *item;
+ char data[MAX_QPATH];
+ char *s, *start;
+ int len;
+
+ item = &bg_itemlist[ itemNum ];
+
+ if( item->pickup_sound ) {
+ trap_S_RegisterSound( item->pickup_sound, qfalse );
+ }
+
+ // parse the space seperated precache string for other media
+ s = item->sounds;
+ if (!s || !s[0])
+ return;
+
+ while (*s) {
+ start = s;
+ while (*s && *s != ' ') {
+ s++;
+ }
+
+ len = s-start;
+ if (len >= MAX_QPATH || len < 5) {
+ CG_Error( "PrecacheItem: %s has bad precache string",
+ item->classname);
+ return;
+ }
+ memcpy (data, start, len);
+ data[len] = 0;
+ if ( *s ) {
+ s++;
+ }
+
+ if ( !strcmp(data+len-3, "wav" )) {
+ trap_S_RegisterSound( data, qfalse );
+ }
+ }
+}
+
+
+/*
+=================
+CG_RegisterSounds
+
+called during a precache command
+=================
+*/
+static void CG_RegisterSounds( void ) {
+ int i;
+ char items[MAX_ITEMS+1];
+ char name[MAX_QPATH];
+ const char *soundName;
+
+ // voice commands
+#ifdef MISSIONPACK
+ CG_LoadVoiceChats();
+#endif
+
+ cgs.media.oneMinuteSound = trap_S_RegisterSound( "sound/feedback/1_minute.wav", qtrue );
+ cgs.media.fiveMinuteSound = trap_S_RegisterSound( "sound/feedback/5_minute.wav", qtrue );
+ cgs.media.suddenDeathSound = trap_S_RegisterSound( "sound/feedback/sudden_death.wav", qtrue );
+ cgs.media.oneFragSound = trap_S_RegisterSound( "sound/feedback/1_frag.wav", qtrue );
+ cgs.media.twoFragSound = trap_S_RegisterSound( "sound/feedback/2_frags.wav", qtrue );
+ cgs.media.threeFragSound = trap_S_RegisterSound( "sound/feedback/3_frags.wav", qtrue );
+ cgs.media.count3Sound = trap_S_RegisterSound( "sound/feedback/three.wav", qtrue );
+ cgs.media.count2Sound = trap_S_RegisterSound( "sound/feedback/two.wav", qtrue );
+ cgs.media.count1Sound = trap_S_RegisterSound( "sound/feedback/one.wav", qtrue );
+ cgs.media.countFightSound = trap_S_RegisterSound( "sound/feedback/fight.wav", qtrue );
+ cgs.media.countPrepareSound = trap_S_RegisterSound( "sound/feedback/prepare.wav", qtrue );
+#ifdef MISSIONPACK
+ cgs.media.countPrepareTeamSound = trap_S_RegisterSound( "sound/feedback/prepare_team.wav", qtrue );
+#endif
+
+ if ( cgs.gametype >= GT_TEAM || cg_buildScript.integer ) {
+
+ cgs.media.captureAwardSound = trap_S_RegisterSound( "sound/teamplay/flagcapture_yourteam.wav", qtrue );
+ cgs.media.redLeadsSound = trap_S_RegisterSound( "sound/feedback/redleads.wav", qtrue );
+ cgs.media.blueLeadsSound = trap_S_RegisterSound( "sound/feedback/blueleads.wav", qtrue );
+ cgs.media.teamsTiedSound = trap_S_RegisterSound( "sound/feedback/teamstied.wav", qtrue );
+ cgs.media.hitTeamSound = trap_S_RegisterSound( "sound/feedback/hit_teammate.wav", qtrue );
+
+ cgs.media.redScoredSound = trap_S_RegisterSound( "sound/teamplay/voc_red_scores.wav", qtrue );
+ cgs.media.blueScoredSound = trap_S_RegisterSound( "sound/teamplay/voc_blue_scores.wav", qtrue );
+
+ cgs.media.captureYourTeamSound = trap_S_RegisterSound( "sound/teamplay/flagcapture_yourteam.wav", qtrue );
+ cgs.media.captureOpponentSound = trap_S_RegisterSound( "sound/teamplay/flagcapture_opponent.wav", qtrue );
+
+ cgs.media.returnYourTeamSound = trap_S_RegisterSound( "sound/teamplay/flagreturn_yourteam.wav", qtrue );
+ cgs.media.returnOpponentSound = trap_S_RegisterSound( "sound/teamplay/flagreturn_opponent.wav", qtrue );
+
+ cgs.media.takenYourTeamSound = trap_S_RegisterSound( "sound/teamplay/flagtaken_yourteam.wav", qtrue );
+ cgs.media.takenOpponentSound = trap_S_RegisterSound( "sound/teamplay/flagtaken_opponent.wav", qtrue );
+
+ if ( cgs.gametype == GT_CTF || cg_buildScript.integer ) {
+ cgs.media.redFlagReturnedSound = trap_S_RegisterSound( "sound/teamplay/voc_red_returned.wav", qtrue );
+ cgs.media.blueFlagReturnedSound = trap_S_RegisterSound( "sound/teamplay/voc_blue_returned.wav", qtrue );
+ cgs.media.enemyTookYourFlagSound = trap_S_RegisterSound( "sound/teamplay/voc_enemy_flag.wav", qtrue );
+ cgs.media.yourTeamTookEnemyFlagSound = trap_S_RegisterSound( "sound/teamplay/voc_team_flag.wav", qtrue );
+ }
+
+#ifdef MISSIONPACK
+ if ( cgs.gametype == GT_1FCTF || cg_buildScript.integer ) {
+ // FIXME: get a replacement for this sound ?
+ cgs.media.neutralFlagReturnedSound = trap_S_RegisterSound( "sound/teamplay/flagreturn_opponent.wav", qtrue );
+ cgs.media.yourTeamTookTheFlagSound = trap_S_RegisterSound( "sound/teamplay/voc_team_1flag.wav", qtrue );
+ cgs.media.enemyTookTheFlagSound = trap_S_RegisterSound( "sound/teamplay/voc_enemy_1flag.wav", qtrue );
+ }
+
+ if ( cgs.gametype == GT_1FCTF || cgs.gametype == GT_CTF || cg_buildScript.integer ) {
+ cgs.media.youHaveFlagSound = trap_S_RegisterSound( "sound/teamplay/voc_you_flag.wav", qtrue );
+ cgs.media.holyShitSound = trap_S_RegisterSound("sound/feedback/voc_holyshit.wav", qtrue);
+ }
+
+ if ( cgs.gametype == GT_OBELISK || cg_buildScript.integer ) {
+ cgs.media.yourBaseIsUnderAttackSound = trap_S_RegisterSound( "sound/teamplay/voc_base_attack.wav", qtrue );
+ }
+#else
+ cgs.media.youHaveFlagSound = trap_S_RegisterSound( "sound/teamplay/voc_you_flag.wav", qtrue );
+ cgs.media.holyShitSound = trap_S_RegisterSound("sound/feedback/voc_holyshit.wav", qtrue);
+ cgs.media.neutralFlagReturnedSound = trap_S_RegisterSound( "sound/teamplay/flagreturn_opponent.wav", qtrue );
+ cgs.media.yourTeamTookTheFlagSound = trap_S_RegisterSound( "sound/teamplay/voc_team_1flag.wav", qtrue );
+ cgs.media.enemyTookTheFlagSound = trap_S_RegisterSound( "sound/teamplay/voc_enemy_1flag.wav", qtrue );
+#endif
+ }
+
+ cgs.media.tracerSound = trap_S_RegisterSound( "sound/weapons/machinegun/buletby1.wav", qfalse );
+ cgs.media.selectSound = trap_S_RegisterSound( "sound/weapons/change.wav", qfalse );
+ cgs.media.wearOffSound = trap_S_RegisterSound( "sound/items/wearoff.wav", qfalse );
+ cgs.media.useNothingSound = trap_S_RegisterSound( "sound/items/use_nothing.wav", qfalse );
+ cgs.media.gibSound = trap_S_RegisterSound( "sound/player/gibsplt1.wav", qfalse );
+ cgs.media.gibBounce1Sound = trap_S_RegisterSound( "sound/player/gibimp1.wav", qfalse );
+ cgs.media.gibBounce2Sound = trap_S_RegisterSound( "sound/player/gibimp2.wav", qfalse );
+ cgs.media.gibBounce3Sound = trap_S_RegisterSound( "sound/player/gibimp3.wav", qfalse );
+
+#ifdef MISSIONPACK
+ cgs.media.useInvulnerabilitySound = trap_S_RegisterSound( "sound/items/invul_activate.wav", qfalse );
+ cgs.media.invulnerabilityImpactSound1 = trap_S_RegisterSound( "sound/items/invul_impact_01.wav", qfalse );
+ cgs.media.invulnerabilityImpactSound2 = trap_S_RegisterSound( "sound/items/invul_impact_02.wav", qfalse );
+ cgs.media.invulnerabilityImpactSound3 = trap_S_RegisterSound( "sound/items/invul_impact_03.wav", qfalse );
+ cgs.media.invulnerabilityJuicedSound = trap_S_RegisterSound( "sound/items/invul_juiced.wav", qfalse );
+ cgs.media.obeliskHitSound1 = trap_S_RegisterSound( "sound/items/obelisk_hit_01.wav", qfalse );
+ cgs.media.obeliskHitSound2 = trap_S_RegisterSound( "sound/items/obelisk_hit_02.wav", qfalse );
+ cgs.media.obeliskHitSound3 = trap_S_RegisterSound( "sound/items/obelisk_hit_03.wav", qfalse );
+ cgs.media.obeliskRespawnSound = trap_S_RegisterSound( "sound/items/obelisk_respawn.wav", qfalse );
+
+ cgs.media.ammoregenSound = trap_S_RegisterSound("sound/items/cl_ammoregen.wav", qfalse);
+ cgs.media.doublerSound = trap_S_RegisterSound("sound/items/cl_doubler.wav", qfalse);
+ cgs.media.guardSound = trap_S_RegisterSound("sound/items/cl_guard.wav", qfalse);
+ cgs.media.scoutSound = trap_S_RegisterSound("sound/items/cl_scout.wav", qfalse);
+#endif
+
+ cgs.media.teleInSound = trap_S_RegisterSound( "sound/world/telein.wav", qfalse );
+ cgs.media.teleOutSound = trap_S_RegisterSound( "sound/world/teleout.wav", qfalse );
+ cgs.media.respawnSound = trap_S_RegisterSound( "sound/items/respawn1.wav", qfalse );
+
+ cgs.media.noAmmoSound = trap_S_RegisterSound( "sound/weapons/noammo.wav", qfalse );
+
+ cgs.media.talkSound = trap_S_RegisterSound( "sound/player/talk.wav", qfalse );
+ cgs.media.landSound = trap_S_RegisterSound( "sound/player/land1.wav", qfalse);
+
+ cgs.media.hitSound = trap_S_RegisterSound( "sound/feedback/hit.wav", qfalse );
+#ifdef MISSIONPACK
+ cgs.media.hitSoundHighArmor = trap_S_RegisterSound( "sound/feedback/hithi.wav", qfalse );
+ cgs.media.hitSoundLowArmor = trap_S_RegisterSound( "sound/feedback/hitlo.wav", qfalse );
+#endif
+
+ cgs.media.impressiveSound = trap_S_RegisterSound( "sound/feedback/impressive.wav", qtrue );
+ cgs.media.excellentSound = trap_S_RegisterSound( "sound/feedback/excellent.wav", qtrue );
+ cgs.media.deniedSound = trap_S_RegisterSound( "sound/feedback/denied.wav", qtrue );
+ cgs.media.humiliationSound = trap_S_RegisterSound( "sound/feedback/humiliation.wav", qtrue );
+ cgs.media.assistSound = trap_S_RegisterSound( "sound/feedback/assist.wav", qtrue );
+ cgs.media.defendSound = trap_S_RegisterSound( "sound/feedback/defense.wav", qtrue );
+#ifdef MISSIONPACK
+ cgs.media.firstImpressiveSound = trap_S_RegisterSound( "sound/feedback/first_impressive.wav", qtrue );
+ cgs.media.firstExcellentSound = trap_S_RegisterSound( "sound/feedback/first_excellent.wav", qtrue );
+ cgs.media.firstHumiliationSound = trap_S_RegisterSound( "sound/feedback/first_gauntlet.wav", qtrue );
+#endif
+
+ cgs.media.takenLeadSound = trap_S_RegisterSound( "sound/feedback/takenlead.wav", qtrue);
+ cgs.media.tiedLeadSound = trap_S_RegisterSound( "sound/feedback/tiedlead.wav", qtrue);
+ cgs.media.lostLeadSound = trap_S_RegisterSound( "sound/feedback/lostlead.wav", qtrue);
+
+#ifdef MISSIONPACK
+ cgs.media.voteNow = trap_S_RegisterSound( "sound/feedback/vote_now.wav", qtrue);
+ cgs.media.votePassed = trap_S_RegisterSound( "sound/feedback/vote_passed.wav", qtrue);
+ cgs.media.voteFailed = trap_S_RegisterSound( "sound/feedback/vote_failed.wav", qtrue);
+#endif
+
+ cgs.media.watrInSound = trap_S_RegisterSound( "sound/player/watr_in.wav", qfalse);
+ cgs.media.watrOutSound = trap_S_RegisterSound( "sound/player/watr_out.wav", qfalse);
+ cgs.media.watrUnSound = trap_S_RegisterSound( "sound/player/watr_un.wav", qfalse);
+
+ cgs.media.jumpPadSound = trap_S_RegisterSound ("sound/world/jumppad.wav", qfalse );
+
+ for (i=0 ; i<4 ; i++) {
+ Com_sprintf (name, sizeof(name), "sound/player/footsteps/step%i.wav", i+1);
+ cgs.media.footsteps[FOOTSTEP_NORMAL][i] = trap_S_RegisterSound (name, qfalse);
+
+ Com_sprintf (name, sizeof(name), "sound/player/footsteps/boot%i.wav", i+1);
+ cgs.media.footsteps[FOOTSTEP_BOOT][i] = trap_S_RegisterSound (name, qfalse);
+
+ Com_sprintf (name, sizeof(name), "sound/player/footsteps/flesh%i.wav", i+1);
+ cgs.media.footsteps[FOOTSTEP_FLESH][i] = trap_S_RegisterSound (name, qfalse);
+
+ Com_sprintf (name, sizeof(name), "sound/player/footsteps/mech%i.wav", i+1);
+ cgs.media.footsteps[FOOTSTEP_MECH][i] = trap_S_RegisterSound (name, qfalse);
+
+ Com_sprintf (name, sizeof(name), "sound/player/footsteps/energy%i.wav", i+1);
+ cgs.media.footsteps[FOOTSTEP_ENERGY][i] = trap_S_RegisterSound (name, qfalse);
+
+ Com_sprintf (name, sizeof(name), "sound/player/footsteps/splash%i.wav", i+1);
+ cgs.media.footsteps[FOOTSTEP_SPLASH][i] = trap_S_RegisterSound (name, qfalse);
+
+ Com_sprintf (name, sizeof(name), "sound/player/footsteps/clank%i.wav", i+1);
+ cgs.media.footsteps[FOOTSTEP_METAL][i] = trap_S_RegisterSound (name, qfalse);
+ }
+
+ // only register the items that the server says we need
+ strcpy( items, CG_ConfigString( CS_ITEMS ) );
+
+ for ( i = 1 ; i < bg_numItems ; i++ ) {
+// if ( items[ i ] == '1' || cg_buildScript.integer ) {
+ CG_RegisterItemSounds( i );
+// }
+ }
+
+ for ( i = 1 ; i < MAX_SOUNDS ; i++ ) {
+ soundName = CG_ConfigString( CS_SOUNDS+i );
+ if ( !soundName[0] ) {
+ break;
+ }
+ if ( soundName[0] == '*' ) {
+ continue; // custom sound
+ }
+ cgs.gameSounds[i] = trap_S_RegisterSound( soundName, qfalse );
+ }
+
+ // FIXME: only needed with item
+ cgs.media.flightSound = trap_S_RegisterSound( "sound/items/flight.wav", qfalse );
+ cgs.media.medkitSound = trap_S_RegisterSound ("sound/items/use_medkit.wav", qfalse);
+ cgs.media.quadSound = trap_S_RegisterSound("sound/items/damage3.wav", qfalse);
+ cgs.media.sfx_ric1 = trap_S_RegisterSound ("sound/weapons/machinegun/ric1.wav", qfalse);
+ cgs.media.sfx_ric2 = trap_S_RegisterSound ("sound/weapons/machinegun/ric2.wav", qfalse);
+ cgs.media.sfx_ric3 = trap_S_RegisterSound ("sound/weapons/machinegun/ric3.wav", qfalse);
+ cgs.media.sfx_railg = trap_S_RegisterSound ("sound/weapons/railgun/railgf1a.wav", qfalse);
+ cgs.media.sfx_rockexp = trap_S_RegisterSound ("sound/weapons/rocket/rocklx1a.wav", qfalse);
+ cgs.media.sfx_plasmaexp = trap_S_RegisterSound ("sound/weapons/plasma/plasmx1a.wav", qfalse);
+#ifdef MISSIONPACK
+ cgs.media.sfx_proxexp = trap_S_RegisterSound( "sound/weapons/proxmine/wstbexpl.wav" , qfalse);
+ cgs.media.sfx_nghit = trap_S_RegisterSound( "sound/weapons/nailgun/wnalimpd.wav" , qfalse);
+ cgs.media.sfx_nghitflesh = trap_S_RegisterSound( "sound/weapons/nailgun/wnalimpl.wav" , qfalse);
+ cgs.media.sfx_nghitmetal = trap_S_RegisterSound( "sound/weapons/nailgun/wnalimpm.wav", qfalse );
+ cgs.media.sfx_chghit = trap_S_RegisterSound( "sound/weapons/vulcan/wvulimpd.wav", qfalse );
+ cgs.media.sfx_chghitflesh = trap_S_RegisterSound( "sound/weapons/vulcan/wvulimpl.wav", qfalse );
+ cgs.media.sfx_chghitmetal = trap_S_RegisterSound( "sound/weapons/vulcan/wvulimpm.wav", qfalse );
+ cgs.media.weaponHoverSound = trap_S_RegisterSound( "sound/weapons/weapon_hover.wav", qfalse );
+ cgs.media.kamikazeExplodeSound = trap_S_RegisterSound( "sound/items/kam_explode.wav", qfalse );
+ cgs.media.kamikazeImplodeSound = trap_S_RegisterSound( "sound/items/kam_implode.wav", qfalse );
+ cgs.media.kamikazeFarSound = trap_S_RegisterSound( "sound/items/kam_explode_far.wav", qfalse );
+ cgs.media.winnerSound = trap_S_RegisterSound( "sound/feedback/voc_youwin.wav", qfalse );
+ cgs.media.loserSound = trap_S_RegisterSound( "sound/feedback/voc_youlose.wav", qfalse );
+ cgs.media.youSuckSound = trap_S_RegisterSound( "sound/misc/yousuck.wav", qfalse );
+
+ cgs.media.wstbimplSound = trap_S_RegisterSound("sound/weapons/proxmine/wstbimpl.wav", qfalse);
+ cgs.media.wstbimpmSound = trap_S_RegisterSound("sound/weapons/proxmine/wstbimpm.wav", qfalse);
+ cgs.media.wstbimpdSound = trap_S_RegisterSound("sound/weapons/proxmine/wstbimpd.wav", qfalse);
+ cgs.media.wstbactvSound = trap_S_RegisterSound("sound/weapons/proxmine/wstbactv.wav", qfalse);
+#endif
+
+ cgs.media.regenSound = trap_S_RegisterSound("sound/items/regen.wav", qfalse);
+ cgs.media.protectSound = trap_S_RegisterSound("sound/items/protect3.wav", qfalse);
+ cgs.media.n_healthSound = trap_S_RegisterSound("sound/items/n_health.wav", qfalse );
+ cgs.media.hgrenb1aSound = trap_S_RegisterSound("sound/weapons/grenade/hgrenb1a.wav", qfalse);
+ cgs.media.hgrenb2aSound = trap_S_RegisterSound("sound/weapons/grenade/hgrenb2a.wav", qfalse);
+
+#ifdef MISSIONPACK
+ trap_S_RegisterSound("sound/player/james/death1.wav", qfalse );
+ trap_S_RegisterSound("sound/player/james/death2.wav", qfalse );
+ trap_S_RegisterSound("sound/player/james/death3.wav", qfalse );
+ trap_S_RegisterSound("sound/player/james/jump1.wav", qfalse );
+ trap_S_RegisterSound("sound/player/james/pain25_1.wav", qfalse );
+ trap_S_RegisterSound("sound/player/james/pain75_1.wav", qfalse );
+ trap_S_RegisterSound("sound/player/james/pain100_1.wav", qfalse );
+ trap_S_RegisterSound("sound/player/james/falling1.wav", qfalse );
+ trap_S_RegisterSound("sound/player/james/gasp.wav", qfalse );
+ trap_S_RegisterSound("sound/player/james/drown.wav", qfalse );
+ trap_S_RegisterSound("sound/player/james/fall1.wav", qfalse );
+ trap_S_RegisterSound("sound/player/james/taunt.wav", qfalse );
+
+ trap_S_RegisterSound("sound/player/janet/death1.wav", qfalse );
+ trap_S_RegisterSound("sound/player/janet/death2.wav", qfalse );
+ trap_S_RegisterSound("sound/player/janet/death3.wav", qfalse );
+ trap_S_RegisterSound("sound/player/janet/jump1.wav", qfalse );
+ trap_S_RegisterSound("sound/player/janet/pain25_1.wav", qfalse );
+ trap_S_RegisterSound("sound/player/janet/pain75_1.wav", qfalse );
+ trap_S_RegisterSound("sound/player/janet/pain100_1.wav", qfalse );
+ trap_S_RegisterSound("sound/player/janet/falling1.wav", qfalse );
+ trap_S_RegisterSound("sound/player/janet/gasp.wav", qfalse );
+ trap_S_RegisterSound("sound/player/janet/drown.wav", qfalse );
+ trap_S_RegisterSound("sound/player/janet/fall1.wav", qfalse );
+ trap_S_RegisterSound("sound/player/janet/taunt.wav", qfalse );
+#endif
+
+}
+
+
+//===================================================================================
+
+
+/*
+=================
+CG_RegisterGraphics
+
+This function may execute for a couple of minutes with a slow disk.
+=================
+*/
+static void CG_RegisterGraphics( void ) {
+ int i;
+ char items[MAX_ITEMS+1];
+ static char *sb_nums[11] = {
+ "gfx/2d/numbers/zero_32b",
+ "gfx/2d/numbers/one_32b",
+ "gfx/2d/numbers/two_32b",
+ "gfx/2d/numbers/three_32b",
+ "gfx/2d/numbers/four_32b",
+ "gfx/2d/numbers/five_32b",
+ "gfx/2d/numbers/six_32b",
+ "gfx/2d/numbers/seven_32b",
+ "gfx/2d/numbers/eight_32b",
+ "gfx/2d/numbers/nine_32b",
+ "gfx/2d/numbers/minus_32b",
+ };
+
+ // clear any references to old media
+ memset( &cg.refdef, 0, sizeof( cg.refdef ) );
+ trap_R_ClearScene();
+
+ CG_LoadingString( cgs.mapname );
+
+ trap_R_LoadWorldMap( cgs.mapname );
+
+ // precache status bar pics
+ CG_LoadingString( "game media" );
+
+ for ( i=0 ; i<11 ; i++) {
+ cgs.media.numberShaders[i] = trap_R_RegisterShader( sb_nums[i] );
+ }
+
+ cgs.media.botSkillShaders[0] = trap_R_RegisterShader( "menu/art/skill1.tga" );
+ cgs.media.botSkillShaders[1] = trap_R_RegisterShader( "menu/art/skill2.tga" );
+ cgs.media.botSkillShaders[2] = trap_R_RegisterShader( "menu/art/skill3.tga" );
+ cgs.media.botSkillShaders[3] = trap_R_RegisterShader( "menu/art/skill4.tga" );
+ cgs.media.botSkillShaders[4] = trap_R_RegisterShader( "menu/art/skill5.tga" );
+
+ cgs.media.viewBloodShader = trap_R_RegisterShader( "viewBloodBlend" );
+
+ cgs.media.deferShader = trap_R_RegisterShaderNoMip( "gfx/2d/defer.tga" );
+
+ cgs.media.scoreboardName = trap_R_RegisterShaderNoMip( "menu/tab/name.tga" );
+ cgs.media.scoreboardPing = trap_R_RegisterShaderNoMip( "menu/tab/ping.tga" );
+ cgs.media.scoreboardScore = trap_R_RegisterShaderNoMip( "menu/tab/score.tga" );
+ cgs.media.scoreboardTime = trap_R_RegisterShaderNoMip( "menu/tab/time.tga" );
+
+ cgs.media.smokePuffShader = trap_R_RegisterShader( "smokePuff" );
+ cgs.media.smokePuffRageProShader = trap_R_RegisterShader( "smokePuffRagePro" );
+ cgs.media.shotgunSmokePuffShader = trap_R_RegisterShader( "shotgunSmokePuff" );
+#ifdef MISSIONPACK
+ cgs.media.nailPuffShader = trap_R_RegisterShader( "nailtrail" );
+ cgs.media.blueProxMine = trap_R_RegisterModel( "models/weaphits/proxmineb.md3" );
+#endif
+ cgs.media.plasmaBallShader = trap_R_RegisterShader( "sprites/plasma1" );
+ cgs.media.bloodTrailShader = trap_R_RegisterShader( "bloodTrail" );
+ cgs.media.lagometerShader = trap_R_RegisterShader("lagometer" );
+ cgs.media.connectionShader = trap_R_RegisterShader( "disconnected" );
+
+ cgs.media.waterBubbleShader = trap_R_RegisterShader( "waterBubble" );
+
+ cgs.media.tracerShader = trap_R_RegisterShader( "gfx/misc/tracer" );
+ cgs.media.selectShader = trap_R_RegisterShader( "gfx/2d/select" );
+
+ for ( i = 0 ; i < NUM_CROSSHAIRS ; i++ ) {
+ cgs.media.crosshairShader[i] = trap_R_RegisterShader( va("gfx/2d/crosshair%c", 'a'+i) );
+ }
+
+ cgs.media.backTileShader = trap_R_RegisterShader( "gfx/2d/backtile" );
+ cgs.media.noammoShader = trap_R_RegisterShader( "icons/noammo" );
+
+ // powerup shaders
+ cgs.media.quadShader = trap_R_RegisterShader("powerups/quad" );
+ cgs.media.quadWeaponShader = trap_R_RegisterShader("powerups/quadWeapon" );
+ cgs.media.battleSuitShader = trap_R_RegisterShader("powerups/battleSuit" );
+ cgs.media.battleWeaponShader = trap_R_RegisterShader("powerups/battleWeapon" );
+ cgs.media.invisShader = trap_R_RegisterShader("powerups/invisibility" );
+ cgs.media.regenShader = trap_R_RegisterShader("powerups/regen" );
+ cgs.media.hastePuffShader = trap_R_RegisterShader("hasteSmokePuff" );
+
+#ifdef MISSIONPACK
+ if ( cgs.gametype == GT_CTF || cgs.gametype == GT_1FCTF || cgs.gametype == GT_HARVESTER || cg_buildScript.integer ) {
+#else
+ if ( cgs.gametype == GT_CTF || cg_buildScript.integer ) {
+#endif
+ cgs.media.redCubeModel = trap_R_RegisterModel( "models/powerups/orb/r_orb.md3" );
+ cgs.media.blueCubeModel = trap_R_RegisterModel( "models/powerups/orb/b_orb.md3" );
+ cgs.media.redCubeIcon = trap_R_RegisterShader( "icons/skull_red" );
+ cgs.media.blueCubeIcon = trap_R_RegisterShader( "icons/skull_blue" );
+ }
+
+#ifdef MISSIONPACK
+ if ( cgs.gametype == GT_CTF || cgs.gametype == GT_1FCTF || cgs.gametype == GT_HARVESTER || cg_buildScript.integer ) {
+#else
+ if ( cgs.gametype == GT_CTF || cg_buildScript.integer ) {
+#endif
+ cgs.media.redFlagModel = trap_R_RegisterModel( "models/flags/r_flag.md3" );
+ cgs.media.blueFlagModel = trap_R_RegisterModel( "models/flags/b_flag.md3" );
+ cgs.media.redFlagShader[0] = trap_R_RegisterShaderNoMip( "icons/iconf_red1" );
+ cgs.media.redFlagShader[1] = trap_R_RegisterShaderNoMip( "icons/iconf_red2" );
+ cgs.media.redFlagShader[2] = trap_R_RegisterShaderNoMip( "icons/iconf_red3" );
+ cgs.media.blueFlagShader[0] = trap_R_RegisterShaderNoMip( "icons/iconf_blu1" );
+ cgs.media.blueFlagShader[1] = trap_R_RegisterShaderNoMip( "icons/iconf_blu2" );
+ cgs.media.blueFlagShader[2] = trap_R_RegisterShaderNoMip( "icons/iconf_blu3" );
+#ifdef MISSIONPACK
+ cgs.media.flagPoleModel = trap_R_RegisterModel( "models/flag2/flagpole.md3" );
+ cgs.media.flagFlapModel = trap_R_RegisterModel( "models/flag2/flagflap3.md3" );
+
+ cgs.media.redFlagFlapSkin = trap_R_RegisterSkin( "models/flag2/red.skin" );
+ cgs.media.blueFlagFlapSkin = trap_R_RegisterSkin( "models/flag2/blue.skin" );
+ cgs.media.neutralFlagFlapSkin = trap_R_RegisterSkin( "models/flag2/white.skin" );
+
+ cgs.media.redFlagBaseModel = trap_R_RegisterModel( "models/mapobjects/flagbase/red_base.md3" );
+ cgs.media.blueFlagBaseModel = trap_R_RegisterModel( "models/mapobjects/flagbase/blue_base.md3" );
+ cgs.media.neutralFlagBaseModel = trap_R_RegisterModel( "models/mapobjects/flagbase/ntrl_base.md3" );
+#endif
+ }
+
+#ifdef MISSIONPACK
+ if ( cgs.gametype == GT_1FCTF || cg_buildScript.integer ) {
+ cgs.media.neutralFlagModel = trap_R_RegisterModel( "models/flags/n_flag.md3" );
+ cgs.media.flagShader[0] = trap_R_RegisterShaderNoMip( "icons/iconf_neutral1" );
+ cgs.media.flagShader[1] = trap_R_RegisterShaderNoMip( "icons/iconf_red2" );
+ cgs.media.flagShader[2] = trap_R_RegisterShaderNoMip( "icons/iconf_blu2" );
+ cgs.media.flagShader[3] = trap_R_RegisterShaderNoMip( "icons/iconf_neutral3" );
+ }
+
+ if ( cgs.gametype == GT_OBELISK || cg_buildScript.integer ) {
+ cgs.media.overloadBaseModel = trap_R_RegisterModel( "models/powerups/overload_base.md3" );
+ cgs.media.overloadTargetModel = trap_R_RegisterModel( "models/powerups/overload_target.md3" );
+ cgs.media.overloadLightsModel = trap_R_RegisterModel( "models/powerups/overload_lights.md3" );
+ cgs.media.overloadEnergyModel = trap_R_RegisterModel( "models/powerups/overload_energy.md3" );
+ }
+
+ if ( cgs.gametype == GT_HARVESTER || cg_buildScript.integer ) {
+ cgs.media.harvesterModel = trap_R_RegisterModel( "models/powerups/harvester/harvester.md3" );
+ cgs.media.harvesterRedSkin = trap_R_RegisterSkin( "models/powerups/harvester/red.skin" );
+ cgs.media.harvesterBlueSkin = trap_R_RegisterSkin( "models/powerups/harvester/blue.skin" );
+ cgs.media.harvesterNeutralModel = trap_R_RegisterModel( "models/powerups/obelisk/obelisk.md3" );
+ }
+
+ cgs.media.redKamikazeShader = trap_R_RegisterShader( "models/weaphits/kamikred" );
+ cgs.media.dustPuffShader = trap_R_RegisterShader("hasteSmokePuff" );
+#endif
+
+ if ( cgs.gametype >= GT_TEAM || cg_buildScript.integer ) {
+ cgs.media.friendShader = trap_R_RegisterShader( "sprites/foe" );
+ cgs.media.redQuadShader = trap_R_RegisterShader("powerups/blueflag" );
+ cgs.media.teamStatusBar = trap_R_RegisterShader( "gfx/2d/colorbar.tga" );
+#ifdef MISSIONPACK
+ cgs.media.blueKamikazeShader = trap_R_RegisterShader( "models/weaphits/kamikblu" );
+#endif
+ }
+
+ cgs.media.armorModel = trap_R_RegisterModel( "models/powerups/armor/armor_yel.md3" );
+ cgs.media.armorIcon = trap_R_RegisterShaderNoMip( "icons/iconr_yellow" );
+
+ cgs.media.machinegunBrassModel = trap_R_RegisterModel( "models/weapons2/shells/m_shell.md3" );
+ cgs.media.shotgunBrassModel = trap_R_RegisterModel( "models/weapons2/shells/s_shell.md3" );
+
+ cgs.media.gibAbdomen = trap_R_RegisterModel( "models/gibs/abdomen.md3" );
+ cgs.media.gibArm = trap_R_RegisterModel( "models/gibs/arm.md3" );
+ cgs.media.gibChest = trap_R_RegisterModel( "models/gibs/chest.md3" );
+ cgs.media.gibFist = trap_R_RegisterModel( "models/gibs/fist.md3" );
+ cgs.media.gibFoot = trap_R_RegisterModel( "models/gibs/foot.md3" );
+ cgs.media.gibForearm = trap_R_RegisterModel( "models/gibs/forearm.md3" );
+ cgs.media.gibIntestine = trap_R_RegisterModel( "models/gibs/intestine.md3" );
+ cgs.media.gibLeg = trap_R_RegisterModel( "models/gibs/leg.md3" );
+ cgs.media.gibSkull = trap_R_RegisterModel( "models/gibs/skull.md3" );
+ cgs.media.gibBrain = trap_R_RegisterModel( "models/gibs/brain.md3" );
+
+ cgs.media.smoke2 = trap_R_RegisterModel( "models/weapons2/shells/s_shell.md3" );
+
+ cgs.media.balloonShader = trap_R_RegisterShader( "sprites/balloon3" );
+
+ cgs.media.bloodExplosionShader = trap_R_RegisterShader( "bloodExplosion" );
+
+ cgs.media.bulletFlashModel = trap_R_RegisterModel("models/weaphits/bullet.md3");
+ cgs.media.ringFlashModel = trap_R_RegisterModel("models/weaphits/ring02.md3");
+ cgs.media.dishFlashModel = trap_R_RegisterModel("models/weaphits/boom01.md3");
+#ifdef MISSIONPACK
+ cgs.media.teleportEffectModel = trap_R_RegisterModel( "models/powerups/pop.md3" );
+#else
+ cgs.media.teleportEffectModel = trap_R_RegisterModel( "models/misc/telep.md3" );
+ cgs.media.teleportEffectShader = trap_R_RegisterShader( "teleportEffect" );
+#endif
+#ifdef MISSIONPACK
+ cgs.media.kamikazeEffectModel = trap_R_RegisterModel( "models/weaphits/kamboom2.md3" );
+ cgs.media.kamikazeShockWave = trap_R_RegisterModel( "models/weaphits/kamwave.md3" );
+ cgs.media.kamikazeHeadModel = trap_R_RegisterModel( "models/powerups/kamikazi.md3" );
+ cgs.media.kamikazeHeadTrail = trap_R_RegisterModel( "models/powerups/trailtest.md3" );
+ cgs.media.guardPowerupModel = trap_R_RegisterModel( "models/powerups/guard_player.md3" );
+ cgs.media.scoutPowerupModel = trap_R_RegisterModel( "models/powerups/scout_player.md3" );
+ cgs.media.doublerPowerupModel = trap_R_RegisterModel( "models/powerups/doubler_player.md3" );
+ cgs.media.ammoRegenPowerupModel = trap_R_RegisterModel( "models/powerups/ammo_player.md3" );
+ cgs.media.invulnerabilityImpactModel = trap_R_RegisterModel( "models/powerups/shield/impact.md3" );
+ cgs.media.invulnerabilityJuicedModel = trap_R_RegisterModel( "models/powerups/shield/juicer.md3" );
+ cgs.media.medkitUsageModel = trap_R_RegisterModel( "models/powerups/regen.md3" );
+ cgs.media.heartShader = trap_R_RegisterShaderNoMip( "ui/assets/statusbar/selectedhealth.tga" );
+
+#endif
+
+ cgs.media.invulnerabilityPowerupModel = trap_R_RegisterModel( "models/powerups/shield/shield.md3" );
+ cgs.media.medalImpressive = trap_R_RegisterShaderNoMip( "medal_impressive" );
+ cgs.media.medalExcellent = trap_R_RegisterShaderNoMip( "medal_excellent" );
+ cgs.media.medalGauntlet = trap_R_RegisterShaderNoMip( "medal_gauntlet" );
+ cgs.media.medalDefend = trap_R_RegisterShaderNoMip( "medal_defend" );
+ cgs.media.medalAssist = trap_R_RegisterShaderNoMip( "medal_assist" );
+ cgs.media.medalCapture = trap_R_RegisterShaderNoMip( "medal_capture" );
+
+
+ memset( cg_items, 0, sizeof( cg_items ) );
+ memset( cg_weapons, 0, sizeof( cg_weapons ) );
+
+ // only register the items that the server says we need
+ strcpy( items, CG_ConfigString( CS_ITEMS) );
+
+ for ( i = 1 ; i < bg_numItems ; i++ ) {
+ if ( items[ i ] == '1' || cg_buildScript.integer ) {
+ CG_LoadingItem( i );
+ CG_RegisterItemVisuals( i );
+ }
+ }
+
+ // wall marks
+ cgs.media.bulletMarkShader = trap_R_RegisterShader( "gfx/damage/bullet_mrk" );
+ cgs.media.burnMarkShader = trap_R_RegisterShader( "gfx/damage/burn_med_mrk" );
+ cgs.media.holeMarkShader = trap_R_RegisterShader( "gfx/damage/hole_lg_mrk" );
+ cgs.media.energyMarkShader = trap_R_RegisterShader( "gfx/damage/plasma_mrk" );
+ cgs.media.shadowMarkShader = trap_R_RegisterShader( "markShadow" );
+ cgs.media.wakeMarkShader = trap_R_RegisterShader( "wake" );
+ cgs.media.bloodMarkShader = trap_R_RegisterShader( "bloodMark" );
+
+ // register the inline models
+ cgs.numInlineModels = trap_CM_NumInlineModels();
+ for ( i = 1 ; i < cgs.numInlineModels ; i++ ) {
+ char name[10];
+ vec3_t mins, maxs;
+ int j;
+
+ Com_sprintf( name, sizeof(name), "*%i", i );
+ cgs.inlineDrawModel[i] = trap_R_RegisterModel( name );
+ trap_R_ModelBounds( cgs.inlineDrawModel[i], mins, maxs );
+ for ( j = 0 ; j < 3 ; j++ ) {
+ cgs.inlineModelMidpoints[i][j] = mins[j] + 0.5 * ( maxs[j] - mins[j] );
+ }
+ }
+
+ // register all the server specified models
+ for (i=1 ; i<MAX_MODELS ; i++) {
+ const char *modelName;
+
+ modelName = CG_ConfigString( CS_MODELS+i );
+ if ( !modelName[0] ) {
+ break;
+ }
+ cgs.gameModels[i] = trap_R_RegisterModel( modelName );
+ }
+
+#ifdef MISSIONPACK
+ // new stuff
+ cgs.media.patrolShader = trap_R_RegisterShaderNoMip("ui/assets/statusbar/patrol.tga");
+ cgs.media.assaultShader = trap_R_RegisterShaderNoMip("ui/assets/statusbar/assault.tga");
+ cgs.media.campShader = trap_R_RegisterShaderNoMip("ui/assets/statusbar/camp.tga");
+ cgs.media.followShader = trap_R_RegisterShaderNoMip("ui/assets/statusbar/follow.tga");
+ cgs.media.defendShader = trap_R_RegisterShaderNoMip("ui/assets/statusbar/defend.tga");
+ cgs.media.teamLeaderShader = trap_R_RegisterShaderNoMip("ui/assets/statusbar/team_leader.tga");
+ cgs.media.retrieveShader = trap_R_RegisterShaderNoMip("ui/assets/statusbar/retrieve.tga");
+ cgs.media.escortShader = trap_R_RegisterShaderNoMip("ui/assets/statusbar/escort.tga");
+ cgs.media.cursor = trap_R_RegisterShaderNoMip( "menu/art/3_cursor2" );
+ cgs.media.sizeCursor = trap_R_RegisterShaderNoMip( "ui/assets/sizecursor.tga" );
+ cgs.media.selectCursor = trap_R_RegisterShaderNoMip( "ui/assets/selectcursor.tga" );
+ cgs.media.flagShaders[0] = trap_R_RegisterShaderNoMip("ui/assets/statusbar/flag_in_base.tga");
+ cgs.media.flagShaders[1] = trap_R_RegisterShaderNoMip("ui/assets/statusbar/flag_capture.tga");
+ cgs.media.flagShaders[2] = trap_R_RegisterShaderNoMip("ui/assets/statusbar/flag_missing.tga");
+
+ trap_R_RegisterModel( "models/players/james/lower.md3" );
+ trap_R_RegisterModel( "models/players/james/upper.md3" );
+ trap_R_RegisterModel( "models/players/heads/james/james.md3" );
+
+ trap_R_RegisterModel( "models/players/janet/lower.md3" );
+ trap_R_RegisterModel( "models/players/janet/upper.md3" );
+ trap_R_RegisterModel( "models/players/heads/janet/janet.md3" );
+
+#endif
+ CG_ClearParticles ();
+/*
+ for (i=1; i<MAX_PARTICLES_AREAS; i++)
+ {
+ {
+ int rval;
+
+ rval = CG_NewParticleArea ( CS_PARTICLES + i);
+ if (!rval)
+ break;
+ }
+ }
+*/
+}
+
+
+
+/*
+=======================
+CG_BuildSpectatorString
+
+=======================
+*/
+void CG_BuildSpectatorString() {
+ int i;
+ cg.spectatorList[0] = 0;
+ for (i = 0; i < MAX_CLIENTS; i++) {
+ if (cgs.clientinfo[i].infoValid && cgs.clientinfo[i].team == TEAM_SPECTATOR ) {
+ Q_strcat(cg.spectatorList, sizeof(cg.spectatorList), va("%s ", cgs.clientinfo[i].name));
+ }
+ }
+ i = strlen(cg.spectatorList);
+ if (i != cg.spectatorLen) {
+ cg.spectatorLen = i;
+ cg.spectatorWidth = -1;
+ }
+}
+
+
+/*
+===================
+CG_RegisterClients
+===================
+*/
+static void CG_RegisterClients( void ) {
+ int i;
+
+ CG_LoadingClient(cg.clientNum);
+ CG_NewClientInfo(cg.clientNum);
+
+ for (i=0 ; i<MAX_CLIENTS ; i++) {
+ const char *clientInfo;
+
+ if (cg.clientNum == i) {
+ continue;
+ }
+
+ clientInfo = CG_ConfigString( CS_PLAYERS+i );
+ if ( !clientInfo[0]) {
+ continue;
+ }
+ CG_LoadingClient( i );
+ CG_NewClientInfo( i );
+ }
+ CG_BuildSpectatorString();
+}
+
+//===========================================================================
+
+/*
+=================
+CG_ConfigString
+=================
+*/
+const char *CG_ConfigString( int index ) {
+ if ( index < 0 || index >= MAX_CONFIGSTRINGS ) {
+ CG_Error( "CG_ConfigString: bad index: %i", index );
+ }
+ return cgs.gameState.stringData + cgs.gameState.stringOffsets[ index ];
+}
+
+//==================================================================
+
+/*
+======================
+CG_StartMusic
+
+======================
+*/
+void CG_StartMusic( void ) {
+ char *s;
+ char parm1[MAX_QPATH], parm2[MAX_QPATH];
+
+ // start the background music
+ s = (char *)CG_ConfigString( CS_MUSIC );
+ Q_strncpyz( parm1, COM_Parse( &s ), sizeof( parm1 ) );
+ Q_strncpyz( parm2, COM_Parse( &s ), sizeof( parm2 ) );
+
+ trap_S_StartBackgroundTrack( parm1, parm2 );
+}
+#ifdef MISSIONPACK
+char *CG_GetMenuBuffer(const char *filename) {
+ int len;
+ fileHandle_t f;
+ static char buf[MAX_MENUFILE];
+
+ len = trap_FS_FOpenFile( filename, &f, FS_READ );
+ if ( !f ) {
+ trap_Print( va( S_COLOR_RED "menu file not found: %s, using default\n", filename ) );
+ return NULL;
+ }
+ if ( len >= MAX_MENUFILE ) {
+ trap_Print( va( S_COLOR_RED "menu file too large: %s is %i, max allowed is %i", filename, len, MAX_MENUFILE ) );
+ trap_FS_FCloseFile( f );
+ return NULL;
+ }
+
+ trap_FS_Read( buf, len, f );
+ buf[len] = 0;
+ trap_FS_FCloseFile( f );
+
+ return buf;
+}
+
+//
+// ==============================
+// new hud stuff ( mission pack )
+// ==============================
+//
+qboolean CG_Asset_Parse(int handle) {
+ pc_token_t token;
+ const char *tempStr;
+
+ if (!trap_PC_ReadToken(handle, &token))
+ return qfalse;
+ if (Q_stricmp(token.string, "{") != 0) {
+ return qfalse;
+ }
+
+ while ( 1 ) {
+ if (!trap_PC_ReadToken(handle, &token))
+ return qfalse;
+
+ if (Q_stricmp(token.string, "}") == 0) {
+ return qtrue;
+ }
+
+ // font
+ if (Q_stricmp(token.string, "font") == 0) {
+ int pointSize;
+ if (!PC_String_Parse(handle, &tempStr) || !PC_Int_Parse(handle, &pointSize)) {
+ return qfalse;
+ }
+ cgDC.registerFont(tempStr, pointSize, &cgDC.Assets.textFont);
+ continue;
+ }
+
+ // smallFont
+ if (Q_stricmp(token.string, "smallFont") == 0) {
+ int pointSize;
+ if (!PC_String_Parse(handle, &tempStr) || !PC_Int_Parse(handle, &pointSize)) {
+ return qfalse;
+ }
+ cgDC.registerFont(tempStr, pointSize, &cgDC.Assets.smallFont);
+ continue;
+ }
+
+ // font
+ if (Q_stricmp(token.string, "bigfont") == 0) {
+ int pointSize;
+ if (!PC_String_Parse(handle, &tempStr) || !PC_Int_Parse(handle, &pointSize)) {
+ return qfalse;
+ }
+ cgDC.registerFont(tempStr, pointSize, &cgDC.Assets.bigFont);
+ continue;
+ }
+
+ // gradientbar
+ if (Q_stricmp(token.string, "gradientbar") == 0) {
+ if (!PC_String_Parse(handle, &tempStr)) {
+ return qfalse;
+ }
+ cgDC.Assets.gradientBar = trap_R_RegisterShaderNoMip(tempStr);
+ continue;
+ }
+
+ // enterMenuSound
+ if (Q_stricmp(token.string, "menuEnterSound") == 0) {
+ if (!PC_String_Parse(handle, &tempStr)) {
+ return qfalse;
+ }
+ cgDC.Assets.menuEnterSound = trap_S_RegisterSound( tempStr, qfalse );
+ continue;
+ }
+
+ // exitMenuSound
+ if (Q_stricmp(token.string, "menuExitSound") == 0) {
+ if (!PC_String_Parse(handle, &tempStr)) {
+ return qfalse;
+ }
+ cgDC.Assets.menuExitSound = trap_S_RegisterSound( tempStr, qfalse );
+ continue;
+ }
+
+ // itemFocusSound
+ if (Q_stricmp(token.string, "itemFocusSound") == 0) {
+ if (!PC_String_Parse(handle, &tempStr)) {
+ return qfalse;
+ }
+ cgDC.Assets.itemFocusSound = trap_S_RegisterSound( tempStr, qfalse );
+ continue;
+ }
+
+ // menuBuzzSound
+ if (Q_stricmp(token.string, "menuBuzzSound") == 0) {
+ if (!PC_String_Parse(handle, &tempStr)) {
+ return qfalse;
+ }
+ cgDC.Assets.menuBuzzSound = trap_S_RegisterSound( tempStr, qfalse );
+ continue;
+ }
+
+ if (Q_stricmp(token.string, "cursor") == 0) {
+ if (!PC_String_Parse(handle, &cgDC.Assets.cursorStr)) {
+ return qfalse;
+ }
+ cgDC.Assets.cursor = trap_R_RegisterShaderNoMip( cgDC.Assets.cursorStr);
+ continue;
+ }
+
+ if (Q_stricmp(token.string, "fadeClamp") == 0) {
+ if (!PC_Float_Parse(handle, &cgDC.Assets.fadeClamp)) {
+ return qfalse;
+ }
+ continue;
+ }
+
+ if (Q_stricmp(token.string, "fadeCycle") == 0) {
+ if (!PC_Int_Parse(handle, &cgDC.Assets.fadeCycle)) {
+ return qfalse;
+ }
+ continue;
+ }
+
+ if (Q_stricmp(token.string, "fadeAmount") == 0) {
+ if (!PC_Float_Parse(handle, &cgDC.Assets.fadeAmount)) {
+ return qfalse;
+ }
+ continue;
+ }
+
+ if (Q_stricmp(token.string, "shadowX") == 0) {
+ if (!PC_Float_Parse(handle, &cgDC.Assets.shadowX)) {
+ return qfalse;
+ }
+ continue;
+ }
+
+ if (Q_stricmp(token.string, "shadowY") == 0) {
+ if (!PC_Float_Parse(handle, &cgDC.Assets.shadowY)) {
+ return qfalse;
+ }
+ continue;
+ }
+
+ if (Q_stricmp(token.string, "shadowColor") == 0) {
+ if (!PC_Color_Parse(handle, &cgDC.Assets.shadowColor)) {
+ return qfalse;
+ }
+ cgDC.Assets.shadowFadeClamp = cgDC.Assets.shadowColor[3];
+ continue;
+ }
+ }
+ return qfalse; // bk001204 - why not?
+}
+
+void CG_ParseMenu(const char *menuFile) {
+ pc_token_t token;
+ int handle;
+
+ handle = trap_PC_LoadSource(menuFile);
+ if (!handle)
+ handle = trap_PC_LoadSource("ui/testhud.menu");
+ if (!handle)
+ return;
+
+ while ( 1 ) {
+ if (!trap_PC_ReadToken( handle, &token )) {
+ break;
+ }
+
+ //if ( Q_stricmp( token, "{" ) ) {
+ // Com_Printf( "Missing { in menu file\n" );
+ // break;
+ //}
+
+ //if ( menuCount == MAX_MENUS ) {
+ // Com_Printf( "Too many menus!\n" );
+ // break;
+ //}
+
+ if ( token.string[0] == '}' ) {
+ break;
+ }
+
+ if (Q_stricmp(token.string, "assetGlobalDef") == 0) {
+ if (CG_Asset_Parse(handle)) {
+ continue;
+ } else {
+ break;
+ }
+ }
+
+
+ if (Q_stricmp(token.string, "menudef") == 0) {
+ // start a new menu
+ Menu_New(handle);
+ }
+ }
+ trap_PC_FreeSource(handle);
+}
+
+qboolean CG_Load_Menu(char **p) {
+ char *token;
+
+ token = COM_ParseExt(p, qtrue);
+
+ if (token[0] != '{') {
+ return qfalse;
+ }
+
+ while ( 1 ) {
+
+ token = COM_ParseExt(p, qtrue);
+
+ if (Q_stricmp(token, "}") == 0) {
+ return qtrue;
+ }
+
+ if ( !token || token[0] == 0 ) {
+ return qfalse;
+ }
+
+ CG_ParseMenu(token);
+ }
+ return qfalse;
+}
+
+
+
+void CG_LoadMenus(const char *menuFile) {
+ char *token;
+ char *p;
+ int len, start;
+ fileHandle_t f;
+ static char buf[MAX_MENUDEFFILE];
+
+ start = trap_Milliseconds();
+
+ len = trap_FS_FOpenFile( menuFile, &f, FS_READ );
+ if ( !f ) {
+ trap_Error( va( S_COLOR_YELLOW "menu file not found: %s, using default\n", menuFile ) );
+ len = trap_FS_FOpenFile( "ui/hud.txt", &f, FS_READ );
+ if (!f) {
+ trap_Error( va( S_COLOR_RED "default menu file not found: ui/hud.txt, unable to continue!\n", menuFile ) );
+ }
+ }
+
+ if ( len >= MAX_MENUDEFFILE ) {
+ trap_Error( va( S_COLOR_RED "menu file too large: %s is %i, max allowed is %i", menuFile, len, MAX_MENUDEFFILE ) );
+ trap_FS_FCloseFile( f );
+ return;
+ }
+
+ trap_FS_Read( buf, len, f );
+ buf[len] = 0;
+ trap_FS_FCloseFile( f );
+
+ COM_Compress(buf);
+
+ Menu_Reset();
+
+ p = buf;
+
+ while ( 1 ) {
+ token = COM_ParseExt( &p, qtrue );
+ if( !token || token[0] == 0 || token[0] == '}') {
+ break;
+ }
+
+ //if ( Q_stricmp( token, "{" ) ) {
+ // Com_Printf( "Missing { in menu file\n" );
+ // break;
+ //}
+
+ //if ( menuCount == MAX_MENUS ) {
+ // Com_Printf( "Too many menus!\n" );
+ // break;
+ //}
+
+ if ( Q_stricmp( token, "}" ) == 0 ) {
+ break;
+ }
+
+ if (Q_stricmp(token, "loadmenu") == 0) {
+ if (CG_Load_Menu(&p)) {
+ continue;
+ } else {
+ break;
+ }
+ }
+ }
+
+ Com_Printf("UI menu load time = %d milli seconds\n", trap_Milliseconds() - start);
+
+}
+
+
+
+static qboolean CG_OwnerDrawHandleKey(int ownerDraw, int flags, float *special, int key) {
+ return qfalse;
+}
+
+
+static int CG_FeederCount(float feederID) {
+ int i, count;
+ count = 0;
+ if (feederID == FEEDER_REDTEAM_LIST) {
+ for (i = 0; i < cg.numScores; i++) {
+ if (cg.scores[i].team == TEAM_RED) {
+ count++;
+ }
+ }
+ } else if (feederID == FEEDER_BLUETEAM_LIST) {
+ for (i = 0; i < cg.numScores; i++) {
+ if (cg.scores[i].team == TEAM_BLUE) {
+ count++;
+ }
+ }
+ } else if (feederID == FEEDER_SCOREBOARD) {
+ return cg.numScores;
+ }
+ return count;
+}
+
+
+void CG_SetScoreSelection(void *p) {
+ menuDef_t *menu = (menuDef_t*)p;
+ playerState_t *ps = &cg.snap->ps;
+ int i, red, blue;
+ red = blue = 0;
+ for (i = 0; i < cg.numScores; i++) {
+ if (cg.scores[i].team == TEAM_RED) {
+ red++;
+ } else if (cg.scores[i].team == TEAM_BLUE) {
+ blue++;
+ }
+ if (ps->clientNum == cg.scores[i].client) {
+ cg.selectedScore = i;
+ }
+ }
+
+ if (menu == NULL) {
+ // just interested in setting the selected score
+ return;
+ }
+
+ if ( cgs.gametype >= GT_TEAM ) {
+ int feeder = FEEDER_REDTEAM_LIST;
+ i = red;
+ if (cg.scores[cg.selectedScore].team == TEAM_BLUE) {
+ feeder = FEEDER_BLUETEAM_LIST;
+ i = blue;
+ }
+ Menu_SetFeederSelection(menu, feeder, i, NULL);
+ } else {
+ Menu_SetFeederSelection(menu, FEEDER_SCOREBOARD, cg.selectedScore, NULL);
+ }
+}
+
+// FIXME: might need to cache this info
+static clientInfo_t * CG_InfoFromScoreIndex(int index, int team, int *scoreIndex) {
+ int i, count;
+ if ( cgs.gametype >= GT_TEAM ) {
+ count = 0;
+ for (i = 0; i < cg.numScores; i++) {
+ if (cg.scores[i].team == team) {
+ if (count == index) {
+ *scoreIndex = i;
+ return &cgs.clientinfo[cg.scores[i].client];
+ }
+ count++;
+ }
+ }
+ }
+ *scoreIndex = index;
+ return &cgs.clientinfo[ cg.scores[index].client ];
+}
+
+static const char *CG_FeederItemText(float feederID, int index, int column, qhandle_t *handle) {
+ gitem_t *item;
+ int scoreIndex = 0;
+ clientInfo_t *info = NULL;
+ int team = -1;
+ score_t *sp = NULL;
+
+ *handle = -1;
+
+ if (feederID == FEEDER_REDTEAM_LIST) {
+ team = TEAM_RED;
+ } else if (feederID == FEEDER_BLUETEAM_LIST) {
+ team = TEAM_BLUE;
+ }
+
+ info = CG_InfoFromScoreIndex(index, team, &scoreIndex);
+ sp = &cg.scores[scoreIndex];
+
+ if (info && info->infoValid) {
+ switch (column) {
+ case 0:
+ if ( info->powerups & ( 1 << PW_NEUTRALFLAG ) ) {
+ item = BG_FindItemForPowerup( PW_NEUTRALFLAG );
+ *handle = cg_items[ ITEM_INDEX(item) ].icon;
+ } else if ( info->powerups & ( 1 << PW_REDFLAG ) ) {
+ item = BG_FindItemForPowerup( PW_REDFLAG );
+ *handle = cg_items[ ITEM_INDEX(item) ].icon;
+ } else if ( info->powerups & ( 1 << PW_BLUEFLAG ) ) {
+ item = BG_FindItemForPowerup( PW_BLUEFLAG );
+ *handle = cg_items[ ITEM_INDEX(item) ].icon;
+ } else {
+ if ( info->botSkill > 0 && info->botSkill <= 5 ) {
+ *handle = cgs.media.botSkillShaders[ info->botSkill - 1 ];
+ } else if ( info->handicap < 100 ) {
+ return va("%i", info->handicap );
+ }
+ }
+ break;
+ case 1:
+ if (team == -1) {
+ return "";
+ } else {
+ *handle = CG_StatusHandle(info->teamTask);
+ }
+ break;
+ case 2:
+ if ( cg.snap->ps.stats[ STAT_CLIENTS_READY ] & ( 1 << sp->client ) ) {
+ return "Ready";
+ }
+ if (team == -1) {
+ if (cgs.gametype == GT_TOURNAMENT) {
+ return va("%i/%i", info->wins, info->losses);
+ } else if (info->infoValid && info->team == TEAM_SPECTATOR ) {
+ return "Spectator";
+ } else {
+ return "";
+ }
+ } else {
+ if (info->teamLeader) {
+ return "Leader";
+ }
+ }
+ break;
+ case 3:
+ return info->name;
+ break;
+ case 4:
+ return va("%i", info->score);
+ break;
+ case 5:
+ return va("%4i", sp->time);
+ break;
+ case 6:
+ if ( sp->ping == -1 ) {
+ return "connecting";
+ }
+ return va("%4i", sp->ping);
+ break;
+ }
+ }
+
+ return "";
+}
+
+static qhandle_t CG_FeederItemImage(float feederID, int index) {
+ return 0;
+}
+
+static void CG_FeederSelection(float feederID, int index) {
+ if ( cgs.gametype >= GT_TEAM ) {
+ int i, count;
+ int team = (feederID == FEEDER_REDTEAM_LIST) ? TEAM_RED : TEAM_BLUE;
+ count = 0;
+ for (i = 0; i < cg.numScores; i++) {
+ if (cg.scores[i].team == team) {
+ if (index == count) {
+ cg.selectedScore = i;
+ }
+ count++;
+ }
+ }
+ } else {
+ cg.selectedScore = index;
+ }
+}
+#endif
+
+#ifdef MISSIONPACK // bk001204 - only needed there
+static float CG_Cvar_Get(const char *cvar) {
+ char buff[128];
+ memset(buff, 0, sizeof(buff));
+ trap_Cvar_VariableStringBuffer(cvar, buff, sizeof(buff));
+ return atof(buff);
+}
+#endif
+
+#ifdef MISSIONPACK
+void CG_Text_PaintWithCursor(float x, float y, float scale, vec4_t color, const char *text, int cursorPos, char cursor, int limit, int style) {
+ CG_Text_Paint(x, y, scale, color, text, 0, limit, style);
+}
+
+static int CG_OwnerDrawWidth(int ownerDraw, float scale) {
+ switch (ownerDraw) {
+ case CG_GAME_TYPE:
+ return CG_Text_Width(CG_GameTypeString(), scale, 0);
+ case CG_GAME_STATUS:
+ return CG_Text_Width(CG_GetGameStatusText(), scale, 0);
+ break;
+ case CG_KILLER:
+ return CG_Text_Width(CG_GetKillerText(), scale, 0);
+ break;
+ case CG_RED_NAME:
+ return CG_Text_Width(cg_redTeamName.string, scale, 0);
+ break;
+ case CG_BLUE_NAME:
+ return CG_Text_Width(cg_blueTeamName.string, scale, 0);
+ break;
+
+
+ }
+ return 0;
+}
+
+static int CG_PlayCinematic(const char *name, float x, float y, float w, float h) {
+ return trap_CIN_PlayCinematic(name, x, y, w, h, CIN_loop);
+}
+
+static void CG_StopCinematic(int handle) {
+ trap_CIN_StopCinematic(handle);
+}
+
+static void CG_DrawCinematic(int handle, float x, float y, float w, float h) {
+ trap_CIN_SetExtents(handle, x, y, w, h);
+ trap_CIN_DrawCinematic(handle);
+}
+
+static void CG_RunCinematicFrame(int handle) {
+ trap_CIN_RunCinematic(handle);
+}
+
+/*
+=================
+CG_LoadHudMenu();
+
+=================
+*/
+void CG_LoadHudMenu() {
+ char buff[1024];
+ const char *hudSet;
+
+ cgDC.registerShaderNoMip = &trap_R_RegisterShaderNoMip;
+ cgDC.setColor = &trap_R_SetColor;
+ cgDC.drawHandlePic = &CG_DrawPic;
+ cgDC.drawStretchPic = &trap_R_DrawStretchPic;
+ cgDC.drawText = &CG_Text_Paint;
+ cgDC.textWidth = &CG_Text_Width;
+ cgDC.textHeight = &CG_Text_Height;
+ cgDC.registerModel = &trap_R_RegisterModel;
+ cgDC.modelBounds = &trap_R_ModelBounds;
+ cgDC.fillRect = &CG_FillRect;
+ cgDC.drawRect = &CG_DrawRect;
+ cgDC.drawSides = &CG_DrawSides;
+ cgDC.drawTopBottom = &CG_DrawTopBottom;
+ cgDC.clearScene = &trap_R_ClearScene;
+ cgDC.addRefEntityToScene = &trap_R_AddRefEntityToScene;
+ cgDC.renderScene = &trap_R_RenderScene;
+ cgDC.registerFont = &trap_R_RegisterFont;
+ cgDC.ownerDrawItem = &CG_OwnerDraw;
+ cgDC.getValue = &CG_GetValue;
+ cgDC.ownerDrawVisible = &CG_OwnerDrawVisible;
+ cgDC.runScript = &CG_RunMenuScript;
+ cgDC.getTeamColor = &CG_GetTeamColor;
+ cgDC.setCVar = trap_Cvar_Set;
+ cgDC.getCVarString = trap_Cvar_VariableStringBuffer;
+ cgDC.getCVarValue = CG_Cvar_Get;
+ cgDC.drawTextWithCursor = &CG_Text_PaintWithCursor;
+ //cgDC.setOverstrikeMode = &trap_Key_SetOverstrikeMode;
+ //cgDC.getOverstrikeMode = &trap_Key_GetOverstrikeMode;
+ cgDC.startLocalSound = &trap_S_StartLocalSound;
+ cgDC.ownerDrawHandleKey = &CG_OwnerDrawHandleKey;
+ cgDC.feederCount = &CG_FeederCount;
+ cgDC.feederItemImage = &CG_FeederItemImage;
+ cgDC.feederItemText = &CG_FeederItemText;
+ cgDC.feederSelection = &CG_FeederSelection;
+ //cgDC.setBinding = &trap_Key_SetBinding;
+ //cgDC.getBindingBuf = &trap_Key_GetBindingBuf;
+ //cgDC.keynumToStringBuf = &trap_Key_KeynumToStringBuf;
+ //cgDC.executeText = &trap_Cmd_ExecuteText;
+ cgDC.Error = &Com_Error;
+ cgDC.Print = &Com_Printf;
+ cgDC.ownerDrawWidth = &CG_OwnerDrawWidth;
+ //cgDC.Pause = &CG_Pause;
+ cgDC.registerSound = &trap_S_RegisterSound;
+ cgDC.startBackgroundTrack = &trap_S_StartBackgroundTrack;
+ cgDC.stopBackgroundTrack = &trap_S_StopBackgroundTrack;
+ cgDC.playCinematic = &CG_PlayCinematic;
+ cgDC.stopCinematic = &CG_StopCinematic;
+ cgDC.drawCinematic = &CG_DrawCinematic;
+ cgDC.runCinematicFrame = &CG_RunCinematicFrame;
+
+ Init_Display(&cgDC);
+
+ Menu_Reset();
+
+ trap_Cvar_VariableStringBuffer("cg_hudFiles", buff, sizeof(buff));
+ hudSet = buff;
+ if (hudSet[0] == '\0') {
+ hudSet = "ui/hud.txt";
+ }
+
+ CG_LoadMenus(hudSet);
+}
+
+void CG_AssetCache() {
+ //if (Assets.textFont == NULL) {
+ // trap_R_RegisterFont("fonts/arial.ttf", 72, &Assets.textFont);
+ //}
+ //Assets.background = trap_R_RegisterShaderNoMip( ASSET_BACKGROUND );
+ //Com_Printf("Menu Size: %i bytes\n", sizeof(Menus));
+ cgDC.Assets.gradientBar = trap_R_RegisterShaderNoMip( ASSET_GRADIENTBAR );
+ cgDC.Assets.fxBasePic = trap_R_RegisterShaderNoMip( ART_FX_BASE );
+ cgDC.Assets.fxPic[0] = trap_R_RegisterShaderNoMip( ART_FX_RED );
+ cgDC.Assets.fxPic[1] = trap_R_RegisterShaderNoMip( ART_FX_YELLOW );
+ cgDC.Assets.fxPic[2] = trap_R_RegisterShaderNoMip( ART_FX_GREEN );
+ cgDC.Assets.fxPic[3] = trap_R_RegisterShaderNoMip( ART_FX_TEAL );
+ cgDC.Assets.fxPic[4] = trap_R_RegisterShaderNoMip( ART_FX_BLUE );
+ cgDC.Assets.fxPic[5] = trap_R_RegisterShaderNoMip( ART_FX_CYAN );
+ cgDC.Assets.fxPic[6] = trap_R_RegisterShaderNoMip( ART_FX_WHITE );
+ cgDC.Assets.scrollBar = trap_R_RegisterShaderNoMip( ASSET_SCROLLBAR );
+ cgDC.Assets.scrollBarArrowDown = trap_R_RegisterShaderNoMip( ASSET_SCROLLBAR_ARROWDOWN );
+ cgDC.Assets.scrollBarArrowUp = trap_R_RegisterShaderNoMip( ASSET_SCROLLBAR_ARROWUP );
+ cgDC.Assets.scrollBarArrowLeft = trap_R_RegisterShaderNoMip( ASSET_SCROLLBAR_ARROWLEFT );
+ cgDC.Assets.scrollBarArrowRight = trap_R_RegisterShaderNoMip( ASSET_SCROLLBAR_ARROWRIGHT );
+ cgDC.Assets.scrollBarThumb = trap_R_RegisterShaderNoMip( ASSET_SCROLL_THUMB );
+ cgDC.Assets.sliderBar = trap_R_RegisterShaderNoMip( ASSET_SLIDER_BAR );
+ cgDC.Assets.sliderThumb = trap_R_RegisterShaderNoMip( ASSET_SLIDER_THUMB );
+}
+#endif
+/*
+=================
+CG_Init
+
+Called after every level change or subsystem restart
+Will perform callbacks to make the loading info screen update.
+=================
+*/
+void CG_Init( int serverMessageNum, int serverCommandSequence, int clientNum ) {
+ const char *s;
+
+ // clear everything
+ memset( &cgs, 0, sizeof( cgs ) );
+ memset( &cg, 0, sizeof( cg ) );
+ memset( cg_entities, 0, sizeof(cg_entities) );
+ memset( cg_weapons, 0, sizeof(cg_weapons) );
+ memset( cg_items, 0, sizeof(cg_items) );
+
+ cg.clientNum = clientNum;
+
+ cgs.processedSnapshotNum = serverMessageNum;
+ cgs.serverCommandSequence = serverCommandSequence;
+
+ // load a few needed things before we do any screen updates
+ cgs.media.charsetShader = trap_R_RegisterShader( "gfx/2d/bigchars" );
+ cgs.media.whiteShader = trap_R_RegisterShader( "white" );
+ cgs.media.charsetProp = trap_R_RegisterShaderNoMip( "menu/art/font1_prop.tga" );
+ cgs.media.charsetPropGlow = trap_R_RegisterShaderNoMip( "menu/art/font1_prop_glo.tga" );
+ cgs.media.charsetPropB = trap_R_RegisterShaderNoMip( "menu/art/font2_prop.tga" );
+
+ CG_RegisterCvars();
+
+ CG_InitConsoleCommands();
+
+ cg.weaponSelect = WP_MACHINEGUN;
+
+ cgs.redflag = cgs.blueflag = -1; // For compatibily, default to unset for
+ cgs.flagStatus = -1;
+ // old servers
+
+ // get the rendering configuration from the client system
+ trap_GetGlconfig( &cgs.glconfig );
+ cgs.screenXScale = cgs.glconfig.vidWidth / 640.0;
+ cgs.screenYScale = cgs.glconfig.vidHeight / 480.0;
+
+ // get the gamestate from the client system
+ trap_GetGameState( &cgs.gameState );
+
+ // check version
+ s = CG_ConfigString( CS_GAME_VERSION );
+ if ( strcmp( s, GAME_VERSION ) ) {
+ CG_Error( "Client/Server game mismatch: %s/%s", GAME_VERSION, s );
+ }
+
+ s = CG_ConfigString( CS_LEVEL_START_TIME );
+ cgs.levelStartTime = atoi( s );
+
+ CG_ParseServerinfo();
+
+ // load the new map
+ CG_LoadingString( "collision map" );
+
+ trap_CM_LoadMap( cgs.mapname );
+
+#ifdef MISSIONPACK
+ String_Init();
+#endif
+
+ cg.loading = qtrue; // force players to load instead of defer
+
+ CG_LoadingString( "sounds" );
+
+ CG_RegisterSounds();
+
+ CG_LoadingString( "graphics" );
+
+ CG_RegisterGraphics();
+
+ CG_LoadingString( "clients" );
+
+ CG_RegisterClients(); // if low on memory, some clients will be deferred
+
+#ifdef MISSIONPACK
+ CG_AssetCache();
+ CG_LoadHudMenu(); // load new hud stuff
+#endif
+
+ cg.loading = qfalse; // future players will be deferred
+
+ CG_InitLocalEntities();
+
+ CG_InitMarkPolys();
+
+ // remove the last loading update
+ cg.infoScreenText[0] = 0;
+
+ // Make sure we have update values (scores)
+ CG_SetConfigValues();
+
+ CG_StartMusic();
+
+ CG_LoadingString( "" );
+
+#ifdef MISSIONPACK
+ CG_InitTeamChat();
+#endif
+
+ CG_ShaderStateChanged();
+
+ trap_S_ClearLoopingSounds( qtrue );
+}
+
+/*
+=================
+CG_Shutdown
+
+Called before every level change or subsystem restart
+=================
+*/
+void CG_Shutdown( void ) {
+ // some mods may need to do cleanup work here,
+ // like closing files or archiving session data
+}
+
+
+/*
+==================
+CG_EventHandling
+==================
+ type 0 - no event handling
+ 1 - team menu
+ 2 - hud editor
+
+*/
+#ifndef MISSIONPACK
+void CG_EventHandling(int type) {
+}
+
+
+
+void CG_KeyEvent(int key, qboolean down) {
+}
+
+void CG_MouseEvent(int x, int y) {
+}
+#endif
+
diff --git a/code/cgame/cg_marks.c b/code/cgame/cg_marks.c
new file mode 100755
index 0000000..4c648d2
--- /dev/null
+++ b/code/cgame/cg_marks.c
@@ -0,0 +1,2274 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// cg_marks.c -- wall marks
+
+#include "cg_local.h"
+
+/*
+===================================================================
+
+MARK POLYS
+
+===================================================================
+*/
+
+
+markPoly_t cg_activeMarkPolys; // double linked list
+markPoly_t *cg_freeMarkPolys; // single linked list
+markPoly_t cg_markPolys[MAX_MARK_POLYS];
+static int markTotal;
+
+/*
+===================
+CG_InitMarkPolys
+
+This is called at startup and for tournement restarts
+===================
+*/
+void CG_InitMarkPolys( void ) {
+ int i;
+
+ memset( cg_markPolys, 0, sizeof(cg_markPolys) );
+
+ cg_activeMarkPolys.nextMark = &cg_activeMarkPolys;
+ cg_activeMarkPolys.prevMark = &cg_activeMarkPolys;
+ cg_freeMarkPolys = cg_markPolys;
+ for ( i = 0 ; i < MAX_MARK_POLYS - 1 ; i++ ) {
+ cg_markPolys[i].nextMark = &cg_markPolys[i+1];
+ }
+}
+
+
+/*
+==================
+CG_FreeMarkPoly
+==================
+*/
+void CG_FreeMarkPoly( markPoly_t *le ) {
+ if ( !le->prevMark ) {
+ CG_Error( "CG_FreeLocalEntity: not active" );
+ }
+
+ // remove from the doubly linked active list
+ le->prevMark->nextMark = le->nextMark;
+ le->nextMark->prevMark = le->prevMark;
+
+ // the free list is only singly linked
+ le->nextMark = cg_freeMarkPolys;
+ cg_freeMarkPolys = le;
+}
+
+/*
+===================
+CG_AllocMark
+
+Will allways succeed, even if it requires freeing an old active mark
+===================
+*/
+markPoly_t *CG_AllocMark( void ) {
+ markPoly_t *le;
+ int time;
+
+ if ( !cg_freeMarkPolys ) {
+ // no free entities, so free the one at the end of the chain
+ // remove the oldest active entity
+ time = cg_activeMarkPolys.prevMark->time;
+ while (cg_activeMarkPolys.prevMark && time == cg_activeMarkPolys.prevMark->time) {
+ CG_FreeMarkPoly( cg_activeMarkPolys.prevMark );
+ }
+ }
+
+ le = cg_freeMarkPolys;
+ cg_freeMarkPolys = cg_freeMarkPolys->nextMark;
+
+ memset( le, 0, sizeof( *le ) );
+
+ // link into the active list
+ le->nextMark = cg_activeMarkPolys.nextMark;
+ le->prevMark = &cg_activeMarkPolys;
+ cg_activeMarkPolys.nextMark->prevMark = le;
+ cg_activeMarkPolys.nextMark = le;
+ return le;
+}
+
+
+
+/*
+=================
+CG_ImpactMark
+
+origin should be a point within a unit of the plane
+dir should be the plane normal
+
+temporary marks will not be stored or randomly oriented, but immediately
+passed to the renderer.
+=================
+*/
+#define MAX_MARK_FRAGMENTS 128
+#define MAX_MARK_POINTS 384
+
+void CG_ImpactMark( qhandle_t markShader, const vec3_t origin, const vec3_t dir,
+ float orientation, float red, float green, float blue, float alpha,
+ qboolean alphaFade, float radius, qboolean temporary ) {
+ vec3_t axis[3];
+ float texCoordScale;
+ vec3_t originalPoints[4];
+ byte colors[4];
+ int i, j;
+ int numFragments;
+ markFragment_t markFragments[MAX_MARK_FRAGMENTS], *mf;
+ vec3_t markPoints[MAX_MARK_POINTS];
+ vec3_t projection;
+
+ if ( !cg_addMarks.integer ) {
+ return;
+ }
+
+ if ( radius <= 0 ) {
+ CG_Error( "CG_ImpactMark called with <= 0 radius" );
+ }
+
+ //if ( markTotal >= MAX_MARK_POLYS ) {
+ // return;
+ //}
+
+ // create the texture axis
+ VectorNormalize2( dir, axis[0] );
+ PerpendicularVector( axis[1], axis[0] );
+ RotatePointAroundVector( axis[2], axis[0], axis[1], orientation );
+ CrossProduct( axis[0], axis[2], axis[1] );
+
+ texCoordScale = 0.5 * 1.0 / radius;
+
+ // create the full polygon
+ for ( i = 0 ; i < 3 ; i++ ) {
+ originalPoints[0][i] = origin[i] - radius * axis[1][i] - radius * axis[2][i];
+ originalPoints[1][i] = origin[i] + radius * axis[1][i] - radius * axis[2][i];
+ originalPoints[2][i] = origin[i] + radius * axis[1][i] + radius * axis[2][i];
+ originalPoints[3][i] = origin[i] - radius * axis[1][i] + radius * axis[2][i];
+ }
+
+ // get the fragments
+ VectorScale( dir, -20, projection );
+ numFragments = trap_CM_MarkFragments( 4, (void *)originalPoints,
+ projection, MAX_MARK_POINTS, markPoints[0],
+ MAX_MARK_FRAGMENTS, markFragments );
+
+ colors[0] = red * 255;
+ colors[1] = green * 255;
+ colors[2] = blue * 255;
+ colors[3] = alpha * 255;
+
+ for ( i = 0, mf = markFragments ; i < numFragments ; i++, mf++ ) {
+ polyVert_t *v;
+ polyVert_t verts[MAX_VERTS_ON_POLY];
+ markPoly_t *mark;
+
+ // we have an upper limit on the complexity of polygons
+ // that we store persistantly
+ if ( mf->numPoints > MAX_VERTS_ON_POLY ) {
+ mf->numPoints = MAX_VERTS_ON_POLY;
+ }
+ for ( j = 0, v = verts ; j < mf->numPoints ; j++, v++ ) {
+ vec3_t delta;
+
+ VectorCopy( markPoints[mf->firstPoint + j], v->xyz );
+
+ VectorSubtract( v->xyz, origin, delta );
+ v->st[0] = 0.5 + DotProduct( delta, axis[1] ) * texCoordScale;
+ v->st[1] = 0.5 + DotProduct( delta, axis[2] ) * texCoordScale;
+ *(int *)v->modulate = *(int *)colors;
+ }
+
+ // if it is a temporary (shadow) mark, add it immediately and forget about it
+ if ( temporary ) {
+ trap_R_AddPolyToScene( markShader, mf->numPoints, verts );
+ continue;
+ }
+
+ // otherwise save it persistantly
+ mark = CG_AllocMark();
+ mark->time = cg.time;
+ mark->alphaFade = alphaFade;
+ mark->markShader = markShader;
+ mark->poly.numVerts = mf->numPoints;
+ mark->color[0] = red;
+ mark->color[1] = green;
+ mark->color[2] = blue;
+ mark->color[3] = alpha;
+ memcpy( mark->verts, verts, mf->numPoints * sizeof( verts[0] ) );
+ markTotal++;
+ }
+}
+
+
+/*
+===============
+CG_AddMarks
+===============
+*/
+#define MARK_TOTAL_TIME 10000
+#define MARK_FADE_TIME 1000
+
+void CG_AddMarks( void ) {
+ int j;
+ markPoly_t *mp, *next;
+ int t;
+ int fade;
+
+ if ( !cg_addMarks.integer ) {
+ return;
+ }
+
+ mp = cg_activeMarkPolys.nextMark;
+ for ( ; mp != &cg_activeMarkPolys ; mp = next ) {
+ // grab next now, so if the local entity is freed we
+ // still have it
+ next = mp->nextMark;
+
+ // see if it is time to completely remove it
+ if ( cg.time > mp->time + MARK_TOTAL_TIME ) {
+ CG_FreeMarkPoly( mp );
+ continue;
+ }
+
+ // fade out the energy bursts
+ if ( mp->markShader == cgs.media.energyMarkShader ) {
+
+ fade = 450 - 450 * ( (cg.time - mp->time ) / 3000.0 );
+ if ( fade < 255 ) {
+ if ( fade < 0 ) {
+ fade = 0;
+ }
+ if ( mp->verts[0].modulate[0] != 0 ) {
+ for ( j = 0 ; j < mp->poly.numVerts ; j++ ) {
+ mp->verts[j].modulate[0] = mp->color[0] * fade;
+ mp->verts[j].modulate[1] = mp->color[1] * fade;
+ mp->verts[j].modulate[2] = mp->color[2] * fade;
+ }
+ }
+ }
+ }
+
+ // fade all marks out with time
+ t = mp->time + MARK_TOTAL_TIME - cg.time;
+ if ( t < MARK_FADE_TIME ) {
+ fade = 255 * t / MARK_FADE_TIME;
+ if ( mp->alphaFade ) {
+ for ( j = 0 ; j < mp->poly.numVerts ; j++ ) {
+ mp->verts[j].modulate[3] = fade;
+ }
+ } else {
+ for ( j = 0 ; j < mp->poly.numVerts ; j++ ) {
+ mp->verts[j].modulate[0] = mp->color[0] * fade;
+ mp->verts[j].modulate[1] = mp->color[1] * fade;
+ mp->verts[j].modulate[2] = mp->color[2] * fade;
+ }
+ }
+ }
+
+
+ trap_R_AddPolyToScene( mp->markShader, mp->poly.numVerts, mp->verts );
+ }
+}
+
+// cg_particles.c
+
+#define BLOODRED 2
+#define EMISIVEFADE 3
+#define GREY75 4
+
+typedef struct particle_s
+{
+ struct particle_s *next;
+
+ float time;
+ float endtime;
+
+ vec3_t org;
+ vec3_t vel;
+ vec3_t accel;
+ int color;
+ float colorvel;
+ float alpha;
+ float alphavel;
+ int type;
+ qhandle_t pshader;
+
+ float height;
+ float width;
+
+ float endheight;
+ float endwidth;
+
+ float start;
+ float end;
+
+ float startfade;
+ qboolean rotate;
+ int snum;
+
+ qboolean link;
+
+ // Ridah
+ int shaderAnim;
+ int roll;
+
+ int accumroll;
+
+} cparticle_t;
+
+typedef enum
+{
+ P_NONE,
+ P_WEATHER,
+ P_FLAT,
+ P_SMOKE,
+ P_ROTATE,
+ P_WEATHER_TURBULENT,
+ P_ANIM, // Ridah
+ P_BAT,
+ P_BLEED,
+ P_FLAT_SCALEUP,
+ P_FLAT_SCALEUP_FADE,
+ P_WEATHER_FLURRY,
+ P_SMOKE_IMPACT,
+ P_BUBBLE,
+ P_BUBBLE_TURBULENT,
+ P_SPRITE
+} particle_type_t;
+
+#define MAX_SHADER_ANIMS 32
+#define MAX_SHADER_ANIM_FRAMES 64
+
+static char *shaderAnimNames[MAX_SHADER_ANIMS] = {
+ "explode1",
+ NULL
+};
+static qhandle_t shaderAnims[MAX_SHADER_ANIMS][MAX_SHADER_ANIM_FRAMES];
+static int shaderAnimCounts[MAX_SHADER_ANIMS] = {
+ 23
+};
+static float shaderAnimSTRatio[MAX_SHADER_ANIMS] = {
+ 1.0f
+};
+static int numShaderAnims;
+// done.
+
+#define PARTICLE_GRAVITY 40
+#define MAX_PARTICLES 1024
+
+cparticle_t *active_particles, *free_particles;
+cparticle_t particles[MAX_PARTICLES];
+int cl_numparticles = MAX_PARTICLES;
+
+qboolean initparticles = qfalse;
+vec3_t pvforward, pvright, pvup;
+vec3_t rforward, rright, rup;
+
+float oldtime;
+
+/*
+===============
+CL_ClearParticles
+===============
+*/
+void CG_ClearParticles (void)
+{
+ int i;
+
+ memset( particles, 0, sizeof(particles) );
+
+ free_particles = &particles[0];
+ active_particles = NULL;
+
+ for (i=0 ;i<cl_numparticles ; i++)
+ {
+ particles[i].next = &particles[i+1];
+ particles[i].type = 0;
+ }
+ particles[cl_numparticles-1].next = NULL;
+
+ oldtime = cg.time;
+
+ // Ridah, init the shaderAnims
+ for (i=0; shaderAnimNames[i]; i++) {
+ int j;
+
+ for (j=0; j<shaderAnimCounts[i]; j++) {
+ shaderAnims[i][j] = trap_R_RegisterShader( va("%s%i", shaderAnimNames[i], j+1) );
+ }
+ }
+ numShaderAnims = i;
+ // done.
+
+ initparticles = qtrue;
+}
+
+
+/*
+=====================
+CG_AddParticleToScene
+=====================
+*/
+void CG_AddParticleToScene (cparticle_t *p, vec3_t org, float alpha)
+{
+
+ vec3_t point;
+ polyVert_t verts[4];
+ float width;
+ float height;
+ float time, time2;
+ float ratio;
+ float invratio;
+ vec3_t color;
+ polyVert_t TRIverts[3];
+ vec3_t rright2, rup2;
+
+ if (p->type == P_WEATHER || p->type == P_WEATHER_TURBULENT || p->type == P_WEATHER_FLURRY
+ || p->type == P_BUBBLE || p->type == P_BUBBLE_TURBULENT)
+ {// create a front facing polygon
+
+ if (p->type != P_WEATHER_FLURRY)
+ {
+ if (p->type == P_BUBBLE || p->type == P_BUBBLE_TURBULENT)
+ {
+ if (org[2] > p->end)
+ {
+ p->time = cg.time;
+ VectorCopy (org, p->org); // Ridah, fixes rare snow flakes that flicker on the ground
+
+ p->org[2] = ( p->start + crandom () * 4 );
+
+
+ if (p->type == P_BUBBLE_TURBULENT)
+ {
+ p->vel[0] = crandom() * 4;
+ p->vel[1] = crandom() * 4;
+ }
+
+ }
+ }
+ else
+ {
+ if (org[2] < p->end)
+ {
+ p->time = cg.time;
+ VectorCopy (org, p->org); // Ridah, fixes rare snow flakes that flicker on the ground
+
+ while (p->org[2] < p->end)
+ {
+ p->org[2] += (p->start - p->end);
+ }
+
+
+ if (p->type == P_WEATHER_TURBULENT)
+ {
+ p->vel[0] = crandom() * 16;
+ p->vel[1] = crandom() * 16;
+ }
+
+ }
+ }
+
+
+ // Rafael snow pvs check
+ if (!p->link)
+ return;
+
+ p->alpha = 1;
+ }
+
+ // Ridah, had to do this or MAX_POLYS is being exceeded in village1.bsp
+ if (Distance( cg.snap->ps.origin, org ) > 1024) {
+ return;
+ }
+ // done.
+
+ if (p->type == P_BUBBLE || p->type == P_BUBBLE_TURBULENT)
+ {
+ VectorMA (org, -p->height, pvup, point);
+ VectorMA (point, -p->width, pvright, point);
+ VectorCopy (point, verts[0].xyz);
+ verts[0].st[0] = 0;
+ verts[0].st[1] = 0;
+ verts[0].modulate[0] = 255;
+ verts[0].modulate[1] = 255;
+ verts[0].modulate[2] = 255;
+ verts[0].modulate[3] = 255 * p->alpha;
+
+ VectorMA (org, -p->height, pvup, point);
+ VectorMA (point, p->width, pvright, point);
+ VectorCopy (point, verts[1].xyz);
+ verts[1].st[0] = 0;
+ verts[1].st[1] = 1;
+ verts[1].modulate[0] = 255;
+ verts[1].modulate[1] = 255;
+ verts[1].modulate[2] = 255;
+ verts[1].modulate[3] = 255 * p->alpha;
+
+ VectorMA (org, p->height, pvup, point);
+ VectorMA (point, p->width, pvright, point);
+ VectorCopy (point, verts[2].xyz);
+ verts[2].st[0] = 1;
+ verts[2].st[1] = 1;
+ verts[2].modulate[0] = 255;
+ verts[2].modulate[1] = 255;
+ verts[2].modulate[2] = 255;
+ verts[2].modulate[3] = 255 * p->alpha;
+
+ VectorMA (org, p->height, pvup, point);
+ VectorMA (point, -p->width, pvright, point);
+ VectorCopy (point, verts[3].xyz);
+ verts[3].st[0] = 1;
+ verts[3].st[1] = 0;
+ verts[3].modulate[0] = 255;
+ verts[3].modulate[1] = 255;
+ verts[3].modulate[2] = 255;
+ verts[3].modulate[3] = 255 * p->alpha;
+ }
+ else
+ {
+ VectorMA (org, -p->height, pvup, point);
+ VectorMA (point, -p->width, pvright, point);
+ VectorCopy( point, TRIverts[0].xyz );
+ TRIverts[0].st[0] = 1;
+ TRIverts[0].st[1] = 0;
+ TRIverts[0].modulate[0] = 255;
+ TRIverts[0].modulate[1] = 255;
+ TRIverts[0].modulate[2] = 255;
+ TRIverts[0].modulate[3] = 255 * p->alpha;
+
+ VectorMA (org, p->height, pvup, point);
+ VectorMA (point, -p->width, pvright, point);
+ VectorCopy (point, TRIverts[1].xyz);
+ TRIverts[1].st[0] = 0;
+ TRIverts[1].st[1] = 0;
+ TRIverts[1].modulate[0] = 255;
+ TRIverts[1].modulate[1] = 255;
+ TRIverts[1].modulate[2] = 255;
+ TRIverts[1].modulate[3] = 255 * p->alpha;
+
+ VectorMA (org, p->height, pvup, point);
+ VectorMA (point, p->width, pvright, point);
+ VectorCopy (point, TRIverts[2].xyz);
+ TRIverts[2].st[0] = 0;
+ TRIverts[2].st[1] = 1;
+ TRIverts[2].modulate[0] = 255;
+ TRIverts[2].modulate[1] = 255;
+ TRIverts[2].modulate[2] = 255;
+ TRIverts[2].modulate[3] = 255 * p->alpha;
+ }
+
+ }
+ else if (p->type == P_SPRITE)
+ {
+ vec3_t rr, ru;
+ vec3_t rotate_ang;
+
+ VectorSet (color, 1.0, 1.0, 0.5);
+ time = cg.time - p->time;
+ time2 = p->endtime - p->time;
+ ratio = time / time2;
+
+ width = p->width + ( ratio * ( p->endwidth - p->width) );
+ height = p->height + ( ratio * ( p->endheight - p->height) );
+
+ if (p->roll) {
+ vectoangles( cg.refdef.viewaxis[0], rotate_ang );
+ rotate_ang[ROLL] += p->roll;
+ AngleVectors ( rotate_ang, NULL, rr, ru);
+ }
+
+ if (p->roll) {
+ VectorMA (org, -height, ru, point);
+ VectorMA (point, -width, rr, point);
+ } else {
+ VectorMA (org, -height, pvup, point);
+ VectorMA (point, -width, pvright, point);
+ }
+ VectorCopy (point, verts[0].xyz);
+ verts[0].st[0] = 0;
+ verts[0].st[1] = 0;
+ verts[0].modulate[0] = 255;
+ verts[0].modulate[1] = 255;
+ verts[0].modulate[2] = 255;
+ verts[0].modulate[3] = 255;
+
+ if (p->roll) {
+ VectorMA (point, 2*height, ru, point);
+ } else {
+ VectorMA (point, 2*height, pvup, point);
+ }
+ VectorCopy (point, verts[1].xyz);
+ verts[1].st[0] = 0;
+ verts[1].st[1] = 1;
+ verts[1].modulate[0] = 255;
+ verts[1].modulate[1] = 255;
+ verts[1].modulate[2] = 255;
+ verts[1].modulate[3] = 255;
+
+ if (p->roll) {
+ VectorMA (point, 2*width, rr, point);
+ } else {
+ VectorMA (point, 2*width, pvright, point);
+ }
+ VectorCopy (point, verts[2].xyz);
+ verts[2].st[0] = 1;
+ verts[2].st[1] = 1;
+ verts[2].modulate[0] = 255;
+ verts[2].modulate[1] = 255;
+ verts[2].modulate[2] = 255;
+ verts[2].modulate[3] = 255;
+
+ if (p->roll) {
+ VectorMA (point, -2*height, ru, point);
+ } else {
+ VectorMA (point, -2*height, pvup, point);
+ }
+ VectorCopy (point, verts[3].xyz);
+ verts[3].st[0] = 1;
+ verts[3].st[1] = 0;
+ verts[3].modulate[0] = 255;
+ verts[3].modulate[1] = 255;
+ verts[3].modulate[2] = 255;
+ verts[3].modulate[3] = 255;
+ }
+ else if (p->type == P_SMOKE || p->type == P_SMOKE_IMPACT)
+ {// create a front rotating facing polygon
+
+ if ( p->type == P_SMOKE_IMPACT && Distance( cg.snap->ps.origin, org ) > 1024) {
+ return;
+ }
+
+ if (p->color == BLOODRED)
+ VectorSet (color, 0.22f, 0.0f, 0.0f);
+ else if (p->color == GREY75)
+ {
+ float len;
+ float greyit;
+ float val;
+ len = Distance (cg.snap->ps.origin, org);
+ if (!len)
+ len = 1;
+
+ val = 4096/len;
+ greyit = 0.25 * val;
+ if (greyit > 0.5)
+ greyit = 0.5;
+
+ VectorSet (color, greyit, greyit, greyit);
+ }
+ else
+ VectorSet (color, 1.0, 1.0, 1.0);
+
+ time = cg.time - p->time;
+ time2 = p->endtime - p->time;
+ ratio = time / time2;
+
+ if (cg.time > p->startfade)
+ {
+ invratio = 1 - ( (cg.time - p->startfade) / (p->endtime - p->startfade) );
+
+ if (p->color == EMISIVEFADE)
+ {
+ float fval;
+ fval = (invratio * invratio);
+ if (fval < 0)
+ fval = 0;
+ VectorSet (color, fval , fval , fval );
+ }
+ invratio *= p->alpha;
+ }
+ else
+ invratio = 1 * p->alpha;
+
+ if ( cgs.glconfig.hardwareType == GLHW_RAGEPRO )
+ invratio = 1;
+
+ if (invratio > 1)
+ invratio = 1;
+
+ width = p->width + ( ratio * ( p->endwidth - p->width) );
+ height = p->height + ( ratio * ( p->endheight - p->height) );
+
+ if (p->type != P_SMOKE_IMPACT)
+ {
+ vec3_t temp;
+
+ vectoangles (rforward, temp);
+ p->accumroll += p->roll;
+ temp[ROLL] += p->accumroll * 0.1;
+ AngleVectors ( temp, NULL, rright2, rup2);
+ }
+ else
+ {
+ VectorCopy (rright, rright2);
+ VectorCopy (rup, rup2);
+ }
+
+ if (p->rotate)
+ {
+ VectorMA (org, -height, rup2, point);
+ VectorMA (point, -width, rright2, point);
+ }
+ else
+ {
+ VectorMA (org, -p->height, pvup, point);
+ VectorMA (point, -p->width, pvright, point);
+ }
+ VectorCopy (point, verts[0].xyz);
+ verts[0].st[0] = 0;
+ verts[0].st[1] = 0;
+ verts[0].modulate[0] = 255 * color[0];
+ verts[0].modulate[1] = 255 * color[1];
+ verts[0].modulate[2] = 255 * color[2];
+ verts[0].modulate[3] = 255 * invratio;
+
+ if (p->rotate)
+ {
+ VectorMA (org, -height, rup2, point);
+ VectorMA (point, width, rright2, point);
+ }
+ else
+ {
+ VectorMA (org, -p->height, pvup, point);
+ VectorMA (point, p->width, pvright, point);
+ }
+ VectorCopy (point, verts[1].xyz);
+ verts[1].st[0] = 0;
+ verts[1].st[1] = 1;
+ verts[1].modulate[0] = 255 * color[0];
+ verts[1].modulate[1] = 255 * color[1];
+ verts[1].modulate[2] = 255 * color[2];
+ verts[1].modulate[3] = 255 * invratio;
+
+ if (p->rotate)
+ {
+ VectorMA (org, height, rup2, point);
+ VectorMA (point, width, rright2, point);
+ }
+ else
+ {
+ VectorMA (org, p->height, pvup, point);
+ VectorMA (point, p->width, pvright, point);
+ }
+ VectorCopy (point, verts[2].xyz);
+ verts[2].st[0] = 1;
+ verts[2].st[1] = 1;
+ verts[2].modulate[0] = 255 * color[0];
+ verts[2].modulate[1] = 255 * color[1];
+ verts[2].modulate[2] = 255 * color[2];
+ verts[2].modulate[3] = 255 * invratio;
+
+ if (p->rotate)
+ {
+ VectorMA (org, height, rup2, point);
+ VectorMA (point, -width, rright2, point);
+ }
+ else
+ {
+ VectorMA (org, p->height, pvup, point);
+ VectorMA (point, -p->width, pvright, point);
+ }
+ VectorCopy (point, verts[3].xyz);
+ verts[3].st[0] = 1;
+ verts[3].st[1] = 0;
+ verts[3].modulate[0] = 255 * color[0];
+ verts[3].modulate[1] = 255 * color[1];
+ verts[3].modulate[2] = 255 * color[2];
+ verts[3].modulate[3] = 255 * invratio;
+
+ }
+ else if (p->type == P_BLEED)
+ {
+ vec3_t rr, ru;
+ vec3_t rotate_ang;
+ float alpha;
+
+ alpha = p->alpha;
+
+ if ( cgs.glconfig.hardwareType == GLHW_RAGEPRO )
+ alpha = 1;
+
+ if (p->roll)
+ {
+ vectoangles( cg.refdef.viewaxis[0], rotate_ang );
+ rotate_ang[ROLL] += p->roll;
+ AngleVectors ( rotate_ang, NULL, rr, ru);
+ }
+ else
+ {
+ VectorCopy (pvup, ru);
+ VectorCopy (pvright, rr);
+ }
+
+ VectorMA (org, -p->height, ru, point);
+ VectorMA (point, -p->width, rr, point);
+ VectorCopy (point, verts[0].xyz);
+ verts[0].st[0] = 0;
+ verts[0].st[1] = 0;
+ verts[0].modulate[0] = 111;
+ verts[0].modulate[1] = 19;
+ verts[0].modulate[2] = 9;
+ verts[0].modulate[3] = 255 * alpha;
+
+ VectorMA (org, -p->height, ru, point);
+ VectorMA (point, p->width, rr, point);
+ VectorCopy (point, verts[1].xyz);
+ verts[1].st[0] = 0;
+ verts[1].st[1] = 1;
+ verts[1].modulate[0] = 111;
+ verts[1].modulate[1] = 19;
+ verts[1].modulate[2] = 9;
+ verts[1].modulate[3] = 255 * alpha;
+
+ VectorMA (org, p->height, ru, point);
+ VectorMA (point, p->width, rr, point);
+ VectorCopy (point, verts[2].xyz);
+ verts[2].st[0] = 1;
+ verts[2].st[1] = 1;
+ verts[2].modulate[0] = 111;
+ verts[2].modulate[1] = 19;
+ verts[2].modulate[2] = 9;
+ verts[2].modulate[3] = 255 * alpha;
+
+ VectorMA (org, p->height, ru, point);
+ VectorMA (point, -p->width, rr, point);
+ VectorCopy (point, verts[3].xyz);
+ verts[3].st[0] = 1;
+ verts[3].st[1] = 0;
+ verts[3].modulate[0] = 111;
+ verts[3].modulate[1] = 19;
+ verts[3].modulate[2] = 9;
+ verts[3].modulate[3] = 255 * alpha;
+
+ }
+ else if (p->type == P_FLAT_SCALEUP)
+ {
+ float width, height;
+ float sinR, cosR;
+
+ if (p->color == BLOODRED)
+ VectorSet (color, 1, 1, 1);
+ else
+ VectorSet (color, 0.5, 0.5, 0.5);
+
+ time = cg.time - p->time;
+ time2 = p->endtime - p->time;
+ ratio = time / time2;
+
+ width = p->width + ( ratio * ( p->endwidth - p->width) );
+ height = p->height + ( ratio * ( p->endheight - p->height) );
+
+ if (width > p->endwidth)
+ width = p->endwidth;
+
+ if (height > p->endheight)
+ height = p->endheight;
+
+ sinR = height * sin(DEG2RAD(p->roll)) * sqrt(2);
+ cosR = width * cos(DEG2RAD(p->roll)) * sqrt(2);
+
+ VectorCopy (org, verts[0].xyz);
+ verts[0].xyz[0] -= sinR;
+ verts[0].xyz[1] -= cosR;
+ verts[0].st[0] = 0;
+ verts[0].st[1] = 0;
+ verts[0].modulate[0] = 255 * color[0];
+ verts[0].modulate[1] = 255 * color[1];
+ verts[0].modulate[2] = 255 * color[2];
+ verts[0].modulate[3] = 255;
+
+ VectorCopy (org, verts[1].xyz);
+ verts[1].xyz[0] -= cosR;
+ verts[1].xyz[1] += sinR;
+ verts[1].st[0] = 0;
+ verts[1].st[1] = 1;
+ verts[1].modulate[0] = 255 * color[0];
+ verts[1].modulate[1] = 255 * color[1];
+ verts[1].modulate[2] = 255 * color[2];
+ verts[1].modulate[3] = 255;
+
+ VectorCopy (org, verts[2].xyz);
+ verts[2].xyz[0] += sinR;
+ verts[2].xyz[1] += cosR;
+ verts[2].st[0] = 1;
+ verts[2].st[1] = 1;
+ verts[2].modulate[0] = 255 * color[0];
+ verts[2].modulate[1] = 255 * color[1];
+ verts[2].modulate[2] = 255 * color[2];
+ verts[2].modulate[3] = 255;
+
+ VectorCopy (org, verts[3].xyz);
+ verts[3].xyz[0] += cosR;
+ verts[3].xyz[1] -= sinR;
+ verts[3].st[0] = 1;
+ verts[3].st[1] = 0;
+ verts[3].modulate[0] = 255 * color[0];
+ verts[3].modulate[1] = 255 * color[1];
+ verts[3].modulate[2] = 255 * color[2];
+ verts[3].modulate[3] = 255;
+ }
+ else if (p->type == P_FLAT)
+ {
+
+ VectorCopy (org, verts[0].xyz);
+ verts[0].xyz[0] -= p->height;
+ verts[0].xyz[1] -= p->width;
+ verts[0].st[0] = 0;
+ verts[0].st[1] = 0;
+ verts[0].modulate[0] = 255;
+ verts[0].modulate[1] = 255;
+ verts[0].modulate[2] = 255;
+ verts[0].modulate[3] = 255;
+
+ VectorCopy (org, verts[1].xyz);
+ verts[1].xyz[0] -= p->height;
+ verts[1].xyz[1] += p->width;
+ verts[1].st[0] = 0;
+ verts[1].st[1] = 1;
+ verts[1].modulate[0] = 255;
+ verts[1].modulate[1] = 255;
+ verts[1].modulate[2] = 255;
+ verts[1].modulate[3] = 255;
+
+ VectorCopy (org, verts[2].xyz);
+ verts[2].xyz[0] += p->height;
+ verts[2].xyz[1] += p->width;
+ verts[2].st[0] = 1;
+ verts[2].st[1] = 1;
+ verts[2].modulate[0] = 255;
+ verts[2].modulate[1] = 255;
+ verts[2].modulate[2] = 255;
+ verts[2].modulate[3] = 255;
+
+ VectorCopy (org, verts[3].xyz);
+ verts[3].xyz[0] += p->height;
+ verts[3].xyz[1] -= p->width;
+ verts[3].st[0] = 1;
+ verts[3].st[1] = 0;
+ verts[3].modulate[0] = 255;
+ verts[3].modulate[1] = 255;
+ verts[3].modulate[2] = 255;
+ verts[3].modulate[3] = 255;
+
+ }
+ // Ridah
+ else if (p->type == P_ANIM) {
+ vec3_t rr, ru;
+ vec3_t rotate_ang;
+ int i, j;
+
+ time = cg.time - p->time;
+ time2 = p->endtime - p->time;
+ ratio = time / time2;
+ if (ratio >= 1.0f) {
+ ratio = 0.9999f;
+ }
+
+ width = p->width + ( ratio * ( p->endwidth - p->width) );
+ height = p->height + ( ratio * ( p->endheight - p->height) );
+
+ // if we are "inside" this sprite, don't draw
+ if (Distance( cg.snap->ps.origin, org ) < width/1.5) {
+ return;
+ }
+
+ i = p->shaderAnim;
+ j = (int)floor(ratio * shaderAnimCounts[p->shaderAnim]);
+ p->pshader = shaderAnims[i][j];
+
+ if (p->roll) {
+ vectoangles( cg.refdef.viewaxis[0], rotate_ang );
+ rotate_ang[ROLL] += p->roll;
+ AngleVectors ( rotate_ang, NULL, rr, ru);
+ }
+
+ if (p->roll) {
+ VectorMA (org, -height, ru, point);
+ VectorMA (point, -width, rr, point);
+ } else {
+ VectorMA (org, -height, pvup, point);
+ VectorMA (point, -width, pvright, point);
+ }
+ VectorCopy (point, verts[0].xyz);
+ verts[0].st[0] = 0;
+ verts[0].st[1] = 0;
+ verts[0].modulate[0] = 255;
+ verts[0].modulate[1] = 255;
+ verts[0].modulate[2] = 255;
+ verts[0].modulate[3] = 255;
+
+ if (p->roll) {
+ VectorMA (point, 2*height, ru, point);
+ } else {
+ VectorMA (point, 2*height, pvup, point);
+ }
+ VectorCopy (point, verts[1].xyz);
+ verts[1].st[0] = 0;
+ verts[1].st[1] = 1;
+ verts[1].modulate[0] = 255;
+ verts[1].modulate[1] = 255;
+ verts[1].modulate[2] = 255;
+ verts[1].modulate[3] = 255;
+
+ if (p->roll) {
+ VectorMA (point, 2*width, rr, point);
+ } else {
+ VectorMA (point, 2*width, pvright, point);
+ }
+ VectorCopy (point, verts[2].xyz);
+ verts[2].st[0] = 1;
+ verts[2].st[1] = 1;
+ verts[2].modulate[0] = 255;
+ verts[2].modulate[1] = 255;
+ verts[2].modulate[2] = 255;
+ verts[2].modulate[3] = 255;
+
+ if (p->roll) {
+ VectorMA (point, -2*height, ru, point);
+ } else {
+ VectorMA (point, -2*height, pvup, point);
+ }
+ VectorCopy (point, verts[3].xyz);
+ verts[3].st[0] = 1;
+ verts[3].st[1] = 0;
+ verts[3].modulate[0] = 255;
+ verts[3].modulate[1] = 255;
+ verts[3].modulate[2] = 255;
+ verts[3].modulate[3] = 255;
+ }
+ // done.
+
+ if (!p->pshader) {
+// (SA) temp commented out for DM
+// CG_Printf ("CG_AddParticleToScene type %d p->pshader == ZERO\n", p->type);
+ return;
+ }
+
+ if (p->type == P_WEATHER || p->type == P_WEATHER_TURBULENT || p->type == P_WEATHER_FLURRY)
+ trap_R_AddPolyToScene( p->pshader, 3, TRIverts );
+ else
+ trap_R_AddPolyToScene( p->pshader, 4, verts );
+
+}
+
+// Ridah, made this static so it doesn't interfere with other files
+static float roll = 0.0;
+
+/*
+===============
+CG_AddParticles
+===============
+*/
+void CG_AddParticles (void)
+{
+ cparticle_t *p, *next;
+ float alpha;
+ float time, time2;
+ vec3_t org;
+ int color;
+ cparticle_t *active, *tail;
+ int type;
+ vec3_t rotate_ang;
+
+ if (!initparticles)
+ CG_ClearParticles ();
+
+ VectorCopy( cg.refdef.viewaxis[0], pvforward );
+ VectorCopy( cg.refdef.viewaxis[1], pvright );
+ VectorCopy( cg.refdef.viewaxis[2], pvup );
+
+ vectoangles( cg.refdef.viewaxis[0], rotate_ang );
+ roll += ((cg.time - oldtime) * 0.1) ;
+ rotate_ang[ROLL] += (roll*0.9);
+ AngleVectors ( rotate_ang, rforward, rright, rup);
+
+ oldtime = cg.time;
+
+ active = NULL;
+ tail = NULL;
+
+ for (p=active_particles ; p ; p=next)
+ {
+
+ next = p->next;
+
+ time = (cg.time - p->time)*0.001;
+
+ alpha = p->alpha + time*p->alphavel;
+ if (alpha <= 0)
+ { // faded out
+ p->next = free_particles;
+ free_particles = p;
+ p->type = 0;
+ p->color = 0;
+ p->alpha = 0;
+ continue;
+ }
+
+ if (p->type == P_SMOKE || p->type == P_ANIM || p->type == P_BLEED || p->type == P_SMOKE_IMPACT)
+ {
+ if (cg.time > p->endtime)
+ {
+ p->next = free_particles;
+ free_particles = p;
+ p->type = 0;
+ p->color = 0;
+ p->alpha = 0;
+
+ continue;
+ }
+
+ }
+
+ if (p->type == P_WEATHER_FLURRY)
+ {
+ if (cg.time > p->endtime)
+ {
+ p->next = free_particles;
+ free_particles = p;
+ p->type = 0;
+ p->color = 0;
+ p->alpha = 0;
+
+ continue;
+ }
+ }
+
+
+ if (p->type == P_FLAT_SCALEUP_FADE)
+ {
+ if (cg.time > p->endtime)
+ {
+ p->next = free_particles;
+ free_particles = p;
+ p->type = 0;
+ p->color = 0;
+ p->alpha = 0;
+ continue;
+ }
+
+ }
+
+ if ((p->type == P_BAT || p->type == P_SPRITE) && p->endtime < 0) {
+ // temporary sprite
+ CG_AddParticleToScene (p, p->org, alpha);
+ p->next = free_particles;
+ free_particles = p;
+ p->type = 0;
+ p->color = 0;
+ p->alpha = 0;
+ continue;
+ }
+
+ p->next = NULL;
+ if (!tail)
+ active = tail = p;
+ else
+ {
+ tail->next = p;
+ tail = p;
+ }
+
+ if (alpha > 1.0)
+ alpha = 1;
+
+ color = p->color;
+
+ time2 = time*time;
+
+ org[0] = p->org[0] + p->vel[0]*time + p->accel[0]*time2;
+ org[1] = p->org[1] + p->vel[1]*time + p->accel[1]*time2;
+ org[2] = p->org[2] + p->vel[2]*time + p->accel[2]*time2;
+
+ type = p->type;
+
+ CG_AddParticleToScene (p, org, alpha);
+ }
+
+ active_particles = active;
+}
+
+/*
+======================
+CG_AddParticles
+======================
+*/
+void CG_ParticleSnowFlurry (qhandle_t pshader, centity_t *cent)
+{
+ cparticle_t *p;
+ qboolean turb = qtrue;
+
+ if (!pshader)
+ CG_Printf ("CG_ParticleSnowFlurry pshader == ZERO!\n");
+
+ if (!free_particles)
+ return;
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+ p->color = 0;
+ p->alpha = 0.90f;
+ p->alphavel = 0;
+
+ p->start = cent->currentState.origin2[0];
+ p->end = cent->currentState.origin2[1];
+
+ p->endtime = cg.time + cent->currentState.time;
+ p->startfade = cg.time + cent->currentState.time2;
+
+ p->pshader = pshader;
+
+ if (rand()%100 > 90)
+ {
+ p->height = 32;
+ p->width = 32;
+ p->alpha = 0.10f;
+ }
+ else
+ {
+ p->height = 1;
+ p->width = 1;
+ }
+
+ p->vel[2] = -20;
+
+ p->type = P_WEATHER_FLURRY;
+
+ if (turb)
+ p->vel[2] = -10;
+
+ VectorCopy(cent->currentState.origin, p->org);
+
+ p->org[0] = p->org[0];
+ p->org[1] = p->org[1];
+ p->org[2] = p->org[2];
+
+ p->vel[0] = p->vel[1] = 0;
+
+ p->accel[0] = p->accel[1] = p->accel[2] = 0;
+
+ p->vel[0] += cent->currentState.angles[0] * 32 + (crandom() * 16);
+ p->vel[1] += cent->currentState.angles[1] * 32 + (crandom() * 16);
+ p->vel[2] += cent->currentState.angles[2];
+
+ if (turb)
+ {
+ p->accel[0] = crandom () * 16;
+ p->accel[1] = crandom () * 16;
+ }
+
+}
+
+void CG_ParticleSnow (qhandle_t pshader, vec3_t origin, vec3_t origin2, int turb, float range, int snum)
+{
+ cparticle_t *p;
+
+ if (!pshader)
+ CG_Printf ("CG_ParticleSnow pshader == ZERO!\n");
+
+ if (!free_particles)
+ return;
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+ p->color = 0;
+ p->alpha = 0.40f;
+ p->alphavel = 0;
+ p->start = origin[2];
+ p->end = origin2[2];
+ p->pshader = pshader;
+ p->height = 1;
+ p->width = 1;
+
+ p->vel[2] = -50;
+
+ if (turb)
+ {
+ p->type = P_WEATHER_TURBULENT;
+ p->vel[2] = -50 * 1.3;
+ }
+ else
+ {
+ p->type = P_WEATHER;
+ }
+
+ VectorCopy(origin, p->org);
+
+ p->org[0] = p->org[0] + ( crandom() * range);
+ p->org[1] = p->org[1] + ( crandom() * range);
+ p->org[2] = p->org[2] + ( crandom() * (p->start - p->end));
+
+ p->vel[0] = p->vel[1] = 0;
+
+ p->accel[0] = p->accel[1] = p->accel[2] = 0;
+
+ if (turb)
+ {
+ p->vel[0] = crandom() * 16;
+ p->vel[1] = crandom() * 16;
+ }
+
+ // Rafael snow pvs check
+ p->snum = snum;
+ p->link = qtrue;
+
+}
+
+void CG_ParticleBubble (qhandle_t pshader, vec3_t origin, vec3_t origin2, int turb, float range, int snum)
+{
+ cparticle_t *p;
+ float randsize;
+
+ if (!pshader)
+ CG_Printf ("CG_ParticleSnow pshader == ZERO!\n");
+
+ if (!free_particles)
+ return;
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+ p->color = 0;
+ p->alpha = 0.40f;
+ p->alphavel = 0;
+ p->start = origin[2];
+ p->end = origin2[2];
+ p->pshader = pshader;
+
+ randsize = 1 + (crandom() * 0.5);
+
+ p->height = randsize;
+ p->width = randsize;
+
+ p->vel[2] = 50 + ( crandom() * 10 );
+
+ if (turb)
+ {
+ p->type = P_BUBBLE_TURBULENT;
+ p->vel[2] = 50 * 1.3;
+ }
+ else
+ {
+ p->type = P_BUBBLE;
+ }
+
+ VectorCopy(origin, p->org);
+
+ p->org[0] = p->org[0] + ( crandom() * range);
+ p->org[1] = p->org[1] + ( crandom() * range);
+ p->org[2] = p->org[2] + ( crandom() * (p->start - p->end));
+
+ p->vel[0] = p->vel[1] = 0;
+
+ p->accel[0] = p->accel[1] = p->accel[2] = 0;
+
+ if (turb)
+ {
+ p->vel[0] = crandom() * 4;
+ p->vel[1] = crandom() * 4;
+ }
+
+ // Rafael snow pvs check
+ p->snum = snum;
+ p->link = qtrue;
+
+}
+
+void CG_ParticleSmoke (qhandle_t pshader, centity_t *cent)
+{
+
+ // using cent->density = enttime
+ // cent->frame = startfade
+ cparticle_t *p;
+
+ if (!pshader)
+ CG_Printf ("CG_ParticleSmoke == ZERO!\n");
+
+ if (!free_particles)
+ return;
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+
+ p->endtime = cg.time + cent->currentState.time;
+ p->startfade = cg.time + cent->currentState.time2;
+
+ p->color = 0;
+ p->alpha = 1.0;
+ p->alphavel = 0;
+ p->start = cent->currentState.origin[2];
+ p->end = cent->currentState.origin2[2];
+ p->pshader = pshader;
+ p->rotate = qfalse;
+ p->height = 8;
+ p->width = 8;
+ p->endheight = 32;
+ p->endwidth = 32;
+ p->type = P_SMOKE;
+
+ VectorCopy(cent->currentState.origin, p->org);
+
+ p->vel[0] = p->vel[1] = 0;
+ p->accel[0] = p->accel[1] = p->accel[2] = 0;
+
+ p->vel[2] = 5;
+
+ if (cent->currentState.frame == 1)// reverse gravity
+ p->vel[2] *= -1;
+
+ p->roll = 8 + (crandom() * 4);
+}
+
+
+void CG_ParticleBulletDebris (vec3_t org, vec3_t vel, int duration)
+{
+
+ cparticle_t *p;
+
+ if (!free_particles)
+ return;
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+
+ p->endtime = cg.time + duration;
+ p->startfade = cg.time + duration/2;
+
+ p->color = EMISIVEFADE;
+ p->alpha = 1.0;
+ p->alphavel = 0;
+
+ p->height = 0.5;
+ p->width = 0.5;
+ p->endheight = 0.5;
+ p->endwidth = 0.5;
+
+ p->pshader = cgs.media.tracerShader;
+
+ p->type = P_SMOKE;
+
+ VectorCopy(org, p->org);
+
+ p->vel[0] = vel[0];
+ p->vel[1] = vel[1];
+ p->vel[2] = vel[2];
+ p->accel[0] = p->accel[1] = p->accel[2] = 0;
+
+ p->accel[2] = -60;
+ p->vel[2] += -20;
+
+}
+
+/*
+======================
+CG_ParticleExplosion
+======================
+*/
+
+void CG_ParticleExplosion (char *animStr, vec3_t origin, vec3_t vel, int duration, int sizeStart, int sizeEnd)
+{
+ cparticle_t *p;
+ int anim;
+
+ if (animStr < (char *)10)
+ CG_Error( "CG_ParticleExplosion: animStr is probably an index rather than a string" );
+
+ // find the animation string
+ for (anim=0; shaderAnimNames[anim]; anim++) {
+ if (!Q_stricmp( animStr, shaderAnimNames[anim] ))
+ break;
+ }
+ if (!shaderAnimNames[anim]) {
+ CG_Error("CG_ParticleExplosion: unknown animation string: %s\n", animStr);
+ return;
+ }
+
+ if (!free_particles)
+ return;
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+ p->alpha = 0.5;
+ p->alphavel = 0;
+
+ if (duration < 0) {
+ duration *= -1;
+ p->roll = 0;
+ } else {
+ p->roll = crandom()*179;
+ }
+
+ p->shaderAnim = anim;
+
+ p->width = sizeStart;
+ p->height = sizeStart*shaderAnimSTRatio[anim]; // for sprites that are stretch in either direction
+
+ p->endheight = sizeEnd;
+ p->endwidth = sizeEnd*shaderAnimSTRatio[anim];
+
+ p->endtime = cg.time + duration;
+
+ p->type = P_ANIM;
+
+ VectorCopy( origin, p->org );
+ VectorCopy( vel, p->vel );
+ VectorClear( p->accel );
+
+}
+
+// Rafael Shrapnel
+void CG_AddParticleShrapnel (localEntity_t *le)
+{
+ return;
+}
+// done.
+
+int CG_NewParticleArea (int num)
+{
+ // const char *str;
+ char *str;
+ char *token;
+ int type;
+ vec3_t origin, origin2;
+ int i;
+ float range = 0;
+ int turb;
+ int numparticles;
+ int snum;
+
+ str = (char *) CG_ConfigString (num);
+ if (!str[0])
+ return (0);
+
+ // returns type 128 64 or 32
+ token = COM_Parse (&str);
+ type = atoi (token);
+
+ if (type == 1)
+ range = 128;
+ else if (type == 2)
+ range = 64;
+ else if (type == 3)
+ range = 32;
+ else if (type == 0)
+ range = 256;
+ else if (type == 4)
+ range = 8;
+ else if (type == 5)
+ range = 16;
+ else if (type == 6)
+ range = 32;
+ else if (type == 7)
+ range = 64;
+
+
+ for (i=0; i<3; i++)
+ {
+ token = COM_Parse (&str);
+ origin[i] = atof (token);
+ }
+
+ for (i=0; i<3; i++)
+ {
+ token = COM_Parse (&str);
+ origin2[i] = atof (token);
+ }
+
+ token = COM_Parse (&str);
+ numparticles = atoi (token);
+
+ token = COM_Parse (&str);
+ turb = atoi (token);
+
+ token = COM_Parse (&str);
+ snum = atoi (token);
+
+ for (i=0; i<numparticles; i++)
+ {
+ if (type >= 4)
+ CG_ParticleBubble (cgs.media.waterBubbleShader, origin, origin2, turb, range, snum);
+ else
+ CG_ParticleSnow (cgs.media.waterBubbleShader, origin, origin2, turb, range, snum);
+ }
+
+ return (1);
+}
+
+void CG_SnowLink (centity_t *cent, qboolean particleOn)
+{
+ cparticle_t *p, *next;
+ int id;
+
+ id = cent->currentState.frame;
+
+ for (p=active_particles ; p ; p=next)
+ {
+ next = p->next;
+
+ if (p->type == P_WEATHER || p->type == P_WEATHER_TURBULENT)
+ {
+ if (p->snum == id)
+ {
+ if (particleOn)
+ p->link = qtrue;
+ else
+ p->link = qfalse;
+ }
+ }
+
+ }
+}
+
+void CG_ParticleImpactSmokePuff (qhandle_t pshader, vec3_t origin)
+{
+ cparticle_t *p;
+
+ if (!pshader)
+ CG_Printf ("CG_ParticleImpactSmokePuff pshader == ZERO!\n");
+
+ if (!free_particles)
+ return;
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+ p->alpha = 0.25;
+ p->alphavel = 0;
+ p->roll = crandom()*179;
+
+ p->pshader = pshader;
+
+ p->endtime = cg.time + 1000;
+ p->startfade = cg.time + 100;
+
+ p->width = rand()%4 + 8;
+ p->height = rand()%4 + 8;
+
+ p->endheight = p->height *2;
+ p->endwidth = p->width * 2;
+
+ p->endtime = cg.time + 500;
+
+ p->type = P_SMOKE_IMPACT;
+
+ VectorCopy( origin, p->org );
+ VectorSet(p->vel, 0, 0, 20);
+ VectorSet(p->accel, 0, 0, 20);
+
+ p->rotate = qtrue;
+}
+
+void CG_Particle_Bleed (qhandle_t pshader, vec3_t start, vec3_t dir, int fleshEntityNum, int duration)
+{
+ cparticle_t *p;
+
+ if (!pshader)
+ CG_Printf ("CG_Particle_Bleed pshader == ZERO!\n");
+
+ if (!free_particles)
+ return;
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+ p->alpha = 1.0;
+ p->alphavel = 0;
+ p->roll = 0;
+
+ p->pshader = pshader;
+
+ p->endtime = cg.time + duration;
+
+ if (fleshEntityNum)
+ p->startfade = cg.time;
+ else
+ p->startfade = cg.time + 100;
+
+ p->width = 4;
+ p->height = 4;
+
+ p->endheight = 4+rand()%3;
+ p->endwidth = p->endheight;
+
+ p->type = P_SMOKE;
+
+ VectorCopy( start, p->org );
+ p->vel[0] = 0;
+ p->vel[1] = 0;
+ p->vel[2] = -20;
+ VectorClear( p->accel );
+
+ p->rotate = qfalse;
+
+ p->roll = rand()%179;
+
+ p->color = BLOODRED;
+ p->alpha = 0.75;
+
+}
+
+void CG_Particle_OilParticle (qhandle_t pshader, centity_t *cent)
+{
+ cparticle_t *p;
+
+ int time;
+ int time2;
+ float ratio;
+
+ float duration = 1500;
+
+ time = cg.time;
+ time2 = cg.time + cent->currentState.time;
+
+ ratio =(float)1 - ((float)time / (float)time2);
+
+ if (!pshader)
+ CG_Printf ("CG_Particle_OilParticle == ZERO!\n");
+
+ if (!free_particles)
+ return;
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+ p->alpha = 1.0;
+ p->alphavel = 0;
+ p->roll = 0;
+
+ p->pshader = pshader;
+
+ p->endtime = cg.time + duration;
+
+ p->startfade = p->endtime;
+
+ p->width = 1;
+ p->height = 3;
+
+ p->endheight = 3;
+ p->endwidth = 1;
+
+ p->type = P_SMOKE;
+
+ VectorCopy(cent->currentState.origin, p->org );
+
+ p->vel[0] = (cent->currentState.origin2[0] * (16 * ratio));
+ p->vel[1] = (cent->currentState.origin2[1] * (16 * ratio));
+ p->vel[2] = (cent->currentState.origin2[2]);
+
+ p->snum = 1.0f;
+
+ VectorClear( p->accel );
+
+ p->accel[2] = -20;
+
+ p->rotate = qfalse;
+
+ p->roll = rand()%179;
+
+ p->alpha = 0.75;
+
+}
+
+
+void CG_Particle_OilSlick (qhandle_t pshader, centity_t *cent)
+{
+ cparticle_t *p;
+
+ if (!pshader)
+ CG_Printf ("CG_Particle_OilSlick == ZERO!\n");
+
+ if (!free_particles)
+ return;
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+
+ if (cent->currentState.angles2[2])
+ p->endtime = cg.time + cent->currentState.angles2[2];
+ else
+ p->endtime = cg.time + 60000;
+
+ p->startfade = p->endtime;
+
+ p->alpha = 1.0;
+ p->alphavel = 0;
+ p->roll = 0;
+
+ p->pshader = pshader;
+
+ if (cent->currentState.angles2[0] || cent->currentState.angles2[1])
+ {
+ p->width = cent->currentState.angles2[0];
+ p->height = cent->currentState.angles2[0];
+
+ p->endheight = cent->currentState.angles2[1];
+ p->endwidth = cent->currentState.angles2[1];
+ }
+ else
+ {
+ p->width = 8;
+ p->height = 8;
+
+ p->endheight = 16;
+ p->endwidth = 16;
+ }
+
+ p->type = P_FLAT_SCALEUP;
+
+ p->snum = 1.0;
+
+ VectorCopy(cent->currentState.origin, p->org );
+
+ p->org[2]+= 0.55 + (crandom() * 0.5);
+
+ p->vel[0] = 0;
+ p->vel[1] = 0;
+ p->vel[2] = 0;
+ VectorClear( p->accel );
+
+ p->rotate = qfalse;
+
+ p->roll = rand()%179;
+
+ p->alpha = 0.75;
+
+}
+
+void CG_OilSlickRemove (centity_t *cent)
+{
+ cparticle_t *p, *next;
+ int id;
+
+ id = 1.0f;
+
+ if (!id)
+ CG_Printf ("CG_OilSlickRevove NULL id\n");
+
+ for (p=active_particles ; p ; p=next)
+ {
+ next = p->next;
+
+ if (p->type == P_FLAT_SCALEUP)
+ {
+ if (p->snum == id)
+ {
+ p->endtime = cg.time + 100;
+ p->startfade = p->endtime;
+ p->type = P_FLAT_SCALEUP_FADE;
+
+ }
+ }
+
+ }
+}
+
+qboolean ValidBloodPool (vec3_t start)
+{
+#define EXTRUDE_DIST 0.5
+
+ vec3_t angles;
+ vec3_t right, up;
+ vec3_t this_pos, x_pos, center_pos, end_pos;
+ float x, y;
+ float fwidth, fheight;
+ trace_t trace;
+ vec3_t normal;
+
+ fwidth = 16;
+ fheight = 16;
+
+ VectorSet (normal, 0, 0, 1);
+
+ vectoangles (normal, angles);
+ AngleVectors (angles, NULL, right, up);
+
+ VectorMA (start, EXTRUDE_DIST, normal, center_pos);
+
+ for (x= -fwidth/2; x<fwidth; x+= fwidth)
+ {
+ VectorMA (center_pos, x, right, x_pos);
+
+ for (y= -fheight/2; y<fheight; y+= fheight)
+ {
+ VectorMA (x_pos, y, up, this_pos);
+ VectorMA (this_pos, -EXTRUDE_DIST*2, normal, end_pos);
+
+ CG_Trace (&trace, this_pos, NULL, NULL, end_pos, -1, CONTENTS_SOLID);
+
+
+ if (trace.entityNum < (MAX_ENTITIES - 1)) // may only land on world
+ return qfalse;
+
+ if (!(!trace.startsolid && trace.fraction < 1))
+ return qfalse;
+
+ }
+ }
+
+ return qtrue;
+}
+
+void CG_BloodPool (localEntity_t *le, qhandle_t pshader, trace_t *tr)
+{
+ cparticle_t *p;
+ qboolean legit;
+ vec3_t start;
+ float rndSize;
+
+ if (!pshader)
+ CG_Printf ("CG_BloodPool pshader == ZERO!\n");
+
+ if (!free_particles)
+ return;
+
+ VectorCopy (tr->endpos, start);
+ legit = ValidBloodPool (start);
+
+ if (!legit)
+ return;
+
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+
+ p->endtime = cg.time + 3000;
+ p->startfade = p->endtime;
+
+ p->alpha = 1.0;
+ p->alphavel = 0;
+ p->roll = 0;
+
+ p->pshader = pshader;
+
+ rndSize = 0.4 + random()*0.6;
+
+ p->width = 8*rndSize;
+ p->height = 8*rndSize;
+
+ p->endheight = 16*rndSize;
+ p->endwidth = 16*rndSize;
+
+ p->type = P_FLAT_SCALEUP;
+
+ VectorCopy(start, p->org );
+
+ p->vel[0] = 0;
+ p->vel[1] = 0;
+ p->vel[2] = 0;
+ VectorClear( p->accel );
+
+ p->rotate = qfalse;
+
+ p->roll = rand()%179;
+
+ p->alpha = 0.75;
+
+ p->color = BLOODRED;
+}
+
+#define NORMALSIZE 16
+#define LARGESIZE 32
+
+void CG_ParticleBloodCloud (centity_t *cent, vec3_t origin, vec3_t dir)
+{
+ float length;
+ float dist;
+ float crittersize;
+ vec3_t angles, forward;
+ vec3_t point;
+ cparticle_t *p;
+ int i;
+
+ dist = 0;
+
+ length = VectorLength (dir);
+ vectoangles (dir, angles);
+ AngleVectors (angles, forward, NULL, NULL);
+
+ crittersize = LARGESIZE;
+
+ if (length)
+ dist = length / crittersize;
+
+ if (dist < 1)
+ dist = 1;
+
+ VectorCopy (origin, point);
+
+ for (i=0; i<dist; i++)
+ {
+ VectorMA (point, crittersize, forward, point);
+
+ if (!free_particles)
+ return;
+
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+
+ p->time = cg.time;
+ p->alpha = 1.0;
+ p->alphavel = 0;
+ p->roll = 0;
+
+ p->pshader = cgs.media.smokePuffShader;
+
+ p->endtime = cg.time + 350 + (crandom() * 100);
+
+ p->startfade = cg.time;
+
+ p->width = LARGESIZE;
+ p->height = LARGESIZE;
+ p->endheight = LARGESIZE;
+ p->endwidth = LARGESIZE;
+
+ p->type = P_SMOKE;
+
+ VectorCopy( origin, p->org );
+
+ p->vel[0] = 0;
+ p->vel[1] = 0;
+ p->vel[2] = -1;
+
+ VectorClear( p->accel );
+
+ p->rotate = qfalse;
+
+ p->roll = rand()%179;
+
+ p->color = BLOODRED;
+
+ p->alpha = 0.75;
+
+ }
+
+
+}
+
+void CG_ParticleSparks (vec3_t org, vec3_t vel, int duration, float x, float y, float speed)
+{
+ cparticle_t *p;
+
+ if (!free_particles)
+ return;
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+
+ p->endtime = cg.time + duration;
+ p->startfade = cg.time + duration/2;
+
+ p->color = EMISIVEFADE;
+ p->alpha = 0.4f;
+ p->alphavel = 0;
+
+ p->height = 0.5;
+ p->width = 0.5;
+ p->endheight = 0.5;
+ p->endwidth = 0.5;
+
+ p->pshader = cgs.media.tracerShader;
+
+ p->type = P_SMOKE;
+
+ VectorCopy(org, p->org);
+
+ p->org[0] += (crandom() * x);
+ p->org[1] += (crandom() * y);
+
+ p->vel[0] = vel[0];
+ p->vel[1] = vel[1];
+ p->vel[2] = vel[2];
+
+ p->accel[0] = p->accel[1] = p->accel[2] = 0;
+
+ p->vel[0] += (crandom() * 4);
+ p->vel[1] += (crandom() * 4);
+ p->vel[2] += (20 + (crandom() * 10)) * speed;
+
+ p->accel[0] = crandom () * 4;
+ p->accel[1] = crandom () * 4;
+
+}
+
+void CG_ParticleDust (centity_t *cent, vec3_t origin, vec3_t dir)
+{
+ float length;
+ float dist;
+ float crittersize;
+ vec3_t angles, forward;
+ vec3_t point;
+ cparticle_t *p;
+ int i;
+
+ dist = 0;
+
+ VectorNegate (dir, dir);
+ length = VectorLength (dir);
+ vectoangles (dir, angles);
+ AngleVectors (angles, forward, NULL, NULL);
+
+ crittersize = LARGESIZE;
+
+ if (length)
+ dist = length / crittersize;
+
+ if (dist < 1)
+ dist = 1;
+
+ VectorCopy (origin, point);
+
+ for (i=0; i<dist; i++)
+ {
+ VectorMA (point, crittersize, forward, point);
+
+ if (!free_particles)
+ return;
+
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+
+ p->time = cg.time;
+ p->alpha = 5.0;
+ p->alphavel = 0;
+ p->roll = 0;
+
+ p->pshader = cgs.media.smokePuffShader;
+
+ // RF, stay around for long enough to expand and dissipate naturally
+ if (length)
+ p->endtime = cg.time + 4500 + (crandom() * 3500);
+ else
+ p->endtime = cg.time + 750 + (crandom() * 500);
+
+ p->startfade = cg.time;
+
+ p->width = LARGESIZE;
+ p->height = LARGESIZE;
+
+ // RF, expand while falling
+ p->endheight = LARGESIZE*3.0;
+ p->endwidth = LARGESIZE*3.0;
+
+ if (!length)
+ {
+ p->width *= 0.2f;
+ p->height *= 0.2f;
+
+ p->endheight = NORMALSIZE;
+ p->endwidth = NORMALSIZE;
+ }
+
+ p->type = P_SMOKE;
+
+ VectorCopy( point, p->org );
+
+ p->vel[0] = crandom()*6;
+ p->vel[1] = crandom()*6;
+ p->vel[2] = random()*20;
+
+ // RF, add some gravity/randomness
+ p->accel[0] = crandom()*3;
+ p->accel[1] = crandom()*3;
+ p->accel[2] = -PARTICLE_GRAVITY*0.4;
+
+ VectorClear( p->accel );
+
+ p->rotate = qfalse;
+
+ p->roll = rand()%179;
+
+ p->alpha = 0.75;
+
+ }
+
+
+}
+
+void CG_ParticleMisc (qhandle_t pshader, vec3_t origin, int size, int duration, float alpha)
+{
+ cparticle_t *p;
+
+ if (!pshader)
+ CG_Printf ("CG_ParticleImpactSmokePuff pshader == ZERO!\n");
+
+ if (!free_particles)
+ return;
+
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+ p->alpha = 1.0;
+ p->alphavel = 0;
+ p->roll = rand()%179;
+
+ p->pshader = pshader;
+
+ if (duration > 0)
+ p->endtime = cg.time + duration;
+ else
+ p->endtime = duration;
+
+ p->startfade = cg.time;
+
+ p->width = size;
+ p->height = size;
+
+ p->endheight = size;
+ p->endwidth = size;
+
+ p->type = P_SPRITE;
+
+ VectorCopy( origin, p->org );
+
+ p->rotate = qfalse;
+}
+
diff --git a/code/cgame/cg_newdraw.c b/code/cgame/cg_newdraw.c
new file mode 100755
index 0000000..28335fe
--- /dev/null
+++ b/code/cgame/cg_newdraw.c
@@ -0,0 +1,1852 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#ifndef MISSIONPACK // bk001204
+#error This file not be used for classic Q3A.
+#endif
+
+#include "cg_local.h"
+#include "../ui/ui_shared.h"
+
+extern displayContextDef_t cgDC;
+
+
+// set in CG_ParseTeamInfo
+
+//static int sortedTeamPlayers[TEAM_MAXOVERLAY];
+//static int numSortedTeamPlayers;
+int drawTeamOverlayModificationCount = -1;
+
+//static char systemChat[256];
+//static char teamChat1[256];
+//static char teamChat2[256];
+
+void CG_InitTeamChat() {
+ memset(teamChat1, 0, sizeof(teamChat1));
+ memset(teamChat2, 0, sizeof(teamChat2));
+ memset(systemChat, 0, sizeof(systemChat));
+}
+
+void CG_SetPrintString(int type, const char *p) {
+ if (type == SYSTEM_PRINT) {
+ strcpy(systemChat, p);
+ } else {
+ strcpy(teamChat2, teamChat1);
+ strcpy(teamChat1, p);
+ }
+}
+
+void CG_CheckOrderPending() {
+ if (cgs.gametype < GT_CTF) {
+ return;
+ }
+ if (cgs.orderPending) {
+ //clientInfo_t *ci = cgs.clientinfo + sortedTeamPlayers[cg_currentSelectedPlayer.integer];
+ const char *p1, *p2, *b;
+ p1 = p2 = b = NULL;
+ switch (cgs.currentOrder) {
+ case TEAMTASK_OFFENSE:
+ p1 = VOICECHAT_ONOFFENSE;
+ p2 = VOICECHAT_OFFENSE;
+ b = "+button7; wait; -button7";
+ break;
+ case TEAMTASK_DEFENSE:
+ p1 = VOICECHAT_ONDEFENSE;
+ p2 = VOICECHAT_DEFEND;
+ b = "+button8; wait; -button8";
+ break;
+ case TEAMTASK_PATROL:
+ p1 = VOICECHAT_ONPATROL;
+ p2 = VOICECHAT_PATROL;
+ b = "+button9; wait; -button9";
+ break;
+ case TEAMTASK_FOLLOW:
+ p1 = VOICECHAT_ONFOLLOW;
+ p2 = VOICECHAT_FOLLOWME;
+ b = "+button10; wait; -button10";
+ break;
+ case TEAMTASK_CAMP:
+ p1 = VOICECHAT_ONCAMPING;
+ p2 = VOICECHAT_CAMP;
+ break;
+ case TEAMTASK_RETRIEVE:
+ p1 = VOICECHAT_ONGETFLAG;
+ p2 = VOICECHAT_RETURNFLAG;
+ break;
+ case TEAMTASK_ESCORT:
+ p1 = VOICECHAT_ONFOLLOWCARRIER;
+ p2 = VOICECHAT_FOLLOWFLAGCARRIER;
+ break;
+ }
+
+ if (cg_currentSelectedPlayer.integer == numSortedTeamPlayers) {
+ // to everyone
+ trap_SendConsoleCommand(va("cmd vsay_team %s\n", p2));
+ } else {
+ // for the player self
+ if (sortedTeamPlayers[cg_currentSelectedPlayer.integer] == cg.snap->ps.clientNum && p1) {
+ trap_SendConsoleCommand(va("teamtask %i\n", cgs.currentOrder));
+ //trap_SendConsoleCommand(va("cmd say_team %s\n", p2));
+ trap_SendConsoleCommand(va("cmd vsay_team %s\n", p1));
+ } else if (p2) {
+ //trap_SendConsoleCommand(va("cmd say_team %s, %s\n", ci->name,p));
+ trap_SendConsoleCommand(va("cmd vtell %d %s\n", sortedTeamPlayers[cg_currentSelectedPlayer.integer], p2));
+ }
+ }
+ if (b) {
+ trap_SendConsoleCommand(b);
+ }
+ cgs.orderPending = qfalse;
+ }
+}
+
+static void CG_SetSelectedPlayerName() {
+ if (cg_currentSelectedPlayer.integer >= 0 && cg_currentSelectedPlayer.integer < numSortedTeamPlayers) {
+ clientInfo_t *ci = cgs.clientinfo + sortedTeamPlayers[cg_currentSelectedPlayer.integer];
+ if (ci) {
+ trap_Cvar_Set("cg_selectedPlayerName", ci->name);
+ trap_Cvar_Set("cg_selectedPlayer", va("%d", sortedTeamPlayers[cg_currentSelectedPlayer.integer]));
+ cgs.currentOrder = ci->teamTask;
+ }
+ } else {
+ trap_Cvar_Set("cg_selectedPlayerName", "Everyone");
+ }
+}
+int CG_GetSelectedPlayer() {
+ if (cg_currentSelectedPlayer.integer < 0 || cg_currentSelectedPlayer.integer >= numSortedTeamPlayers) {
+ cg_currentSelectedPlayer.integer = 0;
+ }
+ return cg_currentSelectedPlayer.integer;
+}
+
+void CG_SelectNextPlayer() {
+ CG_CheckOrderPending();
+ if (cg_currentSelectedPlayer.integer >= 0 && cg_currentSelectedPlayer.integer < numSortedTeamPlayers) {
+ cg_currentSelectedPlayer.integer++;
+ } else {
+ cg_currentSelectedPlayer.integer = 0;
+ }
+ CG_SetSelectedPlayerName();
+}
+
+void CG_SelectPrevPlayer() {
+ CG_CheckOrderPending();
+ if (cg_currentSelectedPlayer.integer > 0 && cg_currentSelectedPlayer.integer < numSortedTeamPlayers) {
+ cg_currentSelectedPlayer.integer--;
+ } else {
+ cg_currentSelectedPlayer.integer = numSortedTeamPlayers;
+ }
+ CG_SetSelectedPlayerName();
+}
+
+
+static void CG_DrawPlayerArmorIcon( rectDef_t *rect, qboolean draw2D ) {
+ centity_t *cent;
+ playerState_t *ps;
+ vec3_t angles;
+ vec3_t origin;
+
+ if ( cg_drawStatus.integer == 0 ) {
+ return;
+ }
+
+ cent = &cg_entities[cg.snap->ps.clientNum];
+ ps = &cg.snap->ps;
+
+ if ( draw2D || ( !cg_draw3dIcons.integer && cg_drawIcons.integer) ) { // bk001206 - parentheses
+ CG_DrawPic( rect->x, rect->y + rect->h/2 + 1, rect->w, rect->h, cgs.media.armorIcon );
+ } else if (cg_draw3dIcons.integer) {
+ VectorClear( angles );
+ origin[0] = 90;
+ origin[1] = 0;
+ origin[2] = -10;
+ angles[YAW] = ( cg.time & 2047 ) * 360 / 2048.0;
+
+ CG_Draw3DModel( rect->x, rect->y, rect->w, rect->h, cgs.media.armorModel, 0, origin, angles );
+ }
+
+}
+
+static void CG_DrawPlayerArmorValue(rectDef_t *rect, float scale, vec4_t color, qhandle_t shader, int textStyle) {
+ char num[16];
+ int value;
+ centity_t *cent;
+ playerState_t *ps;
+
+ cent = &cg_entities[cg.snap->ps.clientNum];
+ ps = &cg.snap->ps;
+
+ value = ps->stats[STAT_ARMOR];
+
+
+ if (shader) {
+ trap_R_SetColor( color );
+ CG_DrawPic(rect->x, rect->y, rect->w, rect->h, shader);
+ trap_R_SetColor( NULL );
+ } else {
+ Com_sprintf (num, sizeof(num), "%i", value);
+ value = CG_Text_Width(num, scale, 0);
+ CG_Text_Paint(rect->x + (rect->w - value) / 2, rect->y + rect->h, scale, color, num, 0, 0, textStyle);
+ }
+}
+
+#ifndef MISSIONPACK // bk001206
+static float healthColors[4][4] = {
+// { 0.2, 1.0, 0.2, 1.0 } , { 1.0, 0.2, 0.2, 1.0 }, {0.5, 0.5, 0.5, 1} };
+ // bk0101016 - float const
+ { 1.0f, 0.69f, 0.0f, 1.0f } , // normal
+ { 1.0f, 0.2f, 0.2f, 1.0f }, // low health
+ { 0.5f, 0.5f, 0.5f, 1.0f}, // weapon firing
+ { 1.0f, 1.0f, 1.0f, 1.0f } }; // health > 100
+#endif
+
+static void CG_DrawPlayerAmmoIcon( rectDef_t *rect, qboolean draw2D ) {
+ centity_t *cent;
+ playerState_t *ps;
+ vec3_t angles;
+ vec3_t origin;
+
+ cent = &cg_entities[cg.snap->ps.clientNum];
+ ps = &cg.snap->ps;
+
+ if ( draw2D || (!cg_draw3dIcons.integer && cg_drawIcons.integer) ) { // bk001206 - parentheses
+ qhandle_t icon;
+ icon = cg_weapons[ cg.predictedPlayerState.weapon ].ammoIcon;
+ if ( icon ) {
+ CG_DrawPic( rect->x, rect->y, rect->w, rect->h, icon );
+ }
+ } else if (cg_draw3dIcons.integer) {
+ if ( cent->currentState.weapon && cg_weapons[ cent->currentState.weapon ].ammoModel ) {
+ VectorClear( angles );
+ origin[0] = 70;
+ origin[1] = 0;
+ origin[2] = 0;
+ angles[YAW] = 90 + 20 * sin( cg.time / 1000.0 );
+ CG_Draw3DModel( rect->x, rect->y, rect->w, rect->h, cg_weapons[ cent->currentState.weapon ].ammoModel, 0, origin, angles );
+ }
+ }
+}
+
+static void CG_DrawPlayerAmmoValue(rectDef_t *rect, float scale, vec4_t color, qhandle_t shader, int textStyle) {
+ char num[16];
+ int value;
+ centity_t *cent;
+ playerState_t *ps;
+
+ cent = &cg_entities[cg.snap->ps.clientNum];
+ ps = &cg.snap->ps;
+
+ if ( cent->currentState.weapon ) {
+ value = ps->ammo[cent->currentState.weapon];
+ if ( value > -1 ) {
+ if (shader) {
+ trap_R_SetColor( color );
+ CG_DrawPic(rect->x, rect->y, rect->w, rect->h, shader);
+ trap_R_SetColor( NULL );
+ } else {
+ Com_sprintf (num, sizeof(num), "%i", value);
+ value = CG_Text_Width(num, scale, 0);
+ CG_Text_Paint(rect->x + (rect->w - value) / 2, rect->y + rect->h, scale, color, num, 0, 0, textStyle);
+ }
+ }
+ }
+
+}
+
+
+
+static void CG_DrawPlayerHead(rectDef_t *rect, qboolean draw2D) {
+ vec3_t angles;
+ float size, stretch;
+ float frac;
+ float x = rect->x;
+
+ VectorClear( angles );
+
+ if ( cg.damageTime && cg.time - cg.damageTime < DAMAGE_TIME ) {
+ frac = (float)(cg.time - cg.damageTime ) / DAMAGE_TIME;
+ size = rect->w * 1.25 * ( 1.5 - frac * 0.5 );
+
+ stretch = size - rect->w * 1.25;
+ // kick in the direction of damage
+ x -= stretch * 0.5 + cg.damageX * stretch * 0.5;
+
+ cg.headStartYaw = 180 + cg.damageX * 45;
+
+ cg.headEndYaw = 180 + 20 * cos( crandom()*M_PI );
+ cg.headEndPitch = 5 * cos( crandom()*M_PI );
+
+ cg.headStartTime = cg.time;
+ cg.headEndTime = cg.time + 100 + random() * 2000;
+ } else {
+ if ( cg.time >= cg.headEndTime ) {
+ // select a new head angle
+ cg.headStartYaw = cg.headEndYaw;
+ cg.headStartPitch = cg.headEndPitch;
+ cg.headStartTime = cg.headEndTime;
+ cg.headEndTime = cg.time + 100 + random() * 2000;
+
+ cg.headEndYaw = 180 + 20 * cos( crandom()*M_PI );
+ cg.headEndPitch = 5 * cos( crandom()*M_PI );
+ }
+
+ size = rect->w * 1.25;
+ }
+
+ // if the server was frozen for a while we may have a bad head start time
+ if ( cg.headStartTime > cg.time ) {
+ cg.headStartTime = cg.time;
+ }
+
+ frac = ( cg.time - cg.headStartTime ) / (float)( cg.headEndTime - cg.headStartTime );
+ frac = frac * frac * ( 3 - 2 * frac );
+ angles[YAW] = cg.headStartYaw + ( cg.headEndYaw - cg.headStartYaw ) * frac;
+ angles[PITCH] = cg.headStartPitch + ( cg.headEndPitch - cg.headStartPitch ) * frac;
+
+ CG_DrawHead( x, rect->y, rect->w, rect->h, cg.snap->ps.clientNum, angles );
+}
+
+static void CG_DrawSelectedPlayerHealth( rectDef_t *rect, float scale, vec4_t color, qhandle_t shader, int textStyle ) {
+ clientInfo_t *ci;
+ int value;
+ char num[16];
+
+ ci = cgs.clientinfo + sortedTeamPlayers[CG_GetSelectedPlayer()];
+ if (ci) {
+ if (shader) {
+ trap_R_SetColor( color );
+ CG_DrawPic(rect->x, rect->y, rect->w, rect->h, shader);
+ trap_R_SetColor( NULL );
+ } else {
+ Com_sprintf (num, sizeof(num), "%i", ci->health);
+ value = CG_Text_Width(num, scale, 0);
+ CG_Text_Paint(rect->x + (rect->w - value) / 2, rect->y + rect->h, scale, color, num, 0, 0, textStyle);
+ }
+ }
+}
+
+static void CG_DrawSelectedPlayerArmor( rectDef_t *rect, float scale, vec4_t color, qhandle_t shader, int textStyle ) {
+ clientInfo_t *ci;
+ int value;
+ char num[16];
+ ci = cgs.clientinfo + sortedTeamPlayers[CG_GetSelectedPlayer()];
+ if (ci) {
+ if (ci->armor > 0) {
+ if (shader) {
+ trap_R_SetColor( color );
+ CG_DrawPic(rect->x, rect->y, rect->w, rect->h, shader);
+ trap_R_SetColor( NULL );
+ } else {
+ Com_sprintf (num, sizeof(num), "%i", ci->armor);
+ value = CG_Text_Width(num, scale, 0);
+ CG_Text_Paint(rect->x + (rect->w - value) / 2, rect->y + rect->h, scale, color, num, 0, 0, textStyle);
+ }
+ }
+ }
+}
+
+qhandle_t CG_StatusHandle(int task) {
+ qhandle_t h = cgs.media.assaultShader;
+ switch (task) {
+ case TEAMTASK_OFFENSE :
+ h = cgs.media.assaultShader;
+ break;
+ case TEAMTASK_DEFENSE :
+ h = cgs.media.defendShader;
+ break;
+ case TEAMTASK_PATROL :
+ h = cgs.media.patrolShader;
+ break;
+ case TEAMTASK_FOLLOW :
+ h = cgs.media.followShader;
+ break;
+ case TEAMTASK_CAMP :
+ h = cgs.media.campShader;
+ break;
+ case TEAMTASK_RETRIEVE :
+ h = cgs.media.retrieveShader;
+ break;
+ case TEAMTASK_ESCORT :
+ h = cgs.media.escortShader;
+ break;
+ default :
+ h = cgs.media.assaultShader;
+ break;
+ }
+ return h;
+}
+
+static void CG_DrawSelectedPlayerStatus( rectDef_t *rect ) {
+ clientInfo_t *ci = cgs.clientinfo + sortedTeamPlayers[CG_GetSelectedPlayer()];
+ if (ci) {
+ qhandle_t h;
+ if (cgs.orderPending) {
+ // blink the icon
+ if ( cg.time > cgs.orderTime - 2500 && (cg.time >> 9 ) & 1 ) {
+ return;
+ }
+ h = CG_StatusHandle(cgs.currentOrder);
+ } else {
+ h = CG_StatusHandle(ci->teamTask);
+ }
+ CG_DrawPic( rect->x, rect->y, rect->w, rect->h, h );
+ }
+}
+
+
+static void CG_DrawPlayerStatus( rectDef_t *rect ) {
+ clientInfo_t *ci = &cgs.clientinfo[cg.snap->ps.clientNum];
+ if (ci) {
+ qhandle_t h = CG_StatusHandle(ci->teamTask);
+ CG_DrawPic( rect->x, rect->y, rect->w, rect->h, h);
+ }
+}
+
+
+static void CG_DrawSelectedPlayerName( rectDef_t *rect, float scale, vec4_t color, qboolean voice, int textStyle) {
+ clientInfo_t *ci;
+ ci = cgs.clientinfo + ((voice) ? cgs.currentVoiceClient : sortedTeamPlayers[CG_GetSelectedPlayer()]);
+ if (ci) {
+ CG_Text_Paint(rect->x, rect->y + rect->h, scale, color, ci->name, 0, 0, textStyle);
+ }
+}
+
+static void CG_DrawSelectedPlayerLocation( rectDef_t *rect, float scale, vec4_t color, int textStyle ) {
+ clientInfo_t *ci;
+ ci = cgs.clientinfo + sortedTeamPlayers[CG_GetSelectedPlayer()];
+ if (ci) {
+ const char *p = CG_ConfigString(CS_LOCATIONS + ci->location);
+ if (!p || !*p) {
+ p = "unknown";
+ }
+ CG_Text_Paint(rect->x, rect->y + rect->h, scale, color, p, 0, 0, textStyle);
+ }
+}
+
+static void CG_DrawPlayerLocation( rectDef_t *rect, float scale, vec4_t color, int textStyle ) {
+ clientInfo_t *ci = &cgs.clientinfo[cg.snap->ps.clientNum];
+ if (ci) {
+ const char *p = CG_ConfigString(CS_LOCATIONS + ci->location);
+ if (!p || !*p) {
+ p = "unknown";
+ }
+ CG_Text_Paint(rect->x, rect->y + rect->h, scale, color, p, 0, 0, textStyle);
+ }
+}
+
+
+
+static void CG_DrawSelectedPlayerWeapon( rectDef_t *rect ) {
+ clientInfo_t *ci;
+
+ ci = cgs.clientinfo + sortedTeamPlayers[CG_GetSelectedPlayer()];
+ if (ci) {
+ if ( cg_weapons[ci->curWeapon].weaponIcon ) {
+ CG_DrawPic( rect->x, rect->y, rect->w, rect->h, cg_weapons[ci->curWeapon].weaponIcon );
+ } else {
+ CG_DrawPic( rect->x, rect->y, rect->w, rect->h, cgs.media.deferShader);
+ }
+ }
+}
+
+static void CG_DrawPlayerScore( rectDef_t *rect, float scale, vec4_t color, qhandle_t shader, int textStyle ) {
+ char num[16];
+ int value = cg.snap->ps.persistant[PERS_SCORE];
+
+ if (shader) {
+ trap_R_SetColor( color );
+ CG_DrawPic(rect->x, rect->y, rect->w, rect->h, shader);
+ trap_R_SetColor( NULL );
+ } else {
+ Com_sprintf (num, sizeof(num), "%i", value);
+ value = CG_Text_Width(num, scale, 0);
+ CG_Text_Paint(rect->x + (rect->w - value) / 2, rect->y + rect->h, scale, color, num, 0, 0, textStyle);
+ }
+}
+
+static void CG_DrawPlayerItem( rectDef_t *rect, float scale, qboolean draw2D) {
+ int value;
+ vec3_t origin, angles;
+
+ value = cg.snap->ps.stats[STAT_HOLDABLE_ITEM];
+ if ( value ) {
+ CG_RegisterItemVisuals( value );
+
+ if (qtrue) {
+ CG_RegisterItemVisuals( value );
+ CG_DrawPic( rect->x, rect->y, rect->w, rect->h, cg_items[ value ].icon );
+ } else {
+ VectorClear( angles );
+ origin[0] = 90;
+ origin[1] = 0;
+ origin[2] = -10;
+ angles[YAW] = ( cg.time & 2047 ) * 360 / 2048.0;
+ CG_Draw3DModel(rect->x, rect->y, rect->w, rect->h, cg_items[ value ].models[0], 0, origin, angles );
+ }
+ }
+
+}
+
+
+static void CG_DrawSelectedPlayerPowerup( rectDef_t *rect, qboolean draw2D ) {
+ clientInfo_t *ci;
+ int j;
+ float x, y;
+
+ ci = cgs.clientinfo + sortedTeamPlayers[CG_GetSelectedPlayer()];
+ if (ci) {
+ x = rect->x;
+ y = rect->y;
+
+ for (j = 0; j < PW_NUM_POWERUPS; j++) {
+ if (ci->powerups & (1 << j)) {
+ gitem_t *item;
+ item = BG_FindItemForPowerup( j );
+ if (item) {
+ CG_DrawPic( x, y, rect->w, rect->h, trap_R_RegisterShader( item->icon ) );
+ x += 3;
+ y += 3;
+ return;
+ }
+ }
+ }
+
+ }
+}
+
+
+static void CG_DrawSelectedPlayerHead( rectDef_t *rect, qboolean draw2D, qboolean voice ) {
+ clipHandle_t cm;
+ clientInfo_t *ci;
+ float len;
+ vec3_t origin;
+ vec3_t mins, maxs, angles;
+
+
+ ci = cgs.clientinfo + ((voice) ? cgs.currentVoiceClient : sortedTeamPlayers[CG_GetSelectedPlayer()]);
+
+ if (ci) {
+ if ( cg_draw3dIcons.integer ) {
+ cm = ci->headModel;
+ if ( !cm ) {
+ return;
+ }
+
+ // offset the origin y and z to center the head
+ trap_R_ModelBounds( cm, mins, maxs );
+
+ origin[2] = -0.5 * ( mins[2] + maxs[2] );
+ origin[1] = 0.5 * ( mins[1] + maxs[1] );
+
+ // calculate distance so the head nearly fills the box
+ // assume heads are taller than wide
+ len = 0.7 * ( maxs[2] - mins[2] );
+ origin[0] = len / 0.268; // len / tan( fov/2 )
+
+ // allow per-model tweaking
+ VectorAdd( origin, ci->headOffset, origin );
+
+ angles[PITCH] = 0;
+ angles[YAW] = 180;
+ angles[ROLL] = 0;
+
+ CG_Draw3DModel( rect->x, rect->y, rect->w, rect->h, ci->headModel, ci->headSkin, origin, angles );
+ } else if ( cg_drawIcons.integer ) {
+ CG_DrawPic( rect->x, rect->y, rect->w, rect->h, ci->modelIcon );
+ }
+
+ // if they are deferred, draw a cross out
+ if ( ci->deferred ) {
+ CG_DrawPic( rect->x, rect->y, rect->w, rect->h, cgs.media.deferShader );
+ }
+ }
+
+}
+
+
+static void CG_DrawPlayerHealth(rectDef_t *rect, float scale, vec4_t color, qhandle_t shader, int textStyle ) {
+ playerState_t *ps;
+ int value;
+ char num[16];
+
+ ps = &cg.snap->ps;
+
+ value = ps->stats[STAT_HEALTH];
+
+ if (shader) {
+ trap_R_SetColor( color );
+ CG_DrawPic(rect->x, rect->y, rect->w, rect->h, shader);
+ trap_R_SetColor( NULL );
+ } else {
+ Com_sprintf (num, sizeof(num), "%i", value);
+ value = CG_Text_Width(num, scale, 0);
+ CG_Text_Paint(rect->x + (rect->w - value) / 2, rect->y + rect->h, scale, color, num, 0, 0, textStyle);
+ }
+}
+
+
+static void CG_DrawRedScore(rectDef_t *rect, float scale, vec4_t color, qhandle_t shader, int textStyle ) {
+ int value;
+ char num[16];
+ if ( cgs.scores1 == SCORE_NOT_PRESENT ) {
+ Com_sprintf (num, sizeof(num), "-");
+ }
+ else {
+ Com_sprintf (num, sizeof(num), "%i", cgs.scores1);
+ }
+ value = CG_Text_Width(num, scale, 0);
+ CG_Text_Paint(rect->x + rect->w - value, rect->y + rect->h, scale, color, num, 0, 0, textStyle);
+}
+
+static void CG_DrawBlueScore(rectDef_t *rect, float scale, vec4_t color, qhandle_t shader, int textStyle ) {
+ int value;
+ char num[16];
+
+ if ( cgs.scores2 == SCORE_NOT_PRESENT ) {
+ Com_sprintf (num, sizeof(num), "-");
+ }
+ else {
+ Com_sprintf (num, sizeof(num), "%i", cgs.scores2);
+ }
+ value = CG_Text_Width(num, scale, 0);
+ CG_Text_Paint(rect->x + rect->w - value, rect->y + rect->h, scale, color, num, 0, 0, textStyle);
+}
+
+// FIXME: team name support
+static void CG_DrawRedName(rectDef_t *rect, float scale, vec4_t color, int textStyle ) {
+ CG_Text_Paint(rect->x, rect->y + rect->h, scale, color, cg_redTeamName.string , 0, 0, textStyle);
+}
+
+static void CG_DrawBlueName(rectDef_t *rect, float scale, vec4_t color, int textStyle ) {
+ CG_Text_Paint(rect->x, rect->y + rect->h, scale, color, cg_blueTeamName.string, 0, 0, textStyle);
+}
+
+static void CG_DrawBlueFlagName(rectDef_t *rect, float scale, vec4_t color, int textStyle ) {
+ int i;
+ for ( i = 0 ; i < cgs.maxclients ; i++ ) {
+ if ( cgs.clientinfo[i].infoValid && cgs.clientinfo[i].team == TEAM_RED && cgs.clientinfo[i].powerups & ( 1<< PW_BLUEFLAG )) {
+ CG_Text_Paint(rect->x, rect->y + rect->h, scale, color, cgs.clientinfo[i].name, 0, 0, textStyle);
+ return;
+ }
+ }
+}
+
+static void CG_DrawBlueFlagStatus(rectDef_t *rect, qhandle_t shader) {
+ if (cgs.gametype != GT_CTF && cgs.gametype != GT_1FCTF) {
+ if (cgs.gametype == GT_HARVESTER) {
+ vec4_t color = {0, 0, 1, 1};
+ trap_R_SetColor(color);
+ CG_DrawPic( rect->x, rect->y, rect->w, rect->h, cgs.media.blueCubeIcon );
+ trap_R_SetColor(NULL);
+ }
+ return;
+ }
+ if (shader) {
+ CG_DrawPic( rect->x, rect->y, rect->w, rect->h, shader );
+ } else {
+ gitem_t *item = BG_FindItemForPowerup( PW_BLUEFLAG );
+ if (item) {
+ vec4_t color = {0, 0, 1, 1};
+ trap_R_SetColor(color);
+ if( cgs.blueflag >= 0 && cgs.blueflag <= 2 ) {
+ CG_DrawPic( rect->x, rect->y, rect->w, rect->h, cgs.media.flagShaders[cgs.blueflag] );
+ } else {
+ CG_DrawPic( rect->x, rect->y, rect->w, rect->h, cgs.media.flagShaders[0] );
+ }
+ trap_R_SetColor(NULL);
+ }
+ }
+}
+
+static void CG_DrawBlueFlagHead(rectDef_t *rect) {
+ int i;
+ for ( i = 0 ; i < cgs.maxclients ; i++ ) {
+ if ( cgs.clientinfo[i].infoValid && cgs.clientinfo[i].team == TEAM_RED && cgs.clientinfo[i].powerups & ( 1<< PW_BLUEFLAG )) {
+ vec3_t angles;
+ VectorClear( angles );
+ angles[YAW] = 180 + 20 * sin( cg.time / 650.0 );;
+ CG_DrawHead( rect->x, rect->y, rect->w, rect->h, 0,angles );
+ return;
+ }
+ }
+}
+
+static void CG_DrawRedFlagName(rectDef_t *rect, float scale, vec4_t color, int textStyle ) {
+ int i;
+ for ( i = 0 ; i < cgs.maxclients ; i++ ) {
+ if ( cgs.clientinfo[i].infoValid && cgs.clientinfo[i].team == TEAM_BLUE && cgs.clientinfo[i].powerups & ( 1<< PW_REDFLAG )) {
+ CG_Text_Paint(rect->x, rect->y + rect->h, scale, color, cgs.clientinfo[i].name, 0, 0, textStyle);
+ return;
+ }
+ }
+}
+
+static void CG_DrawRedFlagStatus(rectDef_t *rect, qhandle_t shader) {
+ if (cgs.gametype != GT_CTF && cgs.gametype != GT_1FCTF) {
+ if (cgs.gametype == GT_HARVESTER) {
+ vec4_t color = {1, 0, 0, 1};
+ trap_R_SetColor(color);
+ CG_DrawPic( rect->x, rect->y, rect->w, rect->h, cgs.media.redCubeIcon );
+ trap_R_SetColor(NULL);
+ }
+ return;
+ }
+ if (shader) {
+ CG_DrawPic( rect->x, rect->y, rect->w, rect->h, shader );
+ } else {
+ gitem_t *item = BG_FindItemForPowerup( PW_REDFLAG );
+ if (item) {
+ vec4_t color = {1, 0, 0, 1};
+ trap_R_SetColor(color);
+ if( cgs.redflag >= 0 && cgs.redflag <= 2) {
+ CG_DrawPic( rect->x, rect->y, rect->w, rect->h, cgs.media.flagShaders[cgs.redflag] );
+ } else {
+ CG_DrawPic( rect->x, rect->y, rect->w, rect->h, cgs.media.flagShaders[0] );
+ }
+ trap_R_SetColor(NULL);
+ }
+ }
+}
+
+static void CG_DrawRedFlagHead(rectDef_t *rect) {
+ int i;
+ for ( i = 0 ; i < cgs.maxclients ; i++ ) {
+ if ( cgs.clientinfo[i].infoValid && cgs.clientinfo[i].team == TEAM_BLUE && cgs.clientinfo[i].powerups & ( 1<< PW_REDFLAG )) {
+ vec3_t angles;
+ VectorClear( angles );
+ angles[YAW] = 180 + 20 * sin( cg.time / 650.0 );;
+ CG_DrawHead( rect->x, rect->y, rect->w, rect->h, 0,angles );
+ return;
+ }
+ }
+}
+
+static void CG_HarvesterSkulls(rectDef_t *rect, float scale, vec4_t color, qboolean force2D, int textStyle ) {
+ char num[16];
+ vec3_t origin, angles;
+ qhandle_t handle;
+ int value = cg.snap->ps.generic1;
+
+ if (cgs.gametype != GT_HARVESTER) {
+ return;
+ }
+
+ if( value > 99 ) {
+ value = 99;
+ }
+
+ Com_sprintf (num, sizeof(num), "%i", value);
+ value = CG_Text_Width(num, scale, 0);
+ CG_Text_Paint(rect->x + (rect->w - value), rect->y + rect->h, scale, color, num, 0, 0, textStyle);
+
+ if (cg_drawIcons.integer) {
+ if (!force2D && cg_draw3dIcons.integer) {
+ VectorClear(angles);
+ origin[0] = 90;
+ origin[1] = 0;
+ origin[2] = -10;
+ angles[YAW] = ( cg.time & 2047 ) * 360 / 2048.0;
+ if( cg.snap->ps.persistant[PERS_TEAM] == TEAM_BLUE ) {
+ handle = cgs.media.redCubeModel;
+ } else {
+ handle = cgs.media.blueCubeModel;
+ }
+ CG_Draw3DModel( rect->x, rect->y, 35, 35, handle, 0, origin, angles );
+ } else {
+ if( cg.snap->ps.persistant[PERS_TEAM] == TEAM_BLUE ) {
+ handle = cgs.media.redCubeIcon;
+ } else {
+ handle = cgs.media.blueCubeIcon;
+ }
+ CG_DrawPic( rect->x + 3, rect->y + 16, 20, 20, handle );
+ }
+ }
+}
+
+static void CG_OneFlagStatus(rectDef_t *rect) {
+ if (cgs.gametype != GT_1FCTF) {
+ return;
+ } else {
+ gitem_t *item = BG_FindItemForPowerup( PW_NEUTRALFLAG );
+ if (item) {
+ if( cgs.flagStatus >= 0 && cgs.flagStatus <= 4 ) {
+ vec4_t color = {1, 1, 1, 1};
+ int index = 0;
+ if (cgs.flagStatus == FLAG_TAKEN_RED) {
+ color[1] = color[2] = 0;
+ index = 1;
+ } else if (cgs.flagStatus == FLAG_TAKEN_BLUE) {
+ color[0] = color[1] = 0;
+ index = 1;
+ } else if (cgs.flagStatus == FLAG_DROPPED) {
+ index = 2;
+ }
+ trap_R_SetColor(color);
+ CG_DrawPic( rect->x, rect->y, rect->w, rect->h, cgs.media.flagShaders[index] );
+ }
+ }
+ }
+}
+
+
+static void CG_DrawCTFPowerUp(rectDef_t *rect) {
+ int value;
+
+ if (cgs.gametype < GT_CTF) {
+ return;
+ }
+ value = cg.snap->ps.stats[STAT_PERSISTANT_POWERUP];
+ if ( value ) {
+ CG_RegisterItemVisuals( value );
+ CG_DrawPic( rect->x, rect->y, rect->w, rect->h, cg_items[ value ].icon );
+ }
+}
+
+
+
+static void CG_DrawTeamColor(rectDef_t *rect, vec4_t color) {
+ CG_DrawTeamBackground(rect->x, rect->y, rect->w, rect->h, color[3], cg.snap->ps.persistant[PERS_TEAM]);
+}
+
+static void CG_DrawAreaPowerUp(rectDef_t *rect, int align, float special, float scale, vec4_t color) {
+ char num[16];
+ int sorted[MAX_POWERUPS];
+ int sortedTime[MAX_POWERUPS];
+ int i, j, k;
+ int active;
+ playerState_t *ps;
+ int t;
+ gitem_t *item;
+ float f;
+ rectDef_t r2;
+ float *inc;
+ r2.x = rect->x;
+ r2.y = rect->y;
+ r2.w = rect->w;
+ r2.h = rect->h;
+
+ inc = (align == HUD_VERTICAL) ? &r2.y : &r2.x;
+
+ ps = &cg.snap->ps;
+
+ if ( ps->stats[STAT_HEALTH] <= 0 ) {
+ return;
+ }
+
+ // sort the list by time remaining
+ active = 0;
+ for ( i = 0 ; i < MAX_POWERUPS ; i++ ) {
+ if ( !ps->powerups[ i ] ) {
+ continue;
+ }
+ t = ps->powerups[ i ] - cg.time;
+ // ZOID--don't draw if the power up has unlimited time (999 seconds)
+ // This is true of the CTF flags
+ if ( t <= 0 || t >= 999000) {
+ continue;
+ }
+
+ // insert into the list
+ for ( j = 0 ; j < active ; j++ ) {
+ if ( sortedTime[j] >= t ) {
+ for ( k = active - 1 ; k >= j ; k-- ) {
+ sorted[k+1] = sorted[k];
+ sortedTime[k+1] = sortedTime[k];
+ }
+ break;
+ }
+ }
+ sorted[j] = i;
+ sortedTime[j] = t;
+ active++;
+ }
+
+ // draw the icons and timers
+ for ( i = 0 ; i < active ; i++ ) {
+ item = BG_FindItemForPowerup( sorted[i] );
+
+ if (item) {
+ t = ps->powerups[ sorted[i] ];
+ if ( t - cg.time >= POWERUP_BLINKS * POWERUP_BLINK_TIME ) {
+ trap_R_SetColor( NULL );
+ } else {
+ vec4_t modulate;
+
+ f = (float)( t - cg.time ) / POWERUP_BLINK_TIME;
+ f -= (int)f;
+ modulate[0] = modulate[1] = modulate[2] = modulate[3] = f;
+ trap_R_SetColor( modulate );
+ }
+
+ CG_DrawPic( r2.x, r2.y, r2.w * .75, r2.h, trap_R_RegisterShader( item->icon ) );
+
+ Com_sprintf (num, sizeof(num), "%i", sortedTime[i] / 1000);
+ CG_Text_Paint(r2.x + (r2.w * .75) + 3 , r2.y + r2.h, scale, color, num, 0, 0, 0);
+ *inc += r2.w + special;
+ }
+
+ }
+ trap_R_SetColor( NULL );
+
+}
+
+float CG_GetValue(int ownerDraw) {
+ centity_t *cent;
+ clientInfo_t *ci;
+ playerState_t *ps;
+
+ cent = &cg_entities[cg.snap->ps.clientNum];
+ ps = &cg.snap->ps;
+
+ switch (ownerDraw) {
+ case CG_SELECTEDPLAYER_ARMOR:
+ ci = cgs.clientinfo + sortedTeamPlayers[CG_GetSelectedPlayer()];
+ return ci->armor;
+ break;
+ case CG_SELECTEDPLAYER_HEALTH:
+ ci = cgs.clientinfo + sortedTeamPlayers[CG_GetSelectedPlayer()];
+ return ci->health;
+ break;
+ case CG_PLAYER_ARMOR_VALUE:
+ return ps->stats[STAT_ARMOR];
+ break;
+ case CG_PLAYER_AMMO_VALUE:
+ if ( cent->currentState.weapon ) {
+ return ps->ammo[cent->currentState.weapon];
+ }
+ break;
+ case CG_PLAYER_SCORE:
+ return cg.snap->ps.persistant[PERS_SCORE];
+ break;
+ case CG_PLAYER_HEALTH:
+ return ps->stats[STAT_HEALTH];
+ break;
+ case CG_RED_SCORE:
+ return cgs.scores1;
+ break;
+ case CG_BLUE_SCORE:
+ return cgs.scores2;
+ break;
+ default:
+ break;
+ }
+ return -1;
+}
+
+qboolean CG_OtherTeamHasFlag() {
+ if (cgs.gametype == GT_CTF || cgs.gametype == GT_1FCTF) {
+ int team = cg.snap->ps.persistant[PERS_TEAM];
+ if (cgs.gametype == GT_1FCTF) {
+ if (team == TEAM_RED && cgs.flagStatus == FLAG_TAKEN_BLUE) {
+ return qtrue;
+ } else if (team == TEAM_BLUE && cgs.flagStatus == FLAG_TAKEN_RED) {
+ return qtrue;
+ } else {
+ return qfalse;
+ }
+ } else {
+ if (team == TEAM_RED && cgs.redflag == FLAG_TAKEN) {
+ return qtrue;
+ } else if (team == TEAM_BLUE && cgs.blueflag == FLAG_TAKEN) {
+ return qtrue;
+ } else {
+ return qfalse;
+ }
+ }
+ }
+ return qfalse;
+}
+
+qboolean CG_YourTeamHasFlag() {
+ if (cgs.gametype == GT_CTF || cgs.gametype == GT_1FCTF) {
+ int team = cg.snap->ps.persistant[PERS_TEAM];
+ if (cgs.gametype == GT_1FCTF) {
+ if (team == TEAM_RED && cgs.flagStatus == FLAG_TAKEN_RED) {
+ return qtrue;
+ } else if (team == TEAM_BLUE && cgs.flagStatus == FLAG_TAKEN_BLUE) {
+ return qtrue;
+ } else {
+ return qfalse;
+ }
+ } else {
+ if (team == TEAM_RED && cgs.blueflag == FLAG_TAKEN) {
+ return qtrue;
+ } else if (team == TEAM_BLUE && cgs.redflag == FLAG_TAKEN) {
+ return qtrue;
+ } else {
+ return qfalse;
+ }
+ }
+ }
+ return qfalse;
+}
+
+// THINKABOUTME: should these be exclusive or inclusive..
+//
+qboolean CG_OwnerDrawVisible(int flags) {
+
+ if (flags & CG_SHOW_TEAMINFO) {
+ return (cg_currentSelectedPlayer.integer == numSortedTeamPlayers);
+ }
+
+ if (flags & CG_SHOW_NOTEAMINFO) {
+ return !(cg_currentSelectedPlayer.integer == numSortedTeamPlayers);
+ }
+
+ if (flags & CG_SHOW_OTHERTEAMHASFLAG) {
+ return CG_OtherTeamHasFlag();
+ }
+
+ if (flags & CG_SHOW_YOURTEAMHASENEMYFLAG) {
+ return CG_YourTeamHasFlag();
+ }
+
+ if (flags & (CG_SHOW_BLUE_TEAM_HAS_REDFLAG | CG_SHOW_RED_TEAM_HAS_BLUEFLAG)) {
+ if (flags & CG_SHOW_BLUE_TEAM_HAS_REDFLAG && (cgs.redflag == FLAG_TAKEN || cgs.flagStatus == FLAG_TAKEN_RED)) {
+ return qtrue;
+ } else if (flags & CG_SHOW_RED_TEAM_HAS_BLUEFLAG && (cgs.blueflag == FLAG_TAKEN || cgs.flagStatus == FLAG_TAKEN_BLUE)) {
+ return qtrue;
+ }
+ return qfalse;
+ }
+
+ if (flags & CG_SHOW_ANYTEAMGAME) {
+ if( cgs.gametype >= GT_TEAM) {
+ return qtrue;
+ }
+ }
+
+ if (flags & CG_SHOW_ANYNONTEAMGAME) {
+ if( cgs.gametype < GT_TEAM) {
+ return qtrue;
+ }
+ }
+
+ if (flags & CG_SHOW_HARVESTER) {
+ if( cgs.gametype == GT_HARVESTER ) {
+ return qtrue;
+ } else {
+ return qfalse;
+ }
+ }
+
+ if (flags & CG_SHOW_ONEFLAG) {
+ if( cgs.gametype == GT_1FCTF ) {
+ return qtrue;
+ } else {
+ return qfalse;
+ }
+ }
+
+ if (flags & CG_SHOW_CTF) {
+ if( cgs.gametype == GT_CTF ) {
+ return qtrue;
+ }
+ }
+
+ if (flags & CG_SHOW_OBELISK) {
+ if( cgs.gametype == GT_OBELISK ) {
+ return qtrue;
+ } else {
+ return qfalse;
+ }
+ }
+
+ if (flags & CG_SHOW_HEALTHCRITICAL) {
+ if (cg.snap->ps.stats[STAT_HEALTH] < 25) {
+ return qtrue;
+ }
+ }
+
+ if (flags & CG_SHOW_HEALTHOK) {
+ if (cg.snap->ps.stats[STAT_HEALTH] >= 25) {
+ return qtrue;
+ }
+ }
+
+ if (flags & CG_SHOW_SINGLEPLAYER) {
+ if( cgs.gametype == GT_SINGLE_PLAYER ) {
+ return qtrue;
+ }
+ }
+
+ if (flags & CG_SHOW_TOURNAMENT) {
+ if( cgs.gametype == GT_TOURNAMENT ) {
+ return qtrue;
+ }
+ }
+
+ if (flags & CG_SHOW_DURINGINCOMINGVOICE) {
+ }
+
+ if (flags & CG_SHOW_IF_PLAYER_HAS_FLAG) {
+ if (cg.snap->ps.powerups[PW_REDFLAG] || cg.snap->ps.powerups[PW_BLUEFLAG] || cg.snap->ps.powerups[PW_NEUTRALFLAG]) {
+ return qtrue;
+ }
+ }
+ return qfalse;
+}
+
+
+
+static void CG_DrawPlayerHasFlag(rectDef_t *rect, qboolean force2D) {
+ int adj = (force2D) ? 0 : 2;
+ if( cg.predictedPlayerState.powerups[PW_REDFLAG] ) {
+ CG_DrawFlagModel( rect->x + adj, rect->y + adj, rect->w - adj, rect->h - adj, TEAM_RED, force2D);
+ } else if( cg.predictedPlayerState.powerups[PW_BLUEFLAG] ) {
+ CG_DrawFlagModel( rect->x + adj, rect->y + adj, rect->w - adj, rect->h - adj, TEAM_BLUE, force2D);
+ } else if( cg.predictedPlayerState.powerups[PW_NEUTRALFLAG] ) {
+ CG_DrawFlagModel( rect->x + adj, rect->y + adj, rect->w - adj, rect->h - adj, TEAM_FREE, force2D);
+ }
+}
+
+static void CG_DrawAreaSystemChat(rectDef_t *rect, float scale, vec4_t color, qhandle_t shader) {
+ CG_Text_Paint(rect->x, rect->y + rect->h, scale, color, systemChat, 0, 0, 0);
+}
+
+static void CG_DrawAreaTeamChat(rectDef_t *rect, float scale, vec4_t color, qhandle_t shader) {
+ CG_Text_Paint(rect->x, rect->y + rect->h, scale, color,teamChat1, 0, 0, 0);
+}
+
+static void CG_DrawAreaChat(rectDef_t *rect, float scale, vec4_t color, qhandle_t shader) {
+ CG_Text_Paint(rect->x, rect->y + rect->h, scale, color, teamChat2, 0, 0, 0);
+}
+
+const char *CG_GetKillerText() {
+ const char *s = "";
+ if ( cg.killerName[0] ) {
+ s = va("Fragged by %s", cg.killerName );
+ }
+ return s;
+}
+
+
+static void CG_DrawKiller(rectDef_t *rect, float scale, vec4_t color, qhandle_t shader, int textStyle ) {
+ // fragged by ... line
+ if ( cg.killerName[0] ) {
+ int x = rect->x + rect->w / 2;
+ CG_Text_Paint(x - CG_Text_Width(CG_GetKillerText(), scale, 0) / 2, rect->y + rect->h, scale, color, CG_GetKillerText(), 0, 0, textStyle);
+ }
+
+}
+
+
+static void CG_DrawCapFragLimit(rectDef_t *rect, float scale, vec4_t color, qhandle_t shader, int textStyle) {
+ int limit = (cgs.gametype >= GT_CTF) ? cgs.capturelimit : cgs.fraglimit;
+ CG_Text_Paint(rect->x, rect->y, scale, color, va("%2i", limit),0, 0, textStyle);
+}
+
+static void CG_Draw1stPlace(rectDef_t *rect, float scale, vec4_t color, qhandle_t shader, int textStyle) {
+ if (cgs.scores1 != SCORE_NOT_PRESENT) {
+ CG_Text_Paint(rect->x, rect->y, scale, color, va("%2i", cgs.scores1),0, 0, textStyle);
+ }
+}
+
+static void CG_Draw2ndPlace(rectDef_t *rect, float scale, vec4_t color, qhandle_t shader, int textStyle) {
+ if (cgs.scores2 != SCORE_NOT_PRESENT) {
+ CG_Text_Paint(rect->x, rect->y, scale, color, va("%2i", cgs.scores2),0, 0, textStyle);
+ }
+}
+
+const char *CG_GetGameStatusText() {
+ const char *s = "";
+ if ( cgs.gametype < GT_TEAM) {
+ if (cg.snap->ps.persistant[PERS_TEAM] != TEAM_SPECTATOR ) {
+ s = va("%s place with %i",CG_PlaceString( cg.snap->ps.persistant[PERS_RANK] + 1 ),cg.snap->ps.persistant[PERS_SCORE] );
+ }
+ } else {
+ if ( cg.teamScores[0] == cg.teamScores[1] ) {
+ s = va("Teams are tied at %i", cg.teamScores[0] );
+ } else if ( cg.teamScores[0] >= cg.teamScores[1] ) {
+ s = va("Red leads Blue, %i to %i", cg.teamScores[0], cg.teamScores[1] );
+ } else {
+ s = va("Blue leads Red, %i to %i", cg.teamScores[1], cg.teamScores[0] );
+ }
+ }
+ return s;
+}
+
+static void CG_DrawGameStatus(rectDef_t *rect, float scale, vec4_t color, qhandle_t shader, int textStyle ) {
+ CG_Text_Paint(rect->x, rect->y + rect->h, scale, color, CG_GetGameStatusText(), 0, 0, textStyle);
+}
+
+const char *CG_GameTypeString() {
+ if ( cgs.gametype == GT_FFA ) {
+ return "Free For All";
+ } else if ( cgs.gametype == GT_TEAM ) {
+ return "Team Deathmatch";
+ } else if ( cgs.gametype == GT_CTF ) {
+ return "Capture the Flag";
+ } else if ( cgs.gametype == GT_1FCTF ) {
+ return "One Flag CTF";
+ } else if ( cgs.gametype == GT_OBELISK ) {
+ return "Overload";
+ } else if ( cgs.gametype == GT_HARVESTER ) {
+ return "Harvester";
+ }
+ return "";
+}
+static void CG_DrawGameType(rectDef_t *rect, float scale, vec4_t color, qhandle_t shader, int textStyle ) {
+ CG_Text_Paint(rect->x, rect->y + rect->h, scale, color, CG_GameTypeString(), 0, 0, textStyle);
+}
+
+static void CG_Text_Paint_Limit(float *maxX, float x, float y, float scale, vec4_t color, const char* text, float adjust, int limit) {
+ int len, count;
+ vec4_t newColor;
+ glyphInfo_t *glyph;
+ if (text) {
+// TTimo: FIXME
+// const unsigned char *s = text; // bk001206 - unsigned
+ const char *s = text;
+ float max = *maxX;
+ float useScale;
+ fontInfo_t *font = &cgDC.Assets.textFont;
+ if (scale <= cg_smallFont.value) {
+ font = &cgDC.Assets.smallFont;
+ } else if (scale > cg_bigFont.value) {
+ font = &cgDC.Assets.bigFont;
+ }
+ useScale = scale * font->glyphScale;
+ trap_R_SetColor( color );
+ len = strlen(text);
+ if (limit > 0 && len > limit) {
+ len = limit;
+ }
+ count = 0;
+ while (s && *s && count < len) {
+ glyph = &font->glyphs[(int)*s]; // TTimo: FIXME: getting nasty warnings without the cast, hopefully this doesn't break the VM build
+ if ( Q_IsColorString( s ) ) {
+ memcpy( newColor, g_color_table[ColorIndex(*(s+1))], sizeof( newColor ) );
+ newColor[3] = color[3];
+ trap_R_SetColor( newColor );
+ s += 2;
+ continue;
+ } else {
+ float yadj = useScale * glyph->top;
+ if (CG_Text_Width(s, useScale, 1) + x > max) {
+ *maxX = 0;
+ break;
+ }
+ CG_Text_PaintChar(x, y - yadj,
+ glyph->imageWidth,
+ glyph->imageHeight,
+ useScale,
+ glyph->s,
+ glyph->t,
+ glyph->s2,
+ glyph->t2,
+ glyph->glyph);
+ x += (glyph->xSkip * useScale) + adjust;
+ *maxX = x;
+ count++;
+ s++;
+ }
+ }
+ trap_R_SetColor( NULL );
+ }
+
+}
+
+
+
+#define PIC_WIDTH 12
+
+void CG_DrawNewTeamInfo(rectDef_t *rect, float text_x, float text_y, float scale, vec4_t color, qhandle_t shader) {
+ int xx;
+ float y;
+ int i, j, len, count;
+ const char *p;
+ vec4_t hcolor;
+ float pwidth, lwidth, maxx, leftOver;
+ clientInfo_t *ci;
+ gitem_t *item;
+ qhandle_t h;
+
+ // max player name width
+ pwidth = 0;
+ count = (numSortedTeamPlayers > 8) ? 8 : numSortedTeamPlayers;
+ for (i = 0; i < count; i++) {
+ ci = cgs.clientinfo + sortedTeamPlayers[i];
+ if ( ci->infoValid && ci->team == cg.snap->ps.persistant[PERS_TEAM]) {
+ len = CG_Text_Width( ci->name, scale, 0);
+ if (len > pwidth)
+ pwidth = len;
+ }
+ }
+
+ // max location name width
+ lwidth = 0;
+ for (i = 1; i < MAX_LOCATIONS; i++) {
+ p = CG_ConfigString(CS_LOCATIONS + i);
+ if (p && *p) {
+ len = CG_Text_Width(p, scale, 0);
+ if (len > lwidth)
+ lwidth = len;
+ }
+ }
+
+ y = rect->y;
+
+ for (i = 0; i < count; i++) {
+ ci = cgs.clientinfo + sortedTeamPlayers[i];
+ if ( ci->infoValid && ci->team == cg.snap->ps.persistant[PERS_TEAM]) {
+
+ xx = rect->x + 1;
+ for (j = 0; j <= PW_NUM_POWERUPS; j++) {
+ if (ci->powerups & (1 << j)) {
+
+ item = BG_FindItemForPowerup( j );
+
+ if (item) {
+ CG_DrawPic( xx, y, PIC_WIDTH, PIC_WIDTH, trap_R_RegisterShader( item->icon ) );
+ xx += PIC_WIDTH;
+ }
+ }
+ }
+
+ // FIXME: max of 3 powerups shown properly
+ xx = rect->x + (PIC_WIDTH * 3) + 2;
+
+ CG_GetColorForHealth( ci->health, ci->armor, hcolor );
+ trap_R_SetColor(hcolor);
+ CG_DrawPic( xx, y + 1, PIC_WIDTH - 2, PIC_WIDTH - 2, cgs.media.heartShader );
+
+ //Com_sprintf (st, sizeof(st), "%3i %3i", ci->health, ci->armor);
+ //CG_Text_Paint(xx, y + text_y, scale, hcolor, st, 0, 0);
+
+ // draw weapon icon
+ xx += PIC_WIDTH + 1;
+
+// weapon used is not that useful, use the space for task
+#if 0
+ if ( cg_weapons[ci->curWeapon].weaponIcon ) {
+ CG_DrawPic( xx, y, PIC_WIDTH, PIC_WIDTH, cg_weapons[ci->curWeapon].weaponIcon );
+ } else {
+ CG_DrawPic( xx, y, PIC_WIDTH, PIC_WIDTH, cgs.media.deferShader );
+ }
+#endif
+
+ trap_R_SetColor(NULL);
+ if (cgs.orderPending) {
+ // blink the icon
+ if ( cg.time > cgs.orderTime - 2500 && (cg.time >> 9 ) & 1 ) {
+ h = 0;
+ } else {
+ h = CG_StatusHandle(cgs.currentOrder);
+ }
+ } else {
+ h = CG_StatusHandle(ci->teamTask);
+ }
+
+ if (h) {
+ CG_DrawPic( xx, y, PIC_WIDTH, PIC_WIDTH, h);
+ }
+
+ xx += PIC_WIDTH + 1;
+
+ leftOver = rect->w - xx;
+ maxx = xx + leftOver / 3;
+
+
+
+ CG_Text_Paint_Limit(&maxx, xx, y + text_y, scale, color, ci->name, 0, 0);
+
+ p = CG_ConfigString(CS_LOCATIONS + ci->location);
+ if (!p || !*p) {
+ p = "unknown";
+ }
+
+ xx += leftOver / 3 + 2;
+ maxx = rect->w - 4;
+
+ CG_Text_Paint_Limit(&maxx, xx, y + text_y, scale, color, p, 0, 0);
+ y += text_y + 2;
+ if ( y + text_y + 2 > rect->y + rect->h ) {
+ break;
+ }
+
+ }
+ }
+}
+
+
+void CG_DrawTeamSpectators(rectDef_t *rect, float scale, vec4_t color, qhandle_t shader) {
+ if (cg.spectatorLen) {
+ float maxX;
+
+ if (cg.spectatorWidth == -1) {
+ cg.spectatorWidth = 0;
+ cg.spectatorPaintX = rect->x + 1;
+ cg.spectatorPaintX2 = -1;
+ }
+
+ if (cg.spectatorOffset > cg.spectatorLen) {
+ cg.spectatorOffset = 0;
+ cg.spectatorPaintX = rect->x + 1;
+ cg.spectatorPaintX2 = -1;
+ }
+
+ if (cg.time > cg.spectatorTime) {
+ cg.spectatorTime = cg.time + 10;
+ if (cg.spectatorPaintX <= rect->x + 2) {
+ if (cg.spectatorOffset < cg.spectatorLen) {
+ cg.spectatorPaintX += CG_Text_Width(&cg.spectatorList[cg.spectatorOffset], scale, 1) - 1;
+ cg.spectatorOffset++;
+ } else {
+ cg.spectatorOffset = 0;
+ if (cg.spectatorPaintX2 >= 0) {
+ cg.spectatorPaintX = cg.spectatorPaintX2;
+ } else {
+ cg.spectatorPaintX = rect->x + rect->w - 2;
+ }
+ cg.spectatorPaintX2 = -1;
+ }
+ } else {
+ cg.spectatorPaintX--;
+ if (cg.spectatorPaintX2 >= 0) {
+ cg.spectatorPaintX2--;
+ }
+ }
+ }
+
+ maxX = rect->x + rect->w - 2;
+ CG_Text_Paint_Limit(&maxX, cg.spectatorPaintX, rect->y + rect->h - 3, scale, color, &cg.spectatorList[cg.spectatorOffset], 0, 0);
+ if (cg.spectatorPaintX2 >= 0) {
+ float maxX2 = rect->x + rect->w - 2;
+ CG_Text_Paint_Limit(&maxX2, cg.spectatorPaintX2, rect->y + rect->h - 3, scale, color, cg.spectatorList, 0, cg.spectatorOffset);
+ }
+ if (cg.spectatorOffset && maxX > 0) {
+ // if we have an offset ( we are skipping the first part of the string ) and we fit the string
+ if (cg.spectatorPaintX2 == -1) {
+ cg.spectatorPaintX2 = rect->x + rect->w - 2;
+ }
+ } else {
+ cg.spectatorPaintX2 = -1;
+ }
+
+ }
+}
+
+
+
+void CG_DrawMedal(int ownerDraw, rectDef_t *rect, float scale, vec4_t color, qhandle_t shader) {
+ score_t *score = &cg.scores[cg.selectedScore];
+ float value = 0;
+ char *text = NULL;
+ color[3] = 0.25;
+
+ switch (ownerDraw) {
+ case CG_ACCURACY:
+ value = score->accuracy;
+ break;
+ case CG_ASSISTS:
+ value = score->assistCount;
+ break;
+ case CG_DEFEND:
+ value = score->defendCount;
+ break;
+ case CG_EXCELLENT:
+ value = score->excellentCount;
+ break;
+ case CG_IMPRESSIVE:
+ value = score->impressiveCount;
+ break;
+ case CG_PERFECT:
+ value = score->perfect;
+ break;
+ case CG_GAUNTLET:
+ value = score->guantletCount;
+ break;
+ case CG_CAPTURES:
+ value = score->captures;
+ break;
+ }
+
+ if (value > 0) {
+ if (ownerDraw != CG_PERFECT) {
+ if (ownerDraw == CG_ACCURACY) {
+ text = va("%i%%", (int)value);
+ if (value > 50) {
+ color[3] = 1.0;
+ }
+ } else {
+ text = va("%i", (int)value);
+ color[3] = 1.0;
+ }
+ } else {
+ if (value) {
+ color[3] = 1.0;
+ }
+ text = "Wow";
+ }
+ }
+
+ trap_R_SetColor(color);
+ CG_DrawPic( rect->x, rect->y, rect->w, rect->h, shader );
+
+ if (text) {
+ color[3] = 1.0;
+ value = CG_Text_Width(text, scale, 0);
+ CG_Text_Paint(rect->x + (rect->w - value) / 2, rect->y + rect->h + 10 , scale, color, text, 0, 0, 0);
+ }
+ trap_R_SetColor(NULL);
+
+}
+
+
+//
+void CG_OwnerDraw(float x, float y, float w, float h, float text_x, float text_y, int ownerDraw, int ownerDrawFlags, int align, float special, float scale, vec4_t color, qhandle_t shader, int textStyle) {
+ rectDef_t rect;
+
+ if ( cg_drawStatus.integer == 0 ) {
+ return;
+ }
+
+ //if (ownerDrawFlags != 0 && !CG_OwnerDrawVisible(ownerDrawFlags)) {
+ // return;
+ //}
+
+ rect.x = x;
+ rect.y = y;
+ rect.w = w;
+ rect.h = h;
+
+ switch (ownerDraw) {
+ case CG_PLAYER_ARMOR_ICON:
+ CG_DrawPlayerArmorIcon(&rect, ownerDrawFlags & CG_SHOW_2DONLY);
+ break;
+ case CG_PLAYER_ARMOR_ICON2D:
+ CG_DrawPlayerArmorIcon(&rect, qtrue);
+ break;
+ case CG_PLAYER_ARMOR_VALUE:
+ CG_DrawPlayerArmorValue(&rect, scale, color, shader, textStyle);
+ break;
+ case CG_PLAYER_AMMO_ICON:
+ CG_DrawPlayerAmmoIcon(&rect, ownerDrawFlags & CG_SHOW_2DONLY);
+ break;
+ case CG_PLAYER_AMMO_ICON2D:
+ CG_DrawPlayerAmmoIcon(&rect, qtrue);
+ break;
+ case CG_PLAYER_AMMO_VALUE:
+ CG_DrawPlayerAmmoValue(&rect, scale, color, shader, textStyle);
+ break;
+ case CG_SELECTEDPLAYER_HEAD:
+ CG_DrawSelectedPlayerHead(&rect, ownerDrawFlags & CG_SHOW_2DONLY, qfalse);
+ break;
+ case CG_VOICE_HEAD:
+ CG_DrawSelectedPlayerHead(&rect, ownerDrawFlags & CG_SHOW_2DONLY, qtrue);
+ break;
+ case CG_VOICE_NAME:
+ CG_DrawSelectedPlayerName(&rect, scale, color, qtrue, textStyle);
+ break;
+ case CG_SELECTEDPLAYER_STATUS:
+ CG_DrawSelectedPlayerStatus(&rect);
+ break;
+ case CG_SELECTEDPLAYER_ARMOR:
+ CG_DrawSelectedPlayerArmor(&rect, scale, color, shader, textStyle);
+ break;
+ case CG_SELECTEDPLAYER_HEALTH:
+ CG_DrawSelectedPlayerHealth(&rect, scale, color, shader, textStyle);
+ break;
+ case CG_SELECTEDPLAYER_NAME:
+ CG_DrawSelectedPlayerName(&rect, scale, color, qfalse, textStyle);
+ break;
+ case CG_SELECTEDPLAYER_LOCATION:
+ CG_DrawSelectedPlayerLocation(&rect, scale, color, textStyle);
+ break;
+ case CG_SELECTEDPLAYER_WEAPON:
+ CG_DrawSelectedPlayerWeapon(&rect);
+ break;
+ case CG_SELECTEDPLAYER_POWERUP:
+ CG_DrawSelectedPlayerPowerup(&rect, ownerDrawFlags & CG_SHOW_2DONLY);
+ break;
+ case CG_PLAYER_HEAD:
+ CG_DrawPlayerHead(&rect, ownerDrawFlags & CG_SHOW_2DONLY);
+ break;
+ case CG_PLAYER_ITEM:
+ CG_DrawPlayerItem(&rect, scale, ownerDrawFlags & CG_SHOW_2DONLY);
+ break;
+ case CG_PLAYER_SCORE:
+ CG_DrawPlayerScore(&rect, scale, color, shader, textStyle);
+ break;
+ case CG_PLAYER_HEALTH:
+ CG_DrawPlayerHealth(&rect, scale, color, shader, textStyle);
+ break;
+ case CG_RED_SCORE:
+ CG_DrawRedScore(&rect, scale, color, shader, textStyle);
+ break;
+ case CG_BLUE_SCORE:
+ CG_DrawBlueScore(&rect, scale, color, shader, textStyle);
+ break;
+ case CG_RED_NAME:
+ CG_DrawRedName(&rect, scale, color, textStyle);
+ break;
+ case CG_BLUE_NAME:
+ CG_DrawBlueName(&rect, scale, color, textStyle);
+ break;
+ case CG_BLUE_FLAGHEAD:
+ CG_DrawBlueFlagHead(&rect);
+ break;
+ case CG_BLUE_FLAGSTATUS:
+ CG_DrawBlueFlagStatus(&rect, shader);
+ break;
+ case CG_BLUE_FLAGNAME:
+ CG_DrawBlueFlagName(&rect, scale, color, textStyle);
+ break;
+ case CG_RED_FLAGHEAD:
+ CG_DrawRedFlagHead(&rect);
+ break;
+ case CG_RED_FLAGSTATUS:
+ CG_DrawRedFlagStatus(&rect, shader);
+ break;
+ case CG_RED_FLAGNAME:
+ CG_DrawRedFlagName(&rect, scale, color, textStyle);
+ break;
+ case CG_HARVESTER_SKULLS:
+ CG_HarvesterSkulls(&rect, scale, color, qfalse, textStyle);
+ break;
+ case CG_HARVESTER_SKULLS2D:
+ CG_HarvesterSkulls(&rect, scale, color, qtrue, textStyle);
+ break;
+ case CG_ONEFLAG_STATUS:
+ CG_OneFlagStatus(&rect);
+ break;
+ case CG_PLAYER_LOCATION:
+ CG_DrawPlayerLocation(&rect, scale, color, textStyle);
+ break;
+ case CG_TEAM_COLOR:
+ CG_DrawTeamColor(&rect, color);
+ break;
+ case CG_CTF_POWERUP:
+ CG_DrawCTFPowerUp(&rect);
+ break;
+ case CG_AREA_POWERUP:
+ CG_DrawAreaPowerUp(&rect, align, special, scale, color);
+ break;
+ case CG_PLAYER_STATUS:
+ CG_DrawPlayerStatus(&rect);
+ break;
+ case CG_PLAYER_HASFLAG:
+ CG_DrawPlayerHasFlag(&rect, qfalse);
+ break;
+ case CG_PLAYER_HASFLAG2D:
+ CG_DrawPlayerHasFlag(&rect, qtrue);
+ break;
+ case CG_AREA_SYSTEMCHAT:
+ CG_DrawAreaSystemChat(&rect, scale, color, shader);
+ break;
+ case CG_AREA_TEAMCHAT:
+ CG_DrawAreaTeamChat(&rect, scale, color, shader);
+ break;
+ case CG_AREA_CHAT:
+ CG_DrawAreaChat(&rect, scale, color, shader);
+ break;
+ case CG_GAME_TYPE:
+ CG_DrawGameType(&rect, scale, color, shader, textStyle);
+ break;
+ case CG_GAME_STATUS:
+ CG_DrawGameStatus(&rect, scale, color, shader, textStyle);
+ break;
+ case CG_KILLER:
+ CG_DrawKiller(&rect, scale, color, shader, textStyle);
+ break;
+ case CG_ACCURACY:
+ case CG_ASSISTS:
+ case CG_DEFEND:
+ case CG_EXCELLENT:
+ case CG_IMPRESSIVE:
+ case CG_PERFECT:
+ case CG_GAUNTLET:
+ case CG_CAPTURES:
+ CG_DrawMedal(ownerDraw, &rect, scale, color, shader);
+ break;
+ case CG_SPECTATORS:
+ CG_DrawTeamSpectators(&rect, scale, color, shader);
+ break;
+ case CG_TEAMINFO:
+ if (cg_currentSelectedPlayer.integer == numSortedTeamPlayers) {
+ CG_DrawNewTeamInfo(&rect, text_x, text_y, scale, color, shader);
+ }
+ break;
+ case CG_CAPFRAGLIMIT:
+ CG_DrawCapFragLimit(&rect, scale, color, shader, textStyle);
+ break;
+ case CG_1STPLACE:
+ CG_Draw1stPlace(&rect, scale, color, shader, textStyle);
+ break;
+ case CG_2NDPLACE:
+ CG_Draw2ndPlace(&rect, scale, color, shader, textStyle);
+ break;
+ default:
+ break;
+ }
+}
+
+void CG_MouseEvent(int x, int y) {
+ int n;
+
+ if ( (cg.predictedPlayerState.pm_type == PM_NORMAL || cg.predictedPlayerState.pm_type == PM_SPECTATOR) && cg.showScores == qfalse) {
+ trap_Key_SetCatcher(0);
+ return;
+ }
+
+ cgs.cursorX+= x;
+ if (cgs.cursorX < 0)
+ cgs.cursorX = 0;
+ else if (cgs.cursorX > 640)
+ cgs.cursorX = 640;
+
+ cgs.cursorY += y;
+ if (cgs.cursorY < 0)
+ cgs.cursorY = 0;
+ else if (cgs.cursorY > 480)
+ cgs.cursorY = 480;
+
+ n = Display_CursorType(cgs.cursorX, cgs.cursorY);
+ cgs.activeCursor = 0;
+ if (n == CURSOR_ARROW) {
+ cgs.activeCursor = cgs.media.selectCursor;
+ } else if (n == CURSOR_SIZER) {
+ cgs.activeCursor = cgs.media.sizeCursor;
+ }
+
+ if (cgs.capturedItem) {
+ Display_MouseMove(cgs.capturedItem, x, y);
+ } else {
+ Display_MouseMove(NULL, cgs.cursorX, cgs.cursorY);
+ }
+
+}
+
+/*
+==================
+CG_HideTeamMenus
+==================
+
+*/
+void CG_HideTeamMenu() {
+ Menus_CloseByName("teamMenu");
+ Menus_CloseByName("getMenu");
+}
+
+/*
+==================
+CG_ShowTeamMenus
+==================
+
+*/
+void CG_ShowTeamMenu() {
+ Menus_OpenByName("teamMenu");
+}
+
+
+
+
+/*
+==================
+CG_EventHandling
+==================
+ type 0 - no event handling
+ 1 - team menu
+ 2 - hud editor
+
+*/
+void CG_EventHandling(int type) {
+ cgs.eventHandling = type;
+ if (type == CGAME_EVENT_NONE) {
+ CG_HideTeamMenu();
+ } else if (type == CGAME_EVENT_TEAMMENU) {
+ //CG_ShowTeamMenu();
+ } else if (type == CGAME_EVENT_SCOREBOARD) {
+ }
+
+}
+
+
+
+void CG_KeyEvent(int key, qboolean down) {
+
+ if (!down) {
+ return;
+ }
+
+ if ( cg.predictedPlayerState.pm_type == PM_NORMAL || (cg.predictedPlayerState.pm_type == PM_SPECTATOR && cg.showScores == qfalse)) {
+ CG_EventHandling(CGAME_EVENT_NONE);
+ trap_Key_SetCatcher(0);
+ return;
+ }
+
+ //if (key == trap_Key_GetKey("teamMenu") || !Display_CaptureItem(cgs.cursorX, cgs.cursorY)) {
+ // if we see this then we should always be visible
+ // CG_EventHandling(CGAME_EVENT_NONE);
+ // trap_Key_SetCatcher(0);
+ //}
+
+
+
+ Display_HandleKey(key, down, cgs.cursorX, cgs.cursorY);
+
+ if (cgs.capturedItem) {
+ cgs.capturedItem = NULL;
+ } else {
+ if (key == K_MOUSE2 && down) {
+ cgs.capturedItem = Display_CaptureItem(cgs.cursorX, cgs.cursorY);
+ }
+ }
+}
+
+int CG_ClientNumFromName(const char *p) {
+ int i;
+ for (i = 0; i < cgs.maxclients; i++) {
+ if (cgs.clientinfo[i].infoValid && Q_stricmp(cgs.clientinfo[i].name, p) == 0) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+void CG_ShowResponseHead() {
+ Menus_OpenByName("voiceMenu");
+ trap_Cvar_Set("cl_conXOffset", "72");
+ cg.voiceTime = cg.time;
+}
+
+void CG_RunMenuScript(char **args) {
+}
+
+
+void CG_GetTeamColor(vec4_t *color) {
+ if (cg.snap->ps.persistant[PERS_TEAM] == TEAM_RED) {
+ (*color)[0] = 1.0f;
+ (*color)[3] = 0.25f;
+ (*color)[1] = (*color)[2] = 0.0f;
+ } else if (cg.snap->ps.persistant[PERS_TEAM] == TEAM_BLUE) {
+ (*color)[0] = (*color)[1] = 0.0f;
+ (*color)[2] = 1.0f;
+ (*color)[3] = 0.25f;
+ } else {
+ (*color)[0] = (*color)[2] = 0.0f;
+ (*color)[1] = 0.17f;
+ (*color)[3] = 0.25f;
+ }
+}
+
diff --git a/code/cgame/cg_particles.c b/code/cgame/cg_particles.c
new file mode 100755
index 0000000..b3ce322
--- /dev/null
+++ b/code/cgame/cg_particles.c
@@ -0,0 +1,2018 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// Rafael particles
+// cg_particles.c
+
+#include "cg_local.h"
+
+#define BLOODRED 2
+#define EMISIVEFADE 3
+#define GREY75 4
+
+typedef struct particle_s
+{
+ struct particle_s *next;
+
+ float time;
+ float endtime;
+
+ vec3_t org;
+ vec3_t vel;
+ vec3_t accel;
+ int color;
+ float colorvel;
+ float alpha;
+ float alphavel;
+ int type;
+ qhandle_t pshader;
+
+ float height;
+ float width;
+
+ float endheight;
+ float endwidth;
+
+ float start;
+ float end;
+
+ float startfade;
+ qboolean rotate;
+ int snum;
+
+ qboolean link;
+
+ // Ridah
+ int shaderAnim;
+ int roll;
+
+ int accumroll;
+
+} cparticle_t;
+
+typedef enum
+{
+ P_NONE,
+ P_WEATHER,
+ P_FLAT,
+ P_SMOKE,
+ P_ROTATE,
+ P_WEATHER_TURBULENT,
+ P_ANIM, // Ridah
+ P_BAT,
+ P_BLEED,
+ P_FLAT_SCALEUP,
+ P_FLAT_SCALEUP_FADE,
+ P_WEATHER_FLURRY,
+ P_SMOKE_IMPACT,
+ P_BUBBLE,
+ P_BUBBLE_TURBULENT,
+ P_SPRITE
+} particle_type_t;
+
+#define MAX_SHADER_ANIMS 32
+#define MAX_SHADER_ANIM_FRAMES 64
+
+static char *shaderAnimNames[MAX_SHADER_ANIMS] = {
+ "explode1",
+ "blacksmokeanim",
+ "twiltb2",
+ "expblue",
+ "blacksmokeanimb", // uses 'explode1' sequence
+ "blood",
+ NULL
+};
+static qhandle_t shaderAnims[MAX_SHADER_ANIMS][MAX_SHADER_ANIM_FRAMES];
+static int shaderAnimCounts[MAX_SHADER_ANIMS] = {
+ 23,
+ 25,
+ 45,
+ 25,
+ 23,
+ 5,
+};
+static float shaderAnimSTRatio[MAX_SHADER_ANIMS] = {
+ 1.405f,
+ 1.0f,
+ 1.0f,
+ 1.0f,
+ 1.0f,
+ 1.0f,
+};
+static int numShaderAnims;
+// done.
+
+#define PARTICLE_GRAVITY 40
+#define MAX_PARTICLES 1024 * 8
+
+cparticle_t *active_particles, *free_particles;
+cparticle_t particles[MAX_PARTICLES];
+int cl_numparticles = MAX_PARTICLES;
+
+qboolean initparticles = qfalse;
+vec3_t vforward, vright, vup;
+vec3_t rforward, rright, rup;
+
+float oldtime;
+
+/*
+===============
+CL_ClearParticles
+===============
+*/
+void CG_ClearParticles (void)
+{
+ int i;
+
+ memset( particles, 0, sizeof(particles) );
+
+ free_particles = &particles[0];
+ active_particles = NULL;
+
+ for (i=0 ;i<cl_numparticles ; i++)
+ {
+ particles[i].next = &particles[i+1];
+ particles[i].type = 0;
+ }
+ particles[cl_numparticles-1].next = NULL;
+
+ oldtime = cg.time;
+
+ // Ridah, init the shaderAnims
+ for (i=0; shaderAnimNames[i]; i++) {
+ int j;
+
+ for (j=0; j<shaderAnimCounts[i]; j++) {
+ shaderAnims[i][j] = trap_R_RegisterShader( va("%s%i", shaderAnimNames[i], j+1) );
+ }
+ }
+ numShaderAnims = i;
+ // done.
+
+ initparticles = qtrue;
+}
+
+
+/*
+=====================
+CG_AddParticleToScene
+=====================
+*/
+void CG_AddParticleToScene (cparticle_t *p, vec3_t org, float alpha)
+{
+
+ vec3_t point;
+ polyVert_t verts[4];
+ float width;
+ float height;
+ float time, time2;
+ float ratio;
+ float invratio;
+ vec3_t color;
+ polyVert_t TRIverts[3];
+ vec3_t rright2, rup2;
+
+ if (p->type == P_WEATHER || p->type == P_WEATHER_TURBULENT || p->type == P_WEATHER_FLURRY
+ || p->type == P_BUBBLE || p->type == P_BUBBLE_TURBULENT)
+ {// create a front facing polygon
+
+ if (p->type != P_WEATHER_FLURRY)
+ {
+ if (p->type == P_BUBBLE || p->type == P_BUBBLE_TURBULENT)
+ {
+ if (org[2] > p->end)
+ {
+ p->time = cg.time;
+ VectorCopy (org, p->org); // Ridah, fixes rare snow flakes that flicker on the ground
+
+ p->org[2] = ( p->start + crandom () * 4 );
+
+
+ if (p->type == P_BUBBLE_TURBULENT)
+ {
+ p->vel[0] = crandom() * 4;
+ p->vel[1] = crandom() * 4;
+ }
+
+ }
+ }
+ else
+ {
+ if (org[2] < p->end)
+ {
+ p->time = cg.time;
+ VectorCopy (org, p->org); // Ridah, fixes rare snow flakes that flicker on the ground
+
+ while (p->org[2] < p->end)
+ {
+ p->org[2] += (p->start - p->end);
+ }
+
+
+ if (p->type == P_WEATHER_TURBULENT)
+ {
+ p->vel[0] = crandom() * 16;
+ p->vel[1] = crandom() * 16;
+ }
+
+ }
+ }
+
+
+ // Rafael snow pvs check
+ if (!p->link)
+ return;
+
+ p->alpha = 1;
+ }
+
+ // Ridah, had to do this or MAX_POLYS is being exceeded in village1.bsp
+ if (Distance( cg.snap->ps.origin, org ) > 1024) {
+ return;
+ }
+ // done.
+
+ if (p->type == P_BUBBLE || p->type == P_BUBBLE_TURBULENT)
+ {
+ VectorMA (org, -p->height, vup, point);
+ VectorMA (point, -p->width, vright, point);
+ VectorCopy (point, verts[0].xyz);
+ verts[0].st[0] = 0;
+ verts[0].st[1] = 0;
+ verts[0].modulate[0] = 255;
+ verts[0].modulate[1] = 255;
+ verts[0].modulate[2] = 255;
+ verts[0].modulate[3] = 255 * p->alpha;
+
+ VectorMA (org, -p->height, vup, point);
+ VectorMA (point, p->width, vright, point);
+ VectorCopy (point, verts[1].xyz);
+ verts[1].st[0] = 0;
+ verts[1].st[1] = 1;
+ verts[1].modulate[0] = 255;
+ verts[1].modulate[1] = 255;
+ verts[1].modulate[2] = 255;
+ verts[1].modulate[3] = 255 * p->alpha;
+
+ VectorMA (org, p->height, vup, point);
+ VectorMA (point, p->width, vright, point);
+ VectorCopy (point, verts[2].xyz);
+ verts[2].st[0] = 1;
+ verts[2].st[1] = 1;
+ verts[2].modulate[0] = 255;
+ verts[2].modulate[1] = 255;
+ verts[2].modulate[2] = 255;
+ verts[2].modulate[3] = 255 * p->alpha;
+
+ VectorMA (org, p->height, vup, point);
+ VectorMA (point, -p->width, vright, point);
+ VectorCopy (point, verts[3].xyz);
+ verts[3].st[0] = 1;
+ verts[3].st[1] = 0;
+ verts[3].modulate[0] = 255;
+ verts[3].modulate[1] = 255;
+ verts[3].modulate[2] = 255;
+ verts[3].modulate[3] = 255 * p->alpha;
+ }
+ else
+ {
+ VectorMA (org, -p->height, vup, point);
+ VectorMA (point, -p->width, vright, point);
+ VectorCopy( point, TRIverts[0].xyz );
+ TRIverts[0].st[0] = 1;
+ TRIverts[0].st[1] = 0;
+ TRIverts[0].modulate[0] = 255;
+ TRIverts[0].modulate[1] = 255;
+ TRIverts[0].modulate[2] = 255;
+ TRIverts[0].modulate[3] = 255 * p->alpha;
+
+ VectorMA (org, p->height, vup, point);
+ VectorMA (point, -p->width, vright, point);
+ VectorCopy (point, TRIverts[1].xyz);
+ TRIverts[1].st[0] = 0;
+ TRIverts[1].st[1] = 0;
+ TRIverts[1].modulate[0] = 255;
+ TRIverts[1].modulate[1] = 255;
+ TRIverts[1].modulate[2] = 255;
+ TRIverts[1].modulate[3] = 255 * p->alpha;
+
+ VectorMA (org, p->height, vup, point);
+ VectorMA (point, p->width, vright, point);
+ VectorCopy (point, TRIverts[2].xyz);
+ TRIverts[2].st[0] = 0;
+ TRIverts[2].st[1] = 1;
+ TRIverts[2].modulate[0] = 255;
+ TRIverts[2].modulate[1] = 255;
+ TRIverts[2].modulate[2] = 255;
+ TRIverts[2].modulate[3] = 255 * p->alpha;
+ }
+
+ }
+ else if (p->type == P_SPRITE)
+ {
+ vec3_t rr, ru;
+ vec3_t rotate_ang;
+
+ VectorSet (color, 1.0, 1.0, 1.0);
+ time = cg.time - p->time;
+ time2 = p->endtime - p->time;
+ ratio = time / time2;
+
+ width = p->width + ( ratio * ( p->endwidth - p->width) );
+ height = p->height + ( ratio * ( p->endheight - p->height) );
+
+ if (p->roll) {
+ vectoangles( cg.refdef.viewaxis[0], rotate_ang );
+ rotate_ang[ROLL] += p->roll;
+ AngleVectors ( rotate_ang, NULL, rr, ru);
+ }
+
+ if (p->roll) {
+ VectorMA (org, -height, ru, point);
+ VectorMA (point, -width, rr, point);
+ } else {
+ VectorMA (org, -height, vup, point);
+ VectorMA (point, -width, vright, point);
+ }
+ VectorCopy (point, verts[0].xyz);
+ verts[0].st[0] = 0;
+ verts[0].st[1] = 0;
+ verts[0].modulate[0] = 255;
+ verts[0].modulate[1] = 255;
+ verts[0].modulate[2] = 255;
+ verts[0].modulate[3] = 255;
+
+ if (p->roll) {
+ VectorMA (point, 2*height, ru, point);
+ } else {
+ VectorMA (point, 2*height, vup, point);
+ }
+ VectorCopy (point, verts[1].xyz);
+ verts[1].st[0] = 0;
+ verts[1].st[1] = 1;
+ verts[1].modulate[0] = 255;
+ verts[1].modulate[1] = 255;
+ verts[1].modulate[2] = 255;
+ verts[1].modulate[3] = 255;
+
+ if (p->roll) {
+ VectorMA (point, 2*width, rr, point);
+ } else {
+ VectorMA (point, 2*width, vright, point);
+ }
+ VectorCopy (point, verts[2].xyz);
+ verts[2].st[0] = 1;
+ verts[2].st[1] = 1;
+ verts[2].modulate[0] = 255;
+ verts[2].modulate[1] = 255;
+ verts[2].modulate[2] = 255;
+ verts[2].modulate[3] = 255;
+
+ if (p->roll) {
+ VectorMA (point, -2*height, ru, point);
+ } else {
+ VectorMA (point, -2*height, vup, point);
+ }
+ VectorCopy (point, verts[3].xyz);
+ verts[3].st[0] = 1;
+ verts[3].st[1] = 0;
+ verts[3].modulate[0] = 255;
+ verts[3].modulate[1] = 255;
+ verts[3].modulate[2] = 255;
+ verts[3].modulate[3] = 255;
+ }
+ else if (p->type == P_SMOKE || p->type == P_SMOKE_IMPACT)
+ {// create a front rotating facing polygon
+
+ if ( p->type == P_SMOKE_IMPACT && Distance( cg.snap->ps.origin, org ) > 1024) {
+ return;
+ }
+
+ if (p->color == BLOODRED)
+ VectorSet (color, 0.22f, 0.0f, 0.0f);
+ else if (p->color == GREY75)
+ {
+ float len;
+ float greyit;
+ float val;
+ len = Distance (cg.snap->ps.origin, org);
+ if (!len)
+ len = 1;
+
+ val = 4096/len;
+ greyit = 0.25 * val;
+ if (greyit > 0.5)
+ greyit = 0.5;
+
+ VectorSet (color, greyit, greyit, greyit);
+ }
+ else
+ VectorSet (color, 1.0, 1.0, 1.0);
+
+ time = cg.time - p->time;
+ time2 = p->endtime - p->time;
+ ratio = time / time2;
+
+ if (cg.time > p->startfade)
+ {
+ invratio = 1 - ( (cg.time - p->startfade) / (p->endtime - p->startfade) );
+
+ if (p->color == EMISIVEFADE)
+ {
+ float fval;
+ fval = (invratio * invratio);
+ if (fval < 0)
+ fval = 0;
+ VectorSet (color, fval , fval , fval );
+ }
+ invratio *= p->alpha;
+ }
+ else
+ invratio = 1 * p->alpha;
+
+ if ( cgs.glconfig.hardwareType == GLHW_RAGEPRO )
+ invratio = 1;
+
+ if (invratio > 1)
+ invratio = 1;
+
+ width = p->width + ( ratio * ( p->endwidth - p->width) );
+ height = p->height + ( ratio * ( p->endheight - p->height) );
+
+ if (p->type != P_SMOKE_IMPACT)
+ {
+ vec3_t temp;
+
+ vectoangles (rforward, temp);
+ p->accumroll += p->roll;
+ temp[ROLL] += p->accumroll * 0.1;
+ AngleVectors ( temp, NULL, rright2, rup2);
+ }
+ else
+ {
+ VectorCopy (rright, rright2);
+ VectorCopy (rup, rup2);
+ }
+
+ if (p->rotate)
+ {
+ VectorMA (org, -height, rup2, point);
+ VectorMA (point, -width, rright2, point);
+ }
+ else
+ {
+ VectorMA (org, -p->height, vup, point);
+ VectorMA (point, -p->width, vright, point);
+ }
+ VectorCopy (point, verts[0].xyz);
+ verts[0].st[0] = 0;
+ verts[0].st[1] = 0;
+ verts[0].modulate[0] = 255 * color[0];
+ verts[0].modulate[1] = 255 * color[1];
+ verts[0].modulate[2] = 255 * color[2];
+ verts[0].modulate[3] = 255 * invratio;
+
+ if (p->rotate)
+ {
+ VectorMA (org, -height, rup2, point);
+ VectorMA (point, width, rright2, point);
+ }
+ else
+ {
+ VectorMA (org, -p->height, vup, point);
+ VectorMA (point, p->width, vright, point);
+ }
+ VectorCopy (point, verts[1].xyz);
+ verts[1].st[0] = 0;
+ verts[1].st[1] = 1;
+ verts[1].modulate[0] = 255 * color[0];
+ verts[1].modulate[1] = 255 * color[1];
+ verts[1].modulate[2] = 255 * color[2];
+ verts[1].modulate[3] = 255 * invratio;
+
+ if (p->rotate)
+ {
+ VectorMA (org, height, rup2, point);
+ VectorMA (point, width, rright2, point);
+ }
+ else
+ {
+ VectorMA (org, p->height, vup, point);
+ VectorMA (point, p->width, vright, point);
+ }
+ VectorCopy (point, verts[2].xyz);
+ verts[2].st[0] = 1;
+ verts[2].st[1] = 1;
+ verts[2].modulate[0] = 255 * color[0];
+ verts[2].modulate[1] = 255 * color[1];
+ verts[2].modulate[2] = 255 * color[2];
+ verts[2].modulate[3] = 255 * invratio;
+
+ if (p->rotate)
+ {
+ VectorMA (org, height, rup2, point);
+ VectorMA (point, -width, rright2, point);
+ }
+ else
+ {
+ VectorMA (org, p->height, vup, point);
+ VectorMA (point, -p->width, vright, point);
+ }
+ VectorCopy (point, verts[3].xyz);
+ verts[3].st[0] = 1;
+ verts[3].st[1] = 0;
+ verts[3].modulate[0] = 255 * color[0];
+ verts[3].modulate[1] = 255 * color[1];
+ verts[3].modulate[2] = 255 * color[2];
+ verts[3].modulate[3] = 255 * invratio;
+
+ }
+ else if (p->type == P_BLEED)
+ {
+ vec3_t rr, ru;
+ vec3_t rotate_ang;
+ float alpha;
+
+ alpha = p->alpha;
+
+ if ( cgs.glconfig.hardwareType == GLHW_RAGEPRO )
+ alpha = 1;
+
+ if (p->roll)
+ {
+ vectoangles( cg.refdef.viewaxis[0], rotate_ang );
+ rotate_ang[ROLL] += p->roll;
+ AngleVectors ( rotate_ang, NULL, rr, ru);
+ }
+ else
+ {
+ VectorCopy (vup, ru);
+ VectorCopy (vright, rr);
+ }
+
+ VectorMA (org, -p->height, ru, point);
+ VectorMA (point, -p->width, rr, point);
+ VectorCopy (point, verts[0].xyz);
+ verts[0].st[0] = 0;
+ verts[0].st[1] = 0;
+ verts[0].modulate[0] = 111;
+ verts[0].modulate[1] = 19;
+ verts[0].modulate[2] = 9;
+ verts[0].modulate[3] = 255 * alpha;
+
+ VectorMA (org, -p->height, ru, point);
+ VectorMA (point, p->width, rr, point);
+ VectorCopy (point, verts[1].xyz);
+ verts[1].st[0] = 0;
+ verts[1].st[1] = 1;
+ verts[1].modulate[0] = 111;
+ verts[1].modulate[1] = 19;
+ verts[1].modulate[2] = 9;
+ verts[1].modulate[3] = 255 * alpha;
+
+ VectorMA (org, p->height, ru, point);
+ VectorMA (point, p->width, rr, point);
+ VectorCopy (point, verts[2].xyz);
+ verts[2].st[0] = 1;
+ verts[2].st[1] = 1;
+ verts[2].modulate[0] = 111;
+ verts[2].modulate[1] = 19;
+ verts[2].modulate[2] = 9;
+ verts[2].modulate[3] = 255 * alpha;
+
+ VectorMA (org, p->height, ru, point);
+ VectorMA (point, -p->width, rr, point);
+ VectorCopy (point, verts[3].xyz);
+ verts[3].st[0] = 1;
+ verts[3].st[1] = 0;
+ verts[3].modulate[0] = 111;
+ verts[3].modulate[1] = 19;
+ verts[3].modulate[2] = 9;
+ verts[3].modulate[3] = 255 * alpha;
+
+ }
+ else if (p->type == P_FLAT_SCALEUP)
+ {
+ float width, height;
+ float sinR, cosR;
+
+ if (p->color == BLOODRED)
+ VectorSet (color, 1, 1, 1);
+ else
+ VectorSet (color, 0.5, 0.5, 0.5);
+
+ time = cg.time - p->time;
+ time2 = p->endtime - p->time;
+ ratio = time / time2;
+
+ width = p->width + ( ratio * ( p->endwidth - p->width) );
+ height = p->height + ( ratio * ( p->endheight - p->height) );
+
+ if (width > p->endwidth)
+ width = p->endwidth;
+
+ if (height > p->endheight)
+ height = p->endheight;
+
+ sinR = height * sin(DEG2RAD(p->roll)) * sqrt(2);
+ cosR = width * cos(DEG2RAD(p->roll)) * sqrt(2);
+
+ VectorCopy (org, verts[0].xyz);
+ verts[0].xyz[0] -= sinR;
+ verts[0].xyz[1] -= cosR;
+ verts[0].st[0] = 0;
+ verts[0].st[1] = 0;
+ verts[0].modulate[0] = 255 * color[0];
+ verts[0].modulate[1] = 255 * color[1];
+ verts[0].modulate[2] = 255 * color[2];
+ verts[0].modulate[3] = 255;
+
+ VectorCopy (org, verts[1].xyz);
+ verts[1].xyz[0] -= cosR;
+ verts[1].xyz[1] += sinR;
+ verts[1].st[0] = 0;
+ verts[1].st[1] = 1;
+ verts[1].modulate[0] = 255 * color[0];
+ verts[1].modulate[1] = 255 * color[1];
+ verts[1].modulate[2] = 255 * color[2];
+ verts[1].modulate[3] = 255;
+
+ VectorCopy (org, verts[2].xyz);
+ verts[2].xyz[0] += sinR;
+ verts[2].xyz[1] += cosR;
+ verts[2].st[0] = 1;
+ verts[2].st[1] = 1;
+ verts[2].modulate[0] = 255 * color[0];
+ verts[2].modulate[1] = 255 * color[1];
+ verts[2].modulate[2] = 255 * color[2];
+ verts[2].modulate[3] = 255;
+
+ VectorCopy (org, verts[3].xyz);
+ verts[3].xyz[0] += cosR;
+ verts[3].xyz[1] -= sinR;
+ verts[3].st[0] = 1;
+ verts[3].st[1] = 0;
+ verts[3].modulate[0] = 255 * color[0];
+ verts[3].modulate[1] = 255 * color[1];
+ verts[3].modulate[2] = 255 * color[2];
+ verts[3].modulate[3] = 255;
+ }
+ else if (p->type == P_FLAT)
+ {
+
+ VectorCopy (org, verts[0].xyz);
+ verts[0].xyz[0] -= p->height;
+ verts[0].xyz[1] -= p->width;
+ verts[0].st[0] = 0;
+ verts[0].st[1] = 0;
+ verts[0].modulate[0] = 255;
+ verts[0].modulate[1] = 255;
+ verts[0].modulate[2] = 255;
+ verts[0].modulate[3] = 255;
+
+ VectorCopy (org, verts[1].xyz);
+ verts[1].xyz[0] -= p->height;
+ verts[1].xyz[1] += p->width;
+ verts[1].st[0] = 0;
+ verts[1].st[1] = 1;
+ verts[1].modulate[0] = 255;
+ verts[1].modulate[1] = 255;
+ verts[1].modulate[2] = 255;
+ verts[1].modulate[3] = 255;
+
+ VectorCopy (org, verts[2].xyz);
+ verts[2].xyz[0] += p->height;
+ verts[2].xyz[1] += p->width;
+ verts[2].st[0] = 1;
+ verts[2].st[1] = 1;
+ verts[2].modulate[0] = 255;
+ verts[2].modulate[1] = 255;
+ verts[2].modulate[2] = 255;
+ verts[2].modulate[3] = 255;
+
+ VectorCopy (org, verts[3].xyz);
+ verts[3].xyz[0] += p->height;
+ verts[3].xyz[1] -= p->width;
+ verts[3].st[0] = 1;
+ verts[3].st[1] = 0;
+ verts[3].modulate[0] = 255;
+ verts[3].modulate[1] = 255;
+ verts[3].modulate[2] = 255;
+ verts[3].modulate[3] = 255;
+
+ }
+ // Ridah
+ else if (p->type == P_ANIM) {
+ vec3_t rr, ru;
+ vec3_t rotate_ang;
+ int i, j;
+
+ time = cg.time - p->time;
+ time2 = p->endtime - p->time;
+ ratio = time / time2;
+ if (ratio >= 1.0f) {
+ ratio = 0.9999f;
+ }
+
+ width = p->width + ( ratio * ( p->endwidth - p->width) );
+ height = p->height + ( ratio * ( p->endheight - p->height) );
+
+ // if we are "inside" this sprite, don't draw
+ if (Distance( cg.snap->ps.origin, org ) < width/1.5) {
+ return;
+ }
+
+ i = p->shaderAnim;
+ j = (int)floor(ratio * shaderAnimCounts[p->shaderAnim]);
+ p->pshader = shaderAnims[i][j];
+
+ if (p->roll) {
+ vectoangles( cg.refdef.viewaxis[0], rotate_ang );
+ rotate_ang[ROLL] += p->roll;
+ AngleVectors ( rotate_ang, NULL, rr, ru);
+ }
+
+ if (p->roll) {
+ VectorMA (org, -height, ru, point);
+ VectorMA (point, -width, rr, point);
+ } else {
+ VectorMA (org, -height, vup, point);
+ VectorMA (point, -width, vright, point);
+ }
+ VectorCopy (point, verts[0].xyz);
+ verts[0].st[0] = 0;
+ verts[0].st[1] = 0;
+ verts[0].modulate[0] = 255;
+ verts[0].modulate[1] = 255;
+ verts[0].modulate[2] = 255;
+ verts[0].modulate[3] = 255;
+
+ if (p->roll) {
+ VectorMA (point, 2*height, ru, point);
+ } else {
+ VectorMA (point, 2*height, vup, point);
+ }
+ VectorCopy (point, verts[1].xyz);
+ verts[1].st[0] = 0;
+ verts[1].st[1] = 1;
+ verts[1].modulate[0] = 255;
+ verts[1].modulate[1] = 255;
+ verts[1].modulate[2] = 255;
+ verts[1].modulate[3] = 255;
+
+ if (p->roll) {
+ VectorMA (point, 2*width, rr, point);
+ } else {
+ VectorMA (point, 2*width, vright, point);
+ }
+ VectorCopy (point, verts[2].xyz);
+ verts[2].st[0] = 1;
+ verts[2].st[1] = 1;
+ verts[2].modulate[0] = 255;
+ verts[2].modulate[1] = 255;
+ verts[2].modulate[2] = 255;
+ verts[2].modulate[3] = 255;
+
+ if (p->roll) {
+ VectorMA (point, -2*height, ru, point);
+ } else {
+ VectorMA (point, -2*height, vup, point);
+ }
+ VectorCopy (point, verts[3].xyz);
+ verts[3].st[0] = 1;
+ verts[3].st[1] = 0;
+ verts[3].modulate[0] = 255;
+ verts[3].modulate[1] = 255;
+ verts[3].modulate[2] = 255;
+ verts[3].modulate[3] = 255;
+ }
+ // done.
+
+ if (!p->pshader) {
+// (SA) temp commented out for DM
+// CG_Printf ("CG_AddParticleToScene type %d p->pshader == ZERO\n", p->type);
+ return;
+ }
+
+ if (p->type == P_WEATHER || p->type == P_WEATHER_TURBULENT || p->type == P_WEATHER_FLURRY)
+ trap_R_AddPolyToScene( p->pshader, 3, TRIverts );
+ else
+ trap_R_AddPolyToScene( p->pshader, 4, verts );
+
+}
+
+// Ridah, made this static so it doesn't interfere with other files
+static float roll = 0.0;
+
+/*
+===============
+CG_AddParticles
+===============
+*/
+void CG_AddParticles (void)
+{
+ cparticle_t *p, *next;
+ float alpha;
+ float time, time2;
+ vec3_t org;
+ int color;
+ cparticle_t *active, *tail;
+ int type;
+ vec3_t rotate_ang;
+
+ if (!initparticles)
+ CG_ClearParticles ();
+
+ VectorCopy( cg.refdef.viewaxis[0], vforward );
+ VectorCopy( cg.refdef.viewaxis[1], vright );
+ VectorCopy( cg.refdef.viewaxis[2], vup );
+
+ vectoangles( cg.refdef.viewaxis[0], rotate_ang );
+ roll += ((cg.time - oldtime) * 0.1) ;
+ rotate_ang[ROLL] += (roll*0.9);
+ AngleVectors ( rotate_ang, rforward, rright, rup);
+
+ oldtime = cg.time;
+
+ active = NULL;
+ tail = NULL;
+
+ for (p=active_particles ; p ; p=next)
+ {
+
+ next = p->next;
+
+ time = (cg.time - p->time)*0.001;
+
+ alpha = p->alpha + time*p->alphavel;
+ if (alpha <= 0)
+ { // faded out
+ p->next = free_particles;
+ free_particles = p;
+ p->type = 0;
+ p->color = 0;
+ p->alpha = 0;
+ continue;
+ }
+
+ if (p->type == P_SMOKE || p->type == P_ANIM || p->type == P_BLEED || p->type == P_SMOKE_IMPACT)
+ {
+ if (cg.time > p->endtime)
+ {
+ p->next = free_particles;
+ free_particles = p;
+ p->type = 0;
+ p->color = 0;
+ p->alpha = 0;
+
+ continue;
+ }
+
+ }
+
+ if (p->type == P_WEATHER_FLURRY)
+ {
+ if (cg.time > p->endtime)
+ {
+ p->next = free_particles;
+ free_particles = p;
+ p->type = 0;
+ p->color = 0;
+ p->alpha = 0;
+
+ continue;
+ }
+ }
+
+
+ if (p->type == P_FLAT_SCALEUP_FADE)
+ {
+ if (cg.time > p->endtime)
+ {
+ p->next = free_particles;
+ free_particles = p;
+ p->type = 0;
+ p->color = 0;
+ p->alpha = 0;
+ continue;
+ }
+
+ }
+
+ if ((p->type == P_BAT || p->type == P_SPRITE) && p->endtime < 0) {
+ // temporary sprite
+ CG_AddParticleToScene (p, p->org, alpha);
+ p->next = free_particles;
+ free_particles = p;
+ p->type = 0;
+ p->color = 0;
+ p->alpha = 0;
+ continue;
+ }
+
+ p->next = NULL;
+ if (!tail)
+ active = tail = p;
+ else
+ {
+ tail->next = p;
+ tail = p;
+ }
+
+ if (alpha > 1.0)
+ alpha = 1;
+
+ color = p->color;
+
+ time2 = time*time;
+
+ org[0] = p->org[0] + p->vel[0]*time + p->accel[0]*time2;
+ org[1] = p->org[1] + p->vel[1]*time + p->accel[1]*time2;
+ org[2] = p->org[2] + p->vel[2]*time + p->accel[2]*time2;
+
+ type = p->type;
+
+ CG_AddParticleToScene (p, org, alpha);
+ }
+
+ active_particles = active;
+}
+
+/*
+======================
+CG_AddParticles
+======================
+*/
+void CG_ParticleSnowFlurry (qhandle_t pshader, centity_t *cent)
+{
+ cparticle_t *p;
+ qboolean turb = qtrue;
+
+ if (!pshader)
+ CG_Printf ("CG_ParticleSnowFlurry pshader == ZERO!\n");
+
+ if (!free_particles)
+ return;
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+ p->color = 0;
+ p->alpha = 0.90f;
+ p->alphavel = 0;
+
+ p->start = cent->currentState.origin2[0];
+ p->end = cent->currentState.origin2[1];
+
+ p->endtime = cg.time + cent->currentState.time;
+ p->startfade = cg.time + cent->currentState.time2;
+
+ p->pshader = pshader;
+
+ if (rand()%100 > 90)
+ {
+ p->height = 32;
+ p->width = 32;
+ p->alpha = 0.10f;
+ }
+ else
+ {
+ p->height = 1;
+ p->width = 1;
+ }
+
+ p->vel[2] = -20;
+
+ p->type = P_WEATHER_FLURRY;
+
+ if (turb)
+ p->vel[2] = -10;
+
+ VectorCopy(cent->currentState.origin, p->org);
+
+ p->org[0] = p->org[0];
+ p->org[1] = p->org[1];
+ p->org[2] = p->org[2];
+
+ p->vel[0] = p->vel[1] = 0;
+
+ p->accel[0] = p->accel[1] = p->accel[2] = 0;
+
+ p->vel[0] += cent->currentState.angles[0] * 32 + (crandom() * 16);
+ p->vel[1] += cent->currentState.angles[1] * 32 + (crandom() * 16);
+ p->vel[2] += cent->currentState.angles[2];
+
+ if (turb)
+ {
+ p->accel[0] = crandom () * 16;
+ p->accel[1] = crandom () * 16;
+ }
+
+}
+
+void CG_ParticleSnow (qhandle_t pshader, vec3_t origin, vec3_t origin2, int turb, float range, int snum)
+{
+ cparticle_t *p;
+
+ if (!pshader)
+ CG_Printf ("CG_ParticleSnow pshader == ZERO!\n");
+
+ if (!free_particles)
+ return;
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+ p->color = 0;
+ p->alpha = 0.40f;
+ p->alphavel = 0;
+ p->start = origin[2];
+ p->end = origin2[2];
+ p->pshader = pshader;
+ p->height = 1;
+ p->width = 1;
+
+ p->vel[2] = -50;
+
+ if (turb)
+ {
+ p->type = P_WEATHER_TURBULENT;
+ p->vel[2] = -50 * 1.3;
+ }
+ else
+ {
+ p->type = P_WEATHER;
+ }
+
+ VectorCopy(origin, p->org);
+
+ p->org[0] = p->org[0] + ( crandom() * range);
+ p->org[1] = p->org[1] + ( crandom() * range);
+ p->org[2] = p->org[2] + ( crandom() * (p->start - p->end));
+
+ p->vel[0] = p->vel[1] = 0;
+
+ p->accel[0] = p->accel[1] = p->accel[2] = 0;
+
+ if (turb)
+ {
+ p->vel[0] = crandom() * 16;
+ p->vel[1] = crandom() * 16;
+ }
+
+ // Rafael snow pvs check
+ p->snum = snum;
+ p->link = qtrue;
+
+}
+
+void CG_ParticleBubble (qhandle_t pshader, vec3_t origin, vec3_t origin2, int turb, float range, int snum)
+{
+ cparticle_t *p;
+ float randsize;
+
+ if (!pshader)
+ CG_Printf ("CG_ParticleSnow pshader == ZERO!\n");
+
+ if (!free_particles)
+ return;
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+ p->color = 0;
+ p->alpha = 0.40f;
+ p->alphavel = 0;
+ p->start = origin[2];
+ p->end = origin2[2];
+ p->pshader = pshader;
+
+ randsize = 1 + (crandom() * 0.5);
+
+ p->height = randsize;
+ p->width = randsize;
+
+ p->vel[2] = 50 + ( crandom() * 10 );
+
+ if (turb)
+ {
+ p->type = P_BUBBLE_TURBULENT;
+ p->vel[2] = 50 * 1.3;
+ }
+ else
+ {
+ p->type = P_BUBBLE;
+ }
+
+ VectorCopy(origin, p->org);
+
+ p->org[0] = p->org[0] + ( crandom() * range);
+ p->org[1] = p->org[1] + ( crandom() * range);
+ p->org[2] = p->org[2] + ( crandom() * (p->start - p->end));
+
+ p->vel[0] = p->vel[1] = 0;
+
+ p->accel[0] = p->accel[1] = p->accel[2] = 0;
+
+ if (turb)
+ {
+ p->vel[0] = crandom() * 4;
+ p->vel[1] = crandom() * 4;
+ }
+
+ // Rafael snow pvs check
+ p->snum = snum;
+ p->link = qtrue;
+
+}
+
+void CG_ParticleSmoke (qhandle_t pshader, centity_t *cent)
+{
+
+ // using cent->density = enttime
+ // cent->frame = startfade
+ cparticle_t *p;
+
+ if (!pshader)
+ CG_Printf ("CG_ParticleSmoke == ZERO!\n");
+
+ if (!free_particles)
+ return;
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+
+ p->endtime = cg.time + cent->currentState.time;
+ p->startfade = cg.time + cent->currentState.time2;
+
+ p->color = 0;
+ p->alpha = 1.0;
+ p->alphavel = 0;
+ p->start = cent->currentState.origin[2];
+ p->end = cent->currentState.origin2[2];
+ p->pshader = pshader;
+ p->rotate = qfalse;
+ p->height = 8;
+ p->width = 8;
+ p->endheight = 32;
+ p->endwidth = 32;
+ p->type = P_SMOKE;
+
+ VectorCopy(cent->currentState.origin, p->org);
+
+ p->vel[0] = p->vel[1] = 0;
+ p->accel[0] = p->accel[1] = p->accel[2] = 0;
+
+ p->vel[2] = 5;
+
+ if (cent->currentState.frame == 1)// reverse gravity
+ p->vel[2] *= -1;
+
+ p->roll = 8 + (crandom() * 4);
+}
+
+
+void CG_ParticleBulletDebris (vec3_t org, vec3_t vel, int duration)
+{
+
+ cparticle_t *p;
+
+ if (!free_particles)
+ return;
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+
+ p->endtime = cg.time + duration;
+ p->startfade = cg.time + duration/2;
+
+ p->color = EMISIVEFADE;
+ p->alpha = 1.0;
+ p->alphavel = 0;
+
+ p->height = 0.5;
+ p->width = 0.5;
+ p->endheight = 0.5;
+ p->endwidth = 0.5;
+
+ p->pshader = cgs.media.tracerShader;
+
+ p->type = P_SMOKE;
+
+ VectorCopy(org, p->org);
+
+ p->vel[0] = vel[0];
+ p->vel[1] = vel[1];
+ p->vel[2] = vel[2];
+ p->accel[0] = p->accel[1] = p->accel[2] = 0;
+
+ p->accel[2] = -60;
+ p->vel[2] += -20;
+
+}
+
+/*
+======================
+CG_ParticleExplosion
+======================
+*/
+
+void CG_ParticleExplosion (char *animStr, vec3_t origin, vec3_t vel, int duration, int sizeStart, int sizeEnd)
+{
+ cparticle_t *p;
+ int anim;
+
+ if (animStr < (char *)10)
+ CG_Error( "CG_ParticleExplosion: animStr is probably an index rather than a string" );
+
+ // find the animation string
+ for (anim=0; shaderAnimNames[anim]; anim++) {
+ if (!stricmp( animStr, shaderAnimNames[anim] ))
+ break;
+ }
+ if (!shaderAnimNames[anim]) {
+ CG_Error("CG_ParticleExplosion: unknown animation string: %s\n", animStr);
+ return;
+ }
+
+ if (!free_particles)
+ return;
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+ p->alpha = 1.0;
+ p->alphavel = 0;
+
+ if (duration < 0) {
+ duration *= -1;
+ p->roll = 0;
+ } else {
+ p->roll = crandom()*179;
+ }
+
+ p->shaderAnim = anim;
+
+ p->width = sizeStart;
+ p->height = sizeStart*shaderAnimSTRatio[anim]; // for sprites that are stretch in either direction
+
+ p->endheight = sizeEnd;
+ p->endwidth = sizeEnd*shaderAnimSTRatio[anim];
+
+ p->endtime = cg.time + duration;
+
+ p->type = P_ANIM;
+
+ VectorCopy( origin, p->org );
+ VectorCopy( vel, p->vel );
+ VectorClear( p->accel );
+
+}
+
+// Rafael Shrapnel
+void CG_AddParticleShrapnel (localEntity_t *le)
+{
+ return;
+}
+// done.
+
+int CG_NewParticleArea (int num)
+{
+ // const char *str;
+ char *str;
+ char *token;
+ int type;
+ vec3_t origin, origin2;
+ int i;
+ float range = 0;
+ int turb;
+ int numparticles;
+ int snum;
+
+ str = (char *) CG_ConfigString (num);
+ if (!str[0])
+ return (0);
+
+ // returns type 128 64 or 32
+ token = COM_Parse (&str);
+ type = atoi (token);
+
+ if (type == 1)
+ range = 128;
+ else if (type == 2)
+ range = 64;
+ else if (type == 3)
+ range = 32;
+ else if (type == 0)
+ range = 256;
+ else if (type == 4)
+ range = 8;
+ else if (type == 5)
+ range = 16;
+ else if (type == 6)
+ range = 32;
+ else if (type == 7)
+ range = 64;
+
+
+ for (i=0; i<3; i++)
+ {
+ token = COM_Parse (&str);
+ origin[i] = atof (token);
+ }
+
+ for (i=0; i<3; i++)
+ {
+ token = COM_Parse (&str);
+ origin2[i] = atof (token);
+ }
+
+ token = COM_Parse (&str);
+ numparticles = atoi (token);
+
+ token = COM_Parse (&str);
+ turb = atoi (token);
+
+ token = COM_Parse (&str);
+ snum = atoi (token);
+
+ for (i=0; i<numparticles; i++)
+ {
+ if (type >= 4)
+ CG_ParticleBubble (cgs.media.waterBubbleShader, origin, origin2, turb, range, snum);
+ else
+ CG_ParticleSnow (cgs.media.waterBubbleShader, origin, origin2, turb, range, snum);
+ }
+
+ return (1);
+}
+
+void CG_SnowLink (centity_t *cent, qboolean particleOn)
+{
+ cparticle_t *p, *next;
+ int id;
+
+ id = cent->currentState.frame;
+
+ for (p=active_particles ; p ; p=next)
+ {
+ next = p->next;
+
+ if (p->type == P_WEATHER || p->type == P_WEATHER_TURBULENT)
+ {
+ if (p->snum == id)
+ {
+ if (particleOn)
+ p->link = qtrue;
+ else
+ p->link = qfalse;
+ }
+ }
+
+ }
+}
+
+void CG_ParticleImpactSmokePuff (qhandle_t pshader, vec3_t origin)
+{
+ cparticle_t *p;
+
+ if (!pshader)
+ CG_Printf ("CG_ParticleImpactSmokePuff pshader == ZERO!\n");
+
+ if (!free_particles)
+ return;
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+ p->alpha = 0.25;
+ p->alphavel = 0;
+ p->roll = crandom()*179;
+
+ p->pshader = pshader;
+
+ p->endtime = cg.time + 1000;
+ p->startfade = cg.time + 100;
+
+ p->width = rand()%4 + 8;
+ p->height = rand()%4 + 8;
+
+ p->endheight = p->height *2;
+ p->endwidth = p->width * 2;
+
+ p->endtime = cg.time + 500;
+
+ p->type = P_SMOKE_IMPACT;
+
+ VectorCopy( origin, p->org );
+ VectorSet(p->vel, 0, 0, 20);
+ VectorSet(p->accel, 0, 0, 20);
+
+ p->rotate = qtrue;
+}
+
+void CG_Particle_Bleed (qhandle_t pshader, vec3_t start, vec3_t dir, int fleshEntityNum, int duration)
+{
+ cparticle_t *p;
+
+ if (!pshader)
+ CG_Printf ("CG_Particle_Bleed pshader == ZERO!\n");
+
+ if (!free_particles)
+ return;
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+ p->alpha = 1.0;
+ p->alphavel = 0;
+ p->roll = 0;
+
+ p->pshader = pshader;
+
+ p->endtime = cg.time + duration;
+
+ if (fleshEntityNum)
+ p->startfade = cg.time;
+ else
+ p->startfade = cg.time + 100;
+
+ p->width = 4;
+ p->height = 4;
+
+ p->endheight = 4+rand()%3;
+ p->endwidth = p->endheight;
+
+ p->type = P_SMOKE;
+
+ VectorCopy( start, p->org );
+ p->vel[0] = 0;
+ p->vel[1] = 0;
+ p->vel[2] = -20;
+ VectorClear( p->accel );
+
+ p->rotate = qfalse;
+
+ p->roll = rand()%179;
+
+ p->color = BLOODRED;
+ p->alpha = 0.75;
+
+}
+
+void CG_Particle_OilParticle (qhandle_t pshader, centity_t *cent)
+{
+ cparticle_t *p;
+
+ int time;
+ int time2;
+ float ratio;
+
+ float duration = 1500;
+
+ time = cg.time;
+ time2 = cg.time + cent->currentState.time;
+
+ ratio =(float)1 - ((float)time / (float)time2);
+
+ if (!pshader)
+ CG_Printf ("CG_Particle_OilParticle == ZERO!\n");
+
+ if (!free_particles)
+ return;
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+ p->alpha = 1.0;
+ p->alphavel = 0;
+ p->roll = 0;
+
+ p->pshader = pshader;
+
+ p->endtime = cg.time + duration;
+
+ p->startfade = p->endtime;
+
+ p->width = 1;
+ p->height = 3;
+
+ p->endheight = 3;
+ p->endwidth = 1;
+
+ p->type = P_SMOKE;
+
+ VectorCopy(cent->currentState.origin, p->org );
+
+ p->vel[0] = (cent->currentState.origin2[0] * (16 * ratio));
+ p->vel[1] = (cent->currentState.origin2[1] * (16 * ratio));
+ p->vel[2] = (cent->currentState.origin2[2]);
+
+ p->snum = 1.0f;
+
+ VectorClear( p->accel );
+
+ p->accel[2] = -20;
+
+ p->rotate = qfalse;
+
+ p->roll = rand()%179;
+
+ p->alpha = 0.75;
+
+}
+
+
+void CG_Particle_OilSlick (qhandle_t pshader, centity_t *cent)
+{
+ cparticle_t *p;
+
+ if (!pshader)
+ CG_Printf ("CG_Particle_OilSlick == ZERO!\n");
+
+ if (!free_particles)
+ return;
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+
+ if (cent->currentState.angles2[2])
+ p->endtime = cg.time + cent->currentState.angles2[2];
+ else
+ p->endtime = cg.time + 60000;
+
+ p->startfade = p->endtime;
+
+ p->alpha = 1.0;
+ p->alphavel = 0;
+ p->roll = 0;
+
+ p->pshader = pshader;
+
+ if (cent->currentState.angles2[0] || cent->currentState.angles2[1])
+ {
+ p->width = cent->currentState.angles2[0];
+ p->height = cent->currentState.angles2[0];
+
+ p->endheight = cent->currentState.angles2[1];
+ p->endwidth = cent->currentState.angles2[1];
+ }
+ else
+ {
+ p->width = 8;
+ p->height = 8;
+
+ p->endheight = 16;
+ p->endwidth = 16;
+ }
+
+ p->type = P_FLAT_SCALEUP;
+
+ p->snum = 1.0;
+
+ VectorCopy(cent->currentState.origin, p->org );
+
+ p->org[2]+= 0.55 + (crandom() * 0.5);
+
+ p->vel[0] = 0;
+ p->vel[1] = 0;
+ p->vel[2] = 0;
+ VectorClear( p->accel );
+
+ p->rotate = qfalse;
+
+ p->roll = rand()%179;
+
+ p->alpha = 0.75;
+
+}
+
+void CG_OilSlickRemove (centity_t *cent)
+{
+ cparticle_t *p, *next;
+ int id;
+
+ id = 1.0f;
+
+ if (!id)
+ CG_Printf ("CG_OilSlickRevove NULL id\n");
+
+ for (p=active_particles ; p ; p=next)
+ {
+ next = p->next;
+
+ if (p->type == P_FLAT_SCALEUP)
+ {
+ if (p->snum == id)
+ {
+ p->endtime = cg.time + 100;
+ p->startfade = p->endtime;
+ p->type = P_FLAT_SCALEUP_FADE;
+
+ }
+ }
+
+ }
+}
+
+qboolean ValidBloodPool (vec3_t start)
+{
+#define EXTRUDE_DIST 0.5
+
+ vec3_t angles;
+ vec3_t right, up;
+ vec3_t this_pos, x_pos, center_pos, end_pos;
+ float x, y;
+ float fwidth, fheight;
+ trace_t trace;
+ vec3_t normal;
+
+ fwidth = 16;
+ fheight = 16;
+
+ VectorSet (normal, 0, 0, 1);
+
+ vectoangles (normal, angles);
+ AngleVectors (angles, NULL, right, up);
+
+ VectorMA (start, EXTRUDE_DIST, normal, center_pos);
+
+ for (x= -fwidth/2; x<fwidth; x+= fwidth)
+ {
+ VectorMA (center_pos, x, right, x_pos);
+
+ for (y= -fheight/2; y<fheight; y+= fheight)
+ {
+ VectorMA (x_pos, y, up, this_pos);
+ VectorMA (this_pos, -EXTRUDE_DIST*2, normal, end_pos);
+
+ CG_Trace (&trace, this_pos, NULL, NULL, end_pos, -1, CONTENTS_SOLID);
+
+
+ if (trace.entityNum < (MAX_ENTITIES - 1)) // may only land on world
+ return qfalse;
+
+ if (!(!trace.startsolid && trace.fraction < 1))
+ return qfalse;
+
+ }
+ }
+
+ return qtrue;
+}
+
+void CG_BloodPool (localEntity_t *le, qhandle_t pshader, trace_t *tr)
+{
+ cparticle_t *p;
+ qboolean legit;
+ vec3_t start;
+ float rndSize;
+
+ if (!pshader)
+ CG_Printf ("CG_BloodPool pshader == ZERO!\n");
+
+ if (!free_particles)
+ return;
+
+ VectorCopy (tr->endpos, start);
+ legit = ValidBloodPool (start);
+
+ if (!legit)
+ return;
+
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+
+ p->endtime = cg.time + 3000;
+ p->startfade = p->endtime;
+
+ p->alpha = 1.0;
+ p->alphavel = 0;
+ p->roll = 0;
+
+ p->pshader = pshader;
+
+ rndSize = 0.4 + random()*0.6;
+
+ p->width = 8*rndSize;
+ p->height = 8*rndSize;
+
+ p->endheight = 16*rndSize;
+ p->endwidth = 16*rndSize;
+
+ p->type = P_FLAT_SCALEUP;
+
+ VectorCopy(start, p->org );
+
+ p->vel[0] = 0;
+ p->vel[1] = 0;
+ p->vel[2] = 0;
+ VectorClear( p->accel );
+
+ p->rotate = qfalse;
+
+ p->roll = rand()%179;
+
+ p->alpha = 0.75;
+
+ p->color = BLOODRED;
+}
+
+#define NORMALSIZE 16
+#define LARGESIZE 32
+
+void CG_ParticleBloodCloud (centity_t *cent, vec3_t origin, vec3_t dir)
+{
+ float length;
+ float dist;
+ float crittersize;
+ vec3_t angles, forward;
+ vec3_t point;
+ cparticle_t *p;
+ int i;
+
+ dist = 0;
+
+ length = VectorLength (dir);
+ vectoangles (dir, angles);
+ AngleVectors (angles, forward, NULL, NULL);
+
+ crittersize = LARGESIZE;
+
+ if (length)
+ dist = length / crittersize;
+
+ if (dist < 1)
+ dist = 1;
+
+ VectorCopy (origin, point);
+
+ for (i=0; i<dist; i++)
+ {
+ VectorMA (point, crittersize, forward, point);
+
+ if (!free_particles)
+ return;
+
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+
+ p->time = cg.time;
+ p->alpha = 1.0;
+ p->alphavel = 0;
+ p->roll = 0;
+
+ p->pshader = cgs.media.smokePuffShader;
+
+ p->endtime = cg.time + 350 + (crandom() * 100);
+
+ p->startfade = cg.time;
+
+ p->width = LARGESIZE;
+ p->height = LARGESIZE;
+ p->endheight = LARGESIZE;
+ p->endwidth = LARGESIZE;
+
+ p->type = P_SMOKE;
+
+ VectorCopy( origin, p->org );
+
+ p->vel[0] = 0;
+ p->vel[1] = 0;
+ p->vel[2] = -1;
+
+ VectorClear( p->accel );
+
+ p->rotate = qfalse;
+
+ p->roll = rand()%179;
+
+ p->color = BLOODRED;
+
+ p->alpha = 0.75;
+
+ }
+
+
+}
+
+void CG_ParticleSparks (vec3_t org, vec3_t vel, int duration, float x, float y, float speed)
+{
+ cparticle_t *p;
+
+ if (!free_particles)
+ return;
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+
+ p->endtime = cg.time + duration;
+ p->startfade = cg.time + duration/2;
+
+ p->color = EMISIVEFADE;
+ p->alpha = 0.4f;
+ p->alphavel = 0;
+
+ p->height = 0.5;
+ p->width = 0.5;
+ p->endheight = 0.5;
+ p->endwidth = 0.5;
+
+ p->pshader = cgs.media.tracerShader;
+
+ p->type = P_SMOKE;
+
+ VectorCopy(org, p->org);
+
+ p->org[0] += (crandom() * x);
+ p->org[1] += (crandom() * y);
+
+ p->vel[0] = vel[0];
+ p->vel[1] = vel[1];
+ p->vel[2] = vel[2];
+
+ p->accel[0] = p->accel[1] = p->accel[2] = 0;
+
+ p->vel[0] += (crandom() * 4);
+ p->vel[1] += (crandom() * 4);
+ p->vel[2] += (20 + (crandom() * 10)) * speed;
+
+ p->accel[0] = crandom () * 4;
+ p->accel[1] = crandom () * 4;
+
+}
+
+void CG_ParticleDust (centity_t *cent, vec3_t origin, vec3_t dir)
+{
+ float length;
+ float dist;
+ float crittersize;
+ vec3_t angles, forward;
+ vec3_t point;
+ cparticle_t *p;
+ int i;
+
+ dist = 0;
+
+ VectorNegate (dir, dir);
+ length = VectorLength (dir);
+ vectoangles (dir, angles);
+ AngleVectors (angles, forward, NULL, NULL);
+
+ crittersize = LARGESIZE;
+
+ if (length)
+ dist = length / crittersize;
+
+ if (dist < 1)
+ dist = 1;
+
+ VectorCopy (origin, point);
+
+ for (i=0; i<dist; i++)
+ {
+ VectorMA (point, crittersize, forward, point);
+
+ if (!free_particles)
+ return;
+
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+
+ p->time = cg.time;
+ p->alpha = 5.0;
+ p->alphavel = 0;
+ p->roll = 0;
+
+ p->pshader = cgs.media.smokePuffShader;
+
+ // RF, stay around for long enough to expand and dissipate naturally
+ if (length)
+ p->endtime = cg.time + 4500 + (crandom() * 3500);
+ else
+ p->endtime = cg.time + 750 + (crandom() * 500);
+
+ p->startfade = cg.time;
+
+ p->width = LARGESIZE;
+ p->height = LARGESIZE;
+
+ // RF, expand while falling
+ p->endheight = LARGESIZE*3.0;
+ p->endwidth = LARGESIZE*3.0;
+
+ if (!length)
+ {
+ p->width *= 0.2f;
+ p->height *= 0.2f;
+
+ p->endheight = NORMALSIZE;
+ p->endwidth = NORMALSIZE;
+ }
+
+ p->type = P_SMOKE;
+
+ VectorCopy( point, p->org );
+
+ p->vel[0] = crandom()*6;
+ p->vel[1] = crandom()*6;
+ p->vel[2] = random()*20;
+
+ // RF, add some gravity/randomness
+ p->accel[0] = crandom()*3;
+ p->accel[1] = crandom()*3;
+ p->accel[2] = -PARTICLE_GRAVITY*0.4;
+
+ VectorClear( p->accel );
+
+ p->rotate = qfalse;
+
+ p->roll = rand()%179;
+
+ p->alpha = 0.75;
+
+ }
+
+
+}
+
+void CG_ParticleMisc (qhandle_t pshader, vec3_t origin, int size, int duration, float alpha)
+{
+ cparticle_t *p;
+
+ if (!pshader)
+ CG_Printf ("CG_ParticleImpactSmokePuff pshader == ZERO!\n");
+
+ if (!free_particles)
+ return;
+
+ p = free_particles;
+ free_particles = p->next;
+ p->next = active_particles;
+ active_particles = p;
+ p->time = cg.time;
+ p->alpha = 1.0;
+ p->alphavel = 0;
+ p->roll = rand()%179;
+
+ p->pshader = pshader;
+
+ if (duration > 0)
+ p->endtime = cg.time + duration;
+ else
+ p->endtime = duration;
+
+ p->startfade = cg.time;
+
+ p->width = size;
+ p->height = size;
+
+ p->endheight = size;
+ p->endwidth = size;
+
+ p->type = P_SPRITE;
+
+ VectorCopy( origin, p->org );
+
+ p->rotate = qfalse;
+}
diff --git a/code/cgame/cg_players.c b/code/cgame/cg_players.c
new file mode 100755
index 0000000..2fd7b73
--- /dev/null
+++ b/code/cgame/cg_players.c
@@ -0,0 +1,2619 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// cg_players.c -- handle the media and animation for player entities
+#include "cg_local.h"
+
+char *cg_customSoundNames[MAX_CUSTOM_SOUNDS] = {
+ "*death1.wav",
+ "*death2.wav",
+ "*death3.wav",
+ "*jump1.wav",
+ "*pain25_1.wav",
+ "*pain50_1.wav",
+ "*pain75_1.wav",
+ "*pain100_1.wav",
+ "*falling1.wav",
+ "*gasp.wav",
+ "*drown.wav",
+ "*fall1.wav",
+ "*taunt.wav"
+};
+
+
+/*
+================
+CG_CustomSound
+
+================
+*/
+sfxHandle_t CG_CustomSound( int clientNum, const char *soundName ) {
+ clientInfo_t *ci;
+ int i;
+
+ if ( soundName[0] != '*' ) {
+ return trap_S_RegisterSound( soundName, qfalse );
+ }
+
+ if ( clientNum < 0 || clientNum >= MAX_CLIENTS ) {
+ clientNum = 0;
+ }
+ ci = &cgs.clientinfo[ clientNum ];
+
+ for ( i = 0 ; i < MAX_CUSTOM_SOUNDS && cg_customSoundNames[i] ; i++ ) {
+ if ( !strcmp( soundName, cg_customSoundNames[i] ) ) {
+ return ci->sounds[i];
+ }
+ }
+
+ CG_Error( "Unknown custom sound: %s", soundName );
+ return 0;
+}
+
+
+
+/*
+=============================================================================
+
+CLIENT INFO
+
+=============================================================================
+*/
+
+/*
+======================
+CG_ParseAnimationFile
+
+Read a configuration file containing animation coutns and rates
+models/players/visor/animation.cfg, etc
+======================
+*/
+static qboolean CG_ParseAnimationFile( const char *filename, clientInfo_t *ci ) {
+ char *text_p, *prev;
+ int len;
+ int i;
+ char *token;
+ float fps;
+ int skip;
+ char text[20000];
+ fileHandle_t f;
+ animation_t *animations;
+
+ animations = ci->animations;
+
+ // load the file
+ len = trap_FS_FOpenFile( filename, &f, FS_READ );
+ if ( len <= 0 ) {
+ return qfalse;
+ }
+ if ( len >= sizeof( text ) - 1 ) {
+ CG_Printf( "File %s too long\n", filename );
+ return qfalse;
+ }
+ trap_FS_Read( text, len, f );
+ text[len] = 0;
+ trap_FS_FCloseFile( f );
+
+ // parse the text
+ text_p = text;
+ skip = 0; // quite the compiler warning
+
+ ci->footsteps = FOOTSTEP_NORMAL;
+ VectorClear( ci->headOffset );
+ ci->gender = GENDER_MALE;
+ ci->fixedlegs = qfalse;
+ ci->fixedtorso = qfalse;
+
+ // read optional parameters
+ while ( 1 ) {
+ prev = text_p; // so we can unget
+ token = COM_Parse( &text_p );
+ if ( !token ) {
+ break;
+ }
+ if ( !Q_stricmp( token, "footsteps" ) ) {
+ token = COM_Parse( &text_p );
+ if ( !token ) {
+ break;
+ }
+ if ( !Q_stricmp( token, "default" ) || !Q_stricmp( token, "normal" ) ) {
+ ci->footsteps = FOOTSTEP_NORMAL;
+ } else if ( !Q_stricmp( token, "boot" ) ) {
+ ci->footsteps = FOOTSTEP_BOOT;
+ } else if ( !Q_stricmp( token, "flesh" ) ) {
+ ci->footsteps = FOOTSTEP_FLESH;
+ } else if ( !Q_stricmp( token, "mech" ) ) {
+ ci->footsteps = FOOTSTEP_MECH;
+ } else if ( !Q_stricmp( token, "energy" ) ) {
+ ci->footsteps = FOOTSTEP_ENERGY;
+ } else {
+ CG_Printf( "Bad footsteps parm in %s: %s\n", filename, token );
+ }
+ continue;
+ } else if ( !Q_stricmp( token, "headoffset" ) ) {
+ for ( i = 0 ; i < 3 ; i++ ) {
+ token = COM_Parse( &text_p );
+ if ( !token ) {
+ break;
+ }
+ ci->headOffset[i] = atof( token );
+ }
+ continue;
+ } else if ( !Q_stricmp( token, "sex" ) ) {
+ token = COM_Parse( &text_p );
+ if ( !token ) {
+ break;
+ }
+ if ( token[0] == 'f' || token[0] == 'F' ) {
+ ci->gender = GENDER_FEMALE;
+ } else if ( token[0] == 'n' || token[0] == 'N' ) {
+ ci->gender = GENDER_NEUTER;
+ } else {
+ ci->gender = GENDER_MALE;
+ }
+ continue;
+ } else if ( !Q_stricmp( token, "fixedlegs" ) ) {
+ ci->fixedlegs = qtrue;
+ continue;
+ } else if ( !Q_stricmp( token, "fixedtorso" ) ) {
+ ci->fixedtorso = qtrue;
+ continue;
+ }
+
+ // if it is a number, start parsing animations
+ if ( token[0] >= '0' && token[0] <= '9' ) {
+ text_p = prev; // unget the token
+ break;
+ }
+ Com_Printf( "unknown token '%s' is %s\n", token, filename );
+ }
+
+ // read information for each frame
+ for ( i = 0 ; i < MAX_ANIMATIONS ; i++ ) {
+
+ token = COM_Parse( &text_p );
+ if ( !*token ) {
+ if( i >= TORSO_GETFLAG && i <= TORSO_NEGATIVE ) {
+ animations[i].firstFrame = animations[TORSO_GESTURE].firstFrame;
+ animations[i].frameLerp = animations[TORSO_GESTURE].frameLerp;
+ animations[i].initialLerp = animations[TORSO_GESTURE].initialLerp;
+ animations[i].loopFrames = animations[TORSO_GESTURE].loopFrames;
+ animations[i].numFrames = animations[TORSO_GESTURE].numFrames;
+ animations[i].reversed = qfalse;
+ animations[i].flipflop = qfalse;
+ continue;
+ }
+ break;
+ }
+ animations[i].firstFrame = atoi( token );
+ // leg only frames are adjusted to not count the upper body only frames
+ if ( i == LEGS_WALKCR ) {
+ skip = animations[LEGS_WALKCR].firstFrame - animations[TORSO_GESTURE].firstFrame;
+ }
+ if ( i >= LEGS_WALKCR && i<TORSO_GETFLAG) {
+ animations[i].firstFrame -= skip;
+ }
+
+ token = COM_Parse( &text_p );
+ if ( !*token ) {
+ break;
+ }
+ animations[i].numFrames = atoi( token );
+
+ animations[i].reversed = qfalse;
+ animations[i].flipflop = qfalse;
+ // if numFrames is negative the animation is reversed
+ if (animations[i].numFrames < 0) {
+ animations[i].numFrames = -animations[i].numFrames;
+ animations[i].reversed = qtrue;
+ }
+
+ token = COM_Parse( &text_p );
+ if ( !*token ) {
+ break;
+ }
+ animations[i].loopFrames = atoi( token );
+
+ token = COM_Parse( &text_p );
+ if ( !*token ) {
+ break;
+ }
+ fps = atof( token );
+ if ( fps == 0 ) {
+ fps = 1;
+ }
+ animations[i].frameLerp = 1000 / fps;
+ animations[i].initialLerp = 1000 / fps;
+ }
+
+ if ( i != MAX_ANIMATIONS ) {
+ CG_Printf( "Error parsing animation file: %s", filename );
+ return qfalse;
+ }
+
+ // crouch backward animation
+ memcpy(&animations[LEGS_BACKCR], &animations[LEGS_WALKCR], sizeof(animation_t));
+ animations[LEGS_BACKCR].reversed = qtrue;
+ // walk backward animation
+ memcpy(&animations[LEGS_BACKWALK], &animations[LEGS_WALK], sizeof(animation_t));
+ animations[LEGS_BACKWALK].reversed = qtrue;
+ // flag moving fast
+ animations[FLAG_RUN].firstFrame = 0;
+ animations[FLAG_RUN].numFrames = 16;
+ animations[FLAG_RUN].loopFrames = 16;
+ animations[FLAG_RUN].frameLerp = 1000 / 15;
+ animations[FLAG_RUN].initialLerp = 1000 / 15;
+ animations[FLAG_RUN].reversed = qfalse;
+ // flag not moving or moving slowly
+ animations[FLAG_STAND].firstFrame = 16;
+ animations[FLAG_STAND].numFrames = 5;
+ animations[FLAG_STAND].loopFrames = 0;
+ animations[FLAG_STAND].frameLerp = 1000 / 20;
+ animations[FLAG_STAND].initialLerp = 1000 / 20;
+ animations[FLAG_STAND].reversed = qfalse;
+ // flag speeding up
+ animations[FLAG_STAND2RUN].firstFrame = 16;
+ animations[FLAG_STAND2RUN].numFrames = 5;
+ animations[FLAG_STAND2RUN].loopFrames = 1;
+ animations[FLAG_STAND2RUN].frameLerp = 1000 / 15;
+ animations[FLAG_STAND2RUN].initialLerp = 1000 / 15;
+ animations[FLAG_STAND2RUN].reversed = qtrue;
+ //
+ // new anims changes
+ //
+// animations[TORSO_GETFLAG].flipflop = qtrue;
+// animations[TORSO_GUARDBASE].flipflop = qtrue;
+// animations[TORSO_PATROL].flipflop = qtrue;
+// animations[TORSO_AFFIRMATIVE].flipflop = qtrue;
+// animations[TORSO_NEGATIVE].flipflop = qtrue;
+ //
+ return qtrue;
+}
+
+/*
+==========================
+CG_FileExists
+==========================
+*/
+static qboolean CG_FileExists(const char *filename) {
+ int len;
+
+ len = trap_FS_FOpenFile( filename, 0, FS_READ );
+ if (len>0) {
+ return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+==========================
+CG_FindClientModelFile
+==========================
+*/
+static qboolean CG_FindClientModelFile( char *filename, int length, clientInfo_t *ci, const char *teamName, const char *modelName, const char *skinName, const char *base, const char *ext ) {
+ char *team, *charactersFolder;
+ int i;
+
+ if ( cgs.gametype >= GT_TEAM ) {
+ switch ( ci->team ) {
+ case TEAM_BLUE: {
+ team = "blue";
+ break;
+ }
+ default: {
+ team = "red";
+ break;
+ }
+ }
+ }
+ else {
+ team = "default";
+ }
+ charactersFolder = "";
+ while(1) {
+ for ( i = 0; i < 2; i++ ) {
+ if ( i == 0 && teamName && *teamName ) {
+ // "models/players/characters/james/stroggs/lower_lily_red.skin"
+ Com_sprintf( filename, length, "models/players/%s%s/%s%s_%s_%s.%s", charactersFolder, modelName, teamName, base, skinName, team, ext );
+ }
+ else {
+ // "models/players/characters/james/lower_lily_red.skin"
+ Com_sprintf( filename, length, "models/players/%s%s/%s_%s_%s.%s", charactersFolder, modelName, base, skinName, team, ext );
+ }
+ if ( CG_FileExists( filename ) ) {
+ return qtrue;
+ }
+ if ( cgs.gametype >= GT_TEAM ) {
+ if ( i == 0 && teamName && *teamName ) {
+ // "models/players/characters/james/stroggs/lower_red.skin"
+ Com_sprintf( filename, length, "models/players/%s%s/%s%s_%s.%s", charactersFolder, modelName, teamName, base, team, ext );
+ }
+ else {
+ // "models/players/characters/james/lower_red.skin"
+ Com_sprintf( filename, length, "models/players/%s%s/%s_%s.%s", charactersFolder, modelName, base, team, ext );
+ }
+ }
+ else {
+ if ( i == 0 && teamName && *teamName ) {
+ // "models/players/characters/james/stroggs/lower_lily.skin"
+ Com_sprintf( filename, length, "models/players/%s%s/%s%s_%s.%s", charactersFolder, modelName, teamName, base, skinName, ext );
+ }
+ else {
+ // "models/players/characters/james/lower_lily.skin"
+ Com_sprintf( filename, length, "models/players/%s%s/%s_%s.%s", charactersFolder, modelName, base, skinName, ext );
+ }
+ }
+ if ( CG_FileExists( filename ) ) {
+ return qtrue;
+ }
+ if ( !teamName || !*teamName ) {
+ break;
+ }
+ }
+ // if tried the heads folder first
+ if ( charactersFolder[0] ) {
+ break;
+ }
+ charactersFolder = "characters/";
+ }
+
+ return qfalse;
+}
+
+/*
+==========================
+CG_FindClientHeadFile
+==========================
+*/
+static qboolean CG_FindClientHeadFile( char *filename, int length, clientInfo_t *ci, const char *teamName, const char *headModelName, const char *headSkinName, const char *base, const char *ext ) {
+ char *team, *headsFolder;
+ int i;
+
+ if ( cgs.gametype >= GT_TEAM ) {
+ switch ( ci->team ) {
+ case TEAM_BLUE: {
+ team = "blue";
+ break;
+ }
+ default: {
+ team = "red";
+ break;
+ }
+ }
+ }
+ else {
+ team = "default";
+ }
+
+ if ( headModelName[0] == '*' ) {
+ headsFolder = "heads/";
+ headModelName++;
+ }
+ else {
+ headsFolder = "";
+ }
+ while(1) {
+ for ( i = 0; i < 2; i++ ) {
+ if ( i == 0 && teamName && *teamName ) {
+ Com_sprintf( filename, length, "models/players/%s%s/%s/%s%s_%s.%s", headsFolder, headModelName, headSkinName, teamName, base, team, ext );
+ }
+ else {
+ Com_sprintf( filename, length, "models/players/%s%s/%s/%s_%s.%s", headsFolder, headModelName, headSkinName, base, team, ext );
+ }
+ if ( CG_FileExists( filename ) ) {
+ return qtrue;
+ }
+ if ( cgs.gametype >= GT_TEAM ) {
+ if ( i == 0 && teamName && *teamName ) {
+ Com_sprintf( filename, length, "models/players/%s%s/%s%s_%s.%s", headsFolder, headModelName, teamName, base, team, ext );
+ }
+ else {
+ Com_sprintf( filename, length, "models/players/%s%s/%s_%s.%s", headsFolder, headModelName, base, team, ext );
+ }
+ }
+ else {
+ if ( i == 0 && teamName && *teamName ) {
+ Com_sprintf( filename, length, "models/players/%s%s/%s%s_%s.%s", headsFolder, headModelName, teamName, base, headSkinName, ext );
+ }
+ else {
+ Com_sprintf( filename, length, "models/players/%s%s/%s_%s.%s", headsFolder, headModelName, base, headSkinName, ext );
+ }
+ }
+ if ( CG_FileExists( filename ) ) {
+ return qtrue;
+ }
+ if ( !teamName || !*teamName ) {
+ break;
+ }
+ }
+ // if tried the heads folder first
+ if ( headsFolder[0] ) {
+ break;
+ }
+ headsFolder = "heads/";
+ }
+
+ return qfalse;
+}
+
+/*
+==========================
+CG_RegisterClientSkin
+==========================
+*/
+static qboolean CG_RegisterClientSkin( clientInfo_t *ci, const char *teamName, const char *modelName, const char *skinName, const char *headModelName, const char *headSkinName ) {
+ char filename[MAX_QPATH];
+
+ /*
+ Com_sprintf( filename, sizeof( filename ), "models/players/%s/%slower_%s.skin", modelName, teamName, skinName );
+ ci->legsSkin = trap_R_RegisterSkin( filename );
+ if (!ci->legsSkin) {
+ Com_sprintf( filename, sizeof( filename ), "models/players/characters/%s/%slower_%s.skin", modelName, teamName, skinName );
+ ci->legsSkin = trap_R_RegisterSkin( filename );
+ if (!ci->legsSkin) {
+ Com_Printf( "Leg skin load failure: %s\n", filename );
+ }
+ }
+
+
+ Com_sprintf( filename, sizeof( filename ), "models/players/%s/%supper_%s.skin", modelName, teamName, skinName );
+ ci->torsoSkin = trap_R_RegisterSkin( filename );
+ if (!ci->torsoSkin) {
+ Com_sprintf( filename, sizeof( filename ), "models/players/characters/%s/%supper_%s.skin", modelName, teamName, skinName );
+ ci->torsoSkin = trap_R_RegisterSkin( filename );
+ if (!ci->torsoSkin) {
+ Com_Printf( "Torso skin load failure: %s\n", filename );
+ }
+ }
+ */
+ if ( CG_FindClientModelFile( filename, sizeof(filename), ci, teamName, modelName, skinName, "lower", "skin" ) ) {
+ ci->legsSkin = trap_R_RegisterSkin( filename );
+ }
+ if (!ci->legsSkin) {
+ Com_Printf( "Leg skin load failure: %s\n", filename );
+ }
+
+ if ( CG_FindClientModelFile( filename, sizeof(filename), ci, teamName, modelName, skinName, "upper", "skin" ) ) {
+ ci->torsoSkin = trap_R_RegisterSkin( filename );
+ }
+ if (!ci->torsoSkin) {
+ Com_Printf( "Torso skin load failure: %s\n", filename );
+ }
+
+ if ( CG_FindClientHeadFile( filename, sizeof(filename), ci, teamName, headModelName, headSkinName, "head", "skin" ) ) {
+ ci->headSkin = trap_R_RegisterSkin( filename );
+ }
+ if (!ci->headSkin) {
+ Com_Printf( "Head skin load failure: %s\n", filename );
+ }
+
+ // if any skins failed to load
+ if ( !ci->legsSkin || !ci->torsoSkin || !ci->headSkin ) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+/*
+==========================
+CG_RegisterClientModelname
+==========================
+*/
+static qboolean CG_RegisterClientModelname( clientInfo_t *ci, const char *modelName, const char *skinName, const char *headModelName, const char *headSkinName, const char *teamName ) {
+ char filename[MAX_QPATH*2];
+ const char *headName;
+ char newTeamName[MAX_QPATH*2];
+
+ if ( headModelName[0] == '\0' ) {
+ headName = modelName;
+ }
+ else {
+ headName = headModelName;
+ }
+ Com_sprintf( filename, sizeof( filename ), "models/players/%s/lower.md3", modelName );
+ ci->legsModel = trap_R_RegisterModel( filename );
+ if ( !ci->legsModel ) {
+ Com_sprintf( filename, sizeof( filename ), "models/players/characters/%s/lower.md3", modelName );
+ ci->legsModel = trap_R_RegisterModel( filename );
+ if ( !ci->legsModel ) {
+ Com_Printf( "Failed to load model file %s\n", filename );
+ return qfalse;
+ }
+ }
+
+ Com_sprintf( filename, sizeof( filename ), "models/players/%s/upper.md3", modelName );
+ ci->torsoModel = trap_R_RegisterModel( filename );
+ if ( !ci->torsoModel ) {
+ Com_sprintf( filename, sizeof( filename ), "models/players/characters/%s/upper.md3", modelName );
+ ci->torsoModel = trap_R_RegisterModel( filename );
+ if ( !ci->torsoModel ) {
+ Com_Printf( "Failed to load model file %s\n", filename );
+ return qfalse;
+ }
+ }
+
+ if( headName[0] == '*' ) {
+ Com_sprintf( filename, sizeof( filename ), "models/players/heads/%s/%s.md3", &headModelName[1], &headModelName[1] );
+ }
+ else {
+ Com_sprintf( filename, sizeof( filename ), "models/players/%s/head.md3", headName );
+ }
+ ci->headModel = trap_R_RegisterModel( filename );
+ // if the head model could not be found and we didn't load from the heads folder try to load from there
+ if ( !ci->headModel && headName[0] != '*' ) {
+ Com_sprintf( filename, sizeof( filename ), "models/players/heads/%s/%s.md3", headModelName, headModelName );
+ ci->headModel = trap_R_RegisterModel( filename );
+ }
+ if ( !ci->headModel ) {
+ Com_Printf( "Failed to load model file %s\n", filename );
+ return qfalse;
+ }
+
+ // if any skins failed to load, return failure
+ if ( !CG_RegisterClientSkin( ci, teamName, modelName, skinName, headName, headSkinName ) ) {
+ if ( teamName && *teamName) {
+ Com_Printf( "Failed to load skin file: %s : %s : %s, %s : %s\n", teamName, modelName, skinName, headName, headSkinName );
+ if( ci->team == TEAM_BLUE ) {
+ Com_sprintf(newTeamName, sizeof(newTeamName), "%s/", DEFAULT_BLUETEAM_NAME);
+ }
+ else {
+ Com_sprintf(newTeamName, sizeof(newTeamName), "%s/", DEFAULT_REDTEAM_NAME);
+ }
+ if ( !CG_RegisterClientSkin( ci, newTeamName, modelName, skinName, headName, headSkinName ) ) {
+ Com_Printf( "Failed to load skin file: %s : %s : %s, %s : %s\n", newTeamName, modelName, skinName, headName, headSkinName );
+ return qfalse;
+ }
+ } else {
+ Com_Printf( "Failed to load skin file: %s : %s, %s : %s\n", modelName, skinName, headName, headSkinName );
+ return qfalse;
+ }
+ }
+
+ // load the animations
+ Com_sprintf( filename, sizeof( filename ), "models/players/%s/animation.cfg", modelName );
+ if ( !CG_ParseAnimationFile( filename, ci ) ) {
+ Com_sprintf( filename, sizeof( filename ), "models/players/characters/%s/animation.cfg", modelName );
+ if ( !CG_ParseAnimationFile( filename, ci ) ) {
+ Com_Printf( "Failed to load animation file %s\n", filename );
+ return qfalse;
+ }
+ }
+
+ if ( CG_FindClientHeadFile( filename, sizeof(filename), ci, teamName, headName, headSkinName, "icon", "skin" ) ) {
+ ci->modelIcon = trap_R_RegisterShaderNoMip( filename );
+ }
+ else if ( CG_FindClientHeadFile( filename, sizeof(filename), ci, teamName, headName, headSkinName, "icon", "tga" ) ) {
+ ci->modelIcon = trap_R_RegisterShaderNoMip( filename );
+ }
+
+ if ( !ci->modelIcon ) {
+ return qfalse;
+ }
+
+ return qtrue;
+}
+
+/*
+====================
+CG_ColorFromString
+====================
+*/
+static void CG_ColorFromString( const char *v, vec3_t color ) {
+ int val;
+
+ VectorClear( color );
+
+ val = atoi( v );
+
+ if ( val < 1 || val > 7 ) {
+ VectorSet( color, 1, 1, 1 );
+ return;
+ }
+
+ if ( val & 1 ) {
+ color[2] = 1.0f;
+ }
+ if ( val & 2 ) {
+ color[1] = 1.0f;
+ }
+ if ( val & 4 ) {
+ color[0] = 1.0f;
+ }
+}
+
+/*
+===================
+CG_LoadClientInfo
+
+Load it now, taking the disk hits.
+This will usually be deferred to a safe time
+===================
+*/
+static void CG_LoadClientInfo( clientInfo_t *ci ) {
+ const char *dir, *fallback;
+ int i, modelloaded;
+ const char *s;
+ int clientNum;
+ char teamname[MAX_QPATH];
+
+ teamname[0] = 0;
+#ifdef MISSIONPACK
+ if( cgs.gametype >= GT_TEAM) {
+ if( ci->team == TEAM_BLUE ) {
+ Q_strncpyz(teamname, cg_blueTeamName.string, sizeof(teamname) );
+ } else {
+ Q_strncpyz(teamname, cg_redTeamName.string, sizeof(teamname) );
+ }
+ }
+ if( teamname[0] ) {
+ strcat( teamname, "/" );
+ }
+#endif
+ modelloaded = qtrue;
+ if ( !CG_RegisterClientModelname( ci, ci->modelName, ci->skinName, ci->headModelName, ci->headSkinName, teamname ) ) {
+ if ( cg_buildScript.integer ) {
+ CG_Error( "CG_RegisterClientModelname( %s, %s, %s, %s %s ) failed", ci->modelName, ci->skinName, ci->headModelName, ci->headSkinName, teamname );
+ }
+
+ // fall back to default team name
+ if( cgs.gametype >= GT_TEAM) {
+ // keep skin name
+ if( ci->team == TEAM_BLUE ) {
+ Q_strncpyz(teamname, DEFAULT_BLUETEAM_NAME, sizeof(teamname) );
+ } else {
+ Q_strncpyz(teamname, DEFAULT_REDTEAM_NAME, sizeof(teamname) );
+ }
+ if ( !CG_RegisterClientModelname( ci, DEFAULT_TEAM_MODEL, ci->skinName, DEFAULT_TEAM_HEAD, ci->skinName, teamname ) ) {
+ CG_Error( "DEFAULT_TEAM_MODEL / skin (%s/%s) failed to register", DEFAULT_TEAM_MODEL, ci->skinName );
+ }
+ } else {
+ if ( !CG_RegisterClientModelname( ci, DEFAULT_MODEL, "default", DEFAULT_MODEL, "default", teamname ) ) {
+ CG_Error( "DEFAULT_MODEL (%s) failed to register", DEFAULT_MODEL );
+ }
+ }
+ modelloaded = qfalse;
+ }
+
+ ci->newAnims = qfalse;
+ if ( ci->torsoModel ) {
+ orientation_t tag;
+ // if the torso model has the "tag_flag"
+ if ( trap_R_LerpTag( &tag, ci->torsoModel, 0, 0, 1, "tag_flag" ) ) {
+ ci->newAnims = qtrue;
+ }
+ }
+
+ // sounds
+ dir = ci->modelName;
+ fallback = (cgs.gametype >= GT_TEAM) ? DEFAULT_TEAM_MODEL : DEFAULT_MODEL;
+
+ for ( i = 0 ; i < MAX_CUSTOM_SOUNDS ; i++ ) {
+ s = cg_customSoundNames[i];
+ if ( !s ) {
+ break;
+ }
+ ci->sounds[i] = 0;
+ // if the model didn't load use the sounds of the default model
+ if (modelloaded) {
+ ci->sounds[i] = trap_S_RegisterSound( va("sound/player/%s/%s", dir, s + 1), qfalse );
+ }
+ if ( !ci->sounds[i] ) {
+ ci->sounds[i] = trap_S_RegisterSound( va("sound/player/%s/%s", fallback, s + 1), qfalse );
+ }
+ }
+
+ ci->deferred = qfalse;
+
+ // reset any existing players and bodies, because they might be in bad
+ // frames for this new model
+ clientNum = ci - cgs.clientinfo;
+ for ( i = 0 ; i < MAX_GENTITIES ; i++ ) {
+ if ( cg_entities[i].currentState.clientNum == clientNum
+ && cg_entities[i].currentState.eType == ET_PLAYER ) {
+ CG_ResetPlayerEntity( &cg_entities[i] );
+ }
+ }
+}
+
+/*
+======================
+CG_CopyClientInfoModel
+======================
+*/
+static void CG_CopyClientInfoModel( clientInfo_t *from, clientInfo_t *to ) {
+ VectorCopy( from->headOffset, to->headOffset );
+ to->footsteps = from->footsteps;
+ to->gender = from->gender;
+
+ to->legsModel = from->legsModel;
+ to->legsSkin = from->legsSkin;
+ to->torsoModel = from->torsoModel;
+ to->torsoSkin = from->torsoSkin;
+ to->headModel = from->headModel;
+ to->headSkin = from->headSkin;
+ to->modelIcon = from->modelIcon;
+
+ to->newAnims = from->newAnims;
+
+ memcpy( to->animations, from->animations, sizeof( to->animations ) );
+ memcpy( to->sounds, from->sounds, sizeof( to->sounds ) );
+}
+
+/*
+======================
+CG_ScanForExistingClientInfo
+======================
+*/
+static qboolean CG_ScanForExistingClientInfo( clientInfo_t *ci ) {
+ int i;
+ clientInfo_t *match;
+
+ for ( i = 0 ; i < cgs.maxclients ; i++ ) {
+ match = &cgs.clientinfo[ i ];
+ if ( !match->infoValid ) {
+ continue;
+ }
+ if ( match->deferred ) {
+ continue;
+ }
+ if ( !Q_stricmp( ci->modelName, match->modelName )
+ && !Q_stricmp( ci->skinName, match->skinName )
+ && !Q_stricmp( ci->headModelName, match->headModelName )
+ && !Q_stricmp( ci->headSkinName, match->headSkinName )
+ && !Q_stricmp( ci->blueTeam, match->blueTeam )
+ && !Q_stricmp( ci->redTeam, match->redTeam )
+ && (cgs.gametype < GT_TEAM || ci->team == match->team) ) {
+ // this clientinfo is identical, so use it's handles
+
+ ci->deferred = qfalse;
+
+ CG_CopyClientInfoModel( match, ci );
+
+ return qtrue;
+ }
+ }
+
+ // nothing matches, so defer the load
+ return qfalse;
+}
+
+/*
+======================
+CG_SetDeferredClientInfo
+
+We aren't going to load it now, so grab some other
+client's info to use until we have some spare time.
+======================
+*/
+static void CG_SetDeferredClientInfo( clientInfo_t *ci ) {
+ int i;
+ clientInfo_t *match;
+
+ // if someone else is already the same models and skins we
+ // can just load the client info
+ for ( i = 0 ; i < cgs.maxclients ; i++ ) {
+ match = &cgs.clientinfo[ i ];
+ if ( !match->infoValid || match->deferred ) {
+ continue;
+ }
+ if ( Q_stricmp( ci->skinName, match->skinName ) ||
+ Q_stricmp( ci->modelName, match->modelName ) ||
+// Q_stricmp( ci->headModelName, match->headModelName ) ||
+// Q_stricmp( ci->headSkinName, match->headSkinName ) ||
+ (cgs.gametype >= GT_TEAM && ci->team != match->team) ) {
+ continue;
+ }
+ // just load the real info cause it uses the same models and skins
+ CG_LoadClientInfo( ci );
+ return;
+ }
+
+ // if we are in teamplay, only grab a model if the skin is correct
+ if ( cgs.gametype >= GT_TEAM ) {
+ for ( i = 0 ; i < cgs.maxclients ; i++ ) {
+ match = &cgs.clientinfo[ i ];
+ if ( !match->infoValid || match->deferred ) {
+ continue;
+ }
+ if ( Q_stricmp( ci->skinName, match->skinName ) ||
+ (cgs.gametype >= GT_TEAM && ci->team != match->team) ) {
+ continue;
+ }
+ ci->deferred = qtrue;
+ CG_CopyClientInfoModel( match, ci );
+ return;
+ }
+ // load the full model, because we don't ever want to show
+ // an improper team skin. This will cause a hitch for the first
+ // player, when the second enters. Combat shouldn't be going on
+ // yet, so it shouldn't matter
+ CG_LoadClientInfo( ci );
+ return;
+ }
+
+ // find the first valid clientinfo and grab its stuff
+ for ( i = 0 ; i < cgs.maxclients ; i++ ) {
+ match = &cgs.clientinfo[ i ];
+ if ( !match->infoValid ) {
+ continue;
+ }
+
+ ci->deferred = qtrue;
+ CG_CopyClientInfoModel( match, ci );
+ return;
+ }
+
+ // we should never get here...
+ CG_Printf( "CG_SetDeferredClientInfo: no valid clients!\n" );
+
+ CG_LoadClientInfo( ci );
+}
+
+
+/*
+======================
+CG_NewClientInfo
+======================
+*/
+void CG_NewClientInfo( int clientNum ) {
+ clientInfo_t *ci;
+ clientInfo_t newInfo;
+ const char *configstring;
+ const char *v;
+ char *slash;
+
+ ci = &cgs.clientinfo[clientNum];
+
+ configstring = CG_ConfigString( clientNum + CS_PLAYERS );
+ if ( !configstring[0] ) {
+ memset( ci, 0, sizeof( *ci ) );
+ return; // player just left
+ }
+
+ // build into a temp buffer so the defer checks can use
+ // the old value
+ memset( &newInfo, 0, sizeof( newInfo ) );
+
+ // isolate the player's name
+ v = Info_ValueForKey(configstring, "n");
+ Q_strncpyz( newInfo.name, v, sizeof( newInfo.name ) );
+
+ // colors
+ v = Info_ValueForKey( configstring, "c1" );
+ CG_ColorFromString( v, newInfo.color1 );
+
+ v = Info_ValueForKey( configstring, "c2" );
+ CG_ColorFromString( v, newInfo.color2 );
+
+ // bot skill
+ v = Info_ValueForKey( configstring, "skill" );
+ newInfo.botSkill = atoi( v );
+
+ // handicap
+ v = Info_ValueForKey( configstring, "hc" );
+ newInfo.handicap = atoi( v );
+
+ // wins
+ v = Info_ValueForKey( configstring, "w" );
+ newInfo.wins = atoi( v );
+
+ // losses
+ v = Info_ValueForKey( configstring, "l" );
+ newInfo.losses = atoi( v );
+
+ // team
+ v = Info_ValueForKey( configstring, "t" );
+ newInfo.team = atoi( v );
+
+ // team task
+ v = Info_ValueForKey( configstring, "tt" );
+ newInfo.teamTask = atoi(v);
+
+ // team leader
+ v = Info_ValueForKey( configstring, "tl" );
+ newInfo.teamLeader = atoi(v);
+
+ v = Info_ValueForKey( configstring, "g_redteam" );
+ Q_strncpyz(newInfo.redTeam, v, MAX_TEAMNAME);
+
+ v = Info_ValueForKey( configstring, "g_blueteam" );
+ Q_strncpyz(newInfo.blueTeam, v, MAX_TEAMNAME);
+
+ // model
+ v = Info_ValueForKey( configstring, "model" );
+ if ( cg_forceModel.integer ) {
+ // forcemodel makes everyone use a single model
+ // to prevent load hitches
+ char modelStr[MAX_QPATH];
+ char *skin;
+
+ if( cgs.gametype >= GT_TEAM ) {
+ Q_strncpyz( newInfo.modelName, DEFAULT_TEAM_MODEL, sizeof( newInfo.modelName ) );
+ Q_strncpyz( newInfo.skinName, "default", sizeof( newInfo.skinName ) );
+ } else {
+ trap_Cvar_VariableStringBuffer( "model", modelStr, sizeof( modelStr ) );
+ if ( ( skin = strchr( modelStr, '/' ) ) == NULL) {
+ skin = "default";
+ } else {
+ *skin++ = 0;
+ }
+
+ Q_strncpyz( newInfo.skinName, skin, sizeof( newInfo.skinName ) );
+ Q_strncpyz( newInfo.modelName, modelStr, sizeof( newInfo.modelName ) );
+ }
+
+ if ( cgs.gametype >= GT_TEAM ) {
+ // keep skin name
+ slash = strchr( v, '/' );
+ if ( slash ) {
+ Q_strncpyz( newInfo.skinName, slash + 1, sizeof( newInfo.skinName ) );
+ }
+ }
+ } else {
+ Q_strncpyz( newInfo.modelName, v, sizeof( newInfo.modelName ) );
+
+ slash = strchr( newInfo.modelName, '/' );
+ if ( !slash ) {
+ // modelName didn not include a skin name
+ Q_strncpyz( newInfo.skinName, "default", sizeof( newInfo.skinName ) );
+ } else {
+ Q_strncpyz( newInfo.skinName, slash + 1, sizeof( newInfo.skinName ) );
+ // truncate modelName
+ *slash = 0;
+ }
+ }
+
+ // head model
+ v = Info_ValueForKey( configstring, "hmodel" );
+ if ( cg_forceModel.integer ) {
+ // forcemodel makes everyone use a single model
+ // to prevent load hitches
+ char modelStr[MAX_QPATH];
+ char *skin;
+
+ if( cgs.gametype >= GT_TEAM ) {
+ Q_strncpyz( newInfo.headModelName, DEFAULT_TEAM_MODEL, sizeof( newInfo.headModelName ) );
+ Q_strncpyz( newInfo.headSkinName, "default", sizeof( newInfo.headSkinName ) );
+ } else {
+ trap_Cvar_VariableStringBuffer( "headmodel", modelStr, sizeof( modelStr ) );
+ if ( ( skin = strchr( modelStr, '/' ) ) == NULL) {
+ skin = "default";
+ } else {
+ *skin++ = 0;
+ }
+
+ Q_strncpyz( newInfo.headSkinName, skin, sizeof( newInfo.headSkinName ) );
+ Q_strncpyz( newInfo.headModelName, modelStr, sizeof( newInfo.headModelName ) );
+ }
+
+ if ( cgs.gametype >= GT_TEAM ) {
+ // keep skin name
+ slash = strchr( v, '/' );
+ if ( slash ) {
+ Q_strncpyz( newInfo.headSkinName, slash + 1, sizeof( newInfo.headSkinName ) );
+ }
+ }
+ } else {
+ Q_strncpyz( newInfo.headModelName, v, sizeof( newInfo.headModelName ) );
+
+ slash = strchr( newInfo.headModelName, '/' );
+ if ( !slash ) {
+ // modelName didn not include a skin name
+ Q_strncpyz( newInfo.headSkinName, "default", sizeof( newInfo.headSkinName ) );
+ } else {
+ Q_strncpyz( newInfo.headSkinName, slash + 1, sizeof( newInfo.headSkinName ) );
+ // truncate modelName
+ *slash = 0;
+ }
+ }
+
+ // scan for an existing clientinfo that matches this modelname
+ // so we can avoid loading checks if possible
+ if ( !CG_ScanForExistingClientInfo( &newInfo ) ) {
+ qboolean forceDefer;
+
+ forceDefer = trap_MemoryRemaining() < 4000000;
+
+ // if we are defering loads, just have it pick the first valid
+ if ( forceDefer || (cg_deferPlayers.integer && !cg_buildScript.integer && !cg.loading ) ) {
+ // keep whatever they had if it won't violate team skins
+ CG_SetDeferredClientInfo( &newInfo );
+ // if we are low on memory, leave them with this model
+ if ( forceDefer ) {
+ CG_Printf( "Memory is low. Using deferred model.\n" );
+ newInfo.deferred = qfalse;
+ }
+ } else {
+ CG_LoadClientInfo( &newInfo );
+ }
+ }
+
+ // replace whatever was there with the new one
+ newInfo.infoValid = qtrue;
+ *ci = newInfo;
+}
+
+
+
+/*
+======================
+CG_LoadDeferredPlayers
+
+Called each frame when a player is dead
+and the scoreboard is up
+so deferred players can be loaded
+======================
+*/
+void CG_LoadDeferredPlayers( void ) {
+ int i;
+ clientInfo_t *ci;
+
+ // scan for a deferred player to load
+ for ( i = 0, ci = cgs.clientinfo ; i < cgs.maxclients ; i++, ci++ ) {
+ if ( ci->infoValid && ci->deferred ) {
+ // if we are low on memory, leave it deferred
+ if ( trap_MemoryRemaining() < 4000000 ) {
+ CG_Printf( "Memory is low. Using deferred model.\n" );
+ ci->deferred = qfalse;
+ continue;
+ }
+ CG_LoadClientInfo( ci );
+// break;
+ }
+ }
+}
+
+/*
+=============================================================================
+
+PLAYER ANIMATION
+
+=============================================================================
+*/
+
+
+/*
+===============
+CG_SetLerpFrameAnimation
+
+may include ANIM_TOGGLEBIT
+===============
+*/
+static void CG_SetLerpFrameAnimation( clientInfo_t *ci, lerpFrame_t *lf, int newAnimation ) {
+ animation_t *anim;
+
+ lf->animationNumber = newAnimation;
+ newAnimation &= ~ANIM_TOGGLEBIT;
+
+ if ( newAnimation < 0 || newAnimation >= MAX_TOTALANIMATIONS ) {
+ CG_Error( "Bad animation number: %i", newAnimation );
+ }
+
+ anim = &ci->animations[ newAnimation ];
+
+ lf->animation = anim;
+ lf->animationTime = lf->frameTime + anim->initialLerp;
+
+ if ( cg_debugAnim.integer ) {
+ CG_Printf( "Anim: %i\n", newAnimation );
+ }
+}
+
+/*
+===============
+CG_RunLerpFrame
+
+Sets cg.snap, cg.oldFrame, and cg.backlerp
+cg.time should be between oldFrameTime and frameTime after exit
+===============
+*/
+static void CG_RunLerpFrame( clientInfo_t *ci, lerpFrame_t *lf, int newAnimation, float speedScale ) {
+ int f, numFrames;
+ animation_t *anim;
+
+ // debugging tool to get no animations
+ if ( cg_animSpeed.integer == 0 ) {
+ lf->oldFrame = lf->frame = lf->backlerp = 0;
+ return;
+ }
+
+ // see if the animation sequence is switching
+ if ( newAnimation != lf->animationNumber || !lf->animation ) {
+ CG_SetLerpFrameAnimation( ci, lf, newAnimation );
+ }
+
+ // if we have passed the current frame, move it to
+ // oldFrame and calculate a new frame
+ if ( cg.time >= lf->frameTime ) {
+ lf->oldFrame = lf->frame;
+ lf->oldFrameTime = lf->frameTime;
+
+ // get the next frame based on the animation
+ anim = lf->animation;
+ if ( !anim->frameLerp ) {
+ return; // shouldn't happen
+ }
+ if ( cg.time < lf->animationTime ) {
+ lf->frameTime = lf->animationTime; // initial lerp
+ } else {
+ lf->frameTime = lf->oldFrameTime + anim->frameLerp;
+ }
+ f = ( lf->frameTime - lf->animationTime ) / anim->frameLerp;
+ f *= speedScale; // adjust for haste, etc
+
+ numFrames = anim->numFrames;
+ if (anim->flipflop) {
+ numFrames *= 2;
+ }
+ if ( f >= numFrames ) {
+ f -= numFrames;
+ if ( anim->loopFrames ) {
+ f %= anim->loopFrames;
+ f += anim->numFrames - anim->loopFrames;
+ } else {
+ f = numFrames - 1;
+ // the animation is stuck at the end, so it
+ // can immediately transition to another sequence
+ lf->frameTime = cg.time;
+ }
+ }
+ if ( anim->reversed ) {
+ lf->frame = anim->firstFrame + anim->numFrames - 1 - f;
+ }
+ else if (anim->flipflop && f>=anim->numFrames) {
+ lf->frame = anim->firstFrame + anim->numFrames - 1 - (f%anim->numFrames);
+ }
+ else {
+ lf->frame = anim->firstFrame + f;
+ }
+ if ( cg.time > lf->frameTime ) {
+ lf->frameTime = cg.time;
+ if ( cg_debugAnim.integer ) {
+ CG_Printf( "Clamp lf->frameTime\n");
+ }
+ }
+ }
+
+ if ( lf->frameTime > cg.time + 200 ) {
+ lf->frameTime = cg.time;
+ }
+
+ if ( lf->oldFrameTime > cg.time ) {
+ lf->oldFrameTime = cg.time;
+ }
+ // calculate current lerp value
+ if ( lf->frameTime == lf->oldFrameTime ) {
+ lf->backlerp = 0;
+ } else {
+ lf->backlerp = 1.0 - (float)( cg.time - lf->oldFrameTime ) / ( lf->frameTime - lf->oldFrameTime );
+ }
+}
+
+
+/*
+===============
+CG_ClearLerpFrame
+===============
+*/
+static void CG_ClearLerpFrame( clientInfo_t *ci, lerpFrame_t *lf, int animationNumber ) {
+ lf->frameTime = lf->oldFrameTime = cg.time;
+ CG_SetLerpFrameAnimation( ci, lf, animationNumber );
+ lf->oldFrame = lf->frame = lf->animation->firstFrame;
+}
+
+
+/*
+===============
+CG_PlayerAnimation
+===============
+*/
+static void CG_PlayerAnimation( centity_t *cent, int *legsOld, int *legs, float *legsBackLerp,
+ int *torsoOld, int *torso, float *torsoBackLerp ) {
+ clientInfo_t *ci;
+ int clientNum;
+ float speedScale;
+
+ clientNum = cent->currentState.clientNum;
+
+ if ( cg_noPlayerAnims.integer ) {
+ *legsOld = *legs = *torsoOld = *torso = 0;
+ return;
+ }
+
+ if ( cent->currentState.powerups & ( 1 << PW_HASTE ) ) {
+ speedScale = 1.5;
+ } else {
+ speedScale = 1;
+ }
+
+ ci = &cgs.clientinfo[ clientNum ];
+
+ // do the shuffle turn frames locally
+ if ( cent->pe.legs.yawing && ( cent->currentState.legsAnim & ~ANIM_TOGGLEBIT ) == LEGS_IDLE ) {
+ CG_RunLerpFrame( ci, &cent->pe.legs, LEGS_TURN, speedScale );
+ } else {
+ CG_RunLerpFrame( ci, &cent->pe.legs, cent->currentState.legsAnim, speedScale );
+ }
+
+ *legsOld = cent->pe.legs.oldFrame;
+ *legs = cent->pe.legs.frame;
+ *legsBackLerp = cent->pe.legs.backlerp;
+
+ CG_RunLerpFrame( ci, &cent->pe.torso, cent->currentState.torsoAnim, speedScale );
+
+ *torsoOld = cent->pe.torso.oldFrame;
+ *torso = cent->pe.torso.frame;
+ *torsoBackLerp = cent->pe.torso.backlerp;
+}
+
+/*
+=============================================================================
+
+PLAYER ANGLES
+
+=============================================================================
+*/
+
+/*
+==================
+CG_SwingAngles
+==================
+*/
+static void CG_SwingAngles( float destination, float swingTolerance, float clampTolerance,
+ float speed, float *angle, qboolean *swinging ) {
+ float swing;
+ float move;
+ float scale;
+
+ if ( !*swinging ) {
+ // see if a swing should be started
+ swing = AngleSubtract( *angle, destination );
+ if ( swing > swingTolerance || swing < -swingTolerance ) {
+ *swinging = qtrue;
+ }
+ }
+
+ if ( !*swinging ) {
+ return;
+ }
+
+ // modify the speed depending on the delta
+ // so it doesn't seem so linear
+ swing = AngleSubtract( destination, *angle );
+ scale = fabs( swing );
+ if ( scale < swingTolerance * 0.5 ) {
+ scale = 0.5;
+ } else if ( scale < swingTolerance ) {
+ scale = 1.0;
+ } else {
+ scale = 2.0;
+ }
+
+ // swing towards the destination angle
+ if ( swing >= 0 ) {
+ move = cg.frametime * scale * speed;
+ if ( move >= swing ) {
+ move = swing;
+ *swinging = qfalse;
+ }
+ *angle = AngleMod( *angle + move );
+ } else if ( swing < 0 ) {
+ move = cg.frametime * scale * -speed;
+ if ( move <= swing ) {
+ move = swing;
+ *swinging = qfalse;
+ }
+ *angle = AngleMod( *angle + move );
+ }
+
+ // clamp to no more than tolerance
+ swing = AngleSubtract( destination, *angle );
+ if ( swing > clampTolerance ) {
+ *angle = AngleMod( destination - (clampTolerance - 1) );
+ } else if ( swing < -clampTolerance ) {
+ *angle = AngleMod( destination + (clampTolerance - 1) );
+ }
+}
+
+/*
+=================
+CG_AddPainTwitch
+=================
+*/
+static void CG_AddPainTwitch( centity_t *cent, vec3_t torsoAngles ) {
+ int t;
+ float f;
+
+ t = cg.time - cent->pe.painTime;
+ if ( t >= PAIN_TWITCH_TIME ) {
+ return;
+ }
+
+ f = 1.0 - (float)t / PAIN_TWITCH_TIME;
+
+ if ( cent->pe.painDirection ) {
+ torsoAngles[ROLL] += 20 * f;
+ } else {
+ torsoAngles[ROLL] -= 20 * f;
+ }
+}
+
+
+/*
+===============
+CG_PlayerAngles
+
+Handles seperate torso motion
+
+ legs pivot based on direction of movement
+
+ head always looks exactly at cent->lerpAngles
+
+ if motion < 20 degrees, show in head only
+ if < 45 degrees, also show in torso
+===============
+*/
+static void CG_PlayerAngles( centity_t *cent, vec3_t legs[3], vec3_t torso[3], vec3_t head[3] ) {
+ vec3_t legsAngles, torsoAngles, headAngles;
+ float dest;
+ static int movementOffsets[8] = { 0, 22, 45, -22, 0, 22, -45, -22 };
+ vec3_t velocity;
+ float speed;
+ int dir, clientNum;
+ clientInfo_t *ci;
+
+ VectorCopy( cent->lerpAngles, headAngles );
+ headAngles[YAW] = AngleMod( headAngles[YAW] );
+ VectorClear( legsAngles );
+ VectorClear( torsoAngles );
+
+ // --------- yaw -------------
+
+ // allow yaw to drift a bit
+ if ( ( cent->currentState.legsAnim & ~ANIM_TOGGLEBIT ) != LEGS_IDLE
+ || ( cent->currentState.torsoAnim & ~ANIM_TOGGLEBIT ) != TORSO_STAND ) {
+ // if not standing still, always point all in the same direction
+ cent->pe.torso.yawing = qtrue; // always center
+ cent->pe.torso.pitching = qtrue; // always center
+ cent->pe.legs.yawing = qtrue; // always center
+ }
+
+ // adjust legs for movement dir
+ if ( cent->currentState.eFlags & EF_DEAD ) {
+ // don't let dead bodies twitch
+ dir = 0;
+ } else {
+ dir = cent->currentState.angles2[YAW];
+ if ( dir < 0 || dir > 7 ) {
+ CG_Error( "Bad player movement angle" );
+ }
+ }
+ legsAngles[YAW] = headAngles[YAW] + movementOffsets[ dir ];
+ torsoAngles[YAW] = headAngles[YAW] + 0.25 * movementOffsets[ dir ];
+
+ // torso
+ CG_SwingAngles( torsoAngles[YAW], 25, 90, cg_swingSpeed.value, &cent->pe.torso.yawAngle, &cent->pe.torso.yawing );
+ CG_SwingAngles( legsAngles[YAW], 40, 90, cg_swingSpeed.value, &cent->pe.legs.yawAngle, &cent->pe.legs.yawing );
+
+ torsoAngles[YAW] = cent->pe.torso.yawAngle;
+ legsAngles[YAW] = cent->pe.legs.yawAngle;
+
+
+ // --------- pitch -------------
+
+ // only show a fraction of the pitch angle in the torso
+ if ( headAngles[PITCH] > 180 ) {
+ dest = (-360 + headAngles[PITCH]) * 0.75f;
+ } else {
+ dest = headAngles[PITCH] * 0.75f;
+ }
+ CG_SwingAngles( dest, 15, 30, 0.1f, &cent->pe.torso.pitchAngle, &cent->pe.torso.pitching );
+ torsoAngles[PITCH] = cent->pe.torso.pitchAngle;
+
+ //
+ clientNum = cent->currentState.clientNum;
+ if ( clientNum >= 0 && clientNum < MAX_CLIENTS ) {
+ ci = &cgs.clientinfo[ clientNum ];
+ if ( ci->fixedtorso ) {
+ torsoAngles[PITCH] = 0.0f;
+ }
+ }
+
+ // --------- roll -------------
+
+
+ // lean towards the direction of travel
+ VectorCopy( cent->currentState.pos.trDelta, velocity );
+ speed = VectorNormalize( velocity );
+ if ( speed ) {
+ vec3_t axis[3];
+ float side;
+
+ speed *= 0.05f;
+
+ AnglesToAxis( legsAngles, axis );
+ side = speed * DotProduct( velocity, axis[1] );
+ legsAngles[ROLL] -= side;
+
+ side = speed * DotProduct( velocity, axis[0] );
+ legsAngles[PITCH] += side;
+ }
+
+ //
+ clientNum = cent->currentState.clientNum;
+ if ( clientNum >= 0 && clientNum < MAX_CLIENTS ) {
+ ci = &cgs.clientinfo[ clientNum ];
+ if ( ci->fixedlegs ) {
+ legsAngles[YAW] = torsoAngles[YAW];
+ legsAngles[PITCH] = 0.0f;
+ legsAngles[ROLL] = 0.0f;
+ }
+ }
+
+ // pain twitch
+ CG_AddPainTwitch( cent, torsoAngles );
+
+ // pull the angles back out of the hierarchial chain
+ AnglesSubtract( headAngles, torsoAngles, headAngles );
+ AnglesSubtract( torsoAngles, legsAngles, torsoAngles );
+ AnglesToAxis( legsAngles, legs );
+ AnglesToAxis( torsoAngles, torso );
+ AnglesToAxis( headAngles, head );
+}
+
+
+//==========================================================================
+
+/*
+===============
+CG_HasteTrail
+===============
+*/
+static void CG_HasteTrail( centity_t *cent ) {
+ localEntity_t *smoke;
+ vec3_t origin;
+ int anim;
+
+ if ( cent->trailTime > cg.time ) {
+ return;
+ }
+ anim = cent->pe.legs.animationNumber & ~ANIM_TOGGLEBIT;
+ if ( anim != LEGS_RUN && anim != LEGS_BACK ) {
+ return;
+ }
+
+ cent->trailTime += 100;
+ if ( cent->trailTime < cg.time ) {
+ cent->trailTime = cg.time;
+ }
+
+ VectorCopy( cent->lerpOrigin, origin );
+ origin[2] -= 16;
+
+ smoke = CG_SmokePuff( origin, vec3_origin,
+ 8,
+ 1, 1, 1, 1,
+ 500,
+ cg.time,
+ 0,
+ 0,
+ cgs.media.hastePuffShader );
+
+ // use the optimized local entity add
+ smoke->leType = LE_SCALE_FADE;
+}
+
+#ifdef MISSIONPACK
+/*
+===============
+CG_BreathPuffs
+===============
+*/
+static void CG_BreathPuffs( centity_t *cent, refEntity_t *head) {
+ clientInfo_t *ci;
+ vec3_t up, origin;
+ int contents;
+
+ ci = &cgs.clientinfo[ cent->currentState.number ];
+
+ if (!cg_enableBreath.integer) {
+ return;
+ }
+ if ( cent->currentState.number == cg.snap->ps.clientNum && !cg.renderingThirdPerson) {
+ return;
+ }
+ if ( cent->currentState.eFlags & EF_DEAD ) {
+ return;
+ }
+ contents = trap_CM_PointContents( head->origin, 0 );
+ if ( contents & ( CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA ) ) {
+ return;
+ }
+ if ( ci->breathPuffTime > cg.time ) {
+ return;
+ }
+
+ VectorSet( up, 0, 0, 8 );
+ VectorMA(head->origin, 8, head->axis[0], origin);
+ VectorMA(origin, -4, head->axis[2], origin);
+ CG_SmokePuff( origin, up, 16, 1, 1, 1, 0.66f, 1500, cg.time, cg.time + 400, LEF_PUFF_DONT_SCALE, cgs.media.shotgunSmokePuffShader );
+ ci->breathPuffTime = cg.time + 2000;
+}
+
+/*
+===============
+CG_DustTrail
+===============
+*/
+static void CG_DustTrail( centity_t *cent ) {
+ int anim;
+ localEntity_t *dust;
+ vec3_t end, vel;
+ trace_t tr;
+
+ if (!cg_enableDust.integer)
+ return;
+
+ if ( cent->dustTrailTime > cg.time ) {
+ return;
+ }
+
+ anim = cent->pe.legs.animationNumber & ~ANIM_TOGGLEBIT;
+ if ( anim != LEGS_LANDB && anim != LEGS_LAND ) {
+ return;
+ }
+
+ cent->dustTrailTime += 40;
+ if ( cent->dustTrailTime < cg.time ) {
+ cent->dustTrailTime = cg.time;
+ }
+
+ VectorCopy(cent->currentState.pos.trBase, end);
+ end[2] -= 64;
+ CG_Trace( &tr, cent->currentState.pos.trBase, NULL, NULL, end, cent->currentState.number, MASK_PLAYERSOLID );
+
+ if ( !(tr.surfaceFlags & SURF_DUST) )
+ return;
+
+ VectorCopy( cent->currentState.pos.trBase, end );
+ end[2] -= 16;
+
+ VectorSet(vel, 0, 0, -30);
+ dust = CG_SmokePuff( end, vel,
+ 24,
+ .8f, .8f, 0.7f, 0.33f,
+ 500,
+ cg.time,
+ 0,
+ 0,
+ cgs.media.dustPuffShader );
+}
+
+#endif
+
+/*
+===============
+CG_TrailItem
+===============
+*/
+static void CG_TrailItem( centity_t *cent, qhandle_t hModel ) {
+ refEntity_t ent;
+ vec3_t angles;
+ vec3_t axis[3];
+
+ VectorCopy( cent->lerpAngles, angles );
+ angles[PITCH] = 0;
+ angles[ROLL] = 0;
+ AnglesToAxis( angles, axis );
+
+ memset( &ent, 0, sizeof( ent ) );
+ VectorMA( cent->lerpOrigin, -16, axis[0], ent.origin );
+ ent.origin[2] += 16;
+ angles[YAW] += 90;
+ AnglesToAxis( angles, ent.axis );
+
+ ent.hModel = hModel;
+ trap_R_AddRefEntityToScene( &ent );
+}
+
+
+/*
+===============
+CG_PlayerFlag
+===============
+*/
+static void CG_PlayerFlag( centity_t *cent, qhandle_t hSkin, refEntity_t *torso ) {
+ clientInfo_t *ci;
+ refEntity_t pole;
+ refEntity_t flag;
+ vec3_t angles, dir;
+ int legsAnim, flagAnim, updateangles;
+ float angle, d;
+
+ // show the flag pole model
+ memset( &pole, 0, sizeof(pole) );
+ pole.hModel = cgs.media.flagPoleModel;
+ VectorCopy( torso->lightingOrigin, pole.lightingOrigin );
+ pole.shadowPlane = torso->shadowPlane;
+ pole.renderfx = torso->renderfx;
+ CG_PositionEntityOnTag( &pole, torso, torso->hModel, "tag_flag" );
+ trap_R_AddRefEntityToScene( &pole );
+
+ // show the flag model
+ memset( &flag, 0, sizeof(flag) );
+ flag.hModel = cgs.media.flagFlapModel;
+ flag.customSkin = hSkin;
+ VectorCopy( torso->lightingOrigin, flag.lightingOrigin );
+ flag.shadowPlane = torso->shadowPlane;
+ flag.renderfx = torso->renderfx;
+
+ VectorClear(angles);
+
+ updateangles = qfalse;
+ legsAnim = cent->currentState.legsAnim & ~ANIM_TOGGLEBIT;
+ if( legsAnim == LEGS_IDLE || legsAnim == LEGS_IDLECR ) {
+ flagAnim = FLAG_STAND;
+ } else if ( legsAnim == LEGS_WALK || legsAnim == LEGS_WALKCR ) {
+ flagAnim = FLAG_STAND;
+ updateangles = qtrue;
+ } else {
+ flagAnim = FLAG_RUN;
+ updateangles = qtrue;
+ }
+
+ if ( updateangles ) {
+
+ VectorCopy( cent->currentState.pos.trDelta, dir );
+ // add gravity
+ dir[2] += 100;
+ VectorNormalize( dir );
+ d = DotProduct(pole.axis[2], dir);
+ // if there is anough movement orthogonal to the flag pole
+ if (fabs(d) < 0.9) {
+ //
+ d = DotProduct(pole.axis[0], dir);
+ if (d > 1.0f) {
+ d = 1.0f;
+ }
+ else if (d < -1.0f) {
+ d = -1.0f;
+ }
+ angle = acos(d);
+
+ d = DotProduct(pole.axis[1], dir);
+ if (d < 0) {
+ angles[YAW] = 360 - angle * 180 / M_PI;
+ }
+ else {
+ angles[YAW] = angle * 180 / M_PI;
+ }
+ if (angles[YAW] < 0)
+ angles[YAW] += 360;
+ if (angles[YAW] > 360)
+ angles[YAW] -= 360;
+
+ //vectoangles( cent->currentState.pos.trDelta, tmpangles );
+ //angles[YAW] = tmpangles[YAW] + 45 - cent->pe.torso.yawAngle;
+ // change the yaw angle
+ CG_SwingAngles( angles[YAW], 25, 90, 0.15f, &cent->pe.flag.yawAngle, &cent->pe.flag.yawing );
+ }
+
+ /*
+ d = DotProduct(pole.axis[2], dir);
+ angle = Q_acos(d);
+
+ d = DotProduct(pole.axis[1], dir);
+ if (d < 0) {
+ angle = 360 - angle * 180 / M_PI;
+ }
+ else {
+ angle = angle * 180 / M_PI;
+ }
+ if (angle > 340 && angle < 20) {
+ flagAnim = FLAG_RUNUP;
+ }
+ if (angle > 160 && angle < 200) {
+ flagAnim = FLAG_RUNDOWN;
+ }
+ */
+ }
+
+ // set the yaw angle
+ angles[YAW] = cent->pe.flag.yawAngle;
+ // lerp the flag animation frames
+ ci = &cgs.clientinfo[ cent->currentState.clientNum ];
+ CG_RunLerpFrame( ci, &cent->pe.flag, flagAnim, 1 );
+ flag.oldframe = cent->pe.flag.oldFrame;
+ flag.frame = cent->pe.flag.frame;
+ flag.backlerp = cent->pe.flag.backlerp;
+
+ AnglesToAxis( angles, flag.axis );
+ CG_PositionRotatedEntityOnTag( &flag, &pole, pole.hModel, "tag_flag" );
+
+ trap_R_AddRefEntityToScene( &flag );
+}
+
+
+#ifdef MISSIONPACK // bk001204
+/*
+===============
+CG_PlayerTokens
+===============
+*/
+static void CG_PlayerTokens( centity_t *cent, int renderfx ) {
+ int tokens, i, j;
+ float angle;
+ refEntity_t ent;
+ vec3_t dir, origin;
+ skulltrail_t *trail;
+ trail = &cg.skulltrails[cent->currentState.number];
+ tokens = cent->currentState.generic1;
+ if ( !tokens ) {
+ trail->numpositions = 0;
+ return;
+ }
+
+ if ( tokens > MAX_SKULLTRAIL ) {
+ tokens = MAX_SKULLTRAIL;
+ }
+
+ // add skulls if there are more than last time
+ for (i = 0; i < tokens - trail->numpositions; i++) {
+ for (j = trail->numpositions; j > 0; j--) {
+ VectorCopy(trail->positions[j-1], trail->positions[j]);
+ }
+ VectorCopy(cent->lerpOrigin, trail->positions[0]);
+ }
+ trail->numpositions = tokens;
+
+ // move all the skulls along the trail
+ VectorCopy(cent->lerpOrigin, origin);
+ for (i = 0; i < trail->numpositions; i++) {
+ VectorSubtract(trail->positions[i], origin, dir);
+ if (VectorNormalize(dir) > 30) {
+ VectorMA(origin, 30, dir, trail->positions[i]);
+ }
+ VectorCopy(trail->positions[i], origin);
+ }
+
+ memset( &ent, 0, sizeof( ent ) );
+ if( cgs.clientinfo[ cent->currentState.clientNum ].team == TEAM_BLUE ) {
+ ent.hModel = cgs.media.redCubeModel;
+ } else {
+ ent.hModel = cgs.media.blueCubeModel;
+ }
+ ent.renderfx = renderfx;
+
+ VectorCopy(cent->lerpOrigin, origin);
+ for (i = 0; i < trail->numpositions; i++) {
+ VectorSubtract(origin, trail->positions[i], ent.axis[0]);
+ ent.axis[0][2] = 0;
+ VectorNormalize(ent.axis[0]);
+ VectorSet(ent.axis[2], 0, 0, 1);
+ CrossProduct(ent.axis[0], ent.axis[2], ent.axis[1]);
+
+ VectorCopy(trail->positions[i], ent.origin);
+ angle = (((cg.time + 500 * MAX_SKULLTRAIL - 500 * i) / 16) & 255) * (M_PI * 2) / 255;
+ ent.origin[2] += sin(angle) * 10;
+ trap_R_AddRefEntityToScene( &ent );
+ VectorCopy(trail->positions[i], origin);
+ }
+}
+#endif
+
+
+/*
+===============
+CG_PlayerPowerups
+===============
+*/
+static void CG_PlayerPowerups( centity_t *cent, refEntity_t *torso ) {
+ int powerups;
+ clientInfo_t *ci;
+
+ powerups = cent->currentState.powerups;
+ if ( !powerups ) {
+ return;
+ }
+
+ // quad gives a dlight
+ if ( powerups & ( 1 << PW_QUAD ) ) {
+ trap_R_AddLightToScene( cent->lerpOrigin, 200 + (rand()&31), 0.2f, 0.2f, 1 );
+ }
+
+ // flight plays a looped sound
+ if ( powerups & ( 1 << PW_FLIGHT ) ) {
+ trap_S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin, cgs.media.flightSound );
+ }
+
+ ci = &cgs.clientinfo[ cent->currentState.clientNum ];
+ // redflag
+ if ( powerups & ( 1 << PW_REDFLAG ) ) {
+ if (ci->newAnims) {
+ CG_PlayerFlag( cent, cgs.media.redFlagFlapSkin, torso );
+ }
+ else {
+ CG_TrailItem( cent, cgs.media.redFlagModel );
+ }
+ trap_R_AddLightToScene( cent->lerpOrigin, 200 + (rand()&31), 1.0, 0.2f, 0.2f );
+ }
+
+ // blueflag
+ if ( powerups & ( 1 << PW_BLUEFLAG ) ) {
+ if (ci->newAnims){
+ CG_PlayerFlag( cent, cgs.media.blueFlagFlapSkin, torso );
+ }
+ else {
+ CG_TrailItem( cent, cgs.media.blueFlagModel );
+ }
+ trap_R_AddLightToScene( cent->lerpOrigin, 200 + (rand()&31), 0.2f, 0.2f, 1.0 );
+ }
+
+ // neutralflag
+ if ( powerups & ( 1 << PW_NEUTRALFLAG ) ) {
+ if (ci->newAnims) {
+ CG_PlayerFlag( cent, cgs.media.neutralFlagFlapSkin, torso );
+ }
+ else {
+ CG_TrailItem( cent, cgs.media.neutralFlagModel );
+ }
+ trap_R_AddLightToScene( cent->lerpOrigin, 200 + (rand()&31), 1.0, 1.0, 1.0 );
+ }
+
+ // haste leaves smoke trails
+ if ( powerups & ( 1 << PW_HASTE ) ) {
+ CG_HasteTrail( cent );
+ }
+}
+
+
+/*
+===============
+CG_PlayerFloatSprite
+
+Float a sprite over the player's head
+===============
+*/
+static void CG_PlayerFloatSprite( centity_t *cent, qhandle_t shader ) {
+ int rf;
+ refEntity_t ent;
+
+ if ( cent->currentState.number == cg.snap->ps.clientNum && !cg.renderingThirdPerson ) {
+ rf = RF_THIRD_PERSON; // only show in mirrors
+ } else {
+ rf = 0;
+ }
+
+ memset( &ent, 0, sizeof( ent ) );
+ VectorCopy( cent->lerpOrigin, ent.origin );
+ ent.origin[2] += 48;
+ ent.reType = RT_SPRITE;
+ ent.customShader = shader;
+ ent.radius = 10;
+ ent.renderfx = rf;
+ ent.shaderRGBA[0] = 255;
+ ent.shaderRGBA[1] = 255;
+ ent.shaderRGBA[2] = 255;
+ ent.shaderRGBA[3] = 255;
+ trap_R_AddRefEntityToScene( &ent );
+}
+
+
+
+/*
+===============
+CG_PlayerSprites
+
+Float sprites over the player's head
+===============
+*/
+static void CG_PlayerSprites( centity_t *cent ) {
+ int team;
+
+ if ( cent->currentState.eFlags & EF_CONNECTION ) {
+ CG_PlayerFloatSprite( cent, cgs.media.connectionShader );
+ return;
+ }
+
+ if ( cent->currentState.eFlags & EF_TALK ) {
+ CG_PlayerFloatSprite( cent, cgs.media.balloonShader );
+ return;
+ }
+
+ if ( cent->currentState.eFlags & EF_AWARD_IMPRESSIVE ) {
+ CG_PlayerFloatSprite( cent, cgs.media.medalImpressive );
+ return;
+ }
+
+ if ( cent->currentState.eFlags & EF_AWARD_EXCELLENT ) {
+ CG_PlayerFloatSprite( cent, cgs.media.medalExcellent );
+ return;
+ }
+
+ if ( cent->currentState.eFlags & EF_AWARD_GAUNTLET ) {
+ CG_PlayerFloatSprite( cent, cgs.media.medalGauntlet );
+ return;
+ }
+
+ if ( cent->currentState.eFlags & EF_AWARD_DEFEND ) {
+ CG_PlayerFloatSprite( cent, cgs.media.medalDefend );
+ return;
+ }
+
+ if ( cent->currentState.eFlags & EF_AWARD_ASSIST ) {
+ CG_PlayerFloatSprite( cent, cgs.media.medalAssist );
+ return;
+ }
+
+ if ( cent->currentState.eFlags & EF_AWARD_CAP ) {
+ CG_PlayerFloatSprite( cent, cgs.media.medalCapture );
+ return;
+ }
+
+ team = cgs.clientinfo[ cent->currentState.clientNum ].team;
+ if ( !(cent->currentState.eFlags & EF_DEAD) &&
+ cg.snap->ps.persistant[PERS_TEAM] == team &&
+ cgs.gametype >= GT_TEAM) {
+ if (cg_drawFriend.integer) {
+ CG_PlayerFloatSprite( cent, cgs.media.friendShader );
+ }
+ return;
+ }
+}
+
+/*
+===============
+CG_PlayerShadow
+
+Returns the Z component of the surface being shadowed
+
+ should it return a full plane instead of a Z?
+===============
+*/
+#define SHADOW_DISTANCE 128
+static qboolean CG_PlayerShadow( centity_t *cent, float *shadowPlane ) {
+ vec3_t end, mins = {-15, -15, 0}, maxs = {15, 15, 2};
+ trace_t trace;
+ float alpha;
+
+ *shadowPlane = 0;
+
+ if ( cg_shadows.integer == 0 ) {
+ return qfalse;
+ }
+
+ // no shadows when invisible
+ if ( cent->currentState.powerups & ( 1 << PW_INVIS ) ) {
+ return qfalse;
+ }
+
+ // send a trace down from the player to the ground
+ VectorCopy( cent->lerpOrigin, end );
+ end[2] -= SHADOW_DISTANCE;
+
+ trap_CM_BoxTrace( &trace, cent->lerpOrigin, end, mins, maxs, 0, MASK_PLAYERSOLID );
+
+ // no shadow if too high
+ if ( trace.fraction == 1.0 || trace.startsolid || trace.allsolid ) {
+ return qfalse;
+ }
+
+ *shadowPlane = trace.endpos[2] + 1;
+
+ if ( cg_shadows.integer != 1 ) { // no mark for stencil or projection shadows
+ return qtrue;
+ }
+
+ // fade the shadow out with height
+ alpha = 1.0 - trace.fraction;
+
+ // bk0101022 - hack / FPE - bogus planes?
+ //assert( DotProduct( trace.plane.normal, trace.plane.normal ) != 0.0f )
+
+ // add the mark as a temporary, so it goes directly to the renderer
+ // without taking a spot in the cg_marks array
+ CG_ImpactMark( cgs.media.shadowMarkShader, trace.endpos, trace.plane.normal,
+ cent->pe.legs.yawAngle, alpha,alpha,alpha,1, qfalse, 24, qtrue );
+
+ return qtrue;
+}
+
+
+/*
+===============
+CG_PlayerSplash
+
+Draw a mark at the water surface
+===============
+*/
+static void CG_PlayerSplash( centity_t *cent ) {
+ vec3_t start, end;
+ trace_t trace;
+ int contents;
+ polyVert_t verts[4];
+
+ if ( !cg_shadows.integer ) {
+ return;
+ }
+
+ VectorCopy( cent->lerpOrigin, end );
+ end[2] -= 24;
+
+ // if the feet aren't in liquid, don't make a mark
+ // this won't handle moving water brushes, but they wouldn't draw right anyway...
+ contents = trap_CM_PointContents( end, 0 );
+ if ( !( contents & ( CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA ) ) ) {
+ return;
+ }
+
+ VectorCopy( cent->lerpOrigin, start );
+ start[2] += 32;
+
+ // if the head isn't out of liquid, don't make a mark
+ contents = trap_CM_PointContents( start, 0 );
+ if ( contents & ( CONTENTS_SOLID | CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA ) ) {
+ return;
+ }
+
+ // trace down to find the surface
+ trap_CM_BoxTrace( &trace, start, end, NULL, NULL, 0, ( CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA ) );
+
+ if ( trace.fraction == 1.0 ) {
+ return;
+ }
+
+ // create a mark polygon
+ VectorCopy( trace.endpos, verts[0].xyz );
+ verts[0].xyz[0] -= 32;
+ verts[0].xyz[1] -= 32;
+ verts[0].st[0] = 0;
+ verts[0].st[1] = 0;
+ verts[0].modulate[0] = 255;
+ verts[0].modulate[1] = 255;
+ verts[0].modulate[2] = 255;
+ verts[0].modulate[3] = 255;
+
+ VectorCopy( trace.endpos, verts[1].xyz );
+ verts[1].xyz[0] -= 32;
+ verts[1].xyz[1] += 32;
+ verts[1].st[0] = 0;
+ verts[1].st[1] = 1;
+ verts[1].modulate[0] = 255;
+ verts[1].modulate[1] = 255;
+ verts[1].modulate[2] = 255;
+ verts[1].modulate[3] = 255;
+
+ VectorCopy( trace.endpos, verts[2].xyz );
+ verts[2].xyz[0] += 32;
+ verts[2].xyz[1] += 32;
+ verts[2].st[0] = 1;
+ verts[2].st[1] = 1;
+ verts[2].modulate[0] = 255;
+ verts[2].modulate[1] = 255;
+ verts[2].modulate[2] = 255;
+ verts[2].modulate[3] = 255;
+
+ VectorCopy( trace.endpos, verts[3].xyz );
+ verts[3].xyz[0] += 32;
+ verts[3].xyz[1] -= 32;
+ verts[3].st[0] = 1;
+ verts[3].st[1] = 0;
+ verts[3].modulate[0] = 255;
+ verts[3].modulate[1] = 255;
+ verts[3].modulate[2] = 255;
+ verts[3].modulate[3] = 255;
+
+ trap_R_AddPolyToScene( cgs.media.wakeMarkShader, 4, verts );
+}
+
+
+
+/*
+===============
+CG_AddRefEntityWithPowerups
+
+Adds a piece with modifications or duplications for powerups
+Also called by CG_Missile for quad rockets, but nobody can tell...
+===============
+*/
+void CG_AddRefEntityWithPowerups( refEntity_t *ent, entityState_t *state, int team ) {
+
+ if ( state->powerups & ( 1 << PW_INVIS ) ) {
+ ent->customShader = cgs.media.invisShader;
+ trap_R_AddRefEntityToScene( ent );
+ } else {
+ /*
+ if ( state->eFlags & EF_KAMIKAZE ) {
+ if (team == TEAM_BLUE)
+ ent->customShader = cgs.media.blueKamikazeShader;
+ else
+ ent->customShader = cgs.media.redKamikazeShader;
+ trap_R_AddRefEntityToScene( ent );
+ }
+ else {*/
+ trap_R_AddRefEntityToScene( ent );
+ //}
+
+ if ( state->powerups & ( 1 << PW_QUAD ) )
+ {
+ if (team == TEAM_RED)
+ ent->customShader = cgs.media.redQuadShader;
+ else
+ ent->customShader = cgs.media.quadShader;
+ trap_R_AddRefEntityToScene( ent );
+ }
+ if ( state->powerups & ( 1 << PW_REGEN ) ) {
+ if ( ( ( cg.time / 100 ) % 10 ) == 1 ) {
+ ent->customShader = cgs.media.regenShader;
+ trap_R_AddRefEntityToScene( ent );
+ }
+ }
+ if ( state->powerups & ( 1 << PW_BATTLESUIT ) ) {
+ ent->customShader = cgs.media.battleSuitShader;
+ trap_R_AddRefEntityToScene( ent );
+ }
+ }
+}
+
+/*
+=================
+CG_LightVerts
+=================
+*/
+int CG_LightVerts( vec3_t normal, int numVerts, polyVert_t *verts )
+{
+ int i, j;
+ float incoming;
+ vec3_t ambientLight;
+ vec3_t lightDir;
+ vec3_t directedLight;
+
+ trap_R_LightForPoint( verts[0].xyz, ambientLight, directedLight, lightDir );
+
+ for (i = 0; i < numVerts; i++) {
+ incoming = DotProduct (normal, lightDir);
+ if ( incoming <= 0 ) {
+ verts[i].modulate[0] = ambientLight[0];
+ verts[i].modulate[1] = ambientLight[1];
+ verts[i].modulate[2] = ambientLight[2];
+ verts[i].modulate[3] = 255;
+ continue;
+ }
+ j = ( ambientLight[0] + incoming * directedLight[0] );
+ if ( j > 255 ) {
+ j = 255;
+ }
+ verts[i].modulate[0] = j;
+
+ j = ( ambientLight[1] + incoming * directedLight[1] );
+ if ( j > 255 ) {
+ j = 255;
+ }
+ verts[i].modulate[1] = j;
+
+ j = ( ambientLight[2] + incoming * directedLight[2] );
+ if ( j > 255 ) {
+ j = 255;
+ }
+ verts[i].modulate[2] = j;
+
+ verts[i].modulate[3] = 255;
+ }
+ return qtrue;
+}
+
+/*
+===============
+CG_Player
+===============
+*/
+void CG_Player( centity_t *cent ) {
+ clientInfo_t *ci;
+ refEntity_t legs;
+ refEntity_t torso;
+ refEntity_t head;
+ int clientNum;
+ int renderfx;
+ qboolean shadow;
+ float shadowPlane;
+#ifdef MISSIONPACK
+ refEntity_t skull;
+ refEntity_t powerup;
+ int t;
+ float c;
+ float angle;
+ vec3_t dir, angles;
+#endif
+
+ // the client number is stored in clientNum. It can't be derived
+ // from the entity number, because a single client may have
+ // multiple corpses on the level using the same clientinfo
+ clientNum = cent->currentState.clientNum;
+ if ( clientNum < 0 || clientNum >= MAX_CLIENTS ) {
+ CG_Error( "Bad clientNum on player entity");
+ }
+ ci = &cgs.clientinfo[ clientNum ];
+
+ // it is possible to see corpses from disconnected players that may
+ // not have valid clientinfo
+ if ( !ci->infoValid ) {
+ return;
+ }
+
+ // get the player model information
+ renderfx = 0;
+ if ( cent->currentState.number == cg.snap->ps.clientNum) {
+ if (!cg.renderingThirdPerson) {
+ renderfx = RF_THIRD_PERSON; // only draw in mirrors
+ } else {
+ if (cg_cameraMode.integer) {
+ return;
+ }
+ }
+ }
+
+
+ memset( &legs, 0, sizeof(legs) );
+ memset( &torso, 0, sizeof(torso) );
+ memset( &head, 0, sizeof(head) );
+
+ // get the rotation information
+ CG_PlayerAngles( cent, legs.axis, torso.axis, head.axis );
+
+ // get the animation state (after rotation, to allow feet shuffle)
+ CG_PlayerAnimation( cent, &legs.oldframe, &legs.frame, &legs.backlerp,
+ &torso.oldframe, &torso.frame, &torso.backlerp );
+
+ // add the talk baloon or disconnect icon
+ CG_PlayerSprites( cent );
+
+ // add the shadow
+ shadow = CG_PlayerShadow( cent, &shadowPlane );
+
+ // add a water splash if partially in and out of water
+ CG_PlayerSplash( cent );
+
+ if ( cg_shadows.integer == 3 && shadow ) {
+ renderfx |= RF_SHADOW_PLANE;
+ }
+ renderfx |= RF_LIGHTING_ORIGIN; // use the same origin for all
+#ifdef MISSIONPACK
+ if( cgs.gametype == GT_HARVESTER ) {
+ CG_PlayerTokens( cent, renderfx );
+ }
+#endif
+ //
+ // add the legs
+ //
+ legs.hModel = ci->legsModel;
+ legs.customSkin = ci->legsSkin;
+
+ VectorCopy( cent->lerpOrigin, legs.origin );
+
+ VectorCopy( cent->lerpOrigin, legs.lightingOrigin );
+ legs.shadowPlane = shadowPlane;
+ legs.renderfx = renderfx;
+ VectorCopy (legs.origin, legs.oldorigin); // don't positionally lerp at all
+
+ CG_AddRefEntityWithPowerups( &legs, &cent->currentState, ci->team );
+
+ // if the model failed, allow the default nullmodel to be displayed
+ if (!legs.hModel) {
+ return;
+ }
+
+ //
+ // add the torso
+ //
+ torso.hModel = ci->torsoModel;
+ if (!torso.hModel) {
+ return;
+ }
+
+ torso.customSkin = ci->torsoSkin;
+
+ VectorCopy( cent->lerpOrigin, torso.lightingOrigin );
+
+ CG_PositionRotatedEntityOnTag( &torso, &legs, ci->legsModel, "tag_torso");
+
+ torso.shadowPlane = shadowPlane;
+ torso.renderfx = renderfx;
+
+ CG_AddRefEntityWithPowerups( &torso, &cent->currentState, ci->team );
+
+#ifdef MISSIONPACK
+ if ( cent->currentState.eFlags & EF_KAMIKAZE ) {
+
+ memset( &skull, 0, sizeof(skull) );
+
+ VectorCopy( cent->lerpOrigin, skull.lightingOrigin );
+ skull.shadowPlane = shadowPlane;
+ skull.renderfx = renderfx;
+
+ if ( cent->currentState.eFlags & EF_DEAD ) {
+ // one skull bobbing above the dead body
+ angle = ((cg.time / 7) & 255) * (M_PI * 2) / 255;
+ if (angle > M_PI * 2)
+ angle -= (float)M_PI * 2;
+ dir[0] = sin(angle) * 20;
+ dir[1] = cos(angle) * 20;
+ angle = ((cg.time / 4) & 255) * (M_PI * 2) / 255;
+ dir[2] = 15 + sin(angle) * 8;
+ VectorAdd(torso.origin, dir, skull.origin);
+
+ dir[2] = 0;
+ VectorCopy(dir, skull.axis[1]);
+ VectorNormalize(skull.axis[1]);
+ VectorSet(skull.axis[2], 0, 0, 1);
+ CrossProduct(skull.axis[1], skull.axis[2], skull.axis[0]);
+
+ skull.hModel = cgs.media.kamikazeHeadModel;
+ trap_R_AddRefEntityToScene( &skull );
+ skull.hModel = cgs.media.kamikazeHeadTrail;
+ trap_R_AddRefEntityToScene( &skull );
+ }
+ else {
+ // three skulls spinning around the player
+ angle = ((cg.time / 4) & 255) * (M_PI * 2) / 255;
+ dir[0] = cos(angle) * 20;
+ dir[1] = sin(angle) * 20;
+ dir[2] = cos(angle) * 20;
+ VectorAdd(torso.origin, dir, skull.origin);
+
+ angles[0] = sin(angle) * 30;
+ angles[1] = (angle * 180 / M_PI) + 90;
+ if (angles[1] > 360)
+ angles[1] -= 360;
+ angles[2] = 0;
+ AnglesToAxis( angles, skull.axis );
+
+ /*
+ dir[2] = 0;
+ VectorInverse(dir);
+ VectorCopy(dir, skull.axis[1]);
+ VectorNormalize(skull.axis[1]);
+ VectorSet(skull.axis[2], 0, 0, 1);
+ CrossProduct(skull.axis[1], skull.axis[2], skull.axis[0]);
+ */
+
+ skull.hModel = cgs.media.kamikazeHeadModel;
+ trap_R_AddRefEntityToScene( &skull );
+ // flip the trail because this skull is spinning in the other direction
+ VectorInverse(skull.axis[1]);
+ skull.hModel = cgs.media.kamikazeHeadTrail;
+ trap_R_AddRefEntityToScene( &skull );
+
+ angle = ((cg.time / 4) & 255) * (M_PI * 2) / 255 + M_PI;
+ if (angle > M_PI * 2)
+ angle -= (float)M_PI * 2;
+ dir[0] = sin(angle) * 20;
+ dir[1] = cos(angle) * 20;
+ dir[2] = cos(angle) * 20;
+ VectorAdd(torso.origin, dir, skull.origin);
+
+ angles[0] = cos(angle - 0.5 * M_PI) * 30;
+ angles[1] = 360 - (angle * 180 / M_PI);
+ if (angles[1] > 360)
+ angles[1] -= 360;
+ angles[2] = 0;
+ AnglesToAxis( angles, skull.axis );
+
+ /*
+ dir[2] = 0;
+ VectorCopy(dir, skull.axis[1]);
+ VectorNormalize(skull.axis[1]);
+ VectorSet(skull.axis[2], 0, 0, 1);
+ CrossProduct(skull.axis[1], skull.axis[2], skull.axis[0]);
+ */
+
+ skull.hModel = cgs.media.kamikazeHeadModel;
+ trap_R_AddRefEntityToScene( &skull );
+ skull.hModel = cgs.media.kamikazeHeadTrail;
+ trap_R_AddRefEntityToScene( &skull );
+
+ angle = ((cg.time / 3) & 255) * (M_PI * 2) / 255 + 0.5 * M_PI;
+ if (angle > M_PI * 2)
+ angle -= (float)M_PI * 2;
+ dir[0] = sin(angle) * 20;
+ dir[1] = cos(angle) * 20;
+ dir[2] = 0;
+ VectorAdd(torso.origin, dir, skull.origin);
+
+ VectorCopy(dir, skull.axis[1]);
+ VectorNormalize(skull.axis[1]);
+ VectorSet(skull.axis[2], 0, 0, 1);
+ CrossProduct(skull.axis[1], skull.axis[2], skull.axis[0]);
+
+ skull.hModel = cgs.media.kamikazeHeadModel;
+ trap_R_AddRefEntityToScene( &skull );
+ skull.hModel = cgs.media.kamikazeHeadTrail;
+ trap_R_AddRefEntityToScene( &skull );
+ }
+ }
+
+ if ( cent->currentState.powerups & ( 1 << PW_GUARD ) ) {
+ memcpy(&powerup, &torso, sizeof(torso));
+ powerup.hModel = cgs.media.guardPowerupModel;
+ powerup.frame = 0;
+ powerup.oldframe = 0;
+ powerup.customSkin = 0;
+ trap_R_AddRefEntityToScene( &powerup );
+ }
+ if ( cent->currentState.powerups & ( 1 << PW_SCOUT ) ) {
+ memcpy(&powerup, &torso, sizeof(torso));
+ powerup.hModel = cgs.media.scoutPowerupModel;
+ powerup.frame = 0;
+ powerup.oldframe = 0;
+ powerup.customSkin = 0;
+ trap_R_AddRefEntityToScene( &powerup );
+ }
+ if ( cent->currentState.powerups & ( 1 << PW_DOUBLER ) ) {
+ memcpy(&powerup, &torso, sizeof(torso));
+ powerup.hModel = cgs.media.doublerPowerupModel;
+ powerup.frame = 0;
+ powerup.oldframe = 0;
+ powerup.customSkin = 0;
+ trap_R_AddRefEntityToScene( &powerup );
+ }
+ if ( cent->currentState.powerups & ( 1 << PW_AMMOREGEN ) ) {
+ memcpy(&powerup, &torso, sizeof(torso));
+ powerup.hModel = cgs.media.ammoRegenPowerupModel;
+ powerup.frame = 0;
+ powerup.oldframe = 0;
+ powerup.customSkin = 0;
+ trap_R_AddRefEntityToScene( &powerup );
+ }
+ if ( cent->currentState.powerups & ( 1 << PW_INVULNERABILITY ) ) {
+ if ( !ci->invulnerabilityStartTime ) {
+ ci->invulnerabilityStartTime = cg.time;
+ }
+ ci->invulnerabilityStopTime = cg.time;
+ }
+ else {
+ ci->invulnerabilityStartTime = 0;
+ }
+ if ( (cent->currentState.powerups & ( 1 << PW_INVULNERABILITY ) ) ||
+ cg.time - ci->invulnerabilityStopTime < 250 ) {
+
+ memcpy(&powerup, &torso, sizeof(torso));
+ powerup.hModel = cgs.media.invulnerabilityPowerupModel;
+ powerup.customSkin = 0;
+ // always draw
+ powerup.renderfx &= ~RF_THIRD_PERSON;
+ VectorCopy(cent->lerpOrigin, powerup.origin);
+
+ if ( cg.time - ci->invulnerabilityStartTime < 250 ) {
+ c = (float) (cg.time - ci->invulnerabilityStartTime) / 250;
+ }
+ else if (cg.time - ci->invulnerabilityStopTime < 250 ) {
+ c = (float) (250 - (cg.time - ci->invulnerabilityStopTime)) / 250;
+ }
+ else {
+ c = 1;
+ }
+ VectorSet( powerup.axis[0], c, 0, 0 );
+ VectorSet( powerup.axis[1], 0, c, 0 );
+ VectorSet( powerup.axis[2], 0, 0, c );
+ trap_R_AddRefEntityToScene( &powerup );
+ }
+
+ t = cg.time - ci->medkitUsageTime;
+ if ( ci->medkitUsageTime && t < 500 ) {
+ memcpy(&powerup, &torso, sizeof(torso));
+ powerup.hModel = cgs.media.medkitUsageModel;
+ powerup.customSkin = 0;
+ // always draw
+ powerup.renderfx &= ~RF_THIRD_PERSON;
+ VectorClear(angles);
+ AnglesToAxis(angles, powerup.axis);
+ VectorCopy(cent->lerpOrigin, powerup.origin);
+ powerup.origin[2] += -24 + (float) t * 80 / 500;
+ if ( t > 400 ) {
+ c = (float) (t - 1000) * 0xff / 100;
+ powerup.shaderRGBA[0] = 0xff - c;
+ powerup.shaderRGBA[1] = 0xff - c;
+ powerup.shaderRGBA[2] = 0xff - c;
+ powerup.shaderRGBA[3] = 0xff - c;
+ }
+ else {
+ powerup.shaderRGBA[0] = 0xff;
+ powerup.shaderRGBA[1] = 0xff;
+ powerup.shaderRGBA[2] = 0xff;
+ powerup.shaderRGBA[3] = 0xff;
+ }
+ trap_R_AddRefEntityToScene( &powerup );
+ }
+#endif // MISSIONPACK
+
+ //
+ // add the head
+ //
+ head.hModel = ci->headModel;
+ if (!head.hModel) {
+ return;
+ }
+ head.customSkin = ci->headSkin;
+
+ VectorCopy( cent->lerpOrigin, head.lightingOrigin );
+
+ CG_PositionRotatedEntityOnTag( &head, &torso, ci->torsoModel, "tag_head");
+
+ head.shadowPlane = shadowPlane;
+ head.renderfx = renderfx;
+
+ CG_AddRefEntityWithPowerups( &head, &cent->currentState, ci->team );
+
+#ifdef MISSIONPACK
+ CG_BreathPuffs(cent, &head);
+
+ CG_DustTrail(cent);
+#endif
+
+ //
+ // add the gun / barrel / flash
+ //
+ CG_AddPlayerWeapon( &torso, NULL, cent, ci->team );
+
+ // add powerups floating behind the player
+ CG_PlayerPowerups( cent, &torso );
+}
+
+
+//=====================================================================
+
+/*
+===============
+CG_ResetPlayerEntity
+
+A player just came into view or teleported, so reset all animation info
+===============
+*/
+void CG_ResetPlayerEntity( centity_t *cent ) {
+ cent->errorTime = -99999; // guarantee no error decay added
+ cent->extrapolated = qfalse;
+
+ CG_ClearLerpFrame( &cgs.clientinfo[ cent->currentState.clientNum ], &cent->pe.legs, cent->currentState.legsAnim );
+ CG_ClearLerpFrame( &cgs.clientinfo[ cent->currentState.clientNum ], &cent->pe.torso, cent->currentState.torsoAnim );
+
+ BG_EvaluateTrajectory( &cent->currentState.pos, cg.time, cent->lerpOrigin );
+ BG_EvaluateTrajectory( &cent->currentState.apos, cg.time, cent->lerpAngles );
+
+ VectorCopy( cent->lerpOrigin, cent->rawOrigin );
+ VectorCopy( cent->lerpAngles, cent->rawAngles );
+
+ memset( &cent->pe.legs, 0, sizeof( cent->pe.legs ) );
+ cent->pe.legs.yawAngle = cent->rawAngles[YAW];
+ cent->pe.legs.yawing = qfalse;
+ cent->pe.legs.pitchAngle = 0;
+ cent->pe.legs.pitching = qfalse;
+
+ memset( &cent->pe.torso, 0, sizeof( cent->pe.legs ) );
+ cent->pe.torso.yawAngle = cent->rawAngles[YAW];
+ cent->pe.torso.yawing = qfalse;
+ cent->pe.torso.pitchAngle = cent->rawAngles[PITCH];
+ cent->pe.torso.pitching = qfalse;
+
+ if ( cg_debugPosition.integer ) {
+ CG_Printf("%i ResetPlayerEntity yaw=%i\n", cent->currentState.number, cent->pe.torso.yawAngle );
+ }
+}
+
diff --git a/code/cgame/cg_playerstate.c b/code/cgame/cg_playerstate.c
new file mode 100755
index 0000000..1e0d61a
--- /dev/null
+++ b/code/cgame/cg_playerstate.c
@@ -0,0 +1,526 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// cg_playerstate.c -- this file acts on changes in a new playerState_t
+// With normal play, this will be done after local prediction, but when
+// following another player or playing back a demo, it will be checked
+// when the snapshot transitions like all the other entities
+
+#include "cg_local.h"
+
+/*
+==============
+CG_CheckAmmo
+
+If the ammo has gone low enough to generate the warning, play a sound
+==============
+*/
+void CG_CheckAmmo( void ) {
+ int i;
+ int total;
+ int previous;
+ int weapons;
+
+ // see about how many seconds of ammo we have remaining
+ weapons = cg.snap->ps.stats[ STAT_WEAPONS ];
+ total = 0;
+ for ( i = WP_MACHINEGUN ; i < WP_NUM_WEAPONS ; i++ ) {
+ if ( ! ( weapons & ( 1 << i ) ) ) {
+ continue;
+ }
+ switch ( i ) {
+ case WP_ROCKET_LAUNCHER:
+ case WP_GRENADE_LAUNCHER:
+ case WP_RAILGUN:
+ case WP_SHOTGUN:
+#ifdef MISSIONPACK
+ case WP_PROX_LAUNCHER:
+#endif
+ total += cg.snap->ps.ammo[i] * 1000;
+ break;
+ default:
+ total += cg.snap->ps.ammo[i] * 200;
+ break;
+ }
+ if ( total >= 5000 ) {
+ cg.lowAmmoWarning = 0;
+ return;
+ }
+ }
+
+ previous = cg.lowAmmoWarning;
+
+ if ( total == 0 ) {
+ cg.lowAmmoWarning = 2;
+ } else {
+ cg.lowAmmoWarning = 1;
+ }
+
+ // play a sound on transitions
+ if ( cg.lowAmmoWarning != previous ) {
+ trap_S_StartLocalSound( cgs.media.noAmmoSound, CHAN_LOCAL_SOUND );
+ }
+}
+
+/*
+==============
+CG_DamageFeedback
+==============
+*/
+void CG_DamageFeedback( int yawByte, int pitchByte, int damage ) {
+ float left, front, up;
+ float kick;
+ int health;
+ float scale;
+ vec3_t dir;
+ vec3_t angles;
+ float dist;
+ float yaw, pitch;
+
+ // show the attacking player's head and name in corner
+ cg.attackerTime = cg.time;
+
+ // the lower on health you are, the greater the view kick will be
+ health = cg.snap->ps.stats[STAT_HEALTH];
+ if ( health < 40 ) {
+ scale = 1;
+ } else {
+ scale = 40.0 / health;
+ }
+ kick = damage * scale;
+
+ if (kick < 5)
+ kick = 5;
+ if (kick > 10)
+ kick = 10;
+
+ // if yaw and pitch are both 255, make the damage always centered (falling, etc)
+ if ( yawByte == 255 && pitchByte == 255 ) {
+ cg.damageX = 0;
+ cg.damageY = 0;
+ cg.v_dmg_roll = 0;
+ cg.v_dmg_pitch = -kick;
+ } else {
+ // positional
+ pitch = pitchByte / 255.0 * 360;
+ yaw = yawByte / 255.0 * 360;
+
+ angles[PITCH] = pitch;
+ angles[YAW] = yaw;
+ angles[ROLL] = 0;
+
+ AngleVectors( angles, dir, NULL, NULL );
+ VectorSubtract( vec3_origin, dir, dir );
+
+ front = DotProduct (dir, cg.refdef.viewaxis[0] );
+ left = DotProduct (dir, cg.refdef.viewaxis[1] );
+ up = DotProduct (dir, cg.refdef.viewaxis[2] );
+
+ dir[0] = front;
+ dir[1] = left;
+ dir[2] = 0;
+ dist = VectorLength( dir );
+ if ( dist < 0.1 ) {
+ dist = 0.1f;
+ }
+
+ cg.v_dmg_roll = kick * left;
+
+ cg.v_dmg_pitch = -kick * front;
+
+ if ( front <= 0.1 ) {
+ front = 0.1f;
+ }
+ cg.damageX = -left / front;
+ cg.damageY = up / dist;
+ }
+
+ // clamp the position
+ if ( cg.damageX > 1.0 ) {
+ cg.damageX = 1.0;
+ }
+ if ( cg.damageX < - 1.0 ) {
+ cg.damageX = -1.0;
+ }
+
+ if ( cg.damageY > 1.0 ) {
+ cg.damageY = 1.0;
+ }
+ if ( cg.damageY < - 1.0 ) {
+ cg.damageY = -1.0;
+ }
+
+ // don't let the screen flashes vary as much
+ if ( kick > 10 ) {
+ kick = 10;
+ }
+ cg.damageValue = kick;
+ cg.v_dmg_time = cg.time + DAMAGE_TIME;
+ cg.damageTime = cg.snap->serverTime;
+}
+
+
+
+
+/*
+================
+CG_Respawn
+
+A respawn happened this snapshot
+================
+*/
+void CG_Respawn( void ) {
+ // no error decay on player movement
+ cg.thisFrameTeleport = qtrue;
+
+ // display weapons available
+ cg.weaponSelectTime = cg.time;
+
+ // select the weapon the server says we are using
+ cg.weaponSelect = cg.snap->ps.weapon;
+}
+
+extern char *eventnames[];
+
+/*
+==============
+CG_CheckPlayerstateEvents
+==============
+*/
+void CG_CheckPlayerstateEvents( playerState_t *ps, playerState_t *ops ) {
+ int i;
+ int event;
+ centity_t *cent;
+
+ if ( ps->externalEvent && ps->externalEvent != ops->externalEvent ) {
+ cent = &cg_entities[ ps->clientNum ];
+ cent->currentState.event = ps->externalEvent;
+ cent->currentState.eventParm = ps->externalEventParm;
+ CG_EntityEvent( cent, cent->lerpOrigin );
+ }
+
+ cent = &cg.predictedPlayerEntity; // cg_entities[ ps->clientNum ];
+ // go through the predictable events buffer
+ for ( i = ps->eventSequence - MAX_PS_EVENTS ; i < ps->eventSequence ; i++ ) {
+ // if we have a new predictable event
+ if ( i >= ops->eventSequence
+ // or the server told us to play another event instead of a predicted event we already issued
+ // or something the server told us changed our prediction causing a different event
+ || (i > ops->eventSequence - MAX_PS_EVENTS && ps->events[i & (MAX_PS_EVENTS-1)] != ops->events[i & (MAX_PS_EVENTS-1)]) ) {
+
+ event = ps->events[ i & (MAX_PS_EVENTS-1) ];
+ cent->currentState.event = event;
+ cent->currentState.eventParm = ps->eventParms[ i & (MAX_PS_EVENTS-1) ];
+ CG_EntityEvent( cent, cent->lerpOrigin );
+
+ cg.predictableEvents[ i & (MAX_PREDICTED_EVENTS-1) ] = event;
+
+ cg.eventSequence++;
+ }
+ }
+}
+
+/*
+==================
+CG_CheckChangedPredictableEvents
+==================
+*/
+void CG_CheckChangedPredictableEvents( playerState_t *ps ) {
+ int i;
+ int event;
+ centity_t *cent;
+
+ cent = &cg.predictedPlayerEntity;
+ for ( i = ps->eventSequence - MAX_PS_EVENTS ; i < ps->eventSequence ; i++ ) {
+ //
+ if (i >= cg.eventSequence) {
+ continue;
+ }
+ // if this event is not further back in than the maximum predictable events we remember
+ if (i > cg.eventSequence - MAX_PREDICTED_EVENTS) {
+ // if the new playerstate event is different from a previously predicted one
+ if ( ps->events[i & (MAX_PS_EVENTS-1)] != cg.predictableEvents[i & (MAX_PREDICTED_EVENTS-1) ] ) {
+
+ event = ps->events[ i & (MAX_PS_EVENTS-1) ];
+ cent->currentState.event = event;
+ cent->currentState.eventParm = ps->eventParms[ i & (MAX_PS_EVENTS-1) ];
+ CG_EntityEvent( cent, cent->lerpOrigin );
+
+ cg.predictableEvents[ i & (MAX_PREDICTED_EVENTS-1) ] = event;
+
+ if ( cg_showmiss.integer ) {
+ CG_Printf("WARNING: changed predicted event\n");
+ }
+ }
+ }
+ }
+}
+
+/*
+==================
+pushReward
+==================
+*/
+static void pushReward(sfxHandle_t sfx, qhandle_t shader, int rewardCount) {
+ if (cg.rewardStack < (MAX_REWARDSTACK-1)) {
+ cg.rewardStack++;
+ cg.rewardSound[cg.rewardStack] = sfx;
+ cg.rewardShader[cg.rewardStack] = shader;
+ cg.rewardCount[cg.rewardStack] = rewardCount;
+ }
+}
+
+/*
+==================
+CG_CheckLocalSounds
+==================
+*/
+void CG_CheckLocalSounds( playerState_t *ps, playerState_t *ops ) {
+ int highScore, health, armor, reward;
+ sfxHandle_t sfx;
+
+ // don't play the sounds if the player just changed teams
+ if ( ps->persistant[PERS_TEAM] != ops->persistant[PERS_TEAM] ) {
+ return;
+ }
+
+ // hit changes
+ if ( ps->persistant[PERS_HITS] > ops->persistant[PERS_HITS] ) {
+ armor = ps->persistant[PERS_ATTACKEE_ARMOR] & 0xff;
+ health = ps->persistant[PERS_ATTACKEE_ARMOR] >> 8;
+#ifdef MISSIONPACK
+ if (armor > 50 ) {
+ trap_S_StartLocalSound( cgs.media.hitSoundHighArmor, CHAN_LOCAL_SOUND );
+ } else if (armor || health > 100) {
+ trap_S_StartLocalSound( cgs.media.hitSoundLowArmor, CHAN_LOCAL_SOUND );
+ } else {
+ trap_S_StartLocalSound( cgs.media.hitSound, CHAN_LOCAL_SOUND );
+ }
+#else
+ trap_S_StartLocalSound( cgs.media.hitSound, CHAN_LOCAL_SOUND );
+#endif
+ } else if ( ps->persistant[PERS_HITS] < ops->persistant[PERS_HITS] ) {
+ trap_S_StartLocalSound( cgs.media.hitTeamSound, CHAN_LOCAL_SOUND );
+ }
+
+ // health changes of more than -1 should make pain sounds
+ if ( ps->stats[STAT_HEALTH] < ops->stats[STAT_HEALTH] - 1 ) {
+ if ( ps->stats[STAT_HEALTH] > 0 ) {
+ CG_PainEvent( &cg.predictedPlayerEntity, ps->stats[STAT_HEALTH] );
+ }
+ }
+
+
+ // if we are going into the intermission, don't start any voices
+ if ( cg.intermissionStarted ) {
+ return;
+ }
+
+ // reward sounds
+ reward = qfalse;
+ if (ps->persistant[PERS_CAPTURES] != ops->persistant[PERS_CAPTURES]) {
+ pushReward(cgs.media.captureAwardSound, cgs.media.medalCapture, ps->persistant[PERS_CAPTURES]);
+ reward = qtrue;
+ //Com_Printf("capture\n");
+ }
+ if (ps->persistant[PERS_IMPRESSIVE_COUNT] != ops->persistant[PERS_IMPRESSIVE_COUNT]) {
+#ifdef MISSIONPACK
+ if (ps->persistant[PERS_IMPRESSIVE_COUNT] == 1) {
+ sfx = cgs.media.firstImpressiveSound;
+ } else {
+ sfx = cgs.media.impressiveSound;
+ }
+#else
+ sfx = cgs.media.impressiveSound;
+#endif
+ pushReward(sfx, cgs.media.medalImpressive, ps->persistant[PERS_IMPRESSIVE_COUNT]);
+ reward = qtrue;
+ //Com_Printf("impressive\n");
+ }
+ if (ps->persistant[PERS_EXCELLENT_COUNT] != ops->persistant[PERS_EXCELLENT_COUNT]) {
+#ifdef MISSIONPACK
+ if (ps->persistant[PERS_EXCELLENT_COUNT] == 1) {
+ sfx = cgs.media.firstExcellentSound;
+ } else {
+ sfx = cgs.media.excellentSound;
+ }
+#else
+ sfx = cgs.media.excellentSound;
+#endif
+ pushReward(sfx, cgs.media.medalExcellent, ps->persistant[PERS_EXCELLENT_COUNT]);
+ reward = qtrue;
+ //Com_Printf("excellent\n");
+ }
+ if (ps->persistant[PERS_GAUNTLET_FRAG_COUNT] != ops->persistant[PERS_GAUNTLET_FRAG_COUNT]) {
+#ifdef MISSIONPACK
+ if (ops->persistant[PERS_GAUNTLET_FRAG_COUNT] == 1) {
+ sfx = cgs.media.firstHumiliationSound;
+ } else {
+ sfx = cgs.media.humiliationSound;
+ }
+#else
+ sfx = cgs.media.humiliationSound;
+#endif
+ pushReward(sfx, cgs.media.medalGauntlet, ps->persistant[PERS_GAUNTLET_FRAG_COUNT]);
+ reward = qtrue;
+ //Com_Printf("guantlet frag\n");
+ }
+ if (ps->persistant[PERS_DEFEND_COUNT] != ops->persistant[PERS_DEFEND_COUNT]) {
+ pushReward(cgs.media.defendSound, cgs.media.medalDefend, ps->persistant[PERS_DEFEND_COUNT]);
+ reward = qtrue;
+ //Com_Printf("defend\n");
+ }
+ if (ps->persistant[PERS_ASSIST_COUNT] != ops->persistant[PERS_ASSIST_COUNT]) {
+ pushReward(cgs.media.assistSound, cgs.media.medalAssist, ps->persistant[PERS_ASSIST_COUNT]);
+ reward = qtrue;
+ //Com_Printf("assist\n");
+ }
+ // if any of the player event bits changed
+ if (ps->persistant[PERS_PLAYEREVENTS] != ops->persistant[PERS_PLAYEREVENTS]) {
+ if ((ps->persistant[PERS_PLAYEREVENTS] & PLAYEREVENT_DENIEDREWARD) !=
+ (ops->persistant[PERS_PLAYEREVENTS] & PLAYEREVENT_DENIEDREWARD)) {
+ trap_S_StartLocalSound( cgs.media.deniedSound, CHAN_ANNOUNCER );
+ }
+ else if ((ps->persistant[PERS_PLAYEREVENTS] & PLAYEREVENT_GAUNTLETREWARD) !=
+ (ops->persistant[PERS_PLAYEREVENTS] & PLAYEREVENT_GAUNTLETREWARD)) {
+ trap_S_StartLocalSound( cgs.media.humiliationSound, CHAN_ANNOUNCER );
+ }
+ else if ((ps->persistant[PERS_PLAYEREVENTS] & PLAYEREVENT_HOLYSHIT) !=
+ (ops->persistant[PERS_PLAYEREVENTS] & PLAYEREVENT_HOLYSHIT)) {
+ trap_S_StartLocalSound( cgs.media.holyShitSound, CHAN_ANNOUNCER );
+ }
+ reward = qtrue;
+ }
+
+ // check for flag pickup
+ if ( cgs.gametype >= GT_TEAM ) {
+ if ((ps->powerups[PW_REDFLAG] != ops->powerups[PW_REDFLAG] && ps->powerups[PW_REDFLAG]) ||
+ (ps->powerups[PW_BLUEFLAG] != ops->powerups[PW_BLUEFLAG] && ps->powerups[PW_BLUEFLAG]) ||
+ (ps->powerups[PW_NEUTRALFLAG] != ops->powerups[PW_NEUTRALFLAG] && ps->powerups[PW_NEUTRALFLAG]) )
+ {
+ trap_S_StartLocalSound( cgs.media.youHaveFlagSound, CHAN_ANNOUNCER );
+ }
+ }
+
+ // lead changes
+ if (!reward) {
+ //
+ if ( !cg.warmup ) {
+ // never play lead changes during warmup
+ if ( ps->persistant[PERS_RANK] != ops->persistant[PERS_RANK] ) {
+ if ( cgs.gametype < GT_TEAM) {
+ if ( ps->persistant[PERS_RANK] == 0 ) {
+ CG_AddBufferedSound(cgs.media.takenLeadSound);
+ } else if ( ps->persistant[PERS_RANK] == RANK_TIED_FLAG ) {
+ CG_AddBufferedSound(cgs.media.tiedLeadSound);
+ } else if ( ( ops->persistant[PERS_RANK] & ~RANK_TIED_FLAG ) == 0 ) {
+ CG_AddBufferedSound(cgs.media.lostLeadSound);
+ }
+ }
+ }
+ }
+ }
+
+ // timelimit warnings
+ if ( cgs.timelimit > 0 ) {
+ int msec;
+
+ msec = cg.time - cgs.levelStartTime;
+ if ( !( cg.timelimitWarnings & 4 ) && msec > ( cgs.timelimit * 60 + 2 ) * 1000 ) {
+ cg.timelimitWarnings |= 1 | 2 | 4;
+ trap_S_StartLocalSound( cgs.media.suddenDeathSound, CHAN_ANNOUNCER );
+ }
+ else if ( !( cg.timelimitWarnings & 2 ) && msec > (cgs.timelimit - 1) * 60 * 1000 ) {
+ cg.timelimitWarnings |= 1 | 2;
+ trap_S_StartLocalSound( cgs.media.oneMinuteSound, CHAN_ANNOUNCER );
+ }
+ else if ( cgs.timelimit > 5 && !( cg.timelimitWarnings & 1 ) && msec > (cgs.timelimit - 5) * 60 * 1000 ) {
+ cg.timelimitWarnings |= 1;
+ trap_S_StartLocalSound( cgs.media.fiveMinuteSound, CHAN_ANNOUNCER );
+ }
+ }
+
+ // fraglimit warnings
+ if ( cgs.fraglimit > 0 && cgs.gametype < GT_CTF) {
+ highScore = cgs.scores1;
+ if ( !( cg.fraglimitWarnings & 4 ) && highScore == (cgs.fraglimit - 1) ) {
+ cg.fraglimitWarnings |= 1 | 2 | 4;
+ CG_AddBufferedSound(cgs.media.oneFragSound);
+ }
+ else if ( cgs.fraglimit > 2 && !( cg.fraglimitWarnings & 2 ) && highScore == (cgs.fraglimit - 2) ) {
+ cg.fraglimitWarnings |= 1 | 2;
+ CG_AddBufferedSound(cgs.media.twoFragSound);
+ }
+ else if ( cgs.fraglimit > 3 && !( cg.fraglimitWarnings & 1 ) && highScore == (cgs.fraglimit - 3) ) {
+ cg.fraglimitWarnings |= 1;
+ CG_AddBufferedSound(cgs.media.threeFragSound);
+ }
+ }
+}
+
+/*
+===============
+CG_TransitionPlayerState
+
+===============
+*/
+void CG_TransitionPlayerState( playerState_t *ps, playerState_t *ops ) {
+ // check for changing follow mode
+ if ( ps->clientNum != ops->clientNum ) {
+ cg.thisFrameTeleport = qtrue;
+ // make sure we don't get any unwanted transition effects
+ *ops = *ps;
+ }
+
+ // damage events (player is getting wounded)
+ if ( ps->damageEvent != ops->damageEvent && ps->damageCount ) {
+ CG_DamageFeedback( ps->damageYaw, ps->damagePitch, ps->damageCount );
+ }
+
+ // respawning
+ if ( ps->persistant[PERS_SPAWN_COUNT] != ops->persistant[PERS_SPAWN_COUNT] ) {
+ CG_Respawn();
+ }
+
+ if ( cg.mapRestart ) {
+ CG_Respawn();
+ cg.mapRestart = qfalse;
+ }
+
+ if ( cg.snap->ps.pm_type != PM_INTERMISSION
+ && ps->persistant[PERS_TEAM] != TEAM_SPECTATOR ) {
+ CG_CheckLocalSounds( ps, ops );
+ }
+
+ // check for going low on ammo
+ CG_CheckAmmo();
+
+ // run events
+ CG_CheckPlayerstateEvents( ps, ops );
+
+ // smooth the ducking viewheight change
+ if ( ps->viewheight != ops->viewheight ) {
+ cg.duckChange = ps->viewheight - ops->viewheight;
+ cg.duckTime = cg.time;
+ }
+}
+
diff --git a/code/cgame/cg_predict.c b/code/cgame/cg_predict.c
new file mode 100755
index 0000000..fec2cfb
--- /dev/null
+++ b/code/cgame/cg_predict.c
@@ -0,0 +1,628 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// cg_predict.c -- this file generates cg.predictedPlayerState by either
+// interpolating between snapshots from the server or locally predicting
+// ahead the client's movement.
+// It also handles local physics interaction, like fragments bouncing off walls
+
+#include "cg_local.h"
+
+static pmove_t cg_pmove;
+
+static int cg_numSolidEntities;
+static centity_t *cg_solidEntities[MAX_ENTITIES_IN_SNAPSHOT];
+static int cg_numTriggerEntities;
+static centity_t *cg_triggerEntities[MAX_ENTITIES_IN_SNAPSHOT];
+
+/*
+====================
+CG_BuildSolidList
+
+When a new cg.snap has been set, this function builds a sublist
+of the entities that are actually solid, to make for more
+efficient collision detection
+====================
+*/
+void CG_BuildSolidList( void ) {
+ int i;
+ centity_t *cent;
+ snapshot_t *snap;
+ entityState_t *ent;
+
+ cg_numSolidEntities = 0;
+ cg_numTriggerEntities = 0;
+
+ if ( cg.nextSnap && !cg.nextFrameTeleport && !cg.thisFrameTeleport ) {
+ snap = cg.nextSnap;
+ } else {
+ snap = cg.snap;
+ }
+
+ for ( i = 0 ; i < snap->numEntities ; i++ ) {
+ cent = &cg_entities[ snap->entities[ i ].number ];
+ ent = &cent->currentState;
+
+ if ( ent->eType == ET_ITEM || ent->eType == ET_PUSH_TRIGGER || ent->eType == ET_TELEPORT_TRIGGER ) {
+ cg_triggerEntities[cg_numTriggerEntities] = cent;
+ cg_numTriggerEntities++;
+ continue;
+ }
+
+ if ( cent->nextState.solid ) {
+ cg_solidEntities[cg_numSolidEntities] = cent;
+ cg_numSolidEntities++;
+ continue;
+ }
+ }
+}
+
+/*
+====================
+CG_ClipMoveToEntities
+
+====================
+*/
+static void CG_ClipMoveToEntities ( const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end,
+ int skipNumber, int mask, trace_t *tr ) {
+ int i, x, zd, zu;
+ trace_t trace;
+ entityState_t *ent;
+ clipHandle_t cmodel;
+ vec3_t bmins, bmaxs;
+ vec3_t origin, angles;
+ centity_t *cent;
+
+ for ( i = 0 ; i < cg_numSolidEntities ; i++ ) {
+ cent = cg_solidEntities[ i ];
+ ent = &cent->currentState;
+
+ if ( ent->number == skipNumber ) {
+ continue;
+ }
+
+ if ( ent->solid == SOLID_BMODEL ) {
+ // special value for bmodel
+ cmodel = trap_CM_InlineModel( ent->modelindex );
+ VectorCopy( cent->lerpAngles, angles );
+ BG_EvaluateTrajectory( &cent->currentState.pos, cg.physicsTime, origin );
+ } else {
+ // encoded bbox
+ x = (ent->solid & 255);
+ zd = ((ent->solid>>8) & 255);
+ zu = ((ent->solid>>16) & 255) - 32;
+
+ bmins[0] = bmins[1] = -x;
+ bmaxs[0] = bmaxs[1] = x;
+ bmins[2] = -zd;
+ bmaxs[2] = zu;
+
+ cmodel = trap_CM_TempBoxModel( bmins, bmaxs );
+ VectorCopy( vec3_origin, angles );
+ VectorCopy( cent->lerpOrigin, origin );
+ }
+
+
+ trap_CM_TransformedBoxTrace ( &trace, start, end,
+ mins, maxs, cmodel, mask, origin, angles);
+
+ if (trace.allsolid || trace.fraction < tr->fraction) {
+ trace.entityNum = ent->number;
+ *tr = trace;
+ } else if (trace.startsolid) {
+ tr->startsolid = qtrue;
+ }
+ if ( tr->allsolid ) {
+ return;
+ }
+ }
+}
+
+/*
+================
+CG_Trace
+================
+*/
+void CG_Trace( trace_t *result, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end,
+ int skipNumber, int mask ) {
+ trace_t t;
+
+ trap_CM_BoxTrace ( &t, start, end, mins, maxs, 0, mask);
+ t.entityNum = t.fraction != 1.0 ? ENTITYNUM_WORLD : ENTITYNUM_NONE;
+ // check all other solid models
+ CG_ClipMoveToEntities (start, mins, maxs, end, skipNumber, mask, &t);
+
+ *result = t;
+}
+
+/*
+================
+CG_PointContents
+================
+*/
+int CG_PointContents( const vec3_t point, int passEntityNum ) {
+ int i;
+ entityState_t *ent;
+ centity_t *cent;
+ clipHandle_t cmodel;
+ int contents;
+
+ contents = trap_CM_PointContents (point, 0);
+
+ for ( i = 0 ; i < cg_numSolidEntities ; i++ ) {
+ cent = cg_solidEntities[ i ];
+
+ ent = &cent->currentState;
+
+ if ( ent->number == passEntityNum ) {
+ continue;
+ }
+
+ if (ent->solid != SOLID_BMODEL) { // special value for bmodel
+ continue;
+ }
+
+ cmodel = trap_CM_InlineModel( ent->modelindex );
+ if ( !cmodel ) {
+ continue;
+ }
+
+ contents |= trap_CM_TransformedPointContents( point, cmodel, ent->origin, ent->angles );
+ }
+
+ return contents;
+}
+
+
+/*
+========================
+CG_InterpolatePlayerState
+
+Generates cg.predictedPlayerState by interpolating between
+cg.snap->player_state and cg.nextFrame->player_state
+========================
+*/
+static void CG_InterpolatePlayerState( qboolean grabAngles ) {
+ float f;
+ int i;
+ playerState_t *out;
+ snapshot_t *prev, *next;
+
+ out = &cg.predictedPlayerState;
+ prev = cg.snap;
+ next = cg.nextSnap;
+
+ *out = cg.snap->ps;
+
+ // if we are still allowing local input, short circuit the view angles
+ if ( grabAngles ) {
+ usercmd_t cmd;
+ int cmdNum;
+
+ cmdNum = trap_GetCurrentCmdNumber();
+ trap_GetUserCmd( cmdNum, &cmd );
+
+ PM_UpdateViewAngles( out, &cmd );
+ }
+
+ // if the next frame is a teleport, we can't lerp to it
+ if ( cg.nextFrameTeleport ) {
+ return;
+ }
+
+ if ( !next || next->serverTime <= prev->serverTime ) {
+ return;
+ }
+
+ f = (float)( cg.time - prev->serverTime ) / ( next->serverTime - prev->serverTime );
+
+ i = next->ps.bobCycle;
+ if ( i < prev->ps.bobCycle ) {
+ i += 256; // handle wraparound
+ }
+ out->bobCycle = prev->ps.bobCycle + f * ( i - prev->ps.bobCycle );
+
+ for ( i = 0 ; i < 3 ; i++ ) {
+ out->origin[i] = prev->ps.origin[i] + f * (next->ps.origin[i] - prev->ps.origin[i] );
+ if ( !grabAngles ) {
+ out->viewangles[i] = LerpAngle(
+ prev->ps.viewangles[i], next->ps.viewangles[i], f );
+ }
+ out->velocity[i] = prev->ps.velocity[i] +
+ f * (next->ps.velocity[i] - prev->ps.velocity[i] );
+ }
+
+}
+
+/*
+===================
+CG_TouchItem
+===================
+*/
+static void CG_TouchItem( centity_t *cent ) {
+ gitem_t *item;
+
+ if ( !cg_predictItems.integer ) {
+ return;
+ }
+ if ( !BG_PlayerTouchesItem( &cg.predictedPlayerState, &cent->currentState, cg.time ) ) {
+ return;
+ }
+
+ // never pick an item up twice in a prediction
+ if ( cent->miscTime == cg.time ) {
+ return;
+ }
+
+ if ( !BG_CanItemBeGrabbed( cgs.gametype, &cent->currentState, &cg.predictedPlayerState ) ) {
+ return; // can't hold it
+ }
+
+ item = &bg_itemlist[ cent->currentState.modelindex ];
+
+ // Special case for flags.
+ // We don't predict touching our own flag
+#ifdef MISSIONPACK
+ if( cgs.gametype == GT_1FCTF ) {
+ if( item->giTag != PW_NEUTRALFLAG ) {
+ return;
+ }
+ }
+ if( cgs.gametype == GT_CTF || cgs.gametype == GT_HARVESTER ) {
+#else
+ if( cgs.gametype == GT_CTF ) {
+#endif
+ if (cg.predictedPlayerState.persistant[PERS_TEAM] == TEAM_RED &&
+ item->giTag == PW_REDFLAG)
+ return;
+ if (cg.predictedPlayerState.persistant[PERS_TEAM] == TEAM_BLUE &&
+ item->giTag == PW_BLUEFLAG)
+ return;
+ }
+
+ // grab it
+ BG_AddPredictableEventToPlayerstate( EV_ITEM_PICKUP, cent->currentState.modelindex , &cg.predictedPlayerState);
+
+ // remove it from the frame so it won't be drawn
+ cent->currentState.eFlags |= EF_NODRAW;
+
+ // don't touch it again this prediction
+ cent->miscTime = cg.time;
+
+ // if its a weapon, give them some predicted ammo so the autoswitch will work
+ if ( item->giType == IT_WEAPON ) {
+ cg.predictedPlayerState.stats[ STAT_WEAPONS ] |= 1 << item->giTag;
+ if ( !cg.predictedPlayerState.ammo[ item->giTag ] ) {
+ cg.predictedPlayerState.ammo[ item->giTag ] = 1;
+ }
+ }
+}
+
+
+/*
+=========================
+CG_TouchTriggerPrediction
+
+Predict push triggers and items
+=========================
+*/
+static void CG_TouchTriggerPrediction( void ) {
+ int i;
+ trace_t trace;
+ entityState_t *ent;
+ clipHandle_t cmodel;
+ centity_t *cent;
+ qboolean spectator;
+
+ // dead clients don't activate triggers
+ if ( cg.predictedPlayerState.stats[STAT_HEALTH] <= 0 ) {
+ return;
+ }
+
+ spectator = ( cg.predictedPlayerState.pm_type == PM_SPECTATOR );
+
+ if ( cg.predictedPlayerState.pm_type != PM_NORMAL && !spectator ) {
+ return;
+ }
+
+ for ( i = 0 ; i < cg_numTriggerEntities ; i++ ) {
+ cent = cg_triggerEntities[ i ];
+ ent = &cent->currentState;
+
+ if ( ent->eType == ET_ITEM && !spectator ) {
+ CG_TouchItem( cent );
+ continue;
+ }
+
+ if ( ent->solid != SOLID_BMODEL ) {
+ continue;
+ }
+
+ cmodel = trap_CM_InlineModel( ent->modelindex );
+ if ( !cmodel ) {
+ continue;
+ }
+
+ trap_CM_BoxTrace( &trace, cg.predictedPlayerState.origin, cg.predictedPlayerState.origin,
+ cg_pmove.mins, cg_pmove.maxs, cmodel, -1 );
+
+ if ( !trace.startsolid ) {
+ continue;
+ }
+
+ if ( ent->eType == ET_TELEPORT_TRIGGER ) {
+ cg.hyperspace = qtrue;
+ } else if ( ent->eType == ET_PUSH_TRIGGER ) {
+ BG_TouchJumpPad( &cg.predictedPlayerState, ent );
+ }
+ }
+
+ // if we didn't touch a jump pad this pmove frame
+ if ( cg.predictedPlayerState.jumppad_frame != cg.predictedPlayerState.pmove_framecount ) {
+ cg.predictedPlayerState.jumppad_frame = 0;
+ cg.predictedPlayerState.jumppad_ent = 0;
+ }
+}
+
+
+
+/*
+=================
+CG_PredictPlayerState
+
+Generates cg.predictedPlayerState for the current cg.time
+cg.predictedPlayerState is guaranteed to be valid after exiting.
+
+For demo playback, this will be an interpolation between two valid
+playerState_t.
+
+For normal gameplay, it will be the result of predicted usercmd_t on
+top of the most recent playerState_t received from the server.
+
+Each new snapshot will usually have one or more new usercmd over the last,
+but we simulate all unacknowledged commands each time, not just the new ones.
+This means that on an internet connection, quite a few pmoves may be issued
+each frame.
+
+OPTIMIZE: don't re-simulate unless the newly arrived snapshot playerState_t
+differs from the predicted one. Would require saving all intermediate
+playerState_t during prediction.
+
+We detect prediction errors and allow them to be decayed off over several frames
+to ease the jerk.
+=================
+*/
+void CG_PredictPlayerState( void ) {
+ int cmdNum, current;
+ playerState_t oldPlayerState;
+ qboolean moved;
+ usercmd_t oldestCmd;
+ usercmd_t latestCmd;
+
+ cg.hyperspace = qfalse; // will be set if touching a trigger_teleport
+
+ // if this is the first frame we must guarantee
+ // predictedPlayerState is valid even if there is some
+ // other error condition
+ if ( !cg.validPPS ) {
+ cg.validPPS = qtrue;
+ cg.predictedPlayerState = cg.snap->ps;
+ }
+
+
+ // demo playback just copies the moves
+ if ( cg.demoPlayback || (cg.snap->ps.pm_flags & PMF_FOLLOW) ) {
+ CG_InterpolatePlayerState( qfalse );
+ return;
+ }
+
+ // non-predicting local movement will grab the latest angles
+ if ( cg_nopredict.integer || cg_synchronousClients.integer ) {
+ CG_InterpolatePlayerState( qtrue );
+ return;
+ }
+
+ // prepare for pmove
+ cg_pmove.ps = &cg.predictedPlayerState;
+ cg_pmove.trace = CG_Trace;
+ cg_pmove.pointcontents = CG_PointContents;
+ if ( cg_pmove.ps->pm_type == PM_DEAD ) {
+ cg_pmove.tracemask = MASK_PLAYERSOLID & ~CONTENTS_BODY;
+ }
+ else {
+ cg_pmove.tracemask = MASK_PLAYERSOLID;
+ }
+ if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR ) {
+ cg_pmove.tracemask &= ~CONTENTS_BODY; // spectators can fly through bodies
+ }
+ cg_pmove.noFootsteps = ( cgs.dmflags & DF_NO_FOOTSTEPS ) > 0;
+
+ // save the state before the pmove so we can detect transitions
+ oldPlayerState = cg.predictedPlayerState;
+
+ current = trap_GetCurrentCmdNumber();
+
+ // if we don't have the commands right after the snapshot, we
+ // can't accurately predict a current position, so just freeze at
+ // the last good position we had
+ cmdNum = current - CMD_BACKUP + 1;
+ trap_GetUserCmd( cmdNum, &oldestCmd );
+ if ( oldestCmd.serverTime > cg.snap->ps.commandTime
+ && oldestCmd.serverTime < cg.time ) { // special check for map_restart
+ if ( cg_showmiss.integer ) {
+ CG_Printf ("exceeded PACKET_BACKUP on commands\n");
+ }
+ return;
+ }
+
+ // get the latest command so we can know which commands are from previous map_restarts
+ trap_GetUserCmd( current, &latestCmd );
+
+ // get the most recent information we have, even if
+ // the server time is beyond our current cg.time,
+ // because predicted player positions are going to
+ // be ahead of everything else anyway
+ if ( cg.nextSnap && !cg.nextFrameTeleport && !cg.thisFrameTeleport ) {
+ cg.predictedPlayerState = cg.nextSnap->ps;
+ cg.physicsTime = cg.nextSnap->serverTime;
+ } else {
+ cg.predictedPlayerState = cg.snap->ps;
+ cg.physicsTime = cg.snap->serverTime;
+ }
+
+ if ( pmove_msec.integer < 8 ) {
+ trap_Cvar_Set("pmove_msec", "8");
+ }
+ else if (pmove_msec.integer > 33) {
+ trap_Cvar_Set("pmove_msec", "33");
+ }
+
+ cg_pmove.pmove_fixed = pmove_fixed.integer;// | cg_pmove_fixed.integer;
+ cg_pmove.pmove_msec = pmove_msec.integer;
+
+ // run cmds
+ moved = qfalse;
+ for ( cmdNum = current - CMD_BACKUP + 1 ; cmdNum <= current ; cmdNum++ ) {
+ // get the command
+ trap_GetUserCmd( cmdNum, &cg_pmove.cmd );
+
+ if ( cg_pmove.pmove_fixed ) {
+ PM_UpdateViewAngles( cg_pmove.ps, &cg_pmove.cmd );
+ }
+
+ // don't do anything if the time is before the snapshot player time
+ if ( cg_pmove.cmd.serverTime <= cg.predictedPlayerState.commandTime ) {
+ continue;
+ }
+
+ // don't do anything if the command was from a previous map_restart
+ if ( cg_pmove.cmd.serverTime > latestCmd.serverTime ) {
+ continue;
+ }
+
+ // check for a prediction error from last frame
+ // on a lan, this will often be the exact value
+ // from the snapshot, but on a wan we will have
+ // to predict several commands to get to the point
+ // we want to compare
+ if ( cg.predictedPlayerState.commandTime == oldPlayerState.commandTime ) {
+ vec3_t delta;
+ float len;
+
+ if ( cg.thisFrameTeleport ) {
+ // a teleport will not cause an error decay
+ VectorClear( cg.predictedError );
+ if ( cg_showmiss.integer ) {
+ CG_Printf( "PredictionTeleport\n" );
+ }
+ cg.thisFrameTeleport = qfalse;
+ } else {
+ vec3_t adjusted;
+ CG_AdjustPositionForMover( cg.predictedPlayerState.origin,
+ cg.predictedPlayerState.groundEntityNum, cg.physicsTime, cg.oldTime, adjusted );
+
+ if ( cg_showmiss.integer ) {
+ if (!VectorCompare( oldPlayerState.origin, adjusted )) {
+ CG_Printf("prediction error\n");
+ }
+ }
+ VectorSubtract( oldPlayerState.origin, adjusted, delta );
+ len = VectorLength( delta );
+ if ( len > 0.1 ) {
+ if ( cg_showmiss.integer ) {
+ CG_Printf("Prediction miss: %f\n", len);
+ }
+ if ( cg_errorDecay.integer ) {
+ int t;
+ float f;
+
+ t = cg.time - cg.predictedErrorTime;
+ f = ( cg_errorDecay.value - t ) / cg_errorDecay.value;
+ if ( f < 0 ) {
+ f = 0;
+ }
+ if ( f > 0 && cg_showmiss.integer ) {
+ CG_Printf("Double prediction decay: %f\n", f);
+ }
+ VectorScale( cg.predictedError, f, cg.predictedError );
+ } else {
+ VectorClear( cg.predictedError );
+ }
+ VectorAdd( delta, cg.predictedError, cg.predictedError );
+ cg.predictedErrorTime = cg.oldTime;
+ }
+ }
+ }
+
+ // don't predict gauntlet firing, which is only supposed to happen
+ // when it actually inflicts damage
+ cg_pmove.gauntletHit = qfalse;
+
+ if ( cg_pmove.pmove_fixed ) {
+ cg_pmove.cmd.serverTime = ((cg_pmove.cmd.serverTime + pmove_msec.integer-1) / pmove_msec.integer) * pmove_msec.integer;
+ }
+
+ Pmove (&cg_pmove);
+
+ moved = qtrue;
+
+ // add push trigger movement effects
+ CG_TouchTriggerPrediction();
+
+ // check for predictable events that changed from previous predictions
+ //CG_CheckChangedPredictableEvents(&cg.predictedPlayerState);
+ }
+
+ if ( cg_showmiss.integer > 1 ) {
+ CG_Printf( "[%i : %i] ", cg_pmove.cmd.serverTime, cg.time );
+ }
+
+ if ( !moved ) {
+ if ( cg_showmiss.integer ) {
+ CG_Printf( "not moved\n" );
+ }
+ return;
+ }
+
+ // adjust for the movement of the groundentity
+ CG_AdjustPositionForMover( cg.predictedPlayerState.origin,
+ cg.predictedPlayerState.groundEntityNum,
+ cg.physicsTime, cg.time, cg.predictedPlayerState.origin );
+
+ if ( cg_showmiss.integer ) {
+ if (cg.predictedPlayerState.eventSequence > oldPlayerState.eventSequence + MAX_PS_EVENTS) {
+ CG_Printf("WARNING: dropped event\n");
+ }
+ }
+
+ // fire events and other transition triggered things
+ CG_TransitionPlayerState( &cg.predictedPlayerState, &oldPlayerState );
+
+ if ( cg_showmiss.integer ) {
+ if (cg.eventSequence > cg.predictedPlayerState.eventSequence) {
+ CG_Printf("WARNING: double event\n");
+ cg.eventSequence = cg.predictedPlayerState.eventSequence;
+ }
+ }
+}
+
+
diff --git a/code/cgame/cg_public.h b/code/cgame/cg_public.h
new file mode 100755
index 0000000..8514143
--- /dev/null
+++ b/code/cgame/cg_public.h
@@ -0,0 +1,238 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+
+#define CMD_BACKUP 64
+#define CMD_MASK (CMD_BACKUP - 1)
+// allow a lot of command backups for very fast systems
+// multiple commands may be combined into a single packet, so this
+// needs to be larger than PACKET_BACKUP
+
+
+#define MAX_ENTITIES_IN_SNAPSHOT 256
+
+// snapshots are a view of the server at a given time
+
+// Snapshots are generated at regular time intervals by the server,
+// but they may not be sent if a client's rate level is exceeded, or
+// they may be dropped by the network.
+typedef struct {
+ int snapFlags; // SNAPFLAG_RATE_DELAYED, etc
+ int ping;
+
+ int serverTime; // server time the message is valid for (in msec)
+
+ byte areamask[MAX_MAP_AREA_BYTES]; // portalarea visibility bits
+
+ playerState_t ps; // complete information about the current player at this time
+
+ int numEntities; // all of the entities that need to be presented
+ entityState_t entities[MAX_ENTITIES_IN_SNAPSHOT]; // at the time of this snapshot
+
+ int numServerCommands; // text based server commands to execute when this
+ int serverCommandSequence; // snapshot becomes current
+} snapshot_t;
+
+enum {
+ CGAME_EVENT_NONE,
+ CGAME_EVENT_TEAMMENU,
+ CGAME_EVENT_SCOREBOARD,
+ CGAME_EVENT_EDITHUD
+};
+
+
+/*
+==================================================================
+
+functions imported from the main executable
+
+==================================================================
+*/
+
+#define CGAME_IMPORT_API_VERSION 4
+
+typedef enum {
+ CG_PRINT,
+ CG_ERROR,
+ CG_MILLISECONDS,
+ CG_CVAR_REGISTER,
+ CG_CVAR_UPDATE,
+ CG_CVAR_SET,
+ CG_CVAR_VARIABLESTRINGBUFFER,
+ CG_ARGC,
+ CG_ARGV,
+ CG_ARGS,
+ CG_FS_FOPENFILE,
+ CG_FS_READ,
+ CG_FS_WRITE,
+ CG_FS_FCLOSEFILE,
+ CG_SENDCONSOLECOMMAND,
+ CG_ADDCOMMAND,
+ CG_SENDCLIENTCOMMAND,
+ CG_UPDATESCREEN,
+ CG_CM_LOADMAP,
+ CG_CM_NUMINLINEMODELS,
+ CG_CM_INLINEMODEL,
+ CG_CM_LOADMODEL,
+ CG_CM_TEMPBOXMODEL,
+ CG_CM_POINTCONTENTS,
+ CG_CM_TRANSFORMEDPOINTCONTENTS,
+ CG_CM_BOXTRACE,
+ CG_CM_TRANSFORMEDBOXTRACE,
+ CG_CM_MARKFRAGMENTS,
+ CG_S_STARTSOUND,
+ CG_S_STARTLOCALSOUND,
+ CG_S_CLEARLOOPINGSOUNDS,
+ CG_S_ADDLOOPINGSOUND,
+ CG_S_UPDATEENTITYPOSITION,
+ CG_S_RESPATIALIZE,
+ CG_S_REGISTERSOUND,
+ CG_S_STARTBACKGROUNDTRACK,
+ CG_R_LOADWORLDMAP,
+ CG_R_REGISTERMODEL,
+ CG_R_REGISTERSKIN,
+ CG_R_REGISTERSHADER,
+ CG_R_CLEARSCENE,
+ CG_R_ADDREFENTITYTOSCENE,
+ CG_R_ADDPOLYTOSCENE,
+ CG_R_ADDLIGHTTOSCENE,
+ CG_R_RENDERSCENE,
+ CG_R_SETCOLOR,
+ CG_R_DRAWSTRETCHPIC,
+ CG_R_MODELBOUNDS,
+ CG_R_LERPTAG,
+ CG_GETGLCONFIG,
+ CG_GETGAMESTATE,
+ CG_GETCURRENTSNAPSHOTNUMBER,
+ CG_GETSNAPSHOT,
+ CG_GETSERVERCOMMAND,
+ CG_GETCURRENTCMDNUMBER,
+ CG_GETUSERCMD,
+ CG_SETUSERCMDVALUE,
+ CG_R_REGISTERSHADERNOMIP,
+ CG_MEMORY_REMAINING,
+ CG_R_REGISTERFONT,
+ CG_KEY_ISDOWN,
+ CG_KEY_GETCATCHER,
+ CG_KEY_SETCATCHER,
+ CG_KEY_GETKEY,
+ CG_PC_ADD_GLOBAL_DEFINE,
+ CG_PC_LOAD_SOURCE,
+ CG_PC_FREE_SOURCE,
+ CG_PC_READ_TOKEN,
+ CG_PC_SOURCE_FILE_AND_LINE,
+ CG_S_STOPBACKGROUNDTRACK,
+ CG_REAL_TIME,
+ CG_SNAPVECTOR,
+ CG_REMOVECOMMAND,
+ CG_R_LIGHTFORPOINT,
+ CG_CIN_PLAYCINEMATIC,
+ CG_CIN_STOPCINEMATIC,
+ CG_CIN_RUNCINEMATIC,
+ CG_CIN_DRAWCINEMATIC,
+ CG_CIN_SETEXTENTS,
+ CG_R_REMAP_SHADER,
+ CG_S_ADDREALLOOPINGSOUND,
+ CG_S_STOPLOOPINGSOUND,
+
+ CG_CM_TEMPCAPSULEMODEL,
+ CG_CM_CAPSULETRACE,
+ CG_CM_TRANSFORMEDCAPSULETRACE,
+ CG_R_ADDADDITIVELIGHTTOSCENE,
+ CG_GET_ENTITY_TOKEN,
+ CG_R_ADDPOLYSTOSCENE,
+ CG_R_INPVS,
+ // 1.32
+ CG_FS_SEEK,
+
+/*
+ CG_LOADCAMERA,
+ CG_STARTCAMERA,
+ CG_GETCAMERAINFO,
+*/
+
+ CG_MEMSET = 100,
+ CG_MEMCPY,
+ CG_STRNCPY,
+ CG_SIN,
+ CG_COS,
+ CG_ATAN2,
+ CG_SQRT,
+ CG_FLOOR,
+ CG_CEIL,
+ CG_TESTPRINTINT,
+ CG_TESTPRINTFLOAT,
+ CG_ACOS
+} cgameImport_t;
+
+
+/*
+==================================================================
+
+functions exported to the main executable
+
+==================================================================
+*/
+
+typedef enum {
+ CG_INIT,
+// void CG_Init( int serverMessageNum, int serverCommandSequence, int clientNum )
+ // called when the level loads or when the renderer is restarted
+ // all media should be registered at this time
+ // cgame will display loading status by calling SCR_Update, which
+ // will call CG_DrawInformation during the loading process
+ // reliableCommandSequence will be 0 on fresh loads, but higher for
+ // demos, tourney restarts, or vid_restarts
+
+ CG_SHUTDOWN,
+// void (*CG_Shutdown)( void );
+ // oportunity to flush and close any open files
+
+ CG_CONSOLE_COMMAND,
+// qboolean (*CG_ConsoleCommand)( void );
+ // a console command has been issued locally that is not recognized by the
+ // main game system.
+ // use Cmd_Argc() / Cmd_Argv() to read the command, return qfalse if the
+ // command is not known to the game
+
+ CG_DRAW_ACTIVE_FRAME,
+// void (*CG_DrawActiveFrame)( int serverTime, stereoFrame_t stereoView, qboolean demoPlayback );
+ // Generates and draws a game scene and status information at the given time.
+ // If demoPlayback is set, local movement prediction will not be enabled
+
+ CG_CROSSHAIR_PLAYER,
+// int (*CG_CrosshairPlayer)( void );
+
+ CG_LAST_ATTACKER,
+// int (*CG_LastAttacker)( void );
+
+ CG_KEY_EVENT,
+// void (*CG_KeyEvent)( int key, qboolean down );
+
+ CG_MOUSE_EVENT,
+// void (*CG_MouseEvent)( int dx, int dy );
+ CG_EVENT_HANDLING
+// void (*CG_EventHandling)(int type);
+} cgameExport_t;
+
+//----------------------------------------------
diff --git a/code/cgame/cg_scoreboard.c b/code/cgame/cg_scoreboard.c
new file mode 100755
index 0000000..25966c9
--- /dev/null
+++ b/code/cgame/cg_scoreboard.c
@@ -0,0 +1,534 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// cg_scoreboard -- draw the scoreboard on top of the game screen
+#include "cg_local.h"
+
+
+#define SCOREBOARD_X (0)
+
+#define SB_HEADER 86
+#define SB_TOP (SB_HEADER+32)
+
+// Where the status bar starts, so we don't overwrite it
+#define SB_STATUSBAR 420
+
+#define SB_NORMAL_HEIGHT 40
+#define SB_INTER_HEIGHT 16 // interleaved height
+
+#define SB_MAXCLIENTS_NORMAL ((SB_STATUSBAR - SB_TOP) / SB_NORMAL_HEIGHT)
+#define SB_MAXCLIENTS_INTER ((SB_STATUSBAR - SB_TOP) / SB_INTER_HEIGHT - 1)
+
+// Used when interleaved
+
+
+
+#define SB_LEFT_BOTICON_X (SCOREBOARD_X+0)
+#define SB_LEFT_HEAD_X (SCOREBOARD_X+32)
+#define SB_RIGHT_BOTICON_X (SCOREBOARD_X+64)
+#define SB_RIGHT_HEAD_X (SCOREBOARD_X+96)
+// Normal
+#define SB_BOTICON_X (SCOREBOARD_X+32)
+#define SB_HEAD_X (SCOREBOARD_X+64)
+
+#define SB_SCORELINE_X 112
+
+#define SB_RATING_WIDTH (6 * BIGCHAR_WIDTH) // width 6
+#define SB_SCORE_X (SB_SCORELINE_X + BIGCHAR_WIDTH) // width 6
+#define SB_RATING_X (SB_SCORELINE_X + 6 * BIGCHAR_WIDTH) // width 6
+#define SB_PING_X (SB_SCORELINE_X + 12 * BIGCHAR_WIDTH + 8) // width 5
+#define SB_TIME_X (SB_SCORELINE_X + 17 * BIGCHAR_WIDTH + 8) // width 5
+#define SB_NAME_X (SB_SCORELINE_X + 22 * BIGCHAR_WIDTH) // width 15
+
+// The new and improved score board
+//
+// In cases where the number of clients is high, the score board heads are interleaved
+// here's the layout
+
+//
+// 0 32 80 112 144 240 320 400 <-- pixel position
+// bot head bot head score ping time name
+//
+// wins/losses are drawn on bot icon now
+
+static qboolean localClient; // true if local client has been displayed
+
+
+ /*
+=================
+CG_DrawScoreboard
+=================
+*/
+static void CG_DrawClientScore( int y, score_t *score, float *color, float fade, qboolean largeFormat ) {
+ char string[1024];
+ vec3_t headAngles;
+ clientInfo_t *ci;
+ int iconx, headx;
+
+ if ( score->client < 0 || score->client >= cgs.maxclients ) {
+ Com_Printf( "Bad score->client: %i\n", score->client );
+ return;
+ }
+
+ ci = &cgs.clientinfo[score->client];
+
+ iconx = SB_BOTICON_X + (SB_RATING_WIDTH / 2);
+ headx = SB_HEAD_X + (SB_RATING_WIDTH / 2);
+
+ // draw the handicap or bot skill marker (unless player has flag)
+ if ( ci->powerups & ( 1 << PW_NEUTRALFLAG ) ) {
+ if( largeFormat ) {
+ CG_DrawFlagModel( iconx, y - ( 32 - BIGCHAR_HEIGHT ) / 2, 32, 32, TEAM_FREE, qfalse );
+ }
+ else {
+ CG_DrawFlagModel( iconx, y, 16, 16, TEAM_FREE, qfalse );
+ }
+ } else if ( ci->powerups & ( 1 << PW_REDFLAG ) ) {
+ if( largeFormat ) {
+ CG_DrawFlagModel( iconx, y - ( 32 - BIGCHAR_HEIGHT ) / 2, 32, 32, TEAM_RED, qfalse );
+ }
+ else {
+ CG_DrawFlagModel( iconx, y, 16, 16, TEAM_RED, qfalse );
+ }
+ } else if ( ci->powerups & ( 1 << PW_BLUEFLAG ) ) {
+ if( largeFormat ) {
+ CG_DrawFlagModel( iconx, y - ( 32 - BIGCHAR_HEIGHT ) / 2, 32, 32, TEAM_BLUE, qfalse );
+ }
+ else {
+ CG_DrawFlagModel( iconx, y, 16, 16, TEAM_BLUE, qfalse );
+ }
+ } else {
+ if ( ci->botSkill > 0 && ci->botSkill <= 5 ) {
+ if ( cg_drawIcons.integer ) {
+ if( largeFormat ) {
+ CG_DrawPic( iconx, y - ( 32 - BIGCHAR_HEIGHT ) / 2, 32, 32, cgs.media.botSkillShaders[ ci->botSkill - 1 ] );
+ }
+ else {
+ CG_DrawPic( iconx, y, 16, 16, cgs.media.botSkillShaders[ ci->botSkill - 1 ] );
+ }
+ }
+ } else if ( ci->handicap < 100 ) {
+ Com_sprintf( string, sizeof( string ), "%i", ci->handicap );
+ if ( cgs.gametype == GT_TOURNAMENT )
+ CG_DrawSmallStringColor( iconx, y - SMALLCHAR_HEIGHT/2, string, color );
+ else
+ CG_DrawSmallStringColor( iconx, y, string, color );
+ }
+
+ // draw the wins / losses
+ if ( cgs.gametype == GT_TOURNAMENT ) {
+ Com_sprintf( string, sizeof( string ), "%i/%i", ci->wins, ci->losses );
+ if( ci->handicap < 100 && !ci->botSkill ) {
+ CG_DrawSmallStringColor( iconx, y + SMALLCHAR_HEIGHT/2, string, color );
+ }
+ else {
+ CG_DrawSmallStringColor( iconx, y, string, color );
+ }
+ }
+ }
+
+ // draw the face
+ VectorClear( headAngles );
+ headAngles[YAW] = 180;
+ if( largeFormat ) {
+ CG_DrawHead( headx, y - ( ICON_SIZE - BIGCHAR_HEIGHT ) / 2, ICON_SIZE, ICON_SIZE,
+ score->client, headAngles );
+ }
+ else {
+ CG_DrawHead( headx, y, 16, 16, score->client, headAngles );
+ }
+
+#ifdef MISSIONPACK
+ // draw the team task
+ if ( ci->teamTask != TEAMTASK_NONE ) {
+ if ( ci->teamTask == TEAMTASK_OFFENSE ) {
+ CG_DrawPic( headx + 48, y, 16, 16, cgs.media.assaultShader );
+ }
+ else if ( ci->teamTask == TEAMTASK_DEFENSE ) {
+ CG_DrawPic( headx + 48, y, 16, 16, cgs.media.defendShader );
+ }
+ }
+#endif
+ // draw the score line
+ if ( score->ping == -1 ) {
+ Com_sprintf(string, sizeof(string),
+ " connecting %s", ci->name);
+ } else if ( ci->team == TEAM_SPECTATOR ) {
+ Com_sprintf(string, sizeof(string),
+ " SPECT %3i %4i %s", score->ping, score->time, ci->name);
+ } else {
+ Com_sprintf(string, sizeof(string),
+ "%5i %4i %4i %s", score->score, score->ping, score->time, ci->name);
+ }
+
+ // highlight your position
+ if ( score->client == cg.snap->ps.clientNum ) {
+ float hcolor[4];
+ int rank;
+
+ localClient = qtrue;
+
+ if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR
+ || cgs.gametype >= GT_TEAM ) {
+ rank = -1;
+ } else {
+ rank = cg.snap->ps.persistant[PERS_RANK] & ~RANK_TIED_FLAG;
+ }
+ if ( rank == 0 ) {
+ hcolor[0] = 0;
+ hcolor[1] = 0;
+ hcolor[2] = 0.7f;
+ } else if ( rank == 1 ) {
+ hcolor[0] = 0.7f;
+ hcolor[1] = 0;
+ hcolor[2] = 0;
+ } else if ( rank == 2 ) {
+ hcolor[0] = 0.7f;
+ hcolor[1] = 0.7f;
+ hcolor[2] = 0;
+ } else {
+ hcolor[0] = 0.7f;
+ hcolor[1] = 0.7f;
+ hcolor[2] = 0.7f;
+ }
+
+ hcolor[3] = fade * 0.7;
+ CG_FillRect( SB_SCORELINE_X + BIGCHAR_WIDTH + (SB_RATING_WIDTH / 2), y,
+ 640 - SB_SCORELINE_X - BIGCHAR_WIDTH, BIGCHAR_HEIGHT+1, hcolor );
+ }
+
+ CG_DrawBigString( SB_SCORELINE_X + (SB_RATING_WIDTH / 2), y, string, fade );
+
+ // add the "ready" marker for intermission exiting
+ if ( cg.snap->ps.stats[ STAT_CLIENTS_READY ] & ( 1 << score->client ) ) {
+ CG_DrawBigStringColor( iconx, y, "READY", color );
+ }
+}
+
+/*
+=================
+CG_TeamScoreboard
+=================
+*/
+static int CG_TeamScoreboard( int y, team_t team, float fade, int maxClients, int lineHeight ) {
+ int i;
+ score_t *score;
+ float color[4];
+ int count;
+ clientInfo_t *ci;
+
+ color[0] = color[1] = color[2] = 1.0;
+ color[3] = fade;
+
+ count = 0;
+ for ( i = 0 ; i < cg.numScores && count < maxClients ; i++ ) {
+ score = &cg.scores[i];
+ ci = &cgs.clientinfo[ score->client ];
+
+ if ( team != ci->team ) {
+ continue;
+ }
+
+ CG_DrawClientScore( y + lineHeight * count, score, color, fade, lineHeight == SB_NORMAL_HEIGHT );
+
+ count++;
+ }
+
+ return count;
+}
+
+/*
+=================
+CG_DrawScoreboard
+
+Draw the normal in-game scoreboard
+=================
+*/
+qboolean CG_DrawOldScoreboard( void ) {
+ int x, y, w, i, n1, n2;
+ float fade;
+ float *fadeColor;
+ char *s;
+ int maxClients;
+ int lineHeight;
+ int topBorderSize, bottomBorderSize;
+
+ // don't draw amuthing if the menu or console is up
+ if ( cg_paused.integer ) {
+ cg.deferredPlayerLoading = 0;
+ return qfalse;
+ }
+
+ if ( cgs.gametype == GT_SINGLE_PLAYER && cg.predictedPlayerState.pm_type == PM_INTERMISSION ) {
+ cg.deferredPlayerLoading = 0;
+ return qfalse;
+ }
+
+ // don't draw scoreboard during death while warmup up
+ if ( cg.warmup && !cg.showScores ) {
+ return qfalse;
+ }
+
+ if ( cg.showScores || cg.predictedPlayerState.pm_type == PM_DEAD ||
+ cg.predictedPlayerState.pm_type == PM_INTERMISSION ) {
+ fade = 1.0;
+ fadeColor = colorWhite;
+ } else {
+ fadeColor = CG_FadeColor( cg.scoreFadeTime, FADE_TIME );
+
+ if ( !fadeColor ) {
+ // next time scoreboard comes up, don't print killer
+ cg.deferredPlayerLoading = 0;
+ cg.killerName[0] = 0;
+ return qfalse;
+ }
+ fade = *fadeColor;
+ }
+
+
+ // fragged by ... line
+ if ( cg.killerName[0] ) {
+ s = va("Fragged by %s", cg.killerName );
+ w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH;
+ x = ( SCREEN_WIDTH - w ) / 2;
+ y = 40;
+ CG_DrawBigString( x, y, s, fade );
+ }
+
+ // current rank
+ if ( cgs.gametype < GT_TEAM) {
+ if (cg.snap->ps.persistant[PERS_TEAM] != TEAM_SPECTATOR ) {
+ s = va("%s place with %i",
+ CG_PlaceString( cg.snap->ps.persistant[PERS_RANK] + 1 ),
+ cg.snap->ps.persistant[PERS_SCORE] );
+ w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH;
+ x = ( SCREEN_WIDTH - w ) / 2;
+ y = 60;
+ CG_DrawBigString( x, y, s, fade );
+ }
+ } else {
+ if ( cg.teamScores[0] == cg.teamScores[1] ) {
+ s = va("Teams are tied at %i", cg.teamScores[0] );
+ } else if ( cg.teamScores[0] >= cg.teamScores[1] ) {
+ s = va("Red leads %i to %i",cg.teamScores[0], cg.teamScores[1] );
+ } else {
+ s = va("Blue leads %i to %i",cg.teamScores[1], cg.teamScores[0] );
+ }
+
+ w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH;
+ x = ( SCREEN_WIDTH - w ) / 2;
+ y = 60;
+ CG_DrawBigString( x, y, s, fade );
+ }
+
+ // scoreboard
+ y = SB_HEADER;
+
+ CG_DrawPic( SB_SCORE_X + (SB_RATING_WIDTH / 2), y, 64, 32, cgs.media.scoreboardScore );
+ CG_DrawPic( SB_PING_X - (SB_RATING_WIDTH / 2), y, 64, 32, cgs.media.scoreboardPing );
+ CG_DrawPic( SB_TIME_X - (SB_RATING_WIDTH / 2), y, 64, 32, cgs.media.scoreboardTime );
+ CG_DrawPic( SB_NAME_X - (SB_RATING_WIDTH / 2), y, 64, 32, cgs.media.scoreboardName );
+
+ y = SB_TOP;
+
+ // If there are more than SB_MAXCLIENTS_NORMAL, use the interleaved scores
+ if ( cg.numScores > SB_MAXCLIENTS_NORMAL ) {
+ maxClients = SB_MAXCLIENTS_INTER;
+ lineHeight = SB_INTER_HEIGHT;
+ topBorderSize = 8;
+ bottomBorderSize = 16;
+ } else {
+ maxClients = SB_MAXCLIENTS_NORMAL;
+ lineHeight = SB_NORMAL_HEIGHT;
+ topBorderSize = 16;
+ bottomBorderSize = 16;
+ }
+
+ localClient = qfalse;
+
+ if ( cgs.gametype >= GT_TEAM ) {
+ //
+ // teamplay scoreboard
+ //
+ y += lineHeight/2;
+
+ if ( cg.teamScores[0] >= cg.teamScores[1] ) {
+ n1 = CG_TeamScoreboard( y, TEAM_RED, fade, maxClients, lineHeight );
+ CG_DrawTeamBackground( 0, y - topBorderSize, 640, n1 * lineHeight + bottomBorderSize, 0.33f, TEAM_RED );
+ y += (n1 * lineHeight) + BIGCHAR_HEIGHT;
+ maxClients -= n1;
+ n2 = CG_TeamScoreboard( y, TEAM_BLUE, fade, maxClients, lineHeight );
+ CG_DrawTeamBackground( 0, y - topBorderSize, 640, n2 * lineHeight + bottomBorderSize, 0.33f, TEAM_BLUE );
+ y += (n2 * lineHeight) + BIGCHAR_HEIGHT;
+ maxClients -= n2;
+ } else {
+ n1 = CG_TeamScoreboard( y, TEAM_BLUE, fade, maxClients, lineHeight );
+ CG_DrawTeamBackground( 0, y - topBorderSize, 640, n1 * lineHeight + bottomBorderSize, 0.33f, TEAM_BLUE );
+ y += (n1 * lineHeight) + BIGCHAR_HEIGHT;
+ maxClients -= n1;
+ n2 = CG_TeamScoreboard( y, TEAM_RED, fade, maxClients, lineHeight );
+ CG_DrawTeamBackground( 0, y - topBorderSize, 640, n2 * lineHeight + bottomBorderSize, 0.33f, TEAM_RED );
+ y += (n2 * lineHeight) + BIGCHAR_HEIGHT;
+ maxClients -= n2;
+ }
+ n1 = CG_TeamScoreboard( y, TEAM_SPECTATOR, fade, maxClients, lineHeight );
+ y += (n1 * lineHeight) + BIGCHAR_HEIGHT;
+
+ } else {
+ //
+ // free for all scoreboard
+ //
+ n1 = CG_TeamScoreboard( y, TEAM_FREE, fade, maxClients, lineHeight );
+ y += (n1 * lineHeight) + BIGCHAR_HEIGHT;
+ n2 = CG_TeamScoreboard( y, TEAM_SPECTATOR, fade, maxClients - n1, lineHeight );
+ y += (n2 * lineHeight) + BIGCHAR_HEIGHT;
+ }
+
+ if (!localClient) {
+ // draw local client at the bottom
+ for ( i = 0 ; i < cg.numScores ; i++ ) {
+ if ( cg.scores[i].client == cg.snap->ps.clientNum ) {
+ CG_DrawClientScore( y, &cg.scores[i], fadeColor, fade, lineHeight == SB_NORMAL_HEIGHT );
+ break;
+ }
+ }
+ }
+
+ // load any models that have been deferred
+ if ( ++cg.deferredPlayerLoading > 10 ) {
+ CG_LoadDeferredPlayers();
+ }
+
+ return qtrue;
+}
+
+//================================================================================
+
+/*
+================
+CG_CenterGiantLine
+================
+*/
+static void CG_CenterGiantLine( float y, const char *string ) {
+ float x;
+ vec4_t color;
+
+ color[0] = 1;
+ color[1] = 1;
+ color[2] = 1;
+ color[3] = 1;
+
+ x = 0.5 * ( 640 - GIANT_WIDTH * CG_DrawStrlen( string ) );
+
+ CG_DrawStringExt( x, y, string, color, qtrue, qtrue, GIANT_WIDTH, GIANT_HEIGHT, 0 );
+}
+
+/*
+=================
+CG_DrawTourneyScoreboard
+
+Draw the oversize scoreboard for tournements
+=================
+*/
+void CG_DrawOldTourneyScoreboard( void ) {
+ const char *s;
+ vec4_t color;
+ int min, tens, ones;
+ clientInfo_t *ci;
+ int y;
+ int i;
+
+ // request more scores regularly
+ if ( cg.scoresRequestTime + 2000 < cg.time ) {
+ cg.scoresRequestTime = cg.time;
+ trap_SendClientCommand( "score" );
+ }
+
+ color[0] = 1;
+ color[1] = 1;
+ color[2] = 1;
+ color[3] = 1;
+
+ // draw the dialog background
+ color[0] = color[1] = color[2] = 0;
+ color[3] = 1;
+ CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, color );
+
+ // print the mesage of the day
+ s = CG_ConfigString( CS_MOTD );
+ if ( !s[0] ) {
+ s = "Scoreboard";
+ }
+
+ // print optional title
+ CG_CenterGiantLine( 8, s );
+
+ // print server time
+ ones = cg.time / 1000;
+ min = ones / 60;
+ ones %= 60;
+ tens = ones / 10;
+ ones %= 10;
+ s = va("%i:%i%i", min, tens, ones );
+
+ CG_CenterGiantLine( 64, s );
+
+
+ // print the two scores
+
+ y = 160;
+ if ( cgs.gametype >= GT_TEAM ) {
+ //
+ // teamplay scoreboard
+ //
+ CG_DrawStringExt( 8, y, "Red Team", color, qtrue, qtrue, GIANT_WIDTH, GIANT_HEIGHT, 0 );
+ s = va("%i", cg.teamScores[0] );
+ CG_DrawStringExt( 632 - GIANT_WIDTH * strlen(s), y, s, color, qtrue, qtrue, GIANT_WIDTH, GIANT_HEIGHT, 0 );
+
+ y += 64;
+
+ CG_DrawStringExt( 8, y, "Blue Team", color, qtrue, qtrue, GIANT_WIDTH, GIANT_HEIGHT, 0 );
+ s = va("%i", cg.teamScores[1] );
+ CG_DrawStringExt( 632 - GIANT_WIDTH * strlen(s), y, s, color, qtrue, qtrue, GIANT_WIDTH, GIANT_HEIGHT, 0 );
+ } else {
+ //
+ // free for all scoreboard
+ //
+ for ( i = 0 ; i < MAX_CLIENTS ; i++ ) {
+ ci = &cgs.clientinfo[i];
+ if ( !ci->infoValid ) {
+ continue;
+ }
+ if ( ci->team != TEAM_FREE ) {
+ continue;
+ }
+
+ CG_DrawStringExt( 8, y, ci->name, color, qtrue, qtrue, GIANT_WIDTH, GIANT_HEIGHT, 0 );
+ s = va("%i", ci->score );
+ CG_DrawStringExt( 632 - GIANT_WIDTH * strlen(s), y, s, color, qtrue, qtrue, GIANT_WIDTH, GIANT_HEIGHT, 0 );
+ y += 64;
+ }
+ }
+
+
+}
+
diff --git a/code/cgame/cg_servercmds.c b/code/cgame/cg_servercmds.c
new file mode 100755
index 0000000..d12cd97
--- /dev/null
+++ b/code/cgame/cg_servercmds.c
@@ -0,0 +1,1098 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// cg_servercmds.c -- reliably sequenced text commands sent by the server
+// these are processed at snapshot transition time, so there will definately
+// be a valid snapshot this frame
+
+#include "cg_local.h"
+#include "../../ui/menudef.h" // bk001205 - for Q3_ui as well
+
+typedef struct {
+ const char *order;
+ int taskNum;
+} orderTask_t;
+
+static const orderTask_t validOrders[] = {
+ { VOICECHAT_GETFLAG, TEAMTASK_OFFENSE },
+ { VOICECHAT_OFFENSE, TEAMTASK_OFFENSE },
+ { VOICECHAT_DEFEND, TEAMTASK_DEFENSE },
+ { VOICECHAT_DEFENDFLAG, TEAMTASK_DEFENSE },
+ { VOICECHAT_PATROL, TEAMTASK_PATROL },
+ { VOICECHAT_CAMP, TEAMTASK_CAMP },
+ { VOICECHAT_FOLLOWME, TEAMTASK_FOLLOW },
+ { VOICECHAT_RETURNFLAG, TEAMTASK_RETRIEVE },
+ { VOICECHAT_FOLLOWFLAGCARRIER, TEAMTASK_ESCORT }
+};
+
+static const int numValidOrders = sizeof(validOrders) / sizeof(orderTask_t);
+
+#ifdef MISSIONPACK // bk001204
+static int CG_ValidOrder(const char *p) {
+ int i;
+ for (i = 0; i < numValidOrders; i++) {
+ if (Q_stricmp(p, validOrders[i].order) == 0) {
+ return validOrders[i].taskNum;
+ }
+ }
+ return -1;
+}
+#endif
+
+/*
+=================
+CG_ParseScores
+
+=================
+*/
+static void CG_ParseScores( void ) {
+ int i, powerups;
+
+ cg.numScores = atoi( CG_Argv( 1 ) );
+ if ( cg.numScores > MAX_CLIENTS ) {
+ cg.numScores = MAX_CLIENTS;
+ }
+
+ cg.teamScores[0] = atoi( CG_Argv( 2 ) );
+ cg.teamScores[1] = atoi( CG_Argv( 3 ) );
+
+ memset( cg.scores, 0, sizeof( cg.scores ) );
+ for ( i = 0 ; i < cg.numScores ; i++ ) {
+ //
+ cg.scores[i].client = atoi( CG_Argv( i * 14 + 4 ) );
+ cg.scores[i].score = atoi( CG_Argv( i * 14 + 5 ) );
+ cg.scores[i].ping = atoi( CG_Argv( i * 14 + 6 ) );
+ cg.scores[i].time = atoi( CG_Argv( i * 14 + 7 ) );
+ cg.scores[i].scoreFlags = atoi( CG_Argv( i * 14 + 8 ) );
+ powerups = atoi( CG_Argv( i * 14 + 9 ) );
+ cg.scores[i].accuracy = atoi(CG_Argv(i * 14 + 10));
+ cg.scores[i].impressiveCount = atoi(CG_Argv(i * 14 + 11));
+ cg.scores[i].excellentCount = atoi(CG_Argv(i * 14 + 12));
+ cg.scores[i].guantletCount = atoi(CG_Argv(i * 14 + 13));
+ cg.scores[i].defendCount = atoi(CG_Argv(i * 14 + 14));
+ cg.scores[i].assistCount = atoi(CG_Argv(i * 14 + 15));
+ cg.scores[i].perfect = atoi(CG_Argv(i * 14 + 16));
+ cg.scores[i].captures = atoi(CG_Argv(i * 14 + 17));
+
+ if ( cg.scores[i].client < 0 || cg.scores[i].client >= MAX_CLIENTS ) {
+ cg.scores[i].client = 0;
+ }
+ cgs.clientinfo[ cg.scores[i].client ].score = cg.scores[i].score;
+ cgs.clientinfo[ cg.scores[i].client ].powerups = powerups;
+
+ cg.scores[i].team = cgs.clientinfo[cg.scores[i].client].team;
+ }
+#ifdef MISSIONPACK
+ CG_SetScoreSelection(NULL);
+#endif
+
+}
+
+/*
+=================
+CG_ParseTeamInfo
+
+=================
+*/
+static void CG_ParseTeamInfo( void ) {
+ int i;
+ int client;
+
+ numSortedTeamPlayers = atoi( CG_Argv( 1 ) );
+
+ for ( i = 0 ; i < numSortedTeamPlayers ; i++ ) {
+ client = atoi( CG_Argv( i * 6 + 2 ) );
+
+ sortedTeamPlayers[i] = client;
+
+ cgs.clientinfo[ client ].location = atoi( CG_Argv( i * 6 + 3 ) );
+ cgs.clientinfo[ client ].health = atoi( CG_Argv( i * 6 + 4 ) );
+ cgs.clientinfo[ client ].armor = atoi( CG_Argv( i * 6 + 5 ) );
+ cgs.clientinfo[ client ].curWeapon = atoi( CG_Argv( i * 6 + 6 ) );
+ cgs.clientinfo[ client ].powerups = atoi( CG_Argv( i * 6 + 7 ) );
+ }
+}
+
+
+/*
+================
+CG_ParseServerinfo
+
+This is called explicitly when the gamestate is first received,
+and whenever the server updates any serverinfo flagged cvars
+================
+*/
+void CG_ParseServerinfo( void ) {
+ const char *info;
+ char *mapname;
+
+ info = CG_ConfigString( CS_SERVERINFO );
+ cgs.gametype = atoi( Info_ValueForKey( info, "g_gametype" ) );
+ trap_Cvar_Set("g_gametype", va("%i", cgs.gametype));
+ cgs.dmflags = atoi( Info_ValueForKey( info, "dmflags" ) );
+ cgs.teamflags = atoi( Info_ValueForKey( info, "teamflags" ) );
+ cgs.fraglimit = atoi( Info_ValueForKey( info, "fraglimit" ) );
+ cgs.capturelimit = atoi( Info_ValueForKey( info, "capturelimit" ) );
+ cgs.timelimit = atoi( Info_ValueForKey( info, "timelimit" ) );
+ cgs.maxclients = atoi( Info_ValueForKey( info, "sv_maxclients" ) );
+ mapname = Info_ValueForKey( info, "mapname" );
+ Com_sprintf( cgs.mapname, sizeof( cgs.mapname ), "maps/%s.bsp", mapname );
+ Q_strncpyz( cgs.redTeam, Info_ValueForKey( info, "g_redTeam" ), sizeof(cgs.redTeam) );
+ trap_Cvar_Set("g_redTeam", cgs.redTeam);
+ Q_strncpyz( cgs.blueTeam, Info_ValueForKey( info, "g_blueTeam" ), sizeof(cgs.blueTeam) );
+ trap_Cvar_Set("g_blueTeam", cgs.blueTeam);
+}
+
+/*
+==================
+CG_ParseWarmup
+==================
+*/
+static void CG_ParseWarmup( void ) {
+ const char *info;
+ int warmup;
+
+ info = CG_ConfigString( CS_WARMUP );
+
+ warmup = atoi( info );
+ cg.warmupCount = -1;
+
+ if ( warmup == 0 && cg.warmup ) {
+
+ } else if ( warmup > 0 && cg.warmup <= 0 ) {
+#ifdef MISSIONPACK
+ if (cgs.gametype >= GT_CTF && cgs.gametype <= GT_HARVESTER) {
+ trap_S_StartLocalSound( cgs.media.countPrepareTeamSound, CHAN_ANNOUNCER );
+ } else
+#endif
+ {
+ trap_S_StartLocalSound( cgs.media.countPrepareSound, CHAN_ANNOUNCER );
+ }
+ }
+
+ cg.warmup = warmup;
+}
+
+/*
+================
+CG_SetConfigValues
+
+Called on load to set the initial values from configure strings
+================
+*/
+void CG_SetConfigValues( void ) {
+ const char *s;
+
+ cgs.scores1 = atoi( CG_ConfigString( CS_SCORES1 ) );
+ cgs.scores2 = atoi( CG_ConfigString( CS_SCORES2 ) );
+ cgs.levelStartTime = atoi( CG_ConfigString( CS_LEVEL_START_TIME ) );
+ if( cgs.gametype == GT_CTF ) {
+ s = CG_ConfigString( CS_FLAGSTATUS );
+ cgs.redflag = s[0] - '0';
+ cgs.blueflag = s[1] - '0';
+ }
+#ifdef MISSIONPACK
+ else if( cgs.gametype == GT_1FCTF ) {
+ s = CG_ConfigString( CS_FLAGSTATUS );
+ cgs.flagStatus = s[0] - '0';
+ }
+#endif
+ cg.warmup = atoi( CG_ConfigString( CS_WARMUP ) );
+}
+
+/*
+=====================
+CG_ShaderStateChanged
+=====================
+*/
+void CG_ShaderStateChanged(void) {
+ char originalShader[MAX_QPATH];
+ char newShader[MAX_QPATH];
+ char timeOffset[16];
+ const char *o;
+ char *n,*t;
+
+ o = CG_ConfigString( CS_SHADERSTATE );
+ while (o && *o) {
+ n = strstr(o, "=");
+ if (n && *n) {
+ strncpy(originalShader, o, n-o);
+ originalShader[n-o] = 0;
+ n++;
+ t = strstr(n, ":");
+ if (t && *t) {
+ strncpy(newShader, n, t-n);
+ newShader[t-n] = 0;
+ } else {
+ break;
+ }
+ t++;
+ o = strstr(t, "@");
+ if (o) {
+ strncpy(timeOffset, t, o-t);
+ timeOffset[o-t] = 0;
+ o++;
+ trap_R_RemapShader( originalShader, newShader, timeOffset );
+ }
+ } else {
+ break;
+ }
+ }
+}
+
+/*
+================
+CG_ConfigStringModified
+
+================
+*/
+static void CG_ConfigStringModified( void ) {
+ const char *str;
+ int num;
+
+ num = atoi( CG_Argv( 1 ) );
+
+ // get the gamestate from the client system, which will have the
+ // new configstring already integrated
+ trap_GetGameState( &cgs.gameState );
+
+ // look up the individual string that was modified
+ str = CG_ConfigString( num );
+
+ // do something with it if necessary
+ if ( num == CS_MUSIC ) {
+ CG_StartMusic();
+ } else if ( num == CS_SERVERINFO ) {
+ CG_ParseServerinfo();
+ } else if ( num == CS_WARMUP ) {
+ CG_ParseWarmup();
+ } else if ( num == CS_SCORES1 ) {
+ cgs.scores1 = atoi( str );
+ } else if ( num == CS_SCORES2 ) {
+ cgs.scores2 = atoi( str );
+ } else if ( num == CS_LEVEL_START_TIME ) {
+ cgs.levelStartTime = atoi( str );
+ } else if ( num == CS_VOTE_TIME ) {
+ cgs.voteTime = atoi( str );
+ cgs.voteModified = qtrue;
+ } else if ( num == CS_VOTE_YES ) {
+ cgs.voteYes = atoi( str );
+ cgs.voteModified = qtrue;
+ } else if ( num == CS_VOTE_NO ) {
+ cgs.voteNo = atoi( str );
+ cgs.voteModified = qtrue;
+ } else if ( num == CS_VOTE_STRING ) {
+ Q_strncpyz( cgs.voteString, str, sizeof( cgs.voteString ) );
+#ifdef MISSIONPACK
+ trap_S_StartLocalSound( cgs.media.voteNow, CHAN_ANNOUNCER );
+#endif //MISSIONPACK
+ } else if ( num >= CS_TEAMVOTE_TIME && num <= CS_TEAMVOTE_TIME + 1) {
+ cgs.teamVoteTime[num-CS_TEAMVOTE_TIME] = atoi( str );
+ cgs.teamVoteModified[num-CS_TEAMVOTE_TIME] = qtrue;
+ } else if ( num >= CS_TEAMVOTE_YES && num <= CS_TEAMVOTE_YES + 1) {
+ cgs.teamVoteYes[num-CS_TEAMVOTE_YES] = atoi( str );
+ cgs.teamVoteModified[num-CS_TEAMVOTE_YES] = qtrue;
+ } else if ( num >= CS_TEAMVOTE_NO && num <= CS_TEAMVOTE_NO + 1) {
+ cgs.teamVoteNo[num-CS_TEAMVOTE_NO] = atoi( str );
+ cgs.teamVoteModified[num-CS_TEAMVOTE_NO] = qtrue;
+ } else if ( num >= CS_TEAMVOTE_STRING && num <= CS_TEAMVOTE_STRING + 1) {
+ Q_strncpyz( cgs.teamVoteString[num-CS_TEAMVOTE_STRING], str, sizeof( cgs.teamVoteString ) );
+#ifdef MISSIONPACK
+ trap_S_StartLocalSound( cgs.media.voteNow, CHAN_ANNOUNCER );
+#endif
+ } else if ( num == CS_INTERMISSION ) {
+ cg.intermissionStarted = atoi( str );
+ } else if ( num >= CS_MODELS && num < CS_MODELS+MAX_MODELS ) {
+ cgs.gameModels[ num-CS_MODELS ] = trap_R_RegisterModel( str );
+ } else if ( num >= CS_SOUNDS && num < CS_SOUNDS+MAX_MODELS ) {
+ if ( str[0] != '*' ) { // player specific sounds don't register here
+ cgs.gameSounds[ num-CS_SOUNDS] = trap_S_RegisterSound( str, qfalse );
+ }
+ } else if ( num >= CS_PLAYERS && num < CS_PLAYERS+MAX_CLIENTS ) {
+ CG_NewClientInfo( num - CS_PLAYERS );
+ CG_BuildSpectatorString();
+ } else if ( num == CS_FLAGSTATUS ) {
+ if( cgs.gametype == GT_CTF ) {
+ // format is rb where its red/blue, 0 is at base, 1 is taken, 2 is dropped
+ cgs.redflag = str[0] - '0';
+ cgs.blueflag = str[1] - '0';
+ }
+#ifdef MISSIONPACK
+ else if( cgs.gametype == GT_1FCTF ) {
+ cgs.flagStatus = str[0] - '0';
+ }
+#endif
+ }
+ else if ( num == CS_SHADERSTATE ) {
+ CG_ShaderStateChanged();
+ }
+
+}
+
+
+/*
+=======================
+CG_AddToTeamChat
+
+=======================
+*/
+static void CG_AddToTeamChat( const char *str ) {
+ int len;
+ char *p, *ls;
+ int lastcolor;
+ int chatHeight;
+
+ if (cg_teamChatHeight.integer < TEAMCHAT_HEIGHT) {
+ chatHeight = cg_teamChatHeight.integer;
+ } else {
+ chatHeight = TEAMCHAT_HEIGHT;
+ }
+
+ if (chatHeight <= 0 || cg_teamChatTime.integer <= 0) {
+ // team chat disabled, dump into normal chat
+ cgs.teamChatPos = cgs.teamLastChatPos = 0;
+ return;
+ }
+
+ len = 0;
+
+ p = cgs.teamChatMsgs[cgs.teamChatPos % chatHeight];
+ *p = 0;
+
+ lastcolor = '7';
+
+ ls = NULL;
+ while (*str) {
+ if (len > TEAMCHAT_WIDTH - 1) {
+ if (ls) {
+ str -= (p - ls);
+ str++;
+ p -= (p - ls);
+ }
+ *p = 0;
+
+ cgs.teamChatMsgTimes[cgs.teamChatPos % chatHeight] = cg.time;
+
+ cgs.teamChatPos++;
+ p = cgs.teamChatMsgs[cgs.teamChatPos % chatHeight];
+ *p = 0;
+ *p++ = Q_COLOR_ESCAPE;
+ *p++ = lastcolor;
+ len = 0;
+ ls = NULL;
+ }
+
+ if ( Q_IsColorString( str ) ) {
+ *p++ = *str++;
+ lastcolor = *str;
+ *p++ = *str++;
+ continue;
+ }
+ if (*str == ' ') {
+ ls = p;
+ }
+ *p++ = *str++;
+ len++;
+ }
+ *p = 0;
+
+ cgs.teamChatMsgTimes[cgs.teamChatPos % chatHeight] = cg.time;
+ cgs.teamChatPos++;
+
+ if (cgs.teamChatPos - cgs.teamLastChatPos > chatHeight)
+ cgs.teamLastChatPos = cgs.teamChatPos - chatHeight;
+}
+
+/*
+===============
+CG_MapRestart
+
+The server has issued a map_restart, so the next snapshot
+is completely new and should not be interpolated to.
+
+A tournement restart will clear everything, but doesn't
+require a reload of all the media
+===============
+*/
+static void CG_MapRestart( void ) {
+ if ( cg_showmiss.integer ) {
+ CG_Printf( "CG_MapRestart\n" );
+ }
+
+ CG_InitLocalEntities();
+ CG_InitMarkPolys();
+ CG_ClearParticles ();
+
+ // make sure the "3 frags left" warnings play again
+ cg.fraglimitWarnings = 0;
+
+ cg.timelimitWarnings = 0;
+
+ cg.intermissionStarted = qfalse;
+
+ cgs.voteTime = 0;
+
+ cg.mapRestart = qtrue;
+
+ CG_StartMusic();
+
+ trap_S_ClearLoopingSounds(qtrue);
+
+ // we really should clear more parts of cg here and stop sounds
+
+ // play the "fight" sound if this is a restart without warmup
+ if ( cg.warmup == 0 /* && cgs.gametype == GT_TOURNAMENT */) {
+ trap_S_StartLocalSound( cgs.media.countFightSound, CHAN_ANNOUNCER );
+ CG_CenterPrint( "FIGHT!", 120, GIANTCHAR_WIDTH*2 );
+ }
+#ifdef MISSIONPACK
+ if (cg_singlePlayerActive.integer) {
+ trap_Cvar_Set("ui_matchStartTime", va("%i", cg.time));
+ if (cg_recordSPDemo.integer && cg_recordSPDemoName.string && *cg_recordSPDemoName.string) {
+ trap_SendConsoleCommand(va("set g_synchronousclients 1 ; record %s \n", cg_recordSPDemoName.string));
+ }
+ }
+#endif
+ trap_Cvar_Set("cg_thirdPerson", "0");
+}
+
+#define MAX_VOICEFILESIZE 16384
+#define MAX_VOICEFILES 8
+#define MAX_VOICECHATS 64
+#define MAX_VOICESOUNDS 64
+#define MAX_CHATSIZE 64
+#define MAX_HEADMODELS 64
+
+typedef struct voiceChat_s
+{
+ char id[64];
+ int numSounds;
+ sfxHandle_t sounds[MAX_VOICESOUNDS];
+ char chats[MAX_VOICESOUNDS][MAX_CHATSIZE];
+} voiceChat_t;
+
+typedef struct voiceChatList_s
+{
+ char name[64];
+ int gender;
+ int numVoiceChats;
+ voiceChat_t voiceChats[MAX_VOICECHATS];
+} voiceChatList_t;
+
+typedef struct headModelVoiceChat_s
+{
+ char headmodel[64];
+ int voiceChatNum;
+} headModelVoiceChat_t;
+
+voiceChatList_t voiceChatLists[MAX_VOICEFILES];
+headModelVoiceChat_t headModelVoiceChat[MAX_HEADMODELS];
+
+/*
+=================
+CG_ParseVoiceChats
+=================
+*/
+int CG_ParseVoiceChats( const char *filename, voiceChatList_t *voiceChatList, int maxVoiceChats ) {
+ int len, i;
+ fileHandle_t f;
+ char buf[MAX_VOICEFILESIZE];
+ char **p, *ptr;
+ char *token;
+ voiceChat_t *voiceChats;
+ qboolean compress;
+ sfxHandle_t sound;
+
+ compress = qtrue;
+ if (cg_buildScript.integer) {
+ compress = qfalse;
+ }
+
+ len = trap_FS_FOpenFile( filename, &f, FS_READ );
+ if ( !f ) {
+ trap_Print( va( S_COLOR_RED "voice chat file not found: %s\n", filename ) );
+ return qfalse;
+ }
+ if ( len >= MAX_VOICEFILESIZE ) {
+ trap_Print( va( S_COLOR_RED "voice chat file too large: %s is %i, max allowed is %i", filename, len, MAX_VOICEFILESIZE ) );
+ trap_FS_FCloseFile( f );
+ return qfalse;
+ }
+
+ trap_FS_Read( buf, len, f );
+ buf[len] = 0;
+ trap_FS_FCloseFile( f );
+
+ ptr = buf;
+ p = &ptr;
+
+ Com_sprintf(voiceChatList->name, sizeof(voiceChatList->name), "%s", filename);
+ voiceChats = voiceChatList->voiceChats;
+ for ( i = 0; i < maxVoiceChats; i++ ) {
+ voiceChats[i].id[0] = 0;
+ }
+ token = COM_ParseExt(p, qtrue);
+ if (!token || token[0] == 0) {
+ return qtrue;
+ }
+ if (!Q_stricmp(token, "female")) {
+ voiceChatList->gender = GENDER_FEMALE;
+ }
+ else if (!Q_stricmp(token, "male")) {
+ voiceChatList->gender = GENDER_MALE;
+ }
+ else if (!Q_stricmp(token, "neuter")) {
+ voiceChatList->gender = GENDER_NEUTER;
+ }
+ else {
+ trap_Print( va( S_COLOR_RED "expected gender not found in voice chat file: %s\n", filename ) );
+ return qfalse;
+ }
+
+ voiceChatList->numVoiceChats = 0;
+ while ( 1 ) {
+ token = COM_ParseExt(p, qtrue);
+ if (!token || token[0] == 0) {
+ return qtrue;
+ }
+ Com_sprintf(voiceChats[voiceChatList->numVoiceChats].id, sizeof( voiceChats[voiceChatList->numVoiceChats].id ), "%s", token);
+ token = COM_ParseExt(p, qtrue);
+ if (Q_stricmp(token, "{")) {
+ trap_Print( va( S_COLOR_RED "expected { found %s in voice chat file: %s\n", token, filename ) );
+ return qfalse;
+ }
+ voiceChats[voiceChatList->numVoiceChats].numSounds = 0;
+ while(1) {
+ token = COM_ParseExt(p, qtrue);
+ if (!token || token[0] == 0) {
+ return qtrue;
+ }
+ if (!Q_stricmp(token, "}"))
+ break;
+ sound = trap_S_RegisterSound( token, compress );
+ voiceChats[voiceChatList->numVoiceChats].sounds[voiceChats[voiceChatList->numVoiceChats].numSounds] = sound;
+ token = COM_ParseExt(p, qtrue);
+ if (!token || token[0] == 0) {
+ return qtrue;
+ }
+ Com_sprintf(voiceChats[voiceChatList->numVoiceChats].chats[
+ voiceChats[voiceChatList->numVoiceChats].numSounds], MAX_CHATSIZE, "%s", token);
+ if (sound)
+ voiceChats[voiceChatList->numVoiceChats].numSounds++;
+ if (voiceChats[voiceChatList->numVoiceChats].numSounds >= MAX_VOICESOUNDS)
+ break;
+ }
+ voiceChatList->numVoiceChats++;
+ if (voiceChatList->numVoiceChats >= maxVoiceChats)
+ return qtrue;
+ }
+ return qtrue;
+}
+
+/*
+=================
+CG_LoadVoiceChats
+=================
+*/
+void CG_LoadVoiceChats( void ) {
+ int size;
+
+ size = trap_MemoryRemaining();
+ CG_ParseVoiceChats( "scripts/female1.voice", &voiceChatLists[0], MAX_VOICECHATS );
+ CG_ParseVoiceChats( "scripts/female2.voice", &voiceChatLists[1], MAX_VOICECHATS );
+ CG_ParseVoiceChats( "scripts/female3.voice", &voiceChatLists[2], MAX_VOICECHATS );
+ CG_ParseVoiceChats( "scripts/male1.voice", &voiceChatLists[3], MAX_VOICECHATS );
+ CG_ParseVoiceChats( "scripts/male2.voice", &voiceChatLists[4], MAX_VOICECHATS );
+ CG_ParseVoiceChats( "scripts/male3.voice", &voiceChatLists[5], MAX_VOICECHATS );
+ CG_ParseVoiceChats( "scripts/male4.voice", &voiceChatLists[6], MAX_VOICECHATS );
+ CG_ParseVoiceChats( "scripts/male5.voice", &voiceChatLists[7], MAX_VOICECHATS );
+ CG_Printf("voice chat memory size = %d\n", size - trap_MemoryRemaining());
+}
+
+/*
+=================
+CG_HeadModelVoiceChats
+=================
+*/
+int CG_HeadModelVoiceChats( char *filename ) {
+ int len, i;
+ fileHandle_t f;
+ char buf[MAX_VOICEFILESIZE];
+ char **p, *ptr;
+ char *token;
+
+ len = trap_FS_FOpenFile( filename, &f, FS_READ );
+ if ( !f ) {
+ //trap_Print( va( "voice chat file not found: %s\n", filename ) );
+ return -1;
+ }
+ if ( len >= MAX_VOICEFILESIZE ) {
+ trap_Print( va( S_COLOR_RED "voice chat file too large: %s is %i, max allowed is %i", filename, len, MAX_VOICEFILESIZE ) );
+ trap_FS_FCloseFile( f );
+ return -1;
+ }
+
+ trap_FS_Read( buf, len, f );
+ buf[len] = 0;
+ trap_FS_FCloseFile( f );
+
+ ptr = buf;
+ p = &ptr;
+
+ token = COM_ParseExt(p, qtrue);
+ if (!token || token[0] == 0) {
+ return -1;
+ }
+
+ for ( i = 0; i < MAX_VOICEFILES; i++ ) {
+ if ( !Q_stricmp(token, voiceChatLists[i].name) ) {
+ return i;
+ }
+ }
+
+ //FIXME: maybe try to load the .voice file which name is stored in token?
+
+ return -1;
+}
+
+
+/*
+=================
+CG_GetVoiceChat
+=================
+*/
+int CG_GetVoiceChat( voiceChatList_t *voiceChatList, const char *id, sfxHandle_t *snd, char **chat) {
+ int i, rnd;
+
+ for ( i = 0; i < voiceChatList->numVoiceChats; i++ ) {
+ if ( !Q_stricmp( id, voiceChatList->voiceChats[i].id ) ) {
+ rnd = random() * voiceChatList->voiceChats[i].numSounds;
+ *snd = voiceChatList->voiceChats[i].sounds[rnd];
+ *chat = voiceChatList->voiceChats[i].chats[rnd];
+ return qtrue;
+ }
+ }
+ return qfalse;
+}
+
+/*
+=================
+CG_VoiceChatListForClient
+=================
+*/
+voiceChatList_t *CG_VoiceChatListForClient( int clientNum ) {
+ clientInfo_t *ci;
+ int voiceChatNum, i, j, k, gender;
+ char filename[MAX_QPATH], headModelName[MAX_QPATH];
+
+ if ( clientNum < 0 || clientNum >= MAX_CLIENTS ) {
+ clientNum = 0;
+ }
+ ci = &cgs.clientinfo[ clientNum ];
+
+ for ( k = 0; k < 2; k++ ) {
+ if ( k == 0 ) {
+ if (ci->headModelName[0] == '*') {
+ Com_sprintf( headModelName, sizeof(headModelName), "%s/%s", ci->headModelName+1, ci->headSkinName );
+ }
+ else {
+ Com_sprintf( headModelName, sizeof(headModelName), "%s/%s", ci->headModelName, ci->headSkinName );
+ }
+ }
+ else {
+ if (ci->headModelName[0] == '*') {
+ Com_sprintf( headModelName, sizeof(headModelName), "%s", ci->headModelName+1 );
+ }
+ else {
+ Com_sprintf( headModelName, sizeof(headModelName), "%s", ci->headModelName );
+ }
+ }
+ // find the voice file for the head model the client uses
+ for ( i = 0; i < MAX_HEADMODELS; i++ ) {
+ if (!Q_stricmp(headModelVoiceChat[i].headmodel, headModelName)) {
+ break;
+ }
+ }
+ if (i < MAX_HEADMODELS) {
+ return &voiceChatLists[headModelVoiceChat[i].voiceChatNum];
+ }
+ // find a <headmodelname>.vc file
+ for ( i = 0; i < MAX_HEADMODELS; i++ ) {
+ if (!strlen(headModelVoiceChat[i].headmodel)) {
+ Com_sprintf(filename, sizeof(filename), "scripts/%s.vc", headModelName);
+ voiceChatNum = CG_HeadModelVoiceChats(filename);
+ if (voiceChatNum == -1)
+ break;
+ Com_sprintf(headModelVoiceChat[i].headmodel, sizeof ( headModelVoiceChat[i].headmodel ),
+ "%s", headModelName);
+ headModelVoiceChat[i].voiceChatNum = voiceChatNum;
+ return &voiceChatLists[headModelVoiceChat[i].voiceChatNum];
+ }
+ }
+ }
+ gender = ci->gender;
+ for (k = 0; k < 2; k++) {
+ // just pick the first with the right gender
+ for ( i = 0; i < MAX_VOICEFILES; i++ ) {
+ if (strlen(voiceChatLists[i].name)) {
+ if (voiceChatLists[i].gender == gender) {
+ // store this head model with voice chat for future reference
+ for ( j = 0; j < MAX_HEADMODELS; j++ ) {
+ if (!strlen(headModelVoiceChat[j].headmodel)) {
+ Com_sprintf(headModelVoiceChat[j].headmodel, sizeof ( headModelVoiceChat[j].headmodel ),
+ "%s", headModelName);
+ headModelVoiceChat[j].voiceChatNum = i;
+ break;
+ }
+ }
+ return &voiceChatLists[i];
+ }
+ }
+ }
+ // fall back to male gender because we don't have neuter in the mission pack
+ if (gender == GENDER_MALE)
+ break;
+ gender = GENDER_MALE;
+ }
+ // store this head model with voice chat for future reference
+ for ( j = 0; j < MAX_HEADMODELS; j++ ) {
+ if (!strlen(headModelVoiceChat[j].headmodel)) {
+ Com_sprintf(headModelVoiceChat[j].headmodel, sizeof ( headModelVoiceChat[j].headmodel ),
+ "%s", headModelName);
+ headModelVoiceChat[j].voiceChatNum = 0;
+ break;
+ }
+ }
+ // just return the first voice chat list
+ return &voiceChatLists[0];
+}
+
+#define MAX_VOICECHATBUFFER 32
+
+typedef struct bufferedVoiceChat_s
+{
+ int clientNum;
+ sfxHandle_t snd;
+ int voiceOnly;
+ char cmd[MAX_SAY_TEXT];
+ char message[MAX_SAY_TEXT];
+} bufferedVoiceChat_t;
+
+bufferedVoiceChat_t voiceChatBuffer[MAX_VOICECHATBUFFER];
+
+/*
+=================
+CG_PlayVoiceChat
+=================
+*/
+void CG_PlayVoiceChat( bufferedVoiceChat_t *vchat ) {
+#ifdef MISSIONPACK
+ // if we are going into the intermission, don't start any voices
+ if ( cg.intermissionStarted ) {
+ return;
+ }
+
+ if ( !cg_noVoiceChats.integer ) {
+ trap_S_StartLocalSound( vchat->snd, CHAN_VOICE);
+ if (vchat->clientNum != cg.snap->ps.clientNum) {
+ int orderTask = CG_ValidOrder(vchat->cmd);
+ if (orderTask > 0) {
+ cgs.acceptOrderTime = cg.time + 5000;
+ Q_strncpyz(cgs.acceptVoice, vchat->cmd, sizeof(cgs.acceptVoice));
+ cgs.acceptTask = orderTask;
+ cgs.acceptLeader = vchat->clientNum;
+ }
+ // see if this was an order
+ CG_ShowResponseHead();
+ }
+ }
+ if (!vchat->voiceOnly && !cg_noVoiceText.integer) {
+ CG_AddToTeamChat( vchat->message );
+ CG_Printf( "%s\n", vchat->message );
+ }
+ voiceChatBuffer[cg.voiceChatBufferOut].snd = 0;
+#endif
+}
+
+/*
+=====================
+CG_PlayBufferedVoieChats
+=====================
+*/
+void CG_PlayBufferedVoiceChats( void ) {
+#ifdef MISSIONPACK
+ if ( cg.voiceChatTime < cg.time ) {
+ if (cg.voiceChatBufferOut != cg.voiceChatBufferIn && voiceChatBuffer[cg.voiceChatBufferOut].snd) {
+ //
+ CG_PlayVoiceChat(&voiceChatBuffer[cg.voiceChatBufferOut]);
+ //
+ cg.voiceChatBufferOut = (cg.voiceChatBufferOut + 1) % MAX_VOICECHATBUFFER;
+ cg.voiceChatTime = cg.time + 1000;
+ }
+ }
+#endif
+}
+
+/*
+=====================
+CG_AddBufferedVoiceChat
+=====================
+*/
+void CG_AddBufferedVoiceChat( bufferedVoiceChat_t *vchat ) {
+#ifdef MISSIONPACK
+ // if we are going into the intermission, don't start any voices
+ if ( cg.intermissionStarted ) {
+ return;
+ }
+
+ memcpy(&voiceChatBuffer[cg.voiceChatBufferIn], vchat, sizeof(bufferedVoiceChat_t));
+ cg.voiceChatBufferIn = (cg.voiceChatBufferIn + 1) % MAX_VOICECHATBUFFER;
+ if (cg.voiceChatBufferIn == cg.voiceChatBufferOut) {
+ CG_PlayVoiceChat( &voiceChatBuffer[cg.voiceChatBufferOut] );
+ cg.voiceChatBufferOut++;
+ }
+#endif
+}
+
+/*
+=================
+CG_VoiceChatLocal
+=================
+*/
+void CG_VoiceChatLocal( int mode, qboolean voiceOnly, int clientNum, int color, const char *cmd ) {
+#ifdef MISSIONPACK
+ char *chat;
+ voiceChatList_t *voiceChatList;
+ clientInfo_t *ci;
+ sfxHandle_t snd;
+ bufferedVoiceChat_t vchat;
+
+ // if we are going into the intermission, don't start any voices
+ if ( cg.intermissionStarted ) {
+ return;
+ }
+
+ if ( clientNum < 0 || clientNum >= MAX_CLIENTS ) {
+ clientNum = 0;
+ }
+ ci = &cgs.clientinfo[ clientNum ];
+
+ cgs.currentVoiceClient = clientNum;
+
+ voiceChatList = CG_VoiceChatListForClient( clientNum );
+
+ if ( CG_GetVoiceChat( voiceChatList, cmd, &snd, &chat ) ) {
+ //
+ if ( mode == SAY_TEAM || !cg_teamChatsOnly.integer ) {
+ vchat.clientNum = clientNum;
+ vchat.snd = snd;
+ vchat.voiceOnly = voiceOnly;
+ Q_strncpyz(vchat.cmd, cmd, sizeof(vchat.cmd));
+ if ( mode == SAY_TELL ) {
+ Com_sprintf(vchat.message, sizeof(vchat.message), "[%s]: %c%c%s", ci->name, Q_COLOR_ESCAPE, color, chat);
+ }
+ else if ( mode == SAY_TEAM ) {
+ Com_sprintf(vchat.message, sizeof(vchat.message), "(%s): %c%c%s", ci->name, Q_COLOR_ESCAPE, color, chat);
+ }
+ else {
+ Com_sprintf(vchat.message, sizeof(vchat.message), "%s: %c%c%s", ci->name, Q_COLOR_ESCAPE, color, chat);
+ }
+ CG_AddBufferedVoiceChat(&vchat);
+ }
+ }
+#endif
+}
+
+/*
+=================
+CG_VoiceChat
+=================
+*/
+void CG_VoiceChat( int mode ) {
+#ifdef MISSIONPACK
+ const char *cmd;
+ int clientNum, color;
+ qboolean voiceOnly;
+
+ voiceOnly = atoi(CG_Argv(1));
+ clientNum = atoi(CG_Argv(2));
+ color = atoi(CG_Argv(3));
+ cmd = CG_Argv(4);
+
+ if (cg_noTaunt.integer != 0) {
+ if (!strcmp(cmd, VOICECHAT_KILLINSULT) || !strcmp(cmd, VOICECHAT_TAUNT) || \
+ !strcmp(cmd, VOICECHAT_DEATHINSULT) || !strcmp(cmd, VOICECHAT_KILLGAUNTLET) || \
+ !strcmp(cmd, VOICECHAT_PRAISE)) {
+ return;
+ }
+ }
+
+ CG_VoiceChatLocal( mode, voiceOnly, clientNum, color, cmd );
+#endif
+}
+
+/*
+=================
+CG_RemoveChatEscapeChar
+=================
+*/
+static void CG_RemoveChatEscapeChar( char *text ) {
+ int i, l;
+
+ l = 0;
+ for ( i = 0; text[i]; i++ ) {
+ if (text[i] == '\x19')
+ continue;
+ text[l++] = text[i];
+ }
+ text[l] = '\0';
+}
+
+/*
+=================
+CG_ServerCommand
+
+The string has been tokenized and can be retrieved with
+Cmd_Argc() / Cmd_Argv()
+=================
+*/
+static void CG_ServerCommand( void ) {
+ const char *cmd;
+ char text[MAX_SAY_TEXT];
+
+ cmd = CG_Argv(0);
+
+ if ( !cmd[0] ) {
+ // server claimed the command
+ return;
+ }
+
+ if ( !strcmp( cmd, "cp" ) ) {
+ CG_CenterPrint( CG_Argv(1), SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH );
+ return;
+ }
+
+ if ( !strcmp( cmd, "cs" ) ) {
+ CG_ConfigStringModified();
+ return;
+ }
+
+ if ( !strcmp( cmd, "print" ) ) {
+ CG_Printf( "%s", CG_Argv(1) );
+#ifdef MISSIONPACK
+ cmd = CG_Argv(1); // yes, this is obviously a hack, but so is the way we hear about
+ // votes passing or failing
+ if ( !Q_stricmpn( cmd, "vote failed", 11 ) || !Q_stricmpn( cmd, "team vote failed", 16 )) {
+ trap_S_StartLocalSound( cgs.media.voteFailed, CHAN_ANNOUNCER );
+ } else if ( !Q_stricmpn( cmd, "vote passed", 11 ) || !Q_stricmpn( cmd, "team vote passed", 16 ) ) {
+ trap_S_StartLocalSound( cgs.media.votePassed, CHAN_ANNOUNCER );
+ }
+#endif
+ return;
+ }
+
+ if ( !strcmp( cmd, "chat" ) ) {
+ if ( !cg_teamChatsOnly.integer ) {
+ trap_S_StartLocalSound( cgs.media.talkSound, CHAN_LOCAL_SOUND );
+ Q_strncpyz( text, CG_Argv(1), MAX_SAY_TEXT );
+ CG_RemoveChatEscapeChar( text );
+ CG_Printf( "%s\n", text );
+ }
+ return;
+ }
+
+ if ( !strcmp( cmd, "tchat" ) ) {
+ trap_S_StartLocalSound( cgs.media.talkSound, CHAN_LOCAL_SOUND );
+ Q_strncpyz( text, CG_Argv(1), MAX_SAY_TEXT );
+ CG_RemoveChatEscapeChar( text );
+ CG_AddToTeamChat( text );
+ CG_Printf( "%s\n", text );
+ return;
+ }
+ if ( !strcmp( cmd, "vchat" ) ) {
+ CG_VoiceChat( SAY_ALL );
+ return;
+ }
+
+ if ( !strcmp( cmd, "vtchat" ) ) {
+ CG_VoiceChat( SAY_TEAM );
+ return;
+ }
+
+ if ( !strcmp( cmd, "vtell" ) ) {
+ CG_VoiceChat( SAY_TELL );
+ return;
+ }
+
+ if ( !strcmp( cmd, "scores" ) ) {
+ CG_ParseScores();
+ return;
+ }
+
+ if ( !strcmp( cmd, "tinfo" ) ) {
+ CG_ParseTeamInfo();
+ return;
+ }
+
+ if ( !strcmp( cmd, "map_restart" ) ) {
+ CG_MapRestart();
+ return;
+ }
+
+ if ( Q_stricmp (cmd, "remapShader") == 0 ) {
+ if (trap_Argc() == 4) {
+ trap_R_RemapShader(CG_Argv(1), CG_Argv(2), CG_Argv(3));
+ }
+ }
+
+ // loaddeferred can be both a servercmd and a consolecmd
+ if ( !strcmp( cmd, "loaddefered" ) ) { // FIXME: spelled wrong, but not changing for demo
+ CG_LoadDeferredPlayers();
+ return;
+ }
+
+ // clientLevelShot is sent before taking a special screenshot for
+ // the menu system during development
+ if ( !strcmp( cmd, "clientLevelShot" ) ) {
+ cg.levelShot = qtrue;
+ return;
+ }
+
+ CG_Printf( "Unknown client game command: %s\n", cmd );
+}
+
+
+/*
+====================
+CG_ExecuteNewServerCommands
+
+Execute all of the server commands that were received along
+with this this snapshot.
+====================
+*/
+void CG_ExecuteNewServerCommands( int latestSequence ) {
+ while ( cgs.serverCommandSequence < latestSequence ) {
+ if ( trap_GetServerCommand( ++cgs.serverCommandSequence ) ) {
+ CG_ServerCommand();
+ }
+ }
+}
diff --git a/code/cgame/cg_snapshot.c b/code/cgame/cg_snapshot.c
new file mode 100755
index 0000000..add49f0
--- /dev/null
+++ b/code/cgame/cg_snapshot.c
@@ -0,0 +1,403 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// cg_snapshot.c -- things that happen on snapshot transition,
+// not necessarily every single rendered frame
+
+#include "cg_local.h"
+
+
+
+/*
+==================
+CG_ResetEntity
+==================
+*/
+static void CG_ResetEntity( centity_t *cent ) {
+ // if the previous snapshot this entity was updated in is at least
+ // an event window back in time then we can reset the previous event
+ if ( cent->snapShotTime < cg.time - EVENT_VALID_MSEC ) {
+ cent->previousEvent = 0;
+ }
+
+ cent->trailTime = cg.snap->serverTime;
+
+ VectorCopy (cent->currentState.origin, cent->lerpOrigin);
+ VectorCopy (cent->currentState.angles, cent->lerpAngles);
+ if ( cent->currentState.eType == ET_PLAYER ) {
+ CG_ResetPlayerEntity( cent );
+ }
+}
+
+/*
+===============
+CG_TransitionEntity
+
+cent->nextState is moved to cent->currentState and events are fired
+===============
+*/
+static void CG_TransitionEntity( centity_t *cent ) {
+ cent->currentState = cent->nextState;
+ cent->currentValid = qtrue;
+
+ // reset if the entity wasn't in the last frame or was teleported
+ if ( !cent->interpolate ) {
+ CG_ResetEntity( cent );
+ }
+
+ // clear the next state. if will be set by the next CG_SetNextSnap
+ cent->interpolate = qfalse;
+
+ // check for events
+ CG_CheckEvents( cent );
+}
+
+
+/*
+==================
+CG_SetInitialSnapshot
+
+This will only happen on the very first snapshot, or
+on tourney restarts. All other times will use
+CG_TransitionSnapshot instead.
+
+FIXME: Also called by map_restart?
+==================
+*/
+void CG_SetInitialSnapshot( snapshot_t *snap ) {
+ int i;
+ centity_t *cent;
+ entityState_t *state;
+
+ cg.snap = snap;
+
+ BG_PlayerStateToEntityState( &snap->ps, &cg_entities[ snap->ps.clientNum ].currentState, qfalse );
+
+ // sort out solid entities
+ CG_BuildSolidList();
+
+ CG_ExecuteNewServerCommands( snap->serverCommandSequence );
+
+ // set our local weapon selection pointer to
+ // what the server has indicated the current weapon is
+ CG_Respawn();
+
+ for ( i = 0 ; i < cg.snap->numEntities ; i++ ) {
+ state = &cg.snap->entities[ i ];
+ cent = &cg_entities[ state->number ];
+
+ memcpy(&cent->currentState, state, sizeof(entityState_t));
+ //cent->currentState = *state;
+ cent->interpolate = qfalse;
+ cent->currentValid = qtrue;
+
+ CG_ResetEntity( cent );
+
+ // check for events
+ CG_CheckEvents( cent );
+ }
+}
+
+
+/*
+===================
+CG_TransitionSnapshot
+
+The transition point from snap to nextSnap has passed
+===================
+*/
+static void CG_TransitionSnapshot( void ) {
+ centity_t *cent;
+ snapshot_t *oldFrame;
+ int i;
+
+ if ( !cg.snap ) {
+ CG_Error( "CG_TransitionSnapshot: NULL cg.snap" );
+ }
+ if ( !cg.nextSnap ) {
+ CG_Error( "CG_TransitionSnapshot: NULL cg.nextSnap" );
+ }
+
+ // execute any server string commands before transitioning entities
+ CG_ExecuteNewServerCommands( cg.nextSnap->serverCommandSequence );
+
+ // if we had a map_restart, set everthing with initial
+ if ( !cg.snap ) {
+ }
+
+ // clear the currentValid flag for all entities in the existing snapshot
+ for ( i = 0 ; i < cg.snap->numEntities ; i++ ) {
+ cent = &cg_entities[ cg.snap->entities[ i ].number ];
+ cent->currentValid = qfalse;
+ }
+
+ // move nextSnap to snap and do the transitions
+ oldFrame = cg.snap;
+ cg.snap = cg.nextSnap;
+
+ BG_PlayerStateToEntityState( &cg.snap->ps, &cg_entities[ cg.snap->ps.clientNum ].currentState, qfalse );
+ cg_entities[ cg.snap->ps.clientNum ].interpolate = qfalse;
+
+ for ( i = 0 ; i < cg.snap->numEntities ; i++ ) {
+ cent = &cg_entities[ cg.snap->entities[ i ].number ];
+ CG_TransitionEntity( cent );
+
+ // remember time of snapshot this entity was last updated in
+ cent->snapShotTime = cg.snap->serverTime;
+ }
+
+ cg.nextSnap = NULL;
+
+ // check for playerstate transition events
+ if ( oldFrame ) {
+ playerState_t *ops, *ps;
+
+ ops = &oldFrame->ps;
+ ps = &cg.snap->ps;
+ // teleporting checks are irrespective of prediction
+ if ( ( ps->eFlags ^ ops->eFlags ) & EF_TELEPORT_BIT ) {
+ cg.thisFrameTeleport = qtrue; // will be cleared by prediction code
+ }
+
+ // if we are not doing client side movement prediction for any
+ // reason, then the client events and view changes will be issued now
+ if ( cg.demoPlayback || (cg.snap->ps.pm_flags & PMF_FOLLOW)
+ || cg_nopredict.integer || cg_synchronousClients.integer ) {
+ CG_TransitionPlayerState( ps, ops );
+ }
+ }
+
+}
+
+
+/*
+===================
+CG_SetNextSnap
+
+A new snapshot has just been read in from the client system.
+===================
+*/
+static void CG_SetNextSnap( snapshot_t *snap ) {
+ int num;
+ entityState_t *es;
+ centity_t *cent;
+
+ cg.nextSnap = snap;
+
+ BG_PlayerStateToEntityState( &snap->ps, &cg_entities[ snap->ps.clientNum ].nextState, qfalse );
+ cg_entities[ cg.snap->ps.clientNum ].interpolate = qtrue;
+
+ // check for extrapolation errors
+ for ( num = 0 ; num < snap->numEntities ; num++ ) {
+ es = &snap->entities[num];
+ cent = &cg_entities[ es->number ];
+
+ memcpy(&cent->nextState, es, sizeof(entityState_t));
+ //cent->nextState = *es;
+
+ // if this frame is a teleport, or the entity wasn't in the
+ // previous frame, don't interpolate
+ if ( !cent->currentValid || ( ( cent->currentState.eFlags ^ es->eFlags ) & EF_TELEPORT_BIT ) ) {
+ cent->interpolate = qfalse;
+ } else {
+ cent->interpolate = qtrue;
+ }
+ }
+
+ // if the next frame is a teleport for the playerstate, we
+ // can't interpolate during demos
+ if ( cg.snap && ( ( snap->ps.eFlags ^ cg.snap->ps.eFlags ) & EF_TELEPORT_BIT ) ) {
+ cg.nextFrameTeleport = qtrue;
+ } else {
+ cg.nextFrameTeleport = qfalse;
+ }
+
+ // if changing follow mode, don't interpolate
+ if ( cg.nextSnap->ps.clientNum != cg.snap->ps.clientNum ) {
+ cg.nextFrameTeleport = qtrue;
+ }
+
+ // if changing server restarts, don't interpolate
+ if ( ( cg.nextSnap->snapFlags ^ cg.snap->snapFlags ) & SNAPFLAG_SERVERCOUNT ) {
+ cg.nextFrameTeleport = qtrue;
+ }
+
+ // sort out solid entities
+ CG_BuildSolidList();
+}
+
+
+/*
+========================
+CG_ReadNextSnapshot
+
+This is the only place new snapshots are requested
+This may increment cgs.processedSnapshotNum multiple
+times if the client system fails to return a
+valid snapshot.
+========================
+*/
+static snapshot_t *CG_ReadNextSnapshot( void ) {
+ qboolean r;
+ snapshot_t *dest;
+
+ if ( cg.latestSnapshotNum > cgs.processedSnapshotNum + 1000 ) {
+ CG_Printf( "WARNING: CG_ReadNextSnapshot: way out of range, %i > %i",
+ cg.latestSnapshotNum, cgs.processedSnapshotNum );
+ }
+
+ while ( cgs.processedSnapshotNum < cg.latestSnapshotNum ) {
+ // decide which of the two slots to load it into
+ if ( cg.snap == &cg.activeSnapshots[0] ) {
+ dest = &cg.activeSnapshots[1];
+ } else {
+ dest = &cg.activeSnapshots[0];
+ }
+
+ // try to read the snapshot from the client system
+ cgs.processedSnapshotNum++;
+ r = trap_GetSnapshot( cgs.processedSnapshotNum, dest );
+
+ // FIXME: why would trap_GetSnapshot return a snapshot with the same server time
+ if ( cg.snap && r && dest->serverTime == cg.snap->serverTime ) {
+ //continue;
+ }
+
+ // if it succeeded, return
+ if ( r ) {
+ CG_AddLagometerSnapshotInfo( dest );
+ return dest;
+ }
+
+ // a GetSnapshot will return failure if the snapshot
+ // never arrived, or is so old that its entities
+ // have been shoved off the end of the circular
+ // buffer in the client system.
+
+ // record as a dropped packet
+ CG_AddLagometerSnapshotInfo( NULL );
+
+ // If there are additional snapshots, continue trying to
+ // read them.
+ }
+
+ // nothing left to read
+ return NULL;
+}
+
+
+/*
+============
+CG_ProcessSnapshots
+
+We are trying to set up a renderable view, so determine
+what the simulated time is, and try to get snapshots
+both before and after that time if available.
+
+If we don't have a valid cg.snap after exiting this function,
+then a 3D game view cannot be rendered. This should only happen
+right after the initial connection. After cg.snap has been valid
+once, it will never turn invalid.
+
+Even if cg.snap is valid, cg.nextSnap may not be, if the snapshot
+hasn't arrived yet (it becomes an extrapolating situation instead
+of an interpolating one)
+
+============
+*/
+void CG_ProcessSnapshots( void ) {
+ snapshot_t *snap;
+ int n;
+
+ // see what the latest snapshot the client system has is
+ trap_GetCurrentSnapshotNumber( &n, &cg.latestSnapshotTime );
+ if ( n != cg.latestSnapshotNum ) {
+ if ( n < cg.latestSnapshotNum ) {
+ // this should never happen
+ CG_Error( "CG_ProcessSnapshots: n < cg.latestSnapshotNum" );
+ }
+ cg.latestSnapshotNum = n;
+ }
+
+ // If we have yet to receive a snapshot, check for it.
+ // Once we have gotten the first snapshot, cg.snap will
+ // always have valid data for the rest of the game
+ while ( !cg.snap ) {
+ snap = CG_ReadNextSnapshot();
+ if ( !snap ) {
+ // we can't continue until we get a snapshot
+ return;
+ }
+
+ // set our weapon selection to what
+ // the playerstate is currently using
+ if ( !( snap->snapFlags & SNAPFLAG_NOT_ACTIVE ) ) {
+ CG_SetInitialSnapshot( snap );
+ }
+ }
+
+ // loop until we either have a valid nextSnap with a serverTime
+ // greater than cg.time to interpolate towards, or we run
+ // out of available snapshots
+ do {
+ // if we don't have a nextframe, try and read a new one in
+ if ( !cg.nextSnap ) {
+ snap = CG_ReadNextSnapshot();
+
+ // if we still don't have a nextframe, we will just have to
+ // extrapolate
+ if ( !snap ) {
+ break;
+ }
+
+ CG_SetNextSnap( snap );
+
+
+ // if time went backwards, we have a level restart
+ if ( cg.nextSnap->serverTime < cg.snap->serverTime ) {
+ CG_Error( "CG_ProcessSnapshots: Server time went backwards" );
+ }
+ }
+
+ // if our time is < nextFrame's, we have a nice interpolating state
+ if ( cg.time >= cg.snap->serverTime && cg.time < cg.nextSnap->serverTime ) {
+ break;
+ }
+
+ // we have passed the transition from nextFrame to frame
+ CG_TransitionSnapshot();
+ } while ( 1 );
+
+ // assert our valid conditions upon exiting
+ if ( cg.snap == NULL ) {
+ CG_Error( "CG_ProcessSnapshots: cg.snap == NULL" );
+ }
+ if ( cg.time < cg.snap->serverTime ) {
+ // this can happen right after a vid_restart
+ cg.time = cg.snap->serverTime;
+ }
+ if ( cg.nextSnap != NULL && cg.nextSnap->serverTime <= cg.time ) {
+ CG_Error( "CG_ProcessSnapshots: cg.nextSnap->serverTime <= cg.time" );
+ }
+
+}
+
diff --git a/code/cgame/cg_syscalls.asm b/code/cgame/cg_syscalls.asm
new file mode 100755
index 0000000..8363fe3
--- /dev/null
+++ b/code/cgame/cg_syscalls.asm
@@ -0,0 +1,106 @@
+code
+
+equ trap_Print -1
+equ trap_Error -2
+equ trap_Milliseconds -3
+equ trap_Cvar_Register -4
+equ trap_Cvar_Update -5
+equ trap_Cvar_Set -6
+equ trap_Cvar_VariableStringBuffer -7
+equ trap_Argc -8
+equ trap_Argv -9
+equ trap_Args -10
+equ trap_FS_FOpenFile -11
+equ trap_FS_Read -12
+equ trap_FS_Write -13
+equ trap_FS_FCloseFile -14
+equ trap_SendConsoleCommand -15
+equ trap_AddCommand -16
+equ trap_SendClientCommand -17
+equ trap_UpdateScreen -18
+equ trap_CM_LoadMap -19
+equ trap_CM_NumInlineModels -20
+equ trap_CM_InlineModel -21
+equ trap_CM_LoadModel -22
+equ trap_CM_TempBoxModel -23
+equ trap_CM_PointContents -24
+equ trap_CM_TransformedPointContents -25
+equ trap_CM_BoxTrace -26
+equ trap_CM_TransformedBoxTrace -27
+equ trap_CM_MarkFragments -28
+equ trap_S_StartSound -29
+equ trap_S_StartLocalSound -30
+equ trap_S_ClearLoopingSounds -31
+equ trap_S_AddLoopingSound -32
+equ trap_S_UpdateEntityPosition -33
+equ trap_S_Respatialize -34
+equ trap_S_RegisterSound -35
+equ trap_S_StartBackgroundTrack -36
+equ trap_R_LoadWorldMap -37
+equ trap_R_RegisterModel -38
+equ trap_R_RegisterSkin -39
+equ trap_R_RegisterShader -40
+equ trap_R_ClearScene -41
+equ trap_R_AddRefEntityToScene -42
+equ trap_R_AddPolyToScene -43
+equ trap_R_AddLightToScene -44
+equ trap_R_RenderScene -45
+equ trap_R_SetColor -46
+equ trap_R_DrawStretchPic -47
+equ trap_R_ModelBounds -48
+equ trap_R_LerpTag -49
+equ trap_GetGlconfig -50
+equ trap_GetGameState -51
+equ trap_GetCurrentSnapshotNumber -52
+equ trap_GetSnapshot -53
+equ trap_GetServerCommand -54
+equ trap_GetCurrentCmdNumber -55
+equ trap_GetUserCmd -56
+equ trap_SetUserCmdValue -57
+equ trap_R_RegisterShaderNoMip -58
+equ trap_MemoryRemaining -59
+equ trap_R_RegisterFont -60
+equ trap_Key_IsDown -61
+equ trap_Key_GetCatcher -62
+equ trap_Key_SetCatcher -63
+equ trap_Key_GetKey -64
+equ trap_PC_AddGlobalDefine -65
+equ trap_PC_LoadSource -66
+equ trap_PC_FreeSource -67
+equ trap_PC_ReadToken -68
+equ trap_PC_SourceFileAndLine -69
+equ trap_S_StopBackgroundTrack -70
+equ trap_RealTime -71
+equ trap_SnapVector -72
+equ trap_RemoveCommand -73
+equ trap_R_LightForPoint -74
+equ trap_CIN_PlayCinematic -75
+equ trap_CIN_StopCinematic -76
+equ trap_CIN_RunCinematic -77
+equ trap_CIN_DrawCinematic -78
+equ trap_CIN_SetExtents -79
+equ trap_R_RemapShader -80
+equ trap_S_AddRealLoopingSound -81
+equ trap_S_StopLoopingSound -82
+equ trap_CM_TempCapsuleModel -83
+equ trap_CM_CapsuleTrace -84
+equ trap_CM_TransformedCapsuleTrace -85
+equ trap_R_AddAdditiveLightToScene -86
+equ trap_GetEntityToken -87
+equ trap_R_AddPolysToScene -88
+equ trap_R_inPVS -89
+equ trap_FS_Seek -90
+
+equ memset -101
+equ memcpy -102
+equ strncpy -103
+equ sin -104
+equ cos -105
+equ atan2 -106
+equ sqrt -107
+equ floor -108
+equ ceil -109
+equ testPrintInt -110
+equ testPrintFloat -111
+equ acos -112
+
diff --git a/code/cgame/cg_syscalls.c b/code/cgame/cg_syscalls.c
new file mode 100755
index 0000000..a7bf659
--- /dev/null
+++ b/code/cgame/cg_syscalls.c
@@ -0,0 +1,445 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// cg_syscalls.c -- this file is only included when building a dll
+// cg_syscalls.asm is included instead when building a qvm
+#ifdef Q3_VM
+#error "Do not use in VM build"
+#endif
+
+#include "cg_local.h"
+
+static int (QDECL *syscall)( int arg, ... ) = (int (QDECL *)( int, ...))-1;
+
+
+void dllEntry( int (QDECL *syscallptr)( int arg,... ) ) {
+ syscall = syscallptr;
+}
+
+
+int PASSFLOAT( float x ) {
+ float floatTemp;
+ floatTemp = x;
+ return *(int *)&floatTemp;
+}
+
+void trap_Print( const char *fmt ) {
+ syscall( CG_PRINT, fmt );
+}
+
+void trap_Error( const char *fmt ) {
+ syscall( CG_ERROR, fmt );
+}
+
+int trap_Milliseconds( void ) {
+ return syscall( CG_MILLISECONDS );
+}
+
+void trap_Cvar_Register( vmCvar_t *vmCvar, const char *varName, const char *defaultValue, int flags ) {
+ syscall( CG_CVAR_REGISTER, vmCvar, varName, defaultValue, flags );
+}
+
+void trap_Cvar_Update( vmCvar_t *vmCvar ) {
+ syscall( CG_CVAR_UPDATE, vmCvar );
+}
+
+void trap_Cvar_Set( const char *var_name, const char *value ) {
+ syscall( CG_CVAR_SET, var_name, value );
+}
+
+void trap_Cvar_VariableStringBuffer( const char *var_name, char *buffer, int bufsize ) {
+ syscall( CG_CVAR_VARIABLESTRINGBUFFER, var_name, buffer, bufsize );
+}
+
+int trap_Argc( void ) {
+ return syscall( CG_ARGC );
+}
+
+void trap_Argv( int n, char *buffer, int bufferLength ) {
+ syscall( CG_ARGV, n, buffer, bufferLength );
+}
+
+void trap_Args( char *buffer, int bufferLength ) {
+ syscall( CG_ARGS, buffer, bufferLength );
+}
+
+int trap_FS_FOpenFile( const char *qpath, fileHandle_t *f, fsMode_t mode ) {
+ return syscall( CG_FS_FOPENFILE, qpath, f, mode );
+}
+
+void trap_FS_Read( void *buffer, int len, fileHandle_t f ) {
+ syscall( CG_FS_READ, buffer, len, f );
+}
+
+void trap_FS_Write( const void *buffer, int len, fileHandle_t f ) {
+ syscall( CG_FS_WRITE, buffer, len, f );
+}
+
+void trap_FS_FCloseFile( fileHandle_t f ) {
+ syscall( CG_FS_FCLOSEFILE, f );
+}
+
+int trap_FS_Seek( fileHandle_t f, long offset, int origin ) {
+ return syscall( CG_FS_SEEK, f, offset, origin );
+}
+
+void trap_SendConsoleCommand( const char *text ) {
+ syscall( CG_SENDCONSOLECOMMAND, text );
+}
+
+void trap_AddCommand( const char *cmdName ) {
+ syscall( CG_ADDCOMMAND, cmdName );
+}
+
+void trap_RemoveCommand( const char *cmdName ) {
+ syscall( CG_REMOVECOMMAND, cmdName );
+}
+
+void trap_SendClientCommand( const char *s ) {
+ syscall( CG_SENDCLIENTCOMMAND, s );
+}
+
+void trap_UpdateScreen( void ) {
+ syscall( CG_UPDATESCREEN );
+}
+
+void trap_CM_LoadMap( const char *mapname ) {
+ syscall( CG_CM_LOADMAP, mapname );
+}
+
+int trap_CM_NumInlineModels( void ) {
+ return syscall( CG_CM_NUMINLINEMODELS );
+}
+
+clipHandle_t trap_CM_InlineModel( int index ) {
+ return syscall( CG_CM_INLINEMODEL, index );
+}
+
+clipHandle_t trap_CM_TempBoxModel( const vec3_t mins, const vec3_t maxs ) {
+ return syscall( CG_CM_TEMPBOXMODEL, mins, maxs );
+}
+
+clipHandle_t trap_CM_TempCapsuleModel( const vec3_t mins, const vec3_t maxs ) {
+ return syscall( CG_CM_TEMPCAPSULEMODEL, mins, maxs );
+}
+
+int trap_CM_PointContents( const vec3_t p, clipHandle_t model ) {
+ return syscall( CG_CM_POINTCONTENTS, p, model );
+}
+
+int trap_CM_TransformedPointContents( const vec3_t p, clipHandle_t model, const vec3_t origin, const vec3_t angles ) {
+ return syscall( CG_CM_TRANSFORMEDPOINTCONTENTS, p, model, origin, angles );
+}
+
+void trap_CM_BoxTrace( trace_t *results, const vec3_t start, const vec3_t end,
+ const vec3_t mins, const vec3_t maxs,
+ clipHandle_t model, int brushmask ) {
+ syscall( CG_CM_BOXTRACE, results, start, end, mins, maxs, model, brushmask );
+}
+
+void trap_CM_CapsuleTrace( trace_t *results, const vec3_t start, const vec3_t end,
+ const vec3_t mins, const vec3_t maxs,
+ clipHandle_t model, int brushmask ) {
+ syscall( CG_CM_CAPSULETRACE, results, start, end, mins, maxs, model, brushmask );
+}
+
+void trap_CM_TransformedBoxTrace( trace_t *results, const vec3_t start, const vec3_t end,
+ const vec3_t mins, const vec3_t maxs,
+ clipHandle_t model, int brushmask,
+ const vec3_t origin, const vec3_t angles ) {
+ syscall( CG_CM_TRANSFORMEDBOXTRACE, results, start, end, mins, maxs, model, brushmask, origin, angles );
+}
+
+void trap_CM_TransformedCapsuleTrace( trace_t *results, const vec3_t start, const vec3_t end,
+ const vec3_t mins, const vec3_t maxs,
+ clipHandle_t model, int brushmask,
+ const vec3_t origin, const vec3_t angles ) {
+ syscall( CG_CM_TRANSFORMEDCAPSULETRACE, results, start, end, mins, maxs, model, brushmask, origin, angles );
+}
+
+int trap_CM_MarkFragments( int numPoints, const vec3_t *points,
+ const vec3_t projection,
+ int maxPoints, vec3_t pointBuffer,
+ int maxFragments, markFragment_t *fragmentBuffer ) {
+ return syscall( CG_CM_MARKFRAGMENTS, numPoints, points, projection, maxPoints, pointBuffer, maxFragments, fragmentBuffer );
+}
+
+void trap_S_StartSound( vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfx ) {
+ syscall( CG_S_STARTSOUND, origin, entityNum, entchannel, sfx );
+}
+
+void trap_S_StartLocalSound( sfxHandle_t sfx, int channelNum ) {
+ syscall( CG_S_STARTLOCALSOUND, sfx, channelNum );
+}
+
+void trap_S_ClearLoopingSounds( qboolean killall ) {
+ syscall( CG_S_CLEARLOOPINGSOUNDS, killall );
+}
+
+void trap_S_AddLoopingSound( int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx ) {
+ syscall( CG_S_ADDLOOPINGSOUND, entityNum, origin, velocity, sfx );
+}
+
+void trap_S_AddRealLoopingSound( int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx ) {
+ syscall( CG_S_ADDREALLOOPINGSOUND, entityNum, origin, velocity, sfx );
+}
+
+void trap_S_StopLoopingSound( int entityNum ) {
+ syscall( CG_S_STOPLOOPINGSOUND, entityNum );
+}
+
+void trap_S_UpdateEntityPosition( int entityNum, const vec3_t origin ) {
+ syscall( CG_S_UPDATEENTITYPOSITION, entityNum, origin );
+}
+
+void trap_S_Respatialize( int entityNum, const vec3_t origin, vec3_t axis[3], int inwater ) {
+ syscall( CG_S_RESPATIALIZE, entityNum, origin, axis, inwater );
+}
+
+sfxHandle_t trap_S_RegisterSound( const char *sample, qboolean compressed ) {
+ return syscall( CG_S_REGISTERSOUND, sample, compressed );
+}
+
+void trap_S_StartBackgroundTrack( const char *intro, const char *loop ) {
+ syscall( CG_S_STARTBACKGROUNDTRACK, intro, loop );
+}
+
+void trap_R_LoadWorldMap( const char *mapname ) {
+ syscall( CG_R_LOADWORLDMAP, mapname );
+}
+
+qhandle_t trap_R_RegisterModel( const char *name ) {
+ return syscall( CG_R_REGISTERMODEL, name );
+}
+
+qhandle_t trap_R_RegisterSkin( const char *name ) {
+ return syscall( CG_R_REGISTERSKIN, name );
+}
+
+qhandle_t trap_R_RegisterShader( const char *name ) {
+ return syscall( CG_R_REGISTERSHADER, name );
+}
+
+qhandle_t trap_R_RegisterShaderNoMip( const char *name ) {
+ return syscall( CG_R_REGISTERSHADERNOMIP, name );
+}
+
+void trap_R_RegisterFont(const char *fontName, int pointSize, fontInfo_t *font) {
+ syscall(CG_R_REGISTERFONT, fontName, pointSize, font );
+}
+
+void trap_R_ClearScene( void ) {
+ syscall( CG_R_CLEARSCENE );
+}
+
+void trap_R_AddRefEntityToScene( const refEntity_t *re ) {
+ syscall( CG_R_ADDREFENTITYTOSCENE, re );
+}
+
+void trap_R_AddPolyToScene( qhandle_t hShader , int numVerts, const polyVert_t *verts ) {
+ syscall( CG_R_ADDPOLYTOSCENE, hShader, numVerts, verts );
+}
+
+void trap_R_AddPolysToScene( qhandle_t hShader , int numVerts, const polyVert_t *verts, int num ) {
+ syscall( CG_R_ADDPOLYSTOSCENE, hShader, numVerts, verts, num );
+}
+
+int trap_R_LightForPoint( vec3_t point, vec3_t ambientLight, vec3_t directedLight, vec3_t lightDir ) {
+ return syscall( CG_R_LIGHTFORPOINT, point, ambientLight, directedLight, lightDir );
+}
+
+void trap_R_AddLightToScene( const vec3_t org, float intensity, float r, float g, float b ) {
+ syscall( CG_R_ADDLIGHTTOSCENE, org, PASSFLOAT(intensity), PASSFLOAT(r), PASSFLOAT(g), PASSFLOAT(b) );
+}
+
+void trap_R_AddAdditiveLightToScene( const vec3_t org, float intensity, float r, float g, float b ) {
+ syscall( CG_R_ADDADDITIVELIGHTTOSCENE, org, PASSFLOAT(intensity), PASSFLOAT(r), PASSFLOAT(g), PASSFLOAT(b) );
+}
+
+void trap_R_RenderScene( const refdef_t *fd ) {
+ syscall( CG_R_RENDERSCENE, fd );
+}
+
+void trap_R_SetColor( const float *rgba ) {
+ syscall( CG_R_SETCOLOR, rgba );
+}
+
+void trap_R_DrawStretchPic( float x, float y, float w, float h,
+ float s1, float t1, float s2, float t2, qhandle_t hShader ) {
+ syscall( CG_R_DRAWSTRETCHPIC, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), hShader );
+}
+
+void trap_R_ModelBounds( clipHandle_t model, vec3_t mins, vec3_t maxs ) {
+ syscall( CG_R_MODELBOUNDS, model, mins, maxs );
+}
+
+int trap_R_LerpTag( orientation_t *tag, clipHandle_t mod, int startFrame, int endFrame,
+ float frac, const char *tagName ) {
+ return syscall( CG_R_LERPTAG, tag, mod, startFrame, endFrame, PASSFLOAT(frac), tagName );
+}
+
+void trap_R_RemapShader( const char *oldShader, const char *newShader, const char *timeOffset ) {
+ syscall( CG_R_REMAP_SHADER, oldShader, newShader, timeOffset );
+}
+
+void trap_GetGlconfig( glconfig_t *glconfig ) {
+ syscall( CG_GETGLCONFIG, glconfig );
+}
+
+void trap_GetGameState( gameState_t *gamestate ) {
+ syscall( CG_GETGAMESTATE, gamestate );
+}
+
+void trap_GetCurrentSnapshotNumber( int *snapshotNumber, int *serverTime ) {
+ syscall( CG_GETCURRENTSNAPSHOTNUMBER, snapshotNumber, serverTime );
+}
+
+qboolean trap_GetSnapshot( int snapshotNumber, snapshot_t *snapshot ) {
+ return syscall( CG_GETSNAPSHOT, snapshotNumber, snapshot );
+}
+
+qboolean trap_GetServerCommand( int serverCommandNumber ) {
+ return syscall( CG_GETSERVERCOMMAND, serverCommandNumber );
+}
+
+int trap_GetCurrentCmdNumber( void ) {
+ return syscall( CG_GETCURRENTCMDNUMBER );
+}
+
+qboolean trap_GetUserCmd( int cmdNumber, usercmd_t *ucmd ) {
+ return syscall( CG_GETUSERCMD, cmdNumber, ucmd );
+}
+
+void trap_SetUserCmdValue( int stateValue, float sensitivityScale ) {
+ syscall( CG_SETUSERCMDVALUE, stateValue, PASSFLOAT(sensitivityScale) );
+}
+
+void testPrintInt( char *string, int i ) {
+ syscall( CG_TESTPRINTINT, string, i );
+}
+
+void testPrintFloat( char *string, float f ) {
+ syscall( CG_TESTPRINTFLOAT, string, PASSFLOAT(f) );
+}
+
+int trap_MemoryRemaining( void ) {
+ return syscall( CG_MEMORY_REMAINING );
+}
+
+qboolean trap_Key_IsDown( int keynum ) {
+ return syscall( CG_KEY_ISDOWN, keynum );
+}
+
+int trap_Key_GetCatcher( void ) {
+ return syscall( CG_KEY_GETCATCHER );
+}
+
+void trap_Key_SetCatcher( int catcher ) {
+ syscall( CG_KEY_SETCATCHER, catcher );
+}
+
+int trap_Key_GetKey( const char *binding ) {
+ return syscall( CG_KEY_GETKEY, binding );
+}
+
+int trap_PC_AddGlobalDefine( char *define ) {
+ return syscall( CG_PC_ADD_GLOBAL_DEFINE, define );
+}
+
+int trap_PC_LoadSource( const char *filename ) {
+ return syscall( CG_PC_LOAD_SOURCE, filename );
+}
+
+int trap_PC_FreeSource( int handle ) {
+ return syscall( CG_PC_FREE_SOURCE, handle );
+}
+
+int trap_PC_ReadToken( int handle, pc_token_t *pc_token ) {
+ return syscall( CG_PC_READ_TOKEN, handle, pc_token );
+}
+
+int trap_PC_SourceFileAndLine( int handle, char *filename, int *line ) {
+ return syscall( CG_PC_SOURCE_FILE_AND_LINE, handle, filename, line );
+}
+
+void trap_S_StopBackgroundTrack( void ) {
+ syscall( CG_S_STOPBACKGROUNDTRACK );
+}
+
+int trap_RealTime(qtime_t *qtime) {
+ return syscall( CG_REAL_TIME, qtime );
+}
+
+void trap_SnapVector( float *v ) {
+ syscall( CG_SNAPVECTOR, v );
+}
+
+// this returns a handle. arg0 is the name in the format "idlogo.roq", set arg1 to NULL, alteredstates to qfalse (do not alter gamestate)
+int trap_CIN_PlayCinematic( const char *arg0, int xpos, int ypos, int width, int height, int bits) {
+ return syscall(CG_CIN_PLAYCINEMATIC, arg0, xpos, ypos, width, height, bits);
+}
+
+// stops playing the cinematic and ends it. should always return FMV_EOF
+// cinematics must be stopped in reverse order of when they are started
+e_status trap_CIN_StopCinematic(int handle) {
+ return syscall(CG_CIN_STOPCINEMATIC, handle);
+}
+
+
+// will run a frame of the cinematic but will not draw it. Will return FMV_EOF if the end of the cinematic has been reached.
+e_status trap_CIN_RunCinematic (int handle) {
+ return syscall(CG_CIN_RUNCINEMATIC, handle);
+}
+
+
+// draws the current frame
+void trap_CIN_DrawCinematic (int handle) {
+ syscall(CG_CIN_DRAWCINEMATIC, handle);
+}
+
+
+// allows you to resize the animation dynamically
+void trap_CIN_SetExtents (int handle, int x, int y, int w, int h) {
+ syscall(CG_CIN_SETEXTENTS, handle, x, y, w, h);
+}
+
+/*
+qboolean trap_loadCamera( const char *name ) {
+ return syscall( CG_LOADCAMERA, name );
+}
+
+void trap_startCamera(int time) {
+ syscall(CG_STARTCAMERA, time);
+}
+
+qboolean trap_getCameraInfo( int time, vec3_t *origin, vec3_t *angles) {
+ return syscall( CG_GETCAMERAINFO, time, origin, angles );
+}
+*/
+
+qboolean trap_GetEntityToken( char *buffer, int bufferSize ) {
+ return syscall( CG_GET_ENTITY_TOKEN, buffer, bufferSize );
+}
+
+qboolean trap_R_inPVS( const vec3_t p1, const vec3_t p2 ) {
+ return syscall( CG_R_INPVS, p1, p2 );
+}
diff --git a/code/cgame/cg_view.c b/code/cgame/cg_view.c
new file mode 100755
index 0000000..83d5141
--- /dev/null
+++ b/code/cgame/cg_view.c
@@ -0,0 +1,876 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// cg_view.c -- setup all the parameters (position, angle, etc)
+// for a 3D rendering
+#include "cg_local.h"
+
+
+/*
+=============================================================================
+
+ MODEL TESTING
+
+The viewthing and gun positioning tools from Q2 have been integrated and
+enhanced into a single model testing facility.
+
+Model viewing can begin with either "testmodel <modelname>" or "testgun <modelname>".
+
+The names must be the full pathname after the basedir, like
+"models/weapons/v_launch/tris.md3" or "players/male/tris.md3"
+
+Testmodel will create a fake entity 100 units in front of the current view
+position, directly facing the viewer. It will remain immobile, so you can
+move around it to view it from different angles.
+
+Testgun will cause the model to follow the player around and supress the real
+view weapon model. The default frame 0 of most guns is completely off screen,
+so you will probably have to cycle a couple frames to see it.
+
+"nextframe", "prevframe", "nextskin", and "prevskin" commands will change the
+frame or skin of the testmodel. These are bound to F5, F6, F7, and F8 in
+q3default.cfg.
+
+If a gun is being tested, the "gun_x", "gun_y", and "gun_z" variables will let
+you adjust the positioning.
+
+Note that none of the model testing features update while the game is paused, so
+it may be convenient to test with deathmatch set to 1 so that bringing down the
+console doesn't pause the game.
+
+=============================================================================
+*/
+
+/*
+=================
+CG_TestModel_f
+
+Creates an entity in front of the current position, which
+can then be moved around
+=================
+*/
+void CG_TestModel_f (void) {
+ vec3_t angles;
+
+ memset( &cg.testModelEntity, 0, sizeof(cg.testModelEntity) );
+ if ( trap_Argc() < 2 ) {
+ return;
+ }
+
+ Q_strncpyz (cg.testModelName, CG_Argv( 1 ), MAX_QPATH );
+ cg.testModelEntity.hModel = trap_R_RegisterModel( cg.testModelName );
+
+ if ( trap_Argc() == 3 ) {
+ cg.testModelEntity.backlerp = atof( CG_Argv( 2 ) );
+ cg.testModelEntity.frame = 1;
+ cg.testModelEntity.oldframe = 0;
+ }
+ if (! cg.testModelEntity.hModel ) {
+ CG_Printf( "Can't register model\n" );
+ return;
+ }
+
+ VectorMA( cg.refdef.vieworg, 100, cg.refdef.viewaxis[0], cg.testModelEntity.origin );
+
+ angles[PITCH] = 0;
+ angles[YAW] = 180 + cg.refdefViewAngles[1];
+ angles[ROLL] = 0;
+
+ AnglesToAxis( angles, cg.testModelEntity.axis );
+ cg.testGun = qfalse;
+}
+
+/*
+=================
+CG_TestGun_f
+
+Replaces the current view weapon with the given model
+=================
+*/
+void CG_TestGun_f (void) {
+ CG_TestModel_f();
+ cg.testGun = qtrue;
+ cg.testModelEntity.renderfx = RF_MINLIGHT | RF_DEPTHHACK | RF_FIRST_PERSON;
+}
+
+
+void CG_TestModelNextFrame_f (void) {
+ cg.testModelEntity.frame++;
+ CG_Printf( "frame %i\n", cg.testModelEntity.frame );
+}
+
+void CG_TestModelPrevFrame_f (void) {
+ cg.testModelEntity.frame--;
+ if ( cg.testModelEntity.frame < 0 ) {
+ cg.testModelEntity.frame = 0;
+ }
+ CG_Printf( "frame %i\n", cg.testModelEntity.frame );
+}
+
+void CG_TestModelNextSkin_f (void) {
+ cg.testModelEntity.skinNum++;
+ CG_Printf( "skin %i\n", cg.testModelEntity.skinNum );
+}
+
+void CG_TestModelPrevSkin_f (void) {
+ cg.testModelEntity.skinNum--;
+ if ( cg.testModelEntity.skinNum < 0 ) {
+ cg.testModelEntity.skinNum = 0;
+ }
+ CG_Printf( "skin %i\n", cg.testModelEntity.skinNum );
+}
+
+static void CG_AddTestModel (void) {
+ int i;
+
+ // re-register the model, because the level may have changed
+ cg.testModelEntity.hModel = trap_R_RegisterModel( cg.testModelName );
+ if (! cg.testModelEntity.hModel ) {
+ CG_Printf ("Can't register model\n");
+ return;
+ }
+
+ // if testing a gun, set the origin reletive to the view origin
+ if ( cg.testGun ) {
+ VectorCopy( cg.refdef.vieworg, cg.testModelEntity.origin );
+ VectorCopy( cg.refdef.viewaxis[0], cg.testModelEntity.axis[0] );
+ VectorCopy( cg.refdef.viewaxis[1], cg.testModelEntity.axis[1] );
+ VectorCopy( cg.refdef.viewaxis[2], cg.testModelEntity.axis[2] );
+
+ // allow the position to be adjusted
+ for (i=0 ; i<3 ; i++) {
+ cg.testModelEntity.origin[i] += cg.refdef.viewaxis[0][i] * cg_gun_x.value;
+ cg.testModelEntity.origin[i] += cg.refdef.viewaxis[1][i] * cg_gun_y.value;
+ cg.testModelEntity.origin[i] += cg.refdef.viewaxis[2][i] * cg_gun_z.value;
+ }
+ }
+
+ trap_R_AddRefEntityToScene( &cg.testModelEntity );
+}
+
+
+
+//============================================================================
+
+
+/*
+=================
+CG_CalcVrect
+
+Sets the coordinates of the rendered window
+=================
+*/
+static void CG_CalcVrect (void) {
+ int size;
+
+ // the intermission should allways be full screen
+ if ( cg.snap->ps.pm_type == PM_INTERMISSION ) {
+ size = 100;
+ } else {
+ // bound normal viewsize
+ if (cg_viewsize.integer < 30) {
+ trap_Cvar_Set ("cg_viewsize","30");
+ size = 30;
+ } else if (cg_viewsize.integer > 100) {
+ trap_Cvar_Set ("cg_viewsize","100");
+ size = 100;
+ } else {
+ size = cg_viewsize.integer;
+ }
+
+ }
+ cg.refdef.width = cgs.glconfig.vidWidth*size/100;
+ cg.refdef.width &= ~1;
+
+ cg.refdef.height = cgs.glconfig.vidHeight*size/100;
+ cg.refdef.height &= ~1;
+
+ cg.refdef.x = (cgs.glconfig.vidWidth - cg.refdef.width)/2;
+ cg.refdef.y = (cgs.glconfig.vidHeight - cg.refdef.height)/2;
+}
+
+//==============================================================================
+
+
+/*
+===============
+CG_OffsetThirdPersonView
+
+===============
+*/
+#define FOCUS_DISTANCE 512
+static void CG_OffsetThirdPersonView( void ) {
+ vec3_t forward, right, up;
+ vec3_t view;
+ vec3_t focusAngles;
+ trace_t trace;
+ static vec3_t mins = { -4, -4, -4 };
+ static vec3_t maxs = { 4, 4, 4 };
+ vec3_t focusPoint;
+ float focusDist;
+ float forwardScale, sideScale;
+
+ cg.refdef.vieworg[2] += cg.predictedPlayerState.viewheight;
+
+ VectorCopy( cg.refdefViewAngles, focusAngles );
+
+ // if dead, look at killer
+ if ( cg.predictedPlayerState.stats[STAT_HEALTH] <= 0 ) {
+ focusAngles[YAW] = cg.predictedPlayerState.stats[STAT_DEAD_YAW];
+ cg.refdefViewAngles[YAW] = cg.predictedPlayerState.stats[STAT_DEAD_YAW];
+ }
+
+ if ( focusAngles[PITCH] > 45 ) {
+ focusAngles[PITCH] = 45; // don't go too far overhead
+ }
+ AngleVectors( focusAngles, forward, NULL, NULL );
+
+ VectorMA( cg.refdef.vieworg, FOCUS_DISTANCE, forward, focusPoint );
+
+ VectorCopy( cg.refdef.vieworg, view );
+
+ view[2] += 8;
+
+ cg.refdefViewAngles[PITCH] *= 0.5;
+
+ AngleVectors( cg.refdefViewAngles, forward, right, up );
+
+ forwardScale = cos( cg_thirdPersonAngle.value / 180 * M_PI );
+ sideScale = sin( cg_thirdPersonAngle.value / 180 * M_PI );
+ VectorMA( view, -cg_thirdPersonRange.value * forwardScale, forward, view );
+ VectorMA( view, -cg_thirdPersonRange.value * sideScale, right, view );
+
+ // trace a ray from the origin to the viewpoint to make sure the view isn't
+ // in a solid block. Use an 8 by 8 block to prevent the view from near clipping anything
+
+ if (!cg_cameraMode.integer) {
+ CG_Trace( &trace, cg.refdef.vieworg, mins, maxs, view, cg.predictedPlayerState.clientNum, MASK_SOLID );
+
+ if ( trace.fraction != 1.0 ) {
+ VectorCopy( trace.endpos, view );
+ view[2] += (1.0 - trace.fraction) * 32;
+ // try another trace to this position, because a tunnel may have the ceiling
+ // close enogh that this is poking out
+
+ CG_Trace( &trace, cg.refdef.vieworg, mins, maxs, view, cg.predictedPlayerState.clientNum, MASK_SOLID );
+ VectorCopy( trace.endpos, view );
+ }
+ }
+
+
+ VectorCopy( view, cg.refdef.vieworg );
+
+ // select pitch to look at focus point from vieword
+ VectorSubtract( focusPoint, cg.refdef.vieworg, focusPoint );
+ focusDist = sqrt( focusPoint[0] * focusPoint[0] + focusPoint[1] * focusPoint[1] );
+ if ( focusDist < 1 ) {
+ focusDist = 1; // should never happen
+ }
+ cg.refdefViewAngles[PITCH] = -180 / M_PI * atan2( focusPoint[2], focusDist );
+ cg.refdefViewAngles[YAW] -= cg_thirdPersonAngle.value;
+}
+
+
+// this causes a compiler bug on mac MrC compiler
+static void CG_StepOffset( void ) {
+ int timeDelta;
+
+ // smooth out stair climbing
+ timeDelta = cg.time - cg.stepTime;
+ if ( timeDelta < STEP_TIME ) {
+ cg.refdef.vieworg[2] -= cg.stepChange
+ * (STEP_TIME - timeDelta) / STEP_TIME;
+ }
+}
+
+/*
+===============
+CG_OffsetFirstPersonView
+
+===============
+*/
+static void CG_OffsetFirstPersonView( void ) {
+ float *origin;
+ float *angles;
+ float bob;
+ float ratio;
+ float delta;
+ float speed;
+ float f;
+ vec3_t predictedVelocity;
+ int timeDelta;
+
+ if ( cg.snap->ps.pm_type == PM_INTERMISSION ) {
+ return;
+ }
+
+ origin = cg.refdef.vieworg;
+ angles = cg.refdefViewAngles;
+
+ // if dead, fix the angle and don't add any kick
+ if ( cg.snap->ps.stats[STAT_HEALTH] <= 0 ) {
+ angles[ROLL] = 40;
+ angles[PITCH] = -15;
+ angles[YAW] = cg.snap->ps.stats[STAT_DEAD_YAW];
+ origin[2] += cg.predictedPlayerState.viewheight;
+ return;
+ }
+
+ // add angles based on weapon kick
+ VectorAdd (angles, cg.kick_angles, angles);
+
+ // add angles based on damage kick
+ if ( cg.damageTime ) {
+ ratio = cg.time - cg.damageTime;
+ if ( ratio < DAMAGE_DEFLECT_TIME ) {
+ ratio /= DAMAGE_DEFLECT_TIME;
+ angles[PITCH] += ratio * cg.v_dmg_pitch;
+ angles[ROLL] += ratio * cg.v_dmg_roll;
+ } else {
+ ratio = 1.0 - ( ratio - DAMAGE_DEFLECT_TIME ) / DAMAGE_RETURN_TIME;
+ if ( ratio > 0 ) {
+ angles[PITCH] += ratio * cg.v_dmg_pitch;
+ angles[ROLL] += ratio * cg.v_dmg_roll;
+ }
+ }
+ }
+
+ // add pitch based on fall kick
+#if 0
+ ratio = ( cg.time - cg.landTime) / FALL_TIME;
+ if (ratio < 0)
+ ratio = 0;
+ angles[PITCH] += ratio * cg.fall_value;
+#endif
+
+ // add angles based on velocity
+ VectorCopy( cg.predictedPlayerState.velocity, predictedVelocity );
+
+ delta = DotProduct ( predictedVelocity, cg.refdef.viewaxis[0]);
+ angles[PITCH] += delta * cg_runpitch.value;
+
+ delta = DotProduct ( predictedVelocity, cg.refdef.viewaxis[1]);
+ angles[ROLL] -= delta * cg_runroll.value;
+
+ // add angles based on bob
+
+ // make sure the bob is visible even at low speeds
+ speed = cg.xyspeed > 200 ? cg.xyspeed : 200;
+
+ delta = cg.bobfracsin * cg_bobpitch.value * speed;
+ if (cg.predictedPlayerState.pm_flags & PMF_DUCKED)
+ delta *= 3; // crouching
+ angles[PITCH] += delta;
+ delta = cg.bobfracsin * cg_bobroll.value * speed;
+ if (cg.predictedPlayerState.pm_flags & PMF_DUCKED)
+ delta *= 3; // crouching accentuates roll
+ if (cg.bobcycle & 1)
+ delta = -delta;
+ angles[ROLL] += delta;
+
+//===================================
+
+ // add view height
+ origin[2] += cg.predictedPlayerState.viewheight;
+
+ // smooth out duck height changes
+ timeDelta = cg.time - cg.duckTime;
+ if ( timeDelta < DUCK_TIME) {
+ cg.refdef.vieworg[2] -= cg.duckChange
+ * (DUCK_TIME - timeDelta) / DUCK_TIME;
+ }
+
+ // add bob height
+ bob = cg.bobfracsin * cg.xyspeed * cg_bobup.value;
+ if (bob > 6) {
+ bob = 6;
+ }
+
+ origin[2] += bob;
+
+
+ // add fall height
+ delta = cg.time - cg.landTime;
+ if ( delta < LAND_DEFLECT_TIME ) {
+ f = delta / LAND_DEFLECT_TIME;
+ cg.refdef.vieworg[2] += cg.landChange * f;
+ } else if ( delta < LAND_DEFLECT_TIME + LAND_RETURN_TIME ) {
+ delta -= LAND_DEFLECT_TIME;
+ f = 1.0 - ( delta / LAND_RETURN_TIME );
+ cg.refdef.vieworg[2] += cg.landChange * f;
+ }
+
+ // add step offset
+ CG_StepOffset();
+
+ // add kick offset
+
+ VectorAdd (origin, cg.kick_origin, origin);
+
+ // pivot the eye based on a neck length
+#if 0
+ {
+#define NECK_LENGTH 8
+ vec3_t forward, up;
+
+ cg.refdef.vieworg[2] -= NECK_LENGTH;
+ AngleVectors( cg.refdefViewAngles, forward, NULL, up );
+ VectorMA( cg.refdef.vieworg, 3, forward, cg.refdef.vieworg );
+ VectorMA( cg.refdef.vieworg, NECK_LENGTH, up, cg.refdef.vieworg );
+ }
+#endif
+}
+
+//======================================================================
+
+void CG_ZoomDown_f( void ) {
+ if ( cg.zoomed ) {
+ return;
+ }
+ cg.zoomed = qtrue;
+ cg.zoomTime = cg.time;
+}
+
+void CG_ZoomUp_f( void ) {
+ if ( !cg.zoomed ) {
+ return;
+ }
+ cg.zoomed = qfalse;
+ cg.zoomTime = cg.time;
+}
+
+
+/*
+====================
+CG_CalcFov
+
+Fixed fov at intermissions, otherwise account for fov variable and zooms.
+====================
+*/
+#define WAVE_AMPLITUDE 1
+#define WAVE_FREQUENCY 0.4
+
+static int CG_CalcFov( void ) {
+ float x;
+ float phase;
+ float v;
+ int contents;
+ float fov_x, fov_y;
+ float zoomFov;
+ float f;
+ int inwater;
+
+ if ( cg.predictedPlayerState.pm_type == PM_INTERMISSION ) {
+ // if in intermission, use a fixed value
+ fov_x = 90;
+ } else {
+ // user selectable
+ if ( cgs.dmflags & DF_FIXED_FOV ) {
+ // dmflag to prevent wide fov for all clients
+ fov_x = 90;
+ } else {
+ fov_x = cg_fov.value;
+ if ( fov_x < 1 ) {
+ fov_x = 1;
+ } else if ( fov_x > 160 ) {
+ fov_x = 160;
+ }
+ }
+
+ // account for zooms
+ zoomFov = cg_zoomFov.value;
+ if ( zoomFov < 1 ) {
+ zoomFov = 1;
+ } else if ( zoomFov > 160 ) {
+ zoomFov = 160;
+ }
+
+ if ( cg.zoomed ) {
+ f = ( cg.time - cg.zoomTime ) / (float)ZOOM_TIME;
+ if ( f > 1.0 ) {
+ fov_x = zoomFov;
+ } else {
+ fov_x = fov_x + f * ( zoomFov - fov_x );
+ }
+ } else {
+ f = ( cg.time - cg.zoomTime ) / (float)ZOOM_TIME;
+ if ( f > 1.0 ) {
+ fov_x = fov_x;
+ } else {
+ fov_x = zoomFov + f * ( fov_x - zoomFov );
+ }
+ }
+ }
+
+ x = cg.refdef.width / tan( fov_x / 360 * M_PI );
+ fov_y = atan2( cg.refdef.height, x );
+ fov_y = fov_y * 360 / M_PI;
+
+ // warp if underwater
+ contents = CG_PointContents( cg.refdef.vieworg, -1 );
+ if ( contents & ( CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA ) ){
+ phase = cg.time / 1000.0 * WAVE_FREQUENCY * M_PI * 2;
+ v = WAVE_AMPLITUDE * sin( phase );
+ fov_x += v;
+ fov_y -= v;
+ inwater = qtrue;
+ }
+ else {
+ inwater = qfalse;
+ }
+
+
+ // set it
+ cg.refdef.fov_x = fov_x;
+ cg.refdef.fov_y = fov_y;
+
+ if ( !cg.zoomed ) {
+ cg.zoomSensitivity = 1;
+ } else {
+ cg.zoomSensitivity = cg.refdef.fov_y / 75.0;
+ }
+
+ return inwater;
+}
+
+
+
+/*
+===============
+CG_DamageBlendBlob
+
+===============
+*/
+static void CG_DamageBlendBlob( void ) {
+ int t;
+ int maxTime;
+ refEntity_t ent;
+
+ if ( !cg.damageValue ) {
+ return;
+ }
+
+ //if (cg.cameraMode) {
+ // return;
+ //}
+
+ // ragePro systems can't fade blends, so don't obscure the screen
+ if ( cgs.glconfig.hardwareType == GLHW_RAGEPRO ) {
+ return;
+ }
+
+ maxTime = DAMAGE_TIME;
+ t = cg.time - cg.damageTime;
+ if ( t <= 0 || t >= maxTime ) {
+ return;
+ }
+
+
+ memset( &ent, 0, sizeof( ent ) );
+ ent.reType = RT_SPRITE;
+ ent.renderfx = RF_FIRST_PERSON;
+
+ VectorMA( cg.refdef.vieworg, 8, cg.refdef.viewaxis[0], ent.origin );
+ VectorMA( ent.origin, cg.damageX * -8, cg.refdef.viewaxis[1], ent.origin );
+ VectorMA( ent.origin, cg.damageY * 8, cg.refdef.viewaxis[2], ent.origin );
+
+ ent.radius = cg.damageValue * 3;
+ ent.customShader = cgs.media.viewBloodShader;
+ ent.shaderRGBA[0] = 255;
+ ent.shaderRGBA[1] = 255;
+ ent.shaderRGBA[2] = 255;
+ ent.shaderRGBA[3] = 200 * ( 1.0 - ((float)t / maxTime) );
+ trap_R_AddRefEntityToScene( &ent );
+}
+
+
+/*
+===============
+CG_CalcViewValues
+
+Sets cg.refdef view values
+===============
+*/
+static int CG_CalcViewValues( void ) {
+ playerState_t *ps;
+
+ memset( &cg.refdef, 0, sizeof( cg.refdef ) );
+
+ // strings for in game rendering
+ // Q_strncpyz( cg.refdef.text[0], "Park Ranger", sizeof(cg.refdef.text[0]) );
+ // Q_strncpyz( cg.refdef.text[1], "19", sizeof(cg.refdef.text[1]) );
+
+ // calculate size of 3D view
+ CG_CalcVrect();
+
+ ps = &cg.predictedPlayerState;
+/*
+ if (cg.cameraMode) {
+ vec3_t origin, angles;
+ if (trap_getCameraInfo(cg.time, &origin, &angles)) {
+ VectorCopy(origin, cg.refdef.vieworg);
+ angles[ROLL] = 0;
+ VectorCopy(angles, cg.refdefViewAngles);
+ AnglesToAxis( cg.refdefViewAngles, cg.refdef.viewaxis );
+ return CG_CalcFov();
+ } else {
+ cg.cameraMode = qfalse;
+ }
+ }
+*/
+ // intermission view
+ if ( ps->pm_type == PM_INTERMISSION ) {
+ VectorCopy( ps->origin, cg.refdef.vieworg );
+ VectorCopy( ps->viewangles, cg.refdefViewAngles );
+ AnglesToAxis( cg.refdefViewAngles, cg.refdef.viewaxis );
+ return CG_CalcFov();
+ }
+
+ cg.bobcycle = ( ps->bobCycle & 128 ) >> 7;
+ cg.bobfracsin = fabs( sin( ( ps->bobCycle & 127 ) / 127.0 * M_PI ) );
+ cg.xyspeed = sqrt( ps->velocity[0] * ps->velocity[0] +
+ ps->velocity[1] * ps->velocity[1] );
+
+
+ VectorCopy( ps->origin, cg.refdef.vieworg );
+ VectorCopy( ps->viewangles, cg.refdefViewAngles );
+
+ if (cg_cameraOrbit.integer) {
+ if (cg.time > cg.nextOrbitTime) {
+ cg.nextOrbitTime = cg.time + cg_cameraOrbitDelay.integer;
+ cg_thirdPersonAngle.value += cg_cameraOrbit.value;
+ }
+ }
+ // add error decay
+ if ( cg_errorDecay.value > 0 ) {
+ int t;
+ float f;
+
+ t = cg.time - cg.predictedErrorTime;
+ f = ( cg_errorDecay.value - t ) / cg_errorDecay.value;
+ if ( f > 0 && f < 1 ) {
+ VectorMA( cg.refdef.vieworg, f, cg.predictedError, cg.refdef.vieworg );
+ } else {
+ cg.predictedErrorTime = 0;
+ }
+ }
+
+ if ( cg.renderingThirdPerson ) {
+ // back away from character
+ CG_OffsetThirdPersonView();
+ } else {
+ // offset for local bobbing and kicks
+ CG_OffsetFirstPersonView();
+ }
+
+ // position eye reletive to origin
+ AnglesToAxis( cg.refdefViewAngles, cg.refdef.viewaxis );
+
+ if ( cg.hyperspace ) {
+ cg.refdef.rdflags |= RDF_NOWORLDMODEL | RDF_HYPERSPACE;
+ }
+
+ // field of view
+ return CG_CalcFov();
+}
+
+
+/*
+=====================
+CG_PowerupTimerSounds
+=====================
+*/
+static void CG_PowerupTimerSounds( void ) {
+ int i;
+ int t;
+
+ // powerup timers going away
+ for ( i = 0 ; i < MAX_POWERUPS ; i++ ) {
+ t = cg.snap->ps.powerups[i];
+ if ( t <= cg.time ) {
+ continue;
+ }
+ if ( t - cg.time >= POWERUP_BLINKS * POWERUP_BLINK_TIME ) {
+ continue;
+ }
+ if ( ( t - cg.time ) / POWERUP_BLINK_TIME != ( t - cg.oldTime ) / POWERUP_BLINK_TIME ) {
+ trap_S_StartSound( NULL, cg.snap->ps.clientNum, CHAN_ITEM, cgs.media.wearOffSound );
+ }
+ }
+}
+
+/*
+=====================
+CG_AddBufferedSound
+=====================
+*/
+void CG_AddBufferedSound( sfxHandle_t sfx ) {
+ if ( !sfx )
+ return;
+ cg.soundBuffer[cg.soundBufferIn] = sfx;
+ cg.soundBufferIn = (cg.soundBufferIn + 1) % MAX_SOUNDBUFFER;
+ if (cg.soundBufferIn == cg.soundBufferOut) {
+ cg.soundBufferOut++;
+ }
+}
+
+/*
+=====================
+CG_PlayBufferedSounds
+=====================
+*/
+static void CG_PlayBufferedSounds( void ) {
+ if ( cg.soundTime < cg.time ) {
+ if (cg.soundBufferOut != cg.soundBufferIn && cg.soundBuffer[cg.soundBufferOut]) {
+ trap_S_StartLocalSound(cg.soundBuffer[cg.soundBufferOut], CHAN_ANNOUNCER);
+ cg.soundBuffer[cg.soundBufferOut] = 0;
+ cg.soundBufferOut = (cg.soundBufferOut + 1) % MAX_SOUNDBUFFER;
+ cg.soundTime = cg.time + 750;
+ }
+ }
+}
+
+//=========================================================================
+
+/*
+=================
+CG_DrawActiveFrame
+
+Generates and draws a game scene and status information at the given time.
+=================
+*/
+void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView, qboolean demoPlayback ) {
+ int inwater;
+
+ cg.time = serverTime;
+ cg.demoPlayback = demoPlayback;
+
+ // update cvars
+ CG_UpdateCvars();
+
+ // if we are only updating the screen as a loading
+ // pacifier, don't even try to read snapshots
+ if ( cg.infoScreenText[0] != 0 ) {
+ CG_DrawInformation();
+ return;
+ }
+
+ // any looped sounds will be respecified as entities
+ // are added to the render list
+ trap_S_ClearLoopingSounds(qfalse);
+
+ // clear all the render lists
+ trap_R_ClearScene();
+
+ // set up cg.snap and possibly cg.nextSnap
+ CG_ProcessSnapshots();
+
+ // if we haven't received any snapshots yet, all
+ // we can draw is the information screen
+ if ( !cg.snap || ( cg.snap->snapFlags & SNAPFLAG_NOT_ACTIVE ) ) {
+ CG_DrawInformation();
+ return;
+ }
+
+ // let the client system know what our weapon and zoom settings are
+ trap_SetUserCmdValue( cg.weaponSelect, cg.zoomSensitivity );
+
+ // this counter will be bumped for every valid scene we generate
+ cg.clientFrame++;
+
+ // update cg.predictedPlayerState
+ CG_PredictPlayerState();
+
+ // decide on third person view
+ cg.renderingThirdPerson = cg_thirdPerson.integer || (cg.snap->ps.stats[STAT_HEALTH] <= 0);
+
+ // build cg.refdef
+ inwater = CG_CalcViewValues();
+
+ // first person blend blobs, done after AnglesToAxis
+ if ( !cg.renderingThirdPerson ) {
+ CG_DamageBlendBlob();
+ }
+
+ // build the render lists
+ if ( !cg.hyperspace ) {
+ CG_AddPacketEntities(); // adter calcViewValues, so predicted player state is correct
+ CG_AddMarks();
+ CG_AddParticles ();
+ CG_AddLocalEntities();
+ }
+ CG_AddViewWeapon( &cg.predictedPlayerState );
+
+ // add buffered sounds
+ CG_PlayBufferedSounds();
+
+ // play buffered voice chats
+ CG_PlayBufferedVoiceChats();
+
+ // finish up the rest of the refdef
+ if ( cg.testModelEntity.hModel ) {
+ CG_AddTestModel();
+ }
+ cg.refdef.time = cg.time;
+ memcpy( cg.refdef.areamask, cg.snap->areamask, sizeof( cg.refdef.areamask ) );
+
+ // warning sounds when powerup is wearing off
+ CG_PowerupTimerSounds();
+
+ // update audio positions
+ trap_S_Respatialize( cg.snap->ps.clientNum, cg.refdef.vieworg, cg.refdef.viewaxis, inwater );
+
+ // make sure the lagometerSample and frame timing isn't done twice when in stereo
+ if ( stereoView != STEREO_RIGHT ) {
+ cg.frametime = cg.time - cg.oldTime;
+ if ( cg.frametime < 0 ) {
+ cg.frametime = 0;
+ }
+ cg.oldTime = cg.time;
+ CG_AddLagometerFrameInfo();
+ }
+ if (cg_timescale.value != cg_timescaleFadeEnd.value) {
+ if (cg_timescale.value < cg_timescaleFadeEnd.value) {
+ cg_timescale.value += cg_timescaleFadeSpeed.value * ((float)cg.frametime) / 1000;
+ if (cg_timescale.value > cg_timescaleFadeEnd.value)
+ cg_timescale.value = cg_timescaleFadeEnd.value;
+ }
+ else {
+ cg_timescale.value -= cg_timescaleFadeSpeed.value * ((float)cg.frametime) / 1000;
+ if (cg_timescale.value < cg_timescaleFadeEnd.value)
+ cg_timescale.value = cg_timescaleFadeEnd.value;
+ }
+ if (cg_timescaleFadeSpeed.value) {
+ trap_Cvar_Set("timescale", va("%f", cg_timescale.value));
+ }
+ }
+
+ // actually issue the rendering calls
+ CG_DrawActive( stereoView );
+
+ if ( cg_stats.integer ) {
+ CG_Printf( "cg.clientFrame:%i\n", cg.clientFrame );
+ }
+
+
+}
+
diff --git a/code/cgame/cg_weapons.c b/code/cgame/cg_weapons.c
new file mode 100755
index 0000000..9ac1ca9
--- /dev/null
+++ b/code/cgame/cg_weapons.c
@@ -0,0 +1,2277 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// cg_weapons.c -- events and effects dealing with weapons
+#include "cg_local.h"
+
+/*
+==========================
+CG_MachineGunEjectBrass
+==========================
+*/
+static void CG_MachineGunEjectBrass( centity_t *cent ) {
+ localEntity_t *le;
+ refEntity_t *re;
+ vec3_t velocity, xvelocity;
+ vec3_t offset, xoffset;
+ float waterScale = 1.0f;
+ vec3_t v[3];
+
+ if ( cg_brassTime.integer <= 0 ) {
+ return;
+ }
+
+ le = CG_AllocLocalEntity();
+ re = &le->refEntity;
+
+ velocity[0] = 0;
+ velocity[1] = -50 + 40 * crandom();
+ velocity[2] = 100 + 50 * crandom();
+
+ le->leType = LE_FRAGMENT;
+ le->startTime = cg.time;
+ le->endTime = le->startTime + cg_brassTime.integer + ( cg_brassTime.integer / 4 ) * random();
+
+ le->pos.trType = TR_GRAVITY;
+ le->pos.trTime = cg.time - (rand()&15);
+
+ AnglesToAxis( cent->lerpAngles, v );
+
+ offset[0] = 8;
+ offset[1] = -4;
+ offset[2] = 24;
+
+ xoffset[0] = offset[0] * v[0][0] + offset[1] * v[1][0] + offset[2] * v[2][0];
+ xoffset[1] = offset[0] * v[0][1] + offset[1] * v[1][1] + offset[2] * v[2][1];
+ xoffset[2] = offset[0] * v[0][2] + offset[1] * v[1][2] + offset[2] * v[2][2];
+ VectorAdd( cent->lerpOrigin, xoffset, re->origin );
+
+ VectorCopy( re->origin, le->pos.trBase );
+
+ if ( CG_PointContents( re->origin, -1 ) & CONTENTS_WATER ) {
+ waterScale = 0.10f;
+ }
+
+ xvelocity[0] = velocity[0] * v[0][0] + velocity[1] * v[1][0] + velocity[2] * v[2][0];
+ xvelocity[1] = velocity[0] * v[0][1] + velocity[1] * v[1][1] + velocity[2] * v[2][1];
+ xvelocity[2] = velocity[0] * v[0][2] + velocity[1] * v[1][2] + velocity[2] * v[2][2];
+ VectorScale( xvelocity, waterScale, le->pos.trDelta );
+
+ AxisCopy( axisDefault, re->axis );
+ re->hModel = cgs.media.machinegunBrassModel;
+
+ le->bounceFactor = 0.4 * waterScale;
+
+ le->angles.trType = TR_LINEAR;
+ le->angles.trTime = cg.time;
+ le->angles.trBase[0] = rand()&31;
+ le->angles.trBase[1] = rand()&31;
+ le->angles.trBase[2] = rand()&31;
+ le->angles.trDelta[0] = 2;
+ le->angles.trDelta[1] = 1;
+ le->angles.trDelta[2] = 0;
+
+ le->leFlags = LEF_TUMBLE;
+ le->leBounceSoundType = LEBS_BRASS;
+ le->leMarkType = LEMT_NONE;
+}
+
+/*
+==========================
+CG_ShotgunEjectBrass
+==========================
+*/
+static void CG_ShotgunEjectBrass( centity_t *cent ) {
+ localEntity_t *le;
+ refEntity_t *re;
+ vec3_t velocity, xvelocity;
+ vec3_t offset, xoffset;
+ vec3_t v[3];
+ int i;
+
+ if ( cg_brassTime.integer <= 0 ) {
+ return;
+ }
+
+ for ( i = 0; i < 2; i++ ) {
+ float waterScale = 1.0f;
+
+ le = CG_AllocLocalEntity();
+ re = &le->refEntity;
+
+ velocity[0] = 60 + 60 * crandom();
+ if ( i == 0 ) {
+ velocity[1] = 40 + 10 * crandom();
+ } else {
+ velocity[1] = -40 + 10 * crandom();
+ }
+ velocity[2] = 100 + 50 * crandom();
+
+ le->leType = LE_FRAGMENT;
+ le->startTime = cg.time;
+ le->endTime = le->startTime + cg_brassTime.integer*3 + cg_brassTime.integer * random();
+
+ le->pos.trType = TR_GRAVITY;
+ le->pos.trTime = cg.time;
+
+ AnglesToAxis( cent->lerpAngles, v );
+
+ offset[0] = 8;
+ offset[1] = 0;
+ offset[2] = 24;
+
+ xoffset[0] = offset[0] * v[0][0] + offset[1] * v[1][0] + offset[2] * v[2][0];
+ xoffset[1] = offset[0] * v[0][1] + offset[1] * v[1][1] + offset[2] * v[2][1];
+ xoffset[2] = offset[0] * v[0][2] + offset[1] * v[1][2] + offset[2] * v[2][2];
+ VectorAdd( cent->lerpOrigin, xoffset, re->origin );
+ VectorCopy( re->origin, le->pos.trBase );
+ if ( CG_PointContents( re->origin, -1 ) & CONTENTS_WATER ) {
+ waterScale = 0.10f;
+ }
+
+ xvelocity[0] = velocity[0] * v[0][0] + velocity[1] * v[1][0] + velocity[2] * v[2][0];
+ xvelocity[1] = velocity[0] * v[0][1] + velocity[1] * v[1][1] + velocity[2] * v[2][1];
+ xvelocity[2] = velocity[0] * v[0][2] + velocity[1] * v[1][2] + velocity[2] * v[2][2];
+ VectorScale( xvelocity, waterScale, le->pos.trDelta );
+
+ AxisCopy( axisDefault, re->axis );
+ re->hModel = cgs.media.shotgunBrassModel;
+ le->bounceFactor = 0.3f;
+
+ le->angles.trType = TR_LINEAR;
+ le->angles.trTime = cg.time;
+ le->angles.trBase[0] = rand()&31;
+ le->angles.trBase[1] = rand()&31;
+ le->angles.trBase[2] = rand()&31;
+ le->angles.trDelta[0] = 1;
+ le->angles.trDelta[1] = 0.5;
+ le->angles.trDelta[2] = 0;
+
+ le->leFlags = LEF_TUMBLE;
+ le->leBounceSoundType = LEBS_BRASS;
+ le->leMarkType = LEMT_NONE;
+ }
+}
+
+
+#ifdef MISSIONPACK
+/*
+==========================
+CG_NailgunEjectBrass
+==========================
+*/
+static void CG_NailgunEjectBrass( centity_t *cent ) {
+ localEntity_t *smoke;
+ vec3_t origin;
+ vec3_t v[3];
+ vec3_t offset;
+ vec3_t xoffset;
+ vec3_t up;
+
+ AnglesToAxis( cent->lerpAngles, v );
+
+ offset[0] = 0;
+ offset[1] = -12;
+ offset[2] = 24;
+
+ xoffset[0] = offset[0] * v[0][0] + offset[1] * v[1][0] + offset[2] * v[2][0];
+ xoffset[1] = offset[0] * v[0][1] + offset[1] * v[1][1] + offset[2] * v[2][1];
+ xoffset[2] = offset[0] * v[0][2] + offset[1] * v[1][2] + offset[2] * v[2][2];
+ VectorAdd( cent->lerpOrigin, xoffset, origin );
+
+ VectorSet( up, 0, 0, 64 );
+
+ smoke = CG_SmokePuff( origin, up, 32, 1, 1, 1, 0.33f, 700, cg.time, 0, 0, cgs.media.smokePuffShader );
+ // use the optimized local entity add
+ smoke->leType = LE_SCALE_FADE;
+}
+#endif
+
+
+/*
+==========================
+CG_RailTrail
+==========================
+*/
+void CG_RailTrail (clientInfo_t *ci, vec3_t start, vec3_t end) {
+ vec3_t axis[36], move, move2, next_move, vec, temp;
+ float len;
+ int i, j, skip;
+
+ localEntity_t *le;
+ refEntity_t *re;
+
+#define RADIUS 4
+#define ROTATION 1
+#define SPACING 5
+
+ start[2] -= 4;
+ VectorCopy (start, move);
+ VectorSubtract (end, start, vec);
+ len = VectorNormalize (vec);
+ PerpendicularVector(temp, vec);
+ for (i = 0 ; i < 36; i++) {
+ RotatePointAroundVector(axis[i], vec, temp, i * 10);//banshee 2.4 was 10
+ }
+
+ le = CG_AllocLocalEntity();
+ re = &le->refEntity;
+
+ le->leType = LE_FADE_RGB;
+ le->startTime = cg.time;
+ le->endTime = cg.time + cg_railTrailTime.value;
+ le->lifeRate = 1.0 / (le->endTime - le->startTime);
+
+ re->shaderTime = cg.time / 1000.0f;
+ re->reType = RT_RAIL_CORE;
+ re->customShader = cgs.media.railCoreShader;
+
+ VectorCopy(start, re->origin);
+ VectorCopy(end, re->oldorigin);
+
+ re->shaderRGBA[0] = ci->color1[0] * 255;
+ re->shaderRGBA[1] = ci->color1[1] * 255;
+ re->shaderRGBA[2] = ci->color1[2] * 255;
+ re->shaderRGBA[3] = 255;
+
+ le->color[0] = ci->color1[0] * 0.75;
+ le->color[1] = ci->color1[1] * 0.75;
+ le->color[2] = ci->color1[2] * 0.75;
+ le->color[3] = 1.0f;
+
+ AxisClear( re->axis );
+
+ VectorMA(move, 20, vec, move);
+ VectorCopy(move, next_move);
+ VectorScale (vec, SPACING, vec);
+
+ if (cg_oldRail.integer != 0) {
+ // nudge down a bit so it isn't exactly in center
+ re->origin[2] -= 8;
+ re->oldorigin[2] -= 8;
+ return;
+ }
+ skip = -1;
+
+ j = 18;
+ for (i = 0; i < len; i += SPACING) {
+ if (i != skip) {
+ skip = i + SPACING;
+ le = CG_AllocLocalEntity();
+ re = &le->refEntity;
+ le->leFlags = LEF_PUFF_DONT_SCALE;
+ le->leType = LE_MOVE_SCALE_FADE;
+ le->startTime = cg.time;
+ le->endTime = cg.time + (i>>1) + 600;
+ le->lifeRate = 1.0 / (le->endTime - le->startTime);
+
+ re->shaderTime = cg.time / 1000.0f;
+ re->reType = RT_SPRITE;
+ re->radius = 1.1f;
+ re->customShader = cgs.media.railRingsShader;
+
+ re->shaderRGBA[0] = ci->color2[0] * 255;
+ re->shaderRGBA[1] = ci->color2[1] * 255;
+ re->shaderRGBA[2] = ci->color2[2] * 255;
+ re->shaderRGBA[3] = 255;
+
+ le->color[0] = ci->color2[0] * 0.75;
+ le->color[1] = ci->color2[1] * 0.75;
+ le->color[2] = ci->color2[2] * 0.75;
+ le->color[3] = 1.0f;
+
+ le->pos.trType = TR_LINEAR;
+ le->pos.trTime = cg.time;
+
+ VectorCopy( move, move2);
+ VectorMA(move2, RADIUS , axis[j], move2);
+ VectorCopy(move2, le->pos.trBase);
+
+ le->pos.trDelta[0] = axis[j][0]*6;
+ le->pos.trDelta[1] = axis[j][1]*6;
+ le->pos.trDelta[2] = axis[j][2]*6;
+ }
+
+ VectorAdd (move, vec, move);
+
+ j = j + ROTATION < 36 ? j + ROTATION : (j + ROTATION) % 36;
+ }
+}
+
+/*
+==========================
+CG_RocketTrail
+==========================
+*/
+static void CG_RocketTrail( centity_t *ent, const weaponInfo_t *wi ) {
+ int step;
+ vec3_t origin, lastPos;
+ int t;
+ int startTime, contents;
+ int lastContents;
+ entityState_t *es;
+ vec3_t up;
+ localEntity_t *smoke;
+
+ if ( cg_noProjectileTrail.integer ) {
+ return;
+ }
+
+ up[0] = 0;
+ up[1] = 0;
+ up[2] = 0;
+
+ step = 50;
+
+ es = &ent->currentState;
+ startTime = ent->trailTime;
+ t = step * ( (startTime + step) / step );
+
+ BG_EvaluateTrajectory( &es->pos, cg.time, origin );
+ contents = CG_PointContents( origin, -1 );
+
+ // if object (e.g. grenade) is stationary, don't toss up smoke
+ if ( es->pos.trType == TR_STATIONARY ) {
+ ent->trailTime = cg.time;
+ return;
+ }
+
+ BG_EvaluateTrajectory( &es->pos, ent->trailTime, lastPos );
+ lastContents = CG_PointContents( lastPos, -1 );
+
+ ent->trailTime = cg.time;
+
+ if ( contents & ( CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA ) ) {
+ if ( contents & lastContents & CONTENTS_WATER ) {
+ CG_BubbleTrail( lastPos, origin, 8 );
+ }
+ return;
+ }
+
+ for ( ; t <= ent->trailTime ; t += step ) {
+ BG_EvaluateTrajectory( &es->pos, t, lastPos );
+
+ smoke = CG_SmokePuff( lastPos, up,
+ wi->trailRadius,
+ 1, 1, 1, 0.33f,
+ wi->wiTrailTime,
+ t,
+ 0,
+ 0,
+ cgs.media.smokePuffShader );
+ // use the optimized local entity add
+ smoke->leType = LE_SCALE_FADE;
+ }
+
+}
+
+#ifdef MISSIONPACK
+/*
+==========================
+CG_NailTrail
+==========================
+*/
+static void CG_NailTrail( centity_t *ent, const weaponInfo_t *wi ) {
+ int step;
+ vec3_t origin, lastPos;
+ int t;
+ int startTime, contents;
+ int lastContents;
+ entityState_t *es;
+ vec3_t up;
+ localEntity_t *smoke;
+
+ if ( cg_noProjectileTrail.integer ) {
+ return;
+ }
+
+ up[0] = 0;
+ up[1] = 0;
+ up[2] = 0;
+
+ step = 50;
+
+ es = &ent->currentState;
+ startTime = ent->trailTime;
+ t = step * ( (startTime + step) / step );
+
+ BG_EvaluateTrajectory( &es->pos, cg.time, origin );
+ contents = CG_PointContents( origin, -1 );
+
+ // if object (e.g. grenade) is stationary, don't toss up smoke
+ if ( es->pos.trType == TR_STATIONARY ) {
+ ent->trailTime = cg.time;
+ return;
+ }
+
+ BG_EvaluateTrajectory( &es->pos, ent->trailTime, lastPos );
+ lastContents = CG_PointContents( lastPos, -1 );
+
+ ent->trailTime = cg.time;
+
+ if ( contents & ( CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA ) ) {
+ if ( contents & lastContents & CONTENTS_WATER ) {
+ CG_BubbleTrail( lastPos, origin, 8 );
+ }
+ return;
+ }
+
+ for ( ; t <= ent->trailTime ; t += step ) {
+ BG_EvaluateTrajectory( &es->pos, t, lastPos );
+
+ smoke = CG_SmokePuff( lastPos, up,
+ wi->trailRadius,
+ 1, 1, 1, 0.33f,
+ wi->wiTrailTime,
+ t,
+ 0,
+ 0,
+ cgs.media.nailPuffShader );
+ // use the optimized local entity add
+ smoke->leType = LE_SCALE_FADE;
+ }
+
+}
+#endif
+
+/*
+==========================
+CG_NailTrail
+==========================
+*/
+static void CG_PlasmaTrail( centity_t *cent, const weaponInfo_t *wi ) {
+ localEntity_t *le;
+ refEntity_t *re;
+ entityState_t *es;
+ vec3_t velocity, xvelocity, origin;
+ vec3_t offset, xoffset;
+ vec3_t v[3];
+ int t, startTime, step;
+
+ float waterScale = 1.0f;
+
+ if ( cg_noProjectileTrail.integer || cg_oldPlasma.integer ) {
+ return;
+ }
+
+ step = 50;
+
+ es = &cent->currentState;
+ startTime = cent->trailTime;
+ t = step * ( (startTime + step) / step );
+
+ BG_EvaluateTrajectory( &es->pos, cg.time, origin );
+
+ le = CG_AllocLocalEntity();
+ re = &le->refEntity;
+
+ velocity[0] = 60 - 120 * crandom();
+ velocity[1] = 40 - 80 * crandom();
+ velocity[2] = 100 - 200 * crandom();
+
+ le->leType = LE_MOVE_SCALE_FADE;
+ le->leFlags = LEF_TUMBLE;
+ le->leBounceSoundType = LEBS_NONE;
+ le->leMarkType = LEMT_NONE;
+
+ le->startTime = cg.time;
+ le->endTime = le->startTime + 600;
+
+ le->pos.trType = TR_GRAVITY;
+ le->pos.trTime = cg.time;
+
+ AnglesToAxis( cent->lerpAngles, v );
+
+ offset[0] = 2;
+ offset[1] = 2;
+ offset[2] = 2;
+
+ xoffset[0] = offset[0] * v[0][0] + offset[1] * v[1][0] + offset[2] * v[2][0];
+ xoffset[1] = offset[0] * v[0][1] + offset[1] * v[1][1] + offset[2] * v[2][1];
+ xoffset[2] = offset[0] * v[0][2] + offset[1] * v[1][2] + offset[2] * v[2][2];
+
+ VectorAdd( origin, xoffset, re->origin );
+ VectorCopy( re->origin, le->pos.trBase );
+
+ if ( CG_PointContents( re->origin, -1 ) & CONTENTS_WATER ) {
+ waterScale = 0.10f;
+ }
+
+ xvelocity[0] = velocity[0] * v[0][0] + velocity[1] * v[1][0] + velocity[2] * v[2][0];
+ xvelocity[1] = velocity[0] * v[0][1] + velocity[1] * v[1][1] + velocity[2] * v[2][1];
+ xvelocity[2] = velocity[0] * v[0][2] + velocity[1] * v[1][2] + velocity[2] * v[2][2];
+ VectorScale( xvelocity, waterScale, le->pos.trDelta );
+
+ AxisCopy( axisDefault, re->axis );
+ re->shaderTime = cg.time / 1000.0f;
+ re->reType = RT_SPRITE;
+ re->radius = 0.25f;
+ re->customShader = cgs.media.railRingsShader;
+ le->bounceFactor = 0.3f;
+
+ re->shaderRGBA[0] = wi->flashDlightColor[0] * 63;
+ re->shaderRGBA[1] = wi->flashDlightColor[1] * 63;
+ re->shaderRGBA[2] = wi->flashDlightColor[2] * 63;
+ re->shaderRGBA[3] = 63;
+
+ le->color[0] = wi->flashDlightColor[0] * 0.2;
+ le->color[1] = wi->flashDlightColor[1] * 0.2;
+ le->color[2] = wi->flashDlightColor[2] * 0.2;
+ le->color[3] = 0.25f;
+
+ le->angles.trType = TR_LINEAR;
+ le->angles.trTime = cg.time;
+ le->angles.trBase[0] = rand()&31;
+ le->angles.trBase[1] = rand()&31;
+ le->angles.trBase[2] = rand()&31;
+ le->angles.trDelta[0] = 1;
+ le->angles.trDelta[1] = 0.5;
+ le->angles.trDelta[2] = 0;
+
+}
+/*
+==========================
+CG_GrappleTrail
+==========================
+*/
+void CG_GrappleTrail( centity_t *ent, const weaponInfo_t *wi ) {
+ vec3_t origin;
+ entityState_t *es;
+ vec3_t forward, up;
+ refEntity_t beam;
+
+ es = &ent->currentState;
+
+ BG_EvaluateTrajectory( &es->pos, cg.time, origin );
+ ent->trailTime = cg.time;
+
+ memset( &beam, 0, sizeof( beam ) );
+ //FIXME adjust for muzzle position
+ VectorCopy ( cg_entities[ ent->currentState.otherEntityNum ].lerpOrigin, beam.origin );
+ beam.origin[2] += 26;
+ AngleVectors( cg_entities[ ent->currentState.otherEntityNum ].lerpAngles, forward, NULL, up );
+ VectorMA( beam.origin, -6, up, beam.origin );
+ VectorCopy( origin, beam.oldorigin );
+
+ if (Distance( beam.origin, beam.oldorigin ) < 64 )
+ return; // Don't draw if close
+
+ beam.reType = RT_LIGHTNING;
+ beam.customShader = cgs.media.lightningShader;
+
+ AxisClear( beam.axis );
+ beam.shaderRGBA[0] = 0xff;
+ beam.shaderRGBA[1] = 0xff;
+ beam.shaderRGBA[2] = 0xff;
+ beam.shaderRGBA[3] = 0xff;
+ trap_R_AddRefEntityToScene( &beam );
+}
+
+/*
+==========================
+CG_GrenadeTrail
+==========================
+*/
+static void CG_GrenadeTrail( centity_t *ent, const weaponInfo_t *wi ) {
+ CG_RocketTrail( ent, wi );
+}
+
+
+/*
+=================
+CG_RegisterWeapon
+
+The server says this item is used on this level
+=================
+*/
+void CG_RegisterWeapon( int weaponNum ) {
+ weaponInfo_t *weaponInfo;
+ gitem_t *item, *ammo;
+ char path[MAX_QPATH];
+ vec3_t mins, maxs;
+ int i;
+
+ weaponInfo = &cg_weapons[weaponNum];
+
+ if ( weaponNum == 0 ) {
+ return;
+ }
+
+ if ( weaponInfo->registered ) {
+ return;
+ }
+
+ memset( weaponInfo, 0, sizeof( *weaponInfo ) );
+ weaponInfo->registered = qtrue;
+
+ for ( item = bg_itemlist + 1 ; item->classname ; item++ ) {
+ if ( item->giType == IT_WEAPON && item->giTag == weaponNum ) {
+ weaponInfo->item = item;
+ break;
+ }
+ }
+ if ( !item->classname ) {
+ CG_Error( "Couldn't find weapon %i", weaponNum );
+ }
+ CG_RegisterItemVisuals( item - bg_itemlist );
+
+ // load cmodel before model so filecache works
+ weaponInfo->weaponModel = trap_R_RegisterModel( item->world_model[0] );
+
+ // calc midpoint for rotation
+ trap_R_ModelBounds( weaponInfo->weaponModel, mins, maxs );
+ for ( i = 0 ; i < 3 ; i++ ) {
+ weaponInfo->weaponMidpoint[i] = mins[i] + 0.5 * ( maxs[i] - mins[i] );
+ }
+
+ weaponInfo->weaponIcon = trap_R_RegisterShader( item->icon );
+ weaponInfo->ammoIcon = trap_R_RegisterShader( item->icon );
+
+ for ( ammo = bg_itemlist + 1 ; ammo->classname ; ammo++ ) {
+ if ( ammo->giType == IT_AMMO && ammo->giTag == weaponNum ) {
+ break;
+ }
+ }
+ if ( ammo->classname && ammo->world_model[0] ) {
+ weaponInfo->ammoModel = trap_R_RegisterModel( ammo->world_model[0] );
+ }
+
+ strcpy( path, item->world_model[0] );
+ COM_StripExtension( path, path );
+ strcat( path, "_flash.md3" );
+ weaponInfo->flashModel = trap_R_RegisterModel( path );
+
+ strcpy( path, item->world_model[0] );
+ COM_StripExtension( path, path );
+ strcat( path, "_barrel.md3" );
+ weaponInfo->barrelModel = trap_R_RegisterModel( path );
+
+ strcpy( path, item->world_model[0] );
+ COM_StripExtension( path, path );
+ strcat( path, "_hand.md3" );
+ weaponInfo->handsModel = trap_R_RegisterModel( path );
+
+ if ( !weaponInfo->handsModel ) {
+ weaponInfo->handsModel = trap_R_RegisterModel( "models/weapons2/shotgun/shotgun_hand.md3" );
+ }
+
+ weaponInfo->loopFireSound = qfalse;
+
+ switch ( weaponNum ) {
+ case WP_GAUNTLET:
+ MAKERGB( weaponInfo->flashDlightColor, 0.6f, 0.6f, 1.0f );
+ weaponInfo->firingSound = trap_S_RegisterSound( "sound/weapons/melee/fstrun.wav", qfalse );
+ weaponInfo->flashSound[0] = trap_S_RegisterSound( "sound/weapons/melee/fstatck.wav", qfalse );
+ break;
+
+ case WP_LIGHTNING:
+ MAKERGB( weaponInfo->flashDlightColor, 0.6f, 0.6f, 1.0f );
+ weaponInfo->readySound = trap_S_RegisterSound( "sound/weapons/melee/fsthum.wav", qfalse );
+ weaponInfo->firingSound = trap_S_RegisterSound( "sound/weapons/lightning/lg_hum.wav", qfalse );
+
+ weaponInfo->flashSound[0] = trap_S_RegisterSound( "sound/weapons/lightning/lg_fire.wav", qfalse );
+ cgs.media.lightningShader = trap_R_RegisterShader( "lightningBoltNew");
+ cgs.media.lightningExplosionModel = trap_R_RegisterModel( "models/weaphits/crackle.md3" );
+ cgs.media.sfx_lghit1 = trap_S_RegisterSound( "sound/weapons/lightning/lg_hit.wav", qfalse );
+ cgs.media.sfx_lghit2 = trap_S_RegisterSound( "sound/weapons/lightning/lg_hit2.wav", qfalse );
+ cgs.media.sfx_lghit3 = trap_S_RegisterSound( "sound/weapons/lightning/lg_hit3.wav", qfalse );
+
+ break;
+
+ case WP_GRAPPLING_HOOK:
+ MAKERGB( weaponInfo->flashDlightColor, 0.6f, 0.6f, 1.0f );
+ weaponInfo->missileModel = trap_R_RegisterModel( "models/ammo/rocket/rocket.md3" );
+ weaponInfo->missileTrailFunc = CG_GrappleTrail;
+ weaponInfo->missileDlight = 200;
+ weaponInfo->wiTrailTime = 2000;
+ weaponInfo->trailRadius = 64;
+ MAKERGB( weaponInfo->missileDlightColor, 1, 0.75f, 0 );
+ weaponInfo->readySound = trap_S_RegisterSound( "sound/weapons/melee/fsthum.wav", qfalse );
+ weaponInfo->firingSound = trap_S_RegisterSound( "sound/weapons/melee/fstrun.wav", qfalse );
+ break;
+
+#ifdef MISSIONPACK
+ case WP_CHAINGUN:
+ weaponInfo->firingSound = trap_S_RegisterSound( "sound/weapons/vulcan/wvulfire.wav", qfalse );
+ weaponInfo->loopFireSound = qtrue;
+ MAKERGB( weaponInfo->flashDlightColor, 1, 1, 0 );
+ weaponInfo->flashSound[0] = trap_S_RegisterSound( "sound/weapons/vulcan/vulcanf1b.wav", qfalse );
+ weaponInfo->flashSound[1] = trap_S_RegisterSound( "sound/weapons/vulcan/vulcanf2b.wav", qfalse );
+ weaponInfo->flashSound[2] = trap_S_RegisterSound( "sound/weapons/vulcan/vulcanf3b.wav", qfalse );
+ weaponInfo->flashSound[3] = trap_S_RegisterSound( "sound/weapons/vulcan/vulcanf4b.wav", qfalse );
+ weaponInfo->ejectBrassFunc = CG_MachineGunEjectBrass;
+ cgs.media.bulletExplosionShader = trap_R_RegisterShader( "bulletExplosion" );
+ break;
+#endif
+
+ case WP_MACHINEGUN:
+ MAKERGB( weaponInfo->flashDlightColor, 1, 1, 0 );
+ weaponInfo->flashSound[0] = trap_S_RegisterSound( "sound/weapons/machinegun/machgf1b.wav", qfalse );
+ weaponInfo->flashSound[1] = trap_S_RegisterSound( "sound/weapons/machinegun/machgf2b.wav", qfalse );
+ weaponInfo->flashSound[2] = trap_S_RegisterSound( "sound/weapons/machinegun/machgf3b.wav", qfalse );
+ weaponInfo->flashSound[3] = trap_S_RegisterSound( "sound/weapons/machinegun/machgf4b.wav", qfalse );
+ weaponInfo->ejectBrassFunc = CG_MachineGunEjectBrass;
+ cgs.media.bulletExplosionShader = trap_R_RegisterShader( "bulletExplosion" );
+ break;
+
+ case WP_SHOTGUN:
+ MAKERGB( weaponInfo->flashDlightColor, 1, 1, 0 );
+ weaponInfo->flashSound[0] = trap_S_RegisterSound( "sound/weapons/shotgun/sshotf1b.wav", qfalse );
+ weaponInfo->ejectBrassFunc = CG_ShotgunEjectBrass;
+ break;
+
+ case WP_ROCKET_LAUNCHER:
+ weaponInfo->missileModel = trap_R_RegisterModel( "models/ammo/rocket/rocket.md3" );
+ weaponInfo->missileSound = trap_S_RegisterSound( "sound/weapons/rocket/rockfly.wav", qfalse );
+ weaponInfo->missileTrailFunc = CG_RocketTrail;
+ weaponInfo->missileDlight = 200;
+ weaponInfo->wiTrailTime = 2000;
+ weaponInfo->trailRadius = 64;
+
+ MAKERGB( weaponInfo->missileDlightColor, 1, 0.75f, 0 );
+ MAKERGB( weaponInfo->flashDlightColor, 1, 0.75f, 0 );
+
+ weaponInfo->flashSound[0] = trap_S_RegisterSound( "sound/weapons/rocket/rocklf1a.wav", qfalse );
+ cgs.media.rocketExplosionShader = trap_R_RegisterShader( "rocketExplosion" );
+ break;
+
+#ifdef MISSIONPACK
+ case WP_PROX_LAUNCHER:
+ weaponInfo->missileModel = trap_R_RegisterModel( "models/weaphits/proxmine.md3" );
+ weaponInfo->missileTrailFunc = CG_GrenadeTrail;
+ weaponInfo->wiTrailTime = 700;
+ weaponInfo->trailRadius = 32;
+ MAKERGB( weaponInfo->flashDlightColor, 1, 0.70f, 0 );
+ weaponInfo->flashSound[0] = trap_S_RegisterSound( "sound/weapons/proxmine/wstbfire.wav", qfalse );
+ cgs.media.grenadeExplosionShader = trap_R_RegisterShader( "grenadeExplosion" );
+ break;
+#endif
+
+ case WP_GRENADE_LAUNCHER:
+ weaponInfo->missileModel = trap_R_RegisterModel( "models/ammo/grenade1.md3" );
+ weaponInfo->missileTrailFunc = CG_GrenadeTrail;
+ weaponInfo->wiTrailTime = 700;
+ weaponInfo->trailRadius = 32;
+ MAKERGB( weaponInfo->flashDlightColor, 1, 0.70f, 0 );
+ weaponInfo->flashSound[0] = trap_S_RegisterSound( "sound/weapons/grenade/grenlf1a.wav", qfalse );
+ cgs.media.grenadeExplosionShader = trap_R_RegisterShader( "grenadeExplosion" );
+ break;
+
+#ifdef MISSIONPACK
+ case WP_NAILGUN:
+ weaponInfo->ejectBrassFunc = CG_NailgunEjectBrass;
+ weaponInfo->missileTrailFunc = CG_NailTrail;
+// weaponInfo->missileSound = trap_S_RegisterSound( "sound/weapons/nailgun/wnalflit.wav", qfalse );
+ weaponInfo->trailRadius = 16;
+ weaponInfo->wiTrailTime = 250;
+ weaponInfo->missileModel = trap_R_RegisterModel( "models/weaphits/nail.md3" );
+ MAKERGB( weaponInfo->flashDlightColor, 1, 0.75f, 0 );
+ weaponInfo->flashSound[0] = trap_S_RegisterSound( "sound/weapons/nailgun/wnalfire.wav", qfalse );
+ break;
+#endif
+
+ case WP_PLASMAGUN:
+// weaponInfo->missileModel = cgs.media.invulnerabilityPowerupModel;
+ weaponInfo->missileTrailFunc = CG_PlasmaTrail;
+ weaponInfo->missileSound = trap_S_RegisterSound( "sound/weapons/plasma/lasfly.wav", qfalse );
+ MAKERGB( weaponInfo->flashDlightColor, 0.6f, 0.6f, 1.0f );
+ weaponInfo->flashSound[0] = trap_S_RegisterSound( "sound/weapons/plasma/hyprbf1a.wav", qfalse );
+ cgs.media.plasmaExplosionShader = trap_R_RegisterShader( "plasmaExplosion" );
+ cgs.media.railRingsShader = trap_R_RegisterShader( "railDisc" );
+ break;
+
+ case WP_RAILGUN:
+ weaponInfo->readySound = trap_S_RegisterSound( "sound/weapons/railgun/rg_hum.wav", qfalse );
+ MAKERGB( weaponInfo->flashDlightColor, 1, 0.5f, 0 );
+ weaponInfo->flashSound[0] = trap_S_RegisterSound( "sound/weapons/railgun/railgf1a.wav", qfalse );
+ cgs.media.railExplosionShader = trap_R_RegisterShader( "railExplosion" );
+ cgs.media.railRingsShader = trap_R_RegisterShader( "railDisc" );
+ cgs.media.railCoreShader = trap_R_RegisterShader( "railCore" );
+ break;
+
+ case WP_BFG:
+ weaponInfo->readySound = trap_S_RegisterSound( "sound/weapons/bfg/bfg_hum.wav", qfalse );
+ MAKERGB( weaponInfo->flashDlightColor, 1, 0.7f, 1 );
+ weaponInfo->flashSound[0] = trap_S_RegisterSound( "sound/weapons/bfg/bfg_fire.wav", qfalse );
+ cgs.media.bfgExplosionShader = trap_R_RegisterShader( "bfgExplosion" );
+ weaponInfo->missileModel = trap_R_RegisterModel( "models/weaphits/bfg.md3" );
+ weaponInfo->missileSound = trap_S_RegisterSound( "sound/weapons/rocket/rockfly.wav", qfalse );
+ break;
+
+ default:
+ MAKERGB( weaponInfo->flashDlightColor, 1, 1, 1 );
+ weaponInfo->flashSound[0] = trap_S_RegisterSound( "sound/weapons/rocket/rocklf1a.wav", qfalse );
+ break;
+ }
+}
+
+/*
+=================
+CG_RegisterItemVisuals
+
+The server says this item is used on this level
+=================
+*/
+void CG_RegisterItemVisuals( int itemNum ) {
+ itemInfo_t *itemInfo;
+ gitem_t *item;
+
+ if ( itemNum < 0 || itemNum >= bg_numItems ) {
+ CG_Error( "CG_RegisterItemVisuals: itemNum %d out of range [0-%d]", itemNum, bg_numItems-1 );
+ }
+
+ itemInfo = &cg_items[ itemNum ];
+ if ( itemInfo->registered ) {
+ return;
+ }
+
+ item = &bg_itemlist[ itemNum ];
+
+ memset( itemInfo, 0, sizeof( &itemInfo ) );
+ itemInfo->registered = qtrue;
+
+ itemInfo->models[0] = trap_R_RegisterModel( item->world_model[0] );
+
+ itemInfo->icon = trap_R_RegisterShader( item->icon );
+
+ if ( item->giType == IT_WEAPON ) {
+ CG_RegisterWeapon( item->giTag );
+ }
+
+ //
+ // powerups have an accompanying ring or sphere
+ //
+ if ( item->giType == IT_POWERUP || item->giType == IT_HEALTH ||
+ item->giType == IT_ARMOR || item->giType == IT_HOLDABLE ) {
+ if ( item->world_model[1] ) {
+ itemInfo->models[1] = trap_R_RegisterModel( item->world_model[1] );
+ }
+ }
+}
+
+
+/*
+========================================================================================
+
+VIEW WEAPON
+
+========================================================================================
+*/
+
+/*
+=================
+CG_MapTorsoToWeaponFrame
+
+=================
+*/
+static int CG_MapTorsoToWeaponFrame( clientInfo_t *ci, int frame ) {
+
+ // change weapon
+ if ( frame >= ci->animations[TORSO_DROP].firstFrame
+ && frame < ci->animations[TORSO_DROP].firstFrame + 9 ) {
+ return frame - ci->animations[TORSO_DROP].firstFrame + 6;
+ }
+
+ // stand attack
+ if ( frame >= ci->animations[TORSO_ATTACK].firstFrame
+ && frame < ci->animations[TORSO_ATTACK].firstFrame + 6 ) {
+ return 1 + frame - ci->animations[TORSO_ATTACK].firstFrame;
+ }
+
+ // stand attack 2
+ if ( frame >= ci->animations[TORSO_ATTACK2].firstFrame
+ && frame < ci->animations[TORSO_ATTACK2].firstFrame + 6 ) {
+ return 1 + frame - ci->animations[TORSO_ATTACK2].firstFrame;
+ }
+
+ return 0;
+}
+
+
+/*
+==============
+CG_CalculateWeaponPosition
+==============
+*/
+static void CG_CalculateWeaponPosition( vec3_t origin, vec3_t angles ) {
+ float scale;
+ int delta;
+ float fracsin;
+
+ VectorCopy( cg.refdef.vieworg, origin );
+ VectorCopy( cg.refdefViewAngles, angles );
+
+ // on odd legs, invert some angles
+ if ( cg.bobcycle & 1 ) {
+ scale = -cg.xyspeed;
+ } else {
+ scale = cg.xyspeed;
+ }
+
+ // gun angles from bobbing
+ angles[ROLL] += scale * cg.bobfracsin * 0.005;
+ angles[YAW] += scale * cg.bobfracsin * 0.01;
+ angles[PITCH] += cg.xyspeed * cg.bobfracsin * 0.005;
+
+ // drop the weapon when landing
+ delta = cg.time - cg.landTime;
+ if ( delta < LAND_DEFLECT_TIME ) {
+ origin[2] += cg.landChange*0.25 * delta / LAND_DEFLECT_TIME;
+ } else if ( delta < LAND_DEFLECT_TIME + LAND_RETURN_TIME ) {
+ origin[2] += cg.landChange*0.25 *
+ (LAND_DEFLECT_TIME + LAND_RETURN_TIME - delta) / LAND_RETURN_TIME;
+ }
+
+#if 0
+ // drop the weapon when stair climbing
+ delta = cg.time - cg.stepTime;
+ if ( delta < STEP_TIME/2 ) {
+ origin[2] -= cg.stepChange*0.25 * delta / (STEP_TIME/2);
+ } else if ( delta < STEP_TIME ) {
+ origin[2] -= cg.stepChange*0.25 * (STEP_TIME - delta) / (STEP_TIME/2);
+ }
+#endif
+
+ // idle drift
+ scale = cg.xyspeed + 40;
+ fracsin = sin( cg.time * 0.001 );
+ angles[ROLL] += scale * fracsin * 0.01;
+ angles[YAW] += scale * fracsin * 0.01;
+ angles[PITCH] += scale * fracsin * 0.01;
+}
+
+
+/*
+===============
+CG_LightningBolt
+
+Origin will be the exact tag point, which is slightly
+different than the muzzle point used for determining hits.
+The cent should be the non-predicted cent if it is from the player,
+so the endpoint will reflect the simulated strike (lagging the predicted
+angle)
+===============
+*/
+static void CG_LightningBolt( centity_t *cent, vec3_t origin ) {
+ trace_t trace;
+ refEntity_t beam;
+ vec3_t forward;
+ vec3_t muzzlePoint, endPoint;
+
+ if (cent->currentState.weapon != WP_LIGHTNING) {
+ return;
+ }
+
+ memset( &beam, 0, sizeof( beam ) );
+
+ // CPMA "true" lightning
+ if ((cent->currentState.number == cg.predictedPlayerState.clientNum) && (cg_trueLightning.value != 0)) {
+ vec3_t angle;
+ int i;
+
+ for (i = 0; i < 3; i++) {
+ float a = cent->lerpAngles[i] - cg.refdefViewAngles[i];
+ if (a > 180) {
+ a -= 360;
+ }
+ if (a < -180) {
+ a += 360;
+ }
+
+ angle[i] = cg.refdefViewAngles[i] + a * (1.0 - cg_trueLightning.value);
+ if (angle[i] < 0) {
+ angle[i] += 360;
+ }
+ if (angle[i] > 360) {
+ angle[i] -= 360;
+ }
+ }
+
+ AngleVectors(angle, forward, NULL, NULL );
+ VectorCopy(cent->lerpOrigin, muzzlePoint );
+// VectorCopy(cg.refdef.vieworg, muzzlePoint );
+ } else {
+ // !CPMA
+ AngleVectors( cent->lerpAngles, forward, NULL, NULL );
+ VectorCopy(cent->lerpOrigin, muzzlePoint );
+ }
+
+ // FIXME: crouch
+ muzzlePoint[2] += DEFAULT_VIEWHEIGHT;
+
+ VectorMA( muzzlePoint, 14, forward, muzzlePoint );
+
+ // project forward by the lightning range
+ VectorMA( muzzlePoint, LIGHTNING_RANGE, forward, endPoint );
+
+ // see if it hit a wall
+ CG_Trace( &trace, muzzlePoint, vec3_origin, vec3_origin, endPoint,
+ cent->currentState.number, MASK_SHOT );
+
+ // this is the endpoint
+ VectorCopy( trace.endpos, beam.oldorigin );
+
+ // use the provided origin, even though it may be slightly
+ // different than the muzzle origin
+ VectorCopy( origin, beam.origin );
+
+ beam.reType = RT_LIGHTNING;
+ beam.customShader = cgs.media.lightningShader;
+ trap_R_AddRefEntityToScene( &beam );
+
+ // add the impact flare if it hit something
+ if ( trace.fraction < 1.0 ) {
+ vec3_t angles;
+ vec3_t dir;
+
+ VectorSubtract( beam.oldorigin, beam.origin, dir );
+ VectorNormalize( dir );
+
+ memset( &beam, 0, sizeof( beam ) );
+ beam.hModel = cgs.media.lightningExplosionModel;
+
+ VectorMA( trace.endpos, -16, dir, beam.origin );
+
+ // make a random orientation
+ angles[0] = rand() % 360;
+ angles[1] = rand() % 360;
+ angles[2] = rand() % 360;
+ AnglesToAxis( angles, beam.axis );
+ trap_R_AddRefEntityToScene( &beam );
+ }
+}
+/*
+
+static void CG_LightningBolt( centity_t *cent, vec3_t origin ) {
+ trace_t trace;
+ refEntity_t beam;
+ vec3_t forward;
+ vec3_t muzzlePoint, endPoint;
+
+ if ( cent->currentState.weapon != WP_LIGHTNING ) {
+ return;
+ }
+
+ memset( &beam, 0, sizeof( beam ) );
+
+ // find muzzle point for this frame
+ VectorCopy( cent->lerpOrigin, muzzlePoint );
+ AngleVectors( cent->lerpAngles, forward, NULL, NULL );
+
+ // FIXME: crouch
+ muzzlePoint[2] += DEFAULT_VIEWHEIGHT;
+
+ VectorMA( muzzlePoint, 14, forward, muzzlePoint );
+
+ // project forward by the lightning range
+ VectorMA( muzzlePoint, LIGHTNING_RANGE, forward, endPoint );
+
+ // see if it hit a wall
+ CG_Trace( &trace, muzzlePoint, vec3_origin, vec3_origin, endPoint,
+ cent->currentState.number, MASK_SHOT );
+
+ // this is the endpoint
+ VectorCopy( trace.endpos, beam.oldorigin );
+
+ // use the provided origin, even though it may be slightly
+ // different than the muzzle origin
+ VectorCopy( origin, beam.origin );
+
+ beam.reType = RT_LIGHTNING;
+ beam.customShader = cgs.media.lightningShader;
+ trap_R_AddRefEntityToScene( &beam );
+
+ // add the impact flare if it hit something
+ if ( trace.fraction < 1.0 ) {
+ vec3_t angles;
+ vec3_t dir;
+
+ VectorSubtract( beam.oldorigin, beam.origin, dir );
+ VectorNormalize( dir );
+
+ memset( &beam, 0, sizeof( beam ) );
+ beam.hModel = cgs.media.lightningExplosionModel;
+
+ VectorMA( trace.endpos, -16, dir, beam.origin );
+
+ // make a random orientation
+ angles[0] = rand() % 360;
+ angles[1] = rand() % 360;
+ angles[2] = rand() % 360;
+ AnglesToAxis( angles, beam.axis );
+ trap_R_AddRefEntityToScene( &beam );
+ }
+}
+*/
+
+/*
+===============
+CG_SpawnRailTrail
+
+Origin will be the exact tag point, which is slightly
+different than the muzzle point used for determining hits.
+===============
+*/
+static void CG_SpawnRailTrail( centity_t *cent, vec3_t origin ) {
+ clientInfo_t *ci;
+
+ if ( cent->currentState.weapon != WP_RAILGUN ) {
+ return;
+ }
+ if ( !cent->pe.railgunFlash ) {
+ return;
+ }
+ cent->pe.railgunFlash = qtrue;
+ ci = &cgs.clientinfo[ cent->currentState.clientNum ];
+ CG_RailTrail( ci, origin, cent->pe.railgunImpact );
+}
+
+
+/*
+======================
+CG_MachinegunSpinAngle
+======================
+*/
+#define SPIN_SPEED 0.9
+#define COAST_TIME 1000
+static float CG_MachinegunSpinAngle( centity_t *cent ) {
+ int delta;
+ float angle;
+ float speed;
+
+ delta = cg.time - cent->pe.barrelTime;
+ if ( cent->pe.barrelSpinning ) {
+ angle = cent->pe.barrelAngle + delta * SPIN_SPEED;
+ } else {
+ if ( delta > COAST_TIME ) {
+ delta = COAST_TIME;
+ }
+
+ speed = 0.5 * ( SPIN_SPEED + (float)( COAST_TIME - delta ) / COAST_TIME );
+ angle = cent->pe.barrelAngle + delta * speed;
+ }
+
+ if ( cent->pe.barrelSpinning == !(cent->currentState.eFlags & EF_FIRING) ) {
+ cent->pe.barrelTime = cg.time;
+ cent->pe.barrelAngle = AngleMod( angle );
+ cent->pe.barrelSpinning = !!(cent->currentState.eFlags & EF_FIRING);
+#ifdef MISSIONPACK
+ if ( cent->currentState.weapon == WP_CHAINGUN && !cent->pe.barrelSpinning ) {
+ trap_S_StartSound( NULL, cent->currentState.number, CHAN_WEAPON, trap_S_RegisterSound( "sound/weapons/vulcan/wvulwind.wav", qfalse ) );
+ }
+#endif
+ }
+
+ return angle;
+}
+
+
+/*
+========================
+CG_AddWeaponWithPowerups
+========================
+*/
+static void CG_AddWeaponWithPowerups( refEntity_t *gun, int powerups ) {
+ // add powerup effects
+ if ( powerups & ( 1 << PW_INVIS ) ) {
+ gun->customShader = cgs.media.invisShader;
+ trap_R_AddRefEntityToScene( gun );
+ } else {
+ trap_R_AddRefEntityToScene( gun );
+
+ if ( powerups & ( 1 << PW_BATTLESUIT ) ) {
+ gun->customShader = cgs.media.battleWeaponShader;
+ trap_R_AddRefEntityToScene( gun );
+ }
+ if ( powerups & ( 1 << PW_QUAD ) ) {
+ gun->customShader = cgs.media.quadWeaponShader;
+ trap_R_AddRefEntityToScene( gun );
+ }
+ }
+}
+
+
+/*
+=============
+CG_AddPlayerWeapon
+
+Used for both the view weapon (ps is valid) and the world modelother character models (ps is NULL)
+The main player will have this called for BOTH cases, so effects like light and
+sound should only be done on the world model case.
+=============
+*/
+void CG_AddPlayerWeapon( refEntity_t *parent, playerState_t *ps, centity_t *cent, int team ) {
+ refEntity_t gun;
+ refEntity_t barrel;
+ refEntity_t flash;
+ vec3_t angles;
+ weapon_t weaponNum;
+ weaponInfo_t *weapon;
+ centity_t *nonPredictedCent;
+// int col;
+
+ weaponNum = cent->currentState.weapon;
+
+ CG_RegisterWeapon( weaponNum );
+ weapon = &cg_weapons[weaponNum];
+
+ // add the weapon
+ memset( &gun, 0, sizeof( gun ) );
+ VectorCopy( parent->lightingOrigin, gun.lightingOrigin );
+ gun.shadowPlane = parent->shadowPlane;
+ gun.renderfx = parent->renderfx;
+
+ // set custom shading for railgun refire rate
+ if ( ps ) {
+ if ( cg.predictedPlayerState.weapon == WP_RAILGUN
+ && cg.predictedPlayerState.weaponstate == WEAPON_FIRING ) {
+ float f;
+
+ f = (float)cg.predictedPlayerState.weaponTime / 1500;
+ gun.shaderRGBA[1] = 0;
+ gun.shaderRGBA[0] =
+ gun.shaderRGBA[2] = 255 * ( 1.0 - f );
+ } else {
+ gun.shaderRGBA[0] = 255;
+ gun.shaderRGBA[1] = 255;
+ gun.shaderRGBA[2] = 255;
+ gun.shaderRGBA[3] = 255;
+ }
+ }
+
+ gun.hModel = weapon->weaponModel;
+ if (!gun.hModel) {
+ return;
+ }
+
+ if ( !ps ) {
+ // add weapon ready sound
+ cent->pe.lightningFiring = qfalse;
+ if ( ( cent->currentState.eFlags & EF_FIRING ) && weapon->firingSound ) {
+ // lightning gun and guantlet make a different sound when fire is held down
+ trap_S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->firingSound );
+ cent->pe.lightningFiring = qtrue;
+ } else if ( weapon->readySound ) {
+ trap_S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->readySound );
+ }
+ }
+
+ CG_PositionEntityOnTag( &gun, parent, parent->hModel, "tag_weapon");
+
+ CG_AddWeaponWithPowerups( &gun, cent->currentState.powerups );
+
+ // add the spinning barrel
+ if ( weapon->barrelModel ) {
+ memset( &barrel, 0, sizeof( barrel ) );
+ VectorCopy( parent->lightingOrigin, barrel.lightingOrigin );
+ barrel.shadowPlane = parent->shadowPlane;
+ barrel.renderfx = parent->renderfx;
+
+ barrel.hModel = weapon->barrelModel;
+ angles[YAW] = 0;
+ angles[PITCH] = 0;
+ angles[ROLL] = CG_MachinegunSpinAngle( cent );
+ AnglesToAxis( angles, barrel.axis );
+
+ CG_PositionRotatedEntityOnTag( &barrel, &gun, weapon->weaponModel, "tag_barrel" );
+
+ CG_AddWeaponWithPowerups( &barrel, cent->currentState.powerups );
+ }
+
+ // make sure we aren't looking at cg.predictedPlayerEntity for LG
+ nonPredictedCent = &cg_entities[cent->currentState.clientNum];
+
+ // if the index of the nonPredictedCent is not the same as the clientNum
+ // then this is a fake player (like on teh single player podiums), so
+ // go ahead and use the cent
+ if( ( nonPredictedCent - cg_entities ) != cent->currentState.clientNum ) {
+ nonPredictedCent = cent;
+ }
+
+ // add the flash
+ if ( ( weaponNum == WP_LIGHTNING || weaponNum == WP_GAUNTLET || weaponNum == WP_GRAPPLING_HOOK )
+ && ( nonPredictedCent->currentState.eFlags & EF_FIRING ) )
+ {
+ // continuous flash
+ } else {
+ // impulse flash
+ if ( cg.time - cent->muzzleFlashTime > MUZZLE_FLASH_TIME && !cent->pe.railgunFlash ) {
+ return;
+ }
+ }
+
+ memset( &flash, 0, sizeof( flash ) );
+ VectorCopy( parent->lightingOrigin, flash.lightingOrigin );
+ flash.shadowPlane = parent->shadowPlane;
+ flash.renderfx = parent->renderfx;
+
+ flash.hModel = weapon->flashModel;
+ if (!flash.hModel) {
+ return;
+ }
+ angles[YAW] = 0;
+ angles[PITCH] = 0;
+ angles[ROLL] = crandom() * 10;
+ AnglesToAxis( angles, flash.axis );
+
+ // colorize the railgun blast
+ if ( weaponNum == WP_RAILGUN ) {
+ clientInfo_t *ci;
+
+ ci = &cgs.clientinfo[ cent->currentState.clientNum ];
+ flash.shaderRGBA[0] = 255 * ci->color1[0];
+ flash.shaderRGBA[1] = 255 * ci->color1[1];
+ flash.shaderRGBA[2] = 255 * ci->color1[2];
+ }
+
+ CG_PositionRotatedEntityOnTag( &flash, &gun, weapon->weaponModel, "tag_flash");
+ trap_R_AddRefEntityToScene( &flash );
+
+ if ( ps || cg.renderingThirdPerson ||
+ cent->currentState.number != cg.predictedPlayerState.clientNum ) {
+ // add lightning bolt
+ CG_LightningBolt( nonPredictedCent, flash.origin );
+
+ // add rail trail
+ CG_SpawnRailTrail( cent, flash.origin );
+
+ if ( weapon->flashDlightColor[0] || weapon->flashDlightColor[1] || weapon->flashDlightColor[2] ) {
+ trap_R_AddLightToScene( flash.origin, 300 + (rand()&31), weapon->flashDlightColor[0],
+ weapon->flashDlightColor[1], weapon->flashDlightColor[2] );
+ }
+ }
+}
+
+/*
+==============
+CG_AddViewWeapon
+
+Add the weapon, and flash for the player's view
+==============
+*/
+void CG_AddViewWeapon( playerState_t *ps ) {
+ refEntity_t hand;
+ centity_t *cent;
+ clientInfo_t *ci;
+ float fovOffset;
+ vec3_t angles;
+ weaponInfo_t *weapon;
+
+ if ( ps->persistant[PERS_TEAM] == TEAM_SPECTATOR ) {
+ return;
+ }
+
+ if ( ps->pm_type == PM_INTERMISSION ) {
+ return;
+ }
+
+ // no gun if in third person view or a camera is active
+ //if ( cg.renderingThirdPerson || cg.cameraMode) {
+ if ( cg.renderingThirdPerson ) {
+ return;
+ }
+
+
+ // allow the gun to be completely removed
+ if ( !cg_drawGun.integer ) {
+ vec3_t origin;
+
+ if ( cg.predictedPlayerState.eFlags & EF_FIRING ) {
+ // special hack for lightning gun...
+ VectorCopy( cg.refdef.vieworg, origin );
+ VectorMA( origin, -8, cg.refdef.viewaxis[2], origin );
+ CG_LightningBolt( &cg_entities[ps->clientNum], origin );
+ }
+ return;
+ }
+
+ // don't draw if testing a gun model
+ if ( cg.testGun ) {
+ return;
+ }
+
+ // drop gun lower at higher fov
+ if ( cg_fov.integer > 90 ) {
+ fovOffset = -0.2 * ( cg_fov.integer - 90 );
+ } else {
+ fovOffset = 0;
+ }
+
+ cent = &cg.predictedPlayerEntity; // &cg_entities[cg.snap->ps.clientNum];
+ CG_RegisterWeapon( ps->weapon );
+ weapon = &cg_weapons[ ps->weapon ];
+
+ memset (&hand, 0, sizeof(hand));
+
+ // set up gun position
+ CG_CalculateWeaponPosition( hand.origin, angles );
+
+ VectorMA( hand.origin, cg_gun_x.value, cg.refdef.viewaxis[0], hand.origin );
+ VectorMA( hand.origin, cg_gun_y.value, cg.refdef.viewaxis[1], hand.origin );
+ VectorMA( hand.origin, (cg_gun_z.value+fovOffset), cg.refdef.viewaxis[2], hand.origin );
+
+ AnglesToAxis( angles, hand.axis );
+
+ // map torso animations to weapon animations
+ if ( cg_gun_frame.integer ) {
+ // development tool
+ hand.frame = hand.oldframe = cg_gun_frame.integer;
+ hand.backlerp = 0;
+ } else {
+ // get clientinfo for animation map
+ ci = &cgs.clientinfo[ cent->currentState.clientNum ];
+ hand.frame = CG_MapTorsoToWeaponFrame( ci, cent->pe.torso.frame );
+ hand.oldframe = CG_MapTorsoToWeaponFrame( ci, cent->pe.torso.oldFrame );
+ hand.backlerp = cent->pe.torso.backlerp;
+ }
+
+ hand.hModel = weapon->handsModel;
+ hand.renderfx = RF_DEPTHHACK | RF_FIRST_PERSON | RF_MINLIGHT;
+
+ // add everything onto the hand
+ CG_AddPlayerWeapon( &hand, ps, &cg.predictedPlayerEntity, ps->persistant[PERS_TEAM] );
+}
+
+/*
+==============================================================================
+
+WEAPON SELECTION
+
+==============================================================================
+*/
+
+/*
+===================
+CG_DrawWeaponSelect
+===================
+*/
+void CG_DrawWeaponSelect( void ) {
+ int i;
+ int bits;
+ int count;
+ int x, y, w;
+ char *name;
+ float *color;
+
+ // don't display if dead
+ if ( cg.predictedPlayerState.stats[STAT_HEALTH] <= 0 ) {
+ return;
+ }
+
+ color = CG_FadeColor( cg.weaponSelectTime, WEAPON_SELECT_TIME );
+ if ( !color ) {
+ return;
+ }
+ trap_R_SetColor( color );
+
+ // showing weapon select clears pickup item display, but not the blend blob
+ cg.itemPickupTime = 0;
+
+ // count the number of weapons owned
+ bits = cg.snap->ps.stats[ STAT_WEAPONS ];
+ count = 0;
+ for ( i = 1 ; i < 16 ; i++ ) {
+ if ( bits & ( 1 << i ) ) {
+ count++;
+ }
+ }
+
+ x = 320 - count * 20;
+ y = 380;
+
+ for ( i = 1 ; i < 16 ; i++ ) {
+ if ( !( bits & ( 1 << i ) ) ) {
+ continue;
+ }
+
+ CG_RegisterWeapon( i );
+
+ // draw weapon icon
+ CG_DrawPic( x, y, 32, 32, cg_weapons[i].weaponIcon );
+
+ // draw selection marker
+ if ( i == cg.weaponSelect ) {
+ CG_DrawPic( x-4, y-4, 40, 40, cgs.media.selectShader );
+ }
+
+ // no ammo cross on top
+ if ( !cg.snap->ps.ammo[ i ] ) {
+ CG_DrawPic( x, y, 32, 32, cgs.media.noammoShader );
+ }
+
+ x += 40;
+ }
+
+ // draw the selected name
+ if ( cg_weapons[ cg.weaponSelect ].item ) {
+ name = cg_weapons[ cg.weaponSelect ].item->pickup_name;
+ if ( name ) {
+ w = CG_DrawStrlen( name ) * BIGCHAR_WIDTH;
+ x = ( SCREEN_WIDTH - w ) / 2;
+ CG_DrawBigStringColor(x, y - 22, name, color);
+ }
+ }
+
+ trap_R_SetColor( NULL );
+}
+
+
+/*
+===============
+CG_WeaponSelectable
+===============
+*/
+static qboolean CG_WeaponSelectable( int i ) {
+ if ( !cg.snap->ps.ammo[i] ) {
+ return qfalse;
+ }
+ if ( ! (cg.snap->ps.stats[ STAT_WEAPONS ] & ( 1 << i ) ) ) {
+ return qfalse;
+ }
+
+ return qtrue;
+}
+
+/*
+===============
+CG_NextWeapon_f
+===============
+*/
+void CG_NextWeapon_f( void ) {
+ int i;
+ int original;
+
+ if ( !cg.snap ) {
+ return;
+ }
+ if ( cg.snap->ps.pm_flags & PMF_FOLLOW ) {
+ return;
+ }
+
+ cg.weaponSelectTime = cg.time;
+ original = cg.weaponSelect;
+
+ for ( i = 0 ; i < 16 ; i++ ) {
+ cg.weaponSelect++;
+ if ( cg.weaponSelect == 16 ) {
+ cg.weaponSelect = 0;
+ }
+ if ( cg.weaponSelect == WP_GAUNTLET ) {
+ continue; // never cycle to gauntlet
+ }
+ if ( CG_WeaponSelectable( cg.weaponSelect ) ) {
+ break;
+ }
+ }
+ if ( i == 16 ) {
+ cg.weaponSelect = original;
+ }
+}
+
+/*
+===============
+CG_PrevWeapon_f
+===============
+*/
+void CG_PrevWeapon_f( void ) {
+ int i;
+ int original;
+
+ if ( !cg.snap ) {
+ return;
+ }
+ if ( cg.snap->ps.pm_flags & PMF_FOLLOW ) {
+ return;
+ }
+
+ cg.weaponSelectTime = cg.time;
+ original = cg.weaponSelect;
+
+ for ( i = 0 ; i < 16 ; i++ ) {
+ cg.weaponSelect--;
+ if ( cg.weaponSelect == -1 ) {
+ cg.weaponSelect = 15;
+ }
+ if ( cg.weaponSelect == WP_GAUNTLET ) {
+ continue; // never cycle to gauntlet
+ }
+ if ( CG_WeaponSelectable( cg.weaponSelect ) ) {
+ break;
+ }
+ }
+ if ( i == 16 ) {
+ cg.weaponSelect = original;
+ }
+}
+
+/*
+===============
+CG_Weapon_f
+===============
+*/
+void CG_Weapon_f( void ) {
+ int num;
+
+ if ( !cg.snap ) {
+ return;
+ }
+ if ( cg.snap->ps.pm_flags & PMF_FOLLOW ) {
+ return;
+ }
+
+ num = atoi( CG_Argv( 1 ) );
+
+ if ( num < 1 || num > 15 ) {
+ return;
+ }
+
+ cg.weaponSelectTime = cg.time;
+
+ if ( ! ( cg.snap->ps.stats[STAT_WEAPONS] & ( 1 << num ) ) ) {
+ return; // don't have the weapon
+ }
+
+ cg.weaponSelect = num;
+}
+
+/*
+===================
+CG_OutOfAmmoChange
+
+The current weapon has just run out of ammo
+===================
+*/
+void CG_OutOfAmmoChange( void ) {
+ int i;
+
+ cg.weaponSelectTime = cg.time;
+
+ for ( i = 15 ; i > 0 ; i-- ) {
+ if ( CG_WeaponSelectable( i ) ) {
+ cg.weaponSelect = i;
+ break;
+ }
+ }
+}
+
+
+
+/*
+===================================================================================================
+
+WEAPON EVENTS
+
+===================================================================================================
+*/
+
+/*
+================
+CG_FireWeapon
+
+Caused by an EV_FIRE_WEAPON event
+================
+*/
+void CG_FireWeapon( centity_t *cent ) {
+ entityState_t *ent;
+ int c;
+ weaponInfo_t *weap;
+
+ ent = &cent->currentState;
+ if ( ent->weapon == WP_NONE ) {
+ return;
+ }
+ if ( ent->weapon >= WP_NUM_WEAPONS ) {
+ CG_Error( "CG_FireWeapon: ent->weapon >= WP_NUM_WEAPONS" );
+ return;
+ }
+ weap = &cg_weapons[ ent->weapon ];
+
+ // mark the entity as muzzle flashing, so when it is added it will
+ // append the flash to the weapon model
+ cent->muzzleFlashTime = cg.time;
+
+ // lightning gun only does this this on initial press
+ if ( ent->weapon == WP_LIGHTNING ) {
+ if ( cent->pe.lightningFiring ) {
+ return;
+ }
+ }
+
+ // play quad sound if needed
+ if ( cent->currentState.powerups & ( 1 << PW_QUAD ) ) {
+ trap_S_StartSound (NULL, cent->currentState.number, CHAN_ITEM, cgs.media.quadSound );
+ }
+
+ // play a sound
+ for ( c = 0 ; c < 4 ; c++ ) {
+ if ( !weap->flashSound[c] ) {
+ break;
+ }
+ }
+ if ( c > 0 ) {
+ c = rand() % c;
+ if ( weap->flashSound[c] )
+ {
+ trap_S_StartSound( NULL, ent->number, CHAN_WEAPON, weap->flashSound[c] );
+ }
+ }
+
+ // do brass ejection
+ if ( weap->ejectBrassFunc && cg_brassTime.integer > 0 ) {
+ weap->ejectBrassFunc( cent );
+ }
+}
+
+
+/*
+=================
+CG_MissileHitWall
+
+Caused by an EV_MISSILE_MISS event, or directly by local bullet tracing
+=================
+*/
+void CG_MissileHitWall( int weapon, int clientNum, vec3_t origin, vec3_t dir, impactSound_t soundType ) {
+ qhandle_t mod;
+ qhandle_t mark;
+ qhandle_t shader;
+ sfxHandle_t sfx;
+ float radius;
+ float light;
+ vec3_t lightColor;
+ localEntity_t *le;
+ int r;
+ qboolean alphaFade;
+ qboolean isSprite;
+ int duration;
+ vec3_t sprOrg;
+ vec3_t sprVel;
+
+ mark = 0;
+ radius = 32;
+ sfx = 0;
+ mod = 0;
+ shader = 0;
+ light = 0;
+ lightColor[0] = 1;
+ lightColor[1] = 1;
+ lightColor[2] = 0;
+
+ // set defaults
+ isSprite = qfalse;
+ duration = 600;
+
+ switch ( weapon ) {
+ default:
+#ifdef MISSIONPACK
+ case WP_NAILGUN:
+ if( soundType == IMPACTSOUND_FLESH ) {
+ sfx = cgs.media.sfx_nghitflesh;
+ } else if( soundType == IMPACTSOUND_METAL ) {
+ sfx = cgs.media.sfx_nghitmetal;
+ } else {
+ sfx = cgs.media.sfx_nghit;
+ }
+ mark = cgs.media.holeMarkShader;
+ radius = 12;
+ break;
+#endif
+ case WP_LIGHTNING:
+ // no explosion at LG impact, it is added with the beam
+ r = rand() & 3;
+ if ( r < 2 ) {
+ sfx = cgs.media.sfx_lghit2;
+ } else if ( r == 2 ) {
+ sfx = cgs.media.sfx_lghit1;
+ } else {
+ sfx = cgs.media.sfx_lghit3;
+ }
+ mark = cgs.media.holeMarkShader;
+ radius = 12;
+ break;
+#ifdef MISSIONPACK
+ case WP_PROX_LAUNCHER:
+ mod = cgs.media.dishFlashModel;
+ shader = cgs.media.grenadeExplosionShader;
+ sfx = cgs.media.sfx_proxexp;
+ mark = cgs.media.burnMarkShader;
+ radius = 64;
+ light = 300;
+ isSprite = qtrue;
+ break;
+#endif
+ case WP_GRENADE_LAUNCHER:
+ mod = cgs.media.dishFlashModel;
+ shader = cgs.media.grenadeExplosionShader;
+ sfx = cgs.media.sfx_rockexp;
+ mark = cgs.media.burnMarkShader;
+ radius = 64;
+ light = 300;
+ isSprite = qtrue;
+ break;
+ case WP_ROCKET_LAUNCHER:
+ mod = cgs.media.dishFlashModel;
+ shader = cgs.media.rocketExplosionShader;
+ sfx = cgs.media.sfx_rockexp;
+ mark = cgs.media.burnMarkShader;
+ radius = 64;
+ light = 300;
+ isSprite = qtrue;
+ duration = 1000;
+ lightColor[0] = 1;
+ lightColor[1] = 0.75;
+ lightColor[2] = 0.0;
+ if (cg_oldRocket.integer == 0) {
+ // explosion sprite animation
+ VectorMA( origin, 24, dir, sprOrg );
+ VectorScale( dir, 64, sprVel );
+
+ CG_ParticleExplosion( "explode1", sprOrg, sprVel, 1400, 20, 30 );
+ }
+ break;
+ case WP_RAILGUN:
+ mod = cgs.media.ringFlashModel;
+ shader = cgs.media.railExplosionShader;
+ sfx = cgs.media.sfx_plasmaexp;
+ mark = cgs.media.energyMarkShader;
+ radius = 24;
+ break;
+ case WP_PLASMAGUN:
+ mod = cgs.media.ringFlashModel;
+ shader = cgs.media.plasmaExplosionShader;
+ sfx = cgs.media.sfx_plasmaexp;
+ mark = cgs.media.energyMarkShader;
+ radius = 16;
+ break;
+ case WP_BFG:
+ mod = cgs.media.dishFlashModel;
+ shader = cgs.media.bfgExplosionShader;
+ sfx = cgs.media.sfx_rockexp;
+ mark = cgs.media.burnMarkShader;
+ radius = 32;
+ isSprite = qtrue;
+ break;
+ case WP_SHOTGUN:
+ mod = cgs.media.bulletFlashModel;
+ shader = cgs.media.bulletExplosionShader;
+ mark = cgs.media.bulletMarkShader;
+ sfx = 0;
+ radius = 4;
+ break;
+
+#ifdef MISSIONPACK
+ case WP_CHAINGUN:
+ mod = cgs.media.bulletFlashModel;
+ if( soundType == IMPACTSOUND_FLESH ) {
+ sfx = cgs.media.sfx_chghitflesh;
+ } else if( soundType == IMPACTSOUND_METAL ) {
+ sfx = cgs.media.sfx_chghitmetal;
+ } else {
+ sfx = cgs.media.sfx_chghit;
+ }
+ mark = cgs.media.bulletMarkShader;
+
+ r = rand() & 3;
+ if ( r < 2 ) {
+ sfx = cgs.media.sfx_ric1;
+ } else if ( r == 2 ) {
+ sfx = cgs.media.sfx_ric2;
+ } else {
+ sfx = cgs.media.sfx_ric3;
+ }
+
+ radius = 8;
+ break;
+#endif
+
+ case WP_MACHINEGUN:
+ mod = cgs.media.bulletFlashModel;
+ shader = cgs.media.bulletExplosionShader;
+ mark = cgs.media.bulletMarkShader;
+
+ r = rand() & 3;
+ if ( r == 0 ) {
+ sfx = cgs.media.sfx_ric1;
+ } else if ( r == 1 ) {
+ sfx = cgs.media.sfx_ric2;
+ } else {
+ sfx = cgs.media.sfx_ric3;
+ }
+
+ radius = 8;
+ break;
+ }
+
+ if ( sfx ) {
+ trap_S_StartSound( origin, ENTITYNUM_WORLD, CHAN_AUTO, sfx );
+ }
+
+ //
+ // create the explosion
+ //
+ if ( mod ) {
+ le = CG_MakeExplosion( origin, dir,
+ mod, shader,
+ duration, isSprite );
+ le->light = light;
+ VectorCopy( lightColor, le->lightColor );
+ if ( weapon == WP_RAILGUN ) {
+ // colorize with client color
+ VectorCopy( cgs.clientinfo[clientNum].color1, le->color );
+ }
+ }
+
+ //
+ // impact mark
+ //
+ alphaFade = (mark == cgs.media.energyMarkShader); // plasma fades alpha, all others fade color
+ if ( weapon == WP_RAILGUN ) {
+ float *color;
+
+ // colorize with client color
+ color = cgs.clientinfo[clientNum].color2;
+ CG_ImpactMark( mark, origin, dir, random()*360, color[0],color[1], color[2],1, alphaFade, radius, qfalse );
+ } else {
+ CG_ImpactMark( mark, origin, dir, random()*360, 1,1,1,1, alphaFade, radius, qfalse );
+ }
+}
+
+
+/*
+=================
+CG_MissileHitPlayer
+=================
+*/
+void CG_MissileHitPlayer( int weapon, vec3_t origin, vec3_t dir, int entityNum ) {
+ CG_Bleed( origin, entityNum );
+
+ // some weapons will make an explosion with the blood, while
+ // others will just make the blood
+ switch ( weapon ) {
+ case WP_GRENADE_LAUNCHER:
+ case WP_ROCKET_LAUNCHER:
+#ifdef MISSIONPACK
+ case WP_NAILGUN:
+ case WP_CHAINGUN:
+ case WP_PROX_LAUNCHER:
+#endif
+ CG_MissileHitWall( weapon, 0, origin, dir, IMPACTSOUND_FLESH );
+ break;
+ default:
+ break;
+ }
+}
+
+
+
+/*
+============================================================================
+
+SHOTGUN TRACING
+
+============================================================================
+*/
+
+/*
+================
+CG_ShotgunPellet
+================
+*/
+static void CG_ShotgunPellet( vec3_t start, vec3_t end, int skipNum ) {
+ trace_t tr;
+ int sourceContentType, destContentType;
+
+ CG_Trace( &tr, start, NULL, NULL, end, skipNum, MASK_SHOT );
+
+ sourceContentType = trap_CM_PointContents( start, 0 );
+ destContentType = trap_CM_PointContents( tr.endpos, 0 );
+
+ // FIXME: should probably move this cruft into CG_BubbleTrail
+ if ( sourceContentType == destContentType ) {
+ if ( sourceContentType & CONTENTS_WATER ) {
+ CG_BubbleTrail( start, tr.endpos, 32 );
+ }
+ } else if ( sourceContentType & CONTENTS_WATER ) {
+ trace_t trace;
+
+ trap_CM_BoxTrace( &trace, end, start, NULL, NULL, 0, CONTENTS_WATER );
+ CG_BubbleTrail( start, trace.endpos, 32 );
+ } else if ( destContentType & CONTENTS_WATER ) {
+ trace_t trace;
+
+ trap_CM_BoxTrace( &trace, start, end, NULL, NULL, 0, CONTENTS_WATER );
+ CG_BubbleTrail( tr.endpos, trace.endpos, 32 );
+ }
+
+ if ( tr.surfaceFlags & SURF_NOIMPACT ) {
+ return;
+ }
+
+ if ( cg_entities[tr.entityNum].currentState.eType == ET_PLAYER ) {
+ CG_MissileHitPlayer( WP_SHOTGUN, tr.endpos, tr.plane.normal, tr.entityNum );
+ } else {
+ if ( tr.surfaceFlags & SURF_NOIMPACT ) {
+ // SURF_NOIMPACT will not make a flame puff or a mark
+ return;
+ }
+ if ( tr.surfaceFlags & SURF_METALSTEPS ) {
+ CG_MissileHitWall( WP_SHOTGUN, 0, tr.endpos, tr.plane.normal, IMPACTSOUND_METAL );
+ } else {
+ CG_MissileHitWall( WP_SHOTGUN, 0, tr.endpos, tr.plane.normal, IMPACTSOUND_DEFAULT );
+ }
+ }
+}
+
+/*
+================
+CG_ShotgunPattern
+
+Perform the same traces the server did to locate the
+hit splashes
+================
+*/
+static void CG_ShotgunPattern( vec3_t origin, vec3_t origin2, int seed, int otherEntNum ) {
+ int i;
+ float r, u;
+ vec3_t end;
+ vec3_t forward, right, up;
+
+ // derive the right and up vectors from the forward vector, because
+ // the client won't have any other information
+ VectorNormalize2( origin2, forward );
+ PerpendicularVector( right, forward );
+ CrossProduct( forward, right, up );
+
+ // generate the "random" spread pattern
+ for ( i = 0 ; i < DEFAULT_SHOTGUN_COUNT ; i++ ) {
+ r = Q_crandom( &seed ) * DEFAULT_SHOTGUN_SPREAD * 16;
+ u = Q_crandom( &seed ) * DEFAULT_SHOTGUN_SPREAD * 16;
+ VectorMA( origin, 8192 * 16, forward, end);
+ VectorMA (end, r, right, end);
+ VectorMA (end, u, up, end);
+
+ CG_ShotgunPellet( origin, end, otherEntNum );
+ }
+}
+
+/*
+==============
+CG_ShotgunFire
+==============
+*/
+void CG_ShotgunFire( entityState_t *es ) {
+ vec3_t v;
+ int contents;
+
+ VectorSubtract( es->origin2, es->pos.trBase, v );
+ VectorNormalize( v );
+ VectorScale( v, 32, v );
+ VectorAdd( es->pos.trBase, v, v );
+ if ( cgs.glconfig.hardwareType != GLHW_RAGEPRO ) {
+ // ragepro can't alpha fade, so don't even bother with smoke
+ vec3_t up;
+
+ contents = trap_CM_PointContents( es->pos.trBase, 0 );
+ if ( !( contents & CONTENTS_WATER ) ) {
+ VectorSet( up, 0, 0, 8 );
+ CG_SmokePuff( v, up, 32, 1, 1, 1, 0.33f, 900, cg.time, 0, LEF_PUFF_DONT_SCALE, cgs.media.shotgunSmokePuffShader );
+ }
+ }
+ CG_ShotgunPattern( es->pos.trBase, es->origin2, es->eventParm, es->otherEntityNum );
+}
+
+/*
+============================================================================
+
+BULLETS
+
+============================================================================
+*/
+
+
+/*
+===============
+CG_Tracer
+===============
+*/
+void CG_Tracer( vec3_t source, vec3_t dest ) {
+ vec3_t forward, right;
+ polyVert_t verts[4];
+ vec3_t line;
+ float len, begin, end;
+ vec3_t start, finish;
+ vec3_t midpoint;
+
+ // tracer
+ VectorSubtract( dest, source, forward );
+ len = VectorNormalize( forward );
+
+ // start at least a little ways from the muzzle
+ if ( len < 100 ) {
+ return;
+ }
+ begin = 50 + random() * (len - 60);
+ end = begin + cg_tracerLength.value;
+ if ( end > len ) {
+ end = len;
+ }
+ VectorMA( source, begin, forward, start );
+ VectorMA( source, end, forward, finish );
+
+ line[0] = DotProduct( forward, cg.refdef.viewaxis[1] );
+ line[1] = DotProduct( forward, cg.refdef.viewaxis[2] );
+
+ VectorScale( cg.refdef.viewaxis[1], line[1], right );
+ VectorMA( right, -line[0], cg.refdef.viewaxis[2], right );
+ VectorNormalize( right );
+
+ VectorMA( finish, cg_tracerWidth.value, right, verts[0].xyz );
+ verts[0].st[0] = 0;
+ verts[0].st[1] = 1;
+ verts[0].modulate[0] = 255;
+ verts[0].modulate[1] = 255;
+ verts[0].modulate[2] = 255;
+ verts[0].modulate[3] = 255;
+
+ VectorMA( finish, -cg_tracerWidth.value, right, verts[1].xyz );
+ verts[1].st[0] = 1;
+ verts[1].st[1] = 0;
+ verts[1].modulate[0] = 255;
+ verts[1].modulate[1] = 255;
+ verts[1].modulate[2] = 255;
+ verts[1].modulate[3] = 255;
+
+ VectorMA( start, -cg_tracerWidth.value, right, verts[2].xyz );
+ verts[2].st[0] = 1;
+ verts[2].st[1] = 1;
+ verts[2].modulate[0] = 255;
+ verts[2].modulate[1] = 255;
+ verts[2].modulate[2] = 255;
+ verts[2].modulate[3] = 255;
+
+ VectorMA( start, cg_tracerWidth.value, right, verts[3].xyz );
+ verts[3].st[0] = 0;
+ verts[3].st[1] = 0;
+ verts[3].modulate[0] = 255;
+ verts[3].modulate[1] = 255;
+ verts[3].modulate[2] = 255;
+ verts[3].modulate[3] = 255;
+
+ trap_R_AddPolyToScene( cgs.media.tracerShader, 4, verts );
+
+ midpoint[0] = ( start[0] + finish[0] ) * 0.5;
+ midpoint[1] = ( start[1] + finish[1] ) * 0.5;
+ midpoint[2] = ( start[2] + finish[2] ) * 0.5;
+
+ // add the tracer sound
+ trap_S_StartSound( midpoint, ENTITYNUM_WORLD, CHAN_AUTO, cgs.media.tracerSound );
+
+}
+
+
+/*
+======================
+CG_CalcMuzzlePoint
+======================
+*/
+static qboolean CG_CalcMuzzlePoint( int entityNum, vec3_t muzzle ) {
+ vec3_t forward;
+ centity_t *cent;
+ int anim;
+
+ if ( entityNum == cg.snap->ps.clientNum ) {
+ VectorCopy( cg.snap->ps.origin, muzzle );
+ muzzle[2] += cg.snap->ps.viewheight;
+ AngleVectors( cg.snap->ps.viewangles, forward, NULL, NULL );
+ VectorMA( muzzle, 14, forward, muzzle );
+ return qtrue;
+ }
+
+ cent = &cg_entities[entityNum];
+ if ( !cent->currentValid ) {
+ return qfalse;
+ }
+
+ VectorCopy( cent->currentState.pos.trBase, muzzle );
+
+ AngleVectors( cent->currentState.apos.trBase, forward, NULL, NULL );
+ anim = cent->currentState.legsAnim & ~ANIM_TOGGLEBIT;
+ if ( anim == LEGS_WALKCR || anim == LEGS_IDLECR ) {
+ muzzle[2] += CROUCH_VIEWHEIGHT;
+ } else {
+ muzzle[2] += DEFAULT_VIEWHEIGHT;
+ }
+
+ VectorMA( muzzle, 14, forward, muzzle );
+
+ return qtrue;
+
+}
+
+/*
+======================
+CG_Bullet
+
+Renders bullet effects.
+======================
+*/
+void CG_Bullet( vec3_t end, int sourceEntityNum, vec3_t normal, qboolean flesh, int fleshEntityNum ) {
+ trace_t trace;
+ int sourceContentType, destContentType;
+ vec3_t start;
+
+ // if the shooter is currently valid, calc a source point and possibly
+ // do trail effects
+ if ( sourceEntityNum >= 0 && cg_tracerChance.value > 0 ) {
+ if ( CG_CalcMuzzlePoint( sourceEntityNum, start ) ) {
+ sourceContentType = trap_CM_PointContents( start, 0 );
+ destContentType = trap_CM_PointContents( end, 0 );
+
+ // do a complete bubble trail if necessary
+ if ( ( sourceContentType == destContentType ) && ( sourceContentType & CONTENTS_WATER ) ) {
+ CG_BubbleTrail( start, end, 32 );
+ }
+ // bubble trail from water into air
+ else if ( ( sourceContentType & CONTENTS_WATER ) ) {
+ trap_CM_BoxTrace( &trace, end, start, NULL, NULL, 0, CONTENTS_WATER );
+ CG_BubbleTrail( start, trace.endpos, 32 );
+ }
+ // bubble trail from air into water
+ else if ( ( destContentType & CONTENTS_WATER ) ) {
+ trap_CM_BoxTrace( &trace, start, end, NULL, NULL, 0, CONTENTS_WATER );
+ CG_BubbleTrail( trace.endpos, end, 32 );
+ }
+
+ // draw a tracer
+ if ( random() < cg_tracerChance.value ) {
+ CG_Tracer( start, end );
+ }
+ }
+ }
+
+ // impact splash and mark
+ if ( flesh ) {
+ CG_Bleed( end, fleshEntityNum );
+ } else {
+ CG_MissileHitWall( WP_MACHINEGUN, 0, end, normal, IMPACTSOUND_DEFAULT );
+ }
+
+}
diff --git a/code/cgame/cgame.bat b/code/cgame/cgame.bat
new file mode 100755
index 0000000..6e13523
--- /dev/null
+++ b/code/cgame/cgame.bat
@@ -0,0 +1,63 @@
+rem make sure we have a safe environement
+set LIBRARY=
+set INCLUDE=
+
+mkdir vm
+cd vm
+set cc=lcc -DQ3_VM -DCGAME -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\ui %1
+
+%cc% ../../game/bg_misc.c
+@if errorlevel 1 goto quit
+%cc% ../../game/bg_pmove.c
+@if errorlevel 1 goto quit
+%cc% ../../game/bg_slidemove.c
+@if errorlevel 1 goto quit
+%cc% ../../game/bg_lib.c
+@if errorlevel 1 goto quit
+%cc% ../../game/q_math.c
+@if errorlevel 1 goto quit
+%cc% ../../game/q_shared.c
+@if errorlevel 1 goto quit
+%cc% ../cg_consolecmds.c
+@if errorlevel 1 goto quit
+%cc% ../cg_draw.c
+@if errorlevel 1 goto quit
+%cc% ../cg_drawtools.c
+@if errorlevel 1 goto quit
+%cc% ../cg_effects.c
+@if errorlevel 1 goto quit
+%cc% ../cg_ents.c
+@if errorlevel 1 goto quit
+%cc% ../cg_event.c
+@if errorlevel 1 goto quit
+%cc% ../cg_info.c
+@if errorlevel 1 goto quit
+%cc% ../cg_localents.c
+@if errorlevel 1 goto quit
+%cc% ../cg_main.c
+@if errorlevel 1 goto quit
+%cc% ../cg_marks.c
+@if errorlevel 1 goto quit
+%cc% ../cg_players.c
+@if errorlevel 1 goto quit
+%cc% ../cg_playerstate.c
+@if errorlevel 1 goto quit
+%cc% ../cg_predict.c
+@if errorlevel 1 goto quit
+%cc% ../cg_scoreboard.c
+@if errorlevel 1 goto quit
+%cc% ../cg_servercmds.c
+@if errorlevel 1 goto quit
+%cc% ../cg_snapshot.c
+@if errorlevel 1 goto quit
+%cc% ../cg_view.c
+@if errorlevel 1 goto quit
+%cc% ../cg_weapons.c
+@if errorlevel 1 goto quit
+
+
+
+
+q3asm -f ../cgame
+:quit
+cd ..
diff --git a/code/cgame/cgame.def b/code/cgame/cgame.def
new file mode 100755
index 0000000..01861ba
--- /dev/null
+++ b/code/cgame/cgame.def
@@ -0,0 +1,3 @@
+EXPORTS
+ vmMain
+ dllEntry
diff --git a/code/cgame/cgame.plg b/code/cgame/cgame.plg
new file mode 100755
index 0000000..b7c80ee
--- /dev/null
+++ b/code/cgame/cgame.plg
@@ -0,0 +1,124 @@
+<html>
+<body>
+<pre>
+<h1>Build Log</h1>
+<h3>
+--------------------Configuration: cgame - Win32 Release--------------------
+</h3>
+<h3>Command Lines</h3>
+Creating temporary file "C:\WINNT\Profiles\ADMINI~1\LOCALS~1\Temp\RSP4BE.tmp" with contents
+[
+/nologo /G6 /ML /W4 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /Fp"Release/cgame.pch" /YX /Fo"Release/" /Fd"Release/" /FD /c
+"D:\quake3\MissionPack\code\game\bg_misc.c"
+"D:\quake3\MissionPack\code\game\bg_pmove.c"
+"D:\quake3\MissionPack\code\game\bg_slidemove.c"
+"D:\quake3\MissionPack\code\cgame\cg_consolecmds.c"
+"D:\quake3\MissionPack\code\cgame\cg_draw.c"
+"D:\quake3\MissionPack\code\cgame\cg_drawtools.c"
+"D:\quake3\MissionPack\code\cgame\cg_effects.c"
+"D:\quake3\MissionPack\code\cgame\cg_ents.c"
+"D:\quake3\MissionPack\code\cgame\cg_event.c"
+"D:\quake3\MissionPack\code\cgame\cg_info.c"
+"D:\quake3\MissionPack\code\cgame\cg_localents.c"
+"D:\quake3\MissionPack\code\cgame\cg_main.c"
+"D:\quake3\MissionPack\code\cgame\cg_marks.c"
+"D:\quake3\MissionPack\code\cgame\cg_players.c"
+"D:\quake3\MissionPack\code\cgame\cg_playerstate.c"
+"D:\quake3\MissionPack\code\cgame\cg_predict.c"
+"D:\quake3\MissionPack\code\cgame\cg_rankings.c"
+"D:\quake3\MissionPack\code\cgame\cg_scoreboard.c"
+"D:\quake3\MissionPack\code\cgame\cg_servercmds.c"
+"D:\quake3\MissionPack\code\cgame\cg_snapshot.c"
+"D:\quake3\MissionPack\code\cgame\cg_syscalls.c"
+"D:\quake3\MissionPack\code\cgame\cg_view.c"
+"D:\quake3\MissionPack\code\cgame\cg_weapons.c"
+"D:\quake3\MissionPack\code\game\q_math.c"
+"D:\quake3\MissionPack\code\game\q_shared.c"
+"D:\quake3\MissionPack\code\ui\ui_shared.c"
+]
+Creating command line "cl.exe @C:\WINNT\Profiles\ADMINI~1\LOCALS~1\Temp\RSP4BE.tmp"
+Creating temporary file "C:\WINNT\Profiles\ADMINI~1\LOCALS~1\Temp\RSP4BF.tmp" with contents
+[
+/nologo /base:"0x30000000" /subsystem:windows /dll /incremental:no /pdb:"Release/cgamex86.pdb" /map:"Release/cgamex86.map" /machine:I386 /def:".\cgame.def" /out:"../Release/cgamex86.dll" /implib:"Release/cgamex86.lib"
+.\Release\bg_misc.obj
+.\Release\bg_pmove.obj
+.\Release\bg_slidemove.obj
+.\Release\cg_consolecmds.obj
+.\Release\cg_draw.obj
+.\Release\cg_drawtools.obj
+.\Release\cg_effects.obj
+.\Release\cg_ents.obj
+.\Release\cg_event.obj
+.\Release\cg_info.obj
+.\Release\cg_localents.obj
+.\Release\cg_main.obj
+.\Release\cg_marks.obj
+.\Release\cg_players.obj
+.\Release\cg_playerstate.obj
+.\Release\cg_predict.obj
+.\Release\cg_rankings.obj
+.\Release\cg_scoreboard.obj
+.\Release\cg_servercmds.obj
+.\Release\cg_snapshot.obj
+.\Release\cg_syscalls.obj
+.\Release\cg_view.obj
+.\Release\cg_weapons.obj
+.\Release\q_math.obj
+.\Release\q_shared.obj
+.\Release\ui_shared.obj
+]
+Creating command line "link.exe @C:\WINNT\Profiles\ADMINI~1\LOCALS~1\Temp\RSP4BF.tmp"
+<h3>Output Window</h3>
+Compiling...
+bg_misc.c
+bg_pmove.c
+D:\quake3\MissionPack\code\game\bg_pmove.c(987) : warning C4189: 'shit' : local variable is initialized but not referenced
+D:\quake3\MissionPack\code\game\bg_pmove.c(2001) : warning C4505: 'PM_InvulnerabilityMove' : unreferenced local function has been removed
+ D:\quake3\MissionPack\code\game\bg_pmove.c(519) : see declaration of 'PM_InvulnerabilityMove'
+bg_slidemove.c
+cg_consolecmds.c
+cg_draw.c
+cg_drawtools.c
+cg_effects.c
+cg_ents.c
+cg_event.c
+cg_info.c
+cg_localents.c
+cg_main.c
+D:\quake3\MissionPack\code\cgame\cg_main.c(1819) : warning C4505: 'CG_Cvar_Get' : unreferenced local function has been removed
+ D:\quake3\MissionPack\code\cgame\cg_main.c(1513) : see declaration of 'CG_Cvar_Get'
+cg_marks.c
+cg_players.c
+D:\quake3\MissionPack\code\cgame\cg_players.c(2209) : warning C4505: 'CG_PlayerTokens' : unreferenced local function has been removed
+ D:\quake3\MissionPack\code\cgame\cg_players.c(1371) : see declaration of 'CG_PlayerTokens'
+cg_playerstate.c
+cg_predict.c
+cg_rankings.c
+cg_scoreboard.c
+cg_servercmds.c
+cg_snapshot.c
+cg_syscalls.c
+cg_view.c
+cg_weapons.c
+q_math.c
+q_shared.c
+ui_shared.c
+D:\quake3\MissionPack\code\ui\ui_shared.c(2223) : warning C4189: 'parent' : local variable is initialized but not referenced
+D:\quake3\MissionPack\code\ui\ui_shared.c(3501) : warning C4189: 'collision' : local variable is initialized but not referenced
+D:\quake3\MissionPack\code\ui\ui_shared.c(4622) : warning C4505: 'Controls_SetDefaults' : unreferenced local function has been removed
+ D:\quake3\MissionPack\code\ui\ui_shared.c(2595) : see declaration of 'Controls_SetDefaults'
+D:\quake3\MissionPack\code\ui\ui_shared.c(1540) : warning C4701: local variable 'value' may be used without having been initialized
+D:\quake3\MissionPack\code\ui\ui_shared.c(1566) : warning C4701: local variable 'value' may be used without having been initialized
+D:\quake3\MissionPack\code\ui\ui_shared.c(1912) : warning C4702: unreachable code
+D:\quake3\MissionPack\code\ui\ui_shared.c(4013) : warning C4702: unreachable code
+D:\quake3\MissionPack\code\ui\ui_shared.c(4056) : warning C4702: unreachable code
+Linking...
+ Creating library Release/cgamex86.lib and object Release/cgamex86.exp
+
+
+
+<h3>Results</h3>
+cgamex86.dll - 0 error(s), 12 warning(s)
+</pre>
+</body>
+</html>
diff --git a/code/cgame/cgame.q3asm b/code/cgame/cgame.q3asm
new file mode 100755
index 0000000..7923f73
--- /dev/null
+++ b/code/cgame/cgame.q3asm
@@ -0,0 +1,26 @@
+-o "\quake3\baseq3\vm\cgame"
+cg_main
+..\cg_syscalls
+cg_consolecmds
+cg_draw
+cg_drawtools
+cg_effects
+cg_ents
+cg_event
+cg_info
+cg_localents
+cg_marks
+cg_players
+cg_playerstate
+cg_predict
+cg_scoreboard
+cg_servercmds
+cg_snapshot
+cg_view
+cg_weapons
+bg_slidemove
+bg_pmove
+bg_lib
+bg_misc
+q_math
+q_shared
diff --git a/code/cgame/cgame.sh b/code/cgame/cgame.sh
new file mode 100755
index 0000000..62f2570
--- /dev/null
+++ b/code/cgame/cgame.sh
@@ -0,0 +1,36 @@
+#!/bin/sh
+
+mkdir -p vm
+cd vm
+
+CC="q3lcc -DQ3_VM -DCGAME -S -Wf-target=bytecode -Wf-g -I../../cgame -I../../game -I../../q3_ui"
+
+$CC ../cg_syscalls.c
+$CC ../../game/bg_misc.c
+$CC ../../game/bg_pmove.c
+$CC ../../game/bg_slidemove.c
+$CC ../../game/bg_lib.c
+$CC ../../game/q_math.c
+$CC ../../game/q_shared.c
+$CC ../cg_consolecmds.c
+$CC ../cg_draw.c
+$CC ../cg_drawtools.c
+$CC ../cg_effects.c
+$CC ../cg_ents.c
+$CC ../cg_event.c
+$CC ../cg_info.c
+$CC ../cg_localents.c
+$CC ../cg_main.c
+$CC ../cg_marks.c
+$CC ../cg_players.c
+$CC ../cg_playerstate.c
+$CC ../cg_predict.c
+$CC ../cg_scoreboard.c
+$CC ../cg_servercmds.c
+$CC ../cg_snapshot.c
+$CC ../cg_view.c
+$CC ../cg_weapons.c
+
+q3asm -f ../cgame
+
+cd ..
diff --git a/code/cgame/cgame.vcproj b/code/cgame/cgame.vcproj
new file mode 100755
index 0000000..4dbdfd0
--- /dev/null
+++ b/code/cgame/cgame.vcproj
@@ -0,0 +1,1221 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+ ProjectType="Visual C++"
+ Version="7.10"
+ Name="cgame"
+ SccProjectName="&quot;$/MissionPack/code/cgame&quot;, NPAAAAAA"
+ SccLocalPath=".">
+ <Platforms>
+ <Platform
+ Name="Win32"/>
+ </Platforms>
+ <Configurations>
+ <Configuration
+ Name="Release TA|Win32"
+ OutputDirectory=".\Release_TA"
+ IntermediateDirectory=".\Release_TA"
+ ConfigurationType="2"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ OptimizeForProcessor="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK"
+ StringPooling="TRUE"
+ RuntimeLibrary="4"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Release_TA/cgame.pch"
+ AssemblerListingLocation=".\Release_TA/"
+ ObjectFile=".\Release_TA/"
+ ProgramDataBaseFileName=".\Release_TA/"
+ WarningLevel="4"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="odbc32.lib odbccp32.lib"
+ OutputFile="../Release_TA/cgamex86.dll"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ ModuleDefinitionFile=".\cgame.def"
+ ProgramDatabaseFile=".\Release_TA/cgamex86.pdb"
+ GenerateMapFile="TRUE"
+ MapFileName=".\Release_TA/cgamex86.map"
+ SubSystem="2"
+ BaseAddress="0x30000000"
+ ImportLibrary=".\Release_TA/cgamex86.lib"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="NDEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\Release_TA/cgame.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Debug|Win32"
+ OutputDirectory=".\Debug"
+ IntermediateDirectory=".\Debug"
+ ConfigurationType="2"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ OptimizeForProcessor="1"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS"
+ RuntimeLibrary="1"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Debug/cgame.pch"
+ AssemblerListingLocation=".\Debug/"
+ ObjectFile=".\Debug/"
+ ProgramDataBaseFileName=".\Debug/"
+ BrowseInformation="1"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="odbc32.lib odbccp32.lib"
+ OutputFile="../Debug/cgamex86.dll"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ ModuleDefinitionFile=".\cgame.def"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile=".\Debug/cgamex86.pdb"
+ GenerateMapFile="TRUE"
+ MapFileName=".\Debug/cgamex86.map"
+ SubSystem="2"
+ BaseAddress="0x30000000"
+ ImportLibrary=".\Debug/cgamex86.lib"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="_DEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\Debug/cgame.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Release|Win32"
+ OutputDirectory=".\Release"
+ IntermediateDirectory=".\Release"
+ ConfigurationType="2"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ OptimizeForProcessor="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS"
+ StringPooling="TRUE"
+ RuntimeLibrary="4"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Release/cgame.pch"
+ AssemblerListingLocation=".\Release/"
+ ObjectFile=".\Release/"
+ ProgramDataBaseFileName=".\Release/"
+ WarningLevel="4"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="odbc32.lib odbccp32.lib"
+ OutputFile="../Release/cgamex86.dll"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ ModuleDefinitionFile=".\cgame.def"
+ ProgramDatabaseFile=".\Release/cgamex86.pdb"
+ GenerateMapFile="TRUE"
+ MapFileName=".\Release/cgamex86.map"
+ SubSystem="2"
+ BaseAddress="0x30000000"
+ ImportLibrary=".\Release/cgamex86.lib"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="NDEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\Release/cgame.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Debug TA|Win32"
+ OutputDirectory=".\Debug_TA"
+ IntermediateDirectory=".\Debug_TA"
+ ConfigurationType="2"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ OptimizeForProcessor="1"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK"
+ RuntimeLibrary="1"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Debug_TA/cgame.pch"
+ AssemblerListingLocation=".\Debug_TA/"
+ ObjectFile=".\Debug_TA/"
+ ProgramDataBaseFileName=".\Debug_TA/"
+ BrowseInformation="1"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="odbc32.lib odbccp32.lib"
+ OutputFile="..\Debug_TA\cgamex86.dll"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ ModuleDefinitionFile=".\cgame.def"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile=".\Debug_TA/cgamex86.pdb"
+ GenerateMapFile="TRUE"
+ MapFileName=".\Debug_TA/cgamex86.map"
+ SubSystem="2"
+ BaseAddress="0x30000000"
+ ImportLibrary=".\Debug_TA/cgamex86.lib"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="_DEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\Debug_TA/cgame.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ </Configurations>
+ <References>
+ </References>
+ <Files>
+ <Filter
+ Name="Source Files"
+ Filter="c">
+ <File
+ RelativePath="..\game\bg_lib.c">
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\game\bg_misc.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\game\bg_pmove.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\game\bg_slidemove.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="cg_consolecmds.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="cg_draw.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="cg_drawtools.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="cg_effects.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="cg_ents.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="cg_event.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="cg_info.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="cg_localents.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="cg_main.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="cg_marks.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="cg_newDraw.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="cg_players.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="cg_playerstate.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="cg_predict.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="cg_scoreboard.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="cg_servercmds.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="cg_snapshot.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="cg_syscalls.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="cg_view.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="cg_weapons.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\game\q_math.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\game\q_shared.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ui\ui_shared.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <Filter
+ Name="Header Files"
+ Filter="h">
+ <File
+ RelativePath="..\game\bg_public.h">
+ </File>
+ <File
+ RelativePath="cg_local.h">
+ </File>
+ <File
+ RelativePath="cg_public.h">
+ </File>
+ <File
+ RelativePath="..\game\q_shared.h">
+ </File>
+ <File
+ RelativePath="..\game\surfaceflags.h">
+ </File>
+ </Filter>
+ <File
+ RelativePath="cgame.def">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ </Files>
+ <Globals>
+ </Globals>
+</VisualStudioProject>
diff --git a/code/cgame/cgame_ta.bat b/code/cgame/cgame_ta.bat
new file mode 100755
index 0000000..266e017
--- /dev/null
+++ b/code/cgame/cgame_ta.bat
@@ -0,0 +1,65 @@
+rem make sure we have a safe environement
+set LIBRARY=
+set INCLUDE=
+
+mkdir vm
+cd vm
+set cc=lcc -DQ3_VM -DMISSIONPACK -DCGAME -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\ui %1
+
+%cc% ../../game/bg_misc.c
+@if errorlevel 1 goto quit
+%cc% ../../game/bg_pmove.c
+@if errorlevel 1 goto quit
+%cc% ../../game/bg_slidemove.c
+@if errorlevel 1 goto quit
+%cc% ../../game/bg_lib.c
+@if errorlevel 1 goto quit
+%cc% ../../game/q_math.c
+@if errorlevel 1 goto quit
+%cc% ../../game/q_shared.c
+@if errorlevel 1 goto quit
+%cc% ../cg_consolecmds.c
+@if errorlevel 1 goto quit
+%cc% ../cg_draw.c
+@if errorlevel 1 goto quit
+%cc% ../cg_drawtools.c
+@if errorlevel 1 goto quit
+%cc% ../cg_effects.c
+@if errorlevel 1 goto quit
+%cc% ../cg_ents.c
+@if errorlevel 1 goto quit
+%cc% ../cg_event.c
+@if errorlevel 1 goto quit
+%cc% ../cg_info.c
+@if errorlevel 1 goto quit
+%cc% ../cg_localents.c
+@if errorlevel 1 goto quit
+%cc% ../cg_main.c
+@if errorlevel 1 goto quit
+%cc% ../cg_marks.c
+@if errorlevel 1 goto quit
+%cc% ../cg_players.c
+@if errorlevel 1 goto quit
+%cc% ../cg_playerstate.c
+@if errorlevel 1 goto quit
+%cc% ../cg_predict.c
+@if errorlevel 1 goto quit
+%cc% ../cg_scoreboard.c
+@if errorlevel 1 goto quit
+%cc% ../cg_servercmds.c
+@if errorlevel 1 goto quit
+%cc% ../cg_snapshot.c
+@if errorlevel 1 goto quit
+%cc% ../cg_view.c
+@if errorlevel 1 goto quit
+%cc% ../cg_weapons.c
+@if errorlevel 1 goto quit
+%cc% ../../ui/ui_shared.c
+@if errorlevel 1 goto quit
+%cc% ../cg_newdraw.c
+@if errorlevel 1 goto quit
+
+
+q3asm -f ../cgame_ta
+:quit
+cd ..
diff --git a/code/cgame/cgame_ta.q3asm b/code/cgame/cgame_ta.q3asm
new file mode 100755
index 0000000..8b14ed9
--- /dev/null
+++ b/code/cgame/cgame_ta.q3asm
@@ -0,0 +1,28 @@
+-o "\quake3\missionpack\vm\cgame"
+cg_main
+..\cg_syscalls
+cg_consolecmds
+cg_draw
+cg_drawtools
+cg_effects
+cg_ents
+cg_event
+cg_info
+cg_localents
+cg_marks
+cg_players
+cg_playerstate
+cg_predict
+cg_scoreboard
+cg_servercmds
+cg_snapshot
+cg_view
+cg_weapons
+bg_slidemove
+bg_pmove
+bg_lib
+bg_misc
+q_math
+q_shared
+ui_shared
+cg_newdraw
diff --git a/code/cgame/cgame_ta.sh b/code/cgame/cgame_ta.sh
new file mode 100755
index 0000000..5f87eb5
--- /dev/null
+++ b/code/cgame/cgame_ta.sh
@@ -0,0 +1,38 @@
+#!/bin/sh
+
+mkdir -p vm
+cd vm
+
+CC="q3lcc -DQ3_VM -DCGAME -DMISSIONPACK -S -Wf-target=bytecode -Wf-g -I../../cgame -I../../game -I../../ui"
+
+$CC ../cg_syscalls.c
+$CC ../../game/bg_misc.c
+$CC ../../game/bg_pmove.c
+$CC ../../game/bg_slidemove.c
+$CC ../../game/bg_lib.c
+$CC ../../game/q_math.c
+$CC ../../game/q_shared.c
+$CC ../cg_consolecmds.c
+$CC ../cg_draw.c
+$CC ../cg_drawtools.c
+$CC ../cg_effects.c
+$CC ../cg_ents.c
+$CC ../cg_event.c
+$CC ../cg_info.c
+$CC ../cg_localents.c
+$CC ../cg_main.c
+$CC ../cg_marks.c
+$CC ../cg_players.c
+$CC ../cg_playerstate.c
+$CC ../cg_predict.c
+$CC ../cg_scoreboard.c
+$CC ../cg_servercmds.c
+$CC ../cg_snapshot.c
+$CC ../cg_view.c
+$CC ../cg_weapons.c
+$CC ../../ui/ui_shared.c
+$CC ../cg_newdraw.c
+
+q3asm -f ../cgame_ta
+
+cd ..
diff --git a/code/cgame/tr_types.h b/code/cgame/tr_types.h
new file mode 100755
index 0000000..ec2e054
--- /dev/null
+++ b/code/cgame/tr_types.h
@@ -0,0 +1,229 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#ifndef __TR_TYPES_H
+#define __TR_TYPES_H
+
+
+#define MAX_DLIGHTS 32 // can't be increased, because bit flags are used on surfaces
+#define MAX_ENTITIES 1023 // can't be increased without changing drawsurf bit packing
+
+// renderfx flags
+#define RF_MINLIGHT 1 // allways have some light (viewmodel, some items)
+#define RF_THIRD_PERSON 2 // don't draw through eyes, only mirrors (player bodies, chat sprites)
+#define RF_FIRST_PERSON 4 // only draw through eyes (view weapon, damage blood blob)
+#define RF_DEPTHHACK 8 // for view weapon Z crunching
+#define RF_NOSHADOW 64 // don't add stencil shadows
+
+#define RF_LIGHTING_ORIGIN 128 // use refEntity->lightingOrigin instead of refEntity->origin
+ // for lighting. This allows entities to sink into the floor
+ // with their origin going solid, and allows all parts of a
+ // player to get the same lighting
+#define RF_SHADOW_PLANE 256 // use refEntity->shadowPlane
+#define RF_WRAP_FRAMES 512 // mod the model frames by the maxframes to allow continuous
+ // animation without needing to know the frame count
+
+// refdef flags
+#define RDF_NOWORLDMODEL 1 // used for player configuration screen
+#define RDF_HYPERSPACE 4 // teleportation effect
+
+typedef struct {
+ vec3_t xyz;
+ float st[2];
+ byte modulate[4];
+} polyVert_t;
+
+typedef struct poly_s {
+ qhandle_t hShader;
+ int numVerts;
+ polyVert_t *verts;
+} poly_t;
+
+typedef enum {
+ RT_MODEL,
+ RT_POLY,
+ RT_SPRITE,
+ RT_BEAM,
+ RT_RAIL_CORE,
+ RT_RAIL_RINGS,
+ RT_LIGHTNING,
+ RT_PORTALSURFACE, // doesn't draw anything, just info for portals
+
+ RT_MAX_REF_ENTITY_TYPE
+} refEntityType_t;
+
+typedef struct {
+ refEntityType_t reType;
+ int renderfx;
+
+ qhandle_t hModel; // opaque type outside refresh
+
+ // most recent data
+ vec3_t lightingOrigin; // so multi-part models can be lit identically (RF_LIGHTING_ORIGIN)
+ float shadowPlane; // projection shadows go here, stencils go slightly lower
+
+ vec3_t axis[3]; // rotation vectors
+ qboolean nonNormalizedAxes; // axis are not normalized, i.e. they have scale
+ float origin[3]; // also used as MODEL_BEAM's "from"
+ int frame; // also used as MODEL_BEAM's diameter
+
+ // previous data for frame interpolation
+ float oldorigin[3]; // also used as MODEL_BEAM's "to"
+ int oldframe;
+ float backlerp; // 0.0 = current, 1.0 = old
+
+ // texturing
+ int skinNum; // inline skin index
+ qhandle_t customSkin; // NULL for default skin
+ qhandle_t customShader; // use one image for the entire thing
+
+ // misc
+ byte shaderRGBA[4]; // colors used by rgbgen entity shaders
+ float shaderTexCoord[2]; // texture coordinates used by tcMod entity modifiers
+ float shaderTime; // subtracted from refdef time to control effect start times
+
+ // extra sprite information
+ float radius;
+ float rotation;
+} refEntity_t;
+
+
+#define MAX_RENDER_STRINGS 8
+#define MAX_RENDER_STRING_LENGTH 32
+
+typedef struct {
+ int x, y, width, height;
+ float fov_x, fov_y;
+ vec3_t vieworg;
+ vec3_t viewaxis[3]; // transformation matrix
+
+ // time in milliseconds for shader effects and other time dependent rendering issues
+ int time;
+
+ int rdflags; // RDF_NOWORLDMODEL, etc
+
+ // 1 bits will prevent the associated area from rendering at all
+ byte areamask[MAX_MAP_AREA_BYTES];
+
+ // text messages for deform text shaders
+ char text[MAX_RENDER_STRINGS][MAX_RENDER_STRING_LENGTH];
+} refdef_t;
+
+
+typedef enum {
+ STEREO_CENTER,
+ STEREO_LEFT,
+ STEREO_RIGHT
+} stereoFrame_t;
+
+
+/*
+** glconfig_t
+**
+** Contains variables specific to the OpenGL configuration
+** being run right now. These are constant once the OpenGL
+** subsystem is initialized.
+*/
+typedef enum {
+ TC_NONE,
+ TC_S3TC
+} textureCompression_t;
+
+typedef enum {
+ GLDRV_ICD, // driver is integrated with window system
+ // WARNING: there are tests that check for
+ // > GLDRV_ICD for minidriverness, so this
+ // should always be the lowest value in this
+ // enum set
+ GLDRV_STANDALONE, // driver is a non-3Dfx standalone driver
+ GLDRV_VOODOO // driver is a 3Dfx standalone driver
+} glDriverType_t;
+
+typedef enum {
+ GLHW_GENERIC, // where everthing works the way it should
+ GLHW_3DFX_2D3D, // Voodoo Banshee or Voodoo3, relevant since if this is
+ // the hardware type then there can NOT exist a secondary
+ // display adapter
+ GLHW_RIVA128, // where you can't interpolate alpha
+ GLHW_RAGEPRO, // where you can't modulate alpha on alpha textures
+ GLHW_PERMEDIA2 // where you don't have src*dst
+} glHardwareType_t;
+
+typedef struct {
+ char renderer_string[MAX_STRING_CHARS];
+ char vendor_string[MAX_STRING_CHARS];
+ char version_string[MAX_STRING_CHARS];
+ char extensions_string[BIG_INFO_STRING];
+
+ int maxTextureSize; // queried from GL
+ int maxActiveTextures; // multitexture ability
+
+ int colorBits, depthBits, stencilBits;
+
+ glDriverType_t driverType;
+ glHardwareType_t hardwareType;
+
+ qboolean deviceSupportsGamma;
+ textureCompression_t textureCompression;
+ qboolean textureEnvAddAvailable;
+
+ int vidWidth, vidHeight;
+ // aspect is the screen's physical width / height, which may be different
+ // than scrWidth / scrHeight if the pixels are non-square
+ // normal screens should be 4/3, but wide aspect monitors may be 16/9
+ float windowAspect;
+
+ int displayFrequency;
+
+ // synonymous with "does rendering consume the entire screen?", therefore
+ // a Voodoo or Voodoo2 will have this set to TRUE, as will a Win32 ICD that
+ // used CDS.
+ qboolean isFullscreen;
+ qboolean stereoEnabled;
+ qboolean smpActive; // dual processor
+} glconfig_t;
+
+// FIXME: VM should be OS agnostic .. in theory
+
+/*
+#ifdef Q3_VM
+
+#define _3DFX_DRIVER_NAME "Voodoo"
+#define OPENGL_DRIVER_NAME "Default"
+
+#elif defined(_WIN32)
+*/
+
+#if defined(Q3_VM) || defined(_WIN32)
+
+#define _3DFX_DRIVER_NAME "3dfxvgl"
+#define OPENGL_DRIVER_NAME "opengl32"
+
+#else
+
+#define _3DFX_DRIVER_NAME "libMesaVoodooGL.so"
+// https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=524
+#define OPENGL_DRIVER_NAME "libGL.so.1"
+
+#endif // !defined _WIN32
+
+#endif // __TR_TYPES_H
diff --git a/code/clean.bat b/code/clean.bat
new file mode 100755
index 0000000..3daad51
--- /dev/null
+++ b/code/clean.bat
@@ -0,0 +1,61 @@
+rmdir debug /s /q
+rmdir release /s /q
+del quake3.ncb
+del quake3.opt
+del quake3.plg
+del quake3.stt
+rmdir cgame\debug /s /q
+rmdir cgame\release /s /q
+del cgame\cgame.ncb
+del cgame\cgame.opt
+del cgame\cgame.plg
+del cgame\cgame.stt
+rmdir game\debug /s /q
+rmdir game\release /s /q
+del game\game.ncb
+del game\game.opt
+del game\game.plg
+del game\game.stt
+rmdir ui\debug /s /q
+rmdir ui\release /s /q
+del ui\ui.ncb
+del ui\ui.opt
+del ui\ui.plg
+del ui\ui.stt
+rmdir renderer\debug /s /q
+rmdir renderer\release /s /q
+del renderer\renderer.ncb
+del renderer\renderer.opt
+del renderer\renderer.plg
+del renderer\renderer.stt
+rmdir botlib\debug /s /q
+rmdir botlib\release /s /q
+del botlib\botlib.ncb
+del botlib\botlib.opt
+del botlib\botlib.plg
+del botlib\botlib.stt
+rmdir botlai\debug /s /q
+rmdir botlai\release /s /q
+del botai\botai.dsp
+del botai\botai.plg
+rmdir bspc\debug /s /q
+rmdir bspc\release /s /q
+del bspc\bspc.exe
+del bspc\bspc.log
+del bspc\bspc.ncb
+del bspc\bspc.opt
+del bspc\bspc.pdb
+del bspc\bspc.plg
+rmdir unix\debugi386-glibc /s /q
+rmdir unix\releasei386-glibc /s /q
+rmdir "mac\MacQuake3 Data" /s /q
+rmdir macosx\Client\Q3Test.app /s /q
+rmdir macosx\Client\Q3Test.build /s /q
+del *.o /s
+del *.obj /s
+del *.lib /s
+del *.dll /s
+del *.ncb /s
+del *.plg /s
+del *.map /s
+del *.opt /s
diff --git a/code/client/cl_cgame.c b/code/client/cl_cgame.c
new file mode 100755
index 0000000..0b259d3
--- /dev/null
+++ b/code/client/cl_cgame.c
@@ -0,0 +1,1029 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// cl_cgame.c -- client system interaction with client game
+
+#include "client.h"
+
+#include "../game/botlib.h"
+
+extern botlib_export_t *botlib_export;
+
+extern qboolean loadCamera(const char *name);
+extern void startCamera(int time);
+extern qboolean getCameraInfo(int time, vec3_t *origin, vec3_t *angles);
+
+/*
+====================
+CL_GetGameState
+====================
+*/
+void CL_GetGameState( gameState_t *gs ) {
+ *gs = cl.gameState;
+}
+
+/*
+====================
+CL_GetGlconfig
+====================
+*/
+void CL_GetGlconfig( glconfig_t *glconfig ) {
+ *glconfig = cls.glconfig;
+}
+
+
+/*
+====================
+CL_GetUserCmd
+====================
+*/
+qboolean CL_GetUserCmd( int cmdNumber, usercmd_t *ucmd ) {
+ // cmds[cmdNumber] is the last properly generated command
+
+ // can't return anything that we haven't created yet
+ if ( cmdNumber > cl.cmdNumber ) {
+ Com_Error( ERR_DROP, "CL_GetUserCmd: %i >= %i", cmdNumber, cl.cmdNumber );
+ }
+
+ // the usercmd has been overwritten in the wrapping
+ // buffer because it is too far out of date
+ if ( cmdNumber <= cl.cmdNumber - CMD_BACKUP ) {
+ return qfalse;
+ }
+
+ *ucmd = cl.cmds[ cmdNumber & CMD_MASK ];
+
+ return qtrue;
+}
+
+int CL_GetCurrentCmdNumber( void ) {
+ return cl.cmdNumber;
+}
+
+
+/*
+====================
+CL_GetParseEntityState
+====================
+*/
+qboolean CL_GetParseEntityState( int parseEntityNumber, entityState_t *state ) {
+ // can't return anything that hasn't been parsed yet
+ if ( parseEntityNumber >= cl.parseEntitiesNum ) {
+ Com_Error( ERR_DROP, "CL_GetParseEntityState: %i >= %i",
+ parseEntityNumber, cl.parseEntitiesNum );
+ }
+
+ // can't return anything that has been overwritten in the circular buffer
+ if ( parseEntityNumber <= cl.parseEntitiesNum - MAX_PARSE_ENTITIES ) {
+ return qfalse;
+ }
+
+ *state = cl.parseEntities[ parseEntityNumber & ( MAX_PARSE_ENTITIES - 1 ) ];
+ return qtrue;
+}
+
+/*
+====================
+CL_GetCurrentSnapshotNumber
+====================
+*/
+void CL_GetCurrentSnapshotNumber( int *snapshotNumber, int *serverTime ) {
+ *snapshotNumber = cl.snap.messageNum;
+ *serverTime = cl.snap.serverTime;
+}
+
+/*
+====================
+CL_GetSnapshot
+====================
+*/
+qboolean CL_GetSnapshot( int snapshotNumber, snapshot_t *snapshot ) {
+ clSnapshot_t *clSnap;
+ int i, count;
+
+ if ( snapshotNumber > cl.snap.messageNum ) {
+ Com_Error( ERR_DROP, "CL_GetSnapshot: snapshotNumber > cl.snapshot.messageNum" );
+ }
+
+ // if the frame has fallen out of the circular buffer, we can't return it
+ if ( cl.snap.messageNum - snapshotNumber >= PACKET_BACKUP ) {
+ return qfalse;
+ }
+
+ // if the frame is not valid, we can't return it
+ clSnap = &cl.snapshots[snapshotNumber & PACKET_MASK];
+ if ( !clSnap->valid ) {
+ return qfalse;
+ }
+
+ // if the entities in the frame have fallen out of their
+ // circular buffer, we can't return it
+ if ( cl.parseEntitiesNum - clSnap->parseEntitiesNum >= MAX_PARSE_ENTITIES ) {
+ return qfalse;
+ }
+
+ // write the snapshot
+ snapshot->snapFlags = clSnap->snapFlags;
+ snapshot->serverCommandSequence = clSnap->serverCommandNum;
+ snapshot->ping = clSnap->ping;
+ snapshot->serverTime = clSnap->serverTime;
+ Com_Memcpy( snapshot->areamask, clSnap->areamask, sizeof( snapshot->areamask ) );
+ snapshot->ps = clSnap->ps;
+ count = clSnap->numEntities;
+ if ( count > MAX_ENTITIES_IN_SNAPSHOT ) {
+ Com_DPrintf( "CL_GetSnapshot: truncated %i entities to %i\n", count, MAX_ENTITIES_IN_SNAPSHOT );
+ count = MAX_ENTITIES_IN_SNAPSHOT;
+ }
+ snapshot->numEntities = count;
+ for ( i = 0 ; i < count ; i++ ) {
+ snapshot->entities[i] =
+ cl.parseEntities[ ( clSnap->parseEntitiesNum + i ) & (MAX_PARSE_ENTITIES-1) ];
+ }
+
+ // FIXME: configstring changes and server commands!!!
+
+ return qtrue;
+}
+
+/*
+=====================
+CL_SetUserCmdValue
+=====================
+*/
+void CL_SetUserCmdValue( int userCmdValue, float sensitivityScale ) {
+ cl.cgameUserCmdValue = userCmdValue;
+ cl.cgameSensitivity = sensitivityScale;
+}
+
+/*
+=====================
+CL_AddCgameCommand
+=====================
+*/
+void CL_AddCgameCommand( const char *cmdName ) {
+ Cmd_AddCommand( cmdName, NULL );
+}
+
+/*
+=====================
+CL_CgameError
+=====================
+*/
+void CL_CgameError( const char *string ) {
+ Com_Error( ERR_DROP, "%s", string );
+}
+
+
+/*
+=====================
+CL_ConfigstringModified
+=====================
+*/
+void CL_ConfigstringModified( void ) {
+ char *old, *s;
+ int i, index;
+ char *dup;
+ gameState_t oldGs;
+ int len;
+
+ index = atoi( Cmd_Argv(1) );
+ if ( index < 0 || index >= MAX_CONFIGSTRINGS ) {
+ Com_Error( ERR_DROP, "configstring > MAX_CONFIGSTRINGS" );
+ }
+ // get everything after "cs <num>"
+ s = Cmd_ArgsFrom(2);
+
+ old = cl.gameState.stringData + cl.gameState.stringOffsets[ index ];
+ if ( !strcmp( old, s ) ) {
+ return; // unchanged
+ }
+
+ // build the new gameState_t
+ oldGs = cl.gameState;
+
+ Com_Memset( &cl.gameState, 0, sizeof( cl.gameState ) );
+
+ // leave the first 0 for uninitialized strings
+ cl.gameState.dataCount = 1;
+
+ for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) {
+ if ( i == index ) {
+ dup = s;
+ } else {
+ dup = oldGs.stringData + oldGs.stringOffsets[ i ];
+ }
+ if ( !dup[0] ) {
+ continue; // leave with the default empty string
+ }
+
+ len = strlen( dup );
+
+ if ( len + 1 + cl.gameState.dataCount > MAX_GAMESTATE_CHARS ) {
+ Com_Error( ERR_DROP, "MAX_GAMESTATE_CHARS exceeded" );
+ }
+
+ // append it to the gameState string buffer
+ cl.gameState.stringOffsets[ i ] = cl.gameState.dataCount;
+ Com_Memcpy( cl.gameState.stringData + cl.gameState.dataCount, dup, len + 1 );
+ cl.gameState.dataCount += len + 1;
+ }
+
+ if ( index == CS_SYSTEMINFO ) {
+ // parse serverId and other cvars
+ CL_SystemInfoChanged();
+ }
+
+}
+
+
+/*
+===================
+CL_GetServerCommand
+
+Set up argc/argv for the given command
+===================
+*/
+qboolean CL_GetServerCommand( int serverCommandNumber ) {
+ char *s;
+ char *cmd;
+ static char bigConfigString[BIG_INFO_STRING];
+ int argc;
+
+ // if we have irretrievably lost a reliable command, drop the connection
+ if ( serverCommandNumber <= clc.serverCommandSequence - MAX_RELIABLE_COMMANDS ) {
+ // when a demo record was started after the client got a whole bunch of
+ // reliable commands then the client never got those first reliable commands
+ if ( clc.demoplaying )
+ return qfalse;
+ Com_Error( ERR_DROP, "CL_GetServerCommand: a reliable command was cycled out" );
+ return qfalse;
+ }
+
+ if ( serverCommandNumber > clc.serverCommandSequence ) {
+ Com_Error( ERR_DROP, "CL_GetServerCommand: requested a command not received" );
+ return qfalse;
+ }
+
+ s = clc.serverCommands[ serverCommandNumber & ( MAX_RELIABLE_COMMANDS - 1 ) ];
+ clc.lastExecutedServerCommand = serverCommandNumber;
+
+ Com_DPrintf( "serverCommand: %i : %s\n", serverCommandNumber, s );
+
+rescan:
+ Cmd_TokenizeString( s );
+ cmd = Cmd_Argv(0);
+ argc = Cmd_Argc();
+
+ if ( !strcmp( cmd, "disconnect" ) ) {
+ // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=552
+ // allow server to indicate why they were disconnected
+ if ( argc >= 2 )
+ Com_Error (ERR_SERVERDISCONNECT, va( "Server Disconnected - %s", Cmd_Argv( 1 ) ) );
+ else
+ Com_Error (ERR_SERVERDISCONNECT,"Server disconnected\n");
+ }
+
+ if ( !strcmp( cmd, "bcs0" ) ) {
+ Com_sprintf( bigConfigString, BIG_INFO_STRING, "cs %s \"%s", Cmd_Argv(1), Cmd_Argv(2) );
+ return qfalse;
+ }
+
+ if ( !strcmp( cmd, "bcs1" ) ) {
+ s = Cmd_Argv(2);
+ if( strlen(bigConfigString) + strlen(s) >= BIG_INFO_STRING ) {
+ Com_Error( ERR_DROP, "bcs exceeded BIG_INFO_STRING" );
+ }
+ strcat( bigConfigString, s );
+ return qfalse;
+ }
+
+ if ( !strcmp( cmd, "bcs2" ) ) {
+ s = Cmd_Argv(2);
+ if( strlen(bigConfigString) + strlen(s) + 1 >= BIG_INFO_STRING ) {
+ Com_Error( ERR_DROP, "bcs exceeded BIG_INFO_STRING" );
+ }
+ strcat( bigConfigString, s );
+ strcat( bigConfigString, "\"" );
+ s = bigConfigString;
+ goto rescan;
+ }
+
+ if ( !strcmp( cmd, "cs" ) ) {
+ CL_ConfigstringModified();
+ // reparse the string, because CL_ConfigstringModified may have done another Cmd_TokenizeString()
+ Cmd_TokenizeString( s );
+ return qtrue;
+ }
+
+ if ( !strcmp( cmd, "map_restart" ) ) {
+ // clear notify lines and outgoing commands before passing
+ // the restart to the cgame
+ Con_ClearNotify();
+ Com_Memset( cl.cmds, 0, sizeof( cl.cmds ) );
+ return qtrue;
+ }
+
+ // the clientLevelShot command is used during development
+ // to generate 128*128 screenshots from the intermission
+ // point of levels for the menu system to use
+ // we pass it along to the cgame to make apropriate adjustments,
+ // but we also clear the console and notify lines here
+ if ( !strcmp( cmd, "clientLevelShot" ) ) {
+ // don't do it if we aren't running the server locally,
+ // otherwise malicious remote servers could overwrite
+ // the existing thumbnails
+ if ( !com_sv_running->integer ) {
+ return qfalse;
+ }
+ // close the console
+ Con_Close();
+ // take a special screenshot next frame
+ Cbuf_AddText( "wait ; wait ; wait ; wait ; screenshot levelshot\n" );
+ return qtrue;
+ }
+
+ // we may want to put a "connect to other server" command here
+
+ // cgame can now act on the command
+ return qtrue;
+}
+
+
+/*
+====================
+CL_CM_LoadMap
+
+Just adds default parameters that cgame doesn't need to know about
+====================
+*/
+void CL_CM_LoadMap( const char *mapname ) {
+ int checksum;
+
+ CM_LoadMap( mapname, qtrue, &checksum );
+}
+
+/*
+====================
+CL_ShutdonwCGame
+
+====================
+*/
+void CL_ShutdownCGame( void ) {
+ cls.keyCatchers &= ~KEYCATCH_CGAME;
+ cls.cgameStarted = qfalse;
+ if ( !cgvm ) {
+ return;
+ }
+ VM_Call( cgvm, CG_SHUTDOWN );
+ VM_Free( cgvm );
+ cgvm = NULL;
+}
+
+static int FloatAsInt( float f ) {
+ int temp;
+
+ *(float *)&temp = f;
+
+ return temp;
+}
+
+/*
+====================
+CL_CgameSystemCalls
+
+The cgame module is making a system call
+====================
+*/
+#define VMA(x) VM_ArgPtr(args[x])
+#define VMF(x) ((float *)args)[x]
+int CL_CgameSystemCalls( int *args ) {
+ switch( args[0] ) {
+ case CG_PRINT:
+ Com_Printf( "%s", VMA(1) );
+ return 0;
+ case CG_ERROR:
+ Com_Error( ERR_DROP, "%s", VMA(1) );
+ return 0;
+ case CG_MILLISECONDS:
+ return Sys_Milliseconds();
+ case CG_CVAR_REGISTER:
+ Cvar_Register( VMA(1), VMA(2), VMA(3), args[4] );
+ return 0;
+ case CG_CVAR_UPDATE:
+ Cvar_Update( VMA(1) );
+ return 0;
+ case CG_CVAR_SET:
+ Cvar_Set( VMA(1), VMA(2) );
+ return 0;
+ case CG_CVAR_VARIABLESTRINGBUFFER:
+ Cvar_VariableStringBuffer( VMA(1), VMA(2), args[3] );
+ return 0;
+ case CG_ARGC:
+ return Cmd_Argc();
+ case CG_ARGV:
+ Cmd_ArgvBuffer( args[1], VMA(2), args[3] );
+ return 0;
+ case CG_ARGS:
+ Cmd_ArgsBuffer( VMA(1), args[2] );
+ return 0;
+ case CG_FS_FOPENFILE:
+ return FS_FOpenFileByMode( VMA(1), VMA(2), args[3] );
+ case CG_FS_READ:
+ FS_Read2( VMA(1), args[2], args[3] );
+ return 0;
+ case CG_FS_WRITE:
+ FS_Write( VMA(1), args[2], args[3] );
+ return 0;
+ case CG_FS_FCLOSEFILE:
+ FS_FCloseFile( args[1] );
+ return 0;
+ case CG_FS_SEEK:
+ return FS_Seek( args[1], args[2], args[3] );
+ case CG_SENDCONSOLECOMMAND:
+ Cbuf_AddText( VMA(1) );
+ return 0;
+ case CG_ADDCOMMAND:
+ CL_AddCgameCommand( VMA(1) );
+ return 0;
+ case CG_REMOVECOMMAND:
+ Cmd_RemoveCommand( VMA(1) );
+ return 0;
+ case CG_SENDCLIENTCOMMAND:
+ CL_AddReliableCommand( VMA(1) );
+ return 0;
+ case CG_UPDATESCREEN:
+ // this is used during lengthy level loading, so pump message loop
+// Com_EventLoop(); // FIXME: if a server restarts here, BAD THINGS HAPPEN!
+// We can't call Com_EventLoop here, a restart will crash and this _does_ happen
+// if there is a map change while we are downloading at pk3.
+// ZOID
+ SCR_UpdateScreen();
+ return 0;
+ case CG_CM_LOADMAP:
+ CL_CM_LoadMap( VMA(1) );
+ return 0;
+ case CG_CM_NUMINLINEMODELS:
+ return CM_NumInlineModels();
+ case CG_CM_INLINEMODEL:
+ return CM_InlineModel( args[1] );
+ case CG_CM_TEMPBOXMODEL:
+ return CM_TempBoxModel( VMA(1), VMA(2), /*int capsule*/ qfalse );
+ case CG_CM_TEMPCAPSULEMODEL:
+ return CM_TempBoxModel( VMA(1), VMA(2), /*int capsule*/ qtrue );
+ case CG_CM_POINTCONTENTS:
+ return CM_PointContents( VMA(1), args[2] );
+ case CG_CM_TRANSFORMEDPOINTCONTENTS:
+ return CM_TransformedPointContents( VMA(1), args[2], VMA(3), VMA(4) );
+ case CG_CM_BOXTRACE:
+ CM_BoxTrace( VMA(1), VMA(2), VMA(3), VMA(4), VMA(5), args[6], args[7], /*int capsule*/ qfalse );
+ return 0;
+ case CG_CM_CAPSULETRACE:
+ CM_BoxTrace( VMA(1), VMA(2), VMA(3), VMA(4), VMA(5), args[6], args[7], /*int capsule*/ qtrue );
+ return 0;
+ case CG_CM_TRANSFORMEDBOXTRACE:
+ CM_TransformedBoxTrace( VMA(1), VMA(2), VMA(3), VMA(4), VMA(5), args[6], args[7], VMA(8), VMA(9), /*int capsule*/ qfalse );
+ return 0;
+ case CG_CM_TRANSFORMEDCAPSULETRACE:
+ CM_TransformedBoxTrace( VMA(1), VMA(2), VMA(3), VMA(4), VMA(5), args[6], args[7], VMA(8), VMA(9), /*int capsule*/ qtrue );
+ return 0;
+ case CG_CM_MARKFRAGMENTS:
+ return re.MarkFragments( args[1], VMA(2), VMA(3), args[4], VMA(5), args[6], VMA(7) );
+ case CG_S_STARTSOUND:
+ S_StartSound( VMA(1), args[2], args[3], args[4] );
+ return 0;
+ case CG_S_STARTLOCALSOUND:
+ S_StartLocalSound( args[1], args[2] );
+ return 0;
+ case CG_S_CLEARLOOPINGSOUNDS:
+ S_ClearLoopingSounds(args[1]);
+ return 0;
+ case CG_S_ADDLOOPINGSOUND:
+ S_AddLoopingSound( args[1], VMA(2), VMA(3), args[4] );
+ return 0;
+ case CG_S_ADDREALLOOPINGSOUND:
+ S_AddRealLoopingSound( args[1], VMA(2), VMA(3), args[4] );
+ return 0;
+ case CG_S_STOPLOOPINGSOUND:
+ S_StopLoopingSound( args[1] );
+ return 0;
+ case CG_S_UPDATEENTITYPOSITION:
+ S_UpdateEntityPosition( args[1], VMA(2) );
+ return 0;
+ case CG_S_RESPATIALIZE:
+ S_Respatialize( args[1], VMA(2), VMA(3), args[4] );
+ return 0;
+ case CG_S_REGISTERSOUND:
+ return S_RegisterSound( VMA(1), args[2] );
+ case CG_S_STARTBACKGROUNDTRACK:
+ S_StartBackgroundTrack( VMA(1), VMA(2) );
+ return 0;
+ case CG_R_LOADWORLDMAP:
+ re.LoadWorld( VMA(1) );
+ return 0;
+ case CG_R_REGISTERMODEL:
+ return re.RegisterModel( VMA(1) );
+ case CG_R_REGISTERSKIN:
+ return re.RegisterSkin( VMA(1) );
+ case CG_R_REGISTERSHADER:
+ return re.RegisterShader( VMA(1) );
+ case CG_R_REGISTERSHADERNOMIP:
+ return re.RegisterShaderNoMip( VMA(1) );
+ case CG_R_REGISTERFONT:
+ re.RegisterFont( VMA(1), args[2], VMA(3));
+ case CG_R_CLEARSCENE:
+ re.ClearScene();
+ return 0;
+ case CG_R_ADDREFENTITYTOSCENE:
+ re.AddRefEntityToScene( VMA(1) );
+ return 0;
+ case CG_R_ADDPOLYTOSCENE:
+ re.AddPolyToScene( args[1], args[2], VMA(3), 1 );
+ return 0;
+ case CG_R_ADDPOLYSTOSCENE:
+ re.AddPolyToScene( args[1], args[2], VMA(3), args[4] );
+ return 0;
+ case CG_R_LIGHTFORPOINT:
+ return re.LightForPoint( VMA(1), VMA(2), VMA(3), VMA(4) );
+ case CG_R_ADDLIGHTTOSCENE:
+ re.AddLightToScene( VMA(1), VMF(2), VMF(3), VMF(4), VMF(5) );
+ return 0;
+ case CG_R_ADDADDITIVELIGHTTOSCENE:
+ re.AddAdditiveLightToScene( VMA(1), VMF(2), VMF(3), VMF(4), VMF(5) );
+ return 0;
+ case CG_R_RENDERSCENE:
+ re.RenderScene( VMA(1) );
+ return 0;
+ case CG_R_SETCOLOR:
+ re.SetColor( VMA(1) );
+ return 0;
+ case CG_R_DRAWSTRETCHPIC:
+ re.DrawStretchPic( VMF(1), VMF(2), VMF(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), args[9] );
+ return 0;
+ case CG_R_MODELBOUNDS:
+ re.ModelBounds( args[1], VMA(2), VMA(3) );
+ return 0;
+ case CG_R_LERPTAG:
+ return re.LerpTag( VMA(1), args[2], args[3], args[4], VMF(5), VMA(6) );
+ case CG_GETGLCONFIG:
+ CL_GetGlconfig( VMA(1) );
+ return 0;
+ case CG_GETGAMESTATE:
+ CL_GetGameState( VMA(1) );
+ return 0;
+ case CG_GETCURRENTSNAPSHOTNUMBER:
+ CL_GetCurrentSnapshotNumber( VMA(1), VMA(2) );
+ return 0;
+ case CG_GETSNAPSHOT:
+ return CL_GetSnapshot( args[1], VMA(2) );
+ case CG_GETSERVERCOMMAND:
+ return CL_GetServerCommand( args[1] );
+ case CG_GETCURRENTCMDNUMBER:
+ return CL_GetCurrentCmdNumber();
+ case CG_GETUSERCMD:
+ return CL_GetUserCmd( args[1], VMA(2) );
+ case CG_SETUSERCMDVALUE:
+ CL_SetUserCmdValue( args[1], VMF(2) );
+ return 0;
+ case CG_MEMORY_REMAINING:
+ return Hunk_MemoryRemaining();
+ case CG_KEY_ISDOWN:
+ return Key_IsDown( args[1] );
+ case CG_KEY_GETCATCHER:
+ return Key_GetCatcher();
+ case CG_KEY_SETCATCHER:
+ Key_SetCatcher( args[1] );
+ return 0;
+ case CG_KEY_GETKEY:
+ return Key_GetKey( VMA(1) );
+
+
+
+ case CG_MEMSET:
+ Com_Memset( VMA(1), args[2], args[3] );
+ return 0;
+ case CG_MEMCPY:
+ Com_Memcpy( VMA(1), VMA(2), args[3] );
+ return 0;
+ case CG_STRNCPY:
+ return (int)strncpy( VMA(1), VMA(2), args[3] );
+ case CG_SIN:
+ return FloatAsInt( sin( VMF(1) ) );
+ case CG_COS:
+ return FloatAsInt( cos( VMF(1) ) );
+ case CG_ATAN2:
+ return FloatAsInt( atan2( VMF(1), VMF(2) ) );
+ case CG_SQRT:
+ return FloatAsInt( sqrt( VMF(1) ) );
+ case CG_FLOOR:
+ return FloatAsInt( floor( VMF(1) ) );
+ case CG_CEIL:
+ return FloatAsInt( ceil( VMF(1) ) );
+ case CG_ACOS:
+ return FloatAsInt( Q_acos( VMF(1) ) );
+
+ case CG_PC_ADD_GLOBAL_DEFINE:
+ return botlib_export->PC_AddGlobalDefine( VMA(1) );
+ case CG_PC_LOAD_SOURCE:
+ return botlib_export->PC_LoadSourceHandle( VMA(1) );
+ case CG_PC_FREE_SOURCE:
+ return botlib_export->PC_FreeSourceHandle( args[1] );
+ case CG_PC_READ_TOKEN:
+ return botlib_export->PC_ReadTokenHandle( args[1], VMA(2) );
+ case CG_PC_SOURCE_FILE_AND_LINE:
+ return botlib_export->PC_SourceFileAndLine( args[1], VMA(2), VMA(3) );
+
+ case CG_S_STOPBACKGROUNDTRACK:
+ S_StopBackgroundTrack();
+ return 0;
+
+ case CG_REAL_TIME:
+ return Com_RealTime( VMA(1) );
+ case CG_SNAPVECTOR:
+ Sys_SnapVector( VMA(1) );
+ return 0;
+
+ case CG_CIN_PLAYCINEMATIC:
+ return CIN_PlayCinematic(VMA(1), args[2], args[3], args[4], args[5], args[6]);
+
+ case CG_CIN_STOPCINEMATIC:
+ return CIN_StopCinematic(args[1]);
+
+ case CG_CIN_RUNCINEMATIC:
+ return CIN_RunCinematic(args[1]);
+
+ case CG_CIN_DRAWCINEMATIC:
+ CIN_DrawCinematic(args[1]);
+ return 0;
+
+ case CG_CIN_SETEXTENTS:
+ CIN_SetExtents(args[1], args[2], args[3], args[4], args[5]);
+ return 0;
+
+ case CG_R_REMAP_SHADER:
+ re.RemapShader( VMA(1), VMA(2), VMA(3) );
+ return 0;
+
+/*
+ case CG_LOADCAMERA:
+ return loadCamera(VMA(1));
+
+ case CG_STARTCAMERA:
+ startCamera(args[1]);
+ return 0;
+
+ case CG_GETCAMERAINFO:
+ return getCameraInfo(args[1], VMA(2), VMA(3));
+*/
+ case CG_GET_ENTITY_TOKEN:
+ return re.GetEntityToken( VMA(1), args[2] );
+ case CG_R_INPVS:
+ return re.inPVS( VMA(1), VMA(2) );
+
+ default:
+ assert(0); // bk010102
+ Com_Error( ERR_DROP, "Bad cgame system trap: %i", args[0] );
+ }
+ return 0;
+}
+
+
+/*
+====================
+CL_InitCGame
+
+Should only be called by CL_StartHunkUsers
+====================
+*/
+void CL_InitCGame( void ) {
+ const char *info;
+ const char *mapname;
+ int t1, t2;
+ vmInterpret_t interpret;
+
+ t1 = Sys_Milliseconds();
+
+ // put away the console
+ Con_Close();
+
+ // find the current mapname
+ info = cl.gameState.stringData + cl.gameState.stringOffsets[ CS_SERVERINFO ];
+ mapname = Info_ValueForKey( info, "mapname" );
+ Com_sprintf( cl.mapname, sizeof( cl.mapname ), "maps/%s.bsp", mapname );
+
+ // load the dll or bytecode
+ if ( cl_connectedToPureServer != 0 ) {
+ // if sv_pure is set we only allow qvms to be loaded
+ interpret = VMI_COMPILED;
+ }
+ else {
+ interpret = Cvar_VariableValue( "vm_cgame" );
+ }
+ cgvm = VM_Create( "cgame", CL_CgameSystemCalls, interpret );
+ if ( !cgvm ) {
+ Com_Error( ERR_DROP, "VM_Create on cgame failed" );
+ }
+ cls.state = CA_LOADING;
+
+ // init for this gamestate
+ // use the lastExecutedServerCommand instead of the serverCommandSequence
+ // otherwise server commands sent just before a gamestate are dropped
+ VM_Call( cgvm, CG_INIT, clc.serverMessageSequence, clc.lastExecutedServerCommand, clc.clientNum );
+
+ // we will send a usercmd this frame, which
+ // will cause the server to send us the first snapshot
+ cls.state = CA_PRIMED;
+
+ t2 = Sys_Milliseconds();
+
+ Com_Printf( "CL_InitCGame: %5.2f seconds\n", (t2-t1)/1000.0 );
+
+ // have the renderer touch all its images, so they are present
+ // on the card even if the driver does deferred loading
+ re.EndRegistration();
+
+ // make sure everything is paged in
+ if (!Sys_LowPhysicalMemory()) {
+ Com_TouchMemory();
+ }
+
+ // clear anything that got printed
+ Con_ClearNotify ();
+}
+
+
+/*
+====================
+CL_GameCommand
+
+See if the current console command is claimed by the cgame
+====================
+*/
+qboolean CL_GameCommand( void ) {
+ if ( !cgvm ) {
+ return qfalse;
+ }
+
+ return VM_Call( cgvm, CG_CONSOLE_COMMAND );
+}
+
+
+
+/*
+=====================
+CL_CGameRendering
+=====================
+*/
+void CL_CGameRendering( stereoFrame_t stereo ) {
+ VM_Call( cgvm, CG_DRAW_ACTIVE_FRAME, cl.serverTime, stereo, clc.demoplaying );
+ VM_Debug( 0 );
+}
+
+
+/*
+=================
+CL_AdjustTimeDelta
+
+Adjust the clients view of server time.
+
+We attempt to have cl.serverTime exactly equal the server's view
+of time plus the timeNudge, but with variable latencies over
+the internet it will often need to drift a bit to match conditions.
+
+Our ideal time would be to have the adjusted time approach, but not pass,
+the very latest snapshot.
+
+Adjustments are only made when a new snapshot arrives with a rational
+latency, which keeps the adjustment process framerate independent and
+prevents massive overadjustment during times of significant packet loss
+or bursted delayed packets.
+=================
+*/
+
+#define RESET_TIME 500
+
+void CL_AdjustTimeDelta( void ) {
+ int resetTime;
+ int newDelta;
+ int deltaDelta;
+
+ cl.newSnapshots = qfalse;
+
+ // the delta never drifts when replaying a demo
+ if ( clc.demoplaying ) {
+ return;
+ }
+
+ // if the current time is WAY off, just correct to the current value
+ if ( com_sv_running->integer ) {
+ resetTime = 100;
+ } else {
+ resetTime = RESET_TIME;
+ }
+
+ newDelta = cl.snap.serverTime - cls.realtime;
+ deltaDelta = abs( newDelta - cl.serverTimeDelta );
+
+ if ( deltaDelta > RESET_TIME ) {
+ cl.serverTimeDelta = newDelta;
+ cl.oldServerTime = cl.snap.serverTime; // FIXME: is this a problem for cgame?
+ cl.serverTime = cl.snap.serverTime;
+ if ( cl_showTimeDelta->integer ) {
+ Com_Printf( "<RESET> " );
+ }
+ } else if ( deltaDelta > 100 ) {
+ // fast adjust, cut the difference in half
+ if ( cl_showTimeDelta->integer ) {
+ Com_Printf( "<FAST> " );
+ }
+ cl.serverTimeDelta = ( cl.serverTimeDelta + newDelta ) >> 1;
+ } else {
+ // slow drift adjust, only move 1 or 2 msec
+
+ // if any of the frames between this and the previous snapshot
+ // had to be extrapolated, nudge our sense of time back a little
+ // the granularity of +1 / -2 is too high for timescale modified frametimes
+ if ( com_timescale->value == 0 || com_timescale->value == 1 ) {
+ if ( cl.extrapolatedSnapshot ) {
+ cl.extrapolatedSnapshot = qfalse;
+ cl.serverTimeDelta -= 2;
+ } else {
+ // otherwise, move our sense of time forward to minimize total latency
+ cl.serverTimeDelta++;
+ }
+ }
+ }
+
+ if ( cl_showTimeDelta->integer ) {
+ Com_Printf( "%i ", cl.serverTimeDelta );
+ }
+}
+
+
+/*
+==================
+CL_FirstSnapshot
+==================
+*/
+void CL_FirstSnapshot( void ) {
+ // ignore snapshots that don't have entities
+ if ( cl.snap.snapFlags & SNAPFLAG_NOT_ACTIVE ) {
+ return;
+ }
+ cls.state = CA_ACTIVE;
+
+ // set the timedelta so we are exactly on this first frame
+ cl.serverTimeDelta = cl.snap.serverTime - cls.realtime;
+ cl.oldServerTime = cl.snap.serverTime;
+
+ clc.timeDemoBaseTime = cl.snap.serverTime;
+
+ // if this is the first frame of active play,
+ // execute the contents of activeAction now
+ // this is to allow scripting a timedemo to start right
+ // after loading
+ if ( cl_activeAction->string[0] ) {
+ Cbuf_AddText( cl_activeAction->string );
+ Cvar_Set( "activeAction", "" );
+ }
+
+ Sys_BeginProfiling();
+}
+
+/*
+==================
+CL_SetCGameTime
+==================
+*/
+void CL_SetCGameTime( void ) {
+ // getting a valid frame message ends the connection process
+ if ( cls.state != CA_ACTIVE ) {
+ if ( cls.state != CA_PRIMED ) {
+ return;
+ }
+ if ( clc.demoplaying ) {
+ // we shouldn't get the first snapshot on the same frame
+ // as the gamestate, because it causes a bad time skip
+ if ( !clc.firstDemoFrameSkipped ) {
+ clc.firstDemoFrameSkipped = qtrue;
+ return;
+ }
+ CL_ReadDemoMessage();
+ }
+ if ( cl.newSnapshots ) {
+ cl.newSnapshots = qfalse;
+ CL_FirstSnapshot();
+ }
+ if ( cls.state != CA_ACTIVE ) {
+ return;
+ }
+ }
+
+ // if we have gotten to this point, cl.snap is guaranteed to be valid
+ if ( !cl.snap.valid ) {
+ Com_Error( ERR_DROP, "CL_SetCGameTime: !cl.snap.valid" );
+ }
+
+ // allow pause in single player
+ if ( sv_paused->integer && cl_paused->integer && com_sv_running->integer ) {
+ // paused
+ return;
+ }
+
+ if ( cl.snap.serverTime < cl.oldFrameServerTime ) {
+ Com_Error( ERR_DROP, "cl.snap.serverTime < cl.oldFrameServerTime" );
+ }
+ cl.oldFrameServerTime = cl.snap.serverTime;
+
+
+ // get our current view of time
+
+ if ( clc.demoplaying && cl_freezeDemo->integer ) {
+ // cl_freezeDemo is used to lock a demo in place for single frame advances
+
+ } else {
+ // cl_timeNudge is a user adjustable cvar that allows more
+ // or less latency to be added in the interest of better
+ // smoothness or better responsiveness.
+ int tn;
+
+ tn = cl_timeNudge->integer;
+ if (tn<-30) {
+ tn = -30;
+ } else if (tn>30) {
+ tn = 30;
+ }
+
+ cl.serverTime = cls.realtime + cl.serverTimeDelta - tn;
+
+ // guarantee that time will never flow backwards, even if
+ // serverTimeDelta made an adjustment or cl_timeNudge was changed
+ if ( cl.serverTime < cl.oldServerTime ) {
+ cl.serverTime = cl.oldServerTime;
+ }
+ cl.oldServerTime = cl.serverTime;
+
+ // note if we are almost past the latest frame (without timeNudge),
+ // so we will try and adjust back a bit when the next snapshot arrives
+ if ( cls.realtime + cl.serverTimeDelta >= cl.snap.serverTime - 5 ) {
+ cl.extrapolatedSnapshot = qtrue;
+ }
+ }
+
+ // if we have gotten new snapshots, drift serverTimeDelta
+ // don't do this every frame, or a period of packet loss would
+ // make a huge adjustment
+ if ( cl.newSnapshots ) {
+ CL_AdjustTimeDelta();
+ }
+
+ if ( !clc.demoplaying ) {
+ return;
+ }
+
+ // if we are playing a demo back, we can just keep reading
+ // messages from the demo file until the cgame definately
+ // has valid snapshots to interpolate between
+
+ // a timedemo will always use a deterministic set of time samples
+ // no matter what speed machine it is run on,
+ // while a normal demo may have different time samples
+ // each time it is played back
+ if ( cl_timedemo->integer ) {
+ if (!clc.timeDemoStart) {
+ clc.timeDemoStart = Sys_Milliseconds();
+ }
+ clc.timeDemoFrames++;
+ cl.serverTime = clc.timeDemoBaseTime + clc.timeDemoFrames * 50;
+ }
+
+ while ( cl.serverTime >= cl.snap.serverTime ) {
+ // feed another messag, which should change
+ // the contents of cl.snap
+ CL_ReadDemoMessage();
+ if ( cls.state != CA_ACTIVE ) {
+ return; // end of demo
+ }
+ }
+
+}
+
+
+
diff --git a/code/client/cl_cin.c b/code/client/cl_cin.c
new file mode 100755
index 0000000..7929624
--- /dev/null
+++ b/code/client/cl_cin.c
@@ -0,0 +1,1740 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: cl_cin.c
+ *
+ * desc: video and cinematic playback
+ *
+ * $Archive: /MissionPack/code/client/cl_cin.c $
+ *
+ * cl_glconfig.hwtype trtypes 3dfx/ragepro need 256x256
+ *
+ *****************************************************************************/
+
+#include "client.h"
+#include "snd_local.h"
+
+#define MAXSIZE 8
+#define MINSIZE 4
+
+#define DEFAULT_CIN_WIDTH 512
+#define DEFAULT_CIN_HEIGHT 512
+
+#define ROQ_QUAD 0x1000
+#define ROQ_QUAD_INFO 0x1001
+#define ROQ_CODEBOOK 0x1002
+#define ROQ_QUAD_VQ 0x1011
+#define ROQ_QUAD_JPEG 0x1012
+#define ROQ_QUAD_HANG 0x1013
+#define ROQ_PACKET 0x1030
+#define ZA_SOUND_MONO 0x1020
+#define ZA_SOUND_STEREO 0x1021
+
+#define MAX_VIDEO_HANDLES 16
+
+extern glconfig_t glConfig;
+extern int s_paintedtime;
+extern int s_rawend;
+
+
+static void RoQ_init( void );
+
+/******************************************************************************
+*
+* Class: trFMV
+*
+* Description: RoQ/RnR manipulation routines
+* not entirely complete for first run
+*
+******************************************************************************/
+
+static long ROQ_YY_tab[256];
+static long ROQ_UB_tab[256];
+static long ROQ_UG_tab[256];
+static long ROQ_VG_tab[256];
+static long ROQ_VR_tab[256];
+static unsigned short vq2[256*16*4];
+static unsigned short vq4[256*64*4];
+static unsigned short vq8[256*256*4];
+
+
+typedef struct {
+ byte linbuf[DEFAULT_CIN_WIDTH*DEFAULT_CIN_HEIGHT*4*2];
+ byte file[65536];
+ short sqrTable[256];
+
+ unsigned int mcomp[256];
+ byte *qStatus[2][32768];
+
+ long oldXOff, oldYOff, oldysize, oldxsize;
+
+ int currentHandle;
+} cinematics_t;
+
+typedef struct {
+ char fileName[MAX_OSPATH];
+ int CIN_WIDTH, CIN_HEIGHT;
+ int xpos, ypos, width, height;
+ qboolean looping, holdAtEnd, dirty, alterGameState, silent, shader;
+ fileHandle_t iFile;
+ e_status status;
+ unsigned int startTime;
+ unsigned int lastTime;
+ long tfps;
+ long RoQPlayed;
+ long ROQSize;
+ unsigned int RoQFrameSize;
+ long onQuad;
+ long numQuads;
+ long samplesPerLine;
+ unsigned int roq_id;
+ long screenDelta;
+
+ void ( *VQ0)(byte *status, void *qdata );
+ void ( *VQ1)(byte *status, void *qdata );
+ void ( *VQNormal)(byte *status, void *qdata );
+ void ( *VQBuffer)(byte *status, void *qdata );
+
+ long samplesPerPixel; // defaults to 2
+ byte* gray;
+ unsigned int xsize, ysize, maxsize, minsize;
+
+ qboolean half, smootheddouble, inMemory;
+ long normalBuffer0;
+ long roq_flags;
+ long roqF0;
+ long roqF1;
+ long t[2];
+ long roqFPS;
+ int playonwalls;
+ byte* buf;
+ long drawX, drawY;
+} cin_cache;
+
+static cinematics_t cin;
+static cin_cache cinTable[MAX_VIDEO_HANDLES];
+static int currentHandle = -1;
+static int CL_handle = -1;
+
+extern int s_soundtime; // sample PAIRS
+extern int s_paintedtime; // sample PAIRS
+
+
+void CIN_CloseAllVideos(void) {
+ int i;
+
+ for ( i = 0 ; i < MAX_VIDEO_HANDLES ; i++ ) {
+ if (cinTable[i].fileName[0] != 0 ) {
+ CIN_StopCinematic(i);
+ }
+ }
+}
+
+
+static int CIN_HandleForVideo(void) {
+ int i;
+
+ for ( i = 0 ; i < MAX_VIDEO_HANDLES ; i++ ) {
+ if ( cinTable[i].fileName[0] == 0 ) {
+ return i;
+ }
+ }
+ Com_Error( ERR_DROP, "CIN_HandleForVideo: none free" );
+ return -1;
+}
+
+
+extern int CL_ScaledMilliseconds(void);
+
+//-----------------------------------------------------------------------------
+// RllSetupTable
+//
+// Allocates and initializes the square table.
+//
+// Parameters: None
+//
+// Returns: Nothing
+//-----------------------------------------------------------------------------
+static void RllSetupTable()
+{
+ int z;
+
+ for (z=0;z<128;z++) {
+ cin.sqrTable[z] = (short)(z*z);
+ cin.sqrTable[z+128] = (short)(-cin.sqrTable[z]);
+ }
+}
+
+
+
+//-----------------------------------------------------------------------------
+// RllDecodeMonoToMono
+//
+// Decode mono source data into a mono buffer.
+//
+// Parameters: from -> buffer holding encoded data
+// to -> buffer to hold decoded data
+// size = number of bytes of input (= # of shorts of output)
+// signedOutput = 0 for unsigned output, non-zero for signed output
+// flag = flags from asset header
+//
+// Returns: Number of samples placed in output buffer
+//-----------------------------------------------------------------------------
+long RllDecodeMonoToMono(unsigned char *from,short *to,unsigned int size,char signedOutput ,unsigned short flag)
+{
+ unsigned int z;
+ int prev;
+
+ if (signedOutput)
+ prev = flag - 0x8000;
+ else
+ prev = flag;
+
+ for (z=0;z<size;z++) {
+ prev = to[z] = (short)(prev + cin.sqrTable[from[z]]);
+ }
+ return size; //*sizeof(short));
+}
+
+
+//-----------------------------------------------------------------------------
+// RllDecodeMonoToStereo
+//
+// Decode mono source data into a stereo buffer. Output is 4 times the number
+// of bytes in the input.
+//
+// Parameters: from -> buffer holding encoded data
+// to -> buffer to hold decoded data
+// size = number of bytes of input (= 1/4 # of bytes of output)
+// signedOutput = 0 for unsigned output, non-zero for signed output
+// flag = flags from asset header
+//
+// Returns: Number of samples placed in output buffer
+//-----------------------------------------------------------------------------
+long RllDecodeMonoToStereo(unsigned char *from,short *to,unsigned int size,char signedOutput,unsigned short flag)
+{
+ unsigned int z;
+ int prev;
+
+ if (signedOutput)
+ prev = flag - 0x8000;
+ else
+ prev = flag;
+
+ for (z = 0; z < size; z++) {
+ prev = (short)(prev + cin.sqrTable[from[z]]);
+ to[z*2+0] = to[z*2+1] = (short)(prev);
+ }
+
+ return size; // * 2 * sizeof(short));
+}
+
+
+//-----------------------------------------------------------------------------
+// RllDecodeStereoToStereo
+//
+// Decode stereo source data into a stereo buffer.
+//
+// Parameters: from -> buffer holding encoded data
+// to -> buffer to hold decoded data
+// size = number of bytes of input (= 1/2 # of bytes of output)
+// signedOutput = 0 for unsigned output, non-zero for signed output
+// flag = flags from asset header
+//
+// Returns: Number of samples placed in output buffer
+//-----------------------------------------------------------------------------
+long RllDecodeStereoToStereo(unsigned char *from,short *to,unsigned int size,char signedOutput, unsigned short flag)
+{
+ unsigned int z;
+ unsigned char *zz = from;
+ int prevL, prevR;
+
+ if (signedOutput) {
+ prevL = (flag & 0xff00) - 0x8000;
+ prevR = ((flag & 0x00ff) << 8) - 0x8000;
+ } else {
+ prevL = flag & 0xff00;
+ prevR = (flag & 0x00ff) << 8;
+ }
+
+ for (z=0;z<size;z+=2) {
+ prevL = (short)(prevL + cin.sqrTable[*zz++]);
+ prevR = (short)(prevR + cin.sqrTable[*zz++]);
+ to[z+0] = (short)(prevL);
+ to[z+1] = (short)(prevR);
+ }
+
+ return (size>>1); //*sizeof(short));
+}
+
+
+//-----------------------------------------------------------------------------
+// RllDecodeStereoToMono
+//
+// Decode stereo source data into a mono buffer.
+//
+// Parameters: from -> buffer holding encoded data
+// to -> buffer to hold decoded data
+// size = number of bytes of input (= # of bytes of output)
+// signedOutput = 0 for unsigned output, non-zero for signed output
+// flag = flags from asset header
+//
+// Returns: Number of samples placed in output buffer
+//-----------------------------------------------------------------------------
+long RllDecodeStereoToMono(unsigned char *from,short *to,unsigned int size,char signedOutput, unsigned short flag)
+{
+ unsigned int z;
+ int prevL,prevR;
+
+ if (signedOutput) {
+ prevL = (flag & 0xff00) - 0x8000;
+ prevR = ((flag & 0x00ff) << 8) -0x8000;
+ } else {
+ prevL = flag & 0xff00;
+ prevR = (flag & 0x00ff) << 8;
+ }
+
+ for (z=0;z<size;z+=1) {
+ prevL= prevL + cin.sqrTable[from[z*2]];
+ prevR = prevR + cin.sqrTable[from[z*2+1]];
+ to[z] = (short)((prevL + prevR)/2);
+ }
+
+ return size;
+}
+
+/******************************************************************************
+*
+* Function:
+*
+* Description:
+*
+******************************************************************************/
+
+static void move8_32( byte *src, byte *dst, int spl )
+{
+ double *dsrc, *ddst;
+ int dspl;
+
+ dsrc = (double *)src;
+ ddst = (double *)dst;
+ dspl = spl>>3;
+
+ ddst[0] = dsrc[0]; ddst[1] = dsrc[1]; ddst[2] = dsrc[2]; ddst[3] = dsrc[3];
+ dsrc += dspl; ddst += dspl;
+ ddst[0] = dsrc[0]; ddst[1] = dsrc[1]; ddst[2] = dsrc[2]; ddst[3] = dsrc[3];
+ dsrc += dspl; ddst += dspl;
+ ddst[0] = dsrc[0]; ddst[1] = dsrc[1]; ddst[2] = dsrc[2]; ddst[3] = dsrc[3];
+ dsrc += dspl; ddst += dspl;
+ ddst[0] = dsrc[0]; ddst[1] = dsrc[1]; ddst[2] = dsrc[2]; ddst[3] = dsrc[3];
+ dsrc += dspl; ddst += dspl;
+ ddst[0] = dsrc[0]; ddst[1] = dsrc[1]; ddst[2] = dsrc[2]; ddst[3] = dsrc[3];
+ dsrc += dspl; ddst += dspl;
+ ddst[0] = dsrc[0]; ddst[1] = dsrc[1]; ddst[2] = dsrc[2]; ddst[3] = dsrc[3];
+ dsrc += dspl; ddst += dspl;
+ ddst[0] = dsrc[0]; ddst[1] = dsrc[1]; ddst[2] = dsrc[2]; ddst[3] = dsrc[3];
+ dsrc += dspl; ddst += dspl;
+ ddst[0] = dsrc[0]; ddst[1] = dsrc[1]; ddst[2] = dsrc[2]; ddst[3] = dsrc[3];
+}
+
+/******************************************************************************
+*
+* Function:
+*
+* Description:
+*
+******************************************************************************/
+
+static void move4_32( byte *src, byte *dst, int spl )
+{
+ double *dsrc, *ddst;
+ int dspl;
+
+ dsrc = (double *)src;
+ ddst = (double *)dst;
+ dspl = spl>>3;
+
+ ddst[0] = dsrc[0]; ddst[1] = dsrc[1];
+ dsrc += dspl; ddst += dspl;
+ ddst[0] = dsrc[0]; ddst[1] = dsrc[1];
+ dsrc += dspl; ddst += dspl;
+ ddst[0] = dsrc[0]; ddst[1] = dsrc[1];
+ dsrc += dspl; ddst += dspl;
+ ddst[0] = dsrc[0]; ddst[1] = dsrc[1];
+}
+
+/******************************************************************************
+*
+* Function:
+*
+* Description:
+*
+******************************************************************************/
+
+static void blit8_32( byte *src, byte *dst, int spl )
+{
+ double *dsrc, *ddst;
+ int dspl;
+
+ dsrc = (double *)src;
+ ddst = (double *)dst;
+ dspl = spl>>3;
+
+ ddst[0] = dsrc[0]; ddst[1] = dsrc[1]; ddst[2] = dsrc[2]; ddst[3] = dsrc[3];
+ dsrc += 4; ddst += dspl;
+ ddst[0] = dsrc[0]; ddst[1] = dsrc[1]; ddst[2] = dsrc[2]; ddst[3] = dsrc[3];
+ dsrc += 4; ddst += dspl;
+ ddst[0] = dsrc[0]; ddst[1] = dsrc[1]; ddst[2] = dsrc[2]; ddst[3] = dsrc[3];
+ dsrc += 4; ddst += dspl;
+ ddst[0] = dsrc[0]; ddst[1] = dsrc[1]; ddst[2] = dsrc[2]; ddst[3] = dsrc[3];
+ dsrc += 4; ddst += dspl;
+ ddst[0] = dsrc[0]; ddst[1] = dsrc[1]; ddst[2] = dsrc[2]; ddst[3] = dsrc[3];
+ dsrc += 4; ddst += dspl;
+ ddst[0] = dsrc[0]; ddst[1] = dsrc[1]; ddst[2] = dsrc[2]; ddst[3] = dsrc[3];
+ dsrc += 4; ddst += dspl;
+ ddst[0] = dsrc[0]; ddst[1] = dsrc[1]; ddst[2] = dsrc[2]; ddst[3] = dsrc[3];
+ dsrc += 4; ddst += dspl;
+ ddst[0] = dsrc[0]; ddst[1] = dsrc[1]; ddst[2] = dsrc[2]; ddst[3] = dsrc[3];
+}
+
+/******************************************************************************
+*
+* Function:
+*
+* Description:
+*
+******************************************************************************/
+#define movs double
+static void blit4_32( byte *src, byte *dst, int spl )
+{
+ movs *dsrc, *ddst;
+ int dspl;
+
+ dsrc = (movs *)src;
+ ddst = (movs *)dst;
+ dspl = spl>>3;
+
+ ddst[0] = dsrc[0]; ddst[1] = dsrc[1];
+ dsrc += 2; ddst += dspl;
+ ddst[0] = dsrc[0]; ddst[1] = dsrc[1];
+ dsrc += 2; ddst += dspl;
+ ddst[0] = dsrc[0]; ddst[1] = dsrc[1];
+ dsrc += 2; ddst += dspl;
+ ddst[0] = dsrc[0]; ddst[1] = dsrc[1];
+}
+
+/******************************************************************************
+*
+* Function:
+*
+* Description:
+*
+******************************************************************************/
+
+static void blit2_32( byte *src, byte *dst, int spl )
+{
+ double *dsrc, *ddst;
+ int dspl;
+
+ dsrc = (double *)src;
+ ddst = (double *)dst;
+ dspl = spl>>3;
+
+ ddst[0] = dsrc[0];
+ ddst[dspl] = dsrc[1];
+}
+
+/******************************************************************************
+*
+* Function:
+*
+* Description:
+*
+******************************************************************************/
+
+static void blitVQQuad32fs( byte **status, unsigned char *data )
+{
+unsigned short newd, celdata, code;
+unsigned int index, i;
+int spl;
+
+ newd = 0;
+ celdata = 0;
+ index = 0;
+
+ spl = cinTable[currentHandle].samplesPerLine;
+
+ do {
+ if (!newd) {
+ newd = 7;
+ celdata = data[0] + data[1]*256;
+ data += 2;
+ } else {
+ newd--;
+ }
+
+ code = (unsigned short)(celdata&0xc000);
+ celdata <<= 2;
+
+ switch (code) {
+ case 0x8000: // vq code
+ blit8_32( (byte *)&vq8[(*data)*128], status[index], spl );
+ data++;
+ index += 5;
+ break;
+ case 0xc000: // drop
+ index++; // skip 8x8
+ for(i=0;i<4;i++) {
+ if (!newd) {
+ newd = 7;
+ celdata = data[0] + data[1]*256;
+ data += 2;
+ } else {
+ newd--;
+ }
+
+ code = (unsigned short)(celdata&0xc000); celdata <<= 2;
+
+ switch (code) { // code in top two bits of code
+ case 0x8000: // 4x4 vq code
+ blit4_32( (byte *)&vq4[(*data)*32], status[index], spl );
+ data++;
+ break;
+ case 0xc000: // 2x2 vq code
+ blit2_32( (byte *)&vq2[(*data)*8], status[index], spl );
+ data++;
+ blit2_32( (byte *)&vq2[(*data)*8], status[index]+8, spl );
+ data++;
+ blit2_32( (byte *)&vq2[(*data)*8], status[index]+spl*2, spl );
+ data++;
+ blit2_32( (byte *)&vq2[(*data)*8], status[index]+spl*2+8, spl );
+ data++;
+ break;
+ case 0x4000: // motion compensation
+ move4_32( status[index] + cin.mcomp[(*data)], status[index], spl );
+ data++;
+ break;
+ }
+ index++;
+ }
+ break;
+ case 0x4000: // motion compensation
+ move8_32( status[index] + cin.mcomp[(*data)], status[index], spl );
+ data++;
+ index += 5;
+ break;
+ case 0x0000:
+ index += 5;
+ break;
+ }
+ } while ( status[index] != NULL );
+}
+
+/******************************************************************************
+*
+* Function:
+*
+* Description:
+*
+******************************************************************************/
+
+static void ROQ_GenYUVTables( void )
+{
+ float t_ub,t_vr,t_ug,t_vg;
+ long i;
+
+ t_ub = (1.77200f/2.0f) * (float)(1<<6) + 0.5f;
+ t_vr = (1.40200f/2.0f) * (float)(1<<6) + 0.5f;
+ t_ug = (0.34414f/2.0f) * (float)(1<<6) + 0.5f;
+ t_vg = (0.71414f/2.0f) * (float)(1<<6) + 0.5f;
+ for(i=0;i<256;i++) {
+ float x = (float)(2 * i - 255);
+
+ ROQ_UB_tab[i] = (long)( ( t_ub * x) + (1<<5));
+ ROQ_VR_tab[i] = (long)( ( t_vr * x) + (1<<5));
+ ROQ_UG_tab[i] = (long)( (-t_ug * x) );
+ ROQ_VG_tab[i] = (long)( (-t_vg * x) + (1<<5));
+ ROQ_YY_tab[i] = (long)( (i << 6) | (i >> 2) );
+ }
+}
+
+#define VQ2TO4(a,b,c,d) { \
+ *c++ = a[0]; \
+ *d++ = a[0]; \
+ *d++ = a[0]; \
+ *c++ = a[1]; \
+ *d++ = a[1]; \
+ *d++ = a[1]; \
+ *c++ = b[0]; \
+ *d++ = b[0]; \
+ *d++ = b[0]; \
+ *c++ = b[1]; \
+ *d++ = b[1]; \
+ *d++ = b[1]; \
+ *d++ = a[0]; \
+ *d++ = a[0]; \
+ *d++ = a[1]; \
+ *d++ = a[1]; \
+ *d++ = b[0]; \
+ *d++ = b[0]; \
+ *d++ = b[1]; \
+ *d++ = b[1]; \
+ a += 2; b += 2; }
+
+#define VQ2TO2(a,b,c,d) { \
+ *c++ = *a; \
+ *d++ = *a; \
+ *d++ = *a; \
+ *c++ = *b; \
+ *d++ = *b; \
+ *d++ = *b; \
+ *d++ = *a; \
+ *d++ = *a; \
+ *d++ = *b; \
+ *d++ = *b; \
+ a++; b++; }
+
+/******************************************************************************
+*
+* Function:
+*
+* Description:
+*
+******************************************************************************/
+
+static unsigned short yuv_to_rgb( long y, long u, long v )
+{
+ long r,g,b,YY = (long)(ROQ_YY_tab[(y)]);
+
+ r = (YY + ROQ_VR_tab[v]) >> 9;
+ g = (YY + ROQ_UG_tab[u] + ROQ_VG_tab[v]) >> 8;
+ b = (YY + ROQ_UB_tab[u]) >> 9;
+
+ if (r<0) r = 0; if (g<0) g = 0; if (b<0) b = 0;
+ if (r > 31) r = 31; if (g > 63) g = 63; if (b > 31) b = 31;
+
+ return (unsigned short)((r<<11)+(g<<5)+(b));
+}
+
+/******************************************************************************
+*
+* Function:
+*
+* Description:
+*
+******************************************************************************/
+#if defined(MACOS_X)
+
+static inline unsigned int yuv_to_rgb24( long y, long u, long v )
+{
+ long r,g,b,YY;
+
+ YY = (long)(ROQ_YY_tab[(y)]);
+
+ r = (YY + ROQ_VR_tab[v]) >> 6;
+ g = (YY + ROQ_UG_tab[u] + ROQ_VG_tab[v]) >> 6;
+ b = (YY + ROQ_UB_tab[u]) >> 6;
+
+ if (r<0) r = 0; if (g<0) g = 0; if (b<0) b = 0;
+ if (r > 255) r = 255; if (g > 255) g = 255; if (b > 255) b = 255;
+
+ return ((r<<24)|(g<<16)|(b<<8))|(255); //+(255<<24));
+}
+
+#else
+static unsigned int yuv_to_rgb24( long y, long u, long v )
+{
+ long r,g,b,YY = (long)(ROQ_YY_tab[(y)]);
+
+ r = (YY + ROQ_VR_tab[v]) >> 6;
+ g = (YY + ROQ_UG_tab[u] + ROQ_VG_tab[v]) >> 6;
+ b = (YY + ROQ_UB_tab[u]) >> 6;
+
+ if (r<0) r = 0; if (g<0) g = 0; if (b<0) b = 0;
+ if (r > 255) r = 255; if (g > 255) g = 255; if (b > 255) b = 255;
+
+ return LittleLong ((r)|(g<<8)|(b<<16)|(255<<24));
+}
+#endif
+
+/******************************************************************************
+*
+* Function:
+*
+* Description:
+*
+******************************************************************************/
+
+static void decodeCodeBook( byte *input, unsigned short roq_flags )
+{
+ long i, j, two, four;
+ unsigned short *aptr, *bptr, *cptr, *dptr;
+ long y0,y1,y2,y3,cr,cb;
+ byte *bbptr, *baptr, *bcptr, *bdptr;
+ unsigned int *iaptr, *ibptr, *icptr, *idptr;
+
+ if (!roq_flags) {
+ two = four = 256;
+ } else {
+ two = roq_flags>>8;
+ if (!two) two = 256;
+ four = roq_flags&0xff;
+ }
+
+ four *= 2;
+
+ bptr = (unsigned short *)vq2;
+
+ if (!cinTable[currentHandle].half) {
+ if (!cinTable[currentHandle].smootheddouble) {
+//
+// normal height
+//
+ if (cinTable[currentHandle].samplesPerPixel==2) {
+ for(i=0;i<two;i++) {
+ y0 = (long)*input++;
+ y1 = (long)*input++;
+ y2 = (long)*input++;
+ y3 = (long)*input++;
+ cr = (long)*input++;
+ cb = (long)*input++;
+ *bptr++ = yuv_to_rgb( y0, cr, cb );
+ *bptr++ = yuv_to_rgb( y1, cr, cb );
+ *bptr++ = yuv_to_rgb( y2, cr, cb );
+ *bptr++ = yuv_to_rgb( y3, cr, cb );
+ }
+
+ cptr = (unsigned short *)vq4;
+ dptr = (unsigned short *)vq8;
+
+ for(i=0;i<four;i++) {
+ aptr = (unsigned short *)vq2 + (*input++)*4;
+ bptr = (unsigned short *)vq2 + (*input++)*4;
+ for(j=0;j<2;j++)
+ VQ2TO4(aptr,bptr,cptr,dptr);
+ }
+ } else if (cinTable[currentHandle].samplesPerPixel==4) {
+ ibptr = (unsigned int *)bptr;
+ for(i=0;i<two;i++) {
+ y0 = (long)*input++;
+ y1 = (long)*input++;
+ y2 = (long)*input++;
+ y3 = (long)*input++;
+ cr = (long)*input++;
+ cb = (long)*input++;
+ *ibptr++ = yuv_to_rgb24( y0, cr, cb );
+ *ibptr++ = yuv_to_rgb24( y1, cr, cb );
+ *ibptr++ = yuv_to_rgb24( y2, cr, cb );
+ *ibptr++ = yuv_to_rgb24( y3, cr, cb );
+ }
+
+ icptr = (unsigned int *)vq4;
+ idptr = (unsigned int *)vq8;
+
+ for(i=0;i<four;i++) {
+ iaptr = (unsigned int *)vq2 + (*input++)*4;
+ ibptr = (unsigned int *)vq2 + (*input++)*4;
+ for(j=0;j<2;j++)
+ VQ2TO4(iaptr, ibptr, icptr, idptr);
+ }
+ } else if (cinTable[currentHandle].samplesPerPixel==1) {
+ bbptr = (byte *)bptr;
+ for(i=0;i<two;i++) {
+ *bbptr++ = cinTable[currentHandle].gray[*input++];
+ *bbptr++ = cinTable[currentHandle].gray[*input++];
+ *bbptr++ = cinTable[currentHandle].gray[*input++];
+ *bbptr++ = cinTable[currentHandle].gray[*input]; input +=3;
+ }
+
+ bcptr = (byte *)vq4;
+ bdptr = (byte *)vq8;
+
+ for(i=0;i<four;i++) {
+ baptr = (byte *)vq2 + (*input++)*4;
+ bbptr = (byte *)vq2 + (*input++)*4;
+ for(j=0;j<2;j++)
+ VQ2TO4(baptr,bbptr,bcptr,bdptr);
+ }
+ }
+ } else {
+//
+// double height, smoothed
+//
+ if (cinTable[currentHandle].samplesPerPixel==2) {
+ for(i=0;i<two;i++) {
+ y0 = (long)*input++;
+ y1 = (long)*input++;
+ y2 = (long)*input++;
+ y3 = (long)*input++;
+ cr = (long)*input++;
+ cb = (long)*input++;
+ *bptr++ = yuv_to_rgb( y0, cr, cb );
+ *bptr++ = yuv_to_rgb( y1, cr, cb );
+ *bptr++ = yuv_to_rgb( ((y0*3)+y2)/4, cr, cb );
+ *bptr++ = yuv_to_rgb( ((y1*3)+y3)/4, cr, cb );
+ *bptr++ = yuv_to_rgb( (y0+(y2*3))/4, cr, cb );
+ *bptr++ = yuv_to_rgb( (y1+(y3*3))/4, cr, cb );
+ *bptr++ = yuv_to_rgb( y2, cr, cb );
+ *bptr++ = yuv_to_rgb( y3, cr, cb );
+ }
+
+ cptr = (unsigned short *)vq4;
+ dptr = (unsigned short *)vq8;
+
+ for(i=0;i<four;i++) {
+ aptr = (unsigned short *)vq2 + (*input++)*8;
+ bptr = (unsigned short *)vq2 + (*input++)*8;
+ for(j=0;j<2;j++) {
+ VQ2TO4(aptr,bptr,cptr,dptr);
+ VQ2TO4(aptr,bptr,cptr,dptr);
+ }
+ }
+ } else if (cinTable[currentHandle].samplesPerPixel==4) {
+ ibptr = (unsigned int *)bptr;
+ for(i=0;i<two;i++) {
+ y0 = (long)*input++;
+ y1 = (long)*input++;
+ y2 = (long)*input++;
+ y3 = (long)*input++;
+ cr = (long)*input++;
+ cb = (long)*input++;
+ *ibptr++ = yuv_to_rgb24( y0, cr, cb );
+ *ibptr++ = yuv_to_rgb24( y1, cr, cb );
+ *ibptr++ = yuv_to_rgb24( ((y0*3)+y2)/4, cr, cb );
+ *ibptr++ = yuv_to_rgb24( ((y1*3)+y3)/4, cr, cb );
+ *ibptr++ = yuv_to_rgb24( (y0+(y2*3))/4, cr, cb );
+ *ibptr++ = yuv_to_rgb24( (y1+(y3*3))/4, cr, cb );
+ *ibptr++ = yuv_to_rgb24( y2, cr, cb );
+ *ibptr++ = yuv_to_rgb24( y3, cr, cb );
+ }
+
+ icptr = (unsigned int *)vq4;
+ idptr = (unsigned int *)vq8;
+
+ for(i=0;i<four;i++) {
+ iaptr = (unsigned int *)vq2 + (*input++)*8;
+ ibptr = (unsigned int *)vq2 + (*input++)*8;
+ for(j=0;j<2;j++) {
+ VQ2TO4(iaptr, ibptr, icptr, idptr);
+ VQ2TO4(iaptr, ibptr, icptr, idptr);
+ }
+ }
+ } else if (cinTable[currentHandle].samplesPerPixel==1) {
+ bbptr = (byte *)bptr;
+ for(i=0;i<two;i++) {
+ y0 = (long)*input++;
+ y1 = (long)*input++;
+ y2 = (long)*input++;
+ y3 = (long)*input; input+= 3;
+ *bbptr++ = cinTable[currentHandle].gray[y0];
+ *bbptr++ = cinTable[currentHandle].gray[y1];
+ *bbptr++ = cinTable[currentHandle].gray[((y0*3)+y2)/4];
+ *bbptr++ = cinTable[currentHandle].gray[((y1*3)+y3)/4];
+ *bbptr++ = cinTable[currentHandle].gray[(y0+(y2*3))/4];
+ *bbptr++ = cinTable[currentHandle].gray[(y1+(y3*3))/4];
+ *bbptr++ = cinTable[currentHandle].gray[y2];
+ *bbptr++ = cinTable[currentHandle].gray[y3];
+ }
+
+ bcptr = (byte *)vq4;
+ bdptr = (byte *)vq8;
+
+ for(i=0;i<four;i++) {
+ baptr = (byte *)vq2 + (*input++)*8;
+ bbptr = (byte *)vq2 + (*input++)*8;
+ for(j=0;j<2;j++) {
+ VQ2TO4(baptr,bbptr,bcptr,bdptr);
+ VQ2TO4(baptr,bbptr,bcptr,bdptr);
+ }
+ }
+ }
+ }
+ } else {
+//
+// 1/4 screen
+//
+ if (cinTable[currentHandle].samplesPerPixel==2) {
+ for(i=0;i<two;i++) {
+ y0 = (long)*input; input+=2;
+ y2 = (long)*input; input+=2;
+ cr = (long)*input++;
+ cb = (long)*input++;
+ *bptr++ = yuv_to_rgb( y0, cr, cb );
+ *bptr++ = yuv_to_rgb( y2, cr, cb );
+ }
+
+ cptr = (unsigned short *)vq4;
+ dptr = (unsigned short *)vq8;
+
+ for(i=0;i<four;i++) {
+ aptr = (unsigned short *)vq2 + (*input++)*2;
+ bptr = (unsigned short *)vq2 + (*input++)*2;
+ for(j=0;j<2;j++) {
+ VQ2TO2(aptr,bptr,cptr,dptr);
+ }
+ }
+ } else if (cinTable[currentHandle].samplesPerPixel == 1) {
+ bbptr = (byte *)bptr;
+
+ for(i=0;i<two;i++) {
+ *bbptr++ = cinTable[currentHandle].gray[*input]; input+=2;
+ *bbptr++ = cinTable[currentHandle].gray[*input]; input+=4;
+ }
+
+ bcptr = (byte *)vq4;
+ bdptr = (byte *)vq8;
+
+ for(i=0;i<four;i++) {
+ baptr = (byte *)vq2 + (*input++)*2;
+ bbptr = (byte *)vq2 + (*input++)*2;
+ for(j=0;j<2;j++) {
+ VQ2TO2(baptr,bbptr,bcptr,bdptr);
+ }
+ }
+ } else if (cinTable[currentHandle].samplesPerPixel == 4) {
+ ibptr = (unsigned int *) bptr;
+ for(i=0;i<two;i++) {
+ y0 = (long)*input; input+=2;
+ y2 = (long)*input; input+=2;
+ cr = (long)*input++;
+ cb = (long)*input++;
+ *ibptr++ = yuv_to_rgb24( y0, cr, cb );
+ *ibptr++ = yuv_to_rgb24( y2, cr, cb );
+ }
+
+ icptr = (unsigned int *)vq4;
+ idptr = (unsigned int *)vq8;
+
+ for(i=0;i<four;i++) {
+ iaptr = (unsigned int *)vq2 + (*input++)*2;
+ ibptr = (unsigned int *)vq2 + (*input++)*2;
+ for(j=0;j<2;j++) {
+ VQ2TO2(iaptr,ibptr,icptr,idptr);
+ }
+ }
+ }
+ }
+}
+
+/******************************************************************************
+*
+* Function:
+*
+* Description:
+*
+******************************************************************************/
+
+static void recurseQuad( long startX, long startY, long quadSize, long xOff, long yOff )
+{
+ byte *scroff;
+ long bigx, bigy, lowx, lowy, useY;
+ long offset;
+
+ offset = cinTable[currentHandle].screenDelta;
+
+ lowx = lowy = 0;
+ bigx = cinTable[currentHandle].xsize;
+ bigy = cinTable[currentHandle].ysize;
+
+ if (bigx > cinTable[currentHandle].CIN_WIDTH) bigx = cinTable[currentHandle].CIN_WIDTH;
+ if (bigy > cinTable[currentHandle].CIN_HEIGHT) bigy = cinTable[currentHandle].CIN_HEIGHT;
+
+ if ( (startX >= lowx) && (startX+quadSize) <= (bigx) && (startY+quadSize) <= (bigy) && (startY >= lowy) && quadSize <= MAXSIZE) {
+ useY = startY;
+ scroff = cin.linbuf + (useY+((cinTable[currentHandle].CIN_HEIGHT-bigy)>>1)+yOff)*(cinTable[currentHandle].samplesPerLine) + (((startX+xOff))*cinTable[currentHandle].samplesPerPixel);
+
+ cin.qStatus[0][cinTable[currentHandle].onQuad ] = scroff;
+ cin.qStatus[1][cinTable[currentHandle].onQuad++] = scroff+offset;
+ }
+
+ if ( quadSize != MINSIZE ) {
+ quadSize >>= 1;
+ recurseQuad( startX, startY , quadSize, xOff, yOff );
+ recurseQuad( startX+quadSize, startY , quadSize, xOff, yOff );
+ recurseQuad( startX, startY+quadSize , quadSize, xOff, yOff );
+ recurseQuad( startX+quadSize, startY+quadSize , quadSize, xOff, yOff );
+ }
+}
+
+
+/******************************************************************************
+*
+* Function:
+*
+* Description:
+*
+******************************************************************************/
+
+static void setupQuad( long xOff, long yOff )
+{
+ long numQuadCels, i,x,y;
+ byte *temp;
+
+ if (xOff == cin.oldXOff && yOff == cin.oldYOff && cinTable[currentHandle].ysize == cin.oldysize && cinTable[currentHandle].xsize == cin.oldxsize) {
+ return;
+ }
+
+ cin.oldXOff = xOff;
+ cin.oldYOff = yOff;
+ cin.oldysize = cinTable[currentHandle].ysize;
+ cin.oldxsize = cinTable[currentHandle].xsize;
+
+ numQuadCels = (cinTable[currentHandle].CIN_WIDTH*cinTable[currentHandle].CIN_HEIGHT) / (16);
+ numQuadCels += numQuadCels/4 + numQuadCels/16;
+ numQuadCels += 64; // for overflow
+
+ numQuadCels = (cinTable[currentHandle].xsize*cinTable[currentHandle].ysize) / (16);
+ numQuadCels += numQuadCels/4;
+ numQuadCels += 64; // for overflow
+
+ cinTable[currentHandle].onQuad = 0;
+
+ for(y=0;y<(long)cinTable[currentHandle].ysize;y+=16)
+ for(x=0;x<(long)cinTable[currentHandle].xsize;x+=16)
+ recurseQuad( x, y, 16, xOff, yOff );
+
+ temp = NULL;
+
+ for(i=(numQuadCels-64);i<numQuadCels;i++) {
+ cin.qStatus[0][i] = temp; // eoq
+ cin.qStatus[1][i] = temp; // eoq
+ }
+}
+
+/******************************************************************************
+*
+* Function:
+*
+* Description:
+*
+******************************************************************************/
+
+static void readQuadInfo( byte *qData )
+{
+ if (currentHandle < 0) return;
+
+ cinTable[currentHandle].xsize = qData[0]+qData[1]*256;
+ cinTable[currentHandle].ysize = qData[2]+qData[3]*256;
+ cinTable[currentHandle].maxsize = qData[4]+qData[5]*256;
+ cinTable[currentHandle].minsize = qData[6]+qData[7]*256;
+
+ cinTable[currentHandle].CIN_HEIGHT = cinTable[currentHandle].ysize;
+ cinTable[currentHandle].CIN_WIDTH = cinTable[currentHandle].xsize;
+
+ cinTable[currentHandle].samplesPerLine = cinTable[currentHandle].CIN_WIDTH*cinTable[currentHandle].samplesPerPixel;
+ cinTable[currentHandle].screenDelta = cinTable[currentHandle].CIN_HEIGHT*cinTable[currentHandle].samplesPerLine;
+
+ cinTable[currentHandle].half = qfalse;
+ cinTable[currentHandle].smootheddouble = qfalse;
+
+ cinTable[currentHandle].VQ0 = cinTable[currentHandle].VQNormal;
+ cinTable[currentHandle].VQ1 = cinTable[currentHandle].VQBuffer;
+
+ cinTable[currentHandle].t[0] = (0 - (unsigned int)cin.linbuf)+(unsigned int)cin.linbuf+cinTable[currentHandle].screenDelta;
+ cinTable[currentHandle].t[1] = (0 - ((unsigned int)cin.linbuf + cinTable[currentHandle].screenDelta))+(unsigned int)cin.linbuf;
+
+ cinTable[currentHandle].drawX = cinTable[currentHandle].CIN_WIDTH;
+ cinTable[currentHandle].drawY = cinTable[currentHandle].CIN_HEIGHT;
+
+ // rage pro is very slow at 512 wide textures, voodoo can't do it at all
+ if ( glConfig.hardwareType == GLHW_RAGEPRO || glConfig.maxTextureSize <= 256) {
+ if (cinTable[currentHandle].drawX>256) {
+ cinTable[currentHandle].drawX = 256;
+ }
+ if (cinTable[currentHandle].drawY>256) {
+ cinTable[currentHandle].drawY = 256;
+ }
+ if (cinTable[currentHandle].CIN_WIDTH != 256 || cinTable[currentHandle].CIN_HEIGHT != 256) {
+ Com_Printf("HACK: approxmimating cinematic for Rage Pro or Voodoo\n");
+ }
+ }
+#if defined(MACOS_X)
+ cinTable[currentHandle].drawX = 256;
+ cinTable[currentHandle].drawX = 256;
+#endif
+}
+
+/******************************************************************************
+*
+* Function:
+*
+* Description:
+*
+******************************************************************************/
+
+static void RoQPrepMcomp( long xoff, long yoff )
+{
+ long i, j, x, y, temp, temp2;
+
+ i=cinTable[currentHandle].samplesPerLine; j=cinTable[currentHandle].samplesPerPixel;
+ if ( cinTable[currentHandle].xsize == (cinTable[currentHandle].ysize*4) && !cinTable[currentHandle].half ) { j = j+j; i = i+i; }
+
+ for(y=0;y<16;y++) {
+ temp2 = (y+yoff-8)*i;
+ for(x=0;x<16;x++) {
+ temp = (x+xoff-8)*j;
+ cin.mcomp[(x*16)+y] = cinTable[currentHandle].normalBuffer0-(temp2+temp);
+ }
+ }
+}
+
+/******************************************************************************
+*
+* Function:
+*
+* Description:
+*
+******************************************************************************/
+
+static void initRoQ()
+{
+ if (currentHandle < 0) return;
+
+ cinTable[currentHandle].VQNormal = (void (*)(byte *, void *))blitVQQuad32fs;
+ cinTable[currentHandle].VQBuffer = (void (*)(byte *, void *))blitVQQuad32fs;
+ cinTable[currentHandle].samplesPerPixel = 4;
+ ROQ_GenYUVTables();
+ RllSetupTable();
+}
+
+/******************************************************************************
+*
+* Function:
+*
+* Description:
+*
+******************************************************************************/
+/*
+static byte* RoQFetchInterlaced( byte *source ) {
+ int x, *src, *dst;
+
+ if (currentHandle < 0) return NULL;
+
+ src = (int *)source;
+ dst = (int *)cinTable[currentHandle].buf2;
+
+ for(x=0;x<256*256;x++) {
+ *dst = *src;
+ dst++; src += 2;
+ }
+ return cinTable[currentHandle].buf2;
+}
+*/
+static void RoQReset() {
+
+ if (currentHandle < 0) return;
+
+ Sys_EndStreamedFile(cinTable[currentHandle].iFile);
+ FS_FCloseFile( cinTable[currentHandle].iFile );
+ FS_FOpenFileRead (cinTable[currentHandle].fileName, &cinTable[currentHandle].iFile, qtrue);
+ // let the background thread start reading ahead
+ Sys_BeginStreamedFile( cinTable[currentHandle].iFile, 0x10000 );
+ Sys_StreamedRead (cin.file, 16, 1, cinTable[currentHandle].iFile);
+ RoQ_init();
+ cinTable[currentHandle].status = FMV_LOOPED;
+}
+
+/******************************************************************************
+*
+* Function:
+*
+* Description:
+*
+******************************************************************************/
+
+static void RoQInterrupt(void)
+{
+ byte *framedata;
+ short sbuf[32768];
+ int ssize;
+
+ if (currentHandle < 0) return;
+
+ Sys_StreamedRead( cin.file, cinTable[currentHandle].RoQFrameSize+8, 1, cinTable[currentHandle].iFile );
+ if ( cinTable[currentHandle].RoQPlayed >= cinTable[currentHandle].ROQSize ) {
+ if (cinTable[currentHandle].holdAtEnd==qfalse) {
+ if (cinTable[currentHandle].looping) {
+ RoQReset();
+ } else {
+ cinTable[currentHandle].status = FMV_EOF;
+ }
+ } else {
+ cinTable[currentHandle].status = FMV_IDLE;
+ }
+ return;
+ }
+
+ framedata = cin.file;
+//
+// new frame is ready
+//
+redump:
+ switch(cinTable[currentHandle].roq_id)
+ {
+ case ROQ_QUAD_VQ:
+ if ((cinTable[currentHandle].numQuads&1)) {
+ cinTable[currentHandle].normalBuffer0 = cinTable[currentHandle].t[1];
+ RoQPrepMcomp( cinTable[currentHandle].roqF0, cinTable[currentHandle].roqF1 );
+ cinTable[currentHandle].VQ1( (byte *)cin.qStatus[1], framedata);
+ cinTable[currentHandle].buf = cin.linbuf + cinTable[currentHandle].screenDelta;
+ } else {
+ cinTable[currentHandle].normalBuffer0 = cinTable[currentHandle].t[0];
+ RoQPrepMcomp( cinTable[currentHandle].roqF0, cinTable[currentHandle].roqF1 );
+ cinTable[currentHandle].VQ0( (byte *)cin.qStatus[0], framedata );
+ cinTable[currentHandle].buf = cin.linbuf;
+ }
+ if (cinTable[currentHandle].numQuads == 0) { // first frame
+ Com_Memcpy(cin.linbuf+cinTable[currentHandle].screenDelta, cin.linbuf, cinTable[currentHandle].samplesPerLine*cinTable[currentHandle].ysize);
+ }
+ cinTable[currentHandle].numQuads++;
+ cinTable[currentHandle].dirty = qtrue;
+ break;
+ case ROQ_CODEBOOK:
+ decodeCodeBook( framedata, (unsigned short)cinTable[currentHandle].roq_flags );
+ break;
+ case ZA_SOUND_MONO:
+ if (!cinTable[currentHandle].silent) {
+ ssize = RllDecodeMonoToStereo( framedata, sbuf, cinTable[currentHandle].RoQFrameSize, 0, (unsigned short)cinTable[currentHandle].roq_flags);
+ S_RawSamples( ssize, 22050, 2, 1, (byte *)sbuf, 1.0f );
+ }
+ break;
+ case ZA_SOUND_STEREO:
+ if (!cinTable[currentHandle].silent) {
+ if (cinTable[currentHandle].numQuads == -1) {
+ S_Update();
+ s_rawend = s_soundtime;
+ }
+ ssize = RllDecodeStereoToStereo( framedata, sbuf, cinTable[currentHandle].RoQFrameSize, 0, (unsigned short)cinTable[currentHandle].roq_flags);
+ S_RawSamples( ssize, 22050, 2, 2, (byte *)sbuf, 1.0f );
+ }
+ break;
+ case ROQ_QUAD_INFO:
+ if (cinTable[currentHandle].numQuads == -1) {
+ readQuadInfo( framedata );
+ setupQuad( 0, 0 );
+ // we need to use CL_ScaledMilliseconds because of the smp mode calls from the renderer
+ cinTable[currentHandle].startTime = cinTable[currentHandle].lastTime = CL_ScaledMilliseconds()*com_timescale->value;
+ }
+ if (cinTable[currentHandle].numQuads != 1) cinTable[currentHandle].numQuads = 0;
+ break;
+ case ROQ_PACKET:
+ cinTable[currentHandle].inMemory = cinTable[currentHandle].roq_flags;
+ cinTable[currentHandle].RoQFrameSize = 0; // for header
+ break;
+ case ROQ_QUAD_HANG:
+ cinTable[currentHandle].RoQFrameSize = 0;
+ break;
+ case ROQ_QUAD_JPEG:
+ break;
+ default:
+ cinTable[currentHandle].status = FMV_EOF;
+ break;
+ }
+//
+// read in next frame data
+//
+ if ( cinTable[currentHandle].RoQPlayed >= cinTable[currentHandle].ROQSize ) {
+ if (cinTable[currentHandle].holdAtEnd==qfalse) {
+ if (cinTable[currentHandle].looping) {
+ RoQReset();
+ } else {
+ cinTable[currentHandle].status = FMV_EOF;
+ }
+ } else {
+ cinTable[currentHandle].status = FMV_IDLE;
+ }
+ return;
+ }
+
+ framedata += cinTable[currentHandle].RoQFrameSize;
+ cinTable[currentHandle].roq_id = framedata[0] + framedata[1]*256;
+ cinTable[currentHandle].RoQFrameSize = framedata[2] + framedata[3]*256 + framedata[4]*65536;
+ cinTable[currentHandle].roq_flags = framedata[6] + framedata[7]*256;
+ cinTable[currentHandle].roqF0 = (char)framedata[7];
+ cinTable[currentHandle].roqF1 = (char)framedata[6];
+
+ if (cinTable[currentHandle].RoQFrameSize>65536||cinTable[currentHandle].roq_id==0x1084) {
+ Com_DPrintf("roq_size>65536||roq_id==0x1084\n");
+ cinTable[currentHandle].status = FMV_EOF;
+ if (cinTable[currentHandle].looping) {
+ RoQReset();
+ }
+ return;
+ }
+ if (cinTable[currentHandle].inMemory && (cinTable[currentHandle].status != FMV_EOF)) { cinTable[currentHandle].inMemory--; framedata += 8; goto redump; }
+//
+// one more frame hits the dust
+//
+// assert(cinTable[currentHandle].RoQFrameSize <= 65536);
+// r = Sys_StreamedRead( cin.file, cinTable[currentHandle].RoQFrameSize+8, 1, cinTable[currentHandle].iFile );
+ cinTable[currentHandle].RoQPlayed += cinTable[currentHandle].RoQFrameSize+8;
+}
+
+/******************************************************************************
+*
+* Function:
+*
+* Description:
+*
+******************************************************************************/
+
+static void RoQ_init( void )
+{
+ // we need to use CL_ScaledMilliseconds because of the smp mode calls from the renderer
+ cinTable[currentHandle].startTime = cinTable[currentHandle].lastTime = CL_ScaledMilliseconds()*com_timescale->value;
+
+ cinTable[currentHandle].RoQPlayed = 24;
+
+/* get frame rate */
+ cinTable[currentHandle].roqFPS = cin.file[ 6] + cin.file[ 7]*256;
+
+ if (!cinTable[currentHandle].roqFPS) cinTable[currentHandle].roqFPS = 30;
+
+ cinTable[currentHandle].numQuads = -1;
+
+ cinTable[currentHandle].roq_id = cin.file[ 8] + cin.file[ 9]*256;
+ cinTable[currentHandle].RoQFrameSize = cin.file[10] + cin.file[11]*256 + cin.file[12]*65536;
+ cinTable[currentHandle].roq_flags = cin.file[14] + cin.file[15]*256;
+
+ if (cinTable[currentHandle].RoQFrameSize > 65536 || !cinTable[currentHandle].RoQFrameSize) {
+ return;
+ }
+
+}
+
+/******************************************************************************
+*
+* Function:
+*
+* Description:
+*
+******************************************************************************/
+
+static void RoQShutdown( void ) {
+ const char *s;
+
+ if (!cinTable[currentHandle].buf) {
+ return;
+ }
+
+ if ( cinTable[currentHandle].status == FMV_IDLE ) {
+ return;
+ }
+ Com_DPrintf("finished cinematic\n");
+ cinTable[currentHandle].status = FMV_IDLE;
+
+ if (cinTable[currentHandle].iFile) {
+ Sys_EndStreamedFile( cinTable[currentHandle].iFile );
+ FS_FCloseFile( cinTable[currentHandle].iFile );
+ cinTable[currentHandle].iFile = 0;
+ }
+
+ if (cinTable[currentHandle].alterGameState) {
+ cls.state = CA_DISCONNECTED;
+ // we can't just do a vstr nextmap, because
+ // if we are aborting the intro cinematic with
+ // a devmap command, nextmap would be valid by
+ // the time it was referenced
+ s = Cvar_VariableString( "nextmap" );
+ if ( s[0] ) {
+ Cbuf_ExecuteText( EXEC_APPEND, va("%s\n", s) );
+ Cvar_Set( "nextmap", "" );
+ }
+ CL_handle = -1;
+ }
+ cinTable[currentHandle].fileName[0] = 0;
+ currentHandle = -1;
+}
+
+/*
+==================
+SCR_StopCinematic
+==================
+*/
+e_status CIN_StopCinematic(int handle) {
+
+ if (handle < 0 || handle>= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) return FMV_EOF;
+ currentHandle = handle;
+
+ Com_DPrintf("trFMV::stop(), closing %s\n", cinTable[currentHandle].fileName);
+
+ if (!cinTable[currentHandle].buf) {
+ return FMV_EOF;
+ }
+
+ if (cinTable[currentHandle].alterGameState) {
+ if ( cls.state != CA_CINEMATIC ) {
+ return cinTable[currentHandle].status;
+ }
+ }
+ cinTable[currentHandle].status = FMV_EOF;
+ RoQShutdown();
+
+ return FMV_EOF;
+}
+
+/*
+==================
+SCR_RunCinematic
+
+Fetch and decompress the pending frame
+==================
+*/
+
+
+e_status CIN_RunCinematic (int handle)
+{
+ // bk001204 - init
+ int start = 0;
+ int thisTime = 0;
+
+ if (handle < 0 || handle>= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) return FMV_EOF;
+
+ if (cin.currentHandle != handle) {
+ currentHandle = handle;
+ cin.currentHandle = currentHandle;
+ cinTable[currentHandle].status = FMV_EOF;
+ RoQReset();
+ }
+
+ if (cinTable[handle].playonwalls < -1)
+ {
+ return cinTable[handle].status;
+ }
+
+ currentHandle = handle;
+
+ if (cinTable[currentHandle].alterGameState) {
+ if ( cls.state != CA_CINEMATIC ) {
+ return cinTable[currentHandle].status;
+ }
+ }
+
+ if (cinTable[currentHandle].status == FMV_IDLE) {
+ return cinTable[currentHandle].status;
+ }
+
+ // we need to use CL_ScaledMilliseconds because of the smp mode calls from the renderer
+ thisTime = CL_ScaledMilliseconds()*com_timescale->value;
+ if (cinTable[currentHandle].shader && (abs(thisTime - cinTable[currentHandle].lastTime))>100) {
+ cinTable[currentHandle].startTime += thisTime - cinTable[currentHandle].lastTime;
+ }
+ // we need to use CL_ScaledMilliseconds because of the smp mode calls from the renderer
+ cinTable[currentHandle].tfps = ((((CL_ScaledMilliseconds()*com_timescale->value) - cinTable[currentHandle].startTime)*3)/100);
+
+ start = cinTable[currentHandle].startTime;
+ while( (cinTable[currentHandle].tfps != cinTable[currentHandle].numQuads)
+ && (cinTable[currentHandle].status == FMV_PLAY) )
+ {
+ RoQInterrupt();
+ if (start != cinTable[currentHandle].startTime) {
+ // we need to use CL_ScaledMilliseconds because of the smp mode calls from the renderer
+ cinTable[currentHandle].tfps = ((((CL_ScaledMilliseconds()*com_timescale->value)
+ - cinTable[currentHandle].startTime)*3)/100);
+ start = cinTable[currentHandle].startTime;
+ }
+ }
+
+ cinTable[currentHandle].lastTime = thisTime;
+
+ if (cinTable[currentHandle].status == FMV_LOOPED) {
+ cinTable[currentHandle].status = FMV_PLAY;
+ }
+
+ if (cinTable[currentHandle].status == FMV_EOF) {
+ if (cinTable[currentHandle].looping) {
+ RoQReset();
+ } else {
+ RoQShutdown();
+ }
+ }
+
+ return cinTable[currentHandle].status;
+}
+
+/*
+==================
+CL_PlayCinematic
+
+==================
+*/
+int CIN_PlayCinematic( const char *arg, int x, int y, int w, int h, int systemBits ) {
+ unsigned short RoQID;
+ char name[MAX_OSPATH];
+ int i;
+
+ if (strstr(arg, "/") == NULL && strstr(arg, "\\") == NULL) {
+ Com_sprintf (name, sizeof(name), "video/%s", arg);
+ } else {
+ Com_sprintf (name, sizeof(name), "%s", arg);
+ }
+
+ if (!(systemBits & CIN_system)) {
+ for ( i = 0 ; i < MAX_VIDEO_HANDLES ; i++ ) {
+ if (!strcmp(cinTable[i].fileName, name) ) {
+ return i;
+ }
+ }
+ }
+
+ Com_DPrintf("SCR_PlayCinematic( %s )\n", arg);
+
+ Com_Memset(&cin, 0, sizeof(cinematics_t) );
+ currentHandle = CIN_HandleForVideo();
+
+ cin.currentHandle = currentHandle;
+
+ strcpy(cinTable[currentHandle].fileName, name);
+
+ cinTable[currentHandle].ROQSize = 0;
+ cinTable[currentHandle].ROQSize = FS_FOpenFileRead (cinTable[currentHandle].fileName, &cinTable[currentHandle].iFile, qtrue);
+
+ if (cinTable[currentHandle].ROQSize<=0) {
+ Com_DPrintf("play(%s), ROQSize<=0\n", arg);
+ cinTable[currentHandle].fileName[0] = 0;
+ return -1;
+ }
+
+ CIN_SetExtents(currentHandle, x, y, w, h);
+ CIN_SetLooping(currentHandle, (systemBits & CIN_loop)!=0);
+
+ cinTable[currentHandle].CIN_HEIGHT = DEFAULT_CIN_HEIGHT;
+ cinTable[currentHandle].CIN_WIDTH = DEFAULT_CIN_WIDTH;
+ cinTable[currentHandle].holdAtEnd = (systemBits & CIN_hold) != 0;
+ cinTable[currentHandle].alterGameState = (systemBits & CIN_system) != 0;
+ cinTable[currentHandle].playonwalls = 1;
+ cinTable[currentHandle].silent = (systemBits & CIN_silent) != 0;
+ cinTable[currentHandle].shader = (systemBits & CIN_shader) != 0;
+
+ if (cinTable[currentHandle].alterGameState) {
+ // close the menu
+ if ( uivm ) {
+ VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_NONE );
+ }
+ } else {
+ cinTable[currentHandle].playonwalls = cl_inGameVideo->integer;
+ }
+
+ initRoQ();
+
+ FS_Read (cin.file, 16, cinTable[currentHandle].iFile);
+
+ RoQID = (unsigned short)(cin.file[0]) + (unsigned short)(cin.file[1])*256;
+ if (RoQID == 0x1084)
+ {
+ RoQ_init();
+// FS_Read (cin.file, cinTable[currentHandle].RoQFrameSize+8, cinTable[currentHandle].iFile);
+ // let the background thread start reading ahead
+ Sys_BeginStreamedFile( cinTable[currentHandle].iFile, 0x10000 );
+
+ cinTable[currentHandle].status = FMV_PLAY;
+ Com_DPrintf("trFMV::play(), playing %s\n", arg);
+
+ if (cinTable[currentHandle].alterGameState) {
+ cls.state = CA_CINEMATIC;
+ }
+
+ Con_Close();
+
+ s_rawend = s_soundtime;
+
+ return currentHandle;
+ }
+ Com_DPrintf("trFMV::play(), invalid RoQ ID\n");
+
+ RoQShutdown();
+ return -1;
+}
+
+void CIN_SetExtents (int handle, int x, int y, int w, int h) {
+ if (handle < 0 || handle>= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) return;
+ cinTable[handle].xpos = x;
+ cinTable[handle].ypos = y;
+ cinTable[handle].width = w;
+ cinTable[handle].height = h;
+ cinTable[handle].dirty = qtrue;
+}
+
+void CIN_SetLooping(int handle, qboolean loop) {
+ if (handle < 0 || handle>= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) return;
+ cinTable[handle].looping = loop;
+}
+
+/*
+==================
+SCR_DrawCinematic
+
+==================
+*/
+void CIN_DrawCinematic (int handle) {
+ float x, y, w, h;
+ byte *buf;
+
+ if (handle < 0 || handle>= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) return;
+
+ if (!cinTable[handle].buf) {
+ return;
+ }
+
+ x = cinTable[handle].xpos;
+ y = cinTable[handle].ypos;
+ w = cinTable[handle].width;
+ h = cinTable[handle].height;
+ buf = cinTable[handle].buf;
+ SCR_AdjustFrom640( &x, &y, &w, &h );
+
+ if (cinTable[handle].dirty && (cinTable[handle].CIN_WIDTH != cinTable[handle].drawX || cinTable[handle].CIN_HEIGHT != cinTable[handle].drawY)) {
+ int ix, iy, *buf2, *buf3, xm, ym, ll;
+
+ xm = cinTable[handle].CIN_WIDTH/256;
+ ym = cinTable[handle].CIN_HEIGHT/256;
+ ll = 8;
+ if (cinTable[handle].CIN_WIDTH==512) {
+ ll = 9;
+ }
+
+ buf3 = (int*)buf;
+ buf2 = Hunk_AllocateTempMemory( 256*256*4 );
+ if (xm==2 && ym==2) {
+ byte *bc2, *bc3;
+ int ic, iiy;
+
+ bc2 = (byte *)buf2;
+ bc3 = (byte *)buf3;
+ for (iy = 0; iy<256; iy++) {
+ iiy = iy<<12;
+ for (ix = 0; ix<2048; ix+=8) {
+ for(ic = ix;ic<(ix+4);ic++) {
+ *bc2=(bc3[iiy+ic]+bc3[iiy+4+ic]+bc3[iiy+2048+ic]+bc3[iiy+2048+4+ic])>>2;
+ bc2++;
+ }
+ }
+ }
+ } else if (xm==2 && ym==1) {
+ byte *bc2, *bc3;
+ int ic, iiy;
+
+ bc2 = (byte *)buf2;
+ bc3 = (byte *)buf3;
+ for (iy = 0; iy<256; iy++) {
+ iiy = iy<<11;
+ for (ix = 0; ix<2048; ix+=8) {
+ for(ic = ix;ic<(ix+4);ic++) {
+ *bc2=(bc3[iiy+ic]+bc3[iiy+4+ic])>>1;
+ bc2++;
+ }
+ }
+ }
+ } else {
+ for (iy = 0; iy<256; iy++) {
+ for (ix = 0; ix<256; ix++) {
+ buf2[(iy<<8)+ix] = buf3[((iy*ym)<<ll) + (ix*xm)];
+ }
+ }
+ }
+ re.DrawStretchRaw( x, y, w, h, 256, 256, (byte *)buf2, handle, qtrue);
+ cinTable[handle].dirty = qfalse;
+ Hunk_FreeTempMemory(buf2);
+ return;
+ }
+
+ re.DrawStretchRaw( x, y, w, h, cinTable[handle].drawX, cinTable[handle].drawY, buf, handle, cinTable[handle].dirty);
+ cinTable[handle].dirty = qfalse;
+}
+
+void CL_PlayCinematic_f(void) {
+ char *arg, *s;
+ qboolean holdatend;
+ int bits = CIN_system;
+
+ Com_DPrintf("CL_PlayCinematic_f\n");
+ if (cls.state == CA_CINEMATIC) {
+ SCR_StopCinematic();
+ }
+
+ arg = Cmd_Argv( 1 );
+ s = Cmd_Argv(2);
+
+ holdatend = qfalse;
+ if ((s && s[0] == '1') || Q_stricmp(arg,"demoend.roq")==0 || Q_stricmp(arg,"end.roq")==0) {
+ bits |= CIN_hold;
+ }
+ if (s && s[0] == '2') {
+ bits |= CIN_loop;
+ }
+
+ S_StopAllSounds ();
+
+ CL_handle = CIN_PlayCinematic( arg, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, bits );
+ if (CL_handle >= 0) {
+ do {
+ SCR_RunCinematic();
+ } while (cinTable[currentHandle].buf == NULL && cinTable[currentHandle].status == FMV_PLAY); // wait for first frame (load codebook and sound)
+ }
+}
+
+
+void SCR_DrawCinematic (void) {
+ if (CL_handle >= 0 && CL_handle < MAX_VIDEO_HANDLES) {
+ CIN_DrawCinematic(CL_handle);
+ }
+}
+
+void SCR_RunCinematic (void)
+{
+ if (CL_handle >= 0 && CL_handle < MAX_VIDEO_HANDLES) {
+ CIN_RunCinematic(CL_handle);
+ }
+}
+
+void SCR_StopCinematic(void) {
+ if (CL_handle >= 0 && CL_handle < MAX_VIDEO_HANDLES) {
+ CIN_StopCinematic(CL_handle);
+ S_StopAllSounds ();
+ CL_handle = -1;
+ }
+}
+
+void CIN_UploadCinematic(int handle) {
+ if (handle >= 0 && handle < MAX_VIDEO_HANDLES) {
+ if (!cinTable[handle].buf) {
+ return;
+ }
+ if (cinTable[handle].playonwalls <= 0 && cinTable[handle].dirty) {
+ if (cinTable[handle].playonwalls == 0) {
+ cinTable[handle].playonwalls = -1;
+ } else {
+ if (cinTable[handle].playonwalls == -1) {
+ cinTable[handle].playonwalls = -2;
+ } else {
+ cinTable[handle].dirty = qfalse;
+ }
+ }
+ }
+ re.UploadCinematic( 256, 256, 256, 256, cinTable[handle].buf, handle, cinTable[handle].dirty);
+ if (cl_inGameVideo->integer == 0 && cinTable[handle].playonwalls == 1) {
+ cinTable[handle].playonwalls--;
+ }
+ }
+}
+
diff --git a/code/client/cl_console.c b/code/client/cl_console.c
new file mode 100755
index 0000000..50df0e2
--- /dev/null
+++ b/code/client/cl_console.c
@@ -0,0 +1,786 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// console.c
+
+#include "client.h"
+
+
+int g_console_field_width = 78;
+
+
+#define NUM_CON_TIMES 4
+
+#define CON_TEXTSIZE 32768
+typedef struct {
+ qboolean initialized;
+
+ short text[CON_TEXTSIZE];
+ int current; // line where next message will be printed
+ int x; // offset in current line for next print
+ int display; // bottom of console displays this line
+
+ int linewidth; // characters across screen
+ int totallines; // total lines in console scrollback
+
+ float xadjust; // for wide aspect screens
+
+ float displayFrac; // aproaches finalFrac at scr_conspeed
+ float finalFrac; // 0.0 to 1.0 lines of console to display
+
+ int vislines; // in scanlines
+
+ int times[NUM_CON_TIMES]; // cls.realtime time the line was generated
+ // for transparent notify lines
+ vec4_t color;
+} console_t;
+
+extern console_t con;
+
+console_t con;
+
+cvar_t *con_conspeed;
+cvar_t *con_notifytime;
+
+#define DEFAULT_CONSOLE_WIDTH 78
+
+vec4_t console_color = {1.0, 1.0, 1.0, 1.0};
+
+
+/*
+================
+Con_ToggleConsole_f
+================
+*/
+void Con_ToggleConsole_f (void) {
+ // closing a full screen console restarts the demo loop
+ if ( cls.state == CA_DISCONNECTED && cls.keyCatchers == KEYCATCH_CONSOLE ) {
+ CL_StartDemoLoop();
+ return;
+ }
+
+ Field_Clear( &g_consoleField );
+ g_consoleField.widthInChars = g_console_field_width;
+
+ Con_ClearNotify ();
+ cls.keyCatchers ^= KEYCATCH_CONSOLE;
+}
+
+/*
+================
+Con_MessageMode_f
+================
+*/
+void Con_MessageMode_f (void) {
+ chat_playerNum = -1;
+ chat_team = qfalse;
+ Field_Clear( &chatField );
+ chatField.widthInChars = 30;
+
+ cls.keyCatchers ^= KEYCATCH_MESSAGE;
+}
+
+/*
+================
+Con_MessageMode2_f
+================
+*/
+void Con_MessageMode2_f (void) {
+ chat_playerNum = -1;
+ chat_team = qtrue;
+ Field_Clear( &chatField );
+ chatField.widthInChars = 25;
+ cls.keyCatchers ^= KEYCATCH_MESSAGE;
+}
+
+/*
+================
+Con_MessageMode3_f
+================
+*/
+void Con_MessageMode3_f (void) {
+ chat_playerNum = VM_Call( cgvm, CG_CROSSHAIR_PLAYER );
+ if ( chat_playerNum < 0 || chat_playerNum >= MAX_CLIENTS ) {
+ chat_playerNum = -1;
+ return;
+ }
+ chat_team = qfalse;
+ Field_Clear( &chatField );
+ chatField.widthInChars = 30;
+ cls.keyCatchers ^= KEYCATCH_MESSAGE;
+}
+
+/*
+================
+Con_MessageMode4_f
+================
+*/
+void Con_MessageMode4_f (void) {
+ chat_playerNum = VM_Call( cgvm, CG_LAST_ATTACKER );
+ if ( chat_playerNum < 0 || chat_playerNum >= MAX_CLIENTS ) {
+ chat_playerNum = -1;
+ return;
+ }
+ chat_team = qfalse;
+ Field_Clear( &chatField );
+ chatField.widthInChars = 30;
+ cls.keyCatchers ^= KEYCATCH_MESSAGE;
+}
+
+/*
+================
+Con_Clear_f
+================
+*/
+void Con_Clear_f (void) {
+ int i;
+
+ for ( i = 0 ; i < CON_TEXTSIZE ; i++ ) {
+ con.text[i] = (ColorIndex(COLOR_WHITE)<<8) | ' ';
+ }
+
+ Con_Bottom(); // go to end
+}
+
+
+/*
+================
+Con_Dump_f
+
+Save the console contents out to a file
+================
+*/
+void Con_Dump_f (void)
+{
+ int l, x, i;
+ short *line;
+ fileHandle_t f;
+ char buffer[1024];
+
+ if (Cmd_Argc() != 2)
+ {
+ Com_Printf ("usage: condump <filename>\n");
+ return;
+ }
+
+ Com_Printf ("Dumped console text to %s.\n", Cmd_Argv(1) );
+
+ f = FS_FOpenFileWrite( Cmd_Argv( 1 ) );
+ if (!f)
+ {
+ Com_Printf ("ERROR: couldn't open.\n");
+ return;
+ }
+
+ // skip empty lines
+ for (l = con.current - con.totallines + 1 ; l <= con.current ; l++)
+ {
+ line = con.text + (l%con.totallines)*con.linewidth;
+ for (x=0 ; x<con.linewidth ; x++)
+ if ((line[x] & 0xff) != ' ')
+ break;
+ if (x != con.linewidth)
+ break;
+ }
+
+ // write the remaining lines
+ buffer[con.linewidth] = 0;
+ for ( ; l <= con.current ; l++)
+ {
+ line = con.text + (l%con.totallines)*con.linewidth;
+ for(i=0; i<con.linewidth; i++)
+ buffer[i] = line[i] & 0xff;
+ for (x=con.linewidth-1 ; x>=0 ; x--)
+ {
+ if (buffer[x] == ' ')
+ buffer[x] = 0;
+ else
+ break;
+ }
+ strcat( buffer, "\n" );
+ FS_Write(buffer, strlen(buffer), f);
+ }
+
+ FS_FCloseFile( f );
+}
+
+
+/*
+================
+Con_ClearNotify
+================
+*/
+void Con_ClearNotify( void ) {
+ int i;
+
+ for ( i = 0 ; i < NUM_CON_TIMES ; i++ ) {
+ con.times[i] = 0;
+ }
+}
+
+
+
+/*
+================
+Con_CheckResize
+
+If the line width has changed, reformat the buffer.
+================
+*/
+void Con_CheckResize (void)
+{
+ int i, j, width, oldwidth, oldtotallines, numlines, numchars;
+ MAC_STATIC short tbuf[CON_TEXTSIZE];
+
+ width = (SCREEN_WIDTH / SMALLCHAR_WIDTH) - 2;
+
+ if (width == con.linewidth)
+ return;
+
+ if (width < 1) // video hasn't been initialized yet
+ {
+ width = DEFAULT_CONSOLE_WIDTH;
+ con.linewidth = width;
+ con.totallines = CON_TEXTSIZE / con.linewidth;
+ for(i=0; i<CON_TEXTSIZE; i++)
+
+ con.text[i] = (ColorIndex(COLOR_WHITE)<<8) | ' ';
+ }
+ else
+ {
+ oldwidth = con.linewidth;
+ con.linewidth = width;
+ oldtotallines = con.totallines;
+ con.totallines = CON_TEXTSIZE / con.linewidth;
+ numlines = oldtotallines;
+
+ if (con.totallines < numlines)
+ numlines = con.totallines;
+
+ numchars = oldwidth;
+
+ if (con.linewidth < numchars)
+ numchars = con.linewidth;
+
+ Com_Memcpy (tbuf, con.text, CON_TEXTSIZE * sizeof(short));
+ for(i=0; i<CON_TEXTSIZE; i++)
+
+ con.text[i] = (ColorIndex(COLOR_WHITE)<<8) | ' ';
+
+
+ for (i=0 ; i<numlines ; i++)
+ {
+ for (j=0 ; j<numchars ; j++)
+ {
+ con.text[(con.totallines - 1 - i) * con.linewidth + j] =
+ tbuf[((con.current - i + oldtotallines) %
+ oldtotallines) * oldwidth + j];
+ }
+ }
+
+ Con_ClearNotify ();
+ }
+
+ con.current = con.totallines - 1;
+ con.display = con.current;
+}
+
+
+/*
+================
+Con_Init
+================
+*/
+void Con_Init (void) {
+ int i;
+
+ con_notifytime = Cvar_Get ("con_notifytime", "3", 0);
+ con_conspeed = Cvar_Get ("scr_conspeed", "3", 0);
+
+ Field_Clear( &g_consoleField );
+ g_consoleField.widthInChars = g_console_field_width;
+ for ( i = 0 ; i < COMMAND_HISTORY ; i++ ) {
+ Field_Clear( &historyEditLines[i] );
+ historyEditLines[i].widthInChars = g_console_field_width;
+ }
+
+ Cmd_AddCommand ("toggleconsole", Con_ToggleConsole_f);
+ Cmd_AddCommand ("messagemode", Con_MessageMode_f);
+ Cmd_AddCommand ("messagemode2", Con_MessageMode2_f);
+ Cmd_AddCommand ("messagemode3", Con_MessageMode3_f);
+ Cmd_AddCommand ("messagemode4", Con_MessageMode4_f);
+ Cmd_AddCommand ("clear", Con_Clear_f);
+ Cmd_AddCommand ("condump", Con_Dump_f);
+}
+
+
+/*
+===============
+Con_Linefeed
+===============
+*/
+void Con_Linefeed (qboolean skipnotify)
+{
+ int i;
+
+ // mark time for transparent overlay
+ if (con.current >= 0)
+ {
+ if (skipnotify)
+ con.times[con.current % NUM_CON_TIMES] = 0;
+ else
+ con.times[con.current % NUM_CON_TIMES] = cls.realtime;
+ }
+
+ con.x = 0;
+ if (con.display == con.current)
+ con.display++;
+ con.current++;
+ for(i=0; i<con.linewidth; i++)
+ con.text[(con.current%con.totallines)*con.linewidth+i] = (ColorIndex(COLOR_WHITE)<<8) | ' ';
+}
+
+/*
+================
+CL_ConsolePrint
+
+Handles cursor positioning, line wrapping, etc
+All console printing must go through this in order to be logged to disk
+If no console is visible, the text will appear at the top of the game window
+================
+*/
+void CL_ConsolePrint( char *txt ) {
+ int y;
+ int c, l;
+ int color;
+ qboolean skipnotify = qfalse; // NERVE - SMF
+ int prev; // NERVE - SMF
+
+ // TTimo - prefix for text that shows up in console but not in notify
+ // backported from RTCW
+ if ( !Q_strncmp( txt, "[skipnotify]", 12 ) ) {
+ skipnotify = qtrue;
+ txt += 12;
+ }
+
+ // for some demos we don't want to ever show anything on the console
+ if ( cl_noprint && cl_noprint->integer ) {
+ return;
+ }
+
+ if (!con.initialized) {
+ con.color[0] =
+ con.color[1] =
+ con.color[2] =
+ con.color[3] = 1.0f;
+ con.linewidth = -1;
+ Con_CheckResize ();
+ con.initialized = qtrue;
+ }
+
+ color = ColorIndex(COLOR_WHITE);
+
+ while ( (c = *txt) != 0 ) {
+ if ( Q_IsColorString( txt ) ) {
+ color = ColorIndex( *(txt+1) );
+ txt += 2;
+ continue;
+ }
+
+ // count word length
+ for (l=0 ; l< con.linewidth ; l++) {
+ if ( txt[l] <= ' ') {
+ break;
+ }
+
+ }
+
+ // word wrap
+ if (l != con.linewidth && (con.x + l >= con.linewidth) ) {
+ Con_Linefeed(skipnotify);
+
+ }
+
+ txt++;
+
+ switch (c)
+ {
+ case '\n':
+ Con_Linefeed (skipnotify);
+ break;
+ case '\r':
+ con.x = 0;
+ break;
+ default: // display character and advance
+ y = con.current % con.totallines;
+ con.text[y*con.linewidth+con.x] = (color << 8) | c;
+ con.x++;
+ if (con.x >= con.linewidth) {
+ Con_Linefeed(skipnotify);
+ con.x = 0;
+ }
+ break;
+ }
+ }
+
+
+ // mark time for transparent overlay
+ if (con.current >= 0) {
+ // NERVE - SMF
+ if ( skipnotify ) {
+ prev = con.current % NUM_CON_TIMES - 1;
+ if ( prev < 0 )
+ prev = NUM_CON_TIMES - 1;
+ con.times[prev] = 0;
+ }
+ else
+ // -NERVE - SMF
+ con.times[con.current % NUM_CON_TIMES] = cls.realtime;
+ }
+}
+
+
+/*
+==============================================================================
+
+DRAWING
+
+==============================================================================
+*/
+
+
+/*
+================
+Con_DrawInput
+
+Draw the editline after a ] prompt
+================
+*/
+void Con_DrawInput (void) {
+ int y;
+
+ if ( cls.state != CA_DISCONNECTED && !(cls.keyCatchers & KEYCATCH_CONSOLE ) ) {
+ return;
+ }
+
+ y = con.vislines - ( SMALLCHAR_HEIGHT * 2 );
+
+ re.SetColor( con.color );
+
+ SCR_DrawSmallChar( con.xadjust + 1 * SMALLCHAR_WIDTH, y, ']' );
+
+ Field_Draw( &g_consoleField, con.xadjust + 2 * SMALLCHAR_WIDTH, y,
+ SCREEN_WIDTH - 3 * SMALLCHAR_WIDTH, qtrue );
+}
+
+
+/*
+================
+Con_DrawNotify
+
+Draws the last few lines of output transparently over the game top
+================
+*/
+void Con_DrawNotify (void)
+{
+ int x, v;
+ short *text;
+ int i;
+ int time;
+ int skip;
+ int currentColor;
+
+ currentColor = 7;
+ re.SetColor( g_color_table[currentColor] );
+
+ v = 0;
+ for (i= con.current-NUM_CON_TIMES+1 ; i<=con.current ; i++)
+ {
+ if (i < 0)
+ continue;
+ time = con.times[i % NUM_CON_TIMES];
+ if (time == 0)
+ continue;
+ time = cls.realtime - time;
+ if (time > con_notifytime->value*1000)
+ continue;
+ text = con.text + (i % con.totallines)*con.linewidth;
+
+ if (cl.snap.ps.pm_type != PM_INTERMISSION && cls.keyCatchers & (KEYCATCH_UI | KEYCATCH_CGAME) ) {
+ continue;
+ }
+
+ for (x = 0 ; x < con.linewidth ; x++) {
+ if ( ( text[x] & 0xff ) == ' ' ) {
+ continue;
+ }
+ if ( ( (text[x]>>8)&7 ) != currentColor ) {
+ currentColor = (text[x]>>8)&7;
+ re.SetColor( g_color_table[currentColor] );
+ }
+ SCR_DrawSmallChar( cl_conXOffset->integer + con.xadjust + (x+1)*SMALLCHAR_WIDTH, v, text[x] & 0xff );
+ }
+
+ v += SMALLCHAR_HEIGHT;
+ }
+
+ re.SetColor( NULL );
+
+ if (cls.keyCatchers & (KEYCATCH_UI | KEYCATCH_CGAME) ) {
+ return;
+ }
+
+ // draw the chat line
+ if ( cls.keyCatchers & KEYCATCH_MESSAGE )
+ {
+ if (chat_team)
+ {
+ SCR_DrawBigString (8, v, "say_team:", 1.0f );
+ skip = 11;
+ }
+ else
+ {
+ SCR_DrawBigString (8, v, "say:", 1.0f );
+ skip = 5;
+ }
+
+ Field_BigDraw( &chatField, skip * BIGCHAR_WIDTH, v,
+ SCREEN_WIDTH - ( skip + 1 ) * BIGCHAR_WIDTH, qtrue );
+
+ v += BIGCHAR_HEIGHT;
+ }
+
+}
+
+/*
+================
+Con_DrawSolidConsole
+
+Draws the console with the solid background
+================
+*/
+void Con_DrawSolidConsole( float frac ) {
+ int i, x, y;
+ int rows;
+ short *text;
+ int row;
+ int lines;
+// qhandle_t conShader;
+ int currentColor;
+ vec4_t color;
+
+ lines = cls.glconfig.vidHeight * frac;
+ if (lines <= 0)
+ return;
+
+ if (lines > cls.glconfig.vidHeight )
+ lines = cls.glconfig.vidHeight;
+
+ // on wide screens, we will center the text
+ con.xadjust = 0;
+ SCR_AdjustFrom640( &con.xadjust, NULL, NULL, NULL );
+
+ // draw the background
+ y = frac * SCREEN_HEIGHT - 2;
+ if ( y < 1 ) {
+ y = 0;
+ }
+ else {
+ SCR_DrawPic( 0, 0, SCREEN_WIDTH, y, cls.consoleShader );
+ }
+
+ color[0] = 1;
+ color[1] = 0;
+ color[2] = 0;
+ color[3] = 1;
+ SCR_FillRect( 0, y, SCREEN_WIDTH, 2, color );
+
+
+ // draw the version number
+
+ re.SetColor( g_color_table[ColorIndex(COLOR_RED)] );
+
+ i = strlen( Q3_VERSION );
+
+ for (x=0 ; x<i ; x++) {
+
+ SCR_DrawSmallChar( cls.glconfig.vidWidth - ( i - x ) * SMALLCHAR_WIDTH,
+
+ (lines-(SMALLCHAR_HEIGHT+SMALLCHAR_HEIGHT/2)), Q3_VERSION[x] );
+
+ }
+
+
+ // draw the text
+ con.vislines = lines;
+ rows = (lines-SMALLCHAR_WIDTH)/SMALLCHAR_WIDTH; // rows of text to draw
+
+ y = lines - (SMALLCHAR_HEIGHT*3);
+
+ // draw from the bottom up
+ if (con.display != con.current)
+ {
+ // draw arrows to show the buffer is backscrolled
+ re.SetColor( g_color_table[ColorIndex(COLOR_RED)] );
+ for (x=0 ; x<con.linewidth ; x+=4)
+ SCR_DrawSmallChar( con.xadjust + (x+1)*SMALLCHAR_WIDTH, y, '^' );
+ y -= SMALLCHAR_HEIGHT;
+ rows--;
+ }
+
+ row = con.display;
+
+ if ( con.x == 0 ) {
+ row--;
+ }
+
+ currentColor = 7;
+ re.SetColor( g_color_table[currentColor] );
+
+ for (i=0 ; i<rows ; i++, y -= SMALLCHAR_HEIGHT, row--)
+ {
+ if (row < 0)
+ break;
+ if (con.current - row >= con.totallines) {
+ // past scrollback wrap point
+ continue;
+ }
+
+ text = con.text + (row % con.totallines)*con.linewidth;
+
+ for (x=0 ; x<con.linewidth ; x++) {
+ if ( ( text[x] & 0xff ) == ' ' ) {
+ continue;
+ }
+
+ if ( ( (text[x]>>8)&7 ) != currentColor ) {
+ currentColor = (text[x]>>8)&7;
+ re.SetColor( g_color_table[currentColor] );
+ }
+ SCR_DrawSmallChar( con.xadjust + (x+1)*SMALLCHAR_WIDTH, y, text[x] & 0xff );
+ }
+ }
+
+ // draw the input prompt, user text, and cursor if desired
+ Con_DrawInput ();
+
+ re.SetColor( NULL );
+}
+
+
+
+/*
+==================
+Con_DrawConsole
+==================
+*/
+void Con_DrawConsole( void ) {
+ // check for console width changes from a vid mode change
+ Con_CheckResize ();
+
+ // if disconnected, render console full screen
+ if ( cls.state == CA_DISCONNECTED ) {
+ if ( !( cls.keyCatchers & (KEYCATCH_UI | KEYCATCH_CGAME)) ) {
+ Con_DrawSolidConsole( 1.0 );
+ return;
+ }
+ }
+
+ if ( con.displayFrac ) {
+ Con_DrawSolidConsole( con.displayFrac );
+ } else {
+ // draw notify lines
+ if ( cls.state == CA_ACTIVE ) {
+ Con_DrawNotify ();
+ }
+ }
+}
+
+//================================================================
+
+/*
+==================
+Con_RunConsole
+
+Scroll it up or down
+==================
+*/
+void Con_RunConsole (void) {
+ // decide on the destination height of the console
+ if ( cls.keyCatchers & KEYCATCH_CONSOLE )
+ con.finalFrac = 0.5; // half screen
+ else
+ con.finalFrac = 0; // none visible
+
+ // scroll towards the destination height
+ if (con.finalFrac < con.displayFrac)
+ {
+ con.displayFrac -= con_conspeed->value*cls.realFrametime*0.001;
+ if (con.finalFrac > con.displayFrac)
+ con.displayFrac = con.finalFrac;
+
+ }
+ else if (con.finalFrac > con.displayFrac)
+ {
+ con.displayFrac += con_conspeed->value*cls.realFrametime*0.001;
+ if (con.finalFrac < con.displayFrac)
+ con.displayFrac = con.finalFrac;
+ }
+
+}
+
+
+void Con_PageUp( void ) {
+ con.display -= 2;
+ if ( con.current - con.display >= con.totallines ) {
+ con.display = con.current - con.totallines + 1;
+ }
+}
+
+void Con_PageDown( void ) {
+ con.display += 2;
+ if (con.display > con.current) {
+ con.display = con.current;
+ }
+}
+
+void Con_Top( void ) {
+ con.display = con.totallines;
+ if ( con.current - con.display >= con.totallines ) {
+ con.display = con.current - con.totallines + 1;
+ }
+}
+
+void Con_Bottom( void ) {
+ con.display = con.current;
+}
+
+
+void Con_Close( void ) {
+ if ( !com_cl_running->integer ) {
+ return;
+ }
+ Field_Clear( &g_consoleField );
+ Con_ClearNotify ();
+ cls.keyCatchers &= ~KEYCATCH_CONSOLE;
+ con.finalFrac = 0; // none visible
+ con.displayFrac = 0;
+}
diff --git a/code/client/cl_input.c b/code/client/cl_input.c
new file mode 100755
index 0000000..f450ee7
--- /dev/null
+++ b/code/client/cl_input.c
@@ -0,0 +1,901 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// cl.input.c -- builds an intended movement command to send to the server
+
+#include "client.h"
+
+unsigned frame_msec;
+int old_com_frameTime;
+
+/*
+===============================================================================
+
+KEY BUTTONS
+
+Continuous button event tracking is complicated by the fact that two different
+input sources (say, mouse button 1 and the control key) can both press the
+same button, but the button should only be released when both of the
+pressing key have been released.
+
+When a key event issues a button command (+forward, +attack, etc), it appends
+its key number as argv(1) so it can be matched up with the release.
+
+argv(2) will be set to the time the event happened, which allows exact
+control even at low framerates when the down and up events may both get qued
+at the same time.
+
+===============================================================================
+*/
+
+
+kbutton_t in_left, in_right, in_forward, in_back;
+kbutton_t in_lookup, in_lookdown, in_moveleft, in_moveright;
+kbutton_t in_strafe, in_speed;
+kbutton_t in_up, in_down;
+
+kbutton_t in_buttons[16];
+
+
+qboolean in_mlooking;
+
+
+void IN_MLookDown( void ) {
+ in_mlooking = qtrue;
+}
+
+void IN_MLookUp( void ) {
+ in_mlooking = qfalse;
+ if ( !cl_freelook->integer ) {
+ IN_CenterView ();
+ }
+}
+
+void IN_KeyDown( kbutton_t *b ) {
+ int k;
+ char *c;
+
+ c = Cmd_Argv(1);
+ if ( c[0] ) {
+ k = atoi(c);
+ } else {
+ k = -1; // typed manually at the console for continuous down
+ }
+
+ if ( k == b->down[0] || k == b->down[1] ) {
+ return; // repeating key
+ }
+
+ if ( !b->down[0] ) {
+ b->down[0] = k;
+ } else if ( !b->down[1] ) {
+ b->down[1] = k;
+ } else {
+ Com_Printf ("Three keys down for a button!\n");
+ return;
+ }
+
+ if ( b->active ) {
+ return; // still down
+ }
+
+ // save timestamp for partial frame summing
+ c = Cmd_Argv(2);
+ b->downtime = atoi(c);
+
+ b->active = qtrue;
+ b->wasPressed = qtrue;
+}
+
+void IN_KeyUp( kbutton_t *b ) {
+ int k;
+ char *c;
+ unsigned uptime;
+
+ c = Cmd_Argv(1);
+ if ( c[0] ) {
+ k = atoi(c);
+ } else {
+ // typed manually at the console, assume for unsticking, so clear all
+ b->down[0] = b->down[1] = 0;
+ b->active = qfalse;
+ return;
+ }
+
+ if ( b->down[0] == k ) {
+ b->down[0] = 0;
+ } else if ( b->down[1] == k ) {
+ b->down[1] = 0;
+ } else {
+ return; // key up without coresponding down (menu pass through)
+ }
+ if ( b->down[0] || b->down[1] ) {
+ return; // some other key is still holding it down
+ }
+
+ b->active = qfalse;
+
+ // save timestamp for partial frame summing
+ c = Cmd_Argv(2);
+ uptime = atoi(c);
+ if ( uptime ) {
+ b->msec += uptime - b->downtime;
+ } else {
+ b->msec += frame_msec / 2;
+ }
+
+ b->active = qfalse;
+}
+
+
+
+/*
+===============
+CL_KeyState
+
+Returns the fraction of the frame that the key was down
+===============
+*/
+float CL_KeyState( kbutton_t *key ) {
+ float val;
+ int msec;
+
+ msec = key->msec;
+ key->msec = 0;
+
+ if ( key->active ) {
+ // still down
+ if ( !key->downtime ) {
+ msec = com_frameTime;
+ } else {
+ msec += com_frameTime - key->downtime;
+ }
+ key->downtime = com_frameTime;
+ }
+
+#if 0
+ if (msec) {
+ Com_Printf ("%i ", msec);
+ }
+#endif
+
+ val = (float)msec / frame_msec;
+ if ( val < 0 ) {
+ val = 0;
+ }
+ if ( val > 1 ) {
+ val = 1;
+ }
+
+ return val;
+}
+
+
+
+void IN_UpDown(void) {IN_KeyDown(&in_up);}
+void IN_UpUp(void) {IN_KeyUp(&in_up);}
+void IN_DownDown(void) {IN_KeyDown(&in_down);}
+void IN_DownUp(void) {IN_KeyUp(&in_down);}
+void IN_LeftDown(void) {IN_KeyDown(&in_left);}
+void IN_LeftUp(void) {IN_KeyUp(&in_left);}
+void IN_RightDown(void) {IN_KeyDown(&in_right);}
+void IN_RightUp(void) {IN_KeyUp(&in_right);}
+void IN_ForwardDown(void) {IN_KeyDown(&in_forward);}
+void IN_ForwardUp(void) {IN_KeyUp(&in_forward);}
+void IN_BackDown(void) {IN_KeyDown(&in_back);}
+void IN_BackUp(void) {IN_KeyUp(&in_back);}
+void IN_LookupDown(void) {IN_KeyDown(&in_lookup);}
+void IN_LookupUp(void) {IN_KeyUp(&in_lookup);}
+void IN_LookdownDown(void) {IN_KeyDown(&in_lookdown);}
+void IN_LookdownUp(void) {IN_KeyUp(&in_lookdown);}
+void IN_MoveleftDown(void) {IN_KeyDown(&in_moveleft);}
+void IN_MoveleftUp(void) {IN_KeyUp(&in_moveleft);}
+void IN_MoverightDown(void) {IN_KeyDown(&in_moveright);}
+void IN_MoverightUp(void) {IN_KeyUp(&in_moveright);}
+
+void IN_SpeedDown(void) {IN_KeyDown(&in_speed);}
+void IN_SpeedUp(void) {IN_KeyUp(&in_speed);}
+void IN_StrafeDown(void) {IN_KeyDown(&in_strafe);}
+void IN_StrafeUp(void) {IN_KeyUp(&in_strafe);}
+
+void IN_Button0Down(void) {IN_KeyDown(&in_buttons[0]);}
+void IN_Button0Up(void) {IN_KeyUp(&in_buttons[0]);}
+void IN_Button1Down(void) {IN_KeyDown(&in_buttons[1]);}
+void IN_Button1Up(void) {IN_KeyUp(&in_buttons[1]);}
+void IN_Button2Down(void) {IN_KeyDown(&in_buttons[2]);}
+void IN_Button2Up(void) {IN_KeyUp(&in_buttons[2]);}
+void IN_Button3Down(void) {IN_KeyDown(&in_buttons[3]);}
+void IN_Button3Up(void) {IN_KeyUp(&in_buttons[3]);}
+void IN_Button4Down(void) {IN_KeyDown(&in_buttons[4]);}
+void IN_Button4Up(void) {IN_KeyUp(&in_buttons[4]);}
+void IN_Button5Down(void) {IN_KeyDown(&in_buttons[5]);}
+void IN_Button5Up(void) {IN_KeyUp(&in_buttons[5]);}
+void IN_Button6Down(void) {IN_KeyDown(&in_buttons[6]);}
+void IN_Button6Up(void) {IN_KeyUp(&in_buttons[6]);}
+void IN_Button7Down(void) {IN_KeyDown(&in_buttons[7]);}
+void IN_Button7Up(void) {IN_KeyUp(&in_buttons[7]);}
+void IN_Button8Down(void) {IN_KeyDown(&in_buttons[8]);}
+void IN_Button8Up(void) {IN_KeyUp(&in_buttons[8]);}
+void IN_Button9Down(void) {IN_KeyDown(&in_buttons[9]);}
+void IN_Button9Up(void) {IN_KeyUp(&in_buttons[9]);}
+void IN_Button10Down(void) {IN_KeyDown(&in_buttons[10]);}
+void IN_Button10Up(void) {IN_KeyUp(&in_buttons[10]);}
+void IN_Button11Down(void) {IN_KeyDown(&in_buttons[11]);}
+void IN_Button11Up(void) {IN_KeyUp(&in_buttons[11]);}
+void IN_Button12Down(void) {IN_KeyDown(&in_buttons[12]);}
+void IN_Button12Up(void) {IN_KeyUp(&in_buttons[12]);}
+void IN_Button13Down(void) {IN_KeyDown(&in_buttons[13]);}
+void IN_Button13Up(void) {IN_KeyUp(&in_buttons[13]);}
+void IN_Button14Down(void) {IN_KeyDown(&in_buttons[14]);}
+void IN_Button14Up(void) {IN_KeyUp(&in_buttons[14]);}
+void IN_Button15Down(void) {IN_KeyDown(&in_buttons[15]);}
+void IN_Button15Up(void) {IN_KeyUp(&in_buttons[15]);}
+
+void IN_ButtonDown (void) {
+ IN_KeyDown(&in_buttons[1]);}
+void IN_ButtonUp (void) {
+ IN_KeyUp(&in_buttons[1]);}
+
+void IN_CenterView (void) {
+ cl.viewangles[PITCH] = -SHORT2ANGLE(cl.snap.ps.delta_angles[PITCH]);
+}
+
+
+//==========================================================================
+
+cvar_t *cl_upspeed;
+cvar_t *cl_forwardspeed;
+cvar_t *cl_sidespeed;
+
+cvar_t *cl_yawspeed;
+cvar_t *cl_pitchspeed;
+
+cvar_t *cl_run;
+
+cvar_t *cl_anglespeedkey;
+
+
+/*
+================
+CL_AdjustAngles
+
+Moves the local angle positions
+================
+*/
+void CL_AdjustAngles( void ) {
+ float speed;
+
+ if ( in_speed.active ) {
+ speed = 0.001 * cls.frametime * cl_anglespeedkey->value;
+ } else {
+ speed = 0.001 * cls.frametime;
+ }
+
+ if ( !in_strafe.active ) {
+ cl.viewangles[YAW] -= speed*cl_yawspeed->value*CL_KeyState (&in_right);
+ cl.viewangles[YAW] += speed*cl_yawspeed->value*CL_KeyState (&in_left);
+ }
+
+ cl.viewangles[PITCH] -= speed*cl_pitchspeed->value * CL_KeyState (&in_lookup);
+ cl.viewangles[PITCH] += speed*cl_pitchspeed->value * CL_KeyState (&in_lookdown);
+}
+
+/*
+================
+CL_KeyMove
+
+Sets the usercmd_t based on key states
+================
+*/
+void CL_KeyMove( usercmd_t *cmd ) {
+ int movespeed;
+ int forward, side, up;
+
+ //
+ // adjust for speed key / running
+ // the walking flag is to keep animations consistant
+ // even during acceleration and develeration
+ //
+ if ( in_speed.active ^ cl_run->integer ) {
+ movespeed = 127;
+ cmd->buttons &= ~BUTTON_WALKING;
+ } else {
+ cmd->buttons |= BUTTON_WALKING;
+ movespeed = 64;
+ }
+
+ forward = 0;
+ side = 0;
+ up = 0;
+ if ( in_strafe.active ) {
+ side += movespeed * CL_KeyState (&in_right);
+ side -= movespeed * CL_KeyState (&in_left);
+ }
+
+ side += movespeed * CL_KeyState (&in_moveright);
+ side -= movespeed * CL_KeyState (&in_moveleft);
+
+
+ up += movespeed * CL_KeyState (&in_up);
+ up -= movespeed * CL_KeyState (&in_down);
+
+ forward += movespeed * CL_KeyState (&in_forward);
+ forward -= movespeed * CL_KeyState (&in_back);
+
+ cmd->forwardmove = ClampChar( forward );
+ cmd->rightmove = ClampChar( side );
+ cmd->upmove = ClampChar( up );
+}
+
+/*
+=================
+CL_MouseEvent
+=================
+*/
+void CL_MouseEvent( int dx, int dy, int time ) {
+ if ( cls.keyCatchers & KEYCATCH_UI ) {
+ VM_Call( uivm, UI_MOUSE_EVENT, dx, dy );
+ } else if (cls.keyCatchers & KEYCATCH_CGAME) {
+ VM_Call (cgvm, CG_MOUSE_EVENT, dx, dy);
+ } else {
+ cl.mouseDx[cl.mouseIndex] += dx;
+ cl.mouseDy[cl.mouseIndex] += dy;
+ }
+}
+
+/*
+=================
+CL_JoystickEvent
+
+Joystick values stay set until changed
+=================
+*/
+void CL_JoystickEvent( int axis, int value, int time ) {
+ if ( axis < 0 || axis >= MAX_JOYSTICK_AXIS ) {
+ Com_Error( ERR_DROP, "CL_JoystickEvent: bad axis %i", axis );
+ }
+ cl.joystickAxis[axis] = value;
+}
+
+/*
+=================
+CL_JoystickMove
+=================
+*/
+void CL_JoystickMove( usercmd_t *cmd ) {
+ int movespeed;
+ float anglespeed;
+
+ if ( in_speed.active ^ cl_run->integer ) {
+ movespeed = 2;
+ } else {
+ movespeed = 1;
+ cmd->buttons |= BUTTON_WALKING;
+ }
+
+ if ( in_speed.active ) {
+ anglespeed = 0.001 * cls.frametime * cl_anglespeedkey->value;
+ } else {
+ anglespeed = 0.001 * cls.frametime;
+ }
+
+ if ( !in_strafe.active ) {
+ cl.viewangles[YAW] += anglespeed * cl_yawspeed->value * cl.joystickAxis[AXIS_SIDE];
+ } else {
+ cmd->rightmove = ClampChar( cmd->rightmove + cl.joystickAxis[AXIS_SIDE] );
+ }
+
+ if ( in_mlooking ) {
+ cl.viewangles[PITCH] += anglespeed * cl_pitchspeed->value * cl.joystickAxis[AXIS_FORWARD];
+ } else {
+ cmd->forwardmove = ClampChar( cmd->forwardmove + cl.joystickAxis[AXIS_FORWARD] );
+ }
+
+ cmd->upmove = ClampChar( cmd->upmove + cl.joystickAxis[AXIS_UP] );
+}
+
+/*
+=================
+CL_MouseMove
+=================
+*/
+void CL_MouseMove( usercmd_t *cmd ) {
+ float mx, my;
+ float accelSensitivity;
+ float rate;
+
+ // allow mouse smoothing
+ if ( m_filter->integer ) {
+ mx = ( cl.mouseDx[0] + cl.mouseDx[1] ) * 0.5;
+ my = ( cl.mouseDy[0] + cl.mouseDy[1] ) * 0.5;
+ } else {
+ mx = cl.mouseDx[cl.mouseIndex];
+ my = cl.mouseDy[cl.mouseIndex];
+ }
+ cl.mouseIndex ^= 1;
+ cl.mouseDx[cl.mouseIndex] = 0;
+ cl.mouseDy[cl.mouseIndex] = 0;
+
+ rate = sqrt( mx * mx + my * my ) / (float)frame_msec;
+ accelSensitivity = cl_sensitivity->value + rate * cl_mouseAccel->value;
+
+ // scale by FOV
+ accelSensitivity *= cl.cgameSensitivity;
+
+ if ( rate && cl_showMouseRate->integer ) {
+ Com_Printf( "%f : %f\n", rate, accelSensitivity );
+ }
+
+ mx *= accelSensitivity;
+ my *= accelSensitivity;
+
+ if (!mx && !my) {
+ return;
+ }
+
+ // add mouse X/Y movement to cmd
+ if ( in_strafe.active ) {
+ cmd->rightmove = ClampChar( cmd->rightmove + m_side->value * mx );
+ } else {
+ cl.viewangles[YAW] -= m_yaw->value * mx;
+ }
+
+ if ( (in_mlooking || cl_freelook->integer) && !in_strafe.active ) {
+ cl.viewangles[PITCH] += m_pitch->value * my;
+ } else {
+ cmd->forwardmove = ClampChar( cmd->forwardmove - m_forward->value * my );
+ }
+}
+
+
+/*
+==============
+CL_CmdButtons
+==============
+*/
+void CL_CmdButtons( usercmd_t *cmd ) {
+ int i;
+
+ //
+ // figure button bits
+ // send a button bit even if the key was pressed and released in
+ // less than a frame
+ //
+ for (i = 0 ; i < 15 ; i++) {
+ if ( in_buttons[i].active || in_buttons[i].wasPressed ) {
+ cmd->buttons |= 1 << i;
+ }
+ in_buttons[i].wasPressed = qfalse;
+ }
+
+ if ( cls.keyCatchers ) {
+ cmd->buttons |= BUTTON_TALK;
+ }
+
+ // allow the game to know if any key at all is
+ // currently pressed, even if it isn't bound to anything
+ if ( anykeydown && !cls.keyCatchers ) {
+ cmd->buttons |= BUTTON_ANY;
+ }
+}
+
+
+/*
+==============
+CL_FinishMove
+==============
+*/
+void CL_FinishMove( usercmd_t *cmd ) {
+ int i;
+
+ // copy the state that the cgame is currently sending
+ cmd->weapon = cl.cgameUserCmdValue;
+
+ // send the current server time so the amount of movement
+ // can be determined without allowing cheating
+ cmd->serverTime = cl.serverTime;
+
+ for (i=0 ; i<3 ; i++) {
+ cmd->angles[i] = ANGLE2SHORT(cl.viewangles[i]);
+ }
+}
+
+
+/*
+=================
+CL_CreateCmd
+=================
+*/
+usercmd_t CL_CreateCmd( void ) {
+ usercmd_t cmd;
+ vec3_t oldAngles;
+
+ VectorCopy( cl.viewangles, oldAngles );
+
+ // keyboard angle adjustment
+ CL_AdjustAngles ();
+
+ Com_Memset( &cmd, 0, sizeof( cmd ) );
+
+ CL_CmdButtons( &cmd );
+
+ // get basic movement from keyboard
+ CL_KeyMove( &cmd );
+
+ // get basic movement from mouse
+ CL_MouseMove( &cmd );
+
+ // get basic movement from joystick
+ CL_JoystickMove( &cmd );
+
+ // check to make sure the angles haven't wrapped
+ if ( cl.viewangles[PITCH] - oldAngles[PITCH] > 90 ) {
+ cl.viewangles[PITCH] = oldAngles[PITCH] + 90;
+ } else if ( oldAngles[PITCH] - cl.viewangles[PITCH] > 90 ) {
+ cl.viewangles[PITCH] = oldAngles[PITCH] - 90;
+ }
+
+ // store out the final values
+ CL_FinishMove( &cmd );
+
+ // draw debug graphs of turning for mouse testing
+ if ( cl_debugMove->integer ) {
+ if ( cl_debugMove->integer == 1 ) {
+ SCR_DebugGraph( abs(cl.viewangles[YAW] - oldAngles[YAW]), 0 );
+ }
+ if ( cl_debugMove->integer == 2 ) {
+ SCR_DebugGraph( abs(cl.viewangles[PITCH] - oldAngles[PITCH]), 0 );
+ }
+ }
+
+ return cmd;
+}
+
+
+/*
+=================
+CL_CreateNewCommands
+
+Create a new usercmd_t structure for this frame
+=================
+*/
+void CL_CreateNewCommands( void ) {
+ usercmd_t *cmd;
+ int cmdNum;
+
+ // no need to create usercmds until we have a gamestate
+ if ( cls.state < CA_PRIMED ) {
+ return;
+ }
+
+ frame_msec = com_frameTime - old_com_frameTime;
+
+ // if running less than 5fps, truncate the extra time to prevent
+ // unexpected moves after a hitch
+ if ( frame_msec > 200 ) {
+ frame_msec = 200;
+ }
+ old_com_frameTime = com_frameTime;
+
+
+ // generate a command for this frame
+ cl.cmdNumber++;
+ cmdNum = cl.cmdNumber & CMD_MASK;
+ cl.cmds[cmdNum] = CL_CreateCmd ();
+ cmd = &cl.cmds[cmdNum];
+}
+
+/*
+=================
+CL_ReadyToSendPacket
+
+Returns qfalse if we are over the maxpackets limit
+and should choke back the bandwidth a bit by not sending
+a packet this frame. All the commands will still get
+delivered in the next packet, but saving a header and
+getting more delta compression will reduce total bandwidth.
+=================
+*/
+qboolean CL_ReadyToSendPacket( void ) {
+ int oldPacketNum;
+ int delta;
+
+ // don't send anything if playing back a demo
+ if ( clc.demoplaying || cls.state == CA_CINEMATIC ) {
+ return qfalse;
+ }
+
+ // If we are downloading, we send no less than 50ms between packets
+ if ( *clc.downloadTempName &&
+ cls.realtime - clc.lastPacketSentTime < 50 ) {
+ return qfalse;
+ }
+
+ // if we don't have a valid gamestate yet, only send
+ // one packet a second
+ if ( cls.state != CA_ACTIVE &&
+ cls.state != CA_PRIMED &&
+ !*clc.downloadTempName &&
+ cls.realtime - clc.lastPacketSentTime < 1000 ) {
+ return qfalse;
+ }
+
+ // send every frame for loopbacks
+ if ( clc.netchan.remoteAddress.type == NA_LOOPBACK ) {
+ return qtrue;
+ }
+
+ // send every frame for LAN
+ if ( Sys_IsLANAddress( clc.netchan.remoteAddress ) ) {
+ return qtrue;
+ }
+
+ // check for exceeding cl_maxpackets
+ if ( cl_maxpackets->integer < 15 ) {
+ Cvar_Set( "cl_maxpackets", "15" );
+ } else if ( cl_maxpackets->integer > 125 ) {
+ Cvar_Set( "cl_maxpackets", "125" );
+ }
+ oldPacketNum = (clc.netchan.outgoingSequence - 1) & PACKET_MASK;
+ delta = cls.realtime - cl.outPackets[ oldPacketNum ].p_realtime;
+ if ( delta < 1000 / cl_maxpackets->integer ) {
+ // the accumulated commands will go out in the next packet
+ return qfalse;
+ }
+
+ return qtrue;
+}
+
+/*
+===================
+CL_WritePacket
+
+Create and send the command packet to the server
+Including both the reliable commands and the usercmds
+
+During normal gameplay, a client packet will contain something like:
+
+4 sequence number
+2 qport
+4 serverid
+4 acknowledged sequence number
+4 clc.serverCommandSequence
+<optional reliable commands>
+1 clc_move or clc_moveNoDelta
+1 command count
+<count * usercmds>
+
+===================
+*/
+void CL_WritePacket( void ) {
+ msg_t buf;
+ byte data[MAX_MSGLEN];
+ int i, j;
+ usercmd_t *cmd, *oldcmd;
+ usercmd_t nullcmd;
+ int packetNum;
+ int oldPacketNum;
+ int count, key;
+
+ // don't send anything if playing back a demo
+ if ( clc.demoplaying || cls.state == CA_CINEMATIC ) {
+ return;
+ }
+
+ Com_Memset( &nullcmd, 0, sizeof(nullcmd) );
+ oldcmd = &nullcmd;
+
+ MSG_Init( &buf, data, sizeof(data) );
+
+ MSG_Bitstream( &buf );
+ // write the current serverId so the server
+ // can tell if this is from the current gameState
+ MSG_WriteLong( &buf, cl.serverId );
+
+ // write the last message we received, which can
+ // be used for delta compression, and is also used
+ // to tell if we dropped a gamestate
+ MSG_WriteLong( &buf, clc.serverMessageSequence );
+
+ // write the last reliable message we received
+ MSG_WriteLong( &buf, clc.serverCommandSequence );
+
+ // write any unacknowledged clientCommands
+ for ( i = clc.reliableAcknowledge + 1 ; i <= clc.reliableSequence ; i++ ) {
+ MSG_WriteByte( &buf, clc_clientCommand );
+ MSG_WriteLong( &buf, i );
+ MSG_WriteString( &buf, clc.reliableCommands[ i & (MAX_RELIABLE_COMMANDS-1) ] );
+ }
+
+ // we want to send all the usercmds that were generated in the last
+ // few packet, so even if a couple packets are dropped in a row,
+ // all the cmds will make it to the server
+ if ( cl_packetdup->integer < 0 ) {
+ Cvar_Set( "cl_packetdup", "0" );
+ } else if ( cl_packetdup->integer > 5 ) {
+ Cvar_Set( "cl_packetdup", "5" );
+ }
+ oldPacketNum = (clc.netchan.outgoingSequence - 1 - cl_packetdup->integer) & PACKET_MASK;
+ count = cl.cmdNumber - cl.outPackets[ oldPacketNum ].p_cmdNumber;
+ if ( count > MAX_PACKET_USERCMDS ) {
+ count = MAX_PACKET_USERCMDS;
+ Com_Printf("MAX_PACKET_USERCMDS\n");
+ }
+ if ( count >= 1 ) {
+ if ( cl_showSend->integer ) {
+ Com_Printf( "(%i)", count );
+ }
+
+ // begin a client move command
+ if ( cl_nodelta->integer || !cl.snap.valid || clc.demowaiting
+ || clc.serverMessageSequence != cl.snap.messageNum ) {
+ MSG_WriteByte (&buf, clc_moveNoDelta);
+ } else {
+ MSG_WriteByte (&buf, clc_move);
+ }
+
+ // write the command count
+ MSG_WriteByte( &buf, count );
+
+ // use the checksum feed in the key
+ key = clc.checksumFeed;
+ // also use the message acknowledge
+ key ^= clc.serverMessageSequence;
+ // also use the last acknowledged server command in the key
+ key ^= Com_HashKey(clc.serverCommands[ clc.serverCommandSequence & (MAX_RELIABLE_COMMANDS-1) ], 32);
+
+ // write all the commands, including the predicted command
+ for ( i = 0 ; i < count ; i++ ) {
+ j = (cl.cmdNumber - count + i + 1) & CMD_MASK;
+ cmd = &cl.cmds[j];
+ MSG_WriteDeltaUsercmdKey (&buf, key, oldcmd, cmd);
+ oldcmd = cmd;
+ }
+ }
+
+ //
+ // deliver the message
+ //
+ packetNum = clc.netchan.outgoingSequence & PACKET_MASK;
+ cl.outPackets[ packetNum ].p_realtime = cls.realtime;
+ cl.outPackets[ packetNum ].p_serverTime = oldcmd->serverTime;
+ cl.outPackets[ packetNum ].p_cmdNumber = cl.cmdNumber;
+ clc.lastPacketSentTime = cls.realtime;
+
+ if ( cl_showSend->integer ) {
+ Com_Printf( "%i ", buf.cursize );
+ }
+
+ CL_Netchan_Transmit (&clc.netchan, &buf);
+
+ // clients never really should have messages large enough
+ // to fragment, but in case they do, fire them all off
+ // at once
+ // TTimo: this causes a packet burst, which is bad karma for winsock
+ // added a WARNING message, we'll see if there are legit situations where this happens
+ while ( clc.netchan.unsentFragments ) {
+ Com_DPrintf( "WARNING: #462 unsent fragments (not supposed to happen!)\n" );
+ CL_Netchan_TransmitNextFragment( &clc.netchan );
+ }
+}
+
+/*
+=================
+CL_SendCmd
+
+Called every frame to builds and sends a command packet to the server.
+=================
+*/
+void CL_SendCmd( void ) {
+ // don't send any message if not connected
+ if ( cls.state < CA_CONNECTED ) {
+ return;
+ }
+
+ // don't send commands if paused
+ if ( com_sv_running->integer && sv_paused->integer && cl_paused->integer ) {
+ return;
+ }
+
+ // we create commands even if a demo is playing,
+ CL_CreateNewCommands();
+
+ // don't send a packet if the last packet was sent too recently
+ if ( !CL_ReadyToSendPacket() ) {
+ if ( cl_showSend->integer ) {
+ Com_Printf( ". " );
+ }
+ return;
+ }
+
+ CL_WritePacket();
+}
+
+/*
+============
+CL_InitInput
+============
+*/
+void CL_InitInput( void ) {
+ Cmd_AddCommand ("centerview",IN_CenterView);
+
+ Cmd_AddCommand ("+moveup",IN_UpDown);
+ Cmd_AddCommand ("-moveup",IN_UpUp);
+ Cmd_AddCommand ("+movedown",IN_DownDown);
+ Cmd_AddCommand ("-movedown",IN_DownUp);
+ Cmd_AddCommand ("+left",IN_LeftDown);
+ Cmd_AddCommand ("-left",IN_LeftUp);
+ Cmd_AddCommand ("+right",IN_RightDown);
+ Cmd_AddCommand ("-right",IN_RightUp);
+ Cmd_AddCommand ("+forward",IN_ForwardDown);
+ Cmd_AddCommand ("-forward",IN_ForwardUp);
+ Cmd_AddCommand ("+back",IN_BackDown);
+ Cmd_AddCommand ("-back",IN_BackUp);
+ Cmd_AddCommand ("+lookup", IN_LookupDown);
+ Cmd_AddCommand ("-lookup", IN_LookupUp);
+ Cmd_AddCommand ("+lookdown", IN_LookdownDown);
+ Cmd_AddCommand ("-lookdown", IN_LookdownUp);
+ Cmd_AddCommand ("+strafe", IN_StrafeDown);
+ Cmd_AddCommand ("-strafe", IN_StrafeUp);
+ Cmd_AddCommand ("+moveleft", IN_MoveleftDown);
+ Cmd_AddCommand ("-moveleft", IN_MoveleftUp);
+ Cmd_AddCommand ("+moveright", IN_MoverightDown);
+ Cmd_AddCommand ("-moveright", IN_MoverightUp);
+ Cmd_AddCommand ("+speed", IN_SpeedDown);
+ Cmd_AddCommand ("-speed", IN_SpeedUp);
+ Cmd_AddCommand ("+attack", IN_Button0Down);
+ Cmd_AddCommand ("-attack", IN_Button0Up);
+ Cmd_AddCommand ("+button0", IN_Button0Down);
+ Cmd_AddCommand ("-button0", IN_Button0Up);
+ Cmd_AddCommand ("+button1", IN_Button1Down);
+ Cmd_AddCommand ("-button1", IN_Button1Up);
+ Cmd_AddCommand ("+button2", IN_Button2Down);
+ Cmd_AddCommand ("-button2", IN_Button2Up);
+ Cmd_AddCommand ("+button3", IN_Button3Down);
+ Cmd_AddCommand ("-button3", IN_Button3Up);
+ Cmd_AddCommand ("+button4", IN_Button4Down);
+ Cmd_AddCommand ("-button4", IN_Button4Up);
+ Cmd_AddCommand ("+button5", IN_Button5Down);
+ Cmd_AddCommand ("-button5", IN_Button5Up);
+ Cmd_AddCommand ("+button6", IN_Button6Down);
+ Cmd_AddCommand ("-button6", IN_Button6Up);
+ Cmd_AddCommand ("+button7", IN_Button7Down);
+ Cmd_AddCommand ("-button7", IN_Button7Up);
+ Cmd_AddCommand ("+button8", IN_Button8Down);
+ Cmd_AddCommand ("-button8", IN_Button8Up);
+ Cmd_AddCommand ("+button9", IN_Button9Down);
+ Cmd_AddCommand ("-button9", IN_Button9Up);
+ Cmd_AddCommand ("+button10", IN_Button10Down);
+ Cmd_AddCommand ("-button10", IN_Button10Up);
+ Cmd_AddCommand ("+button11", IN_Button11Down);
+ Cmd_AddCommand ("-button11", IN_Button11Up);
+ Cmd_AddCommand ("+button12", IN_Button12Down);
+ Cmd_AddCommand ("-button12", IN_Button12Up);
+ Cmd_AddCommand ("+button13", IN_Button13Down);
+ Cmd_AddCommand ("-button13", IN_Button13Up);
+ Cmd_AddCommand ("+button14", IN_Button14Down);
+ Cmd_AddCommand ("-button14", IN_Button14Up);
+ Cmd_AddCommand ("+mlook", IN_MLookDown);
+ Cmd_AddCommand ("-mlook", IN_MLookUp);
+
+ cl_nodelta = Cvar_Get ("cl_nodelta", "0", 0);
+ cl_debugMove = Cvar_Get ("cl_debugMove", "0", 0);
+}
diff --git a/code/client/cl_keys.c b/code/client/cl_keys.c
new file mode 100755
index 0000000..7dcd7d8
--- /dev/null
+++ b/code/client/cl_keys.c
@@ -0,0 +1,1252 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "client.h"
+
+/*
+
+key up events are sent even if in console mode
+
+*/
+
+field_t historyEditLines[COMMAND_HISTORY];
+
+int nextHistoryLine; // the last line in the history buffer, not masked
+int historyLine; // the line being displayed from history buffer
+ // will be <= nextHistoryLine
+
+field_t g_consoleField;
+field_t chatField;
+qboolean chat_team;
+
+int chat_playerNum;
+
+
+qboolean key_overstrikeMode;
+
+qboolean anykeydown;
+qkey_t keys[MAX_KEYS];
+
+
+typedef struct {
+ char *name;
+ int keynum;
+} keyname_t;
+
+
+// names not in this list can either be lowercase ascii, or '0xnn' hex sequences
+keyname_t keynames[] =
+{
+ {"TAB", K_TAB},
+ {"ENTER", K_ENTER},
+ {"ESCAPE", K_ESCAPE},
+ {"SPACE", K_SPACE},
+ {"BACKSPACE", K_BACKSPACE},
+ {"UPARROW", K_UPARROW},
+ {"DOWNARROW", K_DOWNARROW},
+ {"LEFTARROW", K_LEFTARROW},
+ {"RIGHTARROW", K_RIGHTARROW},
+
+ {"ALT", K_ALT},
+ {"CTRL", K_CTRL},
+ {"SHIFT", K_SHIFT},
+
+ {"COMMAND", K_COMMAND},
+
+ {"CAPSLOCK", K_CAPSLOCK},
+
+
+ {"F1", K_F1},
+ {"F2", K_F2},
+ {"F3", K_F3},
+ {"F4", K_F4},
+ {"F5", K_F5},
+ {"F6", K_F6},
+ {"F7", K_F7},
+ {"F8", K_F8},
+ {"F9", K_F9},
+ {"F10", K_F10},
+ {"F11", K_F11},
+ {"F12", K_F12},
+
+ {"INS", K_INS},
+ {"DEL", K_DEL},
+ {"PGDN", K_PGDN},
+ {"PGUP", K_PGUP},
+ {"HOME", K_HOME},
+ {"END", K_END},
+
+ {"MOUSE1", K_MOUSE1},
+ {"MOUSE2", K_MOUSE2},
+ {"MOUSE3", K_MOUSE3},
+ {"MOUSE4", K_MOUSE4},
+ {"MOUSE5", K_MOUSE5},
+
+ {"MWHEELUP", K_MWHEELUP },
+ {"MWHEELDOWN", K_MWHEELDOWN },
+
+ {"JOY1", K_JOY1},
+ {"JOY2", K_JOY2},
+ {"JOY3", K_JOY3},
+ {"JOY4", K_JOY4},
+ {"JOY5", K_JOY5},
+ {"JOY6", K_JOY6},
+ {"JOY7", K_JOY7},
+ {"JOY8", K_JOY8},
+ {"JOY9", K_JOY9},
+ {"JOY10", K_JOY10},
+ {"JOY11", K_JOY11},
+ {"JOY12", K_JOY12},
+ {"JOY13", K_JOY13},
+ {"JOY14", K_JOY14},
+ {"JOY15", K_JOY15},
+ {"JOY16", K_JOY16},
+ {"JOY17", K_JOY17},
+ {"JOY18", K_JOY18},
+ {"JOY19", K_JOY19},
+ {"JOY20", K_JOY20},
+ {"JOY21", K_JOY21},
+ {"JOY22", K_JOY22},
+ {"JOY23", K_JOY23},
+ {"JOY24", K_JOY24},
+ {"JOY25", K_JOY25},
+ {"JOY26", K_JOY26},
+ {"JOY27", K_JOY27},
+ {"JOY28", K_JOY28},
+ {"JOY29", K_JOY29},
+ {"JOY30", K_JOY30},
+ {"JOY31", K_JOY31},
+ {"JOY32", K_JOY32},
+
+ {"AUX1", K_AUX1},
+ {"AUX2", K_AUX2},
+ {"AUX3", K_AUX3},
+ {"AUX4", K_AUX4},
+ {"AUX5", K_AUX5},
+ {"AUX6", K_AUX6},
+ {"AUX7", K_AUX7},
+ {"AUX8", K_AUX8},
+ {"AUX9", K_AUX9},
+ {"AUX10", K_AUX10},
+ {"AUX11", K_AUX11},
+ {"AUX12", K_AUX12},
+ {"AUX13", K_AUX13},
+ {"AUX14", K_AUX14},
+ {"AUX15", K_AUX15},
+ {"AUX16", K_AUX16},
+
+ {"KP_HOME", K_KP_HOME },
+ {"KP_UPARROW", K_KP_UPARROW },
+ {"KP_PGUP", K_KP_PGUP },
+ {"KP_LEFTARROW", K_KP_LEFTARROW },
+ {"KP_5", K_KP_5 },
+ {"KP_RIGHTARROW", K_KP_RIGHTARROW },
+ {"KP_END", K_KP_END },
+ {"KP_DOWNARROW", K_KP_DOWNARROW },
+ {"KP_PGDN", K_KP_PGDN },
+ {"KP_ENTER", K_KP_ENTER },
+ {"KP_INS", K_KP_INS },
+ {"KP_DEL", K_KP_DEL },
+ {"KP_SLASH", K_KP_SLASH },
+ {"KP_MINUS", K_KP_MINUS },
+ {"KP_PLUS", K_KP_PLUS },
+ {"KP_NUMLOCK", K_KP_NUMLOCK },
+ {"KP_STAR", K_KP_STAR },
+ {"KP_EQUALS", K_KP_EQUALS },
+
+ {"PAUSE", K_PAUSE},
+
+ {"SEMICOLON", ';'}, // because a raw semicolon seperates commands
+
+ {NULL,0}
+};
+
+/*
+=============================================================================
+
+EDIT FIELDS
+
+=============================================================================
+*/
+
+
+/*
+===================
+Field_Draw
+
+Handles horizontal scrolling and cursor blinking
+x, y, amd width are in pixels
+===================
+*/
+void Field_VariableSizeDraw( field_t *edit, int x, int y, int width, int size, qboolean showCursor ) {
+ int len;
+ int drawLen;
+ int prestep;
+ int cursorChar;
+ char str[MAX_STRING_CHARS];
+ int i;
+
+ drawLen = edit->widthInChars;
+ len = strlen( edit->buffer ) + 1;
+
+ // guarantee that cursor will be visible
+ if ( len <= drawLen ) {
+ prestep = 0;
+ } else {
+ if ( edit->scroll + drawLen > len ) {
+ edit->scroll = len - drawLen;
+ if ( edit->scroll < 0 ) {
+ edit->scroll = 0;
+ }
+ }
+ prestep = edit->scroll;
+
+/*
+ if ( edit->cursor < len - drawLen ) {
+ prestep = edit->cursor; // cursor at start
+ } else {
+ prestep = len - drawLen;
+ }
+*/
+ }
+
+ if ( prestep + drawLen > len ) {
+ drawLen = len - prestep;
+ }
+
+ // extract <drawLen> characters from the field at <prestep>
+ if ( drawLen >= MAX_STRING_CHARS ) {
+ Com_Error( ERR_DROP, "drawLen >= MAX_STRING_CHARS" );
+ }
+
+ Com_Memcpy( str, edit->buffer + prestep, drawLen );
+ str[ drawLen ] = 0;
+
+ // draw it
+ if ( size == SMALLCHAR_WIDTH ) {
+ float color[4];
+
+ color[0] = color[1] = color[2] = color[3] = 1.0;
+ SCR_DrawSmallStringExt( x, y, str, color, qfalse );
+ } else {
+ // draw big string with drop shadow
+ SCR_DrawBigString( x, y, str, 1.0 );
+ }
+
+ // draw the cursor
+ if ( !showCursor ) {
+ return;
+ }
+
+ if ( (int)( cls.realtime >> 8 ) & 1 ) {
+ return; // off blink
+ }
+
+ if ( key_overstrikeMode ) {
+ cursorChar = 11;
+ } else {
+ cursorChar = 10;
+ }
+
+ i = drawLen - ( Q_PrintStrlen( str ) + 1 );
+
+ if ( size == SMALLCHAR_WIDTH ) {
+ SCR_DrawSmallChar( x + ( edit->cursor - prestep - i ) * size, y, cursorChar );
+ } else {
+ str[0] = cursorChar;
+ str[1] = 0;
+ SCR_DrawBigString( x + ( edit->cursor - prestep - i ) * size, y, str, 1.0 );
+
+ }
+}
+
+void Field_Draw( field_t *edit, int x, int y, int width, qboolean showCursor )
+{
+ Field_VariableSizeDraw( edit, x, y, width, SMALLCHAR_WIDTH, showCursor );
+}
+
+void Field_BigDraw( field_t *edit, int x, int y, int width, qboolean showCursor )
+{
+ Field_VariableSizeDraw( edit, x, y, width, BIGCHAR_WIDTH, showCursor );
+}
+
+/*
+================
+Field_Paste
+================
+*/
+void Field_Paste( field_t *edit ) {
+ char *cbd;
+ int pasteLen, i;
+
+ cbd = Sys_GetClipboardData();
+
+ if ( !cbd ) {
+ return;
+ }
+
+ // send as if typed, so insert / overstrike works properly
+ pasteLen = strlen( cbd );
+ for ( i = 0 ; i < pasteLen ; i++ ) {
+ Field_CharEvent( edit, cbd[i] );
+ }
+
+ Z_Free( cbd );
+}
+
+/*
+=================
+Field_KeyDownEvent
+
+Performs the basic line editing functions for the console,
+in-game talk, and menu fields
+
+Key events are used for non-printable characters, others are gotten from char events.
+=================
+*/
+void Field_KeyDownEvent( field_t *edit, int key ) {
+ int len;
+
+ // shift-insert is paste
+ if ( ( ( key == K_INS ) || ( key == K_KP_INS ) ) && keys[K_SHIFT].down ) {
+ Field_Paste( edit );
+ return;
+ }
+
+ len = strlen( edit->buffer );
+
+ if ( key == K_DEL ) {
+ if ( edit->cursor < len ) {
+ memmove( edit->buffer + edit->cursor,
+ edit->buffer + edit->cursor + 1, len - edit->cursor );
+ }
+ return;
+ }
+
+ if ( key == K_RIGHTARROW )
+ {
+ if ( edit->cursor < len ) {
+ edit->cursor++;
+ }
+
+ if ( edit->cursor >= edit->scroll + edit->widthInChars && edit->cursor <= len )
+ {
+ edit->scroll++;
+ }
+ return;
+ }
+
+ if ( key == K_LEFTARROW )
+ {
+ if ( edit->cursor > 0 ) {
+ edit->cursor--;
+ }
+ if ( edit->cursor < edit->scroll )
+ {
+ edit->scroll--;
+ }
+ return;
+ }
+
+ if ( key == K_HOME || ( tolower(key) == 'a' && keys[K_CTRL].down ) ) {
+ edit->cursor = 0;
+ return;
+ }
+
+ if ( key == K_END || ( tolower(key) == 'e' && keys[K_CTRL].down ) ) {
+ edit->cursor = len;
+ return;
+ }
+
+ if ( key == K_INS ) {
+ key_overstrikeMode = !key_overstrikeMode;
+ return;
+ }
+}
+
+/*
+==================
+Field_CharEvent
+==================
+*/
+void Field_CharEvent( field_t *edit, int ch ) {
+ int len;
+
+ if ( ch == 'v' - 'a' + 1 ) { // ctrl-v is paste
+ Field_Paste( edit );
+ return;
+ }
+
+ if ( ch == 'c' - 'a' + 1 ) { // ctrl-c clears the field
+ Field_Clear( edit );
+ return;
+ }
+
+ len = strlen( edit->buffer );
+
+ if ( ch == 'h' - 'a' + 1 ) { // ctrl-h is backspace
+ if ( edit->cursor > 0 ) {
+ memmove( edit->buffer + edit->cursor - 1,
+ edit->buffer + edit->cursor, len + 1 - edit->cursor );
+ edit->cursor--;
+ if ( edit->cursor < edit->scroll )
+ {
+ edit->scroll--;
+ }
+ }
+ return;
+ }
+
+ if ( ch == 'a' - 'a' + 1 ) { // ctrl-a is home
+ edit->cursor = 0;
+ edit->scroll = 0;
+ return;
+ }
+
+ if ( ch == 'e' - 'a' + 1 ) { // ctrl-e is end
+ edit->cursor = len;
+ edit->scroll = edit->cursor - edit->widthInChars;
+ return;
+ }
+
+ //
+ // ignore any other non printable chars
+ //
+ if ( ch < 32 ) {
+ return;
+ }
+
+ if ( key_overstrikeMode ) {
+ if ( edit->cursor == MAX_EDIT_LINE - 1 )
+ return;
+ edit->buffer[edit->cursor] = ch;
+ edit->cursor++;
+ } else { // insert mode
+ if ( len == MAX_EDIT_LINE - 1 ) {
+ return; // all full
+ }
+ memmove( edit->buffer + edit->cursor + 1,
+ edit->buffer + edit->cursor, len + 1 - edit->cursor );
+ edit->buffer[edit->cursor] = ch;
+ edit->cursor++;
+ }
+
+
+ if ( edit->cursor >= edit->widthInChars ) {
+ edit->scroll++;
+ }
+
+ if ( edit->cursor == len + 1) {
+ edit->buffer[edit->cursor] = 0;
+ }
+}
+
+/*
+=============================================================================
+
+CONSOLE LINE EDITING
+
+==============================================================================
+*/
+
+/*
+====================
+Console_Key
+
+Handles history and console scrollback
+====================
+*/
+void Console_Key (int key) {
+ // ctrl-L clears screen
+ if ( key == 'l' && keys[K_CTRL].down ) {
+ Cbuf_AddText ("clear\n");
+ return;
+ }
+
+ // enter finishes the line
+ if ( key == K_ENTER || key == K_KP_ENTER ) {
+ // if not in the game explicitly prepent a slash if needed
+ if ( cls.state != CA_ACTIVE && g_consoleField.buffer[0] != '\\'
+ && g_consoleField.buffer[0] != '/' ) {
+ char temp[MAX_STRING_CHARS];
+
+ Q_strncpyz( temp, g_consoleField.buffer, sizeof( temp ) );
+ Com_sprintf( g_consoleField.buffer, sizeof( g_consoleField.buffer ), "\\%s", temp );
+ g_consoleField.cursor++;
+ }
+
+ Com_Printf ( "]%s\n", g_consoleField.buffer );
+
+ // leading slash is an explicit command
+ if ( g_consoleField.buffer[0] == '\\' || g_consoleField.buffer[0] == '/' ) {
+ Cbuf_AddText( g_consoleField.buffer+1 ); // valid command
+ Cbuf_AddText ("\n");
+ } else {
+ // other text will be chat messages
+ if ( !g_consoleField.buffer[0] ) {
+ return; // empty lines just scroll the console without adding to history
+ } else {
+ Cbuf_AddText ("cmd say ");
+ Cbuf_AddText( g_consoleField.buffer );
+ Cbuf_AddText ("\n");
+ }
+ }
+
+ // copy line to history buffer
+ historyEditLines[nextHistoryLine % COMMAND_HISTORY] = g_consoleField;
+ nextHistoryLine++;
+ historyLine = nextHistoryLine;
+
+ Field_Clear( &g_consoleField );
+
+ g_consoleField.widthInChars = g_console_field_width;
+
+ if ( cls.state == CA_DISCONNECTED ) {
+ SCR_UpdateScreen (); // force an update, because the command
+ } // may take some time
+ return;
+ }
+
+ // command completion
+
+ if (key == K_TAB) {
+ Field_CompleteCommand(&g_consoleField);
+ return;
+ }
+
+ // command history (ctrl-p ctrl-n for unix style)
+
+ if ( (key == K_MWHEELUP && keys[K_SHIFT].down) || ( key == K_UPARROW ) || ( key == K_KP_UPARROW ) ||
+ ( ( tolower(key) == 'p' ) && keys[K_CTRL].down ) ) {
+ if ( nextHistoryLine - historyLine < COMMAND_HISTORY
+ && historyLine > 0 ) {
+ historyLine--;
+ }
+ g_consoleField = historyEditLines[ historyLine % COMMAND_HISTORY ];
+ return;
+ }
+
+ if ( (key == K_MWHEELDOWN && keys[K_SHIFT].down) || ( key == K_DOWNARROW ) || ( key == K_KP_DOWNARROW ) ||
+ ( ( tolower(key) == 'n' ) && keys[K_CTRL].down ) ) {
+ if (historyLine == nextHistoryLine)
+ return;
+ historyLine++;
+ g_consoleField = historyEditLines[ historyLine % COMMAND_HISTORY ];
+ return;
+ }
+
+ // console scrolling
+ if ( key == K_PGUP ) {
+ Con_PageUp();
+ return;
+ }
+
+ if ( key == K_PGDN) {
+ Con_PageDown();
+ return;
+ }
+
+ if ( key == K_MWHEELUP) { //----(SA) added some mousewheel functionality to the console
+ Con_PageUp();
+ if(keys[K_CTRL].down) { // hold <ctrl> to accelerate scrolling
+ Con_PageUp();
+ Con_PageUp();
+ }
+ return;
+ }
+
+ if ( key == K_MWHEELDOWN) { //----(SA) added some mousewheel functionality to the console
+ Con_PageDown();
+ if(keys[K_CTRL].down) { // hold <ctrl> to accelerate scrolling
+ Con_PageDown();
+ Con_PageDown();
+ }
+ return;
+ }
+
+ // ctrl-home = top of console
+ if ( key == K_HOME && keys[K_CTRL].down ) {
+ Con_Top();
+ return;
+ }
+
+ // ctrl-end = bottom of console
+ if ( key == K_END && keys[K_CTRL].down ) {
+ Con_Bottom();
+ return;
+ }
+
+ // pass to the normal editline routine
+ Field_KeyDownEvent( &g_consoleField, key );
+}
+
+//============================================================================
+
+
+/*
+================
+Message_Key
+
+In game talk message
+================
+*/
+void Message_Key( int key ) {
+
+ char buffer[MAX_STRING_CHARS];
+
+
+ if (key == K_ESCAPE) {
+ cls.keyCatchers &= ~KEYCATCH_MESSAGE;
+ Field_Clear( &chatField );
+ return;
+ }
+
+ if ( key == K_ENTER || key == K_KP_ENTER )
+ {
+ if ( chatField.buffer[0] && cls.state == CA_ACTIVE ) {
+ if (chat_playerNum != -1 )
+
+ Com_sprintf( buffer, sizeof( buffer ), "tell %i \"%s\"\n", chat_playerNum, chatField.buffer );
+
+ else if (chat_team)
+
+ Com_sprintf( buffer, sizeof( buffer ), "say_team \"%s\"\n", chatField.buffer );
+ else
+ Com_sprintf( buffer, sizeof( buffer ), "say \"%s\"\n", chatField.buffer );
+
+
+
+ CL_AddReliableCommand( buffer );
+ }
+ cls.keyCatchers &= ~KEYCATCH_MESSAGE;
+ Field_Clear( &chatField );
+ return;
+ }
+
+ Field_KeyDownEvent( &chatField, key );
+}
+
+//============================================================================
+
+
+qboolean Key_GetOverstrikeMode( void ) {
+ return key_overstrikeMode;
+}
+
+
+void Key_SetOverstrikeMode( qboolean state ) {
+ key_overstrikeMode = state;
+}
+
+
+/*
+===================
+Key_IsDown
+===================
+*/
+qboolean Key_IsDown( int keynum ) {
+ if ( keynum == -1 ) {
+ return qfalse;
+ }
+
+ return keys[keynum].down;
+}
+
+
+/*
+===================
+Key_StringToKeynum
+
+Returns a key number to be used to index keys[] by looking at
+the given string. Single ascii characters return themselves, while
+the K_* names are matched up.
+
+0x11 will be interpreted as raw hex, which will allow new controlers
+
+to be configured even if they don't have defined names.
+===================
+*/
+int Key_StringToKeynum( char *str ) {
+ keyname_t *kn;
+
+ if ( !str || !str[0] ) {
+ return -1;
+ }
+ if ( !str[1] ) {
+ return str[0];
+ }
+
+ // check for hex code
+ if ( str[0] == '0' && str[1] == 'x' && strlen( str ) == 4) {
+ int n1, n2;
+
+ n1 = str[2];
+ if ( n1 >= '0' && n1 <= '9' ) {
+ n1 -= '0';
+ } else if ( n1 >= 'a' && n1 <= 'f' ) {
+ n1 = n1 - 'a' + 10;
+ } else {
+ n1 = 0;
+ }
+
+ n2 = str[3];
+ if ( n2 >= '0' && n2 <= '9' ) {
+ n2 -= '0';
+ } else if ( n2 >= 'a' && n2 <= 'f' ) {
+ n2 = n2 - 'a' + 10;
+ } else {
+ n2 = 0;
+ }
+
+ return n1 * 16 + n2;
+ }
+
+ // scan for a text match
+ for ( kn=keynames ; kn->name ; kn++ ) {
+ if ( !Q_stricmp( str,kn->name ) )
+ return kn->keynum;
+ }
+
+ return -1;
+}
+
+/*
+===================
+Key_KeynumToString
+
+Returns a string (either a single ascii char, a K_* name, or a 0x11 hex string) for the
+given keynum.
+===================
+*/
+char *Key_KeynumToString( int keynum ) {
+ keyname_t *kn;
+ static char tinystr[5];
+ int i, j;
+
+ if ( keynum == -1 ) {
+ return "<KEY NOT FOUND>";
+ }
+
+ if ( keynum < 0 || keynum > 255 ) {
+ return "<OUT OF RANGE>";
+ }
+
+ // check for printable ascii (don't use quote)
+ if ( keynum > 32 && keynum < 127 && keynum != '"' && keynum != ';' ) {
+ tinystr[0] = keynum;
+ tinystr[1] = 0;
+ return tinystr;
+ }
+
+ // check for a key string
+ for ( kn=keynames ; kn->name ; kn++ ) {
+ if (keynum == kn->keynum) {
+ return kn->name;
+ }
+ }
+
+ // make a hex string
+ i = keynum >> 4;
+ j = keynum & 15;
+
+ tinystr[0] = '0';
+ tinystr[1] = 'x';
+ tinystr[2] = i > 9 ? i - 10 + 'a' : i + '0';
+ tinystr[3] = j > 9 ? j - 10 + 'a' : j + '0';
+ tinystr[4] = 0;
+
+ return tinystr;
+}
+
+
+/*
+===================
+Key_SetBinding
+===================
+*/
+void Key_SetBinding( int keynum, const char *binding ) {
+ if ( keynum == -1 ) {
+ return;
+ }
+
+ // free old bindings
+ if ( keys[ keynum ].binding ) {
+ Z_Free( keys[ keynum ].binding );
+ }
+
+ // allocate memory for new binding
+ keys[keynum].binding = CopyString( binding );
+
+ // consider this like modifying an archived cvar, so the
+ // file write will be triggered at the next oportunity
+ cvar_modifiedFlags |= CVAR_ARCHIVE;
+}
+
+
+/*
+===================
+Key_GetBinding
+===================
+*/
+char *Key_GetBinding( int keynum ) {
+ if ( keynum == -1 ) {
+ return "";
+ }
+
+ return keys[ keynum ].binding;
+}
+
+/*
+===================
+Key_GetKey
+===================
+*/
+
+int Key_GetKey(const char *binding) {
+ int i;
+
+ if (binding) {
+ for (i=0 ; i<256 ; i++) {
+ if (keys[i].binding && Q_stricmp(binding, keys[i].binding) == 0) {
+ return i;
+ }
+ }
+ }
+ return -1;
+}
+
+/*
+===================
+Key_Unbind_f
+===================
+*/
+void Key_Unbind_f (void)
+{
+ int b;
+
+ if (Cmd_Argc() != 2)
+ {
+ Com_Printf ("unbind <key> : remove commands from a key\n");
+ return;
+ }
+
+ b = Key_StringToKeynum (Cmd_Argv(1));
+ if (b==-1)
+ {
+ Com_Printf ("\"%s\" isn't a valid key\n", Cmd_Argv(1));
+ return;
+ }
+
+ Key_SetBinding (b, "");
+}
+
+/*
+===================
+Key_Unbindall_f
+===================
+*/
+void Key_Unbindall_f (void)
+{
+ int i;
+
+ for (i=0 ; i<256 ; i++)
+ if (keys[i].binding)
+ Key_SetBinding (i, "");
+}
+
+
+/*
+===================
+Key_Bind_f
+===================
+*/
+void Key_Bind_f (void)
+{
+ int i, c, b;
+ char cmd[1024];
+
+ c = Cmd_Argc();
+
+ if (c < 2)
+ {
+ Com_Printf ("bind <key> [command] : attach a command to a key\n");
+ return;
+ }
+ b = Key_StringToKeynum (Cmd_Argv(1));
+ if (b==-1)
+ {
+ Com_Printf ("\"%s\" isn't a valid key\n", Cmd_Argv(1));
+ return;
+ }
+
+ if (c == 2)
+ {
+ if (keys[b].binding)
+ Com_Printf ("\"%s\" = \"%s\"\n", Cmd_Argv(1), keys[b].binding );
+ else
+ Com_Printf ("\"%s\" is not bound\n", Cmd_Argv(1) );
+ return;
+ }
+
+// copy the rest of the command line
+ cmd[0] = 0; // start out with a null string
+ for (i=2 ; i< c ; i++)
+ {
+ strcat (cmd, Cmd_Argv(i));
+ if (i != (c-1))
+ strcat (cmd, " ");
+ }
+
+ Key_SetBinding (b, cmd);
+}
+
+/*
+============
+Key_WriteBindings
+
+Writes lines containing "bind key value"
+============
+*/
+void Key_WriteBindings( fileHandle_t f ) {
+ int i;
+
+ FS_Printf (f, "unbindall\n" );
+
+ for (i=0 ; i<256 ; i++) {
+ if (keys[i].binding && keys[i].binding[0] ) {
+ FS_Printf (f, "bind %s \"%s\"\n", Key_KeynumToString(i), keys[i].binding);
+
+ }
+
+ }
+}
+
+
+/*
+============
+Key_Bindlist_f
+
+============
+*/
+void Key_Bindlist_f( void ) {
+ int i;
+
+ for ( i = 0 ; i < 256 ; i++ ) {
+ if ( keys[i].binding && keys[i].binding[0] ) {
+ Com_Printf( "%s \"%s\"\n", Key_KeynumToString(i), keys[i].binding );
+ }
+ }
+}
+
+/*
+===================
+CL_InitKeyCommands
+===================
+*/
+void CL_InitKeyCommands( void ) {
+ // register our functions
+ Cmd_AddCommand ("bind",Key_Bind_f);
+ Cmd_AddCommand ("unbind",Key_Unbind_f);
+ Cmd_AddCommand ("unbindall",Key_Unbindall_f);
+ Cmd_AddCommand ("bindlist",Key_Bindlist_f);
+}
+
+/*
+===================
+CL_AddKeyUpCommands
+===================
+*/
+void CL_AddKeyUpCommands( int key, char *kb ) {
+ int i;
+ char button[1024], *buttonPtr;
+ char cmd[1024];
+ qboolean keyevent;
+
+ if ( !kb ) {
+ return;
+ }
+ keyevent = qfalse;
+ buttonPtr = button;
+ for ( i = 0; ; i++ ) {
+ if ( kb[i] == ';' || !kb[i] ) {
+ *buttonPtr = '\0';
+ if ( button[0] == '+') {
+ // button commands add keynum and time as parms so that multiple
+ // sources can be discriminated and subframe corrected
+ Com_sprintf (cmd, sizeof(cmd), "-%s %i %i\n", button+1, key, time);
+ Cbuf_AddText (cmd);
+ keyevent = qtrue;
+ } else {
+ if (keyevent) {
+ // down-only command
+ Cbuf_AddText (button);
+ Cbuf_AddText ("\n");
+ }
+ }
+ buttonPtr = button;
+ while ( (kb[i] <= ' ' || kb[i] == ';') && kb[i] != 0 ) {
+ i++;
+ }
+ }
+ *buttonPtr++ = kb[i];
+ if ( !kb[i] ) {
+ break;
+ }
+ }
+}
+
+/*
+===================
+CL_KeyEvent
+
+Called by the system for both key up and key down events
+===================
+*/
+void CL_KeyEvent (int key, qboolean down, unsigned time) {
+ char *kb;
+ char cmd[1024];
+
+ // update auto-repeat status and BUTTON_ANY status
+ keys[key].down = down;
+
+ if (down) {
+ keys[key].repeats++;
+ if ( keys[key].repeats == 1) {
+ anykeydown++;
+ }
+ } else {
+ keys[key].repeats = 0;
+ anykeydown--;
+ if (anykeydown < 0) {
+ anykeydown = 0;
+ }
+ }
+
+#ifdef __linux__
+ if (key == K_ENTER)
+ {
+ if (down)
+ {
+ if (keys[K_ALT].down)
+ {
+ Key_ClearStates();
+ if (Cvar_VariableValue("r_fullscreen") == 0)
+ {
+ Com_Printf("Switching to fullscreen rendering\n");
+ Cvar_Set("r_fullscreen", "1");
+ }
+ else
+ {
+ Com_Printf("Switching to windowed rendering\n");
+ Cvar_Set("r_fullscreen", "0");
+ }
+ Cbuf_ExecuteText( EXEC_APPEND, "vid_restart\n");
+ return;
+ }
+ }
+ }
+#endif
+
+ // console key is hardcoded, so the user can never unbind it
+ if (key == '`' || key == '~') {
+ if (!down) {
+ return;
+ }
+ Con_ToggleConsole_f ();
+ return;
+ }
+
+
+ // keys can still be used for bound actions
+ if ( down && ( key < 128 || key == K_MOUSE1 ) && ( clc.demoplaying || cls.state == CA_CINEMATIC ) && !cls.keyCatchers) {
+
+ if (Cvar_VariableValue ("com_cameraMode") == 0) {
+ Cvar_Set ("nextdemo","");
+ key = K_ESCAPE;
+ }
+ }
+
+
+ // escape is always handled special
+ if ( key == K_ESCAPE && down ) {
+ if ( cls.keyCatchers & KEYCATCH_MESSAGE ) {
+ // clear message mode
+ Message_Key( key );
+ return;
+ }
+
+ // escape always gets out of CGAME stuff
+ if (cls.keyCatchers & KEYCATCH_CGAME) {
+ cls.keyCatchers &= ~KEYCATCH_CGAME;
+ VM_Call (cgvm, CG_EVENT_HANDLING, CGAME_EVENT_NONE);
+ return;
+ }
+
+ if ( !( cls.keyCatchers & KEYCATCH_UI ) ) {
+ if ( cls.state == CA_ACTIVE && !clc.demoplaying ) {
+ VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_INGAME );
+ }
+ else {
+ CL_Disconnect_f();
+ S_StopAllSounds();
+ VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_MAIN );
+ }
+ return;
+ }
+
+ VM_Call( uivm, UI_KEY_EVENT, key, down );
+ return;
+ }
+
+ //
+ // key up events only perform actions if the game key binding is
+ // a button command (leading + sign). These will be processed even in
+ // console mode and menu mode, to keep the character from continuing
+ // an action started before a mode switch.
+ //
+ if (!down) {
+ kb = keys[key].binding;
+
+ CL_AddKeyUpCommands( key, kb );
+
+ if ( cls.keyCatchers & KEYCATCH_UI && uivm ) {
+ VM_Call( uivm, UI_KEY_EVENT, key, down );
+ } else if ( cls.keyCatchers & KEYCATCH_CGAME && cgvm ) {
+ VM_Call( cgvm, CG_KEY_EVENT, key, down );
+ }
+
+ return;
+ }
+
+
+ // distribute the key down event to the apropriate handler
+ if ( cls.keyCatchers & KEYCATCH_CONSOLE ) {
+ Console_Key( key );
+ } else if ( cls.keyCatchers & KEYCATCH_UI ) {
+ if ( uivm ) {
+ VM_Call( uivm, UI_KEY_EVENT, key, down );
+ }
+ } else if ( cls.keyCatchers & KEYCATCH_CGAME ) {
+ if ( cgvm ) {
+ VM_Call( cgvm, CG_KEY_EVENT, key, down );
+ }
+ } else if ( cls.keyCatchers & KEYCATCH_MESSAGE ) {
+ Message_Key( key );
+ } else if ( cls.state == CA_DISCONNECTED ) {
+ Console_Key( key );
+ } else {
+ // send the bound action
+ kb = keys[key].binding;
+ if ( !kb ) {
+ if (key >= 200) {
+ Com_Printf ("%s is unbound, use controls menu to set.\n"
+ , Key_KeynumToString( key ) );
+ }
+ } else if (kb[0] == '+') {
+ int i;
+ char button[1024], *buttonPtr;
+ buttonPtr = button;
+ for ( i = 0; ; i++ ) {
+ if ( kb[i] == ';' || !kb[i] ) {
+ *buttonPtr = '\0';
+ if ( button[0] == '+') {
+ // button commands add keynum and time as parms so that multiple
+ // sources can be discriminated and subframe corrected
+ Com_sprintf (cmd, sizeof(cmd), "%s %i %i\n", button, key, time);
+ Cbuf_AddText (cmd);
+ } else {
+ // down-only command
+ Cbuf_AddText (button);
+ Cbuf_AddText ("\n");
+ }
+ buttonPtr = button;
+ while ( (kb[i] <= ' ' || kb[i] == ';') && kb[i] != 0 ) {
+ i++;
+ }
+ }
+ *buttonPtr++ = kb[i];
+ if ( !kb[i] ) {
+ break;
+ }
+ }
+ } else {
+ // down-only command
+ Cbuf_AddText (kb);
+ Cbuf_AddText ("\n");
+ }
+ }
+}
+
+
+/*
+===================
+CL_CharEvent
+
+Normal keyboard characters, already shifted / capslocked / etc
+===================
+*/
+void CL_CharEvent( int key ) {
+ // the console key should never be used as a char
+ if ( key == '`' || key == '~' ) {
+ return;
+ }
+
+ // distribute the key down event to the apropriate handler
+ if ( cls.keyCatchers & KEYCATCH_CONSOLE )
+ {
+ Field_CharEvent( &g_consoleField, key );
+ }
+ else if ( cls.keyCatchers & KEYCATCH_UI )
+ {
+ VM_Call( uivm, UI_KEY_EVENT, key | K_CHAR_FLAG, qtrue );
+ }
+ else if ( cls.keyCatchers & KEYCATCH_MESSAGE )
+ {
+ Field_CharEvent( &chatField, key );
+ }
+ else if ( cls.state == CA_DISCONNECTED )
+ {
+ Field_CharEvent( &g_consoleField, key );
+ }
+}
+
+
+/*
+===================
+Key_ClearStates
+===================
+*/
+void Key_ClearStates (void)
+{
+ int i;
+
+ anykeydown = qfalse;
+
+ for ( i=0 ; i < MAX_KEYS ; i++ ) {
+ if ( keys[i].down ) {
+ CL_KeyEvent( i, qfalse, 0 );
+
+ }
+ keys[i].down = 0;
+ keys[i].repeats = 0;
+ }
+}
+
diff --git a/code/client/cl_main.c b/code/client/cl_main.c
new file mode 100755
index 0000000..89d3b48
--- /dev/null
+++ b/code/client/cl_main.c
@@ -0,0 +1,3324 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// cl_main.c -- client main loop
+
+#include "client.h"
+#include <limits.h>
+
+cvar_t *cl_nodelta;
+cvar_t *cl_debugMove;
+
+cvar_t *cl_noprint;
+cvar_t *cl_motd;
+
+cvar_t *rcon_client_password;
+cvar_t *rconAddress;
+
+cvar_t *cl_timeout;
+cvar_t *cl_maxpackets;
+cvar_t *cl_packetdup;
+cvar_t *cl_timeNudge;
+cvar_t *cl_showTimeDelta;
+cvar_t *cl_freezeDemo;
+
+cvar_t *cl_shownet;
+cvar_t *cl_showSend;
+cvar_t *cl_timedemo;
+cvar_t *cl_avidemo;
+cvar_t *cl_forceavidemo;
+
+cvar_t *cl_freelook;
+cvar_t *cl_sensitivity;
+
+cvar_t *cl_mouseAccel;
+cvar_t *cl_showMouseRate;
+
+cvar_t *m_pitch;
+cvar_t *m_yaw;
+cvar_t *m_forward;
+cvar_t *m_side;
+cvar_t *m_filter;
+
+cvar_t *cl_activeAction;
+
+cvar_t *cl_motdString;
+
+cvar_t *cl_allowDownload;
+cvar_t *cl_conXOffset;
+cvar_t *cl_inGameVideo;
+
+cvar_t *cl_serverStatusResendTime;
+cvar_t *cl_trn;
+
+clientActive_t cl;
+clientConnection_t clc;
+clientStatic_t cls;
+vm_t *cgvm;
+
+// Structure containing functions exported from refresh DLL
+refexport_t re;
+
+ping_t cl_pinglist[MAX_PINGREQUESTS];
+
+typedef struct serverStatus_s
+{
+ char string[BIG_INFO_STRING];
+ netadr_t address;
+ int time, startTime;
+ qboolean pending;
+ qboolean print;
+ qboolean retrieved;
+} serverStatus_t;
+
+serverStatus_t cl_serverStatusList[MAX_SERVERSTATUSREQUESTS];
+int serverStatusCount;
+
+#if defined __USEA3D && defined __A3D_GEOM
+ void hA3Dg_ExportRenderGeom (refexport_t *incoming_re);
+#endif
+
+extern void SV_BotFrame( int time );
+void CL_CheckForResend( void );
+void CL_ShowIP_f(void);
+void CL_ServerStatus_f(void);
+void CL_ServerStatusResponse( netadr_t from, msg_t *msg );
+
+/*
+===============
+CL_CDDialog
+
+Called by Com_Error when a cd is needed
+===============
+*/
+void CL_CDDialog( void ) {
+ cls.cddialog = qtrue; // start it next frame
+}
+
+
+/*
+=======================================================================
+
+CLIENT RELIABLE COMMAND COMMUNICATION
+
+=======================================================================
+*/
+
+/*
+======================
+CL_AddReliableCommand
+
+The given command will be transmitted to the server, and is gauranteed to
+not have future usercmd_t executed before it is executed
+======================
+*/
+void CL_AddReliableCommand( const char *cmd ) {
+ int index;
+
+ // if we would be losing an old command that hasn't been acknowledged,
+ // we must drop the connection
+ if ( clc.reliableSequence - clc.reliableAcknowledge > MAX_RELIABLE_COMMANDS ) {
+ Com_Error( ERR_DROP, "Client command overflow" );
+ }
+ clc.reliableSequence++;
+ index = clc.reliableSequence & ( MAX_RELIABLE_COMMANDS - 1 );
+ Q_strncpyz( clc.reliableCommands[ index ], cmd, sizeof( clc.reliableCommands[ index ] ) );
+}
+
+/*
+======================
+CL_ChangeReliableCommand
+======================
+*/
+void CL_ChangeReliableCommand( void ) {
+ int r, index, l;
+
+ r = clc.reliableSequence - (random() * 5);
+ index = clc.reliableSequence & ( MAX_RELIABLE_COMMANDS - 1 );
+ l = strlen(clc.reliableCommands[ index ]);
+ if ( l >= MAX_STRING_CHARS - 1 ) {
+ l = MAX_STRING_CHARS - 2;
+ }
+ clc.reliableCommands[ index ][ l ] = '\n';
+ clc.reliableCommands[ index ][ l+1 ] = '\0';
+}
+
+/*
+=======================================================================
+
+CLIENT SIDE DEMO RECORDING
+
+=======================================================================
+*/
+
+/*
+====================
+CL_WriteDemoMessage
+
+Dumps the current net message, prefixed by the length
+====================
+*/
+void CL_WriteDemoMessage ( msg_t *msg, int headerBytes ) {
+ int len, swlen;
+
+ // write the packet sequence
+ len = clc.serverMessageSequence;
+ swlen = LittleLong( len );
+ FS_Write (&swlen, 4, clc.demofile);
+
+ // skip the packet sequencing information
+ len = msg->cursize - headerBytes;
+ swlen = LittleLong(len);
+ FS_Write (&swlen, 4, clc.demofile);
+ FS_Write ( msg->data + headerBytes, len, clc.demofile );
+}
+
+
+/*
+====================
+CL_StopRecording_f
+
+stop recording a demo
+====================
+*/
+void CL_StopRecord_f( void ) {
+ int len;
+
+ if ( !clc.demorecording ) {
+ Com_Printf ("Not recording a demo.\n");
+ return;
+ }
+
+ // finish up
+ len = -1;
+ FS_Write (&len, 4, clc.demofile);
+ FS_Write (&len, 4, clc.demofile);
+ FS_FCloseFile (clc.demofile);
+ clc.demofile = 0;
+ clc.demorecording = qfalse;
+ clc.spDemoRecording = qfalse;
+ Com_Printf ("Stopped demo.\n");
+}
+
+/*
+==================
+CL_DemoFilename
+==================
+*/
+void CL_DemoFilename( int number, char *fileName ) {
+ int a,b,c,d;
+
+ if ( number < 0 || number > 9999 ) {
+ Com_sprintf( fileName, MAX_OSPATH, "demo9999.tga" );
+ return;
+ }
+
+ a = number / 1000;
+ number -= a*1000;
+ b = number / 100;
+ number -= b*100;
+ c = number / 10;
+ number -= c*10;
+ d = number;
+
+ Com_sprintf( fileName, MAX_OSPATH, "demo%i%i%i%i"
+ , a, b, c, d );
+}
+
+/*
+====================
+CL_Record_f
+
+record <demoname>
+
+Begins recording a demo from the current position
+====================
+*/
+static char demoName[MAX_QPATH]; // compiler bug workaround
+void CL_Record_f( void ) {
+ char name[MAX_OSPATH];
+ byte bufData[MAX_MSGLEN];
+ msg_t buf;
+ int i;
+ int len;
+ entityState_t *ent;
+ entityState_t nullstate;
+ char *s;
+
+ if ( Cmd_Argc() > 2 ) {
+ Com_Printf ("record <demoname>\n");
+ return;
+ }
+
+ if ( clc.demorecording ) {
+ if (!clc.spDemoRecording) {
+ Com_Printf ("Already recording.\n");
+ }
+ return;
+ }
+
+ if ( cls.state != CA_ACTIVE ) {
+ Com_Printf ("You must be in a level to record.\n");
+ return;
+ }
+
+ // sync 0 doesn't prevent recording, so not forcing it off .. everyone does g_sync 1 ; record ; g_sync 0 ..
+ if ( !Cvar_VariableValue( "g_synchronousClients" ) ) {
+ Com_Printf (S_COLOR_YELLOW "WARNING: You should set 'g_synchronousClients 1' for smoother demo recording\n");
+ }
+
+ if ( Cmd_Argc() == 2 ) {
+ s = Cmd_Argv(1);
+ Q_strncpyz( demoName, s, sizeof( demoName ) );
+ Com_sprintf (name, sizeof(name), "demos/%s.dm_%d", demoName, PROTOCOL_VERSION );
+ } else {
+ int number;
+
+ // scan for a free demo name
+ for ( number = 0 ; number <= 9999 ; number++ ) {
+ CL_DemoFilename( number, demoName );
+ Com_sprintf (name, sizeof(name), "demos/%s.dm_%d", demoName, PROTOCOL_VERSION );
+
+ len = FS_ReadFile( name, NULL );
+ if ( len <= 0 ) {
+ break; // file doesn't exist
+ }
+ }
+ }
+
+ // open the demo file
+
+ Com_Printf ("recording to %s.\n", name);
+ clc.demofile = FS_FOpenFileWrite( name );
+ if ( !clc.demofile ) {
+ Com_Printf ("ERROR: couldn't open.\n");
+ return;
+ }
+ clc.demorecording = qtrue;
+ if (Cvar_VariableValue("ui_recordSPDemo")) {
+ clc.spDemoRecording = qtrue;
+ } else {
+ clc.spDemoRecording = qfalse;
+ }
+
+
+ Q_strncpyz( clc.demoName, demoName, sizeof( clc.demoName ) );
+
+ // don't start saving messages until a non-delta compressed message is received
+ clc.demowaiting = qtrue;
+
+ // write out the gamestate message
+ MSG_Init (&buf, bufData, sizeof(bufData));
+ MSG_Bitstream(&buf);
+
+ // NOTE, MRE: all server->client messages now acknowledge
+ MSG_WriteLong( &buf, clc.reliableSequence );
+
+ MSG_WriteByte (&buf, svc_gamestate);
+ MSG_WriteLong (&buf, clc.serverCommandSequence );
+
+ // configstrings
+ for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) {
+ if ( !cl.gameState.stringOffsets[i] ) {
+ continue;
+ }
+ s = cl.gameState.stringData + cl.gameState.stringOffsets[i];
+ MSG_WriteByte (&buf, svc_configstring);
+ MSG_WriteShort (&buf, i);
+ MSG_WriteBigString (&buf, s);
+ }
+
+ // baselines
+ Com_Memset (&nullstate, 0, sizeof(nullstate));
+ for ( i = 0; i < MAX_GENTITIES ; i++ ) {
+ ent = &cl.entityBaselines[i];
+ if ( !ent->number ) {
+ continue;
+ }
+ MSG_WriteByte (&buf, svc_baseline);
+ MSG_WriteDeltaEntity (&buf, &nullstate, ent, qtrue );
+ }
+
+ MSG_WriteByte( &buf, svc_EOF );
+
+ // finished writing the gamestate stuff
+
+ // write the client num
+ MSG_WriteLong(&buf, clc.clientNum);
+ // write the checksum feed
+ MSG_WriteLong(&buf, clc.checksumFeed);
+
+ // finished writing the client packet
+ MSG_WriteByte( &buf, svc_EOF );
+
+ // write it to the demo file
+ len = LittleLong( clc.serverMessageSequence - 1 );
+ FS_Write (&len, 4, clc.demofile);
+
+ len = LittleLong (buf.cursize);
+ FS_Write (&len, 4, clc.demofile);
+ FS_Write (buf.data, buf.cursize, clc.demofile);
+
+ // the rest of the demo file will be copied from net messages
+}
+
+/*
+=======================================================================
+
+CLIENT SIDE DEMO PLAYBACK
+
+=======================================================================
+*/
+
+/*
+=================
+CL_DemoCompleted
+=================
+*/
+void CL_DemoCompleted( void ) {
+ if (cl_timedemo && cl_timedemo->integer) {
+ int time;
+
+ time = Sys_Milliseconds() - clc.timeDemoStart;
+ if ( time > 0 ) {
+ Com_Printf ("%i frames, %3.1f seconds: %3.1f fps\n", clc.timeDemoFrames,
+ time/1000.0, clc.timeDemoFrames*1000.0 / time);
+ }
+ }
+
+ CL_Disconnect( qtrue );
+ CL_NextDemo();
+}
+
+/*
+=================
+CL_ReadDemoMessage
+=================
+*/
+void CL_ReadDemoMessage( void ) {
+ int r;
+ msg_t buf;
+ byte bufData[ MAX_MSGLEN ];
+ int s;
+
+ if ( !clc.demofile ) {
+ CL_DemoCompleted ();
+ return;
+ }
+
+ // get the sequence number
+ r = FS_Read( &s, 4, clc.demofile);
+ if ( r != 4 ) {
+ CL_DemoCompleted ();
+ return;
+ }
+ clc.serverMessageSequence = LittleLong( s );
+
+ // init the message
+ MSG_Init( &buf, bufData, sizeof( bufData ) );
+
+ // get the length
+ r = FS_Read (&buf.cursize, 4, clc.demofile);
+ if ( r != 4 ) {
+ CL_DemoCompleted ();
+ return;
+ }
+ buf.cursize = LittleLong( buf.cursize );
+ if ( buf.cursize == -1 ) {
+ CL_DemoCompleted ();
+ return;
+ }
+ if ( buf.cursize > buf.maxsize ) {
+ Com_Error (ERR_DROP, "CL_ReadDemoMessage: demoMsglen > MAX_MSGLEN");
+ }
+ r = FS_Read( buf.data, buf.cursize, clc.demofile );
+ if ( r != buf.cursize ) {
+ Com_Printf( "Demo file was truncated.\n");
+ CL_DemoCompleted ();
+ return;
+ }
+
+ clc.lastPacketTime = cls.realtime;
+ buf.readcount = 0;
+ CL_ParseServerMessage( &buf );
+}
+
+/*
+====================
+CL_WalkDemoExt
+====================
+*/
+static void CL_WalkDemoExt(char *arg, char *name, int *demofile)
+{
+ int i = 0;
+ *demofile = 0;
+ while(demo_protocols[i])
+ {
+ Com_sprintf (name, MAX_OSPATH, "demos/%s.dm_%d", arg, demo_protocols[i]);
+ FS_FOpenFileRead( name, demofile, qtrue );
+ if (*demofile)
+ {
+ Com_Printf("Demo file: %s\n", name);
+ break;
+ }
+ else
+ Com_Printf("Not found: %s\n", name);
+ i++;
+ }
+}
+
+/*
+====================
+CL_PlayDemo_f
+
+demo <demoname>
+
+====================
+*/
+void CL_PlayDemo_f( void ) {
+ char name[MAX_OSPATH];
+ char *arg, *ext_test;
+ int protocol, i;
+ char retry[MAX_OSPATH];
+
+ if (Cmd_Argc() != 2) {
+ Com_Printf ("playdemo <demoname>\n");
+ return;
+ }
+
+ // make sure a local server is killed
+ Cvar_Set( "sv_killserver", "1" );
+
+ CL_Disconnect( qtrue );
+
+ // open the demo file
+ arg = Cmd_Argv(1);
+
+ // check for an extension .dm_?? (?? is protocol)
+ ext_test = arg + strlen(arg) - 6;
+ if ((strlen(arg) > 6) && (ext_test[0] == '.') && ((ext_test[1] == 'd') || (ext_test[1] == 'D')) && ((ext_test[2] == 'm') || (ext_test[2] == 'M')) && (ext_test[3] == '_'))
+ {
+ protocol = atoi(ext_test+4);
+ i=0;
+ while(demo_protocols[i])
+ {
+ if (demo_protocols[i] == protocol)
+ break;
+ i++;
+ }
+ if (demo_protocols[i])
+ {
+ Com_sprintf (name, sizeof(name), "demos/%s", arg);
+ FS_FOpenFileRead( name, &clc.demofile, qtrue );
+ } else {
+ Com_Printf("Protocol %d not supported for demos\n", protocol);
+ Q_strncpyz(retry, arg, sizeof(retry));
+ retry[strlen(retry)-6] = 0;
+ CL_WalkDemoExt( retry, name, &clc.demofile );
+ }
+ } else {
+ CL_WalkDemoExt( arg, name, &clc.demofile );
+ }
+
+ if (!clc.demofile) {
+ Com_Error( ERR_DROP, "couldn't open %s", name);
+ return;
+ }
+ Q_strncpyz( clc.demoName, Cmd_Argv(1), sizeof( clc.demoName ) );
+
+ Con_Close();
+
+ cls.state = CA_CONNECTED;
+ clc.demoplaying = qtrue;
+ Q_strncpyz( cls.servername, Cmd_Argv(1), sizeof( cls.servername ) );
+
+ // read demo messages until connected
+ while ( cls.state >= CA_CONNECTED && cls.state < CA_PRIMED ) {
+ CL_ReadDemoMessage();
+ }
+ // don't get the first snapshot this frame, to prevent the long
+ // time from the gamestate load from messing causing a time skip
+ clc.firstDemoFrameSkipped = qfalse;
+}
+
+
+/*
+====================
+CL_StartDemoLoop
+
+Closing the main menu will restart the demo loop
+====================
+*/
+void CL_StartDemoLoop( void ) {
+ // start the demo loop again
+ Cbuf_AddText ("d1\n");
+ cls.keyCatchers = 0;
+}
+
+/*
+==================
+CL_NextDemo
+
+Called when a demo or cinematic finishes
+If the "nextdemo" cvar is set, that command will be issued
+==================
+*/
+void CL_NextDemo( void ) {
+ char v[MAX_STRING_CHARS];
+
+ Q_strncpyz( v, Cvar_VariableString ("nextdemo"), sizeof(v) );
+ v[MAX_STRING_CHARS-1] = 0;
+ Com_DPrintf("CL_NextDemo: %s\n", v );
+ if (!v[0]) {
+ return;
+ }
+
+ Cvar_Set ("nextdemo","");
+ Cbuf_AddText (v);
+ Cbuf_AddText ("\n");
+ Cbuf_Execute();
+}
+
+
+//======================================================================
+
+/*
+=====================
+CL_ShutdownAll
+=====================
+*/
+void CL_ShutdownAll(void) {
+
+ // clear sounds
+ S_DisableSounds();
+ // shutdown CGame
+ CL_ShutdownCGame();
+ // shutdown UI
+ CL_ShutdownUI();
+
+ // shutdown the renderer
+ if ( re.Shutdown ) {
+ re.Shutdown( qfalse ); // don't destroy window or context
+ }
+
+ cls.uiStarted = qfalse;
+ cls.cgameStarted = qfalse;
+ cls.rendererStarted = qfalse;
+ cls.soundRegistered = qfalse;
+}
+
+/*
+=================
+CL_FlushMemory
+
+Called by CL_MapLoading, CL_Connect_f, CL_PlayDemo_f, and CL_ParseGamestate the only
+ways a client gets into a game
+Also called by Com_Error
+=================
+*/
+void CL_FlushMemory( void ) {
+
+ // shutdown all the client stuff
+ CL_ShutdownAll();
+
+ // if not running a server clear the whole hunk
+ if ( !com_sv_running->integer ) {
+ // clear the whole hunk
+ Hunk_Clear();
+ // clear collision map data
+ CM_ClearMap();
+ }
+ else {
+ // clear all the client data on the hunk
+ Hunk_ClearToMark();
+ }
+
+ CL_StartHunkUsers();
+}
+
+/*
+=====================
+CL_MapLoading
+
+A local server is starting to load a map, so update the
+screen to let the user know about it, then dump all client
+memory on the hunk from cgame, ui, and renderer
+=====================
+*/
+void CL_MapLoading( void ) {
+ if ( !com_cl_running->integer ) {
+ return;
+ }
+
+ Con_Close();
+ cls.keyCatchers = 0;
+
+ // if we are already connected to the local host, stay connected
+ if ( cls.state >= CA_CONNECTED && !Q_stricmp( cls.servername, "localhost" ) ) {
+ cls.state = CA_CONNECTED; // so the connect screen is drawn
+ Com_Memset( cls.updateInfoString, 0, sizeof( cls.updateInfoString ) );
+ Com_Memset( clc.serverMessage, 0, sizeof( clc.serverMessage ) );
+ Com_Memset( &cl.gameState, 0, sizeof( cl.gameState ) );
+ clc.lastPacketSentTime = -9999;
+ SCR_UpdateScreen();
+ } else {
+ // clear nextmap so the cinematic shutdown doesn't execute it
+ Cvar_Set( "nextmap", "" );
+ CL_Disconnect( qtrue );
+ Q_strncpyz( cls.servername, "localhost", sizeof(cls.servername) );
+ cls.state = CA_CHALLENGING; // so the connect screen is drawn
+ cls.keyCatchers = 0;
+ SCR_UpdateScreen();
+ clc.connectTime = -RETRANSMIT_TIMEOUT;
+ NET_StringToAdr( cls.servername, &clc.serverAddress);
+ // we don't need a challenge on the localhost
+
+ CL_CheckForResend();
+ }
+}
+
+/*
+=====================
+CL_ClearState
+
+Called before parsing a gamestate
+=====================
+*/
+void CL_ClearState (void) {
+
+// S_StopAllSounds();
+
+ Com_Memset( &cl, 0, sizeof( cl ) );
+}
+
+
+/*
+=====================
+CL_Disconnect
+
+Called when a connection, demo, or cinematic is being terminated.
+Goes from a connected state to either a menu state or a console state
+Sends a disconnect message to the server
+This is also called on Com_Error and Com_Quit, so it shouldn't cause any errors
+=====================
+*/
+void CL_Disconnect( qboolean showMainMenu ) {
+ if ( !com_cl_running || !com_cl_running->integer ) {
+ return;
+ }
+
+ // shutting down the client so enter full screen ui mode
+ Cvar_Set("r_uiFullScreen", "1");
+
+ if ( clc.demorecording ) {
+ CL_StopRecord_f ();
+ }
+
+ if (clc.download) {
+ FS_FCloseFile( clc.download );
+ clc.download = 0;
+ }
+ *clc.downloadTempName = *clc.downloadName = 0;
+ Cvar_Set( "cl_downloadName", "" );
+
+ if ( clc.demofile ) {
+ FS_FCloseFile( clc.demofile );
+ clc.demofile = 0;
+ }
+
+ if ( uivm && showMainMenu ) {
+ VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_NONE );
+ }
+
+ SCR_StopCinematic ();
+ S_ClearSoundBuffer();
+
+ // send a disconnect message to the server
+ // send it a few times in case one is dropped
+ if ( cls.state >= CA_CONNECTED ) {
+ CL_AddReliableCommand( "disconnect" );
+ CL_WritePacket();
+ CL_WritePacket();
+ CL_WritePacket();
+ }
+
+ CL_ClearState ();
+
+ // wipe the client connection
+ Com_Memset( &clc, 0, sizeof( clc ) );
+
+ cls.state = CA_DISCONNECTED;
+
+ // allow cheats locally
+ Cvar_Set( "sv_cheats", "1" );
+
+ // not connected to a pure server anymore
+ cl_connectedToPureServer = qfalse;
+}
+
+
+/*
+===================
+CL_ForwardCommandToServer
+
+adds the current command line as a clientCommand
+things like godmode, noclip, etc, are commands directed to the server,
+so when they are typed in at the console, they will need to be forwarded.
+===================
+*/
+void CL_ForwardCommandToServer( const char *string ) {
+ char *cmd;
+
+ cmd = Cmd_Argv(0);
+
+ // ignore key up commands
+ if ( cmd[0] == '-' ) {
+ return;
+ }
+
+ if ( clc.demoplaying || cls.state < CA_CONNECTED || cmd[0] == '+' ) {
+ Com_Printf ("Unknown command \"%s\"\n", cmd);
+ return;
+ }
+
+ if ( Cmd_Argc() > 1 ) {
+ CL_AddReliableCommand( string );
+ } else {
+ CL_AddReliableCommand( cmd );
+ }
+}
+
+/*
+===================
+CL_RequestMotd
+
+===================
+*/
+void CL_RequestMotd( void ) {
+ char info[MAX_INFO_STRING];
+
+ if ( !cl_motd->integer ) {
+ return;
+ }
+ Com_Printf( "Resolving %s\n", UPDATE_SERVER_NAME );
+ if ( !NET_StringToAdr( UPDATE_SERVER_NAME, &cls.updateServer ) ) {
+ Com_Printf( "Couldn't resolve address\n" );
+ return;
+ }
+ cls.updateServer.port = BigShort( PORT_UPDATE );
+ Com_Printf( "%s resolved to %i.%i.%i.%i:%i\n", UPDATE_SERVER_NAME,
+ cls.updateServer.ip[0], cls.updateServer.ip[1],
+ cls.updateServer.ip[2], cls.updateServer.ip[3],
+ BigShort( cls.updateServer.port ) );
+
+ info[0] = 0;
+ // NOTE TTimo xoring against Com_Milliseconds, otherwise we may not have a true randomization
+ // only srand I could catch before here is tr_noise.c l:26 srand(1001)
+ // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=382
+ // NOTE: the Com_Milliseconds xoring only affects the lower 16-bit word,
+ // but I decided it was enough randomization
+ Com_sprintf( cls.updateChallenge, sizeof( cls.updateChallenge ), "%i", ((rand() << 16) ^ rand()) ^ Com_Milliseconds());
+
+ Info_SetValueForKey( info, "challenge", cls.updateChallenge );
+ Info_SetValueForKey( info, "renderer", cls.glconfig.renderer_string );
+ Info_SetValueForKey( info, "version", com_version->string );
+
+ NET_OutOfBandPrint( NS_CLIENT, cls.updateServer, "getmotd \"%s\"\n", info );
+}
+
+/*
+===================
+CL_RequestAuthorization
+
+Authorization server protocol
+-----------------------------
+
+All commands are text in Q3 out of band packets (leading 0xff 0xff 0xff 0xff).
+
+Whenever the client tries to get a challenge from the server it wants to
+connect to, it also blindly fires off a packet to the authorize server:
+
+getKeyAuthorize <challenge> <cdkey>
+
+cdkey may be "demo"
+
+
+#OLD The authorize server returns a:
+#OLD
+#OLD keyAthorize <challenge> <accept | deny>
+#OLD
+#OLD A client will be accepted if the cdkey is valid and it has not been used by any other IP
+#OLD address in the last 15 minutes.
+
+
+The server sends a:
+
+getIpAuthorize <challenge> <ip>
+
+The authorize server returns a:
+
+ipAuthorize <challenge> <accept | deny | demo | unknown >
+
+A client will be accepted if a valid cdkey was sent by that ip (only) in the last 15 minutes.
+If no response is received from the authorize server after two tries, the client will be let
+in anyway.
+===================
+*/
+void CL_RequestAuthorization( void ) {
+ char nums[64];
+ int i, j, l;
+ cvar_t *fs;
+
+ if ( !cls.authorizeServer.port ) {
+ Com_Printf( "Resolving %s\n", AUTHORIZE_SERVER_NAME );
+ if ( !NET_StringToAdr( AUTHORIZE_SERVER_NAME, &cls.authorizeServer ) ) {
+ Com_Printf( "Couldn't resolve address\n" );
+ return;
+ }
+
+ cls.authorizeServer.port = BigShort( PORT_AUTHORIZE );
+ Com_Printf( "%s resolved to %i.%i.%i.%i:%i\n", AUTHORIZE_SERVER_NAME,
+ cls.authorizeServer.ip[0], cls.authorizeServer.ip[1],
+ cls.authorizeServer.ip[2], cls.authorizeServer.ip[3],
+ BigShort( cls.authorizeServer.port ) );
+ }
+ if ( cls.authorizeServer.type == NA_BAD ) {
+ return;
+ }
+
+ if ( Cvar_VariableValue( "fs_restrict" ) ) {
+ Q_strncpyz( nums, "demota", sizeof( nums ) );
+ } else {
+ // only grab the alphanumeric values from the cdkey, to avoid any dashes or spaces
+ j = 0;
+ l = strlen( cl_cdkey );
+ if ( l > 32 ) {
+ l = 32;
+ }
+ for ( i = 0 ; i < l ; i++ ) {
+ if ( ( cl_cdkey[i] >= '0' && cl_cdkey[i] <= '9' )
+ || ( cl_cdkey[i] >= 'a' && cl_cdkey[i] <= 'z' )
+ || ( cl_cdkey[i] >= 'A' && cl_cdkey[i] <= 'Z' )
+ ) {
+ nums[j] = cl_cdkey[i];
+ j++;
+ }
+ }
+ nums[j] = 0;
+ }
+
+ fs = Cvar_Get ("cl_anonymous", "0", CVAR_INIT|CVAR_SYSTEMINFO );
+
+ NET_OutOfBandPrint(NS_CLIENT, cls.authorizeServer, va("getKeyAuthorize %i %s", fs->integer, nums) );
+}
+
+/*
+======================================================================
+
+CONSOLE COMMANDS
+
+======================================================================
+*/
+
+/*
+==================
+CL_ForwardToServer_f
+==================
+*/
+void CL_ForwardToServer_f( void ) {
+ if ( cls.state != CA_ACTIVE || clc.demoplaying ) {
+ Com_Printf ("Not connected to a server.\n");
+ return;
+ }
+
+ // don't forward the first argument
+ if ( Cmd_Argc() > 1 ) {
+ CL_AddReliableCommand( Cmd_Args() );
+ }
+}
+
+/*
+==================
+CL_Setenv_f
+
+Mostly for controlling voodoo environment variables
+==================
+*/
+void CL_Setenv_f( void ) {
+ int argc = Cmd_Argc();
+
+ if ( argc > 2 ) {
+ char buffer[1024];
+ int i;
+
+ strcpy( buffer, Cmd_Argv(1) );
+ strcat( buffer, "=" );
+
+ for ( i = 2; i < argc; i++ ) {
+ strcat( buffer, Cmd_Argv( i ) );
+ strcat( buffer, " " );
+ }
+
+ putenv( buffer );
+ } else if ( argc == 2 ) {
+ char *env = getenv( Cmd_Argv(1) );
+
+ if ( env ) {
+ Com_Printf( "%s=%s\n", Cmd_Argv(1), env );
+ } else {
+ Com_Printf( "%s undefined\n", Cmd_Argv(1), env );
+ }
+ }
+}
+
+
+/*
+==================
+CL_Disconnect_f
+==================
+*/
+void CL_Disconnect_f( void ) {
+ SCR_StopCinematic();
+ Cvar_Set("ui_singlePlayerActive", "0");
+ if ( cls.state != CA_DISCONNECTED && cls.state != CA_CINEMATIC ) {
+ Com_Error (ERR_DISCONNECT, "Disconnected from server");
+ }
+}
+
+
+/*
+================
+CL_Reconnect_f
+
+================
+*/
+void CL_Reconnect_f( void ) {
+ if ( !strlen( cls.servername ) || !strcmp( cls.servername, "localhost" ) ) {
+ Com_Printf( "Can't reconnect to localhost.\n" );
+ return;
+ }
+ Cvar_Set("ui_singlePlayerActive", "0");
+ Cbuf_AddText( va("connect %s\n", cls.servername ) );
+}
+
+/*
+================
+CL_Connect_f
+
+================
+*/
+void CL_Connect_f( void ) {
+ char *server;
+
+ if ( Cmd_Argc() != 2 ) {
+ Com_Printf( "usage: connect [server]\n");
+ return;
+ }
+
+ Cvar_Set("ui_singlePlayerActive", "0");
+
+ // fire a message off to the motd server
+ CL_RequestMotd();
+
+ // clear any previous "server full" type messages
+ clc.serverMessage[0] = 0;
+
+ server = Cmd_Argv (1);
+
+ if ( com_sv_running->integer && !strcmp( server, "localhost" ) ) {
+ // if running a local server, kill it
+ SV_Shutdown( "Server quit\n" );
+ }
+
+ // make sure a local server is killed
+ Cvar_Set( "sv_killserver", "1" );
+ SV_Frame( 0 );
+
+ CL_Disconnect( qtrue );
+ Con_Close();
+
+ /* MrE: 2000-09-13: now called in CL_DownloadsComplete
+ CL_FlushMemory( );
+ */
+
+ Q_strncpyz( cls.servername, server, sizeof(cls.servername) );
+
+ if (!NET_StringToAdr( cls.servername, &clc.serverAddress) ) {
+ Com_Printf ("Bad server address\n");
+ cls.state = CA_DISCONNECTED;
+ return;
+ }
+ if (clc.serverAddress.port == 0) {
+ clc.serverAddress.port = BigShort( PORT_SERVER );
+ }
+ Com_Printf( "%s resolved to %i.%i.%i.%i:%i\n", cls.servername,
+ clc.serverAddress.ip[0], clc.serverAddress.ip[1],
+ clc.serverAddress.ip[2], clc.serverAddress.ip[3],
+ BigShort( clc.serverAddress.port ) );
+
+ // if we aren't playing on a lan, we need to authenticate
+ // with the cd key
+ if ( NET_IsLocalAddress( clc.serverAddress ) ) {
+ cls.state = CA_CHALLENGING;
+ } else {
+ cls.state = CA_CONNECTING;
+ }
+
+ cls.keyCatchers = 0;
+ clc.connectTime = -99999; // CL_CheckForResend() will fire immediately
+ clc.connectPacketCount = 0;
+
+ // server connection string
+ Cvar_Set( "cl_currentServerAddress", server );
+}
+
+
+/*
+=====================
+CL_Rcon_f
+
+ Send the rest of the command line over as
+ an unconnected command.
+=====================
+*/
+void CL_Rcon_f( void ) {
+ char message[1024];
+ netadr_t to;
+
+ if ( !rcon_client_password->string ) {
+ Com_Printf ("You must set 'rconpassword' before\n"
+ "issuing an rcon command.\n");
+ return;
+ }
+
+ message[0] = -1;
+ message[1] = -1;
+ message[2] = -1;
+ message[3] = -1;
+ message[4] = 0;
+
+ strcat (message, "rcon ");
+
+ strcat (message, rcon_client_password->string);
+ strcat (message, " ");
+
+ // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=543
+ strcat (message, Cmd_Cmd()+5);
+
+ if ( cls.state >= CA_CONNECTED ) {
+ to = clc.netchan.remoteAddress;
+ } else {
+ if (!strlen(rconAddress->string)) {
+ Com_Printf ("You must either be connected,\n"
+ "or set the 'rconAddress' cvar\n"
+ "to issue rcon commands\n");
+
+ return;
+ }
+ NET_StringToAdr (rconAddress->string, &to);
+ if (to.port == 0) {
+ to.port = BigShort (PORT_SERVER);
+ }
+ }
+
+ NET_SendPacket (NS_CLIENT, strlen(message)+1, message, to);
+}
+
+/*
+=================
+CL_SendPureChecksums
+=================
+*/
+void CL_SendPureChecksums( void ) {
+ const char *pChecksums;
+ char cMsg[MAX_INFO_VALUE];
+ int i;
+
+ // if we are pure we need to send back a command with our referenced pk3 checksums
+ pChecksums = FS_ReferencedPakPureChecksums();
+
+ // "cp"
+ // "Yf"
+ Com_sprintf(cMsg, sizeof(cMsg), "Yf ");
+ Q_strcat(cMsg, sizeof(cMsg), va("%d ", cl.serverId) );
+ Q_strcat(cMsg, sizeof(cMsg), pChecksums);
+ for (i = 0; i < 2; i++) {
+ cMsg[i] += 10;
+ }
+ CL_AddReliableCommand( cMsg );
+}
+
+/*
+=================
+CL_ResetPureClientAtServer
+=================
+*/
+void CL_ResetPureClientAtServer( void ) {
+ CL_AddReliableCommand( va("vdr") );
+}
+
+/*
+=================
+CL_Vid_Restart_f
+
+Restart the video subsystem
+
+we also have to reload the UI and CGame because the renderer
+doesn't know what graphics to reload
+=================
+*/
+void CL_Vid_Restart_f( void ) {
+
+ // don't let them loop during the restart
+ S_StopAllSounds();
+ // shutdown the UI
+ CL_ShutdownUI();
+ // shutdown the CGame
+ CL_ShutdownCGame();
+ // shutdown the renderer and clear the renderer interface
+ CL_ShutdownRef();
+ // client is no longer pure untill new checksums are sent
+ CL_ResetPureClientAtServer();
+ // clear pak references
+ FS_ClearPakReferences( FS_UI_REF | FS_CGAME_REF );
+ // reinitialize the filesystem if the game directory or checksum has changed
+ FS_ConditionalRestart( clc.checksumFeed );
+
+ cls.rendererStarted = qfalse;
+ cls.uiStarted = qfalse;
+ cls.cgameStarted = qfalse;
+ cls.soundRegistered = qfalse;
+
+ // unpause so the cgame definately gets a snapshot and renders a frame
+ Cvar_Set( "cl_paused", "0" );
+
+ // if not running a server clear the whole hunk
+ if ( !com_sv_running->integer ) {
+ // clear the whole hunk
+ Hunk_Clear();
+ }
+ else {
+ // clear all the client data on the hunk
+ Hunk_ClearToMark();
+ }
+
+ // initialize the renderer interface
+ CL_InitRef();
+
+ // startup all the client stuff
+ CL_StartHunkUsers();
+
+ // start the cgame if connected
+ if ( cls.state > CA_CONNECTED && cls.state != CA_CINEMATIC ) {
+ cls.cgameStarted = qtrue;
+ CL_InitCGame();
+ // send pure checksums
+ CL_SendPureChecksums();
+ }
+}
+
+/*
+=================
+CL_Snd_Restart_f
+
+Restart the sound subsystem
+The cgame and game must also be forced to restart because
+handles will be invalid
+=================
+*/
+void CL_Snd_Restart_f( void ) {
+ S_Shutdown();
+ S_Init();
+
+ CL_Vid_Restart_f();
+}
+
+
+/*
+==================
+CL_PK3List_f
+==================
+*/
+void CL_OpenedPK3List_f( void ) {
+ Com_Printf("Opened PK3 Names: %s\n", FS_LoadedPakNames());
+}
+
+/*
+==================
+CL_PureList_f
+==================
+*/
+void CL_ReferencedPK3List_f( void ) {
+ Com_Printf("Referenced PK3 Names: %s\n", FS_ReferencedPakNames());
+}
+
+/*
+==================
+CL_Configstrings_f
+==================
+*/
+void CL_Configstrings_f( void ) {
+ int i;
+ int ofs;
+
+ if ( cls.state != CA_ACTIVE ) {
+ Com_Printf( "Not connected to a server.\n");
+ return;
+ }
+
+ for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) {
+ ofs = cl.gameState.stringOffsets[ i ];
+ if ( !ofs ) {
+ continue;
+ }
+ Com_Printf( "%4i: %s\n", i, cl.gameState.stringData + ofs );
+ }
+}
+
+/*
+==============
+CL_Clientinfo_f
+==============
+*/
+void CL_Clientinfo_f( void ) {
+ Com_Printf( "--------- Client Information ---------\n" );
+ Com_Printf( "state: %i\n", cls.state );
+ Com_Printf( "Server: %s\n", cls.servername );
+ Com_Printf ("User info settings:\n");
+ Info_Print( Cvar_InfoString( CVAR_USERINFO ) );
+ Com_Printf( "--------------------------------------\n" );
+}
+
+
+//====================================================================
+
+/*
+=================
+CL_DownloadsComplete
+
+Called when all downloading has been completed
+=================
+*/
+void CL_DownloadsComplete( void ) {
+
+ // if we downloaded files we need to restart the file system
+ if (clc.downloadRestart) {
+ clc.downloadRestart = qfalse;
+
+ FS_Restart(clc.checksumFeed); // We possibly downloaded a pak, restart the file system to load it
+
+ // inform the server so we get new gamestate info
+ CL_AddReliableCommand( "donedl" );
+
+ // by sending the donedl command we request a new gamestate
+ // so we don't want to load stuff yet
+ return;
+ }
+
+ // let the client game init and load data
+ cls.state = CA_LOADING;
+
+ // Pump the loop, this may change gamestate!
+ Com_EventLoop();
+
+ // if the gamestate was changed by calling Com_EventLoop
+ // then we loaded everything already and we don't want to do it again.
+ if ( cls.state != CA_LOADING ) {
+ return;
+ }
+
+ // starting to load a map so we get out of full screen ui mode
+ Cvar_Set("r_uiFullScreen", "0");
+
+ // flush client memory and start loading stuff
+ // this will also (re)load the UI
+ // if this is a local client then only the client part of the hunk
+ // will be cleared, note that this is done after the hunk mark has been set
+ CL_FlushMemory();
+
+ // initialize the CGame
+ cls.cgameStarted = qtrue;
+ CL_InitCGame();
+
+ // set pure checksums
+ CL_SendPureChecksums();
+
+ CL_WritePacket();
+ CL_WritePacket();
+ CL_WritePacket();
+}
+
+/*
+=================
+CL_BeginDownload
+
+Requests a file to download from the server. Stores it in the current
+game directory.
+=================
+*/
+void CL_BeginDownload( const char *localName, const char *remoteName ) {
+
+ Com_DPrintf("***** CL_BeginDownload *****\n"
+ "Localname: %s\n"
+ "Remotename: %s\n"
+ "****************************\n", localName, remoteName);
+
+ Q_strncpyz ( clc.downloadName, localName, sizeof(clc.downloadName) );
+ Com_sprintf( clc.downloadTempName, sizeof(clc.downloadTempName), "%s.tmp", localName );
+
+ // Set so UI gets access to it
+ Cvar_Set( "cl_downloadName", remoteName );
+ Cvar_Set( "cl_downloadSize", "0" );
+ Cvar_Set( "cl_downloadCount", "0" );
+ Cvar_SetValue( "cl_downloadTime", cls.realtime );
+
+ clc.downloadBlock = 0; // Starting new file
+ clc.downloadCount = 0;
+
+ CL_AddReliableCommand( va("download %s", remoteName) );
+}
+
+/*
+=================
+CL_NextDownload
+
+A download completed or failed
+=================
+*/
+void CL_NextDownload(void) {
+ char *s;
+ char *remoteName, *localName;
+
+ // We are looking to start a download here
+ if (*clc.downloadList) {
+ s = clc.downloadList;
+
+ // format is:
+ // @remotename@localname@remotename@localname, etc.
+
+ if (*s == '@')
+ s++;
+ remoteName = s;
+
+ if ( (s = strchr(s, '@')) == NULL ) {
+ CL_DownloadsComplete();
+ return;
+ }
+
+ *s++ = 0;
+ localName = s;
+ if ( (s = strchr(s, '@')) != NULL )
+ *s++ = 0;
+ else
+ s = localName + strlen(localName); // point at the nul byte
+
+ CL_BeginDownload( localName, remoteName );
+
+ clc.downloadRestart = qtrue;
+
+ // move over the rest
+ memmove( clc.downloadList, s, strlen(s) + 1);
+
+ return;
+ }
+
+ CL_DownloadsComplete();
+}
+
+/*
+=================
+CL_InitDownloads
+
+After receiving a valid game state, we valid the cgame and local zip files here
+and determine if we need to download them
+=================
+*/
+void CL_InitDownloads(void) {
+ char missingfiles[1024];
+
+ if ( !cl_allowDownload->integer )
+ {
+ // autodownload is disabled on the client
+ // but it's possible that some referenced files on the server are missing
+ if (FS_ComparePaks( missingfiles, sizeof( missingfiles ), qfalse ) )
+ {
+ // NOTE TTimo I would rather have that printed as a modal message box
+ // but at this point while joining the game we don't know wether we will successfully join or not
+ Com_Printf( "\nWARNING: You are missing some files referenced by the server:\n%s"
+ "You might not be able to join the game\n"
+ "Go to the setting menu to turn on autodownload, or get the file elsewhere\n\n", missingfiles );
+ }
+ }
+ else if ( FS_ComparePaks( clc.downloadList, sizeof( clc.downloadList ) , qtrue ) ) {
+
+ Com_Printf("Need paks: %s\n", clc.downloadList );
+
+ if ( *clc.downloadList ) {
+ // if autodownloading is not enabled on the server
+ cls.state = CA_CONNECTED;
+ CL_NextDownload();
+ return;
+ }
+
+ }
+
+ CL_DownloadsComplete();
+}
+
+/*
+=================
+CL_CheckForResend
+
+Resend a connect message if the last one has timed out
+=================
+*/
+void CL_CheckForResend( void ) {
+ int port, i;
+ char info[MAX_INFO_STRING];
+ char data[MAX_INFO_STRING];
+
+ // don't send anything if playing back a demo
+ if ( clc.demoplaying ) {
+ return;
+ }
+
+ // resend if we haven't gotten a reply yet
+ if ( cls.state != CA_CONNECTING && cls.state != CA_CHALLENGING ) {
+ return;
+ }
+
+ if ( cls.realtime - clc.connectTime < RETRANSMIT_TIMEOUT ) {
+ return;
+ }
+
+ clc.connectTime = cls.realtime; // for retransmit requests
+ clc.connectPacketCount++;
+
+
+ switch ( cls.state ) {
+ case CA_CONNECTING:
+ // requesting a challenge
+ if ( !Sys_IsLANAddress( clc.serverAddress ) ) {
+ CL_RequestAuthorization();
+ }
+ NET_OutOfBandPrint(NS_CLIENT, clc.serverAddress, "getchallenge");
+ break;
+
+ case CA_CHALLENGING:
+ // sending back the challenge
+ port = Cvar_VariableValue ("net_qport");
+
+ Q_strncpyz( info, Cvar_InfoString( CVAR_USERINFO ), sizeof( info ) );
+ Info_SetValueForKey( info, "protocol", va("%i", PROTOCOL_VERSION ) );
+ Info_SetValueForKey( info, "qport", va("%i", port ) );
+ Info_SetValueForKey( info, "challenge", va("%i", clc.challenge ) );
+
+ strcpy(data, "connect ");
+ // TTimo adding " " around the userinfo string to avoid truncated userinfo on the server
+ // (Com_TokenizeString tokenizes around spaces)
+ data[8] = '"';
+
+ for(i=0;i<strlen(info);i++) {
+ data[9+i] = info[i]; // + (clc.challenge)&0x3;
+ }
+ data[9+i] = '"';
+ data[10+i] = 0;
+
+ // NOTE TTimo don't forget to set the right data length!
+ NET_OutOfBandData( NS_CLIENT, clc.serverAddress, &data[0], i+10 );
+ // the most current userinfo has been sent, so watch for any
+ // newer changes to userinfo variables
+ cvar_modifiedFlags &= ~CVAR_USERINFO;
+ break;
+
+ default:
+ Com_Error( ERR_FATAL, "CL_CheckForResend: bad cls.state" );
+ }
+}
+
+/*
+===================
+CL_DisconnectPacket
+
+Sometimes the server can drop the client and the netchan based
+disconnect can be lost. If the client continues to send packets
+to the server, the server will send out of band disconnect packets
+to the client so it doesn't have to wait for the full timeout period.
+===================
+*/
+void CL_DisconnectPacket( netadr_t from ) {
+ if ( cls.state < CA_AUTHORIZING ) {
+ return;
+ }
+
+ // if not from our server, ignore it
+ if ( !NET_CompareAdr( from, clc.netchan.remoteAddress ) ) {
+ return;
+ }
+
+ // if we have received packets within three seconds, ignore it
+ // (it might be a malicious spoof)
+ if ( cls.realtime - clc.lastPacketTime < 3000 ) {
+ return;
+ }
+
+ // drop the connection
+ Com_Printf( "Server disconnected for unknown reason\n" );
+ Cvar_Set("com_errorMessage", "Server disconnected for unknown reason\n" );
+ CL_Disconnect( qtrue );
+}
+
+
+/*
+===================
+CL_MotdPacket
+
+===================
+*/
+void CL_MotdPacket( netadr_t from ) {
+ char *challenge;
+ char *info;
+
+ // if not from our server, ignore it
+ if ( !NET_CompareAdr( from, cls.updateServer ) ) {
+ return;
+ }
+
+ info = Cmd_Argv(1);
+
+ // check challenge
+ challenge = Info_ValueForKey( info, "challenge" );
+ if ( strcmp( challenge, cls.updateChallenge ) ) {
+ return;
+ }
+
+ challenge = Info_ValueForKey( info, "motd" );
+
+ Q_strncpyz( cls.updateInfoString, info, sizeof( cls.updateInfoString ) );
+ Cvar_Set( "cl_motdString", challenge );
+}
+
+/*
+===================
+CL_InitServerInfo
+===================
+*/
+void CL_InitServerInfo( serverInfo_t *server, serverAddress_t *address ) {
+ server->adr.type = NA_IP;
+ server->adr.ip[0] = address->ip[0];
+ server->adr.ip[1] = address->ip[1];
+ server->adr.ip[2] = address->ip[2];
+ server->adr.ip[3] = address->ip[3];
+ server->adr.port = address->port;
+ server->clients = 0;
+ server->hostName[0] = '\0';
+ server->mapName[0] = '\0';
+ server->maxClients = 0;
+ server->maxPing = 0;
+ server->minPing = 0;
+ server->ping = -1;
+ server->game[0] = '\0';
+ server->gameType = 0;
+ server->netType = 0;
+}
+
+#define MAX_SERVERSPERPACKET 256
+
+/*
+===================
+CL_ServersResponsePacket
+===================
+*/
+void CL_ServersResponsePacket( netadr_t from, msg_t *msg ) {
+ int i, count, max, total;
+ serverAddress_t addresses[MAX_SERVERSPERPACKET];
+ int numservers;
+ byte* buffptr;
+ byte* buffend;
+
+ Com_Printf("CL_ServersResponsePacket\n");
+
+ if (cls.numglobalservers == -1) {
+ // state to detect lack of servers or lack of response
+ cls.numglobalservers = 0;
+ cls.numGlobalServerAddresses = 0;
+ }
+
+ if (cls.nummplayerservers == -1) {
+ cls.nummplayerservers = 0;
+ }
+
+ // parse through server response string
+ numservers = 0;
+ buffptr = msg->data;
+ buffend = buffptr + msg->cursize;
+ while (buffptr+1 < buffend) {
+ // advance to initial token
+ do {
+ if (*buffptr++ == '\\')
+ break;
+ }
+ while (buffptr < buffend);
+
+ if ( buffptr >= buffend - 6 ) {
+ break;
+ }
+
+ // parse out ip
+ addresses[numservers].ip[0] = *buffptr++;
+ addresses[numservers].ip[1] = *buffptr++;
+ addresses[numservers].ip[2] = *buffptr++;
+ addresses[numservers].ip[3] = *buffptr++;
+
+ // parse out port
+ addresses[numservers].port = (*buffptr++)<<8;
+ addresses[numservers].port += *buffptr++;
+ addresses[numservers].port = BigShort( addresses[numservers].port );
+
+ // syntax check
+ if (*buffptr != '\\') {
+ break;
+ }
+
+ Com_DPrintf( "server: %d ip: %d.%d.%d.%d:%d\n",numservers,
+ addresses[numservers].ip[0],
+ addresses[numservers].ip[1],
+ addresses[numservers].ip[2],
+ addresses[numservers].ip[3],
+ addresses[numservers].port );
+
+ numservers++;
+ if (numservers >= MAX_SERVERSPERPACKET) {
+ break;
+ }
+
+ // parse out EOT
+ if (buffptr[1] == 'E' && buffptr[2] == 'O' && buffptr[3] == 'T') {
+ break;
+ }
+ }
+
+ if (cls.masterNum == 0) {
+ count = cls.numglobalservers;
+ max = MAX_GLOBAL_SERVERS;
+ } else {
+ count = cls.nummplayerservers;
+ max = MAX_OTHER_SERVERS;
+ }
+
+ for (i = 0; i < numservers && count < max; i++) {
+ // build net address
+ serverInfo_t *server = (cls.masterNum == 0) ? &cls.globalServers[count] : &cls.mplayerServers[count];
+
+ CL_InitServerInfo( server, &addresses[i] );
+ // advance to next slot
+ count++;
+ }
+
+ // if getting the global list
+ if (cls.masterNum == 0) {
+ if ( cls.numGlobalServerAddresses < MAX_GLOBAL_SERVERS ) {
+ // if we couldn't store the servers in the main list anymore
+ for (; i < numservers && count >= max; i++) {
+ serverAddress_t *addr;
+ // just store the addresses in an additional list
+ addr = &cls.globalServerAddresses[cls.numGlobalServerAddresses++];
+ addr->ip[0] = addresses[i].ip[0];
+ addr->ip[1] = addresses[i].ip[1];
+ addr->ip[2] = addresses[i].ip[2];
+ addr->ip[3] = addresses[i].ip[3];
+ addr->port = addresses[i].port;
+ }
+ }
+ }
+
+ if (cls.masterNum == 0) {
+ cls.numglobalservers = count;
+ total = count + cls.numGlobalServerAddresses;
+ } else {
+ cls.nummplayerservers = count;
+ total = count;
+ }
+
+ Com_Printf("%d servers parsed (total %d)\n", numservers, total);
+}
+
+/*
+=================
+CL_ConnectionlessPacket
+
+Responses to broadcasts, etc
+=================
+*/
+void CL_ConnectionlessPacket( netadr_t from, msg_t *msg ) {
+ char *s;
+ char *c;
+
+ MSG_BeginReadingOOB( msg );
+ MSG_ReadLong( msg ); // skip the -1
+
+ s = MSG_ReadStringLine( msg );
+
+ Cmd_TokenizeString( s );
+
+ c = Cmd_Argv(0);
+
+ Com_DPrintf ("CL packet %s: %s\n", NET_AdrToString(from), c);
+
+ // challenge from the server we are connecting to
+ if ( !Q_stricmp(c, "challengeResponse") ) {
+ if ( cls.state != CA_CONNECTING ) {
+ Com_Printf( "Unwanted challenge response received. Ignored.\n" );
+ } else {
+ // start sending challenge repsonse instead of challenge request packets
+ clc.challenge = atoi(Cmd_Argv(1));
+ cls.state = CA_CHALLENGING;
+ clc.connectPacketCount = 0;
+ clc.connectTime = -99999;
+
+ // take this address as the new server address. This allows
+ // a server proxy to hand off connections to multiple servers
+ clc.serverAddress = from;
+ Com_DPrintf ("challengeResponse: %d\n", clc.challenge);
+ }
+ return;
+ }
+
+ // server connection
+ if ( !Q_stricmp(c, "connectResponse") ) {
+ if ( cls.state >= CA_CONNECTED ) {
+ Com_Printf ("Dup connect received. Ignored.\n");
+ return;
+ }
+ if ( cls.state != CA_CHALLENGING ) {
+ Com_Printf ("connectResponse packet while not connecting. Ignored.\n");
+ return;
+ }
+ if ( !NET_CompareBaseAdr( from, clc.serverAddress ) ) {
+ Com_Printf( "connectResponse from a different address. Ignored.\n" );
+ Com_Printf( "%s should have been %s\n", NET_AdrToString( from ),
+ NET_AdrToString( clc.serverAddress ) );
+ return;
+ }
+ Netchan_Setup (NS_CLIENT, &clc.netchan, from, Cvar_VariableValue( "net_qport" ) );
+ cls.state = CA_CONNECTED;
+ clc.lastPacketSentTime = -9999; // send first packet immediately
+ return;
+ }
+
+ // server responding to an info broadcast
+ if ( !Q_stricmp(c, "infoResponse") ) {
+ CL_ServerInfoPacket( from, msg );
+ return;
+ }
+
+ // server responding to a get playerlist
+ if ( !Q_stricmp(c, "statusResponse") ) {
+ CL_ServerStatusResponse( from, msg );
+ return;
+ }
+
+ // a disconnect message from the server, which will happen if the server
+ // dropped the connection but it is still getting packets from us
+ if (!Q_stricmp(c, "disconnect")) {
+ CL_DisconnectPacket( from );
+ return;
+ }
+
+ // echo request from server
+ if ( !Q_stricmp(c, "echo") ) {
+ NET_OutOfBandPrint( NS_CLIENT, from, "%s", Cmd_Argv(1) );
+ return;
+ }
+
+ // cd check
+ if ( !Q_stricmp(c, "keyAuthorize") ) {
+ // we don't use these now, so dump them on the floor
+ return;
+ }
+
+ // global MOTD from id
+ if ( !Q_stricmp(c, "motd") ) {
+ CL_MotdPacket( from );
+ return;
+ }
+
+ // echo request from server
+ if ( !Q_stricmp(c, "print") ) {
+ s = MSG_ReadString( msg );
+ Q_strncpyz( clc.serverMessage, s, sizeof( clc.serverMessage ) );
+ Com_Printf( "%s", s );
+ return;
+ }
+
+ // echo request from server
+ if ( !Q_strncmp(c, "getserversResponse", 18) ) {
+ CL_ServersResponsePacket( from, msg );
+ return;
+ }
+
+ Com_DPrintf ("Unknown connectionless packet command.\n");
+}
+
+
+/*
+=================
+CL_PacketEvent
+
+A packet has arrived from the main event loop
+=================
+*/
+void CL_PacketEvent( netadr_t from, msg_t *msg ) {
+ int headerBytes;
+
+ clc.lastPacketTime = cls.realtime;
+
+ if ( msg->cursize >= 4 && *(int *)msg->data == -1 ) {
+ CL_ConnectionlessPacket( from, msg );
+ return;
+ }
+
+ if ( cls.state < CA_CONNECTED ) {
+ return; // can't be a valid sequenced packet
+ }
+
+ if ( msg->cursize < 4 ) {
+ Com_Printf ("%s: Runt packet\n",NET_AdrToString( from ));
+ return;
+ }
+
+ //
+ // packet from server
+ //
+ if ( !NET_CompareAdr( from, clc.netchan.remoteAddress ) ) {
+ Com_DPrintf ("%s:sequenced packet without connection\n"
+ ,NET_AdrToString( from ) );
+ // FIXME: send a client disconnect?
+ return;
+ }
+
+ if (!CL_Netchan_Process( &clc.netchan, msg) ) {
+ return; // out of order, duplicated, etc
+ }
+
+ // the header is different lengths for reliable and unreliable messages
+ headerBytes = msg->readcount;
+
+ // track the last message received so it can be returned in
+ // client messages, allowing the server to detect a dropped
+ // gamestate
+ clc.serverMessageSequence = LittleLong( *(int *)msg->data );
+
+ clc.lastPacketTime = cls.realtime;
+ CL_ParseServerMessage( msg );
+
+ //
+ // we don't know if it is ok to save a demo message until
+ // after we have parsed the frame
+ //
+ if ( clc.demorecording && !clc.demowaiting ) {
+ CL_WriteDemoMessage( msg, headerBytes );
+ }
+}
+
+/*
+==================
+CL_CheckTimeout
+
+==================
+*/
+void CL_CheckTimeout( void ) {
+ //
+ // check timeout
+ //
+ if ( ( !cl_paused->integer || !sv_paused->integer )
+ && cls.state >= CA_CONNECTED && cls.state != CA_CINEMATIC
+ && cls.realtime - clc.lastPacketTime > cl_timeout->value*1000) {
+ if (++cl.timeoutcount > 5) { // timeoutcount saves debugger
+ Com_Printf ("\nServer connection timed out.\n");
+ CL_Disconnect( qtrue );
+ return;
+ }
+ } else {
+ cl.timeoutcount = 0;
+ }
+}
+
+
+//============================================================================
+
+/*
+==================
+CL_CheckUserinfo
+
+==================
+*/
+void CL_CheckUserinfo( void ) {
+ // don't add reliable commands when not yet connected
+ if ( cls.state < CA_CHALLENGING ) {
+ return;
+ }
+ // don't overflow the reliable command buffer when paused
+ if ( cl_paused->integer ) {
+ return;
+ }
+ // send a reliable userinfo update if needed
+ if ( cvar_modifiedFlags & CVAR_USERINFO ) {
+ cvar_modifiedFlags &= ~CVAR_USERINFO;
+ CL_AddReliableCommand( va("userinfo \"%s\"", Cvar_InfoString( CVAR_USERINFO ) ) );
+ }
+
+}
+
+/*
+==================
+CL_Frame
+
+==================
+*/
+void CL_Frame ( int msec ) {
+
+ if ( !com_cl_running->integer ) {
+ return;
+ }
+
+ if ( cls.cddialog ) {
+ // bring up the cd error dialog if needed
+ cls.cddialog = qfalse;
+ VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_NEED_CD );
+ } else if ( cls.state == CA_DISCONNECTED && !( cls.keyCatchers & KEYCATCH_UI )
+ && !com_sv_running->integer ) {
+ // if disconnected, bring up the menu
+ S_StopAllSounds();
+ VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_MAIN );
+ }
+
+ // if recording an avi, lock to a fixed fps
+ if ( cl_avidemo->integer && msec) {
+ // save the current screen
+ if ( cls.state == CA_ACTIVE || cl_forceavidemo->integer) {
+ Cbuf_ExecuteText( EXEC_NOW, "screenshot silent\n" );
+ }
+ // fixed time for next frame'
+ msec = (1000 / cl_avidemo->integer) * com_timescale->value;
+ if (msec == 0) {
+ msec = 1;
+ }
+ }
+
+ // save the msec before checking pause
+ cls.realFrametime = msec;
+
+ // decide the simulation time
+ cls.frametime = msec;
+
+ cls.realtime += cls.frametime;
+
+ if ( cl_timegraph->integer ) {
+ SCR_DebugGraph ( cls.realFrametime * 0.25, 0 );
+ }
+
+ // see if we need to update any userinfo
+ CL_CheckUserinfo();
+
+ // if we haven't gotten a packet in a long time,
+ // drop the connection
+ CL_CheckTimeout();
+
+ // send intentions now
+ CL_SendCmd();
+
+ // resend a connection request if necessary
+ CL_CheckForResend();
+
+ // decide on the serverTime to render
+ CL_SetCGameTime();
+
+ // update the screen
+ SCR_UpdateScreen();
+
+ // update audio
+ S_Update();
+
+ // advance local effects for next frame
+ SCR_RunCinematic();
+
+ Con_RunConsole();
+
+ cls.framecount++;
+}
+
+
+//============================================================================
+
+/*
+================
+CL_RefPrintf
+
+DLL glue
+================
+*/
+void QDECL CL_RefPrintf( int print_level, const char *fmt, ...) {
+ va_list argptr;
+ char msg[MAXPRINTMSG];
+
+ va_start (argptr,fmt);
+ Q_vsnprintf (msg, sizeof(msg), fmt, argptr);
+ va_end (argptr);
+
+ if ( print_level == PRINT_ALL ) {
+ Com_Printf ("%s", msg);
+ } else if ( print_level == PRINT_WARNING ) {
+ Com_Printf (S_COLOR_YELLOW "%s", msg); // yellow
+ } else if ( print_level == PRINT_DEVELOPER ) {
+ Com_DPrintf (S_COLOR_RED "%s", msg); // red
+ }
+}
+
+
+
+/*
+============
+CL_ShutdownRef
+============
+*/
+void CL_ShutdownRef( void ) {
+ if ( !re.Shutdown ) {
+ return;
+ }
+ re.Shutdown( qtrue );
+ Com_Memset( &re, 0, sizeof( re ) );
+}
+
+/*
+============
+CL_InitRenderer
+============
+*/
+void CL_InitRenderer( void ) {
+ // this sets up the renderer and calls R_Init
+ re.BeginRegistration( &cls.glconfig );
+
+ // load character sets
+ cls.charSetShader = re.RegisterShader( "gfx/2d/bigchars" );
+ cls.whiteShader = re.RegisterShader( "white" );
+ cls.consoleShader = re.RegisterShader( "console" );
+ g_console_field_width = cls.glconfig.vidWidth / SMALLCHAR_WIDTH - 2;
+ g_consoleField.widthInChars = g_console_field_width;
+}
+
+/*
+============================
+CL_StartHunkUsers
+
+After the server has cleared the hunk, these will need to be restarted
+This is the only place that any of these functions are called from
+============================
+*/
+void CL_StartHunkUsers( void ) {
+ if (!com_cl_running) {
+ return;
+ }
+
+ if ( !com_cl_running->integer ) {
+ return;
+ }
+
+ if ( !cls.rendererStarted ) {
+ cls.rendererStarted = qtrue;
+ CL_InitRenderer();
+ }
+
+ if ( !cls.soundStarted ) {
+ cls.soundStarted = qtrue;
+ S_Init();
+ }
+
+ if ( !cls.soundRegistered ) {
+ cls.soundRegistered = qtrue;
+ S_BeginRegistration();
+ }
+
+ if ( !cls.uiStarted ) {
+ cls.uiStarted = qtrue;
+ CL_InitUI();
+ }
+}
+
+/*
+============
+CL_RefMalloc
+============
+*/
+void *CL_RefMalloc( int size ) {
+ return Z_TagMalloc( size, TAG_RENDERER );
+}
+
+int CL_ScaledMilliseconds(void) {
+ return Sys_Milliseconds()*com_timescale->value;
+}
+
+/*
+============
+CL_InitRef
+============
+*/
+void CL_InitRef( void ) {
+ refimport_t ri;
+ refexport_t *ret;
+
+ Com_Printf( "----- Initializing Renderer ----\n" );
+
+ ri.Cmd_AddCommand = Cmd_AddCommand;
+ ri.Cmd_RemoveCommand = Cmd_RemoveCommand;
+ ri.Cmd_Argc = Cmd_Argc;
+ ri.Cmd_Argv = Cmd_Argv;
+ ri.Cmd_ExecuteText = Cbuf_ExecuteText;
+ ri.Printf = CL_RefPrintf;
+ ri.Error = Com_Error;
+ ri.Milliseconds = CL_ScaledMilliseconds;
+ ri.Malloc = CL_RefMalloc;
+ ri.Free = Z_Free;
+#ifdef HUNK_DEBUG
+ ri.Hunk_AllocDebug = Hunk_AllocDebug;
+#else
+ ri.Hunk_Alloc = Hunk_Alloc;
+#endif
+ ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory;
+ ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory;
+ ri.CM_DrawDebugSurface = CM_DrawDebugSurface;
+ ri.FS_ReadFile = FS_ReadFile;
+ ri.FS_FreeFile = FS_FreeFile;
+ ri.FS_WriteFile = FS_WriteFile;
+ ri.FS_FreeFileList = FS_FreeFileList;
+ ri.FS_ListFiles = FS_ListFiles;
+ ri.FS_FileIsInPAK = FS_FileIsInPAK;
+ ri.FS_FileExists = FS_FileExists;
+ ri.Cvar_Get = Cvar_Get;
+ ri.Cvar_Set = Cvar_Set;
+
+ // cinematic stuff
+
+ ri.CIN_UploadCinematic = CIN_UploadCinematic;
+ ri.CIN_PlayCinematic = CIN_PlayCinematic;
+ ri.CIN_RunCinematic = CIN_RunCinematic;
+
+ ret = GetRefAPI( REF_API_VERSION, &ri );
+
+#if defined __USEA3D && defined __A3D_GEOM
+ hA3Dg_ExportRenderGeom (ret);
+#endif
+
+ Com_Printf( "-------------------------------\n");
+
+ if ( !ret ) {
+ Com_Error (ERR_FATAL, "Couldn't initialize refresh" );
+ }
+
+ re = *ret;
+
+ // unpause so the cgame definately gets a snapshot and renders a frame
+ Cvar_Set( "cl_paused", "0" );
+}
+
+
+//===========================================================================================
+
+
+void CL_SetModel_f( void ) {
+ char *arg;
+ char name[256];
+
+ arg = Cmd_Argv( 1 );
+ if (arg[0]) {
+ Cvar_Set( "model", arg );
+ Cvar_Set( "headmodel", arg );
+ } else {
+ Cvar_VariableStringBuffer( "model", name, sizeof(name) );
+ Com_Printf("model is set to %s\n", name);
+ }
+}
+
+/*
+====================
+CL_Init
+====================
+*/
+void CL_Init( void ) {
+ Com_Printf( "----- Client Initialization -----\n" );
+
+ Con_Init ();
+
+ CL_ClearState ();
+
+ cls.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED
+
+ cls.realtime = 0;
+
+ CL_InitInput ();
+
+ //
+ // register our variables
+ //
+ cl_noprint = Cvar_Get( "cl_noprint", "0", 0 );
+ cl_motd = Cvar_Get ("cl_motd", "1", 0);
+
+ cl_timeout = Cvar_Get ("cl_timeout", "200", 0);
+
+ cl_timeNudge = Cvar_Get ("cl_timeNudge", "0", CVAR_TEMP );
+ cl_shownet = Cvar_Get ("cl_shownet", "0", CVAR_TEMP );
+ cl_showSend = Cvar_Get ("cl_showSend", "0", CVAR_TEMP );
+ cl_showTimeDelta = Cvar_Get ("cl_showTimeDelta", "0", CVAR_TEMP );
+ cl_freezeDemo = Cvar_Get ("cl_freezeDemo", "0", CVAR_TEMP );
+ rcon_client_password = Cvar_Get ("rconPassword", "", CVAR_TEMP );
+ cl_activeAction = Cvar_Get( "activeAction", "", CVAR_TEMP );
+
+ cl_timedemo = Cvar_Get ("timedemo", "0", 0);
+ cl_avidemo = Cvar_Get ("cl_avidemo", "0", 0);
+ cl_forceavidemo = Cvar_Get ("cl_forceavidemo", "0", 0);
+
+ rconAddress = Cvar_Get ("rconAddress", "", 0);
+
+ cl_yawspeed = Cvar_Get ("cl_yawspeed", "140", CVAR_ARCHIVE);
+ cl_pitchspeed = Cvar_Get ("cl_pitchspeed", "140", CVAR_ARCHIVE);
+ cl_anglespeedkey = Cvar_Get ("cl_anglespeedkey", "1.5", 0);
+
+ cl_maxpackets = Cvar_Get ("cl_maxpackets", "30", CVAR_ARCHIVE );
+ cl_packetdup = Cvar_Get ("cl_packetdup", "1", CVAR_ARCHIVE );
+
+ cl_run = Cvar_Get ("cl_run", "1", CVAR_ARCHIVE);
+ cl_sensitivity = Cvar_Get ("sensitivity", "5", CVAR_ARCHIVE);
+ cl_mouseAccel = Cvar_Get ("cl_mouseAccel", "0", CVAR_ARCHIVE);
+ cl_freelook = Cvar_Get( "cl_freelook", "1", CVAR_ARCHIVE );
+
+ cl_showMouseRate = Cvar_Get ("cl_showmouserate", "0", 0);
+
+ cl_allowDownload = Cvar_Get ("cl_allowDownload", "0", CVAR_ARCHIVE);
+
+ cl_conXOffset = Cvar_Get ("cl_conXOffset", "0", 0);
+#ifdef MACOS_X
+ // In game video is REALLY slow in Mac OS X right now due to driver slowness
+ cl_inGameVideo = Cvar_Get ("r_inGameVideo", "0", CVAR_ARCHIVE);
+#else
+ cl_inGameVideo = Cvar_Get ("r_inGameVideo", "1", CVAR_ARCHIVE);
+#endif
+
+ cl_serverStatusResendTime = Cvar_Get ("cl_serverStatusResendTime", "750", 0);
+
+ // init autoswitch so the ui will have it correctly even
+ // if the cgame hasn't been started
+ Cvar_Get ("cg_autoswitch", "1", CVAR_ARCHIVE);
+
+ m_pitch = Cvar_Get ("m_pitch", "0.022", CVAR_ARCHIVE);
+ m_yaw = Cvar_Get ("m_yaw", "0.022", CVAR_ARCHIVE);
+ m_forward = Cvar_Get ("m_forward", "0.25", CVAR_ARCHIVE);
+ m_side = Cvar_Get ("m_side", "0.25", CVAR_ARCHIVE);
+#ifdef MACOS_X
+ // Input is jittery on OS X w/o this
+ m_filter = Cvar_Get ("m_filter", "1", CVAR_ARCHIVE);
+#else
+ m_filter = Cvar_Get ("m_filter", "0", CVAR_ARCHIVE);
+#endif
+
+ cl_motdString = Cvar_Get( "cl_motdString", "", CVAR_ROM );
+
+ Cvar_Get( "cl_maxPing", "800", CVAR_ARCHIVE );
+
+
+ // userinfo
+ Cvar_Get ("name", "UnnamedPlayer", CVAR_USERINFO | CVAR_ARCHIVE );
+ Cvar_Get ("rate", "3000", CVAR_USERINFO | CVAR_ARCHIVE );
+ Cvar_Get ("snaps", "20", CVAR_USERINFO | CVAR_ARCHIVE );
+ Cvar_Get ("model", "sarge", CVAR_USERINFO | CVAR_ARCHIVE );
+ Cvar_Get ("headmodel", "sarge", CVAR_USERINFO | CVAR_ARCHIVE );
+ Cvar_Get ("team_model", "james", CVAR_USERINFO | CVAR_ARCHIVE );
+ Cvar_Get ("team_headmodel", "*james", CVAR_USERINFO | CVAR_ARCHIVE );
+ Cvar_Get ("g_redTeam", "Stroggs", CVAR_SERVERINFO | CVAR_ARCHIVE);
+ Cvar_Get ("g_blueTeam", "Pagans", CVAR_SERVERINFO | CVAR_ARCHIVE);
+ Cvar_Get ("color1", "4", CVAR_USERINFO | CVAR_ARCHIVE );
+ Cvar_Get ("color2", "5", CVAR_USERINFO | CVAR_ARCHIVE );
+ Cvar_Get ("handicap", "100", CVAR_USERINFO | CVAR_ARCHIVE );
+ Cvar_Get ("teamtask", "0", CVAR_USERINFO );
+ Cvar_Get ("sex", "male", CVAR_USERINFO | CVAR_ARCHIVE );
+ Cvar_Get ("cl_anonymous", "0", CVAR_USERINFO | CVAR_ARCHIVE );
+
+ Cvar_Get ("password", "", CVAR_USERINFO);
+ Cvar_Get ("cg_predictItems", "1", CVAR_USERINFO | CVAR_ARCHIVE );
+
+
+ // cgame might not be initialized before menu is used
+ Cvar_Get ("cg_viewsize", "100", CVAR_ARCHIVE );
+
+ //
+ // register our commands
+ //
+ Cmd_AddCommand ("cmd", CL_ForwardToServer_f);
+ Cmd_AddCommand ("configstrings", CL_Configstrings_f);
+ Cmd_AddCommand ("clientinfo", CL_Clientinfo_f);
+ Cmd_AddCommand ("snd_restart", CL_Snd_Restart_f);
+ Cmd_AddCommand ("vid_restart", CL_Vid_Restart_f);
+ Cmd_AddCommand ("disconnect", CL_Disconnect_f);
+ Cmd_AddCommand ("record", CL_Record_f);
+ Cmd_AddCommand ("demo", CL_PlayDemo_f);
+ Cmd_AddCommand ("cinematic", CL_PlayCinematic_f);
+ Cmd_AddCommand ("stoprecord", CL_StopRecord_f);
+ Cmd_AddCommand ("connect", CL_Connect_f);
+ Cmd_AddCommand ("reconnect", CL_Reconnect_f);
+ Cmd_AddCommand ("localservers", CL_LocalServers_f);
+ Cmd_AddCommand ("globalservers", CL_GlobalServers_f);
+ Cmd_AddCommand ("rcon", CL_Rcon_f);
+ Cmd_AddCommand ("setenv", CL_Setenv_f );
+ Cmd_AddCommand ("ping", CL_Ping_f );
+ Cmd_AddCommand ("serverstatus", CL_ServerStatus_f );
+ Cmd_AddCommand ("showip", CL_ShowIP_f );
+ Cmd_AddCommand ("fs_openedList", CL_OpenedPK3List_f );
+ Cmd_AddCommand ("fs_referencedList", CL_ReferencedPK3List_f );
+ Cmd_AddCommand ("model", CL_SetModel_f );
+ CL_InitRef();
+
+ SCR_Init ();
+
+ Cbuf_Execute ();
+
+ Cvar_Set( "cl_running", "1" );
+
+ Com_Printf( "----- Client Initialization Complete -----\n" );
+}
+
+
+/*
+===============
+CL_Shutdown
+
+===============
+*/
+void CL_Shutdown( void ) {
+ static qboolean recursive = qfalse;
+
+ Com_Printf( "----- CL_Shutdown -----\n" );
+
+ if ( recursive ) {
+ printf ("recursive shutdown\n");
+ return;
+ }
+ recursive = qtrue;
+
+ CL_Disconnect( qtrue );
+
+ S_Shutdown();
+ CL_ShutdownRef();
+
+ CL_ShutdownUI();
+
+ Cmd_RemoveCommand ("cmd");
+ Cmd_RemoveCommand ("configstrings");
+ Cmd_RemoveCommand ("userinfo");
+ Cmd_RemoveCommand ("snd_restart");
+ Cmd_RemoveCommand ("vid_restart");
+ Cmd_RemoveCommand ("disconnect");
+ Cmd_RemoveCommand ("record");
+ Cmd_RemoveCommand ("demo");
+ Cmd_RemoveCommand ("cinematic");
+ Cmd_RemoveCommand ("stoprecord");
+ Cmd_RemoveCommand ("connect");
+ Cmd_RemoveCommand ("localservers");
+ Cmd_RemoveCommand ("globalservers");
+ Cmd_RemoveCommand ("rcon");
+ Cmd_RemoveCommand ("setenv");
+ Cmd_RemoveCommand ("ping");
+ Cmd_RemoveCommand ("serverstatus");
+ Cmd_RemoveCommand ("showip");
+ Cmd_RemoveCommand ("model");
+
+ Cvar_Set( "cl_running", "0" );
+
+ recursive = qfalse;
+
+ Com_Memset( &cls, 0, sizeof( cls ) );
+
+ Com_Printf( "-----------------------\n" );
+
+}
+
+static void CL_SetServerInfo(serverInfo_t *server, const char *info, int ping) {
+ if (server) {
+ if (info) {
+ server->clients = atoi(Info_ValueForKey(info, "clients"));
+ Q_strncpyz(server->hostName,Info_ValueForKey(info, "hostname"), MAX_NAME_LENGTH);
+ Q_strncpyz(server->mapName, Info_ValueForKey(info, "mapname"), MAX_NAME_LENGTH);
+ server->maxClients = atoi(Info_ValueForKey(info, "sv_maxclients"));
+ Q_strncpyz(server->game,Info_ValueForKey(info, "game"), MAX_NAME_LENGTH);
+ server->gameType = atoi(Info_ValueForKey(info, "gametype"));
+ server->netType = atoi(Info_ValueForKey(info, "nettype"));
+ server->minPing = atoi(Info_ValueForKey(info, "minping"));
+ server->maxPing = atoi(Info_ValueForKey(info, "maxping"));
+ server->punkbuster = atoi(Info_ValueForKey(info, "punkbuster"));
+ }
+ server->ping = ping;
+ }
+}
+
+static void CL_SetServerInfoByAddress(netadr_t from, const char *info, int ping) {
+ int i;
+
+ for (i = 0; i < MAX_OTHER_SERVERS; i++) {
+ if (NET_CompareAdr(from, cls.localServers[i].adr)) {
+ CL_SetServerInfo(&cls.localServers[i], info, ping);
+ }
+ }
+
+ for (i = 0; i < MAX_OTHER_SERVERS; i++) {
+ if (NET_CompareAdr(from, cls.mplayerServers[i].adr)) {
+ CL_SetServerInfo(&cls.mplayerServers[i], info, ping);
+ }
+ }
+
+ for (i = 0; i < MAX_GLOBAL_SERVERS; i++) {
+ if (NET_CompareAdr(from, cls.globalServers[i].adr)) {
+ CL_SetServerInfo(&cls.globalServers[i], info, ping);
+ }
+ }
+
+ for (i = 0; i < MAX_OTHER_SERVERS; i++) {
+ if (NET_CompareAdr(from, cls.favoriteServers[i].adr)) {
+ CL_SetServerInfo(&cls.favoriteServers[i], info, ping);
+ }
+ }
+
+}
+
+/*
+===================
+CL_ServerInfoPacket
+===================
+*/
+void CL_ServerInfoPacket( netadr_t from, msg_t *msg ) {
+ int i, type;
+ char info[MAX_INFO_STRING];
+ char* str;
+ char *infoString;
+ int prot;
+
+ infoString = MSG_ReadString( msg );
+
+ // if this isn't the correct protocol version, ignore it
+ prot = atoi( Info_ValueForKey( infoString, "protocol" ) );
+ if ( prot != PROTOCOL_VERSION ) {
+ Com_DPrintf( "Different protocol info packet: %s\n", infoString );
+ return;
+ }
+
+ // iterate servers waiting for ping response
+ for (i=0; i<MAX_PINGREQUESTS; i++)
+ {
+ if ( cl_pinglist[i].adr.port && !cl_pinglist[i].time && NET_CompareAdr( from, cl_pinglist[i].adr ) )
+ {
+ // calc ping time
+ cl_pinglist[i].time = cls.realtime - cl_pinglist[i].start + 1;
+ Com_DPrintf( "ping time %dms from %s\n", cl_pinglist[i].time, NET_AdrToString( from ) );
+
+ // save of info
+ Q_strncpyz( cl_pinglist[i].info, infoString, sizeof( cl_pinglist[i].info ) );
+
+ // tack on the net type
+ // NOTE: make sure these types are in sync with the netnames strings in the UI
+ switch (from.type)
+ {
+ case NA_BROADCAST:
+ case NA_IP:
+ str = "udp";
+ type = 1;
+ break;
+
+ case NA_IPX:
+ case NA_BROADCAST_IPX:
+ str = "ipx";
+ type = 2;
+ break;
+
+ default:
+ str = "???";
+ type = 0;
+ break;
+ }
+ Info_SetValueForKey( cl_pinglist[i].info, "nettype", va("%d", type) );
+ CL_SetServerInfoByAddress(from, infoString, cl_pinglist[i].time);
+
+ return;
+ }
+ }
+
+ // if not just sent a local broadcast or pinging local servers
+ if (cls.pingUpdateSource != AS_LOCAL) {
+ return;
+ }
+
+ for ( i = 0 ; i < MAX_OTHER_SERVERS ; i++ ) {
+ // empty slot
+ if ( cls.localServers[i].adr.port == 0 ) {
+ break;
+ }
+
+ // avoid duplicate
+ if ( NET_CompareAdr( from, cls.localServers[i].adr ) ) {
+ return;
+ }
+ }
+
+ if ( i == MAX_OTHER_SERVERS ) {
+ Com_DPrintf( "MAX_OTHER_SERVERS hit, dropping infoResponse\n" );
+ return;
+ }
+
+ // add this to the list
+ cls.numlocalservers = i+1;
+ cls.localServers[i].adr = from;
+ cls.localServers[i].clients = 0;
+ cls.localServers[i].hostName[0] = '\0';
+ cls.localServers[i].mapName[0] = '\0';
+ cls.localServers[i].maxClients = 0;
+ cls.localServers[i].maxPing = 0;
+ cls.localServers[i].minPing = 0;
+ cls.localServers[i].ping = -1;
+ cls.localServers[i].game[0] = '\0';
+ cls.localServers[i].gameType = 0;
+ cls.localServers[i].netType = from.type;
+ cls.localServers[i].punkbuster = 0;
+
+ Q_strncpyz( info, MSG_ReadString( msg ), MAX_INFO_STRING );
+ if (strlen(info)) {
+ if (info[strlen(info)-1] != '\n') {
+ strncat(info, "\n", sizeof(info));
+ }
+ Com_Printf( "%s: %s", NET_AdrToString( from ), info );
+ }
+}
+
+/*
+===================
+CL_GetServerStatus
+===================
+*/
+serverStatus_t *CL_GetServerStatus( netadr_t from ) {
+ serverStatus_t *serverStatus;
+ int i, oldest, oldestTime;
+
+ serverStatus = NULL;
+ for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) {
+ if ( NET_CompareAdr( from, cl_serverStatusList[i].address ) ) {
+ return &cl_serverStatusList[i];
+ }
+ }
+ for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) {
+ if ( cl_serverStatusList[i].retrieved ) {
+ return &cl_serverStatusList[i];
+ }
+ }
+ oldest = -1;
+ oldestTime = 0;
+ for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) {
+ if (oldest == -1 || cl_serverStatusList[i].startTime < oldestTime) {
+ oldest = i;
+ oldestTime = cl_serverStatusList[i].startTime;
+ }
+ }
+ if (oldest != -1) {
+ return &cl_serverStatusList[oldest];
+ }
+ serverStatusCount++;
+ return &cl_serverStatusList[serverStatusCount & (MAX_SERVERSTATUSREQUESTS-1)];
+}
+
+/*
+===================
+CL_ServerStatus
+===================
+*/
+int CL_ServerStatus( char *serverAddress, char *serverStatusString, int maxLen ) {
+ int i;
+ netadr_t to;
+ serverStatus_t *serverStatus;
+
+ // if no server address then reset all server status requests
+ if ( !serverAddress ) {
+ for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) {
+ cl_serverStatusList[i].address.port = 0;
+ cl_serverStatusList[i].retrieved = qtrue;
+ }
+ return qfalse;
+ }
+ // get the address
+ if ( !NET_StringToAdr( serverAddress, &to ) ) {
+ return qfalse;
+ }
+ serverStatus = CL_GetServerStatus( to );
+ // if no server status string then reset the server status request for this address
+ if ( !serverStatusString ) {
+ serverStatus->retrieved = qtrue;
+ return qfalse;
+ }
+
+ // if this server status request has the same address
+ if ( NET_CompareAdr( to, serverStatus->address) ) {
+ // if we recieved an response for this server status request
+ if (!serverStatus->pending) {
+ Q_strncpyz(serverStatusString, serverStatus->string, maxLen);
+ serverStatus->retrieved = qtrue;
+ serverStatus->startTime = 0;
+ return qtrue;
+ }
+ // resend the request regularly
+ else if ( serverStatus->startTime < Com_Milliseconds() - cl_serverStatusResendTime->integer ) {
+ serverStatus->print = qfalse;
+ serverStatus->pending = qtrue;
+ serverStatus->retrieved = qfalse;
+ serverStatus->time = 0;
+ serverStatus->startTime = Com_Milliseconds();
+ NET_OutOfBandPrint( NS_CLIENT, to, "getstatus" );
+ return qfalse;
+ }
+ }
+ // if retrieved
+ else if ( serverStatus->retrieved ) {
+ serverStatus->address = to;
+ serverStatus->print = qfalse;
+ serverStatus->pending = qtrue;
+ serverStatus->retrieved = qfalse;
+ serverStatus->startTime = Com_Milliseconds();
+ serverStatus->time = 0;
+ NET_OutOfBandPrint( NS_CLIENT, to, "getstatus" );
+ return qfalse;
+ }
+ return qfalse;
+}
+
+/*
+===================
+CL_ServerStatusResponse
+===================
+*/
+void CL_ServerStatusResponse( netadr_t from, msg_t *msg ) {
+ char *s;
+ char info[MAX_INFO_STRING];
+ int i, l, score, ping;
+ int len;
+ serverStatus_t *serverStatus;
+
+ serverStatus = NULL;
+ for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) {
+ if ( NET_CompareAdr( from, cl_serverStatusList[i].address ) ) {
+ serverStatus = &cl_serverStatusList[i];
+ break;
+ }
+ }
+ // if we didn't request this server status
+ if (!serverStatus) {
+ return;
+ }
+
+ s = MSG_ReadStringLine( msg );
+
+ len = 0;
+ Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "%s", s);
+
+ if (serverStatus->print) {
+ Com_Printf("Server settings:\n");
+ // print cvars
+ while (*s) {
+ for (i = 0; i < 2 && *s; i++) {
+ if (*s == '\\')
+ s++;
+ l = 0;
+ while (*s) {
+ info[l++] = *s;
+ if (l >= MAX_INFO_STRING-1)
+ break;
+ s++;
+ if (*s == '\\') {
+ break;
+ }
+ }
+ info[l] = '\0';
+ if (i) {
+ Com_Printf("%s\n", info);
+ }
+ else {
+ Com_Printf("%-24s", info);
+ }
+ }
+ }
+ }
+
+ len = strlen(serverStatus->string);
+ Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "\\");
+
+ if (serverStatus->print) {
+ Com_Printf("\nPlayers:\n");
+ Com_Printf("num: score: ping: name:\n");
+ }
+ for (i = 0, s = MSG_ReadStringLine( msg ); *s; s = MSG_ReadStringLine( msg ), i++) {
+
+ len = strlen(serverStatus->string);
+ Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "\\%s", s);
+
+ if (serverStatus->print) {
+ score = ping = 0;
+ sscanf(s, "%d %d", &score, &ping);
+ s = strchr(s, ' ');
+ if (s)
+ s = strchr(s+1, ' ');
+ if (s)
+ s++;
+ else
+ s = "unknown";
+ Com_Printf("%-2d %-3d %-3d %s\n", i, score, ping, s );
+ }
+ }
+ len = strlen(serverStatus->string);
+ Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "\\");
+
+ serverStatus->time = Com_Milliseconds();
+ serverStatus->address = from;
+ serverStatus->pending = qfalse;
+ if (serverStatus->print) {
+ serverStatus->retrieved = qtrue;
+ }
+}
+
+/*
+==================
+CL_LocalServers_f
+==================
+*/
+void CL_LocalServers_f( void ) {
+ char *message;
+ int i, j;
+ netadr_t to;
+
+ Com_Printf( "Scanning for servers on the local network...\n");
+
+ // reset the list, waiting for response
+ cls.numlocalservers = 0;
+ cls.pingUpdateSource = AS_LOCAL;
+
+ for (i = 0; i < MAX_OTHER_SERVERS; i++) {
+ qboolean b = cls.localServers[i].visible;
+ Com_Memset(&cls.localServers[i], 0, sizeof(cls.localServers[i]));
+ cls.localServers[i].visible = b;
+ }
+ Com_Memset( &to, 0, sizeof( to ) );
+
+ // The 'xxx' in the message is a challenge that will be echoed back
+ // by the server. We don't care about that here, but master servers
+ // can use that to prevent spoofed server responses from invalid ip
+ message = "\377\377\377\377getinfo xxx";
+
+ // send each message twice in case one is dropped
+ for ( i = 0 ; i < 2 ; i++ ) {
+ // send a broadcast packet on each server port
+ // we support multiple server ports so a single machine
+ // can nicely run multiple servers
+ for ( j = 0 ; j < NUM_SERVER_PORTS ; j++ ) {
+ to.port = BigShort( (short)(PORT_SERVER + j) );
+
+ to.type = NA_BROADCAST;
+ NET_SendPacket( NS_CLIENT, strlen( message ), message, to );
+
+ to.type = NA_BROADCAST_IPX;
+ NET_SendPacket( NS_CLIENT, strlen( message ), message, to );
+ }
+ }
+}
+
+/*
+==================
+CL_GlobalServers_f
+==================
+*/
+void CL_GlobalServers_f( void ) {
+ netadr_t to;
+ int i;
+ int count;
+ char *buffptr;
+ char command[1024];
+
+ if ( Cmd_Argc() < 3) {
+ Com_Printf( "usage: globalservers <master# 0-1> <protocol> [keywords]\n");
+ return;
+ }
+
+ cls.masterNum = atoi( Cmd_Argv(1) );
+
+ Com_Printf( "Requesting servers from the master...\n");
+
+ // reset the list, waiting for response
+ // -1 is used to distinguish a "no response"
+
+ if( cls.masterNum == 1 ) {
+ NET_StringToAdr( MASTER_SERVER_NAME, &to );
+ cls.nummplayerservers = -1;
+ cls.pingUpdateSource = AS_MPLAYER;
+ }
+ else {
+ NET_StringToAdr( MASTER_SERVER_NAME, &to );
+ cls.numglobalservers = -1;
+ cls.pingUpdateSource = AS_GLOBAL;
+ }
+ to.type = NA_IP;
+ to.port = BigShort(PORT_MASTER);
+
+ sprintf( command, "getservers %s", Cmd_Argv(2) );
+
+ // tack on keywords
+ buffptr = command + strlen( command );
+ count = Cmd_Argc();
+ for (i=3; i<count; i++)
+ buffptr += sprintf( buffptr, " %s", Cmd_Argv(i) );
+
+ // if we are a demo, automatically add a "demo" keyword
+ if ( Cvar_VariableValue( "fs_restrict" ) ) {
+ buffptr += sprintf( buffptr, " demo" );
+ }
+
+ NET_OutOfBandPrint( NS_SERVER, to, command );
+}
+
+
+/*
+==================
+CL_GetPing
+==================
+*/
+void CL_GetPing( int n, char *buf, int buflen, int *pingtime )
+{
+ const char *str;
+ int time;
+ int maxPing;
+
+ if (!cl_pinglist[n].adr.port)
+ {
+ // empty slot
+ buf[0] = '\0';
+ *pingtime = 0;
+ return;
+ }
+
+ str = NET_AdrToString( cl_pinglist[n].adr );
+ Q_strncpyz( buf, str, buflen );
+
+ time = cl_pinglist[n].time;
+ if (!time)
+ {
+ // check for timeout
+ time = cls.realtime - cl_pinglist[n].start;
+ maxPing = Cvar_VariableIntegerValue( "cl_maxPing" );
+ if( maxPing < 100 ) {
+ maxPing = 100;
+ }
+ if (time < maxPing)
+ {
+ // not timed out yet
+ time = 0;
+ }
+ }
+
+ CL_SetServerInfoByAddress(cl_pinglist[n].adr, cl_pinglist[n].info, cl_pinglist[n].time);
+
+ *pingtime = time;
+}
+
+/*
+==================
+CL_UpdateServerInfo
+==================
+*/
+void CL_UpdateServerInfo( int n )
+{
+ if (!cl_pinglist[n].adr.port)
+ {
+ return;
+ }
+
+ CL_SetServerInfoByAddress(cl_pinglist[n].adr, cl_pinglist[n].info, cl_pinglist[n].time );
+}
+
+/*
+==================
+CL_GetPingInfo
+==================
+*/
+void CL_GetPingInfo( int n, char *buf, int buflen )
+{
+ if (!cl_pinglist[n].adr.port)
+ {
+ // empty slot
+ if (buflen)
+ buf[0] = '\0';
+ return;
+ }
+
+ Q_strncpyz( buf, cl_pinglist[n].info, buflen );
+}
+
+/*
+==================
+CL_ClearPing
+==================
+*/
+void CL_ClearPing( int n )
+{
+ if (n < 0 || n >= MAX_PINGREQUESTS)
+ return;
+
+ cl_pinglist[n].adr.port = 0;
+}
+
+/*
+==================
+CL_GetPingQueueCount
+==================
+*/
+int CL_GetPingQueueCount( void )
+{
+ int i;
+ int count;
+ ping_t* pingptr;
+
+ count = 0;
+ pingptr = cl_pinglist;
+
+ for (i=0; i<MAX_PINGREQUESTS; i++, pingptr++ ) {
+ if (pingptr->adr.port) {
+ count++;
+ }
+ }
+
+ return (count);
+}
+
+/*
+==================
+CL_GetFreePing
+==================
+*/
+ping_t* CL_GetFreePing( void )
+{
+ ping_t* pingptr;
+ ping_t* best;
+ int oldest;
+ int i;
+ int time;
+
+ pingptr = cl_pinglist;
+ for (i=0; i<MAX_PINGREQUESTS; i++, pingptr++ )
+ {
+ // find free ping slot
+ if (pingptr->adr.port)
+ {
+ if (!pingptr->time)
+ {
+ if (cls.realtime - pingptr->start < 500)
+ {
+ // still waiting for response
+ continue;
+ }
+ }
+ else if (pingptr->time < 500)
+ {
+ // results have not been queried
+ continue;
+ }
+ }
+
+ // clear it
+ pingptr->adr.port = 0;
+ return (pingptr);
+ }
+
+ // use oldest entry
+ pingptr = cl_pinglist;
+ best = cl_pinglist;
+ oldest = INT_MIN;
+ for (i=0; i<MAX_PINGREQUESTS; i++, pingptr++ )
+ {
+ // scan for oldest
+ time = cls.realtime - pingptr->start;
+ if (time > oldest)
+ {
+ oldest = time;
+ best = pingptr;
+ }
+ }
+
+ return (best);
+}
+
+/*
+==================
+CL_Ping_f
+==================
+*/
+void CL_Ping_f( void ) {
+ netadr_t to;
+ ping_t* pingptr;
+ char* server;
+
+ if ( Cmd_Argc() != 2 ) {
+ Com_Printf( "usage: ping [server]\n");
+ return;
+ }
+
+ Com_Memset( &to, 0, sizeof(netadr_t) );
+
+ server = Cmd_Argv(1);
+
+ if ( !NET_StringToAdr( server, &to ) ) {
+ return;
+ }
+
+ pingptr = CL_GetFreePing();
+
+ memcpy( &pingptr->adr, &to, sizeof (netadr_t) );
+ pingptr->start = cls.realtime;
+ pingptr->time = 0;
+
+ CL_SetServerInfoByAddress(pingptr->adr, NULL, 0);
+
+ NET_OutOfBandPrint( NS_CLIENT, to, "getinfo xxx" );
+}
+
+/*
+==================
+CL_UpdateVisiblePings_f
+==================
+*/
+qboolean CL_UpdateVisiblePings_f(int source) {
+ int slots, i;
+ char buff[MAX_STRING_CHARS];
+ int pingTime;
+ int max;
+ qboolean status = qfalse;
+
+ if (source < 0 || source > AS_FAVORITES) {
+ return qfalse;
+ }
+
+ cls.pingUpdateSource = source;
+
+ slots = CL_GetPingQueueCount();
+ if (slots < MAX_PINGREQUESTS) {
+ serverInfo_t *server = NULL;
+
+ max = (source == AS_GLOBAL) ? MAX_GLOBAL_SERVERS : MAX_OTHER_SERVERS;
+ switch (source) {
+ case AS_LOCAL :
+ server = &cls.localServers[0];
+ max = cls.numlocalservers;
+ break;
+ case AS_MPLAYER :
+ server = &cls.mplayerServers[0];
+ max = cls.nummplayerservers;
+ break;
+ case AS_GLOBAL :
+ server = &cls.globalServers[0];
+ max = cls.numglobalservers;
+ break;
+ case AS_FAVORITES :
+ server = &cls.favoriteServers[0];
+ max = cls.numfavoriteservers;
+ break;
+ }
+ for (i = 0; i < max; i++) {
+ if (server[i].visible) {
+ if (server[i].ping == -1) {
+ int j;
+
+ if (slots >= MAX_PINGREQUESTS) {
+ break;
+ }
+ for (j = 0; j < MAX_PINGREQUESTS; j++) {
+ if (!cl_pinglist[j].adr.port) {
+ continue;
+ }
+ if (NET_CompareAdr( cl_pinglist[j].adr, server[i].adr)) {
+ // already on the list
+ break;
+ }
+ }
+ if (j >= MAX_PINGREQUESTS) {
+ status = qtrue;
+ for (j = 0; j < MAX_PINGREQUESTS; j++) {
+ if (!cl_pinglist[j].adr.port) {
+ break;
+ }
+ }
+ memcpy(&cl_pinglist[j].adr, &server[i].adr, sizeof(netadr_t));
+ cl_pinglist[j].start = cls.realtime;
+ cl_pinglist[j].time = 0;
+ NET_OutOfBandPrint( NS_CLIENT, cl_pinglist[j].adr, "getinfo xxx" );
+ slots++;
+ }
+ }
+ // if the server has a ping higher than cl_maxPing or
+ // the ping packet got lost
+ else if (server[i].ping == 0) {
+ // if we are updating global servers
+ if (source == AS_GLOBAL) {
+ //
+ if ( cls.numGlobalServerAddresses > 0 ) {
+ // overwrite this server with one from the additional global servers
+ cls.numGlobalServerAddresses--;
+ CL_InitServerInfo(&server[i], &cls.globalServerAddresses[cls.numGlobalServerAddresses]);
+ // NOTE: the server[i].visible flag stays untouched
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if (slots) {
+ status = qtrue;
+ }
+ for (i = 0; i < MAX_PINGREQUESTS; i++) {
+ if (!cl_pinglist[i].adr.port) {
+ continue;
+ }
+ CL_GetPing( i, buff, MAX_STRING_CHARS, &pingTime );
+ if (pingTime != 0) {
+ CL_ClearPing(i);
+ status = qtrue;
+ }
+ }
+
+ return status;
+}
+
+/*
+==================
+CL_ServerStatus_f
+==================
+*/
+void CL_ServerStatus_f(void) {
+ netadr_t to;
+ char *server;
+ serverStatus_t *serverStatus;
+
+ Com_Memset( &to, 0, sizeof(netadr_t) );
+
+ if ( Cmd_Argc() != 2 ) {
+ if ( cls.state != CA_ACTIVE || clc.demoplaying ) {
+ Com_Printf ("Not connected to a server.\n");
+ Com_Printf( "Usage: serverstatus [server]\n");
+ return;
+ }
+ server = cls.servername;
+ }
+ else {
+ server = Cmd_Argv(1);
+ }
+
+ if ( !NET_StringToAdr( server, &to ) ) {
+ return;
+ }
+
+ NET_OutOfBandPrint( NS_CLIENT, to, "getstatus" );
+
+ serverStatus = CL_GetServerStatus( to );
+ serverStatus->address = to;
+ serverStatus->print = qtrue;
+ serverStatus->pending = qtrue;
+}
+
+/*
+==================
+CL_ShowIP_f
+==================
+*/
+void CL_ShowIP_f(void) {
+ Sys_ShowIP();
+}
+
+/*
+=================
+bool CL_CDKeyValidate
+=================
+*/
+qboolean CL_CDKeyValidate( const char *key, const char *checksum ) {
+ char ch;
+ byte sum;
+ char chs[3];
+ int i, len;
+
+ len = strlen(key);
+ if( len != CDKEY_LEN ) {
+ return qfalse;
+ }
+
+ if( checksum && strlen( checksum ) != CDCHKSUM_LEN ) {
+ return qfalse;
+ }
+
+ sum = 0;
+ // for loop gets rid of conditional assignment warning
+ for (i = 0; i < len; i++) {
+ ch = *key++;
+ if (ch>='a' && ch<='z') {
+ ch -= 32;
+ }
+ switch( ch ) {
+ case '2':
+ case '3':
+ case '7':
+ case 'A':
+ case 'B':
+ case 'C':
+ case 'D':
+ case 'G':
+ case 'H':
+ case 'J':
+ case 'L':
+ case 'P':
+ case 'R':
+ case 'S':
+ case 'T':
+ case 'W':
+ sum += ch;
+ continue;
+ default:
+ return qfalse;
+ }
+ }
+
+ sprintf(chs, "%02x", sum);
+
+ if (checksum && !Q_stricmp(chs, checksum)) {
+ return qtrue;
+ }
+
+ if (!checksum) {
+ return qtrue;
+ }
+
+ return qfalse;
+}
+
+
diff --git a/code/client/cl_net_chan.c b/code/client/cl_net_chan.c
new file mode 100755
index 0000000..d1e0b08
--- /dev/null
+++ b/code/client/cl_net_chan.c
@@ -0,0 +1,167 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "../game/q_shared.h"
+#include "../qcommon/qcommon.h"
+#include "client.h"
+
+/*
+==============
+CL_Netchan_Encode
+
+ // first 12 bytes of the data are always:
+ long serverId;
+ long messageAcknowledge;
+ long reliableAcknowledge;
+
+==============
+*/
+static void CL_Netchan_Encode( msg_t *msg ) {
+ int serverId, messageAcknowledge, reliableAcknowledge;
+ int i, index, srdc, sbit, soob;
+ byte key, *string;
+
+ if ( msg->cursize <= CL_ENCODE_START ) {
+ return;
+ }
+
+ srdc = msg->readcount;
+ sbit = msg->bit;
+ soob = msg->oob;
+
+ msg->bit = 0;
+ msg->readcount = 0;
+ msg->oob = 0;
+
+ serverId = MSG_ReadLong(msg);
+ messageAcknowledge = MSG_ReadLong(msg);
+ reliableAcknowledge = MSG_ReadLong(msg);
+
+ msg->oob = soob;
+ msg->bit = sbit;
+ msg->readcount = srdc;
+
+ string = (byte *)clc.serverCommands[ reliableAcknowledge & (MAX_RELIABLE_COMMANDS-1) ];
+ index = 0;
+ //
+ key = clc.challenge ^ serverId ^ messageAcknowledge;
+ for (i = CL_ENCODE_START; i < msg->cursize; i++) {
+ // modify the key with the last received now acknowledged server command
+ if (!string[index])
+ index = 0;
+ if (string[index] > 127 || string[index] == '%') {
+ key ^= '.' << (i & 1);
+ }
+ else {
+ key ^= string[index] << (i & 1);
+ }
+ index++;
+ // encode the data with this key
+ *(msg->data + i) = (*(msg->data + i)) ^ key;
+ }
+}
+
+/*
+==============
+CL_Netchan_Decode
+
+ // first four bytes of the data are always:
+ long reliableAcknowledge;
+
+==============
+*/
+static void CL_Netchan_Decode( msg_t *msg ) {
+ long reliableAcknowledge, i, index;
+ byte key, *string;
+ int srdc, sbit, soob;
+
+ srdc = msg->readcount;
+ sbit = msg->bit;
+ soob = msg->oob;
+
+ msg->oob = 0;
+
+ reliableAcknowledge = MSG_ReadLong(msg);
+
+ msg->oob = soob;
+ msg->bit = sbit;
+ msg->readcount = srdc;
+
+ string = clc.reliableCommands[ reliableAcknowledge & (MAX_RELIABLE_COMMANDS-1) ];
+ index = 0;
+ // xor the client challenge with the netchan sequence number (need something that changes every message)
+ key = clc.challenge ^ LittleLong( *(unsigned *)msg->data );
+ for (i = msg->readcount + CL_DECODE_START; i < msg->cursize; i++) {
+ // modify the key with the last sent and with this message acknowledged client command
+ if (!string[index])
+ index = 0;
+ if (string[index] > 127 || string[index] == '%') {
+ key ^= '.' << (i & 1);
+ }
+ else {
+ key ^= string[index] << (i & 1);
+ }
+ index++;
+ // decode the data with this key
+ *(msg->data + i) = *(msg->data + i) ^ key;
+ }
+}
+
+/*
+=================
+CL_Netchan_TransmitNextFragment
+=================
+*/
+void CL_Netchan_TransmitNextFragment( netchan_t *chan ) {
+ Netchan_TransmitNextFragment( chan );
+}
+
+/*
+===============
+CL_Netchan_Transmit
+================
+*/
+void CL_Netchan_Transmit( netchan_t *chan, msg_t* msg ) {
+ MSG_WriteByte( msg, clc_EOF );
+
+ CL_Netchan_Encode( msg );
+ Netchan_Transmit( chan, msg->cursize, msg->data );
+}
+
+extern int oldsize;
+int newsize = 0;
+
+/*
+=================
+CL_Netchan_Process
+=================
+*/
+qboolean CL_Netchan_Process( netchan_t *chan, msg_t *msg ) {
+ int ret;
+
+ ret = Netchan_Process( chan, msg );
+ if (!ret)
+ return qfalse;
+ CL_Netchan_Decode( msg );
+ newsize += msg->cursize;
+ return qtrue;
+}
diff --git a/code/client/cl_parse.c b/code/client/cl_parse.c
new file mode 100755
index 0000000..9de3588
--- /dev/null
+++ b/code/client/cl_parse.c
@@ -0,0 +1,655 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// cl_parse.c -- parse a message received from the server
+
+#include "client.h"
+
+char *svc_strings[256] = {
+ "svc_bad",
+
+ "svc_nop",
+ "svc_gamestate",
+ "svc_configstring",
+ "svc_baseline",
+ "svc_serverCommand",
+ "svc_download",
+ "svc_snapshot"
+};
+
+void SHOWNET( msg_t *msg, char *s) {
+ if ( cl_shownet->integer >= 2) {
+ Com_Printf ("%3i:%s\n", msg->readcount-1, s);
+ }
+}
+
+
+/*
+=========================================================================
+
+MESSAGE PARSING
+
+=========================================================================
+*/
+
+/*
+==================
+CL_DeltaEntity
+
+Parses deltas from the given base and adds the resulting entity
+to the current frame
+==================
+*/
+void CL_DeltaEntity (msg_t *msg, clSnapshot_t *frame, int newnum, entityState_t *old,
+ qboolean unchanged) {
+ entityState_t *state;
+
+ // save the parsed entity state into the big circular buffer so
+ // it can be used as the source for a later delta
+ state = &cl.parseEntities[cl.parseEntitiesNum & (MAX_PARSE_ENTITIES-1)];
+
+ if ( unchanged ) {
+ *state = *old;
+ } else {
+ MSG_ReadDeltaEntity( msg, old, state, newnum );
+ }
+
+ if ( state->number == (MAX_GENTITIES-1) ) {
+ return; // entity was delta removed
+ }
+ cl.parseEntitiesNum++;
+ frame->numEntities++;
+}
+
+/*
+==================
+CL_ParsePacketEntities
+
+==================
+*/
+void CL_ParsePacketEntities( msg_t *msg, clSnapshot_t *oldframe, clSnapshot_t *newframe) {
+ int newnum;
+ entityState_t *oldstate;
+ int oldindex, oldnum;
+
+ newframe->parseEntitiesNum = cl.parseEntitiesNum;
+ newframe->numEntities = 0;
+
+ // delta from the entities present in oldframe
+ oldindex = 0;
+ oldstate = NULL;
+ if (!oldframe) {
+ oldnum = 99999;
+ } else {
+ if ( oldindex >= oldframe->numEntities ) {
+ oldnum = 99999;
+ } else {
+ oldstate = &cl.parseEntities[
+ (oldframe->parseEntitiesNum + oldindex) & (MAX_PARSE_ENTITIES-1)];
+ oldnum = oldstate->number;
+ }
+ }
+
+ while ( 1 ) {
+ // read the entity index number
+ newnum = MSG_ReadBits( msg, GENTITYNUM_BITS );
+
+ if ( newnum == (MAX_GENTITIES-1) ) {
+ break;
+ }
+
+ if ( msg->readcount > msg->cursize ) {
+ Com_Error (ERR_DROP,"CL_ParsePacketEntities: end of message");
+ }
+
+ while ( oldnum < newnum ) {
+ // one or more entities from the old packet are unchanged
+ if ( cl_shownet->integer == 3 ) {
+ Com_Printf ("%3i: unchanged: %i\n", msg->readcount, oldnum);
+ }
+ CL_DeltaEntity( msg, newframe, oldnum, oldstate, qtrue );
+
+ oldindex++;
+
+ if ( oldindex >= oldframe->numEntities ) {
+ oldnum = 99999;
+ } else {
+ oldstate = &cl.parseEntities[
+ (oldframe->parseEntitiesNum + oldindex) & (MAX_PARSE_ENTITIES-1)];
+ oldnum = oldstate->number;
+ }
+ }
+ if (oldnum == newnum) {
+ // delta from previous state
+ if ( cl_shownet->integer == 3 ) {
+ Com_Printf ("%3i: delta: %i\n", msg->readcount, newnum);
+ }
+ CL_DeltaEntity( msg, newframe, newnum, oldstate, qfalse );
+
+ oldindex++;
+
+ if ( oldindex >= oldframe->numEntities ) {
+ oldnum = 99999;
+ } else {
+ oldstate = &cl.parseEntities[
+ (oldframe->parseEntitiesNum + oldindex) & (MAX_PARSE_ENTITIES-1)];
+ oldnum = oldstate->number;
+ }
+ continue;
+ }
+
+ if ( oldnum > newnum ) {
+ // delta from baseline
+ if ( cl_shownet->integer == 3 ) {
+ Com_Printf ("%3i: baseline: %i\n", msg->readcount, newnum);
+ }
+ CL_DeltaEntity( msg, newframe, newnum, &cl.entityBaselines[newnum], qfalse );
+ continue;
+ }
+
+ }
+
+ // any remaining entities in the old frame are copied over
+ while ( oldnum != 99999 ) {
+ // one or more entities from the old packet are unchanged
+ if ( cl_shownet->integer == 3 ) {
+ Com_Printf ("%3i: unchanged: %i\n", msg->readcount, oldnum);
+ }
+ CL_DeltaEntity( msg, newframe, oldnum, oldstate, qtrue );
+
+ oldindex++;
+
+ if ( oldindex >= oldframe->numEntities ) {
+ oldnum = 99999;
+ } else {
+ oldstate = &cl.parseEntities[
+ (oldframe->parseEntitiesNum + oldindex) & (MAX_PARSE_ENTITIES-1)];
+ oldnum = oldstate->number;
+ }
+ }
+}
+
+
+/*
+================
+CL_ParseSnapshot
+
+If the snapshot is parsed properly, it will be copied to
+cl.snap and saved in cl.snapshots[]. If the snapshot is invalid
+for any reason, no changes to the state will be made at all.
+================
+*/
+void CL_ParseSnapshot( msg_t *msg ) {
+ int len;
+ clSnapshot_t *old;
+ clSnapshot_t newSnap;
+ int deltaNum;
+ int oldMessageNum;
+ int i, packetNum;
+
+ // get the reliable sequence acknowledge number
+ // NOTE: now sent with all server to client messages
+ //clc.reliableAcknowledge = MSG_ReadLong( msg );
+
+ // read in the new snapshot to a temporary buffer
+ // we will only copy to cl.snap if it is valid
+ Com_Memset (&newSnap, 0, sizeof(newSnap));
+
+ // we will have read any new server commands in this
+ // message before we got to svc_snapshot
+ newSnap.serverCommandNum = clc.serverCommandSequence;
+
+ newSnap.serverTime = MSG_ReadLong( msg );
+
+ newSnap.messageNum = clc.serverMessageSequence;
+
+ deltaNum = MSG_ReadByte( msg );
+ if ( !deltaNum ) {
+ newSnap.deltaNum = -1;
+ } else {
+ newSnap.deltaNum = newSnap.messageNum - deltaNum;
+ }
+ newSnap.snapFlags = MSG_ReadByte( msg );
+
+ // If the frame is delta compressed from data that we
+ // no longer have available, we must suck up the rest of
+ // the frame, but not use it, then ask for a non-compressed
+ // message
+ if ( newSnap.deltaNum <= 0 ) {
+ newSnap.valid = qtrue; // uncompressed frame
+ old = NULL;
+ clc.demowaiting = qfalse; // we can start recording now
+ } else {
+ old = &cl.snapshots[newSnap.deltaNum & PACKET_MASK];
+ if ( !old->valid ) {
+ // should never happen
+ Com_Printf ("Delta from invalid frame (not supposed to happen!).\n");
+ } else if ( old->messageNum != newSnap.deltaNum ) {
+ // The frame that the server did the delta from
+ // is too old, so we can't reconstruct it properly.
+ Com_Printf ("Delta frame too old.\n");
+ } else if ( cl.parseEntitiesNum - old->parseEntitiesNum > MAX_PARSE_ENTITIES-128 ) {
+ Com_Printf ("Delta parseEntitiesNum too old.\n");
+ } else {
+ newSnap.valid = qtrue; // valid delta parse
+ }
+ }
+
+ // read areamask
+ len = MSG_ReadByte( msg );
+ MSG_ReadData( msg, &newSnap.areamask, len);
+
+ // read playerinfo
+ SHOWNET( msg, "playerstate" );
+ if ( old ) {
+ MSG_ReadDeltaPlayerstate( msg, &old->ps, &newSnap.ps );
+ } else {
+ MSG_ReadDeltaPlayerstate( msg, NULL, &newSnap.ps );
+ }
+
+ // read packet entities
+ SHOWNET( msg, "packet entities" );
+ CL_ParsePacketEntities( msg, old, &newSnap );
+
+ // if not valid, dump the entire thing now that it has
+ // been properly read
+ if ( !newSnap.valid ) {
+ return;
+ }
+
+ // clear the valid flags of any snapshots between the last
+ // received and this one, so if there was a dropped packet
+ // it won't look like something valid to delta from next
+ // time we wrap around in the buffer
+ oldMessageNum = cl.snap.messageNum + 1;
+
+ if ( newSnap.messageNum - oldMessageNum >= PACKET_BACKUP ) {
+ oldMessageNum = newSnap.messageNum - ( PACKET_BACKUP - 1 );
+ }
+ for ( ; oldMessageNum < newSnap.messageNum ; oldMessageNum++ ) {
+ cl.snapshots[oldMessageNum & PACKET_MASK].valid = qfalse;
+ }
+
+ // copy to the current good spot
+ cl.snap = newSnap;
+ cl.snap.ping = 999;
+ // calculate ping time
+ for ( i = 0 ; i < PACKET_BACKUP ; i++ ) {
+ packetNum = ( clc.netchan.outgoingSequence - 1 - i ) & PACKET_MASK;
+ if ( cl.snap.ps.commandTime >= cl.outPackets[ packetNum ].p_serverTime ) {
+ cl.snap.ping = cls.realtime - cl.outPackets[ packetNum ].p_realtime;
+ break;
+ }
+ }
+ // save the frame off in the backup array for later delta comparisons
+ cl.snapshots[cl.snap.messageNum & PACKET_MASK] = cl.snap;
+
+ if (cl_shownet->integer == 3) {
+ Com_Printf( " snapshot:%i delta:%i ping:%i\n", cl.snap.messageNum,
+ cl.snap.deltaNum, cl.snap.ping );
+ }
+
+ cl.newSnapshots = qtrue;
+}
+
+
+//=====================================================================
+
+int cl_connectedToPureServer;
+
+/*
+==================
+CL_SystemInfoChanged
+
+The systeminfo configstring has been changed, so parse
+new information out of it. This will happen at every
+gamestate, and possibly during gameplay.
+==================
+*/
+void CL_SystemInfoChanged( void ) {
+ char *systemInfo;
+ const char *s, *t;
+ char key[BIG_INFO_KEY];
+ char value[BIG_INFO_VALUE];
+ qboolean gameSet;
+
+ systemInfo = cl.gameState.stringData + cl.gameState.stringOffsets[ CS_SYSTEMINFO ];
+ // NOTE TTimo:
+ // when the serverId changes, any further messages we send to the server will use this new serverId
+ // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=475
+ // in some cases, outdated cp commands might get sent with this news serverId
+ cl.serverId = atoi( Info_ValueForKey( systemInfo, "sv_serverid" ) );
+
+ // don't set any vars when playing a demo
+ if ( clc.demoplaying ) {
+ return;
+ }
+
+ s = Info_ValueForKey( systemInfo, "sv_cheats" );
+ if ( atoi(s) == 0 ) {
+ Cvar_SetCheatState();
+ }
+
+ // check pure server string
+ s = Info_ValueForKey( systemInfo, "sv_paks" );
+ t = Info_ValueForKey( systemInfo, "sv_pakNames" );
+ FS_PureServerSetLoadedPaks( s, t );
+
+ s = Info_ValueForKey( systemInfo, "sv_referencedPaks" );
+ t = Info_ValueForKey( systemInfo, "sv_referencedPakNames" );
+ FS_PureServerSetReferencedPaks( s, t );
+
+ gameSet = qfalse;
+ // scan through all the variables in the systeminfo and locally set cvars to match
+ s = systemInfo;
+ while ( s ) {
+ Info_NextPair( &s, key, value );
+ if ( !key[0] ) {
+ break;
+ }
+ // ehw!
+ if ( !Q_stricmp( key, "fs_game" ) ) {
+ gameSet = qtrue;
+ }
+
+ Cvar_Set( key, value );
+ }
+ // if game folder should not be set and it is set at the client side
+ if ( !gameSet && *Cvar_VariableString("fs_game") ) {
+ Cvar_Set( "fs_game", "" );
+ }
+ cl_connectedToPureServer = Cvar_VariableValue( "sv_pure" );
+}
+
+/*
+==================
+CL_ParseGamestate
+==================
+*/
+void CL_ParseGamestate( msg_t *msg ) {
+ int i;
+ entityState_t *es;
+ int newnum;
+ entityState_t nullstate;
+ int cmd;
+ char *s;
+
+ Con_Close();
+
+ clc.connectPacketCount = 0;
+
+ // wipe local client state
+ CL_ClearState();
+
+ // a gamestate always marks a server command sequence
+ clc.serverCommandSequence = MSG_ReadLong( msg );
+
+ // parse all the configstrings and baselines
+ cl.gameState.dataCount = 1; // leave a 0 at the beginning for uninitialized configstrings
+ while ( 1 ) {
+ cmd = MSG_ReadByte( msg );
+
+ if ( cmd == svc_EOF ) {
+ break;
+ }
+
+ if ( cmd == svc_configstring ) {
+ int len;
+
+ i = MSG_ReadShort( msg );
+ if ( i < 0 || i >= MAX_CONFIGSTRINGS ) {
+ Com_Error( ERR_DROP, "configstring > MAX_CONFIGSTRINGS" );
+ }
+ s = MSG_ReadBigString( msg );
+ len = strlen( s );
+
+ if ( len + 1 + cl.gameState.dataCount > MAX_GAMESTATE_CHARS ) {
+ Com_Error( ERR_DROP, "MAX_GAMESTATE_CHARS exceeded" );
+ }
+
+ // append it to the gameState string buffer
+ cl.gameState.stringOffsets[ i ] = cl.gameState.dataCount;
+ Com_Memcpy( cl.gameState.stringData + cl.gameState.dataCount, s, len + 1 );
+ cl.gameState.dataCount += len + 1;
+ } else if ( cmd == svc_baseline ) {
+ newnum = MSG_ReadBits( msg, GENTITYNUM_BITS );
+ if ( newnum < 0 || newnum >= MAX_GENTITIES ) {
+ Com_Error( ERR_DROP, "Baseline number out of range: %i", newnum );
+ }
+ Com_Memset (&nullstate, 0, sizeof(nullstate));
+ es = &cl.entityBaselines[ newnum ];
+ MSG_ReadDeltaEntity( msg, &nullstate, es, newnum );
+ } else {
+ Com_Error( ERR_DROP, "CL_ParseGamestate: bad command byte" );
+ }
+ }
+
+ clc.clientNum = MSG_ReadLong(msg);
+ // read the checksum feed
+ clc.checksumFeed = MSG_ReadLong( msg );
+
+ // parse serverId and other cvars
+ CL_SystemInfoChanged();
+
+ // reinitialize the filesystem if the game directory has changed
+ FS_ConditionalRestart( clc.checksumFeed );
+
+ // This used to call CL_StartHunkUsers, but now we enter the download state before loading the
+ // cgame
+ CL_InitDownloads();
+
+ // make sure the game starts
+ Cvar_Set( "cl_paused", "0" );
+}
+
+
+//=====================================================================
+
+/*
+=====================
+CL_ParseDownload
+
+A download message has been received from the server
+=====================
+*/
+void CL_ParseDownload ( msg_t *msg ) {
+ int size;
+ unsigned char data[MAX_MSGLEN];
+ int block;
+
+ // read the data
+ block = MSG_ReadShort ( msg );
+
+ if ( !block )
+ {
+ // block zero is special, contains file size
+ clc.downloadSize = MSG_ReadLong ( msg );
+
+ Cvar_SetValue( "cl_downloadSize", clc.downloadSize );
+
+ if (clc.downloadSize < 0)
+ {
+ Com_Error(ERR_DROP, MSG_ReadString( msg ) );
+ return;
+ }
+ }
+
+ size = MSG_ReadShort ( msg );
+ if (size > 0)
+ MSG_ReadData( msg, data, size );
+
+ if (clc.downloadBlock != block) {
+ Com_DPrintf( "CL_ParseDownload: Expected block %d, got %d\n", clc.downloadBlock, block);
+ return;
+ }
+
+ // open the file if not opened yet
+ if (!clc.download)
+ {
+ if (!*clc.downloadTempName) {
+ Com_Printf("Server sending download, but no download was requested\n");
+ CL_AddReliableCommand( "stopdl" );
+ return;
+ }
+
+ clc.download = FS_SV_FOpenFileWrite( clc.downloadTempName );
+
+ if (!clc.download) {
+ Com_Printf( "Could not create %s\n", clc.downloadTempName );
+ CL_AddReliableCommand( "stopdl" );
+ CL_NextDownload();
+ return;
+ }
+ }
+
+ if (size)
+ FS_Write( data, size, clc.download );
+
+ CL_AddReliableCommand( va("nextdl %d", clc.downloadBlock) );
+ clc.downloadBlock++;
+
+ clc.downloadCount += size;
+
+ // So UI gets access to it
+ Cvar_SetValue( "cl_downloadCount", clc.downloadCount );
+
+ if (!size) { // A zero length block means EOF
+ if (clc.download) {
+ FS_FCloseFile( clc.download );
+ clc.download = 0;
+
+ // rename the file
+ FS_SV_Rename ( clc.downloadTempName, clc.downloadName );
+ }
+ *clc.downloadTempName = *clc.downloadName = 0;
+ Cvar_Set( "cl_downloadName", "" );
+
+ // send intentions now
+ // We need this because without it, we would hold the last nextdl and then start
+ // loading right away. If we take a while to load, the server is happily trying
+ // to send us that last block over and over.
+ // Write it twice to help make sure we acknowledge the download
+ CL_WritePacket();
+ CL_WritePacket();
+
+ // get another file if needed
+ CL_NextDownload ();
+ }
+}
+
+/*
+=====================
+CL_ParseCommandString
+
+Command strings are just saved off until cgame asks for them
+when it transitions a snapshot
+=====================
+*/
+void CL_ParseCommandString( msg_t *msg ) {
+ char *s;
+ int seq;
+ int index;
+
+ seq = MSG_ReadLong( msg );
+ s = MSG_ReadString( msg );
+
+ // see if we have already executed stored it off
+ if ( clc.serverCommandSequence >= seq ) {
+ return;
+ }
+ clc.serverCommandSequence = seq;
+
+ index = seq & (MAX_RELIABLE_COMMANDS-1);
+ Q_strncpyz( clc.serverCommands[ index ], s, sizeof( clc.serverCommands[ index ] ) );
+}
+
+
+/*
+=====================
+CL_ParseServerMessage
+=====================
+*/
+void CL_ParseServerMessage( msg_t *msg ) {
+ int cmd;
+
+ if ( cl_shownet->integer == 1 ) {
+ Com_Printf ("%i ",msg->cursize);
+ } else if ( cl_shownet->integer >= 2 ) {
+ Com_Printf ("------------------\n");
+ }
+
+ MSG_Bitstream(msg);
+
+ // get the reliable sequence acknowledge number
+ clc.reliableAcknowledge = MSG_ReadLong( msg );
+ //
+ if ( clc.reliableAcknowledge < clc.reliableSequence - MAX_RELIABLE_COMMANDS ) {
+ clc.reliableAcknowledge = clc.reliableSequence;
+ }
+
+ //
+ // parse the message
+ //
+ while ( 1 ) {
+ if ( msg->readcount > msg->cursize ) {
+ Com_Error (ERR_DROP,"CL_ParseServerMessage: read past end of server message");
+ break;
+ }
+
+ cmd = MSG_ReadByte( msg );
+
+ if ( cmd == svc_EOF) {
+ SHOWNET( msg, "END OF MESSAGE" );
+ break;
+ }
+
+ if ( cl_shownet->integer >= 2 ) {
+ if ( !svc_strings[cmd] ) {
+ Com_Printf( "%3i:BAD CMD %i\n", msg->readcount-1, cmd );
+ } else {
+ SHOWNET( msg, svc_strings[cmd] );
+ }
+ }
+
+ // other commands
+ switch ( cmd ) {
+ default:
+ Com_Error (ERR_DROP,"CL_ParseServerMessage: Illegible server message\n");
+ break;
+ case svc_nop:
+ break;
+ case svc_serverCommand:
+ CL_ParseCommandString( msg );
+ break;
+ case svc_gamestate:
+ CL_ParseGamestate( msg );
+ break;
+ case svc_snapshot:
+ CL_ParseSnapshot( msg );
+ break;
+ case svc_download:
+ CL_ParseDownload( msg );
+ break;
+ }
+ }
+}
+
+
diff --git a/code/client/cl_scrn.c b/code/client/cl_scrn.c
new file mode 100755
index 0000000..c4ccb40
--- /dev/null
+++ b/code/client/cl_scrn.c
@@ -0,0 +1,547 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// cl_scrn.c -- master for refresh, status bar, console, chat, notify, etc
+
+#include "client.h"
+
+qboolean scr_initialized; // ready to draw
+
+cvar_t *cl_timegraph;
+cvar_t *cl_debuggraph;
+cvar_t *cl_graphheight;
+cvar_t *cl_graphscale;
+cvar_t *cl_graphshift;
+
+/*
+================
+SCR_DrawNamedPic
+
+Coordinates are 640*480 virtual values
+=================
+*/
+void SCR_DrawNamedPic( float x, float y, float width, float height, const char *picname ) {
+ qhandle_t hShader;
+
+ assert( width != 0 );
+
+ hShader = re.RegisterShader( picname );
+ SCR_AdjustFrom640( &x, &y, &width, &height );
+ re.DrawStretchPic( x, y, width, height, 0, 0, 1, 1, hShader );
+}
+
+
+/*
+================
+SCR_AdjustFrom640
+
+Adjusted for resolution and screen aspect ratio
+================
+*/
+void SCR_AdjustFrom640( float *x, float *y, float *w, float *h ) {
+ float xscale;
+ float yscale;
+
+#if 0
+ // adjust for wide screens
+ if ( cls.glconfig.vidWidth * 480 > cls.glconfig.vidHeight * 640 ) {
+ *x += 0.5 * ( cls.glconfig.vidWidth - ( cls.glconfig.vidHeight * 640 / 480 ) );
+ }
+#endif
+
+ // scale for screen sizes
+ xscale = cls.glconfig.vidWidth / 640.0;
+ yscale = cls.glconfig.vidHeight / 480.0;
+ if ( x ) {
+ *x *= xscale;
+ }
+ if ( y ) {
+ *y *= yscale;
+ }
+ if ( w ) {
+ *w *= xscale;
+ }
+ if ( h ) {
+ *h *= yscale;
+ }
+}
+
+/*
+================
+SCR_FillRect
+
+Coordinates are 640*480 virtual values
+=================
+*/
+void SCR_FillRect( float x, float y, float width, float height, const float *color ) {
+ re.SetColor( color );
+
+ SCR_AdjustFrom640( &x, &y, &width, &height );
+ re.DrawStretchPic( x, y, width, height, 0, 0, 0, 0, cls.whiteShader );
+
+ re.SetColor( NULL );
+}
+
+
+/*
+================
+SCR_DrawPic
+
+Coordinates are 640*480 virtual values
+=================
+*/
+void SCR_DrawPic( float x, float y, float width, float height, qhandle_t hShader ) {
+ SCR_AdjustFrom640( &x, &y, &width, &height );
+ re.DrawStretchPic( x, y, width, height, 0, 0, 1, 1, hShader );
+}
+
+
+
+/*
+** SCR_DrawChar
+** chars are drawn at 640*480 virtual screen size
+*/
+static void SCR_DrawChar( int x, int y, float size, int ch ) {
+ int row, col;
+ float frow, fcol;
+ float ax, ay, aw, ah;
+
+ ch &= 255;
+
+ if ( ch == ' ' ) {
+ return;
+ }
+
+ if ( y < -size ) {
+ return;
+ }
+
+ ax = x;
+ ay = y;
+ aw = size;
+ ah = size;
+ SCR_AdjustFrom640( &ax, &ay, &aw, &ah );
+
+ row = ch>>4;
+ col = ch&15;
+
+ frow = row*0.0625;
+ fcol = col*0.0625;
+ size = 0.0625;
+
+ re.DrawStretchPic( ax, ay, aw, ah,
+ fcol, frow,
+ fcol + size, frow + size,
+ cls.charSetShader );
+}
+
+/*
+** SCR_DrawSmallChar
+** small chars are drawn at native screen resolution
+*/
+void SCR_DrawSmallChar( int x, int y, int ch ) {
+ int row, col;
+ float frow, fcol;
+ float size;
+
+ ch &= 255;
+
+ if ( ch == ' ' ) {
+ return;
+ }
+
+ if ( y < -SMALLCHAR_HEIGHT ) {
+ return;
+ }
+
+ row = ch>>4;
+ col = ch&15;
+
+ frow = row*0.0625;
+ fcol = col*0.0625;
+ size = 0.0625;
+
+ re.DrawStretchPic( x, y, SMALLCHAR_WIDTH, SMALLCHAR_HEIGHT,
+ fcol, frow,
+ fcol + size, frow + size,
+ cls.charSetShader );
+}
+
+
+/*
+==================
+SCR_DrawBigString[Color]
+
+Draws a multi-colored string with a drop shadow, optionally forcing
+to a fixed color.
+
+Coordinates are at 640 by 480 virtual resolution
+==================
+*/
+void SCR_DrawStringExt( int x, int y, float size, const char *string, float *setColor, qboolean forceColor ) {
+ vec4_t color;
+ const char *s;
+ int xx;
+
+ // draw the drop shadow
+ color[0] = color[1] = color[2] = 0;
+ color[3] = setColor[3];
+ re.SetColor( color );
+ s = string;
+ xx = x;
+ while ( *s ) {
+ if ( Q_IsColorString( s ) ) {
+ s += 2;
+ continue;
+ }
+ SCR_DrawChar( xx+2, y+2, size, *s );
+ xx += size;
+ s++;
+ }
+
+
+ // draw the colored text
+ s = string;
+ xx = x;
+ re.SetColor( setColor );
+ while ( *s ) {
+ if ( Q_IsColorString( s ) ) {
+ if ( !forceColor ) {
+ Com_Memcpy( color, g_color_table[ColorIndex(*(s+1))], sizeof( color ) );
+ color[3] = setColor[3];
+ re.SetColor( color );
+ }
+ s += 2;
+ continue;
+ }
+ SCR_DrawChar( xx, y, size, *s );
+ xx += size;
+ s++;
+ }
+ re.SetColor( NULL );
+}
+
+
+void SCR_DrawBigString( int x, int y, const char *s, float alpha ) {
+ float color[4];
+
+ color[0] = color[1] = color[2] = 1.0;
+ color[3] = alpha;
+ SCR_DrawStringExt( x, y, BIGCHAR_WIDTH, s, color, qfalse );
+}
+
+void SCR_DrawBigStringColor( int x, int y, const char *s, vec4_t color ) {
+ SCR_DrawStringExt( x, y, BIGCHAR_WIDTH, s, color, qtrue );
+}
+
+
+/*
+==================
+SCR_DrawSmallString[Color]
+
+Draws a multi-colored string with a drop shadow, optionally forcing
+to a fixed color.
+
+Coordinates are at 640 by 480 virtual resolution
+==================
+*/
+void SCR_DrawSmallStringExt( int x, int y, const char *string, float *setColor, qboolean forceColor ) {
+ vec4_t color;
+ const char *s;
+ int xx;
+
+ // draw the colored text
+ s = string;
+ xx = x;
+ re.SetColor( setColor );
+ while ( *s ) {
+ if ( Q_IsColorString( s ) ) {
+ if ( !forceColor ) {
+ Com_Memcpy( color, g_color_table[ColorIndex(*(s+1))], sizeof( color ) );
+ color[3] = setColor[3];
+ re.SetColor( color );
+ }
+ s += 2;
+ continue;
+ }
+ SCR_DrawSmallChar( xx, y, *s );
+ xx += SMALLCHAR_WIDTH;
+ s++;
+ }
+ re.SetColor( NULL );
+}
+
+
+
+/*
+** SCR_Strlen -- skips color escape codes
+*/
+static int SCR_Strlen( const char *str ) {
+ const char *s = str;
+ int count = 0;
+
+ while ( *s ) {
+ if ( Q_IsColorString( s ) ) {
+ s += 2;
+ } else {
+ count++;
+ s++;
+ }
+ }
+
+ return count;
+}
+
+/*
+** SCR_GetBigStringWidth
+*/
+int SCR_GetBigStringWidth( const char *str ) {
+ return SCR_Strlen( str ) * 16;
+}
+
+
+//===============================================================================
+
+/*
+=================
+SCR_DrawDemoRecording
+=================
+*/
+void SCR_DrawDemoRecording( void ) {
+ char string[1024];
+ int pos;
+
+ if ( !clc.demorecording ) {
+ return;
+ }
+ if ( clc.spDemoRecording ) {
+ return;
+ }
+
+ pos = FS_FTell( clc.demofile );
+ sprintf( string, "RECORDING %s: %ik", clc.demoName, pos / 1024 );
+
+ SCR_DrawStringExt( 320 - strlen( string ) * 4, 20, 8, string, g_color_table[7], qtrue );
+}
+
+
+/*
+===============================================================================
+
+DEBUG GRAPH
+
+===============================================================================
+*/
+
+typedef struct
+{
+ float value;
+ int color;
+} graphsamp_t;
+
+static int current;
+static graphsamp_t values[1024];
+
+/*
+==============
+SCR_DebugGraph
+==============
+*/
+void SCR_DebugGraph (float value, int color)
+{
+ values[current&1023].value = value;
+ values[current&1023].color = color;
+ current++;
+}
+
+/*
+==============
+SCR_DrawDebugGraph
+==============
+*/
+void SCR_DrawDebugGraph (void)
+{
+ int a, x, y, w, i, h;
+ float v;
+ int color;
+
+ //
+ // draw the graph
+ //
+ w = cls.glconfig.vidWidth;
+ x = 0;
+ y = cls.glconfig.vidHeight;
+ re.SetColor( g_color_table[0] );
+ re.DrawStretchPic(x, y - cl_graphheight->integer,
+ w, cl_graphheight->integer, 0, 0, 0, 0, cls.whiteShader );
+ re.SetColor( NULL );
+
+ for (a=0 ; a<w ; a++)
+ {
+ i = (current-1-a+1024) & 1023;
+ v = values[i].value;
+ color = values[i].color;
+ v = v * cl_graphscale->integer + cl_graphshift->integer;
+
+ if (v < 0)
+ v += cl_graphheight->integer * (1+(int)(-v / cl_graphheight->integer));
+ h = (int)v % cl_graphheight->integer;
+ re.DrawStretchPic( x+w-1-a, y - h, 1, h, 0, 0, 0, 0, cls.whiteShader );
+ }
+}
+
+//=============================================================================
+
+/*
+==================
+SCR_Init
+==================
+*/
+void SCR_Init( void ) {
+ cl_timegraph = Cvar_Get ("timegraph", "0", CVAR_CHEAT);
+ cl_debuggraph = Cvar_Get ("debuggraph", "0", CVAR_CHEAT);
+ cl_graphheight = Cvar_Get ("graphheight", "32", CVAR_CHEAT);
+ cl_graphscale = Cvar_Get ("graphscale", "1", CVAR_CHEAT);
+ cl_graphshift = Cvar_Get ("graphshift", "0", CVAR_CHEAT);
+
+ scr_initialized = qtrue;
+}
+
+
+//=======================================================
+
+/*
+==================
+SCR_DrawScreenField
+
+This will be called twice if rendering in stereo mode
+==================
+*/
+void SCR_DrawScreenField( stereoFrame_t stereoFrame ) {
+ re.BeginFrame( stereoFrame );
+
+ // wide aspect ratio screens need to have the sides cleared
+ // unless they are displaying game renderings
+ if ( cls.state != CA_ACTIVE ) {
+ if ( cls.glconfig.vidWidth * 480 > cls.glconfig.vidHeight * 640 ) {
+ re.SetColor( g_color_table[0] );
+ re.DrawStretchPic( 0, 0, cls.glconfig.vidWidth, cls.glconfig.vidHeight, 0, 0, 0, 0, cls.whiteShader );
+ re.SetColor( NULL );
+ }
+ }
+
+ if ( !uivm ) {
+ Com_DPrintf("draw screen without UI loaded\n");
+ return;
+ }
+
+ // if the menu is going to cover the entire screen, we
+ // don't need to render anything under it
+ if ( !VM_Call( uivm, UI_IS_FULLSCREEN )) {
+ switch( cls.state ) {
+ default:
+ Com_Error( ERR_FATAL, "SCR_DrawScreenField: bad cls.state" );
+ break;
+ case CA_CINEMATIC:
+ SCR_DrawCinematic();
+ break;
+ case CA_DISCONNECTED:
+ // force menu up
+ S_StopAllSounds();
+ VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_MAIN );
+ break;
+ case CA_CONNECTING:
+ case CA_CHALLENGING:
+ case CA_CONNECTED:
+ // connecting clients will only show the connection dialog
+ // refresh to update the time
+ VM_Call( uivm, UI_REFRESH, cls.realtime );
+ VM_Call( uivm, UI_DRAW_CONNECT_SCREEN, qfalse );
+ break;
+ case CA_LOADING:
+ case CA_PRIMED:
+ // draw the game information screen and loading progress
+ CL_CGameRendering( stereoFrame );
+
+ // also draw the connection information, so it doesn't
+ // flash away too briefly on local or lan games
+ // refresh to update the time
+ VM_Call( uivm, UI_REFRESH, cls.realtime );
+ VM_Call( uivm, UI_DRAW_CONNECT_SCREEN, qtrue );
+ break;
+ case CA_ACTIVE:
+ CL_CGameRendering( stereoFrame );
+ SCR_DrawDemoRecording();
+ break;
+ }
+ }
+
+ // the menu draws next
+ if ( cls.keyCatchers & KEYCATCH_UI && uivm ) {
+ VM_Call( uivm, UI_REFRESH, cls.realtime );
+ }
+
+ // console draws next
+ Con_DrawConsole ();
+
+ // debug graph can be drawn on top of anything
+ if ( cl_debuggraph->integer || cl_timegraph->integer || cl_debugMove->integer ) {
+ SCR_DrawDebugGraph ();
+ }
+}
+
+/*
+==================
+SCR_UpdateScreen
+
+This is called every frame, and can also be called explicitly to flush
+text to the screen.
+==================
+*/
+void SCR_UpdateScreen( void ) {
+ static int recursive;
+
+ if ( !scr_initialized ) {
+ return; // not initialized yet
+ }
+
+ if ( ++recursive > 2 ) {
+ Com_Error( ERR_FATAL, "SCR_UpdateScreen: recursively called" );
+ }
+ recursive = 1;
+
+ // if running in stereo, we need to draw the frame twice
+ if ( cls.glconfig.stereoEnabled ) {
+ SCR_DrawScreenField( STEREO_LEFT );
+ SCR_DrawScreenField( STEREO_RIGHT );
+ } else {
+ SCR_DrawScreenField( STEREO_CENTER );
+ }
+
+ if ( com_speeds->integer ) {
+ re.EndFrame( &time_frontend, &time_backend );
+ } else {
+ re.EndFrame( NULL, NULL );
+ }
+
+ recursive = 0;
+}
+
diff --git a/code/client/cl_ui.c b/code/client/cl_ui.c
new file mode 100755
index 0000000..80040a8
--- /dev/null
+++ b/code/client/cl_ui.c
@@ -0,0 +1,1200 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "client.h"
+
+#include "../game/botlib.h"
+
+extern botlib_export_t *botlib_export;
+
+vm_t *uivm;
+
+/*
+====================
+GetClientState
+====================
+*/
+static void GetClientState( uiClientState_t *state ) {
+ state->connectPacketCount = clc.connectPacketCount;
+ state->connState = cls.state;
+ Q_strncpyz( state->servername, cls.servername, sizeof( state->servername ) );
+ Q_strncpyz( state->updateInfoString, cls.updateInfoString, sizeof( state->updateInfoString ) );
+ Q_strncpyz( state->messageString, clc.serverMessage, sizeof( state->messageString ) );
+ state->clientNum = cl.snap.ps.clientNum;
+}
+
+/*
+====================
+LAN_LoadCachedServers
+====================
+*/
+void LAN_LoadCachedServers( ) {
+ int size;
+ fileHandle_t fileIn;
+ cls.numglobalservers = cls.nummplayerservers = cls.numfavoriteservers = 0;
+ cls.numGlobalServerAddresses = 0;
+ if (FS_SV_FOpenFileRead("servercache.dat", &fileIn)) {
+ FS_Read(&cls.numglobalservers, sizeof(int), fileIn);
+ FS_Read(&cls.nummplayerservers, sizeof(int), fileIn);
+ FS_Read(&cls.numfavoriteservers, sizeof(int), fileIn);
+ FS_Read(&size, sizeof(int), fileIn);
+ if (size == sizeof(cls.globalServers) + sizeof(cls.favoriteServers) + sizeof(cls.mplayerServers)) {
+ FS_Read(&cls.globalServers, sizeof(cls.globalServers), fileIn);
+ FS_Read(&cls.mplayerServers, sizeof(cls.mplayerServers), fileIn);
+ FS_Read(&cls.favoriteServers, sizeof(cls.favoriteServers), fileIn);
+ } else {
+ cls.numglobalservers = cls.nummplayerservers = cls.numfavoriteservers = 0;
+ cls.numGlobalServerAddresses = 0;
+ }
+ FS_FCloseFile(fileIn);
+ }
+}
+
+/*
+====================
+LAN_SaveServersToCache
+====================
+*/
+void LAN_SaveServersToCache( ) {
+ int size;
+ fileHandle_t fileOut = FS_SV_FOpenFileWrite("servercache.dat");
+ FS_Write(&cls.numglobalservers, sizeof(int), fileOut);
+ FS_Write(&cls.nummplayerservers, sizeof(int), fileOut);
+ FS_Write(&cls.numfavoriteservers, sizeof(int), fileOut);
+ size = sizeof(cls.globalServers) + sizeof(cls.favoriteServers) + sizeof(cls.mplayerServers);
+ FS_Write(&size, sizeof(int), fileOut);
+ FS_Write(&cls.globalServers, sizeof(cls.globalServers), fileOut);
+ FS_Write(&cls.mplayerServers, sizeof(cls.mplayerServers), fileOut);
+ FS_Write(&cls.favoriteServers, sizeof(cls.favoriteServers), fileOut);
+ FS_FCloseFile(fileOut);
+}
+
+
+/*
+====================
+LAN_ResetPings
+====================
+*/
+static void LAN_ResetPings(int source) {
+ int count,i;
+ serverInfo_t *servers = NULL;
+ count = 0;
+
+ switch (source) {
+ case AS_LOCAL :
+ servers = &cls.localServers[0];
+ count = MAX_OTHER_SERVERS;
+ break;
+ case AS_MPLAYER :
+ servers = &cls.mplayerServers[0];
+ count = MAX_OTHER_SERVERS;
+ break;
+ case AS_GLOBAL :
+ servers = &cls.globalServers[0];
+ count = MAX_GLOBAL_SERVERS;
+ break;
+ case AS_FAVORITES :
+ servers = &cls.favoriteServers[0];
+ count = MAX_OTHER_SERVERS;
+ break;
+ }
+ if (servers) {
+ for (i = 0; i < count; i++) {
+ servers[i].ping = -1;
+ }
+ }
+}
+
+/*
+====================
+LAN_AddServer
+====================
+*/
+static int LAN_AddServer(int source, const char *name, const char *address) {
+ int max, *count, i;
+ netadr_t adr;
+ serverInfo_t *servers = NULL;
+ max = MAX_OTHER_SERVERS;
+ count = 0;
+
+ switch (source) {
+ case AS_LOCAL :
+ count = &cls.numlocalservers;
+ servers = &cls.localServers[0];
+ break;
+ case AS_MPLAYER :
+ count = &cls.nummplayerservers;
+ servers = &cls.mplayerServers[0];
+ break;
+ case AS_GLOBAL :
+ max = MAX_GLOBAL_SERVERS;
+ count = &cls.numglobalservers;
+ servers = &cls.globalServers[0];
+ break;
+ case AS_FAVORITES :
+ count = &cls.numfavoriteservers;
+ servers = &cls.favoriteServers[0];
+ break;
+ }
+ if (servers && *count < max) {
+ NET_StringToAdr( address, &adr );
+ for ( i = 0; i < *count; i++ ) {
+ if (NET_CompareAdr(servers[i].adr, adr)) {
+ break;
+ }
+ }
+ if (i >= *count) {
+ servers[*count].adr = adr;
+ Q_strncpyz(servers[*count].hostName, name, sizeof(servers[*count].hostName));
+ servers[*count].visible = qtrue;
+ (*count)++;
+ return 1;
+ }
+ return 0;
+ }
+ return -1;
+}
+
+/*
+====================
+LAN_RemoveServer
+====================
+*/
+static void LAN_RemoveServer(int source, const char *addr) {
+ int *count, i;
+ serverInfo_t *servers = NULL;
+ count = 0;
+ switch (source) {
+ case AS_LOCAL :
+ count = &cls.numlocalservers;
+ servers = &cls.localServers[0];
+ break;
+ case AS_MPLAYER :
+ count = &cls.nummplayerservers;
+ servers = &cls.mplayerServers[0];
+ break;
+ case AS_GLOBAL :
+ count = &cls.numglobalservers;
+ servers = &cls.globalServers[0];
+ break;
+ case AS_FAVORITES :
+ count = &cls.numfavoriteservers;
+ servers = &cls.favoriteServers[0];
+ break;
+ }
+ if (servers) {
+ netadr_t comp;
+ NET_StringToAdr( addr, &comp );
+ for (i = 0; i < *count; i++) {
+ if (NET_CompareAdr( comp, servers[i].adr)) {
+ int j = i;
+ while (j < *count - 1) {
+ Com_Memcpy(&servers[j], &servers[j+1], sizeof(servers[j]));
+ j++;
+ }
+ (*count)--;
+ break;
+ }
+ }
+ }
+}
+
+
+/*
+====================
+LAN_GetServerCount
+====================
+*/
+static int LAN_GetServerCount( int source ) {
+ switch (source) {
+ case AS_LOCAL :
+ return cls.numlocalservers;
+ break;
+ case AS_MPLAYER :
+ return cls.nummplayerservers;
+ break;
+ case AS_GLOBAL :
+ return cls.numglobalservers;
+ break;
+ case AS_FAVORITES :
+ return cls.numfavoriteservers;
+ break;
+ }
+ return 0;
+}
+
+/*
+====================
+LAN_GetLocalServerAddressString
+====================
+*/
+static void LAN_GetServerAddressString( int source, int n, char *buf, int buflen ) {
+ switch (source) {
+ case AS_LOCAL :
+ if (n >= 0 && n < MAX_OTHER_SERVERS) {
+ Q_strncpyz(buf, NET_AdrToString( cls.localServers[n].adr) , buflen );
+ return;
+ }
+ break;
+ case AS_MPLAYER :
+ if (n >= 0 && n < MAX_OTHER_SERVERS) {
+ Q_strncpyz(buf, NET_AdrToString( cls.mplayerServers[n].adr) , buflen );
+ return;
+ }
+ break;
+ case AS_GLOBAL :
+ if (n >= 0 && n < MAX_GLOBAL_SERVERS) {
+ Q_strncpyz(buf, NET_AdrToString( cls.globalServers[n].adr) , buflen );
+ return;
+ }
+ break;
+ case AS_FAVORITES :
+ if (n >= 0 && n < MAX_OTHER_SERVERS) {
+ Q_strncpyz(buf, NET_AdrToString( cls.favoriteServers[n].adr) , buflen );
+ return;
+ }
+ break;
+ }
+ buf[0] = '\0';
+}
+
+/*
+====================
+LAN_GetServerInfo
+====================
+*/
+static void LAN_GetServerInfo( int source, int n, char *buf, int buflen ) {
+ char info[MAX_STRING_CHARS];
+ serverInfo_t *server = NULL;
+ info[0] = '\0';
+ switch (source) {
+ case AS_LOCAL :
+ if (n >= 0 && n < MAX_OTHER_SERVERS) {
+ server = &cls.localServers[n];
+ }
+ break;
+ case AS_MPLAYER :
+ if (n >= 0 && n < MAX_OTHER_SERVERS) {
+ server = &cls.mplayerServers[n];
+ }
+ break;
+ case AS_GLOBAL :
+ if (n >= 0 && n < MAX_GLOBAL_SERVERS) {
+ server = &cls.globalServers[n];
+ }
+ break;
+ case AS_FAVORITES :
+ if (n >= 0 && n < MAX_OTHER_SERVERS) {
+ server = &cls.favoriteServers[n];
+ }
+ break;
+ }
+ if (server && buf) {
+ buf[0] = '\0';
+ Info_SetValueForKey( info, "hostname", server->hostName);
+ Info_SetValueForKey( info, "mapname", server->mapName);
+ Info_SetValueForKey( info, "clients", va("%i",server->clients));
+ Info_SetValueForKey( info, "sv_maxclients", va("%i",server->maxClients));
+ Info_SetValueForKey( info, "ping", va("%i",server->ping));
+ Info_SetValueForKey( info, "minping", va("%i",server->minPing));
+ Info_SetValueForKey( info, "maxping", va("%i",server->maxPing));
+ Info_SetValueForKey( info, "game", server->game);
+ Info_SetValueForKey( info, "gametype", va("%i",server->gameType));
+ Info_SetValueForKey( info, "nettype", va("%i",server->netType));
+ Info_SetValueForKey( info, "addr", NET_AdrToString(server->adr));
+ Info_SetValueForKey( info, "punkbuster", va("%i", server->punkbuster));
+ Q_strncpyz(buf, info, buflen);
+ } else {
+ if (buf) {
+ buf[0] = '\0';
+ }
+ }
+}
+
+/*
+====================
+LAN_GetServerPing
+====================
+*/
+static int LAN_GetServerPing( int source, int n ) {
+ serverInfo_t *server = NULL;
+ switch (source) {
+ case AS_LOCAL :
+ if (n >= 0 && n < MAX_OTHER_SERVERS) {
+ server = &cls.localServers[n];
+ }
+ break;
+ case AS_MPLAYER :
+ if (n >= 0 && n < MAX_OTHER_SERVERS) {
+ server = &cls.mplayerServers[n];
+ }
+ break;
+ case AS_GLOBAL :
+ if (n >= 0 && n < MAX_GLOBAL_SERVERS) {
+ server = &cls.globalServers[n];
+ }
+ break;
+ case AS_FAVORITES :
+ if (n >= 0 && n < MAX_OTHER_SERVERS) {
+ server = &cls.favoriteServers[n];
+ }
+ break;
+ }
+ if (server) {
+ return server->ping;
+ }
+ return -1;
+}
+
+/*
+====================
+LAN_GetServerPtr
+====================
+*/
+static serverInfo_t *LAN_GetServerPtr( int source, int n ) {
+ switch (source) {
+ case AS_LOCAL :
+ if (n >= 0 && n < MAX_OTHER_SERVERS) {
+ return &cls.localServers[n];
+ }
+ break;
+ case AS_MPLAYER :
+ if (n >= 0 && n < MAX_OTHER_SERVERS) {
+ return &cls.mplayerServers[n];
+ }
+ break;
+ case AS_GLOBAL :
+ if (n >= 0 && n < MAX_GLOBAL_SERVERS) {
+ return &cls.globalServers[n];
+ }
+ break;
+ case AS_FAVORITES :
+ if (n >= 0 && n < MAX_OTHER_SERVERS) {
+ return &cls.favoriteServers[n];
+ }
+ break;
+ }
+ return NULL;
+}
+
+/*
+====================
+LAN_CompareServers
+====================
+*/
+static int LAN_CompareServers( int source, int sortKey, int sortDir, int s1, int s2 ) {
+ int res;
+ serverInfo_t *server1, *server2;
+
+ server1 = LAN_GetServerPtr(source, s1);
+ server2 = LAN_GetServerPtr(source, s2);
+ if (!server1 || !server2) {
+ return 0;
+ }
+
+ res = 0;
+ switch( sortKey ) {
+ case SORT_HOST:
+ res = Q_stricmp( server1->hostName, server2->hostName );
+ break;
+
+ case SORT_MAP:
+ res = Q_stricmp( server1->mapName, server2->mapName );
+ break;
+ case SORT_CLIENTS:
+ if (server1->clients < server2->clients) {
+ res = -1;
+ }
+ else if (server1->clients > server2->clients) {
+ res = 1;
+ }
+ else {
+ res = 0;
+ }
+ break;
+ case SORT_GAME:
+ if (server1->gameType < server2->gameType) {
+ res = -1;
+ }
+ else if (server1->gameType > server2->gameType) {
+ res = 1;
+ }
+ else {
+ res = 0;
+ }
+ break;
+ case SORT_PING:
+ if (server1->ping < server2->ping) {
+ res = -1;
+ }
+ else if (server1->ping > server2->ping) {
+ res = 1;
+ }
+ else {
+ res = 0;
+ }
+ break;
+ }
+
+ if (sortDir) {
+ if (res < 0)
+ return 1;
+ if (res > 0)
+ return -1;
+ return 0;
+ }
+ return res;
+}
+
+/*
+====================
+LAN_GetPingQueueCount
+====================
+*/
+static int LAN_GetPingQueueCount( void ) {
+ return (CL_GetPingQueueCount());
+}
+
+/*
+====================
+LAN_ClearPing
+====================
+*/
+static void LAN_ClearPing( int n ) {
+ CL_ClearPing( n );
+}
+
+/*
+====================
+LAN_GetPing
+====================
+*/
+static void LAN_GetPing( int n, char *buf, int buflen, int *pingtime ) {
+ CL_GetPing( n, buf, buflen, pingtime );
+}
+
+/*
+====================
+LAN_GetPingInfo
+====================
+*/
+static void LAN_GetPingInfo( int n, char *buf, int buflen ) {
+ CL_GetPingInfo( n, buf, buflen );
+}
+
+/*
+====================
+LAN_MarkServerVisible
+====================
+*/
+static void LAN_MarkServerVisible(int source, int n, qboolean visible ) {
+ if (n == -1) {
+ int count = MAX_OTHER_SERVERS;
+ serverInfo_t *server = NULL;
+ switch (source) {
+ case AS_LOCAL :
+ server = &cls.localServers[0];
+ break;
+ case AS_MPLAYER :
+ server = &cls.mplayerServers[0];
+ break;
+ case AS_GLOBAL :
+ server = &cls.globalServers[0];
+ count = MAX_GLOBAL_SERVERS;
+ break;
+ case AS_FAVORITES :
+ server = &cls.favoriteServers[0];
+ break;
+ }
+ if (server) {
+ for (n = 0; n < count; n++) {
+ server[n].visible = visible;
+ }
+ }
+
+ } else {
+ switch (source) {
+ case AS_LOCAL :
+ if (n >= 0 && n < MAX_OTHER_SERVERS) {
+ cls.localServers[n].visible = visible;
+ }
+ break;
+ case AS_MPLAYER :
+ if (n >= 0 && n < MAX_OTHER_SERVERS) {
+ cls.mplayerServers[n].visible = visible;
+ }
+ break;
+ case AS_GLOBAL :
+ if (n >= 0 && n < MAX_GLOBAL_SERVERS) {
+ cls.globalServers[n].visible = visible;
+ }
+ break;
+ case AS_FAVORITES :
+ if (n >= 0 && n < MAX_OTHER_SERVERS) {
+ cls.favoriteServers[n].visible = visible;
+ }
+ break;
+ }
+ }
+}
+
+
+/*
+=======================
+LAN_ServerIsVisible
+=======================
+*/
+static int LAN_ServerIsVisible(int source, int n ) {
+ switch (source) {
+ case AS_LOCAL :
+ if (n >= 0 && n < MAX_OTHER_SERVERS) {
+ return cls.localServers[n].visible;
+ }
+ break;
+ case AS_MPLAYER :
+ if (n >= 0 && n < MAX_OTHER_SERVERS) {
+ return cls.mplayerServers[n].visible;
+ }
+ break;
+ case AS_GLOBAL :
+ if (n >= 0 && n < MAX_GLOBAL_SERVERS) {
+ return cls.globalServers[n].visible;
+ }
+ break;
+ case AS_FAVORITES :
+ if (n >= 0 && n < MAX_OTHER_SERVERS) {
+ return cls.favoriteServers[n].visible;
+ }
+ break;
+ }
+ return qfalse;
+}
+
+/*
+=======================
+LAN_UpdateVisiblePings
+=======================
+*/
+qboolean LAN_UpdateVisiblePings(int source ) {
+ return CL_UpdateVisiblePings_f(source);
+}
+
+/*
+====================
+LAN_GetServerStatus
+====================
+*/
+int LAN_GetServerStatus( char *serverAddress, char *serverStatus, int maxLen ) {
+ return CL_ServerStatus( serverAddress, serverStatus, maxLen );
+}
+
+/*
+====================
+CL_GetGlConfig
+====================
+*/
+static void CL_GetGlconfig( glconfig_t *config ) {
+ *config = cls.glconfig;
+}
+
+/*
+====================
+GetClipboardData
+====================
+*/
+static void GetClipboardData( char *buf, int buflen ) {
+ char *cbd;
+
+ cbd = Sys_GetClipboardData();
+
+ if ( !cbd ) {
+ *buf = 0;
+ return;
+ }
+
+ Q_strncpyz( buf, cbd, buflen );
+
+ Z_Free( cbd );
+}
+
+/*
+====================
+Key_KeynumToStringBuf
+====================
+*/
+static void Key_KeynumToStringBuf( int keynum, char *buf, int buflen ) {
+ Q_strncpyz( buf, Key_KeynumToString( keynum ), buflen );
+}
+
+/*
+====================
+Key_GetBindingBuf
+====================
+*/
+static void Key_GetBindingBuf( int keynum, char *buf, int buflen ) {
+ char *value;
+
+ value = Key_GetBinding( keynum );
+ if ( value ) {
+ Q_strncpyz( buf, value, buflen );
+ }
+ else {
+ *buf = 0;
+ }
+}
+
+/*
+====================
+Key_GetCatcher
+====================
+*/
+int Key_GetCatcher( void ) {
+ return cls.keyCatchers;
+}
+
+/*
+====================
+Ket_SetCatcher
+====================
+*/
+void Key_SetCatcher( int catcher ) {
+ cls.keyCatchers = catcher;
+}
+
+
+/*
+====================
+CLUI_GetCDKey
+====================
+*/
+static void CLUI_GetCDKey( char *buf, int buflen ) {
+ cvar_t *fs;
+ fs = Cvar_Get ("fs_game", "", CVAR_INIT|CVAR_SYSTEMINFO );
+ if (UI_usesUniqueCDKey() && fs && fs->string[0] != 0) {
+ Com_Memcpy( buf, &cl_cdkey[16], 16);
+ buf[16] = 0;
+ } else {
+ Com_Memcpy( buf, cl_cdkey, 16);
+ buf[16] = 0;
+ }
+}
+
+
+/*
+====================
+CLUI_SetCDKey
+====================
+*/
+static void CLUI_SetCDKey( char *buf ) {
+ cvar_t *fs;
+ fs = Cvar_Get ("fs_game", "", CVAR_INIT|CVAR_SYSTEMINFO );
+ if (UI_usesUniqueCDKey() && fs && fs->string[0] != 0) {
+ Com_Memcpy( &cl_cdkey[16], buf, 16 );
+ cl_cdkey[32] = 0;
+ // set the flag so the fle will be written at the next opportunity
+ cvar_modifiedFlags |= CVAR_ARCHIVE;
+ } else {
+ Com_Memcpy( cl_cdkey, buf, 16 );
+ // set the flag so the fle will be written at the next opportunity
+ cvar_modifiedFlags |= CVAR_ARCHIVE;
+ }
+}
+
+/*
+====================
+GetConfigString
+====================
+*/
+static int GetConfigString(int index, char *buf, int size)
+{
+ int offset;
+
+ if (index < 0 || index >= MAX_CONFIGSTRINGS)
+ return qfalse;
+
+ offset = cl.gameState.stringOffsets[index];
+ if (!offset) {
+ if( size ) {
+ buf[0] = 0;
+ }
+ return qfalse;
+ }
+
+ Q_strncpyz( buf, cl.gameState.stringData+offset, size);
+
+ return qtrue;
+}
+
+/*
+====================
+FloatAsInt
+====================
+*/
+static int FloatAsInt( float f ) {
+ int temp;
+
+ *(float *)&temp = f;
+
+ return temp;
+}
+
+void *VM_ArgPtr( int intValue );
+#define VMA(x) VM_ArgPtr(args[x])
+#define VMF(x) ((float *)args)[x]
+
+/*
+====================
+CL_UISystemCalls
+
+The ui module is making a system call
+====================
+*/
+int CL_UISystemCalls( int *args ) {
+ switch( args[0] ) {
+ case UI_ERROR:
+ Com_Error( ERR_DROP, "%s", VMA(1) );
+ return 0;
+
+ case UI_PRINT:
+ Com_Printf( "%s", VMA(1) );
+ return 0;
+
+ case UI_MILLISECONDS:
+ return Sys_Milliseconds();
+
+ case UI_CVAR_REGISTER:
+ Cvar_Register( VMA(1), VMA(2), VMA(3), args[4] );
+ return 0;
+
+ case UI_CVAR_UPDATE:
+ Cvar_Update( VMA(1) );
+ return 0;
+
+ case UI_CVAR_SET:
+ Cvar_Set( VMA(1), VMA(2) );
+ return 0;
+
+ case UI_CVAR_VARIABLEVALUE:
+ return FloatAsInt( Cvar_VariableValue( VMA(1) ) );
+
+ case UI_CVAR_VARIABLESTRINGBUFFER:
+ Cvar_VariableStringBuffer( VMA(1), VMA(2), args[3] );
+ return 0;
+
+ case UI_CVAR_SETVALUE:
+ Cvar_SetValue( VMA(1), VMF(2) );
+ return 0;
+
+ case UI_CVAR_RESET:
+ Cvar_Reset( VMA(1) );
+ return 0;
+
+ case UI_CVAR_CREATE:
+ Cvar_Get( VMA(1), VMA(2), args[3] );
+ return 0;
+
+ case UI_CVAR_INFOSTRINGBUFFER:
+ Cvar_InfoStringBuffer( args[1], VMA(2), args[3] );
+ return 0;
+
+ case UI_ARGC:
+ return Cmd_Argc();
+
+ case UI_ARGV:
+ Cmd_ArgvBuffer( args[1], VMA(2), args[3] );
+ return 0;
+
+ case UI_CMD_EXECUTETEXT:
+ Cbuf_ExecuteText( args[1], VMA(2) );
+ return 0;
+
+ case UI_FS_FOPENFILE:
+ return FS_FOpenFileByMode( VMA(1), VMA(2), args[3] );
+
+ case UI_FS_READ:
+ FS_Read2( VMA(1), args[2], args[3] );
+ return 0;
+
+ case UI_FS_WRITE:
+ FS_Write( VMA(1), args[2], args[3] );
+ return 0;
+
+ case UI_FS_FCLOSEFILE:
+ FS_FCloseFile( args[1] );
+ return 0;
+
+ case UI_FS_GETFILELIST:
+ return FS_GetFileList( VMA(1), VMA(2), VMA(3), args[4] );
+
+ case UI_FS_SEEK:
+ return FS_Seek( args[1], args[2], args[3] );
+
+ case UI_R_REGISTERMODEL:
+ return re.RegisterModel( VMA(1) );
+
+ case UI_R_REGISTERSKIN:
+ return re.RegisterSkin( VMA(1) );
+
+ case UI_R_REGISTERSHADERNOMIP:
+ return re.RegisterShaderNoMip( VMA(1) );
+
+ case UI_R_CLEARSCENE:
+ re.ClearScene();
+ return 0;
+
+ case UI_R_ADDREFENTITYTOSCENE:
+ re.AddRefEntityToScene( VMA(1) );
+ return 0;
+
+ case UI_R_ADDPOLYTOSCENE:
+ re.AddPolyToScene( args[1], args[2], VMA(3), 1 );
+ return 0;
+
+ case UI_R_ADDLIGHTTOSCENE:
+ re.AddLightToScene( VMA(1), VMF(2), VMF(3), VMF(4), VMF(5) );
+ return 0;
+
+ case UI_R_RENDERSCENE:
+ re.RenderScene( VMA(1) );
+ return 0;
+
+ case UI_R_SETCOLOR:
+ re.SetColor( VMA(1) );
+ return 0;
+
+ case UI_R_DRAWSTRETCHPIC:
+ re.DrawStretchPic( VMF(1), VMF(2), VMF(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), args[9] );
+ return 0;
+
+ case UI_R_MODELBOUNDS:
+ re.ModelBounds( args[1], VMA(2), VMA(3) );
+ return 0;
+
+ case UI_UPDATESCREEN:
+ SCR_UpdateScreen();
+ return 0;
+
+ case UI_CM_LERPTAG:
+ re.LerpTag( VMA(1), args[2], args[3], args[4], VMF(5), VMA(6) );
+ return 0;
+
+ case UI_S_REGISTERSOUND:
+ return S_RegisterSound( VMA(1), args[2] );
+
+ case UI_S_STARTLOCALSOUND:
+ S_StartLocalSound( args[1], args[2] );
+ return 0;
+
+ case UI_KEY_KEYNUMTOSTRINGBUF:
+ Key_KeynumToStringBuf( args[1], VMA(2), args[3] );
+ return 0;
+
+ case UI_KEY_GETBINDINGBUF:
+ Key_GetBindingBuf( args[1], VMA(2), args[3] );
+ return 0;
+
+ case UI_KEY_SETBINDING:
+ Key_SetBinding( args[1], VMA(2) );
+ return 0;
+
+ case UI_KEY_ISDOWN:
+ return Key_IsDown( args[1] );
+
+ case UI_KEY_GETOVERSTRIKEMODE:
+ return Key_GetOverstrikeMode();
+
+ case UI_KEY_SETOVERSTRIKEMODE:
+ Key_SetOverstrikeMode( args[1] );
+ return 0;
+
+ case UI_KEY_CLEARSTATES:
+ Key_ClearStates();
+ return 0;
+
+ case UI_KEY_GETCATCHER:
+ return Key_GetCatcher();
+
+ case UI_KEY_SETCATCHER:
+ Key_SetCatcher( args[1] );
+ return 0;
+
+ case UI_GETCLIPBOARDDATA:
+ GetClipboardData( VMA(1), args[2] );
+ return 0;
+
+ case UI_GETCLIENTSTATE:
+ GetClientState( VMA(1) );
+ return 0;
+
+ case UI_GETGLCONFIG:
+ CL_GetGlconfig( VMA(1) );
+ return 0;
+
+ case UI_GETCONFIGSTRING:
+ return GetConfigString( args[1], VMA(2), args[3] );
+
+ case UI_LAN_LOADCACHEDSERVERS:
+ LAN_LoadCachedServers();
+ return 0;
+
+ case UI_LAN_SAVECACHEDSERVERS:
+ LAN_SaveServersToCache();
+ return 0;
+
+ case UI_LAN_ADDSERVER:
+ return LAN_AddServer(args[1], VMA(2), VMA(3));
+
+ case UI_LAN_REMOVESERVER:
+ LAN_RemoveServer(args[1], VMA(2));
+ return 0;
+
+ case UI_LAN_GETPINGQUEUECOUNT:
+ return LAN_GetPingQueueCount();
+
+ case UI_LAN_CLEARPING:
+ LAN_ClearPing( args[1] );
+ return 0;
+
+ case UI_LAN_GETPING:
+ LAN_GetPing( args[1], VMA(2), args[3], VMA(4) );
+ return 0;
+
+ case UI_LAN_GETPINGINFO:
+ LAN_GetPingInfo( args[1], VMA(2), args[3] );
+ return 0;
+
+ case UI_LAN_GETSERVERCOUNT:
+ return LAN_GetServerCount(args[1]);
+
+ case UI_LAN_GETSERVERADDRESSSTRING:
+ LAN_GetServerAddressString( args[1], args[2], VMA(3), args[4] );
+ return 0;
+
+ case UI_LAN_GETSERVERINFO:
+ LAN_GetServerInfo( args[1], args[2], VMA(3), args[4] );
+ return 0;
+
+ case UI_LAN_GETSERVERPING:
+ return LAN_GetServerPing( args[1], args[2] );
+
+ case UI_LAN_MARKSERVERVISIBLE:
+ LAN_MarkServerVisible( args[1], args[2], args[3] );
+ return 0;
+
+ case UI_LAN_SERVERISVISIBLE:
+ return LAN_ServerIsVisible( args[1], args[2] );
+
+ case UI_LAN_UPDATEVISIBLEPINGS:
+ return LAN_UpdateVisiblePings( args[1] );
+
+ case UI_LAN_RESETPINGS:
+ LAN_ResetPings( args[1] );
+ return 0;
+
+ case UI_LAN_SERVERSTATUS:
+ return LAN_GetServerStatus( VMA(1), VMA(2), args[3] );
+
+ case UI_LAN_COMPARESERVERS:
+ return LAN_CompareServers( args[1], args[2], args[3], args[4], args[5] );
+
+ case UI_MEMORY_REMAINING:
+ return Hunk_MemoryRemaining();
+
+ case UI_GET_CDKEY:
+ CLUI_GetCDKey( VMA(1), args[2] );
+ return 0;
+
+ case UI_SET_CDKEY:
+ CLUI_SetCDKey( VMA(1) );
+ return 0;
+
+ case UI_SET_PBCLSTATUS:
+ return 0;
+
+ case UI_R_REGISTERFONT:
+ re.RegisterFont( VMA(1), args[2], VMA(3));
+ return 0;
+
+ case UI_MEMSET:
+ Com_Memset( VMA(1), args[2], args[3] );
+ return 0;
+
+ case UI_MEMCPY:
+ Com_Memcpy( VMA(1), VMA(2), args[3] );
+ return 0;
+
+ case UI_STRNCPY:
+ return (int)strncpy( VMA(1), VMA(2), args[3] );
+
+ case UI_SIN:
+ return FloatAsInt( sin( VMF(1) ) );
+
+ case UI_COS:
+ return FloatAsInt( cos( VMF(1) ) );
+
+ case UI_ATAN2:
+ return FloatAsInt( atan2( VMF(1), VMF(2) ) );
+
+ case UI_SQRT:
+ return FloatAsInt( sqrt( VMF(1) ) );
+
+ case UI_FLOOR:
+ return FloatAsInt( floor( VMF(1) ) );
+
+ case UI_CEIL:
+ return FloatAsInt( ceil( VMF(1) ) );
+
+ case UI_PC_ADD_GLOBAL_DEFINE:
+ return botlib_export->PC_AddGlobalDefine( VMA(1) );
+ case UI_PC_LOAD_SOURCE:
+ return botlib_export->PC_LoadSourceHandle( VMA(1) );
+ case UI_PC_FREE_SOURCE:
+ return botlib_export->PC_FreeSourceHandle( args[1] );
+ case UI_PC_READ_TOKEN:
+ return botlib_export->PC_ReadTokenHandle( args[1], VMA(2) );
+ case UI_PC_SOURCE_FILE_AND_LINE:
+ return botlib_export->PC_SourceFileAndLine( args[1], VMA(2), VMA(3) );
+
+ case UI_S_STOPBACKGROUNDTRACK:
+ S_StopBackgroundTrack();
+ return 0;
+ case UI_S_STARTBACKGROUNDTRACK:
+ S_StartBackgroundTrack( VMA(1), VMA(2));
+ return 0;
+
+ case UI_REAL_TIME:
+ return Com_RealTime( VMA(1) );
+
+ case UI_CIN_PLAYCINEMATIC:
+ Com_DPrintf("UI_CIN_PlayCinematic\n");
+ return CIN_PlayCinematic(VMA(1), args[2], args[3], args[4], args[5], args[6]);
+
+ case UI_CIN_STOPCINEMATIC:
+ return CIN_StopCinematic(args[1]);
+
+ case UI_CIN_RUNCINEMATIC:
+ return CIN_RunCinematic(args[1]);
+
+ case UI_CIN_DRAWCINEMATIC:
+ CIN_DrawCinematic(args[1]);
+ return 0;
+
+ case UI_CIN_SETEXTENTS:
+ CIN_SetExtents(args[1], args[2], args[3], args[4], args[5]);
+ return 0;
+
+ case UI_R_REMAP_SHADER:
+ re.RemapShader( VMA(1), VMA(2), VMA(3) );
+ return 0;
+
+ case UI_VERIFY_CDKEY:
+ return CL_CDKeyValidate(VMA(1), VMA(2));
+
+
+
+ default:
+ Com_Error( ERR_DROP, "Bad UI system trap: %i", args[0] );
+
+ }
+
+ return 0;
+}
+
+/*
+====================
+CL_ShutdownUI
+====================
+*/
+void CL_ShutdownUI( void ) {
+ cls.keyCatchers &= ~KEYCATCH_UI;
+ cls.uiStarted = qfalse;
+ if ( !uivm ) {
+ return;
+ }
+ VM_Call( uivm, UI_SHUTDOWN );
+ VM_Free( uivm );
+ uivm = NULL;
+}
+
+/*
+====================
+CL_InitUI
+====================
+*/
+#define UI_OLD_API_VERSION 4
+
+void CL_InitUI( void ) {
+ int v;
+ vmInterpret_t interpret;
+
+ // load the dll or bytecode
+ if ( cl_connectedToPureServer != 0 ) {
+ // if sv_pure is set we only allow qvms to be loaded
+ interpret = VMI_COMPILED;
+ }
+ else {
+ interpret = Cvar_VariableValue( "vm_ui" );
+ }
+ uivm = VM_Create( "ui", CL_UISystemCalls, interpret );
+ if ( !uivm ) {
+ Com_Error( ERR_FATAL, "VM_Create on UI failed" );
+ }
+
+ // sanity check
+ v = VM_Call( uivm, UI_GETAPIVERSION );
+ if (v == UI_OLD_API_VERSION) {
+// Com_Printf(S_COLOR_YELLOW "WARNING: loading old Quake III Arena User Interface version %d\n", v );
+ // init for this gamestate
+ VM_Call( uivm, UI_INIT, (cls.state >= CA_AUTHORIZING && cls.state < CA_ACTIVE));
+ }
+ else if (v != UI_API_VERSION) {
+ Com_Error( ERR_DROP, "User Interface is version %d, expected %d", v, UI_API_VERSION );
+ cls.uiStarted = qfalse;
+ }
+ else {
+ // init for this gamestate
+ VM_Call( uivm, UI_INIT, (cls.state >= CA_AUTHORIZING && cls.state < CA_ACTIVE) );
+ }
+}
+
+qboolean UI_usesUniqueCDKey() {
+ if (uivm) {
+ return (VM_Call( uivm, UI_HASUNIQUECDKEY) == qtrue);
+ } else {
+ return qfalse;
+ }
+}
+
+/*
+====================
+UI_GameCommand
+
+See if the current console command is claimed by the ui
+====================
+*/
+qboolean UI_GameCommand( void ) {
+ if ( !uivm ) {
+ return qfalse;
+ }
+
+ return VM_Call( uivm, UI_CONSOLE_COMMAND, cls.realtime );
+}
diff --git a/code/client/client.h b/code/client/client.h
new file mode 100755
index 0000000..09e02a8
--- /dev/null
+++ b/code/client/client.h
@@ -0,0 +1,519 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// client.h -- primary header for client
+
+#include "../game/q_shared.h"
+#include "../qcommon/qcommon.h"
+#include "../renderer/tr_public.h"
+#include "../ui/ui_public.h"
+#include "keys.h"
+#include "snd_public.h"
+#include "../cgame/cg_public.h"
+#include "../game/bg_public.h"
+
+#define RETRANSMIT_TIMEOUT 3000 // time between connection packet retransmits
+
+
+// snapshots are a view of the server at a given time
+typedef struct {
+ qboolean valid; // cleared if delta parsing was invalid
+ int snapFlags; // rate delayed and dropped commands
+
+ int serverTime; // server time the message is valid for (in msec)
+
+ int messageNum; // copied from netchan->incoming_sequence
+ int deltaNum; // messageNum the delta is from
+ int ping; // time from when cmdNum-1 was sent to time packet was reeceived
+ byte areamask[MAX_MAP_AREA_BYTES]; // portalarea visibility bits
+
+ int cmdNum; // the next cmdNum the server is expecting
+ playerState_t ps; // complete information about the current player at this time
+
+ int numEntities; // all of the entities that need to be presented
+ int parseEntitiesNum; // at the time of this snapshot
+
+ int serverCommandNum; // execute all commands up to this before
+ // making the snapshot current
+} clSnapshot_t;
+
+
+
+/*
+=============================================================================
+
+the clientActive_t structure is wiped completely at every
+new gamestate_t, potentially several times during an established connection
+
+=============================================================================
+*/
+
+typedef struct {
+ int p_cmdNumber; // cl.cmdNumber when packet was sent
+ int p_serverTime; // usercmd->serverTime when packet was sent
+ int p_realtime; // cls.realtime when packet was sent
+} outPacket_t;
+
+// the parseEntities array must be large enough to hold PACKET_BACKUP frames of
+// entities, so that when a delta compressed message arives from the server
+// it can be un-deltad from the original
+#define MAX_PARSE_ENTITIES 2048
+
+extern int g_console_field_width;
+
+typedef struct {
+ int timeoutcount; // it requres several frames in a timeout condition
+ // to disconnect, preventing debugging breaks from
+ // causing immediate disconnects on continue
+ clSnapshot_t snap; // latest received from server
+
+ int serverTime; // may be paused during play
+ int oldServerTime; // to prevent time from flowing bakcwards
+ int oldFrameServerTime; // to check tournament restarts
+ int serverTimeDelta; // cl.serverTime = cls.realtime + cl.serverTimeDelta
+ // this value changes as net lag varies
+ qboolean extrapolatedSnapshot; // set if any cgame frame has been forced to extrapolate
+ // cleared when CL_AdjustTimeDelta looks at it
+ qboolean newSnapshots; // set on parse of any valid packet
+
+ gameState_t gameState; // configstrings
+ char mapname[MAX_QPATH]; // extracted from CS_SERVERINFO
+
+ int parseEntitiesNum; // index (not anded off) into cl_parse_entities[]
+
+ int mouseDx[2], mouseDy[2]; // added to by mouse events
+ int mouseIndex;
+ int joystickAxis[MAX_JOYSTICK_AXIS]; // set by joystick events
+
+ // cgame communicates a few values to the client system
+ int cgameUserCmdValue; // current weapon to add to usercmd_t
+ float cgameSensitivity;
+
+ // cmds[cmdNumber] is the predicted command, [cmdNumber-1] is the last
+ // properly generated command
+ usercmd_t cmds[CMD_BACKUP]; // each mesage will send several old cmds
+ int cmdNumber; // incremented each frame, because multiple
+ // frames may need to be packed into a single packet
+
+ outPacket_t outPackets[PACKET_BACKUP]; // information about each packet we have sent out
+
+ // the client maintains its own idea of view angles, which are
+ // sent to the server each frame. It is cleared to 0 upon entering each level.
+ // the server sends a delta each frame which is added to the locally
+ // tracked view angles to account for standing on rotating objects,
+ // and teleport direction changes
+ vec3_t viewangles;
+
+ int serverId; // included in each client message so the server
+ // can tell if it is for a prior map_restart
+ // big stuff at end of structure so most offsets are 15 bits or less
+ clSnapshot_t snapshots[PACKET_BACKUP];
+
+ entityState_t entityBaselines[MAX_GENTITIES]; // for delta compression when not in previous frame
+
+ entityState_t parseEntities[MAX_PARSE_ENTITIES];
+} clientActive_t;
+
+extern clientActive_t cl;
+
+/*
+=============================================================================
+
+the clientConnection_t structure is wiped when disconnecting from a server,
+either to go to a full screen console, play a demo, or connect to a different server
+
+A connection can be to either a server through the network layer or a
+demo through a file.
+
+=============================================================================
+*/
+
+
+typedef struct {
+
+ int clientNum;
+ int lastPacketSentTime; // for retransmits during connection
+ int lastPacketTime; // for timeouts
+
+ netadr_t serverAddress;
+ int connectTime; // for connection retransmits
+ int connectPacketCount; // for display on connection dialog
+ char serverMessage[MAX_STRING_TOKENS]; // for display on connection dialog
+
+ int challenge; // from the server to use for connecting
+ int checksumFeed; // from the server for checksum calculations
+
+ // these are our reliable messages that go to the server
+ int reliableSequence;
+ int reliableAcknowledge; // the last one the server has executed
+ char reliableCommands[MAX_RELIABLE_COMMANDS][MAX_STRING_CHARS];
+
+ // server message (unreliable) and command (reliable) sequence
+ // numbers are NOT cleared at level changes, but continue to
+ // increase as long as the connection is valid
+
+ // message sequence is used by both the network layer and the
+ // delta compression layer
+ int serverMessageSequence;
+
+ // reliable messages received from server
+ int serverCommandSequence;
+ int lastExecutedServerCommand; // last server command grabbed or executed with CL_GetServerCommand
+ char serverCommands[MAX_RELIABLE_COMMANDS][MAX_STRING_CHARS];
+
+ // file transfer from server
+ fileHandle_t download;
+ char downloadTempName[MAX_OSPATH];
+ char downloadName[MAX_OSPATH];
+ int downloadNumber;
+ int downloadBlock; // block we are waiting for
+ int downloadCount; // how many bytes we got
+ int downloadSize; // how many bytes we got
+ char downloadList[MAX_INFO_STRING]; // list of paks we need to download
+ qboolean downloadRestart; // if true, we need to do another FS_Restart because we downloaded a pak
+
+ // demo information
+ char demoName[MAX_QPATH];
+ qboolean spDemoRecording;
+ qboolean demorecording;
+ qboolean demoplaying;
+ qboolean demowaiting; // don't record until a non-delta message is received
+ qboolean firstDemoFrameSkipped;
+ fileHandle_t demofile;
+
+ int timeDemoFrames; // counter of rendered frames
+ int timeDemoStart; // cls.realtime before first frame
+ int timeDemoBaseTime; // each frame will be at this time + frameNum * 50
+
+ // big stuff at end of structure so most offsets are 15 bits or less
+ netchan_t netchan;
+} clientConnection_t;
+
+extern clientConnection_t clc;
+
+/*
+==================================================================
+
+the clientStatic_t structure is never wiped, and is used even when
+no client connection is active at all
+
+==================================================================
+*/
+
+typedef struct {
+ netadr_t adr;
+ int start;
+ int time;
+ char info[MAX_INFO_STRING];
+} ping_t;
+
+typedef struct {
+ netadr_t adr;
+ char hostName[MAX_NAME_LENGTH];
+ char mapName[MAX_NAME_LENGTH];
+ char game[MAX_NAME_LENGTH];
+ int netType;
+ int gameType;
+ int clients;
+ int maxClients;
+ int minPing;
+ int maxPing;
+ int ping;
+ qboolean visible;
+ int punkbuster;
+} serverInfo_t;
+
+typedef struct {
+ byte ip[4];
+ unsigned short port;
+} serverAddress_t;
+
+typedef struct {
+ connstate_t state; // connection status
+ int keyCatchers; // bit flags
+
+ qboolean cddialog; // bring up the cd needed dialog next frame
+
+ char servername[MAX_OSPATH]; // name of server from original connect (used by reconnect)
+
+ // when the server clears the hunk, all of these must be restarted
+ qboolean rendererStarted;
+ qboolean soundStarted;
+ qboolean soundRegistered;
+ qboolean uiStarted;
+ qboolean cgameStarted;
+
+ int framecount;
+ int frametime; // msec since last frame
+
+ int realtime; // ignores pause
+ int realFrametime; // ignoring pause, so console always works
+
+ int numlocalservers;
+ serverInfo_t localServers[MAX_OTHER_SERVERS];
+
+ int numglobalservers;
+ serverInfo_t globalServers[MAX_GLOBAL_SERVERS];
+ // additional global servers
+ int numGlobalServerAddresses;
+ serverAddress_t globalServerAddresses[MAX_GLOBAL_SERVERS];
+
+ int numfavoriteservers;
+ serverInfo_t favoriteServers[MAX_OTHER_SERVERS];
+
+ int nummplayerservers;
+ serverInfo_t mplayerServers[MAX_OTHER_SERVERS];
+
+ int pingUpdateSource; // source currently pinging or updating
+
+ int masterNum;
+
+ // update server info
+ netadr_t updateServer;
+ char updateChallenge[MAX_TOKEN_CHARS];
+ char updateInfoString[MAX_INFO_STRING];
+
+ netadr_t authorizeServer;
+
+ // rendering info
+ glconfig_t glconfig;
+ qhandle_t charSetShader;
+ qhandle_t whiteShader;
+ qhandle_t consoleShader;
+} clientStatic_t;
+
+extern clientStatic_t cls;
+
+//=============================================================================
+
+extern vm_t *cgvm; // interface to cgame dll or vm
+extern vm_t *uivm; // interface to ui dll or vm
+extern refexport_t re; // interface to refresh .dll
+
+
+//
+// cvars
+//
+extern cvar_t *cl_nodelta;
+extern cvar_t *cl_debugMove;
+extern cvar_t *cl_noprint;
+extern cvar_t *cl_timegraph;
+extern cvar_t *cl_maxpackets;
+extern cvar_t *cl_packetdup;
+extern cvar_t *cl_shownet;
+extern cvar_t *cl_showSend;
+extern cvar_t *cl_timeNudge;
+extern cvar_t *cl_showTimeDelta;
+extern cvar_t *cl_freezeDemo;
+
+extern cvar_t *cl_yawspeed;
+extern cvar_t *cl_pitchspeed;
+extern cvar_t *cl_run;
+extern cvar_t *cl_anglespeedkey;
+
+extern cvar_t *cl_sensitivity;
+extern cvar_t *cl_freelook;
+
+extern cvar_t *cl_mouseAccel;
+extern cvar_t *cl_showMouseRate;
+
+extern cvar_t *m_pitch;
+extern cvar_t *m_yaw;
+extern cvar_t *m_forward;
+extern cvar_t *m_side;
+extern cvar_t *m_filter;
+
+extern cvar_t *cl_timedemo;
+
+extern cvar_t *cl_activeAction;
+
+extern cvar_t *cl_allowDownload;
+extern cvar_t *cl_conXOffset;
+extern cvar_t *cl_inGameVideo;
+
+//=================================================
+
+//
+// cl_main
+//
+
+void CL_Init (void);
+void CL_FlushMemory(void);
+void CL_ShutdownAll(void);
+void CL_AddReliableCommand( const char *cmd );
+
+void CL_StartHunkUsers( void );
+
+void CL_Disconnect_f (void);
+void CL_GetChallengePacket (void);
+void CL_Vid_Restart_f( void );
+void CL_Snd_Restart_f (void);
+void CL_StartDemoLoop( void );
+void CL_NextDemo( void );
+void CL_ReadDemoMessage( void );
+
+void CL_InitDownloads(void);
+void CL_NextDownload(void);
+
+void CL_GetPing( int n, char *buf, int buflen, int *pingtime );
+void CL_GetPingInfo( int n, char *buf, int buflen );
+void CL_ClearPing( int n );
+int CL_GetPingQueueCount( void );
+
+void CL_ShutdownRef( void );
+void CL_InitRef( void );
+qboolean CL_CDKeyValidate( const char *key, const char *checksum );
+int CL_ServerStatus( char *serverAddress, char *serverStatusString, int maxLen );
+
+
+//
+// cl_input
+//
+typedef struct {
+ int down[2]; // key nums holding it down
+ unsigned downtime; // msec timestamp
+ unsigned msec; // msec down this frame if both a down and up happened
+ qboolean active; // current state
+ qboolean wasPressed; // set when down, not cleared when up
+} kbutton_t;
+
+extern kbutton_t in_mlook, in_klook;
+extern kbutton_t in_strafe;
+extern kbutton_t in_speed;
+
+void CL_InitInput (void);
+void CL_SendCmd (void);
+void CL_ClearState (void);
+void CL_ReadPackets (void);
+
+void CL_WritePacket( void );
+void IN_CenterView (void);
+
+void CL_VerifyCode( void );
+
+float CL_KeyState (kbutton_t *key);
+char *Key_KeynumToString (int keynum);
+
+//
+// cl_parse.c
+//
+extern int cl_connectedToPureServer;
+
+void CL_SystemInfoChanged( void );
+void CL_ParseServerMessage( msg_t *msg );
+
+//====================================================================
+
+void CL_ServerInfoPacket( netadr_t from, msg_t *msg );
+void CL_LocalServers_f( void );
+void CL_GlobalServers_f( void );
+void CL_FavoriteServers_f( void );
+void CL_Ping_f( void );
+qboolean CL_UpdateVisiblePings_f( int source );
+
+
+//
+// console
+//
+void Con_DrawCharacter (int cx, int line, int num);
+
+void Con_CheckResize (void);
+void Con_Init (void);
+void Con_Clear_f (void);
+void Con_ToggleConsole_f (void);
+void Con_DrawNotify (void);
+void Con_ClearNotify (void);
+void Con_RunConsole (void);
+void Con_DrawConsole (void);
+void Con_PageUp( void );
+void Con_PageDown( void );
+void Con_Top( void );
+void Con_Bottom( void );
+void Con_Close( void );
+
+
+//
+// cl_scrn.c
+//
+void SCR_Init (void);
+void SCR_UpdateScreen (void);
+
+void SCR_DebugGraph (float value, int color);
+
+int SCR_GetBigStringWidth( const char *str ); // returns in virtual 640x480 coordinates
+
+void SCR_AdjustFrom640( float *x, float *y, float *w, float *h );
+void SCR_FillRect( float x, float y, float width, float height,
+ const float *color );
+void SCR_DrawPic( float x, float y, float width, float height, qhandle_t hShader );
+void SCR_DrawNamedPic( float x, float y, float width, float height, const char *picname );
+
+void SCR_DrawBigString( int x, int y, const char *s, float alpha ); // draws a string with embedded color control characters with fade
+void SCR_DrawBigStringColor( int x, int y, const char *s, vec4_t color ); // ignores embedded color control characters
+void SCR_DrawSmallStringExt( int x, int y, const char *string, float *setColor, qboolean forceColor );
+void SCR_DrawSmallChar( int x, int y, int ch );
+
+
+//
+// cl_cin.c
+//
+
+void CL_PlayCinematic_f( void );
+void SCR_DrawCinematic (void);
+void SCR_RunCinematic (void);
+void SCR_StopCinematic (void);
+int CIN_PlayCinematic( const char *arg0, int xpos, int ypos, int width, int height, int bits);
+e_status CIN_StopCinematic(int handle);
+e_status CIN_RunCinematic (int handle);
+void CIN_DrawCinematic (int handle);
+void CIN_SetExtents (int handle, int x, int y, int w, int h);
+void CIN_SetLooping (int handle, qboolean loop);
+void CIN_UploadCinematic(int handle);
+void CIN_CloseAllVideos(void);
+
+//
+// cl_cgame.c
+//
+void CL_InitCGame( void );
+void CL_ShutdownCGame( void );
+qboolean CL_GameCommand( void );
+void CL_CGameRendering( stereoFrame_t stereo );
+void CL_SetCGameTime( void );
+void CL_FirstSnapshot( void );
+void CL_ShaderStateChanged(void);
+
+//
+// cl_ui.c
+//
+void CL_InitUI( void );
+void CL_ShutdownUI( void );
+int Key_GetCatcher( void );
+void Key_SetCatcher( int catcher );
+void LAN_LoadCachedServers();
+void LAN_SaveServersToCache();
+
+
+//
+// cl_net_chan.c
+//
+void CL_Netchan_Transmit( netchan_t *chan, msg_t* msg); //int length, const byte *data );
+void CL_Netchan_TransmitNextFragment( netchan_t *chan );
+qboolean CL_Netchan_Process( netchan_t *chan, msg_t *msg );
diff --git a/code/client/keys.h b/code/client/keys.h
new file mode 100755
index 0000000..bc598f4
--- /dev/null
+++ b/code/client/keys.h
@@ -0,0 +1,57 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "../ui/keycodes.h"
+
+#define MAX_KEYS 256
+
+typedef struct {
+ qboolean down;
+ int repeats; // if > 1, it is autorepeating
+ char *binding;
+} qkey_t;
+
+extern qboolean key_overstrikeMode;
+extern qkey_t keys[MAX_KEYS];
+
+// NOTE TTimo the declaration of field_t and Field_Clear is now in qcommon/qcommon.h
+void Field_KeyDownEvent( field_t *edit, int key );
+void Field_CharEvent( field_t *edit, int ch );
+void Field_Draw( field_t *edit, int x, int y, int width, qboolean showCursor );
+void Field_BigDraw( field_t *edit, int x, int y, int width, qboolean showCursor );
+
+#define COMMAND_HISTORY 32
+extern field_t historyEditLines[COMMAND_HISTORY];
+
+extern field_t g_consoleField;
+extern field_t chatField;
+extern qboolean anykeydown;
+extern qboolean chat_team;
+extern int chat_playerNum;
+
+void Key_WriteBindings( fileHandle_t f );
+void Key_SetBinding( int keynum, const char *binding );
+char *Key_GetBinding( int keynum );
+qboolean Key_IsDown( int keynum );
+qboolean Key_GetOverstrikeMode( void );
+void Key_SetOverstrikeMode( qboolean state );
+void Key_ClearStates( void );
+int Key_GetKey(const char *binding);
diff --git a/code/client/snd_adpcm.c b/code/client/snd_adpcm.c
new file mode 100755
index 0000000..bc52ad4
--- /dev/null
+++ b/code/client/snd_adpcm.c
@@ -0,0 +1,330 @@
+/***********************************************************
+Copyright 1992 by Stichting Mathematisch Centrum, Amsterdam, The
+Netherlands.
+
+ All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and its
+documentation for any purpose and without fee is hereby granted,
+provided that the above copyright notice appear in all copies and that
+both that copyright notice and this permission notice appear in
+supporting documentation, and that the names of Stichting Mathematisch
+Centrum or CWI not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior permission.
+
+STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
+THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
+FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+******************************************************************/
+
+/*
+** Intel/DVI ADPCM coder/decoder.
+**
+** The algorithm for this coder was taken from the IMA Compatability Project
+** proceedings, Vol 2, Number 2; May 1992.
+**
+** Version 1.2, 18-Dec-92.
+*/
+
+#include "snd_local.h"
+
+
+/* Intel ADPCM step variation table */
+static int indexTable[16] = {
+ -1, -1, -1, -1, 2, 4, 6, 8,
+ -1, -1, -1, -1, 2, 4, 6, 8,
+};
+
+static int stepsizeTable[89] = {
+ 7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
+ 19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
+ 50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
+ 130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
+ 337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
+ 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
+ 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
+ 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
+ 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
+};
+
+
+void S_AdpcmEncode( short indata[], char outdata[], int len, struct adpcm_state *state ) {
+ short *inp; /* Input buffer pointer */
+ signed char *outp; /* output buffer pointer */
+ int val; /* Current input sample value */
+ int sign; /* Current adpcm sign bit */
+ int delta; /* Current adpcm output value */
+ int diff; /* Difference between val and sample */
+ int step; /* Stepsize */
+ int valpred; /* Predicted output value */
+ int vpdiff; /* Current change to valpred */
+ int index; /* Current step change index */
+ int outputbuffer; /* place to keep previous 4-bit value */
+ int bufferstep; /* toggle between outputbuffer/output */
+
+ outp = (signed char *)outdata;
+ inp = indata;
+
+ valpred = state->sample;
+ index = state->index;
+ step = stepsizeTable[index];
+
+ outputbuffer = 0; // quiet a compiler warning
+ bufferstep = 1;
+
+ for ( ; len > 0 ; len-- ) {
+ val = *inp++;
+
+ /* Step 1 - compute difference with previous value */
+ diff = val - valpred;
+ sign = (diff < 0) ? 8 : 0;
+ if ( sign ) diff = (-diff);
+
+ /* Step 2 - Divide and clamp */
+ /* Note:
+ ** This code *approximately* computes:
+ ** delta = diff*4/step;
+ ** vpdiff = (delta+0.5)*step/4;
+ ** but in shift step bits are dropped. The net result of this is
+ ** that even if you have fast mul/div hardware you cannot put it to
+ ** good use since the fixup would be too expensive.
+ */
+ delta = 0;
+ vpdiff = (step >> 3);
+
+ if ( diff >= step ) {
+ delta = 4;
+ diff -= step;
+ vpdiff += step;
+ }
+ step >>= 1;
+ if ( diff >= step ) {
+ delta |= 2;
+ diff -= step;
+ vpdiff += step;
+ }
+ step >>= 1;
+ if ( diff >= step ) {
+ delta |= 1;
+ vpdiff += step;
+ }
+
+ /* Step 3 - Update previous value */
+ if ( sign )
+ valpred -= vpdiff;
+ else
+ valpred += vpdiff;
+
+ /* Step 4 - Clamp previous value to 16 bits */
+ if ( valpred > 32767 )
+ valpred = 32767;
+ else if ( valpred < -32768 )
+ valpred = -32768;
+
+ /* Step 5 - Assemble value, update index and step values */
+ delta |= sign;
+
+ index += indexTable[delta];
+ if ( index < 0 ) index = 0;
+ if ( index > 88 ) index = 88;
+ step = stepsizeTable[index];
+
+ /* Step 6 - Output value */
+ if ( bufferstep ) {
+ outputbuffer = (delta << 4) & 0xf0;
+ } else {
+ *outp++ = (delta & 0x0f) | outputbuffer;
+ }
+ bufferstep = !bufferstep;
+ }
+
+ /* Output last step, if needed */
+ if ( !bufferstep )
+ *outp++ = outputbuffer;
+
+ state->sample = valpred;
+ state->index = index;
+}
+
+
+/* static */ void S_AdpcmDecode( const char indata[], short *outdata, int len, struct adpcm_state *state ) {
+ signed char *inp; /* Input buffer pointer */
+ int outp; /* output buffer pointer */
+ int sign; /* Current adpcm sign bit */
+ int delta; /* Current adpcm output value */
+ int step; /* Stepsize */
+ int valpred; /* Predicted value */
+ int vpdiff; /* Current change to valpred */
+ int index; /* Current step change index */
+ int inputbuffer; /* place to keep next 4-bit value */
+ int bufferstep; /* toggle between inputbuffer/input */
+
+ outp = 0;
+ inp = (signed char *)indata;
+
+ valpred = state->sample;
+ index = state->index;
+ step = stepsizeTable[index];
+
+ bufferstep = 0;
+ inputbuffer = 0; // quiet a compiler warning
+ for ( ; len > 0 ; len-- ) {
+
+ /* Step 1 - get the delta value */
+ if ( bufferstep ) {
+ delta = inputbuffer & 0xf;
+ } else {
+ inputbuffer = *inp++;
+ delta = (inputbuffer >> 4) & 0xf;
+ }
+ bufferstep = !bufferstep;
+
+ /* Step 2 - Find new index value (for later) */
+ index += indexTable[delta];
+ if ( index < 0 ) index = 0;
+ if ( index > 88 ) index = 88;
+
+ /* Step 3 - Separate sign and magnitude */
+ sign = delta & 8;
+ delta = delta & 7;
+
+ /* Step 4 - Compute difference and new predicted value */
+ /*
+ ** Computes 'vpdiff = (delta+0.5)*step/4', but see comment
+ ** in adpcm_coder.
+ */
+ vpdiff = step >> 3;
+ if ( delta & 4 ) vpdiff += step;
+ if ( delta & 2 ) vpdiff += step>>1;
+ if ( delta & 1 ) vpdiff += step>>2;
+
+ if ( sign )
+ valpred -= vpdiff;
+ else
+ valpred += vpdiff;
+
+ /* Step 5 - clamp output value */
+ if ( valpred > 32767 )
+ valpred = 32767;
+ else if ( valpred < -32768 )
+ valpred = -32768;
+
+ /* Step 6 - Update step value */
+ step = stepsizeTable[index];
+
+ /* Step 7 - Output value */
+ outdata[outp] = valpred;
+ outp++;
+ }
+
+ state->sample = valpred;
+ state->index = index;
+}
+
+
+/*
+====================
+S_AdpcmMemoryNeeded
+
+Returns the amount of memory (in bytes) needed to store the samples in out internal adpcm format
+====================
+*/
+int S_AdpcmMemoryNeeded( const wavinfo_t *info ) {
+ float scale;
+ int scaledSampleCount;
+ int sampleMemory;
+ int blockCount;
+ int headerMemory;
+
+ // determine scale to convert from input sampling rate to desired sampling rate
+ scale = (float)info->rate / dma.speed;
+
+ // calc number of samples at playback sampling rate
+ scaledSampleCount = info->samples / scale;
+
+ // calc memory need to store those samples using ADPCM at 4 bits per sample
+ sampleMemory = scaledSampleCount / 2;
+
+ // calc number of sample blocks needed of PAINTBUFFER_SIZE
+ blockCount = scaledSampleCount / PAINTBUFFER_SIZE;
+ if( scaledSampleCount % PAINTBUFFER_SIZE ) {
+ blockCount++;
+ }
+
+ // calc memory needed to store the block headers
+ headerMemory = blockCount * sizeof(adpcm_state_t);
+
+ return sampleMemory + headerMemory;
+}
+
+
+/*
+====================
+S_AdpcmGetSamples
+====================
+*/
+void S_AdpcmGetSamples(sndBuffer *chunk, short *to) {
+ adpcm_state_t state;
+ byte *out;
+
+ // get the starting state from the block header
+ state.index = chunk->adpcm.index;
+ state.sample = chunk->adpcm.sample;
+
+ out = (byte *)chunk->sndChunk;
+ // get samples
+ S_AdpcmDecode( out, to, SND_CHUNK_SIZE_BYTE*2, &state );
+}
+
+
+/*
+====================
+S_AdpcmEncodeSound
+====================
+*/
+void S_AdpcmEncodeSound( sfx_t *sfx, short *samples ) {
+ adpcm_state_t state;
+ int inOffset;
+ int count;
+ int n;
+ sndBuffer *newchunk, *chunk;
+ byte *out;
+
+ inOffset = 0;
+ count = sfx->soundLength;
+ state.index = 0;
+ state.sample = samples[0];
+
+ chunk = NULL;
+ while( count ) {
+ n = count;
+ if( n > SND_CHUNK_SIZE_BYTE*2 ) {
+ n = SND_CHUNK_SIZE_BYTE*2;
+ }
+
+ newchunk = SND_malloc();
+ if (sfx->soundData == NULL) {
+ sfx->soundData = newchunk;
+ } else {
+ chunk->next = newchunk;
+ }
+ chunk = newchunk;
+
+ // output the header
+ chunk->adpcm.index = state.index;
+ chunk->adpcm.sample = state.sample;
+
+ out = (byte *)chunk->sndChunk;
+
+ // encode the samples
+ S_AdpcmEncode( samples + inOffset, out, n, &state );
+
+ inOffset += n;
+ count -= n;
+ }
+}
diff --git a/code/client/snd_dma.c b/code/client/snd_dma.c
new file mode 100755
index 0000000..6ecff18
--- /dev/null
+++ b/code/client/snd_dma.c
@@ -0,0 +1,1636 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: snd_dma.c
+ *
+ * desc: main control for any streaming sound output device
+ *
+ * $Archive: /MissionPack/code/client/snd_dma.c $
+ *
+ *****************************************************************************/
+
+#include "snd_local.h"
+#include "client.h"
+
+void S_Play_f(void);
+void S_SoundList_f(void);
+void S_Music_f(void);
+
+void S_Update_();
+void S_StopAllSounds(void);
+void S_UpdateBackgroundTrack( void );
+
+static fileHandle_t s_backgroundFile;
+static wavinfo_t s_backgroundInfo;
+//int s_nextWavChunk;
+static int s_backgroundSamples;
+static char s_backgroundLoop[MAX_QPATH];
+//static char s_backgroundMusic[MAX_QPATH]; //TTimo: unused
+
+
+// =======================================================================
+// Internal sound data & structures
+// =======================================================================
+
+// only begin attenuating sound volumes when outside the FULLVOLUME range
+#define SOUND_FULLVOLUME 80
+
+#define SOUND_ATTENUATE 0.0008f
+
+channel_t s_channels[MAX_CHANNELS];
+channel_t loop_channels[MAX_CHANNELS];
+int numLoopChannels;
+
+static int s_soundStarted;
+static qboolean s_soundMuted;
+
+dma_t dma;
+
+static int listener_number;
+static vec3_t listener_origin;
+static vec3_t listener_axis[3];
+
+int s_soundtime; // sample PAIRS
+int s_paintedtime; // sample PAIRS
+
+// MAX_SFX may be larger than MAX_SOUNDS because
+// of custom player sounds
+#define MAX_SFX 4096
+sfx_t s_knownSfx[MAX_SFX];
+int s_numSfx = 0;
+
+#define LOOP_HASH 128
+static sfx_t *sfxHash[LOOP_HASH];
+
+cvar_t *s_volume;
+cvar_t *s_testsound;
+cvar_t *s_khz;
+cvar_t *s_show;
+cvar_t *s_mixahead;
+cvar_t *s_mixPreStep;
+cvar_t *s_musicVolume;
+cvar_t *s_separation;
+cvar_t *s_doppler;
+
+static loopSound_t loopSounds[MAX_GENTITIES];
+static channel_t *freelist = NULL;
+
+int s_rawend;
+portable_samplepair_t s_rawsamples[MAX_RAW_SAMPLES];
+
+
+// ====================================================================
+// User-setable variables
+// ====================================================================
+
+
+void S_SoundInfo_f(void) {
+ Com_Printf("----- Sound Info -----\n" );
+ if (!s_soundStarted) {
+ Com_Printf ("sound system not started\n");
+ } else {
+ if ( s_soundMuted ) {
+ Com_Printf ("sound system is muted\n");
+ }
+
+ Com_Printf("%5d stereo\n", dma.channels - 1);
+ Com_Printf("%5d samples\n", dma.samples);
+ Com_Printf("%5d samplebits\n", dma.samplebits);
+ Com_Printf("%5d submission_chunk\n", dma.submission_chunk);
+ Com_Printf("%5d speed\n", dma.speed);
+ Com_Printf("0x%x dma buffer\n", dma.buffer);
+ if ( s_backgroundFile ) {
+ Com_Printf("Background file: %s\n", s_backgroundLoop );
+ } else {
+ Com_Printf("No background file.\n" );
+ }
+
+ }
+ Com_Printf("----------------------\n" );
+}
+
+
+
+/*
+================
+S_Init
+================
+*/
+void S_Init( void ) {
+ cvar_t *cv;
+ qboolean r;
+
+ Com_Printf("\n------- sound initialization -------\n");
+
+ s_volume = Cvar_Get ("s_volume", "0.8", CVAR_ARCHIVE);
+ s_musicVolume = Cvar_Get ("s_musicvolume", "0.25", CVAR_ARCHIVE);
+ s_separation = Cvar_Get ("s_separation", "0.5", CVAR_ARCHIVE);
+ s_doppler = Cvar_Get ("s_doppler", "1", CVAR_ARCHIVE);
+ s_khz = Cvar_Get ("s_khz", "22", CVAR_ARCHIVE);
+ s_mixahead = Cvar_Get ("s_mixahead", "0.2", CVAR_ARCHIVE);
+
+ s_mixPreStep = Cvar_Get ("s_mixPreStep", "0.05", CVAR_ARCHIVE);
+ s_show = Cvar_Get ("s_show", "0", CVAR_CHEAT);
+ s_testsound = Cvar_Get ("s_testsound", "0", CVAR_CHEAT);
+
+ cv = Cvar_Get ("s_initsound", "1", 0);
+ if ( !cv->integer ) {
+ Com_Printf ("not initializing.\n");
+ Com_Printf("------------------------------------\n");
+ return;
+ }
+
+ Cmd_AddCommand("play", S_Play_f);
+ Cmd_AddCommand("music", S_Music_f);
+ Cmd_AddCommand("s_list", S_SoundList_f);
+ Cmd_AddCommand("s_info", S_SoundInfo_f);
+ Cmd_AddCommand("s_stop", S_StopAllSounds);
+
+ r = SNDDMA_Init();
+ Com_Printf("------------------------------------\n");
+
+ if ( r ) {
+ s_soundStarted = 1;
+ s_soundMuted = 1;
+// s_numSfx = 0;
+
+ Com_Memset(sfxHash, 0, sizeof(sfx_t *)*LOOP_HASH);
+
+ s_soundtime = 0;
+ s_paintedtime = 0;
+
+ S_StopAllSounds ();
+
+ S_SoundInfo_f();
+ }
+
+}
+
+
+void S_ChannelFree(channel_t *v) {
+ v->thesfx = NULL;
+ *(channel_t **)v = freelist;
+ freelist = (channel_t*)v;
+}
+
+channel_t* S_ChannelMalloc() {
+ channel_t *v;
+ if (freelist == NULL) {
+ return NULL;
+ }
+ v = freelist;
+ freelist = *(channel_t **)freelist;
+ v->allocTime = Com_Milliseconds();
+ return v;
+}
+
+void S_ChannelSetup() {
+ channel_t *p, *q;
+
+ // clear all the sounds so they don't
+ Com_Memset( s_channels, 0, sizeof( s_channels ) );
+
+ p = s_channels;;
+ q = p + MAX_CHANNELS;
+ while (--q > p) {
+ *(channel_t **)q = q-1;
+ }
+
+ *(channel_t **)q = NULL;
+ freelist = p + MAX_CHANNELS - 1;
+ Com_DPrintf("Channel memory manager started\n");
+}
+
+// =======================================================================
+// Shutdown sound engine
+// =======================================================================
+
+void S_Shutdown( void ) {
+ if ( !s_soundStarted ) {
+ return;
+ }
+
+ SNDDMA_Shutdown();
+
+ s_soundStarted = 0;
+
+ Cmd_RemoveCommand("play");
+ Cmd_RemoveCommand("music");
+ Cmd_RemoveCommand("stopsound");
+ Cmd_RemoveCommand("soundlist");
+ Cmd_RemoveCommand("soundinfo");
+}
+
+
+// =======================================================================
+// Load a sound
+// =======================================================================
+
+/*
+================
+return a hash value for the sfx name
+================
+*/
+static long S_HashSFXName(const char *name) {
+ int i;
+ long hash;
+ char letter;
+
+ hash = 0;
+ i = 0;
+ while (name[i] != '\0') {
+ letter = tolower(name[i]);
+ if (letter =='.') break; // don't include extension
+ if (letter =='\\') letter = '/'; // damn path names
+ hash+=(long)(letter)*(i+119);
+ i++;
+ }
+ hash &= (LOOP_HASH-1);
+ return hash;
+}
+
+/*
+==================
+S_FindName
+
+Will allocate a new sfx if it isn't found
+==================
+*/
+static sfx_t *S_FindName( const char *name ) {
+ int i;
+ int hash;
+
+ sfx_t *sfx;
+
+ if (!name) {
+ Com_Error (ERR_FATAL, "S_FindName: NULL\n");
+ }
+ if (!name[0]) {
+ Com_Error (ERR_FATAL, "S_FindName: empty name\n");
+ }
+
+ if (strlen(name) >= MAX_QPATH) {
+ Com_Error (ERR_FATAL, "Sound name too long: %s", name);
+ }
+
+ hash = S_HashSFXName(name);
+
+ sfx = sfxHash[hash];
+ // see if already loaded
+ while (sfx) {
+ if (!Q_stricmp(sfx->soundName, name) ) {
+ return sfx;
+ }
+ sfx = sfx->next;
+ }
+
+ // find a free sfx
+ for (i=0 ; i < s_numSfx ; i++) {
+ if (!s_knownSfx[i].soundName[0]) {
+ break;
+ }
+ }
+
+ if (i == s_numSfx) {
+ if (s_numSfx == MAX_SFX) {
+ Com_Error (ERR_FATAL, "S_FindName: out of sfx_t");
+ }
+ s_numSfx++;
+ }
+
+ sfx = &s_knownSfx[i];
+ Com_Memset (sfx, 0, sizeof(*sfx));
+ strcpy (sfx->soundName, name);
+
+ sfx->next = sfxHash[hash];
+ sfxHash[hash] = sfx;
+
+ return sfx;
+}
+
+/*
+=================
+S_DefaultSound
+=================
+*/
+void S_DefaultSound( sfx_t *sfx ) {
+
+ int i;
+
+ sfx->soundLength = 512;
+ sfx->soundData = SND_malloc();
+ sfx->soundData->next = NULL;
+
+
+ for ( i = 0 ; i < sfx->soundLength ; i++ ) {
+ sfx->soundData->sndChunk[i] = i;
+ }
+}
+
+/*
+===================
+S_DisableSounds
+
+Disables sounds until the next S_BeginRegistration.
+This is called when the hunk is cleared and the sounds
+are no longer valid.
+===================
+*/
+void S_DisableSounds( void ) {
+ S_StopAllSounds();
+ s_soundMuted = qtrue;
+}
+
+/*
+=====================
+S_BeginRegistration
+
+=====================
+*/
+void S_BeginRegistration( void ) {
+ s_soundMuted = qfalse; // we can play again
+
+ if (s_numSfx == 0) {
+ SND_setup();
+
+ s_numSfx = 0;
+ Com_Memset( s_knownSfx, 0, sizeof( s_knownSfx ) );
+ Com_Memset(sfxHash, 0, sizeof(sfx_t *)*LOOP_HASH);
+
+ S_RegisterSound("sound/feedback/hit.wav", qfalse); // changed to a sound in baseq3
+ }
+}
+
+
+/*
+==================
+S_RegisterSound
+
+Creates a default buzz sound if the file can't be loaded
+==================
+*/
+sfxHandle_t S_RegisterSound( const char *name, qboolean compressed ) {
+ sfx_t *sfx;
+
+ compressed = qfalse;
+ if (!s_soundStarted) {
+ return 0;
+ }
+
+ if ( strlen( name ) >= MAX_QPATH ) {
+ Com_Printf( "Sound name exceeds MAX_QPATH\n" );
+ return 0;
+ }
+
+ sfx = S_FindName( name );
+ if ( sfx->soundData ) {
+ if ( sfx->defaultSound ) {
+ Com_Printf( S_COLOR_YELLOW "WARNING: could not find %s - using default\n", sfx->soundName );
+ return 0;
+ }
+ return sfx - s_knownSfx;
+ }
+
+ sfx->inMemory = qfalse;
+ sfx->soundCompressed = compressed;
+
+ S_memoryLoad(sfx);
+
+ if ( sfx->defaultSound ) {
+ Com_Printf( S_COLOR_YELLOW "WARNING: could not find %s - using default\n", sfx->soundName );
+ return 0;
+ }
+
+ return sfx - s_knownSfx;
+}
+
+void S_memoryLoad(sfx_t *sfx) {
+ // load the sound file
+ if ( !S_LoadSound ( sfx ) ) {
+// Com_Printf( S_COLOR_YELLOW "WARNING: couldn't load sound: %s\n", sfx->soundName );
+ sfx->defaultSound = qtrue;
+ }
+ sfx->inMemory = qtrue;
+}
+
+//=============================================================================
+
+/*
+=================
+S_SpatializeOrigin
+
+Used for spatializing s_channels
+=================
+*/
+void S_SpatializeOrigin (vec3_t origin, int master_vol, int *left_vol, int *right_vol)
+{
+ vec_t dot;
+ vec_t dist;
+ vec_t lscale, rscale, scale;
+ vec3_t source_vec;
+ vec3_t vec;
+
+ const float dist_mult = SOUND_ATTENUATE;
+
+ // calculate stereo seperation and distance attenuation
+ VectorSubtract(origin, listener_origin, source_vec);
+
+ dist = VectorNormalize(source_vec);
+ dist -= SOUND_FULLVOLUME;
+ if (dist < 0)
+ dist = 0; // close enough to be at full volume
+ dist *= dist_mult; // different attenuation levels
+
+ VectorRotate( source_vec, listener_axis, vec );
+
+ dot = -vec[1];
+
+ if (dma.channels == 1)
+ { // no attenuation = no spatialization
+ rscale = 1.0;
+ lscale = 1.0;
+ }
+ else
+ {
+ rscale = 0.5 * (1.0 + dot);
+ lscale = 0.5 * (1.0 - dot);
+ //rscale = s_separation->value + ( 1.0 - s_separation->value ) * dot;
+ //lscale = s_separation->value - ( 1.0 - s_separation->value ) * dot;
+ if ( rscale < 0 ) {
+ rscale = 0;
+ }
+ if ( lscale < 0 ) {
+ lscale = 0;
+ }
+ }
+
+ // add in distance effect
+ scale = (1.0 - dist) * rscale;
+ *right_vol = (master_vol * scale);
+ if (*right_vol < 0)
+ *right_vol = 0;
+
+ scale = (1.0 - dist) * lscale;
+ *left_vol = (master_vol * scale);
+ if (*left_vol < 0)
+ *left_vol = 0;
+}
+
+// =======================================================================
+// Start a sound effect
+// =======================================================================
+
+/*
+====================
+S_StartSound
+
+Validates the parms and ques the sound up
+if pos is NULL, the sound will be dynamically sourced from the entity
+Entchannel 0 will never override a playing sound
+====================
+*/
+void S_StartSound(vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfxHandle ) {
+ channel_t *ch;
+ sfx_t *sfx;
+ int i, oldest, chosen, time;
+ int inplay, allowed;
+
+ if ( !s_soundStarted || s_soundMuted ) {
+ return;
+ }
+
+ if ( !origin && ( entityNum < 0 || entityNum > MAX_GENTITIES ) ) {
+ Com_Error( ERR_DROP, "S_StartSound: bad entitynum %i", entityNum );
+ }
+
+ if ( sfxHandle < 0 || sfxHandle >= s_numSfx ) {
+ Com_Printf( S_COLOR_YELLOW, "S_StartSound: handle %i out of range\n", sfxHandle );
+ return;
+ }
+
+ sfx = &s_knownSfx[ sfxHandle ];
+
+ if (sfx->inMemory == qfalse) {
+ S_memoryLoad(sfx);
+ }
+
+ if ( s_show->integer == 1 ) {
+ Com_Printf( "%i : %s\n", s_paintedtime, sfx->soundName );
+ }
+
+ time = Com_Milliseconds();
+
+// Com_Printf("playing %s\n", sfx->soundName);
+ // pick a channel to play on
+
+ allowed = 4;
+ if (entityNum == listener_number) {
+ allowed = 8;
+ }
+
+ ch = s_channels;
+ inplay = 0;
+ for ( i = 0; i < MAX_CHANNELS ; i++, ch++ ) {
+ if (ch[i].entnum == entityNum && ch[i].thesfx == sfx) {
+ if (time - ch[i].allocTime < 50) {
+// if (Cvar_VariableValue( "cg_showmiss" )) {
+// Com_Printf("double sound start\n");
+// }
+ return;
+ }
+ inplay++;
+ }
+ }
+
+ if (inplay>allowed) {
+ return;
+ }
+
+ sfx->lastTimeUsed = time;
+
+ ch = S_ChannelMalloc(); // entityNum, entchannel);
+ if (!ch) {
+ ch = s_channels;
+
+ oldest = sfx->lastTimeUsed;
+ chosen = -1;
+ for ( i = 0 ; i < MAX_CHANNELS ; i++, ch++ ) {
+ if (ch->entnum != listener_number && ch->entnum == entityNum && ch->allocTime<oldest && ch->entchannel != CHAN_ANNOUNCER) {
+ oldest = ch->allocTime;
+ chosen = i;
+ }
+ }
+ if (chosen == -1) {
+ ch = s_channels;
+ for ( i = 0 ; i < MAX_CHANNELS ; i++, ch++ ) {
+ if (ch->entnum != listener_number && ch->allocTime<oldest && ch->entchannel != CHAN_ANNOUNCER) {
+ oldest = ch->allocTime;
+ chosen = i;
+ }
+ }
+ if (chosen == -1) {
+ if (ch->entnum == listener_number) {
+ for ( i = 0 ; i < MAX_CHANNELS ; i++, ch++ ) {
+ if (ch->allocTime<oldest) {
+ oldest = ch->allocTime;
+ chosen = i;
+ }
+ }
+ }
+ if (chosen == -1) {
+ Com_Printf("dropping sound\n");
+ return;
+ }
+ }
+ }
+ ch = &s_channels[chosen];
+ ch->allocTime = sfx->lastTimeUsed;
+ }
+
+ if (origin) {
+ VectorCopy (origin, ch->origin);
+ ch->fixed_origin = qtrue;
+ } else {
+ ch->fixed_origin = qfalse;
+ }
+
+ ch->master_vol = 127;
+ ch->entnum = entityNum;
+ ch->thesfx = sfx;
+ ch->startSample = START_SAMPLE_IMMEDIATE;
+ ch->entchannel = entchannel;
+ ch->leftvol = ch->master_vol; // these will get calced at next spatialize
+ ch->rightvol = ch->master_vol; // unless the game isn't running
+ ch->doppler = qfalse;
+}
+
+
+/*
+==================
+S_StartLocalSound
+==================
+*/
+void S_StartLocalSound( sfxHandle_t sfxHandle, int channelNum ) {
+ if ( !s_soundStarted || s_soundMuted ) {
+ return;
+ }
+
+ if ( sfxHandle < 0 || sfxHandle >= s_numSfx ) {
+ Com_Printf( S_COLOR_YELLOW, "S_StartLocalSound: handle %i out of range\n", sfxHandle );
+ return;
+ }
+
+ S_StartSound (NULL, listener_number, channelNum, sfxHandle );
+}
+
+
+/*
+==================
+S_ClearSoundBuffer
+
+If we are about to perform file access, clear the buffer
+so sound doesn't stutter.
+==================
+*/
+void S_ClearSoundBuffer( void ) {
+ int clear;
+
+ if (!s_soundStarted)
+ return;
+
+ // stop looping sounds
+ Com_Memset(loopSounds, 0, MAX_GENTITIES*sizeof(loopSound_t));
+ Com_Memset(loop_channels, 0, MAX_CHANNELS*sizeof(channel_t));
+ numLoopChannels = 0;
+
+ S_ChannelSetup();
+
+ s_rawend = 0;
+
+ if (dma.samplebits == 8)
+ clear = 0x80;
+ else
+ clear = 0;
+
+ SNDDMA_BeginPainting ();
+ if (dma.buffer)
+ // TTimo: due to a particular bug workaround in linux sound code,
+ // have to optionally use a custom C implementation of Com_Memset
+ // not affecting win32, we have #define Snd_Memset Com_Memset
+ // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=371
+ Snd_Memset(dma.buffer, clear, dma.samples * dma.samplebits/8);
+ SNDDMA_Submit ();
+}
+
+/*
+==================
+S_StopAllSounds
+==================
+*/
+void S_StopAllSounds(void) {
+ if ( !s_soundStarted ) {
+ return;
+ }
+
+ // stop the background music
+ S_StopBackgroundTrack();
+
+ S_ClearSoundBuffer ();
+}
+
+/*
+==============================================================
+
+continuous looping sounds are added each frame
+
+==============================================================
+*/
+
+void S_StopLoopingSound(int entityNum) {
+ loopSounds[entityNum].active = qfalse;
+// loopSounds[entityNum].sfx = 0;
+ loopSounds[entityNum].kill = qfalse;
+}
+
+/*
+==================
+S_ClearLoopingSounds
+
+==================
+*/
+void S_ClearLoopingSounds( qboolean killall ) {
+ int i;
+ for ( i = 0 ; i < MAX_GENTITIES ; i++) {
+ if (killall || loopSounds[i].kill == qtrue || (loopSounds[i].sfx && loopSounds[i].sfx->soundLength == 0)) {
+ loopSounds[i].kill = qfalse;
+ S_StopLoopingSound(i);
+ }
+ }
+ numLoopChannels = 0;
+}
+
+/*
+==================
+S_AddLoopingSound
+
+Called during entity generation for a frame
+Include velocity in case I get around to doing doppler...
+==================
+*/
+void S_AddLoopingSound( int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfxHandle ) {
+ sfx_t *sfx;
+
+ if ( !s_soundStarted || s_soundMuted ) {
+ return;
+ }
+
+ if ( sfxHandle < 0 || sfxHandle >= s_numSfx ) {
+ Com_Printf( S_COLOR_YELLOW, "S_AddLoopingSound: handle %i out of range\n", sfxHandle );
+ return;
+ }
+
+ sfx = &s_knownSfx[ sfxHandle ];
+
+ if (sfx->inMemory == qfalse) {
+ S_memoryLoad(sfx);
+ }
+
+ if ( !sfx->soundLength ) {
+ Com_Error( ERR_DROP, "%s has length 0", sfx->soundName );
+ }
+
+ VectorCopy( origin, loopSounds[entityNum].origin );
+ VectorCopy( velocity, loopSounds[entityNum].velocity );
+ loopSounds[entityNum].active = qtrue;
+ loopSounds[entityNum].kill = qtrue;
+ loopSounds[entityNum].doppler = qfalse;
+ loopSounds[entityNum].oldDopplerScale = 1.0;
+ loopSounds[entityNum].dopplerScale = 1.0;
+ loopSounds[entityNum].sfx = sfx;
+
+ if (s_doppler->integer && VectorLengthSquared(velocity)>0.0) {
+ vec3_t out;
+ float lena, lenb;
+
+ loopSounds[entityNum].doppler = qtrue;
+ lena = DistanceSquared(loopSounds[listener_number].origin, loopSounds[entityNum].origin);
+ VectorAdd(loopSounds[entityNum].origin, loopSounds[entityNum].velocity, out);
+ lenb = DistanceSquared(loopSounds[listener_number].origin, out);
+ if ((loopSounds[entityNum].framenum+1) != cls.framecount) {
+ loopSounds[entityNum].oldDopplerScale = 1.0;
+ } else {
+ loopSounds[entityNum].oldDopplerScale = loopSounds[entityNum].dopplerScale;
+ }
+ loopSounds[entityNum].dopplerScale = lenb/(lena*100);
+ if (loopSounds[entityNum].dopplerScale<=1.0) {
+ loopSounds[entityNum].doppler = qfalse; // don't bother doing the math
+ }
+ }
+
+ loopSounds[entityNum].framenum = cls.framecount;
+}
+
+/*
+==================
+S_AddLoopingSound
+
+Called during entity generation for a frame
+Include velocity in case I get around to doing doppler...
+==================
+*/
+void S_AddRealLoopingSound( int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfxHandle ) {
+ sfx_t *sfx;
+
+ if ( !s_soundStarted || s_soundMuted ) {
+ return;
+ }
+
+ if ( sfxHandle < 0 || sfxHandle >= s_numSfx ) {
+ Com_Printf( S_COLOR_YELLOW, "S_AddRealLoopingSound: handle %i out of range\n", sfxHandle );
+ return;
+ }
+
+ sfx = &s_knownSfx[ sfxHandle ];
+
+ if (sfx->inMemory == qfalse) {
+ S_memoryLoad(sfx);
+ }
+
+ if ( !sfx->soundLength ) {
+ Com_Error( ERR_DROP, "%s has length 0", sfx->soundName );
+ }
+ VectorCopy( origin, loopSounds[entityNum].origin );
+ VectorCopy( velocity, loopSounds[entityNum].velocity );
+ loopSounds[entityNum].sfx = sfx;
+ loopSounds[entityNum].active = qtrue;
+ loopSounds[entityNum].kill = qfalse;
+ loopSounds[entityNum].doppler = qfalse;
+}
+
+
+
+/*
+==================
+S_AddLoopSounds
+
+Spatialize all of the looping sounds.
+All sounds are on the same cycle, so any duplicates can just
+sum up the channel multipliers.
+==================
+*/
+void S_AddLoopSounds (void) {
+ int i, j, time;
+ int left_total, right_total, left, right;
+ channel_t *ch;
+ loopSound_t *loop, *loop2;
+ static int loopFrame;
+
+
+ numLoopChannels = 0;
+
+ time = Com_Milliseconds();
+
+ loopFrame++;
+ for ( i = 0 ; i < MAX_GENTITIES ; i++) {
+ loop = &loopSounds[i];
+ if ( !loop->active || loop->mergeFrame == loopFrame ) {
+ continue; // already merged into an earlier sound
+ }
+
+ if (loop->kill) {
+ S_SpatializeOrigin( loop->origin, 127, &left_total, &right_total); // 3d
+ } else {
+ S_SpatializeOrigin( loop->origin, 90, &left_total, &right_total); // sphere
+ }
+
+ loop->sfx->lastTimeUsed = time;
+
+ for (j=(i+1); j< MAX_GENTITIES ; j++) {
+ loop2 = &loopSounds[j];
+ if ( !loop2->active || loop2->doppler || loop2->sfx != loop->sfx) {
+ continue;
+ }
+ loop2->mergeFrame = loopFrame;
+
+ if (loop2->kill) {
+ S_SpatializeOrigin( loop2->origin, 127, &left, &right); // 3d
+ } else {
+ S_SpatializeOrigin( loop2->origin, 90, &left, &right); // sphere
+ }
+
+ loop2->sfx->lastTimeUsed = time;
+ left_total += left;
+ right_total += right;
+ }
+ if (left_total == 0 && right_total == 0) {
+ continue; // not audible
+ }
+
+ // allocate a channel
+ ch = &loop_channels[numLoopChannels];
+
+ if (left_total > 255) {
+ left_total = 255;
+ }
+ if (right_total > 255) {
+ right_total = 255;
+ }
+
+ ch->master_vol = 127;
+ ch->leftvol = left_total;
+ ch->rightvol = right_total;
+ ch->thesfx = loop->sfx;
+ ch->doppler = loop->doppler;
+ ch->dopplerScale = loop->dopplerScale;
+ ch->oldDopplerScale = loop->oldDopplerScale;
+ numLoopChannels++;
+ if (numLoopChannels == MAX_CHANNELS) {
+ return;
+ }
+ }
+}
+
+//=============================================================================
+
+/*
+=================
+S_ByteSwapRawSamples
+
+If raw data has been loaded in little endien binary form, this must be done.
+If raw data was calculated, as with ADPCM, this should not be called.
+=================
+*/
+void S_ByteSwapRawSamples( int samples, int width, int s_channels, const byte *data ) {
+ int i;
+
+ if ( width != 2 ) {
+ return;
+ }
+ if ( LittleShort( 256 ) == 256 ) {
+ return;
+ }
+
+ if ( s_channels == 2 ) {
+ samples <<= 1;
+ }
+ for ( i = 0 ; i < samples ; i++ ) {
+ ((short *)data)[i] = LittleShort( ((short *)data)[i] );
+ }
+}
+
+portable_samplepair_t *S_GetRawSamplePointer() {
+ return s_rawsamples;
+}
+
+/*
+============
+S_RawSamples
+
+Music streaming
+============
+*/
+void S_RawSamples( int samples, int rate, int width, int s_channels, const byte *data, float volume ) {
+ int i;
+ int src, dst;
+ float scale;
+ int intVolume;
+
+ if ( !s_soundStarted || s_soundMuted ) {
+ return;
+ }
+
+ intVolume = 256 * volume;
+
+ if ( s_rawend < s_soundtime ) {
+ Com_DPrintf( "S_RawSamples: resetting minimum: %i < %i\n", s_rawend, s_soundtime );
+ s_rawend = s_soundtime;
+ }
+
+ scale = (float)rate / dma.speed;
+
+//Com_Printf ("%i < %i < %i\n", s_soundtime, s_paintedtime, s_rawend);
+ if (s_channels == 2 && width == 2)
+ {
+ if (scale == 1.0)
+ { // optimized case
+ for (i=0 ; i<samples ; i++)
+ {
+ dst = s_rawend&(MAX_RAW_SAMPLES-1);
+ s_rawend++;
+ s_rawsamples[dst].left = ((short *)data)[i*2] * intVolume;
+ s_rawsamples[dst].right = ((short *)data)[i*2+1] * intVolume;
+ }
+ }
+ else
+ {
+ for (i=0 ; ; i++)
+ {
+ src = i*scale;
+ if (src >= samples)
+ break;
+ dst = s_rawend&(MAX_RAW_SAMPLES-1);
+ s_rawend++;
+ s_rawsamples[dst].left = ((short *)data)[src*2] * intVolume;
+ s_rawsamples[dst].right = ((short *)data)[src*2+1] * intVolume;
+ }
+ }
+ }
+ else if (s_channels == 1 && width == 2)
+ {
+ for (i=0 ; ; i++)
+ {
+ src = i*scale;
+ if (src >= samples)
+ break;
+ dst = s_rawend&(MAX_RAW_SAMPLES-1);
+ s_rawend++;
+ s_rawsamples[dst].left = ((short *)data)[src] * intVolume;
+ s_rawsamples[dst].right = ((short *)data)[src] * intVolume;
+ }
+ }
+ else if (s_channels == 2 && width == 1)
+ {
+ intVolume *= 256;
+
+ for (i=0 ; ; i++)
+ {
+ src = i*scale;
+ if (src >= samples)
+ break;
+ dst = s_rawend&(MAX_RAW_SAMPLES-1);
+ s_rawend++;
+ s_rawsamples[dst].left = ((char *)data)[src*2] * intVolume;
+ s_rawsamples[dst].right = ((char *)data)[src*2+1] * intVolume;
+ }
+ }
+ else if (s_channels == 1 && width == 1)
+ {
+ intVolume *= 256;
+
+ for (i=0 ; ; i++)
+ {
+ src = i*scale;
+ if (src >= samples)
+ break;
+ dst = s_rawend&(MAX_RAW_SAMPLES-1);
+ s_rawend++;
+ s_rawsamples[dst].left = (((byte *)data)[src]-128) * intVolume;
+ s_rawsamples[dst].right = (((byte *)data)[src]-128) * intVolume;
+ }
+ }
+
+ if ( s_rawend > s_soundtime + MAX_RAW_SAMPLES ) {
+ Com_DPrintf( "S_RawSamples: overflowed %i > %i\n", s_rawend, s_soundtime );
+ }
+}
+
+//=============================================================================
+
+/*
+=====================
+S_UpdateEntityPosition
+
+let the sound system know where an entity currently is
+======================
+*/
+void S_UpdateEntityPosition( int entityNum, const vec3_t origin ) {
+ if ( entityNum < 0 || entityNum > MAX_GENTITIES ) {
+ Com_Error( ERR_DROP, "S_UpdateEntityPosition: bad entitynum %i", entityNum );
+ }
+ VectorCopy( origin, loopSounds[entityNum].origin );
+}
+
+
+/*
+============
+S_Respatialize
+
+Change the volumes of all the playing sounds for changes in their positions
+============
+*/
+void S_Respatialize( int entityNum, const vec3_t head, vec3_t axis[3], int inwater ) {
+ int i;
+ channel_t *ch;
+ vec3_t origin;
+
+ if ( !s_soundStarted || s_soundMuted ) {
+ return;
+ }
+
+ listener_number = entityNum;
+ VectorCopy(head, listener_origin);
+ VectorCopy(axis[0], listener_axis[0]);
+ VectorCopy(axis[1], listener_axis[1]);
+ VectorCopy(axis[2], listener_axis[2]);
+
+ // update spatialization for dynamic sounds
+ ch = s_channels;
+ for ( i = 0 ; i < MAX_CHANNELS ; i++, ch++ ) {
+ if ( !ch->thesfx ) {
+ continue;
+ }
+ // anything coming from the view entity will always be full volume
+ if (ch->entnum == listener_number) {
+ ch->leftvol = ch->master_vol;
+ ch->rightvol = ch->master_vol;
+ } else {
+ if (ch->fixed_origin) {
+ VectorCopy( ch->origin, origin );
+ } else {
+ VectorCopy( loopSounds[ ch->entnum ].origin, origin );
+ }
+
+ S_SpatializeOrigin (origin, ch->master_vol, &ch->leftvol, &ch->rightvol);
+ }
+ }
+
+ // add loopsounds
+ S_AddLoopSounds ();
+}
+
+
+/*
+========================
+S_ScanChannelStarts
+
+Returns qtrue if any new sounds were started since the last mix
+========================
+*/
+qboolean S_ScanChannelStarts( void ) {
+ channel_t *ch;
+ int i;
+ qboolean newSamples;
+
+ newSamples = qfalse;
+ ch = s_channels;
+
+ for (i=0; i<MAX_CHANNELS ; i++, ch++) {
+ if ( !ch->thesfx ) {
+ continue;
+ }
+ // if this channel was just started this frame,
+ // set the sample count to it begins mixing
+ // into the very first sample
+ if ( ch->startSample == START_SAMPLE_IMMEDIATE ) {
+ ch->startSample = s_paintedtime;
+ newSamples = qtrue;
+ continue;
+ }
+
+ // if it is completely finished by now, clear it
+ if ( ch->startSample + (ch->thesfx->soundLength) <= s_paintedtime ) {
+ S_ChannelFree(ch);
+ }
+ }
+
+ return newSamples;
+}
+
+/*
+============
+S_Update
+
+Called once each time through the main loop
+============
+*/
+void S_Update( void ) {
+ int i;
+ int total;
+ channel_t *ch;
+
+ if ( !s_soundStarted || s_soundMuted ) {
+ Com_DPrintf ("not started or muted\n");
+ return;
+ }
+
+ //
+ // debugging output
+ //
+ if ( s_show->integer == 2 ) {
+ total = 0;
+ ch = s_channels;
+ for (i=0 ; i<MAX_CHANNELS; i++, ch++) {
+ if (ch->thesfx && (ch->leftvol || ch->rightvol) ) {
+ Com_Printf ("%f %f %s\n", ch->leftvol, ch->rightvol, ch->thesfx->soundName);
+ total++;
+ }
+ }
+
+ Com_Printf ("----(%i)---- painted: %i\n", total, s_paintedtime);
+ }
+
+ // add raw data from streamed samples
+ S_UpdateBackgroundTrack();
+
+ // mix some sound
+ S_Update_();
+}
+
+void S_GetSoundtime(void)
+{
+ int samplepos;
+ static int buffers;
+ static int oldsamplepos;
+ int fullsamples;
+
+ fullsamples = dma.samples / dma.channels;
+
+ // it is possible to miscount buffers if it has wrapped twice between
+ // calls to S_Update. Oh well.
+ samplepos = SNDDMA_GetDMAPos();
+ if (samplepos < oldsamplepos)
+ {
+ buffers++; // buffer wrapped
+
+ if (s_paintedtime > 0x40000000)
+ { // time to chop things off to avoid 32 bit limits
+ buffers = 0;
+ s_paintedtime = fullsamples;
+ S_StopAllSounds ();
+ }
+ }
+ oldsamplepos = samplepos;
+
+ s_soundtime = buffers*fullsamples + samplepos/dma.channels;
+
+#if 0
+// check to make sure that we haven't overshot
+ if (s_paintedtime < s_soundtime)
+ {
+ Com_DPrintf ("S_Update_ : overflow\n");
+ s_paintedtime = s_soundtime;
+ }
+#endif
+
+ if ( dma.submission_chunk < 256 ) {
+ s_paintedtime = s_soundtime + s_mixPreStep->value * dma.speed;
+ } else {
+ s_paintedtime = s_soundtime + dma.submission_chunk;
+ }
+}
+
+
+void S_Update_(void) {
+ unsigned endtime;
+ int samps;
+ static float lastTime = 0.0f;
+ float ma, op;
+ float thisTime, sane;
+ static int ot = -1;
+
+ if ( !s_soundStarted || s_soundMuted ) {
+ return;
+ }
+
+ thisTime = Com_Milliseconds();
+
+ // Updates s_soundtime
+ S_GetSoundtime();
+
+ if (s_soundtime == ot) {
+ return;
+ }
+ ot = s_soundtime;
+
+ // clear any sound effects that end before the current time,
+ // and start any new sounds
+ S_ScanChannelStarts();
+
+ sane = thisTime - lastTime;
+ if (sane<11) {
+ sane = 11; // 85hz
+ }
+
+ ma = s_mixahead->value * dma.speed;
+ op = s_mixPreStep->value + sane*dma.speed*0.01;
+
+ if (op < ma) {
+ ma = op;
+ }
+
+ // mix ahead of current position
+ endtime = s_soundtime + ma;
+
+ // mix to an even submission block size
+ endtime = (endtime + dma.submission_chunk-1)
+ & ~(dma.submission_chunk-1);
+
+ // never mix more than the complete buffer
+ samps = dma.samples >> (dma.channels-1);
+ if (endtime - s_soundtime > samps)
+ endtime = s_soundtime + samps;
+
+
+
+ SNDDMA_BeginPainting ();
+
+ S_PaintChannels (endtime);
+
+ SNDDMA_Submit ();
+
+ lastTime = thisTime;
+}
+
+/*
+===============================================================================
+
+console functions
+
+===============================================================================
+*/
+
+void S_Play_f( void ) {
+ int i;
+ sfxHandle_t h;
+ char name[256];
+
+ i = 1;
+ while ( i<Cmd_Argc() ) {
+ if ( !Q_strrchr(Cmd_Argv(i), '.') ) {
+ Com_sprintf( name, sizeof(name), "%s.wav", Cmd_Argv(1) );
+ } else {
+ Q_strncpyz( name, Cmd_Argv(i), sizeof(name) );
+ }
+ h = S_RegisterSound( name, qfalse );
+ if( h ) {
+ S_StartLocalSound( h, CHAN_LOCAL_SOUND );
+ }
+ i++;
+ }
+}
+
+void S_Music_f( void ) {
+ int c;
+
+ c = Cmd_Argc();
+
+ if ( c == 2 ) {
+ S_StartBackgroundTrack( Cmd_Argv(1), Cmd_Argv(1) );
+ s_backgroundLoop[0] = 0;
+ } else if ( c == 3 ) {
+ S_StartBackgroundTrack( Cmd_Argv(1), Cmd_Argv(2) );
+ } else {
+ Com_Printf ("music <musicfile> [loopfile]\n");
+ return;
+ }
+
+}
+
+void S_SoundList_f( void ) {
+ int i;
+ sfx_t *sfx;
+ int size, total;
+ char type[4][16];
+ char mem[2][16];
+
+ strcpy(type[0], "16bit");
+ strcpy(type[1], "adpcm");
+ strcpy(type[2], "daub4");
+ strcpy(type[3], "mulaw");
+ strcpy(mem[0], "paged out");
+ strcpy(mem[1], "resident ");
+ total = 0;
+ for (sfx=s_knownSfx, i=0 ; i<s_numSfx ; i++, sfx++) {
+ size = sfx->soundLength;
+ total += size;
+ Com_Printf("%6i[%s] : %s[%s]\n", size, type[sfx->soundCompressionMethod], sfx->soundName, mem[sfx->inMemory] );
+ }
+ Com_Printf ("Total resident: %i\n", total);
+ S_DisplayFreeMemory();
+}
+
+
+/*
+===============================================================================
+
+background music functions
+
+===============================================================================
+*/
+
+int FGetLittleLong( fileHandle_t f ) {
+ int v;
+
+ FS_Read( &v, sizeof(v), f );
+
+ return LittleLong( v);
+}
+
+int FGetLittleShort( fileHandle_t f ) {
+ short v;
+
+ FS_Read( &v, sizeof(v), f );
+
+ return LittleShort( v);
+}
+
+// returns the length of the data in the chunk, or 0 if not found
+int S_FindWavChunk( fileHandle_t f, char *chunk ) {
+ char name[5];
+ int len;
+ int r;
+
+ name[4] = 0;
+ len = 0;
+ r = FS_Read( name, 4, f );
+ if ( r != 4 ) {
+ return 0;
+ }
+ len = FGetLittleLong( f );
+ if ( len < 0 || len > 0xfffffff ) {
+ len = 0;
+ return 0;
+ }
+ len = (len + 1 ) & ~1; // pad to word boundary
+// s_nextWavChunk += len + 8;
+
+ if ( strcmp( name, chunk ) ) {
+ return 0;
+ }
+
+ return len;
+}
+
+/*
+======================
+S_StopBackgroundTrack
+======================
+*/
+void S_StopBackgroundTrack( void ) {
+ if ( !s_backgroundFile ) {
+ return;
+ }
+ Sys_EndStreamedFile( s_backgroundFile );
+ FS_FCloseFile( s_backgroundFile );
+ s_backgroundFile = 0;
+ s_rawend = 0;
+}
+
+/*
+======================
+S_StartBackgroundTrack
+======================
+*/
+void S_StartBackgroundTrack( const char *intro, const char *loop ){
+ int len;
+ char dump[16];
+ char name[MAX_QPATH];
+
+ if ( !intro ) {
+ intro = "";
+ }
+ if ( !loop || !loop[0] ) {
+ loop = intro;
+ }
+ Com_DPrintf( "S_StartBackgroundTrack( %s, %s )\n", intro, loop );
+
+ Q_strncpyz( name, intro, sizeof( name ) - 4 );
+ COM_DefaultExtension( name, sizeof( name ), ".wav" );
+
+ if ( !intro[0] ) {
+ return;
+ }
+
+ Q_strncpyz( s_backgroundLoop, loop, sizeof( s_backgroundLoop ) );
+
+ // close the background track, but DON'T reset s_rawend
+ // if restarting the same back ground track
+ if ( s_backgroundFile ) {
+ Sys_EndStreamedFile( s_backgroundFile );
+ FS_FCloseFile( s_backgroundFile );
+ s_backgroundFile = 0;
+ }
+
+ //
+ // open up a wav file and get all the info
+ //
+ FS_FOpenFileRead( name, &s_backgroundFile, qtrue );
+ if ( !s_backgroundFile ) {
+ Com_Printf( S_COLOR_YELLOW "WARNING: couldn't open music file %s\n", name );
+ return;
+ }
+
+ // skip the riff wav header
+
+ FS_Read(dump, 12, s_backgroundFile);
+
+ if ( !S_FindWavChunk( s_backgroundFile, "fmt " ) ) {
+ Com_Printf( "No fmt chunk in %s\n", name );
+ FS_FCloseFile( s_backgroundFile );
+ s_backgroundFile = 0;
+ return;
+ }
+
+ // save name for soundinfo
+ s_backgroundInfo.format = FGetLittleShort( s_backgroundFile );
+ s_backgroundInfo.channels = FGetLittleShort( s_backgroundFile );
+ s_backgroundInfo.rate = FGetLittleLong( s_backgroundFile );
+ FGetLittleLong( s_backgroundFile );
+ FGetLittleShort( s_backgroundFile );
+ s_backgroundInfo.width = FGetLittleShort( s_backgroundFile ) / 8;
+
+ if ( s_backgroundInfo.format != WAV_FORMAT_PCM ) {
+ FS_FCloseFile( s_backgroundFile );
+ s_backgroundFile = 0;
+ Com_Printf("Not a microsoft PCM format wav: %s\n", name);
+ return;
+ }
+
+ if ( s_backgroundInfo.channels != 2 || s_backgroundInfo.rate != 22050 ) {
+ Com_Printf(S_COLOR_YELLOW "WARNING: music file %s is not 22k stereo\n", name );
+ }
+
+ if ( ( len = S_FindWavChunk( s_backgroundFile, "data" ) ) == 0 ) {
+ FS_FCloseFile( s_backgroundFile );
+ s_backgroundFile = 0;
+ Com_Printf("No data chunk in %s\n", name);
+ return;
+ }
+
+ s_backgroundInfo.samples = len / (s_backgroundInfo.width * s_backgroundInfo.channels);
+
+ s_backgroundSamples = s_backgroundInfo.samples;
+
+ //
+ // start the background streaming
+ //
+ Sys_BeginStreamedFile( s_backgroundFile, 0x10000 );
+}
+
+/*
+======================
+S_UpdateBackgroundTrack
+======================
+*/
+void S_UpdateBackgroundTrack( void ) {
+ int bufferSamples;
+ int fileSamples;
+ byte raw[30000]; // just enough to fit in a mac stack frame
+ int fileBytes;
+ int r;
+ static float musicVolume = 0.5f;
+
+ if ( !s_backgroundFile ) {
+ return;
+ }
+
+ // graeme see if this is OK
+ musicVolume = (musicVolume + (s_musicVolume->value * 2))/4.0f;
+
+ // don't bother playing anything if musicvolume is 0
+ if ( musicVolume <= 0 ) {
+ return;
+ }
+
+ // see how many samples should be copied into the raw buffer
+ if ( s_rawend < s_soundtime ) {
+ s_rawend = s_soundtime;
+ }
+
+ while ( s_rawend < s_soundtime + MAX_RAW_SAMPLES ) {
+ bufferSamples = MAX_RAW_SAMPLES - (s_rawend - s_soundtime);
+
+ // decide how much data needs to be read from the file
+ fileSamples = bufferSamples * s_backgroundInfo.rate / dma.speed;
+
+ // don't try and read past the end of the file
+ if ( fileSamples > s_backgroundSamples ) {
+ fileSamples = s_backgroundSamples;
+ }
+
+ // our max buffer size
+ fileBytes = fileSamples * (s_backgroundInfo.width * s_backgroundInfo.channels);
+ if ( fileBytes > sizeof(raw) ) {
+ fileBytes = sizeof(raw);
+ fileSamples = fileBytes / (s_backgroundInfo.width * s_backgroundInfo.channels);
+ }
+
+ r = Sys_StreamedRead( raw, 1, fileBytes, s_backgroundFile );
+ if ( r != fileBytes ) {
+ Com_Printf("StreamedRead failure on music track\n");
+ S_StopBackgroundTrack();
+ return;
+ }
+
+ // byte swap if needed
+ S_ByteSwapRawSamples( fileSamples, s_backgroundInfo.width, s_backgroundInfo.channels, raw );
+
+ // add to raw buffer
+ S_RawSamples( fileSamples, s_backgroundInfo.rate,
+ s_backgroundInfo.width, s_backgroundInfo.channels, raw, musicVolume );
+
+ s_backgroundSamples -= fileSamples;
+ if ( !s_backgroundSamples ) {
+ // loop
+ if (s_backgroundLoop[0]) {
+ Sys_EndStreamedFile( s_backgroundFile );
+ FS_FCloseFile( s_backgroundFile );
+ s_backgroundFile = 0;
+ S_StartBackgroundTrack( s_backgroundLoop, s_backgroundLoop );
+ if ( !s_backgroundFile ) {
+ return; // loop failed to restart
+ }
+ } else {
+ s_backgroundFile = 0;
+ return;
+ }
+ }
+ }
+}
+
+
+/*
+======================
+S_FreeOldestSound
+======================
+*/
+
+void S_FreeOldestSound() {
+ int i, oldest, used;
+ sfx_t *sfx;
+ sndBuffer *buffer, *nbuffer;
+
+ oldest = Com_Milliseconds();
+ used = 0;
+
+ for (i=1 ; i < s_numSfx ; i++) {
+ sfx = &s_knownSfx[i];
+ if (sfx->inMemory && sfx->lastTimeUsed<oldest) {
+ used = i;
+ oldest = sfx->lastTimeUsed;
+ }
+ }
+
+ sfx = &s_knownSfx[used];
+
+ Com_DPrintf("S_FreeOldestSound: freeing sound %s\n", sfx->soundName);
+
+ buffer = sfx->soundData;
+ while(buffer != NULL) {
+ nbuffer = buffer->next;
+ SND_free(buffer);
+ buffer = nbuffer;
+ }
+ sfx->inMemory = qfalse;
+ sfx->soundData = NULL;
+}
diff --git a/code/client/snd_local.h b/code/client/snd_local.h
new file mode 100755
index 0000000..5b0c97a
--- /dev/null
+++ b/code/client/snd_local.h
@@ -0,0 +1,204 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// snd_local.h -- private sound definations
+
+
+#include "../game/q_shared.h"
+#include "../qcommon/qcommon.h"
+#include "snd_public.h"
+
+#define PAINTBUFFER_SIZE 4096 // this is in samples
+
+#define SND_CHUNK_SIZE 1024 // samples
+#define SND_CHUNK_SIZE_FLOAT (SND_CHUNK_SIZE/2) // floats
+#define SND_CHUNK_SIZE_BYTE (SND_CHUNK_SIZE*2) // floats
+
+typedef struct {
+ int left; // the final values will be clamped to +/- 0x00ffff00 and shifted down
+ int right;
+} portable_samplepair_t;
+
+typedef struct adpcm_state {
+ short sample; /* Previous output value */
+ char index; /* Index into stepsize table */
+} adpcm_state_t;
+
+typedef struct sndBuffer_s {
+ short sndChunk[SND_CHUNK_SIZE];
+ struct sndBuffer_s *next;
+ int size;
+ adpcm_state_t adpcm;
+} sndBuffer;
+
+typedef struct sfx_s {
+ sndBuffer *soundData;
+ qboolean defaultSound; // couldn't be loaded, so use buzz
+ qboolean inMemory; // not in Memory
+ qboolean soundCompressed; // not in Memory
+ int soundCompressionMethod;
+ int soundLength;
+ char soundName[MAX_QPATH];
+ int lastTimeUsed;
+ struct sfx_s *next;
+} sfx_t;
+
+typedef struct {
+ int channels;
+ int samples; // mono samples in buffer
+ int submission_chunk; // don't mix less than this #
+ int samplebits;
+ int speed;
+ byte *buffer;
+} dma_t;
+
+#define START_SAMPLE_IMMEDIATE 0x7fffffff
+
+typedef struct loopSound_s {
+ vec3_t origin;
+ vec3_t velocity;
+ sfx_t *sfx;
+ int mergeFrame;
+ qboolean active;
+ qboolean kill;
+ qboolean doppler;
+ float dopplerScale;
+ float oldDopplerScale;
+ int framenum;
+} loopSound_t;
+
+typedef struct
+{
+ int allocTime;
+ int startSample; // START_SAMPLE_IMMEDIATE = set immediately on next mix
+ int entnum; // to allow overriding a specific sound
+ int entchannel; // to allow overriding a specific sound
+ int leftvol; // 0-255 volume after spatialization
+ int rightvol; // 0-255 volume after spatialization
+ int master_vol; // 0-255 volume before spatialization
+ float dopplerScale;
+ float oldDopplerScale;
+ vec3_t origin; // only use if fixed_origin is set
+ qboolean fixed_origin; // use origin instead of fetching entnum's origin
+ sfx_t *thesfx; // sfx structure
+ qboolean doppler;
+} channel_t;
+
+
+#define WAV_FORMAT_PCM 1
+
+
+typedef struct {
+ int format;
+ int rate;
+ int width;
+ int channels;
+ int samples;
+ int dataofs; // chunk starts this many bytes from file start
+} wavinfo_t;
+
+
+/*
+====================================================================
+
+ SYSTEM SPECIFIC FUNCTIONS
+
+====================================================================
+*/
+
+// initializes cycling through a DMA buffer and returns information on it
+qboolean SNDDMA_Init(void);
+
+// gets the current DMA position
+int SNDDMA_GetDMAPos(void);
+
+// shutdown the DMA xfer.
+void SNDDMA_Shutdown(void);
+
+void SNDDMA_BeginPainting (void);
+
+void SNDDMA_Submit(void);
+
+//====================================================================
+
+#define MAX_CHANNELS 96
+
+extern channel_t s_channels[MAX_CHANNELS];
+extern channel_t loop_channels[MAX_CHANNELS];
+extern int numLoopChannels;
+
+extern int s_paintedtime;
+extern int s_rawend;
+extern vec3_t listener_forward;
+extern vec3_t listener_right;
+extern vec3_t listener_up;
+extern dma_t dma;
+
+#define MAX_RAW_SAMPLES 16384
+extern portable_samplepair_t s_rawsamples[MAX_RAW_SAMPLES];
+
+extern cvar_t *s_volume;
+extern cvar_t *s_nosound;
+extern cvar_t *s_khz;
+extern cvar_t *s_show;
+extern cvar_t *s_mixahead;
+
+extern cvar_t *s_testsound;
+extern cvar_t *s_separation;
+
+qboolean S_LoadSound( sfx_t *sfx );
+
+void SND_free(sndBuffer *v);
+sndBuffer* SND_malloc();
+void SND_setup();
+
+void S_PaintChannels(int endtime);
+
+void S_memoryLoad(sfx_t *sfx);
+portable_samplepair_t *S_GetRawSamplePointer();
+
+// spatializes a channel
+void S_Spatialize(channel_t *ch);
+
+// adpcm functions
+int S_AdpcmMemoryNeeded( const wavinfo_t *info );
+void S_AdpcmEncodeSound( sfx_t *sfx, short *samples );
+void S_AdpcmGetSamples(sndBuffer *chunk, short *to);
+
+// wavelet function
+
+#define SENTINEL_MULAW_ZERO_RUN 127
+#define SENTINEL_MULAW_FOUR_BIT_RUN 126
+
+void S_FreeOldestSound();
+
+#define NXStream byte
+
+void encodeWavelet(sfx_t *sfx, short *packets);
+void decodeWavelet( sndBuffer *stream, short *packets);
+
+void encodeMuLaw( sfx_t *sfx, short *packets);
+extern short mulawToShort[256];
+
+extern short *sfxScratchBuffer;
+extern sfx_t *sfxScratchPointer;
+extern int sfxScratchIndex;
+
diff --git a/code/client/snd_mem.c b/code/client/snd_mem.c
new file mode 100755
index 0000000..0e400d5
--- /dev/null
+++ b/code/client/snd_mem.c
@@ -0,0 +1,404 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*****************************************************************************
+ * name: snd_mem.c
+ *
+ * desc: sound caching
+ *
+ * $Archive: /MissionPack/code/client/snd_mem.c $
+ *
+ *****************************************************************************/
+
+#include "snd_local.h"
+
+#define DEF_COMSOUNDMEGS "8"
+
+/*
+===============================================================================
+
+memory management
+
+===============================================================================
+*/
+
+static sndBuffer *buffer = NULL;
+static sndBuffer *freelist = NULL;
+static int inUse = 0;
+static int totalInUse = 0;
+
+short *sfxScratchBuffer = NULL;
+sfx_t *sfxScratchPointer = NULL;
+int sfxScratchIndex = 0;
+
+void SND_free(sndBuffer *v) {
+ *(sndBuffer **)v = freelist;
+ freelist = (sndBuffer*)v;
+ inUse += sizeof(sndBuffer);
+}
+
+sndBuffer* SND_malloc() {
+ sndBuffer *v;
+redo:
+ if (freelist == NULL) {
+ S_FreeOldestSound();
+ goto redo;
+ }
+
+ inUse -= sizeof(sndBuffer);
+ totalInUse += sizeof(sndBuffer);
+
+ v = freelist;
+ freelist = *(sndBuffer **)freelist;
+ v->next = NULL;
+ return v;
+}
+
+void SND_setup() {
+ sndBuffer *p, *q;
+ cvar_t *cv;
+ int scs;
+
+ cv = Cvar_Get( "com_soundMegs", DEF_COMSOUNDMEGS, CVAR_LATCH | CVAR_ARCHIVE );
+
+ scs = (cv->integer*1536);
+
+ buffer = malloc(scs*sizeof(sndBuffer) );
+ // allocate the stack based hunk allocator
+ sfxScratchBuffer = malloc(SND_CHUNK_SIZE * sizeof(short) * 4); //Hunk_Alloc(SND_CHUNK_SIZE * sizeof(short) * 4);
+ sfxScratchPointer = NULL;
+
+ inUse = scs*sizeof(sndBuffer);
+ p = buffer;;
+ q = p + scs;
+ while (--q > p)
+ *(sndBuffer **)q = q-1;
+
+ *(sndBuffer **)q = NULL;
+ freelist = p + scs - 1;
+
+ Com_Printf("Sound memory manager started\n");
+}
+
+/*
+===============================================================================
+
+WAV loading
+
+===============================================================================
+*/
+
+static byte *data_p;
+static byte *iff_end;
+static byte *last_chunk;
+static byte *iff_data;
+static int iff_chunk_len;
+
+static short GetLittleShort(void)
+{
+ short val = 0;
+ val = *data_p;
+ val = val + (*(data_p+1)<<8);
+ data_p += 2;
+ return val;
+}
+
+static int GetLittleLong(void)
+{
+ int val = 0;
+ val = *data_p;
+ val = val + (*(data_p+1)<<8);
+ val = val + (*(data_p+2)<<16);
+ val = val + (*(data_p+3)<<24);
+ data_p += 4;
+ return val;
+}
+
+static void FindNextChunk(char *name)
+{
+ while (1)
+ {
+ data_p=last_chunk;
+
+ if (data_p >= iff_end)
+ { // didn't find the chunk
+ data_p = NULL;
+ return;
+ }
+
+ data_p += 4;
+ iff_chunk_len = GetLittleLong();
+ if (iff_chunk_len < 0)
+ {
+ data_p = NULL;
+ return;
+ }
+ data_p -= 8;
+ last_chunk = data_p + 8 + ( (iff_chunk_len + 1) & ~1 );
+ if (!strncmp((char *)data_p, name, 4))
+ return;
+ }
+}
+
+static void FindChunk(char *name)
+{
+ last_chunk = iff_data;
+ FindNextChunk (name);
+}
+
+/*
+============
+GetWavinfo
+============
+*/
+static wavinfo_t GetWavinfo (char *name, byte *wav, int wavlength)
+{
+ wavinfo_t info;
+
+ Com_Memset (&info, 0, sizeof(info));
+
+ if (!wav)
+ return info;
+
+ iff_data = wav;
+ iff_end = wav + wavlength;
+
+// find "RIFF" chunk
+ FindChunk("RIFF");
+ if (!(data_p && !strncmp((char *)data_p+8, "WAVE", 4)))
+ {
+ Com_Printf("Missing RIFF/WAVE chunks\n");
+ return info;
+ }
+
+// get "fmt " chunk
+ iff_data = data_p + 12;
+// DumpChunks ();
+
+ FindChunk("fmt ");
+ if (!data_p)
+ {
+ Com_Printf("Missing fmt chunk\n");
+ return info;
+ }
+ data_p += 8;
+ info.format = GetLittleShort();
+ info.channels = GetLittleShort();
+ info.rate = GetLittleLong();
+ data_p += 4+2;
+ info.width = GetLittleShort() / 8;
+
+ if (info.format != 1)
+ {
+ Com_Printf("Microsoft PCM format only\n");
+ return info;
+ }
+
+
+// find data chunk
+ FindChunk("data");
+ if (!data_p)
+ {
+ Com_Printf("Missing data chunk\n");
+ return info;
+ }
+
+ data_p += 4;
+ info.samples = GetLittleLong () / info.width;
+ info.dataofs = data_p - wav;
+
+ return info;
+}
+
+
+/*
+================
+ResampleSfx
+
+resample / decimate to the current source rate
+================
+*/
+static void ResampleSfx( sfx_t *sfx, int inrate, int inwidth, byte *data, qboolean compressed ) {
+ int outcount;
+ int srcsample;
+ float stepscale;
+ int i;
+ int sample, samplefrac, fracstep;
+ int part;
+ sndBuffer *chunk;
+
+ stepscale = (float)inrate / dma.speed; // this is usually 0.5, 1, or 2
+
+ outcount = sfx->soundLength / stepscale;
+ sfx->soundLength = outcount;
+
+ samplefrac = 0;
+ fracstep = stepscale * 256;
+ chunk = sfx->soundData;
+
+ for (i=0 ; i<outcount ; i++)
+ {
+ srcsample = samplefrac >> 8;
+ samplefrac += fracstep;
+ if( inwidth == 2 ) {
+ sample = LittleShort ( ((short *)data)[srcsample] );
+ } else {
+ sample = (int)( (unsigned char)(data[srcsample]) - 128) << 8;
+ }
+ part = (i&(SND_CHUNK_SIZE-1));
+ if (part == 0) {
+ sndBuffer *newchunk;
+ newchunk = SND_malloc();
+ if (chunk == NULL) {
+ sfx->soundData = newchunk;
+ } else {
+ chunk->next = newchunk;
+ }
+ chunk = newchunk;
+ }
+
+ chunk->sndChunk[part] = sample;
+ }
+}
+
+/*
+================
+ResampleSfx
+
+resample / decimate to the current source rate
+================
+*/
+static int ResampleSfxRaw( short *sfx, int inrate, int inwidth, int samples, byte *data ) {
+ int outcount;
+ int srcsample;
+ float stepscale;
+ int i;
+ int sample, samplefrac, fracstep;
+
+ stepscale = (float)inrate / dma.speed; // this is usually 0.5, 1, or 2
+
+ outcount = samples / stepscale;
+
+ samplefrac = 0;
+ fracstep = stepscale * 256;
+
+ for (i=0 ; i<outcount ; i++)
+ {
+ srcsample = samplefrac >> 8;
+ samplefrac += fracstep;
+ if( inwidth == 2 ) {
+ sample = LittleShort ( ((short *)data)[srcsample] );
+ } else {
+ sample = (int)( (unsigned char)(data[srcsample]) - 128) << 8;
+ }
+ sfx[i] = sample;
+ }
+ return outcount;
+}
+
+
+//=============================================================================
+
+/*
+==============
+S_LoadSound
+
+The filename may be different than sfx->name in the case
+of a forced fallback of a player specific sound
+==============
+*/
+qboolean S_LoadSound( sfx_t *sfx )
+{
+ byte *data;
+ short *samples;
+ wavinfo_t info;
+ int size;
+
+ // player specific sounds are never directly loaded
+ if ( sfx->soundName[0] == '*') {
+ return qfalse;
+ }
+
+ // load it in
+ size = FS_ReadFile( sfx->soundName, (void **)&data );
+ if ( !data ) {
+ return qfalse;
+ }
+
+ info = GetWavinfo( sfx->soundName, data, size );
+ if ( info.channels != 1 ) {
+ Com_Printf ("%s is a stereo wav file\n", sfx->soundName);
+ FS_FreeFile (data);
+ return qfalse;
+ }
+
+ if ( info.width == 1 ) {
+ Com_DPrintf(S_COLOR_YELLOW "WARNING: %s is a 8 bit wav file\n", sfx->soundName);
+ }
+
+ if ( info.rate != 22050 ) {
+ Com_DPrintf(S_COLOR_YELLOW "WARNING: %s is not a 22kHz wav file\n", sfx->soundName);
+ }
+
+ samples = Hunk_AllocateTempMemory(info.samples * sizeof(short) * 2);
+
+ sfx->lastTimeUsed = Com_Milliseconds()+1;
+
+ // each of these compression schemes works just fine
+ // but the 16bit quality is much nicer and with a local
+ // install assured we can rely upon the sound memory
+ // manager to do the right thing for us and page
+ // sound in as needed
+
+ if( sfx->soundCompressed == qtrue) {
+ sfx->soundCompressionMethod = 1;
+ sfx->soundData = NULL;
+ sfx->soundLength = ResampleSfxRaw( samples, info.rate, info.width, info.samples, (data + info.dataofs) );
+ S_AdpcmEncodeSound(sfx, samples);
+#if 0
+ } else if (info.samples>(SND_CHUNK_SIZE*16) && info.width >1) {
+ sfx->soundCompressionMethod = 3;
+ sfx->soundData = NULL;
+ sfx->soundLength = ResampleSfxRaw( samples, info.rate, info.width, info.samples, (data + info.dataofs) );
+ encodeMuLaw( sfx, samples);
+ } else if (info.samples>(SND_CHUNK_SIZE*6400) && info.width >1) {
+ sfx->soundCompressionMethod = 2;
+ sfx->soundData = NULL;
+ sfx->soundLength = ResampleSfxRaw( samples, info.rate, info.width, info.samples, (data + info.dataofs) );
+ encodeWavelet( sfx, samples);
+#endif
+ } else {
+ sfx->soundCompressionMethod = 0;
+ sfx->soundLength = info.samples;
+ sfx->soundData = NULL;
+ ResampleSfx( sfx, info.rate, info.width, data + info.dataofs, qfalse );
+ }
+
+ Hunk_FreeTempMemory(samples);
+ FS_FreeFile( data );
+
+ return qtrue;
+}
+
+void S_DisplayFreeMemory() {
+ Com_Printf("%d bytes free sound buffer memory, %d total used\n", inUse, totalInUse);
+}
diff --git a/code/client/snd_mix.c b/code/client/snd_mix.c
new file mode 100755
index 0000000..ec983b9
--- /dev/null
+++ b/code/client/snd_mix.c
@@ -0,0 +1,681 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// snd_mix.c -- portable code to mix sounds for snd_dma.c
+
+#include "snd_local.h"
+
+static portable_samplepair_t paintbuffer[PAINTBUFFER_SIZE];
+static int snd_vol;
+
+// bk001119 - these not static, required by unix/snd_mixa.s
+int* snd_p;
+int snd_linear_count;
+short* snd_out;
+
+#if !( (defined __linux__ || defined __FreeBSD__ ) && (defined __i386__) ) // rb010123
+#if !id386
+
+void S_WriteLinearBlastStereo16 (void)
+{
+ int i;
+ int val;
+
+ for (i=0 ; i<snd_linear_count ; i+=2)
+ {
+ val = snd_p[i]>>8;
+ if (val > 0x7fff)
+ snd_out[i] = 0x7fff;
+ else if (val < -32768)
+ snd_out[i] = -32768;
+ else
+ snd_out[i] = val;
+
+ val = snd_p[i+1]>>8;
+ if (val > 0x7fff)
+ snd_out[i+1] = 0x7fff;
+ else if (val < -32768)
+ snd_out[i+1] = -32768;
+ else
+ snd_out[i+1] = val;
+ }
+}
+#else
+
+__declspec( naked ) void S_WriteLinearBlastStereo16 (void)
+{
+ __asm {
+
+ push edi
+ push ebx
+ mov ecx,ds:dword ptr[snd_linear_count]
+ mov ebx,ds:dword ptr[snd_p]
+ mov edi,ds:dword ptr[snd_out]
+LWLBLoopTop:
+ mov eax,ds:dword ptr[-8+ebx+ecx*4]
+ sar eax,8
+ cmp eax,07FFFh
+ jg LClampHigh
+ cmp eax,0FFFF8000h
+ jnl LClampDone
+ mov eax,0FFFF8000h
+ jmp LClampDone
+LClampHigh:
+ mov eax,07FFFh
+LClampDone:
+ mov edx,ds:dword ptr[-4+ebx+ecx*4]
+ sar edx,8
+ cmp edx,07FFFh
+ jg LClampHigh2
+ cmp edx,0FFFF8000h
+ jnl LClampDone2
+ mov edx,0FFFF8000h
+ jmp LClampDone2
+LClampHigh2:
+ mov edx,07FFFh
+LClampDone2:
+ shl edx,16
+ and eax,0FFFFh
+ or edx,eax
+ mov ds:dword ptr[-4+edi+ecx*2],edx
+ sub ecx,2
+ jnz LWLBLoopTop
+ pop ebx
+ pop edi
+ ret
+ }
+}
+
+#endif
+#else
+// forward declare, implementation somewhere else
+void S_WriteLinearBlastStereo16 (void);
+#endif
+
+void S_TransferStereo16 (unsigned long *pbuf, int endtime)
+{
+ int lpos;
+ int ls_paintedtime;
+
+ snd_p = (int *) paintbuffer;
+ ls_paintedtime = s_paintedtime;
+
+ while (ls_paintedtime < endtime)
+ {
+ // handle recirculating buffer issues
+ lpos = ls_paintedtime & ((dma.samples>>1)-1);
+
+ snd_out = (short *) pbuf + (lpos<<1);
+
+ snd_linear_count = (dma.samples>>1) - lpos;
+ if (ls_paintedtime + snd_linear_count > endtime)
+ snd_linear_count = endtime - ls_paintedtime;
+
+ snd_linear_count <<= 1;
+
+ // write a linear blast of samples
+ S_WriteLinearBlastStereo16 ();
+
+ snd_p += snd_linear_count;
+ ls_paintedtime += (snd_linear_count>>1);
+ }
+}
+
+/*
+===================
+S_TransferPaintBuffer
+
+===================
+*/
+void S_TransferPaintBuffer(int endtime)
+{
+ int out_idx;
+ int count;
+ int out_mask;
+ int *p;
+ int step;
+ int val;
+ unsigned long *pbuf;
+
+ pbuf = (unsigned long *)dma.buffer;
+
+
+ if ( s_testsound->integer ) {
+ int i;
+ int count;
+
+ // write a fixed sine wave
+ count = (endtime - s_paintedtime);
+ for (i=0 ; i<count ; i++)
+ paintbuffer[i].left = paintbuffer[i].right = sin((s_paintedtime+i)*0.1)*20000*256;
+ }
+
+
+ if (dma.samplebits == 16 && dma.channels == 2)
+ { // optimized case
+ S_TransferStereo16 (pbuf, endtime);
+ }
+ else
+ { // general case
+ p = (int *) paintbuffer;
+ count = (endtime - s_paintedtime) * dma.channels;
+ out_mask = dma.samples - 1;
+ out_idx = s_paintedtime * dma.channels & out_mask;
+ step = 3 - dma.channels;
+
+ if (dma.samplebits == 16)
+ {
+ short *out = (short *) pbuf;
+ while (count--)
+ {
+ val = *p >> 8;
+ p+= step;
+ if (val > 0x7fff)
+ val = 0x7fff;
+ else if (val < -32768)
+ val = -32768;
+ out[out_idx] = val;
+ out_idx = (out_idx + 1) & out_mask;
+ }
+ }
+ else if (dma.samplebits == 8)
+ {
+ unsigned char *out = (unsigned char *) pbuf;
+ while (count--)
+ {
+ val = *p >> 8;
+ p+= step;
+ if (val > 0x7fff)
+ val = 0x7fff;
+ else if (val < -32768)
+ val = -32768;
+ out[out_idx] = (val>>8) + 128;
+ out_idx = (out_idx + 1) & out_mask;
+ }
+ }
+ }
+}
+
+
+/*
+===============================================================================
+
+CHANNEL MIXING
+
+===============================================================================
+*/
+
+static void S_PaintChannelFrom16( channel_t *ch, const sfx_t *sc, int count, int sampleOffset, int bufferOffset ) {
+ int data, aoff, boff;
+ int leftvol, rightvol;
+ int i, j;
+ portable_samplepair_t *samp;
+ sndBuffer *chunk;
+ short *samples;
+ float ooff, fdata, fdiv, fleftvol, frightvol;
+
+ samp = &paintbuffer[ bufferOffset ];
+
+ if (ch->doppler) {
+ sampleOffset = sampleOffset*ch->oldDopplerScale;
+ }
+
+ chunk = sc->soundData;
+ while (sampleOffset>=SND_CHUNK_SIZE) {
+ chunk = chunk->next;
+ sampleOffset -= SND_CHUNK_SIZE;
+ if (!chunk) {
+ chunk = sc->soundData;
+ }
+ }
+
+ if (!ch->doppler || ch->dopplerScale==1.0f) {
+#if idppc_altivec
+ vector signed short volume_vec;
+ vector unsigned int volume_shift;
+ int vectorCount, samplesLeft, chunkSamplesLeft;
+#endif
+ leftvol = ch->leftvol*snd_vol;
+ rightvol = ch->rightvol*snd_vol;
+ samples = chunk->sndChunk;
+#if idppc_altivec
+ ((short *)&volume_vec)[0] = leftvol;
+ ((short *)&volume_vec)[1] = leftvol;
+ ((short *)&volume_vec)[4] = leftvol;
+ ((short *)&volume_vec)[5] = leftvol;
+ ((short *)&volume_vec)[2] = rightvol;
+ ((short *)&volume_vec)[3] = rightvol;
+ ((short *)&volume_vec)[6] = rightvol;
+ ((short *)&volume_vec)[7] = rightvol;
+ volume_shift = vec_splat_u32(8);
+ i = 0;
+
+ while(i < count) {
+ /* Try to align destination to 16-byte boundary */
+ while(i < count && (((unsigned long)&samp[i] & 0x1f) || ((count-i) < 8) || ((SND_CHUNK_SIZE - sampleOffset) < 8))) {
+ data = samples[sampleOffset++];
+ samp[i].left += (data * leftvol)>>8;
+ samp[i].right += (data * rightvol)>>8;
+
+ if (sampleOffset == SND_CHUNK_SIZE) {
+ chunk = chunk->next;
+ samples = chunk->sndChunk;
+ sampleOffset = 0;
+ }
+ i++;
+ }
+ /* Destination is now aligned. Process as many 8-sample
+ chunks as we can before we run out of room from the current
+ sound chunk. We do 8 per loop to avoid extra source data reads. */
+ samplesLeft = count - i;
+ chunkSamplesLeft = SND_CHUNK_SIZE - sampleOffset;
+ if(samplesLeft > chunkSamplesLeft)
+ samplesLeft = chunkSamplesLeft;
+
+ vectorCount = samplesLeft / 8;
+
+ if(vectorCount)
+ {
+ vector unsigned char tmp;
+ vector short s0, s1, sampleData0, sampleData1;
+ vector short samples0, samples1;
+ vector signed int left0, right0;
+ vector signed int merge0, merge1;
+ vector signed int d0, d1, d2, d3;
+ vector unsigned char samplePermute0 =
+ (vector unsigned char)(0, 1, 4, 5, 0, 1, 4, 5, 2, 3, 6, 7, 2, 3, 6, 7);
+ vector unsigned char samplePermute1 =
+ (vector unsigned char)(8, 9, 12, 13, 8, 9, 12, 13, 10, 11, 14, 15, 10, 11, 14, 15);
+ vector unsigned char loadPermute0, loadPermute1;
+
+ // Rather than permute the vectors after we load them to do the sample
+ // replication and rearrangement, we permute the alignment vector so
+ // we do everything in one step below and avoid data shuffling.
+ tmp = vec_lvsl(0,&samples[sampleOffset]);
+ loadPermute0 = vec_perm(tmp,tmp,samplePermute0);
+ loadPermute1 = vec_perm(tmp,tmp,samplePermute1);
+
+ s0 = *(vector short *)&samples[sampleOffset];
+ while(vectorCount)
+ {
+ /* Load up source (16-bit) sample data */
+ s1 = *(vector short *)&samples[sampleOffset+7];
+
+ /* Load up destination sample data */
+ d0 = *(vector signed int *)&samp[i];
+ d1 = *(vector signed int *)&samp[i+2];
+ d2 = *(vector signed int *)&samp[i+4];
+ d3 = *(vector signed int *)&samp[i+6];
+
+ sampleData0 = vec_perm(s0,s1,loadPermute0);
+ sampleData1 = vec_perm(s0,s1,loadPermute1);
+
+ merge0 = vec_mule(sampleData0,volume_vec);
+ merge0 = vec_sra(merge0,volume_shift); /* Shift down to proper range */
+
+ merge1 = vec_mulo(sampleData0,volume_vec);
+ merge1 = vec_sra(merge1,volume_shift);
+
+ d0 = vec_add(merge0,d0);
+ d1 = vec_add(merge1,d1);
+
+ merge0 = vec_mule(sampleData1,volume_vec);
+ merge0 = vec_sra(merge0,volume_shift); /* Shift down to proper range */
+
+ merge1 = vec_mulo(sampleData1,volume_vec);
+ merge1 = vec_sra(merge1,volume_shift);
+
+ d2 = vec_add(merge0,d2);
+ d3 = vec_add(merge1,d3);
+
+ /* Store destination sample data */
+ *(vector signed int *)&samp[i] = d0;
+ *(vector signed int *)&samp[i+2] = d1;
+ *(vector signed int *)&samp[i+4] = d2;
+ *(vector signed int *)&samp[i+6] = d3;
+
+ i += 8;
+ vectorCount--;
+ s0 = s1;
+ sampleOffset += 8;
+ }
+ if (sampleOffset == SND_CHUNK_SIZE) {
+ chunk = chunk->next;
+ samples = chunk->sndChunk;
+ sampleOffset = 0;
+ }
+ }
+ }
+#else
+ for ( i=0 ; i<count ; i++ ) {
+ data = samples[sampleOffset++];
+ samp[i].left += (data * leftvol)>>8;
+ samp[i].right += (data * rightvol)>>8;
+
+ if (sampleOffset == SND_CHUNK_SIZE) {
+ chunk = chunk->next;
+ samples = chunk->sndChunk;
+ sampleOffset = 0;
+ }
+ }
+#endif
+ } else {
+ fleftvol = ch->leftvol*snd_vol;
+ frightvol = ch->rightvol*snd_vol;
+
+ ooff = sampleOffset;
+ samples = chunk->sndChunk;
+
+
+
+
+ for ( i=0 ; i<count ; i++ ) {
+
+ aoff = ooff;
+ ooff = ooff + ch->dopplerScale;
+ boff = ooff;
+ fdata = 0;
+ for (j=aoff; j<boff; j++) {
+ if (j == SND_CHUNK_SIZE) {
+ chunk = chunk->next;
+ if (!chunk) {
+ chunk = sc->soundData;
+ }
+ samples = chunk->sndChunk;
+ ooff -= SND_CHUNK_SIZE;
+ }
+ fdata += samples[j&(SND_CHUNK_SIZE-1)];
+ }
+ fdiv = 256 * (boff-aoff);
+ samp[i].left += (fdata * fleftvol)/fdiv;
+ samp[i].right += (fdata * frightvol)/fdiv;
+ }
+ }
+}
+
+void S_PaintChannelFromWavelet( channel_t *ch, sfx_t *sc, int count, int sampleOffset, int bufferOffset ) {
+ int data;
+ int leftvol, rightvol;
+ int i;
+ portable_samplepair_t *samp;
+ sndBuffer *chunk;
+ short *samples;
+
+ leftvol = ch->leftvol*snd_vol;
+ rightvol = ch->rightvol*snd_vol;
+
+ i = 0;
+ samp = &paintbuffer[ bufferOffset ];
+ chunk = sc->soundData;
+ while (sampleOffset>=(SND_CHUNK_SIZE_FLOAT*4)) {
+ chunk = chunk->next;
+ sampleOffset -= (SND_CHUNK_SIZE_FLOAT*4);
+ i++;
+ }
+
+ if (i!=sfxScratchIndex || sfxScratchPointer != sc) {
+ S_AdpcmGetSamples( chunk, sfxScratchBuffer );
+ sfxScratchIndex = i;
+ sfxScratchPointer = sc;
+ }
+
+ samples = sfxScratchBuffer;
+
+ for ( i=0 ; i<count ; i++ ) {
+ data = samples[sampleOffset++];
+ samp[i].left += (data * leftvol)>>8;
+ samp[i].right += (data * rightvol)>>8;
+
+ if (sampleOffset == SND_CHUNK_SIZE*2) {
+ chunk = chunk->next;
+ decodeWavelet(chunk, sfxScratchBuffer);
+ sfxScratchIndex++;
+ sampleOffset = 0;
+ }
+ }
+}
+
+void S_PaintChannelFromADPCM( channel_t *ch, sfx_t *sc, int count, int sampleOffset, int bufferOffset ) {
+ int data;
+ int leftvol, rightvol;
+ int i;
+ portable_samplepair_t *samp;
+ sndBuffer *chunk;
+ short *samples;
+
+ leftvol = ch->leftvol*snd_vol;
+ rightvol = ch->rightvol*snd_vol;
+
+ i = 0;
+ samp = &paintbuffer[ bufferOffset ];
+ chunk = sc->soundData;
+
+ if (ch->doppler) {
+ sampleOffset = sampleOffset*ch->oldDopplerScale;
+ }
+
+ while (sampleOffset>=(SND_CHUNK_SIZE*4)) {
+ chunk = chunk->next;
+ sampleOffset -= (SND_CHUNK_SIZE*4);
+ i++;
+ }
+
+ if (i!=sfxScratchIndex || sfxScratchPointer != sc) {
+ S_AdpcmGetSamples( chunk, sfxScratchBuffer );
+ sfxScratchIndex = i;
+ sfxScratchPointer = sc;
+ }
+
+ samples = sfxScratchBuffer;
+
+ for ( i=0 ; i<count ; i++ ) {
+ data = samples[sampleOffset++];
+ samp[i].left += (data * leftvol)>>8;
+ samp[i].right += (data * rightvol)>>8;
+
+ if (sampleOffset == SND_CHUNK_SIZE*4) {
+ chunk = chunk->next;
+ S_AdpcmGetSamples( chunk, sfxScratchBuffer);
+ sampleOffset = 0;
+ sfxScratchIndex++;
+ }
+ }
+}
+
+void S_PaintChannelFromMuLaw( channel_t *ch, sfx_t *sc, int count, int sampleOffset, int bufferOffset ) {
+ int data;
+ int leftvol, rightvol;
+ int i;
+ portable_samplepair_t *samp;
+ sndBuffer *chunk;
+ byte *samples;
+ float ooff;
+
+ leftvol = ch->leftvol*snd_vol;
+ rightvol = ch->rightvol*snd_vol;
+
+ samp = &paintbuffer[ bufferOffset ];
+ chunk = sc->soundData;
+ while (sampleOffset>=(SND_CHUNK_SIZE*2)) {
+ chunk = chunk->next;
+ sampleOffset -= (SND_CHUNK_SIZE*2);
+ if (!chunk) {
+ chunk = sc->soundData;
+ }
+ }
+
+ if (!ch->doppler) {
+ samples = (byte *)chunk->sndChunk + sampleOffset;
+ for ( i=0 ; i<count ; i++ ) {
+ data = mulawToShort[*samples];
+ samp[i].left += (data * leftvol)>>8;
+ samp[i].right += (data * rightvol)>>8;
+ samples++;
+ if (samples == (byte *)chunk->sndChunk+(SND_CHUNK_SIZE*2)) {
+ chunk = chunk->next;
+ samples = (byte *)chunk->sndChunk;
+ }
+ }
+ } else {
+ ooff = sampleOffset;
+ samples = (byte *)chunk->sndChunk;
+ for ( i=0 ; i<count ; i++ ) {
+ data = mulawToShort[samples[(int)(ooff)]];
+ ooff = ooff + ch->dopplerScale;
+ samp[i].left += (data * leftvol)>>8;
+ samp[i].right += (data * rightvol)>>8;
+ if (ooff >= SND_CHUNK_SIZE*2) {
+ chunk = chunk->next;
+ if (!chunk) {
+ chunk = sc->soundData;
+ }
+ samples = (byte *)chunk->sndChunk;
+ ooff = 0.0;
+ }
+ }
+ }
+}
+
+/*
+===================
+S_PaintChannels
+===================
+*/
+void S_PaintChannels( int endtime ) {
+ int i;
+ int end;
+ channel_t *ch;
+ sfx_t *sc;
+ int ltime, count;
+ int sampleOffset;
+
+
+ snd_vol = s_volume->value*255;
+
+//Com_Printf ("%i to %i\n", s_paintedtime, endtime);
+ while ( s_paintedtime < endtime ) {
+ // if paintbuffer is smaller than DMA buffer
+ // we may need to fill it multiple times
+ end = endtime;
+ if ( endtime - s_paintedtime > PAINTBUFFER_SIZE ) {
+ end = s_paintedtime + PAINTBUFFER_SIZE;
+ }
+
+ // clear the paint buffer to either music or zeros
+ if ( s_rawend < s_paintedtime ) {
+ if ( s_rawend ) {
+ //Com_DPrintf ("background sound underrun\n");
+ }
+ Com_Memset(paintbuffer, 0, (end - s_paintedtime) * sizeof(portable_samplepair_t));
+ } else {
+ // copy from the streaming sound source
+ int s;
+ int stop;
+
+ stop = (end < s_rawend) ? end : s_rawend;
+
+ for ( i = s_paintedtime ; i < stop ; i++ ) {
+ s = i&(MAX_RAW_SAMPLES-1);
+ paintbuffer[i-s_paintedtime] = s_rawsamples[s];
+ }
+// if (i != end)
+// Com_Printf ("partial stream\n");
+// else
+// Com_Printf ("full stream\n");
+ for ( ; i < end ; i++ ) {
+ paintbuffer[i-s_paintedtime].left =
+ paintbuffer[i-s_paintedtime].right = 0;
+ }
+ }
+
+ // paint in the channels.
+ ch = s_channels;
+ for ( i = 0; i < MAX_CHANNELS ; i++, ch++ ) {
+ if ( !ch->thesfx || (ch->leftvol<0.25 && ch->rightvol<0.25 )) {
+ continue;
+ }
+
+ ltime = s_paintedtime;
+ sc = ch->thesfx;
+
+ sampleOffset = ltime - ch->startSample;
+ count = end - ltime;
+ if ( sampleOffset + count > sc->soundLength ) {
+ count = sc->soundLength - sampleOffset;
+ }
+
+ if ( count > 0 ) {
+ if( sc->soundCompressionMethod == 1) {
+ S_PaintChannelFromADPCM (ch, sc, count, sampleOffset, ltime - s_paintedtime);
+ } else if( sc->soundCompressionMethod == 2) {
+ S_PaintChannelFromWavelet (ch, sc, count, sampleOffset, ltime - s_paintedtime);
+ } else if( sc->soundCompressionMethod == 3) {
+ S_PaintChannelFromMuLaw (ch, sc, count, sampleOffset, ltime - s_paintedtime);
+ } else {
+ S_PaintChannelFrom16 (ch, sc, count, sampleOffset, ltime - s_paintedtime);
+ }
+ }
+ }
+
+ // paint in the looped channels.
+ ch = loop_channels;
+ for ( i = 0; i < numLoopChannels ; i++, ch++ ) {
+ if ( !ch->thesfx || (!ch->leftvol && !ch->rightvol )) {
+ continue;
+ }
+
+ ltime = s_paintedtime;
+ sc = ch->thesfx;
+
+ if (sc->soundData==NULL || sc->soundLength==0) {
+ continue;
+ }
+ // we might have to make two passes if it
+ // is a looping sound effect and the end of
+ // the sample is hit
+ do {
+ sampleOffset = (ltime % sc->soundLength);
+
+ count = end - ltime;
+ if ( sampleOffset + count > sc->soundLength ) {
+ count = sc->soundLength - sampleOffset;
+ }
+
+ if ( count > 0 ) {
+ if( sc->soundCompressionMethod == 1) {
+ S_PaintChannelFromADPCM (ch, sc, count, sampleOffset, ltime - s_paintedtime);
+ } else if( sc->soundCompressionMethod == 2) {
+ S_PaintChannelFromWavelet (ch, sc, count, sampleOffset, ltime - s_paintedtime);
+ } else if( sc->soundCompressionMethod == 3) {
+ S_PaintChannelFromMuLaw (ch, sc, count, sampleOffset, ltime - s_paintedtime);
+ } else {
+ S_PaintChannelFrom16 (ch, sc, count, sampleOffset, ltime - s_paintedtime);
+ }
+ ltime += count;
+ }
+ } while ( ltime < end);
+ }
+
+ // transfer out according to DMA format
+ S_TransferPaintBuffer( end );
+ s_paintedtime = end;
+ }
+}
diff --git a/code/client/snd_public.h b/code/client/snd_public.h
new file mode 100755
index 0000000..438fc53
--- /dev/null
+++ b/code/client/snd_public.h
@@ -0,0 +1,72 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+
+void S_Init( void );
+void S_Shutdown( void );
+
+// if origin is NULL, the sound will be dynamically sourced from the entity
+void S_StartSound( vec3_t origin, int entnum, int entchannel, sfxHandle_t sfx );
+void S_StartLocalSound( sfxHandle_t sfx, int channelNum );
+
+void S_StartBackgroundTrack( const char *intro, const char *loop );
+void S_StopBackgroundTrack( void );
+
+// cinematics and voice-over-network will send raw samples
+// 1.0 volume will be direct output of source samples
+void S_RawSamples (int samples, int rate, int width, int channels,
+ const byte *data, float volume);
+
+// stop all sounds and the background track
+void S_StopAllSounds( void );
+
+// all continuous looping sounds must be added before calling S_Update
+void S_ClearLoopingSounds( qboolean killall );
+void S_AddLoopingSound( int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx );
+void S_AddRealLoopingSound( int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx );
+void S_StopLoopingSound(int entityNum );
+
+// recompute the reletive volumes for all running sounds
+// reletive to the given entityNum / orientation
+void S_Respatialize( int entityNum, const vec3_t origin, vec3_t axis[3], int inwater );
+
+// let the sound system know where an entity currently is
+void S_UpdateEntityPosition( int entityNum, const vec3_t origin );
+
+void S_Update( void );
+
+void S_DisableSounds( void );
+
+void S_BeginRegistration( void );
+
+// RegisterSound will allways return a valid sample, even if it
+// has to create a placeholder. This prevents continuous filesystem
+// checks for missing files
+sfxHandle_t S_RegisterSound( const char *sample, qboolean compressed );
+
+void S_DisplayFreeMemory(void);
+
+void S_ClearSoundBuffer( void );
+
+void SNDDMA_Activate( void );
+
+void S_UpdateBackgroundTrack( void );
diff --git a/code/client/snd_wavelet.c b/code/client/snd_wavelet.c
new file mode 100755
index 0000000..9b07ee1
--- /dev/null
+++ b/code/client/snd_wavelet.c
@@ -0,0 +1,253 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "snd_local.h"
+
+long myftol( float f );
+
+#define C0 0.4829629131445341
+#define C1 0.8365163037378079
+#define C2 0.2241438680420134
+#define C3 -0.1294095225512604
+
+void daub4(float b[], unsigned long n, int isign)
+{
+ float wksp[4097];
+ float *a=b-1; // numerical recipies so a[1] = b[0]
+
+ unsigned long nh,nh1,i,j;
+
+ if (n < 4) return;
+
+ nh1=(nh=n >> 1)+1;
+ if (isign >= 0) {
+ for (i=1,j=1;j<=n-3;j+=2,i++) {
+ wksp[i] = C0*a[j]+C1*a[j+1]+C2*a[j+2]+C3*a[j+3];
+ wksp[i+nh] = C3*a[j]-C2*a[j+1]+C1*a[j+2]-C0*a[j+3];
+ }
+ wksp[i ] = C0*a[n-1]+C1*a[n]+C2*a[1]+C3*a[2];
+ wksp[i+nh] = C3*a[n-1]-C2*a[n]+C1*a[1]-C0*a[2];
+ } else {
+ wksp[1] = C2*a[nh]+C1*a[n]+C0*a[1]+C3*a[nh1];
+ wksp[2] = C3*a[nh]-C0*a[n]+C1*a[1]-C2*a[nh1];
+ for (i=1,j=3;i<nh;i++) {
+ wksp[j++] = C2*a[i]+C1*a[i+nh]+C0*a[i+1]+C3*a[i+nh1];
+ wksp[j++] = C3*a[i]-C0*a[i+nh]+C1*a[i+1]-C2*a[i+nh1];
+ }
+ }
+ for (i=1;i<=n;i++) {
+ a[i]=wksp[i];
+ }
+}
+
+void wt1(float a[], unsigned long n, int isign)
+{
+ unsigned long nn;
+ int inverseStartLength = n/4;
+ if (n < inverseStartLength) return;
+ if (isign >= 0) {
+ for (nn=n;nn>=inverseStartLength;nn>>=1) daub4(a,nn,isign);
+ } else {
+ for (nn=inverseStartLength;nn<=n;nn<<=1) daub4(a,nn,isign);
+ }
+}
+
+/* The number of bits required by each value */
+static unsigned char numBits[] = {
+ 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
+ 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+};
+
+byte MuLawEncode(short s) {
+ unsigned long adjusted;
+ byte sign, exponent, mantissa;
+
+ sign = (s<0)?0:0x80;
+
+ if (s<0) s=-s;
+ adjusted = (long)s << (16-sizeof(short)*8);
+ adjusted += 128L + 4L;
+ if (adjusted > 32767) adjusted = 32767;
+ exponent = numBits[(adjusted>>7)&0xff] - 1;
+ mantissa = (adjusted>>(exponent+3))&0xf;
+ return ~(sign | (exponent<<4) | mantissa);
+}
+
+short MuLawDecode(byte uLaw) {
+ signed long adjusted;
+ byte exponent, mantissa;
+
+ uLaw = ~uLaw;
+ exponent = (uLaw>>4) & 0x7;
+ mantissa = (uLaw&0xf) + 16;
+ adjusted = (mantissa << (exponent +3)) - 128 - 4;
+
+ return (uLaw & 0x80)? adjusted : -adjusted;
+}
+
+short mulawToShort[256];
+static qboolean madeTable = qfalse;
+
+static int NXStreamCount;
+
+void NXPutc(NXStream *stream, char out) {
+ stream[NXStreamCount++] = out;
+}
+
+
+void encodeWavelet( sfx_t *sfx, short *packets) {
+ float wksp[4097], temp;
+ int i, samples, size;
+ sndBuffer *newchunk, *chunk;
+ byte *out;
+
+ if (!madeTable) {
+ for (i=0;i<256;i++) {
+ mulawToShort[i] = (float)MuLawDecode((byte)i);
+ }
+ madeTable = qtrue;
+ }
+ chunk = NULL;
+
+ samples = sfx->soundLength;
+ while(samples>0) {
+ size = samples;
+ if (size>(SND_CHUNK_SIZE*2)) {
+ size = (SND_CHUNK_SIZE*2);
+ }
+
+ if (size<4) {
+ size = 4;
+ }
+
+ newchunk = SND_malloc();
+ if (sfx->soundData == NULL) {
+ sfx->soundData = newchunk;
+ } else {
+ chunk->next = newchunk;
+ }
+ chunk = newchunk;
+ for(i=0; i<size; i++) {
+ wksp[i] = *packets;
+ packets++;
+ }
+ wt1(wksp, size, 1);
+ out = (byte *)chunk->sndChunk;
+
+ for(i=0;i<size;i++) {
+ temp = wksp[i];
+ if (temp > 32767) temp = 32767; else if (temp<-32768) temp = -32768;
+ out[i] = MuLawEncode((short)temp);
+ }
+
+ chunk->size = size;
+ samples -= size;
+ }
+}
+
+void decodeWavelet(sndBuffer *chunk, short *to) {
+ float wksp[4097];
+ int i;
+ byte *out;
+
+ int size = chunk->size;
+
+ out = (byte *)chunk->sndChunk;
+ for(i=0;i<size;i++) {
+ wksp[i] = mulawToShort[out[i]];
+ }
+
+ wt1(wksp, size, -1);
+
+ if (!to) return;
+
+ for(i=0; i<size; i++) {
+ to[i] = wksp[i];
+ }
+}
+
+
+void encodeMuLaw( sfx_t *sfx, short *packets) {
+ int i, samples, size, grade, poop;
+ sndBuffer *newchunk, *chunk;
+ byte *out;
+
+ if (!madeTable) {
+ for (i=0;i<256;i++) {
+ mulawToShort[i] = (float)MuLawDecode((byte)i);
+ }
+ madeTable = qtrue;
+ }
+
+ chunk = NULL;
+ samples = sfx->soundLength;
+ grade = 0;
+
+ while(samples>0) {
+ size = samples;
+ if (size>(SND_CHUNK_SIZE*2)) {
+ size = (SND_CHUNK_SIZE*2);
+ }
+
+ newchunk = SND_malloc();
+ if (sfx->soundData == NULL) {
+ sfx->soundData = newchunk;
+ } else {
+ chunk->next = newchunk;
+ }
+ chunk = newchunk;
+ out = (byte *)chunk->sndChunk;
+ for(i=0; i<size; i++) {
+ poop = packets[0]+grade;
+ if (poop>32767) {
+ poop = 32767;
+ } else if (poop<-32768) {
+ poop = -32768;
+ }
+ out[i] = MuLawEncode((short)poop);
+ grade = poop - mulawToShort[out[i]];
+ packets++;
+ }
+ chunk->size = size;
+ samples -= size;
+ }
+}
+
+void decodeMuLaw(sndBuffer *chunk, short *to) {
+ int i;
+ byte *out;
+
+ int size = chunk->size;
+
+ out = (byte *)chunk->sndChunk;
+ for(i=0;i<size;i++) {
+ to[i] = mulawToShort[out[i]];
+ }
+}
+
+
diff --git a/code/game.lnt b/code/game.lnt
new file mode 100755
index 0000000..55c8205
--- /dev/null
+++ b/code/game.lnt
@@ -0,0 +1,35 @@
+opts.lnt
+
+game\bg_misc.c
+game\bg_pmove.c
+game\bg_slidemove.c
+game\q_math.c
+game\q_shared.c
+
+botai\ai_chat.c
+botai\ai_cmd.c
+botai\ai_dmnet.c
+botai\ai_dmq3.c
+botai\ai_main.c
+botai\ai_team.c
+
+game\g_active.c
+game\g_arenas.c
+game\g_bot.c
+game\g_client.c
+game\g_cmds.c
+game\g_combat.c
+game\g_items.c
+game\g_main.c
+game\g_mem.c
+game\g_misc.c
+game\g_missile.c
+game\g_mover.c
+game\g_session.c
+game\g_spawn.c
+game\g_svcmds.c
+game\g_target.c
+game\g_team.c
+game\g_trigger.c
+game\g_utils.c
+game\g_weapon.c
diff --git a/code/game/Conscript b/code/game/Conscript
new file mode 100755
index 0000000..f823cef
--- /dev/null
+++ b/code/game/Conscript
@@ -0,0 +1,140 @@
+# game building
+# builds the game for vanilla Q3 and TA
+
+# there are slight differences between Q3 and TA build:
+# -DMISSIONPACK
+# the config is passed in the imported variable TARGET_DIR
+
+# qvm building against native:
+# only native has g_syscalls.c
+# only qvm has ../game/bg_lib.c
+# qvm uses a custom g_syscalls.asm with equ stubs
+
+Import qw( BASE_CFLAGS TARGET_DIR INSTALL_DIR NO_VM NO_SO CC CXX LINK );
+
+$env = new cons(
+ # the code has the very bad habit of doing things like #include "../ui/ui_shared.h"
+ # this seems to confuse the dependency analysis, explicit toplevel includes seem to fix
+ CPPPATH => '#cgame:#game:#q3_ui',
+ CC => $CC,
+ CXX => $CXX,
+ LINK => $LINK,
+ ENV => { PATH => $ENV{PATH}, HOME => $ENV{HOME} },
+ CFLAGS => $BASE_CFLAGS . '-fPIC',
+ LDFLAGS => '-shared -ldl -lm'
+);
+
+# for TA, use -DMISSIONPACK
+%ta_env_hash = $env->copy(
+ CPPPATH => '#cgame:#game:#ui'
+ );
+$ta_env_hash{CFLAGS} = '-DMISSIONPACK ' . $ta_env_hash{CFLAGS};
+$ta_env = new cons(%ta_env_hash);
+
+# qvm building
+# we heavily customize the cons environment
+$vm_env = new cons(
+ # the code has the very bad habit of doing things like #include "../ui/ui_shared.h"
+ # this seems to confuse the dependency analysis, explicit toplevel includes seem to fix
+ CPPPATH => '#cgame:#game:#q3_ui',
+ CC => 'q3lcc',
+ CCCOM => '%CC %CFLAGS %_IFLAGS -c %< -o %>',
+ SUFOBJ => '.asm',
+ LINK => 'q3asm',
+ CFLAGS => '-DQ3_VM -S -Wf-target=bytecode -Wf-g',
+ # need to know where to find the compiler tools
+ ENV => { PATH => $ENV{PATH} . ":./qvmtools", },
+);
+
+# TA qvm building
+%vm_ta_env_hash = $vm_env->copy(
+ CPPPATH => '#cgame:#game:#ui'
+ );
+$vm_ta_env_hash{CFLAGS} = '-DMISSIONPACK ' . $vm_ta_env_hash{CFLAGS};
+$vm_ta_env = new cons(%vm_ta_env_hash);
+
+# the file with vmMain function MUST be the first one of the list
+@FILES = qw(
+ g_main.c
+ ai_chat.c
+ ai_cmd.c
+ ai_dmnet.c
+ ai_dmq3.c
+ ai_main.c
+ ai_team.c
+ ai_vcmd.c
+ bg_misc.c
+ bg_pmove.c
+ bg_slidemove.c
+ g_active.c
+ g_arenas.c
+ g_bot.c
+ g_client.c
+ g_cmds.c
+ g_combat.c
+ g_items.c
+ g_mem.c
+ g_misc.c
+ g_missile.c
+ g_mover.c
+ g_session.c
+ g_spawn.c
+ g_svcmds.c
+ g_target.c
+ g_team.c
+ g_trigger.c
+ g_utils.c
+ g_weapon.c
+ q_math.c
+ q_shared.c
+ );
+$FILESREF = \@FILES;
+
+# only in .so
+# (VM uses a custom .asm with equ stubs)
+@SO_FILES = qw(
+ g_syscalls.c
+ );
+$SO_FILESREF = \@SO_FILES;
+
+# only for VM
+@VM_FILES = qw(
+ bg_lib.c
+ g_syscalls.asm
+ );
+$VM_FILESREF = \@VM_FILES;
+
+# FIXME CPU string?
+# NOTE: $env $ta_env and $vm_env $vm_ta_env may not be necessary
+# we could alter the $env and $ta_env based on $TARGET_DIR
+# doing it this way to ensure homogeneity with cgame building
+if ($TARGET_DIR eq 'Q3')
+{
+ if ($NO_SO eq 0)
+ {
+ Program $env 'qagamei386.so', @$FILESREF, @$SO_FILESREF;
+ Install $env $INSTALL_DIR, 'qagamei386.so';
+ }
+ if ($NO_VM eq 0)
+ {
+ Depends $vm_env 'qagame.qvm', '#qvmtools/q3lcc';
+ Depends $vm_env 'qagame.qvm', '#qvmtools/q3asm';
+ Program $vm_env 'qagame.qvm', @$FILESREF, @$VM_FILESREF;
+ Install $vm_env $INSTALL_DIR . '/vm', 'qagame.qvm';
+ }
+}
+else
+{
+ if ($NO_SO eq 0)
+ {
+ Program $ta_env 'qagamei386.so', @$FILESREF, @$SO_FILESREF;
+ Install $ta_env $INSTALL_DIR, 'qagamei386.so';
+ }
+ if ($NO_VM eq 0)
+ {
+ Depends $vm_env 'qagame.qvm', '#qvmtools/q3lcc';
+ Depends $vm_env 'qagame.qvm', '#qvmtools/q3asm';
+ Program $vm_ta_env 'qagame.qvm', @$FILESREF, @$VM_FILESREF;
+ Install $vm_ta_env $INSTALL_DIR . '/vm', 'qagame.qvm';
+ }
+}
diff --git a/code/game/ai_chat.c b/code/game/ai_chat.c
new file mode 100755
index 0000000..b5485e9
--- /dev/null
+++ b/code/game/ai_chat.c
@@ -0,0 +1,1226 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+/*****************************************************************************
+ * name: ai_chat.c
+ *
+ * desc: Quake3 bot AI
+ *
+ * $Archive: /MissionPack/code/game/ai_chat.c $
+ *
+ *****************************************************************************/
+
+#include "g_local.h"
+#include "botlib.h"
+#include "be_aas.h"
+#include "be_ea.h"
+#include "be_ai_char.h"
+#include "be_ai_chat.h"
+#include "be_ai_gen.h"
+#include "be_ai_goal.h"
+#include "be_ai_move.h"
+#include "be_ai_weap.h"
+//
+#include "ai_main.h"
+#include "ai_dmq3.h"
+#include "ai_chat.h"
+#include "ai_cmd.h"
+#include "ai_dmnet.h"
+//
+#include "chars.h" //characteristics
+#include "inv.h" //indexes into the inventory
+#include "syn.h" //synonyms
+#include "match.h" //string matching types and vars
+
+// for the voice chats
+#ifdef MISSIONPACK // bk001205
+#include "../../ui/menudef.h"
+#endif
+
+#define TIME_BETWEENCHATTING 25
+
+
+/*
+==================
+BotNumActivePlayers
+==================
+*/
+int BotNumActivePlayers(void) {
+ int i, num;
+ char buf[MAX_INFO_STRING];
+ static int maxclients;
+
+ if (!maxclients)
+ maxclients = trap_Cvar_VariableIntegerValue("sv_maxclients");
+
+ num = 0;
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ trap_GetConfigstring(CS_PLAYERS+i, buf, sizeof(buf));
+ //if no config string or no name
+ if (!strlen(buf) || !strlen(Info_ValueForKey(buf, "n"))) continue;
+ //skip spectators
+ if (atoi(Info_ValueForKey(buf, "t")) == TEAM_SPECTATOR) continue;
+ //
+ num++;
+ }
+ return num;
+}
+
+/*
+==================
+BotIsFirstInRankings
+==================
+*/
+int BotIsFirstInRankings(bot_state_t *bs) {
+ int i, score;
+ char buf[MAX_INFO_STRING];
+ static int maxclients;
+ playerState_t ps;
+
+ if (!maxclients)
+ maxclients = trap_Cvar_VariableIntegerValue("sv_maxclients");
+
+ score = bs->cur_ps.persistant[PERS_SCORE];
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ trap_GetConfigstring(CS_PLAYERS+i, buf, sizeof(buf));
+ //if no config string or no name
+ if (!strlen(buf) || !strlen(Info_ValueForKey(buf, "n"))) continue;
+ //skip spectators
+ if (atoi(Info_ValueForKey(buf, "t")) == TEAM_SPECTATOR) continue;
+ //
+ BotAI_GetClientState(i, &ps);
+ if (score < ps.persistant[PERS_SCORE]) return qfalse;
+ }
+ return qtrue;
+}
+
+/*
+==================
+BotIsLastInRankings
+==================
+*/
+int BotIsLastInRankings(bot_state_t *bs) {
+ int i, score;
+ char buf[MAX_INFO_STRING];
+ static int maxclients;
+ playerState_t ps;
+
+ if (!maxclients)
+ maxclients = trap_Cvar_VariableIntegerValue("sv_maxclients");
+
+ score = bs->cur_ps.persistant[PERS_SCORE];
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ trap_GetConfigstring(CS_PLAYERS+i, buf, sizeof(buf));
+ //if no config string or no name
+ if (!strlen(buf) || !strlen(Info_ValueForKey(buf, "n"))) continue;
+ //skip spectators
+ if (atoi(Info_ValueForKey(buf, "t")) == TEAM_SPECTATOR) continue;
+ //
+ BotAI_GetClientState(i, &ps);
+ if (score > ps.persistant[PERS_SCORE]) return qfalse;
+ }
+ return qtrue;
+}
+
+/*
+==================
+BotFirstClientInRankings
+==================
+*/
+char *BotFirstClientInRankings(void) {
+ int i, bestscore, bestclient;
+ char buf[MAX_INFO_STRING];
+ static char name[32];
+ static int maxclients;
+ playerState_t ps;
+
+ if (!maxclients)
+ maxclients = trap_Cvar_VariableIntegerValue("sv_maxclients");
+
+ bestscore = -999999;
+ bestclient = 0;
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ trap_GetConfigstring(CS_PLAYERS+i, buf, sizeof(buf));
+ //if no config string or no name
+ if (!strlen(buf) || !strlen(Info_ValueForKey(buf, "n"))) continue;
+ //skip spectators
+ if (atoi(Info_ValueForKey(buf, "t")) == TEAM_SPECTATOR) continue;
+ //
+ BotAI_GetClientState(i, &ps);
+ if (ps.persistant[PERS_SCORE] > bestscore) {
+ bestscore = ps.persistant[PERS_SCORE];
+ bestclient = i;
+ }
+ }
+ EasyClientName(bestclient, name, 32);
+ return name;
+}
+
+/*
+==================
+BotLastClientInRankings
+==================
+*/
+char *BotLastClientInRankings(void) {
+ int i, worstscore, bestclient;
+ char buf[MAX_INFO_STRING];
+ static char name[32];
+ static int maxclients;
+ playerState_t ps;
+
+ if (!maxclients)
+ maxclients = trap_Cvar_VariableIntegerValue("sv_maxclients");
+
+ worstscore = 999999;
+ bestclient = 0;
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ trap_GetConfigstring(CS_PLAYERS+i, buf, sizeof(buf));
+ //if no config string or no name
+ if (!strlen(buf) || !strlen(Info_ValueForKey(buf, "n"))) continue;
+ //skip spectators
+ if (atoi(Info_ValueForKey(buf, "t")) == TEAM_SPECTATOR) continue;
+ //
+ BotAI_GetClientState(i, &ps);
+ if (ps.persistant[PERS_SCORE] < worstscore) {
+ worstscore = ps.persistant[PERS_SCORE];
+ bestclient = i;
+ }
+ }
+ EasyClientName(bestclient, name, 32);
+ return name;
+}
+
+/*
+==================
+BotRandomOpponentName
+==================
+*/
+char *BotRandomOpponentName(bot_state_t *bs) {
+ int i, count;
+ char buf[MAX_INFO_STRING];
+ int opponents[MAX_CLIENTS], numopponents;
+ static int maxclients;
+ static char name[32];
+
+ if (!maxclients)
+ maxclients = trap_Cvar_VariableIntegerValue("sv_maxclients");
+
+ numopponents = 0;
+ opponents[0] = 0;
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ if (i == bs->client) continue;
+ //
+ trap_GetConfigstring(CS_PLAYERS+i, buf, sizeof(buf));
+ //if no config string or no name
+ if (!strlen(buf) || !strlen(Info_ValueForKey(buf, "n"))) continue;
+ //skip spectators
+ if (atoi(Info_ValueForKey(buf, "t")) == TEAM_SPECTATOR) continue;
+ //skip team mates
+ if (BotSameTeam(bs, i)) continue;
+ //
+ opponents[numopponents] = i;
+ numopponents++;
+ }
+ count = random() * numopponents;
+ for (i = 0; i < numopponents; i++) {
+ count--;
+ if (count <= 0) {
+ EasyClientName(opponents[i], name, sizeof(name));
+ return name;
+ }
+ }
+ EasyClientName(opponents[0], name, sizeof(name));
+ return name;
+}
+
+/*
+==================
+BotMapTitle
+==================
+*/
+
+char *BotMapTitle(void) {
+ char info[1024];
+ static char mapname[128];
+
+ trap_GetServerinfo(info, sizeof(info));
+
+ strncpy(mapname, Info_ValueForKey( info, "mapname" ), sizeof(mapname)-1);
+ mapname[sizeof(mapname)-1] = '\0';
+
+ return mapname;
+}
+
+
+/*
+==================
+BotWeaponNameForMeansOfDeath
+==================
+*/
+
+char *BotWeaponNameForMeansOfDeath(int mod) {
+ switch(mod) {
+ case MOD_SHOTGUN: return "Shotgun";
+ case MOD_GAUNTLET: return "Gauntlet";
+ case MOD_MACHINEGUN: return "Machinegun";
+ case MOD_GRENADE:
+ case MOD_GRENADE_SPLASH: return "Grenade Launcher";
+ case MOD_ROCKET:
+ case MOD_ROCKET_SPLASH: return "Rocket Launcher";
+ case MOD_PLASMA:
+ case MOD_PLASMA_SPLASH: return "Plasmagun";
+ case MOD_RAILGUN: return "Railgun";
+ case MOD_LIGHTNING: return "Lightning Gun";
+ case MOD_BFG:
+ case MOD_BFG_SPLASH: return "BFG10K";
+#ifdef MISSIONPACK
+ case MOD_NAIL: return "Nailgun";
+ case MOD_CHAINGUN: return "Chaingun";
+ case MOD_PROXIMITY_MINE: return "Proximity Launcher";
+ case MOD_KAMIKAZE: return "Kamikaze";
+ case MOD_JUICED: return "Prox mine";
+#endif
+ case MOD_GRAPPLE: return "Grapple";
+ default: return "[unknown weapon]";
+ }
+}
+
+/*
+==================
+BotRandomWeaponName
+==================
+*/
+char *BotRandomWeaponName(void) {
+ int rnd;
+
+#ifdef MISSIONPACK
+ rnd = random() * 11.9;
+#else
+ rnd = random() * 8.9;
+#endif
+ switch(rnd) {
+ case 0: return "Gauntlet";
+ case 1: return "Shotgun";
+ case 2: return "Machinegun";
+ case 3: return "Grenade Launcher";
+ case 4: return "Rocket Launcher";
+ case 5: return "Plasmagun";
+ case 6: return "Railgun";
+ case 7: return "Lightning Gun";
+#ifdef MISSIONPACK
+ case 8: return "Nailgun";
+ case 9: return "Chaingun";
+ case 10: return "Proximity Launcher";
+#endif
+ default: return "BFG10K";
+ }
+}
+
+/*
+==================
+BotVisibleEnemies
+==================
+*/
+int BotVisibleEnemies(bot_state_t *bs) {
+ float vis;
+ int i;
+ aas_entityinfo_t entinfo;
+
+ for (i = 0; i < MAX_CLIENTS; i++) {
+
+ if (i == bs->client) continue;
+ //
+ BotEntityInfo(i, &entinfo);
+ //
+ if (!entinfo.valid) continue;
+ //if the enemy isn't dead and the enemy isn't the bot self
+ if (EntityIsDead(&entinfo) || entinfo.number == bs->entitynum) continue;
+ //if the enemy is invisible and not shooting
+ if (EntityIsInvisible(&entinfo) && !EntityIsShooting(&entinfo)) {
+ continue;
+ }
+ //if on the same team
+ if (BotSameTeam(bs, i)) continue;
+ //check if the enemy is visible
+ vis = BotEntityVisible(bs->entitynum, bs->eye, bs->viewangles, 360, i);
+ if (vis > 0) return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+==================
+BotValidChatPosition
+==================
+*/
+int BotValidChatPosition(bot_state_t *bs) {
+ vec3_t point, start, end, mins, maxs;
+ bsp_trace_t trace;
+
+ //if the bot is dead all positions are valid
+ if (BotIsDead(bs)) return qtrue;
+ //never start chatting with a powerup
+ if (bs->inventory[INVENTORY_QUAD] ||
+ bs->inventory[INVENTORY_HASTE] ||
+ bs->inventory[INVENTORY_INVISIBILITY] ||
+ bs->inventory[INVENTORY_REGEN] ||
+ bs->inventory[INVENTORY_FLIGHT]) return qfalse;
+ //must be on the ground
+ //if (bs->cur_ps.groundEntityNum != ENTITYNUM_NONE) return qfalse;
+ //do not chat if in lava or slime
+ VectorCopy(bs->origin, point);
+ point[2] -= 24;
+ if (trap_PointContents(point,bs->entitynum) & (CONTENTS_LAVA|CONTENTS_SLIME)) return qfalse;
+ //do not chat if under water
+ VectorCopy(bs->origin, point);
+ point[2] += 32;
+ if (trap_PointContents(point,bs->entitynum) & MASK_WATER) return qfalse;
+ //must be standing on the world entity
+ VectorCopy(bs->origin, start);
+ VectorCopy(bs->origin, end);
+ start[2] += 1;
+ end[2] -= 10;
+ trap_AAS_PresenceTypeBoundingBox(PRESENCE_CROUCH, mins, maxs);
+ BotAI_Trace(&trace, start, mins, maxs, end, bs->client, MASK_SOLID);
+ if (trace.ent != ENTITYNUM_WORLD) return qfalse;
+ //the bot is in a position where it can chat
+ return qtrue;
+}
+
+/*
+==================
+BotChat_EnterGame
+==================
+*/
+int BotChat_EnterGame(bot_state_t *bs) {
+ char name[32];
+ float rnd;
+
+ if (bot_nochat.integer) return qfalse;
+ if (bs->lastchat_time > FloatTime() - TIME_BETWEENCHATTING) return qfalse;
+ //don't chat in teamplay
+ if (TeamPlayIsOn()) return qfalse;
+ // don't chat in tournament mode
+ if (gametype == GT_TOURNAMENT) return qfalse;
+ rnd = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_CHAT_ENTEREXITGAME, 0, 1);
+ if (!bot_fastchat.integer) {
+ if (random() > rnd) return qfalse;
+ }
+ if (BotNumActivePlayers() <= 1) return qfalse;
+ if (!BotValidChatPosition(bs)) return qfalse;
+ BotAI_BotInitialChat(bs, "game_enter",
+ EasyClientName(bs->client, name, 32), // 0
+ BotRandomOpponentName(bs), // 1
+ "[invalid var]", // 2
+ "[invalid var]", // 3
+ BotMapTitle(), // 4
+ NULL);
+ bs->lastchat_time = FloatTime();
+ bs->chatto = CHAT_ALL;
+ return qtrue;
+}
+
+/*
+==================
+BotChat_ExitGame
+==================
+*/
+int BotChat_ExitGame(bot_state_t *bs) {
+ char name[32];
+ float rnd;
+
+ if (bot_nochat.integer) return qfalse;
+ if (bs->lastchat_time > FloatTime() - TIME_BETWEENCHATTING) return qfalse;
+ //don't chat in teamplay
+ if (TeamPlayIsOn()) return qfalse;
+ // don't chat in tournament mode
+ if (gametype == GT_TOURNAMENT) return qfalse;
+ rnd = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_CHAT_ENTEREXITGAME, 0, 1);
+ if (!bot_fastchat.integer) {
+ if (random() > rnd) return qfalse;
+ }
+ if (BotNumActivePlayers() <= 1) return qfalse;
+ //
+ BotAI_BotInitialChat(bs, "game_exit",
+ EasyClientName(bs->client, name, 32), // 0
+ BotRandomOpponentName(bs), // 1
+ "[invalid var]", // 2
+ "[invalid var]", // 3
+ BotMapTitle(), // 4
+ NULL);
+ bs->lastchat_time = FloatTime();
+ bs->chatto = CHAT_ALL;
+ return qtrue;
+}
+
+/*
+==================
+BotChat_StartLevel
+==================
+*/
+int BotChat_StartLevel(bot_state_t *bs) {
+ char name[32];
+ float rnd;
+
+ if (bot_nochat.integer) return qfalse;
+ if (BotIsObserver(bs)) return qfalse;
+ if (bs->lastchat_time > FloatTime() - TIME_BETWEENCHATTING) return qfalse;
+ //don't chat in teamplay
+ if (TeamPlayIsOn()) {
+ trap_EA_Command(bs->client, "vtaunt");
+ return qfalse;
+ }
+ // don't chat in tournament mode
+ if (gametype == GT_TOURNAMENT) return qfalse;
+ rnd = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_CHAT_STARTENDLEVEL, 0, 1);
+ if (!bot_fastchat.integer) {
+ if (random() > rnd) return qfalse;
+ }
+ if (BotNumActivePlayers() <= 1) return qfalse;
+ BotAI_BotInitialChat(bs, "level_start",
+ EasyClientName(bs->client, name, 32), // 0
+ NULL);
+ bs->lastchat_time = FloatTime();
+ bs->chatto = CHAT_ALL;
+ return qtrue;
+}
+
+/*
+==================
+BotChat_EndLevel
+==================
+*/
+int BotChat_EndLevel(bot_state_t *bs) {
+ char name[32];
+ float rnd;
+
+ if (bot_nochat.integer) return qfalse;
+ if (BotIsObserver(bs)) return qfalse;
+ if (bs->lastchat_time > FloatTime() - TIME_BETWEENCHATTING) return qfalse;
+ // teamplay
+ if (TeamPlayIsOn())
+ {
+ if (BotIsFirstInRankings(bs)) {
+ trap_EA_Command(bs->client, "vtaunt");
+ }
+ return qtrue;
+ }
+ // don't chat in tournament mode
+ if (gametype == GT_TOURNAMENT) return qfalse;
+ rnd = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_CHAT_STARTENDLEVEL, 0, 1);
+ if (!bot_fastchat.integer) {
+ if (random() > rnd) return qfalse;
+ }
+ if (BotNumActivePlayers() <= 1) return qfalse;
+ //
+ if (BotIsFirstInRankings(bs)) {
+ BotAI_BotInitialChat(bs, "level_end_victory",
+ EasyClientName(bs->client, name, 32), // 0
+ BotRandomOpponentName(bs), // 1
+ "[invalid var]", // 2
+ BotLastClientInRankings(), // 3
+ BotMapTitle(), // 4
+ NULL);
+ }
+ else if (BotIsLastInRankings(bs)) {
+ BotAI_BotInitialChat(bs, "level_end_lose",
+ EasyClientName(bs->client, name, 32), // 0
+ BotRandomOpponentName(bs), // 1
+ BotFirstClientInRankings(), // 2
+ "[invalid var]", // 3
+ BotMapTitle(), // 4
+ NULL);
+ }
+ else {
+ BotAI_BotInitialChat(bs, "level_end",
+ EasyClientName(bs->client, name, 32), // 0
+ BotRandomOpponentName(bs), // 1
+ BotFirstClientInRankings(), // 2
+ BotLastClientInRankings(), // 3
+ BotMapTitle(), // 4
+ NULL);
+ }
+ bs->lastchat_time = FloatTime();
+ bs->chatto = CHAT_ALL;
+ return qtrue;
+}
+
+/*
+==================
+BotChat_Death
+==================
+*/
+int BotChat_Death(bot_state_t *bs) {
+ char name[32];
+ float rnd;
+
+ if (bot_nochat.integer) return qfalse;
+ if (bs->lastchat_time > FloatTime() - TIME_BETWEENCHATTING) return qfalse;
+ rnd = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_CHAT_DEATH, 0, 1);
+ // don't chat in tournament mode
+ if (gametype == GT_TOURNAMENT) return qfalse;
+ //if fast chatting is off
+ if (!bot_fastchat.integer) {
+ if (random() > rnd) return qfalse;
+ }
+ if (BotNumActivePlayers() <= 1) return qfalse;
+ //
+ if (bs->lastkilledby >= 0 && bs->lastkilledby < MAX_CLIENTS)
+ EasyClientName(bs->lastkilledby, name, 32);
+ else
+ strcpy(name, "[world]");
+ //
+ if (TeamPlayIsOn() && BotSameTeam(bs, bs->lastkilledby)) {
+ if (bs->lastkilledby == bs->client) return qfalse;
+ BotAI_BotInitialChat(bs, "death_teammate", name, NULL);
+ bs->chatto = CHAT_TEAM;
+ }
+ else
+ {
+ //teamplay
+ if (TeamPlayIsOn()) {
+ trap_EA_Command(bs->client, "vtaunt");
+ return qtrue;
+ }
+ //
+ if (bs->botdeathtype == MOD_WATER)
+ BotAI_BotInitialChat(bs, "death_drown", BotRandomOpponentName(bs), NULL);
+ else if (bs->botdeathtype == MOD_SLIME)
+ BotAI_BotInitialChat(bs, "death_slime", BotRandomOpponentName(bs), NULL);
+ else if (bs->botdeathtype == MOD_LAVA)
+ BotAI_BotInitialChat(bs, "death_lava", BotRandomOpponentName(bs), NULL);
+ else if (bs->botdeathtype == MOD_FALLING)
+ BotAI_BotInitialChat(bs, "death_cratered", BotRandomOpponentName(bs), NULL);
+ else if (bs->botsuicide || //all other suicides by own weapon
+ bs->botdeathtype == MOD_CRUSH ||
+ bs->botdeathtype == MOD_SUICIDE ||
+ bs->botdeathtype == MOD_TARGET_LASER ||
+ bs->botdeathtype == MOD_TRIGGER_HURT ||
+ bs->botdeathtype == MOD_UNKNOWN)
+ BotAI_BotInitialChat(bs, "death_suicide", BotRandomOpponentName(bs), NULL);
+ else if (bs->botdeathtype == MOD_TELEFRAG)
+ BotAI_BotInitialChat(bs, "death_telefrag", name, NULL);
+#ifdef MISSIONPACK
+ else if (bs->botdeathtype == MOD_KAMIKAZE && trap_BotNumInitialChats(bs->cs, "death_kamikaze"))
+ BotAI_BotInitialChat(bs, "death_kamikaze", name, NULL);
+#endif
+ else {
+ if ((bs->botdeathtype == MOD_GAUNTLET ||
+ bs->botdeathtype == MOD_RAILGUN ||
+ bs->botdeathtype == MOD_BFG ||
+ bs->botdeathtype == MOD_BFG_SPLASH) && random() < 0.5) {
+
+ if (bs->botdeathtype == MOD_GAUNTLET)
+ BotAI_BotInitialChat(bs, "death_gauntlet",
+ name, // 0
+ BotWeaponNameForMeansOfDeath(bs->botdeathtype), // 1
+ NULL);
+ else if (bs->botdeathtype == MOD_RAILGUN)
+ BotAI_BotInitialChat(bs, "death_rail",
+ name, // 0
+ BotWeaponNameForMeansOfDeath(bs->botdeathtype), // 1
+ NULL);
+ else
+ BotAI_BotInitialChat(bs, "death_bfg",
+ name, // 0
+ BotWeaponNameForMeansOfDeath(bs->botdeathtype), // 1
+ NULL);
+ }
+ //choose between insult and praise
+ else if (random() < trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_CHAT_INSULT, 0, 1)) {
+ BotAI_BotInitialChat(bs, "death_insult",
+ name, // 0
+ BotWeaponNameForMeansOfDeath(bs->botdeathtype), // 1
+ NULL);
+ }
+ else {
+ BotAI_BotInitialChat(bs, "death_praise",
+ name, // 0
+ BotWeaponNameForMeansOfDeath(bs->botdeathtype), // 1
+ NULL);
+ }
+ }
+ bs->chatto = CHAT_ALL;
+ }
+ bs->lastchat_time = FloatTime();
+ return qtrue;
+}
+
+/*
+==================
+BotChat_Kill
+==================
+*/
+int BotChat_Kill(bot_state_t *bs) {
+ char name[32];
+ float rnd;
+
+ if (bot_nochat.integer) return qfalse;
+ if (bs->lastchat_time > FloatTime() - TIME_BETWEENCHATTING) return qfalse;
+ rnd = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_CHAT_KILL, 0, 1);
+ // don't chat in tournament mode
+ if (gametype == GT_TOURNAMENT) return qfalse;
+ //if fast chat is off
+ if (!bot_fastchat.integer) {
+ if (random() > rnd) return qfalse;
+ }
+ if (bs->lastkilledplayer == bs->client) return qfalse;
+ if (BotNumActivePlayers() <= 1) return qfalse;
+ if (!BotValidChatPosition(bs)) return qfalse;
+ //
+ if (BotVisibleEnemies(bs)) return qfalse;
+ //
+ EasyClientName(bs->lastkilledplayer, name, 32);
+ //
+ bs->chatto = CHAT_ALL;
+ if (TeamPlayIsOn() && BotSameTeam(bs, bs->lastkilledplayer)) {
+ BotAI_BotInitialChat(bs, "kill_teammate", name, NULL);
+ bs->chatto = CHAT_TEAM;
+ }
+ else
+ {
+ //don't chat in teamplay
+ if (TeamPlayIsOn()) {
+ trap_EA_Command(bs->client, "vtaunt");
+ return qfalse; // don't wait
+ }
+ //
+ if (bs->enemydeathtype == MOD_GAUNTLET) {
+ BotAI_BotInitialChat(bs, "kill_gauntlet", name, NULL);
+ }
+ else if (bs->enemydeathtype == MOD_RAILGUN) {
+ BotAI_BotInitialChat(bs, "kill_rail", name, NULL);
+ }
+ else if (bs->enemydeathtype == MOD_TELEFRAG) {
+ BotAI_BotInitialChat(bs, "kill_telefrag", name, NULL);
+ }
+#ifdef MISSIONPACK
+ else if (bs->botdeathtype == MOD_KAMIKAZE && trap_BotNumInitialChats(bs->cs, "kill_kamikaze"))
+ BotAI_BotInitialChat(bs, "kill_kamikaze", name, NULL);
+#endif
+ //choose between insult and praise
+ else if (random() < trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_CHAT_INSULT, 0, 1)) {
+ BotAI_BotInitialChat(bs, "kill_insult", name, NULL);
+ }
+ else {
+ BotAI_BotInitialChat(bs, "kill_praise", name, NULL);
+ }
+ }
+ bs->lastchat_time = FloatTime();
+ return qtrue;
+}
+
+/*
+==================
+BotChat_EnemySuicide
+==================
+*/
+int BotChat_EnemySuicide(bot_state_t *bs) {
+ char name[32];
+ float rnd;
+
+ if (bot_nochat.integer) return qfalse;
+ if (bs->lastchat_time > FloatTime() - TIME_BETWEENCHATTING) return qfalse;
+ if (BotNumActivePlayers() <= 1) return qfalse;
+ //
+ rnd = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_CHAT_KILL, 0, 1);
+ //don't chat in teamplay
+ if (TeamPlayIsOn()) return qfalse;
+ // don't chat in tournament mode
+ if (gametype == GT_TOURNAMENT) return qfalse;
+ //if fast chat is off
+ if (!bot_fastchat.integer) {
+ if (random() > rnd) return qfalse;
+ }
+ if (!BotValidChatPosition(bs)) return qfalse;
+ //
+ if (BotVisibleEnemies(bs)) return qfalse;
+ //
+ if (bs->enemy >= 0) EasyClientName(bs->enemy, name, 32);
+ else strcpy(name, "");
+ BotAI_BotInitialChat(bs, "enemy_suicide", name, NULL);
+ bs->lastchat_time = FloatTime();
+ bs->chatto = CHAT_ALL;
+ return qtrue;
+}
+
+/*
+==================
+BotChat_HitTalking
+==================
+*/
+int BotChat_HitTalking(bot_state_t *bs) {
+ char name[32], *weap;
+ int lasthurt_client;
+ float rnd;
+
+ if (bot_nochat.integer) return qfalse;
+ if (bs->lastchat_time > FloatTime() - TIME_BETWEENCHATTING) return qfalse;
+ if (BotNumActivePlayers() <= 1) return qfalse;
+ lasthurt_client = g_entities[bs->client].client->lasthurt_client;
+ if (!lasthurt_client) return qfalse;
+ if (lasthurt_client == bs->client) return qfalse;
+ //
+ if (lasthurt_client < 0 || lasthurt_client >= MAX_CLIENTS) return qfalse;
+ //
+ rnd = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_CHAT_HITTALKING, 0, 1);
+ //don't chat in teamplay
+ if (TeamPlayIsOn()) return qfalse;
+ // don't chat in tournament mode
+ if (gametype == GT_TOURNAMENT) return qfalse;
+ //if fast chat is off
+ if (!bot_fastchat.integer) {
+ if (random() > rnd * 0.5) return qfalse;
+ }
+ if (!BotValidChatPosition(bs)) return qfalse;
+ //
+ ClientName(g_entities[bs->client].client->lasthurt_client, name, sizeof(name));
+ weap = BotWeaponNameForMeansOfDeath(g_entities[bs->client].client->lasthurt_client);
+ //
+ BotAI_BotInitialChat(bs, "hit_talking", name, weap, NULL);
+ bs->lastchat_time = FloatTime();
+ bs->chatto = CHAT_ALL;
+ return qtrue;
+}
+
+/*
+==================
+BotChat_HitNoDeath
+==================
+*/
+int BotChat_HitNoDeath(bot_state_t *bs) {
+ char name[32], *weap;
+ float rnd;
+ int lasthurt_client;
+ aas_entityinfo_t entinfo;
+
+ lasthurt_client = g_entities[bs->client].client->lasthurt_client;
+ if (!lasthurt_client) return qfalse;
+ if (lasthurt_client == bs->client) return qfalse;
+ //
+ if (lasthurt_client < 0 || lasthurt_client >= MAX_CLIENTS) return qfalse;
+ //
+ if (bot_nochat.integer) return qfalse;
+ if (bs->lastchat_time > FloatTime() - TIME_BETWEENCHATTING) return qfalse;
+ if (BotNumActivePlayers() <= 1) return qfalse;
+ rnd = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_CHAT_HITNODEATH, 0, 1);
+ //don't chat in teamplay
+ if (TeamPlayIsOn()) return qfalse;
+ // don't chat in tournament mode
+ if (gametype == GT_TOURNAMENT) return qfalse;
+ //if fast chat is off
+ if (!bot_fastchat.integer) {
+ if (random() > rnd * 0.5) return qfalse;
+ }
+ if (!BotValidChatPosition(bs)) return qfalse;
+ //
+ if (BotVisibleEnemies(bs)) return qfalse;
+ //
+ BotEntityInfo(bs->enemy, &entinfo);
+ if (EntityIsShooting(&entinfo)) return qfalse;
+ //
+ ClientName(lasthurt_client, name, sizeof(name));
+ weap = BotWeaponNameForMeansOfDeath(g_entities[bs->client].client->lasthurt_mod);
+ //
+ BotAI_BotInitialChat(bs, "hit_nodeath", name, weap, NULL);
+ bs->lastchat_time = FloatTime();
+ bs->chatto = CHAT_ALL;
+ return qtrue;
+}
+
+/*
+==================
+BotChat_HitNoKill
+==================
+*/
+int BotChat_HitNoKill(bot_state_t *bs) {
+ char name[32], *weap;
+ float rnd;
+ aas_entityinfo_t entinfo;
+
+ if (bot_nochat.integer) return qfalse;
+ if (bs->lastchat_time > FloatTime() - TIME_BETWEENCHATTING) return qfalse;
+ if (BotNumActivePlayers() <= 1) return qfalse;
+ rnd = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_CHAT_HITNOKILL, 0, 1);
+ //don't chat in teamplay
+ if (TeamPlayIsOn()) return qfalse;
+ // don't chat in tournament mode
+ if (gametype == GT_TOURNAMENT) return qfalse;
+ //if fast chat is off
+ if (!bot_fastchat.integer) {
+ if (random() > rnd * 0.5) return qfalse;
+ }
+ if (!BotValidChatPosition(bs)) return qfalse;
+ //
+ if (BotVisibleEnemies(bs)) return qfalse;
+ //
+ BotEntityInfo(bs->enemy, &entinfo);
+ if (EntityIsShooting(&entinfo)) return qfalse;
+ //
+ ClientName(bs->enemy, name, sizeof(name));
+ weap = BotWeaponNameForMeansOfDeath(g_entities[bs->enemy].client->lasthurt_mod);
+ //
+ BotAI_BotInitialChat(bs, "hit_nokill", name, weap, NULL);
+ bs->lastchat_time = FloatTime();
+ bs->chatto = CHAT_ALL;
+ return qtrue;
+}
+
+/*
+==================
+BotChat_Random
+==================
+*/
+int BotChat_Random(bot_state_t *bs) {
+ float rnd;
+ char name[32];
+
+ if (bot_nochat.integer) return qfalse;
+ if (BotIsObserver(bs)) return qfalse;
+ if (bs->lastchat_time > FloatTime() - TIME_BETWEENCHATTING) return qfalse;
+ // don't chat in tournament mode
+ if (gametype == GT_TOURNAMENT) return qfalse;
+ //don't chat when doing something important :)
+ if (bs->ltgtype == LTG_TEAMHELP ||
+ bs->ltgtype == LTG_TEAMACCOMPANY ||
+ bs->ltgtype == LTG_RUSHBASE) return qfalse;
+ //
+ rnd = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_CHAT_RANDOM, 0, 1);
+ if (random() > bs->thinktime * 0.1) return qfalse;
+ if (!bot_fastchat.integer) {
+ if (random() > rnd) return qfalse;
+ if (random() > 0.25) return qfalse;
+ }
+ if (BotNumActivePlayers() <= 1) return qfalse;
+ //
+ if (!BotValidChatPosition(bs)) return qfalse;
+ //
+ if (BotVisibleEnemies(bs)) return qfalse;
+ //
+ if (bs->lastkilledplayer == bs->client) {
+ strcpy(name, BotRandomOpponentName(bs));
+ }
+ else {
+ EasyClientName(bs->lastkilledplayer, name, sizeof(name));
+ }
+ if (TeamPlayIsOn()) {
+ trap_EA_Command(bs->client, "vtaunt");
+ return qfalse; // don't wait
+ }
+ //
+ if (random() < trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_CHAT_MISC, 0, 1)) {
+ BotAI_BotInitialChat(bs, "random_misc",
+ BotRandomOpponentName(bs), // 0
+ name, // 1
+ "[invalid var]", // 2
+ "[invalid var]", // 3
+ BotMapTitle(), // 4
+ BotRandomWeaponName(), // 5
+ NULL);
+ }
+ else {
+ BotAI_BotInitialChat(bs, "random_insult",
+ BotRandomOpponentName(bs), // 0
+ name, // 1
+ "[invalid var]", // 2
+ "[invalid var]", // 3
+ BotMapTitle(), // 4
+ BotRandomWeaponName(), // 5
+ NULL);
+ }
+ bs->lastchat_time = FloatTime();
+ bs->chatto = CHAT_ALL;
+ return qtrue;
+}
+
+/*
+==================
+BotChatTime
+==================
+*/
+float BotChatTime(bot_state_t *bs) {
+ int cpm;
+
+ cpm = trap_Characteristic_BInteger(bs->character, CHARACTERISTIC_CHAT_CPM, 1, 4000);
+
+ return 2.0; //(float) trap_BotChatLength(bs->cs) * 30 / cpm;
+}
+
+/*
+==================
+BotChatTest
+==================
+*/
+void BotChatTest(bot_state_t *bs) {
+
+ char name[32];
+ char *weap;
+ int num, i;
+
+ num = trap_BotNumInitialChats(bs->cs, "game_enter");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "game_enter",
+ EasyClientName(bs->client, name, 32), // 0
+ BotRandomOpponentName(bs), // 1
+ "[invalid var]", // 2
+ "[invalid var]", // 3
+ BotMapTitle(), // 4
+ NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ num = trap_BotNumInitialChats(bs->cs, "game_exit");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "game_exit",
+ EasyClientName(bs->client, name, 32), // 0
+ BotRandomOpponentName(bs), // 1
+ "[invalid var]", // 2
+ "[invalid var]", // 3
+ BotMapTitle(), // 4
+ NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ num = trap_BotNumInitialChats(bs->cs, "level_start");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "level_start",
+ EasyClientName(bs->client, name, 32), // 0
+ NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ num = trap_BotNumInitialChats(bs->cs, "level_end_victory");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "level_end_victory",
+ EasyClientName(bs->client, name, 32), // 0
+ BotRandomOpponentName(bs), // 1
+ BotFirstClientInRankings(), // 2
+ BotLastClientInRankings(), // 3
+ BotMapTitle(), // 4
+ NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ num = trap_BotNumInitialChats(bs->cs, "level_end_lose");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "level_end_lose",
+ EasyClientName(bs->client, name, 32), // 0
+ BotRandomOpponentName(bs), // 1
+ BotFirstClientInRankings(), // 2
+ BotLastClientInRankings(), // 3
+ BotMapTitle(), // 4
+ NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ num = trap_BotNumInitialChats(bs->cs, "level_end");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "level_end",
+ EasyClientName(bs->client, name, 32), // 0
+ BotRandomOpponentName(bs), // 1
+ BotFirstClientInRankings(), // 2
+ BotLastClientInRankings(), // 3
+ BotMapTitle(), // 4
+ NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ EasyClientName(bs->lastkilledby, name, sizeof(name));
+ num = trap_BotNumInitialChats(bs->cs, "death_drown");
+ for (i = 0; i < num; i++)
+ {
+ //
+ BotAI_BotInitialChat(bs, "death_drown", name, NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ num = trap_BotNumInitialChats(bs->cs, "death_slime");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "death_slime", name, NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ num = trap_BotNumInitialChats(bs->cs, "death_lava");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "death_lava", name, NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ num = trap_BotNumInitialChats(bs->cs, "death_cratered");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "death_cratered", name, NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ num = trap_BotNumInitialChats(bs->cs, "death_suicide");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "death_suicide", name, NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ num = trap_BotNumInitialChats(bs->cs, "death_telefrag");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "death_telefrag", name, NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ num = trap_BotNumInitialChats(bs->cs, "death_gauntlet");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "death_gauntlet",
+ name, // 0
+ BotWeaponNameForMeansOfDeath(bs->botdeathtype), // 1
+ NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ num = trap_BotNumInitialChats(bs->cs, "death_rail");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "death_rail",
+ name, // 0
+ BotWeaponNameForMeansOfDeath(bs->botdeathtype), // 1
+ NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ num = trap_BotNumInitialChats(bs->cs, "death_bfg");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "death_bfg",
+ name, // 0
+ BotWeaponNameForMeansOfDeath(bs->botdeathtype), // 1
+ NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ num = trap_BotNumInitialChats(bs->cs, "death_insult");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "death_insult",
+ name, // 0
+ BotWeaponNameForMeansOfDeath(bs->botdeathtype), // 1
+ NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ num = trap_BotNumInitialChats(bs->cs, "death_praise");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "death_praise",
+ name, // 0
+ BotWeaponNameForMeansOfDeath(bs->botdeathtype), // 1
+ NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ //
+ EasyClientName(bs->lastkilledplayer, name, 32);
+ //
+ num = trap_BotNumInitialChats(bs->cs, "kill_gauntlet");
+ for (i = 0; i < num; i++)
+ {
+ //
+ BotAI_BotInitialChat(bs, "kill_gauntlet", name, NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ num = trap_BotNumInitialChats(bs->cs, "kill_rail");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "kill_rail", name, NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ num = trap_BotNumInitialChats(bs->cs, "kill_telefrag");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "kill_telefrag", name, NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ num = trap_BotNumInitialChats(bs->cs, "kill_insult");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "kill_insult", name, NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ num = trap_BotNumInitialChats(bs->cs, "kill_praise");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "kill_praise", name, NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ num = trap_BotNumInitialChats(bs->cs, "enemy_suicide");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "enemy_suicide", name, NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ ClientName(g_entities[bs->client].client->lasthurt_client, name, sizeof(name));
+ weap = BotWeaponNameForMeansOfDeath(g_entities[bs->client].client->lasthurt_client);
+ num = trap_BotNumInitialChats(bs->cs, "hit_talking");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "hit_talking", name, weap, NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ num = trap_BotNumInitialChats(bs->cs, "hit_nodeath");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "hit_nodeath", name, weap, NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ num = trap_BotNumInitialChats(bs->cs, "hit_nokill");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "hit_nokill", name, weap, NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ //
+ if (bs->lastkilledplayer == bs->client) {
+ strcpy(name, BotRandomOpponentName(bs));
+ }
+ else {
+ EasyClientName(bs->lastkilledplayer, name, sizeof(name));
+ }
+ //
+ num = trap_BotNumInitialChats(bs->cs, "random_misc");
+ for (i = 0; i < num; i++)
+ {
+ //
+ BotAI_BotInitialChat(bs, "random_misc",
+ BotRandomOpponentName(bs), // 0
+ name, // 1
+ "[invalid var]", // 2
+ "[invalid var]", // 3
+ BotMapTitle(), // 4
+ BotRandomWeaponName(), // 5
+ NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+ num = trap_BotNumInitialChats(bs->cs, "random_insult");
+ for (i = 0; i < num; i++)
+ {
+ BotAI_BotInitialChat(bs, "random_insult",
+ BotRandomOpponentName(bs), // 0
+ name, // 1
+ "[invalid var]", // 2
+ "[invalid var]", // 3
+ BotMapTitle(), // 4
+ BotRandomWeaponName(), // 5
+ NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_ALL);
+ }
+}
diff --git a/code/game/ai_chat.h b/code/game/ai_chat.h
new file mode 100755
index 0000000..98711c4
--- /dev/null
+++ b/code/game/ai_chat.h
@@ -0,0 +1,61 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+/*****************************************************************************
+ * name: ai_chat.h
+ *
+ * desc: Quake3 bot AI
+ *
+ * $Archive: /source/code/botai/ai_chat.c $
+ *
+ *****************************************************************************/
+
+//
+int BotChat_EnterGame(bot_state_t *bs);
+//
+int BotChat_ExitGame(bot_state_t *bs);
+//
+int BotChat_StartLevel(bot_state_t *bs);
+//
+int BotChat_EndLevel(bot_state_t *bs);
+//
+int BotChat_HitTalking(bot_state_t *bs);
+//
+int BotChat_HitNoDeath(bot_state_t *bs);
+//
+int BotChat_HitNoKill(bot_state_t *bs);
+//
+int BotChat_Death(bot_state_t *bs);
+//
+int BotChat_Kill(bot_state_t *bs);
+//
+int BotChat_EnemySuicide(bot_state_t *bs);
+//
+int BotChat_Random(bot_state_t *bs);
+// time the selected chat takes to type in
+float BotChatTime(bot_state_t *bs);
+// returns true if the bot can chat at the current position
+int BotValidChatPosition(bot_state_t *bs);
+// test the initial bot chats
+void BotChatTest(bot_state_t *bs);
+
diff --git a/code/game/ai_cmd.c b/code/game/ai_cmd.c
new file mode 100755
index 0000000..802d7d8
--- /dev/null
+++ b/code/game/ai_cmd.c
@@ -0,0 +1,1992 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+/*****************************************************************************
+ * name: ai_cmd.c
+ *
+ * desc: Quake3 bot AI
+ *
+ * $Archive: /MissionPack/code/game/ai_cmd.c $
+ *
+ *****************************************************************************/
+
+#include "g_local.h"
+#include "botlib.h"
+#include "be_aas.h"
+#include "be_ea.h"
+#include "be_ai_char.h"
+#include "be_ai_chat.h"
+#include "be_ai_gen.h"
+#include "be_ai_goal.h"
+#include "be_ai_move.h"
+#include "be_ai_weap.h"
+//
+#include "ai_main.h"
+#include "ai_dmq3.h"
+#include "ai_chat.h"
+#include "ai_cmd.h"
+#include "ai_dmnet.h"
+#include "ai_team.h"
+//
+#include "chars.h" //characteristics
+#include "inv.h" //indexes into the inventory
+#include "syn.h" //synonyms
+#include "match.h" //string matching types and vars
+
+// for the voice chats
+#include "../../ui/menudef.h"
+
+int notleader[MAX_CLIENTS];
+
+#ifdef DEBUG
+/*
+==================
+BotPrintTeamGoal
+==================
+*/
+void BotPrintTeamGoal(bot_state_t *bs) {
+ char netname[MAX_NETNAME];
+ float t;
+
+ ClientName(bs->client, netname, sizeof(netname));
+ t = bs->teamgoal_time - FloatTime();
+ switch(bs->ltgtype) {
+ case LTG_TEAMHELP:
+ {
+ BotAI_Print(PRT_MESSAGE, "%s: I'm gonna help a team mate for %1.0f secs\n", netname, t);
+ break;
+ }
+ case LTG_TEAMACCOMPANY:
+ {
+ BotAI_Print(PRT_MESSAGE, "%s: I'm gonna accompany a team mate for %1.0f secs\n", netname, t);
+ break;
+ }
+ case LTG_GETFLAG:
+ {
+ BotAI_Print(PRT_MESSAGE, "%s: I'm gonna get the flag for %1.0f secs\n", netname, t);
+ break;
+ }
+ case LTG_RUSHBASE:
+ {
+ BotAI_Print(PRT_MESSAGE, "%s: I'm gonna rush to the base for %1.0f secs\n", netname, t);
+ break;
+ }
+ case LTG_RETURNFLAG:
+ {
+ BotAI_Print(PRT_MESSAGE, "%s: I'm gonna try to return the flag for %1.0f secs\n", netname, t);
+ break;
+ }
+#ifdef MISSIONPACK
+ case LTG_ATTACKENEMYBASE:
+ {
+ BotAI_Print(PRT_MESSAGE, "%s: I'm gonna attack the enemy base for %1.0f secs\n", netname, t);
+ break;
+ }
+ case LTG_HARVEST:
+ {
+ BotAI_Print(PRT_MESSAGE, "%s: I'm gonna harvest for %1.0f secs\n", netname, t);
+ break;
+ }
+#endif
+ case LTG_DEFENDKEYAREA:
+ {
+ BotAI_Print(PRT_MESSAGE, "%s: I'm gonna defend a key area for %1.0f secs\n", netname, t);
+ break;
+ }
+ case LTG_GETITEM:
+ {
+ BotAI_Print(PRT_MESSAGE, "%s: I'm gonna get an item for %1.0f secs\n", netname, t);
+ break;
+ }
+ case LTG_KILL:
+ {
+ BotAI_Print(PRT_MESSAGE, "%s: I'm gonna kill someone for %1.0f secs\n", netname, t);
+ break;
+ }
+ case LTG_CAMP:
+ case LTG_CAMPORDER:
+ {
+ BotAI_Print(PRT_MESSAGE, "%s: I'm gonna camp for %1.0f secs\n", netname, t);
+ break;
+ }
+ case LTG_PATROL:
+ {
+ BotAI_Print(PRT_MESSAGE, "%s: I'm gonna patrol for %1.0f secs\n", netname, t);
+ break;
+ }
+ default:
+ {
+ if (bs->ctfroam_time > FloatTime()) {
+ t = bs->ctfroam_time - FloatTime();
+ BotAI_Print(PRT_MESSAGE, "%s: I'm gonna roam for %1.0f secs\n", netname, t);
+ }
+ else {
+ BotAI_Print(PRT_MESSAGE, "%s: I've got a regular goal\n", netname);
+ }
+ }
+ }
+}
+#endif //DEBUG
+
+/*
+==================
+BotGetItemTeamGoal
+
+FIXME: add stuff like "upper rocket launcher"
+"the rl near the railgun", "lower grenade launcher" etc.
+==================
+*/
+int BotGetItemTeamGoal(char *goalname, bot_goal_t *goal) {
+ int i;
+
+ if (!strlen(goalname)) return qfalse;
+ i = -1;
+ do {
+ i = trap_BotGetLevelItemGoal(i, goalname, goal);
+ if (i > 0) {
+ //do NOT defend dropped items
+ if (goal->flags & GFL_DROPPED)
+ continue;
+ return qtrue;
+ }
+ } while(i > 0);
+ return qfalse;
+}
+
+/*
+==================
+BotGetMessageTeamGoal
+==================
+*/
+int BotGetMessageTeamGoal(bot_state_t *bs, char *goalname, bot_goal_t *goal) {
+ bot_waypoint_t *cp;
+
+ if (BotGetItemTeamGoal(goalname, goal)) return qtrue;
+
+ cp = BotFindWayPoint(bs->checkpoints, goalname);
+ if (cp) {
+ memcpy(goal, &cp->goal, sizeof(bot_goal_t));
+ return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+==================
+BotGetTime
+==================
+*/
+float BotGetTime(bot_match_t *match) {
+ bot_match_t timematch;
+ char timestring[MAX_MESSAGE_SIZE];
+ float t;
+
+ //if the matched string has a time
+ if (match->subtype & ST_TIME) {
+ //get the time string
+ trap_BotMatchVariable(match, TIME, timestring, MAX_MESSAGE_SIZE);
+ //match it to find out if the time is in seconds or minutes
+ if (trap_BotFindMatch(timestring, &timematch, MTCONTEXT_TIME)) {
+ if (timematch.type == MSG_FOREVER) {
+ t = 99999999.0f;
+ }
+ else if (timematch.type == MSG_FORAWHILE) {
+ t = 10 * 60; // 10 minutes
+ }
+ else if (timematch.type == MSG_FORALONGTIME) {
+ t = 30 * 60; // 30 minutes
+ }
+ else {
+ trap_BotMatchVariable(&timematch, TIME, timestring, MAX_MESSAGE_SIZE);
+ if (timematch.type == MSG_MINUTES) t = atof(timestring) * 60;
+ else if (timematch.type == MSG_SECONDS) t = atof(timestring);
+ else t = 0;
+ }
+ //if there's a valid time
+ if (t > 0) return FloatTime() + t;
+ }
+ }
+ return 0;
+}
+
+/*
+==================
+FindClientByName
+==================
+*/
+int FindClientByName(char *name) {
+ int i;
+ char buf[MAX_INFO_STRING];
+ static int maxclients;
+
+ if (!maxclients)
+ maxclients = trap_Cvar_VariableIntegerValue("sv_maxclients");
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ ClientName(i, buf, sizeof(buf));
+ if (!Q_stricmp(buf, name)) return i;
+ }
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ ClientName(i, buf, sizeof(buf));
+ if (stristr(buf, name)) return i;
+ }
+ return -1;
+}
+
+/*
+==================
+FindEnemyByName
+==================
+*/
+int FindEnemyByName(bot_state_t *bs, char *name) {
+ int i;
+ char buf[MAX_INFO_STRING];
+ static int maxclients;
+
+ if (!maxclients)
+ maxclients = trap_Cvar_VariableIntegerValue("sv_maxclients");
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ if (BotSameTeam(bs, i)) continue;
+ ClientName(i, buf, sizeof(buf));
+ if (!Q_stricmp(buf, name)) return i;
+ }
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ if (BotSameTeam(bs, i)) continue;
+ ClientName(i, buf, sizeof(buf));
+ if (stristr(buf, name)) return i;
+ }
+ return -1;
+}
+
+/*
+==================
+NumPlayersOnSameTeam
+==================
+*/
+int NumPlayersOnSameTeam(bot_state_t *bs) {
+ int i, num;
+ char buf[MAX_INFO_STRING];
+ static int maxclients;
+
+ if (!maxclients)
+ maxclients = trap_Cvar_VariableIntegerValue("sv_maxclients");
+
+ num = 0;
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ trap_GetConfigstring(CS_PLAYERS+i, buf, MAX_INFO_STRING);
+ if (strlen(buf)) {
+ if (BotSameTeam(bs, i+1)) num++;
+ }
+ }
+ return num;
+}
+
+/*
+==================
+TeamPlayIsOn
+==================
+*/
+int BotGetPatrolWaypoints(bot_state_t *bs, bot_match_t *match) {
+ char keyarea[MAX_MESSAGE_SIZE];
+ int patrolflags;
+ bot_waypoint_t *wp, *newwp, *newpatrolpoints;
+ bot_match_t keyareamatch;
+ bot_goal_t goal;
+
+ newpatrolpoints = NULL;
+ patrolflags = 0;
+ //
+ trap_BotMatchVariable(match, KEYAREA, keyarea, MAX_MESSAGE_SIZE);
+ //
+ while(1) {
+ if (!trap_BotFindMatch(keyarea, &keyareamatch, MTCONTEXT_PATROLKEYAREA)) {
+ trap_EA_SayTeam(bs->client, "what do you say?");
+ BotFreeWaypoints(newpatrolpoints);
+ bs->patrolpoints = NULL;
+ return qfalse;
+ }
+ trap_BotMatchVariable(&keyareamatch, KEYAREA, keyarea, MAX_MESSAGE_SIZE);
+ if (!BotGetMessageTeamGoal(bs, keyarea, &goal)) {
+ //BotAI_BotInitialChat(bs, "cannotfind", keyarea, NULL);
+ //trap_BotEnterChat(bs->cs, 0, CHAT_TEAM);
+ BotFreeWaypoints(newpatrolpoints);
+ bs->patrolpoints = NULL;
+ return qfalse;
+ }
+ //create a new waypoint
+ newwp = BotCreateWayPoint(keyarea, goal.origin, goal.areanum);
+ if (!newwp)
+ break;
+ //add the waypoint to the patrol points
+ newwp->next = NULL;
+ for (wp = newpatrolpoints; wp && wp->next; wp = wp->next);
+ if (!wp) {
+ newpatrolpoints = newwp;
+ newwp->prev = NULL;
+ }
+ else {
+ wp->next = newwp;
+ newwp->prev = wp;
+ }
+ //
+ if (keyareamatch.subtype & ST_BACK) {
+ patrolflags = PATROL_LOOP;
+ break;
+ }
+ else if (keyareamatch.subtype & ST_REVERSE) {
+ patrolflags = PATROL_REVERSE;
+ break;
+ }
+ else if (keyareamatch.subtype & ST_MORE) {
+ trap_BotMatchVariable(&keyareamatch, MORE, keyarea, MAX_MESSAGE_SIZE);
+ }
+ else {
+ break;
+ }
+ }
+ //
+ if (!newpatrolpoints || !newpatrolpoints->next) {
+ trap_EA_SayTeam(bs->client, "I need more key points to patrol\n");
+ BotFreeWaypoints(newpatrolpoints);
+ newpatrolpoints = NULL;
+ return qfalse;
+ }
+ //
+ BotFreeWaypoints(bs->patrolpoints);
+ bs->patrolpoints = newpatrolpoints;
+ //
+ bs->curpatrolpoint = bs->patrolpoints;
+ bs->patrolflags = patrolflags;
+ //
+ return qtrue;
+}
+
+/*
+==================
+BotAddressedToBot
+==================
+*/
+int BotAddressedToBot(bot_state_t *bs, bot_match_t *match) {
+ char addressedto[MAX_MESSAGE_SIZE];
+ char netname[MAX_MESSAGE_SIZE];
+ char name[MAX_MESSAGE_SIZE];
+ char botname[128];
+ int client;
+ bot_match_t addresseematch;
+
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ client = ClientOnSameTeamFromName(bs, netname);
+ if (client < 0) return qfalse;
+ //if the message is addressed to someone
+ if (match->subtype & ST_ADDRESSED) {
+ trap_BotMatchVariable(match, ADDRESSEE, addressedto, sizeof(addressedto));
+ //the name of this bot
+ ClientName(bs->client, botname, 128);
+ //
+ while(trap_BotFindMatch(addressedto, &addresseematch, MTCONTEXT_ADDRESSEE)) {
+ if (addresseematch.type == MSG_EVERYONE) {
+ return qtrue;
+ }
+ else if (addresseematch.type == MSG_MULTIPLENAMES) {
+ trap_BotMatchVariable(&addresseematch, TEAMMATE, name, sizeof(name));
+ if (strlen(name)) {
+ if (stristr(botname, name)) return qtrue;
+ if (stristr(bs->subteam, name)) return qtrue;
+ }
+ trap_BotMatchVariable(&addresseematch, MORE, addressedto, MAX_MESSAGE_SIZE);
+ }
+ else {
+ trap_BotMatchVariable(&addresseematch, TEAMMATE, name, MAX_MESSAGE_SIZE);
+ if (strlen(name)) {
+ if (stristr(botname, name)) return qtrue;
+ if (stristr(bs->subteam, name)) return qtrue;
+ }
+ break;
+ }
+ }
+ //Com_sprintf(buf, sizeof(buf), "not addressed to me but %s", addressedto);
+ //trap_EA_Say(bs->client, buf);
+ return qfalse;
+ }
+ else {
+ bot_match_t tellmatch;
+
+ tellmatch.type = 0;
+ //if this message wasn't directed solely to this bot
+ if (!trap_BotFindMatch(match->string, &tellmatch, MTCONTEXT_REPLYCHAT) ||
+ tellmatch.type != MSG_CHATTELL) {
+ //make sure not everyone reacts to this message
+ if (random() > (float ) 1.0 / (NumPlayersOnSameTeam(bs)-1)) return qfalse;
+ }
+ }
+ return qtrue;
+}
+
+/*
+==================
+BotGPSToPosition
+==================
+*/
+int BotGPSToPosition(char *buf, vec3_t position) {
+ int i, j = 0;
+ int num, sign;
+
+ for (i = 0; i < 3; i++) {
+ num = 0;
+ while(buf[j] == ' ') j++;
+ if (buf[j] == '-') {
+ j++;
+ sign = -1;
+ }
+ else {
+ sign = 1;
+ }
+ while (buf[j]) {
+ if (buf[j] >= '0' && buf[j] <= '9') {
+ num = num * 10 + buf[j] - '0';
+ j++;
+ }
+ else {
+ j++;
+ break;
+ }
+ }
+ BotAI_Print(PRT_MESSAGE, "%d\n", sign * num);
+ position[i] = (float) sign * num;
+ }
+ return qtrue;
+}
+
+/*
+==================
+BotMatch_HelpAccompany
+==================
+*/
+void BotMatch_HelpAccompany(bot_state_t *bs, bot_match_t *match) {
+ int client, other, areanum;
+ char teammate[MAX_MESSAGE_SIZE];
+ char netname[MAX_MESSAGE_SIZE];
+ char itemname[MAX_MESSAGE_SIZE];
+ bot_match_t teammatematch;
+ aas_entityinfo_t entinfo;
+
+ if (!TeamPlayIsOn()) return;
+ //if not addressed to this bot
+ if (!BotAddressedToBot(bs, match)) return;
+ //get the team mate name
+ trap_BotMatchVariable(match, TEAMMATE, teammate, sizeof(teammate));
+ //get the client to help
+ if (trap_BotFindMatch(teammate, &teammatematch, MTCONTEXT_TEAMMATE) &&
+ //if someone asks for him or herself
+ teammatematch.type == MSG_ME) {
+ //get the netname
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ client = ClientFromName(netname);
+ other = qfalse;
+ }
+ else {
+ //asked for someone else
+ client = FindClientByName(teammate);
+ //if this is the bot self
+ if (client == bs->client) {
+ other = qfalse;
+ }
+ else if (!BotSameTeam(bs, client)) {
+ //FIXME: say "I don't help the enemy"
+ return;
+ }
+ else {
+ other = qtrue;
+ }
+ }
+ //if the bot doesn't know who to help (FindClientByName returned -1)
+ if (client < 0) {
+ if (other) BotAI_BotInitialChat(bs, "whois", teammate, NULL);
+ else BotAI_BotInitialChat(bs, "whois", netname, NULL);
+ client = ClientFromName(netname);
+ trap_BotEnterChat(bs->cs, client, CHAT_TELL);
+ return;
+ }
+ //don't help or accompany yourself
+ if (client == bs->client) {
+ return;
+ }
+ //
+ bs->teamgoal.entitynum = -1;
+ BotEntityInfo(client, &entinfo);
+ //if info is valid (in PVS)
+ if (entinfo.valid) {
+ areanum = BotPointAreaNum(entinfo.origin);
+ if (areanum) {// && trap_AAS_AreaReachability(areanum)) {
+ bs->teamgoal.entitynum = client;
+ bs->teamgoal.areanum = areanum;
+ VectorCopy(entinfo.origin, bs->teamgoal.origin);
+ VectorSet(bs->teamgoal.mins, -8, -8, -8);
+ VectorSet(bs->teamgoal.maxs, 8, 8, 8);
+ }
+ }
+ //if no teamgoal yet
+ if (bs->teamgoal.entitynum < 0) {
+ //if near an item
+ if (match->subtype & ST_NEARITEM) {
+ //get the match variable
+ trap_BotMatchVariable(match, ITEM, itemname, sizeof(itemname));
+ //
+ if (!BotGetMessageTeamGoal(bs, itemname, &bs->teamgoal)) {
+ //BotAI_BotInitialChat(bs, "cannotfind", itemname, NULL);
+ //trap_BotEnterChat(bs->cs, bs->client, CHAT_TEAM);
+ return;
+ }
+ }
+ }
+ //
+ if (bs->teamgoal.entitynum < 0) {
+ if (other) BotAI_BotInitialChat(bs, "whereis", teammate, NULL);
+ else BotAI_BotInitialChat(bs, "whereareyou", netname, NULL);
+ client = ClientFromName(netname);
+ trap_BotEnterChat(bs->cs, client, CHAT_TEAM);
+ return;
+ }
+ //the team mate
+ bs->teammate = client;
+ //
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ //
+ client = ClientFromName(netname);
+ //the team mate who ordered
+ bs->decisionmaker = client;
+ bs->ordered = qtrue;
+ bs->order_time = FloatTime();
+ //last time the team mate was assumed visible
+ bs->teammatevisible_time = FloatTime();
+ //set the time to send a message to the team mates
+ bs->teammessage_time = FloatTime() + 2 * random();
+ //get the team goal time
+ bs->teamgoal_time = BotGetTime(match);
+ //set the ltg type
+ if (match->type == MSG_HELP) {
+ bs->ltgtype = LTG_TEAMHELP;
+ if (!bs->teamgoal_time) bs->teamgoal_time = FloatTime() + TEAM_HELP_TIME;
+ }
+ else {
+ bs->ltgtype = LTG_TEAMACCOMPANY;
+ if (!bs->teamgoal_time) bs->teamgoal_time = FloatTime() + TEAM_ACCOMPANY_TIME;
+ bs->formation_dist = 3.5 * 32; //3.5 meter
+ bs->arrive_time = 0;
+ //
+ BotSetTeamStatus(bs);
+ // remember last ordered task
+ BotRememberLastOrderedTask(bs);
+ }
+#ifdef DEBUG
+ BotPrintTeamGoal(bs);
+#endif //DEBUG
+}
+
+/*
+==================
+BotMatch_DefendKeyArea
+==================
+*/
+void BotMatch_DefendKeyArea(bot_state_t *bs, bot_match_t *match) {
+ char itemname[MAX_MESSAGE_SIZE];
+ char netname[MAX_MESSAGE_SIZE];
+ int client;
+
+ if (!TeamPlayIsOn()) return;
+ //if not addressed to this bot
+ if (!BotAddressedToBot(bs, match)) return;
+ //get the match variable
+ trap_BotMatchVariable(match, KEYAREA, itemname, sizeof(itemname));
+ //
+ if (!BotGetMessageTeamGoal(bs, itemname, &bs->teamgoal)) {
+ //BotAI_BotInitialChat(bs, "cannotfind", itemname, NULL);
+ //trap_BotEnterChat(bs->cs, bs->client, CHAT_TEAM);
+ return;
+ }
+ //
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ //
+ client = ClientFromName(netname);
+ //the team mate who ordered
+ bs->decisionmaker = client;
+ bs->ordered = qtrue;
+ bs->order_time = FloatTime();
+ //set the time to send a message to the team mates
+ bs->teammessage_time = FloatTime() + 2 * random();
+ //set the ltg type
+ bs->ltgtype = LTG_DEFENDKEYAREA;
+ //get the team goal time
+ bs->teamgoal_time = BotGetTime(match);
+ //set the team goal time
+ if (!bs->teamgoal_time) bs->teamgoal_time = FloatTime() + TEAM_DEFENDKEYAREA_TIME;
+ //away from defending
+ bs->defendaway_time = 0;
+ //
+ BotSetTeamStatus(bs);
+ // remember last ordered task
+ BotRememberLastOrderedTask(bs);
+#ifdef DEBUG
+ BotPrintTeamGoal(bs);
+#endif //DEBUG
+}
+
+/*
+==================
+BotMatch_GetItem
+==================
+*/
+void BotMatch_GetItem(bot_state_t *bs, bot_match_t *match) {
+ char itemname[MAX_MESSAGE_SIZE];
+ char netname[MAX_MESSAGE_SIZE];
+ int client;
+
+ if (!TeamPlayIsOn()) return;
+ //if not addressed to this bot
+ if (!BotAddressedToBot(bs, match)) return;
+ //get the match variable
+ trap_BotMatchVariable(match, ITEM, itemname, sizeof(itemname));
+ //
+ if (!BotGetMessageTeamGoal(bs, itemname, &bs->teamgoal)) {
+ //BotAI_BotInitialChat(bs, "cannotfind", itemname, NULL);
+ //trap_BotEnterChat(bs->cs, bs->client, CHAT_TEAM);
+ return;
+ }
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ client = ClientOnSameTeamFromName(bs, netname);
+ //
+ bs->decisionmaker = client;
+ bs->ordered = qtrue;
+ bs->order_time = FloatTime();
+ //set the time to send a message to the team mates
+ bs->teammessage_time = FloatTime() + 2 * random();
+ //set the ltg type
+ bs->ltgtype = LTG_GETITEM;
+ //set the team goal time
+ bs->teamgoal_time = FloatTime() + TEAM_GETITEM_TIME;
+ //
+ BotSetTeamStatus(bs);
+#ifdef DEBUG
+ BotPrintTeamGoal(bs);
+#endif //DEBUG
+}
+
+/*
+==================
+BotMatch_Camp
+==================
+*/
+void BotMatch_Camp(bot_state_t *bs, bot_match_t *match) {
+ int client, areanum;
+ char netname[MAX_MESSAGE_SIZE];
+ char itemname[MAX_MESSAGE_SIZE];
+ aas_entityinfo_t entinfo;
+
+ if (!TeamPlayIsOn()) return;
+ //if not addressed to this bot
+ if (!BotAddressedToBot(bs, match)) return;
+ //
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ //asked for someone else
+ client = FindClientByName(netname);
+ //if there's no valid client with this name
+ if (client < 0) {
+ BotAI_BotInitialChat(bs, "whois", netname, NULL);
+ trap_BotEnterChat(bs->cs, bs->client, CHAT_TEAM);
+ return;
+ }
+ //get the match variable
+ trap_BotMatchVariable(match, KEYAREA, itemname, sizeof(itemname));
+ //in CTF it could be the base
+ if (match->subtype & ST_THERE) {
+ //camp at the spot the bot is currently standing
+ bs->teamgoal.entitynum = bs->entitynum;
+ bs->teamgoal.areanum = bs->areanum;
+ VectorCopy(bs->origin, bs->teamgoal.origin);
+ VectorSet(bs->teamgoal.mins, -8, -8, -8);
+ VectorSet(bs->teamgoal.maxs, 8, 8, 8);
+ }
+ else if (match->subtype & ST_HERE) {
+ //if this is the bot self
+ if (client == bs->client) return;
+ //
+ bs->teamgoal.entitynum = -1;
+ BotEntityInfo(client, &entinfo);
+ //if info is valid (in PVS)
+ if (entinfo.valid) {
+ areanum = BotPointAreaNum(entinfo.origin);
+ if (areanum) {// && trap_AAS_AreaReachability(areanum)) {
+ //NOTE: just assume the bot knows where the person is
+ //if (BotEntityVisible(bs->entitynum, bs->eye, bs->viewangles, 360, client)) {
+ bs->teamgoal.entitynum = client;
+ bs->teamgoal.areanum = areanum;
+ VectorCopy(entinfo.origin, bs->teamgoal.origin);
+ VectorSet(bs->teamgoal.mins, -8, -8, -8);
+ VectorSet(bs->teamgoal.maxs, 8, 8, 8);
+ //}
+ }
+ }
+ //if the other is not visible
+ if (bs->teamgoal.entitynum < 0) {
+ BotAI_BotInitialChat(bs, "whereareyou", netname, NULL);
+ client = ClientFromName(netname);
+ trap_BotEnterChat(bs->cs, client, CHAT_TELL);
+ return;
+ }
+ }
+ else if (!BotGetMessageTeamGoal(bs, itemname, &bs->teamgoal)) {
+ //BotAI_BotInitialChat(bs, "cannotfind", itemname, NULL);
+ //client = ClientFromName(netname);
+ //trap_BotEnterChat(bs->cs, client, CHAT_TELL);
+ return;
+ }
+ //
+ bs->decisionmaker = client;
+ bs->ordered = qtrue;
+ bs->order_time = FloatTime();
+ //set the time to send a message to the team mates
+ bs->teammessage_time = FloatTime() + 2 * random();
+ //set the ltg type
+ bs->ltgtype = LTG_CAMPORDER;
+ //get the team goal time
+ bs->teamgoal_time = BotGetTime(match);
+ //set the team goal time
+ if (!bs->teamgoal_time) bs->teamgoal_time = FloatTime() + TEAM_CAMP_TIME;
+ //not arrived yet
+ bs->arrive_time = 0;
+ //
+ BotSetTeamStatus(bs);
+ // remember last ordered task
+ BotRememberLastOrderedTask(bs);
+#ifdef DEBUG
+ BotPrintTeamGoal(bs);
+#endif //DEBUG
+}
+
+/*
+==================
+BotMatch_Patrol
+==================
+*/
+void BotMatch_Patrol(bot_state_t *bs, bot_match_t *match) {
+ char netname[MAX_MESSAGE_SIZE];
+ int client;
+
+ if (!TeamPlayIsOn()) return;
+ //if not addressed to this bot
+ if (!BotAddressedToBot(bs, match)) return;
+ //get the patrol waypoints
+ if (!BotGetPatrolWaypoints(bs, match)) return;
+ //
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ //
+ client = FindClientByName(netname);
+ //
+ bs->decisionmaker = client;
+ bs->ordered = qtrue;
+ bs->order_time = FloatTime();
+ //set the time to send a message to the team mates
+ bs->teammessage_time = FloatTime() + 2 * random();
+ //set the ltg type
+ bs->ltgtype = LTG_PATROL;
+ //get the team goal time
+ bs->teamgoal_time = BotGetTime(match);
+ //set the team goal time if not set already
+ if (!bs->teamgoal_time) bs->teamgoal_time = FloatTime() + TEAM_PATROL_TIME;
+ //
+ BotSetTeamStatus(bs);
+ // remember last ordered task
+ BotRememberLastOrderedTask(bs);
+#ifdef DEBUG
+ BotPrintTeamGoal(bs);
+#endif //DEBUG
+}
+
+/*
+==================
+BotMatch_GetFlag
+==================
+*/
+void BotMatch_GetFlag(bot_state_t *bs, bot_match_t *match) {
+ char netname[MAX_MESSAGE_SIZE];
+ int client;
+
+ if (gametype == GT_CTF) {
+ if (!ctf_redflag.areanum || !ctf_blueflag.areanum)
+ return;
+ }
+#ifdef MISSIONPACK
+ else if (gametype == GT_1FCTF) {
+ if (!ctf_neutralflag.areanum || !ctf_redflag.areanum || !ctf_blueflag.areanum)
+ return;
+ }
+#endif
+ else {
+ return;
+ }
+ //if not addressed to this bot
+ if (!BotAddressedToBot(bs, match)) return;
+ //
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ //
+ client = FindClientByName(netname);
+ //
+ bs->decisionmaker = client;
+ bs->ordered = qtrue;
+ bs->order_time = FloatTime();
+ //set the time to send a message to the team mates
+ bs->teammessage_time = FloatTime() + 2 * random();
+ //set the ltg type
+ bs->ltgtype = LTG_GETFLAG;
+ //set the team goal time
+ bs->teamgoal_time = FloatTime() + CTF_GETFLAG_TIME;
+ // get an alternate route in ctf
+ if (gametype == GT_CTF) {
+ //get an alternative route goal towards the enemy base
+ BotGetAlternateRouteGoal(bs, BotOppositeTeam(bs));
+ }
+ //
+ BotSetTeamStatus(bs);
+ // remember last ordered task
+ BotRememberLastOrderedTask(bs);
+#ifdef DEBUG
+ BotPrintTeamGoal(bs);
+#endif //DEBUG
+}
+
+/*
+==================
+BotMatch_AttackEnemyBase
+==================
+*/
+void BotMatch_AttackEnemyBase(bot_state_t *bs, bot_match_t *match) {
+ char netname[MAX_MESSAGE_SIZE];
+ int client;
+
+ if (gametype == GT_CTF) {
+ BotMatch_GetFlag(bs, match);
+ }
+#ifdef MISSIONPACK
+ else if (gametype == GT_1FCTF || gametype == GT_OBELISK || gametype == GT_HARVESTER) {
+ if (!redobelisk.areanum || !blueobelisk.areanum)
+ return;
+ }
+#endif
+ else {
+ return;
+ }
+ //if not addressed to this bot
+ if (!BotAddressedToBot(bs, match)) return;
+ //
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ //
+ client = FindClientByName(netname);
+ //
+ bs->decisionmaker = client;
+ bs->ordered = qtrue;
+ bs->order_time = FloatTime();
+ //set the time to send a message to the team mates
+ bs->teammessage_time = FloatTime() + 2 * random();
+ //set the ltg type
+ bs->ltgtype = LTG_ATTACKENEMYBASE;
+ //set the team goal time
+ bs->teamgoal_time = FloatTime() + TEAM_ATTACKENEMYBASE_TIME;
+ bs->attackaway_time = 0;
+ //
+ BotSetTeamStatus(bs);
+ // remember last ordered task
+ BotRememberLastOrderedTask(bs);
+#ifdef DEBUG
+ BotPrintTeamGoal(bs);
+#endif //DEBUG
+}
+
+#ifdef MISSIONPACK
+/*
+==================
+BotMatch_Harvest
+==================
+*/
+void BotMatch_Harvest(bot_state_t *bs, bot_match_t *match) {
+ char netname[MAX_MESSAGE_SIZE];
+ int client;
+
+ if (gametype == GT_HARVESTER) {
+ if (!neutralobelisk.areanum || !redobelisk.areanum || !blueobelisk.areanum)
+ return;
+ }
+ else {
+ return;
+ }
+ //if not addressed to this bot
+ if (!BotAddressedToBot(bs, match)) return;
+ //
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ //
+ client = FindClientByName(netname);
+ //
+ bs->decisionmaker = client;
+ bs->ordered = qtrue;
+ bs->order_time = FloatTime();
+ //set the time to send a message to the team mates
+ bs->teammessage_time = FloatTime() + 2 * random();
+ //set the ltg type
+ bs->ltgtype = LTG_HARVEST;
+ //set the team goal time
+ bs->teamgoal_time = FloatTime() + TEAM_HARVEST_TIME;
+ bs->harvestaway_time = 0;
+ //
+ BotSetTeamStatus(bs);
+ // remember last ordered task
+ BotRememberLastOrderedTask(bs);
+#ifdef DEBUG
+ BotPrintTeamGoal(bs);
+#endif //DEBUG
+}
+#endif
+
+/*
+==================
+BotMatch_RushBase
+==================
+*/
+void BotMatch_RushBase(bot_state_t *bs, bot_match_t *match) {
+ char netname[MAX_MESSAGE_SIZE];
+ int client;
+
+ if (gametype == GT_CTF) {
+ if (!ctf_redflag.areanum || !ctf_blueflag.areanum)
+ return;
+ }
+#ifdef MISSIONPACK
+ else if (gametype == GT_1FCTF || gametype == GT_HARVESTER) {
+ if (!redobelisk.areanum || !blueobelisk.areanum)
+ return;
+ }
+#endif
+ else {
+ return;
+ }
+ //if not addressed to this bot
+ if (!BotAddressedToBot(bs, match)) return;
+ //
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ //
+ client = FindClientByName(netname);
+ //
+ bs->decisionmaker = client;
+ bs->ordered = qtrue;
+ bs->order_time = FloatTime();
+ //set the time to send a message to the team mates
+ bs->teammessage_time = FloatTime() + 2 * random();
+ //set the ltg type
+ bs->ltgtype = LTG_RUSHBASE;
+ //set the team goal time
+ bs->teamgoal_time = FloatTime() + CTF_RUSHBASE_TIME;
+ bs->rushbaseaway_time = 0;
+ //
+ BotSetTeamStatus(bs);
+#ifdef DEBUG
+ BotPrintTeamGoal(bs);
+#endif //DEBUG
+}
+
+/*
+==================
+BotMatch_TaskPreference
+==================
+*/
+void BotMatch_TaskPreference(bot_state_t *bs, bot_match_t *match) {
+ char netname[MAX_NETNAME];
+ char teammatename[MAX_MESSAGE_SIZE];
+ int teammate, preference;
+
+ ClientName(bs->client, netname, sizeof(netname));
+ if (Q_stricmp(netname, bs->teamleader) != 0) return;
+
+ trap_BotMatchVariable(match, NETNAME, teammatename, sizeof(teammatename));
+ teammate = ClientFromName(teammatename);
+ if (teammate < 0) return;
+
+ preference = BotGetTeamMateTaskPreference(bs, teammate);
+ switch(match->subtype)
+ {
+ case ST_DEFENDER:
+ {
+ preference &= ~TEAMTP_ATTACKER;
+ preference |= TEAMTP_DEFENDER;
+ break;
+ }
+ case ST_ATTACKER:
+ {
+ preference &= ~TEAMTP_DEFENDER;
+ preference |= TEAMTP_ATTACKER;
+ break;
+ }
+ case ST_ROAMER:
+ {
+ preference &= ~(TEAMTP_ATTACKER|TEAMTP_DEFENDER);
+ break;
+ }
+ }
+ BotSetTeamMateTaskPreference(bs, teammate, preference);
+ //
+ EasyClientName(teammate, teammatename, sizeof(teammatename));
+ BotAI_BotInitialChat(bs, "keepinmind", teammatename, NULL);
+ trap_BotEnterChat(bs->cs, teammate, CHAT_TELL);
+ BotVoiceChatOnly(bs, teammate, VOICECHAT_YES);
+ trap_EA_Action(bs->client, ACTION_AFFIRMATIVE);
+}
+
+/*
+==================
+BotMatch_ReturnFlag
+==================
+*/
+void BotMatch_ReturnFlag(bot_state_t *bs, bot_match_t *match) {
+ char netname[MAX_MESSAGE_SIZE];
+ int client;
+
+ //if not in CTF mode
+ if (
+ gametype != GT_CTF
+#ifdef MISSIONPACK
+ && gametype != GT_1FCTF
+#endif
+ )
+ return;
+ //if not addressed to this bot
+ if (!BotAddressedToBot(bs, match))
+ return;
+ //
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ //
+ client = FindClientByName(netname);
+ //
+ bs->decisionmaker = client;
+ bs->ordered = qtrue;
+ bs->order_time = FloatTime();
+ //set the time to send a message to the team mates
+ bs->teammessage_time = FloatTime() + 2 * random();
+ //set the ltg type
+ bs->ltgtype = LTG_RETURNFLAG;
+ //set the team goal time
+ bs->teamgoal_time = FloatTime() + CTF_RETURNFLAG_TIME;
+ bs->rushbaseaway_time = 0;
+ //
+ BotSetTeamStatus(bs);
+#ifdef DEBUG
+ BotPrintTeamGoal(bs);
+#endif //DEBUG
+}
+
+/*
+==================
+BotMatch_JoinSubteam
+==================
+*/
+void BotMatch_JoinSubteam(bot_state_t *bs, bot_match_t *match) {
+ char teammate[MAX_MESSAGE_SIZE];
+ char netname[MAX_MESSAGE_SIZE];
+ int client;
+
+ if (!TeamPlayIsOn()) return;
+ //if not addressed to this bot
+ if (!BotAddressedToBot(bs, match)) return;
+ //get the sub team name
+ trap_BotMatchVariable(match, TEAMNAME, teammate, sizeof(teammate));
+ //set the sub team name
+ strncpy(bs->subteam, teammate, 32);
+ bs->subteam[31] = '\0';
+ //
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ BotAI_BotInitialChat(bs, "joinedteam", teammate, NULL);
+ client = ClientFromName(netname);
+ trap_BotEnterChat(bs->cs, client, CHAT_TELL);
+}
+
+/*
+==================
+BotMatch_LeaveSubteam
+==================
+*/
+void BotMatch_LeaveSubteam(bot_state_t *bs, bot_match_t *match) {
+ char netname[MAX_MESSAGE_SIZE];
+ int client;
+
+ if (!TeamPlayIsOn()) return;
+ //if not addressed to this bot
+ if (!BotAddressedToBot(bs, match)) return;
+ //
+ if (strlen(bs->subteam))
+ {
+ BotAI_BotInitialChat(bs, "leftteam", bs->subteam, NULL);
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ client = ClientFromName(netname);
+ trap_BotEnterChat(bs->cs, client, CHAT_TELL);
+ } //end if
+ strcpy(bs->subteam, "");
+}
+
+/*
+==================
+BotMatch_LeaveSubteam
+==================
+*/
+void BotMatch_WhichTeam(bot_state_t *bs, bot_match_t *match) {
+ if (!TeamPlayIsOn()) return;
+ //if not addressed to this bot
+ if (!BotAddressedToBot(bs, match)) return;
+ //
+ if (strlen(bs->subteam)) {
+ BotAI_BotInitialChat(bs, "inteam", bs->subteam, NULL);
+ }
+ else {
+ BotAI_BotInitialChat(bs, "noteam", NULL);
+ }
+ trap_BotEnterChat(bs->cs, bs->client, CHAT_TEAM);
+}
+
+/*
+==================
+BotMatch_CheckPoint
+==================
+*/
+void BotMatch_CheckPoint(bot_state_t *bs, bot_match_t *match) {
+ int areanum, client;
+ char buf[MAX_MESSAGE_SIZE];
+ char netname[MAX_MESSAGE_SIZE];
+ vec3_t position;
+ bot_waypoint_t *cp;
+
+ if (!TeamPlayIsOn()) return;
+ //
+ trap_BotMatchVariable(match, POSITION, buf, MAX_MESSAGE_SIZE);
+ VectorClear(position);
+ //
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ client = ClientFromName(netname);
+ //BotGPSToPosition(buf, position);
+ sscanf(buf, "%f %f %f", &position[0], &position[1], &position[2]);
+ position[2] += 0.5;
+ areanum = BotPointAreaNum(position);
+ if (!areanum) {
+ if (BotAddressedToBot(bs, match)) {
+ BotAI_BotInitialChat(bs, "checkpoint_invalid", NULL);
+ trap_BotEnterChat(bs->cs, client, CHAT_TELL);
+ }
+ return;
+ }
+ //
+ trap_BotMatchVariable(match, NAME, buf, MAX_MESSAGE_SIZE);
+ //check if there already exists a checkpoint with this name
+ cp = BotFindWayPoint(bs->checkpoints, buf);
+ if (cp) {
+ if (cp->next) cp->next->prev = cp->prev;
+ if (cp->prev) cp->prev->next = cp->next;
+ else bs->checkpoints = cp->next;
+ cp->inuse = qfalse;
+ }
+ //create a new check point
+ cp = BotCreateWayPoint(buf, position, areanum);
+ //add the check point to the bot's known chech points
+ cp->next = bs->checkpoints;
+ if (bs->checkpoints) bs->checkpoints->prev = cp;
+ bs->checkpoints = cp;
+ //
+ if (BotAddressedToBot(bs, match)) {
+ Com_sprintf(buf, sizeof(buf), "%1.0f %1.0f %1.0f", cp->goal.origin[0],
+ cp->goal.origin[1],
+ cp->goal.origin[2]);
+
+ BotAI_BotInitialChat(bs, "checkpoint_confirm", cp->name, buf, NULL);
+ trap_BotEnterChat(bs->cs, client, CHAT_TELL);
+ }
+}
+
+/*
+==================
+BotMatch_FormationSpace
+==================
+*/
+void BotMatch_FormationSpace(bot_state_t *bs, bot_match_t *match) {
+ char buf[MAX_MESSAGE_SIZE];
+ float space;
+
+ if (!TeamPlayIsOn()) return;
+ //if not addressed to this bot
+ if (!BotAddressedToBot(bs, match)) return;
+ //
+ trap_BotMatchVariable(match, NUMBER, buf, MAX_MESSAGE_SIZE);
+ //if it's the distance in feet
+ if (match->subtype & ST_FEET) space = 0.3048 * 32 * atof(buf);
+ //else it's in meters
+ else space = 32 * atof(buf);
+ //check if the formation intervening space is valid
+ if (space < 48 || space > 500) space = 100;
+ bs->formation_dist = space;
+}
+
+/*
+==================
+BotMatch_Dismiss
+==================
+*/
+void BotMatch_Dismiss(bot_state_t *bs, bot_match_t *match) {
+ char netname[MAX_MESSAGE_SIZE];
+ int client;
+
+ if (!TeamPlayIsOn()) return;
+ //if not addressed to this bot
+ if (!BotAddressedToBot(bs, match)) return;
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ client = ClientFromName(netname);
+ //
+ bs->decisionmaker = client;
+ //
+ bs->ltgtype = 0;
+ bs->lead_time = 0;
+ bs->lastgoal_ltgtype = 0;
+ //
+ BotAI_BotInitialChat(bs, "dismissed", NULL);
+ trap_BotEnterChat(bs->cs, client, CHAT_TELL);
+}
+
+/*
+==================
+BotMatch_Suicide
+==================
+*/
+void BotMatch_Suicide(bot_state_t *bs, bot_match_t *match) {
+ char netname[MAX_MESSAGE_SIZE];
+ int client;
+
+ if (!TeamPlayIsOn()) return;
+ //if not addressed to this bot
+ if (!BotAddressedToBot(bs, match)) return;
+ //
+ trap_EA_Command(bs->client, "kill");
+ //
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ client = ClientFromName(netname);
+ //
+ BotVoiceChat(bs, client, VOICECHAT_TAUNT);
+ trap_EA_Action(bs->client, ACTION_AFFIRMATIVE);
+}
+
+/*
+==================
+BotMatch_StartTeamLeaderShip
+==================
+*/
+void BotMatch_StartTeamLeaderShip(bot_state_t *bs, bot_match_t *match) {
+ int client;
+ char teammate[MAX_MESSAGE_SIZE];
+
+ if (!TeamPlayIsOn()) return;
+ //if chats for him or herself
+ if (match->subtype & ST_I) {
+ //get the team mate that will be the team leader
+ trap_BotMatchVariable(match, NETNAME, teammate, sizeof(teammate));
+ strncpy(bs->teamleader, teammate, sizeof(bs->teamleader));
+ bs->teamleader[sizeof(bs->teamleader)] = '\0';
+ }
+ //chats for someone else
+ else {
+ //get the team mate that will be the team leader
+ trap_BotMatchVariable(match, TEAMMATE, teammate, sizeof(teammate));
+ client = FindClientByName(teammate);
+ if (client >= 0) ClientName(client, bs->teamleader, sizeof(bs->teamleader));
+ }
+}
+
+/*
+==================
+BotMatch_StopTeamLeaderShip
+==================
+*/
+void BotMatch_StopTeamLeaderShip(bot_state_t *bs, bot_match_t *match) {
+ int client;
+ char teammate[MAX_MESSAGE_SIZE];
+ char netname[MAX_MESSAGE_SIZE];
+
+ if (!TeamPlayIsOn()) return;
+ //get the team mate that stops being the team leader
+ trap_BotMatchVariable(match, TEAMMATE, teammate, sizeof(teammate));
+ //if chats for him or herself
+ if (match->subtype & ST_I) {
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ client = FindClientByName(netname);
+ }
+ //chats for someone else
+ else {
+ client = FindClientByName(teammate);
+ } //end else
+ if (client >= 0) {
+ if (!Q_stricmp(bs->teamleader, ClientName(client, netname, sizeof(netname)))) {
+ bs->teamleader[0] = '\0';
+ notleader[client] = qtrue;
+ }
+ }
+}
+
+/*
+==================
+BotMatch_WhoIsTeamLeader
+==================
+*/
+void BotMatch_WhoIsTeamLeader(bot_state_t *bs, bot_match_t *match) {
+ char netname[MAX_MESSAGE_SIZE];
+
+ if (!TeamPlayIsOn()) return;
+
+ ClientName(bs->client, netname, sizeof(netname));
+ //if this bot IS the team leader
+ if (!Q_stricmp(netname, bs->teamleader)) {
+ trap_EA_SayTeam(bs->client, "I'm the team leader\n");
+ }
+}
+
+/*
+==================
+BotMatch_WhatAreYouDoing
+==================
+*/
+void BotMatch_WhatAreYouDoing(bot_state_t *bs, bot_match_t *match) {
+ char netname[MAX_MESSAGE_SIZE];
+ char goalname[MAX_MESSAGE_SIZE];
+ int client;
+
+ //if not addressed to this bot
+ if (!BotAddressedToBot(bs, match)) return;
+ //
+ switch(bs->ltgtype) {
+ case LTG_TEAMHELP:
+ {
+ EasyClientName(bs->teammate, netname, sizeof(netname));
+ BotAI_BotInitialChat(bs, "helping", netname, NULL);
+ break;
+ }
+ case LTG_TEAMACCOMPANY:
+ {
+ EasyClientName(bs->teammate, netname, sizeof(netname));
+ BotAI_BotInitialChat(bs, "accompanying", netname, NULL);
+ break;
+ }
+ case LTG_DEFENDKEYAREA:
+ {
+ trap_BotGoalName(bs->teamgoal.number, goalname, sizeof(goalname));
+ BotAI_BotInitialChat(bs, "defending", goalname, NULL);
+ break;
+ }
+ case LTG_GETITEM:
+ {
+ trap_BotGoalName(bs->teamgoal.number, goalname, sizeof(goalname));
+ BotAI_BotInitialChat(bs, "gettingitem", goalname, NULL);
+ break;
+ }
+ case LTG_KILL:
+ {
+ ClientName(bs->teamgoal.entitynum, netname, sizeof(netname));
+ BotAI_BotInitialChat(bs, "killing", netname, NULL);
+ break;
+ }
+ case LTG_CAMP:
+ case LTG_CAMPORDER:
+ {
+ BotAI_BotInitialChat(bs, "camping", NULL);
+ break;
+ }
+ case LTG_PATROL:
+ {
+ BotAI_BotInitialChat(bs, "patrolling", NULL);
+ break;
+ }
+ case LTG_GETFLAG:
+ {
+ BotAI_BotInitialChat(bs, "capturingflag", NULL);
+ break;
+ }
+ case LTG_RUSHBASE:
+ {
+ BotAI_BotInitialChat(bs, "rushingbase", NULL);
+ break;
+ }
+ case LTG_RETURNFLAG:
+ {
+ BotAI_BotInitialChat(bs, "returningflag", NULL);
+ break;
+ }
+#ifdef MISSIONPACK
+ case LTG_ATTACKENEMYBASE:
+ {
+ BotAI_BotInitialChat(bs, "attackingenemybase", NULL);
+ break;
+ }
+ case LTG_HARVEST:
+ {
+ BotAI_BotInitialChat(bs, "harvesting", NULL);
+ break;
+ }
+#endif
+ default:
+ {
+ BotAI_BotInitialChat(bs, "roaming", NULL);
+ break;
+ }
+ }
+ //chat what the bot is doing
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ client = ClientFromName(netname);
+ trap_BotEnterChat(bs->cs, client, CHAT_TELL);
+}
+
+/*
+==================
+BotMatch_WhatIsMyCommand
+==================
+*/
+void BotMatch_WhatIsMyCommand(bot_state_t *bs, bot_match_t *match) {
+ char netname[MAX_NETNAME];
+
+ ClientName(bs->client, netname, sizeof(netname));
+ if (Q_stricmp(netname, bs->teamleader) != 0) return;
+ bs->forceorders = qtrue;
+}
+
+/*
+==================
+BotNearestVisibleItem
+==================
+*/
+float BotNearestVisibleItem(bot_state_t *bs, char *itemname, bot_goal_t *goal) {
+ int i;
+ char name[64];
+ bot_goal_t tmpgoal;
+ float dist, bestdist;
+ vec3_t dir;
+ bsp_trace_t trace;
+
+ bestdist = 999999;
+ i = -1;
+ do {
+ i = trap_BotGetLevelItemGoal(i, itemname, &tmpgoal);
+ trap_BotGoalName(tmpgoal.number, name, sizeof(name));
+ if (Q_stricmp(itemname, name) != 0)
+ continue;
+ VectorSubtract(tmpgoal.origin, bs->origin, dir);
+ dist = VectorLength(dir);
+ if (dist < bestdist) {
+ //trace from start to end
+ BotAI_Trace(&trace, bs->eye, NULL, NULL, tmpgoal.origin, bs->client, CONTENTS_SOLID|CONTENTS_PLAYERCLIP);
+ if (trace.fraction >= 1.0) {
+ bestdist = dist;
+ memcpy(goal, &tmpgoal, sizeof(bot_goal_t));
+ }
+ }
+ } while(i > 0);
+ return bestdist;
+}
+
+/*
+==================
+BotMatch_WhereAreYou
+==================
+*/
+void BotMatch_WhereAreYou(bot_state_t *bs, bot_match_t *match) {
+ float dist, bestdist;
+ int i, bestitem, redtt, bluett, client;
+ bot_goal_t goal;
+ char netname[MAX_MESSAGE_SIZE];
+ char *nearbyitems[] = {
+ "Shotgun",
+ "Grenade Launcher",
+ "Rocket Launcher",
+ "Plasmagun",
+ "Railgun",
+ "Lightning Gun",
+ "BFG10K",
+ "Quad Damage",
+ "Regeneration",
+ "Battle Suit",
+ "Speed",
+ "Invisibility",
+ "Flight",
+ "Armor",
+ "Heavy Armor",
+ "Red Flag",
+ "Blue Flag",
+#ifdef MISSIONPACK
+ "Nailgun",
+ "Prox Launcher",
+ "Chaingun",
+ "Scout",
+ "Guard",
+ "Doubler",
+ "Ammo Regen",
+ "Neutral Flag",
+ "Red Obelisk",
+ "Blue Obelisk",
+ "Neutral Obelisk",
+#endif
+ NULL
+ };
+ //
+ if (!TeamPlayIsOn())
+ return;
+ //if not addressed to this bot
+ if (!BotAddressedToBot(bs, match))
+ return;
+
+ bestitem = -1;
+ bestdist = 999999;
+ for (i = 0; nearbyitems[i]; i++) {
+ dist = BotNearestVisibleItem(bs, nearbyitems[i], &goal);
+ if (dist < bestdist) {
+ bestdist = dist;
+ bestitem = i;
+ }
+ }
+ if (bestitem != -1) {
+ if (gametype == GT_CTF
+#ifdef MISSIONPACK
+ || gametype == GT_1FCTF
+#endif
+ ) {
+ redtt = trap_AAS_AreaTravelTimeToGoalArea(bs->areanum, bs->origin, ctf_redflag.areanum, TFL_DEFAULT);
+ bluett = trap_AAS_AreaTravelTimeToGoalArea(bs->areanum, bs->origin, ctf_blueflag.areanum, TFL_DEFAULT);
+ if (redtt < (redtt + bluett) * 0.4) {
+ BotAI_BotInitialChat(bs, "teamlocation", nearbyitems[bestitem], "red", NULL);
+ }
+ else if (bluett < (redtt + bluett) * 0.4) {
+ BotAI_BotInitialChat(bs, "teamlocation", nearbyitems[bestitem], "blue", NULL);
+ }
+ else {
+ BotAI_BotInitialChat(bs, "location", nearbyitems[bestitem], NULL);
+ }
+ }
+#ifdef MISSIONPACK
+ else if (gametype == GT_OBELISK || gametype == GT_HARVESTER) {
+ redtt = trap_AAS_AreaTravelTimeToGoalArea(bs->areanum, bs->origin, redobelisk.areanum, TFL_DEFAULT);
+ bluett = trap_AAS_AreaTravelTimeToGoalArea(bs->areanum, bs->origin, blueobelisk.areanum, TFL_DEFAULT);
+ if (redtt < (redtt + bluett) * 0.4) {
+ BotAI_BotInitialChat(bs, "teamlocation", nearbyitems[bestitem], "red", NULL);
+ }
+ else if (bluett < (redtt + bluett) * 0.4) {
+ BotAI_BotInitialChat(bs, "teamlocation", nearbyitems[bestitem], "blue", NULL);
+ }
+ else {
+ BotAI_BotInitialChat(bs, "location", nearbyitems[bestitem], NULL);
+ }
+ }
+#endif
+ else {
+ BotAI_BotInitialChat(bs, "location", nearbyitems[bestitem], NULL);
+ }
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ client = ClientFromName(netname);
+ trap_BotEnterChat(bs->cs, client, CHAT_TELL);
+ }
+}
+
+/*
+==================
+BotMatch_LeadTheWay
+==================
+*/
+void BotMatch_LeadTheWay(bot_state_t *bs, bot_match_t *match) {
+ aas_entityinfo_t entinfo;
+ char netname[MAX_MESSAGE_SIZE], teammate[MAX_MESSAGE_SIZE];
+ int client, areanum, other;
+
+ if (!TeamPlayIsOn()) return;
+ //if not addressed to this bot
+ if (!BotAddressedToBot(bs, match)) return;
+ //if someone asks for someone else
+ if (match->subtype & ST_SOMEONE) {
+ //get the team mate name
+ trap_BotMatchVariable(match, TEAMMATE, teammate, sizeof(teammate));
+ client = FindClientByName(teammate);
+ //if this is the bot self
+ if (client == bs->client) {
+ other = qfalse;
+ }
+ else if (!BotSameTeam(bs, client)) {
+ //FIXME: say "I don't help the enemy"
+ return;
+ }
+ else {
+ other = qtrue;
+ }
+ }
+ else {
+ //get the netname
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ client = ClientFromName(netname);
+ other = qfalse;
+ }
+ //if the bot doesn't know who to help (FindClientByName returned -1)
+ if (client < 0) {
+ BotAI_BotInitialChat(bs, "whois", netname, NULL);
+ trap_BotEnterChat(bs->cs, bs->client, CHAT_TEAM);
+ return;
+ }
+ //
+ bs->lead_teamgoal.entitynum = -1;
+ BotEntityInfo(client, &entinfo);
+ //if info is valid (in PVS)
+ if (entinfo.valid) {
+ areanum = BotPointAreaNum(entinfo.origin);
+ if (areanum) { // && trap_AAS_AreaReachability(areanum)) {
+ bs->lead_teamgoal.entitynum = client;
+ bs->lead_teamgoal.areanum = areanum;
+ VectorCopy(entinfo.origin, bs->lead_teamgoal.origin);
+ VectorSet(bs->lead_teamgoal.mins, -8, -8, -8);
+ VectorSet(bs->lead_teamgoal.maxs, 8, 8, 8);
+ }
+ }
+
+ if (bs->teamgoal.entitynum < 0) {
+ if (other) BotAI_BotInitialChat(bs, "whereis", teammate, NULL);
+ else BotAI_BotInitialChat(bs, "whereareyou", netname, NULL);
+ trap_BotEnterChat(bs->cs, bs->client, CHAT_TEAM);
+ return;
+ }
+ bs->lead_teammate = client;
+ bs->lead_time = FloatTime() + TEAM_LEAD_TIME;
+ bs->leadvisible_time = 0;
+ bs->leadmessage_time = -(FloatTime() + 2 * random());
+}
+
+/*
+==================
+BotMatch_Kill
+==================
+*/
+void BotMatch_Kill(bot_state_t *bs, bot_match_t *match) {
+ char enemy[MAX_MESSAGE_SIZE];
+ char netname[MAX_MESSAGE_SIZE];
+ int client;
+
+ if (!TeamPlayIsOn()) return;
+ //if not addressed to this bot
+ if (!BotAddressedToBot(bs, match)) return;
+
+ trap_BotMatchVariable(match, ENEMY, enemy, sizeof(enemy));
+ //
+ client = FindEnemyByName(bs, enemy);
+ if (client < 0) {
+ BotAI_BotInitialChat(bs, "whois", enemy, NULL);
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ client = ClientFromName(netname);
+ trap_BotEnterChat(bs->cs, client, CHAT_TELL);
+ return;
+ }
+ bs->teamgoal.entitynum = client;
+ //set the time to send a message to the team mates
+ bs->teammessage_time = FloatTime() + 2 * random();
+ //set the ltg type
+ bs->ltgtype = LTG_KILL;
+ //set the team goal time
+ bs->teamgoal_time = FloatTime() + TEAM_KILL_SOMEONE;
+ //
+ BotSetTeamStatus(bs);
+#ifdef DEBUG
+ BotPrintTeamGoal(bs);
+#endif //DEBUG
+}
+
+/*
+==================
+BotMatch_CTF
+==================
+*/
+void BotMatch_CTF(bot_state_t *bs, bot_match_t *match) {
+
+ char flag[128], netname[MAX_NETNAME];
+
+ if (gametype == GT_CTF) {
+ trap_BotMatchVariable(match, FLAG, flag, sizeof(flag));
+ if (match->subtype & ST_GOTFLAG) {
+ if (!Q_stricmp(flag, "red")) {
+ bs->redflagstatus = 1;
+ if (BotTeam(bs) == TEAM_BLUE) {
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ bs->flagcarrier = ClientFromName(netname);
+ }
+ }
+ else {
+ bs->blueflagstatus = 1;
+ if (BotTeam(bs) == TEAM_RED) {
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ bs->flagcarrier = ClientFromName(netname);
+ }
+ }
+ bs->flagstatuschanged = 1;
+ bs->lastflagcapture_time = FloatTime();
+ }
+ else if (match->subtype & ST_CAPTUREDFLAG) {
+ bs->redflagstatus = 0;
+ bs->blueflagstatus = 0;
+ bs->flagcarrier = 0;
+ bs->flagstatuschanged = 1;
+ }
+ else if (match->subtype & ST_RETURNEDFLAG) {
+ if (!Q_stricmp(flag, "red")) bs->redflagstatus = 0;
+ else bs->blueflagstatus = 0;
+ bs->flagstatuschanged = 1;
+ }
+ }
+#ifdef MISSIONPACK
+ else if (gametype == GT_1FCTF) {
+ if (match->subtype & ST_1FCTFGOTFLAG) {
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ bs->flagcarrier = ClientFromName(netname);
+ }
+ }
+#endif
+}
+
+void BotMatch_EnterGame(bot_state_t *bs, bot_match_t *match) {
+ int client;
+ char netname[MAX_NETNAME];
+
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ client = FindClientByName(netname);
+ if (client >= 0) {
+ notleader[client] = qfalse;
+ }
+ //NOTE: eliza chats will catch this
+ //Com_sprintf(buf, sizeof(buf), "heya %s", netname);
+ //EA_Say(bs->client, buf);
+}
+
+void BotMatch_NewLeader(bot_state_t *bs, bot_match_t *match) {
+ int client;
+ char netname[MAX_NETNAME];
+
+ trap_BotMatchVariable(match, NETNAME, netname, sizeof(netname));
+ client = FindClientByName(netname);
+ if (!BotSameTeam(bs, client))
+ return;
+ Q_strncpyz(bs->teamleader, netname, sizeof(bs->teamleader));
+}
+
+/*
+==================
+BotMatchMessage
+==================
+*/
+int BotMatchMessage(bot_state_t *bs, char *message) {
+ bot_match_t match;
+
+ match.type = 0;
+ //if it is an unknown message
+ if (!trap_BotFindMatch(message, &match, MTCONTEXT_MISC
+ |MTCONTEXT_INITIALTEAMCHAT
+ |MTCONTEXT_CTF)) {
+ return qfalse;
+ }
+ //react to the found message
+ switch(match.type)
+ {
+ case MSG_HELP: //someone calling for help
+ case MSG_ACCOMPANY: //someone calling for company
+ {
+ BotMatch_HelpAccompany(bs, &match);
+ break;
+ }
+ case MSG_DEFENDKEYAREA: //teamplay defend a key area
+ {
+ BotMatch_DefendKeyArea(bs, &match);
+ break;
+ }
+ case MSG_CAMP: //camp somewhere
+ {
+ BotMatch_Camp(bs, &match);
+ break;
+ }
+ case MSG_PATROL: //patrol between several key areas
+ {
+ BotMatch_Patrol(bs, &match);
+ break;
+ }
+ //CTF & 1FCTF
+ case MSG_GETFLAG: //ctf get the enemy flag
+ {
+ BotMatch_GetFlag(bs, &match);
+ break;
+ }
+#ifdef MISSIONPACK
+ //CTF & 1FCTF & Obelisk & Harvester
+ case MSG_ATTACKENEMYBASE:
+ {
+ BotMatch_AttackEnemyBase(bs, &match);
+ break;
+ }
+ //Harvester
+ case MSG_HARVEST:
+ {
+ BotMatch_Harvest(bs, &match);
+ break;
+ }
+#endif
+ //CTF & 1FCTF & Harvester
+ case MSG_RUSHBASE: //ctf rush to the base
+ {
+ BotMatch_RushBase(bs, &match);
+ break;
+ }
+ //CTF & 1FCTF
+ case MSG_RETURNFLAG:
+ {
+ BotMatch_ReturnFlag(bs, &match);
+ break;
+ }
+ //CTF & 1FCTF & Obelisk & Harvester
+ case MSG_TASKPREFERENCE:
+ {
+ BotMatch_TaskPreference(bs, &match);
+ break;
+ }
+ //CTF & 1FCTF
+ case MSG_CTF:
+ {
+ BotMatch_CTF(bs, &match);
+ break;
+ }
+ case MSG_GETITEM:
+ {
+ BotMatch_GetItem(bs, &match);
+ break;
+ }
+ case MSG_JOINSUBTEAM: //join a sub team
+ {
+ BotMatch_JoinSubteam(bs, &match);
+ break;
+ }
+ case MSG_LEAVESUBTEAM: //leave a sub team
+ {
+ BotMatch_LeaveSubteam(bs, &match);
+ break;
+ }
+ case MSG_WHICHTEAM:
+ {
+ BotMatch_WhichTeam(bs, &match);
+ break;
+ }
+ case MSG_CHECKPOINT: //remember a check point
+ {
+ BotMatch_CheckPoint(bs, &match);
+ break;
+ }
+ case MSG_CREATENEWFORMATION: //start the creation of a new formation
+ {
+ trap_EA_SayTeam(bs->client, "the part of my brain to create formations has been damaged");
+ break;
+ }
+ case MSG_FORMATIONPOSITION: //tell someone his/her position in the formation
+ {
+ trap_EA_SayTeam(bs->client, "the part of my brain to create formations has been damaged");
+ break;
+ }
+ case MSG_FORMATIONSPACE: //set the formation space
+ {
+ BotMatch_FormationSpace(bs, &match);
+ break;
+ }
+ case MSG_DOFORMATION: //form a certain formation
+ {
+ break;
+ }
+ case MSG_DISMISS: //dismiss someone
+ {
+ BotMatch_Dismiss(bs, &match);
+ break;
+ }
+ case MSG_STARTTEAMLEADERSHIP: //someone will become the team leader
+ {
+ BotMatch_StartTeamLeaderShip(bs, &match);
+ break;
+ }
+ case MSG_STOPTEAMLEADERSHIP: //someone will stop being the team leader
+ {
+ BotMatch_StopTeamLeaderShip(bs, &match);
+ break;
+ }
+ case MSG_WHOISTEAMLAEDER:
+ {
+ BotMatch_WhoIsTeamLeader(bs, &match);
+ break;
+ }
+ case MSG_WHATAREYOUDOING: //ask a bot what he/she is doing
+ {
+ BotMatch_WhatAreYouDoing(bs, &match);
+ break;
+ }
+ case MSG_WHATISMYCOMMAND:
+ {
+ BotMatch_WhatIsMyCommand(bs, &match);
+ break;
+ }
+ case MSG_WHEREAREYOU:
+ {
+ BotMatch_WhereAreYou(bs, &match);
+ break;
+ }
+ case MSG_LEADTHEWAY:
+ {
+ BotMatch_LeadTheWay(bs, &match);
+ break;
+ }
+ case MSG_KILL:
+ {
+ BotMatch_Kill(bs, &match);
+ break;
+ }
+ case MSG_ENTERGAME: //someone entered the game
+ {
+ BotMatch_EnterGame(bs, &match);
+ break;
+ }
+ case MSG_NEWLEADER:
+ {
+ BotMatch_NewLeader(bs, &match);
+ break;
+ }
+ case MSG_WAIT:
+ {
+ break;
+ }
+ case MSG_SUICIDE:
+ {
+ BotMatch_Suicide(bs, &match);
+ break;
+ }
+ default:
+ {
+ BotAI_Print(PRT_MESSAGE, "unknown match type\n");
+ break;
+ }
+ }
+ return qtrue;
+}
diff --git a/code/game/ai_cmd.h b/code/game/ai_cmd.h
new file mode 100755
index 0000000..511c57a
--- /dev/null
+++ b/code/game/ai_cmd.h
@@ -0,0 +1,37 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+/*****************************************************************************
+ * name: ai_cmd.h
+ *
+ * desc: Quake3 bot AI
+ *
+ * $Archive: /source/code/botai/ai_chat.c $
+ *
+ *****************************************************************************/
+
+extern int notleader[MAX_CLIENTS];
+
+int BotMatchMessage(bot_state_t *bs, char *message);
+void BotPrintTeamGoal(bot_state_t *bs);
+
diff --git a/code/game/ai_dmnet.c b/code/game/ai_dmnet.c
new file mode 100755
index 0000000..3bf3a8a
--- /dev/null
+++ b/code/game/ai_dmnet.c
@@ -0,0 +1,2610 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+/*****************************************************************************
+ * name: ai_dmnet.c
+ *
+ * desc: Quake3 bot AI
+ *
+ * $Archive: /MissionPack/code/game/ai_dmnet.c $
+ *
+ *****************************************************************************/
+
+#include "g_local.h"
+#include "botlib.h"
+#include "be_aas.h"
+#include "be_ea.h"
+#include "be_ai_char.h"
+#include "be_ai_chat.h"
+#include "be_ai_gen.h"
+#include "be_ai_goal.h"
+#include "be_ai_move.h"
+#include "be_ai_weap.h"
+//
+#include "ai_main.h"
+#include "ai_dmq3.h"
+#include "ai_chat.h"
+#include "ai_cmd.h"
+#include "ai_dmnet.h"
+#include "ai_team.h"
+//data file headers
+#include "chars.h" //characteristics
+#include "inv.h" //indexes into the inventory
+#include "syn.h" //synonyms
+#include "match.h" //string matching types and vars
+
+// for the voice chats
+#include "../../ui/menudef.h"
+
+//goal flag, see be_ai_goal.h for the other GFL_*
+#define GFL_AIR 128
+
+int numnodeswitches;
+char nodeswitch[MAX_NODESWITCHES+1][144];
+
+#define LOOKAHEAD_DISTANCE 300
+
+/*
+==================
+BotResetNodeSwitches
+==================
+*/
+void BotResetNodeSwitches(void) {
+ numnodeswitches = 0;
+}
+
+/*
+==================
+BotDumpNodeSwitches
+==================
+*/
+void BotDumpNodeSwitches(bot_state_t *bs) {
+ int i;
+ char netname[MAX_NETNAME];
+
+ ClientName(bs->client, netname, sizeof(netname));
+ BotAI_Print(PRT_MESSAGE, "%s at %1.1f switched more than %d AI nodes\n", netname, FloatTime(), MAX_NODESWITCHES);
+ for (i = 0; i < numnodeswitches; i++) {
+ BotAI_Print(PRT_MESSAGE, nodeswitch[i]);
+ }
+ BotAI_Print(PRT_FATAL, "");
+}
+
+/*
+==================
+BotRecordNodeSwitch
+==================
+*/
+void BotRecordNodeSwitch(bot_state_t *bs, char *node, char *str, char *s) {
+ char netname[MAX_NETNAME];
+
+ ClientName(bs->client, netname, sizeof(netname));
+ Com_sprintf(nodeswitch[numnodeswitches], 144, "%s at %2.1f entered %s: %s from %s\n", netname, FloatTime(), node, str, s);
+#ifdef DEBUG
+ if (0) {
+ BotAI_Print(PRT_MESSAGE, nodeswitch[numnodeswitches]);
+ }
+#endif //DEBUG
+ numnodeswitches++;
+}
+
+/*
+==================
+BotGetAirGoal
+==================
+*/
+int BotGetAirGoal(bot_state_t *bs, bot_goal_t *goal) {
+ bsp_trace_t bsptrace;
+ vec3_t end, mins = {-15, -15, -2}, maxs = {15, 15, 2};
+ int areanum;
+
+ //trace up until we hit solid
+ VectorCopy(bs->origin, end);
+ end[2] += 1000;
+ BotAI_Trace(&bsptrace, bs->origin, mins, maxs, end, bs->entitynum, CONTENTS_SOLID|CONTENTS_PLAYERCLIP);
+ //trace down until we hit water
+ VectorCopy(bsptrace.endpos, end);
+ BotAI_Trace(&bsptrace, end, mins, maxs, bs->origin, bs->entitynum, CONTENTS_WATER|CONTENTS_SLIME|CONTENTS_LAVA);
+ //if we found the water surface
+ if (bsptrace.fraction > 0) {
+ areanum = BotPointAreaNum(bsptrace.endpos);
+ if (areanum) {
+ VectorCopy(bsptrace.endpos, goal->origin);
+ goal->origin[2] -= 2;
+ goal->areanum = areanum;
+ goal->mins[0] = -15;
+ goal->mins[1] = -15;
+ goal->mins[2] = -1;
+ goal->maxs[0] = 15;
+ goal->maxs[1] = 15;
+ goal->maxs[2] = 1;
+ goal->flags = GFL_AIR;
+ goal->number = 0;
+ goal->iteminfo = 0;
+ goal->entitynum = 0;
+ return qtrue;
+ }
+ }
+ return qfalse;
+}
+
+/*
+==================
+BotGoForAir
+==================
+*/
+int BotGoForAir(bot_state_t *bs, int tfl, bot_goal_t *ltg, float range) {
+ bot_goal_t goal;
+
+ //if the bot needs air
+ if (bs->lastair_time < FloatTime() - 6) {
+ //
+#ifdef DEBUG
+ //BotAI_Print(PRT_MESSAGE, "going for air\n");
+#endif //DEBUG
+ //if we can find an air goal
+ if (BotGetAirGoal(bs, &goal)) {
+ trap_BotPushGoal(bs->gs, &goal);
+ return qtrue;
+ }
+ else {
+ //get a nearby goal outside the water
+ while(trap_BotChooseNBGItem(bs->gs, bs->origin, bs->inventory, tfl, ltg, range)) {
+ trap_BotGetTopGoal(bs->gs, &goal);
+ //if the goal is not in water
+ if (!(trap_AAS_PointContents(goal.origin) & (CONTENTS_WATER|CONTENTS_SLIME|CONTENTS_LAVA))) {
+ return qtrue;
+ }
+ trap_BotPopGoal(bs->gs);
+ }
+ trap_BotResetAvoidGoals(bs->gs);
+ }
+ }
+ return qfalse;
+}
+
+/*
+==================
+BotNearbyGoal
+==================
+*/
+int BotNearbyGoal(bot_state_t *bs, int tfl, bot_goal_t *ltg, float range) {
+ int ret;
+
+ //check if the bot should go for air
+ if (BotGoForAir(bs, tfl, ltg, range)) return qtrue;
+ //if the bot is carrying the enemy flag
+ if (BotCTFCarryingFlag(bs)) {
+ //if the bot is just a few secs away from the base
+ if (trap_AAS_AreaTravelTimeToGoalArea(bs->areanum, bs->origin,
+ bs->teamgoal.areanum, TFL_DEFAULT) < 300) {
+ //make the range really small
+ range = 50;
+ }
+ }
+ //
+ ret = trap_BotChooseNBGItem(bs->gs, bs->origin, bs->inventory, tfl, ltg, range);
+ /*
+ if (ret)
+ {
+ char buf[128];
+ //get the goal at the top of the stack
+ trap_BotGetTopGoal(bs->gs, &goal);
+ trap_BotGoalName(goal.number, buf, sizeof(buf));
+ BotAI_Print(PRT_MESSAGE, "%1.1f: new nearby goal %s\n", FloatTime(), buf);
+ }
+ */
+ return ret;
+}
+
+/*
+==================
+BotReachedGoal
+==================
+*/
+int BotReachedGoal(bot_state_t *bs, bot_goal_t *goal) {
+ if (goal->flags & GFL_ITEM) {
+ //if touching the goal
+ if (trap_BotTouchingGoal(bs->origin, goal)) {
+ if (!(goal->flags & GFL_DROPPED)) {
+ trap_BotSetAvoidGoalTime(bs->gs, goal->number, -1);
+ }
+ return qtrue;
+ }
+ //if the goal isn't there
+ if (trap_BotItemGoalInVisButNotVisible(bs->entitynum, bs->eye, bs->viewangles, goal)) {
+ /*
+ float avoidtime;
+ int t;
+
+ avoidtime = trap_BotAvoidGoalTime(bs->gs, goal->number);
+ if (avoidtime > 0) {
+ t = trap_AAS_AreaTravelTimeToGoalArea(bs->areanum, bs->origin, goal->areanum, bs->tfl);
+ if ((float) t * 0.009 < avoidtime)
+ return qtrue;
+ }
+ */
+ return qtrue;
+ }
+ //if in the goal area and below or above the goal and not swimming
+ if (bs->areanum == goal->areanum) {
+ if (bs->origin[0] > goal->origin[0] + goal->mins[0] && bs->origin[0] < goal->origin[0] + goal->maxs[0]) {
+ if (bs->origin[1] > goal->origin[1] + goal->mins[1] && bs->origin[1] < goal->origin[1] + goal->maxs[1]) {
+ if (!trap_AAS_Swimming(bs->origin)) {
+ return qtrue;
+ }
+ }
+ }
+ }
+ }
+ else if (goal->flags & GFL_AIR) {
+ //if touching the goal
+ if (trap_BotTouchingGoal(bs->origin, goal)) return qtrue;
+ //if the bot got air
+ if (bs->lastair_time > FloatTime() - 1) return qtrue;
+ }
+ else {
+ //if touching the goal
+ if (trap_BotTouchingGoal(bs->origin, goal)) return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+==================
+BotGetItemLongTermGoal
+==================
+*/
+int BotGetItemLongTermGoal(bot_state_t *bs, int tfl, bot_goal_t *goal) {
+ //if the bot has no goal
+ if (!trap_BotGetTopGoal(bs->gs, goal)) {
+ //BotAI_Print(PRT_MESSAGE, "no ltg on stack\n");
+ bs->ltg_time = 0;
+ }
+ //if the bot touches the current goal
+ else if (BotReachedGoal(bs, goal)) {
+ BotChooseWeapon(bs);
+ bs->ltg_time = 0;
+ }
+ //if it is time to find a new long term goal
+ if (bs->ltg_time < FloatTime()) {
+ //pop the current goal from the stack
+ trap_BotPopGoal(bs->gs);
+ //BotAI_Print(PRT_MESSAGE, "%s: choosing new ltg\n", ClientName(bs->client, netname, sizeof(netname)));
+ //choose a new goal
+ //BotAI_Print(PRT_MESSAGE, "%6.1f client %d: BotChooseLTGItem\n", FloatTime(), bs->client);
+ if (trap_BotChooseLTGItem(bs->gs, bs->origin, bs->inventory, tfl)) {
+ /*
+ char buf[128];
+ //get the goal at the top of the stack
+ trap_BotGetTopGoal(bs->gs, goal);
+ trap_BotGoalName(goal->number, buf, sizeof(buf));
+ BotAI_Print(PRT_MESSAGE, "%1.1f: new long term goal %s\n", FloatTime(), buf);
+ */
+ bs->ltg_time = FloatTime() + 20;
+ }
+ else {//the bot gets sorta stuck with all the avoid timings, shouldn't happen though
+ //
+#ifdef DEBUG
+ char netname[128];
+
+ BotAI_Print(PRT_MESSAGE, "%s: no valid ltg (probably stuck)\n", ClientName(bs->client, netname, sizeof(netname)));
+#endif
+ //trap_BotDumpAvoidGoals(bs->gs);
+ //reset the avoid goals and the avoid reach
+ trap_BotResetAvoidGoals(bs->gs);
+ trap_BotResetAvoidReach(bs->ms);
+ }
+ //get the goal at the top of the stack
+ return trap_BotGetTopGoal(bs->gs, goal);
+ }
+ return qtrue;
+}
+
+/*
+==================
+BotGetLongTermGoal
+
+we could also create a seperate AI node for every long term goal type
+however this saves us a lot of code
+==================
+*/
+int BotGetLongTermGoal(bot_state_t *bs, int tfl, int retreat, bot_goal_t *goal) {
+ vec3_t target, dir, dir2;
+ char netname[MAX_NETNAME];
+ char buf[MAX_MESSAGE_SIZE];
+ int areanum;
+ float croucher;
+ aas_entityinfo_t entinfo, botinfo;
+ bot_waypoint_t *wp;
+
+ if (bs->ltgtype == LTG_TEAMHELP && !retreat) {
+ //check for bot typing status message
+ if (bs->teammessage_time && bs->teammessage_time < FloatTime()) {
+ BotAI_BotInitialChat(bs, "help_start", EasyClientName(bs->teammate, netname, sizeof(netname)), NULL);
+ trap_BotEnterChat(bs->cs, bs->decisionmaker, CHAT_TELL);
+ BotVoiceChatOnly(bs, bs->decisionmaker, VOICECHAT_YES);
+ trap_EA_Action(bs->client, ACTION_AFFIRMATIVE);
+ bs->teammessage_time = 0;
+ }
+ //if trying to help the team mate for more than a minute
+ if (bs->teamgoal_time < FloatTime())
+ bs->ltgtype = 0;
+ //if the team mate IS visible for quite some time
+ if (bs->teammatevisible_time < FloatTime() - 10) bs->ltgtype = 0;
+ //get entity information of the companion
+ BotEntityInfo(bs->teammate, &entinfo);
+ //if the team mate is visible
+ if (BotEntityVisible(bs->entitynum, bs->eye, bs->viewangles, 360, bs->teammate)) {
+ //if close just stand still there
+ VectorSubtract(entinfo.origin, bs->origin, dir);
+ if (VectorLengthSquared(dir) < Square(100)) {
+ trap_BotResetAvoidReach(bs->ms);
+ return qfalse;
+ }
+ }
+ else {
+ //last time the bot was NOT visible
+ bs->teammatevisible_time = FloatTime();
+ }
+ //if the entity information is valid (entity in PVS)
+ if (entinfo.valid) {
+ areanum = BotPointAreaNum(entinfo.origin);
+ if (areanum && trap_AAS_AreaReachability(areanum)) {
+ //update team goal
+ bs->teamgoal.entitynum = bs->teammate;
+ bs->teamgoal.areanum = areanum;
+ VectorCopy(entinfo.origin, bs->teamgoal.origin);
+ VectorSet(bs->teamgoal.mins, -8, -8, -8);
+ VectorSet(bs->teamgoal.maxs, 8, 8, 8);
+ }
+ }
+ memcpy(goal, &bs->teamgoal, sizeof(bot_goal_t));
+ return qtrue;
+ }
+ //if the bot accompanies someone
+ if (bs->ltgtype == LTG_TEAMACCOMPANY && !retreat) {
+ //check for bot typing status message
+ if (bs->teammessage_time && bs->teammessage_time < FloatTime()) {
+ BotAI_BotInitialChat(bs, "accompany_start", EasyClientName(bs->teammate, netname, sizeof(netname)), NULL);
+ trap_BotEnterChat(bs->cs, bs->decisionmaker, CHAT_TELL);
+ BotVoiceChatOnly(bs, bs->decisionmaker, VOICECHAT_YES);
+ trap_EA_Action(bs->client, ACTION_AFFIRMATIVE);
+ bs->teammessage_time = 0;
+ }
+ //if accompanying the companion for 3 minutes
+ if (bs->teamgoal_time < FloatTime()) {
+ BotAI_BotInitialChat(bs, "accompany_stop", EasyClientName(bs->teammate, netname, sizeof(netname)), NULL);
+ trap_BotEnterChat(bs->cs, bs->teammate, CHAT_TELL);
+ bs->ltgtype = 0;
+ }
+ //get entity information of the companion
+ BotEntityInfo(bs->teammate, &entinfo);
+ //if the companion is visible
+ if (BotEntityVisible(bs->entitynum, bs->eye, bs->viewangles, 360, bs->teammate)) {
+ //update visible time
+ bs->teammatevisible_time = FloatTime();
+ VectorSubtract(entinfo.origin, bs->origin, dir);
+ if (VectorLengthSquared(dir) < Square(bs->formation_dist)) {
+ //
+ // if the client being followed bumps into this bot then
+ // the bot should back up
+ BotEntityInfo(bs->entitynum, &botinfo);
+ // if the followed client is not standing ontop of the bot
+ if (botinfo.origin[2] + botinfo.maxs[2] > entinfo.origin[2] + entinfo.mins[2]) {
+ // if the bounding boxes touch each other
+ if (botinfo.origin[0] + botinfo.maxs[0] > entinfo.origin[0] + entinfo.mins[0] - 4&&
+ botinfo.origin[0] + botinfo.mins[0] < entinfo.origin[0] + entinfo.maxs[0] + 4) {
+ if (botinfo.origin[1] + botinfo.maxs[1] > entinfo.origin[1] + entinfo.mins[1] - 4 &&
+ botinfo.origin[1] + botinfo.mins[1] < entinfo.origin[1] + entinfo.maxs[1] + 4) {
+ if (botinfo.origin[2] + botinfo.maxs[2] > entinfo.origin[2] + entinfo.mins[2] - 4 &&
+ botinfo.origin[2] + botinfo.mins[2] < entinfo.origin[2] + entinfo.maxs[2] + 4) {
+ // if the followed client looks in the direction of this bot
+ AngleVectors(entinfo.angles, dir, NULL, NULL);
+ dir[2] = 0;
+ VectorNormalize(dir);
+ //VectorSubtract(entinfo.origin, entinfo.lastvisorigin, dir);
+ VectorSubtract(bs->origin, entinfo.origin, dir2);
+ VectorNormalize(dir2);
+ if (DotProduct(dir, dir2) > 0.7) {
+ // back up
+ BotSetupForMovement(bs);
+ trap_BotMoveInDirection(bs->ms, dir2, 400, MOVE_WALK);
+ }
+ }
+ }
+ }
+ }
+ //check if the bot wants to crouch
+ //don't crouch if crouched less than 5 seconds ago
+ if (bs->attackcrouch_time < FloatTime() - 5) {
+ croucher = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_CROUCHER, 0, 1);
+ if (random() < bs->thinktime * croucher) {
+ bs->attackcrouch_time = FloatTime() + 5 + croucher * 15;
+ }
+ }
+ //don't crouch when swimming
+ if (trap_AAS_Swimming(bs->origin)) bs->attackcrouch_time = FloatTime() - 1;
+ //if not arrived yet or arived some time ago
+ if (bs->arrive_time < FloatTime() - 2) {
+ //if not arrived yet
+ if (!bs->arrive_time) {
+ trap_EA_Gesture(bs->client);
+ BotAI_BotInitialChat(bs, "accompany_arrive", EasyClientName(bs->teammate, netname, sizeof(netname)), NULL);
+ trap_BotEnterChat(bs->cs, bs->teammate, CHAT_TELL);
+ bs->arrive_time = FloatTime();
+ }
+ //if the bot wants to crouch
+ else if (bs->attackcrouch_time > FloatTime()) {
+ trap_EA_Crouch(bs->client);
+ }
+ //else do some model taunts
+ else if (random() < bs->thinktime * 0.05) {
+ //do a gesture :)
+ trap_EA_Gesture(bs->client);
+ }
+ }
+ //if just arrived look at the companion
+ if (bs->arrive_time > FloatTime() - 2) {
+ VectorSubtract(entinfo.origin, bs->origin, dir);
+ vectoangles(dir, bs->ideal_viewangles);
+ bs->ideal_viewangles[2] *= 0.5;
+ }
+ //else look strategically around for enemies
+ else if (random() < bs->thinktime * 0.8) {
+ BotRoamGoal(bs, target);
+ VectorSubtract(target, bs->origin, dir);
+ vectoangles(dir, bs->ideal_viewangles);
+ bs->ideal_viewangles[2] *= 0.5;
+ }
+ //check if the bot wants to go for air
+ if (BotGoForAir(bs, bs->tfl, &bs->teamgoal, 400)) {
+ trap_BotResetLastAvoidReach(bs->ms);
+ //get the goal at the top of the stack
+ //trap_BotGetTopGoal(bs->gs, &tmpgoal);
+ //trap_BotGoalName(tmpgoal.number, buf, 144);
+ //BotAI_Print(PRT_MESSAGE, "new nearby goal %s\n", buf);
+ //time the bot gets to pick up the nearby goal item
+ bs->nbg_time = FloatTime() + 8;
+ AIEnter_Seek_NBG(bs, "BotLongTermGoal: go for air");
+ return qfalse;
+ }
+ //
+ trap_BotResetAvoidReach(bs->ms);
+ return qfalse;
+ }
+ }
+ //if the entity information is valid (entity in PVS)
+ if (entinfo.valid) {
+ areanum = BotPointAreaNum(entinfo.origin);
+ if (areanum && trap_AAS_AreaReachability(areanum)) {
+ //update team goal
+ bs->teamgoal.entitynum = bs->teammate;
+ bs->teamgoal.areanum = areanum;
+ VectorCopy(entinfo.origin, bs->teamgoal.origin);
+ VectorSet(bs->teamgoal.mins, -8, -8, -8);
+ VectorSet(bs->teamgoal.maxs, 8, 8, 8);
+ }
+ }
+ //the goal the bot should go for
+ memcpy(goal, &bs->teamgoal, sizeof(bot_goal_t));
+ //if the companion is NOT visible for too long
+ if (bs->teammatevisible_time < FloatTime() - 60) {
+ BotAI_BotInitialChat(bs, "accompany_cannotfind", EasyClientName(bs->teammate, netname, sizeof(netname)), NULL);
+ trap_BotEnterChat(bs->cs, bs->teammate, CHAT_TELL);
+ bs->ltgtype = 0;
+ // just to make sure the bot won't spam this message
+ bs->teammatevisible_time = FloatTime();
+ }
+ return qtrue;
+ }
+ //
+ if (bs->ltgtype == LTG_DEFENDKEYAREA) {
+ if (trap_AAS_AreaTravelTimeToGoalArea(bs->areanum, bs->origin,
+ bs->teamgoal.areanum, TFL_DEFAULT) > bs->defendaway_range) {
+ bs->defendaway_time = 0;
+ }
+ }
+ //if defending a key area
+ if (bs->ltgtype == LTG_DEFENDKEYAREA && !retreat &&
+ bs->defendaway_time < FloatTime()) {
+ //check for bot typing status message
+ if (bs->teammessage_time && bs->teammessage_time < FloatTime()) {
+ trap_BotGoalName(bs->teamgoal.number, buf, sizeof(buf));
+ BotAI_BotInitialChat(bs, "defend_start", buf, NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_TEAM);
+ BotVoiceChatOnly(bs, -1, VOICECHAT_ONDEFENSE);
+ bs->teammessage_time = 0;
+ }
+ //set the bot goal
+ memcpy(goal, &bs->teamgoal, sizeof(bot_goal_t));
+ //stop after 2 minutes
+ if (bs->teamgoal_time < FloatTime()) {
+ trap_BotGoalName(bs->teamgoal.number, buf, sizeof(buf));
+ BotAI_BotInitialChat(bs, "defend_stop", buf, NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_TEAM);
+ bs->ltgtype = 0;
+ }
+ //if very close... go away for some time
+ VectorSubtract(goal->origin, bs->origin, dir);
+ if (VectorLengthSquared(dir) < Square(70)) {
+ trap_BotResetAvoidReach(bs->ms);
+ bs->defendaway_time = FloatTime() + 3 + 3 * random();
+ if (BotHasPersistantPowerupAndWeapon(bs)) {
+ bs->defendaway_range = 100;
+ }
+ else {
+ bs->defendaway_range = 350;
+ }
+ }
+ return qtrue;
+ }
+ //going to kill someone
+ if (bs->ltgtype == LTG_KILL && !retreat) {
+ //check for bot typing status message
+ if (bs->teammessage_time && bs->teammessage_time < FloatTime()) {
+ EasyClientName(bs->teamgoal.entitynum, buf, sizeof(buf));
+ BotAI_BotInitialChat(bs, "kill_start", buf, NULL);
+ trap_BotEnterChat(bs->cs, bs->decisionmaker, CHAT_TELL);
+ bs->teammessage_time = 0;
+ }
+ //
+ if (bs->lastkilledplayer == bs->teamgoal.entitynum) {
+ EasyClientName(bs->teamgoal.entitynum, buf, sizeof(buf));
+ BotAI_BotInitialChat(bs, "kill_done", buf, NULL);
+ trap_BotEnterChat(bs->cs, bs->decisionmaker, CHAT_TELL);
+ bs->lastkilledplayer = -1;
+ bs->ltgtype = 0;
+ }
+ //
+ if (bs->teamgoal_time < FloatTime()) {
+ bs->ltgtype = 0;
+ }
+ //just roam around
+ return BotGetItemLongTermGoal(bs, tfl, goal);
+ }
+ //get an item
+ if (bs->ltgtype == LTG_GETITEM && !retreat) {
+ //check for bot typing status message
+ if (bs->teammessage_time && bs->teammessage_time < FloatTime()) {
+ trap_BotGoalName(bs->teamgoal.number, buf, sizeof(buf));
+ BotAI_BotInitialChat(bs, "getitem_start", buf, NULL);
+ trap_BotEnterChat(bs->cs, bs->decisionmaker, CHAT_TELL);
+ BotVoiceChatOnly(bs, bs->decisionmaker, VOICECHAT_YES);
+ trap_EA_Action(bs->client, ACTION_AFFIRMATIVE);
+ bs->teammessage_time = 0;
+ }
+ //set the bot goal
+ memcpy(goal, &bs->teamgoal, sizeof(bot_goal_t));
+ //stop after some time
+ if (bs->teamgoal_time < FloatTime()) {
+ bs->ltgtype = 0;
+ }
+ //
+ if (trap_BotItemGoalInVisButNotVisible(bs->entitynum, bs->eye, bs->viewangles, goal)) {
+ trap_BotGoalName(bs->teamgoal.number, buf, sizeof(buf));
+ BotAI_BotInitialChat(bs, "getitem_notthere", buf, NULL);
+ trap_BotEnterChat(bs->cs, bs->decisionmaker, CHAT_TELL);
+ bs->ltgtype = 0;
+ }
+ else if (BotReachedGoal(bs, goal)) {
+ trap_BotGoalName(bs->teamgoal.number, buf, sizeof(buf));
+ BotAI_BotInitialChat(bs, "getitem_gotit", buf, NULL);
+ trap_BotEnterChat(bs->cs, bs->decisionmaker, CHAT_TELL);
+ bs->ltgtype = 0;
+ }
+ return qtrue;
+ }
+ //if camping somewhere
+ if ((bs->ltgtype == LTG_CAMP || bs->ltgtype == LTG_CAMPORDER) && !retreat) {
+ //check for bot typing status message
+ if (bs->teammessage_time && bs->teammessage_time < FloatTime()) {
+ if (bs->ltgtype == LTG_CAMPORDER) {
+ BotAI_BotInitialChat(bs, "camp_start", EasyClientName(bs->teammate, netname, sizeof(netname)), NULL);
+ trap_BotEnterChat(bs->cs, bs->decisionmaker, CHAT_TELL);
+ BotVoiceChatOnly(bs, bs->decisionmaker, VOICECHAT_YES);
+ trap_EA_Action(bs->client, ACTION_AFFIRMATIVE);
+ }
+ bs->teammessage_time = 0;
+ }
+ //set the bot goal
+ memcpy(goal, &bs->teamgoal, sizeof(bot_goal_t));
+ //
+ if (bs->teamgoal_time < FloatTime()) {
+ if (bs->ltgtype == LTG_CAMPORDER) {
+ BotAI_BotInitialChat(bs, "camp_stop", NULL);
+ trap_BotEnterChat(bs->cs, bs->decisionmaker, CHAT_TELL);
+ }
+ bs->ltgtype = 0;
+ }
+ //if really near the camp spot
+ VectorSubtract(goal->origin, bs->origin, dir);
+ if (VectorLengthSquared(dir) < Square(60))
+ {
+ //if not arrived yet
+ if (!bs->arrive_time) {
+ if (bs->ltgtype == LTG_CAMPORDER) {
+ BotAI_BotInitialChat(bs, "camp_arrive", EasyClientName(bs->teammate, netname, sizeof(netname)), NULL);
+ trap_BotEnterChat(bs->cs, bs->decisionmaker, CHAT_TELL);
+ BotVoiceChatOnly(bs, bs->decisionmaker, VOICECHAT_INPOSITION);
+ }
+ bs->arrive_time = FloatTime();
+ }
+ //look strategically around for enemies
+ if (random() < bs->thinktime * 0.8) {
+ BotRoamGoal(bs, target);
+ VectorSubtract(target, bs->origin, dir);
+ vectoangles(dir, bs->ideal_viewangles);
+ bs->ideal_viewangles[2] *= 0.5;
+ }
+ //check if the bot wants to crouch
+ //don't crouch if crouched less than 5 seconds ago
+ if (bs->attackcrouch_time < FloatTime() - 5) {
+ croucher = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_CROUCHER, 0, 1);
+ if (random() < bs->thinktime * croucher) {
+ bs->attackcrouch_time = FloatTime() + 5 + croucher * 15;
+ }
+ }
+ //if the bot wants to crouch
+ if (bs->attackcrouch_time > FloatTime()) {
+ trap_EA_Crouch(bs->client);
+ }
+ //don't crouch when swimming
+ if (trap_AAS_Swimming(bs->origin)) bs->attackcrouch_time = FloatTime() - 1;
+ //make sure the bot is not gonna drown
+ if (trap_PointContents(bs->eye,bs->entitynum) & (CONTENTS_WATER|CONTENTS_SLIME|CONTENTS_LAVA)) {
+ if (bs->ltgtype == LTG_CAMPORDER) {
+ BotAI_BotInitialChat(bs, "camp_stop", NULL);
+ trap_BotEnterChat(bs->cs, bs->decisionmaker, CHAT_TELL);
+ //
+ if (bs->lastgoal_ltgtype == LTG_CAMPORDER) {
+ bs->lastgoal_ltgtype = 0;
+ }
+ }
+ bs->ltgtype = 0;
+ }
+ //
+ if (bs->camp_range > 0) {
+ //FIXME: move around a bit
+ }
+ //
+ trap_BotResetAvoidReach(bs->ms);
+ return qfalse;
+ }
+ return qtrue;
+ }
+ //patrolling along several waypoints
+ if (bs->ltgtype == LTG_PATROL && !retreat) {
+ //check for bot typing status message
+ if (bs->teammessage_time && bs->teammessage_time < FloatTime()) {
+ strcpy(buf, "");
+ for (wp = bs->patrolpoints; wp; wp = wp->next) {
+ strcat(buf, wp->name);
+ if (wp->next) strcat(buf, " to ");
+ }
+ BotAI_BotInitialChat(bs, "patrol_start", buf, NULL);
+ trap_BotEnterChat(bs->cs, bs->decisionmaker, CHAT_TELL);
+ BotVoiceChatOnly(bs, bs->decisionmaker, VOICECHAT_YES);
+ trap_EA_Action(bs->client, ACTION_AFFIRMATIVE);
+ bs->teammessage_time = 0;
+ }
+ //
+ if (!bs->curpatrolpoint) {
+ bs->ltgtype = 0;
+ return qfalse;
+ }
+ //if the bot touches the current goal
+ if (trap_BotTouchingGoal(bs->origin, &bs->curpatrolpoint->goal)) {
+ if (bs->patrolflags & PATROL_BACK) {
+ if (bs->curpatrolpoint->prev) {
+ bs->curpatrolpoint = bs->curpatrolpoint->prev;
+ }
+ else {
+ bs->curpatrolpoint = bs->curpatrolpoint->next;
+ bs->patrolflags &= ~PATROL_BACK;
+ }
+ }
+ else {
+ if (bs->curpatrolpoint->next) {
+ bs->curpatrolpoint = bs->curpatrolpoint->next;
+ }
+ else {
+ bs->curpatrolpoint = bs->curpatrolpoint->prev;
+ bs->patrolflags |= PATROL_BACK;
+ }
+ }
+ }
+ //stop after 5 minutes
+ if (bs->teamgoal_time < FloatTime()) {
+ BotAI_BotInitialChat(bs, "patrol_stop", NULL);
+ trap_BotEnterChat(bs->cs, bs->decisionmaker, CHAT_TELL);
+ bs->ltgtype = 0;
+ }
+ if (!bs->curpatrolpoint) {
+ bs->ltgtype = 0;
+ return qfalse;
+ }
+ memcpy(goal, &bs->curpatrolpoint->goal, sizeof(bot_goal_t));
+ return qtrue;
+ }
+#ifdef CTF
+ if (gametype == GT_CTF) {
+ //if going for enemy flag
+ if (bs->ltgtype == LTG_GETFLAG) {
+ //check for bot typing status message
+ if (bs->teammessage_time && bs->teammessage_time < FloatTime()) {
+ BotAI_BotInitialChat(bs, "captureflag_start", NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_TEAM);
+ BotVoiceChatOnly(bs, -1, VOICECHAT_ONGETFLAG);
+ bs->teammessage_time = 0;
+ }
+ //
+ switch(BotTeam(bs)) {
+ case TEAM_RED: memcpy(goal, &ctf_blueflag, sizeof(bot_goal_t)); break;
+ case TEAM_BLUE: memcpy(goal, &ctf_redflag, sizeof(bot_goal_t)); break;
+ default: bs->ltgtype = 0; return qfalse;
+ }
+ //if touching the flag
+ if (trap_BotTouchingGoal(bs->origin, goal)) {
+ // make sure the bot knows the flag isn't there anymore
+ switch(BotTeam(bs)) {
+ case TEAM_RED: bs->blueflagstatus = 1; break;
+ case TEAM_BLUE: bs->redflagstatus = 1; break;
+ }
+ bs->ltgtype = 0;
+ }
+ //stop after 3 minutes
+ if (bs->teamgoal_time < FloatTime()) {
+ bs->ltgtype = 0;
+ }
+ BotAlternateRoute(bs, goal);
+ return qtrue;
+ }
+ //if rushing to the base
+ if (bs->ltgtype == LTG_RUSHBASE && bs->rushbaseaway_time < FloatTime()) {
+ switch(BotTeam(bs)) {
+ case TEAM_RED: memcpy(goal, &ctf_redflag, sizeof(bot_goal_t)); break;
+ case TEAM_BLUE: memcpy(goal, &ctf_blueflag, sizeof(bot_goal_t)); break;
+ default: bs->ltgtype = 0; return qfalse;
+ }
+ //if not carrying the flag anymore
+ if (!BotCTFCarryingFlag(bs)) bs->ltgtype = 0;
+ //quit rushing after 2 minutes
+ if (bs->teamgoal_time < FloatTime()) bs->ltgtype = 0;
+ //if touching the base flag the bot should loose the enemy flag
+ if (trap_BotTouchingGoal(bs->origin, goal)) {
+ //if the bot is still carrying the enemy flag then the
+ //base flag is gone, now just walk near the base a bit
+ if (BotCTFCarryingFlag(bs)) {
+ trap_BotResetAvoidReach(bs->ms);
+ bs->rushbaseaway_time = FloatTime() + 5 + 10 * random();
+ //FIXME: add chat to tell the others to get back the flag
+ }
+ else {
+ bs->ltgtype = 0;
+ }
+ }
+ BotAlternateRoute(bs, goal);
+ return qtrue;
+ }
+ //returning flag
+ if (bs->ltgtype == LTG_RETURNFLAG) {
+ //check for bot typing status message
+ if (bs->teammessage_time && bs->teammessage_time < FloatTime()) {
+ BotAI_BotInitialChat(bs, "returnflag_start", NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_TEAM);
+ BotVoiceChatOnly(bs, -1, VOICECHAT_ONRETURNFLAG);
+ bs->teammessage_time = 0;
+ }
+ //
+ switch(BotTeam(bs)) {
+ case TEAM_RED: memcpy(goal, &ctf_blueflag, sizeof(bot_goal_t)); break;
+ case TEAM_BLUE: memcpy(goal, &ctf_redflag, sizeof(bot_goal_t)); break;
+ default: bs->ltgtype = 0; return qfalse;
+ }
+ //if touching the flag
+ if (trap_BotTouchingGoal(bs->origin, goal)) bs->ltgtype = 0;
+ //stop after 3 minutes
+ if (bs->teamgoal_time < FloatTime()) {
+ bs->ltgtype = 0;
+ }
+ BotAlternateRoute(bs, goal);
+ return qtrue;
+ }
+ }
+#endif //CTF
+#ifdef MISSIONPACK
+ else if (gametype == GT_1FCTF) {
+ if (bs->ltgtype == LTG_GETFLAG) {
+ //check for bot typing status message
+ if (bs->teammessage_time && bs->teammessage_time < FloatTime()) {
+ BotAI_BotInitialChat(bs, "captureflag_start", NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_TEAM);
+ BotVoiceChatOnly(bs, -1, VOICECHAT_ONGETFLAG);
+ bs->teammessage_time = 0;
+ }
+ memcpy(goal, &ctf_neutralflag, sizeof(bot_goal_t));
+ //if touching the flag
+ if (trap_BotTouchingGoal(bs->origin, goal)) {
+ bs->ltgtype = 0;
+ }
+ //stop after 3 minutes
+ if (bs->teamgoal_time < FloatTime()) {
+ bs->ltgtype = 0;
+ }
+ return qtrue;
+ }
+ //if rushing to the base
+ if (bs->ltgtype == LTG_RUSHBASE) {
+ switch(BotTeam(bs)) {
+ case TEAM_RED: memcpy(goal, &ctf_blueflag, sizeof(bot_goal_t)); break;
+ case TEAM_BLUE: memcpy(goal, &ctf_redflag, sizeof(bot_goal_t)); break;
+ default: bs->ltgtype = 0; return qfalse;
+ }
+ //if not carrying the flag anymore
+ if (!Bot1FCTFCarryingFlag(bs)) {
+ bs->ltgtype = 0;
+ }
+ //quit rushing after 2 minutes
+ if (bs->teamgoal_time < FloatTime()) {
+ bs->ltgtype = 0;
+ }
+ //if touching the base flag the bot should loose the enemy flag
+ if (trap_BotTouchingGoal(bs->origin, goal)) {
+ bs->ltgtype = 0;
+ }
+ BotAlternateRoute(bs, goal);
+ return qtrue;
+ }
+ //attack the enemy base
+ if (bs->ltgtype == LTG_ATTACKENEMYBASE &&
+ bs->attackaway_time < FloatTime()) {
+ //check for bot typing status message
+ if (bs->teammessage_time && bs->teammessage_time < FloatTime()) {
+ BotAI_BotInitialChat(bs, "attackenemybase_start", NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_TEAM);
+ BotVoiceChatOnly(bs, -1, VOICECHAT_ONOFFENSE);
+ bs->teammessage_time = 0;
+ }
+ switch(BotTeam(bs)) {
+ case TEAM_RED: memcpy(goal, &ctf_blueflag, sizeof(bot_goal_t)); break;
+ case TEAM_BLUE: memcpy(goal, &ctf_redflag, sizeof(bot_goal_t)); break;
+ default: bs->ltgtype = 0; return qfalse;
+ }
+ //quit rushing after 2 minutes
+ if (bs->teamgoal_time < FloatTime()) {
+ bs->ltgtype = 0;
+ }
+ //if touching the base flag the bot should loose the enemy flag
+ if (trap_BotTouchingGoal(bs->origin, goal)) {
+ bs->attackaway_time = FloatTime() + 2 + 5 * random();
+ }
+ return qtrue;
+ }
+ //returning flag
+ if (bs->ltgtype == LTG_RETURNFLAG) {
+ //check for bot typing status message
+ if (bs->teammessage_time && bs->teammessage_time < FloatTime()) {
+ BotAI_BotInitialChat(bs, "returnflag_start", NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_TEAM);
+ BotVoiceChatOnly(bs, -1, VOICECHAT_ONRETURNFLAG);
+ bs->teammessage_time = 0;
+ }
+ //
+ if (bs->teamgoal_time < FloatTime()) {
+ bs->ltgtype = 0;
+ }
+ //just roam around
+ return BotGetItemLongTermGoal(bs, tfl, goal);
+ }
+ }
+ else if (gametype == GT_OBELISK) {
+ if (bs->ltgtype == LTG_ATTACKENEMYBASE &&
+ bs->attackaway_time < FloatTime()) {
+
+ //check for bot typing status message
+ if (bs->teammessage_time && bs->teammessage_time < FloatTime()) {
+ BotAI_BotInitialChat(bs, "attackenemybase_start", NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_TEAM);
+ BotVoiceChatOnly(bs, -1, VOICECHAT_ONOFFENSE);
+ bs->teammessage_time = 0;
+ }
+ switch(BotTeam(bs)) {
+ case TEAM_RED: memcpy(goal, &blueobelisk, sizeof(bot_goal_t)); break;
+ case TEAM_BLUE: memcpy(goal, &redobelisk, sizeof(bot_goal_t)); break;
+ default: bs->ltgtype = 0; return qfalse;
+ }
+ //if the bot no longer wants to attack the obelisk
+ if (BotFeelingBad(bs) > 50) {
+ return BotGetItemLongTermGoal(bs, tfl, goal);
+ }
+ //if touching the obelisk
+ if (trap_BotTouchingGoal(bs->origin, goal)) {
+ bs->attackaway_time = FloatTime() + 3 + 5 * random();
+ }
+ // or very close to the obelisk
+ VectorSubtract(bs->origin, goal->origin, dir);
+ if (VectorLengthSquared(dir) < Square(60)) {
+ bs->attackaway_time = FloatTime() + 3 + 5 * random();
+ }
+ //quit rushing after 2 minutes
+ if (bs->teamgoal_time < FloatTime()) {
+ bs->ltgtype = 0;
+ }
+ BotAlternateRoute(bs, goal);
+ //just move towards the obelisk
+ return qtrue;
+ }
+ }
+ else if (gametype == GT_HARVESTER) {
+ //if rushing to the base
+ if (bs->ltgtype == LTG_RUSHBASE) {
+ switch(BotTeam(bs)) {
+ case TEAM_RED: memcpy(goal, &blueobelisk, sizeof(bot_goal_t)); break;
+ case TEAM_BLUE: memcpy(goal, &redobelisk, sizeof(bot_goal_t)); break;
+ default: BotGoHarvest(bs); return qfalse;
+ }
+ //if not carrying any cubes
+ if (!BotHarvesterCarryingCubes(bs)) {
+ BotGoHarvest(bs);
+ return qfalse;
+ }
+ //quit rushing after 2 minutes
+ if (bs->teamgoal_time < FloatTime()) {
+ BotGoHarvest(bs);
+ return qfalse;
+ }
+ //if touching the base flag the bot should loose the enemy flag
+ if (trap_BotTouchingGoal(bs->origin, goal)) {
+ BotGoHarvest(bs);
+ return qfalse;
+ }
+ BotAlternateRoute(bs, goal);
+ return qtrue;
+ }
+ //attack the enemy base
+ if (bs->ltgtype == LTG_ATTACKENEMYBASE &&
+ bs->attackaway_time < FloatTime()) {
+ //check for bot typing status message
+ if (bs->teammessage_time && bs->teammessage_time < FloatTime()) {
+ BotAI_BotInitialChat(bs, "attackenemybase_start", NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_TEAM);
+ BotVoiceChatOnly(bs, -1, VOICECHAT_ONOFFENSE);
+ bs->teammessage_time = 0;
+ }
+ switch(BotTeam(bs)) {
+ case TEAM_RED: memcpy(goal, &blueobelisk, sizeof(bot_goal_t)); break;
+ case TEAM_BLUE: memcpy(goal, &redobelisk, sizeof(bot_goal_t)); break;
+ default: bs->ltgtype = 0; return qfalse;
+ }
+ //quit rushing after 2 minutes
+ if (bs->teamgoal_time < FloatTime()) {
+ bs->ltgtype = 0;
+ }
+ //if touching the base flag the bot should loose the enemy flag
+ if (trap_BotTouchingGoal(bs->origin, goal)) {
+ bs->attackaway_time = FloatTime() + 2 + 5 * random();
+ }
+ return qtrue;
+ }
+ //harvest cubes
+ if (bs->ltgtype == LTG_HARVEST &&
+ bs->harvestaway_time < FloatTime()) {
+ //check for bot typing status message
+ if (bs->teammessage_time && bs->teammessage_time < FloatTime()) {
+ BotAI_BotInitialChat(bs, "harvest_start", NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_TEAM);
+ BotVoiceChatOnly(bs, -1, VOICECHAT_ONOFFENSE);
+ bs->teammessage_time = 0;
+ }
+ memcpy(goal, &neutralobelisk, sizeof(bot_goal_t));
+ //
+ if (bs->teamgoal_time < FloatTime()) {
+ bs->ltgtype = 0;
+ }
+ //
+ if (trap_BotTouchingGoal(bs->origin, goal)) {
+ bs->harvestaway_time = FloatTime() + 4 + 3 * random();
+ }
+ return qtrue;
+ }
+ }
+#endif
+ //normal goal stuff
+ return BotGetItemLongTermGoal(bs, tfl, goal);
+}
+
+/*
+==================
+BotLongTermGoal
+==================
+*/
+int BotLongTermGoal(bot_state_t *bs, int tfl, int retreat, bot_goal_t *goal) {
+ aas_entityinfo_t entinfo;
+ char teammate[MAX_MESSAGE_SIZE];
+ float squaredist;
+ int areanum;
+ vec3_t dir;
+
+ //FIXME: also have air long term goals?
+ //
+ //if the bot is leading someone and not retreating
+ if (bs->lead_time > 0 && !retreat) {
+ if (bs->lead_time < FloatTime()) {
+ BotAI_BotInitialChat(bs, "lead_stop", EasyClientName(bs->lead_teammate, teammate, sizeof(teammate)), NULL);
+ trap_BotEnterChat(bs->cs, bs->teammate, CHAT_TELL);
+ bs->lead_time = 0;
+ return BotGetLongTermGoal(bs, tfl, retreat, goal);
+ }
+ //
+ if (bs->leadmessage_time < 0 && -bs->leadmessage_time < FloatTime()) {
+ BotAI_BotInitialChat(bs, "followme", EasyClientName(bs->lead_teammate, teammate, sizeof(teammate)), NULL);
+ trap_BotEnterChat(bs->cs, bs->teammate, CHAT_TELL);
+ bs->leadmessage_time = FloatTime();
+ }
+ //get entity information of the companion
+ BotEntityInfo(bs->lead_teammate, &entinfo);
+ //
+ if (entinfo.valid) {
+ areanum = BotPointAreaNum(entinfo.origin);
+ if (areanum && trap_AAS_AreaReachability(areanum)) {
+ //update team goal
+ bs->lead_teamgoal.entitynum = bs->lead_teammate;
+ bs->lead_teamgoal.areanum = areanum;
+ VectorCopy(entinfo.origin, bs->lead_teamgoal.origin);
+ VectorSet(bs->lead_teamgoal.mins, -8, -8, -8);
+ VectorSet(bs->lead_teamgoal.maxs, 8, 8, 8);
+ }
+ }
+ //if the team mate is visible
+ if (BotEntityVisible(bs->entitynum, bs->eye, bs->viewangles, 360, bs->lead_teammate)) {
+ bs->leadvisible_time = FloatTime();
+ }
+ //if the team mate is not visible for 1 seconds
+ if (bs->leadvisible_time < FloatTime() - 1) {
+ bs->leadbackup_time = FloatTime() + 2;
+ }
+ //distance towards the team mate
+ VectorSubtract(bs->origin, bs->lead_teamgoal.origin, dir);
+ squaredist = VectorLengthSquared(dir);
+ //if backing up towards the team mate
+ if (bs->leadbackup_time > FloatTime()) {
+ if (bs->leadmessage_time < FloatTime() - 20) {
+ BotAI_BotInitialChat(bs, "followme", EasyClientName(bs->lead_teammate, teammate, sizeof(teammate)), NULL);
+ trap_BotEnterChat(bs->cs, bs->teammate, CHAT_TELL);
+ bs->leadmessage_time = FloatTime();
+ }
+ //if very close to the team mate
+ if (squaredist < Square(100)) {
+ bs->leadbackup_time = 0;
+ }
+ //the bot should go back to the team mate
+ memcpy(goal, &bs->lead_teamgoal, sizeof(bot_goal_t));
+ return qtrue;
+ }
+ else {
+ //if quite distant from the team mate
+ if (squaredist > Square(500)) {
+ if (bs->leadmessage_time < FloatTime() - 20) {
+ BotAI_BotInitialChat(bs, "followme", EasyClientName(bs->lead_teammate, teammate, sizeof(teammate)), NULL);
+ trap_BotEnterChat(bs->cs, bs->teammate, CHAT_TELL);
+ bs->leadmessage_time = FloatTime();
+ }
+ //look at the team mate
+ VectorSubtract(entinfo.origin, bs->origin, dir);
+ vectoangles(dir, bs->ideal_viewangles);
+ bs->ideal_viewangles[2] *= 0.5;
+ //just wait for the team mate
+ return qfalse;
+ }
+ }
+ }
+ return BotGetLongTermGoal(bs, tfl, retreat, goal);
+}
+
+/*
+==================
+AIEnter_Intermission
+==================
+*/
+void AIEnter_Intermission(bot_state_t *bs, char *s) {
+ BotRecordNodeSwitch(bs, "intermission", "", s);
+ //reset the bot state
+ BotResetState(bs);
+ //check for end level chat
+ if (BotChat_EndLevel(bs)) {
+ trap_BotEnterChat(bs->cs, 0, bs->chatto);
+ }
+ bs->ainode = AINode_Intermission;
+}
+
+/*
+==================
+AINode_Intermission
+==================
+*/
+int AINode_Intermission(bot_state_t *bs) {
+ //if the intermission ended
+ if (!BotIntermission(bs)) {
+ if (BotChat_StartLevel(bs)) {
+ bs->stand_time = FloatTime() + BotChatTime(bs);
+ }
+ else {
+ bs->stand_time = FloatTime() + 2;
+ }
+ AIEnter_Stand(bs, "intermission: chat");
+ }
+ return qtrue;
+}
+
+/*
+==================
+AIEnter_Observer
+==================
+*/
+void AIEnter_Observer(bot_state_t *bs, char *s) {
+ BotRecordNodeSwitch(bs, "observer", "", s);
+ //reset the bot state
+ BotResetState(bs);
+ bs->ainode = AINode_Observer;
+}
+
+/*
+==================
+AINode_Observer
+==================
+*/
+int AINode_Observer(bot_state_t *bs) {
+ //if the bot left observer mode
+ if (!BotIsObserver(bs)) {
+ AIEnter_Stand(bs, "observer: left observer");
+ }
+ return qtrue;
+}
+
+/*
+==================
+AIEnter_Stand
+==================
+*/
+void AIEnter_Stand(bot_state_t *bs, char *s) {
+ BotRecordNodeSwitch(bs, "stand", "", s);
+ bs->standfindenemy_time = FloatTime() + 1;
+ bs->ainode = AINode_Stand;
+}
+
+/*
+==================
+AINode_Stand
+==================
+*/
+int AINode_Stand(bot_state_t *bs) {
+
+ //if the bot's health decreased
+ if (bs->lastframe_health > bs->inventory[INVENTORY_HEALTH]) {
+ if (BotChat_HitTalking(bs)) {
+ bs->standfindenemy_time = FloatTime() + BotChatTime(bs) + 0.1;
+ bs->stand_time = FloatTime() + BotChatTime(bs) + 0.1;
+ }
+ }
+ if (bs->standfindenemy_time < FloatTime()) {
+ if (BotFindEnemy(bs, -1)) {
+ AIEnter_Battle_Fight(bs, "stand: found enemy");
+ return qfalse;
+ }
+ bs->standfindenemy_time = FloatTime() + 1;
+ }
+ // put up chat icon
+ trap_EA_Talk(bs->client);
+ // when done standing
+ if (bs->stand_time < FloatTime()) {
+ trap_BotEnterChat(bs->cs, 0, bs->chatto);
+ AIEnter_Seek_LTG(bs, "stand: time out");
+ return qfalse;
+ }
+ //
+ return qtrue;
+}
+
+/*
+==================
+AIEnter_Respawn
+==================
+*/
+void AIEnter_Respawn(bot_state_t *bs, char *s) {
+ BotRecordNodeSwitch(bs, "respawn", "", s);
+ //reset some states
+ trap_BotResetMoveState(bs->ms);
+ trap_BotResetGoalState(bs->gs);
+ trap_BotResetAvoidGoals(bs->gs);
+ trap_BotResetAvoidReach(bs->ms);
+ //if the bot wants to chat
+ if (BotChat_Death(bs)) {
+ bs->respawn_time = FloatTime() + BotChatTime(bs);
+ bs->respawnchat_time = FloatTime();
+ }
+ else {
+ bs->respawn_time = FloatTime() + 1 + random();
+ bs->respawnchat_time = 0;
+ }
+ //set respawn state
+ bs->respawn_wait = qfalse;
+ bs->ainode = AINode_Respawn;
+}
+
+/*
+==================
+AINode_Respawn
+==================
+*/
+int AINode_Respawn(bot_state_t *bs) {
+ // if waiting for the actual respawn
+ if (bs->respawn_wait) {
+ if (!BotIsDead(bs)) {
+ AIEnter_Seek_LTG(bs, "respawn: respawned");
+ }
+ else {
+ trap_EA_Respawn(bs->client);
+ }
+ }
+ else if (bs->respawn_time < FloatTime()) {
+ // wait until respawned
+ bs->respawn_wait = qtrue;
+ // elementary action respawn
+ trap_EA_Respawn(bs->client);
+ //
+ if (bs->respawnchat_time) {
+ trap_BotEnterChat(bs->cs, 0, bs->chatto);
+ bs->enemy = -1;
+ }
+ }
+ if (bs->respawnchat_time && bs->respawnchat_time < FloatTime() - 0.5) {
+ trap_EA_Talk(bs->client);
+ }
+ //
+ return qtrue;
+}
+
+/*
+==================
+BotSelectActivateWeapon
+==================
+*/
+int BotSelectActivateWeapon(bot_state_t *bs) {
+ //
+ if (bs->inventory[INVENTORY_MACHINEGUN] > 0 && bs->inventory[INVENTORY_BULLETS] > 0)
+ return WEAPONINDEX_MACHINEGUN;
+ else if (bs->inventory[INVENTORY_SHOTGUN] > 0 && bs->inventory[INVENTORY_SHELLS] > 0)
+ return WEAPONINDEX_SHOTGUN;
+ else if (bs->inventory[INVENTORY_PLASMAGUN] > 0 && bs->inventory[INVENTORY_CELLS] > 0)
+ return WEAPONINDEX_PLASMAGUN;
+ else if (bs->inventory[INVENTORY_LIGHTNING] > 0 && bs->inventory[INVENTORY_LIGHTNINGAMMO] > 0)
+ return WEAPONINDEX_LIGHTNING;
+#ifdef MISSIONPACK
+ else if (bs->inventory[INVENTORY_CHAINGUN] > 0 && bs->inventory[INVENTORY_BELT] > 0)
+ return WEAPONINDEX_CHAINGUN;
+ else if (bs->inventory[INVENTORY_NAILGUN] > 0 && bs->inventory[INVENTORY_NAILS] > 0)
+ return WEAPONINDEX_NAILGUN;
+#endif
+ else if (bs->inventory[INVENTORY_RAILGUN] > 0 && bs->inventory[INVENTORY_SLUGS] > 0)
+ return WEAPONINDEX_RAILGUN;
+ else if (bs->inventory[INVENTORY_ROCKETLAUNCHER] > 0 && bs->inventory[INVENTORY_ROCKETS] > 0)
+ return WEAPONINDEX_ROCKET_LAUNCHER;
+ else if (bs->inventory[INVENTORY_BFG10K] > 0 && bs->inventory[INVENTORY_BFGAMMO] > 0)
+ return WEAPONINDEX_BFG;
+ else {
+ return -1;
+ }
+}
+
+/*
+==================
+BotClearPath
+
+ try to deactivate obstacles like proximity mines on the bot's path
+==================
+*/
+void BotClearPath(bot_state_t *bs, bot_moveresult_t *moveresult) {
+ int i, bestmine;
+ float dist, bestdist;
+ vec3_t target, dir;
+ bsp_trace_t bsptrace;
+ entityState_t state;
+
+ // if there is a dead body wearing kamikze nearby
+ if (bs->kamikazebody) {
+ // if the bot's view angles and weapon are not used for movement
+ if ( !(moveresult->flags & (MOVERESULT_MOVEMENTVIEW | MOVERESULT_MOVEMENTWEAPON)) ) {
+ //
+ BotAI_GetEntityState(bs->kamikazebody, &state);
+ VectorCopy(state.pos.trBase, target);
+ target[2] += 8;
+ VectorSubtract(target, bs->eye, dir);
+ vectoangles(dir, moveresult->ideal_viewangles);
+ //
+ moveresult->weapon = BotSelectActivateWeapon(bs);
+ if (moveresult->weapon == -1) {
+ // FIXME: run away!
+ moveresult->weapon = 0;
+ }
+ if (moveresult->weapon) {
+ //
+ moveresult->flags |= MOVERESULT_MOVEMENTWEAPON | MOVERESULT_MOVEMENTVIEW;
+ // if holding the right weapon
+ if (bs->cur_ps.weapon == moveresult->weapon) {
+ // if the bot is pretty close with it's aim
+ if (InFieldOfVision(bs->viewangles, 20, moveresult->ideal_viewangles)) {
+ //
+ BotAI_Trace(&bsptrace, bs->eye, NULL, NULL, target, bs->entitynum, MASK_SHOT);
+ // if the mine is visible from the current position
+ if (bsptrace.fraction >= 1.0 || bsptrace.ent == state.number) {
+ // shoot at the mine
+ trap_EA_Attack(bs->client);
+ }
+ }
+ }
+ }
+ }
+ }
+ if (moveresult->flags & MOVERESULT_BLOCKEDBYAVOIDSPOT) {
+ bs->blockedbyavoidspot_time = FloatTime() + 5;
+ }
+ // if blocked by an avoid spot and the view angles and weapon are used for movement
+ if (bs->blockedbyavoidspot_time > FloatTime() &&
+ !(moveresult->flags & (MOVERESULT_MOVEMENTVIEW | MOVERESULT_MOVEMENTWEAPON)) ) {
+ bestdist = 300;
+ bestmine = -1;
+ for (i = 0; i < bs->numproxmines; i++) {
+ BotAI_GetEntityState(bs->proxmines[i], &state);
+ VectorSubtract(state.pos.trBase, bs->origin, dir);
+ dist = VectorLength(dir);
+ if (dist < bestdist) {
+ bestdist = dist;
+ bestmine = i;
+ }
+ }
+ if (bestmine != -1) {
+ //
+ // state->generic1 == TEAM_RED || state->generic1 == TEAM_BLUE
+ //
+ // deactivate prox mines in the bot's path by shooting
+ // rockets or plasma cells etc. at them
+ BotAI_GetEntityState(bs->proxmines[bestmine], &state);
+ VectorCopy(state.pos.trBase, target);
+ target[2] += 2;
+ VectorSubtract(target, bs->eye, dir);
+ vectoangles(dir, moveresult->ideal_viewangles);
+ // if the bot has a weapon that does splash damage
+ if (bs->inventory[INVENTORY_PLASMAGUN] > 0 && bs->inventory[INVENTORY_CELLS] > 0)
+ moveresult->weapon = WEAPONINDEX_PLASMAGUN;
+ else if (bs->inventory[INVENTORY_ROCKETLAUNCHER] > 0 && bs->inventory[INVENTORY_ROCKETS] > 0)
+ moveresult->weapon = WEAPONINDEX_ROCKET_LAUNCHER;
+ else if (bs->inventory[INVENTORY_BFG10K] > 0 && bs->inventory[INVENTORY_BFGAMMO] > 0)
+ moveresult->weapon = WEAPONINDEX_BFG;
+ else {
+ moveresult->weapon = 0;
+ }
+ if (moveresult->weapon) {
+ //
+ moveresult->flags |= MOVERESULT_MOVEMENTWEAPON | MOVERESULT_MOVEMENTVIEW;
+ // if holding the right weapon
+ if (bs->cur_ps.weapon == moveresult->weapon) {
+ // if the bot is pretty close with it's aim
+ if (InFieldOfVision(bs->viewangles, 20, moveresult->ideal_viewangles)) {
+ //
+ BotAI_Trace(&bsptrace, bs->eye, NULL, NULL, target, bs->entitynum, MASK_SHOT);
+ // if the mine is visible from the current position
+ if (bsptrace.fraction >= 1.0 || bsptrace.ent == state.number) {
+ // shoot at the mine
+ trap_EA_Attack(bs->client);
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+/*
+==================
+AIEnter_Seek_ActivateEntity
+==================
+*/
+void AIEnter_Seek_ActivateEntity(bot_state_t *bs, char *s) {
+ BotRecordNodeSwitch(bs, "activate entity", "", s);
+ bs->ainode = AINode_Seek_ActivateEntity;
+}
+
+/*
+==================
+AINode_Seek_Activate_Entity
+==================
+*/
+int AINode_Seek_ActivateEntity(bot_state_t *bs) {
+ bot_goal_t *goal;
+ vec3_t target, dir, ideal_viewangles;
+ bot_moveresult_t moveresult;
+ int targetvisible;
+ bsp_trace_t bsptrace;
+ aas_entityinfo_t entinfo;
+
+ if (BotIsObserver(bs)) {
+ BotClearActivateGoalStack(bs);
+ AIEnter_Observer(bs, "active entity: observer");
+ return qfalse;
+ }
+ //if in the intermission
+ if (BotIntermission(bs)) {
+ BotClearActivateGoalStack(bs);
+ AIEnter_Intermission(bs, "activate entity: intermission");
+ return qfalse;
+ }
+ //respawn if dead
+ if (BotIsDead(bs)) {
+ BotClearActivateGoalStack(bs);
+ AIEnter_Respawn(bs, "activate entity: bot dead");
+ return qfalse;
+ }
+ //
+ bs->tfl = TFL_DEFAULT;
+ if (bot_grapple.integer) bs->tfl |= TFL_GRAPPLEHOOK;
+ // if in lava or slime the bot should be able to get out
+ if (BotInLavaOrSlime(bs)) bs->tfl |= TFL_LAVA|TFL_SLIME;
+ // map specific code
+ BotMapScripts(bs);
+ // no enemy
+ bs->enemy = -1;
+ // if the bot has no activate goal
+ if (!bs->activatestack) {
+ BotClearActivateGoalStack(bs);
+ AIEnter_Seek_NBG(bs, "activate entity: no goal");
+ return qfalse;
+ }
+ //
+ goal = &bs->activatestack->goal;
+ // initialize target being visible to false
+ targetvisible = qfalse;
+ // if the bot has to shoot at a target to activate something
+ if (bs->activatestack->shoot) {
+ //
+ BotAI_Trace(&bsptrace, bs->eye, NULL, NULL, bs->activatestack->target, bs->entitynum, MASK_SHOT);
+ // if the shootable entity is visible from the current position
+ if (bsptrace.fraction >= 1.0 || bsptrace.ent == goal->entitynum) {
+ targetvisible = qtrue;
+ // if holding the right weapon
+ if (bs->cur_ps.weapon == bs->activatestack->weapon) {
+ VectorSubtract(bs->activatestack->target, bs->eye, dir);
+ vectoangles(dir, ideal_viewangles);
+ // if the bot is pretty close with it's aim
+ if (InFieldOfVision(bs->viewangles, 20, ideal_viewangles)) {
+ trap_EA_Attack(bs->client);
+ }
+ }
+ }
+ }
+ // if the shoot target is visible
+ if (targetvisible) {
+ // get the entity info of the entity the bot is shooting at
+ BotEntityInfo(goal->entitynum, &entinfo);
+ // if the entity the bot shoots at moved
+ if (!VectorCompare(bs->activatestack->origin, entinfo.origin)) {
+#ifdef DEBUG
+ BotAI_Print(PRT_MESSAGE, "hit shootable button or trigger\n");
+#endif //DEBUG
+ bs->activatestack->time = 0;
+ }
+ // if the activate goal has been activated or the bot takes too long
+ if (bs->activatestack->time < FloatTime()) {
+ BotPopFromActivateGoalStack(bs);
+ // if there are more activate goals on the stack
+ if (bs->activatestack) {
+ bs->activatestack->time = FloatTime() + 10;
+ return qfalse;
+ }
+ AIEnter_Seek_NBG(bs, "activate entity: time out");
+ return qfalse;
+ }
+ memset(&moveresult, 0, sizeof(bot_moveresult_t));
+ }
+ else {
+ // if the bot has no goal
+ if (!goal) {
+ bs->activatestack->time = 0;
+ }
+ // if the bot does not have a shoot goal
+ else if (!bs->activatestack->shoot) {
+ //if the bot touches the current goal
+ if (trap_BotTouchingGoal(bs->origin, goal)) {
+#ifdef DEBUG
+ BotAI_Print(PRT_MESSAGE, "touched button or trigger\n");
+#endif //DEBUG
+ bs->activatestack->time = 0;
+ }
+ }
+ // if the activate goal has been activated or the bot takes too long
+ if (bs->activatestack->time < FloatTime()) {
+ BotPopFromActivateGoalStack(bs);
+ // if there are more activate goals on the stack
+ if (bs->activatestack) {
+ bs->activatestack->time = FloatTime() + 10;
+ return qfalse;
+ }
+ AIEnter_Seek_NBG(bs, "activate entity: activated");
+ return qfalse;
+ }
+ //predict obstacles
+ if (BotAIPredictObstacles(bs, goal))
+ return qfalse;
+ //initialize the movement state
+ BotSetupForMovement(bs);
+ //move towards the goal
+ trap_BotMoveToGoal(&moveresult, bs->ms, goal, bs->tfl);
+ //if the movement failed
+ if (moveresult.failure) {
+ //reset the avoid reach, otherwise bot is stuck in current area
+ trap_BotResetAvoidReach(bs->ms);
+ //
+ bs->activatestack->time = 0;
+ }
+ //check if the bot is blocked
+ BotAIBlocked(bs, &moveresult, qtrue);
+ }
+ //
+ BotClearPath(bs, &moveresult);
+ // if the bot has to shoot to activate
+ if (bs->activatestack->shoot) {
+ // if the view angles aren't yet used for the movement
+ if (!(moveresult.flags & MOVERESULT_MOVEMENTVIEW)) {
+ VectorSubtract(bs->activatestack->target, bs->eye, dir);
+ vectoangles(dir, moveresult.ideal_viewangles);
+ moveresult.flags |= MOVERESULT_MOVEMENTVIEW;
+ }
+ // if there's no weapon yet used for the movement
+ if (!(moveresult.flags & MOVERESULT_MOVEMENTWEAPON)) {
+ moveresult.flags |= MOVERESULT_MOVEMENTWEAPON;
+ //
+ bs->activatestack->weapon = BotSelectActivateWeapon(bs);
+ if (bs->activatestack->weapon == -1) {
+ //FIXME: find a decent weapon first
+ bs->activatestack->weapon = 0;
+ }
+ moveresult.weapon = bs->activatestack->weapon;
+ }
+ }
+ // if the ideal view angles are set for movement
+ if (moveresult.flags & (MOVERESULT_MOVEMENTVIEWSET|MOVERESULT_MOVEMENTVIEW|MOVERESULT_SWIMVIEW)) {
+ VectorCopy(moveresult.ideal_viewangles, bs->ideal_viewangles);
+ }
+ // if waiting for something
+ else if (moveresult.flags & MOVERESULT_WAITING) {
+ if (random() < bs->thinktime * 0.8) {
+ BotRoamGoal(bs, target);
+ VectorSubtract(target, bs->origin, dir);
+ vectoangles(dir, bs->ideal_viewangles);
+ bs->ideal_viewangles[2] *= 0.5;
+ }
+ }
+ else if (!(bs->flags & BFL_IDEALVIEWSET)) {
+ if (trap_BotMovementViewTarget(bs->ms, goal, bs->tfl, 300, target)) {
+ VectorSubtract(target, bs->origin, dir);
+ vectoangles(dir, bs->ideal_viewangles);
+ }
+ else {
+ vectoangles(moveresult.movedir, bs->ideal_viewangles);
+ }
+ bs->ideal_viewangles[2] *= 0.5;
+ }
+ // if the weapon is used for the bot movement
+ if (moveresult.flags & MOVERESULT_MOVEMENTWEAPON)
+ bs->weaponnum = moveresult.weapon;
+ // if there is an enemy
+ if (BotFindEnemy(bs, -1)) {
+ if (BotWantsToRetreat(bs)) {
+ //keep the current long term goal and retreat
+ AIEnter_Battle_NBG(bs, "activate entity: found enemy");
+ }
+ else {
+ trap_BotResetLastAvoidReach(bs->ms);
+ //empty the goal stack
+ trap_BotEmptyGoalStack(bs->gs);
+ //go fight
+ AIEnter_Battle_Fight(bs, "activate entity: found enemy");
+ }
+ BotClearActivateGoalStack(bs);
+ }
+ return qtrue;
+}
+
+/*
+==================
+AIEnter_Seek_NBG
+==================
+*/
+void AIEnter_Seek_NBG(bot_state_t *bs, char *s) {
+ bot_goal_t goal;
+ char buf[144];
+
+ if (trap_BotGetTopGoal(bs->gs, &goal)) {
+ trap_BotGoalName(goal.number, buf, 144);
+ BotRecordNodeSwitch(bs, "seek NBG", buf, s);
+ }
+ else {
+ BotRecordNodeSwitch(bs, "seek NBG", "no goal", s);
+ }
+ bs->ainode = AINode_Seek_NBG;
+}
+
+/*
+==================
+AINode_Seek_NBG
+==================
+*/
+int AINode_Seek_NBG(bot_state_t *bs) {
+ bot_goal_t goal;
+ vec3_t target, dir;
+ bot_moveresult_t moveresult;
+
+ if (BotIsObserver(bs)) {
+ AIEnter_Observer(bs, "seek nbg: observer");
+ return qfalse;
+ }
+ //if in the intermission
+ if (BotIntermission(bs)) {
+ AIEnter_Intermission(bs, "seek nbg: intermision");
+ return qfalse;
+ }
+ //respawn if dead
+ if (BotIsDead(bs)) {
+ AIEnter_Respawn(bs, "seek nbg: bot dead");
+ return qfalse;
+ }
+ //
+ bs->tfl = TFL_DEFAULT;
+ if (bot_grapple.integer) bs->tfl |= TFL_GRAPPLEHOOK;
+ //if in lava or slime the bot should be able to get out
+ if (BotInLavaOrSlime(bs)) bs->tfl |= TFL_LAVA|TFL_SLIME;
+ //
+ if (BotCanAndWantsToRocketJump(bs)) {
+ bs->tfl |= TFL_ROCKETJUMP;
+ }
+ //map specific code
+ BotMapScripts(bs);
+ //no enemy
+ bs->enemy = -1;
+ //if the bot has no goal
+ if (!trap_BotGetTopGoal(bs->gs, &goal)) bs->nbg_time = 0;
+ //if the bot touches the current goal
+ else if (BotReachedGoal(bs, &goal)) {
+ BotChooseWeapon(bs);
+ bs->nbg_time = 0;
+ }
+ //
+ if (bs->nbg_time < FloatTime()) {
+ //pop the current goal from the stack
+ trap_BotPopGoal(bs->gs);
+ //check for new nearby items right away
+ //NOTE: we canNOT reset the check_time to zero because it would create an endless loop of node switches
+ bs->check_time = FloatTime() + 0.05;
+ //go back to seek ltg
+ AIEnter_Seek_LTG(bs, "seek nbg: time out");
+ return qfalse;
+ }
+ //predict obstacles
+ if (BotAIPredictObstacles(bs, &goal))
+ return qfalse;
+ //initialize the movement state
+ BotSetupForMovement(bs);
+ //move towards the goal
+ trap_BotMoveToGoal(&moveresult, bs->ms, &goal, bs->tfl);
+ //if the movement failed
+ if (moveresult.failure) {
+ //reset the avoid reach, otherwise bot is stuck in current area
+ trap_BotResetAvoidReach(bs->ms);
+ bs->nbg_time = 0;
+ }
+ //check if the bot is blocked
+ BotAIBlocked(bs, &moveresult, qtrue);
+ //
+ BotClearPath(bs, &moveresult);
+ //if the viewangles are used for the movement
+ if (moveresult.flags & (MOVERESULT_MOVEMENTVIEWSET|MOVERESULT_MOVEMENTVIEW|MOVERESULT_SWIMVIEW)) {
+ VectorCopy(moveresult.ideal_viewangles, bs->ideal_viewangles);
+ }
+ //if waiting for something
+ else if (moveresult.flags & MOVERESULT_WAITING) {
+ if (random() < bs->thinktime * 0.8) {
+ BotRoamGoal(bs, target);
+ VectorSubtract(target, bs->origin, dir);
+ vectoangles(dir, bs->ideal_viewangles);
+ bs->ideal_viewangles[2] *= 0.5;
+ }
+ }
+ else if (!(bs->flags & BFL_IDEALVIEWSET)) {
+ if (!trap_BotGetSecondGoal(bs->gs, &goal)) trap_BotGetTopGoal(bs->gs, &goal);
+ if (trap_BotMovementViewTarget(bs->ms, &goal, bs->tfl, 300, target)) {
+ VectorSubtract(target, bs->origin, dir);
+ vectoangles(dir, bs->ideal_viewangles);
+ }
+ //FIXME: look at cluster portals?
+ else vectoangles(moveresult.movedir, bs->ideal_viewangles);
+ bs->ideal_viewangles[2] *= 0.5;
+ }
+ //if the weapon is used for the bot movement
+ if (moveresult.flags & MOVERESULT_MOVEMENTWEAPON) bs->weaponnum = moveresult.weapon;
+ //if there is an enemy
+ if (BotFindEnemy(bs, -1)) {
+ if (BotWantsToRetreat(bs)) {
+ //keep the current long term goal and retreat
+ AIEnter_Battle_NBG(bs, "seek nbg: found enemy");
+ }
+ else {
+ trap_BotResetLastAvoidReach(bs->ms);
+ //empty the goal stack
+ trap_BotEmptyGoalStack(bs->gs);
+ //go fight
+ AIEnter_Battle_Fight(bs, "seek nbg: found enemy");
+ }
+ }
+ return qtrue;
+}
+
+/*
+==================
+AIEnter_Seek_LTG
+==================
+*/
+void AIEnter_Seek_LTG(bot_state_t *bs, char *s) {
+ bot_goal_t goal;
+ char buf[144];
+
+ if (trap_BotGetTopGoal(bs->gs, &goal)) {
+ trap_BotGoalName(goal.number, buf, 144);
+ BotRecordNodeSwitch(bs, "seek LTG", buf, s);
+ }
+ else {
+ BotRecordNodeSwitch(bs, "seek LTG", "no goal", s);
+ }
+ bs->ainode = AINode_Seek_LTG;
+}
+
+/*
+==================
+AINode_Seek_LTG
+==================
+*/
+int AINode_Seek_LTG(bot_state_t *bs)
+{
+ bot_goal_t goal;
+ vec3_t target, dir;
+ bot_moveresult_t moveresult;
+ int range;
+ //char buf[128];
+ //bot_goal_t tmpgoal;
+
+ if (BotIsObserver(bs)) {
+ AIEnter_Observer(bs, "seek ltg: observer");
+ return qfalse;
+ }
+ //if in the intermission
+ if (BotIntermission(bs)) {
+ AIEnter_Intermission(bs, "seek ltg: intermission");
+ return qfalse;
+ }
+ //respawn if dead
+ if (BotIsDead(bs)) {
+ AIEnter_Respawn(bs, "seek ltg: bot dead");
+ return qfalse;
+ }
+ //
+ if (BotChat_Random(bs)) {
+ bs->stand_time = FloatTime() + BotChatTime(bs);
+ AIEnter_Stand(bs, "seek ltg: random chat");
+ return qfalse;
+ }
+ //
+ bs->tfl = TFL_DEFAULT;
+ if (bot_grapple.integer) bs->tfl |= TFL_GRAPPLEHOOK;
+ //if in lava or slime the bot should be able to get out
+ if (BotInLavaOrSlime(bs)) bs->tfl |= TFL_LAVA|TFL_SLIME;
+ //
+ if (BotCanAndWantsToRocketJump(bs)) {
+ bs->tfl |= TFL_ROCKETJUMP;
+ }
+ //map specific code
+ BotMapScripts(bs);
+ //no enemy
+ bs->enemy = -1;
+ //
+ if (bs->killedenemy_time > FloatTime() - 2) {
+ if (random() < bs->thinktime * 1) {
+ trap_EA_Gesture(bs->client);
+ }
+ }
+ //if there is an enemy
+ if (BotFindEnemy(bs, -1)) {
+ if (BotWantsToRetreat(bs)) {
+ //keep the current long term goal and retreat
+ AIEnter_Battle_Retreat(bs, "seek ltg: found enemy");
+ return qfalse;
+ }
+ else {
+ trap_BotResetLastAvoidReach(bs->ms);
+ //empty the goal stack
+ trap_BotEmptyGoalStack(bs->gs);
+ //go fight
+ AIEnter_Battle_Fight(bs, "seek ltg: found enemy");
+ return qfalse;
+ }
+ }
+ //
+ BotTeamGoals(bs, qfalse);
+ //get the current long term goal
+ if (!BotLongTermGoal(bs, bs->tfl, qfalse, &goal)) {
+ return qtrue;
+ }
+ //check for nearby goals periodicly
+ if (bs->check_time < FloatTime()) {
+ bs->check_time = FloatTime() + 0.5;
+ //check if the bot wants to camp
+ BotWantsToCamp(bs);
+ //
+ if (bs->ltgtype == LTG_DEFENDKEYAREA) range = 400;
+ else range = 150;
+ //
+#ifdef CTF
+ if (gametype == GT_CTF) {
+ //if carrying a flag the bot shouldn't be distracted too much
+ if (BotCTFCarryingFlag(bs))
+ range = 50;
+ }
+#endif //CTF
+#ifdef MISSIONPACK
+ else if (gametype == GT_1FCTF) {
+ if (Bot1FCTFCarryingFlag(bs))
+ range = 50;
+ }
+ else if (gametype == GT_HARVESTER) {
+ if (BotHarvesterCarryingCubes(bs))
+ range = 80;
+ }
+#endif
+ //
+ if (BotNearbyGoal(bs, bs->tfl, &goal, range)) {
+ trap_BotResetLastAvoidReach(bs->ms);
+ //get the goal at the top of the stack
+ //trap_BotGetTopGoal(bs->gs, &tmpgoal);
+ //trap_BotGoalName(tmpgoal.number, buf, 144);
+ //BotAI_Print(PRT_MESSAGE, "new nearby goal %s\n", buf);
+ //time the bot gets to pick up the nearby goal item
+ bs->nbg_time = FloatTime() + 4 + range * 0.01;
+ AIEnter_Seek_NBG(bs, "ltg seek: nbg");
+ return qfalse;
+ }
+ }
+ //predict obstacles
+ if (BotAIPredictObstacles(bs, &goal))
+ return qfalse;
+ //initialize the movement state
+ BotSetupForMovement(bs);
+ //move towards the goal
+ trap_BotMoveToGoal(&moveresult, bs->ms, &goal, bs->tfl);
+ //if the movement failed
+ if (moveresult.failure) {
+ //reset the avoid reach, otherwise bot is stuck in current area
+ trap_BotResetAvoidReach(bs->ms);
+ //BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype);
+ bs->ltg_time = 0;
+ }
+ //
+ BotAIBlocked(bs, &moveresult, qtrue);
+ //
+ BotClearPath(bs, &moveresult);
+ //if the viewangles are used for the movement
+ if (moveresult.flags & (MOVERESULT_MOVEMENTVIEWSET|MOVERESULT_MOVEMENTVIEW|MOVERESULT_SWIMVIEW)) {
+ VectorCopy(moveresult.ideal_viewangles, bs->ideal_viewangles);
+ }
+ //if waiting for something
+ else if (moveresult.flags & MOVERESULT_WAITING) {
+ if (random() < bs->thinktime * 0.8) {
+ BotRoamGoal(bs, target);
+ VectorSubtract(target, bs->origin, dir);
+ vectoangles(dir, bs->ideal_viewangles);
+ bs->ideal_viewangles[2] *= 0.5;
+ }
+ }
+ else if (!(bs->flags & BFL_IDEALVIEWSET)) {
+ if (trap_BotMovementViewTarget(bs->ms, &goal, bs->tfl, 300, target)) {
+ VectorSubtract(target, bs->origin, dir);
+ vectoangles(dir, bs->ideal_viewangles);
+ }
+ //FIXME: look at cluster portals?
+ else if (VectorLengthSquared(moveresult.movedir)) {
+ vectoangles(moveresult.movedir, bs->ideal_viewangles);
+ }
+ else if (random() < bs->thinktime * 0.8) {
+ BotRoamGoal(bs, target);
+ VectorSubtract(target, bs->origin, dir);
+ vectoangles(dir, bs->ideal_viewangles);
+ bs->ideal_viewangles[2] *= 0.5;
+ }
+ bs->ideal_viewangles[2] *= 0.5;
+ }
+ //if the weapon is used for the bot movement
+ if (moveresult.flags & MOVERESULT_MOVEMENTWEAPON) bs->weaponnum = moveresult.weapon;
+ //
+ return qtrue;
+}
+
+/*
+==================
+AIEnter_Battle_Fight
+==================
+*/
+void AIEnter_Battle_Fight(bot_state_t *bs, char *s) {
+ BotRecordNodeSwitch(bs, "battle fight", "", s);
+ trap_BotResetLastAvoidReach(bs->ms);
+ bs->ainode = AINode_Battle_Fight;
+}
+
+/*
+==================
+AIEnter_Battle_Fight
+==================
+*/
+void AIEnter_Battle_SuicidalFight(bot_state_t *bs, char *s) {
+ BotRecordNodeSwitch(bs, "battle fight", "", s);
+ trap_BotResetLastAvoidReach(bs->ms);
+ bs->ainode = AINode_Battle_Fight;
+ bs->flags |= BFL_FIGHTSUICIDAL;
+}
+
+/*
+==================
+AINode_Battle_Fight
+==================
+*/
+int AINode_Battle_Fight(bot_state_t *bs) {
+ int areanum;
+ vec3_t target;
+ aas_entityinfo_t entinfo;
+ bot_moveresult_t moveresult;
+
+ if (BotIsObserver(bs)) {
+ AIEnter_Observer(bs, "battle fight: observer");
+ return qfalse;
+ }
+
+ //if in the intermission
+ if (BotIntermission(bs)) {
+ AIEnter_Intermission(bs, "battle fight: intermission");
+ return qfalse;
+ }
+ //respawn if dead
+ if (BotIsDead(bs)) {
+ AIEnter_Respawn(bs, "battle fight: bot dead");
+ return qfalse;
+ }
+ //if there is another better enemy
+ if (BotFindEnemy(bs, bs->enemy)) {
+#ifdef DEBUG
+ BotAI_Print(PRT_MESSAGE, "found new better enemy\n");
+#endif
+ }
+ //if no enemy
+ if (bs->enemy < 0) {
+ AIEnter_Seek_LTG(bs, "battle fight: no enemy");
+ return qfalse;
+ }
+ //
+ BotEntityInfo(bs->enemy, &entinfo);
+ //if the enemy is dead
+ if (bs->enemydeath_time) {
+ if (bs->enemydeath_time < FloatTime() - 1.0) {
+ bs->enemydeath_time = 0;
+ if (bs->enemysuicide) {
+ BotChat_EnemySuicide(bs);
+ }
+ if (bs->lastkilledplayer == bs->enemy && BotChat_Kill(bs)) {
+ bs->stand_time = FloatTime() + BotChatTime(bs);
+ AIEnter_Stand(bs, "battle fight: enemy dead");
+ }
+ else {
+ bs->ltg_time = 0;
+ AIEnter_Seek_LTG(bs, "battle fight: enemy dead");
+ }
+ return qfalse;
+ }
+ }
+ else {
+ if (EntityIsDead(&entinfo)) {
+ bs->enemydeath_time = FloatTime();
+ }
+ }
+ //if the enemy is invisible and not shooting the bot looses track easily
+ if (EntityIsInvisible(&entinfo) && !EntityIsShooting(&entinfo)) {
+ if (random() < 0.2) {
+ AIEnter_Seek_LTG(bs, "battle fight: invisible");
+ return qfalse;
+ }
+ }
+ //
+ VectorCopy(entinfo.origin, target);
+ // if not a player enemy
+ if (bs->enemy >= MAX_CLIENTS) {
+#ifdef MISSIONPACK
+ // if attacking an obelisk
+ if ( bs->enemy == redobelisk.entitynum ||
+ bs->enemy == blueobelisk.entitynum ) {
+ target[2] += 16;
+ }
+#endif
+ }
+ //update the reachability area and origin if possible
+ areanum = BotPointAreaNum(target);
+ if (areanum && trap_AAS_AreaReachability(areanum)) {
+ VectorCopy(target, bs->lastenemyorigin);
+ bs->lastenemyareanum = areanum;
+ }
+ //update the attack inventory values
+ BotUpdateBattleInventory(bs, bs->enemy);
+ //if the bot's health decreased
+ if (bs->lastframe_health > bs->inventory[INVENTORY_HEALTH]) {
+ if (BotChat_HitNoDeath(bs)) {
+ bs->stand_time = FloatTime() + BotChatTime(bs);
+ AIEnter_Stand(bs, "battle fight: chat health decreased");
+ return qfalse;
+ }
+ }
+ //if the bot hit someone
+ if (bs->cur_ps.persistant[PERS_HITS] > bs->lasthitcount) {
+ if (BotChat_HitNoKill(bs)) {
+ bs->stand_time = FloatTime() + BotChatTime(bs);
+ AIEnter_Stand(bs, "battle fight: chat hit someone");
+ return qfalse;
+ }
+ }
+ //if the enemy is not visible
+ if (!BotEntityVisible(bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy)) {
+ if (BotWantsToChase(bs)) {
+ AIEnter_Battle_Chase(bs, "battle fight: enemy out of sight");
+ return qfalse;
+ }
+ else {
+ AIEnter_Seek_LTG(bs, "battle fight: enemy out of sight");
+ return qfalse;
+ }
+ }
+ //use holdable items
+ BotBattleUseItems(bs);
+ //
+ bs->tfl = TFL_DEFAULT;
+ if (bot_grapple.integer) bs->tfl |= TFL_GRAPPLEHOOK;
+ //if in lava or slime the bot should be able to get out
+ if (BotInLavaOrSlime(bs)) bs->tfl |= TFL_LAVA|TFL_SLIME;
+ //
+ if (BotCanAndWantsToRocketJump(bs)) {
+ bs->tfl |= TFL_ROCKETJUMP;
+ }
+ //choose the best weapon to fight with
+ BotChooseWeapon(bs);
+ //do attack movements
+ moveresult = BotAttackMove(bs, bs->tfl);
+ //if the movement failed
+ if (moveresult.failure) {
+ //reset the avoid reach, otherwise bot is stuck in current area
+ trap_BotResetAvoidReach(bs->ms);
+ //BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype);
+ bs->ltg_time = 0;
+ }
+ //
+ BotAIBlocked(bs, &moveresult, qfalse);
+ //aim at the enemy
+ BotAimAtEnemy(bs);
+ //attack the enemy if possible
+ BotCheckAttack(bs);
+ //if the bot wants to retreat
+ if (!(bs->flags & BFL_FIGHTSUICIDAL)) {
+ if (BotWantsToRetreat(bs)) {
+ AIEnter_Battle_Retreat(bs, "battle fight: wants to retreat");
+ return qtrue;
+ }
+ }
+ return qtrue;
+}
+
+/*
+==================
+AIEnter_Battle_Chase
+==================
+*/
+void AIEnter_Battle_Chase(bot_state_t *bs, char *s) {
+ BotRecordNodeSwitch(bs, "battle chase", "", s);
+ bs->chase_time = FloatTime();
+ bs->ainode = AINode_Battle_Chase;
+}
+
+/*
+==================
+AINode_Battle_Chase
+==================
+*/
+int AINode_Battle_Chase(bot_state_t *bs)
+{
+ bot_goal_t goal;
+ vec3_t target, dir;
+ bot_moveresult_t moveresult;
+ float range;
+
+ if (BotIsObserver(bs)) {
+ AIEnter_Observer(bs, "battle chase: observer");
+ return qfalse;
+ }
+ //if in the intermission
+ if (BotIntermission(bs)) {
+ AIEnter_Intermission(bs, "battle chase: intermission");
+ return qfalse;
+ }
+ //respawn if dead
+ if (BotIsDead(bs)) {
+ AIEnter_Respawn(bs, "battle chase: bot dead");
+ return qfalse;
+ }
+ //if no enemy
+ if (bs->enemy < 0) {
+ AIEnter_Seek_LTG(bs, "battle chase: no enemy");
+ return qfalse;
+ }
+ //if the enemy is visible
+ if (BotEntityVisible(bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy)) {
+ AIEnter_Battle_Fight(bs, "battle chase");
+ return qfalse;
+ }
+ //if there is another enemy
+ if (BotFindEnemy(bs, -1)) {
+ AIEnter_Battle_Fight(bs, "battle chase: better enemy");
+ return qfalse;
+ }
+ //there is no last enemy area
+ if (!bs->lastenemyareanum) {
+ AIEnter_Seek_LTG(bs, "battle chase: no enemy area");
+ return qfalse;
+ }
+ //
+ bs->tfl = TFL_DEFAULT;
+ if (bot_grapple.integer) bs->tfl |= TFL_GRAPPLEHOOK;
+ //if in lava or slime the bot should be able to get out
+ if (BotInLavaOrSlime(bs)) bs->tfl |= TFL_LAVA|TFL_SLIME;
+ //
+ if (BotCanAndWantsToRocketJump(bs)) {
+ bs->tfl |= TFL_ROCKETJUMP;
+ }
+ //map specific code
+ BotMapScripts(bs);
+ //create the chase goal
+ goal.entitynum = bs->enemy;
+ goal.areanum = bs->lastenemyareanum;
+ VectorCopy(bs->lastenemyorigin, goal.origin);
+ VectorSet(goal.mins, -8, -8, -8);
+ VectorSet(goal.maxs, 8, 8, 8);
+ //if the last seen enemy spot is reached the enemy could not be found
+ if (trap_BotTouchingGoal(bs->origin, &goal)) bs->chase_time = 0;
+ //if there's no chase time left
+ if (!bs->chase_time || bs->chase_time < FloatTime() - 10) {
+ AIEnter_Seek_LTG(bs, "battle chase: time out");
+ return qfalse;
+ }
+ //check for nearby goals periodicly
+ if (bs->check_time < FloatTime()) {
+ bs->check_time = FloatTime() + 1;
+ range = 150;
+ //
+ if (BotNearbyGoal(bs, bs->tfl, &goal, range)) {
+ //the bot gets 5 seconds to pick up the nearby goal item
+ bs->nbg_time = FloatTime() + 0.1 * range + 1;
+ trap_BotResetLastAvoidReach(bs->ms);
+ AIEnter_Battle_NBG(bs, "battle chase: nbg");
+ return qfalse;
+ }
+ }
+ //
+ BotUpdateBattleInventory(bs, bs->enemy);
+ //initialize the movement state
+ BotSetupForMovement(bs);
+ //move towards the goal
+ trap_BotMoveToGoal(&moveresult, bs->ms, &goal, bs->tfl);
+ //if the movement failed
+ if (moveresult.failure) {
+ //reset the avoid reach, otherwise bot is stuck in current area
+ trap_BotResetAvoidReach(bs->ms);
+ //BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype);
+ bs->ltg_time = 0;
+ }
+ //
+ BotAIBlocked(bs, &moveresult, qfalse);
+ //
+ if (moveresult.flags & (MOVERESULT_MOVEMENTVIEWSET|MOVERESULT_MOVEMENTVIEW|MOVERESULT_SWIMVIEW)) {
+ VectorCopy(moveresult.ideal_viewangles, bs->ideal_viewangles);
+ }
+ else if (!(bs->flags & BFL_IDEALVIEWSET)) {
+ if (bs->chase_time > FloatTime() - 2) {
+ BotAimAtEnemy(bs);
+ }
+ else {
+ if (trap_BotMovementViewTarget(bs->ms, &goal, bs->tfl, 300, target)) {
+ VectorSubtract(target, bs->origin, dir);
+ vectoangles(dir, bs->ideal_viewangles);
+ }
+ else {
+ vectoangles(moveresult.movedir, bs->ideal_viewangles);
+ }
+ }
+ bs->ideal_viewangles[2] *= 0.5;
+ }
+ //if the weapon is used for the bot movement
+ if (moveresult.flags & MOVERESULT_MOVEMENTWEAPON) bs->weaponnum = moveresult.weapon;
+ //if the bot is in the area the enemy was last seen in
+ if (bs->areanum == bs->lastenemyareanum) bs->chase_time = 0;
+ //if the bot wants to retreat (the bot could have been damage during the chase)
+ if (BotWantsToRetreat(bs)) {
+ AIEnter_Battle_Retreat(bs, "battle chase: wants to retreat");
+ return qtrue;
+ }
+ return qtrue;
+}
+
+/*
+==================
+AIEnter_Battle_Retreat
+==================
+*/
+void AIEnter_Battle_Retreat(bot_state_t *bs, char *s) {
+ BotRecordNodeSwitch(bs, "battle retreat", "", s);
+ bs->ainode = AINode_Battle_Retreat;
+}
+
+/*
+==================
+AINode_Battle_Retreat
+==================
+*/
+int AINode_Battle_Retreat(bot_state_t *bs) {
+ bot_goal_t goal;
+ aas_entityinfo_t entinfo;
+ bot_moveresult_t moveresult;
+ vec3_t target, dir;
+ float attack_skill, range;
+ int areanum;
+
+ if (BotIsObserver(bs)) {
+ AIEnter_Observer(bs, "battle retreat: observer");
+ return qfalse;
+ }
+ //if in the intermission
+ if (BotIntermission(bs)) {
+ AIEnter_Intermission(bs, "battle retreat: intermission");
+ return qfalse;
+ }
+ //respawn if dead
+ if (BotIsDead(bs)) {
+ AIEnter_Respawn(bs, "battle retreat: bot dead");
+ return qfalse;
+ }
+ //if no enemy
+ if (bs->enemy < 0) {
+ AIEnter_Seek_LTG(bs, "battle retreat: no enemy");
+ return qfalse;
+ }
+ //
+ BotEntityInfo(bs->enemy, &entinfo);
+ if (EntityIsDead(&entinfo)) {
+ AIEnter_Seek_LTG(bs, "battle retreat: enemy dead");
+ return qfalse;
+ }
+ //if there is another better enemy
+ if (BotFindEnemy(bs, bs->enemy)) {
+#ifdef DEBUG
+ BotAI_Print(PRT_MESSAGE, "found new better enemy\n");
+#endif
+ }
+ //
+ bs->tfl = TFL_DEFAULT;
+ if (bot_grapple.integer) bs->tfl |= TFL_GRAPPLEHOOK;
+ //if in lava or slime the bot should be able to get out
+ if (BotInLavaOrSlime(bs)) bs->tfl |= TFL_LAVA|TFL_SLIME;
+ //map specific code
+ BotMapScripts(bs);
+ //update the attack inventory values
+ BotUpdateBattleInventory(bs, bs->enemy);
+ //if the bot doesn't want to retreat anymore... probably picked up some nice items
+ if (BotWantsToChase(bs)) {
+ //empty the goal stack, when chasing, only the enemy is the goal
+ trap_BotEmptyGoalStack(bs->gs);
+ //go chase the enemy
+ AIEnter_Battle_Chase(bs, "battle retreat: wants to chase");
+ return qfalse;
+ }
+ //update the last time the enemy was visible
+ if (BotEntityVisible(bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy)) {
+ bs->enemyvisible_time = FloatTime();
+ VectorCopy(entinfo.origin, target);
+ // if not a player enemy
+ if (bs->enemy >= MAX_CLIENTS) {
+#ifdef MISSIONPACK
+ // if attacking an obelisk
+ if ( bs->enemy == redobelisk.entitynum ||
+ bs->enemy == blueobelisk.entitynum ) {
+ target[2] += 16;
+ }
+#endif
+ }
+ //update the reachability area and origin if possible
+ areanum = BotPointAreaNum(target);
+ if (areanum && trap_AAS_AreaReachability(areanum)) {
+ VectorCopy(target, bs->lastenemyorigin);
+ bs->lastenemyareanum = areanum;
+ }
+ }
+ //if the enemy is NOT visible for 4 seconds
+ if (bs->enemyvisible_time < FloatTime() - 4) {
+ AIEnter_Seek_LTG(bs, "battle retreat: lost enemy");
+ return qfalse;
+ }
+ //else if the enemy is NOT visible
+ else if (bs->enemyvisible_time < FloatTime()) {
+ //if there is another enemy
+ if (BotFindEnemy(bs, -1)) {
+ AIEnter_Battle_Fight(bs, "battle retreat: another enemy");
+ return qfalse;
+ }
+ }
+ //
+ BotTeamGoals(bs, qtrue);
+ //use holdable items
+ BotBattleUseItems(bs);
+ //get the current long term goal while retreating
+ if (!BotLongTermGoal(bs, bs->tfl, qtrue, &goal)) {
+ AIEnter_Battle_SuicidalFight(bs, "battle retreat: no way out");
+ return qfalse;
+ }
+ //check for nearby goals periodicly
+ if (bs->check_time < FloatTime()) {
+ bs->check_time = FloatTime() + 1;
+ range = 150;
+#ifdef CTF
+ if (gametype == GT_CTF) {
+ //if carrying a flag the bot shouldn't be distracted too much
+ if (BotCTFCarryingFlag(bs))
+ range = 50;
+ }
+#endif //CTF
+#ifdef MISSIONPACK
+ else if (gametype == GT_1FCTF) {
+ if (Bot1FCTFCarryingFlag(bs))
+ range = 50;
+ }
+ else if (gametype == GT_HARVESTER) {
+ if (BotHarvesterCarryingCubes(bs))
+ range = 80;
+ }
+#endif
+ //
+ if (BotNearbyGoal(bs, bs->tfl, &goal, range)) {
+ trap_BotResetLastAvoidReach(bs->ms);
+ //time the bot gets to pick up the nearby goal item
+ bs->nbg_time = FloatTime() + range / 100 + 1;
+ AIEnter_Battle_NBG(bs, "battle retreat: nbg");
+ return qfalse;
+ }
+ }
+ //initialize the movement state
+ BotSetupForMovement(bs);
+ //move towards the goal
+ trap_BotMoveToGoal(&moveresult, bs->ms, &goal, bs->tfl);
+ //if the movement failed
+ if (moveresult.failure) {
+ //reset the avoid reach, otherwise bot is stuck in current area
+ trap_BotResetAvoidReach(bs->ms);
+ //BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype);
+ bs->ltg_time = 0;
+ }
+ //
+ BotAIBlocked(bs, &moveresult, qfalse);
+ //choose the best weapon to fight with
+ BotChooseWeapon(bs);
+ //if the view is fixed for the movement
+ if (moveresult.flags & (MOVERESULT_MOVEMENTVIEW|MOVERESULT_SWIMVIEW)) {
+ VectorCopy(moveresult.ideal_viewangles, bs->ideal_viewangles);
+ }
+ else if (!(moveresult.flags & MOVERESULT_MOVEMENTVIEWSET)
+ && !(bs->flags & BFL_IDEALVIEWSET) ) {
+ attack_skill = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_ATTACK_SKILL, 0, 1);
+ //if the bot is skilled anough
+ if (attack_skill > 0.3) {
+ BotAimAtEnemy(bs);
+ }
+ else {
+ if (trap_BotMovementViewTarget(bs->ms, &goal, bs->tfl, 300, target)) {
+ VectorSubtract(target, bs->origin, dir);
+ vectoangles(dir, bs->ideal_viewangles);
+ }
+ else {
+ vectoangles(moveresult.movedir, bs->ideal_viewangles);
+ }
+ bs->ideal_viewangles[2] *= 0.5;
+ }
+ }
+ //if the weapon is used for the bot movement
+ if (moveresult.flags & MOVERESULT_MOVEMENTWEAPON) bs->weaponnum = moveresult.weapon;
+ //attack the enemy if possible
+ BotCheckAttack(bs);
+ //
+ return qtrue;
+}
+
+/*
+==================
+AIEnter_Battle_NBG
+==================
+*/
+void AIEnter_Battle_NBG(bot_state_t *bs, char *s) {
+ BotRecordNodeSwitch(bs, "battle NBG", "", s);
+ bs->ainode = AINode_Battle_NBG;
+}
+
+/*
+==================
+AINode_Battle_NBG
+==================
+*/
+int AINode_Battle_NBG(bot_state_t *bs) {
+ int areanum;
+ bot_goal_t goal;
+ aas_entityinfo_t entinfo;
+ bot_moveresult_t moveresult;
+ float attack_skill;
+ vec3_t target, dir;
+
+ if (BotIsObserver(bs)) {
+ AIEnter_Observer(bs, "battle nbg: observer");
+ return qfalse;
+ }
+ //if in the intermission
+ if (BotIntermission(bs)) {
+ AIEnter_Intermission(bs, "battle nbg: intermission");
+ return qfalse;
+ }
+ //respawn if dead
+ if (BotIsDead(bs)) {
+ AIEnter_Respawn(bs, "battle nbg: bot dead");
+ return qfalse;
+ }
+ //if no enemy
+ if (bs->enemy < 0) {
+ AIEnter_Seek_NBG(bs, "battle nbg: no enemy");
+ return qfalse;
+ }
+ //
+ BotEntityInfo(bs->enemy, &entinfo);
+ if (EntityIsDead(&entinfo)) {
+ AIEnter_Seek_NBG(bs, "battle nbg: enemy dead");
+ return qfalse;
+ }
+ //
+ bs->tfl = TFL_DEFAULT;
+ if (bot_grapple.integer) bs->tfl |= TFL_GRAPPLEHOOK;
+ //if in lava or slime the bot should be able to get out
+ if (BotInLavaOrSlime(bs)) bs->tfl |= TFL_LAVA|TFL_SLIME;
+ //
+ if (BotCanAndWantsToRocketJump(bs)) {
+ bs->tfl |= TFL_ROCKETJUMP;
+ }
+ //map specific code
+ BotMapScripts(bs);
+ //update the last time the enemy was visible
+ if (BotEntityVisible(bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy)) {
+ bs->enemyvisible_time = FloatTime();
+ VectorCopy(entinfo.origin, target);
+ // if not a player enemy
+ if (bs->enemy >= MAX_CLIENTS) {
+#ifdef MISSIONPACK
+ // if attacking an obelisk
+ if ( bs->enemy == redobelisk.entitynum ||
+ bs->enemy == blueobelisk.entitynum ) {
+ target[2] += 16;
+ }
+#endif
+ }
+ //update the reachability area and origin if possible
+ areanum = BotPointAreaNum(target);
+ if (areanum && trap_AAS_AreaReachability(areanum)) {
+ VectorCopy(target, bs->lastenemyorigin);
+ bs->lastenemyareanum = areanum;
+ }
+ }
+ //if the bot has no goal or touches the current goal
+ if (!trap_BotGetTopGoal(bs->gs, &goal)) {
+ bs->nbg_time = 0;
+ }
+ else if (BotReachedGoal(bs, &goal)) {
+ bs->nbg_time = 0;
+ }
+ //
+ if (bs->nbg_time < FloatTime()) {
+ //pop the current goal from the stack
+ trap_BotPopGoal(bs->gs);
+ //if the bot still has a goal
+ if (trap_BotGetTopGoal(bs->gs, &goal))
+ AIEnter_Battle_Retreat(bs, "battle nbg: time out");
+ else
+ AIEnter_Battle_Fight(bs, "battle nbg: time out");
+ //
+ return qfalse;
+ }
+ //initialize the movement state
+ BotSetupForMovement(bs);
+ //move towards the goal
+ trap_BotMoveToGoal(&moveresult, bs->ms, &goal, bs->tfl);
+ //if the movement failed
+ if (moveresult.failure) {
+ //reset the avoid reach, otherwise bot is stuck in current area
+ trap_BotResetAvoidReach(bs->ms);
+ //BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype);
+ bs->nbg_time = 0;
+ }
+ //
+ BotAIBlocked(bs, &moveresult, qfalse);
+ //update the attack inventory values
+ BotUpdateBattleInventory(bs, bs->enemy);
+ //choose the best weapon to fight with
+ BotChooseWeapon(bs);
+ //if the view is fixed for the movement
+ if (moveresult.flags & (MOVERESULT_MOVEMENTVIEW|MOVERESULT_SWIMVIEW)) {
+ VectorCopy(moveresult.ideal_viewangles, bs->ideal_viewangles);
+ }
+ else if (!(moveresult.flags & MOVERESULT_MOVEMENTVIEWSET)
+ && !(bs->flags & BFL_IDEALVIEWSET)) {
+ attack_skill = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_ATTACK_SKILL, 0, 1);
+ //if the bot is skilled anough and the enemy is visible
+ if (attack_skill > 0.3) {
+ //&& BotEntityVisible(bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy)
+ BotAimAtEnemy(bs);
+ }
+ else {
+ if (trap_BotMovementViewTarget(bs->ms, &goal, bs->tfl, 300, target)) {
+ VectorSubtract(target, bs->origin, dir);
+ vectoangles(dir, bs->ideal_viewangles);
+ }
+ else {
+ vectoangles(moveresult.movedir, bs->ideal_viewangles);
+ }
+ bs->ideal_viewangles[2] *= 0.5;
+ }
+ }
+ //if the weapon is used for the bot movement
+ if (moveresult.flags & MOVERESULT_MOVEMENTWEAPON) bs->weaponnum = moveresult.weapon;
+ //attack the enemy if possible
+ BotCheckAttack(bs);
+ //
+ return qtrue;
+}
+
diff --git a/code/game/ai_dmnet.h b/code/game/ai_dmnet.h
new file mode 100755
index 0000000..a5c4c9a
--- /dev/null
+++ b/code/game/ai_dmnet.h
@@ -0,0 +1,61 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+/*****************************************************************************
+ * name: ai_dmnet.h
+ *
+ * desc: Quake3 bot AI
+ *
+ * $Archive: /source/code/botai/ai_chat.c $
+ *
+ *****************************************************************************/
+
+#define MAX_NODESWITCHES 50
+
+void AIEnter_Intermission(bot_state_t *bs, char *s);
+void AIEnter_Observer(bot_state_t *bs, char *s);
+void AIEnter_Respawn(bot_state_t *bs, char *s);
+void AIEnter_Stand(bot_state_t *bs, char *s);
+void AIEnter_Seek_ActivateEntity(bot_state_t *bs, char *s);
+void AIEnter_Seek_NBG(bot_state_t *bs, char *s);
+void AIEnter_Seek_LTG(bot_state_t *bs, char *s);
+void AIEnter_Seek_Camp(bot_state_t *bs, char *s);
+void AIEnter_Battle_Fight(bot_state_t *bs, char *s);
+void AIEnter_Battle_Chase(bot_state_t *bs, char *s);
+void AIEnter_Battle_Retreat(bot_state_t *bs, char *s);
+void AIEnter_Battle_NBG(bot_state_t *bs, char *s);
+int AINode_Intermission(bot_state_t *bs);
+int AINode_Observer(bot_state_t *bs);
+int AINode_Respawn(bot_state_t *bs);
+int AINode_Stand(bot_state_t *bs);
+int AINode_Seek_ActivateEntity(bot_state_t *bs);
+int AINode_Seek_NBG(bot_state_t *bs);
+int AINode_Seek_LTG(bot_state_t *bs);
+int AINode_Battle_Fight(bot_state_t *bs);
+int AINode_Battle_Chase(bot_state_t *bs);
+int AINode_Battle_Retreat(bot_state_t *bs);
+int AINode_Battle_NBG(bot_state_t *bs);
+
+void BotResetNodeSwitches(void);
+void BotDumpNodeSwitches(bot_state_t *bs);
+
diff --git a/code/game/ai_dmq3.c b/code/game/ai_dmq3.c
new file mode 100755
index 0000000..ed7f4c1
--- /dev/null
+++ b/code/game/ai_dmq3.c
@@ -0,0 +1,5461 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+/*****************************************************************************
+ * name: ai_dmq3.c
+ *
+ * desc: Quake3 bot AI
+ *
+ * $Archive: /MissionPack/code/game/ai_dmq3.c $
+ *
+ *****************************************************************************/
+
+
+#include "g_local.h"
+#include "botlib.h"
+#include "be_aas.h"
+#include "be_ea.h"
+#include "be_ai_char.h"
+#include "be_ai_chat.h"
+#include "be_ai_gen.h"
+#include "be_ai_goal.h"
+#include "be_ai_move.h"
+#include "be_ai_weap.h"
+//
+#include "ai_main.h"
+#include "ai_dmq3.h"
+#include "ai_chat.h"
+#include "ai_cmd.h"
+#include "ai_dmnet.h"
+#include "ai_team.h"
+//
+#include "chars.h" //characteristics
+#include "inv.h" //indexes into the inventory
+#include "syn.h" //synonyms
+#include "match.h" //string matching types and vars
+
+// for the voice chats
+#include "../../ui/menudef.h" // sos001205 - for q3_ui also
+
+// from aasfile.h
+#define AREACONTENTS_MOVER 1024
+#define AREACONTENTS_MODELNUMSHIFT 24
+#define AREACONTENTS_MAXMODELNUM 0xFF
+#define AREACONTENTS_MODELNUM (AREACONTENTS_MAXMODELNUM << AREACONTENTS_MODELNUMSHIFT)
+
+#define IDEAL_ATTACKDIST 140
+
+#define MAX_WAYPOINTS 128
+//
+bot_waypoint_t botai_waypoints[MAX_WAYPOINTS];
+bot_waypoint_t *botai_freewaypoints;
+
+//NOTE: not using a cvars which can be updated because the game should be reloaded anyway
+int gametype; //game type
+int maxclients; //maximum number of clients
+
+vmCvar_t bot_grapple;
+vmCvar_t bot_rocketjump;
+vmCvar_t bot_fastchat;
+vmCvar_t bot_nochat;
+vmCvar_t bot_testrchat;
+vmCvar_t bot_challenge;
+vmCvar_t bot_predictobstacles;
+vmCvar_t g_spSkill;
+
+extern vmCvar_t bot_developer;
+
+vec3_t lastteleport_origin; //last teleport event origin
+float lastteleport_time; //last teleport event time
+int max_bspmodelindex; //maximum BSP model index
+
+//CTF flag goals
+bot_goal_t ctf_redflag;
+bot_goal_t ctf_blueflag;
+#ifdef MISSIONPACK
+bot_goal_t ctf_neutralflag;
+bot_goal_t redobelisk;
+bot_goal_t blueobelisk;
+bot_goal_t neutralobelisk;
+#endif
+
+#define MAX_ALTROUTEGOALS 32
+
+int altroutegoals_setup;
+aas_altroutegoal_t red_altroutegoals[MAX_ALTROUTEGOALS];
+int red_numaltroutegoals;
+aas_altroutegoal_t blue_altroutegoals[MAX_ALTROUTEGOALS];
+int blue_numaltroutegoals;
+
+
+/*
+==================
+BotSetUserInfo
+==================
+*/
+void BotSetUserInfo(bot_state_t *bs, char *key, char *value) {
+ char userinfo[MAX_INFO_STRING];
+
+ trap_GetUserinfo(bs->client, userinfo, sizeof(userinfo));
+ Info_SetValueForKey(userinfo, key, value);
+ trap_SetUserinfo(bs->client, userinfo);
+ ClientUserinfoChanged( bs->client );
+}
+
+/*
+==================
+BotCTFCarryingFlag
+==================
+*/
+int BotCTFCarryingFlag(bot_state_t *bs) {
+ if (gametype != GT_CTF) return CTF_FLAG_NONE;
+
+ if (bs->inventory[INVENTORY_REDFLAG] > 0) return CTF_FLAG_RED;
+ else if (bs->inventory[INVENTORY_BLUEFLAG] > 0) return CTF_FLAG_BLUE;
+ return CTF_FLAG_NONE;
+}
+
+/*
+==================
+BotTeam
+==================
+*/
+int BotTeam(bot_state_t *bs) {
+ char info[1024];
+
+ if (bs->client < 0 || bs->client >= MAX_CLIENTS) {
+ //BotAI_Print(PRT_ERROR, "BotCTFTeam: client out of range\n");
+ return qfalse;
+ }
+ trap_GetConfigstring(CS_PLAYERS+bs->client, info, sizeof(info));
+ //
+ if (atoi(Info_ValueForKey(info, "t")) == TEAM_RED) return TEAM_RED;
+ else if (atoi(Info_ValueForKey(info, "t")) == TEAM_BLUE) return TEAM_BLUE;
+ return TEAM_FREE;
+}
+
+/*
+==================
+BotOppositeTeam
+==================
+*/
+int BotOppositeTeam(bot_state_t *bs) {
+ switch(BotTeam(bs)) {
+ case TEAM_RED: return TEAM_BLUE;
+ case TEAM_BLUE: return TEAM_RED;
+ default: return TEAM_FREE;
+ }
+}
+
+/*
+==================
+BotEnemyFlag
+==================
+*/
+bot_goal_t *BotEnemyFlag(bot_state_t *bs) {
+ if (BotTeam(bs) == TEAM_RED) {
+ return &ctf_blueflag;
+ }
+ else {
+ return &ctf_redflag;
+ }
+}
+
+/*
+==================
+BotTeamFlag
+==================
+*/
+bot_goal_t *BotTeamFlag(bot_state_t *bs) {
+ if (BotTeam(bs) == TEAM_RED) {
+ return &ctf_redflag;
+ }
+ else {
+ return &ctf_blueflag;
+ }
+}
+
+
+/*
+==================
+EntityIsDead
+==================
+*/
+qboolean EntityIsDead(aas_entityinfo_t *entinfo) {
+ playerState_t ps;
+
+ if (entinfo->number >= 0 && entinfo->number < MAX_CLIENTS) {
+ //retrieve the current client state
+ BotAI_GetClientState( entinfo->number, &ps );
+ if (ps.pm_type != PM_NORMAL) return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+==================
+EntityCarriesFlag
+==================
+*/
+qboolean EntityCarriesFlag(aas_entityinfo_t *entinfo) {
+ if ( entinfo->powerups & ( 1 << PW_REDFLAG ) )
+ return qtrue;
+ if ( entinfo->powerups & ( 1 << PW_BLUEFLAG ) )
+ return qtrue;
+#ifdef MISSIONPACK
+ if ( entinfo->powerups & ( 1 << PW_NEUTRALFLAG ) )
+ return qtrue;
+#endif
+ return qfalse;
+}
+
+/*
+==================
+EntityIsInvisible
+==================
+*/
+qboolean EntityIsInvisible(aas_entityinfo_t *entinfo) {
+ // the flag is always visible
+ if (EntityCarriesFlag(entinfo)) {
+ return qfalse;
+ }
+ if (entinfo->powerups & (1 << PW_INVIS)) {
+ return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+==================
+EntityIsShooting
+==================
+*/
+qboolean EntityIsShooting(aas_entityinfo_t *entinfo) {
+ if (entinfo->flags & EF_FIRING) {
+ return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+==================
+EntityIsChatting
+==================
+*/
+qboolean EntityIsChatting(aas_entityinfo_t *entinfo) {
+ if (entinfo->flags & EF_TALK) {
+ return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+==================
+EntityHasQuad
+==================
+*/
+qboolean EntityHasQuad(aas_entityinfo_t *entinfo) {
+ if (entinfo->powerups & (1 << PW_QUAD)) {
+ return qtrue;
+ }
+ return qfalse;
+}
+
+#ifdef MISSIONPACK
+/*
+==================
+EntityHasKamikze
+==================
+*/
+qboolean EntityHasKamikaze(aas_entityinfo_t *entinfo) {
+ if (entinfo->flags & EF_KAMIKAZE) {
+ return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+==================
+EntityCarriesCubes
+==================
+*/
+qboolean EntityCarriesCubes(aas_entityinfo_t *entinfo) {
+ entityState_t state;
+
+ if (gametype != GT_HARVESTER)
+ return qfalse;
+ //FIXME: get this info from the aas_entityinfo_t ?
+ BotAI_GetEntityState(entinfo->number, &state);
+ if (state.generic1 > 0)
+ return qtrue;
+ return qfalse;
+}
+
+/*
+==================
+Bot1FCTFCarryingFlag
+==================
+*/
+int Bot1FCTFCarryingFlag(bot_state_t *bs) {
+ if (gametype != GT_1FCTF) return qfalse;
+
+ if (bs->inventory[INVENTORY_NEUTRALFLAG] > 0) return qtrue;
+ return qfalse;
+}
+
+/*
+==================
+BotHarvesterCarryingCubes
+==================
+*/
+int BotHarvesterCarryingCubes(bot_state_t *bs) {
+ if (gametype != GT_HARVESTER) return qfalse;
+
+ if (bs->inventory[INVENTORY_REDCUBE] > 0) return qtrue;
+ if (bs->inventory[INVENTORY_BLUECUBE] > 0) return qtrue;
+ return qfalse;
+}
+#endif
+
+/*
+==================
+BotRememberLastOrderedTask
+==================
+*/
+void BotRememberLastOrderedTask(bot_state_t *bs) {
+ if (!bs->ordered) {
+ return;
+ }
+ bs->lastgoal_decisionmaker = bs->decisionmaker;
+ bs->lastgoal_ltgtype = bs->ltgtype;
+ memcpy(&bs->lastgoal_teamgoal, &bs->teamgoal, sizeof(bot_goal_t));
+ bs->lastgoal_teammate = bs->teammate;
+}
+
+/*
+==================
+BotSetTeamStatus
+==================
+*/
+void BotSetTeamStatus(bot_state_t *bs) {
+#ifdef MISSIONPACK
+ int teamtask;
+ aas_entityinfo_t entinfo;
+
+ teamtask = TEAMTASK_PATROL;
+
+ switch(bs->ltgtype) {
+ case LTG_TEAMHELP:
+ break;
+ case LTG_TEAMACCOMPANY:
+ BotEntityInfo(bs->teammate, &entinfo);
+ if ( ( (gametype == GT_CTF || gametype == GT_1FCTF) && EntityCarriesFlag(&entinfo))
+ || ( gametype == GT_HARVESTER && EntityCarriesCubes(&entinfo)) ) {
+ teamtask = TEAMTASK_ESCORT;
+ }
+ else {
+ teamtask = TEAMTASK_FOLLOW;
+ }
+ break;
+ case LTG_DEFENDKEYAREA:
+ teamtask = TEAMTASK_DEFENSE;
+ break;
+ case LTG_GETFLAG:
+ teamtask = TEAMTASK_OFFENSE;
+ break;
+ case LTG_RUSHBASE:
+ teamtask = TEAMTASK_DEFENSE;
+ break;
+ case LTG_RETURNFLAG:
+ teamtask = TEAMTASK_RETRIEVE;
+ break;
+ case LTG_CAMP:
+ case LTG_CAMPORDER:
+ teamtask = TEAMTASK_CAMP;
+ break;
+ case LTG_PATROL:
+ teamtask = TEAMTASK_PATROL;
+ break;
+ case LTG_GETITEM:
+ teamtask = TEAMTASK_PATROL;
+ break;
+ case LTG_KILL:
+ teamtask = TEAMTASK_PATROL;
+ break;
+ case LTG_HARVEST:
+ teamtask = TEAMTASK_OFFENSE;
+ break;
+ case LTG_ATTACKENEMYBASE:
+ teamtask = TEAMTASK_OFFENSE;
+ break;
+ default:
+ teamtask = TEAMTASK_PATROL;
+ break;
+ }
+ BotSetUserInfo(bs, "teamtask", va("%d", teamtask));
+#endif
+}
+
+/*
+==================
+BotSetLastOrderedTask
+==================
+*/
+int BotSetLastOrderedTask(bot_state_t *bs) {
+
+ if (gametype == GT_CTF) {
+ // don't go back to returning the flag if it's at the base
+ if ( bs->lastgoal_ltgtype == LTG_RETURNFLAG ) {
+ if ( BotTeam(bs) == TEAM_RED ) {
+ if ( bs->redflagstatus == 0 ) {
+ bs->lastgoal_ltgtype = 0;
+ }
+ }
+ else {
+ if ( bs->blueflagstatus == 0 ) {
+ bs->lastgoal_ltgtype = 0;
+ }
+ }
+ }
+ }
+
+ if ( bs->lastgoal_ltgtype ) {
+ bs->decisionmaker = bs->lastgoal_decisionmaker;
+ bs->ordered = qtrue;
+ bs->ltgtype = bs->lastgoal_ltgtype;
+ memcpy(&bs->teamgoal, &bs->lastgoal_teamgoal, sizeof(bot_goal_t));
+ bs->teammate = bs->lastgoal_teammate;
+ bs->teamgoal_time = FloatTime() + 300;
+ BotSetTeamStatus(bs);
+ //
+ if ( gametype == GT_CTF ) {
+ if ( bs->ltgtype == LTG_GETFLAG ) {
+ bot_goal_t *tb, *eb;
+ int tt, et;
+
+ tb = BotTeamFlag(bs);
+ eb = BotEnemyFlag(bs);
+ tt = trap_AAS_AreaTravelTimeToGoalArea(bs->areanum, bs->origin, tb->areanum, TFL_DEFAULT);
+ et = trap_AAS_AreaTravelTimeToGoalArea(bs->areanum, bs->origin, eb->areanum, TFL_DEFAULT);
+ // if the travel time towards the enemy base is larger than towards our base
+ if (et > tt) {
+ //get an alternative route goal towards the enemy base
+ BotGetAlternateRouteGoal(bs, BotOppositeTeam(bs));
+ }
+ }
+ }
+ return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+==================
+BotRefuseOrder
+==================
+*/
+void BotRefuseOrder(bot_state_t *bs) {
+ if (!bs->ordered)
+ return;
+ // if the bot was ordered to do something
+ if ( bs->order_time && bs->order_time > FloatTime() - 10 ) {
+ trap_EA_Action(bs->client, ACTION_NEGATIVE);
+ BotVoiceChat(bs, bs->decisionmaker, VOICECHAT_NO);
+ bs->order_time = 0;
+ }
+}
+
+/*
+==================
+BotCTFSeekGoals
+==================
+*/
+void BotCTFSeekGoals(bot_state_t *bs) {
+ float rnd, l1, l2;
+ int flagstatus, c;
+ vec3_t dir;
+ aas_entityinfo_t entinfo;
+
+ //when carrying a flag in ctf the bot should rush to the base
+ if (BotCTFCarryingFlag(bs)) {
+ //if not already rushing to the base
+ if (bs->ltgtype != LTG_RUSHBASE) {
+ BotRefuseOrder(bs);
+ bs->ltgtype = LTG_RUSHBASE;
+ bs->teamgoal_time = FloatTime() + CTF_RUSHBASE_TIME;
+ bs->rushbaseaway_time = 0;
+ bs->decisionmaker = bs->client;
+ bs->ordered = qfalse;
+ //
+ switch(BotTeam(bs)) {
+ case TEAM_RED: VectorSubtract(bs->origin, ctf_blueflag.origin, dir); break;
+ case TEAM_BLUE: VectorSubtract(bs->origin, ctf_redflag.origin, dir); break;
+ default: VectorSet(dir, 999, 999, 999); break;
+ }
+ // if the bot picked up the flag very close to the enemy base
+ if ( VectorLength(dir) < 128 ) {
+ // get an alternative route goal through the enemy base
+ BotGetAlternateRouteGoal(bs, BotOppositeTeam(bs));
+ } else {
+ // don't use any alt route goal, just get the hell out of the base
+ bs->altroutegoal.areanum = 0;
+ }
+ BotSetUserInfo(bs, "teamtask", va("%d", TEAMTASK_OFFENSE));
+ BotVoiceChat(bs, -1, VOICECHAT_IHAVEFLAG);
+ }
+ else if (bs->rushbaseaway_time > FloatTime()) {
+ if (BotTeam(bs) == TEAM_RED) flagstatus = bs->redflagstatus;
+ else flagstatus = bs->blueflagstatus;
+ //if the flag is back
+ if (flagstatus == 0) {
+ bs->rushbaseaway_time = 0;
+ }
+ }
+ return;
+ }
+ // if the bot decided to follow someone
+ if ( bs->ltgtype == LTG_TEAMACCOMPANY && !bs->ordered ) {
+ // if the team mate being accompanied no longer carries the flag
+ BotEntityInfo(bs->teammate, &entinfo);
+ if (!EntityCarriesFlag(&entinfo)) {
+ bs->ltgtype = 0;
+ }
+ }
+ //
+ if (BotTeam(bs) == TEAM_RED) flagstatus = bs->redflagstatus * 2 + bs->blueflagstatus;
+ else flagstatus = bs->blueflagstatus * 2 + bs->redflagstatus;
+ //if our team has the enemy flag and our flag is at the base
+ if (flagstatus == 1) {
+ //
+ if (bs->owndecision_time < FloatTime()) {
+ //if Not defending the base already
+ if (!(bs->ltgtype == LTG_DEFENDKEYAREA &&
+ (bs->teamgoal.number == ctf_redflag.number ||
+ bs->teamgoal.number == ctf_blueflag.number))) {
+ //if there is a visible team mate flag carrier
+ c = BotTeamFlagCarrierVisible(bs);
+ if (c >= 0 &&
+ // and not already following the team mate flag carrier
+ (bs->ltgtype != LTG_TEAMACCOMPANY || bs->teammate != c)) {
+ //
+ BotRefuseOrder(bs);
+ //follow the flag carrier
+ bs->decisionmaker = bs->client;
+ bs->ordered = qfalse;
+ //the team mate
+ bs->teammate = c;
+ //last time the team mate was visible
+ bs->teammatevisible_time = FloatTime();
+ //no message
+ bs->teammessage_time = 0;
+ //no arrive message
+ bs->arrive_time = 1;
+ //
+ BotVoiceChat(bs, bs->teammate, VOICECHAT_ONFOLLOW);
+ //get the team goal time
+ bs->teamgoal_time = FloatTime() + TEAM_ACCOMPANY_TIME;
+ bs->ltgtype = LTG_TEAMACCOMPANY;
+ bs->formation_dist = 3.5 * 32; //3.5 meter
+ BotSetTeamStatus(bs);
+ bs->owndecision_time = FloatTime() + 5;
+ }
+ }
+ }
+ return;
+ }
+ //if the enemy has our flag
+ else if (flagstatus == 2) {
+ //
+ if (bs->owndecision_time < FloatTime()) {
+ //if enemy flag carrier is visible
+ c = BotEnemyFlagCarrierVisible(bs);
+ if (c >= 0) {
+ //FIXME: fight enemy flag carrier
+ }
+ //if not already doing something important
+ if (bs->ltgtype != LTG_GETFLAG &&
+ bs->ltgtype != LTG_RETURNFLAG &&
+ bs->ltgtype != LTG_TEAMHELP &&
+ bs->ltgtype != LTG_TEAMACCOMPANY &&
+ bs->ltgtype != LTG_CAMPORDER &&
+ bs->ltgtype != LTG_PATROL &&
+ bs->ltgtype != LTG_GETITEM) {
+
+ BotRefuseOrder(bs);
+ bs->decisionmaker = bs->client;
+ bs->ordered = qfalse;
+ //
+ if (random() < 0.5) {
+ //go for the enemy flag
+ bs->ltgtype = LTG_GETFLAG;
+ }
+ else {
+ bs->ltgtype = LTG_RETURNFLAG;
+ }
+ //no team message
+ bs->teammessage_time = 0;
+ //set the time the bot will stop getting the flag
+ bs->teamgoal_time = FloatTime() + CTF_GETFLAG_TIME;
+ //get an alternative route goal towards the enemy base
+ BotGetAlternateRouteGoal(bs, BotOppositeTeam(bs));
+ //
+ BotSetTeamStatus(bs);
+ bs->owndecision_time = FloatTime() + 5;
+ }
+ }
+ return;
+ }
+ //if both flags Not at their bases
+ else if (flagstatus == 3) {
+ //
+ if (bs->owndecision_time < FloatTime()) {
+ // if not trying to return the flag and not following the team flag carrier
+ if ( bs->ltgtype != LTG_RETURNFLAG && bs->ltgtype != LTG_TEAMACCOMPANY ) {
+ //
+ c = BotTeamFlagCarrierVisible(bs);
+ // if there is a visible team mate flag carrier
+ if (c >= 0) {
+ BotRefuseOrder(bs);
+ //follow the flag carrier
+ bs->decisionmaker = bs->client;
+ bs->ordered = qfalse;
+ //the team mate
+ bs->teammate = c;
+ //last time the team mate was visible
+ bs->teammatevisible_time = FloatTime();
+ //no message
+ bs->teammessage_time = 0;
+ //no arrive message
+ bs->arrive_time = 1;
+ //
+ BotVoiceChat(bs, bs->teammate, VOICECHAT_ONFOLLOW);
+ //get the team goal time
+ bs->teamgoal_time = FloatTime() + TEAM_ACCOMPANY_TIME;
+ bs->ltgtype = LTG_TEAMACCOMPANY;
+ bs->formation_dist = 3.5 * 32; //3.5 meter
+ //
+ BotSetTeamStatus(bs);
+ bs->owndecision_time = FloatTime() + 5;
+ }
+ else {
+ BotRefuseOrder(bs);
+ bs->decisionmaker = bs->client;
+ bs->ordered = qfalse;
+ //get the enemy flag
+ bs->teammessage_time = FloatTime() + 2 * random();
+ //get the flag
+ bs->ltgtype = LTG_RETURNFLAG;
+ //set the time the bot will stop getting the flag
+ bs->teamgoal_time = FloatTime() + CTF_RETURNFLAG_TIME;
+ //get an alternative route goal towards the enemy base
+ BotGetAlternateRouteGoal(bs, BotOppositeTeam(bs));
+ //
+ BotSetTeamStatus(bs);
+ bs->owndecision_time = FloatTime() + 5;
+ }
+ }
+ }
+ return;
+ }
+ // don't just do something wait for the bot team leader to give orders
+ if (BotTeamLeader(bs)) {
+ return;
+ }
+ // if the bot is ordered to do something
+ if ( bs->lastgoal_ltgtype ) {
+ bs->teamgoal_time += 60;
+ }
+ // if the bot decided to do something on it's own and has a last ordered goal
+ if ( !bs->ordered && bs->lastgoal_ltgtype ) {
+ bs->ltgtype = 0;
+ }
+ //if already a CTF or team goal
+ if (bs->ltgtype == LTG_TEAMHELP ||
+ bs->ltgtype == LTG_TEAMACCOMPANY ||
+ bs->ltgtype == LTG_DEFENDKEYAREA ||
+ bs->ltgtype == LTG_GETFLAG ||
+ bs->ltgtype == LTG_RUSHBASE ||
+ bs->ltgtype == LTG_RETURNFLAG ||
+ bs->ltgtype == LTG_CAMPORDER ||
+ bs->ltgtype == LTG_PATROL ||
+ bs->ltgtype == LTG_GETITEM ||
+ bs->ltgtype == LTG_MAKELOVE_UNDER ||
+ bs->ltgtype == LTG_MAKELOVE_ONTOP) {
+ return;
+ }
+ //
+ if (BotSetLastOrderedTask(bs))
+ return;
+ //
+ if (bs->owndecision_time > FloatTime())
+ return;;
+ //if the bot is roaming
+ if (bs->ctfroam_time > FloatTime())
+ return;
+ //if the bot has anough aggression to decide what to do
+ if (BotAggression(bs) < 50)
+ return;
+ //set the time to send a message to the team mates
+ bs->teammessage_time = FloatTime() + 2 * random();
+ //
+ if (bs->teamtaskpreference & (TEAMTP_ATTACKER|TEAMTP_DEFENDER)) {
+ if (bs->teamtaskpreference & TEAMTP_ATTACKER) {
+ l1 = 0.7f;
+ }
+ else {
+ l1 = 0.2f;
+ }
+ l2 = 0.9f;
+ }
+ else {
+ l1 = 0.4f;
+ l2 = 0.7f;
+ }
+ //get the flag or defend the base
+ rnd = random();
+ if (rnd < l1 && ctf_redflag.areanum && ctf_blueflag.areanum) {
+ bs->decisionmaker = bs->client;
+ bs->ordered = qfalse;
+ bs->ltgtype = LTG_GETFLAG;
+ //set the time the bot will stop getting the flag
+ bs->teamgoal_time = FloatTime() + CTF_GETFLAG_TIME;
+ //get an alternative route goal towards the enemy base
+ BotGetAlternateRouteGoal(bs, BotOppositeTeam(bs));
+ BotSetTeamStatus(bs);
+ }
+ else if (rnd < l2 && ctf_redflag.areanum && ctf_blueflag.areanum) {
+ bs->decisionmaker = bs->client;
+ bs->ordered = qfalse;
+ //
+ if (BotTeam(bs) == TEAM_RED) memcpy(&bs->teamgoal, &ctf_redflag, sizeof(bot_goal_t));
+ else memcpy(&bs->teamgoal, &ctf_blueflag, sizeof(bot_goal_t));
+ //set the ltg type
+ bs->ltgtype = LTG_DEFENDKEYAREA;
+ //set the time the bot stops defending the base
+ bs->teamgoal_time = FloatTime() + TEAM_DEFENDKEYAREA_TIME;
+ bs->defendaway_time = 0;
+ BotSetTeamStatus(bs);
+ }
+ else {
+ bs->ltgtype = 0;
+ //set the time the bot will stop roaming
+ bs->ctfroam_time = FloatTime() + CTF_ROAM_TIME;
+ BotSetTeamStatus(bs);
+ }
+ bs->owndecision_time = FloatTime() + 5;
+#ifdef DEBUG
+ BotPrintTeamGoal(bs);
+#endif //DEBUG
+}
+
+/*
+==================
+BotCTFRetreatGoals
+==================
+*/
+void BotCTFRetreatGoals(bot_state_t *bs) {
+ //when carrying a flag in ctf the bot should rush to the base
+ if (BotCTFCarryingFlag(bs)) {
+ //if not already rushing to the base
+ if (bs->ltgtype != LTG_RUSHBASE) {
+ BotRefuseOrder(bs);
+ bs->ltgtype = LTG_RUSHBASE;
+ bs->teamgoal_time = FloatTime() + CTF_RUSHBASE_TIME;
+ bs->rushbaseaway_time = 0;
+ bs->decisionmaker = bs->client;
+ bs->ordered = qfalse;
+ BotSetTeamStatus(bs);
+ }
+ }
+}
+
+#ifdef MISSIONPACK
+/*
+==================
+Bot1FCTFSeekGoals
+==================
+*/
+void Bot1FCTFSeekGoals(bot_state_t *bs) {
+ aas_entityinfo_t entinfo;
+ float rnd, l1, l2;
+ int c;
+
+ //when carrying a flag in ctf the bot should rush to the base
+ if (Bot1FCTFCarryingFlag(bs)) {
+ //if not already rushing to the base
+ if (bs->ltgtype != LTG_RUSHBASE) {
+ BotRefuseOrder(bs);
+ bs->ltgtype = LTG_RUSHBASE;
+ bs->teamgoal_time = FloatTime() + CTF_RUSHBASE_TIME;
+ bs->rushbaseaway_time = 0;
+ bs->decisionmaker = bs->client;
+ bs->ordered = qfalse;
+ //get an alternative route goal towards the enemy base
+ BotGetAlternateRouteGoal(bs, BotOppositeTeam(bs));
+ //
+ BotSetTeamStatus(bs);
+ BotVoiceChat(bs, -1, VOICECHAT_IHAVEFLAG);
+ }
+ return;
+ }
+ // if the bot decided to follow someone
+ if ( bs->ltgtype == LTG_TEAMACCOMPANY && !bs->ordered ) {
+ // if the team mate being accompanied no longer carries the flag
+ BotEntityInfo(bs->teammate, &entinfo);
+ if (!EntityCarriesFlag(&entinfo)) {
+ bs->ltgtype = 0;
+ }
+ }
+ //our team has the flag
+ if (bs->neutralflagstatus == 1) {
+ if (bs->owndecision_time < FloatTime()) {
+ // if not already following someone
+ if (bs->ltgtype != LTG_TEAMACCOMPANY) {
+ //if there is a visible team mate flag carrier
+ c = BotTeamFlagCarrierVisible(bs);
+ if (c >= 0) {
+ BotRefuseOrder(bs);
+ //follow the flag carrier
+ bs->decisionmaker = bs->client;
+ bs->ordered = qfalse;
+ //the team mate
+ bs->teammate = c;
+ //last time the team mate was visible
+ bs->teammatevisible_time = FloatTime();
+ //no message
+ bs->teammessage_time = 0;
+ //no arrive message
+ bs->arrive_time = 1;
+ //
+ BotVoiceChat(bs, bs->teammate, VOICECHAT_ONFOLLOW);
+ //get the team goal time
+ bs->teamgoal_time = FloatTime() + TEAM_ACCOMPANY_TIME;
+ bs->ltgtype = LTG_TEAMACCOMPANY;
+ bs->formation_dist = 3.5 * 32; //3.5 meter
+ BotSetTeamStatus(bs);
+ bs->owndecision_time = FloatTime() + 5;
+ return;
+ }
+ }
+ //if already a CTF or team goal
+ if (bs->ltgtype == LTG_TEAMHELP ||
+ bs->ltgtype == LTG_TEAMACCOMPANY ||
+ bs->ltgtype == LTG_DEFENDKEYAREA ||
+ bs->ltgtype == LTG_GETFLAG ||
+ bs->ltgtype == LTG_RUSHBASE ||
+ bs->ltgtype == LTG_CAMPORDER ||
+ bs->ltgtype == LTG_PATROL ||
+ bs->ltgtype == LTG_ATTACKENEMYBASE ||
+ bs->ltgtype == LTG_GETITEM ||
+ bs->ltgtype == LTG_MAKELOVE_UNDER ||
+ bs->ltgtype == LTG_MAKELOVE_ONTOP) {
+ return;
+ }
+ //if not already attacking the enemy base
+ if (bs->ltgtype != LTG_ATTACKENEMYBASE) {
+ BotRefuseOrder(bs);
+ bs->decisionmaker = bs->client;
+ bs->ordered = qfalse;
+ //
+ if (BotTeam(bs) == TEAM_RED) memcpy(&bs->teamgoal, &ctf_blueflag, sizeof(bot_goal_t));
+ else memcpy(&bs->teamgoal, &ctf_redflag, sizeof(bot_goal_t));
+ //set the ltg type
+ bs->ltgtype = LTG_ATTACKENEMYBASE;
+ //set the time the bot will stop getting the flag
+ bs->teamgoal_time = FloatTime() + TEAM_ATTACKENEMYBASE_TIME;
+ BotSetTeamStatus(bs);
+ bs->owndecision_time = FloatTime() + 5;
+ }
+ }
+ return;
+ }
+ //enemy team has the flag
+ else if (bs->neutralflagstatus == 2) {
+ if (bs->owndecision_time < FloatTime()) {
+ c = BotEnemyFlagCarrierVisible(bs);
+ if (c >= 0) {
+ //FIXME: attack enemy flag carrier
+ }
+ //if already a CTF or team goal
+ if (bs->ltgtype == LTG_TEAMHELP ||
+ bs->ltgtype == LTG_TEAMACCOMPANY ||
+ bs->ltgtype == LTG_CAMPORDER ||
+ bs->ltgtype == LTG_PATROL ||
+ bs->ltgtype == LTG_GETITEM) {
+ return;
+ }
+ // if not already defending the base
+ if (bs->ltgtype != LTG_DEFENDKEYAREA) {
+ BotRefuseOrder(bs);
+ bs->decisionmaker = bs->client;
+ bs->ordered = qfalse;
+ //
+ if (BotTeam(bs) == TEAM_RED) memcpy(&bs->teamgoal, &ctf_redflag, sizeof(bot_goal_t));
+ else memcpy(&bs->teamgoal, &ctf_blueflag, sizeof(bot_goal_t));
+ //set the ltg type
+ bs->ltgtype = LTG_DEFENDKEYAREA;
+ //set the time the bot stops defending the base
+ bs->teamgoal_time = FloatTime() + TEAM_DEFENDKEYAREA_TIME;
+ bs->defendaway_time = 0;
+ BotSetTeamStatus(bs);
+ bs->owndecision_time = FloatTime() + 5;
+ }
+ }
+ return;
+ }
+ // don't just do something wait for the bot team leader to give orders
+ if (BotTeamLeader(bs)) {
+ return;
+ }
+ // if the bot is ordered to do something
+ if ( bs->lastgoal_ltgtype ) {
+ bs->teamgoal_time += 60;
+ }
+ // if the bot decided to do something on it's own and has a last ordered goal
+ if ( !bs->ordered && bs->lastgoal_ltgtype ) {
+ bs->ltgtype = 0;
+ }
+ //if already a CTF or team goal
+ if (bs->ltgtype == LTG_TEAMHELP ||
+ bs->ltgtype == LTG_TEAMACCOMPANY ||
+ bs->ltgtype == LTG_DEFENDKEYAREA ||
+ bs->ltgtype == LTG_GETFLAG ||
+ bs->ltgtype == LTG_RUSHBASE ||
+ bs->ltgtype == LTG_RETURNFLAG ||
+ bs->ltgtype == LTG_CAMPORDER ||
+ bs->ltgtype == LTG_PATROL ||
+ bs->ltgtype == LTG_ATTACKENEMYBASE ||
+ bs->ltgtype == LTG_GETITEM ||
+ bs->ltgtype == LTG_MAKELOVE_UNDER ||
+ bs->ltgtype == LTG_MAKELOVE_ONTOP) {
+ return;
+ }
+ //
+ if (BotSetLastOrderedTask(bs))
+ return;
+ //
+ if (bs->owndecision_time > FloatTime())
+ return;;
+ //if the bot is roaming
+ if (bs->ctfroam_time > FloatTime())
+ return;
+ //if the bot has anough aggression to decide what to do
+ if (BotAggression(bs) < 50)
+ return;
+ //set the time to send a message to the team mates
+ bs->teammessage_time = FloatTime() + 2 * random();
+ //
+ if (bs->teamtaskpreference & (TEAMTP_ATTACKER|TEAMTP_DEFENDER)) {
+ if (bs->teamtaskpreference & TEAMTP_ATTACKER) {
+ l1 = 0.7f;
+ }
+ else {
+ l1 = 0.2f;
+ }
+ l2 = 0.9f;
+ }
+ else {
+ l1 = 0.4f;
+ l2 = 0.7f;
+ }
+ //get the flag or defend the base
+ rnd = random();
+ if (rnd < l1 && ctf_neutralflag.areanum) {
+ bs->decisionmaker = bs->client;
+ bs->ordered = qfalse;
+ bs->ltgtype = LTG_GETFLAG;
+ //set the time the bot will stop getting the flag
+ bs->teamgoal_time = FloatTime() + CTF_GETFLAG_TIME;
+ BotSetTeamStatus(bs);
+ }
+ else if (rnd < l2 && ctf_redflag.areanum && ctf_blueflag.areanum) {
+ bs->decisionmaker = bs->client;
+ bs->ordered = qfalse;
+ //
+ if (BotTeam(bs) == TEAM_RED) memcpy(&bs->teamgoal, &ctf_redflag, sizeof(bot_goal_t));
+ else memcpy(&bs->teamgoal, &ctf_blueflag, sizeof(bot_goal_t));
+ //set the ltg type
+ bs->ltgtype = LTG_DEFENDKEYAREA;
+ //set the time the bot stops defending the base
+ bs->teamgoal_time = FloatTime() + TEAM_DEFENDKEYAREA_TIME;
+ bs->defendaway_time = 0;
+ BotSetTeamStatus(bs);
+ }
+ else {
+ bs->ltgtype = 0;
+ //set the time the bot will stop roaming
+ bs->ctfroam_time = FloatTime() + CTF_ROAM_TIME;
+ BotSetTeamStatus(bs);
+ }
+ bs->owndecision_time = FloatTime() + 5;
+#ifdef DEBUG
+ BotPrintTeamGoal(bs);
+#endif //DEBUG
+}
+
+/*
+==================
+Bot1FCTFRetreatGoals
+==================
+*/
+void Bot1FCTFRetreatGoals(bot_state_t *bs) {
+ //when carrying a flag in ctf the bot should rush to the enemy base
+ if (Bot1FCTFCarryingFlag(bs)) {
+ //if not already rushing to the base
+ if (bs->ltgtype != LTG_RUSHBASE) {
+ BotRefuseOrder(bs);
+ bs->ltgtype = LTG_RUSHBASE;
+ bs->teamgoal_time = FloatTime() + CTF_RUSHBASE_TIME;
+ bs->rushbaseaway_time = 0;
+ bs->decisionmaker = bs->client;
+ bs->ordered = qfalse;
+ //get an alternative route goal towards the enemy base
+ BotGetAlternateRouteGoal(bs, BotOppositeTeam(bs));
+ BotSetTeamStatus(bs);
+ }
+ }
+}
+
+/*
+==================
+BotObeliskSeekGoals
+==================
+*/
+void BotObeliskSeekGoals(bot_state_t *bs) {
+ float rnd, l1, l2;
+
+ // don't just do something wait for the bot team leader to give orders
+ if (BotTeamLeader(bs)) {
+ return;
+ }
+ // if the bot is ordered to do something
+ if ( bs->lastgoal_ltgtype ) {
+ bs->teamgoal_time += 60;
+ }
+ //if already a team goal
+ if (bs->ltgtype == LTG_TEAMHELP ||
+ bs->ltgtype == LTG_TEAMACCOMPANY ||
+ bs->ltgtype == LTG_DEFENDKEYAREA ||
+ bs->ltgtype == LTG_GETFLAG ||
+ bs->ltgtype == LTG_RUSHBASE ||
+ bs->ltgtype == LTG_RETURNFLAG ||
+ bs->ltgtype == LTG_CAMPORDER ||
+ bs->ltgtype == LTG_PATROL ||
+ bs->ltgtype == LTG_ATTACKENEMYBASE ||
+ bs->ltgtype == LTG_GETITEM ||
+ bs->ltgtype == LTG_MAKELOVE_UNDER ||
+ bs->ltgtype == LTG_MAKELOVE_ONTOP) {
+ return;
+ }
+ //
+ if (BotSetLastOrderedTask(bs))
+ return;
+ //if the bot is roaming
+ if (bs->ctfroam_time > FloatTime())
+ return;
+ //if the bot has anough aggression to decide what to do
+ if (BotAggression(bs) < 50)
+ return;
+ //set the time to send a message to the team mates
+ bs->teammessage_time = FloatTime() + 2 * random();
+ //
+ if (bs->teamtaskpreference & (TEAMTP_ATTACKER|TEAMTP_DEFENDER)) {
+ if (bs->teamtaskpreference & TEAMTP_ATTACKER) {
+ l1 = 0.7f;
+ }
+ else {
+ l1 = 0.2f;
+ }
+ l2 = 0.9f;
+ }
+ else {
+ l1 = 0.4f;
+ l2 = 0.7f;
+ }
+ //get the flag or defend the base
+ rnd = random();
+ if (rnd < l1 && redobelisk.areanum && blueobelisk.areanum) {
+ bs->decisionmaker = bs->client;
+ bs->ordered = qfalse;
+ //
+ if (BotTeam(bs) == TEAM_RED) memcpy(&bs->teamgoal, &blueobelisk, sizeof(bot_goal_t));
+ else memcpy(&bs->teamgoal, &redobelisk, sizeof(bot_goal_t));
+ //set the ltg type
+ bs->ltgtype = LTG_ATTACKENEMYBASE;
+ //set the time the bot will stop attacking the enemy base
+ bs->teamgoal_time = FloatTime() + TEAM_ATTACKENEMYBASE_TIME;
+ //get an alternate route goal towards the enemy base
+ BotGetAlternateRouteGoal(bs, BotOppositeTeam(bs));
+ BotSetTeamStatus(bs);
+ }
+ else if (rnd < l2 && redobelisk.areanum && blueobelisk.areanum) {
+ bs->decisionmaker = bs->client;
+ bs->ordered = qfalse;
+ //
+ if (BotTeam(bs) == TEAM_RED) memcpy(&bs->teamgoal, &redobelisk, sizeof(bot_goal_t));
+ else memcpy(&bs->teamgoal, &blueobelisk, sizeof(bot_goal_t));
+ //set the ltg type
+ bs->ltgtype = LTG_DEFENDKEYAREA;
+ //set the time the bot stops defending the base
+ bs->teamgoal_time = FloatTime() + TEAM_DEFENDKEYAREA_TIME;
+ bs->defendaway_time = 0;
+ BotSetTeamStatus(bs);
+ }
+ else {
+ bs->ltgtype = 0;
+ //set the time the bot will stop roaming
+ bs->ctfroam_time = FloatTime() + CTF_ROAM_TIME;
+ BotSetTeamStatus(bs);
+ }
+}
+
+/*
+==================
+BotGoHarvest
+==================
+*/
+void BotGoHarvest(bot_state_t *bs) {
+ //
+ if (BotTeam(bs) == TEAM_RED) memcpy(&bs->teamgoal, &blueobelisk, sizeof(bot_goal_t));
+ else memcpy(&bs->teamgoal, &redobelisk, sizeof(bot_goal_t));
+ //set the ltg type
+ bs->ltgtype = LTG_HARVEST;
+ //set the time the bot will stop harvesting
+ bs->teamgoal_time = FloatTime() + TEAM_HARVEST_TIME;
+ bs->harvestaway_time = 0;
+ BotSetTeamStatus(bs);
+}
+
+/*
+==================
+BotObeliskRetreatGoals
+==================
+*/
+void BotObeliskRetreatGoals(bot_state_t *bs) {
+ //nothing special
+}
+
+/*
+==================
+BotHarvesterSeekGoals
+==================
+*/
+void BotHarvesterSeekGoals(bot_state_t *bs) {
+ aas_entityinfo_t entinfo;
+ float rnd, l1, l2;
+ int c;
+
+ //when carrying cubes in harvester the bot should rush to the base
+ if (BotHarvesterCarryingCubes(bs)) {
+ //if not already rushing to the base
+ if (bs->ltgtype != LTG_RUSHBASE) {
+ BotRefuseOrder(bs);
+ bs->ltgtype = LTG_RUSHBASE;
+ bs->teamgoal_time = FloatTime() + CTF_RUSHBASE_TIME;
+ bs->rushbaseaway_time = 0;
+ bs->decisionmaker = bs->client;
+ bs->ordered = qfalse;
+ //get an alternative route goal towards the enemy base
+ BotGetAlternateRouteGoal(bs, BotOppositeTeam(bs));
+ //
+ BotSetTeamStatus(bs);
+ }
+ return;
+ }
+ // don't just do something wait for the bot team leader to give orders
+ if (BotTeamLeader(bs)) {
+ return;
+ }
+ // if the bot decided to follow someone
+ if ( bs->ltgtype == LTG_TEAMACCOMPANY && !bs->ordered ) {
+ // if the team mate being accompanied no longer carries the flag
+ BotEntityInfo(bs->teammate, &entinfo);
+ if (!EntityCarriesCubes(&entinfo)) {
+ bs->ltgtype = 0;
+ }
+ }
+ // if the bot is ordered to do something
+ if ( bs->lastgoal_ltgtype ) {
+ bs->teamgoal_time += 60;
+ }
+ //if not yet doing something
+ if (bs->ltgtype == LTG_TEAMHELP ||
+ bs->ltgtype == LTG_TEAMACCOMPANY ||
+ bs->ltgtype == LTG_DEFENDKEYAREA ||
+ bs->ltgtype == LTG_GETFLAG ||
+ bs->ltgtype == LTG_CAMPORDER ||
+ bs->ltgtype == LTG_PATROL ||
+ bs->ltgtype == LTG_ATTACKENEMYBASE ||
+ bs->ltgtype == LTG_HARVEST ||
+ bs->ltgtype == LTG_GETITEM ||
+ bs->ltgtype == LTG_MAKELOVE_UNDER ||
+ bs->ltgtype == LTG_MAKELOVE_ONTOP) {
+ return;
+ }
+ //
+ if (BotSetLastOrderedTask(bs))
+ return;
+ //if the bot is roaming
+ if (bs->ctfroam_time > FloatTime())
+ return;
+ //if the bot has anough aggression to decide what to do
+ if (BotAggression(bs) < 50)
+ return;
+ //set the time to send a message to the team mates
+ bs->teammessage_time = FloatTime() + 2 * random();
+ //
+ c = BotEnemyCubeCarrierVisible(bs);
+ if (c >= 0) {
+ //FIXME: attack enemy cube carrier
+ }
+ if (bs->ltgtype != LTG_TEAMACCOMPANY) {
+ //if there is a visible team mate carrying cubes
+ c = BotTeamCubeCarrierVisible(bs);
+ if (c >= 0) {
+ //follow the team mate carrying cubes
+ bs->decisionmaker = bs->client;
+ bs->ordered = qfalse;
+ //the team mate
+ bs->teammate = c;
+ //last time the team mate was visible
+ bs->teammatevisible_time = FloatTime();
+ //no message
+ bs->teammessage_time = 0;
+ //no arrive message
+ bs->arrive_time = 1;
+ //
+ BotVoiceChat(bs, bs->teammate, VOICECHAT_ONFOLLOW);
+ //get the team goal time
+ bs->teamgoal_time = FloatTime() + TEAM_ACCOMPANY_TIME;
+ bs->ltgtype = LTG_TEAMACCOMPANY;
+ bs->formation_dist = 3.5 * 32; //3.5 meter
+ BotSetTeamStatus(bs);
+ return;
+ }
+ }
+ //
+ if (bs->teamtaskpreference & (TEAMTP_ATTACKER|TEAMTP_DEFENDER)) {
+ if (bs->teamtaskpreference & TEAMTP_ATTACKER) {
+ l1 = 0.7f;
+ }
+ else {
+ l1 = 0.2f;
+ }
+ l2 = 0.9f;
+ }
+ else {
+ l1 = 0.4f;
+ l2 = 0.7f;
+ }
+ //
+ rnd = random();
+ if (rnd < l1 && redobelisk.areanum && blueobelisk.areanum) {
+ bs->decisionmaker = bs->client;
+ bs->ordered = qfalse;
+ BotGoHarvest(bs);
+ }
+ else if (rnd < l2 && redobelisk.areanum && blueobelisk.areanum) {
+ bs->decisionmaker = bs->client;
+ bs->ordered = qfalse;
+ //
+ if (BotTeam(bs) == TEAM_RED) memcpy(&bs->teamgoal, &redobelisk, sizeof(bot_goal_t));
+ else memcpy(&bs->teamgoal, &blueobelisk, sizeof(bot_goal_t));
+ //set the ltg type
+ bs->ltgtype = LTG_DEFENDKEYAREA;
+ //set the time the bot stops defending the base
+ bs->teamgoal_time = FloatTime() + TEAM_DEFENDKEYAREA_TIME;
+ bs->defendaway_time = 0;
+ BotSetTeamStatus(bs);
+ }
+ else {
+ bs->ltgtype = 0;
+ //set the time the bot will stop roaming
+ bs->ctfroam_time = FloatTime() + CTF_ROAM_TIME;
+ BotSetTeamStatus(bs);
+ }
+}
+
+/*
+==================
+BotHarvesterRetreatGoals
+==================
+*/
+void BotHarvesterRetreatGoals(bot_state_t *bs) {
+ //when carrying cubes in harvester the bot should rush to the base
+ if (BotHarvesterCarryingCubes(bs)) {
+ //if not already rushing to the base
+ if (bs->ltgtype != LTG_RUSHBASE) {
+ BotRefuseOrder(bs);
+ bs->ltgtype = LTG_RUSHBASE;
+ bs->teamgoal_time = FloatTime() + CTF_RUSHBASE_TIME;
+ bs->rushbaseaway_time = 0;
+ bs->decisionmaker = bs->client;
+ bs->ordered = qfalse;
+ BotSetTeamStatus(bs);
+ }
+ return;
+ }
+}
+#endif
+
+/*
+==================
+BotTeamGoals
+==================
+*/
+void BotTeamGoals(bot_state_t *bs, int retreat) {
+
+ if ( retreat ) {
+ if (gametype == GT_CTF) {
+ BotCTFRetreatGoals(bs);
+ }
+#ifdef MISSIONPACK
+ else if (gametype == GT_1FCTF) {
+ Bot1FCTFRetreatGoals(bs);
+ }
+ else if (gametype == GT_OBELISK) {
+ BotObeliskRetreatGoals(bs);
+ }
+ else if (gametype == GT_HARVESTER) {
+ BotHarvesterRetreatGoals(bs);
+ }
+#endif
+ }
+ else {
+ if (gametype == GT_CTF) {
+ //decide what to do in CTF mode
+ BotCTFSeekGoals(bs);
+ }
+#ifdef MISSIONPACK
+ else if (gametype == GT_1FCTF) {
+ Bot1FCTFSeekGoals(bs);
+ }
+ else if (gametype == GT_OBELISK) {
+ BotObeliskSeekGoals(bs);
+ }
+ else if (gametype == GT_HARVESTER) {
+ BotHarvesterSeekGoals(bs);
+ }
+#endif
+ }
+ // reset the order time which is used to see if
+ // we decided to refuse an order
+ bs->order_time = 0;
+}
+
+/*
+==================
+BotPointAreaNum
+==================
+*/
+int BotPointAreaNum(vec3_t origin) {
+ int areanum, numareas, areas[10];
+ vec3_t end;
+
+ areanum = trap_AAS_PointAreaNum(origin);
+ if (areanum) return areanum;
+ VectorCopy(origin, end);
+ end[2] += 10;
+ numareas = trap_AAS_TraceAreas(origin, end, areas, NULL, 10);
+ if (numareas > 0) return areas[0];
+ return 0;
+}
+
+/*
+==================
+ClientName
+==================
+*/
+char *ClientName(int client, char *name, int size) {
+ char buf[MAX_INFO_STRING];
+
+ if (client < 0 || client >= MAX_CLIENTS) {
+ BotAI_Print(PRT_ERROR, "ClientName: client out of range\n");
+ return "[client out of range]";
+ }
+ trap_GetConfigstring(CS_PLAYERS+client, buf, sizeof(buf));
+ strncpy(name, Info_ValueForKey(buf, "n"), size-1);
+ name[size-1] = '\0';
+ Q_CleanStr( name );
+ return name;
+}
+
+/*
+==================
+ClientSkin
+==================
+*/
+char *ClientSkin(int client, char *skin, int size) {
+ char buf[MAX_INFO_STRING];
+
+ if (client < 0 || client >= MAX_CLIENTS) {
+ BotAI_Print(PRT_ERROR, "ClientSkin: client out of range\n");
+ return "[client out of range]";
+ }
+ trap_GetConfigstring(CS_PLAYERS+client, buf, sizeof(buf));
+ strncpy(skin, Info_ValueForKey(buf, "model"), size-1);
+ skin[size-1] = '\0';
+ return skin;
+}
+
+/*
+==================
+ClientFromName
+==================
+*/
+int ClientFromName(char *name) {
+ int i;
+ char buf[MAX_INFO_STRING];
+ static int maxclients;
+
+ if (!maxclients)
+ maxclients = trap_Cvar_VariableIntegerValue("sv_maxclients");
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ trap_GetConfigstring(CS_PLAYERS+i, buf, sizeof(buf));
+ Q_CleanStr( buf );
+ if (!Q_stricmp(Info_ValueForKey(buf, "n"), name)) return i;
+ }
+ return -1;
+}
+
+/*
+==================
+ClientOnSameTeamFromName
+==================
+*/
+int ClientOnSameTeamFromName(bot_state_t *bs, char *name) {
+ int i;
+ char buf[MAX_INFO_STRING];
+ static int maxclients;
+
+ if (!maxclients)
+ maxclients = trap_Cvar_VariableIntegerValue("sv_maxclients");
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ if (!BotSameTeam(bs, i))
+ continue;
+ trap_GetConfigstring(CS_PLAYERS+i, buf, sizeof(buf));
+ Q_CleanStr( buf );
+ if (!Q_stricmp(Info_ValueForKey(buf, "n"), name)) return i;
+ }
+ return -1;
+}
+
+/*
+==================
+stristr
+==================
+*/
+char *stristr(char *str, char *charset) {
+ int i;
+
+ while(*str) {
+ for (i = 0; charset[i] && str[i]; i++) {
+ if (toupper(charset[i]) != toupper(str[i])) break;
+ }
+ if (!charset[i]) return str;
+ str++;
+ }
+ return NULL;
+}
+
+/*
+==================
+EasyClientName
+==================
+*/
+char *EasyClientName(int client, char *buf, int size) {
+ int i;
+ char *str1, *str2, *ptr, c;
+ char name[128];
+
+ strcpy(name, ClientName(client, name, sizeof(name)));
+ for (i = 0; name[i]; i++) name[i] &= 127;
+ //remove all spaces
+ for (ptr = strstr(name, " "); ptr; ptr = strstr(name, " ")) {
+ memmove(ptr, ptr+1, strlen(ptr+1)+1);
+ }
+ //check for [x] and ]x[ clan names
+ str1 = strstr(name, "[");
+ str2 = strstr(name, "]");
+ if (str1 && str2) {
+ if (str2 > str1) memmove(str1, str2+1, strlen(str2+1)+1);
+ else memmove(str2, str1+1, strlen(str1+1)+1);
+ }
+ //remove Mr prefix
+ if ((name[0] == 'm' || name[0] == 'M') &&
+ (name[1] == 'r' || name[1] == 'R')) {
+ memmove(name, name+2, strlen(name+2)+1);
+ }
+ //only allow lower case alphabet characters
+ ptr = name;
+ while(*ptr) {
+ c = *ptr;
+ if ((c >= 'a' && c <= 'z') ||
+ (c >= '0' && c <= '9') || c == '_') {
+ ptr++;
+ }
+ else if (c >= 'A' && c <= 'Z') {
+ *ptr += 'a' - 'A';
+ ptr++;
+ }
+ else {
+ memmove(ptr, ptr+1, strlen(ptr + 1)+1);
+ }
+ }
+ strncpy(buf, name, size-1);
+ buf[size-1] = '\0';
+ return buf;
+}
+
+/*
+==================
+BotSynonymContext
+==================
+*/
+int BotSynonymContext(bot_state_t *bs) {
+ int context;
+
+ context = CONTEXT_NORMAL|CONTEXT_NEARBYITEM|CONTEXT_NAMES;
+ //
+ if (gametype == GT_CTF
+#ifdef MISSIONPACK
+ || gametype == GT_1FCTF
+#endif
+ ) {
+ if (BotTeam(bs) == TEAM_RED) context |= CONTEXT_CTFREDTEAM;
+ else context |= CONTEXT_CTFBLUETEAM;
+ }
+#ifdef MISSIONPACK
+ else if (gametype == GT_OBELISK) {
+ if (BotTeam(bs) == TEAM_RED) context |= CONTEXT_OBELISKREDTEAM;
+ else context |= CONTEXT_OBELISKBLUETEAM;
+ }
+ else if (gametype == GT_HARVESTER) {
+ if (BotTeam(bs) == TEAM_RED) context |= CONTEXT_HARVESTERREDTEAM;
+ else context |= CONTEXT_HARVESTERBLUETEAM;
+ }
+#endif
+ return context;
+}
+
+/*
+==================
+BotChooseWeapon
+==================
+*/
+void BotChooseWeapon(bot_state_t *bs) {
+ int newweaponnum;
+
+ if (bs->cur_ps.weaponstate == WEAPON_RAISING ||
+ bs->cur_ps.weaponstate == WEAPON_DROPPING) {
+ trap_EA_SelectWeapon(bs->client, bs->weaponnum);
+ }
+ else {
+ newweaponnum = trap_BotChooseBestFightWeapon(bs->ws, bs->inventory);
+ if (bs->weaponnum != newweaponnum) bs->weaponchange_time = FloatTime();
+ bs->weaponnum = newweaponnum;
+ //BotAI_Print(PRT_MESSAGE, "bs->weaponnum = %d\n", bs->weaponnum);
+ trap_EA_SelectWeapon(bs->client, bs->weaponnum);
+ }
+}
+
+/*
+==================
+BotSetupForMovement
+==================
+*/
+void BotSetupForMovement(bot_state_t *bs) {
+ bot_initmove_t initmove;
+
+ memset(&initmove, 0, sizeof(bot_initmove_t));
+ VectorCopy(bs->cur_ps.origin, initmove.origin);
+ VectorCopy(bs->cur_ps.velocity, initmove.velocity);
+ VectorClear(initmove.viewoffset);
+ initmove.viewoffset[2] += bs->cur_ps.viewheight;
+ initmove.entitynum = bs->entitynum;
+ initmove.client = bs->client;
+ initmove.thinktime = bs->thinktime;
+ //set the onground flag
+ if (bs->cur_ps.groundEntityNum != ENTITYNUM_NONE) initmove.or_moveflags |= MFL_ONGROUND;
+ //set the teleported flag
+ if ((bs->cur_ps.pm_flags & PMF_TIME_KNOCKBACK) && (bs->cur_ps.pm_time > 0)) {
+ initmove.or_moveflags |= MFL_TELEPORTED;
+ }
+ //set the waterjump flag
+ if ((bs->cur_ps.pm_flags & PMF_TIME_WATERJUMP) && (bs->cur_ps.pm_time > 0)) {
+ initmove.or_moveflags |= MFL_WATERJUMP;
+ }
+ //set presence type
+ if (bs->cur_ps.pm_flags & PMF_DUCKED) initmove.presencetype = PRESENCE_CROUCH;
+ else initmove.presencetype = PRESENCE_NORMAL;
+ //
+ if (bs->walker > 0.5) initmove.or_moveflags |= MFL_WALK;
+ //
+ VectorCopy(bs->viewangles, initmove.viewangles);
+ //
+ trap_BotInitMoveState(bs->ms, &initmove);
+}
+
+/*
+==================
+BotCheckItemPickup
+==================
+*/
+void BotCheckItemPickup(bot_state_t *bs, int *oldinventory) {
+#ifdef MISSIONPACK
+ int offence, leader;
+
+ if (gametype <= GT_TEAM)
+ return;
+
+ offence = -1;
+ // go into offence if picked up the kamikaze or invulnerability
+ if (!oldinventory[INVENTORY_KAMIKAZE] && bs->inventory[INVENTORY_KAMIKAZE] >= 1) {
+ offence = qtrue;
+ }
+ if (!oldinventory[INVENTORY_INVULNERABILITY] && bs->inventory[INVENTORY_INVULNERABILITY] >= 1) {
+ offence = qtrue;
+ }
+ // if not already wearing the kamikaze or invulnerability
+ if (!bs->inventory[INVENTORY_KAMIKAZE] && !bs->inventory[INVENTORY_INVULNERABILITY]) {
+ if (!oldinventory[INVENTORY_SCOUT] && bs->inventory[INVENTORY_SCOUT] >= 1) {
+ offence = qtrue;
+ }
+ if (!oldinventory[INVENTORY_GUARD] && bs->inventory[INVENTORY_GUARD] >= 1) {
+ offence = qtrue;
+ }
+ if (!oldinventory[INVENTORY_DOUBLER] && bs->inventory[INVENTORY_DOUBLER] >= 1) {
+ offence = qfalse;
+ }
+ if (!oldinventory[INVENTORY_AMMOREGEN] && bs->inventory[INVENTORY_AMMOREGEN] >= 1) {
+ offence = qfalse;
+ }
+ }
+
+ if (offence >= 0) {
+ leader = ClientFromName(bs->teamleader);
+ if (offence) {
+ if (!(bs->teamtaskpreference & TEAMTP_ATTACKER)) {
+ // if we have a bot team leader
+ if (BotTeamLeader(bs)) {
+ // tell the leader we want to be on offence
+ BotVoiceChat(bs, leader, VOICECHAT_WANTONOFFENSE);
+ //BotAI_BotInitialChat(bs, "wantoffence", NULL);
+ //trap_BotEnterChat(bs->cs, leader, CHAT_TELL);
+ }
+ else if (g_spSkill.integer <= 3) {
+ if ( bs->ltgtype != LTG_GETFLAG &&
+ bs->ltgtype != LTG_ATTACKENEMYBASE &&
+ bs->ltgtype != LTG_HARVEST ) {
+ //
+ if ((gametype != GT_CTF || (bs->redflagstatus == 0 && bs->blueflagstatus == 0)) &&
+ (gametype != GT_1FCTF || bs->neutralflagstatus == 0) ) {
+ // tell the leader we want to be on offence
+ BotVoiceChat(bs, leader, VOICECHAT_WANTONOFFENSE);
+ //BotAI_BotInitialChat(bs, "wantoffence", NULL);
+ //trap_BotEnterChat(bs->cs, leader, CHAT_TELL);
+ }
+ }
+ bs->teamtaskpreference |= TEAMTP_ATTACKER;
+ }
+ }
+ bs->teamtaskpreference &= ~TEAMTP_DEFENDER;
+ }
+ else {
+ if (!(bs->teamtaskpreference & TEAMTP_DEFENDER)) {
+ // if we have a bot team leader
+ if (BotTeamLeader(bs)) {
+ // tell the leader we want to be on defense
+ BotVoiceChat(bs, -1, VOICECHAT_WANTONDEFENSE);
+ //BotAI_BotInitialChat(bs, "wantdefence", NULL);
+ //trap_BotEnterChat(bs->cs, leader, CHAT_TELL);
+ }
+ else if (g_spSkill.integer <= 3) {
+ if ( bs->ltgtype != LTG_DEFENDKEYAREA ) {
+ //
+ if ((gametype != GT_CTF || (bs->redflagstatus == 0 && bs->blueflagstatus == 0)) &&
+ (gametype != GT_1FCTF || bs->neutralflagstatus == 0) ) {
+ // tell the leader we want to be on defense
+ BotVoiceChat(bs, -1, VOICECHAT_WANTONDEFENSE);
+ //BotAI_BotInitialChat(bs, "wantdefence", NULL);
+ //trap_BotEnterChat(bs->cs, leader, CHAT_TELL);
+ }
+ }
+ }
+ bs->teamtaskpreference |= TEAMTP_DEFENDER;
+ }
+ bs->teamtaskpreference &= ~TEAMTP_ATTACKER;
+ }
+ }
+#endif
+}
+
+/*
+==================
+BotUpdateInventory
+==================
+*/
+void BotUpdateInventory(bot_state_t *bs) {
+ int oldinventory[MAX_ITEMS];
+
+ memcpy(oldinventory, bs->inventory, sizeof(oldinventory));
+ //armor
+ bs->inventory[INVENTORY_ARMOR] = bs->cur_ps.stats[STAT_ARMOR];
+ //weapons
+ bs->inventory[INVENTORY_GAUNTLET] = (bs->cur_ps.stats[STAT_WEAPONS] & (1 << WP_GAUNTLET)) != 0;
+ bs->inventory[INVENTORY_SHOTGUN] = (bs->cur_ps.stats[STAT_WEAPONS] & (1 << WP_SHOTGUN)) != 0;
+ bs->inventory[INVENTORY_MACHINEGUN] = (bs->cur_ps.stats[STAT_WEAPONS] & (1 << WP_MACHINEGUN)) != 0;
+ bs->inventory[INVENTORY_GRENADELAUNCHER] = (bs->cur_ps.stats[STAT_WEAPONS] & (1 << WP_GRENADE_LAUNCHER)) != 0;
+ bs->inventory[INVENTORY_ROCKETLAUNCHER] = (bs->cur_ps.stats[STAT_WEAPONS] & (1 << WP_ROCKET_LAUNCHER)) != 0;
+ bs->inventory[INVENTORY_LIGHTNING] = (bs->cur_ps.stats[STAT_WEAPONS] & (1 << WP_LIGHTNING)) != 0;
+ bs->inventory[INVENTORY_RAILGUN] = (bs->cur_ps.stats[STAT_WEAPONS] & (1 << WP_RAILGUN)) != 0;
+ bs->inventory[INVENTORY_PLASMAGUN] = (bs->cur_ps.stats[STAT_WEAPONS] & (1 << WP_PLASMAGUN)) != 0;
+ bs->inventory[INVENTORY_BFG10K] = (bs->cur_ps.stats[STAT_WEAPONS] & (1 << WP_BFG)) != 0;
+ bs->inventory[INVENTORY_GRAPPLINGHOOK] = (bs->cur_ps.stats[STAT_WEAPONS] & (1 << WP_GRAPPLING_HOOK)) != 0;
+#ifdef MISSIONPACK
+ bs->inventory[INVENTORY_NAILGUN] = (bs->cur_ps.stats[STAT_WEAPONS] & (1 << WP_NAILGUN)) != 0;;
+ bs->inventory[INVENTORY_PROXLAUNCHER] = (bs->cur_ps.stats[STAT_WEAPONS] & (1 << WP_PROX_LAUNCHER)) != 0;;
+ bs->inventory[INVENTORY_CHAINGUN] = (bs->cur_ps.stats[STAT_WEAPONS] & (1 << WP_CHAINGUN)) != 0;;
+#endif
+ //ammo
+ bs->inventory[INVENTORY_SHELLS] = bs->cur_ps.ammo[WP_SHOTGUN];
+ bs->inventory[INVENTORY_BULLETS] = bs->cur_ps.ammo[WP_MACHINEGUN];
+ bs->inventory[INVENTORY_GRENADES] = bs->cur_ps.ammo[WP_GRENADE_LAUNCHER];
+ bs->inventory[INVENTORY_CELLS] = bs->cur_ps.ammo[WP_PLASMAGUN];
+ bs->inventory[INVENTORY_LIGHTNINGAMMO] = bs->cur_ps.ammo[WP_LIGHTNING];
+ bs->inventory[INVENTORY_ROCKETS] = bs->cur_ps.ammo[WP_ROCKET_LAUNCHER];
+ bs->inventory[INVENTORY_SLUGS] = bs->cur_ps.ammo[WP_RAILGUN];
+ bs->inventory[INVENTORY_BFGAMMO] = bs->cur_ps.ammo[WP_BFG];
+#ifdef MISSIONPACK
+ bs->inventory[INVENTORY_NAILS] = bs->cur_ps.ammo[WP_NAILGUN];
+ bs->inventory[INVENTORY_MINES] = bs->cur_ps.ammo[WP_PROX_LAUNCHER];
+ bs->inventory[INVENTORY_BELT] = bs->cur_ps.ammo[WP_CHAINGUN];
+#endif
+ //powerups
+ bs->inventory[INVENTORY_HEALTH] = bs->cur_ps.stats[STAT_HEALTH];
+ bs->inventory[INVENTORY_TELEPORTER] = bs->cur_ps.stats[STAT_HOLDABLE_ITEM] == MODELINDEX_TELEPORTER;
+ bs->inventory[INVENTORY_MEDKIT] = bs->cur_ps.stats[STAT_HOLDABLE_ITEM] == MODELINDEX_MEDKIT;
+#ifdef MISSIONPACK
+ bs->inventory[INVENTORY_KAMIKAZE] = bs->cur_ps.stats[STAT_HOLDABLE_ITEM] == MODELINDEX_KAMIKAZE;
+ bs->inventory[INVENTORY_PORTAL] = bs->cur_ps.stats[STAT_HOLDABLE_ITEM] == MODELINDEX_PORTAL;
+ bs->inventory[INVENTORY_INVULNERABILITY] = bs->cur_ps.stats[STAT_HOLDABLE_ITEM] == MODELINDEX_INVULNERABILITY;
+#endif
+ bs->inventory[INVENTORY_QUAD] = bs->cur_ps.powerups[PW_QUAD] != 0;
+ bs->inventory[INVENTORY_ENVIRONMENTSUIT] = bs->cur_ps.powerups[PW_BATTLESUIT] != 0;
+ bs->inventory[INVENTORY_HASTE] = bs->cur_ps.powerups[PW_HASTE] != 0;
+ bs->inventory[INVENTORY_INVISIBILITY] = bs->cur_ps.powerups[PW_INVIS] != 0;
+ bs->inventory[INVENTORY_REGEN] = bs->cur_ps.powerups[PW_REGEN] != 0;
+ bs->inventory[INVENTORY_FLIGHT] = bs->cur_ps.powerups[PW_FLIGHT] != 0;
+#ifdef MISSIONPACK
+ bs->inventory[INVENTORY_SCOUT] = bs->cur_ps.stats[STAT_PERSISTANT_POWERUP] == MODELINDEX_SCOUT;
+ bs->inventory[INVENTORY_GUARD] = bs->cur_ps.stats[STAT_PERSISTANT_POWERUP] == MODELINDEX_GUARD;
+ bs->inventory[INVENTORY_DOUBLER] = bs->cur_ps.stats[STAT_PERSISTANT_POWERUP] == MODELINDEX_DOUBLER;
+ bs->inventory[INVENTORY_AMMOREGEN] = bs->cur_ps.stats[STAT_PERSISTANT_POWERUP] == MODELINDEX_AMMOREGEN;
+#endif
+ bs->inventory[INVENTORY_REDFLAG] = bs->cur_ps.powerups[PW_REDFLAG] != 0;
+ bs->inventory[INVENTORY_BLUEFLAG] = bs->cur_ps.powerups[PW_BLUEFLAG] != 0;
+#ifdef MISSIONPACK
+ bs->inventory[INVENTORY_NEUTRALFLAG] = bs->cur_ps.powerups[PW_NEUTRALFLAG] != 0;
+ if (BotTeam(bs) == TEAM_RED) {
+ bs->inventory[INVENTORY_REDCUBE] = bs->cur_ps.generic1;
+ bs->inventory[INVENTORY_BLUECUBE] = 0;
+ }
+ else {
+ bs->inventory[INVENTORY_REDCUBE] = 0;
+ bs->inventory[INVENTORY_BLUECUBE] = bs->cur_ps.generic1;
+ }
+#endif
+ BotCheckItemPickup(bs, oldinventory);
+}
+
+/*
+==================
+BotUpdateBattleInventory
+==================
+*/
+void BotUpdateBattleInventory(bot_state_t *bs, int enemy) {
+ vec3_t dir;
+ aas_entityinfo_t entinfo;
+
+ BotEntityInfo(enemy, &entinfo);
+ VectorSubtract(entinfo.origin, bs->origin, dir);
+ bs->inventory[ENEMY_HEIGHT] = (int) dir[2];
+ dir[2] = 0;
+ bs->inventory[ENEMY_HORIZONTAL_DIST] = (int) VectorLength(dir);
+ //FIXME: add num visible enemies and num visible team mates to the inventory
+}
+
+#ifdef MISSIONPACK
+/*
+==================
+BotUseKamikaze
+==================
+*/
+#define KAMIKAZE_DIST 1024
+
+void BotUseKamikaze(bot_state_t *bs) {
+ int c, teammates, enemies;
+ aas_entityinfo_t entinfo;
+ vec3_t dir, target;
+ bot_goal_t *goal;
+ bsp_trace_t trace;
+
+ //if the bot has no kamikaze
+ if (bs->inventory[INVENTORY_KAMIKAZE] <= 0)
+ return;
+ if (bs->kamikaze_time > FloatTime())
+ return;
+ bs->kamikaze_time = FloatTime() + 0.2;
+ if (gametype == GT_CTF) {
+ //never use kamikaze if the team flag carrier is visible
+ if (BotCTFCarryingFlag(bs))
+ return;
+ c = BotTeamFlagCarrierVisible(bs);
+ if (c >= 0) {
+ BotEntityInfo(c, &entinfo);
+ VectorSubtract(entinfo.origin, bs->origin, dir);
+ if (VectorLengthSquared(dir) < Square(KAMIKAZE_DIST))
+ return;
+ }
+ c = BotEnemyFlagCarrierVisible(bs);
+ if (c >= 0) {
+ BotEntityInfo(c, &entinfo);
+ VectorSubtract(entinfo.origin, bs->origin, dir);
+ if (VectorLengthSquared(dir) < Square(KAMIKAZE_DIST)) {
+ trap_EA_Use(bs->client);
+ return;
+ }
+ }
+ }
+ else if (gametype == GT_1FCTF) {
+ //never use kamikaze if the team flag carrier is visible
+ if (Bot1FCTFCarryingFlag(bs))
+ return;
+ c = BotTeamFlagCarrierVisible(bs);
+ if (c >= 0) {
+ BotEntityInfo(c, &entinfo);
+ VectorSubtract(entinfo.origin, bs->origin, dir);
+ if (VectorLengthSquared(dir) < Square(KAMIKAZE_DIST))
+ return;
+ }
+ c = BotEnemyFlagCarrierVisible(bs);
+ if (c >= 0) {
+ BotEntityInfo(c, &entinfo);
+ VectorSubtract(entinfo.origin, bs->origin, dir);
+ if (VectorLengthSquared(dir) < Square(KAMIKAZE_DIST)) {
+ trap_EA_Use(bs->client);
+ return;
+ }
+ }
+ }
+ else if (gametype == GT_OBELISK) {
+ switch(BotTeam(bs)) {
+ case TEAM_RED: goal = &blueobelisk; break;
+ default: goal = &redobelisk; break;
+ }
+ //if the obelisk is visible
+ VectorCopy(goal->origin, target);
+ target[2] += 1;
+ VectorSubtract(bs->origin, target, dir);
+ if (VectorLengthSquared(dir) < Square(KAMIKAZE_DIST * 0.9)) {
+ BotAI_Trace(&trace, bs->eye, NULL, NULL, target, bs->client, CONTENTS_SOLID);
+ if (trace.fraction >= 1 || trace.ent == goal->entitynum) {
+ trap_EA_Use(bs->client);
+ return;
+ }
+ }
+ }
+ else if (gametype == GT_HARVESTER) {
+ //
+ if (BotHarvesterCarryingCubes(bs))
+ return;
+ //never use kamikaze if a team mate carrying cubes is visible
+ c = BotTeamCubeCarrierVisible(bs);
+ if (c >= 0) {
+ BotEntityInfo(c, &entinfo);
+ VectorSubtract(entinfo.origin, bs->origin, dir);
+ if (VectorLengthSquared(dir) < Square(KAMIKAZE_DIST))
+ return;
+ }
+ c = BotEnemyCubeCarrierVisible(bs);
+ if (c >= 0) {
+ BotEntityInfo(c, &entinfo);
+ VectorSubtract(entinfo.origin, bs->origin, dir);
+ if (VectorLengthSquared(dir) < Square(KAMIKAZE_DIST)) {
+ trap_EA_Use(bs->client);
+ return;
+ }
+ }
+ }
+ //
+ BotVisibleTeamMatesAndEnemies(bs, &teammates, &enemies, KAMIKAZE_DIST);
+ //
+ if (enemies > 2 && enemies > teammates+1) {
+ trap_EA_Use(bs->client);
+ return;
+ }
+}
+
+/*
+==================
+BotUseInvulnerability
+==================
+*/
+void BotUseInvulnerability(bot_state_t *bs) {
+ int c;
+ vec3_t dir, target;
+ bot_goal_t *goal;
+ bsp_trace_t trace;
+
+ //if the bot has no invulnerability
+ if (bs->inventory[INVENTORY_INVULNERABILITY] <= 0)
+ return;
+ if (bs->invulnerability_time > FloatTime())
+ return;
+ bs->invulnerability_time = FloatTime() + 0.2;
+ if (gametype == GT_CTF) {
+ //never use kamikaze if the team flag carrier is visible
+ if (BotCTFCarryingFlag(bs))
+ return;
+ c = BotEnemyFlagCarrierVisible(bs);
+ if (c >= 0)
+ return;
+ //if near enemy flag and the flag is visible
+ switch(BotTeam(bs)) {
+ case TEAM_RED: goal = &ctf_blueflag; break;
+ default: goal = &ctf_redflag; break;
+ }
+ //if the obelisk is visible
+ VectorCopy(goal->origin, target);
+ target[2] += 1;
+ VectorSubtract(bs->origin, target, dir);
+ if (VectorLengthSquared(dir) < Square(200)) {
+ BotAI_Trace(&trace, bs->eye, NULL, NULL, target, bs->client, CONTENTS_SOLID);
+ if (trace.fraction >= 1 || trace.ent == goal->entitynum) {
+ trap_EA_Use(bs->client);
+ return;
+ }
+ }
+ }
+ else if (gametype == GT_1FCTF) {
+ //never use kamikaze if the team flag carrier is visible
+ if (Bot1FCTFCarryingFlag(bs))
+ return;
+ c = BotEnemyFlagCarrierVisible(bs);
+ if (c >= 0)
+ return;
+ //if near enemy flag and the flag is visible
+ switch(BotTeam(bs)) {
+ case TEAM_RED: goal = &ctf_blueflag; break;
+ default: goal = &ctf_redflag; break;
+ }
+ //if the obelisk is visible
+ VectorCopy(goal->origin, target);
+ target[2] += 1;
+ VectorSubtract(bs->origin, target, dir);
+ if (VectorLengthSquared(dir) < Square(200)) {
+ BotAI_Trace(&trace, bs->eye, NULL, NULL, target, bs->client, CONTENTS_SOLID);
+ if (trace.fraction >= 1 || trace.ent == goal->entitynum) {
+ trap_EA_Use(bs->client);
+ return;
+ }
+ }
+ }
+ else if (gametype == GT_OBELISK) {
+ switch(BotTeam(bs)) {
+ case TEAM_RED: goal = &blueobelisk; break;
+ default: goal = &redobelisk; break;
+ }
+ //if the obelisk is visible
+ VectorCopy(goal->origin, target);
+ target[2] += 1;
+ VectorSubtract(bs->origin, target, dir);
+ if (VectorLengthSquared(dir) < Square(300)) {
+ BotAI_Trace(&trace, bs->eye, NULL, NULL, target, bs->client, CONTENTS_SOLID);
+ if (trace.fraction >= 1 || trace.ent == goal->entitynum) {
+ trap_EA_Use(bs->client);
+ return;
+ }
+ }
+ }
+ else if (gametype == GT_HARVESTER) {
+ //
+ if (BotHarvesterCarryingCubes(bs))
+ return;
+ c = BotEnemyCubeCarrierVisible(bs);
+ if (c >= 0)
+ return;
+ //if near enemy base and enemy base is visible
+ switch(BotTeam(bs)) {
+ case TEAM_RED: goal = &blueobelisk; break;
+ default: goal = &redobelisk; break;
+ }
+ //if the obelisk is visible
+ VectorCopy(goal->origin, target);
+ target[2] += 1;
+ VectorSubtract(bs->origin, target, dir);
+ if (VectorLengthSquared(dir) < Square(200)) {
+ BotAI_Trace(&trace, bs->eye, NULL, NULL, target, bs->client, CONTENTS_SOLID);
+ if (trace.fraction >= 1 || trace.ent == goal->entitynum) {
+ trap_EA_Use(bs->client);
+ return;
+ }
+ }
+ }
+}
+#endif
+
+/*
+==================
+BotBattleUseItems
+==================
+*/
+void BotBattleUseItems(bot_state_t *bs) {
+ if (bs->inventory[INVENTORY_HEALTH] < 40) {
+ if (bs->inventory[INVENTORY_TELEPORTER] > 0) {
+ if (!BotCTFCarryingFlag(bs)
+#ifdef MISSIONPACK
+ && !Bot1FCTFCarryingFlag(bs)
+ && !BotHarvesterCarryingCubes(bs)
+#endif
+ ) {
+ trap_EA_Use(bs->client);
+ }
+ }
+ }
+ if (bs->inventory[INVENTORY_HEALTH] < 60) {
+ if (bs->inventory[INVENTORY_MEDKIT] > 0) {
+ trap_EA_Use(bs->client);
+ }
+ }
+#ifdef MISSIONPACK
+ BotUseKamikaze(bs);
+ BotUseInvulnerability(bs);
+#endif
+}
+
+/*
+==================
+BotSetTeleportTime
+==================
+*/
+void BotSetTeleportTime(bot_state_t *bs) {
+ if ((bs->cur_ps.eFlags ^ bs->last_eFlags) & EF_TELEPORT_BIT) {
+ bs->teleport_time = FloatTime();
+ }
+ bs->last_eFlags = bs->cur_ps.eFlags;
+}
+
+/*
+==================
+BotIsDead
+==================
+*/
+qboolean BotIsDead(bot_state_t *bs) {
+ return (bs->cur_ps.pm_type == PM_DEAD);
+}
+
+/*
+==================
+BotIsObserver
+==================
+*/
+qboolean BotIsObserver(bot_state_t *bs) {
+ char buf[MAX_INFO_STRING];
+ if (bs->cur_ps.pm_type == PM_SPECTATOR) return qtrue;
+ trap_GetConfigstring(CS_PLAYERS+bs->client, buf, sizeof(buf));
+ if (atoi(Info_ValueForKey(buf, "t")) == TEAM_SPECTATOR) return qtrue;
+ return qfalse;
+}
+
+/*
+==================
+BotIntermission
+==================
+*/
+qboolean BotIntermission(bot_state_t *bs) {
+ //NOTE: we shouldn't be looking at the game code...
+ if (level.intermissiontime) return qtrue;
+ return (bs->cur_ps.pm_type == PM_FREEZE || bs->cur_ps.pm_type == PM_INTERMISSION);
+}
+
+/*
+==================
+BotInLavaOrSlime
+==================
+*/
+qboolean BotInLavaOrSlime(bot_state_t *bs) {
+ vec3_t feet;
+
+ VectorCopy(bs->origin, feet);
+ feet[2] -= 23;
+ return (trap_AAS_PointContents(feet) & (CONTENTS_LAVA|CONTENTS_SLIME));
+}
+
+/*
+==================
+BotCreateWayPoint
+==================
+*/
+bot_waypoint_t *BotCreateWayPoint(char *name, vec3_t origin, int areanum) {
+ bot_waypoint_t *wp;
+ vec3_t waypointmins = {-8, -8, -8}, waypointmaxs = {8, 8, 8};
+
+ wp = botai_freewaypoints;
+ if ( !wp ) {
+ BotAI_Print( PRT_WARNING, "BotCreateWayPoint: Out of waypoints\n" );
+ return NULL;
+ }
+ botai_freewaypoints = botai_freewaypoints->next;
+
+ Q_strncpyz( wp->name, name, sizeof(wp->name) );
+ VectorCopy(origin, wp->goal.origin);
+ VectorCopy(waypointmins, wp->goal.mins);
+ VectorCopy(waypointmaxs, wp->goal.maxs);
+ wp->goal.areanum = areanum;
+ wp->next = NULL;
+ wp->prev = NULL;
+ return wp;
+}
+
+/*
+==================
+BotFindWayPoint
+==================
+*/
+bot_waypoint_t *BotFindWayPoint(bot_waypoint_t *waypoints, char *name) {
+ bot_waypoint_t *wp;
+
+ for (wp = waypoints; wp; wp = wp->next) {
+ if (!Q_stricmp(wp->name, name)) return wp;
+ }
+ return NULL;
+}
+
+/*
+==================
+BotFreeWaypoints
+==================
+*/
+void BotFreeWaypoints(bot_waypoint_t *wp) {
+ bot_waypoint_t *nextwp;
+
+ for (; wp; wp = nextwp) {
+ nextwp = wp->next;
+ wp->next = botai_freewaypoints;
+ botai_freewaypoints = wp;
+ }
+}
+
+/*
+==================
+BotInitWaypoints
+==================
+*/
+void BotInitWaypoints(void) {
+ int i;
+
+ botai_freewaypoints = NULL;
+ for (i = 0; i < MAX_WAYPOINTS; i++) {
+ botai_waypoints[i].next = botai_freewaypoints;
+ botai_freewaypoints = &botai_waypoints[i];
+ }
+}
+
+/*
+==================
+TeamPlayIsOn
+==================
+*/
+int TeamPlayIsOn(void) {
+ return ( gametype >= GT_TEAM );
+}
+
+/*
+==================
+BotAggression
+==================
+*/
+float BotAggression(bot_state_t *bs) {
+ //if the bot has quad
+ if (bs->inventory[INVENTORY_QUAD]) {
+ //if the bot is not holding the gauntlet or the enemy is really nearby
+ if (bs->weaponnum != WP_GAUNTLET ||
+ bs->inventory[ENEMY_HORIZONTAL_DIST] < 80) {
+ return 70;
+ }
+ }
+ //if the enemy is located way higher than the bot
+ if (bs->inventory[ENEMY_HEIGHT] > 200) return 0;
+ //if the bot is very low on health
+ if (bs->inventory[INVENTORY_HEALTH] < 60) return 0;
+ //if the bot is low on health
+ if (bs->inventory[INVENTORY_HEALTH] < 80) {
+ //if the bot has insufficient armor
+ if (bs->inventory[INVENTORY_ARMOR] < 40) return 0;
+ }
+ //if the bot can use the bfg
+ if (bs->inventory[INVENTORY_BFG10K] > 0 &&
+ bs->inventory[INVENTORY_BFGAMMO] > 7) return 100;
+ //if the bot can use the railgun
+ if (bs->inventory[INVENTORY_RAILGUN] > 0 &&
+ bs->inventory[INVENTORY_SLUGS] > 5) return 95;
+ //if the bot can use the lightning gun
+ if (bs->inventory[INVENTORY_LIGHTNING] > 0 &&
+ bs->inventory[INVENTORY_LIGHTNINGAMMO] > 50) return 90;
+ //if the bot can use the rocketlauncher
+ if (bs->inventory[INVENTORY_ROCKETLAUNCHER] > 0 &&
+ bs->inventory[INVENTORY_ROCKETS] > 5) return 90;
+ //if the bot can use the plasmagun
+ if (bs->inventory[INVENTORY_PLASMAGUN] > 0 &&
+ bs->inventory[INVENTORY_CELLS] > 40) return 85;
+ //if the bot can use the grenade launcher
+ if (bs->inventory[INVENTORY_GRENADELAUNCHER] > 0 &&
+ bs->inventory[INVENTORY_GRENADES] > 10) return 80;
+ //if the bot can use the shotgun
+ if (bs->inventory[INVENTORY_SHOTGUN] > 0 &&
+ bs->inventory[INVENTORY_SHELLS] > 10) return 50;
+ //otherwise the bot is not feeling too good
+ return 0;
+}
+
+/*
+==================
+BotFeelingBad
+==================
+*/
+float BotFeelingBad(bot_state_t *bs) {
+ if (bs->weaponnum == WP_GAUNTLET) {
+ return 100;
+ }
+ if (bs->inventory[INVENTORY_HEALTH] < 40) {
+ return 100;
+ }
+ if (bs->weaponnum == WP_MACHINEGUN) {
+ return 90;
+ }
+ if (bs->inventory[INVENTORY_HEALTH] < 60) {
+ return 80;
+ }
+ return 0;
+}
+
+/*
+==================
+BotWantsToRetreat
+==================
+*/
+int BotWantsToRetreat(bot_state_t *bs) {
+ aas_entityinfo_t entinfo;
+
+ if (gametype == GT_CTF) {
+ //always retreat when carrying a CTF flag
+ if (BotCTFCarryingFlag(bs))
+ return qtrue;
+ }
+#ifdef MISSIONPACK
+ else if (gametype == GT_1FCTF) {
+ //if carrying the flag then always retreat
+ if (Bot1FCTFCarryingFlag(bs))
+ return qtrue;
+ }
+ else if (gametype == GT_OBELISK) {
+ //the bots should be dedicated to attacking the enemy obelisk
+ if (bs->ltgtype == LTG_ATTACKENEMYBASE) {
+ if (bs->enemy != redobelisk.entitynum ||
+ bs->enemy != blueobelisk.entitynum) {
+ return qtrue;
+ }
+ }
+ if (BotFeelingBad(bs) > 50) {
+ return qtrue;
+ }
+ return qfalse;
+ }
+ else if (gametype == GT_HARVESTER) {
+ //if carrying cubes then always retreat
+ if (BotHarvesterCarryingCubes(bs)) return qtrue;
+ }
+#endif
+ //
+ if (bs->enemy >= 0) {
+ //if the enemy is carrying a flag
+ BotEntityInfo(bs->enemy, &entinfo);
+ if (EntityCarriesFlag(&entinfo))
+ return qfalse;
+ }
+ //if the bot is getting the flag
+ if (bs->ltgtype == LTG_GETFLAG)
+ return qtrue;
+ //
+ if (BotAggression(bs) < 50)
+ return qtrue;
+ return qfalse;
+}
+
+/*
+==================
+BotWantsToChase
+==================
+*/
+int BotWantsToChase(bot_state_t *bs) {
+ aas_entityinfo_t entinfo;
+
+ if (gametype == GT_CTF) {
+ //never chase when carrying a CTF flag
+ if (BotCTFCarryingFlag(bs))
+ return qfalse;
+ //always chase if the enemy is carrying a flag
+ BotEntityInfo(bs->enemy, &entinfo);
+ if (EntityCarriesFlag(&entinfo))
+ return qtrue;
+ }
+#ifdef MISSIONPACK
+ else if (gametype == GT_1FCTF) {
+ //never chase if carrying the flag
+ if (Bot1FCTFCarryingFlag(bs))
+ return qfalse;
+ //always chase if the enemy is carrying a flag
+ BotEntityInfo(bs->enemy, &entinfo);
+ if (EntityCarriesFlag(&entinfo))
+ return qtrue;
+ }
+ else if (gametype == GT_OBELISK) {
+ //the bots should be dedicated to attacking the enemy obelisk
+ if (bs->ltgtype == LTG_ATTACKENEMYBASE) {
+ if (bs->enemy != redobelisk.entitynum ||
+ bs->enemy != blueobelisk.entitynum) {
+ return qfalse;
+ }
+ }
+ }
+ else if (gametype == GT_HARVESTER) {
+ //never chase if carrying cubes
+ if (BotHarvesterCarryingCubes(bs))
+ return qfalse;
+ }
+#endif
+ //if the bot is getting the flag
+ if (bs->ltgtype == LTG_GETFLAG)
+ return qfalse;
+ //
+ if (BotAggression(bs) > 50)
+ return qtrue;
+ return qfalse;
+}
+
+/*
+==================
+BotWantsToHelp
+==================
+*/
+int BotWantsToHelp(bot_state_t *bs) {
+ return qtrue;
+}
+
+/*
+==================
+BotCanAndWantsToRocketJump
+==================
+*/
+int BotCanAndWantsToRocketJump(bot_state_t *bs) {
+ float rocketjumper;
+
+ //if rocket jumping is disabled
+ if (!bot_rocketjump.integer) return qfalse;
+ //if no rocket launcher
+ if (bs->inventory[INVENTORY_ROCKETLAUNCHER] <= 0) return qfalse;
+ //if low on rockets
+ if (bs->inventory[INVENTORY_ROCKETS] < 3) return qfalse;
+ //never rocket jump with the Quad
+ if (bs->inventory[INVENTORY_QUAD]) return qfalse;
+ //if low on health
+ if (bs->inventory[INVENTORY_HEALTH] < 60) return qfalse;
+ //if not full health
+ if (bs->inventory[INVENTORY_HEALTH] < 90) {
+ //if the bot has insufficient armor
+ if (bs->inventory[INVENTORY_ARMOR] < 40) return qfalse;
+ }
+ rocketjumper = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_WEAPONJUMPING, 0, 1);
+ if (rocketjumper < 0.5) return qfalse;
+ return qtrue;
+}
+
+/*
+==================
+BotHasPersistantPowerupAndWeapon
+==================
+*/
+int BotHasPersistantPowerupAndWeapon(bot_state_t *bs) {
+#ifdef MISSIONPACK
+ // if the bot does not have a persistant powerup
+ if (!bs->inventory[INVENTORY_SCOUT] &&
+ !bs->inventory[INVENTORY_GUARD] &&
+ !bs->inventory[INVENTORY_DOUBLER] &&
+ !bs->inventory[INVENTORY_AMMOREGEN] ) {
+ return qfalse;
+ }
+#endif
+ //if the bot is very low on health
+ if (bs->inventory[INVENTORY_HEALTH] < 60) return qfalse;
+ //if the bot is low on health
+ if (bs->inventory[INVENTORY_HEALTH] < 80) {
+ //if the bot has insufficient armor
+ if (bs->inventory[INVENTORY_ARMOR] < 40) return qfalse;
+ }
+ //if the bot can use the bfg
+ if (bs->inventory[INVENTORY_BFG10K] > 0 &&
+ bs->inventory[INVENTORY_BFGAMMO] > 7) return qtrue;
+ //if the bot can use the railgun
+ if (bs->inventory[INVENTORY_RAILGUN] > 0 &&
+ bs->inventory[INVENTORY_SLUGS] > 5) return qtrue;
+ //if the bot can use the lightning gun
+ if (bs->inventory[INVENTORY_LIGHTNING] > 0 &&
+ bs->inventory[INVENTORY_LIGHTNINGAMMO] > 50) return qtrue;
+ //if the bot can use the rocketlauncher
+ if (bs->inventory[INVENTORY_ROCKETLAUNCHER] > 0 &&
+ bs->inventory[INVENTORY_ROCKETS] > 5) return qtrue;
+ //
+ if (bs->inventory[INVENTORY_NAILGUN] > 0 &&
+ bs->inventory[INVENTORY_NAILS] > 5) return qtrue;
+ //
+ if (bs->inventory[INVENTORY_PROXLAUNCHER] > 0 &&
+ bs->inventory[INVENTORY_MINES] > 5) return qtrue;
+ //
+ if (bs->inventory[INVENTORY_CHAINGUN] > 0 &&
+ bs->inventory[INVENTORY_BELT] > 40) return qtrue;
+ //if the bot can use the plasmagun
+ if (bs->inventory[INVENTORY_PLASMAGUN] > 0 &&
+ bs->inventory[INVENTORY_CELLS] > 20) return qtrue;
+ return qfalse;
+}
+
+/*
+==================
+BotGoCamp
+==================
+*/
+void BotGoCamp(bot_state_t *bs, bot_goal_t *goal) {
+ float camper;
+
+ bs->decisionmaker = bs->client;
+ //set message time to zero so bot will NOT show any message
+ bs->teammessage_time = 0;
+ //set the ltg type
+ bs->ltgtype = LTG_CAMP;
+ //set the team goal
+ memcpy(&bs->teamgoal, goal, sizeof(bot_goal_t));
+ //get the team goal time
+ camper = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_CAMPER, 0, 1);
+ if (camper > 0.99) bs->teamgoal_time = FloatTime() + 99999;
+ else bs->teamgoal_time = FloatTime() + 120 + 180 * camper + random() * 15;
+ //set the last time the bot started camping
+ bs->camp_time = FloatTime();
+ //the teammate that requested the camping
+ bs->teammate = 0;
+ //do NOT type arrive message
+ bs->arrive_time = 1;
+}
+
+/*
+==================
+BotWantsToCamp
+==================
+*/
+int BotWantsToCamp(bot_state_t *bs) {
+ float camper;
+ int cs, traveltime, besttraveltime;
+ bot_goal_t goal, bestgoal;
+
+ camper = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_CAMPER, 0, 1);
+ if (camper < 0.1) return qfalse;
+ //if the bot has a team goal
+ if (bs->ltgtype == LTG_TEAMHELP ||
+ bs->ltgtype == LTG_TEAMACCOMPANY ||
+ bs->ltgtype == LTG_DEFENDKEYAREA ||
+ bs->ltgtype == LTG_GETFLAG ||
+ bs->ltgtype == LTG_RUSHBASE ||
+ bs->ltgtype == LTG_CAMP ||
+ bs->ltgtype == LTG_CAMPORDER ||
+ bs->ltgtype == LTG_PATROL) {
+ return qfalse;
+ }
+ //if camped recently
+ if (bs->camp_time > FloatTime() - 60 + 300 * (1-camper)) return qfalse;
+ //
+ if (random() > camper) {
+ bs->camp_time = FloatTime();
+ return qfalse;
+ }
+ //if the bot isn't healthy anough
+ if (BotAggression(bs) < 50) return qfalse;
+ //the bot should have at least have the rocket launcher, the railgun or the bfg10k with some ammo
+ if ((bs->inventory[INVENTORY_ROCKETLAUNCHER] <= 0 || bs->inventory[INVENTORY_ROCKETS < 10]) &&
+ (bs->inventory[INVENTORY_RAILGUN] <= 0 || bs->inventory[INVENTORY_SLUGS] < 10) &&
+ (bs->inventory[INVENTORY_BFG10K] <= 0 || bs->inventory[INVENTORY_BFGAMMO] < 10)) {
+ return qfalse;
+ }
+ //find the closest camp spot
+ besttraveltime = 99999;
+ for (cs = trap_BotGetNextCampSpotGoal(0, &goal); cs; cs = trap_BotGetNextCampSpotGoal(cs, &goal)) {
+ traveltime = trap_AAS_AreaTravelTimeToGoalArea(bs->areanum, bs->origin, goal.areanum, TFL_DEFAULT);
+ if (traveltime && traveltime < besttraveltime) {
+ besttraveltime = traveltime;
+ memcpy(&bestgoal, &goal, sizeof(bot_goal_t));
+ }
+ }
+ if (besttraveltime > 150) return qfalse;
+ //ok found a camp spot, go camp there
+ BotGoCamp(bs, &bestgoal);
+ bs->ordered = qfalse;
+ //
+ return qtrue;
+}
+
+/*
+==================
+BotDontAvoid
+==================
+*/
+void BotDontAvoid(bot_state_t *bs, char *itemname) {
+ bot_goal_t goal;
+ int num;
+
+ num = trap_BotGetLevelItemGoal(-1, itemname, &goal);
+ while(num >= 0) {
+ trap_BotRemoveFromAvoidGoals(bs->gs, goal.number);
+ num = trap_BotGetLevelItemGoal(num, itemname, &goal);
+ }
+}
+
+/*
+==================
+BotGoForPowerups
+==================
+*/
+void BotGoForPowerups(bot_state_t *bs) {
+
+ //don't avoid any of the powerups anymore
+ BotDontAvoid(bs, "Quad Damage");
+ BotDontAvoid(bs, "Regeneration");
+ BotDontAvoid(bs, "Battle Suit");
+ BotDontAvoid(bs, "Speed");
+ BotDontAvoid(bs, "Invisibility");
+ //BotDontAvoid(bs, "Flight");
+ //reset the long term goal time so the bot will go for the powerup
+ //NOTE: the long term goal type doesn't change
+ bs->ltg_time = 0;
+}
+
+/*
+==================
+BotRoamGoal
+==================
+*/
+void BotRoamGoal(bot_state_t *bs, vec3_t goal) {
+ int pc, i;
+ float len, rnd;
+ vec3_t dir, bestorg, belowbestorg;
+ bsp_trace_t trace;
+
+ for (i = 0; i < 10; i++) {
+ //start at the bot origin
+ VectorCopy(bs->origin, bestorg);
+ rnd = random();
+ if (rnd > 0.25) {
+ //add a random value to the x-coordinate
+ if (random() < 0.5) bestorg[0] -= 800 * random() + 100;
+ else bestorg[0] += 800 * random() + 100;
+ }
+ if (rnd < 0.75) {
+ //add a random value to the y-coordinate
+ if (random() < 0.5) bestorg[1] -= 800 * random() + 100;
+ else bestorg[1] += 800 * random() + 100;
+ }
+ //add a random value to the z-coordinate (NOTE: 48 = maxjump?)
+ bestorg[2] += 2 * 48 * crandom();
+ //trace a line from the origin to the roam target
+ BotAI_Trace(&trace, bs->origin, NULL, NULL, bestorg, bs->entitynum, MASK_SOLID);
+ //direction and length towards the roam target
+ VectorSubtract(trace.endpos, bs->origin, dir);
+ len = VectorNormalize(dir);
+ //if the roam target is far away anough
+ if (len > 200) {
+ //the roam target is in the given direction before walls
+ VectorScale(dir, len * trace.fraction - 40, dir);
+ VectorAdd(bs->origin, dir, bestorg);
+ //get the coordinates of the floor below the roam target
+ belowbestorg[0] = bestorg[0];
+ belowbestorg[1] = bestorg[1];
+ belowbestorg[2] = bestorg[2] - 800;
+ BotAI_Trace(&trace, bestorg, NULL, NULL, belowbestorg, bs->entitynum, MASK_SOLID);
+ //
+ if (!trace.startsolid) {
+ trace.endpos[2]++;
+ pc = trap_PointContents(trace.endpos, bs->entitynum);
+ if (!(pc & (CONTENTS_LAVA | CONTENTS_SLIME))) {
+ VectorCopy(bestorg, goal);
+ return;
+ }
+ }
+ }
+ }
+ VectorCopy(bestorg, goal);
+}
+
+/*
+==================
+BotAttackMove
+==================
+*/
+bot_moveresult_t BotAttackMove(bot_state_t *bs, int tfl) {
+ int movetype, i, attackentity;
+ float attack_skill, jumper, croucher, dist, strafechange_time;
+ float attack_dist, attack_range;
+ vec3_t forward, backward, sideward, hordir, up = {0, 0, 1};
+ aas_entityinfo_t entinfo;
+ bot_moveresult_t moveresult;
+ bot_goal_t goal;
+
+ attackentity = bs->enemy;
+ //
+ if (bs->attackchase_time > FloatTime()) {
+ //create the chase goal
+ goal.entitynum = attackentity;
+ goal.areanum = bs->lastenemyareanum;
+ VectorCopy(bs->lastenemyorigin, goal.origin);
+ VectorSet(goal.mins, -8, -8, -8);
+ VectorSet(goal.maxs, 8, 8, 8);
+ //initialize the movement state
+ BotSetupForMovement(bs);
+ //move towards the goal
+ trap_BotMoveToGoal(&moveresult, bs->ms, &goal, tfl);
+ return moveresult;
+ }
+ //
+ memset(&moveresult, 0, sizeof(bot_moveresult_t));
+ //
+ attack_skill = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_ATTACK_SKILL, 0, 1);
+ jumper = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_JUMPER, 0, 1);
+ croucher = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_CROUCHER, 0, 1);
+ //if the bot is really stupid
+ if (attack_skill < 0.2) return moveresult;
+ //initialize the movement state
+ BotSetupForMovement(bs);
+ //get the enemy entity info
+ BotEntityInfo(attackentity, &entinfo);
+ //direction towards the enemy
+ VectorSubtract(entinfo.origin, bs->origin, forward);
+ //the distance towards the enemy
+ dist = VectorNormalize(forward);
+ VectorNegate(forward, backward);
+ //walk, crouch or jump
+ movetype = MOVE_WALK;
+ //
+ if (bs->attackcrouch_time < FloatTime() - 1) {
+ if (random() < jumper) {
+ movetype = MOVE_JUMP;
+ }
+ //wait at least one second before crouching again
+ else if (bs->attackcrouch_time < FloatTime() - 1 && random() < croucher) {
+ bs->attackcrouch_time = FloatTime() + croucher * 5;
+ }
+ }
+ if (bs->attackcrouch_time > FloatTime()) movetype = MOVE_CROUCH;
+ //if the bot should jump
+ if (movetype == MOVE_JUMP) {
+ //if jumped last frame
+ if (bs->attackjump_time > FloatTime()) {
+ movetype = MOVE_WALK;
+ }
+ else {
+ bs->attackjump_time = FloatTime() + 1;
+ }
+ }
+ if (bs->cur_ps.weapon == WP_GAUNTLET) {
+ attack_dist = 0;
+ attack_range = 0;
+ }
+ else {
+ attack_dist = IDEAL_ATTACKDIST;
+ attack_range = 40;
+ }
+ //if the bot is stupid
+ if (attack_skill <= 0.4) {
+ //just walk to or away from the enemy
+ if (dist > attack_dist + attack_range) {
+ if (trap_BotMoveInDirection(bs->ms, forward, 400, movetype)) return moveresult;
+ }
+ if (dist < attack_dist - attack_range) {
+ if (trap_BotMoveInDirection(bs->ms, backward, 400, movetype)) return moveresult;
+ }
+ return moveresult;
+ }
+ //increase the strafe time
+ bs->attackstrafe_time += bs->thinktime;
+ //get the strafe change time
+ strafechange_time = 0.4 + (1 - attack_skill) * 0.2;
+ if (attack_skill > 0.7) strafechange_time += crandom() * 0.2;
+ //if the strafe direction should be changed
+ if (bs->attackstrafe_time > strafechange_time) {
+ //some magic number :)
+ if (random() > 0.935) {
+ //flip the strafe direction
+ bs->flags ^= BFL_STRAFERIGHT;
+ bs->attackstrafe_time = 0;
+ }
+ }
+ //
+ for (i = 0; i < 2; i++) {
+ hordir[0] = forward[0];
+ hordir[1] = forward[1];
+ hordir[2] = 0;
+ VectorNormalize(hordir);
+ //get the sideward vector
+ CrossProduct(hordir, up, sideward);
+ //reverse the vector depending on the strafe direction
+ if (bs->flags & BFL_STRAFERIGHT) VectorNegate(sideward, sideward);
+ //randomly go back a little
+ if (random() > 0.9) {
+ VectorAdd(sideward, backward, sideward);
+ }
+ else {
+ //walk forward or backward to get at the ideal attack distance
+ if (dist > attack_dist + attack_range) {
+ VectorAdd(sideward, forward, sideward);
+ }
+ else if (dist < attack_dist - attack_range) {
+ VectorAdd(sideward, backward, sideward);
+ }
+ }
+ //perform the movement
+ if (trap_BotMoveInDirection(bs->ms, sideward, 400, movetype))
+ return moveresult;
+ //movement failed, flip the strafe direction
+ bs->flags ^= BFL_STRAFERIGHT;
+ bs->attackstrafe_time = 0;
+ }
+ //bot couldn't do any usefull movement
+// bs->attackchase_time = AAS_Time() + 6;
+ return moveresult;
+}
+
+/*
+==================
+BotSameTeam
+==================
+*/
+int BotSameTeam(bot_state_t *bs, int entnum) {
+ char info1[1024], info2[1024];
+
+ if (bs->client < 0 || bs->client >= MAX_CLIENTS) {
+ //BotAI_Print(PRT_ERROR, "BotSameTeam: client out of range\n");
+ return qfalse;
+ }
+ if (entnum < 0 || entnum >= MAX_CLIENTS) {
+ //BotAI_Print(PRT_ERROR, "BotSameTeam: client out of range\n");
+ return qfalse;
+ }
+ if ( gametype >= GT_TEAM ) {
+ trap_GetConfigstring(CS_PLAYERS+bs->client, info1, sizeof(info1));
+ trap_GetConfigstring(CS_PLAYERS+entnum, info2, sizeof(info2));
+ //
+ if (atoi(Info_ValueForKey(info1, "t")) == atoi(Info_ValueForKey(info2, "t"))) return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+==================
+InFieldOfVision
+==================
+*/
+qboolean InFieldOfVision(vec3_t viewangles, float fov, vec3_t angles)
+{
+ int i;
+ float diff, angle;
+
+ for (i = 0; i < 2; i++) {
+ angle = AngleMod(viewangles[i]);
+ angles[i] = AngleMod(angles[i]);
+ diff = angles[i] - angle;
+ if (angles[i] > angle) {
+ if (diff > 180.0) diff -= 360.0;
+ }
+ else {
+ if (diff < -180.0) diff += 360.0;
+ }
+ if (diff > 0) {
+ if (diff > fov * 0.5) return qfalse;
+ }
+ else {
+ if (diff < -fov * 0.5) return qfalse;
+ }
+ }
+ return qtrue;
+}
+
+/*
+==================
+BotEntityVisible
+
+returns visibility in the range [0, 1] taking fog and water surfaces into account
+==================
+*/
+float BotEntityVisible(int viewer, vec3_t eye, vec3_t viewangles, float fov, int ent) {
+ int i, contents_mask, passent, hitent, infog, inwater, otherinfog, pc;
+ float squaredfogdist, waterfactor, vis, bestvis;
+ bsp_trace_t trace;
+ aas_entityinfo_t entinfo;
+ vec3_t dir, entangles, start, end, middle;
+
+ //calculate middle of bounding box
+ BotEntityInfo(ent, &entinfo);
+ VectorAdd(entinfo.mins, entinfo.maxs, middle);
+ VectorScale(middle, 0.5, middle);
+ VectorAdd(entinfo.origin, middle, middle);
+ //check if entity is within field of vision
+ VectorSubtract(middle, eye, dir);
+ vectoangles(dir, entangles);
+ if (!InFieldOfVision(viewangles, fov, entangles)) return 0;
+ //
+ pc = trap_AAS_PointContents(eye);
+ infog = (pc & CONTENTS_FOG);
+ inwater = (pc & (CONTENTS_LAVA|CONTENTS_SLIME|CONTENTS_WATER));
+ //
+ bestvis = 0;
+ for (i = 0; i < 3; i++) {
+ //if the point is not in potential visible sight
+ //if (!AAS_inPVS(eye, middle)) continue;
+ //
+ contents_mask = CONTENTS_SOLID|CONTENTS_PLAYERCLIP;
+ passent = viewer;
+ hitent = ent;
+ VectorCopy(eye, start);
+ VectorCopy(middle, end);
+ //if the entity is in water, lava or slime
+ if (trap_AAS_PointContents(middle) & (CONTENTS_LAVA|CONTENTS_SLIME|CONTENTS_WATER)) {
+ contents_mask |= (CONTENTS_LAVA|CONTENTS_SLIME|CONTENTS_WATER);
+ }
+ //if eye is in water, lava or slime
+ if (inwater) {
+ if (!(contents_mask & (CONTENTS_LAVA|CONTENTS_SLIME|CONTENTS_WATER))) {
+ passent = ent;
+ hitent = viewer;
+ VectorCopy(middle, start);
+ VectorCopy(eye, end);
+ }
+ contents_mask ^= (CONTENTS_LAVA|CONTENTS_SLIME|CONTENTS_WATER);
+ }
+ //trace from start to end
+ BotAI_Trace(&trace, start, NULL, NULL, end, passent, contents_mask);
+ //if water was hit
+ waterfactor = 1.0;
+ if (trace.contents & (CONTENTS_LAVA|CONTENTS_SLIME|CONTENTS_WATER)) {
+ //if the water surface is translucent
+ if (1) {
+ //trace through the water
+ contents_mask &= ~(CONTENTS_LAVA|CONTENTS_SLIME|CONTENTS_WATER);
+ BotAI_Trace(&trace, trace.endpos, NULL, NULL, end, passent, contents_mask);
+ waterfactor = 0.5;
+ }
+ }
+ //if a full trace or the hitent was hit
+ if (trace.fraction >= 1 || trace.ent == hitent) {
+ //check for fog, assuming there's only one fog brush where
+ //either the viewer or the entity is in or both are in
+ otherinfog = (trap_AAS_PointContents(middle) & CONTENTS_FOG);
+ if (infog && otherinfog) {
+ VectorSubtract(trace.endpos, eye, dir);
+ squaredfogdist = VectorLengthSquared(dir);
+ }
+ else if (infog) {
+ VectorCopy(trace.endpos, start);
+ BotAI_Trace(&trace, start, NULL, NULL, eye, viewer, CONTENTS_FOG);
+ VectorSubtract(eye, trace.endpos, dir);
+ squaredfogdist = VectorLengthSquared(dir);
+ }
+ else if (otherinfog) {
+ VectorCopy(trace.endpos, end);
+ BotAI_Trace(&trace, eye, NULL, NULL, end, viewer, CONTENTS_FOG);
+ VectorSubtract(end, trace.endpos, dir);
+ squaredfogdist = VectorLengthSquared(dir);
+ }
+ else {
+ //if the entity and the viewer are not in fog assume there's no fog in between
+ squaredfogdist = 0;
+ }
+ //decrease visibility with the view distance through fog
+ vis = 1 / ((squaredfogdist * 0.001) < 1 ? 1 : (squaredfogdist * 0.001));
+ //if entering water visibility is reduced
+ vis *= waterfactor;
+ //
+ if (vis > bestvis) bestvis = vis;
+ //if pretty much no fog
+ if (bestvis >= 0.95) return bestvis;
+ }
+ //check bottom and top of bounding box as well
+ if (i == 0) middle[2] += entinfo.mins[2];
+ else if (i == 1) middle[2] += entinfo.maxs[2] - entinfo.mins[2];
+ }
+ return bestvis;
+}
+
+/*
+==================
+BotFindEnemy
+==================
+*/
+int BotFindEnemy(bot_state_t *bs, int curenemy) {
+ int i, healthdecrease;
+ float f, alertness, easyfragger, vis;
+ float squaredist, cursquaredist;
+ aas_entityinfo_t entinfo, curenemyinfo;
+ vec3_t dir, angles;
+
+ alertness = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_ALERTNESS, 0, 1);
+ easyfragger = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_EASY_FRAGGER, 0, 1);
+ //check if the health decreased
+ healthdecrease = bs->lasthealth > bs->inventory[INVENTORY_HEALTH];
+ //remember the current health value
+ bs->lasthealth = bs->inventory[INVENTORY_HEALTH];
+ //
+ if (curenemy >= 0) {
+ BotEntityInfo(curenemy, &curenemyinfo);
+ if (EntityCarriesFlag(&curenemyinfo)) return qfalse;
+ VectorSubtract(curenemyinfo.origin, bs->origin, dir);
+ cursquaredist = VectorLengthSquared(dir);
+ }
+ else {
+ cursquaredist = 0;
+ }
+#ifdef MISSIONPACK
+ if (gametype == GT_OBELISK) {
+ vec3_t target;
+ bot_goal_t *goal;
+ bsp_trace_t trace;
+
+ if (BotTeam(bs) == TEAM_RED)
+ goal = &blueobelisk;
+ else
+ goal = &redobelisk;
+ //if the obelisk is visible
+ VectorCopy(goal->origin, target);
+ target[2] += 1;
+ BotAI_Trace(&trace, bs->eye, NULL, NULL, target, bs->client, CONTENTS_SOLID);
+ if (trace.fraction >= 1 || trace.ent == goal->entitynum) {
+ if (goal->entitynum == bs->enemy) {
+ return qfalse;
+ }
+ bs->enemy = goal->entitynum;
+ bs->enemysight_time = FloatTime();
+ bs->enemysuicide = qfalse;
+ bs->enemydeath_time = 0;
+ bs->enemyvisible_time = FloatTime();
+ return qtrue;
+ }
+ }
+#endif
+ //
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+
+ if (i == bs->client) continue;
+ //if it's the current enemy
+ if (i == curenemy) continue;
+ //
+ BotEntityInfo(i, &entinfo);
+ //
+ if (!entinfo.valid) continue;
+ //if the enemy isn't dead and the enemy isn't the bot self
+ if (EntityIsDead(&entinfo) || entinfo.number == bs->entitynum) continue;
+ //if the enemy is invisible and not shooting
+ if (EntityIsInvisible(&entinfo) && !EntityIsShooting(&entinfo)) {
+ continue;
+ }
+ //if not an easy fragger don't shoot at chatting players
+ if (easyfragger < 0.5 && EntityIsChatting(&entinfo)) continue;
+ //
+ if (lastteleport_time > FloatTime() - 3) {
+ VectorSubtract(entinfo.origin, lastteleport_origin, dir);
+ if (VectorLengthSquared(dir) < Square(70)) continue;
+ }
+ //calculate the distance towards the enemy
+ VectorSubtract(entinfo.origin, bs->origin, dir);
+ squaredist = VectorLengthSquared(dir);
+ //if this entity is not carrying a flag
+ if (!EntityCarriesFlag(&entinfo))
+ {
+ //if this enemy is further away than the current one
+ if (curenemy >= 0 && squaredist > cursquaredist) continue;
+ } //end if
+ //if the bot has no
+ if (squaredist > Square(900.0 + alertness * 4000.0)) continue;
+ //if on the same team
+ if (BotSameTeam(bs, i)) continue;
+ //if the bot's health decreased or the enemy is shooting
+ if (curenemy < 0 && (healthdecrease || EntityIsShooting(&entinfo)))
+ f = 360;
+ else
+ f = 90 + 90 - (90 - (squaredist > Square(810) ? Square(810) : squaredist) / (810 * 9));
+ //check if the enemy is visible
+ vis = BotEntityVisible(bs->entitynum, bs->eye, bs->viewangles, f, i);
+ if (vis <= 0) continue;
+ //if the enemy is quite far away, not shooting and the bot is not damaged
+ if (curenemy < 0 && squaredist > Square(100) && !healthdecrease && !EntityIsShooting(&entinfo))
+ {
+ //check if we can avoid this enemy
+ VectorSubtract(bs->origin, entinfo.origin, dir);
+ vectoangles(dir, angles);
+ //if the bot isn't in the fov of the enemy
+ if (!InFieldOfVision(entinfo.angles, 90, angles)) {
+ //update some stuff for this enemy
+ BotUpdateBattleInventory(bs, i);
+ //if the bot doesn't really want to fight
+ if (BotWantsToRetreat(bs)) continue;
+ }
+ }
+ //found an enemy
+ bs->enemy = entinfo.number;
+ if (curenemy >= 0) bs->enemysight_time = FloatTime() - 2;
+ else bs->enemysight_time = FloatTime();
+ bs->enemysuicide = qfalse;
+ bs->enemydeath_time = 0;
+ bs->enemyvisible_time = FloatTime();
+ return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+==================
+BotTeamFlagCarrierVisible
+==================
+*/
+int BotTeamFlagCarrierVisible(bot_state_t *bs) {
+ int i;
+ float vis;
+ aas_entityinfo_t entinfo;
+
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ if (i == bs->client)
+ continue;
+ //
+ BotEntityInfo(i, &entinfo);
+ //if this player is active
+ if (!entinfo.valid)
+ continue;
+ //if this player is carrying a flag
+ if (!EntityCarriesFlag(&entinfo))
+ continue;
+ //if the flag carrier is not on the same team
+ if (!BotSameTeam(bs, i))
+ continue;
+ //if the flag carrier is not visible
+ vis = BotEntityVisible(bs->entitynum, bs->eye, bs->viewangles, 360, i);
+ if (vis <= 0)
+ continue;
+ //
+ return i;
+ }
+ return -1;
+}
+
+/*
+==================
+BotTeamFlagCarrier
+==================
+*/
+int BotTeamFlagCarrier(bot_state_t *bs) {
+ int i;
+ aas_entityinfo_t entinfo;
+
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ if (i == bs->client)
+ continue;
+ //
+ BotEntityInfo(i, &entinfo);
+ //if this player is active
+ if (!entinfo.valid)
+ continue;
+ //if this player is carrying a flag
+ if (!EntityCarriesFlag(&entinfo))
+ continue;
+ //if the flag carrier is not on the same team
+ if (!BotSameTeam(bs, i))
+ continue;
+ //
+ return i;
+ }
+ return -1;
+}
+
+/*
+==================
+BotEnemyFlagCarrierVisible
+==================
+*/
+int BotEnemyFlagCarrierVisible(bot_state_t *bs) {
+ int i;
+ float vis;
+ aas_entityinfo_t entinfo;
+
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ if (i == bs->client)
+ continue;
+ //
+ BotEntityInfo(i, &entinfo);
+ //if this player is active
+ if (!entinfo.valid)
+ continue;
+ //if this player is carrying a flag
+ if (!EntityCarriesFlag(&entinfo))
+ continue;
+ //if the flag carrier is on the same team
+ if (BotSameTeam(bs, i))
+ continue;
+ //if the flag carrier is not visible
+ vis = BotEntityVisible(bs->entitynum, bs->eye, bs->viewangles, 360, i);
+ if (vis <= 0)
+ continue;
+ //
+ return i;
+ }
+ return -1;
+}
+
+/*
+==================
+BotVisibleTeamMatesAndEnemies
+==================
+*/
+void BotVisibleTeamMatesAndEnemies(bot_state_t *bs, int *teammates, int *enemies, float range) {
+ int i;
+ float vis;
+ aas_entityinfo_t entinfo;
+ vec3_t dir;
+
+ if (teammates)
+ *teammates = 0;
+ if (enemies)
+ *enemies = 0;
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ if (i == bs->client)
+ continue;
+ //
+ BotEntityInfo(i, &entinfo);
+ //if this player is active
+ if (!entinfo.valid)
+ continue;
+ //if this player is carrying a flag
+ if (!EntityCarriesFlag(&entinfo))
+ continue;
+ //if not within range
+ VectorSubtract(entinfo.origin, bs->origin, dir);
+ if (VectorLengthSquared(dir) > Square(range))
+ continue;
+ //if the flag carrier is not visible
+ vis = BotEntityVisible(bs->entitynum, bs->eye, bs->viewangles, 360, i);
+ if (vis <= 0)
+ continue;
+ //if the flag carrier is on the same team
+ if (BotSameTeam(bs, i)) {
+ if (teammates)
+ (*teammates)++;
+ }
+ else {
+ if (enemies)
+ (*enemies)++;
+ }
+ }
+}
+
+#ifdef MISSIONPACK
+/*
+==================
+BotTeamCubeCarrierVisible
+==================
+*/
+int BotTeamCubeCarrierVisible(bot_state_t *bs) {
+ int i;
+ float vis;
+ aas_entityinfo_t entinfo;
+
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ if (i == bs->client) continue;
+ //
+ BotEntityInfo(i, &entinfo);
+ //if this player is active
+ if (!entinfo.valid) continue;
+ //if this player is carrying a flag
+ if (!EntityCarriesCubes(&entinfo)) continue;
+ //if the flag carrier is not on the same team
+ if (!BotSameTeam(bs, i)) continue;
+ //if the flag carrier is not visible
+ vis = BotEntityVisible(bs->entitynum, bs->eye, bs->viewangles, 360, i);
+ if (vis <= 0) continue;
+ //
+ return i;
+ }
+ return -1;
+}
+
+/*
+==================
+BotEnemyCubeCarrierVisible
+==================
+*/
+int BotEnemyCubeCarrierVisible(bot_state_t *bs) {
+ int i;
+ float vis;
+ aas_entityinfo_t entinfo;
+
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ if (i == bs->client)
+ continue;
+ //
+ BotEntityInfo(i, &entinfo);
+ //if this player is active
+ if (!entinfo.valid)
+ continue;
+ //if this player is carrying a flag
+ if (!EntityCarriesCubes(&entinfo)) continue;
+ //if the flag carrier is on the same team
+ if (BotSameTeam(bs, i))
+ continue;
+ //if the flag carrier is not visible
+ vis = BotEntityVisible(bs->entitynum, bs->eye, bs->viewangles, 360, i);
+ if (vis <= 0)
+ continue;
+ //
+ return i;
+ }
+ return -1;
+}
+#endif
+
+/*
+==================
+BotAimAtEnemy
+==================
+*/
+void BotAimAtEnemy(bot_state_t *bs) {
+ int i, enemyvisible;
+ float dist, f, aim_skill, aim_accuracy, speed, reactiontime;
+ vec3_t dir, bestorigin, end, start, groundtarget, cmdmove, enemyvelocity;
+ vec3_t mins = {-4,-4,-4}, maxs = {4, 4, 4};
+ weaponinfo_t wi;
+ aas_entityinfo_t entinfo;
+ bot_goal_t goal;
+ bsp_trace_t trace;
+ vec3_t target;
+
+ //if the bot has no enemy
+ if (bs->enemy < 0) {
+ return;
+ }
+ //get the enemy entity information
+ BotEntityInfo(bs->enemy, &entinfo);
+ //if this is not a player (should be an obelisk)
+ if (bs->enemy >= MAX_CLIENTS) {
+ //if the obelisk is visible
+ VectorCopy(entinfo.origin, target);
+#ifdef MISSIONPACK
+ // if attacking an obelisk
+ if ( bs->enemy == redobelisk.entitynum ||
+ bs->enemy == blueobelisk.entitynum ) {
+ target[2] += 32;
+ }
+#endif
+ //aim at the obelisk
+ VectorSubtract(target, bs->eye, dir);
+ vectoangles(dir, bs->ideal_viewangles);
+ //set the aim target before trying to attack
+ VectorCopy(target, bs->aimtarget);
+ return;
+ }
+ //
+ //BotAI_Print(PRT_MESSAGE, "client %d: aiming at client %d\n", bs->entitynum, bs->enemy);
+ //
+ aim_skill = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_AIM_SKILL, 0, 1);
+ aim_accuracy = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_AIM_ACCURACY, 0, 1);
+ //
+ if (aim_skill > 0.95) {
+ //don't aim too early
+ reactiontime = 0.5 * trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_REACTIONTIME, 0, 1);
+ if (bs->enemysight_time > FloatTime() - reactiontime) return;
+ if (bs->teleport_time > FloatTime() - reactiontime) return;
+ }
+
+ //get the weapon information
+ trap_BotGetWeaponInfo(bs->ws, bs->weaponnum, &wi);
+ //get the weapon specific aim accuracy and or aim skill
+ if (wi.number == WP_MACHINEGUN) {
+ aim_accuracy = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_AIM_ACCURACY_MACHINEGUN, 0, 1);
+ }
+ else if (wi.number == WP_SHOTGUN) {
+ aim_accuracy = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_AIM_ACCURACY_SHOTGUN, 0, 1);
+ }
+ else if (wi.number == WP_GRENADE_LAUNCHER) {
+ aim_accuracy = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_AIM_ACCURACY_GRENADELAUNCHER, 0, 1);
+ aim_skill = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_AIM_SKILL_GRENADELAUNCHER, 0, 1);
+ }
+ else if (wi.number == WP_ROCKET_LAUNCHER) {
+ aim_accuracy = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_AIM_ACCURACY_ROCKETLAUNCHER, 0, 1);
+ aim_skill = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_AIM_SKILL_ROCKETLAUNCHER, 0, 1);
+ }
+ else if (wi.number == WP_LIGHTNING) {
+ aim_accuracy = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_AIM_ACCURACY_LIGHTNING, 0, 1);
+ }
+ else if (wi.number == WP_RAILGUN) {
+ aim_accuracy = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_AIM_ACCURACY_RAILGUN, 0, 1);
+ }
+ else if (wi.number == WP_PLASMAGUN) {
+ aim_accuracy = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_AIM_ACCURACY_PLASMAGUN, 0, 1);
+ aim_skill = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_AIM_SKILL_PLASMAGUN, 0, 1);
+ }
+ else if (wi.number == WP_BFG) {
+ aim_accuracy = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_AIM_ACCURACY_BFG10K, 0, 1);
+ aim_skill = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_AIM_SKILL_BFG10K, 0, 1);
+ }
+ //
+ if (aim_accuracy <= 0) aim_accuracy = 0.0001f;
+ //get the enemy entity information
+ BotEntityInfo(bs->enemy, &entinfo);
+ //if the enemy is invisible then shoot crappy most of the time
+ if (EntityIsInvisible(&entinfo)) {
+ if (random() > 0.1) aim_accuracy *= 0.4f;
+ }
+ //
+ VectorSubtract(entinfo.origin, entinfo.lastvisorigin, enemyvelocity);
+ VectorScale(enemyvelocity, 1 / entinfo.update_time, enemyvelocity);
+ //enemy origin and velocity is remembered every 0.5 seconds
+ if (bs->enemyposition_time < FloatTime()) {
+ //
+ bs->enemyposition_time = FloatTime() + 0.5;
+ VectorCopy(enemyvelocity, bs->enemyvelocity);
+ VectorCopy(entinfo.origin, bs->enemyorigin);
+ }
+ //if not extremely skilled
+ if (aim_skill < 0.9) {
+ VectorSubtract(entinfo.origin, bs->enemyorigin, dir);
+ //if the enemy moved a bit
+ if (VectorLengthSquared(dir) > Square(48)) {
+ //if the enemy changed direction
+ if (DotProduct(bs->enemyvelocity, enemyvelocity) < 0) {
+ //aim accuracy should be worse now
+ aim_accuracy *= 0.7f;
+ }
+ }
+ }
+ //check visibility of enemy
+ enemyvisible = BotEntityVisible(bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy);
+ //if the enemy is visible
+ if (enemyvisible) {
+ //
+ VectorCopy(entinfo.origin, bestorigin);
+ bestorigin[2] += 8;
+ //get the start point shooting from
+ //NOTE: the x and y projectile start offsets are ignored
+ VectorCopy(bs->origin, start);
+ start[2] += bs->cur_ps.viewheight;
+ start[2] += wi.offset[2];
+ //
+ BotAI_Trace(&trace, start, mins, maxs, bestorigin, bs->entitynum, MASK_SHOT);
+ //if the enemy is NOT hit
+ if (trace.fraction <= 1 && trace.ent != entinfo.number) {
+ bestorigin[2] += 16;
+ }
+ //if it is not an instant hit weapon the bot might want to predict the enemy
+ if (wi.speed) {
+ //
+ VectorSubtract(bestorigin, bs->origin, dir);
+ dist = VectorLength(dir);
+ VectorSubtract(entinfo.origin, bs->enemyorigin, dir);
+ //if the enemy is NOT pretty far away and strafing just small steps left and right
+ if (!(dist > 100 && VectorLengthSquared(dir) < Square(32))) {
+ //if skilled anough do exact prediction
+ if (aim_skill > 0.8 &&
+ //if the weapon is ready to fire
+ bs->cur_ps.weaponstate == WEAPON_READY) {
+ aas_clientmove_t move;
+ vec3_t origin;
+
+ VectorSubtract(entinfo.origin, bs->origin, dir);
+ //distance towards the enemy
+ dist = VectorLength(dir);
+ //direction the enemy is moving in
+ VectorSubtract(entinfo.origin, entinfo.lastvisorigin, dir);
+ //
+ VectorScale(dir, 1 / entinfo.update_time, dir);
+ //
+ VectorCopy(entinfo.origin, origin);
+ origin[2] += 1;
+ //
+ VectorClear(cmdmove);
+ //AAS_ClearShownDebugLines();
+ trap_AAS_PredictClientMovement(&move, bs->enemy, origin,
+ PRESENCE_CROUCH, qfalse,
+ dir, cmdmove, 0,
+ dist * 10 / wi.speed, 0.1f, 0, 0, qfalse);
+ VectorCopy(move.endpos, bestorigin);
+ //BotAI_Print(PRT_MESSAGE, "%1.1f predicted speed = %f, frames = %f\n", FloatTime(), VectorLength(dir), dist * 10 / wi.speed);
+ }
+ //if not that skilled do linear prediction
+ else if (aim_skill > 0.4) {
+ VectorSubtract(entinfo.origin, bs->origin, dir);
+ //distance towards the enemy
+ dist = VectorLength(dir);
+ //direction the enemy is moving in
+ VectorSubtract(entinfo.origin, entinfo.lastvisorigin, dir);
+ dir[2] = 0;
+ //
+ speed = VectorNormalize(dir) / entinfo.update_time;
+ //botimport.Print(PRT_MESSAGE, "speed = %f, wi->speed = %f\n", speed, wi->speed);
+ //best spot to aim at
+ VectorMA(entinfo.origin, (dist / wi.speed) * speed, dir, bestorigin);
+ }
+ }
+ }
+ //if the projectile does radial damage
+ if (aim_skill > 0.6 && wi.proj.damagetype & DAMAGETYPE_RADIAL) {
+ //if the enemy isn't standing significantly higher than the bot
+ if (entinfo.origin[2] < bs->origin[2] + 16) {
+ //try to aim at the ground in front of the enemy
+ VectorCopy(entinfo.origin, end);
+ end[2] -= 64;
+ BotAI_Trace(&trace, entinfo.origin, NULL, NULL, end, entinfo.number, MASK_SHOT);
+ //
+ VectorCopy(bestorigin, groundtarget);
+ if (trace.startsolid) groundtarget[2] = entinfo.origin[2] - 16;
+ else groundtarget[2] = trace.endpos[2] - 8;
+ //trace a line from projectile start to ground target
+ BotAI_Trace(&trace, start, NULL, NULL, groundtarget, bs->entitynum, MASK_SHOT);
+ //if hitpoint is not vertically too far from the ground target
+ if (fabs(trace.endpos[2] - groundtarget[2]) < 50) {
+ VectorSubtract(trace.endpos, groundtarget, dir);
+ //if the hitpoint is near anough the ground target
+ if (VectorLengthSquared(dir) < Square(60)) {
+ VectorSubtract(trace.endpos, start, dir);
+ //if the hitpoint is far anough from the bot
+ if (VectorLengthSquared(dir) > Square(100)) {
+ //check if the bot is visible from the ground target
+ trace.endpos[2] += 1;
+ BotAI_Trace(&trace, trace.endpos, NULL, NULL, entinfo.origin, entinfo.number, MASK_SHOT);
+ if (trace.fraction >= 1) {
+ //botimport.Print(PRT_MESSAGE, "%1.1f aiming at ground\n", AAS_Time());
+ VectorCopy(groundtarget, bestorigin);
+ }
+ }
+ }
+ }
+ }
+ }
+ bestorigin[0] += 20 * crandom() * (1 - aim_accuracy);
+ bestorigin[1] += 20 * crandom() * (1 - aim_accuracy);
+ bestorigin[2] += 10 * crandom() * (1 - aim_accuracy);
+ }
+ else {
+ //
+ VectorCopy(bs->lastenemyorigin, bestorigin);
+ bestorigin[2] += 8;
+ //if the bot is skilled anough
+ if (aim_skill > 0.5) {
+ //do prediction shots around corners
+ if (wi.number == WP_BFG ||
+ wi.number == WP_ROCKET_LAUNCHER ||
+ wi.number == WP_GRENADE_LAUNCHER) {
+ //create the chase goal
+ goal.entitynum = bs->client;
+ goal.areanum = bs->areanum;
+ VectorCopy(bs->eye, goal.origin);
+ VectorSet(goal.mins, -8, -8, -8);
+ VectorSet(goal.maxs, 8, 8, 8);
+ //
+ if (trap_BotPredictVisiblePosition(bs->lastenemyorigin, bs->lastenemyareanum, &goal, TFL_DEFAULT, target)) {
+ VectorSubtract(target, bs->eye, dir);
+ if (VectorLengthSquared(dir) > Square(80)) {
+ VectorCopy(target, bestorigin);
+ bestorigin[2] -= 20;
+ }
+ }
+ aim_accuracy = 1;
+ }
+ }
+ }
+ //
+ if (enemyvisible) {
+ BotAI_Trace(&trace, bs->eye, NULL, NULL, bestorigin, bs->entitynum, MASK_SHOT);
+ VectorCopy(trace.endpos, bs->aimtarget);
+ }
+ else {
+ VectorCopy(bestorigin, bs->aimtarget);
+ }
+ //get aim direction
+ VectorSubtract(bestorigin, bs->eye, dir);
+ //
+ if (wi.number == WP_MACHINEGUN ||
+ wi.number == WP_SHOTGUN ||
+ wi.number == WP_LIGHTNING ||
+ wi.number == WP_RAILGUN) {
+ //distance towards the enemy
+ dist = VectorLength(dir);
+ if (dist > 150) dist = 150;
+ f = 0.6 + dist / 150 * 0.4;
+ aim_accuracy *= f;
+ }
+ //add some random stuff to the aim direction depending on the aim accuracy
+ if (aim_accuracy < 0.8) {
+ VectorNormalize(dir);
+ for (i = 0; i < 3; i++) dir[i] += 0.3 * crandom() * (1 - aim_accuracy);
+ }
+ //set the ideal view angles
+ vectoangles(dir, bs->ideal_viewangles);
+ //take the weapon spread into account for lower skilled bots
+ bs->ideal_viewangles[PITCH] += 6 * wi.vspread * crandom() * (1 - aim_accuracy);
+ bs->ideal_viewangles[PITCH] = AngleMod(bs->ideal_viewangles[PITCH]);
+ bs->ideal_viewangles[YAW] += 6 * wi.hspread * crandom() * (1 - aim_accuracy);
+ bs->ideal_viewangles[YAW] = AngleMod(bs->ideal_viewangles[YAW]);
+ //if the bots should be really challenging
+ if (bot_challenge.integer) {
+ //if the bot is really accurate and has the enemy in view for some time
+ if (aim_accuracy > 0.9 && bs->enemysight_time < FloatTime() - 1) {
+ //set the view angles directly
+ if (bs->ideal_viewangles[PITCH] > 180) bs->ideal_viewangles[PITCH] -= 360;
+ VectorCopy(bs->ideal_viewangles, bs->viewangles);
+ trap_EA_View(bs->client, bs->viewangles);
+ }
+ }
+}
+
+/*
+==================
+BotCheckAttack
+==================
+*/
+void BotCheckAttack(bot_state_t *bs) {
+ float points, reactiontime, fov, firethrottle;
+ int attackentity;
+ bsp_trace_t bsptrace;
+ //float selfpreservation;
+ vec3_t forward, right, start, end, dir, angles;
+ weaponinfo_t wi;
+ bsp_trace_t trace;
+ aas_entityinfo_t entinfo;
+ vec3_t mins = {-8, -8, -8}, maxs = {8, 8, 8};
+
+ attackentity = bs->enemy;
+ //
+ BotEntityInfo(attackentity, &entinfo);
+ // if not attacking a player
+ if (attackentity >= MAX_CLIENTS) {
+#ifdef MISSIONPACK
+ // if attacking an obelisk
+ if ( entinfo.number == redobelisk.entitynum ||
+ entinfo.number == blueobelisk.entitynum ) {
+ // if obelisk is respawning return
+ if ( g_entities[entinfo.number].activator &&
+ g_entities[entinfo.number].activator->s.frame == 2 ) {
+ return;
+ }
+ }
+#endif
+ }
+ //
+ reactiontime = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_REACTIONTIME, 0, 1);
+ if (bs->enemysight_time > FloatTime() - reactiontime) return;
+ if (bs->teleport_time > FloatTime() - reactiontime) return;
+ //if changing weapons
+ if (bs->weaponchange_time > FloatTime() - 0.1) return;
+ //check fire throttle characteristic
+ if (bs->firethrottlewait_time > FloatTime()) return;
+ firethrottle = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_FIRETHROTTLE, 0, 1);
+ if (bs->firethrottleshoot_time < FloatTime()) {
+ if (random() > firethrottle) {
+ bs->firethrottlewait_time = FloatTime() + firethrottle;
+ bs->firethrottleshoot_time = 0;
+ }
+ else {
+ bs->firethrottleshoot_time = FloatTime() + 1 - firethrottle;
+ bs->firethrottlewait_time = 0;
+ }
+ }
+ //
+ //
+ VectorSubtract(bs->aimtarget, bs->eye, dir);
+ //
+ if (bs->weaponnum == WP_GAUNTLET) {
+ if (VectorLengthSquared(dir) > Square(60)) {
+ return;
+ }
+ }
+ if (VectorLengthSquared(dir) < Square(100))
+ fov = 120;
+ else
+ fov = 50;
+ //
+ vectoangles(dir, angles);
+ if (!InFieldOfVision(bs->viewangles, fov, angles))
+ return;
+ BotAI_Trace(&bsptrace, bs->eye, NULL, NULL, bs->aimtarget, bs->client, CONTENTS_SOLID|CONTENTS_PLAYERCLIP);
+ if (bsptrace.fraction < 1 && bsptrace.ent != attackentity)
+ return;
+
+ //get the weapon info
+ trap_BotGetWeaponInfo(bs->ws, bs->weaponnum, &wi);
+ //get the start point shooting from
+ VectorCopy(bs->origin, start);
+ start[2] += bs->cur_ps.viewheight;
+ AngleVectors(bs->viewangles, forward, right, NULL);
+ start[0] += forward[0] * wi.offset[0] + right[0] * wi.offset[1];
+ start[1] += forward[1] * wi.offset[0] + right[1] * wi.offset[1];
+ start[2] += forward[2] * wi.offset[0] + right[2] * wi.offset[1] + wi.offset[2];
+ //end point aiming at
+ VectorMA(start, 1000, forward, end);
+ //a little back to make sure not inside a very close enemy
+ VectorMA(start, -12, forward, start);
+ BotAI_Trace(&trace, start, mins, maxs, end, bs->entitynum, MASK_SHOT);
+ //if the entity is a client
+ if (trace.ent > 0 && trace.ent <= MAX_CLIENTS) {
+ if (trace.ent != attackentity) {
+ //if a teammate is hit
+ if (BotSameTeam(bs, trace.ent))
+ return;
+ }
+ }
+ //if won't hit the enemy or not attacking a player (obelisk)
+ if (trace.ent != attackentity || attackentity >= MAX_CLIENTS) {
+ //if the projectile does radial damage
+ if (wi.proj.damagetype & DAMAGETYPE_RADIAL) {
+ if (trace.fraction * 1000 < wi.proj.radius) {
+ points = (wi.proj.damage - 0.5 * trace.fraction * 1000) * 0.5;
+ if (points > 0) {
+ return;
+ }
+ }
+ //FIXME: check if a teammate gets radial damage
+ }
+ }
+ //if fire has to be release to activate weapon
+ if (wi.flags & WFL_FIRERELEASED) {
+ if (bs->flags & BFL_ATTACKED) {
+ trap_EA_Attack(bs->client);
+ }
+ }
+ else {
+ trap_EA_Attack(bs->client);
+ }
+ bs->flags ^= BFL_ATTACKED;
+}
+
+/*
+==================
+BotMapScripts
+==================
+*/
+void BotMapScripts(bot_state_t *bs) {
+ char info[1024];
+ char mapname[128];
+ int i, shootbutton;
+ float aim_accuracy;
+ aas_entityinfo_t entinfo;
+ vec3_t dir;
+
+ trap_GetServerinfo(info, sizeof(info));
+
+ strncpy(mapname, Info_ValueForKey( info, "mapname" ), sizeof(mapname)-1);
+ mapname[sizeof(mapname)-1] = '\0';
+
+ if (!Q_stricmp(mapname, "q3tourney6")) {
+ vec3_t mins = {700, 204, 672}, maxs = {964, 468, 680};
+ vec3_t buttonorg = {304, 352, 920};
+ //NOTE: NEVER use the func_bobbing in q3tourney6
+ bs->tfl &= ~TFL_FUNCBOB;
+ //if the bot is below the bounding box
+ if (bs->origin[0] > mins[0] && bs->origin[0] < maxs[0]) {
+ if (bs->origin[1] > mins[1] && bs->origin[1] < maxs[1]) {
+ if (bs->origin[2] < mins[2]) {
+ return;
+ }
+ }
+ }
+ shootbutton = qfalse;
+ //if an enemy is below this bounding box then shoot the button
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+
+ if (i == bs->client) continue;
+ //
+ BotEntityInfo(i, &entinfo);
+ //
+ if (!entinfo.valid) continue;
+ //if the enemy isn't dead and the enemy isn't the bot self
+ if (EntityIsDead(&entinfo) || entinfo.number == bs->entitynum) continue;
+ //
+ if (entinfo.origin[0] > mins[0] && entinfo.origin[0] < maxs[0]) {
+ if (entinfo.origin[1] > mins[1] && entinfo.origin[1] < maxs[1]) {
+ if (entinfo.origin[2] < mins[2]) {
+ //if there's a team mate below the crusher
+ if (BotSameTeam(bs, i)) {
+ shootbutton = qfalse;
+ break;
+ }
+ else {
+ shootbutton = qtrue;
+ }
+ }
+ }
+ }
+ }
+ if (shootbutton) {
+ bs->flags |= BFL_IDEALVIEWSET;
+ VectorSubtract(buttonorg, bs->eye, dir);
+ vectoangles(dir, bs->ideal_viewangles);
+ aim_accuracy = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_AIM_ACCURACY, 0, 1);
+ bs->ideal_viewangles[PITCH] += 8 * crandom() * (1 - aim_accuracy);
+ bs->ideal_viewangles[PITCH] = AngleMod(bs->ideal_viewangles[PITCH]);
+ bs->ideal_viewangles[YAW] += 8 * crandom() * (1 - aim_accuracy);
+ bs->ideal_viewangles[YAW] = AngleMod(bs->ideal_viewangles[YAW]);
+ //
+ if (InFieldOfVision(bs->viewangles, 20, bs->ideal_viewangles)) {
+ trap_EA_Attack(bs->client);
+ }
+ }
+ }
+ else if (!Q_stricmp(mapname, "mpq3tourney6")) {
+ //NOTE: NEVER use the func_bobbing in mpq3tourney6
+ bs->tfl &= ~TFL_FUNCBOB;
+ }
+}
+
+/*
+==================
+BotSetMovedir
+==================
+*/
+// bk001205 - made these static
+static vec3_t VEC_UP = {0, -1, 0};
+static vec3_t MOVEDIR_UP = {0, 0, 1};
+static vec3_t VEC_DOWN = {0, -2, 0};
+static vec3_t MOVEDIR_DOWN = {0, 0, -1};
+
+void BotSetMovedir(vec3_t angles, vec3_t movedir) {
+ if (VectorCompare(angles, VEC_UP)) {
+ VectorCopy(MOVEDIR_UP, movedir);
+ }
+ else if (VectorCompare(angles, VEC_DOWN)) {
+ VectorCopy(MOVEDIR_DOWN, movedir);
+ }
+ else {
+ AngleVectors(angles, movedir, NULL, NULL);
+ }
+}
+
+/*
+==================
+BotModelMinsMaxs
+
+this is ugly
+==================
+*/
+int BotModelMinsMaxs(int modelindex, int eType, int contents, vec3_t mins, vec3_t maxs) {
+ gentity_t *ent;
+ int i;
+
+ ent = &g_entities[0];
+ for (i = 0; i < level.num_entities; i++, ent++) {
+ if ( !ent->inuse ) {
+ continue;
+ }
+ if ( eType && ent->s.eType != eType) {
+ continue;
+ }
+ if ( contents && ent->r.contents != contents) {
+ continue;
+ }
+ if (ent->s.modelindex == modelindex) {
+ if (mins)
+ VectorAdd(ent->r.currentOrigin, ent->r.mins, mins);
+ if (maxs)
+ VectorAdd(ent->r.currentOrigin, ent->r.maxs, maxs);
+ return i;
+ }
+ }
+ if (mins)
+ VectorClear(mins);
+ if (maxs)
+ VectorClear(maxs);
+ return 0;
+}
+
+/*
+==================
+BotFuncButtonGoal
+==================
+*/
+int BotFuncButtonActivateGoal(bot_state_t *bs, int bspent, bot_activategoal_t *activategoal) {
+ int i, areas[10], numareas, modelindex, entitynum;
+ char model[128];
+ float lip, dist, health, angle;
+ vec3_t size, start, end, mins, maxs, angles, points[10];
+ vec3_t movedir, origin, goalorigin, bboxmins, bboxmaxs;
+ vec3_t extramins = {1, 1, 1}, extramaxs = {-1, -1, -1};
+ bsp_trace_t bsptrace;
+
+ activategoal->shoot = qfalse;
+ VectorClear(activategoal->target);
+ //create a bot goal towards the button
+ trap_AAS_ValueForBSPEpairKey(bspent, "model", model, sizeof(model));
+ if (!*model)
+ return qfalse;
+ modelindex = atoi(model+1);
+ if (!modelindex)
+ return qfalse;
+ VectorClear(angles);
+ entitynum = BotModelMinsMaxs(modelindex, ET_MOVER, 0, mins, maxs);
+ //get the lip of the button
+ trap_AAS_FloatForBSPEpairKey(bspent, "lip", &lip);
+ if (!lip) lip = 4;
+ //get the move direction from the angle
+ trap_AAS_FloatForBSPEpairKey(bspent, "angle", &angle);
+ VectorSet(angles, 0, angle, 0);
+ BotSetMovedir(angles, movedir);
+ //button size
+ VectorSubtract(maxs, mins, size);
+ //button origin
+ VectorAdd(mins, maxs, origin);
+ VectorScale(origin, 0.5, origin);
+ //touch distance of the button
+ dist = fabs(movedir[0]) * size[0] + fabs(movedir[1]) * size[1] + fabs(movedir[2]) * size[2];
+ dist *= 0.5;
+ //
+ trap_AAS_FloatForBSPEpairKey(bspent, "health", &health);
+ //if the button is shootable
+ if (health) {
+ //calculate the shoot target
+ VectorMA(origin, -dist, movedir, goalorigin);
+ //
+ VectorCopy(goalorigin, activategoal->target);
+ activategoal->shoot = qtrue;
+ //
+ BotAI_Trace(&bsptrace, bs->eye, NULL, NULL, goalorigin, bs->entitynum, MASK_SHOT);
+ // if the button is visible from the current position
+ if (bsptrace.fraction >= 1.0 || bsptrace.ent == entitynum) {
+ //
+ activategoal->goal.entitynum = entitynum; //NOTE: this is the entity number of the shootable button
+ activategoal->goal.number = 0;
+ activategoal->goal.flags = 0;
+ VectorCopy(bs->origin, activategoal->goal.origin);
+ activategoal->goal.areanum = bs->areanum;
+ VectorSet(activategoal->goal.mins, -8, -8, -8);
+ VectorSet(activategoal->goal.maxs, 8, 8, 8);
+ //
+ return qtrue;
+ }
+ else {
+ //create a goal from where the button is visible and shoot at the button from there
+ //add bounding box size to the dist
+ trap_AAS_PresenceTypeBoundingBox(PRESENCE_CROUCH, bboxmins, bboxmaxs);
+ for (i = 0; i < 3; i++) {
+ if (movedir[i] < 0) dist += fabs(movedir[i]) * fabs(bboxmaxs[i]);
+ else dist += fabs(movedir[i]) * fabs(bboxmins[i]);
+ }
+ //calculate the goal origin
+ VectorMA(origin, -dist, movedir, goalorigin);
+ //
+ VectorCopy(goalorigin, start);
+ start[2] += 24;
+ VectorCopy(start, end);
+ end[2] -= 512;
+ numareas = trap_AAS_TraceAreas(start, end, areas, points, 10);
+ //
+ for (i = numareas-1; i >= 0; i--) {
+ if (trap_AAS_AreaReachability(areas[i])) {
+ break;
+ }
+ }
+ if (i < 0) {
+ // FIXME: trace forward and maybe in other directions to find a valid area
+ }
+ if (i >= 0) {
+ //
+ VectorCopy(points[i], activategoal->goal.origin);
+ activategoal->goal.areanum = areas[i];
+ VectorSet(activategoal->goal.mins, 8, 8, 8);
+ VectorSet(activategoal->goal.maxs, -8, -8, -8);
+ //
+ for (i = 0; i < 3; i++)
+ {
+ if (movedir[i] < 0) activategoal->goal.maxs[i] += fabs(movedir[i]) * fabs(extramaxs[i]);
+ else activategoal->goal.mins[i] += fabs(movedir[i]) * fabs(extramins[i]);
+ } //end for
+ //
+ activategoal->goal.entitynum = entitynum;
+ activategoal->goal.number = 0;
+ activategoal->goal.flags = 0;
+ return qtrue;
+ }
+ }
+ return qfalse;
+ }
+ else {
+ //add bounding box size to the dist
+ trap_AAS_PresenceTypeBoundingBox(PRESENCE_CROUCH, bboxmins, bboxmaxs);
+ for (i = 0; i < 3; i++) {
+ if (movedir[i] < 0) dist += fabs(movedir[i]) * fabs(bboxmaxs[i]);
+ else dist += fabs(movedir[i]) * fabs(bboxmins[i]);
+ }
+ //calculate the goal origin
+ VectorMA(origin, -dist, movedir, goalorigin);
+ //
+ VectorCopy(goalorigin, start);
+ start[2] += 24;
+ VectorCopy(start, end);
+ end[2] -= 100;
+ numareas = trap_AAS_TraceAreas(start, end, areas, NULL, 10);
+ //
+ for (i = 0; i < numareas; i++) {
+ if (trap_AAS_AreaReachability(areas[i])) {
+ break;
+ }
+ }
+ if (i < numareas) {
+ //
+ VectorCopy(origin, activategoal->goal.origin);
+ activategoal->goal.areanum = areas[i];
+ VectorSubtract(mins, origin, activategoal->goal.mins);
+ VectorSubtract(maxs, origin, activategoal->goal.maxs);
+ //
+ for (i = 0; i < 3; i++)
+ {
+ if (movedir[i] < 0) activategoal->goal.maxs[i] += fabs(movedir[i]) * fabs(extramaxs[i]);
+ else activategoal->goal.mins[i] += fabs(movedir[i]) * fabs(extramins[i]);
+ } //end for
+ //
+ activategoal->goal.entitynum = entitynum;
+ activategoal->goal.number = 0;
+ activategoal->goal.flags = 0;
+ return qtrue;
+ }
+ }
+ return qfalse;
+}
+
+/*
+==================
+BotFuncDoorGoal
+==================
+*/
+int BotFuncDoorActivateGoal(bot_state_t *bs, int bspent, bot_activategoal_t *activategoal) {
+ int modelindex, entitynum;
+ char model[MAX_INFO_STRING];
+ vec3_t mins, maxs, origin, angles;
+
+ //shoot at the shootable door
+ trap_AAS_ValueForBSPEpairKey(bspent, "model", model, sizeof(model));
+ if (!*model)
+ return qfalse;
+ modelindex = atoi(model+1);
+ if (!modelindex)
+ return qfalse;
+ VectorClear(angles);
+ entitynum = BotModelMinsMaxs(modelindex, ET_MOVER, 0, mins, maxs);
+ //door origin
+ VectorAdd(mins, maxs, origin);
+ VectorScale(origin, 0.5, origin);
+ VectorCopy(origin, activategoal->target);
+ activategoal->shoot = qtrue;
+ //
+ activategoal->goal.entitynum = entitynum; //NOTE: this is the entity number of the shootable door
+ activategoal->goal.number = 0;
+ activategoal->goal.flags = 0;
+ VectorCopy(bs->origin, activategoal->goal.origin);
+ activategoal->goal.areanum = bs->areanum;
+ VectorSet(activategoal->goal.mins, -8, -8, -8);
+ VectorSet(activategoal->goal.maxs, 8, 8, 8);
+ return qtrue;
+}
+
+/*
+==================
+BotTriggerMultipleGoal
+==================
+*/
+int BotTriggerMultipleActivateGoal(bot_state_t *bs, int bspent, bot_activategoal_t *activategoal) {
+ int i, areas[10], numareas, modelindex, entitynum;
+ char model[128];
+ vec3_t start, end, mins, maxs, angles;
+ vec3_t origin, goalorigin;
+
+ activategoal->shoot = qfalse;
+ VectorClear(activategoal->target);
+ //create a bot goal towards the trigger
+ trap_AAS_ValueForBSPEpairKey(bspent, "model", model, sizeof(model));
+ if (!*model)
+ return qfalse;
+ modelindex = atoi(model+1);
+ if (!modelindex)
+ return qfalse;
+ VectorClear(angles);
+ entitynum = BotModelMinsMaxs(modelindex, 0, CONTENTS_TRIGGER, mins, maxs);
+ //trigger origin
+ VectorAdd(mins, maxs, origin);
+ VectorScale(origin, 0.5, origin);
+ VectorCopy(origin, goalorigin);
+ //
+ VectorCopy(goalorigin, start);
+ start[2] += 24;
+ VectorCopy(start, end);
+ end[2] -= 100;
+ numareas = trap_AAS_TraceAreas(start, end, areas, NULL, 10);
+ //
+ for (i = 0; i < numareas; i++) {
+ if (trap_AAS_AreaReachability(areas[i])) {
+ break;
+ }
+ }
+ if (i < numareas) {
+ VectorCopy(origin, activategoal->goal.origin);
+ activategoal->goal.areanum = areas[i];
+ VectorSubtract(mins, origin, activategoal->goal.mins);
+ VectorSubtract(maxs, origin, activategoal->goal.maxs);
+ //
+ activategoal->goal.entitynum = entitynum;
+ activategoal->goal.number = 0;
+ activategoal->goal.flags = 0;
+ return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+==================
+BotPopFromActivateGoalStack
+==================
+*/
+int BotPopFromActivateGoalStack(bot_state_t *bs) {
+ if (!bs->activatestack)
+ return qfalse;
+ BotEnableActivateGoalAreas(bs->activatestack, qtrue);
+ bs->activatestack->inuse = qfalse;
+ bs->activatestack->justused_time = FloatTime();
+ bs->activatestack = bs->activatestack->next;
+ return qtrue;
+}
+
+/*
+==================
+BotPushOntoActivateGoalStack
+==================
+*/
+int BotPushOntoActivateGoalStack(bot_state_t *bs, bot_activategoal_t *activategoal) {
+ int i, best;
+ float besttime;
+
+ best = -1;
+ besttime = FloatTime() + 9999;
+ //
+ for (i = 0; i < MAX_ACTIVATESTACK; i++) {
+ if (!bs->activategoalheap[i].inuse) {
+ if (bs->activategoalheap[i].justused_time < besttime) {
+ besttime = bs->activategoalheap[i].justused_time;
+ best = i;
+ }
+ }
+ }
+ if (best != -1) {
+ memcpy(&bs->activategoalheap[best], activategoal, sizeof(bot_activategoal_t));
+ bs->activategoalheap[best].inuse = qtrue;
+ bs->activategoalheap[best].next = bs->activatestack;
+ bs->activatestack = &bs->activategoalheap[best];
+ return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+==================
+BotClearActivateGoalStack
+==================
+*/
+void BotClearActivateGoalStack(bot_state_t *bs) {
+ while(bs->activatestack)
+ BotPopFromActivateGoalStack(bs);
+}
+
+/*
+==================
+BotEnableActivateGoalAreas
+==================
+*/
+void BotEnableActivateGoalAreas(bot_activategoal_t *activategoal, int enable) {
+ int i;
+
+ if (activategoal->areasdisabled == !enable)
+ return;
+ for (i = 0; i < activategoal->numareas; i++)
+ trap_AAS_EnableRoutingArea( activategoal->areas[i], enable );
+ activategoal->areasdisabled = !enable;
+}
+
+/*
+==================
+BotIsGoingToActivateEntity
+==================
+*/
+int BotIsGoingToActivateEntity(bot_state_t *bs, int entitynum) {
+ bot_activategoal_t *a;
+ int i;
+
+ for (a = bs->activatestack; a; a = a->next) {
+ if (a->time < FloatTime())
+ continue;
+ if (a->goal.entitynum == entitynum)
+ return qtrue;
+ }
+ for (i = 0; i < MAX_ACTIVATESTACK; i++) {
+ if (bs->activategoalheap[i].inuse)
+ continue;
+ //
+ if (bs->activategoalheap[i].goal.entitynum == entitynum) {
+ // if the bot went for this goal less than 2 seconds ago
+ if (bs->activategoalheap[i].justused_time > FloatTime() - 2)
+ return qtrue;
+ }
+ }
+ return qfalse;
+}
+
+/*
+==================
+BotGetActivateGoal
+
+ returns the number of the bsp entity to activate
+ goal->entitynum will be set to the game entity to activate
+==================
+*/
+//#define OBSTACLEDEBUG
+
+int BotGetActivateGoal(bot_state_t *bs, int entitynum, bot_activategoal_t *activategoal) {
+ int i, ent, cur_entities[10], spawnflags, modelindex, areas[MAX_ACTIVATEAREAS*2], numareas, t;
+ char model[MAX_INFO_STRING], tmpmodel[128];
+ char target[128], classname[128];
+ float health;
+ char targetname[10][128];
+ aas_entityinfo_t entinfo;
+ aas_areainfo_t areainfo;
+ vec3_t origin, angles, absmins, absmaxs;
+
+ memset(activategoal, 0, sizeof(bot_activategoal_t));
+ BotEntityInfo(entitynum, &entinfo);
+ Com_sprintf(model, sizeof( model ), "*%d", entinfo.modelindex);
+ for (ent = trap_AAS_NextBSPEntity(0); ent; ent = trap_AAS_NextBSPEntity(ent)) {
+ if (!trap_AAS_ValueForBSPEpairKey(ent, "model", tmpmodel, sizeof(tmpmodel))) continue;
+ if (!strcmp(model, tmpmodel)) break;
+ }
+ if (!ent) {
+ BotAI_Print(PRT_ERROR, "BotGetActivateGoal: no entity found with model %s\n", model);
+ return 0;
+ }
+ trap_AAS_ValueForBSPEpairKey(ent, "classname", classname, sizeof(classname));
+ if (!classname) {
+ BotAI_Print(PRT_ERROR, "BotGetActivateGoal: entity with model %s has no classname\n", model);
+ return 0;
+ }
+ //if it is a door
+ if (!strcmp(classname, "func_door")) {
+ if (trap_AAS_FloatForBSPEpairKey(ent, "health", &health)) {
+ //if the door has health then the door must be shot to open
+ if (health) {
+ BotFuncDoorActivateGoal(bs, ent, activategoal);
+ return ent;
+ }
+ }
+ //
+ trap_AAS_IntForBSPEpairKey(ent, "spawnflags", &spawnflags);
+ // if the door starts open then just wait for the door to return
+ if ( spawnflags & 1 )
+ return 0;
+ //get the door origin
+ if (!trap_AAS_VectorForBSPEpairKey(ent, "origin", origin)) {
+ VectorClear(origin);
+ }
+ //if the door is open or opening already
+ if (!VectorCompare(origin, entinfo.origin))
+ return 0;
+ // store all the areas the door is in
+ trap_AAS_ValueForBSPEpairKey(ent, "model", model, sizeof(model));
+ if (*model) {
+ modelindex = atoi(model+1);
+ if (modelindex) {
+ VectorClear(angles);
+ BotModelMinsMaxs(modelindex, ET_MOVER, 0, absmins, absmaxs);
+ //
+ numareas = trap_AAS_BBoxAreas(absmins, absmaxs, areas, MAX_ACTIVATEAREAS*2);
+ // store the areas with reachabilities first
+ for (i = 0; i < numareas; i++) {
+ if (activategoal->numareas >= MAX_ACTIVATEAREAS)
+ break;
+ if ( !trap_AAS_AreaReachability(areas[i]) ) {
+ continue;
+ }
+ trap_AAS_AreaInfo(areas[i], &areainfo);
+ if (areainfo.contents & AREACONTENTS_MOVER) {
+ activategoal->areas[activategoal->numareas++] = areas[i];
+ }
+ }
+ // store any remaining areas
+ for (i = 0; i < numareas; i++) {
+ if (activategoal->numareas >= MAX_ACTIVATEAREAS)
+ break;
+ if ( trap_AAS_AreaReachability(areas[i]) ) {
+ continue;
+ }
+ trap_AAS_AreaInfo(areas[i], &areainfo);
+ if (areainfo.contents & AREACONTENTS_MOVER) {
+ activategoal->areas[activategoal->numareas++] = areas[i];
+ }
+ }
+ }
+ }
+ }
+ // if the bot is blocked by or standing on top of a button
+ if (!strcmp(classname, "func_button")) {
+ return 0;
+ }
+ // get the targetname so we can find an entity with a matching target
+ if (!trap_AAS_ValueForBSPEpairKey(ent, "targetname", targetname[0], sizeof(targetname[0]))) {
+ if (bot_developer.integer) {
+ BotAI_Print(PRT_ERROR, "BotGetActivateGoal: entity with model \"%s\" has no targetname\n", model);
+ }
+ return 0;
+ }
+ // allow tree-like activation
+ cur_entities[0] = trap_AAS_NextBSPEntity(0);
+ for (i = 0; i >= 0 && i < 10;) {
+ for (ent = cur_entities[i]; ent; ent = trap_AAS_NextBSPEntity(ent)) {
+ if (!trap_AAS_ValueForBSPEpairKey(ent, "target", target, sizeof(target))) continue;
+ if (!strcmp(targetname[i], target)) {
+ cur_entities[i] = trap_AAS_NextBSPEntity(ent);
+ break;
+ }
+ }
+ if (!ent) {
+ if (bot_developer.integer) {
+ BotAI_Print(PRT_ERROR, "BotGetActivateGoal: no entity with target \"%s\"\n", targetname[i]);
+ }
+ i--;
+ continue;
+ }
+ if (!trap_AAS_ValueForBSPEpairKey(ent, "classname", classname, sizeof(classname))) {
+ if (bot_developer.integer) {
+ BotAI_Print(PRT_ERROR, "BotGetActivateGoal: entity with target \"%s\" has no classname\n", targetname[i]);
+ }
+ continue;
+ }
+ // BSP button model
+ if (!strcmp(classname, "func_button")) {
+ //
+ if (!BotFuncButtonActivateGoal(bs, ent, activategoal))
+ continue;
+ // if the bot tries to activate this button already
+ if ( bs->activatestack && bs->activatestack->inuse &&
+ bs->activatestack->goal.entitynum == activategoal->goal.entitynum &&
+ bs->activatestack->time > FloatTime() &&
+ bs->activatestack->start_time < FloatTime() - 2)
+ continue;
+ // if the bot is in a reachability area
+ if ( trap_AAS_AreaReachability(bs->areanum) ) {
+ // disable all areas the blocking entity is in
+ BotEnableActivateGoalAreas( activategoal, qfalse );
+ //
+ t = trap_AAS_AreaTravelTimeToGoalArea(bs->areanum, bs->origin, activategoal->goal.areanum, bs->tfl);
+ // if the button is not reachable
+ if (!t) {
+ continue;
+ }
+ activategoal->time = FloatTime() + t * 0.01 + 5;
+ }
+ return ent;
+ }
+ // invisible trigger multiple box
+ else if (!strcmp(classname, "trigger_multiple")) {
+ //
+ if (!BotTriggerMultipleActivateGoal(bs, ent, activategoal))
+ continue;
+ // if the bot tries to activate this trigger already
+ if ( bs->activatestack && bs->activatestack->inuse &&
+ bs->activatestack->goal.entitynum == activategoal->goal.entitynum &&
+ bs->activatestack->time > FloatTime() &&
+ bs->activatestack->start_time < FloatTime() - 2)
+ continue;
+ // if the bot is in a reachability area
+ if ( trap_AAS_AreaReachability(bs->areanum) ) {
+ // disable all areas the blocking entity is in
+ BotEnableActivateGoalAreas( activategoal, qfalse );
+ //
+ t = trap_AAS_AreaTravelTimeToGoalArea(bs->areanum, bs->origin, activategoal->goal.areanum, bs->tfl);
+ // if the trigger is not reachable
+ if (!t) {
+ continue;
+ }
+ activategoal->time = FloatTime() + t * 0.01 + 5;
+ }
+ return ent;
+ }
+ else if (!strcmp(classname, "func_timer")) {
+ // just skip the func_timer
+ continue;
+ }
+ // the actual button or trigger might be linked through a target_relay or target_delay
+ else if (!strcmp(classname, "target_relay") || !strcmp(classname, "target_delay")) {
+ if (trap_AAS_ValueForBSPEpairKey(ent, "targetname", targetname[i+1], sizeof(targetname[0]))) {
+ i++;
+ cur_entities[i] = trap_AAS_NextBSPEntity(0);
+ }
+ }
+ }
+#ifdef OBSTACLEDEBUG
+ BotAI_Print(PRT_ERROR, "BotGetActivateGoal: no valid activator for entity with target \"%s\"\n", targetname[0]);
+#endif
+ return 0;
+}
+
+/*
+==================
+BotGoForActivateGoal
+==================
+*/
+int BotGoForActivateGoal(bot_state_t *bs, bot_activategoal_t *activategoal) {
+ aas_entityinfo_t activateinfo;
+
+ activategoal->inuse = qtrue;
+ if (!activategoal->time)
+ activategoal->time = FloatTime() + 10;
+ activategoal->start_time = FloatTime();
+ BotEntityInfo(activategoal->goal.entitynum, &activateinfo);
+ VectorCopy(activateinfo.origin, activategoal->origin);
+ //
+ if (BotPushOntoActivateGoalStack(bs, activategoal)) {
+ // enter the activate entity AI node
+ AIEnter_Seek_ActivateEntity(bs, "BotGoForActivateGoal");
+ return qtrue;
+ }
+ else {
+ // enable any routing areas that were disabled
+ BotEnableActivateGoalAreas(activategoal, qtrue);
+ return qfalse;
+ }
+}
+
+/*
+==================
+BotPrintActivateGoalInfo
+==================
+*/
+void BotPrintActivateGoalInfo(bot_state_t *bs, bot_activategoal_t *activategoal, int bspent) {
+ char netname[MAX_NETNAME];
+ char classname[128];
+ char buf[128];
+
+ ClientName(bs->client, netname, sizeof(netname));
+ trap_AAS_ValueForBSPEpairKey(bspent, "classname", classname, sizeof(classname));
+ if (activategoal->shoot) {
+ Com_sprintf(buf, sizeof(buf), "%s: I have to shoot at a %s from %1.1f %1.1f %1.1f in area %d\n",
+ netname, classname,
+ activategoal->goal.origin[0],
+ activategoal->goal.origin[1],
+ activategoal->goal.origin[2],
+ activategoal->goal.areanum);
+ }
+ else {
+ Com_sprintf(buf, sizeof(buf), "%s: I have to activate a %s at %1.1f %1.1f %1.1f in area %d\n",
+ netname, classname,
+ activategoal->goal.origin[0],
+ activategoal->goal.origin[1],
+ activategoal->goal.origin[2],
+ activategoal->goal.areanum);
+ }
+ trap_EA_Say(bs->client, buf);
+}
+
+/*
+==================
+BotRandomMove
+==================
+*/
+void BotRandomMove(bot_state_t *bs, bot_moveresult_t *moveresult) {
+ vec3_t dir, angles;
+
+ angles[0] = 0;
+ angles[1] = random() * 360;
+ angles[2] = 0;
+ AngleVectors(angles, dir, NULL, NULL);
+
+ trap_BotMoveInDirection(bs->ms, dir, 400, MOVE_WALK);
+
+ moveresult->failure = qfalse;
+ VectorCopy(dir, moveresult->movedir);
+}
+
+/*
+==================
+BotAIBlocked
+
+Very basic handling of bots being blocked by other entities.
+Check what kind of entity is blocking the bot and try to activate
+it. If that's not an option then try to walk around or over the entity.
+Before the bot ends in this part of the AI it should predict which doors to
+open, which buttons to activate etc.
+==================
+*/
+void BotAIBlocked(bot_state_t *bs, bot_moveresult_t *moveresult, int activate) {
+ int movetype, bspent;
+ vec3_t hordir, start, end, mins, maxs, sideward, angles, up = {0, 0, 1};
+ aas_entityinfo_t entinfo;
+ bot_activategoal_t activategoal;
+
+ // if the bot is not blocked by anything
+ if (!moveresult->blocked) {
+ bs->notblocked_time = FloatTime();
+ return;
+ }
+ // if stuck in a solid area
+ if ( moveresult->type == RESULTTYPE_INSOLIDAREA ) {
+ // move in a random direction in the hope to get out
+ BotRandomMove(bs, moveresult);
+ //
+ return;
+ }
+ // get info for the entity that is blocking the bot
+ BotEntityInfo(moveresult->blockentity, &entinfo);
+#ifdef OBSTACLEDEBUG
+ ClientName(bs->client, netname, sizeof(netname));
+ BotAI_Print(PRT_MESSAGE, "%s: I'm blocked by model %d\n", netname, entinfo.modelindex);
+#endif // OBSTACLEDEBUG
+ // if blocked by a bsp model and the bot wants to activate it
+ if (activate && entinfo.modelindex > 0 && entinfo.modelindex <= max_bspmodelindex) {
+ // find the bsp entity which should be activated in order to get the blocking entity out of the way
+ bspent = BotGetActivateGoal(bs, entinfo.number, &activategoal);
+ if (bspent) {
+ //
+ if (bs->activatestack && !bs->activatestack->inuse)
+ bs->activatestack = NULL;
+ // if not already trying to activate this entity
+ if (!BotIsGoingToActivateEntity(bs, activategoal.goal.entitynum)) {
+ //
+ BotGoForActivateGoal(bs, &activategoal);
+ }
+ // if ontop of an obstacle or
+ // if the bot is not in a reachability area it'll still
+ // need some dynamic obstacle avoidance, otherwise return
+ if (!(moveresult->flags & MOVERESULT_ONTOPOFOBSTACLE) &&
+ trap_AAS_AreaReachability(bs->areanum))
+ return;
+ }
+ else {
+ // enable any routing areas that were disabled
+ BotEnableActivateGoalAreas(&activategoal, qtrue);
+ }
+ }
+ // just some basic dynamic obstacle avoidance code
+ hordir[0] = moveresult->movedir[0];
+ hordir[1] = moveresult->movedir[1];
+ hordir[2] = 0;
+ // if no direction just take a random direction
+ if (VectorNormalize(hordir) < 0.1) {
+ VectorSet(angles, 0, 360 * random(), 0);
+ AngleVectors(angles, hordir, NULL, NULL);
+ }
+ //
+ //if (moveresult->flags & MOVERESULT_ONTOPOFOBSTACLE) movetype = MOVE_JUMP;
+ //else
+ movetype = MOVE_WALK;
+ // if there's an obstacle at the bot's feet and head then
+ // the bot might be able to crouch through
+ VectorCopy(bs->origin, start);
+ start[2] += 18;
+ VectorMA(start, 5, hordir, end);
+ VectorSet(mins, -16, -16, -24);
+ VectorSet(maxs, 16, 16, 4);
+ //
+ //bsptrace = AAS_Trace(start, mins, maxs, end, bs->entitynum, MASK_PLAYERSOLID);
+ //if (bsptrace.fraction >= 1) movetype = MOVE_CROUCH;
+ // get the sideward vector
+ CrossProduct(hordir, up, sideward);
+ //
+ if (bs->flags & BFL_AVOIDRIGHT) VectorNegate(sideward, sideward);
+ // try to crouch straight forward?
+ if (movetype != MOVE_CROUCH || !trap_BotMoveInDirection(bs->ms, hordir, 400, movetype)) {
+ // perform the movement
+ if (!trap_BotMoveInDirection(bs->ms, sideward, 400, movetype)) {
+ // flip the avoid direction flag
+ bs->flags ^= BFL_AVOIDRIGHT;
+ // flip the direction
+ // VectorNegate(sideward, sideward);
+ VectorMA(sideward, -1, hordir, sideward);
+ // move in the other direction
+ trap_BotMoveInDirection(bs->ms, sideward, 400, movetype);
+ }
+ }
+ //
+ if (bs->notblocked_time < FloatTime() - 0.4) {
+ // just reset goals and hope the bot will go into another direction?
+ // is this still needed??
+ if (bs->ainode == AINode_Seek_NBG) bs->nbg_time = 0;
+ else if (bs->ainode == AINode_Seek_LTG) bs->ltg_time = 0;
+ }
+}
+
+/*
+==================
+BotAIPredictObstacles
+
+Predict the route towards the goal and check if the bot
+will be blocked by certain obstacles. When the bot has obstacles
+on it's path the bot should figure out if they can be removed
+by activating certain entities.
+==================
+*/
+int BotAIPredictObstacles(bot_state_t *bs, bot_goal_t *goal) {
+ int modelnum, entitynum, bspent;
+ bot_activategoal_t activategoal;
+ aas_predictroute_t route;
+
+ if (!bot_predictobstacles.integer)
+ return qfalse;
+
+ // always predict when the goal change or at regular intervals
+ if (bs->predictobstacles_goalareanum == goal->areanum &&
+ bs->predictobstacles_time > FloatTime() - 6) {
+ return qfalse;
+ }
+ bs->predictobstacles_goalareanum = goal->areanum;
+ bs->predictobstacles_time = FloatTime();
+
+ // predict at most 100 areas or 10 seconds ahead
+ trap_AAS_PredictRoute(&route, bs->areanum, bs->origin,
+ goal->areanum, bs->tfl, 100, 1000,
+ RSE_USETRAVELTYPE|RSE_ENTERCONTENTS,
+ AREACONTENTS_MOVER, TFL_BRIDGE, 0);
+ // if bot has to travel through an area with a mover
+ if (route.stopevent & RSE_ENTERCONTENTS) {
+ // if the bot will run into a mover
+ if (route.endcontents & AREACONTENTS_MOVER) {
+ //NOTE: this only works with bspc 2.1 or higher
+ modelnum = (route.endcontents & AREACONTENTS_MODELNUM) >> AREACONTENTS_MODELNUMSHIFT;
+ if (modelnum) {
+ //
+ entitynum = BotModelMinsMaxs(modelnum, ET_MOVER, 0, NULL, NULL);
+ if (entitynum) {
+ //NOTE: BotGetActivateGoal already checks if the door is open or not
+ bspent = BotGetActivateGoal(bs, entitynum, &activategoal);
+ if (bspent) {
+ //
+ if (bs->activatestack && !bs->activatestack->inuse)
+ bs->activatestack = NULL;
+ // if not already trying to activate this entity
+ if (!BotIsGoingToActivateEntity(bs, activategoal.goal.entitynum)) {
+ //
+ //BotAI_Print(PRT_MESSAGE, "blocked by mover model %d, entity %d ?\n", modelnum, entitynum);
+ //
+ BotGoForActivateGoal(bs, &activategoal);
+ return qtrue;
+ }
+ else {
+ // enable any routing areas that were disabled
+ BotEnableActivateGoalAreas(&activategoal, qtrue);
+ }
+ }
+ }
+ }
+ }
+ }
+ else if (route.stopevent & RSE_USETRAVELTYPE) {
+ if (route.endtravelflags & TFL_BRIDGE) {
+ //FIXME: check if the bridge is available to travel over
+ }
+ }
+ return qfalse;
+}
+
+/*
+==================
+BotCheckConsoleMessages
+==================
+*/
+void BotCheckConsoleMessages(bot_state_t *bs) {
+ char botname[MAX_NETNAME], message[MAX_MESSAGE_SIZE], netname[MAX_NETNAME], *ptr;
+ float chat_reply;
+ int context, handle;
+ bot_consolemessage_t m;
+ bot_match_t match;
+
+ //the name of this bot
+ ClientName(bs->client, botname, sizeof(botname));
+ //
+ while((handle = trap_BotNextConsoleMessage(bs->cs, &m)) != 0) {
+ //if the chat state is flooded with messages the bot will read them quickly
+ if (trap_BotNumConsoleMessages(bs->cs) < 10) {
+ //if it is a chat message the bot needs some time to read it
+ if (m.type == CMS_CHAT && m.time > FloatTime() - (1 + random())) break;
+ }
+ //
+ ptr = m.message;
+ //if it is a chat message then don't unify white spaces and don't
+ //replace synonyms in the netname
+ if (m.type == CMS_CHAT) {
+ //
+ if (trap_BotFindMatch(m.message, &match, MTCONTEXT_REPLYCHAT)) {
+ ptr = m.message + match.variables[MESSAGE].offset;
+ }
+ }
+ //unify the white spaces in the message
+ trap_UnifyWhiteSpaces(ptr);
+ //replace synonyms in the right context
+ context = BotSynonymContext(bs);
+ trap_BotReplaceSynonyms(ptr, context);
+ //if there's no match
+ if (!BotMatchMessage(bs, m.message)) {
+ //if it is a chat message
+ if (m.type == CMS_CHAT && !bot_nochat.integer) {
+ //
+ if (!trap_BotFindMatch(m.message, &match, MTCONTEXT_REPLYCHAT)) {
+ trap_BotRemoveConsoleMessage(bs->cs, handle);
+ continue;
+ }
+ //don't use eliza chats with team messages
+ if (match.subtype & ST_TEAM) {
+ trap_BotRemoveConsoleMessage(bs->cs, handle);
+ continue;
+ }
+ //
+ trap_BotMatchVariable(&match, NETNAME, netname, sizeof(netname));
+ trap_BotMatchVariable(&match, MESSAGE, message, sizeof(message));
+ //if this is a message from the bot self
+ if (bs->client == ClientFromName(netname)) {
+ trap_BotRemoveConsoleMessage(bs->cs, handle);
+ continue;
+ }
+ //unify the message
+ trap_UnifyWhiteSpaces(message);
+ //
+ trap_Cvar_Update(&bot_testrchat);
+ if (bot_testrchat.integer) {
+ //
+ trap_BotLibVarSet("bot_testrchat", "1");
+ //if bot replies with a chat message
+ if (trap_BotReplyChat(bs->cs, message, context, CONTEXT_REPLY,
+ NULL, NULL,
+ NULL, NULL,
+ NULL, NULL,
+ botname, netname)) {
+ BotAI_Print(PRT_MESSAGE, "------------------------\n");
+ }
+ else {
+ BotAI_Print(PRT_MESSAGE, "**** no valid reply ****\n");
+ }
+ }
+ //if at a valid chat position and not chatting already and not in teamplay
+ else if (bs->ainode != AINode_Stand && BotValidChatPosition(bs) && !TeamPlayIsOn()) {
+ chat_reply = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_CHAT_REPLY, 0, 1);
+ if (random() < 1.5 / (NumBots()+1) && random() < chat_reply) {
+ //if bot replies with a chat message
+ if (trap_BotReplyChat(bs->cs, message, context, CONTEXT_REPLY,
+ NULL, NULL,
+ NULL, NULL,
+ NULL, NULL,
+ botname, netname)) {
+ //remove the console message
+ trap_BotRemoveConsoleMessage(bs->cs, handle);
+ bs->stand_time = FloatTime() + BotChatTime(bs);
+ AIEnter_Stand(bs, "BotCheckConsoleMessages: reply chat");
+ //EA_Say(bs->client, bs->cs.chatmessage);
+ break;
+ }
+ }
+ }
+ }
+ }
+ //remove the console message
+ trap_BotRemoveConsoleMessage(bs->cs, handle);
+ }
+}
+
+/*
+==================
+BotCheckEvents
+==================
+*/
+void BotCheckForGrenades(bot_state_t *bs, entityState_t *state) {
+ // if this is not a grenade
+ if (state->eType != ET_MISSILE || state->weapon != WP_GRENADE_LAUNCHER)
+ return;
+ // try to avoid the grenade
+ trap_BotAddAvoidSpot(bs->ms, state->pos.trBase, 160, AVOID_ALWAYS);
+}
+
+#ifdef MISSIONPACK
+/*
+==================
+BotCheckForProxMines
+==================
+*/
+void BotCheckForProxMines(bot_state_t *bs, entityState_t *state) {
+ // if this is not a prox mine
+ if (state->eType != ET_MISSILE || state->weapon != WP_PROX_LAUNCHER)
+ return;
+ // if this prox mine is from someone on our own team
+ if (state->generic1 == BotTeam(bs))
+ return;
+ // if the bot doesn't have a weapon to deactivate the mine
+ if (!(bs->inventory[INVENTORY_PLASMAGUN] > 0 && bs->inventory[INVENTORY_CELLS] > 0) &&
+ !(bs->inventory[INVENTORY_ROCKETLAUNCHER] > 0 && bs->inventory[INVENTORY_ROCKETS] > 0) &&
+ !(bs->inventory[INVENTORY_BFG10K] > 0 && bs->inventory[INVENTORY_BFGAMMO] > 0) ) {
+ return;
+ }
+ // try to avoid the prox mine
+ trap_BotAddAvoidSpot(bs->ms, state->pos.trBase, 160, AVOID_ALWAYS);
+ //
+ if (bs->numproxmines >= MAX_PROXMINES)
+ return;
+ bs->proxmines[bs->numproxmines] = state->number;
+ bs->numproxmines++;
+}
+
+/*
+==================
+BotCheckForKamikazeBody
+==================
+*/
+void BotCheckForKamikazeBody(bot_state_t *bs, entityState_t *state) {
+ // if this entity is not wearing the kamikaze
+ if (!(state->eFlags & EF_KAMIKAZE))
+ return;
+ // if this entity isn't dead
+ if (!(state->eFlags & EF_DEAD))
+ return;
+ //remember this kamikaze body
+ bs->kamikazebody = state->number;
+}
+#endif
+
+/*
+==================
+BotCheckEvents
+==================
+*/
+void BotCheckEvents(bot_state_t *bs, entityState_t *state) {
+ int event;
+ char buf[128];
+#ifdef MISSIONPACK
+ aas_entityinfo_t entinfo;
+#endif
+
+ //NOTE: this sucks, we're accessing the gentity_t directly
+ //but there's no other fast way to do it right now
+ if (bs->entityeventTime[state->number] == g_entities[state->number].eventTime) {
+ return;
+ }
+ bs->entityeventTime[state->number] = g_entities[state->number].eventTime;
+ //if it's an event only entity
+ if (state->eType > ET_EVENTS) {
+ event = (state->eType - ET_EVENTS) & ~EV_EVENT_BITS;
+ }
+ else {
+ event = state->event & ~EV_EVENT_BITS;
+ }
+ //
+ switch(event) {
+ //client obituary event
+ case EV_OBITUARY:
+ {
+ int target, attacker, mod;
+
+ target = state->otherEntityNum;
+ attacker = state->otherEntityNum2;
+ mod = state->eventParm;
+ //
+ if (target == bs->client) {
+ bs->botdeathtype = mod;
+ bs->lastkilledby = attacker;
+ //
+ if (target == attacker ||
+ target == ENTITYNUM_NONE ||
+ target == ENTITYNUM_WORLD) bs->botsuicide = qtrue;
+ else bs->botsuicide = qfalse;
+ //
+ bs->num_deaths++;
+ }
+ //else if this client was killed by the bot
+ else if (attacker == bs->client) {
+ bs->enemydeathtype = mod;
+ bs->lastkilledplayer = target;
+ bs->killedenemy_time = FloatTime();
+ //
+ bs->num_kills++;
+ }
+ else if (attacker == bs->enemy && target == attacker) {
+ bs->enemysuicide = qtrue;
+ }
+ //
+#ifdef MISSIONPACK
+ if (gametype == GT_1FCTF) {
+ //
+ BotEntityInfo(target, &entinfo);
+ if ( entinfo.powerups & ( 1 << PW_NEUTRALFLAG ) ) {
+ if (!BotSameTeam(bs, target)) {
+ bs->neutralflagstatus = 3; //enemy dropped the flag
+ bs->flagstatuschanged = qtrue;
+ }
+ }
+ }
+#endif
+ break;
+ }
+ case EV_GLOBAL_SOUND:
+ {
+ if (state->eventParm < 0 || state->eventParm > MAX_SOUNDS) {
+ BotAI_Print(PRT_ERROR, "EV_GLOBAL_SOUND: eventParm (%d) out of range\n", state->eventParm);
+ break;
+ }
+ trap_GetConfigstring(CS_SOUNDS + state->eventParm, buf, sizeof(buf));
+ /*
+ if (!strcmp(buf, "sound/teamplay/flagret_red.wav")) {
+ //red flag is returned
+ bs->redflagstatus = 0;
+ bs->flagstatuschanged = qtrue;
+ }
+ else if (!strcmp(buf, "sound/teamplay/flagret_blu.wav")) {
+ //blue flag is returned
+ bs->blueflagstatus = 0;
+ bs->flagstatuschanged = qtrue;
+ }
+ else*/
+#ifdef MISSIONPACK
+ if (!strcmp(buf, "sound/items/kamikazerespawn.wav" )) {
+ //the kamikaze respawned so dont avoid it
+ BotDontAvoid(bs, "Kamikaze");
+ }
+ else
+#endif
+ if (!strcmp(buf, "sound/items/poweruprespawn.wav")) {
+ //powerup respawned... go get it
+ BotGoForPowerups(bs);
+ }
+ break;
+ }
+ case EV_GLOBAL_TEAM_SOUND:
+ {
+ if (gametype == GT_CTF) {
+ switch(state->eventParm) {
+ case GTS_RED_CAPTURE:
+ bs->blueflagstatus = 0;
+ bs->redflagstatus = 0;
+ bs->flagstatuschanged = qtrue;
+ break; //see BotMatch_CTF
+ case GTS_BLUE_CAPTURE:
+ bs->blueflagstatus = 0;
+ bs->redflagstatus = 0;
+ bs->flagstatuschanged = qtrue;
+ break; //see BotMatch_CTF
+ case GTS_RED_RETURN:
+ //blue flag is returned
+ bs->blueflagstatus = 0;
+ bs->flagstatuschanged = qtrue;
+ break;
+ case GTS_BLUE_RETURN:
+ //red flag is returned
+ bs->redflagstatus = 0;
+ bs->flagstatuschanged = qtrue;
+ break;
+ case GTS_RED_TAKEN:
+ //blue flag is taken
+ bs->blueflagstatus = 1;
+ bs->flagstatuschanged = qtrue;
+ break; //see BotMatch_CTF
+ case GTS_BLUE_TAKEN:
+ //red flag is taken
+ bs->redflagstatus = 1;
+ bs->flagstatuschanged = qtrue;
+ break; //see BotMatch_CTF
+ }
+ }
+#ifdef MISSIONPACK
+ else if (gametype == GT_1FCTF) {
+ switch(state->eventParm) {
+ case GTS_RED_CAPTURE:
+ bs->neutralflagstatus = 0;
+ bs->flagstatuschanged = qtrue;
+ break;
+ case GTS_BLUE_CAPTURE:
+ bs->neutralflagstatus = 0;
+ bs->flagstatuschanged = qtrue;
+ break;
+ case GTS_RED_RETURN:
+ //flag has returned
+ bs->neutralflagstatus = 0;
+ bs->flagstatuschanged = qtrue;
+ break;
+ case GTS_BLUE_RETURN:
+ //flag has returned
+ bs->neutralflagstatus = 0;
+ bs->flagstatuschanged = qtrue;
+ break;
+ case GTS_RED_TAKEN:
+ bs->neutralflagstatus = BotTeam(bs) == TEAM_RED ? 2 : 1; //FIXME: check Team_TakeFlagSound in g_team.c
+ bs->flagstatuschanged = qtrue;
+ break;
+ case GTS_BLUE_TAKEN:
+ bs->neutralflagstatus = BotTeam(bs) == TEAM_BLUE ? 2 : 1; //FIXME: check Team_TakeFlagSound in g_team.c
+ bs->flagstatuschanged = qtrue;
+ break;
+ }
+ }
+#endif
+ break;
+ }
+ case EV_PLAYER_TELEPORT_IN:
+ {
+ VectorCopy(state->origin, lastteleport_origin);
+ lastteleport_time = FloatTime();
+ break;
+ }
+ case EV_GENERAL_SOUND:
+ {
+ //if this sound is played on the bot
+ if (state->number == bs->client) {
+ if (state->eventParm < 0 || state->eventParm > MAX_SOUNDS) {
+ BotAI_Print(PRT_ERROR, "EV_GENERAL_SOUND: eventParm (%d) out of range\n", state->eventParm);
+ break;
+ }
+ //check out the sound
+ trap_GetConfigstring(CS_SOUNDS + state->eventParm, buf, sizeof(buf));
+ //if falling into a death pit
+ if (!strcmp(buf, "*falling1.wav")) {
+ //if the bot has a personal teleporter
+ if (bs->inventory[INVENTORY_TELEPORTER] > 0) {
+ //use the holdable item
+ trap_EA_Use(bs->client);
+ }
+ }
+ }
+ break;
+ }
+ case EV_FOOTSTEP:
+ case EV_FOOTSTEP_METAL:
+ case EV_FOOTSPLASH:
+ case EV_FOOTWADE:
+ case EV_SWIM:
+ case EV_FALL_SHORT:
+ case EV_FALL_MEDIUM:
+ case EV_FALL_FAR:
+ case EV_STEP_4:
+ case EV_STEP_8:
+ case EV_STEP_12:
+ case EV_STEP_16:
+ case EV_JUMP_PAD:
+ case EV_JUMP:
+ case EV_TAUNT:
+ case EV_WATER_TOUCH:
+ case EV_WATER_LEAVE:
+ case EV_WATER_UNDER:
+ case EV_WATER_CLEAR:
+ case EV_ITEM_PICKUP:
+ case EV_GLOBAL_ITEM_PICKUP:
+ case EV_NOAMMO:
+ case EV_CHANGE_WEAPON:
+ case EV_FIRE_WEAPON:
+ //FIXME: either add to sound queue or mark player as someone making noise
+ break;
+ case EV_USE_ITEM0:
+ case EV_USE_ITEM1:
+ case EV_USE_ITEM2:
+ case EV_USE_ITEM3:
+ case EV_USE_ITEM4:
+ case EV_USE_ITEM5:
+ case EV_USE_ITEM6:
+ case EV_USE_ITEM7:
+ case EV_USE_ITEM8:
+ case EV_USE_ITEM9:
+ case EV_USE_ITEM10:
+ case EV_USE_ITEM11:
+ case EV_USE_ITEM12:
+ case EV_USE_ITEM13:
+ case EV_USE_ITEM14:
+ break;
+ }
+}
+
+/*
+==================
+BotCheckSnapshot
+==================
+*/
+void BotCheckSnapshot(bot_state_t *bs) {
+ int ent;
+ entityState_t state;
+
+ //remove all avoid spots
+ trap_BotAddAvoidSpot(bs->ms, vec3_origin, 0, AVOID_CLEAR);
+ //reset kamikaze body
+ bs->kamikazebody = 0;
+ //reset number of proxmines
+ bs->numproxmines = 0;
+ //
+ ent = 0;
+ while( ( ent = BotAI_GetSnapshotEntity( bs->client, ent, &state ) ) != -1 ) {
+ //check the entity state for events
+ BotCheckEvents(bs, &state);
+ //check for grenades the bot should avoid
+ BotCheckForGrenades(bs, &state);
+ //
+#ifdef MISSIONPACK
+ //check for proximity mines which the bot should deactivate
+ BotCheckForProxMines(bs, &state);
+ //check for dead bodies with the kamikaze effect which should be gibbed
+ BotCheckForKamikazeBody(bs, &state);
+#endif
+ }
+ //check the player state for events
+ BotAI_GetEntityState(bs->client, &state);
+ //copy the player state events to the entity state
+ state.event = bs->cur_ps.externalEvent;
+ state.eventParm = bs->cur_ps.externalEventParm;
+ //
+ BotCheckEvents(bs, &state);
+}
+
+/*
+==================
+BotCheckAir
+==================
+*/
+void BotCheckAir(bot_state_t *bs) {
+ if (bs->inventory[INVENTORY_ENVIRONMENTSUIT] <= 0) {
+ if (trap_AAS_PointContents(bs->eye) & (CONTENTS_WATER|CONTENTS_SLIME|CONTENTS_LAVA)) {
+ return;
+ }
+ }
+ bs->lastair_time = FloatTime();
+}
+
+/*
+==================
+BotAlternateRoute
+==================
+*/
+bot_goal_t *BotAlternateRoute(bot_state_t *bs, bot_goal_t *goal) {
+ int t;
+
+ // if the bot has an alternative route goal
+ if (bs->altroutegoal.areanum) {
+ //
+ if (bs->reachedaltroutegoal_time)
+ return goal;
+ // travel time towards alternative route goal
+ t = trap_AAS_AreaTravelTimeToGoalArea(bs->areanum, bs->origin, bs->altroutegoal.areanum, bs->tfl);
+ if (t && t < 20) {
+ //BotAI_Print(PRT_MESSAGE, "reached alternate route goal\n");
+ bs->reachedaltroutegoal_time = FloatTime();
+ }
+ memcpy(goal, &bs->altroutegoal, sizeof(bot_goal_t));
+ return &bs->altroutegoal;
+ }
+ return goal;
+}
+
+/*
+==================
+BotGetAlternateRouteGoal
+==================
+*/
+int BotGetAlternateRouteGoal(bot_state_t *bs, int base) {
+ aas_altroutegoal_t *altroutegoals;
+ bot_goal_t *goal;
+ int numaltroutegoals, rnd;
+
+ if (base == TEAM_RED) {
+ altroutegoals = red_altroutegoals;
+ numaltroutegoals = red_numaltroutegoals;
+ }
+ else {
+ altroutegoals = blue_altroutegoals;
+ numaltroutegoals = blue_numaltroutegoals;
+ }
+ if (!numaltroutegoals)
+ return qfalse;
+ rnd = (float) random() * numaltroutegoals;
+ if (rnd >= numaltroutegoals)
+ rnd = numaltroutegoals-1;
+ goal = &bs->altroutegoal;
+ goal->areanum = altroutegoals[rnd].areanum;
+ VectorCopy(altroutegoals[rnd].origin, goal->origin);
+ VectorSet(goal->mins, -8, -8, -8);
+ VectorSet(goal->maxs, 8, 8, 8);
+ goal->entitynum = 0;
+ goal->iteminfo = 0;
+ goal->number = 0;
+ goal->flags = 0;
+ //
+ bs->reachedaltroutegoal_time = 0;
+ return qtrue;
+}
+
+/*
+==================
+BotSetupAlternateRouteGoals
+==================
+*/
+void BotSetupAlternativeRouteGoals(void) {
+
+ if (altroutegoals_setup)
+ return;
+#ifdef MISSIONPACK
+ if (gametype == GT_CTF) {
+ if (trap_BotGetLevelItemGoal(-1, "Neutral Flag", &ctf_neutralflag) < 0)
+ BotAI_Print(PRT_WARNING, "no alt routes without Neutral Flag\n");
+ if (ctf_neutralflag.areanum) {
+ //
+ red_numaltroutegoals = trap_AAS_AlternativeRouteGoals(
+ ctf_neutralflag.origin, ctf_neutralflag.areanum,
+ ctf_redflag.origin, ctf_redflag.areanum, TFL_DEFAULT,
+ red_altroutegoals, MAX_ALTROUTEGOALS,
+ ALTROUTEGOAL_CLUSTERPORTALS|
+ ALTROUTEGOAL_VIEWPORTALS);
+ blue_numaltroutegoals = trap_AAS_AlternativeRouteGoals(
+ ctf_neutralflag.origin, ctf_neutralflag.areanum,
+ ctf_blueflag.origin, ctf_blueflag.areanum, TFL_DEFAULT,
+ blue_altroutegoals, MAX_ALTROUTEGOALS,
+ ALTROUTEGOAL_CLUSTERPORTALS|
+ ALTROUTEGOAL_VIEWPORTALS);
+ }
+ }
+ else if (gametype == GT_1FCTF) {
+ //
+ red_numaltroutegoals = trap_AAS_AlternativeRouteGoals(
+ ctf_neutralflag.origin, ctf_neutralflag.areanum,
+ ctf_redflag.origin, ctf_redflag.areanum, TFL_DEFAULT,
+ red_altroutegoals, MAX_ALTROUTEGOALS,
+ ALTROUTEGOAL_CLUSTERPORTALS|
+ ALTROUTEGOAL_VIEWPORTALS);
+ blue_numaltroutegoals = trap_AAS_AlternativeRouteGoals(
+ ctf_neutralflag.origin, ctf_neutralflag.areanum,
+ ctf_blueflag.origin, ctf_blueflag.areanum, TFL_DEFAULT,
+ blue_altroutegoals, MAX_ALTROUTEGOALS,
+ ALTROUTEGOAL_CLUSTERPORTALS|
+ ALTROUTEGOAL_VIEWPORTALS);
+ }
+ else if (gametype == GT_OBELISK) {
+ if (trap_BotGetLevelItemGoal(-1, "Neutral Obelisk", &neutralobelisk) < 0)
+ BotAI_Print(PRT_WARNING, "Harvester without neutral obelisk\n");
+ //
+ red_numaltroutegoals = trap_AAS_AlternativeRouteGoals(
+ neutralobelisk.origin, neutralobelisk.areanum,
+ redobelisk.origin, redobelisk.areanum, TFL_DEFAULT,
+ red_altroutegoals, MAX_ALTROUTEGOALS,
+ ALTROUTEGOAL_CLUSTERPORTALS|
+ ALTROUTEGOAL_VIEWPORTALS);
+ blue_numaltroutegoals = trap_AAS_AlternativeRouteGoals(
+ neutralobelisk.origin, neutralobelisk.areanum,
+ blueobelisk.origin, blueobelisk.areanum, TFL_DEFAULT,
+ blue_altroutegoals, MAX_ALTROUTEGOALS,
+ ALTROUTEGOAL_CLUSTERPORTALS|
+ ALTROUTEGOAL_VIEWPORTALS);
+ }
+ else if (gametype == GT_HARVESTER) {
+ //
+ red_numaltroutegoals = trap_AAS_AlternativeRouteGoals(
+ neutralobelisk.origin, neutralobelisk.areanum,
+ redobelisk.origin, redobelisk.areanum, TFL_DEFAULT,
+ red_altroutegoals, MAX_ALTROUTEGOALS,
+ ALTROUTEGOAL_CLUSTERPORTALS|
+ ALTROUTEGOAL_VIEWPORTALS);
+ blue_numaltroutegoals = trap_AAS_AlternativeRouteGoals(
+ neutralobelisk.origin, neutralobelisk.areanum,
+ blueobelisk.origin, blueobelisk.areanum, TFL_DEFAULT,
+ blue_altroutegoals, MAX_ALTROUTEGOALS,
+ ALTROUTEGOAL_CLUSTERPORTALS|
+ ALTROUTEGOAL_VIEWPORTALS);
+ }
+#endif
+ altroutegoals_setup = qtrue;
+}
+
+/*
+==================
+BotDeathmatchAI
+==================
+*/
+void BotDeathmatchAI(bot_state_t *bs, float thinktime) {
+ char gender[144], name[144], buf[144];
+ char userinfo[MAX_INFO_STRING];
+ int i;
+
+ //if the bot has just been setup
+ if (bs->setupcount > 0) {
+ bs->setupcount--;
+ if (bs->setupcount > 0) return;
+ //get the gender characteristic
+ trap_Characteristic_String(bs->character, CHARACTERISTIC_GENDER, gender, sizeof(gender));
+ //set the bot gender
+ trap_GetUserinfo(bs->client, userinfo, sizeof(userinfo));
+ Info_SetValueForKey(userinfo, "sex", gender);
+ trap_SetUserinfo(bs->client, userinfo);
+ //set the team
+ if ( !bs->map_restart && g_gametype.integer != GT_TOURNAMENT ) {
+ Com_sprintf(buf, sizeof(buf), "team %s", bs->settings.team);
+ trap_EA_Command(bs->client, buf);
+ }
+ //set the chat gender
+ if (gender[0] == 'm') trap_BotSetChatGender(bs->cs, CHAT_GENDERMALE);
+ else if (gender[0] == 'f') trap_BotSetChatGender(bs->cs, CHAT_GENDERFEMALE);
+ else trap_BotSetChatGender(bs->cs, CHAT_GENDERLESS);
+ //set the chat name
+ ClientName(bs->client, name, sizeof(name));
+ trap_BotSetChatName(bs->cs, name, bs->client);
+ //
+ bs->lastframe_health = bs->inventory[INVENTORY_HEALTH];
+ bs->lasthitcount = bs->cur_ps.persistant[PERS_HITS];
+ //
+ bs->setupcount = 0;
+ //
+ BotSetupAlternativeRouteGoals();
+ }
+ //no ideal view set
+ bs->flags &= ~BFL_IDEALVIEWSET;
+ //
+ if (!BotIntermission(bs)) {
+ //set the teleport time
+ BotSetTeleportTime(bs);
+ //update some inventory values
+ BotUpdateInventory(bs);
+ //check out the snapshot
+ BotCheckSnapshot(bs);
+ //check for air
+ BotCheckAir(bs);
+ }
+ //check the console messages
+ BotCheckConsoleMessages(bs);
+ //if not in the intermission and not in observer mode
+ if (!BotIntermission(bs) && !BotIsObserver(bs)) {
+ //do team AI
+ BotTeamAI(bs);
+ }
+ //if the bot has no ai node
+ if (!bs->ainode) {
+ AIEnter_Seek_LTG(bs, "BotDeathmatchAI: no ai node");
+ }
+ //if the bot entered the game less than 8 seconds ago
+ if (!bs->entergamechat && bs->entergame_time > FloatTime() - 8) {
+ if (BotChat_EnterGame(bs)) {
+ bs->stand_time = FloatTime() + BotChatTime(bs);
+ AIEnter_Stand(bs, "BotDeathmatchAI: chat enter game");
+ }
+ bs->entergamechat = qtrue;
+ }
+ //reset the node switches from the previous frame
+ BotResetNodeSwitches();
+ //execute AI nodes
+ for (i = 0; i < MAX_NODESWITCHES; i++) {
+ if (bs->ainode(bs)) break;
+ }
+ //if the bot removed itself :)
+ if (!bs->inuse) return;
+ //if the bot executed too many AI nodes
+ if (i >= MAX_NODESWITCHES) {
+ trap_BotDumpGoalStack(bs->gs);
+ trap_BotDumpAvoidGoals(bs->gs);
+ BotDumpNodeSwitches(bs);
+ ClientName(bs->client, name, sizeof(name));
+ BotAI_Print(PRT_ERROR, "%s at %1.1f switched more than %d AI nodes\n", name, FloatTime(), MAX_NODESWITCHES);
+ }
+ //
+ bs->lastframe_health = bs->inventory[INVENTORY_HEALTH];
+ bs->lasthitcount = bs->cur_ps.persistant[PERS_HITS];
+}
+
+/*
+==================
+BotSetEntityNumForGoalWithModel
+==================
+*/
+void BotSetEntityNumForGoalWithModel(bot_goal_t *goal, int eType, char *modelname) {
+ gentity_t *ent;
+ int i, modelindex;
+ vec3_t dir;
+
+ modelindex = G_ModelIndex( modelname );
+ ent = &g_entities[0];
+ for (i = 0; i < level.num_entities; i++, ent++) {
+ if ( !ent->inuse ) {
+ continue;
+ }
+ if ( eType && ent->s.eType != eType) {
+ continue;
+ }
+ if (ent->s.modelindex != modelindex) {
+ continue;
+ }
+ VectorSubtract(goal->origin, ent->s.origin, dir);
+ if (VectorLengthSquared(dir) < Square(10)) {
+ goal->entitynum = i;
+ return;
+ }
+ }
+}
+
+/*
+==================
+BotSetEntityNumForGoal
+==================
+*/
+void BotSetEntityNumForGoal(bot_goal_t *goal, char *classname) {
+ gentity_t *ent;
+ int i;
+ vec3_t dir;
+
+ ent = &g_entities[0];
+ for (i = 0; i < level.num_entities; i++, ent++) {
+ if ( !ent->inuse ) {
+ continue;
+ }
+ if ( !Q_stricmp(ent->classname, classname) ) {
+ continue;
+ }
+ VectorSubtract(goal->origin, ent->s.origin, dir);
+ if (VectorLengthSquared(dir) < Square(10)) {
+ goal->entitynum = i;
+ return;
+ }
+ }
+}
+
+/*
+==================
+BotGoalForBSPEntity
+==================
+*/
+int BotGoalForBSPEntity( char *classname, bot_goal_t *goal ) {
+ char value[MAX_INFO_STRING];
+ vec3_t origin, start, end;
+ int ent, numareas, areas[10];
+
+ memset(goal, 0, sizeof(bot_goal_t));
+ for (ent = trap_AAS_NextBSPEntity(0); ent; ent = trap_AAS_NextBSPEntity(ent)) {
+ if (!trap_AAS_ValueForBSPEpairKey(ent, "classname", value, sizeof(value)))
+ continue;
+ if (!strcmp(value, classname)) {
+ if (!trap_AAS_VectorForBSPEpairKey(ent, "origin", origin))
+ return qfalse;
+ VectorCopy(origin, goal->origin);
+ VectorCopy(origin, start);
+ start[2] -= 32;
+ VectorCopy(origin, end);
+ end[2] += 32;
+ numareas = trap_AAS_TraceAreas(start, end, areas, NULL, 10);
+ if (!numareas)
+ return qfalse;
+ goal->areanum = areas[0];
+ return qtrue;
+ }
+ }
+ return qfalse;
+}
+
+/*
+==================
+BotSetupDeathmatchAI
+==================
+*/
+void BotSetupDeathmatchAI(void) {
+ int ent, modelnum;
+ char model[128];
+
+ gametype = trap_Cvar_VariableIntegerValue("g_gametype");
+ maxclients = trap_Cvar_VariableIntegerValue("sv_maxclients");
+
+ trap_Cvar_Register(&bot_rocketjump, "bot_rocketjump", "1", 0);
+ trap_Cvar_Register(&bot_grapple, "bot_grapple", "0", 0);
+ trap_Cvar_Register(&bot_fastchat, "bot_fastchat", "0", 0);
+ trap_Cvar_Register(&bot_nochat, "bot_nochat", "0", 0);
+ trap_Cvar_Register(&bot_testrchat, "bot_testrchat", "0", 0);
+ trap_Cvar_Register(&bot_challenge, "bot_challenge", "0", 0);
+ trap_Cvar_Register(&bot_predictobstacles, "bot_predictobstacles", "1", 0);
+ trap_Cvar_Register(&g_spSkill, "g_spSkill", "2", 0);
+ //
+ if (gametype == GT_CTF) {
+ if (trap_BotGetLevelItemGoal(-1, "Red Flag", &ctf_redflag) < 0)
+ BotAI_Print(PRT_WARNING, "CTF without Red Flag\n");
+ if (trap_BotGetLevelItemGoal(-1, "Blue Flag", &ctf_blueflag) < 0)
+ BotAI_Print(PRT_WARNING, "CTF without Blue Flag\n");
+ }
+#ifdef MISSIONPACK
+ else if (gametype == GT_1FCTF) {
+ if (trap_BotGetLevelItemGoal(-1, "Neutral Flag", &ctf_neutralflag) < 0)
+ BotAI_Print(PRT_WARNING, "One Flag CTF without Neutral Flag\n");
+ if (trap_BotGetLevelItemGoal(-1, "Red Flag", &ctf_redflag) < 0)
+ BotAI_Print(PRT_WARNING, "CTF without Red Flag\n");
+ if (trap_BotGetLevelItemGoal(-1, "Blue Flag", &ctf_blueflag) < 0)
+ BotAI_Print(PRT_WARNING, "CTF without Blue Flag\n");
+ }
+ else if (gametype == GT_OBELISK) {
+ if (trap_BotGetLevelItemGoal(-1, "Red Obelisk", &redobelisk) < 0)
+ BotAI_Print(PRT_WARNING, "Obelisk without red obelisk\n");
+ BotSetEntityNumForGoal(&redobelisk, "team_redobelisk");
+ if (trap_BotGetLevelItemGoal(-1, "Blue Obelisk", &blueobelisk) < 0)
+ BotAI_Print(PRT_WARNING, "Obelisk without blue obelisk\n");
+ BotSetEntityNumForGoal(&blueobelisk, "team_blueobelisk");
+ }
+ else if (gametype == GT_HARVESTER) {
+ if (trap_BotGetLevelItemGoal(-1, "Red Obelisk", &redobelisk) < 0)
+ BotAI_Print(PRT_WARNING, "Harvester without red obelisk\n");
+ BotSetEntityNumForGoal(&redobelisk, "team_redobelisk");
+ if (trap_BotGetLevelItemGoal(-1, "Blue Obelisk", &blueobelisk) < 0)
+ BotAI_Print(PRT_WARNING, "Harvester without blue obelisk\n");
+ BotSetEntityNumForGoal(&blueobelisk, "team_blueobelisk");
+ if (trap_BotGetLevelItemGoal(-1, "Neutral Obelisk", &neutralobelisk) < 0)
+ BotAI_Print(PRT_WARNING, "Harvester without neutral obelisk\n");
+ BotSetEntityNumForGoal(&neutralobelisk, "team_neutralobelisk");
+ }
+#endif
+
+ max_bspmodelindex = 0;
+ for (ent = trap_AAS_NextBSPEntity(0); ent; ent = trap_AAS_NextBSPEntity(ent)) {
+ if (!trap_AAS_ValueForBSPEpairKey(ent, "model", model, sizeof(model))) continue;
+ if (model[0] == '*') {
+ modelnum = atoi(model+1);
+ if (modelnum > max_bspmodelindex)
+ max_bspmodelindex = modelnum;
+ }
+ }
+ //initialize the waypoint heap
+ BotInitWaypoints();
+}
+
+/*
+==================
+BotShutdownDeathmatchAI
+==================
+*/
+void BotShutdownDeathmatchAI(void) {
+ altroutegoals_setup = qfalse;
+}
diff --git a/code/game/ai_dmq3.h b/code/game/ai_dmq3.h
new file mode 100755
index 0000000..b7ab19d
--- /dev/null
+++ b/code/game/ai_dmq3.h
@@ -0,0 +1,206 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+/*****************************************************************************
+ * name: ai_dmq3.h
+ *
+ * desc: Quake3 bot AI
+ *
+ * $Archive: /source/code/botai/ai_chat.c $
+ *
+ *****************************************************************************/
+
+//setup the deathmatch AI
+void BotSetupDeathmatchAI(void);
+//shutdown the deathmatch AI
+void BotShutdownDeathmatchAI(void);
+//let the bot live within it's deathmatch AI net
+void BotDeathmatchAI(bot_state_t *bs, float thinktime);
+//free waypoints
+void BotFreeWaypoints(bot_waypoint_t *wp);
+//choose a weapon
+void BotChooseWeapon(bot_state_t *bs);
+//setup movement stuff
+void BotSetupForMovement(bot_state_t *bs);
+//update the inventory
+void BotUpdateInventory(bot_state_t *bs);
+//update the inventory during battle
+void BotUpdateBattleInventory(bot_state_t *bs, int enemy);
+//use holdable items during battle
+void BotBattleUseItems(bot_state_t *bs);
+//return true if the bot is dead
+qboolean BotIsDead(bot_state_t *bs);
+//returns true if the bot is in observer mode
+qboolean BotIsObserver(bot_state_t *bs);
+//returns true if the bot is in the intermission
+qboolean BotIntermission(bot_state_t *bs);
+//returns true if the bot is in lava or slime
+qboolean BotInLavaOrSlime(bot_state_t *bs);
+//returns true if the entity is dead
+qboolean EntityIsDead(aas_entityinfo_t *entinfo);
+//returns true if the entity is invisible
+qboolean EntityIsInvisible(aas_entityinfo_t *entinfo);
+//returns true if the entity is shooting
+qboolean EntityIsShooting(aas_entityinfo_t *entinfo);
+#ifdef MISSIONPACK
+//returns true if this entity has the kamikaze
+qboolean EntityHasKamikaze(aas_entityinfo_t *entinfo);
+#endif
+// set a user info key/value pair
+void BotSetUserInfo(bot_state_t *bs, char *key, char *value);
+// set the team status (offense, defense etc.)
+void BotSetTeamStatus(bot_state_t *bs);
+//returns the name of the client
+char *ClientName(int client, char *name, int size);
+//returns an simplyfied client name
+char *EasyClientName(int client, char *name, int size);
+//returns the skin used by the client
+char *ClientSkin(int client, char *skin, int size);
+// returns the appropriate synonym context for the current game type and situation
+int BotSynonymContext(bot_state_t *bs);
+// set last ordered task
+int BotSetLastOrderedTask(bot_state_t *bs);
+// selection of goals for teamplay
+void BotTeamGoals(bot_state_t *bs, int retreat);
+//returns the aggression of the bot in the range [0, 100]
+float BotAggression(bot_state_t *bs);
+//returns how bad the bot feels
+float BotFeelingBad(bot_state_t *bs);
+//returns true if the bot wants to retreat
+int BotWantsToRetreat(bot_state_t *bs);
+//returns true if the bot wants to chase
+int BotWantsToChase(bot_state_t *bs);
+//returns true if the bot wants to help
+int BotWantsToHelp(bot_state_t *bs);
+//returns true if the bot can and wants to rocketjump
+int BotCanAndWantsToRocketJump(bot_state_t *bs);
+// returns true if the bot has a persistant powerup and a weapon
+int BotHasPersistantPowerupAndWeapon(bot_state_t *bs);
+//returns true if the bot wants to and goes camping
+int BotWantsToCamp(bot_state_t *bs);
+//the bot will perform attack movements
+bot_moveresult_t BotAttackMove(bot_state_t *bs, int tfl);
+//returns true if the bot and the entity are in the same team
+int BotSameTeam(bot_state_t *bs, int entnum);
+//returns true if teamplay is on
+int TeamPlayIsOn(void);
+// returns the client number of the team mate flag carrier (-1 if none)
+int BotTeamFlagCarrier(bot_state_t *bs);
+//returns visible team mate flag carrier if available
+int BotTeamFlagCarrierVisible(bot_state_t *bs);
+//returns visible enemy flag carrier if available
+int BotEnemyFlagCarrierVisible(bot_state_t *bs);
+//get the number of visible teammates and enemies
+void BotVisibleTeamMatesAndEnemies(bot_state_t *bs, int *teammates, int *enemies, float range);
+//returns true if within the field of vision for the given angles
+qboolean InFieldOfVision(vec3_t viewangles, float fov, vec3_t angles);
+//returns true and sets the .enemy field when an enemy is found
+int BotFindEnemy(bot_state_t *bs, int curenemy);
+//returns a roam goal
+void BotRoamGoal(bot_state_t *bs, vec3_t goal);
+//returns entity visibility in the range [0, 1]
+float BotEntityVisible(int viewer, vec3_t eye, vec3_t viewangles, float fov, int ent);
+//the bot will aim at the current enemy
+void BotAimAtEnemy(bot_state_t *bs);
+//check if the bot should attack
+void BotCheckAttack(bot_state_t *bs);
+//AI when the bot is blocked
+void BotAIBlocked(bot_state_t *bs, bot_moveresult_t *moveresult, int activate);
+//AI to predict obstacles
+int BotAIPredictObstacles(bot_state_t *bs, bot_goal_t *goal);
+//enable or disable the areas the blocking entity is in
+void BotEnableActivateGoalAreas(bot_activategoal_t *activategoal, int enable);
+//pop an activate goal from the stack
+int BotPopFromActivateGoalStack(bot_state_t *bs);
+//clear the activate goal stack
+void BotClearActivateGoalStack(bot_state_t *bs);
+//returns the team the bot is in
+int BotTeam(bot_state_t *bs);
+//retuns the opposite team of the bot
+int BotOppositeTeam(bot_state_t *bs);
+//returns the flag the bot is carrying (CTFFLAG_?)
+int BotCTFCarryingFlag(bot_state_t *bs);
+//remember the last ordered task
+void BotRememberLastOrderedTask(bot_state_t *bs);
+//set ctf goals (defend base, get enemy flag) during seek
+void BotCTFSeekGoals(bot_state_t *bs);
+//set ctf goals (defend base, get enemy flag) during retreat
+void BotCTFRetreatGoals(bot_state_t *bs);
+//
+#ifdef MISSIONPACK
+int Bot1FCTFCarryingFlag(bot_state_t *bs);
+int BotHarvesterCarryingCubes(bot_state_t *bs);
+void Bot1FCTFSeekGoals(bot_state_t *bs);
+void Bot1FCTFRetreatGoals(bot_state_t *bs);
+void BotObeliskSeekGoals(bot_state_t *bs);
+void BotObeliskRetreatGoals(bot_state_t *bs);
+void BotGoHarvest(bot_state_t *bs);
+void BotHarvesterSeekGoals(bot_state_t *bs);
+void BotHarvesterRetreatGoals(bot_state_t *bs);
+int BotTeamCubeCarrierVisible(bot_state_t *bs);
+int BotEnemyCubeCarrierVisible(bot_state_t *bs);
+#endif
+//get a random alternate route goal towards the given base
+int BotGetAlternateRouteGoal(bot_state_t *bs, int base);
+//returns either the alternate route goal or the given goal
+bot_goal_t *BotAlternateRoute(bot_state_t *bs, bot_goal_t *goal);
+//create a new waypoint
+bot_waypoint_t *BotCreateWayPoint(char *name, vec3_t origin, int areanum);
+//find a waypoint with the given name
+bot_waypoint_t *BotFindWayPoint(bot_waypoint_t *waypoints, char *name);
+//strstr but case insensitive
+char *stristr(char *str, char *charset);
+//returns the number of the client with the given name
+int ClientFromName(char *name);
+int ClientOnSameTeamFromName(bot_state_t *bs, char *name);
+//
+int BotPointAreaNum(vec3_t origin);
+//
+void BotMapScripts(bot_state_t *bs);
+
+//ctf flags
+#define CTF_FLAG_NONE 0
+#define CTF_FLAG_RED 1
+#define CTF_FLAG_BLUE 2
+//CTF skins
+#define CTF_SKIN_REDTEAM "red"
+#define CTF_SKIN_BLUETEAM "blue"
+
+extern int gametype; //game type
+extern int maxclients; //maximum number of clients
+
+extern vmCvar_t bot_grapple;
+extern vmCvar_t bot_rocketjump;
+extern vmCvar_t bot_fastchat;
+extern vmCvar_t bot_nochat;
+extern vmCvar_t bot_testrchat;
+extern vmCvar_t bot_challenge;
+
+extern bot_goal_t ctf_redflag;
+extern bot_goal_t ctf_blueflag;
+#ifdef MISSIONPACK
+extern bot_goal_t ctf_neutralflag;
+extern bot_goal_t redobelisk;
+extern bot_goal_t blueobelisk;
+extern bot_goal_t neutralobelisk;
+#endif
diff --git a/code/game/ai_main.c b/code/game/ai_main.c
new file mode 100755
index 0000000..d13696a
--- /dev/null
+++ b/code/game/ai_main.c
@@ -0,0 +1,1695 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+/*****************************************************************************
+ * name: ai_main.c
+ *
+ * desc: Quake3 bot AI
+ *
+ * $Archive: /MissionPack/code/game/ai_main.c $
+ *
+ *****************************************************************************/
+
+
+#include "g_local.h"
+#include "q_shared.h"
+#include "botlib.h" //bot lib interface
+#include "be_aas.h"
+#include "be_ea.h"
+#include "be_ai_char.h"
+#include "be_ai_chat.h"
+#include "be_ai_gen.h"
+#include "be_ai_goal.h"
+#include "be_ai_move.h"
+#include "be_ai_weap.h"
+//
+#include "ai_main.h"
+#include "ai_dmq3.h"
+#include "ai_chat.h"
+#include "ai_cmd.h"
+#include "ai_dmnet.h"
+#include "ai_vcmd.h"
+
+//
+#include "chars.h"
+#include "inv.h"
+#include "syn.h"
+
+#define MAX_PATH 144
+
+
+//bot states
+bot_state_t *botstates[MAX_CLIENTS];
+//number of bots
+int numbots;
+//floating point time
+float floattime;
+//time to do a regular update
+float regularupdate_time;
+//
+int bot_interbreed;
+int bot_interbreedmatchcount;
+//
+vmCvar_t bot_thinktime;
+vmCvar_t bot_memorydump;
+vmCvar_t bot_saveroutingcache;
+vmCvar_t bot_pause;
+vmCvar_t bot_report;
+vmCvar_t bot_testsolid;
+vmCvar_t bot_testclusters;
+vmCvar_t bot_developer;
+vmCvar_t bot_interbreedchar;
+vmCvar_t bot_interbreedbots;
+vmCvar_t bot_interbreedcycle;
+vmCvar_t bot_interbreedwrite;
+
+
+void ExitLevel( void );
+
+
+/*
+==================
+BotAI_Print
+==================
+*/
+void QDECL BotAI_Print(int type, char *fmt, ...) {
+ char str[2048];
+ va_list ap;
+
+ va_start(ap, fmt);
+ vsprintf(str, fmt, ap);
+ va_end(ap);
+
+ switch(type) {
+ case PRT_MESSAGE: {
+ G_Printf("%s", str);
+ break;
+ }
+ case PRT_WARNING: {
+ G_Printf( S_COLOR_YELLOW "Warning: %s", str );
+ break;
+ }
+ case PRT_ERROR: {
+ G_Printf( S_COLOR_RED "Error: %s", str );
+ break;
+ }
+ case PRT_FATAL: {
+ G_Printf( S_COLOR_RED "Fatal: %s", str );
+ break;
+ }
+ case PRT_EXIT: {
+ G_Error( S_COLOR_RED "Exit: %s", str );
+ break;
+ }
+ default: {
+ G_Printf( "unknown print type\n" );
+ break;
+ }
+ }
+}
+
+
+/*
+==================
+BotAI_Trace
+==================
+*/
+void BotAI_Trace(bsp_trace_t *bsptrace, vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int passent, int contentmask) {
+ trace_t trace;
+
+ trap_Trace(&trace, start, mins, maxs, end, passent, contentmask);
+ //copy the trace information
+ bsptrace->allsolid = trace.allsolid;
+ bsptrace->startsolid = trace.startsolid;
+ bsptrace->fraction = trace.fraction;
+ VectorCopy(trace.endpos, bsptrace->endpos);
+ bsptrace->plane.dist = trace.plane.dist;
+ VectorCopy(trace.plane.normal, bsptrace->plane.normal);
+ bsptrace->plane.signbits = trace.plane.signbits;
+ bsptrace->plane.type = trace.plane.type;
+ bsptrace->surface.value = trace.surfaceFlags;
+ bsptrace->ent = trace.entityNum;
+ bsptrace->exp_dist = 0;
+ bsptrace->sidenum = 0;
+ bsptrace->contents = 0;
+}
+
+/*
+==================
+BotAI_GetClientState
+==================
+*/
+int BotAI_GetClientState( int clientNum, playerState_t *state ) {
+ gentity_t *ent;
+
+ ent = &g_entities[clientNum];
+ if ( !ent->inuse ) {
+ return qfalse;
+ }
+ if ( !ent->client ) {
+ return qfalse;
+ }
+
+ memcpy( state, &ent->client->ps, sizeof(playerState_t) );
+ return qtrue;
+}
+
+/*
+==================
+BotAI_GetEntityState
+==================
+*/
+int BotAI_GetEntityState( int entityNum, entityState_t *state ) {
+ gentity_t *ent;
+
+ ent = &g_entities[entityNum];
+ memset( state, 0, sizeof(entityState_t) );
+ if (!ent->inuse) return qfalse;
+ if (!ent->r.linked) return qfalse;
+ if (ent->r.svFlags & SVF_NOCLIENT) return qfalse;
+ memcpy( state, &ent->s, sizeof(entityState_t) );
+ return qtrue;
+}
+
+/*
+==================
+BotAI_GetSnapshotEntity
+==================
+*/
+int BotAI_GetSnapshotEntity( int clientNum, int sequence, entityState_t *state ) {
+ int entNum;
+
+ entNum = trap_BotGetSnapshotEntity( clientNum, sequence );
+ if ( entNum == -1 ) {
+ memset(state, 0, sizeof(entityState_t));
+ return -1;
+ }
+
+ BotAI_GetEntityState( entNum, state );
+
+ return sequence + 1;
+}
+
+/*
+==================
+BotAI_BotInitialChat
+==================
+*/
+void QDECL BotAI_BotInitialChat( bot_state_t *bs, char *type, ... ) {
+ int i, mcontext;
+ va_list ap;
+ char *p;
+ char *vars[MAX_MATCHVARIABLES];
+
+ memset(vars, 0, sizeof(vars));
+ va_start(ap, type);
+ p = va_arg(ap, char *);
+ for (i = 0; i < MAX_MATCHVARIABLES; i++) {
+ if( !p ) {
+ break;
+ }
+ vars[i] = p;
+ p = va_arg(ap, char *);
+ }
+ va_end(ap);
+
+ mcontext = BotSynonymContext(bs);
+
+ trap_BotInitialChat( bs->cs, type, mcontext, vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7] );
+}
+
+
+/*
+==================
+BotTestAAS
+==================
+*/
+void BotTestAAS(vec3_t origin) {
+ int areanum;
+ aas_areainfo_t info;
+
+ trap_Cvar_Update(&bot_testsolid);
+ trap_Cvar_Update(&bot_testclusters);
+ if (bot_testsolid.integer) {
+ if (!trap_AAS_Initialized()) return;
+ areanum = BotPointAreaNum(origin);
+ if (areanum) BotAI_Print(PRT_MESSAGE, "\remtpy area");
+ else BotAI_Print(PRT_MESSAGE, "\r^1SOLID area");
+ }
+ else if (bot_testclusters.integer) {
+ if (!trap_AAS_Initialized()) return;
+ areanum = BotPointAreaNum(origin);
+ if (!areanum)
+ BotAI_Print(PRT_MESSAGE, "\r^1Solid! ");
+ else {
+ trap_AAS_AreaInfo(areanum, &info);
+ BotAI_Print(PRT_MESSAGE, "\rarea %d, cluster %d ", areanum, info.cluster);
+ }
+ }
+}
+
+/*
+==================
+BotReportStatus
+==================
+*/
+void BotReportStatus(bot_state_t *bs) {
+ char goalname[MAX_MESSAGE_SIZE];
+ char netname[MAX_MESSAGE_SIZE];
+ char *leader, flagstatus[32];
+ //
+ ClientName(bs->client, netname, sizeof(netname));
+ if (Q_stricmp(netname, bs->teamleader) == 0) leader = "L";
+ else leader = " ";
+
+ strcpy(flagstatus, " ");
+ if (gametype == GT_CTF) {
+ if (BotCTFCarryingFlag(bs)) {
+ if (BotTeam(bs) == TEAM_RED) strcpy(flagstatus, S_COLOR_RED"F ");
+ else strcpy(flagstatus, S_COLOR_BLUE"F ");
+ }
+ }
+#ifdef MISSIONPACK
+ else if (gametype == GT_1FCTF) {
+ if (Bot1FCTFCarryingFlag(bs)) {
+ if (BotTeam(bs) == TEAM_RED) strcpy(flagstatus, S_COLOR_RED"F ");
+ else strcpy(flagstatus, S_COLOR_BLUE"F ");
+ }
+ }
+ else if (gametype == GT_HARVESTER) {
+ if (BotHarvesterCarryingCubes(bs)) {
+ if (BotTeam(bs) == TEAM_RED) Com_sprintf(flagstatus, sizeof(flagstatus), S_COLOR_RED"%2d", bs->inventory[INVENTORY_REDCUBE]);
+ else Com_sprintf(flagstatus, sizeof(flagstatus), S_COLOR_BLUE"%2d", bs->inventory[INVENTORY_BLUECUBE]);
+ }
+ }
+#endif
+
+ switch(bs->ltgtype) {
+ case LTG_TEAMHELP:
+ {
+ EasyClientName(bs->teammate, goalname, sizeof(goalname));
+ BotAI_Print(PRT_MESSAGE, "%-20s%s%s: helping %s\n", netname, leader, flagstatus, goalname);
+ break;
+ }
+ case LTG_TEAMACCOMPANY:
+ {
+ EasyClientName(bs->teammate, goalname, sizeof(goalname));
+ BotAI_Print(PRT_MESSAGE, "%-20s%s%s: accompanying %s\n", netname, leader, flagstatus, goalname);
+ break;
+ }
+ case LTG_DEFENDKEYAREA:
+ {
+ trap_BotGoalName(bs->teamgoal.number, goalname, sizeof(goalname));
+ BotAI_Print(PRT_MESSAGE, "%-20s%s%s: defending %s\n", netname, leader, flagstatus, goalname);
+ break;
+ }
+ case LTG_GETITEM:
+ {
+ trap_BotGoalName(bs->teamgoal.number, goalname, sizeof(goalname));
+ BotAI_Print(PRT_MESSAGE, "%-20s%s%s: getting item %s\n", netname, leader, flagstatus, goalname);
+ break;
+ }
+ case LTG_KILL:
+ {
+ ClientName(bs->teamgoal.entitynum, goalname, sizeof(goalname));
+ BotAI_Print(PRT_MESSAGE, "%-20s%s%s: killing %s\n", netname, leader, flagstatus, goalname);
+ break;
+ }
+ case LTG_CAMP:
+ case LTG_CAMPORDER:
+ {
+ BotAI_Print(PRT_MESSAGE, "%-20s%s%s: camping\n", netname, leader, flagstatus);
+ break;
+ }
+ case LTG_PATROL:
+ {
+ BotAI_Print(PRT_MESSAGE, "%-20s%s%s: patrolling\n", netname, leader, flagstatus);
+ break;
+ }
+ case LTG_GETFLAG:
+ {
+ BotAI_Print(PRT_MESSAGE, "%-20s%s%s: capturing flag\n", netname, leader, flagstatus);
+ break;
+ }
+ case LTG_RUSHBASE:
+ {
+ BotAI_Print(PRT_MESSAGE, "%-20s%s%s: rushing base\n", netname, leader, flagstatus);
+ break;
+ }
+ case LTG_RETURNFLAG:
+ {
+ BotAI_Print(PRT_MESSAGE, "%-20s%s%s: returning flag\n", netname, leader, flagstatus);
+ break;
+ }
+ case LTG_ATTACKENEMYBASE:
+ {
+ BotAI_Print(PRT_MESSAGE, "%-20s%s%s: attacking the enemy base\n", netname, leader, flagstatus);
+ break;
+ }
+ case LTG_HARVEST:
+ {
+ BotAI_Print(PRT_MESSAGE, "%-20s%s%s: harvesting\n", netname, leader, flagstatus);
+ break;
+ }
+ default:
+ {
+ BotAI_Print(PRT_MESSAGE, "%-20s%s%s: roaming\n", netname, leader, flagstatus);
+ break;
+ }
+ }
+}
+
+/*
+==================
+BotTeamplayReport
+==================
+*/
+void BotTeamplayReport(void) {
+ int i;
+ char buf[MAX_INFO_STRING];
+
+ BotAI_Print(PRT_MESSAGE, S_COLOR_RED"RED\n");
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ //
+ if ( !botstates[i] || !botstates[i]->inuse ) continue;
+ //
+ trap_GetConfigstring(CS_PLAYERS+i, buf, sizeof(buf));
+ //if no config string or no name
+ if (!strlen(buf) || !strlen(Info_ValueForKey(buf, "n"))) continue;
+ //skip spectators
+ if (atoi(Info_ValueForKey(buf, "t")) == TEAM_RED) {
+ BotReportStatus(botstates[i]);
+ }
+ }
+ BotAI_Print(PRT_MESSAGE, S_COLOR_BLUE"BLUE\n");
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ //
+ if ( !botstates[i] || !botstates[i]->inuse ) continue;
+ //
+ trap_GetConfigstring(CS_PLAYERS+i, buf, sizeof(buf));
+ //if no config string or no name
+ if (!strlen(buf) || !strlen(Info_ValueForKey(buf, "n"))) continue;
+ //skip spectators
+ if (atoi(Info_ValueForKey(buf, "t")) == TEAM_BLUE) {
+ BotReportStatus(botstates[i]);
+ }
+ }
+}
+
+/*
+==================
+BotSetInfoConfigString
+==================
+*/
+void BotSetInfoConfigString(bot_state_t *bs) {
+ char goalname[MAX_MESSAGE_SIZE];
+ char netname[MAX_MESSAGE_SIZE];
+ char action[MAX_MESSAGE_SIZE];
+ char *leader, carrying[32], *cs;
+ bot_goal_t goal;
+ //
+ ClientName(bs->client, netname, sizeof(netname));
+ if (Q_stricmp(netname, bs->teamleader) == 0) leader = "L";
+ else leader = " ";
+
+ strcpy(carrying, " ");
+ if (gametype == GT_CTF) {
+ if (BotCTFCarryingFlag(bs)) {
+ strcpy(carrying, "F ");
+ }
+ }
+#ifdef MISSIONPACK
+ else if (gametype == GT_1FCTF) {
+ if (Bot1FCTFCarryingFlag(bs)) {
+ strcpy(carrying, "F ");
+ }
+ }
+ else if (gametype == GT_HARVESTER) {
+ if (BotHarvesterCarryingCubes(bs)) {
+ if (BotTeam(bs) == TEAM_RED) Com_sprintf(carrying, sizeof(carrying), "%2d", bs->inventory[INVENTORY_REDCUBE]);
+ else Com_sprintf(carrying, sizeof(carrying), "%2d", bs->inventory[INVENTORY_BLUECUBE]);
+ }
+ }
+#endif
+
+ switch(bs->ltgtype) {
+ case LTG_TEAMHELP:
+ {
+ EasyClientName(bs->teammate, goalname, sizeof(goalname));
+ Com_sprintf(action, sizeof(action), "helping %s", goalname);
+ break;
+ }
+ case LTG_TEAMACCOMPANY:
+ {
+ EasyClientName(bs->teammate, goalname, sizeof(goalname));
+ Com_sprintf(action, sizeof(action), "accompanying %s", goalname);
+ break;
+ }
+ case LTG_DEFENDKEYAREA:
+ {
+ trap_BotGoalName(bs->teamgoal.number, goalname, sizeof(goalname));
+ Com_sprintf(action, sizeof(action), "defending %s", goalname);
+ break;
+ }
+ case LTG_GETITEM:
+ {
+ trap_BotGoalName(bs->teamgoal.number, goalname, sizeof(goalname));
+ Com_sprintf(action, sizeof(action), "getting item %s", goalname);
+ break;
+ }
+ case LTG_KILL:
+ {
+ ClientName(bs->teamgoal.entitynum, goalname, sizeof(goalname));
+ Com_sprintf(action, sizeof(action), "killing %s", goalname);
+ break;
+ }
+ case LTG_CAMP:
+ case LTG_CAMPORDER:
+ {
+ Com_sprintf(action, sizeof(action), "camping");
+ break;
+ }
+ case LTG_PATROL:
+ {
+ Com_sprintf(action, sizeof(action), "patrolling");
+ break;
+ }
+ case LTG_GETFLAG:
+ {
+ Com_sprintf(action, sizeof(action), "capturing flag");
+ break;
+ }
+ case LTG_RUSHBASE:
+ {
+ Com_sprintf(action, sizeof(action), "rushing base");
+ break;
+ }
+ case LTG_RETURNFLAG:
+ {
+ Com_sprintf(action, sizeof(action), "returning flag");
+ break;
+ }
+ case LTG_ATTACKENEMYBASE:
+ {
+ Com_sprintf(action, sizeof(action), "attacking the enemy base");
+ break;
+ }
+ case LTG_HARVEST:
+ {
+ Com_sprintf(action, sizeof(action), "harvesting");
+ break;
+ }
+ default:
+ {
+ trap_BotGetTopGoal(bs->gs, &goal);
+ trap_BotGoalName(goal.number, goalname, sizeof(goalname));
+ Com_sprintf(action, sizeof(action), "roaming %s", goalname);
+ break;
+ }
+ }
+ cs = va("l\\%s\\c\\%s\\a\\%s",
+ leader,
+ carrying,
+ action);
+ trap_SetConfigstring (CS_BOTINFO + bs->client, cs);
+}
+
+/*
+==============
+BotUpdateInfoConfigStrings
+==============
+*/
+void BotUpdateInfoConfigStrings(void) {
+ int i;
+ char buf[MAX_INFO_STRING];
+
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ //
+ if ( !botstates[i] || !botstates[i]->inuse )
+ continue;
+ //
+ trap_GetConfigstring(CS_PLAYERS+i, buf, sizeof(buf));
+ //if no config string or no name
+ if (!strlen(buf) || !strlen(Info_ValueForKey(buf, "n")))
+ continue;
+ BotSetInfoConfigString(botstates[i]);
+ }
+}
+
+/*
+==============
+BotInterbreedBots
+==============
+*/
+void BotInterbreedBots(void) {
+ float ranks[MAX_CLIENTS];
+ int parent1, parent2, child;
+ int i;
+
+ // get rankings for all the bots
+ for (i = 0; i < MAX_CLIENTS; i++) {
+ if ( botstates[i] && botstates[i]->inuse ) {
+ ranks[i] = botstates[i]->num_kills * 2 - botstates[i]->num_deaths;
+ }
+ else {
+ ranks[i] = -1;
+ }
+ }
+
+ if (trap_GeneticParentsAndChildSelection(MAX_CLIENTS, ranks, &parent1, &parent2, &child)) {
+ trap_BotInterbreedGoalFuzzyLogic(botstates[parent1]->gs, botstates[parent2]->gs, botstates[child]->gs);
+ trap_BotMutateGoalFuzzyLogic(botstates[child]->gs, 1);
+ }
+ // reset the kills and deaths
+ for (i = 0; i < MAX_CLIENTS; i++) {
+ if (botstates[i] && botstates[i]->inuse) {
+ botstates[i]->num_kills = 0;
+ botstates[i]->num_deaths = 0;
+ }
+ }
+}
+
+/*
+==============
+BotWriteInterbreeded
+==============
+*/
+void BotWriteInterbreeded(char *filename) {
+ float rank, bestrank;
+ int i, bestbot;
+
+ bestrank = 0;
+ bestbot = -1;
+ // get the best bot
+ for (i = 0; i < MAX_CLIENTS; i++) {
+ if ( botstates[i] && botstates[i]->inuse ) {
+ rank = botstates[i]->num_kills * 2 - botstates[i]->num_deaths;
+ }
+ else {
+ rank = -1;
+ }
+ if (rank > bestrank) {
+ bestrank = rank;
+ bestbot = i;
+ }
+ }
+ if (bestbot >= 0) {
+ //write out the new goal fuzzy logic
+ trap_BotSaveGoalFuzzyLogic(botstates[bestbot]->gs, filename);
+ }
+}
+
+/*
+==============
+BotInterbreedEndMatch
+
+add link back into ExitLevel?
+==============
+*/
+void BotInterbreedEndMatch(void) {
+
+ if (!bot_interbreed) return;
+ bot_interbreedmatchcount++;
+ if (bot_interbreedmatchcount >= bot_interbreedcycle.integer) {
+ bot_interbreedmatchcount = 0;
+ //
+ trap_Cvar_Update(&bot_interbreedwrite);
+ if (strlen(bot_interbreedwrite.string)) {
+ BotWriteInterbreeded(bot_interbreedwrite.string);
+ trap_Cvar_Set("bot_interbreedwrite", "");
+ }
+ BotInterbreedBots();
+ }
+}
+
+/*
+==============
+BotInterbreeding
+==============
+*/
+void BotInterbreeding(void) {
+ int i;
+
+ trap_Cvar_Update(&bot_interbreedchar);
+ if (!strlen(bot_interbreedchar.string)) return;
+ //make sure we are in tournament mode
+ if (gametype != GT_TOURNAMENT) {
+ trap_Cvar_Set("g_gametype", va("%d", GT_TOURNAMENT));
+ ExitLevel();
+ return;
+ }
+ //shutdown all the bots
+ for (i = 0; i < MAX_CLIENTS; i++) {
+ if (botstates[i] && botstates[i]->inuse) {
+ BotAIShutdownClient(botstates[i]->client, qfalse);
+ }
+ }
+ //make sure all item weight configs are reloaded and Not shared
+ trap_BotLibVarSet("bot_reloadcharacters", "1");
+ //add a number of bots using the desired bot character
+ for (i = 0; i < bot_interbreedbots.integer; i++) {
+ trap_SendConsoleCommand( EXEC_INSERT, va("addbot %s 4 free %i %s%d\n",
+ bot_interbreedchar.string, i * 50, bot_interbreedchar.string, i) );
+ }
+ //
+ trap_Cvar_Set("bot_interbreedchar", "");
+ bot_interbreed = qtrue;
+}
+
+/*
+==============
+BotEntityInfo
+==============
+*/
+void BotEntityInfo(int entnum, aas_entityinfo_t *info) {
+ trap_AAS_EntityInfo(entnum, info);
+}
+
+/*
+==============
+NumBots
+==============
+*/
+int NumBots(void) {
+ return numbots;
+}
+
+/*
+==============
+BotTeamLeader
+==============
+*/
+int BotTeamLeader(bot_state_t *bs) {
+ int leader;
+
+ leader = ClientFromName(bs->teamleader);
+ if (leader < 0) return qfalse;
+ if (!botstates[leader] || !botstates[leader]->inuse) return qfalse;
+ return qtrue;
+}
+
+/*
+==============
+AngleDifference
+==============
+*/
+float AngleDifference(float ang1, float ang2) {
+ float diff;
+
+ diff = ang1 - ang2;
+ if (ang1 > ang2) {
+ if (diff > 180.0) diff -= 360.0;
+ }
+ else {
+ if (diff < -180.0) diff += 360.0;
+ }
+ return diff;
+}
+
+/*
+==============
+BotChangeViewAngle
+==============
+*/
+float BotChangeViewAngle(float angle, float ideal_angle, float speed) {
+ float move;
+
+ angle = AngleMod(angle);
+ ideal_angle = AngleMod(ideal_angle);
+ if (angle == ideal_angle) return angle;
+ move = ideal_angle - angle;
+ if (ideal_angle > angle) {
+ if (move > 180.0) move -= 360.0;
+ }
+ else {
+ if (move < -180.0) move += 360.0;
+ }
+ if (move > 0) {
+ if (move > speed) move = speed;
+ }
+ else {
+ if (move < -speed) move = -speed;
+ }
+ return AngleMod(angle + move);
+}
+
+/*
+==============
+BotChangeViewAngles
+==============
+*/
+void BotChangeViewAngles(bot_state_t *bs, float thinktime) {
+ float diff, factor, maxchange, anglespeed, disired_speed;
+ int i;
+
+ if (bs->ideal_viewangles[PITCH] > 180) bs->ideal_viewangles[PITCH] -= 360;
+ //
+ if (bs->enemy >= 0) {
+ factor = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_VIEW_FACTOR, 0.01f, 1);
+ maxchange = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_VIEW_MAXCHANGE, 1, 1800);
+ }
+ else {
+ factor = 0.05f;
+ maxchange = 360;
+ }
+ if (maxchange < 240) maxchange = 240;
+ maxchange *= thinktime;
+ for (i = 0; i < 2; i++) {
+ //
+ if (bot_challenge.integer) {
+ //smooth slowdown view model
+ diff = abs(AngleDifference(bs->viewangles[i], bs->ideal_viewangles[i]));
+ anglespeed = diff * factor;
+ if (anglespeed > maxchange) anglespeed = maxchange;
+ bs->viewangles[i] = BotChangeViewAngle(bs->viewangles[i],
+ bs->ideal_viewangles[i], anglespeed);
+ }
+ else {
+ //over reaction view model
+ bs->viewangles[i] = AngleMod(bs->viewangles[i]);
+ bs->ideal_viewangles[i] = AngleMod(bs->ideal_viewangles[i]);
+ diff = AngleDifference(bs->viewangles[i], bs->ideal_viewangles[i]);
+ disired_speed = diff * factor;
+ bs->viewanglespeed[i] += (bs->viewanglespeed[i] - disired_speed);
+ if (bs->viewanglespeed[i] > 180) bs->viewanglespeed[i] = maxchange;
+ if (bs->viewanglespeed[i] < -180) bs->viewanglespeed[i] = -maxchange;
+ anglespeed = bs->viewanglespeed[i];
+ if (anglespeed > maxchange) anglespeed = maxchange;
+ if (anglespeed < -maxchange) anglespeed = -maxchange;
+ bs->viewangles[i] += anglespeed;
+ bs->viewangles[i] = AngleMod(bs->viewangles[i]);
+ //demping
+ bs->viewanglespeed[i] *= 0.45 * (1 - factor);
+ }
+ //BotAI_Print(PRT_MESSAGE, "ideal_angles %f %f\n", bs->ideal_viewangles[0], bs->ideal_viewangles[1], bs->ideal_viewangles[2]);`
+ //bs->viewangles[i] = bs->ideal_viewangles[i];
+ }
+ //bs->viewangles[PITCH] = 0;
+ if (bs->viewangles[PITCH] > 180) bs->viewangles[PITCH] -= 360;
+ //elementary action: view
+ trap_EA_View(bs->client, bs->viewangles);
+}
+
+/*
+==============
+BotInputToUserCommand
+==============
+*/
+void BotInputToUserCommand(bot_input_t *bi, usercmd_t *ucmd, int delta_angles[3], int time) {
+ vec3_t angles, forward, right;
+ short temp;
+ int j;
+
+ //clear the whole structure
+ memset(ucmd, 0, sizeof(usercmd_t));
+ //
+ //Com_Printf("dir = %f %f %f speed = %f\n", bi->dir[0], bi->dir[1], bi->dir[2], bi->speed);
+ //the duration for the user command in milli seconds
+ ucmd->serverTime = time;
+ //
+ if (bi->actionflags & ACTION_DELAYEDJUMP) {
+ bi->actionflags |= ACTION_JUMP;
+ bi->actionflags &= ~ACTION_DELAYEDJUMP;
+ }
+ //set the buttons
+ if (bi->actionflags & ACTION_RESPAWN) ucmd->buttons = BUTTON_ATTACK;
+ if (bi->actionflags & ACTION_ATTACK) ucmd->buttons |= BUTTON_ATTACK;
+ if (bi->actionflags & ACTION_TALK) ucmd->buttons |= BUTTON_TALK;
+ if (bi->actionflags & ACTION_GESTURE) ucmd->buttons |= BUTTON_GESTURE;
+ if (bi->actionflags & ACTION_USE) ucmd->buttons |= BUTTON_USE_HOLDABLE;
+ if (bi->actionflags & ACTION_WALK) ucmd->buttons |= BUTTON_WALKING;
+ if (bi->actionflags & ACTION_AFFIRMATIVE) ucmd->buttons |= BUTTON_AFFIRMATIVE;
+ if (bi->actionflags & ACTION_NEGATIVE) ucmd->buttons |= BUTTON_NEGATIVE;
+ if (bi->actionflags & ACTION_GETFLAG) ucmd->buttons |= BUTTON_GETFLAG;
+ if (bi->actionflags & ACTION_GUARDBASE) ucmd->buttons |= BUTTON_GUARDBASE;
+ if (bi->actionflags & ACTION_PATROL) ucmd->buttons |= BUTTON_PATROL;
+ if (bi->actionflags & ACTION_FOLLOWME) ucmd->buttons |= BUTTON_FOLLOWME;
+ //
+ ucmd->weapon = bi->weapon;
+ //set the view angles
+ //NOTE: the ucmd->angles are the angles WITHOUT the delta angles
+ ucmd->angles[PITCH] = ANGLE2SHORT(bi->viewangles[PITCH]);
+ ucmd->angles[YAW] = ANGLE2SHORT(bi->viewangles[YAW]);
+ ucmd->angles[ROLL] = ANGLE2SHORT(bi->viewangles[ROLL]);
+ //subtract the delta angles
+ for (j = 0; j < 3; j++) {
+ temp = ucmd->angles[j] - delta_angles[j];
+ /*NOTE: disabled because temp should be mod first
+ if ( j == PITCH ) {
+ // don't let the player look up or down more than 90 degrees
+ if ( temp > 16000 ) temp = 16000;
+ else if ( temp < -16000 ) temp = -16000;
+ }
+ */
+ ucmd->angles[j] = temp;
+ }
+ //NOTE: movement is relative to the REAL view angles
+ //get the horizontal forward and right vector
+ //get the pitch in the range [-180, 180]
+ if (bi->dir[2]) angles[PITCH] = bi->viewangles[PITCH];
+ else angles[PITCH] = 0;
+ angles[YAW] = bi->viewangles[YAW];
+ angles[ROLL] = 0;
+ AngleVectors(angles, forward, right, NULL);
+ //bot input speed is in the range [0, 400]
+ bi->speed = bi->speed * 127 / 400;
+ //set the view independent movement
+ ucmd->forwardmove = DotProduct(forward, bi->dir) * bi->speed;
+ ucmd->rightmove = DotProduct(right, bi->dir) * bi->speed;
+ ucmd->upmove = abs(forward[2]) * bi->dir[2] * bi->speed;
+ //normal keyboard movement
+ if (bi->actionflags & ACTION_MOVEFORWARD) ucmd->forwardmove += 127;
+ if (bi->actionflags & ACTION_MOVEBACK) ucmd->forwardmove -= 127;
+ if (bi->actionflags & ACTION_MOVELEFT) ucmd->rightmove -= 127;
+ if (bi->actionflags & ACTION_MOVERIGHT) ucmd->rightmove += 127;
+ //jump/moveup
+ if (bi->actionflags & ACTION_JUMP) ucmd->upmove += 127;
+ //crouch/movedown
+ if (bi->actionflags & ACTION_CROUCH) ucmd->upmove -= 127;
+ //
+ //Com_Printf("forward = %d right = %d up = %d\n", ucmd.forwardmove, ucmd.rightmove, ucmd.upmove);
+ //Com_Printf("ucmd->serverTime = %d\n", ucmd->serverTime);
+}
+
+/*
+==============
+BotUpdateInput
+==============
+*/
+void BotUpdateInput(bot_state_t *bs, int time, int elapsed_time) {
+ bot_input_t bi;
+ int j;
+
+ //add the delta angles to the bot's current view angles
+ for (j = 0; j < 3; j++) {
+ bs->viewangles[j] = AngleMod(bs->viewangles[j] + SHORT2ANGLE(bs->cur_ps.delta_angles[j]));
+ }
+ //change the bot view angles
+ BotChangeViewAngles(bs, (float) elapsed_time / 1000);
+ //retrieve the bot input
+ trap_EA_GetInput(bs->client, (float) time / 1000, &bi);
+ //respawn hack
+ if (bi.actionflags & ACTION_RESPAWN) {
+ if (bs->lastucmd.buttons & BUTTON_ATTACK) bi.actionflags &= ~(ACTION_RESPAWN|ACTION_ATTACK);
+ }
+ //convert the bot input to a usercmd
+ BotInputToUserCommand(&bi, &bs->lastucmd, bs->cur_ps.delta_angles, time);
+ //subtract the delta angles
+ for (j = 0; j < 3; j++) {
+ bs->viewangles[j] = AngleMod(bs->viewangles[j] - SHORT2ANGLE(bs->cur_ps.delta_angles[j]));
+ }
+}
+
+/*
+==============
+BotAIRegularUpdate
+==============
+*/
+void BotAIRegularUpdate(void) {
+ if (regularupdate_time < FloatTime()) {
+ trap_BotUpdateEntityItems();
+ regularupdate_time = FloatTime() + 0.3;
+ }
+}
+
+/*
+==============
+RemoveColorEscapeSequences
+==============
+*/
+void RemoveColorEscapeSequences( char *text ) {
+ int i, l;
+
+ l = 0;
+ for ( i = 0; text[i]; i++ ) {
+ if (Q_IsColorString(&text[i])) {
+ i++;
+ continue;
+ }
+ if (text[i] > 0x7E)
+ continue;
+ text[l++] = text[i];
+ }
+ text[l] = '\0';
+}
+
+/*
+==============
+BotAI
+==============
+*/
+int BotAI(int client, float thinktime) {
+ bot_state_t *bs;
+ char buf[1024], *args;
+ int j;
+
+ trap_EA_ResetInput(client);
+ //
+ bs = botstates[client];
+ if (!bs || !bs->inuse) {
+ BotAI_Print(PRT_FATAL, "BotAI: client %d is not setup\n", client);
+ return qfalse;
+ }
+
+ //retrieve the current client state
+ BotAI_GetClientState( client, &bs->cur_ps );
+
+ //retrieve any waiting server commands
+ while( trap_BotGetServerCommand(client, buf, sizeof(buf)) ) {
+ //have buf point to the command and args to the command arguments
+ args = strchr( buf, ' ');
+ if (!args) continue;
+ *args++ = '\0';
+
+ //remove color espace sequences from the arguments
+ RemoveColorEscapeSequences( args );
+
+ if (!Q_stricmp(buf, "cp "))
+ { /*CenterPrintf*/ }
+ else if (!Q_stricmp(buf, "cs"))
+ { /*ConfigStringModified*/ }
+ else if (!Q_stricmp(buf, "print")) {
+ //remove first and last quote from the chat message
+ memmove(args, args+1, strlen(args));
+ args[strlen(args)-1] = '\0';
+ trap_BotQueueConsoleMessage(bs->cs, CMS_NORMAL, args);
+ }
+ else if (!Q_stricmp(buf, "chat")) {
+ //remove first and last quote from the chat message
+ memmove(args, args+1, strlen(args));
+ args[strlen(args)-1] = '\0';
+ trap_BotQueueConsoleMessage(bs->cs, CMS_CHAT, args);
+ }
+ else if (!Q_stricmp(buf, "tchat")) {
+ //remove first and last quote from the chat message
+ memmove(args, args+1, strlen(args));
+ args[strlen(args)-1] = '\0';
+ trap_BotQueueConsoleMessage(bs->cs, CMS_CHAT, args);
+ }
+#ifdef MISSIONPACK
+ else if (!Q_stricmp(buf, "vchat")) {
+ BotVoiceChatCommand(bs, SAY_ALL, args);
+ }
+ else if (!Q_stricmp(buf, "vtchat")) {
+ BotVoiceChatCommand(bs, SAY_TEAM, args);
+ }
+ else if (!Q_stricmp(buf, "vtell")) {
+ BotVoiceChatCommand(bs, SAY_TELL, args);
+ }
+#endif
+ else if (!Q_stricmp(buf, "scores"))
+ { /*FIXME: parse scores?*/ }
+ else if (!Q_stricmp(buf, "clientLevelShot"))
+ { /*ignore*/ }
+ }
+ //add the delta angles to the bot's current view angles
+ for (j = 0; j < 3; j++) {
+ bs->viewangles[j] = AngleMod(bs->viewangles[j] + SHORT2ANGLE(bs->cur_ps.delta_angles[j]));
+ }
+ //increase the local time of the bot
+ bs->ltime += thinktime;
+ //
+ bs->thinktime = thinktime;
+ //origin of the bot
+ VectorCopy(bs->cur_ps.origin, bs->origin);
+ //eye coordinates of the bot
+ VectorCopy(bs->cur_ps.origin, bs->eye);
+ bs->eye[2] += bs->cur_ps.viewheight;
+ //get the area the bot is in
+ bs->areanum = BotPointAreaNum(bs->origin);
+ //the real AI
+ BotDeathmatchAI(bs, thinktime);
+ //set the weapon selection every AI frame
+ trap_EA_SelectWeapon(bs->client, bs->weaponnum);
+ //subtract the delta angles
+ for (j = 0; j < 3; j++) {
+ bs->viewangles[j] = AngleMod(bs->viewangles[j] - SHORT2ANGLE(bs->cur_ps.delta_angles[j]));
+ }
+ //everything was ok
+ return qtrue;
+}
+
+/*
+==================
+BotScheduleBotThink
+==================
+*/
+void BotScheduleBotThink(void) {
+ int i, botnum;
+
+ botnum = 0;
+
+ for( i = 0; i < MAX_CLIENTS; i++ ) {
+ if( !botstates[i] || !botstates[i]->inuse ) {
+ continue;
+ }
+ //initialize the bot think residual time
+ botstates[i]->botthink_residual = bot_thinktime.integer * botnum / numbots;
+ botnum++;
+ }
+}
+
+/*
+==============
+BotWriteSessionData
+==============
+*/
+void BotWriteSessionData(bot_state_t *bs) {
+ const char *s;
+ const char *var;
+
+ s = va(
+ "%i %i %i %i %i %i %i %i"
+ " %f %f %f"
+ " %f %f %f"
+ " %f %f %f",
+ bs->lastgoal_decisionmaker,
+ bs->lastgoal_ltgtype,
+ bs->lastgoal_teammate,
+ bs->lastgoal_teamgoal.areanum,
+ bs->lastgoal_teamgoal.entitynum,
+ bs->lastgoal_teamgoal.flags,
+ bs->lastgoal_teamgoal.iteminfo,
+ bs->lastgoal_teamgoal.number,
+ bs->lastgoal_teamgoal.origin[0],
+ bs->lastgoal_teamgoal.origin[1],
+ bs->lastgoal_teamgoal.origin[2],
+ bs->lastgoal_teamgoal.mins[0],
+ bs->lastgoal_teamgoal.mins[1],
+ bs->lastgoal_teamgoal.mins[2],
+ bs->lastgoal_teamgoal.maxs[0],
+ bs->lastgoal_teamgoal.maxs[1],
+ bs->lastgoal_teamgoal.maxs[2]
+ );
+
+ var = va( "botsession%i", bs->client );
+
+ trap_Cvar_Set( var, s );
+}
+
+/*
+==============
+BotReadSessionData
+==============
+*/
+void BotReadSessionData(bot_state_t *bs) {
+ char s[MAX_STRING_CHARS];
+ const char *var;
+
+ var = va( "botsession%i", bs->client );
+ trap_Cvar_VariableStringBuffer( var, s, sizeof(s) );
+
+ sscanf(s,
+ "%i %i %i %i %i %i %i %i"
+ " %f %f %f"
+ " %f %f %f"
+ " %f %f %f",
+ &bs->lastgoal_decisionmaker,
+ &bs->lastgoal_ltgtype,
+ &bs->lastgoal_teammate,
+ &bs->lastgoal_teamgoal.areanum,
+ &bs->lastgoal_teamgoal.entitynum,
+ &bs->lastgoal_teamgoal.flags,
+ &bs->lastgoal_teamgoal.iteminfo,
+ &bs->lastgoal_teamgoal.number,
+ &bs->lastgoal_teamgoal.origin[0],
+ &bs->lastgoal_teamgoal.origin[1],
+ &bs->lastgoal_teamgoal.origin[2],
+ &bs->lastgoal_teamgoal.mins[0],
+ &bs->lastgoal_teamgoal.mins[1],
+ &bs->lastgoal_teamgoal.mins[2],
+ &bs->lastgoal_teamgoal.maxs[0],
+ &bs->lastgoal_teamgoal.maxs[1],
+ &bs->lastgoal_teamgoal.maxs[2]
+ );
+}
+
+/*
+==============
+BotAISetupClient
+==============
+*/
+int BotAISetupClient(int client, struct bot_settings_s *settings, qboolean restart) {
+ char filename[MAX_PATH], name[MAX_PATH], gender[MAX_PATH];
+ bot_state_t *bs;
+ int errnum;
+
+ if (!botstates[client]) botstates[client] = G_Alloc(sizeof(bot_state_t));
+ bs = botstates[client];
+
+ if (bs && bs->inuse) {
+ BotAI_Print(PRT_FATAL, "BotAISetupClient: client %d already setup\n", client);
+ return qfalse;
+ }
+
+ if (!trap_AAS_Initialized()) {
+ BotAI_Print(PRT_FATAL, "AAS not initialized\n");
+ return qfalse;
+ }
+
+ //load the bot character
+ bs->character = trap_BotLoadCharacter(settings->characterfile, settings->skill);
+ if (!bs->character) {
+ BotAI_Print(PRT_FATAL, "couldn't load skill %f from %s\n", settings->skill, settings->characterfile);
+ return qfalse;
+ }
+ //copy the settings
+ memcpy(&bs->settings, settings, sizeof(bot_settings_t));
+ //allocate a goal state
+ bs->gs = trap_BotAllocGoalState(client);
+ //load the item weights
+ trap_Characteristic_String(bs->character, CHARACTERISTIC_ITEMWEIGHTS, filename, MAX_PATH);
+ errnum = trap_BotLoadItemWeights(bs->gs, filename);
+ if (errnum != BLERR_NOERROR) {
+ trap_BotFreeGoalState(bs->gs);
+ return qfalse;
+ }
+ //allocate a weapon state
+ bs->ws = trap_BotAllocWeaponState();
+ //load the weapon weights
+ trap_Characteristic_String(bs->character, CHARACTERISTIC_WEAPONWEIGHTS, filename, MAX_PATH);
+ errnum = trap_BotLoadWeaponWeights(bs->ws, filename);
+ if (errnum != BLERR_NOERROR) {
+ trap_BotFreeGoalState(bs->gs);
+ trap_BotFreeWeaponState(bs->ws);
+ return qfalse;
+ }
+ //allocate a chat state
+ bs->cs = trap_BotAllocChatState();
+ //load the chat file
+ trap_Characteristic_String(bs->character, CHARACTERISTIC_CHAT_FILE, filename, MAX_PATH);
+ trap_Characteristic_String(bs->character, CHARACTERISTIC_CHAT_NAME, name, MAX_PATH);
+ errnum = trap_BotLoadChatFile(bs->cs, filename, name);
+ if (errnum != BLERR_NOERROR) {
+ trap_BotFreeChatState(bs->cs);
+ trap_BotFreeGoalState(bs->gs);
+ trap_BotFreeWeaponState(bs->ws);
+ return qfalse;
+ }
+ //get the gender characteristic
+ trap_Characteristic_String(bs->character, CHARACTERISTIC_GENDER, gender, MAX_PATH);
+ //set the chat gender
+ if (*gender == 'f' || *gender == 'F') trap_BotSetChatGender(bs->cs, CHAT_GENDERFEMALE);
+ else if (*gender == 'm' || *gender == 'M') trap_BotSetChatGender(bs->cs, CHAT_GENDERMALE);
+ else trap_BotSetChatGender(bs->cs, CHAT_GENDERLESS);
+
+ bs->inuse = qtrue;
+ bs->client = client;
+ bs->entitynum = client;
+ bs->setupcount = 4;
+ bs->entergame_time = FloatTime();
+ bs->ms = trap_BotAllocMoveState();
+ bs->walker = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_WALKER, 0, 1);
+ numbots++;
+
+ if (trap_Cvar_VariableIntegerValue("bot_testichat")) {
+ trap_BotLibVarSet("bot_testichat", "1");
+ BotChatTest(bs);
+ }
+ //NOTE: reschedule the bot thinking
+ BotScheduleBotThink();
+ //if interbreeding start with a mutation
+ if (bot_interbreed) {
+ trap_BotMutateGoalFuzzyLogic(bs->gs, 1);
+ }
+ // if we kept the bot client
+ if (restart) {
+ BotReadSessionData(bs);
+ }
+ //bot has been setup succesfully
+ return qtrue;
+}
+
+/*
+==============
+BotAIShutdownClient
+==============
+*/
+int BotAIShutdownClient(int client, qboolean restart) {
+ bot_state_t *bs;
+
+ bs = botstates[client];
+ if (!bs || !bs->inuse) {
+ //BotAI_Print(PRT_ERROR, "BotAIShutdownClient: client %d already shutdown\n", client);
+ return qfalse;
+ }
+
+ if (restart) {
+ BotWriteSessionData(bs);
+ }
+
+ if (BotChat_ExitGame(bs)) {
+ trap_BotEnterChat(bs->cs, bs->client, CHAT_ALL);
+ }
+
+ trap_BotFreeMoveState(bs->ms);
+ //free the goal state`
+ trap_BotFreeGoalState(bs->gs);
+ //free the chat file
+ trap_BotFreeChatState(bs->cs);
+ //free the weapon weights
+ trap_BotFreeWeaponState(bs->ws);
+ //free the bot character
+ trap_BotFreeCharacter(bs->character);
+ //
+ BotFreeWaypoints(bs->checkpoints);
+ BotFreeWaypoints(bs->patrolpoints);
+ //clear activate goal stack
+ BotClearActivateGoalStack(bs);
+ //clear the bot state
+ memset(bs, 0, sizeof(bot_state_t));
+ //set the inuse flag to qfalse
+ bs->inuse = qfalse;
+ //there's one bot less
+ numbots--;
+ //everything went ok
+ return qtrue;
+}
+
+/*
+==============
+BotResetState
+
+called when a bot enters the intermission or observer mode and
+when the level is changed
+==============
+*/
+void BotResetState(bot_state_t *bs) {
+ int client, entitynum, inuse;
+ int movestate, goalstate, chatstate, weaponstate;
+ bot_settings_t settings;
+ int character;
+ playerState_t ps; //current player state
+ float entergame_time;
+
+ //save some things that should not be reset here
+ memcpy(&settings, &bs->settings, sizeof(bot_settings_t));
+ memcpy(&ps, &bs->cur_ps, sizeof(playerState_t));
+ inuse = bs->inuse;
+ client = bs->client;
+ entitynum = bs->entitynum;
+ character = bs->character;
+ movestate = bs->ms;
+ goalstate = bs->gs;
+ chatstate = bs->cs;
+ weaponstate = bs->ws;
+ entergame_time = bs->entergame_time;
+ //free checkpoints and patrol points
+ BotFreeWaypoints(bs->checkpoints);
+ BotFreeWaypoints(bs->patrolpoints);
+ //reset the whole state
+ memset(bs, 0, sizeof(bot_state_t));
+ //copy back some state stuff that should not be reset
+ bs->ms = movestate;
+ bs->gs = goalstate;
+ bs->cs = chatstate;
+ bs->ws = weaponstate;
+ memcpy(&bs->cur_ps, &ps, sizeof(playerState_t));
+ memcpy(&bs->settings, &settings, sizeof(bot_settings_t));
+ bs->inuse = inuse;
+ bs->client = client;
+ bs->entitynum = entitynum;
+ bs->character = character;
+ bs->entergame_time = entergame_time;
+ //reset several states
+ if (bs->ms) trap_BotResetMoveState(bs->ms);
+ if (bs->gs) trap_BotResetGoalState(bs->gs);
+ if (bs->ws) trap_BotResetWeaponState(bs->ws);
+ if (bs->gs) trap_BotResetAvoidGoals(bs->gs);
+ if (bs->ms) trap_BotResetAvoidReach(bs->ms);
+}
+
+/*
+==============
+BotAILoadMap
+==============
+*/
+int BotAILoadMap( int restart ) {
+ int i;
+ vmCvar_t mapname;
+
+ if (!restart) {
+ trap_Cvar_Register( &mapname, "mapname", "", CVAR_SERVERINFO | CVAR_ROM );
+ trap_BotLibLoadMap( mapname.string );
+ }
+
+ for (i = 0; i < MAX_CLIENTS; i++) {
+ if (botstates[i] && botstates[i]->inuse) {
+ BotResetState( botstates[i] );
+ botstates[i]->setupcount = 4;
+ }
+ }
+
+ BotSetupDeathmatchAI();
+
+ return qtrue;
+}
+
+#ifdef MISSIONPACK
+void ProximityMine_Trigger( gentity_t *trigger, gentity_t *other, trace_t *trace );
+#endif
+
+/*
+==================
+BotAIStartFrame
+==================
+*/
+int BotAIStartFrame(int time) {
+ int i;
+ gentity_t *ent;
+ bot_entitystate_t state;
+ int elapsed_time, thinktime;
+ static int local_time;
+ static int botlib_residual;
+ static int lastbotthink_time;
+
+ G_CheckBotSpawn();
+
+ trap_Cvar_Update(&bot_rocketjump);
+ trap_Cvar_Update(&bot_grapple);
+ trap_Cvar_Update(&bot_fastchat);
+ trap_Cvar_Update(&bot_nochat);
+ trap_Cvar_Update(&bot_testrchat);
+ trap_Cvar_Update(&bot_thinktime);
+ trap_Cvar_Update(&bot_memorydump);
+ trap_Cvar_Update(&bot_saveroutingcache);
+ trap_Cvar_Update(&bot_pause);
+ trap_Cvar_Update(&bot_report);
+
+ if (bot_report.integer) {
+// BotTeamplayReport();
+// trap_Cvar_Set("bot_report", "0");
+ BotUpdateInfoConfigStrings();
+ }
+
+ if (bot_pause.integer) {
+ // execute bot user commands every frame
+ for( i = 0; i < MAX_CLIENTS; i++ ) {
+ if( !botstates[i] || !botstates[i]->inuse ) {
+ continue;
+ }
+ if( g_entities[i].client->pers.connected != CON_CONNECTED ) {
+ continue;
+ }
+ botstates[i]->lastucmd.forwardmove = 0;
+ botstates[i]->lastucmd.rightmove = 0;
+ botstates[i]->lastucmd.upmove = 0;
+ botstates[i]->lastucmd.buttons = 0;
+ botstates[i]->lastucmd.serverTime = time;
+ trap_BotUserCommand(botstates[i]->client, &botstates[i]->lastucmd);
+ }
+ return qtrue;
+ }
+
+ if (bot_memorydump.integer) {
+ trap_BotLibVarSet("memorydump", "1");
+ trap_Cvar_Set("bot_memorydump", "0");
+ }
+ if (bot_saveroutingcache.integer) {
+ trap_BotLibVarSet("saveroutingcache", "1");
+ trap_Cvar_Set("bot_saveroutingcache", "0");
+ }
+ //check if bot interbreeding is activated
+ BotInterbreeding();
+ //cap the bot think time
+ if (bot_thinktime.integer > 200) {
+ trap_Cvar_Set("bot_thinktime", "200");
+ }
+ //if the bot think time changed we should reschedule the bots
+ if (bot_thinktime.integer != lastbotthink_time) {
+ lastbotthink_time = bot_thinktime.integer;
+ BotScheduleBotThink();
+ }
+
+ elapsed_time = time - local_time;
+ local_time = time;
+
+ botlib_residual += elapsed_time;
+
+ if (elapsed_time > bot_thinktime.integer) thinktime = elapsed_time;
+ else thinktime = bot_thinktime.integer;
+
+ // update the bot library
+ if ( botlib_residual >= thinktime ) {
+ botlib_residual -= thinktime;
+
+ trap_BotLibStartFrame((float) time / 1000);
+
+ if (!trap_AAS_Initialized()) return qfalse;
+
+ //update entities in the botlib
+ for (i = 0; i < MAX_GENTITIES; i++) {
+ ent = &g_entities[i];
+ if (!ent->inuse) {
+ trap_BotLibUpdateEntity(i, NULL);
+ continue;
+ }
+ if (!ent->r.linked) {
+ trap_BotLibUpdateEntity(i, NULL);
+ continue;
+ }
+ if (ent->r.svFlags & SVF_NOCLIENT) {
+ trap_BotLibUpdateEntity(i, NULL);
+ continue;
+ }
+ // do not update missiles
+ if (ent->s.eType == ET_MISSILE && ent->s.weapon != WP_GRAPPLING_HOOK) {
+ trap_BotLibUpdateEntity(i, NULL);
+ continue;
+ }
+ // do not update event only entities
+ if (ent->s.eType > ET_EVENTS) {
+ trap_BotLibUpdateEntity(i, NULL);
+ continue;
+ }
+#ifdef MISSIONPACK
+ // never link prox mine triggers
+ if (ent->r.contents == CONTENTS_TRIGGER) {
+ if (ent->touch == ProximityMine_Trigger) {
+ trap_BotLibUpdateEntity(i, NULL);
+ continue;
+ }
+ }
+#endif
+ //
+ memset(&state, 0, sizeof(bot_entitystate_t));
+ //
+ VectorCopy(ent->r.currentOrigin, state.origin);
+ if (i < MAX_CLIENTS) {
+ VectorCopy(ent->s.apos.trBase, state.angles);
+ } else {
+ VectorCopy(ent->r.currentAngles, state.angles);
+ }
+ VectorCopy(ent->s.origin2, state.old_origin);
+ VectorCopy(ent->r.mins, state.mins);
+ VectorCopy(ent->r.maxs, state.maxs);
+ state.type = ent->s.eType;
+ state.flags = ent->s.eFlags;
+ if (ent->r.bmodel) state.solid = SOLID_BSP;
+ else state.solid = SOLID_BBOX;
+ state.groundent = ent->s.groundEntityNum;
+ state.modelindex = ent->s.modelindex;
+ state.modelindex2 = ent->s.modelindex2;
+ state.frame = ent->s.frame;
+ state.event = ent->s.event;
+ state.eventParm = ent->s.eventParm;
+ state.powerups = ent->s.powerups;
+ state.legsAnim = ent->s.legsAnim;
+ state.torsoAnim = ent->s.torsoAnim;
+ state.weapon = ent->s.weapon;
+ //
+ trap_BotLibUpdateEntity(i, &state);
+ }
+
+ BotAIRegularUpdate();
+ }
+
+ floattime = trap_AAS_Time();
+
+ // execute scheduled bot AI
+ for( i = 0; i < MAX_CLIENTS; i++ ) {
+ if( !botstates[i] || !botstates[i]->inuse ) {
+ continue;
+ }
+ //
+ botstates[i]->botthink_residual += elapsed_time;
+ //
+ if ( botstates[i]->botthink_residual >= thinktime ) {
+ botstates[i]->botthink_residual -= thinktime;
+
+ if (!trap_AAS_Initialized()) return qfalse;
+
+ if (g_entities[i].client->pers.connected == CON_CONNECTED) {
+ BotAI(i, (float) thinktime / 1000);
+ }
+ }
+ }
+
+
+ // execute bot user commands every frame
+ for( i = 0; i < MAX_CLIENTS; i++ ) {
+ if( !botstates[i] || !botstates[i]->inuse ) {
+ continue;
+ }
+ if( g_entities[i].client->pers.connected != CON_CONNECTED ) {
+ continue;
+ }
+
+ BotUpdateInput(botstates[i], time, elapsed_time);
+ trap_BotUserCommand(botstates[i]->client, &botstates[i]->lastucmd);
+ }
+
+ return qtrue;
+}
+
+/*
+==============
+BotInitLibrary
+==============
+*/
+int BotInitLibrary(void) {
+ char buf[144];
+
+ //set the maxclients and maxentities library variables before calling BotSetupLibrary
+ trap_Cvar_VariableStringBuffer("sv_maxclients", buf, sizeof(buf));
+ if (!strlen(buf)) strcpy(buf, "8");
+ trap_BotLibVarSet("maxclients", buf);
+ Com_sprintf(buf, sizeof(buf), "%d", MAX_GENTITIES);
+ trap_BotLibVarSet("maxentities", buf);
+ //bsp checksum
+ trap_Cvar_VariableStringBuffer("sv_mapChecksum", buf, sizeof(buf));
+ if (strlen(buf)) trap_BotLibVarSet("sv_mapChecksum", buf);
+ //maximum number of aas links
+ trap_Cvar_VariableStringBuffer("max_aaslinks", buf, sizeof(buf));
+ if (strlen(buf)) trap_BotLibVarSet("max_aaslinks", buf);
+ //maximum number of items in a level
+ trap_Cvar_VariableStringBuffer("max_levelitems", buf, sizeof(buf));
+ if (strlen(buf)) trap_BotLibVarSet("max_levelitems", buf);
+ //game type
+ trap_Cvar_VariableStringBuffer("g_gametype", buf, sizeof(buf));
+ if (!strlen(buf)) strcpy(buf, "0");
+ trap_BotLibVarSet("g_gametype", buf);
+ //bot developer mode and log file
+ trap_BotLibVarSet("bot_developer", bot_developer.string);
+ trap_BotLibVarSet("log", buf);
+ //no chatting
+ trap_Cvar_VariableStringBuffer("bot_nochat", buf, sizeof(buf));
+ if (strlen(buf)) trap_BotLibVarSet("nochat", "0");
+ //visualize jump pads
+ trap_Cvar_VariableStringBuffer("bot_visualizejumppads", buf, sizeof(buf));
+ if (strlen(buf)) trap_BotLibVarSet("bot_visualizejumppads", buf);
+ //forced clustering calculations
+ trap_Cvar_VariableStringBuffer("bot_forceclustering", buf, sizeof(buf));
+ if (strlen(buf)) trap_BotLibVarSet("forceclustering", buf);
+ //forced reachability calculations
+ trap_Cvar_VariableStringBuffer("bot_forcereachability", buf, sizeof(buf));
+ if (strlen(buf)) trap_BotLibVarSet("forcereachability", buf);
+ //force writing of AAS to file
+ trap_Cvar_VariableStringBuffer("bot_forcewrite", buf, sizeof(buf));
+ if (strlen(buf)) trap_BotLibVarSet("forcewrite", buf);
+ //no AAS optimization
+ trap_Cvar_VariableStringBuffer("bot_aasoptimize", buf, sizeof(buf));
+ if (strlen(buf)) trap_BotLibVarSet("aasoptimize", buf);
+ //
+ trap_Cvar_VariableStringBuffer("bot_saveroutingcache", buf, sizeof(buf));
+ if (strlen(buf)) trap_BotLibVarSet("saveroutingcache", buf);
+ //reload instead of cache bot character files
+ trap_Cvar_VariableStringBuffer("bot_reloadcharacters", buf, sizeof(buf));
+ if (!strlen(buf)) strcpy(buf, "0");
+ trap_BotLibVarSet("bot_reloadcharacters", buf);
+ //base directory
+ trap_Cvar_VariableStringBuffer("fs_basepath", buf, sizeof(buf));
+ if (strlen(buf)) trap_BotLibVarSet("basedir", buf);
+ //game directory
+ trap_Cvar_VariableStringBuffer("fs_game", buf, sizeof(buf));
+ if (strlen(buf)) trap_BotLibVarSet("gamedir", buf);
+ //cd directory
+ trap_Cvar_VariableStringBuffer("fs_cdpath", buf, sizeof(buf));
+ if (strlen(buf)) trap_BotLibVarSet("cddir", buf);
+ //
+#ifdef MISSIONPACK
+ trap_BotLibDefine("MISSIONPACK");
+#endif
+ //setup the bot library
+ return trap_BotLibSetup();
+}
+
+/*
+==============
+BotAISetup
+==============
+*/
+int BotAISetup( int restart ) {
+ int errnum;
+
+ trap_Cvar_Register(&bot_thinktime, "bot_thinktime", "100", CVAR_CHEAT);
+ trap_Cvar_Register(&bot_memorydump, "bot_memorydump", "0", CVAR_CHEAT);
+ trap_Cvar_Register(&bot_saveroutingcache, "bot_saveroutingcache", "0", CVAR_CHEAT);
+ trap_Cvar_Register(&bot_pause, "bot_pause", "0", CVAR_CHEAT);
+ trap_Cvar_Register(&bot_report, "bot_report", "0", CVAR_CHEAT);
+ trap_Cvar_Register(&bot_testsolid, "bot_testsolid", "0", CVAR_CHEAT);
+ trap_Cvar_Register(&bot_testclusters, "bot_testclusters", "0", CVAR_CHEAT);
+ trap_Cvar_Register(&bot_developer, "bot_developer", "0", CVAR_CHEAT);
+ trap_Cvar_Register(&bot_interbreedchar, "bot_interbreedchar", "", 0);
+ trap_Cvar_Register(&bot_interbreedbots, "bot_interbreedbots", "10", 0);
+ trap_Cvar_Register(&bot_interbreedcycle, "bot_interbreedcycle", "20", 0);
+ trap_Cvar_Register(&bot_interbreedwrite, "bot_interbreedwrite", "", 0);
+
+ //if the game is restarted for a tournament
+ if (restart) {
+ return qtrue;
+ }
+
+ //initialize the bot states
+ memset( botstates, 0, sizeof(botstates) );
+
+ errnum = BotInitLibrary();
+ if (errnum != BLERR_NOERROR) return qfalse;
+ return qtrue;
+}
+
+/*
+==============
+BotAIShutdown
+==============
+*/
+int BotAIShutdown( int restart ) {
+
+ int i;
+
+ //if the game is restarted for a tournament
+ if ( restart ) {
+ //shutdown all the bots in the botlib
+ for (i = 0; i < MAX_CLIENTS; i++) {
+ if (botstates[i] && botstates[i]->inuse) {
+ BotAIShutdownClient(botstates[i]->client, restart);
+ }
+ }
+ //don't shutdown the bot library
+ }
+ else {
+ trap_BotLibShutdown();
+ }
+ return qtrue;
+}
+
diff --git a/code/game/ai_main.h b/code/game/ai_main.h
new file mode 100755
index 0000000..91e8895
--- /dev/null
+++ b/code/game/ai_main.h
@@ -0,0 +1,299 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+/*****************************************************************************
+ * name: ai_main.h
+ *
+ * desc: Quake3 bot AI
+ *
+ * $Archive: /source/code/botai/ai_chat.c $
+ *
+ *****************************************************************************/
+
+//#define DEBUG
+#define CTF
+
+#define MAX_ITEMS 256
+//bot flags
+#define BFL_STRAFERIGHT 1 //strafe to the right
+#define BFL_ATTACKED 2 //bot has attacked last ai frame
+#define BFL_ATTACKJUMPED 4 //bot jumped during attack last frame
+#define BFL_AIMATENEMY 8 //bot aimed at the enemy this frame
+#define BFL_AVOIDRIGHT 16 //avoid obstacles by going to the right
+#define BFL_IDEALVIEWSET 32 //bot has ideal view angles set
+#define BFL_FIGHTSUICIDAL 64 //bot is in a suicidal fight
+//long term goal types
+#define LTG_TEAMHELP 1 //help a team mate
+#define LTG_TEAMACCOMPANY 2 //accompany a team mate
+#define LTG_DEFENDKEYAREA 3 //defend a key area
+#define LTG_GETFLAG 4 //get the enemy flag
+#define LTG_RUSHBASE 5 //rush to the base
+#define LTG_RETURNFLAG 6 //return the flag
+#define LTG_CAMP 7 //camp somewhere
+#define LTG_CAMPORDER 8 //ordered to camp somewhere
+#define LTG_PATROL 9 //patrol
+#define LTG_GETITEM 10 //get an item
+#define LTG_KILL 11 //kill someone
+#define LTG_HARVEST 12 //harvest skulls
+#define LTG_ATTACKENEMYBASE 13 //attack the enemy base
+#define LTG_MAKELOVE_UNDER 14
+#define LTG_MAKELOVE_ONTOP 15
+//some goal dedication times
+#define TEAM_HELP_TIME 60 //1 minute teamplay help time
+#define TEAM_ACCOMPANY_TIME 600 //10 minutes teamplay accompany time
+#define TEAM_DEFENDKEYAREA_TIME 600 //10 minutes ctf defend base time
+#define TEAM_CAMP_TIME 600 //10 minutes camping time
+#define TEAM_PATROL_TIME 600 //10 minutes patrolling time
+#define TEAM_LEAD_TIME 600 //10 minutes taking the lead
+#define TEAM_GETITEM_TIME 60 //1 minute
+#define TEAM_KILL_SOMEONE 180 //3 minute to kill someone
+#define TEAM_ATTACKENEMYBASE_TIME 600 //10 minutes
+#define TEAM_HARVEST_TIME 120 //2 minutes
+#define CTF_GETFLAG_TIME 600 //10 minutes ctf get flag time
+#define CTF_RUSHBASE_TIME 120 //2 minutes ctf rush base time
+#define CTF_RETURNFLAG_TIME 180 //3 minutes to return the flag
+#define CTF_ROAM_TIME 60 //1 minute ctf roam time
+//patrol flags
+#define PATROL_LOOP 1
+#define PATROL_REVERSE 2
+#define PATROL_BACK 4
+//teamplay task preference
+#define TEAMTP_DEFENDER 1
+#define TEAMTP_ATTACKER 2
+//CTF strategy
+#define CTFS_AGRESSIVE 1
+//copied from the aas file header
+#define PRESENCE_NONE 1
+#define PRESENCE_NORMAL 2
+#define PRESENCE_CROUCH 4
+//
+#define MAX_PROXMINES 64
+
+//check points
+typedef struct bot_waypoint_s
+{
+ int inuse;
+ char name[32];
+ bot_goal_t goal;
+ struct bot_waypoint_s *next, *prev;
+} bot_waypoint_t;
+
+#define MAX_ACTIVATESTACK 8
+#define MAX_ACTIVATEAREAS 32
+
+typedef struct bot_activategoal_s
+{
+ int inuse;
+ bot_goal_t goal; //goal to activate (buttons etc.)
+ float time; //time to activate something
+ float start_time; //time starting to activate something
+ float justused_time; //time the goal was used
+ int shoot; //true if bot has to shoot to activate
+ int weapon; //weapon to be used for activation
+ vec3_t target; //target to shoot at to activate something
+ vec3_t origin; //origin of the blocking entity to activate
+ int areas[MAX_ACTIVATEAREAS]; //routing areas disabled by blocking entity
+ int numareas; //number of disabled routing areas
+ int areasdisabled; //true if the areas are disabled for the routing
+ struct bot_activategoal_s *next; //next activate goal on stack
+} bot_activategoal_t;
+
+//bot state
+typedef struct bot_state_s
+{
+ int inuse; //true if this state is used by a bot client
+ int botthink_residual; //residual for the bot thinks
+ int client; //client number of the bot
+ int entitynum; //entity number of the bot
+ playerState_t cur_ps; //current player state
+ int last_eFlags; //last ps flags
+ usercmd_t lastucmd; //usercmd from last frame
+ int entityeventTime[1024]; //last entity event time
+ //
+ bot_settings_t settings; //several bot settings
+ int (*ainode)(struct bot_state_s *bs); //current AI node
+ float thinktime; //time the bot thinks this frame
+ vec3_t origin; //origin of the bot
+ vec3_t velocity; //velocity of the bot
+ int presencetype; //presence type of the bot
+ vec3_t eye; //eye coordinates of the bot
+ int areanum; //the number of the area the bot is in
+ int inventory[MAX_ITEMS]; //string with items amounts the bot has
+ int tfl; //the travel flags the bot uses
+ int flags; //several flags
+ int respawn_wait; //wait until respawned
+ int lasthealth; //health value previous frame
+ int lastkilledplayer; //last killed player
+ int lastkilledby; //player that last killed this bot
+ int botdeathtype; //the death type of the bot
+ int enemydeathtype; //the death type of the enemy
+ int botsuicide; //true when the bot suicides
+ int enemysuicide; //true when the enemy of the bot suicides
+ int setupcount; //true when the bot has just been setup
+ int map_restart; //true when the map is being restarted
+ int entergamechat; //true when the bot used an enter game chat
+ int num_deaths; //number of time this bot died
+ int num_kills; //number of kills of this bot
+ int revenge_enemy; //the revenge enemy
+ int revenge_kills; //number of kills the enemy made
+ int lastframe_health; //health value the last frame
+ int lasthitcount; //number of hits last frame
+ int chatto; //chat to all or team
+ float walker; //walker charactertic
+ float ltime; //local bot time
+ float entergame_time; //time the bot entered the game
+ float ltg_time; //long term goal time
+ float nbg_time; //nearby goal time
+ float respawn_time; //time the bot takes to respawn
+ float respawnchat_time; //time the bot started a chat during respawn
+ float chase_time; //time the bot will chase the enemy
+ float enemyvisible_time; //time the enemy was last visible
+ float check_time; //time to check for nearby items
+ float stand_time; //time the bot is standing still
+ float lastchat_time; //time the bot last selected a chat
+ float kamikaze_time; //time to check for kamikaze usage
+ float invulnerability_time; //time to check for invulnerability usage
+ float standfindenemy_time; //time to find enemy while standing
+ float attackstrafe_time; //time the bot is strafing in one dir
+ float attackcrouch_time; //time the bot will stop crouching
+ float attackchase_time; //time the bot chases during actual attack
+ float attackjump_time; //time the bot jumped during attack
+ float enemysight_time; //time before reacting to enemy
+ float enemydeath_time; //time the enemy died
+ float enemyposition_time; //time the position and velocity of the enemy were stored
+ float defendaway_time; //time away while defending
+ float defendaway_range; //max travel time away from defend area
+ float rushbaseaway_time; //time away from rushing to the base
+ float attackaway_time; //time away from attacking the enemy base
+ float harvestaway_time; //time away from harvesting
+ float ctfroam_time; //time the bot is roaming in ctf
+ float killedenemy_time; //time the bot killed the enemy
+ float arrive_time; //time arrived (at companion)
+ float lastair_time; //last time the bot had air
+ float teleport_time; //last time the bot teleported
+ float camp_time; //last time camped
+ float camp_range; //camp range
+ float weaponchange_time; //time the bot started changing weapons
+ float firethrottlewait_time; //amount of time to wait
+ float firethrottleshoot_time; //amount of time to shoot
+ float notblocked_time; //last time the bot was not blocked
+ float blockedbyavoidspot_time; //time blocked by an avoid spot
+ float predictobstacles_time; //last time the bot predicted obstacles
+ int predictobstacles_goalareanum; //last goal areanum the bot predicted obstacles for
+ vec3_t aimtarget;
+ vec3_t enemyvelocity; //enemy velocity 0.5 secs ago during battle
+ vec3_t enemyorigin; //enemy origin 0.5 secs ago during battle
+ //
+ int kamikazebody; //kamikaze body
+ int proxmines[MAX_PROXMINES];
+ int numproxmines;
+ //
+ int character; //the bot character
+ int ms; //move state of the bot
+ int gs; //goal state of the bot
+ int cs; //chat state of the bot
+ int ws; //weapon state of the bot
+ //
+ int enemy; //enemy entity number
+ int lastenemyareanum; //last reachability area the enemy was in
+ vec3_t lastenemyorigin; //last origin of the enemy in the reachability area
+ int weaponnum; //current weapon number
+ vec3_t viewangles; //current view angles
+ vec3_t ideal_viewangles; //ideal view angles
+ vec3_t viewanglespeed;
+ //
+ int ltgtype; //long term goal type
+ // team goals
+ int teammate; //team mate involved in this team goal
+ int decisionmaker; //player who decided to go for this goal
+ int ordered; //true if ordered to do something
+ float order_time; //time ordered to do something
+ int owndecision_time; //time the bot made it's own decision
+ bot_goal_t teamgoal; //the team goal
+ bot_goal_t altroutegoal; //alternative route goal
+ float reachedaltroutegoal_time; //time the bot reached the alt route goal
+ float teammessage_time; //time to message team mates what the bot is doing
+ float teamgoal_time; //time to stop helping team mate
+ float teammatevisible_time; //last time the team mate was NOT visible
+ int teamtaskpreference; //team task preference
+ // last ordered team goal
+ int lastgoal_decisionmaker;
+ int lastgoal_ltgtype;
+ int lastgoal_teammate;
+ bot_goal_t lastgoal_teamgoal;
+ // for leading team mates
+ int lead_teammate; //team mate the bot is leading
+ bot_goal_t lead_teamgoal; //team goal while leading
+ float lead_time; //time leading someone
+ float leadvisible_time; //last time the team mate was visible
+ float leadmessage_time; //last time a messaged was sent to the team mate
+ float leadbackup_time; //time backing up towards team mate
+ //
+ char teamleader[32]; //netname of the team leader
+ float askteamleader_time; //time asked for team leader
+ float becometeamleader_time; //time the bot will become the team leader
+ float teamgiveorders_time; //time to give team orders
+ float lastflagcapture_time; //last time a flag was captured
+ int numteammates; //number of team mates
+ int redflagstatus; //0 = at base, 1 = not at base
+ int blueflagstatus; //0 = at base, 1 = not at base
+ int neutralflagstatus; //0 = at base, 1 = our team has flag, 2 = enemy team has flag, 3 = enemy team dropped the flag
+ int flagstatuschanged; //flag status changed
+ int forceorders; //true if forced to give orders
+ int flagcarrier; //team mate carrying the enemy flag
+ int ctfstrategy; //ctf strategy
+ char subteam[32]; //sub team name
+ float formation_dist; //formation team mate intervening space
+ char formation_teammate[16]; //netname of the team mate the bot uses for relative positioning
+ float formation_angle; //angle relative to the formation team mate
+ vec3_t formation_dir; //the direction the formation is moving in
+ vec3_t formation_origin; //origin the bot uses for relative positioning
+ bot_goal_t formation_goal; //formation goal
+
+ bot_activategoal_t *activatestack; //first activate goal on the stack
+ bot_activategoal_t activategoalheap[MAX_ACTIVATESTACK]; //activate goal heap
+
+ bot_waypoint_t *checkpoints; //check points
+ bot_waypoint_t *patrolpoints; //patrol points
+ bot_waypoint_t *curpatrolpoint; //current patrol point the bot is going for
+ int patrolflags; //patrol flags
+} bot_state_t;
+
+//resets the whole bot state
+void BotResetState(bot_state_t *bs);
+//returns the number of bots in the game
+int NumBots(void);
+//returns info about the entity
+void BotEntityInfo(int entnum, aas_entityinfo_t *info);
+
+extern float floattime;
+#define FloatTime() floattime
+
+// from the game source
+void QDECL BotAI_Print(int type, char *fmt, ...);
+void QDECL QDECL BotAI_BotInitialChat( bot_state_t *bs, char *type, ... );
+void BotAI_Trace(bsp_trace_t *bsptrace, vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int passent, int contentmask);
+int BotAI_GetClientState( int clientNum, playerState_t *state );
+int BotAI_GetEntityState( int entityNum, entityState_t *state );
+int BotAI_GetSnapshotEntity( int clientNum, int sequence, entityState_t *state );
+int BotTeamLeader(bot_state_t *bs);
diff --git a/code/game/ai_team.c b/code/game/ai_team.c
new file mode 100755
index 0000000..9215702
--- /dev/null
+++ b/code/game/ai_team.c
@@ -0,0 +1,2080 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+/*****************************************************************************
+ * name: ai_team.c
+ *
+ * desc: Quake3 bot AI
+ *
+ * $Archive: /MissionPack/code/game/ai_team.c $
+ *
+ *****************************************************************************/
+
+#include "g_local.h"
+#include "botlib.h"
+#include "be_aas.h"
+#include "be_ea.h"
+#include "be_ai_char.h"
+#include "be_ai_chat.h"
+#include "be_ai_gen.h"
+#include "be_ai_goal.h"
+#include "be_ai_move.h"
+#include "be_ai_weap.h"
+//
+#include "ai_main.h"
+#include "ai_dmq3.h"
+#include "ai_chat.h"
+#include "ai_cmd.h"
+#include "ai_dmnet.h"
+#include "ai_team.h"
+#include "ai_vcmd.h"
+
+#include "match.h"
+
+// for the voice chats
+#include "../../ui/menudef.h"
+
+//ctf task preferences for a client
+typedef struct bot_ctftaskpreference_s
+{
+ char name[36];
+ int preference;
+} bot_ctftaskpreference_t;
+
+bot_ctftaskpreference_t ctftaskpreferences[MAX_CLIENTS];
+
+
+/*
+==================
+BotValidTeamLeader
+==================
+*/
+int BotValidTeamLeader(bot_state_t *bs) {
+ if (!strlen(bs->teamleader)) return qfalse;
+ if (ClientFromName(bs->teamleader) == -1) return qfalse;
+ return qtrue;
+}
+
+/*
+==================
+BotNumTeamMates
+==================
+*/
+int BotNumTeamMates(bot_state_t *bs) {
+ int i, numplayers;
+ char buf[MAX_INFO_STRING];
+ static int maxclients;
+
+ if (!maxclients)
+ maxclients = trap_Cvar_VariableIntegerValue("sv_maxclients");
+
+ numplayers = 0;
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ trap_GetConfigstring(CS_PLAYERS+i, buf, sizeof(buf));
+ //if no config string or no name
+ if (!strlen(buf) || !strlen(Info_ValueForKey(buf, "n"))) continue;
+ //skip spectators
+ if (atoi(Info_ValueForKey(buf, "t")) == TEAM_SPECTATOR) continue;
+ //
+ if (BotSameTeam(bs, i)) {
+ numplayers++;
+ }
+ }
+ return numplayers;
+}
+
+/*
+==================
+BotClientTravelTimeToGoal
+==================
+*/
+int BotClientTravelTimeToGoal(int client, bot_goal_t *goal) {
+ playerState_t ps;
+ int areanum;
+
+ BotAI_GetClientState(client, &ps);
+ areanum = BotPointAreaNum(ps.origin);
+ if (!areanum) return 1;
+ return trap_AAS_AreaTravelTimeToGoalArea(areanum, ps.origin, goal->areanum, TFL_DEFAULT);
+}
+
+/*
+==================
+BotSortTeamMatesByBaseTravelTime
+==================
+*/
+int BotSortTeamMatesByBaseTravelTime(bot_state_t *bs, int *teammates, int maxteammates) {
+
+ int i, j, k, numteammates, traveltime;
+ char buf[MAX_INFO_STRING];
+ static int maxclients;
+ int traveltimes[MAX_CLIENTS];
+ bot_goal_t *goal = NULL;
+
+ if (gametype == GT_CTF || gametype == GT_1FCTF) {
+ if (BotTeam(bs) == TEAM_RED)
+ goal = &ctf_redflag;
+ else
+ goal = &ctf_blueflag;
+ }
+#ifdef MISSIONPACK
+ else {
+ if (BotTeam(bs) == TEAM_RED)
+ goal = &redobelisk;
+ else
+ goal = &blueobelisk;
+ }
+#endif
+ if (!maxclients)
+ maxclients = trap_Cvar_VariableIntegerValue("sv_maxclients");
+
+ numteammates = 0;
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ trap_GetConfigstring(CS_PLAYERS+i, buf, sizeof(buf));
+ //if no config string or no name
+ if (!strlen(buf) || !strlen(Info_ValueForKey(buf, "n"))) continue;
+ //skip spectators
+ if (atoi(Info_ValueForKey(buf, "t")) == TEAM_SPECTATOR) continue;
+ //
+ if (BotSameTeam(bs, i)) {
+ //
+ traveltime = BotClientTravelTimeToGoal(i, goal);
+ //
+ for (j = 0; j < numteammates; j++) {
+ if (traveltime < traveltimes[j]) {
+ for (k = numteammates; k > j; k--) {
+ traveltimes[k] = traveltimes[k-1];
+ teammates[k] = teammates[k-1];
+ }
+ break;
+ }
+ }
+ traveltimes[j] = traveltime;
+ teammates[j] = i;
+ numteammates++;
+ if (numteammates >= maxteammates) break;
+ }
+ }
+ return numteammates;
+}
+
+/*
+==================
+BotSetTeamMateTaskPreference
+==================
+*/
+void BotSetTeamMateTaskPreference(bot_state_t *bs, int teammate, int preference) {
+ char teammatename[MAX_NETNAME];
+
+ ctftaskpreferences[teammate].preference = preference;
+ ClientName(teammate, teammatename, sizeof(teammatename));
+ strcpy(ctftaskpreferences[teammate].name, teammatename);
+}
+
+/*
+==================
+BotGetTeamMateTaskPreference
+==================
+*/
+int BotGetTeamMateTaskPreference(bot_state_t *bs, int teammate) {
+ char teammatename[MAX_NETNAME];
+
+ if (!ctftaskpreferences[teammate].preference) return 0;
+ ClientName(teammate, teammatename, sizeof(teammatename));
+ if (Q_stricmp(teammatename, ctftaskpreferences[teammate].name)) return 0;
+ return ctftaskpreferences[teammate].preference;
+}
+
+/*
+==================
+BotSortTeamMatesByTaskPreference
+==================
+*/
+int BotSortTeamMatesByTaskPreference(bot_state_t *bs, int *teammates, int numteammates) {
+ int defenders[MAX_CLIENTS], numdefenders;
+ int attackers[MAX_CLIENTS], numattackers;
+ int roamers[MAX_CLIENTS], numroamers;
+ int i, preference;
+
+ numdefenders = numattackers = numroamers = 0;
+ for (i = 0; i < numteammates; i++) {
+ preference = BotGetTeamMateTaskPreference(bs, teammates[i]);
+ if (preference & TEAMTP_DEFENDER) {
+ defenders[numdefenders++] = teammates[i];
+ }
+ else if (preference & TEAMTP_ATTACKER) {
+ attackers[numattackers++] = teammates[i];
+ }
+ else {
+ roamers[numroamers++] = teammates[i];
+ }
+ }
+ numteammates = 0;
+ //defenders at the front of the list
+ memcpy(&teammates[numteammates], defenders, numdefenders * sizeof(int));
+ numteammates += numdefenders;
+ //roamers in the middle
+ memcpy(&teammates[numteammates], roamers, numroamers * sizeof(int));
+ numteammates += numroamers;
+ //attacker in the back of the list
+ memcpy(&teammates[numteammates], attackers, numattackers * sizeof(int));
+ numteammates += numattackers;
+
+ return numteammates;
+}
+
+/*
+==================
+BotSayTeamOrders
+==================
+*/
+void BotSayTeamOrderAlways(bot_state_t *bs, int toclient) {
+ char teamchat[MAX_MESSAGE_SIZE];
+ char buf[MAX_MESSAGE_SIZE];
+ char name[MAX_NETNAME];
+
+ //if the bot is talking to itself
+ if (bs->client == toclient) {
+ //don't show the message just put it in the console message queue
+ trap_BotGetChatMessage(bs->cs, buf, sizeof(buf));
+ ClientName(bs->client, name, sizeof(name));
+ Com_sprintf(teamchat, sizeof(teamchat), EC"(%s"EC")"EC": %s", name, buf);
+ trap_BotQueueConsoleMessage(bs->cs, CMS_CHAT, teamchat);
+ }
+ else {
+ trap_BotEnterChat(bs->cs, toclient, CHAT_TELL);
+ }
+}
+
+/*
+==================
+BotSayTeamOrders
+==================
+*/
+void BotSayTeamOrder(bot_state_t *bs, int toclient) {
+#ifdef MISSIONPACK
+ // voice chats only
+ char buf[MAX_MESSAGE_SIZE];
+
+ trap_BotGetChatMessage(bs->cs, buf, sizeof(buf));
+#else
+ BotSayTeamOrderAlways(bs, toclient);
+#endif
+}
+
+/*
+==================
+BotVoiceChat
+==================
+*/
+void BotVoiceChat(bot_state_t *bs, int toclient, char *voicechat) {
+#ifdef MISSIONPACK
+ if (toclient == -1)
+ // voice only say team
+ trap_EA_Command(bs->client, va("vsay_team %s", voicechat));
+ else
+ // voice only tell single player
+ trap_EA_Command(bs->client, va("vtell %d %s", toclient, voicechat));
+#endif
+}
+
+/*
+==================
+BotVoiceChatOnly
+==================
+*/
+void BotVoiceChatOnly(bot_state_t *bs, int toclient, char *voicechat) {
+#ifdef MISSIONPACK
+ if (toclient == -1)
+ // voice only say team
+ trap_EA_Command(bs->client, va("vosay_team %s", voicechat));
+ else
+ // voice only tell single player
+ trap_EA_Command(bs->client, va("votell %d %s", toclient, voicechat));
+#endif
+}
+
+/*
+==================
+BotSayVoiceTeamOrder
+==================
+*/
+void BotSayVoiceTeamOrder(bot_state_t *bs, int toclient, char *voicechat) {
+#ifdef MISSIONPACK
+ BotVoiceChat(bs, toclient, voicechat);
+#endif
+}
+
+/*
+==================
+BotCTFOrders
+==================
+*/
+void BotCTFOrders_BothFlagsNotAtBase(bot_state_t *bs) {
+ int numteammates, defenders, attackers, i, other;
+ int teammates[MAX_CLIENTS];
+ char name[MAX_NETNAME], carriername[MAX_NETNAME];
+
+ numteammates = BotSortTeamMatesByBaseTravelTime(bs, teammates, sizeof(teammates));
+ BotSortTeamMatesByTaskPreference(bs, teammates, numteammates);
+ //different orders based on the number of team mates
+ switch(bs->numteammates) {
+ case 1: break;
+ case 2:
+ {
+ //tell the one not carrying the flag to attack the enemy base
+ if (teammates[0] != bs->flagcarrier) other = teammates[0];
+ else other = teammates[1];
+ ClientName(other, name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, other);
+ BotSayVoiceTeamOrder(bs, other, VOICECHAT_GETFLAG);
+ break;
+ }
+ case 3:
+ {
+ //tell the one closest to the base not carrying the flag to accompany the flag carrier
+ if (teammates[0] != bs->flagcarrier) other = teammates[0];
+ else other = teammates[1];
+ ClientName(other, name, sizeof(name));
+ if ( bs->flagcarrier != -1 ) {
+ ClientName(bs->flagcarrier, carriername, sizeof(carriername));
+ if (bs->flagcarrier == bs->client) {
+ BotAI_BotInitialChat(bs, "cmd_accompanyme", name, NULL);
+ BotSayVoiceTeamOrder(bs, other, VOICECHAT_FOLLOWME);
+ }
+ else {
+ BotAI_BotInitialChat(bs, "cmd_accompany", name, carriername, NULL);
+ BotSayVoiceTeamOrder(bs, other, VOICECHAT_FOLLOWFLAGCARRIER);
+ }
+ }
+ else {
+ //
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayVoiceTeamOrder(bs, other, VOICECHAT_GETFLAG);
+ }
+ BotSayTeamOrder(bs, other);
+ //tell the one furthest from the the base not carrying the flag to get the enemy flag
+ if (teammates[2] != bs->flagcarrier) other = teammates[2];
+ else other = teammates[1];
+ ClientName(other, name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, other);
+ BotSayVoiceTeamOrder(bs, other, VOICECHAT_RETURNFLAG);
+ break;
+ }
+ default:
+ {
+ defenders = (int) (float) numteammates * 0.4 + 0.5;
+ if (defenders > 4) defenders = 4;
+ attackers = (int) (float) numteammates * 0.5 + 0.5;
+ if (attackers > 5) attackers = 5;
+ if (bs->flagcarrier != -1) {
+ ClientName(bs->flagcarrier, carriername, sizeof(carriername));
+ for (i = 0; i < defenders; i++) {
+ //
+ if (teammates[i] == bs->flagcarrier) {
+ continue;
+ }
+ //
+ ClientName(teammates[i], name, sizeof(name));
+ if (bs->flagcarrier == bs->client) {
+ BotAI_BotInitialChat(bs, "cmd_accompanyme", name, NULL);
+ BotSayVoiceTeamOrder(bs, teammates[i], VOICECHAT_FOLLOWME);
+ }
+ else {
+ BotAI_BotInitialChat(bs, "cmd_accompany", name, carriername, NULL);
+ BotSayVoiceTeamOrder(bs, teammates[i], VOICECHAT_FOLLOWFLAGCARRIER);
+ }
+ BotSayTeamOrder(bs, teammates[i]);
+ }
+ }
+ else {
+ for (i = 0; i < defenders; i++) {
+ //
+ if (teammates[i] == bs->flagcarrier) {
+ continue;
+ }
+ //
+ ClientName(teammates[i], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayVoiceTeamOrder(bs, teammates[i], VOICECHAT_GETFLAG);
+ BotSayTeamOrder(bs, teammates[i]);
+ }
+ }
+ for (i = 0; i < attackers; i++) {
+ //
+ if (teammates[numteammates - i - 1] == bs->flagcarrier) {
+ continue;
+ }
+ //
+ ClientName(teammates[numteammates - i - 1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[numteammates - i - 1]);
+ BotSayVoiceTeamOrder(bs, teammates[numteammates - i - 1], VOICECHAT_RETURNFLAG);
+ }
+ //
+ break;
+ }
+ }
+}
+
+/*
+==================
+BotCTFOrders
+==================
+*/
+void BotCTFOrders_FlagNotAtBase(bot_state_t *bs) {
+ int numteammates, defenders, attackers, i;
+ int teammates[MAX_CLIENTS];
+ char name[MAX_NETNAME];
+
+ numteammates = BotSortTeamMatesByBaseTravelTime(bs, teammates, sizeof(teammates));
+ BotSortTeamMatesByTaskPreference(bs, teammates, numteammates);
+ //passive strategy
+ if (!(bs->ctfstrategy & CTFS_AGRESSIVE)) {
+ //different orders based on the number of team mates
+ switch(bs->numteammates) {
+ case 1: break;
+ case 2:
+ {
+ //both will go for the enemy flag
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_GETFLAG);
+ //
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_GETFLAG);
+ break;
+ }
+ case 3:
+ {
+ //keep one near the base for when the flag is returned
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the other two get the flag
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_GETFLAG);
+ //
+ ClientName(teammates[2], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[2]);
+ BotSayVoiceTeamOrder(bs, teammates[2], VOICECHAT_GETFLAG);
+ break;
+ }
+ default:
+ {
+ //keep some people near the base for when the flag is returned
+ defenders = (int) (float) numteammates * 0.3 + 0.5;
+ if (defenders > 3) defenders = 3;
+ attackers = (int) (float) numteammates * 0.7 + 0.5;
+ if (attackers > 6) attackers = 6;
+ for (i = 0; i < defenders; i++) {
+ //
+ ClientName(teammates[i], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[i]);
+ BotSayVoiceTeamOrder(bs, teammates[i], VOICECHAT_DEFEND);
+ }
+ for (i = 0; i < attackers; i++) {
+ //
+ ClientName(teammates[numteammates - i - 1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[numteammates - i - 1]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_GETFLAG);
+ }
+ //
+ break;
+ }
+ }
+ }
+ else {
+ //different orders based on the number of team mates
+ switch(bs->numteammates) {
+ case 1: break;
+ case 2:
+ {
+ //both will go for the enemy flag
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_GETFLAG);
+ //
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_GETFLAG);
+ break;
+ }
+ case 3:
+ {
+ //everyone go for the flag
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_GETFLAG);
+ //
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_GETFLAG);
+ //
+ ClientName(teammates[2], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[2]);
+ BotSayVoiceTeamOrder(bs, teammates[2], VOICECHAT_GETFLAG);
+ break;
+ }
+ default:
+ {
+ //keep some people near the base for when the flag is returned
+ defenders = (int) (float) numteammates * 0.2 + 0.5;
+ if (defenders > 2) defenders = 2;
+ attackers = (int) (float) numteammates * 0.7 + 0.5;
+ if (attackers > 7) attackers = 7;
+ for (i = 0; i < defenders; i++) {
+ //
+ ClientName(teammates[i], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[i]);
+ BotSayVoiceTeamOrder(bs, teammates[i], VOICECHAT_DEFEND);
+ }
+ for (i = 0; i < attackers; i++) {
+ //
+ ClientName(teammates[numteammates - i - 1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[numteammates - i - 1]);
+ BotSayVoiceTeamOrder(bs, teammates[numteammates - i - 1], VOICECHAT_GETFLAG);
+ }
+ //
+ break;
+ }
+ }
+ }
+}
+
+/*
+==================
+BotCTFOrders
+==================
+*/
+void BotCTFOrders_EnemyFlagNotAtBase(bot_state_t *bs) {
+ int numteammates, defenders, attackers, i, other;
+ int teammates[MAX_CLIENTS];
+ char name[MAX_NETNAME], carriername[MAX_NETNAME];
+
+ numteammates = BotSortTeamMatesByBaseTravelTime(bs, teammates, sizeof(teammates));
+ BotSortTeamMatesByTaskPreference(bs, teammates, numteammates);
+ //different orders based on the number of team mates
+ switch(numteammates) {
+ case 1: break;
+ case 2:
+ {
+ //tell the one not carrying the flag to defend the base
+ if (teammates[0] == bs->flagcarrier) other = teammates[1];
+ else other = teammates[0];
+ ClientName(other, name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, other);
+ BotSayVoiceTeamOrder(bs, other, VOICECHAT_DEFEND);
+ break;
+ }
+ case 3:
+ {
+ //tell the one closest to the base not carrying the flag to defend the base
+ if (teammates[0] != bs->flagcarrier) other = teammates[0];
+ else other = teammates[1];
+ ClientName(other, name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, other);
+ BotSayVoiceTeamOrder(bs, other, VOICECHAT_DEFEND);
+ //tell the other also to defend the base
+ if (teammates[2] != bs->flagcarrier) other = teammates[2];
+ else other = teammates[1];
+ ClientName(other, name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, other);
+ BotSayVoiceTeamOrder(bs, other, VOICECHAT_DEFEND);
+ break;
+ }
+ default:
+ {
+ //60% will defend the base
+ defenders = (int) (float) numteammates * 0.6 + 0.5;
+ if (defenders > 6) defenders = 6;
+ //30% accompanies the flag carrier
+ attackers = (int) (float) numteammates * 0.3 + 0.5;
+ if (attackers > 3) attackers = 3;
+ for (i = 0; i < defenders; i++) {
+ //
+ if (teammates[i] == bs->flagcarrier) {
+ continue;
+ }
+ ClientName(teammates[i], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[i]);
+ BotSayVoiceTeamOrder(bs, teammates[i], VOICECHAT_DEFEND);
+ }
+ // if we have a flag carrier
+ if ( bs->flagcarrier != -1 ) {
+ ClientName(bs->flagcarrier, carriername, sizeof(carriername));
+ for (i = 0; i < attackers; i++) {
+ //
+ if (teammates[numteammates - i - 1] == bs->flagcarrier) {
+ continue;
+ }
+ //
+ ClientName(teammates[numteammates - i - 1], name, sizeof(name));
+ if (bs->flagcarrier == bs->client) {
+ BotAI_BotInitialChat(bs, "cmd_accompanyme", name, NULL);
+ BotSayVoiceTeamOrder(bs, teammates[numteammates - i - 1], VOICECHAT_FOLLOWME);
+ }
+ else {
+ BotAI_BotInitialChat(bs, "cmd_accompany", name, carriername, NULL);
+ BotSayVoiceTeamOrder(bs, teammates[numteammates - i - 1], VOICECHAT_FOLLOWFLAGCARRIER);
+ }
+ BotSayTeamOrder(bs, teammates[numteammates - i - 1]);
+ }
+ }
+ else {
+ for (i = 0; i < attackers; i++) {
+ //
+ if (teammates[numteammates - i - 1] == bs->flagcarrier) {
+ continue;
+ }
+ //
+ ClientName(teammates[numteammates - i - 1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayVoiceTeamOrder(bs, teammates[numteammates - i - 1], VOICECHAT_GETFLAG);
+ BotSayTeamOrder(bs, teammates[numteammates - i - 1]);
+ }
+ }
+ //
+ break;
+ }
+ }
+}
+
+
+/*
+==================
+BotCTFOrders
+==================
+*/
+void BotCTFOrders_BothFlagsAtBase(bot_state_t *bs) {
+ int numteammates, defenders, attackers, i;
+ int teammates[MAX_CLIENTS];
+ char name[MAX_NETNAME];
+
+ //sort team mates by travel time to base
+ numteammates = BotSortTeamMatesByBaseTravelTime(bs, teammates, sizeof(teammates));
+ //sort team mates by CTF preference
+ BotSortTeamMatesByTaskPreference(bs, teammates, numteammates);
+ //passive strategy
+ if (!(bs->ctfstrategy & CTFS_AGRESSIVE)) {
+ //different orders based on the number of team mates
+ switch(numteammates) {
+ case 1: break;
+ case 2:
+ {
+ //the one closest to the base will defend the base
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the other will get the flag
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_GETFLAG);
+ break;
+ }
+ case 3:
+ {
+ //the one closest to the base will defend the base
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the second one closest to the base will defend the base
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_DEFEND);
+ //the other will get the flag
+ ClientName(teammates[2], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[2]);
+ BotSayVoiceTeamOrder(bs, teammates[2], VOICECHAT_GETFLAG);
+ break;
+ }
+ default:
+ {
+ defenders = (int) (float) numteammates * 0.5 + 0.5;
+ if (defenders > 5) defenders = 5;
+ attackers = (int) (float) numteammates * 0.4 + 0.5;
+ if (attackers > 4) attackers = 4;
+ for (i = 0; i < defenders; i++) {
+ //
+ ClientName(teammates[i], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[i]);
+ BotSayVoiceTeamOrder(bs, teammates[i], VOICECHAT_DEFEND);
+ }
+ for (i = 0; i < attackers; i++) {
+ //
+ ClientName(teammates[numteammates - i - 1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[numteammates - i - 1]);
+ BotSayVoiceTeamOrder(bs, teammates[numteammates - i - 1], VOICECHAT_GETFLAG);
+ }
+ //
+ break;
+ }
+ }
+ }
+ else {
+ //different orders based on the number of team mates
+ switch(numteammates) {
+ case 1: break;
+ case 2:
+ {
+ //the one closest to the base will defend the base
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the other will get the flag
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_GETFLAG);
+ break;
+ }
+ case 3:
+ {
+ //the one closest to the base will defend the base
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the others should go for the enemy flag
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_GETFLAG);
+ //
+ ClientName(teammates[2], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[2]);
+ BotSayVoiceTeamOrder(bs, teammates[2], VOICECHAT_GETFLAG);
+ break;
+ }
+ default:
+ {
+ defenders = (int) (float) numteammates * 0.4 + 0.5;
+ if (defenders > 4) defenders = 4;
+ attackers = (int) (float) numteammates * 0.5 + 0.5;
+ if (attackers > 5) attackers = 5;
+ for (i = 0; i < defenders; i++) {
+ //
+ ClientName(teammates[i], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[i]);
+ BotSayVoiceTeamOrder(bs, teammates[i], VOICECHAT_DEFEND);
+ }
+ for (i = 0; i < attackers; i++) {
+ //
+ ClientName(teammates[numteammates - i - 1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[numteammates - i - 1]);
+ BotSayVoiceTeamOrder(bs, teammates[numteammates - i - 1], VOICECHAT_GETFLAG);
+ }
+ //
+ break;
+ }
+ }
+ }
+}
+
+/*
+==================
+BotCTFOrders
+==================
+*/
+void BotCTFOrders(bot_state_t *bs) {
+ int flagstatus;
+
+ //
+ if (BotTeam(bs) == TEAM_RED) flagstatus = bs->redflagstatus * 2 + bs->blueflagstatus;
+ else flagstatus = bs->blueflagstatus * 2 + bs->redflagstatus;
+ //
+ switch(flagstatus) {
+ case 0: BotCTFOrders_BothFlagsAtBase(bs); break;
+ case 1: BotCTFOrders_EnemyFlagNotAtBase(bs); break;
+ case 2: BotCTFOrders_FlagNotAtBase(bs); break;
+ case 3: BotCTFOrders_BothFlagsNotAtBase(bs); break;
+ }
+}
+
+
+/*
+==================
+BotCreateGroup
+==================
+*/
+void BotCreateGroup(bot_state_t *bs, int *teammates, int groupsize) {
+ char name[MAX_NETNAME], leadername[MAX_NETNAME];
+ int i;
+
+ // the others in the group will follow the teammates[0]
+ ClientName(teammates[0], leadername, sizeof(leadername));
+ for (i = 1; i < groupsize; i++)
+ {
+ ClientName(teammates[i], name, sizeof(name));
+ if (teammates[0] == bs->client) {
+ BotAI_BotInitialChat(bs, "cmd_accompanyme", name, NULL);
+ }
+ else {
+ BotAI_BotInitialChat(bs, "cmd_accompany", name, leadername, NULL);
+ }
+ BotSayTeamOrderAlways(bs, teammates[i]);
+ }
+}
+
+/*
+==================
+BotTeamOrders
+
+ FIXME: defend key areas?
+==================
+*/
+void BotTeamOrders(bot_state_t *bs) {
+ int teammates[MAX_CLIENTS];
+ int numteammates, i;
+ char buf[MAX_INFO_STRING];
+ static int maxclients;
+
+ if (!maxclients)
+ maxclients = trap_Cvar_VariableIntegerValue("sv_maxclients");
+
+ numteammates = 0;
+ for (i = 0; i < maxclients && i < MAX_CLIENTS; i++) {
+ trap_GetConfigstring(CS_PLAYERS+i, buf, sizeof(buf));
+ //if no config string or no name
+ if (!strlen(buf) || !strlen(Info_ValueForKey(buf, "n"))) continue;
+ //skip spectators
+ if (atoi(Info_ValueForKey(buf, "t")) == TEAM_SPECTATOR) continue;
+ //
+ if (BotSameTeam(bs, i)) {
+ teammates[numteammates] = i;
+ numteammates++;
+ }
+ }
+ //
+ switch(numteammates) {
+ case 1: break;
+ case 2:
+ {
+ //nothing special
+ break;
+ }
+ case 3:
+ {
+ //have one follow another and one free roaming
+ BotCreateGroup(bs, teammates, 2);
+ break;
+ }
+ case 4:
+ {
+ BotCreateGroup(bs, teammates, 2); //a group of 2
+ BotCreateGroup(bs, &teammates[2], 2); //a group of 2
+ break;
+ }
+ case 5:
+ {
+ BotCreateGroup(bs, teammates, 2); //a group of 2
+ BotCreateGroup(bs, &teammates[2], 3); //a group of 3
+ break;
+ }
+ default:
+ {
+ if (numteammates <= 10) {
+ for (i = 0; i < numteammates / 2; i++) {
+ BotCreateGroup(bs, &teammates[i*2], 2); //groups of 2
+ }
+ }
+ break;
+ }
+ }
+}
+
+#ifdef MISSIONPACK
+
+/*
+==================
+Bot1FCTFOrders_FlagAtCenter
+
+ X% defend the base, Y% get the flag
+==================
+*/
+void Bot1FCTFOrders_FlagAtCenter(bot_state_t *bs) {
+ int numteammates, defenders, attackers, i;
+ int teammates[MAX_CLIENTS];
+ char name[MAX_NETNAME];
+
+ //sort team mates by travel time to base
+ numteammates = BotSortTeamMatesByBaseTravelTime(bs, teammates, sizeof(teammates));
+ //sort team mates by CTF preference
+ BotSortTeamMatesByTaskPreference(bs, teammates, numteammates);
+ //passive strategy
+ if (!(bs->ctfstrategy & CTFS_AGRESSIVE)) {
+ //different orders based on the number of team mates
+ switch(numteammates) {
+ case 1: break;
+ case 2:
+ {
+ //the one closest to the base will defend the base
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the other will get the flag
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_GETFLAG);
+ break;
+ }
+ case 3:
+ {
+ //the one closest to the base will defend the base
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the second one closest to the base will defend the base
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the other will get the flag
+ ClientName(teammates[2], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[2]);
+ BotSayVoiceTeamOrder(bs, teammates[2], VOICECHAT_GETFLAG);
+ break;
+ }
+ default:
+ {
+ //50% defend the base
+ defenders = (int) (float) numteammates * 0.5 + 0.5;
+ if (defenders > 5) defenders = 5;
+ //40% get the flag
+ attackers = (int) (float) numteammates * 0.4 + 0.5;
+ if (attackers > 4) attackers = 4;
+ for (i = 0; i < defenders; i++) {
+ //
+ ClientName(teammates[i], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[i]);
+ BotSayVoiceTeamOrder(bs, teammates[i], VOICECHAT_DEFEND);
+ }
+ for (i = 0; i < attackers; i++) {
+ //
+ ClientName(teammates[numteammates - i - 1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[numteammates - i - 1]);
+ BotSayVoiceTeamOrder(bs, teammates[numteammates - i - 1], VOICECHAT_GETFLAG);
+ }
+ //
+ break;
+ }
+ }
+ }
+ else { //agressive
+ //different orders based on the number of team mates
+ switch(numteammates) {
+ case 1: break;
+ case 2:
+ {
+ //the one closest to the base will defend the base
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the other will get the flag
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_GETFLAG);
+ break;
+ }
+ case 3:
+ {
+ //the one closest to the base will defend the base
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the others should go for the enemy flag
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_GETFLAG);
+ //
+ ClientName(teammates[2], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[2]);
+ BotSayVoiceTeamOrder(bs, teammates[2], VOICECHAT_GETFLAG);
+ break;
+ }
+ default:
+ {
+ //30% defend the base
+ defenders = (int) (float) numteammates * 0.3 + 0.5;
+ if (defenders > 3) defenders = 3;
+ //60% get the flag
+ attackers = (int) (float) numteammates * 0.6 + 0.5;
+ if (attackers > 6) attackers = 6;
+ for (i = 0; i < defenders; i++) {
+ //
+ ClientName(teammates[i], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[i]);
+ BotSayVoiceTeamOrder(bs, teammates[i], VOICECHAT_DEFEND);
+ }
+ for (i = 0; i < attackers; i++) {
+ //
+ ClientName(teammates[numteammates - i - 1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[numteammates - i - 1]);
+ BotSayVoiceTeamOrder(bs, teammates[numteammates - i - 1], VOICECHAT_GETFLAG);
+ }
+ //
+ break;
+ }
+ }
+ }
+}
+
+/*
+==================
+Bot1FCTFOrders_TeamHasFlag
+
+ X% towards neutral flag, Y% go towards enemy base and accompany flag carrier if visible
+==================
+*/
+void Bot1FCTFOrders_TeamHasFlag(bot_state_t *bs) {
+ int numteammates, defenders, attackers, i, other;
+ int teammates[MAX_CLIENTS];
+ char name[MAX_NETNAME], carriername[MAX_NETNAME];
+
+ //sort team mates by travel time to base
+ numteammates = BotSortTeamMatesByBaseTravelTime(bs, teammates, sizeof(teammates));
+ //sort team mates by CTF preference
+ BotSortTeamMatesByTaskPreference(bs, teammates, numteammates);
+ //passive strategy
+ if (!(bs->ctfstrategy & CTFS_AGRESSIVE)) {
+ //different orders based on the number of team mates
+ switch(numteammates) {
+ case 1: break;
+ case 2:
+ {
+ //tell the one not carrying the flag to attack the enemy base
+ if (teammates[0] == bs->flagcarrier) other = teammates[1];
+ else other = teammates[0];
+ ClientName(other, name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_attackenemybase", name, NULL);
+ BotSayTeamOrder(bs, other);
+ BotSayVoiceTeamOrder(bs, other, VOICECHAT_OFFENSE);
+ break;
+ }
+ case 3:
+ {
+ //tell the one closest to the base not carrying the flag to defend the base
+ if (teammates[0] != bs->flagcarrier) other = teammates[0];
+ else other = teammates[1];
+ ClientName(other, name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, other);
+ BotSayVoiceTeamOrder(bs, other, VOICECHAT_DEFEND);
+ //tell the one furthest from the base not carrying the flag to accompany the flag carrier
+ if (teammates[2] != bs->flagcarrier) other = teammates[2];
+ else other = teammates[1];
+ ClientName(other, name, sizeof(name));
+ if ( bs->flagcarrier != -1 ) {
+ ClientName(bs->flagcarrier, carriername, sizeof(carriername));
+ if (bs->flagcarrier == bs->client) {
+ BotAI_BotInitialChat(bs, "cmd_accompanyme", name, NULL);
+ BotSayVoiceTeamOrder(bs, other, VOICECHAT_FOLLOWME);
+ }
+ else {
+ BotAI_BotInitialChat(bs, "cmd_accompany", name, carriername, NULL);
+ BotSayVoiceTeamOrder(bs, other, VOICECHAT_FOLLOWFLAGCARRIER);
+ }
+ }
+ else {
+ //
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayVoiceTeamOrder(bs, other, VOICECHAT_GETFLAG);
+ }
+ BotSayTeamOrder(bs, other);
+ break;
+ }
+ default:
+ {
+ //30% will defend the base
+ defenders = (int) (float) numteammates * 0.3 + 0.5;
+ if (defenders > 3) defenders = 3;
+ //70% accompanies the flag carrier
+ attackers = (int) (float) numteammates * 0.7 + 0.5;
+ if (attackers > 7) attackers = 7;
+ for (i = 0; i < defenders; i++) {
+ //
+ if (teammates[i] == bs->flagcarrier) {
+ continue;
+ }
+ ClientName(teammates[i], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[i]);
+ BotSayVoiceTeamOrder(bs, teammates[i], VOICECHAT_DEFEND);
+ }
+ if (bs->flagcarrier != -1) {
+ ClientName(bs->flagcarrier, carriername, sizeof(carriername));
+ for (i = 0; i < attackers; i++) {
+ //
+ if (teammates[numteammates - i - 1] == bs->flagcarrier) {
+ continue;
+ }
+ //
+ ClientName(teammates[numteammates - i - 1], name, sizeof(name));
+ if (bs->flagcarrier == bs->client) {
+ BotAI_BotInitialChat(bs, "cmd_accompanyme", name, NULL);
+ BotSayVoiceTeamOrder(bs, teammates[numteammates - i - 1], VOICECHAT_FOLLOWME);
+ }
+ else {
+ BotAI_BotInitialChat(bs, "cmd_accompany", name, carriername, NULL);
+ BotSayVoiceTeamOrder(bs, teammates[numteammates - i - 1], VOICECHAT_FOLLOWFLAGCARRIER);
+ }
+ BotSayTeamOrder(bs, teammates[numteammates - i - 1]);
+ }
+ }
+ else {
+ for (i = 0; i < attackers; i++) {
+ //
+ if (teammates[numteammates - i - 1] == bs->flagcarrier) {
+ continue;
+ }
+ //
+ ClientName(teammates[numteammates - i - 1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[numteammates - i - 1]);
+ BotSayVoiceTeamOrder(bs, teammates[numteammates - i - 1], VOICECHAT_GETFLAG);
+ }
+ }
+ //
+ break;
+ }
+ }
+ }
+ else { //agressive
+ //different orders based on the number of team mates
+ switch(numteammates) {
+ case 1: break;
+ case 2:
+ {
+ //tell the one not carrying the flag to defend the base
+ if (teammates[0] == bs->flagcarrier) other = teammates[1];
+ else other = teammates[0];
+ ClientName(other, name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, other);
+ BotSayVoiceTeamOrder(bs, other, VOICECHAT_DEFEND);
+ break;
+ }
+ case 3:
+ {
+ //tell the one closest to the base not carrying the flag to defend the base
+ if (teammates[0] != bs->flagcarrier) other = teammates[0];
+ else other = teammates[1];
+ ClientName(other, name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, other);
+ BotSayVoiceTeamOrder(bs, other, VOICECHAT_DEFEND);
+ //tell the one furthest from the base not carrying the flag to accompany the flag carrier
+ if (teammates[2] != bs->flagcarrier) other = teammates[2];
+ else other = teammates[1];
+ ClientName(other, name, sizeof(name));
+ ClientName(bs->flagcarrier, carriername, sizeof(carriername));
+ if (bs->flagcarrier == bs->client) {
+ BotAI_BotInitialChat(bs, "cmd_accompanyme", name, NULL);
+ BotSayVoiceTeamOrder(bs, other, VOICECHAT_FOLLOWME);
+ }
+ else {
+ BotAI_BotInitialChat(bs, "cmd_accompany", name, carriername, NULL);
+ BotSayVoiceTeamOrder(bs, other, VOICECHAT_FOLLOWFLAGCARRIER);
+ }
+ BotSayTeamOrder(bs, other);
+ break;
+ }
+ default:
+ {
+ //20% will defend the base
+ defenders = (int) (float) numteammates * 0.2 + 0.5;
+ if (defenders > 2) defenders = 2;
+ //80% accompanies the flag carrier
+ attackers = (int) (float) numteammates * 0.8 + 0.5;
+ if (attackers > 8) attackers = 8;
+ for (i = 0; i < defenders; i++) {
+ //
+ if (teammates[i] == bs->flagcarrier) {
+ continue;
+ }
+ ClientName(teammates[i], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[i]);
+ BotSayVoiceTeamOrder(bs, teammates[i], VOICECHAT_DEFEND);
+ }
+ ClientName(bs->flagcarrier, carriername, sizeof(carriername));
+ for (i = 0; i < attackers; i++) {
+ //
+ if (teammates[numteammates - i - 1] == bs->flagcarrier) {
+ continue;
+ }
+ //
+ ClientName(teammates[numteammates - i - 1], name, sizeof(name));
+ if (bs->flagcarrier == bs->client) {
+ BotAI_BotInitialChat(bs, "cmd_accompanyme", name, NULL);
+ BotSayVoiceTeamOrder(bs, teammates[numteammates - i - 1], VOICECHAT_FOLLOWME);
+ }
+ else {
+ BotAI_BotInitialChat(bs, "cmd_accompany", name, carriername, NULL);
+ BotSayVoiceTeamOrder(bs, teammates[numteammates - i - 1], VOICECHAT_FOLLOWFLAGCARRIER);
+ }
+ BotSayTeamOrder(bs, teammates[numteammates - i - 1]);
+ }
+ //
+ break;
+ }
+ }
+ }
+}
+
+/*
+==================
+Bot1FCTFOrders_EnemyHasFlag
+
+ X% defend the base, Y% towards neutral flag
+==================
+*/
+void Bot1FCTFOrders_EnemyHasFlag(bot_state_t *bs) {
+ int numteammates, defenders, attackers, i;
+ int teammates[MAX_CLIENTS];
+ char name[MAX_NETNAME];
+
+ //sort team mates by travel time to base
+ numteammates = BotSortTeamMatesByBaseTravelTime(bs, teammates, sizeof(teammates));
+ //sort team mates by CTF preference
+ BotSortTeamMatesByTaskPreference(bs, teammates, numteammates);
+ //passive strategy
+ if (!(bs->ctfstrategy & CTFS_AGRESSIVE)) {
+ //different orders based on the number of team mates
+ switch(numteammates) {
+ case 1: break;
+ case 2:
+ {
+ //both defend the base
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_DEFEND);
+ break;
+ }
+ case 3:
+ {
+ //the one closest to the base will defend the base
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the second one closest to the base will defend the base
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_DEFEND);
+ //the other will also defend the base
+ ClientName(teammates[2], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[2]);
+ BotSayVoiceTeamOrder(bs, teammates[2], VOICECHAT_DEFEND);
+ break;
+ }
+ default:
+ {
+ //80% will defend the base
+ defenders = (int) (float) numteammates * 0.8 + 0.5;
+ if (defenders > 8) defenders = 8;
+ //10% will try to return the flag
+ attackers = (int) (float) numteammates * 0.1 + 0.5;
+ if (attackers > 2) attackers = 2;
+ for (i = 0; i < defenders; i++) {
+ //
+ ClientName(teammates[i], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[i]);
+ BotSayVoiceTeamOrder(bs, teammates[i], VOICECHAT_DEFEND);
+ }
+ for (i = 0; i < attackers; i++) {
+ //
+ ClientName(teammates[numteammates - i - 1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_returnflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[numteammates - i - 1]);
+ BotSayVoiceTeamOrder(bs, teammates[numteammates - i - 1], VOICECHAT_GETFLAG);
+ }
+ //
+ break;
+ }
+ }
+ }
+ else { //agressive
+ //different orders based on the number of team mates
+ switch(numteammates) {
+ case 1: break;
+ case 2:
+ {
+ //the one closest to the base will defend the base
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the other will get the flag
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_DEFEND);
+ break;
+ }
+ case 3:
+ {
+ //the one closest to the base will defend the base
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the others should go for the enemy flag
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_DEFEND);
+ //
+ ClientName(teammates[2], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_returnflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[2]);
+ BotSayVoiceTeamOrder(bs, teammates[2], VOICECHAT_GETFLAG);
+ break;
+ }
+ default:
+ {
+ //70% defend the base
+ defenders = (int) (float) numteammates * 0.7 + 0.5;
+ if (defenders > 8) defenders = 8;
+ //20% try to return the flag
+ attackers = (int) (float) numteammates * 0.2 + 0.5;
+ if (attackers > 2) attackers = 2;
+ for (i = 0; i < defenders; i++) {
+ //
+ ClientName(teammates[i], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[i]);
+ BotSayVoiceTeamOrder(bs, teammates[i], VOICECHAT_DEFEND);
+ }
+ for (i = 0; i < attackers; i++) {
+ //
+ ClientName(teammates[numteammates - i - 1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_returnflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[numteammates - i - 1]);
+ BotSayVoiceTeamOrder(bs, teammates[numteammates - i - 1], VOICECHAT_GETFLAG);
+ }
+ //
+ break;
+ }
+ }
+ }
+}
+
+/*
+==================
+Bot1FCTFOrders_EnemyDroppedFlag
+
+ X% defend the base, Y% get the flag
+==================
+*/
+void Bot1FCTFOrders_EnemyDroppedFlag(bot_state_t *bs) {
+ int numteammates, defenders, attackers, i;
+ int teammates[MAX_CLIENTS];
+ char name[MAX_NETNAME];
+
+ //sort team mates by travel time to base
+ numteammates = BotSortTeamMatesByBaseTravelTime(bs, teammates, sizeof(teammates));
+ //sort team mates by CTF preference
+ BotSortTeamMatesByTaskPreference(bs, teammates, numteammates);
+ //passive strategy
+ if (!(bs->ctfstrategy & CTFS_AGRESSIVE)) {
+ //different orders based on the number of team mates
+ switch(numteammates) {
+ case 1: break;
+ case 2:
+ {
+ //the one closest to the base will defend the base
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the other will get the flag
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_GETFLAG);
+ break;
+ }
+ case 3:
+ {
+ //the one closest to the base will defend the base
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the second one closest to the base will defend the base
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_DEFEND);
+ //the other will get the flag
+ ClientName(teammates[2], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[2]);
+ BotSayVoiceTeamOrder(bs, teammates[2], VOICECHAT_GETFLAG);
+ break;
+ }
+ default:
+ {
+ //50% defend the base
+ defenders = (int) (float) numteammates * 0.5 + 0.5;
+ if (defenders > 5) defenders = 5;
+ //40% get the flag
+ attackers = (int) (float) numteammates * 0.4 + 0.5;
+ if (attackers > 4) attackers = 4;
+ for (i = 0; i < defenders; i++) {
+ //
+ ClientName(teammates[i], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[i]);
+ BotSayVoiceTeamOrder(bs, teammates[i], VOICECHAT_DEFEND);
+ }
+ for (i = 0; i < attackers; i++) {
+ //
+ ClientName(teammates[numteammates - i - 1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[numteammates - i - 1]);
+ BotSayVoiceTeamOrder(bs, teammates[numteammates - i - 1], VOICECHAT_GETFLAG);
+ }
+ //
+ break;
+ }
+ }
+ }
+ else { //agressive
+ //different orders based on the number of team mates
+ switch(numteammates) {
+ case 1: break;
+ case 2:
+ {
+ //the one closest to the base will defend the base
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the other will get the flag
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_GETFLAG);
+ break;
+ }
+ case 3:
+ {
+ //the one closest to the base will defend the base
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the others should go for the enemy flag
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_GETFLAG);
+ //
+ ClientName(teammates[2], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[2]);
+ BotSayVoiceTeamOrder(bs, teammates[2], VOICECHAT_GETFLAG);
+ break;
+ }
+ default:
+ {
+ //30% defend the base
+ defenders = (int) (float) numteammates * 0.3 + 0.5;
+ if (defenders > 3) defenders = 3;
+ //60% get the flag
+ attackers = (int) (float) numteammates * 0.6 + 0.5;
+ if (attackers > 6) attackers = 6;
+ for (i = 0; i < defenders; i++) {
+ //
+ ClientName(teammates[i], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[i]);
+ BotSayVoiceTeamOrder(bs, teammates[i], VOICECHAT_DEFEND);
+ }
+ for (i = 0; i < attackers; i++) {
+ //
+ ClientName(teammates[numteammates - i - 1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_getflag", name, NULL);
+ BotSayTeamOrder(bs, teammates[numteammates - i - 1]);
+ BotSayVoiceTeamOrder(bs, teammates[numteammates - i - 1], VOICECHAT_DEFEND);
+ }
+ //
+ break;
+ }
+ }
+ }
+}
+
+/*
+==================
+Bot1FCTFOrders
+==================
+*/
+void Bot1FCTFOrders(bot_state_t *bs) {
+ switch(bs->neutralflagstatus) {
+ case 0: Bot1FCTFOrders_FlagAtCenter(bs); break;
+ case 1: Bot1FCTFOrders_TeamHasFlag(bs); break;
+ case 2: Bot1FCTFOrders_EnemyHasFlag(bs); break;
+ case 3: Bot1FCTFOrders_EnemyDroppedFlag(bs); break;
+ }
+}
+
+/*
+==================
+BotObeliskOrders
+
+ X% in defence Y% in offence
+==================
+*/
+void BotObeliskOrders(bot_state_t *bs) {
+ int numteammates, defenders, attackers, i;
+ int teammates[MAX_CLIENTS];
+ char name[MAX_NETNAME];
+
+ //sort team mates by travel time to base
+ numteammates = BotSortTeamMatesByBaseTravelTime(bs, teammates, sizeof(teammates));
+ //sort team mates by CTF preference
+ BotSortTeamMatesByTaskPreference(bs, teammates, numteammates);
+ //passive strategy
+ if (!(bs->ctfstrategy & CTFS_AGRESSIVE)) {
+ //different orders based on the number of team mates
+ switch(numteammates) {
+ case 1: break;
+ case 2:
+ {
+ //the one closest to the base will defend the base
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the other will attack the enemy base
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_attackenemybase", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_OFFENSE);
+ break;
+ }
+ case 3:
+ {
+ //the one closest to the base will defend the base
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the one second closest to the base also defends the base
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_DEFEND);
+ //the other one attacks the enemy base
+ ClientName(teammates[2], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_attackenemybase", name, NULL);
+ BotSayTeamOrder(bs, teammates[2]);
+ BotSayVoiceTeamOrder(bs, teammates[2], VOICECHAT_OFFENSE);
+ break;
+ }
+ default:
+ {
+ //50% defend the base
+ defenders = (int) (float) numteammates * 0.5 + 0.5;
+ if (defenders > 5) defenders = 5;
+ //40% attack the enemy base
+ attackers = (int) (float) numteammates * 0.4 + 0.5;
+ if (attackers > 4) attackers = 4;
+ for (i = 0; i < defenders; i++) {
+ //
+ ClientName(teammates[i], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[i]);
+ BotSayVoiceTeamOrder(bs, teammates[i], VOICECHAT_DEFEND);
+ }
+ for (i = 0; i < attackers; i++) {
+ //
+ ClientName(teammates[numteammates - i - 1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_attackenemybase", name, NULL);
+ BotSayTeamOrder(bs, teammates[numteammates - i - 1]);
+ BotSayVoiceTeamOrder(bs, teammates[numteammates - i - 1], VOICECHAT_OFFENSE);
+ }
+ //
+ break;
+ }
+ }
+ }
+ else {
+ //different orders based on the number of team mates
+ switch(numteammates) {
+ case 1: break;
+ case 2:
+ {
+ //the one closest to the base will defend the base
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the other will attack the enemy base
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_attackenemybase", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_OFFENSE);
+ break;
+ }
+ case 3:
+ {
+ //the one closest to the base will defend the base
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the others attack the enemy base
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_attackenemybase", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_OFFENSE);
+ //
+ ClientName(teammates[2], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_attackenemybase", name, NULL);
+ BotSayTeamOrder(bs, teammates[2]);
+ BotSayVoiceTeamOrder(bs, teammates[2], VOICECHAT_OFFENSE);
+ break;
+ }
+ default:
+ {
+ //30% defend the base
+ defenders = (int) (float) numteammates * 0.3 + 0.5;
+ if (defenders > 3) defenders = 3;
+ //70% attack the enemy base
+ attackers = (int) (float) numteammates * 0.7 + 0.5;
+ if (attackers > 7) attackers = 7;
+ for (i = 0; i < defenders; i++) {
+ //
+ ClientName(teammates[i], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[i]);
+ BotSayVoiceTeamOrder(bs, teammates[i], VOICECHAT_DEFEND);
+ }
+ for (i = 0; i < attackers; i++) {
+ //
+ ClientName(teammates[numteammates - i - 1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_attackenemybase", name, NULL);
+ BotSayTeamOrder(bs, teammates[numteammates - i - 1]);
+ BotSayVoiceTeamOrder(bs, teammates[numteammates - i - 1], VOICECHAT_OFFENSE);
+ }
+ //
+ break;
+ }
+ }
+ }
+}
+
+/*
+==================
+BotHarvesterOrders
+
+ X% defend the base, Y% harvest
+==================
+*/
+void BotHarvesterOrders(bot_state_t *bs) {
+ int numteammates, defenders, attackers, i;
+ int teammates[MAX_CLIENTS];
+ char name[MAX_NETNAME];
+
+ //sort team mates by travel time to base
+ numteammates = BotSortTeamMatesByBaseTravelTime(bs, teammates, sizeof(teammates));
+ //sort team mates by CTF preference
+ BotSortTeamMatesByTaskPreference(bs, teammates, numteammates);
+ //passive strategy
+ if (!(bs->ctfstrategy & CTFS_AGRESSIVE)) {
+ //different orders based on the number of team mates
+ switch(numteammates) {
+ case 1: break;
+ case 2:
+ {
+ //the one closest to the base will defend the base
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the other will harvest
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_harvest", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_OFFENSE);
+ break;
+ }
+ case 3:
+ {
+ //the one closest to the base will defend the base
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the one second closest to the base also defends the base
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_DEFEND);
+ //the other one goes harvesting
+ ClientName(teammates[2], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_harvest", name, NULL);
+ BotSayTeamOrder(bs, teammates[2]);
+ BotSayVoiceTeamOrder(bs, teammates[2], VOICECHAT_OFFENSE);
+ break;
+ }
+ default:
+ {
+ //50% defend the base
+ defenders = (int) (float) numteammates * 0.5 + 0.5;
+ if (defenders > 5) defenders = 5;
+ //40% goes harvesting
+ attackers = (int) (float) numteammates * 0.4 + 0.5;
+ if (attackers > 4) attackers = 4;
+ for (i = 0; i < defenders; i++) {
+ //
+ ClientName(teammates[i], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[i]);
+ BotSayVoiceTeamOrder(bs, teammates[i], VOICECHAT_DEFEND);
+ }
+ for (i = 0; i < attackers; i++) {
+ //
+ ClientName(teammates[numteammates - i - 1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_harvest", name, NULL);
+ BotSayTeamOrder(bs, teammates[numteammates - i - 1]);
+ BotSayVoiceTeamOrder(bs, teammates[numteammates - i - 1], VOICECHAT_OFFENSE);
+ }
+ //
+ break;
+ }
+ }
+ }
+ else {
+ //different orders based on the number of team mates
+ switch(numteammates) {
+ case 1: break;
+ case 2:
+ {
+ //the one closest to the base will defend the base
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the other will harvest
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_harvest", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_OFFENSE);
+ break;
+ }
+ case 3:
+ {
+ //the one closest to the base will defend the base
+ ClientName(teammates[0], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[0]);
+ BotSayVoiceTeamOrder(bs, teammates[0], VOICECHAT_DEFEND);
+ //the others go harvesting
+ ClientName(teammates[1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_harvest", name, NULL);
+ BotSayTeamOrder(bs, teammates[1]);
+ BotSayVoiceTeamOrder(bs, teammates[1], VOICECHAT_OFFENSE);
+ //
+ ClientName(teammates[2], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_harvest", name, NULL);
+ BotSayTeamOrder(bs, teammates[2]);
+ BotSayVoiceTeamOrder(bs, teammates[2], VOICECHAT_OFFENSE);
+ break;
+ }
+ default:
+ {
+ //30% defend the base
+ defenders = (int) (float) numteammates * 0.3 + 0.5;
+ if (defenders > 3) defenders = 3;
+ //70% go harvesting
+ attackers = (int) (float) numteammates * 0.7 + 0.5;
+ if (attackers > 7) attackers = 7;
+ for (i = 0; i < defenders; i++) {
+ //
+ ClientName(teammates[i], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_defendbase", name, NULL);
+ BotSayTeamOrder(bs, teammates[i]);
+ BotSayVoiceTeamOrder(bs, teammates[i], VOICECHAT_DEFEND);
+ }
+ for (i = 0; i < attackers; i++) {
+ //
+ ClientName(teammates[numteammates - i - 1], name, sizeof(name));
+ BotAI_BotInitialChat(bs, "cmd_harvest", name, NULL);
+ BotSayTeamOrder(bs, teammates[numteammates - i - 1]);
+ BotSayVoiceTeamOrder(bs, teammates[numteammates - i - 1], VOICECHAT_OFFENSE);
+ }
+ //
+ break;
+ }
+ }
+ }
+}
+#endif
+
+/*
+==================
+FindHumanTeamLeader
+==================
+*/
+int FindHumanTeamLeader(bot_state_t *bs) {
+ int i;
+
+ for (i = 0; i < MAX_CLIENTS; i++) {
+ if ( g_entities[i].inuse ) {
+ // if this player is not a bot
+ if ( !(g_entities[i].r.svFlags & SVF_BOT) ) {
+ // if this player is ok with being the leader
+ if (!notleader[i]) {
+ // if this player is on the same team
+ if ( BotSameTeam(bs, i) ) {
+ ClientName(i, bs->teamleader, sizeof(bs->teamleader));
+ // if not yet ordered to do anything
+ if ( !BotSetLastOrderedTask(bs) ) {
+ // go on defense by default
+ BotVoiceChat_Defend(bs, i, SAY_TELL);
+ }
+ return qtrue;
+ }
+ }
+ }
+ }
+ }
+ return qfalse;
+}
+
+/*
+==================
+BotTeamAI
+==================
+*/
+void BotTeamAI(bot_state_t *bs) {
+ int numteammates;
+ char netname[MAX_NETNAME];
+
+ //
+ if ( gametype < GT_TEAM )
+ return;
+ // make sure we've got a valid team leader
+ if (!BotValidTeamLeader(bs)) {
+ //
+ if (!FindHumanTeamLeader(bs)) {
+ //
+ if (!bs->askteamleader_time && !bs->becometeamleader_time) {
+ if (bs->entergame_time + 10 > FloatTime()) {
+ bs->askteamleader_time = FloatTime() + 5 + random() * 10;
+ }
+ else {
+ bs->becometeamleader_time = FloatTime() + 5 + random() * 10;
+ }
+ }
+ if (bs->askteamleader_time && bs->askteamleader_time < FloatTime()) {
+ // if asked for a team leader and no response
+ BotAI_BotInitialChat(bs, "whoisteamleader", NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_TEAM);
+ bs->askteamleader_time = 0;
+ bs->becometeamleader_time = FloatTime() + 8 + random() * 10;
+ }
+ if (bs->becometeamleader_time && bs->becometeamleader_time < FloatTime()) {
+ BotAI_BotInitialChat(bs, "iamteamleader", NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_TEAM);
+ BotSayVoiceTeamOrder(bs, -1, VOICECHAT_STARTLEADER);
+ ClientName(bs->client, netname, sizeof(netname));
+ strncpy(bs->teamleader, netname, sizeof(bs->teamleader));
+ bs->teamleader[sizeof(bs->teamleader)] = '\0';
+ bs->becometeamleader_time = 0;
+ }
+ return;
+ }
+ }
+ bs->askteamleader_time = 0;
+ bs->becometeamleader_time = 0;
+
+ //return if this bot is NOT the team leader
+ ClientName(bs->client, netname, sizeof(netname));
+ if (Q_stricmp(netname, bs->teamleader) != 0) return;
+ //
+ numteammates = BotNumTeamMates(bs);
+ //give orders
+ switch(gametype) {
+ case GT_TEAM:
+ {
+ if (bs->numteammates != numteammates || bs->forceorders) {
+ bs->teamgiveorders_time = FloatTime();
+ bs->numteammates = numteammates;
+ bs->forceorders = qfalse;
+ }
+ //if it's time to give orders
+ if (bs->teamgiveorders_time && bs->teamgiveorders_time < FloatTime() - 5) {
+ BotTeamOrders(bs);
+ //give orders again after 120 seconds
+ bs->teamgiveorders_time = FloatTime() + 120;
+ }
+ break;
+ }
+ case GT_CTF:
+ {
+ //if the number of team mates changed or the flag status changed
+ //or someone wants to know what to do
+ if (bs->numteammates != numteammates || bs->flagstatuschanged || bs->forceorders) {
+ bs->teamgiveorders_time = FloatTime();
+ bs->numteammates = numteammates;
+ bs->flagstatuschanged = qfalse;
+ bs->forceorders = qfalse;
+ }
+ //if there were no flag captures the last 3 minutes
+ if (bs->lastflagcapture_time < FloatTime() - 240) {
+ bs->lastflagcapture_time = FloatTime();
+ //randomly change the CTF strategy
+ if (random() < 0.4) {
+ bs->ctfstrategy ^= CTFS_AGRESSIVE;
+ bs->teamgiveorders_time = FloatTime();
+ }
+ }
+ //if it's time to give orders
+ if (bs->teamgiveorders_time && bs->teamgiveorders_time < FloatTime() - 3) {
+ BotCTFOrders(bs);
+ //
+ bs->teamgiveorders_time = 0;
+ }
+ break;
+ }
+#ifdef MISSIONPACK
+ case GT_1FCTF:
+ {
+ if (bs->numteammates != numteammates || bs->flagstatuschanged || bs->forceorders) {
+ bs->teamgiveorders_time = FloatTime();
+ bs->numteammates = numteammates;
+ bs->flagstatuschanged = qfalse;
+ bs->forceorders = qfalse;
+ }
+ //if there were no flag captures the last 4 minutes
+ if (bs->lastflagcapture_time < FloatTime() - 240) {
+ bs->lastflagcapture_time = FloatTime();
+ //randomly change the CTF strategy
+ if (random() < 0.4) {
+ bs->ctfstrategy ^= CTFS_AGRESSIVE;
+ bs->teamgiveorders_time = FloatTime();
+ }
+ }
+ //if it's time to give orders
+ if (bs->teamgiveorders_time && bs->teamgiveorders_time < FloatTime() - 2) {
+ Bot1FCTFOrders(bs);
+ //
+ bs->teamgiveorders_time = 0;
+ }
+ break;
+ }
+ case GT_OBELISK:
+ {
+ if (bs->numteammates != numteammates || bs->forceorders) {
+ bs->teamgiveorders_time = FloatTime();
+ bs->numteammates = numteammates;
+ bs->forceorders = qfalse;
+ }
+ //if it's time to give orders
+ if (bs->teamgiveorders_time && bs->teamgiveorders_time < FloatTime() - 5) {
+ BotObeliskOrders(bs);
+ //give orders again after 30 seconds
+ bs->teamgiveorders_time = FloatTime() + 30;
+ }
+ break;
+ }
+ case GT_HARVESTER:
+ {
+ if (bs->numteammates != numteammates || bs->forceorders) {
+ bs->teamgiveorders_time = FloatTime();
+ bs->numteammates = numteammates;
+ bs->forceorders = qfalse;
+ }
+ //if it's time to give orders
+ if (bs->teamgiveorders_time && bs->teamgiveorders_time < FloatTime() - 5) {
+ BotHarvesterOrders(bs);
+ //give orders again after 30 seconds
+ bs->teamgiveorders_time = FloatTime() + 30;
+ }
+ break;
+ }
+#endif
+ }
+}
+
diff --git a/code/game/ai_team.h b/code/game/ai_team.h
new file mode 100755
index 0000000..fbe4a9e
--- /dev/null
+++ b/code/game/ai_team.h
@@ -0,0 +1,39 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+/*****************************************************************************
+ * name: ai_team.h
+ *
+ * desc: Quake3 bot AI
+ *
+ * $Archive: /source/code/botai/ai_chat.c $
+ *
+ *****************************************************************************/
+
+void BotTeamAI(bot_state_t *bs);
+int BotGetTeamMateTaskPreference(bot_state_t *bs, int teammate);
+void BotSetTeamMateTaskPreference(bot_state_t *bs, int teammate, int preference);
+void BotVoiceChat(bot_state_t *bs, int toclient, char *voicechat);
+void BotVoiceChatOnly(bot_state_t *bs, int toclient, char *voicechat);
+
+
diff --git a/code/game/ai_vcmd.c b/code/game/ai_vcmd.c
new file mode 100755
index 0000000..812fe8f
--- /dev/null
+++ b/code/game/ai_vcmd.c
@@ -0,0 +1,550 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+/*****************************************************************************
+ * name: ai_vcmd.c
+ *
+ * desc: Quake3 bot AI
+ *
+ * $Archive: /MissionPack/code/game/ai_vcmd.c $
+ *
+ *****************************************************************************/
+
+#include "g_local.h"
+#include "botlib.h"
+#include "be_aas.h"
+#include "be_ea.h"
+#include "be_ai_char.h"
+#include "be_ai_chat.h"
+#include "be_ai_gen.h"
+#include "be_ai_goal.h"
+#include "be_ai_move.h"
+#include "be_ai_weap.h"
+//
+#include "ai_main.h"
+#include "ai_dmq3.h"
+#include "ai_chat.h"
+#include "ai_cmd.h"
+#include "ai_dmnet.h"
+#include "ai_team.h"
+#include "ai_vcmd.h"
+//
+#include "chars.h" //characteristics
+#include "inv.h" //indexes into the inventory
+#include "syn.h" //synonyms
+#include "match.h" //string matching types and vars
+
+// for the voice chats
+#include "../../ui/menudef.h"
+
+
+typedef struct voiceCommand_s
+{
+ char *cmd;
+ void (*func)(bot_state_t *bs, int client, int mode);
+} voiceCommand_t;
+
+/*
+==================
+BotVoiceChat_GetFlag
+==================
+*/
+void BotVoiceChat_GetFlag(bot_state_t *bs, int client, int mode) {
+ //
+ if (gametype == GT_CTF) {
+ if (!ctf_redflag.areanum || !ctf_blueflag.areanum)
+ return;
+ }
+#ifdef MISSIONPACK
+ else if (gametype == GT_1FCTF) {
+ if (!ctf_neutralflag.areanum || !ctf_redflag.areanum || !ctf_blueflag.areanum)
+ return;
+ }
+#endif
+ else {
+ return;
+ }
+ //
+ bs->decisionmaker = client;
+ bs->ordered = qtrue;
+ bs->order_time = FloatTime();
+ //set the time to send a message to the team mates
+ bs->teammessage_time = FloatTime() + 2 * random();
+ //set the ltg type
+ bs->ltgtype = LTG_GETFLAG;
+ //set the team goal time
+ bs->teamgoal_time = FloatTime() + CTF_GETFLAG_TIME;
+ // get an alternate route in ctf
+ if (gametype == GT_CTF) {
+ //get an alternative route goal towards the enemy base
+ BotGetAlternateRouteGoal(bs, BotOppositeTeam(bs));
+ }
+ //
+ BotSetTeamStatus(bs);
+ // remember last ordered task
+ BotRememberLastOrderedTask(bs);
+#ifdef DEBUG
+ BotPrintTeamGoal(bs);
+#endif //DEBUG
+}
+
+/*
+==================
+BotVoiceChat_Offense
+==================
+*/
+void BotVoiceChat_Offense(bot_state_t *bs, int client, int mode) {
+ if ( gametype == GT_CTF
+#ifdef MISSIONPACK
+ || gametype == GT_1FCTF
+#endif
+ ) {
+ BotVoiceChat_GetFlag(bs, client, mode);
+ return;
+ }
+#ifdef MISSIONPACK
+ if (gametype == GT_HARVESTER) {
+ //
+ bs->decisionmaker = client;
+ bs->ordered = qtrue;
+ bs->order_time = FloatTime();
+ //set the time to send a message to the team mates
+ bs->teammessage_time = FloatTime() + 2 * random();
+ //set the ltg type
+ bs->ltgtype = LTG_HARVEST;
+ //set the team goal time
+ bs->teamgoal_time = FloatTime() + TEAM_HARVEST_TIME;
+ bs->harvestaway_time = 0;
+ //
+ BotSetTeamStatus(bs);
+ // remember last ordered task
+ BotRememberLastOrderedTask(bs);
+ }
+ else
+#endif
+ {
+ //
+ bs->decisionmaker = client;
+ bs->ordered = qtrue;
+ bs->order_time = FloatTime();
+ //set the time to send a message to the team mates
+ bs->teammessage_time = FloatTime() + 2 * random();
+ //set the ltg type
+ bs->ltgtype = LTG_ATTACKENEMYBASE;
+ //set the team goal time
+ bs->teamgoal_time = FloatTime() + TEAM_ATTACKENEMYBASE_TIME;
+ bs->attackaway_time = 0;
+ //
+ BotSetTeamStatus(bs);
+ // remember last ordered task
+ BotRememberLastOrderedTask(bs);
+ }
+#ifdef DEBUG
+ BotPrintTeamGoal(bs);
+#endif //DEBUG
+}
+
+/*
+==================
+BotVoiceChat_Defend
+==================
+*/
+void BotVoiceChat_Defend(bot_state_t *bs, int client, int mode) {
+#ifdef MISSIONPACK
+ if ( gametype == GT_OBELISK || gametype == GT_HARVESTER) {
+ //
+ switch(BotTeam(bs)) {
+ case TEAM_RED: memcpy(&bs->teamgoal, &redobelisk, sizeof(bot_goal_t)); break;
+ case TEAM_BLUE: memcpy(&bs->teamgoal, &blueobelisk, sizeof(bot_goal_t)); break;
+ default: return;
+ }
+ }
+ else
+#endif
+ if (gametype == GT_CTF
+#ifdef MISSIONPACK
+ || gametype == GT_1FCTF
+#endif
+ ) {
+ //
+ switch(BotTeam(bs)) {
+ case TEAM_RED: memcpy(&bs->teamgoal, &ctf_redflag, sizeof(bot_goal_t)); break;
+ case TEAM_BLUE: memcpy(&bs->teamgoal, &ctf_blueflag, sizeof(bot_goal_t)); break;
+ default: return;
+ }
+ }
+ else {
+ return;
+ }
+ //
+ bs->decisionmaker = client;
+ bs->ordered = qtrue;
+ bs->order_time = FloatTime();
+ //set the time to send a message to the team mates
+ bs->teammessage_time = FloatTime() + 2 * random();
+ //set the ltg type
+ bs->ltgtype = LTG_DEFENDKEYAREA;
+ //get the team goal time
+ bs->teamgoal_time = FloatTime() + TEAM_DEFENDKEYAREA_TIME;
+ //away from defending
+ bs->defendaway_time = 0;
+ //
+ BotSetTeamStatus(bs);
+ // remember last ordered task
+ BotRememberLastOrderedTask(bs);
+#ifdef DEBUG
+ BotPrintTeamGoal(bs);
+#endif //DEBUG
+}
+
+/*
+==================
+BotVoiceChat_DefendFlag
+==================
+*/
+void BotVoiceChat_DefendFlag(bot_state_t *bs, int client, int mode) {
+ BotVoiceChat_Defend(bs, client, mode);
+}
+
+/*
+==================
+BotVoiceChat_Patrol
+==================
+*/
+void BotVoiceChat_Patrol(bot_state_t *bs, int client, int mode) {
+ //
+ bs->decisionmaker = client;
+ //
+ bs->ltgtype = 0;
+ bs->lead_time = 0;
+ bs->lastgoal_ltgtype = 0;
+ //
+ BotAI_BotInitialChat(bs, "dismissed", NULL);
+ trap_BotEnterChat(bs->cs, client, CHAT_TELL);
+ BotVoiceChatOnly(bs, -1, VOICECHAT_ONPATROL);
+ //
+ BotSetTeamStatus(bs);
+#ifdef DEBUG
+ BotPrintTeamGoal(bs);
+#endif //DEBUG
+}
+
+/*
+==================
+BotVoiceChat_Camp
+==================
+*/
+void BotVoiceChat_Camp(bot_state_t *bs, int client, int mode) {
+ int areanum;
+ aas_entityinfo_t entinfo;
+ char netname[MAX_NETNAME];
+
+ //
+ bs->teamgoal.entitynum = -1;
+ BotEntityInfo(client, &entinfo);
+ //if info is valid (in PVS)
+ if (entinfo.valid) {
+ areanum = BotPointAreaNum(entinfo.origin);
+ if (areanum) { // && trap_AAS_AreaReachability(areanum)) {
+ //NOTE: just assume the bot knows where the person is
+ //if (BotEntityVisible(bs->entitynum, bs->eye, bs->viewangles, 360, client)) {
+ bs->teamgoal.entitynum = client;
+ bs->teamgoal.areanum = areanum;
+ VectorCopy(entinfo.origin, bs->teamgoal.origin);
+ VectorSet(bs->teamgoal.mins, -8, -8, -8);
+ VectorSet(bs->teamgoal.maxs, 8, 8, 8);
+ //}
+ }
+ }
+ //if the other is not visible
+ if (bs->teamgoal.entitynum < 0) {
+ BotAI_BotInitialChat(bs, "whereareyou", EasyClientName(client, netname, sizeof(netname)), NULL);
+ trap_BotEnterChat(bs->cs, client, CHAT_TELL);
+ return;
+ }
+ //
+ bs->decisionmaker = client;
+ bs->ordered = qtrue;
+ bs->order_time = FloatTime();
+ //set the time to send a message to the team mates
+ bs->teammessage_time = FloatTime() + 2 * random();
+ //set the ltg type
+ bs->ltgtype = LTG_CAMPORDER;
+ //get the team goal time
+ bs->teamgoal_time = FloatTime() + TEAM_CAMP_TIME;
+ //the teammate that requested the camping
+ bs->teammate = client;
+ //not arrived yet
+ bs->arrive_time = 0;
+ //
+ BotSetTeamStatus(bs);
+ // remember last ordered task
+ BotRememberLastOrderedTask(bs);
+#ifdef DEBUG
+ BotPrintTeamGoal(bs);
+#endif //DEBUG
+}
+
+/*
+==================
+BotVoiceChat_FollowMe
+==================
+*/
+void BotVoiceChat_FollowMe(bot_state_t *bs, int client, int mode) {
+ int areanum;
+ aas_entityinfo_t entinfo;
+ char netname[MAX_NETNAME];
+
+ bs->teamgoal.entitynum = -1;
+ BotEntityInfo(client, &entinfo);
+ //if info is valid (in PVS)
+ if (entinfo.valid) {
+ areanum = BotPointAreaNum(entinfo.origin);
+ if (areanum) { // && trap_AAS_AreaReachability(areanum)) {
+ bs->teamgoal.entitynum = client;
+ bs->teamgoal.areanum = areanum;
+ VectorCopy(entinfo.origin, bs->teamgoal.origin);
+ VectorSet(bs->teamgoal.mins, -8, -8, -8);
+ VectorSet(bs->teamgoal.maxs, 8, 8, 8);
+ }
+ }
+ //if the other is not visible
+ if (bs->teamgoal.entitynum < 0) {
+ BotAI_BotInitialChat(bs, "whereareyou", EasyClientName(client, netname, sizeof(netname)), NULL);
+ trap_BotEnterChat(bs->cs, client, CHAT_TELL);
+ return;
+ }
+ //
+ bs->decisionmaker = client;
+ bs->ordered = qtrue;
+ bs->order_time = FloatTime();
+ //the team mate
+ bs->teammate = client;
+ //last time the team mate was assumed visible
+ bs->teammatevisible_time = FloatTime();
+ //set the time to send a message to the team mates
+ bs->teammessage_time = FloatTime() + 2 * random();
+ //get the team goal time
+ bs->teamgoal_time = FloatTime() + TEAM_ACCOMPANY_TIME;
+ //set the ltg type
+ bs->ltgtype = LTG_TEAMACCOMPANY;
+ bs->formation_dist = 3.5 * 32; //3.5 meter
+ bs->arrive_time = 0;
+ //
+ BotSetTeamStatus(bs);
+ // remember last ordered task
+ BotRememberLastOrderedTask(bs);
+#ifdef DEBUG
+ BotPrintTeamGoal(bs);
+#endif //DEBUG
+}
+
+/*
+==================
+BotVoiceChat_FollowFlagCarrier
+==================
+*/
+void BotVoiceChat_FollowFlagCarrier(bot_state_t *bs, int client, int mode) {
+ int carrier;
+
+ carrier = BotTeamFlagCarrier(bs);
+ if (carrier >= 0)
+ BotVoiceChat_FollowMe(bs, carrier, mode);
+#ifdef DEBUG
+ BotPrintTeamGoal(bs);
+#endif //DEBUG
+}
+
+/*
+==================
+BotVoiceChat_ReturnFlag
+==================
+*/
+void BotVoiceChat_ReturnFlag(bot_state_t *bs, int client, int mode) {
+ //if not in CTF mode
+ if (
+ gametype != GT_CTF
+#ifdef MISSIONPACK
+ && gametype != GT_1FCTF
+#endif
+ ) {
+ return;
+ }
+ //
+ bs->decisionmaker = client;
+ bs->ordered = qtrue;
+ bs->order_time = FloatTime();
+ //set the time to send a message to the team mates
+ bs->teammessage_time = FloatTime() + 2 * random();
+ //set the ltg type
+ bs->ltgtype = LTG_RETURNFLAG;
+ //set the team goal time
+ bs->teamgoal_time = FloatTime() + CTF_RETURNFLAG_TIME;
+ bs->rushbaseaway_time = 0;
+ BotSetTeamStatus(bs);
+#ifdef DEBUG
+ BotPrintTeamGoal(bs);
+#endif //DEBUG
+}
+
+/*
+==================
+BotVoiceChat_StartLeader
+==================
+*/
+void BotVoiceChat_StartLeader(bot_state_t *bs, int client, int mode) {
+ ClientName(client, bs->teamleader, sizeof(bs->teamleader));
+}
+
+/*
+==================
+BotVoiceChat_StopLeader
+==================
+*/
+void BotVoiceChat_StopLeader(bot_state_t *bs, int client, int mode) {
+ char netname[MAX_MESSAGE_SIZE];
+
+ if (!Q_stricmp(bs->teamleader, ClientName(client, netname, sizeof(netname)))) {
+ bs->teamleader[0] = '\0';
+ notleader[client] = qtrue;
+ }
+}
+
+/*
+==================
+BotVoiceChat_WhoIsLeader
+==================
+*/
+void BotVoiceChat_WhoIsLeader(bot_state_t *bs, int client, int mode) {
+ char netname[MAX_MESSAGE_SIZE];
+
+ if (!TeamPlayIsOn()) return;
+
+ ClientName(bs->client, netname, sizeof(netname));
+ //if this bot IS the team leader
+ if (!Q_stricmp(netname, bs->teamleader)) {
+ BotAI_BotInitialChat(bs, "iamteamleader", NULL);
+ trap_BotEnterChat(bs->cs, 0, CHAT_TEAM);
+ BotVoiceChatOnly(bs, -1, VOICECHAT_STARTLEADER);
+ }
+}
+
+/*
+==================
+BotVoiceChat_WantOnDefense
+==================
+*/
+void BotVoiceChat_WantOnDefense(bot_state_t *bs, int client, int mode) {
+ char netname[MAX_NETNAME];
+ int preference;
+
+ preference = BotGetTeamMateTaskPreference(bs, client);
+ preference &= ~TEAMTP_ATTACKER;
+ preference |= TEAMTP_DEFENDER;
+ BotSetTeamMateTaskPreference(bs, client, preference);
+ //
+ EasyClientName(client, netname, sizeof(netname));
+ BotAI_BotInitialChat(bs, "keepinmind", netname, NULL);
+ trap_BotEnterChat(bs->cs, client, CHAT_TELL);
+ BotVoiceChatOnly(bs, client, VOICECHAT_YES);
+ trap_EA_Action(bs->client, ACTION_AFFIRMATIVE);
+}
+
+/*
+==================
+BotVoiceChat_WantOnOffense
+==================
+*/
+void BotVoiceChat_WantOnOffense(bot_state_t *bs, int client, int mode) {
+ char netname[MAX_NETNAME];
+ int preference;
+
+ preference = BotGetTeamMateTaskPreference(bs, client);
+ preference &= ~TEAMTP_DEFENDER;
+ preference |= TEAMTP_ATTACKER;
+ BotSetTeamMateTaskPreference(bs, client, preference);
+ //
+ EasyClientName(client, netname, sizeof(netname));
+ BotAI_BotInitialChat(bs, "keepinmind", netname, NULL);
+ trap_BotEnterChat(bs->cs, client, CHAT_TELL);
+ BotVoiceChatOnly(bs, client, VOICECHAT_YES);
+ trap_EA_Action(bs->client, ACTION_AFFIRMATIVE);
+}
+
+void BotVoiceChat_Dummy(bot_state_t *bs, int client, int mode) {
+}
+
+voiceCommand_t voiceCommands[] = {
+ {VOICECHAT_GETFLAG, BotVoiceChat_GetFlag},
+ {VOICECHAT_OFFENSE, BotVoiceChat_Offense },
+ {VOICECHAT_DEFEND, BotVoiceChat_Defend },
+ {VOICECHAT_DEFENDFLAG, BotVoiceChat_DefendFlag },
+ {VOICECHAT_PATROL, BotVoiceChat_Patrol },
+ {VOICECHAT_CAMP, BotVoiceChat_Camp },
+ {VOICECHAT_FOLLOWME, BotVoiceChat_FollowMe },
+ {VOICECHAT_FOLLOWFLAGCARRIER, BotVoiceChat_FollowFlagCarrier },
+ {VOICECHAT_RETURNFLAG, BotVoiceChat_ReturnFlag },
+ {VOICECHAT_STARTLEADER, BotVoiceChat_StartLeader },
+ {VOICECHAT_STOPLEADER, BotVoiceChat_StopLeader },
+ {VOICECHAT_WHOISLEADER, BotVoiceChat_WhoIsLeader },
+ {VOICECHAT_WANTONDEFENSE, BotVoiceChat_WantOnDefense },
+ {VOICECHAT_WANTONOFFENSE, BotVoiceChat_WantOnOffense },
+ {NULL, BotVoiceChat_Dummy}
+};
+
+int BotVoiceChatCommand(bot_state_t *bs, int mode, char *voiceChat) {
+ int i, voiceOnly, clientNum, color;
+ char *ptr, buf[MAX_MESSAGE_SIZE], *cmd;
+
+ if (!TeamPlayIsOn()) {
+ return qfalse;
+ }
+
+ if ( mode == SAY_ALL ) {
+ return qfalse; // don't do anything with voice chats to everyone
+ }
+
+ Q_strncpyz(buf, voiceChat, sizeof(buf));
+ cmd = buf;
+ for (ptr = cmd; *cmd && *cmd > ' '; cmd++);
+ while (*cmd && *cmd <= ' ') *cmd++ = '\0';
+ voiceOnly = atoi(ptr);
+ for (ptr = cmd; *cmd && *cmd > ' '; cmd++);
+ while (*cmd && *cmd <= ' ') *cmd++ = '\0';
+ clientNum = atoi(ptr);
+ for (ptr = cmd; *cmd && *cmd > ' '; cmd++);
+ while (*cmd && *cmd <= ' ') *cmd++ = '\0';
+ color = atoi(ptr);
+
+ if (!BotSameTeam(bs, clientNum)) {
+ return qfalse;
+ }
+
+ for (i = 0; voiceCommands[i].cmd; i++) {
+ if (!Q_stricmp(cmd, voiceCommands[i].cmd)) {
+ voiceCommands[i].func(bs, clientNum, mode);
+ return qtrue;
+ }
+ }
+ return qfalse;
+}
diff --git a/code/game/ai_vcmd.h b/code/game/ai_vcmd.h
new file mode 100755
index 0000000..0eef6ac
--- /dev/null
+++ b/code/game/ai_vcmd.h
@@ -0,0 +1,36 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+/*****************************************************************************
+ * name: ai_vcmd.h
+ *
+ * desc: Quake3 bot AI
+ *
+ * $Archive: /source/code/botai/ai_vcmd.c $
+ *
+ *****************************************************************************/
+
+int BotVoiceChatCommand(bot_state_t *bs, int mode, char *voicechat);
+void BotVoiceChat_Defend(bot_state_t *bs, int client, int mode);
+
+
diff --git a/code/game/be_aas.h b/code/game/be_aas.h
new file mode 100755
index 0000000..24f982c
--- /dev/null
+++ b/code/game/be_aas.h
@@ -0,0 +1,221 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+/*****************************************************************************
+ * name: be_aas.h
+ *
+ * desc: Area Awareness System, stuff exported to the AI
+ *
+ * $Archive: /source/code/botlib/be_aas.h $
+ *
+ *****************************************************************************/
+
+#ifndef MAX_STRINGFIELD
+#define MAX_STRINGFIELD 80
+#endif
+
+//travel flags
+#define TFL_INVALID 0x00000001 //traveling temporary not possible
+#define TFL_WALK 0x00000002 //walking
+#define TFL_CROUCH 0x00000004 //crouching
+#define TFL_BARRIERJUMP 0x00000008 //jumping onto a barrier
+#define TFL_JUMP 0x00000010 //jumping
+#define TFL_LADDER 0x00000020 //climbing a ladder
+#define TFL_WALKOFFLEDGE 0x00000080 //walking of a ledge
+#define TFL_SWIM 0x00000100 //swimming
+#define TFL_WATERJUMP 0x00000200 //jumping out of the water
+#define TFL_TELEPORT 0x00000400 //teleporting
+#define TFL_ELEVATOR 0x00000800 //elevator
+#define TFL_ROCKETJUMP 0x00001000 //rocket jumping
+#define TFL_BFGJUMP 0x00002000 //bfg jumping
+#define TFL_GRAPPLEHOOK 0x00004000 //grappling hook
+#define TFL_DOUBLEJUMP 0x00008000 //double jump
+#define TFL_RAMPJUMP 0x00010000 //ramp jump
+#define TFL_STRAFEJUMP 0x00020000 //strafe jump
+#define TFL_JUMPPAD 0x00040000 //jump pad
+#define TFL_AIR 0x00080000 //travel through air
+#define TFL_WATER 0x00100000 //travel through water
+#define TFL_SLIME 0x00200000 //travel through slime
+#define TFL_LAVA 0x00400000 //travel through lava
+#define TFL_DONOTENTER 0x00800000 //travel through donotenter area
+#define TFL_FUNCBOB 0x01000000 //func bobbing
+#define TFL_FLIGHT 0x02000000 //flight
+#define TFL_BRIDGE 0x04000000 //move over a bridge
+//
+#define TFL_NOTTEAM1 0x08000000 //not team 1
+#define TFL_NOTTEAM2 0x10000000 //not team 2
+
+//default travel flags
+#define TFL_DEFAULT TFL_WALK|TFL_CROUCH|TFL_BARRIERJUMP|\
+ TFL_JUMP|TFL_LADDER|\
+ TFL_WALKOFFLEDGE|TFL_SWIM|TFL_WATERJUMP|\
+ TFL_TELEPORT|TFL_ELEVATOR|\
+ TFL_AIR|TFL_WATER|TFL_JUMPPAD|TFL_FUNCBOB
+
+typedef enum
+{
+ SOLID_NOT, // no interaction with other objects
+ SOLID_TRIGGER, // only touch when inside, after moving
+ SOLID_BBOX, // touch on edge
+ SOLID_BSP // bsp clip, touch on edge
+} solid_t;
+
+//a trace is returned when a box is swept through the AAS world
+typedef struct aas_trace_s
+{
+ qboolean startsolid; // if true, the initial point was in a solid area
+ float fraction; // time completed, 1.0 = didn't hit anything
+ vec3_t endpos; // final position
+ int ent; // entity blocking the trace
+ int lastarea; // last area the trace was in (zero if none)
+ int area; // area blocking the trace (zero if none)
+ int planenum; // number of the plane that was hit
+} aas_trace_t;
+
+/* Defined in botlib.h
+
+//bsp_trace_t hit surface
+typedef struct bsp_surface_s
+{
+ char name[16];
+ int flags;
+ int value;
+} bsp_surface_t;
+
+//a trace is returned when a box is swept through the BSP world
+typedef struct bsp_trace_s
+{
+ qboolean allsolid; // if true, plane is not valid
+ qboolean startsolid; // if true, the initial point was in a solid area
+ float fraction; // time completed, 1.0 = didn't hit anything
+ vec3_t endpos; // final position
+ cplane_t plane; // surface normal at impact
+ float exp_dist; // expanded plane distance
+ int sidenum; // number of the brush side hit
+ bsp_surface_t surface; // hit surface
+ int contents; // contents on other side of surface hit
+ int ent; // number of entity hit
+} bsp_trace_t;
+//
+*/
+
+//entity info
+typedef struct aas_entityinfo_s
+{
+ int valid; // true if updated this frame
+ int type; // entity type
+ int flags; // entity flags
+ float ltime; // local time
+ float update_time; // time between last and current update
+ int number; // number of the entity
+ vec3_t origin; // origin of the entity
+ vec3_t angles; // angles of the model
+ vec3_t old_origin; // for lerping
+ vec3_t lastvisorigin; // last visible origin
+ vec3_t mins; // bounding box minimums
+ vec3_t maxs; // bounding box maximums
+ int groundent; // ground entity
+ int solid; // solid type
+ int modelindex; // model used
+ int modelindex2; // weapons, CTF flags, etc
+ int frame; // model frame number
+ int event; // impulse events -- muzzle flashes, footsteps, etc
+ int eventParm; // even parameter
+ int powerups; // bit flags
+ int weapon; // determines weapon and flash model, etc
+ int legsAnim; // mask off ANIM_TOGGLEBIT
+ int torsoAnim; // mask off ANIM_TOGGLEBIT
+} aas_entityinfo_t;
+
+// area info
+typedef struct aas_areainfo_s
+{
+ int contents;
+ int flags;
+ int presencetype;
+ int cluster;
+ vec3_t mins;
+ vec3_t maxs;
+ vec3_t center;
+} aas_areainfo_t;
+
+// client movement prediction stop events, stop as soon as:
+#define SE_NONE 0
+#define SE_HITGROUND 1 // the ground is hit
+#define SE_LEAVEGROUND 2 // there's no ground
+#define SE_ENTERWATER 4 // water is entered
+#define SE_ENTERSLIME 8 // slime is entered
+#define SE_ENTERLAVA 16 // lava is entered
+#define SE_HITGROUNDDAMAGE 32 // the ground is hit with damage
+#define SE_GAP 64 // there's a gap
+#define SE_TOUCHJUMPPAD 128 // touching a jump pad area
+#define SE_TOUCHTELEPORTER 256 // touching teleporter
+#define SE_ENTERAREA 512 // the given stoparea is entered
+#define SE_HITGROUNDAREA 1024 // a ground face in the area is hit
+#define SE_HITBOUNDINGBOX 2048 // hit the specified bounding box
+#define SE_TOUCHCLUSTERPORTAL 4096 // touching a cluster portal
+
+typedef struct aas_clientmove_s
+{
+ vec3_t endpos; //position at the end of movement prediction
+ int endarea; //area at end of movement prediction
+ vec3_t velocity; //velocity at the end of movement prediction
+ aas_trace_t trace; //last trace
+ int presencetype; //presence type at end of movement prediction
+ int stopevent; //event that made the prediction stop
+ int endcontents; //contents at the end of movement prediction
+ float time; //time predicted ahead
+ int frames; //number of frames predicted ahead
+} aas_clientmove_t;
+
+// alternate route goals
+#define ALTROUTEGOAL_ALL 1
+#define ALTROUTEGOAL_CLUSTERPORTALS 2
+#define ALTROUTEGOAL_VIEWPORTALS 4
+
+typedef struct aas_altroutegoal_s
+{
+ vec3_t origin;
+ int areanum;
+ unsigned short starttraveltime;
+ unsigned short goaltraveltime;
+ unsigned short extratraveltime;
+} aas_altroutegoal_t;
+
+// route prediction stop events
+#define RSE_NONE 0
+#define RSE_NOROUTE 1 //no route to goal
+#define RSE_USETRAVELTYPE 2 //stop as soon as on of the given travel types is used
+#define RSE_ENTERCONTENTS 4 //stop when entering the given contents
+#define RSE_ENTERAREA 8 //stop when entering the given area
+
+typedef struct aas_predictroute_s
+{
+ vec3_t endpos; //position at the end of movement prediction
+ int endarea; //area at end of movement prediction
+ int stopevent; //event that made the prediction stop
+ int endcontents; //contents at the end of movement prediction
+ int endtravelflags; //end travel flags
+ int numareas; //number of areas predicted ahead
+ int time; //time predicted ahead (in hundreth of a sec)
+} aas_predictroute_t;
diff --git a/code/game/be_ai_char.h b/code/game/be_ai_char.h
new file mode 100755
index 0000000..89f1e52
--- /dev/null
+++ b/code/game/be_ai_char.h
@@ -0,0 +1,48 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+/*****************************************************************************
+ * name: be_ai_char.h
+ *
+ * desc: bot characters
+ *
+ * $Archive: /source/code/botlib/be_ai_char.h $
+ *
+ *****************************************************************************/
+
+//loads a bot character from a file
+int BotLoadCharacter(char *charfile, float skill);
+//frees a bot character
+void BotFreeCharacter(int character);
+//returns a float characteristic
+float Characteristic_Float(int character, int index);
+//returns a bounded float characteristic
+float Characteristic_BFloat(int character, int index, float min, float max);
+//returns an integer characteristic
+int Characteristic_Integer(int character, int index);
+//returns a bounded integer characteristic
+int Characteristic_BInteger(int character, int index, int min, int max);
+//returns a string characteristic
+void Characteristic_String(int character, int index, char *buf, int size);
+//free cached bot characters
+void BotShutdownCharacters(void);
diff --git a/code/game/be_ai_chat.h b/code/game/be_ai_chat.h
new file mode 100755
index 0000000..8d3d7a4
--- /dev/null
+++ b/code/game/be_ai_chat.h
@@ -0,0 +1,113 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*****************************************************************************
+ * name: be_ai_chat.h
+ *
+ * desc: char AI
+ *
+ * $Archive: /source/code/botlib/be_ai_chat.h $
+ *
+ *****************************************************************************/
+
+#define MAX_MESSAGE_SIZE 256
+#define MAX_CHATTYPE_NAME 32
+#define MAX_MATCHVARIABLES 8
+
+#define CHAT_GENDERLESS 0
+#define CHAT_GENDERFEMALE 1
+#define CHAT_GENDERMALE 2
+
+#define CHAT_ALL 0
+#define CHAT_TEAM 1
+#define CHAT_TELL 2
+
+//a console message
+typedef struct bot_consolemessage_s
+{
+ int handle;
+ float time; //message time
+ int type; //message type
+ char message[MAX_MESSAGE_SIZE]; //message
+ struct bot_consolemessage_s *prev, *next; //prev and next in list
+} bot_consolemessage_t;
+
+//match variable
+typedef struct bot_matchvariable_s
+{
+ char offset;
+ int length;
+} bot_matchvariable_t;
+//returned to AI when a match is found
+typedef struct bot_match_s
+{
+ char string[MAX_MESSAGE_SIZE];
+ int type;
+ int subtype;
+ bot_matchvariable_t variables[MAX_MATCHVARIABLES];
+} bot_match_t;
+
+//setup the chat AI
+int BotSetupChatAI(void);
+//shutdown the chat AI
+void BotShutdownChatAI(void);
+//returns the handle to a newly allocated chat state
+int BotAllocChatState(void);
+//frees the chatstate
+void BotFreeChatState(int handle);
+//adds a console message to the chat state
+void BotQueueConsoleMessage(int chatstate, int type, char *message);
+//removes the console message from the chat state
+void BotRemoveConsoleMessage(int chatstate, int handle);
+//returns the next console message from the state
+int BotNextConsoleMessage(int chatstate, bot_consolemessage_t *cm);
+//returns the number of console messages currently stored in the state
+int BotNumConsoleMessages(int chatstate);
+//selects a chat message of the given type
+void BotInitialChat(int chatstate, char *type, int mcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7);
+//returns the number of initial chat messages of the given type
+int BotNumInitialChats(int chatstate, char *type);
+//find and select a reply for the given message
+int BotReplyChat(int chatstate, char *message, int mcontext, int vcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7);
+//returns the length of the currently selected chat message
+int BotChatLength(int chatstate);
+//enters the selected chat message
+void BotEnterChat(int chatstate, int clientto, int sendto);
+//get the chat message ready to be output
+void BotGetChatMessage(int chatstate, char *buf, int size);
+//checks if the first string contains the second one, returns index into first string or -1 if not found
+int StringContains(char *str1, char *str2, int casesensitive);
+//finds a match for the given string using the match templates
+int BotFindMatch(char *str, bot_match_t *match, unsigned long int context);
+//returns a variable from a match
+void BotMatchVariable(bot_match_t *match, int variable, char *buf, int size);
+//unify all the white spaces in the string
+void UnifyWhiteSpaces(char *string);
+//replace all the context related synonyms in the string
+void BotReplaceSynonyms(char *string, unsigned long int context);
+//loads a chat file for the chat state
+int BotLoadChatFile(int chatstate, char *chatfile, char *chatname);
+//store the gender of the bot in the chat state
+void BotSetChatGender(int chatstate, int gender);
+//store the bot name in the chat state
+void BotSetChatName(int chatstate, char *name, int client);
+
diff --git a/code/game/be_ai_gen.h b/code/game/be_ai_gen.h
new file mode 100755
index 0000000..94528ed
--- /dev/null
+++ b/code/game/be_ai_gen.h
@@ -0,0 +1,33 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+/*****************************************************************************
+ * name: be_ai_gen.h
+ *
+ * desc: genetic selection
+ *
+ * $Archive: /source/code/botlib/be_ai_gen.h $
+ *
+ *****************************************************************************/
+
+int GeneticParentsAndChildSelection(int numranks, float *ranks, int *parent1, int *parent2, int *child);
diff --git a/code/game/be_ai_goal.h b/code/game/be_ai_goal.h
new file mode 100755
index 0000000..1fdddf3
--- /dev/null
+++ b/code/game/be_ai_goal.h
@@ -0,0 +1,118 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*****************************************************************************
+ * name: be_ai_goal.h
+ *
+ * desc: goal AI
+ *
+ * $Archive: /source/code/botlib/be_ai_goal.h $
+ *
+ *****************************************************************************/
+
+#define MAX_AVOIDGOALS 256
+#define MAX_GOALSTACK 8
+
+#define GFL_NONE 0
+#define GFL_ITEM 1
+#define GFL_ROAM 2
+#define GFL_DROPPED 4
+
+//a bot goal
+typedef struct bot_goal_s
+{
+ vec3_t origin; //origin of the goal
+ int areanum; //area number of the goal
+ vec3_t mins, maxs; //mins and maxs of the goal
+ int entitynum; //number of the goal entity
+ int number; //goal number
+ int flags; //goal flags
+ int iteminfo; //item information
+} bot_goal_t;
+
+//reset the whole goal state, but keep the item weights
+void BotResetGoalState(int goalstate);
+//reset avoid goals
+void BotResetAvoidGoals(int goalstate);
+//remove the goal with the given number from the avoid goals
+void BotRemoveFromAvoidGoals(int goalstate, int number);
+//push a goal onto the goal stack
+void BotPushGoal(int goalstate, bot_goal_t *goal);
+//pop a goal from the goal stack
+void BotPopGoal(int goalstate);
+//empty the bot's goal stack
+void BotEmptyGoalStack(int goalstate);
+//dump the avoid goals
+void BotDumpAvoidGoals(int goalstate);
+//dump the goal stack
+void BotDumpGoalStack(int goalstate);
+//get the name name of the goal with the given number
+void BotGoalName(int number, char *name, int size);
+//get the top goal from the stack
+int BotGetTopGoal(int goalstate, bot_goal_t *goal);
+//get the second goal on the stack
+int BotGetSecondGoal(int goalstate, bot_goal_t *goal);
+//choose the best long term goal item for the bot
+int BotChooseLTGItem(int goalstate, vec3_t origin, int *inventory, int travelflags);
+//choose the best nearby goal item for the bot
+//the item may not be further away from the current bot position than maxtime
+//also the travel time from the nearby goal towards the long term goal may not
+//be larger than the travel time towards the long term goal from the current bot position
+int BotChooseNBGItem(int goalstate, vec3_t origin, int *inventory, int travelflags,
+ bot_goal_t *ltg, float maxtime);
+//returns true if the bot touches the goal
+int BotTouchingGoal(vec3_t origin, bot_goal_t *goal);
+//returns true if the goal should be visible but isn't
+int BotItemGoalInVisButNotVisible(int viewer, vec3_t eye, vec3_t viewangles, bot_goal_t *goal);
+//search for a goal for the given classname, the index can be used
+//as a start point for the search when multiple goals are available with that same classname
+int BotGetLevelItemGoal(int index, char *classname, bot_goal_t *goal);
+//get the next camp spot in the map
+int BotGetNextCampSpotGoal(int num, bot_goal_t *goal);
+//get the map location with the given name
+int BotGetMapLocationGoal(char *name, bot_goal_t *goal);
+//returns the avoid goal time
+float BotAvoidGoalTime(int goalstate, int number);
+//set the avoid goal time
+void BotSetAvoidGoalTime(int goalstate, int number, float avoidtime);
+//initializes the items in the level
+void BotInitLevelItems(void);
+//regularly update dynamic entity items (dropped weapons, flags etc.)
+void BotUpdateEntityItems(void);
+//interbreed the goal fuzzy logic
+void BotInterbreedGoalFuzzyLogic(int parent1, int parent2, int child);
+//save the goal fuzzy logic to disk
+void BotSaveGoalFuzzyLogic(int goalstate, char *filename);
+//mutate the goal fuzzy logic
+void BotMutateGoalFuzzyLogic(int goalstate, float range);
+//loads item weights for the bot
+int BotLoadItemWeights(int goalstate, char *filename);
+//frees the item weights of the bot
+void BotFreeItemWeights(int goalstate);
+//returns the handle of a newly allocated goal state
+int BotAllocGoalState(int client);
+//free the given goal state
+void BotFreeGoalState(int handle);
+//setup the goal AI
+int BotSetupGoalAI(void);
+//shut down the goal AI
+void BotShutdownGoalAI(void);
diff --git a/code/game/be_ai_move.h b/code/game/be_ai_move.h
new file mode 100755
index 0000000..1f0c756
--- /dev/null
+++ b/code/game/be_ai_move.h
@@ -0,0 +1,142 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+/*****************************************************************************
+ * name: be_ai_move.h
+ *
+ * desc: movement AI
+ *
+ * $Archive: /source/code/botlib/be_ai_move.h $
+ *
+ *****************************************************************************/
+
+//movement types
+#define MOVE_WALK 1
+#define MOVE_CROUCH 2
+#define MOVE_JUMP 4
+#define MOVE_GRAPPLE 8
+#define MOVE_ROCKETJUMP 16
+#define MOVE_BFGJUMP 32
+//move flags
+#define MFL_BARRIERJUMP 1 //bot is performing a barrier jump
+#define MFL_ONGROUND 2 //bot is in the ground
+#define MFL_SWIMMING 4 //bot is swimming
+#define MFL_AGAINSTLADDER 8 //bot is against a ladder
+#define MFL_WATERJUMP 16 //bot is waterjumping
+#define MFL_TELEPORTED 32 //bot is being teleported
+#define MFL_GRAPPLEPULL 64 //bot is being pulled by the grapple
+#define MFL_ACTIVEGRAPPLE 128 //bot is using the grapple hook
+#define MFL_GRAPPLERESET 256 //bot has reset the grapple
+#define MFL_WALK 512 //bot should walk slowly
+// move result flags
+#define MOVERESULT_MOVEMENTVIEW 1 //bot uses view for movement
+#define MOVERESULT_SWIMVIEW 2 //bot uses view for swimming
+#define MOVERESULT_WAITING 4 //bot is waiting for something
+#define MOVERESULT_MOVEMENTVIEWSET 8 //bot has set the view in movement code
+#define MOVERESULT_MOVEMENTWEAPON 16 //bot uses weapon for movement
+#define MOVERESULT_ONTOPOFOBSTACLE 32 //bot is ontop of obstacle
+#define MOVERESULT_ONTOPOF_FUNCBOB 64 //bot is ontop of a func_bobbing
+#define MOVERESULT_ONTOPOF_ELEVATOR 128 //bot is ontop of an elevator (func_plat)
+#define MOVERESULT_BLOCKEDBYAVOIDSPOT 256 //bot is blocked by an avoid spot
+//
+#define MAX_AVOIDREACH 1
+#define MAX_AVOIDSPOTS 32
+// avoid spot types
+#define AVOID_CLEAR 0 //clear all avoid spots
+#define AVOID_ALWAYS 1 //avoid always
+#define AVOID_DONTBLOCK 2 //never totally block
+// restult types
+#define RESULTTYPE_ELEVATORUP 1 //elevator is up
+#define RESULTTYPE_WAITFORFUNCBOBBING 2 //waiting for func bobbing to arrive
+#define RESULTTYPE_BADGRAPPLEPATH 4 //grapple path is obstructed
+#define RESULTTYPE_INSOLIDAREA 8 //stuck in solid area, this is bad
+
+//structure used to initialize the movement state
+//the or_moveflags MFL_ONGROUND, MFL_TELEPORTED and MFL_WATERJUMP come from the playerstate
+typedef struct bot_initmove_s
+{
+ vec3_t origin; //origin of the bot
+ vec3_t velocity; //velocity of the bot
+ vec3_t viewoffset; //view offset
+ int entitynum; //entity number of the bot
+ int client; //client number of the bot
+ float thinktime; //time the bot thinks
+ int presencetype; //presencetype of the bot
+ vec3_t viewangles; //view angles of the bot
+ int or_moveflags; //values ored to the movement flags
+} bot_initmove_t;
+
+//NOTE: the ideal_viewangles are only valid if MFL_MOVEMENTVIEW is set
+typedef struct bot_moveresult_s
+{
+ int failure; //true if movement failed all together
+ int type; //failure or blocked type
+ int blocked; //true if blocked by an entity
+ int blockentity; //entity blocking the bot
+ int traveltype; //last executed travel type
+ int flags; //result flags
+ int weapon; //weapon used for movement
+ vec3_t movedir; //movement direction
+ vec3_t ideal_viewangles; //ideal viewangles for the movement
+} bot_moveresult_t;
+
+// bk001204: from code/botlib/be_ai_move.c
+// TTimo 04/12/2001 was moved here to avoid dup defines
+typedef struct bot_avoidspot_s
+{
+ vec3_t origin;
+ float radius;
+ int type;
+} bot_avoidspot_t;
+
+//resets the whole move state
+void BotResetMoveState(int movestate);
+//moves the bot to the given goal
+void BotMoveToGoal(bot_moveresult_t *result, int movestate, bot_goal_t *goal, int travelflags);
+//moves the bot in the specified direction using the specified type of movement
+int BotMoveInDirection(int movestate, vec3_t dir, float speed, int type);
+//reset avoid reachability
+void BotResetAvoidReach(int movestate);
+//resets the last avoid reachability
+void BotResetLastAvoidReach(int movestate);
+//returns a reachability area if the origin is in one
+int BotReachabilityArea(vec3_t origin, int client);
+//view target based on movement
+int BotMovementViewTarget(int movestate, bot_goal_t *goal, int travelflags, float lookahead, vec3_t target);
+//predict the position of a player based on movement towards a goal
+int BotPredictVisiblePosition(vec3_t origin, int areanum, bot_goal_t *goal, int travelflags, vec3_t target);
+//returns the handle of a newly allocated movestate
+int BotAllocMoveState(void);
+//frees the movestate with the given handle
+void BotFreeMoveState(int handle);
+//initialize movement state before performing any movement
+void BotInitMoveState(int handle, bot_initmove_t *initmove);
+//add a spot to avoid (if type == AVOID_CLEAR all spots are removed)
+void BotAddAvoidSpot(int movestate, vec3_t origin, float radius, int type);
+//must be called every map change
+void BotSetBrushModelTypes(void);
+//setup movement AI
+int BotSetupMoveAI(void);
+//shutdown movement AI
+void BotShutdownMoveAI(void);
+
diff --git a/code/game/be_ai_weap.h b/code/game/be_ai_weap.h
new file mode 100755
index 0000000..6dbb5a2
--- /dev/null
+++ b/code/game/be_ai_weap.h
@@ -0,0 +1,104 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+/*****************************************************************************
+ * name: be_ai_weap.h
+ *
+ * desc: weapon AI
+ *
+ * $Archive: /source/code/botlib/be_ai_weap.h $
+ *
+ *****************************************************************************/
+
+//projectile flags
+#define PFL_WINDOWDAMAGE 1 //projectile damages through window
+#define PFL_RETURN 2 //set when projectile returns to owner
+//weapon flags
+#define WFL_FIRERELEASED 1 //set when projectile is fired with key-up event
+//damage types
+#define DAMAGETYPE_IMPACT 1 //damage on impact
+#define DAMAGETYPE_RADIAL 2 //radial damage
+#define DAMAGETYPE_VISIBLE 4 //damage to all entities visible to the projectile
+
+typedef struct projectileinfo_s
+{
+ char name[MAX_STRINGFIELD];
+ char model[MAX_STRINGFIELD];
+ int flags;
+ float gravity;
+ int damage;
+ float radius;
+ int visdamage;
+ int damagetype;
+ int healthinc;
+ float push;
+ float detonation;
+ float bounce;
+ float bouncefric;
+ float bouncestop;
+} projectileinfo_t;
+
+typedef struct weaponinfo_s
+{
+ int valid; //true if the weapon info is valid
+ int number; //number of the weapon
+ char name[MAX_STRINGFIELD];
+ char model[MAX_STRINGFIELD];
+ int level;
+ int weaponindex;
+ int flags;
+ char projectile[MAX_STRINGFIELD];
+ int numprojectiles;
+ float hspread;
+ float vspread;
+ float speed;
+ float acceleration;
+ vec3_t recoil;
+ vec3_t offset;
+ vec3_t angleoffset;
+ float extrazvelocity;
+ int ammoamount;
+ int ammoindex;
+ float activate;
+ float reload;
+ float spinup;
+ float spindown;
+ projectileinfo_t proj; //pointer to the used projectile
+} weaponinfo_t;
+
+//setup the weapon AI
+int BotSetupWeaponAI(void);
+//shut down the weapon AI
+void BotShutdownWeaponAI(void);
+//returns the best weapon to fight with
+int BotChooseBestFightWeapon(int weaponstate, int *inventory);
+//returns the information of the current weapon
+void BotGetWeaponInfo(int weaponstate, int weapon, weaponinfo_t *weaponinfo);
+//loads the weapon weights
+int BotLoadWeaponWeights(int weaponstate, char *filename);
+//returns a handle to a newly allocated weapon state
+int BotAllocWeaponState(void);
+//frees the weapon state
+void BotFreeWeaponState(int weaponstate);
+//resets the whole weapon state
+void BotResetWeaponState(int weaponstate);
diff --git a/code/game/be_ea.h b/code/game/be_ea.h
new file mode 100755
index 0000000..01cc7e5
--- /dev/null
+++ b/code/game/be_ea.h
@@ -0,0 +1,66 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+/*****************************************************************************
+ * name: be_ea.h
+ *
+ * desc: elementary actions
+ *
+ * $Archive: /source/code/botlib/be_ea.h $
+ *
+ *****************************************************************************/
+
+//ClientCommand elementary actions
+void EA_Say(int client, char *str);
+void EA_SayTeam(int client, char *str);
+void EA_Command(int client, char *command );
+
+void EA_Action(int client, int action);
+void EA_Crouch(int client);
+void EA_Walk(int client);
+void EA_MoveUp(int client);
+void EA_MoveDown(int client);
+void EA_MoveForward(int client);
+void EA_MoveBack(int client);
+void EA_MoveLeft(int client);
+void EA_MoveRight(int client);
+void EA_Attack(int client);
+void EA_Respawn(int client);
+void EA_Talk(int client);
+void EA_Gesture(int client);
+void EA_Use(int client);
+
+//regular elementary actions
+void EA_SelectWeapon(int client, int weapon);
+void EA_Jump(int client);
+void EA_DelayedJump(int client);
+void EA_Move(int client, vec3_t dir, float speed);
+void EA_View(int client, vec3_t viewangles);
+
+//send regular input to the server
+void EA_EndRegular(int client, float thinktime);
+void EA_GetInput(int client, float thinktime, bot_input_t *input);
+void EA_ResetInput(int client);
+//setup and shutdown routines
+int EA_Setup(void);
+void EA_Shutdown(void);
diff --git a/code/game/bg_lib.c b/code/game/bg_lib.c
new file mode 100755
index 0000000..a5ee53e
--- /dev/null
+++ b/code/game/bg_lib.c
@@ -0,0 +1,1324 @@
+//
+//
+// bg_lib,c -- standard C library replacement routines used by code
+// compiled for the virtual machine
+
+#include "q_shared.h"
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. All advertising materials mentioning features or use of this software
+ * must display the following acknowledgement:
+ * This product includes software developed by the University of
+ * California, Berkeley and its contributors.
+ * 4. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static char sccsid[] = "@(#)qsort.c 8.1 (Berkeley) 6/4/93";
+#endif
+static const char rcsid[] =
+#endif /* LIBC_SCCS and not lint */
+
+// bk001127 - needed for DLL's
+#if !defined( Q3_VM )
+typedef int cmp_t(const void *, const void *);
+#endif
+
+static char* med3(char *, char *, char *, cmp_t *);
+static void swapfunc(char *, char *, int, int);
+
+#ifndef min
+#define min(a, b) (a) < (b) ? a : b
+#endif
+
+/*
+ * Qsort routine from Bentley & McIlroy's "Engineering a Sort Function".
+ */
+#define swapcode(TYPE, parmi, parmj, n) { \
+ long i = (n) / sizeof (TYPE); \
+ register TYPE *pi = (TYPE *) (parmi); \
+ register TYPE *pj = (TYPE *) (parmj); \
+ do { \
+ register TYPE t = *pi; \
+ *pi++ = *pj; \
+ *pj++ = t; \
+ } while (--i > 0); \
+}
+
+#define SWAPINIT(a, es) swaptype = ((char *)a - (char *)0) % sizeof(long) || \
+ es % sizeof(long) ? 2 : es == sizeof(long)? 0 : 1;
+
+static void
+swapfunc(a, b, n, swaptype)
+ char *a, *b;
+ int n, swaptype;
+{
+ if(swaptype <= 1)
+ swapcode(long, a, b, n)
+ else
+ swapcode(char, a, b, n)
+}
+
+#define swap(a, b) \
+ if (swaptype == 0) { \
+ long t = *(long *)(a); \
+ *(long *)(a) = *(long *)(b); \
+ *(long *)(b) = t; \
+ } else \
+ swapfunc(a, b, es, swaptype)
+
+#define vecswap(a, b, n) if ((n) > 0) swapfunc(a, b, n, swaptype)
+
+static char *
+med3(a, b, c, cmp)
+ char *a, *b, *c;
+ cmp_t *cmp;
+{
+ return cmp(a, b) < 0 ?
+ (cmp(b, c) < 0 ? b : (cmp(a, c) < 0 ? c : a ))
+ :(cmp(b, c) > 0 ? b : (cmp(a, c) < 0 ? a : c ));
+}
+
+void
+qsort(a, n, es, cmp)
+ void *a;
+ size_t n, es;
+ cmp_t *cmp;
+{
+ char *pa, *pb, *pc, *pd, *pl, *pm, *pn;
+ int d, r, swaptype, swap_cnt;
+
+loop: SWAPINIT(a, es);
+ swap_cnt = 0;
+ if (n < 7) {
+ for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
+ for (pl = pm; pl > (char *)a && cmp(pl - es, pl) > 0;
+ pl -= es)
+ swap(pl, pl - es);
+ return;
+ }
+ pm = (char *)a + (n / 2) * es;
+ if (n > 7) {
+ pl = a;
+ pn = (char *)a + (n - 1) * es;
+ if (n > 40) {
+ d = (n / 8) * es;
+ pl = med3(pl, pl + d, pl + 2 * d, cmp);
+ pm = med3(pm - d, pm, pm + d, cmp);
+ pn = med3(pn - 2 * d, pn - d, pn, cmp);
+ }
+ pm = med3(pl, pm, pn, cmp);
+ }
+ swap(a, pm);
+ pa = pb = (char *)a + es;
+
+ pc = pd = (char *)a + (n - 1) * es;
+ for (;;) {
+ while (pb <= pc && (r = cmp(pb, a)) <= 0) {
+ if (r == 0) {
+ swap_cnt = 1;
+ swap(pa, pb);
+ pa += es;
+ }
+ pb += es;
+ }
+ while (pb <= pc && (r = cmp(pc, a)) >= 0) {
+ if (r == 0) {
+ swap_cnt = 1;
+ swap(pc, pd);
+ pd -= es;
+ }
+ pc -= es;
+ }
+ if (pb > pc)
+ break;
+ swap(pb, pc);
+ swap_cnt = 1;
+ pb += es;
+ pc -= es;
+ }
+ if (swap_cnt == 0) { /* Switch to insertion sort */
+ for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
+ for (pl = pm; pl > (char *)a && cmp(pl - es, pl) > 0;
+ pl -= es)
+ swap(pl, pl - es);
+ return;
+ }
+
+ pn = (char *)a + n * es;
+ r = min(pa - (char *)a, pb - pa);
+ vecswap(a, pb - r, r);
+ r = min(pd - pc, pn - pd - es);
+ vecswap(pb, pn - r, r);
+ if ((r = pb - pa) > es)
+ qsort(a, r / es, es, cmp);
+ if ((r = pd - pc) > es) {
+ /* Iterate rather than recurse to save stack space */
+ a = pn - r;
+ n = r / es;
+ goto loop;
+ }
+/* qsort(pn - r, r / es, es, cmp);*/
+}
+
+//==================================================================================
+
+
+// this file is excluded from release builds because of intrinsics
+
+// bk001211 - gcc errors on compiling strcpy: parse error before `__extension__'
+#if defined ( Q3_VM )
+
+size_t strlen( const char *string ) {
+ const char *s;
+
+ s = string;
+ while ( *s ) {
+ s++;
+ }
+ return s - string;
+}
+
+
+char *strcat( char *strDestination, const char *strSource ) {
+ char *s;
+
+ s = strDestination;
+ while ( *s ) {
+ s++;
+ }
+ while ( *strSource ) {
+ *s++ = *strSource++;
+ }
+ *s = 0;
+ return strDestination;
+}
+
+char *strcpy( char *strDestination, const char *strSource ) {
+ char *s;
+
+ s = strDestination;
+ while ( *strSource ) {
+ *s++ = *strSource++;
+ }
+ *s = 0;
+ return strDestination;
+}
+
+
+int strcmp( const char *string1, const char *string2 ) {
+ while ( *string1 == *string2 && *string1 && *string2 ) {
+ string1++;
+ string2++;
+ }
+ return *string1 - *string2;
+}
+
+
+char *strchr( const char *string, int c ) {
+ while ( *string ) {
+ if ( *string == c ) {
+ return ( char * )string;
+ }
+ string++;
+ }
+ return (char *)0;
+}
+
+char *strstr( const char *string, const char *strCharSet ) {
+ while ( *string ) {
+ int i;
+
+ for ( i = 0 ; strCharSet[i] ; i++ ) {
+ if ( string[i] != strCharSet[i] ) {
+ break;
+ }
+ }
+ if ( !strCharSet[i] ) {
+ return (char *)string;
+ }
+ string++;
+ }
+ return (char *)0;
+}
+#endif // bk001211
+
+// bk001120 - presumably needed for Mac
+//#if !defined(_MSC_VER) && !defined(__linux__)
+// bk001127 - undid undo
+#if defined ( Q3_VM )
+int tolower( int c ) {
+ if ( c >= 'A' && c <= 'Z' ) {
+ c += 'a' - 'A';
+ }
+ return c;
+}
+
+
+int toupper( int c ) {
+ if ( c >= 'a' && c <= 'z' ) {
+ c += 'A' - 'a';
+ }
+ return c;
+}
+
+#endif
+//#ifndef _MSC_VER
+
+void *memmove( void *dest, const void *src, size_t count ) {
+ int i;
+
+ if ( dest > src ) {
+ for ( i = count-1 ; i >= 0 ; i-- ) {
+ ((char *)dest)[i] = ((char *)src)[i];
+ }
+ } else {
+ for ( i = 0 ; i < count ; i++ ) {
+ ((char *)dest)[i] = ((char *)src)[i];
+ }
+ }
+ return dest;
+}
+
+
+#if 0
+
+double floor( double x ) {
+ return (int)(x + 0x40000000) - 0x40000000;
+}
+
+void *memset( void *dest, int c, size_t count ) {
+ while ( count-- ) {
+ ((char *)dest)[count] = c;
+ }
+ return dest;
+}
+
+void *memcpy( void *dest, const void *src, size_t count ) {
+ while ( count-- ) {
+ ((char *)dest)[count] = ((char *)src)[count];
+ }
+ return dest;
+}
+
+char *strncpy( char *strDest, const char *strSource, size_t count ) {
+ char *s;
+
+ s = strDest;
+ while ( *strSource && count ) {
+ *s++ = *strSource++;
+ count--;
+ }
+ while ( count-- ) {
+ *s++ = 0;
+ }
+ return strDest;
+}
+
+double sqrt( double x ) {
+ float y;
+ float delta;
+ float maxError;
+
+ if ( x <= 0 ) {
+ return 0;
+ }
+
+ // initial guess
+ y = x / 2;
+
+ // refine
+ maxError = x * 0.001;
+
+ do {
+ delta = ( y * y ) - x;
+ y -= delta / ( 2 * y );
+ } while ( delta > maxError || delta < -maxError );
+
+ return y;
+}
+
+
+float sintable[1024] = {
+0.000000,0.001534,0.003068,0.004602,0.006136,0.007670,0.009204,0.010738,
+0.012272,0.013805,0.015339,0.016873,0.018407,0.019940,0.021474,0.023008,
+0.024541,0.026075,0.027608,0.029142,0.030675,0.032208,0.033741,0.035274,
+0.036807,0.038340,0.039873,0.041406,0.042938,0.044471,0.046003,0.047535,
+0.049068,0.050600,0.052132,0.053664,0.055195,0.056727,0.058258,0.059790,
+0.061321,0.062852,0.064383,0.065913,0.067444,0.068974,0.070505,0.072035,
+0.073565,0.075094,0.076624,0.078153,0.079682,0.081211,0.082740,0.084269,
+0.085797,0.087326,0.088854,0.090381,0.091909,0.093436,0.094963,0.096490,
+0.098017,0.099544,0.101070,0.102596,0.104122,0.105647,0.107172,0.108697,
+0.110222,0.111747,0.113271,0.114795,0.116319,0.117842,0.119365,0.120888,
+0.122411,0.123933,0.125455,0.126977,0.128498,0.130019,0.131540,0.133061,
+0.134581,0.136101,0.137620,0.139139,0.140658,0.142177,0.143695,0.145213,
+0.146730,0.148248,0.149765,0.151281,0.152797,0.154313,0.155828,0.157343,
+0.158858,0.160372,0.161886,0.163400,0.164913,0.166426,0.167938,0.169450,
+0.170962,0.172473,0.173984,0.175494,0.177004,0.178514,0.180023,0.181532,
+0.183040,0.184548,0.186055,0.187562,0.189069,0.190575,0.192080,0.193586,
+0.195090,0.196595,0.198098,0.199602,0.201105,0.202607,0.204109,0.205610,
+0.207111,0.208612,0.210112,0.211611,0.213110,0.214609,0.216107,0.217604,
+0.219101,0.220598,0.222094,0.223589,0.225084,0.226578,0.228072,0.229565,
+0.231058,0.232550,0.234042,0.235533,0.237024,0.238514,0.240003,0.241492,
+0.242980,0.244468,0.245955,0.247442,0.248928,0.250413,0.251898,0.253382,
+0.254866,0.256349,0.257831,0.259313,0.260794,0.262275,0.263755,0.265234,
+0.266713,0.268191,0.269668,0.271145,0.272621,0.274097,0.275572,0.277046,
+0.278520,0.279993,0.281465,0.282937,0.284408,0.285878,0.287347,0.288816,
+0.290285,0.291752,0.293219,0.294685,0.296151,0.297616,0.299080,0.300543,
+0.302006,0.303468,0.304929,0.306390,0.307850,0.309309,0.310767,0.312225,
+0.313682,0.315138,0.316593,0.318048,0.319502,0.320955,0.322408,0.323859,
+0.325310,0.326760,0.328210,0.329658,0.331106,0.332553,0.334000,0.335445,
+0.336890,0.338334,0.339777,0.341219,0.342661,0.344101,0.345541,0.346980,
+0.348419,0.349856,0.351293,0.352729,0.354164,0.355598,0.357031,0.358463,
+0.359895,0.361326,0.362756,0.364185,0.365613,0.367040,0.368467,0.369892,
+0.371317,0.372741,0.374164,0.375586,0.377007,0.378428,0.379847,0.381266,
+0.382683,0.384100,0.385516,0.386931,0.388345,0.389758,0.391170,0.392582,
+0.393992,0.395401,0.396810,0.398218,0.399624,0.401030,0.402435,0.403838,
+0.405241,0.406643,0.408044,0.409444,0.410843,0.412241,0.413638,0.415034,
+0.416430,0.417824,0.419217,0.420609,0.422000,0.423390,0.424780,0.426168,
+0.427555,0.428941,0.430326,0.431711,0.433094,0.434476,0.435857,0.437237,
+0.438616,0.439994,0.441371,0.442747,0.444122,0.445496,0.446869,0.448241,
+0.449611,0.450981,0.452350,0.453717,0.455084,0.456449,0.457813,0.459177,
+0.460539,0.461900,0.463260,0.464619,0.465976,0.467333,0.468689,0.470043,
+0.471397,0.472749,0.474100,0.475450,0.476799,0.478147,0.479494,0.480839,
+0.482184,0.483527,0.484869,0.486210,0.487550,0.488889,0.490226,0.491563,
+0.492898,0.494232,0.495565,0.496897,0.498228,0.499557,0.500885,0.502212,
+0.503538,0.504863,0.506187,0.507509,0.508830,0.510150,0.511469,0.512786,
+0.514103,0.515418,0.516732,0.518045,0.519356,0.520666,0.521975,0.523283,
+0.524590,0.525895,0.527199,0.528502,0.529804,0.531104,0.532403,0.533701,
+0.534998,0.536293,0.537587,0.538880,0.540171,0.541462,0.542751,0.544039,
+0.545325,0.546610,0.547894,0.549177,0.550458,0.551738,0.553017,0.554294,
+0.555570,0.556845,0.558119,0.559391,0.560662,0.561931,0.563199,0.564466,
+0.565732,0.566996,0.568259,0.569521,0.570781,0.572040,0.573297,0.574553,
+0.575808,0.577062,0.578314,0.579565,0.580814,0.582062,0.583309,0.584554,
+0.585798,0.587040,0.588282,0.589521,0.590760,0.591997,0.593232,0.594466,
+0.595699,0.596931,0.598161,0.599389,0.600616,0.601842,0.603067,0.604290,
+0.605511,0.606731,0.607950,0.609167,0.610383,0.611597,0.612810,0.614022,
+0.615232,0.616440,0.617647,0.618853,0.620057,0.621260,0.622461,0.623661,
+0.624859,0.626056,0.627252,0.628446,0.629638,0.630829,0.632019,0.633207,
+0.634393,0.635578,0.636762,0.637944,0.639124,0.640303,0.641481,0.642657,
+0.643832,0.645005,0.646176,0.647346,0.648514,0.649681,0.650847,0.652011,
+0.653173,0.654334,0.655493,0.656651,0.657807,0.658961,0.660114,0.661266,
+0.662416,0.663564,0.664711,0.665856,0.667000,0.668142,0.669283,0.670422,
+0.671559,0.672695,0.673829,0.674962,0.676093,0.677222,0.678350,0.679476,
+0.680601,0.681724,0.682846,0.683965,0.685084,0.686200,0.687315,0.688429,
+0.689541,0.690651,0.691759,0.692866,0.693971,0.695075,0.696177,0.697278,
+0.698376,0.699473,0.700569,0.701663,0.702755,0.703845,0.704934,0.706021,
+0.707107,0.708191,0.709273,0.710353,0.711432,0.712509,0.713585,0.714659,
+0.715731,0.716801,0.717870,0.718937,0.720003,0.721066,0.722128,0.723188,
+0.724247,0.725304,0.726359,0.727413,0.728464,0.729514,0.730563,0.731609,
+0.732654,0.733697,0.734739,0.735779,0.736817,0.737853,0.738887,0.739920,
+0.740951,0.741980,0.743008,0.744034,0.745058,0.746080,0.747101,0.748119,
+0.749136,0.750152,0.751165,0.752177,0.753187,0.754195,0.755201,0.756206,
+0.757209,0.758210,0.759209,0.760207,0.761202,0.762196,0.763188,0.764179,
+0.765167,0.766154,0.767139,0.768122,0.769103,0.770083,0.771061,0.772036,
+0.773010,0.773983,0.774953,0.775922,0.776888,0.777853,0.778817,0.779778,
+0.780737,0.781695,0.782651,0.783605,0.784557,0.785507,0.786455,0.787402,
+0.788346,0.789289,0.790230,0.791169,0.792107,0.793042,0.793975,0.794907,
+0.795837,0.796765,0.797691,0.798615,0.799537,0.800458,0.801376,0.802293,
+0.803208,0.804120,0.805031,0.805940,0.806848,0.807753,0.808656,0.809558,
+0.810457,0.811355,0.812251,0.813144,0.814036,0.814926,0.815814,0.816701,
+0.817585,0.818467,0.819348,0.820226,0.821103,0.821977,0.822850,0.823721,
+0.824589,0.825456,0.826321,0.827184,0.828045,0.828904,0.829761,0.830616,
+0.831470,0.832321,0.833170,0.834018,0.834863,0.835706,0.836548,0.837387,
+0.838225,0.839060,0.839894,0.840725,0.841555,0.842383,0.843208,0.844032,
+0.844854,0.845673,0.846491,0.847307,0.848120,0.848932,0.849742,0.850549,
+0.851355,0.852159,0.852961,0.853760,0.854558,0.855354,0.856147,0.856939,
+0.857729,0.858516,0.859302,0.860085,0.860867,0.861646,0.862424,0.863199,
+0.863973,0.864744,0.865514,0.866281,0.867046,0.867809,0.868571,0.869330,
+0.870087,0.870842,0.871595,0.872346,0.873095,0.873842,0.874587,0.875329,
+0.876070,0.876809,0.877545,0.878280,0.879012,0.879743,0.880471,0.881197,
+0.881921,0.882643,0.883363,0.884081,0.884797,0.885511,0.886223,0.886932,
+0.887640,0.888345,0.889048,0.889750,0.890449,0.891146,0.891841,0.892534,
+0.893224,0.893913,0.894599,0.895284,0.895966,0.896646,0.897325,0.898001,
+0.898674,0.899346,0.900016,0.900683,0.901349,0.902012,0.902673,0.903332,
+0.903989,0.904644,0.905297,0.905947,0.906596,0.907242,0.907886,0.908528,
+0.909168,0.909806,0.910441,0.911075,0.911706,0.912335,0.912962,0.913587,
+0.914210,0.914830,0.915449,0.916065,0.916679,0.917291,0.917901,0.918508,
+0.919114,0.919717,0.920318,0.920917,0.921514,0.922109,0.922701,0.923291,
+0.923880,0.924465,0.925049,0.925631,0.926210,0.926787,0.927363,0.927935,
+0.928506,0.929075,0.929641,0.930205,0.930767,0.931327,0.931884,0.932440,
+0.932993,0.933544,0.934093,0.934639,0.935184,0.935726,0.936266,0.936803,
+0.937339,0.937872,0.938404,0.938932,0.939459,0.939984,0.940506,0.941026,
+0.941544,0.942060,0.942573,0.943084,0.943593,0.944100,0.944605,0.945107,
+0.945607,0.946105,0.946601,0.947094,0.947586,0.948075,0.948561,0.949046,
+0.949528,0.950008,0.950486,0.950962,0.951435,0.951906,0.952375,0.952842,
+0.953306,0.953768,0.954228,0.954686,0.955141,0.955594,0.956045,0.956494,
+0.956940,0.957385,0.957826,0.958266,0.958703,0.959139,0.959572,0.960002,
+0.960431,0.960857,0.961280,0.961702,0.962121,0.962538,0.962953,0.963366,
+0.963776,0.964184,0.964590,0.964993,0.965394,0.965793,0.966190,0.966584,
+0.966976,0.967366,0.967754,0.968139,0.968522,0.968903,0.969281,0.969657,
+0.970031,0.970403,0.970772,0.971139,0.971504,0.971866,0.972226,0.972584,
+0.972940,0.973293,0.973644,0.973993,0.974339,0.974684,0.975025,0.975365,
+0.975702,0.976037,0.976370,0.976700,0.977028,0.977354,0.977677,0.977999,
+0.978317,0.978634,0.978948,0.979260,0.979570,0.979877,0.980182,0.980485,
+0.980785,0.981083,0.981379,0.981673,0.981964,0.982253,0.982539,0.982824,
+0.983105,0.983385,0.983662,0.983937,0.984210,0.984480,0.984749,0.985014,
+0.985278,0.985539,0.985798,0.986054,0.986308,0.986560,0.986809,0.987057,
+0.987301,0.987544,0.987784,0.988022,0.988258,0.988491,0.988722,0.988950,
+0.989177,0.989400,0.989622,0.989841,0.990058,0.990273,0.990485,0.990695,
+0.990903,0.991108,0.991311,0.991511,0.991710,0.991906,0.992099,0.992291,
+0.992480,0.992666,0.992850,0.993032,0.993212,0.993389,0.993564,0.993737,
+0.993907,0.994075,0.994240,0.994404,0.994565,0.994723,0.994879,0.995033,
+0.995185,0.995334,0.995481,0.995625,0.995767,0.995907,0.996045,0.996180,
+0.996313,0.996443,0.996571,0.996697,0.996820,0.996941,0.997060,0.997176,
+0.997290,0.997402,0.997511,0.997618,0.997723,0.997825,0.997925,0.998023,
+0.998118,0.998211,0.998302,0.998390,0.998476,0.998559,0.998640,0.998719,
+0.998795,0.998870,0.998941,0.999011,0.999078,0.999142,0.999205,0.999265,
+0.999322,0.999378,0.999431,0.999481,0.999529,0.999575,0.999619,0.999660,
+0.999699,0.999735,0.999769,0.999801,0.999831,0.999858,0.999882,0.999905,
+0.999925,0.999942,0.999958,0.999971,0.999981,0.999989,0.999995,0.999999
+};
+
+double sin( double x ) {
+ int index;
+ int quad;
+
+ index = 1024 * x / (M_PI * 0.5);
+ quad = ( index >> 10 ) & 3;
+ index &= 1023;
+ switch ( quad ) {
+ case 0:
+ return sintable[index];
+ case 1:
+ return sintable[1023-index];
+ case 2:
+ return -sintable[index];
+ case 3:
+ return -sintable[1023-index];
+ }
+ return 0;
+}
+
+
+double cos( double x ) {
+ int index;
+ int quad;
+
+ index = 1024 * x / (M_PI * 0.5);
+ quad = ( index >> 10 ) & 3;
+ index &= 1023;
+ switch ( quad ) {
+ case 3:
+ return sintable[index];
+ case 0:
+ return sintable[1023-index];
+ case 1:
+ return -sintable[index];
+ case 2:
+ return -sintable[1023-index];
+ }
+ return 0;
+}
+
+
+/*
+void create_acostable( void ) {
+ int i;
+ FILE *fp;
+ float a;
+
+ fp = fopen("c:\\acostable.txt", "w");
+ fprintf(fp, "float acostable[] = {");
+ for (i = 0; i < 1024; i++) {
+ if (!(i & 7))
+ fprintf(fp, "\n");
+ a = acos( (float) -1 + i / 512 );
+ fprintf(fp, "%1.8f,", a);
+ }
+ fprintf(fp, "\n}\n");
+ fclose(fp);
+}
+*/
+
+float acostable[] = {
+3.14159265,3.07908248,3.05317551,3.03328655,3.01651113,3.00172442,2.98834964,2.97604422,
+2.96458497,2.95381690,2.94362719,2.93393068,2.92466119,2.91576615,2.90720289,2.89893629,
+2.89093699,2.88318015,2.87564455,2.86831188,2.86116621,2.85419358,2.84738169,2.84071962,
+2.83419760,2.82780691,2.82153967,2.81538876,2.80934770,2.80341062,2.79757211,2.79182724,
+2.78617145,2.78060056,2.77511069,2.76969824,2.76435988,2.75909250,2.75389319,2.74875926,
+2.74368816,2.73867752,2.73372510,2.72882880,2.72398665,2.71919677,2.71445741,2.70976688,
+2.70512362,2.70052613,2.69597298,2.69146283,2.68699438,2.68256642,2.67817778,2.67382735,
+2.66951407,2.66523692,2.66099493,2.65678719,2.65261279,2.64847088,2.64436066,2.64028133,
+2.63623214,2.63221238,2.62822133,2.62425835,2.62032277,2.61641398,2.61253138,2.60867440,
+2.60484248,2.60103507,2.59725167,2.59349176,2.58975488,2.58604053,2.58234828,2.57867769,
+2.57502832,2.57139977,2.56779164,2.56420354,2.56063509,2.55708594,2.55355572,2.55004409,
+2.54655073,2.54307530,2.53961750,2.53617701,2.53275354,2.52934680,2.52595650,2.52258238,
+2.51922417,2.51588159,2.51255441,2.50924238,2.50594525,2.50266278,2.49939476,2.49614096,
+2.49290115,2.48967513,2.48646269,2.48326362,2.48007773,2.47690482,2.47374472,2.47059722,
+2.46746215,2.46433933,2.46122860,2.45812977,2.45504269,2.45196720,2.44890314,2.44585034,
+2.44280867,2.43977797,2.43675809,2.43374890,2.43075025,2.42776201,2.42478404,2.42181622,
+2.41885841,2.41591048,2.41297232,2.41004380,2.40712480,2.40421521,2.40131491,2.39842379,
+2.39554173,2.39266863,2.38980439,2.38694889,2.38410204,2.38126374,2.37843388,2.37561237,
+2.37279910,2.36999400,2.36719697,2.36440790,2.36162673,2.35885335,2.35608768,2.35332964,
+2.35057914,2.34783610,2.34510044,2.34237208,2.33965094,2.33693695,2.33423003,2.33153010,
+2.32883709,2.32615093,2.32347155,2.32079888,2.31813284,2.31547337,2.31282041,2.31017388,
+2.30753373,2.30489988,2.30227228,2.29965086,2.29703556,2.29442632,2.29182309,2.28922580,
+2.28663439,2.28404881,2.28146900,2.27889490,2.27632647,2.27376364,2.27120637,2.26865460,
+2.26610827,2.26356735,2.26103177,2.25850149,2.25597646,2.25345663,2.25094195,2.24843238,
+2.24592786,2.24342836,2.24093382,2.23844420,2.23595946,2.23347956,2.23100444,2.22853408,
+2.22606842,2.22360742,2.22115104,2.21869925,2.21625199,2.21380924,2.21137096,2.20893709,
+2.20650761,2.20408248,2.20166166,2.19924511,2.19683280,2.19442469,2.19202074,2.18962092,
+2.18722520,2.18483354,2.18244590,2.18006225,2.17768257,2.17530680,2.17293493,2.17056692,
+2.16820274,2.16584236,2.16348574,2.16113285,2.15878367,2.15643816,2.15409630,2.15175805,
+2.14942338,2.14709226,2.14476468,2.14244059,2.14011997,2.13780279,2.13548903,2.13317865,
+2.13087163,2.12856795,2.12626757,2.12397047,2.12167662,2.11938600,2.11709859,2.11481435,
+2.11253326,2.11025530,2.10798044,2.10570867,2.10343994,2.10117424,2.09891156,2.09665185,
+2.09439510,2.09214129,2.08989040,2.08764239,2.08539725,2.08315496,2.08091550,2.07867884,
+2.07644495,2.07421383,2.07198545,2.06975978,2.06753681,2.06531651,2.06309887,2.06088387,
+2.05867147,2.05646168,2.05425445,2.05204979,2.04984765,2.04764804,2.04545092,2.04325628,
+2.04106409,2.03887435,2.03668703,2.03450211,2.03231957,2.03013941,2.02796159,2.02578610,
+2.02361292,2.02144204,2.01927344,2.01710710,2.01494300,2.01278113,2.01062146,2.00846399,
+2.00630870,2.00415556,2.00200457,1.99985570,1.99770895,1.99556429,1.99342171,1.99128119,
+1.98914271,1.98700627,1.98487185,1.98273942,1.98060898,1.97848051,1.97635399,1.97422942,
+1.97210676,1.96998602,1.96786718,1.96575021,1.96363511,1.96152187,1.95941046,1.95730088,
+1.95519310,1.95308712,1.95098292,1.94888050,1.94677982,1.94468089,1.94258368,1.94048818,
+1.93839439,1.93630228,1.93421185,1.93212308,1.93003595,1.92795046,1.92586659,1.92378433,
+1.92170367,1.91962459,1.91754708,1.91547113,1.91339673,1.91132385,1.90925250,1.90718266,
+1.90511432,1.90304746,1.90098208,1.89891815,1.89685568,1.89479464,1.89273503,1.89067683,
+1.88862003,1.88656463,1.88451060,1.88245794,1.88040664,1.87835668,1.87630806,1.87426076,
+1.87221477,1.87017008,1.86812668,1.86608457,1.86404371,1.86200412,1.85996577,1.85792866,
+1.85589277,1.85385809,1.85182462,1.84979234,1.84776125,1.84573132,1.84370256,1.84167495,
+1.83964848,1.83762314,1.83559892,1.83357582,1.83155381,1.82953289,1.82751305,1.82549429,
+1.82347658,1.82145993,1.81944431,1.81742973,1.81541617,1.81340362,1.81139207,1.80938151,
+1.80737194,1.80536334,1.80335570,1.80134902,1.79934328,1.79733848,1.79533460,1.79333164,
+1.79132959,1.78932843,1.78732817,1.78532878,1.78333027,1.78133261,1.77933581,1.77733985,
+1.77534473,1.77335043,1.77135695,1.76936428,1.76737240,1.76538132,1.76339101,1.76140148,
+1.75941271,1.75742470,1.75543743,1.75345090,1.75146510,1.74948002,1.74749565,1.74551198,
+1.74352900,1.74154672,1.73956511,1.73758417,1.73560389,1.73362426,1.73164527,1.72966692,
+1.72768920,1.72571209,1.72373560,1.72175971,1.71978441,1.71780969,1.71583556,1.71386199,
+1.71188899,1.70991653,1.70794462,1.70597325,1.70400241,1.70203209,1.70006228,1.69809297,
+1.69612416,1.69415584,1.69218799,1.69022062,1.68825372,1.68628727,1.68432127,1.68235571,
+1.68039058,1.67842588,1.67646160,1.67449772,1.67253424,1.67057116,1.66860847,1.66664615,
+1.66468420,1.66272262,1.66076139,1.65880050,1.65683996,1.65487975,1.65291986,1.65096028,
+1.64900102,1.64704205,1.64508338,1.64312500,1.64116689,1.63920905,1.63725148,1.63529416,
+1.63333709,1.63138026,1.62942366,1.62746728,1.62551112,1.62355517,1.62159943,1.61964388,
+1.61768851,1.61573332,1.61377831,1.61182346,1.60986877,1.60791422,1.60595982,1.60400556,
+1.60205142,1.60009739,1.59814349,1.59618968,1.59423597,1.59228235,1.59032882,1.58837536,
+1.58642196,1.58446863,1.58251535,1.58056211,1.57860891,1.57665574,1.57470259,1.57274945,
+1.57079633,1.56884320,1.56689007,1.56493692,1.56298375,1.56103055,1.55907731,1.55712403,
+1.55517069,1.55321730,1.55126383,1.54931030,1.54735668,1.54540297,1.54344917,1.54149526,
+1.53954124,1.53758710,1.53563283,1.53367843,1.53172389,1.52976919,1.52781434,1.52585933,
+1.52390414,1.52194878,1.51999323,1.51803748,1.51608153,1.51412537,1.51216900,1.51021240,
+1.50825556,1.50629849,1.50434117,1.50238360,1.50042576,1.49846765,1.49650927,1.49455060,
+1.49259163,1.49063237,1.48867280,1.48671291,1.48475270,1.48279215,1.48083127,1.47887004,
+1.47690845,1.47494650,1.47298419,1.47102149,1.46905841,1.46709493,1.46513106,1.46316677,
+1.46120207,1.45923694,1.45727138,1.45530538,1.45333893,1.45137203,1.44940466,1.44743682,
+1.44546850,1.44349969,1.44153038,1.43956057,1.43759024,1.43561940,1.43364803,1.43167612,
+1.42970367,1.42773066,1.42575709,1.42378296,1.42180825,1.41983295,1.41785705,1.41588056,
+1.41390346,1.41192573,1.40994738,1.40796840,1.40598877,1.40400849,1.40202755,1.40004594,
+1.39806365,1.39608068,1.39409701,1.39211264,1.39012756,1.38814175,1.38615522,1.38416795,
+1.38217994,1.38019117,1.37820164,1.37621134,1.37422025,1.37222837,1.37023570,1.36824222,
+1.36624792,1.36425280,1.36225684,1.36026004,1.35826239,1.35626387,1.35426449,1.35226422,
+1.35026307,1.34826101,1.34625805,1.34425418,1.34224937,1.34024364,1.33823695,1.33622932,
+1.33422072,1.33221114,1.33020059,1.32818904,1.32617649,1.32416292,1.32214834,1.32013273,
+1.31811607,1.31609837,1.31407960,1.31205976,1.31003885,1.30801684,1.30599373,1.30396951,
+1.30194417,1.29991770,1.29789009,1.29586133,1.29383141,1.29180031,1.28976803,1.28773456,
+1.28569989,1.28366400,1.28162688,1.27958854,1.27754894,1.27550809,1.27346597,1.27142257,
+1.26937788,1.26733189,1.26528459,1.26323597,1.26118602,1.25913471,1.25708205,1.25502803,
+1.25297262,1.25091583,1.24885763,1.24679802,1.24473698,1.24267450,1.24061058,1.23854519,
+1.23647833,1.23440999,1.23234015,1.23026880,1.22819593,1.22612152,1.22404557,1.22196806,
+1.21988898,1.21780832,1.21572606,1.21364219,1.21155670,1.20946958,1.20738080,1.20529037,
+1.20319826,1.20110447,1.19900898,1.19691177,1.19481283,1.19271216,1.19060973,1.18850553,
+1.18639955,1.18429178,1.18218219,1.18007079,1.17795754,1.17584244,1.17372548,1.17160663,
+1.16948589,1.16736324,1.16523866,1.16311215,1.16098368,1.15885323,1.15672081,1.15458638,
+1.15244994,1.15031147,1.14817095,1.14602836,1.14388370,1.14173695,1.13958808,1.13743709,
+1.13528396,1.13312866,1.13097119,1.12881153,1.12664966,1.12448556,1.12231921,1.12015061,
+1.11797973,1.11580656,1.11363107,1.11145325,1.10927308,1.10709055,1.10490563,1.10271831,
+1.10052856,1.09833638,1.09614174,1.09394462,1.09174500,1.08954287,1.08733820,1.08513098,
+1.08292118,1.08070879,1.07849378,1.07627614,1.07405585,1.07183287,1.06960721,1.06737882,
+1.06514770,1.06291382,1.06067715,1.05843769,1.05619540,1.05395026,1.05170226,1.04945136,
+1.04719755,1.04494080,1.04268110,1.04041841,1.03815271,1.03588399,1.03361221,1.03133735,
+1.02905939,1.02677830,1.02449407,1.02220665,1.01991603,1.01762219,1.01532509,1.01302471,
+1.01072102,1.00841400,1.00610363,1.00378986,1.00147268,0.99915206,0.99682798,0.99450039,
+0.99216928,0.98983461,0.98749636,0.98515449,0.98280898,0.98045980,0.97810691,0.97575030,
+0.97338991,0.97102573,0.96865772,0.96628585,0.96391009,0.96153040,0.95914675,0.95675912,
+0.95436745,0.95197173,0.94957191,0.94716796,0.94475985,0.94234754,0.93993099,0.93751017,
+0.93508504,0.93265556,0.93022170,0.92778341,0.92534066,0.92289341,0.92044161,0.91798524,
+0.91552424,0.91305858,0.91058821,0.90811309,0.90563319,0.90314845,0.90065884,0.89816430,
+0.89566479,0.89316028,0.89065070,0.88813602,0.88561619,0.88309116,0.88056088,0.87802531,
+0.87548438,0.87293806,0.87038629,0.86782901,0.86526619,0.86269775,0.86012366,0.85754385,
+0.85495827,0.85236686,0.84976956,0.84716633,0.84455709,0.84194179,0.83932037,0.83669277,
+0.83405893,0.83141877,0.82877225,0.82611928,0.82345981,0.82079378,0.81812110,0.81544172,
+0.81275556,0.81006255,0.80736262,0.80465570,0.80194171,0.79922057,0.79649221,0.79375655,
+0.79101352,0.78826302,0.78550497,0.78273931,0.77996593,0.77718475,0.77439569,0.77159865,
+0.76879355,0.76598029,0.76315878,0.76032891,0.75749061,0.75464376,0.75178826,0.74892402,
+0.74605092,0.74316887,0.74027775,0.73737744,0.73446785,0.73154885,0.72862033,0.72568217,
+0.72273425,0.71977644,0.71680861,0.71383064,0.71084240,0.70784376,0.70483456,0.70181469,
+0.69878398,0.69574231,0.69268952,0.68962545,0.68654996,0.68346288,0.68036406,0.67725332,
+0.67413051,0.67099544,0.66784794,0.66468783,0.66151492,0.65832903,0.65512997,0.65191753,
+0.64869151,0.64545170,0.64219789,0.63892987,0.63564741,0.63235028,0.62903824,0.62571106,
+0.62236849,0.61901027,0.61563615,0.61224585,0.60883911,0.60541564,0.60197515,0.59851735,
+0.59504192,0.59154856,0.58803694,0.58450672,0.58095756,0.57738911,0.57380101,0.57019288,
+0.56656433,0.56291496,0.55924437,0.55555212,0.55183778,0.54810089,0.54434099,0.54055758,
+0.53675018,0.53291825,0.52906127,0.52517867,0.52126988,0.51733431,0.51337132,0.50938028,
+0.50536051,0.50131132,0.49723200,0.49312177,0.48897987,0.48480547,0.48059772,0.47635573,
+0.47207859,0.46776530,0.46341487,0.45902623,0.45459827,0.45012983,0.44561967,0.44106652,
+0.43646903,0.43182577,0.42713525,0.42239588,0.41760600,0.41276385,0.40786755,0.40291513,
+0.39790449,0.39283339,0.38769946,0.38250016,0.37723277,0.37189441,0.36648196,0.36099209,
+0.35542120,0.34976542,0.34402054,0.33818204,0.33224495,0.32620390,0.32005298,0.31378574,
+0.30739505,0.30087304,0.29421096,0.28739907,0.28042645,0.27328078,0.26594810,0.25841250,
+0.25065566,0.24265636,0.23438976,0.22582651,0.21693146,0.20766198,0.19796546,0.18777575,
+0.17700769,0.16554844,0.15324301,0.13986823,0.12508152,0.10830610,0.08841715,0.06251018,
+}
+
+double acos( double x ) {
+ int index;
+
+ if (x < -1)
+ x = -1;
+ if (x > 1)
+ x = 1;
+ index = (float) (1.0 + x) * 511.9;
+ return acostable[index];
+}
+
+double atan2( double y, double x ) {
+ float base;
+ float temp;
+ float dir;
+ float test;
+ int i;
+
+ if ( x < 0 ) {
+ if ( y >= 0 ) {
+ // quad 1
+ base = M_PI / 2;
+ temp = x;
+ x = y;
+ y = -temp;
+ } else {
+ // quad 2
+ base = M_PI;
+ x = -x;
+ y = -y;
+ }
+ } else {
+ if ( y < 0 ) {
+ // quad 3
+ base = 3 * M_PI / 2;
+ temp = x;
+ x = -y;
+ y = temp;
+ }
+ }
+
+ if ( y > x ) {
+ base += M_PI/2;
+ temp = x;
+ x = y;
+ y = temp;
+ dir = -1;
+ } else {
+ dir = 1;
+ }
+
+ // calcualte angle in octant 0
+ if ( x == 0 ) {
+ return base;
+ }
+ y /= x;
+
+ for ( i = 0 ; i < 512 ; i++ ) {
+ test = sintable[i] / sintable[1023-i];
+ if ( test > y ) {
+ break;
+ }
+ }
+
+ return base + dir * i * ( M_PI/2048);
+}
+
+
+#endif
+
+#ifdef Q3_VM
+// bk001127 - guarded this tan replacement
+// ld: undefined versioned symbol name tan@@GLIBC_2.0
+double tan( double x ) {
+ return sin(x) / cos(x);
+}
+#endif
+
+
+static int randSeed = 0;
+
+void srand( unsigned seed ) {
+ randSeed = seed;
+}
+
+int rand( void ) {
+ randSeed = (69069 * randSeed + 1);
+ return randSeed & 0x7fff;
+}
+
+double atof( const char *string ) {
+ float sign;
+ float value;
+ int c;
+
+
+ // skip whitespace
+ while ( *string <= ' ' ) {
+ if ( !*string ) {
+ return 0;
+ }
+ string++;
+ }
+
+ // check sign
+ switch ( *string ) {
+ case '+':
+ string++;
+ sign = 1;
+ break;
+ case '-':
+ string++;
+ sign = -1;
+ break;
+ default:
+ sign = 1;
+ break;
+ }
+
+ // read digits
+ value = 0;
+ c = string[0];
+ if ( c != '.' ) {
+ do {
+ c = *string++;
+ if ( c < '0' || c > '9' ) {
+ break;
+ }
+ c -= '0';
+ value = value * 10 + c;
+ } while ( 1 );
+ } else {
+ string++;
+ }
+
+ // check for decimal point
+ if ( c == '.' ) {
+ double fraction;
+
+ fraction = 0.1;
+ do {
+ c = *string++;
+ if ( c < '0' || c > '9' ) {
+ break;
+ }
+ c -= '0';
+ value += c * fraction;
+ fraction *= 0.1;
+ } while ( 1 );
+
+ }
+
+ // not handling 10e10 notation...
+
+ return value * sign;
+}
+
+double _atof( const char **stringPtr ) {
+ const char *string;
+ float sign;
+ float value;
+ int c = '0'; // bk001211 - uninitialized use possible
+
+ string = *stringPtr;
+
+ // skip whitespace
+ while ( *string <= ' ' ) {
+ if ( !*string ) {
+ *stringPtr = string;
+ return 0;
+ }
+ string++;
+ }
+
+ // check sign
+ switch ( *string ) {
+ case '+':
+ string++;
+ sign = 1;
+ break;
+ case '-':
+ string++;
+ sign = -1;
+ break;
+ default:
+ sign = 1;
+ break;
+ }
+
+ // read digits
+ value = 0;
+ if ( string[0] != '.' ) {
+ do {
+ c = *string++;
+ if ( c < '0' || c > '9' ) {
+ break;
+ }
+ c -= '0';
+ value = value * 10 + c;
+ } while ( 1 );
+ }
+
+ // check for decimal point
+ if ( c == '.' ) {
+ double fraction;
+
+ fraction = 0.1;
+ do {
+ c = *string++;
+ if ( c < '0' || c > '9' ) {
+ break;
+ }
+ c -= '0';
+ value += c * fraction;
+ fraction *= 0.1;
+ } while ( 1 );
+
+ }
+
+ // not handling 10e10 notation...
+ *stringPtr = string;
+
+ return value * sign;
+}
+
+
+// bk001120 - presumably needed for Mac
+//#if !defined ( _MSC_VER ) && ! defined ( __linux__ )
+
+// bk001127 - undid undo
+#if defined ( Q3_VM )
+int atoi( const char *string ) {
+ int sign;
+ int value;
+ int c;
+
+
+ // skip whitespace
+ while ( *string <= ' ' ) {
+ if ( !*string ) {
+ return 0;
+ }
+ string++;
+ }
+
+ // check sign
+ switch ( *string ) {
+ case '+':
+ string++;
+ sign = 1;
+ break;
+ case '-':
+ string++;
+ sign = -1;
+ break;
+ default:
+ sign = 1;
+ break;
+ }
+
+ // read digits
+ value = 0;
+ do {
+ c = *string++;
+ if ( c < '0' || c > '9' ) {
+ break;
+ }
+ c -= '0';
+ value = value * 10 + c;
+ } while ( 1 );
+
+ // not handling 10e10 notation...
+
+ return value * sign;
+}
+
+
+int _atoi( const char **stringPtr ) {
+ int sign;
+ int value;
+ int c;
+ const char *string;
+
+ string = *stringPtr;
+
+ // skip whitespace
+ while ( *string <= ' ' ) {
+ if ( !*string ) {
+ return 0;
+ }
+ string++;
+ }
+
+ // check sign
+ switch ( *string ) {
+ case '+':
+ string++;
+ sign = 1;
+ break;
+ case '-':
+ string++;
+ sign = -1;
+ break;
+ default:
+ sign = 1;
+ break;
+ }
+
+ // read digits
+ value = 0;
+ do {
+ c = *string++;
+ if ( c < '0' || c > '9' ) {
+ break;
+ }
+ c -= '0';
+ value = value * 10 + c;
+ } while ( 1 );
+
+ // not handling 10e10 notation...
+
+ *stringPtr = string;
+
+ return value * sign;
+}
+
+int abs( int n ) {
+ return n < 0 ? -n : n;
+}
+
+double fabs( double x ) {
+ return x < 0 ? -x : x;
+}
+
+
+
+//=========================================================
+
+
+#define ALT 0x00000001 /* alternate form */
+#define HEXPREFIX 0x00000002 /* add 0x or 0X prefix */
+#define LADJUST 0x00000004 /* left adjustment */
+#define LONGDBL 0x00000008 /* long double */
+#define LONGINT 0x00000010 /* long integer */
+#define QUADINT 0x00000020 /* quad integer */
+#define SHORTINT 0x00000040 /* short integer */
+#define ZEROPAD 0x00000080 /* zero (as opposed to blank) pad */
+#define FPT 0x00000100 /* floating point number */
+
+#define to_digit(c) ((c) - '0')
+#define is_digit(c) ((unsigned)to_digit(c) <= 9)
+#define to_char(n) ((n) + '0')
+
+void AddInt( char **buf_p, int val, int width, int flags ) {
+ char text[32];
+ int digits;
+ int signedVal;
+ char *buf;
+
+ digits = 0;
+ signedVal = val;
+ if ( val < 0 ) {
+ val = -val;
+ }
+ do {
+ text[digits++] = '0' + val % 10;
+ val /= 10;
+ } while ( val );
+
+ if ( signedVal < 0 ) {
+ text[digits++] = '-';
+ }
+
+ buf = *buf_p;
+
+ if( !( flags & LADJUST ) ) {
+ while ( digits < width ) {
+ *buf++ = ( flags & ZEROPAD ) ? '0' : ' ';
+ width--;
+ }
+ }
+
+ while ( digits-- ) {
+ *buf++ = text[digits];
+ width--;
+ }
+
+ if( flags & LADJUST ) {
+ while ( width-- ) {
+ *buf++ = ( flags & ZEROPAD ) ? '0' : ' ';
+ }
+ }
+
+ *buf_p = buf;
+}
+
+void AddFloat( char **buf_p, float fval, int width, int prec ) {
+ char text[32];
+ int digits;
+ float signedVal;
+ char *buf;
+ int val;
+
+ // get the sign
+ signedVal = fval;
+ if ( fval < 0 ) {
+ fval = -fval;
+ }
+
+ // write the float number
+ digits = 0;
+ val = (int)fval;
+ do {
+ text[digits++] = '0' + val % 10;
+ val /= 10;
+ } while ( val );
+
+ if ( signedVal < 0 ) {
+ text[digits++] = '-';
+ }
+
+ buf = *buf_p;
+
+ while ( digits < width ) {
+ *buf++ = ' ';
+ width--;
+ }
+
+ while ( digits-- ) {
+ *buf++ = text[digits];
+ }
+
+ *buf_p = buf;
+
+ if (prec < 0)
+ prec = 6;
+ // write the fraction
+ digits = 0;
+ while (digits < prec) {
+ fval -= (int) fval;
+ fval *= 10.0;
+ val = (int) fval;
+ text[digits++] = '0' + val % 10;
+ }
+
+ if (digits > 0) {
+ buf = *buf_p;
+ *buf++ = '.';
+ for (prec = 0; prec < digits; prec++) {
+ *buf++ = text[prec];
+ }
+ *buf_p = buf;
+ }
+}
+
+
+void AddString( char **buf_p, char *string, int width, int prec ) {
+ int size;
+ char *buf;
+
+ buf = *buf_p;
+
+ if ( string == NULL ) {
+ string = "(null)";
+ prec = -1;
+ }
+
+ if ( prec >= 0 ) {
+ for( size = 0; size < prec; size++ ) {
+ if( string[size] == '\0' ) {
+ break;
+ }
+ }
+ }
+ else {
+ size = strlen( string );
+ }
+
+ width -= size;
+
+ while( size-- ) {
+ *buf++ = *string++;
+ }
+
+ while( width-- > 0 ) {
+ *buf++ = ' ';
+ }
+
+ *buf_p = buf;
+}
+
+/*
+vsprintf
+
+I'm not going to support a bunch of the more arcane stuff in here
+just to keep it simpler. For example, the '*' and '$' are not
+currently supported. I've tried to make it so that it will just
+parse and ignore formats we don't support.
+*/
+int vsprintf( char *buffer, const char *fmt, va_list argptr ) {
+ int *arg;
+ char *buf_p;
+ char ch;
+ int flags;
+ int width;
+ int prec;
+ int n;
+ char sign;
+
+ buf_p = buffer;
+ arg = (int *)argptr;
+
+ while( qtrue ) {
+ // run through the format string until we hit a '%' or '\0'
+ for ( ch = *fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++ ) {
+ *buf_p++ = ch;
+ }
+ if ( ch == '\0' ) {
+ goto done;
+ }
+
+ // skip over the '%'
+ fmt++;
+
+ // reset formatting state
+ flags = 0;
+ width = 0;
+ prec = -1;
+ sign = '\0';
+
+rflag:
+ ch = *fmt++;
+reswitch:
+ switch( ch ) {
+ case '-':
+ flags |= LADJUST;
+ goto rflag;
+ case '.':
+ n = 0;
+ while( is_digit( ( ch = *fmt++ ) ) ) {
+ n = 10 * n + ( ch - '0' );
+ }
+ prec = n < 0 ? -1 : n;
+ goto reswitch;
+ case '0':
+ flags |= ZEROPAD;
+ goto rflag;
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ n = 0;
+ do {
+ n = 10 * n + ( ch - '0' );
+ ch = *fmt++;
+ } while( is_digit( ch ) );
+ width = n;
+ goto reswitch;
+ case 'c':
+ *buf_p++ = (char)*arg;
+ arg++;
+ break;
+ case 'd':
+ case 'i':
+ AddInt( &buf_p, *arg, width, flags );
+ arg++;
+ break;
+ case 'f':
+ AddFloat( &buf_p, *(double *)arg, width, prec );
+#ifdef __LCC__
+ arg += 1; // everything is 32 bit in my compiler
+#else
+ arg += 2;
+#endif
+ break;
+ case 's':
+ AddString( &buf_p, (char *)*arg, width, prec );
+ arg++;
+ break;
+ case '%':
+ *buf_p++ = ch;
+ break;
+ default:
+ *buf_p++ = (char)*arg;
+ arg++;
+ break;
+ }
+ }
+
+done:
+ *buf_p = 0;
+ return buf_p - buffer;
+}
+
+/* this is really crappy */
+int sscanf( const char *buffer, const char *fmt, ... ) {
+ int cmd;
+ int **arg;
+ int count;
+
+ arg = (int **)&fmt + 1;
+ count = 0;
+
+ while ( *fmt ) {
+ if ( fmt[0] != '%' ) {
+ fmt++;
+ continue;
+ }
+
+ cmd = fmt[1];
+ fmt += 2;
+
+ switch ( cmd ) {
+ case 'i':
+ case 'd':
+ case 'u':
+ **arg = _atoi( &buffer );
+ break;
+ case 'f':
+ *(float *)*arg = _atof( &buffer );
+ break;
+ }
+ arg++;
+ }
+
+ return count;
+}
+
+#endif
diff --git a/code/game/bg_lib.h b/code/game/bg_lib.h
new file mode 100755
index 0000000..57333c0
--- /dev/null
+++ b/code/game/bg_lib.h
@@ -0,0 +1,91 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// bg_lib.h -- standard C library replacement routines used by code
+// compiled for the virtual machine
+
+// This file is NOT included on native builds
+
+typedef int size_t;
+
+typedef char * va_list;
+#define _INTSIZEOF(n) ( (sizeof(n) + sizeof(int) - 1) & ~(sizeof(int) - 1) )
+#define va_start(ap,v) ( ap = (va_list)&v + _INTSIZEOF(v) )
+#define va_arg(ap,t) ( *(t *)((ap += _INTSIZEOF(t)) - _INTSIZEOF(t)) )
+#define va_end(ap) ( ap = (va_list)0 )
+
+#define CHAR_BIT 8 /* number of bits in a char */
+#define SCHAR_MIN (-128) /* minimum signed char value */
+#define SCHAR_MAX 127 /* maximum signed char value */
+#define UCHAR_MAX 0xff /* maximum unsigned char value */
+
+#define SHRT_MIN (-32768) /* minimum (signed) short value */
+#define SHRT_MAX 32767 /* maximum (signed) short value */
+#define USHRT_MAX 0xffff /* maximum unsigned short value */
+#define INT_MIN (-2147483647 - 1) /* minimum (signed) int value */
+#define INT_MAX 2147483647 /* maximum (signed) int value */
+#define UINT_MAX 0xffffffff /* maximum unsigned int value */
+#define LONG_MIN (-2147483647L - 1) /* minimum (signed) long value */
+#define LONG_MAX 2147483647L /* maximum (signed) long value */
+#define ULONG_MAX 0xffffffffUL /* maximum unsigned long value */
+
+// Misc functions
+typedef int cmp_t(const void *, const void *);
+void qsort(void *a, size_t n, size_t es, cmp_t *cmp);
+void srand( unsigned seed );
+int rand( void );
+
+// String functions
+size_t strlen( const char *string );
+char *strcat( char *strDestination, const char *strSource );
+char *strcpy( char *strDestination, const char *strSource );
+int strcmp( const char *string1, const char *string2 );
+char *strchr( const char *string, int c );
+char *strstr( const char *string, const char *strCharSet );
+char *strncpy( char *strDest, const char *strSource, size_t count );
+int tolower( int c );
+int toupper( int c );
+
+double atof( const char *string );
+double _atof( const char **stringPtr );
+int atoi( const char *string );
+int _atoi( const char **stringPtr );
+
+int vsprintf( char *buffer, const char *fmt, va_list argptr );
+int sscanf( const char *buffer, const char *fmt, ... );
+
+// Memory functions
+void *memmove( void *dest, const void *src, size_t count );
+void *memset( void *dest, int c, size_t count );
+void *memcpy( void *dest, const void *src, size_t count );
+
+// Math functions
+double ceil( double x );
+double floor( double x );
+double sqrt( double x );
+double sin( double x );
+double cos( double x );
+double atan2( double y, double x );
+double tan( double x );
+int abs( int n );
+double fabs( double x );
+double acos( double x );
+
diff --git a/code/game/bg_local.h b/code/game/bg_local.h
new file mode 100755
index 0000000..223c688
--- /dev/null
+++ b/code/game/bg_local.h
@@ -0,0 +1,83 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// bg_local.h -- local definitions for the bg (both games) files
+
+#define MIN_WALK_NORMAL 0.7f // can't walk on very steep slopes
+
+#define STEPSIZE 18
+
+#define JUMP_VELOCITY 270
+
+#define TIMER_LAND 130
+#define TIMER_GESTURE (34*66+50)
+
+#define OVERCLIP 1.001f
+
+// all of the locals will be zeroed before each
+// pmove, just to make damn sure we don't have
+// any differences when running on client or server
+typedef struct {
+ vec3_t forward, right, up;
+ float frametime;
+
+ int msec;
+
+ qboolean walking;
+ qboolean groundPlane;
+ trace_t groundTrace;
+
+ float impactSpeed;
+
+ vec3_t previous_origin;
+ vec3_t previous_velocity;
+ int previous_waterlevel;
+} pml_t;
+
+extern pmove_t *pm;
+extern pml_t pml;
+
+// movement parameters
+extern float pm_stopspeed;
+extern float pm_duckScale;
+extern float pm_swimScale;
+extern float pm_wadeScale;
+
+extern float pm_accelerate;
+extern float pm_airaccelerate;
+extern float pm_wateraccelerate;
+extern float pm_flyaccelerate;
+
+extern float pm_friction;
+extern float pm_waterfriction;
+extern float pm_flightfriction;
+
+extern int c_pmove;
+
+void PM_ClipVelocity( vec3_t in, vec3_t normal, vec3_t out, float overbounce );
+void PM_AddTouchEnt( int entityNum );
+void PM_AddEvent( int newEvent );
+
+qboolean PM_SlideMove( qboolean gravity );
+void PM_StepSlideMove( qboolean gravity );
+
+
diff --git a/code/game/bg_misc.c b/code/game/bg_misc.c
new file mode 100755
index 0000000..f729f06
--- /dev/null
+++ b/code/game/bg_misc.c
@@ -0,0 +1,1604 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// bg_misc.c -- both games misc functions, all completely stateless
+
+#include "q_shared.h"
+#include "bg_public.h"
+
+/*QUAKED item_***** ( 0 0 0 ) (-16 -16 -16) (16 16 16) suspended
+DO NOT USE THIS CLASS, IT JUST HOLDS GENERAL INFORMATION.
+The suspended flag will allow items to hang in the air, otherwise they are dropped to the next surface.
+
+If an item is the target of another entity, it will not spawn in until fired.
+
+An item fires all of its targets when it is picked up. If the toucher can't carry it, the targets won't be fired.
+
+"notfree" if set to 1, don't spawn in free for all games
+"notteam" if set to 1, don't spawn in team games
+"notsingle" if set to 1, don't spawn in single player games
+"wait" override the default wait before respawning. -1 = never respawn automatically, which can be used with targeted spawning.
+"random" random number of plus or minus seconds varied from the respawn time
+"count" override quantity or duration on most items.
+*/
+
+gitem_t bg_itemlist[] =
+{
+ {
+ NULL,
+ NULL,
+ { NULL,
+ NULL,
+ 0, 0} ,
+/* icon */ NULL,
+/* pickup */ NULL,
+ 0,
+ 0,
+ 0,
+/* precache */ "",
+/* sounds */ ""
+ }, // leave index 0 alone
+
+ //
+ // ARMOR
+ //
+
+/*QUAKED item_armor_shard (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "item_armor_shard",
+ "sound/misc/ar1_pkup.wav",
+ { "models/powerups/armor/shard.md3",
+ "models/powerups/armor/shard_sphere.md3",
+ 0, 0} ,
+/* icon */ "icons/iconr_shard",
+/* pickup */ "Armor Shard",
+ 5,
+ IT_ARMOR,
+ 0,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED item_armor_combat (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "item_armor_combat",
+ "sound/misc/ar2_pkup.wav",
+ { "models/powerups/armor/armor_yel.md3",
+ 0, 0, 0},
+/* icon */ "icons/iconr_yellow",
+/* pickup */ "Armor",
+ 50,
+ IT_ARMOR,
+ 0,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED item_armor_body (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "item_armor_body",
+ "sound/misc/ar2_pkup.wav",
+ { "models/powerups/armor/armor_red.md3",
+ 0, 0, 0},
+/* icon */ "icons/iconr_red",
+/* pickup */ "Heavy Armor",
+ 100,
+ IT_ARMOR,
+ 0,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+ //
+ // health
+ //
+/*QUAKED item_health_small (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "item_health_small",
+ "sound/items/s_health.wav",
+ { "models/powerups/health/small_cross.md3",
+ "models/powerups/health/small_sphere.md3",
+ 0, 0 },
+/* icon */ "icons/iconh_green",
+/* pickup */ "5 Health",
+ 5,
+ IT_HEALTH,
+ 0,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED item_health (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "item_health",
+ "sound/items/n_health.wav",
+ { "models/powerups/health/medium_cross.md3",
+ "models/powerups/health/medium_sphere.md3",
+ 0, 0 },
+/* icon */ "icons/iconh_yellow",
+/* pickup */ "25 Health",
+ 25,
+ IT_HEALTH,
+ 0,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED item_health_large (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "item_health_large",
+ "sound/items/l_health.wav",
+ { "models/powerups/health/large_cross.md3",
+ "models/powerups/health/large_sphere.md3",
+ 0, 0 },
+/* icon */ "icons/iconh_red",
+/* pickup */ "50 Health",
+ 50,
+ IT_HEALTH,
+ 0,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED item_health_mega (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "item_health_mega",
+ "sound/items/m_health.wav",
+ { "models/powerups/health/mega_cross.md3",
+ "models/powerups/health/mega_sphere.md3",
+ 0, 0 },
+/* icon */ "icons/iconh_mega",
+/* pickup */ "Mega Health",
+ 100,
+ IT_HEALTH,
+ 0,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+
+ //
+ // WEAPONS
+ //
+
+/*QUAKED weapon_gauntlet (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "weapon_gauntlet",
+ "sound/misc/w_pkup.wav",
+ { "models/weapons2/gauntlet/gauntlet.md3",
+ 0, 0, 0},
+/* icon */ "icons/iconw_gauntlet",
+/* pickup */ "Gauntlet",
+ 0,
+ IT_WEAPON,
+ WP_GAUNTLET,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED weapon_shotgun (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "weapon_shotgun",
+ "sound/misc/w_pkup.wav",
+ { "models/weapons2/shotgun/shotgun.md3",
+ 0, 0, 0},
+/* icon */ "icons/iconw_shotgun",
+/* pickup */ "Shotgun",
+ 10,
+ IT_WEAPON,
+ WP_SHOTGUN,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED weapon_machinegun (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "weapon_machinegun",
+ "sound/misc/w_pkup.wav",
+ { "models/weapons2/machinegun/machinegun.md3",
+ 0, 0, 0},
+/* icon */ "icons/iconw_machinegun",
+/* pickup */ "Machinegun",
+ 40,
+ IT_WEAPON,
+ WP_MACHINEGUN,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED weapon_grenadelauncher (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "weapon_grenadelauncher",
+ "sound/misc/w_pkup.wav",
+ { "models/weapons2/grenadel/grenadel.md3",
+ 0, 0, 0},
+/* icon */ "icons/iconw_grenade",
+/* pickup */ "Grenade Launcher",
+ 10,
+ IT_WEAPON,
+ WP_GRENADE_LAUNCHER,
+/* precache */ "",
+/* sounds */ "sound/weapons/grenade/hgrenb1a.wav sound/weapons/grenade/hgrenb2a.wav"
+ },
+
+/*QUAKED weapon_rocketlauncher (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "weapon_rocketlauncher",
+ "sound/misc/w_pkup.wav",
+ { "models/weapons2/rocketl/rocketl.md3",
+ 0, 0, 0},
+/* icon */ "icons/iconw_rocket",
+/* pickup */ "Rocket Launcher",
+ 10,
+ IT_WEAPON,
+ WP_ROCKET_LAUNCHER,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED weapon_lightning (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "weapon_lightning",
+ "sound/misc/w_pkup.wav",
+ { "models/weapons2/lightning/lightning.md3",
+ 0, 0, 0},
+/* icon */ "icons/iconw_lightning",
+/* pickup */ "Lightning Gun",
+ 100,
+ IT_WEAPON,
+ WP_LIGHTNING,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED weapon_railgun (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "weapon_railgun",
+ "sound/misc/w_pkup.wav",
+ { "models/weapons2/railgun/railgun.md3",
+ 0, 0, 0},
+/* icon */ "icons/iconw_railgun",
+/* pickup */ "Railgun",
+ 10,
+ IT_WEAPON,
+ WP_RAILGUN,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED weapon_plasmagun (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "weapon_plasmagun",
+ "sound/misc/w_pkup.wav",
+ { "models/weapons2/plasma/plasma.md3",
+ 0, 0, 0},
+/* icon */ "icons/iconw_plasma",
+/* pickup */ "Plasma Gun",
+ 50,
+ IT_WEAPON,
+ WP_PLASMAGUN,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED weapon_bfg (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "weapon_bfg",
+ "sound/misc/w_pkup.wav",
+ { "models/weapons2/bfg/bfg.md3",
+ 0, 0, 0},
+/* icon */ "icons/iconw_bfg",
+/* pickup */ "BFG10K",
+ 20,
+ IT_WEAPON,
+ WP_BFG,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED weapon_grapplinghook (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "weapon_grapplinghook",
+ "sound/misc/w_pkup.wav",
+ { "models/weapons2/grapple/grapple.md3",
+ 0, 0, 0},
+/* icon */ "icons/iconw_grapple",
+/* pickup */ "Grappling Hook",
+ 0,
+ IT_WEAPON,
+ WP_GRAPPLING_HOOK,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+ //
+ // AMMO ITEMS
+ //
+
+/*QUAKED ammo_shells (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "ammo_shells",
+ "sound/misc/am_pkup.wav",
+ { "models/powerups/ammo/shotgunam.md3",
+ 0, 0, 0},
+/* icon */ "icons/icona_shotgun",
+/* pickup */ "Shells",
+ 10,
+ IT_AMMO,
+ WP_SHOTGUN,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED ammo_bullets (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "ammo_bullets",
+ "sound/misc/am_pkup.wav",
+ { "models/powerups/ammo/machinegunam.md3",
+ 0, 0, 0},
+/* icon */ "icons/icona_machinegun",
+/* pickup */ "Bullets",
+ 50,
+ IT_AMMO,
+ WP_MACHINEGUN,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED ammo_grenades (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "ammo_grenades",
+ "sound/misc/am_pkup.wav",
+ { "models/powerups/ammo/grenadeam.md3",
+ 0, 0, 0},
+/* icon */ "icons/icona_grenade",
+/* pickup */ "Grenades",
+ 5,
+ IT_AMMO,
+ WP_GRENADE_LAUNCHER,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED ammo_cells (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "ammo_cells",
+ "sound/misc/am_pkup.wav",
+ { "models/powerups/ammo/plasmaam.md3",
+ 0, 0, 0},
+/* icon */ "icons/icona_plasma",
+/* pickup */ "Cells",
+ 30,
+ IT_AMMO,
+ WP_PLASMAGUN,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED ammo_lightning (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "ammo_lightning",
+ "sound/misc/am_pkup.wav",
+ { "models/powerups/ammo/lightningam.md3",
+ 0, 0, 0},
+/* icon */ "icons/icona_lightning",
+/* pickup */ "Lightning",
+ 60,
+ IT_AMMO,
+ WP_LIGHTNING,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED ammo_rockets (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "ammo_rockets",
+ "sound/misc/am_pkup.wav",
+ { "models/powerups/ammo/rocketam.md3",
+ 0, 0, 0},
+/* icon */ "icons/icona_rocket",
+/* pickup */ "Rockets",
+ 5,
+ IT_AMMO,
+ WP_ROCKET_LAUNCHER,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED ammo_slugs (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "ammo_slugs",
+ "sound/misc/am_pkup.wav",
+ { "models/powerups/ammo/railgunam.md3",
+ 0, 0, 0},
+/* icon */ "icons/icona_railgun",
+/* pickup */ "Slugs",
+ 10,
+ IT_AMMO,
+ WP_RAILGUN,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED ammo_bfg (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "ammo_bfg",
+ "sound/misc/am_pkup.wav",
+ { "models/powerups/ammo/bfgam.md3",
+ 0, 0, 0},
+/* icon */ "icons/icona_bfg",
+/* pickup */ "Bfg Ammo",
+ 15,
+ IT_AMMO,
+ WP_BFG,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+ //
+ // HOLDABLE ITEMS
+ //
+/*QUAKED holdable_teleporter (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "holdable_teleporter",
+ "sound/items/holdable.wav",
+ { "models/powerups/holdable/teleporter.md3",
+ 0, 0, 0},
+/* icon */ "icons/teleporter",
+/* pickup */ "Personal Teleporter",
+ 60,
+ IT_HOLDABLE,
+ HI_TELEPORTER,
+/* precache */ "",
+/* sounds */ ""
+ },
+/*QUAKED holdable_medkit (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "holdable_medkit",
+ "sound/items/holdable.wav",
+ {
+ "models/powerups/holdable/medkit.md3",
+ "models/powerups/holdable/medkit_sphere.md3",
+ 0, 0},
+/* icon */ "icons/medkit",
+/* pickup */ "Medkit",
+ 60,
+ IT_HOLDABLE,
+ HI_MEDKIT,
+/* precache */ "",
+/* sounds */ "sound/items/use_medkit.wav"
+ },
+
+ //
+ // POWERUP ITEMS
+ //
+/*QUAKED item_quad (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "item_quad",
+ "sound/items/quaddamage.wav",
+ { "models/powerups/instant/quad.md3",
+ "models/powerups/instant/quad_ring.md3",
+ 0, 0 },
+/* icon */ "icons/quad",
+/* pickup */ "Quad Damage",
+ 30,
+ IT_POWERUP,
+ PW_QUAD,
+/* precache */ "",
+/* sounds */ "sound/items/damage2.wav sound/items/damage3.wav"
+ },
+
+/*QUAKED item_enviro (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "item_enviro",
+ "sound/items/protect.wav",
+ { "models/powerups/instant/enviro.md3",
+ "models/powerups/instant/enviro_ring.md3",
+ 0, 0 },
+/* icon */ "icons/envirosuit",
+/* pickup */ "Battle Suit",
+ 30,
+ IT_POWERUP,
+ PW_BATTLESUIT,
+/* precache */ "",
+/* sounds */ "sound/items/airout.wav sound/items/protect3.wav"
+ },
+
+/*QUAKED item_haste (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "item_haste",
+ "sound/items/haste.wav",
+ { "models/powerups/instant/haste.md3",
+ "models/powerups/instant/haste_ring.md3",
+ 0, 0 },
+/* icon */ "icons/haste",
+/* pickup */ "Speed",
+ 30,
+ IT_POWERUP,
+ PW_HASTE,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED item_invis (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "item_invis",
+ "sound/items/invisibility.wav",
+ { "models/powerups/instant/invis.md3",
+ "models/powerups/instant/invis_ring.md3",
+ 0, 0 },
+/* icon */ "icons/invis",
+/* pickup */ "Invisibility",
+ 30,
+ IT_POWERUP,
+ PW_INVIS,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED item_regen (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "item_regen",
+ "sound/items/regeneration.wav",
+ { "models/powerups/instant/regen.md3",
+ "models/powerups/instant/regen_ring.md3",
+ 0, 0 },
+/* icon */ "icons/regen",
+/* pickup */ "Regeneration",
+ 30,
+ IT_POWERUP,
+ PW_REGEN,
+/* precache */ "",
+/* sounds */ "sound/items/regen.wav"
+ },
+
+/*QUAKED item_flight (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "item_flight",
+ "sound/items/flight.wav",
+ { "models/powerups/instant/flight.md3",
+ "models/powerups/instant/flight_ring.md3",
+ 0, 0 },
+/* icon */ "icons/flight",
+/* pickup */ "Flight",
+ 60,
+ IT_POWERUP,
+ PW_FLIGHT,
+/* precache */ "",
+/* sounds */ "sound/items/flight.wav"
+ },
+
+/*QUAKED team_CTF_redflag (1 0 0) (-16 -16 -16) (16 16 16)
+Only in CTF games
+*/
+ {
+ "team_CTF_redflag",
+ NULL,
+ { "models/flags/r_flag.md3",
+ 0, 0, 0 },
+/* icon */ "icons/iconf_red1",
+/* pickup */ "Red Flag",
+ 0,
+ IT_TEAM,
+ PW_REDFLAG,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED team_CTF_blueflag (0 0 1) (-16 -16 -16) (16 16 16)
+Only in CTF games
+*/
+ {
+ "team_CTF_blueflag",
+ NULL,
+ { "models/flags/b_flag.md3",
+ 0, 0, 0 },
+/* icon */ "icons/iconf_blu1",
+/* pickup */ "Blue Flag",
+ 0,
+ IT_TEAM,
+ PW_BLUEFLAG,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+#ifdef MISSIONPACK
+/*QUAKED holdable_kamikaze (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "holdable_kamikaze",
+ "sound/items/holdable.wav",
+ { "models/powerups/kamikazi.md3",
+ 0, 0, 0},
+/* icon */ "icons/kamikaze",
+/* pickup */ "Kamikaze",
+ 60,
+ IT_HOLDABLE,
+ HI_KAMIKAZE,
+/* precache */ "",
+/* sounds */ "sound/items/kamikazerespawn.wav"
+ },
+
+/*QUAKED holdable_portal (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "holdable_portal",
+ "sound/items/holdable.wav",
+ { "models/powerups/holdable/porter.md3",
+ 0, 0, 0},
+/* icon */ "icons/portal",
+/* pickup */ "Portal",
+ 60,
+ IT_HOLDABLE,
+ HI_PORTAL,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED holdable_invulnerability (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "holdable_invulnerability",
+ "sound/items/holdable.wav",
+ { "models/powerups/holdable/invulnerability.md3",
+ 0, 0, 0},
+/* icon */ "icons/invulnerability",
+/* pickup */ "Invulnerability",
+ 60,
+ IT_HOLDABLE,
+ HI_INVULNERABILITY,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED ammo_nails (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "ammo_nails",
+ "sound/misc/am_pkup.wav",
+ { "models/powerups/ammo/nailgunam.md3",
+ 0, 0, 0},
+/* icon */ "icons/icona_nailgun",
+/* pickup */ "Nails",
+ 20,
+ IT_AMMO,
+ WP_NAILGUN,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED ammo_mines (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "ammo_mines",
+ "sound/misc/am_pkup.wav",
+ { "models/powerups/ammo/proxmineam.md3",
+ 0, 0, 0},
+/* icon */ "icons/icona_proxlauncher",
+/* pickup */ "Proximity Mines",
+ 10,
+ IT_AMMO,
+ WP_PROX_LAUNCHER,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED ammo_belt (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "ammo_belt",
+ "sound/misc/am_pkup.wav",
+ { "models/powerups/ammo/chaingunam.md3",
+ 0, 0, 0},
+/* icon */ "icons/icona_chaingun",
+/* pickup */ "Chaingun Belt",
+ 100,
+ IT_AMMO,
+ WP_CHAINGUN,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+ //
+ // PERSISTANT POWERUP ITEMS
+ //
+/*QUAKED item_scout (.3 .3 1) (-16 -16 -16) (16 16 16) suspended redTeam blueTeam
+*/
+ {
+ "item_scout",
+ "sound/items/scout.wav",
+ { "models/powerups/scout.md3",
+ 0, 0, 0 },
+/* icon */ "icons/scout",
+/* pickup */ "Scout",
+ 30,
+ IT_PERSISTANT_POWERUP,
+ PW_SCOUT,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED item_guard (.3 .3 1) (-16 -16 -16) (16 16 16) suspended redTeam blueTeam
+*/
+ {
+ "item_guard",
+ "sound/items/guard.wav",
+ { "models/powerups/guard.md3",
+ 0, 0, 0 },
+/* icon */ "icons/guard",
+/* pickup */ "Guard",
+ 30,
+ IT_PERSISTANT_POWERUP,
+ PW_GUARD,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED item_doubler (.3 .3 1) (-16 -16 -16) (16 16 16) suspended redTeam blueTeam
+*/
+ {
+ "item_doubler",
+ "sound/items/doubler.wav",
+ { "models/powerups/doubler.md3",
+ 0, 0, 0 },
+/* icon */ "icons/doubler",
+/* pickup */ "Doubler",
+ 30,
+ IT_PERSISTANT_POWERUP,
+ PW_DOUBLER,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED item_doubler (.3 .3 1) (-16 -16 -16) (16 16 16) suspended redTeam blueTeam
+*/
+ {
+ "item_ammoregen",
+ "sound/items/ammoregen.wav",
+ { "models/powerups/ammo.md3",
+ 0, 0, 0 },
+/* icon */ "icons/ammo_regen",
+/* pickup */ "Ammo Regen",
+ 30,
+ IT_PERSISTANT_POWERUP,
+ PW_AMMOREGEN,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+ /*QUAKED team_CTF_neutralflag (0 0 1) (-16 -16 -16) (16 16 16)
+Only in One Flag CTF games
+*/
+ {
+ "team_CTF_neutralflag",
+ NULL,
+ { "models/flags/n_flag.md3",
+ 0, 0, 0 },
+/* icon */ "icons/iconf_neutral1",
+/* pickup */ "Neutral Flag",
+ 0,
+ IT_TEAM,
+ PW_NEUTRALFLAG,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+ {
+ "item_redcube",
+ "sound/misc/am_pkup.wav",
+ { "models/powerups/orb/r_orb.md3",
+ 0, 0, 0 },
+/* icon */ "icons/iconh_rorb",
+/* pickup */ "Red Cube",
+ 0,
+ IT_TEAM,
+ 0,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+ {
+ "item_bluecube",
+ "sound/misc/am_pkup.wav",
+ { "models/powerups/orb/b_orb.md3",
+ 0, 0, 0 },
+/* icon */ "icons/iconh_borb",
+/* pickup */ "Blue Cube",
+ 0,
+ IT_TEAM,
+ 0,
+/* precache */ "",
+/* sounds */ ""
+ },
+/*QUAKED weapon_nailgun (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "weapon_nailgun",
+ "sound/misc/w_pkup.wav",
+ { "models/weapons/nailgun/nailgun.md3",
+ 0, 0, 0},
+/* icon */ "icons/iconw_nailgun",
+/* pickup */ "Nailgun",
+ 10,
+ IT_WEAPON,
+ WP_NAILGUN,
+/* precache */ "",
+/* sounds */ ""
+ },
+
+/*QUAKED weapon_prox_launcher (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "weapon_prox_launcher",
+ "sound/misc/w_pkup.wav",
+ { "models/weapons/proxmine/proxmine.md3",
+ 0, 0, 0},
+/* icon */ "icons/iconw_proxlauncher",
+/* pickup */ "Prox Launcher",
+ 5,
+ IT_WEAPON,
+ WP_PROX_LAUNCHER,
+/* precache */ "",
+/* sounds */ "sound/weapons/proxmine/wstbtick.wav "
+ "sound/weapons/proxmine/wstbactv.wav "
+ "sound/weapons/proxmine/wstbimpl.wav "
+ "sound/weapons/proxmine/wstbimpm.wav "
+ "sound/weapons/proxmine/wstbimpd.wav "
+ "sound/weapons/proxmine/wstbactv.wav"
+ },
+
+/*QUAKED weapon_chaingun (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
+*/
+ {
+ "weapon_chaingun",
+ "sound/misc/w_pkup.wav",
+ { "models/weapons/vulcan/vulcan.md3",
+ 0, 0, 0},
+/* icon */ "icons/iconw_chaingun",
+/* pickup */ "Chaingun",
+ 80,
+ IT_WEAPON,
+ WP_CHAINGUN,
+/* precache */ "",
+/* sounds */ "sound/weapons/vulcan/wvulwind.wav"
+ },
+#endif
+
+ // end of list marker
+ {NULL}
+};
+
+int bg_numItems = sizeof(bg_itemlist) / sizeof(bg_itemlist[0]) - 1;
+
+
+/*
+==============
+BG_FindItemForPowerup
+==============
+*/
+gitem_t *BG_FindItemForPowerup( powerup_t pw ) {
+ int i;
+
+ for ( i = 0 ; i < bg_numItems ; i++ ) {
+ if ( (bg_itemlist[i].giType == IT_POWERUP ||
+ bg_itemlist[i].giType == IT_TEAM ||
+ bg_itemlist[i].giType == IT_PERSISTANT_POWERUP) &&
+ bg_itemlist[i].giTag == pw ) {
+ return &bg_itemlist[i];
+ }
+ }
+
+ return NULL;
+}
+
+
+/*
+==============
+BG_FindItemForHoldable
+==============
+*/
+gitem_t *BG_FindItemForHoldable( holdable_t pw ) {
+ int i;
+
+ for ( i = 0 ; i < bg_numItems ; i++ ) {
+ if ( bg_itemlist[i].giType == IT_HOLDABLE && bg_itemlist[i].giTag == pw ) {
+ return &bg_itemlist[i];
+ }
+ }
+
+ Com_Error( ERR_DROP, "HoldableItem not found" );
+
+ return NULL;
+}
+
+
+/*
+===============
+BG_FindItemForWeapon
+
+===============
+*/
+gitem_t *BG_FindItemForWeapon( weapon_t weapon ) {
+ gitem_t *it;
+
+ for ( it = bg_itemlist + 1 ; it->classname ; it++) {
+ if ( it->giType == IT_WEAPON && it->giTag == weapon ) {
+ return it;
+ }
+ }
+
+ Com_Error( ERR_DROP, "Couldn't find item for weapon %i", weapon);
+ return NULL;
+}
+
+/*
+===============
+BG_FindItem
+
+===============
+*/
+gitem_t *BG_FindItem( const char *pickupName ) {
+ gitem_t *it;
+
+ for ( it = bg_itemlist + 1 ; it->classname ; it++ ) {
+ if ( !Q_stricmp( it->pickup_name, pickupName ) )
+ return it;
+ }
+
+ return NULL;
+}
+
+/*
+============
+BG_PlayerTouchesItem
+
+Items can be picked up without actually touching their physical bounds to make
+grabbing them easier
+============
+*/
+qboolean BG_PlayerTouchesItem( playerState_t *ps, entityState_t *item, int atTime ) {
+ vec3_t origin;
+
+ BG_EvaluateTrajectory( &item->pos, atTime, origin );
+
+ // we are ignoring ducked differences here
+ if ( ps->origin[0] - origin[0] > 44
+ || ps->origin[0] - origin[0] < -50
+ || ps->origin[1] - origin[1] > 36
+ || ps->origin[1] - origin[1] < -36
+ || ps->origin[2] - origin[2] > 36
+ || ps->origin[2] - origin[2] < -36 ) {
+ return qfalse;
+ }
+
+ return qtrue;
+}
+
+
+
+/*
+================
+BG_CanItemBeGrabbed
+
+Returns false if the item should not be picked up.
+This needs to be the same for client side prediction and server use.
+================
+*/
+qboolean BG_CanItemBeGrabbed( int gametype, const entityState_t *ent, const playerState_t *ps ) {
+ gitem_t *item;
+#ifdef MISSIONPACK
+ int upperBound;
+#endif
+
+ if ( ent->modelindex < 1 || ent->modelindex >= bg_numItems ) {
+ Com_Error( ERR_DROP, "BG_CanItemBeGrabbed: index out of range" );
+ }
+
+ item = &bg_itemlist[ent->modelindex];
+
+ switch( item->giType ) {
+ case IT_WEAPON:
+ return qtrue; // weapons are always picked up
+
+ case IT_AMMO:
+ if ( ps->ammo[ item->giTag ] >= 200 ) {
+ return qfalse; // can't hold any more
+ }
+ return qtrue;
+
+ case IT_ARMOR:
+#ifdef MISSIONPACK
+ if( bg_itemlist[ps->stats[STAT_PERSISTANT_POWERUP]].giTag == PW_SCOUT ) {
+ return qfalse;
+ }
+
+ // we also clamp armor to the maxhealth for handicapping
+ if( bg_itemlist[ps->stats[STAT_PERSISTANT_POWERUP]].giTag == PW_GUARD ) {
+ upperBound = ps->stats[STAT_MAX_HEALTH];
+ }
+ else {
+ upperBound = ps->stats[STAT_MAX_HEALTH] * 2;
+ }
+
+ if ( ps->stats[STAT_ARMOR] >= upperBound ) {
+ return qfalse;
+ }
+#else
+ if ( ps->stats[STAT_ARMOR] >= ps->stats[STAT_MAX_HEALTH] * 2 ) {
+ return qfalse;
+ }
+#endif
+ return qtrue;
+
+ case IT_HEALTH:
+ // small and mega healths will go over the max, otherwise
+ // don't pick up if already at max
+#ifdef MISSIONPACK
+ if( bg_itemlist[ps->stats[STAT_PERSISTANT_POWERUP]].giTag == PW_GUARD ) {
+ upperBound = ps->stats[STAT_MAX_HEALTH];
+ }
+ else
+#endif
+ if ( item->quantity == 5 || item->quantity == 100 ) {
+ if ( ps->stats[STAT_HEALTH] >= ps->stats[STAT_MAX_HEALTH] * 2 ) {
+ return qfalse;
+ }
+ return qtrue;
+ }
+
+ if ( ps->stats[STAT_HEALTH] >= ps->stats[STAT_MAX_HEALTH] ) {
+ return qfalse;
+ }
+ return qtrue;
+
+ case IT_POWERUP:
+ return qtrue; // powerups are always picked up
+
+#ifdef MISSIONPACK
+ case IT_PERSISTANT_POWERUP:
+ // can only hold one item at a time
+ if ( ps->stats[STAT_PERSISTANT_POWERUP] ) {
+ return qfalse;
+ }
+
+ // check team only
+ if( ( ent->generic1 & 2 ) && ( ps->persistant[PERS_TEAM] != TEAM_RED ) ) {
+ return qfalse;
+ }
+ if( ( ent->generic1 & 4 ) && ( ps->persistant[PERS_TEAM] != TEAM_BLUE ) ) {
+ return qfalse;
+ }
+
+ return qtrue;
+#endif
+
+ case IT_TEAM: // team items, such as flags
+#ifdef MISSIONPACK
+ if( gametype == GT_1FCTF ) {
+ // neutral flag can always be picked up
+ if( item->giTag == PW_NEUTRALFLAG ) {
+ return qtrue;
+ }
+ if (ps->persistant[PERS_TEAM] == TEAM_RED) {
+ if (item->giTag == PW_BLUEFLAG && ps->powerups[PW_NEUTRALFLAG] ) {
+ return qtrue;
+ }
+ } else if (ps->persistant[PERS_TEAM] == TEAM_BLUE) {
+ if (item->giTag == PW_REDFLAG && ps->powerups[PW_NEUTRALFLAG] ) {
+ return qtrue;
+ }
+ }
+ }
+#endif
+ if( gametype == GT_CTF ) {
+ // ent->modelindex2 is non-zero on items if they are dropped
+ // we need to know this because we can pick up our dropped flag (and return it)
+ // but we can't pick up our flag at base
+ if (ps->persistant[PERS_TEAM] == TEAM_RED) {
+ if (item->giTag == PW_BLUEFLAG ||
+ (item->giTag == PW_REDFLAG && ent->modelindex2) ||
+ (item->giTag == PW_REDFLAG && ps->powerups[PW_BLUEFLAG]) )
+ return qtrue;
+ } else if (ps->persistant[PERS_TEAM] == TEAM_BLUE) {
+ if (item->giTag == PW_REDFLAG ||
+ (item->giTag == PW_BLUEFLAG && ent->modelindex2) ||
+ (item->giTag == PW_BLUEFLAG && ps->powerups[PW_REDFLAG]) )
+ return qtrue;
+ }
+ }
+
+#ifdef MISSIONPACK
+ if( gametype == GT_HARVESTER ) {
+ return qtrue;
+ }
+#endif
+ return qfalse;
+
+ case IT_HOLDABLE:
+ // can only hold one item at a time
+ if ( ps->stats[STAT_HOLDABLE_ITEM] ) {
+ return qfalse;
+ }
+ return qtrue;
+
+ case IT_BAD:
+ Com_Error( ERR_DROP, "BG_CanItemBeGrabbed: IT_BAD" );
+ default:
+#ifndef Q3_VM
+#ifndef NDEBUG // bk0001204
+ Com_Printf("BG_CanItemBeGrabbed: unknown enum %d\n", item->giType );
+#endif
+#endif
+ break;
+ }
+
+ return qfalse;
+}
+
+//======================================================================
+
+/*
+================
+BG_EvaluateTrajectory
+
+================
+*/
+void BG_EvaluateTrajectory( const trajectory_t *tr, int atTime, vec3_t result ) {
+ float deltaTime;
+ float phase;
+
+ switch( tr->trType ) {
+ case TR_STATIONARY:
+ case TR_INTERPOLATE:
+ VectorCopy( tr->trBase, result );
+ break;
+ case TR_LINEAR:
+ deltaTime = ( atTime - tr->trTime ) * 0.001; // milliseconds to seconds
+ VectorMA( tr->trBase, deltaTime, tr->trDelta, result );
+ break;
+ case TR_SINE:
+ deltaTime = ( atTime - tr->trTime ) / (float) tr->trDuration;
+ phase = sin( deltaTime * M_PI * 2 );
+ VectorMA( tr->trBase, phase, tr->trDelta, result );
+ break;
+ case TR_LINEAR_STOP:
+ if ( atTime > tr->trTime + tr->trDuration ) {
+ atTime = tr->trTime + tr->trDuration;
+ }
+ deltaTime = ( atTime - tr->trTime ) * 0.001; // milliseconds to seconds
+ if ( deltaTime < 0 ) {
+ deltaTime = 0;
+ }
+ VectorMA( tr->trBase, deltaTime, tr->trDelta, result );
+ break;
+ case TR_GRAVITY:
+ deltaTime = ( atTime - tr->trTime ) * 0.001; // milliseconds to seconds
+ VectorMA( tr->trBase, deltaTime, tr->trDelta, result );
+ result[2] -= 0.5 * DEFAULT_GRAVITY * deltaTime * deltaTime; // FIXME: local gravity...
+ break;
+ default:
+ Com_Error( ERR_DROP, "BG_EvaluateTrajectory: unknown trType: %i", tr->trTime );
+ break;
+ }
+}
+
+/*
+================
+BG_EvaluateTrajectoryDelta
+
+For determining velocity at a given time
+================
+*/
+void BG_EvaluateTrajectoryDelta( const trajectory_t *tr, int atTime, vec3_t result ) {
+ float deltaTime;
+ float phase;
+
+ switch( tr->trType ) {
+ case TR_STATIONARY:
+ case TR_INTERPOLATE:
+ VectorClear( result );
+ break;
+ case TR_LINEAR:
+ VectorCopy( tr->trDelta, result );
+ break;
+ case TR_SINE:
+ deltaTime = ( atTime - tr->trTime ) / (float) tr->trDuration;
+ phase = cos( deltaTime * M_PI * 2 ); // derivative of sin = cos
+ phase *= 0.5;
+ VectorScale( tr->trDelta, phase, result );
+ break;
+ case TR_LINEAR_STOP:
+ if ( atTime > tr->trTime + tr->trDuration ) {
+ VectorClear( result );
+ return;
+ }
+ VectorCopy( tr->trDelta, result );
+ break;
+ case TR_GRAVITY:
+ deltaTime = ( atTime - tr->trTime ) * 0.001; // milliseconds to seconds
+ VectorCopy( tr->trDelta, result );
+ result[2] -= DEFAULT_GRAVITY * deltaTime; // FIXME: local gravity...
+ break;
+ default:
+ Com_Error( ERR_DROP, "BG_EvaluateTrajectoryDelta: unknown trType: %i", tr->trTime );
+ break;
+ }
+}
+
+char *eventnames[] = {
+ "EV_NONE",
+
+ "EV_FOOTSTEP",
+ "EV_FOOTSTEP_METAL",
+ "EV_FOOTSPLASH",
+ "EV_FOOTWADE",
+ "EV_SWIM",
+
+ "EV_STEP_4",
+ "EV_STEP_8",
+ "EV_STEP_12",
+ "EV_STEP_16",
+
+ "EV_FALL_SHORT",
+ "EV_FALL_MEDIUM",
+ "EV_FALL_FAR",
+
+ "EV_JUMP_PAD", // boing sound at origin", jump sound on player
+
+ "EV_JUMP",
+ "EV_WATER_TOUCH", // foot touches
+ "EV_WATER_LEAVE", // foot leaves
+ "EV_WATER_UNDER", // head touches
+ "EV_WATER_CLEAR", // head leaves
+
+ "EV_ITEM_PICKUP", // normal item pickups are predictable
+ "EV_GLOBAL_ITEM_PICKUP", // powerup / team sounds are broadcast to everyone
+
+ "EV_NOAMMO",
+ "EV_CHANGE_WEAPON",
+ "EV_FIRE_WEAPON",
+
+ "EV_USE_ITEM0",
+ "EV_USE_ITEM1",
+ "EV_USE_ITEM2",
+ "EV_USE_ITEM3",
+ "EV_USE_ITEM4",
+ "EV_USE_ITEM5",
+ "EV_USE_ITEM6",
+ "EV_USE_ITEM7",
+ "EV_USE_ITEM8",
+ "EV_USE_ITEM9",
+ "EV_USE_ITEM10",
+ "EV_USE_ITEM11",
+ "EV_USE_ITEM12",
+ "EV_USE_ITEM13",
+ "EV_USE_ITEM14",
+ "EV_USE_ITEM15",
+
+ "EV_ITEM_RESPAWN",
+ "EV_ITEM_POP",
+ "EV_PLAYER_TELEPORT_IN",
+ "EV_PLAYER_TELEPORT_OUT",
+
+ "EV_GRENADE_BOUNCE", // eventParm will be the soundindex
+
+ "EV_GENERAL_SOUND",
+ "EV_GLOBAL_SOUND", // no attenuation
+ "EV_GLOBAL_TEAM_SOUND",
+
+ "EV_BULLET_HIT_FLESH",
+ "EV_BULLET_HIT_WALL",
+
+ "EV_MISSILE_HIT",
+ "EV_MISSILE_MISS",
+ "EV_MISSILE_MISS_METAL",
+ "EV_RAILTRAIL",
+ "EV_SHOTGUN",
+ "EV_BULLET", // otherEntity is the shooter
+
+ "EV_PAIN",
+ "EV_DEATH1",
+ "EV_DEATH2",
+ "EV_DEATH3",
+ "EV_OBITUARY",
+
+ "EV_POWERUP_QUAD",
+ "EV_POWERUP_BATTLESUIT",
+ "EV_POWERUP_REGEN",
+
+ "EV_GIB_PLAYER", // gib a previously living player
+ "EV_SCOREPLUM", // score plum
+
+//#ifdef MISSIONPACK
+ "EV_PROXIMITY_MINE_STICK",
+ "EV_PROXIMITY_MINE_TRIGGER",
+ "EV_KAMIKAZE", // kamikaze explodes
+ "EV_OBELISKEXPLODE", // obelisk explodes
+ "EV_INVUL_IMPACT", // invulnerability sphere impact
+ "EV_JUICED", // invulnerability juiced effect
+ "EV_LIGHTNINGBOLT", // lightning bolt bounced of invulnerability sphere
+//#endif
+
+ "EV_DEBUG_LINE",
+ "EV_STOPLOOPINGSOUND",
+ "EV_TAUNT"
+
+};
+
+/*
+===============
+BG_AddPredictableEventToPlayerstate
+
+Handles the sequence numbers
+===============
+*/
+
+void trap_Cvar_VariableStringBuffer( const char *var_name, char *buffer, int bufsize );
+
+void BG_AddPredictableEventToPlayerstate( int newEvent, int eventParm, playerState_t *ps ) {
+
+#ifdef _DEBUG
+ {
+ char buf[256];
+ trap_Cvar_VariableStringBuffer("showevents", buf, sizeof(buf));
+ if ( atof(buf) != 0 ) {
+#ifdef QAGAME
+ Com_Printf(" game event svt %5d -> %5d: num = %20s parm %d\n", ps->pmove_framecount/*ps->commandTime*/, ps->eventSequence, eventnames[newEvent], eventParm);
+#else
+ Com_Printf("Cgame event svt %5d -> %5d: num = %20s parm %d\n", ps->pmove_framecount/*ps->commandTime*/, ps->eventSequence, eventnames[newEvent], eventParm);
+#endif
+ }
+ }
+#endif
+ ps->events[ps->eventSequence & (MAX_PS_EVENTS-1)] = newEvent;
+ ps->eventParms[ps->eventSequence & (MAX_PS_EVENTS-1)] = eventParm;
+ ps->eventSequence++;
+}
+
+/*
+========================
+BG_TouchJumpPad
+========================
+*/
+void BG_TouchJumpPad( playerState_t *ps, entityState_t *jumppad ) {
+ vec3_t angles;
+ float p;
+ int effectNum;
+
+ // spectators don't use jump pads
+ if ( ps->pm_type != PM_NORMAL ) {
+ return;
+ }
+
+ // flying characters don't hit bounce pads
+ if ( ps->powerups[PW_FLIGHT] ) {
+ return;
+ }
+
+ // if we didn't hit this same jumppad the previous frame
+ // then don't play the event sound again if we are in a fat trigger
+ if ( ps->jumppad_ent != jumppad->number ) {
+
+ vectoangles( jumppad->origin2, angles);
+ p = fabs( AngleNormalize180( angles[PITCH] ) );
+ if( p < 45 ) {
+ effectNum = 0;
+ } else {
+ effectNum = 1;
+ }
+ BG_AddPredictableEventToPlayerstate( EV_JUMP_PAD, effectNum, ps );
+ }
+ // remember hitting this jumppad this frame
+ ps->jumppad_ent = jumppad->number;
+ ps->jumppad_frame = ps->pmove_framecount;
+ // give the player the velocity from the jumppad
+ VectorCopy( jumppad->origin2, ps->velocity );
+}
+
+/*
+========================
+BG_PlayerStateToEntityState
+
+This is done after each set of usercmd_t on the server,
+and after local prediction on the client
+========================
+*/
+void BG_PlayerStateToEntityState( playerState_t *ps, entityState_t *s, qboolean snap ) {
+ int i;
+
+ if ( ps->pm_type == PM_INTERMISSION || ps->pm_type == PM_SPECTATOR ) {
+ s->eType = ET_INVISIBLE;
+ } else if ( ps->stats[STAT_HEALTH] <= GIB_HEALTH ) {
+ s->eType = ET_INVISIBLE;
+ } else {
+ s->eType = ET_PLAYER;
+ }
+
+ s->number = ps->clientNum;
+
+ s->pos.trType = TR_INTERPOLATE;
+ VectorCopy( ps->origin, s->pos.trBase );
+ if ( snap ) {
+ SnapVector( s->pos.trBase );
+ }
+ // set the trDelta for flag direction
+ VectorCopy( ps->velocity, s->pos.trDelta );
+
+ s->apos.trType = TR_INTERPOLATE;
+ VectorCopy( ps->viewangles, s->apos.trBase );
+ if ( snap ) {
+ SnapVector( s->apos.trBase );
+ }
+
+ s->angles2[YAW] = ps->movementDir;
+ s->legsAnim = ps->legsAnim;
+ s->torsoAnim = ps->torsoAnim;
+ s->clientNum = ps->clientNum; // ET_PLAYER looks here instead of at number
+ // so corpses can also reference the proper config
+ s->eFlags = ps->eFlags;
+ if ( ps->stats[STAT_HEALTH] <= 0 ) {
+ s->eFlags |= EF_DEAD;
+ } else {
+ s->eFlags &= ~EF_DEAD;
+ }
+
+ if ( ps->externalEvent ) {
+ s->event = ps->externalEvent;
+ s->eventParm = ps->externalEventParm;
+ } else if ( ps->entityEventSequence < ps->eventSequence ) {
+ int seq;
+
+ if ( ps->entityEventSequence < ps->eventSequence - MAX_PS_EVENTS) {
+ ps->entityEventSequence = ps->eventSequence - MAX_PS_EVENTS;
+ }
+ seq = ps->entityEventSequence & (MAX_PS_EVENTS-1);
+ s->event = ps->events[ seq ] | ( ( ps->entityEventSequence & 3 ) << 8 );
+ s->eventParm = ps->eventParms[ seq ];
+ ps->entityEventSequence++;
+ }
+
+ s->weapon = ps->weapon;
+ s->groundEntityNum = ps->groundEntityNum;
+
+ s->powerups = 0;
+ for ( i = 0 ; i < MAX_POWERUPS ; i++ ) {
+ if ( ps->powerups[ i ] ) {
+ s->powerups |= 1 << i;
+ }
+ }
+
+ s->loopSound = ps->loopSound;
+ s->generic1 = ps->generic1;
+}
+
+/*
+========================
+BG_PlayerStateToEntityStateExtraPolate
+
+This is done after each set of usercmd_t on the server,
+and after local prediction on the client
+========================
+*/
+void BG_PlayerStateToEntityStateExtraPolate( playerState_t *ps, entityState_t *s, int time, qboolean snap ) {
+ int i;
+
+ if ( ps->pm_type == PM_INTERMISSION || ps->pm_type == PM_SPECTATOR ) {
+ s->eType = ET_INVISIBLE;
+ } else if ( ps->stats[STAT_HEALTH] <= GIB_HEALTH ) {
+ s->eType = ET_INVISIBLE;
+ } else {
+ s->eType = ET_PLAYER;
+ }
+
+ s->number = ps->clientNum;
+
+ s->pos.trType = TR_LINEAR_STOP;
+ VectorCopy( ps->origin, s->pos.trBase );
+ if ( snap ) {
+ SnapVector( s->pos.trBase );
+ }
+ // set the trDelta for flag direction and linear prediction
+ VectorCopy( ps->velocity, s->pos.trDelta );
+ // set the time for linear prediction
+ s->pos.trTime = time;
+ // set maximum extra polation time
+ s->pos.trDuration = 50; // 1000 / sv_fps (default = 20)
+
+ s->apos.trType = TR_INTERPOLATE;
+ VectorCopy( ps->viewangles, s->apos.trBase );
+ if ( snap ) {
+ SnapVector( s->apos.trBase );
+ }
+
+ s->angles2[YAW] = ps->movementDir;
+ s->legsAnim = ps->legsAnim;
+ s->torsoAnim = ps->torsoAnim;
+ s->clientNum = ps->clientNum; // ET_PLAYER looks here instead of at number
+ // so corpses can also reference the proper config
+ s->eFlags = ps->eFlags;
+ if ( ps->stats[STAT_HEALTH] <= 0 ) {
+ s->eFlags |= EF_DEAD;
+ } else {
+ s->eFlags &= ~EF_DEAD;
+ }
+
+ if ( ps->externalEvent ) {
+ s->event = ps->externalEvent;
+ s->eventParm = ps->externalEventParm;
+ } else if ( ps->entityEventSequence < ps->eventSequence ) {
+ int seq;
+
+ if ( ps->entityEventSequence < ps->eventSequence - MAX_PS_EVENTS) {
+ ps->entityEventSequence = ps->eventSequence - MAX_PS_EVENTS;
+ }
+ seq = ps->entityEventSequence & (MAX_PS_EVENTS-1);
+ s->event = ps->events[ seq ] | ( ( ps->entityEventSequence & 3 ) << 8 );
+ s->eventParm = ps->eventParms[ seq ];
+ ps->entityEventSequence++;
+ }
+
+ s->weapon = ps->weapon;
+ s->groundEntityNum = ps->groundEntityNum;
+
+ s->powerups = 0;
+ for ( i = 0 ; i < MAX_POWERUPS ; i++ ) {
+ if ( ps->powerups[ i ] ) {
+ s->powerups |= 1 << i;
+ }
+ }
+
+ s->loopSound = ps->loopSound;
+ s->generic1 = ps->generic1;
+}
diff --git a/code/game/bg_pmove.c b/code/game/bg_pmove.c
new file mode 100755
index 0000000..3711869
--- /dev/null
+++ b/code/game/bg_pmove.c
@@ -0,0 +1,2069 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// bg_pmove.c -- both games player movement code
+// takes a playerstate and a usercmd as input and returns a modifed playerstate
+
+#include "q_shared.h"
+#include "bg_public.h"
+#include "bg_local.h"
+
+pmove_t *pm;
+pml_t pml;
+
+// movement parameters
+float pm_stopspeed = 100.0f;
+float pm_duckScale = 0.25f;
+float pm_swimScale = 0.50f;
+float pm_wadeScale = 0.70f;
+
+float pm_accelerate = 10.0f;
+float pm_airaccelerate = 1.0f;
+float pm_wateraccelerate = 4.0f;
+float pm_flyaccelerate = 8.0f;
+
+float pm_friction = 6.0f;
+float pm_waterfriction = 1.0f;
+float pm_flightfriction = 3.0f;
+float pm_spectatorfriction = 5.0f;
+
+int c_pmove = 0;
+
+
+/*
+===============
+PM_AddEvent
+
+===============
+*/
+void PM_AddEvent( int newEvent ) {
+ BG_AddPredictableEventToPlayerstate( newEvent, 0, pm->ps );
+}
+
+/*
+===============
+PM_AddTouchEnt
+===============
+*/
+void PM_AddTouchEnt( int entityNum ) {
+ int i;
+
+ if ( entityNum == ENTITYNUM_WORLD ) {
+ return;
+ }
+ if ( pm->numtouch == MAXTOUCH ) {
+ return;
+ }
+
+ // see if it is already added
+ for ( i = 0 ; i < pm->numtouch ; i++ ) {
+ if ( pm->touchents[ i ] == entityNum ) {
+ return;
+ }
+ }
+
+ // add it
+ pm->touchents[pm->numtouch] = entityNum;
+ pm->numtouch++;
+}
+
+/*
+===================
+PM_StartTorsoAnim
+===================
+*/
+static void PM_StartTorsoAnim( int anim ) {
+ if ( pm->ps->pm_type >= PM_DEAD ) {
+ return;
+ }
+ pm->ps->torsoAnim = ( ( pm->ps->torsoAnim & ANIM_TOGGLEBIT ) ^ ANIM_TOGGLEBIT )
+ | anim;
+}
+static void PM_StartLegsAnim( int anim ) {
+ if ( pm->ps->pm_type >= PM_DEAD ) {
+ return;
+ }
+ if ( pm->ps->legsTimer > 0 ) {
+ return; // a high priority animation is running
+ }
+ pm->ps->legsAnim = ( ( pm->ps->legsAnim & ANIM_TOGGLEBIT ) ^ ANIM_TOGGLEBIT )
+ | anim;
+}
+
+static void PM_ContinueLegsAnim( int anim ) {
+ if ( ( pm->ps->legsAnim & ~ANIM_TOGGLEBIT ) == anim ) {
+ return;
+ }
+ if ( pm->ps->legsTimer > 0 ) {
+ return; // a high priority animation is running
+ }
+ PM_StartLegsAnim( anim );
+}
+
+static void PM_ContinueTorsoAnim( int anim ) {
+ if ( ( pm->ps->torsoAnim & ~ANIM_TOGGLEBIT ) == anim ) {
+ return;
+ }
+ if ( pm->ps->torsoTimer > 0 ) {
+ return; // a high priority animation is running
+ }
+ PM_StartTorsoAnim( anim );
+}
+
+static void PM_ForceLegsAnim( int anim ) {
+ pm->ps->legsTimer = 0;
+ PM_StartLegsAnim( anim );
+}
+
+
+/*
+==================
+PM_ClipVelocity
+
+Slide off of the impacting surface
+==================
+*/
+void PM_ClipVelocity( vec3_t in, vec3_t normal, vec3_t out, float overbounce ) {
+ float backoff;
+ float change;
+ int i;
+
+ backoff = DotProduct (in, normal);
+
+ if ( backoff < 0 ) {
+ backoff *= overbounce;
+ } else {
+ backoff /= overbounce;
+ }
+
+ for ( i=0 ; i<3 ; i++ ) {
+ change = normal[i]*backoff;
+ out[i] = in[i] - change;
+ }
+}
+
+
+/*
+==================
+PM_Friction
+
+Handles both ground friction and water friction
+==================
+*/
+static void PM_Friction( void ) {
+ vec3_t vec;
+ float *vel;
+ float speed, newspeed, control;
+ float drop;
+
+ vel = pm->ps->velocity;
+
+ VectorCopy( vel, vec );
+ if ( pml.walking ) {
+ vec[2] = 0; // ignore slope movement
+ }
+
+ speed = VectorLength(vec);
+ if (speed < 1) {
+ vel[0] = 0;
+ vel[1] = 0; // allow sinking underwater
+ // FIXME: still have z friction underwater?
+ return;
+ }
+
+ drop = 0;
+
+ // apply ground friction
+ if ( pm->waterlevel <= 1 ) {
+ if ( pml.walking && !(pml.groundTrace.surfaceFlags & SURF_SLICK) ) {
+ // if getting knocked back, no friction
+ if ( ! (pm->ps->pm_flags & PMF_TIME_KNOCKBACK) ) {
+ control = speed < pm_stopspeed ? pm_stopspeed : speed;
+ drop += control*pm_friction*pml.frametime;
+ }
+ }
+ }
+
+ // apply water friction even if just wading
+ if ( pm->waterlevel ) {
+ drop += speed*pm_waterfriction*pm->waterlevel*pml.frametime;
+ }
+
+ // apply flying friction
+ if ( pm->ps->powerups[PW_FLIGHT]) {
+ drop += speed*pm_flightfriction*pml.frametime;
+ }
+
+ if ( pm->ps->pm_type == PM_SPECTATOR) {
+ drop += speed*pm_spectatorfriction*pml.frametime;
+ }
+
+ // scale the velocity
+ newspeed = speed - drop;
+ if (newspeed < 0) {
+ newspeed = 0;
+ }
+ newspeed /= speed;
+
+ vel[0] = vel[0] * newspeed;
+ vel[1] = vel[1] * newspeed;
+ vel[2] = vel[2] * newspeed;
+}
+
+
+/*
+==============
+PM_Accelerate
+
+Handles user intended acceleration
+==============
+*/
+static void PM_Accelerate( vec3_t wishdir, float wishspeed, float accel ) {
+#if 1
+ // q2 style
+ int i;
+ float addspeed, accelspeed, currentspeed;
+
+ currentspeed = DotProduct (pm->ps->velocity, wishdir);
+ addspeed = wishspeed - currentspeed;
+ if (addspeed <= 0) {
+ return;
+ }
+ accelspeed = accel*pml.frametime*wishspeed;
+ if (accelspeed > addspeed) {
+ accelspeed = addspeed;
+ }
+
+ for (i=0 ; i<3 ; i++) {
+ pm->ps->velocity[i] += accelspeed*wishdir[i];
+ }
+#else
+ // proper way (avoids strafe jump maxspeed bug), but feels bad
+ vec3_t wishVelocity;
+ vec3_t pushDir;
+ float pushLen;
+ float canPush;
+
+ VectorScale( wishdir, wishspeed, wishVelocity );
+ VectorSubtract( wishVelocity, pm->ps->velocity, pushDir );
+ pushLen = VectorNormalize( pushDir );
+
+ canPush = accel*pml.frametime*wishspeed;
+ if (canPush > pushLen) {
+ canPush = pushLen;
+ }
+
+ VectorMA( pm->ps->velocity, canPush, pushDir, pm->ps->velocity );
+#endif
+}
+
+
+
+/*
+============
+PM_CmdScale
+
+Returns the scale factor to apply to cmd movements
+This allows the clients to use axial -127 to 127 values for all directions
+without getting a sqrt(2) distortion in speed.
+============
+*/
+static float PM_CmdScale( usercmd_t *cmd ) {
+ int max;
+ float total;
+ float scale;
+
+ max = abs( cmd->forwardmove );
+ if ( abs( cmd->rightmove ) > max ) {
+ max = abs( cmd->rightmove );
+ }
+ if ( abs( cmd->upmove ) > max ) {
+ max = abs( cmd->upmove );
+ }
+ if ( !max ) {
+ return 0;
+ }
+
+ total = sqrt( cmd->forwardmove * cmd->forwardmove
+ + cmd->rightmove * cmd->rightmove + cmd->upmove * cmd->upmove );
+ scale = (float)pm->ps->speed * max / ( 127.0 * total );
+
+ return scale;
+}
+
+
+/*
+================
+PM_SetMovementDir
+
+Determine the rotation of the legs reletive
+to the facing dir
+================
+*/
+static void PM_SetMovementDir( void ) {
+ if ( pm->cmd.forwardmove || pm->cmd.rightmove ) {
+ if ( pm->cmd.rightmove == 0 && pm->cmd.forwardmove > 0 ) {
+ pm->ps->movementDir = 0;
+ } else if ( pm->cmd.rightmove < 0 && pm->cmd.forwardmove > 0 ) {
+ pm->ps->movementDir = 1;
+ } else if ( pm->cmd.rightmove < 0 && pm->cmd.forwardmove == 0 ) {
+ pm->ps->movementDir = 2;
+ } else if ( pm->cmd.rightmove < 0 && pm->cmd.forwardmove < 0 ) {
+ pm->ps->movementDir = 3;
+ } else if ( pm->cmd.rightmove == 0 && pm->cmd.forwardmove < 0 ) {
+ pm->ps->movementDir = 4;
+ } else if ( pm->cmd.rightmove > 0 && pm->cmd.forwardmove < 0 ) {
+ pm->ps->movementDir = 5;
+ } else if ( pm->cmd.rightmove > 0 && pm->cmd.forwardmove == 0 ) {
+ pm->ps->movementDir = 6;
+ } else if ( pm->cmd.rightmove > 0 && pm->cmd.forwardmove > 0 ) {
+ pm->ps->movementDir = 7;
+ }
+ } else {
+ // if they aren't actively going directly sideways,
+ // change the animation to the diagonal so they
+ // don't stop too crooked
+ if ( pm->ps->movementDir == 2 ) {
+ pm->ps->movementDir = 1;
+ } else if ( pm->ps->movementDir == 6 ) {
+ pm->ps->movementDir = 7;
+ }
+ }
+}
+
+
+/*
+=============
+PM_CheckJump
+=============
+*/
+static qboolean PM_CheckJump( void ) {
+ if ( pm->ps->pm_flags & PMF_RESPAWNED ) {
+ return qfalse; // don't allow jump until all buttons are up
+ }
+
+ if ( pm->cmd.upmove < 10 ) {
+ // not holding jump
+ return qfalse;
+ }
+
+ // must wait for jump to be released
+ if ( pm->ps->pm_flags & PMF_JUMP_HELD ) {
+ // clear upmove so cmdscale doesn't lower running speed
+ pm->cmd.upmove = 0;
+ return qfalse;
+ }
+
+ pml.groundPlane = qfalse; // jumping away
+ pml.walking = qfalse;
+ pm->ps->pm_flags |= PMF_JUMP_HELD;
+
+ pm->ps->groundEntityNum = ENTITYNUM_NONE;
+ pm->ps->velocity[2] = JUMP_VELOCITY;
+ PM_AddEvent( EV_JUMP );
+
+ if ( pm->cmd.forwardmove >= 0 ) {
+ PM_ForceLegsAnim( LEGS_JUMP );
+ pm->ps->pm_flags &= ~PMF_BACKWARDS_JUMP;
+ } else {
+ PM_ForceLegsAnim( LEGS_JUMPB );
+ pm->ps->pm_flags |= PMF_BACKWARDS_JUMP;
+ }
+
+ return qtrue;
+}
+
+/*
+=============
+PM_CheckWaterJump
+=============
+*/
+static qboolean PM_CheckWaterJump( void ) {
+ vec3_t spot;
+ int cont;
+ vec3_t flatforward;
+
+ if (pm->ps->pm_time) {
+ return qfalse;
+ }
+
+ // check for water jump
+ if ( pm->waterlevel != 2 ) {
+ return qfalse;
+ }
+
+ flatforward[0] = pml.forward[0];
+ flatforward[1] = pml.forward[1];
+ flatforward[2] = 0;
+ VectorNormalize (flatforward);
+
+ VectorMA (pm->ps->origin, 30, flatforward, spot);
+ spot[2] += 4;
+ cont = pm->pointcontents (spot, pm->ps->clientNum );
+ if ( !(cont & CONTENTS_SOLID) ) {
+ return qfalse;
+ }
+
+ spot[2] += 16;
+ cont = pm->pointcontents (spot, pm->ps->clientNum );
+ if ( cont ) {
+ return qfalse;
+ }
+
+ // jump out of water
+ VectorScale (pml.forward, 200, pm->ps->velocity);
+ pm->ps->velocity[2] = 350;
+
+ pm->ps->pm_flags |= PMF_TIME_WATERJUMP;
+ pm->ps->pm_time = 2000;
+
+ return qtrue;
+}
+
+//============================================================================
+
+
+/*
+===================
+PM_WaterJumpMove
+
+Flying out of the water
+===================
+*/
+static void PM_WaterJumpMove( void ) {
+ // waterjump has no control, but falls
+
+ PM_StepSlideMove( qtrue );
+
+ pm->ps->velocity[2] -= pm->ps->gravity * pml.frametime;
+ if (pm->ps->velocity[2] < 0) {
+ // cancel as soon as we are falling down again
+ pm->ps->pm_flags &= ~PMF_ALL_TIMES;
+ pm->ps->pm_time = 0;
+ }
+}
+
+/*
+===================
+PM_WaterMove
+
+===================
+*/
+static void PM_WaterMove( void ) {
+ int i;
+ vec3_t wishvel;
+ float wishspeed;
+ vec3_t wishdir;
+ float scale;
+ float vel;
+
+ if ( PM_CheckWaterJump() ) {
+ PM_WaterJumpMove();
+ return;
+ }
+#if 0
+ // jump = head for surface
+ if ( pm->cmd.upmove >= 10 ) {
+ if (pm->ps->velocity[2] > -300) {
+ if ( pm->watertype == CONTENTS_WATER ) {
+ pm->ps->velocity[2] = 100;
+ } else if (pm->watertype == CONTENTS_SLIME) {
+ pm->ps->velocity[2] = 80;
+ } else {
+ pm->ps->velocity[2] = 50;
+ }
+ }
+ }
+#endif
+ PM_Friction ();
+
+ scale = PM_CmdScale( &pm->cmd );
+ //
+ // user intentions
+ //
+ if ( !scale ) {
+ wishvel[0] = 0;
+ wishvel[1] = 0;
+ wishvel[2] = -60; // sink towards bottom
+ } else {
+ for (i=0 ; i<3 ; i++)
+ wishvel[i] = scale * pml.forward[i]*pm->cmd.forwardmove + scale * pml.right[i]*pm->cmd.rightmove;
+
+ wishvel[2] += scale * pm->cmd.upmove;
+ }
+
+ VectorCopy (wishvel, wishdir);
+ wishspeed = VectorNormalize(wishdir);
+
+ if ( wishspeed > pm->ps->speed * pm_swimScale ) {
+ wishspeed = pm->ps->speed * pm_swimScale;
+ }
+
+ PM_Accelerate (wishdir, wishspeed, pm_wateraccelerate);
+
+ // make sure we can go up slopes easily under water
+ if ( pml.groundPlane && DotProduct( pm->ps->velocity, pml.groundTrace.plane.normal ) < 0 ) {
+ vel = VectorLength(pm->ps->velocity);
+ // slide along the ground plane
+ PM_ClipVelocity (pm->ps->velocity, pml.groundTrace.plane.normal,
+ pm->ps->velocity, OVERCLIP );
+
+ VectorNormalize(pm->ps->velocity);
+ VectorScale(pm->ps->velocity, vel, pm->ps->velocity);
+ }
+
+ PM_SlideMove( qfalse );
+}
+
+#ifdef MISSIONPACK
+/*
+===================
+PM_InvulnerabilityMove
+
+Only with the invulnerability powerup
+===================
+*/
+static void PM_InvulnerabilityMove( void ) {
+ pm->cmd.forwardmove = 0;
+ pm->cmd.rightmove = 0;
+ pm->cmd.upmove = 0;
+ VectorClear(pm->ps->velocity);
+}
+#endif
+
+/*
+===================
+PM_FlyMove
+
+Only with the flight powerup
+===================
+*/
+static void PM_FlyMove( void ) {
+ int i;
+ vec3_t wishvel;
+ float wishspeed;
+ vec3_t wishdir;
+ float scale;
+
+ // normal slowdown
+ PM_Friction ();
+
+ scale = PM_CmdScale( &pm->cmd );
+ //
+ // user intentions
+ //
+ if ( !scale ) {
+ wishvel[0] = 0;
+ wishvel[1] = 0;
+ wishvel[2] = 0;
+ } else {
+ for (i=0 ; i<3 ; i++) {
+ wishvel[i] = scale * pml.forward[i]*pm->cmd.forwardmove + scale * pml.right[i]*pm->cmd.rightmove;
+ }
+
+ wishvel[2] += scale * pm->cmd.upmove;
+ }
+
+ VectorCopy (wishvel, wishdir);
+ wishspeed = VectorNormalize(wishdir);
+
+ PM_Accelerate (wishdir, wishspeed, pm_flyaccelerate);
+
+ PM_StepSlideMove( qfalse );
+}
+
+
+/*
+===================
+PM_AirMove
+
+===================
+*/
+static void PM_AirMove( void ) {
+ int i;
+ vec3_t wishvel;
+ float fmove, smove;
+ vec3_t wishdir;
+ float wishspeed;
+ float scale;
+ usercmd_t cmd;
+
+ PM_Friction();
+
+ fmove = pm->cmd.forwardmove;
+ smove = pm->cmd.rightmove;
+
+ cmd = pm->cmd;
+ scale = PM_CmdScale( &cmd );
+
+ // set the movementDir so clients can rotate the legs for strafing
+ PM_SetMovementDir();
+
+ // project moves down to flat plane
+ pml.forward[2] = 0;
+ pml.right[2] = 0;
+ VectorNormalize (pml.forward);
+ VectorNormalize (pml.right);
+
+ for ( i = 0 ; i < 2 ; i++ ) {
+ wishvel[i] = pml.forward[i]*fmove + pml.right[i]*smove;
+ }
+ wishvel[2] = 0;
+
+ VectorCopy (wishvel, wishdir);
+ wishspeed = VectorNormalize(wishdir);
+ wishspeed *= scale;
+
+ // not on ground, so little effect on velocity
+ PM_Accelerate (wishdir, wishspeed, pm_airaccelerate);
+
+ // we may have a ground plane that is very steep, even
+ // though we don't have a groundentity
+ // slide along the steep plane
+ if ( pml.groundPlane ) {
+ PM_ClipVelocity (pm->ps->velocity, pml.groundTrace.plane.normal,
+ pm->ps->velocity, OVERCLIP );
+ }
+
+#if 0
+ //ZOID: If we are on the grapple, try stair-stepping
+ //this allows a player to use the grapple to pull himself
+ //over a ledge
+ if (pm->ps->pm_flags & PMF_GRAPPLE_PULL)
+ PM_StepSlideMove ( qtrue );
+ else
+ PM_SlideMove ( qtrue );
+#endif
+
+ PM_StepSlideMove ( qtrue );
+}
+
+/*
+===================
+PM_GrappleMove
+
+===================
+*/
+static void PM_GrappleMove( void ) {
+ vec3_t vel, v;
+ float vlen;
+
+ VectorScale(pml.forward, -16, v);
+ VectorAdd(pm->ps->grapplePoint, v, v);
+ VectorSubtract(v, pm->ps->origin, vel);
+ vlen = VectorLength(vel);
+ VectorNormalize( vel );
+
+ if (vlen <= 100)
+ VectorScale(vel, 10 * vlen, vel);
+ else
+ VectorScale(vel, 800, vel);
+
+ VectorCopy(vel, pm->ps->velocity);
+
+ pml.groundPlane = qfalse;
+}
+
+/*
+===================
+PM_WalkMove
+
+===================
+*/
+static void PM_WalkMove( void ) {
+ int i;
+ vec3_t wishvel;
+ float fmove, smove;
+ vec3_t wishdir;
+ float wishspeed;
+ float scale;
+ usercmd_t cmd;
+ float accelerate;
+ float vel;
+
+ if ( pm->waterlevel > 2 && DotProduct( pml.forward, pml.groundTrace.plane.normal ) > 0 ) {
+ // begin swimming
+ PM_WaterMove();
+ return;
+ }
+
+
+ if ( PM_CheckJump () ) {
+ // jumped away
+ if ( pm->waterlevel > 1 ) {
+ PM_WaterMove();
+ } else {
+ PM_AirMove();
+ }
+ return;
+ }
+
+ PM_Friction ();
+
+ fmove = pm->cmd.forwardmove;
+ smove = pm->cmd.rightmove;
+
+ cmd = pm->cmd;
+ scale = PM_CmdScale( &cmd );
+
+ // set the movementDir so clients can rotate the legs for strafing
+ PM_SetMovementDir();
+
+ // project moves down to flat plane
+ pml.forward[2] = 0;
+ pml.right[2] = 0;
+
+ // project the forward and right directions onto the ground plane
+ PM_ClipVelocity (pml.forward, pml.groundTrace.plane.normal, pml.forward, OVERCLIP );
+ PM_ClipVelocity (pml.right, pml.groundTrace.plane.normal, pml.right, OVERCLIP );
+ //
+ VectorNormalize (pml.forward);
+ VectorNormalize (pml.right);
+
+ for ( i = 0 ; i < 3 ; i++ ) {
+ wishvel[i] = pml.forward[i]*fmove + pml.right[i]*smove;
+ }
+ // when going up or down slopes the wish velocity should Not be zero
+// wishvel[2] = 0;
+
+ VectorCopy (wishvel, wishdir);
+ wishspeed = VectorNormalize(wishdir);
+ wishspeed *= scale;
+
+ // clamp the speed lower if ducking
+ if ( pm->ps->pm_flags & PMF_DUCKED ) {
+ if ( wishspeed > pm->ps->speed * pm_duckScale ) {
+ wishspeed = pm->ps->speed * pm_duckScale;
+ }
+ }
+
+ // clamp the speed lower if wading or walking on the bottom
+ if ( pm->waterlevel ) {
+ float waterScale;
+
+ waterScale = pm->waterlevel / 3.0;
+ waterScale = 1.0 - ( 1.0 - pm_swimScale ) * waterScale;
+ if ( wishspeed > pm->ps->speed * waterScale ) {
+ wishspeed = pm->ps->speed * waterScale;
+ }
+ }
+
+ // when a player gets hit, they temporarily lose
+ // full control, which allows them to be moved a bit
+ if ( ( pml.groundTrace.surfaceFlags & SURF_SLICK ) || pm->ps->pm_flags & PMF_TIME_KNOCKBACK ) {
+ accelerate = pm_airaccelerate;
+ } else {
+ accelerate = pm_accelerate;
+ }
+
+ PM_Accelerate (wishdir, wishspeed, accelerate);
+
+ //Com_Printf("velocity = %1.1f %1.1f %1.1f\n", pm->ps->velocity[0], pm->ps->velocity[1], pm->ps->velocity[2]);
+ //Com_Printf("velocity1 = %1.1f\n", VectorLength(pm->ps->velocity));
+
+ if ( ( pml.groundTrace.surfaceFlags & SURF_SLICK ) || pm->ps->pm_flags & PMF_TIME_KNOCKBACK ) {
+ pm->ps->velocity[2] -= pm->ps->gravity * pml.frametime;
+ } else {
+ // don't reset the z velocity for slopes
+// pm->ps->velocity[2] = 0;
+ }
+
+ vel = VectorLength(pm->ps->velocity);
+
+ // slide along the ground plane
+ PM_ClipVelocity (pm->ps->velocity, pml.groundTrace.plane.normal,
+ pm->ps->velocity, OVERCLIP );
+
+ // don't decrease velocity when going up or down a slope
+ VectorNormalize(pm->ps->velocity);
+ VectorScale(pm->ps->velocity, vel, pm->ps->velocity);
+
+ // don't do anything if standing still
+ if (!pm->ps->velocity[0] && !pm->ps->velocity[1]) {
+ return;
+ }
+
+ PM_StepSlideMove( qfalse );
+
+ //Com_Printf("velocity2 = %1.1f\n", VectorLength(pm->ps->velocity));
+
+}
+
+
+/*
+==============
+PM_DeadMove
+==============
+*/
+static void PM_DeadMove( void ) {
+ float forward;
+
+ if ( !pml.walking ) {
+ return;
+ }
+
+ // extra friction
+
+ forward = VectorLength (pm->ps->velocity);
+ forward -= 20;
+ if ( forward <= 0 ) {
+ VectorClear (pm->ps->velocity);
+ } else {
+ VectorNormalize (pm->ps->velocity);
+ VectorScale (pm->ps->velocity, forward, pm->ps->velocity);
+ }
+}
+
+
+/*
+===============
+PM_NoclipMove
+===============
+*/
+static void PM_NoclipMove( void ) {
+ float speed, drop, friction, control, newspeed;
+ int i;
+ vec3_t wishvel;
+ float fmove, smove;
+ vec3_t wishdir;
+ float wishspeed;
+ float scale;
+
+ pm->ps->viewheight = DEFAULT_VIEWHEIGHT;
+
+ // friction
+
+ speed = VectorLength (pm->ps->velocity);
+ if (speed < 1)
+ {
+ VectorCopy (vec3_origin, pm->ps->velocity);
+ }
+ else
+ {
+ drop = 0;
+
+ friction = pm_friction*1.5; // extra friction
+ control = speed < pm_stopspeed ? pm_stopspeed : speed;
+ drop += control*friction*pml.frametime;
+
+ // scale the velocity
+ newspeed = speed - drop;
+ if (newspeed < 0)
+ newspeed = 0;
+ newspeed /= speed;
+
+ VectorScale (pm->ps->velocity, newspeed, pm->ps->velocity);
+ }
+
+ // accelerate
+ scale = PM_CmdScale( &pm->cmd );
+
+ fmove = pm->cmd.forwardmove;
+ smove = pm->cmd.rightmove;
+
+ for (i=0 ; i<3 ; i++)
+ wishvel[i] = pml.forward[i]*fmove + pml.right[i]*smove;
+ wishvel[2] += pm->cmd.upmove;
+
+ VectorCopy (wishvel, wishdir);
+ wishspeed = VectorNormalize(wishdir);
+ wishspeed *= scale;
+
+ PM_Accelerate( wishdir, wishspeed, pm_accelerate );
+
+ // move
+ VectorMA (pm->ps->origin, pml.frametime, pm->ps->velocity, pm->ps->origin);
+}
+
+//============================================================================
+
+/*
+================
+PM_FootstepForSurface
+
+Returns an event number apropriate for the groundsurface
+================
+*/
+static int PM_FootstepForSurface( void ) {
+ if ( pml.groundTrace.surfaceFlags & SURF_NOSTEPS ) {
+ return 0;
+ }
+ if ( pml.groundTrace.surfaceFlags & SURF_METALSTEPS ) {
+ return EV_FOOTSTEP_METAL;
+ }
+ return EV_FOOTSTEP;
+}
+
+
+/*
+=================
+PM_CrashLand
+
+Check for hard landings that generate sound events
+=================
+*/
+static void PM_CrashLand( void ) {
+ float delta;
+ float dist;
+ float vel, acc;
+ float t;
+ float a, b, c, den;
+
+ // decide which landing animation to use
+ if ( pm->ps->pm_flags & PMF_BACKWARDS_JUMP ) {
+ PM_ForceLegsAnim( LEGS_LANDB );
+ } else {
+ PM_ForceLegsAnim( LEGS_LAND );
+ }
+
+ pm->ps->legsTimer = TIMER_LAND;
+
+ // calculate the exact velocity on landing
+ dist = pm->ps->origin[2] - pml.previous_origin[2];
+ vel = pml.previous_velocity[2];
+ acc = -pm->ps->gravity;
+
+ a = acc / 2;
+ b = vel;
+ c = -dist;
+
+ den = b * b - 4 * a * c;
+ if ( den < 0 ) {
+ return;
+ }
+ t = (-b - sqrt( den ) ) / ( 2 * a );
+
+ delta = vel + t * acc;
+ delta = delta*delta * 0.0001;
+
+ // ducking while falling doubles damage
+ if ( pm->ps->pm_flags & PMF_DUCKED ) {
+ delta *= 2;
+ }
+
+ // never take falling damage if completely underwater
+ if ( pm->waterlevel == 3 ) {
+ return;
+ }
+
+ // reduce falling damage if there is standing water
+ if ( pm->waterlevel == 2 ) {
+ delta *= 0.25;
+ }
+ if ( pm->waterlevel == 1 ) {
+ delta *= 0.5;
+ }
+
+ if ( delta < 1 ) {
+ return;
+ }
+
+ // create a local entity event to play the sound
+
+ // SURF_NODAMAGE is used for bounce pads where you don't ever
+ // want to take damage or play a crunch sound
+ if ( !(pml.groundTrace.surfaceFlags & SURF_NODAMAGE) ) {
+ if ( delta > 60 ) {
+ PM_AddEvent( EV_FALL_FAR );
+ } else if ( delta > 40 ) {
+ // this is a pain grunt, so don't play it if dead
+ if ( pm->ps->stats[STAT_HEALTH] > 0 ) {
+ PM_AddEvent( EV_FALL_MEDIUM );
+ }
+ } else if ( delta > 7 ) {
+ PM_AddEvent( EV_FALL_SHORT );
+ } else {
+ PM_AddEvent( PM_FootstepForSurface() );
+ }
+ }
+
+ // start footstep cycle over
+ pm->ps->bobCycle = 0;
+}
+
+/*
+=============
+PM_CheckStuck
+=============
+*/
+/*
+void PM_CheckStuck(void) {
+ trace_t trace;
+
+ pm->trace (&trace, pm->ps->origin, pm->mins, pm->maxs, pm->ps->origin, pm->ps->clientNum, pm->tracemask);
+ if (trace.allsolid) {
+ //int shit = qtrue;
+ }
+}
+*/
+
+/*
+=============
+PM_CorrectAllSolid
+=============
+*/
+static int PM_CorrectAllSolid( trace_t *trace ) {
+ int i, j, k;
+ vec3_t point;
+
+ if ( pm->debugLevel ) {
+ Com_Printf("%i:allsolid\n", c_pmove);
+ }
+
+ // jitter around
+ for (i = -1; i <= 1; i++) {
+ for (j = -1; j <= 1; j++) {
+ for (k = -1; k <= 1; k++) {
+ VectorCopy(pm->ps->origin, point);
+ point[0] += (float) i;
+ point[1] += (float) j;
+ point[2] += (float) k;
+ pm->trace (trace, point, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask);
+ if ( !trace->allsolid ) {
+ point[0] = pm->ps->origin[0];
+ point[1] = pm->ps->origin[1];
+ point[2] = pm->ps->origin[2] - 0.25;
+
+ pm->trace (trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask);
+ pml.groundTrace = *trace;
+ return qtrue;
+ }
+ }
+ }
+ }
+
+ pm->ps->groundEntityNum = ENTITYNUM_NONE;
+ pml.groundPlane = qfalse;
+ pml.walking = qfalse;
+
+ return qfalse;
+}
+
+
+/*
+=============
+PM_GroundTraceMissed
+
+The ground trace didn't hit a surface, so we are in freefall
+=============
+*/
+static void PM_GroundTraceMissed( void ) {
+ trace_t trace;
+ vec3_t point;
+
+ if ( pm->ps->groundEntityNum != ENTITYNUM_NONE ) {
+ // we just transitioned into freefall
+ if ( pm->debugLevel ) {
+ Com_Printf("%i:lift\n", c_pmove);
+ }
+
+ // if they aren't in a jumping animation and the ground is a ways away, force into it
+ // if we didn't do the trace, the player would be backflipping down staircases
+ VectorCopy( pm->ps->origin, point );
+ point[2] -= 64;
+
+ pm->trace (&trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask);
+ if ( trace.fraction == 1.0 ) {
+ if ( pm->cmd.forwardmove >= 0 ) {
+ PM_ForceLegsAnim( LEGS_JUMP );
+ pm->ps->pm_flags &= ~PMF_BACKWARDS_JUMP;
+ } else {
+ PM_ForceLegsAnim( LEGS_JUMPB );
+ pm->ps->pm_flags |= PMF_BACKWARDS_JUMP;
+ }
+ }
+ }
+
+ pm->ps->groundEntityNum = ENTITYNUM_NONE;
+ pml.groundPlane = qfalse;
+ pml.walking = qfalse;
+}
+
+
+/*
+=============
+PM_GroundTrace
+=============
+*/
+static void PM_GroundTrace( void ) {
+ vec3_t point;
+ trace_t trace;
+
+ point[0] = pm->ps->origin[0];
+ point[1] = pm->ps->origin[1];
+ point[2] = pm->ps->origin[2] - 0.25;
+
+ pm->trace (&trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask);
+ pml.groundTrace = trace;
+
+ // do something corrective if the trace starts in a solid...
+ if ( trace.allsolid ) {
+ if ( !PM_CorrectAllSolid(&trace) )
+ return;
+ }
+
+ // if the trace didn't hit anything, we are in free fall
+ if ( trace.fraction == 1.0 ) {
+ PM_GroundTraceMissed();
+ pml.groundPlane = qfalse;
+ pml.walking = qfalse;
+ return;
+ }
+
+ // check if getting thrown off the ground
+ if ( pm->ps->velocity[2] > 0 && DotProduct( pm->ps->velocity, trace.plane.normal ) > 10 ) {
+ if ( pm->debugLevel ) {
+ Com_Printf("%i:kickoff\n", c_pmove);
+ }
+ // go into jump animation
+ if ( pm->cmd.forwardmove >= 0 ) {
+ PM_ForceLegsAnim( LEGS_JUMP );
+ pm->ps->pm_flags &= ~PMF_BACKWARDS_JUMP;
+ } else {
+ PM_ForceLegsAnim( LEGS_JUMPB );
+ pm->ps->pm_flags |= PMF_BACKWARDS_JUMP;
+ }
+
+ pm->ps->groundEntityNum = ENTITYNUM_NONE;
+ pml.groundPlane = qfalse;
+ pml.walking = qfalse;
+ return;
+ }
+
+ // slopes that are too steep will not be considered onground
+ if ( trace.plane.normal[2] < MIN_WALK_NORMAL ) {
+ if ( pm->debugLevel ) {
+ Com_Printf("%i:steep\n", c_pmove);
+ }
+ // FIXME: if they can't slide down the slope, let them
+ // walk (sharp crevices)
+ pm->ps->groundEntityNum = ENTITYNUM_NONE;
+ pml.groundPlane = qtrue;
+ pml.walking = qfalse;
+ return;
+ }
+
+ pml.groundPlane = qtrue;
+ pml.walking = qtrue;
+
+ // hitting solid ground will end a waterjump
+ if (pm->ps->pm_flags & PMF_TIME_WATERJUMP)
+ {
+ pm->ps->pm_flags &= ~(PMF_TIME_WATERJUMP | PMF_TIME_LAND);
+ pm->ps->pm_time = 0;
+ }
+
+ if ( pm->ps->groundEntityNum == ENTITYNUM_NONE ) {
+ // just hit the ground
+ if ( pm->debugLevel ) {
+ Com_Printf("%i:Land\n", c_pmove);
+ }
+
+ PM_CrashLand();
+
+ // don't do landing time if we were just going down a slope
+ if ( pml.previous_velocity[2] < -200 ) {
+ // don't allow another jump for a little while
+ pm->ps->pm_flags |= PMF_TIME_LAND;
+ pm->ps->pm_time = 250;
+ }
+ }
+
+ pm->ps->groundEntityNum = trace.entityNum;
+
+ // don't reset the z velocity for slopes
+// pm->ps->velocity[2] = 0;
+
+ PM_AddTouchEnt( trace.entityNum );
+}
+
+
+/*
+=============
+PM_SetWaterLevel FIXME: avoid this twice? certainly if not moving
+=============
+*/
+static void PM_SetWaterLevel( void ) {
+ vec3_t point;
+ int cont;
+ int sample1;
+ int sample2;
+
+ //
+ // get waterlevel, accounting for ducking
+ //
+ pm->waterlevel = 0;
+ pm->watertype = 0;
+
+ point[0] = pm->ps->origin[0];
+ point[1] = pm->ps->origin[1];
+ point[2] = pm->ps->origin[2] + MINS_Z + 1;
+ cont = pm->pointcontents( point, pm->ps->clientNum );
+
+ if ( cont & MASK_WATER ) {
+ sample2 = pm->ps->viewheight - MINS_Z;
+ sample1 = sample2 / 2;
+
+ pm->watertype = cont;
+ pm->waterlevel = 1;
+ point[2] = pm->ps->origin[2] + MINS_Z + sample1;
+ cont = pm->pointcontents (point, pm->ps->clientNum );
+ if ( cont & MASK_WATER ) {
+ pm->waterlevel = 2;
+ point[2] = pm->ps->origin[2] + MINS_Z + sample2;
+ cont = pm->pointcontents (point, pm->ps->clientNum );
+ if ( cont & MASK_WATER ){
+ pm->waterlevel = 3;
+ }
+ }
+ }
+
+}
+
+/*
+==============
+PM_CheckDuck
+
+Sets mins, maxs, and pm->ps->viewheight
+==============
+*/
+static void PM_CheckDuck (void)
+{
+ trace_t trace;
+
+ if ( pm->ps->powerups[PW_INVULNERABILITY] ) {
+ if ( pm->ps->pm_flags & PMF_INVULEXPAND ) {
+ // invulnerability sphere has a 42 units radius
+ VectorSet( pm->mins, -42, -42, -42 );
+ VectorSet( pm->maxs, 42, 42, 42 );
+ }
+ else {
+ VectorSet( pm->mins, -15, -15, MINS_Z );
+ VectorSet( pm->maxs, 15, 15, 16 );
+ }
+ pm->ps->pm_flags |= PMF_DUCKED;
+ pm->ps->viewheight = CROUCH_VIEWHEIGHT;
+ return;
+ }
+ pm->ps->pm_flags &= ~PMF_INVULEXPAND;
+
+ pm->mins[0] = -15;
+ pm->mins[1] = -15;
+
+ pm->maxs[0] = 15;
+ pm->maxs[1] = 15;
+
+ pm->mins[2] = MINS_Z;
+
+ if (pm->ps->pm_type == PM_DEAD)
+ {
+ pm->maxs[2] = -8;
+ pm->ps->viewheight = DEAD_VIEWHEIGHT;
+ return;
+ }
+
+ if (pm->cmd.upmove < 0)
+ { // duck
+ pm->ps->pm_flags |= PMF_DUCKED;
+ }
+ else
+ { // stand up if possible
+ if (pm->ps->pm_flags & PMF_DUCKED)
+ {
+ // try to stand up
+ pm->maxs[2] = 32;
+ pm->trace (&trace, pm->ps->origin, pm->mins, pm->maxs, pm->ps->origin, pm->ps->clientNum, pm->tracemask );
+ if (!trace.allsolid)
+ pm->ps->pm_flags &= ~PMF_DUCKED;
+ }
+ }
+
+ if (pm->ps->pm_flags & PMF_DUCKED)
+ {
+ pm->maxs[2] = 16;
+ pm->ps->viewheight = CROUCH_VIEWHEIGHT;
+ }
+ else
+ {
+ pm->maxs[2] = 32;
+ pm->ps->viewheight = DEFAULT_VIEWHEIGHT;
+ }
+}
+
+
+
+//===================================================================
+
+
+/*
+===============
+PM_Footsteps
+===============
+*/
+static void PM_Footsteps( void ) {
+ float bobmove;
+ int old;
+ qboolean footstep;
+
+ //
+ // calculate speed and cycle to be used for
+ // all cyclic walking effects
+ //
+ pm->xyspeed = sqrt( pm->ps->velocity[0] * pm->ps->velocity[0]
+ + pm->ps->velocity[1] * pm->ps->velocity[1] );
+
+ if ( pm->ps->groundEntityNum == ENTITYNUM_NONE ) {
+
+ if ( pm->ps->powerups[PW_INVULNERABILITY] ) {
+ PM_ContinueLegsAnim( LEGS_IDLECR );
+ }
+ // airborne leaves position in cycle intact, but doesn't advance
+ if ( pm->waterlevel > 1 ) {
+ PM_ContinueLegsAnim( LEGS_SWIM );
+ }
+ return;
+ }
+
+ // if not trying to move
+ if ( !pm->cmd.forwardmove && !pm->cmd.rightmove ) {
+ if ( pm->xyspeed < 5 ) {
+ pm->ps->bobCycle = 0; // start at beginning of cycle again
+ if ( pm->ps->pm_flags & PMF_DUCKED ) {
+ PM_ContinueLegsAnim( LEGS_IDLECR );
+ } else {
+ PM_ContinueLegsAnim( LEGS_IDLE );
+ }
+ }
+ return;
+ }
+
+
+ footstep = qfalse;
+
+ if ( pm->ps->pm_flags & PMF_DUCKED ) {
+ bobmove = 0.5; // ducked characters bob much faster
+ if ( pm->ps->pm_flags & PMF_BACKWARDS_RUN ) {
+ PM_ContinueLegsAnim( LEGS_BACKCR );
+ }
+ else {
+ PM_ContinueLegsAnim( LEGS_WALKCR );
+ }
+ // ducked characters never play footsteps
+ /*
+ } else if ( pm->ps->pm_flags & PMF_BACKWARDS_RUN ) {
+ if ( !( pm->cmd.buttons & BUTTON_WALKING ) ) {
+ bobmove = 0.4; // faster speeds bob faster
+ footstep = qtrue;
+ } else {
+ bobmove = 0.3;
+ }
+ PM_ContinueLegsAnim( LEGS_BACK );
+ */
+ } else {
+ if ( !( pm->cmd.buttons & BUTTON_WALKING ) ) {
+ bobmove = 0.4f; // faster speeds bob faster
+ if ( pm->ps->pm_flags & PMF_BACKWARDS_RUN ) {
+ PM_ContinueLegsAnim( LEGS_BACK );
+ }
+ else {
+ PM_ContinueLegsAnim( LEGS_RUN );
+ }
+ footstep = qtrue;
+ } else {
+ bobmove = 0.3f; // walking bobs slow
+ if ( pm->ps->pm_flags & PMF_BACKWARDS_RUN ) {
+ PM_ContinueLegsAnim( LEGS_BACKWALK );
+ }
+ else {
+ PM_ContinueLegsAnim( LEGS_WALK );
+ }
+ }
+ }
+
+ // check for footstep / splash sounds
+ old = pm->ps->bobCycle;
+ pm->ps->bobCycle = (int)( old + bobmove * pml.msec ) & 255;
+
+ // if we just crossed a cycle boundary, play an apropriate footstep event
+ if ( ( ( old + 64 ) ^ ( pm->ps->bobCycle + 64 ) ) & 128 ) {
+ if ( pm->waterlevel == 0 ) {
+ // on ground will only play sounds if running
+ if ( footstep && !pm->noFootsteps ) {
+ PM_AddEvent( PM_FootstepForSurface() );
+ }
+ } else if ( pm->waterlevel == 1 ) {
+ // splashing
+ PM_AddEvent( EV_FOOTSPLASH );
+ } else if ( pm->waterlevel == 2 ) {
+ // wading / swimming at surface
+ PM_AddEvent( EV_SWIM );
+ } else if ( pm->waterlevel == 3 ) {
+ // no sound when completely underwater
+
+ }
+ }
+}
+
+/*
+==============
+PM_WaterEvents
+
+Generate sound events for entering and leaving water
+==============
+*/
+static void PM_WaterEvents( void ) { // FIXME?
+ //
+ // if just entered a water volume, play a sound
+ //
+ if (!pml.previous_waterlevel && pm->waterlevel) {
+ PM_AddEvent( EV_WATER_TOUCH );
+ }
+
+ //
+ // if just completely exited a water volume, play a sound
+ //
+ if (pml.previous_waterlevel && !pm->waterlevel) {
+ PM_AddEvent( EV_WATER_LEAVE );
+ }
+
+ //
+ // check for head just going under water
+ //
+ if (pml.previous_waterlevel != 3 && pm->waterlevel == 3) {
+ PM_AddEvent( EV_WATER_UNDER );
+ }
+
+ //
+ // check for head just coming out of water
+ //
+ if (pml.previous_waterlevel == 3 && pm->waterlevel != 3) {
+ PM_AddEvent( EV_WATER_CLEAR );
+ }
+}
+
+
+/*
+===============
+PM_BeginWeaponChange
+===============
+*/
+static void PM_BeginWeaponChange( int weapon ) {
+ if ( weapon <= WP_NONE || weapon >= WP_NUM_WEAPONS ) {
+ return;
+ }
+
+ if ( !( pm->ps->stats[STAT_WEAPONS] & ( 1 << weapon ) ) ) {
+ return;
+ }
+
+ if ( pm->ps->weaponstate == WEAPON_DROPPING ) {
+ return;
+ }
+
+ PM_AddEvent( EV_CHANGE_WEAPON );
+ pm->ps->weaponstate = WEAPON_DROPPING;
+ pm->ps->weaponTime += 200;
+ PM_StartTorsoAnim( TORSO_DROP );
+}
+
+
+/*
+===============
+PM_FinishWeaponChange
+===============
+*/
+static void PM_FinishWeaponChange( void ) {
+ int weapon;
+
+ weapon = pm->cmd.weapon;
+ if ( weapon < WP_NONE || weapon >= WP_NUM_WEAPONS ) {
+ weapon = WP_NONE;
+ }
+
+ if ( !( pm->ps->stats[STAT_WEAPONS] & ( 1 << weapon ) ) ) {
+ weapon = WP_NONE;
+ }
+
+ pm->ps->weapon = weapon;
+ pm->ps->weaponstate = WEAPON_RAISING;
+ pm->ps->weaponTime += 250;
+ PM_StartTorsoAnim( TORSO_RAISE );
+}
+
+
+/*
+==============
+PM_TorsoAnimation
+
+==============
+*/
+static void PM_TorsoAnimation( void ) {
+ if ( pm->ps->weaponstate == WEAPON_READY ) {
+ if ( pm->ps->weapon == WP_GAUNTLET ) {
+ PM_ContinueTorsoAnim( TORSO_STAND2 );
+ } else {
+ PM_ContinueTorsoAnim( TORSO_STAND );
+ }
+ return;
+ }
+}
+
+
+/*
+==============
+PM_Weapon
+
+Generates weapon events and modifes the weapon counter
+==============
+*/
+static void PM_Weapon( void ) {
+ int addTime;
+
+ // don't allow attack until all buttons are up
+ if ( pm->ps->pm_flags & PMF_RESPAWNED ) {
+ return;
+ }
+
+ // ignore if spectator
+ if ( pm->ps->persistant[PERS_TEAM] == TEAM_SPECTATOR ) {
+ return;
+ }
+
+ // check for dead player
+ if ( pm->ps->stats[STAT_HEALTH] <= 0 ) {
+ pm->ps->weapon = WP_NONE;
+ return;
+ }
+
+ // check for item using
+ if ( pm->cmd.buttons & BUTTON_USE_HOLDABLE ) {
+ if ( ! ( pm->ps->pm_flags & PMF_USE_ITEM_HELD ) ) {
+ if ( bg_itemlist[pm->ps->stats[STAT_HOLDABLE_ITEM]].giTag == HI_MEDKIT
+ && pm->ps->stats[STAT_HEALTH] >= (pm->ps->stats[STAT_MAX_HEALTH] + 25) ) {
+ // don't use medkit if at max health
+ } else {
+ pm->ps->pm_flags |= PMF_USE_ITEM_HELD;
+ PM_AddEvent( EV_USE_ITEM0 + bg_itemlist[pm->ps->stats[STAT_HOLDABLE_ITEM]].giTag );
+ pm->ps->stats[STAT_HOLDABLE_ITEM] = 0;
+ }
+ return;
+ }
+ } else {
+ pm->ps->pm_flags &= ~PMF_USE_ITEM_HELD;
+ }
+
+
+ // make weapon function
+ if ( pm->ps->weaponTime > 0 ) {
+ pm->ps->weaponTime -= pml.msec;
+ }
+
+ // check for weapon change
+ // can't change if weapon is firing, but can change
+ // again if lowering or raising
+ if ( pm->ps->weaponTime <= 0 || pm->ps->weaponstate != WEAPON_FIRING ) {
+ if ( pm->ps->weapon != pm->cmd.weapon ) {
+ PM_BeginWeaponChange( pm->cmd.weapon );
+ }
+ }
+
+ if ( pm->ps->weaponTime > 0 ) {
+ return;
+ }
+
+ // change weapon if time
+ if ( pm->ps->weaponstate == WEAPON_DROPPING ) {
+ PM_FinishWeaponChange();
+ return;
+ }
+
+ if ( pm->ps->weaponstate == WEAPON_RAISING ) {
+ pm->ps->weaponstate = WEAPON_READY;
+ if ( pm->ps->weapon == WP_GAUNTLET ) {
+ PM_StartTorsoAnim( TORSO_STAND2 );
+ } else {
+ PM_StartTorsoAnim( TORSO_STAND );
+ }
+ return;
+ }
+
+ // check for fire
+ if ( ! (pm->cmd.buttons & BUTTON_ATTACK) ) {
+ pm->ps->weaponTime = 0;
+ pm->ps->weaponstate = WEAPON_READY;
+ return;
+ }
+
+ // start the animation even if out of ammo
+ if ( pm->ps->weapon == WP_GAUNTLET ) {
+ // the guantlet only "fires" when it actually hits something
+ if ( !pm->gauntletHit ) {
+ pm->ps->weaponTime = 0;
+ pm->ps->weaponstate = WEAPON_READY;
+ return;
+ }
+ PM_StartTorsoAnim( TORSO_ATTACK2 );
+ } else {
+ PM_StartTorsoAnim( TORSO_ATTACK );
+ }
+
+ pm->ps->weaponstate = WEAPON_FIRING;
+
+ // check for out of ammo
+ if ( ! pm->ps->ammo[ pm->ps->weapon ] ) {
+ PM_AddEvent( EV_NOAMMO );
+ pm->ps->weaponTime += 500;
+ return;
+ }
+
+ // take an ammo away if not infinite
+ if ( pm->ps->ammo[ pm->ps->weapon ] != -1 ) {
+ pm->ps->ammo[ pm->ps->weapon ]--;
+ }
+
+ // fire weapon
+ PM_AddEvent( EV_FIRE_WEAPON );
+
+ switch( pm->ps->weapon ) {
+ default:
+ case WP_GAUNTLET:
+ addTime = 400;
+ break;
+ case WP_LIGHTNING:
+ addTime = 50;
+ break;
+ case WP_SHOTGUN:
+ addTime = 1000;
+ break;
+ case WP_MACHINEGUN:
+ addTime = 100;
+ break;
+ case WP_GRENADE_LAUNCHER:
+ addTime = 800;
+ break;
+ case WP_ROCKET_LAUNCHER:
+ addTime = 800;
+ break;
+ case WP_PLASMAGUN:
+ addTime = 100;
+ break;
+ case WP_RAILGUN:
+ addTime = 1500;
+ break;
+ case WP_BFG:
+ addTime = 200;
+ break;
+ case WP_GRAPPLING_HOOK:
+ addTime = 400;
+ break;
+#ifdef MISSIONPACK
+ case WP_NAILGUN:
+ addTime = 1000;
+ break;
+ case WP_PROX_LAUNCHER:
+ addTime = 800;
+ break;
+ case WP_CHAINGUN:
+ addTime = 30;
+ break;
+#endif
+ }
+
+#ifdef MISSIONPACK
+ if( bg_itemlist[pm->ps->stats[STAT_PERSISTANT_POWERUP]].giTag == PW_SCOUT ) {
+ addTime /= 1.5;
+ }
+ else
+ if( bg_itemlist[pm->ps->stats[STAT_PERSISTANT_POWERUP]].giTag == PW_AMMOREGEN ) {
+ addTime /= 1.3;
+ }
+ else
+#endif
+ if ( pm->ps->powerups[PW_HASTE] ) {
+ addTime /= 1.3;
+ }
+
+ pm->ps->weaponTime += addTime;
+}
+
+/*
+================
+PM_Animate
+================
+*/
+
+static void PM_Animate( void ) {
+ if ( pm->cmd.buttons & BUTTON_GESTURE ) {
+ if ( pm->ps->torsoTimer == 0 ) {
+ PM_StartTorsoAnim( TORSO_GESTURE );
+ pm->ps->torsoTimer = TIMER_GESTURE;
+ PM_AddEvent( EV_TAUNT );
+ }
+#ifdef MISSIONPACK
+ } else if ( pm->cmd.buttons & BUTTON_GETFLAG ) {
+ if ( pm->ps->torsoTimer == 0 ) {
+ PM_StartTorsoAnim( TORSO_GETFLAG );
+ pm->ps->torsoTimer = 600; //TIMER_GESTURE;
+ }
+ } else if ( pm->cmd.buttons & BUTTON_GUARDBASE ) {
+ if ( pm->ps->torsoTimer == 0 ) {
+ PM_StartTorsoAnim( TORSO_GUARDBASE );
+ pm->ps->torsoTimer = 600; //TIMER_GESTURE;
+ }
+ } else if ( pm->cmd.buttons & BUTTON_PATROL ) {
+ if ( pm->ps->torsoTimer == 0 ) {
+ PM_StartTorsoAnim( TORSO_PATROL );
+ pm->ps->torsoTimer = 600; //TIMER_GESTURE;
+ }
+ } else if ( pm->cmd.buttons & BUTTON_FOLLOWME ) {
+ if ( pm->ps->torsoTimer == 0 ) {
+ PM_StartTorsoAnim( TORSO_FOLLOWME );
+ pm->ps->torsoTimer = 600; //TIMER_GESTURE;
+ }
+ } else if ( pm->cmd.buttons & BUTTON_AFFIRMATIVE ) {
+ if ( pm->ps->torsoTimer == 0 ) {
+ PM_StartTorsoAnim( TORSO_AFFIRMATIVE);
+ pm->ps->torsoTimer = 600; //TIMER_GESTURE;
+ }
+ } else if ( pm->cmd.buttons & BUTTON_NEGATIVE ) {
+ if ( pm->ps->torsoTimer == 0 ) {
+ PM_StartTorsoAnim( TORSO_NEGATIVE );
+ pm->ps->torsoTimer = 600; //TIMER_GESTURE;
+ }
+#endif
+ }
+}
+
+
+/*
+================
+PM_DropTimers
+================
+*/
+static void PM_DropTimers( void ) {
+ // drop misc timing counter
+ if ( pm->ps->pm_time ) {
+ if ( pml.msec >= pm->ps->pm_time ) {
+ pm->ps->pm_flags &= ~PMF_ALL_TIMES;
+ pm->ps->pm_time = 0;
+ } else {
+ pm->ps->pm_time -= pml.msec;
+ }
+ }
+
+ // drop animation counter
+ if ( pm->ps->legsTimer > 0 ) {
+ pm->ps->legsTimer -= pml.msec;
+ if ( pm->ps->legsTimer < 0 ) {
+ pm->ps->legsTimer = 0;
+ }
+ }
+
+ if ( pm->ps->torsoTimer > 0 ) {
+ pm->ps->torsoTimer -= pml.msec;
+ if ( pm->ps->torsoTimer < 0 ) {
+ pm->ps->torsoTimer = 0;
+ }
+ }
+}
+
+/*
+================
+PM_UpdateViewAngles
+
+This can be used as another entry point when only the viewangles
+are being updated isntead of a full move
+================
+*/
+void PM_UpdateViewAngles( playerState_t *ps, const usercmd_t *cmd ) {
+ short temp;
+ int i;
+
+ if ( ps->pm_type == PM_INTERMISSION || ps->pm_type == PM_SPINTERMISSION) {
+ return; // no view changes at all
+ }
+
+ if ( ps->pm_type != PM_SPECTATOR && ps->stats[STAT_HEALTH] <= 0 ) {
+ return; // no view changes at all
+ }
+
+ // circularly clamp the angles with deltas
+ for (i=0 ; i<3 ; i++) {
+ temp = cmd->angles[i] + ps->delta_angles[i];
+ if ( i == PITCH ) {
+ // don't let the player look up or down more than 90 degrees
+ if ( temp > 16000 ) {
+ ps->delta_angles[i] = 16000 - cmd->angles[i];
+ temp = 16000;
+ } else if ( temp < -16000 ) {
+ ps->delta_angles[i] = -16000 - cmd->angles[i];
+ temp = -16000;
+ }
+ }
+ ps->viewangles[i] = SHORT2ANGLE(temp);
+ }
+
+}
+
+
+/*
+================
+PmoveSingle
+
+================
+*/
+void trap_SnapVector( float *v );
+
+void PmoveSingle (pmove_t *pmove) {
+ pm = pmove;
+
+ // this counter lets us debug movement problems with a journal
+ // by setting a conditional breakpoint fot the previous frame
+ c_pmove++;
+
+ // clear results
+ pm->numtouch = 0;
+ pm->watertype = 0;
+ pm->waterlevel = 0;
+
+ if ( pm->ps->stats[STAT_HEALTH] <= 0 ) {
+ pm->tracemask &= ~CONTENTS_BODY; // corpses can fly through bodies
+ }
+
+ // make sure walking button is clear if they are running, to avoid
+ // proxy no-footsteps cheats
+ if ( abs( pm->cmd.forwardmove ) > 64 || abs( pm->cmd.rightmove ) > 64 ) {
+ pm->cmd.buttons &= ~BUTTON_WALKING;
+ }
+
+ // set the talk balloon flag
+ if ( pm->cmd.buttons & BUTTON_TALK ) {
+ pm->ps->eFlags |= EF_TALK;
+ } else {
+ pm->ps->eFlags &= ~EF_TALK;
+ }
+
+ // set the firing flag for continuous beam weapons
+ if ( !(pm->ps->pm_flags & PMF_RESPAWNED) && pm->ps->pm_type != PM_INTERMISSION
+ && ( pm->cmd.buttons & BUTTON_ATTACK ) && pm->ps->ammo[ pm->ps->weapon ] ) {
+ pm->ps->eFlags |= EF_FIRING;
+ } else {
+ pm->ps->eFlags &= ~EF_FIRING;
+ }
+
+ // clear the respawned flag if attack and use are cleared
+ if ( pm->ps->stats[STAT_HEALTH] > 0 &&
+ !( pm->cmd.buttons & (BUTTON_ATTACK | BUTTON_USE_HOLDABLE) ) ) {
+ pm->ps->pm_flags &= ~PMF_RESPAWNED;
+ }
+
+ // if talk button is down, dissallow all other input
+ // this is to prevent any possible intercept proxy from
+ // adding fake talk balloons
+ if ( pmove->cmd.buttons & BUTTON_TALK ) {
+ // keep the talk button set tho for when the cmd.serverTime > 66 msec
+ // and the same cmd is used multiple times in Pmove
+ pmove->cmd.buttons = BUTTON_TALK;
+ pmove->cmd.forwardmove = 0;
+ pmove->cmd.rightmove = 0;
+ pmove->cmd.upmove = 0;
+ }
+
+ // clear all pmove local vars
+ memset (&pml, 0, sizeof(pml));
+
+ // determine the time
+ pml.msec = pmove->cmd.serverTime - pm->ps->commandTime;
+ if ( pml.msec < 1 ) {
+ pml.msec = 1;
+ } else if ( pml.msec > 200 ) {
+ pml.msec = 200;
+ }
+ pm->ps->commandTime = pmove->cmd.serverTime;
+
+ // save old org in case we get stuck
+ VectorCopy (pm->ps->origin, pml.previous_origin);
+
+ // save old velocity for crashlanding
+ VectorCopy (pm->ps->velocity, pml.previous_velocity);
+
+ pml.frametime = pml.msec * 0.001;
+
+ // update the viewangles
+ PM_UpdateViewAngles( pm->ps, &pm->cmd );
+
+ AngleVectors (pm->ps->viewangles, pml.forward, pml.right, pml.up);
+
+ if ( pm->cmd.upmove < 10 ) {
+ // not holding jump
+ pm->ps->pm_flags &= ~PMF_JUMP_HELD;
+ }
+
+ // decide if backpedaling animations should be used
+ if ( pm->cmd.forwardmove < 0 ) {
+ pm->ps->pm_flags |= PMF_BACKWARDS_RUN;
+ } else if ( pm->cmd.forwardmove > 0 || ( pm->cmd.forwardmove == 0 && pm->cmd.rightmove ) ) {
+ pm->ps->pm_flags &= ~PMF_BACKWARDS_RUN;
+ }
+
+ if ( pm->ps->pm_type >= PM_DEAD ) {
+ pm->cmd.forwardmove = 0;
+ pm->cmd.rightmove = 0;
+ pm->cmd.upmove = 0;
+ }
+
+ if ( pm->ps->pm_type == PM_SPECTATOR ) {
+ PM_CheckDuck ();
+ PM_FlyMove ();
+ PM_DropTimers ();
+ return;
+ }
+
+ if ( pm->ps->pm_type == PM_NOCLIP ) {
+ PM_NoclipMove ();
+ PM_DropTimers ();
+ return;
+ }
+
+ if (pm->ps->pm_type == PM_FREEZE) {
+ return; // no movement at all
+ }
+
+ if ( pm->ps->pm_type == PM_INTERMISSION || pm->ps->pm_type == PM_SPINTERMISSION) {
+ return; // no movement at all
+ }
+
+ // set watertype, and waterlevel
+ PM_SetWaterLevel();
+ pml.previous_waterlevel = pmove->waterlevel;
+
+ // set mins, maxs, and viewheight
+ PM_CheckDuck ();
+
+ // set groundentity
+ PM_GroundTrace();
+
+ if ( pm->ps->pm_type == PM_DEAD ) {
+ PM_DeadMove ();
+ }
+
+ PM_DropTimers();
+
+#ifdef MISSIONPACK
+ if ( pm->ps->powerups[PW_INVULNERABILITY] ) {
+ PM_InvulnerabilityMove();
+ } else
+#endif
+ if ( pm->ps->powerups[PW_FLIGHT] ) {
+ // flight powerup doesn't allow jump and has different friction
+ PM_FlyMove();
+ } else if (pm->ps->pm_flags & PMF_GRAPPLE_PULL) {
+ PM_GrappleMove();
+ // We can wiggle a bit
+ PM_AirMove();
+ } else if (pm->ps->pm_flags & PMF_TIME_WATERJUMP) {
+ PM_WaterJumpMove();
+ } else if ( pm->waterlevel > 1 ) {
+ // swimming
+ PM_WaterMove();
+ } else if ( pml.walking ) {
+ // walking on ground
+ PM_WalkMove();
+ } else {
+ // airborne
+ PM_AirMove();
+ }
+
+ PM_Animate();
+
+ // set groundentity, watertype, and waterlevel
+ PM_GroundTrace();
+ PM_SetWaterLevel();
+
+ // weapons
+ PM_Weapon();
+
+ // torso animation
+ PM_TorsoAnimation();
+
+ // footstep events / legs animations
+ PM_Footsteps();
+
+ // entering / leaving water splashes
+ PM_WaterEvents();
+
+ // snap some parts of playerstate to save network bandwidth
+ trap_SnapVector( pm->ps->velocity );
+}
+
+
+/*
+================
+Pmove
+
+Can be called by either the server or the client
+================
+*/
+void Pmove (pmove_t *pmove) {
+ int finalTime;
+
+ finalTime = pmove->cmd.serverTime;
+
+ if ( finalTime < pmove->ps->commandTime ) {
+ return; // should not happen
+ }
+
+ if ( finalTime > pmove->ps->commandTime + 1000 ) {
+ pmove->ps->commandTime = finalTime - 1000;
+ }
+
+ pmove->ps->pmove_framecount = (pmove->ps->pmove_framecount+1) & ((1<<PS_PMOVEFRAMECOUNTBITS)-1);
+
+ // chop the move up if it is too long, to prevent framerate
+ // dependent behavior
+ while ( pmove->ps->commandTime != finalTime ) {
+ int msec;
+
+ msec = finalTime - pmove->ps->commandTime;
+
+ if ( pmove->pmove_fixed ) {
+ if ( msec > pmove->pmove_msec ) {
+ msec = pmove->pmove_msec;
+ }
+ }
+ else {
+ if ( msec > 66 ) {
+ msec = 66;
+ }
+ }
+ pmove->cmd.serverTime = pmove->ps->commandTime + msec;
+ PmoveSingle( pmove );
+
+ if ( pmove->ps->pm_flags & PMF_JUMP_HELD ) {
+ pmove->cmd.upmove = 20;
+ }
+ }
+
+ //PM_CheckStuck();
+
+}
+
diff --git a/code/game/bg_public.h b/code/game/bg_public.h
new file mode 100755
index 0000000..0dd59db
--- /dev/null
+++ b/code/game/bg_public.h
@@ -0,0 +1,738 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// bg_public.h -- definitions shared by both the server game and client game modules
+
+// because games can change separately from the main system version, we need a
+// second version that must match between game and cgame
+
+#define GAME_VERSION "baseq3-1"
+
+#define DEFAULT_GRAVITY 800
+#define GIB_HEALTH -40
+#define ARMOR_PROTECTION 0.66
+
+#define MAX_ITEMS 256
+
+#define RANK_TIED_FLAG 0x4000
+
+#define DEFAULT_SHOTGUN_SPREAD 700
+#define DEFAULT_SHOTGUN_COUNT 11
+
+#define ITEM_RADIUS 15 // item sizes are needed for client side pickup detection
+
+#define LIGHTNING_RANGE 768
+
+#define SCORE_NOT_PRESENT -9999 // for the CS_SCORES[12] when only one player is present
+
+#define VOTE_TIME 30000 // 30 seconds before vote times out
+
+#define MINS_Z -24
+#define DEFAULT_VIEWHEIGHT 26
+#define CROUCH_VIEWHEIGHT 12
+#define DEAD_VIEWHEIGHT -16
+
+//
+// config strings are a general means of communicating variable length strings
+// from the server to all connected clients.
+//
+
+// CS_SERVERINFO and CS_SYSTEMINFO are defined in q_shared.h
+#define CS_MUSIC 2
+#define CS_MESSAGE 3 // from the map worldspawn's message field
+#define CS_MOTD 4 // g_motd string for server message of the day
+#define CS_WARMUP 5 // server time when the match will be restarted
+#define CS_SCORES1 6
+#define CS_SCORES2 7
+#define CS_VOTE_TIME 8
+#define CS_VOTE_STRING 9
+#define CS_VOTE_YES 10
+#define CS_VOTE_NO 11
+
+#define CS_TEAMVOTE_TIME 12
+#define CS_TEAMVOTE_STRING 14
+#define CS_TEAMVOTE_YES 16
+#define CS_TEAMVOTE_NO 18
+
+#define CS_GAME_VERSION 20
+#define CS_LEVEL_START_TIME 21 // so the timer only shows the current level
+#define CS_INTERMISSION 22 // when 1, fraglimit/timelimit has been hit and intermission will start in a second or two
+#define CS_FLAGSTATUS 23 // string indicating flag status in CTF
+#define CS_SHADERSTATE 24
+#define CS_BOTINFO 25
+
+#define CS_ITEMS 27 // string of 0's and 1's that tell which items are present
+
+#define CS_MODELS 32
+#define CS_SOUNDS (CS_MODELS+MAX_MODELS)
+#define CS_PLAYERS (CS_SOUNDS+MAX_SOUNDS)
+#define CS_LOCATIONS (CS_PLAYERS+MAX_CLIENTS)
+#define CS_PARTICLES (CS_LOCATIONS+MAX_LOCATIONS)
+
+#define CS_MAX (CS_PARTICLES+MAX_LOCATIONS)
+
+#if (CS_MAX) > MAX_CONFIGSTRINGS
+#error overflow: (CS_MAX) > MAX_CONFIGSTRINGS
+#endif
+
+typedef enum {
+ GT_FFA, // free for all
+ GT_TOURNAMENT, // one on one tournament
+ GT_SINGLE_PLAYER, // single player ffa
+
+ //-- team games go after this --
+
+ GT_TEAM, // team deathmatch
+ GT_CTF, // capture the flag
+ GT_1FCTF,
+ GT_OBELISK,
+ GT_HARVESTER,
+ GT_MAX_GAME_TYPE
+} gametype_t;
+
+typedef enum { GENDER_MALE, GENDER_FEMALE, GENDER_NEUTER } gender_t;
+
+/*
+===================================================================================
+
+PMOVE MODULE
+
+The pmove code takes a player_state_t and a usercmd_t and generates a new player_state_t
+and some other output data. Used for local prediction on the client game and true
+movement on the server game.
+===================================================================================
+*/
+
+typedef enum {
+ PM_NORMAL, // can accelerate and turn
+ PM_NOCLIP, // noclip movement
+ PM_SPECTATOR, // still run into walls
+ PM_DEAD, // no acceleration or turning, but free falling
+ PM_FREEZE, // stuck in place with no control
+ PM_INTERMISSION, // no movement or status bar
+ PM_SPINTERMISSION // no movement or status bar
+} pmtype_t;
+
+typedef enum {
+ WEAPON_READY,
+ WEAPON_RAISING,
+ WEAPON_DROPPING,
+ WEAPON_FIRING
+} weaponstate_t;
+
+// pmove->pm_flags
+#define PMF_DUCKED 1
+#define PMF_JUMP_HELD 2
+#define PMF_BACKWARDS_JUMP 8 // go into backwards land
+#define PMF_BACKWARDS_RUN 16 // coast down to backwards run
+#define PMF_TIME_LAND 32 // pm_time is time before rejump
+#define PMF_TIME_KNOCKBACK 64 // pm_time is an air-accelerate only time
+#define PMF_TIME_WATERJUMP 256 // pm_time is waterjump
+#define PMF_RESPAWNED 512 // clear after attack and jump buttons come up
+#define PMF_USE_ITEM_HELD 1024
+#define PMF_GRAPPLE_PULL 2048 // pull towards grapple location
+#define PMF_FOLLOW 4096 // spectate following another player
+#define PMF_SCOREBOARD 8192 // spectate as a scoreboard
+#define PMF_INVULEXPAND 16384 // invulnerability sphere set to full size
+
+#define PMF_ALL_TIMES (PMF_TIME_WATERJUMP|PMF_TIME_LAND|PMF_TIME_KNOCKBACK)
+
+#define MAXTOUCH 32
+typedef struct {
+ // state (in / out)
+ playerState_t *ps;
+
+ // command (in)
+ usercmd_t cmd;
+ int tracemask; // collide against these types of surfaces
+ int debugLevel; // if set, diagnostic output will be printed
+ qboolean noFootsteps; // if the game is setup for no footsteps by the server
+ qboolean gauntletHit; // true if a gauntlet attack would actually hit something
+
+ int framecount;
+
+ // results (out)
+ int numtouch;
+ int touchents[MAXTOUCH];
+
+ vec3_t mins, maxs; // bounding box size
+
+ int watertype;
+ int waterlevel;
+
+ float xyspeed;
+
+ // for fixed msec Pmove
+ int pmove_fixed;
+ int pmove_msec;
+
+ // callbacks to test the world
+ // these will be different functions during game and cgame
+ void (*trace)( trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentMask );
+ int (*pointcontents)( const vec3_t point, int passEntityNum );
+} pmove_t;
+
+// if a full pmove isn't done on the client, you can just update the angles
+void PM_UpdateViewAngles( playerState_t *ps, const usercmd_t *cmd );
+void Pmove (pmove_t *pmove);
+
+//===================================================================================
+
+
+// player_state->stats[] indexes
+// NOTE: may not have more than 16
+typedef enum {
+ STAT_HEALTH,
+ STAT_HOLDABLE_ITEM,
+#ifdef MISSIONPACK
+ STAT_PERSISTANT_POWERUP,
+#endif
+ STAT_WEAPONS, // 16 bit fields
+ STAT_ARMOR,
+ STAT_DEAD_YAW, // look this direction when dead (FIXME: get rid of?)
+ STAT_CLIENTS_READY, // bit mask of clients wishing to exit the intermission (FIXME: configstring?)
+ STAT_MAX_HEALTH // health / armor limit, changable by handicap
+} statIndex_t;
+
+
+// player_state->persistant[] indexes
+// these fields are the only part of player_state that isn't
+// cleared on respawn
+// NOTE: may not have more than 16
+typedef enum {
+ PERS_SCORE, // !!! MUST NOT CHANGE, SERVER AND GAME BOTH REFERENCE !!!
+ PERS_HITS, // total points damage inflicted so damage beeps can sound on change
+ PERS_RANK, // player rank or team rank
+ PERS_TEAM, // player team
+ PERS_SPAWN_COUNT, // incremented every respawn
+ PERS_PLAYEREVENTS, // 16 bits that can be flipped for events
+ PERS_ATTACKER, // clientnum of last damage inflicter
+ PERS_ATTACKEE_ARMOR, // health/armor of last person we attacked
+ PERS_KILLED, // count of the number of times you died
+ // player awards tracking
+ PERS_IMPRESSIVE_COUNT, // two railgun hits in a row
+ PERS_EXCELLENT_COUNT, // two successive kills in a short amount of time
+ PERS_DEFEND_COUNT, // defend awards
+ PERS_ASSIST_COUNT, // assist awards
+ PERS_GAUNTLET_FRAG_COUNT, // kills with the guantlet
+ PERS_CAPTURES // captures
+} persEnum_t;
+
+
+// entityState_t->eFlags
+#define EF_DEAD 0x00000001 // don't draw a foe marker over players with EF_DEAD
+#ifdef MISSIONPACK
+#define EF_TICKING 0x00000002 // used to make players play the prox mine ticking sound
+#endif
+#define EF_TELEPORT_BIT 0x00000004 // toggled every time the origin abruptly changes
+#define EF_AWARD_EXCELLENT 0x00000008 // draw an excellent sprite
+#define EF_PLAYER_EVENT 0x00000010
+#define EF_BOUNCE 0x00000010 // for missiles
+#define EF_BOUNCE_HALF 0x00000020 // for missiles
+#define EF_AWARD_GAUNTLET 0x00000040 // draw a gauntlet sprite
+#define EF_NODRAW 0x00000080 // may have an event, but no model (unspawned items)
+#define EF_FIRING 0x00000100 // for lightning gun
+#define EF_KAMIKAZE 0x00000200
+#define EF_MOVER_STOP 0x00000400 // will push otherwise
+#define EF_AWARD_CAP 0x00000800 // draw the capture sprite
+#define EF_TALK 0x00001000 // draw a talk balloon
+#define EF_CONNECTION 0x00002000 // draw a connection trouble sprite
+#define EF_VOTED 0x00004000 // already cast a vote
+#define EF_AWARD_IMPRESSIVE 0x00008000 // draw an impressive sprite
+#define EF_AWARD_DEFEND 0x00010000 // draw a defend sprite
+#define EF_AWARD_ASSIST 0x00020000 // draw a assist sprite
+#define EF_AWARD_DENIED 0x00040000 // denied
+#define EF_TEAMVOTED 0x00080000 // already cast a team vote
+
+// NOTE: may not have more than 16
+typedef enum {
+ PW_NONE,
+
+ PW_QUAD,
+ PW_BATTLESUIT,
+ PW_HASTE,
+ PW_INVIS,
+ PW_REGEN,
+ PW_FLIGHT,
+
+ PW_REDFLAG,
+ PW_BLUEFLAG,
+ PW_NEUTRALFLAG,
+
+ PW_SCOUT,
+ PW_GUARD,
+ PW_DOUBLER,
+ PW_AMMOREGEN,
+ PW_INVULNERABILITY,
+
+ PW_NUM_POWERUPS
+
+} powerup_t;
+
+typedef enum {
+ HI_NONE,
+
+ HI_TELEPORTER,
+ HI_MEDKIT,
+ HI_KAMIKAZE,
+ HI_PORTAL,
+ HI_INVULNERABILITY,
+
+ HI_NUM_HOLDABLE
+} holdable_t;
+
+
+typedef enum {
+ WP_NONE,
+
+ WP_GAUNTLET,
+ WP_MACHINEGUN,
+ WP_SHOTGUN,
+ WP_GRENADE_LAUNCHER,
+ WP_ROCKET_LAUNCHER,
+ WP_LIGHTNING,
+ WP_RAILGUN,
+ WP_PLASMAGUN,
+ WP_BFG,
+ WP_GRAPPLING_HOOK,
+#ifdef MISSIONPACK
+ WP_NAILGUN,
+ WP_PROX_LAUNCHER,
+ WP_CHAINGUN,
+#endif
+
+ WP_NUM_WEAPONS
+} weapon_t;
+
+
+// reward sounds (stored in ps->persistant[PERS_PLAYEREVENTS])
+#define PLAYEREVENT_DENIEDREWARD 0x0001
+#define PLAYEREVENT_GAUNTLETREWARD 0x0002
+#define PLAYEREVENT_HOLYSHIT 0x0004
+
+// entityState_t->event values
+// entity events are for effects that take place reletive
+// to an existing entities origin. Very network efficient.
+
+// two bits at the top of the entityState->event field
+// will be incremented with each change in the event so
+// that an identical event started twice in a row can
+// be distinguished. And off the value with ~EV_EVENT_BITS
+// to retrieve the actual event number
+#define EV_EVENT_BIT1 0x00000100
+#define EV_EVENT_BIT2 0x00000200
+#define EV_EVENT_BITS (EV_EVENT_BIT1|EV_EVENT_BIT2)
+
+#define EVENT_VALID_MSEC 300
+
+typedef enum {
+ EV_NONE,
+
+ EV_FOOTSTEP,
+ EV_FOOTSTEP_METAL,
+ EV_FOOTSPLASH,
+ EV_FOOTWADE,
+ EV_SWIM,
+
+ EV_STEP_4,
+ EV_STEP_8,
+ EV_STEP_12,
+ EV_STEP_16,
+
+ EV_FALL_SHORT,
+ EV_FALL_MEDIUM,
+ EV_FALL_FAR,
+
+ EV_JUMP_PAD, // boing sound at origin, jump sound on player
+
+ EV_JUMP,
+ EV_WATER_TOUCH, // foot touches
+ EV_WATER_LEAVE, // foot leaves
+ EV_WATER_UNDER, // head touches
+ EV_WATER_CLEAR, // head leaves
+
+ EV_ITEM_PICKUP, // normal item pickups are predictable
+ EV_GLOBAL_ITEM_PICKUP, // powerup / team sounds are broadcast to everyone
+
+ EV_NOAMMO,
+ EV_CHANGE_WEAPON,
+ EV_FIRE_WEAPON,
+
+ EV_USE_ITEM0,
+ EV_USE_ITEM1,
+ EV_USE_ITEM2,
+ EV_USE_ITEM3,
+ EV_USE_ITEM4,
+ EV_USE_ITEM5,
+ EV_USE_ITEM6,
+ EV_USE_ITEM7,
+ EV_USE_ITEM8,
+ EV_USE_ITEM9,
+ EV_USE_ITEM10,
+ EV_USE_ITEM11,
+ EV_USE_ITEM12,
+ EV_USE_ITEM13,
+ EV_USE_ITEM14,
+ EV_USE_ITEM15,
+
+ EV_ITEM_RESPAWN,
+ EV_ITEM_POP,
+ EV_PLAYER_TELEPORT_IN,
+ EV_PLAYER_TELEPORT_OUT,
+
+ EV_GRENADE_BOUNCE, // eventParm will be the soundindex
+
+ EV_GENERAL_SOUND,
+ EV_GLOBAL_SOUND, // no attenuation
+ EV_GLOBAL_TEAM_SOUND,
+
+ EV_BULLET_HIT_FLESH,
+ EV_BULLET_HIT_WALL,
+
+ EV_MISSILE_HIT,
+ EV_MISSILE_MISS,
+ EV_MISSILE_MISS_METAL,
+ EV_RAILTRAIL,
+ EV_SHOTGUN,
+ EV_BULLET, // otherEntity is the shooter
+
+ EV_PAIN,
+ EV_DEATH1,
+ EV_DEATH2,
+ EV_DEATH3,
+ EV_OBITUARY,
+
+ EV_POWERUP_QUAD,
+ EV_POWERUP_BATTLESUIT,
+ EV_POWERUP_REGEN,
+
+ EV_GIB_PLAYER, // gib a previously living player
+ EV_SCOREPLUM, // score plum
+
+//#ifdef MISSIONPACK
+ EV_PROXIMITY_MINE_STICK,
+ EV_PROXIMITY_MINE_TRIGGER,
+ EV_KAMIKAZE, // kamikaze explodes
+ EV_OBELISKEXPLODE, // obelisk explodes
+ EV_OBELISKPAIN, // obelisk is in pain
+ EV_INVUL_IMPACT, // invulnerability sphere impact
+ EV_JUICED, // invulnerability juiced effect
+ EV_LIGHTNINGBOLT, // lightning bolt bounced of invulnerability sphere
+//#endif
+
+ EV_DEBUG_LINE,
+ EV_STOPLOOPINGSOUND,
+ EV_TAUNT,
+ EV_TAUNT_YES,
+ EV_TAUNT_NO,
+ EV_TAUNT_FOLLOWME,
+ EV_TAUNT_GETFLAG,
+ EV_TAUNT_GUARDBASE,
+ EV_TAUNT_PATROL
+
+} entity_event_t;
+
+
+typedef enum {
+ GTS_RED_CAPTURE,
+ GTS_BLUE_CAPTURE,
+ GTS_RED_RETURN,
+ GTS_BLUE_RETURN,
+ GTS_RED_TAKEN,
+ GTS_BLUE_TAKEN,
+ GTS_REDOBELISK_ATTACKED,
+ GTS_BLUEOBELISK_ATTACKED,
+ GTS_REDTEAM_SCORED,
+ GTS_BLUETEAM_SCORED,
+ GTS_REDTEAM_TOOK_LEAD,
+ GTS_BLUETEAM_TOOK_LEAD,
+ GTS_TEAMS_ARE_TIED,
+ GTS_KAMIKAZE
+} global_team_sound_t;
+
+// animations
+typedef enum {
+ BOTH_DEATH1,
+ BOTH_DEAD1,
+ BOTH_DEATH2,
+ BOTH_DEAD2,
+ BOTH_DEATH3,
+ BOTH_DEAD3,
+
+ TORSO_GESTURE,
+
+ TORSO_ATTACK,
+ TORSO_ATTACK2,
+
+ TORSO_DROP,
+ TORSO_RAISE,
+
+ TORSO_STAND,
+ TORSO_STAND2,
+
+ LEGS_WALKCR,
+ LEGS_WALK,
+ LEGS_RUN,
+ LEGS_BACK,
+ LEGS_SWIM,
+
+ LEGS_JUMP,
+ LEGS_LAND,
+
+ LEGS_JUMPB,
+ LEGS_LANDB,
+
+ LEGS_IDLE,
+ LEGS_IDLECR,
+
+ LEGS_TURN,
+
+ TORSO_GETFLAG,
+ TORSO_GUARDBASE,
+ TORSO_PATROL,
+ TORSO_FOLLOWME,
+ TORSO_AFFIRMATIVE,
+ TORSO_NEGATIVE,
+
+ MAX_ANIMATIONS,
+
+ LEGS_BACKCR,
+ LEGS_BACKWALK,
+ FLAG_RUN,
+ FLAG_STAND,
+ FLAG_STAND2RUN,
+
+ MAX_TOTALANIMATIONS
+} animNumber_t;
+
+
+typedef struct animation_s {
+ int firstFrame;
+ int numFrames;
+ int loopFrames; // 0 to numFrames
+ int frameLerp; // msec between frames
+ int initialLerp; // msec to get to first frame
+ int reversed; // true if animation is reversed
+ int flipflop; // true if animation should flipflop back to base
+} animation_t;
+
+
+// flip the togglebit every time an animation
+// changes so a restart of the same anim can be detected
+#define ANIM_TOGGLEBIT 128
+
+
+typedef enum {
+ TEAM_FREE,
+ TEAM_RED,
+ TEAM_BLUE,
+ TEAM_SPECTATOR,
+
+ TEAM_NUM_TEAMS
+} team_t;
+
+// Time between location updates
+#define TEAM_LOCATION_UPDATE_TIME 1000
+
+// How many players on the overlay
+#define TEAM_MAXOVERLAY 32
+
+//team task
+typedef enum {
+ TEAMTASK_NONE,
+ TEAMTASK_OFFENSE,
+ TEAMTASK_DEFENSE,
+ TEAMTASK_PATROL,
+ TEAMTASK_FOLLOW,
+ TEAMTASK_RETRIEVE,
+ TEAMTASK_ESCORT,
+ TEAMTASK_CAMP
+} teamtask_t;
+
+// means of death
+typedef enum {
+ MOD_UNKNOWN,
+ MOD_SHOTGUN,
+ MOD_GAUNTLET,
+ MOD_MACHINEGUN,
+ MOD_GRENADE,
+ MOD_GRENADE_SPLASH,
+ MOD_ROCKET,
+ MOD_ROCKET_SPLASH,
+ MOD_PLASMA,
+ MOD_PLASMA_SPLASH,
+ MOD_RAILGUN,
+ MOD_LIGHTNING,
+ MOD_BFG,
+ MOD_BFG_SPLASH,
+ MOD_WATER,
+ MOD_SLIME,
+ MOD_LAVA,
+ MOD_CRUSH,
+ MOD_TELEFRAG,
+ MOD_FALLING,
+ MOD_SUICIDE,
+ MOD_TARGET_LASER,
+ MOD_TRIGGER_HURT,
+#ifdef MISSIONPACK
+ MOD_NAIL,
+ MOD_CHAINGUN,
+ MOD_PROXIMITY_MINE,
+ MOD_KAMIKAZE,
+ MOD_JUICED,
+#endif
+ MOD_GRAPPLE
+} meansOfDeath_t;
+
+
+//---------------------------------------------------------
+
+// gitem_t->type
+typedef enum {
+ IT_BAD,
+ IT_WEAPON, // EFX: rotate + upscale + minlight
+ IT_AMMO, // EFX: rotate
+ IT_ARMOR, // EFX: rotate + minlight
+ IT_HEALTH, // EFX: static external sphere + rotating internal
+ IT_POWERUP, // instant on, timer based
+ // EFX: rotate + external ring that rotates
+ IT_HOLDABLE, // single use, holdable item
+ // EFX: rotate + bob
+ IT_PERSISTANT_POWERUP,
+ IT_TEAM
+} itemType_t;
+
+#define MAX_ITEM_MODELS 4
+
+typedef struct gitem_s {
+ char *classname; // spawning name
+ char *pickup_sound;
+ char *world_model[MAX_ITEM_MODELS];
+
+ char *icon;
+ char *pickup_name; // for printing on pickup
+
+ int quantity; // for ammo how much, or duration of powerup
+ itemType_t giType; // IT_* flags
+
+ int giTag;
+
+ char *precaches; // string of all models and images this item will use
+ char *sounds; // string of all sounds this item will use
+} gitem_t;
+
+// included in both the game dll and the client
+extern gitem_t bg_itemlist[];
+extern int bg_numItems;
+
+gitem_t *BG_FindItem( const char *pickupName );
+gitem_t *BG_FindItemForWeapon( weapon_t weapon );
+gitem_t *BG_FindItemForPowerup( powerup_t pw );
+gitem_t *BG_FindItemForHoldable( holdable_t pw );
+#define ITEM_INDEX(x) ((x)-bg_itemlist)
+
+qboolean BG_CanItemBeGrabbed( int gametype, const entityState_t *ent, const playerState_t *ps );
+
+
+// g_dmflags->integer flags
+#define DF_NO_FALLING 8
+#define DF_FIXED_FOV 16
+#define DF_NO_FOOTSTEPS 32
+
+// content masks
+#define MASK_ALL (-1)
+#define MASK_SOLID (CONTENTS_SOLID)
+#define MASK_PLAYERSOLID (CONTENTS_SOLID|CONTENTS_PLAYERCLIP|CONTENTS_BODY)
+#define MASK_DEADSOLID (CONTENTS_SOLID|CONTENTS_PLAYERCLIP)
+#define MASK_WATER (CONTENTS_WATER|CONTENTS_LAVA|CONTENTS_SLIME)
+#define MASK_OPAQUE (CONTENTS_SOLID|CONTENTS_SLIME|CONTENTS_LAVA)
+#define MASK_SHOT (CONTENTS_SOLID|CONTENTS_BODY|CONTENTS_CORPSE)
+
+
+//
+// entityState_t->eType
+//
+typedef enum {
+ ET_GENERAL,
+ ET_PLAYER,
+ ET_ITEM,
+ ET_MISSILE,
+ ET_MOVER,
+ ET_BEAM,
+ ET_PORTAL,
+ ET_SPEAKER,
+ ET_PUSH_TRIGGER,
+ ET_TELEPORT_TRIGGER,
+ ET_INVISIBLE,
+ ET_GRAPPLE, // grapple hooked on wall
+ ET_TEAM,
+
+ ET_EVENTS // any of the EV_* events can be added freestanding
+ // by setting eType to ET_EVENTS + eventNum
+ // this avoids having to set eFlags and eventNum
+} entityType_t;
+
+
+
+void BG_EvaluateTrajectory( const trajectory_t *tr, int atTime, vec3_t result );
+void BG_EvaluateTrajectoryDelta( const trajectory_t *tr, int atTime, vec3_t result );
+
+void BG_AddPredictableEventToPlayerstate( int newEvent, int eventParm, playerState_t *ps );
+
+void BG_TouchJumpPad( playerState_t *ps, entityState_t *jumppad );
+
+void BG_PlayerStateToEntityState( playerState_t *ps, entityState_t *s, qboolean snap );
+void BG_PlayerStateToEntityStateExtraPolate( playerState_t *ps, entityState_t *s, int time, qboolean snap );
+
+qboolean BG_PlayerTouchesItem( playerState_t *ps, entityState_t *item, int atTime );
+
+
+#define ARENAS_PER_TIER 4
+#define MAX_ARENAS 1024
+#define MAX_ARENAS_TEXT 8192
+
+#define MAX_BOTS 1024
+#define MAX_BOTS_TEXT 8192
+
+
+// Kamikaze
+
+// 1st shockwave times
+#define KAMI_SHOCKWAVE_STARTTIME 0
+#define KAMI_SHOCKWAVEFADE_STARTTIME 1500
+#define KAMI_SHOCKWAVE_ENDTIME 2000
+// explosion/implosion times
+#define KAMI_EXPLODE_STARTTIME 250
+#define KAMI_IMPLODE_STARTTIME 2000
+#define KAMI_IMPLODE_ENDTIME 2250
+// 2nd shockwave times
+#define KAMI_SHOCKWAVE2_STARTTIME 2000
+#define KAMI_SHOCKWAVE2FADE_STARTTIME 2500
+#define KAMI_SHOCKWAVE2_ENDTIME 3000
+// radius of the models without scaling
+#define KAMI_SHOCKWAVEMODEL_RADIUS 88
+#define KAMI_BOOMSPHEREMODEL_RADIUS 72
+// maximum radius of the models during the effect
+#define KAMI_SHOCKWAVE_MAXRADIUS 1320
+#define KAMI_BOOMSPHERE_MAXRADIUS 720
+#define KAMI_SHOCKWAVE2_MAXRADIUS 704
+
diff --git a/code/game/bg_slidemove.c b/code/game/bg_slidemove.c
new file mode 100755
index 0000000..ed1349f
--- /dev/null
+++ b/code/game/bg_slidemove.c
@@ -0,0 +1,325 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// bg_slidemove.c -- part of bg_pmove functionality
+
+#include "q_shared.h"
+#include "bg_public.h"
+#include "bg_local.h"
+
+/*
+
+input: origin, velocity, bounds, groundPlane, trace function
+
+output: origin, velocity, impacts, stairup boolean
+
+*/
+
+/*
+==================
+PM_SlideMove
+
+Returns qtrue if the velocity was clipped in some way
+==================
+*/
+#define MAX_CLIP_PLANES 5
+qboolean PM_SlideMove( qboolean gravity ) {
+ int bumpcount, numbumps;
+ vec3_t dir;
+ float d;
+ int numplanes;
+ vec3_t planes[MAX_CLIP_PLANES];
+ vec3_t primal_velocity;
+ vec3_t clipVelocity;
+ int i, j, k;
+ trace_t trace;
+ vec3_t end;
+ float time_left;
+ float into;
+ vec3_t endVelocity;
+ vec3_t endClipVelocity;
+
+ numbumps = 4;
+
+ VectorCopy (pm->ps->velocity, primal_velocity);
+
+ if ( gravity ) {
+ VectorCopy( pm->ps->velocity, endVelocity );
+ endVelocity[2] -= pm->ps->gravity * pml.frametime;
+ pm->ps->velocity[2] = ( pm->ps->velocity[2] + endVelocity[2] ) * 0.5;
+ primal_velocity[2] = endVelocity[2];
+ if ( pml.groundPlane ) {
+ // slide along the ground plane
+ PM_ClipVelocity (pm->ps->velocity, pml.groundTrace.plane.normal,
+ pm->ps->velocity, OVERCLIP );
+ }
+ }
+
+ time_left = pml.frametime;
+
+ // never turn against the ground plane
+ if ( pml.groundPlane ) {
+ numplanes = 1;
+ VectorCopy( pml.groundTrace.plane.normal, planes[0] );
+ } else {
+ numplanes = 0;
+ }
+
+ // never turn against original velocity
+ VectorNormalize2( pm->ps->velocity, planes[numplanes] );
+ numplanes++;
+
+ for ( bumpcount=0 ; bumpcount < numbumps ; bumpcount++ ) {
+
+ // calculate position we are trying to move to
+ VectorMA( pm->ps->origin, time_left, pm->ps->velocity, end );
+
+ // see if we can make it there
+ pm->trace ( &trace, pm->ps->origin, pm->mins, pm->maxs, end, pm->ps->clientNum, pm->tracemask);
+
+ if (trace.allsolid) {
+ // entity is completely trapped in another solid
+ pm->ps->velocity[2] = 0; // don't build up falling damage, but allow sideways acceleration
+ return qtrue;
+ }
+
+ if (trace.fraction > 0) {
+ // actually covered some distance
+ VectorCopy (trace.endpos, pm->ps->origin);
+ }
+
+ if (trace.fraction == 1) {
+ break; // moved the entire distance
+ }
+
+ // save entity for contact
+ PM_AddTouchEnt( trace.entityNum );
+
+ time_left -= time_left * trace.fraction;
+
+ if (numplanes >= MAX_CLIP_PLANES) {
+ // this shouldn't really happen
+ VectorClear( pm->ps->velocity );
+ return qtrue;
+ }
+
+ //
+ // if this is the same plane we hit before, nudge velocity
+ // out along it, which fixes some epsilon issues with
+ // non-axial planes
+ //
+ for ( i = 0 ; i < numplanes ; i++ ) {
+ if ( DotProduct( trace.plane.normal, planes[i] ) > 0.99 ) {
+ VectorAdd( trace.plane.normal, pm->ps->velocity, pm->ps->velocity );
+ break;
+ }
+ }
+ if ( i < numplanes ) {
+ continue;
+ }
+ VectorCopy (trace.plane.normal, planes[numplanes]);
+ numplanes++;
+
+ //
+ // modify velocity so it parallels all of the clip planes
+ //
+
+ // find a plane that it enters
+ for ( i = 0 ; i < numplanes ; i++ ) {
+ into = DotProduct( pm->ps->velocity, planes[i] );
+ if ( into >= 0.1 ) {
+ continue; // move doesn't interact with the plane
+ }
+
+ // see how hard we are hitting things
+ if ( -into > pml.impactSpeed ) {
+ pml.impactSpeed = -into;
+ }
+
+ // slide along the plane
+ PM_ClipVelocity (pm->ps->velocity, planes[i], clipVelocity, OVERCLIP );
+
+ // slide along the plane
+ PM_ClipVelocity (endVelocity, planes[i], endClipVelocity, OVERCLIP );
+
+ // see if there is a second plane that the new move enters
+ for ( j = 0 ; j < numplanes ; j++ ) {
+ if ( j == i ) {
+ continue;
+ }
+ if ( DotProduct( clipVelocity, planes[j] ) >= 0.1 ) {
+ continue; // move doesn't interact with the plane
+ }
+
+ // try clipping the move to the plane
+ PM_ClipVelocity( clipVelocity, planes[j], clipVelocity, OVERCLIP );
+ PM_ClipVelocity( endClipVelocity, planes[j], endClipVelocity, OVERCLIP );
+
+ // see if it goes back into the first clip plane
+ if ( DotProduct( clipVelocity, planes[i] ) >= 0 ) {
+ continue;
+ }
+
+ // slide the original velocity along the crease
+ CrossProduct (planes[i], planes[j], dir);
+ VectorNormalize( dir );
+ d = DotProduct( dir, pm->ps->velocity );
+ VectorScale( dir, d, clipVelocity );
+
+ CrossProduct (planes[i], planes[j], dir);
+ VectorNormalize( dir );
+ d = DotProduct( dir, endVelocity );
+ VectorScale( dir, d, endClipVelocity );
+
+ // see if there is a third plane the the new move enters
+ for ( k = 0 ; k < numplanes ; k++ ) {
+ if ( k == i || k == j ) {
+ continue;
+ }
+ if ( DotProduct( clipVelocity, planes[k] ) >= 0.1 ) {
+ continue; // move doesn't interact with the plane
+ }
+
+ // stop dead at a tripple plane interaction
+ VectorClear( pm->ps->velocity );
+ return qtrue;
+ }
+ }
+
+ // if we have fixed all interactions, try another move
+ VectorCopy( clipVelocity, pm->ps->velocity );
+ VectorCopy( endClipVelocity, endVelocity );
+ break;
+ }
+ }
+
+ if ( gravity ) {
+ VectorCopy( endVelocity, pm->ps->velocity );
+ }
+
+ // don't change velocity if in a timer (FIXME: is this correct?)
+ if ( pm->ps->pm_time ) {
+ VectorCopy( primal_velocity, pm->ps->velocity );
+ }
+
+ return ( bumpcount != 0 );
+}
+
+/*
+==================
+PM_StepSlideMove
+
+==================
+*/
+void PM_StepSlideMove( qboolean gravity ) {
+ vec3_t start_o, start_v;
+ vec3_t down_o, down_v;
+ trace_t trace;
+// float down_dist, up_dist;
+// vec3_t delta, delta2;
+ vec3_t up, down;
+ float stepSize;
+
+ VectorCopy (pm->ps->origin, start_o);
+ VectorCopy (pm->ps->velocity, start_v);
+
+ if ( PM_SlideMove( gravity ) == 0 ) {
+ return; // we got exactly where we wanted to go first try
+ }
+
+ VectorCopy(start_o, down);
+ down[2] -= STEPSIZE;
+ pm->trace (&trace, start_o, pm->mins, pm->maxs, down, pm->ps->clientNum, pm->tracemask);
+ VectorSet(up, 0, 0, 1);
+ // never step up when you still have up velocity
+ if ( pm->ps->velocity[2] > 0 && (trace.fraction == 1.0 ||
+ DotProduct(trace.plane.normal, up) < 0.7)) {
+ return;
+ }
+
+ VectorCopy (pm->ps->origin, down_o);
+ VectorCopy (pm->ps->velocity, down_v);
+
+ VectorCopy (start_o, up);
+ up[2] += STEPSIZE;
+
+ // test the player position if they were a stepheight higher
+ pm->trace (&trace, start_o, pm->mins, pm->maxs, up, pm->ps->clientNum, pm->tracemask);
+ if ( trace.allsolid ) {
+ if ( pm->debugLevel ) {
+ Com_Printf("%i:bend can't step\n", c_pmove);
+ }
+ return; // can't step up
+ }
+
+ stepSize = trace.endpos[2] - start_o[2];
+ // try slidemove from this position
+ VectorCopy (trace.endpos, pm->ps->origin);
+ VectorCopy (start_v, pm->ps->velocity);
+
+ PM_SlideMove( gravity );
+
+ // push down the final amount
+ VectorCopy (pm->ps->origin, down);
+ down[2] -= stepSize;
+ pm->trace (&trace, pm->ps->origin, pm->mins, pm->maxs, down, pm->ps->clientNum, pm->tracemask);
+ if ( !trace.allsolid ) {
+ VectorCopy (trace.endpos, pm->ps->origin);
+ }
+ if ( trace.fraction < 1.0 ) {
+ PM_ClipVelocity( pm->ps->velocity, trace.plane.normal, pm->ps->velocity, OVERCLIP );
+ }
+
+#if 0
+ // if the down trace can trace back to the original position directly, don't step
+ pm->trace( &trace, pm->ps->origin, pm->mins, pm->maxs, start_o, pm->ps->clientNum, pm->tracemask);
+ if ( trace.fraction == 1.0 ) {
+ // use the original move
+ VectorCopy (down_o, pm->ps->origin);
+ VectorCopy (down_v, pm->ps->velocity);
+ if ( pm->debugLevel ) {
+ Com_Printf("%i:bend\n", c_pmove);
+ }
+ } else
+#endif
+ {
+ // use the step move
+ float delta;
+
+ delta = pm->ps->origin[2] - start_o[2];
+ if ( delta > 2 ) {
+ if ( delta < 7 ) {
+ PM_AddEvent( EV_STEP_4 );
+ } else if ( delta < 11 ) {
+ PM_AddEvent( EV_STEP_8 );
+ } else if ( delta < 15 ) {
+ PM_AddEvent( EV_STEP_12 );
+ } else {
+ PM_AddEvent( EV_STEP_16 );
+ }
+ }
+ if ( pm->debugLevel ) {
+ Com_Printf("%i:stepped\n", c_pmove);
+ }
+ }
+}
+
diff --git a/code/game/botlib.h b/code/game/botlib.h
new file mode 100755
index 0000000..a9b45db
--- /dev/null
+++ b/code/game/botlib.h
@@ -0,0 +1,516 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*****************************************************************************
+ * name: botlib.h
+ *
+ * desc: bot AI library
+ *
+ * $Archive: /source/code/game/botai.h $
+ *
+ *****************************************************************************/
+
+#define BOTLIB_API_VERSION 2
+
+struct aas_clientmove_s;
+struct aas_entityinfo_s;
+struct aas_areainfo_s;
+struct aas_altroutegoal_s;
+struct aas_predictroute_s;
+struct bot_consolemessage_s;
+struct bot_match_s;
+struct bot_goal_s;
+struct bot_moveresult_s;
+struct bot_initmove_s;
+struct weaponinfo_s;
+
+#define BOTFILESBASEFOLDER "botfiles"
+//debug line colors
+#define LINECOLOR_NONE -1
+#define LINECOLOR_RED 1//0xf2f2f0f0L
+#define LINECOLOR_GREEN 2//0xd0d1d2d3L
+#define LINECOLOR_BLUE 3//0xf3f3f1f1L
+#define LINECOLOR_YELLOW 4//0xdcdddedfL
+#define LINECOLOR_ORANGE 5//0xe0e1e2e3L
+
+//Print types
+#define PRT_MESSAGE 1
+#define PRT_WARNING 2
+#define PRT_ERROR 3
+#define PRT_FATAL 4
+#define PRT_EXIT 5
+
+//console message types
+#define CMS_NORMAL 0
+#define CMS_CHAT 1
+
+//botlib error codes
+#define BLERR_NOERROR 0 //no error
+#define BLERR_LIBRARYNOTSETUP 1 //library not setup
+#define BLERR_INVALIDENTITYNUMBER 2 //invalid entity number
+#define BLERR_NOAASFILE 3 //no AAS file available
+#define BLERR_CANNOTOPENAASFILE 4 //cannot open AAS file
+#define BLERR_WRONGAASFILEID 5 //incorrect AAS file id
+#define BLERR_WRONGAASFILEVERSION 6 //incorrect AAS file version
+#define BLERR_CANNOTREADAASLUMP 7 //cannot read AAS file lump
+#define BLERR_CANNOTLOADICHAT 8 //cannot load initial chats
+#define BLERR_CANNOTLOADITEMWEIGHTS 9 //cannot load item weights
+#define BLERR_CANNOTLOADITEMCONFIG 10 //cannot load item config
+#define BLERR_CANNOTLOADWEAPONWEIGHTS 11 //cannot load weapon weights
+#define BLERR_CANNOTLOADWEAPONCONFIG 12 //cannot load weapon config
+
+//action flags
+#define ACTION_ATTACK 0x0000001
+#define ACTION_USE 0x0000002
+#define ACTION_RESPAWN 0x0000008
+#define ACTION_JUMP 0x0000010
+#define ACTION_MOVEUP 0x0000020
+#define ACTION_CROUCH 0x0000080
+#define ACTION_MOVEDOWN 0x0000100
+#define ACTION_MOVEFORWARD 0x0000200
+#define ACTION_MOVEBACK 0x0000800
+#define ACTION_MOVELEFT 0x0001000
+#define ACTION_MOVERIGHT 0x0002000
+#define ACTION_DELAYEDJUMP 0x0008000
+#define ACTION_TALK 0x0010000
+#define ACTION_GESTURE 0x0020000
+#define ACTION_WALK 0x0080000
+#define ACTION_AFFIRMATIVE 0x0100000
+#define ACTION_NEGATIVE 0x0200000
+#define ACTION_GETFLAG 0x0800000
+#define ACTION_GUARDBASE 0x1000000
+#define ACTION_PATROL 0x2000000
+#define ACTION_FOLLOWME 0x8000000
+
+//the bot input, will be converted to an usercmd_t
+typedef struct bot_input_s
+{
+ float thinktime; //time since last output (in seconds)
+ vec3_t dir; //movement direction
+ float speed; //speed in the range [0, 400]
+ vec3_t viewangles; //the view angles
+ int actionflags; //one of the ACTION_? flags
+ int weapon; //weapon to use
+} bot_input_t;
+
+#ifndef BSPTRACE
+
+#define BSPTRACE
+
+//bsp_trace_t hit surface
+typedef struct bsp_surface_s
+{
+ char name[16];
+ int flags;
+ int value;
+} bsp_surface_t;
+
+//remove the bsp_trace_s structure definition l8r on
+//a trace is returned when a box is swept through the world
+typedef struct bsp_trace_s
+{
+ qboolean allsolid; // if true, plane is not valid
+ qboolean startsolid; // if true, the initial point was in a solid area
+ float fraction; // time completed, 1.0 = didn't hit anything
+ vec3_t endpos; // final position
+ cplane_t plane; // surface normal at impact
+ float exp_dist; // expanded plane distance
+ int sidenum; // number of the brush side hit
+ bsp_surface_t surface; // the hit point surface
+ int contents; // contents on other side of surface hit
+ int ent; // number of entity hit
+} bsp_trace_t;
+
+#endif // BSPTRACE
+
+//entity state
+typedef struct bot_entitystate_s
+{
+ int type; // entity type
+ int flags; // entity flags
+ vec3_t origin; // origin of the entity
+ vec3_t angles; // angles of the model
+ vec3_t old_origin; // for lerping
+ vec3_t mins; // bounding box minimums
+ vec3_t maxs; // bounding box maximums
+ int groundent; // ground entity
+ int solid; // solid type
+ int modelindex; // model used
+ int modelindex2; // weapons, CTF flags, etc
+ int frame; // model frame number
+ int event; // impulse events -- muzzle flashes, footsteps, etc
+ int eventParm; // even parameter
+ int powerups; // bit flags
+ int weapon; // determines weapon and flash model, etc
+ int legsAnim; // mask off ANIM_TOGGLEBIT
+ int torsoAnim; // mask off ANIM_TOGGLEBIT
+} bot_entitystate_t;
+
+//bot AI library exported functions
+typedef struct botlib_import_s
+{
+ //print messages from the bot library
+ void (QDECL *Print)(int type, char *fmt, ...);
+ //trace a bbox through the world
+ void (*Trace)(bsp_trace_t *trace, vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int passent, int contentmask);
+ //trace a bbox against a specific entity
+ void (*EntityTrace)(bsp_trace_t *trace, vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int entnum, int contentmask);
+ //retrieve the contents at the given point
+ int (*PointContents)(vec3_t point);
+ //check if the point is in potential visible sight
+ int (*inPVS)(vec3_t p1, vec3_t p2);
+ //retrieve the BSP entity data lump
+ char *(*BSPEntityData)(void);
+ //
+ void (*BSPModelMinsMaxsOrigin)(int modelnum, vec3_t angles, vec3_t mins, vec3_t maxs, vec3_t origin);
+ //send a bot client command
+ void (*BotClientCommand)(int client, char *command);
+ //memory allocation
+ void *(*GetMemory)(int size); // allocate from Zone
+ void (*FreeMemory)(void *ptr); // free memory from Zone
+ int (*AvailableMemory)(void); // available Zone memory
+ void *(*HunkAlloc)(int size); // allocate from hunk
+ //file system access
+ int (*FS_FOpenFile)( const char *qpath, fileHandle_t *file, fsMode_t mode );
+ int (*FS_Read)( void *buffer, int len, fileHandle_t f );
+ int (*FS_Write)( const void *buffer, int len, fileHandle_t f );
+ void (*FS_FCloseFile)( fileHandle_t f );
+ int (*FS_Seek)( fileHandle_t f, long offset, int origin );
+ //debug visualisation stuff
+ int (*DebugLineCreate)(void);
+ void (*DebugLineDelete)(int line);
+ void (*DebugLineShow)(int line, vec3_t start, vec3_t end, int color);
+ //
+ int (*DebugPolygonCreate)(int color, int numPoints, vec3_t *points);
+ void (*DebugPolygonDelete)(int id);
+} botlib_import_t;
+
+typedef struct aas_export_s
+{
+ //-----------------------------------
+ // be_aas_entity.h
+ //-----------------------------------
+ void (*AAS_EntityInfo)(int entnum, struct aas_entityinfo_s *info);
+ //-----------------------------------
+ // be_aas_main.h
+ //-----------------------------------
+ int (*AAS_Initialized)(void);
+ void (*AAS_PresenceTypeBoundingBox)(int presencetype, vec3_t mins, vec3_t maxs);
+ float (*AAS_Time)(void);
+ //--------------------------------------------
+ // be_aas_sample.c
+ //--------------------------------------------
+ int (*AAS_PointAreaNum)(vec3_t point);
+ int (*AAS_PointReachabilityAreaIndex)( vec3_t point );
+ int (*AAS_TraceAreas)(vec3_t start, vec3_t end, int *areas, vec3_t *points, int maxareas);
+ int (*AAS_BBoxAreas)(vec3_t absmins, vec3_t absmaxs, int *areas, int maxareas);
+ int (*AAS_AreaInfo)( int areanum, struct aas_areainfo_s *info );
+ //--------------------------------------------
+ // be_aas_bspq3.c
+ //--------------------------------------------
+ int (*AAS_PointContents)(vec3_t point);
+ int (*AAS_NextBSPEntity)(int ent);
+ int (*AAS_ValueForBSPEpairKey)(int ent, char *key, char *value, int size);
+ int (*AAS_VectorForBSPEpairKey)(int ent, char *key, vec3_t v);
+ int (*AAS_FloatForBSPEpairKey)(int ent, char *key, float *value);
+ int (*AAS_IntForBSPEpairKey)(int ent, char *key, int *value);
+ //--------------------------------------------
+ // be_aas_reach.c
+ //--------------------------------------------
+ int (*AAS_AreaReachability)(int areanum);
+ //--------------------------------------------
+ // be_aas_route.c
+ //--------------------------------------------
+ int (*AAS_AreaTravelTimeToGoalArea)(int areanum, vec3_t origin, int goalareanum, int travelflags);
+ int (*AAS_EnableRoutingArea)(int areanum, int enable);
+ int (*AAS_PredictRoute)(struct aas_predictroute_s *route, int areanum, vec3_t origin,
+ int goalareanum, int travelflags, int maxareas, int maxtime,
+ int stopevent, int stopcontents, int stoptfl, int stopareanum);
+ //--------------------------------------------
+ // be_aas_altroute.c
+ //--------------------------------------------
+ int (*AAS_AlternativeRouteGoals)(vec3_t start, int startareanum, vec3_t goal, int goalareanum, int travelflags,
+ struct aas_altroutegoal_s *altroutegoals, int maxaltroutegoals,
+ int type);
+ //--------------------------------------------
+ // be_aas_move.c
+ //--------------------------------------------
+ int (*AAS_Swimming)(vec3_t origin);
+ int (*AAS_PredictClientMovement)(struct aas_clientmove_s *move,
+ int entnum, vec3_t origin,
+ int presencetype, int onground,
+ vec3_t velocity, vec3_t cmdmove,
+ int cmdframes,
+ int maxframes, float frametime,
+ int stopevent, int stopareanum, int visualize);
+} aas_export_t;
+
+typedef struct ea_export_s
+{
+ //ClientCommand elementary actions
+ void (*EA_Command)(int client, char *command );
+ void (*EA_Say)(int client, char *str);
+ void (*EA_SayTeam)(int client, char *str);
+ //
+ void (*EA_Action)(int client, int action);
+ void (*EA_Gesture)(int client);
+ void (*EA_Talk)(int client);
+ void (*EA_Attack)(int client);
+ void (*EA_Use)(int client);
+ void (*EA_Respawn)(int client);
+ void (*EA_MoveUp)(int client);
+ void (*EA_MoveDown)(int client);
+ void (*EA_MoveForward)(int client);
+ void (*EA_MoveBack)(int client);
+ void (*EA_MoveLeft)(int client);
+ void (*EA_MoveRight)(int client);
+ void (*EA_Crouch)(int client);
+
+ void (*EA_SelectWeapon)(int client, int weapon);
+ void (*EA_Jump)(int client);
+ void (*EA_DelayedJump)(int client);
+ void (*EA_Move)(int client, vec3_t dir, float speed);
+ void (*EA_View)(int client, vec3_t viewangles);
+ //send regular input to the server
+ void (*EA_EndRegular)(int client, float thinktime);
+ void (*EA_GetInput)(int client, float thinktime, bot_input_t *input);
+ void (*EA_ResetInput)(int client);
+} ea_export_t;
+
+typedef struct ai_export_s
+{
+ //-----------------------------------
+ // be_ai_char.h
+ //-----------------------------------
+ int (*BotLoadCharacter)(char *charfile, float skill);
+ void (*BotFreeCharacter)(int character);
+ float (*Characteristic_Float)(int character, int index);
+ float (*Characteristic_BFloat)(int character, int index, float min, float max);
+ int (*Characteristic_Integer)(int character, int index);
+ int (*Characteristic_BInteger)(int character, int index, int min, int max);
+ void (*Characteristic_String)(int character, int index, char *buf, int size);
+ //-----------------------------------
+ // be_ai_chat.h
+ //-----------------------------------
+ int (*BotAllocChatState)(void);
+ void (*BotFreeChatState)(int handle);
+ void (*BotQueueConsoleMessage)(int chatstate, int type, char *message);
+ void (*BotRemoveConsoleMessage)(int chatstate, int handle);
+ int (*BotNextConsoleMessage)(int chatstate, struct bot_consolemessage_s *cm);
+ int (*BotNumConsoleMessages)(int chatstate);
+ void (*BotInitialChat)(int chatstate, char *type, int mcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7);
+ int (*BotNumInitialChats)(int chatstate, char *type);
+ int (*BotReplyChat)(int chatstate, char *message, int mcontext, int vcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7);
+ int (*BotChatLength)(int chatstate);
+ void (*BotEnterChat)(int chatstate, int client, int sendto);
+ void (*BotGetChatMessage)(int chatstate, char *buf, int size);
+ int (*StringContains)(char *str1, char *str2, int casesensitive);
+ int (*BotFindMatch)(char *str, struct bot_match_s *match, unsigned long int context);
+ void (*BotMatchVariable)(struct bot_match_s *match, int variable, char *buf, int size);
+ void (*UnifyWhiteSpaces)(char *string);
+ void (*BotReplaceSynonyms)(char *string, unsigned long int context);
+ int (*BotLoadChatFile)(int chatstate, char *chatfile, char *chatname);
+ void (*BotSetChatGender)(int chatstate, int gender);
+ void (*BotSetChatName)(int chatstate, char *name, int client);
+ //-----------------------------------
+ // be_ai_goal.h
+ //-----------------------------------
+ void (*BotResetGoalState)(int goalstate);
+ void (*BotResetAvoidGoals)(int goalstate);
+ void (*BotRemoveFromAvoidGoals)(int goalstate, int number);
+ void (*BotPushGoal)(int goalstate, struct bot_goal_s *goal);
+ void (*BotPopGoal)(int goalstate);
+ void (*BotEmptyGoalStack)(int goalstate);
+ void (*BotDumpAvoidGoals)(int goalstate);
+ void (*BotDumpGoalStack)(int goalstate);
+ void (*BotGoalName)(int number, char *name, int size);
+ int (*BotGetTopGoal)(int goalstate, struct bot_goal_s *goal);
+ int (*BotGetSecondGoal)(int goalstate, struct bot_goal_s *goal);
+ int (*BotChooseLTGItem)(int goalstate, vec3_t origin, int *inventory, int travelflags);
+ int (*BotChooseNBGItem)(int goalstate, vec3_t origin, int *inventory, int travelflags,
+ struct bot_goal_s *ltg, float maxtime);
+ int (*BotTouchingGoal)(vec3_t origin, struct bot_goal_s *goal);
+ int (*BotItemGoalInVisButNotVisible)(int viewer, vec3_t eye, vec3_t viewangles, struct bot_goal_s *goal);
+ int (*BotGetLevelItemGoal)(int index, char *classname, struct bot_goal_s *goal);
+ int (*BotGetNextCampSpotGoal)(int num, struct bot_goal_s *goal);
+ int (*BotGetMapLocationGoal)(char *name, struct bot_goal_s *goal);
+ float (*BotAvoidGoalTime)(int goalstate, int number);
+ void (*BotSetAvoidGoalTime)(int goalstate, int number, float avoidtime);
+ void (*BotInitLevelItems)(void);
+ void (*BotUpdateEntityItems)(void);
+ int (*BotLoadItemWeights)(int goalstate, char *filename);
+ void (*BotFreeItemWeights)(int goalstate);
+ void (*BotInterbreedGoalFuzzyLogic)(int parent1, int parent2, int child);
+ void (*BotSaveGoalFuzzyLogic)(int goalstate, char *filename);
+ void (*BotMutateGoalFuzzyLogic)(int goalstate, float range);
+ int (*BotAllocGoalState)(int client);
+ void (*BotFreeGoalState)(int handle);
+ //-----------------------------------
+ // be_ai_move.h
+ //-----------------------------------
+ void (*BotResetMoveState)(int movestate);
+ void (*BotMoveToGoal)(struct bot_moveresult_s *result, int movestate, struct bot_goal_s *goal, int travelflags);
+ int (*BotMoveInDirection)(int movestate, vec3_t dir, float speed, int type);
+ void (*BotResetAvoidReach)(int movestate);
+ void (*BotResetLastAvoidReach)(int movestate);
+ int (*BotReachabilityArea)(vec3_t origin, int testground);
+ int (*BotMovementViewTarget)(int movestate, struct bot_goal_s *goal, int travelflags, float lookahead, vec3_t target);
+ int (*BotPredictVisiblePosition)(vec3_t origin, int areanum, struct bot_goal_s *goal, int travelflags, vec3_t target);
+ int (*BotAllocMoveState)(void);
+ void (*BotFreeMoveState)(int handle);
+ void (*BotInitMoveState)(int handle, struct bot_initmove_s *initmove);
+ void (*BotAddAvoidSpot)(int movestate, vec3_t origin, float radius, int type);
+ //-----------------------------------
+ // be_ai_weap.h
+ //-----------------------------------
+ int (*BotChooseBestFightWeapon)(int weaponstate, int *inventory);
+ void (*BotGetWeaponInfo)(int weaponstate, int weapon, struct weaponinfo_s *weaponinfo);
+ int (*BotLoadWeaponWeights)(int weaponstate, char *filename);
+ int (*BotAllocWeaponState)(void);
+ void (*BotFreeWeaponState)(int weaponstate);
+ void (*BotResetWeaponState)(int weaponstate);
+ //-----------------------------------
+ // be_ai_gen.h
+ //-----------------------------------
+ int (*GeneticParentsAndChildSelection)(int numranks, float *ranks, int *parent1, int *parent2, int *child);
+} ai_export_t;
+
+//bot AI library imported functions
+typedef struct botlib_export_s
+{
+ //Area Awareness System functions
+ aas_export_t aas;
+ //Elementary Action functions
+ ea_export_t ea;
+ //AI functions
+ ai_export_t ai;
+ //setup the bot library, returns BLERR_
+ int (*BotLibSetup)(void);
+ //shutdown the bot library, returns BLERR_
+ int (*BotLibShutdown)(void);
+ //sets a library variable returns BLERR_
+ int (*BotLibVarSet)(char *var_name, char *value);
+ //gets a library variable returns BLERR_
+ int (*BotLibVarGet)(char *var_name, char *value, int size);
+
+ //sets a C-like define returns BLERR_
+ int (*PC_AddGlobalDefine)(char *string);
+ int (*PC_LoadSourceHandle)(const char *filename);
+ int (*PC_FreeSourceHandle)(int handle);
+ int (*PC_ReadTokenHandle)(int handle, pc_token_t *pc_token);
+ int (*PC_SourceFileAndLine)(int handle, char *filename, int *line);
+
+ //start a frame in the bot library
+ int (*BotLibStartFrame)(float time);
+ //load a new map in the bot library
+ int (*BotLibLoadMap)(const char *mapname);
+ //entity updates
+ int (*BotLibUpdateEntity)(int ent, bot_entitystate_t *state);
+ //just for testing
+ int (*Test)(int parm0, char *parm1, vec3_t parm2, vec3_t parm3);
+} botlib_export_t;
+
+//linking of bot library
+botlib_export_t *GetBotLibAPI( int apiVersion, botlib_import_t *import );
+
+/* Library variables:
+
+name: default: module(s): description:
+
+"basedir" "" l_utils.c base directory
+"gamedir" "" l_utils.c game directory
+"cddir" "" l_utils.c CD directory
+
+"log" "0" l_log.c enable/disable creating a log file
+"maxclients" "4" be_interface.c maximum number of clients
+"maxentities" "1024" be_interface.c maximum number of entities
+"bot_developer" "0" be_interface.c bot developer mode
+
+"phys_friction" "6" be_aas_move.c ground friction
+"phys_stopspeed" "100" be_aas_move.c stop speed
+"phys_gravity" "800" be_aas_move.c gravity value
+"phys_waterfriction" "1" be_aas_move.c water friction
+"phys_watergravity" "400" be_aas_move.c gravity in water
+"phys_maxvelocity" "320" be_aas_move.c maximum velocity
+"phys_maxwalkvelocity" "320" be_aas_move.c maximum walk velocity
+"phys_maxcrouchvelocity" "100" be_aas_move.c maximum crouch velocity
+"phys_maxswimvelocity" "150" be_aas_move.c maximum swim velocity
+"phys_walkaccelerate" "10" be_aas_move.c walk acceleration
+"phys_airaccelerate" "1" be_aas_move.c air acceleration
+"phys_swimaccelerate" "4" be_aas_move.c swim acceleration
+"phys_maxstep" "18" be_aas_move.c maximum step height
+"phys_maxsteepness" "0.7" be_aas_move.c maximum floor steepness
+"phys_maxbarrier" "32" be_aas_move.c maximum barrier height
+"phys_maxwaterjump" "19" be_aas_move.c maximum waterjump height
+"phys_jumpvel" "270" be_aas_move.c jump z velocity
+"phys_falldelta5" "40" be_aas_move.c
+"phys_falldelta10" "60" be_aas_move.c
+"rs_waterjump" "400" be_aas_move.c
+"rs_teleport" "50" be_aas_move.c
+"rs_barrierjump" "100" be_aas_move.c
+"rs_startcrouch" "300" be_aas_move.c
+"rs_startgrapple" "500" be_aas_move.c
+"rs_startwalkoffledge" "70" be_aas_move.c
+"rs_startjump" "300" be_aas_move.c
+"rs_rocketjump" "500" be_aas_move.c
+"rs_bfgjump" "500" be_aas_move.c
+"rs_jumppad" "250" be_aas_move.c
+"rs_aircontrolledjumppad" "300" be_aas_move.c
+"rs_funcbob" "300" be_aas_move.c
+"rs_startelevator" "50" be_aas_move.c
+"rs_falldamage5" "300" be_aas_move.c
+"rs_falldamage10" "500" be_aas_move.c
+"rs_maxjumpfallheight" "450" be_aas_move.c
+
+"max_aaslinks" "4096" be_aas_sample.c maximum links in the AAS
+"max_routingcache" "4096" be_aas_route.c maximum routing cache size in KB
+"forceclustering" "0" be_aas_main.c force recalculation of clusters
+"forcereachability" "0" be_aas_main.c force recalculation of reachabilities
+"forcewrite" "0" be_aas_main.c force writing of aas file
+"aasoptimize" "0" be_aas_main.c enable aas optimization
+"sv_mapChecksum" "0" be_aas_main.c BSP file checksum
+"bot_visualizejumppads" "0" be_aas_reach.c visualize jump pads
+
+"bot_reloadcharacters" "0" - reload bot character files
+"ai_gametype" "0" be_ai_goal.c game type
+"droppedweight" "1000" be_ai_goal.c additional dropped item weight
+"weapindex_rocketlauncher" "5" be_ai_move.c rl weapon index for rocket jumping
+"weapindex_bfg10k" "9" be_ai_move.c bfg weapon index for bfg jumping
+"weapindex_grapple" "10" be_ai_move.c grapple weapon index for grappling
+"entitytypemissile" "3" be_ai_move.c ET_MISSILE
+"offhandgrapple" "0" be_ai_move.c enable off hand grapple hook
+"cmd_grappleon" "grappleon" be_ai_move.c command to activate off hand grapple
+"cmd_grappleoff" "grappleoff" be_ai_move.c command to deactivate off hand grapple
+"itemconfig" "items.c" be_ai_goal.c item configuration file
+"weaponconfig" "weapons.c" be_ai_weap.c weapon configuration file
+"synfile" "syn.c" be_ai_chat.c file with synonyms
+"rndfile" "rnd.c" be_ai_chat.c file with random strings
+"matchfile" "match.c" be_ai_chat.c file with match strings
+"nochat" "0" be_ai_chat.c disable chats
+"max_messages" "1024" be_ai_chat.c console message heap size
+"max_weaponinfo" "32" be_ai_weap.c maximum number of weapon info
+"max_projectileinfo" "32" be_ai_weap.c maximum number of projectile info
+"max_iteminfo" "256" be_ai_goal.c maximum number of item info
+"max_levelitems" "256" be_ai_goal.c maximum number of level items
+
+*/
+
diff --git a/code/game/chars.h b/code/game/chars.h
new file mode 100755
index 0000000..c5b1861
--- /dev/null
+++ b/code/game/chars.h
@@ -0,0 +1,134 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+//========================================================
+//========================================================
+//name
+#define CHARACTERISTIC_NAME 0 //string
+//gender of the bot
+#define CHARACTERISTIC_GENDER 1 //string ("male", "female", "it")
+//attack skill
+// > 0.0 && < 0.2 = don't move
+// > 0.3 && < 1.0 = aim at enemy during retreat
+// > 0.0 && < 0.4 = only move forward/backward
+// >= 0.4 && < 1.0 = circle strafing
+// > 0.7 && < 1.0 = random strafe direction change
+#define CHARACTERISTIC_ATTACK_SKILL 2 //float [0, 1]
+//weapon weight file
+#define CHARACTERISTIC_WEAPONWEIGHTS 3 //string
+//view angle difference to angle change factor
+#define CHARACTERISTIC_VIEW_FACTOR 4 //float <0, 1]
+//maximum view angle change
+#define CHARACTERISTIC_VIEW_MAXCHANGE 5 //float [1, 360]
+//reaction time in seconds
+#define CHARACTERISTIC_REACTIONTIME 6 //float [0, 5]
+//accuracy when aiming
+#define CHARACTERISTIC_AIM_ACCURACY 7 //float [0, 1]
+//weapon specific aim accuracy
+#define CHARACTERISTIC_AIM_ACCURACY_MACHINEGUN 8 //float [0, 1]
+#define CHARACTERISTIC_AIM_ACCURACY_SHOTGUN 9 //float [0, 1]
+#define CHARACTERISTIC_AIM_ACCURACY_ROCKETLAUNCHER 10 //float [0, 1]
+#define CHARACTERISTIC_AIM_ACCURACY_GRENADELAUNCHER 11 //float [0, 1]
+#define CHARACTERISTIC_AIM_ACCURACY_LIGHTNING 12
+#define CHARACTERISTIC_AIM_ACCURACY_PLASMAGUN 13 //float [0, 1]
+#define CHARACTERISTIC_AIM_ACCURACY_RAILGUN 14
+#define CHARACTERISTIC_AIM_ACCURACY_BFG10K 15 //float [0, 1]
+//skill when aiming
+// > 0.0 && < 0.9 = aim is affected by enemy movement
+// > 0.4 && <= 0.8 = enemy linear leading
+// > 0.8 && <= 1.0 = enemy exact movement leading
+// > 0.5 && <= 1.0 = prediction shots when enemy is not visible
+// > 0.6 && <= 1.0 = splash damage by shooting nearby geometry
+#define CHARACTERISTIC_AIM_SKILL 16 //float [0, 1]
+//weapon specific aim skill
+#define CHARACTERISTIC_AIM_SKILL_ROCKETLAUNCHER 17 //float [0, 1]
+#define CHARACTERISTIC_AIM_SKILL_GRENADELAUNCHER 18 //float [0, 1]
+#define CHARACTERISTIC_AIM_SKILL_PLASMAGUN 19 //float [0, 1]
+#define CHARACTERISTIC_AIM_SKILL_BFG10K 20 //float [0, 1]
+//========================================================
+//chat
+//========================================================
+//file with chats
+#define CHARACTERISTIC_CHAT_FILE 21 //string
+//name of the chat character
+#define CHARACTERISTIC_CHAT_NAME 22 //string
+//characters per minute type speed
+#define CHARACTERISTIC_CHAT_CPM 23 //integer [1, 4000]
+//tendency to insult/praise
+#define CHARACTERISTIC_CHAT_INSULT 24 //float [0, 1]
+//tendency to chat misc
+#define CHARACTERISTIC_CHAT_MISC 25 //float [0, 1]
+//tendency to chat at start or end of level
+#define CHARACTERISTIC_CHAT_STARTENDLEVEL 26 //float [0, 1]
+//tendency to chat entering or exiting the game
+#define CHARACTERISTIC_CHAT_ENTEREXITGAME 27 //float [0, 1]
+//tendency to chat when killed someone
+#define CHARACTERISTIC_CHAT_KILL 28 //float [0, 1]
+//tendency to chat when died
+#define CHARACTERISTIC_CHAT_DEATH 29 //float [0, 1]
+//tendency to chat when enemy suicides
+#define CHARACTERISTIC_CHAT_ENEMYSUICIDE 30 //float [0, 1]
+//tendency to chat when hit while talking
+#define CHARACTERISTIC_CHAT_HITTALKING 31 //float [0, 1]
+//tendency to chat when bot was hit but didn't dye
+#define CHARACTERISTIC_CHAT_HITNODEATH 32 //float [0, 1]
+//tendency to chat when bot hit the enemy but enemy didn't dye
+#define CHARACTERISTIC_CHAT_HITNOKILL 33 //float [0, 1]
+//tendency to randomly chat
+#define CHARACTERISTIC_CHAT_RANDOM 34 //float [0, 1]
+//tendency to reply
+#define CHARACTERISTIC_CHAT_REPLY 35 //float [0, 1]
+//========================================================
+//movement
+//========================================================
+//tendency to crouch
+#define CHARACTERISTIC_CROUCHER 36 //float [0, 1]
+//tendency to jump
+#define CHARACTERISTIC_JUMPER 37 //float [0, 1]
+//tendency to walk
+#define CHARACTERISTIC_WALKER 48 //float [0, 1]
+//tendency to jump using a weapon
+#define CHARACTERISTIC_WEAPONJUMPING 38 //float [0, 1]
+//tendency to use the grapple hook when available
+#define CHARACTERISTIC_GRAPPLE_USER 39 //float [0, 1] //use this!!
+//========================================================
+//goal
+//========================================================
+//item weight file
+#define CHARACTERISTIC_ITEMWEIGHTS 40 //string
+//the aggression of the bot
+#define CHARACTERISTIC_AGGRESSION 41 //float [0, 1]
+//the self preservation of the bot (rockets near walls etc.)
+#define CHARACTERISTIC_SELFPRESERVATION 42 //float [0, 1]
+//how likely the bot is to take revenge
+#define CHARACTERISTIC_VENGEFULNESS 43 //float [0, 1] //use this!!
+//tendency to camp
+#define CHARACTERISTIC_CAMPER 44 //float [0, 1]
+//========================================================
+//========================================================
+//tendency to get easy frags
+#define CHARACTERISTIC_EASY_FRAGGER 45 //float [0, 1]
+//how alert the bot is (view distance)
+#define CHARACTERISTIC_ALERTNESS 46 //float [0, 1]
+//how much the bot fires it's weapon
+#define CHARACTERISTIC_FIRETHROTTLE 47 //float [0, 1]
+
diff --git a/code/game/g_active.c b/code/game/g_active.c
new file mode 100755
index 0000000..853f5fb
--- /dev/null
+++ b/code/game/g_active.c
@@ -0,0 +1,1191 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+#include "g_local.h"
+
+
+/*
+===============
+G_DamageFeedback
+
+Called just before a snapshot is sent to the given player.
+Totals up all damage and generates both the player_state_t
+damage values to that client for pain blends and kicks, and
+global pain sound events for all clients.
+===============
+*/
+void P_DamageFeedback( gentity_t *player ) {
+ gclient_t *client;
+ float count;
+ vec3_t angles;
+
+ client = player->client;
+ if ( client->ps.pm_type == PM_DEAD ) {
+ return;
+ }
+
+ // total points of damage shot at the player this frame
+ count = client->damage_blood + client->damage_armor;
+ if ( count == 0 ) {
+ return; // didn't take any damage
+ }
+
+ if ( count > 255 ) {
+ count = 255;
+ }
+
+ // send the information to the client
+
+ // world damage (falling, slime, etc) uses a special code
+ // to make the blend blob centered instead of positional
+ if ( client->damage_fromWorld ) {
+ client->ps.damagePitch = 255;
+ client->ps.damageYaw = 255;
+
+ client->damage_fromWorld = qfalse;
+ } else {
+ vectoangles( client->damage_from, angles );
+ client->ps.damagePitch = angles[PITCH]/360.0 * 256;
+ client->ps.damageYaw = angles[YAW]/360.0 * 256;
+ }
+
+ // play an apropriate pain sound
+ if ( (level.time > player->pain_debounce_time) && !(player->flags & FL_GODMODE) ) {
+ player->pain_debounce_time = level.time + 700;
+ G_AddEvent( player, EV_PAIN, player->health );
+ client->ps.damageEvent++;
+ }
+
+
+ client->ps.damageCount = count;
+
+ //
+ // clear totals
+ //
+ client->damage_blood = 0;
+ client->damage_armor = 0;
+ client->damage_knockback = 0;
+}
+
+
+
+/*
+=============
+P_WorldEffects
+
+Check for lava / slime contents and drowning
+=============
+*/
+void P_WorldEffects( gentity_t *ent ) {
+ qboolean envirosuit;
+ int waterlevel;
+
+ if ( ent->client->noclip ) {
+ ent->client->airOutTime = level.time + 12000; // don't need air
+ return;
+ }
+
+ waterlevel = ent->waterlevel;
+
+ envirosuit = ent->client->ps.powerups[PW_BATTLESUIT] > level.time;
+
+ //
+ // check for drowning
+ //
+ if ( waterlevel == 3 ) {
+ // envirosuit give air
+ if ( envirosuit ) {
+ ent->client->airOutTime = level.time + 10000;
+ }
+
+ // if out of air, start drowning
+ if ( ent->client->airOutTime < level.time) {
+ // drown!
+ ent->client->airOutTime += 1000;
+ if ( ent->health > 0 ) {
+ // take more damage the longer underwater
+ ent->damage += 2;
+ if (ent->damage > 15)
+ ent->damage = 15;
+
+ // play a gurp sound instead of a normal pain sound
+ if (ent->health <= ent->damage) {
+ G_Sound(ent, CHAN_VOICE, G_SoundIndex("*drown.wav"));
+ } else if (rand()&1) {
+ G_Sound(ent, CHAN_VOICE, G_SoundIndex("sound/player/gurp1.wav"));
+ } else {
+ G_Sound(ent, CHAN_VOICE, G_SoundIndex("sound/player/gurp2.wav"));
+ }
+
+ // don't play a normal pain sound
+ ent->pain_debounce_time = level.time + 200;
+
+ G_Damage (ent, NULL, NULL, NULL, NULL,
+ ent->damage, DAMAGE_NO_ARMOR, MOD_WATER);
+ }
+ }
+ } else {
+ ent->client->airOutTime = level.time + 12000;
+ ent->damage = 2;
+ }
+
+ //
+ // check for sizzle damage (move to pmove?)
+ //
+ if (waterlevel &&
+ (ent->watertype&(CONTENTS_LAVA|CONTENTS_SLIME)) ) {
+ if (ent->health > 0
+ && ent->pain_debounce_time <= level.time ) {
+
+ if ( envirosuit ) {
+ G_AddEvent( ent, EV_POWERUP_BATTLESUIT, 0 );
+ } else {
+ if (ent->watertype & CONTENTS_LAVA) {
+ G_Damage (ent, NULL, NULL, NULL, NULL,
+ 30*waterlevel, 0, MOD_LAVA);
+ }
+
+ if (ent->watertype & CONTENTS_SLIME) {
+ G_Damage (ent, NULL, NULL, NULL, NULL,
+ 10*waterlevel, 0, MOD_SLIME);
+ }
+ }
+ }
+ }
+}
+
+
+
+/*
+===============
+G_SetClientSound
+===============
+*/
+void G_SetClientSound( gentity_t *ent ) {
+#ifdef MISSIONPACK
+ if( ent->s.eFlags & EF_TICKING ) {
+ ent->client->ps.loopSound = G_SoundIndex( "sound/weapons/proxmine/wstbtick.wav");
+ }
+ else
+#endif
+ if (ent->waterlevel && (ent->watertype&(CONTENTS_LAVA|CONTENTS_SLIME)) ) {
+ ent->client->ps.loopSound = level.snd_fry;
+ } else {
+ ent->client->ps.loopSound = 0;
+ }
+}
+
+
+
+//==============================================================
+
+/*
+==============
+ClientImpacts
+==============
+*/
+void ClientImpacts( gentity_t *ent, pmove_t *pm ) {
+ int i, j;
+ trace_t trace;
+ gentity_t *other;
+
+ memset( &trace, 0, sizeof( trace ) );
+ for (i=0 ; i<pm->numtouch ; i++) {
+ for (j=0 ; j<i ; j++) {
+ if (pm->touchents[j] == pm->touchents[i] ) {
+ break;
+ }
+ }
+ if (j != i) {
+ continue; // duplicated
+ }
+ other = &g_entities[ pm->touchents[i] ];
+
+ if ( ( ent->r.svFlags & SVF_BOT ) && ( ent->touch ) ) {
+ ent->touch( ent, other, &trace );
+ }
+
+ if ( !other->touch ) {
+ continue;
+ }
+
+ other->touch( other, ent, &trace );
+ }
+
+}
+
+/*
+============
+G_TouchTriggers
+
+Find all trigger entities that ent's current position touches.
+Spectators will only interact with teleporters.
+============
+*/
+void G_TouchTriggers( gentity_t *ent ) {
+ int i, num;
+ int touch[MAX_GENTITIES];
+ gentity_t *hit;
+ trace_t trace;
+ vec3_t mins, maxs;
+ static vec3_t range = { 40, 40, 52 };
+
+ if ( !ent->client ) {
+ return;
+ }
+
+ // dead clients don't activate triggers!
+ if ( ent->client->ps.stats[STAT_HEALTH] <= 0 ) {
+ return;
+ }
+
+ VectorSubtract( ent->client->ps.origin, range, mins );
+ VectorAdd( ent->client->ps.origin, range, maxs );
+
+ num = trap_EntitiesInBox( mins, maxs, touch, MAX_GENTITIES );
+
+ // can't use ent->absmin, because that has a one unit pad
+ VectorAdd( ent->client->ps.origin, ent->r.mins, mins );
+ VectorAdd( ent->client->ps.origin, ent->r.maxs, maxs );
+
+ for ( i=0 ; i<num ; i++ ) {
+ hit = &g_entities[touch[i]];
+
+ if ( !hit->touch && !ent->touch ) {
+ continue;
+ }
+ if ( !( hit->r.contents & CONTENTS_TRIGGER ) ) {
+ continue;
+ }
+
+ // ignore most entities if a spectator
+ if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) {
+ if ( hit->s.eType != ET_TELEPORT_TRIGGER &&
+ // this is ugly but adding a new ET_? type will
+ // most likely cause network incompatibilities
+ hit->touch != Touch_DoorTrigger) {
+ continue;
+ }
+ }
+
+ // use seperate code for determining if an item is picked up
+ // so you don't have to actually contact its bounding box
+ if ( hit->s.eType == ET_ITEM ) {
+ if ( !BG_PlayerTouchesItem( &ent->client->ps, &hit->s, level.time ) ) {
+ continue;
+ }
+ } else {
+ if ( !trap_EntityContact( mins, maxs, hit ) ) {
+ continue;
+ }
+ }
+
+ memset( &trace, 0, sizeof(trace) );
+
+ if ( hit->touch ) {
+ hit->touch (hit, ent, &trace);
+ }
+
+ if ( ( ent->r.svFlags & SVF_BOT ) && ( ent->touch ) ) {
+ ent->touch( ent, hit, &trace );
+ }
+ }
+
+ // if we didn't touch a jump pad this pmove frame
+ if ( ent->client->ps.jumppad_frame != ent->client->ps.pmove_framecount ) {
+ ent->client->ps.jumppad_frame = 0;
+ ent->client->ps.jumppad_ent = 0;
+ }
+}
+
+/*
+=================
+SpectatorThink
+=================
+*/
+void SpectatorThink( gentity_t *ent, usercmd_t *ucmd ) {
+ pmove_t pm;
+ gclient_t *client;
+
+ client = ent->client;
+
+ if ( client->sess.spectatorState != SPECTATOR_FOLLOW ) {
+ client->ps.pm_type = PM_SPECTATOR;
+ client->ps.speed = 400; // faster than normal
+
+ // set up for pmove
+ memset (&pm, 0, sizeof(pm));
+ pm.ps = &client->ps;
+ pm.cmd = *ucmd;
+ pm.tracemask = MASK_PLAYERSOLID & ~CONTENTS_BODY; // spectators can fly through bodies
+ pm.trace = trap_Trace;
+ pm.pointcontents = trap_PointContents;
+
+ // perform a pmove
+ Pmove (&pm);
+ // save results of pmove
+ VectorCopy( client->ps.origin, ent->s.origin );
+
+ G_TouchTriggers( ent );
+ trap_UnlinkEntity( ent );
+ }
+
+ client->oldbuttons = client->buttons;
+ client->buttons = ucmd->buttons;
+
+ // attack button cycles through spectators
+ if ( ( client->buttons & BUTTON_ATTACK ) && ! ( client->oldbuttons & BUTTON_ATTACK ) ) {
+ Cmd_FollowCycle_f( ent, 1 );
+ }
+}
+
+
+
+/*
+=================
+ClientInactivityTimer
+
+Returns qfalse if the client is dropped
+=================
+*/
+qboolean ClientInactivityTimer( gclient_t *client ) {
+ if ( ! g_inactivity.integer ) {
+ // give everyone some time, so if the operator sets g_inactivity during
+ // gameplay, everyone isn't kicked
+ client->inactivityTime = level.time + 60 * 1000;
+ client->inactivityWarning = qfalse;
+ } else if ( client->pers.cmd.forwardmove ||
+ client->pers.cmd.rightmove ||
+ client->pers.cmd.upmove ||
+ (client->pers.cmd.buttons & BUTTON_ATTACK) ) {
+ client->inactivityTime = level.time + g_inactivity.integer * 1000;
+ client->inactivityWarning = qfalse;
+ } else if ( !client->pers.localClient ) {
+ if ( level.time > client->inactivityTime ) {
+ trap_DropClient( client - level.clients, "Dropped due to inactivity" );
+ return qfalse;
+ }
+ if ( level.time > client->inactivityTime - 10000 && !client->inactivityWarning ) {
+ client->inactivityWarning = qtrue;
+ trap_SendServerCommand( client - level.clients, "cp \"Ten seconds until inactivity drop!\n\"" );
+ }
+ }
+ return qtrue;
+}
+
+/*
+==================
+ClientTimerActions
+
+Actions that happen once a second
+==================
+*/
+void ClientTimerActions( gentity_t *ent, int msec ) {
+ gclient_t *client;
+#ifdef MISSIONPACK
+ int maxHealth;
+#endif
+
+ client = ent->client;
+ client->timeResidual += msec;
+
+ while ( client->timeResidual >= 1000 ) {
+ client->timeResidual -= 1000;
+
+ // regenerate
+#ifdef MISSIONPACK
+ if( bg_itemlist[client->ps.stats[STAT_PERSISTANT_POWERUP]].giTag == PW_GUARD ) {
+ maxHealth = client->ps.stats[STAT_MAX_HEALTH] / 2;
+ }
+ else if ( client->ps.powerups[PW_REGEN] ) {
+ maxHealth = client->ps.stats[STAT_MAX_HEALTH];
+ }
+ else {
+ maxHealth = 0;
+ }
+ if( maxHealth ) {
+ if ( ent->health < maxHealth ) {
+ ent->health += 15;
+ if ( ent->health > maxHealth * 1.1 ) {
+ ent->health = maxHealth * 1.1;
+ }
+ G_AddEvent( ent, EV_POWERUP_REGEN, 0 );
+ } else if ( ent->health < maxHealth * 2) {
+ ent->health += 5;
+ if ( ent->health > maxHealth * 2 ) {
+ ent->health = maxHealth * 2;
+ }
+ G_AddEvent( ent, EV_POWERUP_REGEN, 0 );
+ }
+#else
+ if ( client->ps.powerups[PW_REGEN] ) {
+ if ( ent->health < client->ps.stats[STAT_MAX_HEALTH]) {
+ ent->health += 15;
+ if ( ent->health > client->ps.stats[STAT_MAX_HEALTH] * 1.1 ) {
+ ent->health = client->ps.stats[STAT_MAX_HEALTH] * 1.1;
+ }
+ G_AddEvent( ent, EV_POWERUP_REGEN, 0 );
+ } else if ( ent->health < client->ps.stats[STAT_MAX_HEALTH] * 2) {
+ ent->health += 5;
+ if ( ent->health > client->ps.stats[STAT_MAX_HEALTH] * 2 ) {
+ ent->health = client->ps.stats[STAT_MAX_HEALTH] * 2;
+ }
+ G_AddEvent( ent, EV_POWERUP_REGEN, 0 );
+ }
+#endif
+ } else {
+ // count down health when over max
+ if ( ent->health > client->ps.stats[STAT_MAX_HEALTH] ) {
+ ent->health--;
+ }
+ }
+
+ // count down armor when over max
+ if ( client->ps.stats[STAT_ARMOR] > client->ps.stats[STAT_MAX_HEALTH] ) {
+ client->ps.stats[STAT_ARMOR]--;
+ }
+ }
+#ifdef MISSIONPACK
+ if( bg_itemlist[client->ps.stats[STAT_PERSISTANT_POWERUP]].giTag == PW_AMMOREGEN ) {
+ int w, max, inc, t, i;
+ int weapList[]={WP_MACHINEGUN,WP_SHOTGUN,WP_GRENADE_LAUNCHER,WP_ROCKET_LAUNCHER,WP_LIGHTNING,WP_RAILGUN,WP_PLASMAGUN,WP_BFG,WP_NAILGUN,WP_PROX_LAUNCHER,WP_CHAINGUN};
+ int weapCount = sizeof(weapList) / sizeof(int);
+ //
+ for (i = 0; i < weapCount; i++) {
+ w = weapList[i];
+
+ switch(w) {
+ case WP_MACHINEGUN: max = 50; inc = 4; t = 1000; break;
+ case WP_SHOTGUN: max = 10; inc = 1; t = 1500; break;
+ case WP_GRENADE_LAUNCHER: max = 10; inc = 1; t = 2000; break;
+ case WP_ROCKET_LAUNCHER: max = 10; inc = 1; t = 1750; break;
+ case WP_LIGHTNING: max = 50; inc = 5; t = 1500; break;
+ case WP_RAILGUN: max = 10; inc = 1; t = 1750; break;
+ case WP_PLASMAGUN: max = 50; inc = 5; t = 1500; break;
+ case WP_BFG: max = 10; inc = 1; t = 4000; break;
+ case WP_NAILGUN: max = 10; inc = 1; t = 1250; break;
+ case WP_PROX_LAUNCHER: max = 5; inc = 1; t = 2000; break;
+ case WP_CHAINGUN: max = 100; inc = 5; t = 1000; break;
+ default: max = 0; inc = 0; t = 1000; break;
+ }
+ client->ammoTimes[w] += msec;
+ if ( client->ps.ammo[w] >= max ) {
+ client->ammoTimes[w] = 0;
+ }
+ if ( client->ammoTimes[w] >= t ) {
+ while ( client->ammoTimes[w] >= t )
+ client->ammoTimes[w] -= t;
+ client->ps.ammo[w] += inc;
+ if ( client->ps.ammo[w] > max ) {
+ client->ps.ammo[w] = max;
+ }
+ }
+ }
+ }
+#endif
+}
+
+/*
+====================
+ClientIntermissionThink
+====================
+*/
+void ClientIntermissionThink( gclient_t *client ) {
+ client->ps.eFlags &= ~EF_TALK;
+ client->ps.eFlags &= ~EF_FIRING;
+
+ // the level will exit when everyone wants to or after timeouts
+
+ // swap and latch button actions
+ client->oldbuttons = client->buttons;
+ client->buttons = client->pers.cmd.buttons;
+ if ( client->buttons & ( BUTTON_ATTACK | BUTTON_USE_HOLDABLE ) & ( client->oldbuttons ^ client->buttons ) ) {
+ // this used to be an ^1 but once a player says ready, it should stick
+ client->readyToExit = 1;
+ }
+}
+
+
+/*
+================
+ClientEvents
+
+Events will be passed on to the clients for presentation,
+but any server game effects are handled here
+================
+*/
+void ClientEvents( gentity_t *ent, int oldEventSequence ) {
+ int i, j;
+ int event;
+ gclient_t *client;
+ int damage;
+ vec3_t dir;
+ vec3_t origin, angles;
+// qboolean fired;
+ gitem_t *item;
+ gentity_t *drop;
+
+ client = ent->client;
+
+ if ( oldEventSequence < client->ps.eventSequence - MAX_PS_EVENTS ) {
+ oldEventSequence = client->ps.eventSequence - MAX_PS_EVENTS;
+ }
+ for ( i = oldEventSequence ; i < client->ps.eventSequence ; i++ ) {
+ event = client->ps.events[ i & (MAX_PS_EVENTS-1) ];
+
+ switch ( event ) {
+ case EV_FALL_MEDIUM:
+ case EV_FALL_FAR:
+ if ( ent->s.eType != ET_PLAYER ) {
+ break; // not in the player model
+ }
+ if ( g_dmflags.integer & DF_NO_FALLING ) {
+ break;
+ }
+ if ( event == EV_FALL_FAR ) {
+ damage = 10;
+ } else {
+ damage = 5;
+ }
+ VectorSet (dir, 0, 0, 1);
+ ent->pain_debounce_time = level.time + 200; // no normal pain sound
+ G_Damage (ent, NULL, NULL, NULL, NULL, damage, 0, MOD_FALLING);
+ break;
+
+ case EV_FIRE_WEAPON:
+ FireWeapon( ent );
+ break;
+
+ case EV_USE_ITEM1: // teleporter
+ // drop flags in CTF
+ item = NULL;
+ j = 0;
+
+ if ( ent->client->ps.powerups[ PW_REDFLAG ] ) {
+ item = BG_FindItemForPowerup( PW_REDFLAG );
+ j = PW_REDFLAG;
+ } else if ( ent->client->ps.powerups[ PW_BLUEFLAG ] ) {
+ item = BG_FindItemForPowerup( PW_BLUEFLAG );
+ j = PW_BLUEFLAG;
+ } else if ( ent->client->ps.powerups[ PW_NEUTRALFLAG ] ) {
+ item = BG_FindItemForPowerup( PW_NEUTRALFLAG );
+ j = PW_NEUTRALFLAG;
+ }
+
+ if ( item ) {
+ drop = Drop_Item( ent, item, 0 );
+ // decide how many seconds it has left
+ drop->count = ( ent->client->ps.powerups[ j ] - level.time ) / 1000;
+ if ( drop->count < 1 ) {
+ drop->count = 1;
+ }
+
+ ent->client->ps.powerups[ j ] = 0;
+ }
+
+#ifdef MISSIONPACK
+ if ( g_gametype.integer == GT_HARVESTER ) {
+ if ( ent->client->ps.generic1 > 0 ) {
+ if ( ent->client->sess.sessionTeam == TEAM_RED ) {
+ item = BG_FindItem( "Blue Cube" );
+ } else {
+ item = BG_FindItem( "Red Cube" );
+ }
+ if ( item ) {
+ for ( j = 0; j < ent->client->ps.generic1; j++ ) {
+ drop = Drop_Item( ent, item, 0 );
+ if ( ent->client->sess.sessionTeam == TEAM_RED ) {
+ drop->spawnflags = TEAM_BLUE;
+ } else {
+ drop->spawnflags = TEAM_RED;
+ }
+ }
+ }
+ ent->client->ps.generic1 = 0;
+ }
+ }
+#endif
+ SelectSpawnPoint( ent->client->ps.origin, origin, angles );
+ TeleportPlayer( ent, origin, angles );
+ break;
+
+ case EV_USE_ITEM2: // medkit
+ ent->health = ent->client->ps.stats[STAT_MAX_HEALTH] + 25;
+
+ break;
+
+#ifdef MISSIONPACK
+ case EV_USE_ITEM3: // kamikaze
+ // make sure the invulnerability is off
+ ent->client->invulnerabilityTime = 0;
+ // start the kamikze
+ G_StartKamikaze( ent );
+ break;
+
+ case EV_USE_ITEM4: // portal
+ if( ent->client->portalID ) {
+ DropPortalSource( ent );
+ }
+ else {
+ DropPortalDestination( ent );
+ }
+ break;
+ case EV_USE_ITEM5: // invulnerability
+ ent->client->invulnerabilityTime = level.time + 10000;
+ break;
+#endif
+
+ default:
+ break;
+ }
+ }
+
+}
+
+#ifdef MISSIONPACK
+/*
+==============
+StuckInOtherClient
+==============
+*/
+static int StuckInOtherClient(gentity_t *ent) {
+ int i;
+ gentity_t *ent2;
+
+ ent2 = &g_entities[0];
+ for ( i = 0; i < MAX_CLIENTS; i++, ent2++ ) {
+ if ( ent2 == ent ) {
+ continue;
+ }
+ if ( !ent2->inuse ) {
+ continue;
+ }
+ if ( !ent2->client ) {
+ continue;
+ }
+ if ( ent2->health <= 0 ) {
+ continue;
+ }
+ //
+ if (ent2->r.absmin[0] > ent->r.absmax[0])
+ continue;
+ if (ent2->r.absmin[1] > ent->r.absmax[1])
+ continue;
+ if (ent2->r.absmin[2] > ent->r.absmax[2])
+ continue;
+ if (ent2->r.absmax[0] < ent->r.absmin[0])
+ continue;
+ if (ent2->r.absmax[1] < ent->r.absmin[1])
+ continue;
+ if (ent2->r.absmax[2] < ent->r.absmin[2])
+ continue;
+ return qtrue;
+ }
+ return qfalse;
+}
+#endif
+
+void BotTestSolid(vec3_t origin);
+
+/*
+==============
+SendPendingPredictableEvents
+==============
+*/
+void SendPendingPredictableEvents( playerState_t *ps ) {
+ gentity_t *t;
+ int event, seq;
+ int extEvent, number;
+
+ // if there are still events pending
+ if ( ps->entityEventSequence < ps->eventSequence ) {
+ // create a temporary entity for this event which is sent to everyone
+ // except the client who generated the event
+ seq = ps->entityEventSequence & (MAX_PS_EVENTS-1);
+ event = ps->events[ seq ] | ( ( ps->entityEventSequence & 3 ) << 8 );
+ // set external event to zero before calling BG_PlayerStateToEntityState
+ extEvent = ps->externalEvent;
+ ps->externalEvent = 0;
+ // create temporary entity for event
+ t = G_TempEntity( ps->origin, event );
+ number = t->s.number;
+ BG_PlayerStateToEntityState( ps, &t->s, qtrue );
+ t->s.number = number;
+ t->s.eType = ET_EVENTS + event;
+ t->s.eFlags |= EF_PLAYER_EVENT;
+ t->s.otherEntityNum = ps->clientNum;
+ // send to everyone except the client who generated the event
+ t->r.svFlags |= SVF_NOTSINGLECLIENT;
+ t->r.singleClient = ps->clientNum;
+ // set back external event
+ ps->externalEvent = extEvent;
+ }
+}
+
+/*
+==============
+ClientThink
+
+This will be called once for each client frame, which will
+usually be a couple times for each server frame on fast clients.
+
+If "g_synchronousClients 1" is set, this will be called exactly
+once for each server frame, which makes for smooth demo recording.
+==============
+*/
+void ClientThink_real( gentity_t *ent ) {
+ gclient_t *client;
+ pmove_t pm;
+ int oldEventSequence;
+ int msec;
+ usercmd_t *ucmd;
+
+ client = ent->client;
+
+ // don't think if the client is not yet connected (and thus not yet spawned in)
+ if (client->pers.connected != CON_CONNECTED) {
+ return;
+ }
+ // mark the time, so the connection sprite can be removed
+ ucmd = &ent->client->pers.cmd;
+
+ // sanity check the command time to prevent speedup cheating
+ if ( ucmd->serverTime > level.time + 200 ) {
+ ucmd->serverTime = level.time + 200;
+// G_Printf("serverTime <<<<<\n" );
+ }
+ if ( ucmd->serverTime < level.time - 1000 ) {
+ ucmd->serverTime = level.time - 1000;
+// G_Printf("serverTime >>>>>\n" );
+ }
+
+ msec = ucmd->serverTime - client->ps.commandTime;
+ // following others may result in bad times, but we still want
+ // to check for follow toggles
+ if ( msec < 1 && client->sess.spectatorState != SPECTATOR_FOLLOW ) {
+ return;
+ }
+ if ( msec > 200 ) {
+ msec = 200;
+ }
+
+ if ( pmove_msec.integer < 8 ) {
+ trap_Cvar_Set("pmove_msec", "8");
+ }
+ else if (pmove_msec.integer > 33) {
+ trap_Cvar_Set("pmove_msec", "33");
+ }
+
+ if ( pmove_fixed.integer || client->pers.pmoveFixed ) {
+ ucmd->serverTime = ((ucmd->serverTime + pmove_msec.integer-1) / pmove_msec.integer) * pmove_msec.integer;
+ //if (ucmd->serverTime - client->ps.commandTime <= 0)
+ // return;
+ }
+
+ //
+ // check for exiting intermission
+ //
+ if ( level.intermissiontime ) {
+ ClientIntermissionThink( client );
+ return;
+ }
+
+ // spectators don't do much
+ if ( client->sess.sessionTeam == TEAM_SPECTATOR ) {
+ if ( client->sess.spectatorState == SPECTATOR_SCOREBOARD ) {
+ return;
+ }
+ SpectatorThink( ent, ucmd );
+ return;
+ }
+
+ // check for inactivity timer, but never drop the local client of a non-dedicated server
+ if ( !ClientInactivityTimer( client ) ) {
+ return;
+ }
+
+ // clear the rewards if time
+ if ( level.time > client->rewardTime ) {
+ client->ps.eFlags &= ~(EF_AWARD_IMPRESSIVE | EF_AWARD_EXCELLENT | EF_AWARD_GAUNTLET | EF_AWARD_ASSIST | EF_AWARD_DEFEND | EF_AWARD_CAP );
+ }
+
+ if ( client->noclip ) {
+ client->ps.pm_type = PM_NOCLIP;
+ } else if ( client->ps.stats[STAT_HEALTH] <= 0 ) {
+ client->ps.pm_type = PM_DEAD;
+ } else {
+ client->ps.pm_type = PM_NORMAL;
+ }
+
+ client->ps.gravity = g_gravity.value;
+
+ // set speed
+ client->ps.speed = g_speed.value;
+
+#ifdef MISSIONPACK
+ if( bg_itemlist[client->ps.stats[STAT_PERSISTANT_POWERUP]].giTag == PW_SCOUT ) {
+ client->ps.speed *= 1.5;
+ }
+ else
+#endif
+ if ( client->ps.powerups[PW_HASTE] ) {
+ client->ps.speed *= 1.3;
+ }
+
+ // Let go of the hook if we aren't firing
+ if ( client->ps.weapon == WP_GRAPPLING_HOOK &&
+ client->hook && !( ucmd->buttons & BUTTON_ATTACK ) ) {
+ Weapon_HookFree(client->hook);
+ }
+
+ // set up for pmove
+ oldEventSequence = client->ps.eventSequence;
+
+ memset (&pm, 0, sizeof(pm));
+
+ // check for the hit-scan gauntlet, don't let the action
+ // go through as an attack unless it actually hits something
+ if ( client->ps.weapon == WP_GAUNTLET && !( ucmd->buttons & BUTTON_TALK ) &&
+ ( ucmd->buttons & BUTTON_ATTACK ) && client->ps.weaponTime <= 0 ) {
+ pm.gauntletHit = CheckGauntletAttack( ent );
+ }
+
+ if ( ent->flags & FL_FORCE_GESTURE ) {
+ ent->flags &= ~FL_FORCE_GESTURE;
+ ent->client->pers.cmd.buttons |= BUTTON_GESTURE;
+ }
+
+#ifdef MISSIONPACK
+ // check for invulnerability expansion before doing the Pmove
+ if (client->ps.powerups[PW_INVULNERABILITY] ) {
+ if ( !(client->ps.pm_flags & PMF_INVULEXPAND) ) {
+ vec3_t mins = { -42, -42, -42 };
+ vec3_t maxs = { 42, 42, 42 };
+ vec3_t oldmins, oldmaxs;
+
+ VectorCopy (ent->r.mins, oldmins);
+ VectorCopy (ent->r.maxs, oldmaxs);
+ // expand
+ VectorCopy (mins, ent->r.mins);
+ VectorCopy (maxs, ent->r.maxs);
+ trap_LinkEntity(ent);
+ // check if this would get anyone stuck in this player
+ if ( !StuckInOtherClient(ent) ) {
+ // set flag so the expanded size will be set in PM_CheckDuck
+ client->ps.pm_flags |= PMF_INVULEXPAND;
+ }
+ // set back
+ VectorCopy (oldmins, ent->r.mins);
+ VectorCopy (oldmaxs, ent->r.maxs);
+ trap_LinkEntity(ent);
+ }
+ }
+#endif
+
+ pm.ps = &client->ps;
+ pm.cmd = *ucmd;
+ if ( pm.ps->pm_type == PM_DEAD ) {
+ pm.tracemask = MASK_PLAYERSOLID & ~CONTENTS_BODY;
+ }
+ else if ( ent->r.svFlags & SVF_BOT ) {
+ pm.tracemask = MASK_PLAYERSOLID | CONTENTS_BOTCLIP;
+ }
+ else {
+ pm.tracemask = MASK_PLAYERSOLID;
+ }
+ pm.trace = trap_Trace;
+ pm.pointcontents = trap_PointContents;
+ pm.debugLevel = g_debugMove.integer;
+ pm.noFootsteps = ( g_dmflags.integer & DF_NO_FOOTSTEPS ) > 0;
+
+ pm.pmove_fixed = pmove_fixed.integer | client->pers.pmoveFixed;
+ pm.pmove_msec = pmove_msec.integer;
+
+ VectorCopy( client->ps.origin, client->oldOrigin );
+
+#ifdef MISSIONPACK
+ if (level.intermissionQueued != 0 && g_singlePlayer.integer) {
+ if ( level.time - level.intermissionQueued >= 1000 ) {
+ pm.cmd.buttons = 0;
+ pm.cmd.forwardmove = 0;
+ pm.cmd.rightmove = 0;
+ pm.cmd.upmove = 0;
+ if ( level.time - level.intermissionQueued >= 2000 && level.time - level.intermissionQueued <= 2500 ) {
+ trap_SendConsoleCommand( EXEC_APPEND, "centerview\n");
+ }
+ ent->client->ps.pm_type = PM_SPINTERMISSION;
+ }
+ }
+ Pmove (&pm);
+#else
+ Pmove (&pm);
+#endif
+
+ // save results of pmove
+ if ( ent->client->ps.eventSequence != oldEventSequence ) {
+ ent->eventTime = level.time;
+ }
+ if (g_smoothClients.integer) {
+ BG_PlayerStateToEntityStateExtraPolate( &ent->client->ps, &ent->s, ent->client->ps.commandTime, qtrue );
+ }
+ else {
+ BG_PlayerStateToEntityState( &ent->client->ps, &ent->s, qtrue );
+ }
+ SendPendingPredictableEvents( &ent->client->ps );
+
+ if ( !( ent->client->ps.eFlags & EF_FIRING ) ) {
+ client->fireHeld = qfalse; // for grapple
+ }
+
+ // use the snapped origin for linking so it matches client predicted versions
+ VectorCopy( ent->s.pos.trBase, ent->r.currentOrigin );
+
+ VectorCopy (pm.mins, ent->r.mins);
+ VectorCopy (pm.maxs, ent->r.maxs);
+
+ ent->waterlevel = pm.waterlevel;
+ ent->watertype = pm.watertype;
+
+ // execute client events
+ ClientEvents( ent, oldEventSequence );
+
+ // link entity now, after any personal teleporters have been used
+ trap_LinkEntity (ent);
+ if ( !ent->client->noclip ) {
+ G_TouchTriggers( ent );
+ }
+
+ // NOTE: now copy the exact origin over otherwise clients can be snapped into solid
+ VectorCopy( ent->client->ps.origin, ent->r.currentOrigin );
+
+ //test for solid areas in the AAS file
+ BotTestAAS(ent->r.currentOrigin);
+
+ // touch other objects
+ ClientImpacts( ent, &pm );
+
+ // save results of triggers and client events
+ if (ent->client->ps.eventSequence != oldEventSequence) {
+ ent->eventTime = level.time;
+ }
+
+ // swap and latch button actions
+ client->oldbuttons = client->buttons;
+ client->buttons = ucmd->buttons;
+ client->latched_buttons |= client->buttons & ~client->oldbuttons;
+
+ // check for respawning
+ if ( client->ps.stats[STAT_HEALTH] <= 0 ) {
+ // wait for the attack button to be pressed
+ if ( level.time > client->respawnTime ) {
+ // forcerespawn is to prevent users from waiting out powerups
+ if ( g_forcerespawn.integer > 0 &&
+ ( level.time - client->respawnTime ) > g_forcerespawn.integer * 1000 ) {
+ respawn( ent );
+ return;
+ }
+
+ // pressing attack or use is the normal respawn method
+ if ( ucmd->buttons & ( BUTTON_ATTACK | BUTTON_USE_HOLDABLE ) ) {
+ respawn( ent );
+ }
+ }
+ return;
+ }
+
+ // perform once-a-second actions
+ ClientTimerActions( ent, msec );
+}
+
+/*
+==================
+ClientThink
+
+A new command has arrived from the client
+==================
+*/
+void ClientThink( int clientNum ) {
+ gentity_t *ent;
+
+ ent = g_entities + clientNum;
+ trap_GetUsercmd( clientNum, &ent->client->pers.cmd );
+
+ // mark the time we got info, so we can display the
+ // phone jack if they don't get any for a while
+ ent->client->lastCmdTime = level.time;
+
+ if ( !(ent->r.svFlags & SVF_BOT) && !g_synchronousClients.integer ) {
+ ClientThink_real( ent );
+ }
+}
+
+
+void G_RunClient( gentity_t *ent ) {
+ if ( !(ent->r.svFlags & SVF_BOT) && !g_synchronousClients.integer ) {
+ return;
+ }
+ ent->client->pers.cmd.serverTime = level.time;
+ ClientThink_real( ent );
+}
+
+
+/*
+==================
+SpectatorClientEndFrame
+
+==================
+*/
+void SpectatorClientEndFrame( gentity_t *ent ) {
+ gclient_t *cl;
+
+ // if we are doing a chase cam or a remote view, grab the latest info
+ if ( ent->client->sess.spectatorState == SPECTATOR_FOLLOW ) {
+ int clientNum, flags;
+
+ clientNum = ent->client->sess.spectatorClient;
+
+ // team follow1 and team follow2 go to whatever clients are playing
+ if ( clientNum == -1 ) {
+ clientNum = level.follow1;
+ } else if ( clientNum == -2 ) {
+ clientNum = level.follow2;
+ }
+ if ( clientNum >= 0 ) {
+ cl = &level.clients[ clientNum ];
+ if ( cl->pers.connected == CON_CONNECTED && cl->sess.sessionTeam != TEAM_SPECTATOR ) {
+ flags = (cl->ps.eFlags & ~(EF_VOTED | EF_TEAMVOTED)) | (ent->client->ps.eFlags & (EF_VOTED | EF_TEAMVOTED));
+ ent->client->ps = cl->ps;
+ ent->client->ps.pm_flags |= PMF_FOLLOW;
+ ent->client->ps.eFlags = flags;
+ return;
+ } else {
+ // drop them to free spectators unless they are dedicated camera followers
+ if ( ent->client->sess.spectatorClient >= 0 ) {
+ ent->client->sess.spectatorState = SPECTATOR_FREE;
+ ClientBegin( ent->client - level.clients );
+ }
+ }
+ }
+ }
+
+ if ( ent->client->sess.spectatorState == SPECTATOR_SCOREBOARD ) {
+ ent->client->ps.pm_flags |= PMF_SCOREBOARD;
+ } else {
+ ent->client->ps.pm_flags &= ~PMF_SCOREBOARD;
+ }
+}
+
+/*
+==============
+ClientEndFrame
+
+Called at the end of each server frame for each connected client
+A fast client will have multiple ClientThink for each ClientEdFrame,
+while a slow client may have multiple ClientEndFrame between ClientThink.
+==============
+*/
+void ClientEndFrame( gentity_t *ent ) {
+ int i;
+ clientPersistant_t *pers;
+
+ if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) {
+ SpectatorClientEndFrame( ent );
+ return;
+ }
+
+ pers = &ent->client->pers;
+
+ // turn off any expired powerups
+ for ( i = 0 ; i < MAX_POWERUPS ; i++ ) {
+ if ( ent->client->ps.powerups[ i ] < level.time ) {
+ ent->client->ps.powerups[ i ] = 0;
+ }
+ }
+
+#ifdef MISSIONPACK
+ // set powerup for player animation
+ if( bg_itemlist[ent->client->ps.stats[STAT_PERSISTANT_POWERUP]].giTag == PW_GUARD ) {
+ ent->client->ps.powerups[PW_GUARD] = level.time;
+ }
+ if( bg_itemlist[ent->client->ps.stats[STAT_PERSISTANT_POWERUP]].giTag == PW_SCOUT ) {
+ ent->client->ps.powerups[PW_SCOUT] = level.time;
+ }
+ if( bg_itemlist[ent->client->ps.stats[STAT_PERSISTANT_POWERUP]].giTag == PW_DOUBLER ) {
+ ent->client->ps.powerups[PW_DOUBLER] = level.time;
+ }
+ if( bg_itemlist[ent->client->ps.stats[STAT_PERSISTANT_POWERUP]].giTag == PW_AMMOREGEN ) {
+ ent->client->ps.powerups[PW_AMMOREGEN] = level.time;
+ }
+ if ( ent->client->invulnerabilityTime > level.time ) {
+ ent->client->ps.powerups[PW_INVULNERABILITY] = level.time;
+ }
+#endif
+
+ // save network bandwidth
+#if 0
+ if ( !g_synchronousClients->integer && ent->client->ps.pm_type == PM_NORMAL ) {
+ // FIXME: this must change eventually for non-sync demo recording
+ VectorClear( ent->client->ps.viewangles );
+ }
+#endif
+
+ //
+ // If the end of unit layout is displayed, don't give
+ // the player any normal movement attributes
+ //
+ if ( level.intermissiontime ) {
+ return;
+ }
+
+ // burn from lava, etc
+ P_WorldEffects (ent);
+
+ // apply all the damage taken this frame
+ P_DamageFeedback (ent);
+
+ // add the EF_CONNECTION flag if we haven't gotten commands recently
+ if ( level.time - ent->client->lastCmdTime > 1000 ) {
+ ent->s.eFlags |= EF_CONNECTION;
+ } else {
+ ent->s.eFlags &= ~EF_CONNECTION;
+ }
+
+ ent->client->ps.stats[STAT_HEALTH] = ent->health; // FIXME: get rid of ent->health...
+
+ G_SetClientSound (ent);
+
+ // set the latest infor
+ if (g_smoothClients.integer) {
+ BG_PlayerStateToEntityStateExtraPolate( &ent->client->ps, &ent->s, ent->client->ps.commandTime, qtrue );
+ }
+ else {
+ BG_PlayerStateToEntityState( &ent->client->ps, &ent->s, qtrue );
+ }
+ SendPendingPredictableEvents( &ent->client->ps );
+
+ // set the bit for the reachability area the client is currently in
+// i = trap_AAS_PointReachabilityAreaIndex( ent->client->ps.origin );
+// ent->client->areabits[i >> 3] |= 1 << (i & 7);
+}
+
+
diff --git a/code/game/g_arenas.c b/code/game/g_arenas.c
new file mode 100755
index 0000000..1e6476b
--- /dev/null
+++ b/code/game/g_arenas.c
@@ -0,0 +1,376 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+//
+// g_arenas.c
+//
+
+#include "g_local.h"
+
+
+gentity_t *podium1;
+gentity_t *podium2;
+gentity_t *podium3;
+
+
+/*
+==================
+UpdateTournamentInfo
+==================
+*/
+void UpdateTournamentInfo( void ) {
+ int i;
+ gentity_t *player;
+ int playerClientNum;
+ int n, accuracy, perfect, msglen;
+ int buflen;
+#ifdef MISSIONPACK // bk001205
+ int score1, score2;
+ qboolean won;
+#endif
+ char buf[32];
+ char msg[MAX_STRING_CHARS];
+
+ // find the real player
+ player = NULL;
+ for (i = 0; i < level.maxclients; i++ ) {
+ player = &g_entities[i];
+ if ( !player->inuse ) {
+ continue;
+ }
+ if ( !( player->r.svFlags & SVF_BOT ) ) {
+ break;
+ }
+ }
+ // this should never happen!
+ if ( !player || i == level.maxclients ) {
+ return;
+ }
+ playerClientNum = i;
+
+ CalculateRanks();
+
+ if ( level.clients[playerClientNum].sess.sessionTeam == TEAM_SPECTATOR ) {
+#ifdef MISSIONPACK
+ Com_sprintf( msg, sizeof(msg), "postgame %i %i 0 0 0 0 0 0 0 0 0 0 0", level.numNonSpectatorClients, playerClientNum );
+#else
+ Com_sprintf( msg, sizeof(msg), "postgame %i %i 0 0 0 0 0 0", level.numNonSpectatorClients, playerClientNum );
+#endif
+ }
+ else {
+ if( player->client->accuracy_shots ) {
+ accuracy = player->client->accuracy_hits * 100 / player->client->accuracy_shots;
+ }
+ else {
+ accuracy = 0;
+ }
+#ifdef MISSIONPACK
+ won = qfalse;
+ if (g_gametype.integer >= GT_CTF) {
+ score1 = level.teamScores[TEAM_RED];
+ score2 = level.teamScores[TEAM_BLUE];
+ if (level.clients[playerClientNum].sess.sessionTeam == TEAM_RED) {
+ won = (level.teamScores[TEAM_RED] > level.teamScores[TEAM_BLUE]);
+ } else {
+ won = (level.teamScores[TEAM_BLUE] > level.teamScores[TEAM_RED]);
+ }
+ } else {
+ if (&level.clients[playerClientNum] == &level.clients[ level.sortedClients[0] ]) {
+ won = qtrue;
+ score1 = level.clients[ level.sortedClients[0] ].ps.persistant[PERS_SCORE];
+ score2 = level.clients[ level.sortedClients[1] ].ps.persistant[PERS_SCORE];
+ } else {
+ score2 = level.clients[ level.sortedClients[0] ].ps.persistant[PERS_SCORE];
+ score1 = level.clients[ level.sortedClients[1] ].ps.persistant[PERS_SCORE];
+ }
+ }
+ if (won && player->client->ps.persistant[PERS_KILLED] == 0) {
+ perfect = 1;
+ } else {
+ perfect = 0;
+ }
+ Com_sprintf( msg, sizeof(msg), "postgame %i %i %i %i %i %i %i %i %i %i %i %i %i %i", level.numNonSpectatorClients, playerClientNum, accuracy,
+ player->client->ps.persistant[PERS_IMPRESSIVE_COUNT], player->client->ps.persistant[PERS_EXCELLENT_COUNT],player->client->ps.persistant[PERS_DEFEND_COUNT],
+ player->client->ps.persistant[PERS_ASSIST_COUNT], player->client->ps.persistant[PERS_GAUNTLET_FRAG_COUNT], player->client->ps.persistant[PERS_SCORE],
+ perfect, score1, score2, level.time, player->client->ps.persistant[PERS_CAPTURES] );
+
+#else
+ perfect = ( level.clients[playerClientNum].ps.persistant[PERS_RANK] == 0 && player->client->ps.persistant[PERS_KILLED] == 0 ) ? 1 : 0;
+ Com_sprintf( msg, sizeof(msg), "postgame %i %i %i %i %i %i %i %i", level.numNonSpectatorClients, playerClientNum, accuracy,
+ player->client->ps.persistant[PERS_IMPRESSIVE_COUNT], player->client->ps.persistant[PERS_EXCELLENT_COUNT],
+ player->client->ps.persistant[PERS_GAUNTLET_FRAG_COUNT], player->client->ps.persistant[PERS_SCORE],
+ perfect );
+#endif
+ }
+
+ msglen = strlen( msg );
+ for( i = 0; i < level.numNonSpectatorClients; i++ ) {
+ n = level.sortedClients[i];
+ Com_sprintf( buf, sizeof(buf), " %i %i %i", n, level.clients[n].ps.persistant[PERS_RANK], level.clients[n].ps.persistant[PERS_SCORE] );
+ buflen = strlen( buf );
+ if( msglen + buflen + 1 >= sizeof(msg) ) {
+ break;
+ }
+ strcat( msg, buf );
+ }
+ trap_SendConsoleCommand( EXEC_APPEND, msg );
+}
+
+
+static gentity_t *SpawnModelOnVictoryPad( gentity_t *pad, vec3_t offset, gentity_t *ent, int place ) {
+ gentity_t *body;
+ vec3_t vec;
+ vec3_t f, r, u;
+
+ body = G_Spawn();
+ if ( !body ) {
+ G_Printf( S_COLOR_RED "ERROR: out of gentities\n" );
+ return NULL;
+ }
+
+ body->classname = ent->client->pers.netname;
+ body->client = ent->client;
+ body->s = ent->s;
+ body->s.eType = ET_PLAYER; // could be ET_INVISIBLE
+ body->s.eFlags = 0; // clear EF_TALK, etc
+ body->s.powerups = 0; // clear powerups
+ body->s.loopSound = 0; // clear lava burning
+ body->s.number = body - g_entities;
+ body->timestamp = level.time;
+ body->physicsObject = qtrue;
+ body->physicsBounce = 0; // don't bounce
+ body->s.event = 0;
+ body->s.pos.trType = TR_STATIONARY;
+ body->s.groundEntityNum = ENTITYNUM_WORLD;
+ body->s.legsAnim = LEGS_IDLE;
+ body->s.torsoAnim = TORSO_STAND;
+ if( body->s.weapon == WP_NONE ) {
+ body->s.weapon = WP_MACHINEGUN;
+ }
+ if( body->s.weapon == WP_GAUNTLET) {
+ body->s.torsoAnim = TORSO_STAND2;
+ }
+ body->s.event = 0;
+ body->r.svFlags = ent->r.svFlags;
+ VectorCopy (ent->r.mins, body->r.mins);
+ VectorCopy (ent->r.maxs, body->r.maxs);
+ VectorCopy (ent->r.absmin, body->r.absmin);
+ VectorCopy (ent->r.absmax, body->r.absmax);
+ body->clipmask = CONTENTS_SOLID | CONTENTS_PLAYERCLIP;
+ body->r.contents = CONTENTS_BODY;
+ body->r.ownerNum = ent->r.ownerNum;
+ body->takedamage = qfalse;
+
+ VectorSubtract( level.intermission_origin, pad->r.currentOrigin, vec );
+ vectoangles( vec, body->s.apos.trBase );
+ body->s.apos.trBase[PITCH] = 0;
+ body->s.apos.trBase[ROLL] = 0;
+
+ AngleVectors( body->s.apos.trBase, f, r, u );
+ VectorMA( pad->r.currentOrigin, offset[0], f, vec );
+ VectorMA( vec, offset[1], r, vec );
+ VectorMA( vec, offset[2], u, vec );
+
+ G_SetOrigin( body, vec );
+
+ trap_LinkEntity (body);
+
+ body->count = place;
+
+ return body;
+}
+
+
+static void CelebrateStop( gentity_t *player ) {
+ int anim;
+
+ if( player->s.weapon == WP_GAUNTLET) {
+ anim = TORSO_STAND2;
+ }
+ else {
+ anim = TORSO_STAND;
+ }
+ player->s.torsoAnim = ( ( player->s.torsoAnim & ANIM_TOGGLEBIT ) ^ ANIM_TOGGLEBIT ) | anim;
+}
+
+
+#define TIMER_GESTURE (34*66+50)
+static void CelebrateStart( gentity_t *player ) {
+ player->s.torsoAnim = ( ( player->s.torsoAnim & ANIM_TOGGLEBIT ) ^ ANIM_TOGGLEBIT ) | TORSO_GESTURE;
+ player->nextthink = level.time + TIMER_GESTURE;
+ player->think = CelebrateStop;
+
+ /*
+ player->client->ps.events[player->client->ps.eventSequence & (MAX_PS_EVENTS-1)] = EV_TAUNT;
+ player->client->ps.eventParms[player->client->ps.eventSequence & (MAX_PS_EVENTS-1)] = 0;
+ player->client->ps.eventSequence++;
+ */
+ G_AddEvent(player, EV_TAUNT, 0);
+}
+
+
+static vec3_t offsetFirst = {0, 0, 74};
+static vec3_t offsetSecond = {-10, 60, 54};
+static vec3_t offsetThird = {-19, -60, 45};
+
+static void PodiumPlacementThink( gentity_t *podium ) {
+ vec3_t vec;
+ vec3_t origin;
+ vec3_t f, r, u;
+
+ podium->nextthink = level.time + 100;
+
+ AngleVectors( level.intermission_angle, vec, NULL, NULL );
+ VectorMA( level.intermission_origin, trap_Cvar_VariableIntegerValue( "g_podiumDist" ), vec, origin );
+ origin[2] -= trap_Cvar_VariableIntegerValue( "g_podiumDrop" );
+ G_SetOrigin( podium, origin );
+
+ if( podium1 ) {
+ VectorSubtract( level.intermission_origin, podium->r.currentOrigin, vec );
+ vectoangles( vec, podium1->s.apos.trBase );
+ podium1->s.apos.trBase[PITCH] = 0;
+ podium1->s.apos.trBase[ROLL] = 0;
+
+ AngleVectors( podium1->s.apos.trBase, f, r, u );
+ VectorMA( podium->r.currentOrigin, offsetFirst[0], f, vec );
+ VectorMA( vec, offsetFirst[1], r, vec );
+ VectorMA( vec, offsetFirst[2], u, vec );
+
+ G_SetOrigin( podium1, vec );
+ }
+
+ if( podium2 ) {
+ VectorSubtract( level.intermission_origin, podium->r.currentOrigin, vec );
+ vectoangles( vec, podium2->s.apos.trBase );
+ podium2->s.apos.trBase[PITCH] = 0;
+ podium2->s.apos.trBase[ROLL] = 0;
+
+ AngleVectors( podium2->s.apos.trBase, f, r, u );
+ VectorMA( podium->r.currentOrigin, offsetSecond[0], f, vec );
+ VectorMA( vec, offsetSecond[1], r, vec );
+ VectorMA( vec, offsetSecond[2], u, vec );
+
+ G_SetOrigin( podium2, vec );
+ }
+
+ if( podium3 ) {
+ VectorSubtract( level.intermission_origin, podium->r.currentOrigin, vec );
+ vectoangles( vec, podium3->s.apos.trBase );
+ podium3->s.apos.trBase[PITCH] = 0;
+ podium3->s.apos.trBase[ROLL] = 0;
+
+ AngleVectors( podium3->s.apos.trBase, f, r, u );
+ VectorMA( podium->r.currentOrigin, offsetThird[0], f, vec );
+ VectorMA( vec, offsetThird[1], r, vec );
+ VectorMA( vec, offsetThird[2], u, vec );
+
+ G_SetOrigin( podium3, vec );
+ }
+}
+
+
+static gentity_t *SpawnPodium( void ) {
+ gentity_t *podium;
+ vec3_t vec;
+ vec3_t origin;
+
+ podium = G_Spawn();
+ if ( !podium ) {
+ return NULL;
+ }
+
+ podium->classname = "podium";
+ podium->s.eType = ET_GENERAL;
+ podium->s.number = podium - g_entities;
+ podium->clipmask = CONTENTS_SOLID;
+ podium->r.contents = CONTENTS_SOLID;
+ podium->s.modelindex = G_ModelIndex( SP_PODIUM_MODEL );
+
+ AngleVectors( level.intermission_angle, vec, NULL, NULL );
+ VectorMA( level.intermission_origin, trap_Cvar_VariableIntegerValue( "g_podiumDist" ), vec, origin );
+ origin[2] -= trap_Cvar_VariableIntegerValue( "g_podiumDrop" );
+ G_SetOrigin( podium, origin );
+
+ VectorSubtract( level.intermission_origin, podium->r.currentOrigin, vec );
+ podium->s.apos.trBase[YAW] = vectoyaw( vec );
+ trap_LinkEntity (podium);
+
+ podium->think = PodiumPlacementThink;
+ podium->nextthink = level.time + 100;
+ return podium;
+}
+
+
+/*
+==================
+SpawnModelsOnVictoryPads
+==================
+*/
+void SpawnModelsOnVictoryPads( void ) {
+ gentity_t *player;
+ gentity_t *podium;
+
+ podium1 = NULL;
+ podium2 = NULL;
+ podium3 = NULL;
+
+ podium = SpawnPodium();
+
+ player = SpawnModelOnVictoryPad( podium, offsetFirst, &g_entities[level.sortedClients[0]],
+ level.clients[ level.sortedClients[0] ].ps.persistant[PERS_RANK] &~ RANK_TIED_FLAG );
+ if ( player ) {
+ player->nextthink = level.time + 2000;
+ player->think = CelebrateStart;
+ podium1 = player;
+ }
+
+ player = SpawnModelOnVictoryPad( podium, offsetSecond, &g_entities[level.sortedClients[1]],
+ level.clients[ level.sortedClients[1] ].ps.persistant[PERS_RANK] &~ RANK_TIED_FLAG );
+ if ( player ) {
+ podium2 = player;
+ }
+
+ if ( level.numNonSpectatorClients > 2 ) {
+ player = SpawnModelOnVictoryPad( podium, offsetThird, &g_entities[level.sortedClients[2]],
+ level.clients[ level.sortedClients[2] ].ps.persistant[PERS_RANK] &~ RANK_TIED_FLAG );
+ if ( player ) {
+ podium3 = player;
+ }
+ }
+}
+
+
+/*
+===============
+Svcmd_AbortPodium_f
+===============
+*/
+void Svcmd_AbortPodium_f( void ) {
+ if( g_gametype.integer != GT_SINGLE_PLAYER ) {
+ return;
+ }
+
+ if( podium1 ) {
+ podium1->nextthink = level.time;
+ podium1->think = CelebrateStop;
+ }
+}
diff --git a/code/game/g_bot.c b/code/game/g_bot.c
new file mode 100755
index 0000000..e42013d
--- /dev/null
+++ b/code/game/g_bot.c
@@ -0,0 +1,1017 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// g_bot.c
+
+#include "g_local.h"
+
+
+static int g_numBots;
+static char *g_botInfos[MAX_BOTS];
+
+
+int g_numArenas;
+static char *g_arenaInfos[MAX_ARENAS];
+
+
+#define BOT_BEGIN_DELAY_BASE 2000
+#define BOT_BEGIN_DELAY_INCREMENT 1500
+
+#define BOT_SPAWN_QUEUE_DEPTH 16
+
+typedef struct {
+ int clientNum;
+ int spawnTime;
+} botSpawnQueue_t;
+
+//static int botBeginDelay = 0; // bk001206 - unused, init
+static botSpawnQueue_t botSpawnQueue[BOT_SPAWN_QUEUE_DEPTH];
+
+vmCvar_t bot_minplayers;
+
+extern gentity_t *podium1;
+extern gentity_t *podium2;
+extern gentity_t *podium3;
+
+float trap_Cvar_VariableValue( const char *var_name ) {
+ char buf[128];
+
+ trap_Cvar_VariableStringBuffer(var_name, buf, sizeof(buf));
+ return atof(buf);
+}
+
+
+
+/*
+===============
+G_ParseInfos
+===============
+*/
+int G_ParseInfos( char *buf, int max, char *infos[] ) {
+ char *token;
+ int count;
+ char key[MAX_TOKEN_CHARS];
+ char info[MAX_INFO_STRING];
+
+ count = 0;
+
+ while ( 1 ) {
+ token = COM_Parse( &buf );
+ if ( !token[0] ) {
+ break;
+ }
+ if ( strcmp( token, "{" ) ) {
+ Com_Printf( "Missing { in info file\n" );
+ break;
+ }
+
+ if ( count == max ) {
+ Com_Printf( "Max infos exceeded\n" );
+ break;
+ }
+
+ info[0] = '\0';
+ while ( 1 ) {
+ token = COM_ParseExt( &buf, qtrue );
+ if ( !token[0] ) {
+ Com_Printf( "Unexpected end of info file\n" );
+ break;
+ }
+ if ( !strcmp( token, "}" ) ) {
+ break;
+ }
+ Q_strncpyz( key, token, sizeof( key ) );
+
+ token = COM_ParseExt( &buf, qfalse );
+ if ( !token[0] ) {
+ strcpy( token, "<NULL>" );
+ }
+ Info_SetValueForKey( info, key, token );
+ }
+ //NOTE: extra space for arena number
+ infos[count] = G_Alloc(strlen(info) + strlen("\\num\\") + strlen(va("%d", MAX_ARENAS)) + 1);
+ if (infos[count]) {
+ strcpy(infos[count], info);
+ count++;
+ }
+ }
+ return count;
+}
+
+/*
+===============
+G_LoadArenasFromFile
+===============
+*/
+static void G_LoadArenasFromFile( char *filename ) {
+ int len;
+ fileHandle_t f;
+ char buf[MAX_ARENAS_TEXT];
+
+ len = trap_FS_FOpenFile( filename, &f, FS_READ );
+ if ( !f ) {
+ trap_Printf( va( S_COLOR_RED "file not found: %s\n", filename ) );
+ return;
+ }
+ if ( len >= MAX_ARENAS_TEXT ) {
+ trap_Printf( va( S_COLOR_RED "file too large: %s is %i, max allowed is %i", filename, len, MAX_ARENAS_TEXT ) );
+ trap_FS_FCloseFile( f );
+ return;
+ }
+
+ trap_FS_Read( buf, len, f );
+ buf[len] = 0;
+ trap_FS_FCloseFile( f );
+
+ g_numArenas += G_ParseInfos( buf, MAX_ARENAS - g_numArenas, &g_arenaInfos[g_numArenas] );
+}
+
+/*
+===============
+G_LoadArenas
+===============
+*/
+static void G_LoadArenas( void ) {
+ int numdirs;
+ vmCvar_t arenasFile;
+ char filename[128];
+ char dirlist[1024];
+ char* dirptr;
+ int i, n;
+ int dirlen;
+
+ g_numArenas = 0;
+
+ trap_Cvar_Register( &arenasFile, "g_arenasFile", "", CVAR_INIT|CVAR_ROM );
+ if( *arenasFile.string ) {
+ G_LoadArenasFromFile(arenasFile.string);
+ }
+ else {
+ G_LoadArenasFromFile("scripts/arenas.txt");
+ }
+
+ // get all arenas from .arena files
+ numdirs = trap_FS_GetFileList("scripts", ".arena", dirlist, 1024 );
+ dirptr = dirlist;
+ for (i = 0; i < numdirs; i++, dirptr += dirlen+1) {
+ dirlen = strlen(dirptr);
+ strcpy(filename, "scripts/");
+ strcat(filename, dirptr);
+ G_LoadArenasFromFile(filename);
+ }
+ trap_Printf( va( "%i arenas parsed\n", g_numArenas ) );
+
+ for( n = 0; n < g_numArenas; n++ ) {
+ Info_SetValueForKey( g_arenaInfos[n], "num", va( "%i", n ) );
+ }
+}
+
+
+/*
+===============
+G_GetArenaInfoByNumber
+===============
+*/
+const char *G_GetArenaInfoByMap( const char *map ) {
+ int n;
+
+ for( n = 0; n < g_numArenas; n++ ) {
+ if( Q_stricmp( Info_ValueForKey( g_arenaInfos[n], "map" ), map ) == 0 ) {
+ return g_arenaInfos[n];
+ }
+ }
+
+ return NULL;
+}
+
+
+/*
+=================
+PlayerIntroSound
+=================
+*/
+static void PlayerIntroSound( const char *modelAndSkin ) {
+ char model[MAX_QPATH];
+ char *skin;
+
+ Q_strncpyz( model, modelAndSkin, sizeof(model) );
+ skin = Q_strrchr( model, '/' );
+ if ( skin ) {
+ *skin++ = '\0';
+ }
+ else {
+ skin = model;
+ }
+
+ if( Q_stricmp( skin, "default" ) == 0 ) {
+ skin = model;
+ }
+
+ trap_SendConsoleCommand( EXEC_APPEND, va( "play sound/player/announce/%s.wav\n", skin ) );
+}
+
+/*
+===============
+G_AddRandomBot
+===============
+*/
+void G_AddRandomBot( int team ) {
+ int i, n, num;
+ float skill;
+ char *value, netname[36], *teamstr;
+ gclient_t *cl;
+
+ num = 0;
+ for ( n = 0; n < g_numBots ; n++ ) {
+ value = Info_ValueForKey( g_botInfos[n], "name" );
+ //
+ for ( i=0 ; i< g_maxclients.integer ; i++ ) {
+ cl = level.clients + i;
+ if ( cl->pers.connected != CON_CONNECTED ) {
+ continue;
+ }
+ if ( !(g_entities[cl->ps.clientNum].r.svFlags & SVF_BOT) ) {
+ continue;
+ }
+ if ( team >= 0 && cl->sess.sessionTeam != team ) {
+ continue;
+ }
+ if ( !Q_stricmp( value, cl->pers.netname ) ) {
+ break;
+ }
+ }
+ if (i >= g_maxclients.integer) {
+ num++;
+ }
+ }
+ num = random() * num;
+ for ( n = 0; n < g_numBots ; n++ ) {
+ value = Info_ValueForKey( g_botInfos[n], "name" );
+ //
+ for ( i=0 ; i< g_maxclients.integer ; i++ ) {
+ cl = level.clients + i;
+ if ( cl->pers.connected != CON_CONNECTED ) {
+ continue;
+ }
+ if ( !(g_entities[cl->ps.clientNum].r.svFlags & SVF_BOT) ) {
+ continue;
+ }
+ if ( team >= 0 && cl->sess.sessionTeam != team ) {
+ continue;
+ }
+ if ( !Q_stricmp( value, cl->pers.netname ) ) {
+ break;
+ }
+ }
+ if (i >= g_maxclients.integer) {
+ num--;
+ if (num <= 0) {
+ skill = trap_Cvar_VariableValue( "g_spSkill" );
+ if (team == TEAM_RED) teamstr = "red";
+ else if (team == TEAM_BLUE) teamstr = "blue";
+ else teamstr = "";
+ strncpy(netname, value, sizeof(netname)-1);
+ netname[sizeof(netname)-1] = '\0';
+ Q_CleanStr(netname);
+ trap_SendConsoleCommand( EXEC_INSERT, va("addbot %s %f %s %i\n", netname, skill, teamstr, 0) );
+ return;
+ }
+ }
+ }
+}
+
+/*
+===============
+G_RemoveRandomBot
+===============
+*/
+int G_RemoveRandomBot( int team ) {
+ int i;
+ char netname[36];
+ gclient_t *cl;
+
+ for ( i=0 ; i< g_maxclients.integer ; i++ ) {
+ cl = level.clients + i;
+ if ( cl->pers.connected != CON_CONNECTED ) {
+ continue;
+ }
+ if ( !(g_entities[cl->ps.clientNum].r.svFlags & SVF_BOT) ) {
+ continue;
+ }
+ if ( team >= 0 && cl->sess.sessionTeam != team ) {
+ continue;
+ }
+ strcpy(netname, cl->pers.netname);
+ Q_CleanStr(netname);
+ trap_SendConsoleCommand( EXEC_INSERT, va("kick %s\n", netname) );
+ return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+===============
+G_CountHumanPlayers
+===============
+*/
+int G_CountHumanPlayers( int team ) {
+ int i, num;
+ gclient_t *cl;
+
+ num = 0;
+ for ( i=0 ; i< g_maxclients.integer ; i++ ) {
+ cl = level.clients + i;
+ if ( cl->pers.connected != CON_CONNECTED ) {
+ continue;
+ }
+ if ( g_entities[cl->ps.clientNum].r.svFlags & SVF_BOT ) {
+ continue;
+ }
+ if ( team >= 0 && cl->sess.sessionTeam != team ) {
+ continue;
+ }
+ num++;
+ }
+ return num;
+}
+
+/*
+===============
+G_CountBotPlayers
+===============
+*/
+int G_CountBotPlayers( int team ) {
+ int i, n, num;
+ gclient_t *cl;
+
+ num = 0;
+ for ( i=0 ; i< g_maxclients.integer ; i++ ) {
+ cl = level.clients + i;
+ if ( cl->pers.connected != CON_CONNECTED ) {
+ continue;
+ }
+ if ( !(g_entities[cl->ps.clientNum].r.svFlags & SVF_BOT) ) {
+ continue;
+ }
+ if ( team >= 0 && cl->sess.sessionTeam != team ) {
+ continue;
+ }
+ num++;
+ }
+ for( n = 0; n < BOT_SPAWN_QUEUE_DEPTH; n++ ) {
+ if( !botSpawnQueue[n].spawnTime ) {
+ continue;
+ }
+ if ( botSpawnQueue[n].spawnTime > level.time ) {
+ continue;
+ }
+ num++;
+ }
+ return num;
+}
+
+/*
+===============
+G_CheckMinimumPlayers
+===============
+*/
+void G_CheckMinimumPlayers( void ) {
+ int minplayers;
+ int humanplayers, botplayers;
+ static int checkminimumplayers_time;
+
+ if (level.intermissiontime) return;
+ //only check once each 10 seconds
+ if (checkminimumplayers_time > level.time - 10000) {
+ return;
+ }
+ checkminimumplayers_time = level.time;
+ trap_Cvar_Update(&bot_minplayers);
+ minplayers = bot_minplayers.integer;
+ if (minplayers <= 0) return;
+
+ if (g_gametype.integer >= GT_TEAM) {
+ if (minplayers >= g_maxclients.integer / 2) {
+ minplayers = (g_maxclients.integer / 2) -1;
+ }
+
+ humanplayers = G_CountHumanPlayers( TEAM_RED );
+ botplayers = G_CountBotPlayers( TEAM_RED );
+ //
+ if (humanplayers + botplayers < minplayers) {
+ G_AddRandomBot( TEAM_RED );
+ } else if (humanplayers + botplayers > minplayers && botplayers) {
+ G_RemoveRandomBot( TEAM_RED );
+ }
+ //
+ humanplayers = G_CountHumanPlayers( TEAM_BLUE );
+ botplayers = G_CountBotPlayers( TEAM_BLUE );
+ //
+ if (humanplayers + botplayers < minplayers) {
+ G_AddRandomBot( TEAM_BLUE );
+ } else if (humanplayers + botplayers > minplayers && botplayers) {
+ G_RemoveRandomBot( TEAM_BLUE );
+ }
+ }
+ else if (g_gametype.integer == GT_TOURNAMENT ) {
+ if (minplayers >= g_maxclients.integer) {
+ minplayers = g_maxclients.integer-1;
+ }
+ humanplayers = G_CountHumanPlayers( -1 );
+ botplayers = G_CountBotPlayers( -1 );
+ //
+ if (humanplayers + botplayers < minplayers) {
+ G_AddRandomBot( TEAM_FREE );
+ } else if (humanplayers + botplayers > minplayers && botplayers) {
+ // try to remove spectators first
+ if (!G_RemoveRandomBot( TEAM_SPECTATOR )) {
+ // just remove the bot that is playing
+ G_RemoveRandomBot( -1 );
+ }
+ }
+ }
+ else if (g_gametype.integer == GT_FFA) {
+ if (minplayers >= g_maxclients.integer) {
+ minplayers = g_maxclients.integer-1;
+ }
+ humanplayers = G_CountHumanPlayers( TEAM_FREE );
+ botplayers = G_CountBotPlayers( TEAM_FREE );
+ //
+ if (humanplayers + botplayers < minplayers) {
+ G_AddRandomBot( TEAM_FREE );
+ } else if (humanplayers + botplayers > minplayers && botplayers) {
+ G_RemoveRandomBot( TEAM_FREE );
+ }
+ }
+}
+
+/*
+===============
+G_CheckBotSpawn
+===============
+*/
+void G_CheckBotSpawn( void ) {
+ int n;
+ char userinfo[MAX_INFO_VALUE];
+
+ G_CheckMinimumPlayers();
+
+ for( n = 0; n < BOT_SPAWN_QUEUE_DEPTH; n++ ) {
+ if( !botSpawnQueue[n].spawnTime ) {
+ continue;
+ }
+ if ( botSpawnQueue[n].spawnTime > level.time ) {
+ continue;
+ }
+ ClientBegin( botSpawnQueue[n].clientNum );
+ botSpawnQueue[n].spawnTime = 0;
+
+ if( g_gametype.integer == GT_SINGLE_PLAYER ) {
+ trap_GetUserinfo( botSpawnQueue[n].clientNum, userinfo, sizeof(userinfo) );
+ PlayerIntroSound( Info_ValueForKey (userinfo, "model") );
+ }
+ }
+}
+
+
+/*
+===============
+AddBotToSpawnQueue
+===============
+*/
+static void AddBotToSpawnQueue( int clientNum, int delay ) {
+ int n;
+
+ for( n = 0; n < BOT_SPAWN_QUEUE_DEPTH; n++ ) {
+ if( !botSpawnQueue[n].spawnTime ) {
+ botSpawnQueue[n].spawnTime = level.time + delay;
+ botSpawnQueue[n].clientNum = clientNum;
+ return;
+ }
+ }
+
+ G_Printf( S_COLOR_YELLOW "Unable to delay spawn\n" );
+ ClientBegin( clientNum );
+}
+
+
+/*
+===============
+G_RemoveQueuedBotBegin
+
+Called on client disconnect to make sure the delayed spawn
+doesn't happen on a freed index
+===============
+*/
+void G_RemoveQueuedBotBegin( int clientNum ) {
+ int n;
+
+ for( n = 0; n < BOT_SPAWN_QUEUE_DEPTH; n++ ) {
+ if( botSpawnQueue[n].clientNum == clientNum ) {
+ botSpawnQueue[n].spawnTime = 0;
+ return;
+ }
+ }
+}
+
+
+/*
+===============
+G_BotConnect
+===============
+*/
+qboolean G_BotConnect( int clientNum, qboolean restart ) {
+ bot_settings_t settings;
+ char userinfo[MAX_INFO_STRING];
+
+ trap_GetUserinfo( clientNum, userinfo, sizeof(userinfo) );
+
+ Q_strncpyz( settings.characterfile, Info_ValueForKey( userinfo, "characterfile" ), sizeof(settings.characterfile) );
+ settings.skill = atof( Info_ValueForKey( userinfo, "skill" ) );
+ Q_strncpyz( settings.team, Info_ValueForKey( userinfo, "team" ), sizeof(settings.team) );
+
+ if (!BotAISetupClient( clientNum, &settings, restart )) {
+ trap_DropClient( clientNum, "BotAISetupClient failed" );
+ return qfalse;
+ }
+
+ return qtrue;
+}
+
+
+/*
+===============
+G_AddBot
+===============
+*/
+static void G_AddBot( const char *name, float skill, const char *team, int delay, char *altname) {
+ int clientNum;
+ char *botinfo;
+ gentity_t *bot;
+ char *key;
+ char *s;
+ char *botname;
+ char *model;
+ char *headmodel;
+ char userinfo[MAX_INFO_STRING];
+
+ // get the botinfo from bots.txt
+ botinfo = G_GetBotInfoByName( name );
+ if ( !botinfo ) {
+ G_Printf( S_COLOR_RED "Error: Bot '%s' not defined\n", name );
+ return;
+ }
+
+ // create the bot's userinfo
+ userinfo[0] = '\0';
+
+ botname = Info_ValueForKey( botinfo, "funname" );
+ if( !botname[0] ) {
+ botname = Info_ValueForKey( botinfo, "name" );
+ }
+ // check for an alternative name
+ if (altname && altname[0]) {
+ botname = altname;
+ }
+ Info_SetValueForKey( userinfo, "name", botname );
+ Info_SetValueForKey( userinfo, "rate", "25000" );
+ Info_SetValueForKey( userinfo, "snaps", "20" );
+ Info_SetValueForKey( userinfo, "skill", va("%1.2f", skill) );
+
+ if ( skill >= 1 && skill < 2 ) {
+ Info_SetValueForKey( userinfo, "handicap", "50" );
+ }
+ else if ( skill >= 2 && skill < 3 ) {
+ Info_SetValueForKey( userinfo, "handicap", "70" );
+ }
+ else if ( skill >= 3 && skill < 4 ) {
+ Info_SetValueForKey( userinfo, "handicap", "90" );
+ }
+
+ key = "model";
+ model = Info_ValueForKey( botinfo, key );
+ if ( !*model ) {
+ model = "visor/default";
+ }
+ Info_SetValueForKey( userinfo, key, model );
+ key = "team_model";
+ Info_SetValueForKey( userinfo, key, model );
+
+ key = "headmodel";
+ headmodel = Info_ValueForKey( botinfo, key );
+ if ( !*headmodel ) {
+ headmodel = model;
+ }
+ Info_SetValueForKey( userinfo, key, headmodel );
+ key = "team_headmodel";
+ Info_SetValueForKey( userinfo, key, headmodel );
+
+ key = "gender";
+ s = Info_ValueForKey( botinfo, key );
+ if ( !*s ) {
+ s = "male";
+ }
+ Info_SetValueForKey( userinfo, "sex", s );
+
+ key = "color1";
+ s = Info_ValueForKey( botinfo, key );
+ if ( !*s ) {
+ s = "4";
+ }
+ Info_SetValueForKey( userinfo, key, s );
+
+ key = "color2";
+ s = Info_ValueForKey( botinfo, key );
+ if ( !*s ) {
+ s = "5";
+ }
+ Info_SetValueForKey( userinfo, key, s );
+
+ s = Info_ValueForKey(botinfo, "aifile");
+ if (!*s ) {
+ trap_Printf( S_COLOR_RED "Error: bot has no aifile specified\n" );
+ return;
+ }
+
+ // have the server allocate a client slot
+ clientNum = trap_BotAllocateClient();
+ if ( clientNum == -1 ) {
+ G_Printf( S_COLOR_RED "Unable to add bot. All player slots are in use.\n" );
+ G_Printf( S_COLOR_RED "Start server with more 'open' slots (or check setting of sv_maxclients cvar).\n" );
+ return;
+ }
+
+ // initialize the bot settings
+ if( !team || !*team ) {
+ if( g_gametype.integer >= GT_TEAM ) {
+ if( PickTeam(clientNum) == TEAM_RED) {
+ team = "red";
+ }
+ else {
+ team = "blue";
+ }
+ }
+ else {
+ team = "red";
+ }
+ }
+ Info_SetValueForKey( userinfo, "characterfile", Info_ValueForKey( botinfo, "aifile" ) );
+ Info_SetValueForKey( userinfo, "skill", va( "%5.2f", skill ) );
+ Info_SetValueForKey( userinfo, "team", team );
+
+ bot = &g_entities[ clientNum ];
+ bot->r.svFlags |= SVF_BOT;
+ bot->inuse = qtrue;
+
+ // register the userinfo
+ trap_SetUserinfo( clientNum, userinfo );
+
+ // have it connect to the game as a normal client
+ if ( ClientConnect( clientNum, qtrue, qtrue ) ) {
+ return;
+ }
+
+ if( delay == 0 ) {
+ ClientBegin( clientNum );
+ return;
+ }
+
+ AddBotToSpawnQueue( clientNum, delay );
+}
+
+
+/*
+===============
+Svcmd_AddBot_f
+===============
+*/
+void Svcmd_AddBot_f( void ) {
+ float skill;
+ int delay;
+ char name[MAX_TOKEN_CHARS];
+ char altname[MAX_TOKEN_CHARS];
+ char string[MAX_TOKEN_CHARS];
+ char team[MAX_TOKEN_CHARS];
+
+ // are bots enabled?
+ if ( !trap_Cvar_VariableIntegerValue( "bot_enable" ) ) {
+ return;
+ }
+
+ // name
+ trap_Argv( 1, name, sizeof( name ) );
+ if ( !name[0] ) {
+ trap_Printf( "Usage: Addbot <botname> [skill 1-5] [team] [msec delay] [altname]\n" );
+ return;
+ }
+
+ // skill
+ trap_Argv( 2, string, sizeof( string ) );
+ if ( !string[0] ) {
+ skill = 4;
+ }
+ else {
+ skill = atof( string );
+ }
+
+ // team
+ trap_Argv( 3, team, sizeof( team ) );
+
+ // delay
+ trap_Argv( 4, string, sizeof( string ) );
+ if ( !string[0] ) {
+ delay = 0;
+ }
+ else {
+ delay = atoi( string );
+ }
+
+ // alternative name
+ trap_Argv( 5, altname, sizeof( altname ) );
+
+ G_AddBot( name, skill, team, delay, altname );
+
+ // if this was issued during gameplay and we are playing locally,
+ // go ahead and load the bot's media immediately
+ if ( level.time - level.startTime > 1000 &&
+ trap_Cvar_VariableIntegerValue( "cl_running" ) ) {
+ trap_SendServerCommand( -1, "loaddefered\n" ); // FIXME: spelled wrong, but not changing for demo
+ }
+}
+
+/*
+===============
+Svcmd_BotList_f
+===============
+*/
+void Svcmd_BotList_f( void ) {
+ int i;
+ char name[MAX_TOKEN_CHARS];
+ char funname[MAX_TOKEN_CHARS];
+ char model[MAX_TOKEN_CHARS];
+ char aifile[MAX_TOKEN_CHARS];
+
+ trap_Printf("^1name model aifile funname\n");
+ for (i = 0; i < g_numBots; i++) {
+ strcpy(name, Info_ValueForKey( g_botInfos[i], "name" ));
+ if ( !*name ) {
+ strcpy(name, "UnnamedPlayer");
+ }
+ strcpy(funname, Info_ValueForKey( g_botInfos[i], "funname" ));
+ if ( !*funname ) {
+ strcpy(funname, "");
+ }
+ strcpy(model, Info_ValueForKey( g_botInfos[i], "model" ));
+ if ( !*model ) {
+ strcpy(model, "visor/default");
+ }
+ strcpy(aifile, Info_ValueForKey( g_botInfos[i], "aifile"));
+ if (!*aifile ) {
+ strcpy(aifile, "bots/default_c.c");
+ }
+ trap_Printf(va("%-16s %-16s %-20s %-20s\n", name, model, aifile, funname));
+ }
+}
+
+
+/*
+===============
+G_SpawnBots
+===============
+*/
+static void G_SpawnBots( char *botList, int baseDelay ) {
+ char *bot;
+ char *p;
+ float skill;
+ int delay;
+ char bots[MAX_INFO_VALUE];
+
+ podium1 = NULL;
+ podium2 = NULL;
+ podium3 = NULL;
+
+ skill = trap_Cvar_VariableValue( "g_spSkill" );
+ if( skill < 1 ) {
+ trap_Cvar_Set( "g_spSkill", "1" );
+ skill = 1;
+ }
+ else if ( skill > 5 ) {
+ trap_Cvar_Set( "g_spSkill", "5" );
+ skill = 5;
+ }
+
+ Q_strncpyz( bots, botList, sizeof(bots) );
+ p = &bots[0];
+ delay = baseDelay;
+ while( *p ) {
+ //skip spaces
+ while( *p && *p == ' ' ) {
+ p++;
+ }
+ if( !p ) {
+ break;
+ }
+
+ // mark start of bot name
+ bot = p;
+
+ // skip until space of null
+ while( *p && *p != ' ' ) {
+ p++;
+ }
+ if( *p ) {
+ *p++ = 0;
+ }
+
+ // we must add the bot this way, calling G_AddBot directly at this stage
+ // does "Bad Things"
+ trap_SendConsoleCommand( EXEC_INSERT, va("addbot %s %f free %i\n", bot, skill, delay) );
+
+ delay += BOT_BEGIN_DELAY_INCREMENT;
+ }
+}
+
+
+/*
+===============
+G_LoadBotsFromFile
+===============
+*/
+static void G_LoadBotsFromFile( char *filename ) {
+ int len;
+ fileHandle_t f;
+ char buf[MAX_BOTS_TEXT];
+
+ len = trap_FS_FOpenFile( filename, &f, FS_READ );
+ if ( !f ) {
+ trap_Printf( va( S_COLOR_RED "file not found: %s\n", filename ) );
+ return;
+ }
+ if ( len >= MAX_BOTS_TEXT ) {
+ trap_Printf( va( S_COLOR_RED "file too large: %s is %i, max allowed is %i", filename, len, MAX_BOTS_TEXT ) );
+ trap_FS_FCloseFile( f );
+ return;
+ }
+
+ trap_FS_Read( buf, len, f );
+ buf[len] = 0;
+ trap_FS_FCloseFile( f );
+
+ g_numBots += G_ParseInfos( buf, MAX_BOTS - g_numBots, &g_botInfos[g_numBots] );
+}
+
+/*
+===============
+G_LoadBots
+===============
+*/
+static void G_LoadBots( void ) {
+ vmCvar_t botsFile;
+ int numdirs;
+ char filename[128];
+ char dirlist[1024];
+ char* dirptr;
+ int i;
+ int dirlen;
+
+ if ( !trap_Cvar_VariableIntegerValue( "bot_enable" ) ) {
+ return;
+ }
+
+ g_numBots = 0;
+
+ trap_Cvar_Register( &botsFile, "g_botsFile", "", CVAR_INIT|CVAR_ROM );
+ if( *botsFile.string ) {
+ G_LoadBotsFromFile(botsFile.string);
+ }
+ else {
+ G_LoadBotsFromFile("scripts/bots.txt");
+ }
+
+ // get all bots from .bot files
+ numdirs = trap_FS_GetFileList("scripts", ".bot", dirlist, 1024 );
+ dirptr = dirlist;
+ for (i = 0; i < numdirs; i++, dirptr += dirlen+1) {
+ dirlen = strlen(dirptr);
+ strcpy(filename, "scripts/");
+ strcat(filename, dirptr);
+ G_LoadBotsFromFile(filename);
+ }
+ trap_Printf( va( "%i bots parsed\n", g_numBots ) );
+}
+
+
+
+/*
+===============
+G_GetBotInfoByNumber
+===============
+*/
+char *G_GetBotInfoByNumber( int num ) {
+ if( num < 0 || num >= g_numBots ) {
+ trap_Printf( va( S_COLOR_RED "Invalid bot number: %i\n", num ) );
+ return NULL;
+ }
+ return g_botInfos[num];
+}
+
+
+/*
+===============
+G_GetBotInfoByName
+===============
+*/
+char *G_GetBotInfoByName( const char *name ) {
+ int n;
+ char *value;
+
+ for ( n = 0; n < g_numBots ; n++ ) {
+ value = Info_ValueForKey( g_botInfos[n], "name" );
+ if ( !Q_stricmp( value, name ) ) {
+ return g_botInfos[n];
+ }
+ }
+
+ return NULL;
+}
+
+/*
+===============
+G_InitBots
+===============
+*/
+void G_InitBots( qboolean restart ) {
+ int fragLimit;
+ int timeLimit;
+ const char *arenainfo;
+ char *strValue;
+ int basedelay;
+ char map[MAX_QPATH];
+ char serverinfo[MAX_INFO_STRING];
+
+ G_LoadBots();
+ G_LoadArenas();
+
+ trap_Cvar_Register( &bot_minplayers, "bot_minplayers", "0", CVAR_SERVERINFO );
+
+ if( g_gametype.integer == GT_SINGLE_PLAYER ) {
+ trap_GetServerinfo( serverinfo, sizeof(serverinfo) );
+ Q_strncpyz( map, Info_ValueForKey( serverinfo, "mapname" ), sizeof(map) );
+ arenainfo = G_GetArenaInfoByMap( map );
+ if ( !arenainfo ) {
+ return;
+ }
+
+ strValue = Info_ValueForKey( arenainfo, "fraglimit" );
+ fragLimit = atoi( strValue );
+ if ( fragLimit ) {
+ trap_Cvar_Set( "fraglimit", strValue );
+ }
+ else {
+ trap_Cvar_Set( "fraglimit", "0" );
+ }
+
+ strValue = Info_ValueForKey( arenainfo, "timelimit" );
+ timeLimit = atoi( strValue );
+ if ( timeLimit ) {
+ trap_Cvar_Set( "timelimit", strValue );
+ }
+ else {
+ trap_Cvar_Set( "timelimit", "0" );
+ }
+
+ if ( !fragLimit && !timeLimit ) {
+ trap_Cvar_Set( "fraglimit", "10" );
+ trap_Cvar_Set( "timelimit", "0" );
+ }
+
+ basedelay = BOT_BEGIN_DELAY_BASE;
+ strValue = Info_ValueForKey( arenainfo, "special" );
+ if( Q_stricmp( strValue, "training" ) == 0 ) {
+ basedelay += 10000;
+ }
+
+ if( !restart ) {
+ G_SpawnBots( Info_ValueForKey( arenainfo, "bots" ), basedelay );
+ }
+ }
+}
diff --git a/code/game/g_client.c b/code/game/g_client.c
new file mode 100755
index 0000000..5a584d4
--- /dev/null
+++ b/code/game/g_client.c
@@ -0,0 +1,1344 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#include "g_local.h"
+
+// g_client.c -- client functions that don't happen every frame
+
+static vec3_t playerMins = {-15, -15, -24};
+static vec3_t playerMaxs = {15, 15, 32};
+
+/*QUAKED info_player_deathmatch (1 0 1) (-16 -16 -24) (16 16 32) initial
+potential spawning position for deathmatch games.
+The first time a player enters the game, they will be at an 'initial' spot.
+Targets will be fired when someone spawns in on them.
+"nobots" will prevent bots from using this spot.
+"nohumans" will prevent non-bots from using this spot.
+*/
+void SP_info_player_deathmatch( gentity_t *ent ) {
+ int i;
+
+ G_SpawnInt( "nobots", "0", &i);
+ if ( i ) {
+ ent->flags |= FL_NO_BOTS;
+ }
+ G_SpawnInt( "nohumans", "0", &i );
+ if ( i ) {
+ ent->flags |= FL_NO_HUMANS;
+ }
+}
+
+/*QUAKED info_player_start (1 0 0) (-16 -16 -24) (16 16 32)
+equivelant to info_player_deathmatch
+*/
+void SP_info_player_start(gentity_t *ent) {
+ ent->classname = "info_player_deathmatch";
+ SP_info_player_deathmatch( ent );
+}
+
+/*QUAKED info_player_intermission (1 0 1) (-16 -16 -24) (16 16 32)
+The intermission will be viewed from this point. Target an info_notnull for the view direction.
+*/
+void SP_info_player_intermission( gentity_t *ent ) {
+
+}
+
+
+
+/*
+=======================================================================
+
+ SelectSpawnPoint
+
+=======================================================================
+*/
+
+/*
+================
+SpotWouldTelefrag
+
+================
+*/
+qboolean SpotWouldTelefrag( gentity_t *spot ) {
+ int i, num;
+ int touch[MAX_GENTITIES];
+ gentity_t *hit;
+ vec3_t mins, maxs;
+
+ VectorAdd( spot->s.origin, playerMins, mins );
+ VectorAdd( spot->s.origin, playerMaxs, maxs );
+ num = trap_EntitiesInBox( mins, maxs, touch, MAX_GENTITIES );
+
+ for (i=0 ; i<num ; i++) {
+ hit = &g_entities[touch[i]];
+ //if ( hit->client && hit->client->ps.stats[STAT_HEALTH] > 0 ) {
+ if ( hit->client) {
+ return qtrue;
+ }
+
+ }
+
+ return qfalse;
+}
+
+/*
+================
+SelectNearestDeathmatchSpawnPoint
+
+Find the spot that we DON'T want to use
+================
+*/
+#define MAX_SPAWN_POINTS 128
+gentity_t *SelectNearestDeathmatchSpawnPoint( vec3_t from ) {
+ gentity_t *spot;
+ vec3_t delta;
+ float dist, nearestDist;
+ gentity_t *nearestSpot;
+
+ nearestDist = 999999;
+ nearestSpot = NULL;
+ spot = NULL;
+
+ while ((spot = G_Find (spot, FOFS(classname), "info_player_deathmatch")) != NULL) {
+
+ VectorSubtract( spot->s.origin, from, delta );
+ dist = VectorLength( delta );
+ if ( dist < nearestDist ) {
+ nearestDist = dist;
+ nearestSpot = spot;
+ }
+ }
+
+ return nearestSpot;
+}
+
+
+/*
+================
+SelectRandomDeathmatchSpawnPoint
+
+go to a random point that doesn't telefrag
+================
+*/
+#define MAX_SPAWN_POINTS 128
+gentity_t *SelectRandomDeathmatchSpawnPoint( void ) {
+ gentity_t *spot;
+ int count;
+ int selection;
+ gentity_t *spots[MAX_SPAWN_POINTS];
+
+ count = 0;
+ spot = NULL;
+
+ while ((spot = G_Find (spot, FOFS(classname), "info_player_deathmatch")) != NULL) {
+ if ( SpotWouldTelefrag( spot ) ) {
+ continue;
+ }
+ spots[ count ] = spot;
+ count++;
+ }
+
+ if ( !count ) { // no spots that won't telefrag
+ return G_Find( NULL, FOFS(classname), "info_player_deathmatch");
+ }
+
+ selection = rand() % count;
+ return spots[ selection ];
+}
+
+/*
+===========
+SelectRandomFurthestSpawnPoint
+
+Chooses a player start, deathmatch start, etc
+============
+*/
+gentity_t *SelectRandomFurthestSpawnPoint ( vec3_t avoidPoint, vec3_t origin, vec3_t angles ) {
+ gentity_t *spot;
+ vec3_t delta;
+ float dist;
+ float list_dist[64];
+ gentity_t *list_spot[64];
+ int numSpots, rnd, i, j;
+
+ numSpots = 0;
+ spot = NULL;
+
+ while ((spot = G_Find (spot, FOFS(classname), "info_player_deathmatch")) != NULL) {
+ if ( SpotWouldTelefrag( spot ) ) {
+ continue;
+ }
+ VectorSubtract( spot->s.origin, avoidPoint, delta );
+ dist = VectorLength( delta );
+ for (i = 0; i < numSpots; i++) {
+ if ( dist > list_dist[i] ) {
+ if ( numSpots >= 64 )
+ numSpots = 64-1;
+ for (j = numSpots; j > i; j--) {
+ list_dist[j] = list_dist[j-1];
+ list_spot[j] = list_spot[j-1];
+ }
+ list_dist[i] = dist;
+ list_spot[i] = spot;
+ numSpots++;
+ if (numSpots > 64)
+ numSpots = 64;
+ break;
+ }
+ }
+ if (i >= numSpots && numSpots < 64) {
+ list_dist[numSpots] = dist;
+ list_spot[numSpots] = spot;
+ numSpots++;
+ }
+ }
+ if (!numSpots) {
+ spot = G_Find( NULL, FOFS(classname), "info_player_deathmatch");
+ if (!spot)
+ G_Error( "Couldn't find a spawn point" );
+ VectorCopy (spot->s.origin, origin);
+ origin[2] += 9;
+ VectorCopy (spot->s.angles, angles);
+ return spot;
+ }
+
+ // select a random spot from the spawn points furthest away
+ rnd = random() * (numSpots / 2);
+
+ VectorCopy (list_spot[rnd]->s.origin, origin);
+ origin[2] += 9;
+ VectorCopy (list_spot[rnd]->s.angles, angles);
+
+ return list_spot[rnd];
+}
+
+/*
+===========
+SelectSpawnPoint
+
+Chooses a player start, deathmatch start, etc
+============
+*/
+gentity_t *SelectSpawnPoint ( vec3_t avoidPoint, vec3_t origin, vec3_t angles ) {
+ return SelectRandomFurthestSpawnPoint( avoidPoint, origin, angles );
+
+ /*
+ gentity_t *spot;
+ gentity_t *nearestSpot;
+
+ nearestSpot = SelectNearestDeathmatchSpawnPoint( avoidPoint );
+
+ spot = SelectRandomDeathmatchSpawnPoint ( );
+ if ( spot == nearestSpot ) {
+ // roll again if it would be real close to point of death
+ spot = SelectRandomDeathmatchSpawnPoint ( );
+ if ( spot == nearestSpot ) {
+ // last try
+ spot = SelectRandomDeathmatchSpawnPoint ( );
+ }
+ }
+
+ // find a single player start spot
+ if (!spot) {
+ G_Error( "Couldn't find a spawn point" );
+ }
+
+ VectorCopy (spot->s.origin, origin);
+ origin[2] += 9;
+ VectorCopy (spot->s.angles, angles);
+
+ return spot;
+ */
+}
+
+/*
+===========
+SelectInitialSpawnPoint
+
+Try to find a spawn point marked 'initial', otherwise
+use normal spawn selection.
+============
+*/
+gentity_t *SelectInitialSpawnPoint( vec3_t origin, vec3_t angles ) {
+ gentity_t *spot;
+
+ spot = NULL;
+ while ((spot = G_Find (spot, FOFS(classname), "info_player_deathmatch")) != NULL) {
+ if ( spot->spawnflags & 1 ) {
+ break;
+ }
+ }
+
+ if ( !spot || SpotWouldTelefrag( spot ) ) {
+ return SelectSpawnPoint( vec3_origin, origin, angles );
+ }
+
+ VectorCopy (spot->s.origin, origin);
+ origin[2] += 9;
+ VectorCopy (spot->s.angles, angles);
+
+ return spot;
+}
+
+/*
+===========
+SelectSpectatorSpawnPoint
+
+============
+*/
+gentity_t *SelectSpectatorSpawnPoint( vec3_t origin, vec3_t angles ) {
+ FindIntermissionPoint();
+
+ VectorCopy( level.intermission_origin, origin );
+ VectorCopy( level.intermission_angle, angles );
+
+ return NULL;
+}
+
+/*
+=======================================================================
+
+BODYQUE
+
+=======================================================================
+*/
+
+/*
+===============
+InitBodyQue
+===============
+*/
+void InitBodyQue (void) {
+ int i;
+ gentity_t *ent;
+
+ level.bodyQueIndex = 0;
+ for (i=0; i<BODY_QUEUE_SIZE ; i++) {
+ ent = G_Spawn();
+ ent->classname = "bodyque";
+ ent->neverFree = qtrue;
+ level.bodyQue[i] = ent;
+ }
+}
+
+/*
+=============
+BodySink
+
+After sitting around for five seconds, fall into the ground and dissapear
+=============
+*/
+void BodySink( gentity_t *ent ) {
+ if ( level.time - ent->timestamp > 6500 ) {
+ // the body ques are never actually freed, they are just unlinked
+ trap_UnlinkEntity( ent );
+ ent->physicsObject = qfalse;
+ return;
+ }
+ ent->nextthink = level.time + 100;
+ ent->s.pos.trBase[2] -= 1;
+}
+
+/*
+=============
+CopyToBodyQue
+
+A player is respawning, so make an entity that looks
+just like the existing corpse to leave behind.
+=============
+*/
+void CopyToBodyQue( gentity_t *ent ) {
+#ifdef MISSIONPACK
+ gentity_t *e;
+ int i;
+#endif
+ gentity_t *body;
+ int contents;
+
+ trap_UnlinkEntity (ent);
+
+ // if client is in a nodrop area, don't leave the body
+ contents = trap_PointContents( ent->s.origin, -1 );
+ if ( contents & CONTENTS_NODROP ) {
+ return;
+ }
+
+ // grab a body que and cycle to the next one
+ body = level.bodyQue[ level.bodyQueIndex ];
+ level.bodyQueIndex = (level.bodyQueIndex + 1) % BODY_QUEUE_SIZE;
+
+ trap_UnlinkEntity (body);
+
+ body->s = ent->s;
+ body->s.eFlags = EF_DEAD; // clear EF_TALK, etc
+#ifdef MISSIONPACK
+ if ( ent->s.eFlags & EF_KAMIKAZE ) {
+ body->s.eFlags |= EF_KAMIKAZE;
+
+ // check if there is a kamikaze timer around for this owner
+ for (i = 0; i < MAX_GENTITIES; i++) {
+ e = &g_entities[i];
+ if (!e->inuse)
+ continue;
+ if (e->activator != ent)
+ continue;
+ if (strcmp(e->classname, "kamikaze timer"))
+ continue;
+ e->activator = body;
+ break;
+ }
+ }
+#endif
+ body->s.powerups = 0; // clear powerups
+ body->s.loopSound = 0; // clear lava burning
+ body->s.number = body - g_entities;
+ body->timestamp = level.time;
+ body->physicsObject = qtrue;
+ body->physicsBounce = 0; // don't bounce
+ if ( body->s.groundEntityNum == ENTITYNUM_NONE ) {
+ body->s.pos.trType = TR_GRAVITY;
+ body->s.pos.trTime = level.time;
+ VectorCopy( ent->client->ps.velocity, body->s.pos.trDelta );
+ } else {
+ body->s.pos.trType = TR_STATIONARY;
+ }
+ body->s.event = 0;
+
+ // change the animation to the last-frame only, so the sequence
+ // doesn't repeat anew for the body
+ switch ( body->s.legsAnim & ~ANIM_TOGGLEBIT ) {
+ case BOTH_DEATH1:
+ case BOTH_DEAD1:
+ body->s.torsoAnim = body->s.legsAnim = BOTH_DEAD1;
+ break;
+ case BOTH_DEATH2:
+ case BOTH_DEAD2:
+ body->s.torsoAnim = body->s.legsAnim = BOTH_DEAD2;
+ break;
+ case BOTH_DEATH3:
+ case BOTH_DEAD3:
+ default:
+ body->s.torsoAnim = body->s.legsAnim = BOTH_DEAD3;
+ break;
+ }
+
+ body->r.svFlags = ent->r.svFlags;
+ VectorCopy (ent->r.mins, body->r.mins);
+ VectorCopy (ent->r.maxs, body->r.maxs);
+ VectorCopy (ent->r.absmin, body->r.absmin);
+ VectorCopy (ent->r.absmax, body->r.absmax);
+
+ body->clipmask = CONTENTS_SOLID | CONTENTS_PLAYERCLIP;
+ body->r.contents = CONTENTS_CORPSE;
+ body->r.ownerNum = ent->s.number;
+
+ body->nextthink = level.time + 5000;
+ body->think = BodySink;
+
+ body->die = body_die;
+
+ // don't take more damage if already gibbed
+ if ( ent->health <= GIB_HEALTH ) {
+ body->takedamage = qfalse;
+ } else {
+ body->takedamage = qtrue;
+ }
+
+
+ VectorCopy ( body->s.pos.trBase, body->r.currentOrigin );
+ trap_LinkEntity (body);
+}
+
+//======================================================================
+
+
+/*
+==================
+SetClientViewAngle
+
+==================
+*/
+void SetClientViewAngle( gentity_t *ent, vec3_t angle ) {
+ int i;
+
+ // set the delta angle
+ for (i=0 ; i<3 ; i++) {
+ int cmdAngle;
+
+ cmdAngle = ANGLE2SHORT(angle[i]);
+ ent->client->ps.delta_angles[i] = cmdAngle - ent->client->pers.cmd.angles[i];
+ }
+ VectorCopy( angle, ent->s.angles );
+ VectorCopy (ent->s.angles, ent->client->ps.viewangles);
+}
+
+/*
+================
+respawn
+================
+*/
+void respawn( gentity_t *ent ) {
+ gentity_t *tent;
+
+ CopyToBodyQue (ent);
+ ClientSpawn(ent);
+
+ // add a teleportation effect
+ tent = G_TempEntity( ent->client->ps.origin, EV_PLAYER_TELEPORT_IN );
+ tent->s.clientNum = ent->s.clientNum;
+}
+
+/*
+================
+TeamCount
+
+Returns number of players on a team
+================
+*/
+team_t TeamCount( int ignoreClientNum, int team ) {
+ int i;
+ int count = 0;
+
+ for ( i = 0 ; i < level.maxclients ; i++ ) {
+ if ( i == ignoreClientNum ) {
+ continue;
+ }
+ if ( level.clients[i].pers.connected == CON_DISCONNECTED ) {
+ continue;
+ }
+ if ( level.clients[i].sess.sessionTeam == team ) {
+ count++;
+ }
+ }
+
+ return count;
+}
+
+/*
+================
+TeamLeader
+
+Returns the client number of the team leader
+================
+*/
+int TeamLeader( int team ) {
+ int i;
+
+ for ( i = 0 ; i < level.maxclients ; i++ ) {
+ if ( level.clients[i].pers.connected == CON_DISCONNECTED ) {
+ continue;
+ }
+ if ( level.clients[i].sess.sessionTeam == team ) {
+ if ( level.clients[i].sess.teamLeader )
+ return i;
+ }
+ }
+
+ return -1;
+}
+
+
+/*
+================
+PickTeam
+
+================
+*/
+team_t PickTeam( int ignoreClientNum ) {
+ int counts[TEAM_NUM_TEAMS];
+
+ counts[TEAM_BLUE] = TeamCount( ignoreClientNum, TEAM_BLUE );
+ counts[TEAM_RED] = TeamCount( ignoreClientNum, TEAM_RED );
+
+ if ( counts[TEAM_BLUE] > counts[TEAM_RED] ) {
+ return TEAM_RED;
+ }
+ if ( counts[TEAM_RED] > counts[TEAM_BLUE] ) {
+ return TEAM_BLUE;
+ }
+ // equal team count, so join the team with the lowest score
+ if ( level.teamScores[TEAM_BLUE] > level.teamScores[TEAM_RED] ) {
+ return TEAM_RED;
+ }
+ return TEAM_BLUE;
+}
+
+/*
+===========
+ForceClientSkin
+
+Forces a client's skin (for teamplay)
+===========
+*/
+/*
+static void ForceClientSkin( gclient_t *client, char *model, const char *skin ) {
+ char *p;
+
+ if ((p = Q_strrchr(model, '/')) != 0) {
+ *p = 0;
+ }
+
+ Q_strcat(model, MAX_QPATH, "/");
+ Q_strcat(model, MAX_QPATH, skin);
+}
+*/
+
+/*
+===========
+ClientCheckName
+============
+*/
+static void ClientCleanName( const char *in, char *out, int outSize ) {
+ int len, colorlessLen;
+ char ch;
+ char *p;
+ int spaces;
+
+ //save room for trailing null byte
+ outSize--;
+
+ len = 0;
+ colorlessLen = 0;
+ p = out;
+ *p = 0;
+ spaces = 0;
+
+ while( 1 ) {
+ ch = *in++;
+ if( !ch ) {
+ break;
+ }
+
+ // don't allow leading spaces
+ if( !*p && ch == ' ' ) {
+ continue;
+ }
+
+ // check colors
+ if( ch == Q_COLOR_ESCAPE ) {
+ // solo trailing carat is not a color prefix
+ if( !*in ) {
+ break;
+ }
+
+ // don't allow black in a name, period
+ if( ColorIndex(*in) == 0 ) {
+ in++;
+ continue;
+ }
+
+ // make sure room in dest for both chars
+ if( len > outSize - 2 ) {
+ break;
+ }
+
+ *out++ = ch;
+ *out++ = *in++;
+ len += 2;
+ continue;
+ }
+
+ // don't allow too many consecutive spaces
+ if( ch == ' ' ) {
+ spaces++;
+ if( spaces > 3 ) {
+ continue;
+ }
+ }
+ else {
+ spaces = 0;
+ }
+
+ if( len > outSize - 1 ) {
+ break;
+ }
+
+ *out++ = ch;
+ colorlessLen++;
+ len++;
+ }
+ *out = 0;
+
+ // don't allow empty names
+ if( *p == 0 || colorlessLen == 0 ) {
+ Q_strncpyz( p, "UnnamedPlayer", outSize );
+ }
+}
+
+
+/*
+===========
+ClientUserInfoChanged
+
+Called from ClientConnect when the player first connects and
+directly by the server system when the player updates a userinfo variable.
+
+The game can override any of the settings and call trap_SetUserinfo
+if desired.
+============
+*/
+void ClientUserinfoChanged( int clientNum ) {
+ gentity_t *ent;
+ int teamTask, teamLeader, team, health;
+ char *s;
+ char model[MAX_QPATH];
+ char headModel[MAX_QPATH];
+ char oldname[MAX_STRING_CHARS];
+ gclient_t *client;
+ char c1[MAX_INFO_STRING];
+ char c2[MAX_INFO_STRING];
+ char redTeam[MAX_INFO_STRING];
+ char blueTeam[MAX_INFO_STRING];
+ char userinfo[MAX_INFO_STRING];
+
+ ent = g_entities + clientNum;
+ client = ent->client;
+
+ trap_GetUserinfo( clientNum, userinfo, sizeof( userinfo ) );
+
+ // check for malformed or illegal info strings
+ if ( !Info_Validate(userinfo) ) {
+ strcpy (userinfo, "\\name\\badinfo");
+ }
+
+ // check for local client
+ s = Info_ValueForKey( userinfo, "ip" );
+ if ( !strcmp( s, "localhost" ) ) {
+ client->pers.localClient = qtrue;
+ }
+
+ // check the item prediction
+ s = Info_ValueForKey( userinfo, "cg_predictItems" );
+ if ( !atoi( s ) ) {
+ client->pers.predictItemPickup = qfalse;
+ } else {
+ client->pers.predictItemPickup = qtrue;
+ }
+
+ // set name
+ Q_strncpyz ( oldname, client->pers.netname, sizeof( oldname ) );
+ s = Info_ValueForKey (userinfo, "name");
+ ClientCleanName( s, client->pers.netname, sizeof(client->pers.netname) );
+
+ if ( client->sess.sessionTeam == TEAM_SPECTATOR ) {
+ if ( client->sess.spectatorState == SPECTATOR_SCOREBOARD ) {
+ Q_strncpyz( client->pers.netname, "scoreboard", sizeof(client->pers.netname) );
+ }
+ }
+
+ if ( client->pers.connected == CON_CONNECTED ) {
+ if ( strcmp( oldname, client->pers.netname ) ) {
+ trap_SendServerCommand( -1, va("print \"%s" S_COLOR_WHITE " renamed to %s\n\"", oldname,
+ client->pers.netname) );
+ }
+ }
+
+ // set max health
+#ifdef MISSIONPACK
+ if (client->ps.powerups[PW_GUARD]) {
+ client->pers.maxHealth = 200;
+ } else {
+ health = atoi( Info_ValueForKey( userinfo, "handicap" ) );
+ client->pers.maxHealth = health;
+ if ( client->pers.maxHealth < 1 || client->pers.maxHealth > 100 ) {
+ client->pers.maxHealth = 100;
+ }
+ }
+#else
+ health = atoi( Info_ValueForKey( userinfo, "handicap" ) );
+ client->pers.maxHealth = health;
+ if ( client->pers.maxHealth < 1 || client->pers.maxHealth > 100 ) {
+ client->pers.maxHealth = 100;
+ }
+#endif
+ client->ps.stats[STAT_MAX_HEALTH] = client->pers.maxHealth;
+
+ // set model
+ if( g_gametype.integer >= GT_TEAM ) {
+ Q_strncpyz( model, Info_ValueForKey (userinfo, "team_model"), sizeof( model ) );
+ Q_strncpyz( headModel, Info_ValueForKey (userinfo, "team_headmodel"), sizeof( headModel ) );
+ } else {
+ Q_strncpyz( model, Info_ValueForKey (userinfo, "model"), sizeof( model ) );
+ Q_strncpyz( headModel, Info_ValueForKey (userinfo, "headmodel"), sizeof( headModel ) );
+ }
+
+ // bots set their team a few frames later
+ if (g_gametype.integer >= GT_TEAM && g_entities[clientNum].r.svFlags & SVF_BOT) {
+ s = Info_ValueForKey( userinfo, "team" );
+ if ( !Q_stricmp( s, "red" ) || !Q_stricmp( s, "r" ) ) {
+ team = TEAM_RED;
+ } else if ( !Q_stricmp( s, "blue" ) || !Q_stricmp( s, "b" ) ) {
+ team = TEAM_BLUE;
+ } else {
+ // pick the team with the least number of players
+ team = PickTeam( clientNum );
+ }
+ }
+ else {
+ team = client->sess.sessionTeam;
+ }
+
+/* NOTE: all client side now
+
+ // team
+ switch( team ) {
+ case TEAM_RED:
+ ForceClientSkin(client, model, "red");
+// ForceClientSkin(client, headModel, "red");
+ break;
+ case TEAM_BLUE:
+ ForceClientSkin(client, model, "blue");
+// ForceClientSkin(client, headModel, "blue");
+ break;
+ }
+ // don't ever use a default skin in teamplay, it would just waste memory
+ // however bots will always join a team but they spawn in as spectator
+ if ( g_gametype.integer >= GT_TEAM && team == TEAM_SPECTATOR) {
+ ForceClientSkin(client, model, "red");
+// ForceClientSkin(client, headModel, "red");
+ }
+*/
+
+#ifdef MISSIONPACK
+ if (g_gametype.integer >= GT_TEAM) {
+ client->pers.teamInfo = qtrue;
+ } else {
+ s = Info_ValueForKey( userinfo, "teamoverlay" );
+ if ( ! *s || atoi( s ) != 0 ) {
+ client->pers.teamInfo = qtrue;
+ } else {
+ client->pers.teamInfo = qfalse;
+ }
+ }
+#else
+ // teamInfo
+ s = Info_ValueForKey( userinfo, "teamoverlay" );
+ if ( ! *s || atoi( s ) != 0 ) {
+ client->pers.teamInfo = qtrue;
+ } else {
+ client->pers.teamInfo = qfalse;
+ }
+#endif
+ /*
+ s = Info_ValueForKey( userinfo, "cg_pmove_fixed" );
+ if ( !*s || atoi( s ) == 0 ) {
+ client->pers.pmoveFixed = qfalse;
+ }
+ else {
+ client->pers.pmoveFixed = qtrue;
+ }
+ */
+
+ // team task (0 = none, 1 = offence, 2 = defence)
+ teamTask = atoi(Info_ValueForKey(userinfo, "teamtask"));
+ // team Leader (1 = leader, 0 is normal player)
+ teamLeader = client->sess.teamLeader;
+
+ // colors
+ strcpy(c1, Info_ValueForKey( userinfo, "color1" ));
+ strcpy(c2, Info_ValueForKey( userinfo, "color2" ));
+
+ strcpy(redTeam, Info_ValueForKey( userinfo, "g_redteam" ));
+ strcpy(blueTeam, Info_ValueForKey( userinfo, "g_blueteam" ));
+
+ // send over a subset of the userinfo keys so other clients can
+ // print scoreboards, display models, and play custom sounds
+ if ( ent->r.svFlags & SVF_BOT ) {
+ s = va("n\\%s\\t\\%i\\model\\%s\\hmodel\\%s\\c1\\%s\\c2\\%s\\hc\\%i\\w\\%i\\l\\%i\\skill\\%s\\tt\\%d\\tl\\%d",
+ client->pers.netname, team, model, headModel, c1, c2,
+ client->pers.maxHealth, client->sess.wins, client->sess.losses,
+ Info_ValueForKey( userinfo, "skill" ), teamTask, teamLeader );
+ } else {
+ s = va("n\\%s\\t\\%i\\model\\%s\\hmodel\\%s\\g_redteam\\%s\\g_blueteam\\%s\\c1\\%s\\c2\\%s\\hc\\%i\\w\\%i\\l\\%i\\tt\\%d\\tl\\%d",
+ client->pers.netname, client->sess.sessionTeam, model, headModel, redTeam, blueTeam, c1, c2,
+ client->pers.maxHealth, client->sess.wins, client->sess.losses, teamTask, teamLeader);
+ }
+
+ trap_SetConfigstring( CS_PLAYERS+clientNum, s );
+
+ // this is not the userinfo, more like the configstring actually
+ G_LogPrintf( "ClientUserinfoChanged: %i %s\n", clientNum, s );
+}
+
+
+/*
+===========
+ClientConnect
+
+Called when a player begins connecting to the server.
+Called again for every map change or tournement restart.
+
+The session information will be valid after exit.
+
+Return NULL if the client should be allowed, otherwise return
+a string with the reason for denial.
+
+Otherwise, the client will be sent the current gamestate
+and will eventually get to ClientBegin.
+
+firstTime will be qtrue the very first time a client connects
+to the server machine, but qfalse on map changes and tournement
+restarts.
+============
+*/
+char *ClientConnect( int clientNum, qboolean firstTime, qboolean isBot ) {
+ char *value;
+// char *areabits;
+ gclient_t *client;
+ char userinfo[MAX_INFO_STRING];
+ gentity_t *ent;
+
+ ent = &g_entities[ clientNum ];
+
+ trap_GetUserinfo( clientNum, userinfo, sizeof( userinfo ) );
+
+ // IP filtering
+ // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=500
+ // recommanding PB based IP / GUID banning, the builtin system is pretty limited
+ // check to see if they are on the banned IP list
+ value = Info_ValueForKey (userinfo, "ip");
+ if ( G_FilterPacket( value ) ) {
+ return "You are banned from this server.";
+ }
+
+ // we don't check password for bots and local client
+ // NOTE: local client <-> "ip" "localhost"
+ // this means this client is not running in our current process
+ if ( !( ent->r.svFlags & SVF_BOT ) && (strcmp(value, "localhost") != 0)) {
+ // check for a password
+ value = Info_ValueForKey (userinfo, "password");
+ if ( g_password.string[0] && Q_stricmp( g_password.string, "none" ) &&
+ strcmp( g_password.string, value) != 0) {
+ return "Invalid password";
+ }
+ }
+
+ // they can connect
+ ent->client = level.clients + clientNum;
+ client = ent->client;
+
+// areabits = client->areabits;
+
+ memset( client, 0, sizeof(*client) );
+
+ client->pers.connected = CON_CONNECTING;
+
+ // read or initialize the session data
+ if ( firstTime || level.newSession ) {
+ G_InitSessionData( client, userinfo );
+ }
+ G_ReadSessionData( client );
+
+ if( isBot ) {
+ ent->r.svFlags |= SVF_BOT;
+ ent->inuse = qtrue;
+ if( !G_BotConnect( clientNum, !firstTime ) ) {
+ return "BotConnectfailed";
+ }
+ }
+
+ // get and distribute relevent paramters
+ G_LogPrintf( "ClientConnect: %i\n", clientNum );
+ ClientUserinfoChanged( clientNum );
+
+ // don't do the "xxx connected" messages if they were caried over from previous level
+ if ( firstTime ) {
+ trap_SendServerCommand( -1, va("print \"%s" S_COLOR_WHITE " connected\n\"", client->pers.netname) );
+ }
+
+ if ( g_gametype.integer >= GT_TEAM &&
+ client->sess.sessionTeam != TEAM_SPECTATOR ) {
+ BroadcastTeamChange( client, -1 );
+ }
+
+ // count current clients and rank for scoreboard
+ CalculateRanks();
+
+ // for statistics
+// client->areabits = areabits;
+// if ( !client->areabits )
+// client->areabits = G_Alloc( (trap_AAS_PointReachabilityAreaIndex( NULL ) + 7) / 8 );
+
+ return NULL;
+}
+
+/*
+===========
+ClientBegin
+
+called when a client has finished connecting, and is ready
+to be placed into the level. This will happen every level load,
+and on transition between teams, but doesn't happen on respawns
+============
+*/
+void ClientBegin( int clientNum ) {
+ gentity_t *ent;
+ gclient_t *client;
+ gentity_t *tent;
+ int flags;
+
+ ent = g_entities + clientNum;
+
+ client = level.clients + clientNum;
+
+ if ( ent->r.linked ) {
+ trap_UnlinkEntity( ent );
+ }
+ G_InitGentity( ent );
+ ent->touch = 0;
+ ent->pain = 0;
+ ent->client = client;
+
+ client->pers.connected = CON_CONNECTED;
+ client->pers.enterTime = level.time;
+ client->pers.teamState.state = TEAM_BEGIN;
+
+ // save eflags around this, because changing teams will
+ // cause this to happen with a valid entity, and we
+ // want to make sure the teleport bit is set right
+ // so the viewpoint doesn't interpolate through the
+ // world to the new position
+ flags = client->ps.eFlags;
+ memset( &client->ps, 0, sizeof( client->ps ) );
+ client->ps.eFlags = flags;
+
+ // locate ent at a spawn point
+ ClientSpawn( ent );
+
+ if ( client->sess.sessionTeam != TEAM_SPECTATOR ) {
+ // send event
+ tent = G_TempEntity( ent->client->ps.origin, EV_PLAYER_TELEPORT_IN );
+ tent->s.clientNum = ent->s.clientNum;
+
+ if ( g_gametype.integer != GT_TOURNAMENT ) {
+ trap_SendServerCommand( -1, va("print \"%s" S_COLOR_WHITE " entered the game\n\"", client->pers.netname) );
+ }
+ }
+ G_LogPrintf( "ClientBegin: %i\n", clientNum );
+
+ // count current clients and rank for scoreboard
+ CalculateRanks();
+}
+
+/*
+===========
+ClientSpawn
+
+Called every time a client is placed fresh in the world:
+after the first ClientBegin, and after each respawn
+Initializes all non-persistant parts of playerState
+============
+*/
+void ClientSpawn(gentity_t *ent) {
+ int index;
+ vec3_t spawn_origin, spawn_angles;
+ gclient_t *client;
+ int i;
+ clientPersistant_t saved;
+ clientSession_t savedSess;
+ int persistant[MAX_PERSISTANT];
+ gentity_t *spawnPoint;
+ int flags;
+ int savedPing;
+// char *savedAreaBits;
+ int accuracy_hits, accuracy_shots;
+ int eventSequence;
+ char userinfo[MAX_INFO_STRING];
+
+ index = ent - g_entities;
+ client = ent->client;
+
+ // find a spawn point
+ // do it before setting health back up, so farthest
+ // ranging doesn't count this client
+ if ( client->sess.sessionTeam == TEAM_SPECTATOR ) {
+ spawnPoint = SelectSpectatorSpawnPoint (
+ spawn_origin, spawn_angles);
+ } else if (g_gametype.integer >= GT_CTF ) {
+ // all base oriented team games use the CTF spawn points
+ spawnPoint = SelectCTFSpawnPoint (
+ client->sess.sessionTeam,
+ client->pers.teamState.state,
+ spawn_origin, spawn_angles);
+ } else {
+ do {
+ // the first spawn should be at a good looking spot
+ if ( !client->pers.initialSpawn && client->pers.localClient ) {
+ client->pers.initialSpawn = qtrue;
+ spawnPoint = SelectInitialSpawnPoint( spawn_origin, spawn_angles );
+ } else {
+ // don't spawn near existing origin if possible
+ spawnPoint = SelectSpawnPoint (
+ client->ps.origin,
+ spawn_origin, spawn_angles);
+ }
+
+ // Tim needs to prevent bots from spawning at the initial point
+ // on q3dm0...
+ if ( ( spawnPoint->flags & FL_NO_BOTS ) && ( ent->r.svFlags & SVF_BOT ) ) {
+ continue; // try again
+ }
+ // just to be symetric, we have a nohumans option...
+ if ( ( spawnPoint->flags & FL_NO_HUMANS ) && !( ent->r.svFlags & SVF_BOT ) ) {
+ continue; // try again
+ }
+
+ break;
+
+ } while ( 1 );
+ }
+ client->pers.teamState.state = TEAM_ACTIVE;
+
+ // always clear the kamikaze flag
+ ent->s.eFlags &= ~EF_KAMIKAZE;
+
+ // toggle the teleport bit so the client knows to not lerp
+ // and never clear the voted flag
+ flags = ent->client->ps.eFlags & (EF_TELEPORT_BIT | EF_VOTED | EF_TEAMVOTED);
+ flags ^= EF_TELEPORT_BIT;
+
+ // clear everything but the persistant data
+
+ saved = client->pers;
+ savedSess = client->sess;
+ savedPing = client->ps.ping;
+// savedAreaBits = client->areabits;
+ accuracy_hits = client->accuracy_hits;
+ accuracy_shots = client->accuracy_shots;
+ for ( i = 0 ; i < MAX_PERSISTANT ; i++ ) {
+ persistant[i] = client->ps.persistant[i];
+ }
+ eventSequence = client->ps.eventSequence;
+
+ memset (client, 0, sizeof(*client)); // bk FIXME: Com_Memset?
+
+ client->pers = saved;
+ client->sess = savedSess;
+ client->ps.ping = savedPing;
+// client->areabits = savedAreaBits;
+ client->accuracy_hits = accuracy_hits;
+ client->accuracy_shots = accuracy_shots;
+ client->lastkilled_client = -1;
+
+ for ( i = 0 ; i < MAX_PERSISTANT ; i++ ) {
+ client->ps.persistant[i] = persistant[i];
+ }
+ client->ps.eventSequence = eventSequence;
+ // increment the spawncount so the client will detect the respawn
+ client->ps.persistant[PERS_SPAWN_COUNT]++;
+ client->ps.persistant[PERS_TEAM] = client->sess.sessionTeam;
+
+ client->airOutTime = level.time + 12000;
+
+ trap_GetUserinfo( index, userinfo, sizeof(userinfo) );
+ // set max health
+ client->pers.maxHealth = atoi( Info_ValueForKey( userinfo, "handicap" ) );
+ if ( client->pers.maxHealth < 1 || client->pers.maxHealth > 100 ) {
+ client->pers.maxHealth = 100;
+ }
+ // clear entity values
+ client->ps.stats[STAT_MAX_HEALTH] = client->pers.maxHealth;
+ client->ps.eFlags = flags;
+
+ ent->s.groundEntityNum = ENTITYNUM_NONE;
+ ent->client = &level.clients[index];
+ ent->takedamage = qtrue;
+ ent->inuse = qtrue;
+ ent->classname = "player";
+ ent->r.contents = CONTENTS_BODY;
+ ent->clipmask = MASK_PLAYERSOLID;
+ ent->die = player_die;
+ ent->waterlevel = 0;
+ ent->watertype = 0;
+ ent->flags = 0;
+
+ VectorCopy (playerMins, ent->r.mins);
+ VectorCopy (playerMaxs, ent->r.maxs);
+
+ client->ps.clientNum = index;
+
+ client->ps.stats[STAT_WEAPONS] = ( 1 << WP_MACHINEGUN );
+ if ( g_gametype.integer == GT_TEAM ) {
+ client->ps.ammo[WP_MACHINEGUN] = 50;
+ } else {
+ client->ps.ammo[WP_MACHINEGUN] = 100;
+ }
+
+ client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_GAUNTLET );
+ client->ps.ammo[WP_GAUNTLET] = -1;
+ client->ps.ammo[WP_GRAPPLING_HOOK] = -1;
+
+ // health will count down towards max_health
+ ent->health = client->ps.stats[STAT_HEALTH] = client->ps.stats[STAT_MAX_HEALTH] + 25;
+
+ G_SetOrigin( ent, spawn_origin );
+ VectorCopy( spawn_origin, client->ps.origin );
+
+ // the respawned flag will be cleared after the attack and jump keys come up
+ client->ps.pm_flags |= PMF_RESPAWNED;
+
+ trap_GetUsercmd( client - level.clients, &ent->client->pers.cmd );
+ SetClientViewAngle( ent, spawn_angles );
+
+ if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) {
+
+ } else {
+ G_KillBox( ent );
+ trap_LinkEntity (ent);
+
+ // force the base weapon up
+ client->ps.weapon = WP_MACHINEGUN;
+ client->ps.weaponstate = WEAPON_READY;
+
+ }
+
+ // don't allow full run speed for a bit
+ client->ps.pm_flags |= PMF_TIME_KNOCKBACK;
+ client->ps.pm_time = 100;
+
+ client->respawnTime = level.time;
+ client->inactivityTime = level.time + g_inactivity.integer * 1000;
+ client->latched_buttons = 0;
+
+ // set default animations
+ client->ps.torsoAnim = TORSO_STAND;
+ client->ps.legsAnim = LEGS_IDLE;
+
+ if ( level.intermissiontime ) {
+ MoveClientToIntermission( ent );
+ } else {
+ // fire the targets of the spawn point
+ G_UseTargets( spawnPoint, ent );
+
+ // select the highest weapon number available, after any
+ // spawn given items have fired
+ client->ps.weapon = 1;
+ for ( i = WP_NUM_WEAPONS - 1 ; i > 0 ; i-- ) {
+ if ( client->ps.stats[STAT_WEAPONS] & ( 1 << i ) ) {
+ client->ps.weapon = i;
+ break;
+ }
+ }
+ }
+
+ // run a client frame to drop exactly to the floor,
+ // initialize animations and other things
+ client->ps.commandTime = level.time - 100;
+ ent->client->pers.cmd.serverTime = level.time;
+ ClientThink( ent-g_entities );
+
+ // positively link the client, even if the command times are weird
+ if ( ent->client->sess.sessionTeam != TEAM_SPECTATOR ) {
+ BG_PlayerStateToEntityState( &client->ps, &ent->s, qtrue );
+ VectorCopy( ent->client->ps.origin, ent->r.currentOrigin );
+ trap_LinkEntity( ent );
+ }
+
+ // run the presend to set anything else
+ ClientEndFrame( ent );
+
+ // clear entity state values
+ BG_PlayerStateToEntityState( &client->ps, &ent->s, qtrue );
+}
+
+
+/*
+===========
+ClientDisconnect
+
+Called when a player drops from the server.
+Will not be called between levels.
+
+This should NOT be called directly by any game logic,
+call trap_DropClient(), which will call this and do
+server system housekeeping.
+============
+*/
+void ClientDisconnect( int clientNum ) {
+ gentity_t *ent;
+ gentity_t *tent;
+ int i;
+
+ // cleanup if we are kicking a bot that
+ // hasn't spawned yet
+ G_RemoveQueuedBotBegin( clientNum );
+
+ ent = g_entities + clientNum;
+ if ( !ent->client ) {
+ return;
+ }
+
+ // stop any following clients
+ for ( i = 0 ; i < level.maxclients ; i++ ) {
+ if ( level.clients[i].sess.sessionTeam == TEAM_SPECTATOR
+ && level.clients[i].sess.spectatorState == SPECTATOR_FOLLOW
+ && level.clients[i].sess.spectatorClient == clientNum ) {
+ StopFollowing( &g_entities[i] );
+ }
+ }
+
+ // send effect if they were completely connected
+ if ( ent->client->pers.connected == CON_CONNECTED
+ && ent->client->sess.sessionTeam != TEAM_SPECTATOR ) {
+ tent = G_TempEntity( ent->client->ps.origin, EV_PLAYER_TELEPORT_OUT );
+ tent->s.clientNum = ent->s.clientNum;
+
+ // They don't get to take powerups with them!
+ // Especially important for stuff like CTF flags
+ TossClientItems( ent );
+#ifdef MISSIONPACK
+ TossClientPersistantPowerups( ent );
+ if( g_gametype.integer == GT_HARVESTER ) {
+ TossClientCubes( ent );
+ }
+#endif
+
+ }
+
+ G_LogPrintf( "ClientDisconnect: %i\n", clientNum );
+
+ // if we are playing in tourney mode and losing, give a win to the other player
+ if ( (g_gametype.integer == GT_TOURNAMENT )
+ && !level.intermissiontime
+ && !level.warmupTime && level.sortedClients[1] == clientNum ) {
+ level.clients[ level.sortedClients[0] ].sess.wins++;
+ ClientUserinfoChanged( level.sortedClients[0] );
+ }
+
+ trap_UnlinkEntity (ent);
+ ent->s.modelindex = 0;
+ ent->inuse = qfalse;
+ ent->classname = "disconnected";
+ ent->client->pers.connected = CON_DISCONNECTED;
+ ent->client->ps.persistant[PERS_TEAM] = TEAM_FREE;
+ ent->client->sess.sessionTeam = TEAM_FREE;
+
+ trap_SetConfigstring( CS_PLAYERS + clientNum, "");
+
+ CalculateRanks();
+
+ if ( ent->r.svFlags & SVF_BOT ) {
+ BotAIShutdownClient( clientNum, qfalse );
+ }
+}
+
+
diff --git a/code/game/g_cmds.c b/code/game/g_cmds.c
new file mode 100755
index 0000000..e72c80e
--- /dev/null
+++ b/code/game/g_cmds.c
@@ -0,0 +1,1701 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#include "g_local.h"
+
+#include "../../ui/menudef.h" // for the voice chats
+
+/*
+==================
+DeathmatchScoreboardMessage
+
+==================
+*/
+void DeathmatchScoreboardMessage( gentity_t *ent ) {
+ char entry[1024];
+ char string[1400];
+ int stringlength;
+ int i, j;
+ gclient_t *cl;
+ int numSorted, scoreFlags, accuracy, perfect;
+
+ // send the latest information on all clients
+ string[0] = 0;
+ stringlength = 0;
+ scoreFlags = 0;
+
+ numSorted = level.numConnectedClients;
+
+ for (i=0 ; i < numSorted ; i++) {
+ int ping;
+
+ cl = &level.clients[level.sortedClients[i]];
+
+ if ( cl->pers.connected == CON_CONNECTING ) {
+ ping = -1;
+ } else {
+ ping = cl->ps.ping < 999 ? cl->ps.ping : 999;
+ }
+
+ if( cl->accuracy_shots ) {
+ accuracy = cl->accuracy_hits * 100 / cl->accuracy_shots;
+ }
+ else {
+ accuracy = 0;
+ }
+ perfect = ( cl->ps.persistant[PERS_RANK] == 0 && cl->ps.persistant[PERS_KILLED] == 0 ) ? 1 : 0;
+
+ Com_sprintf (entry, sizeof(entry),
+ " %i %i %i %i %i %i %i %i %i %i %i %i %i %i", level.sortedClients[i],
+ cl->ps.persistant[PERS_SCORE], ping, (level.time - cl->pers.enterTime)/60000,
+ scoreFlags, g_entities[level.sortedClients[i]].s.powerups, accuracy,
+ cl->ps.persistant[PERS_IMPRESSIVE_COUNT],
+ cl->ps.persistant[PERS_EXCELLENT_COUNT],
+ cl->ps.persistant[PERS_GAUNTLET_FRAG_COUNT],
+ cl->ps.persistant[PERS_DEFEND_COUNT],
+ cl->ps.persistant[PERS_ASSIST_COUNT],
+ perfect,
+ cl->ps.persistant[PERS_CAPTURES]);
+ j = strlen(entry);
+ if (stringlength + j > 1024)
+ break;
+ strcpy (string + stringlength, entry);
+ stringlength += j;
+ }
+
+ trap_SendServerCommand( ent-g_entities, va("scores %i %i %i%s", i,
+ level.teamScores[TEAM_RED], level.teamScores[TEAM_BLUE],
+ string ) );
+}
+
+
+/*
+==================
+Cmd_Score_f
+
+Request current scoreboard information
+==================
+*/
+void Cmd_Score_f( gentity_t *ent ) {
+ DeathmatchScoreboardMessage( ent );
+}
+
+
+
+/*
+==================
+CheatsOk
+==================
+*/
+qboolean CheatsOk( gentity_t *ent ) {
+ if ( !g_cheats.integer ) {
+ trap_SendServerCommand( ent-g_entities, va("print \"Cheats are not enabled on this server.\n\""));
+ return qfalse;
+ }
+ if ( ent->health <= 0 ) {
+ trap_SendServerCommand( ent-g_entities, va("print \"You must be alive to use this command.\n\""));
+ return qfalse;
+ }
+ return qtrue;
+}
+
+
+/*
+==================
+ConcatArgs
+==================
+*/
+char *ConcatArgs( int start ) {
+ int i, c, tlen;
+ static char line[MAX_STRING_CHARS];
+ int len;
+ char arg[MAX_STRING_CHARS];
+
+ len = 0;
+ c = trap_Argc();
+ for ( i = start ; i < c ; i++ ) {
+ trap_Argv( i, arg, sizeof( arg ) );
+ tlen = strlen( arg );
+ if ( len + tlen >= MAX_STRING_CHARS - 1 ) {
+ break;
+ }
+ memcpy( line + len, arg, tlen );
+ len += tlen;
+ if ( i != c - 1 ) {
+ line[len] = ' ';
+ len++;
+ }
+ }
+
+ line[len] = 0;
+
+ return line;
+}
+
+/*
+==================
+SanitizeString
+
+Remove case and control characters
+==================
+*/
+void SanitizeString( char *in, char *out ) {
+ while ( *in ) {
+ if ( *in == 27 ) {
+ in += 2; // skip color code
+ continue;
+ }
+ if ( *in < 32 ) {
+ in++;
+ continue;
+ }
+ *out++ = tolower( *in++ );
+ }
+
+ *out = 0;
+}
+
+/*
+==================
+ClientNumberFromString
+
+Returns a player number for either a number or name string
+Returns -1 if invalid
+==================
+*/
+int ClientNumberFromString( gentity_t *to, char *s ) {
+ gclient_t *cl;
+ int idnum;
+ char s2[MAX_STRING_CHARS];
+ char n2[MAX_STRING_CHARS];
+
+ // numeric values are just slot numbers
+ if (s[0] >= '0' && s[0] <= '9') {
+ idnum = atoi( s );
+ if ( idnum < 0 || idnum >= level.maxclients ) {
+ trap_SendServerCommand( to-g_entities, va("print \"Bad client slot: %i\n\"", idnum));
+ return -1;
+ }
+
+ cl = &level.clients[idnum];
+ if ( cl->pers.connected != CON_CONNECTED ) {
+ trap_SendServerCommand( to-g_entities, va("print \"Client %i is not active\n\"", idnum));
+ return -1;
+ }
+ return idnum;
+ }
+
+ // check for a name match
+ SanitizeString( s, s2 );
+ for ( idnum=0,cl=level.clients ; idnum < level.maxclients ; idnum++,cl++ ) {
+ if ( cl->pers.connected != CON_CONNECTED ) {
+ continue;
+ }
+ SanitizeString( cl->pers.netname, n2 );
+ if ( !strcmp( n2, s2 ) ) {
+ return idnum;
+ }
+ }
+
+ trap_SendServerCommand( to-g_entities, va("print \"User %s is not on the server\n\"", s));
+ return -1;
+}
+
+/*
+==================
+Cmd_Give_f
+
+Give items to a client
+==================
+*/
+void Cmd_Give_f (gentity_t *ent)
+{
+ char *name;
+ gitem_t *it;
+ int i;
+ qboolean give_all;
+ gentity_t *it_ent;
+ trace_t trace;
+
+ if ( !CheatsOk( ent ) ) {
+ return;
+ }
+
+ name = ConcatArgs( 1 );
+
+ if (Q_stricmp(name, "all") == 0)
+ give_all = qtrue;
+ else
+ give_all = qfalse;
+
+ if (give_all || Q_stricmp( name, "health") == 0)
+ {
+ ent->health = ent->client->ps.stats[STAT_MAX_HEALTH];
+ if (!give_all)
+ return;
+ }
+
+ if (give_all || Q_stricmp(name, "weapons") == 0)
+ {
+ ent->client->ps.stats[STAT_WEAPONS] = (1 << WP_NUM_WEAPONS) - 1 -
+ ( 1 << WP_GRAPPLING_HOOK ) - ( 1 << WP_NONE );
+ if (!give_all)
+ return;
+ }
+
+ if (give_all || Q_stricmp(name, "ammo") == 0)
+ {
+ for ( i = 0 ; i < MAX_WEAPONS ; i++ ) {
+ ent->client->ps.ammo[i] = 999;
+ }
+ if (!give_all)
+ return;
+ }
+
+ if (give_all || Q_stricmp(name, "armor") == 0)
+ {
+ ent->client->ps.stats[STAT_ARMOR] = 200;
+
+ if (!give_all)
+ return;
+ }
+
+ if (Q_stricmp(name, "excellent") == 0) {
+ ent->client->ps.persistant[PERS_EXCELLENT_COUNT]++;
+ return;
+ }
+ if (Q_stricmp(name, "impressive") == 0) {
+ ent->client->ps.persistant[PERS_IMPRESSIVE_COUNT]++;
+ return;
+ }
+ if (Q_stricmp(name, "gauntletaward") == 0) {
+ ent->client->ps.persistant[PERS_GAUNTLET_FRAG_COUNT]++;
+ return;
+ }
+ if (Q_stricmp(name, "defend") == 0) {
+ ent->client->ps.persistant[PERS_DEFEND_COUNT]++;
+ return;
+ }
+ if (Q_stricmp(name, "assist") == 0) {
+ ent->client->ps.persistant[PERS_ASSIST_COUNT]++;
+ return;
+ }
+
+ // spawn a specific item right on the player
+ if ( !give_all ) {
+ it = BG_FindItem (name);
+ if (!it) {
+ return;
+ }
+
+ it_ent = G_Spawn();
+ VectorCopy( ent->r.currentOrigin, it_ent->s.origin );
+ it_ent->classname = it->classname;
+ G_SpawnItem (it_ent, it);
+ FinishSpawningItem(it_ent );
+ memset( &trace, 0, sizeof( trace ) );
+ Touch_Item (it_ent, ent, &trace);
+ if (it_ent->inuse) {
+ G_FreeEntity( it_ent );
+ }
+ }
+}
+
+
+/*
+==================
+Cmd_God_f
+
+Sets client to godmode
+
+argv(0) god
+==================
+*/
+void Cmd_God_f (gentity_t *ent)
+{
+ char *msg;
+
+ if ( !CheatsOk( ent ) ) {
+ return;
+ }
+
+ ent->flags ^= FL_GODMODE;
+ if (!(ent->flags & FL_GODMODE) )
+ msg = "godmode OFF\n";
+ else
+ msg = "godmode ON\n";
+
+ trap_SendServerCommand( ent-g_entities, va("print \"%s\"", msg));
+}
+
+
+/*
+==================
+Cmd_Notarget_f
+
+Sets client to notarget
+
+argv(0) notarget
+==================
+*/
+void Cmd_Notarget_f( gentity_t *ent ) {
+ char *msg;
+
+ if ( !CheatsOk( ent ) ) {
+ return;
+ }
+
+ ent->flags ^= FL_NOTARGET;
+ if (!(ent->flags & FL_NOTARGET) )
+ msg = "notarget OFF\n";
+ else
+ msg = "notarget ON\n";
+
+ trap_SendServerCommand( ent-g_entities, va("print \"%s\"", msg));
+}
+
+
+/*
+==================
+Cmd_Noclip_f
+
+argv(0) noclip
+==================
+*/
+void Cmd_Noclip_f( gentity_t *ent ) {
+ char *msg;
+
+ if ( !CheatsOk( ent ) ) {
+ return;
+ }
+
+ if ( ent->client->noclip ) {
+ msg = "noclip OFF\n";
+ } else {
+ msg = "noclip ON\n";
+ }
+ ent->client->noclip = !ent->client->noclip;
+
+ trap_SendServerCommand( ent-g_entities, va("print \"%s\"", msg));
+}
+
+
+/*
+==================
+Cmd_LevelShot_f
+
+This is just to help generate the level pictures
+for the menus. It goes to the intermission immediately
+and sends over a command to the client to resize the view,
+hide the scoreboard, and take a special screenshot
+==================
+*/
+void Cmd_LevelShot_f( gentity_t *ent ) {
+ if ( !CheatsOk( ent ) ) {
+ return;
+ }
+
+ // doesn't work in single player
+ if ( g_gametype.integer != 0 ) {
+ trap_SendServerCommand( ent-g_entities,
+ "print \"Must be in g_gametype 0 for levelshot\n\"" );
+ return;
+ }
+
+ BeginIntermission();
+ trap_SendServerCommand( ent-g_entities, "clientLevelShot" );
+}
+
+
+/*
+==================
+Cmd_LevelShot_f
+
+This is just to help generate the level pictures
+for the menus. It goes to the intermission immediately
+and sends over a command to the client to resize the view,
+hide the scoreboard, and take a special screenshot
+==================
+*/
+void Cmd_TeamTask_f( gentity_t *ent ) {
+ char userinfo[MAX_INFO_STRING];
+ char arg[MAX_TOKEN_CHARS];
+ int task;
+ int client = ent->client - level.clients;
+
+ if ( trap_Argc() != 2 ) {
+ return;
+ }
+ trap_Argv( 1, arg, sizeof( arg ) );
+ task = atoi( arg );
+
+ trap_GetUserinfo(client, userinfo, sizeof(userinfo));
+ Info_SetValueForKey(userinfo, "teamtask", va("%d", task));
+ trap_SetUserinfo(client, userinfo);
+ ClientUserinfoChanged(client);
+}
+
+
+
+/*
+=================
+Cmd_Kill_f
+=================
+*/
+void Cmd_Kill_f( gentity_t *ent ) {
+ if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) {
+ return;
+ }
+ if (ent->health <= 0) {
+ return;
+ }
+ ent->flags &= ~FL_GODMODE;
+ ent->client->ps.stats[STAT_HEALTH] = ent->health = -999;
+ player_die (ent, ent, ent, 100000, MOD_SUICIDE);
+}
+
+/*
+=================
+BroadCastTeamChange
+
+Let everyone know about a team change
+=================
+*/
+void BroadcastTeamChange( gclient_t *client, int oldTeam )
+{
+ if ( client->sess.sessionTeam == TEAM_RED ) {
+ trap_SendServerCommand( -1, va("cp \"%s" S_COLOR_WHITE " joined the red team.\n\"",
+ client->pers.netname) );
+ } else if ( client->sess.sessionTeam == TEAM_BLUE ) {
+ trap_SendServerCommand( -1, va("cp \"%s" S_COLOR_WHITE " joined the blue team.\n\"",
+ client->pers.netname));
+ } else if ( client->sess.sessionTeam == TEAM_SPECTATOR && oldTeam != TEAM_SPECTATOR ) {
+ trap_SendServerCommand( -1, va("cp \"%s" S_COLOR_WHITE " joined the spectators.\n\"",
+ client->pers.netname));
+ } else if ( client->sess.sessionTeam == TEAM_FREE ) {
+ trap_SendServerCommand( -1, va("cp \"%s" S_COLOR_WHITE " joined the battle.\n\"",
+ client->pers.netname));
+ }
+}
+
+/*
+=================
+SetTeam
+=================
+*/
+void SetTeam( gentity_t *ent, char *s ) {
+ int team, oldTeam;
+ gclient_t *client;
+ int clientNum;
+ spectatorState_t specState;
+ int specClient;
+ int teamLeader;
+
+ //
+ // see what change is requested
+ //
+ client = ent->client;
+
+ clientNum = client - level.clients;
+ specClient = 0;
+ specState = SPECTATOR_NOT;
+ if ( !Q_stricmp( s, "scoreboard" ) || !Q_stricmp( s, "score" ) ) {
+ team = TEAM_SPECTATOR;
+ specState = SPECTATOR_SCOREBOARD;
+ } else if ( !Q_stricmp( s, "follow1" ) ) {
+ team = TEAM_SPECTATOR;
+ specState = SPECTATOR_FOLLOW;
+ specClient = -1;
+ } else if ( !Q_stricmp( s, "follow2" ) ) {
+ team = TEAM_SPECTATOR;
+ specState = SPECTATOR_FOLLOW;
+ specClient = -2;
+ } else if ( !Q_stricmp( s, "spectator" ) || !Q_stricmp( s, "s" ) ) {
+ team = TEAM_SPECTATOR;
+ specState = SPECTATOR_FREE;
+ } else if ( g_gametype.integer >= GT_TEAM ) {
+ // if running a team game, assign player to one of the teams
+ specState = SPECTATOR_NOT;
+ if ( !Q_stricmp( s, "red" ) || !Q_stricmp( s, "r" ) ) {
+ team = TEAM_RED;
+ } else if ( !Q_stricmp( s, "blue" ) || !Q_stricmp( s, "b" ) ) {
+ team = TEAM_BLUE;
+ } else {
+ // pick the team with the least number of players
+ team = PickTeam( clientNum );
+ }
+
+ if ( g_teamForceBalance.integer ) {
+ int counts[TEAM_NUM_TEAMS];
+
+ counts[TEAM_BLUE] = TeamCount( ent->client->ps.clientNum, TEAM_BLUE );
+ counts[TEAM_RED] = TeamCount( ent->client->ps.clientNum, TEAM_RED );
+
+ // We allow a spread of two
+ if ( team == TEAM_RED && counts[TEAM_RED] - counts[TEAM_BLUE] > 1 ) {
+ trap_SendServerCommand( ent->client->ps.clientNum,
+ "cp \"Red team has too many players.\n\"" );
+ return; // ignore the request
+ }
+ if ( team == TEAM_BLUE && counts[TEAM_BLUE] - counts[TEAM_RED] > 1 ) {
+ trap_SendServerCommand( ent->client->ps.clientNum,
+ "cp \"Blue team has too many players.\n\"" );
+ return; // ignore the request
+ }
+
+ // It's ok, the team we are switching to has less or same number of players
+ }
+
+ } else {
+ // force them to spectators if there aren't any spots free
+ team = TEAM_FREE;
+ }
+
+ // override decision if limiting the players
+ if ( (g_gametype.integer == GT_TOURNAMENT)
+ && level.numNonSpectatorClients >= 2 ) {
+ team = TEAM_SPECTATOR;
+ } else if ( g_maxGameClients.integer > 0 &&
+ level.numNonSpectatorClients >= g_maxGameClients.integer ) {
+ team = TEAM_SPECTATOR;
+ }
+
+ //
+ // decide if we will allow the change
+ //
+ oldTeam = client->sess.sessionTeam;
+ if ( team == oldTeam && team != TEAM_SPECTATOR ) {
+ return;
+ }
+
+ //
+ // execute the team change
+ //
+
+ // if the player was dead leave the body
+ if ( client->ps.stats[STAT_HEALTH] <= 0 ) {
+ CopyToBodyQue(ent);
+ }
+
+ // he starts at 'base'
+ client->pers.teamState.state = TEAM_BEGIN;
+ if ( oldTeam != TEAM_SPECTATOR ) {
+ // Kill him (makes sure he loses flags, etc)
+ ent->flags &= ~FL_GODMODE;
+ ent->client->ps.stats[STAT_HEALTH] = ent->health = 0;
+ player_die (ent, ent, ent, 100000, MOD_SUICIDE);
+
+ }
+ // they go to the end of the line for tournements
+ if ( team == TEAM_SPECTATOR ) {
+ client->sess.spectatorTime = level.time;
+ }
+
+ client->sess.sessionTeam = team;
+ client->sess.spectatorState = specState;
+ client->sess.spectatorClient = specClient;
+
+ client->sess.teamLeader = qfalse;
+ if ( team == TEAM_RED || team == TEAM_BLUE ) {
+ teamLeader = TeamLeader( team );
+ // if there is no team leader or the team leader is a bot and this client is not a bot
+ if ( teamLeader == -1 || ( !(g_entities[clientNum].r.svFlags & SVF_BOT) && (g_entities[teamLeader].r.svFlags & SVF_BOT) ) ) {
+ SetLeader( team, clientNum );
+ }
+ }
+ // make sure there is a team leader on the team the player came from
+ if ( oldTeam == TEAM_RED || oldTeam == TEAM_BLUE ) {
+ CheckTeamLeader( oldTeam );
+ }
+
+ BroadcastTeamChange( client, oldTeam );
+
+ // get and distribute relevent paramters
+ ClientUserinfoChanged( clientNum );
+
+ ClientBegin( clientNum );
+}
+
+/*
+=================
+StopFollowing
+
+If the client being followed leaves the game, or you just want to drop
+to free floating spectator mode
+=================
+*/
+void StopFollowing( gentity_t *ent ) {
+ ent->client->ps.persistant[ PERS_TEAM ] = TEAM_SPECTATOR;
+ ent->client->sess.sessionTeam = TEAM_SPECTATOR;
+ ent->client->sess.spectatorState = SPECTATOR_FREE;
+ ent->client->ps.pm_flags &= ~PMF_FOLLOW;
+ ent->r.svFlags &= ~SVF_BOT;
+ ent->client->ps.clientNum = ent - g_entities;
+}
+
+/*
+=================
+Cmd_Team_f
+=================
+*/
+void Cmd_Team_f( gentity_t *ent ) {
+ int oldTeam;
+ char s[MAX_TOKEN_CHARS];
+
+ if ( trap_Argc() != 2 ) {
+ oldTeam = ent->client->sess.sessionTeam;
+ switch ( oldTeam ) {
+ case TEAM_BLUE:
+ trap_SendServerCommand( ent-g_entities, "print \"Blue team\n\"" );
+ break;
+ case TEAM_RED:
+ trap_SendServerCommand( ent-g_entities, "print \"Red team\n\"" );
+ break;
+ case TEAM_FREE:
+ trap_SendServerCommand( ent-g_entities, "print \"Free team\n\"" );
+ break;
+ case TEAM_SPECTATOR:
+ trap_SendServerCommand( ent-g_entities, "print \"Spectator team\n\"" );
+ break;
+ }
+ return;
+ }
+
+ if ( ent->client->switchTeamTime > level.time ) {
+ trap_SendServerCommand( ent-g_entities, "print \"May not switch teams more than once per 5 seconds.\n\"" );
+ return;
+ }
+
+ // if they are playing a tournement game, count as a loss
+ if ( (g_gametype.integer == GT_TOURNAMENT )
+ && ent->client->sess.sessionTeam == TEAM_FREE ) {
+ ent->client->sess.losses++;
+ }
+
+ trap_Argv( 1, s, sizeof( s ) );
+
+ SetTeam( ent, s );
+
+ ent->client->switchTeamTime = level.time + 5000;
+}
+
+
+/*
+=================
+Cmd_Follow_f
+=================
+*/
+void Cmd_Follow_f( gentity_t *ent ) {
+ int i;
+ char arg[MAX_TOKEN_CHARS];
+
+ if ( trap_Argc() != 2 ) {
+ if ( ent->client->sess.spectatorState == SPECTATOR_FOLLOW ) {
+ StopFollowing( ent );
+ }
+ return;
+ }
+
+ trap_Argv( 1, arg, sizeof( arg ) );
+ i = ClientNumberFromString( ent, arg );
+ if ( i == -1 ) {
+ return;
+ }
+
+ // can't follow self
+ if ( &level.clients[ i ] == ent->client ) {
+ return;
+ }
+
+ // can't follow another spectator
+ if ( level.clients[ i ].sess.sessionTeam == TEAM_SPECTATOR ) {
+ return;
+ }
+
+ // if they are playing a tournement game, count as a loss
+ if ( (g_gametype.integer == GT_TOURNAMENT )
+ && ent->client->sess.sessionTeam == TEAM_FREE ) {
+ ent->client->sess.losses++;
+ }
+
+ // first set them to spectator
+ if ( ent->client->sess.sessionTeam != TEAM_SPECTATOR ) {
+ SetTeam( ent, "spectator" );
+ }
+
+ ent->client->sess.spectatorState = SPECTATOR_FOLLOW;
+ ent->client->sess.spectatorClient = i;
+}
+
+/*
+=================
+Cmd_FollowCycle_f
+=================
+*/
+void Cmd_FollowCycle_f( gentity_t *ent, int dir ) {
+ int clientnum;
+ int original;
+
+ // if they are playing a tournement game, count as a loss
+ if ( (g_gametype.integer == GT_TOURNAMENT )
+ && ent->client->sess.sessionTeam == TEAM_FREE ) {
+ ent->client->sess.losses++;
+ }
+ // first set them to spectator
+ if ( ent->client->sess.spectatorState == SPECTATOR_NOT ) {
+ SetTeam( ent, "spectator" );
+ }
+
+ if ( dir != 1 && dir != -1 ) {
+ G_Error( "Cmd_FollowCycle_f: bad dir %i", dir );
+ }
+
+ clientnum = ent->client->sess.spectatorClient;
+ original = clientnum;
+ do {
+ clientnum += dir;
+ if ( clientnum >= level.maxclients ) {
+ clientnum = 0;
+ }
+ if ( clientnum < 0 ) {
+ clientnum = level.maxclients - 1;
+ }
+
+ // can only follow connected clients
+ if ( level.clients[ clientnum ].pers.connected != CON_CONNECTED ) {
+ continue;
+ }
+
+ // can't follow another spectator
+ if ( level.clients[ clientnum ].sess.sessionTeam == TEAM_SPECTATOR ) {
+ continue;
+ }
+
+ // this is good, we can use it
+ ent->client->sess.spectatorClient = clientnum;
+ ent->client->sess.spectatorState = SPECTATOR_FOLLOW;
+ return;
+ } while ( clientnum != original );
+
+ // leave it where it was
+}
+
+
+/*
+==================
+G_Say
+==================
+*/
+
+static void G_SayTo( gentity_t *ent, gentity_t *other, int mode, int color, const char *name, const char *message ) {
+ if (!other) {
+ return;
+ }
+ if (!other->inuse) {
+ return;
+ }
+ if (!other->client) {
+ return;
+ }
+ if ( other->client->pers.connected != CON_CONNECTED ) {
+ return;
+ }
+ if ( mode == SAY_TEAM && !OnSameTeam(ent, other) ) {
+ return;
+ }
+ // no chatting to players in tournements
+ if ( (g_gametype.integer == GT_TOURNAMENT )
+ && other->client->sess.sessionTeam == TEAM_FREE
+ && ent->client->sess.sessionTeam != TEAM_FREE ) {
+ return;
+ }
+
+ trap_SendServerCommand( other-g_entities, va("%s \"%s%c%c%s\"",
+ mode == SAY_TEAM ? "tchat" : "chat",
+ name, Q_COLOR_ESCAPE, color, message));
+}
+
+#define EC "\x19"
+
+void G_Say( gentity_t *ent, gentity_t *target, int mode, const char *chatText ) {
+ int j;
+ gentity_t *other;
+ int color;
+ char name[64];
+ // don't let text be too long for malicious reasons
+ char text[MAX_SAY_TEXT];
+ char location[64];
+
+ if ( g_gametype.integer < GT_TEAM && mode == SAY_TEAM ) {
+ mode = SAY_ALL;
+ }
+
+ switch ( mode ) {
+ default:
+ case SAY_ALL:
+ G_LogPrintf( "say: %s: %s\n", ent->client->pers.netname, chatText );
+ Com_sprintf (name, sizeof(name), "%s%c%c"EC": ", ent->client->pers.netname, Q_COLOR_ESCAPE, COLOR_WHITE );
+ color = COLOR_GREEN;
+ break;
+ case SAY_TEAM:
+ G_LogPrintf( "sayteam: %s: %s\n", ent->client->pers.netname, chatText );
+ if (Team_GetLocationMsg(ent, location, sizeof(location)))
+ Com_sprintf (name, sizeof(name), EC"(%s%c%c"EC") (%s)"EC": ",
+ ent->client->pers.netname, Q_COLOR_ESCAPE, COLOR_WHITE, location);
+ else
+ Com_sprintf (name, sizeof(name), EC"(%s%c%c"EC")"EC": ",
+ ent->client->pers.netname, Q_COLOR_ESCAPE, COLOR_WHITE );
+ color = COLOR_CYAN;
+ break;
+ case SAY_TELL:
+ if (target && g_gametype.integer >= GT_TEAM &&
+ target->client->sess.sessionTeam == ent->client->sess.sessionTeam &&
+ Team_GetLocationMsg(ent, location, sizeof(location)))
+ Com_sprintf (name, sizeof(name), EC"[%s%c%c"EC"] (%s)"EC": ", ent->client->pers.netname, Q_COLOR_ESCAPE, COLOR_WHITE, location );
+ else
+ Com_sprintf (name, sizeof(name), EC"[%s%c%c"EC"]"EC": ", ent->client->pers.netname, Q_COLOR_ESCAPE, COLOR_WHITE );
+ color = COLOR_MAGENTA;
+ break;
+ }
+
+ Q_strncpyz( text, chatText, sizeof(text) );
+
+ if ( target ) {
+ G_SayTo( ent, target, mode, color, name, text );
+ return;
+ }
+
+ // echo the text to the console
+ if ( g_dedicated.integer ) {
+ G_Printf( "%s%s\n", name, text);
+ }
+
+ // send it to all the apropriate clients
+ for (j = 0; j < level.maxclients; j++) {
+ other = &g_entities[j];
+ G_SayTo( ent, other, mode, color, name, text );
+ }
+}
+
+
+/*
+==================
+Cmd_Say_f
+==================
+*/
+static void Cmd_Say_f( gentity_t *ent, int mode, qboolean arg0 ) {
+ char *p;
+
+ if ( trap_Argc () < 2 && !arg0 ) {
+ return;
+ }
+
+ if (arg0)
+ {
+ p = ConcatArgs( 0 );
+ }
+ else
+ {
+ p = ConcatArgs( 1 );
+ }
+
+ G_Say( ent, NULL, mode, p );
+}
+
+/*
+==================
+Cmd_Tell_f
+==================
+*/
+static void Cmd_Tell_f( gentity_t *ent ) {
+ int targetNum;
+ gentity_t *target;
+ char *p;
+ char arg[MAX_TOKEN_CHARS];
+
+ if ( trap_Argc () < 2 ) {
+ return;
+ }
+
+ trap_Argv( 1, arg, sizeof( arg ) );
+ targetNum = atoi( arg );
+ if ( targetNum < 0 || targetNum >= level.maxclients ) {
+ return;
+ }
+
+ target = &g_entities[targetNum];
+ if ( !target || !target->inuse || !target->client ) {
+ return;
+ }
+
+ p = ConcatArgs( 2 );
+
+ G_LogPrintf( "tell: %s to %s: %s\n", ent->client->pers.netname, target->client->pers.netname, p );
+ G_Say( ent, target, SAY_TELL, p );
+ // don't tell to the player self if it was already directed to this player
+ // also don't send the chat back to a bot
+ if ( ent != target && !(ent->r.svFlags & SVF_BOT)) {
+ G_Say( ent, ent, SAY_TELL, p );
+ }
+}
+
+
+static void G_VoiceTo( gentity_t *ent, gentity_t *other, int mode, const char *id, qboolean voiceonly ) {
+ int color;
+ char *cmd;
+
+ if (!other) {
+ return;
+ }
+ if (!other->inuse) {
+ return;
+ }
+ if (!other->client) {
+ return;
+ }
+ if ( mode == SAY_TEAM && !OnSameTeam(ent, other) ) {
+ return;
+ }
+ // no chatting to players in tournements
+ if ( (g_gametype.integer == GT_TOURNAMENT )) {
+ return;
+ }
+
+ if (mode == SAY_TEAM) {
+ color = COLOR_CYAN;
+ cmd = "vtchat";
+ }
+ else if (mode == SAY_TELL) {
+ color = COLOR_MAGENTA;
+ cmd = "vtell";
+ }
+ else {
+ color = COLOR_GREEN;
+ cmd = "vchat";
+ }
+
+ trap_SendServerCommand( other-g_entities, va("%s %d %d %d %s", cmd, voiceonly, ent->s.number, color, id));
+}
+
+void G_Voice( gentity_t *ent, gentity_t *target, int mode, const char *id, qboolean voiceonly ) {
+ int j;
+ gentity_t *other;
+
+ if ( g_gametype.integer < GT_TEAM && mode == SAY_TEAM ) {
+ mode = SAY_ALL;
+ }
+
+ if ( target ) {
+ G_VoiceTo( ent, target, mode, id, voiceonly );
+ return;
+ }
+
+ // echo the text to the console
+ if ( g_dedicated.integer ) {
+ G_Printf( "voice: %s %s\n", ent->client->pers.netname, id);
+ }
+
+ // send it to all the apropriate clients
+ for (j = 0; j < level.maxclients; j++) {
+ other = &g_entities[j];
+ G_VoiceTo( ent, other, mode, id, voiceonly );
+ }
+}
+
+/*
+==================
+Cmd_Voice_f
+==================
+*/
+static void Cmd_Voice_f( gentity_t *ent, int mode, qboolean arg0, qboolean voiceonly ) {
+ char *p;
+
+ if ( trap_Argc () < 2 && !arg0 ) {
+ return;
+ }
+
+ if (arg0)
+ {
+ p = ConcatArgs( 0 );
+ }
+ else
+ {
+ p = ConcatArgs( 1 );
+ }
+
+ G_Voice( ent, NULL, mode, p, voiceonly );
+}
+
+/*
+==================
+Cmd_VoiceTell_f
+==================
+*/
+static void Cmd_VoiceTell_f( gentity_t *ent, qboolean voiceonly ) {
+ int targetNum;
+ gentity_t *target;
+ char *id;
+ char arg[MAX_TOKEN_CHARS];
+
+ if ( trap_Argc () < 2 ) {
+ return;
+ }
+
+ trap_Argv( 1, arg, sizeof( arg ) );
+ targetNum = atoi( arg );
+ if ( targetNum < 0 || targetNum >= level.maxclients ) {
+ return;
+ }
+
+ target = &g_entities[targetNum];
+ if ( !target || !target->inuse || !target->client ) {
+ return;
+ }
+
+ id = ConcatArgs( 2 );
+
+ G_LogPrintf( "vtell: %s to %s: %s\n", ent->client->pers.netname, target->client->pers.netname, id );
+ G_Voice( ent, target, SAY_TELL, id, voiceonly );
+ // don't tell to the player self if it was already directed to this player
+ // also don't send the chat back to a bot
+ if ( ent != target && !(ent->r.svFlags & SVF_BOT)) {
+ G_Voice( ent, ent, SAY_TELL, id, voiceonly );
+ }
+}
+
+
+/*
+==================
+Cmd_VoiceTaunt_f
+==================
+*/
+static void Cmd_VoiceTaunt_f( gentity_t *ent ) {
+ gentity_t *who;
+ int i;
+
+ if (!ent->client) {
+ return;
+ }
+
+ // insult someone who just killed you
+ if (ent->enemy && ent->enemy->client && ent->enemy->client->lastkilled_client == ent->s.number) {
+ // i am a dead corpse
+ if (!(ent->enemy->r.svFlags & SVF_BOT)) {
+ G_Voice( ent, ent->enemy, SAY_TELL, VOICECHAT_DEATHINSULT, qfalse );
+ }
+ if (!(ent->r.svFlags & SVF_BOT)) {
+ G_Voice( ent, ent, SAY_TELL, VOICECHAT_DEATHINSULT, qfalse );
+ }
+ ent->enemy = NULL;
+ return;
+ }
+ // insult someone you just killed
+ if (ent->client->lastkilled_client >= 0 && ent->client->lastkilled_client != ent->s.number) {
+ who = g_entities + ent->client->lastkilled_client;
+ if (who->client) {
+ // who is the person I just killed
+ if (who->client->lasthurt_mod == MOD_GAUNTLET) {
+ if (!(who->r.svFlags & SVF_BOT)) {
+ G_Voice( ent, who, SAY_TELL, VOICECHAT_KILLGAUNTLET, qfalse ); // and I killed them with a gauntlet
+ }
+ if (!(ent->r.svFlags & SVF_BOT)) {
+ G_Voice( ent, ent, SAY_TELL, VOICECHAT_KILLGAUNTLET, qfalse );
+ }
+ } else {
+ if (!(who->r.svFlags & SVF_BOT)) {
+ G_Voice( ent, who, SAY_TELL, VOICECHAT_KILLINSULT, qfalse ); // and I killed them with something else
+ }
+ if (!(ent->r.svFlags & SVF_BOT)) {
+ G_Voice( ent, ent, SAY_TELL, VOICECHAT_KILLINSULT, qfalse );
+ }
+ }
+ ent->client->lastkilled_client = -1;
+ return;
+ }
+ }
+
+ if (g_gametype.integer >= GT_TEAM) {
+ // praise a team mate who just got a reward
+ for(i = 0; i < MAX_CLIENTS; i++) {
+ who = g_entities + i;
+ if (who->client && who != ent && who->client->sess.sessionTeam == ent->client->sess.sessionTeam) {
+ if (who->client->rewardTime > level.time) {
+ if (!(who->r.svFlags & SVF_BOT)) {
+ G_Voice( ent, who, SAY_TELL, VOICECHAT_PRAISE, qfalse );
+ }
+ if (!(ent->r.svFlags & SVF_BOT)) {
+ G_Voice( ent, ent, SAY_TELL, VOICECHAT_PRAISE, qfalse );
+ }
+ return;
+ }
+ }
+ }
+ }
+
+ // just say something
+ G_Voice( ent, NULL, SAY_ALL, VOICECHAT_TAUNT, qfalse );
+}
+
+
+
+static char *gc_orders[] = {
+ "hold your position",
+ "hold this position",
+ "come here",
+ "cover me",
+ "guard location",
+ "search and destroy",
+ "report"
+};
+
+void Cmd_GameCommand_f( gentity_t *ent ) {
+ int player;
+ int order;
+ char str[MAX_TOKEN_CHARS];
+
+ trap_Argv( 1, str, sizeof( str ) );
+ player = atoi( str );
+ trap_Argv( 2, str, sizeof( str ) );
+ order = atoi( str );
+
+ if ( player < 0 || player >= MAX_CLIENTS ) {
+ return;
+ }
+ if ( order < 0 || order > sizeof(gc_orders)/sizeof(char *) ) {
+ return;
+ }
+ G_Say( ent, &g_entities[player], SAY_TELL, gc_orders[order] );
+ G_Say( ent, ent, SAY_TELL, gc_orders[order] );
+}
+
+/*
+==================
+Cmd_Where_f
+==================
+*/
+void Cmd_Where_f( gentity_t *ent ) {
+ trap_SendServerCommand( ent-g_entities, va("print \"%s\n\"", vtos( ent->s.origin ) ) );
+}
+
+static const char *gameNames[] = {
+ "Free For All",
+ "Tournament",
+ "Single Player",
+ "Team Deathmatch",
+ "Capture the Flag",
+ "One Flag CTF",
+ "Overload",
+ "Harvester"
+};
+
+/*
+==================
+Cmd_CallVote_f
+==================
+*/
+void Cmd_CallVote_f( gentity_t *ent ) {
+ int i;
+ char arg1[MAX_STRING_TOKENS];
+ char arg2[MAX_STRING_TOKENS];
+
+ if ( !g_allowVote.integer ) {
+ trap_SendServerCommand( ent-g_entities, "print \"Voting not allowed here.\n\"" );
+ return;
+ }
+
+ if ( level.voteTime ) {
+ trap_SendServerCommand( ent-g_entities, "print \"A vote is already in progress.\n\"" );
+ return;
+ }
+ if ( ent->client->pers.voteCount >= MAX_VOTE_COUNT ) {
+ trap_SendServerCommand( ent-g_entities, "print \"You have called the maximum number of votes.\n\"" );
+ return;
+ }
+ if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) {
+ trap_SendServerCommand( ent-g_entities, "print \"Not allowed to call a vote as spectator.\n\"" );
+ return;
+ }
+
+ // make sure it is a valid command to vote on
+ trap_Argv( 1, arg1, sizeof( arg1 ) );
+ trap_Argv( 2, arg2, sizeof( arg2 ) );
+
+ if( strchr( arg1, ';' ) || strchr( arg2, ';' ) ) {
+ trap_SendServerCommand( ent-g_entities, "print \"Invalid vote string.\n\"" );
+ return;
+ }
+
+ if ( !Q_stricmp( arg1, "map_restart" ) ) {
+ } else if ( !Q_stricmp( arg1, "nextmap" ) ) {
+ } else if ( !Q_stricmp( arg1, "map" ) ) {
+ } else if ( !Q_stricmp( arg1, "g_gametype" ) ) {
+ } else if ( !Q_stricmp( arg1, "kick" ) ) {
+ } else if ( !Q_stricmp( arg1, "clientkick" ) ) {
+ } else if ( !Q_stricmp( arg1, "g_doWarmup" ) ) {
+ } else if ( !Q_stricmp( arg1, "timelimit" ) ) {
+ } else if ( !Q_stricmp( arg1, "fraglimit" ) ) {
+ } else {
+ trap_SendServerCommand( ent-g_entities, "print \"Invalid vote string.\n\"" );
+ trap_SendServerCommand( ent-g_entities, "print \"Vote commands are: map_restart, nextmap, map <mapname>, g_gametype <n>, kick <player>, clientkick <clientnum>, g_doWarmup, timelimit <time>, fraglimit <frags>.\n\"" );
+ return;
+ }
+
+ // if there is still a vote to be executed
+ if ( level.voteExecuteTime ) {
+ level.voteExecuteTime = 0;
+ trap_SendConsoleCommand( EXEC_APPEND, va("%s\n", level.voteString ) );
+ }
+
+ // special case for g_gametype, check for bad values
+ if ( !Q_stricmp( arg1, "g_gametype" ) ) {
+ i = atoi( arg2 );
+ if( i == GT_SINGLE_PLAYER || i < GT_FFA || i >= GT_MAX_GAME_TYPE) {
+ trap_SendServerCommand( ent-g_entities, "print \"Invalid gametype.\n\"" );
+ return;
+ }
+
+ Com_sprintf( level.voteString, sizeof( level.voteString ), "%s %d", arg1, i );
+ Com_sprintf( level.voteDisplayString, sizeof( level.voteDisplayString ), "%s %s", arg1, gameNames[i] );
+ } else if ( !Q_stricmp( arg1, "map" ) ) {
+ // special case for map changes, we want to reset the nextmap setting
+ // this allows a player to change maps, but not upset the map rotation
+ char s[MAX_STRING_CHARS];
+
+ trap_Cvar_VariableStringBuffer( "nextmap", s, sizeof(s) );
+ if (*s) {
+ Com_sprintf( level.voteString, sizeof( level.voteString ), "%s %s; set nextmap \"%s\"", arg1, arg2, s );
+ } else {
+ Com_sprintf( level.voteString, sizeof( level.voteString ), "%s %s", arg1, arg2 );
+ }
+ Com_sprintf( level.voteDisplayString, sizeof( level.voteDisplayString ), "%s", level.voteString );
+ } else if ( !Q_stricmp( arg1, "nextmap" ) ) {
+ char s[MAX_STRING_CHARS];
+
+ trap_Cvar_VariableStringBuffer( "nextmap", s, sizeof(s) );
+ if (!*s) {
+ trap_SendServerCommand( ent-g_entities, "print \"nextmap not set.\n\"" );
+ return;
+ }
+ Com_sprintf( level.voteString, sizeof( level.voteString ), "vstr nextmap");
+ Com_sprintf( level.voteDisplayString, sizeof( level.voteDisplayString ), "%s", level.voteString );
+ } else {
+ Com_sprintf( level.voteString, sizeof( level.voteString ), "%s \"%s\"", arg1, arg2 );
+ Com_sprintf( level.voteDisplayString, sizeof( level.voteDisplayString ), "%s", level.voteString );
+ }
+
+ trap_SendServerCommand( -1, va("print \"%s called a vote.\n\"", ent->client->pers.netname ) );
+
+ // start the voting, the caller autoamtically votes yes
+ level.voteTime = level.time;
+ level.voteYes = 1;
+ level.voteNo = 0;
+
+ for ( i = 0 ; i < level.maxclients ; i++ ) {
+ level.clients[i].ps.eFlags &= ~EF_VOTED;
+ }
+ ent->client->ps.eFlags |= EF_VOTED;
+
+ trap_SetConfigstring( CS_VOTE_TIME, va("%i", level.voteTime ) );
+ trap_SetConfigstring( CS_VOTE_STRING, level.voteDisplayString );
+ trap_SetConfigstring( CS_VOTE_YES, va("%i", level.voteYes ) );
+ trap_SetConfigstring( CS_VOTE_NO, va("%i", level.voteNo ) );
+}
+
+/*
+==================
+Cmd_Vote_f
+==================
+*/
+void Cmd_Vote_f( gentity_t *ent ) {
+ char msg[64];
+
+ if ( !level.voteTime ) {
+ trap_SendServerCommand( ent-g_entities, "print \"No vote in progress.\n\"" );
+ return;
+ }
+ if ( ent->client->ps.eFlags & EF_VOTED ) {
+ trap_SendServerCommand( ent-g_entities, "print \"Vote already cast.\n\"" );
+ return;
+ }
+ if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) {
+ trap_SendServerCommand( ent-g_entities, "print \"Not allowed to vote as spectator.\n\"" );
+ return;
+ }
+
+ trap_SendServerCommand( ent-g_entities, "print \"Vote cast.\n\"" );
+
+ ent->client->ps.eFlags |= EF_VOTED;
+
+ trap_Argv( 1, msg, sizeof( msg ) );
+
+ if ( msg[0] == 'y' || msg[1] == 'Y' || msg[1] == '1' ) {
+ level.voteYes++;
+ trap_SetConfigstring( CS_VOTE_YES, va("%i", level.voteYes ) );
+ } else {
+ level.voteNo++;
+ trap_SetConfigstring( CS_VOTE_NO, va("%i", level.voteNo ) );
+ }
+
+ // a majority will be determined in CheckVote, which will also account
+ // for players entering or leaving
+}
+
+/*
+==================
+Cmd_CallTeamVote_f
+==================
+*/
+void Cmd_CallTeamVote_f( gentity_t *ent ) {
+ int i, team, cs_offset;
+ char arg1[MAX_STRING_TOKENS];
+ char arg2[MAX_STRING_TOKENS];
+
+ team = ent->client->sess.sessionTeam;
+ if ( team == TEAM_RED )
+ cs_offset = 0;
+ else if ( team == TEAM_BLUE )
+ cs_offset = 1;
+ else
+ return;
+
+ if ( !g_allowVote.integer ) {
+ trap_SendServerCommand( ent-g_entities, "print \"Voting not allowed here.\n\"" );
+ return;
+ }
+
+ if ( level.teamVoteTime[cs_offset] ) {
+ trap_SendServerCommand( ent-g_entities, "print \"A team vote is already in progress.\n\"" );
+ return;
+ }
+ if ( ent->client->pers.teamVoteCount >= MAX_VOTE_COUNT ) {
+ trap_SendServerCommand( ent-g_entities, "print \"You have called the maximum number of team votes.\n\"" );
+ return;
+ }
+ if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) {
+ trap_SendServerCommand( ent-g_entities, "print \"Not allowed to call a vote as spectator.\n\"" );
+ return;
+ }
+
+ // make sure it is a valid command to vote on
+ trap_Argv( 1, arg1, sizeof( arg1 ) );
+ arg2[0] = '\0';
+ for ( i = 2; i < trap_Argc(); i++ ) {
+ if (i > 2)
+ strcat(arg2, " ");
+ trap_Argv( i, &arg2[strlen(arg2)], sizeof( arg2 ) - strlen(arg2) );
+ }
+
+ if( strchr( arg1, ';' ) || strchr( arg2, ';' ) ) {
+ trap_SendServerCommand( ent-g_entities, "print \"Invalid vote string.\n\"" );
+ return;
+ }
+
+ if ( !Q_stricmp( arg1, "leader" ) ) {
+ char netname[MAX_NETNAME], leader[MAX_NETNAME];
+
+ if ( !arg2[0] ) {
+ i = ent->client->ps.clientNum;
+ }
+ else {
+ // numeric values are just slot numbers
+ for (i = 0; i < 3; i++) {
+ if ( !arg2[i] || arg2[i] < '0' || arg2[i] > '9' )
+ break;
+ }
+ if ( i >= 3 || !arg2[i]) {
+ i = atoi( arg2 );
+ if ( i < 0 || i >= level.maxclients ) {
+ trap_SendServerCommand( ent-g_entities, va("print \"Bad client slot: %i\n\"", i) );
+ return;
+ }
+
+ if ( !g_entities[i].inuse ) {
+ trap_SendServerCommand( ent-g_entities, va("print \"Client %i is not active\n\"", i) );
+ return;
+ }
+ }
+ else {
+ Q_strncpyz(leader, arg2, sizeof(leader));
+ Q_CleanStr(leader);
+ for ( i = 0 ; i < level.maxclients ; i++ ) {
+ if ( level.clients[i].pers.connected == CON_DISCONNECTED )
+ continue;
+ if (level.clients[i].sess.sessionTeam != team)
+ continue;
+ Q_strncpyz(netname, level.clients[i].pers.netname, sizeof(netname));
+ Q_CleanStr(netname);
+ if ( !Q_stricmp(netname, leader) ) {
+ break;
+ }
+ }
+ if ( i >= level.maxclients ) {
+ trap_SendServerCommand( ent-g_entities, va("print \"%s is not a valid player on your team.\n\"", arg2) );
+ return;
+ }
+ }
+ }
+ Com_sprintf(arg2, sizeof(arg2), "%d", i);
+ } else {
+ trap_SendServerCommand( ent-g_entities, "print \"Invalid vote string.\n\"" );
+ trap_SendServerCommand( ent-g_entities, "print \"Team vote commands are: leader <player>.\n\"" );
+ return;
+ }
+
+ Com_sprintf( level.teamVoteString[cs_offset], sizeof( level.teamVoteString[cs_offset] ), "%s %s", arg1, arg2 );
+
+ for ( i = 0 ; i < level.maxclients ; i++ ) {
+ if ( level.clients[i].pers.connected == CON_DISCONNECTED )
+ continue;
+ if (level.clients[i].sess.sessionTeam == team)
+ trap_SendServerCommand( i, va("print \"%s called a team vote.\n\"", ent->client->pers.netname ) );
+ }
+
+ // start the voting, the caller autoamtically votes yes
+ level.teamVoteTime[cs_offset] = level.time;
+ level.teamVoteYes[cs_offset] = 1;
+ level.teamVoteNo[cs_offset] = 0;
+
+ for ( i = 0 ; i < level.maxclients ; i++ ) {
+ if (level.clients[i].sess.sessionTeam == team)
+ level.clients[i].ps.eFlags &= ~EF_TEAMVOTED;
+ }
+ ent->client->ps.eFlags |= EF_TEAMVOTED;
+
+ trap_SetConfigstring( CS_TEAMVOTE_TIME + cs_offset, va("%i", level.teamVoteTime[cs_offset] ) );
+ trap_SetConfigstring( CS_TEAMVOTE_STRING + cs_offset, level.teamVoteString[cs_offset] );
+ trap_SetConfigstring( CS_TEAMVOTE_YES + cs_offset, va("%i", level.teamVoteYes[cs_offset] ) );
+ trap_SetConfigstring( CS_TEAMVOTE_NO + cs_offset, va("%i", level.teamVoteNo[cs_offset] ) );
+}
+
+/*
+==================
+Cmd_TeamVote_f
+==================
+*/
+void Cmd_TeamVote_f( gentity_t *ent ) {
+ int team, cs_offset;
+ char msg[64];
+
+ team = ent->client->sess.sessionTeam;
+ if ( team == TEAM_RED )
+ cs_offset = 0;
+ else if ( team == TEAM_BLUE )
+ cs_offset = 1;
+ else
+ return;
+
+ if ( !level.teamVoteTime[cs_offset] ) {
+ trap_SendServerCommand( ent-g_entities, "print \"No team vote in progress.\n\"" );
+ return;
+ }
+ if ( ent->client->ps.eFlags & EF_TEAMVOTED ) {
+ trap_SendServerCommand( ent-g_entities, "print \"Team vote already cast.\n\"" );
+ return;
+ }
+ if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) {
+ trap_SendServerCommand( ent-g_entities, "print \"Not allowed to vote as spectator.\n\"" );
+ return;
+ }
+
+ trap_SendServerCommand( ent-g_entities, "print \"Team vote cast.\n\"" );
+
+ ent->client->ps.eFlags |= EF_TEAMVOTED;
+
+ trap_Argv( 1, msg, sizeof( msg ) );
+
+ if ( msg[0] == 'y' || msg[1] == 'Y' || msg[1] == '1' ) {
+ level.teamVoteYes[cs_offset]++;
+ trap_SetConfigstring( CS_TEAMVOTE_YES + cs_offset, va("%i", level.teamVoteYes[cs_offset] ) );
+ } else {
+ level.teamVoteNo[cs_offset]++;
+ trap_SetConfigstring( CS_TEAMVOTE_NO + cs_offset, va("%i", level.teamVoteNo[cs_offset] ) );
+ }
+
+ // a majority will be determined in TeamCheckVote, which will also account
+ // for players entering or leaving
+}
+
+
+/*
+=================
+Cmd_SetViewpos_f
+=================
+*/
+void Cmd_SetViewpos_f( gentity_t *ent ) {
+ vec3_t origin, angles;
+ char buffer[MAX_TOKEN_CHARS];
+ int i;
+
+ if ( !g_cheats.integer ) {
+ trap_SendServerCommand( ent-g_entities, va("print \"Cheats are not enabled on this server.\n\""));
+ return;
+ }
+ if ( trap_Argc() != 5 ) {
+ trap_SendServerCommand( ent-g_entities, va("print \"usage: setviewpos x y z yaw\n\""));
+ return;
+ }
+
+ VectorClear( angles );
+ for ( i = 0 ; i < 3 ; i++ ) {
+ trap_Argv( i + 1, buffer, sizeof( buffer ) );
+ origin[i] = atof( buffer );
+ }
+
+ trap_Argv( 4, buffer, sizeof( buffer ) );
+ angles[YAW] = atof( buffer );
+
+ TeleportPlayer( ent, origin, angles );
+}
+
+
+
+/*
+=================
+Cmd_Stats_f
+=================
+*/
+void Cmd_Stats_f( gentity_t *ent ) {
+/*
+ int max, n, i;
+
+ max = trap_AAS_PointReachabilityAreaIndex( NULL );
+
+ n = 0;
+ for ( i = 0; i < max; i++ ) {
+ if ( ent->client->areabits[i >> 3] & (1 << (i & 7)) )
+ n++;
+ }
+
+ //trap_SendServerCommand( ent-g_entities, va("print \"visited %d of %d areas\n\"", n, max));
+ trap_SendServerCommand( ent-g_entities, va("print \"%d%% level coverage\n\"", n * 100 / max));
+*/
+}
+
+/*
+=================
+ClientCommand
+=================
+*/
+void ClientCommand( int clientNum ) {
+ gentity_t *ent;
+ char cmd[MAX_TOKEN_CHARS];
+
+ ent = g_entities + clientNum;
+ if ( !ent->client ) {
+ return; // not fully in game yet
+ }
+
+
+ trap_Argv( 0, cmd, sizeof( cmd ) );
+
+ if (Q_stricmp (cmd, "say") == 0) {
+ Cmd_Say_f (ent, SAY_ALL, qfalse);
+ return;
+ }
+ if (Q_stricmp (cmd, "say_team") == 0) {
+ Cmd_Say_f (ent, SAY_TEAM, qfalse);
+ return;
+ }
+ if (Q_stricmp (cmd, "tell") == 0) {
+ Cmd_Tell_f ( ent );
+ return;
+ }
+ if (Q_stricmp (cmd, "vsay") == 0) {
+ Cmd_Voice_f (ent, SAY_ALL, qfalse, qfalse);
+ return;
+ }
+ if (Q_stricmp (cmd, "vsay_team") == 0) {
+ Cmd_Voice_f (ent, SAY_TEAM, qfalse, qfalse);
+ return;
+ }
+ if (Q_stricmp (cmd, "vtell") == 0) {
+ Cmd_VoiceTell_f ( ent, qfalse );
+ return;
+ }
+ if (Q_stricmp (cmd, "vosay") == 0) {
+ Cmd_Voice_f (ent, SAY_ALL, qfalse, qtrue);
+ return;
+ }
+ if (Q_stricmp (cmd, "vosay_team") == 0) {
+ Cmd_Voice_f (ent, SAY_TEAM, qfalse, qtrue);
+ return;
+ }
+ if (Q_stricmp (cmd, "votell") == 0) {
+ Cmd_VoiceTell_f ( ent, qtrue );
+ return;
+ }
+ if (Q_stricmp (cmd, "vtaunt") == 0) {
+ Cmd_VoiceTaunt_f ( ent );
+ return;
+ }
+ if (Q_stricmp (cmd, "score") == 0) {
+ Cmd_Score_f (ent);
+ return;
+ }
+
+ // ignore all other commands when at intermission
+ if (level.intermissiontime) {
+ Cmd_Say_f (ent, qfalse, qtrue);
+ return;
+ }
+
+ if (Q_stricmp (cmd, "give") == 0)
+ Cmd_Give_f (ent);
+ else if (Q_stricmp (cmd, "god") == 0)
+ Cmd_God_f (ent);
+ else if (Q_stricmp (cmd, "notarget") == 0)
+ Cmd_Notarget_f (ent);
+ else if (Q_stricmp (cmd, "noclip") == 0)
+ Cmd_Noclip_f (ent);
+ else if (Q_stricmp (cmd, "kill") == 0)
+ Cmd_Kill_f (ent);
+ else if (Q_stricmp (cmd, "teamtask") == 0)
+ Cmd_TeamTask_f (ent);
+ else if (Q_stricmp (cmd, "levelshot") == 0)
+ Cmd_LevelShot_f (ent);
+ else if (Q_stricmp (cmd, "follow") == 0)
+ Cmd_Follow_f (ent);
+ else if (Q_stricmp (cmd, "follownext") == 0)
+ Cmd_FollowCycle_f (ent, 1);
+ else if (Q_stricmp (cmd, "followprev") == 0)
+ Cmd_FollowCycle_f (ent, -1);
+ else if (Q_stricmp (cmd, "team") == 0)
+ Cmd_Team_f (ent);
+ else if (Q_stricmp (cmd, "where") == 0)
+ Cmd_Where_f (ent);
+ else if (Q_stricmp (cmd, "callvote") == 0)
+ Cmd_CallVote_f (ent);
+ else if (Q_stricmp (cmd, "vote") == 0)
+ Cmd_Vote_f (ent);
+ else if (Q_stricmp (cmd, "callteamvote") == 0)
+ Cmd_CallTeamVote_f (ent);
+ else if (Q_stricmp (cmd, "teamvote") == 0)
+ Cmd_TeamVote_f (ent);
+ else if (Q_stricmp (cmd, "gc") == 0)
+ Cmd_GameCommand_f( ent );
+ else if (Q_stricmp (cmd, "setviewpos") == 0)
+ Cmd_SetViewpos_f( ent );
+ else if (Q_stricmp (cmd, "stats") == 0)
+ Cmd_Stats_f( ent );
+ else
+ trap_SendServerCommand( clientNum, va("print \"unknown cmd %s\n\"", cmd ) );
+}
diff --git a/code/game/g_combat.c b/code/game/g_combat.c
new file mode 100755
index 0000000..ab7394a
--- /dev/null
+++ b/code/game/g_combat.c
@@ -0,0 +1,1195 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// g_combat.c
+
+#include "g_local.h"
+
+
+/*
+============
+ScorePlum
+============
+*/
+void ScorePlum( gentity_t *ent, vec3_t origin, int score ) {
+ gentity_t *plum;
+
+ plum = G_TempEntity( origin, EV_SCOREPLUM );
+ // only send this temp entity to a single client
+ plum->r.svFlags |= SVF_SINGLECLIENT;
+ plum->r.singleClient = ent->s.number;
+ //
+ plum->s.otherEntityNum = ent->s.number;
+ plum->s.time = score;
+}
+
+/*
+============
+AddScore
+
+Adds score to both the client and his team
+============
+*/
+void AddScore( gentity_t *ent, vec3_t origin, int score ) {
+ if ( !ent->client ) {
+ return;
+ }
+ // no scoring during pre-match warmup
+ if ( level.warmupTime ) {
+ return;
+ }
+ // show score plum
+ ScorePlum(ent, origin, score);
+ //
+ ent->client->ps.persistant[PERS_SCORE] += score;
+ if ( g_gametype.integer == GT_TEAM )
+ level.teamScores[ ent->client->ps.persistant[PERS_TEAM] ] += score;
+ CalculateRanks();
+}
+
+/*
+=================
+TossClientItems
+
+Toss the weapon and powerups for the killed player
+=================
+*/
+void TossClientItems( gentity_t *self ) {
+ gitem_t *item;
+ int weapon;
+ float angle;
+ int i;
+ gentity_t *drop;
+
+ // drop the weapon if not a gauntlet or machinegun
+ weapon = self->s.weapon;
+
+ // make a special check to see if they are changing to a new
+ // weapon that isn't the mg or gauntlet. Without this, a client
+ // can pick up a weapon, be killed, and not drop the weapon because
+ // their weapon change hasn't completed yet and they are still holding the MG.
+ if ( weapon == WP_MACHINEGUN || weapon == WP_GRAPPLING_HOOK ) {
+ if ( self->client->ps.weaponstate == WEAPON_DROPPING ) {
+ weapon = self->client->pers.cmd.weapon;
+ }
+ if ( !( self->client->ps.stats[STAT_WEAPONS] & ( 1 << weapon ) ) ) {
+ weapon = WP_NONE;
+ }
+ }
+
+ if ( weapon > WP_MACHINEGUN && weapon != WP_GRAPPLING_HOOK &&
+ self->client->ps.ammo[ weapon ] ) {
+ // find the item type for this weapon
+ item = BG_FindItemForWeapon( weapon );
+
+ // spawn the item
+ Drop_Item( self, item, 0 );
+ }
+
+ // drop all the powerups if not in teamplay
+ if ( g_gametype.integer != GT_TEAM ) {
+ angle = 45;
+ for ( i = 1 ; i < PW_NUM_POWERUPS ; i++ ) {
+ if ( self->client->ps.powerups[ i ] > level.time ) {
+ item = BG_FindItemForPowerup( i );
+ if ( !item ) {
+ continue;
+ }
+ drop = Drop_Item( self, item, angle );
+ // decide how many seconds it has left
+ drop->count = ( self->client->ps.powerups[ i ] - level.time ) / 1000;
+ if ( drop->count < 1 ) {
+ drop->count = 1;
+ }
+ angle += 45;
+ }
+ }
+ }
+}
+
+#ifdef MISSIONPACK
+
+/*
+=================
+TossClientCubes
+=================
+*/
+extern gentity_t *neutralObelisk;
+
+void TossClientCubes( gentity_t *self ) {
+ gitem_t *item;
+ gentity_t *drop;
+ vec3_t velocity;
+ vec3_t angles;
+ vec3_t origin;
+
+ self->client->ps.generic1 = 0;
+
+ // this should never happen but we should never
+ // get the server to crash due to skull being spawned in
+ if (!G_EntitiesFree()) {
+ return;
+ }
+
+ if( self->client->sess.sessionTeam == TEAM_RED ) {
+ item = BG_FindItem( "Red Cube" );
+ }
+ else {
+ item = BG_FindItem( "Blue Cube" );
+ }
+
+ angles[YAW] = (float)(level.time % 360);
+ angles[PITCH] = 0; // always forward
+ angles[ROLL] = 0;
+
+ AngleVectors( angles, velocity, NULL, NULL );
+ VectorScale( velocity, 150, velocity );
+ velocity[2] += 200 + crandom() * 50;
+
+ if( neutralObelisk ) {
+ VectorCopy( neutralObelisk->s.pos.trBase, origin );
+ origin[2] += 44;
+ } else {
+ VectorClear( origin ) ;
+ }
+
+ drop = LaunchItem( item, origin, velocity );
+
+ drop->nextthink = level.time + g_cubeTimeout.integer * 1000;
+ drop->think = G_FreeEntity;
+ drop->spawnflags = self->client->sess.sessionTeam;
+}
+
+
+/*
+=================
+TossClientPersistantPowerups
+=================
+*/
+void TossClientPersistantPowerups( gentity_t *ent ) {
+ gentity_t *powerup;
+
+ if( !ent->client ) {
+ return;
+ }
+
+ if( !ent->client->persistantPowerup ) {
+ return;
+ }
+
+ powerup = ent->client->persistantPowerup;
+
+ powerup->r.svFlags &= ~SVF_NOCLIENT;
+ powerup->s.eFlags &= ~EF_NODRAW;
+ powerup->r.contents = CONTENTS_TRIGGER;
+ trap_LinkEntity( powerup );
+
+ ent->client->ps.stats[STAT_PERSISTANT_POWERUP] = 0;
+ ent->client->persistantPowerup = NULL;
+}
+#endif
+
+
+/*
+==================
+LookAtKiller
+==================
+*/
+void LookAtKiller( gentity_t *self, gentity_t *inflictor, gentity_t *attacker ) {
+ vec3_t dir;
+ vec3_t angles;
+
+ if ( attacker && attacker != self ) {
+ VectorSubtract (attacker->s.pos.trBase, self->s.pos.trBase, dir);
+ } else if ( inflictor && inflictor != self ) {
+ VectorSubtract (inflictor->s.pos.trBase, self->s.pos.trBase, dir);
+ } else {
+ self->client->ps.stats[STAT_DEAD_YAW] = self->s.angles[YAW];
+ return;
+ }
+
+ self->client->ps.stats[STAT_DEAD_YAW] = vectoyaw ( dir );
+
+ angles[YAW] = vectoyaw ( dir );
+ angles[PITCH] = 0;
+ angles[ROLL] = 0;
+}
+
+/*
+==================
+GibEntity
+==================
+*/
+void GibEntity( gentity_t *self, int killer ) {
+ gentity_t *ent;
+ int i;
+
+ //if this entity still has kamikaze
+ if (self->s.eFlags & EF_KAMIKAZE) {
+ // check if there is a kamikaze timer around for this owner
+ for (i = 0; i < MAX_GENTITIES; i++) {
+ ent = &g_entities[i];
+ if (!ent->inuse)
+ continue;
+ if (ent->activator != self)
+ continue;
+ if (strcmp(ent->classname, "kamikaze timer"))
+ continue;
+ G_FreeEntity(ent);
+ break;
+ }
+ }
+ G_AddEvent( self, EV_GIB_PLAYER, killer );
+ self->takedamage = qfalse;
+ self->s.eType = ET_INVISIBLE;
+ self->r.contents = 0;
+}
+
+/*
+==================
+body_die
+==================
+*/
+void body_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath ) {
+ if ( self->health > GIB_HEALTH ) {
+ return;
+ }
+ if ( !g_blood.integer ) {
+ self->health = GIB_HEALTH+1;
+ return;
+ }
+
+ GibEntity( self, 0 );
+}
+
+
+// these are just for logging, the client prints its own messages
+char *modNames[] = {
+ "MOD_UNKNOWN",
+ "MOD_SHOTGUN",
+ "MOD_GAUNTLET",
+ "MOD_MACHINEGUN",
+ "MOD_GRENADE",
+ "MOD_GRENADE_SPLASH",
+ "MOD_ROCKET",
+ "MOD_ROCKET_SPLASH",
+ "MOD_PLASMA",
+ "MOD_PLASMA_SPLASH",
+ "MOD_RAILGUN",
+ "MOD_LIGHTNING",
+ "MOD_BFG",
+ "MOD_BFG_SPLASH",
+ "MOD_WATER",
+ "MOD_SLIME",
+ "MOD_LAVA",
+ "MOD_CRUSH",
+ "MOD_TELEFRAG",
+ "MOD_FALLING",
+ "MOD_SUICIDE",
+ "MOD_TARGET_LASER",
+ "MOD_TRIGGER_HURT",
+#ifdef MISSIONPACK
+ "MOD_NAIL",
+ "MOD_CHAINGUN",
+ "MOD_PROXIMITY_MINE",
+ "MOD_KAMIKAZE",
+ "MOD_JUICED",
+#endif
+ "MOD_GRAPPLE"
+};
+
+#ifdef MISSIONPACK
+/*
+==================
+Kamikaze_DeathActivate
+==================
+*/
+void Kamikaze_DeathActivate( gentity_t *ent ) {
+ G_StartKamikaze(ent);
+ G_FreeEntity(ent);
+}
+
+/*
+==================
+Kamikaze_DeathTimer
+==================
+*/
+void Kamikaze_DeathTimer( gentity_t *self ) {
+ gentity_t *ent;
+
+ ent = G_Spawn();
+ ent->classname = "kamikaze timer";
+ VectorCopy(self->s.pos.trBase, ent->s.pos.trBase);
+ ent->r.svFlags |= SVF_NOCLIENT;
+ ent->think = Kamikaze_DeathActivate;
+ ent->nextthink = level.time + 5 * 1000;
+
+ ent->activator = self;
+}
+
+#endif
+
+/*
+==================
+CheckAlmostCapture
+==================
+*/
+void CheckAlmostCapture( gentity_t *self, gentity_t *attacker ) {
+ gentity_t *ent;
+ vec3_t dir;
+ char *classname;
+
+ // if this player was carrying a flag
+ if ( self->client->ps.powerups[PW_REDFLAG] ||
+ self->client->ps.powerups[PW_BLUEFLAG] ||
+ self->client->ps.powerups[PW_NEUTRALFLAG] ) {
+ // get the goal flag this player should have been going for
+ if ( g_gametype.integer == GT_CTF ) {
+ if ( self->client->sess.sessionTeam == TEAM_BLUE ) {
+ classname = "team_CTF_blueflag";
+ }
+ else {
+ classname = "team_CTF_redflag";
+ }
+ }
+ else {
+ if ( self->client->sess.sessionTeam == TEAM_BLUE ) {
+ classname = "team_CTF_redflag";
+ }
+ else {
+ classname = "team_CTF_blueflag";
+ }
+ }
+ ent = NULL;
+ do
+ {
+ ent = G_Find(ent, FOFS(classname), classname);
+ } while (ent && (ent->flags & FL_DROPPED_ITEM));
+ // if we found the destination flag and it's not picked up
+ if (ent && !(ent->r.svFlags & SVF_NOCLIENT) ) {
+ // if the player was *very* close
+ VectorSubtract( self->client->ps.origin, ent->s.origin, dir );
+ if ( VectorLength(dir) < 200 ) {
+ self->client->ps.persistant[PERS_PLAYEREVENTS] ^= PLAYEREVENT_HOLYSHIT;
+ if ( attacker->client ) {
+ attacker->client->ps.persistant[PERS_PLAYEREVENTS] ^= PLAYEREVENT_HOLYSHIT;
+ }
+ }
+ }
+ }
+}
+
+/*
+==================
+CheckAlmostScored
+==================
+*/
+void CheckAlmostScored( gentity_t *self, gentity_t *attacker ) {
+ gentity_t *ent;
+ vec3_t dir;
+ char *classname;
+
+ // if the player was carrying cubes
+ if ( self->client->ps.generic1 ) {
+ if ( self->client->sess.sessionTeam == TEAM_BLUE ) {
+ classname = "team_redobelisk";
+ }
+ else {
+ classname = "team_blueobelisk";
+ }
+ ent = G_Find(NULL, FOFS(classname), classname);
+ // if we found the destination obelisk
+ if ( ent ) {
+ // if the player was *very* close
+ VectorSubtract( self->client->ps.origin, ent->s.origin, dir );
+ if ( VectorLength(dir) < 200 ) {
+ self->client->ps.persistant[PERS_PLAYEREVENTS] ^= PLAYEREVENT_HOLYSHIT;
+ if ( attacker->client ) {
+ attacker->client->ps.persistant[PERS_PLAYEREVENTS] ^= PLAYEREVENT_HOLYSHIT;
+ }
+ }
+ }
+ }
+}
+
+/*
+==================
+player_die
+==================
+*/
+void player_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath ) {
+ gentity_t *ent;
+ int anim;
+ int contents;
+ int killer;
+ int i;
+ char *killerName, *obit;
+
+ if ( self->client->ps.pm_type == PM_DEAD ) {
+ return;
+ }
+
+ if ( level.intermissiontime ) {
+ return;
+ }
+
+ // check for an almost capture
+ CheckAlmostCapture( self, attacker );
+ // check for a player that almost brought in cubes
+ CheckAlmostScored( self, attacker );
+
+ if (self->client && self->client->hook) {
+ Weapon_HookFree(self->client->hook);
+ }
+#ifdef MISSIONPACK
+ if ((self->client->ps.eFlags & EF_TICKING) && self->activator) {
+ self->client->ps.eFlags &= ~EF_TICKING;
+ self->activator->think = G_FreeEntity;
+ self->activator->nextthink = level.time;
+ }
+#endif
+ self->client->ps.pm_type = PM_DEAD;
+
+ if ( attacker ) {
+ killer = attacker->s.number;
+ if ( attacker->client ) {
+ killerName = attacker->client->pers.netname;
+ } else {
+ killerName = "<non-client>";
+ }
+ } else {
+ killer = ENTITYNUM_WORLD;
+ killerName = "<world>";
+ }
+
+ if ( killer < 0 || killer >= MAX_CLIENTS ) {
+ killer = ENTITYNUM_WORLD;
+ killerName = "<world>";
+ }
+
+ if ( meansOfDeath < 0 || meansOfDeath >= sizeof( modNames ) / sizeof( modNames[0] ) ) {
+ obit = "<bad obituary>";
+ } else {
+ obit = modNames[ meansOfDeath ];
+ }
+
+ G_LogPrintf("Kill: %i %i %i: %s killed %s by %s\n",
+ killer, self->s.number, meansOfDeath, killerName,
+ self->client->pers.netname, obit );
+
+ // broadcast the death event to everyone
+ ent = G_TempEntity( self->r.currentOrigin, EV_OBITUARY );
+ ent->s.eventParm = meansOfDeath;
+ ent->s.otherEntityNum = self->s.number;
+ ent->s.otherEntityNum2 = killer;
+ ent->r.svFlags = SVF_BROADCAST; // send to everyone
+
+ self->enemy = attacker;
+
+ self->client->ps.persistant[PERS_KILLED]++;
+
+ if (attacker && attacker->client) {
+ attacker->client->lastkilled_client = self->s.number;
+
+ if ( attacker == self || OnSameTeam (self, attacker ) ) {
+ AddScore( attacker, self->r.currentOrigin, -1 );
+ } else {
+ AddScore( attacker, self->r.currentOrigin, 1 );
+
+ if( meansOfDeath == MOD_GAUNTLET ) {
+
+ // play humiliation on player
+ attacker->client->ps.persistant[PERS_GAUNTLET_FRAG_COUNT]++;
+
+ // add the sprite over the player's head
+ attacker->client->ps.eFlags &= ~(EF_AWARD_IMPRESSIVE | EF_AWARD_EXCELLENT | EF_AWARD_GAUNTLET | EF_AWARD_ASSIST | EF_AWARD_DEFEND | EF_AWARD_CAP );
+ attacker->client->ps.eFlags |= EF_AWARD_GAUNTLET;
+ attacker->client->rewardTime = level.time + REWARD_SPRITE_TIME;
+
+ // also play humiliation on target
+ self->client->ps.persistant[PERS_PLAYEREVENTS] ^= PLAYEREVENT_GAUNTLETREWARD;
+ }
+
+ // check for two kills in a short amount of time
+ // if this is close enough to the last kill, give a reward sound
+ if ( level.time - attacker->client->lastKillTime < CARNAGE_REWARD_TIME ) {
+ // play excellent on player
+ attacker->client->ps.persistant[PERS_EXCELLENT_COUNT]++;
+
+ // add the sprite over the player's head
+ attacker->client->ps.eFlags &= ~(EF_AWARD_IMPRESSIVE | EF_AWARD_EXCELLENT | EF_AWARD_GAUNTLET | EF_AWARD_ASSIST | EF_AWARD_DEFEND | EF_AWARD_CAP );
+ attacker->client->ps.eFlags |= EF_AWARD_EXCELLENT;
+ attacker->client->rewardTime = level.time + REWARD_SPRITE_TIME;
+ }
+ attacker->client->lastKillTime = level.time;
+
+ }
+ } else {
+ AddScore( self, self->r.currentOrigin, -1 );
+ }
+
+ // Add team bonuses
+ Team_FragBonuses(self, inflictor, attacker);
+
+ // if I committed suicide, the flag does not fall, it returns.
+ if (meansOfDeath == MOD_SUICIDE) {
+ if ( self->client->ps.powerups[PW_NEUTRALFLAG] ) { // only happens in One Flag CTF
+ Team_ReturnFlag( TEAM_FREE );
+ self->client->ps.powerups[PW_NEUTRALFLAG] = 0;
+ }
+ else if ( self->client->ps.powerups[PW_REDFLAG] ) { // only happens in standard CTF
+ Team_ReturnFlag( TEAM_RED );
+ self->client->ps.powerups[PW_REDFLAG] = 0;
+ }
+ else if ( self->client->ps.powerups[PW_BLUEFLAG] ) { // only happens in standard CTF
+ Team_ReturnFlag( TEAM_BLUE );
+ self->client->ps.powerups[PW_BLUEFLAG] = 0;
+ }
+ }
+
+ // if client is in a nodrop area, don't drop anything (but return CTF flags!)
+ contents = trap_PointContents( self->r.currentOrigin, -1 );
+ if ( !( contents & CONTENTS_NODROP )) {
+ TossClientItems( self );
+ }
+ else {
+ if ( self->client->ps.powerups[PW_NEUTRALFLAG] ) { // only happens in One Flag CTF
+ Team_ReturnFlag( TEAM_FREE );
+ }
+ else if ( self->client->ps.powerups[PW_REDFLAG] ) { // only happens in standard CTF
+ Team_ReturnFlag( TEAM_RED );
+ }
+ else if ( self->client->ps.powerups[PW_BLUEFLAG] ) { // only happens in standard CTF
+ Team_ReturnFlag( TEAM_BLUE );
+ }
+ }
+#ifdef MISSIONPACK
+ TossClientPersistantPowerups( self );
+ if( g_gametype.integer == GT_HARVESTER ) {
+ TossClientCubes( self );
+ }
+#endif
+
+ Cmd_Score_f( self ); // show scores
+ // send updated scores to any clients that are following this one,
+ // or they would get stale scoreboards
+ for ( i = 0 ; i < level.maxclients ; i++ ) {
+ gclient_t *client;
+
+ client = &level.clients[i];
+ if ( client->pers.connected != CON_CONNECTED ) {
+ continue;
+ }
+ if ( client->sess.sessionTeam != TEAM_SPECTATOR ) {
+ continue;
+ }
+ if ( client->sess.spectatorClient == self->s.number ) {
+ Cmd_Score_f( g_entities + i );
+ }
+ }
+
+ self->takedamage = qtrue; // can still be gibbed
+
+ self->s.weapon = WP_NONE;
+ self->s.powerups = 0;
+ self->r.contents = CONTENTS_CORPSE;
+
+ self->s.angles[0] = 0;
+ self->s.angles[2] = 0;
+ LookAtKiller (self, inflictor, attacker);
+
+ VectorCopy( self->s.angles, self->client->ps.viewangles );
+
+ self->s.loopSound = 0;
+
+ self->r.maxs[2] = -8;
+
+ // don't allow respawn until the death anim is done
+ // g_forcerespawn may force spawning at some later time
+ self->client->respawnTime = level.time + 1700;
+
+ // remove powerups
+ memset( self->client->ps.powerups, 0, sizeof(self->client->ps.powerups) );
+
+ // never gib in a nodrop
+ if ( (self->health <= GIB_HEALTH && !(contents & CONTENTS_NODROP) && g_blood.integer) || meansOfDeath == MOD_SUICIDE) {
+ // gib death
+ GibEntity( self, killer );
+ } else {
+ // normal death
+ static int i;
+
+ switch ( i ) {
+ case 0:
+ anim = BOTH_DEATH1;
+ break;
+ case 1:
+ anim = BOTH_DEATH2;
+ break;
+ case 2:
+ default:
+ anim = BOTH_DEATH3;
+ break;
+ }
+
+ // for the no-blood option, we need to prevent the health
+ // from going to gib level
+ if ( self->health <= GIB_HEALTH ) {
+ self->health = GIB_HEALTH+1;
+ }
+
+ self->client->ps.legsAnim =
+ ( ( self->client->ps.legsAnim & ANIM_TOGGLEBIT ) ^ ANIM_TOGGLEBIT ) | anim;
+ self->client->ps.torsoAnim =
+ ( ( self->client->ps.torsoAnim & ANIM_TOGGLEBIT ) ^ ANIM_TOGGLEBIT ) | anim;
+
+ G_AddEvent( self, EV_DEATH1 + i, killer );
+
+ // the body can still be gibbed
+ self->die = body_die;
+
+ // globally cycle through the different death animations
+ i = ( i + 1 ) % 3;
+
+#ifdef MISSIONPACK
+ if (self->s.eFlags & EF_KAMIKAZE) {
+ Kamikaze_DeathTimer( self );
+ }
+#endif
+ }
+
+ trap_LinkEntity (self);
+
+}
+
+
+/*
+================
+CheckArmor
+================
+*/
+int CheckArmor (gentity_t *ent, int damage, int dflags)
+{
+ gclient_t *client;
+ int save;
+ int count;
+
+ if (!damage)
+ return 0;
+
+ client = ent->client;
+
+ if (!client)
+ return 0;
+
+ if (dflags & DAMAGE_NO_ARMOR)
+ return 0;
+
+ // armor
+ count = client->ps.stats[STAT_ARMOR];
+ save = ceil( damage * ARMOR_PROTECTION );
+ if (save >= count)
+ save = count;
+
+ if (!save)
+ return 0;
+
+ client->ps.stats[STAT_ARMOR] -= save;
+
+ return save;
+}
+
+/*
+================
+RaySphereIntersections
+================
+*/
+int RaySphereIntersections( vec3_t origin, float radius, vec3_t point, vec3_t dir, vec3_t intersections[2] ) {
+ float b, c, d, t;
+
+ // | origin - (point + t * dir) | = radius
+ // a = dir[0]^2 + dir[1]^2 + dir[2]^2;
+ // b = 2 * (dir[0] * (point[0] - origin[0]) + dir[1] * (point[1] - origin[1]) + dir[2] * (point[2] - origin[2]));
+ // c = (point[0] - origin[0])^2 + (point[1] - origin[1])^2 + (point[2] - origin[2])^2 - radius^2;
+
+ // normalize dir so a = 1
+ VectorNormalize(dir);
+ b = 2 * (dir[0] * (point[0] - origin[0]) + dir[1] * (point[1] - origin[1]) + dir[2] * (point[2] - origin[2]));
+ c = (point[0] - origin[0]) * (point[0] - origin[0]) +
+ (point[1] - origin[1]) * (point[1] - origin[1]) +
+ (point[2] - origin[2]) * (point[2] - origin[2]) -
+ radius * radius;
+
+ d = b * b - 4 * c;
+ if (d > 0) {
+ t = (- b + sqrt(d)) / 2;
+ VectorMA(point, t, dir, intersections[0]);
+ t = (- b - sqrt(d)) / 2;
+ VectorMA(point, t, dir, intersections[1]);
+ return 2;
+ }
+ else if (d == 0) {
+ t = (- b ) / 2;
+ VectorMA(point, t, dir, intersections[0]);
+ return 1;
+ }
+ return 0;
+}
+
+#ifdef MISSIONPACK
+/*
+================
+G_InvulnerabilityEffect
+================
+*/
+int G_InvulnerabilityEffect( gentity_t *targ, vec3_t dir, vec3_t point, vec3_t impactpoint, vec3_t bouncedir ) {
+ gentity_t *impact;
+ vec3_t intersections[2], vec;
+ int n;
+
+ if ( !targ->client ) {
+ return qfalse;
+ }
+ VectorCopy(dir, vec);
+ VectorInverse(vec);
+ // sphere model radius = 42 units
+ n = RaySphereIntersections( targ->client->ps.origin, 42, point, vec, intersections);
+ if (n > 0) {
+ impact = G_TempEntity( targ->client->ps.origin, EV_INVUL_IMPACT );
+ VectorSubtract(intersections[0], targ->client->ps.origin, vec);
+ vectoangles(vec, impact->s.angles);
+ impact->s.angles[0] += 90;
+ if (impact->s.angles[0] > 360)
+ impact->s.angles[0] -= 360;
+ if ( impactpoint ) {
+ VectorCopy( intersections[0], impactpoint );
+ }
+ if ( bouncedir ) {
+ VectorCopy( vec, bouncedir );
+ VectorNormalize( bouncedir );
+ }
+ return qtrue;
+ }
+ else {
+ return qfalse;
+ }
+}
+#endif
+/*
+============
+T_Damage
+
+targ entity that is being damaged
+inflictor entity that is causing the damage
+attacker entity that caused the inflictor to damage targ
+ example: targ=monster, inflictor=rocket, attacker=player
+
+dir direction of the attack for knockback
+point point at which the damage is being inflicted, used for headshots
+damage amount of damage being inflicted
+knockback force to be applied against targ as a result of the damage
+
+inflictor, attacker, dir, and point can be NULL for environmental effects
+
+dflags these flags are used to control how T_Damage works
+ DAMAGE_RADIUS damage was indirect (from a nearby explosion)
+ DAMAGE_NO_ARMOR armor does not protect from this damage
+ DAMAGE_NO_KNOCKBACK do not affect velocity, just view angles
+ DAMAGE_NO_PROTECTION kills godmode, armor, everything
+============
+*/
+
+void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker,
+ vec3_t dir, vec3_t point, int damage, int dflags, int mod ) {
+ gclient_t *client;
+ int take;
+ int save;
+ int asave;
+ int knockback;
+ int max;
+#ifdef MISSIONPACK
+ vec3_t bouncedir, impactpoint;
+#endif
+
+ if (!targ->takedamage) {
+ return;
+ }
+
+ // the intermission has allready been qualified for, so don't
+ // allow any extra scoring
+ if ( level.intermissionQueued ) {
+ return;
+ }
+#ifdef MISSIONPACK
+ if ( targ->client && mod != MOD_JUICED) {
+ if ( targ->client->invulnerabilityTime > level.time) {
+ if ( dir && point ) {
+ G_InvulnerabilityEffect( targ, dir, point, impactpoint, bouncedir );
+ }
+ return;
+ }
+ }
+#endif
+ if ( !inflictor ) {
+ inflictor = &g_entities[ENTITYNUM_WORLD];
+ }
+ if ( !attacker ) {
+ attacker = &g_entities[ENTITYNUM_WORLD];
+ }
+
+ // shootable doors / buttons don't actually have any health
+ if ( targ->s.eType == ET_MOVER ) {
+ if ( targ->use && targ->moverState == MOVER_POS1 ) {
+ targ->use( targ, inflictor, attacker );
+ }
+ return;
+ }
+#ifdef MISSIONPACK
+ if( g_gametype.integer == GT_OBELISK && CheckObeliskAttack( targ, attacker ) ) {
+ return;
+ }
+#endif
+ // reduce damage by the attacker's handicap value
+ // unless they are rocket jumping
+ if ( attacker->client && attacker != targ ) {
+ max = attacker->client->ps.stats[STAT_MAX_HEALTH];
+#ifdef MISSIONPACK
+ if( bg_itemlist[attacker->client->ps.stats[STAT_PERSISTANT_POWERUP]].giTag == PW_GUARD ) {
+ max /= 2;
+ }
+#endif
+ damage = damage * max / 100;
+ }
+
+ client = targ->client;
+
+ if ( client ) {
+ if ( client->noclip ) {
+ return;
+ }
+ }
+
+ if ( !dir ) {
+ dflags |= DAMAGE_NO_KNOCKBACK;
+ } else {
+ VectorNormalize(dir);
+ }
+
+ knockback = damage;
+ if ( knockback > 200 ) {
+ knockback = 200;
+ }
+ if ( targ->flags & FL_NO_KNOCKBACK ) {
+ knockback = 0;
+ }
+ if ( dflags & DAMAGE_NO_KNOCKBACK ) {
+ knockback = 0;
+ }
+
+ // figure momentum add, even if the damage won't be taken
+ if ( knockback && targ->client ) {
+ vec3_t kvel;
+ float mass;
+
+ mass = 200;
+
+ VectorScale (dir, g_knockback.value * (float)knockback / mass, kvel);
+ VectorAdd (targ->client->ps.velocity, kvel, targ->client->ps.velocity);
+
+ // set the timer so that the other client can't cancel
+ // out the movement immediately
+ if ( !targ->client->ps.pm_time ) {
+ int t;
+
+ t = knockback * 2;
+ if ( t < 50 ) {
+ t = 50;
+ }
+ if ( t > 200 ) {
+ t = 200;
+ }
+ targ->client->ps.pm_time = t;
+ targ->client->ps.pm_flags |= PMF_TIME_KNOCKBACK;
+ }
+ }
+
+ // check for completely getting out of the damage
+ if ( !(dflags & DAMAGE_NO_PROTECTION) ) {
+
+ // if TF_NO_FRIENDLY_FIRE is set, don't do damage to the target
+ // if the attacker was on the same team
+#ifdef MISSIONPACK
+ if ( mod != MOD_JUICED && targ != attacker && !(dflags & DAMAGE_NO_TEAM_PROTECTION) && OnSameTeam (targ, attacker) ) {
+#else
+ if ( targ != attacker && OnSameTeam (targ, attacker) ) {
+#endif
+ if ( !g_friendlyFire.integer ) {
+ return;
+ }
+ }
+#ifdef MISSIONPACK
+ if (mod == MOD_PROXIMITY_MINE) {
+ if (inflictor && inflictor->parent && OnSameTeam(targ, inflictor->parent)) {
+ return;
+ }
+ if (targ == attacker) {
+ return;
+ }
+ }
+#endif
+
+ // check for godmode
+ if ( targ->flags & FL_GODMODE ) {
+ return;
+ }
+ }
+
+ // battlesuit protects from all radius damage (but takes knockback)
+ // and protects 50% against all damage
+ if ( client && client->ps.powerups[PW_BATTLESUIT] ) {
+ G_AddEvent( targ, EV_POWERUP_BATTLESUIT, 0 );
+ if ( ( dflags & DAMAGE_RADIUS ) || ( mod == MOD_FALLING ) ) {
+ return;
+ }
+ damage *= 0.5;
+ }
+
+ // add to the attacker's hit counter (if the target isn't a general entity like a prox mine)
+ if ( attacker->client && targ != attacker && targ->health > 0
+ && targ->s.eType != ET_MISSILE
+ && targ->s.eType != ET_GENERAL) {
+ if ( OnSameTeam( targ, attacker ) ) {
+ attacker->client->ps.persistant[PERS_HITS]--;
+ } else {
+ attacker->client->ps.persistant[PERS_HITS]++;
+ }
+ attacker->client->ps.persistant[PERS_ATTACKEE_ARMOR] = (targ->health<<8)|(client->ps.stats[STAT_ARMOR]);
+ }
+
+ // always give half damage if hurting self
+ // calculated after knockback, so rocket jumping works
+ if ( targ == attacker) {
+ damage *= 0.5;
+ }
+
+ if ( damage < 1 ) {
+ damage = 1;
+ }
+ take = damage;
+ save = 0;
+
+ // save some from armor
+ asave = CheckArmor (targ, take, dflags);
+ take -= asave;
+
+ if ( g_debugDamage.integer ) {
+ G_Printf( "%i: client:%i health:%i damage:%i armor:%i\n", level.time, targ->s.number,
+ targ->health, take, asave );
+ }
+
+ // add to the damage inflicted on a player this frame
+ // the total will be turned into screen blends and view angle kicks
+ // at the end of the frame
+ if ( client ) {
+ if ( attacker ) {
+ client->ps.persistant[PERS_ATTACKER] = attacker->s.number;
+ } else {
+ client->ps.persistant[PERS_ATTACKER] = ENTITYNUM_WORLD;
+ }
+ client->damage_armor += asave;
+ client->damage_blood += take;
+ client->damage_knockback += knockback;
+ if ( dir ) {
+ VectorCopy ( dir, client->damage_from );
+ client->damage_fromWorld = qfalse;
+ } else {
+ VectorCopy ( targ->r.currentOrigin, client->damage_from );
+ client->damage_fromWorld = qtrue;
+ }
+ }
+
+ // See if it's the player hurting the emeny flag carrier
+#ifdef MISSIONPACK
+ if( g_gametype.integer == GT_CTF || g_gametype.integer == GT_1FCTF ) {
+#else
+ if( g_gametype.integer == GT_CTF) {
+#endif
+ Team_CheckHurtCarrier(targ, attacker);
+ }
+
+ if (targ->client) {
+ // set the last client who damaged the target
+ targ->client->lasthurt_client = attacker->s.number;
+ targ->client->lasthurt_mod = mod;
+ }
+
+ // do the damage
+ if (take) {
+ targ->health = targ->health - take;
+ if ( targ->client ) {
+ targ->client->ps.stats[STAT_HEALTH] = targ->health;
+ }
+
+ if ( targ->health <= 0 ) {
+ if ( client )
+ targ->flags |= FL_NO_KNOCKBACK;
+
+ if (targ->health < -999)
+ targ->health = -999;
+
+ targ->enemy = attacker;
+ targ->die (targ, inflictor, attacker, take, mod);
+ return;
+ } else if ( targ->pain ) {
+ targ->pain (targ, attacker, take);
+ }
+ }
+
+}
+
+
+/*
+============
+CanDamage
+
+Returns qtrue if the inflictor can directly damage the target. Used for
+explosions and melee attacks.
+============
+*/
+qboolean CanDamage (gentity_t *targ, vec3_t origin) {
+ vec3_t dest;
+ trace_t tr;
+ vec3_t midpoint;
+
+ // use the midpoint of the bounds instead of the origin, because
+ // bmodels may have their origin is 0,0,0
+ VectorAdd (targ->r.absmin, targ->r.absmax, midpoint);
+ VectorScale (midpoint, 0.5, midpoint);
+
+ VectorCopy (midpoint, dest);
+ trap_Trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID);
+ if (tr.fraction == 1.0 || tr.entityNum == targ->s.number)
+ return qtrue;
+
+ // this should probably check in the plane of projection,
+ // rather than in world coordinate, and also include Z
+ VectorCopy (midpoint, dest);
+ dest[0] += 15.0;
+ dest[1] += 15.0;
+ trap_Trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID);
+ if (tr.fraction == 1.0)
+ return qtrue;
+
+ VectorCopy (midpoint, dest);
+ dest[0] += 15.0;
+ dest[1] -= 15.0;
+ trap_Trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID);
+ if (tr.fraction == 1.0)
+ return qtrue;
+
+ VectorCopy (midpoint, dest);
+ dest[0] -= 15.0;
+ dest[1] += 15.0;
+ trap_Trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID);
+ if (tr.fraction == 1.0)
+ return qtrue;
+
+ VectorCopy (midpoint, dest);
+ dest[0] -= 15.0;
+ dest[1] -= 15.0;
+ trap_Trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID);
+ if (tr.fraction == 1.0)
+ return qtrue;
+
+
+ return qfalse;
+}
+
+
+/*
+============
+G_RadiusDamage
+============
+*/
+qboolean G_RadiusDamage ( vec3_t origin, gentity_t *attacker, float damage, float radius,
+ gentity_t *ignore, int mod) {
+ float points, dist;
+ gentity_t *ent;
+ int entityList[MAX_GENTITIES];
+ int numListedEntities;
+ vec3_t mins, maxs;
+ vec3_t v;
+ vec3_t dir;
+ int i, e;
+ qboolean hitClient = qfalse;
+
+ if ( radius < 1 ) {
+ radius = 1;
+ }
+
+ for ( i = 0 ; i < 3 ; i++ ) {
+ mins[i] = origin[i] - radius;
+ maxs[i] = origin[i] + radius;
+ }
+
+ numListedEntities = trap_EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES );
+
+ for ( e = 0 ; e < numListedEntities ; e++ ) {
+ ent = &g_entities[entityList[ e ]];
+
+ if (ent == ignore)
+ continue;
+ if (!ent->takedamage)
+ continue;
+
+ // find the distance from the edge of the bounding box
+ for ( i = 0 ; i < 3 ; i++ ) {
+ if ( origin[i] < ent->r.absmin[i] ) {
+ v[i] = ent->r.absmin[i] - origin[i];
+ } else if ( origin[i] > ent->r.absmax[i] ) {
+ v[i] = origin[i] - ent->r.absmax[i];
+ } else {
+ v[i] = 0;
+ }
+ }
+
+ dist = VectorLength( v );
+ if ( dist >= radius ) {
+ continue;
+ }
+
+ points = damage * ( 1.0 - dist / radius );
+
+ if( CanDamage (ent, origin) ) {
+ if( LogAccuracyHit( ent, attacker ) ) {
+ hitClient = qtrue;
+ }
+ VectorSubtract (ent->r.currentOrigin, origin, dir);
+ // push the center of mass higher than the origin so players
+ // get knocked into the air more
+ dir[2] += 24;
+ G_Damage (ent, NULL, attacker, dir, origin, (int)points, DAMAGE_RADIUS, mod);
+ }
+ }
+
+ return hitClient;
+}
diff --git a/code/game/g_items.c b/code/game/g_items.c
new file mode 100755
index 0000000..48d7b9f
--- /dev/null
+++ b/code/game/g_items.c
@@ -0,0 +1,1010 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#include "g_local.h"
+
+/*
+
+ Items are any object that a player can touch to gain some effect.
+
+ Pickup will return the number of seconds until they should respawn.
+
+ all items should pop when dropped in lava or slime
+
+ Respawnable items don't actually go away when picked up, they are
+ just made invisible and untouchable. This allows them to ride
+ movers and respawn apropriately.
+*/
+
+
+#define RESPAWN_ARMOR 25
+#define RESPAWN_HEALTH 35
+#define RESPAWN_AMMO 40
+#define RESPAWN_HOLDABLE 60
+#define RESPAWN_MEGAHEALTH 35//120
+#define RESPAWN_POWERUP 120
+
+
+//======================================================================
+
+int Pickup_Powerup( gentity_t *ent, gentity_t *other ) {
+ int quantity;
+ int i;
+ gclient_t *client;
+
+ if ( !other->client->ps.powerups[ent->item->giTag] ) {
+ // round timing to seconds to make multiple powerup timers
+ // count in sync
+ other->client->ps.powerups[ent->item->giTag] =
+ level.time - ( level.time % 1000 );
+ }
+
+ if ( ent->count ) {
+ quantity = ent->count;
+ } else {
+ quantity = ent->item->quantity;
+ }
+
+ other->client->ps.powerups[ent->item->giTag] += quantity * 1000;
+
+ // give any nearby players a "denied" anti-reward
+ for ( i = 0 ; i < level.maxclients ; i++ ) {
+ vec3_t delta;
+ float len;
+ vec3_t forward;
+ trace_t tr;
+
+ client = &level.clients[i];
+ if ( client == other->client ) {
+ continue;
+ }
+ if ( client->pers.connected == CON_DISCONNECTED ) {
+ continue;
+ }
+ if ( client->ps.stats[STAT_HEALTH] <= 0 ) {
+ continue;
+ }
+
+ // if same team in team game, no sound
+ // cannot use OnSameTeam as it expects to g_entities, not clients
+ if ( g_gametype.integer >= GT_TEAM && other->client->sess.sessionTeam == client->sess.sessionTeam ) {
+ continue;
+ }
+
+ // if too far away, no sound
+ VectorSubtract( ent->s.pos.trBase, client->ps.origin, delta );
+ len = VectorNormalize( delta );
+ if ( len > 192 ) {
+ continue;
+ }
+
+ // if not facing, no sound
+ AngleVectors( client->ps.viewangles, forward, NULL, NULL );
+ if ( DotProduct( delta, forward ) < 0.4 ) {
+ continue;
+ }
+
+ // if not line of sight, no sound
+ trap_Trace( &tr, client->ps.origin, NULL, NULL, ent->s.pos.trBase, ENTITYNUM_NONE, CONTENTS_SOLID );
+ if ( tr.fraction != 1.0 ) {
+ continue;
+ }
+
+ // anti-reward
+ client->ps.persistant[PERS_PLAYEREVENTS] ^= PLAYEREVENT_DENIEDREWARD;
+ }
+ return RESPAWN_POWERUP;
+}
+
+//======================================================================
+
+#ifdef MISSIONPACK
+int Pickup_PersistantPowerup( gentity_t *ent, gentity_t *other ) {
+ int clientNum;
+ char userinfo[MAX_INFO_STRING];
+ float handicap;
+ int max;
+
+ other->client->ps.stats[STAT_PERSISTANT_POWERUP] = ent->item - bg_itemlist;
+ other->client->persistantPowerup = ent;
+
+ switch( ent->item->giTag ) {
+ case PW_GUARD:
+ clientNum = other->client->ps.clientNum;
+ trap_GetUserinfo( clientNum, userinfo, sizeof(userinfo) );
+ handicap = atof( Info_ValueForKey( userinfo, "handicap" ) );
+ if( handicap<=0.0f || handicap>100.0f) {
+ handicap = 100.0f;
+ }
+ max = (int)(2 * handicap);
+
+ other->health = max;
+ other->client->ps.stats[STAT_HEALTH] = max;
+ other->client->ps.stats[STAT_MAX_HEALTH] = max;
+ other->client->ps.stats[STAT_ARMOR] = max;
+ other->client->pers.maxHealth = max;
+
+ break;
+
+ case PW_SCOUT:
+ clientNum = other->client->ps.clientNum;
+ trap_GetUserinfo( clientNum, userinfo, sizeof(userinfo) );
+ handicap = atof( Info_ValueForKey( userinfo, "handicap" ) );
+ if( handicap<=0.0f || handicap>100.0f) {
+ handicap = 100.0f;
+ }
+ other->client->pers.maxHealth = handicap;
+ other->client->ps.stats[STAT_ARMOR] = 0;
+ break;
+
+ case PW_DOUBLER:
+ clientNum = other->client->ps.clientNum;
+ trap_GetUserinfo( clientNum, userinfo, sizeof(userinfo) );
+ handicap = atof( Info_ValueForKey( userinfo, "handicap" ) );
+ if( handicap<=0.0f || handicap>100.0f) {
+ handicap = 100.0f;
+ }
+ other->client->pers.maxHealth = handicap;
+ break;
+ case PW_AMMOREGEN:
+ clientNum = other->client->ps.clientNum;
+ trap_GetUserinfo( clientNum, userinfo, sizeof(userinfo) );
+ handicap = atof( Info_ValueForKey( userinfo, "handicap" ) );
+ if( handicap<=0.0f || handicap>100.0f) {
+ handicap = 100.0f;
+ }
+ other->client->pers.maxHealth = handicap;
+ memset(other->client->ammoTimes, 0, sizeof(other->client->ammoTimes));
+ break;
+ default:
+ clientNum = other->client->ps.clientNum;
+ trap_GetUserinfo( clientNum, userinfo, sizeof(userinfo) );
+ handicap = atof( Info_ValueForKey( userinfo, "handicap" ) );
+ if( handicap<=0.0f || handicap>100.0f) {
+ handicap = 100.0f;
+ }
+ other->client->pers.maxHealth = handicap;
+ break;
+ }
+
+ return -1;
+}
+
+//======================================================================
+#endif
+
+int Pickup_Holdable( gentity_t *ent, gentity_t *other ) {
+
+ other->client->ps.stats[STAT_HOLDABLE_ITEM] = ent->item - bg_itemlist;
+
+ if( ent->item->giTag == HI_KAMIKAZE ) {
+ other->client->ps.eFlags |= EF_KAMIKAZE;
+ }
+
+ return RESPAWN_HOLDABLE;
+}
+
+
+//======================================================================
+
+void Add_Ammo (gentity_t *ent, int weapon, int count)
+{
+ ent->client->ps.ammo[weapon] += count;
+ if ( ent->client->ps.ammo[weapon] > 200 ) {
+ ent->client->ps.ammo[weapon] = 200;
+ }
+}
+
+int Pickup_Ammo (gentity_t *ent, gentity_t *other)
+{
+ int quantity;
+
+ if ( ent->count ) {
+ quantity = ent->count;
+ } else {
+ quantity = ent->item->quantity;
+ }
+
+ Add_Ammo (other, ent->item->giTag, quantity);
+
+ return RESPAWN_AMMO;
+}
+
+//======================================================================
+
+
+int Pickup_Weapon (gentity_t *ent, gentity_t *other) {
+ int quantity;
+
+ if ( ent->count < 0 ) {
+ quantity = 0; // None for you, sir!
+ } else {
+ if ( ent->count ) {
+ quantity = ent->count;
+ } else {
+ quantity = ent->item->quantity;
+ }
+
+ // dropped items and teamplay weapons always have full ammo
+ if ( ! (ent->flags & FL_DROPPED_ITEM) && g_gametype.integer != GT_TEAM ) {
+ // respawning rules
+ // drop the quantity if the already have over the minimum
+ if ( other->client->ps.ammo[ ent->item->giTag ] < quantity ) {
+ quantity = quantity - other->client->ps.ammo[ ent->item->giTag ];
+ } else {
+ quantity = 1; // only add a single shot
+ }
+ }
+ }
+
+ // add the weapon
+ other->client->ps.stats[STAT_WEAPONS] |= ( 1 << ent->item->giTag );
+
+ Add_Ammo( other, ent->item->giTag, quantity );
+
+ if (ent->item->giTag == WP_GRAPPLING_HOOK)
+ other->client->ps.ammo[ent->item->giTag] = -1; // unlimited ammo
+
+ // team deathmatch has slow weapon respawns
+ if ( g_gametype.integer == GT_TEAM ) {
+ return g_weaponTeamRespawn.integer;
+ }
+
+ return g_weaponRespawn.integer;
+}
+
+
+//======================================================================
+
+int Pickup_Health (gentity_t *ent, gentity_t *other) {
+ int max;
+ int quantity;
+
+ // small and mega healths will go over the max
+#ifdef MISSIONPACK
+ if( other->client && bg_itemlist[other->client->ps.stats[STAT_PERSISTANT_POWERUP]].giTag == PW_GUARD ) {
+ max = other->client->ps.stats[STAT_MAX_HEALTH];
+ }
+ else
+#endif
+ if ( ent->item->quantity != 5 && ent->item->quantity != 100 ) {
+ max = other->client->ps.stats[STAT_MAX_HEALTH];
+ } else {
+ max = other->client->ps.stats[STAT_MAX_HEALTH] * 2;
+ }
+
+ if ( ent->count ) {
+ quantity = ent->count;
+ } else {
+ quantity = ent->item->quantity;
+ }
+
+ other->health += quantity;
+
+ if (other->health > max ) {
+ other->health = max;
+ }
+ other->client->ps.stats[STAT_HEALTH] = other->health;
+
+ if ( ent->item->quantity == 100 ) { // mega health respawns slow
+ return RESPAWN_MEGAHEALTH;
+ }
+
+ return RESPAWN_HEALTH;
+}
+
+//======================================================================
+
+int Pickup_Armor( gentity_t *ent, gentity_t *other ) {
+#ifdef MISSIONPACK
+ int upperBound;
+
+ other->client->ps.stats[STAT_ARMOR] += ent->item->quantity;
+
+ if( other->client && bg_itemlist[other->client->ps.stats[STAT_PERSISTANT_POWERUP]].giTag == PW_GUARD ) {
+ upperBound = other->client->ps.stats[STAT_MAX_HEALTH];
+ }
+ else {
+ upperBound = other->client->ps.stats[STAT_MAX_HEALTH] * 2;
+ }
+
+ if ( other->client->ps.stats[STAT_ARMOR] > upperBound ) {
+ other->client->ps.stats[STAT_ARMOR] = upperBound;
+ }
+#else
+ other->client->ps.stats[STAT_ARMOR] += ent->item->quantity;
+ if ( other->client->ps.stats[STAT_ARMOR] > other->client->ps.stats[STAT_MAX_HEALTH] * 2 ) {
+ other->client->ps.stats[STAT_ARMOR] = other->client->ps.stats[STAT_MAX_HEALTH] * 2;
+ }
+#endif
+
+ return RESPAWN_ARMOR;
+}
+
+//======================================================================
+
+/*
+===============
+RespawnItem
+===============
+*/
+void RespawnItem( gentity_t *ent ) {
+ // randomly select from teamed entities
+ if (ent->team) {
+ gentity_t *master;
+ int count;
+ int choice;
+
+ if ( !ent->teammaster ) {
+ G_Error( "RespawnItem: bad teammaster");
+ }
+ master = ent->teammaster;
+
+ for (count = 0, ent = master; ent; ent = ent->teamchain, count++)
+ ;
+
+ choice = rand() % count;
+
+ for (count = 0, ent = master; count < choice; ent = ent->teamchain, count++)
+ ;
+ }
+
+ ent->r.contents = CONTENTS_TRIGGER;
+ ent->s.eFlags &= ~EF_NODRAW;
+ ent->r.svFlags &= ~SVF_NOCLIENT;
+ trap_LinkEntity (ent);
+
+ if ( ent->item->giType == IT_POWERUP ) {
+ // play powerup spawn sound to all clients
+ gentity_t *te;
+
+ // if the powerup respawn sound should Not be global
+ if (ent->speed) {
+ te = G_TempEntity( ent->s.pos.trBase, EV_GENERAL_SOUND );
+ }
+ else {
+ te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_SOUND );
+ }
+ te->s.eventParm = G_SoundIndex( "sound/items/poweruprespawn.wav" );
+ te->r.svFlags |= SVF_BROADCAST;
+ }
+
+ if ( ent->item->giType == IT_HOLDABLE && ent->item->giTag == HI_KAMIKAZE ) {
+ // play powerup spawn sound to all clients
+ gentity_t *te;
+
+ // if the powerup respawn sound should Not be global
+ if (ent->speed) {
+ te = G_TempEntity( ent->s.pos.trBase, EV_GENERAL_SOUND );
+ }
+ else {
+ te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_SOUND );
+ }
+ te->s.eventParm = G_SoundIndex( "sound/items/kamikazerespawn.wav" );
+ te->r.svFlags |= SVF_BROADCAST;
+ }
+
+ // play the normal respawn sound only to nearby clients
+ G_AddEvent( ent, EV_ITEM_RESPAWN, 0 );
+
+ ent->nextthink = 0;
+}
+
+
+/*
+===============
+Touch_Item
+===============
+*/
+void Touch_Item (gentity_t *ent, gentity_t *other, trace_t *trace) {
+ int respawn;
+ qboolean predict;
+
+ if (!other->client)
+ return;
+ if (other->health < 1)
+ return; // dead people can't pickup
+
+ // the same pickup rules are used for client side and server side
+ if ( !BG_CanItemBeGrabbed( g_gametype.integer, &ent->s, &other->client->ps ) ) {
+ return;
+ }
+
+ G_LogPrintf( "Item: %i %s\n", other->s.number, ent->item->classname );
+
+ predict = other->client->pers.predictItemPickup;
+
+ // call the item-specific pickup function
+ switch( ent->item->giType ) {
+ case IT_WEAPON:
+ respawn = Pickup_Weapon(ent, other);
+// predict = qfalse;
+ break;
+ case IT_AMMO:
+ respawn = Pickup_Ammo(ent, other);
+// predict = qfalse;
+ break;
+ case IT_ARMOR:
+ respawn = Pickup_Armor(ent, other);
+ break;
+ case IT_HEALTH:
+ respawn = Pickup_Health(ent, other);
+ break;
+ case IT_POWERUP:
+ respawn = Pickup_Powerup(ent, other);
+ predict = qfalse;
+ break;
+#ifdef MISSIONPACK
+ case IT_PERSISTANT_POWERUP:
+ respawn = Pickup_PersistantPowerup(ent, other);
+ break;
+#endif
+ case IT_TEAM:
+ respawn = Pickup_Team(ent, other);
+ break;
+ case IT_HOLDABLE:
+ respawn = Pickup_Holdable(ent, other);
+ break;
+ default:
+ return;
+ }
+
+ if ( !respawn ) {
+ return;
+ }
+
+ // play the normal pickup sound
+ if (predict) {
+ G_AddPredictableEvent( other, EV_ITEM_PICKUP, ent->s.modelindex );
+ } else {
+ G_AddEvent( other, EV_ITEM_PICKUP, ent->s.modelindex );
+ }
+
+ // powerup pickups are global broadcasts
+ if ( ent->item->giType == IT_POWERUP || ent->item->giType == IT_TEAM) {
+ // if we want the global sound to play
+ if (!ent->speed) {
+ gentity_t *te;
+
+ te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_ITEM_PICKUP );
+ te->s.eventParm = ent->s.modelindex;
+ te->r.svFlags |= SVF_BROADCAST;
+ } else {
+ gentity_t *te;
+
+ te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_ITEM_PICKUP );
+ te->s.eventParm = ent->s.modelindex;
+ // only send this temp entity to a single client
+ te->r.svFlags |= SVF_SINGLECLIENT;
+ te->r.singleClient = other->s.number;
+ }
+ }
+
+ // fire item targets
+ G_UseTargets (ent, other);
+
+ // wait of -1 will not respawn
+ if ( ent->wait == -1 ) {
+ ent->r.svFlags |= SVF_NOCLIENT;
+ ent->s.eFlags |= EF_NODRAW;
+ ent->r.contents = 0;
+ ent->unlinkAfterEvent = qtrue;
+ return;
+ }
+
+ // non zero wait overrides respawn time
+ if ( ent->wait ) {
+ respawn = ent->wait;
+ }
+
+ // random can be used to vary the respawn time
+ if ( ent->random ) {
+ respawn += crandom() * ent->random;
+ if ( respawn < 1 ) {
+ respawn = 1;
+ }
+ }
+
+ // dropped items will not respawn
+ if ( ent->flags & FL_DROPPED_ITEM ) {
+ ent->freeAfterEvent = qtrue;
+ }
+
+ // picked up items still stay around, they just don't
+ // draw anything. This allows respawnable items
+ // to be placed on movers.
+ ent->r.svFlags |= SVF_NOCLIENT;
+ ent->s.eFlags |= EF_NODRAW;
+ ent->r.contents = 0;
+
+ // ZOID
+ // A negative respawn times means to never respawn this item (but don't
+ // delete it). This is used by items that are respawned by third party
+ // events such as ctf flags
+ if ( respawn <= 0 ) {
+ ent->nextthink = 0;
+ ent->think = 0;
+ } else {
+ ent->nextthink = level.time + respawn * 1000;
+ ent->think = RespawnItem;
+ }
+ trap_LinkEntity( ent );
+}
+
+
+//======================================================================
+
+/*
+================
+LaunchItem
+
+Spawns an item and tosses it forward
+================
+*/
+gentity_t *LaunchItem( gitem_t *item, vec3_t origin, vec3_t velocity ) {
+ gentity_t *dropped;
+
+ dropped = G_Spawn();
+
+ dropped->s.eType = ET_ITEM;
+ dropped->s.modelindex = item - bg_itemlist; // store item number in modelindex
+ dropped->s.modelindex2 = 1; // This is non-zero is it's a dropped item
+
+ dropped->classname = item->classname;
+ dropped->item = item;
+ VectorSet (dropped->r.mins, -ITEM_RADIUS, -ITEM_RADIUS, -ITEM_RADIUS);
+ VectorSet (dropped->r.maxs, ITEM_RADIUS, ITEM_RADIUS, ITEM_RADIUS);
+ dropped->r.contents = CONTENTS_TRIGGER;
+
+ dropped->touch = Touch_Item;
+
+ G_SetOrigin( dropped, origin );
+ dropped->s.pos.trType = TR_GRAVITY;
+ dropped->s.pos.trTime = level.time;
+ VectorCopy( velocity, dropped->s.pos.trDelta );
+
+ dropped->s.eFlags |= EF_BOUNCE_HALF;
+#ifdef MISSIONPACK
+ if ((g_gametype.integer == GT_CTF || g_gametype.integer == GT_1FCTF) && item->giType == IT_TEAM) { // Special case for CTF flags
+#else
+ if (g_gametype.integer == GT_CTF && item->giType == IT_TEAM) { // Special case for CTF flags
+#endif
+ dropped->think = Team_DroppedFlagThink;
+ dropped->nextthink = level.time + 30000;
+ Team_CheckDroppedItem( dropped );
+ } else { // auto-remove after 30 seconds
+ dropped->think = G_FreeEntity;
+ dropped->nextthink = level.time + 30000;
+ }
+
+ dropped->flags = FL_DROPPED_ITEM;
+
+ trap_LinkEntity (dropped);
+
+ return dropped;
+}
+
+/*
+================
+Drop_Item
+
+Spawns an item and tosses it forward
+================
+*/
+gentity_t *Drop_Item( gentity_t *ent, gitem_t *item, float angle ) {
+ vec3_t velocity;
+ vec3_t angles;
+
+ VectorCopy( ent->s.apos.trBase, angles );
+ angles[YAW] += angle;
+ angles[PITCH] = 0; // always forward
+
+ AngleVectors( angles, velocity, NULL, NULL );
+ VectorScale( velocity, 150, velocity );
+ velocity[2] += 200 + crandom() * 50;
+
+ return LaunchItem( item, ent->s.pos.trBase, velocity );
+}
+
+
+/*
+================
+Use_Item
+
+Respawn the item
+================
+*/
+void Use_Item( gentity_t *ent, gentity_t *other, gentity_t *activator ) {
+ RespawnItem( ent );
+}
+
+//======================================================================
+
+/*
+================
+FinishSpawningItem
+
+Traces down to find where an item should rest, instead of letting them
+free fall from their spawn points
+================
+*/
+void FinishSpawningItem( gentity_t *ent ) {
+ trace_t tr;
+ vec3_t dest;
+
+ VectorSet( ent->r.mins, -ITEM_RADIUS, -ITEM_RADIUS, -ITEM_RADIUS );
+ VectorSet( ent->r.maxs, ITEM_RADIUS, ITEM_RADIUS, ITEM_RADIUS );
+
+ ent->s.eType = ET_ITEM;
+ ent->s.modelindex = ent->item - bg_itemlist; // store item number in modelindex
+ ent->s.modelindex2 = 0; // zero indicates this isn't a dropped item
+
+ ent->r.contents = CONTENTS_TRIGGER;
+ ent->touch = Touch_Item;
+ // useing an item causes it to respawn
+ ent->use = Use_Item;
+
+ if ( ent->spawnflags & 1 ) {
+ // suspended
+ G_SetOrigin( ent, ent->s.origin );
+ } else {
+ // drop to floor
+ VectorSet( dest, ent->s.origin[0], ent->s.origin[1], ent->s.origin[2] - 4096 );
+ trap_Trace( &tr, ent->s.origin, ent->r.mins, ent->r.maxs, dest, ent->s.number, MASK_SOLID );
+ if ( tr.startsolid ) {
+ G_Printf ("FinishSpawningItem: %s startsolid at %s\n", ent->classname, vtos(ent->s.origin));
+ G_FreeEntity( ent );
+ return;
+ }
+
+ // allow to ride movers
+ ent->s.groundEntityNum = tr.entityNum;
+
+ G_SetOrigin( ent, tr.endpos );
+ }
+
+ // team slaves and targeted items aren't present at start
+ if ( ( ent->flags & FL_TEAMSLAVE ) || ent->targetname ) {
+ ent->s.eFlags |= EF_NODRAW;
+ ent->r.contents = 0;
+ return;
+ }
+
+ // powerups don't spawn in for a while
+ if ( ent->item->giType == IT_POWERUP ) {
+ float respawn;
+
+ respawn = 45 + crandom() * 15;
+ ent->s.eFlags |= EF_NODRAW;
+ ent->r.contents = 0;
+ ent->nextthink = level.time + respawn * 1000;
+ ent->think = RespawnItem;
+ return;
+ }
+
+
+ trap_LinkEntity (ent);
+}
+
+
+qboolean itemRegistered[MAX_ITEMS];
+
+/*
+==================
+G_CheckTeamItems
+==================
+*/
+void G_CheckTeamItems( void ) {
+
+ // Set up team stuff
+ Team_InitGame();
+
+ if( g_gametype.integer == GT_CTF ) {
+ gitem_t *item;
+
+ // check for the two flags
+ item = BG_FindItem( "Red Flag" );
+ if ( !item || !itemRegistered[ item - bg_itemlist ] ) {
+ G_Printf( S_COLOR_YELLOW "WARNING: No team_CTF_redflag in map" );
+ }
+ item = BG_FindItem( "Blue Flag" );
+ if ( !item || !itemRegistered[ item - bg_itemlist ] ) {
+ G_Printf( S_COLOR_YELLOW "WARNING: No team_CTF_blueflag in map" );
+ }
+ }
+#ifdef MISSIONPACK
+ if( g_gametype.integer == GT_1FCTF ) {
+ gitem_t *item;
+
+ // check for all three flags
+ item = BG_FindItem( "Red Flag" );
+ if ( !item || !itemRegistered[ item - bg_itemlist ] ) {
+ G_Printf( S_COLOR_YELLOW "WARNING: No team_CTF_redflag in map" );
+ }
+ item = BG_FindItem( "Blue Flag" );
+ if ( !item || !itemRegistered[ item - bg_itemlist ] ) {
+ G_Printf( S_COLOR_YELLOW "WARNING: No team_CTF_blueflag in map" );
+ }
+ item = BG_FindItem( "Neutral Flag" );
+ if ( !item || !itemRegistered[ item - bg_itemlist ] ) {
+ G_Printf( S_COLOR_YELLOW "WARNING: No team_CTF_neutralflag in map" );
+ }
+ }
+
+ if( g_gametype.integer == GT_OBELISK ) {
+ gentity_t *ent;
+
+ // check for the two obelisks
+ ent = NULL;
+ ent = G_Find( ent, FOFS(classname), "team_redobelisk" );
+ if( !ent ) {
+ G_Printf( S_COLOR_YELLOW "WARNING: No team_redobelisk in map" );
+ }
+
+ ent = NULL;
+ ent = G_Find( ent, FOFS(classname), "team_blueobelisk" );
+ if( !ent ) {
+ G_Printf( S_COLOR_YELLOW "WARNING: No team_blueobelisk in map" );
+ }
+ }
+
+ if( g_gametype.integer == GT_HARVESTER ) {
+ gentity_t *ent;
+
+ // check for all three obelisks
+ ent = NULL;
+ ent = G_Find( ent, FOFS(classname), "team_redobelisk" );
+ if( !ent ) {
+ G_Printf( S_COLOR_YELLOW "WARNING: No team_redobelisk in map" );
+ }
+
+ ent = NULL;
+ ent = G_Find( ent, FOFS(classname), "team_blueobelisk" );
+ if( !ent ) {
+ G_Printf( S_COLOR_YELLOW "WARNING: No team_blueobelisk in map" );
+ }
+
+ ent = NULL;
+ ent = G_Find( ent, FOFS(classname), "team_neutralobelisk" );
+ if( !ent ) {
+ G_Printf( S_COLOR_YELLOW "WARNING: No team_neutralobelisk in map" );
+ }
+ }
+#endif
+}
+
+/*
+==============
+ClearRegisteredItems
+==============
+*/
+void ClearRegisteredItems( void ) {
+ memset( itemRegistered, 0, sizeof( itemRegistered ) );
+
+ // players always start with the base weapon
+ RegisterItem( BG_FindItemForWeapon( WP_MACHINEGUN ) );
+ RegisterItem( BG_FindItemForWeapon( WP_GAUNTLET ) );
+#ifdef MISSIONPACK
+ if( g_gametype.integer == GT_HARVESTER ) {
+ RegisterItem( BG_FindItem( "Red Cube" ) );
+ RegisterItem( BG_FindItem( "Blue Cube" ) );
+ }
+#endif
+}
+
+/*
+===============
+RegisterItem
+
+The item will be added to the precache list
+===============
+*/
+void RegisterItem( gitem_t *item ) {
+ if ( !item ) {
+ G_Error( "RegisterItem: NULL" );
+ }
+ itemRegistered[ item - bg_itemlist ] = qtrue;
+}
+
+
+/*
+===============
+SaveRegisteredItems
+
+Write the needed items to a config string
+so the client will know which ones to precache
+===============
+*/
+void SaveRegisteredItems( void ) {
+ char string[MAX_ITEMS+1];
+ int i;
+ int count;
+
+ count = 0;
+ for ( i = 0 ; i < bg_numItems ; i++ ) {
+ if ( itemRegistered[i] ) {
+ count++;
+ string[i] = '1';
+ } else {
+ string[i] = '0';
+ }
+ }
+ string[ bg_numItems ] = 0;
+
+ G_Printf( "%i items registered\n", count );
+ trap_SetConfigstring(CS_ITEMS, string);
+}
+
+/*
+============
+G_ItemDisabled
+============
+*/
+int G_ItemDisabled( gitem_t *item ) {
+
+ char name[128];
+
+ Com_sprintf(name, sizeof(name), "disable_%s", item->classname);
+ return trap_Cvar_VariableIntegerValue( name );
+}
+
+/*
+============
+G_SpawnItem
+
+Sets the clipping size and plants the object on the floor.
+
+Items can't be immediately dropped to floor, because they might
+be on an entity that hasn't spawned yet.
+============
+*/
+void G_SpawnItem (gentity_t *ent, gitem_t *item) {
+ G_SpawnFloat( "random", "0", &ent->random );
+ G_SpawnFloat( "wait", "0", &ent->wait );
+
+ RegisterItem( item );
+ if ( G_ItemDisabled(item) )
+ return;
+
+ ent->item = item;
+ // some movers spawn on the second frame, so delay item
+ // spawns until the third frame so they can ride trains
+ ent->nextthink = level.time + FRAMETIME * 2;
+ ent->think = FinishSpawningItem;
+
+ ent->physicsBounce = 0.50; // items are bouncy
+
+ if ( item->giType == IT_POWERUP ) {
+ G_SoundIndex( "sound/items/poweruprespawn.wav" );
+ G_SpawnFloat( "noglobalsound", "0", &ent->speed);
+ }
+
+#ifdef MISSIONPACK
+ if ( item->giType == IT_PERSISTANT_POWERUP ) {
+ ent->s.generic1 = ent->spawnflags;
+ }
+#endif
+}
+
+
+/*
+================
+G_BounceItem
+
+================
+*/
+void G_BounceItem( gentity_t *ent, trace_t *trace ) {
+ vec3_t velocity;
+ float dot;
+ int hitTime;
+
+ // reflect the velocity on the trace plane
+ hitTime = level.previousTime + ( level.time - level.previousTime ) * trace->fraction;
+ BG_EvaluateTrajectoryDelta( &ent->s.pos, hitTime, velocity );
+ dot = DotProduct( velocity, trace->plane.normal );
+ VectorMA( velocity, -2*dot, trace->plane.normal, ent->s.pos.trDelta );
+
+ // cut the velocity to keep from bouncing forever
+ VectorScale( ent->s.pos.trDelta, ent->physicsBounce, ent->s.pos.trDelta );
+
+ // check for stop
+ if ( trace->plane.normal[2] > 0 && ent->s.pos.trDelta[2] < 40 ) {
+ trace->endpos[2] += 1.0; // make sure it is off ground
+ SnapVector( trace->endpos );
+ G_SetOrigin( ent, trace->endpos );
+ ent->s.groundEntityNum = trace->entityNum;
+ return;
+ }
+
+ VectorAdd( ent->r.currentOrigin, trace->plane.normal, ent->r.currentOrigin);
+ VectorCopy( ent->r.currentOrigin, ent->s.pos.trBase );
+ ent->s.pos.trTime = level.time;
+}
+
+
+/*
+================
+G_RunItem
+
+================
+*/
+void G_RunItem( gentity_t *ent ) {
+ vec3_t origin;
+ trace_t tr;
+ int contents;
+ int mask;
+
+ // if groundentity has been set to -1, it may have been pushed off an edge
+ if ( ent->s.groundEntityNum == -1 ) {
+ if ( ent->s.pos.trType != TR_GRAVITY ) {
+ ent->s.pos.trType = TR_GRAVITY;
+ ent->s.pos.trTime = level.time;
+ }
+ }
+
+ if ( ent->s.pos.trType == TR_STATIONARY ) {
+ // check think function
+ G_RunThink( ent );
+ return;
+ }
+
+ // get current position
+ BG_EvaluateTrajectory( &ent->s.pos, level.time, origin );
+
+ // trace a line from the previous position to the current position
+ if ( ent->clipmask ) {
+ mask = ent->clipmask;
+ } else {
+ mask = MASK_PLAYERSOLID & ~CONTENTS_BODY;//MASK_SOLID;
+ }
+ trap_Trace( &tr, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, origin,
+ ent->r.ownerNum, mask );
+
+ VectorCopy( tr.endpos, ent->r.currentOrigin );
+
+ if ( tr.startsolid ) {
+ tr.fraction = 0;
+ }
+
+ trap_LinkEntity( ent ); // FIXME: avoid this for stationary?
+
+ // check think function
+ G_RunThink( ent );
+
+ if ( tr.fraction == 1 ) {
+ return;
+ }
+
+ // if it is in a nodrop volume, remove it
+ contents = trap_PointContents( ent->r.currentOrigin, -1 );
+ if ( contents & CONTENTS_NODROP ) {
+ if (ent->item && ent->item->giType == IT_TEAM) {
+ Team_FreeEntity(ent);
+ } else {
+ G_FreeEntity( ent );
+ }
+ return;
+ }
+
+ G_BounceItem( ent, &tr );
+}
+
diff --git a/code/game/g_local.h b/code/game/g_local.h
new file mode 100755
index 0000000..1a55955
--- /dev/null
+++ b/code/game/g_local.h
@@ -0,0 +1,971 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// g_local.h -- local definitions for game module
+
+#include "q_shared.h"
+#include "bg_public.h"
+#include "g_public.h"
+
+//==================================================================
+
+// the "gameversion" client command will print this plus compile date
+#define GAMEVERSION "baseq3"
+
+#define BODY_QUEUE_SIZE 8
+
+#define INFINITE 1000000
+
+#define FRAMETIME 100 // msec
+#define CARNAGE_REWARD_TIME 3000
+#define REWARD_SPRITE_TIME 2000
+
+#define INTERMISSION_DELAY_TIME 1000
+#define SP_INTERMISSION_DELAY_TIME 5000
+
+// gentity->flags
+#define FL_GODMODE 0x00000010
+#define FL_NOTARGET 0x00000020
+#define FL_TEAMSLAVE 0x00000400 // not the first on the team
+#define FL_NO_KNOCKBACK 0x00000800
+#define FL_DROPPED_ITEM 0x00001000
+#define FL_NO_BOTS 0x00002000 // spawn point not for bot use
+#define FL_NO_HUMANS 0x00004000 // spawn point just for bots
+#define FL_FORCE_GESTURE 0x00008000 // force gesture on client
+
+// movers are things like doors, plats, buttons, etc
+typedef enum {
+ MOVER_POS1,
+ MOVER_POS2,
+ MOVER_1TO2,
+ MOVER_2TO1
+} moverState_t;
+
+#define SP_PODIUM_MODEL "models/mapobjects/podium/podium4.md3"
+
+//============================================================================
+
+typedef struct gentity_s gentity_t;
+typedef struct gclient_s gclient_t;
+
+struct gentity_s {
+ entityState_t s; // communicated by server to clients
+ entityShared_t r; // shared by both the server system and game
+
+ // DO NOT MODIFY ANYTHING ABOVE THIS, THE SERVER
+ // EXPECTS THE FIELDS IN THAT ORDER!
+ //================================
+
+ struct gclient_s *client; // NULL if not a client
+
+ qboolean inuse;
+
+ char *classname; // set in QuakeEd
+ int spawnflags; // set in QuakeEd
+
+ qboolean neverFree; // if true, FreeEntity will only unlink
+ // bodyque uses this
+
+ int flags; // FL_* variables
+
+ char *model;
+ char *model2;
+ int freetime; // level.time when the object was freed
+
+ int eventTime; // events will be cleared EVENT_VALID_MSEC after set
+ qboolean freeAfterEvent;
+ qboolean unlinkAfterEvent;
+
+ qboolean physicsObject; // if true, it can be pushed by movers and fall off edges
+ // all game items are physicsObjects,
+ float physicsBounce; // 1.0 = continuous bounce, 0.0 = no bounce
+ int clipmask; // brushes with this content value will be collided against
+ // when moving. items and corpses do not collide against
+ // players, for instance
+
+ // movers
+ moverState_t moverState;
+ int soundPos1;
+ int sound1to2;
+ int sound2to1;
+ int soundPos2;
+ int soundLoop;
+ gentity_t *parent;
+ gentity_t *nextTrain;
+ gentity_t *prevTrain;
+ vec3_t pos1, pos2;
+
+ char *message;
+
+ int timestamp; // body queue sinking, etc
+
+ float angle; // set in editor, -1 = up, -2 = down
+ char *target;
+ char *targetname;
+ char *team;
+ char *targetShaderName;
+ char *targetShaderNewName;
+ gentity_t *target_ent;
+
+ float speed;
+ vec3_t movedir;
+
+ int nextthink;
+ void (*think)(gentity_t *self);
+ void (*reached)(gentity_t *self); // movers call this when hitting endpoint
+ void (*blocked)(gentity_t *self, gentity_t *other);
+ void (*touch)(gentity_t *self, gentity_t *other, trace_t *trace);
+ void (*use)(gentity_t *self, gentity_t *other, gentity_t *activator);
+ void (*pain)(gentity_t *self, gentity_t *attacker, int damage);
+ void (*die)(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod);
+
+ int pain_debounce_time;
+ int fly_sound_debounce_time; // wind tunnel
+ int last_move_time;
+
+ int health;
+
+ qboolean takedamage;
+
+ int damage;
+ int splashDamage; // quad will increase this without increasing radius
+ int splashRadius;
+ int methodOfDeath;
+ int splashMethodOfDeath;
+
+ int count;
+
+ gentity_t *chain;
+ gentity_t *enemy;
+ gentity_t *activator;
+ gentity_t *teamchain; // next entity in team
+ gentity_t *teammaster; // master of the team
+
+#ifdef MISSIONPACK
+ int kamikazeTime;
+ int kamikazeShockTime;
+#endif
+
+ int watertype;
+ int waterlevel;
+
+ int noise_index;
+
+ // timing variables
+ float wait;
+ float random;
+
+ gitem_t *item; // for bonus items
+};
+
+
+typedef enum {
+ CON_DISCONNECTED,
+ CON_CONNECTING,
+ CON_CONNECTED
+} clientConnected_t;
+
+typedef enum {
+ SPECTATOR_NOT,
+ SPECTATOR_FREE,
+ SPECTATOR_FOLLOW,
+ SPECTATOR_SCOREBOARD
+} spectatorState_t;
+
+typedef enum {
+ TEAM_BEGIN, // Beginning a team game, spawn at base
+ TEAM_ACTIVE // Now actively playing
+} playerTeamStateState_t;
+
+typedef struct {
+ playerTeamStateState_t state;
+
+ int location;
+
+ int captures;
+ int basedefense;
+ int carrierdefense;
+ int flagrecovery;
+ int fragcarrier;
+ int assists;
+
+ float lasthurtcarrier;
+ float lastreturnedflag;
+ float flagsince;
+ float lastfraggedcarrier;
+} playerTeamState_t;
+
+// the auto following clients don't follow a specific client
+// number, but instead follow the first two active players
+#define FOLLOW_ACTIVE1 -1
+#define FOLLOW_ACTIVE2 -2
+
+// client data that stays across multiple levels or tournament restarts
+// this is achieved by writing all the data to cvar strings at game shutdown
+// time and reading them back at connection time. Anything added here
+// MUST be dealt with in G_InitSessionData() / G_ReadSessionData() / G_WriteSessionData()
+typedef struct {
+ team_t sessionTeam;
+ int spectatorTime; // for determining next-in-line to play
+ spectatorState_t spectatorState;
+ int spectatorClient; // for chasecam and follow mode
+ int wins, losses; // tournament stats
+ qboolean teamLeader; // true when this client is a team leader
+} clientSession_t;
+
+//
+#define MAX_NETNAME 36
+#define MAX_VOTE_COUNT 3
+
+// client data that stays across multiple respawns, but is cleared
+// on each level change or team change at ClientBegin()
+typedef struct {
+ clientConnected_t connected;
+ usercmd_t cmd; // we would lose angles if not persistant
+ qboolean localClient; // true if "ip" info key is "localhost"
+ qboolean initialSpawn; // the first spawn should be at a cool location
+ qboolean predictItemPickup; // based on cg_predictItems userinfo
+ qboolean pmoveFixed; //
+ char netname[MAX_NETNAME];
+ int maxHealth; // for handicapping
+ int enterTime; // level.time the client entered the game
+ playerTeamState_t teamState; // status in teamplay games
+ int voteCount; // to prevent people from constantly calling votes
+ int teamVoteCount; // to prevent people from constantly calling votes
+ qboolean teamInfo; // send team overlay updates?
+} clientPersistant_t;
+
+
+// this structure is cleared on each ClientSpawn(),
+// except for 'client->pers' and 'client->sess'
+struct gclient_s {
+ // ps MUST be the first element, because the server expects it
+ playerState_t ps; // communicated by server to clients
+
+ // the rest of the structure is private to game
+ clientPersistant_t pers;
+ clientSession_t sess;
+
+ qboolean readyToExit; // wishes to leave the intermission
+
+ qboolean noclip;
+
+ int lastCmdTime; // level.time of last usercmd_t, for EF_CONNECTION
+ // we can't just use pers.lastCommand.time, because
+ // of the g_sycronousclients case
+ int buttons;
+ int oldbuttons;
+ int latched_buttons;
+
+ vec3_t oldOrigin;
+
+ // sum up damage over an entire frame, so
+ // shotgun blasts give a single big kick
+ int damage_armor; // damage absorbed by armor
+ int damage_blood; // damage taken out of health
+ int damage_knockback; // impact damage
+ vec3_t damage_from; // origin for vector calculation
+ qboolean damage_fromWorld; // if true, don't use the damage_from vector
+
+ int accurateCount; // for "impressive" reward sound
+
+ int accuracy_shots; // total number of shots
+ int accuracy_hits; // total number of hits
+
+ //
+ int lastkilled_client; // last client that this client killed
+ int lasthurt_client; // last client that damaged this client
+ int lasthurt_mod; // type of damage the client did
+
+ // timers
+ int respawnTime; // can respawn when time > this, force after g_forcerespwan
+ int inactivityTime; // kick players when time > this
+ qboolean inactivityWarning; // qtrue if the five seoond warning has been given
+ int rewardTime; // clear the EF_AWARD_IMPRESSIVE, etc when time > this
+
+ int airOutTime;
+
+ int lastKillTime; // for multiple kill rewards
+
+ qboolean fireHeld; // used for hook
+ gentity_t *hook; // grapple hook if out
+
+ int switchTeamTime; // time the player switched teams
+
+ // timeResidual is used to handle events that happen every second
+ // like health / armor countdowns and regeneration
+ int timeResidual;
+
+#ifdef MISSIONPACK
+ gentity_t *persistantPowerup;
+ int portalID;
+ int ammoTimes[WP_NUM_WEAPONS];
+ int invulnerabilityTime;
+#endif
+
+ char *areabits;
+};
+
+
+//
+// this structure is cleared as each map is entered
+//
+#define MAX_SPAWN_VARS 64
+#define MAX_SPAWN_VARS_CHARS 4096
+
+typedef struct {
+ struct gclient_s *clients; // [maxclients]
+
+ struct gentity_s *gentities;
+ int gentitySize;
+ int num_entities; // current number, <= MAX_GENTITIES
+
+ int warmupTime; // restart match at this time
+
+ fileHandle_t logFile;
+
+ // store latched cvars here that we want to get at often
+ int maxclients;
+
+ int framenum;
+ int time; // in msec
+ int previousTime; // so movers can back up when blocked
+
+ int startTime; // level.time the map was started
+
+ int teamScores[TEAM_NUM_TEAMS];
+ int lastTeamLocationTime; // last time of client team location update
+
+ qboolean newSession; // don't use any old session data, because
+ // we changed gametype
+
+ qboolean restarted; // waiting for a map_restart to fire
+
+ int numConnectedClients;
+ int numNonSpectatorClients; // includes connecting clients
+ int numPlayingClients; // connected, non-spectators
+ int sortedClients[MAX_CLIENTS]; // sorted by score
+ int follow1, follow2; // clientNums for auto-follow spectators
+
+ int snd_fry; // sound index for standing in lava
+
+ int warmupModificationCount; // for detecting if g_warmup is changed
+
+ // voting state
+ char voteString[MAX_STRING_CHARS];
+ char voteDisplayString[MAX_STRING_CHARS];
+ int voteTime; // level.time vote was called
+ int voteExecuteTime; // time the vote is executed
+ int voteYes;
+ int voteNo;
+ int numVotingClients; // set by CalculateRanks
+
+ // team voting state
+ char teamVoteString[2][MAX_STRING_CHARS];
+ int teamVoteTime[2]; // level.time vote was called
+ int teamVoteYes[2];
+ int teamVoteNo[2];
+ int numteamVotingClients[2];// set by CalculateRanks
+
+ // spawn variables
+ qboolean spawning; // the G_Spawn*() functions are valid
+ int numSpawnVars;
+ char *spawnVars[MAX_SPAWN_VARS][2]; // key / value pairs
+ int numSpawnVarChars;
+ char spawnVarChars[MAX_SPAWN_VARS_CHARS];
+
+ // intermission state
+ int intermissionQueued; // intermission was qualified, but
+ // wait INTERMISSION_DELAY_TIME before
+ // actually going there so the last
+ // frag can be watched. Disable future
+ // kills during this delay
+ int intermissiontime; // time the intermission was started
+ char *changemap;
+ qboolean readyToExit; // at least one client wants to exit
+ int exitTime;
+ vec3_t intermission_origin; // also used for spectator spawns
+ vec3_t intermission_angle;
+
+ qboolean locationLinked; // target_locations get linked
+ gentity_t *locationHead; // head of the location list
+ int bodyQueIndex; // dead bodies
+ gentity_t *bodyQue[BODY_QUEUE_SIZE];
+#ifdef MISSIONPACK
+ int portalSequence;
+#endif
+} level_locals_t;
+
+
+//
+// g_spawn.c
+//
+qboolean G_SpawnString( const char *key, const char *defaultString, char **out );
+// spawn string returns a temporary reference, you must CopyString() if you want to keep it
+qboolean G_SpawnFloat( const char *key, const char *defaultString, float *out );
+qboolean G_SpawnInt( const char *key, const char *defaultString, int *out );
+qboolean G_SpawnVector( const char *key, const char *defaultString, float *out );
+void G_SpawnEntitiesFromString( void );
+char *G_NewString( const char *string );
+
+//
+// g_cmds.c
+//
+void Cmd_Score_f (gentity_t *ent);
+void StopFollowing( gentity_t *ent );
+void BroadcastTeamChange( gclient_t *client, int oldTeam );
+void SetTeam( gentity_t *ent, char *s );
+void Cmd_FollowCycle_f( gentity_t *ent, int dir );
+
+//
+// g_items.c
+//
+void G_CheckTeamItems( void );
+void G_RunItem( gentity_t *ent );
+void RespawnItem( gentity_t *ent );
+
+void UseHoldableItem( gentity_t *ent );
+void PrecacheItem (gitem_t *it);
+gentity_t *Drop_Item( gentity_t *ent, gitem_t *item, float angle );
+gentity_t *LaunchItem( gitem_t *item, vec3_t origin, vec3_t velocity );
+void SetRespawn (gentity_t *ent, float delay);
+void G_SpawnItem (gentity_t *ent, gitem_t *item);
+void FinishSpawningItem( gentity_t *ent );
+void Think_Weapon (gentity_t *ent);
+int ArmorIndex (gentity_t *ent);
+void Add_Ammo (gentity_t *ent, int weapon, int count);
+void Touch_Item (gentity_t *ent, gentity_t *other, trace_t *trace);
+
+void ClearRegisteredItems( void );
+void RegisterItem( gitem_t *item );
+void SaveRegisteredItems( void );
+
+//
+// g_utils.c
+//
+int G_ModelIndex( char *name );
+int G_SoundIndex( char *name );
+void G_TeamCommand( team_t team, char *cmd );
+void G_KillBox (gentity_t *ent);
+gentity_t *G_Find (gentity_t *from, int fieldofs, const char *match);
+gentity_t *G_PickTarget (char *targetname);
+void G_UseTargets (gentity_t *ent, gentity_t *activator);
+void G_SetMovedir ( vec3_t angles, vec3_t movedir);
+
+void G_InitGentity( gentity_t *e );
+gentity_t *G_Spawn (void);
+gentity_t *G_TempEntity( vec3_t origin, int event );
+void G_Sound( gentity_t *ent, int channel, int soundIndex );
+void G_FreeEntity( gentity_t *e );
+qboolean G_EntitiesFree( void );
+
+void G_TouchTriggers (gentity_t *ent);
+void G_TouchSolids (gentity_t *ent);
+
+float *tv (float x, float y, float z);
+char *vtos( const vec3_t v );
+
+float vectoyaw( const vec3_t vec );
+
+void G_AddPredictableEvent( gentity_t *ent, int event, int eventParm );
+void G_AddEvent( gentity_t *ent, int event, int eventParm );
+void G_SetOrigin( gentity_t *ent, vec3_t origin );
+void AddRemap(const char *oldShader, const char *newShader, float timeOffset);
+const char *BuildShaderStateConfig();
+
+//
+// g_combat.c
+//
+qboolean CanDamage (gentity_t *targ, vec3_t origin);
+void G_Damage (gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, vec3_t dir, vec3_t point, int damage, int dflags, int mod);
+qboolean G_RadiusDamage (vec3_t origin, gentity_t *attacker, float damage, float radius, gentity_t *ignore, int mod);
+int G_InvulnerabilityEffect( gentity_t *targ, vec3_t dir, vec3_t point, vec3_t impactpoint, vec3_t bouncedir );
+void body_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath );
+void TossClientItems( gentity_t *self );
+#ifdef MISSIONPACK
+void TossClientPersistantPowerups( gentity_t *self );
+#endif
+void TossClientCubes( gentity_t *self );
+
+// damage flags
+#define DAMAGE_RADIUS 0x00000001 // damage was indirect
+#define DAMAGE_NO_ARMOR 0x00000002 // armour does not protect from this damage
+#define DAMAGE_NO_KNOCKBACK 0x00000004 // do not affect velocity, just view angles
+#define DAMAGE_NO_PROTECTION 0x00000008 // armor, shields, invulnerability, and godmode have no effect
+#ifdef MISSIONPACK
+#define DAMAGE_NO_TEAM_PROTECTION 0x00000010 // armor, shields, invulnerability, and godmode have no effect
+#endif
+
+//
+// g_missile.c
+//
+void G_RunMissile( gentity_t *ent );
+
+gentity_t *fire_blaster (gentity_t *self, vec3_t start, vec3_t aimdir);
+gentity_t *fire_plasma (gentity_t *self, vec3_t start, vec3_t aimdir);
+gentity_t *fire_grenade (gentity_t *self, vec3_t start, vec3_t aimdir);
+gentity_t *fire_rocket (gentity_t *self, vec3_t start, vec3_t dir);
+gentity_t *fire_bfg (gentity_t *self, vec3_t start, vec3_t dir);
+gentity_t *fire_grapple (gentity_t *self, vec3_t start, vec3_t dir);
+#ifdef MISSIONPACK
+gentity_t *fire_nail( gentity_t *self, vec3_t start, vec3_t forward, vec3_t right, vec3_t up );
+gentity_t *fire_prox( gentity_t *self, vec3_t start, vec3_t aimdir );
+#endif
+
+
+//
+// g_mover.c
+//
+void G_RunMover( gentity_t *ent );
+void Touch_DoorTrigger( gentity_t *ent, gentity_t *other, trace_t *trace );
+
+//
+// g_trigger.c
+//
+void trigger_teleporter_touch (gentity_t *self, gentity_t *other, trace_t *trace );
+
+
+//
+// g_misc.c
+//
+void TeleportPlayer( gentity_t *player, vec3_t origin, vec3_t angles );
+#ifdef MISSIONPACK
+void DropPortalSource( gentity_t *ent );
+void DropPortalDestination( gentity_t *ent );
+#endif
+
+
+//
+// g_weapon.c
+//
+qboolean LogAccuracyHit( gentity_t *target, gentity_t *attacker );
+void CalcMuzzlePoint ( gentity_t *ent, vec3_t forward, vec3_t right, vec3_t up, vec3_t muzzlePoint );
+void SnapVectorTowards( vec3_t v, vec3_t to );
+qboolean CheckGauntletAttack( gentity_t *ent );
+void Weapon_HookFree (gentity_t *ent);
+void Weapon_HookThink (gentity_t *ent);
+
+
+//
+// g_client.c
+//
+team_t TeamCount( int ignoreClientNum, int team );
+int TeamLeader( int team );
+team_t PickTeam( int ignoreClientNum );
+void SetClientViewAngle( gentity_t *ent, vec3_t angle );
+gentity_t *SelectSpawnPoint ( vec3_t avoidPoint, vec3_t origin, vec3_t angles );
+void CopyToBodyQue( gentity_t *ent );
+void respawn (gentity_t *ent);
+void BeginIntermission (void);
+void InitClientPersistant (gclient_t *client);
+void InitClientResp (gclient_t *client);
+void InitBodyQue (void);
+void ClientSpawn( gentity_t *ent );
+void player_die (gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod);
+void AddScore( gentity_t *ent, vec3_t origin, int score );
+void CalculateRanks( void );
+qboolean SpotWouldTelefrag( gentity_t *spot );
+
+//
+// g_svcmds.c
+//
+qboolean ConsoleCommand( void );
+void G_ProcessIPBans(void);
+qboolean G_FilterPacket (char *from);
+
+//
+// g_weapon.c
+//
+void FireWeapon( gentity_t *ent );
+#ifdef MISSIONPACK
+void G_StartKamikaze( gentity_t *ent );
+#endif
+
+//
+// p_hud.c
+//
+void MoveClientToIntermission (gentity_t *client);
+void G_SetStats (gentity_t *ent);
+void DeathmatchScoreboardMessage (gentity_t *client);
+
+//
+// g_cmds.c
+//
+
+//
+// g_pweapon.c
+//
+
+
+//
+// g_main.c
+//
+void FindIntermissionPoint( void );
+void SetLeader(int team, int client);
+void CheckTeamLeader( int team );
+void G_RunThink (gentity_t *ent);
+void QDECL G_LogPrintf( const char *fmt, ... );
+void SendScoreboardMessageToAllClients( void );
+void QDECL G_Printf( const char *fmt, ... );
+void QDECL G_Error( const char *fmt, ... );
+
+//
+// g_client.c
+//
+char *ClientConnect( int clientNum, qboolean firstTime, qboolean isBot );
+void ClientUserinfoChanged( int clientNum );
+void ClientDisconnect( int clientNum );
+void ClientBegin( int clientNum );
+void ClientCommand( int clientNum );
+
+//
+// g_active.c
+//
+void ClientThink( int clientNum );
+void ClientEndFrame( gentity_t *ent );
+void G_RunClient( gentity_t *ent );
+
+//
+// g_team.c
+//
+qboolean OnSameTeam( gentity_t *ent1, gentity_t *ent2 );
+void Team_CheckDroppedItem( gentity_t *dropped );
+qboolean CheckObeliskAttack( gentity_t *obelisk, gentity_t *attacker );
+
+//
+// g_mem.c
+//
+void *G_Alloc( int size );
+void G_InitMemory( void );
+void Svcmd_GameMem_f( void );
+
+//
+// g_session.c
+//
+void G_ReadSessionData( gclient_t *client );
+void G_InitSessionData( gclient_t *client, char *userinfo );
+
+void G_InitWorldSession( void );
+void G_WriteSessionData( void );
+
+//
+// g_arenas.c
+//
+void UpdateTournamentInfo( void );
+void SpawnModelsOnVictoryPads( void );
+void Svcmd_AbortPodium_f( void );
+
+//
+// g_bot.c
+//
+void G_InitBots( qboolean restart );
+char *G_GetBotInfoByNumber( int num );
+char *G_GetBotInfoByName( const char *name );
+void G_CheckBotSpawn( void );
+void G_RemoveQueuedBotBegin( int clientNum );
+qboolean G_BotConnect( int clientNum, qboolean restart );
+void Svcmd_AddBot_f( void );
+void Svcmd_BotList_f( void );
+void BotInterbreedEndMatch( void );
+
+// ai_main.c
+#define MAX_FILEPATH 144
+
+//bot settings
+typedef struct bot_settings_s
+{
+ char characterfile[MAX_FILEPATH];
+ float skill;
+ char team[MAX_FILEPATH];
+} bot_settings_t;
+
+int BotAISetup( int restart );
+int BotAIShutdown( int restart );
+int BotAILoadMap( int restart );
+int BotAISetupClient(int client, struct bot_settings_s *settings, qboolean restart);
+int BotAIShutdownClient( int client, qboolean restart );
+int BotAIStartFrame( int time );
+void BotTestAAS(vec3_t origin);
+
+#include "g_team.h" // teamplay specific stuff
+
+
+extern level_locals_t level;
+extern gentity_t g_entities[MAX_GENTITIES];
+
+#define FOFS(x) ((int)&(((gentity_t *)0)->x))
+
+extern vmCvar_t g_gametype;
+extern vmCvar_t g_dedicated;
+extern vmCvar_t g_cheats;
+extern vmCvar_t g_maxclients; // allow this many total, including spectators
+extern vmCvar_t g_maxGameClients; // allow this many active
+extern vmCvar_t g_restarted;
+
+extern vmCvar_t g_dmflags;
+extern vmCvar_t g_fraglimit;
+extern vmCvar_t g_timelimit;
+extern vmCvar_t g_capturelimit;
+extern vmCvar_t g_friendlyFire;
+extern vmCvar_t g_password;
+extern vmCvar_t g_needpass;
+extern vmCvar_t g_gravity;
+extern vmCvar_t g_speed;
+extern vmCvar_t g_knockback;
+extern vmCvar_t g_quadfactor;
+extern vmCvar_t g_forcerespawn;
+extern vmCvar_t g_inactivity;
+extern vmCvar_t g_debugMove;
+extern vmCvar_t g_debugAlloc;
+extern vmCvar_t g_debugDamage;
+extern vmCvar_t g_weaponRespawn;
+extern vmCvar_t g_weaponTeamRespawn;
+extern vmCvar_t g_synchronousClients;
+extern vmCvar_t g_motd;
+extern vmCvar_t g_warmup;
+extern vmCvar_t g_doWarmup;
+extern vmCvar_t g_blood;
+extern vmCvar_t g_allowVote;
+extern vmCvar_t g_teamAutoJoin;
+extern vmCvar_t g_teamForceBalance;
+extern vmCvar_t g_banIPs;
+extern vmCvar_t g_filterBan;
+extern vmCvar_t g_obeliskHealth;
+extern vmCvar_t g_obeliskRegenPeriod;
+extern vmCvar_t g_obeliskRegenAmount;
+extern vmCvar_t g_obeliskRespawnDelay;
+extern vmCvar_t g_cubeTimeout;
+extern vmCvar_t g_redteam;
+extern vmCvar_t g_blueteam;
+extern vmCvar_t g_smoothClients;
+extern vmCvar_t pmove_fixed;
+extern vmCvar_t pmove_msec;
+extern vmCvar_t g_rankings;
+extern vmCvar_t g_enableDust;
+extern vmCvar_t g_enableBreath;
+extern vmCvar_t g_singlePlayer;
+extern vmCvar_t g_proxMineTimeout;
+
+void trap_Printf( const char *fmt );
+void trap_Error( const char *fmt );
+int trap_Milliseconds( void );
+int trap_Argc( void );
+void trap_Argv( int n, char *buffer, int bufferLength );
+void trap_Args( char *buffer, int bufferLength );
+int trap_FS_FOpenFile( const char *qpath, fileHandle_t *f, fsMode_t mode );
+void trap_FS_Read( void *buffer, int len, fileHandle_t f );
+void trap_FS_Write( const void *buffer, int len, fileHandle_t f );
+void trap_FS_FCloseFile( fileHandle_t f );
+int trap_FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize );
+int trap_FS_Seek( fileHandle_t f, long offset, int origin ); // fsOrigin_t
+void trap_SendConsoleCommand( int exec_when, const char *text );
+void trap_Cvar_Register( vmCvar_t *cvar, const char *var_name, const char *value, int flags );
+void trap_Cvar_Update( vmCvar_t *cvar );
+void trap_Cvar_Set( const char *var_name, const char *value );
+int trap_Cvar_VariableIntegerValue( const char *var_name );
+float trap_Cvar_VariableValue( const char *var_name );
+void trap_Cvar_VariableStringBuffer( const char *var_name, char *buffer, int bufsize );
+void trap_LocateGameData( gentity_t *gEnts, int numGEntities, int sizeofGEntity_t, playerState_t *gameClients, int sizeofGameClient );
+void trap_DropClient( int clientNum, const char *reason );
+void trap_SendServerCommand( int clientNum, const char *text );
+void trap_SetConfigstring( int num, const char *string );
+void trap_GetConfigstring( int num, char *buffer, int bufferSize );
+void trap_GetUserinfo( int num, char *buffer, int bufferSize );
+void trap_SetUserinfo( int num, const char *buffer );
+void trap_GetServerinfo( char *buffer, int bufferSize );
+void trap_SetBrushModel( gentity_t *ent, const char *name );
+void trap_Trace( trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentmask );
+int trap_PointContents( const vec3_t point, int passEntityNum );
+qboolean trap_InPVS( const vec3_t p1, const vec3_t p2 );
+qboolean trap_InPVSIgnorePortals( const vec3_t p1, const vec3_t p2 );
+void trap_AdjustAreaPortalState( gentity_t *ent, qboolean open );
+qboolean trap_AreasConnected( int area1, int area2 );
+void trap_LinkEntity( gentity_t *ent );
+void trap_UnlinkEntity( gentity_t *ent );
+int trap_EntitiesInBox( const vec3_t mins, const vec3_t maxs, int *entityList, int maxcount );
+qboolean trap_EntityContact( const vec3_t mins, const vec3_t maxs, const gentity_t *ent );
+int trap_BotAllocateClient( void );
+void trap_BotFreeClient( int clientNum );
+void trap_GetUsercmd( int clientNum, usercmd_t *cmd );
+qboolean trap_GetEntityToken( char *buffer, int bufferSize );
+
+int trap_DebugPolygonCreate(int color, int numPoints, vec3_t *points);
+void trap_DebugPolygonDelete(int id);
+
+int trap_BotLibSetup( void );
+int trap_BotLibShutdown( void );
+int trap_BotLibVarSet(char *var_name, char *value);
+int trap_BotLibVarGet(char *var_name, char *value, int size);
+int trap_BotLibDefine(char *string);
+int trap_BotLibStartFrame(float time);
+int trap_BotLibLoadMap(const char *mapname);
+int trap_BotLibUpdateEntity(int ent, void /* struct bot_updateentity_s */ *bue);
+int trap_BotLibTest(int parm0, char *parm1, vec3_t parm2, vec3_t parm3);
+
+int trap_BotGetSnapshotEntity( int clientNum, int sequence );
+int trap_BotGetServerCommand(int clientNum, char *message, int size);
+void trap_BotUserCommand(int client, usercmd_t *ucmd);
+
+int trap_AAS_BBoxAreas(vec3_t absmins, vec3_t absmaxs, int *areas, int maxareas);
+int trap_AAS_AreaInfo( int areanum, void /* struct aas_areainfo_s */ *info );
+void trap_AAS_EntityInfo(int entnum, void /* struct aas_entityinfo_s */ *info);
+
+int trap_AAS_Initialized(void);
+void trap_AAS_PresenceTypeBoundingBox(int presencetype, vec3_t mins, vec3_t maxs);
+float trap_AAS_Time(void);
+
+int trap_AAS_PointAreaNum(vec3_t point);
+int trap_AAS_PointReachabilityAreaIndex(vec3_t point);
+int trap_AAS_TraceAreas(vec3_t start, vec3_t end, int *areas, vec3_t *points, int maxareas);
+
+int trap_AAS_PointContents(vec3_t point);
+int trap_AAS_NextBSPEntity(int ent);
+int trap_AAS_ValueForBSPEpairKey(int ent, char *key, char *value, int size);
+int trap_AAS_VectorForBSPEpairKey(int ent, char *key, vec3_t v);
+int trap_AAS_FloatForBSPEpairKey(int ent, char *key, float *value);
+int trap_AAS_IntForBSPEpairKey(int ent, char *key, int *value);
+
+int trap_AAS_AreaReachability(int areanum);
+
+int trap_AAS_AreaTravelTimeToGoalArea(int areanum, vec3_t origin, int goalareanum, int travelflags);
+int trap_AAS_EnableRoutingArea( int areanum, int enable );
+int trap_AAS_PredictRoute(void /*struct aas_predictroute_s*/ *route, int areanum, vec3_t origin,
+ int goalareanum, int travelflags, int maxareas, int maxtime,
+ int stopevent, int stopcontents, int stoptfl, int stopareanum);
+
+int trap_AAS_AlternativeRouteGoals(vec3_t start, int startareanum, vec3_t goal, int goalareanum, int travelflags,
+ void /*struct aas_altroutegoal_s*/ *altroutegoals, int maxaltroutegoals,
+ int type);
+int trap_AAS_Swimming(vec3_t origin);
+int trap_AAS_PredictClientMovement(void /* aas_clientmove_s */ *move, int entnum, vec3_t origin, int presencetype, int onground, vec3_t velocity, vec3_t cmdmove, int cmdframes, int maxframes, float frametime, int stopevent, int stopareanum, int visualize);
+
+
+void trap_EA_Say(int client, char *str);
+void trap_EA_SayTeam(int client, char *str);
+void trap_EA_Command(int client, char *command);
+
+void trap_EA_Action(int client, int action);
+void trap_EA_Gesture(int client);
+void trap_EA_Talk(int client);
+void trap_EA_Attack(int client);
+void trap_EA_Use(int client);
+void trap_EA_Respawn(int client);
+void trap_EA_Crouch(int client);
+void trap_EA_MoveUp(int client);
+void trap_EA_MoveDown(int client);
+void trap_EA_MoveForward(int client);
+void trap_EA_MoveBack(int client);
+void trap_EA_MoveLeft(int client);
+void trap_EA_MoveRight(int client);
+void trap_EA_SelectWeapon(int client, int weapon);
+void trap_EA_Jump(int client);
+void trap_EA_DelayedJump(int client);
+void trap_EA_Move(int client, vec3_t dir, float speed);
+void trap_EA_View(int client, vec3_t viewangles);
+
+void trap_EA_EndRegular(int client, float thinktime);
+void trap_EA_GetInput(int client, float thinktime, void /* struct bot_input_s */ *input);
+void trap_EA_ResetInput(int client);
+
+
+int trap_BotLoadCharacter(char *charfile, float skill);
+void trap_BotFreeCharacter(int character);
+float trap_Characteristic_Float(int character, int index);
+float trap_Characteristic_BFloat(int character, int index, float min, float max);
+int trap_Characteristic_Integer(int character, int index);
+int trap_Characteristic_BInteger(int character, int index, int min, int max);
+void trap_Characteristic_String(int character, int index, char *buf, int size);
+
+int trap_BotAllocChatState(void);
+void trap_BotFreeChatState(int handle);
+void trap_BotQueueConsoleMessage(int chatstate, int type, char *message);
+void trap_BotRemoveConsoleMessage(int chatstate, int handle);
+int trap_BotNextConsoleMessage(int chatstate, void /* struct bot_consolemessage_s */ *cm);
+int trap_BotNumConsoleMessages(int chatstate);
+void trap_BotInitialChat(int chatstate, char *type, int mcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7 );
+int trap_BotNumInitialChats(int chatstate, char *type);
+int trap_BotReplyChat(int chatstate, char *message, int mcontext, int vcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7 );
+int trap_BotChatLength(int chatstate);
+void trap_BotEnterChat(int chatstate, int client, int sendto);
+void trap_BotGetChatMessage(int chatstate, char *buf, int size);
+int trap_StringContains(char *str1, char *str2, int casesensitive);
+int trap_BotFindMatch(char *str, void /* struct bot_match_s */ *match, unsigned long int context);
+void trap_BotMatchVariable(void /* struct bot_match_s */ *match, int variable, char *buf, int size);
+void trap_UnifyWhiteSpaces(char *string);
+void trap_BotReplaceSynonyms(char *string, unsigned long int context);
+int trap_BotLoadChatFile(int chatstate, char *chatfile, char *chatname);
+void trap_BotSetChatGender(int chatstate, int gender);
+void trap_BotSetChatName(int chatstate, char *name, int client);
+void trap_BotResetGoalState(int goalstate);
+void trap_BotRemoveFromAvoidGoals(int goalstate, int number);
+void trap_BotResetAvoidGoals(int goalstate);
+void trap_BotPushGoal(int goalstate, void /* struct bot_goal_s */ *goal);
+void trap_BotPopGoal(int goalstate);
+void trap_BotEmptyGoalStack(int goalstate);
+void trap_BotDumpAvoidGoals(int goalstate);
+void trap_BotDumpGoalStack(int goalstate);
+void trap_BotGoalName(int number, char *name, int size);
+int trap_BotGetTopGoal(int goalstate, void /* struct bot_goal_s */ *goal);
+int trap_BotGetSecondGoal(int goalstate, void /* struct bot_goal_s */ *goal);
+int trap_BotChooseLTGItem(int goalstate, vec3_t origin, int *inventory, int travelflags);
+int trap_BotChooseNBGItem(int goalstate, vec3_t origin, int *inventory, int travelflags, void /* struct bot_goal_s */ *ltg, float maxtime);
+int trap_BotTouchingGoal(vec3_t origin, void /* struct bot_goal_s */ *goal);
+int trap_BotItemGoalInVisButNotVisible(int viewer, vec3_t eye, vec3_t viewangles, void /* struct bot_goal_s */ *goal);
+int trap_BotGetNextCampSpotGoal(int num, void /* struct bot_goal_s */ *goal);
+int trap_BotGetMapLocationGoal(char *name, void /* struct bot_goal_s */ *goal);
+int trap_BotGetLevelItemGoal(int index, char *classname, void /* struct bot_goal_s */ *goal);
+float trap_BotAvoidGoalTime(int goalstate, int number);
+void trap_BotSetAvoidGoalTime(int goalstate, int number, float avoidtime);
+void trap_BotInitLevelItems(void);
+void trap_BotUpdateEntityItems(void);
+int trap_BotLoadItemWeights(int goalstate, char *filename);
+void trap_BotFreeItemWeights(int goalstate);
+void trap_BotInterbreedGoalFuzzyLogic(int parent1, int parent2, int child);
+void trap_BotSaveGoalFuzzyLogic(int goalstate, char *filename);
+void trap_BotMutateGoalFuzzyLogic(int goalstate, float range);
+int trap_BotAllocGoalState(int state);
+void trap_BotFreeGoalState(int handle);
+
+void trap_BotResetMoveState(int movestate);
+void trap_BotMoveToGoal(void /* struct bot_moveresult_s */ *result, int movestate, void /* struct bot_goal_s */ *goal, int travelflags);
+int trap_BotMoveInDirection(int movestate, vec3_t dir, float speed, int type);
+void trap_BotResetAvoidReach(int movestate);
+void trap_BotResetLastAvoidReach(int movestate);
+int trap_BotReachabilityArea(vec3_t origin, int testground);
+int trap_BotMovementViewTarget(int movestate, void /* struct bot_goal_s */ *goal, int travelflags, float lookahead, vec3_t target);
+int trap_BotPredictVisiblePosition(vec3_t origin, int areanum, void /* struct bot_goal_s */ *goal, int travelflags, vec3_t target);
+int trap_BotAllocMoveState(void);
+void trap_BotFreeMoveState(int handle);
+void trap_BotInitMoveState(int handle, void /* struct bot_initmove_s */ *initmove);
+void trap_BotAddAvoidSpot(int movestate, vec3_t origin, float radius, int type);
+
+int trap_BotChooseBestFightWeapon(int weaponstate, int *inventory);
+void trap_BotGetWeaponInfo(int weaponstate, int weapon, void /* struct weaponinfo_s */ *weaponinfo);
+int trap_BotLoadWeaponWeights(int weaponstate, char *filename);
+int trap_BotAllocWeaponState(void);
+void trap_BotFreeWeaponState(int weaponstate);
+void trap_BotResetWeaponState(int weaponstate);
+
+int trap_GeneticParentsAndChildSelection(int numranks, float *ranks, int *parent1, int *parent2, int *child);
+
+void trap_SnapVector( float *v );
+
diff --git a/code/game/g_main.c b/code/game/g_main.c
new file mode 100755
index 0000000..9f60272
--- /dev/null
+++ b/code/game/g_main.c
@@ -0,0 +1,1832 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+#include "g_local.h"
+
+level_locals_t level;
+
+typedef struct {
+ vmCvar_t *vmCvar;
+ char *cvarName;
+ char *defaultString;
+ int cvarFlags;
+ int modificationCount; // for tracking changes
+ qboolean trackChange; // track this variable, and announce if changed
+ qboolean teamShader; // track and if changed, update shader state
+} cvarTable_t;
+
+gentity_t g_entities[MAX_GENTITIES];
+gclient_t g_clients[MAX_CLIENTS];
+
+vmCvar_t g_gametype;
+vmCvar_t g_dmflags;
+vmCvar_t g_fraglimit;
+vmCvar_t g_timelimit;
+vmCvar_t g_capturelimit;
+vmCvar_t g_friendlyFire;
+vmCvar_t g_password;
+vmCvar_t g_needpass;
+vmCvar_t g_maxclients;
+vmCvar_t g_maxGameClients;
+vmCvar_t g_dedicated;
+vmCvar_t g_speed;
+vmCvar_t g_gravity;
+vmCvar_t g_cheats;
+vmCvar_t g_knockback;
+vmCvar_t g_quadfactor;
+vmCvar_t g_forcerespawn;
+vmCvar_t g_inactivity;
+vmCvar_t g_debugMove;
+vmCvar_t g_debugDamage;
+vmCvar_t g_debugAlloc;
+vmCvar_t g_weaponRespawn;
+vmCvar_t g_weaponTeamRespawn;
+vmCvar_t g_motd;
+vmCvar_t g_synchronousClients;
+vmCvar_t g_warmup;
+vmCvar_t g_doWarmup;
+vmCvar_t g_restarted;
+vmCvar_t g_log;
+vmCvar_t g_logSync;
+vmCvar_t g_blood;
+vmCvar_t g_podiumDist;
+vmCvar_t g_podiumDrop;
+vmCvar_t g_allowVote;
+vmCvar_t g_teamAutoJoin;
+vmCvar_t g_teamForceBalance;
+vmCvar_t g_banIPs;
+vmCvar_t g_filterBan;
+vmCvar_t g_smoothClients;
+vmCvar_t pmove_fixed;
+vmCvar_t pmove_msec;
+vmCvar_t g_rankings;
+vmCvar_t g_listEntity;
+#ifdef MISSIONPACK
+vmCvar_t g_obeliskHealth;
+vmCvar_t g_obeliskRegenPeriod;
+vmCvar_t g_obeliskRegenAmount;
+vmCvar_t g_obeliskRespawnDelay;
+vmCvar_t g_cubeTimeout;
+vmCvar_t g_redteam;
+vmCvar_t g_blueteam;
+vmCvar_t g_singlePlayer;
+vmCvar_t g_enableDust;
+vmCvar_t g_enableBreath;
+vmCvar_t g_proxMineTimeout;
+#endif
+
+// bk001129 - made static to avoid aliasing
+static cvarTable_t gameCvarTable[] = {
+ // don't override the cheat state set by the system
+ { &g_cheats, "sv_cheats", "", 0, 0, qfalse },
+
+ // noset vars
+ { NULL, "gamename", GAMEVERSION , CVAR_SERVERINFO | CVAR_ROM, 0, qfalse },
+ { NULL, "gamedate", __DATE__ , CVAR_ROM, 0, qfalse },
+ { &g_restarted, "g_restarted", "0", CVAR_ROM, 0, qfalse },
+ { NULL, "sv_mapname", "", CVAR_SERVERINFO | CVAR_ROM, 0, qfalse },
+
+ // latched vars
+ { &g_gametype, "g_gametype", "0", CVAR_SERVERINFO | CVAR_USERINFO | CVAR_LATCH, 0, qfalse },
+
+ { &g_maxclients, "sv_maxclients", "8", CVAR_SERVERINFO | CVAR_LATCH | CVAR_ARCHIVE, 0, qfalse },
+ { &g_maxGameClients, "g_maxGameClients", "0", CVAR_SERVERINFO | CVAR_LATCH | CVAR_ARCHIVE, 0, qfalse },
+
+ // change anytime vars
+ { &g_dmflags, "dmflags", "0", CVAR_SERVERINFO | CVAR_ARCHIVE, 0, qtrue },
+ { &g_fraglimit, "fraglimit", "20", CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_NORESTART, 0, qtrue },
+ { &g_timelimit, "timelimit", "0", CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_NORESTART, 0, qtrue },
+ { &g_capturelimit, "capturelimit", "8", CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_NORESTART, 0, qtrue },
+
+ { &g_synchronousClients, "g_synchronousClients", "0", CVAR_SYSTEMINFO, 0, qfalse },
+
+ { &g_friendlyFire, "g_friendlyFire", "0", CVAR_ARCHIVE, 0, qtrue },
+
+ { &g_teamAutoJoin, "g_teamAutoJoin", "0", CVAR_ARCHIVE },
+ { &g_teamForceBalance, "g_teamForceBalance", "0", CVAR_ARCHIVE },
+
+ { &g_warmup, "g_warmup", "20", CVAR_ARCHIVE, 0, qtrue },
+ { &g_doWarmup, "g_doWarmup", "0", 0, 0, qtrue },
+ { &g_log, "g_log", "games.log", CVAR_ARCHIVE, 0, qfalse },
+ { &g_logSync, "g_logSync", "0", CVAR_ARCHIVE, 0, qfalse },
+
+ { &g_password, "g_password", "", CVAR_USERINFO, 0, qfalse },
+
+ { &g_banIPs, "g_banIPs", "", CVAR_ARCHIVE, 0, qfalse },
+ { &g_filterBan, "g_filterBan", "1", CVAR_ARCHIVE, 0, qfalse },
+
+ { &g_needpass, "g_needpass", "0", CVAR_SERVERINFO | CVAR_ROM, 0, qfalse },
+
+ { &g_dedicated, "dedicated", "0", 0, 0, qfalse },
+
+ { &g_speed, "g_speed", "320", 0, 0, qtrue },
+ { &g_gravity, "g_gravity", "800", 0, 0, qtrue },
+ { &g_knockback, "g_knockback", "1000", 0, 0, qtrue },
+ { &g_quadfactor, "g_quadfactor", "3", 0, 0, qtrue },
+ { &g_weaponRespawn, "g_weaponrespawn", "5", 0, 0, qtrue },
+ { &g_weaponTeamRespawn, "g_weaponTeamRespawn", "30", 0, 0, qtrue },
+ { &g_forcerespawn, "g_forcerespawn", "20", 0, 0, qtrue },
+ { &g_inactivity, "g_inactivity", "0", 0, 0, qtrue },
+ { &g_debugMove, "g_debugMove", "0", 0, 0, qfalse },
+ { &g_debugDamage, "g_debugDamage", "0", 0, 0, qfalse },
+ { &g_debugAlloc, "g_debugAlloc", "0", 0, 0, qfalse },
+ { &g_motd, "g_motd", "", 0, 0, qfalse },
+ { &g_blood, "com_blood", "1", 0, 0, qfalse },
+
+ { &g_podiumDist, "g_podiumDist", "80", 0, 0, qfalse },
+ { &g_podiumDrop, "g_podiumDrop", "70", 0, 0, qfalse },
+
+ { &g_allowVote, "g_allowVote", "1", CVAR_ARCHIVE, 0, qfalse },
+ { &g_listEntity, "g_listEntity", "0", 0, 0, qfalse },
+
+#ifdef MISSIONPACK
+ { &g_obeliskHealth, "g_obeliskHealth", "2500", 0, 0, qfalse },
+ { &g_obeliskRegenPeriod, "g_obeliskRegenPeriod", "1", 0, 0, qfalse },
+ { &g_obeliskRegenAmount, "g_obeliskRegenAmount", "15", 0, 0, qfalse },
+ { &g_obeliskRespawnDelay, "g_obeliskRespawnDelay", "10", CVAR_SERVERINFO, 0, qfalse },
+
+ { &g_cubeTimeout, "g_cubeTimeout", "30", 0, 0, qfalse },
+ { &g_redteam, "g_redteam", "Stroggs", CVAR_ARCHIVE | CVAR_SERVERINFO | CVAR_USERINFO , 0, qtrue, qtrue },
+ { &g_blueteam, "g_blueteam", "Pagans", CVAR_ARCHIVE | CVAR_SERVERINFO | CVAR_USERINFO , 0, qtrue, qtrue },
+ { &g_singlePlayer, "ui_singlePlayerActive", "", 0, 0, qfalse, qfalse },
+
+ { &g_enableDust, "g_enableDust", "0", CVAR_SERVERINFO, 0, qtrue, qfalse },
+ { &g_enableBreath, "g_enableBreath", "0", CVAR_SERVERINFO, 0, qtrue, qfalse },
+ { &g_proxMineTimeout, "g_proxMineTimeout", "20000", 0, 0, qfalse },
+#endif
+ { &g_smoothClients, "g_smoothClients", "1", 0, 0, qfalse},
+ { &pmove_fixed, "pmove_fixed", "0", CVAR_SYSTEMINFO, 0, qfalse},
+ { &pmove_msec, "pmove_msec", "8", CVAR_SYSTEMINFO, 0, qfalse},
+
+ { &g_rankings, "g_rankings", "0", 0, 0, qfalse}
+
+};
+
+// bk001129 - made static to avoid aliasing
+static int gameCvarTableSize = sizeof( gameCvarTable ) / sizeof( gameCvarTable[0] );
+
+
+void G_InitGame( int levelTime, int randomSeed, int restart );
+void G_RunFrame( int levelTime );
+void G_ShutdownGame( int restart );
+void CheckExitRules( void );
+
+
+/*
+================
+vmMain
+
+This is the only way control passes into the module.
+This must be the very first function compiled into the .q3vm file
+================
+*/
+int vmMain( int command, int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11 ) {
+ switch ( command ) {
+ case GAME_INIT:
+ G_InitGame( arg0, arg1, arg2 );
+ return 0;
+ case GAME_SHUTDOWN:
+ G_ShutdownGame( arg0 );
+ return 0;
+ case GAME_CLIENT_CONNECT:
+ return (int)ClientConnect( arg0, arg1, arg2 );
+ case GAME_CLIENT_THINK:
+ ClientThink( arg0 );
+ return 0;
+ case GAME_CLIENT_USERINFO_CHANGED:
+ ClientUserinfoChanged( arg0 );
+ return 0;
+ case GAME_CLIENT_DISCONNECT:
+ ClientDisconnect( arg0 );
+ return 0;
+ case GAME_CLIENT_BEGIN:
+ ClientBegin( arg0 );
+ return 0;
+ case GAME_CLIENT_COMMAND:
+ ClientCommand( arg0 );
+ return 0;
+ case GAME_RUN_FRAME:
+ G_RunFrame( arg0 );
+ return 0;
+ case GAME_CONSOLE_COMMAND:
+ return ConsoleCommand();
+ case BOTAI_START_FRAME:
+ return BotAIStartFrame( arg0 );
+ }
+
+ return -1;
+}
+
+
+void QDECL G_Printf( const char *fmt, ... ) {
+ va_list argptr;
+ char text[1024];
+
+ va_start (argptr, fmt);
+ vsprintf (text, fmt, argptr);
+ va_end (argptr);
+
+ trap_Printf( text );
+}
+
+void QDECL G_Error( const char *fmt, ... ) {
+ va_list argptr;
+ char text[1024];
+
+ va_start (argptr, fmt);
+ vsprintf (text, fmt, argptr);
+ va_end (argptr);
+
+ trap_Error( text );
+}
+
+/*
+================
+G_FindTeams
+
+Chain together all entities with a matching team field.
+Entity teams are used for item groups and multi-entity mover groups.
+
+All but the first will have the FL_TEAMSLAVE flag set and teammaster field set
+All but the last will have the teamchain field set to the next one
+================
+*/
+void G_FindTeams( void ) {
+ gentity_t *e, *e2;
+ int i, j;
+ int c, c2;
+
+ c = 0;
+ c2 = 0;
+ for ( i=1, e=g_entities+i ; i < level.num_entities ; i++,e++ ){
+ if (!e->inuse)
+ continue;
+ if (!e->team)
+ continue;
+ if (e->flags & FL_TEAMSLAVE)
+ continue;
+ e->teammaster = e;
+ c++;
+ c2++;
+ for (j=i+1, e2=e+1 ; j < level.num_entities ; j++,e2++)
+ {
+ if (!e2->inuse)
+ continue;
+ if (!e2->team)
+ continue;
+ if (e2->flags & FL_TEAMSLAVE)
+ continue;
+ if (!strcmp(e->team, e2->team))
+ {
+ c2++;
+ e2->teamchain = e->teamchain;
+ e->teamchain = e2;
+ e2->teammaster = e;
+ e2->flags |= FL_TEAMSLAVE;
+
+ // make sure that targets only point at the master
+ if ( e2->targetname ) {
+ e->targetname = e2->targetname;
+ e2->targetname = NULL;
+ }
+ }
+ }
+ }
+
+ G_Printf ("%i teams with %i entities\n", c, c2);
+}
+
+void G_RemapTeamShaders() {
+#ifdef MISSIONPACK
+ char string[1024];
+ float f = level.time * 0.001;
+ Com_sprintf( string, sizeof(string), "team_icon/%s_red", g_redteam.string );
+ AddRemap("textures/ctf2/redteam01", string, f);
+ AddRemap("textures/ctf2/redteam02", string, f);
+ Com_sprintf( string, sizeof(string), "team_icon/%s_blue", g_blueteam.string );
+ AddRemap("textures/ctf2/blueteam01", string, f);
+ AddRemap("textures/ctf2/blueteam02", string, f);
+ trap_SetConfigstring(CS_SHADERSTATE, BuildShaderStateConfig());
+#endif
+}
+
+
+/*
+=================
+G_RegisterCvars
+=================
+*/
+void G_RegisterCvars( void ) {
+ int i;
+ cvarTable_t *cv;
+ qboolean remapped = qfalse;
+
+ for ( i = 0, cv = gameCvarTable ; i < gameCvarTableSize ; i++, cv++ ) {
+ trap_Cvar_Register( cv->vmCvar, cv->cvarName,
+ cv->defaultString, cv->cvarFlags );
+ if ( cv->vmCvar )
+ cv->modificationCount = cv->vmCvar->modificationCount;
+
+ if (cv->teamShader) {
+ remapped = qtrue;
+ }
+ }
+
+ if (remapped) {
+ G_RemapTeamShaders();
+ }
+
+ // check some things
+ if ( g_gametype.integer < 0 || g_gametype.integer >= GT_MAX_GAME_TYPE ) {
+ G_Printf( "g_gametype %i is out of range, defaulting to 0\n", g_gametype.integer );
+ trap_Cvar_Set( "g_gametype", "0" );
+ }
+
+ level.warmupModificationCount = g_warmup.modificationCount;
+}
+
+/*
+=================
+G_UpdateCvars
+=================
+*/
+void G_UpdateCvars( void ) {
+ int i;
+ cvarTable_t *cv;
+ qboolean remapped = qfalse;
+
+ for ( i = 0, cv = gameCvarTable ; i < gameCvarTableSize ; i++, cv++ ) {
+ if ( cv->vmCvar ) {
+ trap_Cvar_Update( cv->vmCvar );
+
+ if ( cv->modificationCount != cv->vmCvar->modificationCount ) {
+ cv->modificationCount = cv->vmCvar->modificationCount;
+
+ if ( cv->trackChange ) {
+ trap_SendServerCommand( -1, va("print \"Server: %s changed to %s\n\"",
+ cv->cvarName, cv->vmCvar->string ) );
+ }
+
+ if (cv->teamShader) {
+ remapped = qtrue;
+ }
+ }
+ }
+ }
+
+ if (remapped) {
+ G_RemapTeamShaders();
+ }
+}
+
+/*
+============
+G_InitGame
+
+============
+*/
+void G_InitGame( int levelTime, int randomSeed, int restart ) {
+ int i;
+
+ G_Printf ("------- Game Initialization -------\n");
+ G_Printf ("gamename: %s\n", GAMEVERSION);
+ G_Printf ("gamedate: %s\n", __DATE__);
+
+ srand( randomSeed );
+
+ G_RegisterCvars();
+
+ G_ProcessIPBans();
+
+ G_InitMemory();
+
+ // set some level globals
+ memset( &level, 0, sizeof( level ) );
+ level.time = levelTime;
+ level.startTime = levelTime;
+
+ level.snd_fry = G_SoundIndex("sound/player/fry.wav"); // FIXME standing in lava / slime
+
+ if ( g_gametype.integer != GT_SINGLE_PLAYER && g_log.string[0] ) {
+ if ( g_logSync.integer ) {
+ trap_FS_FOpenFile( g_log.string, &level.logFile, FS_APPEND_SYNC );
+ } else {
+ trap_FS_FOpenFile( g_log.string, &level.logFile, FS_APPEND );
+ }
+ if ( !level.logFile ) {
+ G_Printf( "WARNING: Couldn't open logfile: %s\n", g_log.string );
+ } else {
+ char serverinfo[MAX_INFO_STRING];
+
+ trap_GetServerinfo( serverinfo, sizeof( serverinfo ) );
+
+ G_LogPrintf("------------------------------------------------------------\n" );
+ G_LogPrintf("InitGame: %s\n", serverinfo );
+ }
+ } else {
+ G_Printf( "Not logging to disk.\n" );
+ }
+
+ G_InitWorldSession();
+
+ // initialize all entities for this game
+ memset( g_entities, 0, MAX_GENTITIES * sizeof(g_entities[0]) );
+ level.gentities = g_entities;
+
+ // initialize all clients for this game
+ level.maxclients = g_maxclients.integer;
+ memset( g_clients, 0, MAX_CLIENTS * sizeof(g_clients[0]) );
+ level.clients = g_clients;
+
+ // set client fields on player ents
+ for ( i=0 ; i<level.maxclients ; i++ ) {
+ g_entities[i].client = level.clients + i;
+ }
+
+ // always leave room for the max number of clients,
+ // even if they aren't all used, so numbers inside that
+ // range are NEVER anything but clients
+ level.num_entities = MAX_CLIENTS;
+
+ // let the server system know where the entites are
+ trap_LocateGameData( level.gentities, level.num_entities, sizeof( gentity_t ),
+ &level.clients[0].ps, sizeof( level.clients[0] ) );
+
+ // reserve some spots for dead player bodies
+ InitBodyQue();
+
+ ClearRegisteredItems();
+
+ // parse the key/value pairs and spawn gentities
+ G_SpawnEntitiesFromString();
+
+ // general initialization
+ G_FindTeams();
+
+ // make sure we have flags for CTF, etc
+ if( g_gametype.integer >= GT_TEAM ) {
+ G_CheckTeamItems();
+ }
+
+ SaveRegisteredItems();
+
+ G_Printf ("-----------------------------------\n");
+
+ if( g_gametype.integer == GT_SINGLE_PLAYER || trap_Cvar_VariableIntegerValue( "com_buildScript" ) ) {
+ G_ModelIndex( SP_PODIUM_MODEL );
+ G_SoundIndex( "sound/player/gurp1.wav" );
+ G_SoundIndex( "sound/player/gurp2.wav" );
+ }
+
+ if ( trap_Cvar_VariableIntegerValue( "bot_enable" ) ) {
+ BotAISetup( restart );
+ BotAILoadMap( restart );
+ G_InitBots( restart );
+ }
+
+ G_RemapTeamShaders();
+
+}
+
+
+
+/*
+=================
+G_ShutdownGame
+=================
+*/
+void G_ShutdownGame( int restart ) {
+ G_Printf ("==== ShutdownGame ====\n");
+
+ if ( level.logFile ) {
+ G_LogPrintf("ShutdownGame:\n" );
+ G_LogPrintf("------------------------------------------------------------\n" );
+ trap_FS_FCloseFile( level.logFile );
+ }
+
+ // write all the client session data so we can get it back
+ G_WriteSessionData();
+
+ if ( trap_Cvar_VariableIntegerValue( "bot_enable" ) ) {
+ BotAIShutdown( restart );
+ }
+}
+
+
+
+//===================================================================
+
+#ifndef GAME_HARD_LINKED
+// this is only here so the functions in q_shared.c and bg_*.c can link
+
+void QDECL Com_Error ( int level, const char *error, ... ) {
+ va_list argptr;
+ char text[1024];
+
+ va_start (argptr, error);
+ vsprintf (text, error, argptr);
+ va_end (argptr);
+
+ G_Error( "%s", text);
+}
+
+void QDECL Com_Printf( const char *msg, ... ) {
+ va_list argptr;
+ char text[1024];
+
+ va_start (argptr, msg);
+ vsprintf (text, msg, argptr);
+ va_end (argptr);
+
+ G_Printf ("%s", text);
+}
+
+#endif
+
+/*
+========================================================================
+
+PLAYER COUNTING / SCORE SORTING
+
+========================================================================
+*/
+
+/*
+=============
+AddTournamentPlayer
+
+If there are less than two tournament players, put a
+spectator in the game and restart
+=============
+*/
+void AddTournamentPlayer( void ) {
+ int i;
+ gclient_t *client;
+ gclient_t *nextInLine;
+
+ if ( level.numPlayingClients >= 2 ) {
+ return;
+ }
+
+ // never change during intermission
+ if ( level.intermissiontime ) {
+ return;
+ }
+
+ nextInLine = NULL;
+
+ for ( i = 0 ; i < level.maxclients ; i++ ) {
+ client = &level.clients[i];
+ if ( client->pers.connected != CON_CONNECTED ) {
+ continue;
+ }
+ if ( client->sess.sessionTeam != TEAM_SPECTATOR ) {
+ continue;
+ }
+ // never select the dedicated follow or scoreboard clients
+ if ( client->sess.spectatorState == SPECTATOR_SCOREBOARD ||
+ client->sess.spectatorClient < 0 ) {
+ continue;
+ }
+
+ if ( !nextInLine || client->sess.spectatorTime < nextInLine->sess.spectatorTime ) {
+ nextInLine = client;
+ }
+ }
+
+ if ( !nextInLine ) {
+ return;
+ }
+
+ level.warmupTime = -1;
+
+ // set them to free-for-all team
+ SetTeam( &g_entities[ nextInLine - level.clients ], "f" );
+}
+
+/*
+=======================
+RemoveTournamentLoser
+
+Make the loser a spectator at the back of the line
+=======================
+*/
+void RemoveTournamentLoser( void ) {
+ int clientNum;
+
+ if ( level.numPlayingClients != 2 ) {
+ return;
+ }
+
+ clientNum = level.sortedClients[1];
+
+ if ( level.clients[ clientNum ].pers.connected != CON_CONNECTED ) {
+ return;
+ }
+
+ // make them a spectator
+ SetTeam( &g_entities[ clientNum ], "s" );
+}
+
+/*
+=======================
+RemoveTournamentWinner
+=======================
+*/
+void RemoveTournamentWinner( void ) {
+ int clientNum;
+
+ if ( level.numPlayingClients != 2 ) {
+ return;
+ }
+
+ clientNum = level.sortedClients[0];
+
+ if ( level.clients[ clientNum ].pers.connected != CON_CONNECTED ) {
+ return;
+ }
+
+ // make them a spectator
+ SetTeam( &g_entities[ clientNum ], "s" );
+}
+
+/*
+=======================
+AdjustTournamentScores
+=======================
+*/
+void AdjustTournamentScores( void ) {
+ int clientNum;
+
+ clientNum = level.sortedClients[0];
+ if ( level.clients[ clientNum ].pers.connected == CON_CONNECTED ) {
+ level.clients[ clientNum ].sess.wins++;
+ ClientUserinfoChanged( clientNum );
+ }
+
+ clientNum = level.sortedClients[1];
+ if ( level.clients[ clientNum ].pers.connected == CON_CONNECTED ) {
+ level.clients[ clientNum ].sess.losses++;
+ ClientUserinfoChanged( clientNum );
+ }
+
+}
+
+/*
+=============
+SortRanks
+
+=============
+*/
+int QDECL SortRanks( const void *a, const void *b ) {
+ gclient_t *ca, *cb;
+
+ ca = &level.clients[*(int *)a];
+ cb = &level.clients[*(int *)b];
+
+ // sort special clients last
+ if ( ca->sess.spectatorState == SPECTATOR_SCOREBOARD || ca->sess.spectatorClient < 0 ) {
+ return 1;
+ }
+ if ( cb->sess.spectatorState == SPECTATOR_SCOREBOARD || cb->sess.spectatorClient < 0 ) {
+ return -1;
+ }
+
+ // then connecting clients
+ if ( ca->pers.connected == CON_CONNECTING ) {
+ return 1;
+ }
+ if ( cb->pers.connected == CON_CONNECTING ) {
+ return -1;
+ }
+
+
+ // then spectators
+ if ( ca->sess.sessionTeam == TEAM_SPECTATOR && cb->sess.sessionTeam == TEAM_SPECTATOR ) {
+ if ( ca->sess.spectatorTime < cb->sess.spectatorTime ) {
+ return -1;
+ }
+ if ( ca->sess.spectatorTime > cb->sess.spectatorTime ) {
+ return 1;
+ }
+ return 0;
+ }
+ if ( ca->sess.sessionTeam == TEAM_SPECTATOR ) {
+ return 1;
+ }
+ if ( cb->sess.sessionTeam == TEAM_SPECTATOR ) {
+ return -1;
+ }
+
+ // then sort by score
+ if ( ca->ps.persistant[PERS_SCORE]
+ > cb->ps.persistant[PERS_SCORE] ) {
+ return -1;
+ }
+ if ( ca->ps.persistant[PERS_SCORE]
+ < cb->ps.persistant[PERS_SCORE] ) {
+ return 1;
+ }
+ return 0;
+}
+
+/*
+============
+CalculateRanks
+
+Recalculates the score ranks of all players
+This will be called on every client connect, begin, disconnect, death,
+and team change.
+============
+*/
+void CalculateRanks( void ) {
+ int i;
+ int rank;
+ int score;
+ int newScore;
+ gclient_t *cl;
+
+ level.follow1 = -1;
+ level.follow2 = -1;
+ level.numConnectedClients = 0;
+ level.numNonSpectatorClients = 0;
+ level.numPlayingClients = 0;
+ level.numVotingClients = 0; // don't count bots
+ for ( i = 0; i < TEAM_NUM_TEAMS; i++ ) {
+ level.numteamVotingClients[i] = 0;
+ }
+ for ( i = 0 ; i < level.maxclients ; i++ ) {
+ if ( level.clients[i].pers.connected != CON_DISCONNECTED ) {
+ level.sortedClients[level.numConnectedClients] = i;
+ level.numConnectedClients++;
+
+ if ( level.clients[i].sess.sessionTeam != TEAM_SPECTATOR ) {
+ level.numNonSpectatorClients++;
+
+ // decide if this should be auto-followed
+ if ( level.clients[i].pers.connected == CON_CONNECTED ) {
+ level.numPlayingClients++;
+ if ( !(g_entities[i].r.svFlags & SVF_BOT) ) {
+ level.numVotingClients++;
+ if ( level.clients[i].sess.sessionTeam == TEAM_RED )
+ level.numteamVotingClients[0]++;
+ else if ( level.clients[i].sess.sessionTeam == TEAM_BLUE )
+ level.numteamVotingClients[1]++;
+ }
+ if ( level.follow1 == -1 ) {
+ level.follow1 = i;
+ } else if ( level.follow2 == -1 ) {
+ level.follow2 = i;
+ }
+ }
+ }
+ }
+ }
+
+ qsort( level.sortedClients, level.numConnectedClients,
+ sizeof(level.sortedClients[0]), SortRanks );
+
+ // set the rank value for all clients that are connected and not spectators
+ if ( g_gametype.integer >= GT_TEAM ) {
+ // in team games, rank is just the order of the teams, 0=red, 1=blue, 2=tied
+ for ( i = 0; i < level.numConnectedClients; i++ ) {
+ cl = &level.clients[ level.sortedClients[i] ];
+ if ( level.teamScores[TEAM_RED] == level.teamScores[TEAM_BLUE] ) {
+ cl->ps.persistant[PERS_RANK] = 2;
+ } else if ( level.teamScores[TEAM_RED] > level.teamScores[TEAM_BLUE] ) {
+ cl->ps.persistant[PERS_RANK] = 0;
+ } else {
+ cl->ps.persistant[PERS_RANK] = 1;
+ }
+ }
+ } else {
+ rank = -1;
+ score = 0;
+ for ( i = 0; i < level.numPlayingClients; i++ ) {
+ cl = &level.clients[ level.sortedClients[i] ];
+ newScore = cl->ps.persistant[PERS_SCORE];
+ if ( i == 0 || newScore != score ) {
+ rank = i;
+ // assume we aren't tied until the next client is checked
+ level.clients[ level.sortedClients[i] ].ps.persistant[PERS_RANK] = rank;
+ } else {
+ // we are tied with the previous client
+ level.clients[ level.sortedClients[i-1] ].ps.persistant[PERS_RANK] = rank | RANK_TIED_FLAG;
+ level.clients[ level.sortedClients[i] ].ps.persistant[PERS_RANK] = rank | RANK_TIED_FLAG;
+ }
+ score = newScore;
+ if ( g_gametype.integer == GT_SINGLE_PLAYER && level.numPlayingClients == 1 ) {
+ level.clients[ level.sortedClients[i] ].ps.persistant[PERS_RANK] = rank | RANK_TIED_FLAG;
+ }
+ }
+ }
+
+ // set the CS_SCORES1/2 configstrings, which will be visible to everyone
+ if ( g_gametype.integer >= GT_TEAM ) {
+ trap_SetConfigstring( CS_SCORES1, va("%i", level.teamScores[TEAM_RED] ) );
+ trap_SetConfigstring( CS_SCORES2, va("%i", level.teamScores[TEAM_BLUE] ) );
+ } else {
+ if ( level.numConnectedClients == 0 ) {
+ trap_SetConfigstring( CS_SCORES1, va("%i", SCORE_NOT_PRESENT) );
+ trap_SetConfigstring( CS_SCORES2, va("%i", SCORE_NOT_PRESENT) );
+ } else if ( level.numConnectedClients == 1 ) {
+ trap_SetConfigstring( CS_SCORES1, va("%i", level.clients[ level.sortedClients[0] ].ps.persistant[PERS_SCORE] ) );
+ trap_SetConfigstring( CS_SCORES2, va("%i", SCORE_NOT_PRESENT) );
+ } else {
+ trap_SetConfigstring( CS_SCORES1, va("%i", level.clients[ level.sortedClients[0] ].ps.persistant[PERS_SCORE] ) );
+ trap_SetConfigstring( CS_SCORES2, va("%i", level.clients[ level.sortedClients[1] ].ps.persistant[PERS_SCORE] ) );
+ }
+ }
+
+ // see if it is time to end the level
+ CheckExitRules();
+
+ // if we are at the intermission, send the new info to everyone
+ if ( level.intermissiontime ) {
+ SendScoreboardMessageToAllClients();
+ }
+}
+
+
+/*
+========================================================================
+
+MAP CHANGING
+
+========================================================================
+*/
+
+/*
+========================
+SendScoreboardMessageToAllClients
+
+Do this at BeginIntermission time and whenever ranks are recalculated
+due to enters/exits/forced team changes
+========================
+*/
+void SendScoreboardMessageToAllClients( void ) {
+ int i;
+
+ for ( i = 0 ; i < level.maxclients ; i++ ) {
+ if ( level.clients[ i ].pers.connected == CON_CONNECTED ) {
+ DeathmatchScoreboardMessage( g_entities + i );
+ }
+ }
+}
+
+/*
+========================
+MoveClientToIntermission
+
+When the intermission starts, this will be called for all players.
+If a new client connects, this will be called after the spawn function.
+========================
+*/
+void MoveClientToIntermission( gentity_t *ent ) {
+ // take out of follow mode if needed
+ if ( ent->client->sess.spectatorState == SPECTATOR_FOLLOW ) {
+ StopFollowing( ent );
+ }
+
+
+ // move to the spot
+ VectorCopy( level.intermission_origin, ent->s.origin );
+ VectorCopy( level.intermission_origin, ent->client->ps.origin );
+ VectorCopy (level.intermission_angle, ent->client->ps.viewangles);
+ ent->client->ps.pm_type = PM_INTERMISSION;
+
+ // clean up powerup info
+ memset( ent->client->ps.powerups, 0, sizeof(ent->client->ps.powerups) );
+
+ ent->client->ps.eFlags = 0;
+ ent->s.eFlags = 0;
+ ent->s.eType = ET_GENERAL;
+ ent->s.modelindex = 0;
+ ent->s.loopSound = 0;
+ ent->s.event = 0;
+ ent->r.contents = 0;
+}
+
+/*
+==================
+FindIntermissionPoint
+
+This is also used for spectator spawns
+==================
+*/
+void FindIntermissionPoint( void ) {
+ gentity_t *ent, *target;
+ vec3_t dir;
+
+ // find the intermission spot
+ ent = G_Find (NULL, FOFS(classname), "info_player_intermission");
+ if ( !ent ) { // the map creator forgot to put in an intermission point...
+ SelectSpawnPoint ( vec3_origin, level.intermission_origin, level.intermission_angle );
+ } else {
+ VectorCopy (ent->s.origin, level.intermission_origin);
+ VectorCopy (ent->s.angles, level.intermission_angle);
+ // if it has a target, look towards it
+ if ( ent->target ) {
+ target = G_PickTarget( ent->target );
+ if ( target ) {
+ VectorSubtract( target->s.origin, level.intermission_origin, dir );
+ vectoangles( dir, level.intermission_angle );
+ }
+ }
+ }
+
+}
+
+/*
+==================
+BeginIntermission
+==================
+*/
+void BeginIntermission( void ) {
+ int i;
+ gentity_t *client;
+
+ if ( level.intermissiontime ) {
+ return; // already active
+ }
+
+ // if in tournement mode, change the wins / losses
+ if ( g_gametype.integer == GT_TOURNAMENT ) {
+ AdjustTournamentScores();
+ }
+
+ level.intermissiontime = level.time;
+ FindIntermissionPoint();
+
+#ifdef MISSIONPACK
+ if (g_singlePlayer.integer) {
+ trap_Cvar_Set("ui_singlePlayerActive", "0");
+ UpdateTournamentInfo();
+ }
+#else
+ // if single player game
+ if ( g_gametype.integer == GT_SINGLE_PLAYER ) {
+ UpdateTournamentInfo();
+ SpawnModelsOnVictoryPads();
+ }
+#endif
+
+ // move all clients to the intermission point
+ for (i=0 ; i< level.maxclients ; i++) {
+ client = g_entities + i;
+ if (!client->inuse)
+ continue;
+ // respawn if dead
+ if (client->health <= 0) {
+ respawn(client);
+ }
+ MoveClientToIntermission( client );
+ }
+
+ // send the current scoring to all clients
+ SendScoreboardMessageToAllClients();
+
+}
+
+
+/*
+=============
+ExitLevel
+
+When the intermission has been exited, the server is either killed
+or moved to a new level based on the "nextmap" cvar
+
+=============
+*/
+void ExitLevel (void) {
+ int i;
+ gclient_t *cl;
+
+ //bot interbreeding
+ BotInterbreedEndMatch();
+
+ // if we are running a tournement map, kick the loser to spectator status,
+ // which will automatically grab the next spectator and restart
+ if ( g_gametype.integer == GT_TOURNAMENT ) {
+ if ( !level.restarted ) {
+ RemoveTournamentLoser();
+ trap_SendConsoleCommand( EXEC_APPEND, "map_restart 0\n" );
+ level.restarted = qtrue;
+ level.changemap = NULL;
+ level.intermissiontime = 0;
+ }
+ return;
+ }
+
+
+ trap_SendConsoleCommand( EXEC_APPEND, "vstr nextmap\n" );
+ level.changemap = NULL;
+ level.intermissiontime = 0;
+
+ // reset all the scores so we don't enter the intermission again
+ level.teamScores[TEAM_RED] = 0;
+ level.teamScores[TEAM_BLUE] = 0;
+ for ( i=0 ; i< g_maxclients.integer ; i++ ) {
+ cl = level.clients + i;
+ if ( cl->pers.connected != CON_CONNECTED ) {
+ continue;
+ }
+ cl->ps.persistant[PERS_SCORE] = 0;
+ }
+
+ // we need to do this here before chaning to CON_CONNECTING
+ G_WriteSessionData();
+
+ // change all client states to connecting, so the early players into the
+ // next level will know the others aren't done reconnecting
+ for (i=0 ; i< g_maxclients.integer ; i++) {
+ if ( level.clients[i].pers.connected == CON_CONNECTED ) {
+ level.clients[i].pers.connected = CON_CONNECTING;
+ }
+ }
+
+}
+
+/*
+=================
+G_LogPrintf
+
+Print to the logfile with a time stamp if it is open
+=================
+*/
+void QDECL G_LogPrintf( const char *fmt, ... ) {
+ va_list argptr;
+ char string[1024];
+ int min, tens, sec;
+
+ sec = level.time / 1000;
+
+ min = sec / 60;
+ sec -= min * 60;
+ tens = sec / 10;
+ sec -= tens * 10;
+
+ Com_sprintf( string, sizeof(string), "%3i:%i%i ", min, tens, sec );
+
+ va_start( argptr, fmt );
+ vsprintf( string +7 , fmt,argptr );
+ va_end( argptr );
+
+ if ( g_dedicated.integer ) {
+ G_Printf( "%s", string + 7 );
+ }
+
+ if ( !level.logFile ) {
+ return;
+ }
+
+ trap_FS_Write( string, strlen( string ), level.logFile );
+}
+
+/*
+================
+LogExit
+
+Append information about this game to the log file
+================
+*/
+void LogExit( const char *string ) {
+ int i, numSorted;
+ gclient_t *cl;
+#ifdef MISSIONPACK // bk001205
+ qboolean won = qtrue;
+#endif
+ G_LogPrintf( "Exit: %s\n", string );
+
+ level.intermissionQueued = level.time;
+
+ // this will keep the clients from playing any voice sounds
+ // that will get cut off when the queued intermission starts
+ trap_SetConfigstring( CS_INTERMISSION, "1" );
+
+ // don't send more than 32 scores (FIXME?)
+ numSorted = level.numConnectedClients;
+ if ( numSorted > 32 ) {
+ numSorted = 32;
+ }
+
+ if ( g_gametype.integer >= GT_TEAM ) {
+ G_LogPrintf( "red:%i blue:%i\n",
+ level.teamScores[TEAM_RED], level.teamScores[TEAM_BLUE] );
+ }
+
+ for (i=0 ; i < numSorted ; i++) {
+ int ping;
+
+ cl = &level.clients[level.sortedClients[i]];
+
+ if ( cl->sess.sessionTeam == TEAM_SPECTATOR ) {
+ continue;
+ }
+ if ( cl->pers.connected == CON_CONNECTING ) {
+ continue;
+ }
+
+ ping = cl->ps.ping < 999 ? cl->ps.ping : 999;
+
+ G_LogPrintf( "score: %i ping: %i client: %i %s\n", cl->ps.persistant[PERS_SCORE], ping, level.sortedClients[i], cl->pers.netname );
+#ifdef MISSIONPACK
+ if (g_singlePlayer.integer && g_gametype.integer == GT_TOURNAMENT) {
+ if (g_entities[cl - level.clients].r.svFlags & SVF_BOT && cl->ps.persistant[PERS_RANK] == 0) {
+ won = qfalse;
+ }
+ }
+#endif
+
+ }
+
+#ifdef MISSIONPACK
+ if (g_singlePlayer.integer) {
+ if (g_gametype.integer >= GT_CTF) {
+ won = level.teamScores[TEAM_RED] > level.teamScores[TEAM_BLUE];
+ }
+ trap_SendConsoleCommand( EXEC_APPEND, (won) ? "spWin\n" : "spLose\n" );
+ }
+#endif
+
+
+}
+
+
+/*
+=================
+CheckIntermissionExit
+
+The level will stay at the intermission for a minimum of 5 seconds
+If all players wish to continue, the level will then exit.
+If one or more players have not acknowledged the continue, the game will
+wait 10 seconds before going on.
+=================
+*/
+void CheckIntermissionExit( void ) {
+ int ready, notReady;
+ int i;
+ gclient_t *cl;
+ int readyMask;
+
+ if ( g_gametype.integer == GT_SINGLE_PLAYER ) {
+ return;
+ }
+
+ // see which players are ready
+ ready = 0;
+ notReady = 0;
+ readyMask = 0;
+ for (i=0 ; i< g_maxclients.integer ; i++) {
+ cl = level.clients + i;
+ if ( cl->pers.connected != CON_CONNECTED ) {
+ continue;
+ }
+ if ( g_entities[cl->ps.clientNum].r.svFlags & SVF_BOT ) {
+ continue;
+ }
+
+ if ( cl->readyToExit ) {
+ ready++;
+ if ( i < 16 ) {
+ readyMask |= 1 << i;
+ }
+ } else {
+ notReady++;
+ }
+ }
+
+ // copy the readyMask to each player's stats so
+ // it can be displayed on the scoreboard
+ for (i=0 ; i< g_maxclients.integer ; i++) {
+ cl = level.clients + i;
+ if ( cl->pers.connected != CON_CONNECTED ) {
+ continue;
+ }
+ cl->ps.stats[STAT_CLIENTS_READY] = readyMask;
+ }
+
+ // never exit in less than five seconds
+ if ( level.time < level.intermissiontime + 5000 ) {
+ return;
+ }
+
+ // if nobody wants to go, clear timer
+ if ( !ready ) {
+ level.readyToExit = qfalse;
+ return;
+ }
+
+ // if everyone wants to go, go now
+ if ( !notReady ) {
+ ExitLevel();
+ return;
+ }
+
+ // the first person to ready starts the ten second timeout
+ if ( !level.readyToExit ) {
+ level.readyToExit = qtrue;
+ level.exitTime = level.time;
+ }
+
+ // if we have waited ten seconds since at least one player
+ // wanted to exit, go ahead
+ if ( level.time < level.exitTime + 10000 ) {
+ return;
+ }
+
+ ExitLevel();
+}
+
+/*
+=============
+ScoreIsTied
+=============
+*/
+qboolean ScoreIsTied( void ) {
+ int a, b;
+
+ if ( level.numPlayingClients < 2 ) {
+ return qfalse;
+ }
+
+ if ( g_gametype.integer >= GT_TEAM ) {
+ return level.teamScores[TEAM_RED] == level.teamScores[TEAM_BLUE];
+ }
+
+ a = level.clients[level.sortedClients[0]].ps.persistant[PERS_SCORE];
+ b = level.clients[level.sortedClients[1]].ps.persistant[PERS_SCORE];
+
+ return a == b;
+}
+
+/*
+=================
+CheckExitRules
+
+There will be a delay between the time the exit is qualified for
+and the time everyone is moved to the intermission spot, so you
+can see the last frag.
+=================
+*/
+void CheckExitRules( void ) {
+ int i;
+ gclient_t *cl;
+ // if at the intermission, wait for all non-bots to
+ // signal ready, then go to next level
+ if ( level.intermissiontime ) {
+ CheckIntermissionExit ();
+ return;
+ }
+
+ if ( level.intermissionQueued ) {
+#ifdef MISSIONPACK
+ int time = (g_singlePlayer.integer) ? SP_INTERMISSION_DELAY_TIME : INTERMISSION_DELAY_TIME;
+ if ( level.time - level.intermissionQueued >= time ) {
+ level.intermissionQueued = 0;
+ BeginIntermission();
+ }
+#else
+ if ( level.time - level.intermissionQueued >= INTERMISSION_DELAY_TIME ) {
+ level.intermissionQueued = 0;
+ BeginIntermission();
+ }
+#endif
+ return;
+ }
+
+ // check for sudden death
+ if ( ScoreIsTied() ) {
+ // always wait for sudden death
+ return;
+ }
+
+ if ( g_timelimit.integer && !level.warmupTime ) {
+ if ( level.time - level.startTime >= g_timelimit.integer*60000 ) {
+ trap_SendServerCommand( -1, "print \"Timelimit hit.\n\"");
+ LogExit( "Timelimit hit." );
+ return;
+ }
+ }
+
+ if ( level.numPlayingClients < 2 ) {
+ return;
+ }
+
+ if ( g_gametype.integer < GT_CTF && g_fraglimit.integer ) {
+ if ( level.teamScores[TEAM_RED] >= g_fraglimit.integer ) {
+ trap_SendServerCommand( -1, "print \"Red hit the fraglimit.\n\"" );
+ LogExit( "Fraglimit hit." );
+ return;
+ }
+
+ if ( level.teamScores[TEAM_BLUE] >= g_fraglimit.integer ) {
+ trap_SendServerCommand( -1, "print \"Blue hit the fraglimit.\n\"" );
+ LogExit( "Fraglimit hit." );
+ return;
+ }
+
+ for ( i=0 ; i< g_maxclients.integer ; i++ ) {
+ cl = level.clients + i;
+ if ( cl->pers.connected != CON_CONNECTED ) {
+ continue;
+ }
+ if ( cl->sess.sessionTeam != TEAM_FREE ) {
+ continue;
+ }
+
+ if ( cl->ps.persistant[PERS_SCORE] >= g_fraglimit.integer ) {
+ LogExit( "Fraglimit hit." );
+ trap_SendServerCommand( -1, va("print \"%s" S_COLOR_WHITE " hit the fraglimit.\n\"",
+ cl->pers.netname ) );
+ return;
+ }
+ }
+ }
+
+ if ( g_gametype.integer >= GT_CTF && g_capturelimit.integer ) {
+
+ if ( level.teamScores[TEAM_RED] >= g_capturelimit.integer ) {
+ trap_SendServerCommand( -1, "print \"Red hit the capturelimit.\n\"" );
+ LogExit( "Capturelimit hit." );
+ return;
+ }
+
+ if ( level.teamScores[TEAM_BLUE] >= g_capturelimit.integer ) {
+ trap_SendServerCommand( -1, "print \"Blue hit the capturelimit.\n\"" );
+ LogExit( "Capturelimit hit." );
+ return;
+ }
+ }
+}
+
+
+
+/*
+========================================================================
+
+FUNCTIONS CALLED EVERY FRAME
+
+========================================================================
+*/
+
+
+/*
+=============
+CheckTournament
+
+Once a frame, check for changes in tournement player state
+=============
+*/
+void CheckTournament( void ) {
+ // check because we run 3 game frames before calling Connect and/or ClientBegin
+ // for clients on a map_restart
+ if ( level.numPlayingClients == 0 ) {
+ return;
+ }
+
+ if ( g_gametype.integer == GT_TOURNAMENT ) {
+
+ // pull in a spectator if needed
+ if ( level.numPlayingClients < 2 ) {
+ AddTournamentPlayer();
+ }
+
+ // if we don't have two players, go back to "waiting for players"
+ if ( level.numPlayingClients != 2 ) {
+ if ( level.warmupTime != -1 ) {
+ level.warmupTime = -1;
+ trap_SetConfigstring( CS_WARMUP, va("%i", level.warmupTime) );
+ G_LogPrintf( "Warmup:\n" );
+ }
+ return;
+ }
+
+ if ( level.warmupTime == 0 ) {
+ return;
+ }
+
+ // if the warmup is changed at the console, restart it
+ if ( g_warmup.modificationCount != level.warmupModificationCount ) {
+ level.warmupModificationCount = g_warmup.modificationCount;
+ level.warmupTime = -1;
+ }
+
+ // if all players have arrived, start the countdown
+ if ( level.warmupTime < 0 ) {
+ if ( level.numPlayingClients == 2 ) {
+ // fudge by -1 to account for extra delays
+ level.warmupTime = level.time + ( g_warmup.integer - 1 ) * 1000;
+ trap_SetConfigstring( CS_WARMUP, va("%i", level.warmupTime) );
+ }
+ return;
+ }
+
+ // if the warmup time has counted down, restart
+ if ( level.time > level.warmupTime ) {
+ level.warmupTime += 10000;
+ trap_Cvar_Set( "g_restarted", "1" );
+ trap_SendConsoleCommand( EXEC_APPEND, "map_restart 0\n" );
+ level.restarted = qtrue;
+ return;
+ }
+ } else if ( g_gametype.integer != GT_SINGLE_PLAYER && level.warmupTime != 0 ) {
+ int counts[TEAM_NUM_TEAMS];
+ qboolean notEnough = qfalse;
+
+ if ( g_gametype.integer > GT_TEAM ) {
+ counts[TEAM_BLUE] = TeamCount( -1, TEAM_BLUE );
+ counts[TEAM_RED] = TeamCount( -1, TEAM_RED );
+
+ if (counts[TEAM_RED] < 1 || counts[TEAM_BLUE] < 1) {
+ notEnough = qtrue;
+ }
+ } else if ( level.numPlayingClients < 2 ) {
+ notEnough = qtrue;
+ }
+
+ if ( notEnough ) {
+ if ( level.warmupTime != -1 ) {
+ level.warmupTime = -1;
+ trap_SetConfigstring( CS_WARMUP, va("%i", level.warmupTime) );
+ G_LogPrintf( "Warmup:\n" );
+ }
+ return; // still waiting for team members
+ }
+
+ if ( level.warmupTime == 0 ) {
+ return;
+ }
+
+ // if the warmup is changed at the console, restart it
+ if ( g_warmup.modificationCount != level.warmupModificationCount ) {
+ level.warmupModificationCount = g_warmup.modificationCount;
+ level.warmupTime = -1;
+ }
+
+ // if all players have arrived, start the countdown
+ if ( level.warmupTime < 0 ) {
+ // fudge by -1 to account for extra delays
+ level.warmupTime = level.time + ( g_warmup.integer - 1 ) * 1000;
+ trap_SetConfigstring( CS_WARMUP, va("%i", level.warmupTime) );
+ return;
+ }
+
+ // if the warmup time has counted down, restart
+ if ( level.time > level.warmupTime ) {
+ level.warmupTime += 10000;
+ trap_Cvar_Set( "g_restarted", "1" );
+ trap_SendConsoleCommand( EXEC_APPEND, "map_restart 0\n" );
+ level.restarted = qtrue;
+ return;
+ }
+ }
+}
+
+
+/*
+==================
+CheckVote
+==================
+*/
+void CheckVote( void ) {
+ if ( level.voteExecuteTime && level.voteExecuteTime < level.time ) {
+ level.voteExecuteTime = 0;
+ trap_SendConsoleCommand( EXEC_APPEND, va("%s\n", level.voteString ) );
+ }
+ if ( !level.voteTime ) {
+ return;
+ }
+ if ( level.time - level.voteTime >= VOTE_TIME ) {
+ trap_SendServerCommand( -1, "print \"Vote failed.\n\"" );
+ } else {
+ // ATVI Q3 1.32 Patch #9, WNF
+ if ( level.voteYes > level.numVotingClients/2 ) {
+ // execute the command, then remove the vote
+ trap_SendServerCommand( -1, "print \"Vote passed.\n\"" );
+ level.voteExecuteTime = level.time + 3000;
+ } else if ( level.voteNo >= level.numVotingClients/2 ) {
+ // same behavior as a timeout
+ trap_SendServerCommand( -1, "print \"Vote failed.\n\"" );
+ } else {
+ // still waiting for a majority
+ return;
+ }
+ }
+ level.voteTime = 0;
+ trap_SetConfigstring( CS_VOTE_TIME, "" );
+
+}
+
+/*
+==================
+PrintTeam
+==================
+*/
+void PrintTeam(int team, char *message) {
+ int i;
+
+ for ( i = 0 ; i < level.maxclients ; i++ ) {
+ if (level.clients[i].sess.sessionTeam != team)
+ continue;
+ trap_SendServerCommand( i, message );
+ }
+}
+
+/*
+==================
+SetLeader
+==================
+*/
+void SetLeader(int team, int client) {
+ int i;
+
+ if ( level.clients[client].pers.connected == CON_DISCONNECTED ) {
+ PrintTeam(team, va("print \"%s is not connected\n\"", level.clients[client].pers.netname) );
+ return;
+ }
+ if (level.clients[client].sess.sessionTeam != team) {
+ PrintTeam(team, va("print \"%s is not on the team anymore\n\"", level.clients[client].pers.netname) );
+ return;
+ }
+ for ( i = 0 ; i < level.maxclients ; i++ ) {
+ if (level.clients[i].sess.sessionTeam != team)
+ continue;
+ if (level.clients[i].sess.teamLeader) {
+ level.clients[i].sess.teamLeader = qfalse;
+ ClientUserinfoChanged(i);
+ }
+ }
+ level.clients[client].sess.teamLeader = qtrue;
+ ClientUserinfoChanged( client );
+ PrintTeam(team, va("print \"%s is the new team leader\n\"", level.clients[client].pers.netname) );
+}
+
+/*
+==================
+CheckTeamLeader
+==================
+*/
+void CheckTeamLeader( int team ) {
+ int i;
+
+ for ( i = 0 ; i < level.maxclients ; i++ ) {
+ if (level.clients[i].sess.sessionTeam != team)
+ continue;
+ if (level.clients[i].sess.teamLeader)
+ break;
+ }
+ if (i >= level.maxclients) {
+ for ( i = 0 ; i < level.maxclients ; i++ ) {
+ if (level.clients[i].sess.sessionTeam != team)
+ continue;
+ if (!(g_entities[i].r.svFlags & SVF_BOT)) {
+ level.clients[i].sess.teamLeader = qtrue;
+ break;
+ }
+ }
+ for ( i = 0 ; i < level.maxclients ; i++ ) {
+ if (level.clients[i].sess.sessionTeam != team)
+ continue;
+ level.clients[i].sess.teamLeader = qtrue;
+ break;
+ }
+ }
+}
+
+/*
+==================
+CheckTeamVote
+==================
+*/
+void CheckTeamVote( int team ) {
+ int cs_offset;
+
+ if ( team == TEAM_RED )
+ cs_offset = 0;
+ else if ( team == TEAM_BLUE )
+ cs_offset = 1;
+ else
+ return;
+
+ if ( !level.teamVoteTime[cs_offset] ) {
+ return;
+ }
+ if ( level.time - level.teamVoteTime[cs_offset] >= VOTE_TIME ) {
+ trap_SendServerCommand( -1, "print \"Team vote failed.\n\"" );
+ } else {
+ if ( level.teamVoteYes[cs_offset] > level.numteamVotingClients[cs_offset]/2 ) {
+ // execute the command, then remove the vote
+ trap_SendServerCommand( -1, "print \"Team vote passed.\n\"" );
+ //
+ if ( !Q_strncmp( "leader", level.teamVoteString[cs_offset], 6) ) {
+ //set the team leader
+ SetLeader(team, atoi(level.teamVoteString[cs_offset] + 7));
+ }
+ else {
+ trap_SendConsoleCommand( EXEC_APPEND, va("%s\n", level.teamVoteString[cs_offset] ) );
+ }
+ } else if ( level.teamVoteNo[cs_offset] >= level.numteamVotingClients[cs_offset]/2 ) {
+ // same behavior as a timeout
+ trap_SendServerCommand( -1, "print \"Team vote failed.\n\"" );
+ } else {
+ // still waiting for a majority
+ return;
+ }
+ }
+ level.teamVoteTime[cs_offset] = 0;
+ trap_SetConfigstring( CS_TEAMVOTE_TIME + cs_offset, "" );
+
+}
+
+
+/*
+==================
+CheckCvars
+==================
+*/
+void CheckCvars( void ) {
+ static int lastMod = -1;
+
+ if ( g_password.modificationCount != lastMod ) {
+ lastMod = g_password.modificationCount;
+ if ( *g_password.string && Q_stricmp( g_password.string, "none" ) ) {
+ trap_Cvar_Set( "g_needpass", "1" );
+ } else {
+ trap_Cvar_Set( "g_needpass", "0" );
+ }
+ }
+}
+
+/*
+=============
+G_RunThink
+
+Runs thinking code for this frame if necessary
+=============
+*/
+void G_RunThink (gentity_t *ent) {
+ float thinktime;
+
+ thinktime = ent->nextthink;
+ if (thinktime <= 0) {
+ return;
+ }
+ if (thinktime > level.time) {
+ return;
+ }
+
+ ent->nextthink = 0;
+ if (!ent->think) {
+ G_Error ( "NULL ent->think");
+ }
+ ent->think (ent);
+}
+
+/*
+================
+G_RunFrame
+
+Advances the non-player objects in the world
+================
+*/
+void G_RunFrame( int levelTime ) {
+ int i;
+ gentity_t *ent;
+ int msec;
+int start, end;
+
+ // if we are waiting for the level to restart, do nothing
+ if ( level.restarted ) {
+ return;
+ }
+
+ level.framenum++;
+ level.previousTime = level.time;
+ level.time = levelTime;
+ msec = level.time - level.previousTime;
+
+ // get any cvar changes
+ G_UpdateCvars();
+
+ //
+ // go through all allocated objects
+ //
+ start = trap_Milliseconds();
+ ent = &g_entities[0];
+ for (i=0 ; i<level.num_entities ; i++, ent++) {
+ if ( !ent->inuse ) {
+ continue;
+ }
+
+ // clear events that are too old
+ if ( level.time - ent->eventTime > EVENT_VALID_MSEC ) {
+ if ( ent->s.event ) {
+ ent->s.event = 0; // &= EV_EVENT_BITS;
+ if ( ent->client ) {
+ ent->client->ps.externalEvent = 0;
+ // predicted events should never be set to zero
+ //ent->client->ps.events[0] = 0;
+ //ent->client->ps.events[1] = 0;
+ }
+ }
+ if ( ent->freeAfterEvent ) {
+ // tempEntities or dropped items completely go away after their event
+ G_FreeEntity( ent );
+ continue;
+ } else if ( ent->unlinkAfterEvent ) {
+ // items that will respawn will hide themselves after their pickup event
+ ent->unlinkAfterEvent = qfalse;
+ trap_UnlinkEntity( ent );
+ }
+ }
+
+ // temporary entities don't think
+ if ( ent->freeAfterEvent ) {
+ continue;
+ }
+
+ if ( !ent->r.linked && ent->neverFree ) {
+ continue;
+ }
+
+ if ( ent->s.eType == ET_MISSILE ) {
+ G_RunMissile( ent );
+ continue;
+ }
+
+ if ( ent->s.eType == ET_ITEM || ent->physicsObject ) {
+ G_RunItem( ent );
+ continue;
+ }
+
+ if ( ent->s.eType == ET_MOVER ) {
+ G_RunMover( ent );
+ continue;
+ }
+
+ if ( i < MAX_CLIENTS ) {
+ G_RunClient( ent );
+ continue;
+ }
+
+ G_RunThink( ent );
+ }
+end = trap_Milliseconds();
+
+start = trap_Milliseconds();
+ // perform final fixups on the players
+ ent = &g_entities[0];
+ for (i=0 ; i < level.maxclients ; i++, ent++ ) {
+ if ( ent->inuse ) {
+ ClientEndFrame( ent );
+ }
+ }
+end = trap_Milliseconds();
+
+ // see if it is time to do a tournement restart
+ CheckTournament();
+
+ // see if it is time to end the level
+ CheckExitRules();
+
+ // update to team status?
+ CheckTeamStatus();
+
+ // cancel vote if timed out
+ CheckVote();
+
+ // check team votes
+ CheckTeamVote( TEAM_RED );
+ CheckTeamVote( TEAM_BLUE );
+
+ // for tracking changes
+ CheckCvars();
+
+ if (g_listEntity.integer) {
+ for (i = 0; i < MAX_GENTITIES; i++) {
+ G_Printf("%4i: %s\n", i, g_entities[i].classname);
+ }
+ trap_Cvar_Set("g_listEntity", "0");
+ }
+}
diff --git a/code/game/g_mem.c b/code/game/g_mem.c
new file mode 100755
index 0000000..5c768f4
--- /dev/null
+++ b/code/game/g_mem.c
@@ -0,0 +1,61 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+//
+// g_mem.c
+//
+
+
+#include "g_local.h"
+
+
+#define POOLSIZE (256 * 1024)
+
+static char memoryPool[POOLSIZE];
+static int allocPoint;
+
+void *G_Alloc( int size ) {
+ char *p;
+
+ if ( g_debugAlloc.integer ) {
+ G_Printf( "G_Alloc of %i bytes (%i left)\n", size, POOLSIZE - allocPoint - ( ( size + 31 ) & ~31 ) );
+ }
+
+ if ( allocPoint + size > POOLSIZE ) {
+ G_Error( "G_Alloc: failed on allocation of %i bytes\n", size ); // bk010103 - was %u, but is signed
+ return NULL;
+ }
+
+ p = &memoryPool[allocPoint];
+
+ allocPoint += ( size + 31 ) & ~31;
+
+ return p;
+}
+
+void G_InitMemory( void ) {
+ allocPoint = 0;
+}
+
+void Svcmd_GameMem_f( void ) {
+ G_Printf( "Game memory status: %i out of %i bytes allocated\n", allocPoint, POOLSIZE );
+}
diff --git a/code/game/g_misc.c b/code/game/g_misc.c
new file mode 100755
index 0000000..2328461
--- /dev/null
+++ b/code/game/g_misc.c
@@ -0,0 +1,482 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// g_misc.c
+
+#include "g_local.h"
+
+
+/*QUAKED func_group (0 0 0) ?
+Used to group brushes together just for editor convenience. They are turned into normal brushes by the utilities.
+*/
+
+
+/*QUAKED info_camp (0 0.5 0) (-4 -4 -4) (4 4 4)
+Used as a positional target for calculations in the utilities (spotlights, etc), but removed during gameplay.
+*/
+void SP_info_camp( gentity_t *self ) {
+ G_SetOrigin( self, self->s.origin );
+}
+
+
+/*QUAKED info_null (0 0.5 0) (-4 -4 -4) (4 4 4)
+Used as a positional target for calculations in the utilities (spotlights, etc), but removed during gameplay.
+*/
+void SP_info_null( gentity_t *self ) {
+ G_FreeEntity( self );
+}
+
+
+/*QUAKED info_notnull (0 0.5 0) (-4 -4 -4) (4 4 4)
+Used as a positional target for in-game calculation, like jumppad targets.
+target_position does the same thing
+*/
+void SP_info_notnull( gentity_t *self ){
+ G_SetOrigin( self, self->s.origin );
+}
+
+
+/*QUAKED light (0 1 0) (-8 -8 -8) (8 8 8) linear
+Non-displayed light.
+"light" overrides the default 300 intensity.
+Linear checbox gives linear falloff instead of inverse square
+Lights pointed at a target will be spotlights.
+"radius" overrides the default 64 unit radius of a spotlight at the target point.
+*/
+void SP_light( gentity_t *self ) {
+ G_FreeEntity( self );
+}
+
+
+
+/*
+=================================================================================
+
+TELEPORTERS
+
+=================================================================================
+*/
+
+void TeleportPlayer( gentity_t *player, vec3_t origin, vec3_t angles ) {
+ gentity_t *tent;
+
+ // use temp events at source and destination to prevent the effect
+ // from getting dropped by a second player event
+ if ( player->client->sess.sessionTeam != TEAM_SPECTATOR ) {
+ tent = G_TempEntity( player->client->ps.origin, EV_PLAYER_TELEPORT_OUT );
+ tent->s.clientNum = player->s.clientNum;
+
+ tent = G_TempEntity( origin, EV_PLAYER_TELEPORT_IN );
+ tent->s.clientNum = player->s.clientNum;
+ }
+
+ // unlink to make sure it can't possibly interfere with G_KillBox
+ trap_UnlinkEntity (player);
+
+ VectorCopy ( origin, player->client->ps.origin );
+ player->client->ps.origin[2] += 1;
+
+ // spit the player out
+ AngleVectors( angles, player->client->ps.velocity, NULL, NULL );
+ VectorScale( player->client->ps.velocity, 400, player->client->ps.velocity );
+ player->client->ps.pm_time = 160; // hold time
+ player->client->ps.pm_flags |= PMF_TIME_KNOCKBACK;
+
+ // toggle the teleport bit so the client knows to not lerp
+ player->client->ps.eFlags ^= EF_TELEPORT_BIT;
+
+ // set angles
+ SetClientViewAngle( player, angles );
+
+ // kill anything at the destination
+ if ( player->client->sess.sessionTeam != TEAM_SPECTATOR ) {
+ G_KillBox (player);
+ }
+
+ // save results of pmove
+ BG_PlayerStateToEntityState( &player->client->ps, &player->s, qtrue );
+
+ // use the precise origin for linking
+ VectorCopy( player->client->ps.origin, player->r.currentOrigin );
+
+ if ( player->client->sess.sessionTeam != TEAM_SPECTATOR ) {
+ trap_LinkEntity (player);
+ }
+}
+
+
+/*QUAKED misc_teleporter_dest (1 0 0) (-32 -32 -24) (32 32 -16)
+Point teleporters at these.
+Now that we don't have teleport destination pads, this is just
+an info_notnull
+*/
+void SP_misc_teleporter_dest( gentity_t *ent ) {
+}
+
+
+//===========================================================
+
+/*QUAKED misc_model (1 0 0) (-16 -16 -16) (16 16 16)
+"model" arbitrary .md3 file to display
+*/
+void SP_misc_model( gentity_t *ent ) {
+
+#if 0
+ ent->s.modelindex = G_ModelIndex( ent->model );
+ VectorSet (ent->mins, -16, -16, -16);
+ VectorSet (ent->maxs, 16, 16, 16);
+ trap_LinkEntity (ent);
+
+ G_SetOrigin( ent, ent->s.origin );
+ VectorCopy( ent->s.angles, ent->s.apos.trBase );
+#else
+ G_FreeEntity( ent );
+#endif
+}
+
+//===========================================================
+
+void locateCamera( gentity_t *ent ) {
+ vec3_t dir;
+ gentity_t *target;
+ gentity_t *owner;
+
+ owner = G_PickTarget( ent->target );
+ if ( !owner ) {
+ G_Printf( "Couldn't find target for misc_partal_surface\n" );
+ G_FreeEntity( ent );
+ return;
+ }
+ ent->r.ownerNum = owner->s.number;
+
+ // frame holds the rotate speed
+ if ( owner->spawnflags & 1 ) {
+ ent->s.frame = 25;
+ } else if ( owner->spawnflags & 2 ) {
+ ent->s.frame = 75;
+ }
+
+ // swing camera ?
+ if ( owner->spawnflags & 4 ) {
+ // set to 0 for no rotation at all
+ ent->s.powerups = 0;
+ }
+ else {
+ ent->s.powerups = 1;
+ }
+
+ // clientNum holds the rotate offset
+ ent->s.clientNum = owner->s.clientNum;
+
+ VectorCopy( owner->s.origin, ent->s.origin2 );
+
+ // see if the portal_camera has a target
+ target = G_PickTarget( owner->target );
+ if ( target ) {
+ VectorSubtract( target->s.origin, owner->s.origin, dir );
+ VectorNormalize( dir );
+ } else {
+ G_SetMovedir( owner->s.angles, dir );
+ }
+
+ ent->s.eventParm = DirToByte( dir );
+}
+
+/*QUAKED misc_portal_surface (0 0 1) (-8 -8 -8) (8 8 8)
+The portal surface nearest this entity will show a view from the targeted misc_portal_camera, or a mirror view if untargeted.
+This must be within 64 world units of the surface!
+*/
+void SP_misc_portal_surface(gentity_t *ent) {
+ VectorClear( ent->r.mins );
+ VectorClear( ent->r.maxs );
+ trap_LinkEntity (ent);
+
+ ent->r.svFlags = SVF_PORTAL;
+ ent->s.eType = ET_PORTAL;
+
+ if ( !ent->target ) {
+ VectorCopy( ent->s.origin, ent->s.origin2 );
+ } else {
+ ent->think = locateCamera;
+ ent->nextthink = level.time + 100;
+ }
+}
+
+/*QUAKED misc_portal_camera (0 0 1) (-8 -8 -8) (8 8 8) slowrotate fastrotate noswing
+The target for a misc_portal_director. You can set either angles or target another entity to determine the direction of view.
+"roll" an angle modifier to orient the camera around the target vector;
+*/
+void SP_misc_portal_camera(gentity_t *ent) {
+ float roll;
+
+ VectorClear( ent->r.mins );
+ VectorClear( ent->r.maxs );
+ trap_LinkEntity (ent);
+
+ G_SpawnFloat( "roll", "0", &roll );
+
+ ent->s.clientNum = roll/360.0 * 256;
+}
+
+/*
+======================================================================
+
+ SHOOTERS
+
+======================================================================
+*/
+
+void Use_Shooter( gentity_t *ent, gentity_t *other, gentity_t *activator ) {
+ vec3_t dir;
+ float deg;
+ vec3_t up, right;
+
+ // see if we have a target
+ if ( ent->enemy ) {
+ VectorSubtract( ent->enemy->r.currentOrigin, ent->s.origin, dir );
+ VectorNormalize( dir );
+ } else {
+ VectorCopy( ent->movedir, dir );
+ }
+
+ // randomize a bit
+ PerpendicularVector( up, dir );
+ CrossProduct( up, dir, right );
+
+ deg = crandom() * ent->random;
+ VectorMA( dir, deg, up, dir );
+
+ deg = crandom() * ent->random;
+ VectorMA( dir, deg, right, dir );
+
+ VectorNormalize( dir );
+
+ switch ( ent->s.weapon ) {
+ case WP_GRENADE_LAUNCHER:
+ fire_grenade( ent, ent->s.origin, dir );
+ break;
+ case WP_ROCKET_LAUNCHER:
+ fire_rocket( ent, ent->s.origin, dir );
+ break;
+ case WP_PLASMAGUN:
+ fire_plasma( ent, ent->s.origin, dir );
+ break;
+ }
+
+ G_AddEvent( ent, EV_FIRE_WEAPON, 0 );
+}
+
+
+static void InitShooter_Finish( gentity_t *ent ) {
+ ent->enemy = G_PickTarget( ent->target );
+ ent->think = 0;
+ ent->nextthink = 0;
+}
+
+void InitShooter( gentity_t *ent, int weapon ) {
+ ent->use = Use_Shooter;
+ ent->s.weapon = weapon;
+
+ RegisterItem( BG_FindItemForWeapon( weapon ) );
+
+ G_SetMovedir( ent->s.angles, ent->movedir );
+
+ if ( !ent->random ) {
+ ent->random = 1.0;
+ }
+ ent->random = sin( M_PI * ent->random / 180 );
+ // target might be a moving object, so we can't set movedir for it
+ if ( ent->target ) {
+ ent->think = InitShooter_Finish;
+ ent->nextthink = level.time + 500;
+ }
+ trap_LinkEntity( ent );
+}
+
+/*QUAKED shooter_rocket (1 0 0) (-16 -16 -16) (16 16 16)
+Fires at either the target or the current direction.
+"random" the number of degrees of deviance from the taget. (1.0 default)
+*/
+void SP_shooter_rocket( gentity_t *ent ) {
+ InitShooter( ent, WP_ROCKET_LAUNCHER );
+}
+
+/*QUAKED shooter_plasma (1 0 0) (-16 -16 -16) (16 16 16)
+Fires at either the target or the current direction.
+"random" is the number of degrees of deviance from the taget. (1.0 default)
+*/
+void SP_shooter_plasma( gentity_t *ent ) {
+ InitShooter( ent, WP_PLASMAGUN);
+}
+
+/*QUAKED shooter_grenade (1 0 0) (-16 -16 -16) (16 16 16)
+Fires at either the target or the current direction.
+"random" is the number of degrees of deviance from the taget. (1.0 default)
+*/
+void SP_shooter_grenade( gentity_t *ent ) {
+ InitShooter( ent, WP_GRENADE_LAUNCHER);
+}
+
+
+#ifdef MISSIONPACK
+static void PortalDie (gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod) {
+ G_FreeEntity( self );
+ //FIXME do something more interesting
+}
+
+
+void DropPortalDestination( gentity_t *player ) {
+ gentity_t *ent;
+ vec3_t snapped;
+
+ // create the portal destination
+ ent = G_Spawn();
+ ent->s.modelindex = G_ModelIndex( "models/powerups/teleporter/tele_exit.md3" );
+
+ VectorCopy( player->s.pos.trBase, snapped );
+ SnapVector( snapped );
+ G_SetOrigin( ent, snapped );
+ VectorCopy( player->r.mins, ent->r.mins );
+ VectorCopy( player->r.maxs, ent->r.maxs );
+
+ ent->classname = "hi_portal destination";
+ ent->s.pos.trType = TR_STATIONARY;
+
+ ent->r.contents = CONTENTS_CORPSE;
+ ent->takedamage = qtrue;
+ ent->health = 200;
+ ent->die = PortalDie;
+
+ VectorCopy( player->s.apos.trBase, ent->s.angles );
+
+ ent->think = G_FreeEntity;
+ ent->nextthink = level.time + 2 * 60 * 1000;
+
+ trap_LinkEntity( ent );
+
+ player->client->portalID = ++level.portalSequence;
+ ent->count = player->client->portalID;
+
+ // give the item back so they can drop the source now
+ player->client->ps.stats[STAT_HOLDABLE_ITEM] = BG_FindItem( "Portal" ) - bg_itemlist;
+}
+
+
+static void PortalTouch( gentity_t *self, gentity_t *other, trace_t *trace) {
+ gentity_t *destination;
+
+ // see if we will even let other try to use it
+ if( other->health <= 0 ) {
+ return;
+ }
+ if( !other->client ) {
+ return;
+ }
+// if( other->client->ps.persistant[PERS_TEAM] != self->spawnflags ) {
+// return;
+// }
+
+ if ( other->client->ps.powerups[PW_NEUTRALFLAG] ) { // only happens in One Flag CTF
+ Drop_Item( other, BG_FindItemForPowerup( PW_NEUTRALFLAG ), 0 );
+ other->client->ps.powerups[PW_NEUTRALFLAG] = 0;
+ }
+ else if ( other->client->ps.powerups[PW_REDFLAG] ) { // only happens in standard CTF
+ Drop_Item( other, BG_FindItemForPowerup( PW_REDFLAG ), 0 );
+ other->client->ps.powerups[PW_REDFLAG] = 0;
+ }
+ else if ( other->client->ps.powerups[PW_BLUEFLAG] ) { // only happens in standard CTF
+ Drop_Item( other, BG_FindItemForPowerup( PW_BLUEFLAG ), 0 );
+ other->client->ps.powerups[PW_BLUEFLAG] = 0;
+ }
+
+ // find the destination
+ destination = NULL;
+ while( (destination = G_Find(destination, FOFS(classname), "hi_portal destination")) != NULL ) {
+ if( destination->count == self->count ) {
+ break;
+ }
+ }
+
+ // if there is not one, die!
+ if( !destination ) {
+ if( self->pos1[0] || self->pos1[1] || self->pos1[2] ) {
+ TeleportPlayer( other, self->pos1, self->s.angles );
+ }
+ G_Damage( other, other, other, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, MOD_TELEFRAG );
+ return;
+ }
+
+ TeleportPlayer( other, destination->s.pos.trBase, destination->s.angles );
+}
+
+
+static void PortalEnable( gentity_t *self ) {
+ self->touch = PortalTouch;
+ self->think = G_FreeEntity;
+ self->nextthink = level.time + 2 * 60 * 1000;
+}
+
+
+void DropPortalSource( gentity_t *player ) {
+ gentity_t *ent;
+ gentity_t *destination;
+ vec3_t snapped;
+
+ // create the portal source
+ ent = G_Spawn();
+ ent->s.modelindex = G_ModelIndex( "models/powerups/teleporter/tele_enter.md3" );
+
+ VectorCopy( player->s.pos.trBase, snapped );
+ SnapVector( snapped );
+ G_SetOrigin( ent, snapped );
+ VectorCopy( player->r.mins, ent->r.mins );
+ VectorCopy( player->r.maxs, ent->r.maxs );
+
+ ent->classname = "hi_portal source";
+ ent->s.pos.trType = TR_STATIONARY;
+
+ ent->r.contents = CONTENTS_CORPSE | CONTENTS_TRIGGER;
+ ent->takedamage = qtrue;
+ ent->health = 200;
+ ent->die = PortalDie;
+
+ trap_LinkEntity( ent );
+
+ ent->count = player->client->portalID;
+ player->client->portalID = 0;
+
+// ent->spawnflags = player->client->ps.persistant[PERS_TEAM];
+
+ ent->nextthink = level.time + 1000;
+ ent->think = PortalEnable;
+
+ // find the destination
+ destination = NULL;
+ while( (destination = G_Find(destination, FOFS(classname), "hi_portal destination")) != NULL ) {
+ if( destination->count == ent->count ) {
+ VectorCopy( destination->s.pos.trBase, ent->pos1 );
+ break;
+ }
+ }
+
+}
+#endif
diff --git a/code/game/g_missile.c b/code/game/g_missile.c
new file mode 100755
index 0000000..05922a5
--- /dev/null
+++ b/code/game/g_missile.c
@@ -0,0 +1,808 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#include "g_local.h"
+
+#define MISSILE_PRESTEP_TIME 50
+
+/*
+================
+G_BounceMissile
+
+================
+*/
+void G_BounceMissile( gentity_t *ent, trace_t *trace ) {
+ vec3_t velocity;
+ float dot;
+ int hitTime;
+
+ // reflect the velocity on the trace plane
+ hitTime = level.previousTime + ( level.time - level.previousTime ) * trace->fraction;
+ BG_EvaluateTrajectoryDelta( &ent->s.pos, hitTime, velocity );
+ dot = DotProduct( velocity, trace->plane.normal );
+ VectorMA( velocity, -2*dot, trace->plane.normal, ent->s.pos.trDelta );
+
+ if ( ent->s.eFlags & EF_BOUNCE_HALF ) {
+ VectorScale( ent->s.pos.trDelta, 0.65, ent->s.pos.trDelta );
+ // check for stop
+ if ( trace->plane.normal[2] > 0.2 && VectorLength( ent->s.pos.trDelta ) < 40 ) {
+ G_SetOrigin( ent, trace->endpos );
+ return;
+ }
+ }
+
+ VectorAdd( ent->r.currentOrigin, trace->plane.normal, ent->r.currentOrigin);
+ VectorCopy( ent->r.currentOrigin, ent->s.pos.trBase );
+ ent->s.pos.trTime = level.time;
+}
+
+
+/*
+================
+G_ExplodeMissile
+
+Explode a missile without an impact
+================
+*/
+void G_ExplodeMissile( gentity_t *ent ) {
+ vec3_t dir;
+ vec3_t origin;
+
+ BG_EvaluateTrajectory( &ent->s.pos, level.time, origin );
+ SnapVector( origin );
+ G_SetOrigin( ent, origin );
+
+ // we don't have a valid direction, so just point straight up
+ dir[0] = dir[1] = 0;
+ dir[2] = 1;
+
+ ent->s.eType = ET_GENERAL;
+ G_AddEvent( ent, EV_MISSILE_MISS, DirToByte( dir ) );
+
+ ent->freeAfterEvent = qtrue;
+
+ // splash damage
+ if ( ent->splashDamage ) {
+ if( G_RadiusDamage( ent->r.currentOrigin, ent->parent, ent->splashDamage, ent->splashRadius, ent
+ , ent->splashMethodOfDeath ) ) {
+ g_entities[ent->r.ownerNum].client->accuracy_hits++;
+ }
+ }
+
+ trap_LinkEntity( ent );
+}
+
+
+#ifdef MISSIONPACK
+/*
+================
+ProximityMine_Explode
+================
+*/
+static void ProximityMine_Explode( gentity_t *mine ) {
+ G_ExplodeMissile( mine );
+ // if the prox mine has a trigger free it
+ if (mine->activator) {
+ G_FreeEntity(mine->activator);
+ mine->activator = NULL;
+ }
+}
+
+/*
+================
+ProximityMine_Die
+================
+*/
+static void ProximityMine_Die( gentity_t *ent, gentity_t *inflictor, gentity_t *attacker, int damage, int mod ) {
+ ent->think = ProximityMine_Explode;
+ ent->nextthink = level.time + 1;
+}
+
+/*
+================
+ProximityMine_Trigger
+================
+*/
+void ProximityMine_Trigger( gentity_t *trigger, gentity_t *other, trace_t *trace ) {
+ vec3_t v;
+ gentity_t *mine;
+
+ if( !other->client ) {
+ return;
+ }
+
+ // trigger is a cube, do a distance test now to act as if it's a sphere
+ VectorSubtract( trigger->s.pos.trBase, other->s.pos.trBase, v );
+ if( VectorLength( v ) > trigger->parent->splashRadius ) {
+ return;
+ }
+
+
+ if ( g_gametype.integer >= GT_TEAM ) {
+ // don't trigger same team mines
+ if (trigger->parent->s.generic1 == other->client->sess.sessionTeam) {
+ return;
+ }
+ }
+
+ // ok, now check for ability to damage so we don't get triggered thru walls, closed doors, etc...
+ if( !CanDamage( other, trigger->s.pos.trBase ) ) {
+ return;
+ }
+
+ // trigger the mine!
+ mine = trigger->parent;
+ mine->s.loopSound = 0;
+ G_AddEvent( mine, EV_PROXIMITY_MINE_TRIGGER, 0 );
+ mine->nextthink = level.time + 500;
+
+ G_FreeEntity( trigger );
+}
+
+/*
+================
+ProximityMine_Activate
+================
+*/
+static void ProximityMine_Activate( gentity_t *ent ) {
+ gentity_t *trigger;
+ float r;
+
+ ent->think = ProximityMine_Explode;
+ ent->nextthink = level.time + g_proxMineTimeout.integer;
+
+ ent->takedamage = qtrue;
+ ent->health = 1;
+ ent->die = ProximityMine_Die;
+
+ ent->s.loopSound = G_SoundIndex( "sound/weapons/proxmine/wstbtick.wav" );
+
+ // build the proximity trigger
+ trigger = G_Spawn ();
+
+ trigger->classname = "proxmine_trigger";
+
+ r = ent->splashRadius;
+ VectorSet( trigger->r.mins, -r, -r, -r );
+ VectorSet( trigger->r.maxs, r, r, r );
+
+ G_SetOrigin( trigger, ent->s.pos.trBase );
+
+ trigger->parent = ent;
+ trigger->r.contents = CONTENTS_TRIGGER;
+ trigger->touch = ProximityMine_Trigger;
+
+ trap_LinkEntity (trigger);
+
+ // set pointer to trigger so the entity can be freed when the mine explodes
+ ent->activator = trigger;
+}
+
+/*
+================
+ProximityMine_ExplodeOnPlayer
+================
+*/
+static void ProximityMine_ExplodeOnPlayer( gentity_t *mine ) {
+ gentity_t *player;
+
+ player = mine->enemy;
+ player->client->ps.eFlags &= ~EF_TICKING;
+
+ if ( player->client->invulnerabilityTime > level.time ) {
+ G_Damage( player, mine->parent, mine->parent, vec3_origin, mine->s.origin, 1000, DAMAGE_NO_KNOCKBACK, MOD_JUICED );
+ player->client->invulnerabilityTime = 0;
+ G_TempEntity( player->client->ps.origin, EV_JUICED );
+ }
+ else {
+ G_SetOrigin( mine, player->s.pos.trBase );
+ // make sure the explosion gets to the client
+ mine->r.svFlags &= ~SVF_NOCLIENT;
+ mine->splashMethodOfDeath = MOD_PROXIMITY_MINE;
+ G_ExplodeMissile( mine );
+ }
+}
+
+/*
+================
+ProximityMine_Player
+================
+*/
+static void ProximityMine_Player( gentity_t *mine, gentity_t *player ) {
+ if( mine->s.eFlags & EF_NODRAW ) {
+ return;
+ }
+
+ G_AddEvent( mine, EV_PROXIMITY_MINE_STICK, 0 );
+
+ if( player->s.eFlags & EF_TICKING ) {
+ player->activator->splashDamage += mine->splashDamage;
+ player->activator->splashRadius *= 1.50;
+ mine->think = G_FreeEntity;
+ mine->nextthink = level.time;
+ return;
+ }
+
+ player->client->ps.eFlags |= EF_TICKING;
+ player->activator = mine;
+
+ mine->s.eFlags |= EF_NODRAW;
+ mine->r.svFlags |= SVF_NOCLIENT;
+ mine->s.pos.trType = TR_LINEAR;
+ VectorClear( mine->s.pos.trDelta );
+
+ mine->enemy = player;
+ mine->think = ProximityMine_ExplodeOnPlayer;
+ if ( player->client->invulnerabilityTime > level.time ) {
+ mine->nextthink = level.time + 2 * 1000;
+ }
+ else {
+ mine->nextthink = level.time + 10 * 1000;
+ }
+}
+#endif
+
+/*
+================
+G_MissileImpact
+================
+*/
+void G_MissileImpact( gentity_t *ent, trace_t *trace ) {
+ gentity_t *other;
+ qboolean hitClient = qfalse;
+#ifdef MISSIONPACK
+ vec3_t forward, impactpoint, bouncedir;
+ int eFlags;
+#endif
+ other = &g_entities[trace->entityNum];
+
+ // check for bounce
+ if ( !other->takedamage &&
+ ( ent->s.eFlags & ( EF_BOUNCE | EF_BOUNCE_HALF ) ) ) {
+ G_BounceMissile( ent, trace );
+ G_AddEvent( ent, EV_GRENADE_BOUNCE, 0 );
+ return;
+ }
+
+#ifdef MISSIONPACK
+ if ( other->takedamage ) {
+ if ( ent->s.weapon != WP_PROX_LAUNCHER ) {
+ if ( other->client && other->client->invulnerabilityTime > level.time ) {
+ //
+ VectorCopy( ent->s.pos.trDelta, forward );
+ VectorNormalize( forward );
+ if (G_InvulnerabilityEffect( other, forward, ent->s.pos.trBase, impactpoint, bouncedir )) {
+ VectorCopy( bouncedir, trace->plane.normal );
+ eFlags = ent->s.eFlags & EF_BOUNCE_HALF;
+ ent->s.eFlags &= ~EF_BOUNCE_HALF;
+ G_BounceMissile( ent, trace );
+ ent->s.eFlags |= eFlags;
+ }
+ ent->target_ent = other;
+ return;
+ }
+ }
+ }
+#endif
+ // impact damage
+ if (other->takedamage) {
+ // FIXME: wrong damage direction?
+ if ( ent->damage ) {
+ vec3_t velocity;
+
+ if( LogAccuracyHit( other, &g_entities[ent->r.ownerNum] ) ) {
+ g_entities[ent->r.ownerNum].client->accuracy_hits++;
+ hitClient = qtrue;
+ }
+ BG_EvaluateTrajectoryDelta( &ent->s.pos, level.time, velocity );
+ if ( VectorLength( velocity ) == 0 ) {
+ velocity[2] = 1; // stepped on a grenade
+ }
+ G_Damage (other, ent, &g_entities[ent->r.ownerNum], velocity,
+ ent->s.origin, ent->damage,
+ 0, ent->methodOfDeath);
+ }
+ }
+
+#ifdef MISSIONPACK
+ if( ent->s.weapon == WP_PROX_LAUNCHER ) {
+ if( ent->s.pos.trType != TR_GRAVITY ) {
+ return;
+ }
+
+ // if it's a player, stick it on to them (flag them and remove this entity)
+ if( other->s.eType == ET_PLAYER && other->health > 0 ) {
+ ProximityMine_Player( ent, other );
+ return;
+ }
+
+ SnapVectorTowards( trace->endpos, ent->s.pos.trBase );
+ G_SetOrigin( ent, trace->endpos );
+ ent->s.pos.trType = TR_STATIONARY;
+ VectorClear( ent->s.pos.trDelta );
+
+ G_AddEvent( ent, EV_PROXIMITY_MINE_STICK, trace->surfaceFlags );
+
+ ent->think = ProximityMine_Activate;
+ ent->nextthink = level.time + 2000;
+
+ vectoangles( trace->plane.normal, ent->s.angles );
+ ent->s.angles[0] += 90;
+
+ // link the prox mine to the other entity
+ ent->enemy = other;
+ ent->die = ProximityMine_Die;
+ VectorCopy(trace->plane.normal, ent->movedir);
+ VectorSet(ent->r.mins, -4, -4, -4);
+ VectorSet(ent->r.maxs, 4, 4, 4);
+ trap_LinkEntity(ent);
+
+ return;
+ }
+#endif
+
+ if (!strcmp(ent->classname, "hook")) {
+ gentity_t *nent;
+ vec3_t v;
+
+ nent = G_Spawn();
+ if ( other->takedamage && other->client ) {
+
+ G_AddEvent( nent, EV_MISSILE_HIT, DirToByte( trace->plane.normal ) );
+ nent->s.otherEntityNum = other->s.number;
+
+ ent->enemy = other;
+
+ v[0] = other->r.currentOrigin[0] + (other->r.mins[0] + other->r.maxs[0]) * 0.5;
+ v[1] = other->r.currentOrigin[1] + (other->r.mins[1] + other->r.maxs[1]) * 0.5;
+ v[2] = other->r.currentOrigin[2] + (other->r.mins[2] + other->r.maxs[2]) * 0.5;
+
+ SnapVectorTowards( v, ent->s.pos.trBase ); // save net bandwidth
+ } else {
+ VectorCopy(trace->endpos, v);
+ G_AddEvent( nent, EV_MISSILE_MISS, DirToByte( trace->plane.normal ) );
+ ent->enemy = NULL;
+ }
+
+ SnapVectorTowards( v, ent->s.pos.trBase ); // save net bandwidth
+
+ nent->freeAfterEvent = qtrue;
+ // change over to a normal entity right at the point of impact
+ nent->s.eType = ET_GENERAL;
+ ent->s.eType = ET_GRAPPLE;
+
+ G_SetOrigin( ent, v );
+ G_SetOrigin( nent, v );
+
+ ent->think = Weapon_HookThink;
+ ent->nextthink = level.time + FRAMETIME;
+
+ ent->parent->client->ps.pm_flags |= PMF_GRAPPLE_PULL;
+ VectorCopy( ent->r.currentOrigin, ent->parent->client->ps.grapplePoint);
+
+ trap_LinkEntity( ent );
+ trap_LinkEntity( nent );
+
+ return;
+ }
+
+ // is it cheaper in bandwidth to just remove this ent and create a new
+ // one, rather than changing the missile into the explosion?
+
+ if ( other->takedamage && other->client ) {
+ G_AddEvent( ent, EV_MISSILE_HIT, DirToByte( trace->plane.normal ) );
+ ent->s.otherEntityNum = other->s.number;
+ } else if( trace->surfaceFlags & SURF_METALSTEPS ) {
+ G_AddEvent( ent, EV_MISSILE_MISS_METAL, DirToByte( trace->plane.normal ) );
+ } else {
+ G_AddEvent( ent, EV_MISSILE_MISS, DirToByte( trace->plane.normal ) );
+ }
+
+ ent->freeAfterEvent = qtrue;
+
+ // change over to a normal entity right at the point of impact
+ ent->s.eType = ET_GENERAL;
+
+ SnapVectorTowards( trace->endpos, ent->s.pos.trBase ); // save net bandwidth
+
+ G_SetOrigin( ent, trace->endpos );
+
+ // splash damage (doesn't apply to person directly hit)
+ if ( ent->splashDamage ) {
+ if( G_RadiusDamage( trace->endpos, ent->parent, ent->splashDamage, ent->splashRadius,
+ other, ent->splashMethodOfDeath ) ) {
+ if( !hitClient ) {
+ g_entities[ent->r.ownerNum].client->accuracy_hits++;
+ }
+ }
+ }
+
+ trap_LinkEntity( ent );
+}
+
+/*
+================
+G_RunMissile
+================
+*/
+void G_RunMissile( gentity_t *ent ) {
+ vec3_t origin;
+ trace_t tr;
+ int passent;
+
+ // get current position
+ BG_EvaluateTrajectory( &ent->s.pos, level.time, origin );
+
+ // if this missile bounced off an invulnerability sphere
+ if ( ent->target_ent ) {
+ passent = ent->target_ent->s.number;
+ }
+#ifdef MISSIONPACK
+ // prox mines that left the owner bbox will attach to anything, even the owner
+ else if (ent->s.weapon == WP_PROX_LAUNCHER && ent->count) {
+ passent = ENTITYNUM_NONE;
+ }
+#endif
+ else {
+ // ignore interactions with the missile owner
+ passent = ent->r.ownerNum;
+ }
+ // trace a line from the previous position to the current position
+ trap_Trace( &tr, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, origin, passent, ent->clipmask );
+
+ if ( tr.startsolid || tr.allsolid ) {
+ // make sure the tr.entityNum is set to the entity we're stuck in
+ trap_Trace( &tr, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, ent->r.currentOrigin, passent, ent->clipmask );
+ tr.fraction = 0;
+ }
+ else {
+ VectorCopy( tr.endpos, ent->r.currentOrigin );
+ }
+
+ trap_LinkEntity( ent );
+
+ if ( tr.fraction != 1 ) {
+ // never explode or bounce on sky
+ if ( tr.surfaceFlags & SURF_NOIMPACT ) {
+ // If grapple, reset owner
+ if (ent->parent && ent->parent->client && ent->parent->client->hook == ent) {
+ ent->parent->client->hook = NULL;
+ }
+ G_FreeEntity( ent );
+ return;
+ }
+ G_MissileImpact( ent, &tr );
+ if ( ent->s.eType != ET_MISSILE ) {
+ return; // exploded
+ }
+ }
+#ifdef MISSIONPACK
+ // if the prox mine wasn't yet outside the player body
+ if (ent->s.weapon == WP_PROX_LAUNCHER && !ent->count) {
+ // check if the prox mine is outside the owner bbox
+ trap_Trace( &tr, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, ent->r.currentOrigin, ENTITYNUM_NONE, ent->clipmask );
+ if (!tr.startsolid || tr.entityNum != ent->r.ownerNum) {
+ ent->count = 1;
+ }
+ }
+#endif
+ // check think function after bouncing
+ G_RunThink( ent );
+}
+
+
+//=============================================================================
+
+/*
+=================
+fire_plasma
+
+=================
+*/
+gentity_t *fire_plasma (gentity_t *self, vec3_t start, vec3_t dir) {
+ gentity_t *bolt;
+
+ VectorNormalize (dir);
+
+ bolt = G_Spawn();
+ bolt->classname = "plasma";
+ bolt->nextthink = level.time + 10000;
+ bolt->think = G_ExplodeMissile;
+ bolt->s.eType = ET_MISSILE;
+ bolt->r.svFlags = SVF_USE_CURRENT_ORIGIN;
+ bolt->s.weapon = WP_PLASMAGUN;
+ bolt->r.ownerNum = self->s.number;
+ bolt->parent = self;
+ bolt->damage = 20;
+ bolt->splashDamage = 15;
+ bolt->splashRadius = 20;
+ bolt->methodOfDeath = MOD_PLASMA;
+ bolt->splashMethodOfDeath = MOD_PLASMA_SPLASH;
+ bolt->clipmask = MASK_SHOT;
+ bolt->target_ent = NULL;
+
+ bolt->s.pos.trType = TR_LINEAR;
+ bolt->s.pos.trTime = level.time - MISSILE_PRESTEP_TIME; // move a bit on the very first frame
+ VectorCopy( start, bolt->s.pos.trBase );
+ VectorScale( dir, 2000, bolt->s.pos.trDelta );
+ SnapVector( bolt->s.pos.trDelta ); // save net bandwidth
+
+ VectorCopy (start, bolt->r.currentOrigin);
+
+ return bolt;
+}
+
+//=============================================================================
+
+
+/*
+=================
+fire_grenade
+=================
+*/
+gentity_t *fire_grenade (gentity_t *self, vec3_t start, vec3_t dir) {
+ gentity_t *bolt;
+
+ VectorNormalize (dir);
+
+ bolt = G_Spawn();
+ bolt->classname = "grenade";
+ bolt->nextthink = level.time + 2500;
+ bolt->think = G_ExplodeMissile;
+ bolt->s.eType = ET_MISSILE;
+ bolt->r.svFlags = SVF_USE_CURRENT_ORIGIN;
+ bolt->s.weapon = WP_GRENADE_LAUNCHER;
+ bolt->s.eFlags = EF_BOUNCE_HALF;
+ bolt->r.ownerNum = self->s.number;
+ bolt->parent = self;
+ bolt->damage = 100;
+ bolt->splashDamage = 100;
+ bolt->splashRadius = 150;
+ bolt->methodOfDeath = MOD_GRENADE;
+ bolt->splashMethodOfDeath = MOD_GRENADE_SPLASH;
+ bolt->clipmask = MASK_SHOT;
+ bolt->target_ent = NULL;
+
+ bolt->s.pos.trType = TR_GRAVITY;
+ bolt->s.pos.trTime = level.time - MISSILE_PRESTEP_TIME; // move a bit on the very first frame
+ VectorCopy( start, bolt->s.pos.trBase );
+ VectorScale( dir, 700, bolt->s.pos.trDelta );
+ SnapVector( bolt->s.pos.trDelta ); // save net bandwidth
+
+ VectorCopy (start, bolt->r.currentOrigin);
+
+ return bolt;
+}
+
+//=============================================================================
+
+
+/*
+=================
+fire_bfg
+=================
+*/
+gentity_t *fire_bfg (gentity_t *self, vec3_t start, vec3_t dir) {
+ gentity_t *bolt;
+
+ VectorNormalize (dir);
+
+ bolt = G_Spawn();
+ bolt->classname = "bfg";
+ bolt->nextthink = level.time + 10000;
+ bolt->think = G_ExplodeMissile;
+ bolt->s.eType = ET_MISSILE;
+ bolt->r.svFlags = SVF_USE_CURRENT_ORIGIN;
+ bolt->s.weapon = WP_BFG;
+ bolt->r.ownerNum = self->s.number;
+ bolt->parent = self;
+ bolt->damage = 100;
+ bolt->splashDamage = 100;
+ bolt->splashRadius = 120;
+ bolt->methodOfDeath = MOD_BFG;
+ bolt->splashMethodOfDeath = MOD_BFG_SPLASH;
+ bolt->clipmask = MASK_SHOT;
+ bolt->target_ent = NULL;
+
+ bolt->s.pos.trType = TR_LINEAR;
+ bolt->s.pos.trTime = level.time - MISSILE_PRESTEP_TIME; // move a bit on the very first frame
+ VectorCopy( start, bolt->s.pos.trBase );
+ VectorScale( dir, 2000, bolt->s.pos.trDelta );
+ SnapVector( bolt->s.pos.trDelta ); // save net bandwidth
+ VectorCopy (start, bolt->r.currentOrigin);
+
+ return bolt;
+}
+
+//=============================================================================
+
+
+/*
+=================
+fire_rocket
+=================
+*/
+gentity_t *fire_rocket (gentity_t *self, vec3_t start, vec3_t dir) {
+ gentity_t *bolt;
+
+ VectorNormalize (dir);
+
+ bolt = G_Spawn();
+ bolt->classname = "rocket";
+ bolt->nextthink = level.time + 15000;
+ bolt->think = G_ExplodeMissile;
+ bolt->s.eType = ET_MISSILE;
+ bolt->r.svFlags = SVF_USE_CURRENT_ORIGIN;
+ bolt->s.weapon = WP_ROCKET_LAUNCHER;
+ bolt->r.ownerNum = self->s.number;
+ bolt->parent = self;
+ bolt->damage = 100;
+ bolt->splashDamage = 100;
+ bolt->splashRadius = 120;
+ bolt->methodOfDeath = MOD_ROCKET;
+ bolt->splashMethodOfDeath = MOD_ROCKET_SPLASH;
+ bolt->clipmask = MASK_SHOT;
+ bolt->target_ent = NULL;
+
+ bolt->s.pos.trType = TR_LINEAR;
+ bolt->s.pos.trTime = level.time - MISSILE_PRESTEP_TIME; // move a bit on the very first frame
+ VectorCopy( start, bolt->s.pos.trBase );
+ VectorScale( dir, 900, bolt->s.pos.trDelta );
+ SnapVector( bolt->s.pos.trDelta ); // save net bandwidth
+ VectorCopy (start, bolt->r.currentOrigin);
+
+ return bolt;
+}
+
+/*
+=================
+fire_grapple
+=================
+*/
+gentity_t *fire_grapple (gentity_t *self, vec3_t start, vec3_t dir) {
+ gentity_t *hook;
+
+ VectorNormalize (dir);
+
+ hook = G_Spawn();
+ hook->classname = "hook";
+ hook->nextthink = level.time + 10000;
+ hook->think = Weapon_HookFree;
+ hook->s.eType = ET_MISSILE;
+ hook->r.svFlags = SVF_USE_CURRENT_ORIGIN;
+ hook->s.weapon = WP_GRAPPLING_HOOK;
+ hook->r.ownerNum = self->s.number;
+ hook->methodOfDeath = MOD_GRAPPLE;
+ hook->clipmask = MASK_SHOT;
+ hook->parent = self;
+ hook->target_ent = NULL;
+
+ hook->s.pos.trType = TR_LINEAR;
+ hook->s.pos.trTime = level.time - MISSILE_PRESTEP_TIME; // move a bit on the very first frame
+ hook->s.otherEntityNum = self->s.number; // use to match beam in client
+ VectorCopy( start, hook->s.pos.trBase );
+ VectorScale( dir, 800, hook->s.pos.trDelta );
+ SnapVector( hook->s.pos.trDelta ); // save net bandwidth
+ VectorCopy (start, hook->r.currentOrigin);
+
+ self->client->hook = hook;
+
+ return hook;
+}
+
+
+#ifdef MISSIONPACK
+/*
+=================
+fire_nail
+=================
+*/
+#define NAILGUN_SPREAD 500
+
+gentity_t *fire_nail( gentity_t *self, vec3_t start, vec3_t forward, vec3_t right, vec3_t up ) {
+ gentity_t *bolt;
+ vec3_t dir;
+ vec3_t end;
+ float r, u, scale;
+
+ bolt = G_Spawn();
+ bolt->classname = "nail";
+ bolt->nextthink = level.time + 10000;
+ bolt->think = G_ExplodeMissile;
+ bolt->s.eType = ET_MISSILE;
+ bolt->r.svFlags = SVF_USE_CURRENT_ORIGIN;
+ bolt->s.weapon = WP_NAILGUN;
+ bolt->r.ownerNum = self->s.number;
+ bolt->parent = self;
+ bolt->damage = 20;
+ bolt->methodOfDeath = MOD_NAIL;
+ bolt->clipmask = MASK_SHOT;
+ bolt->target_ent = NULL;
+
+ bolt->s.pos.trType = TR_LINEAR;
+ bolt->s.pos.trTime = level.time;
+ VectorCopy( start, bolt->s.pos.trBase );
+
+ r = random() * M_PI * 2.0f;
+ u = sin(r) * crandom() * NAILGUN_SPREAD * 16;
+ r = cos(r) * crandom() * NAILGUN_SPREAD * 16;
+ VectorMA( start, 8192 * 16, forward, end);
+ VectorMA (end, r, right, end);
+ VectorMA (end, u, up, end);
+ VectorSubtract( end, start, dir );
+ VectorNormalize( dir );
+
+ scale = 555 + random() * 1800;
+ VectorScale( dir, scale, bolt->s.pos.trDelta );
+ SnapVector( bolt->s.pos.trDelta );
+
+ VectorCopy( start, bolt->r.currentOrigin );
+
+ return bolt;
+}
+
+
+/*
+=================
+fire_prox
+=================
+*/
+gentity_t *fire_prox( gentity_t *self, vec3_t start, vec3_t dir ) {
+ gentity_t *bolt;
+
+ VectorNormalize (dir);
+
+ bolt = G_Spawn();
+ bolt->classname = "prox mine";
+ bolt->nextthink = level.time + 3000;
+ bolt->think = G_ExplodeMissile;
+ bolt->s.eType = ET_MISSILE;
+ bolt->r.svFlags = SVF_USE_CURRENT_ORIGIN;
+ bolt->s.weapon = WP_PROX_LAUNCHER;
+ bolt->s.eFlags = 0;
+ bolt->r.ownerNum = self->s.number;
+ bolt->parent = self;
+ bolt->damage = 0;
+ bolt->splashDamage = 100;
+ bolt->splashRadius = 150;
+ bolt->methodOfDeath = MOD_PROXIMITY_MINE;
+ bolt->splashMethodOfDeath = MOD_PROXIMITY_MINE;
+ bolt->clipmask = MASK_SHOT;
+ bolt->target_ent = NULL;
+ // count is used to check if the prox mine left the player bbox
+ // if count == 1 then the prox mine left the player bbox and can attack to it
+ bolt->count = 0;
+
+ //FIXME: we prolly wanna abuse another field
+ bolt->s.generic1 = self->client->sess.sessionTeam;
+
+ bolt->s.pos.trType = TR_GRAVITY;
+ bolt->s.pos.trTime = level.time - MISSILE_PRESTEP_TIME; // move a bit on the very first frame
+ VectorCopy( start, bolt->s.pos.trBase );
+ VectorScale( dir, 700, bolt->s.pos.trDelta );
+ SnapVector( bolt->s.pos.trDelta ); // save net bandwidth
+
+ VectorCopy (start, bolt->r.currentOrigin);
+
+ return bolt;
+}
+#endif
diff --git a/code/game/g_mover.c b/code/game/g_mover.c
new file mode 100755
index 0000000..92b71c9
--- /dev/null
+++ b/code/game/g_mover.c
@@ -0,0 +1,1612 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+#include "g_local.h"
+
+
+
+/*
+===============================================================================
+
+PUSHMOVE
+
+===============================================================================
+*/
+
+void MatchTeam( gentity_t *teamLeader, int moverState, int time );
+
+typedef struct {
+ gentity_t *ent;
+ vec3_t origin;
+ vec3_t angles;
+ float deltayaw;
+} pushed_t;
+pushed_t pushed[MAX_GENTITIES], *pushed_p;
+
+
+/*
+============
+G_TestEntityPosition
+
+============
+*/
+gentity_t *G_TestEntityPosition( gentity_t *ent ) {
+ trace_t tr;
+ int mask;
+
+ if ( ent->clipmask ) {
+ mask = ent->clipmask;
+ } else {
+ mask = MASK_SOLID;
+ }
+ if ( ent->client ) {
+ trap_Trace( &tr, ent->client->ps.origin, ent->r.mins, ent->r.maxs, ent->client->ps.origin, ent->s.number, mask );
+ } else {
+ trap_Trace( &tr, ent->s.pos.trBase, ent->r.mins, ent->r.maxs, ent->s.pos.trBase, ent->s.number, mask );
+ }
+
+ if (tr.startsolid)
+ return &g_entities[ tr.entityNum ];
+
+ return NULL;
+}
+
+/*
+================
+G_CreateRotationMatrix
+================
+*/
+void G_CreateRotationMatrix(vec3_t angles, vec3_t matrix[3]) {
+ AngleVectors(angles, matrix[0], matrix[1], matrix[2]);
+ VectorInverse(matrix[1]);
+}
+
+/*
+================
+G_TransposeMatrix
+================
+*/
+void G_TransposeMatrix(vec3_t matrix[3], vec3_t transpose[3]) {
+ int i, j;
+ for (i = 0; i < 3; i++) {
+ for (j = 0; j < 3; j++) {
+ transpose[i][j] = matrix[j][i];
+ }
+ }
+}
+
+/*
+================
+G_RotatePoint
+================
+*/
+void G_RotatePoint(vec3_t point, vec3_t matrix[3]) {
+ vec3_t tvec;
+
+ VectorCopy(point, tvec);
+ point[0] = DotProduct(matrix[0], tvec);
+ point[1] = DotProduct(matrix[1], tvec);
+ point[2] = DotProduct(matrix[2], tvec);
+}
+
+/*
+==================
+G_TryPushingEntity
+
+Returns qfalse if the move is blocked
+==================
+*/
+qboolean G_TryPushingEntity( gentity_t *check, gentity_t *pusher, vec3_t move, vec3_t amove ) {
+ vec3_t matrix[3], transpose[3];
+ vec3_t org, org2, move2;
+ gentity_t *block;
+
+ // EF_MOVER_STOP will just stop when contacting another entity
+ // instead of pushing it, but entities can still ride on top of it
+ if ( ( pusher->s.eFlags & EF_MOVER_STOP ) &&
+ check->s.groundEntityNum != pusher->s.number ) {
+ return qfalse;
+ }
+
+ // save off the old position
+ if (pushed_p > &pushed[MAX_GENTITIES]) {
+ G_Error( "pushed_p > &pushed[MAX_GENTITIES]" );
+ }
+ pushed_p->ent = check;
+ VectorCopy (check->s.pos.trBase, pushed_p->origin);
+ VectorCopy (check->s.apos.trBase, pushed_p->angles);
+ if ( check->client ) {
+ pushed_p->deltayaw = check->client->ps.delta_angles[YAW];
+ VectorCopy (check->client->ps.origin, pushed_p->origin);
+ }
+ pushed_p++;
+
+ // try moving the contacted entity
+ // figure movement due to the pusher's amove
+ G_CreateRotationMatrix( amove, transpose );
+ G_TransposeMatrix( transpose, matrix );
+ if ( check->client ) {
+ VectorSubtract (check->client->ps.origin, pusher->r.currentOrigin, org);
+ }
+ else {
+ VectorSubtract (check->s.pos.trBase, pusher->r.currentOrigin, org);
+ }
+ VectorCopy( org, org2 );
+ G_RotatePoint( org2, matrix );
+ VectorSubtract (org2, org, move2);
+ // add movement
+ VectorAdd (check->s.pos.trBase, move, check->s.pos.trBase);
+ VectorAdd (check->s.pos.trBase, move2, check->s.pos.trBase);
+ if ( check->client ) {
+ VectorAdd (check->client->ps.origin, move, check->client->ps.origin);
+ VectorAdd (check->client->ps.origin, move2, check->client->ps.origin);
+ // make sure the client's view rotates when on a rotating mover
+ check->client->ps.delta_angles[YAW] += ANGLE2SHORT(amove[YAW]);
+ }
+
+ // may have pushed them off an edge
+ if ( check->s.groundEntityNum != pusher->s.number ) {
+ check->s.groundEntityNum = -1;
+ }
+
+ block = G_TestEntityPosition( check );
+ if (!block) {
+ // pushed ok
+ if ( check->client ) {
+ VectorCopy( check->client->ps.origin, check->r.currentOrigin );
+ } else {
+ VectorCopy( check->s.pos.trBase, check->r.currentOrigin );
+ }
+ trap_LinkEntity (check);
+ return qtrue;
+ }
+
+ // if it is ok to leave in the old position, do it
+ // this is only relevent for riding entities, not pushed
+ // Sliding trapdoors can cause this.
+ VectorCopy( (pushed_p-1)->origin, check->s.pos.trBase);
+ if ( check->client ) {
+ VectorCopy( (pushed_p-1)->origin, check->client->ps.origin);
+ }
+ VectorCopy( (pushed_p-1)->angles, check->s.apos.trBase );
+ block = G_TestEntityPosition (check);
+ if ( !block ) {
+ check->s.groundEntityNum = -1;
+ pushed_p--;
+ return qtrue;
+ }
+
+ // blocked
+ return qfalse;
+}
+
+/*
+==================
+G_CheckProxMinePosition
+==================
+*/
+qboolean G_CheckProxMinePosition( gentity_t *check ) {
+ vec3_t start, end;
+ trace_t tr;
+
+ VectorMA(check->s.pos.trBase, 0.125, check->movedir, start);
+ VectorMA(check->s.pos.trBase, 2, check->movedir, end);
+ trap_Trace( &tr, start, NULL, NULL, end, check->s.number, MASK_SOLID );
+
+ if (tr.startsolid || tr.fraction < 1)
+ return qfalse;
+
+ return qtrue;
+}
+
+/*
+==================
+G_TryPushingProxMine
+==================
+*/
+qboolean G_TryPushingProxMine( gentity_t *check, gentity_t *pusher, vec3_t move, vec3_t amove ) {
+ vec3_t forward, right, up;
+ vec3_t org, org2, move2;
+ int ret;
+
+ // we need this for pushing things later
+ VectorSubtract (vec3_origin, amove, org);
+ AngleVectors (org, forward, right, up);
+
+ // try moving the contacted entity
+ VectorAdd (check->s.pos.trBase, move, check->s.pos.trBase);
+
+ // figure movement due to the pusher's amove
+ VectorSubtract (check->s.pos.trBase, pusher->r.currentOrigin, org);
+ org2[0] = DotProduct (org, forward);
+ org2[1] = -DotProduct (org, right);
+ org2[2] = DotProduct (org, up);
+ VectorSubtract (org2, org, move2);
+ VectorAdd (check->s.pos.trBase, move2, check->s.pos.trBase);
+
+ ret = G_CheckProxMinePosition( check );
+ if (ret) {
+ VectorCopy( check->s.pos.trBase, check->r.currentOrigin );
+ trap_LinkEntity (check);
+ }
+ return ret;
+}
+
+void G_ExplodeMissile( gentity_t *ent );
+
+/*
+============
+G_MoverPush
+
+Objects need to be moved back on a failed push,
+otherwise riders would continue to slide.
+If qfalse is returned, *obstacle will be the blocking entity
+============
+*/
+qboolean G_MoverPush( gentity_t *pusher, vec3_t move, vec3_t amove, gentity_t **obstacle ) {
+ int i, e;
+ gentity_t *check;
+ vec3_t mins, maxs;
+ pushed_t *p;
+ int entityList[MAX_GENTITIES];
+ int listedEntities;
+ vec3_t totalMins, totalMaxs;
+
+ *obstacle = NULL;
+
+
+ // mins/maxs are the bounds at the destination
+ // totalMins / totalMaxs are the bounds for the entire move
+ if ( pusher->r.currentAngles[0] || pusher->r.currentAngles[1] || pusher->r.currentAngles[2]
+ || amove[0] || amove[1] || amove[2] ) {
+ float radius;
+
+ radius = RadiusFromBounds( pusher->r.mins, pusher->r.maxs );
+ for ( i = 0 ; i < 3 ; i++ ) {
+ mins[i] = pusher->r.currentOrigin[i] + move[i] - radius;
+ maxs[i] = pusher->r.currentOrigin[i] + move[i] + radius;
+ totalMins[i] = mins[i] - move[i];
+ totalMaxs[i] = maxs[i] - move[i];
+ }
+ } else {
+ for (i=0 ; i<3 ; i++) {
+ mins[i] = pusher->r.absmin[i] + move[i];
+ maxs[i] = pusher->r.absmax[i] + move[i];
+ }
+
+ VectorCopy( pusher->r.absmin, totalMins );
+ VectorCopy( pusher->r.absmax, totalMaxs );
+ for (i=0 ; i<3 ; i++) {
+ if ( move[i] > 0 ) {
+ totalMaxs[i] += move[i];
+ } else {
+ totalMins[i] += move[i];
+ }
+ }
+ }
+
+ // unlink the pusher so we don't get it in the entityList
+ trap_UnlinkEntity( pusher );
+
+ listedEntities = trap_EntitiesInBox( totalMins, totalMaxs, entityList, MAX_GENTITIES );
+
+ // move the pusher to it's final position
+ VectorAdd( pusher->r.currentOrigin, move, pusher->r.currentOrigin );
+ VectorAdd( pusher->r.currentAngles, amove, pusher->r.currentAngles );
+ trap_LinkEntity( pusher );
+
+ // see if any solid entities are inside the final position
+ for ( e = 0 ; e < listedEntities ; e++ ) {
+ check = &g_entities[ entityList[ e ] ];
+
+#ifdef MISSIONPACK
+ if ( check->s.eType == ET_MISSILE ) {
+ // if it is a prox mine
+ if ( !strcmp(check->classname, "prox mine") ) {
+ // if this prox mine is attached to this mover try to move it with the pusher
+ if ( check->enemy == pusher ) {
+ if (!G_TryPushingProxMine( check, pusher, move, amove )) {
+ //explode
+ check->s.loopSound = 0;
+ G_AddEvent( check, EV_PROXIMITY_MINE_TRIGGER, 0 );
+ G_ExplodeMissile(check);
+ if (check->activator) {
+ G_FreeEntity(check->activator);
+ check->activator = NULL;
+ }
+ //G_Printf("prox mine explodes\n");
+ }
+ }
+ else {
+ //check if the prox mine is crushed by the mover
+ if (!G_CheckProxMinePosition( check )) {
+ //explode
+ check->s.loopSound = 0;
+ G_AddEvent( check, EV_PROXIMITY_MINE_TRIGGER, 0 );
+ G_ExplodeMissile(check);
+ if (check->activator) {
+ G_FreeEntity(check->activator);
+ check->activator = NULL;
+ }
+ //G_Printf("prox mine explodes\n");
+ }
+ }
+ continue;
+ }
+ }
+#endif
+ // only push items and players
+ if ( check->s.eType != ET_ITEM && check->s.eType != ET_PLAYER && !check->physicsObject ) {
+ continue;
+ }
+
+ // if the entity is standing on the pusher, it will definitely be moved
+ if ( check->s.groundEntityNum != pusher->s.number ) {
+ // see if the ent needs to be tested
+ if ( check->r.absmin[0] >= maxs[0]
+ || check->r.absmin[1] >= maxs[1]
+ || check->r.absmin[2] >= maxs[2]
+ || check->r.absmax[0] <= mins[0]
+ || check->r.absmax[1] <= mins[1]
+ || check->r.absmax[2] <= mins[2] ) {
+ continue;
+ }
+ // see if the ent's bbox is inside the pusher's final position
+ // this does allow a fast moving object to pass through a thin entity...
+ if (!G_TestEntityPosition (check)) {
+ continue;
+ }
+ }
+
+ // the entity needs to be pushed
+ if ( G_TryPushingEntity( check, pusher, move, amove ) ) {
+ continue;
+ }
+
+ // the move was blocked an entity
+
+ // bobbing entities are instant-kill and never get blocked
+ if ( pusher->s.pos.trType == TR_SINE || pusher->s.apos.trType == TR_SINE ) {
+ G_Damage( check, pusher, pusher, NULL, NULL, 99999, 0, MOD_CRUSH );
+ continue;
+ }
+
+
+ // save off the obstacle so we can call the block function (crush, etc)
+ *obstacle = check;
+
+ // move back any entities we already moved
+ // go backwards, so if the same entity was pushed
+ // twice, it goes back to the original position
+ for ( p=pushed_p-1 ; p>=pushed ; p-- ) {
+ VectorCopy (p->origin, p->ent->s.pos.trBase);
+ VectorCopy (p->angles, p->ent->s.apos.trBase);
+ if ( p->ent->client ) {
+ p->ent->client->ps.delta_angles[YAW] = p->deltayaw;
+ VectorCopy (p->origin, p->ent->client->ps.origin);
+ }
+ trap_LinkEntity (p->ent);
+ }
+ return qfalse;
+ }
+
+ return qtrue;
+}
+
+
+/*
+=================
+G_MoverTeam
+=================
+*/
+void G_MoverTeam( gentity_t *ent ) {
+ vec3_t move, amove;
+ gentity_t *part, *obstacle;
+ vec3_t origin, angles;
+
+ obstacle = NULL;
+
+ // make sure all team slaves can move before commiting
+ // any moves or calling any think functions
+ // if the move is blocked, all moved objects will be backed out
+ pushed_p = pushed;
+ for (part = ent ; part ; part=part->teamchain) {
+ // get current position
+ BG_EvaluateTrajectory( &part->s.pos, level.time, origin );
+ BG_EvaluateTrajectory( &part->s.apos, level.time, angles );
+ VectorSubtract( origin, part->r.currentOrigin, move );
+ VectorSubtract( angles, part->r.currentAngles, amove );
+ if ( !G_MoverPush( part, move, amove, &obstacle ) ) {
+ break; // move was blocked
+ }
+ }
+
+ if (part) {
+ // go back to the previous position
+ for ( part = ent ; part ; part = part->teamchain ) {
+ part->s.pos.trTime += level.time - level.previousTime;
+ part->s.apos.trTime += level.time - level.previousTime;
+ BG_EvaluateTrajectory( &part->s.pos, level.time, part->r.currentOrigin );
+ BG_EvaluateTrajectory( &part->s.apos, level.time, part->r.currentAngles );
+ trap_LinkEntity( part );
+ }
+
+ // if the pusher has a "blocked" function, call it
+ if (ent->blocked) {
+ ent->blocked( ent, obstacle );
+ }
+ return;
+ }
+
+ // the move succeeded
+ for ( part = ent ; part ; part = part->teamchain ) {
+ // call the reached function if time is at or past end point
+ if ( part->s.pos.trType == TR_LINEAR_STOP ) {
+ if ( level.time >= part->s.pos.trTime + part->s.pos.trDuration ) {
+ if ( part->reached ) {
+ part->reached( part );
+ }
+ }
+ }
+ }
+}
+
+/*
+================
+G_RunMover
+
+================
+*/
+void G_RunMover( gentity_t *ent ) {
+ // if not a team captain, don't do anything, because
+ // the captain will handle everything
+ if ( ent->flags & FL_TEAMSLAVE ) {
+ return;
+ }
+
+ // if stationary at one of the positions, don't move anything
+ if ( ent->s.pos.trType != TR_STATIONARY || ent->s.apos.trType != TR_STATIONARY ) {
+ G_MoverTeam( ent );
+ }
+
+ // check think function
+ G_RunThink( ent );
+}
+
+/*
+============================================================================
+
+GENERAL MOVERS
+
+Doors, plats, and buttons are all binary (two position) movers
+Pos1 is "at rest", pos2 is "activated"
+============================================================================
+*/
+
+/*
+===============
+SetMoverState
+===============
+*/
+void SetMoverState( gentity_t *ent, moverState_t moverState, int time ) {
+ vec3_t delta;
+ float f;
+
+ ent->moverState = moverState;
+
+ ent->s.pos.trTime = time;
+ switch( moverState ) {
+ case MOVER_POS1:
+ VectorCopy( ent->pos1, ent->s.pos.trBase );
+ ent->s.pos.trType = TR_STATIONARY;
+ break;
+ case MOVER_POS2:
+ VectorCopy( ent->pos2, ent->s.pos.trBase );
+ ent->s.pos.trType = TR_STATIONARY;
+ break;
+ case MOVER_1TO2:
+ VectorCopy( ent->pos1, ent->s.pos.trBase );
+ VectorSubtract( ent->pos2, ent->pos1, delta );
+ f = 1000.0 / ent->s.pos.trDuration;
+ VectorScale( delta, f, ent->s.pos.trDelta );
+ ent->s.pos.trType = TR_LINEAR_STOP;
+ break;
+ case MOVER_2TO1:
+ VectorCopy( ent->pos2, ent->s.pos.trBase );
+ VectorSubtract( ent->pos1, ent->pos2, delta );
+ f = 1000.0 / ent->s.pos.trDuration;
+ VectorScale( delta, f, ent->s.pos.trDelta );
+ ent->s.pos.trType = TR_LINEAR_STOP;
+ break;
+ }
+ BG_EvaluateTrajectory( &ent->s.pos, level.time, ent->r.currentOrigin );
+ trap_LinkEntity( ent );
+}
+
+/*
+================
+MatchTeam
+
+All entities in a mover team will move from pos1 to pos2
+in the same amount of time
+================
+*/
+void MatchTeam( gentity_t *teamLeader, int moverState, int time ) {
+ gentity_t *slave;
+
+ for ( slave = teamLeader ; slave ; slave = slave->teamchain ) {
+ SetMoverState( slave, moverState, time );
+ }
+}
+
+
+
+/*
+================
+ReturnToPos1
+================
+*/
+void ReturnToPos1( gentity_t *ent ) {
+ MatchTeam( ent, MOVER_2TO1, level.time );
+
+ // looping sound
+ ent->s.loopSound = ent->soundLoop;
+
+ // starting sound
+ if ( ent->sound2to1 ) {
+ G_AddEvent( ent, EV_GENERAL_SOUND, ent->sound2to1 );
+ }
+}
+
+
+/*
+================
+Reached_BinaryMover
+================
+*/
+void Reached_BinaryMover( gentity_t *ent ) {
+
+ // stop the looping sound
+ ent->s.loopSound = ent->soundLoop;
+
+ if ( ent->moverState == MOVER_1TO2 ) {
+ // reached pos2
+ SetMoverState( ent, MOVER_POS2, level.time );
+
+ // play sound
+ if ( ent->soundPos2 ) {
+ G_AddEvent( ent, EV_GENERAL_SOUND, ent->soundPos2 );
+ }
+
+ // return to pos1 after a delay
+ ent->think = ReturnToPos1;
+ ent->nextthink = level.time + ent->wait;
+
+ // fire targets
+ if ( !ent->activator ) {
+ ent->activator = ent;
+ }
+ G_UseTargets( ent, ent->activator );
+ } else if ( ent->moverState == MOVER_2TO1 ) {
+ // reached pos1
+ SetMoverState( ent, MOVER_POS1, level.time );
+
+ // play sound
+ if ( ent->soundPos1 ) {
+ G_AddEvent( ent, EV_GENERAL_SOUND, ent->soundPos1 );
+ }
+
+ // close areaportals
+ if ( ent->teammaster == ent || !ent->teammaster ) {
+ trap_AdjustAreaPortalState( ent, qfalse );
+ }
+ } else {
+ G_Error( "Reached_BinaryMover: bad moverState" );
+ }
+}
+
+
+/*
+================
+Use_BinaryMover
+================
+*/
+void Use_BinaryMover( gentity_t *ent, gentity_t *other, gentity_t *activator ) {
+ int total;
+ int partial;
+
+ // only the master should be used
+ if ( ent->flags & FL_TEAMSLAVE ) {
+ Use_BinaryMover( ent->teammaster, other, activator );
+ return;
+ }
+
+ ent->activator = activator;
+
+ if ( ent->moverState == MOVER_POS1 ) {
+ // start moving 50 msec later, becase if this was player
+ // triggered, level.time hasn't been advanced yet
+ MatchTeam( ent, MOVER_1TO2, level.time + 50 );
+
+ // starting sound
+ if ( ent->sound1to2 ) {
+ G_AddEvent( ent, EV_GENERAL_SOUND, ent->sound1to2 );
+ }
+
+ // looping sound
+ ent->s.loopSound = ent->soundLoop;
+
+ // open areaportal
+ if ( ent->teammaster == ent || !ent->teammaster ) {
+ trap_AdjustAreaPortalState( ent, qtrue );
+ }
+ return;
+ }
+
+ // if all the way up, just delay before coming down
+ if ( ent->moverState == MOVER_POS2 ) {
+ ent->nextthink = level.time + ent->wait;
+ return;
+ }
+
+ // only partway down before reversing
+ if ( ent->moverState == MOVER_2TO1 ) {
+ total = ent->s.pos.trDuration;
+ partial = level.time - ent->s.pos.trTime;
+ if ( partial > total ) {
+ partial = total;
+ }
+
+ MatchTeam( ent, MOVER_1TO2, level.time - ( total - partial ) );
+
+ if ( ent->sound1to2 ) {
+ G_AddEvent( ent, EV_GENERAL_SOUND, ent->sound1to2 );
+ }
+ return;
+ }
+
+ // only partway up before reversing
+ if ( ent->moverState == MOVER_1TO2 ) {
+ total = ent->s.pos.trDuration;
+ partial = level.time - ent->s.pos.trTime;
+ if ( partial > total ) {
+ partial = total;
+ }
+
+ MatchTeam( ent, MOVER_2TO1, level.time - ( total - partial ) );
+
+ if ( ent->sound2to1 ) {
+ G_AddEvent( ent, EV_GENERAL_SOUND, ent->sound2to1 );
+ }
+ return;
+ }
+}
+
+
+
+/*
+================
+InitMover
+
+"pos1", "pos2", and "speed" should be set before calling,
+so the movement delta can be calculated
+================
+*/
+void InitMover( gentity_t *ent ) {
+ vec3_t move;
+ float distance;
+ float light;
+ vec3_t color;
+ qboolean lightSet, colorSet;
+ char *sound;
+
+ // if the "model2" key is set, use a seperate model
+ // for drawing, but clip against the brushes
+ if ( ent->model2 ) {
+ ent->s.modelindex2 = G_ModelIndex( ent->model2 );
+ }
+
+ // if the "loopsound" key is set, use a constant looping sound when moving
+ if ( G_SpawnString( "noise", "100", &sound ) ) {
+ ent->s.loopSound = G_SoundIndex( sound );
+ }
+
+ // if the "color" or "light" keys are set, setup constantLight
+ lightSet = G_SpawnFloat( "light", "100", &light );
+ colorSet = G_SpawnVector( "color", "1 1 1", color );
+ if ( lightSet || colorSet ) {
+ int r, g, b, i;
+
+ r = color[0] * 255;
+ if ( r > 255 ) {
+ r = 255;
+ }
+ g = color[1] * 255;
+ if ( g > 255 ) {
+ g = 255;
+ }
+ b = color[2] * 255;
+ if ( b > 255 ) {
+ b = 255;
+ }
+ i = light / 4;
+ if ( i > 255 ) {
+ i = 255;
+ }
+ ent->s.constantLight = r | ( g << 8 ) | ( b << 16 ) | ( i << 24 );
+ }
+
+
+ ent->use = Use_BinaryMover;
+ ent->reached = Reached_BinaryMover;
+
+ ent->moverState = MOVER_POS1;
+ ent->r.svFlags = SVF_USE_CURRENT_ORIGIN;
+ ent->s.eType = ET_MOVER;
+ VectorCopy (ent->pos1, ent->r.currentOrigin);
+ trap_LinkEntity (ent);
+
+ ent->s.pos.trType = TR_STATIONARY;
+ VectorCopy( ent->pos1, ent->s.pos.trBase );
+
+ // calculate time to reach second position from speed
+ VectorSubtract( ent->pos2, ent->pos1, move );
+ distance = VectorLength( move );
+ if ( ! ent->speed ) {
+ ent->speed = 100;
+ }
+ VectorScale( move, ent->speed, ent->s.pos.trDelta );
+ ent->s.pos.trDuration = distance * 1000 / ent->speed;
+ if ( ent->s.pos.trDuration <= 0 ) {
+ ent->s.pos.trDuration = 1;
+ }
+}
+
+
+/*
+===============================================================================
+
+DOOR
+
+A use can be triggered either by a touch function, by being shot, or by being
+targeted by another entity.
+
+===============================================================================
+*/
+
+/*
+================
+Blocked_Door
+================
+*/
+void Blocked_Door( gentity_t *ent, gentity_t *other ) {
+ // remove anything other than a client
+ if ( !other->client ) {
+ // except CTF flags!!!!
+ if( other->s.eType == ET_ITEM && other->item->giType == IT_TEAM ) {
+ Team_DroppedFlagThink( other );
+ return;
+ }
+ G_TempEntity( other->s.origin, EV_ITEM_POP );
+ G_FreeEntity( other );
+ return;
+ }
+
+ if ( ent->damage ) {
+ G_Damage( other, ent, ent, NULL, NULL, ent->damage, 0, MOD_CRUSH );
+ }
+ if ( ent->spawnflags & 4 ) {
+ return; // crushers don't reverse
+ }
+
+ // reverse direction
+ Use_BinaryMover( ent, ent, other );
+}
+
+/*
+================
+Touch_DoorTriggerSpectator
+================
+*/
+static void Touch_DoorTriggerSpectator( gentity_t *ent, gentity_t *other, trace_t *trace ) {
+ int i, axis;
+ vec3_t origin, dir, angles;
+
+ axis = ent->count;
+ VectorClear(dir);
+ if (fabs(other->s.origin[axis] - ent->r.absmax[axis]) <
+ fabs(other->s.origin[axis] - ent->r.absmin[axis])) {
+ origin[axis] = ent->r.absmin[axis] - 10;
+ dir[axis] = -1;
+ }
+ else {
+ origin[axis] = ent->r.absmax[axis] + 10;
+ dir[axis] = 1;
+ }
+ for (i = 0; i < 3; i++) {
+ if (i == axis) continue;
+ origin[i] = (ent->r.absmin[i] + ent->r.absmax[i]) * 0.5;
+ }
+ vectoangles(dir, angles);
+ TeleportPlayer(other, origin, angles );
+}
+
+/*
+================
+Touch_DoorTrigger
+================
+*/
+void Touch_DoorTrigger( gentity_t *ent, gentity_t *other, trace_t *trace ) {
+ if ( other->client && other->client->sess.sessionTeam == TEAM_SPECTATOR ) {
+ // if the door is not open and not opening
+ if ( ent->parent->moverState != MOVER_1TO2 &&
+ ent->parent->moverState != MOVER_POS2) {
+ Touch_DoorTriggerSpectator( ent, other, trace );
+ }
+ }
+ else if ( ent->parent->moverState != MOVER_1TO2 ) {
+ Use_BinaryMover( ent->parent, ent, other );
+ }
+}
+
+
+/*
+======================
+Think_SpawnNewDoorTrigger
+
+All of the parts of a door have been spawned, so create
+a trigger that encloses all of them
+======================
+*/
+void Think_SpawnNewDoorTrigger( gentity_t *ent ) {
+ gentity_t *other;
+ vec3_t mins, maxs;
+ int i, best;
+
+ // set all of the slaves as shootable
+ for ( other = ent ; other ; other = other->teamchain ) {
+ other->takedamage = qtrue;
+ }
+
+ // find the bounds of everything on the team
+ VectorCopy (ent->r.absmin, mins);
+ VectorCopy (ent->r.absmax, maxs);
+
+ for (other = ent->teamchain ; other ; other=other->teamchain) {
+ AddPointToBounds (other->r.absmin, mins, maxs);
+ AddPointToBounds (other->r.absmax, mins, maxs);
+ }
+
+ // find the thinnest axis, which will be the one we expand
+ best = 0;
+ for ( i = 1 ; i < 3 ; i++ ) {
+ if ( maxs[i] - mins[i] < maxs[best] - mins[best] ) {
+ best = i;
+ }
+ }
+ maxs[best] += 120;
+ mins[best] -= 120;
+
+ // create a trigger with this size
+ other = G_Spawn ();
+ other->classname = "door_trigger";
+ VectorCopy (mins, other->r.mins);
+ VectorCopy (maxs, other->r.maxs);
+ other->parent = ent;
+ other->r.contents = CONTENTS_TRIGGER;
+ other->touch = Touch_DoorTrigger;
+ // remember the thinnest axis
+ other->count = best;
+ trap_LinkEntity (other);
+
+ MatchTeam( ent, ent->moverState, level.time );
+}
+
+void Think_MatchTeam( gentity_t *ent ) {
+ MatchTeam( ent, ent->moverState, level.time );
+}
+
+
+/*QUAKED func_door (0 .5 .8) ? START_OPEN x CRUSHER
+TOGGLE wait in both the start and end states for a trigger event.
+START_OPEN the door to moves to its destination when spawned, and operate in reverse. It is used to temporarily or permanently close off an area when triggered (not useful for touch or takedamage doors).
+NOMONSTER monsters will not trigger this door
+
+"model2" .md3 model to also draw
+"angle" determines the opening direction
+"targetname" if set, no touch field will be spawned and a remote button or trigger field activates the door.
+"speed" movement speed (100 default)
+"wait" wait before returning (3 default, -1 = never return)
+"lip" lip remaining at end of move (8 default)
+"dmg" damage to inflict when blocked (2 default)
+"color" constantLight color
+"light" constantLight radius
+"health" if set, the door must be shot open
+*/
+void SP_func_door (gentity_t *ent) {
+ vec3_t abs_movedir;
+ float distance;
+ vec3_t size;
+ float lip;
+
+ ent->sound1to2 = ent->sound2to1 = G_SoundIndex("sound/movers/doors/dr1_strt.wav");
+ ent->soundPos1 = ent->soundPos2 = G_SoundIndex("sound/movers/doors/dr1_end.wav");
+
+ ent->blocked = Blocked_Door;
+
+ // default speed of 400
+ if (!ent->speed)
+ ent->speed = 400;
+
+ // default wait of 2 seconds
+ if (!ent->wait)
+ ent->wait = 2;
+ ent->wait *= 1000;
+
+ // default lip of 8 units
+ G_SpawnFloat( "lip", "8", &lip );
+
+ // default damage of 2 points
+ G_SpawnInt( "dmg", "2", &ent->damage );
+
+ // first position at start
+ VectorCopy( ent->s.origin, ent->pos1 );
+
+ // calculate second position
+ trap_SetBrushModel( ent, ent->model );
+ G_SetMovedir (ent->s.angles, ent->movedir);
+ abs_movedir[0] = fabs(ent->movedir[0]);
+ abs_movedir[1] = fabs(ent->movedir[1]);
+ abs_movedir[2] = fabs(ent->movedir[2]);
+ VectorSubtract( ent->r.maxs, ent->r.mins, size );
+ distance = DotProduct( abs_movedir, size ) - lip;
+ VectorMA( ent->pos1, distance, ent->movedir, ent->pos2 );
+
+ // if "start_open", reverse position 1 and 2
+ if ( ent->spawnflags & 1 ) {
+ vec3_t temp;
+
+ VectorCopy( ent->pos2, temp );
+ VectorCopy( ent->s.origin, ent->pos2 );
+ VectorCopy( temp, ent->pos1 );
+ }
+
+ InitMover( ent );
+
+ ent->nextthink = level.time + FRAMETIME;
+
+ if ( ! (ent->flags & FL_TEAMSLAVE ) ) {
+ int health;
+
+ G_SpawnInt( "health", "0", &health );
+ if ( health ) {
+ ent->takedamage = qtrue;
+ }
+ if ( ent->targetname || health ) {
+ // non touch/shoot doors
+ ent->think = Think_MatchTeam;
+ } else {
+ ent->think = Think_SpawnNewDoorTrigger;
+ }
+ }
+
+
+}
+
+/*
+===============================================================================
+
+PLAT
+
+===============================================================================
+*/
+
+/*
+==============
+Touch_Plat
+
+Don't allow decent if a living player is on it
+===============
+*/
+void Touch_Plat( gentity_t *ent, gentity_t *other, trace_t *trace ) {
+ if ( !other->client || other->client->ps.stats[STAT_HEALTH] <= 0 ) {
+ return;
+ }
+
+ // delay return-to-pos1 by one second
+ if ( ent->moverState == MOVER_POS2 ) {
+ ent->nextthink = level.time + 1000;
+ }
+}
+
+/*
+==============
+Touch_PlatCenterTrigger
+
+If the plat is at the bottom position, start it going up
+===============
+*/
+void Touch_PlatCenterTrigger(gentity_t *ent, gentity_t *other, trace_t *trace ) {
+ if ( !other->client ) {
+ return;
+ }
+
+ if ( ent->parent->moverState == MOVER_POS1 ) {
+ Use_BinaryMover( ent->parent, ent, other );
+ }
+}
+
+
+/*
+================
+SpawnPlatTrigger
+
+Spawn a trigger in the middle of the plat's low position
+Elevator cars require that the trigger extend through the entire low position,
+not just sit on top of it.
+================
+*/
+void SpawnPlatTrigger( gentity_t *ent ) {
+ gentity_t *trigger;
+ vec3_t tmin, tmax;
+
+ // the middle trigger will be a thin trigger just
+ // above the starting position
+ trigger = G_Spawn();
+ trigger->classname = "plat_trigger";
+ trigger->touch = Touch_PlatCenterTrigger;
+ trigger->r.contents = CONTENTS_TRIGGER;
+ trigger->parent = ent;
+
+ tmin[0] = ent->pos1[0] + ent->r.mins[0] + 33;
+ tmin[1] = ent->pos1[1] + ent->r.mins[1] + 33;
+ tmin[2] = ent->pos1[2] + ent->r.mins[2];
+
+ tmax[0] = ent->pos1[0] + ent->r.maxs[0] - 33;
+ tmax[1] = ent->pos1[1] + ent->r.maxs[1] - 33;
+ tmax[2] = ent->pos1[2] + ent->r.maxs[2] + 8;
+
+ if ( tmax[0] <= tmin[0] ) {
+ tmin[0] = ent->pos1[0] + (ent->r.mins[0] + ent->r.maxs[0]) *0.5;
+ tmax[0] = tmin[0] + 1;
+ }
+ if ( tmax[1] <= tmin[1] ) {
+ tmin[1] = ent->pos1[1] + (ent->r.mins[1] + ent->r.maxs[1]) *0.5;
+ tmax[1] = tmin[1] + 1;
+ }
+
+ VectorCopy (tmin, trigger->r.mins);
+ VectorCopy (tmax, trigger->r.maxs);
+
+ trap_LinkEntity (trigger);
+}
+
+
+/*QUAKED func_plat (0 .5 .8) ?
+Plats are always drawn in the extended position so they will light correctly.
+
+"lip" default 8, protrusion above rest position
+"height" total height of movement, defaults to model height
+"speed" overrides default 200.
+"dmg" overrides default 2
+"model2" .md3 model to also draw
+"color" constantLight color
+"light" constantLight radius
+*/
+void SP_func_plat (gentity_t *ent) {
+ float lip, height;
+
+ ent->sound1to2 = ent->sound2to1 = G_SoundIndex("sound/movers/plats/pt1_strt.wav");
+ ent->soundPos1 = ent->soundPos2 = G_SoundIndex("sound/movers/plats/pt1_end.wav");
+
+ VectorClear (ent->s.angles);
+
+ G_SpawnFloat( "speed", "200", &ent->speed );
+ G_SpawnInt( "dmg", "2", &ent->damage );
+ G_SpawnFloat( "wait", "1", &ent->wait );
+ G_SpawnFloat( "lip", "8", &lip );
+
+ ent->wait = 1000;
+
+ // create second position
+ trap_SetBrushModel( ent, ent->model );
+
+ if ( !G_SpawnFloat( "height", "0", &height ) ) {
+ height = (ent->r.maxs[2] - ent->r.mins[2]) - lip;
+ }
+
+ // pos1 is the rest (bottom) position, pos2 is the top
+ VectorCopy( ent->s.origin, ent->pos2 );
+ VectorCopy( ent->pos2, ent->pos1 );
+ ent->pos1[2] -= height;
+
+ InitMover( ent );
+
+ // touch function keeps the plat from returning while
+ // a live player is standing on it
+ ent->touch = Touch_Plat;
+
+ ent->blocked = Blocked_Door;
+
+ ent->parent = ent; // so it can be treated as a door
+
+ // spawn the trigger if one hasn't been custom made
+ if ( !ent->targetname ) {
+ SpawnPlatTrigger(ent);
+ }
+}
+
+
+/*
+===============================================================================
+
+BUTTON
+
+===============================================================================
+*/
+
+/*
+==============
+Touch_Button
+
+===============
+*/
+void Touch_Button(gentity_t *ent, gentity_t *other, trace_t *trace ) {
+ if ( !other->client ) {
+ return;
+ }
+
+ if ( ent->moverState == MOVER_POS1 ) {
+ Use_BinaryMover( ent, other, other );
+ }
+}
+
+
+/*QUAKED func_button (0 .5 .8) ?
+When a button is touched, it moves some distance in the direction of it's angle, triggers all of it's targets, waits some time, then returns to it's original position where it can be triggered again.
+
+"model2" .md3 model to also draw
+"angle" determines the opening direction
+"target" all entities with a matching targetname will be used
+"speed" override the default 40 speed
+"wait" override the default 1 second wait (-1 = never return)
+"lip" override the default 4 pixel lip remaining at end of move
+"health" if set, the button must be killed instead of touched
+"color" constantLight color
+"light" constantLight radius
+*/
+void SP_func_button( gentity_t *ent ) {
+ vec3_t abs_movedir;
+ float distance;
+ vec3_t size;
+ float lip;
+
+ ent->sound1to2 = G_SoundIndex("sound/movers/switches/butn2.wav");
+
+ if ( !ent->speed ) {
+ ent->speed = 40;
+ }
+
+ if ( !ent->wait ) {
+ ent->wait = 1;
+ }
+ ent->wait *= 1000;
+
+ // first position
+ VectorCopy( ent->s.origin, ent->pos1 );
+
+ // calculate second position
+ trap_SetBrushModel( ent, ent->model );
+
+ G_SpawnFloat( "lip", "4", &lip );
+
+ G_SetMovedir( ent->s.angles, ent->movedir );
+ abs_movedir[0] = fabs(ent->movedir[0]);
+ abs_movedir[1] = fabs(ent->movedir[1]);
+ abs_movedir[2] = fabs(ent->movedir[2]);
+ VectorSubtract( ent->r.maxs, ent->r.mins, size );
+ distance = abs_movedir[0] * size[0] + abs_movedir[1] * size[1] + abs_movedir[2] * size[2] - lip;
+ VectorMA (ent->pos1, distance, ent->movedir, ent->pos2);
+
+ if (ent->health) {
+ // shootable button
+ ent->takedamage = qtrue;
+ } else {
+ // touchable button
+ ent->touch = Touch_Button;
+ }
+
+ InitMover( ent );
+}
+
+
+
+/*
+===============================================================================
+
+TRAIN
+
+===============================================================================
+*/
+
+
+#define TRAIN_START_ON 1
+#define TRAIN_TOGGLE 2
+#define TRAIN_BLOCK_STOPS 4
+
+/*
+===============
+Think_BeginMoving
+
+The wait time at a corner has completed, so start moving again
+===============
+*/
+void Think_BeginMoving( gentity_t *ent ) {
+ ent->s.pos.trTime = level.time;
+ ent->s.pos.trType = TR_LINEAR_STOP;
+}
+
+/*
+===============
+Reached_Train
+===============
+*/
+void Reached_Train( gentity_t *ent ) {
+ gentity_t *next;
+ float speed;
+ vec3_t move;
+ float length;
+
+ // copy the apropriate values
+ next = ent->nextTrain;
+ if ( !next || !next->nextTrain ) {
+ return; // just stop
+ }
+
+ // fire all other targets
+ G_UseTargets( next, NULL );
+
+ // set the new trajectory
+ ent->nextTrain = next->nextTrain;
+ VectorCopy( next->s.origin, ent->pos1 );
+ VectorCopy( next->nextTrain->s.origin, ent->pos2 );
+
+ // if the path_corner has a speed, use that
+ if ( next->speed ) {
+ speed = next->speed;
+ } else {
+ // otherwise use the train's speed
+ speed = ent->speed;
+ }
+ if ( speed < 1 ) {
+ speed = 1;
+ }
+
+ // calculate duration
+ VectorSubtract( ent->pos2, ent->pos1, move );
+ length = VectorLength( move );
+
+ ent->s.pos.trDuration = length * 1000 / speed;
+
+ // looping sound
+ ent->s.loopSound = next->soundLoop;
+
+ // start it going
+ SetMoverState( ent, MOVER_1TO2, level.time );
+
+ // if there is a "wait" value on the target, don't start moving yet
+ if ( next->wait ) {
+ ent->nextthink = level.time + next->wait * 1000;
+ ent->think = Think_BeginMoving;
+ ent->s.pos.trType = TR_STATIONARY;
+ }
+}
+
+
+/*
+===============
+Think_SetupTrainTargets
+
+Link all the corners together
+===============
+*/
+void Think_SetupTrainTargets( gentity_t *ent ) {
+ gentity_t *path, *next, *start;
+
+ ent->nextTrain = G_Find( NULL, FOFS(targetname), ent->target );
+ if ( !ent->nextTrain ) {
+ G_Printf( "func_train at %s with an unfound target\n",
+ vtos(ent->r.absmin) );
+ return;
+ }
+
+ start = NULL;
+ for ( path = ent->nextTrain ; path != start ; path = next ) {
+ if ( !start ) {
+ start = path;
+ }
+
+ if ( !path->target ) {
+ G_Printf( "Train corner at %s without a target\n",
+ vtos(path->s.origin) );
+ return;
+ }
+
+ // find a path_corner among the targets
+ // there may also be other targets that get fired when the corner
+ // is reached
+ next = NULL;
+ do {
+ next = G_Find( next, FOFS(targetname), path->target );
+ if ( !next ) {
+ G_Printf( "Train corner at %s without a target path_corner\n",
+ vtos(path->s.origin) );
+ return;
+ }
+ } while ( strcmp( next->classname, "path_corner" ) );
+
+ path->nextTrain = next;
+ }
+
+ // start the train moving from the first corner
+ Reached_Train( ent );
+}
+
+
+
+/*QUAKED path_corner (.5 .3 0) (-8 -8 -8) (8 8 8)
+Train path corners.
+Target: next path corner and other targets to fire
+"speed" speed to move to the next corner
+"wait" seconds to wait before behining move to next corner
+*/
+void SP_path_corner( gentity_t *self ) {
+ if ( !self->targetname ) {
+ G_Printf ("path_corner with no targetname at %s\n", vtos(self->s.origin));
+ G_FreeEntity( self );
+ return;
+ }
+ // path corners don't need to be linked in
+}
+
+
+
+/*QUAKED func_train (0 .5 .8) ? START_ON TOGGLE BLOCK_STOPS
+A train is a mover that moves between path_corner target points.
+Trains MUST HAVE AN ORIGIN BRUSH.
+The train spawns at the first target it is pointing at.
+"model2" .md3 model to also draw
+"speed" default 100
+"dmg" default 2
+"noise" looping sound to play when the train is in motion
+"target" next path corner
+"color" constantLight color
+"light" constantLight radius
+*/
+void SP_func_train (gentity_t *self) {
+ VectorClear (self->s.angles);
+
+ if (self->spawnflags & TRAIN_BLOCK_STOPS) {
+ self->damage = 0;
+ } else {
+ if (!self->damage) {
+ self->damage = 2;
+ }
+ }
+
+ if ( !self->speed ) {
+ self->speed = 100;
+ }
+
+ if ( !self->target ) {
+ G_Printf ("func_train without a target at %s\n", vtos(self->r.absmin));
+ G_FreeEntity( self );
+ return;
+ }
+
+ trap_SetBrushModel( self, self->model );
+ InitMover( self );
+
+ self->reached = Reached_Train;
+
+ // start trains on the second frame, to make sure their targets have had
+ // a chance to spawn
+ self->nextthink = level.time + FRAMETIME;
+ self->think = Think_SetupTrainTargets;
+}
+
+/*
+===============================================================================
+
+STATIC
+
+===============================================================================
+*/
+
+
+/*QUAKED func_static (0 .5 .8) ?
+A bmodel that just sits there, doing nothing. Can be used for conditional walls and models.
+"model2" .md3 model to also draw
+"color" constantLight color
+"light" constantLight radius
+*/
+void SP_func_static( gentity_t *ent ) {
+ trap_SetBrushModel( ent, ent->model );
+ InitMover( ent );
+ VectorCopy( ent->s.origin, ent->s.pos.trBase );
+ VectorCopy( ent->s.origin, ent->r.currentOrigin );
+}
+
+
+/*
+===============================================================================
+
+ROTATING
+
+===============================================================================
+*/
+
+
+/*QUAKED func_rotating (0 .5 .8) ? START_ON - X_AXIS Y_AXIS
+You need to have an origin brush as part of this entity. The center of that brush will be
+the point around which it is rotated. It will rotate around the Z axis by default. You can
+check either the X_AXIS or Y_AXIS box to change that.
+
+"model2" .md3 model to also draw
+"speed" determines how fast it moves; default value is 100.
+"dmg" damage to inflict when blocked (2 default)
+"color" constantLight color
+"light" constantLight radius
+*/
+void SP_func_rotating (gentity_t *ent) {
+ if ( !ent->speed ) {
+ ent->speed = 100;
+ }
+
+ // set the axis of rotation
+ ent->s.apos.trType = TR_LINEAR;
+ if ( ent->spawnflags & 4 ) {
+ ent->s.apos.trDelta[2] = ent->speed;
+ } else if ( ent->spawnflags & 8 ) {
+ ent->s.apos.trDelta[0] = ent->speed;
+ } else {
+ ent->s.apos.trDelta[1] = ent->speed;
+ }
+
+ if (!ent->damage) {
+ ent->damage = 2;
+ }
+
+ trap_SetBrushModel( ent, ent->model );
+ InitMover( ent );
+
+ VectorCopy( ent->s.origin, ent->s.pos.trBase );
+ VectorCopy( ent->s.pos.trBase, ent->r.currentOrigin );
+ VectorCopy( ent->s.apos.trBase, ent->r.currentAngles );
+
+ trap_LinkEntity( ent );
+}
+
+
+/*
+===============================================================================
+
+BOBBING
+
+===============================================================================
+*/
+
+
+/*QUAKED func_bobbing (0 .5 .8) ? X_AXIS Y_AXIS
+Normally bobs on the Z axis
+"model2" .md3 model to also draw
+"height" amplitude of bob (32 default)
+"speed" seconds to complete a bob cycle (4 default)
+"phase" the 0.0 to 1.0 offset in the cycle to start at
+"dmg" damage to inflict when blocked (2 default)
+"color" constantLight color
+"light" constantLight radius
+*/
+void SP_func_bobbing (gentity_t *ent) {
+ float height;
+ float phase;
+
+ G_SpawnFloat( "speed", "4", &ent->speed );
+ G_SpawnFloat( "height", "32", &height );
+ G_SpawnInt( "dmg", "2", &ent->damage );
+ G_SpawnFloat( "phase", "0", &phase );
+
+ trap_SetBrushModel( ent, ent->model );
+ InitMover( ent );
+
+ VectorCopy( ent->s.origin, ent->s.pos.trBase );
+ VectorCopy( ent->s.origin, ent->r.currentOrigin );
+
+ ent->s.pos.trDuration = ent->speed * 1000;
+ ent->s.pos.trTime = ent->s.pos.trDuration * phase;
+ ent->s.pos.trType = TR_SINE;
+
+ // set the axis of bobbing
+ if ( ent->spawnflags & 1 ) {
+ ent->s.pos.trDelta[0] = height;
+ } else if ( ent->spawnflags & 2 ) {
+ ent->s.pos.trDelta[1] = height;
+ } else {
+ ent->s.pos.trDelta[2] = height;
+ }
+}
+
+/*
+===============================================================================
+
+PENDULUM
+
+===============================================================================
+*/
+
+
+/*QUAKED func_pendulum (0 .5 .8) ?
+You need to have an origin brush as part of this entity.
+Pendulums always swing north / south on unrotated models. Add an angles field to the model to allow rotation in other directions.
+Pendulum frequency is a physical constant based on the length of the beam and gravity.
+"model2" .md3 model to also draw
+"speed" the number of degrees each way the pendulum swings, (30 default)
+"phase" the 0.0 to 1.0 offset in the cycle to start at
+"dmg" damage to inflict when blocked (2 default)
+"color" constantLight color
+"light" constantLight radius
+*/
+void SP_func_pendulum(gentity_t *ent) {
+ float freq;
+ float length;
+ float phase;
+ float speed;
+
+ G_SpawnFloat( "speed", "30", &speed );
+ G_SpawnInt( "dmg", "2", &ent->damage );
+ G_SpawnFloat( "phase", "0", &phase );
+
+ trap_SetBrushModel( ent, ent->model );
+
+ // find pendulum length
+ length = fabs( ent->r.mins[2] );
+ if ( length < 8 ) {
+ length = 8;
+ }
+
+ freq = 1 / ( M_PI * 2 ) * sqrt( g_gravity.value / ( 3 * length ) );
+
+ ent->s.pos.trDuration = ( 1000 / freq );
+
+ InitMover( ent );
+
+ VectorCopy( ent->s.origin, ent->s.pos.trBase );
+ VectorCopy( ent->s.origin, ent->r.currentOrigin );
+
+ VectorCopy( ent->s.angles, ent->s.apos.trBase );
+
+ ent->s.apos.trDuration = 1000 / freq;
+ ent->s.apos.trTime = ent->s.apos.trDuration * phase;
+ ent->s.apos.trType = TR_SINE;
+ ent->s.apos.trDelta[2] = speed;
+}
diff --git a/code/game/g_public.h b/code/game/g_public.h
new file mode 100755
index 0000000..e2fc1c0
--- /dev/null
+++ b/code/game/g_public.h
@@ -0,0 +1,429 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+// g_public.h -- game module information visible to server
+
+#define GAME_API_VERSION 8
+
+// entity->svFlags
+// the server does not know how to interpret most of the values
+// in entityStates (level eType), so the game must explicitly flag
+// special server behaviors
+#define SVF_NOCLIENT 0x00000001 // don't send entity to clients, even if it has effects
+
+// TTimo
+// https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=551
+#define SVF_CLIENTMASK 0x00000002
+
+#define SVF_BOT 0x00000008 // set if the entity is a bot
+#define SVF_BROADCAST 0x00000020 // send to all connected clients
+#define SVF_PORTAL 0x00000040 // merge a second pvs at origin2 into snapshots
+#define SVF_USE_CURRENT_ORIGIN 0x00000080 // entity->r.currentOrigin instead of entity->s.origin
+ // for link position (missiles and movers)
+#define SVF_SINGLECLIENT 0x00000100 // only send to a single client (entityShared_t->singleClient)
+#define SVF_NOSERVERINFO 0x00000200 // don't send CS_SERVERINFO updates to this client
+ // so that it can be updated for ping tools without
+ // lagging clients
+#define SVF_CAPSULE 0x00000400 // use capsule for collision detection instead of bbox
+#define SVF_NOTSINGLECLIENT 0x00000800 // send entity to everyone but one client
+ // (entityShared_t->singleClient)
+
+
+
+//===============================================================
+
+
+typedef struct {
+ entityState_t s; // communicated by server to clients
+
+ qboolean linked; // qfalse if not in any good cluster
+ int linkcount;
+
+ int svFlags; // SVF_NOCLIENT, SVF_BROADCAST, etc
+
+ // only send to this client when SVF_SINGLECLIENT is set
+ // if SVF_CLIENTMASK is set, use bitmask for clients to send to (maxclients must be <= 32, up to the mod to enforce this)
+ int singleClient;
+
+ qboolean bmodel; // if false, assume an explicit mins / maxs bounding box
+ // only set by trap_SetBrushModel
+ vec3_t mins, maxs;
+ int contents; // CONTENTS_TRIGGER, CONTENTS_SOLID, CONTENTS_BODY, etc
+ // a non-solid entity should set to 0
+
+ vec3_t absmin, absmax; // derived from mins/maxs and origin + rotation
+
+ // currentOrigin will be used for all collision detection and world linking.
+ // it will not necessarily be the same as the trajectory evaluation for the current
+ // time, because each entity must be moved one at a time after time is advanced
+ // to avoid simultanious collision issues
+ vec3_t currentOrigin;
+ vec3_t currentAngles;
+
+ // when a trace call is made and passEntityNum != ENTITYNUM_NONE,
+ // an ent will be excluded from testing if:
+ // ent->s.number == passEntityNum (don't interact with self)
+ // ent->s.ownerNum = passEntityNum (don't interact with your own missiles)
+ // entity[ent->s.ownerNum].ownerNum = passEntityNum (don't interact with other missiles from owner)
+ int ownerNum;
+} entityShared_t;
+
+
+
+// the server looks at a sharedEntity, which is the start of the game's gentity_t structure
+typedef struct {
+ entityState_t s; // communicated by server to clients
+ entityShared_t r; // shared by both the server system and game
+} sharedEntity_t;
+
+
+
+//===============================================================
+
+//
+// system traps provided by the main engine
+//
+typedef enum {
+ //============== general Quake services ==================
+
+ G_PRINT, // ( const char *string );
+ // print message on the local console
+
+ G_ERROR, // ( const char *string );
+ // abort the game
+
+ G_MILLISECONDS, // ( void );
+ // get current time for profiling reasons
+ // this should NOT be used for any game related tasks,
+ // because it is not journaled
+
+ // console variable interaction
+ G_CVAR_REGISTER, // ( vmCvar_t *vmCvar, const char *varName, const char *defaultValue, int flags );
+ G_CVAR_UPDATE, // ( vmCvar_t *vmCvar );
+ G_CVAR_SET, // ( const char *var_name, const char *value );
+ G_CVAR_VARIABLE_INTEGER_VALUE, // ( const char *var_name );
+
+ G_CVAR_VARIABLE_STRING_BUFFER, // ( const char *var_name, char *buffer, int bufsize );
+
+ G_ARGC, // ( void );
+ // ClientCommand and ServerCommand parameter access
+
+ G_ARGV, // ( int n, char *buffer, int bufferLength );
+
+ G_FS_FOPEN_FILE, // ( const char *qpath, fileHandle_t *file, fsMode_t mode );
+ G_FS_READ, // ( void *buffer, int len, fileHandle_t f );
+ G_FS_WRITE, // ( const void *buffer, int len, fileHandle_t f );
+ G_FS_FCLOSE_FILE, // ( fileHandle_t f );
+
+ G_SEND_CONSOLE_COMMAND, // ( const char *text );
+ // add commands to the console as if they were typed in
+ // for map changing, etc
+
+
+ //=========== server specific functionality =============
+
+ G_LOCATE_GAME_DATA, // ( gentity_t *gEnts, int numGEntities, int sizeofGEntity_t,
+ // playerState_t *clients, int sizeofGameClient );
+ // the game needs to let the server system know where and how big the gentities
+ // are, so it can look at them directly without going through an interface
+
+ G_DROP_CLIENT, // ( int clientNum, const char *reason );
+ // kick a client off the server with a message
+
+ G_SEND_SERVER_COMMAND, // ( int clientNum, const char *fmt, ... );
+ // reliably sends a command string to be interpreted by the given
+ // client. If clientNum is -1, it will be sent to all clients
+
+ G_SET_CONFIGSTRING, // ( int num, const char *string );
+ // config strings hold all the index strings, and various other information
+ // that is reliably communicated to all clients
+ // All of the current configstrings are sent to clients when
+ // they connect, and changes are sent to all connected clients.
+ // All confgstrings are cleared at each level start.
+
+ G_GET_CONFIGSTRING, // ( int num, char *buffer, int bufferSize );
+
+ G_GET_USERINFO, // ( int num, char *buffer, int bufferSize );
+ // userinfo strings are maintained by the server system, so they
+ // are persistant across level loads, while all other game visible
+ // data is completely reset
+
+ G_SET_USERINFO, // ( int num, const char *buffer );
+
+ G_GET_SERVERINFO, // ( char *buffer, int bufferSize );
+ // the serverinfo info string has all the cvars visible to server browsers
+
+ G_SET_BRUSH_MODEL, // ( gentity_t *ent, const char *name );
+ // sets mins and maxs based on the brushmodel name
+
+ G_TRACE, // ( trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentmask );
+ // collision detection against all linked entities
+
+ G_POINT_CONTENTS, // ( const vec3_t point, int passEntityNum );
+ // point contents against all linked entities
+
+ G_IN_PVS, // ( const vec3_t p1, const vec3_t p2 );
+
+ G_IN_PVS_IGNORE_PORTALS, // ( const vec3_t p1, const vec3_t p2 );
+
+ G_ADJUST_AREA_PORTAL_STATE, // ( gentity_t *ent, qboolean open );
+
+ G_AREAS_CONNECTED, // ( int area1, int area2 );
+
+ G_LINKENTITY, // ( gentity_t *ent );
+ // an entity will never be sent to a client or used for collision
+ // if it is not passed to linkentity. If the size, position, or
+ // solidity changes, it must be relinked.
+
+ G_UNLINKENTITY, // ( gentity_t *ent );
+ // call before removing an interactive entity
+
+ G_ENTITIES_IN_BOX, // ( const vec3_t mins, const vec3_t maxs, gentity_t **list, int maxcount );
+ // EntitiesInBox will return brush models based on their bounding box,
+ // so exact determination must still be done with EntityContact
+
+ G_ENTITY_CONTACT, // ( const vec3_t mins, const vec3_t maxs, const gentity_t *ent );
+ // perform an exact check against inline brush models of non-square shape
+
+ // access for bots to get and free a server client (FIXME?)
+ G_BOT_ALLOCATE_CLIENT, // ( void );
+
+ G_BOT_FREE_CLIENT, // ( int clientNum );
+
+ G_GET_USERCMD, // ( int clientNum, usercmd_t *cmd )
+
+ G_GET_ENTITY_TOKEN, // qboolean ( char *buffer, int bufferSize )
+ // Retrieves the next string token from the entity spawn text, returning
+ // false when all tokens have been parsed.
+ // This should only be done at GAME_INIT time.
+
+ G_FS_GETFILELIST,
+ G_DEBUG_POLYGON_CREATE,
+ G_DEBUG_POLYGON_DELETE,
+ G_REAL_TIME,
+ G_SNAPVECTOR,
+
+ G_TRACECAPSULE, // ( trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentmask );
+ G_ENTITY_CONTACTCAPSULE, // ( const vec3_t mins, const vec3_t maxs, const gentity_t *ent );
+
+ // 1.32
+ G_FS_SEEK,
+
+ BOTLIB_SETUP = 200, // ( void );
+ BOTLIB_SHUTDOWN, // ( void );
+ BOTLIB_LIBVAR_SET,
+ BOTLIB_LIBVAR_GET,
+ BOTLIB_PC_ADD_GLOBAL_DEFINE,
+ BOTLIB_START_FRAME,
+ BOTLIB_LOAD_MAP,
+ BOTLIB_UPDATENTITY,
+ BOTLIB_TEST,
+
+ BOTLIB_GET_SNAPSHOT_ENTITY, // ( int client, int ent );
+ BOTLIB_GET_CONSOLE_MESSAGE, // ( int client, char *message, int size );
+ BOTLIB_USER_COMMAND, // ( int client, usercmd_t *ucmd );
+
+ BOTLIB_AAS_ENABLE_ROUTING_AREA = 300,
+ BOTLIB_AAS_BBOX_AREAS,
+ BOTLIB_AAS_AREA_INFO,
+ BOTLIB_AAS_ENTITY_INFO,
+
+ BOTLIB_AAS_INITIALIZED,
+ BOTLIB_AAS_PRESENCE_TYPE_BOUNDING_BOX,
+ BOTLIB_AAS_TIME,
+
+ BOTLIB_AAS_POINT_AREA_NUM,
+ BOTLIB_AAS_TRACE_AREAS,
+
+ BOTLIB_AAS_POINT_CONTENTS,
+ BOTLIB_AAS_NEXT_BSP_ENTITY,
+ BOTLIB_AAS_VALUE_FOR_BSP_EPAIR_KEY,
+ BOTLIB_AAS_VECTOR_FOR_BSP_EPAIR_KEY,
+ BOTLIB_AAS_FLOAT_FOR_BSP_EPAIR_KEY,
+ BOTLIB_AAS_INT_FOR_BSP_EPAIR_KEY,
+
+ BOTLIB_AAS_AREA_REACHABILITY,
+
+ BOTLIB_AAS_AREA_TRAVEL_TIME_TO_GOAL_AREA,
+
+ BOTLIB_AAS_SWIMMING,
+ BOTLIB_AAS_PREDICT_CLIENT_MOVEMENT,
+
+ BOTLIB_EA_SAY = 400,
+ BOTLIB_EA_SAY_TEAM,
+ BOTLIB_EA_COMMAND,
+
+ BOTLIB_EA_ACTION,
+ BOTLIB_EA_GESTURE,
+ BOTLIB_EA_TALK,
+ BOTLIB_EA_ATTACK,
+ BOTLIB_EA_USE,
+ BOTLIB_EA_RESPAWN,
+ BOTLIB_EA_CROUCH,
+ BOTLIB_EA_MOVE_UP,
+ BOTLIB_EA_MOVE_DOWN,
+ BOTLIB_EA_MOVE_FORWARD,
+ BOTLIB_EA_MOVE_BACK,
+ BOTLIB_EA_MOVE_LEFT,
+ BOTLIB_EA_MOVE_RIGHT,
+
+ BOTLIB_EA_SELECT_WEAPON,
+ BOTLIB_EA_JUMP,
+ BOTLIB_EA_DELAYED_JUMP,
+ BOTLIB_EA_MOVE,
+ BOTLIB_EA_VIEW,
+
+ BOTLIB_EA_END_REGULAR,
+ BOTLIB_EA_GET_INPUT,
+ BOTLIB_EA_RESET_INPUT,
+
+
+ BOTLIB_AI_LOAD_CHARACTER = 500,
+ BOTLIB_AI_FREE_CHARACTER,
+ BOTLIB_AI_CHARACTERISTIC_FLOAT,
+ BOTLIB_AI_CHARACTERISTIC_BFLOAT,
+ BOTLIB_AI_CHARACTERISTIC_INTEGER,
+ BOTLIB_AI_CHARACTERISTIC_BINTEGER,
+ BOTLIB_AI_CHARACTERISTIC_STRING,
+
+ BOTLIB_AI_ALLOC_CHAT_STATE,
+ BOTLIB_AI_FREE_CHAT_STATE,
+ BOTLIB_AI_QUEUE_CONSOLE_MESSAGE,
+ BOTLIB_AI_REMOVE_CONSOLE_MESSAGE,
+ BOTLIB_AI_NEXT_CONSOLE_MESSAGE,
+ BOTLIB_AI_NUM_CONSOLE_MESSAGE,
+ BOTLIB_AI_INITIAL_CHAT,
+ BOTLIB_AI_REPLY_CHAT,
+ BOTLIB_AI_CHAT_LENGTH,
+ BOTLIB_AI_ENTER_CHAT,
+ BOTLIB_AI_STRING_CONTAINS,
+ BOTLIB_AI_FIND_MATCH,
+ BOTLIB_AI_MATCH_VARIABLE,
+ BOTLIB_AI_UNIFY_WHITE_SPACES,
+ BOTLIB_AI_REPLACE_SYNONYMS,
+ BOTLIB_AI_LOAD_CHAT_FILE,
+ BOTLIB_AI_SET_CHAT_GENDER,
+ BOTLIB_AI_SET_CHAT_NAME,
+
+ BOTLIB_AI_RESET_GOAL_STATE,
+ BOTLIB_AI_RESET_AVOID_GOALS,
+ BOTLIB_AI_PUSH_GOAL,
+ BOTLIB_AI_POP_GOAL,
+ BOTLIB_AI_EMPTY_GOAL_STACK,
+ BOTLIB_AI_DUMP_AVOID_GOALS,
+ BOTLIB_AI_DUMP_GOAL_STACK,
+ BOTLIB_AI_GOAL_NAME,
+ BOTLIB_AI_GET_TOP_GOAL,
+ BOTLIB_AI_GET_SECOND_GOAL,
+ BOTLIB_AI_CHOOSE_LTG_ITEM,
+ BOTLIB_AI_CHOOSE_NBG_ITEM,
+ BOTLIB_AI_TOUCHING_GOAL,
+ BOTLIB_AI_ITEM_GOAL_IN_VIS_BUT_NOT_VISIBLE,
+ BOTLIB_AI_GET_LEVEL_ITEM_GOAL,
+ BOTLIB_AI_AVOID_GOAL_TIME,
+ BOTLIB_AI_INIT_LEVEL_ITEMS,
+ BOTLIB_AI_UPDATE_ENTITY_ITEMS,
+ BOTLIB_AI_LOAD_ITEM_WEIGHTS,
+ BOTLIB_AI_FREE_ITEM_WEIGHTS,
+ BOTLIB_AI_SAVE_GOAL_FUZZY_LOGIC,
+ BOTLIB_AI_ALLOC_GOAL_STATE,
+ BOTLIB_AI_FREE_GOAL_STATE,
+
+ BOTLIB_AI_RESET_MOVE_STATE,
+ BOTLIB_AI_MOVE_TO_GOAL,
+ BOTLIB_AI_MOVE_IN_DIRECTION,
+ BOTLIB_AI_RESET_AVOID_REACH,
+ BOTLIB_AI_RESET_LAST_AVOID_REACH,
+ BOTLIB_AI_REACHABILITY_AREA,
+ BOTLIB_AI_MOVEMENT_VIEW_TARGET,
+ BOTLIB_AI_ALLOC_MOVE_STATE,
+ BOTLIB_AI_FREE_MOVE_STATE,
+ BOTLIB_AI_INIT_MOVE_STATE,
+
+ BOTLIB_AI_CHOOSE_BEST_FIGHT_WEAPON,
+ BOTLIB_AI_GET_WEAPON_INFO,
+ BOTLIB_AI_LOAD_WEAPON_WEIGHTS,
+ BOTLIB_AI_ALLOC_WEAPON_STATE,
+ BOTLIB_AI_FREE_WEAPON_STATE,
+ BOTLIB_AI_RESET_WEAPON_STATE,
+
+ BOTLIB_AI_GENETIC_PARENTS_AND_CHILD_SELECTION,
+ BOTLIB_AI_INTERBREED_GOAL_FUZZY_LOGIC,
+ BOTLIB_AI_MUTATE_GOAL_FUZZY_LOGIC,
+ BOTLIB_AI_GET_NEXT_CAMP_SPOT_GOAL,
+ BOTLIB_AI_GET_MAP_LOCATION_GOAL,
+ BOTLIB_AI_NUM_INITIAL_CHATS,
+ BOTLIB_AI_GET_CHAT_MESSAGE,
+ BOTLIB_AI_REMOVE_FROM_AVOID_GOALS,
+ BOTLIB_AI_PREDICT_VISIBLE_POSITION,
+
+ BOTLIB_AI_SET_AVOID_GOAL_TIME,
+ BOTLIB_AI_ADD_AVOID_SPOT,
+ BOTLIB_AAS_ALTERNATIVE_ROUTE_GOAL,
+ BOTLIB_AAS_PREDICT_ROUTE,
+ BOTLIB_AAS_POINT_REACHABILITY_AREA_INDEX,
+
+ BOTLIB_PC_LOAD_SOURCE,
+ BOTLIB_PC_FREE_SOURCE,
+ BOTLIB_PC_READ_TOKEN,
+ BOTLIB_PC_SOURCE_FILE_AND_LINE
+
+} gameImport_t;
+
+
+//
+// functions exported by the game subsystem
+//
+typedef enum {
+ GAME_INIT, // ( int levelTime, int randomSeed, int restart );
+ // init and shutdown will be called every single level
+ // The game should call G_GET_ENTITY_TOKEN to parse through all the
+ // entity configuration text and spawn gentities.
+
+ GAME_SHUTDOWN, // (void);
+
+ GAME_CLIENT_CONNECT, // ( int clientNum, qboolean firstTime, qboolean isBot );
+ // return NULL if the client is allowed to connect, otherwise return
+ // a text string with the reason for denial
+
+ GAME_CLIENT_BEGIN, // ( int clientNum );
+
+ GAME_CLIENT_USERINFO_CHANGED, // ( int clientNum );
+
+ GAME_CLIENT_DISCONNECT, // ( int clientNum );
+
+ GAME_CLIENT_COMMAND, // ( int clientNum );
+
+ GAME_CLIENT_THINK, // ( int clientNum );
+
+ GAME_RUN_FRAME, // ( int levelTime );
+
+ GAME_CONSOLE_COMMAND, // ( void );
+ // ConsoleCommand will be called when a command has been issued
+ // that is not recognized as a builtin function.
+ // The game can issue trap_argc() / trap_argv() commands to get the command
+ // and parameters. Return qfalse if the game doesn't recognize it as a command.
+
+ BOTAI_START_FRAME // ( int time );
+} gameExport_t;
+
diff --git a/code/game/g_rankings.c b/code/game/g_rankings.c
new file mode 100755
index 0000000..b50c355
--- /dev/null
+++ b/code/game/g_rankings.c
@@ -0,0 +1,1135 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// g_rankings.c -- reports for global rankings system
+
+#include "g_local.h"
+#include "g_rankings.h"
+
+/*
+================
+G_RankRunFrame
+================
+*/
+void G_RankRunFrame()
+{
+ gentity_t* ent;
+ gentity_t* ent2;
+ grank_status_t old_status;
+ grank_status_t status;
+ int time;
+ int i;
+ int j;
+
+ if( !trap_RankCheckInit() )
+ {
+ trap_RankBegin( GR_GAMEKEY );
+ }
+
+ trap_RankPoll();
+
+ if( trap_RankActive() )
+ {
+ for( i = 0; i < level.maxclients; i++ )
+ {
+ ent = &(g_entities[i]);
+ if ( !ent->inuse )
+ continue;
+ if ( ent->client == NULL )
+ continue;
+ if ( ent->r.svFlags & SVF_BOT)
+ {
+ // no bots in ranked games
+ trap_SendConsoleCommand( EXEC_INSERT, va("kick %s\n",
+ ent->client->pers.netname) );
+ continue;
+ }
+
+ old_status = ent->client->client_status;
+ status = trap_RankUserStatus( i );
+
+ if( ent->client->client_status != status )
+ {
+ // inform client of current status
+ // not needed for client side log in
+ trap_SendServerCommand( i, va("rank_status %i\n",status) );
+ if ( i == 0 )
+ {
+ int j = 0;
+ }
+ ent->client->client_status = status;
+ }
+
+ switch( status )
+ {
+ case QGR_STATUS_NEW:
+ case QGR_STATUS_SPECTATOR:
+ if( ent->client->sess.sessionTeam != TEAM_SPECTATOR )
+ {
+ ent->client->sess.sessionTeam = TEAM_SPECTATOR;
+ ent->client->sess.spectatorState = SPECTATOR_FREE;
+ ClientSpawn( ent );
+ // make sure by now CS_GRAND rankingsGameID is ready
+ trap_SendServerCommand( i, va("rank_status %i\n",status) );
+ trap_SendServerCommand( i, "rank_menu\n" );
+ }
+ break;
+ case QGR_STATUS_NO_USER:
+ case QGR_STATUS_BAD_PASSWORD:
+ case QGR_STATUS_TIMEOUT:
+ case QGR_STATUS_NO_MEMBERSHIP:
+ case QGR_STATUS_INVALIDUSER:
+ case QGR_STATUS_ERROR:
+ if( (ent->r.svFlags & SVF_BOT) == 0 )
+ {
+ trap_RankUserReset( ent->s.clientNum );
+ }
+ break;
+ case QGR_STATUS_ACTIVE:
+ if( (ent->client->sess.sessionTeam == TEAM_SPECTATOR) &&
+ (g_gametype.integer < GT_TEAM) )
+ {
+ SetTeam( ent, "free" );
+ }
+
+ if( old_status != QGR_STATUS_ACTIVE )
+ {
+ // player has just become active
+ for( j = 0; j < level.maxclients; j++ )
+ {
+ ent2 = &(g_entities[j]);
+ if ( !ent2->inuse )
+ continue;
+ if ( ent2->client == NULL )
+ continue;
+ if ( ent2->r.svFlags & SVF_BOT)
+ continue;
+
+ if( (i != j) && (trap_RankUserStatus( j ) == QGR_STATUS_ACTIVE) )
+ {
+ trap_RankReportInt( i, j, QGR_KEY_PLAYED_WITH, 1, 0 );
+ }
+
+ // send current scores so the player's rank will show
+ // up under the crosshair immediately
+ DeathmatchScoreboardMessage( ent2 );
+ }
+ }
+ break;
+ default:
+ break;
+ }
+ }
+
+ // don't let ranked games last forever
+ if( ((g_fraglimit.integer == 0) || (g_fraglimit.integer > 100)) &&
+ ((g_timelimit.integer == 0) || (g_timelimit.integer > 1000)) )
+ {
+ trap_Cvar_Set( "timelimit", "1000" );
+ }
+ }
+
+ // tell time to clients so they can show current match rating
+ if( level.intermissiontime == 0 )
+ {
+ for( i = 0; i < level.maxclients; i++ )
+ {
+ ent = &(g_entities[i]);
+ if( ent->client == NULL )
+ {
+ continue;
+ }
+
+ time = (level.time - ent->client->pers.enterTime) / 1000;
+ ent->client->ps.persistant[PERS_MATCH_TIME] = time;
+ }
+ }
+}
+
+/*
+================
+G_RankFireWeapon
+================
+*/
+void G_RankFireWeapon( int self, int weapon )
+{
+ if( level.warmupTime != 0 )
+ {
+ // no reports during warmup period
+ return;
+ }
+
+ if( weapon == WP_GAUNTLET )
+ {
+ // the gauntlet only "fires" when it actually hits something
+ return;
+ }
+
+ trap_RankReportInt( self, -1, QGR_KEY_SHOT_FIRED, 1, 1 );
+
+ switch( weapon )
+ {
+ case WP_MACHINEGUN:
+ trap_RankReportInt( self, -1, QGR_KEY_SHOT_FIRED_MACHINEGUN, 1, 1 );
+ break;
+ case WP_SHOTGUN:
+ trap_RankReportInt( self, -1, QGR_KEY_SHOT_FIRED_SHOTGUN, 1, 1 );
+ break;
+ case WP_GRENADE_LAUNCHER:
+ trap_RankReportInt( self, -1, QGR_KEY_SHOT_FIRED_GRENADE, 1, 1 );
+ break;
+ case WP_ROCKET_LAUNCHER:
+ trap_RankReportInt( self, -1, QGR_KEY_SHOT_FIRED_ROCKET, 1, 1 );
+ break;
+ case WP_LIGHTNING:
+ trap_RankReportInt( self, -1, QGR_KEY_SHOT_FIRED_LIGHTNING, 1, 1 );
+ break;
+ case WP_RAILGUN:
+ trap_RankReportInt( self, -1, QGR_KEY_SHOT_FIRED_RAILGUN, 1, 1 );
+ break;
+ case WP_PLASMAGUN:
+ trap_RankReportInt( self, -1, QGR_KEY_SHOT_FIRED_PLASMA, 1, 1 );
+ break;
+ case WP_BFG:
+ trap_RankReportInt( self, -1, QGR_KEY_SHOT_FIRED_BFG, 1, 1 );
+ break;
+ case WP_GRAPPLING_HOOK:
+ trap_RankReportInt( self, -1, QGR_KEY_SHOT_FIRED_GRAPPLE, 1, 1 );
+ break;
+ default:
+ break;
+ }
+}
+
+/*
+================
+G_RankDamage
+================
+*/
+void G_RankDamage( int self, int attacker, int damage, int means_of_death )
+{
+ // state information to avoid counting each shotgun pellet as a hit
+ static int last_framenum = -1;
+ static int last_self = -1;
+ static int last_attacker = -1;
+ static int last_means_of_death = MOD_UNKNOWN;
+
+ qboolean new_hit;
+ int splash;
+ int key_hit;
+ int key_damage;
+ int key_splash;
+
+ if( level.warmupTime != 0 )
+ {
+ // no reports during warmup period
+ return;
+ }
+
+ new_hit = (level.framenum != last_framenum) ||
+ (self != last_self) ||
+ (attacker != last_attacker) ||
+ (means_of_death != last_means_of_death);
+
+ // update state information
+ last_framenum = level.framenum;
+ last_self = self;
+ last_attacker = attacker;
+ last_means_of_death = means_of_death;
+
+ // the gauntlet only "fires" when it actually hits something
+ if( (attacker != ENTITYNUM_WORLD) && (attacker != self) &&
+ (means_of_death == MOD_GAUNTLET) &&
+ (g_entities[attacker].client) )
+ {
+ trap_RankReportInt( attacker, -1, QGR_KEY_SHOT_FIRED_GAUNTLET, 1, 1 );
+ }
+
+ // don't track hazard damage, just deaths
+ switch( means_of_death )
+ {
+ case MOD_WATER:
+ case MOD_SLIME:
+ case MOD_LAVA:
+ case MOD_CRUSH:
+ case MOD_TELEFRAG:
+ case MOD_FALLING:
+ case MOD_SUICIDE:
+ case MOD_TRIGGER_HURT:
+ return;
+ default:
+ break;
+ }
+
+ // get splash damage
+ switch( means_of_death )
+ {
+ case MOD_GRENADE_SPLASH:
+ case MOD_ROCKET_SPLASH:
+ case MOD_PLASMA_SPLASH:
+ case MOD_BFG_SPLASH:
+ splash = damage;
+ break;
+ default:
+ splash = 0;
+ key_splash = -1;
+ break;
+ }
+
+ // hit, damage, and splash taken
+ switch( means_of_death )
+ {
+ case MOD_GAUNTLET:
+ key_hit = QGR_KEY_HIT_TAKEN_GAUNTLET;
+ key_damage = QGR_KEY_DAMAGE_TAKEN_GAUNTLET;
+ break;
+ case MOD_MACHINEGUN:
+ key_hit = QGR_KEY_HIT_TAKEN_MACHINEGUN;
+ key_damage = QGR_KEY_DAMAGE_TAKEN_MACHINEGUN;
+ break;
+ case MOD_SHOTGUN:
+ key_hit = QGR_KEY_HIT_TAKEN_SHOTGUN;
+ key_damage = QGR_KEY_DAMAGE_TAKEN_SHOTGUN;
+ break;
+ case MOD_GRENADE:
+ case MOD_GRENADE_SPLASH:
+ key_hit = QGR_KEY_HIT_TAKEN_GRENADE;
+ key_damage = QGR_KEY_DAMAGE_TAKEN_GRENADE;
+ key_splash = QGR_KEY_SPLASH_TAKEN_GRENADE;
+ break;
+ case MOD_ROCKET:
+ case MOD_ROCKET_SPLASH:
+ key_hit = QGR_KEY_HIT_TAKEN_ROCKET;
+ key_damage = QGR_KEY_DAMAGE_TAKEN_ROCKET;
+ key_splash = QGR_KEY_SPLASH_TAKEN_ROCKET;
+ break;
+ case MOD_PLASMA:
+ case MOD_PLASMA_SPLASH:
+ key_hit = QGR_KEY_HIT_TAKEN_PLASMA;
+ key_damage = QGR_KEY_DAMAGE_TAKEN_PLASMA;
+ key_splash = QGR_KEY_SPLASH_TAKEN_PLASMA;
+ break;
+ case MOD_RAILGUN:
+ key_hit = QGR_KEY_HIT_TAKEN_RAILGUN;
+ key_damage = QGR_KEY_DAMAGE_TAKEN_RAILGUN;
+ break;
+ case MOD_LIGHTNING:
+ key_hit = QGR_KEY_HIT_TAKEN_LIGHTNING;
+ key_damage = QGR_KEY_DAMAGE_TAKEN_LIGHTNING;
+ break;
+ case MOD_BFG:
+ case MOD_BFG_SPLASH:
+ key_hit = QGR_KEY_HIT_TAKEN_BFG;
+ key_damage = QGR_KEY_DAMAGE_TAKEN_BFG;
+ key_splash = QGR_KEY_SPLASH_TAKEN_BFG;
+ break;
+ case MOD_GRAPPLE:
+ key_hit = QGR_KEY_HIT_TAKEN_GRAPPLE;
+ key_damage = QGR_KEY_DAMAGE_TAKEN_GRAPPLE;
+ break;
+ default:
+ key_hit = QGR_KEY_HIT_TAKEN_UNKNOWN;
+ key_damage = QGR_KEY_DAMAGE_TAKEN_UNKNOWN;
+ break;
+ }
+
+ // report general and specific hit taken
+ if( new_hit )
+ {
+ trap_RankReportInt( self, -1, QGR_KEY_HIT_TAKEN, 1, 1 );
+ trap_RankReportInt( self, -1, key_hit, 1, 1 );
+ }
+
+ // report general and specific damage taken
+ trap_RankReportInt( self, -1, QGR_KEY_DAMAGE_TAKEN, damage, 1 );
+ trap_RankReportInt( self, -1, key_damage, damage, 1 );
+
+ // report general and specific splash taken
+ if( splash != 0 )
+ {
+ trap_RankReportInt( self, -1, QGR_KEY_SPLASH_TAKEN, splash, 1 );
+ trap_RankReportInt( self, -1, key_splash, splash, 1 );
+ }
+
+ // hit, damage, and splash given
+ if( (attacker != ENTITYNUM_WORLD) && (attacker != self) )
+ {
+ switch( means_of_death )
+ {
+ case MOD_GAUNTLET:
+ key_hit = QGR_KEY_HIT_GIVEN_GAUNTLET;
+ key_damage = QGR_KEY_DAMAGE_GIVEN_GAUNTLET;
+ break;
+ case MOD_MACHINEGUN:
+ key_hit = QGR_KEY_HIT_GIVEN_MACHINEGUN;
+ key_damage = QGR_KEY_DAMAGE_GIVEN_MACHINEGUN;
+ break;
+ case MOD_SHOTGUN:
+ key_hit = QGR_KEY_HIT_GIVEN_SHOTGUN;
+ key_damage = QGR_KEY_DAMAGE_GIVEN_SHOTGUN;
+ break;
+ case MOD_GRENADE:
+ case MOD_GRENADE_SPLASH:
+ key_hit = QGR_KEY_HIT_GIVEN_GRENADE;
+ key_damage = QGR_KEY_DAMAGE_GIVEN_GRENADE;
+ key_splash = QGR_KEY_SPLASH_GIVEN_GRENADE;
+ break;
+ case MOD_ROCKET:
+ case MOD_ROCKET_SPLASH:
+ key_hit = QGR_KEY_HIT_GIVEN_ROCKET;
+ key_damage = QGR_KEY_DAMAGE_GIVEN_ROCKET;
+ key_splash = QGR_KEY_SPLASH_GIVEN_ROCKET;
+ break;
+ case MOD_PLASMA:
+ case MOD_PLASMA_SPLASH:
+ key_hit = QGR_KEY_HIT_GIVEN_PLASMA;
+ key_damage = QGR_KEY_DAMAGE_GIVEN_PLASMA;
+ key_splash = QGR_KEY_SPLASH_GIVEN_PLASMA;
+ break;
+ case MOD_RAILGUN:
+ key_hit = QGR_KEY_HIT_GIVEN_RAILGUN;
+ key_damage = QGR_KEY_DAMAGE_GIVEN_RAILGUN;
+ break;
+ case MOD_LIGHTNING:
+ key_hit = QGR_KEY_HIT_GIVEN_LIGHTNING;
+ key_damage = QGR_KEY_DAMAGE_GIVEN_LIGHTNING;
+ break;
+ case MOD_BFG:
+ case MOD_BFG_SPLASH:
+ key_hit = QGR_KEY_HIT_GIVEN_BFG;
+ key_damage = QGR_KEY_DAMAGE_GIVEN_BFG;
+ key_splash = QGR_KEY_SPLASH_GIVEN_BFG;
+ break;
+ case MOD_GRAPPLE:
+ key_hit = QGR_KEY_HIT_GIVEN_GRAPPLE;
+ key_damage = QGR_KEY_DAMAGE_GIVEN_GRAPPLE;
+ break;
+ default:
+ key_hit = QGR_KEY_HIT_GIVEN_UNKNOWN;
+ key_damage = QGR_KEY_DAMAGE_GIVEN_UNKNOWN;
+ break;
+ }
+
+ // report general and specific hit given
+ // jwu 8/26/00
+ // had a case where attacker is 245 which is grnadeshooter attacker is
+ // g_entities index not necessarilly clientnum
+ if (g_entities[attacker].client) {
+ if( new_hit )
+ {
+ trap_RankReportInt( attacker, -1, QGR_KEY_HIT_GIVEN, 1, 1 );
+ trap_RankReportInt( attacker, -1, key_hit, 1, 1 );
+ }
+
+ // report general and specific damage given
+ trap_RankReportInt( attacker, -1, QGR_KEY_DAMAGE_GIVEN, damage, 1 );
+ trap_RankReportInt( attacker, -1, key_damage, damage, 1 );
+
+ // report general and specific splash given
+ if( splash != 0 )
+ {
+ trap_RankReportInt( attacker, -1, QGR_KEY_SPLASH_GIVEN, splash, 1 );
+ trap_RankReportInt( attacker, -1, key_splash, splash, 1 );
+ }
+ }
+ }
+
+ // friendly fire
+ if( (attacker != self) &&
+ OnSameTeam( &(g_entities[self]), &(g_entities[attacker])) &&
+ (g_entities[attacker].client) )
+ {
+ // report teammate hit
+ if( new_hit )
+ {
+ trap_RankReportInt( self, -1, QGR_KEY_TEAMMATE_HIT_TAKEN, 1, 1 );
+ trap_RankReportInt( attacker, -1, QGR_KEY_TEAMMATE_HIT_GIVEN, 1,
+ 1 );
+ }
+
+ // report teammate damage
+ trap_RankReportInt( self, -1, QGR_KEY_TEAMMATE_DAMAGE_TAKEN, damage,
+ 1 );
+ trap_RankReportInt( attacker, -1, QGR_KEY_TEAMMATE_DAMAGE_GIVEN,
+ damage, 1 );
+
+ // report teammate splash
+ if( splash != 0 )
+ {
+ trap_RankReportInt( self, -1, QGR_KEY_TEAMMATE_SPLASH_TAKEN,
+ splash, 1 );
+ trap_RankReportInt( attacker, -1, QGR_KEY_TEAMMATE_SPLASH_GIVEN,
+ splash, 1 );
+ }
+ }
+}
+
+/*
+================
+G_RankPlayerDie
+================
+*/
+void G_RankPlayerDie( int self, int attacker, int means_of_death )
+{
+ int p1;
+ int p2;
+
+ if( level.warmupTime != 0 )
+ {
+ // no reports during warmup period
+ return;
+ }
+
+ if( attacker == ENTITYNUM_WORLD )
+ {
+ p1 = self;
+ p2 = -1;
+
+ trap_RankReportInt( p1, p2, QGR_KEY_HAZARD_DEATH, 1, 1 );
+
+ switch( means_of_death )
+ {
+ case MOD_WATER:
+ trap_RankReportInt( p1, p2, QGR_KEY_WATER, 1, 1 );
+ break;
+ case MOD_SLIME:
+ trap_RankReportInt( p1, p2, QGR_KEY_SLIME, 1, 1 );
+ break;
+ case MOD_LAVA:
+ trap_RankReportInt( p1, p2, QGR_KEY_LAVA, 1, 1 );
+ break;
+ case MOD_CRUSH:
+ trap_RankReportInt( p1, p2, QGR_KEY_CRUSH, 1, 1 );
+ break;
+ case MOD_TELEFRAG:
+ trap_RankReportInt( p1, p2, QGR_KEY_TELEFRAG, 1, 1 );
+ break;
+ case MOD_FALLING:
+ trap_RankReportInt( p1, p2, QGR_KEY_FALLING, 1, 1 );
+ break;
+ case MOD_SUICIDE:
+ trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE_CMD, 1, 1 );
+ break;
+ case MOD_TRIGGER_HURT:
+ trap_RankReportInt( p1, p2, QGR_KEY_TRIGGER_HURT, 1, 1 );
+ break;
+ default:
+ trap_RankReportInt( p1, p2, QGR_KEY_HAZARD_MISC, 1, 1 );
+ break;
+ }
+ }
+ else if( attacker == self )
+ {
+ p1 = self;
+ p2 = -1;
+
+ trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE, 1, 1 );
+
+ switch( means_of_death )
+ {
+ case MOD_GAUNTLET:
+ trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE_GAUNTLET, 1, 1 );
+ break;
+ case MOD_MACHINEGUN:
+ trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE_MACHINEGUN, 1, 1 );
+ break;
+ case MOD_SHOTGUN:
+ trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE_SHOTGUN, 1, 1 );
+ break;
+ case MOD_GRENADE:
+ case MOD_GRENADE_SPLASH:
+ trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE_GRENADE, 1, 1 );
+ break;
+ case MOD_ROCKET:
+ case MOD_ROCKET_SPLASH:
+ trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE_ROCKET, 1, 1 );
+ break;
+ case MOD_PLASMA:
+ case MOD_PLASMA_SPLASH:
+ trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE_PLASMA, 1, 1 );
+ break;
+ case MOD_RAILGUN:
+ trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE_RAILGUN, 1, 1 );
+ break;
+ case MOD_LIGHTNING:
+ trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE_LIGHTNING, 1, 1 );
+ break;
+ case MOD_BFG:
+ case MOD_BFG_SPLASH:
+ trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE_BFG, 1, 1 );
+ break;
+ case MOD_GRAPPLE:
+ trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE_GRAPPLE, 1, 1 );
+ break;
+ default:
+ trap_RankReportInt( p1, p2, QGR_KEY_SUICIDE_UNKNOWN, 1, 1 );
+ break;
+ }
+ }
+ else
+ {
+ p1 = attacker;
+ p2 = self;
+
+ trap_RankReportInt( p1, p2, QGR_KEY_FRAG, 1, 1 );
+
+ switch( means_of_death )
+ {
+ case MOD_GAUNTLET:
+ trap_RankReportInt( p1, p2, QGR_KEY_FRAG_GAUNTLET, 1, 1 );
+ break;
+ case MOD_MACHINEGUN:
+ trap_RankReportInt( p1, p2, QGR_KEY_FRAG_MACHINEGUN, 1, 1 );
+ break;
+ case MOD_SHOTGUN:
+ trap_RankReportInt( p1, p2, QGR_KEY_FRAG_SHOTGUN, 1, 1 );
+ break;
+ case MOD_GRENADE:
+ case MOD_GRENADE_SPLASH:
+ trap_RankReportInt( p1, p2, QGR_KEY_FRAG_GRENADE, 1, 1 );
+ break;
+ case MOD_ROCKET:
+ case MOD_ROCKET_SPLASH:
+ trap_RankReportInt( p1, p2, QGR_KEY_FRAG_ROCKET, 1, 1 );
+ break;
+ case MOD_PLASMA:
+ case MOD_PLASMA_SPLASH:
+ trap_RankReportInt( p1, p2, QGR_KEY_FRAG_PLASMA, 1, 1 );
+ break;
+ case MOD_RAILGUN:
+ trap_RankReportInt( p1, p2, QGR_KEY_FRAG_RAILGUN, 1, 1 );
+ break;
+ case MOD_LIGHTNING:
+ trap_RankReportInt( p1, p2, QGR_KEY_FRAG_LIGHTNING, 1, 1 );
+ break;
+ case MOD_BFG:
+ case MOD_BFG_SPLASH:
+ trap_RankReportInt( p1, p2, QGR_KEY_FRAG_BFG, 1, 1 );
+ break;
+ case MOD_GRAPPLE:
+ trap_RankReportInt( p1, p2, QGR_KEY_FRAG_GRAPPLE, 1, 1 );
+ break;
+ default:
+ trap_RankReportInt( p1, p2, QGR_KEY_FRAG_UNKNOWN, 1, 1 );
+ break;
+ }
+ }
+}
+
+/*
+================
+G_RankWeaponTime
+================
+*/
+void G_RankWeaponTime( int self, int weapon )
+{
+ gclient_t* client;
+ int time;
+
+ if( level.warmupTime != 0 )
+ {
+ // no reports during warmup period
+ return;
+ }
+
+ client = g_entities[self].client;
+ time = (level.time - client->weapon_change_time) / 1000;
+ client->weapon_change_time = level.time;
+
+ if( time <= 0 )
+ {
+ return;
+ }
+
+ trap_RankReportInt( self, -1, QGR_KEY_TIME, time, 1 );
+
+ switch( weapon )
+ {
+ case WP_GAUNTLET:
+ trap_RankReportInt( self, -1, QGR_KEY_TIME_GAUNTLET, time, 1 );
+ break;
+ case WP_MACHINEGUN:
+ trap_RankReportInt( self, -1, QGR_KEY_TIME_MACHINEGUN, time, 1 );
+ break;
+ case WP_SHOTGUN:
+ trap_RankReportInt( self, -1, QGR_KEY_TIME_SHOTGUN, time, 1 );
+ break;
+ case WP_GRENADE_LAUNCHER:
+ trap_RankReportInt( self, -1, QGR_KEY_TIME_GRENADE, time, 1 );
+ break;
+ case WP_ROCKET_LAUNCHER:
+ trap_RankReportInt( self, -1, QGR_KEY_TIME_ROCKET, time, 1 );
+ break;
+ case WP_LIGHTNING:
+ trap_RankReportInt( self, -1, QGR_KEY_TIME_LIGHTNING, time, 1 );
+ break;
+ case WP_RAILGUN:
+ trap_RankReportInt( self, -1, QGR_KEY_TIME_RAILGUN, time, 1 );
+ break;
+ case WP_PLASMAGUN:
+ trap_RankReportInt( self, -1, QGR_KEY_TIME_PLASMA, time, 1 );
+ break;
+ case WP_BFG:
+ trap_RankReportInt( self, -1, QGR_KEY_TIME_BFG, time, 1 );
+ break;
+ case WP_GRAPPLING_HOOK:
+ trap_RankReportInt( self, -1, QGR_KEY_TIME_GRAPPLE, time, 1 );
+ break;
+ default:
+ break;
+ }
+}
+
+/*
+================
+G_RankPickupWeapon
+================
+*/
+void G_RankPickupWeapon( int self, int weapon )
+{
+ if( level.warmupTime != 0 )
+ {
+ // no reports during warmup period
+ return;
+ }
+
+ trap_RankReportInt( self, -1, QGR_KEY_PICKUP_WEAPON, 1, 1 );
+ switch( weapon )
+ {
+ case WP_GAUNTLET:
+ trap_RankReportInt( self, -1, QGR_KEY_PICKUP_GAUNTLET, 1, 1 );
+ break;
+ case WP_MACHINEGUN:
+ trap_RankReportInt( self, -1, QGR_KEY_PICKUP_MACHINEGUN, 1, 1 );
+ break;
+ case WP_SHOTGUN:
+ trap_RankReportInt( self, -1, QGR_KEY_PICKUP_SHOTGUN, 1, 1 );
+ break;
+ case WP_GRENADE_LAUNCHER:
+ trap_RankReportInt( self, -1, QGR_KEY_PICKUP_GRENADE, 1, 1 );
+ break;
+ case WP_ROCKET_LAUNCHER:
+ trap_RankReportInt( self, -1, QGR_KEY_PICKUP_ROCKET, 1, 1 );
+ break;
+ case WP_LIGHTNING:
+ trap_RankReportInt( self, -1, QGR_KEY_PICKUP_LIGHTNING, 1, 1 );
+ break;
+ case WP_RAILGUN:
+ trap_RankReportInt( self, -1, QGR_KEY_PICKUP_RAILGUN, 1, 1 );
+ break;
+ case WP_PLASMAGUN:
+ trap_RankReportInt( self, -1, QGR_KEY_PICKUP_PLASMA, 1, 1 );
+ break;
+ case WP_BFG:
+ trap_RankReportInt( self, -1, QGR_KEY_PICKUP_BFG, 1, 1 );
+ break;
+ case WP_GRAPPLING_HOOK:
+ trap_RankReportInt( self, -1, QGR_KEY_PICKUP_GRAPPLE, 1, 1 );
+ break;
+ default:
+ break;
+ }
+}
+
+/*
+================
+G_RankPickupAmmo
+================
+*/
+void G_RankPickupAmmo( int self, int weapon, int quantity )
+{
+ if( level.warmupTime != 0 )
+ {
+ // no reports during warmup period
+ return;
+ }
+
+ trap_RankReportInt( self, -1, QGR_KEY_BOXES, 1, 1 );
+ trap_RankReportInt( self, -1, QGR_KEY_ROUNDS, quantity, 1 );
+
+ switch( weapon )
+ {
+ case WP_MACHINEGUN:
+ trap_RankReportInt( self, -1, QGR_KEY_BOXES_BULLETS, 1, 1 );
+ trap_RankReportInt( self, -1, QGR_KEY_ROUNDS_BULLETS, quantity, 1 );
+ break;
+ case WP_SHOTGUN:
+ trap_RankReportInt( self, -1, QGR_KEY_BOXES_SHELLS, 1, 1 );
+ trap_RankReportInt( self, -1, QGR_KEY_ROUNDS_SHELLS, quantity, 1 );
+ break;
+ case WP_GRENADE_LAUNCHER:
+ trap_RankReportInt( self, -1, QGR_KEY_BOXES_GRENADES, 1, 1 );
+ trap_RankReportInt( self, -1, QGR_KEY_ROUNDS_GRENADES, quantity, 1 );
+ break;
+ case WP_ROCKET_LAUNCHER:
+ trap_RankReportInt( self, -1, QGR_KEY_BOXES_ROCKETS, 1, 1 );
+ trap_RankReportInt( self, -1, QGR_KEY_ROUNDS_ROCKETS, quantity, 1 );
+ break;
+ case WP_LIGHTNING:
+ trap_RankReportInt( self, -1, QGR_KEY_BOXES_LG_AMMO, 1, 1 );
+ trap_RankReportInt( self, -1, QGR_KEY_ROUNDS_LG_AMMO, quantity, 1 );
+ break;
+ case WP_RAILGUN:
+ trap_RankReportInt( self, -1, QGR_KEY_BOXES_SLUGS, 1, 1 );
+ trap_RankReportInt( self, -1, QGR_KEY_ROUNDS_SLUGS, quantity, 1 );
+ break;
+ case WP_PLASMAGUN:
+ trap_RankReportInt( self, -1, QGR_KEY_BOXES_CELLS, 1, 1 );
+ trap_RankReportInt( self, -1, QGR_KEY_ROUNDS_CELLS, quantity, 1 );
+ break;
+ case WP_BFG:
+ trap_RankReportInt( self, -1, QGR_KEY_BOXES_BFG_AMMO, 1, 1 );
+ trap_RankReportInt( self, -1, QGR_KEY_ROUNDS_BFG_AMMO, quantity, 1 );
+ break;
+ default:
+ break;
+ }
+}
+
+/*
+================
+G_RankPickupHealth
+================
+*/
+void G_RankPickupHealth( int self, int quantity )
+{
+ if( level.warmupTime != 0 )
+ {
+ // no reports during warmup period
+ return;
+ }
+
+ trap_RankReportInt( self, -1, QGR_KEY_HEALTH, 1, 1 );
+ trap_RankReportInt( self, -1, QGR_KEY_HEALTH_TOTAL, quantity, 1 );
+
+ switch( quantity )
+ {
+ case 5:
+ trap_RankReportInt( self, -1, QGR_KEY_HEALTH_5, 1, 1 );
+ break;
+ case 25:
+ trap_RankReportInt( self, -1, QGR_KEY_HEALTH_25, 1, 1 );
+ break;
+ case 50:
+ trap_RankReportInt( self, -1, QGR_KEY_HEALTH_50, 1, 1 );
+ break;
+ case 100:
+ trap_RankReportInt( self, -1, QGR_KEY_HEALTH_MEGA, 1, 1 );
+ break;
+ default:
+ break;
+ }
+}
+
+/*
+================
+G_RankPickupArmor
+================
+*/
+void G_RankPickupArmor( int self, int quantity )
+{
+ if( level.warmupTime != 0 )
+ {
+ // no reports during warmup period
+ return;
+ }
+
+ trap_RankReportInt( self, -1, QGR_KEY_ARMOR, 1, 1 );
+ trap_RankReportInt( self, -1, QGR_KEY_ARMOR_TOTAL, quantity, 1 );
+
+ switch( quantity )
+ {
+ case 5:
+ trap_RankReportInt( self, -1, QGR_KEY_ARMOR_SHARD, 1, 1 );
+ break;
+ case 50:
+ trap_RankReportInt( self, -1, QGR_KEY_ARMOR_YELLOW, 1, 1 );
+ break;
+ case 100:
+ trap_RankReportInt( self, -1, QGR_KEY_ARMOR_RED, 1, 1 );
+ break;
+ default:
+ break;
+ }
+}
+
+/*
+================
+G_RankPickupPowerup
+================
+*/
+void G_RankPickupPowerup( int self, int powerup )
+{
+ if( level.warmupTime != 0 )
+ {
+ // no reports during warmup period
+ return;
+ }
+
+ // ctf flags are treated as powerups
+ if( (powerup == PW_REDFLAG) || (powerup == PW_BLUEFLAG) )
+ {
+ trap_RankReportInt( self, -1, QGR_KEY_FLAG_PICKUP, 1, 1 );
+ return;
+ }
+
+ trap_RankReportInt( self, -1, QGR_KEY_POWERUP, 1, 1 );
+
+ switch( powerup )
+ {
+ case PW_QUAD:
+ trap_RankReportInt( self, -1, QGR_KEY_QUAD, 1, 1 );
+ break;
+ case PW_BATTLESUIT:
+ trap_RankReportInt( self, -1, QGR_KEY_SUIT, 1, 1 );
+ break;
+ case PW_HASTE:
+ trap_RankReportInt( self, -1, QGR_KEY_HASTE, 1, 1 );
+ break;
+ case PW_INVIS:
+ trap_RankReportInt( self, -1, QGR_KEY_INVIS, 1, 1 );
+ break;
+ case PW_REGEN:
+ trap_RankReportInt( self, -1, QGR_KEY_REGEN, 1, 1 );
+ break;
+ case PW_FLIGHT:
+ trap_RankReportInt( self, -1, QGR_KEY_FLIGHT, 1, 1 );
+ break;
+ default:
+ break;
+ }
+}
+
+/*
+================
+G_RankPickupHoldable
+================
+*/
+void G_RankPickupHoldable( int self, int holdable )
+{
+ if( level.warmupTime != 0 )
+ {
+ // no reports during warmup period
+ return;
+ }
+
+ switch( holdable )
+ {
+ case HI_MEDKIT:
+ trap_RankReportInt( self, -1, QGR_KEY_MEDKIT, 1, 1 );
+ break;
+ case HI_TELEPORTER:
+ trap_RankReportInt( self, -1, QGR_KEY_TELEPORTER, 1, 1 );
+ break;
+ default:
+ break;
+ }
+}
+
+/*
+================
+G_RankUseHoldable
+================
+*/
+void G_RankUseHoldable( int self, int holdable )
+{
+ if( level.warmupTime != 0 )
+ {
+ // no reports during warmup period
+ return;
+ }
+
+ switch( holdable )
+ {
+ case HI_MEDKIT:
+ trap_RankReportInt( self, -1, QGR_KEY_MEDKIT_USE, 1, 1 );
+ break;
+ case HI_TELEPORTER:
+ trap_RankReportInt( self, -1, QGR_KEY_TELEPORTER_USE, 1, 1 );
+ break;
+ default:
+ break;
+ }
+}
+
+/*
+================
+G_RankReward
+================
+*/
+void G_RankReward( int self, int award )
+{
+ if( level.warmupTime != 0 )
+ {
+ // no reports during warmup period
+ return;
+ }
+
+ switch( award )
+ {
+ case EF_AWARD_IMPRESSIVE:
+ trap_RankReportInt( self, -1, QGR_KEY_IMPRESSIVE, 1, 1 );
+ break;
+ case EF_AWARD_EXCELLENT:
+ trap_RankReportInt( self, -1, QGR_KEY_EXCELLENT, 1, 1 );
+ break;
+ default:
+ break;
+ }
+}
+
+/*
+================
+G_RankCapture
+================
+*/
+void G_RankCapture( int self )
+{
+ if( level.warmupTime != 0 )
+ {
+ // no reports during warmup period
+ return;
+ }
+
+ trap_RankReportInt( self, -1, QGR_KEY_FLAG_CAPTURE, 1, 1 );
+}
+
+/*
+================
+G_RankUserTeamName
+================
+*/
+void G_RankUserTeamName( int self, char* team_name )
+{
+ if( level.warmupTime != 0 )
+ {
+ // no reports during warmup period
+ return;
+ }
+
+ trap_RankReportStr( self, -1, QGR_KEY_TEAM_NAME, team_name );
+}
+
+/*
+================
+G_RankClientDisconnect
+================
+*/
+void G_RankClientDisconnect( int self )
+{
+ gclient_t* client;
+ int time;
+ int match_rating;
+
+ if( level.warmupTime != 0 )
+ {
+ // no reports during warmup period
+ return;
+ }
+
+ // match rating
+ client = g_entities[self].client;
+ time = (level.time - client->pers.enterTime) / 1000;
+ if( time < 60 )
+ {
+ match_rating = 0;
+ }
+ else
+ {
+ match_rating = client->ps.persistant[PERS_MATCH_RATING] / time;
+ }
+ trap_RankReportInt( self, -1, QGR_KEY_MATCH_RATING, match_rating, 0 );
+}
+
+/*
+================
+G_RankGameOver
+================
+*/
+void G_RankGameOver( void )
+{
+ int i;
+ char str[MAX_INFO_VALUE];
+ int num;
+
+ if( level.warmupTime != 0 )
+ {
+ // no reports during warmup period
+ return;
+ }
+
+ for( i = 0; i < level.maxclients; i++ )
+ {
+ if( trap_RankUserStatus( i ) == QGR_STATUS_ACTIVE )
+ {
+ G_RankClientDisconnect( i );
+ }
+ }
+
+ // hostname
+ trap_Cvar_VariableStringBuffer( "sv_hostname", str, sizeof(str) );
+ trap_RankReportStr( -1, -1, QGR_KEY_HOSTNAME, str );
+
+ // map
+ trap_Cvar_VariableStringBuffer( "mapname", str, sizeof(str) );
+ trap_RankReportStr( -1, -1, QGR_KEY_MAP, str );
+
+ // mod
+ trap_Cvar_VariableStringBuffer( "fs_game", str, sizeof(str) );
+ trap_RankReportStr( -1, -1, QGR_KEY_MOD, str );
+
+ // gametype
+ num = trap_Cvar_VariableIntegerValue("g_gametype");
+ trap_RankReportInt( -1, -1, QGR_KEY_GAMETYPE, num, 0 );
+
+ // fraglimit
+ num = trap_Cvar_VariableIntegerValue("fraglimit");
+ trap_RankReportInt( -1, -1, QGR_KEY_FRAGLIMIT, num, 0 );
+
+ // timelimit
+ num = trap_Cvar_VariableIntegerValue("timelimit");
+ trap_RankReportInt( -1, -1, QGR_KEY_TIMELIMIT, num, 0 );
+
+ // maxclients
+ num = trap_Cvar_VariableIntegerValue("sv_maxclients");
+ trap_RankReportInt( -1, -1, QGR_KEY_MAXCLIENTS, num, 0 );
+
+ // maxrate
+ num = trap_Cvar_VariableIntegerValue("sv_maxRate");
+ trap_RankReportInt( -1, -1, QGR_KEY_MAXRATE, num, 0 );
+
+ // minping
+ num = trap_Cvar_VariableIntegerValue("sv_minPing");
+ trap_RankReportInt( -1, -1, QGR_KEY_MINPING, num, 0 );
+
+ // maxping
+ num = trap_Cvar_VariableIntegerValue("sv_maxPing");
+ trap_RankReportInt( -1, -1, QGR_KEY_MAXPING, num, 0 );
+
+ // dedicated
+ num = trap_Cvar_VariableIntegerValue("dedicated");
+ trap_RankReportInt( -1, -1, QGR_KEY_DEDICATED, num, 0 );
+
+ // version
+ trap_Cvar_VariableStringBuffer( "version", str, sizeof(str) );
+ trap_RankReportStr( -1, -1, QGR_KEY_VERSION, str );
+}
+
diff --git a/code/game/g_rankings.h b/code/game/g_rankings.h
new file mode 100755
index 0000000..310c478
--- /dev/null
+++ b/code/game/g_rankings.h
@@ -0,0 +1,396 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// g_rankings.h -- score keys for global rankings
+
+#ifndef _G_RANKINGS_H_
+#define _G_RANKINGS_H_
+
+/*
+==============================================================================
+
+Key digits:
+ 10^9: report type
+ 1 = normal
+ 2 = developer-only
+ 10^8: stat type
+ 0 = match stat
+ 1 = single player stat
+ 2 = duel stat
+ 10^7: data type
+ 0 = string
+ 1 = uint32
+ 10^6: calculation
+ 0 = use raw value
+ 1 = add to total
+ 2 = average
+ 3 = max
+ 4 = min
+ 10^5
+ 10^4: category
+ 00 = general
+ 01 = session
+ 02 = weapon
+ 03 = ammo
+ 04 = health
+ 05 = armor
+ 06 = powerup
+ 07 = holdable
+ 08 = hazard
+ 09 = reward
+ 10 = teammate
+ 11 = ctf
+ 10^3:
+ 10^2: sub-category
+ 10^1:
+ 10^0: ordinal
+
+==============================================================================
+*/
+
+// general keys
+#define QGR_KEY_MATCH_RATING 1112000001
+#define QGR_KEY_PLAYED_WITH 1210000002
+
+// session keys
+#define QGR_KEY_HOSTNAME 1000010000
+#define QGR_KEY_MAP 1000010001
+#define QGR_KEY_MOD 1000010002
+#define QGR_KEY_GAMETYPE 1010010003
+#define QGR_KEY_FRAGLIMIT 1010010004
+#define QGR_KEY_TIMELIMIT 1010010005
+#define QGR_KEY_MAXCLIENTS 1010010006
+#define QGR_KEY_MAXRATE 1010010007
+#define QGR_KEY_MINPING 1010010008
+#define QGR_KEY_MAXPING 1010010009
+#define QGR_KEY_DEDICATED 1010010010
+#define QGR_KEY_VERSION 1000010011
+
+// weapon keys
+#define QGR_KEY_FRAG 1211020000
+#define QGR_KEY_SUICIDE 1111020001
+#define QGR_KEY_SHOT_FIRED 1111020002
+#define QGR_KEY_HIT_GIVEN 1111020003
+#define QGR_KEY_HIT_TAKEN 1111020004
+#define QGR_KEY_DAMAGE_GIVEN 1111020005
+#define QGR_KEY_DAMAGE_TAKEN 1111020006
+#define QGR_KEY_SPLASH_GIVEN 1111020007
+#define QGR_KEY_SPLASH_TAKEN 1111020008
+#define QGR_KEY_PICKUP_WEAPON 1111020009
+#define QGR_KEY_TIME 1111020010
+
+#define QGR_KEY_FRAG_GAUNTLET 1211020100
+#define QGR_KEY_SUICIDE_GAUNTLET 1111020101
+#define QGR_KEY_SHOT_FIRED_GAUNTLET 1111020102
+#define QGR_KEY_HIT_GIVEN_GAUNTLET 1111020103
+#define QGR_KEY_HIT_TAKEN_GAUNTLET 1111020104
+#define QGR_KEY_DAMAGE_GIVEN_GAUNTLET 1111020105
+#define QGR_KEY_DAMAGE_TAKEN_GAUNTLET 1111020106
+#define QGR_KEY_SPLASH_GIVEN_GAUNTLET 1111020107
+#define QGR_KEY_SPLASH_TAKEN_GAUNTLET 1111020108
+#define QGR_KEY_PICKUP_GAUNTLET 1111020109
+#define QGR_KEY_TIME_GAUNTLET 1111020110
+
+#define QGR_KEY_FRAG_MACHINEGUN 1211020200
+#define QGR_KEY_SUICIDE_MACHINEGUN 1111020201
+#define QGR_KEY_SHOT_FIRED_MACHINEGUN 1111020202
+#define QGR_KEY_HIT_GIVEN_MACHINEGUN 1111020203
+#define QGR_KEY_HIT_TAKEN_MACHINEGUN 1111020204
+#define QGR_KEY_DAMAGE_GIVEN_MACHINEGUN 1111020205
+#define QGR_KEY_DAMAGE_TAKEN_MACHINEGUN 1111020206
+#define QGR_KEY_SPLASH_GIVEN_MACHINEGUN 1111020207
+#define QGR_KEY_SPLASH_TAKEN_MACHINEGUN 1111020208
+#define QGR_KEY_PICKUP_MACHINEGUN 1111020209
+#define QGR_KEY_TIME_MACHINEGUN 1111020210
+
+#define QGR_KEY_FRAG_SHOTGUN 1211020300
+#define QGR_KEY_SUICIDE_SHOTGUN 1111020301
+#define QGR_KEY_SHOT_FIRED_SHOTGUN 1111020302
+#define QGR_KEY_HIT_GIVEN_SHOTGUN 1111020303
+#define QGR_KEY_HIT_TAKEN_SHOTGUN 1111020304
+#define QGR_KEY_DAMAGE_GIVEN_SHOTGUN 1111020305
+#define QGR_KEY_DAMAGE_TAKEN_SHOTGUN 1111020306
+#define QGR_KEY_SPLASH_GIVEN_SHOTGUN 1111020307
+#define QGR_KEY_SPLASH_TAKEN_SHOTGUN 1111020308
+#define QGR_KEY_PICKUP_SHOTGUN 1111020309
+#define QGR_KEY_TIME_SHOTGUN 1111020310
+
+#define QGR_KEY_FRAG_GRENADE 1211020400
+#define QGR_KEY_SUICIDE_GRENADE 1111020401
+#define QGR_KEY_SHOT_FIRED_GRENADE 1111020402
+#define QGR_KEY_HIT_GIVEN_GRENADE 1111020403
+#define QGR_KEY_HIT_TAKEN_GRENADE 1111020404
+#define QGR_KEY_DAMAGE_GIVEN_GRENADE 1111020405
+#define QGR_KEY_DAMAGE_TAKEN_GRENADE 1111020406
+#define QGR_KEY_SPLASH_GIVEN_GRENADE 1111020407
+#define QGR_KEY_SPLASH_TAKEN_GRENADE 1111020408
+#define QGR_KEY_PICKUP_GRENADE 1111020409
+#define QGR_KEY_TIME_GRENADE 1111020410
+
+#define QGR_KEY_FRAG_ROCKET 1211020500
+#define QGR_KEY_SUICIDE_ROCKET 1111020501
+#define QGR_KEY_SHOT_FIRED_ROCKET 1111020502
+#define QGR_KEY_HIT_GIVEN_ROCKET 1111020503
+#define QGR_KEY_HIT_TAKEN_ROCKET 1111020504
+#define QGR_KEY_DAMAGE_GIVEN_ROCKET 1111020505
+#define QGR_KEY_DAMAGE_TAKEN_ROCKET 1111020506
+#define QGR_KEY_SPLASH_GIVEN_ROCKET 1111020507
+#define QGR_KEY_SPLASH_TAKEN_ROCKET 1111020508
+#define QGR_KEY_PICKUP_ROCKET 1111020509
+#define QGR_KEY_TIME_ROCKET 1111020510
+
+#define QGR_KEY_FRAG_PLASMA 1211020600
+#define QGR_KEY_SUICIDE_PLASMA 1111020601
+#define QGR_KEY_SHOT_FIRED_PLASMA 1111020602
+#define QGR_KEY_HIT_GIVEN_PLASMA 1111020603
+#define QGR_KEY_HIT_TAKEN_PLASMA 1111020604
+#define QGR_KEY_DAMAGE_GIVEN_PLASMA 1111020605
+#define QGR_KEY_DAMAGE_TAKEN_PLASMA 1111020606
+#define QGR_KEY_SPLASH_GIVEN_PLASMA 1111020607
+#define QGR_KEY_SPLASH_TAKEN_PLASMA 1111020608
+#define QGR_KEY_PICKUP_PLASMA 1111020609
+#define QGR_KEY_TIME_PLASMA 1111020610
+
+#define QGR_KEY_FRAG_RAILGUN 1211020700
+#define QGR_KEY_SUICIDE_RAILGUN 1111020701
+#define QGR_KEY_SHOT_FIRED_RAILGUN 1111020702
+#define QGR_KEY_HIT_GIVEN_RAILGUN 1111020703
+#define QGR_KEY_HIT_TAKEN_RAILGUN 1111020704
+#define QGR_KEY_DAMAGE_GIVEN_RAILGUN 1111020705
+#define QGR_KEY_DAMAGE_TAKEN_RAILGUN 1111020706
+#define QGR_KEY_SPLASH_GIVEN_RAILGUN 1111020707
+#define QGR_KEY_SPLASH_TAKEN_RAILGUN 1111020708
+#define QGR_KEY_PICKUP_RAILGUN 1111020709
+#define QGR_KEY_TIME_RAILGUN 1111020710
+
+#define QGR_KEY_FRAG_LIGHTNING 1211020800
+#define QGR_KEY_SUICIDE_LIGHTNING 1111020801
+#define QGR_KEY_SHOT_FIRED_LIGHTNING 1111020802
+#define QGR_KEY_HIT_GIVEN_LIGHTNING 1111020803
+#define QGR_KEY_HIT_TAKEN_LIGHTNING 1111020804
+#define QGR_KEY_DAMAGE_GIVEN_LIGHTNING 1111020805
+#define QGR_KEY_DAMAGE_TAKEN_LIGHTNING 1111020806
+#define QGR_KEY_SPLASH_GIVEN_LIGHTNING 1111020807
+#define QGR_KEY_SPLASH_TAKEN_LIGHTNING 1111020808
+#define QGR_KEY_PICKUP_LIGHTNING 1111020809
+#define QGR_KEY_TIME_LIGHTNING 1111020810
+
+#define QGR_KEY_FRAG_BFG 1211020900
+#define QGR_KEY_SUICIDE_BFG 1111020901
+#define QGR_KEY_SHOT_FIRED_BFG 1111020902
+#define QGR_KEY_HIT_GIVEN_BFG 1111020903
+#define QGR_KEY_HIT_TAKEN_BFG 1111020904
+#define QGR_KEY_DAMAGE_GIVEN_BFG 1111020905
+#define QGR_KEY_DAMAGE_TAKEN_BFG 1111020906
+#define QGR_KEY_SPLASH_GIVEN_BFG 1111020907
+#define QGR_KEY_SPLASH_TAKEN_BFG 1111020908
+#define QGR_KEY_PICKUP_BFG 1111020909
+#define QGR_KEY_TIME_BFG 1111020910
+
+#define QGR_KEY_FRAG_GRAPPLE 1211021000
+#define QGR_KEY_SUICIDE_GRAPPLE 1111021001
+#define QGR_KEY_SHOT_FIRED_GRAPPLE 1111021002
+#define QGR_KEY_HIT_GIVEN_GRAPPLE 1111021003
+#define QGR_KEY_HIT_TAKEN_GRAPPLE 1111021004
+#define QGR_KEY_DAMAGE_GIVEN_GRAPPLE 1111021005
+#define QGR_KEY_DAMAGE_TAKEN_GRAPPLE 1111021006
+#define QGR_KEY_SPLASH_GIVEN_GRAPPLE 1111021007
+#define QGR_KEY_SPLASH_TAKEN_GRAPPLE 1111021008
+#define QGR_KEY_PICKUP_GRAPPLE 1111021009
+#define QGR_KEY_TIME_GRAPPLE 1111021010
+
+#define QGR_KEY_FRAG_UNKNOWN 1211021100
+#define QGR_KEY_SUICIDE_UNKNOWN 1111021101
+#define QGR_KEY_SHOT_FIRED_UNKNOWN 1111021102
+#define QGR_KEY_HIT_GIVEN_UNKNOWN 1111021103
+#define QGR_KEY_HIT_TAKEN_UNKNOWN 1111021104
+#define QGR_KEY_DAMAGE_GIVEN_UNKNOWN 1111021105
+#define QGR_KEY_DAMAGE_TAKEN_UNKNOWN 1111021106
+#define QGR_KEY_SPLASH_GIVEN_UNKNOWN 1111021107
+#define QGR_KEY_SPLASH_TAKEN_UNKNOWN 1111021108
+#define QGR_KEY_PICKUP_UNKNOWN 1111021109
+#define QGR_KEY_TIME_UNKNOWN 1111021110
+
+#ifdef MISSIONPACK
+// new to team arena
+#define QGR_KEY_FRAG_NAILGIN 1211021200
+#define QGR_KEY_SUICIDE_NAILGIN 1111021201
+#define QGR_KEY_SHOT_FIRED_NAILGIN 1111021202
+#define QGR_KEY_HIT_GIVEN_NAILGIN 1111021203
+#define QGR_KEY_HIT_TAKEN_NAILGIN 1111021204
+#define QGR_KEY_DAMAGE_GIVEN_NAILGIN 1111021205
+#define QGR_KEY_DAMAGE_TAKEN_NAILGIN 1111021206
+#define QGR_KEY_SPLASH_GIVEN_NAILGIN 1111021207
+#define QGR_KEY_SPLASH_TAKEN_NAILGIN 1111021208
+#define QGR_KEY_PICKUP_NAILGIN 1111021209
+#define QGR_KEY_TIME_NAILGIN 1111021210
+// new to team arena
+#define QGR_KEY_FRAG_PROX_LAUNCHER 1211021300
+#define QGR_KEY_SUICIDE_PROX_LAUNCHER 1111021301
+#define QGR_KEY_SHOT_FIRED_PROX_LAUNCHER 1111021302
+#define QGR_KEY_HIT_GIVEN_PROX_LAUNCHER 1111021303
+#define QGR_KEY_HIT_TAKEN_PROX_LAUNCHER 1111021304
+#define QGR_KEY_DAMAGE_GIVEN_PROX_LAUNCHER 1111021305
+#define QGR_KEY_DAMAGE_TAKEN_PROX_LAUNCHER 1111021306
+#define QGR_KEY_SPLASH_GIVEN_PROX_LAUNCHER 1111021307
+#define QGR_KEY_SPLASH_TAKEN_PROX_LAUNCHER 1111021308
+#define QGR_KEY_PICKUP_PROX_LAUNCHER 1111021309
+#define QGR_KEY_TIME_PROX_LAUNCHER 1111021310
+// new to team arena
+#define QGR_KEY_FRAG_CHAINGUN 1211021400
+#define QGR_KEY_SUICIDE_CHAINGUN 1111021401
+#define QGR_KEY_SHOT_FIRED_CHAINGUN 1111021402
+#define QGR_KEY_HIT_GIVEN_CHAINGUN 1111021403
+#define QGR_KEY_HIT_TAKEN_CHAINGUN 1111021404
+#define QGR_KEY_DAMAGE_GIVEN_CHAINGUN 1111021405
+#define QGR_KEY_DAMAGE_TAKEN_CHAINGUN 1111021406
+#define QGR_KEY_SPLASH_GIVEN_CHAINGUN 1111021407
+#define QGR_KEY_SPLASH_TAKEN_CHAINGUN 1111021408
+#define QGR_KEY_PICKUP_CHAINGUN 1111021409
+#define QGR_KEY_TIME_CHAINGUN 1111021410
+#endif /* MISSIONPACK */
+
+// ammo keys
+#define QGR_KEY_BOXES 1111030000
+#define QGR_KEY_ROUNDS 1111030001
+
+#define QGR_KEY_BOXES_BULLETS 1111030100
+#define QGR_KEY_ROUNDS_BULLETS 1111030101
+
+#define QGR_KEY_BOXES_SHELLS 1111030200
+#define QGR_KEY_ROUNDS_SHELLS 1111030201
+
+#define QGR_KEY_BOXES_GRENADES 1111030300
+#define QGR_KEY_ROUNDS_GRENADES 1111030301
+
+#define QGR_KEY_BOXES_ROCKETS 1111030400
+#define QGR_KEY_ROUNDS_ROCKETS 1111030401
+
+#define QGR_KEY_BOXES_CELLS 1111030500
+#define QGR_KEY_ROUNDS_CELLS 1111030501
+
+#define QGR_KEY_BOXES_SLUGS 1111030600
+#define QGR_KEY_ROUNDS_SLUGS 1111030601
+
+#define QGR_KEY_BOXES_LG_AMMO 1111030700
+#define QGR_KEY_ROUNDS_LG_AMMO 1111030701
+
+#define QGR_KEY_BOXES_BFG_AMMO 1111030800
+#define QGR_KEY_ROUNDS_BFG_AMMO 1111030801
+
+#ifdef MISSIONPACK
+// new to team arena
+#define QGR_KEY_BOXES_NAILGUN_AMMO 1111030900
+#define QGR_KEY_ROUNDS_NAILGUN_AMMO 1111030901
+// new to team arena
+#define QGR_KEY_BOXES_PROX_LAUNCHER_AMMO 1111031000
+#define QGR_KEY_ROUNDS_PROX_LAUNCHER_AMMO 1111031001
+// new to team arena
+#define QGR_KEY_BOXES_CHAINGUN_AMMO 1111031100
+#define QGR_KEY_ROUNDS_CHAINGUN_AMMO 1111031101
+#endif /* MISSIONPACK */
+
+// health keys
+#define QGR_KEY_HEALTH 1111040000
+#define QGR_KEY_HEALTH_TOTAL 1111040001
+
+#define QGR_KEY_HEALTH_5 1111040100
+#define QGR_KEY_HEALTH_25 1111040200
+#define QGR_KEY_HEALTH_50 1111040300
+#define QGR_KEY_HEALTH_MEGA 1111040400
+
+// armor keys
+#define QGR_KEY_ARMOR 1111050000
+#define QGR_KEY_ARMOR_TOTAL 1111050001
+
+#define QGR_KEY_ARMOR_SHARD 1111050100
+#define QGR_KEY_ARMOR_YELLOW 1111050200
+#define QGR_KEY_ARMOR_RED 1111050300
+
+// powerup keys
+#define QGR_KEY_POWERUP 1111060000
+#define QGR_KEY_QUAD 1111060100
+#define QGR_KEY_SUIT 1111060200
+#define QGR_KEY_HASTE 1111060300
+#define QGR_KEY_INVIS 1111060400
+#define QGR_KEY_REGEN 1111060500
+#define QGR_KEY_FLIGHT 1111060600
+
+#ifdef MISSIONPACK
+// persistant powerup keys
+// new to team arena
+#define QGR_KEY_SCOUT 1111160800
+#define QGR_KEY_GUARD 1111160801
+#define QGR_KEY_DOUBLER 1111160802
+#define QGR_KEY_AMMOREGEN 1111160803
+
+#endif //MISSIONPACK
+
+// holdable item keys
+#define QGR_KEY_MEDKIT 1111070000
+#define QGR_KEY_MEDKIT_USE 1111070001
+
+#define QGR_KEY_TELEPORTER 1111070100
+#define QGR_KEY_TELEPORTER_USE 1111070101
+
+#ifdef MISSIONPACK
+// new to team arena
+#define QGR_KEY_KAMIKAZE 1111070200
+#define QGR_KEY_KAMIKAZE_USE 1111070201
+// new to team arena
+#define QGR_KEY_PORTAL 1111070300
+#define QGR_KEY_PORTAL_USE 1111070301
+// new to team arena
+#define QGR_KEY_INVULNERABILITY 1111070400
+#define QGR_KEY_INVULNERABILITY_USE 1111070401
+#endif /* MISSIONPACK */
+
+// hazard keys
+#define QGR_KEY_HAZARD_DEATH 1111080000
+#define QGR_KEY_WATER 1111080100
+#define QGR_KEY_SLIME 1111080200
+#define QGR_KEY_LAVA 1111080300
+#define QGR_KEY_CRUSH 1111080400
+#define QGR_KEY_TELEFRAG 1111080500
+#define QGR_KEY_FALLING 1111080600
+#define QGR_KEY_SUICIDE_CMD 1111080700
+#define QGR_KEY_TRIGGER_HURT 1111080800
+#define QGR_KEY_HAZARD_MISC 1111080900
+
+// reward keys
+#define QGR_KEY_IMPRESSIVE 1111090000
+#define QGR_KEY_EXCELLENT 1111090100
+
+// teammate keys
+#define QGR_KEY_TEAMMATE_FRAG 1211100000
+#define QGR_KEY_TEAMMATE_HIT_GIVEN 1111100001
+#define QGR_KEY_TEAMMATE_HIT_TAKEN 1111100002
+#define QGR_KEY_TEAMMATE_DAMAGE_GIVEN 1111100003
+#define QGR_KEY_TEAMMATE_DAMAGE_TAKEN 1111100004
+#define QGR_KEY_TEAMMATE_SPLASH_GIVEN 1111100005
+#define QGR_KEY_TEAMMATE_SPLASH_TAKEN 1111100006
+#define QGR_KEY_TEAM_NAME 1100100007
+
+// ctf keys
+#define QGR_KEY_FLAG_PICKUP 1111110000
+#define QGR_KEY_FLAG_CAPTURE 1111110001
+
+#endif // _G_RANKINGS_H_
diff --git a/code/game/g_session.c b/code/game/g_session.c
new file mode 100755
index 0000000..e65c3e1
--- /dev/null
+++ b/code/game/g_session.c
@@ -0,0 +1,193 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#include "g_local.h"
+
+
+/*
+=======================================================================
+
+ SESSION DATA
+
+Session data is the only data that stays persistant across level loads
+and tournament restarts.
+=======================================================================
+*/
+
+/*
+================
+G_WriteClientSessionData
+
+Called on game shutdown
+================
+*/
+void G_WriteClientSessionData( gclient_t *client ) {
+ const char *s;
+ const char *var;
+
+ s = va("%i %i %i %i %i %i %i",
+ client->sess.sessionTeam,
+ client->sess.spectatorTime,
+ client->sess.spectatorState,
+ client->sess.spectatorClient,
+ client->sess.wins,
+ client->sess.losses,
+ client->sess.teamLeader
+ );
+
+ var = va( "session%i", client - level.clients );
+
+ trap_Cvar_Set( var, s );
+}
+
+/*
+================
+G_ReadSessionData
+
+Called on a reconnect
+================
+*/
+void G_ReadSessionData( gclient_t *client ) {
+ char s[MAX_STRING_CHARS];
+ const char *var;
+
+ // bk001205 - format
+ int teamLeader;
+ int spectatorState;
+ int sessionTeam;
+
+ var = va( "session%i", client - level.clients );
+ trap_Cvar_VariableStringBuffer( var, s, sizeof(s) );
+
+ sscanf( s, "%i %i %i %i %i %i %i",
+ &sessionTeam, // bk010221 - format
+ &client->sess.spectatorTime,
+ &spectatorState, // bk010221 - format
+ &client->sess.spectatorClient,
+ &client->sess.wins,
+ &client->sess.losses,
+ &teamLeader // bk010221 - format
+ );
+
+ // bk001205 - format issues
+ client->sess.sessionTeam = (team_t)sessionTeam;
+ client->sess.spectatorState = (spectatorState_t)spectatorState;
+ client->sess.teamLeader = (qboolean)teamLeader;
+}
+
+
+/*
+================
+G_InitSessionData
+
+Called on a first-time connect
+================
+*/
+void G_InitSessionData( gclient_t *client, char *userinfo ) {
+ clientSession_t *sess;
+ const char *value;
+
+ sess = &client->sess;
+
+ // initial team determination
+ if ( g_gametype.integer >= GT_TEAM ) {
+ if ( g_teamAutoJoin.integer ) {
+ sess->sessionTeam = PickTeam( -1 );
+ BroadcastTeamChange( client, -1 );
+ } else {
+ // always spawn as spectator in team games
+ sess->sessionTeam = TEAM_SPECTATOR;
+ }
+ } else {
+ value = Info_ValueForKey( userinfo, "team" );
+ if ( value[0] == 's' ) {
+ // a willing spectator, not a waiting-in-line
+ sess->sessionTeam = TEAM_SPECTATOR;
+ } else {
+ switch ( g_gametype.integer ) {
+ default:
+ case GT_FFA:
+ case GT_SINGLE_PLAYER:
+ if ( g_maxGameClients.integer > 0 &&
+ level.numNonSpectatorClients >= g_maxGameClients.integer ) {
+ sess->sessionTeam = TEAM_SPECTATOR;
+ } else {
+ sess->sessionTeam = TEAM_FREE;
+ }
+ break;
+ case GT_TOURNAMENT:
+ // if the game is full, go into a waiting mode
+ if ( level.numNonSpectatorClients >= 2 ) {
+ sess->sessionTeam = TEAM_SPECTATOR;
+ } else {
+ sess->sessionTeam = TEAM_FREE;
+ }
+ break;
+ }
+ }
+ }
+
+ sess->spectatorState = SPECTATOR_FREE;
+ sess->spectatorTime = level.time;
+
+ G_WriteClientSessionData( client );
+}
+
+
+/*
+==================
+G_InitWorldSession
+
+==================
+*/
+void G_InitWorldSession( void ) {
+ char s[MAX_STRING_CHARS];
+ int gt;
+
+ trap_Cvar_VariableStringBuffer( "session", s, sizeof(s) );
+ gt = atoi( s );
+
+ // if the gametype changed since the last session, don't use any
+ // client sessions
+ if ( g_gametype.integer != gt ) {
+ level.newSession = qtrue;
+ G_Printf( "Gametype changed, clearing session data.\n" );
+ }
+}
+
+/*
+==================
+G_WriteSessionData
+
+==================
+*/
+void G_WriteSessionData( void ) {
+ int i;
+
+ trap_Cvar_Set( "session", va("%i", g_gametype.integer) );
+
+ for ( i = 0 ; i < level.maxclients ; i++ ) {
+ if ( level.clients[i].pers.connected == CON_CONNECTED ) {
+ G_WriteClientSessionData( &level.clients[i] );
+ }
+ }
+}
diff --git a/code/game/g_spawn.c b/code/game/g_spawn.c
new file mode 100755
index 0000000..5bb5547
--- /dev/null
+++ b/code/game/g_spawn.c
@@ -0,0 +1,643 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+#include "g_local.h"
+
+qboolean G_SpawnString( const char *key, const char *defaultString, char **out ) {
+ int i;
+
+ if ( !level.spawning ) {
+ *out = (char *)defaultString;
+// G_Error( "G_SpawnString() called while not spawning" );
+ }
+
+ for ( i = 0 ; i < level.numSpawnVars ; i++ ) {
+ if ( !Q_stricmp( key, level.spawnVars[i][0] ) ) {
+ *out = level.spawnVars[i][1];
+ return qtrue;
+ }
+ }
+
+ *out = (char *)defaultString;
+ return qfalse;
+}
+
+qboolean G_SpawnFloat( const char *key, const char *defaultString, float *out ) {
+ char *s;
+ qboolean present;
+
+ present = G_SpawnString( key, defaultString, &s );
+ *out = atof( s );
+ return present;
+}
+
+qboolean G_SpawnInt( const char *key, const char *defaultString, int *out ) {
+ char *s;
+ qboolean present;
+
+ present = G_SpawnString( key, defaultString, &s );
+ *out = atoi( s );
+ return present;
+}
+
+qboolean G_SpawnVector( const char *key, const char *defaultString, float *out ) {
+ char *s;
+ qboolean present;
+
+ present = G_SpawnString( key, defaultString, &s );
+ sscanf( s, "%f %f %f", &out[0], &out[1], &out[2] );
+ return present;
+}
+
+
+
+//
+// fields are needed for spawning from the entity string
+//
+typedef enum {
+ F_INT,
+ F_FLOAT,
+ F_LSTRING, // string on disk, pointer in memory, TAG_LEVEL
+ F_GSTRING, // string on disk, pointer in memory, TAG_GAME
+ F_VECTOR,
+ F_ANGLEHACK,
+ F_ENTITY, // index on disk, pointer in memory
+ F_ITEM, // index on disk, pointer in memory
+ F_CLIENT, // index on disk, pointer in memory
+ F_IGNORE
+} fieldtype_t;
+
+typedef struct
+{
+ char *name;
+ int ofs;
+ fieldtype_t type;
+ int flags;
+} field_t;
+
+field_t fields[] = {
+ {"classname", FOFS(classname), F_LSTRING},
+ {"origin", FOFS(s.origin), F_VECTOR},
+ {"model", FOFS(model), F_LSTRING},
+ {"model2", FOFS(model2), F_LSTRING},
+ {"spawnflags", FOFS(spawnflags), F_INT},
+ {"speed", FOFS(speed), F_FLOAT},
+ {"target", FOFS(target), F_LSTRING},
+ {"targetname", FOFS(targetname), F_LSTRING},
+ {"message", FOFS(message), F_LSTRING},
+ {"team", FOFS(team), F_LSTRING},
+ {"wait", FOFS(wait), F_FLOAT},
+ {"random", FOFS(random), F_FLOAT},
+ {"count", FOFS(count), F_INT},
+ {"health", FOFS(health), F_INT},
+ {"light", 0, F_IGNORE},
+ {"dmg", FOFS(damage), F_INT},
+ {"angles", FOFS(s.angles), F_VECTOR},
+ {"angle", FOFS(s.angles), F_ANGLEHACK},
+ {"targetShaderName", FOFS(targetShaderName), F_LSTRING},
+ {"targetShaderNewName", FOFS(targetShaderNewName), F_LSTRING},
+
+ {NULL}
+};
+
+
+typedef struct {
+ char *name;
+ void (*spawn)(gentity_t *ent);
+} spawn_t;
+
+void SP_info_player_start (gentity_t *ent);
+void SP_info_player_deathmatch (gentity_t *ent);
+void SP_info_player_intermission (gentity_t *ent);
+void SP_info_firstplace(gentity_t *ent);
+void SP_info_secondplace(gentity_t *ent);
+void SP_info_thirdplace(gentity_t *ent);
+void SP_info_podium(gentity_t *ent);
+
+void SP_func_plat (gentity_t *ent);
+void SP_func_static (gentity_t *ent);
+void SP_func_rotating (gentity_t *ent);
+void SP_func_bobbing (gentity_t *ent);
+void SP_func_pendulum( gentity_t *ent );
+void SP_func_button (gentity_t *ent);
+void SP_func_door (gentity_t *ent);
+void SP_func_train (gentity_t *ent);
+void SP_func_timer (gentity_t *self);
+
+void SP_trigger_always (gentity_t *ent);
+void SP_trigger_multiple (gentity_t *ent);
+void SP_trigger_push (gentity_t *ent);
+void SP_trigger_teleport (gentity_t *ent);
+void SP_trigger_hurt (gentity_t *ent);
+
+void SP_target_remove_powerups( gentity_t *ent );
+void SP_target_give (gentity_t *ent);
+void SP_target_delay (gentity_t *ent);
+void SP_target_speaker (gentity_t *ent);
+void SP_target_print (gentity_t *ent);
+void SP_target_laser (gentity_t *self);
+void SP_target_character (gentity_t *ent);
+void SP_target_score( gentity_t *ent );
+void SP_target_teleporter( gentity_t *ent );
+void SP_target_relay (gentity_t *ent);
+void SP_target_kill (gentity_t *ent);
+void SP_target_position (gentity_t *ent);
+void SP_target_location (gentity_t *ent);
+void SP_target_push (gentity_t *ent);
+
+void SP_light (gentity_t *self);
+void SP_info_null (gentity_t *self);
+void SP_info_notnull (gentity_t *self);
+void SP_info_camp (gentity_t *self);
+void SP_path_corner (gentity_t *self);
+
+void SP_misc_teleporter_dest (gentity_t *self);
+void SP_misc_model(gentity_t *ent);
+void SP_misc_portal_camera(gentity_t *ent);
+void SP_misc_portal_surface(gentity_t *ent);
+
+void SP_shooter_rocket( gentity_t *ent );
+void SP_shooter_plasma( gentity_t *ent );
+void SP_shooter_grenade( gentity_t *ent );
+
+void SP_team_CTF_redplayer( gentity_t *ent );
+void SP_team_CTF_blueplayer( gentity_t *ent );
+
+void SP_team_CTF_redspawn( gentity_t *ent );
+void SP_team_CTF_bluespawn( gentity_t *ent );
+
+#ifdef MISSIONPACK
+void SP_team_blueobelisk( gentity_t *ent );
+void SP_team_redobelisk( gentity_t *ent );
+void SP_team_neutralobelisk( gentity_t *ent );
+#endif
+void SP_item_botroam( gentity_t *ent ) {};
+
+spawn_t spawns[] = {
+ // info entities don't do anything at all, but provide positional
+ // information for things controlled by other processes
+ {"info_player_start", SP_info_player_start},
+ {"info_player_deathmatch", SP_info_player_deathmatch},
+ {"info_player_intermission", SP_info_player_intermission},
+ {"info_null", SP_info_null},
+ {"info_notnull", SP_info_notnull}, // use target_position instead
+ {"info_camp", SP_info_camp},
+
+ {"func_plat", SP_func_plat},
+ {"func_button", SP_func_button},
+ {"func_door", SP_func_door},
+ {"func_static", SP_func_static},
+ {"func_rotating", SP_func_rotating},
+ {"func_bobbing", SP_func_bobbing},
+ {"func_pendulum", SP_func_pendulum},
+ {"func_train", SP_func_train},
+ {"func_group", SP_info_null},
+ {"func_timer", SP_func_timer}, // rename trigger_timer?
+
+ // Triggers are brush objects that cause an effect when contacted
+ // by a living player, usually involving firing targets.
+ // While almost everything could be done with
+ // a single trigger class and different targets, triggered effects
+ // could not be client side predicted (push and teleport).
+ {"trigger_always", SP_trigger_always},
+ {"trigger_multiple", SP_trigger_multiple},
+ {"trigger_push", SP_trigger_push},
+ {"trigger_teleport", SP_trigger_teleport},
+ {"trigger_hurt", SP_trigger_hurt},
+
+ // targets perform no action by themselves, but must be triggered
+ // by another entity
+ {"target_give", SP_target_give},
+ {"target_remove_powerups", SP_target_remove_powerups},
+ {"target_delay", SP_target_delay},
+ {"target_speaker", SP_target_speaker},
+ {"target_print", SP_target_print},
+ {"target_laser", SP_target_laser},
+ {"target_score", SP_target_score},
+ {"target_teleporter", SP_target_teleporter},
+ {"target_relay", SP_target_relay},
+ {"target_kill", SP_target_kill},
+ {"target_position", SP_target_position},
+ {"target_location", SP_target_location},
+ {"target_push", SP_target_push},
+
+ {"light", SP_light},
+ {"path_corner", SP_path_corner},
+
+ {"misc_teleporter_dest", SP_misc_teleporter_dest},
+ {"misc_model", SP_misc_model},
+ {"misc_portal_surface", SP_misc_portal_surface},
+ {"misc_portal_camera", SP_misc_portal_camera},
+
+ {"shooter_rocket", SP_shooter_rocket},
+ {"shooter_grenade", SP_shooter_grenade},
+ {"shooter_plasma", SP_shooter_plasma},
+
+ {"team_CTF_redplayer", SP_team_CTF_redplayer},
+ {"team_CTF_blueplayer", SP_team_CTF_blueplayer},
+
+ {"team_CTF_redspawn", SP_team_CTF_redspawn},
+ {"team_CTF_bluespawn", SP_team_CTF_bluespawn},
+
+#ifdef MISSIONPACK
+ {"team_redobelisk", SP_team_redobelisk},
+ {"team_blueobelisk", SP_team_blueobelisk},
+ {"team_neutralobelisk", SP_team_neutralobelisk},
+#endif
+ {"item_botroam", SP_item_botroam},
+
+ {0, 0}
+};
+
+/*
+===============
+G_CallSpawn
+
+Finds the spawn function for the entity and calls it,
+returning qfalse if not found
+===============
+*/
+qboolean G_CallSpawn( gentity_t *ent ) {
+ spawn_t *s;
+ gitem_t *item;
+
+ if ( !ent->classname ) {
+ G_Printf ("G_CallSpawn: NULL classname\n");
+ return qfalse;
+ }
+
+ // check item spawn functions
+ for ( item=bg_itemlist+1 ; item->classname ; item++ ) {
+ if ( !strcmp(item->classname, ent->classname) ) {
+ G_SpawnItem( ent, item );
+ return qtrue;
+ }
+ }
+
+ // check normal spawn functions
+ for ( s=spawns ; s->name ; s++ ) {
+ if ( !strcmp(s->name, ent->classname) ) {
+ // found it
+ s->spawn(ent);
+ return qtrue;
+ }
+ }
+ G_Printf ("%s doesn't have a spawn function\n", ent->classname);
+ return qfalse;
+}
+
+/*
+=============
+G_NewString
+
+Builds a copy of the string, translating \n to real linefeeds
+so message texts can be multi-line
+=============
+*/
+char *G_NewString( const char *string ) {
+ char *newb, *new_p;
+ int i,l;
+
+ l = strlen(string) + 1;
+
+ newb = G_Alloc( l );
+
+ new_p = newb;
+
+ // turn \n into a real linefeed
+ for ( i=0 ; i< l ; i++ ) {
+ if (string[i] == '\\' && i < l-1) {
+ i++;
+ if (string[i] == 'n') {
+ *new_p++ = '\n';
+ } else {
+ *new_p++ = '\\';
+ }
+ } else {
+ *new_p++ = string[i];
+ }
+ }
+
+ return newb;
+}
+
+
+
+
+/*
+===============
+G_ParseField
+
+Takes a key/value pair and sets the binary values
+in a gentity
+===============
+*/
+void G_ParseField( const char *key, const char *value, gentity_t *ent ) {
+ field_t *f;
+ byte *b;
+ float v;
+ vec3_t vec;
+
+ for ( f=fields ; f->name ; f++ ) {
+ if ( !Q_stricmp(f->name, key) ) {
+ // found it
+ b = (byte *)ent;
+
+ switch( f->type ) {
+ case F_LSTRING:
+ *(char **)(b+f->ofs) = G_NewString (value);
+ break;
+ case F_VECTOR:
+ sscanf (value, "%f %f %f", &vec[0], &vec[1], &vec[2]);
+ ((float *)(b+f->ofs))[0] = vec[0];
+ ((float *)(b+f->ofs))[1] = vec[1];
+ ((float *)(b+f->ofs))[2] = vec[2];
+ break;
+ case F_INT:
+ *(int *)(b+f->ofs) = atoi(value);
+ break;
+ case F_FLOAT:
+ *(float *)(b+f->ofs) = atof(value);
+ break;
+ case F_ANGLEHACK:
+ v = atof(value);
+ ((float *)(b+f->ofs))[0] = 0;
+ ((float *)(b+f->ofs))[1] = v;
+ ((float *)(b+f->ofs))[2] = 0;
+ break;
+ default:
+ case F_IGNORE:
+ break;
+ }
+ return;
+ }
+ }
+}
+
+
+
+
+/*
+===================
+G_SpawnGEntityFromSpawnVars
+
+Spawn an entity and fill in all of the level fields from
+level.spawnVars[], then call the class specfic spawn function
+===================
+*/
+void G_SpawnGEntityFromSpawnVars( void ) {
+ int i;
+ gentity_t *ent;
+ char *s, *value, *gametypeName;
+ static char *gametypeNames[] = {"ffa", "tournament", "single", "team", "ctf", "oneflag", "obelisk", "harvester", "teamtournament"};
+
+ // get the next free entity
+ ent = G_Spawn();
+
+ for ( i = 0 ; i < level.numSpawnVars ; i++ ) {
+ G_ParseField( level.spawnVars[i][0], level.spawnVars[i][1], ent );
+ }
+
+ // check for "notsingle" flag
+ if ( g_gametype.integer == GT_SINGLE_PLAYER ) {
+ G_SpawnInt( "notsingle", "0", &i );
+ if ( i ) {
+ G_FreeEntity( ent );
+ return;
+ }
+ }
+ // check for "notteam" flag (GT_FFA, GT_TOURNAMENT, GT_SINGLE_PLAYER)
+ if ( g_gametype.integer >= GT_TEAM ) {
+ G_SpawnInt( "notteam", "0", &i );
+ if ( i ) {
+ G_FreeEntity( ent );
+ return;
+ }
+ } else {
+ G_SpawnInt( "notfree", "0", &i );
+ if ( i ) {
+ G_FreeEntity( ent );
+ return;
+ }
+ }
+
+#ifdef MISSIONPACK
+ G_SpawnInt( "notta", "0", &i );
+ if ( i ) {
+ G_FreeEntity( ent );
+ return;
+ }
+#else
+ G_SpawnInt( "notq3a", "0", &i );
+ if ( i ) {
+ G_FreeEntity( ent );
+ return;
+ }
+#endif
+
+ if( G_SpawnString( "gametype", NULL, &value ) ) {
+ if( g_gametype.integer >= GT_FFA && g_gametype.integer < GT_MAX_GAME_TYPE ) {
+ gametypeName = gametypeNames[g_gametype.integer];
+
+ s = strstr( value, gametypeName );
+ if( !s ) {
+ G_FreeEntity( ent );
+ return;
+ }
+ }
+ }
+
+ // move editor origin to pos
+ VectorCopy( ent->s.origin, ent->s.pos.trBase );
+ VectorCopy( ent->s.origin, ent->r.currentOrigin );
+
+ // if we didn't get a classname, don't bother spawning anything
+ if ( !G_CallSpawn( ent ) ) {
+ G_FreeEntity( ent );
+ }
+}
+
+
+
+/*
+====================
+G_AddSpawnVarToken
+====================
+*/
+char *G_AddSpawnVarToken( const char *string ) {
+ int l;
+ char *dest;
+
+ l = strlen( string );
+ if ( level.numSpawnVarChars + l + 1 > MAX_SPAWN_VARS_CHARS ) {
+ G_Error( "G_AddSpawnVarToken: MAX_SPAWN_CHARS" );
+ }
+
+ dest = level.spawnVarChars + level.numSpawnVarChars;
+ memcpy( dest, string, l+1 );
+
+ level.numSpawnVarChars += l + 1;
+
+ return dest;
+}
+
+/*
+====================
+G_ParseSpawnVars
+
+Parses a brace bounded set of key / value pairs out of the
+level's entity strings into level.spawnVars[]
+
+This does not actually spawn an entity.
+====================
+*/
+qboolean G_ParseSpawnVars( void ) {
+ char keyname[MAX_TOKEN_CHARS];
+ char com_token[MAX_TOKEN_CHARS];
+
+ level.numSpawnVars = 0;
+ level.numSpawnVarChars = 0;
+
+ // parse the opening brace
+ if ( !trap_GetEntityToken( com_token, sizeof( com_token ) ) ) {
+ // end of spawn string
+ return qfalse;
+ }
+ if ( com_token[0] != '{' ) {
+ G_Error( "G_ParseSpawnVars: found %s when expecting {",com_token );
+ }
+
+ // go through all the key / value pairs
+ while ( 1 ) {
+ // parse key
+ if ( !trap_GetEntityToken( keyname, sizeof( keyname ) ) ) {
+ G_Error( "G_ParseSpawnVars: EOF without closing brace" );
+ }
+
+ if ( keyname[0] == '}' ) {
+ break;
+ }
+
+ // parse value
+ if ( !trap_GetEntityToken( com_token, sizeof( com_token ) ) ) {
+ G_Error( "G_ParseSpawnVars: EOF without closing brace" );
+ }
+
+ if ( com_token[0] == '}' ) {
+ G_Error( "G_ParseSpawnVars: closing brace without data" );
+ }
+ if ( level.numSpawnVars == MAX_SPAWN_VARS ) {
+ G_Error( "G_ParseSpawnVars: MAX_SPAWN_VARS" );
+ }
+ level.spawnVars[ level.numSpawnVars ][0] = G_AddSpawnVarToken( keyname );
+ level.spawnVars[ level.numSpawnVars ][1] = G_AddSpawnVarToken( com_token );
+ level.numSpawnVars++;
+ }
+
+ return qtrue;
+}
+
+
+
+/*QUAKED worldspawn (0 0 0) ?
+
+Every map should have exactly one worldspawn.
+"music" music wav file
+"gravity" 800 is default gravity
+"message" Text to print during connection process
+*/
+void SP_worldspawn( void ) {
+ char *s;
+
+ G_SpawnString( "classname", "", &s );
+ if ( Q_stricmp( s, "worldspawn" ) ) {
+ G_Error( "SP_worldspawn: The first entity isn't 'worldspawn'" );
+ }
+
+ // make some data visible to connecting client
+ trap_SetConfigstring( CS_GAME_VERSION, GAME_VERSION );
+
+ trap_SetConfigstring( CS_LEVEL_START_TIME, va("%i", level.startTime ) );
+
+ G_SpawnString( "music", "", &s );
+ trap_SetConfigstring( CS_MUSIC, s );
+
+ G_SpawnString( "message", "", &s );
+ trap_SetConfigstring( CS_MESSAGE, s ); // map specific message
+
+ trap_SetConfigstring( CS_MOTD, g_motd.string ); // message of the day
+
+ G_SpawnString( "gravity", "800", &s );
+ trap_Cvar_Set( "g_gravity", s );
+
+ G_SpawnString( "enableDust", "0", &s );
+ trap_Cvar_Set( "g_enableDust", s );
+
+ G_SpawnString( "enableBreath", "0", &s );
+ trap_Cvar_Set( "g_enableBreath", s );
+
+ g_entities[ENTITYNUM_WORLD].s.number = ENTITYNUM_WORLD;
+ g_entities[ENTITYNUM_WORLD].classname = "worldspawn";
+
+ // see if we want a warmup time
+ trap_SetConfigstring( CS_WARMUP, "" );
+ if ( g_restarted.integer ) {
+ trap_Cvar_Set( "g_restarted", "0" );
+ level.warmupTime = 0;
+ } else if ( g_doWarmup.integer ) { // Turn it on
+ level.warmupTime = -1;
+ trap_SetConfigstring( CS_WARMUP, va("%i", level.warmupTime) );
+ G_LogPrintf( "Warmup:\n" );
+ }
+
+}
+
+
+/*
+==============
+G_SpawnEntitiesFromString
+
+Parses textual entity definitions out of an entstring and spawns gentities.
+==============
+*/
+void G_SpawnEntitiesFromString( void ) {
+ // allow calls to G_Spawn*()
+ level.spawning = qtrue;
+ level.numSpawnVars = 0;
+
+ // the worldspawn is not an actual entity, but it still
+ // has a "spawn" function to perform any global setup
+ // needed by a level (setting configstrings or cvars, etc)
+ if ( !G_ParseSpawnVars() ) {
+ G_Error( "SpawnEntities: no entities" );
+ }
+ SP_worldspawn();
+
+ // parse ents
+ while( G_ParseSpawnVars() ) {
+ G_SpawnGEntityFromSpawnVars();
+ }
+
+ level.spawning = qfalse; // any future calls to G_Spawn*() will be errors
+}
+
diff --git a/code/game/g_svcmds.c b/code/game/g_svcmds.c
new file mode 100755
index 0000000..dd3b08f
--- /dev/null
+++ b/code/game/g_svcmds.c
@@ -0,0 +1,508 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+// this file holds commands that can be executed by the server console, but not remote clients
+
+#include "g_local.h"
+
+
+/*
+==============================================================================
+
+PACKET FILTERING
+
+
+You can add or remove addresses from the filter list with:
+
+addip <ip>
+removeip <ip>
+
+The ip address is specified in dot format, and you can use '*' to match any value
+so you can specify an entire class C network with "addip 192.246.40.*"
+
+Removeip will only remove an address specified exactly the same way. You cannot addip a subnet, then removeip a single host.
+
+listip
+Prints the current list of filters.
+
+g_filterban <0 or 1>
+
+If 1 (the default), then ip addresses matching the current list will be prohibited from entering the game. This is the default setting.
+
+If 0, then only addresses matching the list will be allowed. This lets you easily set up a private game, or a game that only allows players from your local network.
+
+TTimo NOTE: for persistence, bans are stored in g_banIPs cvar MAX_CVAR_VALUE_STRING
+The size of the cvar string buffer is limiting the banning to around 20 masks
+this could be improved by putting some g_banIPs2 g_banIps3 etc. maybe
+still, you should rely on PB for banning instead
+
+==============================================================================
+*/
+
+typedef struct ipFilter_s
+{
+ unsigned mask;
+ unsigned compare;
+} ipFilter_t;
+
+#define MAX_IPFILTERS 1024
+
+static ipFilter_t ipFilters[MAX_IPFILTERS];
+static int numIPFilters;
+
+/*
+=================
+StringToFilter
+=================
+*/
+static qboolean StringToFilter (char *s, ipFilter_t *f)
+{
+ char num[128];
+ int i, j;
+ byte b[4];
+ byte m[4];
+
+ for (i=0 ; i<4 ; i++)
+ {
+ b[i] = 0;
+ m[i] = 0;
+ }
+
+ for (i=0 ; i<4 ; i++)
+ {
+ if (*s < '0' || *s > '9')
+ {
+ if (*s == '*') // 'match any'
+ {
+ // b[i] and m[i] to 0
+ s++;
+ if (!*s)
+ break;
+ s++;
+ continue;
+ }
+ G_Printf( "Bad filter address: %s\n", s );
+ return qfalse;
+ }
+
+ j = 0;
+ while (*s >= '0' && *s <= '9')
+ {
+ num[j++] = *s++;
+ }
+ num[j] = 0;
+ b[i] = atoi(num);
+ m[i] = 255;
+
+ if (!*s)
+ break;
+ s++;
+ }
+
+ f->mask = *(unsigned *)m;
+ f->compare = *(unsigned *)b;
+
+ return qtrue;
+}
+
+/*
+=================
+UpdateIPBans
+=================
+*/
+static void UpdateIPBans (void)
+{
+ byte b[4];
+ byte m[4];
+ int i,j;
+ char iplist_final[MAX_CVAR_VALUE_STRING];
+ char ip[64];
+
+ *iplist_final = 0;
+ for (i = 0 ; i < numIPFilters ; i++)
+ {
+ if (ipFilters[i].compare == 0xffffffff)
+ continue;
+
+ *(unsigned *)b = ipFilters[i].compare;
+ *(unsigned *)m = ipFilters[i].mask;
+ *ip = 0;
+ for (j = 0 ; j < 4 ; j++)
+ {
+ if (m[j]!=255)
+ Q_strcat(ip, sizeof(ip), "*");
+ else
+ Q_strcat(ip, sizeof(ip), va("%i", b[j]));
+ Q_strcat(ip, sizeof(ip), (j<3) ? "." : " ");
+ }
+ if (strlen(iplist_final)+strlen(ip) < MAX_CVAR_VALUE_STRING)
+ {
+ Q_strcat( iplist_final, sizeof(iplist_final), ip);
+ }
+ else
+ {
+ Com_Printf("g_banIPs overflowed at MAX_CVAR_VALUE_STRING\n");
+ break;
+ }
+ }
+
+ trap_Cvar_Set( "g_banIPs", iplist_final );
+}
+
+/*
+=================
+G_FilterPacket
+=================
+*/
+qboolean G_FilterPacket (char *from)
+{
+ int i;
+ unsigned in;
+ byte m[4];
+ char *p;
+
+ i = 0;
+ p = from;
+ while (*p && i < 4) {
+ m[i] = 0;
+ while (*p >= '0' && *p <= '9') {
+ m[i] = m[i]*10 + (*p - '0');
+ p++;
+ }
+ if (!*p || *p == ':')
+ break;
+ i++, p++;
+ }
+
+ in = *(unsigned *)m;
+
+ for (i=0 ; i<numIPFilters ; i++)
+ if ( (in & ipFilters[i].mask) == ipFilters[i].compare)
+ return g_filterBan.integer != 0;
+
+ return g_filterBan.integer == 0;
+}
+
+/*
+=================
+AddIP
+=================
+*/
+static void AddIP( char *str )
+{
+ int i;
+
+ for (i = 0 ; i < numIPFilters ; i++)
+ if (ipFilters[i].compare == 0xffffffff)
+ break; // free spot
+ if (i == numIPFilters)
+ {
+ if (numIPFilters == MAX_IPFILTERS)
+ {
+ G_Printf ("IP filter list is full\n");
+ return;
+ }
+ numIPFilters++;
+ }
+
+ if (!StringToFilter (str, &ipFilters[i]))
+ ipFilters[i].compare = 0xffffffffu;
+
+ UpdateIPBans();
+}
+
+/*
+=================
+G_ProcessIPBans
+=================
+*/
+void G_ProcessIPBans(void)
+{
+ char *s, *t;
+ char str[MAX_CVAR_VALUE_STRING];
+
+ Q_strncpyz( str, g_banIPs.string, sizeof(str) );
+
+ for (t = s = g_banIPs.string; *t; /* */ ) {
+ s = strchr(s, ' ');
+ if (!s)
+ break;
+ while (*s == ' ')
+ *s++ = 0;
+ if (*t)
+ AddIP( t );
+ t = s;
+ }
+}
+
+
+/*
+=================
+Svcmd_AddIP_f
+=================
+*/
+void Svcmd_AddIP_f (void)
+{
+ char str[MAX_TOKEN_CHARS];
+
+ if ( trap_Argc() < 2 ) {
+ G_Printf("Usage: addip <ip-mask>\n");
+ return;
+ }
+
+ trap_Argv( 1, str, sizeof( str ) );
+
+ AddIP( str );
+
+}
+
+/*
+=================
+Svcmd_RemoveIP_f
+=================
+*/
+void Svcmd_RemoveIP_f (void)
+{
+ ipFilter_t f;
+ int i;
+ char str[MAX_TOKEN_CHARS];
+
+ if ( trap_Argc() < 2 ) {
+ G_Printf("Usage: sv removeip <ip-mask>\n");
+ return;
+ }
+
+ trap_Argv( 1, str, sizeof( str ) );
+
+ if (!StringToFilter (str, &f))
+ return;
+
+ for (i=0 ; i<numIPFilters ; i++) {
+ if (ipFilters[i].mask == f.mask &&
+ ipFilters[i].compare == f.compare) {
+ ipFilters[i].compare = 0xffffffffu;
+ G_Printf ("Removed.\n");
+
+ UpdateIPBans();
+ return;
+ }
+ }
+
+ G_Printf ( "Didn't find %s.\n", str );
+}
+
+/*
+===================
+Svcmd_EntityList_f
+===================
+*/
+void Svcmd_EntityList_f (void) {
+ int e;
+ gentity_t *check;
+
+ check = g_entities+1;
+ for (e = 1; e < level.num_entities ; e++, check++) {
+ if ( !check->inuse ) {
+ continue;
+ }
+ G_Printf("%3i:", e);
+ switch ( check->s.eType ) {
+ case ET_GENERAL:
+ G_Printf("ET_GENERAL ");
+ break;
+ case ET_PLAYER:
+ G_Printf("ET_PLAYER ");
+ break;
+ case ET_ITEM:
+ G_Printf("ET_ITEM ");
+ break;
+ case ET_MISSILE:
+ G_Printf("ET_MISSILE ");
+ break;
+ case ET_MOVER:
+ G_Printf("ET_MOVER ");
+ break;
+ case ET_BEAM:
+ G_Printf("ET_BEAM ");
+ break;
+ case ET_PORTAL:
+ G_Printf("ET_PORTAL ");
+ break;
+ case ET_SPEAKER:
+ G_Printf("ET_SPEAKER ");
+ break;
+ case ET_PUSH_TRIGGER:
+ G_Printf("ET_PUSH_TRIGGER ");
+ break;
+ case ET_TELEPORT_TRIGGER:
+ G_Printf("ET_TELEPORT_TRIGGER ");
+ break;
+ case ET_INVISIBLE:
+ G_Printf("ET_INVISIBLE ");
+ break;
+ case ET_GRAPPLE:
+ G_Printf("ET_GRAPPLE ");
+ break;
+ default:
+ G_Printf("%3i ", check->s.eType);
+ break;
+ }
+
+ if ( check->classname ) {
+ G_Printf("%s", check->classname);
+ }
+ G_Printf("\n");
+ }
+}
+
+gclient_t *ClientForString( const char *s ) {
+ gclient_t *cl;
+ int i;
+ int idnum;
+
+ // numeric values are just slot numbers
+ if ( s[0] >= '0' && s[0] <= '9' ) {
+ idnum = atoi( s );
+ if ( idnum < 0 || idnum >= level.maxclients ) {
+ Com_Printf( "Bad client slot: %i\n", idnum );
+ return NULL;
+ }
+
+ cl = &level.clients[idnum];
+ if ( cl->pers.connected == CON_DISCONNECTED ) {
+ G_Printf( "Client %i is not connected\n", idnum );
+ return NULL;
+ }
+ return cl;
+ }
+
+ // check for a name match
+ for ( i=0 ; i < level.maxclients ; i++ ) {
+ cl = &level.clients[i];
+ if ( cl->pers.connected == CON_DISCONNECTED ) {
+ continue;
+ }
+ if ( !Q_stricmp( cl->pers.netname, s ) ) {
+ return cl;
+ }
+ }
+
+ G_Printf( "User %s is not on the server\n", s );
+
+ return NULL;
+}
+
+/*
+===================
+Svcmd_ForceTeam_f
+
+forceteam <player> <team>
+===================
+*/
+void Svcmd_ForceTeam_f( void ) {
+ gclient_t *cl;
+ char str[MAX_TOKEN_CHARS];
+
+ // find the player
+ trap_Argv( 1, str, sizeof( str ) );
+ cl = ClientForString( str );
+ if ( !cl ) {
+ return;
+ }
+
+ // set the team
+ trap_Argv( 2, str, sizeof( str ) );
+ SetTeam( &g_entities[cl - level.clients], str );
+}
+
+char *ConcatArgs( int start );
+
+/*
+=================
+ConsoleCommand
+
+=================
+*/
+qboolean ConsoleCommand( void ) {
+ char cmd[MAX_TOKEN_CHARS];
+
+ trap_Argv( 0, cmd, sizeof( cmd ) );
+
+ if ( Q_stricmp (cmd, "entitylist") == 0 ) {
+ Svcmd_EntityList_f();
+ return qtrue;
+ }
+
+ if ( Q_stricmp (cmd, "forceteam") == 0 ) {
+ Svcmd_ForceTeam_f();
+ return qtrue;
+ }
+
+ if (Q_stricmp (cmd, "game_memory") == 0) {
+ Svcmd_GameMem_f();
+ return qtrue;
+ }
+
+ if (Q_stricmp (cmd, "addbot") == 0) {
+ Svcmd_AddBot_f();
+ return qtrue;
+ }
+
+ if (Q_stricmp (cmd, "botlist") == 0) {
+ Svcmd_BotList_f();
+ return qtrue;
+ }
+
+ if (Q_stricmp (cmd, "abort_podium") == 0) {
+ Svcmd_AbortPodium_f();
+ return qtrue;
+ }
+
+ if (Q_stricmp (cmd, "addip") == 0) {
+ Svcmd_AddIP_f();
+ return qtrue;
+ }
+
+ if (Q_stricmp (cmd, "removeip") == 0) {
+ Svcmd_RemoveIP_f();
+ return qtrue;
+ }
+
+ if (Q_stricmp (cmd, "listip") == 0) {
+ trap_SendConsoleCommand( EXEC_NOW, "g_banIPs\n" );
+ return qtrue;
+ }
+
+ if (g_dedicated.integer) {
+ if (Q_stricmp (cmd, "say") == 0) {
+ trap_SendServerCommand( -1, va("print \"server: %s\"", ConcatArgs(1) ) );
+ return qtrue;
+ }
+ // everything else will also be printed as a say command
+ trap_SendServerCommand( -1, va("print \"server: %s\"", ConcatArgs(0) ) );
+ return qtrue;
+ }
+
+ return qfalse;
+}
+
diff --git a/code/game/g_syscalls.asm b/code/game/g_syscalls.asm
new file mode 100755
index 0000000..3909b84
--- /dev/null
+++ b/code/game/g_syscalls.asm
@@ -0,0 +1,225 @@
+code
+
+equ trap_Printf -1
+equ trap_Error -2
+equ trap_Milliseconds -3
+equ trap_Cvar_Register -4
+equ trap_Cvar_Update -5
+equ trap_Cvar_Set -6
+equ trap_Cvar_VariableIntegerValue -7
+equ trap_Cvar_VariableStringBuffer -8
+equ trap_Argc -9
+equ trap_Argv -10
+equ trap_FS_FOpenFile -11
+equ trap_FS_Read -12
+equ trap_FS_Write -13
+equ trap_FS_FCloseFile -14
+equ trap_SendConsoleCommand -15
+equ trap_LocateGameData -16
+equ trap_DropClient -17
+equ trap_SendServerCommand -18
+equ trap_SetConfigstring -19
+equ trap_GetConfigstring -20
+equ trap_GetUserinfo -21
+equ trap_SetUserinfo -22
+equ trap_GetServerinfo -23
+equ trap_SetBrushModel -24
+equ trap_Trace -25
+equ trap_PointContents -26
+equ trap_InPVS -27
+equ trap_InPVSIgnorePortals -28
+equ trap_AdjustAreaPortalState -29
+equ trap_AreasConnected -30
+equ trap_LinkEntity -31
+equ trap_UnlinkEntity -32
+equ trap_EntitiesInBox -33
+equ trap_EntityContact -34
+equ trap_BotAllocateClient -35
+equ trap_BotFreeClient -36
+equ trap_GetUsercmd -37
+equ trap_GetEntityToken -38
+equ trap_FS_GetFileList -39
+equ trap_DebugPolygonCreate -40
+equ trap_DebugPolygonDelete -41
+equ trap_RealTime -42
+equ trap_SnapVector -43
+equ trap_TraceCapsule -44
+equ trap_EntityContactCapsule -45
+equ trap_FS_Seek -46
+
+equ memset -101
+equ memcpy -102
+equ strncpy -103
+equ sin -104
+equ cos -105
+equ atan2 -106
+equ sqrt -107
+equ floor -111
+equ ceil -112
+equ testPrintInt -113
+equ testPrintFloat -114
+
+
+
+equ trap_BotLibSetup -201
+equ trap_BotLibShutdown -202
+equ trap_BotLibVarSet -203
+equ trap_BotLibVarGet -204
+equ trap_BotLibDefine -205
+equ trap_BotLibStartFrame -206
+equ trap_BotLibLoadMap -207
+equ trap_BotLibUpdateEntity -208
+equ trap_BotLibTest -209
+
+equ trap_BotGetSnapshotEntity -210
+equ trap_BotGetServerCommand -211
+equ trap_BotUserCommand -212
+
+
+
+equ trap_AAS_EnableRoutingArea -301
+equ trap_AAS_BBoxAreas -302
+equ trap_AAS_AreaInfo -303
+equ trap_AAS_EntityInfo -304
+
+equ trap_AAS_Initialized -305
+equ trap_AAS_PresenceTypeBoundingBox -306
+equ trap_AAS_Time -307
+
+equ trap_AAS_PointAreaNum -308
+equ trap_AAS_TraceAreas -309
+
+equ trap_AAS_PointContents -310
+equ trap_AAS_NextBSPEntity -311
+equ trap_AAS_ValueForBSPEpairKey -312
+equ trap_AAS_VectorForBSPEpairKey -313
+equ trap_AAS_FloatForBSPEpairKey -314
+equ trap_AAS_IntForBSPEpairKey -315
+
+equ trap_AAS_AreaReachability -316
+
+equ trap_AAS_AreaTravelTimeToGoalArea -317
+
+equ trap_AAS_Swimming -318
+equ trap_AAS_PredictClientMovement -319
+
+
+
+equ trap_EA_Say -401
+equ trap_EA_SayTeam -402
+equ trap_EA_Command -403
+
+equ trap_EA_Action -404
+equ trap_EA_Gesture -405
+equ trap_EA_Talk -406
+equ trap_EA_Attack -407
+equ trap_EA_Use -408
+equ trap_EA_Respawn -409
+equ trap_EA_Crouch -410
+equ trap_EA_MoveUp -411
+equ trap_EA_MoveDown -412
+equ trap_EA_MoveForward -413
+equ trap_EA_MoveBack -414
+equ trap_EA_MoveLeft -415
+equ trap_EA_MoveRight -416
+
+equ trap_EA_SelectWeapon -417
+equ trap_EA_Jump -418
+equ trap_EA_DelayedJump -419
+equ trap_EA_Move -420
+equ trap_EA_View -421
+
+equ trap_EA_EndRegular -422
+equ trap_EA_GetInput -423
+equ trap_EA_ResetInput -424
+
+
+
+equ trap_BotLoadCharacter -501
+equ trap_BotFreeCharacter -502
+equ trap_Characteristic_Float -503
+equ trap_Characteristic_BFloat -504
+equ trap_Characteristic_Integer -505
+equ trap_Characteristic_BInteger -506
+equ trap_Characteristic_String -507
+
+equ trap_BotAllocChatState -508
+equ trap_BotFreeChatState -509
+equ trap_BotQueueConsoleMessage -510
+equ trap_BotRemoveConsoleMessage -511
+equ trap_BotNextConsoleMessage -512
+equ trap_BotNumConsoleMessages -513
+equ trap_BotInitialChat -514
+equ trap_BotReplyChat -515
+equ trap_BotChatLength -516
+equ trap_BotEnterChat -517
+equ trap_StringContains -518
+equ trap_BotFindMatch -519
+equ trap_BotMatchVariable -520
+equ trap_UnifyWhiteSpaces -521
+equ trap_BotReplaceSynonyms -522
+equ trap_BotLoadChatFile -523
+equ trap_BotSetChatGender -524
+equ trap_BotSetChatName -525
+
+equ trap_BotResetGoalState -526
+equ trap_BotResetAvoidGoals -527
+equ trap_BotPushGoal -528
+equ trap_BotPopGoal -529
+equ trap_BotEmptyGoalStack -530
+equ trap_BotDumpAvoidGoals -531
+equ trap_BotDumpGoalStack -532
+equ trap_BotGoalName -533
+equ trap_BotGetTopGoal -534
+equ trap_BotGetSecondGoal -535
+equ trap_BotChooseLTGItem -536
+equ trap_BotChooseNBGItem -537
+equ trap_BotTouchingGoal -538
+equ trap_BotItemGoalInVisButNotVisible -539
+equ trap_BotGetLevelItemGoal -540
+equ trap_BotAvoidGoalTime -541
+equ trap_BotInitLevelItems -542
+equ trap_BotUpdateEntityItems -543
+equ trap_BotLoadItemWeights -544
+equ trap_BotFreeItemWeights -546
+equ trap_BotSaveGoalFuzzyLogic -546
+equ trap_BotAllocGoalState -547
+equ trap_BotFreeGoalState -548
+
+equ trap_BotResetMoveState -549
+equ trap_BotMoveToGoal -550
+equ trap_BotMoveInDirection -551
+equ trap_BotResetAvoidReach -552
+equ trap_BotResetLastAvoidReach -553
+equ trap_BotReachabilityArea -554
+equ trap_BotMovementViewTarget -555
+equ trap_BotAllocMoveState -556
+equ trap_BotFreeMoveState -557
+equ trap_BotInitMoveState -558
+
+equ trap_BotChooseBestFightWeapon -559
+equ trap_BotGetWeaponInfo -560
+equ trap_BotLoadWeaponWeights -561
+equ trap_BotAllocWeaponState -562
+equ trap_BotFreeWeaponState -563
+equ trap_BotResetWeaponState -564
+equ trap_GeneticParentsAndChildSelection -565
+equ trap_BotInterbreedGoalFuzzyLogic -566
+equ trap_BotMutateGoalFuzzyLogic -567
+equ trap_BotGetNextCampSpotGoal -568
+equ trap_BotGetMapLocationGoal -569
+equ trap_BotNumInitialChats -570
+equ trap_BotGetChatMessage -571
+equ trap_BotRemoveFromAvoidGoals -572
+equ trap_BotPredictVisiblePosition -573
+equ trap_BotSetAvoidGoalTime -574
+equ trap_BotAddAvoidSpot -575
+equ trap_AAS_AlternativeRouteGoals -576
+equ trap_AAS_PredictRoute -577
+equ trap_AAS_PointReachabilityAreaIndex -578
+
+equ trap_BotLibLoadSource -579
+equ trap_BotLibFreeSource -580
+equ trap_BotLibReadToken -581
+equ trap_BotLibSourceFileAndLine -582
+
diff --git a/code/game/g_syscalls.c b/code/game/g_syscalls.c
new file mode 100755
index 0000000..80a0661
--- /dev/null
+++ b/code/game/g_syscalls.c
@@ -0,0 +1,790 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#include "g_local.h"
+
+// this file is only included when building a dll
+// g_syscalls.asm is included instead when building a qvm
+#ifdef Q3_VM
+#error "Do not use in VM build"
+#endif
+
+static int (QDECL *syscall)( int arg, ... ) = (int (QDECL *)( int, ...))-1;
+
+
+void dllEntry( int (QDECL *syscallptr)( int arg,... ) ) {
+ syscall = syscallptr;
+}
+
+int PASSFLOAT( float x ) {
+ float floatTemp;
+ floatTemp = x;
+ return *(int *)&floatTemp;
+}
+
+void trap_Printf( const char *fmt ) {
+ syscall( G_PRINT, fmt );
+}
+
+void trap_Error( const char *fmt ) {
+ syscall( G_ERROR, fmt );
+}
+
+int trap_Milliseconds( void ) {
+ return syscall( G_MILLISECONDS );
+}
+int trap_Argc( void ) {
+ return syscall( G_ARGC );
+}
+
+void trap_Argv( int n, char *buffer, int bufferLength ) {
+ syscall( G_ARGV, n, buffer, bufferLength );
+}
+
+int trap_FS_FOpenFile( const char *qpath, fileHandle_t *f, fsMode_t mode ) {
+ return syscall( G_FS_FOPEN_FILE, qpath, f, mode );
+}
+
+void trap_FS_Read( void *buffer, int len, fileHandle_t f ) {
+ syscall( G_FS_READ, buffer, len, f );
+}
+
+void trap_FS_Write( const void *buffer, int len, fileHandle_t f ) {
+ syscall( G_FS_WRITE, buffer, len, f );
+}
+
+void trap_FS_FCloseFile( fileHandle_t f ) {
+ syscall( G_FS_FCLOSE_FILE, f );
+}
+
+int trap_FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize ) {
+ return syscall( G_FS_GETFILELIST, path, extension, listbuf, bufsize );
+}
+
+int trap_FS_Seek( fileHandle_t f, long offset, int origin ) {
+ return syscall( G_FS_SEEK, f, offset, origin );
+}
+
+void trap_SendConsoleCommand( int exec_when, const char *text ) {
+ syscall( G_SEND_CONSOLE_COMMAND, exec_when, text );
+}
+
+void trap_Cvar_Register( vmCvar_t *cvar, const char *var_name, const char *value, int flags ) {
+ syscall( G_CVAR_REGISTER, cvar, var_name, value, flags );
+}
+
+void trap_Cvar_Update( vmCvar_t *cvar ) {
+ syscall( G_CVAR_UPDATE, cvar );
+}
+
+void trap_Cvar_Set( const char *var_name, const char *value ) {
+ syscall( G_CVAR_SET, var_name, value );
+}
+
+int trap_Cvar_VariableIntegerValue( const char *var_name ) {
+ return syscall( G_CVAR_VARIABLE_INTEGER_VALUE, var_name );
+}
+
+void trap_Cvar_VariableStringBuffer( const char *var_name, char *buffer, int bufsize ) {
+ syscall( G_CVAR_VARIABLE_STRING_BUFFER, var_name, buffer, bufsize );
+}
+
+
+void trap_LocateGameData( gentity_t *gEnts, int numGEntities, int sizeofGEntity_t,
+ playerState_t *clients, int sizeofGClient ) {
+ syscall( G_LOCATE_GAME_DATA, gEnts, numGEntities, sizeofGEntity_t, clients, sizeofGClient );
+}
+
+void trap_DropClient( int clientNum, const char *reason ) {
+ syscall( G_DROP_CLIENT, clientNum, reason );
+}
+
+void trap_SendServerCommand( int clientNum, const char *text ) {
+ syscall( G_SEND_SERVER_COMMAND, clientNum, text );
+}
+
+void trap_SetConfigstring( int num, const char *string ) {
+ syscall( G_SET_CONFIGSTRING, num, string );
+}
+
+void trap_GetConfigstring( int num, char *buffer, int bufferSize ) {
+ syscall( G_GET_CONFIGSTRING, num, buffer, bufferSize );
+}
+
+void trap_GetUserinfo( int num, char *buffer, int bufferSize ) {
+ syscall( G_GET_USERINFO, num, buffer, bufferSize );
+}
+
+void trap_SetUserinfo( int num, const char *buffer ) {
+ syscall( G_SET_USERINFO, num, buffer );
+}
+
+void trap_GetServerinfo( char *buffer, int bufferSize ) {
+ syscall( G_GET_SERVERINFO, buffer, bufferSize );
+}
+
+void trap_SetBrushModel( gentity_t *ent, const char *name ) {
+ syscall( G_SET_BRUSH_MODEL, ent, name );
+}
+
+void trap_Trace( trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentmask ) {
+ syscall( G_TRACE, results, start, mins, maxs, end, passEntityNum, contentmask );
+}
+
+void trap_TraceCapsule( trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentmask ) {
+ syscall( G_TRACECAPSULE, results, start, mins, maxs, end, passEntityNum, contentmask );
+}
+
+int trap_PointContents( const vec3_t point, int passEntityNum ) {
+ return syscall( G_POINT_CONTENTS, point, passEntityNum );
+}
+
+
+qboolean trap_InPVS( const vec3_t p1, const vec3_t p2 ) {
+ return syscall( G_IN_PVS, p1, p2 );
+}
+
+qboolean trap_InPVSIgnorePortals( const vec3_t p1, const vec3_t p2 ) {
+ return syscall( G_IN_PVS_IGNORE_PORTALS, p1, p2 );
+}
+
+void trap_AdjustAreaPortalState( gentity_t *ent, qboolean open ) {
+ syscall( G_ADJUST_AREA_PORTAL_STATE, ent, open );
+}
+
+qboolean trap_AreasConnected( int area1, int area2 ) {
+ return syscall( G_AREAS_CONNECTED, area1, area2 );
+}
+
+void trap_LinkEntity( gentity_t *ent ) {
+ syscall( G_LINKENTITY, ent );
+}
+
+void trap_UnlinkEntity( gentity_t *ent ) {
+ syscall( G_UNLINKENTITY, ent );
+}
+
+int trap_EntitiesInBox( const vec3_t mins, const vec3_t maxs, int *list, int maxcount ) {
+ return syscall( G_ENTITIES_IN_BOX, mins, maxs, list, maxcount );
+}
+
+qboolean trap_EntityContact( const vec3_t mins, const vec3_t maxs, const gentity_t *ent ) {
+ return syscall( G_ENTITY_CONTACT, mins, maxs, ent );
+}
+
+qboolean trap_EntityContactCapsule( const vec3_t mins, const vec3_t maxs, const gentity_t *ent ) {
+ return syscall( G_ENTITY_CONTACTCAPSULE, mins, maxs, ent );
+}
+
+int trap_BotAllocateClient( void ) {
+ return syscall( G_BOT_ALLOCATE_CLIENT );
+}
+
+void trap_BotFreeClient( int clientNum ) {
+ syscall( G_BOT_FREE_CLIENT, clientNum );
+}
+
+void trap_GetUsercmd( int clientNum, usercmd_t *cmd ) {
+ syscall( G_GET_USERCMD, clientNum, cmd );
+}
+
+qboolean trap_GetEntityToken( char *buffer, int bufferSize ) {
+ return syscall( G_GET_ENTITY_TOKEN, buffer, bufferSize );
+}
+
+int trap_DebugPolygonCreate(int color, int numPoints, vec3_t *points) {
+ return syscall( G_DEBUG_POLYGON_CREATE, color, numPoints, points );
+}
+
+void trap_DebugPolygonDelete(int id) {
+ syscall( G_DEBUG_POLYGON_DELETE, id );
+}
+
+int trap_RealTime( qtime_t *qtime ) {
+ return syscall( G_REAL_TIME, qtime );
+}
+
+void trap_SnapVector( float *v ) {
+ syscall( G_SNAPVECTOR, v );
+ return;
+}
+
+// BotLib traps start here
+int trap_BotLibSetup( void ) {
+ return syscall( BOTLIB_SETUP );
+}
+
+int trap_BotLibShutdown( void ) {
+ return syscall( BOTLIB_SHUTDOWN );
+}
+
+int trap_BotLibVarSet(char *var_name, char *value) {
+ return syscall( BOTLIB_LIBVAR_SET, var_name, value );
+}
+
+int trap_BotLibVarGet(char *var_name, char *value, int size) {
+ return syscall( BOTLIB_LIBVAR_GET, var_name, value, size );
+}
+
+int trap_BotLibDefine(char *string) {
+ return syscall( BOTLIB_PC_ADD_GLOBAL_DEFINE, string );
+}
+
+int trap_BotLibStartFrame(float time) {
+ return syscall( BOTLIB_START_FRAME, PASSFLOAT( time ) );
+}
+
+int trap_BotLibLoadMap(const char *mapname) {
+ return syscall( BOTLIB_LOAD_MAP, mapname );
+}
+
+int trap_BotLibUpdateEntity(int ent, void /* struct bot_updateentity_s */ *bue) {
+ return syscall( BOTLIB_UPDATENTITY, ent, bue );
+}
+
+int trap_BotLibTest(int parm0, char *parm1, vec3_t parm2, vec3_t parm3) {
+ return syscall( BOTLIB_TEST, parm0, parm1, parm2, parm3 );
+}
+
+int trap_BotGetSnapshotEntity( int clientNum, int sequence ) {
+ return syscall( BOTLIB_GET_SNAPSHOT_ENTITY, clientNum, sequence );
+}
+
+int trap_BotGetServerCommand(int clientNum, char *message, int size) {
+ return syscall( BOTLIB_GET_CONSOLE_MESSAGE, clientNum, message, size );
+}
+
+void trap_BotUserCommand(int clientNum, usercmd_t *ucmd) {
+ syscall( BOTLIB_USER_COMMAND, clientNum, ucmd );
+}
+
+void trap_AAS_EntityInfo(int entnum, void /* struct aas_entityinfo_s */ *info) {
+ syscall( BOTLIB_AAS_ENTITY_INFO, entnum, info );
+}
+
+int trap_AAS_Initialized(void) {
+ return syscall( BOTLIB_AAS_INITIALIZED );
+}
+
+void trap_AAS_PresenceTypeBoundingBox(int presencetype, vec3_t mins, vec3_t maxs) {
+ syscall( BOTLIB_AAS_PRESENCE_TYPE_BOUNDING_BOX, presencetype, mins, maxs );
+}
+
+float trap_AAS_Time(void) {
+ int temp;
+ temp = syscall( BOTLIB_AAS_TIME );
+ return (*(float*)&temp);
+}
+
+int trap_AAS_PointAreaNum(vec3_t point) {
+ return syscall( BOTLIB_AAS_POINT_AREA_NUM, point );
+}
+
+int trap_AAS_PointReachabilityAreaIndex(vec3_t point) {
+ return syscall( BOTLIB_AAS_POINT_REACHABILITY_AREA_INDEX, point );
+}
+
+int trap_AAS_TraceAreas(vec3_t start, vec3_t end, int *areas, vec3_t *points, int maxareas) {
+ return syscall( BOTLIB_AAS_TRACE_AREAS, start, end, areas, points, maxareas );
+}
+
+int trap_AAS_BBoxAreas(vec3_t absmins, vec3_t absmaxs, int *areas, int maxareas) {
+ return syscall( BOTLIB_AAS_BBOX_AREAS, absmins, absmaxs, areas, maxareas );
+}
+
+int trap_AAS_AreaInfo( int areanum, void /* struct aas_areainfo_s */ *info ) {
+ return syscall( BOTLIB_AAS_AREA_INFO, areanum, info );
+}
+
+int trap_AAS_PointContents(vec3_t point) {
+ return syscall( BOTLIB_AAS_POINT_CONTENTS, point );
+}
+
+int trap_AAS_NextBSPEntity(int ent) {
+ return syscall( BOTLIB_AAS_NEXT_BSP_ENTITY, ent );
+}
+
+int trap_AAS_ValueForBSPEpairKey(int ent, char *key, char *value, int size) {
+ return syscall( BOTLIB_AAS_VALUE_FOR_BSP_EPAIR_KEY, ent, key, value, size );
+}
+
+int trap_AAS_VectorForBSPEpairKey(int ent, char *key, vec3_t v) {
+ return syscall( BOTLIB_AAS_VECTOR_FOR_BSP_EPAIR_KEY, ent, key, v );
+}
+
+int trap_AAS_FloatForBSPEpairKey(int ent, char *key, float *value) {
+ return syscall( BOTLIB_AAS_FLOAT_FOR_BSP_EPAIR_KEY, ent, key, value );
+}
+
+int trap_AAS_IntForBSPEpairKey(int ent, char *key, int *value) {
+ return syscall( BOTLIB_AAS_INT_FOR_BSP_EPAIR_KEY, ent, key, value );
+}
+
+int trap_AAS_AreaReachability(int areanum) {
+ return syscall( BOTLIB_AAS_AREA_REACHABILITY, areanum );
+}
+
+int trap_AAS_AreaTravelTimeToGoalArea(int areanum, vec3_t origin, int goalareanum, int travelflags) {
+ return syscall( BOTLIB_AAS_AREA_TRAVEL_TIME_TO_GOAL_AREA, areanum, origin, goalareanum, travelflags );
+}
+
+int trap_AAS_EnableRoutingArea( int areanum, int enable ) {
+ return syscall( BOTLIB_AAS_ENABLE_ROUTING_AREA, areanum, enable );
+}
+
+int trap_AAS_PredictRoute(void /*struct aas_predictroute_s*/ *route, int areanum, vec3_t origin,
+ int goalareanum, int travelflags, int maxareas, int maxtime,
+ int stopevent, int stopcontents, int stoptfl, int stopareanum) {
+ return syscall( BOTLIB_AAS_PREDICT_ROUTE, route, areanum, origin, goalareanum, travelflags, maxareas, maxtime, stopevent, stopcontents, stoptfl, stopareanum );
+}
+
+int trap_AAS_AlternativeRouteGoals(vec3_t start, int startareanum, vec3_t goal, int goalareanum, int travelflags,
+ void /*struct aas_altroutegoal_s*/ *altroutegoals, int maxaltroutegoals,
+ int type) {
+ return syscall( BOTLIB_AAS_ALTERNATIVE_ROUTE_GOAL, start, startareanum, goal, goalareanum, travelflags, altroutegoals, maxaltroutegoals, type );
+}
+
+int trap_AAS_Swimming(vec3_t origin) {
+ return syscall( BOTLIB_AAS_SWIMMING, origin );
+}
+
+int trap_AAS_PredictClientMovement(void /* struct aas_clientmove_s */ *move, int entnum, vec3_t origin, int presencetype, int onground, vec3_t velocity, vec3_t cmdmove, int cmdframes, int maxframes, float frametime, int stopevent, int stopareanum, int visualize) {
+ return syscall( BOTLIB_AAS_PREDICT_CLIENT_MOVEMENT, move, entnum, origin, presencetype, onground, velocity, cmdmove, cmdframes, maxframes, PASSFLOAT(frametime), stopevent, stopareanum, visualize );
+}
+
+void trap_EA_Say(int client, char *str) {
+ syscall( BOTLIB_EA_SAY, client, str );
+}
+
+void trap_EA_SayTeam(int client, char *str) {
+ syscall( BOTLIB_EA_SAY_TEAM, client, str );
+}
+
+void trap_EA_Command(int client, char *command) {
+ syscall( BOTLIB_EA_COMMAND, client, command );
+}
+
+void trap_EA_Action(int client, int action) {
+ syscall( BOTLIB_EA_ACTION, client, action );
+}
+
+void trap_EA_Gesture(int client) {
+ syscall( BOTLIB_EA_GESTURE, client );
+}
+
+void trap_EA_Talk(int client) {
+ syscall( BOTLIB_EA_TALK, client );
+}
+
+void trap_EA_Attack(int client) {
+ syscall( BOTLIB_EA_ATTACK, client );
+}
+
+void trap_EA_Use(int client) {
+ syscall( BOTLIB_EA_USE, client );
+}
+
+void trap_EA_Respawn(int client) {
+ syscall( BOTLIB_EA_RESPAWN, client );
+}
+
+void trap_EA_Crouch(int client) {
+ syscall( BOTLIB_EA_CROUCH, client );
+}
+
+void trap_EA_MoveUp(int client) {
+ syscall( BOTLIB_EA_MOVE_UP, client );
+}
+
+void trap_EA_MoveDown(int client) {
+ syscall( BOTLIB_EA_MOVE_DOWN, client );
+}
+
+void trap_EA_MoveForward(int client) {
+ syscall( BOTLIB_EA_MOVE_FORWARD, client );
+}
+
+void trap_EA_MoveBack(int client) {
+ syscall( BOTLIB_EA_MOVE_BACK, client );
+}
+
+void trap_EA_MoveLeft(int client) {
+ syscall( BOTLIB_EA_MOVE_LEFT, client );
+}
+
+void trap_EA_MoveRight(int client) {
+ syscall( BOTLIB_EA_MOVE_RIGHT, client );
+}
+
+void trap_EA_SelectWeapon(int client, int weapon) {
+ syscall( BOTLIB_EA_SELECT_WEAPON, client, weapon );
+}
+
+void trap_EA_Jump(int client) {
+ syscall( BOTLIB_EA_JUMP, client );
+}
+
+void trap_EA_DelayedJump(int client) {
+ syscall( BOTLIB_EA_DELAYED_JUMP, client );
+}
+
+void trap_EA_Move(int client, vec3_t dir, float speed) {
+ syscall( BOTLIB_EA_MOVE, client, dir, PASSFLOAT(speed) );
+}
+
+void trap_EA_View(int client, vec3_t viewangles) {
+ syscall( BOTLIB_EA_VIEW, client, viewangles );
+}
+
+void trap_EA_EndRegular(int client, float thinktime) {
+ syscall( BOTLIB_EA_END_REGULAR, client, PASSFLOAT(thinktime) );
+}
+
+void trap_EA_GetInput(int client, float thinktime, void /* struct bot_input_s */ *input) {
+ syscall( BOTLIB_EA_GET_INPUT, client, PASSFLOAT(thinktime), input );
+}
+
+void trap_EA_ResetInput(int client) {
+ syscall( BOTLIB_EA_RESET_INPUT, client );
+}
+
+int trap_BotLoadCharacter(char *charfile, float skill) {
+ return syscall( BOTLIB_AI_LOAD_CHARACTER, charfile, PASSFLOAT(skill));
+}
+
+void trap_BotFreeCharacter(int character) {
+ syscall( BOTLIB_AI_FREE_CHARACTER, character );
+}
+
+float trap_Characteristic_Float(int character, int index) {
+ int temp;
+ temp = syscall( BOTLIB_AI_CHARACTERISTIC_FLOAT, character, index );
+ return (*(float*)&temp);
+}
+
+float trap_Characteristic_BFloat(int character, int index, float min, float max) {
+ int temp;
+ temp = syscall( BOTLIB_AI_CHARACTERISTIC_BFLOAT, character, index, PASSFLOAT(min), PASSFLOAT(max) );
+ return (*(float*)&temp);
+}
+
+int trap_Characteristic_Integer(int character, int index) {
+ return syscall( BOTLIB_AI_CHARACTERISTIC_INTEGER, character, index );
+}
+
+int trap_Characteristic_BInteger(int character, int index, int min, int max) {
+ return syscall( BOTLIB_AI_CHARACTERISTIC_BINTEGER, character, index, min, max );
+}
+
+void trap_Characteristic_String(int character, int index, char *buf, int size) {
+ syscall( BOTLIB_AI_CHARACTERISTIC_STRING, character, index, buf, size );
+}
+
+int trap_BotAllocChatState(void) {
+ return syscall( BOTLIB_AI_ALLOC_CHAT_STATE );
+}
+
+void trap_BotFreeChatState(int handle) {
+ syscall( BOTLIB_AI_FREE_CHAT_STATE, handle );
+}
+
+void trap_BotQueueConsoleMessage(int chatstate, int type, char *message) {
+ syscall( BOTLIB_AI_QUEUE_CONSOLE_MESSAGE, chatstate, type, message );
+}
+
+void trap_BotRemoveConsoleMessage(int chatstate, int handle) {
+ syscall( BOTLIB_AI_REMOVE_CONSOLE_MESSAGE, chatstate, handle );
+}
+
+int trap_BotNextConsoleMessage(int chatstate, void /* struct bot_consolemessage_s */ *cm) {
+ return syscall( BOTLIB_AI_NEXT_CONSOLE_MESSAGE, chatstate, cm );
+}
+
+int trap_BotNumConsoleMessages(int chatstate) {
+ return syscall( BOTLIB_AI_NUM_CONSOLE_MESSAGE, chatstate );
+}
+
+void trap_BotInitialChat(int chatstate, char *type, int mcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7 ) {
+ syscall( BOTLIB_AI_INITIAL_CHAT, chatstate, type, mcontext, var0, var1, var2, var3, var4, var5, var6, var7 );
+}
+
+int trap_BotNumInitialChats(int chatstate, char *type) {
+ return syscall( BOTLIB_AI_NUM_INITIAL_CHATS, chatstate, type );
+}
+
+int trap_BotReplyChat(int chatstate, char *message, int mcontext, int vcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7 ) {
+ return syscall( BOTLIB_AI_REPLY_CHAT, chatstate, message, mcontext, vcontext, var0, var1, var2, var3, var4, var5, var6, var7 );
+}
+
+int trap_BotChatLength(int chatstate) {
+ return syscall( BOTLIB_AI_CHAT_LENGTH, chatstate );
+}
+
+void trap_BotEnterChat(int chatstate, int client, int sendto) {
+ syscall( BOTLIB_AI_ENTER_CHAT, chatstate, client, sendto );
+}
+
+void trap_BotGetChatMessage(int chatstate, char *buf, int size) {
+ syscall( BOTLIB_AI_GET_CHAT_MESSAGE, chatstate, buf, size);
+}
+
+int trap_StringContains(char *str1, char *str2, int casesensitive) {
+ return syscall( BOTLIB_AI_STRING_CONTAINS, str1, str2, casesensitive );
+}
+
+int trap_BotFindMatch(char *str, void /* struct bot_match_s */ *match, unsigned long int context) {
+ return syscall( BOTLIB_AI_FIND_MATCH, str, match, context );
+}
+
+void trap_BotMatchVariable(void /* struct bot_match_s */ *match, int variable, char *buf, int size) {
+ syscall( BOTLIB_AI_MATCH_VARIABLE, match, variable, buf, size );
+}
+
+void trap_UnifyWhiteSpaces(char *string) {
+ syscall( BOTLIB_AI_UNIFY_WHITE_SPACES, string );
+}
+
+void trap_BotReplaceSynonyms(char *string, unsigned long int context) {
+ syscall( BOTLIB_AI_REPLACE_SYNONYMS, string, context );
+}
+
+int trap_BotLoadChatFile(int chatstate, char *chatfile, char *chatname) {
+ return syscall( BOTLIB_AI_LOAD_CHAT_FILE, chatstate, chatfile, chatname );
+}
+
+void trap_BotSetChatGender(int chatstate, int gender) {
+ syscall( BOTLIB_AI_SET_CHAT_GENDER, chatstate, gender );
+}
+
+void trap_BotSetChatName(int chatstate, char *name, int client) {
+ syscall( BOTLIB_AI_SET_CHAT_NAME, chatstate, name, client );
+}
+
+void trap_BotResetGoalState(int goalstate) {
+ syscall( BOTLIB_AI_RESET_GOAL_STATE, goalstate );
+}
+
+void trap_BotResetAvoidGoals(int goalstate) {
+ syscall( BOTLIB_AI_RESET_AVOID_GOALS, goalstate );
+}
+
+void trap_BotRemoveFromAvoidGoals(int goalstate, int number) {
+ syscall( BOTLIB_AI_REMOVE_FROM_AVOID_GOALS, goalstate, number);
+}
+
+void trap_BotPushGoal(int goalstate, void /* struct bot_goal_s */ *goal) {
+ syscall( BOTLIB_AI_PUSH_GOAL, goalstate, goal );
+}
+
+void trap_BotPopGoal(int goalstate) {
+ syscall( BOTLIB_AI_POP_GOAL, goalstate );
+}
+
+void trap_BotEmptyGoalStack(int goalstate) {
+ syscall( BOTLIB_AI_EMPTY_GOAL_STACK, goalstate );
+}
+
+void trap_BotDumpAvoidGoals(int goalstate) {
+ syscall( BOTLIB_AI_DUMP_AVOID_GOALS, goalstate );
+}
+
+void trap_BotDumpGoalStack(int goalstate) {
+ syscall( BOTLIB_AI_DUMP_GOAL_STACK, goalstate );
+}
+
+void trap_BotGoalName(int number, char *name, int size) {
+ syscall( BOTLIB_AI_GOAL_NAME, number, name, size );
+}
+
+int trap_BotGetTopGoal(int goalstate, void /* struct bot_goal_s */ *goal) {
+ return syscall( BOTLIB_AI_GET_TOP_GOAL, goalstate, goal );
+}
+
+int trap_BotGetSecondGoal(int goalstate, void /* struct bot_goal_s */ *goal) {
+ return syscall( BOTLIB_AI_GET_SECOND_GOAL, goalstate, goal );
+}
+
+int trap_BotChooseLTGItem(int goalstate, vec3_t origin, int *inventory, int travelflags) {
+ return syscall( BOTLIB_AI_CHOOSE_LTG_ITEM, goalstate, origin, inventory, travelflags );
+}
+
+int trap_BotChooseNBGItem(int goalstate, vec3_t origin, int *inventory, int travelflags, void /* struct bot_goal_s */ *ltg, float maxtime) {
+ return syscall( BOTLIB_AI_CHOOSE_NBG_ITEM, goalstate, origin, inventory, travelflags, ltg, PASSFLOAT(maxtime) );
+}
+
+int trap_BotTouchingGoal(vec3_t origin, void /* struct bot_goal_s */ *goal) {
+ return syscall( BOTLIB_AI_TOUCHING_GOAL, origin, goal );
+}
+
+int trap_BotItemGoalInVisButNotVisible(int viewer, vec3_t eye, vec3_t viewangles, void /* struct bot_goal_s */ *goal) {
+ return syscall( BOTLIB_AI_ITEM_GOAL_IN_VIS_BUT_NOT_VISIBLE, viewer, eye, viewangles, goal );
+}
+
+int trap_BotGetLevelItemGoal(int index, char *classname, void /* struct bot_goal_s */ *goal) {
+ return syscall( BOTLIB_AI_GET_LEVEL_ITEM_GOAL, index, classname, goal );
+}
+
+int trap_BotGetNextCampSpotGoal(int num, void /* struct bot_goal_s */ *goal) {
+ return syscall( BOTLIB_AI_GET_NEXT_CAMP_SPOT_GOAL, num, goal );
+}
+
+int trap_BotGetMapLocationGoal(char *name, void /* struct bot_goal_s */ *goal) {
+ return syscall( BOTLIB_AI_GET_MAP_LOCATION_GOAL, name, goal );
+}
+
+float trap_BotAvoidGoalTime(int goalstate, int number) {
+ int temp;
+ temp = syscall( BOTLIB_AI_AVOID_GOAL_TIME, goalstate, number );
+ return (*(float*)&temp);
+}
+
+void trap_BotSetAvoidGoalTime(int goalstate, int number, float avoidtime) {
+ syscall( BOTLIB_AI_SET_AVOID_GOAL_TIME, goalstate, number, PASSFLOAT(avoidtime));
+}
+
+void trap_BotInitLevelItems(void) {
+ syscall( BOTLIB_AI_INIT_LEVEL_ITEMS );
+}
+
+void trap_BotUpdateEntityItems(void) {
+ syscall( BOTLIB_AI_UPDATE_ENTITY_ITEMS );
+}
+
+int trap_BotLoadItemWeights(int goalstate, char *filename) {
+ return syscall( BOTLIB_AI_LOAD_ITEM_WEIGHTS, goalstate, filename );
+}
+
+void trap_BotFreeItemWeights(int goalstate) {
+ syscall( BOTLIB_AI_FREE_ITEM_WEIGHTS, goalstate );
+}
+
+void trap_BotInterbreedGoalFuzzyLogic(int parent1, int parent2, int child) {
+ syscall( BOTLIB_AI_INTERBREED_GOAL_FUZZY_LOGIC, parent1, parent2, child );
+}
+
+void trap_BotSaveGoalFuzzyLogic(int goalstate, char *filename) {
+ syscall( BOTLIB_AI_SAVE_GOAL_FUZZY_LOGIC, goalstate, filename );
+}
+
+void trap_BotMutateGoalFuzzyLogic(int goalstate, float range) {
+ syscall( BOTLIB_AI_MUTATE_GOAL_FUZZY_LOGIC, goalstate, range );
+}
+
+int trap_BotAllocGoalState(int state) {
+ return syscall( BOTLIB_AI_ALLOC_GOAL_STATE, state );
+}
+
+void trap_BotFreeGoalState(int handle) {
+ syscall( BOTLIB_AI_FREE_GOAL_STATE, handle );
+}
+
+void trap_BotResetMoveState(int movestate) {
+ syscall( BOTLIB_AI_RESET_MOVE_STATE, movestate );
+}
+
+void trap_BotAddAvoidSpot(int movestate, vec3_t origin, float radius, int type) {
+ syscall( BOTLIB_AI_ADD_AVOID_SPOT, movestate, origin, PASSFLOAT(radius), type);
+}
+
+void trap_BotMoveToGoal(void /* struct bot_moveresult_s */ *result, int movestate, void /* struct bot_goal_s */ *goal, int travelflags) {
+ syscall( BOTLIB_AI_MOVE_TO_GOAL, result, movestate, goal, travelflags );
+}
+
+int trap_BotMoveInDirection(int movestate, vec3_t dir, float speed, int type) {
+ return syscall( BOTLIB_AI_MOVE_IN_DIRECTION, movestate, dir, PASSFLOAT(speed), type );
+}
+
+void trap_BotResetAvoidReach(int movestate) {
+ syscall( BOTLIB_AI_RESET_AVOID_REACH, movestate );
+}
+
+void trap_BotResetLastAvoidReach(int movestate) {
+ syscall( BOTLIB_AI_RESET_LAST_AVOID_REACH,movestate );
+}
+
+int trap_BotReachabilityArea(vec3_t origin, int testground) {
+ return syscall( BOTLIB_AI_REACHABILITY_AREA, origin, testground );
+}
+
+int trap_BotMovementViewTarget(int movestate, void /* struct bot_goal_s */ *goal, int travelflags, float lookahead, vec3_t target) {
+ return syscall( BOTLIB_AI_MOVEMENT_VIEW_TARGET, movestate, goal, travelflags, PASSFLOAT(lookahead), target );
+}
+
+int trap_BotPredictVisiblePosition(vec3_t origin, int areanum, void /* struct bot_goal_s */ *goal, int travelflags, vec3_t target) {
+ return syscall( BOTLIB_AI_PREDICT_VISIBLE_POSITION, origin, areanum, goal, travelflags, target );
+}
+
+int trap_BotAllocMoveState(void) {
+ return syscall( BOTLIB_AI_ALLOC_MOVE_STATE );
+}
+
+void trap_BotFreeMoveState(int handle) {
+ syscall( BOTLIB_AI_FREE_MOVE_STATE, handle );
+}
+
+void trap_BotInitMoveState(int handle, void /* struct bot_initmove_s */ *initmove) {
+ syscall( BOTLIB_AI_INIT_MOVE_STATE, handle, initmove );
+}
+
+int trap_BotChooseBestFightWeapon(int weaponstate, int *inventory) {
+ return syscall( BOTLIB_AI_CHOOSE_BEST_FIGHT_WEAPON, weaponstate, inventory );
+}
+
+void trap_BotGetWeaponInfo(int weaponstate, int weapon, void /* struct weaponinfo_s */ *weaponinfo) {
+ syscall( BOTLIB_AI_GET_WEAPON_INFO, weaponstate, weapon, weaponinfo );
+}
+
+int trap_BotLoadWeaponWeights(int weaponstate, char *filename) {
+ return syscall( BOTLIB_AI_LOAD_WEAPON_WEIGHTS, weaponstate, filename );
+}
+
+int trap_BotAllocWeaponState(void) {
+ return syscall( BOTLIB_AI_ALLOC_WEAPON_STATE );
+}
+
+void trap_BotFreeWeaponState(int weaponstate) {
+ syscall( BOTLIB_AI_FREE_WEAPON_STATE, weaponstate );
+}
+
+void trap_BotResetWeaponState(int weaponstate) {
+ syscall( BOTLIB_AI_RESET_WEAPON_STATE, weaponstate );
+}
+
+int trap_GeneticParentsAndChildSelection(int numranks, float *ranks, int *parent1, int *parent2, int *child) {
+ return syscall( BOTLIB_AI_GENETIC_PARENTS_AND_CHILD_SELECTION, numranks, ranks, parent1, parent2, child );
+}
+
+int trap_PC_LoadSource( const char *filename ) {
+ return syscall( BOTLIB_PC_LOAD_SOURCE, filename );
+}
+
+int trap_PC_FreeSource( int handle ) {
+ return syscall( BOTLIB_PC_FREE_SOURCE, handle );
+}
+
+int trap_PC_ReadToken( int handle, pc_token_t *pc_token ) {
+ return syscall( BOTLIB_PC_READ_TOKEN, handle, pc_token );
+}
+
+int trap_PC_SourceFileAndLine( int handle, char *filename, int *line ) {
+ return syscall( BOTLIB_PC_SOURCE_FILE_AND_LINE, handle, filename, line );
+}
diff --git a/code/game/g_target.c b/code/game/g_target.c
new file mode 100755
index 0000000..bd3e731
--- /dev/null
+++ b/code/game/g_target.c
@@ -0,0 +1,467 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#include "g_local.h"
+
+//==========================================================
+
+/*QUAKED target_give (1 0 0) (-8 -8 -8) (8 8 8)
+Gives the activator all the items pointed to.
+*/
+void Use_Target_Give( gentity_t *ent, gentity_t *other, gentity_t *activator ) {
+ gentity_t *t;
+ trace_t trace;
+
+ if ( !activator->client ) {
+ return;
+ }
+
+ if ( !ent->target ) {
+ return;
+ }
+
+ memset( &trace, 0, sizeof( trace ) );
+ t = NULL;
+ while ( (t = G_Find (t, FOFS(targetname), ent->target)) != NULL ) {
+ if ( !t->item ) {
+ continue;
+ }
+ Touch_Item( t, activator, &trace );
+
+ // make sure it isn't going to respawn or show any events
+ t->nextthink = 0;
+ trap_UnlinkEntity( t );
+ }
+}
+
+void SP_target_give( gentity_t *ent ) {
+ ent->use = Use_Target_Give;
+}
+
+
+//==========================================================
+
+/*QUAKED target_remove_powerups (1 0 0) (-8 -8 -8) (8 8 8)
+takes away all the activators powerups.
+Used to drop flight powerups into death puts.
+*/
+void Use_target_remove_powerups( gentity_t *ent, gentity_t *other, gentity_t *activator ) {
+ if( !activator->client ) {
+ return;
+ }
+
+ if( activator->client->ps.powerups[PW_REDFLAG] ) {
+ Team_ReturnFlag( TEAM_RED );
+ } else if( activator->client->ps.powerups[PW_BLUEFLAG] ) {
+ Team_ReturnFlag( TEAM_BLUE );
+ } else if( activator->client->ps.powerups[PW_NEUTRALFLAG] ) {
+ Team_ReturnFlag( TEAM_FREE );
+ }
+
+ memset( activator->client->ps.powerups, 0, sizeof( activator->client->ps.powerups ) );
+}
+
+void SP_target_remove_powerups( gentity_t *ent ) {
+ ent->use = Use_target_remove_powerups;
+}
+
+
+//==========================================================
+
+/*QUAKED target_delay (1 0 0) (-8 -8 -8) (8 8 8)
+"wait" seconds to pause before firing targets.
+"random" delay variance, total delay = delay +/- random seconds
+*/
+void Think_Target_Delay( gentity_t *ent ) {
+ G_UseTargets( ent, ent->activator );
+}
+
+void Use_Target_Delay( gentity_t *ent, gentity_t *other, gentity_t *activator ) {
+ ent->nextthink = level.time + ( ent->wait + ent->random * crandom() ) * 1000;
+ ent->think = Think_Target_Delay;
+ ent->activator = activator;
+}
+
+void SP_target_delay( gentity_t *ent ) {
+ // check delay for backwards compatability
+ if ( !G_SpawnFloat( "delay", "0", &ent->wait ) ) {
+ G_SpawnFloat( "wait", "1", &ent->wait );
+ }
+
+ if ( !ent->wait ) {
+ ent->wait = 1;
+ }
+ ent->use = Use_Target_Delay;
+}
+
+
+//==========================================================
+
+/*QUAKED target_score (1 0 0) (-8 -8 -8) (8 8 8)
+"count" number of points to add, default 1
+
+The activator is given this many points.
+*/
+void Use_Target_Score (gentity_t *ent, gentity_t *other, gentity_t *activator) {
+ AddScore( activator, ent->r.currentOrigin, ent->count );
+}
+
+void SP_target_score( gentity_t *ent ) {
+ if ( !ent->count ) {
+ ent->count = 1;
+ }
+ ent->use = Use_Target_Score;
+}
+
+
+//==========================================================
+
+/*QUAKED target_print (1 0 0) (-8 -8 -8) (8 8 8) redteam blueteam private
+"message" text to print
+If "private", only the activator gets the message. If no checks, all clients get the message.
+*/
+void Use_Target_Print (gentity_t *ent, gentity_t *other, gentity_t *activator) {
+ if ( activator->client && ( ent->spawnflags & 4 ) ) {
+ trap_SendServerCommand( activator-g_entities, va("cp \"%s\"", ent->message ));
+ return;
+ }
+
+ if ( ent->spawnflags & 3 ) {
+ if ( ent->spawnflags & 1 ) {
+ G_TeamCommand( TEAM_RED, va("cp \"%s\"", ent->message) );
+ }
+ if ( ent->spawnflags & 2 ) {
+ G_TeamCommand( TEAM_BLUE, va("cp \"%s\"", ent->message) );
+ }
+ return;
+ }
+
+ trap_SendServerCommand( -1, va("cp \"%s\"", ent->message ));
+}
+
+void SP_target_print( gentity_t *ent ) {
+ ent->use = Use_Target_Print;
+}
+
+
+//==========================================================
+
+
+/*QUAKED target_speaker (1 0 0) (-8 -8 -8) (8 8 8) looped-on looped-off global activator
+"noise" wav file to play
+
+A global sound will play full volume throughout the level.
+Activator sounds will play on the player that activated the target.
+Global and activator sounds can't be combined with looping.
+Normal sounds play each time the target is used.
+Looped sounds will be toggled by use functions.
+Multiple identical looping sounds will just increase volume without any speed cost.
+"wait" : Seconds between auto triggerings, 0 = don't auto trigger
+"random" wait variance, default is 0
+*/
+void Use_Target_Speaker (gentity_t *ent, gentity_t *other, gentity_t *activator) {
+ if (ent->spawnflags & 3) { // looping sound toggles
+ if (ent->s.loopSound)
+ ent->s.loopSound = 0; // turn it off
+ else
+ ent->s.loopSound = ent->noise_index; // start it
+ }else { // normal sound
+ if ( ent->spawnflags & 8 ) {
+ G_AddEvent( activator, EV_GENERAL_SOUND, ent->noise_index );
+ } else if (ent->spawnflags & 4) {
+ G_AddEvent( ent, EV_GLOBAL_SOUND, ent->noise_index );
+ } else {
+ G_AddEvent( ent, EV_GENERAL_SOUND, ent->noise_index );
+ }
+ }
+}
+
+void SP_target_speaker( gentity_t *ent ) {
+ char buffer[MAX_QPATH];
+ char *s;
+
+ G_SpawnFloat( "wait", "0", &ent->wait );
+ G_SpawnFloat( "random", "0", &ent->random );
+
+ if ( !G_SpawnString( "noise", "NOSOUND", &s ) ) {
+ G_Error( "target_speaker without a noise key at %s", vtos( ent->s.origin ) );
+ }
+
+ // force all client reletive sounds to be "activator" speakers that
+ // play on the entity that activates it
+ if ( s[0] == '*' ) {
+ ent->spawnflags |= 8;
+ }
+
+ if (!strstr( s, ".wav" )) {
+ Com_sprintf (buffer, sizeof(buffer), "%s.wav", s );
+ } else {
+ Q_strncpyz( buffer, s, sizeof(buffer) );
+ }
+ ent->noise_index = G_SoundIndex(buffer);
+
+ // a repeating speaker can be done completely client side
+ ent->s.eType = ET_SPEAKER;
+ ent->s.eventParm = ent->noise_index;
+ ent->s.frame = ent->wait * 10;
+ ent->s.clientNum = ent->random * 10;
+
+
+ // check for prestarted looping sound
+ if ( ent->spawnflags & 1 ) {
+ ent->s.loopSound = ent->noise_index;
+ }
+
+ ent->use = Use_Target_Speaker;
+
+ if (ent->spawnflags & 4) {
+ ent->r.svFlags |= SVF_BROADCAST;
+ }
+
+ VectorCopy( ent->s.origin, ent->s.pos.trBase );
+
+ // must link the entity so we get areas and clusters so
+ // the server can determine who to send updates to
+ trap_LinkEntity( ent );
+}
+
+
+
+//==========================================================
+
+/*QUAKED target_laser (0 .5 .8) (-8 -8 -8) (8 8 8) START_ON
+When triggered, fires a laser. You can either set a target or a direction.
+*/
+void target_laser_think (gentity_t *self) {
+ vec3_t end;
+ trace_t tr;
+ vec3_t point;
+
+ // if pointed at another entity, set movedir to point at it
+ if ( self->enemy ) {
+ VectorMA (self->enemy->s.origin, 0.5, self->enemy->r.mins, point);
+ VectorMA (point, 0.5, self->enemy->r.maxs, point);
+ VectorSubtract (point, self->s.origin, self->movedir);
+ VectorNormalize (self->movedir);
+ }
+
+ // fire forward and see what we hit
+ VectorMA (self->s.origin, 2048, self->movedir, end);
+
+ trap_Trace( &tr, self->s.origin, NULL, NULL, end, self->s.number, CONTENTS_SOLID|CONTENTS_BODY|CONTENTS_CORPSE);
+
+ if ( tr.entityNum ) {
+ // hurt it if we can
+ G_Damage ( &g_entities[tr.entityNum], self, self->activator, self->movedir,
+ tr.endpos, self->damage, DAMAGE_NO_KNOCKBACK, MOD_TARGET_LASER);
+ }
+
+ VectorCopy (tr.endpos, self->s.origin2);
+
+ trap_LinkEntity( self );
+ self->nextthink = level.time + FRAMETIME;
+}
+
+void target_laser_on (gentity_t *self)
+{
+ if (!self->activator)
+ self->activator = self;
+ target_laser_think (self);
+}
+
+void target_laser_off (gentity_t *self)
+{
+ trap_UnlinkEntity( self );
+ self->nextthink = 0;
+}
+
+void target_laser_use (gentity_t *self, gentity_t *other, gentity_t *activator)
+{
+ self->activator = activator;
+ if ( self->nextthink > 0 )
+ target_laser_off (self);
+ else
+ target_laser_on (self);
+}
+
+void target_laser_start (gentity_t *self)
+{
+ gentity_t *ent;
+
+ self->s.eType = ET_BEAM;
+
+ if (self->target) {
+ ent = G_Find (NULL, FOFS(targetname), self->target);
+ if (!ent) {
+ G_Printf ("%s at %s: %s is a bad target\n", self->classname, vtos(self->s.origin), self->target);
+ }
+ self->enemy = ent;
+ } else {
+ G_SetMovedir (self->s.angles, self->movedir);
+ }
+
+ self->use = target_laser_use;
+ self->think = target_laser_think;
+
+ if ( !self->damage ) {
+ self->damage = 1;
+ }
+
+ if (self->spawnflags & 1)
+ target_laser_on (self);
+ else
+ target_laser_off (self);
+}
+
+void SP_target_laser (gentity_t *self)
+{
+ // let everything else get spawned before we start firing
+ self->think = target_laser_start;
+ self->nextthink = level.time + FRAMETIME;
+}
+
+
+//==========================================================
+
+void target_teleporter_use( gentity_t *self, gentity_t *other, gentity_t *activator ) {
+ gentity_t *dest;
+
+ if (!activator->client)
+ return;
+ dest = G_PickTarget( self->target );
+ if (!dest) {
+ G_Printf ("Couldn't find teleporter destination\n");
+ return;
+ }
+
+ TeleportPlayer( activator, dest->s.origin, dest->s.angles );
+}
+
+/*QUAKED target_teleporter (1 0 0) (-8 -8 -8) (8 8 8)
+The activator will be teleported away.
+*/
+void SP_target_teleporter( gentity_t *self ) {
+ if (!self->targetname)
+ G_Printf("untargeted %s at %s\n", self->classname, vtos(self->s.origin));
+
+ self->use = target_teleporter_use;
+}
+
+//==========================================================
+
+
+/*QUAKED target_relay (.5 .5 .5) (-8 -8 -8) (8 8 8) RED_ONLY BLUE_ONLY RANDOM
+This doesn't perform any actions except fire its targets.
+The activator can be forced to be from a certain team.
+if RANDOM is checked, only one of the targets will be fired, not all of them
+*/
+void target_relay_use (gentity_t *self, gentity_t *other, gentity_t *activator) {
+ if ( ( self->spawnflags & 1 ) && activator->client
+ && activator->client->sess.sessionTeam != TEAM_RED ) {
+ return;
+ }
+ if ( ( self->spawnflags & 2 ) && activator->client
+ && activator->client->sess.sessionTeam != TEAM_BLUE ) {
+ return;
+ }
+ if ( self->spawnflags & 4 ) {
+ gentity_t *ent;
+
+ ent = G_PickTarget( self->target );
+ if ( ent && ent->use ) {
+ ent->use( ent, self, activator );
+ }
+ return;
+ }
+ G_UseTargets (self, activator);
+}
+
+void SP_target_relay (gentity_t *self) {
+ self->use = target_relay_use;
+}
+
+
+//==========================================================
+
+/*QUAKED target_kill (.5 .5 .5) (-8 -8 -8) (8 8 8)
+Kills the activator.
+*/
+void target_kill_use( gentity_t *self, gentity_t *other, gentity_t *activator ) {
+ G_Damage ( activator, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, MOD_TELEFRAG);
+}
+
+void SP_target_kill( gentity_t *self ) {
+ self->use = target_kill_use;
+}
+
+/*QUAKED target_position (0 0.5 0) (-4 -4 -4) (4 4 4)
+Used as a positional target for in-game calculation, like jumppad targets.
+*/
+void SP_target_position( gentity_t *self ){
+ G_SetOrigin( self, self->s.origin );
+}
+
+static void target_location_linkup(gentity_t *ent)
+{
+ int i;
+ int n;
+
+ if (level.locationLinked)
+ return;
+
+ level.locationLinked = qtrue;
+
+ level.locationHead = NULL;
+
+ trap_SetConfigstring( CS_LOCATIONS, "unknown" );
+
+ for (i = 0, ent = g_entities, n = 1;
+ i < level.num_entities;
+ i++, ent++) {
+ if (ent->classname && !Q_stricmp(ent->classname, "target_location")) {
+ // lets overload some variables!
+ ent->health = n; // use for location marking
+ trap_SetConfigstring( CS_LOCATIONS + n, ent->message );
+ n++;
+ ent->nextTrain = level.locationHead;
+ level.locationHead = ent;
+ }
+ }
+
+ // All linked together now
+}
+
+/*QUAKED target_location (0 0.5 0) (-8 -8 -8) (8 8 8)
+Set "message" to the name of this location.
+Set "count" to 0-7 for color.
+0:white 1:red 2:green 3:yellow 4:blue 5:cyan 6:magenta 7:white
+
+Closest target_location in sight used for the location, if none
+in site, closest in distance
+*/
+void SP_target_location( gentity_t *self ){
+ self->think = target_location_linkup;
+ self->nextthink = level.time + 200; // Let them all spawn first
+
+ G_SetOrigin( self, self->s.origin );
+}
+
diff --git a/code/game/g_team.c b/code/game/g_team.c
new file mode 100755
index 0000000..6f6b413
--- /dev/null
+++ b/code/game/g_team.c
@@ -0,0 +1,1483 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+#include "g_local.h"
+
+
+typedef struct teamgame_s {
+ float last_flag_capture;
+ int last_capture_team;
+ flagStatus_t redStatus; // CTF
+ flagStatus_t blueStatus; // CTF
+ flagStatus_t flagStatus; // One Flag CTF
+ int redTakenTime;
+ int blueTakenTime;
+ int redObeliskAttackedTime;
+ int blueObeliskAttackedTime;
+} teamgame_t;
+
+teamgame_t teamgame;
+
+gentity_t *neutralObelisk;
+
+void Team_SetFlagStatus( int team, flagStatus_t status );
+
+void Team_InitGame( void ) {
+ memset(&teamgame, 0, sizeof teamgame);
+
+ switch( g_gametype.integer ) {
+ case GT_CTF:
+ teamgame.redStatus = teamgame.blueStatus = -1; // Invalid to force update
+ Team_SetFlagStatus( TEAM_RED, FLAG_ATBASE );
+ Team_SetFlagStatus( TEAM_BLUE, FLAG_ATBASE );
+ break;
+#ifdef MISSIONPACK
+ case GT_1FCTF:
+ teamgame.flagStatus = -1; // Invalid to force update
+ Team_SetFlagStatus( TEAM_FREE, FLAG_ATBASE );
+ break;
+#endif
+ default:
+ break;
+ }
+}
+
+int OtherTeam(int team) {
+ if (team==TEAM_RED)
+ return TEAM_BLUE;
+ else if (team==TEAM_BLUE)
+ return TEAM_RED;
+ return team;
+}
+
+const char *TeamName(int team) {
+ if (team==TEAM_RED)
+ return "RED";
+ else if (team==TEAM_BLUE)
+ return "BLUE";
+ else if (team==TEAM_SPECTATOR)
+ return "SPECTATOR";
+ return "FREE";
+}
+
+const char *OtherTeamName(int team) {
+ if (team==TEAM_RED)
+ return "BLUE";
+ else if (team==TEAM_BLUE)
+ return "RED";
+ else if (team==TEAM_SPECTATOR)
+ return "SPECTATOR";
+ return "FREE";
+}
+
+const char *TeamColorString(int team) {
+ if (team==TEAM_RED)
+ return S_COLOR_RED;
+ else if (team==TEAM_BLUE)
+ return S_COLOR_BLUE;
+ else if (team==TEAM_SPECTATOR)
+ return S_COLOR_YELLOW;
+ return S_COLOR_WHITE;
+}
+
+// NULL for everyone
+void QDECL PrintMsg( gentity_t *ent, const char *fmt, ... ) {
+ char msg[1024];
+ va_list argptr;
+ char *p;
+
+ va_start (argptr,fmt);
+ if (vsprintf (msg, fmt, argptr) > sizeof(msg)) {
+ G_Error ( "PrintMsg overrun" );
+ }
+ va_end (argptr);
+
+ // double quotes are bad
+ while ((p = strchr(msg, '"')) != NULL)
+ *p = '\'';
+
+ trap_SendServerCommand ( ( (ent == NULL) ? -1 : ent-g_entities ), va("print \"%s\"", msg ));
+}
+
+/*
+==============
+AddTeamScore
+
+ used for gametype > GT_TEAM
+ for gametype GT_TEAM the level.teamScores is updated in AddScore in g_combat.c
+==============
+*/
+void AddTeamScore(vec3_t origin, int team, int score) {
+ gentity_t *te;
+
+ te = G_TempEntity(origin, EV_GLOBAL_TEAM_SOUND );
+ te->r.svFlags |= SVF_BROADCAST;
+
+ if ( team == TEAM_RED ) {
+ if ( level.teamScores[ TEAM_RED ] + score == level.teamScores[ TEAM_BLUE ] ) {
+ //teams are tied sound
+ te->s.eventParm = GTS_TEAMS_ARE_TIED;
+ }
+ else if ( level.teamScores[ TEAM_RED ] <= level.teamScores[ TEAM_BLUE ] &&
+ level.teamScores[ TEAM_RED ] + score > level.teamScores[ TEAM_BLUE ]) {
+ // red took the lead sound
+ te->s.eventParm = GTS_REDTEAM_TOOK_LEAD;
+ }
+ else {
+ // red scored sound
+ te->s.eventParm = GTS_REDTEAM_SCORED;
+ }
+ }
+ else {
+ if ( level.teamScores[ TEAM_BLUE ] + score == level.teamScores[ TEAM_RED ] ) {
+ //teams are tied sound
+ te->s.eventParm = GTS_TEAMS_ARE_TIED;
+ }
+ else if ( level.teamScores[ TEAM_BLUE ] <= level.teamScores[ TEAM_RED ] &&
+ level.teamScores[ TEAM_BLUE ] + score > level.teamScores[ TEAM_RED ]) {
+ // blue took the lead sound
+ te->s.eventParm = GTS_BLUETEAM_TOOK_LEAD;
+ }
+ else {
+ // blue scored sound
+ te->s.eventParm = GTS_BLUETEAM_SCORED;
+ }
+ }
+ level.teamScores[ team ] += score;
+}
+
+/*
+==============
+OnSameTeam
+==============
+*/
+qboolean OnSameTeam( gentity_t *ent1, gentity_t *ent2 ) {
+ if ( !ent1->client || !ent2->client ) {
+ return qfalse;
+ }
+
+ if ( g_gametype.integer < GT_TEAM ) {
+ return qfalse;
+ }
+
+ if ( ent1->client->sess.sessionTeam == ent2->client->sess.sessionTeam ) {
+ return qtrue;
+ }
+
+ return qfalse;
+}
+
+
+static char ctfFlagStatusRemap[] = { '0', '1', '*', '*', '2' };
+static char oneFlagStatusRemap[] = { '0', '1', '2', '3', '4' };
+
+void Team_SetFlagStatus( int team, flagStatus_t status ) {
+ qboolean modified = qfalse;
+
+ switch( team ) {
+ case TEAM_RED: // CTF
+ if( teamgame.redStatus != status ) {
+ teamgame.redStatus = status;
+ modified = qtrue;
+ }
+ break;
+
+ case TEAM_BLUE: // CTF
+ if( teamgame.blueStatus != status ) {
+ teamgame.blueStatus = status;
+ modified = qtrue;
+ }
+ break;
+
+ case TEAM_FREE: // One Flag CTF
+ if( teamgame.flagStatus != status ) {
+ teamgame.flagStatus = status;
+ modified = qtrue;
+ }
+ break;
+ }
+
+ if( modified ) {
+ char st[4];
+
+ if( g_gametype.integer == GT_CTF ) {
+ st[0] = ctfFlagStatusRemap[teamgame.redStatus];
+ st[1] = ctfFlagStatusRemap[teamgame.blueStatus];
+ st[2] = 0;
+ }
+ else { // GT_1FCTF
+ st[0] = oneFlagStatusRemap[teamgame.flagStatus];
+ st[1] = 0;
+ }
+
+ trap_SetConfigstring( CS_FLAGSTATUS, st );
+ }
+}
+
+void Team_CheckDroppedItem( gentity_t *dropped ) {
+ if( dropped->item->giTag == PW_REDFLAG ) {
+ Team_SetFlagStatus( TEAM_RED, FLAG_DROPPED );
+ }
+ else if( dropped->item->giTag == PW_BLUEFLAG ) {
+ Team_SetFlagStatus( TEAM_BLUE, FLAG_DROPPED );
+ }
+ else if( dropped->item->giTag == PW_NEUTRALFLAG ) {
+ Team_SetFlagStatus( TEAM_FREE, FLAG_DROPPED );
+ }
+}
+
+/*
+================
+Team_ForceGesture
+================
+*/
+void Team_ForceGesture(int team) {
+ int i;
+ gentity_t *ent;
+
+ for (i = 0; i < MAX_CLIENTS; i++) {
+ ent = &g_entities[i];
+ if (!ent->inuse)
+ continue;
+ if (!ent->client)
+ continue;
+ if (ent->client->sess.sessionTeam != team)
+ continue;
+ //
+ ent->flags |= FL_FORCE_GESTURE;
+ }
+}
+
+/*
+================
+Team_FragBonuses
+
+Calculate the bonuses for flag defense, flag carrier defense, etc.
+Note that bonuses are not cumulative. You get one, they are in importance
+order.
+================
+*/
+void Team_FragBonuses(gentity_t *targ, gentity_t *inflictor, gentity_t *attacker)
+{
+ int i;
+ gentity_t *ent;
+ int flag_pw, enemy_flag_pw;
+ int otherteam;
+ int tokens;
+ gentity_t *flag, *carrier = NULL;
+ char *c;
+ vec3_t v1, v2;
+ int team;
+
+ // no bonus for fragging yourself or team mates
+ if (!targ->client || !attacker->client || targ == attacker || OnSameTeam(targ, attacker))
+ return;
+
+ team = targ->client->sess.sessionTeam;
+ otherteam = OtherTeam(targ->client->sess.sessionTeam);
+ if (otherteam < 0)
+ return; // whoever died isn't on a team
+
+ // same team, if the flag at base, check to he has the enemy flag
+ if (team == TEAM_RED) {
+ flag_pw = PW_REDFLAG;
+ enemy_flag_pw = PW_BLUEFLAG;
+ } else {
+ flag_pw = PW_BLUEFLAG;
+ enemy_flag_pw = PW_REDFLAG;
+ }
+
+ if (g_gametype.integer == GT_1FCTF) {
+ enemy_flag_pw = PW_NEUTRALFLAG;
+ }
+
+ // did the attacker frag the flag carrier?
+ tokens = 0;
+#ifdef MISSIONPACK
+ if( g_gametype.integer == GT_HARVESTER ) {
+ tokens = targ->client->ps.generic1;
+ }
+#endif
+ if (targ->client->ps.powerups[enemy_flag_pw]) {
+ attacker->client->pers.teamState.lastfraggedcarrier = level.time;
+ AddScore(attacker, targ->r.currentOrigin, CTF_FRAG_CARRIER_BONUS);
+ attacker->client->pers.teamState.fragcarrier++;
+ PrintMsg(NULL, "%s" S_COLOR_WHITE " fragged %s's flag carrier!\n",
+ attacker->client->pers.netname, TeamName(team));
+
+ // the target had the flag, clear the hurt carrier
+ // field on the other team
+ for (i = 0; i < g_maxclients.integer; i++) {
+ ent = g_entities + i;
+ if (ent->inuse && ent->client->sess.sessionTeam == otherteam)
+ ent->client->pers.teamState.lasthurtcarrier = 0;
+ }
+ return;
+ }
+
+ // did the attacker frag a head carrier? other->client->ps.generic1
+ if (tokens) {
+ attacker->client->pers.teamState.lastfraggedcarrier = level.time;
+ AddScore(attacker, targ->r.currentOrigin, CTF_FRAG_CARRIER_BONUS * tokens * tokens);
+ attacker->client->pers.teamState.fragcarrier++;
+ PrintMsg(NULL, "%s" S_COLOR_WHITE " fragged %s's skull carrier!\n",
+ attacker->client->pers.netname, TeamName(team));
+
+ // the target had the flag, clear the hurt carrier
+ // field on the other team
+ for (i = 0; i < g_maxclients.integer; i++) {
+ ent = g_entities + i;
+ if (ent->inuse && ent->client->sess.sessionTeam == otherteam)
+ ent->client->pers.teamState.lasthurtcarrier = 0;
+ }
+ return;
+ }
+
+ if (targ->client->pers.teamState.lasthurtcarrier &&
+ level.time - targ->client->pers.teamState.lasthurtcarrier < CTF_CARRIER_DANGER_PROTECT_TIMEOUT &&
+ !attacker->client->ps.powerups[flag_pw]) {
+ // attacker is on the same team as the flag carrier and
+ // fragged a guy who hurt our flag carrier
+ AddScore(attacker, targ->r.currentOrigin, CTF_CARRIER_DANGER_PROTECT_BONUS);
+
+ attacker->client->pers.teamState.carrierdefense++;
+ targ->client->pers.teamState.lasthurtcarrier = 0;
+
+ attacker->client->ps.persistant[PERS_DEFEND_COUNT]++;
+ team = attacker->client->sess.sessionTeam;
+ // add the sprite over the player's head
+ attacker->client->ps.eFlags &= ~(EF_AWARD_IMPRESSIVE | EF_AWARD_EXCELLENT | EF_AWARD_GAUNTLET | EF_AWARD_ASSIST | EF_AWARD_DEFEND | EF_AWARD_CAP );
+ attacker->client->ps.eFlags |= EF_AWARD_DEFEND;
+ attacker->client->rewardTime = level.time + REWARD_SPRITE_TIME;
+
+ return;
+ }
+
+ if (targ->client->pers.teamState.lasthurtcarrier &&
+ level.time - targ->client->pers.teamState.lasthurtcarrier < CTF_CARRIER_DANGER_PROTECT_TIMEOUT) {
+ // attacker is on the same team as the skull carrier and
+ AddScore(attacker, targ->r.currentOrigin, CTF_CARRIER_DANGER_PROTECT_BONUS);
+
+ attacker->client->pers.teamState.carrierdefense++;
+ targ->client->pers.teamState.lasthurtcarrier = 0;
+
+ attacker->client->ps.persistant[PERS_DEFEND_COUNT]++;
+ team = attacker->client->sess.sessionTeam;
+ // add the sprite over the player's head
+ attacker->client->ps.eFlags &= ~(EF_AWARD_IMPRESSIVE | EF_AWARD_EXCELLENT | EF_AWARD_GAUNTLET | EF_AWARD_ASSIST | EF_AWARD_DEFEND | EF_AWARD_CAP );
+ attacker->client->ps.eFlags |= EF_AWARD_DEFEND;
+ attacker->client->rewardTime = level.time + REWARD_SPRITE_TIME;
+
+ return;
+ }
+
+ // flag and flag carrier area defense bonuses
+
+ // we have to find the flag and carrier entities
+
+#ifdef MISSIONPACK
+ if( g_gametype.integer == GT_OBELISK ) {
+ // find the team obelisk
+ switch (attacker->client->sess.sessionTeam) {
+ case TEAM_RED:
+ c = "team_redobelisk";
+ break;
+ case TEAM_BLUE:
+ c = "team_blueobelisk";
+ break;
+ default:
+ return;
+ }
+
+ } else if (g_gametype.integer == GT_HARVESTER ) {
+ // find the center obelisk
+ c = "team_neutralobelisk";
+ } else {
+#endif
+ // find the flag
+ switch (attacker->client->sess.sessionTeam) {
+ case TEAM_RED:
+ c = "team_CTF_redflag";
+ break;
+ case TEAM_BLUE:
+ c = "team_CTF_blueflag";
+ break;
+ default:
+ return;
+ }
+ // find attacker's team's flag carrier
+ for (i = 0; i < g_maxclients.integer; i++) {
+ carrier = g_entities + i;
+ if (carrier->inuse && carrier->client->ps.powerups[flag_pw])
+ break;
+ carrier = NULL;
+ }
+#ifdef MISSIONPACK
+ }
+#endif
+ flag = NULL;
+ while ((flag = G_Find (flag, FOFS(classname), c)) != NULL) {
+ if (!(flag->flags & FL_DROPPED_ITEM))
+ break;
+ }
+
+ if (!flag)
+ return; // can't find attacker's flag
+
+ // ok we have the attackers flag and a pointer to the carrier
+
+ // check to see if we are defending the base's flag
+ VectorSubtract(targ->r.currentOrigin, flag->r.currentOrigin, v1);
+ VectorSubtract(attacker->r.currentOrigin, flag->r.currentOrigin, v2);
+
+ if ( ( ( VectorLength(v1) < CTF_TARGET_PROTECT_RADIUS &&
+ trap_InPVS(flag->r.currentOrigin, targ->r.currentOrigin ) ) ||
+ ( VectorLength(v2) < CTF_TARGET_PROTECT_RADIUS &&
+ trap_InPVS(flag->r.currentOrigin, attacker->r.currentOrigin ) ) ) &&
+ attacker->client->sess.sessionTeam != targ->client->sess.sessionTeam) {
+
+ // we defended the base flag
+ AddScore(attacker, targ->r.currentOrigin, CTF_FLAG_DEFENSE_BONUS);
+ attacker->client->pers.teamState.basedefense++;
+
+ attacker->client->ps.persistant[PERS_DEFEND_COUNT]++;
+ // add the sprite over the player's head
+ attacker->client->ps.eFlags &= ~(EF_AWARD_IMPRESSIVE | EF_AWARD_EXCELLENT | EF_AWARD_GAUNTLET | EF_AWARD_ASSIST | EF_AWARD_DEFEND | EF_AWARD_CAP );
+ attacker->client->ps.eFlags |= EF_AWARD_DEFEND;
+ attacker->client->rewardTime = level.time + REWARD_SPRITE_TIME;
+
+ return;
+ }
+
+ if (carrier && carrier != attacker) {
+ VectorSubtract(targ->r.currentOrigin, carrier->r.currentOrigin, v1);
+ VectorSubtract(attacker->r.currentOrigin, carrier->r.currentOrigin, v1);
+
+ if ( ( ( VectorLength(v1) < CTF_ATTACKER_PROTECT_RADIUS &&
+ trap_InPVS(carrier->r.currentOrigin, targ->r.currentOrigin ) ) ||
+ ( VectorLength(v2) < CTF_ATTACKER_PROTECT_RADIUS &&
+ trap_InPVS(carrier->r.currentOrigin, attacker->r.currentOrigin ) ) ) &&
+ attacker->client->sess.sessionTeam != targ->client->sess.sessionTeam) {
+ AddScore(attacker, targ->r.currentOrigin, CTF_CARRIER_PROTECT_BONUS);
+ attacker->client->pers.teamState.carrierdefense++;
+
+ attacker->client->ps.persistant[PERS_DEFEND_COUNT]++;
+ // add the sprite over the player's head
+ attacker->client->ps.eFlags &= ~(EF_AWARD_IMPRESSIVE | EF_AWARD_EXCELLENT | EF_AWARD_GAUNTLET | EF_AWARD_ASSIST | EF_AWARD_DEFEND | EF_AWARD_CAP );
+ attacker->client->ps.eFlags |= EF_AWARD_DEFEND;
+ attacker->client->rewardTime = level.time + REWARD_SPRITE_TIME;
+
+ return;
+ }
+ }
+}
+
+/*
+================
+Team_CheckHurtCarrier
+
+Check to see if attacker hurt the flag carrier. Needed when handing out bonuses for assistance to flag
+carrier defense.
+================
+*/
+void Team_CheckHurtCarrier(gentity_t *targ, gentity_t *attacker)
+{
+ int flag_pw;
+
+ if (!targ->client || !attacker->client)
+ return;
+
+ if (targ->client->sess.sessionTeam == TEAM_RED)
+ flag_pw = PW_BLUEFLAG;
+ else
+ flag_pw = PW_REDFLAG;
+
+ // flags
+ if (targ->client->ps.powerups[flag_pw] &&
+ targ->client->sess.sessionTeam != attacker->client->sess.sessionTeam)
+ attacker->client->pers.teamState.lasthurtcarrier = level.time;
+
+ // skulls
+ if (targ->client->ps.generic1 &&
+ targ->client->sess.sessionTeam != attacker->client->sess.sessionTeam)
+ attacker->client->pers.teamState.lasthurtcarrier = level.time;
+}
+
+
+gentity_t *Team_ResetFlag( int team ) {
+ char *c;
+ gentity_t *ent, *rent = NULL;
+
+ switch (team) {
+ case TEAM_RED:
+ c = "team_CTF_redflag";
+ break;
+ case TEAM_BLUE:
+ c = "team_CTF_blueflag";
+ break;
+ case TEAM_FREE:
+ c = "team_CTF_neutralflag";
+ break;
+ default:
+ return NULL;
+ }
+
+ ent = NULL;
+ while ((ent = G_Find (ent, FOFS(classname), c)) != NULL) {
+ if (ent->flags & FL_DROPPED_ITEM)
+ G_FreeEntity(ent);
+ else {
+ rent = ent;
+ RespawnItem(ent);
+ }
+ }
+
+ Team_SetFlagStatus( team, FLAG_ATBASE );
+
+ return rent;
+}
+
+void Team_ResetFlags( void ) {
+ if( g_gametype.integer == GT_CTF ) {
+ Team_ResetFlag( TEAM_RED );
+ Team_ResetFlag( TEAM_BLUE );
+ }
+#ifdef MISSIONPACK
+ else if( g_gametype.integer == GT_1FCTF ) {
+ Team_ResetFlag( TEAM_FREE );
+ }
+#endif
+}
+
+void Team_ReturnFlagSound( gentity_t *ent, int team ) {
+ gentity_t *te;
+
+ if (ent == NULL) {
+ G_Printf ("Warning: NULL passed to Team_ReturnFlagSound\n");
+ return;
+ }
+
+ te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_TEAM_SOUND );
+ if( team == TEAM_BLUE ) {
+ te->s.eventParm = GTS_RED_RETURN;
+ }
+ else {
+ te->s.eventParm = GTS_BLUE_RETURN;
+ }
+ te->r.svFlags |= SVF_BROADCAST;
+}
+
+void Team_TakeFlagSound( gentity_t *ent, int team ) {
+ gentity_t *te;
+
+ if (ent == NULL) {
+ G_Printf ("Warning: NULL passed to Team_TakeFlagSound\n");
+ return;
+ }
+
+ // only play sound when the flag was at the base
+ // or not picked up the last 10 seconds
+ switch(team) {
+ case TEAM_RED:
+ if( teamgame.blueStatus != FLAG_ATBASE ) {
+ if (teamgame.blueTakenTime > level.time - 10000)
+ return;
+ }
+ teamgame.blueTakenTime = level.time;
+ break;
+
+ case TEAM_BLUE: // CTF
+ if( teamgame.redStatus != FLAG_ATBASE ) {
+ if (teamgame.redTakenTime > level.time - 10000)
+ return;
+ }
+ teamgame.redTakenTime = level.time;
+ break;
+ }
+
+ te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_TEAM_SOUND );
+ if( team == TEAM_BLUE ) {
+ te->s.eventParm = GTS_RED_TAKEN;
+ }
+ else {
+ te->s.eventParm = GTS_BLUE_TAKEN;
+ }
+ te->r.svFlags |= SVF_BROADCAST;
+}
+
+void Team_CaptureFlagSound( gentity_t *ent, int team ) {
+ gentity_t *te;
+
+ if (ent == NULL) {
+ G_Printf ("Warning: NULL passed to Team_CaptureFlagSound\n");
+ return;
+ }
+
+ te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_TEAM_SOUND );
+ if( team == TEAM_BLUE ) {
+ te->s.eventParm = GTS_BLUE_CAPTURE;
+ }
+ else {
+ te->s.eventParm = GTS_RED_CAPTURE;
+ }
+ te->r.svFlags |= SVF_BROADCAST;
+}
+
+void Team_ReturnFlag( int team ) {
+ Team_ReturnFlagSound(Team_ResetFlag(team), team);
+ if( team == TEAM_FREE ) {
+ PrintMsg(NULL, "The flag has returned!\n" );
+ }
+ else {
+ PrintMsg(NULL, "The %s flag has returned!\n", TeamName(team));
+ }
+}
+
+void Team_FreeEntity( gentity_t *ent ) {
+ if( ent->item->giTag == PW_REDFLAG ) {
+ Team_ReturnFlag( TEAM_RED );
+ }
+ else if( ent->item->giTag == PW_BLUEFLAG ) {
+ Team_ReturnFlag( TEAM_BLUE );
+ }
+ else if( ent->item->giTag == PW_NEUTRALFLAG ) {
+ Team_ReturnFlag( TEAM_FREE );
+ }
+}
+
+/*
+==============
+Team_DroppedFlagThink
+
+Automatically set in Launch_Item if the item is one of the flags
+
+Flags are unique in that if they are dropped, the base flag must be respawned when they time out
+==============
+*/
+void Team_DroppedFlagThink(gentity_t *ent) {
+ int team = TEAM_FREE;
+
+ if( ent->item->giTag == PW_REDFLAG ) {
+ team = TEAM_RED;
+ }
+ else if( ent->item->giTag == PW_BLUEFLAG ) {
+ team = TEAM_BLUE;
+ }
+ else if( ent->item->giTag == PW_NEUTRALFLAG ) {
+ team = TEAM_FREE;
+ }
+
+ Team_ReturnFlagSound( Team_ResetFlag( team ), team );
+ // Reset Flag will delete this entity
+}
+
+
+/*
+==============
+Team_DroppedFlagThink
+==============
+*/
+int Team_TouchOurFlag( gentity_t *ent, gentity_t *other, int team ) {
+ int i;
+ gentity_t *player;
+ gclient_t *cl = other->client;
+ int enemy_flag;
+
+#ifdef MISSIONPACK
+ if( g_gametype.integer == GT_1FCTF ) {
+ enemy_flag = PW_NEUTRALFLAG;
+ }
+ else {
+#endif
+ if (cl->sess.sessionTeam == TEAM_RED) {
+ enemy_flag = PW_BLUEFLAG;
+ } else {
+ enemy_flag = PW_REDFLAG;
+ }
+
+ if ( ent->flags & FL_DROPPED_ITEM ) {
+ // hey, its not home. return it by teleporting it back
+ PrintMsg( NULL, "%s" S_COLOR_WHITE " returned the %s flag!\n",
+ cl->pers.netname, TeamName(team));
+ AddScore(other, ent->r.currentOrigin, CTF_RECOVERY_BONUS);
+ other->client->pers.teamState.flagrecovery++;
+ other->client->pers.teamState.lastreturnedflag = level.time;
+ //ResetFlag will remove this entity! We must return zero
+ Team_ReturnFlagSound(Team_ResetFlag(team), team);
+ return 0;
+ }
+#ifdef MISSIONPACK
+ }
+#endif
+
+ // the flag is at home base. if the player has the enemy
+ // flag, he's just won!
+ if (!cl->ps.powerups[enemy_flag])
+ return 0; // We don't have the flag
+#ifdef MISSIONPACK
+ if( g_gametype.integer == GT_1FCTF ) {
+ PrintMsg( NULL, "%s" S_COLOR_WHITE " captured the flag!\n", cl->pers.netname );
+ }
+ else {
+#endif
+ PrintMsg( NULL, "%s" S_COLOR_WHITE " captured the %s flag!\n", cl->pers.netname, TeamName(OtherTeam(team)));
+#ifdef MISSIONPACK
+ }
+#endif
+
+ cl->ps.powerups[enemy_flag] = 0;
+
+ teamgame.last_flag_capture = level.time;
+ teamgame.last_capture_team = team;
+
+ // Increase the team's score
+ AddTeamScore(ent->s.pos.trBase, other->client->sess.sessionTeam, 1);
+ Team_ForceGesture(other->client->sess.sessionTeam);
+
+ other->client->pers.teamState.captures++;
+ // add the sprite over the player's head
+ other->client->ps.eFlags &= ~(EF_AWARD_IMPRESSIVE | EF_AWARD_EXCELLENT | EF_AWARD_GAUNTLET | EF_AWARD_ASSIST | EF_AWARD_DEFEND | EF_AWARD_CAP );
+ other->client->ps.eFlags |= EF_AWARD_CAP;
+ other->client->rewardTime = level.time + REWARD_SPRITE_TIME;
+ other->client->ps.persistant[PERS_CAPTURES]++;
+
+ // other gets another 10 frag bonus
+ AddScore(other, ent->r.currentOrigin, CTF_CAPTURE_BONUS);
+
+ Team_CaptureFlagSound( ent, team );
+
+ // Ok, let's do the player loop, hand out the bonuses
+ for (i = 0; i < g_maxclients.integer; i++) {
+ player = &g_entities[i];
+ if (!player->inuse)
+ continue;
+
+ if (player->client->sess.sessionTeam !=
+ cl->sess.sessionTeam) {
+ player->client->pers.teamState.lasthurtcarrier = -5;
+ } else if (player->client->sess.sessionTeam ==
+ cl->sess.sessionTeam) {
+ if (player != other)
+ AddScore(player, ent->r.currentOrigin, CTF_TEAM_BONUS);
+ // award extra points for capture assists
+ if (player->client->pers.teamState.lastreturnedflag +
+ CTF_RETURN_FLAG_ASSIST_TIMEOUT > level.time) {
+ AddScore (player, ent->r.currentOrigin, CTF_RETURN_FLAG_ASSIST_BONUS);
+ other->client->pers.teamState.assists++;
+
+ player->client->ps.persistant[PERS_ASSIST_COUNT]++;
+ // add the sprite over the player's head
+ player->client->ps.eFlags &= ~(EF_AWARD_IMPRESSIVE | EF_AWARD_EXCELLENT | EF_AWARD_GAUNTLET | EF_AWARD_ASSIST | EF_AWARD_DEFEND | EF_AWARD_CAP );
+ player->client->ps.eFlags |= EF_AWARD_ASSIST;
+ player->client->rewardTime = level.time + REWARD_SPRITE_TIME;
+
+ } else if (player->client->pers.teamState.lastfraggedcarrier +
+ CTF_FRAG_CARRIER_ASSIST_TIMEOUT > level.time) {
+ AddScore(player, ent->r.currentOrigin, CTF_FRAG_CARRIER_ASSIST_BONUS);
+ other->client->pers.teamState.assists++;
+ player->client->ps.persistant[PERS_ASSIST_COUNT]++;
+ // add the sprite over the player's head
+ player->client->ps.eFlags &= ~(EF_AWARD_IMPRESSIVE | EF_AWARD_EXCELLENT | EF_AWARD_GAUNTLET | EF_AWARD_ASSIST | EF_AWARD_DEFEND | EF_AWARD_CAP );
+ player->client->ps.eFlags |= EF_AWARD_ASSIST;
+ player->client->rewardTime = level.time + REWARD_SPRITE_TIME;
+ }
+ }
+ }
+ Team_ResetFlags();
+
+ CalculateRanks();
+
+ return 0; // Do not respawn this automatically
+}
+
+int Team_TouchEnemyFlag( gentity_t *ent, gentity_t *other, int team ) {
+ gclient_t *cl = other->client;
+
+#ifdef MISSIONPACK
+ if( g_gametype.integer == GT_1FCTF ) {
+ PrintMsg (NULL, "%s" S_COLOR_WHITE " got the flag!\n", other->client->pers.netname );
+
+ cl->ps.powerups[PW_NEUTRALFLAG] = INT_MAX; // flags never expire
+
+ if( team == TEAM_RED ) {
+ Team_SetFlagStatus( TEAM_FREE, FLAG_TAKEN_RED );
+ }
+ else {
+ Team_SetFlagStatus( TEAM_FREE, FLAG_TAKEN_BLUE );
+ }
+ }
+ else{
+#endif
+ PrintMsg (NULL, "%s" S_COLOR_WHITE " got the %s flag!\n",
+ other->client->pers.netname, TeamName(team));
+
+ if (team == TEAM_RED)
+ cl->ps.powerups[PW_REDFLAG] = INT_MAX; // flags never expire
+ else
+ cl->ps.powerups[PW_BLUEFLAG] = INT_MAX; // flags never expire
+
+ Team_SetFlagStatus( team, FLAG_TAKEN );
+#ifdef MISSIONPACK
+ }
+#endif
+
+ AddScore(other, ent->r.currentOrigin, CTF_FLAG_BONUS);
+ cl->pers.teamState.flagsince = level.time;
+ Team_TakeFlagSound( ent, team );
+
+ return -1; // Do not respawn this automatically, but do delete it if it was FL_DROPPED
+}
+
+int Pickup_Team( gentity_t *ent, gentity_t *other ) {
+ int team;
+ gclient_t *cl = other->client;
+
+#ifdef MISSIONPACK
+ if( g_gametype.integer == GT_OBELISK ) {
+ // there are no team items that can be picked up in obelisk
+ G_FreeEntity( ent );
+ return 0;
+ }
+
+ if( g_gametype.integer == GT_HARVESTER ) {
+ // the only team items that can be picked up in harvester are the cubes
+ if( ent->spawnflags != cl->sess.sessionTeam ) {
+ cl->ps.generic1 += 1;
+ }
+ G_FreeEntity( ent );
+ return 0;
+ }
+#endif
+ // figure out what team this flag is
+ if( strcmp(ent->classname, "team_CTF_redflag") == 0 ) {
+ team = TEAM_RED;
+ }
+ else if( strcmp(ent->classname, "team_CTF_blueflag") == 0 ) {
+ team = TEAM_BLUE;
+ }
+#ifdef MISSIONPACK
+ else if( strcmp(ent->classname, "team_CTF_neutralflag") == 0 ) {
+ team = TEAM_FREE;
+ }
+#endif
+ else {
+ PrintMsg ( other, "Don't know what team the flag is on.\n");
+ return 0;
+ }
+#ifdef MISSIONPACK
+ if( g_gametype.integer == GT_1FCTF ) {
+ if( team == TEAM_FREE ) {
+ return Team_TouchEnemyFlag( ent, other, cl->sess.sessionTeam );
+ }
+ if( team != cl->sess.sessionTeam) {
+ return Team_TouchOurFlag( ent, other, cl->sess.sessionTeam );
+ }
+ return 0;
+ }
+#endif
+ // GT_CTF
+ if( team == cl->sess.sessionTeam) {
+ return Team_TouchOurFlag( ent, other, team );
+ }
+ return Team_TouchEnemyFlag( ent, other, team );
+}
+
+/*
+===========
+Team_GetLocation
+
+Report a location for the player. Uses placed nearby target_location entities
+============
+*/
+gentity_t *Team_GetLocation(gentity_t *ent)
+{
+ gentity_t *eloc, *best;
+ float bestlen, len;
+ vec3_t origin;
+
+ best = NULL;
+ bestlen = 3*8192.0*8192.0;
+
+ VectorCopy( ent->r.currentOrigin, origin );
+
+ for (eloc = level.locationHead; eloc; eloc = eloc->nextTrain) {
+ len = ( origin[0] - eloc->r.currentOrigin[0] ) * ( origin[0] - eloc->r.currentOrigin[0] )
+ + ( origin[1] - eloc->r.currentOrigin[1] ) * ( origin[1] - eloc->r.currentOrigin[1] )
+ + ( origin[2] - eloc->r.currentOrigin[2] ) * ( origin[2] - eloc->r.currentOrigin[2] );
+
+ if ( len > bestlen ) {
+ continue;
+ }
+
+ if ( !trap_InPVS( origin, eloc->r.currentOrigin ) ) {
+ continue;
+ }
+
+ bestlen = len;
+ best = eloc;
+ }
+
+ return best;
+}
+
+
+/*
+===========
+Team_GetLocation
+
+Report a location for the player. Uses placed nearby target_location entities
+============
+*/
+qboolean Team_GetLocationMsg(gentity_t *ent, char *loc, int loclen)
+{
+ gentity_t *best;
+
+ best = Team_GetLocation( ent );
+
+ if (!best)
+ return qfalse;
+
+ if (best->count) {
+ if (best->count < 0)
+ best->count = 0;
+ if (best->count > 7)
+ best->count = 7;
+ Com_sprintf(loc, loclen, "%c%c%s" S_COLOR_WHITE, Q_COLOR_ESCAPE, best->count + '0', best->message );
+ } else
+ Com_sprintf(loc, loclen, "%s", best->message);
+
+ return qtrue;
+}
+
+
+/*---------------------------------------------------------------------------*/
+
+/*
+================
+SelectRandomDeathmatchSpawnPoint
+
+go to a random point that doesn't telefrag
+================
+*/
+#define MAX_TEAM_SPAWN_POINTS 32
+gentity_t *SelectRandomTeamSpawnPoint( int teamstate, team_t team ) {
+ gentity_t *spot;
+ int count;
+ int selection;
+ gentity_t *spots[MAX_TEAM_SPAWN_POINTS];
+ char *classname;
+
+ if (teamstate == TEAM_BEGIN) {
+ if (team == TEAM_RED)
+ classname = "team_CTF_redplayer";
+ else if (team == TEAM_BLUE)
+ classname = "team_CTF_blueplayer";
+ else
+ return NULL;
+ } else {
+ if (team == TEAM_RED)
+ classname = "team_CTF_redspawn";
+ else if (team == TEAM_BLUE)
+ classname = "team_CTF_bluespawn";
+ else
+ return NULL;
+ }
+ count = 0;
+
+ spot = NULL;
+
+ while ((spot = G_Find (spot, FOFS(classname), classname)) != NULL) {
+ if ( SpotWouldTelefrag( spot ) ) {
+ continue;
+ }
+ spots[ count ] = spot;
+ if (++count == MAX_TEAM_SPAWN_POINTS)
+ break;
+ }
+
+ if ( !count ) { // no spots that won't telefrag
+ return G_Find( NULL, FOFS(classname), classname);
+ }
+
+ selection = rand() % count;
+ return spots[ selection ];
+}
+
+
+/*
+===========
+SelectCTFSpawnPoint
+
+============
+*/
+gentity_t *SelectCTFSpawnPoint ( team_t team, int teamstate, vec3_t origin, vec3_t angles ) {
+ gentity_t *spot;
+
+ spot = SelectRandomTeamSpawnPoint ( teamstate, team );
+
+ if (!spot) {
+ return SelectSpawnPoint( vec3_origin, origin, angles );
+ }
+
+ VectorCopy (spot->s.origin, origin);
+ origin[2] += 9;
+ VectorCopy (spot->s.angles, angles);
+
+ return spot;
+}
+
+/*---------------------------------------------------------------------------*/
+
+static int QDECL SortClients( const void *a, const void *b ) {
+ return *(int *)a - *(int *)b;
+}
+
+
+/*
+==================
+TeamplayLocationsMessage
+
+Format:
+ clientNum location health armor weapon powerups
+
+==================
+*/
+void TeamplayInfoMessage( gentity_t *ent ) {
+ char entry[1024];
+ char string[8192];
+ int stringlength;
+ int i, j;
+ gentity_t *player;
+ int cnt;
+ int h, a;
+ int clients[TEAM_MAXOVERLAY];
+
+ if ( ! ent->client->pers.teamInfo )
+ return;
+
+ // figure out what client should be on the display
+ // we are limited to 8, but we want to use the top eight players
+ // but in client order (so they don't keep changing position on the overlay)
+ for (i = 0, cnt = 0; i < g_maxclients.integer && cnt < TEAM_MAXOVERLAY; i++) {
+ player = g_entities + level.sortedClients[i];
+ if (player->inuse && player->client->sess.sessionTeam ==
+ ent->client->sess.sessionTeam ) {
+ clients[cnt++] = level.sortedClients[i];
+ }
+ }
+
+ // We have the top eight players, sort them by clientNum
+ qsort( clients, cnt, sizeof( clients[0] ), SortClients );
+
+ // send the latest information on all clients
+ string[0] = 0;
+ stringlength = 0;
+
+ for (i = 0, cnt = 0; i < g_maxclients.integer && cnt < TEAM_MAXOVERLAY; i++) {
+ player = g_entities + i;
+ if (player->inuse && player->client->sess.sessionTeam ==
+ ent->client->sess.sessionTeam ) {
+
+ h = player->client->ps.stats[STAT_HEALTH];
+ a = player->client->ps.stats[STAT_ARMOR];
+ if (h < 0) h = 0;
+ if (a < 0) a = 0;
+
+ Com_sprintf (entry, sizeof(entry),
+ " %i %i %i %i %i %i",
+// level.sortedClients[i], player->client->pers.teamState.location, h, a,
+ i, player->client->pers.teamState.location, h, a,
+ player->client->ps.weapon, player->s.powerups);
+ j = strlen(entry);
+ if (stringlength + j > sizeof(string))
+ break;
+ strcpy (string + stringlength, entry);
+ stringlength += j;
+ cnt++;
+ }
+ }
+
+ trap_SendServerCommand( ent-g_entities, va("tinfo %i %s", cnt, string) );
+}
+
+void CheckTeamStatus(void) {
+ int i;
+ gentity_t *loc, *ent;
+
+ if (level.time - level.lastTeamLocationTime > TEAM_LOCATION_UPDATE_TIME) {
+
+ level.lastTeamLocationTime = level.time;
+
+ for (i = 0; i < g_maxclients.integer; i++) {
+ ent = g_entities + i;
+
+ if ( ent->client->pers.connected != CON_CONNECTED ) {
+ continue;
+ }
+
+ if (ent->inuse && (ent->client->sess.sessionTeam == TEAM_RED || ent->client->sess.sessionTeam == TEAM_BLUE)) {
+ loc = Team_GetLocation( ent );
+ if (loc)
+ ent->client->pers.teamState.location = loc->health;
+ else
+ ent->client->pers.teamState.location = 0;
+ }
+ }
+
+ for (i = 0; i < g_maxclients.integer; i++) {
+ ent = g_entities + i;
+
+ if ( ent->client->pers.connected != CON_CONNECTED ) {
+ continue;
+ }
+
+ if (ent->inuse && (ent->client->sess.sessionTeam == TEAM_RED || ent->client->sess.sessionTeam == TEAM_BLUE)) {
+ TeamplayInfoMessage( ent );
+ }
+ }
+ }
+}
+
+/*-----------------------------------------------------------------*/
+
+/*QUAKED team_CTF_redplayer (1 0 0) (-16 -16 -16) (16 16 32)
+Only in CTF games. Red players spawn here at game start.
+*/
+void SP_team_CTF_redplayer( gentity_t *ent ) {
+}
+
+
+/*QUAKED team_CTF_blueplayer (0 0 1) (-16 -16 -16) (16 16 32)
+Only in CTF games. Blue players spawn here at game start.
+*/
+void SP_team_CTF_blueplayer( gentity_t *ent ) {
+}
+
+
+/*QUAKED team_CTF_redspawn (1 0 0) (-16 -16 -24) (16 16 32)
+potential spawning position for red team in CTF games.
+Targets will be fired when someone spawns in on them.
+*/
+void SP_team_CTF_redspawn(gentity_t *ent) {
+}
+
+/*QUAKED team_CTF_bluespawn (0 0 1) (-16 -16 -24) (16 16 32)
+potential spawning position for blue team in CTF games.
+Targets will be fired when someone spawns in on them.
+*/
+void SP_team_CTF_bluespawn(gentity_t *ent) {
+}
+
+
+#ifdef MISSIONPACK
+/*
+================
+Obelisks
+================
+*/
+
+static void ObeliskRegen( gentity_t *self ) {
+ self->nextthink = level.time + g_obeliskRegenPeriod.integer * 1000;
+ if( self->health >= g_obeliskHealth.integer ) {
+ return;
+ }
+
+ G_AddEvent( self, EV_POWERUP_REGEN, 0 );
+ self->health += g_obeliskRegenAmount.integer;
+ if ( self->health > g_obeliskHealth.integer ) {
+ self->health = g_obeliskHealth.integer;
+ }
+
+ self->activator->s.modelindex2 = self->health * 0xff / g_obeliskHealth.integer;
+ self->activator->s.frame = 0;
+}
+
+
+static void ObeliskRespawn( gentity_t *self ) {
+ self->takedamage = qtrue;
+ self->health = g_obeliskHealth.integer;
+
+ self->think = ObeliskRegen;
+ self->nextthink = level.time + g_obeliskRegenPeriod.integer * 1000;
+
+ self->activator->s.frame = 0;
+}
+
+
+static void ObeliskDie( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod ) {
+ int otherTeam;
+
+ otherTeam = OtherTeam( self->spawnflags );
+ AddTeamScore(self->s.pos.trBase, otherTeam, 1);
+ Team_ForceGesture(otherTeam);
+
+ CalculateRanks();
+
+ self->takedamage = qfalse;
+ self->think = ObeliskRespawn;
+ self->nextthink = level.time + g_obeliskRespawnDelay.integer * 1000;
+
+ self->activator->s.modelindex2 = 0xff;
+ self->activator->s.frame = 2;
+
+ G_AddEvent( self->activator, EV_OBELISKEXPLODE, 0 );
+
+ AddScore(attacker, self->r.currentOrigin, CTF_CAPTURE_BONUS);
+
+ // add the sprite over the player's head
+ attacker->client->ps.eFlags &= ~(EF_AWARD_IMPRESSIVE | EF_AWARD_EXCELLENT | EF_AWARD_GAUNTLET | EF_AWARD_ASSIST | EF_AWARD_DEFEND | EF_AWARD_CAP );
+ attacker->client->ps.eFlags |= EF_AWARD_CAP;
+ attacker->client->rewardTime = level.time + REWARD_SPRITE_TIME;
+ attacker->client->ps.persistant[PERS_CAPTURES]++;
+
+ teamgame.redObeliskAttackedTime = 0;
+ teamgame.blueObeliskAttackedTime = 0;
+}
+
+
+static void ObeliskTouch( gentity_t *self, gentity_t *other, trace_t *trace ) {
+ int tokens;
+
+ if ( !other->client ) {
+ return;
+ }
+
+ if ( OtherTeam(other->client->sess.sessionTeam) != self->spawnflags ) {
+ return;
+ }
+
+ tokens = other->client->ps.generic1;
+ if( tokens <= 0 ) {
+ return;
+ }
+
+ PrintMsg(NULL, "%s" S_COLOR_WHITE " brought in %i skull%s.\n",
+ other->client->pers.netname, tokens, tokens ? "s" : "" );
+
+ AddTeamScore(self->s.pos.trBase, other->client->sess.sessionTeam, tokens);
+ Team_ForceGesture(other->client->sess.sessionTeam);
+
+ AddScore(other, self->r.currentOrigin, CTF_CAPTURE_BONUS*tokens);
+
+ // add the sprite over the player's head
+ other->client->ps.eFlags &= ~(EF_AWARD_IMPRESSIVE | EF_AWARD_EXCELLENT | EF_AWARD_GAUNTLET | EF_AWARD_ASSIST | EF_AWARD_DEFEND | EF_AWARD_CAP );
+ other->client->ps.eFlags |= EF_AWARD_CAP;
+ other->client->rewardTime = level.time + REWARD_SPRITE_TIME;
+ other->client->ps.persistant[PERS_CAPTURES] += tokens;
+
+ other->client->ps.generic1 = 0;
+ CalculateRanks();
+
+ Team_CaptureFlagSound( self, self->spawnflags );
+}
+
+static void ObeliskPain( gentity_t *self, gentity_t *attacker, int damage ) {
+ int actualDamage = damage / 10;
+ if (actualDamage <= 0) {
+ actualDamage = 1;
+ }
+ self->activator->s.modelindex2 = self->health * 0xff / g_obeliskHealth.integer;
+ if (!self->activator->s.frame) {
+ G_AddEvent(self, EV_OBELISKPAIN, 0);
+ }
+ self->activator->s.frame = 1;
+ AddScore(attacker, self->r.currentOrigin, actualDamage);
+}
+
+gentity_t *SpawnObelisk( vec3_t origin, int team, int spawnflags) {
+ trace_t tr;
+ vec3_t dest;
+ gentity_t *ent;
+
+ ent = G_Spawn();
+
+ VectorCopy( origin, ent->s.origin );
+ VectorCopy( origin, ent->s.pos.trBase );
+ VectorCopy( origin, ent->r.currentOrigin );
+
+ VectorSet( ent->r.mins, -15, -15, 0 );
+ VectorSet( ent->r.maxs, 15, 15, 87 );
+
+ ent->s.eType = ET_GENERAL;
+ ent->flags = FL_NO_KNOCKBACK;
+
+ if( g_gametype.integer == GT_OBELISK ) {
+ ent->r.contents = CONTENTS_SOLID;
+ ent->takedamage = qtrue;
+ ent->health = g_obeliskHealth.integer;
+ ent->die = ObeliskDie;
+ ent->pain = ObeliskPain;
+ ent->think = ObeliskRegen;
+ ent->nextthink = level.time + g_obeliskRegenPeriod.integer * 1000;
+ }
+ if( g_gametype.integer == GT_HARVESTER ) {
+ ent->r.contents = CONTENTS_TRIGGER;
+ ent->touch = ObeliskTouch;
+ }
+
+ if ( spawnflags & 1 ) {
+ // suspended
+ G_SetOrigin( ent, ent->s.origin );
+ } else {
+ // mappers like to put them exactly on the floor, but being coplanar
+ // will sometimes show up as starting in solid, so lif it up one pixel
+ ent->s.origin[2] += 1;
+
+ // drop to floor
+ VectorSet( dest, ent->s.origin[0], ent->s.origin[1], ent->s.origin[2] - 4096 );
+ trap_Trace( &tr, ent->s.origin, ent->r.mins, ent->r.maxs, dest, ent->s.number, MASK_SOLID );
+ if ( tr.startsolid ) {
+ ent->s.origin[2] -= 1;
+ G_Printf( "SpawnObelisk: %s startsolid at %s\n", ent->classname, vtos(ent->s.origin) );
+
+ ent->s.groundEntityNum = ENTITYNUM_NONE;
+ G_SetOrigin( ent, ent->s.origin );
+ }
+ else {
+ // allow to ride movers
+ ent->s.groundEntityNum = tr.entityNum;
+ G_SetOrigin( ent, tr.endpos );
+ }
+ }
+
+ ent->spawnflags = team;
+
+ trap_LinkEntity( ent );
+
+ return ent;
+}
+
+/*QUAKED team_redobelisk (1 0 0) (-16 -16 0) (16 16 8)
+*/
+void SP_team_redobelisk( gentity_t *ent ) {
+ gentity_t *obelisk;
+
+ if ( g_gametype.integer <= GT_TEAM ) {
+ G_FreeEntity(ent);
+ return;
+ }
+ ent->s.eType = ET_TEAM;
+ if ( g_gametype.integer == GT_OBELISK ) {
+ obelisk = SpawnObelisk( ent->s.origin, TEAM_RED, ent->spawnflags );
+ obelisk->activator = ent;
+ // initial obelisk health value
+ ent->s.modelindex2 = 0xff;
+ ent->s.frame = 0;
+ }
+ if ( g_gametype.integer == GT_HARVESTER ) {
+ obelisk = SpawnObelisk( ent->s.origin, TEAM_RED, ent->spawnflags );
+ obelisk->activator = ent;
+ }
+ ent->s.modelindex = TEAM_RED;
+ trap_LinkEntity(ent);
+}
+
+/*QUAKED team_blueobelisk (0 0 1) (-16 -16 0) (16 16 88)
+*/
+void SP_team_blueobelisk( gentity_t *ent ) {
+ gentity_t *obelisk;
+
+ if ( g_gametype.integer <= GT_TEAM ) {
+ G_FreeEntity(ent);
+ return;
+ }
+ ent->s.eType = ET_TEAM;
+ if ( g_gametype.integer == GT_OBELISK ) {
+ obelisk = SpawnObelisk( ent->s.origin, TEAM_BLUE, ent->spawnflags );
+ obelisk->activator = ent;
+ // initial obelisk health value
+ ent->s.modelindex2 = 0xff;
+ ent->s.frame = 0;
+ }
+ if ( g_gametype.integer == GT_HARVESTER ) {
+ obelisk = SpawnObelisk( ent->s.origin, TEAM_BLUE, ent->spawnflags );
+ obelisk->activator = ent;
+ }
+ ent->s.modelindex = TEAM_BLUE;
+ trap_LinkEntity(ent);
+}
+
+/*QUAKED team_neutralobelisk (0 0 1) (-16 -16 0) (16 16 88)
+*/
+void SP_team_neutralobelisk( gentity_t *ent ) {
+ if ( g_gametype.integer != GT_1FCTF && g_gametype.integer != GT_HARVESTER ) {
+ G_FreeEntity(ent);
+ return;
+ }
+ ent->s.eType = ET_TEAM;
+ if ( g_gametype.integer == GT_HARVESTER) {
+ neutralObelisk = SpawnObelisk( ent->s.origin, TEAM_FREE, ent->spawnflags);
+ neutralObelisk->spawnflags = TEAM_FREE;
+ }
+ ent->s.modelindex = TEAM_FREE;
+ trap_LinkEntity(ent);
+}
+
+
+/*
+================
+CheckObeliskAttack
+================
+*/
+qboolean CheckObeliskAttack( gentity_t *obelisk, gentity_t *attacker ) {
+ gentity_t *te;
+
+ // if this really is an obelisk
+ if( obelisk->die != ObeliskDie ) {
+ return qfalse;
+ }
+
+ // if the attacker is a client
+ if( !attacker->client ) {
+ return qfalse;
+ }
+
+ // if the obelisk is on the same team as the attacker then don't hurt it
+ if( obelisk->spawnflags == attacker->client->sess.sessionTeam ) {
+ return qtrue;
+ }
+
+ // obelisk may be hurt
+
+ // if not played any sounds recently
+ if ((obelisk->spawnflags == TEAM_RED &&
+ teamgame.redObeliskAttackedTime < level.time - OVERLOAD_ATTACK_BASE_SOUND_TIME) ||
+ (obelisk->spawnflags == TEAM_BLUE &&
+ teamgame.blueObeliskAttackedTime < level.time - OVERLOAD_ATTACK_BASE_SOUND_TIME) ) {
+
+ // tell which obelisk is under attack
+ te = G_TempEntity( obelisk->s.pos.trBase, EV_GLOBAL_TEAM_SOUND );
+ if( obelisk->spawnflags == TEAM_RED ) {
+ te->s.eventParm = GTS_REDOBELISK_ATTACKED;
+ teamgame.redObeliskAttackedTime = level.time;
+ }
+ else {
+ te->s.eventParm = GTS_BLUEOBELISK_ATTACKED;
+ teamgame.blueObeliskAttackedTime = level.time;
+ }
+ te->r.svFlags |= SVF_BROADCAST;
+ }
+
+ return qfalse;
+}
+#endif
diff --git a/code/game/g_team.h b/code/game/g_team.h
new file mode 100755
index 0000000..807946e
--- /dev/null
+++ b/code/game/g_team.h
@@ -0,0 +1,88 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+
+#ifdef MISSIONPACK
+
+#define CTF_CAPTURE_BONUS 100 // what you get for capture
+#define CTF_TEAM_BONUS 25 // what your team gets for capture
+#define CTF_RECOVERY_BONUS 10 // what you get for recovery
+#define CTF_FLAG_BONUS 10 // what you get for picking up enemy flag
+#define CTF_FRAG_CARRIER_BONUS 20 // what you get for fragging enemy flag carrier
+#define CTF_FLAG_RETURN_TIME 40000 // seconds until auto return
+
+#define CTF_CARRIER_DANGER_PROTECT_BONUS 5 // bonus for fraggin someone who has recently hurt your flag carrier
+#define CTF_CARRIER_PROTECT_BONUS 2 // bonus for fraggin someone while either you or your target are near your flag carrier
+#define CTF_FLAG_DEFENSE_BONUS 10 // bonus for fraggin someone while either you or your target are near your flag
+#define CTF_RETURN_FLAG_ASSIST_BONUS 10 // awarded for returning a flag that causes a capture to happen almost immediately
+#define CTF_FRAG_CARRIER_ASSIST_BONUS 10 // award for fragging a flag carrier if a capture happens almost immediately
+
+#else
+
+#define CTF_CAPTURE_BONUS 5 // what you get for capture
+#define CTF_TEAM_BONUS 0 // what your team gets for capture
+#define CTF_RECOVERY_BONUS 1 // what you get for recovery
+#define CTF_FLAG_BONUS 0 // what you get for picking up enemy flag
+#define CTF_FRAG_CARRIER_BONUS 2 // what you get for fragging enemy flag carrier
+#define CTF_FLAG_RETURN_TIME 40000 // seconds until auto return
+
+#define CTF_CARRIER_DANGER_PROTECT_BONUS 2 // bonus for fraggin someone who has recently hurt your flag carrier
+#define CTF_CARRIER_PROTECT_BONUS 1 // bonus for fraggin someone while either you or your target are near your flag carrier
+#define CTF_FLAG_DEFENSE_BONUS 1 // bonus for fraggin someone while either you or your target are near your flag
+#define CTF_RETURN_FLAG_ASSIST_BONUS 1 // awarded for returning a flag that causes a capture to happen almost immediately
+#define CTF_FRAG_CARRIER_ASSIST_BONUS 2 // award for fragging a flag carrier if a capture happens almost immediately
+
+#endif
+
+#define CTF_TARGET_PROTECT_RADIUS 1000 // the radius around an object being defended where a target will be worth extra frags
+#define CTF_ATTACKER_PROTECT_RADIUS 1000 // the radius around an object being defended where an attacker will get extra frags when making kills
+
+#define CTF_CARRIER_DANGER_PROTECT_TIMEOUT 8000
+#define CTF_FRAG_CARRIER_ASSIST_TIMEOUT 10000
+#define CTF_RETURN_FLAG_ASSIST_TIMEOUT 10000
+
+#define CTF_GRAPPLE_SPEED 750 // speed of grapple in flight
+#define CTF_GRAPPLE_PULL_SPEED 750 // speed player is pulled at
+
+#define OVERLOAD_ATTACK_BASE_SOUND_TIME 20000
+
+// Prototypes
+
+int OtherTeam(int team);
+const char *TeamName(int team);
+const char *OtherTeamName(int team);
+const char *TeamColorString(int team);
+void AddTeamScore(vec3_t origin, int team, int score);
+
+void Team_DroppedFlagThink(gentity_t *ent);
+void Team_FragBonuses(gentity_t *targ, gentity_t *inflictor, gentity_t *attacker);
+void Team_CheckHurtCarrier(gentity_t *targ, gentity_t *attacker);
+void Team_InitGame(void);
+void Team_ReturnFlag(int team);
+void Team_FreeEntity(gentity_t *ent);
+gentity_t *SelectCTFSpawnPoint ( team_t team, int teamstate, vec3_t origin, vec3_t angles );
+gentity_t *Team_GetLocation(gentity_t *ent);
+qboolean Team_GetLocationMsg(gentity_t *ent, char *loc, int loclen);
+void TeamplayInfoMessage( gentity_t *ent );
+void CheckTeamStatus(void);
+
+int Pickup_Team( gentity_t *ent, gentity_t *other );
diff --git a/code/game/g_trigger.c b/code/game/g_trigger.c
new file mode 100755
index 0000000..6ec8a35
--- /dev/null
+++ b/code/game/g_trigger.c
@@ -0,0 +1,465 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#include "g_local.h"
+
+
+void InitTrigger( gentity_t *self ) {
+ if (!VectorCompare (self->s.angles, vec3_origin))
+ G_SetMovedir (self->s.angles, self->movedir);
+
+ trap_SetBrushModel( self, self->model );
+ self->r.contents = CONTENTS_TRIGGER; // replaces the -1 from trap_SetBrushModel
+ self->r.svFlags = SVF_NOCLIENT;
+}
+
+
+// the wait time has passed, so set back up for another activation
+void multi_wait( gentity_t *ent ) {
+ ent->nextthink = 0;
+}
+
+
+// the trigger was just activated
+// ent->activator should be set to the activator so it can be held through a delay
+// so wait for the delay time before firing
+void multi_trigger( gentity_t *ent, gentity_t *activator ) {
+ ent->activator = activator;
+ if ( ent->nextthink ) {
+ return; // can't retrigger until the wait is over
+ }
+
+ if ( activator->client ) {
+ if ( ( ent->spawnflags & 1 ) &&
+ activator->client->sess.sessionTeam != TEAM_RED ) {
+ return;
+ }
+ if ( ( ent->spawnflags & 2 ) &&
+ activator->client->sess.sessionTeam != TEAM_BLUE ) {
+ return;
+ }
+ }
+
+ G_UseTargets (ent, ent->activator);
+
+ if ( ent->wait > 0 ) {
+ ent->think = multi_wait;
+ ent->nextthink = level.time + ( ent->wait + ent->random * crandom() ) * 1000;
+ } else {
+ // we can't just remove (self) here, because this is a touch function
+ // called while looping through area links...
+ ent->touch = 0;
+ ent->nextthink = level.time + FRAMETIME;
+ ent->think = G_FreeEntity;
+ }
+}
+
+void Use_Multi( gentity_t *ent, gentity_t *other, gentity_t *activator ) {
+ multi_trigger( ent, activator );
+}
+
+void Touch_Multi( gentity_t *self, gentity_t *other, trace_t *trace ) {
+ if( !other->client ) {
+ return;
+ }
+ multi_trigger( self, other );
+}
+
+/*QUAKED trigger_multiple (.5 .5 .5) ?
+"wait" : Seconds between triggerings, 0.5 default, -1 = one time only.
+"random" wait variance, default is 0
+Variable sized repeatable trigger. Must be targeted at one or more entities.
+so, the basic time between firing is a random time between
+(wait - random) and (wait + random)
+*/
+void SP_trigger_multiple( gentity_t *ent ) {
+ G_SpawnFloat( "wait", "0.5", &ent->wait );
+ G_SpawnFloat( "random", "0", &ent->random );
+
+ if ( ent->random >= ent->wait && ent->wait >= 0 ) {
+ ent->random = ent->wait - FRAMETIME;
+ G_Printf( "trigger_multiple has random >= wait\n" );
+ }
+
+ ent->touch = Touch_Multi;
+ ent->use = Use_Multi;
+
+ InitTrigger( ent );
+ trap_LinkEntity (ent);
+}
+
+
+
+/*
+==============================================================================
+
+trigger_always
+
+==============================================================================
+*/
+
+void trigger_always_think( gentity_t *ent ) {
+ G_UseTargets(ent, ent);
+ G_FreeEntity( ent );
+}
+
+/*QUAKED trigger_always (.5 .5 .5) (-8 -8 -8) (8 8 8)
+This trigger will always fire. It is activated by the world.
+*/
+void SP_trigger_always (gentity_t *ent) {
+ // we must have some delay to make sure our use targets are present
+ ent->nextthink = level.time + 300;
+ ent->think = trigger_always_think;
+}
+
+
+/*
+==============================================================================
+
+trigger_push
+
+==============================================================================
+*/
+
+void trigger_push_touch (gentity_t *self, gentity_t *other, trace_t *trace ) {
+
+ if ( !other->client ) {
+ return;
+ }
+
+ BG_TouchJumpPad( &other->client->ps, &self->s );
+}
+
+
+/*
+=================
+AimAtTarget
+
+Calculate origin2 so the target apogee will be hit
+=================
+*/
+void AimAtTarget( gentity_t *self ) {
+ gentity_t *ent;
+ vec3_t origin;
+ float height, gravity, time, forward;
+ float dist;
+
+ VectorAdd( self->r.absmin, self->r.absmax, origin );
+ VectorScale ( origin, 0.5, origin );
+
+ ent = G_PickTarget( self->target );
+ if ( !ent ) {
+ G_FreeEntity( self );
+ return;
+ }
+
+ height = ent->s.origin[2] - origin[2];
+ gravity = g_gravity.value;
+ time = sqrt( height / ( .5 * gravity ) );
+ if ( !time ) {
+ G_FreeEntity( self );
+ return;
+ }
+
+ // set s.origin2 to the push velocity
+ VectorSubtract ( ent->s.origin, origin, self->s.origin2 );
+ self->s.origin2[2] = 0;
+ dist = VectorNormalize( self->s.origin2);
+
+ forward = dist / time;
+ VectorScale( self->s.origin2, forward, self->s.origin2 );
+
+ self->s.origin2[2] = time * gravity;
+}
+
+
+/*QUAKED trigger_push (.5 .5 .5) ?
+Must point at a target_position, which will be the apex of the leap.
+This will be client side predicted, unlike target_push
+*/
+void SP_trigger_push( gentity_t *self ) {
+ InitTrigger (self);
+
+ // unlike other triggers, we need to send this one to the client
+ self->r.svFlags &= ~SVF_NOCLIENT;
+
+ // make sure the client precaches this sound
+ G_SoundIndex("sound/world/jumppad.wav");
+
+ self->s.eType = ET_PUSH_TRIGGER;
+ self->touch = trigger_push_touch;
+ self->think = AimAtTarget;
+ self->nextthink = level.time + FRAMETIME;
+ trap_LinkEntity (self);
+}
+
+
+void Use_target_push( gentity_t *self, gentity_t *other, gentity_t *activator ) {
+ if ( !activator->client ) {
+ return;
+ }
+
+ if ( activator->client->ps.pm_type != PM_NORMAL ) {
+ return;
+ }
+ if ( activator->client->ps.powerups[PW_FLIGHT] ) {
+ return;
+ }
+
+ VectorCopy (self->s.origin2, activator->client->ps.velocity);
+
+ // play fly sound every 1.5 seconds
+ if ( activator->fly_sound_debounce_time < level.time ) {
+ activator->fly_sound_debounce_time = level.time + 1500;
+ G_Sound( activator, CHAN_AUTO, self->noise_index );
+ }
+}
+
+/*QUAKED target_push (.5 .5 .5) (-8 -8 -8) (8 8 8) bouncepad
+Pushes the activator in the direction.of angle, or towards a target apex.
+"speed" defaults to 1000
+if "bouncepad", play bounce noise instead of windfly
+*/
+void SP_target_push( gentity_t *self ) {
+ if (!self->speed) {
+ self->speed = 1000;
+ }
+ G_SetMovedir (self->s.angles, self->s.origin2);
+ VectorScale (self->s.origin2, self->speed, self->s.origin2);
+
+ if ( self->spawnflags & 1 ) {
+ self->noise_index = G_SoundIndex("sound/world/jumppad.wav");
+ } else {
+ self->noise_index = G_SoundIndex("sound/misc/windfly.wav");
+ }
+ if ( self->target ) {
+ VectorCopy( self->s.origin, self->r.absmin );
+ VectorCopy( self->s.origin, self->r.absmax );
+ self->think = AimAtTarget;
+ self->nextthink = level.time + FRAMETIME;
+ }
+ self->use = Use_target_push;
+}
+
+/*
+==============================================================================
+
+trigger_teleport
+
+==============================================================================
+*/
+
+void trigger_teleporter_touch (gentity_t *self, gentity_t *other, trace_t *trace ) {
+ gentity_t *dest;
+
+ if ( !other->client ) {
+ return;
+ }
+ if ( other->client->ps.pm_type == PM_DEAD ) {
+ return;
+ }
+ // Spectators only?
+ if ( ( self->spawnflags & 1 ) &&
+ other->client->sess.sessionTeam != TEAM_SPECTATOR ) {
+ return;
+ }
+
+
+ dest = G_PickTarget( self->target );
+ if (!dest) {
+ G_Printf ("Couldn't find teleporter destination\n");
+ return;
+ }
+
+ TeleportPlayer( other, dest->s.origin, dest->s.angles );
+}
+
+
+/*QUAKED trigger_teleport (.5 .5 .5) ? SPECTATOR
+Allows client side prediction of teleportation events.
+Must point at a target_position, which will be the teleport destination.
+
+If spectator is set, only spectators can use this teleport
+Spectator teleporters are not normally placed in the editor, but are created
+automatically near doors to allow spectators to move through them
+*/
+void SP_trigger_teleport( gentity_t *self ) {
+ InitTrigger (self);
+
+ // unlike other triggers, we need to send this one to the client
+ // unless is a spectator trigger
+ if ( self->spawnflags & 1 ) {
+ self->r.svFlags |= SVF_NOCLIENT;
+ } else {
+ self->r.svFlags &= ~SVF_NOCLIENT;
+ }
+
+ // make sure the client precaches this sound
+ G_SoundIndex("sound/world/jumppad.wav");
+
+ self->s.eType = ET_TELEPORT_TRIGGER;
+ self->touch = trigger_teleporter_touch;
+
+ trap_LinkEntity (self);
+}
+
+
+/*
+==============================================================================
+
+trigger_hurt
+
+==============================================================================
+*/
+
+/*QUAKED trigger_hurt (.5 .5 .5) ? START_OFF - SILENT NO_PROTECTION SLOW
+Any entity that touches this will be hurt.
+It does dmg points of damage each server frame
+Targeting the trigger will toggle its on / off state.
+
+SILENT supresses playing the sound
+SLOW changes the damage rate to once per second
+NO_PROTECTION *nothing* stops the damage
+
+"dmg" default 5 (whole numbers only)
+
+*/
+void hurt_use( gentity_t *self, gentity_t *other, gentity_t *activator ) {
+ if ( self->r.linked ) {
+ trap_UnlinkEntity( self );
+ } else {
+ trap_LinkEntity( self );
+ }
+}
+
+void hurt_touch( gentity_t *self, gentity_t *other, trace_t *trace ) {
+ int dflags;
+
+ if ( !other->takedamage ) {
+ return;
+ }
+
+ if ( self->timestamp > level.time ) {
+ return;
+ }
+
+ if ( self->spawnflags & 16 ) {
+ self->timestamp = level.time + 1000;
+ } else {
+ self->timestamp = level.time + FRAMETIME;
+ }
+
+ // play sound
+ if ( !(self->spawnflags & 4) ) {
+ G_Sound( other, CHAN_AUTO, self->noise_index );
+ }
+
+ if (self->spawnflags & 8)
+ dflags = DAMAGE_NO_PROTECTION;
+ else
+ dflags = 0;
+ G_Damage (other, self, self, NULL, NULL, self->damage, dflags, MOD_TRIGGER_HURT);
+}
+
+void SP_trigger_hurt( gentity_t *self ) {
+ InitTrigger (self);
+
+ self->noise_index = G_SoundIndex( "sound/world/electro.wav" );
+ self->touch = hurt_touch;
+
+ if ( !self->damage ) {
+ self->damage = 5;
+ }
+
+ self->r.contents = CONTENTS_TRIGGER;
+
+ if ( self->spawnflags & 2 ) {
+ self->use = hurt_use;
+ }
+
+ // link in to the world if starting active
+ if ( ! (self->spawnflags & 1) ) {
+ trap_LinkEntity (self);
+ }
+}
+
+
+/*
+==============================================================================
+
+timer
+
+==============================================================================
+*/
+
+
+/*QUAKED func_timer (0.3 0.1 0.6) (-8 -8 -8) (8 8 8) START_ON
+This should be renamed trigger_timer...
+Repeatedly fires its targets.
+Can be turned on or off by using.
+
+"wait" base time between triggering all targets, default is 1
+"random" wait variance, default is 0
+so, the basic time between firing is a random time between
+(wait - random) and (wait + random)
+
+*/
+void func_timer_think( gentity_t *self ) {
+ G_UseTargets (self, self->activator);
+ // set time before next firing
+ self->nextthink = level.time + 1000 * ( self->wait + crandom() * self->random );
+}
+
+void func_timer_use( gentity_t *self, gentity_t *other, gentity_t *activator ) {
+ self->activator = activator;
+
+ // if on, turn it off
+ if ( self->nextthink ) {
+ self->nextthink = 0;
+ return;
+ }
+
+ // turn it on
+ func_timer_think (self);
+}
+
+void SP_func_timer( gentity_t *self ) {
+ G_SpawnFloat( "random", "1", &self->random);
+ G_SpawnFloat( "wait", "1", &self->wait );
+
+ self->use = func_timer_use;
+ self->think = func_timer_think;
+
+ if ( self->random >= self->wait ) {
+ self->random = self->wait - FRAMETIME;
+ G_Printf( "func_timer at %s has random >= wait\n", vtos( self->s.origin ) );
+ }
+
+ if ( self->spawnflags & 1 ) {
+ self->nextthink = level.time + FRAMETIME;
+ self->activator = self;
+ }
+
+ self->r.svFlags = SVF_NOCLIENT;
+}
+
+
diff --git a/code/game/g_utils.c b/code/game/g_utils.c
new file mode 100755
index 0000000..adef5d1
--- /dev/null
+++ b/code/game/g_utils.c
@@ -0,0 +1,666 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// g_utils.c -- misc utility functions for game module
+
+#include "g_local.h"
+
+typedef struct {
+ char oldShader[MAX_QPATH];
+ char newShader[MAX_QPATH];
+ float timeOffset;
+} shaderRemap_t;
+
+#define MAX_SHADER_REMAPS 128
+
+int remapCount = 0;
+shaderRemap_t remappedShaders[MAX_SHADER_REMAPS];
+
+void AddRemap(const char *oldShader, const char *newShader, float timeOffset) {
+ int i;
+
+ for (i = 0; i < remapCount; i++) {
+ if (Q_stricmp(oldShader, remappedShaders[i].oldShader) == 0) {
+ // found it, just update this one
+ strcpy(remappedShaders[i].newShader,newShader);
+ remappedShaders[i].timeOffset = timeOffset;
+ return;
+ }
+ }
+ if (remapCount < MAX_SHADER_REMAPS) {
+ strcpy(remappedShaders[remapCount].newShader,newShader);
+ strcpy(remappedShaders[remapCount].oldShader,oldShader);
+ remappedShaders[remapCount].timeOffset = timeOffset;
+ remapCount++;
+ }
+}
+
+const char *BuildShaderStateConfig() {
+ static char buff[MAX_STRING_CHARS*4];
+ char out[(MAX_QPATH * 2) + 5];
+ int i;
+
+ memset(buff, 0, MAX_STRING_CHARS);
+ for (i = 0; i < remapCount; i++) {
+ Com_sprintf(out, (MAX_QPATH * 2) + 5, "%s=%s:%5.2f@", remappedShaders[i].oldShader, remappedShaders[i].newShader, remappedShaders[i].timeOffset);
+ Q_strcat( buff, sizeof( buff ), out);
+ }
+ return buff;
+}
+
+/*
+=========================================================================
+
+model / sound configstring indexes
+
+=========================================================================
+*/
+
+/*
+================
+G_FindConfigstringIndex
+
+================
+*/
+int G_FindConfigstringIndex( char *name, int start, int max, qboolean create ) {
+ int i;
+ char s[MAX_STRING_CHARS];
+
+ if ( !name || !name[0] ) {
+ return 0;
+ }
+
+ for ( i=1 ; i<max ; i++ ) {
+ trap_GetConfigstring( start + i, s, sizeof( s ) );
+ if ( !s[0] ) {
+ break;
+ }
+ if ( !strcmp( s, name ) ) {
+ return i;
+ }
+ }
+
+ if ( !create ) {
+ return 0;
+ }
+
+ if ( i == max ) {
+ G_Error( "G_FindConfigstringIndex: overflow" );
+ }
+
+ trap_SetConfigstring( start + i, name );
+
+ return i;
+}
+
+
+int G_ModelIndex( char *name ) {
+ return G_FindConfigstringIndex (name, CS_MODELS, MAX_MODELS, qtrue);
+}
+
+int G_SoundIndex( char *name ) {
+ return G_FindConfigstringIndex (name, CS_SOUNDS, MAX_SOUNDS, qtrue);
+}
+
+//=====================================================================
+
+
+/*
+================
+G_TeamCommand
+
+Broadcasts a command to only a specific team
+================
+*/
+void G_TeamCommand( team_t team, char *cmd ) {
+ int i;
+
+ for ( i = 0 ; i < level.maxclients ; i++ ) {
+ if ( level.clients[i].pers.connected == CON_CONNECTED ) {
+ if ( level.clients[i].sess.sessionTeam == team ) {
+ trap_SendServerCommand( i, va("%s", cmd ));
+ }
+ }
+ }
+}
+
+
+/*
+=============
+G_Find
+
+Searches all active entities for the next one that holds
+the matching string at fieldofs (use the FOFS() macro) in the structure.
+
+Searches beginning at the entity after from, or the beginning if NULL
+NULL will be returned if the end of the list is reached.
+
+=============
+*/
+gentity_t *G_Find (gentity_t *from, int fieldofs, const char *match)
+{
+ char *s;
+
+ if (!from)
+ from = g_entities;
+ else
+ from++;
+
+ for ( ; from < &g_entities[level.num_entities] ; from++)
+ {
+ if (!from->inuse)
+ continue;
+ s = *(char **) ((byte *)from + fieldofs);
+ if (!s)
+ continue;
+ if (!Q_stricmp (s, match))
+ return from;
+ }
+
+ return NULL;
+}
+
+
+/*
+=============
+G_PickTarget
+
+Selects a random entity from among the targets
+=============
+*/
+#define MAXCHOICES 32
+
+gentity_t *G_PickTarget (char *targetname)
+{
+ gentity_t *ent = NULL;
+ int num_choices = 0;
+ gentity_t *choice[MAXCHOICES];
+
+ if (!targetname)
+ {
+ G_Printf("G_PickTarget called with NULL targetname\n");
+ return NULL;
+ }
+
+ while(1)
+ {
+ ent = G_Find (ent, FOFS(targetname), targetname);
+ if (!ent)
+ break;
+ choice[num_choices++] = ent;
+ if (num_choices == MAXCHOICES)
+ break;
+ }
+
+ if (!num_choices)
+ {
+ G_Printf("G_PickTarget: target %s not found\n", targetname);
+ return NULL;
+ }
+
+ return choice[rand() % num_choices];
+}
+
+
+/*
+==============================
+G_UseTargets
+
+"activator" should be set to the entity that initiated the firing.
+
+Search for (string)targetname in all entities that
+match (string)self.target and call their .use function
+
+==============================
+*/
+void G_UseTargets( gentity_t *ent, gentity_t *activator ) {
+ gentity_t *t;
+
+ if ( !ent ) {
+ return;
+ }
+
+ if (ent->targetShaderName && ent->targetShaderNewName) {
+ float f = level.time * 0.001;
+ AddRemap(ent->targetShaderName, ent->targetShaderNewName, f);
+ trap_SetConfigstring(CS_SHADERSTATE, BuildShaderStateConfig());
+ }
+
+ if ( !ent->target ) {
+ return;
+ }
+
+ t = NULL;
+ while ( (t = G_Find (t, FOFS(targetname), ent->target)) != NULL ) {
+ if ( t == ent ) {
+ G_Printf ("WARNING: Entity used itself.\n");
+ } else {
+ if ( t->use ) {
+ t->use (t, ent, activator);
+ }
+ }
+ if ( !ent->inuse ) {
+ G_Printf("entity was removed while using targets\n");
+ return;
+ }
+ }
+}
+
+
+/*
+=============
+TempVector
+
+This is just a convenience function
+for making temporary vectors for function calls
+=============
+*/
+float *tv( float x, float y, float z ) {
+ static int index;
+ static vec3_t vecs[8];
+ float *v;
+
+ // use an array so that multiple tempvectors won't collide
+ // for a while
+ v = vecs[index];
+ index = (index + 1)&7;
+
+ v[0] = x;
+ v[1] = y;
+ v[2] = z;
+
+ return v;
+}
+
+
+/*
+=============
+VectorToString
+
+This is just a convenience function
+for printing vectors
+=============
+*/
+char *vtos( const vec3_t v ) {
+ static int index;
+ static char str[8][32];
+ char *s;
+
+ // use an array so that multiple vtos won't collide
+ s = str[index];
+ index = (index + 1)&7;
+
+ Com_sprintf (s, 32, "(%i %i %i)", (int)v[0], (int)v[1], (int)v[2]);
+
+ return s;
+}
+
+
+/*
+===============
+G_SetMovedir
+
+The editor only specifies a single value for angles (yaw),
+but we have special constants to generate an up or down direction.
+Angles will be cleared, because it is being used to represent a direction
+instead of an orientation.
+===============
+*/
+void G_SetMovedir( vec3_t angles, vec3_t movedir ) {
+ static vec3_t VEC_UP = {0, -1, 0};
+ static vec3_t MOVEDIR_UP = {0, 0, 1};
+ static vec3_t VEC_DOWN = {0, -2, 0};
+ static vec3_t MOVEDIR_DOWN = {0, 0, -1};
+
+ if ( VectorCompare (angles, VEC_UP) ) {
+ VectorCopy (MOVEDIR_UP, movedir);
+ } else if ( VectorCompare (angles, VEC_DOWN) ) {
+ VectorCopy (MOVEDIR_DOWN, movedir);
+ } else {
+ AngleVectors (angles, movedir, NULL, NULL);
+ }
+ VectorClear( angles );
+}
+
+
+float vectoyaw( const vec3_t vec ) {
+ float yaw;
+
+ if (vec[YAW] == 0 && vec[PITCH] == 0) {
+ yaw = 0;
+ } else {
+ if (vec[PITCH]) {
+ yaw = ( atan2( vec[YAW], vec[PITCH]) * 180 / M_PI );
+ } else if (vec[YAW] > 0) {
+ yaw = 90;
+ } else {
+ yaw = 270;
+ }
+ if (yaw < 0) {
+ yaw += 360;
+ }
+ }
+
+ return yaw;
+}
+
+
+void G_InitGentity( gentity_t *e ) {
+ e->inuse = qtrue;
+ e->classname = "noclass";
+ e->s.number = e - g_entities;
+ e->r.ownerNum = ENTITYNUM_NONE;
+}
+
+/*
+=================
+G_Spawn
+
+Either finds a free entity, or allocates a new one.
+
+ The slots from 0 to MAX_CLIENTS-1 are always reserved for clients, and will
+never be used by anything else.
+
+Try to avoid reusing an entity that was recently freed, because it
+can cause the client to think the entity morphed into something else
+instead of being removed and recreated, which can cause interpolated
+angles and bad trails.
+=================
+*/
+gentity_t *G_Spawn( void ) {
+ int i, force;
+ gentity_t *e;
+
+ e = NULL; // shut up warning
+ i = 0; // shut up warning
+ for ( force = 0 ; force < 2 ; force++ ) {
+ // if we go through all entities and can't find one to free,
+ // override the normal minimum times before use
+ e = &g_entities[MAX_CLIENTS];
+ for ( i = MAX_CLIENTS ; i<level.num_entities ; i++, e++) {
+ if ( e->inuse ) {
+ continue;
+ }
+
+ // the first couple seconds of server time can involve a lot of
+ // freeing and allocating, so relax the replacement policy
+ if ( !force && e->freetime > level.startTime + 2000 && level.time - e->freetime < 1000 ) {
+ continue;
+ }
+
+ // reuse this slot
+ G_InitGentity( e );
+ return e;
+ }
+ if ( i != MAX_GENTITIES ) {
+ break;
+ }
+ }
+ if ( i == ENTITYNUM_MAX_NORMAL ) {
+ for (i = 0; i < MAX_GENTITIES; i++) {
+ G_Printf("%4i: %s\n", i, g_entities[i].classname);
+ }
+ G_Error( "G_Spawn: no free entities" );
+ }
+
+ // open up a new slot
+ level.num_entities++;
+
+ // let the server system know that there are more entities
+ trap_LocateGameData( level.gentities, level.num_entities, sizeof( gentity_t ),
+ &level.clients[0].ps, sizeof( level.clients[0] ) );
+
+ G_InitGentity( e );
+ return e;
+}
+
+/*
+=================
+G_EntitiesFree
+=================
+*/
+qboolean G_EntitiesFree( void ) {
+ int i;
+ gentity_t *e;
+
+ e = &g_entities[MAX_CLIENTS];
+ for ( i = MAX_CLIENTS; i < level.num_entities; i++, e++) {
+ if ( e->inuse ) {
+ continue;
+ }
+ // slot available
+ return qtrue;
+ }
+ return qfalse;
+}
+
+
+/*
+=================
+G_FreeEntity
+
+Marks the entity as free
+=================
+*/
+void G_FreeEntity( gentity_t *ed ) {
+ trap_UnlinkEntity (ed); // unlink from world
+
+ if ( ed->neverFree ) {
+ return;
+ }
+
+ memset (ed, 0, sizeof(*ed));
+ ed->classname = "freed";
+ ed->freetime = level.time;
+ ed->inuse = qfalse;
+}
+
+/*
+=================
+G_TempEntity
+
+Spawns an event entity that will be auto-removed
+The origin will be snapped to save net bandwidth, so care
+must be taken if the origin is right on a surface (snap towards start vector first)
+=================
+*/
+gentity_t *G_TempEntity( vec3_t origin, int event ) {
+ gentity_t *e;
+ vec3_t snapped;
+
+ e = G_Spawn();
+ e->s.eType = ET_EVENTS + event;
+
+ e->classname = "tempEntity";
+ e->eventTime = level.time;
+ e->freeAfterEvent = qtrue;
+
+ VectorCopy( origin, snapped );
+ SnapVector( snapped ); // save network bandwidth
+ G_SetOrigin( e, snapped );
+
+ // find cluster for PVS
+ trap_LinkEntity( e );
+
+ return e;
+}
+
+
+
+/*
+==============================================================================
+
+Kill box
+
+==============================================================================
+*/
+
+/*
+=================
+G_KillBox
+
+Kills all entities that would touch the proposed new positioning
+of ent. Ent should be unlinked before calling this!
+=================
+*/
+void G_KillBox (gentity_t *ent) {
+ int i, num;
+ int touch[MAX_GENTITIES];
+ gentity_t *hit;
+ vec3_t mins, maxs;
+
+ VectorAdd( ent->client->ps.origin, ent->r.mins, mins );
+ VectorAdd( ent->client->ps.origin, ent->r.maxs, maxs );
+ num = trap_EntitiesInBox( mins, maxs, touch, MAX_GENTITIES );
+
+ for (i=0 ; i<num ; i++) {
+ hit = &g_entities[touch[i]];
+ if ( !hit->client ) {
+ continue;
+ }
+
+ // nail it
+ G_Damage ( hit, ent, ent, NULL, NULL,
+ 100000, DAMAGE_NO_PROTECTION, MOD_TELEFRAG);
+ }
+
+}
+
+//==============================================================================
+
+/*
+===============
+G_AddPredictableEvent
+
+Use for non-pmove events that would also be predicted on the
+client side: jumppads and item pickups
+Adds an event+parm and twiddles the event counter
+===============
+*/
+void G_AddPredictableEvent( gentity_t *ent, int event, int eventParm ) {
+ if ( !ent->client ) {
+ return;
+ }
+ BG_AddPredictableEventToPlayerstate( event, eventParm, &ent->client->ps );
+}
+
+
+/*
+===============
+G_AddEvent
+
+Adds an event+parm and twiddles the event counter
+===============
+*/
+void G_AddEvent( gentity_t *ent, int event, int eventParm ) {
+ int bits;
+
+ if ( !event ) {
+ G_Printf( "G_AddEvent: zero event added for entity %i\n", ent->s.number );
+ return;
+ }
+
+ // clients need to add the event in playerState_t instead of entityState_t
+ if ( ent->client ) {
+ bits = ent->client->ps.externalEvent & EV_EVENT_BITS;
+ bits = ( bits + EV_EVENT_BIT1 ) & EV_EVENT_BITS;
+ ent->client->ps.externalEvent = event | bits;
+ ent->client->ps.externalEventParm = eventParm;
+ ent->client->ps.externalEventTime = level.time;
+ } else {
+ bits = ent->s.event & EV_EVENT_BITS;
+ bits = ( bits + EV_EVENT_BIT1 ) & EV_EVENT_BITS;
+ ent->s.event = event | bits;
+ ent->s.eventParm = eventParm;
+ }
+ ent->eventTime = level.time;
+}
+
+
+/*
+=============
+G_Sound
+=============
+*/
+void G_Sound( gentity_t *ent, int channel, int soundIndex ) {
+ gentity_t *te;
+
+ te = G_TempEntity( ent->r.currentOrigin, EV_GENERAL_SOUND );
+ te->s.eventParm = soundIndex;
+}
+
+
+//==============================================================================
+
+
+/*
+================
+G_SetOrigin
+
+Sets the pos trajectory for a fixed position
+================
+*/
+void G_SetOrigin( gentity_t *ent, vec3_t origin ) {
+ VectorCopy( origin, ent->s.pos.trBase );
+ ent->s.pos.trType = TR_STATIONARY;
+ ent->s.pos.trTime = 0;
+ ent->s.pos.trDuration = 0;
+ VectorClear( ent->s.pos.trDelta );
+
+ VectorCopy( origin, ent->r.currentOrigin );
+}
+
+/*
+================
+DebugLine
+
+ debug polygons only work when running a local game
+ with r_debugSurface set to 2
+================
+*/
+int DebugLine(vec3_t start, vec3_t end, int color) {
+ vec3_t points[4], dir, cross, up = {0, 0, 1};
+ float dot;
+
+ VectorCopy(start, points[0]);
+ VectorCopy(start, points[1]);
+ //points[1][2] -= 2;
+ VectorCopy(end, points[2]);
+ //points[2][2] -= 2;
+ VectorCopy(end, points[3]);
+
+
+ VectorSubtract(end, start, dir);
+ VectorNormalize(dir);
+ dot = DotProduct(dir, up);
+ if (dot > 0.99 || dot < -0.99) VectorSet(cross, 1, 0, 0);
+ else CrossProduct(dir, up, cross);
+
+ VectorNormalize(cross);
+
+ VectorMA(points[0], 2, cross, points[0]);
+ VectorMA(points[1], -2, cross, points[1]);
+ VectorMA(points[2], -2, cross, points[2]);
+ VectorMA(points[3], 2, cross, points[3]);
+
+ return trap_DebugPolygonCreate(color, 4, points);
+}
diff --git a/code/game/g_weapon.c b/code/game/g_weapon.c
new file mode 100755
index 0000000..5a3fe5e
--- /dev/null
+++ b/code/game/g_weapon.c
@@ -0,0 +1,1145 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// g_weapon.c
+// perform the server side effects of a weapon firing
+
+#include "g_local.h"
+
+static float s_quadFactor;
+static vec3_t forward, right, up;
+static vec3_t muzzle;
+
+#define NUM_NAILSHOTS 15
+
+/*
+================
+G_BounceProjectile
+================
+*/
+void G_BounceProjectile( vec3_t start, vec3_t impact, vec3_t dir, vec3_t endout ) {
+ vec3_t v, newv;
+ float dot;
+
+ VectorSubtract( impact, start, v );
+ dot = DotProduct( v, dir );
+ VectorMA( v, -2*dot, dir, newv );
+
+ VectorNormalize(newv);
+ VectorMA(impact, 8192, newv, endout);
+}
+
+
+/*
+======================================================================
+
+GAUNTLET
+
+======================================================================
+*/
+
+void Weapon_Gauntlet( gentity_t *ent ) {
+
+}
+
+/*
+===============
+CheckGauntletAttack
+===============
+*/
+qboolean CheckGauntletAttack( gentity_t *ent ) {
+ trace_t tr;
+ vec3_t end;
+ gentity_t *tent;
+ gentity_t *traceEnt;
+ int damage;
+
+ // set aiming directions
+ AngleVectors (ent->client->ps.viewangles, forward, right, up);
+
+ CalcMuzzlePoint ( ent, forward, right, up, muzzle );
+
+ VectorMA (muzzle, 32, forward, end);
+
+ trap_Trace (&tr, muzzle, NULL, NULL, end, ent->s.number, MASK_SHOT);
+ if ( tr.surfaceFlags & SURF_NOIMPACT ) {
+ return qfalse;
+ }
+
+ traceEnt = &g_entities[ tr.entityNum ];
+
+ // send blood impact
+ if ( traceEnt->takedamage && traceEnt->client ) {
+ tent = G_TempEntity( tr.endpos, EV_MISSILE_HIT );
+ tent->s.otherEntityNum = traceEnt->s.number;
+ tent->s.eventParm = DirToByte( tr.plane.normal );
+ tent->s.weapon = ent->s.weapon;
+ }
+
+ if ( !traceEnt->takedamage) {
+ return qfalse;
+ }
+
+ if (ent->client->ps.powerups[PW_QUAD] ) {
+ G_AddEvent( ent, EV_POWERUP_QUAD, 0 );
+ s_quadFactor = g_quadfactor.value;
+ } else {
+ s_quadFactor = 1;
+ }
+#ifdef MISSIONPACK
+ if( ent->client->persistantPowerup && ent->client->persistantPowerup->item && ent->client->persistantPowerup->item->giTag == PW_DOUBLER ) {
+ s_quadFactor *= 2;
+ }
+#endif
+
+ damage = 50 * s_quadFactor;
+ G_Damage( traceEnt, ent, ent, forward, tr.endpos,
+ damage, 0, MOD_GAUNTLET );
+
+ return qtrue;
+}
+
+
+/*
+======================================================================
+
+MACHINEGUN
+
+======================================================================
+*/
+
+/*
+======================
+SnapVectorTowards
+
+Round a vector to integers for more efficient network
+transmission, but make sure that it rounds towards a given point
+rather than blindly truncating. This prevents it from truncating
+into a wall.
+======================
+*/
+void SnapVectorTowards( vec3_t v, vec3_t to ) {
+ int i;
+
+ for ( i = 0 ; i < 3 ; i++ ) {
+ if ( to[i] <= v[i] ) {
+ v[i] = (int)v[i];
+ } else {
+ v[i] = (int)v[i] + 1;
+ }
+ }
+}
+
+#ifdef MISSIONPACK
+#define CHAINGUN_SPREAD 600
+#endif
+#define MACHINEGUN_SPREAD 200
+#define MACHINEGUN_DAMAGE 7
+#define MACHINEGUN_TEAM_DAMAGE 5 // wimpier MG in teamplay
+
+void Bullet_Fire (gentity_t *ent, float spread, int damage ) {
+ trace_t tr;
+ vec3_t end;
+#ifdef MISSIONPACK
+ vec3_t impactpoint, bouncedir;
+#endif
+ float r;
+ float u;
+ gentity_t *tent;
+ gentity_t *traceEnt;
+ int i, passent;
+
+ damage *= s_quadFactor;
+
+ r = random() * M_PI * 2.0f;
+ u = sin(r) * crandom() * spread * 16;
+ r = cos(r) * crandom() * spread * 16;
+ VectorMA (muzzle, 8192*16, forward, end);
+ VectorMA (end, r, right, end);
+ VectorMA (end, u, up, end);
+
+ passent = ent->s.number;
+ for (i = 0; i < 10; i++) {
+
+ trap_Trace (&tr, muzzle, NULL, NULL, end, passent, MASK_SHOT);
+ if ( tr.surfaceFlags & SURF_NOIMPACT ) {
+ return;
+ }
+
+ traceEnt = &g_entities[ tr.entityNum ];
+
+ // snap the endpos to integers, but nudged towards the line
+ SnapVectorTowards( tr.endpos, muzzle );
+
+ // send bullet impact
+ if ( traceEnt->takedamage && traceEnt->client ) {
+ tent = G_TempEntity( tr.endpos, EV_BULLET_HIT_FLESH );
+ tent->s.eventParm = traceEnt->s.number;
+ if( LogAccuracyHit( traceEnt, ent ) ) {
+ ent->client->accuracy_hits++;
+ }
+ } else {
+ tent = G_TempEntity( tr.endpos, EV_BULLET_HIT_WALL );
+ tent->s.eventParm = DirToByte( tr.plane.normal );
+ }
+ tent->s.otherEntityNum = ent->s.number;
+
+ if ( traceEnt->takedamage) {
+#ifdef MISSIONPACK
+ if ( traceEnt->client && traceEnt->client->invulnerabilityTime > level.time ) {
+ if (G_InvulnerabilityEffect( traceEnt, forward, tr.endpos, impactpoint, bouncedir )) {
+ G_BounceProjectile( muzzle, impactpoint, bouncedir, end );
+ VectorCopy( impactpoint, muzzle );
+ // the player can hit him/herself with the bounced rail
+ passent = ENTITYNUM_NONE;
+ }
+ else {
+ VectorCopy( tr.endpos, muzzle );
+ passent = traceEnt->s.number;
+ }
+ continue;
+ }
+ else {
+#endif
+ G_Damage( traceEnt, ent, ent, forward, tr.endpos,
+ damage, 0, MOD_MACHINEGUN);
+#ifdef MISSIONPACK
+ }
+#endif
+ }
+ break;
+ }
+}
+
+
+/*
+======================================================================
+
+BFG
+
+======================================================================
+*/
+
+void BFG_Fire ( gentity_t *ent ) {
+ gentity_t *m;
+
+ m = fire_bfg (ent, muzzle, forward);
+ m->damage *= s_quadFactor;
+ m->splashDamage *= s_quadFactor;
+
+// VectorAdd( m->s.pos.trDelta, ent->client->ps.velocity, m->s.pos.trDelta ); // "real" physics
+}
+
+
+/*
+======================================================================
+
+SHOTGUN
+
+======================================================================
+*/
+
+// DEFAULT_SHOTGUN_SPREAD and DEFAULT_SHOTGUN_COUNT are in bg_public.h, because
+// client predicts same spreads
+#define DEFAULT_SHOTGUN_DAMAGE 10
+
+qboolean ShotgunPellet( vec3_t start, vec3_t end, gentity_t *ent ) {
+ trace_t tr;
+ int damage, i, passent;
+ gentity_t *traceEnt;
+#ifdef MISSIONPACK
+ vec3_t impactpoint, bouncedir;
+#endif
+ vec3_t tr_start, tr_end;
+
+ passent = ent->s.number;
+ VectorCopy( start, tr_start );
+ VectorCopy( end, tr_end );
+ for (i = 0; i < 10; i++) {
+ trap_Trace (&tr, tr_start, NULL, NULL, tr_end, passent, MASK_SHOT);
+ traceEnt = &g_entities[ tr.entityNum ];
+
+ // send bullet impact
+ if ( tr.surfaceFlags & SURF_NOIMPACT ) {
+ return qfalse;
+ }
+
+ if ( traceEnt->takedamage) {
+ damage = DEFAULT_SHOTGUN_DAMAGE * s_quadFactor;
+#ifdef MISSIONPACK
+ if ( traceEnt->client && traceEnt->client->invulnerabilityTime > level.time ) {
+ if (G_InvulnerabilityEffect( traceEnt, forward, tr.endpos, impactpoint, bouncedir )) {
+ G_BounceProjectile( tr_start, impactpoint, bouncedir, tr_end );
+ VectorCopy( impactpoint, tr_start );
+ // the player can hit him/herself with the bounced rail
+ passent = ENTITYNUM_NONE;
+ }
+ else {
+ VectorCopy( tr.endpos, tr_start );
+ passent = traceEnt->s.number;
+ }
+ continue;
+ }
+ else {
+ G_Damage( traceEnt, ent, ent, forward, tr.endpos,
+ damage, 0, MOD_SHOTGUN);
+ if( LogAccuracyHit( traceEnt, ent ) ) {
+ return qtrue;
+ }
+ }
+#else
+ G_Damage( traceEnt, ent, ent, forward, tr.endpos, damage, 0, MOD_SHOTGUN);
+ if( LogAccuracyHit( traceEnt, ent ) ) {
+ return qtrue;
+ }
+#endif
+ }
+ return qfalse;
+ }
+ return qfalse;
+}
+
+// this should match CG_ShotgunPattern
+void ShotgunPattern( vec3_t origin, vec3_t origin2, int seed, gentity_t *ent ) {
+ int i;
+ float r, u;
+ vec3_t end;
+ vec3_t forward, right, up;
+ int oldScore;
+ qboolean hitClient = qfalse;
+
+ // derive the right and up vectors from the forward vector, because
+ // the client won't have any other information
+ VectorNormalize2( origin2, forward );
+ PerpendicularVector( right, forward );
+ CrossProduct( forward, right, up );
+
+ oldScore = ent->client->ps.persistant[PERS_SCORE];
+
+ // generate the "random" spread pattern
+ for ( i = 0 ; i < DEFAULT_SHOTGUN_COUNT ; i++ ) {
+ r = Q_crandom( &seed ) * DEFAULT_SHOTGUN_SPREAD * 16;
+ u = Q_crandom( &seed ) * DEFAULT_SHOTGUN_SPREAD * 16;
+ VectorMA( origin, 8192 * 16, forward, end);
+ VectorMA (end, r, right, end);
+ VectorMA (end, u, up, end);
+ if( ShotgunPellet( origin, end, ent ) && !hitClient ) {
+ hitClient = qtrue;
+ ent->client->accuracy_hits++;
+ }
+ }
+}
+
+
+void weapon_supershotgun_fire (gentity_t *ent) {
+ gentity_t *tent;
+
+ // send shotgun blast
+ tent = G_TempEntity( muzzle, EV_SHOTGUN );
+ VectorScale( forward, 4096, tent->s.origin2 );
+ SnapVector( tent->s.origin2 );
+ tent->s.eventParm = rand() & 255; // seed for spread pattern
+ tent->s.otherEntityNum = ent->s.number;
+
+ ShotgunPattern( tent->s.pos.trBase, tent->s.origin2, tent->s.eventParm, ent );
+}
+
+
+/*
+======================================================================
+
+GRENADE LAUNCHER
+
+======================================================================
+*/
+
+void weapon_grenadelauncher_fire (gentity_t *ent) {
+ gentity_t *m;
+
+ // extra vertical velocity
+ forward[2] += 0.2f;
+ VectorNormalize( forward );
+
+ m = fire_grenade (ent, muzzle, forward);
+ m->damage *= s_quadFactor;
+ m->splashDamage *= s_quadFactor;
+
+// VectorAdd( m->s.pos.trDelta, ent->client->ps.velocity, m->s.pos.trDelta ); // "real" physics
+}
+
+/*
+======================================================================
+
+ROCKET
+
+======================================================================
+*/
+
+void Weapon_RocketLauncher_Fire (gentity_t *ent) {
+ gentity_t *m;
+
+ m = fire_rocket (ent, muzzle, forward);
+ m->damage *= s_quadFactor;
+ m->splashDamage *= s_quadFactor;
+
+// VectorAdd( m->s.pos.trDelta, ent->client->ps.velocity, m->s.pos.trDelta ); // "real" physics
+}
+
+
+/*
+======================================================================
+
+PLASMA GUN
+
+======================================================================
+*/
+
+void Weapon_Plasmagun_Fire (gentity_t *ent) {
+ gentity_t *m;
+
+ m = fire_plasma (ent, muzzle, forward);
+ m->damage *= s_quadFactor;
+ m->splashDamage *= s_quadFactor;
+
+// VectorAdd( m->s.pos.trDelta, ent->client->ps.velocity, m->s.pos.trDelta ); // "real" physics
+}
+
+/*
+======================================================================
+
+RAILGUN
+
+======================================================================
+*/
+
+
+/*
+=================
+weapon_railgun_fire
+=================
+*/
+#define MAX_RAIL_HITS 4
+void weapon_railgun_fire (gentity_t *ent) {
+ vec3_t end;
+#ifdef MISSIONPACK
+ vec3_t impactpoint, bouncedir;
+#endif
+ trace_t trace;
+ gentity_t *tent;
+ gentity_t *traceEnt;
+ int damage;
+ int i;
+ int hits;
+ int unlinked;
+ int passent;
+ gentity_t *unlinkedEntities[MAX_RAIL_HITS];
+
+ damage = 100 * s_quadFactor;
+
+ VectorMA (muzzle, 8192, forward, end);
+
+ // trace only against the solids, so the railgun will go through people
+ unlinked = 0;
+ hits = 0;
+ passent = ent->s.number;
+ do {
+ trap_Trace (&trace, muzzle, NULL, NULL, end, passent, MASK_SHOT );
+ if ( trace.entityNum >= ENTITYNUM_MAX_NORMAL ) {
+ break;
+ }
+ traceEnt = &g_entities[ trace.entityNum ];
+ if ( traceEnt->takedamage ) {
+#ifdef MISSIONPACK
+ if ( traceEnt->client && traceEnt->client->invulnerabilityTime > level.time ) {
+ if ( G_InvulnerabilityEffect( traceEnt, forward, trace.endpos, impactpoint, bouncedir ) ) {
+ G_BounceProjectile( muzzle, impactpoint, bouncedir, end );
+ // snap the endpos to integers to save net bandwidth, but nudged towards the line
+ SnapVectorTowards( trace.endpos, muzzle );
+ // send railgun beam effect
+ tent = G_TempEntity( trace.endpos, EV_RAILTRAIL );
+ // set player number for custom colors on the railtrail
+ tent->s.clientNum = ent->s.clientNum;
+ VectorCopy( muzzle, tent->s.origin2 );
+ // move origin a bit to come closer to the drawn gun muzzle
+ VectorMA( tent->s.origin2, 4, right, tent->s.origin2 );
+ VectorMA( tent->s.origin2, -1, up, tent->s.origin2 );
+ tent->s.eventParm = 255; // don't make the explosion at the end
+ //
+ VectorCopy( impactpoint, muzzle );
+ // the player can hit him/herself with the bounced rail
+ passent = ENTITYNUM_NONE;
+ }
+ }
+ else {
+ if( LogAccuracyHit( traceEnt, ent ) ) {
+ hits++;
+ }
+ G_Damage (traceEnt, ent, ent, forward, trace.endpos, damage, 0, MOD_RAILGUN);
+ }
+#else
+ if( LogAccuracyHit( traceEnt, ent ) ) {
+ hits++;
+ }
+ G_Damage (traceEnt, ent, ent, forward, trace.endpos, damage, 0, MOD_RAILGUN);
+#endif
+ }
+ if ( trace.contents & CONTENTS_SOLID ) {
+ break; // we hit something solid enough to stop the beam
+ }
+ // unlink this entity, so the next trace will go past it
+ trap_UnlinkEntity( traceEnt );
+ unlinkedEntities[unlinked] = traceEnt;
+ unlinked++;
+ } while ( unlinked < MAX_RAIL_HITS );
+
+ // link back in any entities we unlinked
+ for ( i = 0 ; i < unlinked ; i++ ) {
+ trap_LinkEntity( unlinkedEntities[i] );
+ }
+
+ // the final trace endpos will be the terminal point of the rail trail
+
+ // snap the endpos to integers to save net bandwidth, but nudged towards the line
+ SnapVectorTowards( trace.endpos, muzzle );
+
+ // send railgun beam effect
+ tent = G_TempEntity( trace.endpos, EV_RAILTRAIL );
+
+ // set player number for custom colors on the railtrail
+ tent->s.clientNum = ent->s.clientNum;
+
+ VectorCopy( muzzle, tent->s.origin2 );
+ // move origin a bit to come closer to the drawn gun muzzle
+ VectorMA( tent->s.origin2, 4, right, tent->s.origin2 );
+ VectorMA( tent->s.origin2, -1, up, tent->s.origin2 );
+
+ // no explosion at end if SURF_NOIMPACT, but still make the trail
+ if ( trace.surfaceFlags & SURF_NOIMPACT ) {
+ tent->s.eventParm = 255; // don't make the explosion at the end
+ } else {
+ tent->s.eventParm = DirToByte( trace.plane.normal );
+ }
+ tent->s.clientNum = ent->s.clientNum;
+
+ // give the shooter a reward sound if they have made two railgun hits in a row
+ if ( hits == 0 ) {
+ // complete miss
+ ent->client->accurateCount = 0;
+ } else {
+ // check for "impressive" reward sound
+ ent->client->accurateCount += hits;
+ if ( ent->client->accurateCount >= 2 ) {
+ ent->client->accurateCount -= 2;
+ ent->client->ps.persistant[PERS_IMPRESSIVE_COUNT]++;
+ // add the sprite over the player's head
+ ent->client->ps.eFlags &= ~(EF_AWARD_IMPRESSIVE | EF_AWARD_EXCELLENT | EF_AWARD_GAUNTLET | EF_AWARD_ASSIST | EF_AWARD_DEFEND | EF_AWARD_CAP );
+ ent->client->ps.eFlags |= EF_AWARD_IMPRESSIVE;
+ ent->client->rewardTime = level.time + REWARD_SPRITE_TIME;
+ }
+ ent->client->accuracy_hits++;
+ }
+
+}
+
+
+/*
+======================================================================
+
+GRAPPLING HOOK
+
+======================================================================
+*/
+
+void Weapon_GrapplingHook_Fire (gentity_t *ent)
+{
+ if (!ent->client->fireHeld && !ent->client->hook)
+ fire_grapple (ent, muzzle, forward);
+
+ ent->client->fireHeld = qtrue;
+}
+
+void Weapon_HookFree (gentity_t *ent)
+{
+ ent->parent->client->hook = NULL;
+ ent->parent->client->ps.pm_flags &= ~PMF_GRAPPLE_PULL;
+ G_FreeEntity( ent );
+}
+
+void Weapon_HookThink (gentity_t *ent)
+{
+ if (ent->enemy) {
+ vec3_t v, oldorigin;
+
+ VectorCopy(ent->r.currentOrigin, oldorigin);
+ v[0] = ent->enemy->r.currentOrigin[0] + (ent->enemy->r.mins[0] + ent->enemy->r.maxs[0]) * 0.5;
+ v[1] = ent->enemy->r.currentOrigin[1] + (ent->enemy->r.mins[1] + ent->enemy->r.maxs[1]) * 0.5;
+ v[2] = ent->enemy->r.currentOrigin[2] + (ent->enemy->r.mins[2] + ent->enemy->r.maxs[2]) * 0.5;
+ SnapVectorTowards( v, oldorigin ); // save net bandwidth
+
+ G_SetOrigin( ent, v );
+ }
+
+ VectorCopy( ent->r.currentOrigin, ent->parent->client->ps.grapplePoint);
+}
+
+/*
+======================================================================
+
+LIGHTNING GUN
+
+======================================================================
+*/
+
+void Weapon_LightningFire( gentity_t *ent ) {
+ trace_t tr;
+ vec3_t end;
+#ifdef MISSIONPACK
+ vec3_t impactpoint, bouncedir;
+#endif
+ gentity_t *traceEnt, *tent;
+ int damage, i, passent;
+
+ damage = 8 * s_quadFactor;
+
+ passent = ent->s.number;
+ for (i = 0; i < 10; i++) {
+ VectorMA( muzzle, LIGHTNING_RANGE, forward, end );
+
+ trap_Trace( &tr, muzzle, NULL, NULL, end, passent, MASK_SHOT );
+
+#ifdef MISSIONPACK
+ // if not the first trace (the lightning bounced of an invulnerability sphere)
+ if (i) {
+ // add bounced off lightning bolt temp entity
+ // the first lightning bolt is a cgame only visual
+ //
+ tent = G_TempEntity( muzzle, EV_LIGHTNINGBOLT );
+ VectorCopy( tr.endpos, end );
+ SnapVector( end );
+ VectorCopy( end, tent->s.origin2 );
+ }
+#endif
+ if ( tr.entityNum == ENTITYNUM_NONE ) {
+ return;
+ }
+
+ traceEnt = &g_entities[ tr.entityNum ];
+
+ if ( traceEnt->takedamage) {
+#ifdef MISSIONPACK
+ if ( traceEnt->client && traceEnt->client->invulnerabilityTime > level.time ) {
+ if (G_InvulnerabilityEffect( traceEnt, forward, tr.endpos, impactpoint, bouncedir )) {
+ G_BounceProjectile( muzzle, impactpoint, bouncedir, end );
+ VectorCopy( impactpoint, muzzle );
+ VectorSubtract( end, impactpoint, forward );
+ VectorNormalize(forward);
+ // the player can hit him/herself with the bounced lightning
+ passent = ENTITYNUM_NONE;
+ }
+ else {
+ VectorCopy( tr.endpos, muzzle );
+ passent = traceEnt->s.number;
+ }
+ continue;
+ }
+ else {
+ G_Damage( traceEnt, ent, ent, forward, tr.endpos,
+ damage, 0, MOD_LIGHTNING);
+ }
+#else
+ G_Damage( traceEnt, ent, ent, forward, tr.endpos,
+ damage, 0, MOD_LIGHTNING);
+#endif
+ }
+
+ if ( traceEnt->takedamage && traceEnt->client ) {
+ tent = G_TempEntity( tr.endpos, EV_MISSILE_HIT );
+ tent->s.otherEntityNum = traceEnt->s.number;
+ tent->s.eventParm = DirToByte( tr.plane.normal );
+ tent->s.weapon = ent->s.weapon;
+ if( LogAccuracyHit( traceEnt, ent ) ) {
+ ent->client->accuracy_hits++;
+ }
+ } else if ( !( tr.surfaceFlags & SURF_NOIMPACT ) ) {
+ tent = G_TempEntity( tr.endpos, EV_MISSILE_MISS );
+ tent->s.eventParm = DirToByte( tr.plane.normal );
+ }
+
+ break;
+ }
+}
+
+#ifdef MISSIONPACK
+/*
+======================================================================
+
+NAILGUN
+
+======================================================================
+*/
+
+void Weapon_Nailgun_Fire (gentity_t *ent) {
+ gentity_t *m;
+ int count;
+
+ for( count = 0; count < NUM_NAILSHOTS; count++ ) {
+ m = fire_nail (ent, muzzle, forward, right, up );
+ m->damage *= s_quadFactor;
+ m->splashDamage *= s_quadFactor;
+ }
+
+// VectorAdd( m->s.pos.trDelta, ent->client->ps.velocity, m->s.pos.trDelta ); // "real" physics
+}
+
+
+/*
+======================================================================
+
+PROXIMITY MINE LAUNCHER
+
+======================================================================
+*/
+
+void weapon_proxlauncher_fire (gentity_t *ent) {
+ gentity_t *m;
+
+ // extra vertical velocity
+ forward[2] += 0.2f;
+ VectorNormalize( forward );
+
+ m = fire_prox (ent, muzzle, forward);
+ m->damage *= s_quadFactor;
+ m->splashDamage *= s_quadFactor;
+
+// VectorAdd( m->s.pos.trDelta, ent->client->ps.velocity, m->s.pos.trDelta ); // "real" physics
+}
+
+#endif
+
+//======================================================================
+
+
+/*
+===============
+LogAccuracyHit
+===============
+*/
+qboolean LogAccuracyHit( gentity_t *target, gentity_t *attacker ) {
+ if( !target->takedamage ) {
+ return qfalse;
+ }
+
+ if ( target == attacker ) {
+ return qfalse;
+ }
+
+ if( !target->client ) {
+ return qfalse;
+ }
+
+ if( !attacker->client ) {
+ return qfalse;
+ }
+
+ if( target->client->ps.stats[STAT_HEALTH] <= 0 ) {
+ return qfalse;
+ }
+
+ if ( OnSameTeam( target, attacker ) ) {
+ return qfalse;
+ }
+
+ return qtrue;
+}
+
+
+/*
+===============
+CalcMuzzlePoint
+
+set muzzle location relative to pivoting eye
+===============
+*/
+void CalcMuzzlePoint ( gentity_t *ent, vec3_t forward, vec3_t right, vec3_t up, vec3_t muzzlePoint ) {
+ VectorCopy( ent->s.pos.trBase, muzzlePoint );
+ muzzlePoint[2] += ent->client->ps.viewheight;
+ VectorMA( muzzlePoint, 14, forward, muzzlePoint );
+ // snap to integer coordinates for more efficient network bandwidth usage
+ SnapVector( muzzlePoint );
+}
+
+/*
+===============
+CalcMuzzlePointOrigin
+
+set muzzle location relative to pivoting eye
+===============
+*/
+void CalcMuzzlePointOrigin ( gentity_t *ent, vec3_t origin, vec3_t forward, vec3_t right, vec3_t up, vec3_t muzzlePoint ) {
+ VectorCopy( ent->s.pos.trBase, muzzlePoint );
+ muzzlePoint[2] += ent->client->ps.viewheight;
+ VectorMA( muzzlePoint, 14, forward, muzzlePoint );
+ // snap to integer coordinates for more efficient network bandwidth usage
+ SnapVector( muzzlePoint );
+}
+
+
+
+/*
+===============
+FireWeapon
+===============
+*/
+void FireWeapon( gentity_t *ent ) {
+ if (ent->client->ps.powerups[PW_QUAD] ) {
+ s_quadFactor = g_quadfactor.value;
+ } else {
+ s_quadFactor = 1;
+ }
+#ifdef MISSIONPACK
+ if( ent->client->persistantPowerup && ent->client->persistantPowerup->item && ent->client->persistantPowerup->item->giTag == PW_DOUBLER ) {
+ s_quadFactor *= 2;
+ }
+#endif
+
+ // track shots taken for accuracy tracking. Grapple is not a weapon and gauntet is just not tracked
+ if( ent->s.weapon != WP_GRAPPLING_HOOK && ent->s.weapon != WP_GAUNTLET ) {
+#ifdef MISSIONPACK
+ if( ent->s.weapon == WP_NAILGUN ) {
+ ent->client->accuracy_shots += NUM_NAILSHOTS;
+ } else {
+ ent->client->accuracy_shots++;
+ }
+#else
+ ent->client->accuracy_shots++;
+#endif
+ }
+
+ // set aiming directions
+ AngleVectors (ent->client->ps.viewangles, forward, right, up);
+
+ CalcMuzzlePointOrigin ( ent, ent->client->oldOrigin, forward, right, up, muzzle );
+
+ // fire the specific weapon
+ switch( ent->s.weapon ) {
+ case WP_GAUNTLET:
+ Weapon_Gauntlet( ent );
+ break;
+ case WP_LIGHTNING:
+ Weapon_LightningFire( ent );
+ break;
+ case WP_SHOTGUN:
+ weapon_supershotgun_fire( ent );
+ break;
+ case WP_MACHINEGUN:
+ if ( g_gametype.integer != GT_TEAM ) {
+ Bullet_Fire( ent, MACHINEGUN_SPREAD, MACHINEGUN_DAMAGE );
+ } else {
+ Bullet_Fire( ent, MACHINEGUN_SPREAD, MACHINEGUN_TEAM_DAMAGE );
+ }
+ break;
+ case WP_GRENADE_LAUNCHER:
+ weapon_grenadelauncher_fire( ent );
+ break;
+ case WP_ROCKET_LAUNCHER:
+ Weapon_RocketLauncher_Fire( ent );
+ break;
+ case WP_PLASMAGUN:
+ Weapon_Plasmagun_Fire( ent );
+ break;
+ case WP_RAILGUN:
+ weapon_railgun_fire( ent );
+ break;
+ case WP_BFG:
+ BFG_Fire( ent );
+ break;
+ case WP_GRAPPLING_HOOK:
+ Weapon_GrapplingHook_Fire( ent );
+ break;
+#ifdef MISSIONPACK
+ case WP_NAILGUN:
+ Weapon_Nailgun_Fire( ent );
+ break;
+ case WP_PROX_LAUNCHER:
+ weapon_proxlauncher_fire( ent );
+ break;
+ case WP_CHAINGUN:
+ Bullet_Fire( ent, CHAINGUN_SPREAD, MACHINEGUN_DAMAGE );
+ break;
+#endif
+ default:
+// FIXME G_Error( "Bad ent->s.weapon" );
+ break;
+ }
+}
+
+
+#ifdef MISSIONPACK
+
+/*
+===============
+KamikazeRadiusDamage
+===============
+*/
+static void KamikazeRadiusDamage( vec3_t origin, gentity_t *attacker, float damage, float radius ) {
+ float dist;
+ gentity_t *ent;
+ int entityList[MAX_GENTITIES];
+ int numListedEntities;
+ vec3_t mins, maxs;
+ vec3_t v;
+ vec3_t dir;
+ int i, e;
+
+ if ( radius < 1 ) {
+ radius = 1;
+ }
+
+ for ( i = 0 ; i < 3 ; i++ ) {
+ mins[i] = origin[i] - radius;
+ maxs[i] = origin[i] + radius;
+ }
+
+ numListedEntities = trap_EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES );
+
+ for ( e = 0 ; e < numListedEntities ; e++ ) {
+ ent = &g_entities[entityList[ e ]];
+
+ if (!ent->takedamage) {
+ continue;
+ }
+
+ // dont hit things we have already hit
+ if( ent->kamikazeTime > level.time ) {
+ continue;
+ }
+
+ // find the distance from the edge of the bounding box
+ for ( i = 0 ; i < 3 ; i++ ) {
+ if ( origin[i] < ent->r.absmin[i] ) {
+ v[i] = ent->r.absmin[i] - origin[i];
+ } else if ( origin[i] > ent->r.absmax[i] ) {
+ v[i] = origin[i] - ent->r.absmax[i];
+ } else {
+ v[i] = 0;
+ }
+ }
+
+ dist = VectorLength( v );
+ if ( dist >= radius ) {
+ continue;
+ }
+
+// if( CanDamage (ent, origin) ) {
+ VectorSubtract (ent->r.currentOrigin, origin, dir);
+ // push the center of mass higher than the origin so players
+ // get knocked into the air more
+ dir[2] += 24;
+ G_Damage( ent, NULL, attacker, dir, origin, damage, DAMAGE_RADIUS|DAMAGE_NO_TEAM_PROTECTION, MOD_KAMIKAZE );
+ ent->kamikazeTime = level.time + 3000;
+// }
+ }
+}
+
+/*
+===============
+KamikazeShockWave
+===============
+*/
+static void KamikazeShockWave( vec3_t origin, gentity_t *attacker, float damage, float push, float radius ) {
+ float dist;
+ gentity_t *ent;
+ int entityList[MAX_GENTITIES];
+ int numListedEntities;
+ vec3_t mins, maxs;
+ vec3_t v;
+ vec3_t dir;
+ int i, e;
+
+ if ( radius < 1 )
+ radius = 1;
+
+ for ( i = 0 ; i < 3 ; i++ ) {
+ mins[i] = origin[i] - radius;
+ maxs[i] = origin[i] + radius;
+ }
+
+ numListedEntities = trap_EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES );
+
+ for ( e = 0 ; e < numListedEntities ; e++ ) {
+ ent = &g_entities[entityList[ e ]];
+
+ // dont hit things we have already hit
+ if( ent->kamikazeShockTime > level.time ) {
+ continue;
+ }
+
+ // find the distance from the edge of the bounding box
+ for ( i = 0 ; i < 3 ; i++ ) {
+ if ( origin[i] < ent->r.absmin[i] ) {
+ v[i] = ent->r.absmin[i] - origin[i];
+ } else if ( origin[i] > ent->r.absmax[i] ) {
+ v[i] = origin[i] - ent->r.absmax[i];
+ } else {
+ v[i] = 0;
+ }
+ }
+
+ dist = VectorLength( v );
+ if ( dist >= radius ) {
+ continue;
+ }
+
+// if( CanDamage (ent, origin) ) {
+ VectorSubtract (ent->r.currentOrigin, origin, dir);
+ dir[2] += 24;
+ G_Damage( ent, NULL, attacker, dir, origin, damage, DAMAGE_RADIUS|DAMAGE_NO_TEAM_PROTECTION, MOD_KAMIKAZE );
+ //
+ dir[2] = 0;
+ VectorNormalize(dir);
+ if ( ent->client ) {
+ ent->client->ps.velocity[0] = dir[0] * push;
+ ent->client->ps.velocity[1] = dir[1] * push;
+ ent->client->ps.velocity[2] = 100;
+ }
+ ent->kamikazeShockTime = level.time + 3000;
+// }
+ }
+}
+
+/*
+===============
+KamikazeDamage
+===============
+*/
+static void KamikazeDamage( gentity_t *self ) {
+ int i;
+ float t;
+ gentity_t *ent;
+ vec3_t newangles;
+
+ self->count += 100;
+
+ if (self->count >= KAMI_SHOCKWAVE_STARTTIME) {
+ // shockwave push back
+ t = self->count - KAMI_SHOCKWAVE_STARTTIME;
+ KamikazeShockWave(self->s.pos.trBase, self->activator, 25, 400, (int) (float) t * KAMI_SHOCKWAVE_MAXRADIUS / (KAMI_SHOCKWAVE_ENDTIME - KAMI_SHOCKWAVE_STARTTIME) );
+ }
+ //
+ if (self->count >= KAMI_EXPLODE_STARTTIME) {
+ // do our damage
+ t = self->count - KAMI_EXPLODE_STARTTIME;
+ KamikazeRadiusDamage( self->s.pos.trBase, self->activator, 400, (int) (float) t * KAMI_BOOMSPHERE_MAXRADIUS / (KAMI_IMPLODE_STARTTIME - KAMI_EXPLODE_STARTTIME) );
+ }
+
+ // either cycle or kill self
+ if( self->count >= KAMI_SHOCKWAVE_ENDTIME ) {
+ G_FreeEntity( self );
+ return;
+ }
+ self->nextthink = level.time + 100;
+
+ // add earth quake effect
+ newangles[0] = crandom() * 2;
+ newangles[1] = crandom() * 2;
+ newangles[2] = 0;
+ for (i = 0; i < MAX_CLIENTS; i++)
+ {
+ ent = &g_entities[i];
+ if (!ent->inuse)
+ continue;
+ if (!ent->client)
+ continue;
+
+ if (ent->client->ps.groundEntityNum != ENTITYNUM_NONE) {
+ ent->client->ps.velocity[0] += crandom() * 120;
+ ent->client->ps.velocity[1] += crandom() * 120;
+ ent->client->ps.velocity[2] = 30 + random() * 25;
+ }
+
+ ent->client->ps.delta_angles[0] += ANGLE2SHORT(newangles[0] - self->movedir[0]);
+ ent->client->ps.delta_angles[1] += ANGLE2SHORT(newangles[1] - self->movedir[1]);
+ ent->client->ps.delta_angles[2] += ANGLE2SHORT(newangles[2] - self->movedir[2]);
+ }
+ VectorCopy(newangles, self->movedir);
+}
+
+/*
+===============
+G_StartKamikaze
+===============
+*/
+void G_StartKamikaze( gentity_t *ent ) {
+ gentity_t *explosion;
+ gentity_t *te;
+ vec3_t snapped;
+
+ // start up the explosion logic
+ explosion = G_Spawn();
+
+ explosion->s.eType = ET_EVENTS + EV_KAMIKAZE;
+ explosion->eventTime = level.time;
+
+ if ( ent->client ) {
+ VectorCopy( ent->s.pos.trBase, snapped );
+ }
+ else {
+ VectorCopy( ent->activator->s.pos.trBase, snapped );
+ }
+ SnapVector( snapped ); // save network bandwidth
+ G_SetOrigin( explosion, snapped );
+
+ explosion->classname = "kamikaze";
+ explosion->s.pos.trType = TR_STATIONARY;
+
+ explosion->kamikazeTime = level.time;
+
+ explosion->think = KamikazeDamage;
+ explosion->nextthink = level.time + 100;
+ explosion->count = 0;
+ VectorClear(explosion->movedir);
+
+ trap_LinkEntity( explosion );
+
+ if (ent->client) {
+ //
+ explosion->activator = ent;
+ //
+ ent->s.eFlags &= ~EF_KAMIKAZE;
+ // nuke the guy that used it
+ G_Damage( ent, ent, ent, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, MOD_KAMIKAZE );
+ }
+ else {
+ if ( !strcmp(ent->activator->classname, "bodyque") ) {
+ explosion->activator = &g_entities[ent->activator->r.ownerNum];
+ }
+ else {
+ explosion->activator = ent->activator;
+ }
+ }
+
+ // play global sound at all clients
+ te = G_TempEntity(snapped, EV_GLOBAL_TEAM_SOUND );
+ te->r.svFlags |= SVF_BROADCAST;
+ te->s.eventParm = GTS_KAMIKAZE;
+}
+#endif
diff --git a/code/game/game.bat b/code/game/game.bat
new file mode 100755
index 0000000..65dd2b9
--- /dev/null
+++ b/code/game/game.bat
@@ -0,0 +1,85 @@
+rem make sure we have a safe environement
+set LIBRARY=
+set INCLUDE=
+
+mkdir vm
+cd vm
+set cc=lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\ui %1
+
+%cc% ../g_main.c
+@if errorlevel 1 goto quit
+
+%cc% ../g_syscalls.c
+@if errorlevel 1 goto quit
+
+%cc% ../bg_misc.c
+@if errorlevel 1 goto quit
+%cc% ../bg_lib.c
+@if errorlevel 1 goto quit
+%cc% ../bg_pmove.c
+@if errorlevel 1 goto quit
+%cc% ../bg_slidemove.c
+@if errorlevel 1 goto quit
+%cc% ../q_math.c
+@if errorlevel 1 goto quit
+%cc% ../q_shared.c
+@if errorlevel 1 goto quit
+
+%cc% ../ai_dmnet.c
+@if errorlevel 1 goto quit
+%cc% ../ai_dmq3.c
+@if errorlevel 1 goto quit
+%cc% ../ai_main.c
+@if errorlevel 1 goto quit
+%cc% ../ai_chat.c
+@if errorlevel 1 goto quit
+%cc% ../ai_cmd.c
+@if errorlevel 1 goto quit
+%cc% ../ai_team.c
+@if errorlevel 1 goto quit
+
+%cc% ../g_active.c
+@if errorlevel 1 goto quit
+%cc% ../g_arenas.c
+@if errorlevel 1 goto quit
+%cc% ../g_bot.c
+@if errorlevel 1 goto quit
+%cc% ../g_client.c
+@if errorlevel 1 goto quit
+%cc% ../g_cmds.c
+@if errorlevel 1 goto quit
+%cc% ../g_combat.c
+@if errorlevel 1 goto quit
+%cc% ../g_items.c
+@if errorlevel 1 goto quit
+%cc% ../g_mem.c
+@if errorlevel 1 goto quit
+%cc% ../g_misc.c
+@if errorlevel 1 goto quit
+%cc% ../g_missile.c
+@if errorlevel 1 goto quit
+%cc% ../g_mover.c
+@if errorlevel 1 goto quit
+%cc% ../g_session.c
+@if errorlevel 1 goto quit
+%cc% ../g_spawn.c
+@if errorlevel 1 goto quit
+%cc% ../g_svcmds.c
+@if errorlevel 1 goto quit
+%cc% ../g_target.c
+@if errorlevel 1 goto quit
+%cc% ../g_team.c
+@if errorlevel 1 goto quit
+%cc% ../g_trigger.c
+@if errorlevel 1 goto quit
+%cc% ../g_utils.c
+@if errorlevel 1 goto quit
+%cc% ../g_weapon.c
+@if errorlevel 1 goto quit
+%cc% ../ai_vcmd.c
+@if errorlevel 1 goto quit
+
+
+q3asm -f ../game
+:quit
+cd ..
diff --git a/code/game/game.def b/code/game/game.def
new file mode 100755
index 0000000..ea649b4
--- /dev/null
+++ b/code/game/game.def
@@ -0,0 +1,3 @@
+EXPORTS
+ dllEntry
+ vmMain
diff --git a/code/game/game.q3asm b/code/game/game.q3asm
new file mode 100755
index 0000000..c884e97
--- /dev/null
+++ b/code/game/game.q3asm
@@ -0,0 +1,35 @@
+-o "\quake3\baseq3\vm\qagame"
+g_main
+..\g_syscalls
+bg_misc
+bg_lib
+bg_pmove
+bg_slidemove
+q_math
+q_shared
+ai_dmnet
+ai_dmq3
+ai_team
+ai_main
+ai_chat
+ai_cmd
+ai_vcmd
+g_active
+g_arenas
+g_bot
+g_client
+g_cmds
+g_combat
+g_items
+g_mem
+g_misc
+g_missile
+g_mover
+g_session
+g_spawn
+g_svcmds
+g_target
+g_team
+g_trigger
+g_utils
+g_weapon
diff --git a/code/game/game.sh b/code/game/game.sh
new file mode 100755
index 0000000..be4984a
--- /dev/null
+++ b/code/game/game.sh
@@ -0,0 +1,48 @@
+#!/bin/sh
+
+mkdir -p vm
+cd vm
+
+CC="q3lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I../../cgame -I../../game -I../../q3_ui"
+
+$CC ../g_main.c
+$CC ../g_syscalls.c
+
+$CC ../bg_misc.c
+$CC ../bg_lib.c
+$CC ../bg_pmove.c
+$CC ../bg_slidemove.c
+$CC ../q_math.c
+$CC ../q_shared.c
+
+$CC ../ai_vcmd.c
+$CC ../ai_dmnet.c
+$CC ../ai_dmq3.c
+$CC ../ai_main.c
+$CC ../ai_chat.c
+$CC ../ai_cmd.c
+$CC ../ai_team.c
+
+$CC ../g_active.c
+$CC ../g_arenas.c
+$CC ../g_bot.c
+$CC ../g_client.c
+$CC ../g_cmds.c
+$CC ../g_combat.c
+$CC ../g_items.c
+$CC ../g_mem.c
+$CC ../g_misc.c
+$CC ../g_missile.c
+$CC ../g_mover.c
+$CC ../g_session.c
+$CC ../g_spawn.c
+$CC ../g_svcmds.c
+$CC ../g_target.c
+$CC ../g_team.c
+$CC ../g_trigger.c
+$CC ../g_utils.c
+$CC ../g_weapon.c
+
+q3asm -f ../game
+
+cd ..
diff --git a/code/game/game.vcproj b/code/game/game.vcproj
new file mode 100755
index 0000000..624a596
--- /dev/null
+++ b/code/game/game.vcproj
@@ -0,0 +1,2132 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+ ProjectType="Visual C++"
+ Version="7.10"
+ Name="game"
+ SccProjectName="&quot;$/MissionPack/code/game&quot;, CYAAAAAA"
+ SccLocalPath=".">
+ <Platforms>
+ <Platform
+ Name="Win32"/>
+ </Platforms>
+ <Configurations>
+ <Configuration
+ Name="Debug TA|Win32"
+ OutputDirectory=".\Debug_TA"
+ IntermediateDirectory=".\Debug_TA"
+ ConfigurationType="2"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ OptimizeForProcessor="1"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME"
+ RuntimeLibrary="1"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Debug_TA/game.pch"
+ AssemblerListingLocation=".\Debug_TA/"
+ ObjectFile=".\Debug_TA/"
+ ProgramDataBaseFileName=".\Debug_TA/"
+ BrowseInformation="1"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="winmm.lib"
+ OutputFile="..\Debug_TA\qagamex86.dll"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ ModuleDefinitionFile=".\game.def"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile=".\Debug_TA/qagamex86.pdb"
+ GenerateMapFile="TRUE"
+ MapFileName=".\Debug_TA/qagamex86.map"
+ SubSystem="2"
+ BaseAddress="0x20000000"
+ ImportLibrary=".\Debug_TA/qagamex86.lib"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="_DEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\Debug_TA/game.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Debug|Win32"
+ OutputDirectory=".\Debug"
+ IntermediateDirectory=".\Debug"
+ ConfigurationType="2"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ OptimizeForProcessor="1"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK"
+ RuntimeLibrary="1"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Debug/game.pch"
+ AssemblerListingLocation=".\Debug/"
+ ObjectFile=".\Debug/"
+ ProgramDataBaseFileName=".\Debug/"
+ BrowseInformation="1"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="winmm.lib"
+ OutputFile="../Debug/qagamex86.dll"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ ModuleDefinitionFile=".\game.def"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile=".\Debug/qagamex86.pdb"
+ GenerateMapFile="TRUE"
+ MapFileName=".\Debug/qagamex86.map"
+ SubSystem="2"
+ BaseAddress="0x20000000"
+ ImportLibrary=".\Debug/qagamex86.lib"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="_DEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\Debug/game.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Release Alpha|Win32"
+ OutputDirectory=".\..\ReleaseAXP"
+ IntermediateDirectory=".\ReleaseAXP"
+ ConfigurationType="2"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE">
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalOptions="/QA21164 "
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY"
+ StringPooling="TRUE"
+ RuntimeLibrary="4"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\ReleaseAXP/game.pch"
+ AssemblerListingLocation=".\ReleaseAXP/"
+ ObjectFile=".\ReleaseAXP/"
+ ProgramDataBaseFileName=".\ReleaseAXP/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="2"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="winmm.lib"
+ OutputFile="..\ReleaseAXP/qagameaxp.dll"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ ModuleDefinitionFile=".\game.def"
+ ProgramDatabaseFile=".\..\ReleaseAXP/qagameaxp.pdb"
+ SubSystem="2"
+ BaseAddress="0x20000000"
+ ImportLibrary=".\..\ReleaseAXP/qagameaxp.lib"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="NDEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\..\ReleaseAXP/game.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Debug Alpha|Win32"
+ OutputDirectory=".\..\DebugAxp"
+ IntermediateDirectory=".\DebugAxp"
+ ConfigurationType="2"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE">
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalOptions="/QA21164 /MTd "
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY"
+ RuntimeLibrary="5"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\DebugAxp/game.pch"
+ AssemblerListingLocation=".\DebugAxp/"
+ ObjectFile=".\DebugAxp/"
+ ProgramDataBaseFileName=".\DebugAxp/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="3"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="winmm.lib"
+ OutputFile="..\DebugAxp/qagameaxp.dll"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ ModuleDefinitionFile=".\game.def"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile=".\..\DebugAxp/qagameaxp.pdb"
+ SubSystem="2"
+ BaseAddress="0x20000000"
+ ImportLibrary=".\..\DebugAxp/qagameaxp.lib"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="_DEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\..\DebugAxp/game.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Release|Win32"
+ OutputDirectory=".\Release"
+ IntermediateDirectory=".\Release"
+ ConfigurationType="2"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ OptimizeForProcessor="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK"
+ StringPooling="TRUE"
+ RuntimeLibrary="4"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Release/game.pch"
+ AssemblerListingLocation=".\Release/"
+ ObjectFile=".\Release/"
+ ProgramDataBaseFileName=".\Release/"
+ WarningLevel="4"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="winmm.lib"
+ OutputFile="../Release/qagamex86.dll"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ ModuleDefinitionFile=".\game.def"
+ ProgramDatabaseFile=".\Release/qagamex86.pdb"
+ GenerateMapFile="TRUE"
+ MapFileName=".\Release/qagamex86.map"
+ SubSystem="2"
+ BaseAddress="0x20000000"
+ ImportLibrary=".\Release/qagamex86.lib"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="NDEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\Release/game.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Release TA|Win32"
+ OutputDirectory=".\Release_TA"
+ IntermediateDirectory=".\Release_TA"
+ ConfigurationType="2"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ OptimizeForProcessor="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK"
+ StringPooling="TRUE"
+ RuntimeLibrary="4"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Release_TA/game.pch"
+ AssemblerListingLocation=".\Release_TA/"
+ ObjectFile=".\Release_TA/"
+ ProgramDataBaseFileName=".\Release_TA/"
+ WarningLevel="4"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="winmm.lib"
+ OutputFile="../Release_TA/qagamex86.dll"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ ModuleDefinitionFile=".\game.def"
+ ProgramDatabaseFile=".\Release_TA/qagamex86.pdb"
+ GenerateMapFile="TRUE"
+ MapFileName=".\Release_TA/qagamex86.map"
+ SubSystem="2"
+ BaseAddress="0x20000000"
+ ImportLibrary=".\Release_TA/qagamex86.lib"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="NDEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\Release_TA/game.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ </Configurations>
+ <References>
+ </References>
+ <Files>
+ <Filter
+ Name="Source Files"
+ Filter="cpp;c;cxx;rc;def;r;odl;hpj;bat;for;f90">
+ <File
+ RelativePath="ai_chat.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ai_cmd.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ai_dmnet.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ai_dmq3.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ai_main.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ai_team.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ai_vcmd.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="bg_lib.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="bg_misc.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="bg_pmove.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="bg_slidemove.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="g_active.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="g_arenas.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="g_bot.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="g_client.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="g_cmds.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="g_combat.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="g_items.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="g_main.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="g_mem.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="g_misc.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="g_missile.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="g_mover.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="g_session.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="g_spawn.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="g_svcmds.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="g_syscalls.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="g_target.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="g_team.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="g_trigger.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="g_utils.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="g_weapon.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="game.def">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="q_math.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="q_shared.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;MISSIONPACK;QAGAME;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;BUILDING_REF_GL;DEBUG;GLOBALRANK;$(NoInherit)"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug Alpha|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;C_ONLY;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;GLOBALRANK;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;MISSIONPACK;$(NoInherit)"/>
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <Filter
+ Name="Header Files"
+ Filter="h;hpp;hxx;hm;inl;fi;fd">
+ <File
+ RelativePath="ai_chat.h">
+ </File>
+ <File
+ RelativePath="ai_cmd.h">
+ </File>
+ <File
+ RelativePath="ai_dmnet.h">
+ </File>
+ <File
+ RelativePath="ai_dmq3.h">
+ </File>
+ <File
+ RelativePath="ai_main.h">
+ </File>
+ <File
+ RelativePath="ai_team.h">
+ </File>
+ <File
+ RelativePath="ai_vcmd.h">
+ </File>
+ <File
+ RelativePath="be_aas.h">
+ </File>
+ <File
+ RelativePath="be_ai_char.h">
+ </File>
+ <File
+ RelativePath="be_ai_chat.h">
+ </File>
+ <File
+ RelativePath="be_ai_gen.h">
+ </File>
+ <File
+ RelativePath="be_ai_goal.h">
+ </File>
+ <File
+ RelativePath="be_ai_move.h">
+ </File>
+ <File
+ RelativePath="be_ai_weap.h">
+ </File>
+ <File
+ RelativePath="be_ea.h">
+ </File>
+ <File
+ RelativePath="bg_local.h">
+ </File>
+ <File
+ RelativePath="bg_public.h">
+ </File>
+ <File
+ RelativePath="botlib.h">
+ </File>
+ <File
+ RelativePath="chars.h">
+ </File>
+ <File
+ RelativePath="g_local.h">
+ </File>
+ <File
+ RelativePath="g_public.h">
+ </File>
+ <File
+ RelativePath="g_team.h">
+ </File>
+ <File
+ RelativePath="inv.h">
+ </File>
+ <File
+ RelativePath="match.h">
+ </File>
+ <File
+ RelativePath="q_shared.h">
+ </File>
+ <File
+ RelativePath="surfaceflags.h">
+ </File>
+ <File
+ RelativePath="syn.h">
+ </File>
+ </Filter>
+ <Filter
+ Name="Resource Files"
+ Filter="ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe">
+ </Filter>
+ </Files>
+ <Globals>
+ </Globals>
+</VisualStudioProject>
diff --git a/code/game/game_ta.bat b/code/game/game_ta.bat
new file mode 100755
index 0000000..96db7eb
--- /dev/null
+++ b/code/game/game_ta.bat
@@ -0,0 +1,86 @@
+rem make sure we have a safe environement
+set LIBRARY=
+set INCLUDE=
+
+mkdir vm
+cd vm
+set cc=lcc -DQ3_VM -DMISSIONPACK -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\ui %1
+
+%cc% ../g_main.c
+@if errorlevel 1 goto quit
+
+%cc% ../g_syscalls.c
+@if errorlevel 1 goto quit
+
+%cc% ../bg_misc.c
+@if errorlevel 1 goto quit
+%cc% ../bg_lib.c
+@if errorlevel 1 goto quit
+%cc% ../bg_pmove.c
+@if errorlevel 1 goto quit
+%cc% ../bg_slidemove.c
+@if errorlevel 1 goto quit
+%cc% ../q_math.c
+@if errorlevel 1 goto quit
+%cc% ../q_shared.c
+@if errorlevel 1 goto quit
+
+%cc% ../ai_dmnet.c
+@if errorlevel 1 goto quit
+%cc% ../ai_dmq3.c
+@if errorlevel 1 goto quit
+%cc% ../ai_main.c
+@if errorlevel 1 goto quit
+%cc% ../ai_chat.c
+@if errorlevel 1 goto quit
+%cc% ../ai_cmd.c
+@if errorlevel 1 goto quit
+%cc% ../ai_team.c
+@if errorlevel 1 goto quit
+
+%cc% ../g_active.c
+@if errorlevel 1 goto quit
+%cc% ../g_arenas.c
+@if errorlevel 1 goto quit
+%cc% ../g_bot.c
+@if errorlevel 1 goto quit
+%cc% ../g_client.c
+@if errorlevel 1 goto quit
+%cc% ../g_cmds.c
+@if errorlevel 1 goto quit
+%cc% ../g_combat.c
+@if errorlevel 1 goto quit
+%cc% ../g_items.c
+@if errorlevel 1 goto quit
+%cc% ../g_mem.c
+@if errorlevel 1 goto quit
+%cc% ../g_misc.c
+@if errorlevel 1 goto quit
+%cc% ../g_missile.c
+@if errorlevel 1 goto quit
+%cc% ../g_mover.c
+@if errorlevel 1 goto quit
+%cc% ../g_session.c
+@if errorlevel 1 goto quit
+%cc% ../g_spawn.c
+@if errorlevel 1 goto quit
+%cc% ../g_svcmds.c
+@if errorlevel 1 goto quit
+%cc% ../g_target.c
+@if errorlevel 1 goto quit
+%cc% ../g_team.c
+@if errorlevel 1 goto quit
+%cc% ../g_trigger.c
+@if errorlevel 1 goto quit
+%cc% ../g_utils.c
+@if errorlevel 1 goto quit
+%cc% ../g_weapon.c
+@if errorlevel 1 goto quit
+%cc% ../ai_vcmd.c
+@if errorlevel 1 goto quit
+
+
+
+q3asm -f ../game_ta
+:quit
+cd ..
diff --git a/code/game/game_ta.q3asm b/code/game/game_ta.q3asm
new file mode 100755
index 0000000..8c129cb
--- /dev/null
+++ b/code/game/game_ta.q3asm
@@ -0,0 +1,35 @@
+-o "\quake3\missionpack\vm\qagame"
+g_main
+..\g_syscalls
+bg_misc
+bg_lib
+bg_pmove
+bg_slidemove
+q_math
+q_shared
+ai_dmnet
+ai_dmq3
+ai_team
+ai_main
+ai_chat
+ai_cmd
+g_active
+g_arenas
+g_bot
+g_client
+g_cmds
+g_combat
+g_items
+g_mem
+g_misc
+g_missile
+g_mover
+g_session
+g_spawn
+g_svcmds
+g_target
+g_team
+g_trigger
+g_utils
+g_weapon
+ai_vcmd
diff --git a/code/game/game_ta.sh b/code/game/game_ta.sh
new file mode 100755
index 0000000..5ca3d7d
--- /dev/null
+++ b/code/game/game_ta.sh
@@ -0,0 +1,48 @@
+#!/bin/sh
+
+mkdir -p vm
+cd vm
+
+CC="q3lcc -DQ3_VM -DMISSIONPACK -S -Wf-target=bytecode -Wf-g -I../../cgame -I../../game -I../../ui"
+
+$CC ../g_main.c
+$CC ../g_syscalls.c
+
+$CC ../bg_misc.c
+$CC ../bg_lib.c
+$CC ../bg_pmove.c
+$CC ../bg_slidemove.c
+$CC ../q_math.c
+$CC ../q_shared.c
+
+$CC ../ai_vcmd.c
+$CC ../ai_dmnet.c
+$CC ../ai_dmq3.c
+$CC ../ai_main.c
+$CC ../ai_chat.c
+$CC ../ai_cmd.c
+$CC ../ai_team.c
+
+$CC ../g_active.c
+$CC ../g_arenas.c
+$CC ../g_bot.c
+$CC ../g_client.c
+$CC ../g_cmds.c
+$CC ../g_combat.c
+$CC ../g_items.c
+$CC ../g_mem.c
+$CC ../g_misc.c
+$CC ../g_missile.c
+$CC ../g_mover.c
+$CC ../g_session.c
+$CC ../g_spawn.c
+$CC ../g_svcmds.c
+$CC ../g_target.c
+$CC ../g_team.c
+$CC ../g_trigger.c
+$CC ../g_utils.c
+$CC ../g_weapon.c
+
+q3asm -f ../game_ta
+
+cd ..
diff --git a/code/game/inv.h b/code/game/inv.h
new file mode 100755
index 0000000..2d18bb8
--- /dev/null
+++ b/code/game/inv.h
@@ -0,0 +1,166 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#define INVENTORY_NONE 0
+//armor
+#define INVENTORY_ARMOR 1
+//weapons
+#define INVENTORY_GAUNTLET 4
+#define INVENTORY_SHOTGUN 5
+#define INVENTORY_MACHINEGUN 6
+#define INVENTORY_GRENADELAUNCHER 7
+#define INVENTORY_ROCKETLAUNCHER 8
+#define INVENTORY_LIGHTNING 9
+#define INVENTORY_RAILGUN 10
+#define INVENTORY_PLASMAGUN 11
+#define INVENTORY_BFG10K 13
+#define INVENTORY_GRAPPLINGHOOK 14
+#define INVENTORY_NAILGUN 15
+#define INVENTORY_PROXLAUNCHER 16
+#define INVENTORY_CHAINGUN 17
+//ammo
+#define INVENTORY_SHELLS 18
+#define INVENTORY_BULLETS 19
+#define INVENTORY_GRENADES 20
+#define INVENTORY_CELLS 21
+#define INVENTORY_LIGHTNINGAMMO 22
+#define INVENTORY_ROCKETS 23
+#define INVENTORY_SLUGS 24
+#define INVENTORY_BFGAMMO 25
+#define INVENTORY_NAILS 26
+#define INVENTORY_MINES 27
+#define INVENTORY_BELT 28
+//powerups
+#define INVENTORY_HEALTH 29
+#define INVENTORY_TELEPORTER 30
+#define INVENTORY_MEDKIT 31
+#define INVENTORY_KAMIKAZE 32
+#define INVENTORY_PORTAL 33
+#define INVENTORY_INVULNERABILITY 34
+#define INVENTORY_QUAD 35
+#define INVENTORY_ENVIRONMENTSUIT 36
+#define INVENTORY_HASTE 37
+#define INVENTORY_INVISIBILITY 38
+#define INVENTORY_REGEN 39
+#define INVENTORY_FLIGHT 40
+#define INVENTORY_SCOUT 41
+#define INVENTORY_GUARD 42
+#define INVENTORY_DOUBLER 43
+#define INVENTORY_AMMOREGEN 44
+
+#define INVENTORY_REDFLAG 45
+#define INVENTORY_BLUEFLAG 46
+#define INVENTORY_NEUTRALFLAG 47
+#define INVENTORY_REDCUBE 48
+#define INVENTORY_BLUECUBE 49
+//enemy stuff
+#define ENEMY_HORIZONTAL_DIST 200
+#define ENEMY_HEIGHT 201
+#define NUM_VISIBLE_ENEMIES 202
+#define NUM_VISIBLE_TEAMMATES 203
+
+// if running the mission pack
+#ifdef MISSIONPACK
+
+//#error "running mission pack"
+
+#endif
+
+//item numbers (make sure they are in sync with bg_itemlist in bg_misc.c)
+#define MODELINDEX_ARMORSHARD 1
+#define MODELINDEX_ARMORCOMBAT 2
+#define MODELINDEX_ARMORBODY 3
+#define MODELINDEX_HEALTHSMALL 4
+#define MODELINDEX_HEALTH 5
+#define MODELINDEX_HEALTHLARGE 6
+#define MODELINDEX_HEALTHMEGA 7
+
+#define MODELINDEX_GAUNTLET 8
+#define MODELINDEX_SHOTGUN 9
+#define MODELINDEX_MACHINEGUN 10
+#define MODELINDEX_GRENADELAUNCHER 11
+#define MODELINDEX_ROCKETLAUNCHER 12
+#define MODELINDEX_LIGHTNING 13
+#define MODELINDEX_RAILGUN 14
+#define MODELINDEX_PLASMAGUN 15
+#define MODELINDEX_BFG10K 16
+#define MODELINDEX_GRAPPLINGHOOK 17
+
+#define MODELINDEX_SHELLS 18
+#define MODELINDEX_BULLETS 19
+#define MODELINDEX_GRENADES 20
+#define MODELINDEX_CELLS 21
+#define MODELINDEX_LIGHTNINGAMMO 22
+#define MODELINDEX_ROCKETS 23
+#define MODELINDEX_SLUGS 24
+#define MODELINDEX_BFGAMMO 25
+
+#define MODELINDEX_TELEPORTER 26
+#define MODELINDEX_MEDKIT 27
+#define MODELINDEX_QUAD 28
+#define MODELINDEX_ENVIRONMENTSUIT 29
+#define MODELINDEX_HASTE 30
+#define MODELINDEX_INVISIBILITY 31
+#define MODELINDEX_REGEN 32
+#define MODELINDEX_FLIGHT 33
+
+#define MODELINDEX_REDFLAG 34
+#define MODELINDEX_BLUEFLAG 35
+
+// mission pack only defines
+
+#define MODELINDEX_KAMIKAZE 36
+#define MODELINDEX_PORTAL 37
+#define MODELINDEX_INVULNERABILITY 38
+
+#define MODELINDEX_NAILS 39
+#define MODELINDEX_MINES 40
+#define MODELINDEX_BELT 41
+
+#define MODELINDEX_SCOUT 42
+#define MODELINDEX_GUARD 43
+#define MODELINDEX_DOUBLER 44
+#define MODELINDEX_AMMOREGEN 45
+
+#define MODELINDEX_NEUTRALFLAG 46
+#define MODELINDEX_REDCUBE 47
+#define MODELINDEX_BLUECUBE 48
+
+#define MODELINDEX_NAILGUN 49
+#define MODELINDEX_PROXLAUNCHER 50
+#define MODELINDEX_CHAINGUN 51
+
+
+//
+#define WEAPONINDEX_GAUNTLET 1
+#define WEAPONINDEX_MACHINEGUN 2
+#define WEAPONINDEX_SHOTGUN 3
+#define WEAPONINDEX_GRENADE_LAUNCHER 4
+#define WEAPONINDEX_ROCKET_LAUNCHER 5
+#define WEAPONINDEX_LIGHTNING 6
+#define WEAPONINDEX_RAILGUN 7
+#define WEAPONINDEX_PLASMAGUN 8
+#define WEAPONINDEX_BFG 9
+#define WEAPONINDEX_GRAPPLING_HOOK 10
+#define WEAPONINDEX_NAILGUN 11
+#define WEAPONINDEX_PROXLAUNCHER 12
+#define WEAPONINDEX_CHAINGUN 13
diff --git a/code/game/match.h b/code/game/match.h
new file mode 100755
index 0000000..edd4d88
--- /dev/null
+++ b/code/game/match.h
@@ -0,0 +1,134 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+// make sure this is the same character as we use in chats in g_cmd.c
+#define EC "\x19"
+
+//match template contexts
+#define MTCONTEXT_MISC 2
+#define MTCONTEXT_INITIALTEAMCHAT 4
+#define MTCONTEXT_TIME 8
+#define MTCONTEXT_TEAMMATE 16
+#define MTCONTEXT_ADDRESSEE 32
+#define MTCONTEXT_PATROLKEYAREA 64
+#define MTCONTEXT_REPLYCHAT 128
+#define MTCONTEXT_CTF 256
+
+//message types
+#define MSG_NEWLEADER 1 //new leader
+#define MSG_ENTERGAME 2 //enter game message
+#define MSG_HELP 3 //help someone
+#define MSG_ACCOMPANY 4 //accompany someone
+#define MSG_DEFENDKEYAREA 5 //defend a key area
+#define MSG_RUSHBASE 6 //everyone rush to base
+#define MSG_GETFLAG 7 //get the enemy flag
+#define MSG_STARTTEAMLEADERSHIP 8 //someone wants to become the team leader
+#define MSG_STOPTEAMLEADERSHIP 9 //someone wants to stop being the team leader
+#define MSG_WHOISTEAMLAEDER 10 //who is the team leader
+#define MSG_WAIT 11 //wait for someone
+#define MSG_WHATAREYOUDOING 12 //what are you doing?
+#define MSG_JOINSUBTEAM 13 //join a sub-team
+#define MSG_LEAVESUBTEAM 14 //leave a sub-team
+#define MSG_CREATENEWFORMATION 15 //create a new formation
+#define MSG_FORMATIONPOSITION 16 //tell someone his/her position in a formation
+#define MSG_FORMATIONSPACE 17 //set the formation intervening space
+#define MSG_DOFORMATION 18 //form a known formation
+#define MSG_DISMISS 19 //dismiss commanded team mates
+#define MSG_CAMP 20 //camp somewhere
+#define MSG_CHECKPOINT 21 //remember a check point
+#define MSG_PATROL 22 //patrol between certain keypoints
+#define MSG_LEADTHEWAY 23 //lead the way
+#define MSG_GETITEM 24 //get an item
+#define MSG_KILL 25 //kill someone
+#define MSG_WHEREAREYOU 26 //where is someone
+#define MSG_RETURNFLAG 27 //return the flag
+#define MSG_WHATISMYCOMMAND 28 //ask the team leader what to do
+#define MSG_WHICHTEAM 29 //ask which team a bot is in
+#define MSG_TASKPREFERENCE 30 //tell your teamplay task preference
+#define MSG_ATTACKENEMYBASE 31 //attack the enemy base
+#define MSG_HARVEST 32 //go harvest
+#define MSG_SUICIDE 33 //order to suicide
+//
+#define MSG_ME 100
+#define MSG_EVERYONE 101
+#define MSG_MULTIPLENAMES 102
+#define MSG_NAME 103
+#define MSG_PATROLKEYAREA 104
+#define MSG_MINUTES 105
+#define MSG_SECONDS 106
+#define MSG_FOREVER 107
+#define MSG_FORALONGTIME 108
+#define MSG_FORAWHILE 109
+//
+#define MSG_CHATALL 200
+#define MSG_CHATTEAM 201
+#define MSG_CHATTELL 202
+//
+#define MSG_CTF 300 //ctf message
+
+//command sub types
+#define ST_SOMEWHERE 0
+#define ST_NEARITEM 1
+#define ST_ADDRESSED 2
+#define ST_METER 4
+#define ST_FEET 8
+#define ST_TIME 16
+#define ST_HERE 32
+#define ST_THERE 64
+#define ST_I 128
+#define ST_MORE 256
+#define ST_BACK 512
+#define ST_REVERSE 1024
+#define ST_SOMEONE 2048
+#define ST_GOTFLAG 4096
+#define ST_CAPTUREDFLAG 8192
+#define ST_RETURNEDFLAG 16384
+#define ST_TEAM 32768
+#define ST_1FCTFGOTFLAG 65535
+//ctf task preferences
+#define ST_DEFENDER 1
+#define ST_ATTACKER 2
+#define ST_ROAMER 4
+
+
+//word replacement variables
+#define THE_ENEMY 7
+#define THE_TEAM 7
+//team message variables
+#define NETNAME 0
+#define PLACE 1
+#define FLAG 1
+#define MESSAGE 2
+#define ADDRESSEE 2
+#define ITEM 3
+#define TEAMMATE 4
+#define TEAMNAME 4
+#define ENEMY 4
+#define KEYAREA 5
+#define FORMATION 5
+#define POSITION 5
+#define NUMBER 5
+#define TIME 6
+#define NAME 6
+#define MORE 6
+
+
diff --git a/code/game/q_math.c b/code/game/q_math.c
new file mode 100755
index 0000000..e5853ba
--- /dev/null
+++ b/code/game/q_math.c
@@ -0,0 +1,1308 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// q_math.c -- stateless support routines that are included in each code module
+#include "q_shared.h"
+
+
+vec3_t vec3_origin = {0,0,0};
+vec3_t axisDefault[3] = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 } };
+
+
+vec4_t colorBlack = {0, 0, 0, 1};
+vec4_t colorRed = {1, 0, 0, 1};
+vec4_t colorGreen = {0, 1, 0, 1};
+vec4_t colorBlue = {0, 0, 1, 1};
+vec4_t colorYellow = {1, 1, 0, 1};
+vec4_t colorMagenta= {1, 0, 1, 1};
+vec4_t colorCyan = {0, 1, 1, 1};
+vec4_t colorWhite = {1, 1, 1, 1};
+vec4_t colorLtGrey = {0.75, 0.75, 0.75, 1};
+vec4_t colorMdGrey = {0.5, 0.5, 0.5, 1};
+vec4_t colorDkGrey = {0.25, 0.25, 0.25, 1};
+
+vec4_t g_color_table[8] =
+ {
+ {0.0, 0.0, 0.0, 1.0},
+ {1.0, 0.0, 0.0, 1.0},
+ {0.0, 1.0, 0.0, 1.0},
+ {1.0, 1.0, 0.0, 1.0},
+ {0.0, 0.0, 1.0, 1.0},
+ {0.0, 1.0, 1.0, 1.0},
+ {1.0, 0.0, 1.0, 1.0},
+ {1.0, 1.0, 1.0, 1.0},
+ };
+
+
+vec3_t bytedirs[NUMVERTEXNORMALS] =
+{
+{-0.525731f, 0.000000f, 0.850651f}, {-0.442863f, 0.238856f, 0.864188f},
+{-0.295242f, 0.000000f, 0.955423f}, {-0.309017f, 0.500000f, 0.809017f},
+{-0.162460f, 0.262866f, 0.951056f}, {0.000000f, 0.000000f, 1.000000f},
+{0.000000f, 0.850651f, 0.525731f}, {-0.147621f, 0.716567f, 0.681718f},
+{0.147621f, 0.716567f, 0.681718f}, {0.000000f, 0.525731f, 0.850651f},
+{0.309017f, 0.500000f, 0.809017f}, {0.525731f, 0.000000f, 0.850651f},
+{0.295242f, 0.000000f, 0.955423f}, {0.442863f, 0.238856f, 0.864188f},
+{0.162460f, 0.262866f, 0.951056f}, {-0.681718f, 0.147621f, 0.716567f},
+{-0.809017f, 0.309017f, 0.500000f},{-0.587785f, 0.425325f, 0.688191f},
+{-0.850651f, 0.525731f, 0.000000f},{-0.864188f, 0.442863f, 0.238856f},
+{-0.716567f, 0.681718f, 0.147621f},{-0.688191f, 0.587785f, 0.425325f},
+{-0.500000f, 0.809017f, 0.309017f}, {-0.238856f, 0.864188f, 0.442863f},
+{-0.425325f, 0.688191f, 0.587785f}, {-0.716567f, 0.681718f, -0.147621f},
+{-0.500000f, 0.809017f, -0.309017f}, {-0.525731f, 0.850651f, 0.000000f},
+{0.000000f, 0.850651f, -0.525731f}, {-0.238856f, 0.864188f, -0.442863f},
+{0.000000f, 0.955423f, -0.295242f}, {-0.262866f, 0.951056f, -0.162460f},
+{0.000000f, 1.000000f, 0.000000f}, {0.000000f, 0.955423f, 0.295242f},
+{-0.262866f, 0.951056f, 0.162460f}, {0.238856f, 0.864188f, 0.442863f},
+{0.262866f, 0.951056f, 0.162460f}, {0.500000f, 0.809017f, 0.309017f},
+{0.238856f, 0.864188f, -0.442863f},{0.262866f, 0.951056f, -0.162460f},
+{0.500000f, 0.809017f, -0.309017f},{0.850651f, 0.525731f, 0.000000f},
+{0.716567f, 0.681718f, 0.147621f}, {0.716567f, 0.681718f, -0.147621f},
+{0.525731f, 0.850651f, 0.000000f}, {0.425325f, 0.688191f, 0.587785f},
+{0.864188f, 0.442863f, 0.238856f}, {0.688191f, 0.587785f, 0.425325f},
+{0.809017f, 0.309017f, 0.500000f}, {0.681718f, 0.147621f, 0.716567f},
+{0.587785f, 0.425325f, 0.688191f}, {0.955423f, 0.295242f, 0.000000f},
+{1.000000f, 0.000000f, 0.000000f}, {0.951056f, 0.162460f, 0.262866f},
+{0.850651f, -0.525731f, 0.000000f},{0.955423f, -0.295242f, 0.000000f},
+{0.864188f, -0.442863f, 0.238856f}, {0.951056f, -0.162460f, 0.262866f},
+{0.809017f, -0.309017f, 0.500000f}, {0.681718f, -0.147621f, 0.716567f},
+{0.850651f, 0.000000f, 0.525731f}, {0.864188f, 0.442863f, -0.238856f},
+{0.809017f, 0.309017f, -0.500000f}, {0.951056f, 0.162460f, -0.262866f},
+{0.525731f, 0.000000f, -0.850651f}, {0.681718f, 0.147621f, -0.716567f},
+{0.681718f, -0.147621f, -0.716567f},{0.850651f, 0.000000f, -0.525731f},
+{0.809017f, -0.309017f, -0.500000f}, {0.864188f, -0.442863f, -0.238856f},
+{0.951056f, -0.162460f, -0.262866f}, {0.147621f, 0.716567f, -0.681718f},
+{0.309017f, 0.500000f, -0.809017f}, {0.425325f, 0.688191f, -0.587785f},
+{0.442863f, 0.238856f, -0.864188f}, {0.587785f, 0.425325f, -0.688191f},
+{0.688191f, 0.587785f, -0.425325f}, {-0.147621f, 0.716567f, -0.681718f},
+{-0.309017f, 0.500000f, -0.809017f}, {0.000000f, 0.525731f, -0.850651f},
+{-0.525731f, 0.000000f, -0.850651f}, {-0.442863f, 0.238856f, -0.864188f},
+{-0.295242f, 0.000000f, -0.955423f}, {-0.162460f, 0.262866f, -0.951056f},
+{0.000000f, 0.000000f, -1.000000f}, {0.295242f, 0.000000f, -0.955423f},
+{0.162460f, 0.262866f, -0.951056f}, {-0.442863f, -0.238856f, -0.864188f},
+{-0.309017f, -0.500000f, -0.809017f}, {-0.162460f, -0.262866f, -0.951056f},
+{0.000000f, -0.850651f, -0.525731f}, {-0.147621f, -0.716567f, -0.681718f},
+{0.147621f, -0.716567f, -0.681718f}, {0.000000f, -0.525731f, -0.850651f},
+{0.309017f, -0.500000f, -0.809017f}, {0.442863f, -0.238856f, -0.864188f},
+{0.162460f, -0.262866f, -0.951056f}, {0.238856f, -0.864188f, -0.442863f},
+{0.500000f, -0.809017f, -0.309017f}, {0.425325f, -0.688191f, -0.587785f},
+{0.716567f, -0.681718f, -0.147621f}, {0.688191f, -0.587785f, -0.425325f},
+{0.587785f, -0.425325f, -0.688191f}, {0.000000f, -0.955423f, -0.295242f},
+{0.000000f, -1.000000f, 0.000000f}, {0.262866f, -0.951056f, -0.162460f},
+{0.000000f, -0.850651f, 0.525731f}, {0.000000f, -0.955423f, 0.295242f},
+{0.238856f, -0.864188f, 0.442863f}, {0.262866f, -0.951056f, 0.162460f},
+{0.500000f, -0.809017f, 0.309017f}, {0.716567f, -0.681718f, 0.147621f},
+{0.525731f, -0.850651f, 0.000000f}, {-0.238856f, -0.864188f, -0.442863f},
+{-0.500000f, -0.809017f, -0.309017f}, {-0.262866f, -0.951056f, -0.162460f},
+{-0.850651f, -0.525731f, 0.000000f}, {-0.716567f, -0.681718f, -0.147621f},
+{-0.716567f, -0.681718f, 0.147621f}, {-0.525731f, -0.850651f, 0.000000f},
+{-0.500000f, -0.809017f, 0.309017f}, {-0.238856f, -0.864188f, 0.442863f},
+{-0.262866f, -0.951056f, 0.162460f}, {-0.864188f, -0.442863f, 0.238856f},
+{-0.809017f, -0.309017f, 0.500000f}, {-0.688191f, -0.587785f, 0.425325f},
+{-0.681718f, -0.147621f, 0.716567f}, {-0.442863f, -0.238856f, 0.864188f},
+{-0.587785f, -0.425325f, 0.688191f}, {-0.309017f, -0.500000f, 0.809017f},
+{-0.147621f, -0.716567f, 0.681718f}, {-0.425325f, -0.688191f, 0.587785f},
+{-0.162460f, -0.262866f, 0.951056f}, {0.442863f, -0.238856f, 0.864188f},
+{0.162460f, -0.262866f, 0.951056f}, {0.309017f, -0.500000f, 0.809017f},
+{0.147621f, -0.716567f, 0.681718f}, {0.000000f, -0.525731f, 0.850651f},
+{0.425325f, -0.688191f, 0.587785f}, {0.587785f, -0.425325f, 0.688191f},
+{0.688191f, -0.587785f, 0.425325f}, {-0.955423f, 0.295242f, 0.000000f},
+{-0.951056f, 0.162460f, 0.262866f}, {-1.000000f, 0.000000f, 0.000000f},
+{-0.850651f, 0.000000f, 0.525731f}, {-0.955423f, -0.295242f, 0.000000f},
+{-0.951056f, -0.162460f, 0.262866f}, {-0.864188f, 0.442863f, -0.238856f},
+{-0.951056f, 0.162460f, -0.262866f}, {-0.809017f, 0.309017f, -0.500000f},
+{-0.864188f, -0.442863f, -0.238856f}, {-0.951056f, -0.162460f, -0.262866f},
+{-0.809017f, -0.309017f, -0.500000f}, {-0.681718f, 0.147621f, -0.716567f},
+{-0.681718f, -0.147621f, -0.716567f}, {-0.850651f, 0.000000f, -0.525731f},
+{-0.688191f, 0.587785f, -0.425325f}, {-0.587785f, 0.425325f, -0.688191f},
+{-0.425325f, 0.688191f, -0.587785f}, {-0.425325f, -0.688191f, -0.587785f},
+{-0.587785f, -0.425325f, -0.688191f}, {-0.688191f, -0.587785f, -0.425325f}
+};
+
+//==============================================================
+
+int Q_rand( int *seed ) {
+ *seed = (69069 * *seed + 1);
+ return *seed;
+}
+
+float Q_random( int *seed ) {
+ return ( Q_rand( seed ) & 0xffff ) / (float)0x10000;
+}
+
+float Q_crandom( int *seed ) {
+ return 2.0 * ( Q_random( seed ) - 0.5 );
+}
+
+#ifdef __LCC__
+
+int VectorCompare( const vec3_t v1, const vec3_t v2 ) {
+ if (v1[0] != v2[0] || v1[1] != v2[1] || v1[2] != v2[2]) {
+ return 0;
+ }
+ return 1;
+}
+
+vec_t VectorLength( const vec3_t v ) {
+ return (vec_t)sqrt (v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
+}
+
+vec_t VectorLengthSquared( const vec3_t v ) {
+ return (v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
+}
+
+vec_t Distance( const vec3_t p1, const vec3_t p2 ) {
+ vec3_t v;
+
+ VectorSubtract (p2, p1, v);
+ return VectorLength( v );
+}
+
+vec_t DistanceSquared( const vec3_t p1, const vec3_t p2 ) {
+ vec3_t v;
+
+ VectorSubtract (p2, p1, v);
+ return v[0]*v[0] + v[1]*v[1] + v[2]*v[2];
+}
+
+// fast vector normalize routine that does not check to make sure
+// that length != 0, nor does it return length, uses rsqrt approximation
+void VectorNormalizeFast( vec3_t v )
+{
+ float ilength;
+
+ ilength = Q_rsqrt( DotProduct( v, v ) );
+
+ v[0] *= ilength;
+ v[1] *= ilength;
+ v[2] *= ilength;
+}
+
+void VectorInverse( vec3_t v ){
+ v[0] = -v[0];
+ v[1] = -v[1];
+ v[2] = -v[2];
+}
+
+void CrossProduct( const vec3_t v1, const vec3_t v2, vec3_t cross ) {
+ cross[0] = v1[1]*v2[2] - v1[2]*v2[1];
+ cross[1] = v1[2]*v2[0] - v1[0]*v2[2];
+ cross[2] = v1[0]*v2[1] - v1[1]*v2[0];
+}
+#endif
+
+//=======================================================
+
+signed char ClampChar( int i ) {
+ if ( i < -128 ) {
+ return -128;
+ }
+ if ( i > 127 ) {
+ return 127;
+ }
+ return i;
+}
+
+signed short ClampShort( int i ) {
+ if ( i < -32768 ) {
+ return -32768;
+ }
+ if ( i > 0x7fff ) {
+ return 0x7fff;
+ }
+ return i;
+}
+
+
+// this isn't a real cheap function to call!
+int DirToByte( vec3_t dir ) {
+ int i, best;
+ float d, bestd;
+
+ if ( !dir ) {
+ return 0;
+ }
+
+ bestd = 0;
+ best = 0;
+ for (i=0 ; i<NUMVERTEXNORMALS ; i++)
+ {
+ d = DotProduct (dir, bytedirs[i]);
+ if (d > bestd)
+ {
+ bestd = d;
+ best = i;
+ }
+ }
+
+ return best;
+}
+
+void ByteToDir( int b, vec3_t dir ) {
+ if ( b < 0 || b >= NUMVERTEXNORMALS ) {
+ VectorCopy( vec3_origin, dir );
+ return;
+ }
+ VectorCopy (bytedirs[b], dir);
+}
+
+
+unsigned ColorBytes3 (float r, float g, float b) {
+ unsigned i;
+
+ ( (byte *)&i )[0] = r * 255;
+ ( (byte *)&i )[1] = g * 255;
+ ( (byte *)&i )[2] = b * 255;
+
+ return i;
+}
+
+unsigned ColorBytes4 (float r, float g, float b, float a) {
+ unsigned i;
+
+ ( (byte *)&i )[0] = r * 255;
+ ( (byte *)&i )[1] = g * 255;
+ ( (byte *)&i )[2] = b * 255;
+ ( (byte *)&i )[3] = a * 255;
+
+ return i;
+}
+
+float NormalizeColor( const vec3_t in, vec3_t out ) {
+ float max;
+
+ max = in[0];
+ if ( in[1] > max ) {
+ max = in[1];
+ }
+ if ( in[2] > max ) {
+ max = in[2];
+ }
+
+ if ( !max ) {
+ VectorClear( out );
+ } else {
+ out[0] = in[0] / max;
+ out[1] = in[1] / max;
+ out[2] = in[2] / max;
+ }
+ return max;
+}
+
+
+/*
+=====================
+PlaneFromPoints
+
+Returns false if the triangle is degenrate.
+The normal will point out of the clock for clockwise ordered points
+=====================
+*/
+qboolean PlaneFromPoints( vec4_t plane, const vec3_t a, const vec3_t b, const vec3_t c ) {
+ vec3_t d1, d2;
+
+ VectorSubtract( b, a, d1 );
+ VectorSubtract( c, a, d2 );
+ CrossProduct( d2, d1, plane );
+ if ( VectorNormalize( plane ) == 0 ) {
+ return qfalse;
+ }
+
+ plane[3] = DotProduct( a, plane );
+ return qtrue;
+}
+
+/*
+===============
+RotatePointAroundVector
+
+This is not implemented very well...
+===============
+*/
+void RotatePointAroundVector( vec3_t dst, const vec3_t dir, const vec3_t point,
+ float degrees ) {
+ float m[3][3];
+ float im[3][3];
+ float zrot[3][3];
+ float tmpmat[3][3];
+ float rot[3][3];
+ int i;
+ vec3_t vr, vup, vf;
+ float rad;
+
+ vf[0] = dir[0];
+ vf[1] = dir[1];
+ vf[2] = dir[2];
+
+ PerpendicularVector( vr, dir );
+ CrossProduct( vr, vf, vup );
+
+ m[0][0] = vr[0];
+ m[1][0] = vr[1];
+ m[2][0] = vr[2];
+
+ m[0][1] = vup[0];
+ m[1][1] = vup[1];
+ m[2][1] = vup[2];
+
+ m[0][2] = vf[0];
+ m[1][2] = vf[1];
+ m[2][2] = vf[2];
+
+ memcpy( im, m, sizeof( im ) );
+
+ im[0][1] = m[1][0];
+ im[0][2] = m[2][0];
+ im[1][0] = m[0][1];
+ im[1][2] = m[2][1];
+ im[2][0] = m[0][2];
+ im[2][1] = m[1][2];
+
+ memset( zrot, 0, sizeof( zrot ) );
+ zrot[0][0] = zrot[1][1] = zrot[2][2] = 1.0F;
+
+ rad = DEG2RAD( degrees );
+ zrot[0][0] = cos( rad );
+ zrot[0][1] = sin( rad );
+ zrot[1][0] = -sin( rad );
+ zrot[1][1] = cos( rad );
+
+ MatrixMultiply( m, zrot, tmpmat );
+ MatrixMultiply( tmpmat, im, rot );
+
+ for ( i = 0; i < 3; i++ ) {
+ dst[i] = rot[i][0] * point[0] + rot[i][1] * point[1] + rot[i][2] * point[2];
+ }
+}
+
+/*
+===============
+RotateAroundDirection
+===============
+*/
+void RotateAroundDirection( vec3_t axis[3], float yaw ) {
+
+ // create an arbitrary axis[1]
+ PerpendicularVector( axis[1], axis[0] );
+
+ // rotate it around axis[0] by yaw
+ if ( yaw ) {
+ vec3_t temp;
+
+ VectorCopy( axis[1], temp );
+ RotatePointAroundVector( axis[1], axis[0], temp, yaw );
+ }
+
+ // cross to get axis[2]
+ CrossProduct( axis[0], axis[1], axis[2] );
+}
+
+
+
+void vectoangles( const vec3_t value1, vec3_t angles ) {
+ float forward;
+ float yaw, pitch;
+
+ if ( value1[1] == 0 && value1[0] == 0 ) {
+ yaw = 0;
+ if ( value1[2] > 0 ) {
+ pitch = 90;
+ }
+ else {
+ pitch = 270;
+ }
+ }
+ else {
+ if ( value1[0] ) {
+ yaw = ( atan2 ( value1[1], value1[0] ) * 180 / M_PI );
+ }
+ else if ( value1[1] > 0 ) {
+ yaw = 90;
+ }
+ else {
+ yaw = 270;
+ }
+ if ( yaw < 0 ) {
+ yaw += 360;
+ }
+
+ forward = sqrt ( value1[0]*value1[0] + value1[1]*value1[1] );
+ pitch = ( atan2(value1[2], forward) * 180 / M_PI );
+ if ( pitch < 0 ) {
+ pitch += 360;
+ }
+ }
+
+ angles[PITCH] = -pitch;
+ angles[YAW] = yaw;
+ angles[ROLL] = 0;
+}
+
+
+/*
+=================
+AnglesToAxis
+=================
+*/
+void AnglesToAxis( const vec3_t angles, vec3_t axis[3] ) {
+ vec3_t right;
+
+ // angle vectors returns "right" instead of "y axis"
+ AngleVectors( angles, axis[0], right, axis[2] );
+ VectorSubtract( vec3_origin, right, axis[1] );
+}
+
+void AxisClear( vec3_t axis[3] ) {
+ axis[0][0] = 1;
+ axis[0][1] = 0;
+ axis[0][2] = 0;
+ axis[1][0] = 0;
+ axis[1][1] = 1;
+ axis[1][2] = 0;
+ axis[2][0] = 0;
+ axis[2][1] = 0;
+ axis[2][2] = 1;
+}
+
+void AxisCopy( vec3_t in[3], vec3_t out[3] ) {
+ VectorCopy( in[0], out[0] );
+ VectorCopy( in[1], out[1] );
+ VectorCopy( in[2], out[2] );
+}
+
+void ProjectPointOnPlane( vec3_t dst, const vec3_t p, const vec3_t normal )
+{
+ float d;
+ vec3_t n;
+ float inv_denom;
+
+ inv_denom = DotProduct( normal, normal );
+#ifndef Q3_VM
+ assert( Q_fabs(inv_denom) != 0.0f ); // bk010122 - zero vectors get here
+#endif
+ inv_denom = 1.0f / inv_denom;
+
+ d = DotProduct( normal, p ) * inv_denom;
+
+ n[0] = normal[0] * inv_denom;
+ n[1] = normal[1] * inv_denom;
+ n[2] = normal[2] * inv_denom;
+
+ dst[0] = p[0] - d * n[0];
+ dst[1] = p[1] - d * n[1];
+ dst[2] = p[2] - d * n[2];
+}
+
+/*
+================
+MakeNormalVectors
+
+Given a normalized forward vector, create two
+other perpendicular vectors
+================
+*/
+void MakeNormalVectors( const vec3_t forward, vec3_t right, vec3_t up) {
+ float d;
+
+ // this rotate and negate guarantees a vector
+ // not colinear with the original
+ right[1] = -forward[0];
+ right[2] = forward[1];
+ right[0] = forward[2];
+
+ d = DotProduct (right, forward);
+ VectorMA (right, -d, forward, right);
+ VectorNormalize (right);
+ CrossProduct (right, forward, up);
+}
+
+
+void VectorRotate( vec3_t in, vec3_t matrix[3], vec3_t out )
+{
+ out[0] = DotProduct( in, matrix[0] );
+ out[1] = DotProduct( in, matrix[1] );
+ out[2] = DotProduct( in, matrix[2] );
+}
+
+//============================================================================
+
+#if !idppc
+/*
+** float q_rsqrt( float number )
+*/
+float Q_rsqrt( float number )
+{
+ long i;
+ float x2, y;
+ const float threehalfs = 1.5F;
+
+ x2 = number * 0.5F;
+ y = number;
+ i = * ( long * ) &y; // evil floating point bit level hacking
+ i = 0x5f3759df - ( i >> 1 ); // what the fuck?
+ y = * ( float * ) &i;
+ y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
+// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
+
+#ifndef Q3_VM
+#ifdef __linux__
+ assert( !isnan(y) ); // bk010122 - FPE?
+#endif
+#endif
+ return y;
+}
+
+float Q_fabs( float f ) {
+ int tmp = * ( int * ) &f;
+ tmp &= 0x7FFFFFFF;
+ return * ( float * ) &tmp;
+}
+#endif
+
+//============================================================
+
+/*
+===============
+LerpAngle
+
+===============
+*/
+float LerpAngle (float from, float to, float frac) {
+ float a;
+
+ if ( to - from > 180 ) {
+ to -= 360;
+ }
+ if ( to - from < -180 ) {
+ to += 360;
+ }
+ a = from + frac * (to - from);
+
+ return a;
+}
+
+
+/*
+=================
+AngleSubtract
+
+Always returns a value from -180 to 180
+=================
+*/
+float AngleSubtract( float a1, float a2 ) {
+ float a;
+
+ a = a1 - a2;
+ while ( a > 180 ) {
+ a -= 360;
+ }
+ while ( a < -180 ) {
+ a += 360;
+ }
+ return a;
+}
+
+
+void AnglesSubtract( vec3_t v1, vec3_t v2, vec3_t v3 ) {
+ v3[0] = AngleSubtract( v1[0], v2[0] );
+ v3[1] = AngleSubtract( v1[1], v2[1] );
+ v3[2] = AngleSubtract( v1[2], v2[2] );
+}
+
+
+float AngleMod(float a) {
+ a = (360.0/65536) * ((int)(a*(65536/360.0)) & 65535);
+ return a;
+}
+
+
+/*
+=================
+AngleNormalize360
+
+returns angle normalized to the range [0 <= angle < 360]
+=================
+*/
+float AngleNormalize360 ( float angle ) {
+ return (360.0 / 65536) * ((int)(angle * (65536 / 360.0)) & 65535);
+}
+
+
+/*
+=================
+AngleNormalize180
+
+returns angle normalized to the range [-180 < angle <= 180]
+=================
+*/
+float AngleNormalize180 ( float angle ) {
+ angle = AngleNormalize360( angle );
+ if ( angle > 180.0 ) {
+ angle -= 360.0;
+ }
+ return angle;
+}
+
+
+/*
+=================
+AngleDelta
+
+returns the normalized delta from angle1 to angle2
+=================
+*/
+float AngleDelta ( float angle1, float angle2 ) {
+ return AngleNormalize180( angle1 - angle2 );
+}
+
+
+//============================================================
+
+
+/*
+=================
+SetPlaneSignbits
+=================
+*/
+void SetPlaneSignbits (cplane_t *out) {
+ int bits, j;
+
+ // for fast box on planeside test
+ bits = 0;
+ for (j=0 ; j<3 ; j++) {
+ if (out->normal[j] < 0) {
+ bits |= 1<<j;
+ }
+ }
+ out->signbits = bits;
+}
+
+
+/*
+==================
+BoxOnPlaneSide
+
+Returns 1, 2, or 1 + 2
+
+// this is the slow, general version
+int BoxOnPlaneSide2 (vec3_t emins, vec3_t emaxs, struct cplane_s *p)
+{
+ int i;
+ float dist1, dist2;
+ int sides;
+ vec3_t corners[2];
+
+ for (i=0 ; i<3 ; i++)
+ {
+ if (p->normal[i] < 0)
+ {
+ corners[0][i] = emins[i];
+ corners[1][i] = emaxs[i];
+ }
+ else
+ {
+ corners[1][i] = emins[i];
+ corners[0][i] = emaxs[i];
+ }
+ }
+ dist1 = DotProduct (p->normal, corners[0]) - p->dist;
+ dist2 = DotProduct (p->normal, corners[1]) - p->dist;
+ sides = 0;
+ if (dist1 >= 0)
+ sides = 1;
+ if (dist2 < 0)
+ sides |= 2;
+
+ return sides;
+}
+
+==================
+*/
+
+#if !( (defined __linux__ || __FreeBSD__) && (defined __i386__) && (!defined C_ONLY)) // rb010123
+
+#if defined __LCC__ || defined C_ONLY || !id386 || defined __VECTORC
+
+int BoxOnPlaneSide (vec3_t emins, vec3_t emaxs, struct cplane_s *p)
+{
+ float dist1, dist2;
+ int sides;
+
+// fast axial cases
+ if (p->type < 3)
+ {
+ if (p->dist <= emins[p->type])
+ return 1;
+ if (p->dist >= emaxs[p->type])
+ return 2;
+ return 3;
+ }
+
+// general case
+ switch (p->signbits)
+ {
+ case 0:
+ dist1 = p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2];
+ dist2 = p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2];
+ break;
+ case 1:
+ dist1 = p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2];
+ dist2 = p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2];
+ break;
+ case 2:
+ dist1 = p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2];
+ dist2 = p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2];
+ break;
+ case 3:
+ dist1 = p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2];
+ dist2 = p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2];
+ break;
+ case 4:
+ dist1 = p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2];
+ dist2 = p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2];
+ break;
+ case 5:
+ dist1 = p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2];
+ dist2 = p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2];
+ break;
+ case 6:
+ dist1 = p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2];
+ dist2 = p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2];
+ break;
+ case 7:
+ dist1 = p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2];
+ dist2 = p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2];
+ break;
+ default:
+ dist1 = dist2 = 0; // shut up compiler
+ break;
+ }
+
+ sides = 0;
+ if (dist1 >= p->dist)
+ sides = 1;
+ if (dist2 < p->dist)
+ sides |= 2;
+
+ return sides;
+}
+#else
+#pragma warning( disable: 4035 )
+
+__declspec( naked ) int BoxOnPlaneSide (vec3_t emins, vec3_t emaxs, struct cplane_s *p)
+{
+ static int bops_initialized;
+ static int Ljmptab[8];
+
+ __asm {
+
+ push ebx
+
+ cmp bops_initialized, 1
+ je initialized
+ mov bops_initialized, 1
+
+ mov Ljmptab[0*4], offset Lcase0
+ mov Ljmptab[1*4], offset Lcase1
+ mov Ljmptab[2*4], offset Lcase2
+ mov Ljmptab[3*4], offset Lcase3
+ mov Ljmptab[4*4], offset Lcase4
+ mov Ljmptab[5*4], offset Lcase5
+ mov Ljmptab[6*4], offset Lcase6
+ mov Ljmptab[7*4], offset Lcase7
+
+initialized:
+
+ mov edx,dword ptr[4+12+esp]
+ mov ecx,dword ptr[4+4+esp]
+ xor eax,eax
+ mov ebx,dword ptr[4+8+esp]
+ mov al,byte ptr[17+edx]
+ cmp al,8
+ jge Lerror
+ fld dword ptr[0+edx]
+ fld st(0)
+ jmp dword ptr[Ljmptab+eax*4]
+Lcase0:
+ fmul dword ptr[ebx]
+ fld dword ptr[0+4+edx]
+ fxch st(2)
+ fmul dword ptr[ecx]
+ fxch st(2)
+ fld st(0)
+ fmul dword ptr[4+ebx]
+ fld dword ptr[0+8+edx]
+ fxch st(2)
+ fmul dword ptr[4+ecx]
+ fxch st(2)
+ fld st(0)
+ fmul dword ptr[8+ebx]
+ fxch st(5)
+ faddp st(3),st(0)
+ fmul dword ptr[8+ecx]
+ fxch st(1)
+ faddp st(3),st(0)
+ fxch st(3)
+ faddp st(2),st(0)
+ jmp LSetSides
+Lcase1:
+ fmul dword ptr[ecx]
+ fld dword ptr[0+4+edx]
+ fxch st(2)
+ fmul dword ptr[ebx]
+ fxch st(2)
+ fld st(0)
+ fmul dword ptr[4+ebx]
+ fld dword ptr[0+8+edx]
+ fxch st(2)
+ fmul dword ptr[4+ecx]
+ fxch st(2)
+ fld st(0)
+ fmul dword ptr[8+ebx]
+ fxch st(5)
+ faddp st(3),st(0)
+ fmul dword ptr[8+ecx]
+ fxch st(1)
+ faddp st(3),st(0)
+ fxch st(3)
+ faddp st(2),st(0)
+ jmp LSetSides
+Lcase2:
+ fmul dword ptr[ebx]
+ fld dword ptr[0+4+edx]
+ fxch st(2)
+ fmul dword ptr[ecx]
+ fxch st(2)
+ fld st(0)
+ fmul dword ptr[4+ecx]
+ fld dword ptr[0+8+edx]
+ fxch st(2)
+ fmul dword ptr[4+ebx]
+ fxch st(2)
+ fld st(0)
+ fmul dword ptr[8+ebx]
+ fxch st(5)
+ faddp st(3),st(0)
+ fmul dword ptr[8+ecx]
+ fxch st(1)
+ faddp st(3),st(0)
+ fxch st(3)
+ faddp st(2),st(0)
+ jmp LSetSides
+Lcase3:
+ fmul dword ptr[ecx]
+ fld dword ptr[0+4+edx]
+ fxch st(2)
+ fmul dword ptr[ebx]
+ fxch st(2)
+ fld st(0)
+ fmul dword ptr[4+ecx]
+ fld dword ptr[0+8+edx]
+ fxch st(2)
+ fmul dword ptr[4+ebx]
+ fxch st(2)
+ fld st(0)
+ fmul dword ptr[8+ebx]
+ fxch st(5)
+ faddp st(3),st(0)
+ fmul dword ptr[8+ecx]
+ fxch st(1)
+ faddp st(3),st(0)
+ fxch st(3)
+ faddp st(2),st(0)
+ jmp LSetSides
+Lcase4:
+ fmul dword ptr[ebx]
+ fld dword ptr[0+4+edx]
+ fxch st(2)
+ fmul dword ptr[ecx]
+ fxch st(2)
+ fld st(0)
+ fmul dword ptr[4+ebx]
+ fld dword ptr[0+8+edx]
+ fxch st(2)
+ fmul dword ptr[4+ecx]
+ fxch st(2)
+ fld st(0)
+ fmul dword ptr[8+ecx]
+ fxch st(5)
+ faddp st(3),st(0)
+ fmul dword ptr[8+ebx]
+ fxch st(1)
+ faddp st(3),st(0)
+ fxch st(3)
+ faddp st(2),st(0)
+ jmp LSetSides
+Lcase5:
+ fmul dword ptr[ecx]
+ fld dword ptr[0+4+edx]
+ fxch st(2)
+ fmul dword ptr[ebx]
+ fxch st(2)
+ fld st(0)
+ fmul dword ptr[4+ebx]
+ fld dword ptr[0+8+edx]
+ fxch st(2)
+ fmul dword ptr[4+ecx]
+ fxch st(2)
+ fld st(0)
+ fmul dword ptr[8+ecx]
+ fxch st(5)
+ faddp st(3),st(0)
+ fmul dword ptr[8+ebx]
+ fxch st(1)
+ faddp st(3),st(0)
+ fxch st(3)
+ faddp st(2),st(0)
+ jmp LSetSides
+Lcase6:
+ fmul dword ptr[ebx]
+ fld dword ptr[0+4+edx]
+ fxch st(2)
+ fmul dword ptr[ecx]
+ fxch st(2)
+ fld st(0)
+ fmul dword ptr[4+ecx]
+ fld dword ptr[0+8+edx]
+ fxch st(2)
+ fmul dword ptr[4+ebx]
+ fxch st(2)
+ fld st(0)
+ fmul dword ptr[8+ecx]
+ fxch st(5)
+ faddp st(3),st(0)
+ fmul dword ptr[8+ebx]
+ fxch st(1)
+ faddp st(3),st(0)
+ fxch st(3)
+ faddp st(2),st(0)
+ jmp LSetSides
+Lcase7:
+ fmul dword ptr[ecx]
+ fld dword ptr[0+4+edx]
+ fxch st(2)
+ fmul dword ptr[ebx]
+ fxch st(2)
+ fld st(0)
+ fmul dword ptr[4+ecx]
+ fld dword ptr[0+8+edx]
+ fxch st(2)
+ fmul dword ptr[4+ebx]
+ fxch st(2)
+ fld st(0)
+ fmul dword ptr[8+ecx]
+ fxch st(5)
+ faddp st(3),st(0)
+ fmul dword ptr[8+ebx]
+ fxch st(1)
+ faddp st(3),st(0)
+ fxch st(3)
+ faddp st(2),st(0)
+LSetSides:
+ faddp st(2),st(0)
+ fcomp dword ptr[12+edx]
+ xor ecx,ecx
+ fnstsw ax
+ fcomp dword ptr[12+edx]
+ and ah,1
+ xor ah,1
+ add cl,ah
+ fnstsw ax
+ and ah,1
+ add ah,ah
+ add cl,ah
+ pop ebx
+ mov eax,ecx
+ ret
+Lerror:
+ int 3
+ }
+}
+#pragma warning( default: 4035 )
+
+#endif
+#endif
+
+/*
+=================
+RadiusFromBounds
+=================
+*/
+float RadiusFromBounds( const vec3_t mins, const vec3_t maxs ) {
+ int i;
+ vec3_t corner;
+ float a, b;
+
+ for (i=0 ; i<3 ; i++) {
+ a = fabs( mins[i] );
+ b = fabs( maxs[i] );
+ corner[i] = a > b ? a : b;
+ }
+
+ return VectorLength (corner);
+}
+
+
+void ClearBounds( vec3_t mins, vec3_t maxs ) {
+ mins[0] = mins[1] = mins[2] = 99999;
+ maxs[0] = maxs[1] = maxs[2] = -99999;
+}
+
+void AddPointToBounds( const vec3_t v, vec3_t mins, vec3_t maxs ) {
+ if ( v[0] < mins[0] ) {
+ mins[0] = v[0];
+ }
+ if ( v[0] > maxs[0]) {
+ maxs[0] = v[0];
+ }
+
+ if ( v[1] < mins[1] ) {
+ mins[1] = v[1];
+ }
+ if ( v[1] > maxs[1]) {
+ maxs[1] = v[1];
+ }
+
+ if ( v[2] < mins[2] ) {
+ mins[2] = v[2];
+ }
+ if ( v[2] > maxs[2]) {
+ maxs[2] = v[2];
+ }
+}
+
+
+vec_t VectorNormalize( vec3_t v ) {
+ // NOTE: TTimo - Apple G4 altivec source uses double?
+ float length, ilength;
+
+ length = v[0]*v[0] + v[1]*v[1] + v[2]*v[2];
+ length = sqrt (length);
+
+ if ( length ) {
+ ilength = 1/length;
+ v[0] *= ilength;
+ v[1] *= ilength;
+ v[2] *= ilength;
+ }
+
+ return length;
+}
+
+vec_t VectorNormalize2( const vec3_t v, vec3_t out) {
+ float length, ilength;
+
+ length = v[0]*v[0] + v[1]*v[1] + v[2]*v[2];
+ length = sqrt (length);
+
+ if (length)
+ {
+#ifndef Q3_VM // bk0101022 - FPE related
+// assert( ((Q_fabs(v[0])!=0.0f) || (Q_fabs(v[1])!=0.0f) || (Q_fabs(v[2])!=0.0f)) );
+#endif
+ ilength = 1/length;
+ out[0] = v[0]*ilength;
+ out[1] = v[1]*ilength;
+ out[2] = v[2]*ilength;
+ } else {
+#ifndef Q3_VM // bk0101022 - FPE related
+// assert( ((Q_fabs(v[0])==0.0f) && (Q_fabs(v[1])==0.0f) && (Q_fabs(v[2])==0.0f)) );
+#endif
+ VectorClear( out );
+ }
+
+ return length;
+
+}
+
+void _VectorMA( const vec3_t veca, float scale, const vec3_t vecb, vec3_t vecc) {
+ vecc[0] = veca[0] + scale*vecb[0];
+ vecc[1] = veca[1] + scale*vecb[1];
+ vecc[2] = veca[2] + scale*vecb[2];
+}
+
+
+vec_t _DotProduct( const vec3_t v1, const vec3_t v2 ) {
+ return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2];
+}
+
+void _VectorSubtract( const vec3_t veca, const vec3_t vecb, vec3_t out ) {
+ out[0] = veca[0]-vecb[0];
+ out[1] = veca[1]-vecb[1];
+ out[2] = veca[2]-vecb[2];
+}
+
+void _VectorAdd( const vec3_t veca, const vec3_t vecb, vec3_t out ) {
+ out[0] = veca[0]+vecb[0];
+ out[1] = veca[1]+vecb[1];
+ out[2] = veca[2]+vecb[2];
+}
+
+void _VectorCopy( const vec3_t in, vec3_t out ) {
+ out[0] = in[0];
+ out[1] = in[1];
+ out[2] = in[2];
+}
+
+void _VectorScale( const vec3_t in, vec_t scale, vec3_t out ) {
+ out[0] = in[0]*scale;
+ out[1] = in[1]*scale;
+ out[2] = in[2]*scale;
+}
+
+void Vector4Scale( const vec4_t in, vec_t scale, vec4_t out ) {
+ out[0] = in[0]*scale;
+ out[1] = in[1]*scale;
+ out[2] = in[2]*scale;
+ out[3] = in[3]*scale;
+}
+
+
+int Q_log2( int val ) {
+ int answer;
+
+ answer = 0;
+ while ( ( val>>=1 ) != 0 ) {
+ answer++;
+ }
+ return answer;
+}
+
+
+
+/*
+=================
+PlaneTypeForNormal
+=================
+*/
+/*
+int PlaneTypeForNormal (vec3_t normal) {
+ if ( normal[0] == 1.0 )
+ return PLANE_X;
+ if ( normal[1] == 1.0 )
+ return PLANE_Y;
+ if ( normal[2] == 1.0 )
+ return PLANE_Z;
+
+ return PLANE_NON_AXIAL;
+}
+*/
+
+
+/*
+================
+MatrixMultiply
+================
+*/
+void MatrixMultiply(float in1[3][3], float in2[3][3], float out[3][3]) {
+ out[0][0] = in1[0][0] * in2[0][0] + in1[0][1] * in2[1][0] +
+ in1[0][2] * in2[2][0];
+ out[0][1] = in1[0][0] * in2[0][1] + in1[0][1] * in2[1][1] +
+ in1[0][2] * in2[2][1];
+ out[0][2] = in1[0][0] * in2[0][2] + in1[0][1] * in2[1][2] +
+ in1[0][2] * in2[2][2];
+ out[1][0] = in1[1][0] * in2[0][0] + in1[1][1] * in2[1][0] +
+ in1[1][2] * in2[2][0];
+ out[1][1] = in1[1][0] * in2[0][1] + in1[1][1] * in2[1][1] +
+ in1[1][2] * in2[2][1];
+ out[1][2] = in1[1][0] * in2[0][2] + in1[1][1] * in2[1][2] +
+ in1[1][2] * in2[2][2];
+ out[2][0] = in1[2][0] * in2[0][0] + in1[2][1] * in2[1][0] +
+ in1[2][2] * in2[2][0];
+ out[2][1] = in1[2][0] * in2[0][1] + in1[2][1] * in2[1][1] +
+ in1[2][2] * in2[2][1];
+ out[2][2] = in1[2][0] * in2[0][2] + in1[2][1] * in2[1][2] +
+ in1[2][2] * in2[2][2];
+}
+
+
+void AngleVectors( const vec3_t angles, vec3_t forward, vec3_t right, vec3_t up) {
+ float angle;
+ static float sr, sp, sy, cr, cp, cy;
+ // static to help MS compiler fp bugs
+
+ angle = angles[YAW] * (M_PI*2 / 360);
+ sy = sin(angle);
+ cy = cos(angle);
+ angle = angles[PITCH] * (M_PI*2 / 360);
+ sp = sin(angle);
+ cp = cos(angle);
+ angle = angles[ROLL] * (M_PI*2 / 360);
+ sr = sin(angle);
+ cr = cos(angle);
+
+ if (forward)
+ {
+ forward[0] = cp*cy;
+ forward[1] = cp*sy;
+ forward[2] = -sp;
+ }
+ if (right)
+ {
+ right[0] = (-1*sr*sp*cy+-1*cr*-sy);
+ right[1] = (-1*sr*sp*sy+-1*cr*cy);
+ right[2] = -1*sr*cp;
+ }
+ if (up)
+ {
+ up[0] = (cr*sp*cy+-sr*-sy);
+ up[1] = (cr*sp*sy+-sr*cy);
+ up[2] = cr*cp;
+ }
+}
+
+/*
+** assumes "src" is normalized
+*/
+void PerpendicularVector( vec3_t dst, const vec3_t src )
+{
+ int pos;
+ int i;
+ float minelem = 1.0F;
+ vec3_t tempvec;
+
+ /*
+ ** find the smallest magnitude axially aligned vector
+ */
+ for ( pos = 0, i = 0; i < 3; i++ )
+ {
+ if ( fabs( src[i] ) < minelem )
+ {
+ pos = i;
+ minelem = fabs( src[i] );
+ }
+ }
+ tempvec[0] = tempvec[1] = tempvec[2] = 0.0F;
+ tempvec[pos] = 1.0F;
+
+ /*
+ ** project the point onto the plane defined by src
+ */
+ ProjectPointOnPlane( dst, tempvec, src );
+
+ /*
+ ** normalize the result
+ */
+ VectorNormalize( dst );
+}
+
+
diff --git a/code/game/q_shared.c b/code/game/q_shared.c
new file mode 100755
index 0000000..9c06995
--- /dev/null
+++ b/code/game/q_shared.c
@@ -0,0 +1,1258 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// q_shared.c -- stateless support routines that are included in each code dll
+#include "q_shared.h"
+
+float Com_Clamp( float min, float max, float value ) {
+ if ( value < min ) {
+ return min;
+ }
+ if ( value > max ) {
+ return max;
+ }
+ return value;
+}
+
+
+/*
+============
+COM_SkipPath
+============
+*/
+char *COM_SkipPath (char *pathname)
+{
+ char *last;
+
+ last = pathname;
+ while (*pathname)
+ {
+ if (*pathname=='/')
+ last = pathname+1;
+ pathname++;
+ }
+ return last;
+}
+
+/*
+============
+COM_StripExtension
+============
+*/
+void COM_StripExtension( const char *in, char *out ) {
+ while ( *in && *in != '.' ) {
+ *out++ = *in++;
+ }
+ *out = 0;
+}
+
+
+/*
+==================
+COM_DefaultExtension
+==================
+*/
+void COM_DefaultExtension (char *path, int maxSize, const char *extension ) {
+ char oldPath[MAX_QPATH];
+ char *src;
+
+//
+// if path doesn't have a .EXT, append extension
+// (extension should include the .)
+//
+ src = path + strlen(path) - 1;
+
+ while (*src != '/' && src != path) {
+ if ( *src == '.' ) {
+ return; // it has an extension
+ }
+ src--;
+ }
+
+ Q_strncpyz( oldPath, path, sizeof( oldPath ) );
+ Com_sprintf( path, maxSize, "%s%s", oldPath, extension );
+}
+
+/*
+============================================================================
+
+ BYTE ORDER FUNCTIONS
+
+============================================================================
+*/
+/*
+// can't just use function pointers, or dll linkage can
+// mess up when qcommon is included in multiple places
+static short (*_BigShort) (short l);
+static short (*_LittleShort) (short l);
+static int (*_BigLong) (int l);
+static int (*_LittleLong) (int l);
+static qint64 (*_BigLong64) (qint64 l);
+static qint64 (*_LittleLong64) (qint64 l);
+static float (*_BigFloat) (const float *l);
+static float (*_LittleFloat) (const float *l);
+
+short BigShort(short l){return _BigShort(l);}
+short LittleShort(short l) {return _LittleShort(l);}
+int BigLong (int l) {return _BigLong(l);}
+int LittleLong (int l) {return _LittleLong(l);}
+qint64 BigLong64 (qint64 l) {return _BigLong64(l);}
+qint64 LittleLong64 (qint64 l) {return _LittleLong64(l);}
+float BigFloat (const float *l) {return _BigFloat(l);}
+float LittleFloat (const float *l) {return _LittleFloat(l);}
+*/
+
+short ShortSwap (short l)
+{
+ byte b1,b2;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+
+ return (b1<<8) + b2;
+}
+
+short ShortNoSwap (short l)
+{
+ return l;
+}
+
+int LongSwap (int l)
+{
+ byte b1,b2,b3,b4;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+ b3 = (l>>16)&255;
+ b4 = (l>>24)&255;
+
+ return ((int)b1<<24) + ((int)b2<<16) + ((int)b3<<8) + b4;
+}
+
+int LongNoSwap (int l)
+{
+ return l;
+}
+
+qint64 Long64Swap (qint64 ll)
+{
+ qint64 result;
+
+ result.b0 = ll.b7;
+ result.b1 = ll.b6;
+ result.b2 = ll.b5;
+ result.b3 = ll.b4;
+ result.b4 = ll.b3;
+ result.b5 = ll.b2;
+ result.b6 = ll.b1;
+ result.b7 = ll.b0;
+
+ return result;
+}
+
+qint64 Long64NoSwap (qint64 ll)
+{
+ return ll;
+}
+
+typedef union {
+ float f;
+ unsigned int i;
+} _FloatByteUnion;
+
+float FloatSwap (const float *f) {
+ const _FloatByteUnion *in;
+ _FloatByteUnion out;
+
+ in = (_FloatByteUnion *)f;
+ out.i = LongSwap(in->i);
+
+ return out.f;
+}
+
+float FloatNoSwap (const float *f)
+{
+ return *f;
+}
+
+/*
+================
+Swap_Init
+================
+*/
+/*
+void Swap_Init (void)
+{
+ byte swaptest[2] = {1,0};
+
+// set the byte swapping variables in a portable manner
+ if ( *(short *)swaptest == 1)
+ {
+ _BigShort = ShortSwap;
+ _LittleShort = ShortNoSwap;
+ _BigLong = LongSwap;
+ _LittleLong = LongNoSwap;
+ _BigLong64 = Long64Swap;
+ _LittleLong64 = Long64NoSwap;
+ _BigFloat = FloatSwap;
+ _LittleFloat = FloatNoSwap;
+ }
+ else
+ {
+ _BigShort = ShortNoSwap;
+ _LittleShort = ShortSwap;
+ _BigLong = LongNoSwap;
+ _LittleLong = LongSwap;
+ _BigLong64 = Long64NoSwap;
+ _LittleLong64 = Long64Swap;
+ _BigFloat = FloatNoSwap;
+ _LittleFloat = FloatSwap;
+ }
+
+}
+*/
+
+/*
+============================================================================
+
+PARSING
+
+============================================================================
+*/
+
+static char com_token[MAX_TOKEN_CHARS];
+static char com_parsename[MAX_TOKEN_CHARS];
+static int com_lines;
+
+void COM_BeginParseSession( const char *name )
+{
+ com_lines = 0;
+ Com_sprintf(com_parsename, sizeof(com_parsename), "%s", name);
+}
+
+int COM_GetCurrentParseLine( void )
+{
+ return com_lines;
+}
+
+char *COM_Parse( char **data_p )
+{
+ return COM_ParseExt( data_p, qtrue );
+}
+
+void COM_ParseError( char *format, ... )
+{
+ va_list argptr;
+ static char string[4096];
+
+ va_start (argptr, format);
+ vsprintf (string, format, argptr);
+ va_end (argptr);
+
+ Com_Printf("ERROR: %s, line %d: %s\n", com_parsename, com_lines, string);
+}
+
+void COM_ParseWarning( char *format, ... )
+{
+ va_list argptr;
+ static char string[4096];
+
+ va_start (argptr, format);
+ vsprintf (string, format, argptr);
+ va_end (argptr);
+
+ Com_Printf("WARNING: %s, line %d: %s\n", com_parsename, com_lines, string);
+}
+
+/*
+==============
+COM_Parse
+
+Parse a token out of a string
+Will never return NULL, just empty strings
+
+If "allowLineBreaks" is qtrue then an empty
+string will be returned if the next token is
+a newline.
+==============
+*/
+static char *SkipWhitespace( char *data, qboolean *hasNewLines ) {
+ int c;
+
+ while( (c = *data) <= ' ') {
+ if( !c ) {
+ return NULL;
+ }
+ if( c == '\n' ) {
+ com_lines++;
+ *hasNewLines = qtrue;
+ }
+ data++;
+ }
+
+ return data;
+}
+
+int COM_Compress( char *data_p ) {
+ char *in, *out;
+ int c;
+ qboolean newline = qfalse, whitespace = qfalse;
+
+ in = out = data_p;
+ if (in) {
+ while ((c = *in) != 0) {
+ // skip double slash comments
+ if ( c == '/' && in[1] == '/' ) {
+ while (*in && *in != '\n') {
+ in++;
+ }
+ // skip /* */ comments
+ } else if ( c == '/' && in[1] == '*' ) {
+ while ( *in && ( *in != '*' || in[1] != '/' ) )
+ in++;
+ if ( *in )
+ in += 2;
+ // record when we hit a newline
+ } else if ( c == '\n' || c == '\r' ) {
+ newline = qtrue;
+ in++;
+ // record when we hit whitespace
+ } else if ( c == ' ' || c == '\t') {
+ whitespace = qtrue;
+ in++;
+ // an actual token
+ } else {
+ // if we have a pending newline, emit it (and it counts as whitespace)
+ if (newline) {
+ *out++ = '\n';
+ newline = qfalse;
+ whitespace = qfalse;
+ } if (whitespace) {
+ *out++ = ' ';
+ whitespace = qfalse;
+ }
+
+ // copy quoted strings unmolested
+ if (c == '"') {
+ *out++ = c;
+ in++;
+ while (1) {
+ c = *in;
+ if (c && c != '"') {
+ *out++ = c;
+ in++;
+ } else {
+ break;
+ }
+ }
+ if (c == '"') {
+ *out++ = c;
+ in++;
+ }
+ } else {
+ *out = c;
+ out++;
+ in++;
+ }
+ }
+ }
+ }
+ *out = 0;
+ return out - data_p;
+}
+
+char *COM_ParseExt( char **data_p, qboolean allowLineBreaks )
+{
+ int c = 0, len;
+ qboolean hasNewLines = qfalse;
+ char *data;
+
+ data = *data_p;
+ len = 0;
+ com_token[0] = 0;
+
+ // make sure incoming data is valid
+ if ( !data )
+ {
+ *data_p = NULL;
+ return com_token;
+ }
+
+ while ( 1 )
+ {
+ // skip whitespace
+ data = SkipWhitespace( data, &hasNewLines );
+ if ( !data )
+ {
+ *data_p = NULL;
+ return com_token;
+ }
+ if ( hasNewLines && !allowLineBreaks )
+ {
+ *data_p = data;
+ return com_token;
+ }
+
+ c = *data;
+
+ // skip double slash comments
+ if ( c == '/' && data[1] == '/' )
+ {
+ data += 2;
+ while (*data && *data != '\n') {
+ data++;
+ }
+ }
+ // skip /* */ comments
+ else if ( c=='/' && data[1] == '*' )
+ {
+ data += 2;
+ while ( *data && ( *data != '*' || data[1] != '/' ) )
+ {
+ data++;
+ }
+ if ( *data )
+ {
+ data += 2;
+ }
+ }
+ else
+ {
+ break;
+ }
+ }
+
+ // handle quoted strings
+ if (c == '\"')
+ {
+ data++;
+ while (1)
+ {
+ c = *data++;
+ if (c=='\"' || !c)
+ {
+ com_token[len] = 0;
+ *data_p = ( char * ) data;
+ return com_token;
+ }
+ if (len < MAX_TOKEN_CHARS)
+ {
+ com_token[len] = c;
+ len++;
+ }
+ }
+ }
+
+ // parse a regular word
+ do
+ {
+ if (len < MAX_TOKEN_CHARS)
+ {
+ com_token[len] = c;
+ len++;
+ }
+ data++;
+ c = *data;
+ if ( c == '\n' )
+ com_lines++;
+ } while (c>32);
+
+ if (len == MAX_TOKEN_CHARS)
+ {
+// Com_Printf ("Token exceeded %i chars, discarded.\n", MAX_TOKEN_CHARS);
+ len = 0;
+ }
+ com_token[len] = 0;
+
+ *data_p = ( char * ) data;
+ return com_token;
+}
+
+
+#if 0
+// no longer used
+/*
+===============
+COM_ParseInfos
+===============
+*/
+int COM_ParseInfos( char *buf, int max, char infos[][MAX_INFO_STRING] ) {
+ char *token;
+ int count;
+ char key[MAX_TOKEN_CHARS];
+
+ count = 0;
+
+ while ( 1 ) {
+ token = COM_Parse( &buf );
+ if ( !token[0] ) {
+ break;
+ }
+ if ( strcmp( token, "{" ) ) {
+ Com_Printf( "Missing { in info file\n" );
+ break;
+ }
+
+ if ( count == max ) {
+ Com_Printf( "Max infos exceeded\n" );
+ break;
+ }
+
+ infos[count][0] = 0;
+ while ( 1 ) {
+ token = COM_ParseExt( &buf, qtrue );
+ if ( !token[0] ) {
+ Com_Printf( "Unexpected end of info file\n" );
+ break;
+ }
+ if ( !strcmp( token, "}" ) ) {
+ break;
+ }
+ Q_strncpyz( key, token, sizeof( key ) );
+
+ token = COM_ParseExt( &buf, qfalse );
+ if ( !token[0] ) {
+ strcpy( token, "<NULL>" );
+ }
+ Info_SetValueForKey( infos[count], key, token );
+ }
+ count++;
+ }
+
+ return count;
+}
+#endif
+
+
+/*
+==================
+COM_MatchToken
+==================
+*/
+void COM_MatchToken( char **buf_p, char *match ) {
+ char *token;
+
+ token = COM_Parse( buf_p );
+ if ( strcmp( token, match ) ) {
+ Com_Error( ERR_DROP, "MatchToken: %s != %s", token, match );
+ }
+}
+
+
+/*
+=================
+SkipBracedSection
+
+The next token should be an open brace.
+Skips until a matching close brace is found.
+Internal brace depths are properly skipped.
+=================
+*/
+void SkipBracedSection (char **program) {
+ char *token;
+ int depth;
+
+ depth = 0;
+ do {
+ token = COM_ParseExt( program, qtrue );
+ if( token[1] == 0 ) {
+ if( token[0] == '{' ) {
+ depth++;
+ }
+ else if( token[0] == '}' ) {
+ depth--;
+ }
+ }
+ } while( depth && *program );
+}
+
+/*
+=================
+SkipRestOfLine
+=================
+*/
+void SkipRestOfLine ( char **data ) {
+ char *p;
+ int c;
+
+ p = *data;
+ while ( (c = *p++) != 0 ) {
+ if ( c == '\n' ) {
+ com_lines++;
+ break;
+ }
+ }
+
+ *data = p;
+}
+
+
+void Parse1DMatrix (char **buf_p, int x, float *m) {
+ char *token;
+ int i;
+
+ COM_MatchToken( buf_p, "(" );
+
+ for (i = 0 ; i < x ; i++) {
+ token = COM_Parse(buf_p);
+ m[i] = atof(token);
+ }
+
+ COM_MatchToken( buf_p, ")" );
+}
+
+void Parse2DMatrix (char **buf_p, int y, int x, float *m) {
+ int i;
+
+ COM_MatchToken( buf_p, "(" );
+
+ for (i = 0 ; i < y ; i++) {
+ Parse1DMatrix (buf_p, x, m + i * x);
+ }
+
+ COM_MatchToken( buf_p, ")" );
+}
+
+void Parse3DMatrix (char **buf_p, int z, int y, int x, float *m) {
+ int i;
+
+ COM_MatchToken( buf_p, "(" );
+
+ for (i = 0 ; i < z ; i++) {
+ Parse2DMatrix (buf_p, y, x, m + i * x*y);
+ }
+
+ COM_MatchToken( buf_p, ")" );
+}
+
+
+/*
+============================================================================
+
+ LIBRARY REPLACEMENT FUNCTIONS
+
+============================================================================
+*/
+
+int Q_isprint( int c )
+{
+ if ( c >= 0x20 && c <= 0x7E )
+ return ( 1 );
+ return ( 0 );
+}
+
+int Q_islower( int c )
+{
+ if (c >= 'a' && c <= 'z')
+ return ( 1 );
+ return ( 0 );
+}
+
+int Q_isupper( int c )
+{
+ if (c >= 'A' && c <= 'Z')
+ return ( 1 );
+ return ( 0 );
+}
+
+int Q_isalpha( int c )
+{
+ if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
+ return ( 1 );
+ return ( 0 );
+}
+
+char* Q_strrchr( const char* string, int c )
+{
+ char cc = c;
+ char *s;
+ char *sp=(char *)0;
+
+ s = (char*)string;
+
+ while (*s)
+ {
+ if (*s == cc)
+ sp = s;
+ s++;
+ }
+ if (cc == 0)
+ sp = s;
+
+ return sp;
+}
+
+/*
+=============
+Q_strncpyz
+
+Safe strncpy that ensures a trailing zero
+=============
+*/
+void Q_strncpyz( char *dest, const char *src, int destsize ) {
+ // bk001129 - also NULL dest
+ if ( !dest ) {
+ Com_Error( ERR_FATAL, "Q_strncpyz: NULL dest" );
+ }
+ if ( !src ) {
+ Com_Error( ERR_FATAL, "Q_strncpyz: NULL src" );
+ }
+ if ( destsize < 1 ) {
+ Com_Error(ERR_FATAL,"Q_strncpyz: destsize < 1" );
+ }
+
+ strncpy( dest, src, destsize-1 );
+ dest[destsize-1] = 0;
+}
+
+int Q_stricmpn (const char *s1, const char *s2, int n) {
+ int c1, c2;
+
+ // bk001129 - moved in 1.17 fix not in id codebase
+ if ( s1 == NULL ) {
+ if ( s2 == NULL )
+ return 0;
+ else
+ return -1;
+ }
+ else if ( s2==NULL )
+ return 1;
+
+
+
+ do {
+ c1 = *s1++;
+ c2 = *s2++;
+
+ if (!n--) {
+ return 0; // strings are equal until end point
+ }
+
+ if (c1 != c2) {
+ if (c1 >= 'a' && c1 <= 'z') {
+ c1 -= ('a' - 'A');
+ }
+ if (c2 >= 'a' && c2 <= 'z') {
+ c2 -= ('a' - 'A');
+ }
+ if (c1 != c2) {
+ return c1 < c2 ? -1 : 1;
+ }
+ }
+ } while (c1);
+
+ return 0; // strings are equal
+}
+
+int Q_strncmp (const char *s1, const char *s2, int n) {
+ int c1, c2;
+
+ do {
+ c1 = *s1++;
+ c2 = *s2++;
+
+ if (!n--) {
+ return 0; // strings are equal until end point
+ }
+
+ if (c1 != c2) {
+ return c1 < c2 ? -1 : 1;
+ }
+ } while (c1);
+
+ return 0; // strings are equal
+}
+
+int Q_stricmp (const char *s1, const char *s2) {
+ return (s1 && s2) ? Q_stricmpn (s1, s2, 99999) : -1;
+}
+
+
+char *Q_strlwr( char *s1 ) {
+ char *s;
+
+ s = s1;
+ while ( *s ) {
+ *s = tolower(*s);
+ s++;
+ }
+ return s1;
+}
+
+char *Q_strupr( char *s1 ) {
+ char *s;
+
+ s = s1;
+ while ( *s ) {
+ *s = toupper(*s);
+ s++;
+ }
+ return s1;
+}
+
+
+// never goes past bounds or leaves without a terminating 0
+void Q_strcat( char *dest, int size, const char *src ) {
+ int l1;
+
+ l1 = strlen( dest );
+ if ( l1 >= size ) {
+ Com_Error( ERR_FATAL, "Q_strcat: already overflowed" );
+ }
+ Q_strncpyz( dest + l1, src, size - l1 );
+}
+
+
+int Q_PrintStrlen( const char *string ) {
+ int len;
+ const char *p;
+
+ if( !string ) {
+ return 0;
+ }
+
+ len = 0;
+ p = string;
+ while( *p ) {
+ if( Q_IsColorString( p ) ) {
+ p += 2;
+ continue;
+ }
+ p++;
+ len++;
+ }
+
+ return len;
+}
+
+
+char *Q_CleanStr( char *string ) {
+ char* d;
+ char* s;
+ int c;
+
+ s = string;
+ d = string;
+ while ((c = *s) != 0 ) {
+ if ( Q_IsColorString( s ) ) {
+ s++;
+ }
+ else if ( c >= 0x20 && c <= 0x7E ) {
+ *d++ = c;
+ }
+ s++;
+ }
+ *d = '\0';
+
+ return string;
+}
+
+
+void QDECL Com_sprintf( char *dest, int size, const char *fmt, ...) {
+ int len;
+ va_list argptr;
+ char bigbuffer[32000]; // big, but small enough to fit in PPC stack
+
+ va_start (argptr,fmt);
+ len = vsprintf (bigbuffer,fmt,argptr);
+ va_end (argptr);
+ if ( len >= sizeof( bigbuffer ) ) {
+ Com_Error( ERR_FATAL, "Com_sprintf: overflowed bigbuffer" );
+ }
+ if (len >= size) {
+ Com_Printf ("Com_sprintf: overflow of %i in %i\n", len, size);
+#ifdef _DEBUG
+ __asm {
+ int 3;
+ }
+#endif
+ }
+ Q_strncpyz (dest, bigbuffer, size );
+}
+
+
+/*
+============
+va
+
+does a varargs printf into a temp buffer, so I don't need to have
+varargs versions of all text functions.
+FIXME: make this buffer size safe someday
+============
+*/
+char * QDECL va( char *format, ... ) {
+ va_list argptr;
+ static char string[2][32000]; // in case va is called by nested functions
+ static int index = 0;
+ char *buf;
+
+ buf = string[index & 1];
+ index++;
+
+ va_start (argptr, format);
+ vsprintf (buf, format,argptr);
+ va_end (argptr);
+
+ return buf;
+}
+
+
+/*
+=====================================================================
+
+ INFO STRINGS
+
+=====================================================================
+*/
+
+/*
+===============
+Info_ValueForKey
+
+Searches the string for the given
+key and returns the associated value, or an empty string.
+FIXME: overflow check?
+===============
+*/
+char *Info_ValueForKey( const char *s, const char *key ) {
+ char pkey[BIG_INFO_KEY];
+ static char value[2][BIG_INFO_VALUE]; // use two buffers so compares
+ // work without stomping on each other
+ static int valueindex = 0;
+ char *o;
+
+ if ( !s || !key ) {
+ return "";
+ }
+
+ if ( strlen( s ) >= BIG_INFO_STRING ) {
+ Com_Error( ERR_DROP, "Info_ValueForKey: oversize infostring" );
+ }
+
+ valueindex ^= 1;
+ if (*s == '\\')
+ s++;
+ while (1)
+ {
+ o = pkey;
+ while (*s != '\\')
+ {
+ if (!*s)
+ return "";
+ *o++ = *s++;
+ }
+ *o = 0;
+ s++;
+
+ o = value[valueindex];
+
+ while (*s != '\\' && *s)
+ {
+ *o++ = *s++;
+ }
+ *o = 0;
+
+ if (!Q_stricmp (key, pkey) )
+ return value[valueindex];
+
+ if (!*s)
+ break;
+ s++;
+ }
+
+ return "";
+}
+
+
+/*
+===================
+Info_NextPair
+
+Used to itterate through all the key/value pairs in an info string
+===================
+*/
+void Info_NextPair( const char **head, char *key, char *value ) {
+ char *o;
+ const char *s;
+
+ s = *head;
+
+ if ( *s == '\\' ) {
+ s++;
+ }
+ key[0] = 0;
+ value[0] = 0;
+
+ o = key;
+ while ( *s != '\\' ) {
+ if ( !*s ) {
+ *o = 0;
+ *head = s;
+ return;
+ }
+ *o++ = *s++;
+ }
+ *o = 0;
+ s++;
+
+ o = value;
+ while ( *s != '\\' && *s ) {
+ *o++ = *s++;
+ }
+ *o = 0;
+
+ *head = s;
+}
+
+
+/*
+===================
+Info_RemoveKey
+===================
+*/
+void Info_RemoveKey( char *s, const char *key ) {
+ char *start;
+ char pkey[MAX_INFO_KEY];
+ char value[MAX_INFO_VALUE];
+ char *o;
+
+ if ( strlen( s ) >= MAX_INFO_STRING ) {
+ Com_Error( ERR_DROP, "Info_RemoveKey: oversize infostring" );
+ }
+
+ if (strchr (key, '\\')) {
+ return;
+ }
+
+ while (1)
+ {
+ start = s;
+ if (*s == '\\')
+ s++;
+ o = pkey;
+ while (*s != '\\')
+ {
+ if (!*s)
+ return;
+ *o++ = *s++;
+ }
+ *o = 0;
+ s++;
+
+ o = value;
+ while (*s != '\\' && *s)
+ {
+ if (!*s)
+ return;
+ *o++ = *s++;
+ }
+ *o = 0;
+
+ if (!strcmp (key, pkey) )
+ {
+ strcpy (start, s); // remove this part
+ return;
+ }
+
+ if (!*s)
+ return;
+ }
+
+}
+
+/*
+===================
+Info_RemoveKey_Big
+===================
+*/
+void Info_RemoveKey_Big( char *s, const char *key ) {
+ char *start;
+ char pkey[BIG_INFO_KEY];
+ char value[BIG_INFO_VALUE];
+ char *o;
+
+ if ( strlen( s ) >= BIG_INFO_STRING ) {
+ Com_Error( ERR_DROP, "Info_RemoveKey_Big: oversize infostring" );
+ }
+
+ if (strchr (key, '\\')) {
+ return;
+ }
+
+ while (1)
+ {
+ start = s;
+ if (*s == '\\')
+ s++;
+ o = pkey;
+ while (*s != '\\')
+ {
+ if (!*s)
+ return;
+ *o++ = *s++;
+ }
+ *o = 0;
+ s++;
+
+ o = value;
+ while (*s != '\\' && *s)
+ {
+ if (!*s)
+ return;
+ *o++ = *s++;
+ }
+ *o = 0;
+
+ if (!strcmp (key, pkey) )
+ {
+ strcpy (start, s); // remove this part
+ return;
+ }
+
+ if (!*s)
+ return;
+ }
+
+}
+
+
+
+
+/*
+==================
+Info_Validate
+
+Some characters are illegal in info strings because they
+can mess up the server's parsing
+==================
+*/
+qboolean Info_Validate( const char *s ) {
+ if ( strchr( s, '\"' ) ) {
+ return qfalse;
+ }
+ if ( strchr( s, ';' ) ) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+/*
+==================
+Info_SetValueForKey
+
+Changes or adds a key/value pair
+==================
+*/
+void Info_SetValueForKey( char *s, const char *key, const char *value ) {
+ char newi[MAX_INFO_STRING];
+
+ if ( strlen( s ) >= MAX_INFO_STRING ) {
+ Com_Error( ERR_DROP, "Info_SetValueForKey: oversize infostring" );
+ }
+
+ if (strchr (key, '\\') || strchr (value, '\\'))
+ {
+ Com_Printf ("Can't use keys or values with a \\\n");
+ return;
+ }
+
+ if (strchr (key, ';') || strchr (value, ';'))
+ {
+ Com_Printf ("Can't use keys or values with a semicolon\n");
+ return;
+ }
+
+ if (strchr (key, '\"') || strchr (value, '\"'))
+ {
+ Com_Printf ("Can't use keys or values with a \"\n");
+ return;
+ }
+
+ Info_RemoveKey (s, key);
+ if (!value || !strlen(value))
+ return;
+
+ Com_sprintf (newi, sizeof(newi), "\\%s\\%s", key, value);
+
+ if (strlen(newi) + strlen(s) > MAX_INFO_STRING)
+ {
+ Com_Printf ("Info string length exceeded\n");
+ return;
+ }
+
+ strcat (newi, s);
+ strcpy (s, newi);
+}
+
+/*
+==================
+Info_SetValueForKey_Big
+
+Changes or adds a key/value pair
+==================
+*/
+void Info_SetValueForKey_Big( char *s, const char *key, const char *value ) {
+ char newi[BIG_INFO_STRING];
+
+ if ( strlen( s ) >= BIG_INFO_STRING ) {
+ Com_Error( ERR_DROP, "Info_SetValueForKey: oversize infostring" );
+ }
+
+ if (strchr (key, '\\') || strchr (value, '\\'))
+ {
+ Com_Printf ("Can't use keys or values with a \\\n");
+ return;
+ }
+
+ if (strchr (key, ';') || strchr (value, ';'))
+ {
+ Com_Printf ("Can't use keys or values with a semicolon\n");
+ return;
+ }
+
+ if (strchr (key, '\"') || strchr (value, '\"'))
+ {
+ Com_Printf ("Can't use keys or values with a \"\n");
+ return;
+ }
+
+ Info_RemoveKey_Big (s, key);
+ if (!value || !strlen(value))
+ return;
+
+ Com_sprintf (newi, sizeof(newi), "\\%s\\%s", key, value);
+
+ if (strlen(newi) + strlen(s) > BIG_INFO_STRING)
+ {
+ Com_Printf ("BIG Info string length exceeded\n");
+ return;
+ }
+
+ strcat (s, newi);
+}
+
+
+
+
+//====================================================================
+
+
diff --git a/code/game/q_shared.h b/code/game/q_shared.h
new file mode 100755
index 0000000..eed5689
--- /dev/null
+++ b/code/game/q_shared.h
@@ -0,0 +1,1432 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#ifndef __Q_SHARED_H
+#define __Q_SHARED_H
+
+// q_shared.h -- included first by ALL program modules.
+// A user mod should never modify this file
+
+#define Q3_VERSION "Q3 1.32b"
+// 1.32 released 7-10-2002
+
+#define MAX_TEAMNAME 32
+
+#ifdef _WIN32
+
+#pragma warning(disable : 4018) // signed/unsigned mismatch
+#pragma warning(disable : 4032)
+#pragma warning(disable : 4051)
+#pragma warning(disable : 4057) // slightly different base types
+#pragma warning(disable : 4100) // unreferenced formal parameter
+#pragma warning(disable : 4115)
+#pragma warning(disable : 4125) // decimal digit terminates octal escape sequence
+#pragma warning(disable : 4127) // conditional expression is constant
+#pragma warning(disable : 4136)
+#pragma warning(disable : 4152) // nonstandard extension, function/data pointer conversion in expression
+//#pragma warning(disable : 4201)
+//#pragma warning(disable : 4214)
+#pragma warning(disable : 4244)
+#pragma warning(disable : 4142) // benign redefinition
+//#pragma warning(disable : 4305) // truncation from const double to float
+//#pragma warning(disable : 4310) // cast truncates constant value
+//#pragma warning(disable: 4505) // unreferenced local function has been removed
+#pragma warning(disable : 4514)
+#pragma warning(disable : 4702) // unreachable code
+#pragma warning(disable : 4711) // selected for automatic inline expansion
+#pragma warning(disable : 4220) // varargs matches remaining parameters
+#endif
+
+/**********************************************************************
+ VM Considerations
+
+ The VM can not use the standard system headers because we aren't really
+ using the compiler they were meant for. We use bg_lib.h which contains
+ prototypes for the functions we define for our own use in bg_lib.c.
+
+ When writing mods, please add needed headers HERE, do not start including
+ stuff like <stdio.h> in the various .c files that make up each of the VMs
+ since you will be including system headers files can will have issues.
+
+ Remember, if you use a C library function that is not defined in bg_lib.c,
+ you will have to add your own version for support in the VM.
+
+ **********************************************************************/
+
+#ifdef Q3_VM
+
+#include "bg_lib.h"
+
+#else
+
+#include <assert.h>
+#include <math.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <string.h>
+#include <stdlib.h>
+#include <time.h>
+#include <ctype.h>
+#include <limits.h>
+
+#endif
+
+#ifdef _WIN32
+
+//#pragma intrinsic( memset, memcpy )
+
+#endif
+
+
+// this is the define for determining if we have an asm version of a C function
+#if (defined _M_IX86 || defined __i386__) && !defined __sun__ && !defined __LCC__
+#define id386 1
+#else
+#define id386 0
+#endif
+
+#if (defined(powerc) || defined(powerpc) || defined(ppc) || defined(__ppc) || defined(__ppc__)) && !defined(C_ONLY)
+#define idppc 1
+#if defined(__VEC__)
+#define idppc_altivec 1
+#else
+#define idppc_altivec 0
+#endif
+#else
+#define idppc 0
+#define idppc_altivec 0
+#endif
+
+// for windows fastcall option
+
+#define QDECL
+
+short ShortSwap (short l);
+int LongSwap (int l);
+float FloatSwap (const float *f);
+
+//======================= WIN32 DEFINES =================================
+
+#ifdef WIN32
+
+#define MAC_STATIC
+
+#undef QDECL
+#define QDECL __cdecl
+
+// buildstring will be incorporated into the version string
+#ifdef NDEBUG
+#ifdef _M_IX86
+#define CPUSTRING "win-x86"
+#elif defined _M_ALPHA
+#define CPUSTRING "win-AXP"
+#endif
+#else
+#ifdef _M_IX86
+#define CPUSTRING "win-x86-debug"
+#elif defined _M_ALPHA
+#define CPUSTRING "win-AXP-debug"
+#endif
+#endif
+
+#define ID_INLINE __inline
+
+static ID_INLINE short BigShort( short l) { return ShortSwap(l); }
+#define LittleShort
+static ID_INLINE int BigLong(int l) { LongSwap(l); }
+#define LittleLong
+static ID_INLINE float BigFloat(const float *l) { FloatSwap(l); }
+#define LittleFloat
+
+#define PATH_SEP '\\'
+
+#endif
+
+//======================= MAC OS X DEFINES =====================
+
+#if defined(MACOS_X)
+
+#define MAC_STATIC
+#define __cdecl
+#define __declspec(x)
+#define stricmp strcasecmp
+#define ID_INLINE inline
+
+#ifdef __ppc__
+#define CPUSTRING "MacOSX-ppc"
+#elif defined __i386__
+#define CPUSTRING "MacOSX-i386"
+#else
+#define CPUSTRING "MacOSX-other"
+#endif
+
+#define PATH_SEP '/'
+
+#define __rlwimi(out, in, shift, maskBegin, maskEnd) asm("rlwimi %0,%1,%2,%3,%4" : "=r" (out) : "r" (in), "i" (shift), "i" (maskBegin), "i" (maskEnd))
+#define __dcbt(addr, offset) asm("dcbt %0,%1" : : "b" (addr), "r" (offset))
+
+static inline unsigned int __lwbrx(register void *addr, register int offset) {
+ register unsigned int word;
+
+ asm("lwbrx %0,%2,%1" : "=r" (word) : "r" (addr), "b" (offset));
+ return word;
+}
+
+static inline unsigned short __lhbrx(register void *addr, register int offset) {
+ register unsigned short halfword;
+
+ asm("lhbrx %0,%2,%1" : "=r" (halfword) : "r" (addr), "b" (offset));
+ return halfword;
+}
+
+static inline float __fctiw(register float f) {
+ register float fi;
+
+ asm("fctiw %0,%1" : "=f" (fi) : "f" (f));
+
+ return fi;
+}
+
+#define BigShort
+static inline short LittleShort(short l) { return ShortSwap(l); }
+#define BigLong
+static inline int LittleLong (int l) { return LongSwap(l); }
+#define BigFloat
+static inline float LittleFloat (const float l) { return FloatSwap(&l); }
+
+#endif
+
+//======================= MAC DEFINES =================================
+
+#ifdef __MACOS__
+
+#include <MacTypes.h>
+#define MAC_STATIC
+#define ID_INLINE inline
+
+#define CPUSTRING "MacOS-PPC"
+
+#define PATH_SEP ':'
+
+void Sys_PumpEvents( void );
+
+#define BigShort
+static inline short LittleShort(short l) { return ShortSwap(l); }
+#define BigLong
+static inline int LittleLong (int l) { return LongSwap(l); }
+#define BigFloat
+static inline float LittleFloat (const float l) { return FloatSwap(&l); }
+
+#endif
+
+//======================= LINUX DEFINES =================================
+
+// the mac compiler can't handle >32k of locals, so we
+// just waste space and make big arrays static...
+#ifdef __linux__
+
+// bk001205 - from Makefile
+#define stricmp strcasecmp
+
+#define MAC_STATIC // bk: FIXME
+#define ID_INLINE inline
+
+#ifdef __i386__
+#define CPUSTRING "linux-i386"
+#elif defined __axp__
+#define CPUSTRING "linux-alpha"
+#else
+#define CPUSTRING "linux-other"
+#endif
+
+#define PATH_SEP '/'
+
+// bk001205 - try
+#ifdef Q3_STATIC
+#define GAME_HARD_LINKED
+#define CGAME_HARD_LINKED
+#define UI_HARD_LINKED
+#define BOTLIB_HARD_LINKED
+#endif
+
+#if !idppc
+inline static short BigShort( short l) { return ShortSwap(l); }
+#define LittleShort
+inline static int BigLong(int l) { return LongSwap(l); }
+#define LittleLong
+inline static float BigFloat(const float *l) { return FloatSwap(l); }
+#define LittleFloat
+#else
+#define BigShort
+inline static short LittleShort(short l) { return ShortSwap(l); }
+#define BigLong
+inline static int LittleLong (int l) { return LongSwap(l); }
+#define BigFloat
+inline static float LittleFloat (const float *l) { return FloatSwap(l); }
+#endif
+
+#endif
+
+//======================= FreeBSD DEFINES =====================
+#ifdef __FreeBSD__ // rb010123
+
+#define stricmp strcasecmp
+
+#define MAC_STATIC
+#define ID_INLINE inline
+
+#ifdef __i386__
+#define CPUSTRING "freebsd-i386"
+#elif defined __axp__
+#define CPUSTRING "freebsd-alpha"
+#else
+#define CPUSTRING "freebsd-other"
+#endif
+
+#define PATH_SEP '/'
+
+// bk010116 - omitted Q3STATIC (see Linux above), broken target
+
+#if !idppc
+static short BigShort( short l) { return ShortSwap(l); }
+#define LittleShort
+static int BigLong(int l) { LongSwap(l); }
+#define LittleLong
+static float BigFloat(const float *l) { FloatSwap(l); }
+#define LittleFloat
+#else
+#define BigShort
+static short LittleShort(short l) { return ShortSwap(l); }
+#define BigLong
+static int LittleLong (int l) { return LongSwap(l); }
+#define BigFloat
+static float LittleFloat (const float *l) { return FloatSwap(l); }
+#endif
+
+#endif
+
+//=============================================================
+
+typedef unsigned char byte;
+
+typedef enum {qfalse, qtrue} qboolean;
+
+typedef int qhandle_t;
+typedef int sfxHandle_t;
+typedef int fileHandle_t;
+typedef int clipHandle_t;
+
+
+#ifndef NULL
+#define NULL ((void *)0)
+#endif
+
+#define MAX_QINT 0x7fffffff
+#define MIN_QINT (-MAX_QINT-1)
+
+
+// angle indexes
+#define PITCH 0 // up / down
+#define YAW 1 // left / right
+#define ROLL 2 // fall over
+
+// the game guarantees that no string from the network will ever
+// exceed MAX_STRING_CHARS
+#define MAX_STRING_CHARS 1024 // max length of a string passed to Cmd_TokenizeString
+#define MAX_STRING_TOKENS 1024 // max tokens resulting from Cmd_TokenizeString
+#define MAX_TOKEN_CHARS 1024 // max length of an individual token
+
+#define MAX_INFO_STRING 1024
+#define MAX_INFO_KEY 1024
+#define MAX_INFO_VALUE 1024
+
+#define BIG_INFO_STRING 8192 // used for system info key only
+#define BIG_INFO_KEY 8192
+#define BIG_INFO_VALUE 8192
+
+
+#define MAX_QPATH 64 // max length of a quake game pathname
+#ifdef PATH_MAX
+#define MAX_OSPATH PATH_MAX
+#else
+#define MAX_OSPATH 256 // max length of a filesystem pathname
+#endif
+
+#define MAX_NAME_LENGTH 32 // max length of a client name
+
+#define MAX_SAY_TEXT 150
+
+// paramters for command buffer stuffing
+typedef enum {
+ EXEC_NOW, // don't return until completed, a VM should NEVER use this,
+ // because some commands might cause the VM to be unloaded...
+ EXEC_INSERT, // insert at current position, but don't run yet
+ EXEC_APPEND // add to end of the command buffer (normal case)
+} cbufExec_t;
+
+
+//
+// these aren't needed by any of the VMs. put in another header?
+//
+#define MAX_MAP_AREA_BYTES 32 // bit vector of area visibility
+
+
+// print levels from renderer (FIXME: set up for game / cgame?)
+typedef enum {
+ PRINT_ALL,
+ PRINT_DEVELOPER, // only print when "developer 1"
+ PRINT_WARNING,
+ PRINT_ERROR
+} printParm_t;
+
+
+#ifdef ERR_FATAL
+#undef ERR_FATAL // this is be defined in malloc.h
+#endif
+
+// parameters to the main Error routine
+typedef enum {
+ ERR_FATAL, // exit the entire game with a popup window
+ ERR_DROP, // print to console and disconnect from game
+ ERR_SERVERDISCONNECT, // don't kill server
+ ERR_DISCONNECT, // client disconnected from the server
+ ERR_NEED_CD // pop up the need-cd dialog
+} errorParm_t;
+
+
+// font rendering values used by ui and cgame
+
+#define PROP_GAP_WIDTH 3
+#define PROP_SPACE_WIDTH 8
+#define PROP_HEIGHT 27
+#define PROP_SMALL_SIZE_SCALE 0.75
+
+#define BLINK_DIVISOR 200
+#define PULSE_DIVISOR 75
+
+#define UI_LEFT 0x00000000 // default
+#define UI_CENTER 0x00000001
+#define UI_RIGHT 0x00000002
+#define UI_FORMATMASK 0x00000007
+#define UI_SMALLFONT 0x00000010
+#define UI_BIGFONT 0x00000020 // default
+#define UI_GIANTFONT 0x00000040
+#define UI_DROPSHADOW 0x00000800
+#define UI_BLINK 0x00001000
+#define UI_INVERSE 0x00002000
+#define UI_PULSE 0x00004000
+
+#if defined(_DEBUG) && !defined(BSPC)
+ #define HUNK_DEBUG
+#endif
+
+typedef enum {
+ h_high,
+ h_low,
+ h_dontcare
+} ha_pref;
+
+#ifdef HUNK_DEBUG
+#define Hunk_Alloc( size, preference ) Hunk_AllocDebug(size, preference, #size, __FILE__, __LINE__)
+void *Hunk_AllocDebug( int size, ha_pref preference, char *label, char *file, int line );
+#else
+void *Hunk_Alloc( int size, ha_pref preference );
+#endif
+
+#ifdef __linux__
+// https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=371
+// custom Snd_Memset implementation for glibc memset bug workaround
+void Snd_Memset (void* dest, const int val, const size_t count);
+#else
+#define Snd_Memset Com_Memset
+#endif
+
+#if !( defined __VECTORC )
+void Com_Memset (void* dest, const int val, const size_t count);
+void Com_Memcpy (void* dest, const void* src, const size_t count);
+#else
+#define Com_Memset memset
+#define Com_Memcpy memcpy
+#endif
+
+#define CIN_system 1
+#define CIN_loop 2
+#define CIN_hold 4
+#define CIN_silent 8
+#define CIN_shader 16
+
+/*
+==============================================================
+
+MATHLIB
+
+==============================================================
+*/
+
+
+typedef float vec_t;
+typedef vec_t vec2_t[2];
+typedef vec_t vec3_t[3];
+typedef vec_t vec4_t[4];
+typedef vec_t vec5_t[5];
+
+typedef int fixed4_t;
+typedef int fixed8_t;
+typedef int fixed16_t;
+
+#ifndef M_PI
+#define M_PI 3.14159265358979323846f // matches value in gcc v2 math.h
+#endif
+
+#define NUMVERTEXNORMALS 162
+extern vec3_t bytedirs[NUMVERTEXNORMALS];
+
+// all drawing is done to a 640*480 virtual screen size
+// and will be automatically scaled to the real resolution
+#define SCREEN_WIDTH 640
+#define SCREEN_HEIGHT 480
+
+#define TINYCHAR_WIDTH (SMALLCHAR_WIDTH)
+#define TINYCHAR_HEIGHT (SMALLCHAR_HEIGHT/2)
+
+#define SMALLCHAR_WIDTH 8
+#define SMALLCHAR_HEIGHT 16
+
+#define BIGCHAR_WIDTH 16
+#define BIGCHAR_HEIGHT 16
+
+#define GIANTCHAR_WIDTH 32
+#define GIANTCHAR_HEIGHT 48
+
+extern vec4_t colorBlack;
+extern vec4_t colorRed;
+extern vec4_t colorGreen;
+extern vec4_t colorBlue;
+extern vec4_t colorYellow;
+extern vec4_t colorMagenta;
+extern vec4_t colorCyan;
+extern vec4_t colorWhite;
+extern vec4_t colorLtGrey;
+extern vec4_t colorMdGrey;
+extern vec4_t colorDkGrey;
+
+#define Q_COLOR_ESCAPE '^'
+#define Q_IsColorString(p) ( p && *(p) == Q_COLOR_ESCAPE && *((p)+1) && *((p)+1) != Q_COLOR_ESCAPE )
+
+#define COLOR_BLACK '0'
+#define COLOR_RED '1'
+#define COLOR_GREEN '2'
+#define COLOR_YELLOW '3'
+#define COLOR_BLUE '4'
+#define COLOR_CYAN '5'
+#define COLOR_MAGENTA '6'
+#define COLOR_WHITE '7'
+#define ColorIndex(c) ( ( (c) - '0' ) & 7 )
+
+#define S_COLOR_BLACK "^0"
+#define S_COLOR_RED "^1"
+#define S_COLOR_GREEN "^2"
+#define S_COLOR_YELLOW "^3"
+#define S_COLOR_BLUE "^4"
+#define S_COLOR_CYAN "^5"
+#define S_COLOR_MAGENTA "^6"
+#define S_COLOR_WHITE "^7"
+
+extern vec4_t g_color_table[8];
+
+#define MAKERGB( v, r, g, b ) v[0]=r;v[1]=g;v[2]=b
+#define MAKERGBA( v, r, g, b, a ) v[0]=r;v[1]=g;v[2]=b;v[3]=a
+
+#define DEG2RAD( a ) ( ( (a) * M_PI ) / 180.0F )
+#define RAD2DEG( a ) ( ( (a) * 180.0f ) / M_PI )
+
+struct cplane_s;
+
+extern vec3_t vec3_origin;
+extern vec3_t axisDefault[3];
+
+#define nanmask (255<<23)
+
+#define IS_NAN(x) (((*(int *)&x)&nanmask)==nanmask)
+
+#if idppc
+
+static inline float Q_rsqrt( float number ) {
+ float x = 0.5f * number;
+ float y;
+#ifdef __GNUC__
+ asm("frsqrte %0,%1" : "=f" (y) : "f" (number));
+#else
+ y = __frsqrte( number );
+#endif
+ return y * (1.5f - (x * y * y));
+ }
+
+#ifdef __GNUC__
+static inline float Q_fabs(float x) {
+ float abs_x;
+
+ asm("fabs %0,%1" : "=f" (abs_x) : "f" (x));
+ return abs_x;
+}
+#else
+#define Q_fabs __fabsf
+#endif
+
+#else
+float Q_fabs( float f );
+float Q_rsqrt( float f ); // reciprocal square root
+#endif
+
+#define SQRTFAST( x ) ( (x) * Q_rsqrt( x ) )
+
+signed char ClampChar( int i );
+signed short ClampShort( int i );
+
+// this isn't a real cheap function to call!
+int DirToByte( vec3_t dir );
+void ByteToDir( int b, vec3_t dir );
+
+#if 1
+
+#define DotProduct(x,y) ((x)[0]*(y)[0]+(x)[1]*(y)[1]+(x)[2]*(y)[2])
+#define VectorSubtract(a,b,c) ((c)[0]=(a)[0]-(b)[0],(c)[1]=(a)[1]-(b)[1],(c)[2]=(a)[2]-(b)[2])
+#define VectorAdd(a,b,c) ((c)[0]=(a)[0]+(b)[0],(c)[1]=(a)[1]+(b)[1],(c)[2]=(a)[2]+(b)[2])
+#define VectorCopy(a,b) ((b)[0]=(a)[0],(b)[1]=(a)[1],(b)[2]=(a)[2])
+#define VectorScale(v, s, o) ((o)[0]=(v)[0]*(s),(o)[1]=(v)[1]*(s),(o)[2]=(v)[2]*(s))
+#define VectorMA(v, s, b, o) ((o)[0]=(v)[0]+(b)[0]*(s),(o)[1]=(v)[1]+(b)[1]*(s),(o)[2]=(v)[2]+(b)[2]*(s))
+
+#else
+
+#define DotProduct(x,y) _DotProduct(x,y)
+#define VectorSubtract(a,b,c) _VectorSubtract(a,b,c)
+#define VectorAdd(a,b,c) _VectorAdd(a,b,c)
+#define VectorCopy(a,b) _VectorCopy(a,b)
+#define VectorScale(v, s, o) _VectorScale(v,s,o)
+#define VectorMA(v, s, b, o) _VectorMA(v,s,b,o)
+
+#endif
+
+#ifdef __LCC__
+#ifdef VectorCopy
+#undef VectorCopy
+// this is a little hack to get more efficient copies in our interpreter
+typedef struct {
+ float v[3];
+} vec3struct_t;
+#define VectorCopy(a,b) (*(vec3struct_t *)b=*(vec3struct_t *)a)
+#define ID_INLINE static
+#endif
+#endif
+
+#define VectorClear(a) ((a)[0]=(a)[1]=(a)[2]=0)
+#define VectorNegate(a,b) ((b)[0]=-(a)[0],(b)[1]=-(a)[1],(b)[2]=-(a)[2])
+#define VectorSet(v, x, y, z) ((v)[0]=(x), (v)[1]=(y), (v)[2]=(z))
+#define Vector4Copy(a,b) ((b)[0]=(a)[0],(b)[1]=(a)[1],(b)[2]=(a)[2],(b)[3]=(a)[3])
+
+#define SnapVector(v) {v[0]=((int)(v[0]));v[1]=((int)(v[1]));v[2]=((int)(v[2]));}
+// just in case you do't want to use the macros
+vec_t _DotProduct( const vec3_t v1, const vec3_t v2 );
+void _VectorSubtract( const vec3_t veca, const vec3_t vecb, vec3_t out );
+void _VectorAdd( const vec3_t veca, const vec3_t vecb, vec3_t out );
+void _VectorCopy( const vec3_t in, vec3_t out );
+void _VectorScale( const vec3_t in, float scale, vec3_t out );
+void _VectorMA( const vec3_t veca, float scale, const vec3_t vecb, vec3_t vecc );
+
+unsigned ColorBytes3 (float r, float g, float b);
+unsigned ColorBytes4 (float r, float g, float b, float a);
+
+float NormalizeColor( const vec3_t in, vec3_t out );
+
+float RadiusFromBounds( const vec3_t mins, const vec3_t maxs );
+void ClearBounds( vec3_t mins, vec3_t maxs );
+void AddPointToBounds( const vec3_t v, vec3_t mins, vec3_t maxs );
+
+#ifndef __LCC__
+static ID_INLINE int VectorCompare( const vec3_t v1, const vec3_t v2 ) {
+ if (v1[0] != v2[0] || v1[1] != v2[1] || v1[2] != v2[2]) {
+ return 0;
+ }
+ return 1;
+}
+
+static ID_INLINE vec_t VectorLength( const vec3_t v ) {
+ return (vec_t)sqrt (v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
+}
+
+static ID_INLINE vec_t VectorLengthSquared( const vec3_t v ) {
+ return (v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
+}
+
+static ID_INLINE vec_t Distance( const vec3_t p1, const vec3_t p2 ) {
+ vec3_t v;
+
+ VectorSubtract (p2, p1, v);
+ return VectorLength( v );
+}
+
+static ID_INLINE vec_t DistanceSquared( const vec3_t p1, const vec3_t p2 ) {
+ vec3_t v;
+
+ VectorSubtract (p2, p1, v);
+ return v[0]*v[0] + v[1]*v[1] + v[2]*v[2];
+}
+
+// fast vector normalize routine that does not check to make sure
+// that length != 0, nor does it return length, uses rsqrt approximation
+static ID_INLINE void VectorNormalizeFast( vec3_t v )
+{
+ float ilength;
+
+ ilength = Q_rsqrt( DotProduct( v, v ) );
+
+ v[0] *= ilength;
+ v[1] *= ilength;
+ v[2] *= ilength;
+}
+
+static ID_INLINE void VectorInverse( vec3_t v ){
+ v[0] = -v[0];
+ v[1] = -v[1];
+ v[2] = -v[2];
+}
+
+static ID_INLINE void CrossProduct( const vec3_t v1, const vec3_t v2, vec3_t cross ) {
+ cross[0] = v1[1]*v2[2] - v1[2]*v2[1];
+ cross[1] = v1[2]*v2[0] - v1[0]*v2[2];
+ cross[2] = v1[0]*v2[1] - v1[1]*v2[0];
+}
+
+#else
+int VectorCompare( const vec3_t v1, const vec3_t v2 );
+
+vec_t VectorLength( const vec3_t v );
+
+vec_t VectorLengthSquared( const vec3_t v );
+
+vec_t Distance( const vec3_t p1, const vec3_t p2 );
+
+vec_t DistanceSquared( const vec3_t p1, const vec3_t p2 );
+
+void VectorNormalizeFast( vec3_t v );
+
+void VectorInverse( vec3_t v );
+
+void CrossProduct( const vec3_t v1, const vec3_t v2, vec3_t cross );
+
+#endif
+
+vec_t VectorNormalize (vec3_t v); // returns vector length
+vec_t VectorNormalize2( const vec3_t v, vec3_t out );
+void Vector4Scale( const vec4_t in, vec_t scale, vec4_t out );
+void VectorRotate( vec3_t in, vec3_t matrix[3], vec3_t out );
+int Q_log2(int val);
+
+float Q_acos(float c);
+
+int Q_rand( int *seed );
+float Q_random( int *seed );
+float Q_crandom( int *seed );
+
+#define random() ((rand () & 0x7fff) / ((float)0x7fff))
+#define crandom() (2.0 * (random() - 0.5))
+
+void vectoangles( const vec3_t value1, vec3_t angles);
+void AnglesToAxis( const vec3_t angles, vec3_t axis[3] );
+
+void AxisClear( vec3_t axis[3] );
+void AxisCopy( vec3_t in[3], vec3_t out[3] );
+
+void SetPlaneSignbits( struct cplane_s *out );
+int BoxOnPlaneSide (vec3_t emins, vec3_t emaxs, struct cplane_s *plane);
+
+float AngleMod(float a);
+float LerpAngle (float from, float to, float frac);
+float AngleSubtract( float a1, float a2 );
+void AnglesSubtract( vec3_t v1, vec3_t v2, vec3_t v3 );
+
+float AngleNormalize360 ( float angle );
+float AngleNormalize180 ( float angle );
+float AngleDelta ( float angle1, float angle2 );
+
+qboolean PlaneFromPoints( vec4_t plane, const vec3_t a, const vec3_t b, const vec3_t c );
+void ProjectPointOnPlane( vec3_t dst, const vec3_t p, const vec3_t normal );
+void RotatePointAroundVector( vec3_t dst, const vec3_t dir, const vec3_t point, float degrees );
+void RotateAroundDirection( vec3_t axis[3], float yaw );
+void MakeNormalVectors( const vec3_t forward, vec3_t right, vec3_t up );
+// perpendicular vector could be replaced by this
+
+//int PlaneTypeForNormal (vec3_t normal);
+
+void MatrixMultiply(float in1[3][3], float in2[3][3], float out[3][3]);
+void AngleVectors( const vec3_t angles, vec3_t forward, vec3_t right, vec3_t up);
+void PerpendicularVector( vec3_t dst, const vec3_t src );
+
+
+//=============================================
+
+float Com_Clamp( float min, float max, float value );
+
+char *COM_SkipPath( char *pathname );
+void COM_StripExtension( const char *in, char *out );
+void COM_DefaultExtension( char *path, int maxSize, const char *extension );
+
+void COM_BeginParseSession( const char *name );
+int COM_GetCurrentParseLine( void );
+char *COM_Parse( char **data_p );
+char *COM_ParseExt( char **data_p, qboolean allowLineBreak );
+int COM_Compress( char *data_p );
+void COM_ParseError( char *format, ... );
+void COM_ParseWarning( char *format, ... );
+//int COM_ParseInfos( char *buf, int max, char infos[][MAX_INFO_STRING] );
+
+#define MAX_TOKENLENGTH 1024
+
+#ifndef TT_STRING
+//token types
+#define TT_STRING 1 // string
+#define TT_LITERAL 2 // literal
+#define TT_NUMBER 3 // number
+#define TT_NAME 4 // name
+#define TT_PUNCTUATION 5 // punctuation
+#endif
+
+typedef struct pc_token_s
+{
+ int type;
+ int subtype;
+ int intvalue;
+ float floatvalue;
+ char string[MAX_TOKENLENGTH];
+} pc_token_t;
+
+// data is an in/out parm, returns a parsed out token
+
+void COM_MatchToken( char**buf_p, char *match );
+
+void SkipBracedSection (char **program);
+void SkipRestOfLine ( char **data );
+
+void Parse1DMatrix (char **buf_p, int x, float *m);
+void Parse2DMatrix (char **buf_p, int y, int x, float *m);
+void Parse3DMatrix (char **buf_p, int z, int y, int x, float *m);
+
+void QDECL Com_sprintf (char *dest, int size, const char *fmt, ...);
+
+
+// mode parm for FS_FOpenFile
+typedef enum {
+ FS_READ,
+ FS_WRITE,
+ FS_APPEND,
+ FS_APPEND_SYNC
+} fsMode_t;
+
+typedef enum {
+ FS_SEEK_CUR,
+ FS_SEEK_END,
+ FS_SEEK_SET
+} fsOrigin_t;
+
+//=============================================
+
+int Q_isprint( int c );
+int Q_islower( int c );
+int Q_isupper( int c );
+int Q_isalpha( int c );
+
+// portable case insensitive compare
+int Q_stricmp (const char *s1, const char *s2);
+int Q_strncmp (const char *s1, const char *s2, int n);
+int Q_stricmpn (const char *s1, const char *s2, int n);
+char *Q_strlwr( char *s1 );
+char *Q_strupr( char *s1 );
+char *Q_strrchr( const char* string, int c );
+
+// buffer size safe library replacements
+void Q_strncpyz( char *dest, const char *src, int destsize );
+void Q_strcat( char *dest, int size, const char *src );
+
+// strlen that discounts Quake color sequences
+int Q_PrintStrlen( const char *string );
+// removes color sequences from string
+char *Q_CleanStr( char *string );
+
+//=============================================
+
+// 64-bit integers for global rankings interface
+// implemented as a struct for qvm compatibility
+typedef struct
+{
+ byte b0;
+ byte b1;
+ byte b2;
+ byte b3;
+ byte b4;
+ byte b5;
+ byte b6;
+ byte b7;
+} qint64;
+
+//=============================================
+/*
+short BigShort(short l);
+short LittleShort(short l);
+int BigLong (int l);
+int LittleLong (int l);
+qint64 BigLong64 (qint64 l);
+qint64 LittleLong64 (qint64 l);
+float BigFloat (const float *l);
+float LittleFloat (const float *l);
+
+void Swap_Init (void);
+*/
+char * QDECL va(char *format, ...);
+
+//=============================================
+
+//
+// key / value info strings
+//
+char *Info_ValueForKey( const char *s, const char *key );
+void Info_RemoveKey( char *s, const char *key );
+void Info_RemoveKey_big( char *s, const char *key );
+void Info_SetValueForKey( char *s, const char *key, const char *value );
+void Info_SetValueForKey_Big( char *s, const char *key, const char *value );
+qboolean Info_Validate( const char *s );
+void Info_NextPair( const char **s, char *key, char *value );
+
+// this is only here so the functions in q_shared.c and bg_*.c can link
+void QDECL Com_Error( int level, const char *error, ... );
+void QDECL Com_Printf( const char *msg, ... );
+
+
+/*
+==========================================================
+
+CVARS (console variables)
+
+Many variables can be used for cheating purposes, so when
+cheats is zero, force all unspecified variables to their
+default values.
+==========================================================
+*/
+
+#define CVAR_ARCHIVE 1 // set to cause it to be saved to vars.rc
+ // used for system variables, not for player
+ // specific configurations
+#define CVAR_USERINFO 2 // sent to server on connect or change
+#define CVAR_SERVERINFO 4 // sent in response to front end requests
+#define CVAR_SYSTEMINFO 8 // these cvars will be duplicated on all clients
+#define CVAR_INIT 16 // don't allow change from console at all,
+ // but can be set from the command line
+#define CVAR_LATCH 32 // will only change when C code next does
+ // a Cvar_Get(), so it can't be changed
+ // without proper initialization. modified
+ // will be set, even though the value hasn't
+ // changed yet
+#define CVAR_ROM 64 // display only, cannot be set by user at all
+#define CVAR_USER_CREATED 128 // created by a set command
+#define CVAR_TEMP 256 // can be set even when cheats are disabled, but is not archived
+#define CVAR_CHEAT 512 // can not be changed if cheats are disabled
+#define CVAR_NORESTART 1024 // do not clear when a cvar_restart is issued
+
+// nothing outside the Cvar_*() functions should modify these fields!
+typedef struct cvar_s {
+ char *name;
+ char *string;
+ char *resetString; // cvar_restart will reset to this value
+ char *latchedString; // for CVAR_LATCH vars
+ int flags;
+ qboolean modified; // set each time the cvar is changed
+ int modificationCount; // incremented each time the cvar is changed
+ float value; // atof( string )
+ int integer; // atoi( string )
+ struct cvar_s *next;
+ struct cvar_s *hashNext;
+} cvar_t;
+
+#define MAX_CVAR_VALUE_STRING 256
+
+typedef int cvarHandle_t;
+
+// the modules that run in the virtual machine can't access the cvar_t directly,
+// so they must ask for structured updates
+typedef struct {
+ cvarHandle_t handle;
+ int modificationCount;
+ float value;
+ int integer;
+ char string[MAX_CVAR_VALUE_STRING];
+} vmCvar_t;
+
+/*
+==============================================================
+
+COLLISION DETECTION
+
+==============================================================
+*/
+
+#include "surfaceflags.h" // shared with the q3map utility
+
+// plane types are used to speed some tests
+// 0-2 are axial planes
+#define PLANE_X 0
+#define PLANE_Y 1
+#define PLANE_Z 2
+#define PLANE_NON_AXIAL 3
+
+
+/*
+=================
+PlaneTypeForNormal
+=================
+*/
+
+#define PlaneTypeForNormal(x) (x[0] == 1.0 ? PLANE_X : (x[1] == 1.0 ? PLANE_Y : (x[2] == 1.0 ? PLANE_Z : PLANE_NON_AXIAL) ) )
+
+// plane_t structure
+// !!! if this is changed, it must be changed in asm code too !!!
+typedef struct cplane_s {
+ vec3_t normal;
+ float dist;
+ byte type; // for fast side tests: 0,1,2 = axial, 3 = nonaxial
+ byte signbits; // signx + (signy<<1) + (signz<<2), used as lookup during collision
+ byte pad[2];
+} cplane_t;
+
+
+// a trace is returned when a box is swept through the world
+typedef struct {
+ qboolean allsolid; // if true, plane is not valid
+ qboolean startsolid; // if true, the initial point was in a solid area
+ float fraction; // time completed, 1.0 = didn't hit anything
+ vec3_t endpos; // final position
+ cplane_t plane; // surface normal at impact, transformed to world space
+ int surfaceFlags; // surface hit
+ int contents; // contents on other side of surface hit
+ int entityNum; // entity the contacted sirface is a part of
+} trace_t;
+
+// trace->entityNum can also be 0 to (MAX_GENTITIES-1)
+// or ENTITYNUM_NONE, ENTITYNUM_WORLD
+
+
+// markfragments are returned by CM_MarkFragments()
+typedef struct {
+ int firstPoint;
+ int numPoints;
+} markFragment_t;
+
+
+
+typedef struct {
+ vec3_t origin;
+ vec3_t axis[3];
+} orientation_t;
+
+//=====================================================================
+
+
+// in order from highest priority to lowest
+// if none of the catchers are active, bound key strings will be executed
+#define KEYCATCH_CONSOLE 0x0001
+#define KEYCATCH_UI 0x0002
+#define KEYCATCH_MESSAGE 0x0004
+#define KEYCATCH_CGAME 0x0008
+
+
+// sound channels
+// channel 0 never willingly overrides
+// other channels will allways override a playing sound on that channel
+typedef enum {
+ CHAN_AUTO,
+ CHAN_LOCAL, // menu sounds, etc
+ CHAN_WEAPON,
+ CHAN_VOICE,
+ CHAN_ITEM,
+ CHAN_BODY,
+ CHAN_LOCAL_SOUND, // chat messages, etc
+ CHAN_ANNOUNCER // announcer voices, etc
+} soundChannel_t;
+
+
+/*
+========================================================================
+
+ ELEMENTS COMMUNICATED ACROSS THE NET
+
+========================================================================
+*/
+
+#define ANGLE2SHORT(x) ((int)((x)*65536/360) & 65535)
+#define SHORT2ANGLE(x) ((x)*(360.0/65536))
+
+#define SNAPFLAG_RATE_DELAYED 1
+#define SNAPFLAG_NOT_ACTIVE 2 // snapshot used during connection and for zombies
+#define SNAPFLAG_SERVERCOUNT 4 // toggled every map_restart so transitions can be detected
+
+//
+// per-level limits
+//
+#define MAX_CLIENTS 64 // absolute limit
+#define MAX_LOCATIONS 64
+
+#define GENTITYNUM_BITS 10 // don't need to send any more
+#define MAX_GENTITIES (1<<GENTITYNUM_BITS)
+
+// entitynums are communicated with GENTITY_BITS, so any reserved
+// values that are going to be communcated over the net need to
+// also be in this range
+#define ENTITYNUM_NONE (MAX_GENTITIES-1)
+#define ENTITYNUM_WORLD (MAX_GENTITIES-2)
+#define ENTITYNUM_MAX_NORMAL (MAX_GENTITIES-2)
+
+
+#define MAX_MODELS 256 // these are sent over the net as 8 bits
+#define MAX_SOUNDS 256 // so they cannot be blindly increased
+
+
+#define MAX_CONFIGSTRINGS 1024
+
+// these are the only configstrings that the system reserves, all the
+// other ones are strictly for servergame to clientgame communication
+#define CS_SERVERINFO 0 // an info string with all the serverinfo cvars
+#define CS_SYSTEMINFO 1 // an info string for server system to client system configuration (timescale, etc)
+
+#define RESERVED_CONFIGSTRINGS 2 // game can't modify below this, only the system can
+
+#define MAX_GAMESTATE_CHARS 16000
+typedef struct {
+ int stringOffsets[MAX_CONFIGSTRINGS];
+ char stringData[MAX_GAMESTATE_CHARS];
+ int dataCount;
+} gameState_t;
+
+//=========================================================
+
+// bit field limits
+#define MAX_STATS 16
+#define MAX_PERSISTANT 16
+#define MAX_POWERUPS 16
+#define MAX_WEAPONS 16
+
+#define MAX_PS_EVENTS 2
+
+#define PS_PMOVEFRAMECOUNTBITS 6
+
+// playerState_t is the information needed by both the client and server
+// to predict player motion and actions
+// nothing outside of pmove should modify these, or some degree of prediction error
+// will occur
+
+// you can't add anything to this without modifying the code in msg.c
+
+// playerState_t is a full superset of entityState_t as it is used by players,
+// so if a playerState_t is transmitted, the entityState_t can be fully derived
+// from it.
+typedef struct playerState_s {
+ int commandTime; // cmd->serverTime of last executed command
+ int pm_type;
+ int bobCycle; // for view bobbing and footstep generation
+ int pm_flags; // ducked, jump_held, etc
+ int pm_time;
+
+ vec3_t origin;
+ vec3_t velocity;
+ int weaponTime;
+ int gravity;
+ int speed;
+ int delta_angles[3]; // add to command angles to get view direction
+ // changed by spawns, rotating objects, and teleporters
+
+ int groundEntityNum;// ENTITYNUM_NONE = in air
+
+ int legsTimer; // don't change low priority animations until this runs out
+ int legsAnim; // mask off ANIM_TOGGLEBIT
+
+ int torsoTimer; // don't change low priority animations until this runs out
+ int torsoAnim; // mask off ANIM_TOGGLEBIT
+
+ int movementDir; // a number 0 to 7 that represents the reletive angle
+ // of movement to the view angle (axial and diagonals)
+ // when at rest, the value will remain unchanged
+ // used to twist the legs during strafing
+
+ vec3_t grapplePoint; // location of grapple to pull towards if PMF_GRAPPLE_PULL
+
+ int eFlags; // copied to entityState_t->eFlags
+
+ int eventSequence; // pmove generated events
+ int events[MAX_PS_EVENTS];
+ int eventParms[MAX_PS_EVENTS];
+
+ int externalEvent; // events set on player from another source
+ int externalEventParm;
+ int externalEventTime;
+
+ int clientNum; // ranges from 0 to MAX_CLIENTS-1
+ int weapon; // copied to entityState_t->weapon
+ int weaponstate;
+
+ vec3_t viewangles; // for fixed views
+ int viewheight;
+
+ // damage feedback
+ int damageEvent; // when it changes, latch the other parms
+ int damageYaw;
+ int damagePitch;
+ int damageCount;
+
+ int stats[MAX_STATS];
+ int persistant[MAX_PERSISTANT]; // stats that aren't cleared on death
+ int powerups[MAX_POWERUPS]; // level.time that the powerup runs out
+ int ammo[MAX_WEAPONS];
+
+ int generic1;
+ int loopSound;
+ int jumppad_ent; // jumppad entity hit this frame
+
+ // not communicated over the net at all
+ int ping; // server to game info for scoreboard
+ int pmove_framecount; // FIXME: don't transmit over the network
+ int jumppad_frame;
+ int entityEventSequence;
+} playerState_t;
+
+
+//====================================================================
+
+
+//
+// usercmd_t->button bits, many of which are generated by the client system,
+// so they aren't game/cgame only definitions
+//
+#define BUTTON_ATTACK 1
+#define BUTTON_TALK 2 // displays talk balloon and disables actions
+#define BUTTON_USE_HOLDABLE 4
+#define BUTTON_GESTURE 8
+#define BUTTON_WALKING 16 // walking can't just be infered from MOVE_RUN
+ // because a key pressed late in the frame will
+ // only generate a small move value for that frame
+ // walking will use different animations and
+ // won't generate footsteps
+#define BUTTON_AFFIRMATIVE 32
+#define BUTTON_NEGATIVE 64
+
+#define BUTTON_GETFLAG 128
+#define BUTTON_GUARDBASE 256
+#define BUTTON_PATROL 512
+#define BUTTON_FOLLOWME 1024
+
+#define BUTTON_ANY 2048 // any key whatsoever
+
+#define MOVE_RUN 120 // if forwardmove or rightmove are >= MOVE_RUN,
+ // then BUTTON_WALKING should be set
+
+// usercmd_t is sent to the server each client frame
+typedef struct usercmd_s {
+ int serverTime;
+ int angles[3];
+ int buttons;
+ byte weapon; // weapon
+ signed char forwardmove, rightmove, upmove;
+} usercmd_t;
+
+//===================================================================
+
+// if entityState->solid == SOLID_BMODEL, modelindex is an inline model number
+#define SOLID_BMODEL 0xffffff
+
+typedef enum {
+ TR_STATIONARY,
+ TR_INTERPOLATE, // non-parametric, but interpolate between snapshots
+ TR_LINEAR,
+ TR_LINEAR_STOP,
+ TR_SINE, // value = base + sin( time / duration ) * delta
+ TR_GRAVITY
+} trType_t;
+
+typedef struct {
+ trType_t trType;
+ int trTime;
+ int trDuration; // if non 0, trTime + trDuration = stop time
+ vec3_t trBase;
+ vec3_t trDelta; // velocity, etc
+} trajectory_t;
+
+// entityState_t is the information conveyed from the server
+// in an update message about entities that the client will
+// need to render in some way
+// Different eTypes may use the information in different ways
+// The messages are delta compressed, so it doesn't really matter if
+// the structure size is fairly large
+
+typedef struct entityState_s {
+ int number; // entity index
+ int eType; // entityType_t
+ int eFlags;
+
+ trajectory_t pos; // for calculating position
+ trajectory_t apos; // for calculating angles
+
+ int time;
+ int time2;
+
+ vec3_t origin;
+ vec3_t origin2;
+
+ vec3_t angles;
+ vec3_t angles2;
+
+ int otherEntityNum; // shotgun sources, etc
+ int otherEntityNum2;
+
+ int groundEntityNum; // -1 = in air
+
+ int constantLight; // r + (g<<8) + (b<<16) + (intensity<<24)
+ int loopSound; // constantly loop this sound
+
+ int modelindex;
+ int modelindex2;
+ int clientNum; // 0 to (MAX_CLIENTS - 1), for players and corpses
+ int frame;
+
+ int solid; // for client side prediction, trap_linkentity sets this properly
+
+ int event; // impulse events -- muzzle flashes, footsteps, etc
+ int eventParm;
+
+ // for players
+ int powerups; // bit flags
+ int weapon; // determines weapon and flash model, etc
+ int legsAnim; // mask off ANIM_TOGGLEBIT
+ int torsoAnim; // mask off ANIM_TOGGLEBIT
+
+ int generic1;
+} entityState_t;
+
+typedef enum {
+ CA_UNINITIALIZED,
+ CA_DISCONNECTED, // not talking to a server
+ CA_AUTHORIZING, // not used any more, was checking cd key
+ CA_CONNECTING, // sending request packets to the server
+ CA_CHALLENGING, // sending challenge packets to the server
+ CA_CONNECTED, // netchan_t established, getting gamestate
+ CA_LOADING, // only during cgame initialization, never during main loop
+ CA_PRIMED, // got gamestate, waiting for first frame
+ CA_ACTIVE, // game views should be displayed
+ CA_CINEMATIC // playing a cinematic or a static pic, not connected to a server
+} connstate_t;
+
+// font support
+
+#define GLYPH_START 0
+#define GLYPH_END 255
+#define GLYPH_CHARSTART 32
+#define GLYPH_CHAREND 127
+#define GLYPHS_PER_FONT GLYPH_END - GLYPH_START + 1
+typedef struct {
+ int height; // number of scan lines
+ int top; // top of glyph in buffer
+ int bottom; // bottom of glyph in buffer
+ int pitch; // width for copying
+ int xSkip; // x adjustment
+ int imageWidth; // width of actual image
+ int imageHeight; // height of actual image
+ float s; // x offset in image where glyph starts
+ float t; // y offset in image where glyph starts
+ float s2;
+ float t2;
+ qhandle_t glyph; // handle to the shader with the glyph
+ char shaderName[32];
+} glyphInfo_t;
+
+typedef struct {
+ glyphInfo_t glyphs [GLYPHS_PER_FONT];
+ float glyphScale;
+ char name[MAX_QPATH];
+} fontInfo_t;
+
+#define Square(x) ((x)*(x))
+
+// real time
+//=============================================
+
+
+typedef struct qtime_s {
+ int tm_sec; /* seconds after the minute - [0,59] */
+ int tm_min; /* minutes after the hour - [0,59] */
+ int tm_hour; /* hours since midnight - [0,23] */
+ int tm_mday; /* day of the month - [1,31] */
+ int tm_mon; /* months since January - [0,11] */
+ int tm_year; /* years since 1900 */
+ int tm_wday; /* days since Sunday - [0,6] */
+ int tm_yday; /* days since January 1 - [0,365] */
+ int tm_isdst; /* daylight savings time flag */
+} qtime_t;
+
+
+// server browser sources
+// TTimo: AS_MPLAYER is no longer used
+#define AS_LOCAL 0
+#define AS_MPLAYER 1
+#define AS_GLOBAL 2
+#define AS_FAVORITES 3
+
+
+// cinematic states
+typedef enum {
+ FMV_IDLE,
+ FMV_PLAY, // play
+ FMV_EOF, // all other conditions, i.e. stop/EOF/abort
+ FMV_ID_BLT,
+ FMV_ID_IDLE,
+ FMV_LOOPED,
+ FMV_ID_WAIT
+} e_status;
+
+typedef enum _flag_status {
+ FLAG_ATBASE = 0,
+ FLAG_TAKEN, // CTF
+ FLAG_TAKEN_RED, // One Flag CTF
+ FLAG_TAKEN_BLUE, // One Flag CTF
+ FLAG_DROPPED
+} flagStatus_t;
+
+
+
+#define MAX_GLOBAL_SERVERS 4096
+#define MAX_OTHER_SERVERS 128
+#define MAX_PINGREQUESTS 32
+#define MAX_SERVERSTATUSREQUESTS 16
+
+#define SAY_ALL 0
+#define SAY_TEAM 1
+#define SAY_TELL 2
+
+#define CDKEY_LEN 16
+#define CDCHKSUM_LEN 2
+
+
+#endif // __Q_SHARED_H
diff --git a/code/game/surfaceflags.h b/code/game/surfaceflags.h
new file mode 100755
index 0000000..f35369e
--- /dev/null
+++ b/code/game/surfaceflags.h
@@ -0,0 +1,80 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// This file must be identical in the quake and utils directories
+
+// contents flags are seperate bits
+// a given brush can contribute multiple content bits
+
+// these definitions also need to be in q_shared.h!
+
+#define CONTENTS_SOLID 1 // an eye is never valid in a solid
+#define CONTENTS_LAVA 8
+#define CONTENTS_SLIME 16
+#define CONTENTS_WATER 32
+#define CONTENTS_FOG 64
+
+#define CONTENTS_NOTTEAM1 0x0080
+#define CONTENTS_NOTTEAM2 0x0100
+#define CONTENTS_NOBOTCLIP 0x0200
+
+#define CONTENTS_AREAPORTAL 0x8000
+
+#define CONTENTS_PLAYERCLIP 0x10000
+#define CONTENTS_MONSTERCLIP 0x20000
+//bot specific contents types
+#define CONTENTS_TELEPORTER 0x40000
+#define CONTENTS_JUMPPAD 0x80000
+#define CONTENTS_CLUSTERPORTAL 0x100000
+#define CONTENTS_DONOTENTER 0x200000
+#define CONTENTS_BOTCLIP 0x400000
+#define CONTENTS_MOVER 0x800000
+
+#define CONTENTS_ORIGIN 0x1000000 // removed before bsping an entity
+
+#define CONTENTS_BODY 0x2000000 // should never be on a brush, only in game
+#define CONTENTS_CORPSE 0x4000000
+#define CONTENTS_DETAIL 0x8000000 // brushes not used for the bsp
+#define CONTENTS_STRUCTURAL 0x10000000 // brushes used for the bsp
+#define CONTENTS_TRANSLUCENT 0x20000000 // don't consume surface fragments inside
+#define CONTENTS_TRIGGER 0x40000000
+#define CONTENTS_NODROP 0x80000000 // don't leave bodies or items (death fog, lava)
+
+#define SURF_NODAMAGE 0x1 // never give falling damage
+#define SURF_SLICK 0x2 // effects game physics
+#define SURF_SKY 0x4 // lighting from environment map
+#define SURF_LADDER 0x8
+#define SURF_NOIMPACT 0x10 // don't make missile explosions
+#define SURF_NOMARKS 0x20 // don't leave missile marks
+#define SURF_FLESH 0x40 // make flesh sounds and effects
+#define SURF_NODRAW 0x80 // don't generate a drawsurface at all
+#define SURF_HINT 0x100 // make a primary bsp splitter
+#define SURF_SKIP 0x200 // completely ignore, allowing non-closed brushes
+#define SURF_NOLIGHTMAP 0x400 // surface doesn't need a lightmap
+#define SURF_POINTLIGHT 0x800 // generate lighting info at vertexes
+#define SURF_METALSTEPS 0x1000 // clanking footsteps
+#define SURF_NOSTEPS 0x2000 // no footstep sounds
+#define SURF_NONSOLID 0x4000 // don't collide against curves with this set
+#define SURF_LIGHTFILTER 0x8000 // act as a light filter during q3map -light
+#define SURF_ALPHASHADOW 0x10000 // do per-pixel light shadow casting in q3map
+#define SURF_NODLIGHT 0x20000 // don't dlight even if solid (solid lava, skies)
+#define SURF_DUST 0x40000 // leave a dust trail when walking on this surface
diff --git a/code/game/syn.h b/code/game/syn.h
new file mode 100755
index 0000000..0109966
--- /dev/null
+++ b/code/game/syn.h
@@ -0,0 +1,34 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#define CONTEXT_ALL 0xFFFFFFFF
+#define CONTEXT_NORMAL 1
+#define CONTEXT_NEARBYITEM 2
+#define CONTEXT_CTFREDTEAM 4
+#define CONTEXT_CTFBLUETEAM 8
+#define CONTEXT_REPLY 16
+#define CONTEXT_OBELISKREDTEAM 32
+#define CONTEXT_OBELISKBLUETEAM 64
+#define CONTEXT_HARVESTERREDTEAM 128
+#define CONTEXT_HARVESTERBLUETEAM 256
+
+#define CONTEXT_NAMES 1024
diff --git a/code/installdebug.bat b/code/installdebug.bat
new file mode 100755
index 0000000..c853faa
--- /dev/null
+++ b/code/installdebug.bat
@@ -0,0 +1,6 @@
+call closefiles
+copy debug\quake3.exe g:\quake3
+copy debug\qagamex86.dll g:\quake3
+copy debug\cgamex86.dll g:\quake3
+copy debug\uix86.dll g:\quake3
+
diff --git a/code/installrelease.bat b/code/installrelease.bat
new file mode 100755
index 0000000..efd35da
--- /dev/null
+++ b/code/installrelease.bat
@@ -0,0 +1,14 @@
+cd game
+call game_ta
+call game
+cd ..\cgame
+call cgame_ta
+call cgame
+cd ..\ui
+call ui
+cd ..\q3_ui
+call q3_ui
+cd ..
+call closefiles
+copy release_ta\quake3.exe g:\quake3\quake3.exe
+call installvms \ No newline at end of file
diff --git a/code/installvms.bat b/code/installvms.bat
new file mode 100755
index 0000000..468a083
--- /dev/null
+++ b/code/installvms.bat
@@ -0,0 +1,7 @@
+copy \quake3\missionpack\vm\cgame.* g:\quake3\missionpack\vm
+copy \quake3\missionpack\vm\qagame.* g:\quake3\missionpack\vm
+copy \quake3\missionpack\vm\ui.* g:\quake3\missionpack\vm
+copy \quake3\baseq3\vm\cgame.* g:\quake3\baseq3\vm
+copy \quake3\baseq3\vm\qagame.* g:\quake3\baseq3\vm
+copy \quake3\baseq3\vm\q3_ui.qvm g:\quake3\baseq3\vm\ui.qvm
+
diff --git a/code/jpeg-6/README b/code/jpeg-6/README
new file mode 100755
index 0000000..86cc206
--- /dev/null
+++ b/code/jpeg-6/README
@@ -0,0 +1,385 @@
+The Independent JPEG Group's JPEG software
+==========================================
+
+README for release 6b of 27-Mar-1998
+====================================
+
+This distribution contains the sixth public release of the Independent JPEG
+Group's free JPEG software. You are welcome to redistribute this software and
+to use it for any purpose, subject to the conditions under LEGAL ISSUES, below.
+
+Serious users of this software (particularly those incorporating it into
+larger programs) should contact IJG at jpeg-info@uunet.uu.net to be added to
+our electronic mailing list. Mailing list members are notified of updates
+and have a chance to participate in technical discussions, etc.
+
+This software is the work of Tom Lane, Philip Gladstone, Jim Boucher,
+Lee Crocker, Julian Minguillon, Luis Ortiz, George Phillips, Davide Rossi,
+Guido Vollbeding, Ge' Weijers, and other members of the Independent JPEG
+Group.
+
+IJG is not affiliated with the official ISO JPEG standards committee.
+
+
+DOCUMENTATION ROADMAP
+=====================
+
+This file contains the following sections:
+
+OVERVIEW General description of JPEG and the IJG software.
+LEGAL ISSUES Copyright, lack of warranty, terms of distribution.
+REFERENCES Where to learn more about JPEG.
+ARCHIVE LOCATIONS Where to find newer versions of this software.
+RELATED SOFTWARE Other stuff you should get.
+FILE FORMAT WARS Software *not* to get.
+TO DO Plans for future IJG releases.
+
+Other documentation files in the distribution are:
+
+User documentation:
+ install.doc How to configure and install the IJG software.
+ usage.doc Usage instructions for cjpeg, djpeg, jpegtran,
+ rdjpgcom, and wrjpgcom.
+ *.1 Unix-style man pages for programs (same info as usage.doc).
+ wizard.doc Advanced usage instructions for JPEG wizards only.
+ change.log Version-to-version change highlights.
+Programmer and internal documentation:
+ libjpeg.doc How to use the JPEG library in your own programs.
+ example.c Sample code for calling the JPEG library.
+ structure.doc Overview of the JPEG library's internal structure.
+ filelist.doc Road map of IJG files.
+ coderules.doc Coding style rules --- please read if you contribute code.
+
+Please read at least the files install.doc and usage.doc. Useful information
+can also be found in the JPEG FAQ (Frequently Asked Questions) article. See
+ARCHIVE LOCATIONS below to find out where to obtain the FAQ article.
+
+If you want to understand how the JPEG code works, we suggest reading one or
+more of the REFERENCES, then looking at the documentation files (in roughly
+the order listed) before diving into the code.
+
+
+OVERVIEW
+========
+
+This package contains C software to implement JPEG image compression and
+decompression. JPEG (pronounced "jay-peg") is a standardized compression
+method for full-color and gray-scale images. JPEG is intended for compressing
+"real-world" scenes; line drawings, cartoons and other non-realistic images
+are not its strong suit. JPEG is lossy, meaning that the output image is not
+exactly identical to the input image. Hence you must not use JPEG if you
+have to have identical output bits. However, on typical photographic images,
+very good compression levels can be obtained with no visible change, and
+remarkably high compression levels are possible if you can tolerate a
+low-quality image. For more details, see the references, or just experiment
+with various compression settings.
+
+This software implements JPEG baseline, extended-sequential, and progressive
+compression processes. Provision is made for supporting all variants of these
+processes, although some uncommon parameter settings aren't implemented yet.
+For legal reasons, we are not distributing code for the arithmetic-coding
+variants of JPEG; see LEGAL ISSUES. We have made no provision for supporting
+the hierarchical or lossless processes defined in the standard.
+
+We provide a set of library routines for reading and writing JPEG image files,
+plus two sample applications "cjpeg" and "djpeg", which use the library to
+perform conversion between JPEG and some other popular image file formats.
+The library is intended to be reused in other applications.
+
+In order to support file conversion and viewing software, we have included
+considerable functionality beyond the bare JPEG coding/decoding capability;
+for example, the color quantization modules are not strictly part of JPEG
+decoding, but they are essential for output to colormapped file formats or
+colormapped displays. These extra functions can be compiled out of the
+library if not required for a particular application. We have also included
+"jpegtran", a utility for lossless transcoding between different JPEG
+processes, and "rdjpgcom" and "wrjpgcom", two simple applications for
+inserting and extracting textual comments in JFIF files.
+
+The emphasis in designing this software has been on achieving portability and
+flexibility, while also making it fast enough to be useful. In particular,
+the software is not intended to be read as a tutorial on JPEG. (See the
+REFERENCES section for introductory material.) Rather, it is intended to
+be reliable, portable, industrial-strength code. We do not claim to have
+achieved that goal in every aspect of the software, but we strive for it.
+
+We welcome the use of this software as a component of commercial products.
+No royalty is required, but we do ask for an acknowledgement in product
+documentation, as described under LEGAL ISSUES.
+
+
+LEGAL ISSUES
+============
+
+In plain English:
+
+1. We don't promise that this software works. (But if you find any bugs,
+ please let us know!)
+2. You can use this software for whatever you want. You don't have to pay us.
+3. You may not pretend that you wrote this software. If you use it in a
+ program, you must acknowledge somewhere in your documentation that
+ you've used the IJG code.
+
+In legalese:
+
+The authors make NO WARRANTY or representation, either express or implied,
+with respect to this software, its quality, accuracy, merchantability, or
+fitness for a particular purpose. This software is provided "AS IS", and you,
+its user, assume the entire risk as to its quality and accuracy.
+
+This software is copyright (C) 1991-1998, Thomas G. Lane.
+All Rights Reserved except as specified below.
+
+Permission is hereby granted to use, copy, modify, and distribute this
+software (or portions thereof) for any purpose, without fee, subject to these
+conditions:
+(1) If any part of the source code for this software is distributed, then this
+README file must be included, with this copyright and no-warranty notice
+unaltered; and any additions, deletions, or changes to the original files
+must be clearly indicated in accompanying documentation.
+(2) If only executable code is distributed, then the accompanying
+documentation must state that "this software is based in part on the work of
+the Independent JPEG Group".
+(3) Permission for use of this software is granted only if the user accepts
+full responsibility for any undesirable consequences; the authors accept
+NO LIABILITY for damages of any kind.
+
+These conditions apply to any software derived from or based on the IJG code,
+not just to the unmodified library. If you use our work, you ought to
+acknowledge us.
+
+Permission is NOT granted for the use of any IJG author's name or company name
+in advertising or publicity relating to this software or products derived from
+it. This software may be referred to only as "the Independent JPEG Group's
+software".
+
+We specifically permit and encourage the use of this software as the basis of
+commercial products, provided that all warranty or liability claims are
+assumed by the product vendor.
+
+
+ansi2knr.c is included in this distribution by permission of L. Peter Deutsch,
+sole proprietor of its copyright holder, Aladdin Enterprises of Menlo Park, CA.
+ansi2knr.c is NOT covered by the above copyright and conditions, but instead
+by the usual distribution terms of the Free Software Foundation; principally,
+that you must include source code if you redistribute it. (See the file
+ansi2knr.c for full details.) However, since ansi2knr.c is not needed as part
+of any program generated from the IJG code, this does not limit you more than
+the foregoing paragraphs do.
+
+The Unix configuration script "configure" was produced with GNU Autoconf.
+It is copyright by the Free Software Foundation but is freely distributable.
+The same holds for its supporting scripts (config.guess, config.sub,
+ltconfig, ltmain.sh). Another support script, install-sh, is copyright
+by M.I.T. but is also freely distributable.
+
+It appears that the arithmetic coding option of the JPEG spec is covered by
+patents owned by IBM, AT&T, and Mitsubishi. Hence arithmetic coding cannot
+legally be used without obtaining one or more licenses. For this reason,
+support for arithmetic coding has been removed from the free JPEG software.
+(Since arithmetic coding provides only a marginal gain over the unpatented
+Huffman mode, it is unlikely that very many implementations will support it.)
+So far as we are aware, there are no patent restrictions on the remaining
+code.
+
+The IJG distribution formerly included code to read and write GIF files.
+To avoid entanglement with the Unisys LZW patent, GIF reading support has
+been removed altogether, and the GIF writer has been simplified to produce
+"uncompressed GIFs". This technique does not use the LZW algorithm; the
+resulting GIF files are larger than usual, but are readable by all standard
+GIF decoders.
+
+We are required to state that
+ "The Graphics Interchange Format(c) is the Copyright property of
+ CompuServe Incorporated. GIF(sm) is a Service Mark property of
+ CompuServe Incorporated."
+
+
+REFERENCES
+==========
+
+We highly recommend reading one or more of these references before trying to
+understand the innards of the JPEG software.
+
+The best short technical introduction to the JPEG compression algorithm is
+ Wallace, Gregory K. "The JPEG Still Picture Compression Standard",
+ Communications of the ACM, April 1991 (vol. 34 no. 4), pp. 30-44.
+(Adjacent articles in that issue discuss MPEG motion picture compression,
+applications of JPEG, and related topics.) If you don't have the CACM issue
+handy, a PostScript file containing a revised version of Wallace's article is
+available at ftp://ftp.uu.net/graphics/jpeg/wallace.ps.gz. The file (actually
+a preprint for an article that appeared in IEEE Trans. Consumer Electronics)
+omits the sample images that appeared in CACM, but it includes corrections
+and some added material. Note: the Wallace article is copyright ACM and IEEE,
+and it may not be used for commercial purposes.
+
+A somewhat less technical, more leisurely introduction to JPEG can be found in
+"The Data Compression Book" by Mark Nelson and Jean-loup Gailly, published by
+M&T Books (New York), 2nd ed. 1996, ISBN 1-55851-434-1. This book provides
+good explanations and example C code for a multitude of compression methods
+including JPEG. It is an excellent source if you are comfortable reading C
+code but don't know much about data compression in general. The book's JPEG
+sample code is far from industrial-strength, but when you are ready to look
+at a full implementation, you've got one here...
+
+The best full description of JPEG is the textbook "JPEG Still Image Data
+Compression Standard" by William B. Pennebaker and Joan L. Mitchell, published
+by Van Nostrand Reinhold, 1993, ISBN 0-442-01272-1. Price US$59.95, 638 pp.
+The book includes the complete text of the ISO JPEG standards (DIS 10918-1
+and draft DIS 10918-2). This is by far the most complete exposition of JPEG
+in existence, and we highly recommend it.
+
+The JPEG standard itself is not available electronically; you must order a
+paper copy through ISO or ITU. (Unless you feel a need to own a certified
+official copy, we recommend buying the Pennebaker and Mitchell book instead;
+it's much cheaper and includes a great deal of useful explanatory material.)
+In the USA, copies of the standard may be ordered from ANSI Sales at (212)
+642-4900, or from Global Engineering Documents at (800) 854-7179. (ANSI
+doesn't take credit card orders, but Global does.) It's not cheap: as of
+1992, ANSI was charging $95 for Part 1 and $47 for Part 2, plus 7%
+shipping/handling. The standard is divided into two parts, Part 1 being the
+actual specification, while Part 2 covers compliance testing methods. Part 1
+is titled "Digital Compression and Coding of Continuous-tone Still Images,
+Part 1: Requirements and guidelines" and has document numbers ISO/IEC IS
+10918-1, ITU-T T.81. Part 2 is titled "Digital Compression and Coding of
+Continuous-tone Still Images, Part 2: Compliance testing" and has document
+numbers ISO/IEC IS 10918-2, ITU-T T.83.
+
+Some extensions to the original JPEG standard are defined in JPEG Part 3,
+a newer ISO standard numbered ISO/IEC IS 10918-3 and ITU-T T.84. IJG
+currently does not support any Part 3 extensions.
+
+The JPEG standard does not specify all details of an interchangeable file
+format. For the omitted details we follow the "JFIF" conventions, revision
+1.02. A copy of the JFIF spec is available from:
+ Literature Department
+ C-Cube Microsystems, Inc.
+ 1778 McCarthy Blvd.
+ Milpitas, CA 95035
+ phone (408) 944-6300, fax (408) 944-6314
+A PostScript version of this document is available by FTP at
+ftp://ftp.uu.net/graphics/jpeg/jfif.ps.gz. There is also a plain text
+version at ftp://ftp.uu.net/graphics/jpeg/jfif.txt.gz, but it is missing
+the figures.
+
+The TIFF 6.0 file format specification can be obtained by FTP from
+ftp://ftp.sgi.com/graphics/tiff/TIFF6.ps.gz. The JPEG incorporation scheme
+found in the TIFF 6.0 spec of 3-June-92 has a number of serious problems.
+IJG does not recommend use of the TIFF 6.0 design (TIFF Compression tag 6).
+Instead, we recommend the JPEG design proposed by TIFF Technical Note #2
+(Compression tag 7). Copies of this Note can be obtained from ftp.sgi.com or
+from ftp://ftp.uu.net/graphics/jpeg/. It is expected that the next revision
+of the TIFF spec will replace the 6.0 JPEG design with the Note's design.
+Although IJG's own code does not support TIFF/JPEG, the free libtiff library
+uses our library to implement TIFF/JPEG per the Note. libtiff is available
+from ftp://ftp.sgi.com/graphics/tiff/.
+
+
+ARCHIVE LOCATIONS
+=================
+
+The "official" archive site for this software is ftp.uu.net (Internet
+address 192.48.96.9). The most recent released version can always be found
+there in directory graphics/jpeg. This particular version will be archived
+as ftp://ftp.uu.net/graphics/jpeg/jpegsrc.v6b.tar.gz. If you don't have
+direct Internet access, UUNET's archives are also available via UUCP; contact
+help@uunet.uu.net for information on retrieving files that way.
+
+Numerous Internet sites maintain copies of the UUNET files. However, only
+ftp.uu.net is guaranteed to have the latest official version.
+
+You can also obtain this software in DOS-compatible "zip" archive format from
+the SimTel archives (ftp://ftp.simtel.net/pub/simtelnet/msdos/graphics/), or
+on CompuServe in the Graphics Support forum (GO CIS:GRAPHSUP), library 12
+"JPEG Tools". Again, these versions may sometimes lag behind the ftp.uu.net
+release.
+
+The JPEG FAQ (Frequently Asked Questions) article is a useful source of
+general information about JPEG. It is updated constantly and therefore is
+not included in this distribution. The FAQ is posted every two weeks to
+Usenet newsgroups comp.graphics.misc, news.answers, and other groups.
+It is available on the World Wide Web at http://www.faqs.org/faqs/jpeg-faq/
+and other news.answers archive sites, including the official news.answers
+archive at rtfm.mit.edu: ftp://rtfm.mit.edu/pub/usenet/news.answers/jpeg-faq/.
+If you don't have Web or FTP access, send e-mail to mail-server@rtfm.mit.edu
+with body
+ send usenet/news.answers/jpeg-faq/part1
+ send usenet/news.answers/jpeg-faq/part2
+
+
+RELATED SOFTWARE
+================
+
+Numerous viewing and image manipulation programs now support JPEG. (Quite a
+few of them use this library to do so.) The JPEG FAQ described above lists
+some of the more popular free and shareware viewers, and tells where to
+obtain them on Internet.
+
+If you are on a Unix machine, we highly recommend Jef Poskanzer's free
+PBMPLUS software, which provides many useful operations on PPM-format image
+files. In particular, it can convert PPM images to and from a wide range of
+other formats, thus making cjpeg/djpeg considerably more useful. The latest
+version is distributed by the NetPBM group, and is available from numerous
+sites, notably ftp://wuarchive.wustl.edu/graphics/graphics/packages/NetPBM/.
+Unfortunately PBMPLUS/NETPBM is not nearly as portable as the IJG software is;
+you are likely to have difficulty making it work on any non-Unix machine.
+
+A different free JPEG implementation, written by the PVRG group at Stanford,
+is available from ftp://havefun.stanford.edu/pub/jpeg/. This program
+is designed for research and experimentation rather than production use;
+it is slower, harder to use, and less portable than the IJG code, but it
+is easier to read and modify. Also, the PVRG code supports lossless JPEG,
+which we do not. (On the other hand, it doesn't do progressive JPEG.)
+
+
+FILE FORMAT WARS
+================
+
+Some JPEG programs produce files that are not compatible with our library.
+The root of the problem is that the ISO JPEG committee failed to specify a
+concrete file format. Some vendors "filled in the blanks" on their own,
+creating proprietary formats that no one else could read. (For example, none
+of the early commercial JPEG implementations for the Macintosh were able to
+exchange compressed files.)
+
+The file format we have adopted is called JFIF (see REFERENCES). This format
+has been agreed to by a number of major commercial JPEG vendors, and it has
+become the de facto standard. JFIF is a minimal or "low end" representation.
+We recommend the use of TIFF/JPEG (TIFF revision 6.0 as modified by TIFF
+Technical Note #2) for "high end" applications that need to record a lot of
+additional data about an image. TIFF/JPEG is fairly new and not yet widely
+supported, unfortunately.
+
+The upcoming JPEG Part 3 standard defines a file format called SPIFF.
+SPIFF is interoperable with JFIF, in the sense that most JFIF decoders should
+be able to read the most common variant of SPIFF. SPIFF has some technical
+advantages over JFIF, but its major claim to fame is simply that it is an
+official standard rather than an informal one. At this point it is unclear
+whether SPIFF will supersede JFIF or whether JFIF will remain the de-facto
+standard. IJG intends to support SPIFF once the standard is frozen, but we
+have not decided whether it should become our default output format or not.
+(In any case, our decoder will remain capable of reading JFIF indefinitely.)
+
+Various proprietary file formats incorporating JPEG compression also exist.
+We have little or no sympathy for the existence of these formats. Indeed,
+one of the original reasons for developing this free software was to help
+force convergence on common, open format standards for JPEG files. Don't
+use a proprietary file format!
+
+
+TO DO
+=====
+
+The major thrust for v7 will probably be improvement of visual quality.
+The current method for scaling the quantization tables is known not to be
+very good at low Q values. We also intend to investigate block boundary
+smoothing, "poor man's variable quantization", and other means of improving
+quality-vs-file-size performance without sacrificing compatibility.
+
+In future versions, we are considering supporting some of the upcoming JPEG
+Part 3 extensions --- principally, variable quantization and the SPIFF file
+format.
+
+As always, speeding things up is of great interest.
+
+Please send bug reports, offers of help, etc. to jpeg-info@uunet.uu.net.
diff --git a/code/jpeg-6/jcapimin.c b/code/jpeg-6/jcapimin.c
new file mode 100755
index 0000000..6d603e7
--- /dev/null
+++ b/code/jpeg-6/jcapimin.c
@@ -0,0 +1,228 @@
+/*
+ * jcapimin.c
+ *
+ * Copyright (C) 1994-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains application interface code for the compression half
+ * of the JPEG library. These are the "minimum" API routines that may be
+ * needed in either the normal full-compression case or the transcoding-only
+ * case.
+ *
+ * Most of the routines intended to be called directly by an application
+ * are in this file or in jcapistd.c. But also see jcparam.c for
+ * parameter-setup helper routines, jcomapi.c for routines shared by
+ * compression and decompression, and jctrans.c for the transcoding case.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/*
+ * Initialization of a JPEG compression object.
+ * The error manager must already be set up (in case memory manager fails).
+ */
+
+GLOBAL void
+jpeg_create_compress (j_compress_ptr cinfo)
+{
+ int i;
+
+ /* For debugging purposes, zero the whole master structure.
+ * But error manager pointer is already there, so save and restore it.
+ */
+ {
+ struct jpeg_error_mgr * err = cinfo->err;
+ MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
+ cinfo->err = err;
+ }
+ cinfo->is_decompressor = FALSE;
+
+ /* Initialize a memory manager instance for this object */
+ jinit_memory_mgr((j_common_ptr) cinfo);
+
+ /* Zero out pointers to permanent structures. */
+ cinfo->progress = NULL;
+ cinfo->dest = NULL;
+
+ cinfo->comp_info = NULL;
+
+ for (i = 0; i < NUM_QUANT_TBLS; i++)
+ cinfo->quant_tbl_ptrs[i] = NULL;
+
+ for (i = 0; i < NUM_HUFF_TBLS; i++) {
+ cinfo->dc_huff_tbl_ptrs[i] = NULL;
+ cinfo->ac_huff_tbl_ptrs[i] = NULL;
+ }
+
+ cinfo->input_gamma = 1.0; /* in case application forgets */
+
+ /* OK, I'm ready */
+ cinfo->global_state = CSTATE_START;
+}
+
+
+/*
+ * Destruction of a JPEG compression object
+ */
+
+GLOBAL void
+jpeg_destroy_compress (j_compress_ptr cinfo)
+{
+ jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
+}
+
+
+/*
+ * Abort processing of a JPEG compression operation,
+ * but don't destroy the object itself.
+ */
+
+GLOBAL void
+jpeg_abort_compress (j_compress_ptr cinfo)
+{
+ jpeg_abort((j_common_ptr) cinfo); /* use common routine */
+}
+
+
+/*
+ * Forcibly suppress or un-suppress all quantization and Huffman tables.
+ * Marks all currently defined tables as already written (if suppress)
+ * or not written (if !suppress). This will control whether they get emitted
+ * by a subsequent jpeg_start_compress call.
+ *
+ * This routine is exported for use by applications that want to produce
+ * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
+ * since it is called by jpeg_start_compress, we put it here --- otherwise
+ * jcparam.o would be linked whether the application used it or not.
+ */
+
+GLOBAL void
+jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
+{
+ int i;
+ JQUANT_TBL * qtbl;
+ JHUFF_TBL * htbl;
+
+ for (i = 0; i < NUM_QUANT_TBLS; i++) {
+ if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
+ qtbl->sent_table = suppress;
+ }
+
+ for (i = 0; i < NUM_HUFF_TBLS; i++) {
+ if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
+ htbl->sent_table = suppress;
+ if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
+ htbl->sent_table = suppress;
+ }
+}
+
+
+/*
+ * Finish JPEG compression.
+ *
+ * If a multipass operating mode was selected, this may do a great deal of
+ * work including most of the actual output.
+ */
+
+GLOBAL void
+jpeg_finish_compress (j_compress_ptr cinfo)
+{
+ JDIMENSION iMCU_row;
+
+ if (cinfo->global_state == CSTATE_SCANNING ||
+ cinfo->global_state == CSTATE_RAW_OK) {
+ /* Terminate first pass */
+ if (cinfo->next_scanline < cinfo->image_height)
+ ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
+ (*cinfo->master->finish_pass) (cinfo);
+ } else if (cinfo->global_state != CSTATE_WRCOEFS)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ /* Perform any remaining passes */
+ while (! cinfo->master->is_last_pass) {
+ (*cinfo->master->prepare_for_pass) (cinfo);
+ for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
+ if (cinfo->progress != NULL) {
+ cinfo->progress->pass_counter = (long) iMCU_row;
+ cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
+ (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+ }
+ /* We bypass the main controller and invoke coef controller directly;
+ * all work is being done from the coefficient buffer.
+ */
+ if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
+ ERREXIT(cinfo, JERR_CANT_SUSPEND);
+ }
+ (*cinfo->master->finish_pass) (cinfo);
+ }
+ /* Write EOI, do final cleanup */
+ (*cinfo->marker->write_file_trailer) (cinfo);
+ (*cinfo->dest->term_destination) (cinfo);
+ /* We can use jpeg_abort to release memory and reset global_state */
+ jpeg_abort((j_common_ptr) cinfo);
+}
+
+
+/*
+ * Write a special marker.
+ * This is only recommended for writing COM or APPn markers.
+ * Must be called after jpeg_start_compress() and before
+ * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
+ */
+
+GLOBAL void
+jpeg_write_marker (j_compress_ptr cinfo, int marker,
+ const JOCTET *dataptr, unsigned int datalen)
+{
+ if (cinfo->next_scanline != 0 ||
+ (cinfo->global_state != CSTATE_SCANNING &&
+ cinfo->global_state != CSTATE_RAW_OK &&
+ cinfo->global_state != CSTATE_WRCOEFS))
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+ (*cinfo->marker->write_any_marker) (cinfo, marker, dataptr, datalen);
+}
+
+
+/*
+ * Alternate compression function: just write an abbreviated table file.
+ * Before calling this, all parameters and a data destination must be set up.
+ *
+ * To produce a pair of files containing abbreviated tables and abbreviated
+ * image data, one would proceed as follows:
+ *
+ * initialize JPEG object
+ * set JPEG parameters
+ * set destination to table file
+ * jpeg_write_tables(cinfo);
+ * set destination to image file
+ * jpeg_start_compress(cinfo, FALSE);
+ * write data...
+ * jpeg_finish_compress(cinfo);
+ *
+ * jpeg_write_tables has the side effect of marking all tables written
+ * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
+ * will not re-emit the tables unless it is passed write_all_tables=TRUE.
+ */
+
+GLOBAL void
+jpeg_write_tables (j_compress_ptr cinfo)
+{
+ if (cinfo->global_state != CSTATE_START)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+ /* (Re)initialize error mgr and destination modules */
+ (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
+ (*cinfo->dest->init_destination) (cinfo);
+ /* Initialize the marker writer ... bit of a crock to do it here. */
+ jinit_marker_writer(cinfo);
+ /* Write them tables! */
+ (*cinfo->marker->write_tables_only) (cinfo);
+ /* And clean up. */
+ (*cinfo->dest->term_destination) (cinfo);
+ /* We can use jpeg_abort to release memory. */
+ jpeg_abort((j_common_ptr) cinfo);
+}
diff --git a/code/jpeg-6/jcapistd.c b/code/jpeg-6/jcapistd.c
new file mode 100755
index 0000000..8c3721d
--- /dev/null
+++ b/code/jpeg-6/jcapistd.c
@@ -0,0 +1,161 @@
+/*
+ * jcapistd.c
+ *
+ * Copyright (C) 1994-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains application interface code for the compression half
+ * of the JPEG library. These are the "standard" API routines that are
+ * used in the normal full-compression case. They are not used by a
+ * transcoding-only application. Note that if an application links in
+ * jpeg_start_compress, it will end up linking in the entire compressor.
+ * We thus must separate this file from jcapimin.c to avoid linking the
+ * whole compression library into a transcoder.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/*
+ * Compression initialization.
+ * Before calling this, all parameters and a data destination must be set up.
+ *
+ * We require a write_all_tables parameter as a failsafe check when writing
+ * multiple datastreams from the same compression object. Since prior runs
+ * will have left all the tables marked sent_table=TRUE, a subsequent run
+ * would emit an abbreviated stream (no tables) by default. This may be what
+ * is wanted, but for safety's sake it should not be the default behavior:
+ * programmers should have to make a deliberate choice to emit abbreviated
+ * images. Therefore the documentation and examples should encourage people
+ * to pass write_all_tables=TRUE; then it will take active thought to do the
+ * wrong thing.
+ */
+
+GLOBAL void
+jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
+{
+ if (cinfo->global_state != CSTATE_START)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+ if (write_all_tables)
+ jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
+
+ /* (Re)initialize error mgr and destination modules */
+ (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
+ (*cinfo->dest->init_destination) (cinfo);
+ /* Perform master selection of active modules */
+ jinit_compress_master(cinfo);
+ /* Set up for the first pass */
+ (*cinfo->master->prepare_for_pass) (cinfo);
+ /* Ready for application to drive first pass through jpeg_write_scanlines
+ * or jpeg_write_raw_data.
+ */
+ cinfo->next_scanline = 0;
+ cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
+}
+
+
+/*
+ * Write some scanlines of data to the JPEG compressor.
+ *
+ * The return value will be the number of lines actually written.
+ * This should be less than the supplied num_lines only in case that
+ * the data destination module has requested suspension of the compressor,
+ * or if more than image_height scanlines are passed in.
+ *
+ * Note: we warn about excess calls to jpeg_write_scanlines() since
+ * this likely signals an application programmer error. However,
+ * excess scanlines passed in the last valid call are *silently* ignored,
+ * so that the application need not adjust num_lines for end-of-image
+ * when using a multiple-scanline buffer.
+ */
+
+GLOBAL JDIMENSION
+jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
+ JDIMENSION num_lines)
+{
+ JDIMENSION row_ctr, rows_left;
+
+ if (cinfo->global_state != CSTATE_SCANNING)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ if (cinfo->next_scanline >= cinfo->image_height)
+ WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
+
+ /* Call progress monitor hook if present */
+ if (cinfo->progress != NULL) {
+ cinfo->progress->pass_counter = (long) cinfo->next_scanline;
+ cinfo->progress->pass_limit = (long) cinfo->image_height;
+ (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+ }
+
+ /* Give master control module another chance if this is first call to
+ * jpeg_write_scanlines. This lets output of the frame/scan headers be
+ * delayed so that application can write COM, etc, markers between
+ * jpeg_start_compress and jpeg_write_scanlines.
+ */
+ if (cinfo->master->call_pass_startup)
+ (*cinfo->master->pass_startup) (cinfo);
+
+ /* Ignore any extra scanlines at bottom of image. */
+ rows_left = cinfo->image_height - cinfo->next_scanline;
+ if (num_lines > rows_left)
+ num_lines = rows_left;
+
+ row_ctr = 0;
+ (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
+ cinfo->next_scanline += row_ctr;
+ return row_ctr;
+}
+
+
+/*
+ * Alternate entry point to write raw data.
+ * Processes exactly one iMCU row per call, unless suspended.
+ */
+
+GLOBAL JDIMENSION
+jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
+ JDIMENSION num_lines)
+{
+ JDIMENSION lines_per_iMCU_row;
+
+ if (cinfo->global_state != CSTATE_RAW_OK)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ if (cinfo->next_scanline >= cinfo->image_height) {
+ WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
+ return 0;
+ }
+
+ /* Call progress monitor hook if present */
+ if (cinfo->progress != NULL) {
+ cinfo->progress->pass_counter = (long) cinfo->next_scanline;
+ cinfo->progress->pass_limit = (long) cinfo->image_height;
+ (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+ }
+
+ /* Give master control module another chance if this is first call to
+ * jpeg_write_raw_data. This lets output of the frame/scan headers be
+ * delayed so that application can write COM, etc, markers between
+ * jpeg_start_compress and jpeg_write_raw_data.
+ */
+ if (cinfo->master->call_pass_startup)
+ (*cinfo->master->pass_startup) (cinfo);
+
+ /* Verify that at least one iMCU row has been passed. */
+ lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
+ if (num_lines < lines_per_iMCU_row)
+ ERREXIT(cinfo, JERR_BUFFER_SIZE);
+
+ /* Directly compress the row. */
+ if (! (*cinfo->coef->compress_data) (cinfo, data)) {
+ /* If compressor did not consume the whole row, suspend processing. */
+ return 0;
+ }
+
+ /* OK, we processed one iMCU row. */
+ cinfo->next_scanline += lines_per_iMCU_row;
+ return lines_per_iMCU_row;
+}
diff --git a/code/jpeg-6/jccoefct.c b/code/jpeg-6/jccoefct.c
new file mode 100755
index 0000000..9a33f7a
--- /dev/null
+++ b/code/jpeg-6/jccoefct.c
@@ -0,0 +1,448 @@
+/*
+ * jccoefct.c
+ *
+ * Copyright (C) 1994-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the coefficient buffer controller for compression.
+ * This controller is the top level of the JPEG compressor proper.
+ * The coefficient buffer lies between forward-DCT and entropy encoding steps.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* We use a full-image coefficient buffer when doing Huffman optimization,
+ * and also for writing multiple-scan JPEG files. In all cases, the DCT
+ * step is run during the first pass, and subsequent passes need only read
+ * the buffered coefficients.
+ */
+#ifdef ENTROPY_OPT_SUPPORTED
+#define FULL_COEF_BUFFER_SUPPORTED
+#else
+#ifdef C_MULTISCAN_FILES_SUPPORTED
+#define FULL_COEF_BUFFER_SUPPORTED
+#endif
+#endif
+
+
+/* Private buffer controller object */
+
+typedef struct {
+ struct jpeg_c_coef_controller pub; /* public fields */
+
+ JDIMENSION iMCU_row_num; /* iMCU row # within image */
+ JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
+ int MCU_vert_offset; /* counts MCU rows within iMCU row */
+ int MCU_rows_per_iMCU_row; /* number of such rows needed */
+
+ /* For single-pass compression, it's sufficient to buffer just one MCU
+ * (although this may prove a bit slow in practice). We allocate a
+ * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
+ * MCU constructed and sent. (On 80x86, the workspace is FAR even though
+ * it's not really very big; this is to keep the module interfaces unchanged
+ * when a large coefficient buffer is necessary.)
+ * In multi-pass modes, this array points to the current MCU's blocks
+ * within the virtual arrays.
+ */
+ JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
+
+ /* In multi-pass modes, we need a virtual block array for each component. */
+ jvirt_barray_ptr whole_image[MAX_COMPONENTS];
+} my_coef_controller;
+
+typedef my_coef_controller * my_coef_ptr;
+
+
+/* Forward declarations */
+METHODDEF boolean compress_data
+ JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
+#ifdef FULL_COEF_BUFFER_SUPPORTED
+METHODDEF boolean compress_first_pass
+ JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
+METHODDEF boolean compress_output
+ JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
+#endif
+
+
+LOCAL void
+start_iMCU_row (j_compress_ptr cinfo)
+/* Reset within-iMCU-row counters for a new row */
+{
+ my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+
+ /* In an interleaved scan, an MCU row is the same as an iMCU row.
+ * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
+ * But at the bottom of the image, process only what's left.
+ */
+ if (cinfo->comps_in_scan > 1) {
+ coef->MCU_rows_per_iMCU_row = 1;
+ } else {
+ if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
+ coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
+ else
+ coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
+ }
+
+ coef->mcu_ctr = 0;
+ coef->MCU_vert_offset = 0;
+}
+
+
+/*
+ * Initialize for a processing pass.
+ */
+
+METHODDEF void
+start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
+{
+ my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+
+ coef->iMCU_row_num = 0;
+ start_iMCU_row(cinfo);
+
+ switch (pass_mode) {
+ case JBUF_PASS_THRU:
+ if (coef->whole_image[0] != NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ coef->pub.compress_data = compress_data;
+ break;
+#ifdef FULL_COEF_BUFFER_SUPPORTED
+ case JBUF_SAVE_AND_PASS:
+ if (coef->whole_image[0] == NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ coef->pub.compress_data = compress_first_pass;
+ break;
+ case JBUF_CRANK_DEST:
+ if (coef->whole_image[0] == NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ coef->pub.compress_data = compress_output;
+ break;
+#endif
+ default:
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ break;
+ }
+}
+
+
+/*
+ * Process some data in the single-pass case.
+ * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
+ * per call, ie, v_samp_factor block rows for each component in the image.
+ * Returns TRUE if the iMCU row is completed, FALSE if suspended.
+ *
+ * NB: input_buf contains a plane for each component in image.
+ * For single pass, this is the same as the components in the scan.
+ */
+
+METHODDEF boolean
+compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
+{
+ my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ int blkn, bi, ci, yindex, yoffset, blockcnt;
+ JDIMENSION ypos, xpos;
+ jpeg_component_info *compptr;
+
+ /* Loop to write as much as one whole iMCU row */
+ for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
+ yoffset++) {
+ for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
+ MCU_col_num++) {
+ /* Determine where data comes from in input_buf and do the DCT thing.
+ * Each call on forward_DCT processes a horizontal row of DCT blocks
+ * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
+ * sequentially. Dummy blocks at the right or bottom edge are filled in
+ * specially. The data in them does not matter for image reconstruction,
+ * so we fill them with values that will encode to the smallest amount of
+ * data, viz: all zeroes in the AC entries, DC entries equal to previous
+ * block's DC value. (Thanks to Thomas Kinsman for this idea.)
+ */
+ blkn = 0;
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
+ : compptr->last_col_width;
+ xpos = MCU_col_num * compptr->MCU_sample_width;
+ ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
+ for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
+ if (coef->iMCU_row_num < last_iMCU_row ||
+ yoffset+yindex < compptr->last_row_height) {
+ (*cinfo->fdct->forward_DCT) (cinfo, compptr,
+ input_buf[ci], coef->MCU_buffer[blkn],
+ ypos, xpos, (JDIMENSION) blockcnt);
+ if (blockcnt < compptr->MCU_width) {
+ /* Create some dummy blocks at the right edge of the image. */
+ jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
+ (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
+ for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
+ coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
+ }
+ }
+ } else {
+ /* Create a row of dummy blocks at the bottom of the image. */
+ jzero_far((void FAR *) coef->MCU_buffer[blkn],
+ compptr->MCU_width * SIZEOF(JBLOCK));
+ for (bi = 0; bi < compptr->MCU_width; bi++) {
+ coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
+ }
+ }
+ blkn += compptr->MCU_width;
+ ypos += DCTSIZE;
+ }
+ }
+ /* Try to write the MCU. In event of a suspension failure, we will
+ * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
+ */
+ if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
+ /* Suspension forced; update state counters and exit */
+ coef->MCU_vert_offset = yoffset;
+ coef->mcu_ctr = MCU_col_num;
+ return FALSE;
+ }
+ }
+ /* Completed an MCU row, but perhaps not an iMCU row */
+ coef->mcu_ctr = 0;
+ }
+ /* Completed the iMCU row, advance counters for next one */
+ coef->iMCU_row_num++;
+ start_iMCU_row(cinfo);
+ return TRUE;
+}
+
+
+#ifdef FULL_COEF_BUFFER_SUPPORTED
+
+/*
+ * Process some data in the first pass of a multi-pass case.
+ * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
+ * per call, ie, v_samp_factor block rows for each component in the image.
+ * This amount of data is read from the source buffer, DCT'd and quantized,
+ * and saved into the virtual arrays. We also generate suitable dummy blocks
+ * as needed at the right and lower edges. (The dummy blocks are constructed
+ * in the virtual arrays, which have been padded appropriately.) This makes
+ * it possible for subsequent passes not to worry about real vs. dummy blocks.
+ *
+ * We must also emit the data to the entropy encoder. This is conveniently
+ * done by calling compress_output() after we've loaded the current strip
+ * of the virtual arrays.
+ *
+ * NB: input_buf contains a plane for each component in image. All
+ * components are DCT'd and loaded into the virtual arrays in this pass.
+ * However, it may be that only a subset of the components are emitted to
+ * the entropy encoder during this first pass; be careful about looking
+ * at the scan-dependent variables (MCU dimensions, etc).
+ */
+
+METHODDEF boolean
+compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
+{
+ my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ JDIMENSION blocks_across, MCUs_across, MCUindex;
+ int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
+ JCOEF lastDC;
+ jpeg_component_info *compptr;
+ JBLOCKARRAY buffer;
+ JBLOCKROW thisblockrow, lastblockrow;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Align the virtual buffer for this component. */
+ buffer = (*cinfo->mem->access_virt_barray)
+ ((j_common_ptr) cinfo, coef->whole_image[ci],
+ coef->iMCU_row_num * compptr->v_samp_factor,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ /* Count non-dummy DCT block rows in this iMCU row. */
+ if (coef->iMCU_row_num < last_iMCU_row)
+ block_rows = compptr->v_samp_factor;
+ else {
+ /* NB: can't use last_row_height here, since may not be set! */
+ block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
+ if (block_rows == 0) block_rows = compptr->v_samp_factor;
+ }
+ blocks_across = compptr->width_in_blocks;
+ h_samp_factor = compptr->h_samp_factor;
+ /* Count number of dummy blocks to be added at the right margin. */
+ ndummy = (int) (blocks_across % h_samp_factor);
+ if (ndummy > 0)
+ ndummy = h_samp_factor - ndummy;
+ /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
+ * on forward_DCT processes a complete horizontal row of DCT blocks.
+ */
+ for (block_row = 0; block_row < block_rows; block_row++) {
+ thisblockrow = buffer[block_row];
+ (*cinfo->fdct->forward_DCT) (cinfo, compptr,
+ input_buf[ci], thisblockrow,
+ (JDIMENSION) (block_row * DCTSIZE),
+ (JDIMENSION) 0, blocks_across);
+ if (ndummy > 0) {
+ /* Create dummy blocks at the right edge of the image. */
+ thisblockrow += blocks_across; /* => first dummy block */
+ jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
+ lastDC = thisblockrow[-1][0];
+ for (bi = 0; bi < ndummy; bi++) {
+ thisblockrow[bi][0] = lastDC;
+ }
+ }
+ }
+ /* If at end of image, create dummy block rows as needed.
+ * The tricky part here is that within each MCU, we want the DC values
+ * of the dummy blocks to match the last real block's DC value.
+ * This squeezes a few more bytes out of the resulting file...
+ */
+ if (coef->iMCU_row_num == last_iMCU_row) {
+ blocks_across += ndummy; /* include lower right corner */
+ MCUs_across = blocks_across / h_samp_factor;
+ for (block_row = block_rows; block_row < compptr->v_samp_factor;
+ block_row++) {
+ thisblockrow = buffer[block_row];
+ lastblockrow = buffer[block_row-1];
+ jzero_far((void FAR *) thisblockrow,
+ (size_t) (blocks_across * SIZEOF(JBLOCK)));
+ for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
+ lastDC = lastblockrow[h_samp_factor-1][0];
+ for (bi = 0; bi < h_samp_factor; bi++) {
+ thisblockrow[bi][0] = lastDC;
+ }
+ thisblockrow += h_samp_factor; /* advance to next MCU in row */
+ lastblockrow += h_samp_factor;
+ }
+ }
+ }
+ }
+ /* NB: compress_output will increment iMCU_row_num if successful.
+ * A suspension return will result in redoing all the work above next time.
+ */
+
+ /* Emit data to the entropy encoder, sharing code with subsequent passes */
+ return compress_output(cinfo, input_buf);
+}
+
+
+/*
+ * Process some data in subsequent passes of a multi-pass case.
+ * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
+ * per call, ie, v_samp_factor block rows for each component in the scan.
+ * The data is obtained from the virtual arrays and fed to the entropy coder.
+ * Returns TRUE if the iMCU row is completed, FALSE if suspended.
+ *
+ * NB: input_buf is ignored; it is likely to be a NULL pointer.
+ */
+
+METHODDEF boolean
+compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
+{
+ my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ int blkn, ci, xindex, yindex, yoffset;
+ JDIMENSION start_col;
+ JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
+ JBLOCKROW buffer_ptr;
+ jpeg_component_info *compptr;
+
+ /* Align the virtual buffers for the components used in this scan.
+ * NB: during first pass, this is safe only because the buffers will
+ * already be aligned properly, so jmemmgr.c won't need to do any I/O.
+ */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ buffer[ci] = (*cinfo->mem->access_virt_barray)
+ ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
+ coef->iMCU_row_num * compptr->v_samp_factor,
+ (JDIMENSION) compptr->v_samp_factor, FALSE);
+ }
+
+ /* Loop to process one whole iMCU row */
+ for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
+ yoffset++) {
+ for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
+ MCU_col_num++) {
+ /* Construct list of pointers to DCT blocks belonging to this MCU */
+ blkn = 0; /* index of current DCT block within MCU */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ start_col = MCU_col_num * compptr->MCU_width;
+ for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
+ buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
+ for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
+ coef->MCU_buffer[blkn++] = buffer_ptr++;
+ }
+ }
+ }
+ /* Try to write the MCU. */
+ if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
+ /* Suspension forced; update state counters and exit */
+ coef->MCU_vert_offset = yoffset;
+ coef->mcu_ctr = MCU_col_num;
+ return FALSE;
+ }
+ }
+ /* Completed an MCU row, but perhaps not an iMCU row */
+ coef->mcu_ctr = 0;
+ }
+ /* Completed the iMCU row, advance counters for next one */
+ coef->iMCU_row_num++;
+ start_iMCU_row(cinfo);
+ return TRUE;
+}
+
+#endif /* FULL_COEF_BUFFER_SUPPORTED */
+
+
+/*
+ * Initialize coefficient buffer controller.
+ */
+
+GLOBAL void
+jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
+{
+ my_coef_ptr coef;
+
+ coef = (my_coef_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_coef_controller));
+ cinfo->coef = (struct jpeg_c_coef_controller *) coef;
+ coef->pub.start_pass = start_pass_coef;
+
+ /* Create the coefficient buffer. */
+ if (need_full_buffer) {
+#ifdef FULL_COEF_BUFFER_SUPPORTED
+ /* Allocate a full-image virtual array for each component, */
+ /* padded to a multiple of samp_factor DCT blocks in each direction. */
+ int ci;
+ jpeg_component_info *compptr;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+ (JDIMENSION) jround_up((long) compptr->width_in_blocks,
+ (long) compptr->h_samp_factor),
+ (JDIMENSION) jround_up((long) compptr->height_in_blocks,
+ (long) compptr->v_samp_factor),
+ (JDIMENSION) compptr->v_samp_factor);
+ }
+#else
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+#endif
+ } else {
+ /* We only need a single-MCU buffer. */
+ JBLOCKROW buffer;
+ int i;
+
+ buffer = (JBLOCKROW)
+ (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
+ for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
+ coef->MCU_buffer[i] = buffer + i;
+ }
+ coef->whole_image[0] = NULL; /* flag for no virtual arrays */
+ }
+}
diff --git a/code/jpeg-6/jccolor.c b/code/jpeg-6/jccolor.c
new file mode 100755
index 0000000..1f0f760
--- /dev/null
+++ b/code/jpeg-6/jccolor.c
@@ -0,0 +1,459 @@
+/*
+ * jccolor.c
+ *
+ * Copyright (C) 1991-1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains input colorspace conversion routines.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Private subobject */
+
+typedef struct {
+ struct jpeg_color_converter pub; /* public fields */
+
+ /* Private state for RGB->YCC conversion */
+ INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
+} my_color_converter;
+
+typedef my_color_converter * my_cconvert_ptr;
+
+
+/**************** RGB -> YCbCr conversion: most common case **************/
+
+/*
+ * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
+ * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
+ * The conversion equations to be implemented are therefore
+ * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
+ * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
+ * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
+ * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
+ * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
+ * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
+ * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
+ * were not represented exactly. Now we sacrifice exact representation of
+ * maximum red and maximum blue in order to get exact grayscales.
+ *
+ * To avoid floating-point arithmetic, we represent the fractional constants
+ * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
+ * the products by 2^16, with appropriate rounding, to get the correct answer.
+ *
+ * For even more speed, we avoid doing any multiplications in the inner loop
+ * by precalculating the constants times R,G,B for all possible values.
+ * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
+ * for 12-bit samples it is still acceptable. It's not very reasonable for
+ * 16-bit samples, but if you want lossless storage you shouldn't be changing
+ * colorspace anyway.
+ * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
+ * in the tables to save adding them separately in the inner loop.
+ */
+
+#define SCALEBITS 16 /* speediest right-shift on some machines */
+#define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
+#define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
+#define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
+
+/* We allocate one big table and divide it up into eight parts, instead of
+ * doing eight alloc_small requests. This lets us use a single table base
+ * address, which can be held in a register in the inner loops on many
+ * machines (more than can hold all eight addresses, anyway).
+ */
+
+#define R_Y_OFF 0 /* offset to R => Y section */
+#define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
+#define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
+#define R_CB_OFF (3*(MAXJSAMPLE+1))
+#define G_CB_OFF (4*(MAXJSAMPLE+1))
+#define B_CB_OFF (5*(MAXJSAMPLE+1))
+#define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
+#define G_CR_OFF (6*(MAXJSAMPLE+1))
+#define B_CR_OFF (7*(MAXJSAMPLE+1))
+#define TABLE_SIZE (8*(MAXJSAMPLE+1))
+
+
+/*
+ * Initialize for RGB->YCC colorspace conversion.
+ */
+
+METHODDEF void
+rgb_ycc_start (j_compress_ptr cinfo)
+{
+ my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+ INT32 * rgb_ycc_tab;
+ INT32 i;
+
+ /* Allocate and fill in the conversion tables. */
+ cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (TABLE_SIZE * SIZEOF(INT32)));
+
+ for (i = 0; i <= MAXJSAMPLE; i++) {
+ rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
+ rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
+ rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
+ rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
+ rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
+ /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
+ * This ensures that the maximum output will round to MAXJSAMPLE
+ * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
+ */
+ rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
+/* B=>Cb and R=>Cr tables are the same
+ rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
+*/
+ rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
+ rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
+ }
+}
+
+
+/*
+ * Convert some rows of samples to the JPEG colorspace.
+ *
+ * Note that we change from the application's interleaved-pixel format
+ * to our internal noninterleaved, one-plane-per-component format.
+ * The input buffer is therefore three times as wide as the output buffer.
+ *
+ * A starting row offset is provided only for the output buffer. The caller
+ * can easily adjust the passed input_buf value to accommodate any row
+ * offset required on that side.
+ */
+
+METHODDEF void
+rgb_ycc_convert (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+ JDIMENSION output_row, int num_rows)
+{
+ my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+ register int r, g, b;
+ register INT32 * ctab = cconvert->rgb_ycc_tab;
+ register JSAMPROW inptr;
+ register JSAMPROW outptr0, outptr1, outptr2;
+ register JDIMENSION col;
+ JDIMENSION num_cols = cinfo->image_width;
+
+ while (--num_rows >= 0) {
+ inptr = *input_buf++;
+ outptr0 = output_buf[0][output_row];
+ outptr1 = output_buf[1][output_row];
+ outptr2 = output_buf[2][output_row];
+ output_row++;
+ for (col = 0; col < num_cols; col++) {
+ r = GETJSAMPLE(inptr[RGB_RED]);
+ g = GETJSAMPLE(inptr[RGB_GREEN]);
+ b = GETJSAMPLE(inptr[RGB_BLUE]);
+ inptr += RGB_PIXELSIZE;
+ /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
+ * must be too; we do not need an explicit range-limiting operation.
+ * Hence the value being shifted is never negative, and we don't
+ * need the general RIGHT_SHIFT macro.
+ */
+ /* Y */
+ outptr0[col] = (JSAMPLE)
+ ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
+ >> SCALEBITS);
+ /* Cb */
+ outptr1[col] = (JSAMPLE)
+ ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
+ >> SCALEBITS);
+ /* Cr */
+ outptr2[col] = (JSAMPLE)
+ ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
+ >> SCALEBITS);
+ }
+ }
+}
+
+
+/**************** Cases other than RGB -> YCbCr **************/
+
+
+/*
+ * Convert some rows of samples to the JPEG colorspace.
+ * This version handles RGB->grayscale conversion, which is the same
+ * as the RGB->Y portion of RGB->YCbCr.
+ * We assume rgb_ycc_start has been called (we only use the Y tables).
+ */
+
+METHODDEF void
+rgb_gray_convert (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+ JDIMENSION output_row, int num_rows)
+{
+ my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+ register int r, g, b;
+ register INT32 * ctab = cconvert->rgb_ycc_tab;
+ register JSAMPROW inptr;
+ register JSAMPROW outptr;
+ register JDIMENSION col;
+ JDIMENSION num_cols = cinfo->image_width;
+
+ while (--num_rows >= 0) {
+ inptr = *input_buf++;
+ outptr = output_buf[0][output_row];
+ output_row++;
+ for (col = 0; col < num_cols; col++) {
+ r = GETJSAMPLE(inptr[RGB_RED]);
+ g = GETJSAMPLE(inptr[RGB_GREEN]);
+ b = GETJSAMPLE(inptr[RGB_BLUE]);
+ inptr += RGB_PIXELSIZE;
+ /* Y */
+ outptr[col] = (JSAMPLE)
+ ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
+ >> SCALEBITS);
+ }
+ }
+}
+
+
+/*
+ * Convert some rows of samples to the JPEG colorspace.
+ * This version handles Adobe-style CMYK->YCCK conversion,
+ * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
+ * conversion as above, while passing K (black) unchanged.
+ * We assume rgb_ycc_start has been called.
+ */
+
+METHODDEF void
+cmyk_ycck_convert (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+ JDIMENSION output_row, int num_rows)
+{
+ my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+ register int r, g, b;
+ register INT32 * ctab = cconvert->rgb_ycc_tab;
+ register JSAMPROW inptr;
+ register JSAMPROW outptr0, outptr1, outptr2, outptr3;
+ register JDIMENSION col;
+ JDIMENSION num_cols = cinfo->image_width;
+
+ while (--num_rows >= 0) {
+ inptr = *input_buf++;
+ outptr0 = output_buf[0][output_row];
+ outptr1 = output_buf[1][output_row];
+ outptr2 = output_buf[2][output_row];
+ outptr3 = output_buf[3][output_row];
+ output_row++;
+ for (col = 0; col < num_cols; col++) {
+ r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
+ g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
+ b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
+ /* K passes through as-is */
+ outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
+ inptr += 4;
+ /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
+ * must be too; we do not need an explicit range-limiting operation.
+ * Hence the value being shifted is never negative, and we don't
+ * need the general RIGHT_SHIFT macro.
+ */
+ /* Y */
+ outptr0[col] = (JSAMPLE)
+ ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
+ >> SCALEBITS);
+ /* Cb */
+ outptr1[col] = (JSAMPLE)
+ ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
+ >> SCALEBITS);
+ /* Cr */
+ outptr2[col] = (JSAMPLE)
+ ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
+ >> SCALEBITS);
+ }
+ }
+}
+
+
+/*
+ * Convert some rows of samples to the JPEG colorspace.
+ * This version handles grayscale output with no conversion.
+ * The source can be either plain grayscale or YCbCr (since Y == gray).
+ */
+
+METHODDEF void
+grayscale_convert (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+ JDIMENSION output_row, int num_rows)
+{
+ register JSAMPROW inptr;
+ register JSAMPROW outptr;
+ register JDIMENSION col;
+ JDIMENSION num_cols = cinfo->image_width;
+ int instride = cinfo->input_components;
+
+ while (--num_rows >= 0) {
+ inptr = *input_buf++;
+ outptr = output_buf[0][output_row];
+ output_row++;
+ for (col = 0; col < num_cols; col++) {
+ outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
+ inptr += instride;
+ }
+ }
+}
+
+
+/*
+ * Convert some rows of samples to the JPEG colorspace.
+ * This version handles multi-component colorspaces without conversion.
+ * We assume input_components == num_components.
+ */
+
+METHODDEF void
+null_convert (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+ JDIMENSION output_row, int num_rows)
+{
+ register JSAMPROW inptr;
+ register JSAMPROW outptr;
+ register JDIMENSION col;
+ register int ci;
+ int nc = cinfo->num_components;
+ JDIMENSION num_cols = cinfo->image_width;
+
+ while (--num_rows >= 0) {
+ /* It seems fastest to make a separate pass for each component. */
+ for (ci = 0; ci < nc; ci++) {
+ inptr = *input_buf;
+ outptr = output_buf[ci][output_row];
+ for (col = 0; col < num_cols; col++) {
+ outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
+ inptr += nc;
+ }
+ }
+ input_buf++;
+ output_row++;
+ }
+}
+
+
+/*
+ * Empty method for start_pass.
+ */
+
+METHODDEF void
+null_method (j_compress_ptr cinfo)
+{
+ /* no work needed */
+}
+
+
+/*
+ * Module initialization routine for input colorspace conversion.
+ */
+
+GLOBAL void
+jinit_color_converter (j_compress_ptr cinfo)
+{
+ my_cconvert_ptr cconvert;
+
+ cconvert = (my_cconvert_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_color_converter));
+ cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
+ /* set start_pass to null method until we find out differently */
+ cconvert->pub.start_pass = null_method;
+
+ /* Make sure input_components agrees with in_color_space */
+ switch (cinfo->in_color_space) {
+ case JCS_GRAYSCALE:
+ if (cinfo->input_components != 1)
+ ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
+ break;
+
+ case JCS_RGB:
+#if RGB_PIXELSIZE != 3
+ if (cinfo->input_components != RGB_PIXELSIZE)
+ ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
+ break;
+#endif /* else share code with YCbCr */
+
+ case JCS_YCbCr:
+ if (cinfo->input_components != 3)
+ ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
+ break;
+
+ case JCS_CMYK:
+ case JCS_YCCK:
+ if (cinfo->input_components != 4)
+ ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
+ break;
+
+ default: /* JCS_UNKNOWN can be anything */
+ if (cinfo->input_components < 1)
+ ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
+ break;
+ }
+
+ /* Check num_components, set conversion method based on requested space */
+ switch (cinfo->jpeg_color_space) {
+ case JCS_GRAYSCALE:
+ if (cinfo->num_components != 1)
+ ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+ if (cinfo->in_color_space == JCS_GRAYSCALE)
+ cconvert->pub.color_convert = grayscale_convert;
+ else if (cinfo->in_color_space == JCS_RGB) {
+ cconvert->pub.start_pass = rgb_ycc_start;
+ cconvert->pub.color_convert = rgb_gray_convert;
+ } else if (cinfo->in_color_space == JCS_YCbCr)
+ cconvert->pub.color_convert = grayscale_convert;
+ else
+ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+ break;
+
+ case JCS_RGB:
+ if (cinfo->num_components != 3)
+ ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+ if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
+ cconvert->pub.color_convert = null_convert;
+ else
+ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+ break;
+
+ case JCS_YCbCr:
+ if (cinfo->num_components != 3)
+ ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+ if (cinfo->in_color_space == JCS_RGB) {
+ cconvert->pub.start_pass = rgb_ycc_start;
+ cconvert->pub.color_convert = rgb_ycc_convert;
+ } else if (cinfo->in_color_space == JCS_YCbCr)
+ cconvert->pub.color_convert = null_convert;
+ else
+ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+ break;
+
+ case JCS_CMYK:
+ if (cinfo->num_components != 4)
+ ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+ if (cinfo->in_color_space == JCS_CMYK)
+ cconvert->pub.color_convert = null_convert;
+ else
+ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+ break;
+
+ case JCS_YCCK:
+ if (cinfo->num_components != 4)
+ ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+ if (cinfo->in_color_space == JCS_CMYK) {
+ cconvert->pub.start_pass = rgb_ycc_start;
+ cconvert->pub.color_convert = cmyk_ycck_convert;
+ } else if (cinfo->in_color_space == JCS_YCCK)
+ cconvert->pub.color_convert = null_convert;
+ else
+ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+ break;
+
+ default: /* allow null conversion of JCS_UNKNOWN */
+ if (cinfo->jpeg_color_space != cinfo->in_color_space ||
+ cinfo->num_components != cinfo->input_components)
+ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+ cconvert->pub.color_convert = null_convert;
+ break;
+ }
+}
diff --git a/code/jpeg-6/jcdctmgr.c b/code/jpeg-6/jcdctmgr.c
new file mode 100755
index 0000000..52a72a2
--- /dev/null
+++ b/code/jpeg-6/jcdctmgr.c
@@ -0,0 +1,391 @@
+/*
+ * jcdctmgr.c
+ *
+ * Copyright (C) 1994-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the forward-DCT management logic.
+ * This code selects a particular DCT implementation to be used,
+ * and it performs related housekeeping chores including coefficient
+ * quantization.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jdct.h" /* Private declarations for DCT subsystem */
+
+
+/* Private subobject for this module */
+
+typedef struct {
+ struct jpeg_forward_dct pub; /* public fields */
+
+ /* Pointer to the DCT routine actually in use */
+ forward_DCT_method_ptr do_dct;
+
+ /* The actual post-DCT divisors --- not identical to the quant table
+ * entries, because of scaling (especially for an unnormalized DCT).
+ * Each table is given in normal array order; note that this must
+ * be converted from the zigzag order of the quantization tables.
+ */
+ DCTELEM * divisors[NUM_QUANT_TBLS];
+
+#ifdef DCT_FLOAT_SUPPORTED
+ /* Same as above for the floating-point case. */
+ float_DCT_method_ptr do_float_dct;
+ FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
+#endif
+} my_fdct_controller;
+
+typedef my_fdct_controller * my_fdct_ptr;
+
+
+/*
+ * Initialize for a processing pass.
+ * Verify that all referenced Q-tables are present, and set up
+ * the divisor table for each one.
+ * In the current implementation, DCT of all components is done during
+ * the first pass, even if only some components will be output in the
+ * first scan. Hence all components should be examined here.
+ */
+
+METHODDEF void
+start_pass_fdctmgr (j_compress_ptr cinfo)
+{
+ my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
+ int ci, qtblno, i;
+ jpeg_component_info *compptr;
+ JQUANT_TBL * qtbl;
+#ifdef DCT_ISLOW_SUPPORTED
+ DCTELEM * dtbl;
+#endif
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ qtblno = compptr->quant_tbl_no;
+ /* Make sure specified quantization table is present */
+ if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
+ cinfo->quant_tbl_ptrs[qtblno] == NULL)
+ ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
+ qtbl = cinfo->quant_tbl_ptrs[qtblno];
+ /* Compute divisors for this quant table */
+ /* We may do this more than once for same table, but it's not a big deal */
+ switch (cinfo->dct_method) {
+#ifdef DCT_ISLOW_SUPPORTED
+ case JDCT_ISLOW:
+ /* For LL&M IDCT method, divisors are equal to raw quantization
+ * coefficients multiplied by 8 (to counteract scaling).
+ */
+ if (fdct->divisors[qtblno] == NULL) {
+ fdct->divisors[qtblno] = (DCTELEM *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ DCTSIZE2 * SIZEOF(DCTELEM));
+ }
+ dtbl = fdct->divisors[qtblno];
+ for (i = 0; i < DCTSIZE2; i++) {
+ dtbl[i] = ((DCTELEM) qtbl->quantval[jpeg_zigzag_order[i]]) << 3;
+ }
+ break;
+#endif
+#ifdef DCT_IFAST_SUPPORTED
+ case JDCT_IFAST:
+ {
+ /* For AA&N IDCT method, divisors are equal to quantization
+ * coefficients scaled by scalefactor[row]*scalefactor[col], where
+ * scalefactor[0] = 1
+ * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
+ * We apply a further scale factor of 8.
+ */
+#define CONST_BITS 14
+ static const INT16 aanscales[DCTSIZE2] = {
+ /* precomputed values scaled up by 14 bits: in natural order */
+ 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
+ 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
+ 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
+ 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
+ 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
+ 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
+ 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
+ 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
+ };
+ SHIFT_TEMPS
+
+ if (fdct->divisors[qtblno] == NULL) {
+ fdct->divisors[qtblno] = (DCTELEM *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ DCTSIZE2 * SIZEOF(DCTELEM));
+ }
+ dtbl = fdct->divisors[qtblno];
+ for (i = 0; i < DCTSIZE2; i++) {
+ dtbl[i] = (DCTELEM)
+ DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[jpeg_zigzag_order[i]],
+ (INT32) aanscales[i]),
+ CONST_BITS-3);
+ }
+ }
+ break;
+#endif
+#ifdef DCT_FLOAT_SUPPORTED
+ case JDCT_FLOAT:
+ {
+ /* For float AA&N IDCT method, divisors are equal to quantization
+ * coefficients scaled by scalefactor[row]*scalefactor[col], where
+ * scalefactor[0] = 1
+ * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
+ * We apply a further scale factor of 8.
+ * What's actually stored is 1/divisor so that the inner loop can
+ * use a multiplication rather than a division.
+ */
+ FAST_FLOAT * fdtbl;
+ int row, col;
+ static const double aanscalefactor[DCTSIZE] = {
+ 1.0, 1.387039845, 1.306562965, 1.175875602,
+ 1.0, 0.785694958, 0.541196100, 0.275899379
+ };
+
+ if (fdct->float_divisors[qtblno] == NULL) {
+ fdct->float_divisors[qtblno] = (FAST_FLOAT *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ DCTSIZE2 * SIZEOF(FAST_FLOAT));
+ }
+ fdtbl = fdct->float_divisors[qtblno];
+ i = 0;
+ for (row = 0; row < DCTSIZE; row++) {
+ for (col = 0; col < DCTSIZE; col++) {
+ fdtbl[i] = (FAST_FLOAT)
+ (1.0 / (((double) qtbl->quantval[jpeg_zigzag_order[i]] *
+ aanscalefactor[row] * aanscalefactor[col] * 8.0)));
+ i++;
+ }
+ }
+ }
+ break;
+#endif
+ default:
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+ break;
+ }
+ }
+}
+
+
+/*
+ * Perform forward DCT on one or more blocks of a component.
+ *
+ * The input samples are taken from the sample_data[] array starting at
+ * position start_row/start_col, and moving to the right for any additional
+ * blocks. The quantized coefficients are returned in coef_blocks[].
+ */
+
+#if 0 // bk001204
+METHODDEF void
+forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
+ JDIMENSION start_row, JDIMENSION start_col,
+ JDIMENSION num_blocks)
+/* This version is used for integer DCT implementations. */
+{
+ /* This routine is heavily used, so it's worth coding it tightly. */
+ my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
+ forward_DCT_method_ptr do_dct = fdct->do_dct;
+ DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
+ DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
+ JDIMENSION bi;
+
+ sample_data += start_row; /* fold in the vertical offset once */
+
+ for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
+ /* Load data into workspace, applying unsigned->signed conversion */
+ { register DCTELEM *workspaceptr;
+ register JSAMPROW elemptr;
+ register int elemr;
+
+ workspaceptr = workspace;
+ for (elemr = 0; elemr < DCTSIZE; elemr++) {
+ elemptr = sample_data[elemr] + start_col;
+#if DCTSIZE == 8 /* unroll the inner loop */
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+#else
+ { register int elemc;
+ for (elemc = DCTSIZE; elemc > 0; elemc--) {
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+ }
+ }
+#endif
+ }
+ }
+
+ /* Perform the DCT */
+ (*do_dct) (workspace);
+
+ /* Quantize/descale the coefficients, and store into coef_blocks[] */
+ { register DCTELEM temp, qval;
+ register int i;
+ register JCOEFPTR output_ptr = coef_blocks[bi];
+
+ for (i = 0; i < DCTSIZE2; i++) {
+ qval = divisors[i];
+ temp = workspace[i];
+ /* Divide the coefficient value by qval, ensuring proper rounding.
+ * Since C does not specify the direction of rounding for negative
+ * quotients, we have to force the dividend positive for portability.
+ *
+ * In most files, at least half of the output values will be zero
+ * (at default quantization settings, more like three-quarters...)
+ * so we should ensure that this case is fast. On many machines,
+ * a comparison is enough cheaper than a divide to make a special test
+ * a win. Since both inputs will be nonnegative, we need only test
+ * for a < b to discover whether a/b is 0.
+ * If your machine's division is fast enough, define FAST_DIVIDE.
+ */
+#ifdef FAST_DIVIDE
+#define DIVIDE_BY(a,b) a /= b
+#else
+#define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
+#endif
+ if (temp < 0) {
+ temp = -temp;
+ temp += qval>>1; /* for rounding */
+ DIVIDE_BY(temp, qval);
+ temp = -temp;
+ } else {
+ temp += qval>>1; /* for rounding */
+ DIVIDE_BY(temp, qval);
+ }
+ output_ptr[i] = (JCOEF) temp;
+ }
+ }
+ }
+}
+#endif // 0
+
+#ifdef DCT_FLOAT_SUPPORTED
+
+METHODDEF void
+forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
+ JDIMENSION start_row, JDIMENSION start_col,
+ JDIMENSION num_blocks)
+/* This version is used for floating-point DCT implementations. */
+{
+ /* This routine is heavily used, so it's worth coding it tightly. */
+ my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
+ float_DCT_method_ptr do_dct = fdct->do_float_dct;
+ FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
+ FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
+ JDIMENSION bi;
+
+ sample_data += start_row; /* fold in the vertical offset once */
+
+ for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
+ /* Load data into workspace, applying unsigned->signed conversion */
+ { register FAST_FLOAT *workspaceptr;
+ register JSAMPROW elemptr;
+ register int elemr;
+
+ workspaceptr = workspace;
+ for (elemr = 0; elemr < DCTSIZE; elemr++) {
+ elemptr = sample_data[elemr] + start_col;
+#if DCTSIZE == 8 /* unroll the inner loop */
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
+#else
+ { register int elemc;
+ for (elemc = DCTSIZE; elemc > 0; elemc--) {
+ *workspaceptr++ = (FAST_FLOAT)
+ (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
+ }
+ }
+#endif
+ }
+ }
+
+ /* Perform the DCT */
+ (*do_dct) (workspace);
+
+ /* Quantize/descale the coefficients, and store into coef_blocks[] */
+ { register FAST_FLOAT temp;
+ register int i;
+ register JCOEFPTR output_ptr = coef_blocks[bi];
+
+ for (i = 0; i < DCTSIZE2; i++) {
+ /* Apply the quantization and scaling factor */
+ temp = workspace[i] * divisors[i];
+ /* Round to nearest integer.
+ * Since C does not specify the direction of rounding for negative
+ * quotients, we have to force the dividend positive for portability.
+ * The maximum coefficient size is +-16K (for 12-bit data), so this
+ * code should work for either 16-bit or 32-bit ints.
+ */
+ output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
+ }
+ }
+ }
+}
+
+#endif /* DCT_FLOAT_SUPPORTED */
+
+
+/*
+ * Initialize FDCT manager.
+ */
+
+GLOBAL void
+jinit_forward_dct (j_compress_ptr cinfo)
+{
+ my_fdct_ptr fdct;
+ int i;
+
+ fdct = (my_fdct_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_fdct_controller));
+ cinfo->fdct = (struct jpeg_forward_dct *) fdct;
+ fdct->pub.start_pass = start_pass_fdctmgr;
+
+ switch (cinfo->dct_method) {
+#ifdef DCT_ISLOW_SUPPORTED
+ case JDCT_ISLOW:
+ fdct->pub.forward_DCT = forward_DCT;
+ fdct->do_dct = jpeg_fdct_islow;
+ break;
+#endif
+#ifdef DCT_IFAST_SUPPORTED
+ case JDCT_IFAST:
+ fdct->pub.forward_DCT = forward_DCT;
+ fdct->do_dct = jpeg_fdct_ifast;
+ break;
+#endif
+#ifdef DCT_FLOAT_SUPPORTED
+ case JDCT_FLOAT:
+ fdct->pub.forward_DCT = forward_DCT_float;
+ fdct->do_float_dct = jpeg_fdct_float;
+ break;
+#endif
+ default:
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+ break;
+ }
+
+ /* Mark divisor tables unallocated */
+ for (i = 0; i < NUM_QUANT_TBLS; i++) {
+ fdct->divisors[i] = NULL;
+#ifdef DCT_FLOAT_SUPPORTED
+ fdct->float_divisors[i] = NULL;
+#endif
+ }
+}
diff --git a/code/jpeg-6/jchuff.c b/code/jpeg-6/jchuff.c
new file mode 100755
index 0000000..d6a81ef
--- /dev/null
+++ b/code/jpeg-6/jchuff.c
@@ -0,0 +1,846 @@
+/*
+ * jchuff.c
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains Huffman entropy encoding routines.
+ *
+ * Much of the complexity here has to do with supporting output suspension.
+ * If the data destination module demands suspension, we want to be able to
+ * back up to the start of the current MCU. To do this, we copy state
+ * variables into local working storage, and update them back to the
+ * permanent JPEG objects only upon successful completion of an MCU.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jchuff.h" /* Declarations shared with jcphuff.c */
+
+
+/* Expanded entropy encoder object for Huffman encoding.
+ *
+ * The savable_state subrecord contains fields that change within an MCU,
+ * but must not be updated permanently until we complete the MCU.
+ */
+
+typedef struct {
+ INT32 put_buffer; /* current bit-accumulation buffer */
+ int put_bits; /* # of bits now in it */
+ int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
+} savable_state;
+
+/* This macro is to work around compilers with missing or broken
+ * structure assignment. You'll need to fix this code if you have
+ * such a compiler and you change MAX_COMPS_IN_SCAN.
+ */
+
+#ifndef NO_STRUCT_ASSIGN
+#define ASSIGN_STATE(dest,src) ((dest) = (src))
+#else
+#if MAX_COMPS_IN_SCAN == 4
+#define ASSIGN_STATE(dest,src) \
+ ((dest).put_buffer = (src).put_buffer, \
+ (dest).put_bits = (src).put_bits, \
+ (dest).last_dc_val[0] = (src).last_dc_val[0], \
+ (dest).last_dc_val[1] = (src).last_dc_val[1], \
+ (dest).last_dc_val[2] = (src).last_dc_val[2], \
+ (dest).last_dc_val[3] = (src).last_dc_val[3])
+#endif
+#endif
+
+
+typedef struct {
+ struct jpeg_entropy_encoder pub; /* public fields */
+
+ savable_state saved; /* Bit buffer & DC state at start of MCU */
+
+ /* These fields are NOT loaded into local working state. */
+ unsigned int restarts_to_go; /* MCUs left in this restart interval */
+ int next_restart_num; /* next restart number to write (0-7) */
+
+ /* Pointers to derived tables (these workspaces have image lifespan) */
+ c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
+ c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
+
+#ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
+ long * dc_count_ptrs[NUM_HUFF_TBLS];
+ long * ac_count_ptrs[NUM_HUFF_TBLS];
+#endif
+} huff_entropy_encoder;
+
+typedef huff_entropy_encoder * huff_entropy_ptr;
+
+/* Working state while writing an MCU.
+ * This struct contains all the fields that are needed by subroutines.
+ */
+
+typedef struct {
+ JOCTET * next_output_byte; /* => next byte to write in buffer */
+ size_t free_in_buffer; /* # of byte spaces remaining in buffer */
+ savable_state cur; /* Current bit buffer & DC state */
+ j_compress_ptr cinfo; /* dump_buffer needs access to this */
+} working_state;
+
+
+/* Forward declarations */
+METHODDEF boolean encode_mcu_huff JPP((j_compress_ptr cinfo,
+ JBLOCKROW *MCU_data));
+METHODDEF void finish_pass_huff JPP((j_compress_ptr cinfo));
+#ifdef ENTROPY_OPT_SUPPORTED
+METHODDEF boolean encode_mcu_gather JPP((j_compress_ptr cinfo,
+ JBLOCKROW *MCU_data));
+METHODDEF void finish_pass_gather JPP((j_compress_ptr cinfo));
+#endif
+
+
+/*
+ * Initialize for a Huffman-compressed scan.
+ * If gather_statistics is TRUE, we do not output anything during the scan,
+ * just count the Huffman symbols used and generate Huffman code tables.
+ */
+
+METHODDEF void
+start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
+{
+ huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
+ int ci, dctbl, actbl;
+ jpeg_component_info * compptr;
+
+ if (gather_statistics) {
+#ifdef ENTROPY_OPT_SUPPORTED
+ entropy->pub.encode_mcu = encode_mcu_gather;
+ entropy->pub.finish_pass = finish_pass_gather;
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else {
+ entropy->pub.encode_mcu = encode_mcu_huff;
+ entropy->pub.finish_pass = finish_pass_huff;
+ }
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ dctbl = compptr->dc_tbl_no;
+ actbl = compptr->ac_tbl_no;
+ /* Make sure requested tables are present */
+ /* (In gather mode, tables need not be allocated yet) */
+ if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS ||
+ (cinfo->dc_huff_tbl_ptrs[dctbl] == NULL && !gather_statistics))
+ ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
+ if (actbl < 0 || actbl >= NUM_HUFF_TBLS ||
+ (cinfo->ac_huff_tbl_ptrs[actbl] == NULL && !gather_statistics))
+ ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
+ if (gather_statistics) {
+#ifdef ENTROPY_OPT_SUPPORTED
+ /* Allocate and zero the statistics tables */
+ /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
+ if (entropy->dc_count_ptrs[dctbl] == NULL)
+ entropy->dc_count_ptrs[dctbl] = (long *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ 257 * SIZEOF(long));
+ MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
+ if (entropy->ac_count_ptrs[actbl] == NULL)
+ entropy->ac_count_ptrs[actbl] = (long *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ 257 * SIZEOF(long));
+ MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
+#endif
+ } else {
+ /* Compute derived values for Huffman tables */
+ /* We may do this more than once for a table, but it's not expensive */
+ jpeg_make_c_derived_tbl(cinfo, cinfo->dc_huff_tbl_ptrs[dctbl],
+ & entropy->dc_derived_tbls[dctbl]);
+ jpeg_make_c_derived_tbl(cinfo, cinfo->ac_huff_tbl_ptrs[actbl],
+ & entropy->ac_derived_tbls[actbl]);
+ }
+ /* Initialize DC predictions to 0 */
+ entropy->saved.last_dc_val[ci] = 0;
+ }
+
+ /* Initialize bit buffer to empty */
+ entropy->saved.put_buffer = 0;
+ entropy->saved.put_bits = 0;
+
+ /* Initialize restart stuff */
+ entropy->restarts_to_go = cinfo->restart_interval;
+ entropy->next_restart_num = 0;
+}
+
+
+/*
+ * Compute the derived values for a Huffman table.
+ * Note this is also used by jcphuff.c.
+ */
+
+GLOBAL void
+jpeg_make_c_derived_tbl (j_compress_ptr cinfo, JHUFF_TBL * htbl,
+ c_derived_tbl ** pdtbl)
+{
+ c_derived_tbl *dtbl;
+ int p, i, l, lastp, si;
+ char huffsize[257];
+ unsigned int huffcode[257];
+ unsigned int code;
+
+ /* Allocate a workspace if we haven't already done so. */
+ if (*pdtbl == NULL)
+ *pdtbl = (c_derived_tbl *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(c_derived_tbl));
+ dtbl = *pdtbl;
+
+ /* Figure C.1: make table of Huffman code length for each symbol */
+ /* Note that this is in code-length order. */
+
+ p = 0;
+ for (l = 1; l <= 16; l++) {
+ for (i = 1; i <= (int) htbl->bits[l]; i++)
+ huffsize[p++] = (char) l;
+ }
+ huffsize[p] = 0;
+ lastp = p;
+
+ /* Figure C.2: generate the codes themselves */
+ /* Note that this is in code-length order. */
+
+ code = 0;
+ si = huffsize[0];
+ p = 0;
+ while (huffsize[p]) {
+ while (((int) huffsize[p]) == si) {
+ huffcode[p++] = code;
+ code++;
+ }
+ code <<= 1;
+ si++;
+ }
+
+ /* Figure C.3: generate encoding tables */
+ /* These are code and size indexed by symbol value */
+
+ /* Set any codeless symbols to have code length 0;
+ * this allows emit_bits to detect any attempt to emit such symbols.
+ */
+ MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
+
+ for (p = 0; p < lastp; p++) {
+ dtbl->ehufco[htbl->huffval[p]] = huffcode[p];
+ dtbl->ehufsi[htbl->huffval[p]] = huffsize[p];
+ }
+}
+
+
+/* Outputting bytes to the file */
+
+/* Emit a byte, taking 'action' if must suspend. */
+#define emit_byte(state,val,action) \
+ { *(state)->next_output_byte++ = (JOCTET) (val); \
+ if (--(state)->free_in_buffer == 0) \
+ if (! dump_buffer(state)) \
+ { action; } }
+
+
+LOCAL boolean
+dump_buffer (working_state * state)
+/* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
+{
+ struct jpeg_destination_mgr * dest = state->cinfo->dest;
+
+ if (! (*dest->empty_output_buffer) (state->cinfo))
+ return FALSE;
+ /* After a successful buffer dump, must reset buffer pointers */
+ state->next_output_byte = dest->next_output_byte;
+ state->free_in_buffer = dest->free_in_buffer;
+ return TRUE;
+}
+
+
+/* Outputting bits to the file */
+
+/* Only the right 24 bits of put_buffer are used; the valid bits are
+ * left-justified in this part. At most 16 bits can be passed to emit_bits
+ * in one call, and we never retain more than 7 bits in put_buffer
+ * between calls, so 24 bits are sufficient.
+ */
+
+INLINE
+LOCAL boolean
+emit_bits (working_state * state, unsigned int code, int size)
+/* Emit some bits; return TRUE if successful, FALSE if must suspend */
+{
+ /* This routine is heavily used, so it's worth coding tightly. */
+ register INT32 put_buffer = (INT32) code;
+ register int put_bits = state->cur.put_bits;
+
+ /* if size is 0, caller used an invalid Huffman table entry */
+ if (size == 0)
+ ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
+
+ put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
+
+ put_bits += size; /* new number of bits in buffer */
+
+ put_buffer <<= 24 - put_bits; /* align incoming bits */
+
+ put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
+
+ while (put_bits >= 8) {
+ int c = (int) ((put_buffer >> 16) & 0xFF);
+
+ emit_byte(state, c, return FALSE);
+ if (c == 0xFF) { /* need to stuff a zero byte? */
+ emit_byte(state, 0, return FALSE);
+ }
+ put_buffer <<= 8;
+ put_bits -= 8;
+ }
+
+ state->cur.put_buffer = put_buffer; /* update state variables */
+ state->cur.put_bits = put_bits;
+
+ return TRUE;
+}
+
+
+LOCAL boolean
+flush_bits (working_state * state)
+{
+ if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
+ return FALSE;
+ state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
+ state->cur.put_bits = 0;
+ return TRUE;
+}
+
+
+/* Encode a single block's worth of coefficients */
+
+LOCAL boolean
+encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
+ c_derived_tbl *dctbl, c_derived_tbl *actbl)
+{
+ register int temp, temp2;
+ register int nbits;
+ register int k, r, i;
+
+ /* Encode the DC coefficient difference per section F.1.2.1 */
+
+ temp = temp2 = block[0] - last_dc_val;
+
+ if (temp < 0) {
+ temp = -temp; /* temp is abs value of input */
+ /* For a negative input, want temp2 = bitwise complement of abs(input) */
+ /* This code assumes we are on a two's complement machine */
+ temp2--;
+ }
+
+ /* Find the number of bits needed for the magnitude of the coefficient */
+ nbits = 0;
+ while (temp) {
+ nbits++;
+ temp >>= 1;
+ }
+
+ /* Emit the Huffman-coded symbol for the number of bits */
+ if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
+ return FALSE;
+
+ /* Emit that number of bits of the value, if positive, */
+ /* or the complement of its magnitude, if negative. */
+ if (nbits) /* emit_bits rejects calls with size 0 */
+ if (! emit_bits(state, (unsigned int) temp2, nbits))
+ return FALSE;
+
+ /* Encode the AC coefficients per section F.1.2.2 */
+
+ r = 0; /* r = run length of zeros */
+
+ for (k = 1; k < DCTSIZE2; k++) {
+ if ((temp = block[jpeg_natural_order[k]]) == 0) {
+ r++;
+ } else {
+ /* if run length > 15, must emit special run-length-16 codes (0xF0) */
+ while (r > 15) {
+ if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
+ return FALSE;
+ r -= 16;
+ }
+
+ temp2 = temp;
+ if (temp < 0) {
+ temp = -temp; /* temp is abs value of input */
+ /* This code assumes we are on a two's complement machine */
+ temp2--;
+ }
+
+ /* Find the number of bits needed for the magnitude of the coefficient */
+ nbits = 1; /* there must be at least one 1 bit */
+ while ((temp >>= 1))
+ nbits++;
+
+ /* Emit Huffman symbol for run length / number of bits */
+ i = (r << 4) + nbits;
+ if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
+ return FALSE;
+
+ /* Emit that number of bits of the value, if positive, */
+ /* or the complement of its magnitude, if negative. */
+ if (! emit_bits(state, (unsigned int) temp2, nbits))
+ return FALSE;
+
+ r = 0;
+ }
+ }
+
+ /* If the last coef(s) were zero, emit an end-of-block code */
+ if (r > 0)
+ if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
+ return FALSE;
+
+ return TRUE;
+}
+
+
+/*
+ * Emit a restart marker & resynchronize predictions.
+ */
+
+LOCAL boolean
+emit_restart (working_state * state, int restart_num)
+{
+ int ci;
+
+ if (! flush_bits(state))
+ return FALSE;
+
+ emit_byte(state, 0xFF, return FALSE);
+ emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
+
+ /* Re-initialize DC predictions to 0 */
+ for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
+ state->cur.last_dc_val[ci] = 0;
+
+ /* The restart counter is not updated until we successfully write the MCU. */
+
+ return TRUE;
+}
+
+
+/*
+ * Encode and output one MCU's worth of Huffman-compressed coefficients.
+ */
+
+METHODDEF boolean
+encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
+{
+ huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
+ working_state state;
+ int blkn, ci;
+ jpeg_component_info * compptr;
+
+ /* Load up working state */
+ state.next_output_byte = cinfo->dest->next_output_byte;
+ state.free_in_buffer = cinfo->dest->free_in_buffer;
+ ASSIGN_STATE(state.cur, entropy->saved);
+ state.cinfo = cinfo;
+
+ /* Emit restart marker if needed */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0)
+ if (! emit_restart(&state, entropy->next_restart_num))
+ return FALSE;
+ }
+
+ /* Encode the MCU data blocks */
+ for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
+ ci = cinfo->MCU_membership[blkn];
+ compptr = cinfo->cur_comp_info[ci];
+ if (! encode_one_block(&state,
+ MCU_data[blkn][0], state.cur.last_dc_val[ci],
+ entropy->dc_derived_tbls[compptr->dc_tbl_no],
+ entropy->ac_derived_tbls[compptr->ac_tbl_no]))
+ return FALSE;
+ /* Update last_dc_val */
+ state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
+ }
+
+ /* Completed MCU, so update state */
+ cinfo->dest->next_output_byte = state.next_output_byte;
+ cinfo->dest->free_in_buffer = state.free_in_buffer;
+ ASSIGN_STATE(entropy->saved, state.cur);
+
+ /* Update restart-interval state too */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0) {
+ entropy->restarts_to_go = cinfo->restart_interval;
+ entropy->next_restart_num++;
+ entropy->next_restart_num &= 7;
+ }
+ entropy->restarts_to_go--;
+ }
+
+ return TRUE;
+}
+
+
+/*
+ * Finish up at the end of a Huffman-compressed scan.
+ */
+
+METHODDEF void
+finish_pass_huff (j_compress_ptr cinfo)
+{
+ huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
+ working_state state;
+
+ /* Load up working state ... flush_bits needs it */
+ state.next_output_byte = cinfo->dest->next_output_byte;
+ state.free_in_buffer = cinfo->dest->free_in_buffer;
+ ASSIGN_STATE(state.cur, entropy->saved);
+ state.cinfo = cinfo;
+
+ /* Flush out the last data */
+ if (! flush_bits(&state))
+ ERREXIT(cinfo, JERR_CANT_SUSPEND);
+
+ /* Update state */
+ cinfo->dest->next_output_byte = state.next_output_byte;
+ cinfo->dest->free_in_buffer = state.free_in_buffer;
+ ASSIGN_STATE(entropy->saved, state.cur);
+}
+
+
+/*
+ * Huffman coding optimization.
+ *
+ * This actually is optimization, in the sense that we find the best possible
+ * Huffman table(s) for the given data. We first scan the supplied data and
+ * count the number of uses of each symbol that is to be Huffman-coded.
+ * (This process must agree with the code above.) Then we build an
+ * optimal Huffman coding tree for the observed counts.
+ *
+ * The JPEG standard requires Huffman codes to be no more than 16 bits long.
+ * If some symbols have a very small but nonzero probability, the Huffman tree
+ * must be adjusted to meet the code length restriction. We currently use
+ * the adjustment method suggested in the JPEG spec. This method is *not*
+ * optimal; it may not choose the best possible limited-length code. But
+ * since the symbols involved are infrequently used, it's not clear that
+ * going to extra trouble is worthwhile.
+ */
+
+#ifdef ENTROPY_OPT_SUPPORTED
+
+
+/* Process a single block's worth of coefficients */
+
+LOCAL void
+htest_one_block (JCOEFPTR block, int last_dc_val,
+ long dc_counts[], long ac_counts[])
+{
+ register int temp;
+ register int nbits;
+ register int k, r;
+
+ /* Encode the DC coefficient difference per section F.1.2.1 */
+
+ temp = block[0] - last_dc_val;
+ if (temp < 0)
+ temp = -temp;
+
+ /* Find the number of bits needed for the magnitude of the coefficient */
+ nbits = 0;
+ while (temp) {
+ nbits++;
+ temp >>= 1;
+ }
+
+ /* Count the Huffman symbol for the number of bits */
+ dc_counts[nbits]++;
+
+ /* Encode the AC coefficients per section F.1.2.2 */
+
+ r = 0; /* r = run length of zeros */
+
+ for (k = 1; k < DCTSIZE2; k++) {
+ if ((temp = block[jpeg_natural_order[k]]) == 0) {
+ r++;
+ } else {
+ /* if run length > 15, must emit special run-length-16 codes (0xF0) */
+ while (r > 15) {
+ ac_counts[0xF0]++;
+ r -= 16;
+ }
+
+ /* Find the number of bits needed for the magnitude of the coefficient */
+ if (temp < 0)
+ temp = -temp;
+
+ /* Find the number of bits needed for the magnitude of the coefficient */
+ nbits = 1; /* there must be at least one 1 bit */
+ while ((temp >>= 1))
+ nbits++;
+
+ /* Count Huffman symbol for run length / number of bits */
+ ac_counts[(r << 4) + nbits]++;
+
+ r = 0;
+ }
+ }
+
+ /* If the last coef(s) were zero, emit an end-of-block code */
+ if (r > 0)
+ ac_counts[0]++;
+}
+
+
+/*
+ * Trial-encode one MCU's worth of Huffman-compressed coefficients.
+ * No data is actually output, so no suspension return is possible.
+ */
+
+METHODDEF boolean
+encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
+{
+ huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
+ int blkn, ci;
+ jpeg_component_info * compptr;
+
+ /* Take care of restart intervals if needed */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0) {
+ /* Re-initialize DC predictions to 0 */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++)
+ entropy->saved.last_dc_val[ci] = 0;
+ /* Update restart state */
+ entropy->restarts_to_go = cinfo->restart_interval;
+ }
+ entropy->restarts_to_go--;
+ }
+
+ for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
+ ci = cinfo->MCU_membership[blkn];
+ compptr = cinfo->cur_comp_info[ci];
+ htest_one_block(MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
+ entropy->dc_count_ptrs[compptr->dc_tbl_no],
+ entropy->ac_count_ptrs[compptr->ac_tbl_no]);
+ entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
+ }
+
+ return TRUE;
+}
+
+
+/*
+ * Generate the optimal coding for the given counts, fill htbl.
+ * Note this is also used by jcphuff.c.
+ */
+
+GLOBAL void
+jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
+{
+#define MAX_CLEN 32 /* assumed maximum initial code length */
+ UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
+ int codesize[257]; /* codesize[k] = code length of symbol k */
+ int others[257]; /* next symbol in current branch of tree */
+ int c1, c2;
+ int p, i, j;
+ long v;
+
+ /* This algorithm is explained in section K.2 of the JPEG standard */
+
+ MEMZERO(bits, SIZEOF(bits));
+ MEMZERO(codesize, SIZEOF(codesize));
+ for (i = 0; i < 257; i++)
+ others[i] = -1; /* init links to empty */
+
+ freq[256] = 1; /* make sure there is a nonzero count */
+ /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
+ * that no real symbol is given code-value of all ones, because 256
+ * will be placed in the largest codeword category.
+ */
+
+ /* Huffman's basic algorithm to assign optimal code lengths to symbols */
+
+ for (;;) {
+ /* Find the smallest nonzero frequency, set c1 = its symbol */
+ /* In case of ties, take the larger symbol number */
+ c1 = -1;
+ v = 1000000000L;
+ for (i = 0; i <= 256; i++) {
+ if (freq[i] && freq[i] <= v) {
+ v = freq[i];
+ c1 = i;
+ }
+ }
+
+ /* Find the next smallest nonzero frequency, set c2 = its symbol */
+ /* In case of ties, take the larger symbol number */
+ c2 = -1;
+ v = 1000000000L;
+ for (i = 0; i <= 256; i++) {
+ if (freq[i] && freq[i] <= v && i != c1) {
+ v = freq[i];
+ c2 = i;
+ }
+ }
+
+ /* Done if we've merged everything into one frequency */
+ if (c2 < 0)
+ break;
+
+ /* Else merge the two counts/trees */
+ freq[c1] += freq[c2];
+ freq[c2] = 0;
+
+ /* Increment the codesize of everything in c1's tree branch */
+ codesize[c1]++;
+ while (others[c1] >= 0) {
+ c1 = others[c1];
+ codesize[c1]++;
+ }
+
+ others[c1] = c2; /* chain c2 onto c1's tree branch */
+
+ /* Increment the codesize of everything in c2's tree branch */
+ codesize[c2]++;
+ while (others[c2] >= 0) {
+ c2 = others[c2];
+ codesize[c2]++;
+ }
+ }
+
+ /* Now count the number of symbols of each code length */
+ for (i = 0; i <= 256; i++) {
+ if (codesize[i]) {
+ /* The JPEG standard seems to think that this can't happen, */
+ /* but I'm paranoid... */
+ if (codesize[i] > MAX_CLEN)
+ ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
+
+ bits[codesize[i]]++;
+ }
+ }
+
+ /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
+ * Huffman procedure assigned any such lengths, we must adjust the coding.
+ * Here is what the JPEG spec says about how this next bit works:
+ * Since symbols are paired for the longest Huffman code, the symbols are
+ * removed from this length category two at a time. The prefix for the pair
+ * (which is one bit shorter) is allocated to one of the pair; then,
+ * skipping the BITS entry for that prefix length, a code word from the next
+ * shortest nonzero BITS entry is converted into a prefix for two code words
+ * one bit longer.
+ */
+
+ for (i = MAX_CLEN; i > 16; i--) {
+ while (bits[i] > 0) {
+ j = i - 2; /* find length of new prefix to be used */
+ while (bits[j] == 0)
+ j--;
+
+ bits[i] -= 2; /* remove two symbols */
+ bits[i-1]++; /* one goes in this length */
+ bits[j+1] += 2; /* two new symbols in this length */
+ bits[j]--; /* symbol of this length is now a prefix */
+ }
+ }
+
+ /* Remove the count for the pseudo-symbol 256 from the largest codelength */
+ while (bits[i] == 0) /* find largest codelength still in use */
+ i--;
+ bits[i]--;
+
+ /* Return final symbol counts (only for lengths 0..16) */
+ MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
+
+ /* Return a list of the symbols sorted by code length */
+ /* It's not real clear to me why we don't need to consider the codelength
+ * changes made above, but the JPEG spec seems to think this works.
+ */
+ p = 0;
+ for (i = 1; i <= MAX_CLEN; i++) {
+ for (j = 0; j <= 255; j++) {
+ if (codesize[j] == i) {
+ htbl->huffval[p] = (UINT8) j;
+ p++;
+ }
+ }
+ }
+
+ /* Set sent_table FALSE so updated table will be written to JPEG file. */
+ htbl->sent_table = FALSE;
+}
+
+
+/*
+ * Finish up a statistics-gathering pass and create the new Huffman tables.
+ */
+
+METHODDEF void
+finish_pass_gather (j_compress_ptr cinfo)
+{
+ huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
+ int ci, dctbl, actbl;
+ jpeg_component_info * compptr;
+ JHUFF_TBL **htblptr;
+ boolean did_dc[NUM_HUFF_TBLS];
+ boolean did_ac[NUM_HUFF_TBLS];
+
+ /* It's important not to apply jpeg_gen_optimal_table more than once
+ * per table, because it clobbers the input frequency counts!
+ */
+ MEMZERO(did_dc, SIZEOF(did_dc));
+ MEMZERO(did_ac, SIZEOF(did_ac));
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ dctbl = compptr->dc_tbl_no;
+ actbl = compptr->ac_tbl_no;
+ if (! did_dc[dctbl]) {
+ htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
+ if (*htblptr == NULL)
+ *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
+ jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
+ did_dc[dctbl] = TRUE;
+ }
+ if (! did_ac[actbl]) {
+ htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
+ if (*htblptr == NULL)
+ *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
+ jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
+ did_ac[actbl] = TRUE;
+ }
+ }
+}
+
+
+#endif /* ENTROPY_OPT_SUPPORTED */
+
+
+/*
+ * Module initialization routine for Huffman entropy encoding.
+ */
+
+GLOBAL void
+jinit_huff_encoder (j_compress_ptr cinfo)
+{
+ huff_entropy_ptr entropy;
+ int i;
+
+ entropy = (huff_entropy_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(huff_entropy_encoder));
+ cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
+ entropy->pub.start_pass = start_pass_huff;
+
+ /* Mark tables unallocated */
+ for (i = 0; i < NUM_HUFF_TBLS; i++) {
+ entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
+#ifdef ENTROPY_OPT_SUPPORTED
+ entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
+#endif
+ }
+}
diff --git a/code/jpeg-6/jchuff.h b/code/jpeg-6/jchuff.h
new file mode 100755
index 0000000..0a81d54
--- /dev/null
+++ b/code/jpeg-6/jchuff.h
@@ -0,0 +1,34 @@
+/*
+ * jchuff.h
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains declarations for Huffman entropy encoding routines
+ * that are shared between the sequential encoder (jchuff.c) and the
+ * progressive encoder (jcphuff.c). No other modules need to see these.
+ */
+
+/* Derived data constructed for each Huffman table */
+
+typedef struct {
+ unsigned int ehufco[256]; /* code for each symbol */
+ char ehufsi[256]; /* length of code for each symbol */
+ /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
+} c_derived_tbl;
+
+/* Short forms of external names for systems with brain-damaged linkers. */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jpeg_make_c_derived_tbl jMkCDerived
+#define jpeg_gen_optimal_table jGenOptTbl
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+/* Expand a Huffman table definition into the derived format */
+EXTERN void jpeg_make_c_derived_tbl JPP((j_compress_ptr cinfo,
+ JHUFF_TBL * htbl, c_derived_tbl ** pdtbl));
+
+/* Generate an optimal table definition given the specified counts */
+EXTERN void jpeg_gen_optimal_table JPP((j_compress_ptr cinfo,
+ JHUFF_TBL * htbl, long freq[]));
diff --git a/code/jpeg-6/jcinit.c b/code/jpeg-6/jcinit.c
new file mode 100755
index 0000000..8055661
--- /dev/null
+++ b/code/jpeg-6/jcinit.c
@@ -0,0 +1,72 @@
+/*
+ * jcinit.c
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains initialization logic for the JPEG compressor.
+ * This routine is in charge of selecting the modules to be executed and
+ * making an initialization call to each one.
+ *
+ * Logically, this code belongs in jcmaster.c. It's split out because
+ * linking this routine implies linking the entire compression library.
+ * For a transcoding-only application, we want to be able to use jcmaster.c
+ * without linking in the whole library.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/*
+ * Master selection of compression modules.
+ * This is done once at the start of processing an image. We determine
+ * which modules will be used and give them appropriate initialization calls.
+ */
+
+GLOBAL void
+jinit_compress_master (j_compress_ptr cinfo)
+{
+ /* Initialize master control (includes parameter checking/processing) */
+ jinit_c_master_control(cinfo, FALSE /* full compression */);
+
+ /* Preprocessing */
+ if (! cinfo->raw_data_in) {
+ jinit_color_converter(cinfo);
+ jinit_downsampler(cinfo);
+ jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
+ }
+ /* Forward DCT */
+ jinit_forward_dct(cinfo);
+ /* Entropy encoding: either Huffman or arithmetic coding. */
+ if (cinfo->arith_code) {
+ ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
+ } else {
+ if (cinfo->progressive_mode) {
+#ifdef C_PROGRESSIVE_SUPPORTED
+ jinit_phuff_encoder(cinfo);
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else
+ jinit_huff_encoder(cinfo);
+ }
+
+ /* Need a full-image coefficient buffer in any multi-pass mode. */
+ jinit_c_coef_controller(cinfo,
+ (cinfo->num_scans > 1 || cinfo->optimize_coding));
+ jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
+
+ jinit_marker_writer(cinfo);
+
+ /* We can now tell the memory manager to allocate virtual arrays. */
+ (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
+
+ /* Write the datastream header (SOI) immediately.
+ * Frame and scan headers are postponed till later.
+ * This lets application insert special markers after the SOI.
+ */
+ (*cinfo->marker->write_file_header) (cinfo);
+}
diff --git a/code/jpeg-6/jcmainct.c b/code/jpeg-6/jcmainct.c
new file mode 100755
index 0000000..3a71c1f
--- /dev/null
+++ b/code/jpeg-6/jcmainct.c
@@ -0,0 +1,296 @@
+/*
+ * jcmainct.c
+ *
+ * Copyright (C) 1994-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the main buffer controller for compression.
+ * The main buffer lies between the pre-processor and the JPEG
+ * compressor proper; it holds downsampled data in the JPEG colorspace.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Note: currently, there is no operating mode in which a full-image buffer
+ * is needed at this step. If there were, that mode could not be used with
+ * "raw data" input, since this module is bypassed in that case. However,
+ * we've left the code here for possible use in special applications.
+ */
+#undef FULL_MAIN_BUFFER_SUPPORTED
+
+
+/* Private buffer controller object */
+
+typedef struct {
+ struct jpeg_c_main_controller pub; /* public fields */
+
+ JDIMENSION cur_iMCU_row; /* number of current iMCU row */
+ JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
+ boolean suspended; /* remember if we suspended output */
+ J_BUF_MODE pass_mode; /* current operating mode */
+
+ /* If using just a strip buffer, this points to the entire set of buffers
+ * (we allocate one for each component). In the full-image case, this
+ * points to the currently accessible strips of the virtual arrays.
+ */
+ JSAMPARRAY buffer[MAX_COMPONENTS];
+
+#ifdef FULL_MAIN_BUFFER_SUPPORTED
+ /* If using full-image storage, this array holds pointers to virtual-array
+ * control blocks for each component. Unused if not full-image storage.
+ */
+ jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
+#endif
+} my_main_controller;
+
+typedef my_main_controller * my_main_ptr;
+
+
+/* Forward declarations */
+METHODDEF void process_data_simple_main
+ JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
+ JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
+#ifdef FULL_MAIN_BUFFER_SUPPORTED
+METHODDEF void process_data_buffer_main
+ JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
+ JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
+#endif
+
+
+/*
+ * Initialize for a processing pass.
+ */
+
+METHODDEF void
+start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
+{
+ // bk001204 - don't use main...
+ my_main_ptr jmain = (my_main_ptr) cinfo->main;
+
+ /* Do nothing in raw-data mode. */
+ if (cinfo->raw_data_in)
+ return;
+
+ jmain->cur_iMCU_row = 0; /* initialize counters */
+ jmain->rowgroup_ctr = 0;
+ jmain->suspended = FALSE;
+ jmain->pass_mode = pass_mode; /* save mode for use by process_data */
+
+ switch (pass_mode) {
+ case JBUF_PASS_THRU:
+#ifdef FULL_MAIN_BUFFER_SUPPORTED
+ if (jmain->whole_image[0] != NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+#endif
+ jmain->pub.process_data = process_data_simple_main;
+ break;
+#ifdef FULL_MAIN_BUFFER_SUPPORTED
+ case JBUF_SAVE_SOURCE:
+ case JBUF_CRANK_DEST:
+ case JBUF_SAVE_AND_PASS:
+ if (jmain->whole_image[0] == NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ jmain->pub.process_data = process_data_buffer_main;
+ break;
+#endif
+ default:
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ break;
+ }
+}
+
+
+/*
+ * Process some data.
+ * This routine handles the simple pass-through mode,
+ * where we have only a strip buffer.
+ */
+
+METHODDEF void
+process_data_simple_main (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
+ JDIMENSION in_rows_avail)
+{
+ // bk001204 - don't use main
+ my_main_ptr jmain = (my_main_ptr) cinfo->main;
+
+ while (jmain->cur_iMCU_row < cinfo->total_iMCU_rows) {
+ /* Read input data if we haven't filled the main buffer yet */
+ if (jmain->rowgroup_ctr < DCTSIZE)
+ (*cinfo->prep->pre_process_data) (cinfo,
+ input_buf, in_row_ctr, in_rows_avail,
+ jmain->buffer, &jmain->rowgroup_ctr,
+ (JDIMENSION) DCTSIZE);
+
+ /* If we don't have a full iMCU row buffered, return to application for
+ * more data. Note that preprocessor will always pad to fill the iMCU row
+ * at the bottom of the image.
+ */
+ if (jmain->rowgroup_ctr != DCTSIZE)
+ return;
+
+ /* Send the completed row to the compressor */
+ if (! (*cinfo->coef->compress_data) (cinfo, jmain->buffer)) {
+ /* If compressor did not consume the whole row, then we must need to
+ * suspend processing and return to the application. In this situation
+ * we pretend we didn't yet consume the last input row; otherwise, if
+ * it happened to be the last row of the image, the application would
+ * think we were done.
+ */
+ if (! jmain->suspended) {
+ (*in_row_ctr)--;
+ jmain->suspended = TRUE;
+ }
+ return;
+ }
+ /* We did finish the row. Undo our little suspension hack if a previous
+ * call suspended; then mark the main buffer empty.
+ */
+ if (jmain->suspended) {
+ (*in_row_ctr)++;
+ jmain->suspended = FALSE;
+ }
+ jmain->rowgroup_ctr = 0;
+ jmain->cur_iMCU_row++;
+ }
+}
+
+
+#ifdef FULL_MAIN_BUFFER_SUPPORTED
+
+/*
+ * Process some data.
+ * This routine handles all of the modes that use a full-size buffer.
+ */
+
+METHODDEF void
+process_data_buffer_main (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
+ JDIMENSION in_rows_avail)
+{
+ my_main_ptr main = (my_main_ptr) cinfo->main;
+ int ci;
+ jpeg_component_info *compptr;
+ boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
+
+ while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
+ /* Realign the virtual buffers if at the start of an iMCU row. */
+ if (main->rowgroup_ctr == 0) {
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, main->whole_image[ci],
+ main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
+ (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
+ }
+ /* In a read pass, pretend we just read some source data. */
+ if (! writing) {
+ *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
+ main->rowgroup_ctr = DCTSIZE;
+ }
+ }
+
+ /* If a write pass, read input data until the current iMCU row is full. */
+ /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
+ if (writing) {
+ (*cinfo->prep->pre_process_data) (cinfo,
+ input_buf, in_row_ctr, in_rows_avail,
+ main->buffer, &main->rowgroup_ctr,
+ (JDIMENSION) DCTSIZE);
+ /* Return to application if we need more data to fill the iMCU row. */
+ if (main->rowgroup_ctr < DCTSIZE)
+ return;
+ }
+
+ /* Emit data, unless this is a sink-only pass. */
+ if (main->pass_mode != JBUF_SAVE_SOURCE) {
+ if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
+ /* If compressor did not consume the whole row, then we must need to
+ * suspend processing and return to the application. In this situation
+ * we pretend we didn't yet consume the last input row; otherwise, if
+ * it happened to be the last row of the image, the application would
+ * think we were done.
+ */
+ if (! main->suspended) {
+ (*in_row_ctr)--;
+ main->suspended = TRUE;
+ }
+ return;
+ }
+ /* We did finish the row. Undo our little suspension hack if a previous
+ * call suspended; then mark the main buffer empty.
+ */
+ if (main->suspended) {
+ (*in_row_ctr)++;
+ main->suspended = FALSE;
+ }
+ }
+
+ /* If get here, we are done with this iMCU row. Mark buffer empty. */
+ main->rowgroup_ctr = 0;
+ main->cur_iMCU_row++;
+ }
+}
+
+#endif /* FULL_MAIN_BUFFER_SUPPORTED */
+
+
+/*
+ * Initialize main buffer controller.
+ */
+
+GLOBAL void
+jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
+{
+ // bk001204 - don't use main
+ my_main_ptr jmain;
+ int ci;
+ jpeg_component_info *compptr;
+
+ jmain = (my_main_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_main_controller));
+ cinfo->main = (struct jpeg_c_main_controller *) jmain;
+ jmain->pub.start_pass = start_pass_main;
+
+ /* We don't need to create a buffer in raw-data mode. */
+ if (cinfo->raw_data_in)
+ return;
+
+ /* Create the buffer. It holds downsampled data, so each component
+ * may be of a different size.
+ */
+ if (need_full_buffer) {
+#ifdef FULL_MAIN_BUFFER_SUPPORTED
+ /* Allocate a full-image virtual array for each component */
+ /* Note we pad the bottom to a multiple of the iMCU height */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ jmain->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+ compptr->width_in_blocks * DCTSIZE,
+ (JDIMENSION) jround_up((long) compptr->height_in_blocks,
+ (long) compptr->v_samp_factor) * DCTSIZE,
+ (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
+ }
+#else
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+#endif
+ } else {
+#ifdef FULL_MAIN_BUFFER_SUPPORTED
+ jmain->whole_image[0] = NULL; /* flag for no virtual arrays */
+#endif
+ /* Allocate a strip buffer for each component */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ jmain->buffer[ci] = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ compptr->width_in_blocks * DCTSIZE,
+ (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
+ }
+ }
+}
diff --git a/code/jpeg-6/jcmarker.c b/code/jpeg-6/jcmarker.c
new file mode 100755
index 0000000..4220280
--- /dev/null
+++ b/code/jpeg-6/jcmarker.c
@@ -0,0 +1,639 @@
+/*
+ * jcmarker.c
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains routines to write JPEG datastream markers.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+typedef enum { /* JPEG marker codes */
+ M_SOF0 = 0xc0,
+ M_SOF1 = 0xc1,
+ M_SOF2 = 0xc2,
+ M_SOF3 = 0xc3,
+
+ M_SOF5 = 0xc5,
+ M_SOF6 = 0xc6,
+ M_SOF7 = 0xc7,
+
+ M_JPG = 0xc8,
+ M_SOF9 = 0xc9,
+ M_SOF10 = 0xca,
+ M_SOF11 = 0xcb,
+
+ M_SOF13 = 0xcd,
+ M_SOF14 = 0xce,
+ M_SOF15 = 0xcf,
+
+ M_DHT = 0xc4,
+
+ M_DAC = 0xcc,
+
+ M_RST0 = 0xd0,
+ M_RST1 = 0xd1,
+ M_RST2 = 0xd2,
+ M_RST3 = 0xd3,
+ M_RST4 = 0xd4,
+ M_RST5 = 0xd5,
+ M_RST6 = 0xd6,
+ M_RST7 = 0xd7,
+
+ M_SOI = 0xd8,
+ M_EOI = 0xd9,
+ M_SOS = 0xda,
+ M_DQT = 0xdb,
+ M_DNL = 0xdc,
+ M_DRI = 0xdd,
+ M_DHP = 0xde,
+ M_EXP = 0xdf,
+
+ M_APP0 = 0xe0,
+ M_APP1 = 0xe1,
+ M_APP2 = 0xe2,
+ M_APP3 = 0xe3,
+ M_APP4 = 0xe4,
+ M_APP5 = 0xe5,
+ M_APP6 = 0xe6,
+ M_APP7 = 0xe7,
+ M_APP8 = 0xe8,
+ M_APP9 = 0xe9,
+ M_APP10 = 0xea,
+ M_APP11 = 0xeb,
+ M_APP12 = 0xec,
+ M_APP13 = 0xed,
+ M_APP14 = 0xee,
+ M_APP15 = 0xef,
+
+ M_JPG0 = 0xf0,
+ M_JPG13 = 0xfd,
+ M_COM = 0xfe,
+
+ M_TEM = 0x01,
+
+ M_ERROR = 0x100
+} JPEG_MARKER;
+
+
+/*
+ * Basic output routines.
+ *
+ * Note that we do not support suspension while writing a marker.
+ * Therefore, an application using suspension must ensure that there is
+ * enough buffer space for the initial markers (typ. 600-700 bytes) before
+ * calling jpeg_start_compress, and enough space to write the trailing EOI
+ * (a few bytes) before calling jpeg_finish_compress. Multipass compression
+ * modes are not supported at all with suspension, so those two are the only
+ * points where markers will be written.
+ */
+
+LOCAL void
+emit_byte (j_compress_ptr cinfo, int val)
+/* Emit a byte */
+{
+ struct jpeg_destination_mgr * dest = cinfo->dest;
+
+ *(dest->next_output_byte)++ = (JOCTET) val;
+ if (--dest->free_in_buffer == 0) {
+ if (! (*dest->empty_output_buffer) (cinfo))
+ ERREXIT(cinfo, JERR_CANT_SUSPEND);
+ }
+}
+
+
+LOCAL void
+emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
+/* Emit a marker code */
+{
+ emit_byte(cinfo, 0xFF);
+ emit_byte(cinfo, (int) mark);
+}
+
+
+LOCAL void
+emit_2bytes (j_compress_ptr cinfo, int value)
+/* Emit a 2-byte integer; these are always MSB first in JPEG files */
+{
+ emit_byte(cinfo, (value >> 8) & 0xFF);
+ emit_byte(cinfo, value & 0xFF);
+}
+
+
+/*
+ * Routines to write specific marker types.
+ */
+
+LOCAL int
+emit_dqt (j_compress_ptr cinfo, int index)
+/* Emit a DQT marker */
+/* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
+{
+ JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
+ int prec;
+ int i;
+
+ if (qtbl == NULL)
+ ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
+
+ prec = 0;
+ for (i = 0; i < DCTSIZE2; i++) {
+ if (qtbl->quantval[i] > 255)
+ prec = 1;
+ }
+
+ if (! qtbl->sent_table) {
+ emit_marker(cinfo, M_DQT);
+
+ emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
+
+ emit_byte(cinfo, index + (prec<<4));
+
+ for (i = 0; i < DCTSIZE2; i++) {
+ if (prec)
+ emit_byte(cinfo, qtbl->quantval[i] >> 8);
+ emit_byte(cinfo, qtbl->quantval[i] & 0xFF);
+ }
+
+ qtbl->sent_table = TRUE;
+ }
+
+ return prec;
+}
+
+
+LOCAL void
+emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
+/* Emit a DHT marker */
+{
+ JHUFF_TBL * htbl;
+ int length, i;
+
+ if (is_ac) {
+ htbl = cinfo->ac_huff_tbl_ptrs[index];
+ index += 0x10; /* output index has AC bit set */
+ } else {
+ htbl = cinfo->dc_huff_tbl_ptrs[index];
+ }
+
+ if (htbl == NULL)
+ ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
+
+ if (! htbl->sent_table) {
+ emit_marker(cinfo, M_DHT);
+
+ length = 0;
+ for (i = 1; i <= 16; i++)
+ length += htbl->bits[i];
+
+ emit_2bytes(cinfo, length + 2 + 1 + 16);
+ emit_byte(cinfo, index);
+
+ for (i = 1; i <= 16; i++)
+ emit_byte(cinfo, htbl->bits[i]);
+
+ for (i = 0; i < length; i++)
+ emit_byte(cinfo, htbl->huffval[i]);
+
+ htbl->sent_table = TRUE;
+ }
+}
+
+
+LOCAL void
+emit_dac (j_compress_ptr cinfo)
+/* Emit a DAC marker */
+/* Since the useful info is so small, we want to emit all the tables in */
+/* one DAC marker. Therefore this routine does its own scan of the table. */
+{
+#ifdef C_ARITH_CODING_SUPPORTED
+ char dc_in_use[NUM_ARITH_TBLS];
+ char ac_in_use[NUM_ARITH_TBLS];
+ int length, i;
+ jpeg_component_info *compptr;
+
+ for (i = 0; i < NUM_ARITH_TBLS; i++)
+ dc_in_use[i] = ac_in_use[i] = 0;
+
+ for (i = 0; i < cinfo->comps_in_scan; i++) {
+ compptr = cinfo->cur_comp_info[i];
+ dc_in_use[compptr->dc_tbl_no] = 1;
+ ac_in_use[compptr->ac_tbl_no] = 1;
+ }
+
+ length = 0;
+ for (i = 0; i < NUM_ARITH_TBLS; i++)
+ length += dc_in_use[i] + ac_in_use[i];
+
+ emit_marker(cinfo, M_DAC);
+
+ emit_2bytes(cinfo, length*2 + 2);
+
+ for (i = 0; i < NUM_ARITH_TBLS; i++) {
+ if (dc_in_use[i]) {
+ emit_byte(cinfo, i);
+ emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
+ }
+ if (ac_in_use[i]) {
+ emit_byte(cinfo, i + 0x10);
+ emit_byte(cinfo, cinfo->arith_ac_K[i]);
+ }
+ }
+#endif /* C_ARITH_CODING_SUPPORTED */
+}
+
+
+LOCAL void
+emit_dri (j_compress_ptr cinfo)
+/* Emit a DRI marker */
+{
+ emit_marker(cinfo, M_DRI);
+
+ emit_2bytes(cinfo, 4); /* fixed length */
+
+ emit_2bytes(cinfo, (int) cinfo->restart_interval);
+}
+
+
+LOCAL void
+emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
+/* Emit a SOF marker */
+{
+ int ci;
+ jpeg_component_info *compptr;
+
+ emit_marker(cinfo, code);
+
+ emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
+
+ /* Make sure image isn't bigger than SOF field can handle */
+ if ((long) cinfo->image_height > 65535L ||
+ (long) cinfo->image_width > 65535L)
+ ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
+
+ emit_byte(cinfo, cinfo->data_precision);
+ emit_2bytes(cinfo, (int) cinfo->image_height);
+ emit_2bytes(cinfo, (int) cinfo->image_width);
+
+ emit_byte(cinfo, cinfo->num_components);
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ emit_byte(cinfo, compptr->component_id);
+ emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
+ emit_byte(cinfo, compptr->quant_tbl_no);
+ }
+}
+
+
+LOCAL void
+emit_sos (j_compress_ptr cinfo)
+/* Emit a SOS marker */
+{
+ int i, td, ta;
+ jpeg_component_info *compptr;
+
+ emit_marker(cinfo, M_SOS);
+
+ emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
+
+ emit_byte(cinfo, cinfo->comps_in_scan);
+
+ for (i = 0; i < cinfo->comps_in_scan; i++) {
+ compptr = cinfo->cur_comp_info[i];
+ emit_byte(cinfo, compptr->component_id);
+ td = compptr->dc_tbl_no;
+ ta = compptr->ac_tbl_no;
+ if (cinfo->progressive_mode) {
+ /* Progressive mode: only DC or only AC tables are used in one scan;
+ * furthermore, Huffman coding of DC refinement uses no table at all.
+ * We emit 0 for unused field(s); this is recommended by the P&M text
+ * but does not seem to be specified in the standard.
+ */
+ if (cinfo->Ss == 0) {
+ ta = 0; /* DC scan */
+ if (cinfo->Ah != 0 && !cinfo->arith_code)
+ td = 0; /* no DC table either */
+ } else {
+ td = 0; /* AC scan */
+ }
+ }
+ emit_byte(cinfo, (td << 4) + ta);
+ }
+
+ emit_byte(cinfo, cinfo->Ss);
+ emit_byte(cinfo, cinfo->Se);
+ emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
+}
+
+
+LOCAL void
+emit_jfif_app0 (j_compress_ptr cinfo)
+/* Emit a JFIF-compliant APP0 marker */
+{
+ /*
+ * Length of APP0 block (2 bytes)
+ * Block ID (4 bytes - ASCII "JFIF")
+ * Zero byte (1 byte to terminate the ID string)
+ * Version Major, Minor (2 bytes - 0x01, 0x01)
+ * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
+ * Xdpu (2 bytes - dots per unit horizontal)
+ * Ydpu (2 bytes - dots per unit vertical)
+ * Thumbnail X size (1 byte)
+ * Thumbnail Y size (1 byte)
+ */
+
+ emit_marker(cinfo, M_APP0);
+
+ emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
+
+ emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
+ emit_byte(cinfo, 0x46);
+ emit_byte(cinfo, 0x49);
+ emit_byte(cinfo, 0x46);
+ emit_byte(cinfo, 0);
+ /* We currently emit version code 1.01 since we use no 1.02 features.
+ * This may avoid complaints from some older decoders.
+ */
+ emit_byte(cinfo, 1); /* Major version */
+ emit_byte(cinfo, 1); /* Minor version */
+ emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
+ emit_2bytes(cinfo, (int) cinfo->X_density);
+ emit_2bytes(cinfo, (int) cinfo->Y_density);
+ emit_byte(cinfo, 0); /* No thumbnail image */
+ emit_byte(cinfo, 0);
+}
+
+
+LOCAL void
+emit_adobe_app14 (j_compress_ptr cinfo)
+/* Emit an Adobe APP14 marker */
+{
+ /*
+ * Length of APP14 block (2 bytes)
+ * Block ID (5 bytes - ASCII "Adobe")
+ * Version Number (2 bytes - currently 100)
+ * Flags0 (2 bytes - currently 0)
+ * Flags1 (2 bytes - currently 0)
+ * Color transform (1 byte)
+ *
+ * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
+ * now in circulation seem to use Version = 100, so that's what we write.
+ *
+ * We write the color transform byte as 1 if the JPEG color space is
+ * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
+ * whether the encoder performed a transformation, which is pretty useless.
+ */
+
+ emit_marker(cinfo, M_APP14);
+
+ emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
+
+ emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
+ emit_byte(cinfo, 0x64);
+ emit_byte(cinfo, 0x6F);
+ emit_byte(cinfo, 0x62);
+ emit_byte(cinfo, 0x65);
+ emit_2bytes(cinfo, 100); /* Version */
+ emit_2bytes(cinfo, 0); /* Flags0 */
+ emit_2bytes(cinfo, 0); /* Flags1 */
+ switch (cinfo->jpeg_color_space) {
+ case JCS_YCbCr:
+ emit_byte(cinfo, 1); /* Color transform = 1 */
+ break;
+ case JCS_YCCK:
+ emit_byte(cinfo, 2); /* Color transform = 2 */
+ break;
+ default:
+ emit_byte(cinfo, 0); /* Color transform = 0 */
+ break;
+ }
+}
+
+
+/*
+ * This routine is exported for possible use by applications.
+ * The intended use is to emit COM or APPn markers after calling
+ * jpeg_start_compress() and before the first jpeg_write_scanlines() call
+ * (hence, after write_file_header but before write_frame_header).
+ * Other uses are not guaranteed to produce desirable results.
+ */
+
+METHODDEF void
+write_any_marker (j_compress_ptr cinfo, int marker,
+ const JOCTET *dataptr, unsigned int datalen)
+/* Emit an arbitrary marker with parameters */
+{
+ if (datalen <= (unsigned int) 65533) { /* safety check */
+ emit_marker(cinfo, (JPEG_MARKER) marker);
+
+ emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
+
+ while (datalen--) {
+ emit_byte(cinfo, *dataptr);
+ dataptr++;
+ }
+ }
+}
+
+
+/*
+ * Write datastream header.
+ * This consists of an SOI and optional APPn markers.
+ * We recommend use of the JFIF marker, but not the Adobe marker,
+ * when using YCbCr or grayscale data. The JFIF marker should NOT
+ * be used for any other JPEG colorspace. The Adobe marker is helpful
+ * to distinguish RGB, CMYK, and YCCK colorspaces.
+ * Note that an application can write additional header markers after
+ * jpeg_start_compress returns.
+ */
+
+METHODDEF void
+write_file_header (j_compress_ptr cinfo)
+{
+ emit_marker(cinfo, M_SOI); /* first the SOI */
+
+ if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
+ emit_jfif_app0(cinfo);
+ if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
+ emit_adobe_app14(cinfo);
+}
+
+
+/*
+ * Write frame header.
+ * This consists of DQT and SOFn markers.
+ * Note that we do not emit the SOF until we have emitted the DQT(s).
+ * This avoids compatibility problems with incorrect implementations that
+ * try to error-check the quant table numbers as soon as they see the SOF.
+ */
+
+METHODDEF void
+write_frame_header (j_compress_ptr cinfo)
+{
+ int ci, prec;
+ boolean is_baseline;
+ jpeg_component_info *compptr;
+
+ /* Emit DQT for each quantization table.
+ * Note that emit_dqt() suppresses any duplicate tables.
+ */
+ prec = 0;
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ prec += emit_dqt(cinfo, compptr->quant_tbl_no);
+ }
+ /* now prec is nonzero iff there are any 16-bit quant tables. */
+
+ /* Check for a non-baseline specification.
+ * Note we assume that Huffman table numbers won't be changed later.
+ */
+ if (cinfo->arith_code || cinfo->progressive_mode ||
+ cinfo->data_precision != 8) {
+ is_baseline = FALSE;
+ } else {
+ is_baseline = TRUE;
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
+ is_baseline = FALSE;
+ }
+ if (prec && is_baseline) {
+ is_baseline = FALSE;
+ /* If it's baseline except for quantizer size, warn the user */
+ TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
+ }
+ }
+
+ /* Emit the proper SOF marker */
+ if (cinfo->arith_code) {
+ emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
+ } else {
+ if (cinfo->progressive_mode)
+ emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
+ else if (is_baseline)
+ emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
+ else
+ emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
+ }
+}
+
+
+/*
+ * Write scan header.
+ * This consists of DHT or DAC markers, optional DRI, and SOS.
+ * Compressed data will be written following the SOS.
+ */
+
+METHODDEF void
+write_scan_header (j_compress_ptr cinfo)
+{
+ int i;
+ jpeg_component_info *compptr;
+
+ if (cinfo->arith_code) {
+ /* Emit arith conditioning info. We may have some duplication
+ * if the file has multiple scans, but it's so small it's hardly
+ * worth worrying about.
+ */
+ emit_dac(cinfo);
+ } else {
+ /* Emit Huffman tables.
+ * Note that emit_dht() suppresses any duplicate tables.
+ */
+ for (i = 0; i < cinfo->comps_in_scan; i++) {
+ compptr = cinfo->cur_comp_info[i];
+ if (cinfo->progressive_mode) {
+ /* Progressive mode: only DC or only AC tables are used in one scan */
+ if (cinfo->Ss == 0) {
+ if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
+ emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
+ } else {
+ emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
+ }
+ } else {
+ /* Sequential mode: need both DC and AC tables */
+ emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
+ emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
+ }
+ }
+ }
+
+ /* Emit DRI if required --- note that DRI value could change for each scan.
+ * If it doesn't, a tiny amount of space is wasted in multiple-scan files.
+ * We assume DRI will never be nonzero for one scan and zero for a later one.
+ */
+ if (cinfo->restart_interval)
+ emit_dri(cinfo);
+
+ emit_sos(cinfo);
+}
+
+
+/*
+ * Write datastream trailer.
+ */
+
+METHODDEF void
+write_file_trailer (j_compress_ptr cinfo)
+{
+ emit_marker(cinfo, M_EOI);
+}
+
+
+/*
+ * Write an abbreviated table-specification datastream.
+ * This consists of SOI, DQT and DHT tables, and EOI.
+ * Any table that is defined and not marked sent_table = TRUE will be
+ * emitted. Note that all tables will be marked sent_table = TRUE at exit.
+ */
+
+METHODDEF void
+write_tables_only (j_compress_ptr cinfo)
+{
+ int i;
+
+ emit_marker(cinfo, M_SOI);
+
+ for (i = 0; i < NUM_QUANT_TBLS; i++) {
+ if (cinfo->quant_tbl_ptrs[i] != NULL)
+ (void) emit_dqt(cinfo, i);
+ }
+
+ if (! cinfo->arith_code) {
+ for (i = 0; i < NUM_HUFF_TBLS; i++) {
+ if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
+ emit_dht(cinfo, i, FALSE);
+ if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
+ emit_dht(cinfo, i, TRUE);
+ }
+ }
+
+ emit_marker(cinfo, M_EOI);
+}
+
+
+/*
+ * Initialize the marker writer module.
+ */
+
+GLOBAL void
+jinit_marker_writer (j_compress_ptr cinfo)
+{
+ /* Create the subobject */
+ cinfo->marker = (struct jpeg_marker_writer *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(struct jpeg_marker_writer));
+ /* Initialize method pointers */
+ cinfo->marker->write_any_marker = write_any_marker;
+ cinfo->marker->write_file_header = write_file_header;
+ cinfo->marker->write_frame_header = write_frame_header;
+ cinfo->marker->write_scan_header = write_scan_header;
+ cinfo->marker->write_file_trailer = write_file_trailer;
+ cinfo->marker->write_tables_only = write_tables_only;
+}
diff --git a/code/jpeg-6/jcmaster.c b/code/jpeg-6/jcmaster.c
new file mode 100755
index 0000000..6be2fd0
--- /dev/null
+++ b/code/jpeg-6/jcmaster.c
@@ -0,0 +1,578 @@
+/*
+ * jcmaster.c
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains master control logic for the JPEG compressor.
+ * These routines are concerned with parameter validation, initial setup,
+ * and inter-pass control (determining the number of passes and the work
+ * to be done in each pass).
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Private state */
+
+typedef enum {
+ main_pass, /* input data, also do first output step */
+ huff_opt_pass, /* Huffman code optimization pass */
+ output_pass /* data output pass */
+} c_pass_type;
+
+typedef struct {
+ struct jpeg_comp_master pub; /* public fields */
+
+ c_pass_type pass_type; /* the type of the current pass */
+
+ int pass_number; /* # of passes completed */
+ int total_passes; /* total # of passes needed */
+
+ int scan_number; /* current index in scan_info[] */
+} my_comp_master;
+
+typedef my_comp_master * my_master_ptr;
+
+
+/*
+ * Support routines that do various essential calculations.
+ */
+
+LOCAL void
+initial_setup (j_compress_ptr cinfo)
+/* Do computations that are needed before master selection phase */
+{
+ int ci;
+ jpeg_component_info *compptr;
+ long samplesperrow;
+ JDIMENSION jd_samplesperrow;
+
+ /* Sanity check on image dimensions */
+ if (cinfo->image_height <= 0 || cinfo->image_width <= 0
+ || cinfo->num_components <= 0 || cinfo->input_components <= 0)
+ ERREXIT(cinfo, JERR_EMPTY_IMAGE);
+
+ /* Make sure image isn't bigger than I can handle */
+ if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
+ (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
+ ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
+
+ /* Width of an input scanline must be representable as JDIMENSION. */
+ samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
+ jd_samplesperrow = (JDIMENSION) samplesperrow;
+ if ((long) jd_samplesperrow != samplesperrow)
+ ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
+
+ /* For now, precision must match compiled-in value... */
+ if (cinfo->data_precision != BITS_IN_JSAMPLE)
+ ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
+
+ /* Check that number of components won't exceed internal array sizes */
+ if (cinfo->num_components > MAX_COMPONENTS)
+ ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
+ MAX_COMPONENTS);
+
+ /* Compute maximum sampling factors; check factor validity */
+ cinfo->max_h_samp_factor = 1;
+ cinfo->max_v_samp_factor = 1;
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
+ compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
+ ERREXIT(cinfo, JERR_BAD_SAMPLING);
+ cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
+ compptr->h_samp_factor);
+ cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
+ compptr->v_samp_factor);
+ }
+
+ /* Compute dimensions of components */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Fill in the correct component_index value; don't rely on application */
+ compptr->component_index = ci;
+ /* For compression, we never do DCT scaling. */
+ compptr->DCT_scaled_size = DCTSIZE;
+ /* Size in DCT blocks */
+ compptr->width_in_blocks = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
+ (long) (cinfo->max_h_samp_factor * DCTSIZE));
+ compptr->height_in_blocks = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
+ (long) (cinfo->max_v_samp_factor * DCTSIZE));
+ /* Size in samples */
+ compptr->downsampled_width = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
+ (long) cinfo->max_h_samp_factor);
+ compptr->downsampled_height = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
+ (long) cinfo->max_v_samp_factor);
+ /* Mark component needed (this flag isn't actually used for compression) */
+ compptr->component_needed = TRUE;
+ }
+
+ /* Compute number of fully interleaved MCU rows (number of times that
+ * main controller will call coefficient controller).
+ */
+ cinfo->total_iMCU_rows = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height,
+ (long) (cinfo->max_v_samp_factor*DCTSIZE));
+}
+
+
+#ifdef C_MULTISCAN_FILES_SUPPORTED
+
+LOCAL void
+validate_script (j_compress_ptr cinfo)
+/* Verify that the scan script in cinfo->scan_info[] is valid; also
+ * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
+ */
+{
+ const jpeg_scan_info * scanptr;
+ int scanno, ncomps, ci, coefi, thisi;
+ int Ss, Se, Ah, Al;
+ boolean component_sent[MAX_COMPONENTS];
+#ifdef C_PROGRESSIVE_SUPPORTED
+ int * last_bitpos_ptr;
+ int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
+ /* -1 until that coefficient has been seen; then last Al for it */
+#endif
+
+ if (cinfo->num_scans <= 0)
+ ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
+
+ /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
+ * for progressive JPEG, no scan can have this.
+ */
+ scanptr = cinfo->scan_info;
+ if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
+#ifdef C_PROGRESSIVE_SUPPORTED
+ cinfo->progressive_mode = TRUE;
+ last_bitpos_ptr = & last_bitpos[0][0];
+ for (ci = 0; ci < cinfo->num_components; ci++)
+ for (coefi = 0; coefi < DCTSIZE2; coefi++)
+ *last_bitpos_ptr++ = -1;
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else {
+ cinfo->progressive_mode = FALSE;
+ for (ci = 0; ci < cinfo->num_components; ci++)
+ component_sent[ci] = FALSE;
+ }
+
+ for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
+ /* Validate component indexes */
+ ncomps = scanptr->comps_in_scan;
+ if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
+ ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
+ for (ci = 0; ci < ncomps; ci++) {
+ thisi = scanptr->component_index[ci];
+ if (thisi < 0 || thisi >= cinfo->num_components)
+ ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
+ /* Components must appear in SOF order within each scan */
+ if (ci > 0 && thisi <= scanptr->component_index[ci-1])
+ ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
+ }
+ /* Validate progression parameters */
+ Ss = scanptr->Ss;
+ Se = scanptr->Se;
+ Ah = scanptr->Ah;
+ Al = scanptr->Al;
+ if (cinfo->progressive_mode) {
+#ifdef C_PROGRESSIVE_SUPPORTED
+ if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
+ Ah < 0 || Ah > 13 || Al < 0 || Al > 13)
+ ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
+ if (Ss == 0) {
+ if (Se != 0) /* DC and AC together not OK */
+ ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
+ } else {
+ if (ncomps != 1) /* AC scans must be for only one component */
+ ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
+ }
+ for (ci = 0; ci < ncomps; ci++) {
+ last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
+ if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
+ ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
+ for (coefi = Ss; coefi <= Se; coefi++) {
+ if (last_bitpos_ptr[coefi] < 0) {
+ /* first scan of this coefficient */
+ if (Ah != 0)
+ ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
+ } else {
+ /* not first scan */
+ if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
+ ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
+ }
+ last_bitpos_ptr[coefi] = Al;
+ }
+ }
+#endif
+ } else {
+ /* For sequential JPEG, all progression parameters must be these: */
+ if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
+ ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
+ /* Make sure components are not sent twice */
+ for (ci = 0; ci < ncomps; ci++) {
+ thisi = scanptr->component_index[ci];
+ if (component_sent[thisi])
+ ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
+ component_sent[thisi] = TRUE;
+ }
+ }
+ }
+
+ /* Now verify that everything got sent. */
+ if (cinfo->progressive_mode) {
+#ifdef C_PROGRESSIVE_SUPPORTED
+ /* For progressive mode, we only check that at least some DC data
+ * got sent for each component; the spec does not require that all bits
+ * of all coefficients be transmitted. Would it be wiser to enforce
+ * transmission of all coefficient bits??
+ */
+ for (ci = 0; ci < cinfo->num_components; ci++) {
+ if (last_bitpos[ci][0] < 0)
+ ERREXIT(cinfo, JERR_MISSING_DATA);
+ }
+#endif
+ } else {
+ for (ci = 0; ci < cinfo->num_components; ci++) {
+ if (! component_sent[ci])
+ ERREXIT(cinfo, JERR_MISSING_DATA);
+ }
+ }
+}
+
+#endif /* C_MULTISCAN_FILES_SUPPORTED */
+
+
+LOCAL void
+select_scan_parameters (j_compress_ptr cinfo)
+/* Set up the scan parameters for the current scan */
+{
+ int ci;
+
+#ifdef C_MULTISCAN_FILES_SUPPORTED
+ if (cinfo->scan_info != NULL) {
+ /* Prepare for current scan --- the script is already validated */
+ my_master_ptr master = (my_master_ptr) cinfo->master;
+ const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
+
+ cinfo->comps_in_scan = scanptr->comps_in_scan;
+ for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
+ cinfo->cur_comp_info[ci] =
+ &cinfo->comp_info[scanptr->component_index[ci]];
+ }
+ cinfo->Ss = scanptr->Ss;
+ cinfo->Se = scanptr->Se;
+ cinfo->Ah = scanptr->Ah;
+ cinfo->Al = scanptr->Al;
+ }
+ else
+#endif
+ {
+ /* Prepare for single sequential-JPEG scan containing all components */
+ if (cinfo->num_components > MAX_COMPS_IN_SCAN)
+ ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
+ MAX_COMPS_IN_SCAN);
+ cinfo->comps_in_scan = cinfo->num_components;
+ for (ci = 0; ci < cinfo->num_components; ci++) {
+ cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
+ }
+ cinfo->Ss = 0;
+ cinfo->Se = DCTSIZE2-1;
+ cinfo->Ah = 0;
+ cinfo->Al = 0;
+ }
+}
+
+
+LOCAL void
+per_scan_setup (j_compress_ptr cinfo)
+/* Do computations that are needed before processing a JPEG scan */
+/* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
+{
+ int ci, mcublks, tmp;
+ jpeg_component_info *compptr;
+
+ if (cinfo->comps_in_scan == 1) {
+
+ /* Noninterleaved (single-component) scan */
+ compptr = cinfo->cur_comp_info[0];
+
+ /* Overall image size in MCUs */
+ cinfo->MCUs_per_row = compptr->width_in_blocks;
+ cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
+
+ /* For noninterleaved scan, always one block per MCU */
+ compptr->MCU_width = 1;
+ compptr->MCU_height = 1;
+ compptr->MCU_blocks = 1;
+ compptr->MCU_sample_width = DCTSIZE;
+ compptr->last_col_width = 1;
+ /* For noninterleaved scans, it is convenient to define last_row_height
+ * as the number of block rows present in the last iMCU row.
+ */
+ tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
+ if (tmp == 0) tmp = compptr->v_samp_factor;
+ compptr->last_row_height = tmp;
+
+ /* Prepare array describing MCU composition */
+ cinfo->blocks_in_MCU = 1;
+ cinfo->MCU_membership[0] = 0;
+
+ } else {
+
+ /* Interleaved (multi-component) scan */
+ if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
+ ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
+ MAX_COMPS_IN_SCAN);
+
+ /* Overall image size in MCUs */
+ cinfo->MCUs_per_row = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width,
+ (long) (cinfo->max_h_samp_factor*DCTSIZE));
+ cinfo->MCU_rows_in_scan = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height,
+ (long) (cinfo->max_v_samp_factor*DCTSIZE));
+
+ cinfo->blocks_in_MCU = 0;
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ /* Sampling factors give # of blocks of component in each MCU */
+ compptr->MCU_width = compptr->h_samp_factor;
+ compptr->MCU_height = compptr->v_samp_factor;
+ compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
+ compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
+ /* Figure number of non-dummy blocks in last MCU column & row */
+ tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
+ if (tmp == 0) tmp = compptr->MCU_width;
+ compptr->last_col_width = tmp;
+ tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
+ if (tmp == 0) tmp = compptr->MCU_height;
+ compptr->last_row_height = tmp;
+ /* Prepare array describing MCU composition */
+ mcublks = compptr->MCU_blocks;
+ if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
+ ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
+ while (mcublks-- > 0) {
+ cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
+ }
+ }
+
+ }
+
+ /* Convert restart specified in rows to actual MCU count. */
+ /* Note that count must fit in 16 bits, so we provide limiting. */
+ if (cinfo->restart_in_rows > 0) {
+ long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
+ cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
+ }
+}
+
+
+/*
+ * Per-pass setup.
+ * This is called at the beginning of each pass. We determine which modules
+ * will be active during this pass and give them appropriate start_pass calls.
+ * We also set is_last_pass to indicate whether any more passes will be
+ * required.
+ */
+
+METHODDEF void
+prepare_for_pass (j_compress_ptr cinfo)
+{
+ my_master_ptr master = (my_master_ptr) cinfo->master;
+
+ switch (master->pass_type) {
+ case main_pass:
+ /* Initial pass: will collect input data, and do either Huffman
+ * optimization or data output for the first scan.
+ */
+ select_scan_parameters(cinfo);
+ per_scan_setup(cinfo);
+ if (! cinfo->raw_data_in) {
+ (*cinfo->cconvert->start_pass) (cinfo);
+ (*cinfo->downsample->start_pass) (cinfo);
+ (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
+ }
+ (*cinfo->fdct->start_pass) (cinfo);
+ (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
+ (*cinfo->coef->start_pass) (cinfo,
+ (master->total_passes > 1 ?
+ JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
+ (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
+ if (cinfo->optimize_coding) {
+ /* No immediate data output; postpone writing frame/scan headers */
+ master->pub.call_pass_startup = FALSE;
+ } else {
+ /* Will write frame/scan headers at first jpeg_write_scanlines call */
+ master->pub.call_pass_startup = TRUE;
+ }
+ break;
+#ifdef ENTROPY_OPT_SUPPORTED
+ case huff_opt_pass:
+ /* Do Huffman optimization for a scan after the first one. */
+ select_scan_parameters(cinfo);
+ per_scan_setup(cinfo);
+ if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
+ (*cinfo->entropy->start_pass) (cinfo, TRUE);
+ (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
+ master->pub.call_pass_startup = FALSE;
+ break;
+ }
+ /* Special case: Huffman DC refinement scans need no Huffman table
+ * and therefore we can skip the optimization pass for them.
+ */
+ master->pass_type = output_pass;
+ master->pass_number++;
+ /*FALLTHROUGH*/
+#endif
+ case output_pass:
+ /* Do a data-output pass. */
+ /* We need not repeat per-scan setup if prior optimization pass did it. */
+ if (! cinfo->optimize_coding) {
+ select_scan_parameters(cinfo);
+ per_scan_setup(cinfo);
+ }
+ (*cinfo->entropy->start_pass) (cinfo, FALSE);
+ (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
+ /* We emit frame/scan headers now */
+ if (master->scan_number == 0)
+ (*cinfo->marker->write_frame_header) (cinfo);
+ (*cinfo->marker->write_scan_header) (cinfo);
+ master->pub.call_pass_startup = FALSE;
+ break;
+ default:
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+ }
+
+ master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
+
+ /* Set up progress monitor's pass info if present */
+ if (cinfo->progress != NULL) {
+ cinfo->progress->completed_passes = master->pass_number;
+ cinfo->progress->total_passes = master->total_passes;
+ }
+}
+
+
+/*
+ * Special start-of-pass hook.
+ * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
+ * In single-pass processing, we need this hook because we don't want to
+ * write frame/scan headers during jpeg_start_compress; we want to let the
+ * application write COM markers etc. between jpeg_start_compress and the
+ * jpeg_write_scanlines loop.
+ * In multi-pass processing, this routine is not used.
+ */
+
+METHODDEF void
+pass_startup (j_compress_ptr cinfo)
+{
+ cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
+
+ (*cinfo->marker->write_frame_header) (cinfo);
+ (*cinfo->marker->write_scan_header) (cinfo);
+}
+
+
+/*
+ * Finish up at end of pass.
+ */
+
+METHODDEF void
+finish_pass_master (j_compress_ptr cinfo)
+{
+ my_master_ptr master = (my_master_ptr) cinfo->master;
+
+ /* The entropy coder always needs an end-of-pass call,
+ * either to analyze statistics or to flush its output buffer.
+ */
+ (*cinfo->entropy->finish_pass) (cinfo);
+
+ /* Update state for next pass */
+ switch (master->pass_type) {
+ case main_pass:
+ /* next pass is either output of scan 0 (after optimization)
+ * or output of scan 1 (if no optimization).
+ */
+ master->pass_type = output_pass;
+ if (! cinfo->optimize_coding)
+ master->scan_number++;
+ break;
+ case huff_opt_pass:
+ /* next pass is always output of current scan */
+ master->pass_type = output_pass;
+ break;
+ case output_pass:
+ /* next pass is either optimization or output of next scan */
+ if (cinfo->optimize_coding)
+ master->pass_type = huff_opt_pass;
+ master->scan_number++;
+ break;
+ }
+
+ master->pass_number++;
+}
+
+
+/*
+ * Initialize master compression control.
+ */
+
+GLOBAL void
+jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
+{
+ my_master_ptr master;
+
+ master = (my_master_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_comp_master));
+ cinfo->master = (struct jpeg_comp_master *) master;
+ master->pub.prepare_for_pass = prepare_for_pass;
+ master->pub.pass_startup = pass_startup;
+ master->pub.finish_pass = finish_pass_master;
+ master->pub.is_last_pass = FALSE;
+
+ /* Validate parameters, determine derived values */
+ initial_setup(cinfo);
+
+ if (cinfo->scan_info != NULL) {
+#ifdef C_MULTISCAN_FILES_SUPPORTED
+ validate_script(cinfo);
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else {
+ cinfo->progressive_mode = FALSE;
+ cinfo->num_scans = 1;
+ }
+
+ if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
+ cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
+
+ /* Initialize my private state */
+ if (transcode_only) {
+ /* no main pass in transcoding */
+ if (cinfo->optimize_coding)
+ master->pass_type = huff_opt_pass;
+ else
+ master->pass_type = output_pass;
+ } else {
+ /* for normal compression, first pass is always this type: */
+ master->pass_type = main_pass;
+ }
+ master->scan_number = 0;
+ master->pass_number = 0;
+ if (cinfo->optimize_coding)
+ master->total_passes = cinfo->num_scans * 2;
+ else
+ master->total_passes = cinfo->num_scans;
+}
diff --git a/code/jpeg-6/jcomapi.c b/code/jpeg-6/jcomapi.c
new file mode 100755
index 0000000..8f417c0
--- /dev/null
+++ b/code/jpeg-6/jcomapi.c
@@ -0,0 +1,94 @@
+/*
+ * jcomapi.c
+ *
+ * Copyright (C) 1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains application interface routines that are used for both
+ * compression and decompression.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/*
+ * Abort processing of a JPEG compression or decompression operation,
+ * but don't destroy the object itself.
+ *
+ * For this, we merely clean up all the nonpermanent memory pools.
+ * Note that temp files (virtual arrays) are not allowed to belong to
+ * the permanent pool, so we will be able to close all temp files here.
+ * Closing a data source or destination, if necessary, is the application's
+ * responsibility.
+ */
+
+GLOBAL void
+jpeg_abort (j_common_ptr cinfo)
+{
+ int pool;
+
+ /* Releasing pools in reverse order might help avoid fragmentation
+ * with some (brain-damaged) malloc libraries.
+ */
+ for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
+ (*cinfo->mem->free_pool) (cinfo, pool);
+ }
+
+ /* Reset overall state for possible reuse of object */
+ cinfo->global_state = (cinfo->is_decompressor ? DSTATE_START : CSTATE_START);
+}
+
+
+/*
+ * Destruction of a JPEG object.
+ *
+ * Everything gets deallocated except the master jpeg_compress_struct itself
+ * and the error manager struct. Both of these are supplied by the application
+ * and must be freed, if necessary, by the application. (Often they are on
+ * the stack and so don't need to be freed anyway.)
+ * Closing a data source or destination, if necessary, is the application's
+ * responsibility.
+ */
+
+GLOBAL void
+jpeg_destroy (j_common_ptr cinfo)
+{
+ /* We need only tell the memory manager to release everything. */
+ /* NB: mem pointer is NULL if memory mgr failed to initialize. */
+ if (cinfo->mem != NULL)
+ (*cinfo->mem->self_destruct) (cinfo);
+ cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
+ cinfo->global_state = 0; /* mark it destroyed */
+}
+
+
+/*
+ * Convenience routines for allocating quantization and Huffman tables.
+ * (Would jutils.c be a more reasonable place to put these?)
+ */
+
+GLOBAL JQUANT_TBL *
+jpeg_alloc_quant_table (j_common_ptr cinfo)
+{
+ JQUANT_TBL *tbl;
+
+ tbl = (JQUANT_TBL *)
+ (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
+ tbl->sent_table = FALSE; /* make sure this is false in any new table */
+ return tbl;
+}
+
+
+GLOBAL JHUFF_TBL *
+jpeg_alloc_huff_table (j_common_ptr cinfo)
+{
+ JHUFF_TBL *tbl;
+
+ tbl = (JHUFF_TBL *)
+ (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
+ tbl->sent_table = FALSE; /* make sure this is false in any new table */
+ return tbl;
+}
diff --git a/code/jpeg-6/jconfig.h b/code/jpeg-6/jconfig.h
new file mode 100755
index 0000000..187ecfc
--- /dev/null
+++ b/code/jpeg-6/jconfig.h
@@ -0,0 +1,41 @@
+/* jconfig.wat --- jconfig.h for Watcom C/C++ on MS-DOS or OS/2. */
+/* see jconfig.doc for explanations */
+
+#define HAVE_PROTOTYPES
+#define HAVE_UNSIGNED_CHAR
+#define HAVE_UNSIGNED_SHORT
+/* #define void char */
+/* #define const */
+#define CHAR_IS_UNSIGNED
+#define HAVE_STDDEF_H
+#define HAVE_STDLIB_H
+#undef NEED_BSD_STRINGS
+#undef NEED_SYS_TYPES_H
+#undef NEED_FAR_POINTERS /* Watcom uses flat 32-bit addressing */
+#undef NEED_SHORT_EXTERNAL_NAMES
+#undef INCOMPLETE_TYPES_BROKEN
+
+#define JDCT_DEFAULT JDCT_FLOAT
+#define JDCT_FASTEST JDCT_FLOAT
+
+#ifdef JPEG_INTERNALS
+
+#undef RIGHT_SHIFT_IS_UNSIGNED
+
+#endif /* JPEG_INTERNALS */
+
+#ifdef JPEG_CJPEG_DJPEG
+
+#define BMP_SUPPORTED /* BMP image file format */
+#define GIF_SUPPORTED /* GIF image file format */
+#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
+#undef RLE_SUPPORTED /* Utah RLE image file format */
+#define TARGA_SUPPORTED /* Targa image file format */
+
+#undef TWO_FILE_COMMANDLINE /* optional */
+#define USE_SETMODE /* Needed to make one-file style work in Watcom */
+#undef NEED_SIGNAL_CATCHER /* Define this if you use jmemname.c */
+#undef DONT_USE_B_MODE
+#undef PROGRESS_REPORT /* optional */
+
+#endif /* JPEG_CJPEG_DJPEG */
diff --git a/code/jpeg-6/jcparam.c b/code/jpeg-6/jcparam.c
new file mode 100755
index 0000000..bf539f9
--- /dev/null
+++ b/code/jpeg-6/jcparam.c
@@ -0,0 +1,575 @@
+/*
+ * jcparam.c
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains optional default-setting code for the JPEG compressor.
+ * Applications do not have to use this file, but those that don't use it
+ * must know a lot more about the innards of the JPEG code.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/*
+ * Quantization table setup routines
+ */
+
+GLOBAL void
+jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
+ const unsigned int *basic_table,
+ int scale_factor, boolean force_baseline)
+/* Define a quantization table equal to the basic_table times
+ * a scale factor (given as a percentage).
+ * If force_baseline is TRUE, the computed quantization table entries
+ * are limited to 1..255 for JPEG baseline compatibility.
+ */
+{
+ JQUANT_TBL ** qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
+ int i;
+ long temp;
+
+ /* Safety check to ensure start_compress not called yet. */
+ if (cinfo->global_state != CSTATE_START)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+ if (*qtblptr == NULL)
+ *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
+
+ for (i = 0; i < DCTSIZE2; i++) {
+ temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
+ /* limit the values to the valid range */
+ if (temp <= 0L) temp = 1L;
+ if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
+ if (force_baseline && temp > 255L)
+ temp = 255L; /* limit to baseline range if requested */
+ (*qtblptr)->quantval[i] = (UINT16) temp;
+ }
+
+ /* Initialize sent_table FALSE so table will be written to JPEG file. */
+ (*qtblptr)->sent_table = FALSE;
+}
+
+
+GLOBAL void
+jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
+ boolean force_baseline)
+/* Set or change the 'quality' (quantization) setting, using default tables
+ * and a straight percentage-scaling quality scale. In most cases it's better
+ * to use jpeg_set_quality (below); this entry point is provided for
+ * applications that insist on a linear percentage scaling.
+ */
+{
+ /* This is the sample quantization table given in the JPEG spec section K.1,
+ * but expressed in zigzag order (as are all of our quant. tables).
+ * The spec says that the values given produce "good" quality, and
+ * when divided by 2, "very good" quality.
+ */
+ static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
+ 16, 11, 12, 14, 12, 10, 16, 14,
+ 13, 14, 18, 17, 16, 19, 24, 40,
+ 26, 24, 22, 22, 24, 49, 35, 37,
+ 29, 40, 58, 51, 61, 60, 57, 51,
+ 56, 55, 64, 72, 92, 78, 64, 68,
+ 87, 69, 55, 56, 80, 109, 81, 87,
+ 95, 98, 103, 104, 103, 62, 77, 113,
+ 121, 112, 100, 120, 92, 101, 103, 99
+ };
+ static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
+ 17, 18, 18, 24, 21, 24, 47, 26,
+ 26, 47, 99, 66, 56, 66, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99
+ };
+
+ /* Set up two quantization tables using the specified scaling */
+ jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
+ scale_factor, force_baseline);
+ jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
+ scale_factor, force_baseline);
+}
+
+
+GLOBAL int
+jpeg_quality_scaling (int quality)
+/* Convert a user-specified quality rating to a percentage scaling factor
+ * for an underlying quantization table, using our recommended scaling curve.
+ * The input 'quality' factor should be 0 (terrible) to 100 (very good).
+ */
+{
+ /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
+ if (quality <= 0) quality = 1;
+ if (quality > 100) quality = 100;
+
+ /* The basic table is used as-is (scaling 100) for a quality of 50.
+ * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
+ * note that at Q=100 the scaling is 0, which will cause j_add_quant_table
+ * to make all the table entries 1 (hence, no quantization loss).
+ * Qualities 1..50 are converted to scaling percentage 5000/Q.
+ */
+ if (quality < 50)
+ quality = 5000 / quality;
+ else
+ quality = 200 - quality*2;
+
+ return quality;
+}
+
+
+GLOBAL void
+jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
+/* Set or change the 'quality' (quantization) setting, using default tables.
+ * This is the standard quality-adjusting entry point for typical user
+ * interfaces; only those who want detailed control over quantization tables
+ * would use the preceding three routines directly.
+ */
+{
+ /* Convert user 0-100 rating to percentage scaling */
+ quality = jpeg_quality_scaling(quality);
+
+ /* Set up standard quality tables */
+ jpeg_set_linear_quality(cinfo, quality, force_baseline);
+}
+
+
+/*
+ * Huffman table setup routines
+ */
+
+LOCAL void
+add_huff_table (j_compress_ptr cinfo,
+ JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
+/* Define a Huffman table */
+{
+ if (*htblptr == NULL)
+ *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
+
+ MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
+ MEMCOPY((*htblptr)->huffval, val, SIZEOF((*htblptr)->huffval));
+
+ /* Initialize sent_table FALSE so table will be written to JPEG file. */
+ (*htblptr)->sent_table = FALSE;
+}
+
+
+LOCAL void
+std_huff_tables (j_compress_ptr cinfo)
+/* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
+/* IMPORTANT: these are only valid for 8-bit data precision! */
+{
+ static const UINT8 bits_dc_luminance[17] =
+ { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
+ static const UINT8 val_dc_luminance[] =
+ { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
+
+ static const UINT8 bits_dc_chrominance[17] =
+ { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
+ static const UINT8 val_dc_chrominance[] =
+ { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
+
+ static const UINT8 bits_ac_luminance[17] =
+ { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
+ static const UINT8 val_ac_luminance[] =
+ { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
+ 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
+ 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
+ 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
+ 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
+ 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
+ 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
+ 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
+ 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
+ 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
+ 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
+ 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
+ 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
+ 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
+ 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
+ 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
+ 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
+ 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
+ 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
+ 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
+ 0xf9, 0xfa };
+
+ static const UINT8 bits_ac_chrominance[17] =
+ { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
+ static const UINT8 val_ac_chrominance[] =
+ { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
+ 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
+ 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
+ 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
+ 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
+ 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
+ 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
+ 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
+ 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
+ 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
+ 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
+ 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
+ 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
+ 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
+ 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
+ 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
+ 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
+ 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
+ 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
+ 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
+ 0xf9, 0xfa };
+
+ add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
+ bits_dc_luminance, val_dc_luminance);
+ add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
+ bits_ac_luminance, val_ac_luminance);
+ add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
+ bits_dc_chrominance, val_dc_chrominance);
+ add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
+ bits_ac_chrominance, val_ac_chrominance);
+}
+
+
+/*
+ * Default parameter setup for compression.
+ *
+ * Applications that don't choose to use this routine must do their
+ * own setup of all these parameters. Alternately, you can call this
+ * to establish defaults and then alter parameters selectively. This
+ * is the recommended approach since, if we add any new parameters,
+ * your code will still work (they'll be set to reasonable defaults).
+ */
+
+GLOBAL void
+jpeg_set_defaults (j_compress_ptr cinfo)
+{
+ int i;
+
+ /* Safety check to ensure start_compress not called yet. */
+ if (cinfo->global_state != CSTATE_START)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+ /* Allocate comp_info array large enough for maximum component count.
+ * Array is made permanent in case application wants to compress
+ * multiple images at same param settings.
+ */
+ if (cinfo->comp_info == NULL)
+ cinfo->comp_info = (jpeg_component_info *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ MAX_COMPONENTS * SIZEOF(jpeg_component_info));
+
+ /* Initialize everything not dependent on the color space */
+
+ cinfo->data_precision = BITS_IN_JSAMPLE;
+ /* Set up two quantization tables using default quality of 75 */
+ jpeg_set_quality(cinfo, 75, TRUE);
+ /* Set up two Huffman tables */
+ std_huff_tables(cinfo);
+
+ /* Initialize default arithmetic coding conditioning */
+ for (i = 0; i < NUM_ARITH_TBLS; i++) {
+ cinfo->arith_dc_L[i] = 0;
+ cinfo->arith_dc_U[i] = 1;
+ cinfo->arith_ac_K[i] = 5;
+ }
+
+ /* Default is no multiple-scan output */
+ cinfo->scan_info = NULL;
+ cinfo->num_scans = 0;
+
+ /* Expect normal source image, not raw downsampled data */
+ cinfo->raw_data_in = FALSE;
+
+ /* Use Huffman coding, not arithmetic coding, by default */
+ cinfo->arith_code = FALSE;
+
+ /* By default, don't do extra passes to optimize entropy coding */
+ cinfo->optimize_coding = FALSE;
+ /* The standard Huffman tables are only valid for 8-bit data precision.
+ * If the precision is higher, force optimization on so that usable
+ * tables will be computed. This test can be removed if default tables
+ * are supplied that are valid for the desired precision.
+ */
+ if (cinfo->data_precision > 8)
+ cinfo->optimize_coding = TRUE;
+
+ /* By default, use the simpler non-cosited sampling alignment */
+ cinfo->CCIR601_sampling = FALSE;
+
+ /* No input smoothing */
+ cinfo->smoothing_factor = 0;
+
+ /* DCT algorithm preference */
+ cinfo->dct_method = JDCT_DEFAULT;
+
+ /* No restart markers */
+ cinfo->restart_interval = 0;
+ cinfo->restart_in_rows = 0;
+
+ /* Fill in default JFIF marker parameters. Note that whether the marker
+ * will actually be written is determined by jpeg_set_colorspace.
+ */
+ cinfo->density_unit = 0; /* Pixel size is unknown by default */
+ cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
+ cinfo->Y_density = 1;
+
+ /* Choose JPEG colorspace based on input space, set defaults accordingly */
+
+ jpeg_default_colorspace(cinfo);
+}
+
+
+/*
+ * Select an appropriate JPEG colorspace for in_color_space.
+ */
+
+GLOBAL void
+jpeg_default_colorspace (j_compress_ptr cinfo)
+{
+ switch (cinfo->in_color_space) {
+ case JCS_GRAYSCALE:
+ jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
+ break;
+ case JCS_RGB:
+ jpeg_set_colorspace(cinfo, JCS_YCbCr);
+ break;
+ case JCS_YCbCr:
+ jpeg_set_colorspace(cinfo, JCS_YCbCr);
+ break;
+ case JCS_CMYK:
+ jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
+ break;
+ case JCS_YCCK:
+ jpeg_set_colorspace(cinfo, JCS_YCCK);
+ break;
+ case JCS_UNKNOWN:
+ jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
+ break;
+ default:
+ ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
+ }
+}
+
+
+/*
+ * Set the JPEG colorspace, and choose colorspace-dependent default values.
+ */
+
+GLOBAL void
+jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
+{
+ jpeg_component_info * compptr;
+ int ci;
+
+#define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
+ (compptr = &cinfo->comp_info[index], \
+ compptr->component_id = (id), \
+ compptr->h_samp_factor = (hsamp), \
+ compptr->v_samp_factor = (vsamp), \
+ compptr->quant_tbl_no = (quant), \
+ compptr->dc_tbl_no = (dctbl), \
+ compptr->ac_tbl_no = (actbl) )
+
+ /* Safety check to ensure start_compress not called yet. */
+ if (cinfo->global_state != CSTATE_START)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+ /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
+ * tables 1 for chrominance components.
+ */
+
+ cinfo->jpeg_color_space = colorspace;
+
+ cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
+ cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
+
+ switch (colorspace) {
+ case JCS_GRAYSCALE:
+ cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
+ cinfo->num_components = 1;
+ /* JFIF specifies component ID 1 */
+ SET_COMP(0, 1, 1,1, 0, 0,0);
+ break;
+ case JCS_RGB:
+ cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
+ cinfo->num_components = 3;
+ SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
+ SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
+ SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
+ break;
+ case JCS_YCbCr:
+ cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
+ cinfo->num_components = 3;
+ /* JFIF specifies component IDs 1,2,3 */
+ /* We default to 2x2 subsamples of chrominance */
+ SET_COMP(0, 1, 2,2, 0, 0,0);
+ SET_COMP(1, 2, 1,1, 1, 1,1);
+ SET_COMP(2, 3, 1,1, 1, 1,1);
+ break;
+ case JCS_CMYK:
+ cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
+ cinfo->num_components = 4;
+ SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
+ SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
+ SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
+ SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
+ break;
+ case JCS_YCCK:
+ cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
+ cinfo->num_components = 4;
+ SET_COMP(0, 1, 2,2, 0, 0,0);
+ SET_COMP(1, 2, 1,1, 1, 1,1);
+ SET_COMP(2, 3, 1,1, 1, 1,1);
+ SET_COMP(3, 4, 2,2, 0, 0,0);
+ break;
+ case JCS_UNKNOWN:
+ cinfo->num_components = cinfo->input_components;
+ if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
+ ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
+ MAX_COMPONENTS);
+ for (ci = 0; ci < cinfo->num_components; ci++) {
+ SET_COMP(ci, ci, 1,1, 0, 0,0);
+ }
+ break;
+ default:
+ ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+ }
+}
+
+
+#ifdef C_PROGRESSIVE_SUPPORTED
+
+LOCAL jpeg_scan_info *
+fill_a_scan (jpeg_scan_info * scanptr, int ci,
+ int Ss, int Se, int Ah, int Al)
+/* Support routine: generate one scan for specified component */
+{
+ scanptr->comps_in_scan = 1;
+ scanptr->component_index[0] = ci;
+ scanptr->Ss = Ss;
+ scanptr->Se = Se;
+ scanptr->Ah = Ah;
+ scanptr->Al = Al;
+ scanptr++;
+ return scanptr;
+}
+
+LOCAL jpeg_scan_info *
+fill_scans (jpeg_scan_info * scanptr, int ncomps,
+ int Ss, int Se, int Ah, int Al)
+/* Support routine: generate one scan for each component */
+{
+ int ci;
+
+ for (ci = 0; ci < ncomps; ci++) {
+ scanptr->comps_in_scan = 1;
+ scanptr->component_index[0] = ci;
+ scanptr->Ss = Ss;
+ scanptr->Se = Se;
+ scanptr->Ah = Ah;
+ scanptr->Al = Al;
+ scanptr++;
+ }
+ return scanptr;
+}
+
+LOCAL jpeg_scan_info *
+fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
+/* Support routine: generate interleaved DC scan if possible, else N scans */
+{
+ int ci;
+
+ if (ncomps <= MAX_COMPS_IN_SCAN) {
+ /* Single interleaved DC scan */
+ scanptr->comps_in_scan = ncomps;
+ for (ci = 0; ci < ncomps; ci++)
+ scanptr->component_index[ci] = ci;
+ scanptr->Ss = scanptr->Se = 0;
+ scanptr->Ah = Ah;
+ scanptr->Al = Al;
+ scanptr++;
+ } else {
+ /* Noninterleaved DC scan for each component */
+ scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
+ }
+ return scanptr;
+}
+
+
+/*
+ * Create a recommended progressive-JPEG script.
+ * cinfo->num_components and cinfo->jpeg_color_space must be correct.
+ */
+
+GLOBAL void
+jpeg_simple_progression (j_compress_ptr cinfo)
+{
+ int ncomps = cinfo->num_components;
+ int nscans;
+ jpeg_scan_info * scanptr;
+
+ /* Safety check to ensure start_compress not called yet. */
+ if (cinfo->global_state != CSTATE_START)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+ /* Figure space needed for script. Calculation must match code below! */
+ if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
+ /* Custom script for YCbCr color images. */
+ nscans = 10;
+ } else {
+ /* All-purpose script for other color spaces. */
+ if (ncomps > MAX_COMPS_IN_SCAN)
+ nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
+ else
+ nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
+ }
+
+ /* Allocate space for script. */
+ /* We use permanent pool just in case application re-uses script. */
+ scanptr = (jpeg_scan_info *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ nscans * SIZEOF(jpeg_scan_info));
+ cinfo->scan_info = scanptr;
+ cinfo->num_scans = nscans;
+
+ if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
+ /* Custom script for YCbCr color images. */
+ /* Initial DC scan */
+ scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
+ /* Initial AC scan: get some luma data out in a hurry */
+ scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
+ /* Chroma data is too small to be worth expending many scans on */
+ scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
+ scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
+ /* Complete spectral selection for luma AC */
+ scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
+ /* Refine next bit of luma AC */
+ scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
+ /* Finish DC successive approximation */
+ scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
+ /* Finish AC successive approximation */
+ scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
+ scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
+ /* Luma bottom bit comes last since it's usually largest scan */
+ scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
+ } else {
+ /* All-purpose script for other color spaces. */
+ /* Successive approximation first pass */
+ scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
+ scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
+ scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
+ /* Successive approximation second pass */
+ scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
+ /* Successive approximation final pass */
+ scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
+ scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
+ }
+}
+
+#endif /* C_PROGRESSIVE_SUPPORTED */
diff --git a/code/jpeg-6/jcphuff.c b/code/jpeg-6/jcphuff.c
new file mode 100755
index 0000000..8d817e4
--- /dev/null
+++ b/code/jpeg-6/jcphuff.c
@@ -0,0 +1,829 @@
+/*
+ * jcphuff.c
+ *
+ * Copyright (C) 1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains Huffman entropy encoding routines for progressive JPEG.
+ *
+ * We do not support output suspension in this module, since the library
+ * currently does not allow multiple-scan files to be written with output
+ * suspension.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jchuff.h" /* Declarations shared with jchuff.c */
+
+#ifdef C_PROGRESSIVE_SUPPORTED
+
+/* Expanded entropy encoder object for progressive Huffman encoding. */
+
+typedef struct {
+ struct jpeg_entropy_encoder pub; /* public fields */
+
+ /* Mode flag: TRUE for optimization, FALSE for actual data output */
+ boolean gather_statistics;
+
+ /* Bit-level coding status.
+ * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
+ */
+ JOCTET * next_output_byte; /* => next byte to write in buffer */
+ size_t free_in_buffer; /* # of byte spaces remaining in buffer */
+ INT32 put_buffer; /* current bit-accumulation buffer */
+ int put_bits; /* # of bits now in it */
+ j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
+
+ /* Coding status for DC components */
+ int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
+
+ /* Coding status for AC components */
+ int ac_tbl_no; /* the table number of the single component */
+ unsigned int EOBRUN; /* run length of EOBs */
+ unsigned int BE; /* # of buffered correction bits before MCU */
+ char * bit_buffer; /* buffer for correction bits (1 per char) */
+ /* packing correction bits tightly would save some space but cost time... */
+
+ unsigned int restarts_to_go; /* MCUs left in this restart interval */
+ int next_restart_num; /* next restart number to write (0-7) */
+
+ /* Pointers to derived tables (these workspaces have image lifespan).
+ * Since any one scan codes only DC or only AC, we only need one set
+ * of tables, not one for DC and one for AC.
+ */
+ c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
+
+ /* Statistics tables for optimization; again, one set is enough */
+ long * count_ptrs[NUM_HUFF_TBLS];
+} phuff_entropy_encoder;
+
+typedef phuff_entropy_encoder * phuff_entropy_ptr;
+
+/* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
+ * buffer can hold. Larger sizes may slightly improve compression, but
+ * 1000 is already well into the realm of overkill.
+ * The minimum safe size is 64 bits.
+ */
+
+#define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
+
+/* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
+ * We assume that int right shift is unsigned if INT32 right shift is,
+ * which should be safe.
+ */
+
+#ifdef RIGHT_SHIFT_IS_UNSIGNED
+#define ISHIFT_TEMPS int ishift_temp;
+#define IRIGHT_SHIFT(x,shft) \
+ ((ishift_temp = (x)) < 0 ? \
+ (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
+ (ishift_temp >> (shft)))
+#else
+#define ISHIFT_TEMPS
+#define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
+#endif
+
+/* Forward declarations */
+METHODDEF boolean encode_mcu_DC_first JPP((j_compress_ptr cinfo,
+ JBLOCKROW *MCU_data));
+METHODDEF boolean encode_mcu_AC_first JPP((j_compress_ptr cinfo,
+ JBLOCKROW *MCU_data));
+METHODDEF boolean encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
+ JBLOCKROW *MCU_data));
+METHODDEF boolean encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
+ JBLOCKROW *MCU_data));
+METHODDEF void finish_pass_phuff JPP((j_compress_ptr cinfo));
+METHODDEF void finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
+
+
+/*
+ * Initialize for a Huffman-compressed scan using progressive JPEG.
+ */
+
+METHODDEF void
+start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
+{
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+ boolean is_DC_band;
+ int ci, tbl;
+ jpeg_component_info * compptr;
+
+ entropy->cinfo = cinfo;
+ entropy->gather_statistics = gather_statistics;
+
+ is_DC_band = (cinfo->Ss == 0);
+
+ /* We assume jcmaster.c already validated the scan parameters. */
+
+ /* Select execution routines */
+ if (cinfo->Ah == 0) {
+ if (is_DC_band)
+ entropy->pub.encode_mcu = encode_mcu_DC_first;
+ else
+ entropy->pub.encode_mcu = encode_mcu_AC_first;
+ } else {
+ if (is_DC_band)
+ entropy->pub.encode_mcu = encode_mcu_DC_refine;
+ else {
+ entropy->pub.encode_mcu = encode_mcu_AC_refine;
+ /* AC refinement needs a correction bit buffer */
+ if (entropy->bit_buffer == NULL)
+ entropy->bit_buffer = (char *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ MAX_CORR_BITS * SIZEOF(char));
+ }
+ }
+ if (gather_statistics)
+ entropy->pub.finish_pass = finish_pass_gather_phuff;
+ else
+ entropy->pub.finish_pass = finish_pass_phuff;
+
+ /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
+ * for AC coefficients.
+ */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ /* Initialize DC predictions to 0 */
+ entropy->last_dc_val[ci] = 0;
+ /* Make sure requested tables are present */
+ /* (In gather mode, tables need not be allocated yet) */
+ if (is_DC_band) {
+ if (cinfo->Ah != 0) /* DC refinement needs no table */
+ continue;
+ tbl = compptr->dc_tbl_no;
+ if (tbl < 0 || tbl >= NUM_HUFF_TBLS ||
+ (cinfo->dc_huff_tbl_ptrs[tbl] == NULL && !gather_statistics))
+ ERREXIT1(cinfo,JERR_NO_HUFF_TABLE, tbl);
+ } else {
+ entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
+ if (tbl < 0 || tbl >= NUM_HUFF_TBLS ||
+ (cinfo->ac_huff_tbl_ptrs[tbl] == NULL && !gather_statistics))
+ ERREXIT1(cinfo,JERR_NO_HUFF_TABLE, tbl);
+ }
+ if (gather_statistics) {
+ /* Allocate and zero the statistics tables */
+ /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
+ if (entropy->count_ptrs[tbl] == NULL)
+ entropy->count_ptrs[tbl] = (long *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ 257 * SIZEOF(long));
+ MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
+ } else {
+ /* Compute derived values for Huffman tables */
+ /* We may do this more than once for a table, but it's not expensive */
+ if (is_DC_band)
+ jpeg_make_c_derived_tbl(cinfo, cinfo->dc_huff_tbl_ptrs[tbl],
+ & entropy->derived_tbls[tbl]);
+ else
+ jpeg_make_c_derived_tbl(cinfo, cinfo->ac_huff_tbl_ptrs[tbl],
+ & entropy->derived_tbls[tbl]);
+ }
+ }
+
+ /* Initialize AC stuff */
+ entropy->EOBRUN = 0;
+ entropy->BE = 0;
+
+ /* Initialize bit buffer to empty */
+ entropy->put_buffer = 0;
+ entropy->put_bits = 0;
+
+ /* Initialize restart stuff */
+ entropy->restarts_to_go = cinfo->restart_interval;
+ entropy->next_restart_num = 0;
+}
+
+
+/* Outputting bytes to the file.
+ * NB: these must be called only when actually outputting,
+ * that is, entropy->gather_statistics == FALSE.
+ */
+
+/* Emit a byte */
+#define emit_byte(entropy,val) \
+ { *(entropy)->next_output_byte++ = (JOCTET) (val); \
+ if (--(entropy)->free_in_buffer == 0) \
+ dump_buffer(entropy); }
+
+
+LOCAL void
+dump_buffer (phuff_entropy_ptr entropy)
+/* Empty the output buffer; we do not support suspension in this module. */
+{
+ struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
+
+ if (! (*dest->empty_output_buffer) (entropy->cinfo))
+ ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
+ /* After a successful buffer dump, must reset buffer pointers */
+ entropy->next_output_byte = dest->next_output_byte;
+ entropy->free_in_buffer = dest->free_in_buffer;
+}
+
+
+/* Outputting bits to the file */
+
+/* Only the right 24 bits of put_buffer are used; the valid bits are
+ * left-justified in this part. At most 16 bits can be passed to emit_bits
+ * in one call, and we never retain more than 7 bits in put_buffer
+ * between calls, so 24 bits are sufficient.
+ */
+
+INLINE
+LOCAL void
+emit_bits (phuff_entropy_ptr entropy, unsigned int code, int size)
+/* Emit some bits, unless we are in gather mode */
+{
+ /* This routine is heavily used, so it's worth coding tightly. */
+ register INT32 put_buffer = (INT32) code;
+ register int put_bits = entropy->put_bits;
+
+ /* if size is 0, caller used an invalid Huffman table entry */
+ if (size == 0)
+ ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
+
+ if (entropy->gather_statistics)
+ return; /* do nothing if we're only getting stats */
+
+ put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
+
+ put_bits += size; /* new number of bits in buffer */
+
+ put_buffer <<= 24 - put_bits; /* align incoming bits */
+
+ put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
+
+ while (put_bits >= 8) {
+ int c = (int) ((put_buffer >> 16) & 0xFF);
+
+ emit_byte(entropy, c);
+ if (c == 0xFF) { /* need to stuff a zero byte? */
+ emit_byte(entropy, 0);
+ }
+ put_buffer <<= 8;
+ put_bits -= 8;
+ }
+
+ entropy->put_buffer = put_buffer; /* update variables */
+ entropy->put_bits = put_bits;
+}
+
+
+LOCAL void
+flush_bits (phuff_entropy_ptr entropy)
+{
+ emit_bits(entropy, 0x7F, 7); /* fill any partial byte with ones */
+ entropy->put_buffer = 0; /* and reset bit-buffer to empty */
+ entropy->put_bits = 0;
+}
+
+
+/*
+ * Emit (or just count) a Huffman symbol.
+ */
+
+INLINE
+LOCAL void
+emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
+{
+ if (entropy->gather_statistics)
+ entropy->count_ptrs[tbl_no][symbol]++;
+ else {
+ c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
+ emit_bits(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
+ }
+}
+
+
+/*
+ * Emit bits from a correction bit buffer.
+ */
+
+LOCAL void
+emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
+ unsigned int nbits)
+{
+ if (entropy->gather_statistics)
+ return; /* no real work */
+
+ while (nbits > 0) {
+ emit_bits(entropy, (unsigned int) (*bufstart), 1);
+ bufstart++;
+ nbits--;
+ }
+}
+
+
+/*
+ * Emit any pending EOBRUN symbol.
+ */
+
+LOCAL void
+emit_eobrun (phuff_entropy_ptr entropy)
+{
+ register int temp, nbits;
+
+ if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
+ temp = entropy->EOBRUN;
+ nbits = 0;
+ while ((temp >>= 1))
+ nbits++;
+
+ emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
+ if (nbits)
+ emit_bits(entropy, entropy->EOBRUN, nbits);
+
+ entropy->EOBRUN = 0;
+
+ /* Emit any buffered correction bits */
+ emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
+ entropy->BE = 0;
+ }
+}
+
+
+/*
+ * Emit a restart marker & resynchronize predictions.
+ */
+
+LOCAL void
+emit_restart (phuff_entropy_ptr entropy, int restart_num)
+{
+ int ci;
+
+ emit_eobrun(entropy);
+
+ if (! entropy->gather_statistics) {
+ flush_bits(entropy);
+ emit_byte(entropy, 0xFF);
+ emit_byte(entropy, JPEG_RST0 + restart_num);
+ }
+
+ if (entropy->cinfo->Ss == 0) {
+ /* Re-initialize DC predictions to 0 */
+ for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
+ entropy->last_dc_val[ci] = 0;
+ } else {
+ /* Re-initialize all AC-related fields to 0 */
+ entropy->EOBRUN = 0;
+ entropy->BE = 0;
+ }
+}
+
+
+/*
+ * MCU encoding for DC initial scan (either spectral selection,
+ * or first pass of successive approximation).
+ */
+
+METHODDEF boolean
+encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
+{
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+ register int temp, temp2;
+ register int nbits;
+ int blkn, ci;
+ int Al = cinfo->Al;
+ JBLOCKROW block;
+ jpeg_component_info * compptr;
+ ISHIFT_TEMPS
+
+ entropy->next_output_byte = cinfo->dest->next_output_byte;
+ entropy->free_in_buffer = cinfo->dest->free_in_buffer;
+
+ /* Emit restart marker if needed */
+ if (cinfo->restart_interval)
+ if (entropy->restarts_to_go == 0)
+ emit_restart(entropy, entropy->next_restart_num);
+
+ /* Encode the MCU data blocks */
+ for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
+ block = MCU_data[blkn];
+ ci = cinfo->MCU_membership[blkn];
+ compptr = cinfo->cur_comp_info[ci];
+
+ /* Compute the DC value after the required point transform by Al.
+ * This is simply an arithmetic right shift.
+ */
+ temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
+
+ /* DC differences are figured on the point-transformed values. */
+ temp = temp2 - entropy->last_dc_val[ci];
+ entropy->last_dc_val[ci] = temp2;
+
+ /* Encode the DC coefficient difference per section G.1.2.1 */
+ temp2 = temp;
+ if (temp < 0) {
+ temp = -temp; /* temp is abs value of input */
+ /* For a negative input, want temp2 = bitwise complement of abs(input) */
+ /* This code assumes we are on a two's complement machine */
+ temp2--;
+ }
+
+ /* Find the number of bits needed for the magnitude of the coefficient */
+ nbits = 0;
+ while (temp) {
+ nbits++;
+ temp >>= 1;
+ }
+
+ /* Count/emit the Huffman-coded symbol for the number of bits */
+ emit_symbol(entropy, compptr->dc_tbl_no, nbits);
+
+ /* Emit that number of bits of the value, if positive, */
+ /* or the complement of its magnitude, if negative. */
+ if (nbits) /* emit_bits rejects calls with size 0 */
+ emit_bits(entropy, (unsigned int) temp2, nbits);
+ }
+
+ cinfo->dest->next_output_byte = entropy->next_output_byte;
+ cinfo->dest->free_in_buffer = entropy->free_in_buffer;
+
+ /* Update restart-interval state too */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0) {
+ entropy->restarts_to_go = cinfo->restart_interval;
+ entropy->next_restart_num++;
+ entropy->next_restart_num &= 7;
+ }
+ entropy->restarts_to_go--;
+ }
+
+ return TRUE;
+}
+
+
+/*
+ * MCU encoding for AC initial scan (either spectral selection,
+ * or first pass of successive approximation).
+ */
+
+METHODDEF boolean
+encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
+{
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+ register int temp, temp2;
+ register int nbits;
+ register int r, k;
+ int Se = cinfo->Se;
+ int Al = cinfo->Al;
+ JBLOCKROW block;
+
+ entropy->next_output_byte = cinfo->dest->next_output_byte;
+ entropy->free_in_buffer = cinfo->dest->free_in_buffer;
+
+ /* Emit restart marker if needed */
+ if (cinfo->restart_interval)
+ if (entropy->restarts_to_go == 0)
+ emit_restart(entropy, entropy->next_restart_num);
+
+ /* Encode the MCU data block */
+ block = MCU_data[0];
+
+ /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
+
+ r = 0; /* r = run length of zeros */
+
+ for (k = cinfo->Ss; k <= Se; k++) {
+ if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
+ r++;
+ continue;
+ }
+ /* We must apply the point transform by Al. For AC coefficients this
+ * is an integer division with rounding towards 0. To do this portably
+ * in C, we shift after obtaining the absolute value; so the code is
+ * interwoven with finding the abs value (temp) and output bits (temp2).
+ */
+ if (temp < 0) {
+ temp = -temp; /* temp is abs value of input */
+ temp >>= Al; /* apply the point transform */
+ /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
+ temp2 = ~temp;
+ } else {
+ temp >>= Al; /* apply the point transform */
+ temp2 = temp;
+ }
+ /* Watch out for case that nonzero coef is zero after point transform */
+ if (temp == 0) {
+ r++;
+ continue;
+ }
+
+ /* Emit any pending EOBRUN */
+ if (entropy->EOBRUN > 0)
+ emit_eobrun(entropy);
+ /* if run length > 15, must emit special run-length-16 codes (0xF0) */
+ while (r > 15) {
+ emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
+ r -= 16;
+ }
+
+ /* Find the number of bits needed for the magnitude of the coefficient */
+ nbits = 1; /* there must be at least one 1 bit */
+ while ((temp >>= 1))
+ nbits++;
+
+ /* Count/emit Huffman symbol for run length / number of bits */
+ emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
+
+ /* Emit that number of bits of the value, if positive, */
+ /* or the complement of its magnitude, if negative. */
+ emit_bits(entropy, (unsigned int) temp2, nbits);
+
+ r = 0; /* reset zero run length */
+ }
+
+ if (r > 0) { /* If there are trailing zeroes, */
+ entropy->EOBRUN++; /* count an EOB */
+ if (entropy->EOBRUN == 0x7FFF)
+ emit_eobrun(entropy); /* force it out to avoid overflow */
+ }
+
+ cinfo->dest->next_output_byte = entropy->next_output_byte;
+ cinfo->dest->free_in_buffer = entropy->free_in_buffer;
+
+ /* Update restart-interval state too */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0) {
+ entropy->restarts_to_go = cinfo->restart_interval;
+ entropy->next_restart_num++;
+ entropy->next_restart_num &= 7;
+ }
+ entropy->restarts_to_go--;
+ }
+
+ return TRUE;
+}
+
+
+/*
+ * MCU encoding for DC successive approximation refinement scan.
+ * Note: we assume such scans can be multi-component, although the spec
+ * is not very clear on the point.
+ */
+
+METHODDEF boolean
+encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
+{
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+ register int temp;
+ int blkn;
+ int Al = cinfo->Al;
+ JBLOCKROW block;
+
+ entropy->next_output_byte = cinfo->dest->next_output_byte;
+ entropy->free_in_buffer = cinfo->dest->free_in_buffer;
+
+ /* Emit restart marker if needed */
+ if (cinfo->restart_interval)
+ if (entropy->restarts_to_go == 0)
+ emit_restart(entropy, entropy->next_restart_num);
+
+ /* Encode the MCU data blocks */
+ for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
+ block = MCU_data[blkn];
+
+ /* We simply emit the Al'th bit of the DC coefficient value. */
+ temp = (*block)[0];
+ emit_bits(entropy, (unsigned int) (temp >> Al), 1);
+ }
+
+ cinfo->dest->next_output_byte = entropy->next_output_byte;
+ cinfo->dest->free_in_buffer = entropy->free_in_buffer;
+
+ /* Update restart-interval state too */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0) {
+ entropy->restarts_to_go = cinfo->restart_interval;
+ entropy->next_restart_num++;
+ entropy->next_restart_num &= 7;
+ }
+ entropy->restarts_to_go--;
+ }
+
+ return TRUE;
+}
+
+
+/*
+ * MCU encoding for AC successive approximation refinement scan.
+ */
+
+METHODDEF boolean
+encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
+{
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+ register int temp;
+ register int r, k;
+ int EOB;
+ char *BR_buffer;
+ unsigned int BR;
+ int Se = cinfo->Se;
+ int Al = cinfo->Al;
+ JBLOCKROW block;
+ int absvalues[DCTSIZE2];
+
+ entropy->next_output_byte = cinfo->dest->next_output_byte;
+ entropy->free_in_buffer = cinfo->dest->free_in_buffer;
+
+ /* Emit restart marker if needed */
+ if (cinfo->restart_interval)
+ if (entropy->restarts_to_go == 0)
+ emit_restart(entropy, entropy->next_restart_num);
+
+ /* Encode the MCU data block */
+ block = MCU_data[0];
+
+ /* It is convenient to make a pre-pass to determine the transformed
+ * coefficients' absolute values and the EOB position.
+ */
+ EOB = 0;
+ for (k = cinfo->Ss; k <= Se; k++) {
+ temp = (*block)[jpeg_natural_order[k]];
+ /* We must apply the point transform by Al. For AC coefficients this
+ * is an integer division with rounding towards 0. To do this portably
+ * in C, we shift after obtaining the absolute value.
+ */
+ if (temp < 0)
+ temp = -temp; /* temp is abs value of input */
+ temp >>= Al; /* apply the point transform */
+ absvalues[k] = temp; /* save abs value for main pass */
+ if (temp == 1)
+ EOB = k; /* EOB = index of last newly-nonzero coef */
+ }
+
+ /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
+
+ r = 0; /* r = run length of zeros */
+ BR = 0; /* BR = count of buffered bits added now */
+ BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
+
+ for (k = cinfo->Ss; k <= Se; k++) {
+ if ((temp = absvalues[k]) == 0) {
+ r++;
+ continue;
+ }
+
+ /* Emit any required ZRLs, but not if they can be folded into EOB */
+ while (r > 15 && k <= EOB) {
+ /* emit any pending EOBRUN and the BE correction bits */
+ emit_eobrun(entropy);
+ /* Emit ZRL */
+ emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
+ r -= 16;
+ /* Emit buffered correction bits that must be associated with ZRL */
+ emit_buffered_bits(entropy, BR_buffer, BR);
+ BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
+ BR = 0;
+ }
+
+ /* If the coef was previously nonzero, it only needs a correction bit.
+ * NOTE: a straight translation of the spec's figure G.7 would suggest
+ * that we also need to test r > 15. But if r > 15, we can only get here
+ * if k > EOB, which implies that this coefficient is not 1.
+ */
+ if (temp > 1) {
+ /* The correction bit is the next bit of the absolute value. */
+ BR_buffer[BR++] = (char) (temp & 1);
+ continue;
+ }
+
+ /* Emit any pending EOBRUN and the BE correction bits */
+ emit_eobrun(entropy);
+
+ /* Count/emit Huffman symbol for run length / number of bits */
+ emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
+
+ /* Emit output bit for newly-nonzero coef */
+ temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
+ emit_bits(entropy, (unsigned int) temp, 1);
+
+ /* Emit buffered correction bits that must be associated with this code */
+ emit_buffered_bits(entropy, BR_buffer, BR);
+ BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
+ BR = 0;
+ r = 0; /* reset zero run length */
+ }
+
+ if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
+ entropy->EOBRUN++; /* count an EOB */
+ entropy->BE += BR; /* concat my correction bits to older ones */
+ /* We force out the EOB if we risk either:
+ * 1. overflow of the EOB counter;
+ * 2. overflow of the correction bit buffer during the next MCU.
+ */
+ if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
+ emit_eobrun(entropy);
+ }
+
+ cinfo->dest->next_output_byte = entropy->next_output_byte;
+ cinfo->dest->free_in_buffer = entropy->free_in_buffer;
+
+ /* Update restart-interval state too */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0) {
+ entropy->restarts_to_go = cinfo->restart_interval;
+ entropy->next_restart_num++;
+ entropy->next_restart_num &= 7;
+ }
+ entropy->restarts_to_go--;
+ }
+
+ return TRUE;
+}
+
+
+/*
+ * Finish up at the end of a Huffman-compressed progressive scan.
+ */
+
+METHODDEF void
+finish_pass_phuff (j_compress_ptr cinfo)
+{
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+
+ entropy->next_output_byte = cinfo->dest->next_output_byte;
+ entropy->free_in_buffer = cinfo->dest->free_in_buffer;
+
+ /* Flush out any buffered data */
+ emit_eobrun(entropy);
+ flush_bits(entropy);
+
+ cinfo->dest->next_output_byte = entropy->next_output_byte;
+ cinfo->dest->free_in_buffer = entropy->free_in_buffer;
+}
+
+
+/*
+ * Finish up a statistics-gathering pass and create the new Huffman tables.
+ */
+
+METHODDEF void
+finish_pass_gather_phuff (j_compress_ptr cinfo)
+{
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+ boolean is_DC_band;
+ int ci, tbl;
+ jpeg_component_info * compptr;
+ JHUFF_TBL **htblptr;
+ boolean did[NUM_HUFF_TBLS];
+
+ /* Flush out buffered data (all we care about is counting the EOB symbol) */
+ emit_eobrun(entropy);
+
+ is_DC_band = (cinfo->Ss == 0);
+
+ /* It's important not to apply jpeg_gen_optimal_table more than once
+ * per table, because it clobbers the input frequency counts!
+ */
+ MEMZERO(did, SIZEOF(did));
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ if (is_DC_band) {
+ if (cinfo->Ah != 0) /* DC refinement needs no table */
+ continue;
+ tbl = compptr->dc_tbl_no;
+ } else {
+ tbl = compptr->ac_tbl_no;
+ }
+ if (! did[tbl]) {
+ if (is_DC_band)
+ htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
+ else
+ htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
+ if (*htblptr == NULL)
+ *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
+ jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
+ did[tbl] = TRUE;
+ }
+ }
+}
+
+
+/*
+ * Module initialization routine for progressive Huffman entropy encoding.
+ */
+
+GLOBAL void
+jinit_phuff_encoder (j_compress_ptr cinfo)
+{
+ phuff_entropy_ptr entropy;
+ int i;
+
+ entropy = (phuff_entropy_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(phuff_entropy_encoder));
+ cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
+ entropy->pub.start_pass = start_pass_phuff;
+
+ /* Mark tables unallocated */
+ for (i = 0; i < NUM_HUFF_TBLS; i++) {
+ entropy->derived_tbls[i] = NULL;
+ entropy->count_ptrs[i] = NULL;
+ }
+ entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
+}
+
+#endif /* C_PROGRESSIVE_SUPPORTED */
diff --git a/code/jpeg-6/jcprepct.c b/code/jpeg-6/jcprepct.c
new file mode 100755
index 0000000..d6567fb
--- /dev/null
+++ b/code/jpeg-6/jcprepct.c
@@ -0,0 +1,371 @@
+/*
+ * jcprepct.c
+ *
+ * Copyright (C) 1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the compression preprocessing controller.
+ * This controller manages the color conversion, downsampling,
+ * and edge expansion steps.
+ *
+ * Most of the complexity here is associated with buffering input rows
+ * as required by the downsampler. See the comments at the head of
+ * jcsample.c for the downsampler's needs.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* At present, jcsample.c can request context rows only for smoothing.
+ * In the future, we might also need context rows for CCIR601 sampling
+ * or other more-complex downsampling procedures. The code to support
+ * context rows should be compiled only if needed.
+ */
+#ifdef INPUT_SMOOTHING_SUPPORTED
+#define CONTEXT_ROWS_SUPPORTED
+#endif
+
+
+/*
+ * For the simple (no-context-row) case, we just need to buffer one
+ * row group's worth of pixels for the downsampling step. At the bottom of
+ * the image, we pad to a full row group by replicating the last pixel row.
+ * The downsampler's last output row is then replicated if needed to pad
+ * out to a full iMCU row.
+ *
+ * When providing context rows, we must buffer three row groups' worth of
+ * pixels. Three row groups are physically allocated, but the row pointer
+ * arrays are made five row groups high, with the extra pointers above and
+ * below "wrapping around" to point to the last and first real row groups.
+ * This allows the downsampler to access the proper context rows.
+ * At the top and bottom of the image, we create dummy context rows by
+ * copying the first or last real pixel row. This copying could be avoided
+ * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
+ * trouble on the compression side.
+ */
+
+
+/* Private buffer controller object */
+
+typedef struct {
+ struct jpeg_c_prep_controller pub; /* public fields */
+
+ /* Downsampling input buffer. This buffer holds color-converted data
+ * until we have enough to do a downsample step.
+ */
+ JSAMPARRAY color_buf[MAX_COMPONENTS];
+
+ JDIMENSION rows_to_go; /* counts rows remaining in source image */
+ int next_buf_row; /* index of next row to store in color_buf */
+
+#ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
+ int this_row_group; /* starting row index of group to process */
+ int next_buf_stop; /* downsample when we reach this index */
+#endif
+} my_prep_controller;
+
+typedef my_prep_controller * my_prep_ptr;
+
+
+/*
+ * Initialize for a processing pass.
+ */
+
+METHODDEF void
+start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
+{
+ my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
+
+ if (pass_mode != JBUF_PASS_THRU)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+
+ /* Initialize total-height counter for detecting bottom of image */
+ prep->rows_to_go = cinfo->image_height;
+ /* Mark the conversion buffer empty */
+ prep->next_buf_row = 0;
+#ifdef CONTEXT_ROWS_SUPPORTED
+ /* Preset additional state variables for context mode.
+ * These aren't used in non-context mode, so we needn't test which mode.
+ */
+ prep->this_row_group = 0;
+ /* Set next_buf_stop to stop after two row groups have been read in. */
+ prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
+#endif
+}
+
+
+/*
+ * Expand an image vertically from height input_rows to height output_rows,
+ * by duplicating the bottom row.
+ */
+
+LOCAL void
+expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
+ int input_rows, int output_rows)
+{
+ register int row;
+
+ for (row = input_rows; row < output_rows; row++) {
+ jcopy_sample_rows(image_data, input_rows-1, image_data, row,
+ 1, num_cols);
+ }
+}
+
+
+/*
+ * Process some data in the simple no-context case.
+ *
+ * Preprocessor output data is counted in "row groups". A row group
+ * is defined to be v_samp_factor sample rows of each component.
+ * Downsampling will produce this much data from each max_v_samp_factor
+ * input rows.
+ */
+
+METHODDEF void
+pre_process_data (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
+ JDIMENSION in_rows_avail,
+ JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
+ JDIMENSION out_row_groups_avail)
+{
+ my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
+ int numrows, ci;
+ JDIMENSION inrows;
+ jpeg_component_info * compptr;
+
+ while (*in_row_ctr < in_rows_avail &&
+ *out_row_group_ctr < out_row_groups_avail) {
+ /* Do color conversion to fill the conversion buffer. */
+ inrows = in_rows_avail - *in_row_ctr;
+ numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
+ numrows = (int) MIN((JDIMENSION) numrows, inrows);
+ (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
+ prep->color_buf,
+ (JDIMENSION) prep->next_buf_row,
+ numrows);
+ *in_row_ctr += numrows;
+ prep->next_buf_row += numrows;
+ prep->rows_to_go -= numrows;
+ /* If at bottom of image, pad to fill the conversion buffer. */
+ if (prep->rows_to_go == 0 &&
+ prep->next_buf_row < cinfo->max_v_samp_factor) {
+ for (ci = 0; ci < cinfo->num_components; ci++) {
+ expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
+ prep->next_buf_row, cinfo->max_v_samp_factor);
+ }
+ prep->next_buf_row = cinfo->max_v_samp_factor;
+ }
+ /* If we've filled the conversion buffer, empty it. */
+ if (prep->next_buf_row == cinfo->max_v_samp_factor) {
+ (*cinfo->downsample->downsample) (cinfo,
+ prep->color_buf, (JDIMENSION) 0,
+ output_buf, *out_row_group_ctr);
+ prep->next_buf_row = 0;
+ (*out_row_group_ctr)++;
+ }
+ /* If at bottom of image, pad the output to a full iMCU height.
+ * Note we assume the caller is providing a one-iMCU-height output buffer!
+ */
+ if (prep->rows_to_go == 0 &&
+ *out_row_group_ctr < out_row_groups_avail) {
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ expand_bottom_edge(output_buf[ci],
+ compptr->width_in_blocks * DCTSIZE,
+ (int) (*out_row_group_ctr * compptr->v_samp_factor),
+ (int) (out_row_groups_avail * compptr->v_samp_factor));
+ }
+ *out_row_group_ctr = out_row_groups_avail;
+ break; /* can exit outer loop without test */
+ }
+ }
+}
+
+
+#ifdef CONTEXT_ROWS_SUPPORTED
+
+/*
+ * Process some data in the context case.
+ */
+
+METHODDEF void
+pre_process_context (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
+ JDIMENSION in_rows_avail,
+ JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
+ JDIMENSION out_row_groups_avail)
+{
+ my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
+ int numrows, ci;
+ int buf_height = cinfo->max_v_samp_factor * 3;
+ JDIMENSION inrows;
+ jpeg_component_info * compptr;
+
+ while (*out_row_group_ctr < out_row_groups_avail) {
+ if (*in_row_ctr < in_rows_avail) {
+ /* Do color conversion to fill the conversion buffer. */
+ inrows = in_rows_avail - *in_row_ctr;
+ numrows = prep->next_buf_stop - prep->next_buf_row;
+ numrows = (int) MIN((JDIMENSION) numrows, inrows);
+ (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
+ prep->color_buf,
+ (JDIMENSION) prep->next_buf_row,
+ numrows);
+ /* Pad at top of image, if first time through */
+ if (prep->rows_to_go == cinfo->image_height) {
+ for (ci = 0; ci < cinfo->num_components; ci++) {
+ int row;
+ for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
+ jcopy_sample_rows(prep->color_buf[ci], 0,
+ prep->color_buf[ci], -row,
+ 1, cinfo->image_width);
+ }
+ }
+ }
+ *in_row_ctr += numrows;
+ prep->next_buf_row += numrows;
+ prep->rows_to_go -= numrows;
+ } else {
+ /* Return for more data, unless we are at the bottom of the image. */
+ if (prep->rows_to_go != 0)
+ break;
+ }
+ /* If at bottom of image, pad to fill the conversion buffer. */
+ if (prep->rows_to_go == 0 &&
+ prep->next_buf_row < prep->next_buf_stop) {
+ for (ci = 0; ci < cinfo->num_components; ci++) {
+ expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
+ prep->next_buf_row, prep->next_buf_stop);
+ }
+ prep->next_buf_row = prep->next_buf_stop;
+ }
+ /* If we've gotten enough data, downsample a row group. */
+ if (prep->next_buf_row == prep->next_buf_stop) {
+ (*cinfo->downsample->downsample) (cinfo,
+ prep->color_buf,
+ (JDIMENSION) prep->this_row_group,
+ output_buf, *out_row_group_ctr);
+ (*out_row_group_ctr)++;
+ /* Advance pointers with wraparound as necessary. */
+ prep->this_row_group += cinfo->max_v_samp_factor;
+ if (prep->this_row_group >= buf_height)
+ prep->this_row_group = 0;
+ if (prep->next_buf_row >= buf_height)
+ prep->next_buf_row = 0;
+ prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
+ }
+ /* If at bottom of image, pad the output to a full iMCU height.
+ * Note we assume the caller is providing a one-iMCU-height output buffer!
+ */
+ if (prep->rows_to_go == 0 &&
+ *out_row_group_ctr < out_row_groups_avail) {
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ expand_bottom_edge(output_buf[ci],
+ compptr->width_in_blocks * DCTSIZE,
+ (int) (*out_row_group_ctr * compptr->v_samp_factor),
+ (int) (out_row_groups_avail * compptr->v_samp_factor));
+ }
+ *out_row_group_ctr = out_row_groups_avail;
+ break; /* can exit outer loop without test */
+ }
+ }
+}
+
+
+/*
+ * Create the wrapped-around downsampling input buffer needed for context mode.
+ */
+
+LOCAL void
+create_context_buffer (j_compress_ptr cinfo)
+{
+ my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
+ int rgroup_height = cinfo->max_v_samp_factor;
+ int ci, i;
+ jpeg_component_info * compptr;
+ JSAMPARRAY true_buffer, fake_buffer;
+
+ /* Grab enough space for fake row pointers for all the components;
+ * we need five row groups' worth of pointers for each component.
+ */
+ fake_buffer = (JSAMPARRAY)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (cinfo->num_components * 5 * rgroup_height) *
+ SIZEOF(JSAMPROW));
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Allocate the actual buffer space (3 row groups) for this component.
+ * We make the buffer wide enough to allow the downsampler to edge-expand
+ * horizontally within the buffer, if it so chooses.
+ */
+ true_buffer = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
+ cinfo->max_h_samp_factor) / compptr->h_samp_factor),
+ (JDIMENSION) (3 * rgroup_height));
+ /* Copy true buffer row pointers into the middle of the fake row array */
+ MEMCOPY(fake_buffer + rgroup_height, true_buffer,
+ 3 * rgroup_height * SIZEOF(JSAMPROW));
+ /* Fill in the above and below wraparound pointers */
+ for (i = 0; i < rgroup_height; i++) {
+ fake_buffer[i] = true_buffer[2 * rgroup_height + i];
+ fake_buffer[4 * rgroup_height + i] = true_buffer[i];
+ }
+ prep->color_buf[ci] = fake_buffer + rgroup_height;
+ fake_buffer += 5 * rgroup_height; /* point to space for next component */
+ }
+}
+
+#endif /* CONTEXT_ROWS_SUPPORTED */
+
+
+/*
+ * Initialize preprocessing controller.
+ */
+
+GLOBAL void
+jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
+{
+ my_prep_ptr prep;
+ int ci;
+ jpeg_component_info * compptr;
+
+ if (need_full_buffer) /* safety check */
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+
+ prep = (my_prep_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_prep_controller));
+ cinfo->prep = (struct jpeg_c_prep_controller *) prep;
+ prep->pub.start_pass = start_pass_prep;
+
+ /* Allocate the color conversion buffer.
+ * We make the buffer wide enough to allow the downsampler to edge-expand
+ * horizontally within the buffer, if it so chooses.
+ */
+ if (cinfo->downsample->need_context_rows) {
+ /* Set up to provide context rows */
+#ifdef CONTEXT_ROWS_SUPPORTED
+ prep->pub.pre_process_data = pre_process_context;
+ create_context_buffer(cinfo);
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else {
+ /* No context, just make it tall enough for one row group */
+ prep->pub.pre_process_data = pre_process_data;
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
+ cinfo->max_h_samp_factor) / compptr->h_samp_factor),
+ (JDIMENSION) cinfo->max_v_samp_factor);
+ }
+ }
+}
diff --git a/code/jpeg-6/jcsample.c b/code/jpeg-6/jcsample.c
new file mode 100755
index 0000000..06b18f4
--- /dev/null
+++ b/code/jpeg-6/jcsample.c
@@ -0,0 +1,519 @@
+/*
+ * jcsample.c
+ *
+ * Copyright (C) 1991-1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains downsampling routines.
+ *
+ * Downsampling input data is counted in "row groups". A row group
+ * is defined to be max_v_samp_factor pixel rows of each component,
+ * from which the downsampler produces v_samp_factor sample rows.
+ * A single row group is processed in each call to the downsampler module.
+ *
+ * The downsampler is responsible for edge-expansion of its output data
+ * to fill an integral number of DCT blocks horizontally. The source buffer
+ * may be modified if it is helpful for this purpose (the source buffer is
+ * allocated wide enough to correspond to the desired output width).
+ * The caller (the prep controller) is responsible for vertical padding.
+ *
+ * The downsampler may request "context rows" by setting need_context_rows
+ * during startup. In this case, the input arrays will contain at least
+ * one row group's worth of pixels above and below the passed-in data;
+ * the caller will create dummy rows at image top and bottom by replicating
+ * the first or last real pixel row.
+ *
+ * An excellent reference for image resampling is
+ * Digital Image Warping, George Wolberg, 1990.
+ * Pub. by IEEE Computer Society Press, Los Alamitos, CA. ISBN 0-8186-8944-7.
+ *
+ * The downsampling algorithm used here is a simple average of the source
+ * pixels covered by the output pixel. The hi-falutin sampling literature
+ * refers to this as a "box filter". In general the characteristics of a box
+ * filter are not very good, but for the specific cases we normally use (1:1
+ * and 2:1 ratios) the box is equivalent to a "triangle filter" which is not
+ * nearly so bad. If you intend to use other sampling ratios, you'd be well
+ * advised to improve this code.
+ *
+ * A simple input-smoothing capability is provided. This is mainly intended
+ * for cleaning up color-dithered GIF input files (if you find it inadequate,
+ * we suggest using an external filtering program such as pnmconvol). When
+ * enabled, each input pixel P is replaced by a weighted sum of itself and its
+ * eight neighbors. P's weight is 1-8*SF and each neighbor's weight is SF,
+ * where SF = (smoothing_factor / 1024).
+ * Currently, smoothing is only supported for 2h2v sampling factors.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Pointer to routine to downsample a single component */
+typedef JMETHOD(void, downsample1_ptr,
+ (j_compress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY input_data, JSAMPARRAY output_data));
+
+/* Private subobject */
+
+typedef struct {
+ struct jpeg_downsampler pub; /* public fields */
+
+ /* Downsampling method pointers, one per component */
+ downsample1_ptr methods[MAX_COMPONENTS];
+} my_downsampler;
+
+typedef my_downsampler * my_downsample_ptr;
+
+
+/*
+ * Initialize for a downsampling pass.
+ */
+
+METHODDEF void
+start_pass_downsample (j_compress_ptr cinfo)
+{
+ /* no work for now */
+}
+
+
+/*
+ * Expand a component horizontally from width input_cols to width output_cols,
+ * by duplicating the rightmost samples.
+ */
+
+LOCAL void
+expand_right_edge (JSAMPARRAY image_data, int num_rows,
+ JDIMENSION input_cols, JDIMENSION output_cols)
+{
+ register JSAMPROW ptr;
+ register JSAMPLE pixval;
+ register int count;
+ int row;
+ int numcols = (int) (output_cols - input_cols);
+
+ if (numcols > 0) {
+ for (row = 0; row < num_rows; row++) {
+ ptr = image_data[row] + input_cols;
+ pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
+ for (count = numcols; count > 0; count--)
+ *ptr++ = pixval;
+ }
+ }
+}
+
+
+/*
+ * Do downsampling for a whole row group (all components).
+ *
+ * In this version we simply downsample each component independently.
+ */
+
+METHODDEF void
+sep_downsample (j_compress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION in_row_index,
+ JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
+{
+ my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
+ int ci;
+ jpeg_component_info * compptr;
+ JSAMPARRAY in_ptr, out_ptr;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ in_ptr = input_buf[ci] + in_row_index;
+ out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
+ (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
+ }
+}
+
+
+/*
+ * Downsample pixel values of a single component.
+ * One row group is processed per call.
+ * This version handles arbitrary integral sampling ratios, without smoothing.
+ * Note that this version is not actually used for customary sampling ratios.
+ */
+
+METHODDEF void
+int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY input_data, JSAMPARRAY output_data)
+{
+ int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
+ JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
+ JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
+ JSAMPROW inptr, outptr;
+ INT32 outvalue;
+
+ h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
+ v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
+ numpix = h_expand * v_expand;
+ numpix2 = numpix/2;
+
+ /* Expand input data enough to let all the output samples be generated
+ * by the standard loop. Special-casing padded output would be more
+ * efficient.
+ */
+ expand_right_edge(input_data, cinfo->max_v_samp_factor,
+ cinfo->image_width, output_cols * h_expand);
+
+ inrow = 0;
+ for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
+ outptr = output_data[outrow];
+ for (outcol = 0, outcol_h = 0; outcol < output_cols;
+ outcol++, outcol_h += h_expand) {
+ outvalue = 0;
+ for (v = 0; v < v_expand; v++) {
+ inptr = input_data[inrow+v] + outcol_h;
+ for (h = 0; h < h_expand; h++) {
+ outvalue += (INT32) GETJSAMPLE(*inptr++);
+ }
+ }
+ *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
+ }
+ inrow += v_expand;
+ }
+}
+
+
+/*
+ * Downsample pixel values of a single component.
+ * This version handles the special case of a full-size component,
+ * without smoothing.
+ */
+
+METHODDEF void
+fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY input_data, JSAMPARRAY output_data)
+{
+ /* Copy the data */
+ jcopy_sample_rows(input_data, 0, output_data, 0,
+ cinfo->max_v_samp_factor, cinfo->image_width);
+ /* Edge-expand */
+ expand_right_edge(output_data, cinfo->max_v_samp_factor,
+ cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
+}
+
+
+/*
+ * Downsample pixel values of a single component.
+ * This version handles the common case of 2:1 horizontal and 1:1 vertical,
+ * without smoothing.
+ *
+ * A note about the "bias" calculations: when rounding fractional values to
+ * integer, we do not want to always round 0.5 up to the next integer.
+ * If we did that, we'd introduce a noticeable bias towards larger values.
+ * Instead, this code is arranged so that 0.5 will be rounded up or down at
+ * alternate pixel locations (a simple ordered dither pattern).
+ */
+
+METHODDEF void
+h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY input_data, JSAMPARRAY output_data)
+{
+ int outrow;
+ JDIMENSION outcol;
+ JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
+ register JSAMPROW inptr, outptr;
+ register int bias;
+
+ /* Expand input data enough to let all the output samples be generated
+ * by the standard loop. Special-casing padded output would be more
+ * efficient.
+ */
+ expand_right_edge(input_data, cinfo->max_v_samp_factor,
+ cinfo->image_width, output_cols * 2);
+
+ for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
+ outptr = output_data[outrow];
+ inptr = input_data[outrow];
+ bias = 0; /* bias = 0,1,0,1,... for successive samples */
+ for (outcol = 0; outcol < output_cols; outcol++) {
+ *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
+ + bias) >> 1);
+ bias ^= 1; /* 0=>1, 1=>0 */
+ inptr += 2;
+ }
+ }
+}
+
+
+/*
+ * Downsample pixel values of a single component.
+ * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
+ * without smoothing.
+ */
+
+METHODDEF void
+h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY input_data, JSAMPARRAY output_data)
+{
+ int inrow, outrow;
+ JDIMENSION outcol;
+ JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
+ register JSAMPROW inptr0, inptr1, outptr;
+ register int bias;
+
+ /* Expand input data enough to let all the output samples be generated
+ * by the standard loop. Special-casing padded output would be more
+ * efficient.
+ */
+ expand_right_edge(input_data, cinfo->max_v_samp_factor,
+ cinfo->image_width, output_cols * 2);
+
+ inrow = 0;
+ for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
+ outptr = output_data[outrow];
+ inptr0 = input_data[inrow];
+ inptr1 = input_data[inrow+1];
+ bias = 1; /* bias = 1,2,1,2,... for successive samples */
+ for (outcol = 0; outcol < output_cols; outcol++) {
+ *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
+ GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
+ + bias) >> 2);
+ bias ^= 3; /* 1=>2, 2=>1 */
+ inptr0 += 2; inptr1 += 2;
+ }
+ inrow += 2;
+ }
+}
+
+
+#ifdef INPUT_SMOOTHING_SUPPORTED
+
+/*
+ * Downsample pixel values of a single component.
+ * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
+ * with smoothing. One row of context is required.
+ */
+
+METHODDEF void
+h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY input_data, JSAMPARRAY output_data)
+{
+ int inrow, outrow;
+ JDIMENSION colctr;
+ JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
+ register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
+ INT32 membersum, neighsum, memberscale, neighscale;
+
+ /* Expand input data enough to let all the output samples be generated
+ * by the standard loop. Special-casing padded output would be more
+ * efficient.
+ */
+ expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
+ cinfo->image_width, output_cols * 2);
+
+ /* We don't bother to form the individual "smoothed" input pixel values;
+ * we can directly compute the output which is the average of the four
+ * smoothed values. Each of the four member pixels contributes a fraction
+ * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
+ * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
+ * output. The four corner-adjacent neighbor pixels contribute a fraction
+ * SF to just one smoothed pixel, or SF/4 to the final output; while the
+ * eight edge-adjacent neighbors contribute SF to each of two smoothed
+ * pixels, or SF/2 overall. In order to use integer arithmetic, these
+ * factors are scaled by 2^16 = 65536.
+ * Also recall that SF = smoothing_factor / 1024.
+ */
+
+ memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
+ neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
+
+ inrow = 0;
+ for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
+ outptr = output_data[outrow];
+ inptr0 = input_data[inrow];
+ inptr1 = input_data[inrow+1];
+ above_ptr = input_data[inrow-1];
+ below_ptr = input_data[inrow+2];
+
+ /* Special case for first column: pretend column -1 is same as column 0 */
+ membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
+ GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
+ neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
+ GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
+ GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
+ GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
+ neighsum += neighsum;
+ neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
+ GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
+ membersum = membersum * memberscale + neighsum * neighscale;
+ *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
+ inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
+
+ for (colctr = output_cols - 2; colctr > 0; colctr--) {
+ /* sum of pixels directly mapped to this output element */
+ membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
+ GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
+ /* sum of edge-neighbor pixels */
+ neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
+ GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
+ GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
+ GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
+ /* The edge-neighbors count twice as much as corner-neighbors */
+ neighsum += neighsum;
+ /* Add in the corner-neighbors */
+ neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
+ GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
+ /* form final output scaled up by 2^16 */
+ membersum = membersum * memberscale + neighsum * neighscale;
+ /* round, descale and output it */
+ *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
+ inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
+ }
+
+ /* Special case for last column */
+ membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
+ GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
+ neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
+ GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
+ GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
+ GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
+ neighsum += neighsum;
+ neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
+ GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
+ membersum = membersum * memberscale + neighsum * neighscale;
+ *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
+
+ inrow += 2;
+ }
+}
+
+
+/*
+ * Downsample pixel values of a single component.
+ * This version handles the special case of a full-size component,
+ * with smoothing. One row of context is required.
+ */
+
+METHODDEF void
+fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
+ JSAMPARRAY input_data, JSAMPARRAY output_data)
+{
+ int outrow;
+ JDIMENSION colctr;
+ JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
+ register JSAMPROW inptr, above_ptr, below_ptr, outptr;
+ INT32 membersum, neighsum, memberscale, neighscale;
+ int colsum, lastcolsum, nextcolsum;
+
+ /* Expand input data enough to let all the output samples be generated
+ * by the standard loop. Special-casing padded output would be more
+ * efficient.
+ */
+ expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
+ cinfo->image_width, output_cols);
+
+ /* Each of the eight neighbor pixels contributes a fraction SF to the
+ * smoothed pixel, while the main pixel contributes (1-8*SF). In order
+ * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
+ * Also recall that SF = smoothing_factor / 1024.
+ */
+
+ memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
+ neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
+
+ for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
+ outptr = output_data[outrow];
+ inptr = input_data[outrow];
+ above_ptr = input_data[outrow-1];
+ below_ptr = input_data[outrow+1];
+
+ /* Special case for first column */
+ colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
+ GETJSAMPLE(*inptr);
+ membersum = GETJSAMPLE(*inptr++);
+ nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
+ GETJSAMPLE(*inptr);
+ neighsum = colsum + (colsum - membersum) + nextcolsum;
+ membersum = membersum * memberscale + neighsum * neighscale;
+ *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
+ lastcolsum = colsum; colsum = nextcolsum;
+
+ for (colctr = output_cols - 2; colctr > 0; colctr--) {
+ membersum = GETJSAMPLE(*inptr++);
+ above_ptr++; below_ptr++;
+ nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
+ GETJSAMPLE(*inptr);
+ neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
+ membersum = membersum * memberscale + neighsum * neighscale;
+ *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
+ lastcolsum = colsum; colsum = nextcolsum;
+ }
+
+ /* Special case for last column */
+ membersum = GETJSAMPLE(*inptr);
+ neighsum = lastcolsum + (colsum - membersum) + colsum;
+ membersum = membersum * memberscale + neighsum * neighscale;
+ *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
+
+ }
+}
+
+#endif /* INPUT_SMOOTHING_SUPPORTED */
+
+
+/*
+ * Module initialization routine for downsampling.
+ * Note that we must select a routine for each component.
+ */
+
+GLOBAL void
+jinit_downsampler (j_compress_ptr cinfo)
+{
+ my_downsample_ptr downsample;
+ int ci;
+ jpeg_component_info * compptr;
+ boolean smoothok = TRUE;
+
+ downsample = (my_downsample_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_downsampler));
+ cinfo->downsample = (struct jpeg_downsampler *) downsample;
+ downsample->pub.start_pass = start_pass_downsample;
+ downsample->pub.downsample = sep_downsample;
+ downsample->pub.need_context_rows = FALSE;
+
+ if (cinfo->CCIR601_sampling)
+ ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
+
+ /* Verify we can handle the sampling factors, and set up method pointers */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
+ compptr->v_samp_factor == cinfo->max_v_samp_factor) {
+#ifdef INPUT_SMOOTHING_SUPPORTED
+ if (cinfo->smoothing_factor) {
+ downsample->methods[ci] = fullsize_smooth_downsample;
+ downsample->pub.need_context_rows = TRUE;
+ } else
+#endif
+ downsample->methods[ci] = fullsize_downsample;
+ } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
+ compptr->v_samp_factor == cinfo->max_v_samp_factor) {
+ smoothok = FALSE;
+ downsample->methods[ci] = h2v1_downsample;
+ } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
+ compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
+#ifdef INPUT_SMOOTHING_SUPPORTED
+ if (cinfo->smoothing_factor) {
+ downsample->methods[ci] = h2v2_smooth_downsample;
+ downsample->pub.need_context_rows = TRUE;
+ } else
+#endif
+ downsample->methods[ci] = h2v2_downsample;
+ } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
+ (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
+ smoothok = FALSE;
+ downsample->methods[ci] = int_downsample;
+ } else
+ ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
+ }
+
+#ifdef INPUT_SMOOTHING_SUPPORTED
+ if (cinfo->smoothing_factor && !smoothok)
+ TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
+#endif
+}
diff --git a/code/jpeg-6/jctrans.c b/code/jpeg-6/jctrans.c
new file mode 100755
index 0000000..a7b82f5
--- /dev/null
+++ b/code/jpeg-6/jctrans.c
@@ -0,0 +1,371 @@
+/*
+ * jctrans.c
+ *
+ * Copyright (C) 1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains library routines for transcoding compression,
+ * that is, writing raw DCT coefficient arrays to an output JPEG file.
+ * The routines in jcapimin.c will also be needed by a transcoder.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Forward declarations */
+LOCAL void transencode_master_selection
+ JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
+LOCAL void transencode_coef_controller
+ JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
+
+
+/*
+ * Compression initialization for writing raw-coefficient data.
+ * Before calling this, all parameters and a data destination must be set up.
+ * Call jpeg_finish_compress() to actually write the data.
+ *
+ * The number of passed virtual arrays must match cinfo->num_components.
+ * Note that the virtual arrays need not be filled or even realized at
+ * the time write_coefficients is called; indeed, if the virtual arrays
+ * were requested from this compression object's memory manager, they
+ * typically will be realized during this routine and filled afterwards.
+ */
+
+GLOBAL void
+jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
+{
+ if (cinfo->global_state != CSTATE_START)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ /* Mark all tables to be written */
+ jpeg_suppress_tables(cinfo, FALSE);
+ /* (Re)initialize error mgr and destination modules */
+ (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
+ (*cinfo->dest->init_destination) (cinfo);
+ /* Perform master selection of active modules */
+ transencode_master_selection(cinfo, coef_arrays);
+ /* Wait for jpeg_finish_compress() call */
+ cinfo->next_scanline = 0; /* so jpeg_write_marker works */
+ cinfo->global_state = CSTATE_WRCOEFS;
+}
+
+
+/*
+ * Initialize the compression object with default parameters,
+ * then copy from the source object all parameters needed for lossless
+ * transcoding. Parameters that can be varied without loss (such as
+ * scan script and Huffman optimization) are left in their default states.
+ */
+
+GLOBAL void
+jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
+ j_compress_ptr dstinfo)
+{
+ JQUANT_TBL ** qtblptr;
+ jpeg_component_info *incomp, *outcomp;
+ JQUANT_TBL *c_quant, *slot_quant;
+ int tblno, ci, coefi;
+
+ /* Safety check to ensure start_compress not called yet. */
+ if (dstinfo->global_state != CSTATE_START)
+ ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
+ /* Copy fundamental image dimensions */
+ dstinfo->image_width = srcinfo->image_width;
+ dstinfo->image_height = srcinfo->image_height;
+ dstinfo->input_components = srcinfo->num_components;
+ dstinfo->in_color_space = srcinfo->jpeg_color_space;
+ /* Initialize all parameters to default values */
+ jpeg_set_defaults(dstinfo);
+ /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
+ * Fix it to get the right header markers for the image colorspace.
+ */
+ jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
+ dstinfo->data_precision = srcinfo->data_precision;
+ dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
+ /* Copy the source's quantization tables. */
+ for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
+ if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
+ qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
+ if (*qtblptr == NULL)
+ *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
+ MEMCOPY((*qtblptr)->quantval,
+ srcinfo->quant_tbl_ptrs[tblno]->quantval,
+ SIZEOF((*qtblptr)->quantval));
+ (*qtblptr)->sent_table = FALSE;
+ }
+ }
+ /* Copy the source's per-component info.
+ * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
+ */
+ dstinfo->num_components = srcinfo->num_components;
+ if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
+ ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
+ MAX_COMPONENTS);
+ for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
+ ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
+ outcomp->component_id = incomp->component_id;
+ outcomp->h_samp_factor = incomp->h_samp_factor;
+ outcomp->v_samp_factor = incomp->v_samp_factor;
+ outcomp->quant_tbl_no = incomp->quant_tbl_no;
+ /* Make sure saved quantization table for component matches the qtable
+ * slot. If not, the input file re-used this qtable slot.
+ * IJG encoder currently cannot duplicate this.
+ */
+ tblno = outcomp->quant_tbl_no;
+ if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
+ srcinfo->quant_tbl_ptrs[tblno] == NULL)
+ ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
+ slot_quant = srcinfo->quant_tbl_ptrs[tblno];
+ c_quant = incomp->quant_table;
+ if (c_quant != NULL) {
+ for (coefi = 0; coefi < DCTSIZE2; coefi++) {
+ if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
+ ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
+ }
+ }
+ /* Note: we do not copy the source's Huffman table assignments;
+ * instead we rely on jpeg_set_colorspace to have made a suitable choice.
+ */
+ }
+}
+
+
+/*
+ * Master selection of compression modules for transcoding.
+ * This substitutes for jcinit.c's initialization of the full compressor.
+ */
+
+LOCAL void
+transencode_master_selection (j_compress_ptr cinfo,
+ jvirt_barray_ptr * coef_arrays)
+{
+ /* Although we don't actually use input_components for transcoding,
+ * jcmaster.c's initial_setup will complain if input_components is 0.
+ */
+ cinfo->input_components = 1;
+ /* Initialize master control (includes parameter checking/processing) */
+ jinit_c_master_control(cinfo, TRUE /* transcode only */);
+
+ /* Entropy encoding: either Huffman or arithmetic coding. */
+ if (cinfo->arith_code) {
+ ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
+ } else {
+ if (cinfo->progressive_mode) {
+#ifdef C_PROGRESSIVE_SUPPORTED
+ jinit_phuff_encoder(cinfo);
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else
+ jinit_huff_encoder(cinfo);
+ }
+
+ /* We need a special coefficient buffer controller. */
+ transencode_coef_controller(cinfo, coef_arrays);
+
+ jinit_marker_writer(cinfo);
+
+ /* We can now tell the memory manager to allocate virtual arrays. */
+ (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
+
+ /* Write the datastream header (SOI) immediately.
+ * Frame and scan headers are postponed till later.
+ * This lets application insert special markers after the SOI.
+ */
+ (*cinfo->marker->write_file_header) (cinfo);
+}
+
+
+/*
+ * The rest of this file is a special implementation of the coefficient
+ * buffer controller. This is similar to jccoefct.c, but it handles only
+ * output from presupplied virtual arrays. Furthermore, we generate any
+ * dummy padding blocks on-the-fly rather than expecting them to be present
+ * in the arrays.
+ */
+
+/* Private buffer controller object */
+
+typedef struct {
+ struct jpeg_c_coef_controller pub; /* public fields */
+
+ JDIMENSION iMCU_row_num; /* iMCU row # within image */
+ JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
+ int MCU_vert_offset; /* counts MCU rows within iMCU row */
+ int MCU_rows_per_iMCU_row; /* number of such rows needed */
+
+ /* Virtual block array for each component. */
+ jvirt_barray_ptr * whole_image;
+
+ /* Workspace for constructing dummy blocks at right/bottom edges. */
+ JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
+} my_coef_controller;
+
+typedef my_coef_controller * my_coef_ptr;
+
+
+LOCAL void
+start_iMCU_row (j_compress_ptr cinfo)
+/* Reset within-iMCU-row counters for a new row */
+{
+ my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+
+ /* In an interleaved scan, an MCU row is the same as an iMCU row.
+ * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
+ * But at the bottom of the image, process only what's left.
+ */
+ if (cinfo->comps_in_scan > 1) {
+ coef->MCU_rows_per_iMCU_row = 1;
+ } else {
+ if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
+ coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
+ else
+ coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
+ }
+
+ coef->mcu_ctr = 0;
+ coef->MCU_vert_offset = 0;
+}
+
+
+/*
+ * Initialize for a processing pass.
+ */
+
+METHODDEF void
+start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
+{
+ my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+
+ if (pass_mode != JBUF_CRANK_DEST)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+
+ coef->iMCU_row_num = 0;
+ start_iMCU_row(cinfo);
+}
+
+
+/*
+ * Process some data.
+ * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
+ * per call, ie, v_samp_factor block rows for each component in the scan.
+ * The data is obtained from the virtual arrays and fed to the entropy coder.
+ * Returns TRUE if the iMCU row is completed, FALSE if suspended.
+ *
+ * NB: input_buf is ignored; it is likely to be a NULL pointer.
+ */
+
+METHODDEF boolean
+compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
+{
+ my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ int blkn, ci, xindex, yindex, yoffset, blockcnt;
+ JDIMENSION start_col;
+ JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
+ JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
+ JBLOCKROW buffer_ptr;
+ jpeg_component_info *compptr;
+
+ /* Align the virtual buffers for the components used in this scan. */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ buffer[ci] = (*cinfo->mem->access_virt_barray)
+ ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
+ coef->iMCU_row_num * compptr->v_samp_factor,
+ (JDIMENSION) compptr->v_samp_factor, FALSE);
+ }
+
+ /* Loop to process one whole iMCU row */
+ for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
+ yoffset++) {
+ for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
+ MCU_col_num++) {
+ /* Construct list of pointers to DCT blocks belonging to this MCU */
+ blkn = 0; /* index of current DCT block within MCU */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ start_col = MCU_col_num * compptr->MCU_width;
+ blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
+ : compptr->last_col_width;
+ for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
+ if (coef->iMCU_row_num < last_iMCU_row ||
+ yindex+yoffset < compptr->last_row_height) {
+ /* Fill in pointers to real blocks in this row */
+ buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
+ for (xindex = 0; xindex < blockcnt; xindex++)
+ MCU_buffer[blkn++] = buffer_ptr++;
+ } else {
+ /* At bottom of image, need a whole row of dummy blocks */
+ xindex = 0;
+ }
+ /* Fill in any dummy blocks needed in this row.
+ * Dummy blocks are filled in the same way as in jccoefct.c:
+ * all zeroes in the AC entries, DC entries equal to previous
+ * block's DC value. The init routine has already zeroed the
+ * AC entries, so we need only set the DC entries correctly.
+ */
+ for (; xindex < compptr->MCU_width; xindex++) {
+ MCU_buffer[blkn] = coef->dummy_buffer[blkn];
+ MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
+ blkn++;
+ }
+ }
+ }
+ /* Try to write the MCU. */
+ if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
+ /* Suspension forced; update state counters and exit */
+ coef->MCU_vert_offset = yoffset;
+ coef->mcu_ctr = MCU_col_num;
+ return FALSE;
+ }
+ }
+ /* Completed an MCU row, but perhaps not an iMCU row */
+ coef->mcu_ctr = 0;
+ }
+ /* Completed the iMCU row, advance counters for next one */
+ coef->iMCU_row_num++;
+ start_iMCU_row(cinfo);
+ return TRUE;
+}
+
+
+/*
+ * Initialize coefficient buffer controller.
+ *
+ * Each passed coefficient array must be the right size for that
+ * coefficient: width_in_blocks wide and height_in_blocks high,
+ * with unitheight at least v_samp_factor.
+ */
+
+LOCAL void
+transencode_coef_controller (j_compress_ptr cinfo,
+ jvirt_barray_ptr * coef_arrays)
+{
+ my_coef_ptr coef;
+ JBLOCKROW buffer;
+ int i;
+
+ coef = (my_coef_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_coef_controller));
+ cinfo->coef = (struct jpeg_c_coef_controller *) coef;
+ coef->pub.start_pass = start_pass_coef;
+ coef->pub.compress_data = compress_output;
+
+ /* Save pointer to virtual arrays */
+ coef->whole_image = coef_arrays;
+
+ /* Allocate and pre-zero space for dummy DCT blocks. */
+ buffer = (JBLOCKROW)
+ (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
+ jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
+ for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
+ coef->dummy_buffer[i] = buffer + i;
+ }
+}
diff --git a/code/jpeg-6/jdapimin.c b/code/jpeg-6/jdapimin.c
new file mode 100755
index 0000000..7be4b48
--- /dev/null
+++ b/code/jpeg-6/jdapimin.c
@@ -0,0 +1,398 @@
+/*
+ * jdapimin.c
+ *
+ * Copyright (C) 1994-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains application interface code for the decompression half
+ * of the JPEG library. These are the "minimum" API routines that may be
+ * needed in either the normal full-decompression case or the
+ * transcoding-only case.
+ *
+ * Most of the routines intended to be called directly by an application
+ * are in this file or in jdapistd.c. But also see jcomapi.c for routines
+ * shared by compression and decompression, and jdtrans.c for the transcoding
+ * case.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/*
+ * Initialization of a JPEG decompression object.
+ * The error manager must already be set up (in case memory manager fails).
+ */
+
+GLOBAL void
+jpeg_create_decompress (j_decompress_ptr cinfo)
+{
+ int i;
+
+ /* For debugging purposes, zero the whole master structure.
+ * But error manager pointer is already there, so save and restore it.
+ */
+ {
+ struct jpeg_error_mgr * err = cinfo->err;
+ MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
+ cinfo->err = err;
+ }
+ cinfo->is_decompressor = TRUE;
+
+ /* Initialize a memory manager instance for this object */
+ jinit_memory_mgr((j_common_ptr) cinfo);
+
+ /* Zero out pointers to permanent structures. */
+ cinfo->progress = NULL;
+ cinfo->src = NULL;
+
+ for (i = 0; i < NUM_QUANT_TBLS; i++)
+ cinfo->quant_tbl_ptrs[i] = NULL;
+
+ for (i = 0; i < NUM_HUFF_TBLS; i++) {
+ cinfo->dc_huff_tbl_ptrs[i] = NULL;
+ cinfo->ac_huff_tbl_ptrs[i] = NULL;
+ }
+
+ /* Initialize marker processor so application can override methods
+ * for COM, APPn markers before calling jpeg_read_header.
+ */
+ jinit_marker_reader(cinfo);
+
+ /* And initialize the overall input controller. */
+ jinit_input_controller(cinfo);
+
+ /* OK, I'm ready */
+ cinfo->global_state = DSTATE_START;
+}
+
+
+/*
+ * Destruction of a JPEG decompression object
+ */
+
+GLOBAL void
+jpeg_destroy_decompress (j_decompress_ptr cinfo)
+{
+ jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
+}
+
+
+/*
+ * Abort processing of a JPEG decompression operation,
+ * but don't destroy the object itself.
+ */
+
+GLOBAL void
+jpeg_abort_decompress (j_decompress_ptr cinfo)
+{
+ jpeg_abort((j_common_ptr) cinfo); /* use common routine */
+}
+
+
+/*
+ * Install a special processing method for COM or APPn markers.
+ */
+
+GLOBAL void
+jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
+ jpeg_marker_parser_method routine)
+{
+ if (marker_code == JPEG_COM)
+ cinfo->marker->process_COM = routine;
+ else if (marker_code >= JPEG_APP0 && marker_code <= JPEG_APP0+15)
+ cinfo->marker->process_APPn[marker_code-JPEG_APP0] = routine;
+ else
+ ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
+}
+
+
+/*
+ * Set default decompression parameters.
+ */
+
+LOCAL void
+default_decompress_parms (j_decompress_ptr cinfo)
+{
+ /* Guess the input colorspace, and set output colorspace accordingly. */
+ /* (Wish JPEG committee had provided a real way to specify this...) */
+ /* Note application may override our guesses. */
+ switch (cinfo->num_components) {
+ case 1:
+ cinfo->jpeg_color_space = JCS_GRAYSCALE;
+ cinfo->out_color_space = JCS_GRAYSCALE;
+ break;
+
+ case 3:
+ if (cinfo->saw_JFIF_marker) {
+ cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
+ } else if (cinfo->saw_Adobe_marker) {
+ switch (cinfo->Adobe_transform) {
+ case 0:
+ cinfo->jpeg_color_space = JCS_RGB;
+ break;
+ case 1:
+ cinfo->jpeg_color_space = JCS_YCbCr;
+ break;
+ default:
+ WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
+ cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
+ break;
+ }
+ } else {
+ /* Saw no special markers, try to guess from the component IDs */
+ int cid0 = cinfo->comp_info[0].component_id;
+ int cid1 = cinfo->comp_info[1].component_id;
+ int cid2 = cinfo->comp_info[2].component_id;
+
+ if (cid0 == 1 && cid1 == 2 && cid2 == 3)
+ cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
+ else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
+ cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
+ else {
+ TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
+ cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
+ }
+ }
+ /* Always guess RGB is proper output colorspace. */
+ cinfo->out_color_space = JCS_RGB;
+ break;
+
+ case 4:
+ if (cinfo->saw_Adobe_marker) {
+ switch (cinfo->Adobe_transform) {
+ case 0:
+ cinfo->jpeg_color_space = JCS_CMYK;
+ break;
+ case 2:
+ cinfo->jpeg_color_space = JCS_YCCK;
+ break;
+ default:
+ WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
+ cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
+ break;
+ }
+ } else {
+ /* No special markers, assume straight CMYK. */
+ cinfo->jpeg_color_space = JCS_CMYK;
+ }
+ cinfo->out_color_space = JCS_CMYK;
+ break;
+
+ default:
+ cinfo->jpeg_color_space = JCS_UNKNOWN;
+ cinfo->out_color_space = JCS_UNKNOWN;
+ break;
+ }
+
+ /* Set defaults for other decompression parameters. */
+ cinfo->scale_num = 1; /* 1:1 scaling */
+ cinfo->scale_denom = 1;
+ cinfo->output_gamma = 1.0;
+ cinfo->buffered_image = FALSE;
+ cinfo->raw_data_out = FALSE;
+ cinfo->dct_method = JDCT_DEFAULT;
+ cinfo->do_fancy_upsampling = TRUE;
+ cinfo->do_block_smoothing = TRUE;
+ cinfo->quantize_colors = FALSE;
+ /* We set these in case application only sets quantize_colors. */
+ cinfo->dither_mode = JDITHER_FS;
+#ifdef QUANT_2PASS_SUPPORTED
+ cinfo->two_pass_quantize = TRUE;
+#else
+ cinfo->two_pass_quantize = FALSE;
+#endif
+ cinfo->desired_number_of_colors = 256;
+ cinfo->colormap = NULL;
+ /* Initialize for no mode change in buffered-image mode. */
+ cinfo->enable_1pass_quant = FALSE;
+ cinfo->enable_external_quant = FALSE;
+ cinfo->enable_2pass_quant = FALSE;
+}
+
+
+/*
+ * Decompression startup: read start of JPEG datastream to see what's there.
+ * Need only initialize JPEG object and supply a data source before calling.
+ *
+ * This routine will read as far as the first SOS marker (ie, actual start of
+ * compressed data), and will save all tables and parameters in the JPEG
+ * object. It will also initialize the decompression parameters to default
+ * values, and finally return JPEG_HEADER_OK. On return, the application may
+ * adjust the decompression parameters and then call jpeg_start_decompress.
+ * (Or, if the application only wanted to determine the image parameters,
+ * the data need not be decompressed. In that case, call jpeg_abort or
+ * jpeg_destroy to release any temporary space.)
+ * If an abbreviated (tables only) datastream is presented, the routine will
+ * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
+ * re-use the JPEG object to read the abbreviated image datastream(s).
+ * It is unnecessary (but OK) to call jpeg_abort in this case.
+ * The JPEG_SUSPENDED return code only occurs if the data source module
+ * requests suspension of the decompressor. In this case the application
+ * should load more source data and then re-call jpeg_read_header to resume
+ * processing.
+ * If a non-suspending data source is used and require_image is TRUE, then the
+ * return code need not be inspected since only JPEG_HEADER_OK is possible.
+ *
+ * This routine is now just a front end to jpeg_consume_input, with some
+ * extra error checking.
+ */
+
+GLOBAL int
+jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
+{
+ int retcode;
+
+ if (cinfo->global_state != DSTATE_START &&
+ cinfo->global_state != DSTATE_INHEADER)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+ retcode = jpeg_consume_input(cinfo);
+
+ switch (retcode) {
+ case JPEG_REACHED_SOS:
+ retcode = JPEG_HEADER_OK;
+ break;
+ case JPEG_REACHED_EOI:
+ if (require_image) /* Complain if application wanted an image */
+ ERREXIT(cinfo, JERR_NO_IMAGE);
+ /* Reset to start state; it would be safer to require the application to
+ * call jpeg_abort, but we can't change it now for compatibility reasons.
+ * A side effect is to free any temporary memory (there shouldn't be any).
+ */
+ jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
+ retcode = JPEG_HEADER_TABLES_ONLY;
+ break;
+ case JPEG_SUSPENDED:
+ /* no work */
+ break;
+ }
+
+ return retcode;
+}
+
+
+/*
+ * Consume data in advance of what the decompressor requires.
+ * This can be called at any time once the decompressor object has
+ * been created and a data source has been set up.
+ *
+ * This routine is essentially a state machine that handles a couple
+ * of critical state-transition actions, namely initial setup and
+ * transition from header scanning to ready-for-start_decompress.
+ * All the actual input is done via the input controller's consume_input
+ * method.
+ */
+
+GLOBAL int
+jpeg_consume_input (j_decompress_ptr cinfo)
+{
+ int retcode = JPEG_SUSPENDED;
+
+ /* NB: every possible DSTATE value should be listed in this switch */
+ switch (cinfo->global_state) {
+ case DSTATE_START:
+ /* Start-of-datastream actions: reset appropriate modules */
+ (*cinfo->inputctl->reset_input_controller) (cinfo);
+ /* Initialize application's data source module */
+ (*cinfo->src->init_source) (cinfo);
+ cinfo->global_state = DSTATE_INHEADER;
+ /*FALLTHROUGH*/
+ case DSTATE_INHEADER:
+ retcode = (*cinfo->inputctl->consume_input) (cinfo);
+ if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
+ /* Set up default parameters based on header data */
+ default_decompress_parms(cinfo);
+ /* Set global state: ready for start_decompress */
+ cinfo->global_state = DSTATE_READY;
+ }
+ break;
+ case DSTATE_READY:
+ /* Can't advance past first SOS until start_decompress is called */
+ retcode = JPEG_REACHED_SOS;
+ break;
+ case DSTATE_PRELOAD:
+ case DSTATE_PRESCAN:
+ case DSTATE_SCANNING:
+ case DSTATE_RAW_OK:
+ case DSTATE_BUFIMAGE:
+ case DSTATE_BUFPOST:
+ case DSTATE_STOPPING:
+ retcode = (*cinfo->inputctl->consume_input) (cinfo);
+ break;
+ default:
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ }
+ return retcode;
+}
+
+
+/*
+ * Have we finished reading the input file?
+ */
+
+GLOBAL boolean
+jpeg_input_complete (j_decompress_ptr cinfo)
+{
+ /* Check for valid jpeg object */
+ if (cinfo->global_state < DSTATE_START ||
+ cinfo->global_state > DSTATE_STOPPING)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ return cinfo->inputctl->eoi_reached;
+}
+
+
+/*
+ * Is there more than one scan?
+ */
+
+GLOBAL boolean
+jpeg_has_multiple_scans (j_decompress_ptr cinfo)
+{
+ /* Only valid after jpeg_read_header completes */
+ if (cinfo->global_state < DSTATE_READY ||
+ cinfo->global_state > DSTATE_STOPPING)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ return cinfo->inputctl->has_multiple_scans;
+}
+
+
+/*
+ * Finish JPEG decompression.
+ *
+ * This will normally just verify the file trailer and release temp storage.
+ *
+ * Returns FALSE if suspended. The return value need be inspected only if
+ * a suspending data source is used.
+ */
+
+GLOBAL boolean
+jpeg_finish_decompress (j_decompress_ptr cinfo)
+{
+ if ((cinfo->global_state == DSTATE_SCANNING ||
+ cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
+ /* Terminate final pass of non-buffered mode */
+ if (cinfo->output_scanline < cinfo->output_height)
+ ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
+ (*cinfo->master->finish_output_pass) (cinfo);
+ cinfo->global_state = DSTATE_STOPPING;
+ } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
+ /* Finishing after a buffered-image operation */
+ cinfo->global_state = DSTATE_STOPPING;
+ } else if (cinfo->global_state != DSTATE_STOPPING) {
+ /* STOPPING = repeat call after a suspension, anything else is error */
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ }
+ /* Read until EOI */
+ while (! cinfo->inputctl->eoi_reached) {
+ if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
+ return FALSE; /* Suspend, come back later */
+ }
+ /* Do final cleanup */
+ (*cinfo->src->term_source) (cinfo);
+ /* We can use jpeg_abort to release memory and reset global_state */
+ jpeg_abort((j_common_ptr) cinfo);
+ return TRUE;
+}
diff --git a/code/jpeg-6/jdapistd.c b/code/jpeg-6/jdapistd.c
new file mode 100755
index 0000000..7781e16
--- /dev/null
+++ b/code/jpeg-6/jdapistd.c
@@ -0,0 +1,275 @@
+/*
+ * jdapistd.c
+ *
+ * Copyright (C) 1994-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains application interface code for the decompression half
+ * of the JPEG library. These are the "standard" API routines that are
+ * used in the normal full-decompression case. They are not used by a
+ * transcoding-only application. Note that if an application links in
+ * jpeg_start_decompress, it will end up linking in the entire decompressor.
+ * We thus must separate this file from jdapimin.c to avoid linking the
+ * whole decompression library into a transcoder.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Forward declarations */
+LOCAL boolean output_pass_setup JPP((j_decompress_ptr cinfo));
+
+
+/*
+ * Decompression initialization.
+ * jpeg_read_header must be completed before calling this.
+ *
+ * If a multipass operating mode was selected, this will do all but the
+ * last pass, and thus may take a great deal of time.
+ *
+ * Returns FALSE if suspended. The return value need be inspected only if
+ * a suspending data source is used.
+ */
+
+GLOBAL boolean
+jpeg_start_decompress (j_decompress_ptr cinfo)
+{
+ if (cinfo->global_state == DSTATE_READY) {
+ /* First call: initialize master control, select active modules */
+ jinit_master_decompress(cinfo);
+ if (cinfo->buffered_image) {
+ /* No more work here; expecting jpeg_start_output next */
+ cinfo->global_state = DSTATE_BUFIMAGE;
+ return TRUE;
+ }
+ cinfo->global_state = DSTATE_PRELOAD;
+ }
+ if (cinfo->global_state == DSTATE_PRELOAD) {
+ /* If file has multiple scans, absorb them all into the coef buffer */
+ if (cinfo->inputctl->has_multiple_scans) {
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+ for (;;) {
+ int retcode;
+ /* Call progress monitor hook if present */
+ if (cinfo->progress != NULL)
+ (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+ /* Absorb some more input */
+ retcode = (*cinfo->inputctl->consume_input) (cinfo);
+ if (retcode == JPEG_SUSPENDED)
+ return FALSE;
+ if (retcode == JPEG_REACHED_EOI)
+ break;
+ /* Advance progress counter if appropriate */
+ if (cinfo->progress != NULL &&
+ (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
+ if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
+ /* jdmaster underestimated number of scans; ratchet up one scan */
+ cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
+ }
+ }
+ }
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif /* D_MULTISCAN_FILES_SUPPORTED */
+ }
+ cinfo->output_scan_number = cinfo->input_scan_number;
+ } else if (cinfo->global_state != DSTATE_PRESCAN)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ /* Perform any dummy output passes, and set up for the final pass */
+ return output_pass_setup(cinfo);
+}
+
+
+/*
+ * Set up for an output pass, and perform any dummy pass(es) needed.
+ * Common subroutine for jpeg_start_decompress and jpeg_start_output.
+ * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
+ * Exit: If done, returns TRUE and sets global_state for proper output mode.
+ * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
+ */
+
+LOCAL boolean
+output_pass_setup (j_decompress_ptr cinfo)
+{
+ if (cinfo->global_state != DSTATE_PRESCAN) {
+ /* First call: do pass setup */
+ (*cinfo->master->prepare_for_output_pass) (cinfo);
+ cinfo->output_scanline = 0;
+ cinfo->global_state = DSTATE_PRESCAN;
+ }
+ /* Loop over any required dummy passes */
+ while (cinfo->master->is_dummy_pass) {
+#ifdef QUANT_2PASS_SUPPORTED
+ /* Crank through the dummy pass */
+ while (cinfo->output_scanline < cinfo->output_height) {
+ JDIMENSION last_scanline;
+ /* Call progress monitor hook if present */
+ if (cinfo->progress != NULL) {
+ cinfo->progress->pass_counter = (long) cinfo->output_scanline;
+ cinfo->progress->pass_limit = (long) cinfo->output_height;
+ (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+ }
+ /* Process some data */
+ last_scanline = cinfo->output_scanline;
+ (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
+ &cinfo->output_scanline, (JDIMENSION) 0);
+ if (cinfo->output_scanline == last_scanline)
+ return FALSE; /* No progress made, must suspend */
+ }
+ /* Finish up dummy pass, and set up for another one */
+ (*cinfo->master->finish_output_pass) (cinfo);
+ (*cinfo->master->prepare_for_output_pass) (cinfo);
+ cinfo->output_scanline = 0;
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif /* QUANT_2PASS_SUPPORTED */
+ }
+ /* Ready for application to drive output pass through
+ * jpeg_read_scanlines or jpeg_read_raw_data.
+ */
+ cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
+ return TRUE;
+}
+
+
+/*
+ * Read some scanlines of data from the JPEG decompressor.
+ *
+ * The return value will be the number of lines actually read.
+ * This may be less than the number requested in several cases,
+ * including bottom of image, data source suspension, and operating
+ * modes that emit multiple scanlines at a time.
+ *
+ * Note: we warn about excess calls to jpeg_read_scanlines() since
+ * this likely signals an application programmer error. However,
+ * an oversize buffer (max_lines > scanlines remaining) is not an error.
+ */
+
+GLOBAL JDIMENSION
+jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
+ JDIMENSION max_lines)
+{
+ JDIMENSION row_ctr;
+
+ if (cinfo->global_state != DSTATE_SCANNING)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ if (cinfo->output_scanline >= cinfo->output_height) {
+ WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
+ return 0;
+ }
+
+ /* Call progress monitor hook if present */
+ if (cinfo->progress != NULL) {
+ cinfo->progress->pass_counter = (long) cinfo->output_scanline;
+ cinfo->progress->pass_limit = (long) cinfo->output_height;
+ (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+ }
+
+ /* Process some data */
+ row_ctr = 0;
+ (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
+ cinfo->output_scanline += row_ctr;
+ return row_ctr;
+}
+
+
+/*
+ * Alternate entry point to read raw data.
+ * Processes exactly one iMCU row per call, unless suspended.
+ */
+
+GLOBAL JDIMENSION
+jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
+ JDIMENSION max_lines)
+{
+ JDIMENSION lines_per_iMCU_row;
+
+ if (cinfo->global_state != DSTATE_RAW_OK)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ if (cinfo->output_scanline >= cinfo->output_height) {
+ WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
+ return 0;
+ }
+
+ /* Call progress monitor hook if present */
+ if (cinfo->progress != NULL) {
+ cinfo->progress->pass_counter = (long) cinfo->output_scanline;
+ cinfo->progress->pass_limit = (long) cinfo->output_height;
+ (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+ }
+
+ /* Verify that at least one iMCU row can be returned. */
+ lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
+ if (max_lines < lines_per_iMCU_row)
+ ERREXIT(cinfo, JERR_BUFFER_SIZE);
+
+ /* Decompress directly into user's buffer. */
+ if (! (*cinfo->coef->decompress_data) (cinfo, data))
+ return 0; /* suspension forced, can do nothing more */
+
+ /* OK, we processed one iMCU row. */
+ cinfo->output_scanline += lines_per_iMCU_row;
+ return lines_per_iMCU_row;
+}
+
+
+/* Additional entry points for buffered-image mode. */
+
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+
+/*
+ * Initialize for an output pass in buffered-image mode.
+ */
+
+GLOBAL boolean
+jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
+{
+ if (cinfo->global_state != DSTATE_BUFIMAGE &&
+ cinfo->global_state != DSTATE_PRESCAN)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ /* Limit scan number to valid range */
+ if (scan_number <= 0)
+ scan_number = 1;
+ if (cinfo->inputctl->eoi_reached &&
+ scan_number > cinfo->input_scan_number)
+ scan_number = cinfo->input_scan_number;
+ cinfo->output_scan_number = scan_number;
+ /* Perform any dummy output passes, and set up for the real pass */
+ return output_pass_setup(cinfo);
+}
+
+
+/*
+ * Finish up after an output pass in buffered-image mode.
+ *
+ * Returns FALSE if suspended. The return value need be inspected only if
+ * a suspending data source is used.
+ */
+
+GLOBAL boolean
+jpeg_finish_output (j_decompress_ptr cinfo)
+{
+ if ((cinfo->global_state == DSTATE_SCANNING ||
+ cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
+ /* Terminate this pass. */
+ /* We do not require the whole pass to have been completed. */
+ (*cinfo->master->finish_output_pass) (cinfo);
+ cinfo->global_state = DSTATE_BUFPOST;
+ } else if (cinfo->global_state != DSTATE_BUFPOST) {
+ /* BUFPOST = repeat call after a suspension, anything else is error */
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ }
+ /* Read markers looking for SOS or EOI */
+ while (cinfo->input_scan_number <= cinfo->output_scan_number &&
+ ! cinfo->inputctl->eoi_reached) {
+ if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
+ return FALSE; /* Suspend, come back later */
+ }
+ cinfo->global_state = DSTATE_BUFIMAGE;
+ return TRUE;
+}
+
+#endif /* D_MULTISCAN_FILES_SUPPORTED */
diff --git a/code/jpeg-6/jdatadst.c b/code/jpeg-6/jdatadst.c
new file mode 100755
index 0000000..748bca5
--- /dev/null
+++ b/code/jpeg-6/jdatadst.c
@@ -0,0 +1,151 @@
+/*
+ * jdatadst.c
+ *
+ * Copyright (C) 1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains compression data destination routines for the case of
+ * emitting JPEG data to a file (or any stdio stream). While these routines
+ * are sufficient for most applications, some will want to use a different
+ * destination manager.
+ * IMPORTANT: we assume that fwrite() will correctly transcribe an array of
+ * JOCTETs into 8-bit-wide elements on external storage. If char is wider
+ * than 8 bits on your machine, you may need to do some tweaking.
+ */
+
+/* this is not a core library module, so it doesn't define JPEG_INTERNALS */
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jerror.h"
+
+
+/* Expanded data destination object for stdio output */
+
+typedef struct {
+ struct jpeg_destination_mgr pub; /* public fields */
+
+ FILE * outfile; /* target stream */
+ JOCTET * buffer; /* start of buffer */
+} my_destination_mgr;
+
+typedef my_destination_mgr * my_dest_ptr;
+
+#define OUTPUT_BUF_SIZE 4096 /* choose an efficiently fwrite'able size */
+
+
+/*
+ * Initialize destination --- called by jpeg_start_compress
+ * before any data is actually written.
+ */
+
+METHODDEF void
+init_destination (j_compress_ptr cinfo)
+{
+ my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
+
+ /* Allocate the output buffer --- it will be released when done with image */
+ dest->buffer = (JOCTET *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ OUTPUT_BUF_SIZE * SIZEOF(JOCTET));
+
+ dest->pub.next_output_byte = dest->buffer;
+ dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
+}
+
+
+/*
+ * Empty the output buffer --- called whenever buffer fills up.
+ *
+ * In typical applications, this should write the entire output buffer
+ * (ignoring the current state of next_output_byte & free_in_buffer),
+ * reset the pointer & count to the start of the buffer, and return TRUE
+ * indicating that the buffer has been dumped.
+ *
+ * In applications that need to be able to suspend compression due to output
+ * overrun, a FALSE return indicates that the buffer cannot be emptied now.
+ * In this situation, the compressor will return to its caller (possibly with
+ * an indication that it has not accepted all the supplied scanlines). The
+ * application should resume compression after it has made more room in the
+ * output buffer. Note that there are substantial restrictions on the use of
+ * suspension --- see the documentation.
+ *
+ * When suspending, the compressor will back up to a convenient restart point
+ * (typically the start of the current MCU). next_output_byte & free_in_buffer
+ * indicate where the restart point will be if the current call returns FALSE.
+ * Data beyond this point will be regenerated after resumption, so do not
+ * write it out when emptying the buffer externally.
+ */
+
+METHODDEF boolean
+empty_output_buffer (j_compress_ptr cinfo)
+{
+ my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
+
+ if (JFWRITE(dest->outfile, dest->buffer, OUTPUT_BUF_SIZE) !=
+ (size_t) OUTPUT_BUF_SIZE)
+ ERREXIT(cinfo, JERR_FILE_WRITE);
+
+ dest->pub.next_output_byte = dest->buffer;
+ dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
+
+ return TRUE;
+}
+
+
+/*
+ * Terminate destination --- called by jpeg_finish_compress
+ * after all data has been written. Usually needs to flush buffer.
+ *
+ * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
+ * application must deal with any cleanup that should happen even
+ * for error exit.
+ */
+
+METHODDEF void
+term_destination (j_compress_ptr cinfo)
+{
+ my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
+ size_t datacount = OUTPUT_BUF_SIZE - dest->pub.free_in_buffer;
+
+ /* Write any data remaining in the buffer */
+ if (datacount > 0) {
+ if (JFWRITE(dest->outfile, dest->buffer, datacount) != datacount)
+ ERREXIT(cinfo, JERR_FILE_WRITE);
+ }
+ fflush(dest->outfile);
+ /* Make sure we wrote the output file OK */
+ if (ferror(dest->outfile))
+ ERREXIT(cinfo, JERR_FILE_WRITE);
+}
+
+
+/*
+ * Prepare for output to a stdio stream.
+ * The caller must have already opened the stream, and is responsible
+ * for closing it after finishing compression.
+ */
+
+GLOBAL void
+jpeg_stdio_dest (j_compress_ptr cinfo, FILE * outfile)
+{
+ my_dest_ptr dest;
+
+ /* The destination object is made permanent so that multiple JPEG images
+ * can be written to the same file without re-executing jpeg_stdio_dest.
+ * This makes it dangerous to use this manager and a different destination
+ * manager serially with the same JPEG object, because their private object
+ * sizes may be different. Caveat programmer.
+ */
+ if (cinfo->dest == NULL) { /* first time for this JPEG object? */
+ cinfo->dest = (struct jpeg_destination_mgr *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ SIZEOF(my_destination_mgr));
+ }
+
+ dest = (my_dest_ptr) cinfo->dest;
+ dest->pub.init_destination = init_destination;
+ dest->pub.empty_output_buffer = empty_output_buffer;
+ dest->pub.term_destination = term_destination;
+ dest->outfile = outfile;
+}
diff --git a/code/jpeg-6/jdatasrc.c b/code/jpeg-6/jdatasrc.c
new file mode 100755
index 0000000..5c1696d
--- /dev/null
+++ b/code/jpeg-6/jdatasrc.c
@@ -0,0 +1,204 @@
+/*
+ * jdatasrc.c
+ *
+ * Copyright (C) 1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains decompression data source routines for the case of
+ * reading JPEG data from a file (or any stdio stream). While these routines
+ * are sufficient for most applications, some will want to use a different
+ * source manager.
+ * IMPORTANT: we assume that fread() will correctly transcribe an array of
+ * JOCTETs from 8-bit-wide elements on external storage. If char is wider
+ * than 8 bits on your machine, you may need to do some tweaking.
+ */
+
+
+/* this is not a core library module, so it doesn't define JPEG_INTERNALS */
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jerror.h"
+
+
+/* Expanded data source object for stdio input */
+
+typedef struct {
+ struct jpeg_source_mgr pub; /* public fields */
+
+ unsigned char *infile; /* source stream */
+ JOCTET * buffer; /* start of buffer */
+ boolean start_of_file; /* have we gotten any data yet? */
+} my_source_mgr;
+
+typedef my_source_mgr * my_src_ptr;
+
+#define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
+
+
+/*
+ * Initialize source --- called by jpeg_read_header
+ * before any data is actually read.
+ */
+
+METHODDEF void
+init_source (j_decompress_ptr cinfo)
+{
+ my_src_ptr src = (my_src_ptr) cinfo->src;
+
+ /* We reset the empty-input-file flag for each image,
+ * but we don't clear the input buffer.
+ * This is correct behavior for reading a series of images from one source.
+ */
+ src->start_of_file = TRUE;
+}
+
+
+/*
+ * Fill the input buffer --- called whenever buffer is emptied.
+ *
+ * In typical applications, this should read fresh data into the buffer
+ * (ignoring the current state of next_input_byte & bytes_in_buffer),
+ * reset the pointer & count to the start of the buffer, and return TRUE
+ * indicating that the buffer has been reloaded. It is not necessary to
+ * fill the buffer entirely, only to obtain at least one more byte.
+ *
+ * There is no such thing as an EOF return. If the end of the file has been
+ * reached, the routine has a choice of ERREXIT() or inserting fake data into
+ * the buffer. In most cases, generating a warning message and inserting a
+ * fake EOI marker is the best course of action --- this will allow the
+ * decompressor to output however much of the image is there. However,
+ * the resulting error message is misleading if the real problem is an empty
+ * input file, so we handle that case specially.
+ *
+ * In applications that need to be able to suspend compression due to input
+ * not being available yet, a FALSE return indicates that no more data can be
+ * obtained right now, but more may be forthcoming later. In this situation,
+ * the decompressor will return to its caller (with an indication of the
+ * number of scanlines it has read, if any). The application should resume
+ * decompression after it has loaded more data into the input buffer. Note
+ * that there are substantial restrictions on the use of suspension --- see
+ * the documentation.
+ *
+ * When suspending, the decompressor will back up to a convenient restart point
+ * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
+ * indicate where the restart point will be if the current call returns FALSE.
+ * Data beyond this point must be rescanned after resumption, so move it to
+ * the front of the buffer rather than discarding it.
+ */
+
+METHODDEF boolean
+fill_input_buffer (j_decompress_ptr cinfo)
+{
+ my_src_ptr src = (my_src_ptr) cinfo->src;
+
+ memcpy( src->buffer, src->infile, INPUT_BUF_SIZE );
+
+ src->infile += INPUT_BUF_SIZE;
+
+ src->pub.next_input_byte = src->buffer;
+ src->pub.bytes_in_buffer = INPUT_BUF_SIZE;
+ src->start_of_file = FALSE;
+
+ return TRUE;
+}
+
+
+/*
+ * Skip data --- used to skip over a potentially large amount of
+ * uninteresting data (such as an APPn marker).
+ *
+ * Writers of suspendable-input applications must note that skip_input_data
+ * is not granted the right to give a suspension return. If the skip extends
+ * beyond the data currently in the buffer, the buffer can be marked empty so
+ * that the next read will cause a fill_input_buffer call that can suspend.
+ * Arranging for additional bytes to be discarded before reloading the input
+ * buffer is the application writer's problem.
+ */
+
+METHODDEF void
+skip_input_data (j_decompress_ptr cinfo, long num_bytes)
+{
+ my_src_ptr src = (my_src_ptr) cinfo->src;
+
+ /* Just a dumb implementation for now. Could use fseek() except
+ * it doesn't work on pipes. Not clear that being smart is worth
+ * any trouble anyway --- large skips are infrequent.
+ */
+ if (num_bytes > 0) {
+ while (num_bytes > (long) src->pub.bytes_in_buffer) {
+ num_bytes -= (long) src->pub.bytes_in_buffer;
+ (void) fill_input_buffer(cinfo);
+ /* note we assume that fill_input_buffer will never return FALSE,
+ * so suspension need not be handled.
+ */
+ }
+ src->pub.next_input_byte += (size_t) num_bytes;
+ src->pub.bytes_in_buffer -= (size_t) num_bytes;
+ }
+}
+
+
+/*
+ * An additional method that can be provided by data source modules is the
+ * resync_to_restart method for error recovery in the presence of RST markers.
+ * For the moment, this source module just uses the default resync method
+ * provided by the JPEG library. That method assumes that no backtracking
+ * is possible.
+ */
+
+
+/*
+ * Terminate source --- called by jpeg_finish_decompress
+ * after all data has been read. Often a no-op.
+ *
+ * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
+ * application must deal with any cleanup that should happen even
+ * for error exit.
+ */
+
+METHODDEF void
+term_source (j_decompress_ptr cinfo)
+{
+ /* no work necessary here */
+}
+
+
+/*
+ * Prepare for input from a stdio stream.
+ * The caller must have already opened the stream, and is responsible
+ * for closing it after finishing decompression.
+ */
+
+GLOBAL void
+jpeg_stdio_src (j_decompress_ptr cinfo, unsigned char *infile)
+{
+ my_src_ptr src;
+
+ /* The source object and input buffer are made permanent so that a series
+ * of JPEG images can be read from the same file by calling jpeg_stdio_src
+ * only before the first one. (If we discarded the buffer at the end of
+ * one image, we'd likely lose the start of the next one.)
+ * This makes it unsafe to use this manager and a different source
+ * manager serially with the same JPEG object. Caveat programmer.
+ */
+ if (cinfo->src == NULL) { /* first time for this JPEG object? */
+ cinfo->src = (struct jpeg_source_mgr *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ SIZEOF(my_source_mgr));
+ src = (my_src_ptr) cinfo->src;
+ src->buffer = (JOCTET *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ INPUT_BUF_SIZE * SIZEOF(JOCTET));
+ }
+
+ src = (my_src_ptr) cinfo->src;
+ src->pub.init_source = init_source;
+ src->pub.fill_input_buffer = fill_input_buffer;
+ src->pub.skip_input_data = skip_input_data;
+ src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
+ src->pub.term_source = term_source;
+ src->infile = infile;
+ src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
+ src->pub.next_input_byte = NULL; /* until buffer loaded */
+}
diff --git a/code/jpeg-6/jdcoefct.c b/code/jpeg-6/jdcoefct.c
new file mode 100755
index 0000000..2b20c07
--- /dev/null
+++ b/code/jpeg-6/jdcoefct.c
@@ -0,0 +1,725 @@
+/*
+ * jdcoefct.c
+ *
+ * Copyright (C) 1994-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the coefficient buffer controller for decompression.
+ * This controller is the top level of the JPEG decompressor proper.
+ * The coefficient buffer lies between entropy decoding and inverse-DCT steps.
+ *
+ * In buffered-image mode, this controller is the interface between
+ * input-oriented processing and output-oriented processing.
+ * Also, the input side (only) is used when reading a file for transcoding.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+/* Block smoothing is only applicable for progressive JPEG, so: */
+#ifndef D_PROGRESSIVE_SUPPORTED
+#undef BLOCK_SMOOTHING_SUPPORTED
+#endif
+
+/* Private buffer controller object */
+
+typedef struct {
+ struct jpeg_d_coef_controller pub; /* public fields */
+
+ /* These variables keep track of the current location of the input side. */
+ /* cinfo->input_iMCU_row is also used for this. */
+ JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
+ int MCU_vert_offset; /* counts MCU rows within iMCU row */
+ int MCU_rows_per_iMCU_row; /* number of such rows needed */
+
+ /* The output side's location is represented by cinfo->output_iMCU_row. */
+
+ /* In single-pass modes, it's sufficient to buffer just one MCU.
+ * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
+ * and let the entropy decoder write into that workspace each time.
+ * (On 80x86, the workspace is FAR even though it's not really very big;
+ * this is to keep the module interfaces unchanged when a large coefficient
+ * buffer is necessary.)
+ * In multi-pass modes, this array points to the current MCU's blocks
+ * within the virtual arrays; it is used only by the input side.
+ */
+ JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
+
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+ /* In multi-pass modes, we need a virtual block array for each component. */
+ jvirt_barray_ptr whole_image[MAX_COMPONENTS];
+#endif
+
+#ifdef BLOCK_SMOOTHING_SUPPORTED
+ /* When doing block smoothing, we latch coefficient Al values here */
+ int * coef_bits_latch;
+#define SAVED_COEFS 6 /* we save coef_bits[0..5] */
+#endif
+} my_coef_controller;
+
+typedef my_coef_controller * my_coef_ptr;
+
+/* Forward declarations */
+METHODDEF int decompress_onepass
+ JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+METHODDEF int decompress_data
+ JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
+#endif
+#ifdef BLOCK_SMOOTHING_SUPPORTED
+LOCAL boolean smoothing_ok JPP((j_decompress_ptr cinfo));
+METHODDEF int decompress_smooth_data
+ JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
+#endif
+
+
+LOCAL void
+start_iMCU_row (j_decompress_ptr cinfo)
+/* Reset within-iMCU-row counters for a new row (input side) */
+{
+ my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+
+ /* In an interleaved scan, an MCU row is the same as an iMCU row.
+ * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
+ * But at the bottom of the image, process only what's left.
+ */
+ if (cinfo->comps_in_scan > 1) {
+ coef->MCU_rows_per_iMCU_row = 1;
+ } else {
+ if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
+ coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
+ else
+ coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
+ }
+
+ coef->MCU_ctr = 0;
+ coef->MCU_vert_offset = 0;
+}
+
+
+/*
+ * Initialize for an input processing pass.
+ */
+
+METHODDEF void
+start_input_pass (j_decompress_ptr cinfo)
+{
+ cinfo->input_iMCU_row = 0;
+ start_iMCU_row(cinfo);
+}
+
+
+/*
+ * Initialize for an output processing pass.
+ */
+
+METHODDEF void
+start_output_pass (j_decompress_ptr cinfo)
+{
+#ifdef BLOCK_SMOOTHING_SUPPORTED
+ my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+
+ /* If multipass, check to see whether to use block smoothing on this pass */
+ if (coef->pub.coef_arrays != NULL) {
+ if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
+ coef->pub.decompress_data = decompress_smooth_data;
+ else
+ coef->pub.decompress_data = decompress_data;
+ }
+#endif
+ cinfo->output_iMCU_row = 0;
+}
+
+
+/*
+ * Decompress and return some data in the single-pass case.
+ * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
+ * Input and output must run in lockstep since we have only a one-MCU buffer.
+ * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
+ *
+ * NB: output_buf contains a plane for each component in image.
+ * For single pass, this is the same as the components in the scan.
+ */
+
+METHODDEF int
+decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
+{
+ my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ int blkn, ci, xindex, yindex, yoffset, useful_width;
+ JSAMPARRAY output_ptr;
+ JDIMENSION start_col, output_col;
+ jpeg_component_info *compptr;
+ inverse_DCT_method_ptr inverse_DCT;
+
+ /* Loop to process as much as one whole iMCU row */
+ for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
+ yoffset++) {
+ for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
+ MCU_col_num++) {
+ /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
+ jzero_far((void FAR *) coef->MCU_buffer[0],
+ (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
+ if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
+ /* Suspension forced; update state counters and exit */
+ coef->MCU_vert_offset = yoffset;
+ coef->MCU_ctr = MCU_col_num;
+ return JPEG_SUSPENDED;
+ }
+ /* Determine where data should go in output_buf and do the IDCT thing.
+ * We skip dummy blocks at the right and bottom edges (but blkn gets
+ * incremented past them!). Note the inner loop relies on having
+ * allocated the MCU_buffer[] blocks sequentially.
+ */
+ blkn = 0; /* index of current DCT block within MCU */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ /* Don't bother to IDCT an uninteresting component. */
+ if (! compptr->component_needed) {
+ blkn += compptr->MCU_blocks;
+ continue;
+ }
+ inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
+ useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
+ : compptr->last_col_width;
+ output_ptr = output_buf[ci] + yoffset * compptr->DCT_scaled_size;
+ start_col = MCU_col_num * compptr->MCU_sample_width;
+ for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
+ if (cinfo->input_iMCU_row < last_iMCU_row ||
+ yoffset+yindex < compptr->last_row_height) {
+ output_col = start_col;
+ for (xindex = 0; xindex < useful_width; xindex++) {
+ (*inverse_DCT) (cinfo, compptr,
+ (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
+ output_ptr, output_col);
+ output_col += compptr->DCT_scaled_size;
+ }
+ }
+ blkn += compptr->MCU_width;
+ output_ptr += compptr->DCT_scaled_size;
+ }
+ }
+ }
+ /* Completed an MCU row, but perhaps not an iMCU row */
+ coef->MCU_ctr = 0;
+ }
+ /* Completed the iMCU row, advance counters for next one */
+ cinfo->output_iMCU_row++;
+ if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
+ start_iMCU_row(cinfo);
+ return JPEG_ROW_COMPLETED;
+ }
+ /* Completed the scan */
+ (*cinfo->inputctl->finish_input_pass) (cinfo);
+ return JPEG_SCAN_COMPLETED;
+}
+
+
+/*
+ * Dummy consume-input routine for single-pass operation.
+ */
+
+METHODDEF int
+dummy_consume_data (j_decompress_ptr cinfo)
+{
+ return JPEG_SUSPENDED; /* Always indicate nothing was done */
+}
+
+
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+
+/*
+ * Consume input data and store it in the full-image coefficient buffer.
+ * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
+ * ie, v_samp_factor block rows for each component in the scan.
+ * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
+ */
+
+METHODDEF int
+consume_data (j_decompress_ptr cinfo)
+{
+ my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ int blkn, ci, xindex, yindex, yoffset;
+ JDIMENSION start_col;
+ JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
+ JBLOCKROW buffer_ptr;
+ jpeg_component_info *compptr;
+
+ /* Align the virtual buffers for the components used in this scan. */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ buffer[ci] = (*cinfo->mem->access_virt_barray)
+ ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
+ cinfo->input_iMCU_row * compptr->v_samp_factor,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ /* Note: entropy decoder expects buffer to be zeroed,
+ * but this is handled automatically by the memory manager
+ * because we requested a pre-zeroed array.
+ */
+ }
+
+ /* Loop to process one whole iMCU row */
+ for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
+ yoffset++) {
+ for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
+ MCU_col_num++) {
+ /* Construct list of pointers to DCT blocks belonging to this MCU */
+ blkn = 0; /* index of current DCT block within MCU */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ start_col = MCU_col_num * compptr->MCU_width;
+ for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
+ buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
+ for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
+ coef->MCU_buffer[blkn++] = buffer_ptr++;
+ }
+ }
+ }
+ /* Try to fetch the MCU. */
+ if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
+ /* Suspension forced; update state counters and exit */
+ coef->MCU_vert_offset = yoffset;
+ coef->MCU_ctr = MCU_col_num;
+ return JPEG_SUSPENDED;
+ }
+ }
+ /* Completed an MCU row, but perhaps not an iMCU row */
+ coef->MCU_ctr = 0;
+ }
+ /* Completed the iMCU row, advance counters for next one */
+ if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
+ start_iMCU_row(cinfo);
+ return JPEG_ROW_COMPLETED;
+ }
+ /* Completed the scan */
+ (*cinfo->inputctl->finish_input_pass) (cinfo);
+ return JPEG_SCAN_COMPLETED;
+}
+
+
+/*
+ * Decompress and return some data in the multi-pass case.
+ * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
+ * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
+ *
+ * NB: output_buf contains a plane for each component in image.
+ */
+
+METHODDEF int
+decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
+{
+ my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ JDIMENSION block_num;
+ int ci, block_row, block_rows;
+ JBLOCKARRAY buffer;
+ JBLOCKROW buffer_ptr;
+ JSAMPARRAY output_ptr;
+ JDIMENSION output_col;
+ jpeg_component_info *compptr;
+ inverse_DCT_method_ptr inverse_DCT;
+
+ /* Force some input to be done if we are getting ahead of the input. */
+ while (cinfo->input_scan_number < cinfo->output_scan_number ||
+ (cinfo->input_scan_number == cinfo->output_scan_number &&
+ cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
+ if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
+ return JPEG_SUSPENDED;
+ }
+
+ /* OK, output from the virtual arrays. */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Don't bother to IDCT an uninteresting component. */
+ if (! compptr->component_needed)
+ continue;
+ /* Align the virtual buffer for this component. */
+ buffer = (*cinfo->mem->access_virt_barray)
+ ((j_common_ptr) cinfo, coef->whole_image[ci],
+ cinfo->output_iMCU_row * compptr->v_samp_factor,
+ (JDIMENSION) compptr->v_samp_factor, FALSE);
+ /* Count non-dummy DCT block rows in this iMCU row. */
+ if (cinfo->output_iMCU_row < last_iMCU_row)
+ block_rows = compptr->v_samp_factor;
+ else {
+ /* NB: can't use last_row_height here; it is input-side-dependent! */
+ block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
+ if (block_rows == 0) block_rows = compptr->v_samp_factor;
+ }
+ inverse_DCT = cinfo->idct->inverse_DCT[ci];
+ output_ptr = output_buf[ci];
+ /* Loop over all DCT blocks to be processed. */
+ for (block_row = 0; block_row < block_rows; block_row++) {
+ buffer_ptr = buffer[block_row];
+ output_col = 0;
+ for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
+ (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
+ output_ptr, output_col);
+ buffer_ptr++;
+ output_col += compptr->DCT_scaled_size;
+ }
+ output_ptr += compptr->DCT_scaled_size;
+ }
+ }
+
+ if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
+ return JPEG_ROW_COMPLETED;
+ return JPEG_SCAN_COMPLETED;
+}
+
+#endif /* D_MULTISCAN_FILES_SUPPORTED */
+
+
+#ifdef BLOCK_SMOOTHING_SUPPORTED
+
+/*
+ * This code applies interblock smoothing as described by section K.8
+ * of the JPEG standard: the first 5 AC coefficients are estimated from
+ * the DC values of a DCT block and its 8 neighboring blocks.
+ * We apply smoothing only for progressive JPEG decoding, and only if
+ * the coefficients it can estimate are not yet known to full precision.
+ */
+
+/*
+ * Determine whether block smoothing is applicable and safe.
+ * We also latch the current states of the coef_bits[] entries for the
+ * AC coefficients; otherwise, if the input side of the decompressor
+ * advances into a new scan, we might think the coefficients are known
+ * more accurately than they really are.
+ */
+
+LOCAL boolean
+smoothing_ok (j_decompress_ptr cinfo)
+{
+ my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+ boolean smoothing_useful = FALSE;
+ int ci, coefi;
+ jpeg_component_info *compptr;
+ JQUANT_TBL * qtable;
+ int * coef_bits;
+ int * coef_bits_latch;
+
+ if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
+ return FALSE;
+
+ /* Allocate latch area if not already done */
+ if (coef->coef_bits_latch == NULL)
+ coef->coef_bits_latch = (int *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ cinfo->num_components *
+ (SAVED_COEFS * SIZEOF(int)));
+ coef_bits_latch = coef->coef_bits_latch;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* All components' quantization values must already be latched. */
+ if ((qtable = compptr->quant_table) == NULL)
+ return FALSE;
+ /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
+ for (coefi = 0; coefi <= 5; coefi++) {
+ if (qtable->quantval[coefi] == 0)
+ return FALSE;
+ }
+ /* DC values must be at least partly known for all components. */
+ coef_bits = cinfo->coef_bits[ci];
+ if (coef_bits[0] < 0)
+ return FALSE;
+ /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
+ for (coefi = 1; coefi <= 5; coefi++) {
+ coef_bits_latch[coefi] = coef_bits[coefi];
+ if (coef_bits[coefi] != 0)
+ smoothing_useful = TRUE;
+ }
+ coef_bits_latch += SAVED_COEFS;
+ }
+
+ return smoothing_useful;
+}
+
+
+/*
+ * Variant of decompress_data for use when doing block smoothing.
+ */
+
+METHODDEF int
+decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
+{
+ my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ JDIMENSION block_num, last_block_column;
+ int ci, block_row, block_rows, access_rows;
+ JBLOCKARRAY buffer;
+ JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
+ JSAMPARRAY output_ptr;
+ JDIMENSION output_col;
+ jpeg_component_info *compptr;
+ inverse_DCT_method_ptr inverse_DCT;
+ boolean first_row, last_row;
+ JBLOCK workspace;
+ int *coef_bits;
+ JQUANT_TBL *quanttbl;
+ INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
+ int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
+ int Al, pred;
+
+ /* Force some input to be done if we are getting ahead of the input. */
+ while (cinfo->input_scan_number <= cinfo->output_scan_number &&
+ ! cinfo->inputctl->eoi_reached) {
+ if (cinfo->input_scan_number == cinfo->output_scan_number) {
+ /* If input is working on current scan, we ordinarily want it to
+ * have completed the current row. But if input scan is DC,
+ * we want it to keep one row ahead so that next block row's DC
+ * values are up to date.
+ */
+ JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
+ if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
+ break;
+ }
+ if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
+ return JPEG_SUSPENDED;
+ }
+
+ /* OK, output from the virtual arrays. */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Don't bother to IDCT an uninteresting component. */
+ if (! compptr->component_needed)
+ continue;
+ /* Count non-dummy DCT block rows in this iMCU row. */
+ if (cinfo->output_iMCU_row < last_iMCU_row) {
+ block_rows = compptr->v_samp_factor;
+ access_rows = block_rows * 2; /* this and next iMCU row */
+ last_row = FALSE;
+ } else {
+ /* NB: can't use last_row_height here; it is input-side-dependent! */
+ block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
+ if (block_rows == 0) block_rows = compptr->v_samp_factor;
+ access_rows = block_rows; /* this iMCU row only */
+ last_row = TRUE;
+ }
+ /* Align the virtual buffer for this component. */
+ if (cinfo->output_iMCU_row > 0) {
+ access_rows += compptr->v_samp_factor; /* prior iMCU row too */
+ buffer = (*cinfo->mem->access_virt_barray)
+ ((j_common_ptr) cinfo, coef->whole_image[ci],
+ (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
+ (JDIMENSION) access_rows, FALSE);
+ buffer += compptr->v_samp_factor; /* point to current iMCU row */
+ first_row = FALSE;
+ } else {
+ buffer = (*cinfo->mem->access_virt_barray)
+ ((j_common_ptr) cinfo, coef->whole_image[ci],
+ (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
+ first_row = TRUE;
+ }
+ /* Fetch component-dependent info */
+ coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
+ quanttbl = compptr->quant_table;
+ Q00 = quanttbl->quantval[0];
+ Q01 = quanttbl->quantval[1];
+ Q10 = quanttbl->quantval[2];
+ Q20 = quanttbl->quantval[3];
+ Q11 = quanttbl->quantval[4];
+ Q02 = quanttbl->quantval[5];
+ inverse_DCT = cinfo->idct->inverse_DCT[ci];
+ output_ptr = output_buf[ci];
+ /* Loop over all DCT blocks to be processed. */
+ for (block_row = 0; block_row < block_rows; block_row++) {
+ buffer_ptr = buffer[block_row];
+ if (first_row && block_row == 0)
+ prev_block_row = buffer_ptr;
+ else
+ prev_block_row = buffer[block_row-1];
+ if (last_row && block_row == block_rows-1)
+ next_block_row = buffer_ptr;
+ else
+ next_block_row = buffer[block_row+1];
+ /* We fetch the surrounding DC values using a sliding-register approach.
+ * Initialize all nine here so as to do the right thing on narrow pics.
+ */
+ DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
+ DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
+ DC7 = DC8 = DC9 = (int) next_block_row[0][0];
+ output_col = 0;
+ last_block_column = compptr->width_in_blocks - 1;
+ for (block_num = 0; block_num <= last_block_column; block_num++) {
+ /* Fetch current DCT block into workspace so we can modify it. */
+ jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
+ /* Update DC values */
+ if (block_num < last_block_column) {
+ DC3 = (int) prev_block_row[1][0];
+ DC6 = (int) buffer_ptr[1][0];
+ DC9 = (int) next_block_row[1][0];
+ }
+ /* Compute coefficient estimates per K.8.
+ * An estimate is applied only if coefficient is still zero,
+ * and is not known to be fully accurate.
+ */
+ /* AC01 */
+ if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
+ num = 36 * Q00 * (DC4 - DC6);
+ if (num >= 0) {
+ pred = (int) (((Q01<<7) + num) / (Q01<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ } else {
+ pred = (int) (((Q01<<7) - num) / (Q01<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ pred = -pred;
+ }
+ workspace[1] = (JCOEF) pred;
+ }
+ /* AC10 */
+ if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
+ num = 36 * Q00 * (DC2 - DC8);
+ if (num >= 0) {
+ pred = (int) (((Q10<<7) + num) / (Q10<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ } else {
+ pred = (int) (((Q10<<7) - num) / (Q10<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ pred = -pred;
+ }
+ workspace[8] = (JCOEF) pred;
+ }
+ /* AC20 */
+ if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
+ num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
+ if (num >= 0) {
+ pred = (int) (((Q20<<7) + num) / (Q20<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ } else {
+ pred = (int) (((Q20<<7) - num) / (Q20<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ pred = -pred;
+ }
+ workspace[16] = (JCOEF) pred;
+ }
+ /* AC11 */
+ if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
+ num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
+ if (num >= 0) {
+ pred = (int) (((Q11<<7) + num) / (Q11<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ } else {
+ pred = (int) (((Q11<<7) - num) / (Q11<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ pred = -pred;
+ }
+ workspace[9] = (JCOEF) pred;
+ }
+ /* AC02 */
+ if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
+ num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
+ if (num >= 0) {
+ pred = (int) (((Q02<<7) + num) / (Q02<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ } else {
+ pred = (int) (((Q02<<7) - num) / (Q02<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ pred = -pred;
+ }
+ workspace[2] = (JCOEF) pred;
+ }
+ /* OK, do the IDCT */
+ (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
+ output_ptr, output_col);
+ /* Advance for next column */
+ DC1 = DC2; DC2 = DC3;
+ DC4 = DC5; DC5 = DC6;
+ DC7 = DC8; DC8 = DC9;
+ buffer_ptr++, prev_block_row++, next_block_row++;
+ output_col += compptr->DCT_scaled_size;
+ }
+ output_ptr += compptr->DCT_scaled_size;
+ }
+ }
+
+ if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
+ return JPEG_ROW_COMPLETED;
+ return JPEG_SCAN_COMPLETED;
+}
+
+#endif /* BLOCK_SMOOTHING_SUPPORTED */
+
+
+/*
+ * Initialize coefficient buffer controller.
+ */
+
+GLOBAL void
+jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
+{
+ my_coef_ptr coef;
+
+ coef = (my_coef_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_coef_controller));
+ cinfo->coef = (struct jpeg_d_coef_controller *) coef;
+ coef->pub.start_input_pass = start_input_pass;
+ coef->pub.start_output_pass = start_output_pass;
+#ifdef BLOCK_SMOOTHING_SUPPORTED
+ coef->coef_bits_latch = NULL;
+#endif
+
+ /* Create the coefficient buffer. */
+ if (need_full_buffer) {
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+ /* Allocate a full-image virtual array for each component, */
+ /* padded to a multiple of samp_factor DCT blocks in each direction. */
+ /* Note we ask for a pre-zeroed array. */
+ int ci, access_rows;
+ jpeg_component_info *compptr;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ access_rows = compptr->v_samp_factor;
+#ifdef BLOCK_SMOOTHING_SUPPORTED
+ /* If block smoothing could be used, need a bigger window */
+ if (cinfo->progressive_mode)
+ access_rows *= 3;
+#endif
+ coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
+ (JDIMENSION) jround_up((long) compptr->width_in_blocks,
+ (long) compptr->h_samp_factor),
+ (JDIMENSION) jround_up((long) compptr->height_in_blocks,
+ (long) compptr->v_samp_factor),
+ (JDIMENSION) access_rows);
+ }
+ coef->pub.consume_data = consume_data;
+ coef->pub.decompress_data = decompress_data;
+ coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else {
+ /* We only need a single-MCU buffer. */
+ JBLOCKROW buffer;
+ int i;
+
+ buffer = (JBLOCKROW)
+ (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
+ for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
+ coef->MCU_buffer[i] = buffer + i;
+ }
+ coef->pub.consume_data = dummy_consume_data;
+ coef->pub.decompress_data = decompress_onepass;
+ coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
+ }
+}
diff --git a/code/jpeg-6/jdcolor.c b/code/jpeg-6/jdcolor.c
new file mode 100755
index 0000000..d360b53
--- /dev/null
+++ b/code/jpeg-6/jdcolor.c
@@ -0,0 +1,367 @@
+/*
+ * jdcolor.c
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains output colorspace conversion routines.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Private subobject */
+
+typedef struct {
+ struct jpeg_color_deconverter pub; /* public fields */
+
+ /* Private state for YCC->RGB conversion */
+ int * Cr_r_tab; /* => table for Cr to R conversion */
+ int * Cb_b_tab; /* => table for Cb to B conversion */
+ INT32 * Cr_g_tab; /* => table for Cr to G conversion */
+ INT32 * Cb_g_tab; /* => table for Cb to G conversion */
+} my_color_deconverter;
+
+typedef my_color_deconverter * my_cconvert_ptr;
+
+
+/**************** YCbCr -> RGB conversion: most common case **************/
+
+/*
+ * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
+ * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
+ * The conversion equations to be implemented are therefore
+ * R = Y + 1.40200 * Cr
+ * G = Y - 0.34414 * Cb - 0.71414 * Cr
+ * B = Y + 1.77200 * Cb
+ * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
+ * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
+ *
+ * To avoid floating-point arithmetic, we represent the fractional constants
+ * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
+ * the products by 2^16, with appropriate rounding, to get the correct answer.
+ * Notice that Y, being an integral input, does not contribute any fraction
+ * so it need not participate in the rounding.
+ *
+ * For even more speed, we avoid doing any multiplications in the inner loop
+ * by precalculating the constants times Cb and Cr for all possible values.
+ * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
+ * for 12-bit samples it is still acceptable. It's not very reasonable for
+ * 16-bit samples, but if you want lossless storage you shouldn't be changing
+ * colorspace anyway.
+ * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
+ * values for the G calculation are left scaled up, since we must add them
+ * together before rounding.
+ */
+
+#define SCALEBITS 16 /* speediest right-shift on some machines */
+#define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
+#define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
+
+
+/*
+ * Initialize tables for YCC->RGB colorspace conversion.
+ */
+
+LOCAL void
+build_ycc_rgb_table (j_decompress_ptr cinfo)
+{
+ my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+ int i;
+ INT32 x;
+ SHIFT_TEMPS
+
+ cconvert->Cr_r_tab = (int *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (MAXJSAMPLE+1) * SIZEOF(int));
+ cconvert->Cb_b_tab = (int *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (MAXJSAMPLE+1) * SIZEOF(int));
+ cconvert->Cr_g_tab = (INT32 *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (MAXJSAMPLE+1) * SIZEOF(INT32));
+ cconvert->Cb_g_tab = (INT32 *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (MAXJSAMPLE+1) * SIZEOF(INT32));
+
+ for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
+ /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
+ /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
+ /* Cr=>R value is nearest int to 1.40200 * x */
+ cconvert->Cr_r_tab[i] = (int)
+ RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
+ /* Cb=>B value is nearest int to 1.77200 * x */
+ cconvert->Cb_b_tab[i] = (int)
+ RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
+ /* Cr=>G value is scaled-up -0.71414 * x */
+ cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
+ /* Cb=>G value is scaled-up -0.34414 * x */
+ /* We also add in ONE_HALF so that need not do it in inner loop */
+ cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
+ }
+}
+
+
+/*
+ * Convert some rows of samples to the output colorspace.
+ *
+ * Note that we change from noninterleaved, one-plane-per-component format
+ * to interleaved-pixel format. The output buffer is therefore three times
+ * as wide as the input buffer.
+ * A starting row offset is provided only for the input buffer. The caller
+ * can easily adjust the passed output_buf value to accommodate any row
+ * offset required on that side.
+ */
+
+METHODDEF void
+ycc_rgb_convert (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION input_row,
+ JSAMPARRAY output_buf, int num_rows)
+{
+ my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+ register int y, cb, cr;
+ register JSAMPROW outptr;
+ register JSAMPROW inptr0, inptr1, inptr2;
+ register JDIMENSION col;
+ JDIMENSION num_cols = cinfo->output_width;
+ /* copy these pointers into registers if possible */
+ register JSAMPLE * range_limit = cinfo->sample_range_limit;
+ register int * Crrtab = cconvert->Cr_r_tab;
+ register int * Cbbtab = cconvert->Cb_b_tab;
+ register INT32 * Crgtab = cconvert->Cr_g_tab;
+ register INT32 * Cbgtab = cconvert->Cb_g_tab;
+ SHIFT_TEMPS
+
+ while (--num_rows >= 0) {
+ inptr0 = input_buf[0][input_row];
+ inptr1 = input_buf[1][input_row];
+ inptr2 = input_buf[2][input_row];
+ input_row++;
+ outptr = *output_buf++;
+ for (col = 0; col < num_cols; col++) {
+ y = GETJSAMPLE(inptr0[col]);
+ cb = GETJSAMPLE(inptr1[col]);
+ cr = GETJSAMPLE(inptr2[col]);
+ /* Range-limiting is essential due to noise introduced by DCT losses. */
+ outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
+ outptr[RGB_GREEN] = range_limit[y +
+ ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
+ SCALEBITS))];
+ outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
+ outptr += RGB_PIXELSIZE;
+ }
+ }
+}
+
+
+/**************** Cases other than YCbCr -> RGB **************/
+
+
+/*
+ * Color conversion for no colorspace change: just copy the data,
+ * converting from separate-planes to interleaved representation.
+ */
+
+METHODDEF void
+null_convert (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION input_row,
+ JSAMPARRAY output_buf, int num_rows)
+{
+ register JSAMPROW inptr, outptr;
+ register JDIMENSION count;
+ register int num_components = cinfo->num_components;
+ JDIMENSION num_cols = cinfo->output_width;
+ int ci;
+
+ while (--num_rows >= 0) {
+ for (ci = 0; ci < num_components; ci++) {
+ inptr = input_buf[ci][input_row];
+ outptr = output_buf[0] + ci;
+ for (count = num_cols; count > 0; count--) {
+ *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
+ outptr += num_components;
+ }
+ }
+ input_row++;
+ output_buf++;
+ }
+}
+
+
+/*
+ * Color conversion for grayscale: just copy the data.
+ * This also works for YCbCr -> grayscale conversion, in which
+ * we just copy the Y (luminance) component and ignore chrominance.
+ */
+
+METHODDEF void
+grayscale_convert (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION input_row,
+ JSAMPARRAY output_buf, int num_rows)
+{
+ jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
+ num_rows, cinfo->output_width);
+}
+
+
+/*
+ * Adobe-style YCCK->CMYK conversion.
+ * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
+ * conversion as above, while passing K (black) unchanged.
+ * We assume build_ycc_rgb_table has been called.
+ */
+
+METHODDEF void
+ycck_cmyk_convert (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION input_row,
+ JSAMPARRAY output_buf, int num_rows)
+{
+ my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+ register int y, cb, cr;
+ register JSAMPROW outptr;
+ register JSAMPROW inptr0, inptr1, inptr2, inptr3;
+ register JDIMENSION col;
+ JDIMENSION num_cols = cinfo->output_width;
+ /* copy these pointers into registers if possible */
+ register JSAMPLE * range_limit = cinfo->sample_range_limit;
+ register int * Crrtab = cconvert->Cr_r_tab;
+ register int * Cbbtab = cconvert->Cb_b_tab;
+ register INT32 * Crgtab = cconvert->Cr_g_tab;
+ register INT32 * Cbgtab = cconvert->Cb_g_tab;
+ SHIFT_TEMPS
+
+ while (--num_rows >= 0) {
+ inptr0 = input_buf[0][input_row];
+ inptr1 = input_buf[1][input_row];
+ inptr2 = input_buf[2][input_row];
+ inptr3 = input_buf[3][input_row];
+ input_row++;
+ outptr = *output_buf++;
+ for (col = 0; col < num_cols; col++) {
+ y = GETJSAMPLE(inptr0[col]);
+ cb = GETJSAMPLE(inptr1[col]);
+ cr = GETJSAMPLE(inptr2[col]);
+ /* Range-limiting is essential due to noise introduced by DCT losses. */
+ outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
+ outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
+ ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
+ SCALEBITS)))];
+ outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
+ /* K passes through unchanged */
+ outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
+ outptr += 4;
+ }
+ }
+}
+
+
+/*
+ * Empty method for start_pass.
+ */
+
+METHODDEF void
+start_pass_dcolor (j_decompress_ptr cinfo)
+{
+ /* no work needed */
+}
+
+
+/*
+ * Module initialization routine for output colorspace conversion.
+ */
+
+GLOBAL void
+jinit_color_deconverter (j_decompress_ptr cinfo)
+{
+ my_cconvert_ptr cconvert;
+ int ci;
+
+ cconvert = (my_cconvert_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_color_deconverter));
+ cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
+ cconvert->pub.start_pass = start_pass_dcolor;
+
+ /* Make sure num_components agrees with jpeg_color_space */
+ switch (cinfo->jpeg_color_space) {
+ case JCS_GRAYSCALE:
+ if (cinfo->num_components != 1)
+ ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+ break;
+
+ case JCS_RGB:
+ case JCS_YCbCr:
+ if (cinfo->num_components != 3)
+ ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+ break;
+
+ case JCS_CMYK:
+ case JCS_YCCK:
+ if (cinfo->num_components != 4)
+ ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+ break;
+
+ default: /* JCS_UNKNOWN can be anything */
+ if (cinfo->num_components < 1)
+ ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+ break;
+ }
+
+ /* Set out_color_components and conversion method based on requested space.
+ * Also clear the component_needed flags for any unused components,
+ * so that earlier pipeline stages can avoid useless computation.
+ */
+
+ switch (cinfo->out_color_space) {
+ case JCS_GRAYSCALE:
+ cinfo->out_color_components = 1;
+ if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
+ cinfo->jpeg_color_space == JCS_YCbCr) {
+ cconvert->pub.color_convert = grayscale_convert;
+ /* For color->grayscale conversion, only the Y (0) component is needed */
+ for (ci = 1; ci < cinfo->num_components; ci++)
+ cinfo->comp_info[ci].component_needed = FALSE;
+ } else
+ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+ break;
+
+ case JCS_RGB:
+ cinfo->out_color_components = RGB_PIXELSIZE;
+ if (cinfo->jpeg_color_space == JCS_YCbCr) {
+ cconvert->pub.color_convert = ycc_rgb_convert;
+ build_ycc_rgb_table(cinfo);
+ } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
+ cconvert->pub.color_convert = null_convert;
+ } else
+ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+ break;
+
+ case JCS_CMYK:
+ cinfo->out_color_components = 4;
+ if (cinfo->jpeg_color_space == JCS_YCCK) {
+ cconvert->pub.color_convert = ycck_cmyk_convert;
+ build_ycc_rgb_table(cinfo);
+ } else if (cinfo->jpeg_color_space == JCS_CMYK) {
+ cconvert->pub.color_convert = null_convert;
+ } else
+ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+ break;
+
+ default:
+ /* Permit null conversion to same output space */
+ if (cinfo->out_color_space == cinfo->jpeg_color_space) {
+ cinfo->out_color_components = cinfo->num_components;
+ cconvert->pub.color_convert = null_convert;
+ } else /* unsupported non-null conversion */
+ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+ break;
+ }
+
+ if (cinfo->quantize_colors)
+ cinfo->output_components = 1; /* single colormapped output component */
+ else
+ cinfo->output_components = cinfo->out_color_components;
+}
diff --git a/code/jpeg-6/jdct.h b/code/jpeg-6/jdct.h
new file mode 100755
index 0000000..1d66d4f
--- /dev/null
+++ b/code/jpeg-6/jdct.h
@@ -0,0 +1,176 @@
+/*
+ * jdct.h
+ *
+ * Copyright (C) 1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This include file contains common declarations for the forward and
+ * inverse DCT modules. These declarations are private to the DCT managers
+ * (jcdctmgr.c, jddctmgr.c) and the individual DCT algorithms.
+ * The individual DCT algorithms are kept in separate files to ease
+ * machine-dependent tuning (e.g., assembly coding).
+ */
+
+
+/*
+ * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
+ * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
+ * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
+ * implementations use an array of type FAST_FLOAT, instead.)
+ * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
+ * The DCT outputs are returned scaled up by a factor of 8; they therefore
+ * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
+ * convention improves accuracy in integer implementations and saves some
+ * work in floating-point ones.
+ * Quantization of the output coefficients is done by jcdctmgr.c.
+ */
+
+#if BITS_IN_JSAMPLE == 8
+typedef int DCTELEM; /* 16 or 32 bits is fine */
+#else
+typedef INT32 DCTELEM; /* must have 32 bits */
+#endif
+
+typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
+typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
+
+
+/*
+ * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
+ * to an output sample array. The routine must dequantize the input data as
+ * well as perform the IDCT; for dequantization, it uses the multiplier table
+ * pointed to by compptr->dct_table. The output data is to be placed into the
+ * sample array starting at a specified column. (Any row offset needed will
+ * be applied to the array pointer before it is passed to the IDCT code.)
+ * Note that the number of samples emitted by the IDCT routine is
+ * DCT_scaled_size * DCT_scaled_size.
+ */
+
+/* typedef inverse_DCT_method_ptr is declared in jpegint.h */
+
+/*
+ * Each IDCT routine has its own ideas about the best dct_table element type.
+ */
+
+typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
+#if BITS_IN_JSAMPLE == 8
+typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
+#define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
+#else
+typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
+#define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
+#endif
+typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
+
+
+/*
+ * Each IDCT routine is responsible for range-limiting its results and
+ * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
+ * be quite far out of range if the input data is corrupt, so a bulletproof
+ * range-limiting step is required. We use a mask-and-table-lookup method
+ * to do the combined operations quickly. See the comments with
+ * prepare_range_limit_table (in jdmaster.c) for more info.
+ */
+
+#define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
+
+#define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
+
+
+/* Short forms of external names for systems with brain-damaged linkers. */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jpeg_fdct_islow jFDislow
+#define jpeg_fdct_ifast jFDifast
+#define jpeg_fdct_float jFDfloat
+#define jpeg_idct_islow jRDislow
+#define jpeg_idct_ifast jRDifast
+#define jpeg_idct_float jRDfloat
+#define jpeg_idct_4x4 jRD4x4
+#define jpeg_idct_2x2 jRD2x2
+#define jpeg_idct_1x1 jRD1x1
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+/* Extern declarations for the forward and inverse DCT routines. */
+
+EXTERN void jpeg_fdct_islow JPP((DCTELEM * data));
+EXTERN void jpeg_fdct_ifast JPP((DCTELEM * data));
+EXTERN void jpeg_fdct_float JPP((FAST_FLOAT * data));
+
+EXTERN void jpeg_idct_islow
+ JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN void jpeg_idct_ifast
+ JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN void jpeg_idct_float
+ JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN void jpeg_idct_4x4
+ JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN void jpeg_idct_2x2
+ JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN void jpeg_idct_1x1
+ JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+
+
+/*
+ * Macros for handling fixed-point arithmetic; these are used by many
+ * but not all of the DCT/IDCT modules.
+ *
+ * All values are expected to be of type INT32.
+ * Fractional constants are scaled left by CONST_BITS bits.
+ * CONST_BITS is defined within each module using these macros,
+ * and may differ from one module to the next.
+ */
+
+#define ONE ((INT32) 1)
+#define CONST_SCALE (ONE << CONST_BITS)
+
+/* Convert a positive real constant to an integer scaled by CONST_SCALE.
+ * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
+ * thus causing a lot of useless floating-point operations at run time.
+ */
+
+#define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
+
+/* Descale and correctly round an INT32 value that's scaled by N bits.
+ * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
+ * the fudge factor is correct for either sign of X.
+ */
+
+#define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
+
+/* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
+ * This macro is used only when the two inputs will actually be no more than
+ * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
+ * full 32x32 multiply. This provides a useful speedup on many machines.
+ * Unfortunately there is no way to specify a 16x16->32 multiply portably
+ * in C, but some C compilers will do the right thing if you provide the
+ * correct combination of casts.
+ */
+
+#ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
+#define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
+#endif
+#ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
+#define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
+#endif
+
+#ifndef MULTIPLY16C16 /* default definition */
+#define MULTIPLY16C16(var,const) ((var) * (const))
+#endif
+
+/* Same except both inputs are variables. */
+
+#ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
+#define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
+#endif
+
+#ifndef MULTIPLY16V16 /* default definition */
+#define MULTIPLY16V16(var1,var2) ((var1) * (var2))
+#endif
diff --git a/code/jpeg-6/jddctmgr.c b/code/jpeg-6/jddctmgr.c
new file mode 100755
index 0000000..ba01fc6
--- /dev/null
+++ b/code/jpeg-6/jddctmgr.c
@@ -0,0 +1,270 @@
+/*
+ * jddctmgr.c
+ *
+ * Copyright (C) 1994-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the inverse-DCT management logic.
+ * This code selects a particular IDCT implementation to be used,
+ * and it performs related housekeeping chores. No code in this file
+ * is executed per IDCT step, only during output pass setup.
+ *
+ * Note that the IDCT routines are responsible for performing coefficient
+ * dequantization as well as the IDCT proper. This module sets up the
+ * dequantization multiplier table needed by the IDCT routine.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jdct.h" /* Private declarations for DCT subsystem */
+
+
+/*
+ * The decompressor input side (jdinput.c) saves away the appropriate
+ * quantization table for each component at the start of the first scan
+ * involving that component. (This is necessary in order to correctly
+ * decode files that reuse Q-table slots.)
+ * When we are ready to make an output pass, the saved Q-table is converted
+ * to a multiplier table that will actually be used by the IDCT routine.
+ * The multiplier table contents are IDCT-method-dependent. To support
+ * application changes in IDCT method between scans, we can remake the
+ * multiplier tables if necessary.
+ * In buffered-image mode, the first output pass may occur before any data
+ * has been seen for some components, and thus before their Q-tables have
+ * been saved away. To handle this case, multiplier tables are preset
+ * to zeroes; the result of the IDCT will be a neutral gray level.
+ */
+
+
+/* Private subobject for this module */
+
+typedef struct {
+ struct jpeg_inverse_dct pub; /* public fields */
+
+ /* This array contains the IDCT method code that each multiplier table
+ * is currently set up for, or -1 if it's not yet set up.
+ * The actual multiplier tables are pointed to by dct_table in the
+ * per-component comp_info structures.
+ */
+ int cur_method[MAX_COMPONENTS];
+} my_idct_controller;
+
+typedef my_idct_controller * my_idct_ptr;
+
+
+/* Allocated multiplier tables: big enough for any supported variant */
+
+typedef union {
+ ISLOW_MULT_TYPE islow_array[DCTSIZE2];
+#ifdef DCT_IFAST_SUPPORTED
+ IFAST_MULT_TYPE ifast_array[DCTSIZE2];
+#endif
+#ifdef DCT_FLOAT_SUPPORTED
+ FLOAT_MULT_TYPE float_array[DCTSIZE2];
+#endif
+} multiplier_table;
+
+
+/* The current scaled-IDCT routines require ISLOW-style multiplier tables,
+ * so be sure to compile that code if either ISLOW or SCALING is requested.
+ */
+#ifdef DCT_ISLOW_SUPPORTED
+#define PROVIDE_ISLOW_TABLES
+#else
+#ifdef IDCT_SCALING_SUPPORTED
+#define PROVIDE_ISLOW_TABLES
+#endif
+#endif
+
+
+/*
+ * Prepare for an output pass.
+ * Here we select the proper IDCT routine for each component and build
+ * a matching multiplier table.
+ */
+
+METHODDEF void
+start_pass (j_decompress_ptr cinfo)
+{
+ my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
+ int ci, i;
+ jpeg_component_info *compptr;
+ int method = 0;
+ inverse_DCT_method_ptr method_ptr = NULL;
+ JQUANT_TBL * qtbl;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Select the proper IDCT routine for this component's scaling */
+ switch (compptr->DCT_scaled_size) {
+#ifdef IDCT_SCALING_SUPPORTED
+ case 1:
+ method_ptr = jpeg_idct_1x1;
+ method = JDCT_ISLOW; /* jidctred uses islow-style table */
+ break;
+ case 2:
+ method_ptr = jpeg_idct_2x2;
+ method = JDCT_ISLOW; /* jidctred uses islow-style table */
+ break;
+ case 4:
+ method_ptr = jpeg_idct_4x4;
+ method = JDCT_ISLOW; /* jidctred uses islow-style table */
+ break;
+#endif
+ case DCTSIZE:
+ switch (cinfo->dct_method) {
+#ifdef DCT_ISLOW_SUPPORTED
+ case JDCT_ISLOW:
+ method_ptr = jpeg_idct_islow;
+ method = JDCT_ISLOW;
+ break;
+#endif
+#ifdef DCT_IFAST_SUPPORTED
+ case JDCT_IFAST:
+ method_ptr = jpeg_idct_ifast;
+ method = JDCT_IFAST;
+ break;
+#endif
+#ifdef DCT_FLOAT_SUPPORTED
+ case JDCT_FLOAT:
+ method_ptr = jpeg_idct_float;
+ method = JDCT_FLOAT;
+ break;
+#endif
+ default:
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+ break;
+ }
+ break;
+ default:
+ ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
+ break;
+ }
+ idct->pub.inverse_DCT[ci] = method_ptr;
+ /* Create multiplier table from quant table.
+ * However, we can skip this if the component is uninteresting
+ * or if we already built the table. Also, if no quant table
+ * has yet been saved for the component, we leave the
+ * multiplier table all-zero; we'll be reading zeroes from the
+ * coefficient controller's buffer anyway.
+ */
+ if (! compptr->component_needed || idct->cur_method[ci] == method)
+ continue;
+ qtbl = compptr->quant_table;
+ if (qtbl == NULL) /* happens if no data yet for component */
+ continue;
+ idct->cur_method[ci] = method;
+ switch (method) {
+#ifdef PROVIDE_ISLOW_TABLES
+ case JDCT_ISLOW:
+ {
+ /* For LL&M IDCT method, multipliers are equal to raw quantization
+ * coefficients, but are stored in natural order as ints.
+ */
+ ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
+ for (i = 0; i < DCTSIZE2; i++) {
+ ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[jpeg_zigzag_order[i]];
+ }
+ }
+ break;
+#endif
+#ifdef DCT_IFAST_SUPPORTED
+ case JDCT_IFAST:
+ {
+ /* For AA&N IDCT method, multipliers are equal to quantization
+ * coefficients scaled by scalefactor[row]*scalefactor[col], where
+ * scalefactor[0] = 1
+ * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
+ * For integer operation, the multiplier table is to be scaled by
+ * IFAST_SCALE_BITS. The multipliers are stored in natural order.
+ */
+ IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
+#define CONST_BITS 14
+ static const INT16 aanscales[DCTSIZE2] = {
+ /* precomputed values scaled up by 14 bits */
+ 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
+ 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
+ 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
+ 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
+ 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
+ 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
+ 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
+ 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
+ };
+ SHIFT_TEMPS
+
+ for (i = 0; i < DCTSIZE2; i++) {
+ ifmtbl[i] = (IFAST_MULT_TYPE)
+ DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[jpeg_zigzag_order[i]],
+ (INT32) aanscales[i]),
+ CONST_BITS-IFAST_SCALE_BITS);
+ }
+ }
+ break;
+#endif
+#ifdef DCT_FLOAT_SUPPORTED
+ case JDCT_FLOAT:
+ {
+ /* For float AA&N IDCT method, multipliers are equal to quantization
+ * coefficients scaled by scalefactor[row]*scalefactor[col], where
+ * scalefactor[0] = 1
+ * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
+ * The multipliers are stored in natural order.
+ */
+ FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
+ int row, col;
+ static const double aanscalefactor[DCTSIZE] = {
+ 1.0, 1.387039845, 1.306562965, 1.175875602,
+ 1.0, 0.785694958, 0.541196100, 0.275899379
+ };
+
+ i = 0;
+ for (row = 0; row < DCTSIZE; row++) {
+ for (col = 0; col < DCTSIZE; col++) {
+ fmtbl[i] = (FLOAT_MULT_TYPE)
+ ((double) qtbl->quantval[jpeg_zigzag_order[i]] *
+ aanscalefactor[row] * aanscalefactor[col]);
+ i++;
+ }
+ }
+ }
+ break;
+#endif
+ default:
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+ break;
+ }
+ }
+}
+
+
+/*
+ * Initialize IDCT manager.
+ */
+
+GLOBAL void
+jinit_inverse_dct (j_decompress_ptr cinfo)
+{
+ my_idct_ptr idct;
+ int ci;
+ jpeg_component_info *compptr;
+
+ idct = (my_idct_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_idct_controller));
+ cinfo->idct = (struct jpeg_inverse_dct *) idct;
+ idct->pub.start_pass = start_pass;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Allocate and pre-zero a multiplier table for each component */
+ compptr->dct_table =
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(multiplier_table));
+ MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
+ /* Mark multiplier table not yet set up for any method */
+ idct->cur_method[ci] = -1;
+ }
+}
diff --git a/code/jpeg-6/jdhuff.c b/code/jpeg-6/jdhuff.c
new file mode 100755
index 0000000..db42772
--- /dev/null
+++ b/code/jpeg-6/jdhuff.c
@@ -0,0 +1,574 @@
+/*
+ * jdhuff.c
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains Huffman entropy decoding routines.
+ *
+ * Much of the complexity here has to do with supporting input suspension.
+ * If the data source module demands suspension, we want to be able to back
+ * up to the start of the current MCU. To do this, we copy state variables
+ * into local working storage, and update them back to the permanent
+ * storage only upon successful completion of an MCU.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jdhuff.h" /* Declarations shared with jdphuff.c */
+
+
+/*
+ * Expanded entropy decoder object for Huffman decoding.
+ *
+ * The savable_state subrecord contains fields that change within an MCU,
+ * but must not be updated permanently until we complete the MCU.
+ */
+
+typedef struct {
+ int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
+} savable_state;
+
+/* This macro is to work around compilers with missing or broken
+ * structure assignment. You'll need to fix this code if you have
+ * such a compiler and you change MAX_COMPS_IN_SCAN.
+ */
+
+#ifndef NO_STRUCT_ASSIGN
+#define ASSIGN_STATE(dest,src) ((dest) = (src))
+#else
+#if MAX_COMPS_IN_SCAN == 4
+#define ASSIGN_STATE(dest,src) \
+ ((dest).last_dc_val[0] = (src).last_dc_val[0], \
+ (dest).last_dc_val[1] = (src).last_dc_val[1], \
+ (dest).last_dc_val[2] = (src).last_dc_val[2], \
+ (dest).last_dc_val[3] = (src).last_dc_val[3])
+#endif
+#endif
+
+
+typedef struct {
+ struct jpeg_entropy_decoder pub; /* public fields */
+
+ /* These fields are loaded into local variables at start of each MCU.
+ * In case of suspension, we exit WITHOUT updating them.
+ */
+ bitread_perm_state bitstate; /* Bit buffer at start of MCU */
+ savable_state saved; /* Other state at start of MCU */
+
+ /* These fields are NOT loaded into local working state. */
+ unsigned int restarts_to_go; /* MCUs left in this restart interval */
+
+ /* Pointers to derived tables (these workspaces have image lifespan) */
+ d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
+ d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
+} huff_entropy_decoder;
+
+typedef huff_entropy_decoder * huff_entropy_ptr;
+
+
+/*
+ * Initialize for a Huffman-compressed scan.
+ */
+
+METHODDEF void
+start_pass_huff_decoder (j_decompress_ptr cinfo)
+{
+ huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
+ int ci, dctbl, actbl;
+ jpeg_component_info * compptr;
+
+ /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
+ * This ought to be an error condition, but we make it a warning because
+ * there are some baseline files out there with all zeroes in these bytes.
+ */
+ if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
+ cinfo->Ah != 0 || cinfo->Al != 0)
+ WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ dctbl = compptr->dc_tbl_no;
+ actbl = compptr->ac_tbl_no;
+ /* Make sure requested tables are present */
+ if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS ||
+ cinfo->dc_huff_tbl_ptrs[dctbl] == NULL)
+ ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
+ if (actbl < 0 || actbl >= NUM_HUFF_TBLS ||
+ cinfo->ac_huff_tbl_ptrs[actbl] == NULL)
+ ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
+ /* Compute derived values for Huffman tables */
+ /* We may do this more than once for a table, but it's not expensive */
+ jpeg_make_d_derived_tbl(cinfo, cinfo->dc_huff_tbl_ptrs[dctbl],
+ & entropy->dc_derived_tbls[dctbl]);
+ jpeg_make_d_derived_tbl(cinfo, cinfo->ac_huff_tbl_ptrs[actbl],
+ & entropy->ac_derived_tbls[actbl]);
+ /* Initialize DC predictions to 0 */
+ entropy->saved.last_dc_val[ci] = 0;
+ }
+
+ /* Initialize bitread state variables */
+ entropy->bitstate.bits_left = 0;
+ entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
+ entropy->bitstate.printed_eod = FALSE;
+
+ /* Initialize restart counter */
+ entropy->restarts_to_go = cinfo->restart_interval;
+}
+
+
+/*
+ * Compute the derived values for a Huffman table.
+ * Note this is also used by jdphuff.c.
+ */
+
+GLOBAL void
+jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, JHUFF_TBL * htbl,
+ d_derived_tbl ** pdtbl)
+{
+ d_derived_tbl *dtbl;
+ int p, i, l, si;
+ int lookbits, ctr;
+ char huffsize[257];
+ unsigned int huffcode[257];
+ unsigned int code;
+
+ /* Allocate a workspace if we haven't already done so. */
+ if (*pdtbl == NULL)
+ *pdtbl = (d_derived_tbl *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(d_derived_tbl));
+ dtbl = *pdtbl;
+ dtbl->pub = htbl; /* fill in back link */
+
+ /* Figure C.1: make table of Huffman code length for each symbol */
+ /* Note that this is in code-length order. */
+
+ p = 0;
+ for (l = 1; l <= 16; l++) {
+ for (i = 1; i <= (int) htbl->bits[l]; i++)
+ huffsize[p++] = (char) l;
+ }
+ huffsize[p] = 0;
+
+ /* Figure C.2: generate the codes themselves */
+ /* Note that this is in code-length order. */
+
+ code = 0;
+ si = huffsize[0];
+ p = 0;
+ while (huffsize[p]) {
+ while (((int) huffsize[p]) == si) {
+ huffcode[p++] = code;
+ code++;
+ }
+ code <<= 1;
+ si++;
+ }
+
+ /* Figure F.15: generate decoding tables for bit-sequential decoding */
+
+ p = 0;
+ for (l = 1; l <= 16; l++) {
+ if (htbl->bits[l]) {
+ dtbl->valptr[l] = p; /* huffval[] index of 1st symbol of code length l */
+ dtbl->mincode[l] = huffcode[p]; /* minimum code of length l */
+ p += htbl->bits[l];
+ dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
+ } else {
+ dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
+ }
+ }
+ dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
+
+ /* Compute lookahead tables to speed up decoding.
+ * First we set all the table entries to 0, indicating "too long";
+ * then we iterate through the Huffman codes that are short enough and
+ * fill in all the entries that correspond to bit sequences starting
+ * with that code.
+ */
+
+ MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
+
+ p = 0;
+ for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
+ for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
+ /* l = current code's length, p = its index in huffcode[] & huffval[]. */
+ /* Generate left-justified code followed by all possible bit sequences */
+ lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
+ for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
+ dtbl->look_nbits[lookbits] = l;
+ dtbl->look_sym[lookbits] = htbl->huffval[p];
+ lookbits++;
+ }
+ }
+ }
+}
+
+
+/*
+ * Out-of-line code for bit fetching (shared with jdphuff.c).
+ * See jdhuff.h for info about usage.
+ * Note: current values of get_buffer and bits_left are passed as parameters,
+ * but are returned in the corresponding fields of the state struct.
+ *
+ * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
+ * of get_buffer to be used. (On machines with wider words, an even larger
+ * buffer could be used.) However, on some machines 32-bit shifts are
+ * quite slow and take time proportional to the number of places shifted.
+ * (This is true with most PC compilers, for instance.) In this case it may
+ * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
+ * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
+ */
+
+#ifdef SLOW_SHIFT_32
+#define MIN_GET_BITS 15 /* minimum allowable value */
+#else
+#define MIN_GET_BITS (BIT_BUF_SIZE-7)
+#endif
+
+
+GLOBAL boolean
+jpeg_fill_bit_buffer (bitread_working_state * state,
+ register bit_buf_type get_buffer, register int bits_left,
+ int nbits)
+/* Load up the bit buffer to a depth of at least nbits */
+{
+ /* Copy heavily used state fields into locals (hopefully registers) */
+ register const JOCTET * next_input_byte = state->next_input_byte;
+ register size_t bytes_in_buffer = state->bytes_in_buffer;
+ register int c;
+
+ /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
+ /* (It is assumed that no request will be for more than that many bits.) */
+
+ while (bits_left < MIN_GET_BITS) {
+ /* Attempt to read a byte */
+ if (state->unread_marker != 0)
+ goto no_more_data; /* can't advance past a marker */
+
+ if (bytes_in_buffer == 0) {
+ if (! (*state->cinfo->src->fill_input_buffer) (state->cinfo))
+ return FALSE;
+ next_input_byte = state->cinfo->src->next_input_byte;
+ bytes_in_buffer = state->cinfo->src->bytes_in_buffer;
+ }
+ bytes_in_buffer--;
+ c = GETJOCTET(*next_input_byte++);
+
+ /* If it's 0xFF, check and discard stuffed zero byte */
+ if (c == 0xFF) {
+ do {
+ if (bytes_in_buffer == 0) {
+ if (! (*state->cinfo->src->fill_input_buffer) (state->cinfo))
+ return FALSE;
+ next_input_byte = state->cinfo->src->next_input_byte;
+ bytes_in_buffer = state->cinfo->src->bytes_in_buffer;
+ }
+ bytes_in_buffer--;
+ c = GETJOCTET(*next_input_byte++);
+ } while (c == 0xFF);
+
+ if (c == 0) {
+ /* Found FF/00, which represents an FF data byte */
+ c = 0xFF;
+ } else {
+ /* Oops, it's actually a marker indicating end of compressed data. */
+ /* Better put it back for use later */
+ state->unread_marker = c;
+
+ no_more_data:
+ /* There should be enough bits still left in the data segment; */
+ /* if so, just break out of the outer while loop. */
+ if (bits_left >= nbits)
+ break;
+ /* Uh-oh. Report corrupted data to user and stuff zeroes into
+ * the data stream, so that we can produce some kind of image.
+ * Note that this code will be repeated for each byte demanded
+ * for the rest of the segment. We use a nonvolatile flag to ensure
+ * that only one warning message appears.
+ */
+ if (! *(state->printed_eod_ptr)) {
+ WARNMS(state->cinfo, JWRN_HIT_MARKER);
+ *(state->printed_eod_ptr) = TRUE;
+ }
+ c = 0; /* insert a zero byte into bit buffer */
+ }
+ }
+
+ /* OK, load c into get_buffer */
+ get_buffer = (get_buffer << 8) | c;
+ bits_left += 8;
+ }
+
+ /* Unload the local registers */
+ state->next_input_byte = next_input_byte;
+ state->bytes_in_buffer = bytes_in_buffer;
+ state->get_buffer = get_buffer;
+ state->bits_left = bits_left;
+
+ return TRUE;
+}
+
+
+/*
+ * Out-of-line code for Huffman code decoding.
+ * See jdhuff.h for info about usage.
+ */
+
+GLOBAL int
+jpeg_huff_decode (bitread_working_state * state,
+ register bit_buf_type get_buffer, register int bits_left,
+ d_derived_tbl * htbl, int min_bits)
+{
+ register int l = min_bits;
+ register INT32 code;
+
+ /* HUFF_DECODE has determined that the code is at least min_bits */
+ /* bits long, so fetch that many bits in one swoop. */
+
+ CHECK_BIT_BUFFER(*state, l, return -1);
+ code = GET_BITS(l);
+
+ /* Collect the rest of the Huffman code one bit at a time. */
+ /* This is per Figure F.16 in the JPEG spec. */
+
+ while (code > htbl->maxcode[l]) {
+ code <<= 1;
+ CHECK_BIT_BUFFER(*state, 1, return -1);
+ code |= GET_BITS(1);
+ l++;
+ }
+
+ /* Unload the local registers */
+ state->get_buffer = get_buffer;
+ state->bits_left = bits_left;
+
+ /* With garbage input we may reach the sentinel value l = 17. */
+
+ if (l > 16) {
+ WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
+ return 0; /* fake a zero as the safest result */
+ }
+
+ return htbl->pub->huffval[ htbl->valptr[l] +
+ ((int) (code - htbl->mincode[l])) ];
+}
+
+
+/*
+ * Figure F.12: extend sign bit.
+ * On some machines, a shift and add will be faster than a table lookup.
+ */
+
+#ifdef AVOID_TABLES
+
+#define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
+
+#else
+
+#define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
+
+static const int extend_test[16] = /* entry n is 2**(n-1) */
+ { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
+ 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
+
+static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
+ { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
+ ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
+ ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
+ ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
+
+#endif /* AVOID_TABLES */
+
+
+/*
+ * Check for a restart marker & resynchronize decoder.
+ * Returns FALSE if must suspend.
+ */
+
+LOCAL boolean
+process_restart (j_decompress_ptr cinfo)
+{
+ huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
+ int ci;
+
+ /* Throw away any unused bits remaining in bit buffer; */
+ /* include any full bytes in next_marker's count of discarded bytes */
+ cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
+ entropy->bitstate.bits_left = 0;
+
+ /* Advance past the RSTn marker */
+ if (! (*cinfo->marker->read_restart_marker) (cinfo))
+ return FALSE;
+
+ /* Re-initialize DC predictions to 0 */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++)
+ entropy->saved.last_dc_val[ci] = 0;
+
+ /* Reset restart counter */
+ entropy->restarts_to_go = cinfo->restart_interval;
+
+ /* Next segment can get another out-of-data warning */
+ entropy->bitstate.printed_eod = FALSE;
+
+ return TRUE;
+}
+
+
+/*
+ * Decode and return one MCU's worth of Huffman-compressed coefficients.
+ * The coefficients are reordered from zigzag order into natural array order,
+ * but are not dequantized.
+ *
+ * The i'th block of the MCU is stored into the block pointed to by
+ * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
+ * (Wholesale zeroing is usually a little faster than retail...)
+ *
+ * Returns FALSE if data source requested suspension. In that case no
+ * changes have been made to permanent state. (Exception: some output
+ * coefficients may already have been assigned. This is harmless for
+ * this module, since we'll just re-assign them on the next call.)
+ */
+
+METHODDEF boolean
+decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
+{
+ huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
+ register int s, k, r;
+ int blkn, ci;
+ JBLOCKROW block;
+ BITREAD_STATE_VARS;
+ savable_state state;
+ d_derived_tbl * dctbl;
+ d_derived_tbl * actbl;
+ jpeg_component_info * compptr;
+
+ /* Process restart marker if needed; may have to suspend */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0)
+ if (! process_restart(cinfo))
+ return FALSE;
+ }
+
+ /* Load up working state */
+ BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
+ ASSIGN_STATE(state, entropy->saved);
+
+ /* Outer loop handles each block in the MCU */
+
+ for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
+ block = MCU_data[blkn];
+ ci = cinfo->MCU_membership[blkn];
+ compptr = cinfo->cur_comp_info[ci];
+ dctbl = entropy->dc_derived_tbls[compptr->dc_tbl_no];
+ actbl = entropy->ac_derived_tbls[compptr->ac_tbl_no];
+
+ /* Decode a single block's worth of coefficients */
+
+ /* Section F.2.2.1: decode the DC coefficient difference */
+ HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
+ if (s) {
+ CHECK_BIT_BUFFER(br_state, s, return FALSE);
+ r = GET_BITS(s);
+ s = HUFF_EXTEND(r, s);
+ }
+
+ /* Shortcut if component's values are not interesting */
+ if (! compptr->component_needed)
+ goto skip_ACs;
+
+ /* Convert DC difference to actual value, update last_dc_val */
+ s += state.last_dc_val[ci];
+ state.last_dc_val[ci] = s;
+ /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
+ (*block)[0] = (JCOEF) s;
+
+ /* Do we need to decode the AC coefficients for this component? */
+ if (compptr->DCT_scaled_size > 1) {
+
+ /* Section F.2.2.2: decode the AC coefficients */
+ /* Since zeroes are skipped, output area must be cleared beforehand */
+ for (k = 1; k < DCTSIZE2; k++) {
+ HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
+
+ r = s >> 4;
+ s &= 15;
+
+ if (s) {
+ k += r;
+ CHECK_BIT_BUFFER(br_state, s, return FALSE);
+ r = GET_BITS(s);
+ s = HUFF_EXTEND(r, s);
+ /* Output coefficient in natural (dezigzagged) order.
+ * Note: the extra entries in jpeg_natural_order[] will save us
+ * if k >= DCTSIZE2, which could happen if the data is corrupted.
+ */
+ (*block)[jpeg_natural_order[k]] = (JCOEF) s;
+ } else {
+ if (r != 15)
+ break;
+ k += 15;
+ }
+ }
+
+ } else {
+skip_ACs:
+
+ /* Section F.2.2.2: decode the AC coefficients */
+ /* In this path we just discard the values */
+ for (k = 1; k < DCTSIZE2; k++) {
+ HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
+
+ r = s >> 4;
+ s &= 15;
+
+ if (s) {
+ k += r;
+ CHECK_BIT_BUFFER(br_state, s, return FALSE);
+ DROP_BITS(s);
+ } else {
+ if (r != 15)
+ break;
+ k += 15;
+ }
+ }
+
+ }
+ }
+
+ /* Completed MCU, so update state */
+ BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
+ ASSIGN_STATE(entropy->saved, state);
+
+ /* Account for restart interval (no-op if not using restarts) */
+ entropy->restarts_to_go--;
+
+ return TRUE;
+}
+
+
+/*
+ * Module initialization routine for Huffman entropy decoding.
+ */
+
+GLOBAL void
+jinit_huff_decoder (j_decompress_ptr cinfo)
+{
+ huff_entropy_ptr entropy;
+ int i;
+
+ entropy = (huff_entropy_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(huff_entropy_decoder));
+ cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
+ entropy->pub.start_pass = start_pass_huff_decoder;
+ entropy->pub.decode_mcu = decode_mcu;
+
+ /* Mark tables unallocated */
+ for (i = 0; i < NUM_HUFF_TBLS; i++) {
+ entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
+ }
+}
diff --git a/code/jpeg-6/jdhuff.h b/code/jpeg-6/jdhuff.h
new file mode 100755
index 0000000..65f3054
--- /dev/null
+++ b/code/jpeg-6/jdhuff.h
@@ -0,0 +1,202 @@
+/*
+ * jdhuff.h
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains declarations for Huffman entropy decoding routines
+ * that are shared between the sequential decoder (jdhuff.c) and the
+ * progressive decoder (jdphuff.c). No other modules need to see these.
+ */
+
+/* Short forms of external names for systems with brain-damaged linkers. */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jpeg_make_d_derived_tbl jMkDDerived
+#define jpeg_fill_bit_buffer jFilBitBuf
+#define jpeg_huff_decode jHufDecode
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+
+/* Derived data constructed for each Huffman table */
+
+#define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
+
+typedef struct {
+ /* Basic tables: (element [0] of each array is unused) */
+ INT32 mincode[17]; /* smallest code of length k */
+ INT32 maxcode[18]; /* largest code of length k (-1 if none) */
+ /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
+ int valptr[17]; /* huffval[] index of 1st symbol of length k */
+
+ /* Link to public Huffman table (needed only in jpeg_huff_decode) */
+ JHUFF_TBL *pub;
+
+ /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
+ * the input data stream. If the next Huffman code is no more
+ * than HUFF_LOOKAHEAD bits long, we can obtain its length and
+ * the corresponding symbol directly from these tables.
+ */
+ int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
+ UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
+} d_derived_tbl;
+
+/* Expand a Huffman table definition into the derived format */
+EXTERN void jpeg_make_d_derived_tbl JPP((j_decompress_ptr cinfo,
+ JHUFF_TBL * htbl, d_derived_tbl ** pdtbl));
+
+
+/*
+ * Fetching the next N bits from the input stream is a time-critical operation
+ * for the Huffman decoders. We implement it with a combination of inline
+ * macros and out-of-line subroutines. Note that N (the number of bits
+ * demanded at one time) never exceeds 15 for JPEG use.
+ *
+ * We read source bytes into get_buffer and dole out bits as needed.
+ * If get_buffer already contains enough bits, they are fetched in-line
+ * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
+ * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
+ * as full as possible (not just to the number of bits needed; this
+ * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
+ * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
+ * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
+ * at least the requested number of bits --- dummy zeroes are inserted if
+ * necessary.
+ */
+
+typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
+#define BIT_BUF_SIZE 32 /* size of buffer in bits */
+
+/* If long is > 32 bits on your machine, and shifting/masking longs is
+ * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
+ * appropriately should be a win. Unfortunately we can't do this with
+ * something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
+ * because not all machines measure sizeof in 8-bit bytes.
+ */
+
+typedef struct { /* Bitreading state saved across MCUs */
+ bit_buf_type get_buffer; /* current bit-extraction buffer */
+ int bits_left; /* # of unused bits in it */
+ boolean printed_eod; /* flag to suppress multiple warning msgs */
+} bitread_perm_state;
+
+typedef struct { /* Bitreading working state within an MCU */
+ /* current data source state */
+ const JOCTET * next_input_byte; /* => next byte to read from source */
+ size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
+ int unread_marker; /* nonzero if we have hit a marker */
+ /* bit input buffer --- note these values are kept in register variables,
+ * not in this struct, inside the inner loops.
+ */
+ bit_buf_type get_buffer; /* current bit-extraction buffer */
+ int bits_left; /* # of unused bits in it */
+ /* pointers needed by jpeg_fill_bit_buffer */
+ j_decompress_ptr cinfo; /* back link to decompress master record */
+ boolean * printed_eod_ptr; /* => flag in permanent state */
+} bitread_working_state;
+
+/* Macros to declare and load/save bitread local variables. */
+#define BITREAD_STATE_VARS \
+ register bit_buf_type get_buffer; \
+ register int bits_left; \
+ bitread_working_state br_state
+
+#define BITREAD_LOAD_STATE(cinfop,permstate) \
+ br_state.cinfo = cinfop; \
+ br_state.next_input_byte = cinfop->src->next_input_byte; \
+ br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
+ br_state.unread_marker = cinfop->unread_marker; \
+ get_buffer = permstate.get_buffer; \
+ bits_left = permstate.bits_left; \
+ br_state.printed_eod_ptr = & permstate.printed_eod
+
+#define BITREAD_SAVE_STATE(cinfop,permstate) \
+ cinfop->src->next_input_byte = br_state.next_input_byte; \
+ cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
+ cinfop->unread_marker = br_state.unread_marker; \
+ permstate.get_buffer = get_buffer; \
+ permstate.bits_left = bits_left
+
+/*
+ * These macros provide the in-line portion of bit fetching.
+ * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
+ * before using GET_BITS, PEEK_BITS, or DROP_BITS.
+ * The variables get_buffer and bits_left are assumed to be locals,
+ * but the state struct might not be (jpeg_huff_decode needs this).
+ * CHECK_BIT_BUFFER(state,n,action);
+ * Ensure there are N bits in get_buffer; if suspend, take action.
+ * val = GET_BITS(n);
+ * Fetch next N bits.
+ * val = PEEK_BITS(n);
+ * Fetch next N bits without removing them from the buffer.
+ * DROP_BITS(n);
+ * Discard next N bits.
+ * The value N should be a simple variable, not an expression, because it
+ * is evaluated multiple times.
+ */
+
+#define CHECK_BIT_BUFFER(state,nbits,action) \
+ { if (bits_left < (nbits)) { \
+ if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
+ { action; } \
+ get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
+
+#define GET_BITS(nbits) \
+ (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
+
+#define PEEK_BITS(nbits) \
+ (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
+
+#define DROP_BITS(nbits) \
+ (bits_left -= (nbits))
+
+/* Load up the bit buffer to a depth of at least nbits */
+EXTERN boolean jpeg_fill_bit_buffer JPP((bitread_working_state * state,
+ register bit_buf_type get_buffer, register int bits_left,
+ int nbits));
+
+
+/*
+ * Code for extracting next Huffman-coded symbol from input bit stream.
+ * Again, this is time-critical and we make the main paths be macros.
+ *
+ * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
+ * without looping. Usually, more than 95% of the Huffman codes will be 8
+ * or fewer bits long. The few overlength codes are handled with a loop,
+ * which need not be inline code.
+ *
+ * Notes about the HUFF_DECODE macro:
+ * 1. Near the end of the data segment, we may fail to get enough bits
+ * for a lookahead. In that case, we do it the hard way.
+ * 2. If the lookahead table contains no entry, the next code must be
+ * more than HUFF_LOOKAHEAD bits long.
+ * 3. jpeg_huff_decode returns -1 if forced to suspend.
+ */
+
+#define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
+{ register int nb, look; \
+ if (bits_left < HUFF_LOOKAHEAD) { \
+ if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
+ get_buffer = state.get_buffer; bits_left = state.bits_left; \
+ if (bits_left < HUFF_LOOKAHEAD) { \
+ nb = 1; goto slowlabel; \
+ } \
+ } \
+ look = PEEK_BITS(HUFF_LOOKAHEAD); \
+ if ((nb = htbl->look_nbits[look]) != 0) { \
+ DROP_BITS(nb); \
+ result = htbl->look_sym[look]; \
+ } else { \
+ nb = HUFF_LOOKAHEAD+1; \
+slowlabel: \
+ if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
+ { failaction; } \
+ get_buffer = state.get_buffer; bits_left = state.bits_left; \
+ } \
+}
+
+/* Out-of-line case for Huffman code fetching */
+EXTERN int jpeg_huff_decode JPP((bitread_working_state * state,
+ register bit_buf_type get_buffer, register int bits_left,
+ d_derived_tbl * htbl, int min_bits));
diff --git a/code/jpeg-6/jdinput.c b/code/jpeg-6/jdinput.c
new file mode 100755
index 0000000..5b4774f
--- /dev/null
+++ b/code/jpeg-6/jdinput.c
@@ -0,0 +1,381 @@
+/*
+ * jdinput.c
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains input control logic for the JPEG decompressor.
+ * These routines are concerned with controlling the decompressor's input
+ * processing (marker reading and coefficient decoding). The actual input
+ * reading is done in jdmarker.c, jdhuff.c, and jdphuff.c.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Private state */
+
+typedef struct {
+ struct jpeg_input_controller pub; /* public fields */
+
+ boolean inheaders; /* TRUE until first SOS is reached */
+} my_input_controller;
+
+typedef my_input_controller * my_inputctl_ptr;
+
+
+/* Forward declarations */
+METHODDEF int consume_markers JPP((j_decompress_ptr cinfo));
+
+
+/*
+ * Routines to calculate various quantities related to the size of the image.
+ */
+
+LOCAL void
+initial_setup (j_decompress_ptr cinfo)
+/* Called once, when first SOS marker is reached */
+{
+ int ci;
+ jpeg_component_info *compptr;
+
+ /* Make sure image isn't bigger than I can handle */
+ if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
+ (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
+ ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
+
+ /* For now, precision must match compiled-in value... */
+ if (cinfo->data_precision != BITS_IN_JSAMPLE)
+ ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
+
+ /* Check that number of components won't exceed internal array sizes */
+ if (cinfo->num_components > MAX_COMPONENTS)
+ ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
+ MAX_COMPONENTS);
+
+ /* Compute maximum sampling factors; check factor validity */
+ cinfo->max_h_samp_factor = 1;
+ cinfo->max_v_samp_factor = 1;
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
+ compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
+ ERREXIT(cinfo, JERR_BAD_SAMPLING);
+ cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
+ compptr->h_samp_factor);
+ cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
+ compptr->v_samp_factor);
+ }
+
+ /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
+ * In the full decompressor, this will be overridden by jdmaster.c;
+ * but in the transcoder, jdmaster.c is not used, so we must do it here.
+ */
+ cinfo->min_DCT_scaled_size = DCTSIZE;
+
+ /* Compute dimensions of components */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ compptr->DCT_scaled_size = DCTSIZE;
+ /* Size in DCT blocks */
+ compptr->width_in_blocks = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
+ (long) (cinfo->max_h_samp_factor * DCTSIZE));
+ compptr->height_in_blocks = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
+ (long) (cinfo->max_v_samp_factor * DCTSIZE));
+ /* downsampled_width and downsampled_height will also be overridden by
+ * jdmaster.c if we are doing full decompression. The transcoder library
+ * doesn't use these values, but the calling application might.
+ */
+ /* Size in samples */
+ compptr->downsampled_width = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
+ (long) cinfo->max_h_samp_factor);
+ compptr->downsampled_height = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
+ (long) cinfo->max_v_samp_factor);
+ /* Mark component needed, until color conversion says otherwise */
+ compptr->component_needed = TRUE;
+ /* Mark no quantization table yet saved for component */
+ compptr->quant_table = NULL;
+ }
+
+ /* Compute number of fully interleaved MCU rows. */
+ cinfo->total_iMCU_rows = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height,
+ (long) (cinfo->max_v_samp_factor*DCTSIZE));
+
+ /* Decide whether file contains multiple scans */
+ if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
+ cinfo->inputctl->has_multiple_scans = TRUE;
+ else
+ cinfo->inputctl->has_multiple_scans = FALSE;
+}
+
+
+LOCAL void
+per_scan_setup (j_decompress_ptr cinfo)
+/* Do computations that are needed before processing a JPEG scan */
+/* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
+{
+ int ci, mcublks, tmp;
+ jpeg_component_info *compptr;
+
+ if (cinfo->comps_in_scan == 1) {
+
+ /* Noninterleaved (single-component) scan */
+ compptr = cinfo->cur_comp_info[0];
+
+ /* Overall image size in MCUs */
+ cinfo->MCUs_per_row = compptr->width_in_blocks;
+ cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
+
+ /* For noninterleaved scan, always one block per MCU */
+ compptr->MCU_width = 1;
+ compptr->MCU_height = 1;
+ compptr->MCU_blocks = 1;
+ compptr->MCU_sample_width = compptr->DCT_scaled_size;
+ compptr->last_col_width = 1;
+ /* For noninterleaved scans, it is convenient to define last_row_height
+ * as the number of block rows present in the last iMCU row.
+ */
+ tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
+ if (tmp == 0) tmp = compptr->v_samp_factor;
+ compptr->last_row_height = tmp;
+
+ /* Prepare array describing MCU composition */
+ cinfo->blocks_in_MCU = 1;
+ cinfo->MCU_membership[0] = 0;
+
+ } else {
+
+ /* Interleaved (multi-component) scan */
+ if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
+ ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
+ MAX_COMPS_IN_SCAN);
+
+ /* Overall image size in MCUs */
+ cinfo->MCUs_per_row = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width,
+ (long) (cinfo->max_h_samp_factor*DCTSIZE));
+ cinfo->MCU_rows_in_scan = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height,
+ (long) (cinfo->max_v_samp_factor*DCTSIZE));
+
+ cinfo->blocks_in_MCU = 0;
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ /* Sampling factors give # of blocks of component in each MCU */
+ compptr->MCU_width = compptr->h_samp_factor;
+ compptr->MCU_height = compptr->v_samp_factor;
+ compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
+ compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
+ /* Figure number of non-dummy blocks in last MCU column & row */
+ tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
+ if (tmp == 0) tmp = compptr->MCU_width;
+ compptr->last_col_width = tmp;
+ tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
+ if (tmp == 0) tmp = compptr->MCU_height;
+ compptr->last_row_height = tmp;
+ /* Prepare array describing MCU composition */
+ mcublks = compptr->MCU_blocks;
+ if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
+ ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
+ while (mcublks-- > 0) {
+ cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
+ }
+ }
+
+ }
+}
+
+
+/*
+ * Save away a copy of the Q-table referenced by each component present
+ * in the current scan, unless already saved during a prior scan.
+ *
+ * In a multiple-scan JPEG file, the encoder could assign different components
+ * the same Q-table slot number, but change table definitions between scans
+ * so that each component uses a different Q-table. (The IJG encoder is not
+ * currently capable of doing this, but other encoders might.) Since we want
+ * to be able to dequantize all the components at the end of the file, this
+ * means that we have to save away the table actually used for each component.
+ * We do this by copying the table at the start of the first scan containing
+ * the component.
+ * The JPEG spec prohibits the encoder from changing the contents of a Q-table
+ * slot between scans of a component using that slot. If the encoder does so
+ * anyway, this decoder will simply use the Q-table values that were current
+ * at the start of the first scan for the component.
+ *
+ * The decompressor output side looks only at the saved quant tables,
+ * not at the current Q-table slots.
+ */
+
+LOCAL void
+latch_quant_tables (j_decompress_ptr cinfo)
+{
+ int ci, qtblno;
+ jpeg_component_info *compptr;
+ JQUANT_TBL * qtbl;
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ /* No work if we already saved Q-table for this component */
+ if (compptr->quant_table != NULL)
+ continue;
+ /* Make sure specified quantization table is present */
+ qtblno = compptr->quant_tbl_no;
+ if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
+ cinfo->quant_tbl_ptrs[qtblno] == NULL)
+ ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
+ /* OK, save away the quantization table */
+ qtbl = (JQUANT_TBL *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(JQUANT_TBL));
+ MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
+ compptr->quant_table = qtbl;
+ }
+}
+
+
+/*
+ * Initialize the input modules to read a scan of compressed data.
+ * The first call to this is done by jdmaster.c after initializing
+ * the entire decompressor (during jpeg_start_decompress).
+ * Subsequent calls come from consume_markers, below.
+ */
+
+METHODDEF void
+start_input_pass (j_decompress_ptr cinfo)
+{
+ per_scan_setup(cinfo);
+ latch_quant_tables(cinfo);
+ (*cinfo->entropy->start_pass) (cinfo);
+ (*cinfo->coef->start_input_pass) (cinfo);
+ cinfo->inputctl->consume_input = cinfo->coef->consume_data;
+}
+
+
+/*
+ * Finish up after inputting a compressed-data scan.
+ * This is called by the coefficient controller after it's read all
+ * the expected data of the scan.
+ */
+
+METHODDEF void
+finish_input_pass (j_decompress_ptr cinfo)
+{
+ cinfo->inputctl->consume_input = consume_markers;
+}
+
+
+/*
+ * Read JPEG markers before, between, or after compressed-data scans.
+ * Change state as necessary when a new scan is reached.
+ * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
+ *
+ * The consume_input method pointer points either here or to the
+ * coefficient controller's consume_data routine, depending on whether
+ * we are reading a compressed data segment or inter-segment markers.
+ */
+
+METHODDEF int
+consume_markers (j_decompress_ptr cinfo)
+{
+ my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
+ int val;
+
+ if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
+ return JPEG_REACHED_EOI;
+
+ val = (*cinfo->marker->read_markers) (cinfo);
+
+ switch (val) {
+ case JPEG_REACHED_SOS: /* Found SOS */
+ if (inputctl->inheaders) { /* 1st SOS */
+ initial_setup(cinfo);
+ inputctl->inheaders = FALSE;
+ /* Note: start_input_pass must be called by jdmaster.c
+ * before any more input can be consumed. jdapi.c is
+ * responsible for enforcing this sequencing.
+ */
+ } else { /* 2nd or later SOS marker */
+ if (! inputctl->pub.has_multiple_scans)
+ ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
+ start_input_pass(cinfo);
+ }
+ break;
+ case JPEG_REACHED_EOI: /* Found EOI */
+ inputctl->pub.eoi_reached = TRUE;
+ if (inputctl->inheaders) { /* Tables-only datastream, apparently */
+ if (cinfo->marker->saw_SOF)
+ ERREXIT(cinfo, JERR_SOF_NO_SOS);
+ } else {
+ /* Prevent infinite loop in coef ctlr's decompress_data routine
+ * if user set output_scan_number larger than number of scans.
+ */
+ if (cinfo->output_scan_number > cinfo->input_scan_number)
+ cinfo->output_scan_number = cinfo->input_scan_number;
+ }
+ break;
+ case JPEG_SUSPENDED:
+ break;
+ }
+
+ return val;
+}
+
+
+/*
+ * Reset state to begin a fresh datastream.
+ */
+
+METHODDEF void
+reset_input_controller (j_decompress_ptr cinfo)
+{
+ my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
+
+ inputctl->pub.consume_input = consume_markers;
+ inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
+ inputctl->pub.eoi_reached = FALSE;
+ inputctl->inheaders = TRUE;
+ /* Reset other modules */
+ (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
+ (*cinfo->marker->reset_marker_reader) (cinfo);
+ /* Reset progression state -- would be cleaner if entropy decoder did this */
+ cinfo->coef_bits = NULL;
+}
+
+
+/*
+ * Initialize the input controller module.
+ * This is called only once, when the decompression object is created.
+ */
+
+GLOBAL void
+jinit_input_controller (j_decompress_ptr cinfo)
+{
+ my_inputctl_ptr inputctl;
+
+ /* Create subobject in permanent pool */
+ inputctl = (my_inputctl_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ SIZEOF(my_input_controller));
+ cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
+ /* Initialize method pointers */
+ inputctl->pub.consume_input = consume_markers;
+ inputctl->pub.reset_input_controller = reset_input_controller;
+ inputctl->pub.start_input_pass = start_input_pass;
+ inputctl->pub.finish_input_pass = finish_input_pass;
+ /* Initialize state: can't use reset_input_controller since we don't
+ * want to try to reset other modules yet.
+ */
+ inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
+ inputctl->pub.eoi_reached = FALSE;
+ inputctl->inheaders = TRUE;
+}
diff --git a/code/jpeg-6/jdmainct.c b/code/jpeg-6/jdmainct.c
new file mode 100755
index 0000000..7059cdf
--- /dev/null
+++ b/code/jpeg-6/jdmainct.c
@@ -0,0 +1,520 @@
+/*
+ * jdmainct.c
+ *
+ * Copyright (C) 1994-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the main buffer controller for decompression.
+ * The main buffer lies between the JPEG decompressor proper and the
+ * post-processor; it holds downsampled data in the JPEG colorspace.
+ *
+ * Note that this code is bypassed in raw-data mode, since the application
+ * supplies the equivalent of the main buffer in that case.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/*
+ * In the current system design, the main buffer need never be a full-image
+ * buffer; any full-height buffers will be found inside the coefficient or
+ * postprocessing controllers. Nonetheless, the main controller is not
+ * trivial. Its responsibility is to provide context rows for upsampling/
+ * rescaling, and doing this in an efficient fashion is a bit tricky.
+ *
+ * Postprocessor input data is counted in "row groups". A row group
+ * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
+ * sample rows of each component. (We require DCT_scaled_size values to be
+ * chosen such that these numbers are integers. In practice DCT_scaled_size
+ * values will likely be powers of two, so we actually have the stronger
+ * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
+ * Upsampling will typically produce max_v_samp_factor pixel rows from each
+ * row group (times any additional scale factor that the upsampler is
+ * applying).
+ *
+ * The coefficient controller will deliver data to us one iMCU row at a time;
+ * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
+ * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
+ * to one row of MCUs when the image is fully interleaved.) Note that the
+ * number of sample rows varies across components, but the number of row
+ * groups does not. Some garbage sample rows may be included in the last iMCU
+ * row at the bottom of the image.
+ *
+ * Depending on the vertical scaling algorithm used, the upsampler may need
+ * access to the sample row(s) above and below its current input row group.
+ * The upsampler is required to set need_context_rows TRUE at global selection
+ * time if so. When need_context_rows is FALSE, this controller can simply
+ * obtain one iMCU row at a time from the coefficient controller and dole it
+ * out as row groups to the postprocessor.
+ *
+ * When need_context_rows is TRUE, this controller guarantees that the buffer
+ * passed to postprocessing contains at least one row group's worth of samples
+ * above and below the row group(s) being processed. Note that the context
+ * rows "above" the first passed row group appear at negative row offsets in
+ * the passed buffer. At the top and bottom of the image, the required
+ * context rows are manufactured by duplicating the first or last real sample
+ * row; this avoids having special cases in the upsampling inner loops.
+ *
+ * The amount of context is fixed at one row group just because that's a
+ * convenient number for this controller to work with. The existing
+ * upsamplers really only need one sample row of context. An upsampler
+ * supporting arbitrary output rescaling might wish for more than one row
+ * group of context when shrinking the image; tough, we don't handle that.
+ * (This is justified by the assumption that downsizing will be handled mostly
+ * by adjusting the DCT_scaled_size values, so that the actual scale factor at
+ * the upsample step needn't be much less than one.)
+ *
+ * To provide the desired context, we have to retain the last two row groups
+ * of one iMCU row while reading in the next iMCU row. (The last row group
+ * can't be processed until we have another row group for its below-context,
+ * and so we have to save the next-to-last group too for its above-context.)
+ * We could do this most simply by copying data around in our buffer, but
+ * that'd be very slow. We can avoid copying any data by creating a rather
+ * strange pointer structure. Here's how it works. We allocate a workspace
+ * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
+ * of row groups per iMCU row). We create two sets of redundant pointers to
+ * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
+ * pointer lists look like this:
+ * M+1 M-1
+ * master pointer --> 0 master pointer --> 0
+ * 1 1
+ * ... ...
+ * M-3 M-3
+ * M-2 M
+ * M-1 M+1
+ * M M-2
+ * M+1 M-1
+ * 0 0
+ * We read alternate iMCU rows using each master pointer; thus the last two
+ * row groups of the previous iMCU row remain un-overwritten in the workspace.
+ * The pointer lists are set up so that the required context rows appear to
+ * be adjacent to the proper places when we pass the pointer lists to the
+ * upsampler.
+ *
+ * The above pictures describe the normal state of the pointer lists.
+ * At top and bottom of the image, we diddle the pointer lists to duplicate
+ * the first or last sample row as necessary (this is cheaper than copying
+ * sample rows around).
+ *
+ * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
+ * situation each iMCU row provides only one row group so the buffering logic
+ * must be different (eg, we must read two iMCU rows before we can emit the
+ * first row group). For now, we simply do not support providing context
+ * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
+ * be worth providing --- if someone wants a 1/8th-size preview, they probably
+ * want it quick and dirty, so a context-free upsampler is sufficient.
+ */
+
+
+/* Private buffer controller object */
+
+typedef struct {
+ struct jpeg_d_main_controller pub; /* public fields */
+
+ /* Pointer to allocated workspace (M or M+2 row groups). */
+ JSAMPARRAY buffer[MAX_COMPONENTS];
+
+ boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
+ JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
+
+ /* Remaining fields are only used in the context case. */
+
+ /* These are the master pointers to the funny-order pointer lists. */
+ JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
+
+ int whichptr; /* indicates which pointer set is now in use */
+ int context_state; /* process_data state machine status */
+ JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
+ JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
+} my_main_controller;
+
+typedef my_main_controller * my_main_ptr;
+
+/* context_state values: */
+#define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
+#define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
+#define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
+
+
+/* Forward declarations */
+METHODDEF void process_data_simple_main
+ JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
+ JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
+METHODDEF void process_data_context_main
+ JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
+ JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
+#ifdef QUANT_2PASS_SUPPORTED
+METHODDEF void process_data_crank_post
+ JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
+ JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
+#endif
+
+
+LOCAL void
+alloc_funny_pointers (j_decompress_ptr cinfo)
+/* Allocate space for the funny pointer lists.
+ * This is done only once, not once per pass.
+ */
+{
+ // bk001204 - no use main
+ my_main_ptr jmain = (my_main_ptr) cinfo->main;
+ int ci, rgroup;
+ int M = cinfo->min_DCT_scaled_size;
+ jpeg_component_info *compptr;
+ JSAMPARRAY xbuf;
+
+ /* Get top-level space for component array pointers.
+ * We alloc both arrays with one call to save a few cycles.
+ */
+ jmain->xbuffer[0] = (JSAMPIMAGE)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
+ jmain->xbuffer[1] = jmain->xbuffer[0] + cinfo->num_components;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
+ cinfo->min_DCT_scaled_size; /* height of a row group of component */
+ /* Get space for pointer lists --- M+4 row groups in each list.
+ * We alloc both pointer lists with one call to save a few cycles.
+ */
+ xbuf = (JSAMPARRAY)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
+ xbuf += rgroup; /* want one row group at negative offsets */
+ jmain->xbuffer[0][ci] = xbuf;
+ xbuf += rgroup * (M + 4);
+ jmain->xbuffer[1][ci] = xbuf;
+ }
+}
+
+
+LOCAL void
+make_funny_pointers (j_decompress_ptr cinfo)
+/* Create the funny pointer lists discussed in the comments above.
+ * The actual workspace is already allocated (in main->buffer),
+ * and the space for the pointer lists is allocated too.
+ * This routine just fills in the curiously ordered lists.
+ * This will be repeated at the beginning of each pass.
+ */
+{
+ // bk001204 - no use main
+ my_main_ptr jmain = (my_main_ptr) cinfo->main;
+ int ci, i, rgroup;
+ int M = cinfo->min_DCT_scaled_size;
+ jpeg_component_info *compptr;
+ JSAMPARRAY buf, xbuf0, xbuf1;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
+ cinfo->min_DCT_scaled_size; /* height of a row group of component */
+ xbuf0 = jmain->xbuffer[0][ci];
+ xbuf1 = jmain->xbuffer[1][ci];
+ /* First copy the workspace pointers as-is */
+ buf = jmain->buffer[ci];
+ for (i = 0; i < rgroup * (M + 2); i++) {
+ xbuf0[i] = xbuf1[i] = buf[i];
+ }
+ /* In the second list, put the last four row groups in swapped order */
+ for (i = 0; i < rgroup * 2; i++) {
+ xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
+ xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
+ }
+ /* The wraparound pointers at top and bottom will be filled later
+ * (see set_wraparound_pointers, below). Initially we want the "above"
+ * pointers to duplicate the first actual data line. This only needs
+ * to happen in xbuffer[0].
+ */
+ for (i = 0; i < rgroup; i++) {
+ xbuf0[i - rgroup] = xbuf0[0];
+ }
+ }
+}
+
+
+LOCAL void
+set_wraparound_pointers (j_decompress_ptr cinfo)
+/* Set up the "wraparound" pointers at top and bottom of the pointer lists.
+ * This changes the pointer list state from top-of-image to the normal state.
+ */
+{
+ // bk001204 - no use main
+ my_main_ptr jmain = (my_main_ptr) cinfo->main;
+ int ci, i, rgroup;
+ int M = cinfo->min_DCT_scaled_size;
+ jpeg_component_info *compptr;
+ JSAMPARRAY xbuf0, xbuf1;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
+ cinfo->min_DCT_scaled_size; /* height of a row group of component */
+ xbuf0 = jmain->xbuffer[0][ci];
+ xbuf1 = jmain->xbuffer[1][ci];
+ for (i = 0; i < rgroup; i++) {
+ xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
+ xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
+ xbuf0[rgroup*(M+2) + i] = xbuf0[i];
+ xbuf1[rgroup*(M+2) + i] = xbuf1[i];
+ }
+ }
+}
+
+
+LOCAL void
+set_bottom_pointers (j_decompress_ptr cinfo)
+/* Change the pointer lists to duplicate the last sample row at the bottom
+ * of the image. whichptr indicates which xbuffer holds the final iMCU row.
+ * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
+ */
+{
+ // bk001204 - no use main
+ my_main_ptr jmain = (my_main_ptr) cinfo->main;
+ int ci, i, rgroup, iMCUheight, rows_left;
+ jpeg_component_info *compptr;
+ JSAMPARRAY xbuf;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Count sample rows in one iMCU row and in one row group */
+ iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
+ rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
+ /* Count nondummy sample rows remaining for this component */
+ rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
+ if (rows_left == 0) rows_left = iMCUheight;
+ /* Count nondummy row groups. Should get same answer for each component,
+ * so we need only do it once.
+ */
+ if (ci == 0) {
+ jmain->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
+ }
+ /* Duplicate the last real sample row rgroup*2 times; this pads out the
+ * last partial rowgroup and ensures at least one full rowgroup of context.
+ */
+ xbuf = jmain->xbuffer[jmain->whichptr][ci];
+ for (i = 0; i < rgroup * 2; i++) {
+ xbuf[rows_left + i] = xbuf[rows_left-1];
+ }
+ }
+}
+
+
+/*
+ * Initialize for a processing pass.
+ */
+
+METHODDEF void
+start_pass_main (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
+{
+ // bk001204 - no use main
+ my_main_ptr jmain = (my_main_ptr) cinfo->main;
+
+ switch (pass_mode) {
+ case JBUF_PASS_THRU:
+ if (cinfo->upsample->need_context_rows) {
+ jmain->pub.process_data = process_data_context_main;
+ make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
+ jmain->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
+ jmain->context_state = CTX_PREPARE_FOR_IMCU;
+ jmain->iMCU_row_ctr = 0;
+ } else {
+ /* Simple case with no context needed */
+ jmain->pub.process_data = process_data_simple_main;
+ }
+ jmain->buffer_full = FALSE; /* Mark buffer empty */
+ jmain->rowgroup_ctr = 0;
+ break;
+#ifdef QUANT_2PASS_SUPPORTED
+ case JBUF_CRANK_DEST:
+ /* For last pass of 2-pass quantization, just crank the postprocessor */
+ jmain->pub.process_data = process_data_crank_post;
+ break;
+#endif
+ default:
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ break;
+ }
+}
+
+
+/*
+ * Process some data.
+ * This handles the simple case where no context is required.
+ */
+
+METHODDEF void
+process_data_simple_main (j_decompress_ptr cinfo,
+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+{
+ // bk001204 - no use main
+ my_main_ptr jmain = (my_main_ptr) cinfo->main;
+ JDIMENSION rowgroups_avail;
+
+ /* Read input data if we haven't filled the main buffer yet */
+ if (! jmain->buffer_full) {
+ if (! (*cinfo->coef->decompress_data) (cinfo, jmain->buffer))
+ return; /* suspension forced, can do nothing more */
+ jmain->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
+ }
+
+ /* There are always min_DCT_scaled_size row groups in an iMCU row. */
+ rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
+ /* Note: at the bottom of the image, we may pass extra garbage row groups
+ * to the postprocessor. The postprocessor has to check for bottom
+ * of image anyway (at row resolution), so no point in us doing it too.
+ */
+
+ /* Feed the postprocessor */
+ (*cinfo->post->post_process_data) (cinfo, jmain->buffer,
+ &jmain->rowgroup_ctr, rowgroups_avail,
+ output_buf, out_row_ctr, out_rows_avail);
+
+ /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
+ if (jmain->rowgroup_ctr >= rowgroups_avail) {
+ jmain->buffer_full = FALSE;
+ jmain->rowgroup_ctr = 0;
+ }
+}
+
+
+/*
+ * Process some data.
+ * This handles the case where context rows must be provided.
+ */
+
+METHODDEF void
+process_data_context_main (j_decompress_ptr cinfo,
+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+{
+ // bk001204 - no use main
+ my_main_ptr jmain = (my_main_ptr) cinfo->main;
+
+ /* Read input data if we haven't filled the main buffer yet */
+ if (! jmain->buffer_full) {
+ if (! (*cinfo->coef->decompress_data) (cinfo,
+ jmain->xbuffer[jmain->whichptr]))
+ return; /* suspension forced, can do nothing more */
+ jmain->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
+ jmain->iMCU_row_ctr++; /* count rows received */
+ }
+
+ /* Postprocessor typically will not swallow all the input data it is handed
+ * in one call (due to filling the output buffer first). Must be prepared
+ * to exit and restart. This switch lets us keep track of how far we got.
+ * Note that each case falls through to the next on successful completion.
+ */
+ switch (jmain->context_state) {
+ case CTX_POSTPONED_ROW:
+ /* Call postprocessor using previously set pointers for postponed row */
+ (*cinfo->post->post_process_data) (cinfo, jmain->xbuffer[jmain->whichptr],
+ &jmain->rowgroup_ctr, jmain->rowgroups_avail,
+ output_buf, out_row_ctr, out_rows_avail);
+ if (jmain->rowgroup_ctr < jmain->rowgroups_avail)
+ return; /* Need to suspend */
+ jmain->context_state = CTX_PREPARE_FOR_IMCU;
+ if (*out_row_ctr >= out_rows_avail)
+ return; /* Postprocessor exactly filled output buf */
+ /*FALLTHROUGH*/
+ case CTX_PREPARE_FOR_IMCU:
+ /* Prepare to process first M-1 row groups of this iMCU row */
+ jmain->rowgroup_ctr = 0;
+ jmain->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
+ /* Check for bottom of image: if so, tweak pointers to "duplicate"
+ * the last sample row, and adjust rowgroups_avail to ignore padding rows.
+ */
+ if (jmain->iMCU_row_ctr == cinfo->total_iMCU_rows)
+ set_bottom_pointers(cinfo);
+ jmain->context_state = CTX_PROCESS_IMCU;
+ /*FALLTHROUGH*/
+ case CTX_PROCESS_IMCU:
+ /* Call postprocessor using previously set pointers */
+ (*cinfo->post->post_process_data) (cinfo, jmain->xbuffer[jmain->whichptr],
+ &jmain->rowgroup_ctr, jmain->rowgroups_avail,
+ output_buf, out_row_ctr, out_rows_avail);
+ if (jmain->rowgroup_ctr < jmain->rowgroups_avail)
+ return; /* Need to suspend */
+ /* After the first iMCU, change wraparound pointers to normal state */
+ if (jmain->iMCU_row_ctr == 1)
+ set_wraparound_pointers(cinfo);
+ /* Prepare to load new iMCU row using other xbuffer list */
+ jmain->whichptr ^= 1; /* 0=>1 or 1=>0 */
+ jmain->buffer_full = FALSE;
+ /* Still need to process last row group of this iMCU row, */
+ /* which is saved at index M+1 of the other xbuffer */
+ jmain->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
+ jmain->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
+ jmain->context_state = CTX_POSTPONED_ROW;
+ }
+}
+
+
+/*
+ * Process some data.
+ * Final pass of two-pass quantization: just call the postprocessor.
+ * Source data will be the postprocessor controller's internal buffer.
+ */
+
+#ifdef QUANT_2PASS_SUPPORTED
+
+METHODDEF void
+process_data_crank_post (j_decompress_ptr cinfo,
+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+{
+ (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
+ (JDIMENSION *) NULL, (JDIMENSION) 0,
+ output_buf, out_row_ctr, out_rows_avail);
+}
+
+#endif /* QUANT_2PASS_SUPPORTED */
+
+
+/*
+ * Initialize main buffer controller.
+ */
+
+GLOBAL void
+jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
+{
+ // bk001204 - no use main
+ my_main_ptr jmain;
+ int ci, rgroup, ngroups;
+ jpeg_component_info *compptr;
+
+ jmain = (my_main_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_main_controller));
+ cinfo->main = (struct jpeg_d_main_controller *) jmain;
+ jmain->pub.start_pass = start_pass_main;
+
+ if (need_full_buffer) /* shouldn't happen */
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+
+ /* Allocate the workspace.
+ * ngroups is the number of row groups we need.
+ */
+ if (cinfo->upsample->need_context_rows) {
+ if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
+ ERREXIT(cinfo, JERR_NOTIMPL);
+ alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
+ ngroups = cinfo->min_DCT_scaled_size + 2;
+ } else {
+ ngroups = cinfo->min_DCT_scaled_size;
+ }
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
+ cinfo->min_DCT_scaled_size; /* height of a row group of component */
+ jmain->buffer[ci] = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ compptr->width_in_blocks * compptr->DCT_scaled_size,
+ (JDIMENSION) (rgroup * ngroups));
+ }
+}
diff --git a/code/jpeg-6/jdmarker.c b/code/jpeg-6/jdmarker.c
new file mode 100755
index 0000000..6c3c519
--- /dev/null
+++ b/code/jpeg-6/jdmarker.c
@@ -0,0 +1,1052 @@
+/*
+ * jdmarker.c
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains routines to decode JPEG datastream markers.
+ * Most of the complexity arises from our desire to support input
+ * suspension: if not all of the data for a marker is available,
+ * we must exit back to the application. On resumption, we reprocess
+ * the marker.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+typedef enum { /* JPEG marker codes */
+ M_SOF0 = 0xc0,
+ M_SOF1 = 0xc1,
+ M_SOF2 = 0xc2,
+ M_SOF3 = 0xc3,
+
+ M_SOF5 = 0xc5,
+ M_SOF6 = 0xc6,
+ M_SOF7 = 0xc7,
+
+ M_JPG = 0xc8,
+ M_SOF9 = 0xc9,
+ M_SOF10 = 0xca,
+ M_SOF11 = 0xcb,
+
+ M_SOF13 = 0xcd,
+ M_SOF14 = 0xce,
+ M_SOF15 = 0xcf,
+
+ M_DHT = 0xc4,
+
+ M_DAC = 0xcc,
+
+ M_RST0 = 0xd0,
+ M_RST1 = 0xd1,
+ M_RST2 = 0xd2,
+ M_RST3 = 0xd3,
+ M_RST4 = 0xd4,
+ M_RST5 = 0xd5,
+ M_RST6 = 0xd6,
+ M_RST7 = 0xd7,
+
+ M_SOI = 0xd8,
+ M_EOI = 0xd9,
+ M_SOS = 0xda,
+ M_DQT = 0xdb,
+ M_DNL = 0xdc,
+ M_DRI = 0xdd,
+ M_DHP = 0xde,
+ M_EXP = 0xdf,
+
+ M_APP0 = 0xe0,
+ M_APP1 = 0xe1,
+ M_APP2 = 0xe2,
+ M_APP3 = 0xe3,
+ M_APP4 = 0xe4,
+ M_APP5 = 0xe5,
+ M_APP6 = 0xe6,
+ M_APP7 = 0xe7,
+ M_APP8 = 0xe8,
+ M_APP9 = 0xe9,
+ M_APP10 = 0xea,
+ M_APP11 = 0xeb,
+ M_APP12 = 0xec,
+ M_APP13 = 0xed,
+ M_APP14 = 0xee,
+ M_APP15 = 0xef,
+
+ M_JPG0 = 0xf0,
+ M_JPG13 = 0xfd,
+ M_COM = 0xfe,
+
+ M_TEM = 0x01,
+
+ M_ERROR = 0x100
+} JPEG_MARKER;
+
+
+/*
+ * Macros for fetching data from the data source module.
+ *
+ * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
+ * the current restart point; we update them only when we have reached a
+ * suitable place to restart if a suspension occurs.
+ */
+
+/* Declare and initialize local copies of input pointer/count */
+#define INPUT_VARS(cinfo) \
+ struct jpeg_source_mgr * datasrc = (cinfo)->src; \
+ const JOCTET * next_input_byte = datasrc->next_input_byte; \
+ size_t bytes_in_buffer = datasrc->bytes_in_buffer
+
+/* Unload the local copies --- do this only at a restart boundary */
+#define INPUT_SYNC(cinfo) \
+ ( datasrc->next_input_byte = next_input_byte, \
+ datasrc->bytes_in_buffer = bytes_in_buffer )
+
+/* Reload the local copies --- seldom used except in MAKE_BYTE_AVAIL */
+#define INPUT_RELOAD(cinfo) \
+ ( next_input_byte = datasrc->next_input_byte, \
+ bytes_in_buffer = datasrc->bytes_in_buffer )
+
+/* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
+ * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
+ * but we must reload the local copies after a successful fill.
+ */
+#define MAKE_BYTE_AVAIL(cinfo,action) \
+ if (bytes_in_buffer == 0) { \
+ if (! (*datasrc->fill_input_buffer) (cinfo)) \
+ { action; } \
+ INPUT_RELOAD(cinfo); \
+ } \
+ bytes_in_buffer--
+
+/* Read a byte into variable V.
+ * If must suspend, take the specified action (typically "return FALSE").
+ */
+#define INPUT_BYTE(cinfo,V,action) \
+ MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
+ V = GETJOCTET(*next_input_byte++); )
+
+/* As above, but read two bytes interpreted as an unsigned 16-bit integer.
+ * V should be declared unsigned int or perhaps INT32.
+ */
+#define INPUT_2BYTES(cinfo,V,action) \
+ MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
+ V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
+ MAKE_BYTE_AVAIL(cinfo,action); \
+ V += GETJOCTET(*next_input_byte++); )
+
+
+/*
+ * Routines to process JPEG markers.
+ *
+ * Entry condition: JPEG marker itself has been read and its code saved
+ * in cinfo->unread_marker; input restart point is just after the marker.
+ *
+ * Exit: if return TRUE, have read and processed any parameters, and have
+ * updated the restart point to point after the parameters.
+ * If return FALSE, was forced to suspend before reaching end of
+ * marker parameters; restart point has not been moved. Same routine
+ * will be called again after application supplies more input data.
+ *
+ * This approach to suspension assumes that all of a marker's parameters can
+ * fit into a single input bufferload. This should hold for "normal"
+ * markers. Some COM/APPn markers might have large parameter segments,
+ * but we use skip_input_data to get past those, and thereby put the problem
+ * on the source manager's shoulders.
+ *
+ * Note that we don't bother to avoid duplicate trace messages if a
+ * suspension occurs within marker parameters. Other side effects
+ * require more care.
+ */
+
+
+LOCAL boolean
+get_soi (j_decompress_ptr cinfo)
+/* Process an SOI marker */
+{
+ int i;
+
+ TRACEMS(cinfo, 1, JTRC_SOI);
+
+ if (cinfo->marker->saw_SOI)
+ ERREXIT(cinfo, JERR_SOI_DUPLICATE);
+
+ /* Reset all parameters that are defined to be reset by SOI */
+
+ for (i = 0; i < NUM_ARITH_TBLS; i++) {
+ cinfo->arith_dc_L[i] = 0;
+ cinfo->arith_dc_U[i] = 1;
+ cinfo->arith_ac_K[i] = 5;
+ }
+ cinfo->restart_interval = 0;
+
+ /* Set initial assumptions for colorspace etc */
+
+ cinfo->jpeg_color_space = JCS_UNKNOWN;
+ cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
+
+ cinfo->saw_JFIF_marker = FALSE;
+ cinfo->density_unit = 0; /* set default JFIF APP0 values */
+ cinfo->X_density = 1;
+ cinfo->Y_density = 1;
+ cinfo->saw_Adobe_marker = FALSE;
+ cinfo->Adobe_transform = 0;
+
+ cinfo->marker->saw_SOI = TRUE;
+
+ return TRUE;
+}
+
+
+LOCAL boolean
+get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
+/* Process a SOFn marker */
+{
+ INT32 length;
+ int c, ci;
+ jpeg_component_info * compptr;
+ INPUT_VARS(cinfo);
+
+ cinfo->progressive_mode = is_prog;
+ cinfo->arith_code = is_arith;
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+
+ INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
+ INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
+ INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
+ INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
+
+ length -= 8;
+
+ TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
+ (int) cinfo->image_width, (int) cinfo->image_height,
+ cinfo->num_components);
+
+ if (cinfo->marker->saw_SOF)
+ ERREXIT(cinfo, JERR_SOF_DUPLICATE);
+
+ /* We don't support files in which the image height is initially specified */
+ /* as 0 and is later redefined by DNL. As long as we have to check that, */
+ /* might as well have a general sanity check. */
+ if (cinfo->image_height <= 0 || cinfo->image_width <= 0
+ || cinfo->num_components <= 0)
+ ERREXIT(cinfo, JERR_EMPTY_IMAGE);
+
+ if (length != (cinfo->num_components * 3))
+ ERREXIT(cinfo, JERR_BAD_LENGTH);
+
+ if (cinfo->comp_info == NULL) /* do only once, even if suspend */
+ cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ cinfo->num_components * SIZEOF(jpeg_component_info));
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ compptr->component_index = ci;
+ INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
+ INPUT_BYTE(cinfo, c, return FALSE);
+ compptr->h_samp_factor = (c >> 4) & 15;
+ compptr->v_samp_factor = (c ) & 15;
+ INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
+
+ TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
+ compptr->component_id, compptr->h_samp_factor,
+ compptr->v_samp_factor, compptr->quant_tbl_no);
+ }
+
+ cinfo->marker->saw_SOF = TRUE;
+
+ INPUT_SYNC(cinfo);
+ return TRUE;
+}
+
+
+LOCAL boolean
+get_sos (j_decompress_ptr cinfo)
+/* Process a SOS marker */
+{
+ INT32 length;
+ int i, ci, n, c, cc;
+ jpeg_component_info * compptr;
+ INPUT_VARS(cinfo);
+
+ if (! cinfo->marker->saw_SOF)
+ ERREXIT(cinfo, JERR_SOS_NO_SOF);
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+
+ INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
+
+ if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
+ ERREXIT(cinfo, JERR_BAD_LENGTH);
+
+ TRACEMS1(cinfo, 1, JTRC_SOS, n);
+
+ cinfo->comps_in_scan = n;
+
+ /* Collect the component-spec parameters */
+
+ for (i = 0; i < n; i++) {
+ INPUT_BYTE(cinfo, cc, return FALSE);
+ INPUT_BYTE(cinfo, c, return FALSE);
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ if (cc == compptr->component_id)
+ goto id_found;
+ }
+
+ ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
+
+ id_found:
+
+ cinfo->cur_comp_info[i] = compptr;
+ compptr->dc_tbl_no = (c >> 4) & 15;
+ compptr->ac_tbl_no = (c ) & 15;
+
+ TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
+ compptr->dc_tbl_no, compptr->ac_tbl_no);
+ }
+
+ /* Collect the additional scan parameters Ss, Se, Ah/Al. */
+ INPUT_BYTE(cinfo, c, return FALSE);
+ cinfo->Ss = c;
+ INPUT_BYTE(cinfo, c, return FALSE);
+ cinfo->Se = c;
+ INPUT_BYTE(cinfo, c, return FALSE);
+ cinfo->Ah = (c >> 4) & 15;
+ cinfo->Al = (c ) & 15;
+
+ TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
+ cinfo->Ah, cinfo->Al);
+
+ /* Prepare to scan data & restart markers */
+ cinfo->marker->next_restart_num = 0;
+
+ /* Count another SOS marker */
+ cinfo->input_scan_number++;
+
+ INPUT_SYNC(cinfo);
+ return TRUE;
+}
+
+
+METHODDEF boolean
+get_app0 (j_decompress_ptr cinfo)
+/* Process an APP0 marker */
+{
+#define JFIF_LEN 14
+ INT32 length;
+ UINT8 b[JFIF_LEN];
+ int buffp;
+ INPUT_VARS(cinfo);
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+ length -= 2;
+
+ /* See if a JFIF APP0 marker is present */
+
+ if (length >= JFIF_LEN) {
+ for (buffp = 0; buffp < JFIF_LEN; buffp++)
+ INPUT_BYTE(cinfo, b[buffp], return FALSE);
+ length -= JFIF_LEN;
+
+ if (b[0]==0x4A && b[1]==0x46 && b[2]==0x49 && b[3]==0x46 && b[4]==0) {
+ /* Found JFIF APP0 marker: check version */
+ /* Major version must be 1, anything else signals an incompatible change.
+ * We used to treat this as an error, but now it's a nonfatal warning,
+ * because some bozo at Hijaak couldn't read the spec.
+ * Minor version should be 0..2, but process anyway if newer.
+ */
+ if (b[5] != 1)
+ WARNMS2(cinfo, JWRN_JFIF_MAJOR, b[5], b[6]);
+ else if (b[6] > 2)
+ TRACEMS2(cinfo, 1, JTRC_JFIF_MINOR, b[5], b[6]);
+ /* Save info */
+ cinfo->saw_JFIF_marker = TRUE;
+ cinfo->density_unit = b[7];
+ cinfo->X_density = (b[8] << 8) + b[9];
+ cinfo->Y_density = (b[10] << 8) + b[11];
+ TRACEMS3(cinfo, 1, JTRC_JFIF,
+ cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
+ if (b[12] | b[13])
+ TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL, b[12], b[13]);
+ if (length != ((INT32) b[12] * (INT32) b[13] * (INT32) 3))
+ TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) length);
+ } else {
+ /* Start of APP0 does not match "JFIF" */
+ TRACEMS1(cinfo, 1, JTRC_APP0, (int) length + JFIF_LEN);
+ }
+ } else {
+ /* Too short to be JFIF marker */
+ TRACEMS1(cinfo, 1, JTRC_APP0, (int) length);
+ }
+
+ INPUT_SYNC(cinfo);
+ if (length > 0) /* skip any remaining data -- could be lots */
+ (*cinfo->src->skip_input_data) (cinfo, (long) length);
+
+ return TRUE;
+}
+
+
+METHODDEF boolean
+get_app14 (j_decompress_ptr cinfo)
+/* Process an APP14 marker */
+{
+#define ADOBE_LEN 12
+ INT32 length;
+ UINT8 b[ADOBE_LEN];
+ int buffp;
+ unsigned int version, flags0, flags1, transform;
+ INPUT_VARS(cinfo);
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+ length -= 2;
+
+ /* See if an Adobe APP14 marker is present */
+
+ if (length >= ADOBE_LEN) {
+ for (buffp = 0; buffp < ADOBE_LEN; buffp++)
+ INPUT_BYTE(cinfo, b[buffp], return FALSE);
+ length -= ADOBE_LEN;
+
+ if (b[0]==0x41 && b[1]==0x64 && b[2]==0x6F && b[3]==0x62 && b[4]==0x65) {
+ /* Found Adobe APP14 marker */
+ version = (b[5] << 8) + b[6];
+ flags0 = (b[7] << 8) + b[8];
+ flags1 = (b[9] << 8) + b[10];
+ transform = b[11];
+ TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
+ cinfo->saw_Adobe_marker = TRUE;
+ cinfo->Adobe_transform = (UINT8) transform;
+ } else {
+ /* Start of APP14 does not match "Adobe" */
+ TRACEMS1(cinfo, 1, JTRC_APP14, (int) length + ADOBE_LEN);
+ }
+ } else {
+ /* Too short to be Adobe marker */
+ TRACEMS1(cinfo, 1, JTRC_APP14, (int) length);
+ }
+
+ INPUT_SYNC(cinfo);
+ if (length > 0) /* skip any remaining data -- could be lots */
+ (*cinfo->src->skip_input_data) (cinfo, (long) length);
+
+ return TRUE;
+}
+
+
+LOCAL boolean
+get_dac (j_decompress_ptr cinfo)
+/* Process a DAC marker */
+{
+ INT32 length;
+ int index, val;
+ INPUT_VARS(cinfo);
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+ length -= 2;
+
+ while (length > 0) {
+ INPUT_BYTE(cinfo, index, return FALSE);
+ INPUT_BYTE(cinfo, val, return FALSE);
+
+ length -= 2;
+
+ TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
+
+ if (index < 0 || index >= (2*NUM_ARITH_TBLS))
+ ERREXIT1(cinfo, JERR_DAC_INDEX, index);
+
+ if (index >= NUM_ARITH_TBLS) { /* define AC table */
+ cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
+ } else { /* define DC table */
+ cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
+ cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
+ if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
+ ERREXIT1(cinfo, JERR_DAC_VALUE, val);
+ }
+ }
+
+ INPUT_SYNC(cinfo);
+ return TRUE;
+}
+
+
+LOCAL boolean
+get_dht (j_decompress_ptr cinfo)
+/* Process a DHT marker */
+{
+ INT32 length;
+ UINT8 bits[17];
+ UINT8 huffval[256];
+ int i, index, count;
+ JHUFF_TBL **htblptr;
+ INPUT_VARS(cinfo);
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+ length -= 2;
+
+ while (length > 0) {
+ INPUT_BYTE(cinfo, index, return FALSE);
+
+ TRACEMS1(cinfo, 1, JTRC_DHT, index);
+
+ bits[0] = 0;
+ count = 0;
+ for (i = 1; i <= 16; i++) {
+ INPUT_BYTE(cinfo, bits[i], return FALSE);
+ count += bits[i];
+ }
+
+ length -= 1 + 16;
+
+ TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
+ bits[1], bits[2], bits[3], bits[4],
+ bits[5], bits[6], bits[7], bits[8]);
+ TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
+ bits[9], bits[10], bits[11], bits[12],
+ bits[13], bits[14], bits[15], bits[16]);
+
+ if (count > 256 || ((INT32) count) > length)
+ ERREXIT(cinfo, JERR_DHT_COUNTS);
+
+ for (i = 0; i < count; i++)
+ INPUT_BYTE(cinfo, huffval[i], return FALSE);
+
+ length -= count;
+
+ if (index & 0x10) { /* AC table definition */
+ index -= 0x10;
+ htblptr = &cinfo->ac_huff_tbl_ptrs[index];
+ } else { /* DC table definition */
+ htblptr = &cinfo->dc_huff_tbl_ptrs[index];
+ }
+
+ if (index < 0 || index >= NUM_HUFF_TBLS)
+ ERREXIT1(cinfo, JERR_DHT_INDEX, index);
+
+ if (*htblptr == NULL)
+ *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
+
+ MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
+ MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
+ }
+
+ INPUT_SYNC(cinfo);
+ return TRUE;
+}
+
+
+LOCAL boolean
+get_dqt (j_decompress_ptr cinfo)
+/* Process a DQT marker */
+{
+ INT32 length;
+ int n, i, prec;
+ unsigned int tmp;
+ JQUANT_TBL *quant_ptr;
+ INPUT_VARS(cinfo);
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+ length -= 2;
+
+ while (length > 0) {
+ INPUT_BYTE(cinfo, n, return FALSE);
+ prec = n >> 4;
+ n &= 0x0F;
+
+ TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
+
+ if (n >= NUM_QUANT_TBLS)
+ ERREXIT1(cinfo, JERR_DQT_INDEX, n);
+
+ if (cinfo->quant_tbl_ptrs[n] == NULL)
+ cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
+ quant_ptr = cinfo->quant_tbl_ptrs[n];
+
+ for (i = 0; i < DCTSIZE2; i++) {
+ if (prec)
+ INPUT_2BYTES(cinfo, tmp, return FALSE);
+ else
+ INPUT_BYTE(cinfo, tmp, return FALSE);
+ quant_ptr->quantval[i] = (UINT16) tmp;
+ }
+
+ for (i = 0; i < DCTSIZE2; i += 8) {
+ TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
+ quant_ptr->quantval[i ], quant_ptr->quantval[i+1],
+ quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
+ quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
+ quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
+ }
+
+ length -= DCTSIZE2+1;
+ if (prec) length -= DCTSIZE2;
+ }
+
+ INPUT_SYNC(cinfo);
+ return TRUE;
+}
+
+
+LOCAL boolean
+get_dri (j_decompress_ptr cinfo)
+/* Process a DRI marker */
+{
+ INT32 length;
+ unsigned int tmp;
+ INPUT_VARS(cinfo);
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+
+ if (length != 4)
+ ERREXIT(cinfo, JERR_BAD_LENGTH);
+
+ INPUT_2BYTES(cinfo, tmp, return FALSE);
+
+ TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
+
+ cinfo->restart_interval = tmp;
+
+ INPUT_SYNC(cinfo);
+ return TRUE;
+}
+
+
+METHODDEF boolean
+skip_variable (j_decompress_ptr cinfo)
+/* Skip over an unknown or uninteresting variable-length marker */
+{
+ INT32 length;
+ INPUT_VARS(cinfo);
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+
+ TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
+
+ INPUT_SYNC(cinfo); /* do before skip_input_data */
+ (*cinfo->src->skip_input_data) (cinfo, (long) length - 2L);
+
+ return TRUE;
+}
+
+
+/*
+ * Find the next JPEG marker, save it in cinfo->unread_marker.
+ * Returns FALSE if had to suspend before reaching a marker;
+ * in that case cinfo->unread_marker is unchanged.
+ *
+ * Note that the result might not be a valid marker code,
+ * but it will never be 0 or FF.
+ */
+
+LOCAL boolean
+next_marker (j_decompress_ptr cinfo)
+{
+ int c;
+ INPUT_VARS(cinfo);
+
+ for (;;) {
+ INPUT_BYTE(cinfo, c, return FALSE);
+ /* Skip any non-FF bytes.
+ * This may look a bit inefficient, but it will not occur in a valid file.
+ * We sync after each discarded byte so that a suspending data source
+ * can discard the byte from its buffer.
+ */
+ while (c != 0xFF) {
+ cinfo->marker->discarded_bytes++;
+ INPUT_SYNC(cinfo);
+ INPUT_BYTE(cinfo, c, return FALSE);
+ }
+ /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
+ * pad bytes, so don't count them in discarded_bytes. We assume there
+ * will not be so many consecutive FF bytes as to overflow a suspending
+ * data source's input buffer.
+ */
+ do {
+ INPUT_BYTE(cinfo, c, return FALSE);
+ } while (c == 0xFF);
+ if (c != 0)
+ break; /* found a valid marker, exit loop */
+ /* Reach here if we found a stuffed-zero data sequence (FF/00).
+ * Discard it and loop back to try again.
+ */
+ cinfo->marker->discarded_bytes += 2;
+ INPUT_SYNC(cinfo);
+ }
+
+ if (cinfo->marker->discarded_bytes != 0) {
+ WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
+ cinfo->marker->discarded_bytes = 0;
+ }
+
+ cinfo->unread_marker = c;
+
+ INPUT_SYNC(cinfo);
+ return TRUE;
+}
+
+
+LOCAL boolean
+first_marker (j_decompress_ptr cinfo)
+/* Like next_marker, but used to obtain the initial SOI marker. */
+/* For this marker, we do not allow preceding garbage or fill; otherwise,
+ * we might well scan an entire input file before realizing it ain't JPEG.
+ * If an application wants to process non-JFIF files, it must seek to the
+ * SOI before calling the JPEG library.
+ */
+{
+ int c, c2;
+ INPUT_VARS(cinfo);
+
+ INPUT_BYTE(cinfo, c, return FALSE);
+ INPUT_BYTE(cinfo, c2, return FALSE);
+ if (c != 0xFF || c2 != (int) M_SOI)
+ ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
+
+ cinfo->unread_marker = c2;
+
+ INPUT_SYNC(cinfo);
+ return TRUE;
+}
+
+
+/*
+ * Read markers until SOS or EOI.
+ *
+ * Returns same codes as are defined for jpeg_consume_input:
+ * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
+ */
+
+METHODDEF int
+read_markers (j_decompress_ptr cinfo)
+{
+ /* Outer loop repeats once for each marker. */
+ for (;;) {
+ /* Collect the marker proper, unless we already did. */
+ /* NB: first_marker() enforces the requirement that SOI appear first. */
+ if (cinfo->unread_marker == 0) {
+ if (! cinfo->marker->saw_SOI) {
+ if (! first_marker(cinfo))
+ return JPEG_SUSPENDED;
+ } else {
+ if (! next_marker(cinfo))
+ return JPEG_SUSPENDED;
+ }
+ }
+ /* At this point cinfo->unread_marker contains the marker code and the
+ * input point is just past the marker proper, but before any parameters.
+ * A suspension will cause us to return with this state still true.
+ */
+ switch (cinfo->unread_marker) {
+ case M_SOI:
+ if (! get_soi(cinfo))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_SOF0: /* Baseline */
+ case M_SOF1: /* Extended sequential, Huffman */
+ if (! get_sof(cinfo, FALSE, FALSE))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_SOF2: /* Progressive, Huffman */
+ if (! get_sof(cinfo, TRUE, FALSE))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_SOF9: /* Extended sequential, arithmetic */
+ if (! get_sof(cinfo, FALSE, TRUE))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_SOF10: /* Progressive, arithmetic */
+ if (! get_sof(cinfo, TRUE, TRUE))
+ return JPEG_SUSPENDED;
+ break;
+
+ /* Currently unsupported SOFn types */
+ case M_SOF3: /* Lossless, Huffman */
+ case M_SOF5: /* Differential sequential, Huffman */
+ case M_SOF6: /* Differential progressive, Huffman */
+ case M_SOF7: /* Differential lossless, Huffman */
+ case M_JPG: /* Reserved for JPEG extensions */
+ case M_SOF11: /* Lossless, arithmetic */
+ case M_SOF13: /* Differential sequential, arithmetic */
+ case M_SOF14: /* Differential progressive, arithmetic */
+ case M_SOF15: /* Differential lossless, arithmetic */
+ ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
+ break;
+
+ case M_SOS:
+ if (! get_sos(cinfo))
+ return JPEG_SUSPENDED;
+ cinfo->unread_marker = 0; /* processed the marker */
+ return JPEG_REACHED_SOS;
+
+ case M_EOI:
+ TRACEMS(cinfo, 1, JTRC_EOI);
+ cinfo->unread_marker = 0; /* processed the marker */
+ return JPEG_REACHED_EOI;
+
+ case M_DAC:
+ if (! get_dac(cinfo))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_DHT:
+ if (! get_dht(cinfo))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_DQT:
+ if (! get_dqt(cinfo))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_DRI:
+ if (! get_dri(cinfo))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_APP0:
+ case M_APP1:
+ case M_APP2:
+ case M_APP3:
+ case M_APP4:
+ case M_APP5:
+ case M_APP6:
+ case M_APP7:
+ case M_APP8:
+ case M_APP9:
+ case M_APP10:
+ case M_APP11:
+ case M_APP12:
+ case M_APP13:
+ case M_APP14:
+ case M_APP15:
+ if (! (*cinfo->marker->process_APPn[cinfo->unread_marker - (int) M_APP0]) (cinfo))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_COM:
+ if (! (*cinfo->marker->process_COM) (cinfo))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_RST0: /* these are all parameterless */
+ case M_RST1:
+ case M_RST2:
+ case M_RST3:
+ case M_RST4:
+ case M_RST5:
+ case M_RST6:
+ case M_RST7:
+ case M_TEM:
+ TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
+ break;
+
+ case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
+ if (! skip_variable(cinfo))
+ return JPEG_SUSPENDED;
+ break;
+
+ default: /* must be DHP, EXP, JPGn, or RESn */
+ /* For now, we treat the reserved markers as fatal errors since they are
+ * likely to be used to signal incompatible JPEG Part 3 extensions.
+ * Once the JPEG 3 version-number marker is well defined, this code
+ * ought to change!
+ */
+ ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
+ break;
+ }
+ /* Successfully processed marker, so reset state variable */
+ cinfo->unread_marker = 0;
+ } /* end loop */
+}
+
+
+/*
+ * Read a restart marker, which is expected to appear next in the datastream;
+ * if the marker is not there, take appropriate recovery action.
+ * Returns FALSE if suspension is required.
+ *
+ * This is called by the entropy decoder after it has read an appropriate
+ * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
+ * has already read a marker from the data source. Under normal conditions
+ * cinfo->unread_marker will be reset to 0 before returning; if not reset,
+ * it holds a marker which the decoder will be unable to read past.
+ */
+
+METHODDEF boolean
+read_restart_marker (j_decompress_ptr cinfo)
+{
+ /* Obtain a marker unless we already did. */
+ /* Note that next_marker will complain if it skips any data. */
+ if (cinfo->unread_marker == 0) {
+ if (! next_marker(cinfo))
+ return FALSE;
+ }
+
+ if (cinfo->unread_marker ==
+ ((int) M_RST0 + cinfo->marker->next_restart_num)) {
+ /* Normal case --- swallow the marker and let entropy decoder continue */
+ TRACEMS1(cinfo, 2, JTRC_RST, cinfo->marker->next_restart_num);
+ cinfo->unread_marker = 0;
+ } else {
+ /* Uh-oh, the restart markers have been messed up. */
+ /* Let the data source manager determine how to resync. */
+ if (! (*cinfo->src->resync_to_restart) (cinfo,
+ cinfo->marker->next_restart_num))
+ return FALSE;
+ }
+
+ /* Update next-restart state */
+ cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
+
+ return TRUE;
+}
+
+
+/*
+ * This is the default resync_to_restart method for data source managers
+ * to use if they don't have any better approach. Some data source managers
+ * may be able to back up, or may have additional knowledge about the data
+ * which permits a more intelligent recovery strategy; such managers would
+ * presumably supply their own resync method.
+ *
+ * read_restart_marker calls resync_to_restart if it finds a marker other than
+ * the restart marker it was expecting. (This code is *not* used unless
+ * a nonzero restart interval has been declared.) cinfo->unread_marker is
+ * the marker code actually found (might be anything, except 0 or FF).
+ * The desired restart marker number (0..7) is passed as a parameter.
+ * This routine is supposed to apply whatever error recovery strategy seems
+ * appropriate in order to position the input stream to the next data segment.
+ * Note that cinfo->unread_marker is treated as a marker appearing before
+ * the current data-source input point; usually it should be reset to zero
+ * before returning.
+ * Returns FALSE if suspension is required.
+ *
+ * This implementation is substantially constrained by wanting to treat the
+ * input as a data stream; this means we can't back up. Therefore, we have
+ * only the following actions to work with:
+ * 1. Simply discard the marker and let the entropy decoder resume at next
+ * byte of file.
+ * 2. Read forward until we find another marker, discarding intervening
+ * data. (In theory we could look ahead within the current bufferload,
+ * without having to discard data if we don't find the desired marker.
+ * This idea is not implemented here, in part because it makes behavior
+ * dependent on buffer size and chance buffer-boundary positions.)
+ * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
+ * This will cause the entropy decoder to process an empty data segment,
+ * inserting dummy zeroes, and then we will reprocess the marker.
+ *
+ * #2 is appropriate if we think the desired marker lies ahead, while #3 is
+ * appropriate if the found marker is a future restart marker (indicating
+ * that we have missed the desired restart marker, probably because it got
+ * corrupted).
+ * We apply #2 or #3 if the found marker is a restart marker no more than
+ * two counts behind or ahead of the expected one. We also apply #2 if the
+ * found marker is not a legal JPEG marker code (it's certainly bogus data).
+ * If the found marker is a restart marker more than 2 counts away, we do #1
+ * (too much risk that the marker is erroneous; with luck we will be able to
+ * resync at some future point).
+ * For any valid non-restart JPEG marker, we apply #3. This keeps us from
+ * overrunning the end of a scan. An implementation limited to single-scan
+ * files might find it better to apply #2 for markers other than EOI, since
+ * any other marker would have to be bogus data in that case.
+ */
+
+GLOBAL boolean
+jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
+{
+ int marker = cinfo->unread_marker;
+ int action = 1;
+
+ /* Always put up a warning. */
+ WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
+
+ /* Outer loop handles repeated decision after scanning forward. */
+ for (;;) {
+ if (marker < (int) M_SOF0)
+ action = 2; /* invalid marker */
+ else if (marker < (int) M_RST0 || marker > (int) M_RST7)
+ action = 3; /* valid non-restart marker */
+ else {
+ if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
+ marker == ((int) M_RST0 + ((desired+2) & 7)))
+ action = 3; /* one of the next two expected restarts */
+ else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
+ marker == ((int) M_RST0 + ((desired-2) & 7)))
+ action = 2; /* a prior restart, so advance */
+ else
+ action = 1; /* desired restart or too far away */
+ }
+ TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
+ switch (action) {
+ case 1:
+ /* Discard marker and let entropy decoder resume processing. */
+ cinfo->unread_marker = 0;
+ return TRUE;
+ case 2:
+ /* Scan to the next marker, and repeat the decision loop. */
+ if (! next_marker(cinfo))
+ return FALSE;
+ marker = cinfo->unread_marker;
+ break;
+ case 3:
+ /* Return without advancing past this marker. */
+ /* Entropy decoder will be forced to process an empty segment. */
+ return TRUE;
+ }
+ } /* end loop */
+}
+
+
+/*
+ * Reset marker processing state to begin a fresh datastream.
+ */
+
+METHODDEF void
+reset_marker_reader (j_decompress_ptr cinfo)
+{
+ cinfo->comp_info = NULL; /* until allocated by get_sof */
+ cinfo->input_scan_number = 0; /* no SOS seen yet */
+ cinfo->unread_marker = 0; /* no pending marker */
+ cinfo->marker->saw_SOI = FALSE; /* set internal state too */
+ cinfo->marker->saw_SOF = FALSE;
+ cinfo->marker->discarded_bytes = 0;
+}
+
+
+/*
+ * Initialize the marker reader module.
+ * This is called only once, when the decompression object is created.
+ */
+
+GLOBAL void
+jinit_marker_reader (j_decompress_ptr cinfo)
+{
+ int i;
+
+ /* Create subobject in permanent pool */
+ cinfo->marker = (struct jpeg_marker_reader *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ SIZEOF(struct jpeg_marker_reader));
+ /* Initialize method pointers */
+ cinfo->marker->reset_marker_reader = reset_marker_reader;
+ cinfo->marker->read_markers = read_markers;
+ cinfo->marker->read_restart_marker = read_restart_marker;
+ cinfo->marker->process_COM = skip_variable;
+ for (i = 0; i < 16; i++)
+ cinfo->marker->process_APPn[i] = skip_variable;
+ cinfo->marker->process_APPn[0] = get_app0;
+ cinfo->marker->process_APPn[14] = get_app14;
+ /* Reset marker processing state */
+ reset_marker_reader(cinfo);
+}
diff --git a/code/jpeg-6/jdmaster.c b/code/jpeg-6/jdmaster.c
new file mode 100755
index 0000000..64f730f
--- /dev/null
+++ b/code/jpeg-6/jdmaster.c
@@ -0,0 +1,557 @@
+/*
+ * jdmaster.c
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains master control logic for the JPEG decompressor.
+ * These routines are concerned with selecting the modules to be executed
+ * and with determining the number of passes and the work to be done in each
+ * pass.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Private state */
+
+typedef struct {
+ struct jpeg_decomp_master pub; /* public fields */
+
+ int pass_number; /* # of passes completed */
+
+ boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
+
+ /* Saved references to initialized quantizer modules,
+ * in case we need to switch modes.
+ */
+ struct jpeg_color_quantizer * quantizer_1pass;
+ struct jpeg_color_quantizer * quantizer_2pass;
+} my_decomp_master;
+
+typedef my_decomp_master * my_master_ptr;
+
+
+/*
+ * Determine whether merged upsample/color conversion should be used.
+ * CRUCIAL: this must match the actual capabilities of jdmerge.c!
+ */
+
+LOCAL boolean
+use_merged_upsample (j_decompress_ptr cinfo)
+{
+#ifdef UPSAMPLE_MERGING_SUPPORTED
+ /* Merging is the equivalent of plain box-filter upsampling */
+ if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
+ return FALSE;
+ /* jdmerge.c only supports YCC=>RGB color conversion */
+ if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
+ cinfo->out_color_space != JCS_RGB ||
+ cinfo->out_color_components != RGB_PIXELSIZE)
+ return FALSE;
+ /* and it only handles 2h1v or 2h2v sampling ratios */
+ if (cinfo->comp_info[0].h_samp_factor != 2 ||
+ cinfo->comp_info[1].h_samp_factor != 1 ||
+ cinfo->comp_info[2].h_samp_factor != 1 ||
+ cinfo->comp_info[0].v_samp_factor > 2 ||
+ cinfo->comp_info[1].v_samp_factor != 1 ||
+ cinfo->comp_info[2].v_samp_factor != 1)
+ return FALSE;
+ /* furthermore, it doesn't work if we've scaled the IDCTs differently */
+ if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
+ cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
+ cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
+ return FALSE;
+ /* ??? also need to test for upsample-time rescaling, when & if supported */
+ return TRUE; /* by golly, it'll work... */
+#else
+ return FALSE;
+#endif
+}
+
+
+/*
+ * Compute output image dimensions and related values.
+ * NOTE: this is exported for possible use by application.
+ * Hence it mustn't do anything that can't be done twice.
+ * Also note that it may be called before the master module is initialized!
+ */
+
+GLOBAL void
+jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
+/* Do computations that are needed before master selection phase */
+{
+#if 0 // JDC: commented out to remove warning
+ int ci;
+ jpeg_component_info *compptr;
+#endif
+
+ /* Prevent application from calling me at wrong times */
+ if (cinfo->global_state != DSTATE_READY)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+#ifdef IDCT_SCALING_SUPPORTED
+
+ /* Compute actual output image dimensions and DCT scaling choices. */
+ if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
+ /* Provide 1/8 scaling */
+ cinfo->output_width = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width, 8L);
+ cinfo->output_height = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height, 8L);
+ cinfo->min_DCT_scaled_size = 1;
+ } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
+ /* Provide 1/4 scaling */
+ cinfo->output_width = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width, 4L);
+ cinfo->output_height = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height, 4L);
+ cinfo->min_DCT_scaled_size = 2;
+ } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
+ /* Provide 1/2 scaling */
+ cinfo->output_width = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width, 2L);
+ cinfo->output_height = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height, 2L);
+ cinfo->min_DCT_scaled_size = 4;
+ } else {
+ /* Provide 1/1 scaling */
+ cinfo->output_width = cinfo->image_width;
+ cinfo->output_height = cinfo->image_height;
+ cinfo->min_DCT_scaled_size = DCTSIZE;
+ }
+ /* In selecting the actual DCT scaling for each component, we try to
+ * scale up the chroma components via IDCT scaling rather than upsampling.
+ * This saves time if the upsampler gets to use 1:1 scaling.
+ * Note this code assumes that the supported DCT scalings are powers of 2.
+ */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ int ssize = cinfo->min_DCT_scaled_size;
+ while (ssize < DCTSIZE &&
+ (compptr->h_samp_factor * ssize * 2 <=
+ cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
+ (compptr->v_samp_factor * ssize * 2 <=
+ cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
+ ssize = ssize * 2;
+ }
+ compptr->DCT_scaled_size = ssize;
+ }
+
+ /* Recompute downsampled dimensions of components;
+ * application needs to know these if using raw downsampled data.
+ */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Size in samples, after IDCT scaling */
+ compptr->downsampled_width = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width *
+ (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
+ (long) (cinfo->max_h_samp_factor * DCTSIZE));
+ compptr->downsampled_height = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height *
+ (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
+ (long) (cinfo->max_v_samp_factor * DCTSIZE));
+ }
+
+#else /* !IDCT_SCALING_SUPPORTED */
+
+ /* Hardwire it to "no scaling" */
+ cinfo->output_width = cinfo->image_width;
+ cinfo->output_height = cinfo->image_height;
+ /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
+ * and has computed unscaled downsampled_width and downsampled_height.
+ */
+
+#endif /* IDCT_SCALING_SUPPORTED */
+
+ /* Report number of components in selected colorspace. */
+ /* Probably this should be in the color conversion module... */
+ switch (cinfo->out_color_space) {
+ case JCS_GRAYSCALE:
+ cinfo->out_color_components = 1;
+ break;
+ case JCS_RGB:
+#if RGB_PIXELSIZE != 3
+ cinfo->out_color_components = RGB_PIXELSIZE;
+ break;
+#endif /* else share code with YCbCr */
+ case JCS_YCbCr:
+ cinfo->out_color_components = 3;
+ break;
+ case JCS_CMYK:
+ case JCS_YCCK:
+ cinfo->out_color_components = 4;
+ break;
+ default: /* else must be same colorspace as in file */
+ cinfo->out_color_components = cinfo->num_components;
+ break;
+ }
+ cinfo->output_components = (cinfo->quantize_colors ? 1 :
+ cinfo->out_color_components);
+
+ /* See if upsampler will want to emit more than one row at a time */
+ if (use_merged_upsample(cinfo))
+ cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
+ else
+ cinfo->rec_outbuf_height = 1;
+}
+
+
+/*
+ * Several decompression processes need to range-limit values to the range
+ * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
+ * due to noise introduced by quantization, roundoff error, etc. These
+ * processes are inner loops and need to be as fast as possible. On most
+ * machines, particularly CPUs with pipelines or instruction prefetch,
+ * a (subscript-check-less) C table lookup
+ * x = sample_range_limit[x];
+ * is faster than explicit tests
+ * if (x < 0) x = 0;
+ * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
+ * These processes all use a common table prepared by the routine below.
+ *
+ * For most steps we can mathematically guarantee that the initial value
+ * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
+ * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
+ * limiting step (just after the IDCT), a wildly out-of-range value is
+ * possible if the input data is corrupt. To avoid any chance of indexing
+ * off the end of memory and getting a bad-pointer trap, we perform the
+ * post-IDCT limiting thus:
+ * x = range_limit[x & MASK];
+ * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
+ * samples. Under normal circumstances this is more than enough range and
+ * a correct output will be generated; with bogus input data the mask will
+ * cause wraparound, and we will safely generate a bogus-but-in-range output.
+ * For the post-IDCT step, we want to convert the data from signed to unsigned
+ * representation by adding CENTERJSAMPLE at the same time that we limit it.
+ * So the post-IDCT limiting table ends up looking like this:
+ * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
+ * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
+ * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
+ * 0,1,...,CENTERJSAMPLE-1
+ * Negative inputs select values from the upper half of the table after
+ * masking.
+ *
+ * We can save some space by overlapping the start of the post-IDCT table
+ * with the simpler range limiting table. The post-IDCT table begins at
+ * sample_range_limit + CENTERJSAMPLE.
+ *
+ * Note that the table is allocated in near data space on PCs; it's small
+ * enough and used often enough to justify this.
+ */
+
+LOCAL void
+prepare_range_limit_table (j_decompress_ptr cinfo)
+/* Allocate and fill in the sample_range_limit table */
+{
+ JSAMPLE * table;
+ int i;
+
+ table = (JSAMPLE *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
+ table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
+ cinfo->sample_range_limit = table;
+ /* First segment of "simple" table: limit[x] = 0 for x < 0 */
+ MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
+ /* Main part of "simple" table: limit[x] = x */
+ for (i = 0; i <= MAXJSAMPLE; i++)
+ table[i] = (JSAMPLE) i;
+ table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
+ /* End of simple table, rest of first half of post-IDCT table */
+ for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
+ table[i] = MAXJSAMPLE;
+ /* Second half of post-IDCT table */
+ MEMZERO(table + (2 * (MAXJSAMPLE+1)),
+ (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
+ MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
+ cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
+}
+
+
+/*
+ * Master selection of decompression modules.
+ * This is done once at jpeg_start_decompress time. We determine
+ * which modules will be used and give them appropriate initialization calls.
+ * We also initialize the decompressor input side to begin consuming data.
+ *
+ * Since jpeg_read_header has finished, we know what is in the SOF
+ * and (first) SOS markers. We also have all the application parameter
+ * settings.
+ */
+
+LOCAL void
+master_selection (j_decompress_ptr cinfo)
+{
+ my_master_ptr master = (my_master_ptr) cinfo->master;
+ boolean use_c_buffer;
+ long samplesperrow;
+ JDIMENSION jd_samplesperrow;
+
+ /* Initialize dimensions and other stuff */
+ jpeg_calc_output_dimensions(cinfo);
+ prepare_range_limit_table(cinfo);
+
+ /* Width of an output scanline must be representable as JDIMENSION. */
+ samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
+ jd_samplesperrow = (JDIMENSION) samplesperrow;
+ if ((long) jd_samplesperrow != samplesperrow)
+ ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
+
+ /* Initialize my private state */
+ master->pass_number = 0;
+ master->using_merged_upsample = use_merged_upsample(cinfo);
+
+ /* Color quantizer selection */
+ master->quantizer_1pass = NULL;
+ master->quantizer_2pass = NULL;
+ /* No mode changes if not using buffered-image mode. */
+ if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
+ cinfo->enable_1pass_quant = FALSE;
+ cinfo->enable_external_quant = FALSE;
+ cinfo->enable_2pass_quant = FALSE;
+ }
+ if (cinfo->quantize_colors) {
+ if (cinfo->raw_data_out)
+ ERREXIT(cinfo, JERR_NOTIMPL);
+ /* 2-pass quantizer only works in 3-component color space. */
+ if (cinfo->out_color_components != 3) {
+ cinfo->enable_1pass_quant = TRUE;
+ cinfo->enable_external_quant = FALSE;
+ cinfo->enable_2pass_quant = FALSE;
+ cinfo->colormap = NULL;
+ } else if (cinfo->colormap != NULL) {
+ cinfo->enable_external_quant = TRUE;
+ } else if (cinfo->two_pass_quantize) {
+ cinfo->enable_2pass_quant = TRUE;
+ } else {
+ cinfo->enable_1pass_quant = TRUE;
+ }
+
+ if (cinfo->enable_1pass_quant) {
+#ifdef QUANT_1PASS_SUPPORTED
+ jinit_1pass_quantizer(cinfo);
+ master->quantizer_1pass = cinfo->cquantize;
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ }
+
+ /* We use the 2-pass code to map to external colormaps. */
+ if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
+#ifdef QUANT_2PASS_SUPPORTED
+ jinit_2pass_quantizer(cinfo);
+ master->quantizer_2pass = cinfo->cquantize;
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ }
+ /* If both quantizers are initialized, the 2-pass one is left active;
+ * this is necessary for starting with quantization to an external map.
+ */
+ }
+
+ /* Post-processing: in particular, color conversion first */
+ if (! cinfo->raw_data_out) {
+ if (master->using_merged_upsample) {
+#ifdef UPSAMPLE_MERGING_SUPPORTED
+ jinit_merged_upsampler(cinfo); /* does color conversion too */
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else {
+ jinit_color_deconverter(cinfo);
+ jinit_upsampler(cinfo);
+ }
+ jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
+ }
+ /* Inverse DCT */
+ jinit_inverse_dct(cinfo);
+ /* Entropy decoding: either Huffman or arithmetic coding. */
+ if (cinfo->arith_code) {
+ ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
+ } else {
+ if (cinfo->progressive_mode) {
+#ifdef D_PROGRESSIVE_SUPPORTED
+ jinit_phuff_decoder(cinfo);
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else
+ jinit_huff_decoder(cinfo);
+ }
+
+ /* Initialize principal buffer controllers. */
+ use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
+ jinit_d_coef_controller(cinfo, use_c_buffer);
+
+ if (! cinfo->raw_data_out)
+ jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
+
+ /* We can now tell the memory manager to allocate virtual arrays. */
+ (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
+
+ /* Initialize input side of decompressor to consume first scan. */
+ (*cinfo->inputctl->start_input_pass) (cinfo);
+
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+ /* If jpeg_start_decompress will read the whole file, initialize
+ * progress monitoring appropriately. The input step is counted
+ * as one pass.
+ */
+ if (cinfo->progress != NULL && ! cinfo->buffered_image &&
+ cinfo->inputctl->has_multiple_scans) {
+ int nscans;
+ /* Estimate number of scans to set pass_limit. */
+ if (cinfo->progressive_mode) {
+ /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
+ nscans = 2 + 3 * cinfo->num_components;
+ } else {
+ /* For a nonprogressive multiscan file, estimate 1 scan per component. */
+ nscans = cinfo->num_components;
+ }
+ cinfo->progress->pass_counter = 0L;
+ cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
+ cinfo->progress->completed_passes = 0;
+ cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
+ /* Count the input pass as done */
+ master->pass_number++;
+ }
+#endif /* D_MULTISCAN_FILES_SUPPORTED */
+}
+
+
+/*
+ * Per-pass setup.
+ * This is called at the beginning of each output pass. We determine which
+ * modules will be active during this pass and give them appropriate
+ * start_pass calls. We also set is_dummy_pass to indicate whether this
+ * is a "real" output pass or a dummy pass for color quantization.
+ * (In the latter case, jdapi.c will crank the pass to completion.)
+ */
+
+METHODDEF void
+prepare_for_output_pass (j_decompress_ptr cinfo)
+{
+ my_master_ptr master = (my_master_ptr) cinfo->master;
+
+ if (master->pub.is_dummy_pass) {
+#ifdef QUANT_2PASS_SUPPORTED
+ /* Final pass of 2-pass quantization */
+ master->pub.is_dummy_pass = FALSE;
+ (*cinfo->cquantize->start_pass) (cinfo, FALSE);
+ (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
+ (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif /* QUANT_2PASS_SUPPORTED */
+ } else {
+ if (cinfo->quantize_colors && cinfo->colormap == NULL) {
+ /* Select new quantization method */
+ if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
+ cinfo->cquantize = master->quantizer_2pass;
+ master->pub.is_dummy_pass = TRUE;
+ } else if (cinfo->enable_1pass_quant) {
+ cinfo->cquantize = master->quantizer_1pass;
+ } else {
+ ERREXIT(cinfo, JERR_MODE_CHANGE);
+ }
+ }
+ (*cinfo->idct->start_pass) (cinfo);
+ (*cinfo->coef->start_output_pass) (cinfo);
+ if (! cinfo->raw_data_out) {
+ if (! master->using_merged_upsample)
+ (*cinfo->cconvert->start_pass) (cinfo);
+ (*cinfo->upsample->start_pass) (cinfo);
+ if (cinfo->quantize_colors)
+ (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
+ (*cinfo->post->start_pass) (cinfo,
+ (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
+ (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
+ }
+ }
+
+ /* Set up progress monitor's pass info if present */
+ if (cinfo->progress != NULL) {
+ cinfo->progress->completed_passes = master->pass_number;
+ cinfo->progress->total_passes = master->pass_number +
+ (master->pub.is_dummy_pass ? 2 : 1);
+ /* In buffered-image mode, we assume one more output pass if EOI not
+ * yet reached, but no more passes if EOI has been reached.
+ */
+ if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
+ cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
+ }
+ }
+}
+
+
+/*
+ * Finish up at end of an output pass.
+ */
+
+METHODDEF void
+finish_output_pass (j_decompress_ptr cinfo)
+{
+ my_master_ptr master = (my_master_ptr) cinfo->master;
+
+ if (cinfo->quantize_colors)
+ (*cinfo->cquantize->finish_pass) (cinfo);
+ master->pass_number++;
+}
+
+
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+
+/*
+ * Switch to a new external colormap between output passes.
+ */
+
+GLOBAL void
+jpeg_new_colormap (j_decompress_ptr cinfo)
+{
+ my_master_ptr master = (my_master_ptr) cinfo->master;
+
+ /* Prevent application from calling me at wrong times */
+ if (cinfo->global_state != DSTATE_BUFIMAGE)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+ if (cinfo->quantize_colors && cinfo->enable_external_quant &&
+ cinfo->colormap != NULL) {
+ /* Select 2-pass quantizer for external colormap use */
+ cinfo->cquantize = master->quantizer_2pass;
+ /* Notify quantizer of colormap change */
+ (*cinfo->cquantize->new_color_map) (cinfo);
+ master->pub.is_dummy_pass = FALSE; /* just in case */
+ } else
+ ERREXIT(cinfo, JERR_MODE_CHANGE);
+}
+
+#endif /* D_MULTISCAN_FILES_SUPPORTED */
+
+
+/*
+ * Initialize master decompression control and select active modules.
+ * This is performed at the start of jpeg_start_decompress.
+ */
+
+GLOBAL void
+jinit_master_decompress (j_decompress_ptr cinfo)
+{
+ my_master_ptr master;
+
+ master = (my_master_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_decomp_master));
+ cinfo->master = (struct jpeg_decomp_master *) master;
+ master->pub.prepare_for_output_pass = prepare_for_output_pass;
+ master->pub.finish_output_pass = finish_output_pass;
+
+ master->pub.is_dummy_pass = FALSE;
+
+ master_selection(cinfo);
+}
diff --git a/code/jpeg-6/jdmerge.c b/code/jpeg-6/jdmerge.c
new file mode 100755
index 0000000..cc81640
--- /dev/null
+++ b/code/jpeg-6/jdmerge.c
@@ -0,0 +1,400 @@
+/*
+ * jdmerge.c
+ *
+ * Copyright (C) 1994-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains code for merged upsampling/color conversion.
+ *
+ * This file combines functions from jdsample.c and jdcolor.c;
+ * read those files first to understand what's going on.
+ *
+ * When the chroma components are to be upsampled by simple replication
+ * (ie, box filtering), we can save some work in color conversion by
+ * calculating all the output pixels corresponding to a pair of chroma
+ * samples at one time. In the conversion equations
+ * R = Y + K1 * Cr
+ * G = Y + K2 * Cb + K3 * Cr
+ * B = Y + K4 * Cb
+ * only the Y term varies among the group of pixels corresponding to a pair
+ * of chroma samples, so the rest of the terms can be calculated just once.
+ * At typical sampling ratios, this eliminates half or three-quarters of the
+ * multiplications needed for color conversion.
+ *
+ * This file currently provides implementations for the following cases:
+ * YCbCr => RGB color conversion only.
+ * Sampling ratios of 2h1v or 2h2v.
+ * No scaling needed at upsample time.
+ * Corner-aligned (non-CCIR601) sampling alignment.
+ * Other special cases could be added, but in most applications these are
+ * the only common cases. (For uncommon cases we fall back on the more
+ * general code in jdsample.c and jdcolor.c.)
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+#ifdef UPSAMPLE_MERGING_SUPPORTED
+
+
+/* Private subobject */
+
+typedef struct {
+ struct jpeg_upsampler pub; /* public fields */
+
+ /* Pointer to routine to do actual upsampling/conversion of one row group */
+ JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
+ JSAMPARRAY output_buf));
+
+ /* Private state for YCC->RGB conversion */
+ int * Cr_r_tab; /* => table for Cr to R conversion */
+ int * Cb_b_tab; /* => table for Cb to B conversion */
+ INT32 * Cr_g_tab; /* => table for Cr to G conversion */
+ INT32 * Cb_g_tab; /* => table for Cb to G conversion */
+
+ /* For 2:1 vertical sampling, we produce two output rows at a time.
+ * We need a "spare" row buffer to hold the second output row if the
+ * application provides just a one-row buffer; we also use the spare
+ * to discard the dummy last row if the image height is odd.
+ */
+ JSAMPROW spare_row;
+ boolean spare_full; /* T if spare buffer is occupied */
+
+ JDIMENSION out_row_width; /* samples per output row */
+ JDIMENSION rows_to_go; /* counts rows remaining in image */
+} my_upsampler;
+
+typedef my_upsampler * my_upsample_ptr;
+
+#define SCALEBITS 16 /* speediest right-shift on some machines */
+#define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
+#define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
+
+
+/*
+ * Initialize tables for YCC->RGB colorspace conversion.
+ * This is taken directly from jdcolor.c; see that file for more info.
+ */
+
+LOCAL void
+build_ycc_rgb_table (j_decompress_ptr cinfo)
+{
+ my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
+ int i;
+ INT32 x;
+ SHIFT_TEMPS
+
+ upsample->Cr_r_tab = (int *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (MAXJSAMPLE+1) * SIZEOF(int));
+ upsample->Cb_b_tab = (int *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (MAXJSAMPLE+1) * SIZEOF(int));
+ upsample->Cr_g_tab = (INT32 *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (MAXJSAMPLE+1) * SIZEOF(INT32));
+ upsample->Cb_g_tab = (INT32 *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (MAXJSAMPLE+1) * SIZEOF(INT32));
+
+ for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
+ /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
+ /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
+ /* Cr=>R value is nearest int to 1.40200 * x */
+ upsample->Cr_r_tab[i] = (int)
+ RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
+ /* Cb=>B value is nearest int to 1.77200 * x */
+ upsample->Cb_b_tab[i] = (int)
+ RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
+ /* Cr=>G value is scaled-up -0.71414 * x */
+ upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
+ /* Cb=>G value is scaled-up -0.34414 * x */
+ /* We also add in ONE_HALF so that need not do it in inner loop */
+ upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
+ }
+}
+
+
+/*
+ * Initialize for an upsampling pass.
+ */
+
+METHODDEF void
+start_pass_merged_upsample (j_decompress_ptr cinfo)
+{
+ my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
+
+ /* Mark the spare buffer empty */
+ upsample->spare_full = FALSE;
+ /* Initialize total-height counter for detecting bottom of image */
+ upsample->rows_to_go = cinfo->output_height;
+}
+
+
+/*
+ * Control routine to do upsampling (and color conversion).
+ *
+ * The control routine just handles the row buffering considerations.
+ */
+
+METHODDEF void
+merged_2v_upsample (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+/* 2:1 vertical sampling case: may need a spare row. */
+{
+ my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
+ JSAMPROW work_ptrs[2];
+ JDIMENSION num_rows; /* number of rows returned to caller */
+
+ if (upsample->spare_full) {
+ /* If we have a spare row saved from a previous cycle, just return it. */
+ jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
+ 1, upsample->out_row_width);
+ num_rows = 1;
+ upsample->spare_full = FALSE;
+ } else {
+ /* Figure number of rows to return to caller. */
+ num_rows = 2;
+ /* Not more than the distance to the end of the image. */
+ if (num_rows > upsample->rows_to_go)
+ num_rows = upsample->rows_to_go;
+ /* And not more than what the client can accept: */
+ out_rows_avail -= *out_row_ctr;
+ if (num_rows > out_rows_avail)
+ num_rows = out_rows_avail;
+ /* Create output pointer array for upsampler. */
+ work_ptrs[0] = output_buf[*out_row_ctr];
+ if (num_rows > 1) {
+ work_ptrs[1] = output_buf[*out_row_ctr + 1];
+ } else {
+ work_ptrs[1] = upsample->spare_row;
+ upsample->spare_full = TRUE;
+ }
+ /* Now do the upsampling. */
+ (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
+ }
+
+ /* Adjust counts */
+ *out_row_ctr += num_rows;
+ upsample->rows_to_go -= num_rows;
+ /* When the buffer is emptied, declare this input row group consumed */
+ if (! upsample->spare_full)
+ (*in_row_group_ctr)++;
+}
+
+
+METHODDEF void
+merged_1v_upsample (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+/* 1:1 vertical sampling case: much easier, never need a spare row. */
+{
+ my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
+
+ /* Just do the upsampling. */
+ (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
+ output_buf + *out_row_ctr);
+ /* Adjust counts */
+ (*out_row_ctr)++;
+ (*in_row_group_ctr)++;
+}
+
+
+/*
+ * These are the routines invoked by the control routines to do
+ * the actual upsampling/conversion. One row group is processed per call.
+ *
+ * Note: since we may be writing directly into application-supplied buffers,
+ * we have to be honest about the output width; we can't assume the buffer
+ * has been rounded up to an even width.
+ */
+
+
+/*
+ * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
+ */
+
+METHODDEF void
+h2v1_merged_upsample (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
+ JSAMPARRAY output_buf)
+{
+ my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
+ register int y, cred, cgreen, cblue;
+ int cb, cr;
+ register JSAMPROW outptr;
+ JSAMPROW inptr0, inptr1, inptr2;
+ JDIMENSION col;
+ /* copy these pointers into registers if possible */
+ register JSAMPLE * range_limit = cinfo->sample_range_limit;
+ int * Crrtab = upsample->Cr_r_tab;
+ int * Cbbtab = upsample->Cb_b_tab;
+ INT32 * Crgtab = upsample->Cr_g_tab;
+ INT32 * Cbgtab = upsample->Cb_g_tab;
+ SHIFT_TEMPS
+
+ inptr0 = input_buf[0][in_row_group_ctr];
+ inptr1 = input_buf[1][in_row_group_ctr];
+ inptr2 = input_buf[2][in_row_group_ctr];
+ outptr = output_buf[0];
+ /* Loop for each pair of output pixels */
+ for (col = cinfo->output_width >> 1; col > 0; col--) {
+ /* Do the chroma part of the calculation */
+ cb = GETJSAMPLE(*inptr1++);
+ cr = GETJSAMPLE(*inptr2++);
+ cred = Crrtab[cr];
+ cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
+ cblue = Cbbtab[cb];
+ /* Fetch 2 Y values and emit 2 pixels */
+ y = GETJSAMPLE(*inptr0++);
+ outptr[RGB_RED] = range_limit[y + cred];
+ outptr[RGB_GREEN] = range_limit[y + cgreen];
+ outptr[RGB_BLUE] = range_limit[y + cblue];
+ outptr += RGB_PIXELSIZE;
+ y = GETJSAMPLE(*inptr0++);
+ outptr[RGB_RED] = range_limit[y + cred];
+ outptr[RGB_GREEN] = range_limit[y + cgreen];
+ outptr[RGB_BLUE] = range_limit[y + cblue];
+ outptr += RGB_PIXELSIZE;
+ }
+ /* If image width is odd, do the last output column separately */
+ if (cinfo->output_width & 1) {
+ cb = GETJSAMPLE(*inptr1);
+ cr = GETJSAMPLE(*inptr2);
+ cred = Crrtab[cr];
+ cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
+ cblue = Cbbtab[cb];
+ y = GETJSAMPLE(*inptr0);
+ outptr[RGB_RED] = range_limit[y + cred];
+ outptr[RGB_GREEN] = range_limit[y + cgreen];
+ outptr[RGB_BLUE] = range_limit[y + cblue];
+ }
+}
+
+
+/*
+ * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
+ */
+
+METHODDEF void
+h2v2_merged_upsample (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
+ JSAMPARRAY output_buf)
+{
+ my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
+ register int y, cred, cgreen, cblue;
+ int cb, cr;
+ register JSAMPROW outptr0, outptr1;
+ JSAMPROW inptr00, inptr01, inptr1, inptr2;
+ JDIMENSION col;
+ /* copy these pointers into registers if possible */
+ register JSAMPLE * range_limit = cinfo->sample_range_limit;
+ int * Crrtab = upsample->Cr_r_tab;
+ int * Cbbtab = upsample->Cb_b_tab;
+ INT32 * Crgtab = upsample->Cr_g_tab;
+ INT32 * Cbgtab = upsample->Cb_g_tab;
+ SHIFT_TEMPS
+
+ inptr00 = input_buf[0][in_row_group_ctr*2];
+ inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
+ inptr1 = input_buf[1][in_row_group_ctr];
+ inptr2 = input_buf[2][in_row_group_ctr];
+ outptr0 = output_buf[0];
+ outptr1 = output_buf[1];
+ /* Loop for each group of output pixels */
+ for (col = cinfo->output_width >> 1; col > 0; col--) {
+ /* Do the chroma part of the calculation */
+ cb = GETJSAMPLE(*inptr1++);
+ cr = GETJSAMPLE(*inptr2++);
+ cred = Crrtab[cr];
+ cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
+ cblue = Cbbtab[cb];
+ /* Fetch 4 Y values and emit 4 pixels */
+ y = GETJSAMPLE(*inptr00++);
+ outptr0[RGB_RED] = range_limit[y + cred];
+ outptr0[RGB_GREEN] = range_limit[y + cgreen];
+ outptr0[RGB_BLUE] = range_limit[y + cblue];
+ outptr0 += RGB_PIXELSIZE;
+ y = GETJSAMPLE(*inptr00++);
+ outptr0[RGB_RED] = range_limit[y + cred];
+ outptr0[RGB_GREEN] = range_limit[y + cgreen];
+ outptr0[RGB_BLUE] = range_limit[y + cblue];
+ outptr0 += RGB_PIXELSIZE;
+ y = GETJSAMPLE(*inptr01++);
+ outptr1[RGB_RED] = range_limit[y + cred];
+ outptr1[RGB_GREEN] = range_limit[y + cgreen];
+ outptr1[RGB_BLUE] = range_limit[y + cblue];
+ outptr1 += RGB_PIXELSIZE;
+ y = GETJSAMPLE(*inptr01++);
+ outptr1[RGB_RED] = range_limit[y + cred];
+ outptr1[RGB_GREEN] = range_limit[y + cgreen];
+ outptr1[RGB_BLUE] = range_limit[y + cblue];
+ outptr1 += RGB_PIXELSIZE;
+ }
+ /* If image width is odd, do the last output column separately */
+ if (cinfo->output_width & 1) {
+ cb = GETJSAMPLE(*inptr1);
+ cr = GETJSAMPLE(*inptr2);
+ cred = Crrtab[cr];
+ cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
+ cblue = Cbbtab[cb];
+ y = GETJSAMPLE(*inptr00);
+ outptr0[RGB_RED] = range_limit[y + cred];
+ outptr0[RGB_GREEN] = range_limit[y + cgreen];
+ outptr0[RGB_BLUE] = range_limit[y + cblue];
+ y = GETJSAMPLE(*inptr01);
+ outptr1[RGB_RED] = range_limit[y + cred];
+ outptr1[RGB_GREEN] = range_limit[y + cgreen];
+ outptr1[RGB_BLUE] = range_limit[y + cblue];
+ }
+}
+
+
+/*
+ * Module initialization routine for merged upsampling/color conversion.
+ *
+ * NB: this is called under the conditions determined by use_merged_upsample()
+ * in jdmaster.c. That routine MUST correspond to the actual capabilities
+ * of this module; no safety checks are made here.
+ */
+
+GLOBAL void
+jinit_merged_upsampler (j_decompress_ptr cinfo)
+{
+ my_upsample_ptr upsample;
+
+ upsample = (my_upsample_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_upsampler));
+ cinfo->upsample = (struct jpeg_upsampler *) upsample;
+ upsample->pub.start_pass = start_pass_merged_upsample;
+ upsample->pub.need_context_rows = FALSE;
+
+ upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
+
+ if (cinfo->max_v_samp_factor == 2) {
+ upsample->pub.upsample = merged_2v_upsample;
+ upsample->upmethod = h2v2_merged_upsample;
+ /* Allocate a spare row buffer */
+ upsample->spare_row = (JSAMPROW)
+ (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
+ } else {
+ upsample->pub.upsample = merged_1v_upsample;
+ upsample->upmethod = h2v1_merged_upsample;
+ /* No spare row needed */
+ upsample->spare_row = NULL;
+ }
+
+ build_ycc_rgb_table(cinfo);
+}
+
+#endif /* UPSAMPLE_MERGING_SUPPORTED */
diff --git a/code/jpeg-6/jdphuff.c b/code/jpeg-6/jdphuff.c
new file mode 100755
index 0000000..9399bcc
--- /dev/null
+++ b/code/jpeg-6/jdphuff.c
@@ -0,0 +1,642 @@
+/*
+ * jdphuff.c
+ *
+ * Copyright (C) 1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains Huffman entropy decoding routines for progressive JPEG.
+ *
+ * Much of the complexity here has to do with supporting input suspension.
+ * If the data source module demands suspension, we want to be able to back
+ * up to the start of the current MCU. To do this, we copy state variables
+ * into local working storage, and update them back to the permanent
+ * storage only upon successful completion of an MCU.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jdhuff.h" /* Declarations shared with jdhuff.c */
+
+
+#ifdef D_PROGRESSIVE_SUPPORTED
+
+/*
+ * Expanded entropy decoder object for progressive Huffman decoding.
+ *
+ * The savable_state subrecord contains fields that change within an MCU,
+ * but must not be updated permanently until we complete the MCU.
+ */
+
+typedef struct {
+ unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
+ int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
+} savable_state;
+
+/* This macro is to work around compilers with missing or broken
+ * structure assignment. You'll need to fix this code if you have
+ * such a compiler and you change MAX_COMPS_IN_SCAN.
+ */
+
+#ifndef NO_STRUCT_ASSIGN
+#define ASSIGN_STATE(dest,src) ((dest) = (src))
+#else
+#if MAX_COMPS_IN_SCAN == 4
+#define ASSIGN_STATE(dest,src) \
+ ((dest).EOBRUN = (src).EOBRUN, \
+ (dest).last_dc_val[0] = (src).last_dc_val[0], \
+ (dest).last_dc_val[1] = (src).last_dc_val[1], \
+ (dest).last_dc_val[2] = (src).last_dc_val[2], \
+ (dest).last_dc_val[3] = (src).last_dc_val[3])
+#endif
+#endif
+
+
+typedef struct {
+ struct jpeg_entropy_decoder pub; /* public fields */
+
+ /* These fields are loaded into local variables at start of each MCU.
+ * In case of suspension, we exit WITHOUT updating them.
+ */
+ bitread_perm_state bitstate; /* Bit buffer at start of MCU */
+ savable_state saved; /* Other state at start of MCU */
+
+ /* These fields are NOT loaded into local working state. */
+ unsigned int restarts_to_go; /* MCUs left in this restart interval */
+
+ /* Pointers to derived tables (these workspaces have image lifespan) */
+ d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
+
+ d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
+} phuff_entropy_decoder;
+
+typedef phuff_entropy_decoder * phuff_entropy_ptr;
+
+/* Forward declarations */
+METHODDEF boolean decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
+ JBLOCKROW *MCU_data));
+METHODDEF boolean decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
+ JBLOCKROW *MCU_data));
+METHODDEF boolean decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
+ JBLOCKROW *MCU_data));
+METHODDEF boolean decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
+ JBLOCKROW *MCU_data));
+
+
+/*
+ * Initialize for a Huffman-compressed scan.
+ */
+
+METHODDEF void
+start_pass_phuff_decoder (j_decompress_ptr cinfo)
+{
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+ boolean is_DC_band, bad;
+ int ci, coefi, tbl;
+ int *coef_bit_ptr;
+ jpeg_component_info * compptr;
+
+ is_DC_band = (cinfo->Ss == 0);
+
+ /* Validate scan parameters */
+ bad = FALSE;
+ if (is_DC_band) {
+ if (cinfo->Se != 0)
+ bad = TRUE;
+ } else {
+ /* need not check Ss/Se < 0 since they came from unsigned bytes */
+ if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
+ bad = TRUE;
+ /* AC scans may have only one component */
+ if (cinfo->comps_in_scan != 1)
+ bad = TRUE;
+ }
+ if (cinfo->Ah != 0) {
+ /* Successive approximation refinement scan: must have Al = Ah-1. */
+ if (cinfo->Al != cinfo->Ah-1)
+ bad = TRUE;
+ }
+ if (cinfo->Al > 13) /* need not check for < 0 */
+ bad = TRUE;
+ if (bad)
+ ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
+ cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
+ /* Update progression status, and verify that scan order is legal.
+ * Note that inter-scan inconsistencies are treated as warnings
+ * not fatal errors ... not clear if this is right way to behave.
+ */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ int cindex = cinfo->cur_comp_info[ci]->component_index;
+ coef_bit_ptr = & cinfo->coef_bits[cindex][0];
+ if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
+ WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
+ for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
+ int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
+ if (cinfo->Ah != expected)
+ WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
+ coef_bit_ptr[coefi] = cinfo->Al;
+ }
+ }
+
+ /* Select MCU decoding routine */
+ if (cinfo->Ah == 0) {
+ if (is_DC_band)
+ entropy->pub.decode_mcu = decode_mcu_DC_first;
+ else
+ entropy->pub.decode_mcu = decode_mcu_AC_first;
+ } else {
+ if (is_DC_band)
+ entropy->pub.decode_mcu = decode_mcu_DC_refine;
+ else
+ entropy->pub.decode_mcu = decode_mcu_AC_refine;
+ }
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ /* Make sure requested tables are present, and compute derived tables.
+ * We may build same derived table more than once, but it's not expensive.
+ */
+ if (is_DC_band) {
+ if (cinfo->Ah == 0) { /* DC refinement needs no table */
+ tbl = compptr->dc_tbl_no;
+ if (tbl < 0 || tbl >= NUM_HUFF_TBLS ||
+ cinfo->dc_huff_tbl_ptrs[tbl] == NULL)
+ ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
+ jpeg_make_d_derived_tbl(cinfo, cinfo->dc_huff_tbl_ptrs[tbl],
+ & entropy->derived_tbls[tbl]);
+ }
+ } else {
+ tbl = compptr->ac_tbl_no;
+ if (tbl < 0 || tbl >= NUM_HUFF_TBLS ||
+ cinfo->ac_huff_tbl_ptrs[tbl] == NULL)
+ ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
+ jpeg_make_d_derived_tbl(cinfo, cinfo->ac_huff_tbl_ptrs[tbl],
+ & entropy->derived_tbls[tbl]);
+ /* remember the single active table */
+ entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
+ }
+ /* Initialize DC predictions to 0 */
+ entropy->saved.last_dc_val[ci] = 0;
+ }
+
+ /* Initialize bitread state variables */
+ entropy->bitstate.bits_left = 0;
+ entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
+ entropy->bitstate.printed_eod = FALSE;
+
+ /* Initialize private state variables */
+ entropy->saved.EOBRUN = 0;
+
+ /* Initialize restart counter */
+ entropy->restarts_to_go = cinfo->restart_interval;
+}
+
+
+/*
+ * Figure F.12: extend sign bit.
+ * On some machines, a shift and add will be faster than a table lookup.
+ */
+
+#ifdef AVOID_TABLES
+
+#define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
+
+#else
+
+#define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
+
+static const int extend_test[16] = /* entry n is 2**(n-1) */
+ { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
+ 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
+
+static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
+ { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
+ ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
+ ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
+ ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
+
+#endif /* AVOID_TABLES */
+
+
+/*
+ * Check for a restart marker & resynchronize decoder.
+ * Returns FALSE if must suspend.
+ */
+
+LOCAL boolean
+process_restart (j_decompress_ptr cinfo)
+{
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+ int ci;
+
+ /* Throw away any unused bits remaining in bit buffer; */
+ /* include any full bytes in next_marker's count of discarded bytes */
+ cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
+ entropy->bitstate.bits_left = 0;
+
+ /* Advance past the RSTn marker */
+ if (! (*cinfo->marker->read_restart_marker) (cinfo))
+ return FALSE;
+
+ /* Re-initialize DC predictions to 0 */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++)
+ entropy->saved.last_dc_val[ci] = 0;
+ /* Re-init EOB run count, too */
+ entropy->saved.EOBRUN = 0;
+
+ /* Reset restart counter */
+ entropy->restarts_to_go = cinfo->restart_interval;
+
+ /* Next segment can get another out-of-data warning */
+ entropy->bitstate.printed_eod = FALSE;
+
+ return TRUE;
+}
+
+
+/*
+ * Huffman MCU decoding.
+ * Each of these routines decodes and returns one MCU's worth of
+ * Huffman-compressed coefficients.
+ * The coefficients are reordered from zigzag order into natural array order,
+ * but are not dequantized.
+ *
+ * The i'th block of the MCU is stored into the block pointed to by
+ * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
+ *
+ * We return FALSE if data source requested suspension. In that case no
+ * changes have been made to permanent state. (Exception: some output
+ * coefficients may already have been assigned. This is harmless for
+ * spectral selection, since we'll just re-assign them on the next call.
+ * Successive approximation AC refinement has to be more careful, however.)
+ */
+
+/*
+ * MCU decoding for DC initial scan (either spectral selection,
+ * or first pass of successive approximation).
+ */
+
+METHODDEF boolean
+decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
+{
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+ int Al = cinfo->Al;
+ register int s, r;
+ int blkn, ci;
+ JBLOCKROW block;
+ BITREAD_STATE_VARS;
+ savable_state state;
+ d_derived_tbl * tbl;
+ jpeg_component_info * compptr;
+
+ /* Process restart marker if needed; may have to suspend */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0)
+ if (! process_restart(cinfo))
+ return FALSE;
+ }
+
+ /* Load up working state */
+ BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
+ ASSIGN_STATE(state, entropy->saved);
+
+ /* Outer loop handles each block in the MCU */
+
+ for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
+ block = MCU_data[blkn];
+ ci = cinfo->MCU_membership[blkn];
+ compptr = cinfo->cur_comp_info[ci];
+ tbl = entropy->derived_tbls[compptr->dc_tbl_no];
+
+ /* Decode a single block's worth of coefficients */
+
+ /* Section F.2.2.1: decode the DC coefficient difference */
+ HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
+ if (s) {
+ CHECK_BIT_BUFFER(br_state, s, return FALSE);
+ r = GET_BITS(s);
+ s = HUFF_EXTEND(r, s);
+ }
+
+ /* Convert DC difference to actual value, update last_dc_val */
+ s += state.last_dc_val[ci];
+ state.last_dc_val[ci] = s;
+ /* Scale and output the DC coefficient (assumes jpeg_natural_order[0]=0) */
+ (*block)[0] = (JCOEF) (s << Al);
+ }
+
+ /* Completed MCU, so update state */
+ BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
+ ASSIGN_STATE(entropy->saved, state);
+
+ /* Account for restart interval (no-op if not using restarts) */
+ entropy->restarts_to_go--;
+
+ return TRUE;
+}
+
+
+/*
+ * MCU decoding for AC initial scan (either spectral selection,
+ * or first pass of successive approximation).
+ */
+
+METHODDEF boolean
+decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
+{
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+ int Se = cinfo->Se;
+ int Al = cinfo->Al;
+ register int s, k, r;
+ unsigned int EOBRUN;
+ JBLOCKROW block;
+ BITREAD_STATE_VARS;
+ d_derived_tbl * tbl;
+
+ /* Process restart marker if needed; may have to suspend */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0)
+ if (! process_restart(cinfo))
+ return FALSE;
+ }
+
+ /* Load up working state.
+ * We can avoid loading/saving bitread state if in an EOB run.
+ */
+ EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we care about */
+
+ /* There is always only one block per MCU */
+
+ if (EOBRUN > 0) /* if it's a band of zeroes... */
+ EOBRUN--; /* ...process it now (we do nothing) */
+ else {
+ BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
+ block = MCU_data[0];
+ tbl = entropy->ac_derived_tbl;
+
+ for (k = cinfo->Ss; k <= Se; k++) {
+ HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
+ r = s >> 4;
+ s &= 15;
+ if (s) {
+ k += r;
+ CHECK_BIT_BUFFER(br_state, s, return FALSE);
+ r = GET_BITS(s);
+ s = HUFF_EXTEND(r, s);
+ /* Scale and output coefficient in natural (dezigzagged) order */
+ (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
+ } else {
+ if (r == 15) { /* ZRL */
+ k += 15; /* skip 15 zeroes in band */
+ } else { /* EOBr, run length is 2^r + appended bits */
+ EOBRUN = 1 << r;
+ if (r) { /* EOBr, r > 0 */
+ CHECK_BIT_BUFFER(br_state, r, return FALSE);
+ r = GET_BITS(r);
+ EOBRUN += r;
+ }
+ EOBRUN--; /* this band is processed at this moment */
+ break; /* force end-of-band */
+ }
+ }
+ }
+
+ BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
+ }
+
+ /* Completed MCU, so update state */
+ entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we care about */
+
+ /* Account for restart interval (no-op if not using restarts) */
+ entropy->restarts_to_go--;
+
+ return TRUE;
+}
+
+
+/*
+ * MCU decoding for DC successive approximation refinement scan.
+ * Note: we assume such scans can be multi-component, although the spec
+ * is not very clear on the point.
+ */
+
+METHODDEF boolean
+decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
+{
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+ int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
+ int blkn;
+ JBLOCKROW block;
+ BITREAD_STATE_VARS;
+
+ /* Process restart marker if needed; may have to suspend */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0)
+ if (! process_restart(cinfo))
+ return FALSE;
+ }
+
+ /* Load up working state */
+ BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
+
+ /* Outer loop handles each block in the MCU */
+
+ for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
+ block = MCU_data[blkn];
+
+ /* Encoded data is simply the next bit of the two's-complement DC value */
+ CHECK_BIT_BUFFER(br_state, 1, return FALSE);
+ if (GET_BITS(1))
+ (*block)[0] |= p1;
+ /* Note: since we use |=, repeating the assignment later is safe */
+ }
+
+ /* Completed MCU, so update state */
+ BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
+
+ /* Account for restart interval (no-op if not using restarts) */
+ entropy->restarts_to_go--;
+
+ return TRUE;
+}
+
+
+/*
+ * MCU decoding for AC successive approximation refinement scan.
+ */
+
+METHODDEF boolean
+decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
+{
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+ int Se = cinfo->Se;
+ int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
+ int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
+ register int s, k, r;
+ unsigned int EOBRUN;
+ JBLOCKROW block;
+ JCOEFPTR thiscoef;
+ BITREAD_STATE_VARS;
+ d_derived_tbl * tbl;
+ int num_newnz;
+ int newnz_pos[DCTSIZE2];
+
+ /* Process restart marker if needed; may have to suspend */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0)
+ if (! process_restart(cinfo))
+ return FALSE;
+ }
+
+ /* Load up working state */
+ BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
+ EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we care about */
+
+ /* There is always only one block per MCU */
+ block = MCU_data[0];
+ tbl = entropy->ac_derived_tbl;
+
+ /* If we are forced to suspend, we must undo the assignments to any newly
+ * nonzero coefficients in the block, because otherwise we'd get confused
+ * next time about which coefficients were already nonzero.
+ * But we need not undo addition of bits to already-nonzero coefficients;
+ * instead, we can test the current bit position to see if we already did it.
+ */
+ num_newnz = 0;
+
+ /* initialize coefficient loop counter to start of band */
+ k = cinfo->Ss;
+
+ if (EOBRUN == 0) {
+ for (; k <= Se; k++) {
+ HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
+ r = s >> 4;
+ s &= 15;
+ if (s) {
+ if (s != 1) /* size of new coef should always be 1 */
+ WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
+ CHECK_BIT_BUFFER(br_state, 1, goto undoit);
+ if (GET_BITS(1))
+ s = p1; /* newly nonzero coef is positive */
+ else
+ s = m1; /* newly nonzero coef is negative */
+ } else {
+ if (r != 15) {
+ EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
+ if (r) {
+ CHECK_BIT_BUFFER(br_state, r, goto undoit);
+ r = GET_BITS(r);
+ EOBRUN += r;
+ }
+ break; /* rest of block is handled by EOB logic */
+ }
+ /* note s = 0 for processing ZRL */
+ }
+ /* Advance over already-nonzero coefs and r still-zero coefs,
+ * appending correction bits to the nonzeroes. A correction bit is 1
+ * if the absolute value of the coefficient must be increased.
+ */
+ do {
+ thiscoef = *block + jpeg_natural_order[k];
+ if (*thiscoef != 0) {
+ CHECK_BIT_BUFFER(br_state, 1, goto undoit);
+ if (GET_BITS(1)) {
+ if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
+ if (*thiscoef >= 0)
+ *thiscoef += p1;
+ else
+ *thiscoef += m1;
+ }
+ }
+ } else {
+ if (--r < 0)
+ break; /* reached target zero coefficient */
+ }
+ k++;
+ } while (k <= Se);
+ if (s) {
+ int pos = jpeg_natural_order[k];
+ /* Output newly nonzero coefficient */
+ (*block)[pos] = (JCOEF) s;
+ /* Remember its position in case we have to suspend */
+ newnz_pos[num_newnz++] = pos;
+ }
+ }
+ }
+
+ if (EOBRUN > 0) {
+ /* Scan any remaining coefficient positions after the end-of-band
+ * (the last newly nonzero coefficient, if any). Append a correction
+ * bit to each already-nonzero coefficient. A correction bit is 1
+ * if the absolute value of the coefficient must be increased.
+ */
+ for (; k <= Se; k++) {
+ thiscoef = *block + jpeg_natural_order[k];
+ if (*thiscoef != 0) {
+ CHECK_BIT_BUFFER(br_state, 1, goto undoit);
+ if (GET_BITS(1)) {
+ if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
+ if (*thiscoef >= 0)
+ *thiscoef += p1;
+ else
+ *thiscoef += m1;
+ }
+ }
+ }
+ }
+ /* Count one block completed in EOB run */
+ EOBRUN--;
+ }
+
+ /* Completed MCU, so update state */
+ BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
+ entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we care about */
+
+ /* Account for restart interval (no-op if not using restarts) */
+ entropy->restarts_to_go--;
+
+ return TRUE;
+
+undoit:
+ /* Re-zero any output coefficients that we made newly nonzero */
+ while (num_newnz > 0)
+ (*block)[newnz_pos[--num_newnz]] = 0;
+
+ return FALSE;
+}
+
+
+/*
+ * Module initialization routine for progressive Huffman entropy decoding.
+ */
+
+GLOBAL void
+jinit_phuff_decoder (j_decompress_ptr cinfo)
+{
+ phuff_entropy_ptr entropy;
+ int *coef_bit_ptr;
+ int ci, i;
+
+ entropy = (phuff_entropy_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(phuff_entropy_decoder));
+ cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
+ entropy->pub.start_pass = start_pass_phuff_decoder;
+
+ /* Mark derived tables unallocated */
+ for (i = 0; i < NUM_HUFF_TBLS; i++) {
+ entropy->derived_tbls[i] = NULL;
+ }
+
+ /* Create progression status table */
+ cinfo->coef_bits = (int (*)[DCTSIZE2])
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ cinfo->num_components*DCTSIZE2*SIZEOF(int));
+ coef_bit_ptr = & cinfo->coef_bits[0][0];
+ for (ci = 0; ci < cinfo->num_components; ci++)
+ for (i = 0; i < DCTSIZE2; i++)
+ *coef_bit_ptr++ = -1;
+}
+
+#endif /* D_PROGRESSIVE_SUPPORTED */
diff --git a/code/jpeg-6/jdpostct.c b/code/jpeg-6/jdpostct.c
new file mode 100755
index 0000000..e3283b0
--- /dev/null
+++ b/code/jpeg-6/jdpostct.c
@@ -0,0 +1,290 @@
+/*
+ * jdpostct.c
+ *
+ * Copyright (C) 1994-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the decompression postprocessing controller.
+ * This controller manages the upsampling, color conversion, and color
+ * quantization/reduction steps; specifically, it controls the buffering
+ * between upsample/color conversion and color quantization/reduction.
+ *
+ * If no color quantization/reduction is required, then this module has no
+ * work to do, and it just hands off to the upsample/color conversion code.
+ * An integrated upsample/convert/quantize process would replace this module
+ * entirely.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Private buffer controller object */
+
+typedef struct {
+ struct jpeg_d_post_controller pub; /* public fields */
+
+ /* Color quantization source buffer: this holds output data from
+ * the upsample/color conversion step to be passed to the quantizer.
+ * For two-pass color quantization, we need a full-image buffer;
+ * for one-pass operation, a strip buffer is sufficient.
+ */
+ jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
+ JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
+ JDIMENSION strip_height; /* buffer size in rows */
+ /* for two-pass mode only: */
+ JDIMENSION starting_row; /* row # of first row in current strip */
+ JDIMENSION next_row; /* index of next row to fill/empty in strip */
+} my_post_controller;
+
+typedef my_post_controller * my_post_ptr;
+
+
+/* Forward declarations */
+METHODDEF void post_process_1pass
+ JPP((j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail));
+#ifdef QUANT_2PASS_SUPPORTED
+METHODDEF void post_process_prepass
+ JPP((j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail));
+METHODDEF void post_process_2pass
+ JPP((j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail));
+#endif
+
+
+/*
+ * Initialize for a processing pass.
+ */
+
+METHODDEF void
+start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
+{
+ my_post_ptr post = (my_post_ptr) cinfo->post;
+
+ switch (pass_mode) {
+ case JBUF_PASS_THRU:
+ if (cinfo->quantize_colors) {
+ /* Single-pass processing with color quantization. */
+ post->pub.post_process_data = post_process_1pass;
+ /* We could be doing buffered-image output before starting a 2-pass
+ * color quantization; in that case, jinit_d_post_controller did not
+ * allocate a strip buffer. Use the virtual-array buffer as workspace.
+ */
+ if (post->buffer == NULL) {
+ post->buffer = (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, post->whole_image,
+ (JDIMENSION) 0, post->strip_height, TRUE);
+ }
+ } else {
+ /* For single-pass processing without color quantization,
+ * I have no work to do; just call the upsampler directly.
+ */
+ post->pub.post_process_data = cinfo->upsample->upsample;
+ }
+ break;
+#ifdef QUANT_2PASS_SUPPORTED
+ case JBUF_SAVE_AND_PASS:
+ /* First pass of 2-pass quantization */
+ if (post->whole_image == NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ post->pub.post_process_data = post_process_prepass;
+ break;
+ case JBUF_CRANK_DEST:
+ /* Second pass of 2-pass quantization */
+ if (post->whole_image == NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ post->pub.post_process_data = post_process_2pass;
+ break;
+#endif /* QUANT_2PASS_SUPPORTED */
+ default:
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ break;
+ }
+ post->starting_row = post->next_row = 0;
+}
+
+
+/*
+ * Process some data in the one-pass (strip buffer) case.
+ * This is used for color precision reduction as well as one-pass quantization.
+ */
+
+METHODDEF void
+post_process_1pass (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+{
+ my_post_ptr post = (my_post_ptr) cinfo->post;
+ JDIMENSION num_rows, max_rows;
+
+ /* Fill the buffer, but not more than what we can dump out in one go. */
+ /* Note we rely on the upsampler to detect bottom of image. */
+ max_rows = out_rows_avail - *out_row_ctr;
+ if (max_rows > post->strip_height)
+ max_rows = post->strip_height;
+ num_rows = 0;
+ (*cinfo->upsample->upsample) (cinfo,
+ input_buf, in_row_group_ctr, in_row_groups_avail,
+ post->buffer, &num_rows, max_rows);
+ /* Quantize and emit data. */
+ (*cinfo->cquantize->color_quantize) (cinfo,
+ post->buffer, output_buf + *out_row_ctr, (int) num_rows);
+ *out_row_ctr += num_rows;
+}
+
+
+#ifdef QUANT_2PASS_SUPPORTED
+
+/*
+ * Process some data in the first pass of 2-pass quantization.
+ */
+
+METHODDEF void
+post_process_prepass (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+{
+ my_post_ptr post = (my_post_ptr) cinfo->post;
+ JDIMENSION old_next_row, num_rows;
+
+ /* Reposition virtual buffer if at start of strip. */
+ if (post->next_row == 0) {
+ post->buffer = (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, post->whole_image,
+ post->starting_row, post->strip_height, TRUE);
+ }
+
+ /* Upsample some data (up to a strip height's worth). */
+ old_next_row = post->next_row;
+ (*cinfo->upsample->upsample) (cinfo,
+ input_buf, in_row_group_ctr, in_row_groups_avail,
+ post->buffer, &post->next_row, post->strip_height);
+
+ /* Allow quantizer to scan new data. No data is emitted, */
+ /* but we advance out_row_ctr so outer loop can tell when we're done. */
+ if (post->next_row > old_next_row) {
+ num_rows = post->next_row - old_next_row;
+ (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
+ (JSAMPARRAY) NULL, (int) num_rows);
+ *out_row_ctr += num_rows;
+ }
+
+ /* Advance if we filled the strip. */
+ if (post->next_row >= post->strip_height) {
+ post->starting_row += post->strip_height;
+ post->next_row = 0;
+ }
+}
+
+
+/*
+ * Process some data in the second pass of 2-pass quantization.
+ */
+
+METHODDEF void
+post_process_2pass (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+{
+ my_post_ptr post = (my_post_ptr) cinfo->post;
+ JDIMENSION num_rows, max_rows;
+
+ /* Reposition virtual buffer if at start of strip. */
+ if (post->next_row == 0) {
+ post->buffer = (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, post->whole_image,
+ post->starting_row, post->strip_height, FALSE);
+ }
+
+ /* Determine number of rows to emit. */
+ num_rows = post->strip_height - post->next_row; /* available in strip */
+ max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
+ if (num_rows > max_rows)
+ num_rows = max_rows;
+ /* We have to check bottom of image here, can't depend on upsampler. */
+ max_rows = cinfo->output_height - post->starting_row;
+ if (num_rows > max_rows)
+ num_rows = max_rows;
+
+ /* Quantize and emit data. */
+ (*cinfo->cquantize->color_quantize) (cinfo,
+ post->buffer + post->next_row, output_buf + *out_row_ctr,
+ (int) num_rows);
+ *out_row_ctr += num_rows;
+
+ /* Advance if we filled the strip. */
+ post->next_row += num_rows;
+ if (post->next_row >= post->strip_height) {
+ post->starting_row += post->strip_height;
+ post->next_row = 0;
+ }
+}
+
+#endif /* QUANT_2PASS_SUPPORTED */
+
+
+/*
+ * Initialize postprocessing controller.
+ */
+
+GLOBAL void
+jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
+{
+ my_post_ptr post;
+
+ post = (my_post_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_post_controller));
+ cinfo->post = (struct jpeg_d_post_controller *) post;
+ post->pub.start_pass = start_pass_dpost;
+ post->whole_image = NULL; /* flag for no virtual arrays */
+ post->buffer = NULL; /* flag for no strip buffer */
+
+ /* Create the quantization buffer, if needed */
+ if (cinfo->quantize_colors) {
+ /* The buffer strip height is max_v_samp_factor, which is typically
+ * an efficient number of rows for upsampling to return.
+ * (In the presence of output rescaling, we might want to be smarter?)
+ */
+ post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
+ if (need_full_buffer) {
+ /* Two-pass color quantization: need full-image storage. */
+ /* We round up the number of rows to a multiple of the strip height. */
+#ifdef QUANT_2PASS_SUPPORTED
+ post->whole_image = (*cinfo->mem->request_virt_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+ cinfo->output_width * cinfo->out_color_components,
+ (JDIMENSION) jround_up((long) cinfo->output_height,
+ (long) post->strip_height),
+ post->strip_height);
+#else
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+#endif /* QUANT_2PASS_SUPPORTED */
+ } else {
+ /* One-pass color quantization: just make a strip buffer. */
+ post->buffer = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ cinfo->output_width * cinfo->out_color_components,
+ post->strip_height);
+ }
+ }
+}
diff --git a/code/jpeg-6/jdsample.c b/code/jpeg-6/jdsample.c
new file mode 100755
index 0000000..bc171f4
--- /dev/null
+++ b/code/jpeg-6/jdsample.c
@@ -0,0 +1,478 @@
+/*
+ * jdsample.c
+ *
+ * Copyright (C) 1991-1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains upsampling routines.
+ *
+ * Upsampling input data is counted in "row groups". A row group
+ * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
+ * sample rows of each component. Upsampling will normally produce
+ * max_v_samp_factor pixel rows from each row group (but this could vary
+ * if the upsampler is applying a scale factor of its own).
+ *
+ * An excellent reference for image resampling is
+ * Digital Image Warping, George Wolberg, 1990.
+ * Pub. by IEEE Computer Society Press, Los Alamitos, CA. ISBN 0-8186-8944-7.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Pointer to routine to upsample a single component */
+typedef JMETHOD(void, upsample1_ptr,
+ (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
+
+/* Private subobject */
+
+typedef struct {
+ struct jpeg_upsampler pub; /* public fields */
+
+ /* Color conversion buffer. When using separate upsampling and color
+ * conversion steps, this buffer holds one upsampled row group until it
+ * has been color converted and output.
+ * Note: we do not allocate any storage for component(s) which are full-size,
+ * ie do not need rescaling. The corresponding entry of color_buf[] is
+ * simply set to point to the input data array, thereby avoiding copying.
+ */
+ JSAMPARRAY color_buf[MAX_COMPONENTS];
+
+ /* Per-component upsampling method pointers */
+ upsample1_ptr methods[MAX_COMPONENTS];
+
+ int next_row_out; /* counts rows emitted from color_buf */
+ JDIMENSION rows_to_go; /* counts rows remaining in image */
+
+ /* Height of an input row group for each component. */
+ int rowgroup_height[MAX_COMPONENTS];
+
+ /* These arrays save pixel expansion factors so that int_expand need not
+ * recompute them each time. They are unused for other upsampling methods.
+ */
+ UINT8 h_expand[MAX_COMPONENTS];
+ UINT8 v_expand[MAX_COMPONENTS];
+} my_upsampler;
+
+typedef my_upsampler * my_upsample_ptr;
+
+
+/*
+ * Initialize for an upsampling pass.
+ */
+
+METHODDEF void
+start_pass_upsample (j_decompress_ptr cinfo)
+{
+ my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
+
+ /* Mark the conversion buffer empty */
+ upsample->next_row_out = cinfo->max_v_samp_factor;
+ /* Initialize total-height counter for detecting bottom of image */
+ upsample->rows_to_go = cinfo->output_height;
+}
+
+
+/*
+ * Control routine to do upsampling (and color conversion).
+ *
+ * In this version we upsample each component independently.
+ * We upsample one row group into the conversion buffer, then apply
+ * color conversion a row at a time.
+ */
+
+METHODDEF void
+sep_upsample (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+{
+ my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
+ int ci;
+ jpeg_component_info * compptr;
+ JDIMENSION num_rows;
+
+ /* Fill the conversion buffer, if it's empty */
+ if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Invoke per-component upsample method. Notice we pass a POINTER
+ * to color_buf[ci], so that fullsize_upsample can change it.
+ */
+ (*upsample->methods[ci]) (cinfo, compptr,
+ input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
+ upsample->color_buf + ci);
+ }
+ upsample->next_row_out = 0;
+ }
+
+ /* Color-convert and emit rows */
+
+ /* How many we have in the buffer: */
+ num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
+ /* Not more than the distance to the end of the image. Need this test
+ * in case the image height is not a multiple of max_v_samp_factor:
+ */
+ if (num_rows > upsample->rows_to_go)
+ num_rows = upsample->rows_to_go;
+ /* And not more than what the client can accept: */
+ out_rows_avail -= *out_row_ctr;
+ if (num_rows > out_rows_avail)
+ num_rows = out_rows_avail;
+
+ (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
+ (JDIMENSION) upsample->next_row_out,
+ output_buf + *out_row_ctr,
+ (int) num_rows);
+
+ /* Adjust counts */
+ *out_row_ctr += num_rows;
+ upsample->rows_to_go -= num_rows;
+ upsample->next_row_out += num_rows;
+ /* When the buffer is emptied, declare this input row group consumed */
+ if (upsample->next_row_out >= cinfo->max_v_samp_factor)
+ (*in_row_group_ctr)++;
+}
+
+
+/*
+ * These are the routines invoked by sep_upsample to upsample pixel values
+ * of a single component. One row group is processed per call.
+ */
+
+
+/*
+ * For full-size components, we just make color_buf[ci] point at the
+ * input buffer, and thus avoid copying any data. Note that this is
+ * safe only because sep_upsample doesn't declare the input row group
+ * "consumed" until we are done color converting and emitting it.
+ */
+
+METHODDEF void
+fullsize_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
+{
+ *output_data_ptr = input_data;
+}
+
+
+/*
+ * This is a no-op version used for "uninteresting" components.
+ * These components will not be referenced by color conversion.
+ */
+
+METHODDEF void
+noop_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
+{
+ *output_data_ptr = NULL; /* safety check */
+}
+
+
+/*
+ * This version handles any integral sampling ratios.
+ * This is not used for typical JPEG files, so it need not be fast.
+ * Nor, for that matter, is it particularly accurate: the algorithm is
+ * simple replication of the input pixel onto the corresponding output
+ * pixels. The hi-falutin sampling literature refers to this as a
+ * "box filter". A box filter tends to introduce visible artifacts,
+ * so if you are actually going to use 3:1 or 4:1 sampling ratios
+ * you would be well advised to improve this code.
+ */
+
+METHODDEF void
+int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
+{
+ my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
+ JSAMPARRAY output_data = *output_data_ptr;
+ register JSAMPROW inptr, outptr;
+ register JSAMPLE invalue;
+ register int h;
+ JSAMPROW outend;
+ int h_expand, v_expand;
+ int inrow, outrow;
+
+ h_expand = upsample->h_expand[compptr->component_index];
+ v_expand = upsample->v_expand[compptr->component_index];
+
+ inrow = outrow = 0;
+ while (outrow < cinfo->max_v_samp_factor) {
+ /* Generate one output row with proper horizontal expansion */
+ inptr = input_data[inrow];
+ outptr = output_data[outrow];
+ outend = outptr + cinfo->output_width;
+ while (outptr < outend) {
+ invalue = *inptr++; /* don't need GETJSAMPLE() here */
+ for (h = h_expand; h > 0; h--) {
+ *outptr++ = invalue;
+ }
+ }
+ /* Generate any additional output rows by duplicating the first one */
+ if (v_expand > 1) {
+ jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
+ v_expand-1, cinfo->output_width);
+ }
+ inrow++;
+ outrow += v_expand;
+ }
+}
+
+
+/*
+ * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
+ * It's still a box filter.
+ */
+
+METHODDEF void
+h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
+{
+ JSAMPARRAY output_data = *output_data_ptr;
+ register JSAMPROW inptr, outptr;
+ register JSAMPLE invalue;
+ JSAMPROW outend;
+ int inrow;
+
+ for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
+ inptr = input_data[inrow];
+ outptr = output_data[inrow];
+ outend = outptr + cinfo->output_width;
+ while (outptr < outend) {
+ invalue = *inptr++; /* don't need GETJSAMPLE() here */
+ *outptr++ = invalue;
+ *outptr++ = invalue;
+ }
+ }
+}
+
+
+/*
+ * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
+ * It's still a box filter.
+ */
+
+METHODDEF void
+h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
+{
+ JSAMPARRAY output_data = *output_data_ptr;
+ register JSAMPROW inptr, outptr;
+ register JSAMPLE invalue;
+ JSAMPROW outend;
+ int inrow, outrow;
+
+ inrow = outrow = 0;
+ while (outrow < cinfo->max_v_samp_factor) {
+ inptr = input_data[inrow];
+ outptr = output_data[outrow];
+ outend = outptr + cinfo->output_width;
+ while (outptr < outend) {
+ invalue = *inptr++; /* don't need GETJSAMPLE() here */
+ *outptr++ = invalue;
+ *outptr++ = invalue;
+ }
+ jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
+ 1, cinfo->output_width);
+ inrow++;
+ outrow += 2;
+ }
+}
+
+
+/*
+ * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
+ *
+ * The upsampling algorithm is linear interpolation between pixel centers,
+ * also known as a "triangle filter". This is a good compromise between
+ * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
+ * of the way between input pixel centers.
+ *
+ * A note about the "bias" calculations: when rounding fractional values to
+ * integer, we do not want to always round 0.5 up to the next integer.
+ * If we did that, we'd introduce a noticeable bias towards larger values.
+ * Instead, this code is arranged so that 0.5 will be rounded up or down at
+ * alternate pixel locations (a simple ordered dither pattern).
+ */
+
+METHODDEF void
+h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
+{
+ JSAMPARRAY output_data = *output_data_ptr;
+ register JSAMPROW inptr, outptr;
+ register int invalue;
+ register JDIMENSION colctr;
+ int inrow;
+
+ for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
+ inptr = input_data[inrow];
+ outptr = output_data[inrow];
+ /* Special case for first column */
+ invalue = GETJSAMPLE(*inptr++);
+ *outptr++ = (JSAMPLE) invalue;
+ *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
+
+ for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
+ /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
+ invalue = GETJSAMPLE(*inptr++) * 3;
+ *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
+ *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
+ }
+
+ /* Special case for last column */
+ invalue = GETJSAMPLE(*inptr);
+ *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
+ *outptr++ = (JSAMPLE) invalue;
+ }
+}
+
+
+/*
+ * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
+ * Again a triangle filter; see comments for h2v1 case, above.
+ *
+ * It is OK for us to reference the adjacent input rows because we demanded
+ * context from the main buffer controller (see initialization code).
+ */
+
+METHODDEF void
+h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
+{
+ JSAMPARRAY output_data = *output_data_ptr;
+ register JSAMPROW inptr0, inptr1, outptr;
+#if BITS_IN_JSAMPLE == 8
+ register int thiscolsum, lastcolsum, nextcolsum;
+#else
+ register INT32 thiscolsum, lastcolsum, nextcolsum;
+#endif
+ register JDIMENSION colctr;
+ int inrow, outrow, v;
+
+ inrow = outrow = 0;
+ while (outrow < cinfo->max_v_samp_factor) {
+ for (v = 0; v < 2; v++) {
+ /* inptr0 points to nearest input row, inptr1 points to next nearest */
+ inptr0 = input_data[inrow];
+ if (v == 0) /* next nearest is row above */
+ inptr1 = input_data[inrow-1];
+ else /* next nearest is row below */
+ inptr1 = input_data[inrow+1];
+ outptr = output_data[outrow++];
+
+ /* Special case for first column */
+ thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
+ nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
+ *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
+ *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
+ lastcolsum = thiscolsum; thiscolsum = nextcolsum;
+
+ for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
+ /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
+ /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
+ nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
+ *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
+ *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
+ lastcolsum = thiscolsum; thiscolsum = nextcolsum;
+ }
+
+ /* Special case for last column */
+ *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
+ *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
+ }
+ inrow++;
+ }
+}
+
+
+/*
+ * Module initialization routine for upsampling.
+ */
+
+GLOBAL void
+jinit_upsampler (j_decompress_ptr cinfo)
+{
+ my_upsample_ptr upsample;
+ int ci;
+ jpeg_component_info * compptr;
+ boolean need_buffer, do_fancy;
+ int h_in_group, v_in_group, h_out_group, v_out_group;
+
+ upsample = (my_upsample_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_upsampler));
+ cinfo->upsample = (struct jpeg_upsampler *) upsample;
+ upsample->pub.start_pass = start_pass_upsample;
+ upsample->pub.upsample = sep_upsample;
+ upsample->pub.need_context_rows = FALSE; /* until we find out differently */
+
+ if (cinfo->CCIR601_sampling) /* this isn't supported */
+ ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
+
+ /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
+ * so don't ask for it.
+ */
+ do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
+
+ /* Verify we can handle the sampling factors, select per-component methods,
+ * and create storage as needed.
+ */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Compute size of an "input group" after IDCT scaling. This many samples
+ * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
+ */
+ h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
+ cinfo->min_DCT_scaled_size;
+ v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
+ cinfo->min_DCT_scaled_size;
+ h_out_group = cinfo->max_h_samp_factor;
+ v_out_group = cinfo->max_v_samp_factor;
+ upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
+ need_buffer = TRUE;
+ if (! compptr->component_needed) {
+ /* Don't bother to upsample an uninteresting component. */
+ upsample->methods[ci] = noop_upsample;
+ need_buffer = FALSE;
+ } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
+ /* Fullsize components can be processed without any work. */
+ upsample->methods[ci] = fullsize_upsample;
+ need_buffer = FALSE;
+ } else if (h_in_group * 2 == h_out_group &&
+ v_in_group == v_out_group) {
+ /* Special cases for 2h1v upsampling */
+ if (do_fancy && compptr->downsampled_width > 2)
+ upsample->methods[ci] = h2v1_fancy_upsample;
+ else
+ upsample->methods[ci] = h2v1_upsample;
+ } else if (h_in_group * 2 == h_out_group &&
+ v_in_group * 2 == v_out_group) {
+ /* Special cases for 2h2v upsampling */
+ if (do_fancy && compptr->downsampled_width > 2) {
+ upsample->methods[ci] = h2v2_fancy_upsample;
+ upsample->pub.need_context_rows = TRUE;
+ } else
+ upsample->methods[ci] = h2v2_upsample;
+ } else if ((h_out_group % h_in_group) == 0 &&
+ (v_out_group % v_in_group) == 0) {
+ /* Generic integral-factors upsampling method */
+ upsample->methods[ci] = int_upsample;
+ upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
+ upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
+ } else
+ ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
+ if (need_buffer) {
+ upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) jround_up((long) cinfo->output_width,
+ (long) cinfo->max_h_samp_factor),
+ (JDIMENSION) cinfo->max_v_samp_factor);
+ }
+ }
+}
diff --git a/code/jpeg-6/jdtrans.c b/code/jpeg-6/jdtrans.c
new file mode 100755
index 0000000..eb873e0
--- /dev/null
+++ b/code/jpeg-6/jdtrans.c
@@ -0,0 +1,122 @@
+/*
+ * jdtrans.c
+ *
+ * Copyright (C) 1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains library routines for transcoding decompression,
+ * that is, reading raw DCT coefficient arrays from an input JPEG file.
+ * The routines in jdapimin.c will also be needed by a transcoder.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Forward declarations */
+LOCAL void transdecode_master_selection JPP((j_decompress_ptr cinfo));
+
+
+/*
+ * Read the coefficient arrays from a JPEG file.
+ * jpeg_read_header must be completed before calling this.
+ *
+ * The entire image is read into a set of virtual coefficient-block arrays,
+ * one per component. The return value is a pointer to the array of
+ * virtual-array descriptors. These can be manipulated directly via the
+ * JPEG memory manager, or handed off to jpeg_write_coefficients().
+ * To release the memory occupied by the virtual arrays, call
+ * jpeg_finish_decompress() when done with the data.
+ *
+ * Returns NULL if suspended. This case need be checked only if
+ * a suspending data source is used.
+ */
+
+GLOBAL jvirt_barray_ptr *
+jpeg_read_coefficients (j_decompress_ptr cinfo)
+{
+ if (cinfo->global_state == DSTATE_READY) {
+ /* First call: initialize active modules */
+ transdecode_master_selection(cinfo);
+ cinfo->global_state = DSTATE_RDCOEFS;
+ } else if (cinfo->global_state != DSTATE_RDCOEFS)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ /* Absorb whole file into the coef buffer */
+ for (;;) {
+ int retcode;
+ /* Call progress monitor hook if present */
+ if (cinfo->progress != NULL)
+ (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+ /* Absorb some more input */
+ retcode = (*cinfo->inputctl->consume_input) (cinfo);
+ if (retcode == JPEG_SUSPENDED)
+ return NULL;
+ if (retcode == JPEG_REACHED_EOI)
+ break;
+ /* Advance progress counter if appropriate */
+ if (cinfo->progress != NULL &&
+ (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
+ if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
+ /* startup underestimated number of scans; ratchet up one scan */
+ cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
+ }
+ }
+ }
+ /* Set state so that jpeg_finish_decompress does the right thing */
+ cinfo->global_state = DSTATE_STOPPING;
+ return cinfo->coef->coef_arrays;
+}
+
+
+/*
+ * Master selection of decompression modules for transcoding.
+ * This substitutes for jdmaster.c's initialization of the full decompressor.
+ */
+
+LOCAL void
+transdecode_master_selection (j_decompress_ptr cinfo)
+{
+ /* Entropy decoding: either Huffman or arithmetic coding. */
+ if (cinfo->arith_code) {
+ ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
+ } else {
+ if (cinfo->progressive_mode) {
+#ifdef D_PROGRESSIVE_SUPPORTED
+ jinit_phuff_decoder(cinfo);
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else
+ jinit_huff_decoder(cinfo);
+ }
+
+ /* Always get a full-image coefficient buffer. */
+ jinit_d_coef_controller(cinfo, TRUE);
+
+ /* We can now tell the memory manager to allocate virtual arrays. */
+ (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
+
+ /* Initialize input side of decompressor to consume first scan. */
+ (*cinfo->inputctl->start_input_pass) (cinfo);
+
+ /* Initialize progress monitoring. */
+ if (cinfo->progress != NULL) {
+ int nscans;
+ /* Estimate number of scans to set pass_limit. */
+ if (cinfo->progressive_mode) {
+ /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
+ nscans = 2 + 3 * cinfo->num_components;
+ } else if (cinfo->inputctl->has_multiple_scans) {
+ /* For a nonprogressive multiscan file, estimate 1 scan per component. */
+ nscans = cinfo->num_components;
+ } else {
+ nscans = 1;
+ }
+ cinfo->progress->pass_counter = 0L;
+ cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
+ cinfo->progress->completed_passes = 0;
+ cinfo->progress->total_passes = 1;
+ }
+}
diff --git a/code/jpeg-6/jerror.c b/code/jpeg-6/jerror.c
new file mode 100755
index 0000000..aff0a79
--- /dev/null
+++ b/code/jpeg-6/jerror.c
@@ -0,0 +1,232 @@
+/*
+ * jerror.c
+ *
+ * Copyright (C) 1991-1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains simple error-reporting and trace-message routines.
+ * These are suitable for Unix-like systems and others where writing to
+ * stderr is the right thing to do. Many applications will want to replace
+ * some or all of these routines.
+ *
+ * These routines are used by both the compression and decompression code.
+ */
+
+/* this is not a core library module, so it doesn't define JPEG_INTERNALS */
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jversion.h"
+#include "jerror.h"
+
+#include "../renderer/tr_local.h"
+
+#ifndef EXIT_FAILURE /* define exit() codes if not provided */
+#define EXIT_FAILURE 1
+#endif
+
+
+/*
+ * Create the message string table.
+ * We do this from the master message list in jerror.h by re-reading
+ * jerror.h with a suitable definition for macro JMESSAGE.
+ * The message table is made an external symbol just in case any applications
+ * want to refer to it directly.
+ */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jpeg_std_message_table jMsgTable
+#endif
+
+#define JMESSAGE(code,string) string ,
+
+const char * const jpeg_std_message_table[] = {
+#include "jerror.h"
+ NULL
+};
+
+
+/*
+ * Error exit handler: must not return to caller.
+ *
+ * Applications may override this if they want to get control back after
+ * an error. Typically one would longjmp somewhere instead of exiting.
+ * The setjmp buffer can be made a private field within an expanded error
+ * handler object. Note that the info needed to generate an error message
+ * is stored in the error object, so you can generate the message now or
+ * later, at your convenience.
+ * You should make sure that the JPEG object is cleaned up (with jpeg_abort
+ * or jpeg_destroy) at some point.
+ */
+
+METHODDEF void
+error_exit (j_common_ptr cinfo)
+{
+ char buffer[JMSG_LENGTH_MAX];
+
+ /* Create the message */
+ (*cinfo->err->format_message) (cinfo, buffer);
+
+ /* Let the memory manager delete any temp files before we die */
+ jpeg_destroy(cinfo);
+
+ ri.Error( ERR_FATAL, "%s\n", buffer );
+}
+
+
+/*
+ * Actual output of an error or trace message.
+ * Applications may override this method to send JPEG messages somewhere
+ * other than stderr.
+ */
+
+METHODDEF void
+output_message (j_common_ptr cinfo)
+{
+ char buffer[JMSG_LENGTH_MAX];
+
+ /* Create the message */
+ (*cinfo->err->format_message) (cinfo, buffer);
+
+ /* Send it to stderr, adding a newline */
+ ri.Printf(PRINT_ALL, "%s\n", buffer);
+}
+
+
+/*
+ * Decide whether to emit a trace or warning message.
+ * msg_level is one of:
+ * -1: recoverable corrupt-data warning, may want to abort.
+ * 0: important advisory messages (always display to user).
+ * 1: first level of tracing detail.
+ * 2,3,...: successively more detailed tracing messages.
+ * An application might override this method if it wanted to abort on warnings
+ * or change the policy about which messages to display.
+ */
+
+METHODDEF void
+emit_message (j_common_ptr cinfo, int msg_level)
+{
+ struct jpeg_error_mgr * err = cinfo->err;
+
+ if (msg_level < 0) {
+ /* It's a warning message. Since corrupt files may generate many warnings,
+ * the policy implemented here is to show only the first warning,
+ * unless trace_level >= 3.
+ */
+ if (err->num_warnings == 0 || err->trace_level >= 3)
+ (*err->output_message) (cinfo);
+ /* Always count warnings in num_warnings. */
+ err->num_warnings++;
+ } else {
+ /* It's a trace message. Show it if trace_level >= msg_level. */
+ if (err->trace_level >= msg_level)
+ (*err->output_message) (cinfo);
+ }
+}
+
+
+/*
+ * Format a message string for the most recent JPEG error or message.
+ * The message is stored into buffer, which should be at least JMSG_LENGTH_MAX
+ * characters. Note that no '\n' character is added to the string.
+ * Few applications should need to override this method.
+ */
+
+METHODDEF void
+format_message (j_common_ptr cinfo, char * buffer)
+{
+ struct jpeg_error_mgr * err = cinfo->err;
+ int msg_code = err->msg_code;
+ const char * msgtext = NULL;
+ const char * msgptr;
+ char ch;
+ boolean isstring;
+
+ /* Look up message string in proper table */
+ if (msg_code > 0 && msg_code <= err->last_jpeg_message) {
+ msgtext = err->jpeg_message_table[msg_code];
+ } else if (err->addon_message_table != NULL &&
+ msg_code >= err->first_addon_message &&
+ msg_code <= err->last_addon_message) {
+ msgtext = err->addon_message_table[msg_code - err->first_addon_message];
+ }
+
+ /* Defend against bogus message number */
+ if (msgtext == NULL) {
+ err->msg_parm.i[0] = msg_code;
+ msgtext = err->jpeg_message_table[0];
+ }
+
+ /* Check for string parameter, as indicated by %s in the message text */
+ isstring = FALSE;
+ msgptr = msgtext;
+ while ((ch = *msgptr++) != '\0') {
+ if (ch == '%') {
+ if (*msgptr == 's') isstring = TRUE;
+ break;
+ }
+ }
+
+ /* Format the message into the passed buffer */
+ if (isstring)
+ sprintf(buffer, msgtext, err->msg_parm.s);
+ else
+ sprintf(buffer, msgtext,
+ err->msg_parm.i[0], err->msg_parm.i[1],
+ err->msg_parm.i[2], err->msg_parm.i[3],
+ err->msg_parm.i[4], err->msg_parm.i[5],
+ err->msg_parm.i[6], err->msg_parm.i[7]);
+}
+
+
+/*
+ * Reset error state variables at start of a new image.
+ * This is called during compression startup to reset trace/error
+ * processing to default state, without losing any application-specific
+ * method pointers. An application might possibly want to override
+ * this method if it has additional error processing state.
+ */
+
+METHODDEF void
+reset_error_mgr (j_common_ptr cinfo)
+{
+ cinfo->err->num_warnings = 0;
+ /* trace_level is not reset since it is an application-supplied parameter */
+ cinfo->err->msg_code = 0; /* may be useful as a flag for "no error" */
+}
+
+
+/*
+ * Fill in the standard error-handling methods in a jpeg_error_mgr object.
+ * Typical call is:
+ * struct jpeg_compress_struct cinfo;
+ * struct jpeg_error_mgr err;
+ *
+ * cinfo.err = jpeg_std_error(&err);
+ * after which the application may override some of the methods.
+ */
+
+GLOBAL struct jpeg_error_mgr *
+jpeg_std_error (struct jpeg_error_mgr * err)
+{
+ err->error_exit = error_exit;
+ err->emit_message = emit_message;
+ err->output_message = output_message;
+ err->format_message = format_message;
+ err->reset_error_mgr = reset_error_mgr;
+
+ err->trace_level = 0; /* default = no tracing */
+ err->num_warnings = 0; /* no warnings emitted yet */
+ err->msg_code = 0; /* may be useful as a flag for "no error" */
+
+ /* Initialize message table pointers */
+ err->jpeg_message_table = jpeg_std_message_table;
+ err->last_jpeg_message = (int) JMSG_LASTMSGCODE - 1;
+
+ err->addon_message_table = NULL;
+ err->first_addon_message = 0; /* for safety */
+ err->last_addon_message = 0;
+
+ return err;
+}
diff --git a/code/jpeg-6/jerror.h b/code/jpeg-6/jerror.h
new file mode 100755
index 0000000..0ffb8b4
--- /dev/null
+++ b/code/jpeg-6/jerror.h
@@ -0,0 +1,273 @@
+/*
+ * jerror.h
+ *
+ * Copyright (C) 1994-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file defines the error and message codes for the JPEG library.
+ * Edit this file to add new codes, or to translate the message strings to
+ * some other language.
+ * A set of error-reporting macros are defined too. Some applications using
+ * the JPEG library may wish to include this file to get the error codes
+ * and/or the macros.
+ */
+
+/*
+ * To define the enum list of message codes, include this file without
+ * defining macro JMESSAGE. To create a message string table, include it
+ * again with a suitable JMESSAGE definition (see jerror.c for an example).
+ */
+#ifndef JMESSAGE
+#ifndef JERROR_H
+/* First time through, define the enum list */
+#define JMAKE_ENUM_LIST
+#else
+/* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
+#define JMESSAGE(code,string)
+#endif /* JERROR_H */
+#endif /* JMESSAGE */
+
+#ifdef JMAKE_ENUM_LIST
+
+typedef enum {
+
+#define JMESSAGE(code,string) code ,
+
+#endif /* JMAKE_ENUM_LIST */
+
+JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
+
+/* For maintenance convenience, list is alphabetical by message code name */
+JMESSAGE(JERR_ARITH_NOTIMPL,
+ "Sorry, there are legal restrictions on arithmetic coding")
+JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
+JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
+JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
+JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
+JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
+JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
+JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
+JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
+JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
+JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
+JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
+JMESSAGE(JERR_BAD_PROGRESSION,
+ "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
+JMESSAGE(JERR_BAD_PROG_SCRIPT,
+ "Invalid progressive parameters at scan script entry %d")
+JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
+JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
+JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
+JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
+JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
+JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
+JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
+JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
+JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
+JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
+JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
+JMESSAGE(JERR_DHT_COUNTS, "Bogus DHT counts")
+JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
+JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
+JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
+JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
+JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
+JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
+JMESSAGE(JERR_FILE_READ, "Input file read error")
+JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
+JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
+JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
+JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
+JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
+JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
+JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
+JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
+ "Cannot transcode due to multiple use of quantization table %d")
+JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
+JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
+JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
+JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
+JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
+JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
+JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
+JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
+JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
+JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
+JMESSAGE(JERR_QUANT_COMPONENTS,
+ "Cannot quantize more than %d color components")
+JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
+JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
+JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
+JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
+JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
+JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
+JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
+JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
+JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
+JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
+JMESSAGE(JERR_TFILE_WRITE,
+ "Write failed on temporary file --- out of disk space?")
+JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
+JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
+JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
+JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
+JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
+JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
+JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
+JMESSAGE(JMSG_VERSION, JVERSION)
+JMESSAGE(JTRC_16BIT_TABLES,
+ "Caution: quantization tables are too coarse for baseline JPEG")
+JMESSAGE(JTRC_ADOBE,
+ "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
+JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
+JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
+JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
+JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
+JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
+JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
+JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
+JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
+JMESSAGE(JTRC_EOI, "End Of Image")
+JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
+JMESSAGE(JTRC_JFIF, "JFIF APP0 marker, density %dx%d %d")
+JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
+ "Warning: thumbnail image size does not match data length %u")
+JMESSAGE(JTRC_JFIF_MINOR, "Unknown JFIF minor revision number %d.%02d")
+JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
+JMESSAGE(JTRC_MISC_MARKER, "Skipping marker 0x%02x, length %u")
+JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
+JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
+JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
+JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
+JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
+JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
+JMESSAGE(JTRC_RST, "RST%d")
+JMESSAGE(JTRC_SMOOTH_NOTIMPL,
+ "Smoothing not supported with nonstandard sampling ratios")
+JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
+JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
+JMESSAGE(JTRC_SOI, "Start of Image")
+JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
+JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
+JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
+JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
+JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
+JMESSAGE(JTRC_UNKNOWN_IDS,
+ "Unrecognized component IDs %d %d %d, assuming YCbCr")
+JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
+JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
+JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
+JMESSAGE(JWRN_BOGUS_PROGRESSION,
+ "Inconsistent progression sequence for component %d coefficient %d")
+JMESSAGE(JWRN_EXTRANEOUS_DATA,
+ "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
+JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
+JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
+JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
+JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
+JMESSAGE(JWRN_MUST_RESYNC,
+ "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
+JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
+JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
+
+#ifdef JMAKE_ENUM_LIST
+
+ JMSG_LASTMSGCODE
+} J_MESSAGE_CODE;
+
+#undef JMAKE_ENUM_LIST
+#endif /* JMAKE_ENUM_LIST */
+
+/* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
+#undef JMESSAGE
+
+
+#ifndef JERROR_H
+#define JERROR_H
+
+/* Macros to simplify using the error and trace message stuff */
+/* The first parameter is either type of cinfo pointer */
+
+/* Fatal errors (print message and exit) */
+#define ERREXIT(cinfo,code) \
+ ((cinfo)->err->msg_code = (code), \
+ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXIT1(cinfo,code,p1) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXIT2(cinfo,code,p1,p2) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (cinfo)->err->msg_parm.i[1] = (p2), \
+ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXIT3(cinfo,code,p1,p2,p3) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (cinfo)->err->msg_parm.i[1] = (p2), \
+ (cinfo)->err->msg_parm.i[2] = (p3), \
+ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (cinfo)->err->msg_parm.i[1] = (p2), \
+ (cinfo)->err->msg_parm.i[2] = (p3), \
+ (cinfo)->err->msg_parm.i[3] = (p4), \
+ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXITS(cinfo,code,str) \
+ ((cinfo)->err->msg_code = (code), \
+ strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
+ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+
+#define MAKESTMT(stuff) do { stuff } while (0)
+
+/* Nonfatal errors (we can keep going, but the data is probably corrupt) */
+#define WARNMS(cinfo,code) \
+ ((cinfo)->err->msg_code = (code), \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
+#define WARNMS1(cinfo,code,p1) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
+#define WARNMS2(cinfo,code,p1,p2) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (cinfo)->err->msg_parm.i[1] = (p2), \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
+
+/* Informational/debugging messages */
+#define TRACEMS(cinfo,lvl,code) \
+ ((cinfo)->err->msg_code = (code), \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
+#define TRACEMS1(cinfo,lvl,code,p1) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
+#define TRACEMS2(cinfo,lvl,code,p1,p2) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (cinfo)->err->msg_parm.i[1] = (p2), \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
+#define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
+ MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
+ _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
+ (cinfo)->err->msg_code = (code); \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
+#define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
+ MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
+ _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
+ (cinfo)->err->msg_code = (code); \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
+#define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
+ MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
+ _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
+ _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
+ (cinfo)->err->msg_code = (code); \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
+#define TRACEMSS(cinfo,lvl,code,str) \
+ ((cinfo)->err->msg_code = (code), \
+ strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
+
+#endif /* JERROR_H */
diff --git a/code/jpeg-6/jfdctflt.c b/code/jpeg-6/jfdctflt.c
new file mode 100755
index 0000000..1509b88
--- /dev/null
+++ b/code/jpeg-6/jfdctflt.c
@@ -0,0 +1,168 @@
+/*
+ * jfdctflt.c
+ *
+ * Copyright (C) 1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains a floating-point implementation of the
+ * forward DCT (Discrete Cosine Transform).
+ *
+ * This implementation should be more accurate than either of the integer
+ * DCT implementations. However, it may not give the same results on all
+ * machines because of differences in roundoff behavior. Speed will depend
+ * on the hardware's floating point capacity.
+ *
+ * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT
+ * on each column. Direct algorithms are also available, but they are
+ * much more complex and seem not to be any faster when reduced to code.
+ *
+ * This implementation is based on Arai, Agui, and Nakajima's algorithm for
+ * scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in
+ * Japanese, but the algorithm is described in the Pennebaker & Mitchell
+ * JPEG textbook (see REFERENCES section in file README). The following code
+ * is based directly on figure 4-8 in P&M.
+ * While an 8-point DCT cannot be done in less than 11 multiplies, it is
+ * possible to arrange the computation so that many of the multiplies are
+ * simple scalings of the final outputs. These multiplies can then be
+ * folded into the multiplications or divisions by the JPEG quantization
+ * table entries. The AA&N method leaves only 5 multiplies and 29 adds
+ * to be done in the DCT itself.
+ * The primary disadvantage of this method is that with a fixed-point
+ * implementation, accuracy is lost due to imprecise representation of the
+ * scaled quantization values. However, that problem does not arise if
+ * we use floating point arithmetic.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jdct.h" /* Private declarations for DCT subsystem */
+
+#ifdef DCT_FLOAT_SUPPORTED
+
+
+/*
+ * This module is specialized to the case DCTSIZE = 8.
+ */
+
+#if DCTSIZE != 8
+ Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
+#endif
+
+
+/*
+ * Perform the forward DCT on one block of samples.
+ */
+
+GLOBAL void
+jpeg_fdct_float (FAST_FLOAT * data)
+{
+ FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
+ FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
+ FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
+ FAST_FLOAT *dataptr;
+ int ctr;
+
+ /* Pass 1: process rows. */
+
+ dataptr = data;
+ for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
+ tmp0 = dataptr[0] + dataptr[7];
+ tmp7 = dataptr[0] - dataptr[7];
+ tmp1 = dataptr[1] + dataptr[6];
+ tmp6 = dataptr[1] - dataptr[6];
+ tmp2 = dataptr[2] + dataptr[5];
+ tmp5 = dataptr[2] - dataptr[5];
+ tmp3 = dataptr[3] + dataptr[4];
+ tmp4 = dataptr[3] - dataptr[4];
+
+ /* Even part */
+
+ tmp10 = tmp0 + tmp3; /* phase 2 */
+ tmp13 = tmp0 - tmp3;
+ tmp11 = tmp1 + tmp2;
+ tmp12 = tmp1 - tmp2;
+
+ dataptr[0] = tmp10 + tmp11; /* phase 3 */
+ dataptr[4] = tmp10 - tmp11;
+
+ z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
+ dataptr[2] = tmp13 + z1; /* phase 5 */
+ dataptr[6] = tmp13 - z1;
+
+ /* Odd part */
+
+ tmp10 = tmp4 + tmp5; /* phase 2 */
+ tmp11 = tmp5 + tmp6;
+ tmp12 = tmp6 + tmp7;
+
+ /* The rotator is modified from fig 4-8 to avoid extra negations. */
+ z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
+ z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
+ z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
+ z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
+
+ z11 = tmp7 + z3; /* phase 5 */
+ z13 = tmp7 - z3;
+
+ dataptr[5] = z13 + z2; /* phase 6 */
+ dataptr[3] = z13 - z2;
+ dataptr[1] = z11 + z4;
+ dataptr[7] = z11 - z4;
+
+ dataptr += DCTSIZE; /* advance pointer to next row */
+ }
+
+ /* Pass 2: process columns. */
+
+ dataptr = data;
+ for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
+ tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
+ tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
+ tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
+ tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
+ tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
+ tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
+ tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
+ tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
+
+ /* Even part */
+
+ tmp10 = tmp0 + tmp3; /* phase 2 */
+ tmp13 = tmp0 - tmp3;
+ tmp11 = tmp1 + tmp2;
+ tmp12 = tmp1 - tmp2;
+
+ dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
+ dataptr[DCTSIZE*4] = tmp10 - tmp11;
+
+ z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
+ dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
+ dataptr[DCTSIZE*6] = tmp13 - z1;
+
+ /* Odd part */
+
+ tmp10 = tmp4 + tmp5; /* phase 2 */
+ tmp11 = tmp5 + tmp6;
+ tmp12 = tmp6 + tmp7;
+
+ /* The rotator is modified from fig 4-8 to avoid extra negations. */
+ z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
+ z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
+ z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
+ z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
+
+ z11 = tmp7 + z3; /* phase 5 */
+ z13 = tmp7 - z3;
+
+ dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
+ dataptr[DCTSIZE*3] = z13 - z2;
+ dataptr[DCTSIZE*1] = z11 + z4;
+ dataptr[DCTSIZE*7] = z11 - z4;
+
+ dataptr++; /* advance pointer to next column */
+ }
+}
+
+#endif /* DCT_FLOAT_SUPPORTED */
diff --git a/code/jpeg-6/jfdctfst.c b/code/jpeg-6/jfdctfst.c
new file mode 100755
index 0000000..e311fc0
--- /dev/null
+++ b/code/jpeg-6/jfdctfst.c
@@ -0,0 +1,224 @@
+/*
+ * jfdctfst.c
+ *
+ * Copyright (C) 1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains a fast, not so accurate integer implementation of the
+ * forward DCT (Discrete Cosine Transform).
+ *
+ * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT
+ * on each column. Direct algorithms are also available, but they are
+ * much more complex and seem not to be any faster when reduced to code.
+ *
+ * This implementation is based on Arai, Agui, and Nakajima's algorithm for
+ * scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in
+ * Japanese, but the algorithm is described in the Pennebaker & Mitchell
+ * JPEG textbook (see REFERENCES section in file README). The following code
+ * is based directly on figure 4-8 in P&M.
+ * While an 8-point DCT cannot be done in less than 11 multiplies, it is
+ * possible to arrange the computation so that many of the multiplies are
+ * simple scalings of the final outputs. These multiplies can then be
+ * folded into the multiplications or divisions by the JPEG quantization
+ * table entries. The AA&N method leaves only 5 multiplies and 29 adds
+ * to be done in the DCT itself.
+ * The primary disadvantage of this method is that with fixed-point math,
+ * accuracy is lost due to imprecise representation of the scaled
+ * quantization values. The smaller the quantization table entry, the less
+ * precise the scaled value, so this implementation does worse with high-
+ * quality-setting files than with low-quality ones.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jdct.h" /* Private declarations for DCT subsystem */
+
+#ifdef DCT_IFAST_SUPPORTED
+
+
+/*
+ * This module is specialized to the case DCTSIZE = 8.
+ */
+
+#if DCTSIZE != 8
+ Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
+#endif
+
+
+/* Scaling decisions are generally the same as in the LL&M algorithm;
+ * see jfdctint.c for more details. However, we choose to descale
+ * (right shift) multiplication products as soon as they are formed,
+ * rather than carrying additional fractional bits into subsequent additions.
+ * This compromises accuracy slightly, but it lets us save a few shifts.
+ * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
+ * everywhere except in the multiplications proper; this saves a good deal
+ * of work on 16-bit-int machines.
+ *
+ * Again to save a few shifts, the intermediate results between pass 1 and
+ * pass 2 are not upscaled, but are represented only to integral precision.
+ *
+ * A final compromise is to represent the multiplicative constants to only
+ * 8 fractional bits, rather than 13. This saves some shifting work on some
+ * machines, and may also reduce the cost of multiplication (since there
+ * are fewer one-bits in the constants).
+ */
+
+#define CONST_BITS 8
+
+
+/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
+ * causing a lot of useless floating-point operations at run time.
+ * To get around this we use the following pre-calculated constants.
+ * If you change CONST_BITS you may want to add appropriate values.
+ * (With a reasonable C compiler, you can just rely on the FIX() macro...)
+ */
+
+#if CONST_BITS == 8
+#define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
+#define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
+#define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
+#define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
+#else
+#define FIX_0_382683433 FIX(0.382683433)
+#define FIX_0_541196100 FIX(0.541196100)
+#define FIX_0_707106781 FIX(0.707106781)
+#define FIX_1_306562965 FIX(1.306562965)
+#endif
+
+
+/* We can gain a little more speed, with a further compromise in accuracy,
+ * by omitting the addition in a descaling shift. This yields an incorrectly
+ * rounded result half the time...
+ */
+
+#ifndef USE_ACCURATE_ROUNDING
+#undef DESCALE
+#define DESCALE(x,n) RIGHT_SHIFT(x, n)
+#endif
+
+
+/* Multiply a DCTELEM variable by an INT32 constant, and immediately
+ * descale to yield a DCTELEM result.
+ */
+
+#define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
+
+
+/*
+ * Perform the forward DCT on one block of samples.
+ */
+
+GLOBAL void
+jpeg_fdct_ifast (DCTELEM * data)
+{
+ DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
+ DCTELEM tmp10, tmp11, tmp12, tmp13;
+ DCTELEM z1, z2, z3, z4, z5, z11, z13;
+ DCTELEM *dataptr;
+ int ctr;
+ SHIFT_TEMPS
+
+ /* Pass 1: process rows. */
+
+ dataptr = data;
+ for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
+ tmp0 = dataptr[0] + dataptr[7];
+ tmp7 = dataptr[0] - dataptr[7];
+ tmp1 = dataptr[1] + dataptr[6];
+ tmp6 = dataptr[1] - dataptr[6];
+ tmp2 = dataptr[2] + dataptr[5];
+ tmp5 = dataptr[2] - dataptr[5];
+ tmp3 = dataptr[3] + dataptr[4];
+ tmp4 = dataptr[3] - dataptr[4];
+
+ /* Even part */
+
+ tmp10 = tmp0 + tmp3; /* phase 2 */
+ tmp13 = tmp0 - tmp3;
+ tmp11 = tmp1 + tmp2;
+ tmp12 = tmp1 - tmp2;
+
+ dataptr[0] = tmp10 + tmp11; /* phase 3 */
+ dataptr[4] = tmp10 - tmp11;
+
+ z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
+ dataptr[2] = tmp13 + z1; /* phase 5 */
+ dataptr[6] = tmp13 - z1;
+
+ /* Odd part */
+
+ tmp10 = tmp4 + tmp5; /* phase 2 */
+ tmp11 = tmp5 + tmp6;
+ tmp12 = tmp6 + tmp7;
+
+ /* The rotator is modified from fig 4-8 to avoid extra negations. */
+ z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
+ z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
+ z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
+ z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
+
+ z11 = tmp7 + z3; /* phase 5 */
+ z13 = tmp7 - z3;
+
+ dataptr[5] = z13 + z2; /* phase 6 */
+ dataptr[3] = z13 - z2;
+ dataptr[1] = z11 + z4;
+ dataptr[7] = z11 - z4;
+
+ dataptr += DCTSIZE; /* advance pointer to next row */
+ }
+
+ /* Pass 2: process columns. */
+
+ dataptr = data;
+ for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
+ tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
+ tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
+ tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
+ tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
+ tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
+ tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
+ tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
+ tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
+
+ /* Even part */
+
+ tmp10 = tmp0 + tmp3; /* phase 2 */
+ tmp13 = tmp0 - tmp3;
+ tmp11 = tmp1 + tmp2;
+ tmp12 = tmp1 - tmp2;
+
+ dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
+ dataptr[DCTSIZE*4] = tmp10 - tmp11;
+
+ z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
+ dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
+ dataptr[DCTSIZE*6] = tmp13 - z1;
+
+ /* Odd part */
+
+ tmp10 = tmp4 + tmp5; /* phase 2 */
+ tmp11 = tmp5 + tmp6;
+ tmp12 = tmp6 + tmp7;
+
+ /* The rotator is modified from fig 4-8 to avoid extra negations. */
+ z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
+ z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
+ z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
+ z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
+
+ z11 = tmp7 + z3; /* phase 5 */
+ z13 = tmp7 - z3;
+
+ dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
+ dataptr[DCTSIZE*3] = z13 - z2;
+ dataptr[DCTSIZE*1] = z11 + z4;
+ dataptr[DCTSIZE*7] = z11 - z4;
+
+ dataptr++; /* advance pointer to next column */
+ }
+}
+
+#endif /* DCT_IFAST_SUPPORTED */
diff --git a/code/jpeg-6/jfdctint.c b/code/jpeg-6/jfdctint.c
new file mode 100755
index 0000000..168fd0b
--- /dev/null
+++ b/code/jpeg-6/jfdctint.c
@@ -0,0 +1,283 @@
+/*
+ * jfdctint.c
+ *
+ * Copyright (C) 1991-1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains a slow-but-accurate integer implementation of the
+ * forward DCT (Discrete Cosine Transform).
+ *
+ * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT
+ * on each column. Direct algorithms are also available, but they are
+ * much more complex and seem not to be any faster when reduced to code.
+ *
+ * This implementation is based on an algorithm described in
+ * C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT
+ * Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics,
+ * Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991.
+ * The primary algorithm described there uses 11 multiplies and 29 adds.
+ * We use their alternate method with 12 multiplies and 32 adds.
+ * The advantage of this method is that no data path contains more than one
+ * multiplication; this allows a very simple and accurate implementation in
+ * scaled fixed-point arithmetic, with a minimal number of shifts.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jdct.h" /* Private declarations for DCT subsystem */
+
+#ifdef DCT_ISLOW_SUPPORTED
+
+
+/*
+ * This module is specialized to the case DCTSIZE = 8.
+ */
+
+#if DCTSIZE != 8
+ Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
+#endif
+
+
+/*
+ * The poop on this scaling stuff is as follows:
+ *
+ * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
+ * larger than the true DCT outputs. The final outputs are therefore
+ * a factor of N larger than desired; since N=8 this can be cured by
+ * a simple right shift at the end of the algorithm. The advantage of
+ * this arrangement is that we save two multiplications per 1-D DCT,
+ * because the y0 and y4 outputs need not be divided by sqrt(N).
+ * In the IJG code, this factor of 8 is removed by the quantization step
+ * (in jcdctmgr.c), NOT in this module.
+ *
+ * We have to do addition and subtraction of the integer inputs, which
+ * is no problem, and multiplication by fractional constants, which is
+ * a problem to do in integer arithmetic. We multiply all the constants
+ * by CONST_SCALE and convert them to integer constants (thus retaining
+ * CONST_BITS bits of precision in the constants). After doing a
+ * multiplication we have to divide the product by CONST_SCALE, with proper
+ * rounding, to produce the correct output. This division can be done
+ * cheaply as a right shift of CONST_BITS bits. We postpone shifting
+ * as long as possible so that partial sums can be added together with
+ * full fractional precision.
+ *
+ * The outputs of the first pass are scaled up by PASS1_BITS bits so that
+ * they are represented to better-than-integral precision. These outputs
+ * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
+ * with the recommended scaling. (For 12-bit sample data, the intermediate
+ * array is INT32 anyway.)
+ *
+ * To avoid overflow of the 32-bit intermediate results in pass 2, we must
+ * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
+ * shows that the values given below are the most effective.
+ */
+
+#if BITS_IN_JSAMPLE == 8
+#define CONST_BITS 13
+#define PASS1_BITS 2
+#else
+#define CONST_BITS 13
+#define PASS1_BITS 1 /* lose a little precision to avoid overflow */
+#endif
+
+/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
+ * causing a lot of useless floating-point operations at run time.
+ * To get around this we use the following pre-calculated constants.
+ * If you change CONST_BITS you may want to add appropriate values.
+ * (With a reasonable C compiler, you can just rely on the FIX() macro...)
+ */
+
+#if CONST_BITS == 13
+#define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
+#define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
+#define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
+#define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
+#define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
+#define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
+#define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
+#define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
+#define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
+#define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
+#define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
+#define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
+#else
+#define FIX_0_298631336 FIX(0.298631336)
+#define FIX_0_390180644 FIX(0.390180644)
+#define FIX_0_541196100 FIX(0.541196100)
+#define FIX_0_765366865 FIX(0.765366865)
+#define FIX_0_899976223 FIX(0.899976223)
+#define FIX_1_175875602 FIX(1.175875602)
+#define FIX_1_501321110 FIX(1.501321110)
+#define FIX_1_847759065 FIX(1.847759065)
+#define FIX_1_961570560 FIX(1.961570560)
+#define FIX_2_053119869 FIX(2.053119869)
+#define FIX_2_562915447 FIX(2.562915447)
+#define FIX_3_072711026 FIX(3.072711026)
+#endif
+
+
+/* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
+ * For 8-bit samples with the recommended scaling, all the variable
+ * and constant values involved are no more than 16 bits wide, so a
+ * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
+ * For 12-bit samples, a full 32-bit multiplication will be needed.
+ */
+
+#if BITS_IN_JSAMPLE == 8
+#define MULTIPLY(var,const) MULTIPLY16C16(var,const)
+#else
+#define MULTIPLY(var,const) ((var) * (const))
+#endif
+
+
+/*
+ * Perform the forward DCT on one block of samples.
+ */
+
+GLOBAL void
+jpeg_fdct_islow (DCTELEM * data)
+{
+ INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
+ INT32 tmp10, tmp11, tmp12, tmp13;
+ INT32 z1, z2, z3, z4, z5;
+ DCTELEM *dataptr;
+ int ctr;
+ SHIFT_TEMPS
+
+ /* Pass 1: process rows. */
+ /* Note results are scaled up by sqrt(8) compared to a true DCT; */
+ /* furthermore, we scale the results by 2**PASS1_BITS. */
+
+ dataptr = data;
+ for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
+ tmp0 = dataptr[0] + dataptr[7];
+ tmp7 = dataptr[0] - dataptr[7];
+ tmp1 = dataptr[1] + dataptr[6];
+ tmp6 = dataptr[1] - dataptr[6];
+ tmp2 = dataptr[2] + dataptr[5];
+ tmp5 = dataptr[2] - dataptr[5];
+ tmp3 = dataptr[3] + dataptr[4];
+ tmp4 = dataptr[3] - dataptr[4];
+
+ /* Even part per LL&M figure 1 --- note that published figure is faulty;
+ * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
+ */
+
+ tmp10 = tmp0 + tmp3;
+ tmp13 = tmp0 - tmp3;
+ tmp11 = tmp1 + tmp2;
+ tmp12 = tmp1 - tmp2;
+
+ dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
+ dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
+
+ z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
+ dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
+ CONST_BITS-PASS1_BITS);
+ dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
+ CONST_BITS-PASS1_BITS);
+
+ /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
+ * cK represents cos(K*pi/16).
+ * i0..i3 in the paper are tmp4..tmp7 here.
+ */
+
+ z1 = tmp4 + tmp7;
+ z2 = tmp5 + tmp6;
+ z3 = tmp4 + tmp6;
+ z4 = tmp5 + tmp7;
+ z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
+
+ tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+
+ z3 += z5;
+ z4 += z5;
+
+ dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
+ dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
+ dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
+ dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
+
+ dataptr += DCTSIZE; /* advance pointer to next row */
+ }
+
+ /* Pass 2: process columns.
+ * We remove the PASS1_BITS scaling, but leave the results scaled up
+ * by an overall factor of 8.
+ */
+
+ dataptr = data;
+ for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
+ tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
+ tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
+ tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
+ tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
+ tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
+ tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
+ tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
+ tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
+
+ /* Even part per LL&M figure 1 --- note that published figure is faulty;
+ * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
+ */
+
+ tmp10 = tmp0 + tmp3;
+ tmp13 = tmp0 - tmp3;
+ tmp11 = tmp1 + tmp2;
+ tmp12 = tmp1 - tmp2;
+
+ dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
+ dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
+
+ z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
+ dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
+ CONST_BITS+PASS1_BITS);
+ dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
+ CONST_BITS+PASS1_BITS);
+
+ /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
+ * cK represents cos(K*pi/16).
+ * i0..i3 in the paper are tmp4..tmp7 here.
+ */
+
+ z1 = tmp4 + tmp7;
+ z2 = tmp5 + tmp6;
+ z3 = tmp4 + tmp6;
+ z4 = tmp5 + tmp7;
+ z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
+
+ tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+
+ z3 += z5;
+ z4 += z5;
+
+ dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
+ CONST_BITS+PASS1_BITS);
+ dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
+ CONST_BITS+PASS1_BITS);
+ dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
+ CONST_BITS+PASS1_BITS);
+ dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
+ CONST_BITS+PASS1_BITS);
+
+ dataptr++; /* advance pointer to next column */
+ }
+}
+
+#endif /* DCT_ISLOW_SUPPORTED */
diff --git a/code/jpeg-6/jidctflt.c b/code/jpeg-6/jidctflt.c
new file mode 100755
index 0000000..2e25c44
--- /dev/null
+++ b/code/jpeg-6/jidctflt.c
@@ -0,0 +1,241 @@
+/*
+ * jidctflt.c
+ *
+ * Copyright (C) 1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains a floating-point implementation of the
+ * inverse DCT (Discrete Cosine Transform). In the IJG code, this routine
+ * must also perform dequantization of the input coefficients.
+ *
+ * This implementation should be more accurate than either of the integer
+ * IDCT implementations. However, it may not give the same results on all
+ * machines because of differences in roundoff behavior. Speed will depend
+ * on the hardware's floating point capacity.
+ *
+ * A 2-D IDCT can be done by 1-D IDCT on each column followed by 1-D IDCT
+ * on each row (or vice versa, but it's more convenient to emit a row at
+ * a time). Direct algorithms are also available, but they are much more
+ * complex and seem not to be any faster when reduced to code.
+ *
+ * This implementation is based on Arai, Agui, and Nakajima's algorithm for
+ * scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in
+ * Japanese, but the algorithm is described in the Pennebaker & Mitchell
+ * JPEG textbook (see REFERENCES section in file README). The following code
+ * is based directly on figure 4-8 in P&M.
+ * While an 8-point DCT cannot be done in less than 11 multiplies, it is
+ * possible to arrange the computation so that many of the multiplies are
+ * simple scalings of the final outputs. These multiplies can then be
+ * folded into the multiplications or divisions by the JPEG quantization
+ * table entries. The AA&N method leaves only 5 multiplies and 29 adds
+ * to be done in the DCT itself.
+ * The primary disadvantage of this method is that with a fixed-point
+ * implementation, accuracy is lost due to imprecise representation of the
+ * scaled quantization values. However, that problem does not arise if
+ * we use floating point arithmetic.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jdct.h" /* Private declarations for DCT subsystem */
+
+#ifdef DCT_FLOAT_SUPPORTED
+
+
+/*
+ * This module is specialized to the case DCTSIZE = 8.
+ */
+
+#if DCTSIZE != 8
+ Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
+#endif
+
+
+/* Dequantize a coefficient by multiplying it by the multiplier-table
+ * entry; produce a float result.
+ */
+
+#define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
+
+
+/*
+ * Perform dequantization and inverse DCT on one block of coefficients.
+ */
+
+GLOBAL void
+jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block,
+ JSAMPARRAY output_buf, JDIMENSION output_col)
+{
+ FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
+ FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
+ FAST_FLOAT z5, z10, z11, z12, z13;
+ JCOEFPTR inptr;
+ FLOAT_MULT_TYPE * quantptr;
+ FAST_FLOAT * wsptr;
+ JSAMPROW outptr;
+ JSAMPLE *range_limit = IDCT_range_limit(cinfo);
+ int ctr;
+ FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
+ SHIFT_TEMPS
+
+ /* Pass 1: process columns from input, store into work array. */
+
+ inptr = coef_block;
+ quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
+ wsptr = workspace;
+ for (ctr = DCTSIZE; ctr > 0; ctr--) {
+ /* Due to quantization, we will usually find that many of the input
+ * coefficients are zero, especially the AC terms. We can exploit this
+ * by short-circuiting the IDCT calculation for any column in which all
+ * the AC terms are zero. In that case each output is equal to the
+ * DC coefficient (with scale factor as needed).
+ * With typical images and quantization tables, half or more of the
+ * column DCT calculations can be simplified this way.
+ */
+
+ if ((inptr[DCTSIZE*1] | inptr[DCTSIZE*2] | inptr[DCTSIZE*3] |
+ inptr[DCTSIZE*4] | inptr[DCTSIZE*5] | inptr[DCTSIZE*6] |
+ inptr[DCTSIZE*7]) == 0) {
+ /* AC terms all zero */
+ FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
+
+ wsptr[DCTSIZE*0] = dcval;
+ wsptr[DCTSIZE*1] = dcval;
+ wsptr[DCTSIZE*2] = dcval;
+ wsptr[DCTSIZE*3] = dcval;
+ wsptr[DCTSIZE*4] = dcval;
+ wsptr[DCTSIZE*5] = dcval;
+ wsptr[DCTSIZE*6] = dcval;
+ wsptr[DCTSIZE*7] = dcval;
+
+ inptr++; /* advance pointers to next column */
+ quantptr++;
+ wsptr++;
+ continue;
+ }
+
+ /* Even part */
+
+ tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
+ tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
+ tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
+ tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
+
+ tmp10 = tmp0 + tmp2; /* phase 3 */
+ tmp11 = tmp0 - tmp2;
+
+ tmp13 = tmp1 + tmp3; /* phases 5-3 */
+ tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
+
+ tmp0 = tmp10 + tmp13; /* phase 2 */
+ tmp3 = tmp10 - tmp13;
+ tmp1 = tmp11 + tmp12;
+ tmp2 = tmp11 - tmp12;
+
+ /* Odd part */
+
+ tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
+ tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
+ tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
+ tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
+
+ z13 = tmp6 + tmp5; /* phase 6 */
+ z10 = tmp6 - tmp5;
+ z11 = tmp4 + tmp7;
+ z12 = tmp4 - tmp7;
+
+ tmp7 = z11 + z13; /* phase 5 */
+ tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
+
+ z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
+ tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
+ tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
+
+ tmp6 = tmp12 - tmp7; /* phase 2 */
+ tmp5 = tmp11 - tmp6;
+ tmp4 = tmp10 + tmp5;
+
+ wsptr[DCTSIZE*0] = tmp0 + tmp7;
+ wsptr[DCTSIZE*7] = tmp0 - tmp7;
+ wsptr[DCTSIZE*1] = tmp1 + tmp6;
+ wsptr[DCTSIZE*6] = tmp1 - tmp6;
+ wsptr[DCTSIZE*2] = tmp2 + tmp5;
+ wsptr[DCTSIZE*5] = tmp2 - tmp5;
+ wsptr[DCTSIZE*4] = tmp3 + tmp4;
+ wsptr[DCTSIZE*3] = tmp3 - tmp4;
+
+ inptr++; /* advance pointers to next column */
+ quantptr++;
+ wsptr++;
+ }
+
+ /* Pass 2: process rows from work array, store into output array. */
+ /* Note that we must descale the results by a factor of 8 == 2**3. */
+
+ wsptr = workspace;
+ for (ctr = 0; ctr < DCTSIZE; ctr++) {
+ outptr = output_buf[ctr] + output_col;
+ /* Rows of zeroes can be exploited in the same way as we did with columns.
+ * However, the column calculation has created many nonzero AC terms, so
+ * the simplification applies less often (typically 5% to 10% of the time).
+ * And testing floats for zero is relatively expensive, so we don't bother.
+ */
+
+ /* Even part */
+
+ tmp10 = wsptr[0] + wsptr[4];
+ tmp11 = wsptr[0] - wsptr[4];
+
+ tmp13 = wsptr[2] + wsptr[6];
+ tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
+
+ tmp0 = tmp10 + tmp13;
+ tmp3 = tmp10 - tmp13;
+ tmp1 = tmp11 + tmp12;
+ tmp2 = tmp11 - tmp12;
+
+ /* Odd part */
+
+ z13 = wsptr[5] + wsptr[3];
+ z10 = wsptr[5] - wsptr[3];
+ z11 = wsptr[1] + wsptr[7];
+ z12 = wsptr[1] - wsptr[7];
+
+ tmp7 = z11 + z13;
+ tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
+
+ z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
+ tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
+ tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
+
+ tmp6 = tmp12 - tmp7;
+ tmp5 = tmp11 - tmp6;
+ tmp4 = tmp10 + tmp5;
+
+ /* Final output stage: scale down by a factor of 8 and range-limit */
+
+ outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
+ & RANGE_MASK];
+ outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
+ & RANGE_MASK];
+ outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
+ & RANGE_MASK];
+ outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
+ & RANGE_MASK];
+ outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
+ & RANGE_MASK];
+ outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
+ & RANGE_MASK];
+ outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
+ & RANGE_MASK];
+ outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
+ & RANGE_MASK];
+
+ wsptr += DCTSIZE; /* advance pointer to next row */
+ }
+}
+
+#endif /* DCT_FLOAT_SUPPORTED */
diff --git a/code/jpeg-6/jidctfst.c b/code/jpeg-6/jidctfst.c
new file mode 100755
index 0000000..c9777c5
--- /dev/null
+++ b/code/jpeg-6/jidctfst.c
@@ -0,0 +1,367 @@
+/*
+ * jidctfst.c
+ *
+ * Copyright (C) 1994-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains a fast, not so accurate integer implementation of the
+ * inverse DCT (Discrete Cosine Transform). In the IJG code, this routine
+ * must also perform dequantization of the input coefficients.
+ *
+ * A 2-D IDCT can be done by 1-D IDCT on each column followed by 1-D IDCT
+ * on each row (or vice versa, but it's more convenient to emit a row at
+ * a time). Direct algorithms are also available, but they are much more
+ * complex and seem not to be any faster when reduced to code.
+ *
+ * This implementation is based on Arai, Agui, and Nakajima's algorithm for
+ * scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in
+ * Japanese, but the algorithm is described in the Pennebaker & Mitchell
+ * JPEG textbook (see REFERENCES section in file README). The following code
+ * is based directly on figure 4-8 in P&M.
+ * While an 8-point DCT cannot be done in less than 11 multiplies, it is
+ * possible to arrange the computation so that many of the multiplies are
+ * simple scalings of the final outputs. These multiplies can then be
+ * folded into the multiplications or divisions by the JPEG quantization
+ * table entries. The AA&N method leaves only 5 multiplies and 29 adds
+ * to be done in the DCT itself.
+ * The primary disadvantage of this method is that with fixed-point math,
+ * accuracy is lost due to imprecise representation of the scaled
+ * quantization values. The smaller the quantization table entry, the less
+ * precise the scaled value, so this implementation does worse with high-
+ * quality-setting files than with low-quality ones.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jdct.h" /* Private declarations for DCT subsystem */
+
+#ifdef DCT_IFAST_SUPPORTED
+
+
+/*
+ * This module is specialized to the case DCTSIZE = 8.
+ */
+
+#if DCTSIZE != 8
+ Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
+#endif
+
+
+/* Scaling decisions are generally the same as in the LL&M algorithm;
+ * see jidctint.c for more details. However, we choose to descale
+ * (right shift) multiplication products as soon as they are formed,
+ * rather than carrying additional fractional bits into subsequent additions.
+ * This compromises accuracy slightly, but it lets us save a few shifts.
+ * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
+ * everywhere except in the multiplications proper; this saves a good deal
+ * of work on 16-bit-int machines.
+ *
+ * The dequantized coefficients are not integers because the AA&N scaling
+ * factors have been incorporated. We represent them scaled up by PASS1_BITS,
+ * so that the first and second IDCT rounds have the same input scaling.
+ * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
+ * avoid a descaling shift; this compromises accuracy rather drastically
+ * for small quantization table entries, but it saves a lot of shifts.
+ * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
+ * so we use a much larger scaling factor to preserve accuracy.
+ *
+ * A final compromise is to represent the multiplicative constants to only
+ * 8 fractional bits, rather than 13. This saves some shifting work on some
+ * machines, and may also reduce the cost of multiplication (since there
+ * are fewer one-bits in the constants).
+ */
+
+#if BITS_IN_JSAMPLE == 8
+#define CONST_BITS 8
+#define PASS1_BITS 2
+#else
+#define CONST_BITS 8
+#define PASS1_BITS 1 /* lose a little precision to avoid overflow */
+#endif
+
+/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
+ * causing a lot of useless floating-point operations at run time.
+ * To get around this we use the following pre-calculated constants.
+ * If you change CONST_BITS you may want to add appropriate values.
+ * (With a reasonable C compiler, you can just rely on the FIX() macro...)
+ */
+
+#if CONST_BITS == 8
+#define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
+#define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
+#define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
+#define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
+#else
+#define FIX_1_082392200 FIX(1.082392200)
+#define FIX_1_414213562 FIX(1.414213562)
+#define FIX_1_847759065 FIX(1.847759065)
+#define FIX_2_613125930 FIX(2.613125930)
+#endif
+
+
+/* We can gain a little more speed, with a further compromise in accuracy,
+ * by omitting the addition in a descaling shift. This yields an incorrectly
+ * rounded result half the time...
+ */
+
+#ifndef USE_ACCURATE_ROUNDING
+#undef DESCALE
+#define DESCALE(x,n) RIGHT_SHIFT(x, n)
+#endif
+
+
+/* Multiply a DCTELEM variable by an INT32 constant, and immediately
+ * descale to yield a DCTELEM result.
+ */
+
+#define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
+
+
+/* Dequantize a coefficient by multiplying it by the multiplier-table
+ * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
+ * multiplication will do. For 12-bit data, the multiplier table is
+ * declared INT32, so a 32-bit multiply will be used.
+ */
+
+#if BITS_IN_JSAMPLE == 8
+#define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
+#else
+#define DEQUANTIZE(coef,quantval) \
+ DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
+#endif
+
+
+/* Like DESCALE, but applies to a DCTELEM and produces an int.
+ * We assume that int right shift is unsigned if INT32 right shift is.
+ */
+
+#ifdef RIGHT_SHIFT_IS_UNSIGNED
+#define ISHIFT_TEMPS DCTELEM ishift_temp;
+#if BITS_IN_JSAMPLE == 8
+#define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
+#else
+#define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
+#endif
+#define IRIGHT_SHIFT(x,shft) \
+ ((ishift_temp = (x)) < 0 ? \
+ (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
+ (ishift_temp >> (shft)))
+#else
+#define ISHIFT_TEMPS
+#define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
+#endif
+
+#ifdef USE_ACCURATE_ROUNDING
+#define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
+#else
+#define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
+#endif
+
+
+/*
+ * Perform dequantization and inverse DCT on one block of coefficients.
+ */
+
+GLOBAL void
+jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block,
+ JSAMPARRAY output_buf, JDIMENSION output_col)
+{
+ DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
+ DCTELEM tmp10, tmp11, tmp12, tmp13;
+ DCTELEM z5, z10, z11, z12, z13;
+ JCOEFPTR inptr;
+ IFAST_MULT_TYPE * quantptr;
+ int * wsptr;
+ JSAMPROW outptr;
+ JSAMPLE *range_limit = IDCT_range_limit(cinfo);
+ int ctr;
+ int workspace[DCTSIZE2]; /* buffers data between passes */
+ SHIFT_TEMPS /* for DESCALE */
+ ISHIFT_TEMPS /* for IDESCALE */
+
+ /* Pass 1: process columns from input, store into work array. */
+
+ inptr = coef_block;
+ quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
+ wsptr = workspace;
+ for (ctr = DCTSIZE; ctr > 0; ctr--) {
+ /* Due to quantization, we will usually find that many of the input
+ * coefficients are zero, especially the AC terms. We can exploit this
+ * by short-circuiting the IDCT calculation for any column in which all
+ * the AC terms are zero. In that case each output is equal to the
+ * DC coefficient (with scale factor as needed).
+ * With typical images and quantization tables, half or more of the
+ * column DCT calculations can be simplified this way.
+ */
+
+ if ((inptr[DCTSIZE*1] | inptr[DCTSIZE*2] | inptr[DCTSIZE*3] |
+ inptr[DCTSIZE*4] | inptr[DCTSIZE*5] | inptr[DCTSIZE*6] |
+ inptr[DCTSIZE*7]) == 0) {
+ /* AC terms all zero */
+ int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
+
+ wsptr[DCTSIZE*0] = dcval;
+ wsptr[DCTSIZE*1] = dcval;
+ wsptr[DCTSIZE*2] = dcval;
+ wsptr[DCTSIZE*3] = dcval;
+ wsptr[DCTSIZE*4] = dcval;
+ wsptr[DCTSIZE*5] = dcval;
+ wsptr[DCTSIZE*6] = dcval;
+ wsptr[DCTSIZE*7] = dcval;
+
+ inptr++; /* advance pointers to next column */
+ quantptr++;
+ wsptr++;
+ continue;
+ }
+
+ /* Even part */
+
+ tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
+ tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
+ tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
+ tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
+
+ tmp10 = tmp0 + tmp2; /* phase 3 */
+ tmp11 = tmp0 - tmp2;
+
+ tmp13 = tmp1 + tmp3; /* phases 5-3 */
+ tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
+
+ tmp0 = tmp10 + tmp13; /* phase 2 */
+ tmp3 = tmp10 - tmp13;
+ tmp1 = tmp11 + tmp12;
+ tmp2 = tmp11 - tmp12;
+
+ /* Odd part */
+
+ tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
+ tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
+ tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
+ tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
+
+ z13 = tmp6 + tmp5; /* phase 6 */
+ z10 = tmp6 - tmp5;
+ z11 = tmp4 + tmp7;
+ z12 = tmp4 - tmp7;
+
+ tmp7 = z11 + z13; /* phase 5 */
+ tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
+
+ z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
+ tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
+ tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
+
+ tmp6 = tmp12 - tmp7; /* phase 2 */
+ tmp5 = tmp11 - tmp6;
+ tmp4 = tmp10 + tmp5;
+
+ wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
+ wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
+ wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
+ wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
+ wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
+ wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
+ wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
+ wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
+
+ inptr++; /* advance pointers to next column */
+ quantptr++;
+ wsptr++;
+ }
+
+ /* Pass 2: process rows from work array, store into output array. */
+ /* Note that we must descale the results by a factor of 8 == 2**3, */
+ /* and also undo the PASS1_BITS scaling. */
+
+ wsptr = workspace;
+ for (ctr = 0; ctr < DCTSIZE; ctr++) {
+ outptr = output_buf[ctr] + output_col;
+ /* Rows of zeroes can be exploited in the same way as we did with columns.
+ * However, the column calculation has created many nonzero AC terms, so
+ * the simplification applies less often (typically 5% to 10% of the time).
+ * On machines with very fast multiplication, it's possible that the
+ * test takes more time than it's worth. In that case this section
+ * may be commented out.
+ */
+
+#ifndef NO_ZERO_ROW_TEST
+ if ((wsptr[1] | wsptr[2] | wsptr[3] | wsptr[4] | wsptr[5] | wsptr[6] |
+ wsptr[7]) == 0) {
+ /* AC terms all zero */
+ JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
+ & RANGE_MASK];
+
+ outptr[0] = dcval;
+ outptr[1] = dcval;
+ outptr[2] = dcval;
+ outptr[3] = dcval;
+ outptr[4] = dcval;
+ outptr[5] = dcval;
+ outptr[6] = dcval;
+ outptr[7] = dcval;
+
+ wsptr += DCTSIZE; /* advance pointer to next row */
+ continue;
+ }
+#endif
+
+ /* Even part */
+
+ tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
+ tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
+
+ tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
+ tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
+ - tmp13;
+
+ tmp0 = tmp10 + tmp13;
+ tmp3 = tmp10 - tmp13;
+ tmp1 = tmp11 + tmp12;
+ tmp2 = tmp11 - tmp12;
+
+ /* Odd part */
+
+ z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
+ z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
+ z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
+ z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
+
+ tmp7 = z11 + z13; /* phase 5 */
+ tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
+
+ z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
+ tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
+ tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
+
+ tmp6 = tmp12 - tmp7; /* phase 2 */
+ tmp5 = tmp11 - tmp6;
+ tmp4 = tmp10 + tmp5;
+
+ /* Final output stage: scale down by a factor of 8 and range-limit */
+
+ outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
+ & RANGE_MASK];
+
+ wsptr += DCTSIZE; /* advance pointer to next row */
+ }
+}
+
+#endif /* DCT_IFAST_SUPPORTED */
diff --git a/code/jpeg-6/jidctint.c b/code/jpeg-6/jidctint.c
new file mode 100755
index 0000000..b3271d8
--- /dev/null
+++ b/code/jpeg-6/jidctint.c
@@ -0,0 +1,388 @@
+/*
+ * jidctint.c
+ *
+ * Copyright (C) 1991-1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains a slow-but-accurate integer implementation of the
+ * inverse DCT (Discrete Cosine Transform). In the IJG code, this routine
+ * must also perform dequantization of the input coefficients.
+ *
+ * A 2-D IDCT can be done by 1-D IDCT on each column followed by 1-D IDCT
+ * on each row (or vice versa, but it's more convenient to emit a row at
+ * a time). Direct algorithms are also available, but they are much more
+ * complex and seem not to be any faster when reduced to code.
+ *
+ * This implementation is based on an algorithm described in
+ * C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT
+ * Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics,
+ * Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991.
+ * The primary algorithm described there uses 11 multiplies and 29 adds.
+ * We use their alternate method with 12 multiplies and 32 adds.
+ * The advantage of this method is that no data path contains more than one
+ * multiplication; this allows a very simple and accurate implementation in
+ * scaled fixed-point arithmetic, with a minimal number of shifts.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jdct.h" /* Private declarations for DCT subsystem */
+
+#ifdef DCT_ISLOW_SUPPORTED
+
+
+/*
+ * This module is specialized to the case DCTSIZE = 8.
+ */
+
+#if DCTSIZE != 8
+ Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
+#endif
+
+
+/*
+ * The poop on this scaling stuff is as follows:
+ *
+ * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
+ * larger than the true IDCT outputs. The final outputs are therefore
+ * a factor of N larger than desired; since N=8 this can be cured by
+ * a simple right shift at the end of the algorithm. The advantage of
+ * this arrangement is that we save two multiplications per 1-D IDCT,
+ * because the y0 and y4 inputs need not be divided by sqrt(N).
+ *
+ * We have to do addition and subtraction of the integer inputs, which
+ * is no problem, and multiplication by fractional constants, which is
+ * a problem to do in integer arithmetic. We multiply all the constants
+ * by CONST_SCALE and convert them to integer constants (thus retaining
+ * CONST_BITS bits of precision in the constants). After doing a
+ * multiplication we have to divide the product by CONST_SCALE, with proper
+ * rounding, to produce the correct output. This division can be done
+ * cheaply as a right shift of CONST_BITS bits. We postpone shifting
+ * as long as possible so that partial sums can be added together with
+ * full fractional precision.
+ *
+ * The outputs of the first pass are scaled up by PASS1_BITS bits so that
+ * they are represented to better-than-integral precision. These outputs
+ * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
+ * with the recommended scaling. (To scale up 12-bit sample data further, an
+ * intermediate INT32 array would be needed.)
+ *
+ * To avoid overflow of the 32-bit intermediate results in pass 2, we must
+ * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
+ * shows that the values given below are the most effective.
+ */
+
+#if BITS_IN_JSAMPLE == 8
+#define CONST_BITS 13
+#define PASS1_BITS 2
+#else
+#define CONST_BITS 13
+#define PASS1_BITS 1 /* lose a little precision to avoid overflow */
+#endif
+
+/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
+ * causing a lot of useless floating-point operations at run time.
+ * To get around this we use the following pre-calculated constants.
+ * If you change CONST_BITS you may want to add appropriate values.
+ * (With a reasonable C compiler, you can just rely on the FIX() macro...)
+ */
+
+#if CONST_BITS == 13
+#define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
+#define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
+#define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
+#define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
+#define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
+#define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
+#define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
+#define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
+#define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
+#define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
+#define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
+#define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
+#else
+#define FIX_0_298631336 FIX(0.298631336)
+#define FIX_0_390180644 FIX(0.390180644)
+#define FIX_0_541196100 FIX(0.541196100)
+#define FIX_0_765366865 FIX(0.765366865)
+#define FIX_0_899976223 FIX(0.899976223)
+#define FIX_1_175875602 FIX(1.175875602)
+#define FIX_1_501321110 FIX(1.501321110)
+#define FIX_1_847759065 FIX(1.847759065)
+#define FIX_1_961570560 FIX(1.961570560)
+#define FIX_2_053119869 FIX(2.053119869)
+#define FIX_2_562915447 FIX(2.562915447)
+#define FIX_3_072711026 FIX(3.072711026)
+#endif
+
+
+/* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
+ * For 8-bit samples with the recommended scaling, all the variable
+ * and constant values involved are no more than 16 bits wide, so a
+ * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
+ * For 12-bit samples, a full 32-bit multiplication will be needed.
+ */
+
+#if BITS_IN_JSAMPLE == 8
+#define MULTIPLY(var,const) MULTIPLY16C16(var,const)
+#else
+#define MULTIPLY(var,const) ((var) * (const))
+#endif
+
+
+/* Dequantize a coefficient by multiplying it by the multiplier-table
+ * entry; produce an int result. In this module, both inputs and result
+ * are 16 bits or less, so either int or short multiply will work.
+ */
+
+#define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
+
+
+/*
+ * Perform dequantization and inverse DCT on one block of coefficients.
+ */
+
+GLOBAL void
+jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block,
+ JSAMPARRAY output_buf, JDIMENSION output_col)
+{
+ INT32 tmp0, tmp1, tmp2, tmp3;
+ INT32 tmp10, tmp11, tmp12, tmp13;
+ INT32 z1, z2, z3, z4, z5;
+ JCOEFPTR inptr;
+ ISLOW_MULT_TYPE * quantptr;
+ int * wsptr;
+ JSAMPROW outptr;
+ JSAMPLE *range_limit = IDCT_range_limit(cinfo);
+ int ctr;
+ int workspace[DCTSIZE2]; /* buffers data between passes */
+ SHIFT_TEMPS
+
+ /* Pass 1: process columns from input, store into work array. */
+ /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
+ /* furthermore, we scale the results by 2**PASS1_BITS. */
+
+ inptr = coef_block;
+ quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
+ wsptr = workspace;
+ for (ctr = DCTSIZE; ctr > 0; ctr--) {
+ /* Due to quantization, we will usually find that many of the input
+ * coefficients are zero, especially the AC terms. We can exploit this
+ * by short-circuiting the IDCT calculation for any column in which all
+ * the AC terms are zero. In that case each output is equal to the
+ * DC coefficient (with scale factor as needed).
+ * With typical images and quantization tables, half or more of the
+ * column DCT calculations can be simplified this way.
+ */
+
+ if ((inptr[DCTSIZE*1] | inptr[DCTSIZE*2] | inptr[DCTSIZE*3] |
+ inptr[DCTSIZE*4] | inptr[DCTSIZE*5] | inptr[DCTSIZE*6] |
+ inptr[DCTSIZE*7]) == 0) {
+ /* AC terms all zero */
+ int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
+
+ wsptr[DCTSIZE*0] = dcval;
+ wsptr[DCTSIZE*1] = dcval;
+ wsptr[DCTSIZE*2] = dcval;
+ wsptr[DCTSIZE*3] = dcval;
+ wsptr[DCTSIZE*4] = dcval;
+ wsptr[DCTSIZE*5] = dcval;
+ wsptr[DCTSIZE*6] = dcval;
+ wsptr[DCTSIZE*7] = dcval;
+
+ inptr++; /* advance pointers to next column */
+ quantptr++;
+ wsptr++;
+ continue;
+ }
+
+ /* Even part: reverse the even part of the forward DCT. */
+ /* The rotator is sqrt(2)*c(-6). */
+
+ z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
+ z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
+
+ z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
+ tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
+ tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
+
+ z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
+ z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
+
+ tmp0 = (z2 + z3) << CONST_BITS;
+ tmp1 = (z2 - z3) << CONST_BITS;
+
+ tmp10 = tmp0 + tmp3;
+ tmp13 = tmp0 - tmp3;
+ tmp11 = tmp1 + tmp2;
+ tmp12 = tmp1 - tmp2;
+
+ /* Odd part per figure 8; the matrix is unitary and hence its
+ * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
+ */
+
+ tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
+ tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
+ tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
+ tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
+
+ z1 = tmp0 + tmp3;
+ z2 = tmp1 + tmp2;
+ z3 = tmp0 + tmp2;
+ z4 = tmp1 + tmp3;
+ z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
+
+ tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+
+ z3 += z5;
+ z4 += z5;
+
+ tmp0 += z1 + z3;
+ tmp1 += z2 + z4;
+ tmp2 += z2 + z3;
+ tmp3 += z1 + z4;
+
+ /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
+
+ wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
+ wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
+ wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
+ wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
+ wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
+ wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
+ wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
+ wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
+
+ inptr++; /* advance pointers to next column */
+ quantptr++;
+ wsptr++;
+ }
+
+ /* Pass 2: process rows from work array, store into output array. */
+ /* Note that we must descale the results by a factor of 8 == 2**3, */
+ /* and also undo the PASS1_BITS scaling. */
+
+ wsptr = workspace;
+ for (ctr = 0; ctr < DCTSIZE; ctr++) {
+ outptr = output_buf[ctr] + output_col;
+ /* Rows of zeroes can be exploited in the same way as we did with columns.
+ * However, the column calculation has created many nonzero AC terms, so
+ * the simplification applies less often (typically 5% to 10% of the time).
+ * On machines with very fast multiplication, it's possible that the
+ * test takes more time than it's worth. In that case this section
+ * may be commented out.
+ */
+
+#ifndef NO_ZERO_ROW_TEST
+ if ((wsptr[1] | wsptr[2] | wsptr[3] | wsptr[4] | wsptr[5] | wsptr[6] |
+ wsptr[7]) == 0) {
+ /* AC terms all zero */
+ JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
+ & RANGE_MASK];
+
+ outptr[0] = dcval;
+ outptr[1] = dcval;
+ outptr[2] = dcval;
+ outptr[3] = dcval;
+ outptr[4] = dcval;
+ outptr[5] = dcval;
+ outptr[6] = dcval;
+ outptr[7] = dcval;
+
+ wsptr += DCTSIZE; /* advance pointer to next row */
+ continue;
+ }
+#endif
+
+ /* Even part: reverse the even part of the forward DCT. */
+ /* The rotator is sqrt(2)*c(-6). */
+
+ z2 = (INT32) wsptr[2];
+ z3 = (INT32) wsptr[6];
+
+ z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
+ tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
+ tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
+
+ tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
+ tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
+
+ tmp10 = tmp0 + tmp3;
+ tmp13 = tmp0 - tmp3;
+ tmp11 = tmp1 + tmp2;
+ tmp12 = tmp1 - tmp2;
+
+ /* Odd part per figure 8; the matrix is unitary and hence its
+ * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
+ */
+
+ tmp0 = (INT32) wsptr[7];
+ tmp1 = (INT32) wsptr[5];
+ tmp2 = (INT32) wsptr[3];
+ tmp3 = (INT32) wsptr[1];
+
+ z1 = tmp0 + tmp3;
+ z2 = tmp1 + tmp2;
+ z3 = tmp0 + tmp2;
+ z4 = tmp1 + tmp3;
+ z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
+
+ tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+
+ z3 += z5;
+ z4 += z5;
+
+ tmp0 += z1 + z3;
+ tmp1 += z2 + z4;
+ tmp2 += z2 + z3;
+ tmp3 += z1 + z4;
+
+ /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
+
+ outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
+ CONST_BITS+PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
+ CONST_BITS+PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
+ CONST_BITS+PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
+ CONST_BITS+PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
+ CONST_BITS+PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
+ CONST_BITS+PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
+ CONST_BITS+PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
+ CONST_BITS+PASS1_BITS+3)
+ & RANGE_MASK];
+
+ wsptr += DCTSIZE; /* advance pointer to next row */
+ }
+}
+
+#endif /* DCT_ISLOW_SUPPORTED */
diff --git a/code/jpeg-6/jidctred.c b/code/jpeg-6/jidctred.c
new file mode 100755
index 0000000..13877ed
--- /dev/null
+++ b/code/jpeg-6/jidctred.c
@@ -0,0 +1,397 @@
+/*
+ * jidctred.c
+ *
+ * Copyright (C) 1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains inverse-DCT routines that produce reduced-size output:
+ * either 4x4, 2x2, or 1x1 pixels from an 8x8 DCT block.
+ *
+ * The implementation is based on the Loeffler, Ligtenberg and Moschytz (LL&M)
+ * algorithm used in jidctint.c. We simply replace each 8-to-8 1-D IDCT step
+ * with an 8-to-4 step that produces the four averages of two adjacent outputs
+ * (or an 8-to-2 step producing two averages of four outputs, for 2x2 output).
+ * These steps were derived by computing the corresponding values at the end
+ * of the normal LL&M code, then simplifying as much as possible.
+ *
+ * 1x1 is trivial: just take the DC coefficient divided by 8.
+ *
+ * See jidctint.c for additional comments.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jdct.h" /* Private declarations for DCT subsystem */
+
+#ifdef IDCT_SCALING_SUPPORTED
+
+
+/*
+ * This module is specialized to the case DCTSIZE = 8.
+ */
+
+#if DCTSIZE != 8
+ Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
+#endif
+
+
+/* Scaling is the same as in jidctint.c. */
+
+#if BITS_IN_JSAMPLE == 8
+#define CONST_BITS 13
+#define PASS1_BITS 2
+#else
+#define CONST_BITS 13
+#define PASS1_BITS 1 /* lose a little precision to avoid overflow */
+#endif
+
+/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
+ * causing a lot of useless floating-point operations at run time.
+ * To get around this we use the following pre-calculated constants.
+ * If you change CONST_BITS you may want to add appropriate values.
+ * (With a reasonable C compiler, you can just rely on the FIX() macro...)
+ */
+
+#if CONST_BITS == 13
+#define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
+#define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
+#define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
+#define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
+#define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
+#define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
+#define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
+#define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
+#define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
+#define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
+#define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
+#define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
+#define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
+#define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
+#else
+#define FIX_0_211164243 FIX(0.211164243)
+#define FIX_0_509795579 FIX(0.509795579)
+#define FIX_0_601344887 FIX(0.601344887)
+#define FIX_0_720959822 FIX(0.720959822)
+#define FIX_0_765366865 FIX(0.765366865)
+#define FIX_0_850430095 FIX(0.850430095)
+#define FIX_0_899976223 FIX(0.899976223)
+#define FIX_1_061594337 FIX(1.061594337)
+#define FIX_1_272758580 FIX(1.272758580)
+#define FIX_1_451774981 FIX(1.451774981)
+#define FIX_1_847759065 FIX(1.847759065)
+#define FIX_2_172734803 FIX(2.172734803)
+#define FIX_2_562915447 FIX(2.562915447)
+#define FIX_3_624509785 FIX(3.624509785)
+#endif
+
+
+/* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
+ * For 8-bit samples with the recommended scaling, all the variable
+ * and constant values involved are no more than 16 bits wide, so a
+ * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
+ * For 12-bit samples, a full 32-bit multiplication will be needed.
+ */
+
+#if BITS_IN_JSAMPLE == 8
+#define MULTIPLY(var,const) MULTIPLY16C16(var,const)
+#else
+#define MULTIPLY(var,const) ((var) * (const))
+#endif
+
+
+/* Dequantize a coefficient by multiplying it by the multiplier-table
+ * entry; produce an int result. In this module, both inputs and result
+ * are 16 bits or less, so either int or short multiply will work.
+ */
+
+#define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
+
+
+/*
+ * Perform dequantization and inverse DCT on one block of coefficients,
+ * producing a reduced-size 4x4 output block.
+ */
+
+GLOBAL void
+jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block,
+ JSAMPARRAY output_buf, JDIMENSION output_col)
+{
+ INT32 tmp0, tmp2, tmp10, tmp12;
+ INT32 z1, z2, z3, z4;
+ JCOEFPTR inptr;
+ ISLOW_MULT_TYPE * quantptr;
+ int * wsptr;
+ JSAMPROW outptr;
+ JSAMPLE *range_limit = IDCT_range_limit(cinfo);
+ int ctr;
+ int workspace[DCTSIZE*4]; /* buffers data between passes */
+ SHIFT_TEMPS
+
+ /* Pass 1: process columns from input, store into work array. */
+
+ inptr = coef_block;
+ quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
+ wsptr = workspace;
+ for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
+ /* Don't bother to process column 4, because second pass won't use it */
+ if (ctr == DCTSIZE-4)
+ continue;
+ if ((inptr[DCTSIZE*1] | inptr[DCTSIZE*2] | inptr[DCTSIZE*3] |
+ inptr[DCTSIZE*5] | inptr[DCTSIZE*6] | inptr[DCTSIZE*7]) == 0) {
+ /* AC terms all zero; we need not examine term 4 for 4x4 output */
+ int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
+
+ wsptr[DCTSIZE*0] = dcval;
+ wsptr[DCTSIZE*1] = dcval;
+ wsptr[DCTSIZE*2] = dcval;
+ wsptr[DCTSIZE*3] = dcval;
+
+ continue;
+ }
+
+ /* Even part */
+
+ tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
+ tmp0 <<= (CONST_BITS+1);
+
+ z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
+ z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
+
+ tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
+
+ tmp10 = tmp0 + tmp2;
+ tmp12 = tmp0 - tmp2;
+
+ /* Odd part */
+
+ z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
+ z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
+ z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
+ z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
+
+ tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
+ + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
+ + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
+ + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
+
+ tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
+ + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
+ + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
+ + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
+
+ /* Final output stage */
+
+ wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
+ wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
+ wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
+ wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
+ }
+
+ /* Pass 2: process 4 rows from work array, store into output array. */
+
+ wsptr = workspace;
+ for (ctr = 0; ctr < 4; ctr++) {
+ outptr = output_buf[ctr] + output_col;
+ /* It's not clear whether a zero row test is worthwhile here ... */
+
+#ifndef NO_ZERO_ROW_TEST
+ if ((wsptr[1] | wsptr[2] | wsptr[3] | wsptr[5] | wsptr[6] |
+ wsptr[7]) == 0) {
+ /* AC terms all zero */
+ JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
+ & RANGE_MASK];
+
+ outptr[0] = dcval;
+ outptr[1] = dcval;
+ outptr[2] = dcval;
+ outptr[3] = dcval;
+
+ wsptr += DCTSIZE; /* advance pointer to next row */
+ continue;
+ }
+#endif
+
+ /* Even part */
+
+ tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
+
+ tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
+ + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
+
+ tmp10 = tmp0 + tmp2;
+ tmp12 = tmp0 - tmp2;
+
+ /* Odd part */
+
+ z1 = (INT32) wsptr[7];
+ z2 = (INT32) wsptr[5];
+ z3 = (INT32) wsptr[3];
+ z4 = (INT32) wsptr[1];
+
+ tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
+ + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
+ + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
+ + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
+
+ tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
+ + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
+ + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
+ + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
+
+ /* Final output stage */
+
+ outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
+ CONST_BITS+PASS1_BITS+3+1)
+ & RANGE_MASK];
+ outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
+ CONST_BITS+PASS1_BITS+3+1)
+ & RANGE_MASK];
+ outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
+ CONST_BITS+PASS1_BITS+3+1)
+ & RANGE_MASK];
+ outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
+ CONST_BITS+PASS1_BITS+3+1)
+ & RANGE_MASK];
+
+ wsptr += DCTSIZE; /* advance pointer to next row */
+ }
+}
+
+
+/*
+ * Perform dequantization and inverse DCT on one block of coefficients,
+ * producing a reduced-size 2x2 output block.
+ */
+
+GLOBAL void
+jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block,
+ JSAMPARRAY output_buf, JDIMENSION output_col)
+{
+ INT32 tmp0, tmp10, z1;
+ JCOEFPTR inptr;
+ ISLOW_MULT_TYPE * quantptr;
+ int * wsptr;
+ JSAMPROW outptr;
+ JSAMPLE *range_limit = IDCT_range_limit(cinfo);
+ int ctr;
+ int workspace[DCTSIZE*2]; /* buffers data between passes */
+ SHIFT_TEMPS
+
+ /* Pass 1: process columns from input, store into work array. */
+
+ inptr = coef_block;
+ quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
+ wsptr = workspace;
+ for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
+ /* Don't bother to process columns 2,4,6 */
+ if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
+ continue;
+ if ((inptr[DCTSIZE*1] | inptr[DCTSIZE*3] |
+ inptr[DCTSIZE*5] | inptr[DCTSIZE*7]) == 0) {
+ /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
+ int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
+
+ wsptr[DCTSIZE*0] = dcval;
+ wsptr[DCTSIZE*1] = dcval;
+
+ continue;
+ }
+
+ /* Even part */
+
+ z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
+ tmp10 = z1 << (CONST_BITS+2);
+
+ /* Odd part */
+
+ z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
+ tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
+ z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
+ tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
+ z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
+ tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
+ z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
+ tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
+
+ /* Final output stage */
+
+ wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
+ wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
+ }
+
+ /* Pass 2: process 2 rows from work array, store into output array. */
+
+ wsptr = workspace;
+ for (ctr = 0; ctr < 2; ctr++) {
+ outptr = output_buf[ctr] + output_col;
+ /* It's not clear whether a zero row test is worthwhile here ... */
+
+#ifndef NO_ZERO_ROW_TEST
+ if ((wsptr[1] | wsptr[3] | wsptr[5] | wsptr[7]) == 0) {
+ /* AC terms all zero */
+ JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
+ & RANGE_MASK];
+
+ outptr[0] = dcval;
+ outptr[1] = dcval;
+
+ wsptr += DCTSIZE; /* advance pointer to next row */
+ continue;
+ }
+#endif
+
+ /* Even part */
+
+ tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
+
+ /* Odd part */
+
+ tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
+ + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
+ + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
+ + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
+
+ /* Final output stage */
+
+ outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
+ CONST_BITS+PASS1_BITS+3+2)
+ & RANGE_MASK];
+ outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
+ CONST_BITS+PASS1_BITS+3+2)
+ & RANGE_MASK];
+
+ wsptr += DCTSIZE; /* advance pointer to next row */
+ }
+}
+
+
+/*
+ * Perform dequantization and inverse DCT on one block of coefficients,
+ * producing a reduced-size 1x1 output block.
+ */
+
+GLOBAL void
+jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block,
+ JSAMPARRAY output_buf, JDIMENSION output_col)
+{
+ int dcval;
+ ISLOW_MULT_TYPE * quantptr;
+ JSAMPLE *range_limit = IDCT_range_limit(cinfo);
+ SHIFT_TEMPS
+
+ /* We hardly need an inverse DCT routine for this: just take the
+ * average pixel value, which is one-eighth of the DC coefficient.
+ */
+ quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
+ dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
+ dcval = (int) DESCALE((INT32) dcval, 3);
+
+ output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
+}
+
+#endif /* IDCT_SCALING_SUPPORTED */
diff --git a/code/jpeg-6/jinclude.h b/code/jpeg-6/jinclude.h
new file mode 100755
index 0000000..99f535d
--- /dev/null
+++ b/code/jpeg-6/jinclude.h
@@ -0,0 +1,116 @@
+/*
+ * jinclude.h
+ *
+ * Copyright (C) 1991-1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file exists to provide a single place to fix any problems with
+ * including the wrong system include files. (Common problems are taken
+ * care of by the standard jconfig symbols, but on really weird systems
+ * you may have to edit this file.)
+ *
+ * NOTE: this file is NOT intended to be included by applications using the
+ * JPEG library. Most applications need only include jpeglib.h.
+ */
+
+
+#ifdef _WIN32
+
+#pragma warning(disable : 4018) // signed/unsigned mismatch
+#pragma warning(disable : 4032)
+#pragma warning(disable : 4051)
+#pragma warning(disable : 4057) // slightly different base types
+#pragma warning(disable : 4100) // unreferenced formal parameter
+#pragma warning(disable : 4115)
+#pragma warning(disable : 4125) // decimal digit terminates octal escape sequence
+#pragma warning(disable : 4127) // conditional expression is constant
+#pragma warning(disable : 4136)
+#pragma warning(disable : 4152) // nonstandard extension, function/data pointer conversion in expression
+#pragma warning(disable : 4201)
+#pragma warning(disable : 4214)
+#pragma warning(disable : 4244)
+#pragma warning(disable : 4305) // truncation from const double to float
+#pragma warning(disable : 4310) // cast truncates constant value
+#pragma warning(disable: 4505) // unreferenced local function has been removed
+#pragma warning(disable : 4514)
+#pragma warning(disable : 4702) // unreachable code
+#pragma warning(disable : 4711) // selected for automatic inline expansion
+#pragma warning(disable : 4220) // varargs matches remaining parameters
+#pragma warning(disable : 4761) // integral size mismatch
+#endif
+
+/* Include auto-config file to find out which system include files we need. */
+
+#include "../jpeg-6/jconfig.h" /* auto configuration options */
+#define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
+
+/*
+ * We need the NULL macro and size_t typedef.
+ * On an ANSI-conforming system it is sufficient to include <stddef.h>.
+ * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
+ * pull in <sys/types.h> as well.
+ * Note that the core JPEG library does not require <stdio.h>;
+ * only the default error handler and data source/destination modules do.
+ * But we must pull it in because of the references to FILE in jpeglib.h.
+ * You can remove those references if you want to compile without <stdio.h>.
+ */
+
+#ifdef HAVE_STDDEF_H
+#include <stddef.h>
+#endif
+
+#ifdef HAVE_STDLIB_H
+#include <stdlib.h>
+#endif
+
+#ifdef NEED_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+
+#include <stdio.h>
+
+/*
+ * We need memory copying and zeroing functions, plus strncpy().
+ * ANSI and System V implementations declare these in <string.h>.
+ * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
+ * Some systems may declare memset and memcpy in <memory.h>.
+ *
+ * NOTE: we assume the size parameters to these functions are of type size_t.
+ * Change the casts in these macros if not!
+ */
+
+#ifdef NEED_BSD_STRINGS
+
+#include <strings.h>
+#define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
+#define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
+
+#else /* not BSD, assume ANSI/SysV string lib */
+
+#include <string.h>
+#define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
+#define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
+
+#endif
+
+/*
+ * In ANSI C, and indeed any rational implementation, size_t is also the
+ * type returned by sizeof(). However, it seems there are some irrational
+ * implementations out there, in which sizeof() returns an int even though
+ * size_t is defined as long or unsigned long. To ensure consistent results
+ * we always use this SIZEOF() macro in place of using sizeof() directly.
+ */
+
+#define SIZEOF(object) ((size_t) sizeof(object))
+
+/*
+ * The modules that use fread() and fwrite() always invoke them through
+ * these macros. On some systems you may need to twiddle the argument casts.
+ * CAUTION: argument order is different from underlying functions!
+ */
+
+#define JFREAD(file,buf,sizeofbuf) \
+ ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
+#define JFWRITE(file,buf,sizeofbuf) \
+ ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
diff --git a/code/jpeg-6/jload.c b/code/jpeg-6/jload.c
new file mode 100755
index 0000000..5cbec78
--- /dev/null
+++ b/code/jpeg-6/jload.c
@@ -0,0 +1,145 @@
+
+#include "../game/q_shared.h"
+#include "../qcommon/qcommon.h"
+
+/*
+ * Include file for users of JPEG library.
+ * You will need to have included system headers that define at least
+ * the typedefs FILE and size_t before you can include jpeglib.h.
+ * (stdio.h is sufficient on ANSI-conforming systems.)
+ * You may also wish to include "jerror.h".
+ */
+
+#include "jpeglib.h"
+
+
+int LoadJPG( const char *filename, unsigned char **pic, int *width, int *height ) {
+ /* This struct contains the JPEG decompression parameters and pointers to
+ * working space (which is allocated as needed by the JPEG library).
+ */
+ struct jpeg_decompress_struct cinfo;
+ /* We use our private extension JPEG error handler.
+ * Note that this struct must live as long as the main JPEG parameter
+ * struct, to avoid dangling-pointer problems.
+ */
+ /* This struct represents a JPEG error handler. It is declared separately
+ * because applications often want to supply a specialized error handler
+ * (see the second half of this file for an example). But here we just
+ * take the easy way out and use the standard error handler, which will
+ * print a message on stderr and call exit() if compression fails.
+ * Note that this struct must live as long as the main JPEG parameter
+ * struct, to avoid dangling-pointer problems.
+ */
+ struct jpeg_error_mgr jerr;
+ /* More stuff */
+ fileHandle_t infile; /* source file */
+ JSAMPARRAY buffer; /* Output row buffer */
+ int row_stride; /* physical row width in output buffer */
+ unsigned char *out;
+
+ /* In this example we want to open the input file before doing anything else,
+ * so that the setjmp() error recovery below can assume the file is open.
+ * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
+ * requires it in order to read binary files.
+ */
+
+ FS_FOpenFileRead( filename, &infile, qfalse );
+ if (infile == 0) {
+ return 0;
+ }
+
+ /* Step 1: allocate and initialize JPEG decompression object */
+
+ /* We have to set up the error handler first, in case the initialization
+ * step fails. (Unlikely, but it could happen if you are out of memory.)
+ * This routine fills in the contents of struct jerr, and returns jerr's
+ * address which we place into the link field in cinfo.
+ */
+ cinfo.err = jpeg_std_error(&jerr);
+
+ /* Now we can initialize the JPEG decompression object. */
+ jpeg_create_decompress(&cinfo);
+
+ /* Step 2: specify data source (eg, a file) */
+
+ jpeg_stdio_src(&cinfo, infile);
+
+ /* Step 3: read file parameters with jpeg_read_header() */
+
+ (void) jpeg_read_header(&cinfo, TRUE);
+ /* We can ignore the return value from jpeg_read_header since
+ * (a) suspension is not possible with the stdio data source, and
+ * (b) we passed TRUE to reject a tables-only JPEG file as an error.
+ * See libjpeg.doc for more info.
+ */
+
+ /* Step 4: set parameters for decompression */
+
+ /* In this example, we don't need to change any of the defaults set by
+ * jpeg_read_header(), so we do nothing here.
+ */
+
+ /* Step 5: Start decompressor */
+
+ (void) jpeg_start_decompress(&cinfo);
+ /* We can ignore the return value since suspension is not possible
+ * with the stdio data source.
+ */
+
+ /* We may need to do some setup of our own at this point before reading
+ * the data. After jpeg_start_decompress() we have the correct scaled
+ * output image dimensions available, as well as the output colormap
+ * if we asked for color quantization.
+ * In this example, we need to make an output work buffer of the right size.
+ */
+ /* JSAMPLEs per row in output buffer */
+ row_stride = cinfo.output_width * cinfo.output_components;
+
+ out = Z_Malloc(cinfo.output_width*cinfo.output_height*cinfo.output_components);
+
+ *pic = out;
+ *width = cinfo.output_width;
+ *height = cinfo.output_height;
+
+ /* Step 6: while (scan lines remain to be read) */
+ /* jpeg_read_scanlines(...); */
+
+ /* Here we use the library's state variable cinfo.output_scanline as the
+ * loop counter, so that we don't have to keep track ourselves.
+ */
+ while (cinfo.output_scanline < cinfo.output_height) {
+ /* jpeg_read_scanlines expects an array of pointers to scanlines.
+ * Here the array is only one element long, but you could ask for
+ * more than one scanline at a time if that's more convenient.
+ */
+ buffer = (JSAMPARRAY)out+(row_stride*cinfo.output_scanline);
+ (void) jpeg_read_scanlines(&cinfo, buffer, 1);
+ }
+
+ /* Step 7: Finish decompression */
+
+ (void) jpeg_finish_decompress(&cinfo);
+ /* We can ignore the return value since suspension is not possible
+ * with the stdio data source.
+ */
+
+ /* Step 8: Release JPEG decompression object */
+
+ /* This is an important step since it will release a good deal of memory. */
+ jpeg_destroy_decompress(&cinfo);
+
+ /* After finish_decompress, we can close the input file.
+ * Here we postpone it until after no more JPEG errors are possible,
+ * so as to simplify the setjmp error logic above. (Actually, I don't
+ * think that jpeg_destroy can do an error exit, but why assume anything...)
+ */
+ FS_FCloseFile(infile);
+
+ /* At this point you may want to check to see whether any corrupt-data
+ * warnings occurred (test whether jerr.pub.num_warnings is nonzero).
+ */
+
+ /* And we're done! */
+ return 1;
+}
+
diff --git a/code/jpeg-6/jmemansi.c b/code/jpeg-6/jmemansi.c
new file mode 100755
index 0000000..b560d20
--- /dev/null
+++ b/code/jpeg-6/jmemansi.c
@@ -0,0 +1,167 @@
+/*
+ * jmemansi.c
+ *
+ * Copyright (C) 1992-1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file provides a simple generic implementation of the system-
+ * dependent portion of the JPEG memory manager. This implementation
+ * assumes that you have the ANSI-standard library routine tmpfile().
+ * Also, the problem of determining the amount of memory available
+ * is shoved onto the user.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jmemsys.h" /* import the system-dependent declarations */
+
+#ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
+extern void * malloc JPP((size_t size));
+extern void free JPP((void *ptr));
+#endif
+
+#ifndef SEEK_SET /* pre-ANSI systems may not define this; */
+#define SEEK_SET 0 /* if not, assume 0 is correct */
+#endif
+
+
+/*
+ * Memory allocation and freeing are controlled by the regular library
+ * routines malloc() and free().
+ */
+
+GLOBAL void *
+jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
+{
+ return (void *) malloc(sizeofobject);
+}
+
+GLOBAL void
+jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
+{
+ free(object);
+}
+
+
+/*
+ * "Large" objects are treated the same as "small" ones.
+ * NB: although we include FAR keywords in the routine declarations,
+ * this file won't actually work in 80x86 small/medium model; at least,
+ * you probably won't be able to process useful-size images in only 64KB.
+ */
+
+GLOBAL void FAR *
+jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
+{
+ return (void FAR *) malloc(sizeofobject);
+}
+
+GLOBAL void
+jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
+{
+ free(object);
+}
+
+
+/*
+ * This routine computes the total memory space available for allocation.
+ * It's impossible to do this in a portable way; our current solution is
+ * to make the user tell us (with a default value set at compile time).
+ * If you can actually get the available space, it's a good idea to subtract
+ * a slop factor of 5% or so.
+ */
+
+#ifndef DEFAULT_MAX_MEM /* so can override from makefile */
+#define DEFAULT_MAX_MEM 1000000L /* default: one megabyte */
+#endif
+
+GLOBAL long
+jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
+ long max_bytes_needed, long already_allocated)
+{
+ return cinfo->mem->max_memory_to_use - already_allocated;
+}
+
+
+/*
+ * Backing store (temporary file) management.
+ * Backing store objects are only used when the value returned by
+ * jpeg_mem_available is less than the total space needed. You can dispense
+ * with these routines if you have plenty of virtual memory; see jmemnobs.c.
+ */
+
+
+METHODDEF void
+read_backing_store (j_common_ptr cinfo, backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count)
+{
+ if (fseek(info->temp_file, file_offset, SEEK_SET))
+ ERREXIT(cinfo, JERR_TFILE_SEEK);
+ if (JFREAD(info->temp_file, buffer_address, byte_count)
+ != (size_t) byte_count)
+ ERREXIT(cinfo, JERR_TFILE_READ);
+}
+
+
+METHODDEF void
+write_backing_store (j_common_ptr cinfo, backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count)
+{
+ if (fseek(info->temp_file, file_offset, SEEK_SET))
+ ERREXIT(cinfo, JERR_TFILE_SEEK);
+ if (JFWRITE(info->temp_file, buffer_address, byte_count)
+ != (size_t) byte_count)
+ ERREXIT(cinfo, JERR_TFILE_WRITE);
+}
+
+
+METHODDEF void
+close_backing_store (j_common_ptr cinfo, backing_store_ptr info)
+{
+ fclose(info->temp_file);
+ /* Since this implementation uses tmpfile() to create the file,
+ * no explicit file deletion is needed.
+ */
+}
+
+
+/*
+ * Initial opening of a backing-store object.
+ *
+ * This version uses tmpfile(), which constructs a suitable file name
+ * behind the scenes. We don't have to use info->temp_name[] at all;
+ * indeed, we can't even find out the actual name of the temp file.
+ */
+
+GLOBAL void
+jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info,
+ long total_bytes_needed)
+{
+ if ((info->temp_file = tmpfile()) == NULL)
+ ERREXITS(cinfo, JERR_TFILE_CREATE, "");
+ info->read_backing_store = read_backing_store;
+ info->write_backing_store = write_backing_store;
+ info->close_backing_store = close_backing_store;
+}
+
+
+/*
+ * These routines take care of any system-dependent initialization and
+ * cleanup required.
+ */
+
+GLOBAL long
+jpeg_mem_init (j_common_ptr cinfo)
+{
+ return DEFAULT_MAX_MEM; /* default for max_memory_to_use */
+}
+
+GLOBAL void
+jpeg_mem_term (j_common_ptr cinfo)
+{
+ /* no work */
+}
diff --git a/code/jpeg-6/jmemdos.c b/code/jpeg-6/jmemdos.c
new file mode 100755
index 0000000..fd4a923
--- /dev/null
+++ b/code/jpeg-6/jmemdos.c
@@ -0,0 +1,634 @@
+/*
+ * jmemdos.c
+ *
+ * Copyright (C) 1992-1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file provides an MS-DOS-compatible implementation of the system-
+ * dependent portion of the JPEG memory manager. Temporary data can be
+ * stored in extended or expanded memory as well as in regular DOS files.
+ *
+ * If you use this file, you must be sure that NEED_FAR_POINTERS is defined
+ * if you compile in a small-data memory model; it should NOT be defined if
+ * you use a large-data memory model. This file is not recommended if you
+ * are using a flat-memory-space 386 environment such as DJGCC or Watcom C.
+ * Also, this code will NOT work if struct fields are aligned on greater than
+ * 2-byte boundaries.
+ *
+ * Based on code contributed by Ge' Weijers.
+ */
+
+/*
+ * If you have both extended and expanded memory, you may want to change the
+ * order in which they are tried in jopen_backing_store. On a 286 machine
+ * expanded memory is usually faster, since extended memory access involves
+ * an expensive protected-mode-and-back switch. On 386 and better, extended
+ * memory is usually faster. As distributed, the code tries extended memory
+ * first (what? not everyone has a 386? :-).
+ *
+ * You can disable use of extended/expanded memory entirely by altering these
+ * definitions or overriding them from the Makefile (eg, -DEMS_SUPPORTED=0).
+ */
+
+#ifndef XMS_SUPPORTED
+#define XMS_SUPPORTED 1
+#endif
+#ifndef EMS_SUPPORTED
+#define EMS_SUPPORTED 1
+#endif
+
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jmemsys.h" /* import the system-dependent declarations */
+
+#ifndef HAVE_STDLIB_H /* <stdlib.h> should declare these */
+extern void * malloc JPP((size_t size));
+extern void free JPP((void *ptr));
+extern char * getenv JPP((const char * name));
+#endif
+
+#ifdef NEED_FAR_POINTERS
+
+#ifdef __TURBOC__
+/* These definitions work for Borland C (Turbo C) */
+#include <alloc.h> /* need farmalloc(), farfree() */
+#define far_malloc(x) farmalloc(x)
+#define far_free(x) farfree(x)
+#else
+/* These definitions work for Microsoft C and compatible compilers */
+#include <malloc.h> /* need _fmalloc(), _ffree() */
+#define far_malloc(x) _fmalloc(x)
+#define far_free(x) _ffree(x)
+#endif
+
+#else /* not NEED_FAR_POINTERS */
+
+#define far_malloc(x) malloc(x)
+#define far_free(x) free(x)
+
+#endif /* NEED_FAR_POINTERS */
+
+#ifdef DONT_USE_B_MODE /* define mode parameters for fopen() */
+#define READ_BINARY "r"
+#else
+#define READ_BINARY "rb"
+#endif
+
+#if MAX_ALLOC_CHUNK >= 65535L /* make sure jconfig.h got this right */
+ MAX_ALLOC_CHUNK should be less than 64K. /* deliberate syntax error */
+#endif
+
+
+/*
+ * Declarations for assembly-language support routines (see jmemdosa.asm).
+ *
+ * The functions are declared "far" as are all pointer arguments;
+ * this ensures the assembly source code will work regardless of the
+ * compiler memory model. We assume "short" is 16 bits, "long" is 32.
+ */
+
+typedef void far * XMSDRIVER; /* actually a pointer to code */
+typedef struct { /* registers for calling XMS driver */
+ unsigned short ax, dx, bx;
+ void far * ds_si;
+ } XMScontext;
+typedef struct { /* registers for calling EMS driver */
+ unsigned short ax, dx, bx;
+ void far * ds_si;
+ } EMScontext;
+
+EXTERN short far jdos_open JPP((short far * handle, char far * filename));
+EXTERN short far jdos_close JPP((short handle));
+EXTERN short far jdos_seek JPP((short handle, long offset));
+EXTERN short far jdos_read JPP((short handle, void far * buffer,
+ unsigned short count));
+EXTERN short far jdos_write JPP((short handle, void far * buffer,
+ unsigned short count));
+EXTERN void far jxms_getdriver JPP((XMSDRIVER far *));
+EXTERN void far jxms_calldriver JPP((XMSDRIVER, XMScontext far *));
+EXTERN short far jems_available JPP((void));
+EXTERN void far jems_calldriver JPP((EMScontext far *));
+
+
+/*
+ * Selection of a file name for a temporary file.
+ * This is highly system-dependent, and you may want to customize it.
+ */
+
+static int next_file_num; /* to distinguish among several temp files */
+
+LOCAL void
+select_file_name (char * fname)
+{
+ const char * env;
+ char * ptr;
+ FILE * tfile;
+
+ /* Keep generating file names till we find one that's not in use */
+ for (;;) {
+ /* Get temp directory name from environment TMP or TEMP variable;
+ * if none, use "."
+ */
+ if ((env = (const char *) getenv("TMP")) == NULL)
+ if ((env = (const char *) getenv("TEMP")) == NULL)
+ env = ".";
+ if (*env == '\0') /* null string means "." */
+ env = ".";
+ ptr = fname; /* copy name to fname */
+ while (*env != '\0')
+ *ptr++ = *env++;
+ if (ptr[-1] != '\\' && ptr[-1] != '/')
+ *ptr++ = '\\'; /* append backslash if not in env variable */
+ /* Append a suitable file name */
+ next_file_num++; /* advance counter */
+ sprintf(ptr, "JPG%03d.TMP", next_file_num);
+ /* Probe to see if file name is already in use */
+ if ((tfile = fopen(fname, READ_BINARY)) == NULL)
+ break;
+ fclose(tfile); /* oops, it's there; close tfile & try again */
+ }
+}
+
+
+/*
+ * Near-memory allocation and freeing are controlled by the regular library
+ * routines malloc() and free().
+ */
+
+GLOBAL void *
+jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
+{
+ return (void *) malloc(sizeofobject);
+}
+
+GLOBAL void
+jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
+{
+ free(object);
+}
+
+
+/*
+ * "Large" objects are allocated in far memory, if possible
+ */
+
+GLOBAL void FAR *
+jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
+{
+ return (void FAR *) far_malloc(sizeofobject);
+}
+
+GLOBAL void
+jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
+{
+ far_free(object);
+}
+
+
+/*
+ * This routine computes the total memory space available for allocation.
+ * It's impossible to do this in a portable way; our current solution is
+ * to make the user tell us (with a default value set at compile time).
+ * If you can actually get the available space, it's a good idea to subtract
+ * a slop factor of 5% or so.
+ */
+
+#ifndef DEFAULT_MAX_MEM /* so can override from makefile */
+#define DEFAULT_MAX_MEM 300000L /* for total usage about 450K */
+#endif
+
+GLOBAL long
+jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
+ long max_bytes_needed, long already_allocated)
+{
+ return cinfo->mem->max_memory_to_use - already_allocated;
+}
+
+
+/*
+ * Backing store (temporary file) management.
+ * Backing store objects are only used when the value returned by
+ * jpeg_mem_available is less than the total space needed. You can dispense
+ * with these routines if you have plenty of virtual memory; see jmemnobs.c.
+ */
+
+/*
+ * For MS-DOS we support three types of backing storage:
+ * 1. Conventional DOS files. We access these by direct DOS calls rather
+ * than via the stdio package. This provides a bit better performance,
+ * but the real reason is that the buffers to be read or written are FAR.
+ * The stdio library for small-data memory models can't cope with that.
+ * 2. Extended memory, accessed per the XMS V2.0 specification.
+ * 3. Expanded memory, accessed per the LIM/EMS 4.0 specification.
+ * You'll need copies of those specs to make sense of the related code.
+ * The specs are available by Internet FTP from the SIMTEL archives
+ * (oak.oakland.edu and its various mirror sites). See files
+ * pub/msdos/microsoft/xms20.arc and pub/msdos/info/limems41.zip.
+ */
+
+
+/*
+ * Access methods for a DOS file.
+ */
+
+
+METHODDEF void
+read_file_store (j_common_ptr cinfo, backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count)
+{
+ if (jdos_seek(info->handle.file_handle, file_offset))
+ ERREXIT(cinfo, JERR_TFILE_SEEK);
+ /* Since MAX_ALLOC_CHUNK is less than 64K, byte_count will be too. */
+ if (byte_count > 65535L) /* safety check */
+ ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
+ if (jdos_read(info->handle.file_handle, buffer_address,
+ (unsigned short) byte_count))
+ ERREXIT(cinfo, JERR_TFILE_READ);
+}
+
+
+METHODDEF void
+write_file_store (j_common_ptr cinfo, backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count)
+{
+ if (jdos_seek(info->handle.file_handle, file_offset))
+ ERREXIT(cinfo, JERR_TFILE_SEEK);
+ /* Since MAX_ALLOC_CHUNK is less than 64K, byte_count will be too. */
+ if (byte_count > 65535L) /* safety check */
+ ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
+ if (jdos_write(info->handle.file_handle, buffer_address,
+ (unsigned short) byte_count))
+ ERREXIT(cinfo, JERR_TFILE_WRITE);
+}
+
+
+METHODDEF void
+close_file_store (j_common_ptr cinfo, backing_store_ptr info)
+{
+ jdos_close(info->handle.file_handle); /* close the file */
+ remove(info->temp_name); /* delete the file */
+/* If your system doesn't have remove(), try unlink() instead.
+ * remove() is the ANSI-standard name for this function, but
+ * unlink() was more common in pre-ANSI systems.
+ */
+ TRACEMSS(cinfo, 1, JTRC_TFILE_CLOSE, info->temp_name);
+}
+
+
+LOCAL boolean
+open_file_store (j_common_ptr cinfo, backing_store_ptr info,
+ long total_bytes_needed)
+{
+ short handle;
+
+ select_file_name(info->temp_name);
+ if (jdos_open((short far *) & handle, (char far *) info->temp_name)) {
+ /* might as well exit since jpeg_open_backing_store will fail anyway */
+ ERREXITS(cinfo, JERR_TFILE_CREATE, info->temp_name);
+ return FALSE;
+ }
+ info->handle.file_handle = handle;
+ info->read_backing_store = read_file_store;
+ info->write_backing_store = write_file_store;
+ info->close_backing_store = close_file_store;
+ TRACEMSS(cinfo, 1, JTRC_TFILE_OPEN, info->temp_name);
+ return TRUE; /* succeeded */
+}
+
+
+/*
+ * Access methods for extended memory.
+ */
+
+#if XMS_SUPPORTED
+
+static XMSDRIVER xms_driver; /* saved address of XMS driver */
+
+typedef union { /* either long offset or real-mode pointer */
+ long offset;
+ void far * ptr;
+ } XMSPTR;
+
+typedef struct { /* XMS move specification structure */
+ long length;
+ XMSH src_handle;
+ XMSPTR src;
+ XMSH dst_handle;
+ XMSPTR dst;
+ } XMSspec;
+
+#define ODD(X) (((X) & 1L) != 0)
+
+
+METHODDEF void
+read_xms_store (j_common_ptr cinfo, backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count)
+{
+ XMScontext ctx;
+ XMSspec spec;
+ char endbuffer[2];
+
+ /* The XMS driver can't cope with an odd length, so handle the last byte
+ * specially if byte_count is odd. We don't expect this to be common.
+ */
+
+ spec.length = byte_count & (~ 1L);
+ spec.src_handle = info->handle.xms_handle;
+ spec.src.offset = file_offset;
+ spec.dst_handle = 0;
+ spec.dst.ptr = buffer_address;
+
+ ctx.ds_si = (void far *) & spec;
+ ctx.ax = 0x0b00; /* EMB move */
+ jxms_calldriver(xms_driver, (XMScontext far *) & ctx);
+ if (ctx.ax != 1)
+ ERREXIT(cinfo, JERR_XMS_READ);
+
+ if (ODD(byte_count)) {
+ read_xms_store(cinfo, info, (void FAR *) endbuffer,
+ file_offset + byte_count - 1L, 2L);
+ ((char FAR *) buffer_address)[byte_count - 1L] = endbuffer[0];
+ }
+}
+
+
+METHODDEF void
+write_xms_store (j_common_ptr cinfo, backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count)
+{
+ XMScontext ctx;
+ XMSspec spec;
+ char endbuffer[2];
+
+ /* The XMS driver can't cope with an odd length, so handle the last byte
+ * specially if byte_count is odd. We don't expect this to be common.
+ */
+
+ spec.length = byte_count & (~ 1L);
+ spec.src_handle = 0;
+ spec.src.ptr = buffer_address;
+ spec.dst_handle = info->handle.xms_handle;
+ spec.dst.offset = file_offset;
+
+ ctx.ds_si = (void far *) & spec;
+ ctx.ax = 0x0b00; /* EMB move */
+ jxms_calldriver(xms_driver, (XMScontext far *) & ctx);
+ if (ctx.ax != 1)
+ ERREXIT(cinfo, JERR_XMS_WRITE);
+
+ if (ODD(byte_count)) {
+ read_xms_store(cinfo, info, (void FAR *) endbuffer,
+ file_offset + byte_count - 1L, 2L);
+ endbuffer[0] = ((char FAR *) buffer_address)[byte_count - 1L];
+ write_xms_store(cinfo, info, (void FAR *) endbuffer,
+ file_offset + byte_count - 1L, 2L);
+ }
+}
+
+
+METHODDEF void
+close_xms_store (j_common_ptr cinfo, backing_store_ptr info)
+{
+ XMScontext ctx;
+
+ ctx.dx = info->handle.xms_handle;
+ ctx.ax = 0x0a00;
+ jxms_calldriver(xms_driver, (XMScontext far *) & ctx);
+ TRACEMS1(cinfo, 1, JTRC_XMS_CLOSE, info->handle.xms_handle);
+ /* we ignore any error return from the driver */
+}
+
+
+LOCAL boolean
+open_xms_store (j_common_ptr cinfo, backing_store_ptr info,
+ long total_bytes_needed)
+{
+ XMScontext ctx;
+
+ /* Get address of XMS driver */
+ jxms_getdriver((XMSDRIVER far *) & xms_driver);
+ if (xms_driver == NULL)
+ return FALSE; /* no driver to be had */
+
+ /* Get version number, must be >= 2.00 */
+ ctx.ax = 0x0000;
+ jxms_calldriver(xms_driver, (XMScontext far *) & ctx);
+ if (ctx.ax < (unsigned short) 0x0200)
+ return FALSE;
+
+ /* Try to get space (expressed in kilobytes) */
+ ctx.dx = (unsigned short) ((total_bytes_needed + 1023L) >> 10);
+ ctx.ax = 0x0900;
+ jxms_calldriver(xms_driver, (XMScontext far *) & ctx);
+ if (ctx.ax != 1)
+ return FALSE;
+
+ /* Succeeded, save the handle and away we go */
+ info->handle.xms_handle = ctx.dx;
+ info->read_backing_store = read_xms_store;
+ info->write_backing_store = write_xms_store;
+ info->close_backing_store = close_xms_store;
+ TRACEMS1(cinfo, 1, JTRC_XMS_OPEN, ctx.dx);
+ return TRUE; /* succeeded */
+}
+
+#endif /* XMS_SUPPORTED */
+
+
+/*
+ * Access methods for expanded memory.
+ */
+
+#if EMS_SUPPORTED
+
+/* The EMS move specification structure requires word and long fields aligned
+ * at odd byte boundaries. Some compilers will align struct fields at even
+ * byte boundaries. While it's usually possible to force byte alignment,
+ * that causes an overall performance penalty and may pose problems in merging
+ * JPEG into a larger application. Instead we accept some rather dirty code
+ * here. Note this code would fail if the hardware did not allow odd-byte
+ * word & long accesses, but all 80x86 CPUs do.
+ */
+
+typedef void far * EMSPTR;
+
+typedef union { /* EMS move specification structure */
+ long length; /* It's easy to access first 4 bytes */
+ char bytes[18]; /* Misaligned fields in here! */
+ } EMSspec;
+
+/* Macros for accessing misaligned fields */
+#define FIELD_AT(spec,offset,type) (*((type *) &(spec.bytes[offset])))
+#define SRC_TYPE(spec) FIELD_AT(spec,4,char)
+#define SRC_HANDLE(spec) FIELD_AT(spec,5,EMSH)
+#define SRC_OFFSET(spec) FIELD_AT(spec,7,unsigned short)
+#define SRC_PAGE(spec) FIELD_AT(spec,9,unsigned short)
+#define SRC_PTR(spec) FIELD_AT(spec,7,EMSPTR)
+#define DST_TYPE(spec) FIELD_AT(spec,11,char)
+#define DST_HANDLE(spec) FIELD_AT(spec,12,EMSH)
+#define DST_OFFSET(spec) FIELD_AT(spec,14,unsigned short)
+#define DST_PAGE(spec) FIELD_AT(spec,16,unsigned short)
+#define DST_PTR(spec) FIELD_AT(spec,14,EMSPTR)
+
+#define EMSPAGESIZE 16384L /* gospel, see the EMS specs */
+
+#define HIBYTE(W) (((W) >> 8) & 0xFF)
+#define LOBYTE(W) ((W) & 0xFF)
+
+
+METHODDEF void
+read_ems_store (j_common_ptr cinfo, backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count)
+{
+ EMScontext ctx;
+ EMSspec spec;
+
+ spec.length = byte_count;
+ SRC_TYPE(spec) = 1;
+ SRC_HANDLE(spec) = info->handle.ems_handle;
+ SRC_PAGE(spec) = (unsigned short) (file_offset / EMSPAGESIZE);
+ SRC_OFFSET(spec) = (unsigned short) (file_offset % EMSPAGESIZE);
+ DST_TYPE(spec) = 0;
+ DST_HANDLE(spec) = 0;
+ DST_PTR(spec) = buffer_address;
+
+ ctx.ds_si = (void far *) & spec;
+ ctx.ax = 0x5700; /* move memory region */
+ jems_calldriver((EMScontext far *) & ctx);
+ if (HIBYTE(ctx.ax) != 0)
+ ERREXIT(cinfo, JERR_EMS_READ);
+}
+
+
+METHODDEF void
+write_ems_store (j_common_ptr cinfo, backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count)
+{
+ EMScontext ctx;
+ EMSspec spec;
+
+ spec.length = byte_count;
+ SRC_TYPE(spec) = 0;
+ SRC_HANDLE(spec) = 0;
+ SRC_PTR(spec) = buffer_address;
+ DST_TYPE(spec) = 1;
+ DST_HANDLE(spec) = info->handle.ems_handle;
+ DST_PAGE(spec) = (unsigned short) (file_offset / EMSPAGESIZE);
+ DST_OFFSET(spec) = (unsigned short) (file_offset % EMSPAGESIZE);
+
+ ctx.ds_si = (void far *) & spec;
+ ctx.ax = 0x5700; /* move memory region */
+ jems_calldriver((EMScontext far *) & ctx);
+ if (HIBYTE(ctx.ax) != 0)
+ ERREXIT(cinfo, JERR_EMS_WRITE);
+}
+
+
+METHODDEF void
+close_ems_store (j_common_ptr cinfo, backing_store_ptr info)
+{
+ EMScontext ctx;
+
+ ctx.ax = 0x4500;
+ ctx.dx = info->handle.ems_handle;
+ jems_calldriver((EMScontext far *) & ctx);
+ TRACEMS1(cinfo, 1, JTRC_EMS_CLOSE, info->handle.ems_handle);
+ /* we ignore any error return from the driver */
+}
+
+
+LOCAL boolean
+open_ems_store (j_common_ptr cinfo, backing_store_ptr info,
+ long total_bytes_needed)
+{
+ EMScontext ctx;
+
+ /* Is EMS driver there? */
+ if (! jems_available())
+ return FALSE;
+
+ /* Get status, make sure EMS is OK */
+ ctx.ax = 0x4000;
+ jems_calldriver((EMScontext far *) & ctx);
+ if (HIBYTE(ctx.ax) != 0)
+ return FALSE;
+
+ /* Get version, must be >= 4.0 */
+ ctx.ax = 0x4600;
+ jems_calldriver((EMScontext far *) & ctx);
+ if (HIBYTE(ctx.ax) != 0 || LOBYTE(ctx.ax) < 0x40)
+ return FALSE;
+
+ /* Try to allocate requested space */
+ ctx.ax = 0x4300;
+ ctx.bx = (unsigned short) ((total_bytes_needed + EMSPAGESIZE-1L) / EMSPAGESIZE);
+ jems_calldriver((EMScontext far *) & ctx);
+ if (HIBYTE(ctx.ax) != 0)
+ return FALSE;
+
+ /* Succeeded, save the handle and away we go */
+ info->handle.ems_handle = ctx.dx;
+ info->read_backing_store = read_ems_store;
+ info->write_backing_store = write_ems_store;
+ info->close_backing_store = close_ems_store;
+ TRACEMS1(cinfo, 1, JTRC_EMS_OPEN, ctx.dx);
+ return TRUE; /* succeeded */
+}
+
+#endif /* EMS_SUPPORTED */
+
+
+/*
+ * Initial opening of a backing-store object.
+ */
+
+GLOBAL void
+jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info,
+ long total_bytes_needed)
+{
+ /* Try extended memory, then expanded memory, then regular file. */
+#if XMS_SUPPORTED
+ if (open_xms_store(cinfo, info, total_bytes_needed))
+ return;
+#endif
+#if EMS_SUPPORTED
+ if (open_ems_store(cinfo, info, total_bytes_needed))
+ return;
+#endif
+ if (open_file_store(cinfo, info, total_bytes_needed))
+ return;
+ ERREXITS(cinfo, JERR_TFILE_CREATE, "");
+}
+
+
+/*
+ * These routines take care of any system-dependent initialization and
+ * cleanup required.
+ */
+
+GLOBAL long
+jpeg_mem_init (j_common_ptr cinfo)
+{
+ next_file_num = 0; /* initialize temp file name generator */
+ return DEFAULT_MAX_MEM; /* default for max_memory_to_use */
+}
+
+GLOBAL void
+jpeg_mem_term (j_common_ptr cinfo)
+{
+ /* Microsoft C, at least in v6.00A, will not successfully reclaim freed
+ * blocks of size > 32Kbytes unless we give it a kick in the rear, like so:
+ */
+#ifdef NEED_FHEAPMIN
+ _fheapmin();
+#endif
+}
diff --git a/code/jpeg-6/jmemmgr.c b/code/jpeg-6/jmemmgr.c
new file mode 100755
index 0000000..61045f9
--- /dev/null
+++ b/code/jpeg-6/jmemmgr.c
@@ -0,0 +1,1115 @@
+/*
+ * jmemmgr.c
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the JPEG system-independent memory management
+ * routines. This code is usable across a wide variety of machines; most
+ * of the system dependencies have been isolated in a separate file.
+ * The major functions provided here are:
+ * * pool-based allocation and freeing of memory;
+ * * policy decisions about how to divide available memory among the
+ * virtual arrays;
+ * * control logic for swapping virtual arrays between main memory and
+ * backing storage.
+ * The separate system-dependent file provides the actual backing-storage
+ * access code, and it contains the policy decision about how much total
+ * main memory to use.
+ * This file is system-dependent in the sense that some of its functions
+ * are unnecessary in some systems. For example, if there is enough virtual
+ * memory so that backing storage will never be used, much of the virtual
+ * array control logic could be removed. (Of course, if you have that much
+ * memory then you shouldn't care about a little bit of unused code...)
+ */
+
+#define JPEG_INTERNALS
+#define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jmemsys.h" /* import the system-dependent declarations */
+
+#ifndef NO_GETENV
+#ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
+extern char * getenv JPP((const char * name));
+#endif
+#endif
+
+
+/*
+ * Some important notes:
+ * The allocation routines provided here must never return NULL.
+ * They should exit to error_exit if unsuccessful.
+ *
+ * It's not a good idea to try to merge the sarray and barray routines,
+ * even though they are textually almost the same, because samples are
+ * usually stored as bytes while coefficients are shorts or ints. Thus,
+ * in machines where byte pointers have a different representation from
+ * word pointers, the resulting machine code could not be the same.
+ */
+
+
+/*
+ * Many machines require storage alignment: longs must start on 4-byte
+ * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
+ * always returns pointers that are multiples of the worst-case alignment
+ * requirement, and we had better do so too.
+ * There isn't any really portable way to determine the worst-case alignment
+ * requirement. This module assumes that the alignment requirement is
+ * multiples of sizeof(ALIGN_TYPE).
+ * By default, we define ALIGN_TYPE as double. This is necessary on some
+ * workstations (where doubles really do need 8-byte alignment) and will work
+ * fine on nearly everything. If your machine has lesser alignment needs,
+ * you can save a few bytes by making ALIGN_TYPE smaller.
+ * The only place I know of where this will NOT work is certain Macintosh
+ * 680x0 compilers that define double as a 10-byte IEEE extended float.
+ * Doing 10-byte alignment is counterproductive because longwords won't be
+ * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
+ * such a compiler.
+ */
+
+#ifndef ALIGN_TYPE /* so can override from jconfig.h */
+#define ALIGN_TYPE double
+#endif
+
+
+/*
+ * We allocate objects from "pools", where each pool is gotten with a single
+ * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
+ * overhead within a pool, except for alignment padding. Each pool has a
+ * header with a link to the next pool of the same class.
+ * Small and large pool headers are identical except that the latter's
+ * link pointer must be FAR on 80x86 machines.
+ * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
+ * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
+ * of the alignment requirement of ALIGN_TYPE.
+ */
+
+typedef union small_pool_struct * small_pool_ptr;
+
+typedef union small_pool_struct {
+ struct {
+ small_pool_ptr next; /* next in list of pools */
+ size_t bytes_used; /* how many bytes already used within pool */
+ size_t bytes_left; /* bytes still available in this pool */
+ } hdr;
+ ALIGN_TYPE dummy; /* included in union to ensure alignment */
+} small_pool_hdr;
+
+typedef union large_pool_struct FAR * large_pool_ptr;
+
+typedef union large_pool_struct {
+ struct {
+ large_pool_ptr next; /* next in list of pools */
+ size_t bytes_used; /* how many bytes already used within pool */
+ size_t bytes_left; /* bytes still available in this pool */
+ } hdr;
+ ALIGN_TYPE dummy; /* included in union to ensure alignment */
+} large_pool_hdr;
+
+
+/*
+ * Here is the full definition of a memory manager object.
+ */
+
+typedef struct {
+ struct jpeg_memory_mgr pub; /* public fields */
+
+ /* Each pool identifier (lifetime class) names a linked list of pools. */
+ small_pool_ptr small_list[JPOOL_NUMPOOLS];
+ large_pool_ptr large_list[JPOOL_NUMPOOLS];
+
+ /* Since we only have one lifetime class of virtual arrays, only one
+ * linked list is necessary (for each datatype). Note that the virtual
+ * array control blocks being linked together are actually stored somewhere
+ * in the small-pool list.
+ */
+ jvirt_sarray_ptr virt_sarray_list;
+ jvirt_barray_ptr virt_barray_list;
+
+ /* This counts total space obtained from jpeg_get_small/large */
+ long total_space_allocated;
+
+ /* alloc_sarray and alloc_barray set this value for use by virtual
+ * array routines.
+ */
+ JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
+} my_memory_mgr;
+
+typedef my_memory_mgr * my_mem_ptr;
+
+
+/*
+ * The control blocks for virtual arrays.
+ * Note that these blocks are allocated in the "small" pool area.
+ * System-dependent info for the associated backing store (if any) is hidden
+ * inside the backing_store_info struct.
+ */
+
+struct jvirt_sarray_control {
+ JSAMPARRAY mem_buffer; /* => the in-memory buffer */
+ JDIMENSION rows_in_array; /* total virtual array height */
+ JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
+ JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
+ JDIMENSION rows_in_mem; /* height of memory buffer */
+ JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
+ JDIMENSION cur_start_row; /* first logical row # in the buffer */
+ JDIMENSION first_undef_row; /* row # of first uninitialized row */
+ boolean pre_zero; /* pre-zero mode requested? */
+ boolean dirty; /* do current buffer contents need written? */
+ boolean b_s_open; /* is backing-store data valid? */
+ jvirt_sarray_ptr next; /* link to next virtual sarray control block */
+ backing_store_info b_s_info; /* System-dependent control info */
+};
+
+struct jvirt_barray_control {
+ JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
+ JDIMENSION rows_in_array; /* total virtual array height */
+ JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
+ JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
+ JDIMENSION rows_in_mem; /* height of memory buffer */
+ JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
+ JDIMENSION cur_start_row; /* first logical row # in the buffer */
+ JDIMENSION first_undef_row; /* row # of first uninitialized row */
+ boolean pre_zero; /* pre-zero mode requested? */
+ boolean dirty; /* do current buffer contents need written? */
+ boolean b_s_open; /* is backing-store data valid? */
+ jvirt_barray_ptr next; /* link to next virtual barray control block */
+ backing_store_info b_s_info; /* System-dependent control info */
+};
+
+
+#ifdef MEM_STATS /* optional extra stuff for statistics */
+
+LOCAL void
+print_mem_stats (j_common_ptr cinfo, int pool_id)
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ small_pool_ptr shdr_ptr;
+ large_pool_ptr lhdr_ptr;
+
+ /* Since this is only a debugging stub, we can cheat a little by using
+ * fprintf directly rather than going through the trace message code.
+ * This is helpful because message parm array can't handle longs.
+ */
+ fprintf(stderr, "Freeing pool %d, total space = %ld\n",
+ pool_id, mem->total_space_allocated);
+
+ for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
+ lhdr_ptr = lhdr_ptr->hdr.next) {
+ fprintf(stderr, " Large chunk used %ld\n",
+ (long) lhdr_ptr->hdr.bytes_used);
+ }
+
+ for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
+ shdr_ptr = shdr_ptr->hdr.next) {
+ fprintf(stderr, " Small chunk used %ld free %ld\n",
+ (long) shdr_ptr->hdr.bytes_used,
+ (long) shdr_ptr->hdr.bytes_left);
+ }
+}
+
+#endif /* MEM_STATS */
+
+
+LOCAL void
+out_of_memory (j_common_ptr cinfo, int which)
+/* Report an out-of-memory error and stop execution */
+/* If we compiled MEM_STATS support, report alloc requests before dying */
+{
+#ifdef MEM_STATS
+ cinfo->err->trace_level = 2; /* force self_destruct to report stats */
+#endif
+ ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
+}
+
+
+/*
+ * Allocation of "small" objects.
+ *
+ * For these, we use pooled storage. When a new pool must be created,
+ * we try to get enough space for the current request plus a "slop" factor,
+ * where the slop will be the amount of leftover space in the new pool.
+ * The speed vs. space tradeoff is largely determined by the slop values.
+ * A different slop value is provided for each pool class (lifetime),
+ * and we also distinguish the first pool of a class from later ones.
+ * NOTE: the values given work fairly well on both 16- and 32-bit-int
+ * machines, but may be too small if longs are 64 bits or more.
+ */
+
+static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
+{
+ 1600, /* first PERMANENT pool */
+ 16000 /* first IMAGE pool */
+};
+
+static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
+{
+ 0, /* additional PERMANENT pools */
+ 5000 /* additional IMAGE pools */
+};
+
+#define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
+
+
+METHODDEF void *
+alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
+/* Allocate a "small" object */
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ small_pool_ptr hdr_ptr, prev_hdr_ptr;
+ char * data_ptr;
+ size_t odd_bytes, min_request, slop;
+
+ /* Check for unsatisfiable request (do now to ensure no overflow below) */
+ if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
+ out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
+
+ /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
+ odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
+ if (odd_bytes > 0)
+ sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
+
+ /* See if space is available in any existing pool */
+ if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
+ ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
+ prev_hdr_ptr = NULL;
+ hdr_ptr = mem->small_list[pool_id];
+ while (hdr_ptr != NULL) {
+ if (hdr_ptr->hdr.bytes_left >= sizeofobject)
+ break; /* found pool with enough space */
+ prev_hdr_ptr = hdr_ptr;
+ hdr_ptr = hdr_ptr->hdr.next;
+ }
+
+ /* Time to make a new pool? */
+ if (hdr_ptr == NULL) {
+ /* min_request is what we need now, slop is what will be leftover */
+ min_request = sizeofobject + SIZEOF(small_pool_hdr);
+ if (prev_hdr_ptr == NULL) /* first pool in class? */
+ slop = first_pool_slop[pool_id];
+ else
+ slop = extra_pool_slop[pool_id];
+ /* Don't ask for more than MAX_ALLOC_CHUNK */
+ if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
+ slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
+ /* Try to get space, if fail reduce slop and try again */
+ for (;;) {
+ hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
+ if (hdr_ptr != NULL)
+ break;
+ slop /= 2;
+ if (slop < MIN_SLOP) /* give up when it gets real small */
+ out_of_memory(cinfo, 2); /* jpeg_get_small failed */
+ }
+ mem->total_space_allocated += min_request + slop;
+ /* Success, initialize the new pool header and add to end of list */
+ hdr_ptr->hdr.next = NULL;
+ hdr_ptr->hdr.bytes_used = 0;
+ hdr_ptr->hdr.bytes_left = sizeofobject + slop;
+ if (prev_hdr_ptr == NULL) /* first pool in class? */
+ mem->small_list[pool_id] = hdr_ptr;
+ else
+ prev_hdr_ptr->hdr.next = hdr_ptr;
+ }
+
+ /* OK, allocate the object from the current pool */
+ data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
+ data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
+ hdr_ptr->hdr.bytes_used += sizeofobject;
+ hdr_ptr->hdr.bytes_left -= sizeofobject;
+
+ return (void *) data_ptr;
+}
+
+
+/*
+ * Allocation of "large" objects.
+ *
+ * The external semantics of these are the same as "small" objects,
+ * except that FAR pointers are used on 80x86. However the pool
+ * management heuristics are quite different. We assume that each
+ * request is large enough that it may as well be passed directly to
+ * jpeg_get_large; the pool management just links everything together
+ * so that we can free it all on demand.
+ * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
+ * structures. The routines that create these structures (see below)
+ * deliberately bunch rows together to ensure a large request size.
+ */
+
+METHODDEF void FAR *
+alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
+/* Allocate a "large" object */
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ large_pool_ptr hdr_ptr;
+ size_t odd_bytes;
+
+ /* Check for unsatisfiable request (do now to ensure no overflow below) */
+ if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
+ out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
+
+ /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
+ odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
+ if (odd_bytes > 0)
+ sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
+
+ /* Always make a new pool */
+ if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
+ ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
+
+ hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
+ SIZEOF(large_pool_hdr));
+ if (hdr_ptr == NULL)
+ out_of_memory(cinfo, 4); /* jpeg_get_large failed */
+ mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
+
+ /* Success, initialize the new pool header and add to list */
+ hdr_ptr->hdr.next = mem->large_list[pool_id];
+ /* We maintain space counts in each pool header for statistical purposes,
+ * even though they are not needed for allocation.
+ */
+ hdr_ptr->hdr.bytes_used = sizeofobject;
+ hdr_ptr->hdr.bytes_left = 0;
+ mem->large_list[pool_id] = hdr_ptr;
+
+ return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
+}
+
+
+/*
+ * Creation of 2-D sample arrays.
+ * The pointers are in near heap, the samples themselves in FAR heap.
+ *
+ * To minimize allocation overhead and to allow I/O of large contiguous
+ * blocks, we allocate the sample rows in groups of as many rows as possible
+ * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
+ * NB: the virtual array control routines, later in this file, know about
+ * this chunking of rows. The rowsperchunk value is left in the mem manager
+ * object so that it can be saved away if this sarray is the workspace for
+ * a virtual array.
+ */
+
+METHODDEF JSAMPARRAY
+alloc_sarray (j_common_ptr cinfo, int pool_id,
+ JDIMENSION samplesperrow, JDIMENSION numrows)
+/* Allocate a 2-D sample array */
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ JSAMPARRAY result;
+ JSAMPROW workspace;
+ JDIMENSION rowsperchunk, currow, i;
+ long ltemp;
+
+ /* Calculate max # of rows allowed in one allocation chunk */
+ ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
+ ((long) samplesperrow * SIZEOF(JSAMPLE));
+ if (ltemp <= 0)
+ ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
+ if (ltemp < (long) numrows)
+ rowsperchunk = (JDIMENSION) ltemp;
+ else
+ rowsperchunk = numrows;
+ mem->last_rowsperchunk = rowsperchunk;
+
+ /* Get space for row pointers (small object) */
+ result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
+ (size_t) (numrows * SIZEOF(JSAMPROW)));
+
+ /* Get the rows themselves (large objects) */
+ currow = 0;
+ while (currow < numrows) {
+ rowsperchunk = MIN(rowsperchunk, numrows - currow);
+ workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
+ (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
+ * SIZEOF(JSAMPLE)));
+ for (i = rowsperchunk; i > 0; i--) {
+ result[currow++] = workspace;
+ workspace += samplesperrow;
+ }
+ }
+
+ return result;
+}
+
+
+/*
+ * Creation of 2-D coefficient-block arrays.
+ * This is essentially the same as the code for sample arrays, above.
+ */
+
+METHODDEF JBLOCKARRAY
+alloc_barray (j_common_ptr cinfo, int pool_id,
+ JDIMENSION blocksperrow, JDIMENSION numrows)
+/* Allocate a 2-D coefficient-block array */
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ JBLOCKARRAY result;
+ JBLOCKROW workspace;
+ JDIMENSION rowsperchunk, currow, i;
+ long ltemp;
+
+ /* Calculate max # of rows allowed in one allocation chunk */
+ ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
+ ((long) blocksperrow * SIZEOF(JBLOCK));
+ if (ltemp <= 0)
+ ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
+ if (ltemp < (long) numrows)
+ rowsperchunk = (JDIMENSION) ltemp;
+ else
+ rowsperchunk = numrows;
+ mem->last_rowsperchunk = rowsperchunk;
+
+ /* Get space for row pointers (small object) */
+ result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
+ (size_t) (numrows * SIZEOF(JBLOCKROW)));
+
+ /* Get the rows themselves (large objects) */
+ currow = 0;
+ while (currow < numrows) {
+ rowsperchunk = MIN(rowsperchunk, numrows - currow);
+ workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
+ (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
+ * SIZEOF(JBLOCK)));
+ for (i = rowsperchunk; i > 0; i--) {
+ result[currow++] = workspace;
+ workspace += blocksperrow;
+ }
+ }
+
+ return result;
+}
+
+
+/*
+ * About virtual array management:
+ *
+ * The above "normal" array routines are only used to allocate strip buffers
+ * (as wide as the image, but just a few rows high). Full-image-sized buffers
+ * are handled as "virtual" arrays. The array is still accessed a strip at a
+ * time, but the memory manager must save the whole array for repeated
+ * accesses. The intended implementation is that there is a strip buffer in
+ * memory (as high as is possible given the desired memory limit), plus a
+ * backing file that holds the rest of the array.
+ *
+ * The request_virt_array routines are told the total size of the image and
+ * the maximum number of rows that will be accessed at once. The in-memory
+ * buffer must be at least as large as the maxaccess value.
+ *
+ * The request routines create control blocks but not the in-memory buffers.
+ * That is postponed until realize_virt_arrays is called. At that time the
+ * total amount of space needed is known (approximately, anyway), so free
+ * memory can be divided up fairly.
+ *
+ * The access_virt_array routines are responsible for making a specific strip
+ * area accessible (after reading or writing the backing file, if necessary).
+ * Note that the access routines are told whether the caller intends to modify
+ * the accessed strip; during a read-only pass this saves having to rewrite
+ * data to disk. The access routines are also responsible for pre-zeroing
+ * any newly accessed rows, if pre-zeroing was requested.
+ *
+ * In current usage, the access requests are usually for nonoverlapping
+ * strips; that is, successive access start_row numbers differ by exactly
+ * num_rows = maxaccess. This means we can get good performance with simple
+ * buffer dump/reload logic, by making the in-memory buffer be a multiple
+ * of the access height; then there will never be accesses across bufferload
+ * boundaries. The code will still work with overlapping access requests,
+ * but it doesn't handle bufferload overlaps very efficiently.
+ */
+
+
+METHODDEF jvirt_sarray_ptr
+request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
+ JDIMENSION samplesperrow, JDIMENSION numrows,
+ JDIMENSION maxaccess)
+/* Request a virtual 2-D sample array */
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ jvirt_sarray_ptr result;
+
+ /* Only IMAGE-lifetime virtual arrays are currently supported */
+ if (pool_id != JPOOL_IMAGE)
+ ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
+
+ /* get control block */
+ result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
+ SIZEOF(struct jvirt_sarray_control));
+
+ result->mem_buffer = NULL; /* marks array not yet realized */
+ result->rows_in_array = numrows;
+ result->samplesperrow = samplesperrow;
+ result->maxaccess = maxaccess;
+ result->pre_zero = pre_zero;
+ result->b_s_open = FALSE; /* no associated backing-store object */
+ result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
+ mem->virt_sarray_list = result;
+
+ return result;
+}
+
+
+METHODDEF jvirt_barray_ptr
+request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
+ JDIMENSION blocksperrow, JDIMENSION numrows,
+ JDIMENSION maxaccess)
+/* Request a virtual 2-D coefficient-block array */
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ jvirt_barray_ptr result;
+
+ /* Only IMAGE-lifetime virtual arrays are currently supported */
+ if (pool_id != JPOOL_IMAGE)
+ ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
+
+ /* get control block */
+ result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
+ SIZEOF(struct jvirt_barray_control));
+
+ result->mem_buffer = NULL; /* marks array not yet realized */
+ result->rows_in_array = numrows;
+ result->blocksperrow = blocksperrow;
+ result->maxaccess = maxaccess;
+ result->pre_zero = pre_zero;
+ result->b_s_open = FALSE; /* no associated backing-store object */
+ result->next = mem->virt_barray_list; /* add to list of virtual arrays */
+ mem->virt_barray_list = result;
+
+ return result;
+}
+
+
+METHODDEF void
+realize_virt_arrays (j_common_ptr cinfo)
+/* Allocate the in-memory buffers for any unrealized virtual arrays */
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ long space_per_minheight, maximum_space, avail_mem;
+ long minheights, max_minheights;
+ jvirt_sarray_ptr sptr;
+ jvirt_barray_ptr bptr;
+
+ /* Compute the minimum space needed (maxaccess rows in each buffer)
+ * and the maximum space needed (full image height in each buffer).
+ * These may be of use to the system-dependent jpeg_mem_available routine.
+ */
+ space_per_minheight = 0;
+ maximum_space = 0;
+ for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
+ if (sptr->mem_buffer == NULL) { /* if not realized yet */
+ space_per_minheight += (long) sptr->maxaccess *
+ (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
+ maximum_space += (long) sptr->rows_in_array *
+ (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
+ }
+ }
+ for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
+ if (bptr->mem_buffer == NULL) { /* if not realized yet */
+ space_per_minheight += (long) bptr->maxaccess *
+ (long) bptr->blocksperrow * SIZEOF(JBLOCK);
+ maximum_space += (long) bptr->rows_in_array *
+ (long) bptr->blocksperrow * SIZEOF(JBLOCK);
+ }
+ }
+
+ if (space_per_minheight <= 0)
+ return; /* no unrealized arrays, no work */
+
+ /* Determine amount of memory to actually use; this is system-dependent. */
+ avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
+ mem->total_space_allocated);
+
+ /* If the maximum space needed is available, make all the buffers full
+ * height; otherwise parcel it out with the same number of minheights
+ * in each buffer.
+ */
+ if (avail_mem >= maximum_space)
+ max_minheights = 1000000000L;
+ else {
+ max_minheights = avail_mem / space_per_minheight;
+ /* If there doesn't seem to be enough space, try to get the minimum
+ * anyway. This allows a "stub" implementation of jpeg_mem_available().
+ */
+ if (max_minheights <= 0)
+ max_minheights = 1;
+ }
+
+ /* Allocate the in-memory buffers and initialize backing store as needed. */
+
+ for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
+ if (sptr->mem_buffer == NULL) { /* if not realized yet */
+ minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
+ if (minheights <= max_minheights) {
+ /* This buffer fits in memory */
+ sptr->rows_in_mem = sptr->rows_in_array;
+ } else {
+ /* It doesn't fit in memory, create backing store. */
+ sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
+ jpeg_open_backing_store(cinfo, & sptr->b_s_info,
+ (long) sptr->rows_in_array *
+ (long) sptr->samplesperrow *
+ (long) SIZEOF(JSAMPLE));
+ sptr->b_s_open = TRUE;
+ }
+ sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
+ sptr->samplesperrow, sptr->rows_in_mem);
+ sptr->rowsperchunk = mem->last_rowsperchunk;
+ sptr->cur_start_row = 0;
+ sptr->first_undef_row = 0;
+ sptr->dirty = FALSE;
+ }
+ }
+
+ for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
+ if (bptr->mem_buffer == NULL) { /* if not realized yet */
+ minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
+ if (minheights <= max_minheights) {
+ /* This buffer fits in memory */
+ bptr->rows_in_mem = bptr->rows_in_array;
+ } else {
+ /* It doesn't fit in memory, create backing store. */
+ bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
+ jpeg_open_backing_store(cinfo, & bptr->b_s_info,
+ (long) bptr->rows_in_array *
+ (long) bptr->blocksperrow *
+ (long) SIZEOF(JBLOCK));
+ bptr->b_s_open = TRUE;
+ }
+ bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
+ bptr->blocksperrow, bptr->rows_in_mem);
+ bptr->rowsperchunk = mem->last_rowsperchunk;
+ bptr->cur_start_row = 0;
+ bptr->first_undef_row = 0;
+ bptr->dirty = FALSE;
+ }
+ }
+}
+
+
+LOCAL void
+do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
+/* Do backing store read or write of a virtual sample array */
+{
+ long bytesperrow, file_offset, byte_count, rows, thisrow, i;
+
+ bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
+ file_offset = ptr->cur_start_row * bytesperrow;
+ /* Loop to read or write each allocation chunk in mem_buffer */
+ for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
+ /* One chunk, but check for short chunk at end of buffer */
+ rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
+ /* Transfer no more than is currently defined */
+ thisrow = (long) ptr->cur_start_row + i;
+ rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
+ /* Transfer no more than fits in file */
+ rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
+ if (rows <= 0) /* this chunk might be past end of file! */
+ break;
+ byte_count = rows * bytesperrow;
+ if (writing)
+ (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
+ (void FAR *) ptr->mem_buffer[i],
+ file_offset, byte_count);
+ else
+ (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
+ (void FAR *) ptr->mem_buffer[i],
+ file_offset, byte_count);
+ file_offset += byte_count;
+ }
+}
+
+
+LOCAL void
+do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
+/* Do backing store read or write of a virtual coefficient-block array */
+{
+ long bytesperrow, file_offset, byte_count, rows, thisrow, i;
+
+ bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
+ file_offset = ptr->cur_start_row * bytesperrow;
+ /* Loop to read or write each allocation chunk in mem_buffer */
+ for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
+ /* One chunk, but check for short chunk at end of buffer */
+ rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
+ /* Transfer no more than is currently defined */
+ thisrow = (long) ptr->cur_start_row + i;
+ rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
+ /* Transfer no more than fits in file */
+ rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
+ if (rows <= 0) /* this chunk might be past end of file! */
+ break;
+ byte_count = rows * bytesperrow;
+ if (writing)
+ (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
+ (void FAR *) ptr->mem_buffer[i],
+ file_offset, byte_count);
+ else
+ (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
+ (void FAR *) ptr->mem_buffer[i],
+ file_offset, byte_count);
+ file_offset += byte_count;
+ }
+}
+
+
+METHODDEF JSAMPARRAY
+access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
+ JDIMENSION start_row, JDIMENSION num_rows,
+ boolean writable)
+/* Access the part of a virtual sample array starting at start_row */
+/* and extending for num_rows rows. writable is true if */
+/* caller intends to modify the accessed area. */
+{
+ JDIMENSION end_row = start_row + num_rows;
+ JDIMENSION undef_row;
+
+ /* debugging check */
+ if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
+ ptr->mem_buffer == NULL)
+ ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
+
+ /* Make the desired part of the virtual array accessible */
+ if (start_row < ptr->cur_start_row ||
+ end_row > ptr->cur_start_row+ptr->rows_in_mem) {
+ if (! ptr->b_s_open)
+ ERREXIT(cinfo, JERR_VIRTUAL_BUG);
+ /* Flush old buffer contents if necessary */
+ if (ptr->dirty) {
+ do_sarray_io(cinfo, ptr, TRUE);
+ ptr->dirty = FALSE;
+ }
+ /* Decide what part of virtual array to access.
+ * Algorithm: if target address > current window, assume forward scan,
+ * load starting at target address. If target address < current window,
+ * assume backward scan, load so that target area is top of window.
+ * Note that when switching from forward write to forward read, will have
+ * start_row = 0, so the limiting case applies and we load from 0 anyway.
+ */
+ if (start_row > ptr->cur_start_row) {
+ ptr->cur_start_row = start_row;
+ } else {
+ /* use long arithmetic here to avoid overflow & unsigned problems */
+ long ltemp;
+
+ ltemp = (long) end_row - (long) ptr->rows_in_mem;
+ if (ltemp < 0)
+ ltemp = 0; /* don't fall off front end of file */
+ ptr->cur_start_row = (JDIMENSION) ltemp;
+ }
+ /* Read in the selected part of the array.
+ * During the initial write pass, we will do no actual read
+ * because the selected part is all undefined.
+ */
+ do_sarray_io(cinfo, ptr, FALSE);
+ }
+ /* Ensure the accessed part of the array is defined; prezero if needed.
+ * To improve locality of access, we only prezero the part of the array
+ * that the caller is about to access, not the entire in-memory array.
+ */
+ if (ptr->first_undef_row < end_row) {
+ if (ptr->first_undef_row < start_row) {
+ if (writable) /* writer skipped over a section of array */
+ ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
+ undef_row = start_row; /* but reader is allowed to read ahead */
+ } else {
+ undef_row = ptr->first_undef_row;
+ }
+ if (writable)
+ ptr->first_undef_row = end_row;
+ if (ptr->pre_zero) {
+ size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
+ undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
+ end_row -= ptr->cur_start_row;
+ while (undef_row < end_row) {
+ jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
+ undef_row++;
+ }
+ } else {
+ if (! writable) /* reader looking at undefined data */
+ ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
+ }
+ }
+ /* Flag the buffer dirty if caller will write in it */
+ if (writable)
+ ptr->dirty = TRUE;
+ /* Return address of proper part of the buffer */
+ return ptr->mem_buffer + (start_row - ptr->cur_start_row);
+}
+
+
+METHODDEF JBLOCKARRAY
+access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
+ JDIMENSION start_row, JDIMENSION num_rows,
+ boolean writable)
+/* Access the part of a virtual block array starting at start_row */
+/* and extending for num_rows rows. writable is true if */
+/* caller intends to modify the accessed area. */
+{
+ JDIMENSION end_row = start_row + num_rows;
+ JDIMENSION undef_row;
+
+ /* debugging check */
+ if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
+ ptr->mem_buffer == NULL)
+ ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
+
+ /* Make the desired part of the virtual array accessible */
+ if (start_row < ptr->cur_start_row ||
+ end_row > ptr->cur_start_row+ptr->rows_in_mem) {
+ if (! ptr->b_s_open)
+ ERREXIT(cinfo, JERR_VIRTUAL_BUG);
+ /* Flush old buffer contents if necessary */
+ if (ptr->dirty) {
+ do_barray_io(cinfo, ptr, TRUE);
+ ptr->dirty = FALSE;
+ }
+ /* Decide what part of virtual array to access.
+ * Algorithm: if target address > current window, assume forward scan,
+ * load starting at target address. If target address < current window,
+ * assume backward scan, load so that target area is top of window.
+ * Note that when switching from forward write to forward read, will have
+ * start_row = 0, so the limiting case applies and we load from 0 anyway.
+ */
+ if (start_row > ptr->cur_start_row) {
+ ptr->cur_start_row = start_row;
+ } else {
+ /* use long arithmetic here to avoid overflow & unsigned problems */
+ long ltemp;
+
+ ltemp = (long) end_row - (long) ptr->rows_in_mem;
+ if (ltemp < 0)
+ ltemp = 0; /* don't fall off front end of file */
+ ptr->cur_start_row = (JDIMENSION) ltemp;
+ }
+ /* Read in the selected part of the array.
+ * During the initial write pass, we will do no actual read
+ * because the selected part is all undefined.
+ */
+ do_barray_io(cinfo, ptr, FALSE);
+ }
+ /* Ensure the accessed part of the array is defined; prezero if needed.
+ * To improve locality of access, we only prezero the part of the array
+ * that the caller is about to access, not the entire in-memory array.
+ */
+ if (ptr->first_undef_row < end_row) {
+ if (ptr->first_undef_row < start_row) {
+ if (writable) /* writer skipped over a section of array */
+ ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
+ undef_row = start_row; /* but reader is allowed to read ahead */
+ } else {
+ undef_row = ptr->first_undef_row;
+ }
+ if (writable)
+ ptr->first_undef_row = end_row;
+ if (ptr->pre_zero) {
+ size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
+ undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
+ end_row -= ptr->cur_start_row;
+ while (undef_row < end_row) {
+ jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
+ undef_row++;
+ }
+ } else {
+ if (! writable) /* reader looking at undefined data */
+ ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
+ }
+ }
+ /* Flag the buffer dirty if caller will write in it */
+ if (writable)
+ ptr->dirty = TRUE;
+ /* Return address of proper part of the buffer */
+ return ptr->mem_buffer + (start_row - ptr->cur_start_row);
+}
+
+
+/*
+ * Release all objects belonging to a specified pool.
+ */
+
+METHODDEF void
+free_pool (j_common_ptr cinfo, int pool_id)
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ small_pool_ptr shdr_ptr;
+ large_pool_ptr lhdr_ptr;
+ size_t space_freed;
+
+ if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
+ ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
+
+#ifdef MEM_STATS
+ if (cinfo->err->trace_level > 1)
+ print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
+#endif
+
+ /* If freeing IMAGE pool, close any virtual arrays first */
+ if (pool_id == JPOOL_IMAGE) {
+ jvirt_sarray_ptr sptr;
+ jvirt_barray_ptr bptr;
+
+ for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
+ if (sptr->b_s_open) { /* there may be no backing store */
+ sptr->b_s_open = FALSE; /* prevent recursive close if error */
+ (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
+ }
+ }
+ mem->virt_sarray_list = NULL;
+ for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
+ if (bptr->b_s_open) { /* there may be no backing store */
+ bptr->b_s_open = FALSE; /* prevent recursive close if error */
+ (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
+ }
+ }
+ mem->virt_barray_list = NULL;
+ }
+
+ /* Release large objects */
+ lhdr_ptr = mem->large_list[pool_id];
+ mem->large_list[pool_id] = NULL;
+
+ while (lhdr_ptr != NULL) {
+ large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
+ space_freed = lhdr_ptr->hdr.bytes_used +
+ lhdr_ptr->hdr.bytes_left +
+ SIZEOF(large_pool_hdr);
+ jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
+ mem->total_space_allocated -= space_freed;
+ lhdr_ptr = next_lhdr_ptr;
+ }
+
+ /* Release small objects */
+ shdr_ptr = mem->small_list[pool_id];
+ mem->small_list[pool_id] = NULL;
+
+ while (shdr_ptr != NULL) {
+ small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
+ space_freed = shdr_ptr->hdr.bytes_used +
+ shdr_ptr->hdr.bytes_left +
+ SIZEOF(small_pool_hdr);
+ jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
+ mem->total_space_allocated -= space_freed;
+ shdr_ptr = next_shdr_ptr;
+ }
+}
+
+
+/*
+ * Close up shop entirely.
+ * Note that this cannot be called unless cinfo->mem is non-NULL.
+ */
+
+METHODDEF void
+self_destruct (j_common_ptr cinfo)
+{
+ int pool;
+
+ /* Close all backing store, release all memory.
+ * Releasing pools in reverse order might help avoid fragmentation
+ * with some (brain-damaged) malloc libraries.
+ */
+ for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
+ free_pool(cinfo, pool);
+ }
+
+ /* Release the memory manager control block too. */
+ jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
+ cinfo->mem = NULL; /* ensures I will be called only once */
+
+ jpeg_mem_term(cinfo); /* system-dependent cleanup */
+}
+
+
+/*
+ * Memory manager initialization.
+ * When this is called, only the error manager pointer is valid in cinfo!
+ */
+
+GLOBAL void
+jinit_memory_mgr (j_common_ptr cinfo)
+{
+ my_mem_ptr mem;
+ long max_to_use;
+ int pool;
+ size_t test_mac;
+
+ cinfo->mem = NULL; /* for safety if init fails */
+
+ /* Check for configuration errors.
+ * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
+ * doesn't reflect any real hardware alignment requirement.
+ * The test is a little tricky: for X>0, X and X-1 have no one-bits
+ * in common if and only if X is a power of 2, ie has only one one-bit.
+ * Some compilers may give an "unreachable code" warning here; ignore it.
+ */
+ if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
+ ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
+ /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
+ * a multiple of SIZEOF(ALIGN_TYPE).
+ * Again, an "unreachable code" warning may be ignored here.
+ * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
+ */
+ test_mac = (size_t) MAX_ALLOC_CHUNK;
+ if ((long) test_mac != MAX_ALLOC_CHUNK ||
+ (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
+ ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
+
+ max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
+
+ /* Attempt to allocate memory manager's control block */
+ mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
+
+ if (mem == NULL) {
+ jpeg_mem_term(cinfo); /* system-dependent cleanup */
+ ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
+ }
+
+ /* OK, fill in the method pointers */
+ mem->pub.alloc_small = alloc_small;
+ mem->pub.alloc_large = alloc_large;
+ mem->pub.alloc_sarray = alloc_sarray;
+ mem->pub.alloc_barray = alloc_barray;
+ mem->pub.request_virt_sarray = request_virt_sarray;
+ mem->pub.request_virt_barray = request_virt_barray;
+ mem->pub.realize_virt_arrays = realize_virt_arrays;
+ mem->pub.access_virt_sarray = access_virt_sarray;
+ mem->pub.access_virt_barray = access_virt_barray;
+ mem->pub.free_pool = free_pool;
+ mem->pub.self_destruct = self_destruct;
+
+ /* Initialize working state */
+ mem->pub.max_memory_to_use = max_to_use;
+
+ for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
+ mem->small_list[pool] = NULL;
+ mem->large_list[pool] = NULL;
+ }
+ mem->virt_sarray_list = NULL;
+ mem->virt_barray_list = NULL;
+
+ mem->total_space_allocated = SIZEOF(my_memory_mgr);
+
+ /* Declare ourselves open for business */
+ cinfo->mem = & mem->pub;
+
+ /* Check for an environment variable JPEGMEM; if found, override the
+ * default max_memory setting from jpeg_mem_init. Note that the
+ * surrounding application may again override this value.
+ * If your system doesn't support getenv(), define NO_GETENV to disable
+ * this feature.
+ */
+#ifndef NO_GETENV
+ { char * memenv;
+
+ if ((memenv = getenv("JPEGMEM")) != NULL) {
+ char ch = 'x';
+
+ if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
+ if (ch == 'm' || ch == 'M')
+ max_to_use *= 1000L;
+ mem->pub.max_memory_to_use = max_to_use * 1000L;
+ }
+ }
+ }
+#endif
+
+}
diff --git a/code/jpeg-6/jmemname.c b/code/jpeg-6/jmemname.c
new file mode 100755
index 0000000..a3f6494
--- /dev/null
+++ b/code/jpeg-6/jmemname.c
@@ -0,0 +1,271 @@
+/*
+ * jmemname.c
+ *
+ * Copyright (C) 1992-1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file provides a generic implementation of the system-dependent
+ * portion of the JPEG memory manager. This implementation assumes that
+ * you must explicitly construct a name for each temp file.
+ * Also, the problem of determining the amount of memory available
+ * is shoved onto the user.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jmemsys.h" /* import the system-dependent declarations */
+
+#ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
+extern void * malloc JPP((size_t size));
+extern void free JPP((void *ptr));
+#endif
+
+#ifndef SEEK_SET /* pre-ANSI systems may not define this; */
+#define SEEK_SET 0 /* if not, assume 0 is correct */
+#endif
+
+#ifdef DONT_USE_B_MODE /* define mode parameters for fopen() */
+#define READ_BINARY "r"
+#define RW_BINARY "w+"
+#else
+#define READ_BINARY "rb"
+#define RW_BINARY "w+b"
+#endif
+
+
+/*
+ * Selection of a file name for a temporary file.
+ * This is system-dependent!
+ *
+ * The code as given is suitable for most Unix systems, and it is easily
+ * modified for most non-Unix systems. Some notes:
+ * 1. The temp file is created in the directory named by TEMP_DIRECTORY.
+ * The default value is /usr/tmp, which is the conventional place for
+ * creating large temp files on Unix. On other systems you'll probably
+ * want to change the file location. You can do this by editing the
+ * #define, or (preferred) by defining TEMP_DIRECTORY in jconfig.h.
+ *
+ * 2. If you need to change the file name as well as its location,
+ * you can override the TEMP_FILE_NAME macro. (Note that this is
+ * actually a printf format string; it must contain %s and %d.)
+ * Few people should need to do this.
+ *
+ * 3. mktemp() is used to ensure that multiple processes running
+ * simultaneously won't select the same file names. If your system
+ * doesn't have mktemp(), define NO_MKTEMP to do it the hard way.
+ * (If you don't have <errno.h>, also define NO_ERRNO_H.)
+ *
+ * 4. You probably want to define NEED_SIGNAL_CATCHER so that cjpeg.c/djpeg.c
+ * will cause the temp files to be removed if you stop the program early.
+ */
+
+#ifndef TEMP_DIRECTORY /* can override from jconfig.h or Makefile */
+#define TEMP_DIRECTORY "/usr/tmp/" /* recommended setting for Unix */
+#endif
+
+static int next_file_num; /* to distinguish among several temp files */
+
+#ifdef NO_MKTEMP
+
+#ifndef TEMP_FILE_NAME /* can override from jconfig.h or Makefile */
+#define TEMP_FILE_NAME "%sJPG%03d.TMP"
+#endif
+
+#ifndef NO_ERRNO_H
+#include <errno.h> /* to define ENOENT */
+#endif
+
+/* ANSI C specifies that errno is a macro, but on older systems it's more
+ * likely to be a plain int variable. And not all versions of errno.h
+ * bother to declare it, so we have to in order to be most portable. Thus:
+ */
+#ifndef errno
+extern int errno;
+#endif
+
+
+LOCAL void
+select_file_name (char * fname)
+{
+ FILE * tfile;
+
+ /* Keep generating file names till we find one that's not in use */
+ for (;;) {
+ next_file_num++; /* advance counter */
+ sprintf(fname, TEMP_FILE_NAME, TEMP_DIRECTORY, next_file_num);
+ if ((tfile = fopen(fname, READ_BINARY)) == NULL) {
+ /* fopen could have failed for a reason other than the file not
+ * being there; for example, file there but unreadable.
+ * If <errno.h> isn't available, then we cannot test the cause.
+ */
+#ifdef ENOENT
+ if (errno != ENOENT)
+ continue;
+#endif
+ break;
+ }
+ fclose(tfile); /* oops, it's there; close tfile & try again */
+ }
+}
+
+#else /* ! NO_MKTEMP */
+
+/* Note that mktemp() requires the initial filename to end in six X's */
+#ifndef TEMP_FILE_NAME /* can override from jconfig.h or Makefile */
+#define TEMP_FILE_NAME "%sJPG%dXXXXXX"
+#endif
+
+LOCAL void
+select_file_name (char * fname)
+{
+ next_file_num++; /* advance counter */
+ sprintf(fname, TEMP_FILE_NAME, TEMP_DIRECTORY, next_file_num);
+ mktemp(fname); /* make sure file name is unique */
+ /* mktemp replaces the trailing XXXXXX with a unique string of characters */
+}
+
+#endif /* NO_MKTEMP */
+
+
+/*
+ * Memory allocation and freeing are controlled by the regular library
+ * routines malloc() and free().
+ */
+
+GLOBAL void *
+jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
+{
+ return (void *) malloc(sizeofobject);
+}
+
+GLOBAL void
+jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
+{
+ free(object);
+}
+
+
+/*
+ * "Large" objects are treated the same as "small" ones.
+ * NB: although we include FAR keywords in the routine declarations,
+ * this file won't actually work in 80x86 small/medium model; at least,
+ * you probably won't be able to process useful-size images in only 64KB.
+ */
+
+GLOBAL void FAR *
+jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
+{
+ return (void FAR *) malloc(sizeofobject);
+}
+
+GLOBAL void
+jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
+{
+ free(object);
+}
+
+
+/*
+ * This routine computes the total memory space available for allocation.
+ * It's impossible to do this in a portable way; our current solution is
+ * to make the user tell us (with a default value set at compile time).
+ * If you can actually get the available space, it's a good idea to subtract
+ * a slop factor of 5% or so.
+ */
+
+#ifndef DEFAULT_MAX_MEM /* so can override from makefile */
+#define DEFAULT_MAX_MEM 1000000L /* default: one megabyte */
+#endif
+
+GLOBAL long
+jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
+ long max_bytes_needed, long already_allocated)
+{
+ return cinfo->mem->max_memory_to_use - already_allocated;
+}
+
+
+/*
+ * Backing store (temporary file) management.
+ * Backing store objects are only used when the value returned by
+ * jpeg_mem_available is less than the total space needed. You can dispense
+ * with these routines if you have plenty of virtual memory; see jmemnobs.c.
+ */
+
+
+METHODDEF void
+read_backing_store (j_common_ptr cinfo, backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count)
+{
+ if (fseek(info->temp_file, file_offset, SEEK_SET))
+ ERREXIT(cinfo, JERR_TFILE_SEEK);
+ if (JFREAD(info->temp_file, buffer_address, byte_count)
+ != (size_t) byte_count)
+ ERREXIT(cinfo, JERR_TFILE_READ);
+}
+
+
+METHODDEF void
+write_backing_store (j_common_ptr cinfo, backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count)
+{
+ if (fseek(info->temp_file, file_offset, SEEK_SET))
+ ERREXIT(cinfo, JERR_TFILE_SEEK);
+ if (JFWRITE(info->temp_file, buffer_address, byte_count)
+ != (size_t) byte_count)
+ ERREXIT(cinfo, JERR_TFILE_WRITE);
+}
+
+
+METHODDEF void
+close_backing_store (j_common_ptr cinfo, backing_store_ptr info)
+{
+ fclose(info->temp_file); /* close the file */
+ unlink(info->temp_name); /* delete the file */
+/* If your system doesn't have unlink(), use remove() instead.
+ * remove() is the ANSI-standard name for this function, but if
+ * your system was ANSI you'd be using jmemansi.c, right?
+ */
+ TRACEMSS(cinfo, 1, JTRC_TFILE_CLOSE, info->temp_name);
+}
+
+
+/*
+ * Initial opening of a backing-store object.
+ */
+
+GLOBAL void
+jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info,
+ long total_bytes_needed)
+{
+ select_file_name(info->temp_name);
+ if ((info->temp_file = fopen(info->temp_name, RW_BINARY)) == NULL)
+ ERREXITS(cinfo, JERR_TFILE_CREATE, info->temp_name);
+ info->read_backing_store = read_backing_store;
+ info->write_backing_store = write_backing_store;
+ info->close_backing_store = close_backing_store;
+ TRACEMSS(cinfo, 1, JTRC_TFILE_OPEN, info->temp_name);
+}
+
+
+/*
+ * These routines take care of any system-dependent initialization and
+ * cleanup required.
+ */
+
+GLOBAL long
+jpeg_mem_init (j_common_ptr cinfo)
+{
+ next_file_num = 0; /* initialize temp file name generator */
+ return DEFAULT_MAX_MEM; /* default for max_memory_to_use */
+}
+
+GLOBAL void
+jpeg_mem_term (j_common_ptr cinfo)
+{
+ /* no work */
+}
diff --git a/code/jpeg-6/jmemnobs.c b/code/jpeg-6/jmemnobs.c
new file mode 100755
index 0000000..50090c7
--- /dev/null
+++ b/code/jpeg-6/jmemnobs.c
@@ -0,0 +1,105 @@
+/*
+ * jmemnobs.c
+ *
+ * Copyright (C) 1992-1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file provides a really simple implementation of the system-
+ * dependent portion of the JPEG memory manager. This implementation
+ * assumes that no backing-store files are needed: all required space
+ * can be obtained from ri.Malloc().
+ * This is very portable in the sense that it'll compile on almost anything,
+ * but you'd better have lots of main memory (or virtual memory) if you want
+ * to process big images.
+ * Note that the max_memory_to_use option is ignored by this implementation.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jmemsys.h" /* import the system-dependent declarations */
+
+#include "../renderer/tr_local.h"
+
+/*
+ * Memory allocation and ri.Freeing are controlled by the regular library
+ * routines ri.Malloc() and ri.Free().
+ */
+
+GLOBAL void *
+jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
+{
+ return (void *) ri.Malloc(sizeofobject);
+}
+
+GLOBAL void
+jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
+{
+ ri.Free(object);
+}
+
+
+/*
+ * "Large" objects are treated the same as "small" ones.
+ * NB: although we include FAR keywords in the routine declarations,
+ * this file won't actually work in 80x86 small/medium model; at least,
+ * you probably won't be able to process useful-size images in only 64KB.
+ */
+
+GLOBAL void FAR *
+jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
+{
+ return (void FAR *) ri.Malloc(sizeofobject);
+}
+
+GLOBAL void
+jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
+{
+ ri.Free(object);
+}
+
+
+/*
+ * This routine computes the total memory space available for allocation.
+ * Here we always say, "we got all you want bud!"
+ */
+
+GLOBAL long
+jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
+ long max_bytes_needed, long already_allocated)
+{
+ return max_bytes_needed;
+}
+
+
+/*
+ * Backing store (temporary file) management.
+ * Since jpeg_mem_available always promised the moon,
+ * this should never be called and we can just error out.
+ */
+
+GLOBAL void
+jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info,
+ long total_bytes_needed)
+{
+ ERREXIT(cinfo, JERR_NO_BACKING_STORE);
+}
+
+
+/*
+ * These routines take care of any system-dependent initialization and
+ * cleanup required. Here, there isn't any.
+ */
+
+GLOBAL long
+jpeg_mem_init (j_common_ptr cinfo)
+{
+ return 0; /* just set max_memory_to_use to 0 */
+}
+
+GLOBAL void
+jpeg_mem_term (j_common_ptr cinfo)
+{
+ /* no work */
+}
diff --git a/code/jpeg-6/jmemsys.h b/code/jpeg-6/jmemsys.h
new file mode 100755
index 0000000..0c7d7c1
--- /dev/null
+++ b/code/jpeg-6/jmemsys.h
@@ -0,0 +1,182 @@
+/*
+ * jmemsys.h
+ *
+ * Copyright (C) 1992-1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This include file defines the interface between the system-independent
+ * and system-dependent portions of the JPEG memory manager. No other
+ * modules need include it. (The system-independent portion is jmemmgr.c;
+ * there are several different versions of the system-dependent portion.)
+ *
+ * This file works as-is for the system-dependent memory managers supplied
+ * in the IJG distribution. You may need to modify it if you write a
+ * custom memory manager. If system-dependent changes are needed in
+ * this file, the best method is to #ifdef them based on a configuration
+ * symbol supplied in jconfig.h, as we have done with USE_MSDOS_MEMMGR.
+ */
+
+
+/* Short forms of external names for systems with brain-damaged linkers. */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jpeg_get_small jGetSmall
+#define jpeg_free_small jFreeSmall
+#define jpeg_get_large jGetLarge
+#define jpeg_free_large jFreeLarge
+#define jpeg_mem_available jMemAvail
+#define jpeg_open_backing_store jOpenBackStore
+#define jpeg_mem_init jMemInit
+#define jpeg_mem_term jMemTerm
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+
+/*
+ * These two functions are used to allocate and release small chunks of
+ * memory. (Typically the total amount requested through jpeg_get_small is
+ * no more than 20K or so; this will be requested in chunks of a few K each.)
+ * Behavior should be the same as for the standard library functions malloc
+ * and free; in particular, jpeg_get_small must return NULL on failure.
+ * On most systems, these ARE malloc and free. jpeg_free_small is passed the
+ * size of the object being freed, just in case it's needed.
+ * On an 80x86 machine using small-data memory model, these manage near heap.
+ */
+
+EXTERN void * jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
+EXTERN void jpeg_free_small JPP((j_common_ptr cinfo, void * object,
+ size_t sizeofobject));
+
+/*
+ * These two functions are used to allocate and release large chunks of
+ * memory (up to the total free space designated by jpeg_mem_available).
+ * The interface is the same as above, except that on an 80x86 machine,
+ * far pointers are used. On most other machines these are identical to
+ * the jpeg_get/free_small routines; but we keep them separate anyway,
+ * in case a different allocation strategy is desirable for large chunks.
+ */
+
+EXTERN void FAR * jpeg_get_large JPP((j_common_ptr cinfo,size_t sizeofobject));
+EXTERN void jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
+ size_t sizeofobject));
+
+/*
+ * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
+ * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
+ * matter, but that case should never come into play). This macro is needed
+ * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
+ * On those machines, we expect that jconfig.h will provide a proper value.
+ * On machines with 32-bit flat address spaces, any large constant may be used.
+ *
+ * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
+ * size_t and will be a multiple of sizeof(align_type).
+ */
+
+#ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
+#define MAX_ALLOC_CHUNK 1000000000L
+#endif
+
+/*
+ * This routine computes the total space still available for allocation by
+ * jpeg_get_large. If more space than this is needed, backing store will be
+ * used. NOTE: any memory already allocated must not be counted.
+ *
+ * There is a minimum space requirement, corresponding to the minimum
+ * feasible buffer sizes; jmemmgr.c will request that much space even if
+ * jpeg_mem_available returns zero. The maximum space needed, enough to hold
+ * all working storage in memory, is also passed in case it is useful.
+ * Finally, the total space already allocated is passed. If no better
+ * method is available, cinfo->mem->max_memory_to_use - already_allocated
+ * is often a suitable calculation.
+ *
+ * It is OK for jpeg_mem_available to underestimate the space available
+ * (that'll just lead to more backing-store access than is really necessary).
+ * However, an overestimate will lead to failure. Hence it's wise to subtract
+ * a slop factor from the true available space. 5% should be enough.
+ *
+ * On machines with lots of virtual memory, any large constant may be returned.
+ * Conversely, zero may be returned to always use the minimum amount of memory.
+ */
+
+EXTERN long jpeg_mem_available JPP((j_common_ptr cinfo,
+ long min_bytes_needed,
+ long max_bytes_needed,
+ long already_allocated));
+
+
+/*
+ * This structure holds whatever state is needed to access a single
+ * backing-store object. The read/write/close method pointers are called
+ * by jmemmgr.c to manipulate the backing-store object; all other fields
+ * are private to the system-dependent backing store routines.
+ */
+
+#define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
+
+#ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
+
+typedef unsigned short XMSH; /* type of extended-memory handles */
+typedef unsigned short EMSH; /* type of expanded-memory handles */
+
+typedef union {
+ short file_handle; /* DOS file handle if it's a temp file */
+ XMSH xms_handle; /* handle if it's a chunk of XMS */
+ EMSH ems_handle; /* handle if it's a chunk of EMS */
+} handle_union;
+
+#endif /* USE_MSDOS_MEMMGR */
+
+typedef struct backing_store_struct * backing_store_ptr;
+
+typedef struct backing_store_struct {
+ /* Methods for reading/writing/closing this backing-store object */
+ JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
+ backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count));
+ JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
+ backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count));
+ JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
+ backing_store_ptr info));
+
+ /* Private fields for system-dependent backing-store management */
+#ifdef USE_MSDOS_MEMMGR
+ /* For the MS-DOS manager (jmemdos.c), we need: */
+ handle_union handle; /* reference to backing-store storage object */
+ char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
+#else
+ /* For a typical implementation with temp files, we need: */
+ FILE * temp_file; /* stdio reference to temp file */
+ char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
+#endif
+} backing_store_info;
+
+/*
+ * Initial opening of a backing-store object. This must fill in the
+ * read/write/close pointers in the object. The read/write routines
+ * may take an error exit if the specified maximum file size is exceeded.
+ * (If jpeg_mem_available always returns a large value, this routine can
+ * just take an error exit.)
+ */
+
+EXTERN void jpeg_open_backing_store JPP((j_common_ptr cinfo,
+ backing_store_ptr info,
+ long total_bytes_needed));
+
+
+/*
+ * These routines take care of any system-dependent initialization and
+ * cleanup required. jpeg_mem_init will be called before anything is
+ * allocated (and, therefore, nothing in cinfo is of use except the error
+ * manager pointer). It should return a suitable default value for
+ * max_memory_to_use; this may subsequently be overridden by the surrounding
+ * application. (Note that max_memory_to_use is only important if
+ * jpeg_mem_available chooses to consult it ... no one else will.)
+ * jpeg_mem_term may assume that all requested memory has been freed and that
+ * all opened backing-store objects have been closed.
+ */
+
+EXTERN long jpeg_mem_init JPP((j_common_ptr cinfo));
+EXTERN void jpeg_mem_term JPP((j_common_ptr cinfo));
diff --git a/code/jpeg-6/jmorecfg.h b/code/jpeg-6/jmorecfg.h
new file mode 100755
index 0000000..204dbbd
--- /dev/null
+++ b/code/jpeg-6/jmorecfg.h
@@ -0,0 +1,348 @@
+/*
+ * jmorecfg.h
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains additional configuration options that customize the
+ * JPEG software for special applications or support machine-dependent
+ * optimizations. Most users will not need to touch this file.
+ */
+
+
+/*
+ * Define BITS_IN_JSAMPLE as either
+ * 8 for 8-bit sample values (the usual setting)
+ * 12 for 12-bit sample values
+ * Only 8 and 12 are legal data precisions for lossy JPEG according to the
+ * JPEG standard, and the IJG code does not support anything else!
+ * We do not support run-time selection of data precision, sorry.
+ */
+
+#define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
+
+
+/*
+ * Maximum number of components (color channels) allowed in JPEG image.
+ * To meet the letter of the JPEG spec, set this to 255. However, darn
+ * few applications need more than 4 channels (maybe 5 for CMYK + alpha
+ * mask). We recommend 10 as a reasonable compromise; use 4 if you are
+ * really short on memory. (Each allowed component costs a hundred or so
+ * bytes of storage, whether actually used in an image or not.)
+ */
+
+#define MAX_COMPONENTS 10 /* maximum number of image components */
+
+
+/*
+ * Basic data types.
+ * You may need to change these if you have a machine with unusual data
+ * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
+ * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
+ * but it had better be at least 16.
+ */
+
+/* Representation of a single sample (pixel element value).
+ * We frequently allocate large arrays of these, so it's important to keep
+ * them small. But if you have memory to burn and access to char or short
+ * arrays is very slow on your hardware, you might want to change these.
+ */
+
+#if BITS_IN_JSAMPLE == 8
+/* JSAMPLE should be the smallest type that will hold the values 0..255.
+ * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
+ */
+
+#ifdef HAVE_UNSIGNED_CHAR
+
+typedef unsigned char JSAMPLE;
+#define GETJSAMPLE(value) ((int) (value))
+
+#else /* not HAVE_UNSIGNED_CHAR */
+
+typedef char JSAMPLE;
+#ifdef CHAR_IS_UNSIGNED
+#define GETJSAMPLE(value) ((int) (value))
+#else
+#define GETJSAMPLE(value) ((int) (value) & 0xFF)
+#endif /* CHAR_IS_UNSIGNED */
+
+#endif /* HAVE_UNSIGNED_CHAR */
+
+#define MAXJSAMPLE 255
+#define CENTERJSAMPLE 128
+
+#endif /* BITS_IN_JSAMPLE == 8 */
+
+
+#if BITS_IN_JSAMPLE == 12
+/* JSAMPLE should be the smallest type that will hold the values 0..4095.
+ * On nearly all machines "short" will do nicely.
+ */
+
+typedef short JSAMPLE;
+#define GETJSAMPLE(value) ((int) (value))
+
+#define MAXJSAMPLE 4095
+#define CENTERJSAMPLE 2048
+
+#endif /* BITS_IN_JSAMPLE == 12 */
+
+
+/* Representation of a DCT frequency coefficient.
+ * This should be a signed value of at least 16 bits; "short" is usually OK.
+ * Again, we allocate large arrays of these, but you can change to int
+ * if you have memory to burn and "short" is really slow.
+ */
+
+typedef short JCOEF;
+
+
+/* Compressed datastreams are represented as arrays of JOCTET.
+ * These must be EXACTLY 8 bits wide, at least once they are written to
+ * external storage. Note that when using the stdio data source/destination
+ * managers, this is also the data type passed to fread/fwrite.
+ */
+
+#ifdef HAVE_UNSIGNED_CHAR
+
+typedef unsigned char JOCTET;
+#define GETJOCTET(value) (value)
+
+#else /* not HAVE_UNSIGNED_CHAR */
+
+typedef char JOCTET;
+#ifdef CHAR_IS_UNSIGNED
+#define GETJOCTET(value) (value)
+#else
+#define GETJOCTET(value) ((value) & 0xFF)
+#endif /* CHAR_IS_UNSIGNED */
+
+#endif /* HAVE_UNSIGNED_CHAR */
+
+
+/* These typedefs are used for various table entries and so forth.
+ * They must be at least as wide as specified; but making them too big
+ * won't cost a huge amount of memory, so we don't provide special
+ * extraction code like we did for JSAMPLE. (In other words, these
+ * typedefs live at a different point on the speed/space tradeoff curve.)
+ */
+
+/* UINT8 must hold at least the values 0..255. */
+
+#ifdef HAVE_UNSIGNED_CHAR
+typedef unsigned char UINT8;
+#else /* not HAVE_UNSIGNED_CHAR */
+#ifdef CHAR_IS_UNSIGNED
+typedef char UINT8;
+#else /* not CHAR_IS_UNSIGNED */
+typedef short UINT8;
+#endif /* CHAR_IS_UNSIGNED */
+#endif /* HAVE_UNSIGNED_CHAR */
+
+/* UINT16 must hold at least the values 0..65535. */
+
+#ifdef HAVE_UNSIGNED_SHORT
+typedef unsigned short UINT16;
+#else /* not HAVE_UNSIGNED_SHORT */
+typedef unsigned int UINT16;
+#endif /* HAVE_UNSIGNED_SHORT */
+
+typedef long INT32;
+
+/* INT16 must hold at least the values -32768..32767. */
+
+#ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
+typedef short INT16;
+#endif
+
+/* INT32 must hold at least signed 32-bit values. */
+
+//#ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
+//typedef long INT32;
+//#endif
+
+/* Datatype used for image dimensions. The JPEG standard only supports
+ * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
+ * "unsigned int" is sufficient on all machines. However, if you need to
+ * handle larger images and you don't mind deviating from the spec, you
+ * can change this datatype.
+ */
+
+typedef unsigned int JDIMENSION;
+
+#define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
+
+
+/* These defines are used in all function definitions and extern declarations.
+ * You could modify them if you need to change function linkage conventions.
+ * Another application is to make all functions global for use with debuggers
+ * or code profilers that require it.
+ */
+
+#define METHODDEF static /* a function called through method pointers */
+#define LOCAL static /* a function used only in its module */
+#define GLOBAL /* a function referenced thru EXTERNs */
+#define EXTERN extern /* a reference to a GLOBAL function */
+
+
+/* Here is the pseudo-keyword for declaring pointers that must be "far"
+ * on 80x86 machines. Most of the specialized coding for 80x86 is handled
+ * by just saying "FAR *" where such a pointer is needed. In a few places
+ * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
+ */
+
+#ifdef NEED_FAR_POINTERS
+#undef FAR
+#define FAR far
+#else
+#undef FAR
+#define FAR
+#endif
+
+
+/*
+ * On a few systems, type boolean and/or its values FALSE, TRUE may appear
+ * in standard header files. Or you may have conflicts with application-
+ * specific header files that you want to include together with these files.
+ * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
+ */
+
+//#ifndef HAVE_BOOLEAN
+//typedef int boolean;
+//#endif
+#ifndef FALSE /* in case these macros already exist */
+#define FALSE 0 /* values of boolean */
+#endif
+#ifndef TRUE
+#define TRUE 1
+#endif
+
+
+/*
+ * The remaining options affect code selection within the JPEG library,
+ * but they don't need to be visible to most applications using the library.
+ * To minimize application namespace pollution, the symbols won't be
+ * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
+ */
+
+#ifdef JPEG_INTERNALS
+#define JPEG_INTERNAL_OPTIONS
+#endif
+
+#ifdef JPEG_INTERNAL_OPTIONS
+
+
+/*
+ * These defines indicate whether to include various optional functions.
+ * Undefining some of these symbols will produce a smaller but less capable
+ * library. Note that you can leave certain source files out of the
+ * compilation/linking process if you've #undef'd the corresponding symbols.
+ * (You may HAVE to do that if your compiler doesn't like null source files.)
+ */
+
+/* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
+
+/* Capability options common to encoder and decoder: */
+
+#undef DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
+#undef DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
+#define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
+
+/* Encoder capability options: */
+
+#undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
+#define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
+#define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
+#define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
+/* Note: if you selected 12-bit data precision, it is dangerous to turn off
+ * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
+ * precision, so jchuff.c normally uses entropy optimization to compute
+ * usable tables for higher precision. If you don't want to do optimization,
+ * you'll have to supply different default Huffman tables.
+ * The exact same statements apply for progressive JPEG: the default tables
+ * don't work for progressive mode. (This may get fixed, however.)
+ */
+#define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
+
+/* Decoder capability options: */
+
+#undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
+#undef D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
+#undef D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
+#undef BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
+#undef IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
+#undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
+#undef UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
+#undef QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
+#undef QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
+
+/* more capability options later, no doubt */
+
+
+/*
+ * Ordering of RGB data in scanlines passed to or from the application.
+ * If your application wants to deal with data in the order B,G,R, just
+ * change these macros. You can also deal with formats such as R,G,B,X
+ * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
+ * the offsets will also change the order in which colormap data is organized.
+ * RESTRICTIONS:
+ * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
+ * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
+ * useful if you are using JPEG color spaces other than YCbCr or grayscale.
+ * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
+ * is not 3 (they don't understand about dummy color components!). So you
+ * can't use color quantization if you change that value.
+ */
+
+#define RGB_RED 0 /* Offset of Red in an RGB scanline element */
+#define RGB_GREEN 1 /* Offset of Green */
+#define RGB_BLUE 2 /* Offset of Blue */
+#define RGB_PIXELSIZE 4 /* JSAMPLEs per RGB scanline element */
+
+
+/* Definitions for speed-related optimizations. */
+
+
+/* If your compiler supports inline functions, define INLINE
+ * as the inline keyword; otherwise define it as empty.
+ */
+
+#ifndef INLINE
+#ifdef __GNUC__ /* for instance, GNU C knows about inline */
+#define INLINE __inline__
+#endif
+#ifndef INLINE
+#define INLINE /* default is to define it as empty */
+#endif
+#endif
+
+
+/* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
+ * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
+ * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
+ */
+
+#ifndef MULTIPLIER
+#define MULTIPLIER int /* type for fastest integer multiply */
+#endif
+
+
+/* FAST_FLOAT should be either float or double, whichever is done faster
+ * by your compiler. (Note that this type is only used in the floating point
+ * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
+ * Typically, float is faster in ANSI C compilers, while double is faster in
+ * pre-ANSI compilers (because they insist on converting to double anyway).
+ * The code below therefore chooses float if we have ANSI-style prototypes.
+ */
+
+#ifndef FAST_FLOAT
+#ifdef HAVE_PROTOTYPES
+#define FAST_FLOAT float
+#else
+#define FAST_FLOAT double
+#endif
+#endif
+
+#endif /* JPEG_INTERNAL_OPTIONS */
diff --git a/code/jpeg-6/jpegint.h b/code/jpeg-6/jpegint.h
new file mode 100755
index 0000000..b3b6a6d
--- /dev/null
+++ b/code/jpeg-6/jpegint.h
@@ -0,0 +1,388 @@
+/*
+ * jpegint.h
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file provides common declarations for the various JPEG modules.
+ * These declarations are considered internal to the JPEG library; most
+ * applications using the library shouldn't need to include this file.
+ */
+
+
+/* Declarations for both compression & decompression */
+
+typedef enum { /* Operating modes for buffer controllers */
+ JBUF_PASS_THRU, /* Plain stripwise operation */
+ /* Remaining modes require a full-image buffer to have been created */
+ JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
+ JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
+ JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
+} J_BUF_MODE;
+
+/* Values of global_state field (jdapi.c has some dependencies on ordering!) */
+#define CSTATE_START 100 /* after create_compress */
+#define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
+#define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
+#define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
+#define DSTATE_START 200 /* after create_decompress */
+#define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
+#define DSTATE_READY 202 /* found SOS, ready for start_decompress */
+#define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
+#define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
+#define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
+#define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
+#define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
+#define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
+#define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
+#define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
+
+
+/* Declarations for compression modules */
+
+/* Master control module */
+struct jpeg_comp_master {
+ JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
+ JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
+ JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
+
+ /* State variables made visible to other modules */
+ boolean call_pass_startup; /* True if pass_startup must be called */
+ boolean is_last_pass; /* True during last pass */
+};
+
+/* Main buffer control (downsampled-data buffer) */
+struct jpeg_c_main_controller {
+ JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
+ JMETHOD(void, process_data, (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
+ JDIMENSION in_rows_avail));
+};
+
+/* Compression preprocessing (downsampling input buffer control) */
+struct jpeg_c_prep_controller {
+ JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
+ JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf,
+ JDIMENSION *in_row_ctr,
+ JDIMENSION in_rows_avail,
+ JSAMPIMAGE output_buf,
+ JDIMENSION *out_row_group_ctr,
+ JDIMENSION out_row_groups_avail));
+};
+
+/* Coefficient buffer control */
+struct jpeg_c_coef_controller {
+ JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
+ JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
+ JSAMPIMAGE input_buf));
+};
+
+/* Colorspace conversion */
+struct jpeg_color_converter {
+ JMETHOD(void, start_pass, (j_compress_ptr cinfo));
+ JMETHOD(void, color_convert, (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+ JDIMENSION output_row, int num_rows));
+};
+
+/* Downsampling */
+struct jpeg_downsampler {
+ JMETHOD(void, start_pass, (j_compress_ptr cinfo));
+ JMETHOD(void, downsample, (j_compress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION in_row_index,
+ JSAMPIMAGE output_buf,
+ JDIMENSION out_row_group_index));
+
+ boolean need_context_rows; /* TRUE if need rows above & below */
+};
+
+/* Forward DCT (also controls coefficient quantization) */
+struct jpeg_forward_dct {
+ JMETHOD(void, start_pass, (j_compress_ptr cinfo));
+ /* perhaps this should be an array??? */
+ JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
+ jpeg_component_info * compptr,
+ JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
+ JDIMENSION start_row, JDIMENSION start_col,
+ JDIMENSION num_blocks));
+};
+
+/* Entropy encoding */
+struct jpeg_entropy_encoder {
+ JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
+ JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
+ JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
+};
+
+/* Marker writing */
+struct jpeg_marker_writer {
+ /* write_any_marker is exported for use by applications */
+ /* Probably only COM and APPn markers should be written */
+ JMETHOD(void, write_any_marker, (j_compress_ptr cinfo, int marker,
+ const JOCTET *dataptr, unsigned int datalen));
+ JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
+ JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
+ JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
+ JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
+ JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
+};
+
+
+/* Declarations for decompression modules */
+
+/* Master control module */
+struct jpeg_decomp_master {
+ JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
+ JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
+
+ /* State variables made visible to other modules */
+ boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
+};
+
+/* Input control module */
+struct jpeg_input_controller {
+ JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
+ JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
+ JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
+ JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
+
+ /* State variables made visible to other modules */
+ boolean has_multiple_scans; /* True if file has multiple scans */
+ boolean eoi_reached; /* True when EOI has been consumed */
+};
+
+/* Main buffer control (downsampled-data buffer) */
+struct jpeg_d_main_controller {
+ JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
+ JMETHOD(void, process_data, (j_decompress_ptr cinfo,
+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail));
+};
+
+/* Coefficient buffer control */
+struct jpeg_d_coef_controller {
+ JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
+ JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
+ JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
+ JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
+ JSAMPIMAGE output_buf));
+ /* Pointer to array of coefficient virtual arrays, or NULL if none */
+ jvirt_barray_ptr *coef_arrays;
+};
+
+/* Decompression postprocessing (color quantization buffer control) */
+struct jpeg_d_post_controller {
+ JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
+ JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf,
+ JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY output_buf,
+ JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail));
+};
+
+/* Marker reading & parsing */
+struct jpeg_marker_reader {
+ JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
+ /* Read markers until SOS or EOI.
+ * Returns same codes as are defined for jpeg_consume_input:
+ * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
+ */
+ JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
+ /* Read a restart marker --- exported for use by entropy decoder only */
+ jpeg_marker_parser_method read_restart_marker;
+ /* Application-overridable marker processing methods */
+ jpeg_marker_parser_method process_COM;
+ jpeg_marker_parser_method process_APPn[16];
+
+ /* State of marker reader --- nominally internal, but applications
+ * supplying COM or APPn handlers might like to know the state.
+ */
+ boolean saw_SOI; /* found SOI? */
+ boolean saw_SOF; /* found SOF? */
+ int next_restart_num; /* next restart number expected (0-7) */
+ unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
+};
+
+/* Entropy decoding */
+struct jpeg_entropy_decoder {
+ JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
+ JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
+ JBLOCKROW *MCU_data));
+};
+
+/* Inverse DCT (also performs dequantization) */
+typedef JMETHOD(void, inverse_DCT_method_ptr,
+ (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block,
+ JSAMPARRAY output_buf, JDIMENSION output_col));
+
+struct jpeg_inverse_dct {
+ JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
+ /* It is useful to allow each component to have a separate IDCT method. */
+ inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
+};
+
+/* Upsampling (note that upsampler must also call color converter) */
+struct jpeg_upsampler {
+ JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
+ JMETHOD(void, upsample, (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf,
+ JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY output_buf,
+ JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail));
+
+ boolean need_context_rows; /* TRUE if need rows above & below */
+};
+
+/* Colorspace conversion */
+struct jpeg_color_deconverter {
+ JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
+ JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION input_row,
+ JSAMPARRAY output_buf, int num_rows));
+};
+
+/* Color quantization or color precision reduction */
+struct jpeg_color_quantizer {
+ JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
+ JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPARRAY output_buf,
+ int num_rows));
+ JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
+ JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
+};
+
+
+/* Miscellaneous useful macros */
+
+#undef MAX
+#define MAX(a,b) ((a) > (b) ? (a) : (b))
+#undef MIN
+#define MIN(a,b) ((a) < (b) ? (a) : (b))
+
+
+/* We assume that right shift corresponds to signed division by 2 with
+ * rounding towards minus infinity. This is correct for typical "arithmetic
+ * shift" instructions that shift in copies of the sign bit. But some
+ * C compilers implement >> with an unsigned shift. For these machines you
+ * must define RIGHT_SHIFT_IS_UNSIGNED.
+ * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
+ * It is only applied with constant shift counts. SHIFT_TEMPS must be
+ * included in the variables of any routine using RIGHT_SHIFT.
+ */
+
+#ifdef RIGHT_SHIFT_IS_UNSIGNED
+#define SHIFT_TEMPS INT32 shift_temp;
+#define RIGHT_SHIFT(x,shft) \
+ ((shift_temp = (x)) < 0 ? \
+ (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
+ (shift_temp >> (shft)))
+#else
+#define SHIFT_TEMPS
+#define RIGHT_SHIFT(x,shft) ((x) >> (shft))
+#endif
+
+
+/* Short forms of external names for systems with brain-damaged linkers. */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jinit_compress_master jICompress
+#define jinit_c_master_control jICMaster
+#define jinit_c_main_controller jICMainC
+#define jinit_c_prep_controller jICPrepC
+#define jinit_c_coef_controller jICCoefC
+#define jinit_color_converter jICColor
+#define jinit_downsampler jIDownsampler
+#define jinit_forward_dct jIFDCT
+#define jinit_huff_encoder jIHEncoder
+#define jinit_phuff_encoder jIPHEncoder
+#define jinit_marker_writer jIMWriter
+#define jinit_master_decompress jIDMaster
+#define jinit_d_main_controller jIDMainC
+#define jinit_d_coef_controller jIDCoefC
+#define jinit_d_post_controller jIDPostC
+#define jinit_input_controller jIInCtlr
+#define jinit_marker_reader jIMReader
+#define jinit_huff_decoder jIHDecoder
+#define jinit_phuff_decoder jIPHDecoder
+#define jinit_inverse_dct jIIDCT
+#define jinit_upsampler jIUpsampler
+#define jinit_color_deconverter jIDColor
+#define jinit_1pass_quantizer jI1Quant
+#define jinit_2pass_quantizer jI2Quant
+#define jinit_merged_upsampler jIMUpsampler
+#define jinit_memory_mgr jIMemMgr
+#define jdiv_round_up jDivRound
+#define jround_up jRound
+#define jcopy_sample_rows jCopySamples
+#define jcopy_block_row jCopyBlocks
+#define jzero_far jZeroFar
+#define jpeg_zigzag_order jZIGTable
+#define jpeg_natural_order jZAGTable
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+
+/* Compression module initialization routines */
+EXTERN void jinit_compress_master JPP((j_compress_ptr cinfo));
+EXTERN void jinit_c_master_control JPP((j_compress_ptr cinfo,
+ boolean transcode_only));
+EXTERN void jinit_c_main_controller JPP((j_compress_ptr cinfo,
+ boolean need_full_buffer));
+EXTERN void jinit_c_prep_controller JPP((j_compress_ptr cinfo,
+ boolean need_full_buffer));
+EXTERN void jinit_c_coef_controller JPP((j_compress_ptr cinfo,
+ boolean need_full_buffer));
+EXTERN void jinit_color_converter JPP((j_compress_ptr cinfo));
+EXTERN void jinit_downsampler JPP((j_compress_ptr cinfo));
+EXTERN void jinit_forward_dct JPP((j_compress_ptr cinfo));
+EXTERN void jinit_huff_encoder JPP((j_compress_ptr cinfo));
+EXTERN void jinit_phuff_encoder JPP((j_compress_ptr cinfo));
+EXTERN void jinit_marker_writer JPP((j_compress_ptr cinfo));
+/* Decompression module initialization routines */
+EXTERN void jinit_master_decompress JPP((j_decompress_ptr cinfo));
+EXTERN void jinit_d_main_controller JPP((j_decompress_ptr cinfo,
+ boolean need_full_buffer));
+EXTERN void jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
+ boolean need_full_buffer));
+EXTERN void jinit_d_post_controller JPP((j_decompress_ptr cinfo,
+ boolean need_full_buffer));
+EXTERN void jinit_input_controller JPP((j_decompress_ptr cinfo));
+EXTERN void jinit_marker_reader JPP((j_decompress_ptr cinfo));
+EXTERN void jinit_huff_decoder JPP((j_decompress_ptr cinfo));
+EXTERN void jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
+EXTERN void jinit_inverse_dct JPP((j_decompress_ptr cinfo));
+EXTERN void jinit_upsampler JPP((j_decompress_ptr cinfo));
+EXTERN void jinit_color_deconverter JPP((j_decompress_ptr cinfo));
+EXTERN void jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
+EXTERN void jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
+EXTERN void jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
+/* Memory manager initialization */
+EXTERN void jinit_memory_mgr JPP((j_common_ptr cinfo));
+
+/* Utility routines in jutils.c */
+EXTERN long jdiv_round_up JPP((long a, long b));
+EXTERN long jround_up JPP((long a, long b));
+EXTERN void jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
+ JSAMPARRAY output_array, int dest_row,
+ int num_rows, JDIMENSION num_cols));
+EXTERN void jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
+ JDIMENSION num_blocks));
+EXTERN void jzero_far JPP((void FAR * target, size_t bytestozero));
+/* Constant tables in jutils.c */
+extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
+extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
+
+/* Suppress undefined-structure complaints if necessary. */
+
+#ifdef INCOMPLETE_TYPES_BROKEN
+#ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
+struct jvirt_sarray_control { long dummy; };
+struct jvirt_barray_control { long dummy; };
+#endif
+#endif /* INCOMPLETE_TYPES_BROKEN */
diff --git a/code/jpeg-6/jpeglib.h b/code/jpeg-6/jpeglib.h
new file mode 100755
index 0000000..3c57308
--- /dev/null
+++ b/code/jpeg-6/jpeglib.h
@@ -0,0 +1,1051 @@
+/*
+ * jpeglib.h
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file defines the application interface for the JPEG library.
+ * Most applications using the library need only include this file,
+ * and perhaps jerror.h if they want to know the exact error codes.
+ */
+
+#ifndef JPEGLIB_H
+#define JPEGLIB_H
+
+typedef unsigned char boolean;
+/*
+ * First we include the configuration files that record how this
+ * installation of the JPEG library is set up. jconfig.h can be
+ * generated automatically for many systems. jmorecfg.h contains
+ * manual configuration options that most people need not worry about.
+ */
+
+#ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
+#include "../jpeg-6/jconfig.h" /* widely used configuration options */
+#endif
+#include "../jpeg-6/jmorecfg.h" /* seldom changed options */
+
+
+/* Version ID for the JPEG library.
+ * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
+ */
+
+#define JPEG_LIB_VERSION 60 /* Version 6 */
+
+
+/* Various constants determining the sizes of things.
+ * All of these are specified by the JPEG standard, so don't change them
+ * if you want to be compatible.
+ */
+
+#define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
+#define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
+#define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
+#define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
+#define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
+#define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
+#define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
+/* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
+ * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
+ * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
+ * to handle it. We even let you do this from the jconfig.h file. However,
+ * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
+ * sometimes emits noncompliant files doesn't mean you should too.
+ */
+#define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
+#ifndef D_MAX_BLOCKS_IN_MCU
+#define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
+#endif
+
+
+/* This macro is used to declare a "method", that is, a function pointer.
+ * We want to supply prototype parameters if the compiler can cope.
+ * Note that the arglist parameter must be parenthesized!
+ */
+
+#ifdef HAVE_PROTOTYPES
+#define JMETHOD(type,methodname,arglist) type (*methodname) arglist
+#else
+#define JMETHOD(type,methodname,arglist) type (*methodname) ()
+#endif
+
+
+/* Data structures for images (arrays of samples and of DCT coefficients).
+ * On 80x86 machines, the image arrays are too big for near pointers,
+ * but the pointer arrays can fit in near memory.
+ */
+
+typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
+typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
+typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
+
+typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
+typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
+typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
+typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
+
+typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
+
+
+/* Types for JPEG compression parameters and working tables. */
+
+
+/* DCT coefficient quantization tables. */
+
+typedef struct {
+ /* This field directly represents the contents of a JPEG DQT marker.
+ * Note: the values are always given in zigzag order.
+ */
+ UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
+ /* This field is used only during compression. It's initialized FALSE when
+ * the table is created, and set TRUE when it's been output to the file.
+ * You could suppress output of a table by setting this to TRUE.
+ * (See jpeg_suppress_tables for an example.)
+ */
+ boolean sent_table; /* TRUE when table has been output */
+} JQUANT_TBL;
+
+
+/* Huffman coding tables. */
+
+typedef struct {
+ /* These two fields directly represent the contents of a JPEG DHT marker */
+ UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
+ /* length k bits; bits[0] is unused */
+ UINT8 huffval[256]; /* The symbols, in order of incr code length */
+ /* This field is used only during compression. It's initialized FALSE when
+ * the table is created, and set TRUE when it's been output to the file.
+ * You could suppress output of a table by setting this to TRUE.
+ * (See jpeg_suppress_tables for an example.)
+ */
+ boolean sent_table; /* TRUE when table has been output */
+} JHUFF_TBL;
+
+
+/* Basic info about one component (color channel). */
+
+typedef struct {
+ /* These values are fixed over the whole image. */
+ /* For compression, they must be supplied by parameter setup; */
+ /* for decompression, they are read from the SOF marker. */
+ int component_id; /* identifier for this component (0..255) */
+ int component_index; /* its index in SOF or cinfo->comp_info[] */
+ int h_samp_factor; /* horizontal sampling factor (1..4) */
+ int v_samp_factor; /* vertical sampling factor (1..4) */
+ int quant_tbl_no; /* quantization table selector (0..3) */
+ /* These values may vary between scans. */
+ /* For compression, they must be supplied by parameter setup; */
+ /* for decompression, they are read from the SOS marker. */
+ /* The decompressor output side may not use these variables. */
+ int dc_tbl_no; /* DC entropy table selector (0..3) */
+ int ac_tbl_no; /* AC entropy table selector (0..3) */
+
+ /* Remaining fields should be treated as private by applications. */
+
+ /* These values are computed during compression or decompression startup: */
+ /* Component's size in DCT blocks.
+ * Any dummy blocks added to complete an MCU are not counted; therefore
+ * these values do not depend on whether a scan is interleaved or not.
+ */
+ JDIMENSION width_in_blocks;
+ JDIMENSION height_in_blocks;
+ /* Size of a DCT block in samples. Always DCTSIZE for compression.
+ * For decompression this is the size of the output from one DCT block,
+ * reflecting any scaling we choose to apply during the IDCT step.
+ * Values of 1,2,4,8 are likely to be supported. Note that different
+ * components may receive different IDCT scalings.
+ */
+ int DCT_scaled_size;
+ /* The downsampled dimensions are the component's actual, unpadded number
+ * of samples at the main buffer (preprocessing/compression interface), thus
+ * downsampled_width = ceil(image_width * Hi/Hmax)
+ * and similarly for height. For decompression, IDCT scaling is included, so
+ * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
+ */
+ JDIMENSION downsampled_width; /* actual width in samples */
+ JDIMENSION downsampled_height; /* actual height in samples */
+ /* This flag is used only for decompression. In cases where some of the
+ * components will be ignored (eg grayscale output from YCbCr image),
+ * we can skip most computations for the unused components.
+ */
+ boolean component_needed; /* do we need the value of this component? */
+
+ /* These values are computed before starting a scan of the component. */
+ /* The decompressor output side may not use these variables. */
+ int MCU_width; /* number of blocks per MCU, horizontally */
+ int MCU_height; /* number of blocks per MCU, vertically */
+ int MCU_blocks; /* MCU_width * MCU_height */
+ int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
+ int last_col_width; /* # of non-dummy blocks across in last MCU */
+ int last_row_height; /* # of non-dummy blocks down in last MCU */
+
+ /* Saved quantization table for component; NULL if none yet saved.
+ * See jdinput.c comments about the need for this information.
+ * This field is not currently used by the compressor.
+ */
+ JQUANT_TBL * quant_table;
+
+ /* Private per-component storage for DCT or IDCT subsystem. */
+ void * dct_table;
+} jpeg_component_info;
+
+
+/* The script for encoding a multiple-scan file is an array of these: */
+
+typedef struct {
+ int comps_in_scan; /* number of components encoded in this scan */
+ int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
+ int Ss, Se; /* progressive JPEG spectral selection parms */
+ int Ah, Al; /* progressive JPEG successive approx. parms */
+} jpeg_scan_info;
+
+
+/* Known color spaces. */
+
+typedef enum {
+ JCS_UNKNOWN, /* error/unspecified */
+ JCS_GRAYSCALE, /* monochrome */
+ JCS_RGB, /* red/green/blue */
+ JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
+ JCS_CMYK, /* C/M/Y/K */
+ JCS_YCCK /* Y/Cb/Cr/K */
+} J_COLOR_SPACE;
+
+/* DCT/IDCT algorithm options. */
+
+typedef enum {
+ JDCT_ISLOW, /* slow but accurate integer algorithm */
+ JDCT_IFAST, /* faster, less accurate integer method */
+ JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
+} J_DCT_METHOD;
+
+#ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
+#define JDCT_DEFAULT JDCT_ISLOW
+#endif
+#ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
+#define JDCT_FASTEST JDCT_IFAST
+#endif
+
+/* Dithering options for decompression. */
+
+typedef enum {
+ JDITHER_NONE, /* no dithering */
+ JDITHER_ORDERED, /* simple ordered dither */
+ JDITHER_FS /* Floyd-Steinberg error diffusion dither */
+} J_DITHER_MODE;
+
+
+/* Common fields between JPEG compression and decompression master structs. */
+
+#define jpeg_common_fields \
+ struct jpeg_error_mgr * err; /* Error handler module */\
+ struct jpeg_memory_mgr * mem; /* Memory manager module */\
+ struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
+ boolean is_decompressor; /* so common code can tell which is which */\
+ int global_state /* for checking call sequence validity */
+
+/* Routines that are to be used by both halves of the library are declared
+ * to receive a pointer to this structure. There are no actual instances of
+ * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
+ */
+struct jpeg_common_struct {
+ jpeg_common_fields; /* Fields common to both master struct types */
+ /* Additional fields follow in an actual jpeg_compress_struct or
+ * jpeg_decompress_struct. All three structs must agree on these
+ * initial fields! (This would be a lot cleaner in C++.)
+ */
+};
+
+typedef struct jpeg_common_struct * j_common_ptr;
+typedef struct jpeg_compress_struct * j_compress_ptr;
+typedef struct jpeg_decompress_struct * j_decompress_ptr;
+
+
+/* Master record for a compression instance */
+
+struct jpeg_compress_struct {
+ jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
+
+ /* Destination for compressed data */
+ struct jpeg_destination_mgr * dest;
+
+ /* Description of source image --- these fields must be filled in by
+ * outer application before starting compression. in_color_space must
+ * be correct before you can even call jpeg_set_defaults().
+ */
+
+ JDIMENSION image_width; /* input image width */
+ JDIMENSION image_height; /* input image height */
+ int input_components; /* # of color components in input image */
+ J_COLOR_SPACE in_color_space; /* colorspace of input image */
+
+ double input_gamma; /* image gamma of input image */
+
+ /* Compression parameters --- these fields must be set before calling
+ * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
+ * initialize everything to reasonable defaults, then changing anything
+ * the application specifically wants to change. That way you won't get
+ * burnt when new parameters are added. Also note that there are several
+ * helper routines to simplify changing parameters.
+ */
+
+ int data_precision; /* bits of precision in image data */
+
+ int num_components; /* # of color components in JPEG image */
+ J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
+
+ jpeg_component_info * comp_info;
+ /* comp_info[i] describes component that appears i'th in SOF */
+
+ JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
+ /* ptrs to coefficient quantization tables, or NULL if not defined */
+
+ JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
+ JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
+ /* ptrs to Huffman coding tables, or NULL if not defined */
+
+ UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
+ UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
+ UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
+
+ int num_scans; /* # of entries in scan_info array */
+ const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
+ /* The default value of scan_info is NULL, which causes a single-scan
+ * sequential JPEG file to be emitted. To create a multi-scan file,
+ * set num_scans and scan_info to point to an array of scan definitions.
+ */
+
+ boolean raw_data_in; /* TRUE=caller supplies downsampled data */
+ boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
+ boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
+ boolean CCIR601_sampling; /* TRUE=first samples are cosited */
+ int smoothing_factor; /* 1..100, or 0 for no input smoothing */
+ J_DCT_METHOD dct_method; /* DCT algorithm selector */
+
+ /* The restart interval can be specified in absolute MCUs by setting
+ * restart_interval, or in MCU rows by setting restart_in_rows
+ * (in which case the correct restart_interval will be figured
+ * for each scan).
+ */
+ unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
+ int restart_in_rows; /* if > 0, MCU rows per restart interval */
+
+ /* Parameters controlling emission of special markers. */
+
+ boolean write_JFIF_header; /* should a JFIF marker be written? */
+ /* These three values are not used by the JPEG code, merely copied */
+ /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
+ /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
+ /* ratio is defined by X_density/Y_density even when density_unit=0. */
+ UINT8 density_unit; /* JFIF code for pixel size units */
+ UINT16 X_density; /* Horizontal pixel density */
+ UINT16 Y_density; /* Vertical pixel density */
+ boolean write_Adobe_marker; /* should an Adobe marker be written? */
+
+ /* State variable: index of next scanline to be written to
+ * jpeg_write_scanlines(). Application may use this to control its
+ * processing loop, e.g., "while (next_scanline < image_height)".
+ */
+
+ JDIMENSION next_scanline; /* 0 .. image_height-1 */
+
+ /* Remaining fields are known throughout compressor, but generally
+ * should not be touched by a surrounding application.
+ */
+
+ /*
+ * These fields are computed during compression startup
+ */
+ boolean progressive_mode; /* TRUE if scan script uses progressive mode */
+ int max_h_samp_factor; /* largest h_samp_factor */
+ int max_v_samp_factor; /* largest v_samp_factor */
+
+ JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
+ /* The coefficient controller receives data in units of MCU rows as defined
+ * for fully interleaved scans (whether the JPEG file is interleaved or not).
+ * There are v_samp_factor * DCTSIZE sample rows of each component in an
+ * "iMCU" (interleaved MCU) row.
+ */
+
+ /*
+ * These fields are valid during any one scan.
+ * They describe the components and MCUs actually appearing in the scan.
+ */
+ int comps_in_scan; /* # of JPEG components in this scan */
+ jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
+ /* *cur_comp_info[i] describes component that appears i'th in SOS */
+
+ JDIMENSION MCUs_per_row; /* # of MCUs across the image */
+ JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
+
+ int blocks_in_MCU; /* # of DCT blocks per MCU */
+ int MCU_membership[C_MAX_BLOCKS_IN_MCU];
+ /* MCU_membership[i] is index in cur_comp_info of component owning */
+ /* i'th block in an MCU */
+
+ int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
+
+ /*
+ * Links to compression subobjects (methods and private variables of modules)
+ */
+ struct jpeg_comp_master * master;
+ struct jpeg_c_main_controller * main;
+ struct jpeg_c_prep_controller * prep;
+ struct jpeg_c_coef_controller * coef;
+ struct jpeg_marker_writer * marker;
+ struct jpeg_color_converter * cconvert;
+ struct jpeg_downsampler * downsample;
+ struct jpeg_forward_dct * fdct;
+ struct jpeg_entropy_encoder * entropy;
+};
+
+
+/* Master record for a decompression instance */
+
+struct jpeg_decompress_struct {
+ jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
+
+ /* Source of compressed data */
+ struct jpeg_source_mgr * src;
+
+ /* Basic description of image --- filled in by jpeg_read_header(). */
+ /* Application may inspect these values to decide how to process image. */
+
+ JDIMENSION image_width; /* nominal image width (from SOF marker) */
+ JDIMENSION image_height; /* nominal image height */
+ int num_components; /* # of color components in JPEG image */
+ J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
+
+ /* Decompression processing parameters --- these fields must be set before
+ * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
+ * them to default values.
+ */
+
+ J_COLOR_SPACE out_color_space; /* colorspace for output */
+
+ unsigned int scale_num, scale_denom; /* fraction by which to scale image */
+
+ double output_gamma; /* image gamma wanted in output */
+
+ boolean buffered_image; /* TRUE=multiple output passes */
+ boolean raw_data_out; /* TRUE=downsampled data wanted */
+
+ J_DCT_METHOD dct_method; /* IDCT algorithm selector */
+ boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
+ boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
+
+ boolean quantize_colors; /* TRUE=colormapped output wanted */
+ /* the following are ignored if not quantize_colors: */
+ J_DITHER_MODE dither_mode; /* type of color dithering to use */
+ boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
+ int desired_number_of_colors; /* max # colors to use in created colormap */
+ /* these are significant only in buffered-image mode: */
+ boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
+ boolean enable_external_quant;/* enable future use of external colormap */
+ boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
+
+ /* Description of actual output image that will be returned to application.
+ * These fields are computed by jpeg_start_decompress().
+ * You can also use jpeg_calc_output_dimensions() to determine these values
+ * in advance of calling jpeg_start_decompress().
+ */
+
+ JDIMENSION output_width; /* scaled image width */
+ JDIMENSION output_height; /* scaled image height */
+ int out_color_components; /* # of color components in out_color_space */
+ int output_components; /* # of color components returned */
+ /* output_components is 1 (a colormap index) when quantizing colors;
+ * otherwise it equals out_color_components.
+ */
+ int rec_outbuf_height; /* min recommended height of scanline buffer */
+ /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
+ * high, space and time will be wasted due to unnecessary data copying.
+ * Usually rec_outbuf_height will be 1 or 2, at most 4.
+ */
+
+ /* When quantizing colors, the output colormap is described by these fields.
+ * The application can supply a colormap by setting colormap non-NULL before
+ * calling jpeg_start_decompress; otherwise a colormap is created during
+ * jpeg_start_decompress or jpeg_start_output.
+ * The map has out_color_components rows and actual_number_of_colors columns.
+ */
+ int actual_number_of_colors; /* number of entries in use */
+ JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
+
+ /* State variables: these variables indicate the progress of decompression.
+ * The application may examine these but must not modify them.
+ */
+
+ /* Row index of next scanline to be read from jpeg_read_scanlines().
+ * Application may use this to control its processing loop, e.g.,
+ * "while (output_scanline < output_height)".
+ */
+ JDIMENSION output_scanline; /* 0 .. output_height-1 */
+
+ /* Current input scan number and number of iMCU rows completed in scan.
+ * These indicate the progress of the decompressor input side.
+ */
+ int input_scan_number; /* Number of SOS markers seen so far */
+ JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
+
+ /* The "output scan number" is the notional scan being displayed by the
+ * output side. The decompressor will not allow output scan/row number
+ * to get ahead of input scan/row, but it can fall arbitrarily far behind.
+ */
+ int output_scan_number; /* Nominal scan number being displayed */
+ JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
+
+ /* Current progression status. coef_bits[c][i] indicates the precision
+ * with which component c's DCT coefficient i (in zigzag order) is known.
+ * It is -1 when no data has yet been received, otherwise it is the point
+ * transform (shift) value for the most recent scan of the coefficient
+ * (thus, 0 at completion of the progression).
+ * This pointer is NULL when reading a non-progressive file.
+ */
+ int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
+
+ /* Internal JPEG parameters --- the application usually need not look at
+ * these fields. Note that the decompressor output side may not use
+ * any parameters that can change between scans.
+ */
+
+ /* Quantization and Huffman tables are carried forward across input
+ * datastreams when processing abbreviated JPEG datastreams.
+ */
+
+ JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
+ /* ptrs to coefficient quantization tables, or NULL if not defined */
+
+ JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
+ JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
+ /* ptrs to Huffman coding tables, or NULL if not defined */
+
+ /* These parameters are never carried across datastreams, since they
+ * are given in SOF/SOS markers or defined to be reset by SOI.
+ */
+
+ int data_precision; /* bits of precision in image data */
+
+ jpeg_component_info * comp_info;
+ /* comp_info[i] describes component that appears i'th in SOF */
+
+ boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
+ boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
+
+ UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
+ UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
+ UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
+
+ unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
+
+ /* These fields record data obtained from optional markers recognized by
+ * the JPEG library.
+ */
+ boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
+ /* Data copied from JFIF marker: */
+ UINT8 density_unit; /* JFIF code for pixel size units */
+ UINT16 X_density; /* Horizontal pixel density */
+ UINT16 Y_density; /* Vertical pixel density */
+ boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
+ UINT8 Adobe_transform; /* Color transform code from Adobe marker */
+
+ boolean CCIR601_sampling; /* TRUE=first samples are cosited */
+
+ /* Remaining fields are known throughout decompressor, but generally
+ * should not be touched by a surrounding application.
+ */
+
+ /*
+ * These fields are computed during decompression startup
+ */
+ int max_h_samp_factor; /* largest h_samp_factor */
+ int max_v_samp_factor; /* largest v_samp_factor */
+
+ int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
+
+ JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
+ /* The coefficient controller's input and output progress is measured in
+ * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
+ * in fully interleaved JPEG scans, but are used whether the scan is
+ * interleaved or not. We define an iMCU row as v_samp_factor DCT block
+ * rows of each component. Therefore, the IDCT output contains
+ * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
+ */
+
+ JSAMPLE * sample_range_limit; /* table for fast range-limiting */
+
+ /*
+ * These fields are valid during any one scan.
+ * They describe the components and MCUs actually appearing in the scan.
+ * Note that the decompressor output side must not use these fields.
+ */
+ int comps_in_scan; /* # of JPEG components in this scan */
+ jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
+ /* *cur_comp_info[i] describes component that appears i'th in SOS */
+
+ JDIMENSION MCUs_per_row; /* # of MCUs across the image */
+ JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
+
+ int blocks_in_MCU; /* # of DCT blocks per MCU */
+ int MCU_membership[D_MAX_BLOCKS_IN_MCU];
+ /* MCU_membership[i] is index in cur_comp_info of component owning */
+ /* i'th block in an MCU */
+
+ int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
+
+ /* This field is shared between entropy decoder and marker parser.
+ * It is either zero or the code of a JPEG marker that has been
+ * read from the data source, but has not yet been processed.
+ */
+ int unread_marker;
+
+ /*
+ * Links to decompression subobjects (methods, private variables of modules)
+ */
+ struct jpeg_decomp_master * master;
+ struct jpeg_d_main_controller * main;
+ struct jpeg_d_coef_controller * coef;
+ struct jpeg_d_post_controller * post;
+ struct jpeg_input_controller * inputctl;
+ struct jpeg_marker_reader * marker;
+ struct jpeg_entropy_decoder * entropy;
+ struct jpeg_inverse_dct * idct;
+ struct jpeg_upsampler * upsample;
+ struct jpeg_color_deconverter * cconvert;
+ struct jpeg_color_quantizer * cquantize;
+};
+
+
+/* "Object" declarations for JPEG modules that may be supplied or called
+ * directly by the surrounding application.
+ * As with all objects in the JPEG library, these structs only define the
+ * publicly visible methods and state variables of a module. Additional
+ * private fields may exist after the public ones.
+ */
+
+
+/* Error handler object */
+
+struct jpeg_error_mgr {
+ /* Error exit handler: does not return to caller */
+ JMETHOD(void, error_exit, (j_common_ptr cinfo));
+ /* Conditionally emit a trace or warning message */
+ JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
+ /* Routine that actually outputs a trace or error message */
+ JMETHOD(void, output_message, (j_common_ptr cinfo));
+ /* Format a message string for the most recent JPEG error or message */
+ JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
+#define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
+ /* Reset error state variables at start of a new image */
+ JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
+
+ /* The message ID code and any parameters are saved here.
+ * A message can have one string parameter or up to 8 int parameters.
+ */
+ int msg_code;
+#define JMSG_STR_PARM_MAX 80
+ union {
+ int i[8];
+ char s[JMSG_STR_PARM_MAX];
+ } msg_parm;
+
+ /* Standard state variables for error facility */
+
+ int trace_level; /* max msg_level that will be displayed */
+
+ /* For recoverable corrupt-data errors, we emit a warning message,
+ * but keep going unless emit_message chooses to abort. emit_message
+ * should count warnings in num_warnings. The surrounding application
+ * can check for bad data by seeing if num_warnings is nonzero at the
+ * end of processing.
+ */
+ long num_warnings; /* number of corrupt-data warnings */
+
+ /* These fields point to the table(s) of error message strings.
+ * An application can change the table pointer to switch to a different
+ * message list (typically, to change the language in which errors are
+ * reported). Some applications may wish to add additional error codes
+ * that will be handled by the JPEG library error mechanism; the second
+ * table pointer is used for this purpose.
+ *
+ * First table includes all errors generated by JPEG library itself.
+ * Error code 0 is reserved for a "no such error string" message.
+ */
+ const char * const * jpeg_message_table; /* Library errors */
+ int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
+ /* Second table can be added by application (see cjpeg/djpeg for example).
+ * It contains strings numbered first_addon_message..last_addon_message.
+ */
+ const char * const * addon_message_table; /* Non-library errors */
+ int first_addon_message; /* code for first string in addon table */
+ int last_addon_message; /* code for last string in addon table */
+};
+
+
+/* Progress monitor object */
+
+struct jpeg_progress_mgr {
+ JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
+
+ long pass_counter; /* work units completed in this pass */
+ long pass_limit; /* total number of work units in this pass */
+ int completed_passes; /* passes completed so far */
+ int total_passes; /* total number of passes expected */
+};
+
+
+/* Data destination object for compression */
+
+struct jpeg_destination_mgr {
+ JOCTET * next_output_byte; /* => next byte to write in buffer */
+ size_t free_in_buffer; /* # of byte spaces remaining in buffer */
+
+ JMETHOD(void, init_destination, (j_compress_ptr cinfo));
+ JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
+ JMETHOD(void, term_destination, (j_compress_ptr cinfo));
+};
+
+
+/* Data source object for decompression */
+
+struct jpeg_source_mgr {
+ const JOCTET * next_input_byte; /* => next byte to read from buffer */
+ size_t bytes_in_buffer; /* # of bytes remaining in buffer */
+
+ JMETHOD(void, init_source, (j_decompress_ptr cinfo));
+ JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
+ JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
+ JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
+ JMETHOD(void, term_source, (j_decompress_ptr cinfo));
+};
+
+
+/* Memory manager object.
+ * Allocates "small" objects (a few K total), "large" objects (tens of K),
+ * and "really big" objects (virtual arrays with backing store if needed).
+ * The memory manager does not allow individual objects to be freed; rather,
+ * each created object is assigned to a pool, and whole pools can be freed
+ * at once. This is faster and more convenient than remembering exactly what
+ * to free, especially where malloc()/free() are not too speedy.
+ * NB: alloc routines never return NULL. They exit to error_exit if not
+ * successful.
+ */
+
+#define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
+#define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
+#define JPOOL_NUMPOOLS 2
+
+typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
+typedef struct jvirt_barray_control * jvirt_barray_ptr;
+
+
+struct jpeg_memory_mgr {
+ /* Method pointers */
+ JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
+ size_t sizeofobject));
+ JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
+ size_t sizeofobject));
+ JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
+ JDIMENSION samplesperrow,
+ JDIMENSION numrows));
+ JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
+ JDIMENSION blocksperrow,
+ JDIMENSION numrows));
+ JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
+ int pool_id,
+ boolean pre_zero,
+ JDIMENSION samplesperrow,
+ JDIMENSION numrows,
+ JDIMENSION maxaccess));
+ JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
+ int pool_id,
+ boolean pre_zero,
+ JDIMENSION blocksperrow,
+ JDIMENSION numrows,
+ JDIMENSION maxaccess));
+ JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
+ JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
+ jvirt_sarray_ptr ptr,
+ JDIMENSION start_row,
+ JDIMENSION num_rows,
+ boolean writable));
+ JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
+ jvirt_barray_ptr ptr,
+ JDIMENSION start_row,
+ JDIMENSION num_rows,
+ boolean writable));
+ JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
+ JMETHOD(void, self_destruct, (j_common_ptr cinfo));
+
+ /* Limit on memory allocation for this JPEG object. (Note that this is
+ * merely advisory, not a guaranteed maximum; it only affects the space
+ * used for virtual-array buffers.) May be changed by outer application
+ * after creating the JPEG object.
+ */
+ long max_memory_to_use;
+};
+
+
+/* Routine signature for application-supplied marker processing methods.
+ * Need not pass marker code since it is stored in cinfo->unread_marker.
+ */
+typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
+
+
+/* Declarations for routines called by application.
+ * The JPP macro hides prototype parameters from compilers that can't cope.
+ * Note JPP requires double parentheses.
+ */
+
+#ifdef HAVE_PROTOTYPES
+#define JPP(arglist) arglist
+#else
+#define JPP(arglist) ()
+#endif
+
+
+/* Short forms of external names for systems with brain-damaged linkers.
+ * We shorten external names to be unique in the first six letters, which
+ * is good enough for all known systems.
+ * (If your compiler itself needs names to be unique in less than 15
+ * characters, you are out of luck. Get a better compiler.)
+ */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jpeg_std_error jStdError
+#define jpeg_create_compress jCreaCompress
+#define jpeg_create_decompress jCreaDecompress
+#define jpeg_destroy_compress jDestCompress
+#define jpeg_destroy_decompress jDestDecompress
+#define jpeg_stdio_dest jStdDest
+#define jpeg_stdio_src jStdSrc
+#define jpeg_set_defaults jSetDefaults
+#define jpeg_set_colorspace jSetColorspace
+#define jpeg_default_colorspace jDefColorspace
+#define jpeg_set_quality jSetQuality
+#define jpeg_set_linear_quality jSetLQuality
+#define jpeg_add_quant_table jAddQuantTable
+#define jpeg_quality_scaling jQualityScaling
+#define jpeg_simple_progression jSimProgress
+#define jpeg_suppress_tables jSuppressTables
+#define jpeg_alloc_quant_table jAlcQTable
+#define jpeg_alloc_huff_table jAlcHTable
+#define jpeg_start_compress jStrtCompress
+#define jpeg_write_scanlines jWrtScanlines
+#define jpeg_finish_compress jFinCompress
+#define jpeg_write_raw_data jWrtRawData
+#define jpeg_write_marker jWrtMarker
+#define jpeg_write_tables jWrtTables
+#define jpeg_read_header jReadHeader
+#define jpeg_start_decompress jStrtDecompress
+#define jpeg_read_scanlines jReadScanlines
+#define jpeg_finish_decompress jFinDecompress
+#define jpeg_read_raw_data jReadRawData
+#define jpeg_has_multiple_scans jHasMultScn
+#define jpeg_start_output jStrtOutput
+#define jpeg_finish_output jFinOutput
+#define jpeg_input_complete jInComplete
+#define jpeg_new_colormap jNewCMap
+#define jpeg_consume_input jConsumeInput
+#define jpeg_calc_output_dimensions jCalcDimensions
+#define jpeg_set_marker_processor jSetMarker
+#define jpeg_read_coefficients jReadCoefs
+#define jpeg_write_coefficients jWrtCoefs
+#define jpeg_copy_critical_parameters jCopyCrit
+#define jpeg_abort_compress jAbrtCompress
+#define jpeg_abort_decompress jAbrtDecompress
+#define jpeg_abort jAbort
+#define jpeg_destroy jDestroy
+#define jpeg_resync_to_restart jResyncRestart
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+
+/* Default error-management setup */
+EXTERN struct jpeg_error_mgr *jpeg_std_error JPP((struct jpeg_error_mgr *err));
+
+/* Initialization and destruction of JPEG compression objects */
+/* NB: you must set up the error-manager BEFORE calling jpeg_create_xxx */
+EXTERN void jpeg_create_compress JPP((j_compress_ptr cinfo));
+EXTERN void jpeg_create_decompress JPP((j_decompress_ptr cinfo));
+EXTERN void jpeg_destroy_compress JPP((j_compress_ptr cinfo));
+EXTERN void jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
+
+/* Standard data source and destination managers: stdio streams. */
+/* Caller is responsible for opening the file before and closing after. */
+EXTERN void jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
+EXTERN void jpeg_stdio_src JPP((j_decompress_ptr cinfo, unsigned char *infile));
+
+/* Default parameter setup for compression */
+EXTERN void jpeg_set_defaults JPP((j_compress_ptr cinfo));
+/* Compression parameter setup aids */
+EXTERN void jpeg_set_colorspace JPP((j_compress_ptr cinfo,
+ J_COLOR_SPACE colorspace));
+EXTERN void jpeg_default_colorspace JPP((j_compress_ptr cinfo));
+EXTERN void jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
+ boolean force_baseline));
+EXTERN void jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
+ int scale_factor,
+ boolean force_baseline));
+EXTERN void jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
+ const unsigned int *basic_table,
+ int scale_factor,
+ boolean force_baseline));
+EXTERN int jpeg_quality_scaling JPP((int quality));
+EXTERN void jpeg_simple_progression JPP((j_compress_ptr cinfo));
+EXTERN void jpeg_suppress_tables JPP((j_compress_ptr cinfo,
+ boolean suppress));
+EXTERN JQUANT_TBL * jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
+EXTERN JHUFF_TBL * jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
+
+/* Main entry points for compression */
+EXTERN void jpeg_start_compress JPP((j_compress_ptr cinfo,
+ boolean write_all_tables));
+EXTERN JDIMENSION jpeg_write_scanlines JPP((j_compress_ptr cinfo,
+ JSAMPARRAY scanlines,
+ JDIMENSION num_lines));
+EXTERN void jpeg_finish_compress JPP((j_compress_ptr cinfo));
+
+/* Replaces jpeg_write_scanlines when writing raw downsampled data. */
+EXTERN JDIMENSION jpeg_write_raw_data JPP((j_compress_ptr cinfo,
+ JSAMPIMAGE data,
+ JDIMENSION num_lines));
+
+/* Write a special marker. See libjpeg.doc concerning safe usage. */
+EXTERN void jpeg_write_marker JPP((j_compress_ptr cinfo, int marker,
+ const JOCTET *dataptr, unsigned int datalen));
+
+/* Alternate compression function: just write an abbreviated table file */
+EXTERN void jpeg_write_tables JPP((j_compress_ptr cinfo));
+
+/* Decompression startup: read start of JPEG datastream to see what's there */
+EXTERN int jpeg_read_header JPP((j_decompress_ptr cinfo,
+ boolean require_image));
+/* Return value is one of: */
+#define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
+#define JPEG_HEADER_OK 1 /* Found valid image datastream */
+#define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
+/* If you pass require_image = TRUE (normal case), you need not check for
+ * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
+ * JPEG_SUSPENDED is only possible if you use a data source module that can
+ * give a suspension return (the stdio source module doesn't).
+ */
+
+/* Main entry points for decompression */
+EXTERN boolean jpeg_start_decompress JPP((j_decompress_ptr cinfo));
+EXTERN JDIMENSION jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
+ JSAMPARRAY scanlines,
+ JDIMENSION max_lines));
+EXTERN boolean jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
+
+/* Replaces jpeg_read_scanlines when reading raw downsampled data. */
+EXTERN JDIMENSION jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
+ JSAMPIMAGE data,
+ JDIMENSION max_lines));
+
+/* Additional entry points for buffered-image mode. */
+EXTERN boolean jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
+EXTERN boolean jpeg_start_output JPP((j_decompress_ptr cinfo,
+ int scan_number));
+EXTERN boolean jpeg_finish_output JPP((j_decompress_ptr cinfo));
+EXTERN boolean jpeg_input_complete JPP((j_decompress_ptr cinfo));
+EXTERN void jpeg_new_colormap JPP((j_decompress_ptr cinfo));
+EXTERN int jpeg_consume_input JPP((j_decompress_ptr cinfo));
+/* Return value is one of: */
+/* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
+#define JPEG_REACHED_SOS 1 /* Reached start of new scan */
+#define JPEG_REACHED_EOI 2 /* Reached end of image */
+#define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
+#define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
+
+/* Precalculate output dimensions for current decompression parameters. */
+EXTERN void jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
+
+/* Install a special processing method for COM or APPn markers. */
+EXTERN void jpeg_set_marker_processor JPP((j_decompress_ptr cinfo,
+ int marker_code,
+ jpeg_marker_parser_method routine));
+
+/* Read or write raw DCT coefficients --- useful for lossless transcoding. */
+EXTERN jvirt_barray_ptr * jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
+EXTERN void jpeg_write_coefficients JPP((j_compress_ptr cinfo,
+ jvirt_barray_ptr * coef_arrays));
+EXTERN void jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
+ j_compress_ptr dstinfo));
+
+/* If you choose to abort compression or decompression before completing
+ * jpeg_finish_(de)compress, then you need to clean up to release memory,
+ * temporary files, etc. You can just call jpeg_destroy_(de)compress
+ * if you're done with the JPEG object, but if you want to clean it up and
+ * reuse it, call this:
+ */
+EXTERN void jpeg_abort_compress JPP((j_compress_ptr cinfo));
+EXTERN void jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
+
+/* Generic versions of jpeg_abort and jpeg_destroy that work on either
+ * flavor of JPEG object. These may be more convenient in some places.
+ */
+EXTERN void jpeg_abort JPP((j_common_ptr cinfo));
+EXTERN void jpeg_destroy JPP((j_common_ptr cinfo));
+
+/* Default restart-marker-resync procedure for use by data source modules */
+EXTERN boolean jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
+ int desired));
+
+
+/* These marker codes are exported since applications and data source modules
+ * are likely to want to use them.
+ */
+
+#define JPEG_RST0 0xD0 /* RST0 marker code */
+#define JPEG_EOI 0xD9 /* EOI marker code */
+#define JPEG_APP0 0xE0 /* APP0 marker code */
+#define JPEG_COM 0xFE /* COM marker code */
+
+
+/* If we have a brain-damaged compiler that emits warnings (or worse, errors)
+ * for structure definitions that are never filled in, keep it quiet by
+ * supplying dummy definitions for the various substructures.
+ */
+
+#ifdef INCOMPLETE_TYPES_BROKEN
+#ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
+struct jvirt_sarray_control { long dummy; };
+struct jvirt_barray_control { long dummy; };
+struct jpeg_comp_master { long dummy; };
+struct jpeg_c_main_controller { long dummy; };
+struct jpeg_c_prep_controller { long dummy; };
+struct jpeg_c_coef_controller { long dummy; };
+struct jpeg_marker_writer { long dummy; };
+struct jpeg_color_converter { long dummy; };
+struct jpeg_downsampler { long dummy; };
+struct jpeg_forward_dct { long dummy; };
+struct jpeg_entropy_encoder { long dummy; };
+struct jpeg_decomp_master { long dummy; };
+struct jpeg_d_main_controller { long dummy; };
+struct jpeg_d_coef_controller { long dummy; };
+struct jpeg_d_post_controller { long dummy; };
+struct jpeg_input_controller { long dummy; };
+struct jpeg_marker_reader { long dummy; };
+struct jpeg_entropy_decoder { long dummy; };
+struct jpeg_inverse_dct { long dummy; };
+struct jpeg_upsampler { long dummy; };
+struct jpeg_color_deconverter { long dummy; };
+struct jpeg_color_quantizer { long dummy; };
+#endif /* JPEG_INTERNALS */
+#endif /* INCOMPLETE_TYPES_BROKEN */
+
+
+/*
+ * The JPEG library modules define JPEG_INTERNALS before including this file.
+ * The internal structure declarations are read only when that is true.
+ * Applications using the library should not include jpegint.h, but may wish
+ * to include jerror.h.
+ */
+
+#ifdef JPEG_INTERNALS
+#include "../jpeg-6/jpegint.h" /* fetch private declarations */
+#include "../jpeg-6/jerror.h" /* fetch error codes too */
+#endif
+
+#endif /* JPEGLIB_H */
diff --git a/code/jpeg-6/jpegtran.c b/code/jpeg-6/jpegtran.c
new file mode 100755
index 0000000..f23a4b4
--- /dev/null
+++ b/code/jpeg-6/jpegtran.c
@@ -0,0 +1,370 @@
+/*
+ * jpegtran.c
+ *
+ * Copyright (C) 1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains a command-line user interface for JPEG transcoding.
+ * It is very similar to cjpeg.c, but provides lossless transcoding between
+ * different JPEG file formats.
+ */
+
+#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
+#include "jversion.h" /* for version message */
+
+#ifdef USE_CCOMMAND /* command-line reader for Macintosh */
+#ifdef __MWERKS__
+#include <SIOUX.h> /* Metrowerks declares it here */
+#endif
+#ifdef THINK_C
+#include <console.h> /* Think declares it here */
+#endif
+#endif
+
+
+/*
+ * Argument-parsing code.
+ * The switch parser is designed to be useful with DOS-style command line
+ * syntax, ie, intermixed switches and file names, where only the switches
+ * to the left of a given file name affect processing of that file.
+ * The main program in this file doesn't actually use this capability...
+ */
+
+
+static const char * progname; /* program name for error messages */
+static char * outfilename; /* for -outfile switch */
+
+
+LOCAL void
+usage (void)
+/* complain about bad command line */
+{
+ fprintf(stderr, "usage: %s [switches] ", progname);
+#ifdef TWO_FILE_COMMANDLINE
+ fprintf(stderr, "inputfile outputfile\n");
+#else
+ fprintf(stderr, "[inputfile]\n");
+#endif
+
+ fprintf(stderr, "Switches (names may be abbreviated):\n");
+#ifdef ENTROPY_OPT_SUPPORTED
+ fprintf(stderr, " -optimize Optimize Huffman table (smaller file, but slow compression)\n");
+#endif
+#ifdef C_PROGRESSIVE_SUPPORTED
+ fprintf(stderr, " -progressive Create progressive JPEG file\n");
+#endif
+ fprintf(stderr, "Switches for advanced users:\n");
+ fprintf(stderr, " -restart N Set restart interval in rows, or in blocks with B\n");
+ fprintf(stderr, " -maxmemory N Maximum memory to use (in kbytes)\n");
+ fprintf(stderr, " -outfile name Specify name for output file\n");
+ fprintf(stderr, " -verbose or -debug Emit debug output\n");
+ fprintf(stderr, "Switches for wizards:\n");
+#ifdef C_ARITH_CODING_SUPPORTED
+ fprintf(stderr, " -arithmetic Use arithmetic coding\n");
+#endif
+#ifdef C_MULTISCAN_FILES_SUPPORTED
+ fprintf(stderr, " -scans file Create multi-scan JPEG per script file\n");
+#endif
+ exit(EXIT_FAILURE);
+}
+
+
+LOCAL int
+parse_switches (j_compress_ptr cinfo, int argc, char **argv,
+ int last_file_arg_seen, boolean for_real)
+/* Parse optional switches.
+ * Returns argv[] index of first file-name argument (== argc if none).
+ * Any file names with indexes <= last_file_arg_seen are ignored;
+ * they have presumably been processed in a previous iteration.
+ * (Pass 0 for last_file_arg_seen on the first or only iteration.)
+ * for_real is FALSE on the first (dummy) pass; we may skip any expensive
+ * processing.
+ */
+{
+ int argn;
+ char * arg;
+ boolean simple_progressive;
+ char * scansarg = NULL; /* saves -scans parm if any */
+
+ /* Set up default JPEG parameters. */
+ simple_progressive = FALSE;
+ outfilename = NULL;
+ cinfo->err->trace_level = 0;
+
+ /* Scan command line options, adjust parameters */
+
+ for (argn = 1; argn < argc; argn++) {
+ arg = argv[argn];
+ if (*arg != '-') {
+ /* Not a switch, must be a file name argument */
+ if (argn <= last_file_arg_seen) {
+ outfilename = NULL; /* -outfile applies to just one input file */
+ continue; /* ignore this name if previously processed */
+ }
+ break; /* else done parsing switches */
+ }
+ arg++; /* advance past switch marker character */
+
+ if (keymatch(arg, "arithmetic", 1)) {
+ /* Use arithmetic coding. */
+#ifdef C_ARITH_CODING_SUPPORTED
+ cinfo->arith_code = TRUE;
+#else
+ fprintf(stderr, "%s: sorry, arithmetic coding not supported\n",
+ progname);
+ exit(EXIT_FAILURE);
+#endif
+
+ } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
+ /* Enable debug printouts. */
+ /* On first -d, print version identification */
+ static boolean printed_version = FALSE;
+
+ if (! printed_version) {
+ fprintf(stderr, "Independent JPEG Group's JPEGTRAN, version %s\n%s\n",
+ JVERSION, JCOPYRIGHT);
+ printed_version = TRUE;
+ }
+ cinfo->err->trace_level++;
+
+ } else if (keymatch(arg, "maxmemory", 3)) {
+ /* Maximum memory in Kb (or Mb with 'm'). */
+ long lval;
+ char ch = 'x';
+
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
+ usage();
+ if (ch == 'm' || ch == 'M')
+ lval *= 1000L;
+ cinfo->mem->max_memory_to_use = lval * 1000L;
+
+ } else if (keymatch(arg, "optimize", 1) || keymatch(arg, "optimise", 1)) {
+ /* Enable entropy parm optimization. */
+#ifdef ENTROPY_OPT_SUPPORTED
+ cinfo->optimize_coding = TRUE;
+#else
+ fprintf(stderr, "%s: sorry, entropy optimization was not compiled\n",
+ progname);
+ exit(EXIT_FAILURE);
+#endif
+
+ } else if (keymatch(arg, "outfile", 4)) {
+ /* Set output file name. */
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ outfilename = argv[argn]; /* save it away for later use */
+
+ } else if (keymatch(arg, "progressive", 1)) {
+ /* Select simple progressive mode. */
+#ifdef C_PROGRESSIVE_SUPPORTED
+ simple_progressive = TRUE;
+ /* We must postpone execution until num_components is known. */
+#else
+ fprintf(stderr, "%s: sorry, progressive output was not compiled\n",
+ progname);
+ exit(EXIT_FAILURE);
+#endif
+
+ } else if (keymatch(arg, "restart", 1)) {
+ /* Restart interval in MCU rows (or in MCUs with 'b'). */
+ long lval;
+ char ch = 'x';
+
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
+ usage();
+ if (lval < 0 || lval > 65535L)
+ usage();
+ if (ch == 'b' || ch == 'B') {
+ cinfo->restart_interval = (unsigned int) lval;
+ cinfo->restart_in_rows = 0; /* else prior '-restart n' overrides me */
+ } else {
+ cinfo->restart_in_rows = (int) lval;
+ /* restart_interval will be computed during startup */
+ }
+
+ } else if (keymatch(arg, "scans", 2)) {
+ /* Set scan script. */
+#ifdef C_MULTISCAN_FILES_SUPPORTED
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ scansarg = argv[argn];
+ /* We must postpone reading the file in case -progressive appears. */
+#else
+ fprintf(stderr, "%s: sorry, multi-scan output was not compiled\n",
+ progname);
+ exit(EXIT_FAILURE);
+#endif
+
+ } else {
+ usage(); /* bogus switch */
+ }
+ }
+
+ /* Post-switch-scanning cleanup */
+
+ if (for_real) {
+
+#ifdef C_PROGRESSIVE_SUPPORTED
+ if (simple_progressive) /* process -progressive; -scans can override */
+ jpeg_simple_progression(cinfo);
+#endif
+
+#ifdef C_MULTISCAN_FILES_SUPPORTED
+ if (scansarg != NULL) /* process -scans if it was present */
+ if (! read_scan_script(cinfo, scansarg))
+ usage();
+#endif
+ }
+
+ return argn; /* return index of next arg (file name) */
+}
+
+
+/*
+ * The main program.
+ */
+
+GLOBAL int
+main (int argc, char **argv)
+{
+ struct jpeg_decompress_struct srcinfo;
+ struct jpeg_compress_struct dstinfo;
+ struct jpeg_error_mgr jsrcerr, jdsterr;
+#ifdef PROGRESS_REPORT
+ struct cdjpeg_progress_mgr progress;
+#endif
+ jvirt_barray_ptr * coef_arrays;
+ int file_index;
+ FILE * input_file;
+ FILE * output_file;
+
+ /* On Mac, fetch a command line. */
+#ifdef USE_CCOMMAND
+ argc = ccommand(&argv);
+#endif
+
+ progname = argv[0];
+ if (progname == NULL || progname[0] == 0)
+ progname = "jpegtran"; /* in case C library doesn't provide it */
+
+ /* Initialize the JPEG decompression object with default error handling. */
+ srcinfo.err = jpeg_std_error(&jsrcerr);
+ jpeg_create_decompress(&srcinfo);
+ /* Initialize the JPEG compression object with default error handling. */
+ dstinfo.err = jpeg_std_error(&jdsterr);
+ jpeg_create_compress(&dstinfo);
+
+ /* Now safe to enable signal catcher.
+ * Note: we assume only the decompression object will have virtual arrays.
+ */
+#ifdef NEED_SIGNAL_CATCHER
+ enable_signal_catcher((j_common_ptr) &srcinfo);
+#endif
+
+ /* Scan command line to find file names.
+ * It is convenient to use just one switch-parsing routine, but the switch
+ * values read here are ignored; we will rescan the switches after opening
+ * the input file.
+ */
+
+ file_index = parse_switches(&dstinfo, argc, argv, 0, FALSE);
+ jsrcerr.trace_level = jdsterr.trace_level;
+
+#ifdef TWO_FILE_COMMANDLINE
+ /* Must have either -outfile switch or explicit output file name */
+ if (outfilename == NULL) {
+ if (file_index != argc-2) {
+ fprintf(stderr, "%s: must name one input and one output file\n",
+ progname);
+ usage();
+ }
+ outfilename = argv[file_index+1];
+ } else {
+ if (file_index != argc-1) {
+ fprintf(stderr, "%s: must name one input and one output file\n",
+ progname);
+ usage();
+ }
+ }
+#else
+ /* Unix style: expect zero or one file name */
+ if (file_index < argc-1) {
+ fprintf(stderr, "%s: only one input file\n", progname);
+ usage();
+ }
+#endif /* TWO_FILE_COMMANDLINE */
+
+ /* Open the input file. */
+ if (file_index < argc) {
+ if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
+ fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
+ exit(EXIT_FAILURE);
+ }
+ } else {
+ /* default input file is stdin */
+ input_file = read_stdin();
+ }
+
+ /* Open the output file. */
+ if (outfilename != NULL) {
+ if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
+ fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
+ exit(EXIT_FAILURE);
+ }
+ } else {
+ /* default output file is stdout */
+ output_file = write_stdout();
+ }
+
+#ifdef PROGRESS_REPORT
+ start_progress_monitor((j_common_ptr) &dstinfo, &progress);
+#endif
+
+ /* Specify data source for decompression */
+ jpeg_stdio_src(&srcinfo, input_file);
+
+ /* Read file header */
+ (void) jpeg_read_header(&srcinfo, TRUE);
+
+ /* Read source file as DCT coefficients */
+ coef_arrays = jpeg_read_coefficients(&srcinfo);
+
+ /* Initialize destination compression parameters from source values */
+ jpeg_copy_critical_parameters(&srcinfo, &dstinfo);
+
+ /* Adjust default compression parameters by re-parsing the options */
+ file_index = parse_switches(&dstinfo, argc, argv, 0, TRUE);
+
+ /* Specify data destination for compression */
+ jpeg_stdio_dest(&dstinfo, output_file);
+
+ /* Start compressor */
+ jpeg_write_coefficients(&dstinfo, coef_arrays);
+
+ /* ought to copy source comments here... */
+
+ /* Finish compression and release memory */
+ jpeg_finish_compress(&dstinfo);
+ jpeg_destroy_compress(&dstinfo);
+ (void) jpeg_finish_decompress(&srcinfo);
+ jpeg_destroy_decompress(&srcinfo);
+
+ /* Close files, if we opened them */
+ if (input_file != stdin)
+ fclose(input_file);
+ if (output_file != stdout)
+ fclose(output_file);
+
+#ifdef PROGRESS_REPORT
+ end_progress_monitor((j_common_ptr) &dstinfo);
+#endif
+
+ /* All done. */
+ exit(jsrcerr.num_warnings + jdsterr.num_warnings ?EXIT_WARNING:EXIT_SUCCESS);
+ return 0; /* suppress no-return-value warnings */
+}
diff --git a/code/jpeg-6/jquant1.c b/code/jpeg-6/jquant1.c
new file mode 100755
index 0000000..ab7e99c
--- /dev/null
+++ b/code/jpeg-6/jquant1.c
@@ -0,0 +1,856 @@
+/*
+ * jquant1.c
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains 1-pass color quantization (color mapping) routines.
+ * These routines provide mapping to a fixed color map using equally spaced
+ * color values. Optional Floyd-Steinberg or ordered dithering is available.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+#ifdef QUANT_1PASS_SUPPORTED
+
+
+/*
+ * The main purpose of 1-pass quantization is to provide a fast, if not very
+ * high quality, colormapped output capability. A 2-pass quantizer usually
+ * gives better visual quality; however, for quantized grayscale output this
+ * quantizer is perfectly adequate. Dithering is highly recommended with this
+ * quantizer, though you can turn it off if you really want to.
+ *
+ * In 1-pass quantization the colormap must be chosen in advance of seeing the
+ * image. We use a map consisting of all combinations of Ncolors[i] color
+ * values for the i'th component. The Ncolors[] values are chosen so that
+ * their product, the total number of colors, is no more than that requested.
+ * (In most cases, the product will be somewhat less.)
+ *
+ * Since the colormap is orthogonal, the representative value for each color
+ * component can be determined without considering the other components;
+ * then these indexes can be combined into a colormap index by a standard
+ * N-dimensional-array-subscript calculation. Most of the arithmetic involved
+ * can be precalculated and stored in the lookup table colorindex[].
+ * colorindex[i][j] maps pixel value j in component i to the nearest
+ * representative value (grid plane) for that component; this index is
+ * multiplied by the array stride for component i, so that the
+ * index of the colormap entry closest to a given pixel value is just
+ * sum( colorindex[component-number][pixel-component-value] )
+ * Aside from being fast, this scheme allows for variable spacing between
+ * representative values with no additional lookup cost.
+ *
+ * If gamma correction has been applied in color conversion, it might be wise
+ * to adjust the color grid spacing so that the representative colors are
+ * equidistant in linear space. At this writing, gamma correction is not
+ * implemented by jdcolor, so nothing is done here.
+ */
+
+
+/* Declarations for ordered dithering.
+ *
+ * We use a standard 16x16 ordered dither array. The basic concept of ordered
+ * dithering is described in many references, for instance Dale Schumacher's
+ * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
+ * In place of Schumacher's comparisons against a "threshold" value, we add a
+ * "dither" value to the input pixel and then round the result to the nearest
+ * output value. The dither value is equivalent to (0.5 - threshold) times
+ * the distance between output values. For ordered dithering, we assume that
+ * the output colors are equally spaced; if not, results will probably be
+ * worse, since the dither may be too much or too little at a given point.
+ *
+ * The normal calculation would be to form pixel value + dither, range-limit
+ * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
+ * We can skip the separate range-limiting step by extending the colorindex
+ * table in both directions.
+ */
+
+#define ODITHER_SIZE 16 /* dimension of dither matrix */
+/* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
+#define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
+#define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
+
+typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
+typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
+
+static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
+ /* Bayer's order-4 dither array. Generated by the code given in
+ * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
+ * The values in this array must range from 0 to ODITHER_CELLS-1.
+ */
+ { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
+ { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
+ { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
+ { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
+ { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
+ { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
+ { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
+ { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
+ { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
+ { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
+ { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
+ { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
+ { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
+ { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
+ { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
+ { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
+};
+
+
+/* Declarations for Floyd-Steinberg dithering.
+ *
+ * Errors are accumulated into the array fserrors[], at a resolution of
+ * 1/16th of a pixel count. The error at a given pixel is propagated
+ * to its not-yet-processed neighbors using the standard F-S fractions,
+ * ... (here) 7/16
+ * 3/16 5/16 1/16
+ * We work left-to-right on even rows, right-to-left on odd rows.
+ *
+ * We can get away with a single array (holding one row's worth of errors)
+ * by using it to store the current row's errors at pixel columns not yet
+ * processed, but the next row's errors at columns already processed. We
+ * need only a few extra variables to hold the errors immediately around the
+ * current column. (If we are lucky, those variables are in registers, but
+ * even if not, they're probably cheaper to access than array elements are.)
+ *
+ * The fserrors[] array is indexed [component#][position].
+ * We provide (#columns + 2) entries per component; the extra entry at each
+ * end saves us from special-casing the first and last pixels.
+ *
+ * Note: on a wide image, we might not have enough room in a PC's near data
+ * segment to hold the error array; so it is allocated with alloc_large.
+ */
+
+#if BITS_IN_JSAMPLE == 8
+typedef INT16 FSERROR; /* 16 bits should be enough */
+typedef int LOCFSERROR; /* use 'int' for calculation temps */
+#else
+typedef INT32 FSERROR; /* may need more than 16 bits */
+typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
+#endif
+
+typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
+
+
+/* Private subobject */
+
+#define MAX_Q_COMPS 4 /* max components I can handle */
+
+typedef struct {
+ struct jpeg_color_quantizer pub; /* public fields */
+
+ /* Initially allocated colormap is saved here */
+ JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
+ int sv_actual; /* number of entries in use */
+
+ JSAMPARRAY colorindex; /* Precomputed mapping for speed */
+ /* colorindex[i][j] = index of color closest to pixel value j in component i,
+ * premultiplied as described above. Since colormap indexes must fit into
+ * JSAMPLEs, the entries of this array will too.
+ */
+ boolean is_padded; /* is the colorindex padded for odither? */
+
+ int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
+
+ /* Variables for ordered dithering */
+ int row_index; /* cur row's vertical index in dither matrix */
+ ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
+
+ /* Variables for Floyd-Steinberg dithering */
+ FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
+ boolean on_odd_row; /* flag to remember which row we are on */
+} my_cquantizer;
+
+typedef my_cquantizer * my_cquantize_ptr;
+
+
+/*
+ * Policy-making subroutines for create_colormap and create_colorindex.
+ * These routines determine the colormap to be used. The rest of the module
+ * only assumes that the colormap is orthogonal.
+ *
+ * * select_ncolors decides how to divvy up the available colors
+ * among the components.
+ * * output_value defines the set of representative values for a component.
+ * * largest_input_value defines the mapping from input values to
+ * representative values for a component.
+ * Note that the latter two routines may impose different policies for
+ * different components, though this is not currently done.
+ */
+
+
+LOCAL int
+select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
+/* Determine allocation of desired colors to components, */
+/* and fill in Ncolors[] array to indicate choice. */
+/* Return value is total number of colors (product of Ncolors[] values). */
+{
+ int nc = cinfo->out_color_components; /* number of color components */
+ int max_colors = cinfo->desired_number_of_colors;
+ int total_colors, iroot, i, j;
+ boolean changed;
+ long temp;
+ static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
+
+ /* We can allocate at least the nc'th root of max_colors per component. */
+ /* Compute floor(nc'th root of max_colors). */
+ iroot = 1;
+ do {
+ iroot++;
+ temp = iroot; /* set temp = iroot ** nc */
+ for (i = 1; i < nc; i++)
+ temp *= iroot;
+ } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
+ iroot--; /* now iroot = floor(root) */
+
+ /* Must have at least 2 color values per component */
+ if (iroot < 2)
+ ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
+
+ /* Initialize to iroot color values for each component */
+ total_colors = 1;
+ for (i = 0; i < nc; i++) {
+ Ncolors[i] = iroot;
+ total_colors *= iroot;
+ }
+ /* We may be able to increment the count for one or more components without
+ * exceeding max_colors, though we know not all can be incremented.
+ * Sometimes, the first component can be incremented more than once!
+ * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
+ * In RGB colorspace, try to increment G first, then R, then B.
+ */
+ do {
+ changed = FALSE;
+ for (i = 0; i < nc; i++) {
+ j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
+ /* calculate new total_colors if Ncolors[j] is incremented */
+ temp = total_colors / Ncolors[j];
+ temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
+ if (temp > (long) max_colors)
+ break; /* won't fit, done with this pass */
+ Ncolors[j]++; /* OK, apply the increment */
+ total_colors = (int) temp;
+ changed = TRUE;
+ }
+ } while (changed);
+
+ return total_colors;
+}
+
+
+LOCAL int
+output_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
+/* Return j'th output value, where j will range from 0 to maxj */
+/* The output values must fall in 0..MAXJSAMPLE in increasing order */
+{
+ /* We always provide values 0 and MAXJSAMPLE for each component;
+ * any additional values are equally spaced between these limits.
+ * (Forcing the upper and lower values to the limits ensures that
+ * dithering can't produce a color outside the selected gamut.)
+ */
+ return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
+}
+
+
+LOCAL int
+largest_input_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
+/* Return largest input value that should map to j'th output value */
+/* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
+{
+ /* Breakpoints are halfway between values returned by output_value */
+ return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
+}
+
+
+/*
+ * Create the colormap.
+ */
+
+LOCAL void
+create_colormap (j_decompress_ptr cinfo)
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ JSAMPARRAY colormap; /* Created colormap */
+ int total_colors; /* Number of distinct output colors */
+ int i,j,k, nci, blksize, blkdist, ptr, val;
+
+ /* Select number of colors for each component */
+ total_colors = select_ncolors(cinfo, cquantize->Ncolors);
+
+ /* Report selected color counts */
+ if (cinfo->out_color_components == 3)
+ TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
+ total_colors, cquantize->Ncolors[0],
+ cquantize->Ncolors[1], cquantize->Ncolors[2]);
+ else
+ TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
+
+ /* Allocate and fill in the colormap. */
+ /* The colors are ordered in the map in standard row-major order, */
+ /* i.e. rightmost (highest-indexed) color changes most rapidly. */
+
+ colormap = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
+
+ /* blksize is number of adjacent repeated entries for a component */
+ /* blkdist is distance between groups of identical entries for a component */
+ blkdist = total_colors;
+
+ for (i = 0; i < cinfo->out_color_components; i++) {
+ /* fill in colormap entries for i'th color component */
+ nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
+ blksize = blkdist / nci;
+ for (j = 0; j < nci; j++) {
+ /* Compute j'th output value (out of nci) for component */
+ val = output_value(cinfo, i, j, nci-1);
+ /* Fill in all colormap entries that have this value of this component */
+ for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
+ /* fill in blksize entries beginning at ptr */
+ for (k = 0; k < blksize; k++)
+ colormap[i][ptr+k] = (JSAMPLE) val;
+ }
+ }
+ blkdist = blksize; /* blksize of this color is blkdist of next */
+ }
+
+ /* Save the colormap in private storage,
+ * where it will survive color quantization mode changes.
+ */
+ cquantize->sv_colormap = colormap;
+ cquantize->sv_actual = total_colors;
+}
+
+
+/*
+ * Create the color index table.
+ */
+
+LOCAL void
+create_colorindex (j_decompress_ptr cinfo)
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ JSAMPROW indexptr;
+ int i,j,k, nci, blksize, val, pad;
+
+ /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
+ * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
+ * This is not necessary in the other dithering modes. However, we
+ * flag whether it was done in case user changes dithering mode.
+ */
+ if (cinfo->dither_mode == JDITHER_ORDERED) {
+ pad = MAXJSAMPLE*2;
+ cquantize->is_padded = TRUE;
+ } else {
+ pad = 0;
+ cquantize->is_padded = FALSE;
+ }
+
+ cquantize->colorindex = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) (MAXJSAMPLE+1 + pad),
+ (JDIMENSION) cinfo->out_color_components);
+
+ /* blksize is number of adjacent repeated entries for a component */
+ blksize = cquantize->sv_actual;
+
+ for (i = 0; i < cinfo->out_color_components; i++) {
+ /* fill in colorindex entries for i'th color component */
+ nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
+ blksize = blksize / nci;
+
+ /* adjust colorindex pointers to provide padding at negative indexes. */
+ if (pad)
+ cquantize->colorindex[i] += MAXJSAMPLE;
+
+ /* in loop, val = index of current output value, */
+ /* and k = largest j that maps to current val */
+ indexptr = cquantize->colorindex[i];
+ val = 0;
+ k = largest_input_value(cinfo, i, 0, nci-1);
+ for (j = 0; j <= MAXJSAMPLE; j++) {
+ while (j > k) /* advance val if past boundary */
+ k = largest_input_value(cinfo, i, ++val, nci-1);
+ /* premultiply so that no multiplication needed in main processing */
+ indexptr[j] = (JSAMPLE) (val * blksize);
+ }
+ /* Pad at both ends if necessary */
+ if (pad)
+ for (j = 1; j <= MAXJSAMPLE; j++) {
+ indexptr[-j] = indexptr[0];
+ indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
+ }
+ }
+}
+
+
+/*
+ * Create an ordered-dither array for a component having ncolors
+ * distinct output values.
+ */
+
+LOCAL ODITHER_MATRIX_PTR
+make_odither_array (j_decompress_ptr cinfo, int ncolors)
+{
+ ODITHER_MATRIX_PTR odither;
+ int j,k;
+ INT32 num,den;
+
+ odither = (ODITHER_MATRIX_PTR)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(ODITHER_MATRIX));
+ /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
+ * Hence the dither value for the matrix cell with fill order f
+ * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
+ * On 16-bit-int machine, be careful to avoid overflow.
+ */
+ den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
+ for (j = 0; j < ODITHER_SIZE; j++) {
+ for (k = 0; k < ODITHER_SIZE; k++) {
+ num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
+ * MAXJSAMPLE;
+ /* Ensure round towards zero despite C's lack of consistency
+ * about rounding negative values in integer division...
+ */
+ odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
+ }
+ }
+ return odither;
+}
+
+
+/*
+ * Create the ordered-dither tables.
+ * Components having the same number of representative colors may
+ * share a dither table.
+ */
+
+LOCAL void
+create_odither_tables (j_decompress_ptr cinfo)
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ ODITHER_MATRIX_PTR odither;
+ int i, j, nci;
+
+ for (i = 0; i < cinfo->out_color_components; i++) {
+ nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
+ odither = NULL; /* search for matching prior component */
+ for (j = 0; j < i; j++) {
+ if (nci == cquantize->Ncolors[j]) {
+ odither = cquantize->odither[j];
+ break;
+ }
+ }
+ if (odither == NULL) /* need a new table? */
+ odither = make_odither_array(cinfo, nci);
+ cquantize->odither[i] = odither;
+ }
+}
+
+
+/*
+ * Map some rows of pixels to the output colormapped representation.
+ */
+
+METHODDEF void
+color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
+ JSAMPARRAY output_buf, int num_rows)
+/* General case, no dithering */
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ JSAMPARRAY colorindex = cquantize->colorindex;
+ register int pixcode, ci;
+ register JSAMPROW ptrin, ptrout;
+ int row;
+ JDIMENSION col;
+ JDIMENSION width = cinfo->output_width;
+ register int nc = cinfo->out_color_components;
+
+ for (row = 0; row < num_rows; row++) {
+ ptrin = input_buf[row];
+ ptrout = output_buf[row];
+ for (col = width; col > 0; col--) {
+ pixcode = 0;
+ for (ci = 0; ci < nc; ci++) {
+ pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
+ }
+ *ptrout++ = (JSAMPLE) pixcode;
+ }
+ }
+}
+
+
+METHODDEF void
+color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
+ JSAMPARRAY output_buf, int num_rows)
+/* Fast path for out_color_components==3, no dithering */
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ register int pixcode;
+ register JSAMPROW ptrin, ptrout;
+ JSAMPROW colorindex0 = cquantize->colorindex[0];
+ JSAMPROW colorindex1 = cquantize->colorindex[1];
+ JSAMPROW colorindex2 = cquantize->colorindex[2];
+ int row;
+ JDIMENSION col;
+ JDIMENSION width = cinfo->output_width;
+
+ for (row = 0; row < num_rows; row++) {
+ ptrin = input_buf[row];
+ ptrout = output_buf[row];
+ for (col = width; col > 0; col--) {
+ pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
+ pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
+ pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
+ *ptrout++ = (JSAMPLE) pixcode;
+ }
+ }
+}
+
+
+METHODDEF void
+quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
+ JSAMPARRAY output_buf, int num_rows)
+/* General case, with ordered dithering */
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ register JSAMPROW input_ptr;
+ register JSAMPROW output_ptr;
+ JSAMPROW colorindex_ci;
+ int * dither; /* points to active row of dither matrix */
+ int row_index, col_index; /* current indexes into dither matrix */
+ int nc = cinfo->out_color_components;
+ int ci;
+ int row;
+ JDIMENSION col;
+ JDIMENSION width = cinfo->output_width;
+
+ for (row = 0; row < num_rows; row++) {
+ /* Initialize output values to 0 so can process components separately */
+ jzero_far((void FAR *) output_buf[row],
+ (size_t) (width * SIZEOF(JSAMPLE)));
+ row_index = cquantize->row_index;
+ for (ci = 0; ci < nc; ci++) {
+ input_ptr = input_buf[row] + ci;
+ output_ptr = output_buf[row];
+ colorindex_ci = cquantize->colorindex[ci];
+ dither = cquantize->odither[ci][row_index];
+ col_index = 0;
+
+ for (col = width; col > 0; col--) {
+ /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
+ * select output value, accumulate into output code for this pixel.
+ * Range-limiting need not be done explicitly, as we have extended
+ * the colorindex table to produce the right answers for out-of-range
+ * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
+ * required amount of padding.
+ */
+ *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
+ input_ptr += nc;
+ output_ptr++;
+ col_index = (col_index + 1) & ODITHER_MASK;
+ }
+ }
+ /* Advance row index for next row */
+ row_index = (row_index + 1) & ODITHER_MASK;
+ cquantize->row_index = row_index;
+ }
+}
+
+
+METHODDEF void
+quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
+ JSAMPARRAY output_buf, int num_rows)
+/* Fast path for out_color_components==3, with ordered dithering */
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ register int pixcode;
+ register JSAMPROW input_ptr;
+ register JSAMPROW output_ptr;
+ JSAMPROW colorindex0 = cquantize->colorindex[0];
+ JSAMPROW colorindex1 = cquantize->colorindex[1];
+ JSAMPROW colorindex2 = cquantize->colorindex[2];
+ int * dither0; /* points to active row of dither matrix */
+ int * dither1;
+ int * dither2;
+ int row_index, col_index; /* current indexes into dither matrix */
+ int row;
+ JDIMENSION col;
+ JDIMENSION width = cinfo->output_width;
+
+ for (row = 0; row < num_rows; row++) {
+ row_index = cquantize->row_index;
+ input_ptr = input_buf[row];
+ output_ptr = output_buf[row];
+ dither0 = cquantize->odither[0][row_index];
+ dither1 = cquantize->odither[1][row_index];
+ dither2 = cquantize->odither[2][row_index];
+ col_index = 0;
+
+ for (col = width; col > 0; col--) {
+ pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
+ dither0[col_index]]);
+ pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
+ dither1[col_index]]);
+ pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
+ dither2[col_index]]);
+ *output_ptr++ = (JSAMPLE) pixcode;
+ col_index = (col_index + 1) & ODITHER_MASK;
+ }
+ row_index = (row_index + 1) & ODITHER_MASK;
+ cquantize->row_index = row_index;
+ }
+}
+
+
+METHODDEF void
+quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
+ JSAMPARRAY output_buf, int num_rows)
+/* General case, with Floyd-Steinberg dithering */
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ register LOCFSERROR cur; /* current error or pixel value */
+ LOCFSERROR belowerr; /* error for pixel below cur */
+ LOCFSERROR bpreverr; /* error for below/prev col */
+ LOCFSERROR bnexterr; /* error for below/next col */
+ LOCFSERROR delta;
+ register FSERRPTR errorptr; /* => fserrors[] at column before current */
+ register JSAMPROW input_ptr;
+ register JSAMPROW output_ptr;
+ JSAMPROW colorindex_ci;
+ JSAMPROW colormap_ci;
+ int pixcode;
+ int nc = cinfo->out_color_components;
+ int dir; /* 1 for left-to-right, -1 for right-to-left */
+ int dirnc; /* dir * nc */
+ int ci;
+ int row;
+ JDIMENSION col;
+ JDIMENSION width = cinfo->output_width;
+ JSAMPLE *range_limit = cinfo->sample_range_limit;
+ SHIFT_TEMPS
+
+ for (row = 0; row < num_rows; row++) {
+ /* Initialize output values to 0 so can process components separately */
+ jzero_far((void FAR *) output_buf[row],
+ (size_t) (width * SIZEOF(JSAMPLE)));
+ for (ci = 0; ci < nc; ci++) {
+ input_ptr = input_buf[row] + ci;
+ output_ptr = output_buf[row];
+ if (cquantize->on_odd_row) {
+ /* work right to left in this row */
+ input_ptr += (width-1) * nc; /* so point to rightmost pixel */
+ output_ptr += width-1;
+ dir = -1;
+ dirnc = -nc;
+ errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
+ } else {
+ /* work left to right in this row */
+ dir = 1;
+ dirnc = nc;
+ errorptr = cquantize->fserrors[ci]; /* => entry before first column */
+ }
+ colorindex_ci = cquantize->colorindex[ci];
+ colormap_ci = cquantize->sv_colormap[ci];
+ /* Preset error values: no error propagated to first pixel from left */
+ cur = 0;
+ /* and no error propagated to row below yet */
+ belowerr = bpreverr = 0;
+
+ for (col = width; col > 0; col--) {
+ /* cur holds the error propagated from the previous pixel on the
+ * current line. Add the error propagated from the previous line
+ * to form the complete error correction term for this pixel, and
+ * round the error term (which is expressed * 16) to an integer.
+ * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
+ * for either sign of the error value.
+ * Note: errorptr points to *previous* column's array entry.
+ */
+ cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
+ /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
+ * The maximum error is +- MAXJSAMPLE; this sets the required size
+ * of the range_limit array.
+ */
+ cur += GETJSAMPLE(*input_ptr);
+ cur = GETJSAMPLE(range_limit[cur]);
+ /* Select output value, accumulate into output code for this pixel */
+ pixcode = GETJSAMPLE(colorindex_ci[cur]);
+ *output_ptr += (JSAMPLE) pixcode;
+ /* Compute actual representation error at this pixel */
+ /* Note: we can do this even though we don't have the final */
+ /* pixel code, because the colormap is orthogonal. */
+ cur -= GETJSAMPLE(colormap_ci[pixcode]);
+ /* Compute error fractions to be propagated to adjacent pixels.
+ * Add these into the running sums, and simultaneously shift the
+ * next-line error sums left by 1 column.
+ */
+ bnexterr = cur;
+ delta = cur * 2;
+ cur += delta; /* form error * 3 */
+ errorptr[0] = (FSERROR) (bpreverr + cur);
+ cur += delta; /* form error * 5 */
+ bpreverr = belowerr + cur;
+ belowerr = bnexterr;
+ cur += delta; /* form error * 7 */
+ /* At this point cur contains the 7/16 error value to be propagated
+ * to the next pixel on the current line, and all the errors for the
+ * next line have been shifted over. We are therefore ready to move on.
+ */
+ input_ptr += dirnc; /* advance input ptr to next column */
+ output_ptr += dir; /* advance output ptr to next column */
+ errorptr += dir; /* advance errorptr to current column */
+ }
+ /* Post-loop cleanup: we must unload the final error value into the
+ * final fserrors[] entry. Note we need not unload belowerr because
+ * it is for the dummy column before or after the actual array.
+ */
+ errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
+ }
+ cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
+ }
+}
+
+
+/*
+ * Allocate workspace for Floyd-Steinberg errors.
+ */
+
+LOCAL void
+alloc_fs_workspace (j_decompress_ptr cinfo)
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ size_t arraysize;
+ int i;
+
+ arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
+ for (i = 0; i < cinfo->out_color_components; i++) {
+ cquantize->fserrors[i] = (FSERRPTR)
+ (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
+ }
+}
+
+
+/*
+ * Initialize for one-pass color quantization.
+ */
+
+METHODDEF void
+start_pass_1_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ size_t arraysize;
+ int i;
+
+ /* Install my colormap. */
+ cinfo->colormap = cquantize->sv_colormap;
+ cinfo->actual_number_of_colors = cquantize->sv_actual;
+
+ /* Initialize for desired dithering mode. */
+ switch (cinfo->dither_mode) {
+ case JDITHER_NONE:
+ if (cinfo->out_color_components == 3)
+ cquantize->pub.color_quantize = color_quantize3;
+ else
+ cquantize->pub.color_quantize = color_quantize;
+ break;
+ case JDITHER_ORDERED:
+ if (cinfo->out_color_components == 3)
+ cquantize->pub.color_quantize = quantize3_ord_dither;
+ else
+ cquantize->pub.color_quantize = quantize_ord_dither;
+ cquantize->row_index = 0; /* initialize state for ordered dither */
+ /* If user changed to ordered dither from another mode,
+ * we must recreate the color index table with padding.
+ * This will cost extra space, but probably isn't very likely.
+ */
+ if (! cquantize->is_padded)
+ create_colorindex(cinfo);
+ /* Create ordered-dither tables if we didn't already. */
+ if (cquantize->odither[0] == NULL)
+ create_odither_tables(cinfo);
+ break;
+ case JDITHER_FS:
+ cquantize->pub.color_quantize = quantize_fs_dither;
+ cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
+ /* Allocate Floyd-Steinberg workspace if didn't already. */
+ if (cquantize->fserrors[0] == NULL)
+ alloc_fs_workspace(cinfo);
+ /* Initialize the propagated errors to zero. */
+ arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
+ for (i = 0; i < cinfo->out_color_components; i++)
+ jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
+ break;
+ default:
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+ break;
+ }
+}
+
+
+/*
+ * Finish up at the end of the pass.
+ */
+
+METHODDEF void
+finish_pass_1_quant (j_decompress_ptr cinfo)
+{
+ /* no work in 1-pass case */
+}
+
+
+/*
+ * Switch to a new external colormap between output passes.
+ * Shouldn't get to this module!
+ */
+
+METHODDEF void
+new_color_map_1_quant (j_decompress_ptr cinfo)
+{
+ ERREXIT(cinfo, JERR_MODE_CHANGE);
+}
+
+
+/*
+ * Module initialization routine for 1-pass color quantization.
+ */
+
+GLOBAL void
+jinit_1pass_quantizer (j_decompress_ptr cinfo)
+{
+ my_cquantize_ptr cquantize;
+
+ cquantize = (my_cquantize_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_cquantizer));
+ cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
+ cquantize->pub.start_pass = start_pass_1_quant;
+ cquantize->pub.finish_pass = finish_pass_1_quant;
+ cquantize->pub.new_color_map = new_color_map_1_quant;
+ cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
+ cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
+
+ /* Make sure my internal arrays won't overflow */
+ if (cinfo->out_color_components > MAX_Q_COMPS)
+ ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
+ /* Make sure colormap indexes can be represented by JSAMPLEs */
+ if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
+ ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
+
+ /* Create the colormap and color index table. */
+ create_colormap(cinfo);
+ create_colorindex(cinfo);
+
+ /* Allocate Floyd-Steinberg workspace now if requested.
+ * We do this now since it is FAR storage and may affect the memory
+ * manager's space calculations. If the user changes to FS dither
+ * mode in a later pass, we will allocate the space then, and will
+ * possibly overrun the max_memory_to_use setting.
+ */
+ if (cinfo->dither_mode == JDITHER_FS)
+ alloc_fs_workspace(cinfo);
+}
+
+#endif /* QUANT_1PASS_SUPPORTED */
diff --git a/code/jpeg-6/jquant2.c b/code/jpeg-6/jquant2.c
new file mode 100755
index 0000000..c944e4b
--- /dev/null
+++ b/code/jpeg-6/jquant2.c
@@ -0,0 +1,1310 @@
+/*
+ * jquant2.c
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains 2-pass color quantization (color mapping) routines.
+ * These routines provide selection of a custom color map for an image,
+ * followed by mapping of the image to that color map, with optional
+ * Floyd-Steinberg dithering.
+ * It is also possible to use just the second pass to map to an arbitrary
+ * externally-given color map.
+ *
+ * Note: ordered dithering is not supported, since there isn't any fast
+ * way to compute intercolor distances; it's unclear that ordered dither's
+ * fundamental assumptions even hold with an irregularly spaced color map.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+#ifdef QUANT_2PASS_SUPPORTED
+
+
+/*
+ * This module implements the well-known Heckbert paradigm for color
+ * quantization. Most of the ideas used here can be traced back to
+ * Heckbert's seminal paper
+ * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
+ * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
+ *
+ * In the first pass over the image, we accumulate a histogram showing the
+ * usage count of each possible color. To keep the histogram to a reasonable
+ * size, we reduce the precision of the input; typical practice is to retain
+ * 5 or 6 bits per color, so that 8 or 4 different input values are counted
+ * in the same histogram cell.
+ *
+ * Next, the color-selection step begins with a box representing the whole
+ * color space, and repeatedly splits the "largest" remaining box until we
+ * have as many boxes as desired colors. Then the mean color in each
+ * remaining box becomes one of the possible output colors.
+ *
+ * The second pass over the image maps each input pixel to the closest output
+ * color (optionally after applying a Floyd-Steinberg dithering correction).
+ * This mapping is logically trivial, but making it go fast enough requires
+ * considerable care.
+ *
+ * Heckbert-style quantizers vary a good deal in their policies for choosing
+ * the "largest" box and deciding where to cut it. The particular policies
+ * used here have proved out well in experimental comparisons, but better ones
+ * may yet be found.
+ *
+ * In earlier versions of the IJG code, this module quantized in YCbCr color
+ * space, processing the raw upsampled data without a color conversion step.
+ * This allowed the color conversion math to be done only once per colormap
+ * entry, not once per pixel. However, that optimization precluded other
+ * useful optimizations (such as merging color conversion with upsampling)
+ * and it also interfered with desired capabilities such as quantizing to an
+ * externally-supplied colormap. We have therefore abandoned that approach.
+ * The present code works in the post-conversion color space, typically RGB.
+ *
+ * To improve the visual quality of the results, we actually work in scaled
+ * RGB space, giving G distances more weight than R, and R in turn more than
+ * B. To do everything in integer math, we must use integer scale factors.
+ * The 2/3/1 scale factors used here correspond loosely to the relative
+ * weights of the colors in the NTSC grayscale equation.
+ * If you want to use this code to quantize a non-RGB color space, you'll
+ * probably need to change these scale factors.
+ */
+
+#define R_SCALE 2 /* scale R distances by this much */
+#define G_SCALE 3 /* scale G distances by this much */
+#define B_SCALE 1 /* and B by this much */
+
+/* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
+ * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
+ * and B,G,R orders. If you define some other weird order in jmorecfg.h,
+ * you'll get compile errors until you extend this logic. In that case
+ * you'll probably want to tweak the histogram sizes too.
+ */
+
+#if RGB_RED == 0
+#define C0_SCALE R_SCALE
+#endif
+#if RGB_BLUE == 0
+#define C0_SCALE B_SCALE
+#endif
+#if RGB_GREEN == 1
+#define C1_SCALE G_SCALE
+#endif
+#if RGB_RED == 2
+#define C2_SCALE R_SCALE
+#endif
+#if RGB_BLUE == 2
+#define C2_SCALE B_SCALE
+#endif
+
+
+/*
+ * First we have the histogram data structure and routines for creating it.
+ *
+ * The number of bits of precision can be adjusted by changing these symbols.
+ * We recommend keeping 6 bits for G and 5 each for R and B.
+ * If you have plenty of memory and cycles, 6 bits all around gives marginally
+ * better results; if you are short of memory, 5 bits all around will save
+ * some space but degrade the results.
+ * To maintain a fully accurate histogram, we'd need to allocate a "long"
+ * (preferably unsigned long) for each cell. In practice this is overkill;
+ * we can get by with 16 bits per cell. Few of the cell counts will overflow,
+ * and clamping those that do overflow to the maximum value will give close-
+ * enough results. This reduces the recommended histogram size from 256Kb
+ * to 128Kb, which is a useful savings on PC-class machines.
+ * (In the second pass the histogram space is re-used for pixel mapping data;
+ * in that capacity, each cell must be able to store zero to the number of
+ * desired colors. 16 bits/cell is plenty for that too.)
+ * Since the JPEG code is intended to run in small memory model on 80x86
+ * machines, we can't just allocate the histogram in one chunk. Instead
+ * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
+ * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
+ * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
+ * on 80x86 machines, the pointer row is in near memory but the actual
+ * arrays are in far memory (same arrangement as we use for image arrays).
+ */
+
+#define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
+
+/* These will do the right thing for either R,G,B or B,G,R color order,
+ * but you may not like the results for other color orders.
+ */
+#define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
+#define HIST_C1_BITS 6 /* bits of precision in G histogram */
+#define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
+
+/* Number of elements along histogram axes. */
+#define HIST_C0_ELEMS (1<<HIST_C0_BITS)
+#define HIST_C1_ELEMS (1<<HIST_C1_BITS)
+#define HIST_C2_ELEMS (1<<HIST_C2_BITS)
+
+/* These are the amounts to shift an input value to get a histogram index. */
+#define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
+#define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
+#define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
+
+
+typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
+
+typedef histcell FAR * histptr; /* for pointers to histogram cells */
+
+typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
+typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
+typedef hist2d * hist3d; /* type for top-level pointer */
+
+
+/* Declarations for Floyd-Steinberg dithering.
+ *
+ * Errors are accumulated into the array fserrors[], at a resolution of
+ * 1/16th of a pixel count. The error at a given pixel is propagated
+ * to its not-yet-processed neighbors using the standard F-S fractions,
+ * ... (here) 7/16
+ * 3/16 5/16 1/16
+ * We work left-to-right on even rows, right-to-left on odd rows.
+ *
+ * We can get away with a single array (holding one row's worth of errors)
+ * by using it to store the current row's errors at pixel columns not yet
+ * processed, but the next row's errors at columns already processed. We
+ * need only a few extra variables to hold the errors immediately around the
+ * current column. (If we are lucky, those variables are in registers, but
+ * even if not, they're probably cheaper to access than array elements are.)
+ *
+ * The fserrors[] array has (#columns + 2) entries; the extra entry at
+ * each end saves us from special-casing the first and last pixels.
+ * Each entry is three values long, one value for each color component.
+ *
+ * Note: on a wide image, we might not have enough room in a PC's near data
+ * segment to hold the error array; so it is allocated with alloc_large.
+ */
+
+#if BITS_IN_JSAMPLE == 8
+typedef INT16 FSERROR; /* 16 bits should be enough */
+typedef int LOCFSERROR; /* use 'int' for calculation temps */
+#else
+typedef INT32 FSERROR; /* may need more than 16 bits */
+typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
+#endif
+
+typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
+
+
+/* Private subobject */
+
+typedef struct {
+ struct jpeg_color_quantizer pub; /* public fields */
+
+ /* Space for the eventually created colormap is stashed here */
+ JSAMPARRAY sv_colormap; /* colormap allocated at init time */
+ int desired; /* desired # of colors = size of colormap */
+
+ /* Variables for accumulating image statistics */
+ hist3d histogram; /* pointer to the histogram */
+
+ boolean needs_zeroed; /* TRUE if next pass must zero histogram */
+
+ /* Variables for Floyd-Steinberg dithering */
+ FSERRPTR fserrors; /* accumulated errors */
+ boolean on_odd_row; /* flag to remember which row we are on */
+ int * error_limiter; /* table for clamping the applied error */
+} my_cquantizer;
+
+typedef my_cquantizer * my_cquantize_ptr;
+
+
+/*
+ * Prescan some rows of pixels.
+ * In this module the prescan simply updates the histogram, which has been
+ * initialized to zeroes by start_pass.
+ * An output_buf parameter is required by the method signature, but no data
+ * is actually output (in fact the buffer controller is probably passing a
+ * NULL pointer).
+ */
+
+METHODDEF void
+prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
+ JSAMPARRAY output_buf, int num_rows)
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ register JSAMPROW ptr;
+ register histptr histp;
+ register hist3d histogram = cquantize->histogram;
+ int row;
+ JDIMENSION col;
+ JDIMENSION width = cinfo->output_width;
+
+ for (row = 0; row < num_rows; row++) {
+ ptr = input_buf[row];
+ for (col = width; col > 0; col--) {
+ /* get pixel value and index into the histogram */
+ histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
+ [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
+ [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
+ /* increment, check for overflow and undo increment if so. */
+ if (++(*histp) <= 0)
+ (*histp)--;
+ ptr += 3;
+ }
+ }
+}
+
+
+/*
+ * Next we have the really interesting routines: selection of a colormap
+ * given the completed histogram.
+ * These routines work with a list of "boxes", each representing a rectangular
+ * subset of the input color space (to histogram precision).
+ */
+
+typedef struct {
+ /* The bounds of the box (inclusive); expressed as histogram indexes */
+ int c0min, c0max;
+ int c1min, c1max;
+ int c2min, c2max;
+ /* The volume (actually 2-norm) of the box */
+ INT32 volume;
+ /* The number of nonzero histogram cells within this box */
+ long colorcount;
+} box;
+
+typedef box * boxptr;
+
+
+LOCAL boxptr
+find_biggest_color_pop (boxptr boxlist, int numboxes)
+/* Find the splittable box with the largest color population */
+/* Returns NULL if no splittable boxes remain */
+{
+ register boxptr boxp;
+ register int i;
+ register long maxc = 0;
+ boxptr which = NULL;
+
+ for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
+ if (boxp->colorcount > maxc && boxp->volume > 0) {
+ which = boxp;
+ maxc = boxp->colorcount;
+ }
+ }
+ return which;
+}
+
+
+LOCAL boxptr
+find_biggest_volume (boxptr boxlist, int numboxes)
+/* Find the splittable box with the largest (scaled) volume */
+/* Returns NULL if no splittable boxes remain */
+{
+ register boxptr boxp;
+ register int i;
+ register INT32 maxv = 0;
+ boxptr which = NULL;
+
+ for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
+ if (boxp->volume > maxv) {
+ which = boxp;
+ maxv = boxp->volume;
+ }
+ }
+ return which;
+}
+
+
+LOCAL void
+update_box (j_decompress_ptr cinfo, boxptr boxp)
+/* Shrink the min/max bounds of a box to enclose only nonzero elements, */
+/* and recompute its volume and population */
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ hist3d histogram = cquantize->histogram;
+ histptr histp;
+ int c0,c1,c2;
+ int c0min,c0max,c1min,c1max,c2min,c2max;
+ INT32 dist0,dist1,dist2;
+ long ccount;
+
+ c0min = boxp->c0min; c0max = boxp->c0max;
+ c1min = boxp->c1min; c1max = boxp->c1max;
+ c2min = boxp->c2min; c2max = boxp->c2max;
+
+ if (c0max > c0min)
+ for (c0 = c0min; c0 <= c0max; c0++)
+ for (c1 = c1min; c1 <= c1max; c1++) {
+ histp = & histogram[c0][c1][c2min];
+ for (c2 = c2min; c2 <= c2max; c2++)
+ if (*histp++ != 0) {
+ boxp->c0min = c0min = c0;
+ goto have_c0min;
+ }
+ }
+ have_c0min:
+ if (c0max > c0min)
+ for (c0 = c0max; c0 >= c0min; c0--)
+ for (c1 = c1min; c1 <= c1max; c1++) {
+ histp = & histogram[c0][c1][c2min];
+ for (c2 = c2min; c2 <= c2max; c2++)
+ if (*histp++ != 0) {
+ boxp->c0max = c0max = c0;
+ goto have_c0max;
+ }
+ }
+ have_c0max:
+ if (c1max > c1min)
+ for (c1 = c1min; c1 <= c1max; c1++)
+ for (c0 = c0min; c0 <= c0max; c0++) {
+ histp = & histogram[c0][c1][c2min];
+ for (c2 = c2min; c2 <= c2max; c2++)
+ if (*histp++ != 0) {
+ boxp->c1min = c1min = c1;
+ goto have_c1min;
+ }
+ }
+ have_c1min:
+ if (c1max > c1min)
+ for (c1 = c1max; c1 >= c1min; c1--)
+ for (c0 = c0min; c0 <= c0max; c0++) {
+ histp = & histogram[c0][c1][c2min];
+ for (c2 = c2min; c2 <= c2max; c2++)
+ if (*histp++ != 0) {
+ boxp->c1max = c1max = c1;
+ goto have_c1max;
+ }
+ }
+ have_c1max:
+ if (c2max > c2min)
+ for (c2 = c2min; c2 <= c2max; c2++)
+ for (c0 = c0min; c0 <= c0max; c0++) {
+ histp = & histogram[c0][c1min][c2];
+ for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
+ if (*histp != 0) {
+ boxp->c2min = c2min = c2;
+ goto have_c2min;
+ }
+ }
+ have_c2min:
+ if (c2max > c2min)
+ for (c2 = c2max; c2 >= c2min; c2--)
+ for (c0 = c0min; c0 <= c0max; c0++) {
+ histp = & histogram[c0][c1min][c2];
+ for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
+ if (*histp != 0) {
+ boxp->c2max = c2max = c2;
+ goto have_c2max;
+ }
+ }
+ have_c2max:
+
+ /* Update box volume.
+ * We use 2-norm rather than real volume here; this biases the method
+ * against making long narrow boxes, and it has the side benefit that
+ * a box is splittable iff norm > 0.
+ * Since the differences are expressed in histogram-cell units,
+ * we have to shift back to JSAMPLE units to get consistent distances;
+ * after which, we scale according to the selected distance scale factors.
+ */
+ dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
+ dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
+ dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
+ boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
+
+ /* Now scan remaining volume of box and compute population */
+ ccount = 0;
+ for (c0 = c0min; c0 <= c0max; c0++)
+ for (c1 = c1min; c1 <= c1max; c1++) {
+ histp = & histogram[c0][c1][c2min];
+ for (c2 = c2min; c2 <= c2max; c2++, histp++)
+ if (*histp != 0) {
+ ccount++;
+ }
+ }
+ boxp->colorcount = ccount;
+}
+
+
+LOCAL int
+median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
+ int desired_colors)
+/* Repeatedly select and split the largest box until we have enough boxes */
+{
+ int n,lb;
+ int c0,c1,c2,cmax;
+ register boxptr b1,b2;
+
+ while (numboxes < desired_colors) {
+ /* Select box to split.
+ * Current algorithm: by population for first half, then by volume.
+ */
+ if (numboxes*2 <= desired_colors) {
+ b1 = find_biggest_color_pop(boxlist, numboxes);
+ } else {
+ b1 = find_biggest_volume(boxlist, numboxes);
+ }
+ if (b1 == NULL) /* no splittable boxes left! */
+ break;
+ b2 = &boxlist[numboxes]; /* where new box will go */
+ /* Copy the color bounds to the new box. */
+ b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
+ b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
+ /* Choose which axis to split the box on.
+ * Current algorithm: longest scaled axis.
+ * See notes in update_box about scaling distances.
+ */
+ c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
+ c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
+ c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
+ /* We want to break any ties in favor of green, then red, blue last.
+ * This code does the right thing for R,G,B or B,G,R color orders only.
+ */
+#if RGB_RED == 0
+ cmax = c1; n = 1;
+ if (c0 > cmax) { cmax = c0; n = 0; }
+ if (c2 > cmax) { n = 2; }
+#else
+ cmax = c1; n = 1;
+ if (c2 > cmax) { cmax = c2; n = 2; }
+ if (c0 > cmax) { n = 0; }
+#endif
+ /* Choose split point along selected axis, and update box bounds.
+ * Current algorithm: split at halfway point.
+ * (Since the box has been shrunk to minimum volume,
+ * any split will produce two nonempty subboxes.)
+ * Note that lb value is max for lower box, so must be < old max.
+ */
+ switch (n) {
+ case 0:
+ lb = (b1->c0max + b1->c0min) / 2;
+ b1->c0max = lb;
+ b2->c0min = lb+1;
+ break;
+ case 1:
+ lb = (b1->c1max + b1->c1min) / 2;
+ b1->c1max = lb;
+ b2->c1min = lb+1;
+ break;
+ case 2:
+ lb = (b1->c2max + b1->c2min) / 2;
+ b1->c2max = lb;
+ b2->c2min = lb+1;
+ break;
+ }
+ /* Update stats for boxes */
+ update_box(cinfo, b1);
+ update_box(cinfo, b2);
+ numboxes++;
+ }
+ return numboxes;
+}
+
+
+LOCAL void
+compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
+/* Compute representative color for a box, put it in colormap[icolor] */
+{
+ /* Current algorithm: mean weighted by pixels (not colors) */
+ /* Note it is important to get the rounding correct! */
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ hist3d histogram = cquantize->histogram;
+ histptr histp;
+ int c0,c1,c2;
+ int c0min,c0max,c1min,c1max,c2min,c2max;
+ long count;
+ long total = 0;
+ long c0total = 0;
+ long c1total = 0;
+ long c2total = 0;
+
+ c0min = boxp->c0min; c0max = boxp->c0max;
+ c1min = boxp->c1min; c1max = boxp->c1max;
+ c2min = boxp->c2min; c2max = boxp->c2max;
+
+ for (c0 = c0min; c0 <= c0max; c0++)
+ for (c1 = c1min; c1 <= c1max; c1++) {
+ histp = & histogram[c0][c1][c2min];
+ for (c2 = c2min; c2 <= c2max; c2++) {
+ if ((count = *histp++) != 0) {
+ total += count;
+ c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
+ c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
+ c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
+ }
+ }
+ }
+
+ cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
+ cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
+ cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
+}
+
+
+LOCAL void
+select_colors (j_decompress_ptr cinfo, int desired_colors)
+/* Master routine for color selection */
+{
+ boxptr boxlist;
+ int numboxes;
+ int i;
+
+ /* Allocate workspace for box list */
+ boxlist = (boxptr) (*cinfo->mem->alloc_small)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
+ /* Initialize one box containing whole space */
+ numboxes = 1;
+ boxlist[0].c0min = 0;
+ boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
+ boxlist[0].c1min = 0;
+ boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
+ boxlist[0].c2min = 0;
+ boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
+ /* Shrink it to actually-used volume and set its statistics */
+ update_box(cinfo, & boxlist[0]);
+ /* Perform median-cut to produce final box list */
+ numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
+ /* Compute the representative color for each box, fill colormap */
+ for (i = 0; i < numboxes; i++)
+ compute_color(cinfo, & boxlist[i], i);
+ cinfo->actual_number_of_colors = numboxes;
+ TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
+}
+
+
+/*
+ * These routines are concerned with the time-critical task of mapping input
+ * colors to the nearest color in the selected colormap.
+ *
+ * We re-use the histogram space as an "inverse color map", essentially a
+ * cache for the results of nearest-color searches. All colors within a
+ * histogram cell will be mapped to the same colormap entry, namely the one
+ * closest to the cell's center. This may not be quite the closest entry to
+ * the actual input color, but it's almost as good. A zero in the cache
+ * indicates we haven't found the nearest color for that cell yet; the array
+ * is cleared to zeroes before starting the mapping pass. When we find the
+ * nearest color for a cell, its colormap index plus one is recorded in the
+ * cache for future use. The pass2 scanning routines call fill_inverse_cmap
+ * when they need to use an unfilled entry in the cache.
+ *
+ * Our method of efficiently finding nearest colors is based on the "locally
+ * sorted search" idea described by Heckbert and on the incremental distance
+ * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
+ * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
+ * the distances from a given colormap entry to each cell of the histogram can
+ * be computed quickly using an incremental method: the differences between
+ * distances to adjacent cells themselves differ by a constant. This allows a
+ * fairly fast implementation of the "brute force" approach of computing the
+ * distance from every colormap entry to every histogram cell. Unfortunately,
+ * it needs a work array to hold the best-distance-so-far for each histogram
+ * cell (because the inner loop has to be over cells, not colormap entries).
+ * The work array elements have to be INT32s, so the work array would need
+ * 256Kb at our recommended precision. This is not feasible in DOS machines.
+ *
+ * To get around these problems, we apply Thomas' method to compute the
+ * nearest colors for only the cells within a small subbox of the histogram.
+ * The work array need be only as big as the subbox, so the memory usage
+ * problem is solved. Furthermore, we need not fill subboxes that are never
+ * referenced in pass2; many images use only part of the color gamut, so a
+ * fair amount of work is saved. An additional advantage of this
+ * approach is that we can apply Heckbert's locality criterion to quickly
+ * eliminate colormap entries that are far away from the subbox; typically
+ * three-fourths of the colormap entries are rejected by Heckbert's criterion,
+ * and we need not compute their distances to individual cells in the subbox.
+ * The speed of this approach is heavily influenced by the subbox size: too
+ * small means too much overhead, too big loses because Heckbert's criterion
+ * can't eliminate as many colormap entries. Empirically the best subbox
+ * size seems to be about 1/512th of the histogram (1/8th in each direction).
+ *
+ * Thomas' article also describes a refined method which is asymptotically
+ * faster than the brute-force method, but it is also far more complex and
+ * cannot efficiently be applied to small subboxes. It is therefore not
+ * useful for programs intended to be portable to DOS machines. On machines
+ * with plenty of memory, filling the whole histogram in one shot with Thomas'
+ * refined method might be faster than the present code --- but then again,
+ * it might not be any faster, and it's certainly more complicated.
+ */
+
+
+/* log2(histogram cells in update box) for each axis; this can be adjusted */
+#define BOX_C0_LOG (HIST_C0_BITS-3)
+#define BOX_C1_LOG (HIST_C1_BITS-3)
+#define BOX_C2_LOG (HIST_C2_BITS-3)
+
+#define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
+#define BOX_C1_ELEMS (1<<BOX_C1_LOG)
+#define BOX_C2_ELEMS (1<<BOX_C2_LOG)
+
+#define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
+#define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
+#define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
+
+
+/*
+ * The next three routines implement inverse colormap filling. They could
+ * all be folded into one big routine, but splitting them up this way saves
+ * some stack space (the mindist[] and bestdist[] arrays need not coexist)
+ * and may allow some compilers to produce better code by registerizing more
+ * inner-loop variables.
+ */
+
+LOCAL int
+find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
+ JSAMPLE colorlist[])
+/* Locate the colormap entries close enough to an update box to be candidates
+ * for the nearest entry to some cell(s) in the update box. The update box
+ * is specified by the center coordinates of its first cell. The number of
+ * candidate colormap entries is returned, and their colormap indexes are
+ * placed in colorlist[].
+ * This routine uses Heckbert's "locally sorted search" criterion to select
+ * the colors that need further consideration.
+ */
+{
+ int numcolors = cinfo->actual_number_of_colors;
+ int maxc0, maxc1, maxc2;
+ int centerc0, centerc1, centerc2;
+ int i, x, ncolors;
+ INT32 minmaxdist, min_dist, max_dist, tdist;
+ INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
+
+ /* Compute true coordinates of update box's upper corner and center.
+ * Actually we compute the coordinates of the center of the upper-corner
+ * histogram cell, which are the upper bounds of the volume we care about.
+ * Note that since ">>" rounds down, the "center" values may be closer to
+ * min than to max; hence comparisons to them must be "<=", not "<".
+ */
+ maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
+ centerc0 = (minc0 + maxc0) >> 1;
+ maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
+ centerc1 = (minc1 + maxc1) >> 1;
+ maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
+ centerc2 = (minc2 + maxc2) >> 1;
+
+ /* For each color in colormap, find:
+ * 1. its minimum squared-distance to any point in the update box
+ * (zero if color is within update box);
+ * 2. its maximum squared-distance to any point in the update box.
+ * Both of these can be found by considering only the corners of the box.
+ * We save the minimum distance for each color in mindist[];
+ * only the smallest maximum distance is of interest.
+ */
+ minmaxdist = 0x7FFFFFFFL;
+
+ for (i = 0; i < numcolors; i++) {
+ /* We compute the squared-c0-distance term, then add in the other two. */
+ x = GETJSAMPLE(cinfo->colormap[0][i]);
+ if (x < minc0) {
+ tdist = (x - minc0) * C0_SCALE;
+ min_dist = tdist*tdist;
+ tdist = (x - maxc0) * C0_SCALE;
+ max_dist = tdist*tdist;
+ } else if (x > maxc0) {
+ tdist = (x - maxc0) * C0_SCALE;
+ min_dist = tdist*tdist;
+ tdist = (x - minc0) * C0_SCALE;
+ max_dist = tdist*tdist;
+ } else {
+ /* within cell range so no contribution to min_dist */
+ min_dist = 0;
+ if (x <= centerc0) {
+ tdist = (x - maxc0) * C0_SCALE;
+ max_dist = tdist*tdist;
+ } else {
+ tdist = (x - minc0) * C0_SCALE;
+ max_dist = tdist*tdist;
+ }
+ }
+
+ x = GETJSAMPLE(cinfo->colormap[1][i]);
+ if (x < minc1) {
+ tdist = (x - minc1) * C1_SCALE;
+ min_dist += tdist*tdist;
+ tdist = (x - maxc1) * C1_SCALE;
+ max_dist += tdist*tdist;
+ } else if (x > maxc1) {
+ tdist = (x - maxc1) * C1_SCALE;
+ min_dist += tdist*tdist;
+ tdist = (x - minc1) * C1_SCALE;
+ max_dist += tdist*tdist;
+ } else {
+ /* within cell range so no contribution to min_dist */
+ if (x <= centerc1) {
+ tdist = (x - maxc1) * C1_SCALE;
+ max_dist += tdist*tdist;
+ } else {
+ tdist = (x - minc1) * C1_SCALE;
+ max_dist += tdist*tdist;
+ }
+ }
+
+ x = GETJSAMPLE(cinfo->colormap[2][i]);
+ if (x < minc2) {
+ tdist = (x - minc2) * C2_SCALE;
+ min_dist += tdist*tdist;
+ tdist = (x - maxc2) * C2_SCALE;
+ max_dist += tdist*tdist;
+ } else if (x > maxc2) {
+ tdist = (x - maxc2) * C2_SCALE;
+ min_dist += tdist*tdist;
+ tdist = (x - minc2) * C2_SCALE;
+ max_dist += tdist*tdist;
+ } else {
+ /* within cell range so no contribution to min_dist */
+ if (x <= centerc2) {
+ tdist = (x - maxc2) * C2_SCALE;
+ max_dist += tdist*tdist;
+ } else {
+ tdist = (x - minc2) * C2_SCALE;
+ max_dist += tdist*tdist;
+ }
+ }
+
+ mindist[i] = min_dist; /* save away the results */
+ if (max_dist < minmaxdist)
+ minmaxdist = max_dist;
+ }
+
+ /* Now we know that no cell in the update box is more than minmaxdist
+ * away from some colormap entry. Therefore, only colors that are
+ * within minmaxdist of some part of the box need be considered.
+ */
+ ncolors = 0;
+ for (i = 0; i < numcolors; i++) {
+ if (mindist[i] <= minmaxdist)
+ colorlist[ncolors++] = (JSAMPLE) i;
+ }
+ return ncolors;
+}
+
+
+LOCAL void
+find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
+ int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
+/* Find the closest colormap entry for each cell in the update box,
+ * given the list of candidate colors prepared by find_nearby_colors.
+ * Return the indexes of the closest entries in the bestcolor[] array.
+ * This routine uses Thomas' incremental distance calculation method to
+ * find the distance from a colormap entry to successive cells in the box.
+ */
+{
+ int ic0, ic1, ic2;
+ int i, icolor;
+ register INT32 * bptr; /* pointer into bestdist[] array */
+ JSAMPLE * cptr; /* pointer into bestcolor[] array */
+ INT32 dist0, dist1; /* initial distance values */
+ register INT32 dist2; /* current distance in inner loop */
+ INT32 xx0, xx1; /* distance increments */
+ register INT32 xx2;
+ INT32 inc0, inc1, inc2; /* initial values for increments */
+ /* This array holds the distance to the nearest-so-far color for each cell */
+ INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
+
+ /* Initialize best-distance for each cell of the update box */
+ bptr = bestdist;
+ for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
+ *bptr++ = 0x7FFFFFFFL;
+
+ /* For each color selected by find_nearby_colors,
+ * compute its distance to the center of each cell in the box.
+ * If that's less than best-so-far, update best distance and color number.
+ */
+
+ /* Nominal steps between cell centers ("x" in Thomas article) */
+#define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
+#define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
+#define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
+
+ for (i = 0; i < numcolors; i++) {
+ icolor = GETJSAMPLE(colorlist[i]);
+ /* Compute (square of) distance from minc0/c1/c2 to this color */
+ inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
+ dist0 = inc0*inc0;
+ inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
+ dist0 += inc1*inc1;
+ inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
+ dist0 += inc2*inc2;
+ /* Form the initial difference increments */
+ inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
+ inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
+ inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
+ /* Now loop over all cells in box, updating distance per Thomas method */
+ bptr = bestdist;
+ cptr = bestcolor;
+ xx0 = inc0;
+ for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
+ dist1 = dist0;
+ xx1 = inc1;
+ for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
+ dist2 = dist1;
+ xx2 = inc2;
+ for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
+ if (dist2 < *bptr) {
+ *bptr = dist2;
+ *cptr = (JSAMPLE) icolor;
+ }
+ dist2 += xx2;
+ xx2 += 2 * STEP_C2 * STEP_C2;
+ bptr++;
+ cptr++;
+ }
+ dist1 += xx1;
+ xx1 += 2 * STEP_C1 * STEP_C1;
+ }
+ dist0 += xx0;
+ xx0 += 2 * STEP_C0 * STEP_C0;
+ }
+ }
+}
+
+
+LOCAL void
+fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
+/* Fill the inverse-colormap entries in the update box that contains */
+/* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
+/* we can fill as many others as we wish.) */
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ hist3d histogram = cquantize->histogram;
+ int minc0, minc1, minc2; /* lower left corner of update box */
+ int ic0, ic1, ic2;
+ register JSAMPLE * cptr; /* pointer into bestcolor[] array */
+ register histptr cachep; /* pointer into main cache array */
+ /* This array lists the candidate colormap indexes. */
+ JSAMPLE colorlist[MAXNUMCOLORS];
+ int numcolors; /* number of candidate colors */
+ /* This array holds the actually closest colormap index for each cell. */
+ JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
+
+ /* Convert cell coordinates to update box ID */
+ c0 >>= BOX_C0_LOG;
+ c1 >>= BOX_C1_LOG;
+ c2 >>= BOX_C2_LOG;
+
+ /* Compute true coordinates of update box's origin corner.
+ * Actually we compute the coordinates of the center of the corner
+ * histogram cell, which are the lower bounds of the volume we care about.
+ */
+ minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
+ minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
+ minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
+
+ /* Determine which colormap entries are close enough to be candidates
+ * for the nearest entry to some cell in the update box.
+ */
+ numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
+
+ /* Determine the actually nearest colors. */
+ find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
+ bestcolor);
+
+ /* Save the best color numbers (plus 1) in the main cache array */
+ c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
+ c1 <<= BOX_C1_LOG;
+ c2 <<= BOX_C2_LOG;
+ cptr = bestcolor;
+ for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
+ for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
+ cachep = & histogram[c0+ic0][c1+ic1][c2];
+ for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
+ *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
+ }
+ }
+ }
+}
+
+
+/*
+ * Map some rows of pixels to the output colormapped representation.
+ */
+
+METHODDEF void
+pass2_no_dither (j_decompress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
+/* This version performs no dithering */
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ hist3d histogram = cquantize->histogram;
+ register JSAMPROW inptr, outptr;
+ register histptr cachep;
+ register int c0, c1, c2;
+ int row;
+ JDIMENSION col;
+ JDIMENSION width = cinfo->output_width;
+
+ for (row = 0; row < num_rows; row++) {
+ inptr = input_buf[row];
+ outptr = output_buf[row];
+ for (col = width; col > 0; col--) {
+ /* get pixel value and index into the cache */
+ c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
+ c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
+ c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
+ cachep = & histogram[c0][c1][c2];
+ /* If we have not seen this color before, find nearest colormap entry */
+ /* and update the cache */
+ if (*cachep == 0)
+ fill_inverse_cmap(cinfo, c0,c1,c2);
+ /* Now emit the colormap index for this cell */
+ *outptr++ = (JSAMPLE) (*cachep - 1);
+ }
+ }
+}
+
+
+METHODDEF void
+pass2_fs_dither (j_decompress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
+/* This version performs Floyd-Steinberg dithering */
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ hist3d histogram = cquantize->histogram;
+ register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
+ LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
+ LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
+ register FSERRPTR errorptr; /* => fserrors[] at column before current */
+ JSAMPROW inptr; /* => current input pixel */
+ JSAMPROW outptr; /* => current output pixel */
+ histptr cachep;
+ int dir; /* +1 or -1 depending on direction */
+ int dir3; /* 3*dir, for advancing inptr & errorptr */
+ int row;
+ JDIMENSION col;
+ JDIMENSION width = cinfo->output_width;
+ JSAMPLE *range_limit = cinfo->sample_range_limit;
+ int *error_limit = cquantize->error_limiter;
+ JSAMPROW colormap0 = cinfo->colormap[0];
+ JSAMPROW colormap1 = cinfo->colormap[1];
+ JSAMPROW colormap2 = cinfo->colormap[2];
+ SHIFT_TEMPS
+
+ for (row = 0; row < num_rows; row++) {
+ inptr = input_buf[row];
+ outptr = output_buf[row];
+ if (cquantize->on_odd_row) {
+ /* work right to left in this row */
+ inptr += (width-1) * 3; /* so point to rightmost pixel */
+ outptr += width-1;
+ dir = -1;
+ dir3 = -3;
+ errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
+ cquantize->on_odd_row = FALSE; /* flip for next time */
+ } else {
+ /* work left to right in this row */
+ dir = 1;
+ dir3 = 3;
+ errorptr = cquantize->fserrors; /* => entry before first real column */
+ cquantize->on_odd_row = TRUE; /* flip for next time */
+ }
+ /* Preset error values: no error propagated to first pixel from left */
+ cur0 = cur1 = cur2 = 0;
+ /* and no error propagated to row below yet */
+ belowerr0 = belowerr1 = belowerr2 = 0;
+ bpreverr0 = bpreverr1 = bpreverr2 = 0;
+
+ for (col = width; col > 0; col--) {
+ /* curN holds the error propagated from the previous pixel on the
+ * current line. Add the error propagated from the previous line
+ * to form the complete error correction term for this pixel, and
+ * round the error term (which is expressed * 16) to an integer.
+ * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
+ * for either sign of the error value.
+ * Note: errorptr points to *previous* column's array entry.
+ */
+ cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
+ cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
+ cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
+ /* Limit the error using transfer function set by init_error_limit.
+ * See comments with init_error_limit for rationale.
+ */
+ cur0 = error_limit[cur0];
+ cur1 = error_limit[cur1];
+ cur2 = error_limit[cur2];
+ /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
+ * The maximum error is +- MAXJSAMPLE (or less with error limiting);
+ * this sets the required size of the range_limit array.
+ */
+ cur0 += GETJSAMPLE(inptr[0]);
+ cur1 += GETJSAMPLE(inptr[1]);
+ cur2 += GETJSAMPLE(inptr[2]);
+ cur0 = GETJSAMPLE(range_limit[cur0]);
+ cur1 = GETJSAMPLE(range_limit[cur1]);
+ cur2 = GETJSAMPLE(range_limit[cur2]);
+ /* Index into the cache with adjusted pixel value */
+ cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
+ /* If we have not seen this color before, find nearest colormap */
+ /* entry and update the cache */
+ if (*cachep == 0)
+ fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
+ /* Now emit the colormap index for this cell */
+ { register int pixcode = *cachep - 1;
+ *outptr = (JSAMPLE) pixcode;
+ /* Compute representation error for this pixel */
+ cur0 -= GETJSAMPLE(colormap0[pixcode]);
+ cur1 -= GETJSAMPLE(colormap1[pixcode]);
+ cur2 -= GETJSAMPLE(colormap2[pixcode]);
+ }
+ /* Compute error fractions to be propagated to adjacent pixels.
+ * Add these into the running sums, and simultaneously shift the
+ * next-line error sums left by 1 column.
+ */
+ { register LOCFSERROR bnexterr, delta;
+
+ bnexterr = cur0; /* Process component 0 */
+ delta = cur0 * 2;
+ cur0 += delta; /* form error * 3 */
+ errorptr[0] = (FSERROR) (bpreverr0 + cur0);
+ cur0 += delta; /* form error * 5 */
+ bpreverr0 = belowerr0 + cur0;
+ belowerr0 = bnexterr;
+ cur0 += delta; /* form error * 7 */
+ bnexterr = cur1; /* Process component 1 */
+ delta = cur1 * 2;
+ cur1 += delta; /* form error * 3 */
+ errorptr[1] = (FSERROR) (bpreverr1 + cur1);
+ cur1 += delta; /* form error * 5 */
+ bpreverr1 = belowerr1 + cur1;
+ belowerr1 = bnexterr;
+ cur1 += delta; /* form error * 7 */
+ bnexterr = cur2; /* Process component 2 */
+ delta = cur2 * 2;
+ cur2 += delta; /* form error * 3 */
+ errorptr[2] = (FSERROR) (bpreverr2 + cur2);
+ cur2 += delta; /* form error * 5 */
+ bpreverr2 = belowerr2 + cur2;
+ belowerr2 = bnexterr;
+ cur2 += delta; /* form error * 7 */
+ }
+ /* At this point curN contains the 7/16 error value to be propagated
+ * to the next pixel on the current line, and all the errors for the
+ * next line have been shifted over. We are therefore ready to move on.
+ */
+ inptr += dir3; /* Advance pixel pointers to next column */
+ outptr += dir;
+ errorptr += dir3; /* advance errorptr to current column */
+ }
+ /* Post-loop cleanup: we must unload the final error values into the
+ * final fserrors[] entry. Note we need not unload belowerrN because
+ * it is for the dummy column before or after the actual array.
+ */
+ errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
+ errorptr[1] = (FSERROR) bpreverr1;
+ errorptr[2] = (FSERROR) bpreverr2;
+ }
+}
+
+
+/*
+ * Initialize the error-limiting transfer function (lookup table).
+ * The raw F-S error computation can potentially compute error values of up to
+ * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
+ * much less, otherwise obviously wrong pixels will be created. (Typical
+ * effects include weird fringes at color-area boundaries, isolated bright
+ * pixels in a dark area, etc.) The standard advice for avoiding this problem
+ * is to ensure that the "corners" of the color cube are allocated as output
+ * colors; then repeated errors in the same direction cannot cause cascading
+ * error buildup. However, that only prevents the error from getting
+ * completely out of hand; Aaron Giles reports that error limiting improves
+ * the results even with corner colors allocated.
+ * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
+ * well, but the smoother transfer function used below is even better. Thanks
+ * to Aaron Giles for this idea.
+ */
+
+LOCAL void
+init_error_limit (j_decompress_ptr cinfo)
+/* Allocate and fill in the error_limiter table */
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ int * table;
+ int in, out;
+
+ table = (int *) (*cinfo->mem->alloc_small)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
+ table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
+ cquantize->error_limiter = table;
+
+#define STEPSIZE ((MAXJSAMPLE+1)/16)
+ /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
+ out = 0;
+ for (in = 0; in < STEPSIZE; in++, out++) {
+ table[in] = out; table[-in] = -out;
+ }
+ /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
+ for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
+ table[in] = out; table[-in] = -out;
+ }
+ /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
+ for (; in <= MAXJSAMPLE; in++) {
+ table[in] = out; table[-in] = -out;
+ }
+#undef STEPSIZE
+}
+
+
+/*
+ * Finish up at the end of each pass.
+ */
+
+METHODDEF void
+finish_pass1 (j_decompress_ptr cinfo)
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+
+ /* Select the representative colors and fill in cinfo->colormap */
+ cinfo->colormap = cquantize->sv_colormap;
+ select_colors(cinfo, cquantize->desired);
+ /* Force next pass to zero the color index table */
+ cquantize->needs_zeroed = TRUE;
+}
+
+
+METHODDEF void
+finish_pass2 (j_decompress_ptr cinfo)
+{
+ /* no work */
+}
+
+
+/*
+ * Initialize for each processing pass.
+ */
+
+METHODDEF void
+start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ hist3d histogram = cquantize->histogram;
+ int i;
+
+ /* Only F-S dithering or no dithering is supported. */
+ /* If user asks for ordered dither, give him F-S. */
+ if (cinfo->dither_mode != JDITHER_NONE)
+ cinfo->dither_mode = JDITHER_FS;
+
+ if (is_pre_scan) {
+ /* Set up method pointers */
+ cquantize->pub.color_quantize = prescan_quantize;
+ cquantize->pub.finish_pass = finish_pass1;
+ cquantize->needs_zeroed = TRUE; /* Always zero histogram */
+ } else {
+ /* Set up method pointers */
+ if (cinfo->dither_mode == JDITHER_FS)
+ cquantize->pub.color_quantize = pass2_fs_dither;
+ else
+ cquantize->pub.color_quantize = pass2_no_dither;
+ cquantize->pub.finish_pass = finish_pass2;
+
+ /* Make sure color count is acceptable */
+ i = cinfo->actual_number_of_colors;
+ if (i < 1)
+ ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
+ if (i > MAXNUMCOLORS)
+ ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
+
+ if (cinfo->dither_mode == JDITHER_FS) {
+ size_t arraysize = (size_t) ((cinfo->output_width + 2) *
+ (3 * SIZEOF(FSERROR)));
+ /* Allocate Floyd-Steinberg workspace if we didn't already. */
+ if (cquantize->fserrors == NULL)
+ cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
+ /* Initialize the propagated errors to zero. */
+ jzero_far((void FAR *) cquantize->fserrors, arraysize);
+ /* Make the error-limit table if we didn't already. */
+ if (cquantize->error_limiter == NULL)
+ init_error_limit(cinfo);
+ cquantize->on_odd_row = FALSE;
+ }
+
+ }
+ /* Zero the histogram or inverse color map, if necessary */
+ if (cquantize->needs_zeroed) {
+ for (i = 0; i < HIST_C0_ELEMS; i++) {
+ jzero_far((void FAR *) histogram[i],
+ HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
+ }
+ cquantize->needs_zeroed = FALSE;
+ }
+}
+
+
+/*
+ * Switch to a new external colormap between output passes.
+ */
+
+METHODDEF void
+new_color_map_2_quant (j_decompress_ptr cinfo)
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+
+ /* Reset the inverse color map */
+ cquantize->needs_zeroed = TRUE;
+}
+
+
+/*
+ * Module initialization routine for 2-pass color quantization.
+ */
+
+GLOBAL void
+jinit_2pass_quantizer (j_decompress_ptr cinfo)
+{
+ my_cquantize_ptr cquantize;
+ int i;
+
+ cquantize = (my_cquantize_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_cquantizer));
+ cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
+ cquantize->pub.start_pass = start_pass_2_quant;
+ cquantize->pub.new_color_map = new_color_map_2_quant;
+ cquantize->fserrors = NULL; /* flag optional arrays not allocated */
+ cquantize->error_limiter = NULL;
+
+ /* Make sure jdmaster didn't give me a case I can't handle */
+ if (cinfo->out_color_components != 3)
+ ERREXIT(cinfo, JERR_NOTIMPL);
+
+ /* Allocate the histogram/inverse colormap storage */
+ cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
+ for (i = 0; i < HIST_C0_ELEMS; i++) {
+ cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
+ }
+ cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
+
+ /* Allocate storage for the completed colormap, if required.
+ * We do this now since it is FAR storage and may affect
+ * the memory manager's space calculations.
+ */
+ if (cinfo->enable_2pass_quant) {
+ /* Make sure color count is acceptable */
+ int desired = cinfo->desired_number_of_colors;
+ /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
+ if (desired < 8)
+ ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
+ /* Make sure colormap indexes can be represented by JSAMPLEs */
+ if (desired > MAXNUMCOLORS)
+ ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
+ cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
+ cquantize->desired = desired;
+ } else
+ cquantize->sv_colormap = NULL;
+
+ /* Only F-S dithering or no dithering is supported. */
+ /* If user asks for ordered dither, give him F-S. */
+ if (cinfo->dither_mode != JDITHER_NONE)
+ cinfo->dither_mode = JDITHER_FS;
+
+ /* Allocate Floyd-Steinberg workspace if necessary.
+ * This isn't really needed until pass 2, but again it is FAR storage.
+ * Although we will cope with a later change in dither_mode,
+ * we do not promise to honor max_memory_to_use if dither_mode changes.
+ */
+ if (cinfo->dither_mode == JDITHER_FS) {
+ cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
+ /* Might as well create the error-limiting table too. */
+ init_error_limit(cinfo);
+ }
+}
+
+#endif /* QUANT_2PASS_SUPPORTED */
diff --git a/code/jpeg-6/jutils.c b/code/jpeg-6/jutils.c
new file mode 100755
index 0000000..8e8dc13
--- /dev/null
+++ b/code/jpeg-6/jutils.c
@@ -0,0 +1,175 @@
+/*
+ * jutils.c
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains tables and miscellaneous utility routines needed
+ * for both compression and decompression.
+ * Note we prefix all global names with "j" to minimize conflicts with
+ * a surrounding application.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/*
+ * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
+ * of a DCT block read in natural order (left to right, top to bottom).
+ */
+
+const int jpeg_zigzag_order[DCTSIZE2] = {
+ 0, 1, 5, 6, 14, 15, 27, 28,
+ 2, 4, 7, 13, 16, 26, 29, 42,
+ 3, 8, 12, 17, 25, 30, 41, 43,
+ 9, 11, 18, 24, 31, 40, 44, 53,
+ 10, 19, 23, 32, 39, 45, 52, 54,
+ 20, 22, 33, 38, 46, 51, 55, 60,
+ 21, 34, 37, 47, 50, 56, 59, 61,
+ 35, 36, 48, 49, 57, 58, 62, 63
+};
+
+/*
+ * jpeg_natural_order[i] is the natural-order position of the i'th element
+ * of zigzag order.
+ *
+ * When reading corrupted data, the Huffman decoders could attempt
+ * to reference an entry beyond the end of this array (if the decoded
+ * zero run length reaches past the end of the block). To prevent
+ * wild stores without adding an inner-loop test, we put some extra
+ * "63"s after the real entries. This will cause the extra coefficient
+ * to be stored in location 63 of the block, not somewhere random.
+ * The worst case would be a run-length of 15, which means we need 16
+ * fake entries.
+ */
+
+const int jpeg_natural_order[DCTSIZE2+16] = {
+ 0, 1, 8, 16, 9, 2, 3, 10,
+ 17, 24, 32, 25, 18, 11, 4, 5,
+ 12, 19, 26, 33, 40, 48, 41, 34,
+ 27, 20, 13, 6, 7, 14, 21, 28,
+ 35, 42, 49, 56, 57, 50, 43, 36,
+ 29, 22, 15, 23, 30, 37, 44, 51,
+ 58, 59, 52, 45, 38, 31, 39, 46,
+ 53, 60, 61, 54, 47, 55, 62, 63,
+ 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
+ 63, 63, 63, 63, 63, 63, 63, 63
+};
+
+
+/*
+ * Arithmetic utilities
+ */
+
+GLOBAL long
+jdiv_round_up (long a, long b)
+/* Compute a/b rounded up to next integer, ie, ceil(a/b) */
+/* Assumes a >= 0, b > 0 */
+{
+ return (a + b - 1L) / b;
+}
+
+
+GLOBAL long
+jround_up (long a, long b)
+/* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
+/* Assumes a >= 0, b > 0 */
+{
+ a += b - 1L;
+ return a - (a % b);
+}
+
+
+/* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
+ * and coefficient-block arrays. This won't work on 80x86 because the arrays
+ * are FAR and we're assuming a small-pointer memory model. However, some
+ * DOS compilers provide far-pointer versions of memcpy() and memset() even
+ * in the small-model libraries. These will be used if USE_FMEM is defined.
+ * Otherwise, the routines below do it the hard way. (The performance cost
+ * is not all that great, because these routines aren't very heavily used.)
+ */
+
+#ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
+#define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
+#define FMEMZERO(target,size) MEMZERO(target,size)
+#else /* 80x86 case, define if we can */
+#ifdef USE_FMEM
+#define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
+#define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
+#endif
+#endif
+
+
+GLOBAL void
+jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
+ JSAMPARRAY output_array, int dest_row,
+ int num_rows, JDIMENSION num_cols)
+/* Copy some rows of samples from one place to another.
+ * num_rows rows are copied from input_array[source_row++]
+ * to output_array[dest_row++]; these areas may overlap for duplication.
+ * The source and destination arrays must be at least as wide as num_cols.
+ */
+{
+ register JSAMPROW inptr, outptr;
+#ifdef FMEMCOPY
+ register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
+#else
+ register JDIMENSION count;
+#endif
+ register int row;
+
+ input_array += source_row;
+ output_array += dest_row;
+
+ for (row = num_rows; row > 0; row--) {
+ inptr = *input_array++;
+ outptr = *output_array++;
+#ifdef FMEMCOPY
+ FMEMCOPY(outptr, inptr, count);
+#else
+ for (count = num_cols; count > 0; count--)
+ *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
+#endif
+ }
+}
+
+
+GLOBAL void
+jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
+ JDIMENSION num_blocks)
+/* Copy a row of coefficient blocks from one place to another. */
+{
+#ifdef FMEMCOPY
+ FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
+#else
+ register JCOEFPTR inptr, outptr;
+ register long count;
+
+ inptr = (JCOEFPTR) input_row;
+ outptr = (JCOEFPTR) output_row;
+ for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
+ *outptr++ = *inptr++;
+ }
+#endif
+}
+
+
+GLOBAL void
+jzero_far (void FAR * target, size_t bytestozero)
+/* Zero out a chunk of FAR memory. */
+/* This might be sample-array data, block-array data, or alloc_large data. */
+{
+#ifdef FMEMZERO
+ FMEMZERO(target, bytestozero);
+#else
+ register char FAR * ptr = (char FAR *) target;
+ register size_t count;
+
+ for (count = bytestozero; count > 0; count--) {
+ *ptr++ = 0;
+ }
+#endif
+}
diff --git a/code/jpeg-6/jversion.h b/code/jpeg-6/jversion.h
new file mode 100755
index 0000000..02083ac
--- /dev/null
+++ b/code/jpeg-6/jversion.h
@@ -0,0 +1,14 @@
+/*
+ * jversion.h
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains software version identification.
+ */
+
+
+#define JVERSION "6 2-Aug-95"
+
+#define JCOPYRIGHT "Copyright (C) 1995, Thomas G. Lane"
diff --git a/code/macosx/BuildRelease b/code/macosx/BuildRelease
new file mode 100755
index 0000000..fd49285
--- /dev/null
+++ b/code/macosx/BuildRelease
@@ -0,0 +1,17 @@
+#!/bin/zsh
+
+APPNAME="Quake3"
+PACKAGENAME= Quake3
+
+(cd $OMNI_SOURCE_ROOT; ./Build Quake3 install)
+
+rm -rf "/tmp/$APPNAME"
+mkdir "/tmp/$APPNAME"
+cp "Read Me.rtf" "/tmp/$APPNAME"
+
+cd /Users/Shared/$USER/InstalledProducts
+gnutar cf - FAKK2.app | (cd "/tmp/$APPNAME"; gnutar xf -)
+
+cd "/tmp/$APPNAME"
+sudo ~bungi/Unix/bin/files2image $PACKAGENAME ./*
+
diff --git a/code/macosx/CGMouseDeltaFix.h b/code/macosx/CGMouseDeltaFix.h
new file mode 100755
index 0000000..b613a98
--- /dev/null
+++ b/code/macosx/CGMouseDeltaFix.h
@@ -0,0 +1,27 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#import <ApplicationServices/ApplicationServices.h>
+
+extern void CGFix_Initialize();
+
+extern void CGFix_GetLastMouseDelta(CGMouseDelta *dx, CGMouseDelta *dy);
+
diff --git a/code/macosx/CGMouseDeltaFix.m b/code/macosx/CGMouseDeltaFix.m
new file mode 100755
index 0000000..ee83eeb
--- /dev/null
+++ b/code/macosx/CGMouseDeltaFix.m
@@ -0,0 +1,131 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#import "CGMouseDeltaFix.h"
+#import "CGPrivateAPI.h"
+
+#import <Foundation/Foundation.h>
+#import <mach-o/dyld.h>
+
+
+// We will try to automatically fall back to using the original CGGetLastMouseDelta when we are on a system new enough to have the fix. Any version of CoreGraphics past 1.93.0 will have the fixed version.
+
+
+static BOOL originalVersionShouldWork = YES;
+static CGMouseDelta CGFix_Mouse_DeltaX, CGFix_Mouse_DeltaY;
+
+static void CGFix_NotificationCallback(CGSNotificationType note, CGSNotificationData data, CGSByteCount dataLength, CGSNotificationArg arg);
+
+static CGSRegisterNotifyProcType registerNotifyProc = NULL;
+
+void CGFix_Initialize()
+{
+ NSAutoreleasePool *pool;
+ NSBundle *cgBundle;
+ NSString *version;
+ NSArray *components;
+
+ if (registerNotifyProc)
+ // We've already been called once and have registered our callbacks. If the original version works, this will be NULL, but we'll end up doing nothing (again, possibly).
+ return;
+
+ //NSLog(@"CGFix_Initialize\n");
+
+ pool = [[NSAutoreleasePool alloc] init];
+ cgBundle = [NSBundle bundleWithPath: @"/System/Library/Frameworks/ApplicationServices.framework/Frameworks/CoreGraphics.framework"];
+ if (!cgBundle) {
+ // If it's moved, it must be newer than what we know about and should work
+ //NSLog(@"No /System/Library/Frameworks/ApplicationServices.framework/Frameworks/CoreGraphics.framework\n");
+ goto done;
+ }
+
+ version = [[cgBundle infoDictionary] objectForKey: @"CFBundleShortVersionString"];
+ components = [version componentsSeparatedByString: @"."];
+ //NSLog(@"version = %@\n", version);
+ //NSLog(@"components = %@\n", components);
+
+
+ if ([components count] < 2)
+ // We don't understand this versioning scheme. Must have changed.
+ goto done;
+
+ if (![[components objectAtIndex: 0] isEqualToString: @"1"] || [[components objectAtIndex: 1] intValue] > 93)
+ // This version should be new enough to work
+ goto done;
+
+ // Look up the function pointer we need to register our callback.
+ if (!NSIsSymbolNameDefined("_CGSRegisterNotifyProc")) {
+ //NSLog(@"No _CGSRegisterNotifyProc\n");
+ goto done;
+ }
+
+ registerNotifyProc = NSAddressOfSymbol(NSLookupAndBindSymbol("_CGSRegisterNotifyProc"));
+ //NSLog(@"registerNotifyProc = 0x%08x", registerNotifyProc);
+
+ // Must not work if we got here
+ originalVersionShouldWork = NO;
+
+ // We want to catch all the events that could possible indicate mouse movement and sum them up
+ registerNotifyProc( CGFix_NotificationCallback, kCGSEventNotificationMouseMoved, NULL);
+ registerNotifyProc( CGFix_NotificationCallback, kCGSEventNotificationLeftMouseDragged, NULL);
+ registerNotifyProc( CGFix_NotificationCallback, kCGSEventNotificationRightMouseDragged, NULL);
+ registerNotifyProc( CGFix_NotificationCallback, kCGSEventNotificationNotificationOtherMouseDragged, NULL);
+
+done:
+ [pool release];
+}
+
+void CGFix_GetLastMouseDelta(CGMouseDelta *dx, CGMouseDelta *dy)
+{
+ if (originalVersionShouldWork) {
+ CGGetLastMouseDelta(dx, dy);
+ return;
+ }
+
+ *dx = CGFix_Mouse_DeltaX;
+ *dy = CGFix_Mouse_DeltaY;
+
+ CGFix_Mouse_DeltaX = CGFix_Mouse_DeltaY = 0;
+}
+
+static void CGFix_NotificationCallback(CGSNotificationType note, CGSNotificationData data, CGSByteCount dataLength, CGSNotificationArg arg)
+{
+ CGSEventRecordPtr event;
+
+ //fprintf(stderr, "CGFix_NotificationCallback(note=%d, date=0x%08x, dataLength=%d, arg=0x%08x)\n", note, data, dataLength, arg);
+
+#ifdef DEBUG
+ if ((note != kCGSEventNotificationMouseMoved &&
+ note != kCGSEventNotificationLeftMouseDragged &&
+ note != kCGSEventNotificationRightMouseDragged &&
+ note != kCGSEventNotificationNotificationOtherMouseDragged) ||
+ dataLength != sizeof (CGSEventRecord))
+ fprintf(stderr, "Unexpected arguments to callback function CGFix_NotificationCallback(note=%d, date=0x%08x, dataLength=%d, arg=0x%08x)\n", note, data, dataLength, arg);
+ abort();
+ }
+#endif
+
+ event = (CGSEventRecordPtr)data;
+
+ CGFix_Mouse_DeltaX += event->data.move.deltaX;
+ CGFix_Mouse_DeltaY += event->data.move.deltaY;
+ //fprintf(stderr, " dx += %d, dy += %d\n", event->data.move.deltaX, event->data.move.deltaY);
+}
diff --git a/code/macosx/CGPrivateAPI.h b/code/macosx/CGPrivateAPI.h
new file mode 100755
index 0000000..0eb8779
--- /dev/null
+++ b/code/macosx/CGPrivateAPI.h
@@ -0,0 +1,185 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+
+typedef unsigned long CGSNotificationType;
+typedef void * CGSNotificationData;
+typedef void * CGSNotificationArg;
+typedef void * CGSWindowID;
+typedef void * CGSConnectionID;
+
+typedef unsigned long long CGSUInt64;
+typedef long long CGSInt64;
+typedef unsigned long CGSUInt32;
+typedef long CGSInt32;
+typedef unsigned short CGSUInt16;
+typedef short CGSInt16;
+typedef unsigned char CGSUInt8;
+typedef char CGSInt8;
+typedef float CGSFloat32;
+
+typedef CGSUInt32 CGSByteCount;
+typedef CGSUInt16 CGSEventRecordVersion;
+typedef unsigned long CGSEventType;
+typedef CGSUInt64 CGSEventRecordTime; /* nanosecond timer */
+typedef unsigned long CGSEventFlag;
+typedef CGSUInt32 CGSError;
+
+
+typedef union {
+ struct { /* For mouse events */
+ CGSUInt8 subx; /* sub-pixel position for x */
+ CGSUInt8 suby; /* sub-pixel position for y */
+ CGSInt16 eventNum; /* unique identifier for this button */
+ CGSInt32 click; /* click state of this event */
+ CGSUInt8 pressure; /* pressure value: 0=none, 255=full */
+ CGSInt8 _reserved1;
+ CGSInt16 _reserved2;
+ CGSInt16 deltaX;
+ CGSInt16 deltaY;
+ CGSInt32 _padding[8];
+ } mouse;
+ struct { /* For pointer movement events */
+ CGSInt16 _obsolete_deltaX; /* Revert to subX, subY, eventNum */
+ CGSInt16 _obsolete_deltaY; /* for Gonzo 1H */
+ CGSInt32 click; /* click state of this event */
+ CGSUInt8 pressure; /* pressure value: 0=none, 255=full */
+ CGSInt8 _reserved1;
+ CGSInt16 _reserved2;
+ CGSInt16 deltaX;
+ CGSInt16 deltaY;
+ CGSInt32 _padding[8];
+ } move;
+ struct { /* For key-down and key-up events */
+ CGSInt16 reserved;
+ CGSInt16 repeat; /* for key-down: nonzero if really a repeat */
+ CGSUInt16 charSet; /* character set code */
+ CGSUInt16 charCode; /* character code in that set */
+ CGSUInt16 keyCode; /* device-dependent virtual key code */
+ CGSInt16 keyData; /* device-dependent info */
+ CGSInt16 specialKey; /* CPSSpecialKeyID if kCGSFlagsMaskSpecialKey is set */
+ CGSInt16 _pad;
+ CGSInt32 _padding[8];
+ } key;
+ struct { /* For mouse-entered and mouse-exited events */
+ CGSInt16 reserved;
+ CGSInt16 eventNum; /* unique identifier from mouse down event */
+ CGSInt32 trackingNum; /* unique identifier from settrackingrect */
+ CGSInt32 userData; /* unCGSInt32erpreted CGSInt32eger from settrackingrect */
+ CGSInt32 _padding[9];
+ } tracking;
+ struct { /* For process-related events */
+ CGSUInt16 notifyCode; /* CPSNotificationCodes in CPSProcesses.h */
+ CGSUInt16 flags; /* CPSEventFlags in CPSProcesses.h */
+ CGSUInt32 targetHiPSN; /* hiword of PSN */
+ CGSUInt32 targetLoPSN; /* loword of PSN */
+ CGSInt32 status; /* operation result */
+ CGSInt32 _padding[8];
+ } process;
+ struct { /* For scroll wheel events */
+ CGSInt16 deltaAxis1;
+ CGSInt16 deltaAxis2;
+ CGSInt16 deltaAxis3;
+ CGSInt16 reserved1;
+ CGSInt32 reserved2;
+ CGSInt32 _padding[9];
+ } scrollWheel;
+ struct {
+ CGSInt32 x; /* absolute x coordinate in tablet space at full tablet resolution */
+ CGSInt32 y; /* absolute y coordinate in tablet space at full tablet resolution */
+ CGSInt32 z; /* absolute z coordinate in tablet space at full tablet resolution */
+ CGSUInt16 buttons; /* one bit per button - bit 0 is first button - 1 = closed */
+ CGSUInt16 pressure; /* scaled pressure value; MAXPRESSURE=(2^16)-1, MINPRESSURE=0 */
+ struct {
+ CGSInt16 x; /* scaled tilt x value; range is -((2^15)-1) to (2^15)-1 (-32767 to 32767) */
+ CGSInt16 y; /* scaled tilt y value; range is -((2^15)-1) to (2^15)-1 (-32767 to 32767) */
+ } tilt;
+ CGSUInt16 rotation; /* Fixed-point representation of device rotation in a 10.6 format */
+ CGSInt16 tangentialPressure; /* tangential pressure on the device; range same as tilt */
+ CGSUInt16 deviceID; /* system-assigned unique device ID - matches to deviceID field in proximity event */
+ CGSInt16 vendor1; /* vendor-defined signed 16-bit integer */
+ CGSInt16 vendor2; /* vendor-defined signed 16-bit integer */
+ CGSInt16 vendor3; /* vendor-defined signed 16-bit integer */
+ CGSInt32 _padding[4];
+ } tablet;
+ struct {
+ CGSUInt16 vendorID; /* vendor-defined ID - typically will be USB vendor ID */
+ CGSUInt16 tabletID; /* vendor-defined tablet ID - typically will be USB product ID for the tablet */
+ CGSUInt16 pointerID; /* vendor-defined ID of the specific pointing device */
+ CGSUInt16 deviceID; /* system-assigned unique device ID - matches to deviceID field in tablet event */
+ CGSUInt16 systemTabletID; /* system-assigned unique tablet ID */
+ CGSUInt16 vendorPointerType; /* vendor-defined pointer type */
+ CGSUInt32 pointerSerialNumber; /* vendor-defined serial number of the specific pointing device */
+ CGSUInt64 uniqueID; /* vendor-defined unique ID for this pointer */
+ CGSUInt32 capabilityMask; /* mask representing the capabilities of the device */
+ CGSUInt8 pointerType; /* type of pointing device - enum to be defined */
+ CGSUInt8 enterProximity; /* non-zero = entering; zero = leaving */
+ CGSInt16 reserved1;
+ CGSInt32 _padding[4];
+ } proximity;
+ struct { /* For AppKit-defined, sys-defined, and app-defined events */
+ CGSInt16 reserved;
+ CGSInt16 subtype; /* event subtype for compound events */
+ union {
+ CGSFloat32 F[11]; /* for use in compound events */
+ CGSInt32 L[11]; /* for use in compound events */
+ CGSInt16 S[22]; /* for use in compound events */
+ CGSInt8 C[44]; /* for use in compound events */
+ } misc;
+ } compound;
+} CGSEventRecordData;
+
+
+struct _CGSEventRecord {
+ CGSEventRecordVersion major;
+ CGSEventRecordVersion minor;
+ CGSByteCount length; /* Length of complete event record */
+ CGSEventType type; /* An event type from above */
+ CGPoint location; /* Base coordinates (global), from upper-left */
+ CGPoint windowLocation; /* Coordinates relative to window */
+ CGSEventRecordTime time; /* nanoseconds since startup */
+ CGSEventFlag flags; /* key state flags */
+ CGSWindowID window; /* window number of assigned window */
+ CGSConnectionID connection; /* connection the event came from */
+ CGSEventRecordData data; /* type-dependent data: 40 bytes */
+};
+typedef struct _CGSEventRecord CGSEventRecord;
+typedef CGSEventRecord *CGSEventRecordPtr;
+
+
+typedef void (*CGSNotifyProcPtr)(CGSNotificationType type,
+ CGSNotificationData data,
+ CGSByteCount dataLength,
+ CGSNotificationArg arg);
+
+// Define a type for the 'CGSRegisterNotifyProc' call. Don't reference it explicitly since we don't want link errors if Apple removes this private function.
+typedef CGSError (*CGSRegisterNotifyProcType)(CGSNotifyProcPtr proc,
+ CGSNotificationType type,
+ CGSNotificationArg arg);
+
+
+#define kCGSEventNotificationMouseMoved (710 + 5)
+#define kCGSEventNotificationLeftMouseDragged (710 + 6)
+#define kCGSEventNotificationRightMouseDragged (710 + 7)
+#define kCGSEventNotificationNotificationOtherMouseDragged (710 + 27)
+
+
diff --git a/code/macosx/GenerateQGL.pl b/code/macosx/GenerateQGL.pl
new file mode 100755
index 0000000..27854df
--- /dev/null
+++ b/code/macosx/GenerateQGL.pl
@@ -0,0 +1,146 @@
+#!/usr/bin/perl
+
+open(INPUT_FILE, ">/tmp/input-$$.h") || die "$!";
+print INPUT_FILE "#import <OpenGL/gl.h>\n";
+close INPUT_FILE;
+open(CPP, "cpp /tmp/input-$$.h|") || die "$!";
+
+print "/**** This file is autogenerated. Run GenerateQGL.pl to update it ****/\n\n";
+
+print "#ifdef QGL_LOG_GL_CALLS\n";
+print "extern unsigned int QGLLogGLCalls;\n";
+print "extern FILE *QGLDebugFile(void);\n";
+print "#endif\n\n";
+
+print "extern void QGLCheckError(const char *message);\n";
+print "extern unsigned int QGLBeginStarted;\n\n";
+print "// This has to be done to avoid infinite recursion between our glGetError wrapper and QGLCheckError()\n";
+print "static inline GLenum _glGetError(void) {\n";
+print " return glGetError();\n";
+print "}\n\n";
+
+@functionNames = ();
+
+while (<CPP>) {
+ chop;
+ /^extern/ || next;
+ s/extern //;
+ print "// $_\n";
+
+ # This approach is necessary to deal with glGetString whos type isn't a single word
+ ($type, $rest) = m/(.+)\s+(gl.*)/;
+# print "type='$type'\n";
+# print "rest='$rest'\n";
+
+ ($name, $argString) = ($rest =~ m/(\w+).*\s*\((.*)\)/);
+ $isVoid = ($type =~ m/void/);
+ push(@functionNames, $name);
+
+# print "name=$name\n";
+# print "argString=$argString\n";
+# print "argCount=$#args\n";
+
+ # Parse the argument list into two arrays, one of types and one of argument names
+ if ($argString =~ m/^void$/) {
+ @args = ();
+ } else {
+ @args = split(",", $argString);
+ }
+ @argTypes = ();
+ @argNames = ();
+ for $arg (@args) {
+ ($argType, $argName) = ($arg =~ m/(.*[ \*])([_a-zA-Z0-9]+)/);
+ $argType =~ s/^ *//;
+ $argType =~ s/ *$//;
+
+ push(@argTypes, $argType);
+ push(@argNames, $argName);
+# print "argType='$argType'\n";
+# print "argName='$argName'\n";
+ }
+
+
+ print "static inline $type q$name($argString)\n";
+ print "{\n";
+
+ if (! $isVoid) {
+ print " $type returnValue;\n";
+ }
+
+ print "#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)\n";
+ print " if (QGLLogGLCalls)\n";
+ print " fprintf(QGLDebugFile(), \"$name(";
+
+ if ($#argTypes >= 0) {
+ for ($i = 0; $i <= $#argTypes; $i++) {
+ $argType = $argTypes[$i];
+ $argName = $argNames[$i];
+ $_ = $argType;
+ if (/^GLenum$/ || /^GLuint$/ || /^GLbitfield$/) {
+ print "$argName=%lu";
+ } elsif (/^GLsizei$/ || /^GLint$/) {
+ print "$argName=%ld";
+ } elsif (/^GLfloat$/ || /^GLdouble$/ || /^GLclampf$/ || /^GLclampd$/) {
+ print "$argName=%f";
+ } elsif (/^GLbyte$/) {
+ print "$argName=%d";
+ } elsif (/^GLubyte$/) {
+ print "$argName=%u";
+ } elsif (/^GLshort$/) {
+ print "$argName=%d";
+ } elsif (/^GLushort$/) {
+ print "$argName=%u";
+ } elsif (/^GLboolean$/) {
+ print "$argName=%u";
+ } elsif (/\*$/) {
+ # TJW -- Later we should look at the count specified in the function name, look at the basic type and print out an array. Or we could just special case them...
+ print "$argName=%p";
+ } else {
+ print STDERR "Unknown type '$argType'\n";
+ exit(1);
+ }
+
+ print ", " if ($i != $#argTypes);
+ }
+ } else {
+ print "void";
+ }
+
+ print ")\\n\"";
+ print ", " if $#argTypes >= 0;
+ print join(", ", @argNames);
+ print ");\n";
+ print "#endif\n";
+
+ if (! $isVoid) {
+ print " returnValue = ";
+ } else {
+ print " ";
+ }
+ print "$name(" . join(", ", @argNames) . ");\n";
+
+ print "#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)\n";
+ if ($name eq "glBegin") {
+ print " QGLBeginStarted++;\n";
+ }
+ if ($name eq "glEnd") {
+ print " QGLBeginStarted--;\n";
+ }
+ print " if (!QGLBeginStarted)\n";
+ print " QGLCheckError(\"$name\");\n";
+ print "#endif\n";
+
+ if (! $isVoid) {
+ print " return returnValue;\n";
+ }
+
+ print "}\n\n";
+}
+
+
+print "// Prevent calls to the 'normal' GL functions\n";
+for $name (@functionNames) {
+ print "#define $name CALL_THE_QGL_VERSION_OF_$name\n";
+}
+
+
diff --git a/code/macosx/Performance.rtf b/code/macosx/Performance.rtf
new file mode 100755
index 0000000..4ba0bfe
--- /dev/null
+++ b/code/macosx/Performance.rtf
@@ -0,0 +1,114 @@
+{\rtf1\mac\ansicpg10000{\fonttbl\f0\fswiss\fcharset77 Helvetica;}
+{\colortbl;\red255\green255\blue255;\red255\green0\blue16;\red255\green0\blue16;}
+\paperw14240\paperh14700
+\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
+
+\f0\fs24 \cf0 \
+
+\b +set timedemo 1 +demo die.dm3 +set s_initsound 0 +set r_enablerender 0 +set vm_cgame 0 +set vm_game 0\
+4865 frames, 154.3 seconds: 31.5 fps\
+\
+\
++set timedemo 1 +demo die.dm3 +set s_initsound 0 +set r_enablerender 0 +set vm_cgame 2 +set vm_game 2\
+4865 frames, 199.8 seconds: 24.4 fps\
+\
+\
++set timedemo 1 +demo demo001.dm3 +set s_initsound 0 +set r_enablerender 0 +set vm_cgame 0 +set vm_game 0\
+1346 frames, 10.1 seconds: 133.0 fps\
+\
+\
++set timedemo 1 +demo demo001.dm3 +set s_initsound 0 +set r_enablerender 0 +set vm_cgame 2 +set vm_game 2\
+1346 frames, 12.8 seconds: 105.4 fps\
+\
+\
+\
+Starting point\
+
+\b0 4865 frames, 154.5 seconds: 31.5 fps\
+[seconds spent locally, % of parent, % of total, # of samples]\
+[133.623469 -- 60130560955, 100.00%, 100.00%, 4866] Root\
+ [126.853849 -- 57084231997, 94.93%, 94.93%, 4866] CL_Frame\
+ [125.895845 -- 56653130083, 99.24%, 94.22%, 4918] SCR_UpdateScreen\
+ [50.532841 -- 22739778533, 40.14%, 37.82%, 524036] RB_SurfaceMesh\
+ [46.583051 -- 20962372767, 92.18%, 34.86%, 524036] LerpMeshVertexes\
+ [8.465527 -- 3809487228, 18.17%, 6.34%, 455917] LerpMeshVertexes 1\
+
+\b \cf2 [37.967433 -- 17085344910, 81.50%, 28.41%, 68119] LerpMeshVertexes 2\
+
+\b0 \cf0 [0.32% spent locally]\
+ [7.82% spent locally]\
+ [59.86% spent locally]\
+ [0.76% spent locally]\
+[5.07% spent locally]\
+\
+
+\b Minor cleanup of local variables\
+
+\b0 [seconds spent locally, % of parent, % of total, # of samples]\
+[133.121489 -- 59904670191, 100.00%, 100.00%, 4866] Root\
+ [126.329343 -- 56848204176, 94.90%, 94.90%, 4866] CL_Frame\
+ [125.402239 -- 56431007399, 99.27%, 94.20%, 4918] SCR_UpdateScreen\
+ [50.013076 -- 22505884288, 39.88%, 37.57%, 524036] RB_SurfaceMesh\
+ [46.085775 -- 20738598809, 92.15%, 34.62%, 524036] LerpMeshVertexes\
+ [8.427565 -- 3792404277, 18.29%, 6.33%, 455917] LerpMeshVertexes 1\
+\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
+
+\b \cf3 [37.517092 -- 16882691281, 81.41%, 28.18%, 68119] LerpMeshVertexes 2\
+\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
+
+\b0 \cf0 [0.31% spent locally]\
+ [7.85% spent locally]\
+ [60.12% spent locally]\
+ [0.73% spent locally]\
+[5.10% spent locally]\
+\
+\
+
+\b Split out normalization of LERPed normals (i.e., all the sqrt calls)\
+
+\b0 [seconds spent locally, % of parent, % of total, # of samples]\
+[133.110463 -- 59899708244, 100.00%, 100.00%, 4866] Root\
+ [126.357393 -- 56860826689, 94.93%, 94.93%, 4866] CL_Frame\
+ [125.364641 -- 56414088645, 99.21%, 94.18%, 4918] SCR_UpdateScreen\
+ [49.854816 -- 22434667309, 39.77%, 37.45%, 524036] RB_SurfaceMesh\
+ [45.981802 -- 20691810706, 92.23%, 34.54%, 524036] LerpMeshVertexes\
+ [8.407983 -- 3783592133, 18.29%, 6.32%, 455917] LerpMeshVertexes 1\
+ [37.432159 -- 16844471717, 81.41%, 28.12%, 68119] LerpMeshVertexes 2\
+\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
+
+\b \cf3 [30.288000 -- 13629599780, 80.91%, 22.75%, 68119] VectorArrayNormalize\
+\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
+
+\b0 \cf0 [19.09% spent locally]\
+ [0.31% spent locally]\
+ [7.77% spent locally]\
+ [60.23% spent locally]\
+ [0.79% spent locally]\
+[5.07% spent locally]\
+\
+
+\b Rewrote VectorArrayNormalize to use PPC frsqrt instruction (with Newton-Rhapson refinement)\
+
+\b0 4865 frames, 128.7 seconds: 37.8 fps\
+[seconds spent locally, % of parent, % of total, # of samples]\
+[103.972710 -- 46787719721, 100.00%, 100.00%, 4866] Root\
+ [97.153160 -- 43718922078, 93.44%, 93.44%, 4866] CL_Frame\
+ [96.219348 -- 43298706398, 99.04%, 92.54%, 4918] SCR_UpdateScreen\
+ [20.873944 -- 9393274747, 21.69%, 20.08%, 524036] RB_SurfaceMesh\
+ [17.053245 -- 7673960266, 81.70%, 16.40%, 524036] LerpMeshVertexes\
+ [8.356579 -- 3760460537, 49.00%, 8.04%, 455917] LerpMeshVertexes 1\
+ [8.560159 -- 3852071404, 50.20%, 8.23%, 68119] LerpMeshVertexes 2\
+\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
+
+\b \cf3 [1.429376 -- 643219234, 16.70%, 1.37%, 68119] VectorArrayNormalize\
+\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
+
+\b0 \cf0 [83.30% spent locally]\
+ [0.80% spent locally]\
+ [18.30% spent locally]\
+ [78.31% spent locally]\
+ [0.96% spent locally]\
+[6.56% spent locally]\
+\
+\
+}
diff --git a/code/macosx/Q3Controller.h b/code/macosx/Q3Controller.h
new file mode 100755
index 0000000..426e437
--- /dev/null
+++ b/code/macosx/Q3Controller.h
@@ -0,0 +1,40 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#import <AppKit/AppKit.h>
+
+@interface Q3Controller : NSObject
+{
+ IBOutlet NSPanel *bannerPanel;
+}
+
+#ifndef DEDICATED
+- (IBAction)paste:(id)sender;
+- (IBAction)requestTerminate:(id)sender;
+
+- (void) showBanner;
+#endif
+
+- (void)quakeMain;
+
+@end
+
diff --git a/code/macosx/Q3Controller.m b/code/macosx/Q3Controller.m
new file mode 100755
index 0000000..7839d59
--- /dev/null
+++ b/code/macosx/Q3Controller.m
@@ -0,0 +1,435 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#import "Q3Controller.h"
+
+#import <Foundation/Foundation.h>
+#import <AppKit/AppKit.h>
+
+#include "client.h"
+#include "macosx_local.h"
+//#include "GameRanger SDK/gameranger.h"
+#ifdef OMNI_TIMER
+#import "macosx_timers.h"
+#endif
+
+#define MAX_ARGC 1024
+
+static qboolean Sys_IsProcessingTerminationRequest = qfalse;
+static void Sys_CreatePathToFile(NSString *path, NSDictionary *attributes);
+
+@interface Q3Controller (Private)
+- (void)quakeMain;
+@end
+
+@implementation Q3Controller
+
+#ifndef DEDICATED
+
+- (void)applicationDidFinishLaunching:(NSNotification *)notification;
+{
+ NS_DURING {
+ [self quakeMain];
+ } NS_HANDLER {
+ Sys_Error("%@", [localException reason]);
+ } NS_ENDHANDLER;
+ Sys_Quit();
+}
+
+- (void)applicationDidUnhide:(NSNotification *)notification;
+{
+ // Don't reactivate the game if we are asking whether to quit
+ if (Sys_IsProcessingTerminationRequest)
+ return;
+
+ if (!Sys_Unhide())
+ // Didn't work -- hide again so we should get another chance to unhide later
+ [NSApp hide: nil];
+}
+
+- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender;
+{
+ int choice;
+
+ if (!Sys_IsHidden) {
+ // We're terminating via -terminate:
+ return NSTerminateNow;
+ }
+
+ // Avoid reactivating GL when we unhide due to this panel
+ Sys_IsProcessingTerminationRequest = qtrue;
+ choice = NSRunAlertPanel(nil, @"Quit without saving?", @"Don't Quit", @"Quit", nil);
+ Sys_IsProcessingTerminationRequest = qfalse;
+
+ if (choice == NSAlertAlternateReturn)
+ return NSTerminateNow;
+
+ // Make sure we get re-hidden
+ [NSApp hide:nil];
+
+ return NSTerminateCancel;
+}
+
+// Actions
+
+- (IBAction)paste:(id)sender;
+{
+ int shiftWasDown, insertWasDown;
+ unsigned int currentTime;
+
+ currentTime = Sys_Milliseconds();
+ // Save the original keyboard state
+ shiftWasDown = keys[K_SHIFT].down;
+ insertWasDown = keys[K_INS].down;
+ // Fake a Shift-Insert keyboard event
+ keys[K_SHIFT].down = qtrue;
+ Sys_QueEvent(currentTime, SE_KEY, K_INS, qtrue, 0, NULL);
+ Sys_QueEvent(currentTime, SE_KEY, K_INS, qfalse, 0, NULL);
+ // Restore the original keyboard state
+ keys[K_SHIFT].down = shiftWasDown;
+ keys[K_INS].down = insertWasDown;
+}
+
+extern void CL_Quit_f(void);
+
+
+- (IBAction)requestTerminate:(id)sender;
+{
+ Com_Quit_f();
+ // UI_QuitMenu();
+}
+
+- (void)showBanner;
+{
+ static BOOL hasShownBanner = NO;
+
+ if (!hasShownBanner) {
+ cvar_t *showBanner;
+
+ hasShownBanner = YES;
+ showBanner = Cvar_Get("cl_showBanner", "1", 0);
+ if (showBanner->integer != 0) {
+ NSPanel *splashPanel;
+ NSImage *bannerImage;
+ NSRect bannerRect;
+ NSImageView *bannerImageView;
+
+ bannerImage = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForImageResource:@"banner.jpg"]];
+ bannerRect = NSMakeRect(0.0, 0.0, [bannerImage size].width, [bannerImage size].height);
+
+ splashPanel = [[NSPanel alloc] initWithContentRect:bannerRect styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO];
+
+ bannerImageView = [[NSImageView alloc] initWithFrame:bannerRect];
+ [bannerImageView setImage:bannerImage];
+ [splashPanel setContentView:bannerImageView];
+ [bannerImageView release];
+
+ [splashPanel center];
+ [splashPanel setHasShadow:YES];
+ [splashPanel orderFront: nil];
+ [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.5]];
+ [splashPanel close];
+
+ [bannerImage release];
+ }
+ }
+}
+
+// Services
+
+- (void)connectToServer:(NSPasteboard *)pasteboard userData:(NSString *)data error:(NSString **)error;
+{
+ NSArray *pasteboardTypes;
+
+ pasteboardTypes = [pasteboard types];
+ if ([pasteboardTypes containsObject:NSStringPboardType]) {
+ NSString *requestedServer;
+
+ requestedServer = [pasteboard stringForType:NSStringPboardType];
+ if (requestedServer) {
+ Cbuf_AddText(va("connect %s\n", [requestedServer cString]));
+ return;
+ }
+ }
+ *error = @"Unable to connect to server: could not find string on pasteboard";
+}
+
+- (void)performCommand:(NSPasteboard *)pasteboard userData:(NSString *)data error:(NSString **)error;
+{
+ NSArray *pasteboardTypes;
+
+ pasteboardTypes = [pasteboard types];
+ if ([pasteboardTypes containsObject:NSStringPboardType]) {
+ NSString *requestedCommand;
+
+ requestedCommand = [pasteboard stringForType:NSStringPboardType];
+ if (requestedCommand) {
+ Cbuf_AddText(va("%s\n", [requestedCommand cString]));
+ return;
+ }
+ }
+ *error = @"Unable to perform command: could not find string on pasteboard";
+}
+
+#endif
+
+- (void)quakeMain;
+{
+ NSAutoreleasePool *pool;
+ int argc = 0;
+ const char *argv[MAX_ARGC];
+ NSProcessInfo *processInfo;
+ NSArray *arguments;
+ unsigned int argumentIndex, argumentCount;
+ NSFileManager *defaultManager;
+ unsigned int commandLineLength;
+ NSString *installationPathKey, *installationPath;
+ char *cmdline;
+ BOOL foundDirectory;
+ NSString *appName, *demoAppName, *selectButton;
+ int count = 0;
+ pool = [[NSAutoreleasePool alloc] init];
+
+ [NSApp setServicesProvider:self];
+
+ processInfo = [NSProcessInfo processInfo];
+ arguments = [processInfo arguments];
+ argumentCount = [arguments count];
+ for (argumentIndex = 0; argumentIndex < argumentCount; argumentIndex++) {
+ NSString *arg;
+
+ arg = [arguments objectAtIndex:argumentIndex];
+ // Don't pass the Process Serial Number command line arg that the Window Server/Finder invokes us with
+ if ([arg hasPrefix: @"-psn_"])
+ continue;
+
+ argv[argc++] = strdup([arg cString]);
+ }
+
+ // Figure out where the level data is stored.
+ installationPathKey = @"RetailInstallationPath";
+
+ installationPath = [[NSUserDefaults standardUserDefaults] objectForKey:installationPathKey];
+ if (!installationPath) {
+ // Default to the directory containing the executable (which is where most users will want to put it
+ installationPath = [[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent];
+ }
+
+#if !defined(DEDICATED)
+ appName = [[[NSBundle mainBundle] infoDictionary] objectForKey: @"CFBundleName"];
+#else
+ // We are hard coding the app name here since the dedicated server is a tool, not a app bundle and does not have access to the Info.plist that the client app does. Suck.
+ appName = @"Quake3";
+#endif
+ demoAppName = appName;
+
+ while (YES) {
+ NSString *dataPath;
+ NSOpenPanel *openPanel;
+ int result;
+
+ foundDirectory = NO;
+ defaultManager = [NSFileManager defaultManager];
+ //NSLog(@"Candidate installation path = %@", installationPath);
+ dataPath = [installationPath stringByAppendingPathComponent: @"baseq3"];
+
+ if ([defaultManager fileExistsAtPath: dataPath]) {
+ // Check that the data directory contains at least one .pk3 file. We don't know what it will be named, so don't hard code a name (for example it might be named 'french.pk3' for a French release
+ NSArray *files;
+ unsigned int fileIndex;
+
+ files = [defaultManager directoryContentsAtPath: dataPath];
+ fileIndex = [files count];
+ while (fileIndex--) {
+ if ([[files objectAtIndex: fileIndex] hasSuffix: @"pk3"]) {
+ //NSLog(@"Found %@.", [files objectAtIndex: fileIndex]);
+ foundDirectory = YES;
+ break;
+ }
+ }
+ }
+
+ if (foundDirectory)
+ break;
+
+#ifdef DEDICATED
+ break;
+#warning TJW: We are hard coding the app name and default domain here since the dedicated server is a tool, not a app bundle and does not have access to the Info.plist that the client app does. Suck.
+ NSLog(@"Unable to determine installation directory. Please move the executable into the '%@' installation directory or add a '%@' key in the 'Q3DedicatedServer' defaults domain.", appName, installationPathKey, [[NSBundle mainBundle] bundleIdentifier]);
+ Sys_Quit();
+ exit(1);
+#else
+ selectButton = @"Select Retail Installation...";
+
+ result = NSRunAlertPanel(demoAppName, @"You need to select the installation directory for %@ (not any directory inside of it -- the installation directory itself).", selectButton, @"Quit", nil, appName);
+ switch (result) {
+ case NSAlertDefaultReturn:
+ break;
+ default:
+ Sys_Quit();
+ break;
+ }
+
+ openPanel = [NSOpenPanel openPanel];
+ [openPanel setAllowsMultipleSelection:NO];
+ [openPanel setCanChooseDirectories:YES];
+ [openPanel setCanChooseFiles:NO];
+ result = [openPanel runModalForDirectory:nil file:nil];
+ if (result == NSOKButton) {
+ NSArray *filenames;
+
+ filenames = [openPanel filenames];
+ if ([filenames count] == 1) {
+ installationPath = [filenames objectAtIndex:0];
+ [[NSUserDefaults standardUserDefaults] setObject:installationPath forKey:installationPathKey];
+ [[NSUserDefaults standardUserDefaults] synchronize];
+ }
+ }
+#endif
+ }
+
+ // Create the application support directory if it doesn't exist already
+ do {
+ NSArray *results;
+ NSString *libraryPath, *homePath, *filePath;
+ NSDictionary *attributes;
+
+ results = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
+ if (![results count])
+ break;
+
+ libraryPath = [results objectAtIndex: 0];
+ homePath = [libraryPath stringByAppendingPathComponent: @"Application Support"];
+ homePath = [homePath stringByAppendingPathComponent: appName];
+ filePath = [homePath stringByAppendingPathComponent: @"foo"];
+
+ attributes = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithUnsignedInt: 0750], NSFilePosixPermissions, nil];
+ NS_DURING {
+ Sys_CreatePathToFile(filePath, attributes);
+ Sys_SetDefaultHomePath([homePath fileSystemRepresentation]);
+ } NS_HANDLER {
+ NSLog(@"Exception: %@", localException);
+#ifndef DEDICATED
+ NSRunAlertPanel(nil, @"Unable to create '%@'. Please make sure that you have permission to write to this folder and re-run the game.", @"OK", nil, nil, homePath);
+#endif
+ Sys_Quit();
+ } NS_ENDHANDLER;
+ } while(0);
+
+ // Provoke the CD scanning code into looking up the CD.
+ Sys_CheckCD();
+
+ // Let the filesystem know where our local install is
+ Sys_SetDefaultInstallPath([installationPath cString]);
+
+ cmdline = NULL;
+#if 0
+ if (GRCheckFileForCmd()) {
+ GRGetWaitingCmd();
+ if (GRHasProperty( 'Exec' )) {
+ NSString *cfgPath, *grCfg;
+ cfgPath = [[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent];
+ cfgPath = [cfgPath stringByAppendingPathComponent: [NSString stringWithCString: GRGetPropertyStr( 'Exec' )]];
+ grCfg = [NSString stringWithContentsOfFile: cfgPath];
+ cmdline = malloc(strlen([grCfg cString])+1);
+ [grCfg getCString: cmdline];
+ }
+ }
+#endif
+ if (!cmdline) {
+ // merge the command line, this is kinda silly
+ for (commandLineLength = 1, argumentIndex = 1; argumentIndex < argc; argumentIndex++)
+ commandLineLength += strlen(argv[argumentIndex]) + 1;
+ cmdline = malloc(commandLineLength);
+ *cmdline = '\0';
+ for (argumentIndex = 1; argumentIndex < argc; argumentIndex++) {
+ if (argumentIndex > 1)
+ strcat(cmdline, " ");
+ strcat(cmdline, argv[argumentIndex]);
+ }
+ }
+ Com_Printf("command line: %s\n", cmdline);
+
+ Com_Init(cmdline);
+
+#ifndef DEDICATED
+ [NSApp activateIgnoringOtherApps:YES];
+#endif
+
+ while (1) {
+ Com_Frame();
+
+ if ((count & 15)==0) {
+ // We should think about doing this less frequently than every frame
+ [pool release];
+ pool = [[NSAutoreleasePool alloc] init];
+ }
+ }
+
+ [pool release];
+}
+
+@end
+
+
+
+// Creates any directories needed to be able to create a file at the specified path. Raises an exception on failure.
+static void Sys_CreatePathToFile(NSString *path, NSDictionary *attributes)
+{
+ NSArray *pathComponents;
+ unsigned int dirIndex, dirCount;
+ unsigned int startingIndex;
+ NSFileManager *manager;
+
+ manager = [NSFileManager defaultManager];
+ pathComponents = [path pathComponents];
+ dirCount = [pathComponents count] - 1;
+
+ startingIndex = 0;
+ for (dirIndex = startingIndex; dirIndex < dirCount; dirIndex++) {
+ NSString *partialPath;
+ BOOL fileExists;
+
+ partialPath = [NSString pathWithComponents:[pathComponents subarrayWithRange:NSMakeRange(0, dirIndex + 1)]];
+
+ // Don't use the 'fileExistsAtPath:isDirectory:' version since it doesn't traverse symlinks
+ fileExists = [manager fileExistsAtPath:partialPath];
+ if (!fileExists) {
+ if (![manager createDirectoryAtPath:partialPath attributes:attributes]) {
+ [NSException raise:NSGenericException format:@"Unable to create a directory at path: %@", partialPath];
+ }
+ } else {
+ NSDictionary *attributes;
+
+ attributes = [manager fileAttributesAtPath:partialPath traverseLink:YES];
+ if (![[attributes objectForKey:NSFileType] isEqualToString: NSFileTypeDirectory]) {
+ [NSException raise:NSGenericException format:@"Unable to write to path \"%@\" because \"%@\" is not a directory",
+ path, partialPath];
+ }
+ }
+ }
+}
+
+#ifdef DEDICATED
+void S_ClearSoundBuffer( void ) {
+}
+#endif
diff --git a/code/macosx/Quake3.icns b/code/macosx/Quake3.icns
new file mode 100755
index 0000000..30e3b67
--- /dev/null
+++ b/code/macosx/Quake3.icns
Binary files differ
diff --git a/code/macosx/Quake3.nib/classes.nib b/code/macosx/Quake3.nib/classes.nib
new file mode 100755
index 0000000..8436859
--- /dev/null
+++ b/code/macosx/Quake3.nib/classes.nib
@@ -0,0 +1,18 @@
+{
+ IBClasses = (
+ {
+ ACTIONS = {showHelp = id; };
+ CLASS = FirstResponder;
+ LANGUAGE = ObjC;
+ SUPERCLASS = NSObject;
+ },
+ {
+ ACTIONS = {paste = id; requestTerminate = id; };
+ CLASS = Q3Controller;
+ LANGUAGE = ObjC;
+ OUTLETS = {bannerPanel = id; };
+ SUPERCLASS = NSObject;
+ }
+ );
+ IBVersion = 1;
+} \ No newline at end of file
diff --git a/code/macosx/Quake3.nib/info.nib b/code/macosx/Quake3.nib/info.nib
new file mode 100755
index 0000000..41085f5
--- /dev/null
+++ b/code/macosx/Quake3.nib/info.nib
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd">
+<plist version="0.9">
+<dict>
+ <key>IBEditorPositions</key>
+ <dict>
+ <key>29</key>
+ <string>69 252 121 44 0 0 1152 746 </string>
+ </dict>
+ <key>IBFramework Version</key>
+ <string>248.0</string>
+ <key>IBOpenObjects</key>
+ <array>
+ <integer>29</integer>
+ </array>
+ <key>IBSystem Version</key>
+ <string>5V21</string>
+</dict>
+</plist>
diff --git a/code/macosx/Quake3.nib/objects.nib b/code/macosx/Quake3.nib/objects.nib
new file mode 100755
index 0000000..fbea89a
--- /dev/null
+++ b/code/macosx/Quake3.nib/objects.nib
Binary files differ
diff --git a/code/macosx/Quake3.pbproj/apple.pbxuser b/code/macosx/Quake3.pbproj/apple.pbxuser
new file mode 100755
index 0000000..ae03b31
--- /dev/null
+++ b/code/macosx/Quake3.pbproj/apple.pbxuser
@@ -0,0 +1,563 @@
+// !$*UTF8*$!
+{
+ 00F5ED38FEBA95B7C697A12F = {
+ activeExec = 0;
+ };
+ 00F5ED90FEBA9615C697A12F = {
+ activeExec = 0;
+ };
+ 016EAE0300B4BDD1C697A10E = {
+ activeExec = 0;
+ };
+ 0170304B00B4885DC697A10E = {
+ activeExec = 0;
+ executables = (
+ 1895FF35065E291B00F8B3F4,
+ );
+ };
+ 0170311C00B49352C697A10E = {
+ activeExec = 0;
+ };
+ 043627B100868916C697A10E = {
+ uiCtxt = {
+ sepNavIntBoundsRect = "{{0, 0}, {1586, 6033}}";
+ sepNavSelRange = "{136, 0}";
+ sepNavVisRect = "{{0, 0}, {711, 428}}";
+ };
+ };
+ 0654BA41FE8ECEE0C697A12F = {
+ activeBuildStyle = 07F3F50BFFE98E8EC697A10E;
+ activeExecutable = 1895FF30065E291B00F8B3F4;
+ activeTarget = 00F5ED90FEBA9615C697A12F;
+ codeSenseManager = 1895FF4C065E294000F8B3F4;
+ executables = (
+ 1895FF2F065E291B00F8B3F4,
+ 1895FF30065E291B00F8B3F4,
+ 1895FF31065E291B00F8B3F4,
+ 1895FF35065E291B00F8B3F4,
+ );
+ perUserDictionary = {
+ PBXConfiguration.PBXFileTableDataSource3.PBXExecutablesDataSource = {
+ PBXFileTableDataSourceColumnSortingDirectionKey = "-1";
+ PBXFileTableDataSourceColumnSortingKey = PBXExecutablesDataSource_NameID;
+ PBXFileTableDataSourceColumnWidthsKey = (
+ 22,
+ 843.7974,
+ );
+ PBXFileTableDataSourceColumnsKey = (
+ PBXExecutablesDataSource_ActiveFlagID,
+ PBXExecutablesDataSource_NameID,
+ );
+ };
+ PBXConfiguration.PBXFileTableDataSource3.PBXFileTableDataSource = {
+ PBXFileTableDataSourceColumnSortingDirectionKey = "-1";
+ PBXFileTableDataSourceColumnSortingKey = PBXFileDataSource_Filename_ColumnID;
+ PBXFileTableDataSourceColumnWidthsKey = (
+ 20,
+ 550,
+ 20,
+ 99,
+ 43,
+ 43,
+ 20,
+ );
+ PBXFileTableDataSourceColumnsKey = (
+ PBXFileDataSource_FiletypeID,
+ PBXFileDataSource_Filename_ColumnID,
+ PBXFileDataSource_Built_ColumnID,
+ PBXFileDataSource_ObjectSize_ColumnID,
+ PBXFileDataSource_Errors_ColumnID,
+ PBXFileDataSource_Warnings_ColumnID,
+ PBXFileDataSource_Target_ColumnID,
+ );
+ };
+ PBXConfiguration.PBXTargetDataSource.PBXTargetDataSource = {
+ PBXFileTableDataSourceColumnSortingDirectionKey = "-1";
+ PBXFileTableDataSourceColumnSortingKey = PBXFileDataSource_Filename_ColumnID;
+ PBXFileTableDataSourceColumnWidthsKey = (
+ 20,
+ 467,
+ 101,
+ 20,
+ 101,
+ 43,
+ 43,
+ );
+ PBXFileTableDataSourceColumnsKey = (
+ PBXFileDataSource_FiletypeID,
+ PBXFileDataSource_Filename_ColumnID,
+ PBXTargetDataSource_PrimaryAttribute,
+ PBXFileDataSource_Built_ColumnID,
+ PBXFileDataSource_ObjectSize_ColumnID,
+ PBXFileDataSource_Errors_ColumnID,
+ PBXFileDataSource_Warnings_ColumnID,
+ );
+ };
+ PBXPerProjectTemplateStateSaveDate = 106915007;
+ PBXPrepackagedSmartGroups_v2 = (
+ {
+ PBXTransientLocationAtTop = bottom;
+ absolutePathToBundle = "";
+ activationKey = OldTargetSmartGroup;
+ clz = PBXTargetSmartGroup;
+ description = "Displays all targets of the project.";
+ globalID = 1C37FABC04509CD000000102;
+ name = Targets;
+ preferences = {
+ image = Targets;
+ };
+ },
+ {
+ PBXTransientLocationAtTop = bottom;
+ absolutePathToBundle = "";
+ clz = PBXTargetSmartGroup2;
+ description = "Displays all targets of the project as well as nested build phases.";
+ globalID = 1C37FBAC04509CD000000102;
+ name = Targets;
+ preferences = {
+ image = Targets;
+ };
+ },
+ {
+ PBXTransientLocationAtTop = bottom;
+ absolutePathToBundle = "";
+ clz = PBXExecutablesSmartGroup;
+ description = "Displays all executables of the project.";
+ globalID = 1C37FAAC04509CD000000102;
+ name = Executables;
+ preferences = {
+ image = Executable;
+ };
+ },
+ {
+ " PBXTransientLocationAtTop " = bottom;
+ absolutePathToBundle = "";
+ clz = PBXErrorsWarningsSmartGroup;
+ description = "Displays files with errors or warnings.";
+ globalID = 1C08E77C0454961000C914BD;
+ name = "Errors and Warnings";
+ preferences = {
+ fnmatch = "";
+ image = WarningsErrors;
+ recursive = 1;
+ regex = "";
+ root = "<PROJECT>";
+ };
+ },
+ {
+ PBXTransientLocationAtTop = bottom;
+ absolutePathToBundle = "";
+ clz = PBXFilenameSmartGroup;
+ description = "Filters items in a given group (potentially recursively) based on matching the name with the regular expression of the filter.";
+ globalID = 1CC0EA4004350EF90044410B;
+ name = "Implementation Files";
+ preferences = {
+ canSave = 1;
+ fnmatch = "";
+ image = SmartFolder;
+ isLeaf = 0;
+ recursive = 1;
+ regex = "?*\\.[mcMC]";
+ root = "<PROJECT>";
+ };
+ },
+ {
+ PBXTransientLocationAtTop = bottom;
+ absolutePathToBundle = "";
+ clz = PBXFilenameSmartGroup;
+ description = "This group displays Interface Builder NIB Files.";
+ globalID = 1CC0EA4004350EF90041110B;
+ name = "NIB Files";
+ preferences = {
+ canSave = 1;
+ fnmatch = "*.nib";
+ image = SmartFolder;
+ isLeaf = 0;
+ recursive = 1;
+ regex = "";
+ root = "<PROJECT>";
+ };
+ },
+ {
+ PBXTransientLocationAtTop = no;
+ absolutePathToBundle = "";
+ clz = PBXFindSmartGroup;
+ description = "Displays Find Results.";
+ globalID = 1C37FABC05509CD000000102;
+ name = "Find Results";
+ preferences = {
+ image = spyglass;
+ };
+ },
+ {
+ PBXTransientLocationAtTop = no;
+ absolutePathToBundle = "";
+ clz = PBXBookmarksSmartGroup;
+ description = "Displays Project Bookmarks.";
+ globalID = 1C37FABC05539CD112110102;
+ name = Bookmarks;
+ preferences = {
+ image = Bookmarks;
+ };
+ },
+ {
+ PBXTransientLocationAtTop = bottom;
+ absolutePathToBundle = "";
+ clz = XCSCMSmartGroup;
+ description = "Displays files with interesting SCM status.";
+ globalID = E2644B35053B69B200211256;
+ name = SCM;
+ preferences = {
+ image = PBXRepository;
+ isLeaf = 0;
+ };
+ },
+ {
+ PBXTransientLocationAtTop = bottom;
+ absolutePathToBundle = "";
+ clz = PBXSymbolsSmartGroup;
+ description = "Displays all symbols for the project.";
+ globalID = 1C37FABC04509CD000100104;
+ name = "Project Symbols";
+ preferences = {
+ image = ProjectSymbols;
+ isLeaf = 1;
+ };
+ },
+ {
+ PBXTransientLocationAtTop = bottom;
+ absolutePathToBundle = "";
+ clz = PBXFilenameSmartGroup;
+ description = "Filters items in a given group (potentially recursively) based on matching the name with the regular expression of the filter.";
+ globalID = PBXTemplateMarker;
+ name = "Simple Filter SmartGroup";
+ preferences = {
+ canSave = 1;
+ fnmatch = "*.nib";
+ image = SmartFolder;
+ isLeaf = 0;
+ recursive = 1;
+ regex = "";
+ root = "<PROJECT>";
+ };
+ },
+ {
+ PBXTransientLocationAtTop = bottom;
+ absolutePathToBundle = "";
+ clz = PBXFilenameSmartGroup;
+ description = "Filters items in a given group (potentially recursively) based on matching the name with the regular expression of the filter.";
+ globalID = PBXTemplateMarker;
+ name = "Simple Regular Expression SmartGroup";
+ preferences = {
+ canSave = 1;
+ fnmatch = "";
+ image = SmartFolder;
+ isLeaf = 0;
+ recursive = 1;
+ regex = "?*\\.[mcMC]";
+ root = "<PROJECT>";
+ };
+ },
+ );
+ PBXWorkspaceContents = (
+ {
+ PBXProjectWorkspaceModule_StateKey_Rev39 = {
+ PBXProjectWorkspaceModule_DataSourceSelectionKey_Rev6 = {
+ BoundsStr = "{{0, 0}, {823, 735}}";
+ Rows = (
+ );
+ VisibleRectStr = "{{0, 0}, {823, 735}}";
+ };
+ PBXProjectWorkspaceModule_EditorOpen = false;
+ PBXProjectWorkspaceModule_EmbeddedNavigatorGroup = {
+ PBXSplitModuleInNavigatorKey = {
+ SplitCount = 1;
+ };
+ };
+ PBXProjectWorkspaceModule_GeometryKey_Rev15 = {
+ PBXProjectWorkspaceModule_SGTM_Geometry = {
+ _collapsingFrameDimension = 0;
+ _indexOfCollapsedView = 0;
+ _percentageOfCollapsedView = 0;
+ sizes = (
+ "{{0, 0}, {210, 752}}",
+ "{{210, 0}, {838, 752}}",
+ );
+ };
+ };
+ PBXProjectWorkspaceModule_OldDetailFrame = "{{0, 0}, {838, 752}}";
+ PBXProjectWorkspaceModule_OldEditorFrame = "{{0, 0}, {750, 480}}";
+ PBXProjectWorkspaceModule_OldSuperviewFrame = "{{210, 0}, {838, 752}}";
+ PBXProjectWorkspaceModule_SGTM = {
+ PBXBottomSmartGroupGIDs = (
+ 1C37FBAC04509CD000000102,
+ 1C37FAAC04509CD000000102,
+ 1C08E77C0454961000C914BD,
+ 1CC0EA4004350EF90044410B,
+ 1CC0EA4004350EF90041110B,
+ 1C37FABC05509CD000000102,
+ 1C37FABC05539CD112110102,
+ E2644B35053B69B200211256,
+ 1C37FABC04509CD000100104,
+ );
+ PBXSmartGroupTreeModuleColumnData = {
+ PBXSmartGroupTreeModuleColumnWidthsKey = (
+ 193,
+ );
+ PBXSmartGroupTreeModuleColumnsKey_v4 = (
+ MainColumn,
+ );
+ };
+ PBXSmartGroupTreeModuleOutlineStateKey_v7 = {
+ PBXSmartGroupTreeModuleOutlineStateExpansionKey = (
+ 1C37FBAC04509CD000000102,
+ 18A3D348065F659F006A719A,
+ 18A3D35B065F6655006A719A,
+ );
+ PBXSmartGroupTreeModuleOutlineStateSelectionKey = (
+ (
+ 2,
+ 1,
+ ),
+ );
+ PBXSmartGroupTreeModuleOutlineStateVisibleRectKey = "{{0, 0}, {193, 734}}";
+ };
+ PBXTopSmartGroupGIDs = (
+ );
+ };
+ };
+ },
+ );
+ "PBXWorkspaceContents:PBXConfiguration.PBXModule.PBXBuildResultsModule" = {
+ };
+ "PBXWorkspaceContents:PBXConfiguration.PBXModule.PBXCVSModule" = {
+ };
+ "PBXWorkspaceContents:PBXConfiguration.PBXModule.PBXDebugCLIModule" = {
+ };
+ "PBXWorkspaceContents:PBXConfiguration.PBXModule.PBXNavigatorGroup" = {
+ PBXSplitModuleInNavigatorKey = {
+ SplitCount = 1;
+ };
+ };
+ "PBXWorkspaceContents:PBXConfiguration.PBXModule.PBXProjectWorkspaceModule" = {
+ PBXProjectWorkspaceModule_StateKey_Rev39 = {
+ PBXProjectWorkspaceModule_DataSourceSelectionKey_Rev6 = {
+ BoundsStr = "{{0, 0}, {851, 4290}}";
+ Rows = (
+ 0,
+ );
+ VisibleRectStr = "{{0, 0}, {851, 735}}";
+ };
+ PBXProjectWorkspaceModule_EditorOpen = false;
+ PBXProjectWorkspaceModule_EmbeddedNavigatorGroup = {
+ PBXSplitModuleInNavigatorKey = {
+ SplitCount = 1;
+ };
+ };
+ PBXProjectWorkspaceModule_GeometryKey_Rev15 = {
+ PBXProjectWorkspaceModule_SGTM_Geometry = {
+ _collapsingFrameDimension = 0;
+ _indexOfCollapsedView = 0;
+ _percentageOfCollapsedView = 0;
+ sizes = (
+ "{{0, 0}, {182, 752}}",
+ "{{182, 0}, {866, 752}}",
+ );
+ };
+ };
+ PBXProjectWorkspaceModule_OldDetailFrame = "{{0, 0}, {866, 752}}";
+ PBXProjectWorkspaceModule_OldEditorFrame = "{{0, 0}, {750, 480}}";
+ PBXProjectWorkspaceModule_OldSuperviewFrame = "{{182, 0}, {866, 752}}";
+ PBXProjectWorkspaceModule_SGTM = {
+ PBXBottomSmartGroupGIDs = (
+ 1C37FBAC04509CD000000102,
+ 1C37FAAC04509CD000000102,
+ 1C08E77C0454961000C914BD,
+ 1CC0EA4004350EF90044410B,
+ 1CC0EA4004350EF90041110B,
+ 1C37FABC05509CD000000102,
+ 1C37FABC05539CD112110102,
+ E2644B35053B69B200211256,
+ 1C37FABC04509CD000100104,
+ );
+ PBXSmartGroupTreeModuleColumnData = {
+ PBXSmartGroupTreeModuleColumnWidthsKey = (
+ 165,
+ );
+ PBXSmartGroupTreeModuleColumnsKey_v4 = (
+ MainColumn,
+ );
+ };
+ PBXSmartGroupTreeModuleOutlineStateKey_v7 = {
+ PBXSmartGroupTreeModuleOutlineStateExpansionKey = (
+ 1C37FBAC04509CD000000102,
+ 18A3D340065F651C006A719A,
+ 18A3D341065F651D006A719A,
+ );
+ PBXSmartGroupTreeModuleOutlineStateSelectionKey = (
+ (
+ 1,
+ ),
+ );
+ PBXSmartGroupTreeModuleOutlineStateVisibleRectKey = "{{0, 0}, {165, 734}}";
+ };
+ PBXTopSmartGroupGIDs = (
+ );
+ };
+ };
+ };
+ PBXWorkspaceGeometries = (
+ {
+ Frame = "{{0, 0}, {1048, 752}}";
+ PBXProjectWorkspaceModule_GeometryKey_Rev15 = {
+ };
+ RubberWindowFrame = "17 182 1048 794 0 0 1680 1028 ";
+ },
+ );
+ "PBXWorkspaceGeometries:PBXConfiguration.PBXModule.PBXBuildResultsModule" = {
+ Frame = "{{0, 0}, {755, 578}}";
+ PBXModuleWindowStatusBarHidden = YES;
+ RubberWindowFrame = "612 317 755 599 0 0 1680 1028 ";
+ };
+ "PBXWorkspaceGeometries:PBXConfiguration.PBXModule.PBXCVSModule" = {
+ Frame = "{{0, 0}, {482, 276}}";
+ RubberWindowFrame = "590 449 482 318 0 0 1680 1028 ";
+ };
+ "PBXWorkspaceGeometries:PBXConfiguration.PBXModule.PBXDebugCLIModule" = {
+ Frame = "{{0, 0}, {400, 201}}";
+ PBXModuleWindowStatusBarHidden = YES;
+ RubberWindowFrame = "50 1000 400 222 0 0 1680 1028 ";
+ };
+ "PBXWorkspaceGeometries:PBXConfiguration.PBXModule.PBXNavigatorGroup" = {
+ Frame = "{{0, 0}, {750, 460}}";
+ RubberWindowFrame = "428 357 750 502 0 0 1680 1028 ";
+ };
+ "PBXWorkspaceGeometries:PBXConfiguration.PBXModule.PBXProjectWorkspaceModule" = {
+ Frame = "{{0, 0}, {1048, 752}}";
+ PBXProjectWorkspaceModule_GeometryKey_Rev15 = {
+ PBXProjectWorkspaceModule_BuildResultsWindowVisible = true;
+ };
+ RubberWindowFrame = "17 182 1048 794 0 0 1680 1028 ";
+ };
+ PBXWorkspaceStateSaveDate = 106915007;
+ };
+ sourceControlManager = 1895FF4B065E294000F8B3F4;
+ userBuildSettings = {
+ };
+ };
+ 0654BA5CFE8ECEE0C697A12F = {
+ activeExec = 0;
+ executables = (
+ 1895FF2F065E291B00F8B3F4,
+ );
+ };
+ 1895FF2F065E291B00F8B3F4 = {
+ activeArgIndex = 2147483647;
+ activeArgIndices = (
+ );
+ argumentStrings = (
+ );
+ configStateDict = {
+ };
+ debuggerPlugin = GDBDebugging;
+ dylibVariantSuffix = "";
+ enableDebugStr = 1;
+ environmentEntries = (
+ );
+ isa = PBXExecutable;
+ name = "Quake3 (Application)";
+ shlibInfoDictList = (
+ );
+ sourceDirectories = (
+ );
+ };
+ 1895FF30065E291B00F8B3F4 = {
+ activeArgIndex = 2147483647;
+ activeArgIndices = (
+ );
+ argumentStrings = (
+ );
+ configStateDict = {
+ };
+ debuggerPlugin = GDBDebugging;
+ enableDebugStr = 1;
+ environmentEntries = (
+ );
+ isa = PBXExecutable;
+ name = "Dedicated Server G4";
+ shlibInfoDictList = (
+ );
+ sourceDirectories = (
+ );
+ };
+ 1895FF31065E291B00F8B3F4 = {
+ activeArgIndex = 2147483647;
+ activeArgIndices = (
+ );
+ argumentStrings = (
+ );
+ configStateDict = {
+ };
+ debuggerPlugin = GDBDebugging;
+ enableDebugStr = 1;
+ environmentEntries = (
+ );
+ isa = PBXExecutable;
+ name = "Quake3 G4 (Application)";
+ shlibInfoDictList = (
+ );
+ sourceDirectories = (
+ );
+ };
+ 1895FF35065E291B00F8B3F4 = {
+ activeArgIndex = 2147483647;
+ activeArgIndices = (
+ );
+ argumentStrings = (
+ );
+ configStateDict = {
+ };
+ debuggerPlugin = GDBDebugging;
+ enableDebugStr = 1;
+ environmentEntries = (
+ );
+ isa = PBXExecutable;
+ name = "Dedicated Server";
+ shlibInfoDictList = (
+ );
+ sourceDirectories = (
+ );
+ };
+ 1895FF4B065E294000F8B3F4 = {
+ isa = PBXSourceControlManager;
+ scmConfiguration = {
+ };
+ scmType = scm.cvs;
+ };
+ 1895FF4C065E294000F8B3F4 = {
+ indexTemplatePath = "";
+ isa = PBXCodeSenseManager;
+ usesDefaults = 1;
+ wantsCodeCompletion = 1;
+ wantsCodeCompletionAutoPopup = 0;
+ wantsCodeCompletionAutoSuggestions = 0;
+ wantsCodeCompletionCaseSensitivity = 1;
+ wantsCodeCompletionOnlyMatchingItems = 1;
+ wantsCodeCompletionParametersIncluded = 1;
+ wantsCodeCompletionPlaceholdersInserted = 1;
+ wantsCodeCompletionTabCompletes = 1;
+ wantsIndex = 1;
+ };
+ 4FF0904804896C0E00030DA8 = {
+ activeExec = 0;
+ executables = (
+ 1895FF31065E291B00F8B3F4,
+ );
+ };
+ 4FF0912704896C1600030DA8 = {
+ activeExec = 0;
+ executables = (
+ 1895FF30065E291B00F8B3F4,
+ );
+ };
+}
diff --git a/code/macosx/Quake3.pbproj/project.pbxproj b/code/macosx/Quake3.pbproj/project.pbxproj
new file mode 100755
index 0000000..9af4f36
--- /dev/null
+++ b/code/macosx/Quake3.pbproj/project.pbxproj
@@ -0,0 +1,11802 @@
+// !$*UTF8*$!
+{
+ archiveVersion = 1;
+ classes = {
+ };
+ objectVersion = 39;
+ objects = {
+ 00E9D914FEDB4D29C697A12F = {
+ isa = PBXFileReference;
+ lastKnownFileType = wrapper.framework;
+ name = CoreAudio.framework;
+ path = /System/Library/Frameworks/CoreAudio.framework;
+ refType = 0;
+ sourceTree = "<absolute>";
+ };
+ 00E9D91DFEDB5295C697A12F = {
+ fileRef = 00E9D914FEDB4D29C697A12F;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 00F5ED38FEBA95B7C697A12F = {
+ buildPhases = (
+ 00F5ED39FEBA95B7C697A12F,
+ 00F5ED55FEBA95B7C697A12F,
+ 00F5ED56FEBA95B7C697A12F,
+ 00F5ED77FEBA95B7C697A12F,
+ 00F5ED78FEBA95B7C697A12F,
+ );
+ buildSettings = {
+ FRAMEWORK_SEARCH_PATHS = "";
+ HEADER_SEARCH_PATHS = "";
+ INSTALL_PATH = "/Users/Shared/$(USER)/InstalledProducts";
+ LIBRARY_SEARCH_PATHS = "";
+ OTHER_LDFLAGS = "-bundle -undefined error";
+ OTHER_REZFLAGS = "";
+ PRODUCT_NAME = qagame;
+ PROFILE_FLAGS = "";
+ SECTORDER_FLAGS = "";
+ WARNING_CFLAGS = "-Wall -Wno-four-char-constants -Wno-unknown-pragmas";
+ WRAPPER_EXTENSION = bundle;
+ };
+ dependencies = (
+ );
+ isa = PBXBundleTarget;
+ name = qagame;
+ productInstallPath = "/Users/Shared/$(USER)/InstalledProducts";
+ productName = game;
+ productReference = 07F3F507FFE98E8EC697A10E;
+ productSettingsXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
+<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
+<plist version=\"1.0\">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>English</string>
+ <key>CFBundleExecutable</key>
+ <string>qagame</string>
+ <key>CFBundleGetInfoString</key>
+ <string>Quake 3 Arena (1.16)</string>
+ <key>CFBundleIconFile</key>
+ <string>Quake3.icns</string>
+ <key>CFBundleIdentifier</key>
+ <string></string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string></string>
+ <key>CFBundlePackageType</key>
+ <string>APPL</string>
+ <key>CFBundleShortVersionString</key>
+ <string>1.16</string>
+ <key>CFBundleSignature</key>
+ <string>????</string>
+ <key>CFBundleVersion</key>
+ <string>0.0.1d1</string>
+</dict>
+</plist>
+";
+ };
+ 00F5ED39FEBA95B7C697A12F = {
+ buildActionMask = 2147483647;
+ files = (
+ 13380E0F00ADFAACC697A10E,
+ 13380E1300ADFAD5C697A10E,
+ 13380E1500ADFB0CC697A10E,
+ 13380E1700ADFBFDC697A10E,
+ 13380E1900ADFC10C697A10E,
+ 13380E1B00ADFC22C697A10E,
+ 13380E1D00ADFC32C697A10E,
+ 13380E1F00ADFC43C697A10E,
+ 13380E2500ADFCA7C697A10E,
+ );
+ isa = PBXHeadersBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 00F5ED55FEBA95B7C697A12F = {
+ buildActionMask = 2147483647;
+ files = (
+ );
+ isa = PBXResourcesBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 00F5ED56FEBA95B7C697A12F = {
+ buildActionMask = 2147483647;
+ files = (
+ 13380E0900ADF941C697A10E,
+ 13380E0B00ADFA16C697A10E,
+ 13380E0C00ADFA72C697A10E,
+ 13380E0D00ADFA94C697A10E,
+ 13380E0E00ADFA9EC697A10E,
+ 13380E1000ADFAACC697A10E,
+ 13380E1100ADFAACC697A10E,
+ 13380E1200ADFACAC697A10E,
+ 13380E1400ADFAD5C697A10E,
+ 13380E1600ADFB0CC697A10E,
+ 13380E1800ADFBFDC697A10E,
+ 13380E1A00ADFC10C697A10E,
+ 13380E1C00ADFC22C697A10E,
+ 13380E1E00ADFC32C697A10E,
+ 13380E2000ADFC43C697A10E,
+ 13380E2100ADFC59C697A10E,
+ 13380E2200ADFC78C697A10E,
+ 13380E2300ADFC85C697A10E,
+ 13380E2400ADFC9CC697A10E,
+ 13380E2600ADFCA7C697A10E,
+ 13380E2700ADFCBDC697A10E,
+ 13380E2800ADFCC8C697A10E,
+ 13380E2900ADFCD1C697A10E,
+ 13380E2A00ADFCEBC697A10E,
+ 13380E2B00ADFCF6C697A10E,
+ 13380E2C00ADFD01C697A10E,
+ 13380E2D00ADFD1FC697A10E,
+ 13380E2E00ADFD28C697A10E,
+ 13380E2F00ADFD38C697A10E,
+ 13380E3000ADFD46C697A10E,
+ 13380E3100ADFD58C697A10E,
+ 13380E3200ADFD71C697A10E,
+ 13380E3300ADFD85C697A10E,
+ );
+ isa = PBXSourcesBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 00F5ED77FEBA95B7C697A12F = {
+ buildActionMask = 2147483647;
+ files = (
+ );
+ isa = PBXFrameworksBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 00F5ED78FEBA95B7C697A12F = {
+ buildActionMask = 2147483647;
+ files = (
+ );
+ isa = PBXRezBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 00F5ED90FEBA9615C697A12F = {
+ buildPhases = (
+ 00F5ED91FEBA9615C697A12F,
+ 00F5ED92FEBA9615C697A12F,
+ 00F5ED93FEBA9615C697A12F,
+ 00F5ED94FEBA9615C697A12F,
+ 00F5ED95FEBA9615C697A12F,
+ );
+ buildSettings = {
+ FRAMEWORK_SEARCH_PATHS = "";
+ HEADER_SEARCH_PATHS = "";
+ INSTALL_PATH = "/Users/Shared/$(USER)/InstalledProducts";
+ LIBRARY_SEARCH_PATHS = "";
+ OTHER_LDFLAGS = "-bundle -undefined error";
+ OTHER_REZFLAGS = "";
+ PRODUCT_NAME = cgame;
+ PROFILE_FLAGS = "";
+ SECTORDER_FLAGS = "";
+ WARNING_CFLAGS = "-Wall -Wno-four-char-constants -Wno-unknown-pragmas";
+ WRAPPER_EXTENSION = bundle;
+ };
+ dependencies = (
+ );
+ isa = PBXBundleTarget;
+ name = cgame;
+ productInstallPath = "/Users/Shared/$(USER)/InstalledProducts";
+ productName = cgame;
+ productReference = 07F3F508FFE98E8EC697A10E;
+ productSettingsXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
+<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
+<plist version=\"1.0\">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>English</string>
+ <key>CFBundleExecutable</key>
+ <string></string>
+ <key>CFBundleGetInfoString</key>
+ <string></string>
+ <key>CFBundleIconFile</key>
+ <string></string>
+ <key>CFBundleIdentifier</key>
+ <string></string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string></string>
+ <key>CFBundlePackageType</key>
+ <string>BNDL</string>
+ <key>CFBundleShortVersionString</key>
+ <string></string>
+ <key>CFBundleSignature</key>
+ <string>????</string>
+ <key>CFBundleVersion</key>
+ <string>0.0.1d1</string>
+</dict>
+</plist>
+";
+ };
+ 00F5ED91FEBA9615C697A12F = {
+ buildActionMask = 2147483647;
+ files = (
+ 13380E3600ADFDCFC697A10E,
+ 13380E5100AE0235C697A10E,
+ );
+ isa = PBXHeadersBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 00F5ED92FEBA9615C697A12F = {
+ buildActionMask = 2147483647;
+ files = (
+ );
+ isa = PBXResourcesBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 00F5ED93FEBA9615C697A12F = {
+ buildActionMask = 2147483647;
+ files = (
+ 13380E3400ADFDA1C697A10E,
+ 13380E3500ADFDA1C697A10E,
+ 13380E3700ADFDCFC697A10E,
+ 13380E3800ADFDCFC697A10E,
+ 13380E3900ADFDE1C697A10E,
+ 13380E3B00ADFE0CC697A10E,
+ 13380E3C00ADFE1EC697A10E,
+ 13380E3D00ADFE24C697A10E,
+ 13380E3E00ADFE3DC697A10E,
+ 13380E3F00ADFE4AC697A10E,
+ 13380E4000ADFE58C697A10E,
+ 13380E4100ADFE6BC697A10E,
+ 13380E4200ADFE7AC697A10E,
+ 13380E4300ADFE88C697A10E,
+ 13380E4400ADFE97C697A10E,
+ 13380E4500ADFEA7C697A10E,
+ 13380E4600ADFEB8C697A10E,
+ 13380E4700ADFEC9C697A10E,
+ 13380E4800ADFED7C697A10E,
+ 13380E4900ADFEE7C697A10E,
+ 13380E4A00ADFEF5C697A10E,
+ 13380E4B00ADFF05C697A10E,
+ 13380E4C00ADFF27C697A10E,
+ 13380E4F00AE0112C697A10E,
+ 13380E5000AE020FC697A10E,
+ 13380E5200AE0235C697A10E,
+ );
+ isa = PBXSourcesBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 00F5ED94FEBA9615C697A12F = {
+ buildActionMask = 2147483647;
+ files = (
+ );
+ isa = PBXFrameworksBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 00F5ED95FEBA9615C697A12F = {
+ buildActionMask = 2147483647;
+ files = (
+ );
+ isa = PBXRezBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+//000
+//001
+//002
+//003
+//004
+//010
+//011
+//012
+//013
+//014
+ 011F78F200B25B65C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = macosx_qgl.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 011F78F300B25B66C697A10E = {
+ fileRef = 011F78F200B25B65C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 012AD90700868211C697A10E = {
+ children = (
+ 012AD90800868211C697A10E,
+ 012AD90900868211C697A10E,
+ 012AD90A00868211C697A10E,
+ 012AD90B00868211C697A10E,
+ 012AD90C00868211C697A10E,
+ 012AD90D00868211C697A10E,
+ 012AD90E00868211C697A10E,
+ 012AD90F00868211C697A10E,
+ 012AD91000868211C697A10E,
+ 012AD91100868211C697A10E,
+ 012AD91200868211C697A10E,
+ 012AD91300868211C697A10E,
+ 012AD91400868211C697A10E,
+ 012AD91500868211C697A10E,
+ 012AD91600868211C697A10E,
+ 012AD91700868211C697A10E,
+ 012AD91800868211C697A10E,
+ 012AD91900868211C697A10E,
+ 012AD91A00868211C697A10E,
+ 012AD91B00868211C697A10E,
+ 012AD91C00868211C697A10E,
+ 012AD91D00868211C697A10E,
+ 012AD91E00868211C697A10E,
+ 012AD91F00868211C697A10E,
+ 012AD92000868211C697A10E,
+ 012AD92100868211C697A10E,
+ 012AD92200868211C697A10E,
+ 012AD92300868211C697A10E,
+ 012AD92400868211C697A10E,
+ 012AD92500868211C697A10E,
+ 012AD92600868211C697A10E,
+ 012AD92700868211C697A10E,
+ 012AD92800868211C697A10E,
+ 012AD92900868211C697A10E,
+ 012AD92A00868211C697A10E,
+ 012AD92B00868211C697A10E,
+ 012AD92C00868211C697A10E,
+ 012AD92D00868211C697A10E,
+ 012AD92E00868211C697A10E,
+ 012AD92F00868211C697A10E,
+ 012AD93000868211C697A10E,
+ 012AD93100868211C697A10E,
+ 012AD93200868211C697A10E,
+ 012AD93300868211C697A10E,
+ 012AD93400868211C697A10E,
+ 012AD93500868211C697A10E,
+ 012AD93600868211C697A10E,
+ 012AD93700868211C697A10E,
+ 012AD93800868211C697A10E,
+ 012AD93900868211C697A10E,
+ 012AD93A00868211C697A10E,
+ 012AD93B00868211C697A10E,
+ 012AD93C00868211C697A10E,
+ );
+ isa = PBXGroup;
+ path = botlib;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD90800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = aasfile.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD90900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_aas_bsp.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD90A00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = be_aas_bspq3.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD90B00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = be_aas_cluster.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD90C00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_aas_cluster.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD90D00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = be_aas_debug.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD90E00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_aas_debug.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD90F00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_aas_def.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD91000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = be_aas_entity.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD91100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_aas_entity.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD91200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = be_aas_file.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD91300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_aas_file.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD91400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_aas_funcs.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD91500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = be_aas_main.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD91600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_aas_main.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD91700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = be_aas_move.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD91800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_aas_move.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD91900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = be_aas_optimize.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD91A00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_aas_optimize.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD91B00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = be_aas_reach.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD91C00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_aas_reach.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD91D00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = be_aas_route.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD91E00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_aas_route.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD91F00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = be_aas_routealt.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD92000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_aas_routealt.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD92100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = be_aas_sample.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD92200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_aas_sample.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD92300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = be_ai_char.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD92400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = be_ai_chat.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD92500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = be_ai_gen.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD92600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = be_ai_goal.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD92700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = be_ai_move.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD92800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = be_ai_weap.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD92900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = be_ai_weight.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD92A00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_ai_weight.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD92B00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = be_ea.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD92C00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = be_interface.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD92D00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_interface.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD92E00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = l_crc.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD92F00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = l_crc.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD93000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = l_libvar.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD93100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = l_libvar.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD93200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = l_log.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD93300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = l_log.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD93400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = l_memory.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD93500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = l_memory.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD93600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = l_precomp.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD93700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = l_precomp.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD93800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = l_script.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD93900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = l_script.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD93A00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = l_struct.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD93B00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = l_struct.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD93C00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = l_utils.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD93D00868211C697A10E = {
+ children = (
+ 012AD93E00868211C697A10E,
+ 012AD93F00868211C697A10E,
+ 012AD94000868211C697A10E,
+ 012AD94100868211C697A10E,
+ 012AD94200868211C697A10E,
+ 012AD94300868211C697A10E,
+ 012AD94400868211C697A10E,
+ 012AD94500868211C697A10E,
+ 012AD94600868211C697A10E,
+ 012AD94700868211C697A10E,
+ 012AD94800868211C697A10E,
+ 012AD94900868211C697A10E,
+ 012AD94A00868211C697A10E,
+ 012AD94B00868211C697A10E,
+ 012AD94C00868211C697A10E,
+ 012AD94D00868211C697A10E,
+ 012AD94E00868211C697A10E,
+ 012AD94F00868211C697A10E,
+ 012AD95000868211C697A10E,
+ 012AD95100868211C697A10E,
+ 012AD95200868211C697A10E,
+ 012AD95300868211C697A10E,
+ 012AD95400868211C697A10E,
+ 012AD95500868211C697A10E,
+ 012AD95600868211C697A10E,
+ 012AD95700868211C697A10E,
+ 012AD95800868211C697A10E,
+ 012AD95900868211C697A10E,
+ 012AD95A00868211C697A10E,
+ 012AD95B00868211C697A10E,
+ 012AD95C00868211C697A10E,
+ 012AD95D00868211C697A10E,
+ 012AD95E00868211C697A10E,
+ 012AD95F00868211C697A10E,
+ 012AD96000868211C697A10E,
+ 012AD96100868211C697A10E,
+ 012AD96200868211C697A10E,
+ 012AD96300868211C697A10E,
+ 012AD96400868211C697A10E,
+ 012AD96500868211C697A10E,
+ 012AD96600868211C697A10E,
+ 012AD96700868211C697A10E,
+ 012AD96800868211C697A10E,
+ 012AD96900868211C697A10E,
+ 012AD96A00868211C697A10E,
+ 012AD96B00868211C697A10E,
+ 012AD96C00868211C697A10E,
+ 012AD96D00868211C697A10E,
+ 012AD96E00868211C697A10E,
+ 012AD96F00868211C697A10E,
+ 012AD97000868211C697A10E,
+ 012AD97100868211C697A10E,
+ 012AD97200868211C697A10E,
+ 012AD97300868211C697A10E,
+ 012AD97400868211C697A10E,
+ 012AD97500868211C697A10E,
+ 012AD97600868211C697A10E,
+ 012AD97700868211C697A10E,
+ 012AD97800868211C697A10E,
+ 012AD97900868211C697A10E,
+ 012AD97A00868211C697A10E,
+ 012AD97B00868211C697A10E,
+ 012AD97C00868211C697A10E,
+ 012AD97D00868211C697A10E,
+ 012AD97E00868211C697A10E,
+ 012AD97F00868211C697A10E,
+ 012AD98000868211C697A10E,
+ 012AD98100868211C697A10E,
+ 012AD98200868211C697A10E,
+ 012AD98300868211C697A10E,
+ 012AD98400868211C697A10E,
+ 012AD98500868211C697A10E,
+ 012AD98600868211C697A10E,
+ 012AD98700868211C697A10E,
+ 012AD98800868211C697A10E,
+ 012AD98900868211C697A10E,
+ 012AD98A00868211C697A10E,
+ 012AD98B00868211C697A10E,
+ 012AD98C00868211C697A10E,
+ );
+ isa = PBXGroup;
+ path = bspc;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD93E00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = _files.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD93F00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = aas_areamerging.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD94000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = aas_areamerging.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD94100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = aas_cfg.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD94200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = aas_cfg.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD94300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = aas_create.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD94400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = aas_create.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD94500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = aas_edgemelting.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD94600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = aas_edgemelting.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD94700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = aas_facemerging.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD94800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = aas_facemerging.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD94900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = aas_file.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD94A00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = aas_file.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD94B00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = aas_gsubdiv.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD94C00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = aas_gsubdiv.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD94D00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = aas_map.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD94E00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = aas_map.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD94F00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = aas_prunenodes.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD95000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = aas_prunenodes.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD95100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = aas_store.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD95200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = aas_store.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD95300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = aasfile.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD95400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = be_aas_bspc.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD95500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_aas_bspc.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD95600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = brushbsp.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD95700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = bspc.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD95800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cfgq3.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD95900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = csg.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD95A00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = faces.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD95B00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = gldraw.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD95C00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = glfile.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD95D00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = l_bsp_ent.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD95E00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = l_bsp_ent.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD95F00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = l_bsp_hl.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD96000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = l_bsp_hl.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD96100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = l_bsp_q1.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD96200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = l_bsp_q1.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD96300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = l_bsp_q2.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD96400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = l_bsp_q2.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD96500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = l_bsp_q3.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD96600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = l_bsp_q3.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD96700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = l_bsp_sin.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD96800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = l_bsp_sin.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD96900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = l_cmd.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD96A00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = l_cmd.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD96B00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = l_log.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD96C00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = l_log.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD96D00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = l_math.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD96E00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = l_math.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD96F00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = l_mem.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD97000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = l_mem.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD97100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = l_poly.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD97200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = l_poly.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD97300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = l_qfiles.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD97400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = l_qfiles.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD97500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = l_threads.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD97600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = l_threads.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD97700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = l_utils.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD97800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = l_utils.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD97900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = leakfile.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD97A00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = map.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD97B00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = map_hl.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD97C00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = map_q1.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD97D00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = map_q2.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD97E00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = map_q3.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD97F00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = map_sin.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD98000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = nodraw.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD98100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = portals.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD98200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = prtfile.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD98300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = q2files.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD98400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = q3files.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD98500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = qbsp.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD98600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = qfiles.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD98700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = sinfiles.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD98800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = tetrahedron.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD98900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = tetrahedron.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD98A00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = textures.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD98B00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = tree.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD98C00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = writebsp.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD98D00868211C697A10E = {
+ children = (
+ 012AD98E00868211C697A10E,
+ 012AD98F00868211C697A10E,
+ 012AD99000868211C697A10E,
+ 012AD99100868211C697A10E,
+ 012AD99200868211C697A10E,
+ 012AD99300868211C697A10E,
+ 012AD99400868211C697A10E,
+ 012AD99500868211C697A10E,
+ 012AD99600868211C697A10E,
+ 012AD99700868211C697A10E,
+ 012AD99800868211C697A10E,
+ 012AD99900868211C697A10E,
+ 012AD99A00868211C697A10E,
+ 012AD99B00868211C697A10E,
+ 012AD99C00868211C697A10E,
+ 012AD99D00868211C697A10E,
+ 012AD99E00868211C697A10E,
+ 012AD99F00868211C697A10E,
+ 012AD9A000868211C697A10E,
+ 012AD9A100868211C697A10E,
+ 012AD9A200868211C697A10E,
+ 012AD9A300868211C697A10E,
+ 012AD9A400868211C697A10E,
+ );
+ isa = PBXGroup;
+ path = cgame;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD98E00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cg_consolecmds.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD98F00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cg_draw.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD99000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cg_drawtools.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD99100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cg_effects.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD99200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cg_ents.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD99300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cg_event.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD99400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cg_info.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD99500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = cg_local.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD99600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cg_localents.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD99700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cg_main.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD99800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cg_marks.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD99900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cg_newdraw.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD99A00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cg_players.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD99B00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cg_playerstate.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD99C00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cg_predict.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD99D00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = cg_public.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD99E00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cg_scoreboard.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD99F00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cg_servercmds.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9A000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cg_snapshot.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9A100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cg_syscalls.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9A200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cg_view.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9A300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cg_weapons.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9A400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = tr_types.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9A500868211C697A10E = {
+ children = (
+ 012AD9A600868211C697A10E,
+ 012AD9A700868211C697A10E,
+ 012AD9A800868211C697A10E,
+ 012AD9A900868211C697A10E,
+ 012AD9AA00868211C697A10E,
+ 012AD9AB00868211C697A10E,
+ 012AD9AC00868211C697A10E,
+ 012AD9AD00868211C697A10E,
+ 012AD9AE00868211C697A10E,
+ 012AD9AF00868211C697A10E,
+ 012AD9B000868211C697A10E,
+ 012AD9B100868211C697A10E,
+ 012AD9B200868211C697A10E,
+ 012AD9B300868211C697A10E,
+ 012AD9B400868211C697A10E,
+ 012AD9B500868211C697A10E,
+ 012AD9B600868211C697A10E,
+ 012AD9B700868211C697A10E,
+ 012AD9B800868211C697A10E,
+ );
+ isa = PBXGroup;
+ path = client;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9A600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cl_cgame.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9A700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cl_cin.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9A800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cl_console.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9A900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cl_input.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9AA00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cl_keys.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9AB00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cl_main.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9AC00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cl_net_chan.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9AD00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cl_parse.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9AE00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cl_scrn.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9AF00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cl_ui.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9B000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = client.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9B100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = keys.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9B200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = snd_adpcm.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9B300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = snd_dma.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9B400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = snd_local.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9B500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = snd_mem.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9B600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = snd_mix.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9B700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = snd_public.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012AD9B800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = snd_wavelet.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA2400868211C697A10E = {
+ children = (
+ 012ADA2500868211C697A10E,
+ 012ADA2600868211C697A10E,
+ 012ADA2700868211C697A10E,
+ 012ADA2800868211C697A10E,
+ 012ADA2900868211C697A10E,
+ 012ADA2A00868211C697A10E,
+ 012ADA2B00868211C697A10E,
+ 012ADA2C00868211C697A10E,
+ 012ADA2D00868211C697A10E,
+ 012ADA2E00868211C697A10E,
+ 012ADA2F00868211C697A10E,
+ 012ADA3000868211C697A10E,
+ 012ADA3100868211C697A10E,
+ 012ADA3200868211C697A10E,
+ 012ADA3300868211C697A10E,
+ 012ADA3400868211C697A10E,
+ 012ADA3500868211C697A10E,
+ 012ADA3600868211C697A10E,
+ 012ADA3700868211C697A10E,
+ 012ADA3800868211C697A10E,
+ 012ADA3900868211C697A10E,
+ 012ADA3A00868211C697A10E,
+ 012ADA3B00868211C697A10E,
+ 012ADA3C00868211C697A10E,
+ 012ADA3D00868211C697A10E,
+ 012ADA3E00868211C697A10E,
+ 012ADA3F00868211C697A10E,
+ 012ADA4000868211C697A10E,
+ 012ADA4100868211C697A10E,
+ 012ADA4200868211C697A10E,
+ 012ADA4300868211C697A10E,
+ 012ADA4400868211C697A10E,
+ 012ADA4500868211C697A10E,
+ 012ADA4600868211C697A10E,
+ 012ADA4700868211C697A10E,
+ 012ADA4800868211C697A10E,
+ 012ADA4900868211C697A10E,
+ 012ADA4A00868211C697A10E,
+ 012ADA4B00868211C697A10E,
+ 012ADA4C00868211C697A10E,
+ 012ADA4D00868211C697A10E,
+ 012ADA4E00868211C697A10E,
+ 012ADA4F00868211C697A10E,
+ 012ADA5000868211C697A10E,
+ 012ADA5100868211C697A10E,
+ 012ADA5200868211C697A10E,
+ 012ADA5300868211C697A10E,
+ 012ADA5400868211C697A10E,
+ 012ADA5500868211C697A10E,
+ 012ADA5600868211C697A10E,
+ 012ADA5700868211C697A10E,
+ 012ADA5800868211C697A10E,
+ 012ADA5900868211C697A10E,
+ 012ADA5A00868211C697A10E,
+ 012ADA5B00868211C697A10E,
+ 012ADA5C00868211C697A10E,
+ 012ADA5D00868211C697A10E,
+ 012ADA5E00868211C697A10E,
+ 012ADA5F00868211C697A10E,
+ 012ADA6000868211C697A10E,
+ 012ADA6100868211C697A10E,
+ 012ADA6200868211C697A10E,
+ 012ADA6300868211C697A10E,
+ 012ADA6400868211C697A10E,
+ );
+ isa = PBXGroup;
+ path = game;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA2500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ai_chat.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA2600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = ai_chat.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA2700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ai_cmd.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA2800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = ai_cmd.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA2900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ai_dmnet.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA2A00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = ai_dmnet.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA2B00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ai_dmq3.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA2C00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = ai_dmq3.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA2D00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ai_main.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA2E00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = ai_main.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA2F00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ai_team.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA3000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = ai_team.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA3100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ai_vcmd.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA3200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = ai_vcmd.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA3300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_aas.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA3400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_ai_char.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA3500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_ai_chat.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA3600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_ai_gen.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA3700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_ai_goal.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA3800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_ai_move.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA3900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_ai_weap.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA3A00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = be_ea.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA3B00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = bg_lib.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA3C00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = bg_lib.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA3D00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = bg_local.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA3E00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = bg_misc.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA3F00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = bg_pmove.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA4000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = bg_public.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA4100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = bg_slidemove.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA4200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = botlib.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA4300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = chars.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA4400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = g_active.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA4500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = g_arenas.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA4600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = g_bot.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA4700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = g_client.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA4800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = g_cmds.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA4900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = g_combat.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA4A00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = g_items.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA4B00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = g_local.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA4C00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = g_main.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA4D00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = g_mem.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA4E00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = g_misc.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA4F00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = g_missile.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA5000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = g_mover.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA5100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = g_public.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA5200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = g_rankings.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA5300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = g_rankings.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA5400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = g_session.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA5500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = g_spawn.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA5600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = g_svcmds.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA5700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = g_syscalls.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA5800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = g_target.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA5900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = g_team.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA5A00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = g_team.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA5B00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = g_trigger.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA5C00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = g_utils.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA5D00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = g_weapon.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA5E00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = inv.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA5F00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = match.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA6000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = q_math.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA6100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = q_shared.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA6200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = q_shared.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA6300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = surfaceflags.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA6400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = syn.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA6500868211C697A10E = {
+ children = (
+ 012ADA6600868211C697A10E,
+ 012ADA6700868211C697A10E,
+ 012ADA6800868211C697A10E,
+ 012ADA6900868211C697A10E,
+ 012ADA6A00868211C697A10E,
+ 012ADA6B00868211C697A10E,
+ 012ADA6C00868211C697A10E,
+ 012ADA6D00868211C697A10E,
+ 012ADA6E00868211C697A10E,
+ 012ADA6F00868211C697A10E,
+ 012ADA7000868211C697A10E,
+ 012ADA7100868211C697A10E,
+ 012ADA7200868211C697A10E,
+ 012ADA7300868211C697A10E,
+ 012ADA7400868211C697A10E,
+ 012ADA7500868211C697A10E,
+ 012ADA7600868211C697A10E,
+ 012ADA7700868211C697A10E,
+ 012ADA7800868211C697A10E,
+ 012ADA7900868211C697A10E,
+ 012ADA7A00868211C697A10E,
+ 012ADA7B00868211C697A10E,
+ 012ADA7C00868211C697A10E,
+ 012ADA7D00868211C697A10E,
+ 012ADA7E00868211C697A10E,
+ 012ADA7F00868211C697A10E,
+ 012ADA8000868211C697A10E,
+ 012ADA8100868211C697A10E,
+ 012ADA8200868211C697A10E,
+ 012ADA8300868211C697A10E,
+ 012ADA8400868211C697A10E,
+ 012ADA8500868211C697A10E,
+ 012ADA8600868211C697A10E,
+ 012ADA8700868211C697A10E,
+ 012ADA8800868211C697A10E,
+ 012ADA8900868211C697A10E,
+ 012ADA8A00868211C697A10E,
+ 012ADA8B00868211C697A10E,
+ 012ADA8C00868211C697A10E,
+ 012ADA8D00868211C697A10E,
+ 012ADA8E00868211C697A10E,
+ 012ADA8F00868211C697A10E,
+ 012ADA9000868211C697A10E,
+ 012ADA9100868211C697A10E,
+ 012ADA9200868211C697A10E,
+ 012ADA9300868211C697A10E,
+ 012ADA9400868211C697A10E,
+ 012ADA9500868211C697A10E,
+ 012ADA9600868211C697A10E,
+ 012ADA9700868211C697A10E,
+ 012ADA9800868211C697A10E,
+ 012ADA9900868211C697A10E,
+ 012ADA9A00868211C697A10E,
+ 012ADA9B00868211C697A10E,
+ 012ADA9C00868211C697A10E,
+ 012ADA9D00868211C697A10E,
+ 012ADA9E00868211C697A10E,
+ 012ADA9F00868211C697A10E,
+ 012ADAA000868211C697A10E,
+ 012ADAA100868211C697A10E,
+ 012ADAA200868211C697A10E,
+ 012ADAA300868211C697A10E,
+ );
+ isa = PBXGroup;
+ path = "jpeg-6";
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA6600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jcapimin.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA6700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jcapistd.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA6800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jccoefct.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA6900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jccolor.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA6A00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jcdctmgr.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA6B00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jchuff.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA6C00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = jchuff.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA6D00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jcinit.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA6E00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jcmainct.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA6F00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jcmarker.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA7000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jcmaster.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA7100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jcomapi.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA7200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = jconfig.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA7300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jcparam.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA7400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jcphuff.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA7500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jcprepct.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA7600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jcsample.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA7700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jctrans.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA7800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jdapimin.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA7900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jdapistd.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA7A00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jdatadst.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA7B00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jdatasrc.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA7C00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jdcoefct.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA7D00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jdcolor.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA7E00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = jdct.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA7F00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jddctmgr.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA8000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jdhuff.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA8100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = jdhuff.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA8200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jdinput.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA8300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jdmainct.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA8400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jdmarker.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA8500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jdmaster.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA8600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jdmerge.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA8700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jdphuff.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA8800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jdpostct.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA8900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jdsample.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA8A00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jdtrans.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA8B00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jerror.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA8C00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = jerror.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA8D00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jfdctflt.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA8E00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jfdctfst.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA8F00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jfdctint.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA9000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jidctflt.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA9100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jidctfst.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA9200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jidctint.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA9300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jidctred.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA9400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = jinclude.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA9500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jload.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA9600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jmemansi.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA9700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jmemdos.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA9800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jmemmgr.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA9900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jmemname.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA9A00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jmemnobs.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA9B00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = jmemsys.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA9C00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = jmorecfg.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA9D00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = jpegint.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA9E00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = jpeglib.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADA9F00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jpegtran.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAA000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jquant1.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAA100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jquant2.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAA200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = jutils.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAA300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = jversion.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAA400868211C697A10E = {
+ children = (
+ 012ADAA500868211C697A10E,
+ 012ADAA600868211C697A10E,
+ 012ADAA700868211C697A10E,
+ 012ADAA800868211C697A10E,
+ 012ADAA900868211C697A10E,
+ 012ADAAA00868211C697A10E,
+ 012ADAAB00868211C697A10E,
+ 012ADAAC00868211C697A10E,
+ 012ADAAD00868211C697A10E,
+ 012ADAAE00868211C697A10E,
+ 012ADAAF00868211C697A10E,
+ 012ADAB000868211C697A10E,
+ 012ADAB100868211C697A10E,
+ 012ADAB200868211C697A10E,
+ );
+ isa = PBXGroup;
+ path = mac;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAA500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = mac_console.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAA600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = mac_event.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAA700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = mac_glimp2.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAA800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = mac_input.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAA900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = mac_local.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAAA00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = mac_main.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAAB00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = mac_net.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAAC00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = mac_snddma.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAAD00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = MacGamma.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAAE00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = MacGamma.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAAF00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = macprefix.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAB000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.rez;
+ path = q3.r;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAB100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = SetupGL.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAB200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = SetupGL.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAB300868211C697A10E = {
+ children = (
+ 012ADAB400868211C697A10E,
+ 012ADAB500868211C697A10E,
+ 012ADAB600868211C697A10E,
+ 012ADAB700868211C697A10E,
+ 012ADAB800868211C697A10E,
+ 012ADAB900868211C697A10E,
+ 012ADABA00868211C697A10E,
+ );
+ isa = PBXGroup;
+ path = null;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAB400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = mac_net.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAB500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = null_client.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAB600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = null_glimp.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAB700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = null_input.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAB800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = null_main.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAB900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = null_net.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADABA00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = null_snddma.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADABB00868211C697A10E = {
+ children = (
+ 012ADABC00868211C697A10E,
+ 012ADABD00868211C697A10E,
+ 012ADABE00868211C697A10E,
+ 012ADABF00868211C697A10E,
+ 012ADAC000868211C697A10E,
+ 012ADAC100868211C697A10E,
+ 012ADAC200868211C697A10E,
+ 012ADAC300868211C697A10E,
+ 012ADAC400868211C697A10E,
+ 012ADAC500868211C697A10E,
+ 012ADAC600868211C697A10E,
+ 012ADAC700868211C697A10E,
+ 012ADAC800868211C697A10E,
+ 012ADAC900868211C697A10E,
+ 012ADACA00868211C697A10E,
+ 012ADACB00868211C697A10E,
+ 012ADACC00868211C697A10E,
+ 012ADACD00868211C697A10E,
+ 012ADACE00868211C697A10E,
+ 012ADACF00868211C697A10E,
+ 012ADAD000868211C697A10E,
+ 012ADAD100868211C697A10E,
+ 012ADAD200868211C697A10E,
+ 012ADAD300868211C697A10E,
+ 012ADAD400868211C697A10E,
+ 012ADAD500868211C697A10E,
+ 012ADAD600868211C697A10E,
+ 012ADAD700868211C697A10E,
+ 012ADAD800868211C697A10E,
+ 012ADAD900868211C697A10E,
+ 012ADADA00868211C697A10E,
+ 012ADADB00868211C697A10E,
+ 012ADADC00868211C697A10E,
+ 012ADADD00868211C697A10E,
+ 012ADADE00868211C697A10E,
+ 012ADADF00868211C697A10E,
+ 012ADAE000868211C697A10E,
+ 012ADAE100868211C697A10E,
+ 012ADAE200868211C697A10E,
+ 012ADAE300868211C697A10E,
+ 012ADAE400868211C697A10E,
+ 012ADAE500868211C697A10E,
+ 012ADAE600868211C697A10E,
+ 012ADAE700868211C697A10E,
+ 012ADAE800868211C697A10E,
+ 012ADAE900868211C697A10E,
+ 012ADAEA00868211C697A10E,
+ 012ADAEB00868211C697A10E,
+ );
+ isa = PBXGroup;
+ path = q3_ui;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADABC00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = keycodes.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADABD00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_addbots.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADABE00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_atoms.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADABF00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_cdkey.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAC000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_cinematics.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAC100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_confirm.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAC200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_connect.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAC300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_controls2.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAC400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_credits.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAC500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_demo2.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAC600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_display.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAC700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_gameinfo.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAC800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_ingame.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAC900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_loadconfig.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADACA00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = ui_local.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADACB00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_login.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADACC00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_main.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADACD00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_menu.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADACE00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_mfield.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADACF00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_mods.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAD000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_network.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAD100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_options.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAD200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_playermodel.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAD300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_players.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAD400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_playersettings.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAD500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_preferences.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAD600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_qmenu.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAD700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_rankings.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAD800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_rankstatus.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAD900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_removebots.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADADA00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_saveconfig.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADADB00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_serverinfo.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADADC00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_servers2.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADADD00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_setup.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADADE00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_signup.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADADF00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_sound.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAE000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_sparena.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAE100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_specifyleague.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAE200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_specifyserver.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAE300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_splevel.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAE400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_sppostgame.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAE500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_spreset.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAE600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_spskill.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAE700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_startserver.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAE800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = file;
+ path = ui_syscalls.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAE900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_team.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAEA00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_teamorders.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAEB00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_video.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAEC00868211C697A10E = {
+ children = (
+ 012ADAED00868211C697A10E,
+ 012ADAEE00868211C697A10E,
+ 012ADAEF00868211C697A10E,
+ 012ADAF000868211C697A10E,
+ 012ADAF100868211C697A10E,
+ 012ADAF200868211C697A10E,
+ 012ADAF300868211C697A10E,
+ 012ADAF400868211C697A10E,
+ 012ADAF500868211C697A10E,
+ 012ADAF600868211C697A10E,
+ 012ADAF700868211C697A10E,
+ 012ADAF800868211C697A10E,
+ 012ADAF900868211C697A10E,
+ 016F1B6300ACDA9BC697A10E,
+ 012ADAFA00868211C697A10E,
+ 012ADAFB00868211C697A10E,
+ 012ADAFC00868211C697A10E,
+ 012ADAFD00868211C697A10E,
+ 012ADAFE00868211C697A10E,
+ 012ADAFF00868211C697A10E,
+ 012ADB0000868211C697A10E,
+ 012ADB0100868211C697A10E,
+ 012ADB0200868211C697A10E,
+ 012ADB0300868211C697A10E,
+ 012ADB0400868211C697A10E,
+ 012ADB0500868211C697A10E,
+ 4FB23863047AB9F60098ACF3,
+ );
+ isa = PBXGroup;
+ path = qcommon;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAED00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cm_load.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAEE00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = cm_local.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAEF00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cm_patch.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAF000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = cm_patch.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAF100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cm_polylib.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAF200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = cm_polylib.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAF300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = cm_public.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAF400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cm_test.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAF500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cm_trace.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAF600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cmd.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAF700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = common.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAF800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = cvar.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAF900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = files.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAFA00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = md4.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAFB00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = msg.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAFC00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = net_chan.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAFD00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = qcommon.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAFE00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = qfiles.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADAFF00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = unzip.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB0000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = unzip.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB0100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = vm.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB0200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = vm_interpreted.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB0300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = vm_local.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB0400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = vm_ppc.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB0500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = vm_x86.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB0600868211C697A10E = {
+ children = (
+ 012ADB0700868211C697A10E,
+ 012ADB0800868211C697A10E,
+ 012ADB0900868211C697A10E,
+ 012ADB0A00868211C697A10E,
+ 012ADB0B00868211C697A10E,
+ 012ADB0C00868211C697A10E,
+ 012ADB0D00868211C697A10E,
+ 012ADB0E00868211C697A10E,
+ 012ADB0F00868211C697A10E,
+ 012ADB1000868211C697A10E,
+ 012ADB1100868211C697A10E,
+ 012ADB1200868211C697A10E,
+ 012ADB1300868211C697A10E,
+ 012ADB1400868211C697A10E,
+ 012ADB1500868211C697A10E,
+ 012ADB1600868211C697A10E,
+ 012ADB1700868211C697A10E,
+ 012ADB1800868211C697A10E,
+ 012ADB1900868211C697A10E,
+ 012ADB1A00868211C697A10E,
+ 012ADB1B00868211C697A10E,
+ 012ADB1C00868211C697A10E,
+ 012ADB1D00868211C697A10E,
+ 012ADB1E00868211C697A10E,
+ 012ADB1F00868211C697A10E,
+ 012ADB2000868211C697A10E,
+ 012ADB2100868211C697A10E,
+ 012ADB2200868211C697A10E,
+ );
+ isa = PBXGroup;
+ path = renderer;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB0700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = amd3d.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB0800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = qgl.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB0900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = qgl_linked.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB0A00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = tr_animation.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB0B00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = tr_backend.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB0C00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ lineEnding = 0;
+ path = tr_bsp.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB0D00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = tr_cmds.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB0E00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = tr_curve.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB0F00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = tr_flares.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB1000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = tr_font.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB1100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = tr_image.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB1200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = tr_init.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB1300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = tr_light.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB1400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = tr_local.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB1500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = tr_main.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB1600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = tr_marks.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB1700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = tr_mesh.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB1800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = tr_model.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB1900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = tr_noise.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB1A00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = tr_public.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB1B00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = tr_scene.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB1C00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = tr_shade.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB1D00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = tr_shade_calc.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB1E00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = tr_shader.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB1F00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = tr_shadows.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB2000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = tr_sky.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB2100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = tr_surface.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB2200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = tr_world.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB2300868211C697A10E = {
+ children = (
+ 012ADB2400868211C697A10E,
+ 012ADB2500868211C697A10E,
+ 012ADB2600868211C697A10E,
+ 012ADB2700868211C697A10E,
+ 012ADB2800868211C697A10E,
+ 012ADB2900868211C697A10E,
+ 012ADB2A00868211C697A10E,
+ 012ADB2B00868211C697A10E,
+ 012ADB2C00868211C697A10E,
+ 012ADB2D00868211C697A10E,
+ 012ADB2E00868211C697A10E,
+ );
+ isa = PBXGroup;
+ path = server;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB2400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = server.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB2500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = sv_bot.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB2600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = sv_ccmds.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB2700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = sv_client.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB2800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = sv_game.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB2900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = sv_init.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB2A00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = sv_main.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB2B00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = sv_net_chan.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB2C00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = sv_rankings.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB2D00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = sv_snapshot.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB2E00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = sv_world.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB2F00868211C697A10E = {
+ children = (
+ 012ADB3000868211C697A10E,
+ 012ADB3100868211C697A10E,
+ 012ADB3200868211C697A10E,
+ 012ADB3300868211C697A10E,
+ 012ADB3400868211C697A10E,
+ 012ADB3500868211C697A10E,
+ 012ADB3600868211C697A10E,
+ 012ADB3700868211C697A10E,
+ 012ADB3800868211C697A10E,
+ 012ADB3900868211C697A10E,
+ 012ADB3A00868211C697A10E,
+ 012ADB3B00868211C697A10E,
+ 012ADB3D00868211C697A10E,
+ 012ADB3E00868211C697A10E,
+ 012ADB3F00868211C697A10E,
+ F5ED1435037096A001F6289A,
+ );
+ isa = PBXGroup;
+ path = splines;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB3000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.cpp.cpp;
+ path = math_angles.cpp;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB3100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = math_angles.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB3200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.cpp.cpp;
+ path = math_matrix.cpp;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB3300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = math_matrix.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB3400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.cpp.cpp;
+ path = math_quaternion.cpp;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB3500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = math_quaternion.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB3600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.cpp.cpp;
+ path = math_vector.cpp;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB3700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = math_vector.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB3800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.cpp.cpp;
+ path = q_parse.cpp;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB3900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.cpp.cpp;
+ path = q_shared.cpp;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB3A00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.cpp.h;
+ path = q_shared.hpp;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB3B00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.cpp.cpp;
+ path = splines.cpp;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB3D00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = util_list.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB3E00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.cpp.cpp;
+ path = util_str.cpp;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB3F00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = util_str.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB4000868211C697A10E = {
+ children = (
+ 012ADB4100868211C697A10E,
+ 012ADB4200868211C697A10E,
+ 012ADB4300868211C697A10E,
+ 012ADB4400868211C697A10E,
+ 012ADB4500868211C697A10E,
+ 012ADB4600868211C697A10E,
+ 012ADB4700868211C697A10E,
+ 012ADB4800868211C697A10E,
+ 012ADB4900868211C697A10E,
+ 012ADB4A00868211C697A10E,
+ 012ADB4B00868211C697A10E,
+ );
+ isa = PBXGroup;
+ path = ui;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB4100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = keycodes.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB4200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_atoms.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB4300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_gameinfo.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB4400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = ui_local.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB4500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_main.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB4600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_players.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB4700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = ui_public.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB4800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_shared.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB4900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = ui_shared.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB4A00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_syscalls.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB4B00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = ui_util.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB4C00868211C697A10E = {
+ children = (
+ 012ADB4D00868211C697A10E,
+ 012ADB4E00868211C697A10E,
+ 012ADB4F00868211C697A10E,
+ 012ADB5000868211C697A10E,
+ 012ADB5100868211C697A10E,
+ 012ADB5200868211C697A10E,
+ 012ADB5300868211C697A10E,
+ 012ADB5400868211C697A10E,
+ 012ADB5500868211C697A10E,
+ 012ADB5600868211C697A10E,
+ 012ADB5700868211C697A10E,
+ 012ADB5800868211C697A10E,
+ 012ADB5900868211C697A10E,
+ );
+ isa = PBXGroup;
+ path = unix;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB4D00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = linux_common.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB4E00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = linux_glimp.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB4F00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = linux_joystick.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB5000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = linux_local.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB5100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = linux_qgl.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB5200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = linux_snd.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB5300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = qasm.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB5400868211C697A10E = {
+ isa = PBXFileReference;
+ lastKnownFileType = image.gif;
+ path = quake3.gif;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB5500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = unix_glw.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB5600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = unix_main.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB5700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = unix_net.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB5800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = unix_shared.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB5900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = vm_x86.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB5A00868211C697A10E = {
+ children = (
+ 012ADB5B00868211C697A10E,
+ 012ADB5C00868211C697A10E,
+ 012ADB5D00868211C697A10E,
+ 012ADB5E00868211C697A10E,
+ 012ADB5F00868211C697A10E,
+ 012ADB6000868211C697A10E,
+ 012ADB6100868211C697A10E,
+ 012ADB6200868211C697A10E,
+ 012ADB6300868211C697A10E,
+ 012ADB6400868211C697A10E,
+ 012ADB6500868211C697A10E,
+ 012ADB6600868211C697A10E,
+ 012ADB6700868211C697A10E,
+ 012ADB6800868211C697A10E,
+ 012ADB6900868211C697A10E,
+ 012ADB6A00868211C697A10E,
+ 012ADB6B00868211C697A10E,
+ );
+ isa = PBXGroup;
+ path = win32;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB5B00868211C697A10E = {
+ isa = PBXFileReference;
+ lastKnownFileType = image.bmp;
+ path = background.bmp;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB5C00868211C697A10E = {
+ isa = PBXFileReference;
+ lastKnownFileType = image.bmp;
+ path = clear.bmp;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB5D00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = glw_win.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB5E00868211C697A10E = {
+ isa = PBXFileReference;
+ lastKnownFileType = image.ico;
+ path = icon2.ico;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB5F00868211C697A10E = {
+ isa = PBXFileReference;
+ lastKnownFileType = image.ico;
+ path = qe3.ico;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB6000868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = resource.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB6100868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = win_gamma.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB6200868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = win_glimp.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB6300868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = win_input.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB6400868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = win_local.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB6500868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = win_main.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB6600868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = win_net.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB6700868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = win_qgl.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB6800868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = win_shared.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB6900868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = win_snd.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB6A00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = win_syscon.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 012ADB6B00868211C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = win_wndproc.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 015ECC0C00894EC0C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = macosx_display.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 015ECC0D00894EC0C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.objc;
+ path = macosx_display.m;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 015ECC0E00894EC0C697A10E = {
+ fileRef = 015ECC0C00894EC0C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 015ECC0F00894EC0C697A10E = {
+ fileRef = 015ECC0D00894EC0C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 016B4A3B00ACCF9FC697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.objc;
+ path = macosx_glsmp_mutex.m;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 016B4A3C00ACCF9FC697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.objc;
+ path = macosx_glsmp_null.m;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 016B4A3D00ACCF9FC697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.objc;
+ path = macosx_glsmp_ports.m;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 016B4A3E00ACCF9FC697A10E = {
+ fileRef = 016B4A3B00ACCF9FC697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 016EAE0200B4BDD1C697A10E = {
+ explicitFileType = wrapper.cfbundle;
+ isa = PBXFileReference;
+ path = ui.bundle;
+ refType = 3;
+ sourceTree = BUILT_PRODUCTS_DIR;
+ };
+ 016EAE0300B4BDD1C697A10E = {
+ buildPhases = (
+ 016EAE0400B4BDD1C697A10E,
+ 016EAE0900B4BDD1C697A10E,
+ 016EAE0A00B4BDD1C697A10E,
+ 016EAE1200B4BDD1C697A10E,
+ 016EAE1300B4BDD1C697A10E,
+ );
+ buildSettings = {
+ INSTALL_PATH = "/Users/Shared/$(USER)/InstalledProducts";
+ OTHER_CFLAGS = "";
+ OTHER_LDFLAGS = "-bundle -undefined error";
+ OTHER_REZFLAGS = "";
+ PRODUCT_NAME = ui;
+ SECTORDER_FLAGS = "";
+ WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas";
+ WRAPPER_EXTENSION = bundle;
+ };
+ dependencies = (
+ );
+ isa = PBXBundleTarget;
+ name = ui;
+ productInstallPath = "/Users/Shared/$(USER)/InstalledProducts";
+ productName = ui;
+ productReference = 016EAE0200B4BDD1C697A10E;
+ productSettingsXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
+<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
+<plist version=\"1.0\">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>English</string>
+ <key>CFBundleExecutable</key>
+ <string></string>
+ <key>CFBundleGetInfoString</key>
+ <string></string>
+ <key>CFBundleIconFile</key>
+ <string></string>
+ <key>CFBundleIdentifier</key>
+ <string></string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string></string>
+ <key>CFBundlePackageType</key>
+ <string>BNDL</string>
+ <key>CFBundleShortVersionString</key>
+ <string></string>
+ <key>CFBundleSignature</key>
+ <string>????</string>
+ <key>CFBundleVersion</key>
+ <string>0.0.1d1</string>
+</dict>
+</plist>
+";
+ };
+ 016EAE0400B4BDD1C697A10E = {
+ buildActionMask = 2147483647;
+ files = (
+ 016EAE0500B4BDD1C697A10E,
+ 016EAE0600B4BDD1C697A10E,
+ 016EAE0700B4BDD1C697A10E,
+ 016EAE0800B4BDD1C697A10E,
+ 016EAE1400B4BE42C697A10E,
+ );
+ isa = PBXHeadersBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 016EAE0500B4BDD1C697A10E = {
+ fileRef = 012ADB4900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 016EAE0600B4BDD1C697A10E = {
+ fileRef = 012ADB4700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 016EAE0700B4BDD1C697A10E = {
+ fileRef = 012ADB4400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 016EAE0800B4BDD1C697A10E = {
+ fileRef = 012ADB4100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 016EAE0900B4BDD1C697A10E = {
+ buildActionMask = 2147483647;
+ files = (
+ );
+ isa = PBXResourcesBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 016EAE0A00B4BDD1C697A10E = {
+ buildActionMask = 2147483647;
+ files = (
+ 016EAE0B00B4BDD1C697A10E,
+ 016EAE0C00B4BDD1C697A10E,
+ 016EAE0D00B4BDD1C697A10E,
+ 016EAE0E00B4BDD1C697A10E,
+ 016EAE0F00B4BDD1C697A10E,
+ 016EAE1000B4BDD1C697A10E,
+ 016EAE1100B4BDD1C697A10E,
+ 016EAE1500B4BE42C697A10E,
+ 016EAE1600B4BE42C697A10E,
+ 016EAE1700B4BE53C697A10E,
+ );
+ isa = PBXSourcesBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 016EAE0B00B4BDD1C697A10E = {
+ fileRef = 012ADB4B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 016EAE0C00B4BDD1C697A10E = {
+ fileRef = 012ADB4A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 016EAE0D00B4BDD1C697A10E = {
+ fileRef = 012ADB4800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 016EAE0E00B4BDD1C697A10E = {
+ fileRef = 012ADB4600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 016EAE0F00B4BDD1C697A10E = {
+ fileRef = 012ADB4500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 016EAE1000B4BDD1C697A10E = {
+ fileRef = 012ADB4300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 016EAE1100B4BDD1C697A10E = {
+ fileRef = 012ADB4200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 016EAE1200B4BDD1C697A10E = {
+ buildActionMask = 2147483647;
+ files = (
+ );
+ isa = PBXFrameworksBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 016EAE1300B4BDD1C697A10E = {
+ buildActionMask = 2147483647;
+ files = (
+ );
+ isa = PBXRezBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 016EAE1400B4BE42C697A10E = {
+ fileRef = 012ADA6200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 016EAE1500B4BE42C697A10E = {
+ fileRef = 012ADA6000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 016EAE1600B4BE42C697A10E = {
+ fileRef = 012ADA6100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 016EAE1700B4BE53C697A10E = {
+ fileRef = 012ADA3E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 016F1B6300ACDA9BC697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = huffman.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 016F1B6400ACDA9BC697A10E = {
+ fileRef = 016F1B6300ACDA9BC697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170304A00B4885DC697A10E = {
+ explicitFileType = "compiled.mach-o.executable";
+ isa = PBXFileReference;
+ path = Q3DedicatedServer;
+ refType = 3;
+ sourceTree = BUILT_PRODUCTS_DIR;
+ };
+ 0170304B00B4885DC697A10E = {
+ buildPhases = (
+ 0170304C00B4885DC697A10E,
+ 0170304D00B4885DC697A10E,
+ 0170304E00B4885DC697A10E,
+ 0170304F00B4885DC697A10E,
+ );
+ buildSettings = {
+ DEBUGGING_SYMBOLS = NO;
+ GCC_VERSION = 3.3;
+ INSTALL_PATH = "";
+ LIBRARY_SEARCH_PATHS = "\"/Users/zaphod/Quake3/code/macosx/GameRanger SDK/Libraries\"";
+ OPTIMIZATION_CFLAGS = "-O2";
+ OTHER_CFLAGS = "-DDEDICATED -DMACOS_X -DBOTLIB -DMISSIONPACK -force_cpusubtype_ALL -Wno-long-double";
+ OTHER_LDFLAGS = "";
+ OTHER_REZFLAGS = "";
+ PRODUCT_NAME = Q3DedicatedServer;
+ REZ_EXECUTABLE = YES;
+ SECTORDER_FLAGS = "";
+ WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas";
+ };
+ dependencies = (
+ );
+ isa = PBXToolTarget;
+ name = "Dedicated Server";
+ productInstallPath = "";
+ productName = "Dedicated Server";
+ productReference = 0170304A00B4885DC697A10E;
+ };
+ 0170304C00B4885DC697A10E = {
+ buildActionMask = 2147483647;
+ files = (
+ 0170305200B488AEC697A10E,
+ 0170305300B488AEC697A10E,
+ 0170305400B488AEC697A10E,
+ 0170305500B488AEC697A10E,
+ 0170305600B488AEC697A10E,
+ 0170305700B488AEC697A10E,
+ 0170305800B488AEC697A10E,
+ 0170305900B488AEC697A10E,
+ 0170306B00B489B5C697A10E,
+ 0170307600B48B5CC697A10E,
+ 0170307700B48B5CC697A10E,
+ 0170307800B48B5CC697A10E,
+ 0170307900B48B5CC697A10E,
+ 0170307A00B48B5CC697A10E,
+ 0170307B00B48B5CC697A10E,
+ 0170307C00B48B5CC697A10E,
+ 0170307D00B48B5CC697A10E,
+ 0170307E00B48B5CC697A10E,
+ 0170307F00B48B5CC697A10E,
+ 0170308400B48B5CC697A10E,
+ 0170308500B48B5CC697A10E,
+ 0170308600B48B5CC697A10E,
+ 0170308700B48B5CC697A10E,
+ 0170308800B48B5CC697A10E,
+ 0170308900B48B5CC697A10E,
+ 0170308A00B48B5CC697A10E,
+ 0170308B00B48B5CC697A10E,
+ 0170308C00B48B5CC697A10E,
+ 0170308D00B48B5CC697A10E,
+ 0170308E00B48B5CC697A10E,
+ 0170308F00B48B5CC697A10E,
+ 0170309000B48B5CC697A10E,
+ 0170309100B48B5CC697A10E,
+ 0170309200B48B5CC697A10E,
+ 0170309300B48B5CC697A10E,
+ 0170309400B48B5CC697A10E,
+ 0170309500B48B5CC697A10E,
+ 0170309600B48B5CC697A10E,
+ 0170309700B48B5CC697A10E,
+ 0170309800B48B5CC697A10E,
+ 0170309900B48B5CC697A10E,
+ 0170309A00B48B5CC697A10E,
+ 0170309B00B48B5CC697A10E,
+ 0170309C00B48B5CC697A10E,
+ 0170309E00B48B5CC697A10E,
+ 0170309F00B48B5CC697A10E,
+ 017030A000B48B5CC697A10E,
+ 017030A100B48B5CC697A10E,
+ 017030A200B48B5CC697A10E,
+ 017030A300B48B5CC697A10E,
+ );
+ isa = PBXHeadersBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 0170304D00B4885DC697A10E = {
+ buildActionMask = 2147483647;
+ files = (
+ 0170305B00B488AEC697A10E,
+ 0170305C00B488AEC697A10E,
+ 0170305D00B488AEC697A10E,
+ 0170305E00B488AEC697A10E,
+ 0170305F00B488AEC697A10E,
+ 0170306000B488AEC697A10E,
+ 0170306100B488AEC697A10E,
+ 0170306200B488AEC697A10E,
+ 0170306300B488AEC697A10E,
+ 0170306400B488AEC697A10E,
+ 0170306500B488AEC697A10E,
+ 0170306600B488AEC697A10E,
+ 0170306700B488AEC697A10E,
+ 0170306800B488AEC697A10E,
+ 0170306900B488AEC697A10E,
+ 0170306A00B488AEC697A10E,
+ 0170306C00B489B5C697A10E,
+ 0170306D00B489B5C697A10E,
+ 0170306E00B489B5C697A10E,
+ 0170306F00B489B5C697A10E,
+ 0170307000B489B5C697A10E,
+ 0170307100B489B5C697A10E,
+ 0170307200B489B5C697A10E,
+ 0170307400B489B5C697A10E,
+ 0170307500B489B5C697A10E,
+ 017030A400B48B5CC697A10E,
+ 017030A500B48B5CC697A10E,
+ 017030A600B48B5CC697A10E,
+ 017030A700B48B5CC697A10E,
+ 017030A800B48B5CC697A10E,
+ 017030A900B48B5CC697A10E,
+ 017030AA00B48B5CC697A10E,
+ 017030AB00B48B5CC697A10E,
+ 017030AC00B48B5CC697A10E,
+ 017030AD00B48B5CC697A10E,
+ 017030AE00B48B5CC697A10E,
+ 017030AF00B48B5CC697A10E,
+ 017030B000B48B5CC697A10E,
+ 017030B100B48B5CC697A10E,
+ 017030B200B48B5CC697A10E,
+ 017030B300B48B5CC697A10E,
+ 017030B400B48B5CC697A10E,
+ 017030B500B48B5CC697A10E,
+ 017030B600B48B5CC697A10E,
+ 017030B700B48B5CC697A10E,
+ 017030B800B48B5CC697A10E,
+ 017030B900B48B5CC697A10E,
+ 017030BA00B48B5CC697A10E,
+ 017030BB00B48B5CC697A10E,
+ 017030BC00B48B5CC697A10E,
+ 017030BD00B48B5CC697A10E,
+ 017030BE00B48B5CC697A10E,
+ 017030BF00B48B5CC697A10E,
+ 017030C000B48B5CC697A10E,
+ 017030C100B48B5CC697A10E,
+ 017030C200B48B5CC697A10E,
+ 017030C300B48B5CC697A10E,
+ 017030C400B48B5CC697A10E,
+ 017030C500B48B5CC697A10E,
+ 017030C600B48B5CC697A10E,
+ 017030C700B48B5CC697A10E,
+ 017030C800B48B5CC697A10E,
+ 017030C900B48B5CC697A10E,
+ 017030CA00B48B5CC697A10E,
+ 017030CB00B48B5CC697A10E,
+ 017030CC00B48B5CC697A10E,
+ 017030CD00B48B5CC697A10E,
+ 017030CE00B48B5CC697A10E,
+ 017030CF00B48B5CC697A10E,
+ 017030D000B48B5CC697A10E,
+ 017030D100B48B5CC697A10E,
+ 017030D200B48B5CC697A10E,
+ 017030D300B48B5CC697A10E,
+ 017030D400B48B5CC697A10E,
+ 017030D500B48B5CC697A10E,
+ 017030D600B48B5CC697A10E,
+ 017030D700B48B5CC697A10E,
+ 017030D800B48B5CC697A10E,
+ 017030D900B48B5CC697A10E,
+ 017030DA00B48B5CC697A10E,
+ 017030DB00B48B5CC697A10E,
+ 017030DC00B48B5CC697A10E,
+ 017030DD00B48B5CC697A10E,
+ 017030DE00B48B5CC697A10E,
+ 017030DF00B48B5CC697A10E,
+ 017030E000B48B5CC697A10E,
+ 017030E100B48B5CC697A10E,
+ 017030E200B48B5CC697A10E,
+ 017030F200B48B5CC697A10E,
+ 017030F300B48B5CC697A10E,
+ 017030F400B48B5CC697A10E,
+ 017030F500B48B5CC697A10E,
+ 017030F600B48B5CC697A10E,
+ 017030F700B48B5CC697A10E,
+ 017030F800B48B5CC697A10E,
+ 017030F900B48B5CC697A10E,
+ 017030FA00B48B5CC697A10E,
+ 017030FB00B48B5CC697A10E,
+ 017030FC00B48B5CC697A10E,
+ 017030FD00B48B5CC697A10E,
+ 017030FE00B48B5CC697A10E,
+ 017030FF00B48B5CC697A10E,
+ 0170310000B48B5CC697A10E,
+ 0170310100B48B5CC697A10E,
+ 0170310200B48B5CC697A10E,
+ 0170310300B48B5CC697A10E,
+ 0170310400B48B5CC697A10E,
+ 0170310500B48B5CC697A10E,
+ 0170310600B48B5CC697A10E,
+ 0170310700B48B5CC697A10E,
+ 0170310800B48B5CC697A10E,
+ 0170310900B48B5CC697A10E,
+ 0170310A00B48B5CC697A10E,
+ 0170310B00B48B5CC697A10E,
+ 0170310C00B48B5CC697A10E,
+ 0170310D00B48B5CC697A10E,
+ 0170310F00B48B5CC697A10E,
+ 0170311000B48B5CC697A10E,
+ 0170311100B48B5CC697A10E,
+ 0170311200B48B5CC697A10E,
+ 0170311400B48B5CC697A10E,
+ 0170311500B48B5CC697A10E,
+ 0170311600B48B5CC697A10E,
+ F54951F40354EAA2011BCB42,
+ 4FB23865047AB9F60098ACF3,
+ );
+ isa = PBXSourcesBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 0170304E00B4885DC697A10E = {
+ buildActionMask = 2147483647;
+ files = (
+ 0170311700B48E9AC697A10E,
+ 0170311800B48E9AC697A10E,
+ 0170311900B48E9AC697A10E,
+ 0170311A00B48E9AC697A10E,
+ 0170311B00B48E9AC697A10E,
+ F54951E80354E75E011BCB42,
+ );
+ isa = PBXFrameworksBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 0170304F00B4885DC697A10E = {
+ buildActionMask = 2147483647;
+ files = (
+ );
+ isa = PBXRezBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 0170305200B488AEC697A10E = {
+ fileRef = 012ADB0300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170305300B488AEC697A10E = {
+ fileRef = 012ADB0000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170305400B488AEC697A10E = {
+ fileRef = 012ADAFE00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170305500B488AEC697A10E = {
+ fileRef = 012ADAFD00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170305600B488AEC697A10E = {
+ fileRef = 012ADAF300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170305700B488AEC697A10E = {
+ fileRef = 012ADAF200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170305800B488AEC697A10E = {
+ fileRef = 012ADAF000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170305900B488AEC697A10E = {
+ fileRef = 012ADAEE00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170305B00B488AEC697A10E = {
+ fileRef = 012ADB0200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170305C00B488AEC697A10E = {
+ fileRef = 012ADAFF00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170305D00B488AEC697A10E = {
+ fileRef = 012ADB0100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170305E00B488AEC697A10E = {
+ fileRef = 012ADAFC00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170305F00B488AEC697A10E = {
+ fileRef = 012ADAFB00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170306000B488AEC697A10E = {
+ fileRef = 012ADAFA00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170306100B488AEC697A10E = {
+ fileRef = 016F1B6300ACDA9BC697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170306200B488AEC697A10E = {
+ fileRef = 012ADAF900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170306300B488AEC697A10E = {
+ fileRef = 012ADAF800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170306400B488AEC697A10E = {
+ fileRef = 012ADAF700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170306500B488AEC697A10E = {
+ fileRef = 012ADAF600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170306600B488AEC697A10E = {
+ fileRef = 012ADAF500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170306700B488AEC697A10E = {
+ fileRef = 012ADAF400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170306800B488AEC697A10E = {
+ fileRef = 012ADAF100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170306900B488AEC697A10E = {
+ fileRef = 012ADAEF00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170306A00B488AEC697A10E = {
+ fileRef = 012ADAED00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170306B00B489B5C697A10E = {
+ fileRef = 012ADB2400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170306C00B489B5C697A10E = {
+ fileRef = 012ADB2500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170306D00B489B5C697A10E = {
+ fileRef = 012ADB2600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170306E00B489B5C697A10E = {
+ fileRef = 012ADB2700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170306F00B489B5C697A10E = {
+ fileRef = 012ADB2800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170307000B489B5C697A10E = {
+ fileRef = 012ADB2900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170307100B489B5C697A10E = {
+ fileRef = 012ADB2A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170307200B489B5C697A10E = {
+ fileRef = 012ADB2B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170307400B489B5C697A10E = {
+ fileRef = 012ADB2D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170307500B489B5C697A10E = {
+ fileRef = 012ADB2E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170307600B48B5CC697A10E = {
+ fileRef = 012ADB3F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170307700B48B5CC697A10E = {
+ fileRef = 012ADB1400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170307800B48B5CC697A10E = {
+ fileRef = 012ADB1A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170307900B48B5CC697A10E = {
+ fileRef = 012ADB0800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170307A00B48B5CC697A10E = {
+ fileRef = 012ADB0900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170307B00B48B5CC697A10E = {
+ fileRef = 012ADA6C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170307C00B48B5CC697A10E = {
+ fileRef = 012ADA8100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170307D00B48B5CC697A10E = {
+ fileRef = 012ADA8C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170307E00B48B5CC697A10E = {
+ fileRef = 012ADA9B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170307F00B48B5CC697A10E = {
+ fileRef = 012ADA6200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170308400B48B5CC697A10E = {
+ fileRef = 012AD90800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170308500B48B5CC697A10E = {
+ fileRef = 012AD90900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170308600B48B5CC697A10E = {
+ fileRef = 012AD90C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170308700B48B5CC697A10E = {
+ fileRef = 012AD90E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170308800B48B5CC697A10E = {
+ fileRef = 012AD90F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170308900B48B5CC697A10E = {
+ fileRef = 012AD91100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170308A00B48B5CC697A10E = {
+ fileRef = 012AD91300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170308B00B48B5CC697A10E = {
+ fileRef = 012AD91400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170308C00B48B5CC697A10E = {
+ fileRef = 012AD91600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170308D00B48B5CC697A10E = {
+ fileRef = 012AD91800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170308E00B48B5CC697A10E = {
+ fileRef = 012AD91A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170308F00B48B5CC697A10E = {
+ fileRef = 012AD91C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170309000B48B5CC697A10E = {
+ fileRef = 012AD91E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170309100B48B5CC697A10E = {
+ fileRef = 012AD92000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170309200B48B5CC697A10E = {
+ fileRef = 012AD92200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170309300B48B5CC697A10E = {
+ fileRef = 012AD92A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170309400B48B5CC697A10E = {
+ fileRef = 012AD92D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170309500B48B5CC697A10E = {
+ fileRef = 012AD92F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170309600B48B5CC697A10E = {
+ fileRef = 012AD93100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170309700B48B5CC697A10E = {
+ fileRef = 012AD93300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170309800B48B5CC697A10E = {
+ fileRef = 012AD93500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170309900B48B5CC697A10E = {
+ fileRef = 012AD93700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170309A00B48B5CC697A10E = {
+ fileRef = 012AD93900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170309B00B48B5CC697A10E = {
+ fileRef = 012AD93B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170309C00B48B5CC697A10E = {
+ fileRef = 012AD93C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170309E00B48B5CC697A10E = {
+ fileRef = 015ECC0C00894EC0C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170309F00B48B5CC697A10E = {
+ fileRef = 011F78F200B25B65C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030A000B48B5CC697A10E = {
+ fileRef = 043627A600868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030A100B48B5CC697A10E = {
+ fileRef = 043627A900868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030A200B48B5CC697A10E = {
+ fileRef = 043627B000868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030A300B48B5CC697A10E = {
+ fileRef = 043627AE00868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030A400B48B5CC697A10E = {
+ fileRef = 012ADB5700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030A500B48B5CC697A10E = {
+ fileRef = 012ADB5800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030A600B48B5CC697A10E = {
+ fileRef = 012ADB3800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030A700B48B5CC697A10E = {
+ fileRef = 012ADB3B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030A800B48B5CC697A10E = {
+ fileRef = 012ADB3E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030A900B48B5CC697A10E = {
+ fileRef = 012ADB0A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030AA00B48B5CC697A10E = {
+ fileRef = 012ADB0B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030AB00B48B5CC697A10E = {
+ fileRef = 012ADB0C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030AC00B48B5CC697A10E = {
+ fileRef = 012ADB0D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030AD00B48B5CC697A10E = {
+ fileRef = 012ADB0E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030AE00B48B5CC697A10E = {
+ fileRef = 012ADB0F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030AF00B48B5CC697A10E = {
+ fileRef = 012ADB1000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030B000B48B5CC697A10E = {
+ fileRef = 012ADB1100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030B100B48B5CC697A10E = {
+ fileRef = 012ADB1200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030B200B48B5CC697A10E = {
+ fileRef = 012ADB1300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030B300B48B5CC697A10E = {
+ fileRef = 012ADB1500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030B400B48B5CC697A10E = {
+ fileRef = 012ADB1600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030B500B48B5CC697A10E = {
+ fileRef = 012ADB1700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030B600B48B5CC697A10E = {
+ fileRef = 012ADB1800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030B700B48B5CC697A10E = {
+ fileRef = 012ADB1900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030B800B48B5CC697A10E = {
+ fileRef = 012ADB1B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030B900B48B5CC697A10E = {
+ fileRef = 012ADB1C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030BA00B48B5CC697A10E = {
+ fileRef = 012ADB1D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030BB00B48B5CC697A10E = {
+ fileRef = 012ADB1E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030BC00B48B5CC697A10E = {
+ fileRef = 012ADB1F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030BD00B48B5CC697A10E = {
+ fileRef = 012ADB2000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030BE00B48B5CC697A10E = {
+ fileRef = 012ADB2100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030BF00B48B5CC697A10E = {
+ fileRef = 012ADB2200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030C000B48B5CC697A10E = {
+ fileRef = 012ADA6600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030C100B48B5CC697A10E = {
+ fileRef = 012ADA6800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030C200B48B5CC697A10E = {
+ fileRef = 012ADA6900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030C300B48B5CC697A10E = {
+ fileRef = 012ADA6A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030C400B48B5CC697A10E = {
+ fileRef = 012ADA6B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030C500B48B5CC697A10E = {
+ fileRef = 012ADA6D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030C600B48B5CC697A10E = {
+ fileRef = 012ADA6E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030C700B48B5CC697A10E = {
+ fileRef = 012ADA6F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030C800B48B5CC697A10E = {
+ fileRef = 012ADA7000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030C900B48B5CC697A10E = {
+ fileRef = 012ADA7100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030CA00B48B5CC697A10E = {
+ fileRef = 012ADA7300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030CB00B48B5CC697A10E = {
+ fileRef = 012ADA7400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030CC00B48B5CC697A10E = {
+ fileRef = 012ADA7500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030CD00B48B5CC697A10E = {
+ fileRef = 012ADA7600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030CE00B48B5CC697A10E = {
+ fileRef = 012ADA7800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030CF00B48B5CC697A10E = {
+ fileRef = 012ADA7900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030D000B48B5CC697A10E = {
+ fileRef = 012ADA7B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030D100B48B5CC697A10E = {
+ fileRef = 012ADA7C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030D200B48B5CC697A10E = {
+ fileRef = 012ADA7D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030D300B48B5CC697A10E = {
+ fileRef = 012ADA7F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030D400B48B5CC697A10E = {
+ fileRef = 012ADA8000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030D500B48B5CC697A10E = {
+ fileRef = 012ADA8200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030D600B48B5CC697A10E = {
+ fileRef = 012ADA8300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030D700B48B5CC697A10E = {
+ fileRef = 012ADA8400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030D800B48B5CC697A10E = {
+ fileRef = 012ADA8500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030D900B48B5CC697A10E = {
+ fileRef = 012ADA8900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030DA00B48B5CC697A10E = {
+ fileRef = 012ADA8800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030DB00B48B5CC697A10E = {
+ fileRef = 012ADA8B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030DC00B48B5CC697A10E = {
+ fileRef = 012ADA8D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030DD00B48B5CC697A10E = {
+ fileRef = 012ADA9000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030DE00B48B5CC697A10E = {
+ fileRef = 012ADA9600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030DF00B48B5CC697A10E = {
+ fileRef = 012ADA9800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030E000B48B5CC697A10E = {
+ fileRef = 012ADAA200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030E100B48B5CC697A10E = {
+ fileRef = 012ADA6000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030E200B48B5CC697A10E = {
+ fileRef = 012ADA6100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030F200B48B5CC697A10E = {
+ fileRef = 012AD90A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030F300B48B5CC697A10E = {
+ fileRef = 012AD90B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030F400B48B5CC697A10E = {
+ fileRef = 012AD90D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030F500B48B5CC697A10E = {
+ fileRef = 012AD91000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030F600B48B5CC697A10E = {
+ fileRef = 012AD91200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030F700B48B5CC697A10E = {
+ fileRef = 012AD91500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030F800B48B5CC697A10E = {
+ fileRef = 012AD91700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030F900B48B5CC697A10E = {
+ fileRef = 012AD91900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030FA00B48B5CC697A10E = {
+ fileRef = 012AD91B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030FB00B48B5CC697A10E = {
+ fileRef = 012AD91D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030FC00B48B5CC697A10E = {
+ fileRef = 012AD91F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030FD00B48B5CC697A10E = {
+ fileRef = 012AD92100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030FE00B48B5CC697A10E = {
+ fileRef = 012AD92300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 017030FF00B48B5CC697A10E = {
+ fileRef = 012AD92400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170310000B48B5CC697A10E = {
+ fileRef = 012AD92500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170310100B48B5CC697A10E = {
+ fileRef = 012AD92600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170310200B48B5CC697A10E = {
+ fileRef = 012AD92700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170310300B48B5CC697A10E = {
+ fileRef = 012AD92800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170310400B48B5CC697A10E = {
+ fileRef = 012AD92900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170310500B48B5CC697A10E = {
+ fileRef = 012AD92B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170310600B48B5CC697A10E = {
+ fileRef = 012AD92C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170310700B48B5CC697A10E = {
+ fileRef = 012AD92E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170310800B48B5CC697A10E = {
+ fileRef = 012AD93000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170310900B48B5CC697A10E = {
+ fileRef = 012AD93200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170310A00B48B5CC697A10E = {
+ fileRef = 012AD93400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170310B00B48B5CC697A10E = {
+ fileRef = 012AD93600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170310C00B48B5CC697A10E = {
+ fileRef = 012AD93800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170310D00B48B5CC697A10E = {
+ fileRef = 012AD93A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170310F00B48B5CC697A10E = {
+ fileRef = 015ECC0D00894EC0C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170311000B48B5CC697A10E = {
+ fileRef = 043627A700868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170311100B48B5CC697A10E = {
+ fileRef = 016B4A3B00ACCF9FC697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170311200B48B5CC697A10E = {
+ fileRef = 043627A800868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170311400B48B5CC697A10E = {
+ fileRef = 043627AD00868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170311500B48B5CC697A10E = {
+ fileRef = 043627B100868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170311600B48B5CC697A10E = {
+ fileRef = 043627AF00868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170311700B48E9AC697A10E = {
+ fileRef = 0654BA58FE8ECEE0C697A12F;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170311800B48E9AC697A10E = {
+ fileRef = 0654BA59FE8ECEE0C697A12F;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170311900B48E9AC697A10E = {
+ fileRef = 00E9D914FEDB4D29C697A12F;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170311A00B48E9AC697A10E = {
+ fileRef = 0654BA5AFE8ECEE0C697A12F;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170311B00B48E9AC697A10E = {
+ fileRef = 0654BA5BFE8ECEE0C697A12F;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0170311C00B49352C697A10E = {
+ buildPhases = (
+ );
+ buildSettings = {
+ OTHER_CFLAGS = "";
+ OTHER_LDFLAGS = "";
+ OTHER_REZFLAGS = "";
+ PRODUCT_NAME = All;
+ SECTORDER_FLAGS = "";
+ WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas";
+ };
+ dependencies = (
+ 0170311D00B49352C697A10E,
+ 4FF091EA04897B0000030DA8,
+ 18A3D356065F6636006A719A,
+ 18A3D358065F663A006A719A,
+ 18A3D35A065F663F006A719A,
+ );
+ isa = PBXAggregateTarget;
+ name = All;
+ productName = All;
+ };
+ 0170311D00B49352C697A10E = {
+ isa = PBXTargetDependency;
+ target = 0654BA5CFE8ECEE0C697A12F;
+ targetProxy = 1895FF33065E291B00F8B3F4;
+ };
+//010
+//011
+//012
+//013
+//014
+//040
+//041
+//042
+//043
+//044
+ 043627A000868916C697A10E = {
+ children = (
+ 015ECC0C00894EC0C697A10E,
+ 015ECC0D00894EC0C697A10E,
+ 011F78F200B25B65C697A10E,
+ 043627A600868916C697A10E,
+ 043627A700868916C697A10E,
+ 016B4A3B00ACCF9FC697A10E,
+ 016B4A3C00ACCF9FC697A10E,
+ 016B4A3D00ACCF9FC697A10E,
+ 043627A800868916C697A10E,
+ 043627A900868916C697A10E,
+ 043627AB00868916C697A10E,
+ 043627AD00868916C697A10E,
+ 043627AE00868916C697A10E,
+ 043627AF00868916C697A10E,
+ 043627B000868916C697A10E,
+ 043627B100868916C697A10E,
+ 043627B200868916C697A10E,
+ 043627B300868916C697A10E,
+ 043627B400868916C697A10E,
+ 043627B500868916C697A10E,
+ 043627B600868916C697A10E,
+ 043627B700868916C697A10E,
+ 043627B800868916C697A10E,
+ );
+ isa = PBXGroup;
+ name = "Mac OS X";
+ path = "";
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 043627A600868916C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = macosx_glimp.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 043627A700868916C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.objc;
+ path = macosx_glimp.m;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 043627A800868916C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.objc;
+ path = macosx_input.m;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 043627A900868916C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = macosx_local.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 043627AB00868916C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.objc;
+ path = macosx_sndcore.m;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 043627AD00868916C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.objc;
+ path = macosx_sys.m;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 043627AE00868916C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = macosx_timers.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 043627AF00868916C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.objc;
+ path = macosx_timers.m;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 043627B000868916C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = Q3Controller.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 043627B100868916C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.objc;
+ path = Q3Controller.m;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 043627B200868916C697A10E = {
+ isa = PBXFileReference;
+ lastKnownFileType = wrapper.nib;
+ path = Quake3.nib;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 043627B300868916C697A10E = {
+ isa = PBXFileReference;
+ lastKnownFileType = image.icns;
+ path = Quake3.icns;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 043627B400868916C697A10E = {
+ isa = PBXFileReference;
+ lastKnownFileType = image.jpeg;
+ path = banner.jpg;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 043627B500868916C697A10E = {
+ isa = PBXFileReference;
+ lastKnownFileType = text.rtf;
+ path = Performance.rtf;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 043627B600868916C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = text.script.sh;
+ path = BuildRelease;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 043627B700868916C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = text.script.sh;
+ path = RecordDemo.zsh;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 043627B800868916C697A10E = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = text.script.sh;
+ path = timedemo.zsh;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 043627BC00868916C697A10E = {
+ fileRef = 043627A600868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627BD00868916C697A10E = {
+ fileRef = 043627A900868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627BE00868916C697A10E = {
+ fileRef = 043627AE00868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627BF00868916C697A10E = {
+ fileRef = 043627B000868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627C000868916C697A10E = {
+ fileRef = 043627B300868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627C100868916C697A10E = {
+ fileRef = 043627B200868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627C200868916C697A10E = {
+ fileRef = 043627B400868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627C500868916C697A10E = {
+ fileRef = 043627A700868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627C600868916C697A10E = {
+ fileRef = 043627A800868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627C800868916C697A10E = {
+ fileRef = 043627AB00868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627CA00868916C697A10E = {
+ fileRef = 043627AD00868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627CB00868916C697A10E = {
+ fileRef = 043627AF00868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627CC00868916C697A10E = {
+ fileRef = 043627B100868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627D20086963EC697A10E = {
+ fileRef = 012ADAF600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627D30086965EC697A10E = {
+ fileRef = 012ADA6200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627D40086965EC697A10E = {
+ fileRef = 012ADA6100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627D50086965EC697A10E = {
+ fileRef = 012ADA6000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627D600869679C697A10E = {
+ fileRef = 012ADB1200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627D700869713C697A10E = {
+ fileRef = 012ADB0300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627D800869713C697A10E = {
+ fileRef = 012ADAF700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627D900869713C697A10E = {
+ fileRef = 012ADAF800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627DA00869713C697A10E = {
+ fileRef = 012ADAF900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627DB00869713C697A10E = {
+ fileRef = 012ADB0100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627DD00869713C697A10E = {
+ fileRef = 012ADB0200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627DE00869726C697A10E = {
+ fileRef = 012ADB0000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627DF00869726C697A10E = {
+ fileRef = 012ADAFF00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627E00086978DC697A10E = {
+ fileRef = 012ADB5800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627E100869827C697A10E = {
+ fileRef = 012ADAEE00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627E200869827C697A10E = {
+ fileRef = 012ADAF000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627E300869827C697A10E = {
+ fileRef = 012ADAF200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627E400869827C697A10E = {
+ fileRef = 012ADAF300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627E500869827C697A10E = {
+ fileRef = 012ADAFD00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627E600869827C697A10E = {
+ fileRef = 012ADAFE00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627E700869827C697A10E = {
+ fileRef = 012ADB0800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627E800869827C697A10E = {
+ fileRef = 012ADB0900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627E900869827C697A10E = {
+ fileRef = 012ADB1400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627EA00869827C697A10E = {
+ fileRef = 012ADB1A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627EB00869827C697A10E = {
+ fileRef = 012ADB2400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627EC00869827C697A10E = {
+ fileRef = 012AD9A600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627ED00869827C697A10E = {
+ fileRef = 012AD9A700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627EE00869827C697A10E = {
+ fileRef = 012AD9A800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627EF00869827C697A10E = {
+ fileRef = 012AD9A900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627F000869827C697A10E = {
+ fileRef = 012AD9AA00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627F100869827C697A10E = {
+ fileRef = 012AD9AB00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627F200869827C697A10E = {
+ fileRef = 012AD9AC00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627F300869827C697A10E = {
+ fileRef = 012AD9AD00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627F400869827C697A10E = {
+ fileRef = 012AD9AE00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627F500869827C697A10E = {
+ fileRef = 012AD9AF00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627F600869827C697A10E = {
+ fileRef = 012ADAED00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627F700869827C697A10E = {
+ fileRef = 012ADAEF00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627F900869827C697A10E = {
+ fileRef = 012ADAF400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627FA00869827C697A10E = {
+ fileRef = 012ADAF500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627FB00869827C697A10E = {
+ fileRef = 012ADAFA00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627FC00869827C697A10E = {
+ fileRef = 012ADAFB00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627FD00869827C697A10E = {
+ fileRef = 012ADAFC00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627FE00869827C697A10E = {
+ fileRef = 012ADB0A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043627FF00869827C697A10E = {
+ fileRef = 012ADB0B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436280000869827C697A10E = {
+ fileRef = 012ADB0C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436280100869827C697A10E = {
+ fileRef = 012ADB0D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436280200869827C697A10E = {
+ fileRef = 012ADB0E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436280300869827C697A10E = {
+ fileRef = 012ADB0F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436280400869827C697A10E = {
+ fileRef = 012ADB1000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436280500869827C697A10E = {
+ fileRef = 012ADB1100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436280600869827C697A10E = {
+ fileRef = 012ADB1300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436280700869827C697A10E = {
+ fileRef = 012ADB1500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436280800869827C697A10E = {
+ fileRef = 012ADB1600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436280900869827C697A10E = {
+ fileRef = 012ADB1700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436280A00869827C697A10E = {
+ fileRef = 012ADB1800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436280B00869827C697A10E = {
+ fileRef = 012ADB1900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436280C00869827C697A10E = {
+ fileRef = 012ADB1B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436280D00869827C697A10E = {
+ fileRef = 012ADB1C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436280E00869827C697A10E = {
+ fileRef = 012ADB1D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436280F00869827C697A10E = {
+ fileRef = 012ADB1E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436281000869827C697A10E = {
+ fileRef = 012ADB1F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436281100869827C697A10E = {
+ fileRef = 012ADB2000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436281200869827C697A10E = {
+ fileRef = 012ADB2100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436281300869827C697A10E = {
+ fileRef = 012ADB2200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436281400869827C697A10E = {
+ fileRef = 012ADB2500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436281500869827C697A10E = {
+ fileRef = 012ADB2600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436281600869827C697A10E = {
+ fileRef = 012ADB2700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436281700869827C697A10E = {
+ fileRef = 012ADB2800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436281800869827C697A10E = {
+ fileRef = 012ADB2900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436281900869827C697A10E = {
+ fileRef = 012ADB2A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436281A00869827C697A10E = {
+ fileRef = 012ADB2B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436281C00869827C697A10E = {
+ fileRef = 012ADB2D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436281D00869827C697A10E = {
+ fileRef = 012ADB2E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436281E00869827C697A10E = {
+ fileRef = 012ADB5700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436281F008698F8C697A10E = {
+ fileRef = 012AD9B000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 04362820008698F8C697A10E = {
+ fileRef = 012AD9B100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 04362821008698F8C697A10E = {
+ fileRef = 012AD9B400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 04362822008698F8C697A10E = {
+ fileRef = 012AD9B700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 04362823008698F8C697A10E = {
+ fileRef = 012AD9B200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 04362824008698F8C697A10E = {
+ fileRef = 012AD9B300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 04362825008698F8C697A10E = {
+ fileRef = 012AD9B500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 04362826008698F8C697A10E = {
+ fileRef = 012AD9B600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628270086991FC697A10E = {
+ fileRef = 012AD9B800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436282E00869A16C697A10E = {
+ fileRef = 012ADB3B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436282F00869A7FC697A10E = {
+ fileRef = 012ADB3800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436283000869A8EC697A10E = {
+ fileRef = 012ADB3F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436283100869A8EC697A10E = {
+ fileRef = 012ADB3E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436283300869AC5C697A10E = {
+ fileRef = 012ADA9800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436283400869AC5C697A10E = {
+ fileRef = 012ADA9600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436284900869B0BC697A10E = {
+ fileRef = 012ADA8C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436284B00869B0BC697A10E = {
+ fileRef = 012ADA9B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436286A00869C36C697A10E = {
+ fileRef = 012ADA8B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436286B00869C6FC697A10E = {
+ fileRef = 012ADA6600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436286C00869CB4C697A10E = {
+ fileRef = 012ADA7100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436286D00869CC9C697A10E = {
+ fileRef = 012ADAA200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436286E00869D0AC697A10E = {
+ fileRef = 012ADA6F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436286F00869D18C697A10E = {
+ fileRef = 012ADA7900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436287000869D23C697A10E = {
+ fileRef = 012ADA6D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436287100869D3BC697A10E = {
+ fileRef = 012ADA7400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436287200869D48C697A10E = {
+ fileRef = 012ADA6C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436287300869D48C697A10E = {
+ fileRef = 012ADA6B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436287400869D56C697A10E = {
+ fileRef = 012ADA6A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436287500869D61C697A10E = {
+ fileRef = 012ADA7600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436287600869D71C697A10E = {
+ fileRef = 012ADA6900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436287700869D7FC697A10E = {
+ fileRef = 012ADA7500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436287800869D92C697A10E = {
+ fileRef = 012ADA6800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436287900869DBBC697A10E = {
+ fileRef = 012ADA8D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436287A00869DC7C697A10E = {
+ fileRef = 012ADA7000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436287B00869DD4C697A10E = {
+ fileRef = 012ADA8500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436287C00869DDDC697A10E = {
+ fileRef = 012ADA7800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436287D00869DF1C697A10E = {
+ fileRef = 012ADA8400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436287E00869DFAC697A10E = {
+ fileRef = 012ADA8200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436287F00869E04C697A10E = {
+ fileRef = 012ADA8900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436288000869E10C697A10E = {
+ fileRef = 012ADA7F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436288100869E21C697A10E = {
+ fileRef = 012ADA8100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436288200869E21C697A10E = {
+ fileRef = 012ADA8000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436288300869E3DC697A10E = {
+ fileRef = 012ADA9000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436288400869E4CC697A10E = {
+ fileRef = 012ADA8800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436288500869E56C697A10E = {
+ fileRef = 012ADA7300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436288600869E60C697A10E = {
+ fileRef = 012ADA7B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436288700869E80C697A10E = {
+ fileRef = 012ADA8300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436288800869E8DC697A10E = {
+ fileRef = 012ADA7C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436288900869E96C697A10E = {
+ fileRef = 012ADA7D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436288A00869EA2C697A10E = {
+ fileRef = 012ADA6E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436288B00869ED7C697A10E = {
+ fileRef = 012AD92C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436288C00869EF3C697A10E = {
+ fileRef = 012AD92400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436288D00869F06C697A10E = {
+ fileRef = 012AD93700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436288E00869F06C697A10E = {
+ fileRef = 012AD93600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436288F00869F0FC697A10E = {
+ fileRef = 012AD93100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436289000869F0FC697A10E = {
+ fileRef = 012AD93000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436289100869F2AC697A10E = {
+ fileRef = 012AD93900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436289200869F2AC697A10E = {
+ fileRef = 012AD93800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436289300869F38C697A10E = {
+ fileRef = 012AD93500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436289400869F38C697A10E = {
+ fileRef = 012AD93400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436289500869F40C697A10E = {
+ fileRef = 012AD93300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436289600869F40C697A10E = {
+ fileRef = 012AD93200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436289700869F4BC697A10E = {
+ fileRef = 012AD92500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436289800869F63C697A10E = {
+ fileRef = 012AD92B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436289900869F7FC697A10E = {
+ fileRef = 012AD92300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436289A00869F8EC697A10E = {
+ fileRef = 012AD92700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436289B00869FAEC697A10E = {
+ fileRef = 012AD91E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436289C00869FAEC697A10E = {
+ fileRef = 012AD91D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436289D00869FBBC697A10E = {
+ fileRef = 012AD91800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436289E00869FBBC697A10E = {
+ fileRef = 012AD91700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0436289F00869FC3C697A10E = {
+ fileRef = 012AD92200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628A000869FC3C697A10E = {
+ fileRef = 012AD92100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628A100869FDEC697A10E = {
+ fileRef = 012AD90900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628A200869FDEC697A10E = {
+ fileRef = 012AD90A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628A300869FE8C697A10E = {
+ fileRef = 012AD90E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628A400869FE8C697A10E = {
+ fileRef = 012AD90D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628A500869FEFC697A10E = {
+ fileRef = 012AD91C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628A600869FEFC697A10E = {
+ fileRef = 012AD91B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628A70086A057C697A10E = {
+ fileRef = 012AD91600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628A80086A057C697A10E = {
+ fileRef = 012AD91500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628A90086A061C697A10E = {
+ fileRef = 012AD92600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628AA0086A081C697A10E = {
+ fileRef = 012AD92A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628AB0086A081C697A10E = {
+ fileRef = 012AD92900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628AC0086A092C697A10E = {
+ fileRef = 012AD91A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628AD0086A092C697A10E = {
+ fileRef = 012AD91900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628AE0086A099C697A10E = {
+ fileRef = 012AD92000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628AF0086A099C697A10E = {
+ fileRef = 012AD91F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628B00086A0B9C697A10E = {
+ fileRef = 012AD93B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628B10086A0B9C697A10E = {
+ fileRef = 012AD92D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628B20086A0B9C697A10E = {
+ fileRef = 012AD92F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628B30086A0B9C697A10E = {
+ fileRef = 012AD93C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628B40086A0B9C697A10E = {
+ fileRef = 012AD93A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628B50086A0B9C697A10E = {
+ fileRef = 012AD92E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628B60086A0BFC697A10E = {
+ fileRef = 012AD92800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628B70086A0E6C697A10E = {
+ fileRef = 012AD91300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628B80086A0E6C697A10E = {
+ fileRef = 012AD91200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628B90086A0F1C697A10E = {
+ fileRef = 012AD91100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628BA0086A0F1C697A10E = {
+ fileRef = 012AD91000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628BB0086A136C697A10E = {
+ fileRef = 012AD90C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628BC0086A136C697A10E = {
+ fileRef = 012AD90F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628BD0086A136C697A10E = {
+ fileRef = 012AD91400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628BE0086A136C697A10E = {
+ fileRef = 012AD90800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 043628BF0086A136C697A10E = {
+ fileRef = 012AD90B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+//040
+//041
+//042
+//043
+//044
+//060
+//061
+//062
+//063
+//064
+ 0654BA41FE8ECEE0C697A12F = {
+ buildSettings = {
+ };
+ buildStyles = (
+ 07F3F50BFFE98E8EC697A10E,
+ 07F3F50CFFE98E8EC697A10E,
+ );
+ hasScannedForEncodings = 1;
+ isa = PBXProject;
+ mainGroup = 0654BA42FE8ECEE0C697A12F;
+ projectDirPath = "";
+ targets = (
+ 0170311C00B49352C697A10E,
+ 0654BA5CFE8ECEE0C697A12F,
+ 4FF0904804896C0E00030DA8,
+ 00F5ED38FEBA95B7C697A12F,
+ 00F5ED90FEBA9615C697A12F,
+ 016EAE0300B4BDD1C697A10E,
+ 0170304B00B4885DC697A10E,
+ 4FF0912704896C1600030DA8,
+ );
+ };
+ 0654BA42FE8ECEE0C697A12F = {
+ children = (
+ 043627A000868916C697A10E,
+ 0654BA76FE8ED011C697A12F,
+ 0654BA57FE8ECEE0C697A12F,
+ 07FB599DFEB762C8C697A12F,
+ );
+ isa = PBXGroup;
+ name = Quake3;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 0654BA57FE8ECEE0C697A12F = {
+ children = (
+ 0654BA58FE8ECEE0C697A12F,
+ 0654BA5AFE8ECEE0C697A12F,
+ 0654BA5BFE8ECEE0C697A12F,
+ F564505801E623B201F62882,
+ 00E9D914FEDB4D29C697A12F,
+ 0654BA59FE8ECEE0C697A12F,
+ );
+ isa = PBXGroup;
+ name = "External Frameworks and Libraries";
+ path = "";
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 0654BA58FE8ECEE0C697A12F = {
+ isa = PBXFileReference;
+ lastKnownFileType = wrapper.framework;
+ name = OpenGL.framework;
+ path = /System/Library/Frameworks/OpenGL.framework;
+ refType = 0;
+ sourceTree = "<absolute>";
+ };
+ 0654BA59FE8ECEE0C697A12F = {
+ isa = PBXFileReference;
+ lastKnownFileType = wrapper.framework;
+ name = Carbon.framework;
+ path = /System/Library/Frameworks/Carbon.framework;
+ refType = 0;
+ sourceTree = "<absolute>";
+ };
+ 0654BA5AFE8ECEE0C697A12F = {
+ isa = PBXFileReference;
+ lastKnownFileType = wrapper.framework;
+ name = AppKit.framework;
+ path = /System/Library/Frameworks/AppKit.framework;
+ refType = 0;
+ sourceTree = "<absolute>";
+ };
+ 0654BA5BFE8ECEE0C697A12F = {
+ isa = PBXFileReference;
+ lastKnownFileType = wrapper.framework;
+ name = Foundation.framework;
+ path = /System/Library/Frameworks/Foundation.framework;
+ refType = 0;
+ sourceTree = "<absolute>";
+ };
+ 0654BA5CFE8ECEE0C697A12F = {
+ buildPhases = (
+ 0654BA5DFE8ECEE0C697A12F,
+ 0654BA61FE8ECEE0C697A12F,
+ 0654BA65FE8ECEE0C697A12F,
+ 0654BA6BFE8ECEE0C697A12F,
+ 0654BA70FE8ECEE0C697A12F,
+ );
+ buildSettings = {
+ FRAMEWORK_SEARCH_PATHS = "";
+ HEADER_SEARCH_PATHS = "";
+ INSTALL_PATH = "/Users/Shared/$(USER)/InstalledProducts";
+ LIBRARY_SEARCH_PATHS = "";
+ OPTIMIZATION_CFLAGS = "-O2";
+ OTHER_CFLAGS = "-DMACOS_X -DBOTLIB -DMISSIONPACK -DSMP -force_cpusubtype_ALL";
+ OTHER_LDFLAGS = "";
+ OTHER_REZFLAGS = "";
+ PRODUCT_NAME = Quake3;
+ SECTORDER_FLAGS = "";
+ USE_GCC3_PFE_SUPPORT = NO;
+ WARNING_CFLAGS = "-Wno-long-double -Wall -Wno-four-char-constants -Wno-unknown-pragmas";
+ WRAPPER_EXTENSION = app;
+ };
+ dependencies = (
+ );
+ isa = PBXApplicationTarget;
+ name = "Quake3 (Application)";
+ productInstallPath = "/Users/Shared/$(USER)/InstalledProducts";
+ productName = Quake3;
+ productReference = 09143A93FF39F3EF11CA2562;
+ productSettingsXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
+<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
+<plist version=\"1.0\">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>English</string>
+ <key>CFBundleExecutable</key>
+ <string>Quake3</string>
+ <key>CFBundleGetInfoString</key>
+ <string>Quake 3 Arena 1.32b</string>
+ <key>CFBundleIconFile</key>
+ <string>Quake3.icns</string>
+ <key>CFBundleIdentifier</key>
+ <string>com.idsoftware.Quake3</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>Quake3</string>
+ <key>CFBundlePackageType</key>
+ <string>APPL</string>
+ <key>CFBundleShortVersionString</key>
+ <string>1.32b</string>
+ <key>CFBundleSignature</key>
+ <string>IDQ3</string>
+ <key>CFBundleVersion</key>
+ <string>1.3.2</string>
+ <key>NSExtensions</key>
+ <dict/>
+ <key>NSMainNibFile</key>
+ <string>Quake3.nib</string>
+ <key>NSPrincipalClass</key>
+ <string>NSApplication</string>
+ <key>NSServices</key>
+ <array>
+ <dict>
+ <key>NSMenuItem</key>
+ <dict>
+ <key>default</key>
+ <string>Quake3/Connect To Server</string>
+ </dict>
+ <key>NSMessage</key>
+ <string>connectToServer</string>
+ <key>NSPortName</key>
+ <string>Quake3</string>
+ <key>NSSendTypes</key>
+ <array>
+ <string>NSStringPboardType</string>
+ </array>
+ </dict>
+ <dict>
+ <key>NSMenuItem</key>
+ <dict>
+ <key>default</key>
+ <string>Quake3/Perform Command</string>
+ </dict>
+ <key>NSMessage</key>
+ <string>performCommand</string>
+ <key>NSPortName</key>
+ <string>Quake3</string>
+ <key>NSSendTypes</key>
+ <array>
+ <string>NSStringPboardType</string>
+ </array>
+ </dict>
+ </array>
+</dict>
+</plist>
+";
+ };
+ 0654BA5DFE8ECEE0C697A12F = {
+ buildActionMask = 2147483647;
+ files = (
+ 043627BC00868916C697A10E,
+ 043627BD00868916C697A10E,
+ 043627BE00868916C697A10E,
+ 043627BF00868916C697A10E,
+ 043627D30086965EC697A10E,
+ 043627D700869713C697A10E,
+ 043627DE00869726C697A10E,
+ 043627E100869827C697A10E,
+ 043627E200869827C697A10E,
+ 043627E300869827C697A10E,
+ 043627E400869827C697A10E,
+ 043627E500869827C697A10E,
+ 043627E600869827C697A10E,
+ 043627E700869827C697A10E,
+ 043627E800869827C697A10E,
+ 043627E900869827C697A10E,
+ 043627EA00869827C697A10E,
+ 043627EB00869827C697A10E,
+ 0436281F008698F8C697A10E,
+ 04362820008698F8C697A10E,
+ 04362821008698F8C697A10E,
+ 04362822008698F8C697A10E,
+ 0436283000869A8EC697A10E,
+ 0436284900869B0BC697A10E,
+ 0436284B00869B0BC697A10E,
+ 0436287200869D48C697A10E,
+ 0436288100869E21C697A10E,
+ 0436288D00869F06C697A10E,
+ 0436288F00869F0FC697A10E,
+ 0436289100869F2AC697A10E,
+ 0436289300869F38C697A10E,
+ 0436289500869F40C697A10E,
+ 0436289B00869FAEC697A10E,
+ 0436289D00869FBBC697A10E,
+ 0436289F00869FC3C697A10E,
+ 043628A100869FDEC697A10E,
+ 043628A300869FE8C697A10E,
+ 043628A500869FEFC697A10E,
+ 043628A70086A057C697A10E,
+ 043628AA0086A081C697A10E,
+ 043628AC0086A092C697A10E,
+ 043628AE0086A099C697A10E,
+ 043628B00086A0B9C697A10E,
+ 043628B10086A0B9C697A10E,
+ 043628B20086A0B9C697A10E,
+ 043628B30086A0B9C697A10E,
+ 043628B70086A0E6C697A10E,
+ 043628B90086A0F1C697A10E,
+ 043628BB0086A136C697A10E,
+ 043628BC0086A136C697A10E,
+ 043628BD0086A136C697A10E,
+ 043628BE0086A136C697A10E,
+ 015ECC0E00894EC0C697A10E,
+ 011F78F300B25B66C697A10E,
+ F5ED1436037096A001F6289A,
+ );
+ isa = PBXHeadersBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 0654BA61FE8ECEE0C697A12F = {
+ buildActionMask = 2147483647;
+ files = (
+ 043627C000868916C697A10E,
+ 043627C100868916C697A10E,
+ 043627C200868916C697A10E,
+ );
+ isa = PBXResourcesBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 0654BA65FE8ECEE0C697A12F = {
+ buildActionMask = 2147483647;
+ files = (
+ 043627C500868916C697A10E,
+ 043627C600868916C697A10E,
+ 043627C800868916C697A10E,
+ 043627CA00868916C697A10E,
+ 043627CB00868916C697A10E,
+ 043627CC00868916C697A10E,
+ 043627D20086963EC697A10E,
+ 043627D40086965EC697A10E,
+ 043627D50086965EC697A10E,
+ 043627D600869679C697A10E,
+ 043627D800869713C697A10E,
+ 043627D900869713C697A10E,
+ 043627DA00869713C697A10E,
+ 043627DB00869713C697A10E,
+ 043627DD00869713C697A10E,
+ 043627DF00869726C697A10E,
+ 043627E00086978DC697A10E,
+ 043627EC00869827C697A10E,
+ 043627ED00869827C697A10E,
+ 043627EE00869827C697A10E,
+ 043627EF00869827C697A10E,
+ 043627F000869827C697A10E,
+ 043627F100869827C697A10E,
+ 043627F200869827C697A10E,
+ 043627F300869827C697A10E,
+ 043627F400869827C697A10E,
+ 043627F500869827C697A10E,
+ 043627F600869827C697A10E,
+ 043627F700869827C697A10E,
+ 043627F900869827C697A10E,
+ 043627FA00869827C697A10E,
+ 043627FB00869827C697A10E,
+ 043627FC00869827C697A10E,
+ 043627FD00869827C697A10E,
+ 043627FE00869827C697A10E,
+ 043627FF00869827C697A10E,
+ 0436280000869827C697A10E,
+ 0436280100869827C697A10E,
+ 0436280200869827C697A10E,
+ 0436280300869827C697A10E,
+ 0436280400869827C697A10E,
+ 0436280500869827C697A10E,
+ 0436280600869827C697A10E,
+ 0436280700869827C697A10E,
+ 0436280800869827C697A10E,
+ 0436280900869827C697A10E,
+ 0436280A00869827C697A10E,
+ 0436280B00869827C697A10E,
+ 0436280C00869827C697A10E,
+ 0436280D00869827C697A10E,
+ 0436280E00869827C697A10E,
+ 0436280F00869827C697A10E,
+ 0436281000869827C697A10E,
+ 0436281100869827C697A10E,
+ 0436281200869827C697A10E,
+ 0436281300869827C697A10E,
+ 0436281400869827C697A10E,
+ 0436281500869827C697A10E,
+ 0436281600869827C697A10E,
+ 0436281700869827C697A10E,
+ 0436281800869827C697A10E,
+ 0436281900869827C697A10E,
+ 0436281A00869827C697A10E,
+ 0436281C00869827C697A10E,
+ 0436281D00869827C697A10E,
+ 0436281E00869827C697A10E,
+ 04362823008698F8C697A10E,
+ 04362824008698F8C697A10E,
+ 04362825008698F8C697A10E,
+ 04362826008698F8C697A10E,
+ 043628270086991FC697A10E,
+ 0436282E00869A16C697A10E,
+ 0436282F00869A7FC697A10E,
+ 0436283100869A8EC697A10E,
+ 0436283300869AC5C697A10E,
+ 0436283400869AC5C697A10E,
+ 0436286A00869C36C697A10E,
+ 0436286B00869C6FC697A10E,
+ 0436286C00869CB4C697A10E,
+ 0436286D00869CC9C697A10E,
+ 0436286E00869D0AC697A10E,
+ 0436286F00869D18C697A10E,
+ 0436287000869D23C697A10E,
+ 0436287100869D3BC697A10E,
+ 0436287300869D48C697A10E,
+ 0436287400869D56C697A10E,
+ 0436287500869D61C697A10E,
+ 0436287600869D71C697A10E,
+ 0436287700869D7FC697A10E,
+ 0436287800869D92C697A10E,
+ 0436287900869DBBC697A10E,
+ 0436287A00869DC7C697A10E,
+ 0436287B00869DD4C697A10E,
+ 0436287C00869DDDC697A10E,
+ 0436287D00869DF1C697A10E,
+ 0436287E00869DFAC697A10E,
+ 0436287F00869E04C697A10E,
+ 0436288000869E10C697A10E,
+ 0436288200869E21C697A10E,
+ 0436288300869E3DC697A10E,
+ 0436288400869E4CC697A10E,
+ 0436288500869E56C697A10E,
+ 0436288600869E60C697A10E,
+ 0436288700869E80C697A10E,
+ 0436288800869E8DC697A10E,
+ 0436288900869E96C697A10E,
+ 0436288A00869EA2C697A10E,
+ 0436288B00869ED7C697A10E,
+ 0436288C00869EF3C697A10E,
+ 0436288E00869F06C697A10E,
+ 0436289000869F0FC697A10E,
+ 0436289200869F2AC697A10E,
+ 0436289400869F38C697A10E,
+ 0436289600869F40C697A10E,
+ 0436289700869F4BC697A10E,
+ 0436289800869F63C697A10E,
+ 0436289900869F7FC697A10E,
+ 0436289A00869F8EC697A10E,
+ 0436289C00869FAEC697A10E,
+ 0436289E00869FBBC697A10E,
+ 043628A000869FC3C697A10E,
+ 043628A200869FDEC697A10E,
+ 043628A400869FE8C697A10E,
+ 043628A600869FEFC697A10E,
+ 043628A80086A057C697A10E,
+ 043628A90086A061C697A10E,
+ 043628AB0086A081C697A10E,
+ 043628AD0086A092C697A10E,
+ 043628AF0086A099C697A10E,
+ 043628B40086A0B9C697A10E,
+ 043628B50086A0B9C697A10E,
+ 043628B60086A0BFC697A10E,
+ 043628B80086A0E6C697A10E,
+ 043628BA0086A0F1C697A10E,
+ 043628BF0086A136C697A10E,
+ 015ECC0F00894EC0C697A10E,
+ 016B4A3E00ACCF9FC697A10E,
+ 016F1B6400ACDA9BC697A10E,
+ 4FB23867047ABF780098ACF3,
+ 4FEFFEDA047B008000719638,
+ );
+ isa = PBXSourcesBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 0654BA6BFE8ECEE0C697A12F = {
+ buildActionMask = 2147483647;
+ files = (
+ 0654BA6CFE8ECEE0C697A12F,
+ 0654BA6EFE8ECEE0C697A12F,
+ 0654BA6FFE8ECEE0C697A12F,
+ 00E9D91DFEDB5295C697A12F,
+ F564505901E623B201F62882,
+ F5D8C5E0035259DF0106E832,
+ );
+ isa = PBXFrameworksBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 0654BA6CFE8ECEE0C697A12F = {
+ fileRef = 0654BA58FE8ECEE0C697A12F;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0654BA6EFE8ECEE0C697A12F = {
+ fileRef = 0654BA5AFE8ECEE0C697A12F;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0654BA6FFE8ECEE0C697A12F = {
+ fileRef = 0654BA5BFE8ECEE0C697A12F;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 0654BA70FE8ECEE0C697A12F = {
+ buildActionMask = 2147483647;
+ files = (
+ );
+ isa = PBXRezBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 0654BA76FE8ED011C697A12F = {
+ children = (
+ 012AD90700868211C697A10E,
+ 012AD93D00868211C697A10E,
+ 012AD98D00868211C697A10E,
+ 012AD9A500868211C697A10E,
+ 012ADA2400868211C697A10E,
+ 012ADA6500868211C697A10E,
+ 012ADAA400868211C697A10E,
+ 012ADAB300868211C697A10E,
+ 012ADABB00868211C697A10E,
+ 012ADAEC00868211C697A10E,
+ 012ADB0600868211C697A10E,
+ 012ADB2300868211C697A10E,
+ 012ADB2F00868211C697A10E,
+ 012ADB4000868211C697A10E,
+ 012ADB4C00868211C697A10E,
+ 012ADB5A00868211C697A10E,
+ );
+ isa = PBXGroup;
+ name = "Id Source";
+ path = ..;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+//060
+//061
+//062
+//063
+//064
+//070
+//071
+//072
+//073
+//074
+ 07F3F507FFE98E8EC697A10E = {
+ explicitFileType = wrapper.cfbundle;
+ isa = PBXFileReference;
+ path = qagame.bundle;
+ refType = 3;
+ sourceTree = BUILT_PRODUCTS_DIR;
+ };
+ 07F3F508FFE98E8EC697A10E = {
+ explicitFileType = wrapper.cfbundle;
+ isa = PBXFileReference;
+ path = cgame.bundle;
+ refType = 3;
+ sourceTree = BUILT_PRODUCTS_DIR;
+ };
+ 07F3F50BFFE98E8EC697A10E = {
+ buildSettings = {
+ COMMON_CFLAGS = "-DMISSIONPACK -DBOTLIB -DMACOS_X -force_cpusubtype_ALL";
+ COPY_PHASE_STRIP = NO;
+ GCC_DYNAMIC_NO_PIC = NO;
+ GCC_ENABLE_FIX_AND_CONTINUE = YES;
+ GCC_GENERATE_DEBUGGING_SYMBOLS = YES;
+ GCC_OPTIMIZATION_LEVEL = 0;
+ NO_OPT_CFLAGS = "-O0 -fno-inline -fno-inline-functions";
+ OPTIMIZATION_CFLAGS = "-O0";
+ OTHER_CFLAGS = "\U0001-g -Wall -DQGL_CHECK_GL_ERRORS $(NO_OPT_CFLAGS) $(COMMON_CFLAGS)";
+ ZERO_LINK = YES;
+ };
+ isa = PBXBuildStyle;
+ name = Development;
+ };
+ 07F3F50CFFE98E8EC697A10E = {
+ buildSettings = {
+ COMMON_CFLAGS = "-DMISSIONPACK -DBOTLIB -DMACOS_X -force_cpusubtype_ALL\n";
+ COPY_PHASE_STRIP = YES;
+ GCC_ENABLE_FIX_AND_CONTINUE = NO;
+ ZERO_LINK = NO;
+ };
+ isa = PBXBuildStyle;
+ name = Deployment;
+ };
+ 07FB599DFEB762C8C697A12F = {
+ children = (
+ 09143A93FF39F3EF11CA2562,
+ 07F3F507FFE98E8EC697A10E,
+ 07F3F508FFE98E8EC697A10E,
+ 016EAE0200B4BDD1C697A10E,
+ 0170304A00B4885DC697A10E,
+ 4FF0912504896C0E00030DA8,
+ 4FF091E804896C1600030DA8,
+ );
+ isa = PBXGroup;
+ name = Products;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+//070
+//071
+//072
+//073
+//074
+//090
+//091
+//092
+//093
+//094
+ 09143A93FF39F3EF11CA2562 = {
+ explicitFileType = wrapper.application;
+ isa = PBXFileReference;
+ path = Quake3.app;
+ refType = 3;
+ sourceTree = BUILT_PRODUCTS_DIR;
+ };
+//090
+//091
+//092
+//093
+//094
+//130
+//131
+//132
+//133
+//134
+ 13380E0900ADF941C697A10E = {
+ fileRef = 012ADA4C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E0B00ADFA16C697A10E = {
+ fileRef = 012ADA5700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E0C00ADFA72C697A10E = {
+ fileRef = 012ADA5600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E0D00ADFA94C697A10E = {
+ fileRef = 012ADA4D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E0E00ADFA9EC697A10E = {
+ fileRef = 012ADA4600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E0F00ADFAACC697A10E = {
+ fileRef = 012ADA6200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E1000ADFAACC697A10E = {
+ fileRef = 012ADA6000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E1100ADFAACC697A10E = {
+ fileRef = 012ADA6100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E1200ADFACAC697A10E = {
+ fileRef = 012ADA4500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E1300ADFAD5C697A10E = {
+ fileRef = 012ADA2E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E1400ADFAD5C697A10E = {
+ fileRef = 012ADA2D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E1500ADFB0CC697A10E = {
+ fileRef = 012ADA2C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E1600ADFB0CC697A10E = {
+ fileRef = 012ADA2B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E1700ADFBFDC697A10E = {
+ fileRef = 012ADA3200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E1800ADFBFDC697A10E = {
+ fileRef = 012ADA3100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E1900ADFC10C697A10E = {
+ fileRef = 012ADA2800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E1A00ADFC10C697A10E = {
+ fileRef = 012ADA2700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E1B00ADFC22C697A10E = {
+ fileRef = 012ADA3000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E1C00ADFC22C697A10E = {
+ fileRef = 012ADA2F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E1D00ADFC32C697A10E = {
+ fileRef = 012ADA2600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E1E00ADFC32C697A10E = {
+ fileRef = 012ADA2500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E1F00ADFC43C697A10E = {
+ fileRef = 012ADA2A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E2000ADFC43C697A10E = {
+ fileRef = 012ADA2900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E2100ADFC59C697A10E = {
+ fileRef = 012ADA5C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E2200ADFC78C697A10E = {
+ fileRef = 012ADA4900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E2300ADFC85C697A10E = {
+ fileRef = 012ADA3E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E2400ADFC9CC697A10E = {
+ fileRef = 012ADA5D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E2500ADFCA7C697A10E = {
+ fileRef = 012ADA5A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E2600ADFCA7C697A10E = {
+ fileRef = 012ADA5900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E2700ADFCBDC697A10E = {
+ fileRef = 012ADA4700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E2800ADFCC8C697A10E = {
+ fileRef = 012ADA4A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E2900ADFCD1C697A10E = {
+ fileRef = 012ADA4F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E2A00ADFCEBC697A10E = {
+ fileRef = 012ADA5500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E2B00ADFCF6C697A10E = {
+ fileRef = 012ADA5400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E2C00ADFD01C697A10E = {
+ fileRef = 012ADA4800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E2D00ADFD1FC697A10E = {
+ fileRef = 012ADA4E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E2E00ADFD28C697A10E = {
+ fileRef = 012ADA5B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E2F00ADFD38C697A10E = {
+ fileRef = 012ADA5800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E3000ADFD46C697A10E = {
+ fileRef = 012ADA5000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E3100ADFD58C697A10E = {
+ fileRef = 012ADA4400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E3200ADFD71C697A10E = {
+ fileRef = 012ADA3F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E3300ADFD85C697A10E = {
+ fileRef = 012ADA4100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E3400ADFDA1C697A10E = {
+ fileRef = 012AD99700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E3500ADFDA1C697A10E = {
+ fileRef = 012AD9A100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E3600ADFDCFC697A10E = {
+ fileRef = 012ADA6200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E3700ADFDCFC697A10E = {
+ fileRef = 012ADA6100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E3800ADFDCFC697A10E = {
+ fileRef = 012ADA6000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E3900ADFDE1C697A10E = {
+ fileRef = 012ADA3E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E3B00ADFE0CC697A10E = {
+ fileRef = 012AD99C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E3C00ADFE1EC697A10E = {
+ fileRef = 012ADA3F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E3D00ADFE24C697A10E = {
+ fileRef = 012ADA4100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E3E00ADFE3DC697A10E = {
+ fileRef = 012AD99B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E3F00ADFE4AC697A10E = {
+ fileRef = 012AD99300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E4000ADFE58C697A10E = {
+ fileRef = 012AD99100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E4100ADFE6BC697A10E = {
+ fileRef = 012AD99600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E4200ADFE7AC697A10E = {
+ fileRef = 012AD99800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E4300ADFE88C697A10E = {
+ fileRef = 012AD9A300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E4400ADFE97C697A10E = {
+ fileRef = 012AD99200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E4500ADFEA7C697A10E = {
+ fileRef = 012AD99A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E4600ADFEB8C697A10E = {
+ fileRef = 012AD99000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E4700ADFEC9C697A10E = {
+ fileRef = 012AD9A200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E4800ADFED7C697A10E = {
+ fileRef = 012AD9A000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E4900ADFEE7C697A10E = {
+ fileRef = 012AD99F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E4A00ADFEF5C697A10E = {
+ fileRef = 012AD99E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E4B00ADFF05C697A10E = {
+ fileRef = 012AD99400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E4C00ADFF27C697A10E = {
+ fileRef = 012AD98E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E4F00AE0112C697A10E = {
+ fileRef = 012AD98F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E5000AE020FC697A10E = {
+ fileRef = 012AD99900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E5100AE0235C697A10E = {
+ fileRef = 012ADB4900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 13380E5200AE0235C697A10E = {
+ fileRef = 012ADB4800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+//130
+//131
+//132
+//133
+//134
+//180
+//181
+//182
+//183
+//184
+ 1895FF2E065E291B00F8B3F4 = {
+ containerPortal = 0654BA41FE8ECEE0C697A12F;
+ isa = PBXContainerItemProxy;
+ proxyType = 1;
+ remoteGlobalIDString = 4FF0904804896C0E00030DA8;
+ remoteInfo = "Quake3 G4 (Application)";
+ };
+ 1895FF33065E291B00F8B3F4 = {
+ containerPortal = 0654BA41FE8ECEE0C697A12F;
+ isa = PBXContainerItemProxy;
+ proxyType = 1;
+ remoteGlobalIDString = 0654BA5CFE8ECEE0C697A12F;
+ remoteInfo = "Quake3 (Application)";
+ };
+ 18A3D355065F6636006A719A = {
+ containerPortal = 0654BA41FE8ECEE0C697A12F;
+ isa = PBXContainerItemProxy;
+ proxyType = 1;
+ remoteGlobalIDString = 00F5ED38FEBA95B7C697A12F;
+ remoteInfo = qagame;
+ };
+ 18A3D356065F6636006A719A = {
+ isa = PBXTargetDependency;
+ target = 00F5ED38FEBA95B7C697A12F;
+ targetProxy = 18A3D355065F6636006A719A;
+ };
+ 18A3D357065F663A006A719A = {
+ containerPortal = 0654BA41FE8ECEE0C697A12F;
+ isa = PBXContainerItemProxy;
+ proxyType = 1;
+ remoteGlobalIDString = 00F5ED90FEBA9615C697A12F;
+ remoteInfo = cgame;
+ };
+ 18A3D358065F663A006A719A = {
+ isa = PBXTargetDependency;
+ target = 00F5ED90FEBA9615C697A12F;
+ targetProxy = 18A3D357065F663A006A719A;
+ };
+ 18A3D359065F663F006A719A = {
+ containerPortal = 0654BA41FE8ECEE0C697A12F;
+ isa = PBXContainerItemProxy;
+ proxyType = 1;
+ remoteGlobalIDString = 016EAE0300B4BDD1C697A10E;
+ remoteInfo = ui;
+ };
+ 18A3D35A065F663F006A719A = {
+ isa = PBXTargetDependency;
+ target = 016EAE0300B4BDD1C697A10E;
+ targetProxy = 18A3D359065F663F006A719A;
+ };
+//180
+//181
+//182
+//183
+//184
+//4F0
+//4F1
+//4F2
+//4F3
+//4F4
+ 4FB23863047AB9F60098ACF3 = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.c;
+ path = vm_ppc_new.c;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ 4FB23865047AB9F60098ACF3 = {
+ fileRef = 4FB23863047AB9F60098ACF3;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FB23867047ABF780098ACF3 = {
+ fileRef = 4FB23863047AB9F60098ACF3;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FEFFEDA047B008000719638 = {
+ fileRef = 012ADAF100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0904804896C0E00030DA8 = {
+ buildPhases = (
+ 4FF0904904896C0E00030DA8,
+ 4FF0908704896C0E00030DA8,
+ 4FF0908B04896C0E00030DA8,
+ 4FF0911D04896C0E00030DA8,
+ 4FF0912404896C0E00030DA8,
+ );
+ buildSettings = {
+ FRAMEWORK_SEARCH_PATHS = "";
+ GCC_VERSION = 3.3;
+ HEADER_SEARCH_PATHS = "";
+ INSTALL_PATH = "/Users/Shared/$(USER)/InstalledProducts";
+ LIBRARY_SEARCH_PATHS = "\"/Users/zaphod/QUAKE3/CODE/macosx/GameRanger SDK/Libraries\"";
+ OPTIMIZATION_CFLAGS = "-O2";
+ OTHER_CFLAGS = "-DMACOS_X -DBOTLIB -DMISSIONPACK -DSMP -force_cpusubtype_ALL -faltivec";
+ OTHER_LDFLAGS = "";
+ OTHER_REZFLAGS = "";
+ PRODUCT_NAME = "Quake3 G4";
+ SECTORDER_FLAGS = "";
+ USE_GCC3_PFE_SUPPORT = NO;
+ WARNING_CFLAGS = "-Wno-long-double -Wall -Wno-four-char-constants -Wno-unknown-pragmas";
+ WRAPPER_EXTENSION = app;
+ };
+ dependencies = (
+ );
+ isa = PBXApplicationTarget;
+ name = "Quake3 G4 (Application)";
+ productInstallPath = "/Users/Shared/$(USER)/InstalledProducts";
+ productName = Quake3;
+ productReference = 4FF0912504896C0E00030DA8;
+ productSettingsXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
+<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
+<plist version=\"1.0\">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>English</string>
+ <key>CFBundleExecutable</key>
+ <string>Quake3 G4</string>
+ <key>CFBundleGetInfoString</key>
+ <string>Quake 3 Arena 1.3.2</string>
+ <key>CFBundleIconFile</key>
+ <string>Quake3.icns</string>
+ <key>CFBundleIdentifier</key>
+ <string>com.idsoftware.Quake3</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>Quake3</string>
+ <key>CFBundlePackageType</key>
+ <string>APPL</string>
+ <key>CFBundleShortVersionString</key>
+ <string>1.3.2</string>
+ <key>CFBundleSignature</key>
+ <string>IDQ3</string>
+ <key>CFBundleVersion</key>
+ <string>1.3.2</string>
+ <key>NSExtensions</key>
+ <dict/>
+ <key>NSMainNibFile</key>
+ <string>Quake3.nib</string>
+ <key>NSPrincipalClass</key>
+ <string>NSApplication</string>
+ <key>NSServices</key>
+ <array>
+ <dict>
+ <key>NSMenuItem</key>
+ <dict>
+ <key>default</key>
+ <string>Quake3/Connect To Server</string>
+ </dict>
+ <key>NSMessage</key>
+ <string>connectToServer</string>
+ <key>NSPortName</key>
+ <string>Quake3</string>
+ <key>NSSendTypes</key>
+ <array>
+ <string>NSStringPboardType</string>
+ </array>
+ </dict>
+ <dict>
+ <key>NSMenuItem</key>
+ <dict>
+ <key>default</key>
+ <string>Quake3/Perform Command</string>
+ </dict>
+ <key>NSMessage</key>
+ <string>performCommand</string>
+ <key>NSPortName</key>
+ <string>Quake3</string>
+ <key>NSSendTypes</key>
+ <array>
+ <string>NSStringPboardType</string>
+ </array>
+ </dict>
+ </array>
+</dict>
+</plist>
+";
+ };
+ 4FF0904904896C0E00030DA8 = {
+ buildActionMask = 2147483647;
+ files = (
+ 4FF0904A04896C0E00030DA8,
+ 4FF0904B04896C0E00030DA8,
+ 4FF0904C04896C0E00030DA8,
+ 4FF0904D04896C0E00030DA8,
+ 4FF0904E04896C0E00030DA8,
+ 4FF0904F04896C0E00030DA8,
+ 4FF0905004896C0E00030DA8,
+ 4FF0905104896C0E00030DA8,
+ 4FF0905204896C0E00030DA8,
+ 4FF0905304896C0E00030DA8,
+ 4FF0905404896C0E00030DA8,
+ 4FF0905504896C0E00030DA8,
+ 4FF0905604896C0E00030DA8,
+ 4FF0905704896C0E00030DA8,
+ 4FF0905804896C0E00030DA8,
+ 4FF0905904896C0E00030DA8,
+ 4FF0905A04896C0E00030DA8,
+ 4FF0905B04896C0E00030DA8,
+ 4FF0905C04896C0E00030DA8,
+ 4FF0905D04896C0E00030DA8,
+ 4FF0905E04896C0E00030DA8,
+ 4FF0905F04896C0E00030DA8,
+ 4FF0906004896C0E00030DA8,
+ 4FF0906104896C0E00030DA8,
+ 4FF0906204896C0E00030DA8,
+ 4FF0906304896C0E00030DA8,
+ 4FF0906404896C0E00030DA8,
+ 4FF0906504896C0E00030DA8,
+ 4FF0906604896C0E00030DA8,
+ 4FF0906704896C0E00030DA8,
+ 4FF0906804896C0E00030DA8,
+ 4FF0906904896C0E00030DA8,
+ 4FF0906A04896C0E00030DA8,
+ 4FF0906B04896C0E00030DA8,
+ 4FF0906C04896C0E00030DA8,
+ 4FF0906D04896C0E00030DA8,
+ 4FF0906E04896C0E00030DA8,
+ 4FF0906F04896C0E00030DA8,
+ 4FF0907004896C0E00030DA8,
+ 4FF0907104896C0E00030DA8,
+ 4FF0907204896C0E00030DA8,
+ 4FF0907304896C0E00030DA8,
+ 4FF0907404896C0E00030DA8,
+ 4FF0907504896C0E00030DA8,
+ 4FF0907604896C0E00030DA8,
+ 4FF0907704896C0E00030DA8,
+ 4FF0907804896C0E00030DA8,
+ 4FF0907904896C0E00030DA8,
+ 4FF0907A04896C0E00030DA8,
+ 4FF0907B04896C0E00030DA8,
+ 4FF0907C04896C0E00030DA8,
+ 4FF0907D04896C0E00030DA8,
+ 4FF0907E04896C0E00030DA8,
+ 4FF0907F04896C0E00030DA8,
+ 4FF0908604896C0E00030DA8,
+ );
+ isa = PBXHeadersBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 4FF0904A04896C0E00030DA8 = {
+ fileRef = 043627A600868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0904B04896C0E00030DA8 = {
+ fileRef = 043627A900868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0904C04896C0E00030DA8 = {
+ fileRef = 043627AE00868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0904D04896C0E00030DA8 = {
+ fileRef = 043627B000868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0904E04896C0E00030DA8 = {
+ fileRef = 012ADA6200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0904F04896C0E00030DA8 = {
+ fileRef = 012ADB0300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0905004896C0E00030DA8 = {
+ fileRef = 012ADB0000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0905104896C0E00030DA8 = {
+ fileRef = 012ADAEE00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0905204896C0E00030DA8 = {
+ fileRef = 012ADAF000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0905304896C0E00030DA8 = {
+ fileRef = 012ADAF200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0905404896C0E00030DA8 = {
+ fileRef = 012ADAF300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0905504896C0E00030DA8 = {
+ fileRef = 012ADAFD00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0905604896C0E00030DA8 = {
+ fileRef = 012ADAFE00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0905704896C0E00030DA8 = {
+ fileRef = 012ADB0800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0905804896C0E00030DA8 = {
+ fileRef = 012ADB0900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0905904896C0E00030DA8 = {
+ fileRef = 012ADB1400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0905A04896C0E00030DA8 = {
+ fileRef = 012ADB1A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0905B04896C0E00030DA8 = {
+ fileRef = 012ADB2400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0905C04896C0E00030DA8 = {
+ fileRef = 012AD9B000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0905D04896C0E00030DA8 = {
+ fileRef = 012AD9B100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0905E04896C0E00030DA8 = {
+ fileRef = 012AD9B400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0905F04896C0E00030DA8 = {
+ fileRef = 012AD9B700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0906004896C0E00030DA8 = {
+ fileRef = 012ADB3F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0906104896C0E00030DA8 = {
+ fileRef = 012ADA8C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0906204896C0E00030DA8 = {
+ fileRef = 012ADA9B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0906304896C0E00030DA8 = {
+ fileRef = 012ADA6C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0906404896C0E00030DA8 = {
+ fileRef = 012ADA8100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0906504896C0E00030DA8 = {
+ fileRef = 012AD93700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0906604896C0E00030DA8 = {
+ fileRef = 012AD93100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0906704896C0E00030DA8 = {
+ fileRef = 012AD93900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0906804896C0E00030DA8 = {
+ fileRef = 012AD93500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0906904896C0E00030DA8 = {
+ fileRef = 012AD93300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0906A04896C0E00030DA8 = {
+ fileRef = 012AD91E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0906B04896C0E00030DA8 = {
+ fileRef = 012AD91800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0906C04896C0E00030DA8 = {
+ fileRef = 012AD92200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0906D04896C0E00030DA8 = {
+ fileRef = 012AD90900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0906E04896C0E00030DA8 = {
+ fileRef = 012AD90E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0906F04896C0E00030DA8 = {
+ fileRef = 012AD91C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0907004896C0E00030DA8 = {
+ fileRef = 012AD91600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0907104896C0E00030DA8 = {
+ fileRef = 012AD92A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0907204896C0E00030DA8 = {
+ fileRef = 012AD91A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0907304896C0E00030DA8 = {
+ fileRef = 012AD92000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0907404896C0E00030DA8 = {
+ fileRef = 012AD93B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0907504896C0E00030DA8 = {
+ fileRef = 012AD92D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0907604896C0E00030DA8 = {
+ fileRef = 012AD92F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0907704896C0E00030DA8 = {
+ fileRef = 012AD93C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0907804896C0E00030DA8 = {
+ fileRef = 012AD91300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0907904896C0E00030DA8 = {
+ fileRef = 012AD91100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0907A04896C0E00030DA8 = {
+ fileRef = 012AD90C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0907B04896C0E00030DA8 = {
+ fileRef = 012AD90F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0907C04896C0E00030DA8 = {
+ fileRef = 012AD91400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0907D04896C0E00030DA8 = {
+ fileRef = 012AD90800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0907E04896C0E00030DA8 = {
+ fileRef = 015ECC0C00894EC0C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0907F04896C0E00030DA8 = {
+ fileRef = 011F78F200B25B65C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0908604896C0E00030DA8 = {
+ fileRef = F5ED1435037096A001F6289A;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0908704896C0E00030DA8 = {
+ buildActionMask = 2147483647;
+ files = (
+ 4FF0908804896C0E00030DA8,
+ 4FF0908904896C0E00030DA8,
+ 4FF0908A04896C0E00030DA8,
+ );
+ isa = PBXResourcesBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 4FF0908804896C0E00030DA8 = {
+ fileRef = 043627B300868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0908904896C0E00030DA8 = {
+ fileRef = 043627B200868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0908A04896C0E00030DA8 = {
+ fileRef = 043627B400868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0908B04896C0E00030DA8 = {
+ buildActionMask = 2147483647;
+ files = (
+ 4FF0908C04896C0E00030DA8,
+ 4FF0908D04896C0E00030DA8,
+ 4FF0908E04896C0E00030DA8,
+ 4FF0908F04896C0E00030DA8,
+ 4FF0909004896C0E00030DA8,
+ 4FF0909104896C0E00030DA8,
+ 4FF0909204896C0E00030DA8,
+ 4FF0909304896C0E00030DA8,
+ 4FF0909404896C0E00030DA8,
+ 4FF0909504896C0E00030DA8,
+ 4FF0909604896C0E00030DA8,
+ 4FF0909704896C0E00030DA8,
+ 4FF0909804896C0E00030DA8,
+ 4FF0909904896C0E00030DA8,
+ 4FF0909A04896C0E00030DA8,
+ 4FF0909B04896C0E00030DA8,
+ 4FF0909C04896C0E00030DA8,
+ 4FF0909D04896C0E00030DA8,
+ 4FF0909E04896C0E00030DA8,
+ 4FF0909F04896C0E00030DA8,
+ 4FF090A004896C0E00030DA8,
+ 4FF090A104896C0E00030DA8,
+ 4FF090A204896C0E00030DA8,
+ 4FF090A304896C0E00030DA8,
+ 4FF090A404896C0E00030DA8,
+ 4FF090A504896C0E00030DA8,
+ 4FF090A604896C0E00030DA8,
+ 4FF090A704896C0E00030DA8,
+ 4FF090A804896C0E00030DA8,
+ 4FF090A904896C0E00030DA8,
+ 4FF090AA04896C0E00030DA8,
+ 4FF090AB04896C0E00030DA8,
+ 4FF090AC04896C0E00030DA8,
+ 4FF090AD04896C0E00030DA8,
+ 4FF090AE04896C0E00030DA8,
+ 4FF090AF04896C0E00030DA8,
+ 4FF090B004896C0E00030DA8,
+ 4FF090B104896C0E00030DA8,
+ 4FF090B204896C0E00030DA8,
+ 4FF090B304896C0E00030DA8,
+ 4FF090B404896C0E00030DA8,
+ 4FF090B504896C0E00030DA8,
+ 4FF090B604896C0E00030DA8,
+ 4FF090B704896C0E00030DA8,
+ 4FF090B804896C0E00030DA8,
+ 4FF090B904896C0E00030DA8,
+ 4FF090BA04896C0E00030DA8,
+ 4FF090BB04896C0E00030DA8,
+ 4FF090BC04896C0E00030DA8,
+ 4FF090BD04896C0E00030DA8,
+ 4FF090BE04896C0E00030DA8,
+ 4FF090BF04896C0E00030DA8,
+ 4FF090C004896C0E00030DA8,
+ 4FF090C104896C0E00030DA8,
+ 4FF090C204896C0E00030DA8,
+ 4FF090C304896C0E00030DA8,
+ 4FF090C404896C0E00030DA8,
+ 4FF090C504896C0E00030DA8,
+ 4FF090C604896C0E00030DA8,
+ 4FF090C704896C0E00030DA8,
+ 4FF090C804896C0E00030DA8,
+ 4FF090C904896C0E00030DA8,
+ 4FF090CA04896C0E00030DA8,
+ 4FF090CB04896C0E00030DA8,
+ 4FF090CC04896C0E00030DA8,
+ 4FF090CD04896C0E00030DA8,
+ 4FF090CE04896C0E00030DA8,
+ 4FF090CF04896C0E00030DA8,
+ 4FF090D004896C0E00030DA8,
+ 4FF090D104896C0E00030DA8,
+ 4FF090D204896C0E00030DA8,
+ 4FF090D304896C0E00030DA8,
+ 4FF090D404896C0E00030DA8,
+ 4FF090D504896C0E00030DA8,
+ 4FF090D604896C0E00030DA8,
+ 4FF090D704896C0E00030DA8,
+ 4FF090D804896C0E00030DA8,
+ 4FF090D904896C0E00030DA8,
+ 4FF090DA04896C0E00030DA8,
+ 4FF090DB04896C0E00030DA8,
+ 4FF090DC04896C0E00030DA8,
+ 4FF090DD04896C0E00030DA8,
+ 4FF090DE04896C0E00030DA8,
+ 4FF090DF04896C0E00030DA8,
+ 4FF090E004896C0E00030DA8,
+ 4FF090E104896C0E00030DA8,
+ 4FF090E204896C0E00030DA8,
+ 4FF090E304896C0E00030DA8,
+ 4FF090E404896C0E00030DA8,
+ 4FF090E504896C0E00030DA8,
+ 4FF090E604896C0E00030DA8,
+ 4FF090E704896C0E00030DA8,
+ 4FF090E804896C0E00030DA8,
+ 4FF090E904896C0E00030DA8,
+ 4FF090EA04896C0E00030DA8,
+ 4FF090EB04896C0E00030DA8,
+ 4FF090EC04896C0E00030DA8,
+ 4FF090ED04896C0E00030DA8,
+ 4FF090EE04896C0E00030DA8,
+ 4FF090EF04896C0E00030DA8,
+ 4FF090F004896C0E00030DA8,
+ 4FF090F104896C0E00030DA8,
+ 4FF090F204896C0E00030DA8,
+ 4FF090F304896C0E00030DA8,
+ 4FF090F404896C0E00030DA8,
+ 4FF090F504896C0E00030DA8,
+ 4FF090F604896C0E00030DA8,
+ 4FF090F704896C0E00030DA8,
+ 4FF090F804896C0E00030DA8,
+ 4FF090F904896C0E00030DA8,
+ 4FF090FA04896C0E00030DA8,
+ 4FF090FB04896C0E00030DA8,
+ 4FF090FC04896C0E00030DA8,
+ 4FF090FD04896C0E00030DA8,
+ 4FF090FE04896C0E00030DA8,
+ 4FF090FF04896C0E00030DA8,
+ 4FF0910004896C0E00030DA8,
+ 4FF0910104896C0E00030DA8,
+ 4FF0910204896C0E00030DA8,
+ 4FF0910304896C0E00030DA8,
+ 4FF0910404896C0E00030DA8,
+ 4FF0910504896C0E00030DA8,
+ 4FF0910604896C0E00030DA8,
+ 4FF0910704896C0E00030DA8,
+ 4FF0910804896C0E00030DA8,
+ 4FF0910904896C0E00030DA8,
+ 4FF0910A04896C0E00030DA8,
+ 4FF0910B04896C0E00030DA8,
+ 4FF0910C04896C0E00030DA8,
+ 4FF0910D04896C0E00030DA8,
+ 4FF0910E04896C0E00030DA8,
+ 4FF0910F04896C0E00030DA8,
+ 4FF0911004896C0E00030DA8,
+ 4FF0911104896C0E00030DA8,
+ 4FF0911204896C0E00030DA8,
+ 4FF0911304896C0E00030DA8,
+ 4FF0911404896C0E00030DA8,
+ 4FF0911504896C0E00030DA8,
+ 4FF0911B04896C0E00030DA8,
+ 4FF0911C04896C0E00030DA8,
+ );
+ isa = PBXSourcesBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 4FF0908C04896C0E00030DA8 = {
+ fileRef = 043627A700868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0908D04896C0E00030DA8 = {
+ fileRef = 043627A800868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0908E04896C0E00030DA8 = {
+ fileRef = 043627AB00868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0908F04896C0E00030DA8 = {
+ fileRef = 043627AD00868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0909004896C0E00030DA8 = {
+ fileRef = 043627AF00868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0909104896C0E00030DA8 = {
+ fileRef = 043627B100868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0909204896C0E00030DA8 = {
+ fileRef = 012ADAF600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0909304896C0E00030DA8 = {
+ fileRef = 012ADA6100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0909404896C0E00030DA8 = {
+ fileRef = 012ADA6000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0909504896C0E00030DA8 = {
+ fileRef = 012ADB1200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0909604896C0E00030DA8 = {
+ fileRef = 012ADAF700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0909704896C0E00030DA8 = {
+ fileRef = 012ADAF800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0909804896C0E00030DA8 = {
+ fileRef = 012ADAF900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0909904896C0E00030DA8 = {
+ fileRef = 012ADB0100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0909A04896C0E00030DA8 = {
+ fileRef = 012ADB0200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0909B04896C0E00030DA8 = {
+ fileRef = 012ADAFF00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0909C04896C0E00030DA8 = {
+ fileRef = 012ADB5800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0909D04896C0E00030DA8 = {
+ fileRef = 012AD9A600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0909E04896C0E00030DA8 = {
+ fileRef = 012AD9A700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0909F04896C0E00030DA8 = {
+ fileRef = 012AD9A800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090A004896C0E00030DA8 = {
+ fileRef = 012AD9A900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090A104896C0E00030DA8 = {
+ fileRef = 012AD9AA00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090A204896C0E00030DA8 = {
+ fileRef = 012AD9AB00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090A304896C0E00030DA8 = {
+ fileRef = 012AD9AC00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090A404896C0E00030DA8 = {
+ fileRef = 012AD9AD00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090A504896C0E00030DA8 = {
+ fileRef = 012AD9AE00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090A604896C0E00030DA8 = {
+ fileRef = 012AD9AF00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090A704896C0E00030DA8 = {
+ fileRef = 012ADAED00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090A804896C0E00030DA8 = {
+ fileRef = 012ADAEF00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090A904896C0E00030DA8 = {
+ fileRef = 012ADAF400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090AA04896C0E00030DA8 = {
+ fileRef = 012ADAF500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090AB04896C0E00030DA8 = {
+ fileRef = 012ADAFA00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090AC04896C0E00030DA8 = {
+ fileRef = 012ADAFB00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090AD04896C0E00030DA8 = {
+ fileRef = 012ADAFC00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090AE04896C0E00030DA8 = {
+ fileRef = 012ADB0A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090AF04896C0E00030DA8 = {
+ fileRef = 012ADB0B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090B004896C0E00030DA8 = {
+ fileRef = 012ADB0C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090B104896C0E00030DA8 = {
+ fileRef = 012ADB0D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090B204896C0E00030DA8 = {
+ fileRef = 012ADB0E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090B304896C0E00030DA8 = {
+ fileRef = 012ADB0F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090B404896C0E00030DA8 = {
+ fileRef = 012ADB1000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090B504896C0E00030DA8 = {
+ fileRef = 012ADB1100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090B604896C0E00030DA8 = {
+ fileRef = 012ADB1300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090B704896C0E00030DA8 = {
+ fileRef = 012ADB1500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090B804896C0E00030DA8 = {
+ fileRef = 012ADB1600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090B904896C0E00030DA8 = {
+ fileRef = 012ADB1700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090BA04896C0E00030DA8 = {
+ fileRef = 012ADB1800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090BB04896C0E00030DA8 = {
+ fileRef = 012ADB1900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090BC04896C0E00030DA8 = {
+ fileRef = 012ADB1B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090BD04896C0E00030DA8 = {
+ fileRef = 012ADB1C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090BE04896C0E00030DA8 = {
+ fileRef = 012ADB1D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090BF04896C0E00030DA8 = {
+ fileRef = 012ADB1E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090C004896C0E00030DA8 = {
+ fileRef = 012ADB1F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090C104896C0E00030DA8 = {
+ fileRef = 012ADB2000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090C204896C0E00030DA8 = {
+ fileRef = 012ADB2100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090C304896C0E00030DA8 = {
+ fileRef = 012ADB2200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090C404896C0E00030DA8 = {
+ fileRef = 012ADB2500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090C504896C0E00030DA8 = {
+ fileRef = 012ADB2600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090C604896C0E00030DA8 = {
+ fileRef = 012ADB2700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090C704896C0E00030DA8 = {
+ fileRef = 012ADB2800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090C804896C0E00030DA8 = {
+ fileRef = 012ADB2900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090C904896C0E00030DA8 = {
+ fileRef = 012ADB2A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090CA04896C0E00030DA8 = {
+ fileRef = 012ADB2B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090CB04896C0E00030DA8 = {
+ fileRef = 012ADB2D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090CC04896C0E00030DA8 = {
+ fileRef = 012ADB2E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090CD04896C0E00030DA8 = {
+ fileRef = 012ADB5700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090CE04896C0E00030DA8 = {
+ fileRef = 012AD9B200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090CF04896C0E00030DA8 = {
+ fileRef = 012AD9B300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090D004896C0E00030DA8 = {
+ fileRef = 012AD9B500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090D104896C0E00030DA8 = {
+ fileRef = 012AD9B600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090D204896C0E00030DA8 = {
+ fileRef = 012AD9B800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090D304896C0E00030DA8 = {
+ fileRef = 012ADB3B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090D404896C0E00030DA8 = {
+ fileRef = 012ADB3800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090D504896C0E00030DA8 = {
+ fileRef = 012ADB3E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090D604896C0E00030DA8 = {
+ fileRef = 012ADA9800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090D704896C0E00030DA8 = {
+ fileRef = 012ADA9600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090D804896C0E00030DA8 = {
+ fileRef = 012ADA8B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090D904896C0E00030DA8 = {
+ fileRef = 012ADA6600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090DA04896C0E00030DA8 = {
+ fileRef = 012ADA7100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090DB04896C0E00030DA8 = {
+ fileRef = 012ADAA200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090DC04896C0E00030DA8 = {
+ fileRef = 012ADA6F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090DD04896C0E00030DA8 = {
+ fileRef = 012ADA7900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090DE04896C0E00030DA8 = {
+ fileRef = 012ADA6D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090DF04896C0E00030DA8 = {
+ fileRef = 012ADA7400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090E004896C0E00030DA8 = {
+ fileRef = 012ADA6B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090E104896C0E00030DA8 = {
+ fileRef = 012ADA6A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090E204896C0E00030DA8 = {
+ fileRef = 012ADA7600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090E304896C0E00030DA8 = {
+ fileRef = 012ADA6900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090E404896C0E00030DA8 = {
+ fileRef = 012ADA7500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090E504896C0E00030DA8 = {
+ fileRef = 012ADA6800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090E604896C0E00030DA8 = {
+ fileRef = 012ADA8D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090E704896C0E00030DA8 = {
+ fileRef = 012ADA7000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090E804896C0E00030DA8 = {
+ fileRef = 012ADA8500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090E904896C0E00030DA8 = {
+ fileRef = 012ADA7800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090EA04896C0E00030DA8 = {
+ fileRef = 012ADA8400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090EB04896C0E00030DA8 = {
+ fileRef = 012ADA8200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090EC04896C0E00030DA8 = {
+ fileRef = 012ADA8900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090ED04896C0E00030DA8 = {
+ fileRef = 012ADA7F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090EE04896C0E00030DA8 = {
+ fileRef = 012ADA8000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090EF04896C0E00030DA8 = {
+ fileRef = 012ADA9000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090F004896C0E00030DA8 = {
+ fileRef = 012ADA8800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090F104896C0E00030DA8 = {
+ fileRef = 012ADA7300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090F204896C0E00030DA8 = {
+ fileRef = 012ADA7B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090F304896C0E00030DA8 = {
+ fileRef = 012ADA8300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090F404896C0E00030DA8 = {
+ fileRef = 012ADA7C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090F504896C0E00030DA8 = {
+ fileRef = 012ADA7D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090F604896C0E00030DA8 = {
+ fileRef = 012ADA6E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090F704896C0E00030DA8 = {
+ fileRef = 012AD92C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090F804896C0E00030DA8 = {
+ fileRef = 012AD92400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090F904896C0E00030DA8 = {
+ fileRef = 012AD93600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090FA04896C0E00030DA8 = {
+ fileRef = 012AD93000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090FB04896C0E00030DA8 = {
+ fileRef = 012AD93800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090FC04896C0E00030DA8 = {
+ fileRef = 012AD93400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090FD04896C0E00030DA8 = {
+ fileRef = 012AD93200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090FE04896C0E00030DA8 = {
+ fileRef = 012AD92500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF090FF04896C0E00030DA8 = {
+ fileRef = 012AD92B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0910004896C0E00030DA8 = {
+ fileRef = 012AD92300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0910104896C0E00030DA8 = {
+ fileRef = 012AD92700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0910204896C0E00030DA8 = {
+ fileRef = 012AD91D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0910304896C0E00030DA8 = {
+ fileRef = 012AD91700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0910404896C0E00030DA8 = {
+ fileRef = 012AD92100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0910504896C0E00030DA8 = {
+ fileRef = 012AD90A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0910604896C0E00030DA8 = {
+ fileRef = 012AD90D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0910704896C0E00030DA8 = {
+ fileRef = 012AD91B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0910804896C0E00030DA8 = {
+ fileRef = 012AD91500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0910904896C0E00030DA8 = {
+ fileRef = 012AD92600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0910A04896C0E00030DA8 = {
+ fileRef = 012AD92900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0910B04896C0E00030DA8 = {
+ fileRef = 012AD91900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0910C04896C0E00030DA8 = {
+ fileRef = 012AD91F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0910D04896C0E00030DA8 = {
+ fileRef = 012AD93A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0910E04896C0E00030DA8 = {
+ fileRef = 012AD92E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0910F04896C0E00030DA8 = {
+ fileRef = 012AD92800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0911004896C0E00030DA8 = {
+ fileRef = 012AD91200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0911104896C0E00030DA8 = {
+ fileRef = 012AD91000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0911204896C0E00030DA8 = {
+ fileRef = 012AD90B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0911304896C0E00030DA8 = {
+ fileRef = 015ECC0D00894EC0C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0911404896C0E00030DA8 = {
+ fileRef = 016B4A3B00ACCF9FC697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0911504896C0E00030DA8 = {
+ fileRef = 016F1B6300ACDA9BC697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0911B04896C0E00030DA8 = {
+ fileRef = 4FB23863047AB9F60098ACF3;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0911C04896C0E00030DA8 = {
+ fileRef = 012ADAF100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0911D04896C0E00030DA8 = {
+ buildActionMask = 2147483647;
+ files = (
+ 4FF0911E04896C0E00030DA8,
+ 4FF0911F04896C0E00030DA8,
+ 4FF0912004896C0E00030DA8,
+ 4FF0912104896C0E00030DA8,
+ 4FF0912204896C0E00030DA8,
+ 4FF0912304896C0E00030DA8,
+ );
+ isa = PBXFrameworksBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 4FF0911E04896C0E00030DA8 = {
+ fileRef = 0654BA58FE8ECEE0C697A12F;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0911F04896C0E00030DA8 = {
+ fileRef = 0654BA5AFE8ECEE0C697A12F;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0912004896C0E00030DA8 = {
+ fileRef = 0654BA5BFE8ECEE0C697A12F;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0912104896C0E00030DA8 = {
+ fileRef = 00E9D914FEDB4D29C697A12F;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0912204896C0E00030DA8 = {
+ fileRef = F564505801E623B201F62882;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0912304896C0E00030DA8 = {
+ fileRef = 0654BA59FE8ECEE0C697A12F;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0912404896C0E00030DA8 = {
+ buildActionMask = 2147483647;
+ files = (
+ );
+ isa = PBXRezBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 4FF0912504896C0E00030DA8 = {
+ explicitFileType = wrapper.application;
+ isa = PBXFileReference;
+ path = "Quake3 G4.app";
+ refType = 3;
+ sourceTree = BUILT_PRODUCTS_DIR;
+ };
+ 4FF0912704896C1600030DA8 = {
+ buildPhases = (
+ 4FF0912804896C1600030DA8,
+ 4FF0915C04896C1600030DA8,
+ 4FF091E004896C1600030DA8,
+ 4FF091E704896C1600030DA8,
+ );
+ buildSettings = {
+ DEBUGGING_SYMBOLS = NO;
+ GCC_VERSION = 3.3;
+ INSTALL_PATH = "";
+ LIBRARY_SEARCH_PATHS = "\"/Users/zaphod/Quake3/code/macosx/GameRanger SDK/Libraries\"";
+ OPTIMIZATION_CFLAGS = "-O2";
+ OTHER_CFLAGS = "-DMACOS_X -DBOTLIB -DMISSIONPACK -DSMP -force_cpusubtype_ALL -faltivec -falign-loops=16 -falign-jumps=16 -fstrict-aliasing ";
+ OTHER_LDFLAGS = "";
+ OTHER_REZFLAGS = "";
+ PRODUCT_NAME = Q3DedicatedServer;
+ REZ_EXECUTABLE = YES;
+ SECTORDER_FLAGS = "";
+ WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas";
+ };
+ dependencies = (
+ );
+ isa = PBXToolTarget;
+ name = "Dedicated Server G4";
+ productInstallPath = "";
+ productName = "Dedicated Server";
+ productReference = 4FF091E804896C1600030DA8;
+ };
+ 4FF0912804896C1600030DA8 = {
+ buildActionMask = 2147483647;
+ files = (
+ 4FF0912904896C1600030DA8,
+ 4FF0912A04896C1600030DA8,
+ 4FF0912B04896C1600030DA8,
+ 4FF0912C04896C1600030DA8,
+ 4FF0912D04896C1600030DA8,
+ 4FF0912E04896C1600030DA8,
+ 4FF0912F04896C1600030DA8,
+ 4FF0913004896C1600030DA8,
+ 4FF0913104896C1600030DA8,
+ 4FF0913204896C1600030DA8,
+ 4FF0913304896C1600030DA8,
+ 4FF0913404896C1600030DA8,
+ 4FF0913504896C1600030DA8,
+ 4FF0913604896C1600030DA8,
+ 4FF0913704896C1600030DA8,
+ 4FF0913804896C1600030DA8,
+ 4FF0913904896C1600030DA8,
+ 4FF0913A04896C1600030DA8,
+ 4FF0913B04896C1600030DA8,
+ 4FF0913C04896C1600030DA8,
+ 4FF0913D04896C1600030DA8,
+ 4FF0913E04896C1600030DA8,
+ 4FF0913F04896C1600030DA8,
+ 4FF0914004896C1600030DA8,
+ 4FF0914104896C1600030DA8,
+ 4FF0914204896C1600030DA8,
+ 4FF0914304896C1600030DA8,
+ 4FF0914404896C1600030DA8,
+ 4FF0914504896C1600030DA8,
+ 4FF0914604896C1600030DA8,
+ 4FF0914704896C1600030DA8,
+ 4FF0914804896C1600030DA8,
+ 4FF0914904896C1600030DA8,
+ 4FF0914A04896C1600030DA8,
+ 4FF0914B04896C1600030DA8,
+ 4FF0914C04896C1600030DA8,
+ 4FF0914D04896C1600030DA8,
+ 4FF0914E04896C1600030DA8,
+ 4FF0914F04896C1600030DA8,
+ 4FF0915004896C1600030DA8,
+ 4FF0915104896C1600030DA8,
+ 4FF0915204896C1600030DA8,
+ 4FF0915304896C1600030DA8,
+ 4FF0915404896C1600030DA8,
+ 4FF0915604896C1600030DA8,
+ 4FF0915704896C1600030DA8,
+ 4FF0915804896C1600030DA8,
+ 4FF0915904896C1600030DA8,
+ 4FF0915A04896C1600030DA8,
+ 4FF0915B04896C1600030DA8,
+ );
+ isa = PBXHeadersBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 4FF0912904896C1600030DA8 = {
+ fileRef = 012ADB0300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0912A04896C1600030DA8 = {
+ fileRef = 012ADB0000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0912B04896C1600030DA8 = {
+ fileRef = 012ADAFE00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0912C04896C1600030DA8 = {
+ fileRef = 012ADAFD00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0912D04896C1600030DA8 = {
+ fileRef = 012ADAF300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0912E04896C1600030DA8 = {
+ fileRef = 012ADAF200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0912F04896C1600030DA8 = {
+ fileRef = 012ADAF000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0913004896C1600030DA8 = {
+ fileRef = 012ADAEE00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0913104896C1600030DA8 = {
+ fileRef = 012ADB2400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0913204896C1600030DA8 = {
+ fileRef = 012ADB3F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0913304896C1600030DA8 = {
+ fileRef = 012ADB1400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0913404896C1600030DA8 = {
+ fileRef = 012ADB1A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0913504896C1600030DA8 = {
+ fileRef = 012ADB0800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0913604896C1600030DA8 = {
+ fileRef = 012ADB0900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0913704896C1600030DA8 = {
+ fileRef = 012ADA6C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0913804896C1600030DA8 = {
+ fileRef = 012ADA8100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0913904896C1600030DA8 = {
+ fileRef = 012ADA8C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0913A04896C1600030DA8 = {
+ fileRef = 012ADA9B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0913B04896C1600030DA8 = {
+ fileRef = 012ADA6200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0913C04896C1600030DA8 = {
+ fileRef = 012AD90800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0913D04896C1600030DA8 = {
+ fileRef = 012AD90900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0913E04896C1600030DA8 = {
+ fileRef = 012AD90C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0913F04896C1600030DA8 = {
+ fileRef = 012AD90E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0914004896C1600030DA8 = {
+ fileRef = 012AD90F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0914104896C1600030DA8 = {
+ fileRef = 012AD91100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0914204896C1600030DA8 = {
+ fileRef = 012AD91300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0914304896C1600030DA8 = {
+ fileRef = 012AD91400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0914404896C1600030DA8 = {
+ fileRef = 012AD91600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0914504896C1600030DA8 = {
+ fileRef = 012AD91800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0914604896C1600030DA8 = {
+ fileRef = 012AD91A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0914704896C1600030DA8 = {
+ fileRef = 012AD91C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0914804896C1600030DA8 = {
+ fileRef = 012AD91E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0914904896C1600030DA8 = {
+ fileRef = 012AD92000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0914A04896C1600030DA8 = {
+ fileRef = 012AD92200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0914B04896C1600030DA8 = {
+ fileRef = 012AD92A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0914C04896C1600030DA8 = {
+ fileRef = 012AD92D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0914D04896C1600030DA8 = {
+ fileRef = 012AD92F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0914E04896C1600030DA8 = {
+ fileRef = 012AD93100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0914F04896C1600030DA8 = {
+ fileRef = 012AD93300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0915004896C1600030DA8 = {
+ fileRef = 012AD93500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0915104896C1600030DA8 = {
+ fileRef = 012AD93700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0915204896C1600030DA8 = {
+ fileRef = 012AD93900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0915304896C1600030DA8 = {
+ fileRef = 012AD93B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0915404896C1600030DA8 = {
+ fileRef = 012AD93C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0915604896C1600030DA8 = {
+ fileRef = 015ECC0C00894EC0C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0915704896C1600030DA8 = {
+ fileRef = 011F78F200B25B65C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0915804896C1600030DA8 = {
+ fileRef = 043627A600868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0915904896C1600030DA8 = {
+ fileRef = 043627A900868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0915A04896C1600030DA8 = {
+ fileRef = 043627B000868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0915B04896C1600030DA8 = {
+ fileRef = 043627AE00868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0915C04896C1600030DA8 = {
+ buildActionMask = 2147483647;
+ files = (
+ 4FF0915E04896C1600030DA8,
+ 4FF0915F04896C1600030DA8,
+ 4FF0916004896C1600030DA8,
+ 4FF0916104896C1600030DA8,
+ 4FF0916204896C1600030DA8,
+ 4FF0916304896C1600030DA8,
+ 4FF0916404896C1600030DA8,
+ 4FF0916504896C1600030DA8,
+ 4FF0916604896C1600030DA8,
+ 4FF0916704896C1600030DA8,
+ 4FF0916804896C1600030DA8,
+ 4FF0916904896C1600030DA8,
+ 4FF0916A04896C1600030DA8,
+ 4FF0916B04896C1600030DA8,
+ 4FF0916C04896C1600030DA8,
+ 4FF0916D04896C1600030DA8,
+ 4FF0916E04896C1600030DA8,
+ 4FF0916F04896C1600030DA8,
+ 4FF0917004896C1600030DA8,
+ 4FF0917104896C1600030DA8,
+ 4FF0917204896C1600030DA8,
+ 4FF0917304896C1600030DA8,
+ 4FF0917404896C1600030DA8,
+ 4FF0917504896C1600030DA8,
+ 4FF0917604896C1600030DA8,
+ 4FF0917704896C1600030DA8,
+ 4FF0917804896C1600030DA8,
+ 4FF0917904896C1600030DA8,
+ 4FF0917A04896C1600030DA8,
+ 4FF0917B04896C1600030DA8,
+ 4FF0917C04896C1600030DA8,
+ 4FF0917D04896C1600030DA8,
+ 4FF0917E04896C1600030DA8,
+ 4FF0917F04896C1600030DA8,
+ 4FF0918004896C1600030DA8,
+ 4FF0918104896C1600030DA8,
+ 4FF0918204896C1600030DA8,
+ 4FF0918304896C1600030DA8,
+ 4FF0918404896C1600030DA8,
+ 4FF0918504896C1600030DA8,
+ 4FF0918604896C1600030DA8,
+ 4FF0918704896C1600030DA8,
+ 4FF0918804896C1600030DA8,
+ 4FF0918904896C1600030DA8,
+ 4FF0918A04896C1600030DA8,
+ 4FF0918B04896C1600030DA8,
+ 4FF0918C04896C1600030DA8,
+ 4FF0918D04896C1600030DA8,
+ 4FF0918E04896C1600030DA8,
+ 4FF0918F04896C1600030DA8,
+ 4FF0919004896C1600030DA8,
+ 4FF0919104896C1600030DA8,
+ 4FF0919204896C1600030DA8,
+ 4FF0919304896C1600030DA8,
+ 4FF0919404896C1600030DA8,
+ 4FF0919504896C1600030DA8,
+ 4FF0919604896C1600030DA8,
+ 4FF0919704896C1600030DA8,
+ 4FF0919804896C1600030DA8,
+ 4FF0919904896C1600030DA8,
+ 4FF0919A04896C1600030DA8,
+ 4FF0919B04896C1600030DA8,
+ 4FF0919C04896C1600030DA8,
+ 4FF0919D04896C1600030DA8,
+ 4FF0919E04896C1600030DA8,
+ 4FF0919F04896C1600030DA8,
+ 4FF091A004896C1600030DA8,
+ 4FF091A104896C1600030DA8,
+ 4FF091A204896C1600030DA8,
+ 4FF091A304896C1600030DA8,
+ 4FF091A404896C1600030DA8,
+ 4FF091A504896C1600030DA8,
+ 4FF091A604896C1600030DA8,
+ 4FF091A704896C1600030DA8,
+ 4FF091A804896C1600030DA8,
+ 4FF091A904896C1600030DA8,
+ 4FF091AA04896C1600030DA8,
+ 4FF091AB04896C1600030DA8,
+ 4FF091AC04896C1600030DA8,
+ 4FF091AD04896C1600030DA8,
+ 4FF091AE04896C1600030DA8,
+ 4FF091AF04896C1600030DA8,
+ 4FF091B004896C1600030DA8,
+ 4FF091B104896C1600030DA8,
+ 4FF091B204896C1600030DA8,
+ 4FF091B304896C1600030DA8,
+ 4FF091B404896C1600030DA8,
+ 4FF091B504896C1600030DA8,
+ 4FF091B604896C1600030DA8,
+ 4FF091B704896C1600030DA8,
+ 4FF091B804896C1600030DA8,
+ 4FF091B904896C1600030DA8,
+ 4FF091BA04896C1600030DA8,
+ 4FF091BB04896C1600030DA8,
+ 4FF091BC04896C1600030DA8,
+ 4FF091BD04896C1600030DA8,
+ 4FF091BE04896C1600030DA8,
+ 4FF091BF04896C1600030DA8,
+ 4FF091C004896C1600030DA8,
+ 4FF091C104896C1600030DA8,
+ 4FF091C204896C1600030DA8,
+ 4FF091C304896C1600030DA8,
+ 4FF091C404896C1600030DA8,
+ 4FF091C504896C1600030DA8,
+ 4FF091C604896C1600030DA8,
+ 4FF091C704896C1600030DA8,
+ 4FF091C804896C1600030DA8,
+ 4FF091C904896C1600030DA8,
+ 4FF091CA04896C1600030DA8,
+ 4FF091CB04896C1600030DA8,
+ 4FF091CC04896C1600030DA8,
+ 4FF091CD04896C1600030DA8,
+ 4FF091CE04896C1600030DA8,
+ 4FF091CF04896C1600030DA8,
+ 4FF091D004896C1600030DA8,
+ 4FF091D104896C1600030DA8,
+ 4FF091D304896C1600030DA8,
+ 4FF091D404896C1600030DA8,
+ 4FF091D504896C1600030DA8,
+ 4FF091D604896C1600030DA8,
+ 4FF091D704896C1600030DA8,
+ 4FF091D804896C1600030DA8,
+ 4FF091D904896C1600030DA8,
+ 4FF091DD04896C1600030DA8,
+ 4FF091DF04896C1600030DA8,
+ );
+ isa = PBXSourcesBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 4FF0915E04896C1600030DA8 = {
+ fileRef = 012ADB0200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0915F04896C1600030DA8 = {
+ fileRef = 012ADAFF00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0916004896C1600030DA8 = {
+ fileRef = 012ADB0100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0916104896C1600030DA8 = {
+ fileRef = 012ADAFC00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0916204896C1600030DA8 = {
+ fileRef = 012ADAFB00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0916304896C1600030DA8 = {
+ fileRef = 012ADAFA00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0916404896C1600030DA8 = {
+ fileRef = 016F1B6300ACDA9BC697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0916504896C1600030DA8 = {
+ fileRef = 012ADAF900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0916604896C1600030DA8 = {
+ fileRef = 012ADAF800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0916704896C1600030DA8 = {
+ fileRef = 012ADAF700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0916804896C1600030DA8 = {
+ fileRef = 012ADAF600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0916904896C1600030DA8 = {
+ fileRef = 012ADAF500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0916A04896C1600030DA8 = {
+ fileRef = 012ADAF400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0916B04896C1600030DA8 = {
+ fileRef = 012ADAF100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0916C04896C1600030DA8 = {
+ fileRef = 012ADAEF00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0916D04896C1600030DA8 = {
+ fileRef = 012ADAED00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0916E04896C1600030DA8 = {
+ fileRef = 012ADB2500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0916F04896C1600030DA8 = {
+ fileRef = 012ADB2600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0917004896C1600030DA8 = {
+ fileRef = 012ADB2700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0917104896C1600030DA8 = {
+ fileRef = 012ADB2800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0917204896C1600030DA8 = {
+ fileRef = 012ADB2900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0917304896C1600030DA8 = {
+ fileRef = 012ADB2A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0917404896C1600030DA8 = {
+ fileRef = 012ADB2B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0917504896C1600030DA8 = {
+ fileRef = 012ADB2D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0917604896C1600030DA8 = {
+ fileRef = 012ADB2E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0917704896C1600030DA8 = {
+ fileRef = 012ADB5700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0917804896C1600030DA8 = {
+ fileRef = 012ADB5800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0917904896C1600030DA8 = {
+ fileRef = 012ADB3800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0917A04896C1600030DA8 = {
+ fileRef = 012ADB3B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0917B04896C1600030DA8 = {
+ fileRef = 012ADB3E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0917C04896C1600030DA8 = {
+ fileRef = 012ADB0A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0917D04896C1600030DA8 = {
+ fileRef = 012ADB0B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0917E04896C1600030DA8 = {
+ fileRef = 012ADB0C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0917F04896C1600030DA8 = {
+ fileRef = 012ADB0D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0918004896C1600030DA8 = {
+ fileRef = 012ADB0E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0918104896C1600030DA8 = {
+ fileRef = 012ADB0F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0918204896C1600030DA8 = {
+ fileRef = 012ADB1000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0918304896C1600030DA8 = {
+ fileRef = 012ADB1100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0918404896C1600030DA8 = {
+ fileRef = 012ADB1200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0918504896C1600030DA8 = {
+ fileRef = 012ADB1300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0918604896C1600030DA8 = {
+ fileRef = 012ADB1500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0918704896C1600030DA8 = {
+ fileRef = 012ADB1600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0918804896C1600030DA8 = {
+ fileRef = 012ADB1700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0918904896C1600030DA8 = {
+ fileRef = 012ADB1800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0918A04896C1600030DA8 = {
+ fileRef = 012ADB1900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0918B04896C1600030DA8 = {
+ fileRef = 012ADB1B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0918C04896C1600030DA8 = {
+ fileRef = 012ADB1C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0918D04896C1600030DA8 = {
+ fileRef = 012ADB1D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0918E04896C1600030DA8 = {
+ fileRef = 012ADB1E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0918F04896C1600030DA8 = {
+ fileRef = 012ADB1F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0919004896C1600030DA8 = {
+ fileRef = 012ADB2000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0919104896C1600030DA8 = {
+ fileRef = 012ADB2100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0919204896C1600030DA8 = {
+ fileRef = 012ADB2200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0919304896C1600030DA8 = {
+ fileRef = 012ADA6600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0919404896C1600030DA8 = {
+ fileRef = 012ADA6800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0919504896C1600030DA8 = {
+ fileRef = 012ADA6900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0919604896C1600030DA8 = {
+ fileRef = 012ADA6A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0919704896C1600030DA8 = {
+ fileRef = 012ADA6B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0919804896C1600030DA8 = {
+ fileRef = 012ADA6D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0919904896C1600030DA8 = {
+ fileRef = 012ADA6E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0919A04896C1600030DA8 = {
+ fileRef = 012ADA6F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0919B04896C1600030DA8 = {
+ fileRef = 012ADA7000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0919C04896C1600030DA8 = {
+ fileRef = 012ADA7100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0919D04896C1600030DA8 = {
+ fileRef = 012ADA7300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0919E04896C1600030DA8 = {
+ fileRef = 012ADA7400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF0919F04896C1600030DA8 = {
+ fileRef = 012ADA7500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091A004896C1600030DA8 = {
+ fileRef = 012ADA7600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091A104896C1600030DA8 = {
+ fileRef = 012ADA7800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091A204896C1600030DA8 = {
+ fileRef = 012ADA7900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091A304896C1600030DA8 = {
+ fileRef = 012ADA7B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091A404896C1600030DA8 = {
+ fileRef = 012ADA7C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091A504896C1600030DA8 = {
+ fileRef = 012ADA7D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091A604896C1600030DA8 = {
+ fileRef = 012ADA7F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091A704896C1600030DA8 = {
+ fileRef = 012ADA8000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091A804896C1600030DA8 = {
+ fileRef = 012ADA8200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091A904896C1600030DA8 = {
+ fileRef = 012ADA8300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091AA04896C1600030DA8 = {
+ fileRef = 012ADA8400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091AB04896C1600030DA8 = {
+ fileRef = 012ADA8500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091AC04896C1600030DA8 = {
+ fileRef = 012ADA8900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091AD04896C1600030DA8 = {
+ fileRef = 012ADA8800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091AE04896C1600030DA8 = {
+ fileRef = 012ADA8B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091AF04896C1600030DA8 = {
+ fileRef = 012ADA8D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091B004896C1600030DA8 = {
+ fileRef = 012ADA9000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091B104896C1600030DA8 = {
+ fileRef = 012ADA9600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091B204896C1600030DA8 = {
+ fileRef = 012ADA9800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091B304896C1600030DA8 = {
+ fileRef = 012ADAA200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091B404896C1600030DA8 = {
+ fileRef = 012ADA6000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091B504896C1600030DA8 = {
+ fileRef = 012ADA6100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091B604896C1600030DA8 = {
+ fileRef = 012AD90A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091B704896C1600030DA8 = {
+ fileRef = 012AD90B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091B804896C1600030DA8 = {
+ fileRef = 012AD90D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091B904896C1600030DA8 = {
+ fileRef = 012AD91000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091BA04896C1600030DA8 = {
+ fileRef = 012AD91200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091BB04896C1600030DA8 = {
+ fileRef = 012AD91500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091BC04896C1600030DA8 = {
+ fileRef = 012AD91700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091BD04896C1600030DA8 = {
+ fileRef = 012AD91900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091BE04896C1600030DA8 = {
+ fileRef = 012AD91B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091BF04896C1600030DA8 = {
+ fileRef = 012AD91D00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091C004896C1600030DA8 = {
+ fileRef = 012AD91F00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091C104896C1600030DA8 = {
+ fileRef = 012AD92100868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091C204896C1600030DA8 = {
+ fileRef = 012AD92300868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091C304896C1600030DA8 = {
+ fileRef = 012AD92400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091C404896C1600030DA8 = {
+ fileRef = 012AD92500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091C504896C1600030DA8 = {
+ fileRef = 012AD92600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091C604896C1600030DA8 = {
+ fileRef = 012AD92700868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091C704896C1600030DA8 = {
+ fileRef = 012AD92800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091C804896C1600030DA8 = {
+ fileRef = 012AD92900868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091C904896C1600030DA8 = {
+ fileRef = 012AD92B00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091CA04896C1600030DA8 = {
+ fileRef = 012AD92C00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091CB04896C1600030DA8 = {
+ fileRef = 012AD92E00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091CC04896C1600030DA8 = {
+ fileRef = 012AD93000868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091CD04896C1600030DA8 = {
+ fileRef = 012AD93200868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091CE04896C1600030DA8 = {
+ fileRef = 012AD93400868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091CF04896C1600030DA8 = {
+ fileRef = 012AD93600868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091D004896C1600030DA8 = {
+ fileRef = 012AD93800868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091D104896C1600030DA8 = {
+ fileRef = 012AD93A00868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091D304896C1600030DA8 = {
+ fileRef = 015ECC0D00894EC0C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091D404896C1600030DA8 = {
+ fileRef = 043627A700868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091D504896C1600030DA8 = {
+ fileRef = 016B4A3B00ACCF9FC697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091D604896C1600030DA8 = {
+ fileRef = 043627A800868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091D704896C1600030DA8 = {
+ fileRef = 043627AD00868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091D804896C1600030DA8 = {
+ fileRef = 043627B100868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091D904896C1600030DA8 = {
+ fileRef = 043627AF00868916C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091DD04896C1600030DA8 = {
+ fileRef = 012ADAB500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091DF04896C1600030DA8 = {
+ fileRef = 4FB23863047AB9F60098ACF3;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091E004896C1600030DA8 = {
+ buildActionMask = 2147483647;
+ files = (
+ 4FF091E104896C1600030DA8,
+ 4FF091E204896C1600030DA8,
+ 4FF091E304896C1600030DA8,
+ 4FF091E404896C1600030DA8,
+ 4FF091E504896C1600030DA8,
+ 4FF091E604896C1600030DA8,
+ );
+ isa = PBXFrameworksBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 4FF091E104896C1600030DA8 = {
+ fileRef = 0654BA58FE8ECEE0C697A12F;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091E204896C1600030DA8 = {
+ fileRef = 0654BA59FE8ECEE0C697A12F;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091E304896C1600030DA8 = {
+ fileRef = 00E9D914FEDB4D29C697A12F;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091E404896C1600030DA8 = {
+ fileRef = 0654BA5AFE8ECEE0C697A12F;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091E504896C1600030DA8 = {
+ fileRef = 0654BA5BFE8ECEE0C697A12F;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091E604896C1600030DA8 = {
+ fileRef = F564505801E623B201F62882;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ 4FF091E704896C1600030DA8 = {
+ buildActionMask = 2147483647;
+ files = (
+ );
+ isa = PBXRezBuildPhase;
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 4FF091E804896C1600030DA8 = {
+ explicitFileType = "compiled.mach-o.executable";
+ isa = PBXFileReference;
+ path = Q3DedicatedServer;
+ refType = 3;
+ sourceTree = BUILT_PRODUCTS_DIR;
+ };
+ 4FF091EA04897B0000030DA8 = {
+ isa = PBXTargetDependency;
+ target = 4FF0904804896C0E00030DA8;
+ targetProxy = 1895FF2E065E291B00F8B3F4;
+ };
+//4F0
+//4F1
+//4F2
+//4F3
+//4F4
+//F50
+//F51
+//F52
+//F53
+//F54
+ F54951E80354E75E011BCB42 = {
+ fileRef = F564505801E623B201F62882;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ F54951F40354EAA2011BCB42 = {
+ fileRef = 012ADAB500868211C697A10E;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ F564505801E623B201F62882 = {
+ isa = PBXFileReference;
+ lastKnownFileType = wrapper.framework;
+ name = IOKit.framework;
+ path = /System/Library/Frameworks/IOKit.framework;
+ refType = 0;
+ sourceTree = "<absolute>";
+ };
+ F564505901E623B201F62882 = {
+ fileRef = F564505801E623B201F62882;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ F5D8C5E0035259DF0106E832 = {
+ fileRef = 0654BA59FE8ECEE0C697A12F;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ F5ED1435037096A001F6289A = {
+ fileEncoding = 30;
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ path = splines.h;
+ refType = 4;
+ sourceTree = "<group>";
+ };
+ F5ED1436037096A001F6289A = {
+ fileRef = F5ED1435037096A001F6289A;
+ isa = PBXBuildFile;
+ settings = {
+ };
+ };
+ };
+ rootObject = 0654BA41FE8ECEE0C697A12F;
+}
diff --git a/code/macosx/RecordDemo.zsh b/code/macosx/RecordDemo.zsh
new file mode 100755
index 0000000..88fb0d3
--- /dev/null
+++ b/code/macosx/RecordDemo.zsh
@@ -0,0 +1,9 @@
+#!/bin/zsh -x
+
+/Local/Public/bungi/BuildOutput/Quake3.app/Contents/MacOS/Quake3 \
+ +set sv_pure 0 \
+ +set g_syncronousClients 1 \
+ +map q3dm6 \
+ +record foo
+
+
diff --git a/code/macosx/banner.jpg b/code/macosx/banner.jpg
new file mode 100755
index 0000000..7087c34
--- /dev/null
+++ b/code/macosx/banner.jpg
Binary files differ
diff --git a/code/macosx/botlib.log b/code/macosx/botlib.log
new file mode 100755
index 0000000..e430ca6
--- /dev/null
+++ b/code/macosx/botlib.log
@@ -0,0 +1,196 @@
+item team_redobelisk has modelindex 0item team_blueobelisk has modelindex 0item team_neutralobelisk has modelindex 0item item_botroam has modelindex 0entity worldspawn unknown item
+entity target_delay unknown item
+entity light unknown item
+entity target_delay unknown item
+entity target_speaker unknown item
+entity trigger_multiple unknown item
+entity target_speaker unknown item
+entity trigger_multiple unknown item
+entity target_speaker unknown item
+entity trigger_multiple unknown item
+entity target_speaker unknown item
+entity trigger_multiple unknown item
+entity target_speaker unknown item
+entity trigger_multiple unknown item
+entity target_speaker unknown item
+entity trigger_multiple unknown item
+entity misc_model unknown item
+entity light unknown item
+entity light unknown item
+entity target_speaker unknown item
+entity target_speaker unknown item
+entity func_timer unknown item
+entity target_speaker unknown item
+entity target_speaker unknown item
+entity target_position unknown item
+entity info_player_intermission unknown item
+entity target_speaker unknown item
+entity func_timer unknown item
+entity target_speaker unknown item
+entity misc_model unknown item
+entity light unknown item
+entity misc_teleporter_dest unknown item
+entity target_position unknown item
+entity misc_portal_camera unknown item
+entity light unknown item
+entity light unknown item
+entity target_position unknown item
+entity light unknown item
+entity info_player_deathmatch unknown item
+entity light unknown item
+entity light unknown item
+entity info_null unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity target_position unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity info_player_deathmatch unknown item
+entity info_player_deathmatch unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity misc_model unknown item
+entity light unknown item
+entity light unknown item
+entity misc_model unknown item
+entity info_player_deathmatch unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity trigger_multiple unknown item
+entity func_timer unknown item
+entity target_speaker unknown item
+entity trigger_multiple unknown item
+entity func_timer unknown item
+entity target_speaker unknown item
+entity target_speaker unknown item
+entity trigger_teleport unknown item
+entity misc_portal_surface unknown item
+entity misc_portal_surface unknown item
+entity info_player_deathmatch unknown item
+entity misc_model unknown item
+entity light unknown item
+entity func_rotating unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity target_position unknown item
+entity light unknown item
+entity light unknown item
+entity target_position unknown item
+entity light unknown item
+entity light unknown item
+entity func_rotating unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity light unknown item
+entity misc_model unknown item
+entity misc_model unknown item
+entity func_timer unknown item
+entity target_speaker unknown item
+entity target_speaker unknown item
+entity func_timer unknown item
+entity target_speaker unknown item
+entity func_timer unknown item
+entity target_speaker unknown item
+entity func_door unknown item
+entity func_door unknown item
+entity light unknown item
+entity light unknown item
+entity misc_model unknown item
+entity light unknown item
+bots/crash_c.cskill 1073741824
+{
+ 0 Crash
+ 1 female
+ 2 0.366667
+ 3 bots/crash_w.c
+ 4 0.366667
+ 5 180
+ 6 4.166667
+ 7 0.366667
+ 8 0.366667
+ 9 0.450000
+ 10 0.450000
+ 11 0.450000
+ 12 0.450000
+ 13 0.450000
+ 14 0.450000
+ 15 0.450000
+ 16 0.366667
+ 17 0.450000
+ 18 0.450000
+ 19 0.450000
+ 20 0.450000
+ 21 bots/crash_t.c
+ 22 crash
+ 23 400
+ 24 0.400000
+ 25 1.000000
+ 26 1.000000
+ 27 1.000000
+ 28 1.000000
+ 29 1.000000
+ 30 1.000000
+ 31 1.000000
+ 32 1.000000
+ 33 1.000000
+ 34 1.000000
+ 35 1.000000
+ 36 0.000000
+ 37 0.000000
+ 38 0.000000
+ 39 0.000000
+ 40 bots/crash_i.c
+ 41 0.233333
+ 42 0.233333
+ 43 0.233333
+ 44 0.233333
+ 45 0.000000
+ 46 0.233333
+ 47 0.333333
+ 48 1.000000
+}
+item info 7 "weapon_gauntlet" has no fuzzy weight
+item info 16 "weapon_grapplinghook" has no fuzzy weight
+item info 49 "team_redobelisk" has no fuzzy weight
+item info 50 "team_blueobelisk" has no fuzzy weight
+item info 51 "team_neutralobelisk" has no fuzzy weight
diff --git a/code/macosx/macosx_display.h b/code/macosx/macosx_display.h
new file mode 100755
index 0000000..86ce93c
--- /dev/null
+++ b/code/macosx/macosx_display.h
@@ -0,0 +1,38 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "tr_local.h"
+#include "macosx_local.h"
+
+@class NSDictionary;
+
+extern NSDictionary *Sys_GetMatchingDisplayMode(qboolean allowStretchedModes);
+
+extern void Sys_StoreGammaTables();
+extern void Sys_GetGammaTable(glwgamma_t *table);
+extern void Sys_SetScreenFade(glwgamma_t *table, float fraction);
+
+extern void Sys_FadeScreens();
+extern void Sys_FadeScreen(CGDirectDisplayID display);
+extern void Sys_UnfadeScreens();
+extern void Sys_UnfadeScreen(CGDirectDisplayID display, glwgamma_t *table);
+extern void Sys_ReleaseAllDisplays();
+
diff --git a/code/macosx/macosx_display.m b/code/macosx/macosx_display.m
new file mode 100755
index 0000000..b6f687c
--- /dev/null
+++ b/code/macosx/macosx_display.m
@@ -0,0 +1,373 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#import "macosx_display.h"
+
+#include "tr_local.h"
+#import "macosx_local.h"
+
+#import <Foundation/Foundation.h>
+#import <IOKit/graphics/IOGraphicsTypes.h> // for interpreting the kCGDisplayIOFlags element of the display mode
+
+
+NSDictionary *Sys_GetMatchingDisplayMode(qboolean allowStretchedModes)
+{
+ NSArray *displayModes;
+ NSDictionary *mode;
+ unsigned int modeIndex, modeCount, bestModeIndex;
+ int verbose;
+ cvar_t *cMinFreq, *cMaxFreq;
+ int minFreq, maxFreq;
+ unsigned int colorDepth;
+
+ verbose = r_verbose->integer;
+
+ colorDepth = r_colorbits->integer;
+ if (colorDepth < 16 || !r_fullscreen->integer)
+ colorDepth = [[glw_state.desktopMode objectForKey: (id)kCGDisplayBitsPerPixel] intValue];
+
+ cMinFreq = ri.Cvar_Get("r_minDisplayRefresh", "0", CVAR_ARCHIVE);
+ cMaxFreq = ri.Cvar_Get("r_maxDisplayRefresh", "0", CVAR_ARCHIVE);
+
+ if (cMinFreq && cMaxFreq && cMinFreq->integer && cMaxFreq->integer &&
+ cMinFreq->integer > cMaxFreq->integer) {
+ ri.Error(ERR_FATAL, "r_minDisplayRefresh must be less than or equal to r_maxDisplayRefresh");
+ }
+
+ minFreq = cMinFreq ? cMinFreq->integer : 0;
+ maxFreq = cMaxFreq ? cMaxFreq->integer : 0;
+
+ displayModes = (NSArray *)CGDisplayAvailableModes(glw_state.display);
+ if (!displayModes) {
+ ri.Error(ERR_FATAL, "CGDisplayAvailableModes returned NULL -- 0x%0x is an invalid display", glw_state.display);
+ }
+
+ modeCount = [displayModes count];
+ if (verbose) {
+ ri.Printf(PRINT_ALL, "%d modes avaliable\n", modeCount);
+ ri.Printf(PRINT_ALL, "Current mode is %s\n", [[(id)CGDisplayCurrentMode(glw_state.display) description] cString]);
+ }
+
+ // Default to the current desktop mode
+ bestModeIndex = 0xFFFFFFFF;
+
+ for ( modeIndex = 0; modeIndex < modeCount; ++modeIndex ) {
+ id object;
+ int refresh;
+
+ mode = [displayModes objectAtIndex: modeIndex];
+ if (verbose) {
+ ri.Printf(PRINT_ALL, " mode %d -- %s\n", modeIndex, [[mode description] cString]);
+ }
+
+ // Make sure we get the right size
+ object = [mode objectForKey: (id)kCGDisplayWidth];
+
+ if ([[mode objectForKey: (id)kCGDisplayWidth] intValue] != glConfig.vidWidth ||
+ [[mode objectForKey: (id)kCGDisplayHeight] intValue] != glConfig.vidHeight) {
+ if (verbose)
+ ri.Printf(PRINT_ALL, " -- bad size\n");
+ continue;
+ }
+
+ if (!allowStretchedModes) {
+ if ([[mode objectForKey: (id)kCGDisplayIOFlags] intValue] & kDisplayModeStretchedFlag) {
+ if (verbose)
+ ri.Printf(PRINT_ALL, " -- stretched modes disallowed\n");
+ continue;
+ }
+ }
+
+ // Make sure that our frequency restrictions are observed
+ refresh = [[mode objectForKey: (id)kCGDisplayRefreshRate] intValue];
+ if (minFreq && refresh < minFreq) {
+ if (verbose)
+ ri.Printf(PRINT_ALL, " -- refresh too low\n");
+ continue;
+ }
+
+ if (maxFreq && refresh > maxFreq) {
+ if (verbose)
+ ri.Printf(PRINT_ALL, " -- refresh too high\n");
+ continue;
+ }
+
+ if ([[mode objectForKey: (id)kCGDisplayBitsPerPixel] intValue] != colorDepth) {
+ if (verbose)
+ ri.Printf(PRINT_ALL, " -- bad depth\n");
+ continue;
+ }
+
+ bestModeIndex = modeIndex;
+ if (verbose)
+ ri.Printf(PRINT_ALL, " -- OK\n", bestModeIndex);
+ }
+
+ if (verbose)
+ ri.Printf(PRINT_ALL, " bestModeIndex = %d\n", bestModeIndex);
+
+ if (bestModeIndex == 0xFFFFFFFF) {
+ ri.Printf(PRINT_ALL, "No suitable display mode available.\n");
+ return nil;
+ }
+
+ return [displayModes objectAtIndex: bestModeIndex];
+}
+
+
+#define MAX_DISPLAYS 128
+
+void Sys_GetGammaTable(glwgamma_t *table)
+{
+ CGTableCount tableSize = 512;
+ CGDisplayErr err;
+
+ table->tableSize = tableSize;
+ if (table->red)
+ free(table->red);
+ table->red = malloc(tableSize * sizeof(*table->red));
+ if (table->green)
+ free(table->green);
+ table->green = malloc(tableSize * sizeof(*table->green));
+ if (table->blue)
+ free(table->blue);
+ table->blue = malloc(tableSize * sizeof(*table->blue));
+
+ // TJW: We _could_ loop here if we get back the same size as our table, increasing the table size.
+ err = CGGetDisplayTransferByTable(table->display, tableSize, table->red, table->green, table->blue,
+&table->tableSize);
+ if (err != CGDisplayNoErr) {
+ Com_Printf("GLimp_Init: CGGetDisplayTransferByTable returned %d.\n", err);
+ table->tableSize = 0;
+ }
+}
+
+void Sys_SetGammaTable(glwgamma_t *table)
+{
+}
+
+
+void Sys_StoreGammaTables()
+{
+ // Store the original gamma for all monitors so that we can fade and unfade them all
+ CGDirectDisplayID displays[MAX_DISPLAYS];
+ CGDisplayCount displayIndex;
+ CGDisplayErr err;
+
+ err = CGGetActiveDisplayList(MAX_DISPLAYS, displays, &glw_state.displayCount);
+ if (err != CGDisplayNoErr)
+ Sys_Error("Cannot get display list -- CGGetActiveDisplayList returned %d.\n", err);
+
+ glw_state.originalDisplayGammaTables = calloc(glw_state.displayCount, sizeof(*glw_state.originalDisplayGammaTables));
+ for (displayIndex = 0; displayIndex < glw_state.displayCount; displayIndex++) {
+ glwgamma_t *table;
+
+ table = &glw_state.originalDisplayGammaTables[displayIndex];
+ table->display = displays[displayIndex];
+ Sys_GetGammaTable(table);
+ }
+}
+
+
+// This isn't a mathematically correct fade, but we don't care that much.
+void Sys_SetScreenFade(glwgamma_t *table, float fraction)
+{
+ CGTableCount tableSize;
+ CGGammaValue *red, *blue, *green;
+ CGTableCount gammaIndex;
+
+ if (!glConfig.deviceSupportsGamma)
+ return;
+
+ if (!(tableSize = table->tableSize))
+ // we couldn't get the table for this display for some reason
+ return;
+
+// Com_Printf("0x%08x %f\n", table->display, fraction);
+
+ red = glw_state.tempTable.red;
+ green = glw_state.tempTable.green;
+ blue = glw_state.tempTable.blue;
+ if (glw_state.tempTable.tableSize < tableSize) {
+ glw_state.tempTable.tableSize = tableSize;
+ red = realloc(red, sizeof(*red) * tableSize);
+ green = realloc(green, sizeof(*green) * tableSize);
+ blue = realloc(blue, sizeof(*blue) * tableSize);
+ glw_state.tempTable.red = red;
+ glw_state.tempTable.green = green;
+ glw_state.tempTable.blue = blue;
+ }
+
+ for (gammaIndex = 0; gammaIndex < table->tableSize; gammaIndex++) {
+ red[gammaIndex] = table->red[gammaIndex] * fraction;
+ blue[gammaIndex] = table->blue[gammaIndex] * fraction;
+ green[gammaIndex] = table->green[gammaIndex] * fraction;
+ }
+
+ CGSetDisplayTransferByTable(table->display, table->tableSize, red, green, blue);
+}
+
+// Fades all the active displays at the same time.
+
+#define FADE_DURATION 0.5
+void Sys_FadeScreens()
+{
+ CGDisplayCount displayIndex;
+ int stepIndex;
+ glwgamma_t *table;
+ NSTimeInterval start, current;
+ float time;
+
+ if (!glConfig.deviceSupportsGamma)
+ return;
+
+ Com_Printf("Fading all displays\n");
+
+ start = [NSDate timeIntervalSinceReferenceDate];
+ time = 0.0;
+ while (time != FADE_DURATION) {
+ current = [NSDate timeIntervalSinceReferenceDate];
+ time = current - start;
+ if (time > FADE_DURATION)
+ time = FADE_DURATION;
+
+ for (displayIndex = 0; displayIndex < glw_state.displayCount; displayIndex++) {
+ table = &glw_state.originalDisplayGammaTables[displayIndex];
+ Sys_SetScreenFade(table, 1.0 - time / FADE_DURATION);
+ }
+ }
+}
+
+void Sys_FadeScreen(CGDirectDisplayID display)
+{
+ CGDisplayCount displayIndex;
+ glwgamma_t *table;
+ int stepIndex;
+
+ if (!glConfig.deviceSupportsGamma)
+ return;
+
+ Com_Printf("Fading display 0x%08x\n", display);
+
+ for (displayIndex = 0; displayIndex < glw_state.displayCount; displayIndex++) {
+ if (display == glw_state.originalDisplayGammaTables[displayIndex].display) {
+ NSTimeInterval start, current;
+ float time;
+
+ start = [NSDate timeIntervalSinceReferenceDate];
+ time = 0.0;
+
+ table = &glw_state.originalDisplayGammaTables[displayIndex];
+ while (time != FADE_DURATION) {
+ current = [NSDate timeIntervalSinceReferenceDate];
+ time = current - start;
+ if (time > FADE_DURATION)
+ time = FADE_DURATION;
+
+ Sys_SetScreenFade(table, 1.0 - time / FADE_DURATION);
+ }
+ return;
+ }
+ }
+
+ Com_Printf("Unable to find display to fade it\n");
+}
+
+void Sys_UnfadeScreens()
+{
+ CGDisplayCount displayIndex;
+ int stepIndex;
+ glwgamma_t *table;
+ NSTimeInterval start, current;
+ float time;
+
+ if (!glConfig.deviceSupportsGamma)
+ return;
+
+ Com_Printf("Unfading all displays\n");
+
+ start = [NSDate timeIntervalSinceReferenceDate];
+ time = 0.0;
+ while (time != FADE_DURATION) {
+ current = [NSDate timeIntervalSinceReferenceDate];
+ time = current - start;
+ if (time > FADE_DURATION)
+ time = FADE_DURATION;
+
+ for (displayIndex = 0; displayIndex < glw_state.displayCount; displayIndex++) {
+ table = &glw_state.originalDisplayGammaTables[displayIndex];
+ Sys_SetScreenFade(table, time / FADE_DURATION);
+ }
+ }
+}
+
+void Sys_UnfadeScreen(CGDirectDisplayID display, glwgamma_t *table)
+{
+ CGDisplayCount displayIndex;
+ int stepIndex;
+
+ if (!glConfig.deviceSupportsGamma)
+ return;
+
+ Com_Printf("Unfading display 0x%08x\n", display);
+
+ if (table) {
+ CGTableCount i;
+
+ Com_Printf("Given table:\n");
+ for (i = 0; i < table->tableSize; i++) {
+ Com_Printf(" %f %f %f\n", table->red[i], table->blue[i], table->green[i]);
+ }
+ }
+
+ // Search for the original gamma table for the display
+ if (!table) {
+ for (displayIndex = 0; displayIndex < glw_state.displayCount; displayIndex++) {
+ if (display == glw_state.originalDisplayGammaTables[displayIndex].display) {
+ table = &glw_state.originalDisplayGammaTables[displayIndex];
+ break;
+ }
+ }
+ }
+
+ if (table) {
+ NSTimeInterval start, current;
+ float time;
+
+ start = [NSDate timeIntervalSinceReferenceDate];
+ time = 0.0;
+
+ while (time != FADE_DURATION) {
+ current = [NSDate timeIntervalSinceReferenceDate];
+ time = current - start;
+ if (time > FADE_DURATION)
+ time = FADE_DURATION;
+ Sys_SetScreenFade(table, time / FADE_DURATION);
+ }
+ return;
+ }
+
+ Com_Printf("Unable to find display to unfade it\n");
+}
+
+
+
diff --git a/code/macosx/macosx_glimp.h b/code/macosx/macosx_glimp.h
new file mode 100755
index 0000000..eeaf9f1
--- /dev/null
+++ b/code/macosx/macosx_glimp.h
@@ -0,0 +1,37 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include <OpenGL/OpenGL.h>
+#include <OpenGL/gl.h>
+#include <OpenGL/glu.h>
+#ifndef GL_EXT_abgr
+#include <OpenGL/glext.h>
+#endif
+
+// This can be defined to use the CGLMacro.h support which avoids looking up
+// the current context.
+//#define USE_CGLMACROS
+
+#ifdef USE_CGLMACROS
+#include "macosx_local.h"
+#define cgl_ctx glw_state._cgl_ctx
+#include <OpenGL/CGLMacro.h>
+#endif
diff --git a/code/macosx/macosx_glimp.m b/code/macosx/macosx_glimp.m
new file mode 100755
index 0000000..93e9675
--- /dev/null
+++ b/code/macosx/macosx_glimp.m
@@ -0,0 +1,1114 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#import "macosx_glimp.h"
+
+#include "tr_local.h"
+#import "macosx_local.h"
+#import "macosx_display.h"
+#import "macosx_timers.h"
+
+#import <AppKit/AppKit.h>
+#import <Foundation/Foundation.h>
+
+#import <mach-o/dyld.h>
+#import <mach/mach.h>
+#import <mach/mach_error.h>
+
+cvar_t *r_allowSoftwareGL; // don't abort out if the pixelformat claims software
+cvar_t *r_enablerender; // Enable actual rendering
+cvar_t *r_appleTransformHint; // Enable Apple transform hint
+
+static void GLW_InitExtensions( void );
+static qboolean CreateGameWindow( qboolean isSecondTry );
+static unsigned long Sys_QueryVideoMemory();
+static CGDisplayErr Sys_CaptureActiveDisplays(void);
+
+
+glwstate_t glw_state;
+qboolean Sys_IsHidden = qfalse;
+
+#ifdef OMNI_TIMER
+OTStampList glThreadStampList;
+#endif
+
+@interface NSOpenGLContext (CGLContextAccess)
+- (CGLContextObj) cglContext;
+@end
+
+@implementation NSOpenGLContext (CGLContextAccess)
+- (CGLContextObj) cglContext;
+{
+ return _contextAuxiliary;
+}
+@end
+
+/*
+============
+CheckErrors
+============
+*/
+void CheckErrors( void )
+{
+ GLenum err;
+
+ err = qglGetError();
+ if ( err != GL_NO_ERROR ) {
+ ri.Error( ERR_FATAL, "glGetError: %s\n", qglGetString( err ) );
+ }
+}
+
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+
+unsigned int QGLBeginStarted = 0;
+
+void QGLErrorBreak(void)
+{
+}
+
+void QGLCheckError(const char *message)
+{
+ GLenum error;
+ static unsigned int errorCount = 0;
+
+ error = _glGetError();
+ if (error != GL_NO_ERROR) {
+ if (errorCount == 100) {
+ Com_Printf("100 GL errors printed ... disabling further error reporting.\n");
+ } else if (errorCount < 100) {
+ if (errorCount == 0) {
+ fprintf(stderr, "BREAK ON QGLErrorBreak to stop at the GL errors\n");
+ }
+ fprintf(stderr, "OpenGL Error(%s): 0x%04x -- %s\n", message, (int)error, gluErrorString(error));
+ QGLErrorBreak();
+ }
+ errorCount++;
+ }
+}
+#endif
+
+/*
+** GLimp_SetMode
+*/
+
+qboolean GLimp_SetMode( qboolean isSecondTry )
+{
+ if ( !CreateGameWindow(isSecondTry) ) {
+ ri.Printf( PRINT_ALL, "GLimp_Init: window could not be created!\n" );
+ return qfalse;
+ }
+
+ // draw something to show that GL is alive
+ if (r_enablerender->integer) {
+ qglClearColor( 0.5, 0.5, 0.7, 0 );
+ qglClear( GL_COLOR_BUFFER_BIT );
+ GLimp_EndFrame();
+
+ qglClearColor( 0.5, 0.5, 0.7, 0 );
+ qglClear( GL_COLOR_BUFFER_BIT );
+ GLimp_EndFrame();
+ }
+
+ Sys_UnfadeScreen(Sys_DisplayToUse(), NULL);
+
+ CheckErrors();
+
+ return qtrue;
+}
+
+/*
+ =================
+ GetPixelAttributes
+ =================
+ */
+
+#define ADD_ATTR(x) \
+do { \
+ if (attributeIndex >= attributeSize) { \
+ attributeSize *= 2; \
+ pixelAttributes = NSZoneRealloc(NULL, pixelAttributes, sizeof(*pixelAttributes) * attributeSize); \
+ } \
+ pixelAttributes[attributeIndex] = x; \
+ attributeIndex++; \
+ if (verbose) { \
+ ri.Printf(PRINT_ALL, "Adding pixel attribute: %d (%s)\n", x, #x); \
+ } \
+} while(0)
+
+static NSOpenGLPixelFormatAttribute *GetPixelAttributes()
+{
+ NSOpenGLPixelFormatAttribute *pixelAttributes;
+ unsigned int attributeIndex = 0;
+ unsigned int attributeSize = 128;
+ int verbose = 0;
+ unsigned int colorDepth;
+
+ verbose = r_verbose->integer;
+
+ pixelAttributes = NSZoneMalloc(NULL, sizeof(*pixelAttributes) * attributeSize);
+
+ if (r_fullscreen->integer) {
+ ADD_ATTR(NSOpenGLPFAFullScreen);
+
+ // Since we are fullscreen, specify the screen that we need.
+ ADD_ATTR(NSOpenGLPFAScreenMask);
+ ADD_ATTR(CGDisplayIDToOpenGLDisplayMask(Sys_DisplayToUse()));
+ }
+
+ // Require hardware acceleration unless otherwise directed
+ if (!r_allowSoftwareGL->integer) {
+ ADD_ATTR(NSOpenGLPFAAccelerated);
+ }
+
+ // Require double-buffer
+ ADD_ATTR(NSOpenGLPFADoubleBuffer);
+
+ // Specify the number of color bits. If we don't have a valid specified value or we are not full screen, use the current display mode's value.
+ ADD_ATTR(NSOpenGLPFAColorSize);
+ colorDepth = r_colorbits->integer;
+ if (colorDepth < 16)
+ colorDepth = 16;
+ else if (colorDepth > 16)
+ colorDepth = 32;
+ if (!r_fullscreen->integer)
+ colorDepth = [[glw_state.desktopMode objectForKey: (id)kCGDisplayBitsPerPixel] intValue];
+ ADD_ATTR(colorDepth);
+
+ // Specify the number of depth bits
+ ADD_ATTR(NSOpenGLPFADepthSize);
+ ADD_ATTR(r_depthbits->integer ? r_depthbits->integer : 16);
+
+ // Specify the number of stencil bits
+ if (r_stencilbits->integer) {
+ ADD_ATTR(NSOpenGLPFAStencilSize);
+ ADD_ATTR(r_stencilbits->integer);
+ }
+
+ // Terminate the list
+ ADD_ATTR(0);
+
+ return pixelAttributes;
+}
+
+// Needs to be visible to Q3Controller.m.
+void Sys_UpdateWindowMouseInputRect(void)
+{
+ NSRect windowRect, screenRect;
+ NSScreen *screen;
+
+ // It appears we need to flip the coordinate system here. This means we need
+ // to know the size of the screen.
+ screen = [glw_state.window screen];
+ screenRect = [screen frame];
+ windowRect = [glw_state.window frame];
+ windowRect.origin.y = screenRect.size.height - (windowRect.origin.y + windowRect.size.height);
+
+ Sys_SetMouseInputRect(CGRectMake(windowRect.origin.x, windowRect.origin.y,
+ windowRect.size.width, windowRect.size.height));
+}
+
+// This is needed since CGReleaseAllDisplays() restores the gamma on the displays and we want to fade it up rather than just flickering all the displays
+static void ReleaseAllDisplays()
+{
+ CGDisplayCount displayIndex;
+
+ Com_Printf("Releasing displays\n");
+ for (displayIndex = 0; displayIndex < glw_state.displayCount; displayIndex++) {
+ CGDisplayRelease(glw_state.originalDisplayGammaTables[displayIndex].display);
+ }
+}
+
+/*
+=================
+CreateGameWindow
+=================
+*/
+static qboolean CreateGameWindow( qboolean isSecondTry )
+{
+ const char *windowed[] = { "Windowed", "Fullscreen" };
+ int current_mode;
+ NSOpenGLPixelFormatAttribute *pixelAttributes;
+ NSOpenGLPixelFormat *pixelFormat;
+ CGDisplayErr err;
+
+
+ // get mode info
+ current_mode = r_mode->integer;
+ glConfig.isFullscreen = (r_fullscreen->integer != 0);
+
+ glw_state.desktopMode = (NSDictionary *)CGDisplayCurrentMode(glw_state.display);
+ if (!glw_state.desktopMode) {
+ ri.Error(ERR_FATAL, "Could not get current graphics mode for display 0x%08x\n", glw_state.display);
+ }
+
+#if 0
+ ri.Printf( PRINT_ALL, "... desktop mode %d = %dx%d %s\n", glw_state.desktopMode,
+ glw_state.desktopDesc.width, glw_state.desktopDesc.height,
+ depthStrings[glw_state.desktopDesc.depth]);
+#endif
+
+ ri.Printf( PRINT_ALL, "...setting mode %d:\n", current_mode );
+ if ( !R_GetModeInfo( &glConfig.vidWidth, &glConfig.vidHeight, &glConfig.windowAspect, current_mode ) ) {
+ ri.Printf( PRINT_ALL, " invalid mode\n" );
+ return qfalse;
+ }
+ ri.Printf( PRINT_ALL, " %d %d %s\n", glConfig.vidWidth, glConfig.vidHeight, windowed[glConfig.isFullscreen] );
+
+ if (glConfig.isFullscreen) {
+
+ // We'll set up the screen resolution first in case that effects the list of pixel
+ // formats that are available (for example, a smaller frame buffer might mean more
+ // bits for depth/stencil buffers). Allow stretched video modes if we are in fallback mode.
+ glw_state.gameMode = Sys_GetMatchingDisplayMode(isSecondTry);
+ if (!glw_state.gameMode) {
+ ri.Printf( PRINT_ALL, "Unable to find requested display mode.\n");
+ return qfalse;
+ }
+
+ // Fade all screens to black
+ Sys_FadeScreens();
+
+ err = Sys_CaptureActiveDisplays();
+ if ( err != CGDisplayNoErr ) {
+ CGDisplayRestoreColorSyncSettings();
+ ri.Printf( PRINT_ALL, " Unable to capture displays err = %d\n", err );
+ return qfalse;
+ }
+
+ err = CGDisplaySwitchToMode(glw_state.display, (CFDictionaryRef)glw_state.gameMode);
+ if ( err != CGDisplayNoErr ) {
+ CGDisplayRestoreColorSyncSettings();
+ ReleaseAllDisplays();
+ ri.Printf( PRINT_ALL, " Unable to set display mode, err = %d\n", err );
+ return qfalse;
+ }
+ } else {
+ glw_state.gameMode = glw_state.desktopMode;
+ }
+
+
+ // Get the GL pixel format
+ pixelAttributes = GetPixelAttributes();
+ pixelFormat = [[[NSOpenGLPixelFormat alloc] initWithAttributes: pixelAttributes] autorelease];
+ NSZoneFree(NULL, pixelAttributes);
+
+ if (!pixelFormat) {
+ CGDisplayRestoreColorSyncSettings();
+ CGDisplaySwitchToMode(glw_state.display, (CFDictionaryRef)glw_state.desktopMode);
+ ReleaseAllDisplays();
+ ri.Printf( PRINT_ALL, " No pixel format found\n");
+ return qfalse;
+ }
+
+ // Create a context with the desired pixel attributes
+ OSX_SetGLContext([[NSOpenGLContext alloc] initWithFormat: pixelFormat shareContext: nil]);
+ if (!OSX_GetNSGLContext()) {
+ CGDisplayRestoreColorSyncSettings();
+ CGDisplaySwitchToMode(glw_state.display, (CFDictionaryRef)glw_state.desktopMode);
+ ReleaseAllDisplays();
+ ri.Printf(PRINT_ALL, "... +[NSOpenGLContext createWithFormat:share:] failed.\n" );
+ return qfalse;
+ }
+
+ if (!glConfig.isFullscreen) {
+ cvar_t *vid_xpos;
+ cvar_t *vid_ypos;
+ NSRect windowRect;
+
+ vid_xpos = ri.Cvar_Get( "vid_xpos", "100", CVAR_ARCHIVE );
+ vid_ypos = ri.Cvar_Get( "vid_ypos", "100", CVAR_ARCHIVE );
+
+ // Create a window of the desired size
+ windowRect.origin.x = vid_xpos->integer;
+ windowRect.origin.y = vid_ypos->integer;
+ windowRect.size.width = glConfig.vidWidth;
+ windowRect.size.height = glConfig.vidHeight;
+
+ glw_state.window = [[NSWindow alloc] initWithContentRect:windowRect
+ styleMask:NSTitledWindowMask
+ backing:NSBackingStoreRetained
+ defer:NO];
+
+ [glw_state.window setTitle: @"Quake3"];
+
+ [glw_state.window orderFront: nil];
+
+ // Always get mouse moved events (if mouse support is turned off (rare)
+ // the event system will filter them out.
+ [glw_state.window setAcceptsMouseMovedEvents: YES];
+
+ // Direct the context to draw in this window
+ [OSX_GetNSGLContext() setView: [glw_state.window contentView]];
+
+ // Sync input rect with where the window actually is...
+ Sys_UpdateWindowMouseInputRect();
+ } else {
+ CGLError err;
+
+ err = CGLSetFullScreen(OSX_GetCGLContext());
+ if (err) {
+ CGDisplayRestoreColorSyncSettings();
+ CGDisplaySwitchToMode(glw_state.display, (CFDictionaryRef)glw_state.desktopMode);
+ ReleaseAllDisplays();
+ Com_Printf("CGLSetFullScreen -> %d (%s)\n", err, CGLErrorString(err));
+ return qfalse;
+ }
+
+ Sys_SetMouseInputRect(CGDisplayBounds(glw_state.display));
+ }
+
+
+#ifndef USE_CGLMACROS
+ // Make this the current context
+ OSX_GLContextSetCurrent();
+#endif
+
+ // Store off the pixel format attributes that we actually got
+ [pixelFormat getValues: (long *) &glConfig.colorBits forAttribute: NSOpenGLPFAColorSize forVirtualScreen: 0];
+ [pixelFormat getValues: (long *) &glConfig.depthBits forAttribute: NSOpenGLPFADepthSize forVirtualScreen: 0];
+ [pixelFormat getValues: (long *) &glConfig.stencilBits forAttribute: NSOpenGLPFAStencilSize forVirtualScreen: 0];
+
+ glConfig.displayFrequency = [[glw_state.gameMode objectForKey: (id)kCGDisplayRefreshRate] intValue];
+
+
+ ri.Printf(PRINT_ALL, "ok\n" );
+
+ return qtrue;
+}
+
+// This can be used to temporarily disassociate the GL context from the screen so that CoreGraphics can be used to draw to the screen.
+void Sys_PauseGL ()
+{
+ if (!glw_state.glPauseCount) {
+ qglFinish (); // must do this to ensure the queue is complete
+
+ // Have to call both to actually deallocate kernel resources and free the NSSurface
+ CGLClearDrawable(OSX_GetCGLContext());
+ [OSX_GetNSGLContext() clearDrawable];
+ }
+ glw_state.glPauseCount++;
+}
+
+// This can be used to reverse the pausing caused by Sys_PauseGL()
+void Sys_ResumeGL ()
+{
+ if (glw_state.glPauseCount) {
+ glw_state.glPauseCount--;
+ if (!glw_state.glPauseCount) {
+ if (!glConfig.isFullscreen) {
+ [OSX_GetNSGLContext() setView: [glw_state.window contentView]];
+ } else {
+ CGLError err;
+
+ err = CGLSetFullScreen(OSX_GetCGLContext());
+ if (err)
+ Com_Printf("CGLSetFullScreen -> %d (%s)\n", err, CGLErrorString(err));
+ }
+ }
+ }
+}
+
+/*
+===================
+GLimp_Init
+
+Don't return unless OpenGL has been properly initialized
+===================
+*/
+
+static void GLImp_Toggle_Renderer_f(void)
+{
+ ri.Cvar_Set("r_enablerender", r_enablerender->integer ? "0" : "1");
+}
+
+#ifdef OMNI_TIMER
+static void GLImp_Dump_Stamp_List_f(void)
+{
+ OTStampListDumpToFile(glThreadStampList, "/tmp/gl_stamps");
+}
+#endif
+
+void GLimp_Init( void )
+{
+ static BOOL addedCommands = NO;
+ cvar_t *lastValidRenderer = ri.Cvar_Get( "r_lastValidRenderer", "(uninitialized)", CVAR_ARCHIVE );
+ char *buf;
+
+ if (!addedCommands) {
+ addedCommands = YES;
+
+#ifdef OMNI_TIMER
+ glThreadStampList = OTStampListCreate(64);
+ Cmd_AddCommand ("dump_stamp_list", GLImp_Dump_Stamp_List_f);
+#endif
+ Cmd_AddCommand ("toggle_renderer", GLImp_Toggle_Renderer_f);
+ }
+
+ ri.Printf( PRINT_ALL, "Initializing OpenGL subsystem\n" );
+ ri.Printf( PRINT_ALL, " Last renderer was '%s'\n", lastValidRenderer->string);
+ ri.Printf( PRINT_ALL, " r_fullscreen = %d\n", r_fullscreen->integer);
+
+ memset( &glConfig, 0, sizeof( glConfig ) );
+
+ // We only allow changing the gamma if we are full screen
+ glConfig.deviceSupportsGamma = (r_fullscreen->integer != 0);
+ if (glConfig.deviceSupportsGamma) {
+ Sys_StoreGammaTables();
+ }
+
+ r_allowSoftwareGL = ri.Cvar_Get( "r_allowSoftwareGL", "0", CVAR_LATCH );
+ r_enablerender = ri.Cvar_Get("r_enablerender", "1", 0 );
+
+ if (Sys_QueryVideoMemory() == 0 && !r_allowSoftwareGL->integer) {
+ ri.Error( ERR_FATAL, "Could not initialize OpenGL. There does not appear to be an OpenGL-supported video card in your system.\n" );
+ }
+
+ if ( ! GLimp_SetMode(qfalse) ) {
+ // fall back to the known-good mode
+ ri.Cvar_Set( "r_fullscreen", "1" );
+ ri.Cvar_Set( "r_mode", "3" );
+ ri.Cvar_Set( "r_stereo", "0" );
+ ri.Cvar_Set( "r_depthBits", "16" );
+ ri.Cvar_Set( "r_colorBits", "16" );
+ ri.Cvar_Set( "r_stencilBits", "0" );
+ if ( GLimp_SetMode(qtrue) ) {
+ ri.Printf( PRINT_ALL, "------------------\n" );
+ return;
+ }
+
+ ri.Error( ERR_FATAL, "Could not initialize OpenGL\n" );
+ return;
+ }
+
+ ri.Printf( PRINT_ALL, "------------------\n" );
+
+ // get our config strings
+ Q_strncpyz( glConfig.vendor_string, (const char *)qglGetString (GL_VENDOR), sizeof( glConfig.vendor_string ) );
+ Q_strncpyz( glConfig.renderer_string, (const char *)qglGetString (GL_RENDERER), sizeof( glConfig.renderer_string ) );
+ Q_strncpyz( glConfig.version_string, (const char *)qglGetString (GL_VERSION), sizeof( glConfig.version_string ) );
+ Q_strncpyz( glConfig.extensions_string, (const char *)qglGetString (GL_EXTENSIONS), sizeof( glConfig.extensions_string ) );
+
+ //
+ // chipset specific configuration
+ //
+ buf = malloc(strlen(glConfig.renderer_string) + 1);
+ strcpy( buf, glConfig.renderer_string );
+ Q_strlwr( buf );
+
+ ri.Cvar_Set( "r_lastValidRenderer", glConfig.renderer_string );
+ free(buf);
+
+ GLW_InitExtensions();
+
+#ifndef USE_CGLMACROS
+ if (!r_enablerender->integer)
+ OSX_GLContextClearCurrent();
+#endif
+}
+
+
+/*
+** GLimp_EndFrame
+**
+** Responsible for doing a swapbuffers and possibly for other stuff
+** as yet to be determined. Probably better not to make this a GLimp
+** function and instead do a call to GLimp_SwapBuffers.
+*/
+void GLimp_EndFrame (void)
+{
+ GLSTAMP("GLimp_EndFrame start", 0);
+
+ //
+ // swapinterval stuff
+ //
+ if ( r_swapInterval->modified ) {
+ r_swapInterval->modified = qfalse;
+
+ if ( !glConfig.stereoEnabled ) { // why?
+ [[NSOpenGLContext currentContext] setValues: (long *)&r_swapInterval->integer
+ forParameter: NSOpenGLCPSwapInterval];
+ }
+ }
+
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ QGLCheckError("GLimp_EndFrame");
+#endif
+
+ if (!glw_state.glPauseCount && !Sys_IsHidden) {
+ glw_state.bufferSwapCount++;
+ [OSX_GetNSGLContext() flushBuffer];
+ }
+
+ // Enable turning off GL at any point for performance testing
+ if (OSX_GLContextIsCurrent() != r_enablerender->integer) {
+ if (r_enablerender->integer) {
+ Com_Printf("--- Enabling Renderer ---\n");
+ OSX_GLContextSetCurrent();
+ } else {
+ Com_Printf("--- Disabling Renderer ---\n");
+ OSX_GLContextClearCurrent();
+ }
+ }
+
+ GLSTAMP("GLimp_EndFrame end", 0);
+}
+
+/*
+** GLimp_Shutdown
+**
+** This routine does all OS specific shutdown procedures for the OpenGL
+** subsystem. Under OpenGL this means NULLing out the current DC and
+** HGLRC, deleting the rendering context, and releasing the DC acquired
+** for the window. The state structure is also nulled out.
+**
+*/
+
+static void _GLimp_RestoreOriginalVideoSettings()
+{
+ CGDisplayErr err;
+
+ // CGDisplayCurrentMode lies because we've captured the display and thus we won't
+ // get any notifications about what the current display mode really is. For now,
+ // we just always force it back to what mode we remember the desktop being in.
+ if (glConfig.isFullscreen) {
+ err = CGDisplaySwitchToMode(glw_state.display, (CFDictionaryRef)glw_state.desktopMode);
+ if ( err != CGDisplayNoErr )
+ ri.Printf( PRINT_ALL, " Unable to restore display mode!\n" );
+
+ ReleaseAllDisplays();
+ }
+}
+
+void GLimp_Shutdown( void )
+{
+ CGDisplayCount displayIndex;
+
+ Com_Printf("----- Shutting down GL -----\n");
+
+ Sys_FadeScreen(Sys_DisplayToUse());
+
+ if (OSX_GetNSGLContext()) {
+#ifndef USE_CGLMACROS
+ OSX_GLContextClearCurrent();
+#endif
+ // Have to call both to actually deallocate kernel resources and free the NSSurface
+ CGLClearDrawable(OSX_GetCGLContext());
+ [OSX_GetNSGLContext() clearDrawable];
+
+ [OSX_GetNSGLContext() release];
+ OSX_SetGLContext((id)nil);
+ }
+
+ _GLimp_RestoreOriginalVideoSettings();
+
+ Sys_UnfadeScreens();
+
+ // Restore the original gamma if needed.
+ if (glConfig.deviceSupportsGamma) {
+ Com_Printf("Restoring ColorSync settings\n");
+ CGDisplayRestoreColorSyncSettings();
+ }
+
+ if (glw_state.window) {
+ [glw_state.window release];
+ glw_state.window = nil;
+ }
+
+ if (glw_state.log_fp) {
+ fclose(glw_state.log_fp);
+ glw_state.log_fp = 0;
+ }
+
+ for (displayIndex = 0; displayIndex < glw_state.displayCount; displayIndex++) {
+ free(glw_state.originalDisplayGammaTables[displayIndex].red);
+ free(glw_state.originalDisplayGammaTables[displayIndex].blue);
+ free(glw_state.originalDisplayGammaTables[displayIndex].green);
+ }
+ free(glw_state.originalDisplayGammaTables);
+ if (glw_state.tempTable.red) {
+ free(glw_state.tempTable.red);
+ free(glw_state.tempTable.blue);
+ free(glw_state.tempTable.green);
+ }
+ if (glw_state.inGameTable.red) {
+ free(glw_state.inGameTable.red);
+ free(glw_state.inGameTable.blue);
+ free(glw_state.inGameTable.green);
+ }
+
+ memset(&glConfig, 0, sizeof(glConfig));
+ memset(&glState, 0, sizeof(glState));
+ memset(&glw_state, 0, sizeof(glw_state));
+
+ Com_Printf("----- Done shutting down GL -----\n");
+}
+
+/*
+===============
+GLimp_LogComment
+
+===============
+*/
+void GLimp_LogComment( char *comment ) {
+ }
+
+/*
+===============
+GLimp_SetGamma
+
+===============
+*/
+void GLimp_SetGamma(unsigned char red[256],
+ unsigned char green[256],
+ unsigned char blue[256])
+{
+ CGGammaValue redGamma[256], greenGamma[256], blueGamma[256];
+ CGTableCount i;
+ CGDisplayErr err;
+
+ if (!glConfig.deviceSupportsGamma)
+ return;
+
+ for (i = 0; i < 256; i++) {
+ redGamma[i] = red[i] / 255.0;
+ greenGamma[i] = green[i] / 255.0;
+ blueGamma[i] = blue[i] / 255.0;
+ }
+
+ err = CGSetDisplayTransferByTable(glw_state.display, 256, redGamma, greenGamma, blueGamma);
+ if (err != CGDisplayNoErr) {
+ Com_Printf("GLimp_SetGamma: CGSetDisplayTransferByByteTable returned %d.\n", err);
+ }
+
+ // Store the gamma table that we ended up using so we can reapply it later when unhiding or to work around the bug where if you leave the game sitting and the monitor sleeps, when it wakes, the gamma isn't reset.
+ glw_state.inGameTable.display = glw_state.display;
+ Sys_GetGammaTable(&glw_state.inGameTable);
+}
+
+qboolean GLimp_ChangeMode( int mode )
+{
+ qboolean result;
+ int oldvalue = r_mode->integer;
+
+ Com_Printf("*** GLimp_ChangeMode\n");
+ r_mode->integer = mode;
+ if (!(result = GLimp_SetMode(qfalse)))
+ r_mode->integer = oldvalue;
+
+ return result;
+}
+
+/*****************************************************************************/
+
+void *qwglGetProcAddress(const char *name)
+{
+ NSSymbol symbol;
+ char *symbolName;
+
+ // Prepend a '_' for the Unix C symbol mangling convention
+ symbolName = malloc(strlen(name) + 2);
+ strcpy(symbolName + 1, name);
+ symbolName[0] = '_';
+
+ if (NSIsSymbolNameDefined(symbolName))
+ symbol = NSLookupAndBindSymbol(symbolName);
+ else
+ symbol = NULL;
+
+ free(symbolName);
+
+ if (!symbol)
+ // shouldn't happen ...
+ return NULL;
+
+ return NSAddressOfSymbol(symbol);
+}
+
+/*
+** GLW_InitExtensions
+*/
+static void GLW_InitExtensions( void )
+{
+ if ( !r_allowExtensions->integer )
+ {
+ ri.Printf( PRINT_ALL, "*** IGNORING OPENGL EXTENSIONS ***\n" );
+ return;
+ }
+
+ ri.Printf( PRINT_ALL, "Initializing OpenGL extensions\n" );
+ ri.Printf( PRINT_ALL, "... Supported extensions are %s\n", glConfig.extensions_string);
+
+ // GL_S3_s3tc
+ glConfig.textureCompression = TC_NONE;
+ if ( strstr( glConfig.extensions_string, "GL_S3_s3tc" ) )
+ {
+ if ( r_ext_compressed_textures->integer )
+ {
+ glConfig.textureCompression = TC_S3TC;
+ ri.Printf( PRINT_ALL, "...using GL_S3_s3tc\n" );
+ }
+ else
+ {
+ glConfig.textureCompression = TC_NONE;
+ ri.Printf( PRINT_ALL, "...ignoring GL_S3_s3tc\n" );
+ }
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "...GL_S3_s3tc not found\n" );
+ }
+
+
+#ifdef GL_EXT_texture_env_add
+ // GL_EXT_texture_env_add
+ glConfig.textureEnvAddAvailable = qfalse;
+ if ( strstr( glConfig.extensions_string, "GL_EXT_texture_env_add" ) )
+ {
+ if ( r_ext_texture_env_add->integer )
+ {
+ glConfig.textureEnvAddAvailable = qtrue;
+ ri.Printf( PRINT_ALL, "...using GL_EXT_texture_env_add\n" );
+ }
+ else
+ {
+ glConfig.textureEnvAddAvailable = qfalse;
+ ri.Printf( PRINT_ALL, "...ignoring GL_EXT_texture_env_add\n" );
+ }
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "...GL_EXT_texture_env_add not found\n" );
+ }
+#endif
+
+#ifdef GL_ARB_texture_env_add
+ // GL_ARB_texture_env_add -- only if we didn't find GL_EXT_texture_env_add
+ if (!glConfig.textureEnvAddAvailable) {
+ if ( strstr( glConfig.extensions_string, "GL_ARB_texture_env_add" ) )
+ {
+ if ( r_ext_texture_env_add->integer )
+ {
+ glConfig.textureEnvAddAvailable = qtrue;
+ ri.Printf( PRINT_ALL, "...using GL_ARB_texture_env_add\n" );
+ }
+ else
+ {
+ glConfig.textureEnvAddAvailable = qfalse;
+ ri.Printf( PRINT_ALL, "...ignoring GL_ARB_texture_env_add\n" );
+ }
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "...GL_ARB_texture_env_add not found\n" );
+ }
+ }
+#endif
+
+
+#if 0 // Win32 does this differently than we do -- I'll provide a C function that looks the same
+ // that will do the correct ObjC stuff
+ // WGL_EXT_swap_control
+ qwglSwapIntervalEXT = ( BOOL (WINAPI *)(int)) qwglGetProcAddress( "wglSwapIntervalEXT" );
+ if ( qwglSwapIntervalEXT )
+ {
+ ri.Printf( PRINT_ALL, "...using WGL_EXT_swap_control\n" );
+ r_swapInterval->modified = qtrue; // force a set next frame
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "...WGL_EXT_swap_control not found\n" );
+ }
+#else
+ if (r_swapInterval) {
+ ri.Printf( PRINT_ALL, "...using +[NSOpenGLContext setParameter:] for qwglSwapIntervalEXT\n" );
+ r_swapInterval->modified = qtrue; // force a set next frame
+ }
+#endif
+
+ // GL_ARB_multitexture
+ qglMultiTexCoord2fARB = NULL;
+ qglActiveTextureARB = NULL;
+ qglClientActiveTextureARB = NULL;
+ if ( strstr( glConfig.extensions_string, "GL_ARB_multitexture" ) )
+ {
+ if ( r_ext_multitexture->integer )
+ {
+ qglMultiTexCoord2fARB = ( PFNGLMULTITEXCOORD2FARBPROC ) qwglGetProcAddress( "glMultiTexCoord2fARB" );
+ qglActiveTextureARB = ( PFNGLACTIVETEXTUREARBPROC ) qwglGetProcAddress( "glActiveTextureARB" );
+ qglClientActiveTextureARB = ( PFNGLCLIENTACTIVETEXTUREARBPROC ) qwglGetProcAddress( "glClientActiveTextureARB" );
+
+ if ( qglActiveTextureARB )
+ {
+ qglGetIntegerv( GL_MAX_ACTIVE_TEXTURES_ARB, (GLint *)&glConfig.maxActiveTextures );
+
+ if ( glConfig.maxActiveTextures > 1 )
+ {
+ ri.Printf( PRINT_ALL, "...using GL_ARB_multitexture\n" );
+ }
+ else
+ {
+ qglMultiTexCoord2fARB = NULL;
+ qglActiveTextureARB = NULL;
+ qglClientActiveTextureARB = NULL;
+ ri.Printf( PRINT_ALL, "...not using GL_ARB_multitexture, < 2 texture units\n" );
+ }
+ }
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "...ignoring GL_ARB_multitexture\n" );
+ }
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "...GL_ARB_multitexture not found\n" );
+ }
+
+ // GL_EXT_compiled_vertex_array
+ qglLockArraysEXT = NULL;
+ qglUnlockArraysEXT = NULL;
+ if ( strstr( glConfig.extensions_string, "GL_EXT_compiled_vertex_array" ) && ( glConfig.hardwareType != GLHW_RIVA128 ) )
+ {
+ if ( r_ext_compiled_vertex_array->integer )
+ {
+ ri.Printf( PRINT_ALL, "...using GL_EXT_compiled_vertex_array\n" );
+ qglLockArraysEXT = ( void ( APIENTRY * )( GLint, GLint ) ) qwglGetProcAddress( "glLockArraysEXT" );
+ qglUnlockArraysEXT = ( void ( APIENTRY * )( void ) ) qwglGetProcAddress( "glUnlockArraysEXT" );
+ if (!qglLockArraysEXT || !qglUnlockArraysEXT) {
+ ri.Error (ERR_FATAL, "bad getprocaddress\n");
+ }
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "...ignoring GL_EXT_compiled_vertex_array\n" );
+ }
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "...GL_EXT_compiled_vertex_array not found\n" );
+ }
+
+#ifdef GL_APPLE_transform_hint
+ if ( strstr( glConfig.extensions_string, "GL_APPLE_transform_hint" ) ) {
+ r_appleTransformHint = ri.Cvar_Get("r_appleTransformHint", "1", CVAR_ARCHIVE );
+ if (r_appleTransformHint->value) {
+ ri.Printf( PRINT_ALL, "...using GL_APPLE_transform_hint\n");
+ qglHint(GL_TRANSFORM_HINT_APPLE, GL_FASTEST);
+ CheckErrors();
+ } else {
+ ri.Printf( PRINT_ALL, "...ignoring using GL_APPLE_transform_hint\n");
+ }
+ } else {
+ ri.Printf( PRINT_ALL, "...GL_APPLE_transform_hint not found\n" );
+ }
+#endif
+}
+
+
+#define MAX_RENDERER_INFO_COUNT 128
+
+// Returns zero if there are no hardware renderers. Otherwise, returns the max memory across all renderers (on the presumption that the screen that we'll use has the most memory).
+static unsigned long Sys_QueryVideoMemory()
+{
+ CGLError err;
+ CGLRendererInfoObj rendererInfo, rendererInfos[MAX_RENDERER_INFO_COUNT];
+ long rendererInfoIndex, rendererInfoCount = MAX_RENDERER_INFO_COUNT;
+ long rendererIndex, rendererCount;
+ long maxVRAM = 0, vram;
+ long accelerated;
+ long rendererID;
+ long totalRenderers = 0;
+
+ err = CGLQueryRendererInfo(CGDisplayIDToOpenGLDisplayMask(Sys_DisplayToUse()), rendererInfos, &rendererInfoCount);
+ if (err) {
+ Com_Printf("CGLQueryRendererInfo -> %d\n", err);
+ return vram;
+ }
+
+ //Com_Printf("rendererInfoCount = %d\n", rendererInfoCount);
+ for (rendererInfoIndex = 0; rendererInfoIndex < rendererInfoCount && totalRenderers < rendererInfoCount; rendererInfoIndex++) {
+ rendererInfo = rendererInfos[rendererInfoIndex];
+ //Com_Printf("rendererInfo: 0x%08x\n", rendererInfo);
+
+
+ err = CGLDescribeRenderer(rendererInfo, 0, kCGLRPRendererCount, &rendererCount);
+ if (err) {
+ Com_Printf("CGLDescribeRenderer(kCGLRPRendererID) -> %d\n", err);
+ continue;
+ }
+ //Com_Printf(" rendererCount: %d\n", rendererCount);
+
+ for (rendererIndex = 0; rendererIndex < rendererCount; rendererIndex++) {
+ totalRenderers++;
+ //Com_Printf(" rendererIndex: %d\n", rendererIndex);
+
+ rendererID = 0xffffffff;
+ err = CGLDescribeRenderer(rendererInfo, rendererIndex, kCGLRPRendererID, &rendererID);
+ if (err) {
+ Com_Printf("CGLDescribeRenderer(kCGLRPRendererID) -> %d\n", err);
+ continue;
+ }
+ //Com_Printf(" rendererID: 0x%08x\n", rendererID);
+
+ accelerated = 0;
+ err = CGLDescribeRenderer(rendererInfo, rendererIndex, kCGLRPAccelerated, &accelerated);
+ if (err) {
+ Com_Printf("CGLDescribeRenderer(kCGLRPAccelerated) -> %d\n", err);
+ continue;
+ }
+ //Com_Printf(" accelerated: %d\n", accelerated);
+ if (!accelerated)
+ continue;
+
+ vram = 0;
+ err = CGLDescribeRenderer(rendererInfo, rendererIndex, kCGLRPVideoMemory, &vram);
+ if (err) {
+ Com_Printf("CGLDescribeRenderer -> %d\n", err);
+ continue;
+ }
+ //Com_Printf(" vram: 0x%08x\n", vram);
+
+ // presumably we'll be running on the best card, so we'll take the max of the vrams
+ if (vram > maxVRAM)
+ maxVRAM = vram;
+ }
+
+#if 0
+ err = CGLDestroyRendererInfo(rendererInfo);
+ if (err) {
+ Com_Printf("CGLDestroyRendererInfo -> %d\n", err);
+ }
+#endif
+ }
+
+ return maxVRAM;
+}
+
+
+// We will set the Sys_IsHidden global to cause input to be handle differently (we'll just let NSApp handle events in this case). We also will unbind the GL context and restore the video mode.
+qboolean Sys_Hide()
+{
+ if (Sys_IsHidden)
+ // Eh?
+ return qfalse;
+
+ if (!r_fullscreen->integer)
+ // We only support hiding in fullscreen mode right now
+ return qfalse;
+
+ Sys_IsHidden = qtrue;
+
+ // Don't need to store the current gamma since we always keep it around in glw_state.inGameTable.
+
+ Sys_FadeScreen(Sys_DisplayToUse());
+
+ // Disassociate the GL context from the screen
+ // Have to call both to actually deallocate kernel resources and free the NSSurface
+ CGLClearDrawable(OSX_GetCGLContext());
+ [OSX_GetNSGLContext() clearDrawable];
+
+ // Restore the original video mode
+ _GLimp_RestoreOriginalVideoSettings();
+
+ // Restore the original gamma if needed.
+ if (glConfig.deviceSupportsGamma) {
+ CGDisplayRestoreColorSyncSettings();
+ }
+
+ // Release the screen(s)
+ ReleaseAllDisplays();
+
+ Sys_UnfadeScreens();
+
+ // Shut down the input system so the mouse and keyboard settings are restore to normal
+ Sys_ShutdownInput();
+
+ // Hide the application so that when the user clicks on our app icon, we'll get an unhide notification
+ [NSApp hide: nil];
+
+ return qtrue;
+}
+
+static CGDisplayErr Sys_CaptureActiveDisplays(void)
+{
+ CGDisplayErr err;
+ CGDisplayCount displayIndex;
+ for (displayIndex = 0; displayIndex < glw_state.displayCount; displayIndex++) {
+ const glwgamma_t *table;
+ table = &glw_state.originalDisplayGammaTables[displayIndex];
+ err = CGDisplayCapture(table->display);
+ if (err != CGDisplayNoErr)
+ return err;
+ }
+ return CGDisplayNoErr;
+}
+
+qboolean Sys_Unhide()
+{
+ CGDisplayErr err;
+ CGLError glErr;
+
+ if (!Sys_IsHidden)
+ // Eh?
+ return qfalse;
+
+ Sys_FadeScreens();
+
+ // Capture the screen(s)
+ err = Sys_CaptureActiveDisplays();
+ if (err != CGDisplayNoErr) {
+ Sys_UnfadeScreens();
+ ri.Printf( PRINT_ALL, "Unhide failed -- cannot capture the display again.\n" );
+ return qfalse;
+ }
+
+ // Restore the game mode
+ err = CGDisplaySwitchToMode(glw_state.display, (CFDictionaryRef)glw_state.gameMode);
+ if ( err != CGDisplayNoErr ) {
+ ReleaseAllDisplays();
+ Sys_UnfadeScreens();
+ ri.Printf( PRINT_ALL, "Unhide failed -- Unable to set display mode\n" );
+ return qfalse;
+ }
+
+ // Reassociate the GL context and the screen
+ glErr = CGLSetFullScreen(OSX_GetCGLContext());
+ if (err) {
+ ReleaseAllDisplays();
+ Sys_UnfadeScreens();
+ ri.Printf( PRINT_ALL, "Unhide failed: CGLSetFullScreen -> %d (%s)\n", err, CGLErrorString(err));
+ return qfalse;
+ }
+
+ // Restore the current context
+ [OSX_GetNSGLContext() makeCurrentContext];
+
+ // Restore the gamma that the game had set
+ Sys_UnfadeScreen(Sys_DisplayToUse(), &glw_state.inGameTable);
+
+ // Restore the input system (last so if something goes wrong we don't eat the mouse)
+ Sys_InitInput();
+
+ Sys_IsHidden = qfalse;
+ return qtrue;
+}
+
+
diff --git a/code/macosx/macosx_glsmp_mutex.m b/code/macosx/macosx_glsmp_mutex.m
new file mode 100755
index 0000000..ad3e1ef
--- /dev/null
+++ b/code/macosx/macosx_glsmp_mutex.m
@@ -0,0 +1,176 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#import "macosx_glimp.h"
+
+#include "tr_local.h"
+#import "macosx_local.h"
+#import "macosx_display.h"
+
+#import <AppKit/AppKit.h>
+#import <Foundation/Foundation.h>
+#import <pthread.h>
+
+//
+// The main Q3 SMP API
+//
+
+static pthread_mutex_t smpMutex;
+static pthread_cond_t mainThreadCondition;
+static pthread_cond_t renderThreadCondition;
+
+static volatile qboolean smpDataChanged;
+static volatile void *smpData;
+
+
+static void *GLimp_RenderThreadWrapper(void *arg)
+{
+ Com_Printf("Render thread starting\n");
+
+ ((void (*)())arg)();
+
+#ifndef USE_CGLMACROS
+ // Unbind the context before we die
+ OSX_GLContextClearCurrent();
+#endif
+
+ Com_Printf("Render thread terminating\n");
+
+ return arg;
+}
+
+qboolean GLimp_SpawnRenderThread( void (*function)( void ) )
+{
+ pthread_t renderThread;
+ int rc;
+
+ pthread_mutex_init(&smpMutex, NULL);
+ pthread_cond_init(&mainThreadCondition, NULL);
+ pthread_cond_init(&renderThreadCondition, NULL);
+
+ rc = pthread_create(&renderThread, NULL, GLimp_RenderThreadWrapper, function);
+ if (rc) {
+ ri.Printf(PRINT_ALL, "pthread_create returned %d: %s", rc, strerror(rc));
+ return qfalse;
+ } else {
+ rc = pthread_detach(renderThread);
+ if (rc) {
+ ri.Printf(PRINT_ALL, "pthread_detach returned %d: %s", rc, strerror(rc));
+ }
+ }
+
+ return qtrue;
+}
+
+// Called in the rendering thread to wait until a command buffer is ready.
+// The command buffer returned might be NULL, indicating that the rendering thread should exit.
+void *GLimp_RendererSleep(void)
+{
+ void *data;
+
+ GLSTAMP("GLimp_RendererSleep start", 0);
+
+#ifndef USE_CGLMACROS
+ // Clear the current context while we sleep so the main thread can access it
+ OSX_GLContextClearCurrent();
+#endif
+
+ pthread_mutex_lock(&smpMutex); {
+ // Clear out any data we had and signal the main thread that we are no longer busy
+ smpData = NULL;
+ smpDataChanged = qfalse;
+ pthread_cond_signal(&mainThreadCondition);
+
+ // Wait until we get something new to work on
+ while (!smpDataChanged)
+ pthread_cond_wait(&renderThreadCondition, &smpMutex);
+
+ // Record the data (if any).
+ data = smpData;
+ } pthread_mutex_unlock(&smpMutex);
+
+#ifndef USE_CGLMACROS
+ // We are going to render a frame... retake the context
+ OSX_GLContextSetCurrent();
+#endif
+
+ GLSTAMP("GLimp_RendererSleep end", 0);
+
+ return (void *)data;
+}
+
+// Called from the main thread to wait until the rendering thread is done with the command buffer.
+void GLimp_FrontEndSleep(void)
+{
+ GLSTAMP("GLimp_FrontEndSleep start", 0);
+
+ pthread_mutex_lock(&smpMutex); {
+ while (smpData) {
+#if 0
+ struct timespec ts;
+ int result;
+
+ ts.tv_sec = 1;
+ ts.tv_nsec = 0;
+ result = pthread_cond_timedwait_relative_np(&mainThreadCondition, &smpMutex, &ts);
+ if (result) {
+ Com_Printf("GLimp_FrontEndSleep timed out. Probably due to R_SyncRenderThread called due to Com_Error being called\n");
+ break;
+ }
+#else
+ pthread_cond_wait(&mainThreadCondition, &smpMutex);
+#endif
+ }
+ } pthread_mutex_unlock(&smpMutex);
+
+
+#ifndef USE_CGLMACROS
+ // We are done waiting for the background thread, take the current context back.
+ OSX_GLContextSetCurrent();
+#endif
+
+ GLSTAMP("GLimp_FrontEndSleep end", 0);
+}
+
+// This is called in the main thread to issue another command
+// buffer to the rendering thread. This is always called AFTER
+// GLimp_FrontEndSleep, so we know that there is no command
+// pending in 'smpData'.
+void GLimp_WakeRenderer( void *data )
+{
+ GLSTAMP("GLimp_WakeRenderer start", data);
+
+#ifndef USE_CGLMACROS
+ // We want the background thread to draw stuff. Give up the current context
+ OSX_GLContextClearCurrent();
+#endif
+
+ pthread_mutex_lock(&smpMutex); {
+ // Store the new data pointer and wake up the rendering thread
+ assert(smpData == NULL);
+ smpData = data;
+ smpDataChanged = qtrue;
+ pthread_cond_signal(&renderThreadCondition);
+ } pthread_mutex_unlock(&smpMutex);
+
+ GLSTAMP("GLimp_WakeRenderer end", data);
+}
+
diff --git a/code/macosx/macosx_glsmp_null.m b/code/macosx/macosx_glsmp_null.m
new file mode 100755
index 0000000..d189e3f
--- /dev/null
+++ b/code/macosx/macosx_glsmp_null.m
@@ -0,0 +1,46 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#import "macosx_glimp.h"
+
+#include "tr_local.h"
+#import "macosx_local.h"
+
+qboolean GLimp_SpawnRenderThread( void (*function)( void ) )
+{
+ return qfalse;
+}
+
+void *GLimp_RendererSleep(void)
+{
+ return NULL;
+}
+
+void GLimp_FrontEndSleep(void)
+{
+
+}
+
+void GLimp_WakeRenderer( void *data )
+{
+
+}
+
diff --git a/code/macosx/macosx_glsmp_ports.m b/code/macosx/macosx_glsmp_ports.m
new file mode 100755
index 0000000..ce6dc9f
--- /dev/null
+++ b/code/macosx/macosx_glsmp_ports.m
@@ -0,0 +1,425 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#import "macosx_glimp.h"
+
+#include "tr_local.h"
+#import "macosx_local.h"
+#import "macosx_display.h"
+
+#import <AppKit/AppKit.h>
+#import <Foundation/Foundation.h>
+#import <mach/mach.h>
+#import <mach/mach_error.h>
+
+
+#warning Using Mach Ports SMP acceleration implementation
+
+/*
+===========================================================
+
+SMP acceleration
+
+===========================================================
+*/
+
+#import <pthread.h>
+
+#define USE_MACH_PORTS 1
+
+// This is a small cover layer that makes for easier calling
+
+typedef struct _MsgPort {
+#if USE_MACH_PORTS
+ mach_port_t port;
+ id nsPort;
+#else
+ pthread_mutex_t mutex;
+ pthread_cond_t condition;
+ volatile unsigned int status;
+ unsigned int msgCode;
+ void *msgData;
+#endif
+} MsgPort;
+
+static BOOL portsInited = NO;
+static pthread_mutex_t logMutex;
+
+static unsigned int renderMsgOutstanding;
+static unsigned int rendererProcessingCommand;
+
+static MsgPort rendererMsgPort;
+static MsgPort frontEndMsgPort;
+
+enum {
+ MsgNone,
+ MsgPending,
+};
+
+enum {
+ MsgCodeInvalid = 0,
+ RenderCommandMsg = 1,
+ RenderCompletedMsg = 2,
+};
+
+static /*inline*/ void MsgPortInit(MsgPort *port)
+{
+#if USE_MACH_PORTS
+ port->nsPort = [[NSMachPort alloc] init];
+ port->port = [port->nsPort machPort];
+
+ //rc = mach_port_allocate(mach_task_self(), MACH_PORT_TYPE_SEND_RECEIVE, &port->port);
+ //if (rc) {
+ // fprintf(stderr, "MsgPortInit: mach_port_allocate returned: %d: %s \n",rc, mach_error_string(rc));
+ // }
+#else
+ int rc;
+ rc = pthread_mutex_init(&port->mutex, NULL);
+ if (rc) {
+ ri.Printf(PRINT_ALL, "MsgPortInit: pthread_mutex_init returned: %d: %s\n", rc, strerror(rc));
+ }
+ rc = pthread_cond_init(&port->condition, NULL);
+ if (rc) {
+ ri.Printf(PRINT_ALL, "EventInit: pthread_cond_init returned %d: %s\n", rc, strerror(rc));
+ }
+ port->status = MsgNone;
+ port->msgCode = MsgCodeInvalid;
+ port->msgData = NULL;
+#endif
+}
+
+static /*inline*/ void _SendMsg(MsgPort *port, unsigned int msgCode, void *msgData,
+ const char *functionName, const char *portName, const char *msgName)
+{
+ int rc;
+
+#if USE_MACH_PORTS
+ mach_msg_header_t msg;
+
+ //printf("SendMsg: %s %s %s (%d %08lx)\n",functionName, portName, msgName, msgCode, msgData);
+/*
+ typedef struct
+ {
+ mach_msg_bits_t msgh_bits;
+ mach_msg_size_t msgh_size;
+ mach_port_t msgh_remote_port;
+ mach_port_t msgh_local_port;
+ mach_msg_size_t msgh_reserved;
+ mach_msg_id_t msgh_id;
+ } mach_msg_header_t;
+*/
+ msg.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND,MACH_MSG_TYPE_MAKE_SEND_ONCE);
+ msg.msgh_size=sizeof(msg);
+ //msg.msg_type=MSG_TYPE_NORMAL;
+ msg.msgh_local_port=MACH_PORT_NULL;
+ msg.msgh_remote_port=port->port;
+ msg.msgh_reserved = 0;
+ msg.msgh_id=(mach_msg_id_t)msgData; // HACK
+
+ rc = mach_msg_send(&msg);
+ if(rc) {
+ fprintf(stderr,"SendMsg: mach_msg_send returned %d: %s\n", rc, mach_error_string(rc));
+ }
+#else
+ //printf("SendMsg: %s %s %s (%d %08lx)\n",functionName, portName, msgName, msgCode, msgData);
+ rc = pthread_mutex_lock(&port->mutex);
+ if(rc) {
+ fprintf(stderr,"SendMsg: pthread_mutex_lock returned %d: %s\n", rc, strerror(rc));
+ }
+
+ /* Block until port is empty */
+ while(port->status != MsgNone) {
+ //fprintf(stderr, "SendMsg: %s blocking until port %s is empty\n", functionName, portName);
+ rc = pthread_cond_wait(&port->condition, &port->mutex);
+ if(rc) {
+ fprintf(stderr, "SendMsg: pthread_cond_wait returned %d: %s\n", rc, strerror(rc));
+ }
+ }
+
+ /* Queue msg */
+ port->msgCode = msgCode;
+ port->msgData = msgData;
+ port->status = MsgPending;
+
+ /* Unlock port */
+ rc = pthread_mutex_unlock(&port->mutex);
+ if(rc) {
+ fprintf(stderr, "SendMsg: pthread_mutex_unlock returned %d: %s\n", rc, strerror(rc));
+ }
+
+ /* Wake up any threads blocked waiting for a message */
+ rc = pthread_cond_broadcast(&port->condition);
+ if(rc) {
+ fprintf(stderr, "SendMsg: pthread_cond_broadcast returned %d: %s\n", rc, strerror(rc));
+ }
+#endif
+}
+
+static /*inline*/ void _WaitMsg(MsgPort *port, unsigned int *msgCode, void **msgData,
+ const char *functionName, const char *portName)
+{
+ int rc;
+#if USE_MACH_PORTS
+ mach_msg_empty_rcv_t msg;
+
+ //printf("WaitMsg: %s %s\n",functionName, portName);
+
+ msg.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND,MACH_MSG_TYPE_MAKE_SEND_ONCE);
+ msg.header.msgh_size= sizeof(msg);
+ //msg.msg_type=MSG_TYPE_NORMAL;
+ msg.header.msgh_local_port=port->port;
+ msg.header.msgh_remote_port=MACH_PORT_NULL;
+ msg.header.msgh_reserved = 0;
+ msg.header.msgh_id=(mach_msg_id_t)msgData; // HACK
+
+ rc = mach_msg_receive(&msg.header);
+ if(rc) {
+ fprintf(stderr,"SendMsg: mach_msg_receive returned %d: %s\n", rc, mach_error_string(rc));
+ }
+
+ *msgData = (void *)msg.header.msgh_id;
+ //printf("WaitMsg: %s %s got %08lx\n",functionName, portName, *msgData);
+#else
+ //printf("WaitMsg: %s %s\n",functionName, portName);
+
+ rc = pthread_mutex_lock(&port->mutex);
+ if(rc) {
+ fprintf(stderr, "WaitMsg: pthread_mutex_lock returned %d: %s\n", rc, strerror(rc));
+ }
+
+ /* Block until port is empty */
+ while(port->status != MsgPending) {
+ rc = pthread_cond_wait(&port->condition, &port->mutex);
+ if(rc) {
+ fprintf(stderr, "WaitMsg: pthread_cond_wait returned %d: %s\n", rc, strerror(rc));
+ }
+ }
+
+ /* Remove msg */
+ *msgCode = port->msgCode;
+ *msgData = port->msgData;
+
+ //printf("WaitMsg: %s %s got %d %08lx\n",functionName, portName, *msgCode, *msgData);
+
+ port->status = MsgNone;
+ port->msgCode = 0;
+ port->msgData = NULL;
+
+ rc = pthread_mutex_unlock(&port->mutex);
+ if(rc) {
+ fprintf(stderr, "WaitMsg: pthread_mutex_unlock returned %d: %s\n", rc, strerror(rc));
+ }
+
+ /* Wake up any threads blocked waiting for port to be empty. */
+ rc = pthread_cond_broadcast(&port->condition);
+ if(rc) {
+ fprintf(stderr, "SendMsg: pthread_cond_broadcast returned %d: %s\n", rc, strerror(rc));
+ }
+#endif
+}
+
+
+#define SendMsg(p, c, d) _SendMsg(p, c, d, __PRETTY_FUNCTION__, #p, #c)
+#define WaitMsg(p, c, d) _WaitMsg(p, c, d, __PRETTY_FUNCTION__, #p)
+
+#if 0
+static void _Log(const char *msg)
+{
+ int rc;
+
+ rc = pthread_mutex_lock(&logMutex);
+ if (rc)
+ ri.Printf(PRINT_ALL, "_Log: pthread_mutex_lock returned %d: %s\n", rc, strerror(rc));
+
+ fputs(msg,stderr);
+ fflush(stderr);
+
+ rc = pthread_mutex_unlock(&logMutex);
+ if (rc)
+ ri.Printf(PRINT_ALL, "_Log: pthread_mutex_unlock returned %d: %s\n", rc, strerror(rc));
+}
+#endif
+
+
+//
+// The main Q3 SMP API
+//
+
+static void (*glimpRenderThread)( void ) = NULL;
+
+static void *GLimp_RenderThreadWrapper(void *arg)
+{
+ Com_Printf("Render thread starting\n");
+
+ glimpRenderThread();
+
+#ifndef USE_CGLMACROS
+ // Unbind the context before we die
+ OSX_GLContextClearCurrent();
+#endif
+
+ // Send one last message back to front end before we die...
+ // This is somewhat of a hack.. fixme.
+ if (rendererProcessingCommand) {
+ SendMsg(&frontEndMsgPort, RenderCompletedMsg, NULL);
+ rendererProcessingCommand = NO;
+ }
+
+ Com_Printf("Render thread terminating\n");
+
+ return arg;
+}
+
+qboolean GLimp_SpawnRenderThread( void (*function)( void ) )
+{
+ pthread_t renderThread;
+ int rc;
+
+ if (!portsInited) {
+ portsInited = YES;
+ MsgPortInit(&rendererMsgPort);
+ MsgPortInit(&frontEndMsgPort);
+ renderMsgOutstanding = NO;
+ rendererProcessingCommand = NO;
+ pthread_mutex_init(&logMutex, NULL);
+ }
+
+ glimpRenderThread = function;
+
+ rc = pthread_create(&renderThread,
+ NULL, // attributes
+ GLimp_RenderThreadWrapper,
+ NULL); // argument
+ if (rc) {
+ ri.Printf(PRINT_ALL, "pthread_create returned %d: %s", rc, strerror(rc));
+ return qfalse;
+ } else {
+ rc = pthread_detach(renderThread);
+ if (rc) {
+ ri.Printf(PRINT_ALL, "pthread_detach returned %d: %s", rc, strerror(rc));
+ }
+ }
+
+ return qtrue;
+}
+
+static volatile void *smpData;
+
+// TJW - This is calling in the rendering thread to wait until another
+// command buffer is ready. The command buffer returned might be NULL,
+// indicating that the rendering thread should exit.
+void *GLimp_RendererSleep(void)
+{
+ //_Log(__PRETTY_FUNCTION__ " entered");
+ unsigned int msgCode;
+ void *msgData;
+
+ GLSTAMP("GLimp_RendererSleep start", 0);
+
+#ifndef USE_CGLMACROS
+ // Clear the current context while we sleep so the main thread can access it
+ OSX_GLContextClearCurrent();
+#endif
+
+ // Let the main thread we are idle and that no work is queued
+ //_Log("rs0\n");
+ /* If we actually had some work to do, then tell the front end we completed it. */
+ if (rendererProcessingCommand) {
+ SendMsg(&frontEndMsgPort, RenderCompletedMsg, NULL);
+ rendererProcessingCommand = NO;
+ }
+
+ // Wait for new msg
+ for (;;) {
+ WaitMsg(&rendererMsgPort, &msgCode, &msgData);
+ if (1 || msgCode == RenderCommandMsg) {
+ smpData = msgData;
+ break;
+ } else {
+ printf("renderer received unknown message: %d\n",msgCode);
+ }
+ }
+
+#ifndef USE_CGLMACROS
+ // We are going to render a frame... retake the context
+ OSX_GLContextSetCurrent();
+#endif
+
+ rendererProcessingCommand = YES;
+
+ GLSTAMP("GLimp_RendererSleep end", 0);
+
+ return (void *)smpData;
+}
+
+
+// TJW - This is from the main thread to wait until the rendering thread
+// has completed the command buffer that it has
+void GLimp_FrontEndSleep(void)
+{
+ unsigned int msgCode;
+ void *msgData;
+
+ GLSTAMP("GLimp_FrontEndSleep start", 1);
+
+ if (renderMsgOutstanding) {
+ for (;;) {
+ WaitMsg(&frontEndMsgPort, &msgCode, &msgData);
+ if(1 || msgCode == RenderCompletedMsg) {
+ break;
+ } else {
+ printf("front end received unknown message: %d\n",msgCode);
+ }
+ }
+ renderMsgOutstanding = NO;
+ }
+
+#ifndef USE_CGLMACROS
+ // We are done waiting for the background thread, take the current context back.
+ OSX_GLContextSetCurrent();
+#endif
+
+ GLSTAMP("GLimp_FrontEndSleep end", 1);
+}
+
+
+// TJW - This is called in the main thread to issue another command
+// buffer to the rendering thread. This is always called AFTER
+// GLimp_FrontEndSleep, so we know that there is no command
+// pending in 'smpData'.
+void GLimp_WakeRenderer( void *data )
+{
+ GLSTAMP("GLimp_WakeRenderer start", 1);
+
+#ifndef USE_CGLMACROS
+ // We want the background thread to draw stuff. Give up the current context
+ OSX_GLContextClearCurrent();
+#endif
+
+ SendMsg(&rendererMsgPort, RenderCommandMsg, data);
+
+ // Don't set flag saying that the renderer is processing something if it's just
+ // being told to exit.
+ //if(data != NULL)
+ renderMsgOutstanding = YES;
+
+ GLSTAMP("GLimp_WakeRenderer end", 1);
+}
diff --git a/code/macosx/macosx_input.m b/code/macosx/macosx_input.m
new file mode 100755
index 0000000..0697a86
--- /dev/null
+++ b/code/macosx/macosx_input.m
@@ -0,0 +1,916 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#import <AppKit/AppKit.h>
+#import <Foundation/Foundation.h>
+#include <ApplicationServices/ApplicationServices.h>
+
+#import "../client/client.h"
+#import "macosx_local.h"
+#import "../renderer/tr_local.h"
+
+#import "Q3Controller.h"
+//#import "CGMouseDeltaFix.h"
+#import "macosx_timers.h"
+#import "macosx_display.h" // For Sys_SetScreenFade
+
+#import <drivers/event_status_driver.h>
+#import <sys/types.h>
+#import <sys/time.h>
+#import <unistd.h>
+
+
+static qboolean inputActive;
+
+static NSDate *distantPast;
+
+static cvar_t *in_nomouse;
+static cvar_t *in_showevents;
+static cvar_t *in_mouseLowEndSlope;
+static cvar_t *in_mouseHighEndCutoff;
+static cvar_t *in_disableOSMouseScaling;
+
+static void Sys_StartMouseInput();
+static void Sys_StopMouseInput();
+static qboolean mouseactive = qfalse;
+static BOOL inputRectValid = NO;
+static CGRect inputRect;
+static NXMouseScaling originalScaling;
+
+static unsigned int currentModifierFlags;
+
+
+
+static void Sys_PreventMouseMovement(CGPoint point)
+{
+ CGEventErr err;
+
+ //Com_Printf("**** Calling CGAssociateMouseAndMouseCursorPosition(false)\n");
+ err = CGAssociateMouseAndMouseCursorPosition(false);
+ if (err != CGEventNoErr) {
+ Sys_Error("Could not disable mouse movement, CGAssociateMouseAndMouseCursorPosition returned %d\n", err);
+ }
+
+ // Put the mouse in the position we want to leave it at
+ err = CGWarpMouseCursorPosition(point);
+ if (err != CGEventNoErr) {
+ Sys_Error("Could not disable mouse movement, CGWarpMouseCursorPosition returned %d\n", err);
+ }
+}
+
+static void Sys_ReenableMouseMovement()
+{
+ CGEventErr err;
+
+ //Com_Printf("**** Calling CGAssociateMouseAndMouseCursorPosition(true)\n");
+
+ err = CGAssociateMouseAndMouseCursorPosition(true);
+ if (err != CGEventNoErr) {
+ Sys_Error("Could not reenable mouse movement, CGAssociateMouseAndMouseCursorPosition returned %d\n", err);
+ }
+
+ // Leave the mouse where it was -- don't warp here.
+}
+
+
+void Sys_InitInput(void)
+{
+ // no input with dedicated servers
+ if ( com_dedicated->integer ) {
+ return;
+ }
+
+ // The Cvars don't seem to work really early.
+ [(Q3Controller *)[NSApp delegate] showBanner];
+
+ Com_Printf( "------- Input Initialization -------\n" );
+
+ if (!distantPast)
+ distantPast = [[NSDate distantPast] retain];
+
+ // For hide support. If we don't do this, then the command key will get stuck on when we hide (since we won't get the flags changed event when it goes up).
+ currentModifierFlags = 0;
+
+ r_fullscreen = Cvar_Get( "r_fullscreen", "1", CVAR_ARCHIVE | CVAR_LATCH );
+ in_nomouse = Cvar_Get( "in_nomouse", "0", 0 );
+ in_showevents = Cvar_Get( "in_showevents", "0", 0 );
+
+ // these defaults were arrived at via emprical testing between a Windows box and a Mac OS X box
+#define ACT_LIKE_WINDOWS
+#ifdef ACT_LIKE_WINDOWS
+ in_mouseLowEndSlope = Cvar_Get("in_mouseLowEndSlope", "3.5", CVAR_ARCHIVE);
+ if (in_mouseLowEndSlope->value < 1) {
+ Cvar_Set("in_mouseLowEndSlope", "1");
+ }
+#else
+ in_mouseLowEndSlope = Cvar_Get("in_mouseLowEndSlope", "1", CVAR_ARCHIVE);
+ if (in_mouseLowEndSlope->value < 1) {
+ Cvar_Set("in_mouseLowEndSlope", "1");
+ }
+#endif
+
+ in_mouseHighEndCutoff = Cvar_Get("in_mouseHighEndCutoff", "20", CVAR_ARCHIVE);
+ if (in_mouseLowEndSlope->value < 1) {
+ Cvar_Set("in_mouseHighEndCutoff", "1");
+ }
+ in_disableOSMouseScaling = Cvar_Get("in_disableOSMouseScaling", "1", CVAR_ARCHIVE );
+
+ glw_state.display = Sys_DisplayToUse();
+
+ inputActive = qtrue;
+
+ if ( in_nomouse->integer == 0 )
+ Sys_StartMouseInput();
+ else
+ Com_Printf( " in_nomouse is set, skipping.\n" );
+
+ Com_Printf( "------------------------------------\n" );
+}
+
+void Sys_ShutdownInput(void)
+{
+ // no input with dedicated servers
+ if ( !com_dedicated || com_dedicated->integer ) {
+ return;
+ }
+
+ Com_Printf( "------- Input Shutdown -------\n" );
+ if ( !inputActive ) {
+ return;
+ }
+ inputActive = qfalse;
+
+ if (mouseactive)
+ Sys_StopMouseInput();
+
+ Com_Printf( "------------------------------\n" );
+}
+
+static void Sys_LockMouseInInputRect(CGRect rect)
+{
+ CGPoint center;
+
+ center.x = rect.origin.x + rect.size.width / 2.0;
+ center.y = rect.origin.y + rect.size.height / 2.0;
+
+ // Now, put the mouse in the middle of the input rect (anywhere over it would do)
+ // and don't allow it to move. This means that the user won't be able to accidentally
+ // select another application.
+ Sys_PreventMouseMovement(center);
+}
+
+extern void Sys_UpdateWindowMouseInputRect(void);
+
+static void Sys_StartMouseInput()
+{
+ NXEventHandle eventStatus;
+ CGMouseDelta dx, dy;
+
+ if (mouseactive) {
+ //Com_Printf("**** Attempted to start mouse input while already started\n");
+ return;
+ }
+
+ Com_Printf("Starting mouse input\n");
+
+ mouseactive = qtrue;
+ if (inputRectValid && !glConfig.isFullscreen)
+ // Make sure that if window moved we don't hose the user...
+ Sys_UpdateWindowMouseInputRect();
+
+ Sys_LockMouseInInputRect(inputRect);
+
+ // Grab any mouse delta information to reset the last delta buffer
+ CGGetLastMouseDelta(&dx, &dy);
+
+ // Turn off mouse scaling
+ if (in_disableOSMouseScaling->integer==0 && (eventStatus = NXOpenEventStatus())) {
+ NXMouseScaling newScaling;
+
+ NXGetMouseScaling(eventStatus, &originalScaling);
+ newScaling.numScaleLevels = 1;
+ newScaling.scaleThresholds[0] = 1;
+ newScaling.scaleFactors[0] = -1;
+ NXSetMouseScaling(eventStatus, &newScaling);
+ NXCloseEventStatus(eventStatus);
+ }
+
+ [NSCursor hide];
+}
+
+static void Sys_StopMouseInput()
+{
+ NXEventHandle eventStatus;
+ if (!mouseactive) {
+ //Com_Printf("**** Attempted to stop mouse input while already stopped\n");
+ return;
+ }
+
+ Com_Printf("Stopping mouse input\n");
+
+ // Restore mouse scaling
+ if (in_disableOSMouseScaling->integer == 0 && (eventStatus = NXOpenEventStatus())) {
+ NXSetMouseScaling(eventStatus, &originalScaling);
+ NXCloseEventStatus(eventStatus);
+ }
+
+ mouseactive = qfalse;
+ Sys_ReenableMouseMovement();
+
+ [NSCursor unhide];
+}
+
+//===========================================================================
+
+#include <sys/types.h>
+#include <sys/time.h>
+#include <unistd.h>
+
+static char *Sys_ConsoleInput(void)
+{
+ extern qboolean stdin_active;
+ static char text[256];
+ int len;
+ fd_set fdset;
+ struct timeval timeout;
+
+ if (!com_dedicated || !com_dedicated->integer)
+ return NULL;
+
+ if (!stdin_active)
+ return NULL;
+
+ FD_ZERO(&fdset);
+ FD_SET(fileno(stdin), &fdset);
+ timeout.tv_sec = 0;
+ timeout.tv_usec = 0;
+ if (select (1, &fdset, NULL, NULL, &timeout) == -1 || !FD_ISSET(fileno(stdin), &fdset))
+ return NULL;
+
+ len = read (fileno(stdin), text, sizeof(text));
+ if (len == 0) { // eof!
+ stdin_active = qfalse;
+ return NULL;
+ }
+
+ if (len < 1)
+ return NULL;
+ text[len-1] = 0; // rip off the /n and terminate
+
+ return text;
+}
+
+//===========================================================================
+// Mouse input
+//===========================================================================
+
+#define MAX_DISPLAYS 128
+
+CGDirectDisplayID Sys_DisplayToUse(void)
+{
+ static BOOL gotDisplay = NO;
+ static CGDirectDisplayID displayToUse;
+
+ cvar_t *vid_screen;
+ CGDisplayErr err;
+ CGDirectDisplayID displays[MAX_DISPLAYS];
+ CGDisplayCount displayCount;
+ int displayIndex;
+
+ if (gotDisplay)
+ return displayToUse;
+ gotDisplay = YES;
+
+ err = CGGetActiveDisplayList(MAX_DISPLAYS, displays, &displayCount);
+ if (err != CGDisplayNoErr)
+ Sys_Error("Cannot get display list -- CGGetActiveDisplayList returned %d.\n", err);
+
+ // -1, the default, means to use the main screen
+ if ((vid_screen = Cvar_Get("vid_screen", "-1", CVAR_ARCHIVE)))
+ displayIndex = vid_screen->integer;
+ else
+ displayIndex = -1;
+
+ if (displayIndex < 0 || displayIndex >= displayCount)
+ // This is documented (in CGDirectDisplay.h) to be the main display. We want to
+ // return this instead of kCGDirectMainDisplay since this will allow us to compare
+ // display IDs.
+ displayToUse = displays[0];
+ else
+ displayToUse = displays[displayIndex];
+
+ return displayToUse;
+}
+
+void Sys_SetMouseInputRect(CGRect newRect)
+{
+ inputRectValid = YES;
+ inputRect = newRect;
+ //Com_Printf("**** inputRect = (%f, %f, %f, %f)\n", newRect.origin.x, newRect.origin.y, newRect.size.width, newRect.size.height);
+
+ if (mouseactive)
+ Sys_LockMouseInInputRect(inputRect);
+}
+
+
+static void Sys_ProcessMouseMovedEvent(NSEvent *mouseMovedEvent, int currentTime)
+{
+ float dx, dy;
+
+ if (!mouseactive)
+ return;
+
+ dx = [mouseMovedEvent deltaX];
+ dy = [mouseMovedEvent deltaY];
+
+ if (in_showevents->integer)
+ Com_Printf("MOUSE MOVED: %d, %d\n", dx, dy);
+
+ Sys_QueEvent(currentTime, SE_MOUSE, dx, dy, 0, NULL );
+}
+
+// If we are 'paused' (i.e., in any state that our normal key bindings aren't in effect), then interpret cmd-h and cmd-tab as hiding the application.
+static qboolean maybeHide()
+{
+ if ((currentModifierFlags & NSCommandKeyMask) == 0)
+ return qfalse;
+
+ return Sys_Hide();
+}
+
+static inline void sendEventForCharacter(NSEvent *event, unichar character, qboolean keyDownFlag, int currentTime)
+{
+ if (in_showevents->integer)
+ Com_Printf("CHARACTER: 0x%02x down=%d\n", character, keyDownFlag);
+
+#ifdef OMNI_TIMER
+ if (character == NSF9FunctionKey && !keyDownFlag) {
+ // Log and reset the root timer. We should currently only have the root on the stack.
+ OTStackPopRoot();
+ OTStackReportResults(NULL);
+ OTStackReset();
+ OTStackPushRoot(rootNode);
+ }
+#endif
+
+ switch (character) {
+ case 0x03:
+ Sys_QueEvent(currentTime, SE_KEY, K_KP_ENTER, keyDownFlag, 0, NULL);
+ break;
+ case '\b':
+ case '\177':
+ Sys_QueEvent(currentTime, SE_KEY, K_BACKSPACE, keyDownFlag, 0, NULL);
+ if (keyDownFlag) {
+ Sys_QueEvent(currentTime, SE_CHAR, '\b', 0, 0, NULL);
+ }
+ break;
+ case '\t':
+ if (maybeHide())
+ return;
+ Sys_QueEvent(currentTime, SE_KEY, K_TAB, keyDownFlag, 0, NULL);
+ if (keyDownFlag) {
+ Sys_QueEvent(currentTime, SE_CHAR, '\t', 0, 0, NULL);
+ }
+ break;
+ case '\r':
+ case '\n':
+ Sys_QueEvent(currentTime, SE_KEY, K_ENTER, keyDownFlag, 0, NULL);
+ if (keyDownFlag) {
+ Sys_QueEvent(currentTime, SE_CHAR, '\r', 0, 0, NULL);
+ }
+ break;
+ case '\033':
+ Sys_QueEvent(currentTime, SE_KEY, K_ESCAPE, keyDownFlag, 0, NULL);
+ break;
+ case ' ':
+ Sys_QueEvent(currentTime, SE_KEY, K_SPACE, keyDownFlag, 0, NULL);
+ if (keyDownFlag) {
+ Sys_QueEvent(currentTime, SE_CHAR, ' ', 0, 0, NULL);
+ }
+ break;
+ case NSUpArrowFunctionKey:
+ Sys_QueEvent(currentTime, SE_KEY, K_UPARROW, keyDownFlag, 0, NULL);
+ break;
+ case NSDownArrowFunctionKey:
+ Sys_QueEvent(currentTime, SE_KEY, K_DOWNARROW, keyDownFlag, 0, NULL);
+ break;
+ case NSLeftArrowFunctionKey:
+ Sys_QueEvent(currentTime, SE_KEY, K_LEFTARROW, keyDownFlag, 0, NULL);
+ break;
+ case NSRightArrowFunctionKey:
+ Sys_QueEvent(currentTime, SE_KEY, K_RIGHTARROW, keyDownFlag, 0, NULL);
+ break;
+ case NSF1FunctionKey:
+ Sys_QueEvent(currentTime, SE_KEY, K_F1, keyDownFlag, 0, NULL);
+ break;
+ case NSF2FunctionKey:
+ Sys_QueEvent(currentTime, SE_KEY, K_F2, keyDownFlag, 0, NULL);
+ break;
+ case NSF3FunctionKey:
+ Sys_QueEvent(currentTime, SE_KEY, K_F3, keyDownFlag, 0, NULL);
+ break;
+ case NSF4FunctionKey:
+ Sys_QueEvent(currentTime, SE_KEY, K_F4, keyDownFlag, 0, NULL);
+ break;
+ case NSF5FunctionKey:
+ Sys_QueEvent(currentTime, SE_KEY, K_F5, keyDownFlag, 0, NULL);
+ break;
+ case NSF6FunctionKey:
+ Sys_QueEvent(currentTime, SE_KEY, K_F6, keyDownFlag, 0, NULL);
+ break;
+ case NSF7FunctionKey:
+ Sys_QueEvent(currentTime, SE_KEY, K_F7, keyDownFlag, 0, NULL);
+ break;
+ case NSF8FunctionKey:
+ Sys_QueEvent(currentTime, SE_KEY, K_F8, keyDownFlag, 0, NULL);
+ break;
+ case NSF9FunctionKey:
+ Sys_QueEvent(currentTime, SE_KEY, K_F9, keyDownFlag, 0, NULL);
+ break;
+ case NSF10FunctionKey:
+ Sys_QueEvent(currentTime, SE_KEY, K_F10, keyDownFlag, 0, NULL);
+ break;
+ case NSF11FunctionKey:
+ Sys_QueEvent(currentTime, SE_KEY, K_F11, keyDownFlag, 0, NULL);
+ break;
+ case NSF12FunctionKey:
+ Sys_QueEvent(currentTime, SE_KEY, K_F12, keyDownFlag, 0, NULL);
+ break;
+ case NSF13FunctionKey:
+ Sys_QueEvent(currentTime, SE_KEY, '`', keyDownFlag, 0, NULL);
+ if (keyDownFlag) {
+ Sys_QueEvent(currentTime, SE_CHAR, '`', 0, 0, NULL);
+ }
+ break;
+ case NSInsertFunctionKey:
+ Sys_QueEvent(currentTime, SE_KEY, K_INS, keyDownFlag, 0, NULL);
+ break;
+ case NSDeleteFunctionKey:
+ Sys_QueEvent(currentTime, SE_KEY, K_DEL, keyDownFlag, 0, NULL);
+ break;
+ case NSPageDownFunctionKey:
+ Sys_QueEvent(currentTime, SE_KEY, K_PGDN, keyDownFlag, 0, NULL);
+ break;
+ case NSPageUpFunctionKey:
+ Sys_QueEvent(currentTime, SE_KEY, K_PGUP, keyDownFlag, 0, NULL);
+ break;
+ case NSHomeFunctionKey:
+ Sys_QueEvent(currentTime, SE_KEY, K_HOME, keyDownFlag, 0, NULL);
+ break;
+ case NSEndFunctionKey:
+ Sys_QueEvent(currentTime, SE_KEY, K_END, keyDownFlag, 0, NULL);
+ break;
+ case NSPauseFunctionKey:
+ Sys_QueEvent(currentTime, SE_KEY, K_PAUSE, keyDownFlag, 0, NULL);
+ break;
+ default:
+ if ([event modifierFlags] & NSNumericPadKeyMask) {
+ switch (character) {
+ case '0':
+ Sys_QueEvent(currentTime, SE_KEY, K_KP_INS, keyDownFlag, 0, NULL);
+ break;
+ case '1':
+ Sys_QueEvent(currentTime, SE_KEY, K_KP_END, keyDownFlag, 0, NULL);
+ break;
+ case '2':
+ Sys_QueEvent(currentTime, SE_KEY, K_KP_DOWNARROW, keyDownFlag, 0, NULL);
+ break;
+ case '3':
+ Sys_QueEvent(currentTime, SE_KEY, K_KP_PGDN, keyDownFlag, 0, NULL);
+ break;
+ case '4':
+ Sys_QueEvent(currentTime, SE_KEY, K_KP_LEFTARROW, keyDownFlag, 0, NULL);
+ break;
+ case '5':
+ Sys_QueEvent(currentTime, SE_KEY, K_KP_5, keyDownFlag, 0, NULL);
+ break;
+ case '6':
+ Sys_QueEvent(currentTime, SE_KEY, K_KP_RIGHTARROW, keyDownFlag, 0, NULL);
+ break;
+ case '7':
+ Sys_QueEvent(currentTime, SE_KEY, K_KP_HOME, keyDownFlag, 0, NULL);
+ break;
+ case '8':
+ Sys_QueEvent(currentTime, SE_KEY, K_KP_UPARROW, keyDownFlag, 0, NULL);
+ break;
+ case '9':
+ Sys_QueEvent(currentTime, SE_KEY, K_KP_PGUP, keyDownFlag, 0, NULL);
+ break;
+ case '.':
+ case ',':
+ Sys_QueEvent(currentTime, SE_KEY, K_KP_DEL, keyDownFlag, 0, NULL);
+ break;
+ case '+':
+ Sys_QueEvent(currentTime, SE_KEY, K_KP_PLUS, keyDownFlag, 0, NULL);
+ break;
+ case '-':
+ Sys_QueEvent(currentTime, SE_KEY, K_KP_MINUS, keyDownFlag, 0, NULL);
+ break;
+ case '*':
+ Sys_QueEvent(currentTime, SE_KEY, K_KP_STAR, keyDownFlag, 0, NULL);
+ break;
+ case '/':
+ Sys_QueEvent(currentTime, SE_KEY, K_KP_SLASH, keyDownFlag, 0, NULL);
+ break;
+ case '=':
+ Sys_QueEvent(currentTime, SE_KEY, K_KP_EQUALS, keyDownFlag, 0, NULL);
+ break;
+ default:
+ //NSLog(@"TODO: Implement character %d", (int)character);
+ break;
+ }
+ } else if (character >= 'a' && character <= 'z') {
+ if (character == 'h') {
+ if (maybeHide())
+ return;
+ }
+ Sys_QueEvent(currentTime, SE_KEY, character, keyDownFlag, 0, NULL);
+ if (keyDownFlag) {
+ Sys_QueEvent(currentTime, SE_CHAR, (char)character, 0, 0, NULL);
+ }
+ } else if (character >= 'A' && character <= 'Z') {
+ Sys_QueEvent(currentTime, SE_KEY, 'a' + (character - 'A'), keyDownFlag, 0, NULL);
+ if (keyDownFlag) {
+ Sys_QueEvent(currentTime, SE_CHAR, character, 0, 0, NULL);
+ }
+ } else if (character >= 32 && character < 127) {
+ Sys_QueEvent(currentTime, SE_KEY, character, keyDownFlag, 0, NULL);
+ if (keyDownFlag) {
+ Sys_QueEvent(currentTime, SE_CHAR, (char)character, 0, 0, NULL);
+ }
+ } else {
+ //NSLog(@"TODO: Implement character %d", (int)character);
+ }
+ break;
+ }
+}
+
+static inline void processKeyEvent(NSEvent *keyEvent, qboolean keyDownFlag, int currentTime)
+{
+ NSEventType eventType;
+ NSString *characters;
+ unsigned int characterIndex, characterCount;
+
+ eventType = [keyEvent type];
+ characters = [keyEvent charactersIgnoringModifiers];
+ characterCount = [characters length];
+
+ for (characterIndex = 0; characterIndex < characterCount; characterIndex++) {
+ sendEventForCharacter(keyEvent, [characters characterAtIndex:characterIndex], keyDownFlag, currentTime);
+ }
+}
+
+static inline void sendEventForMaskChangeInFlags(int quakeKey, unsigned int modifierMask, unsigned int newModifierFlags, int currentTime)
+{
+ BOOL oldHadModifier, newHasModifier;
+
+ oldHadModifier = (currentModifierFlags & modifierMask) != 0;
+ newHasModifier = (newModifierFlags & modifierMask) != 0;
+ if (oldHadModifier != newHasModifier) {
+ // NSLog(@"Key %d posted for modifier mask modifierMask", quakeKey);
+ Sys_QueEvent(currentTime, SE_KEY, quakeKey, newHasModifier, 0, NULL);
+ }
+}
+
+static inline void processFlagsChangedEvent(NSEvent *flagsChangedEvent, int currentTime)
+{
+ int newModifierFlags;
+
+ newModifierFlags = [flagsChangedEvent modifierFlags];
+ sendEventForMaskChangeInFlags(K_COMMAND, NSCommandKeyMask, newModifierFlags, currentTime);
+ sendEventForMaskChangeInFlags(K_CAPSLOCK, NSAlphaShiftKeyMask, newModifierFlags, currentTime);
+ sendEventForMaskChangeInFlags(K_ALT, NSAlternateKeyMask, newModifierFlags, currentTime);
+ sendEventForMaskChangeInFlags(K_CTRL, NSControlKeyMask, newModifierFlags, currentTime);
+ sendEventForMaskChangeInFlags(K_SHIFT, NSShiftKeyMask, newModifierFlags, currentTime);
+ currentModifierFlags = newModifierFlags;
+}
+
+static inline void processSystemDefinedEvent(NSEvent *systemDefinedEvent, int currentTime)
+{
+ static int oldButtons = 0;
+ int buttonsDelta;
+ int buttons;
+ int isDown;
+
+ if ([systemDefinedEvent subtype] == 7) {
+
+ if (!mouseactive)
+ return;
+
+
+ buttons = [systemDefinedEvent data2];
+ buttonsDelta = oldButtons ^ buttons;
+
+ //Com_Printf("uberbuttons: %08lx %08lx\n",buttonsDelta,buttons);
+
+
+ if (buttonsDelta & 1) {
+ isDown = buttons & 1;
+ Sys_QueEvent(currentTime, SE_KEY, K_MOUSE1, isDown, 0, NULL);
+ if (in_showevents->integer) {
+ Com_Printf("MOUSE2: %s\n", isDown ? "down" : "up");
+ }
+ }
+
+ if (buttonsDelta & 2) {
+ isDown = buttons & 2;
+ Sys_QueEvent(currentTime, SE_KEY, K_MOUSE2, isDown, 0, NULL);
+ if (in_showevents->integer) {
+ Com_Printf("MOUSE3: %s\n", isDown ? "down" : "up");
+ }
+ }
+
+ if (buttonsDelta & 4) {
+ isDown = buttons & 4;
+ Sys_QueEvent(currentTime, SE_KEY, K_MOUSE3, isDown, 0, NULL);
+ if (in_showevents->integer) {
+ Com_Printf("MOUSE1: %s\n", isDown ? "down" : "up");
+ }
+ }
+
+ if (buttonsDelta & 8) {
+ isDown = buttons & 8;
+ Sys_QueEvent(currentTime, SE_KEY, K_MOUSE4, isDown, 0, NULL);
+ if (in_showevents->integer) {
+ Com_Printf("MOUSE4: %s\n", isDown ? "down" : "up");
+ }
+ }
+
+ if (buttonsDelta & 16) {
+ isDown = buttons & 16;
+ Sys_QueEvent(currentTime, SE_KEY, K_MOUSE5, isDown, 0, NULL);
+ if (in_showevents->integer) {
+ Com_Printf("MOUSE5: %s\n", isDown ? "down" : "up");
+ }
+ }
+
+ oldButtons = buttons;
+ }
+}
+
+static inline void processEvent(NSEvent *event, int currentTime)
+{
+ NSEventType eventType;
+
+ if (!inputActive)
+ return;
+
+ eventType = [event type];
+
+ if (in_showevents->integer)
+ NSLog(@"event = %@", event);
+
+ switch (eventType) {
+ // These six event types are ignored since we do all of our mouse down/up process via the uber-mouse system defined event. We have to accept these events however since they get enqueued and the queue will fill up if we don't.
+ case NSLeftMouseDown:
+ //Sys_QueEvent(currentTime, SE_KEY, K_MOUSE1, qtrue, 0, NULL);
+ return;
+ case NSLeftMouseUp:
+ //Sys_QueEvent(currentTime, SE_KEY, K_MOUSE1, qfalse, 0, NULL);
+ return;
+ case NSRightMouseDown:
+ //Sys_QueEvent(currentTime, SE_KEY, K_MOUSE2, qtrue, 0, NULL);
+ return;
+ case NSRightMouseUp:
+ //Sys_QueEvent(currentTime, SE_KEY, K_MOUSE2, qfalse, 0, NULL);
+ return;
+ case 25: // other mouse down
+ return;
+ case 26: // other mouse up
+ return;
+
+ case NSMouseMoved:
+ case NSLeftMouseDragged:
+ case NSRightMouseDragged:
+ case 27: // other mouse dragged
+ Sys_ProcessMouseMovedEvent(event, currentTime);
+ return;
+ case NSKeyDown:
+ case NSKeyUp:
+ processKeyEvent(event, eventType == NSKeyDown, currentTime);
+ return;
+ case NSFlagsChanged:
+ processFlagsChangedEvent(event, currentTime);
+ return;
+ case NSSystemDefined:
+ processSystemDefinedEvent(event, currentTime);
+ return;
+ case NSScrollWheel:
+ if ([event deltaY] < 0.0) {
+ Sys_QueEvent(currentTime, SE_KEY, K_MWHEELDOWN, qtrue, 0, NULL );
+ Sys_QueEvent(currentTime, SE_KEY, K_MWHEELDOWN, qfalse, 0, NULL );
+ } else {
+ Sys_QueEvent(currentTime, SE_KEY, K_MWHEELUP, qtrue, 0, NULL );
+ Sys_QueEvent(currentTime, SE_KEY, K_MWHEELUP, qfalse, 0, NULL );
+ }
+ return;
+ default:
+ break;
+ }
+ [NSApp sendEvent:event];
+}
+
+static void Sys_SendKeyEvents(int currentTime)
+{
+#ifndef DEDICATED
+ NSEvent *event;
+ NSDate *timeout;
+ extern float SNDDMA_GetBufferDuration();
+
+ timeout = distantPast;
+ if (Sys_IsHidden)
+ timeout = [NSDate dateWithTimeIntervalSinceNow: 0.25 * SNDDMA_GetBufferDuration()];
+
+ // This gets call regardless of whether inputActive is true or not. This is important since we need to be poking the event queue in order for the unhide event to make its way through the system. This means that when we hide, we can just shut down the input system and reeanbled it when we unhide.
+ while ((event = [NSApp nextEventMatchingMask: NSAnyEventMask
+ untilDate: timeout
+ inMode: NSDefaultRunLoopMode
+ dequeue:YES])) {
+ if (Sys_IsHidden) {
+ // Just let NSApp handle events so that we'll get the app activation event
+ [NSApp sendEvent: event];
+ timeout = [NSDate dateWithTimeIntervalSinceNow: 0.1];
+ } else {
+ static int lastEventTime = 0;
+ static BOOL lastEventTimeValid = NO;
+
+ // Mac OS X 10.0.3 has a bug where the if the monitor goes to sleep in fullscreen GL mode, the gamma won't be restored. We'll restore the gamma if there is a pause while in the game of more than 10 seconds. We don't do this on the 'Sys_IsHidden' branch since unhiding will restore the monitor gamma.
+ if ((currentTime - lastEventTime > 1 * 1000) && lastEventTimeValid) {
+ //Com_Printf("Restoring monitor gamma after being idle for %f seconds.\n", (currentTime - lastEventTime) / 1000.0);
+ [NSCursor hide];
+ Sys_SetScreenFade(&glw_state.inGameTable, 1.0);
+ }
+ lastEventTime = [event timestamp] * 1000.0; //currentTime;
+ lastEventTimeValid = YES;
+
+ processEvent(event, lastEventTime);
+ }
+ }
+#endif
+}
+
+/*
+========================================================================
+
+EVENT LOOP
+
+========================================================================
+*/
+
+extern qboolean Sys_GetPacket ( netadr_t *net_from, msg_t *net_message );
+
+#define MAX_QUED_EVENTS 256
+#define MASK_QUED_EVENTS ( MAX_QUED_EVENTS - 1 )
+
+static sysEvent_t eventQue[MAX_QUED_EVENTS];
+static int eventHead, eventTail;
+static byte sys_packetReceived[MAX_MSGLEN];
+
+/*
+================
+Sys_QueEvent
+
+A time of 0 will get the current time
+Ptr should either be null, or point to a block of data that can
+be freed by the game later.
+================
+*/
+void Sys_QueEvent( int time, sysEventType_t type, int value, int value2, int ptrLength, void *ptr ) {
+ sysEvent_t *ev;
+ int i,j;
+#ifndef DEDICATED
+ if (in_showevents->integer)
+ NSLog(@"EVENT ENQUEUE: time=%d type=%d value=0x%08x value2=0x%08x\n", time, type, value, value2);
+#endif
+
+ if ( eventHead - eventTail >= MAX_QUED_EVENTS ) {
+ Com_Printf("Sys_QueEvent: overflow\n");
+ }
+
+ if ( !time ) {
+ time = Sys_Milliseconds();
+ }
+
+ // insert it by time
+ for ( i = eventTail ; i < eventHead ; i++ ) {
+ ev = &eventQue[ i & MASK_QUED_EVENTS ];
+ if ( ev->evTime > time ) {
+ break;
+ }
+ }
+
+ // insert before i
+ for ( j = eventHead ; j > i ; j-- ) {
+ eventQue[ j & MASK_QUED_EVENTS ] = eventQue[ (j-1) & MASK_QUED_EVENTS ];
+ }
+ ev = &eventQue[ i & MASK_QUED_EVENTS ];
+
+ eventHead++;
+
+ ev->evTime = time;
+ ev->evType = type;
+ ev->evValue = value;
+ ev->evValue2 = value2;
+ ev->evPtrLength = ptrLength;
+ ev->evPtr = ptr;
+}
+
+/*
+================
+Sys_GetEvent
+
+================
+*/
+sysEvent_t Sys_GetEvent( void )
+{
+ sysEvent_t ev;
+ char *s;
+ msg_t netmsg;
+ netadr_t adr;
+ int currentTime;
+
+ // return if we have data
+ if (eventHead > eventTail) {
+ eventTail++;
+ return eventQue[ ( eventTail - 1 ) & MASK_QUED_EVENTS ];
+ }
+
+ // The queue must be empty. Check all of the event sources. If the events are
+ // already in the queue, we can't imply any real ordering, so we'll avoid extra
+ // system calls and give them all the same time.
+ currentTime = Sys_Milliseconds();
+
+ // Check for mouse and keyboard events
+ Sys_SendKeyEvents(currentTime);
+
+ // check for console commands
+ s = Sys_ConsoleInput();
+ if ( s ) {
+ char *b;
+ int len;
+
+ len = strlen( s ) + 1;
+ b = Z_Malloc( len );
+ strcpy( b, s );
+ Sys_QueEvent( currentTime, SE_CONSOLE, 0, 0, len, b );
+ }
+
+
+ // During debugging it is sometimes usefull to be able to start/stop mouse input.
+ // Don't turn on the input when we've disabled it because we're hidden, however.
+ if (!com_dedicated->integer) {
+ if (in_nomouse->integer == mouseactive && !Sys_IsHidden) {
+ if (in_nomouse->integer)
+ Sys_StopMouseInput();
+ else
+ Sys_StartMouseInput();
+ }
+ }
+
+ // check for network packets
+ MSG_Init( &netmsg, sys_packetReceived, sizeof( sys_packetReceived ) );
+ if ( Sys_GetPacket ( &adr, &netmsg ) ) {
+ netadr_t *buf;
+ int len;
+
+ // copy out to a seperate buffer for qeueing
+ len = sizeof( netadr_t ) + netmsg.cursize;
+ buf = Z_Malloc( len );
+ *buf = adr;
+ memcpy( buf+1, netmsg.data, netmsg.cursize );
+ Sys_QueEvent( currentTime, SE_PACKET, 0, 0, len, buf );
+ }
+
+ // If we got an event, return it
+ if (eventHead > eventTail) {
+ eventTail++;
+ return eventQue[ ( eventTail - 1 ) & MASK_QUED_EVENTS ];
+ }
+
+ // Otherwise, return an empty event to indicate that there are no events pending.
+ memset( &ev, 0, sizeof( ev ) );
+ ev.evTime = currentTime;
+
+ return ev;
+}
+
+
+
diff --git a/code/macosx/macosx_local.h b/code/macosx/macosx_local.h
new file mode 100755
index 0000000..c687c1a
--- /dev/null
+++ b/code/macosx/macosx_local.h
@@ -0,0 +1,129 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __macosx_local_h
+#define __macosx_local_h
+
+#include "qcommon.h"
+
+#ifdef __cplusplus
+typedef void NSDictionary;
+typedef void NSOpenGLContext;
+typedef void NSWindow;
+
+extern "C" {
+#else
+#import <Foundation/NSGeometry.h>
+@class NSEvent, NSOpenGLContext, NSWindow;
+#endif
+
+#include <ApplicationServices/ApplicationServices.h>
+#include <OpenGL/CGLTypes.h>
+
+// In macosx_input.m
+extern void Sys_InitInput(void);
+extern void Sys_ShutdownInput(void);
+extern void Sys_SetMouseInputRect(CGRect newRect);
+extern CGDirectDisplayID Sys_DisplayToUse(void);
+
+// In macosx_sys.m
+extern void Sys_QueEvent(int time, sysEventType_t type, int value, int value2, int ptrLength, void *ptr);
+extern void Sys_AnnoyingBanner();
+
+// In macosx_glimp.m
+extern qboolean Sys_IsHidden;
+extern qboolean Sys_Hide();
+extern qboolean Sys_Unhide();
+
+typedef struct {
+ CGDirectDisplayID display;
+ CGTableCount tableSize;
+ CGGammaValue *red;
+ CGGammaValue *blue;
+ CGGammaValue *green;
+} glwgamma_t;
+
+typedef struct
+{
+ CGDirectDisplayID display;
+ NSDictionary *desktopMode;
+ NSDictionary *gameMode;
+
+ CGDisplayCount displayCount;
+ glwgamma_t *originalDisplayGammaTables;
+ glwgamma_t inGameTable;
+ glwgamma_t tempTable;
+
+ NSOpenGLContext *_ctx;
+ CGLContextObj _cgl_ctx;
+ qboolean _ctx_is_current;
+ NSWindow *window;
+
+ FILE *log_fp;
+
+ unsigned int bufferSwapCount;
+ unsigned int glPauseCount;
+} glwstate_t;
+
+extern glwstate_t glw_state;
+
+#define OSX_SetGLContext(context) \
+do { \
+ NSOpenGLContext *_context = (context); \
+ glw_state._ctx = _context; \
+ glw_state._cgl_ctx = [_context cglContext]; \
+} while (0)
+
+#define OSX_GetNSGLContext() glw_state._ctx
+#define OSX_GetCGLContext() glw_state._cgl_ctx
+
+#define OSX_GLContextIsCurrent() glw_state._ctx_is_current
+#define OSX_GLContextSetCurrent() \
+do { \
+ [glw_state._ctx makeCurrentContext]; \
+ glw_state._ctx_is_current = (glw_state._ctx != nil); \
+} while (0)
+
+#define OSX_GLContextClearCurrent() \
+do { \
+ [NSOpenGLContext clearCurrentContext]; \
+ glw_state._ctx_is_current = NO; \
+} while (0)
+
+
+extern void Sys_PauseGL();
+extern void Sys_ResumeGL();
+
+
+#import "macosx_timers.h"
+
+#ifdef OMNI_TIMER
+extern OTStampList glThreadStampList;
+#define GLSTAMP(name, data) OTStampListAddStamp(glThreadStampList, name, data)
+#else
+#define GLSTAMP(name, data)
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // __macosx_local_h
diff --git a/code/macosx/macosx_qgl.h b/code/macosx/macosx_qgl.h
new file mode 100755
index 0000000..d11c971
--- /dev/null
+++ b/code/macosx/macosx_qgl.h
@@ -0,0 +1,5095 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+/**** This file is autogenerated. Run GenerateQGL.pl to update it ****/
+
+#ifdef QGL_LOG_GL_CALLS
+extern unsigned int QGLLogGLCalls;
+extern FILE *QGLDebugFile(void);
+#endif
+
+extern void QGLCheckError(const char *message);
+extern unsigned int QGLBeginStarted;
+
+// This has to be done to avoid infinite recursion between our glGetError wrapper and QGLCheckError()
+static inline GLenum _glGetError(void) {
+ return glGetError();
+}
+
+// void glAccum (GLenum op, GLfloat value);
+static inline void qglAccum(GLenum op, GLfloat value)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glAccum(op=%lu, value=%f)\n", op, value);
+#endif
+ glAccum(op, value);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glAccum");
+#endif
+}
+
+// void glAlphaFunc (GLenum func, GLclampf ref);
+static inline void qglAlphaFunc(GLenum func, GLclampf ref)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glAlphaFunc(func=%lu, ref=%f)\n", func, ref);
+#endif
+ glAlphaFunc(func, ref);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glAlphaFunc");
+#endif
+}
+
+// GLboolean glAreTexturesResident (GLsizei n, const GLuint *textures, GLboolean *residences);
+static inline GLboolean qglAreTexturesResident(GLsizei n, const GLuint *textures, GLboolean *residences)
+{
+ GLboolean returnValue;
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glAreTexturesResident(n=%ld, textures=%p, residences=%p)\n", n, textures, residences);
+#endif
+ returnValue = glAreTexturesResident(n, textures, residences);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glAreTexturesResident");
+#endif
+ return returnValue;
+}
+
+// void glArrayElement (GLint i);
+static inline void qglArrayElement(GLint i)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glArrayElement(i=%ld)\n", i);
+#endif
+ glArrayElement(i);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glArrayElement");
+#endif
+}
+
+// void glBegin (GLenum mode);
+static inline void qglBegin(GLenum mode)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glBegin(mode=%lu)\n", mode);
+#endif
+ glBegin(mode);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ QGLBeginStarted++;
+ if (!QGLBeginStarted)
+ QGLCheckError("glBegin");
+#endif
+}
+
+// void glBindTexture (GLenum target, GLuint texture);
+static inline void qglBindTexture(GLenum target, GLuint texture)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glBindTexture(target=%lu, texture=%lu)\n", target, texture);
+#endif
+ glBindTexture(target, texture);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glBindTexture");
+#endif
+}
+
+// void glBitmap (GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap);
+static inline void qglBitmap(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glBitmap(width=%ld, height=%ld, xorig=%f, yorig=%f, xmove=%f, ymove=%f, bitmap=%p)\n", width, height, xorig, yorig, xmove, ymove, bitmap);
+#endif
+ glBitmap(width, height, xorig, yorig, xmove, ymove, bitmap);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glBitmap");
+#endif
+}
+
+// void glBlendFunc (GLenum sfactor, GLenum dfactor);
+static inline void qglBlendFunc(GLenum sfactor, GLenum dfactor)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glBlendFunc(sfactor=%lu, dfactor=%lu)\n", sfactor, dfactor);
+#endif
+ glBlendFunc(sfactor, dfactor);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glBlendFunc");
+#endif
+}
+
+// void glCallList (GLuint list);
+static inline void qglCallList(GLuint list)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glCallList(list=%lu)\n", list);
+#endif
+ glCallList(list);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glCallList");
+#endif
+}
+
+// void glCallLists (GLsizei n, GLenum type, const GLvoid *lists);
+static inline void qglCallLists(GLsizei n, GLenum type, const GLvoid *lists)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glCallLists(n=%ld, type=%lu, lists=%p)\n", n, type, lists);
+#endif
+ glCallLists(n, type, lists);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glCallLists");
+#endif
+}
+
+// void glClear (GLbitfield mask);
+static inline void qglClear(GLbitfield mask)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glClear(mask=%lu)\n", mask);
+#endif
+ glClear(mask);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glClear");
+#endif
+}
+
+// void glClearAccum (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+static inline void qglClearAccum(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glClearAccum(red=%f, green=%f, blue=%f, alpha=%f)\n", red, green, blue, alpha);
+#endif
+ glClearAccum(red, green, blue, alpha);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glClearAccum");
+#endif
+}
+
+// void glClearColor (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+static inline void qglClearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glClearColor(red=%f, green=%f, blue=%f, alpha=%f)\n", red, green, blue, alpha);
+#endif
+ glClearColor(red, green, blue, alpha);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glClearColor");
+#endif
+}
+
+// void glClearDepth (GLclampd depth);
+static inline void qglClearDepth(GLclampd depth)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glClearDepth(depth=%f)\n", depth);
+#endif
+ glClearDepth(depth);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glClearDepth");
+#endif
+}
+
+// void glClearIndex (GLfloat c);
+static inline void qglClearIndex(GLfloat c)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glClearIndex(c=%f)\n", c);
+#endif
+ glClearIndex(c);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glClearIndex");
+#endif
+}
+
+// void glClearStencil (GLint s);
+static inline void qglClearStencil(GLint s)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glClearStencil(s=%ld)\n", s);
+#endif
+ glClearStencil(s);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glClearStencil");
+#endif
+}
+
+// void glClipPlane (GLenum plane, const GLdouble *equation);
+static inline void qglClipPlane(GLenum plane, const GLdouble *equation)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glClipPlane(plane=%lu, equation=%p)\n", plane, equation);
+#endif
+ glClipPlane(plane, equation);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glClipPlane");
+#endif
+}
+
+// void glColor3b (GLbyte red, GLbyte green, GLbyte blue);
+static inline void qglColor3b(GLbyte red, GLbyte green, GLbyte blue)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor3b(red=%d, green=%d, blue=%d)\n", red, green, blue);
+#endif
+ glColor3b(red, green, blue);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor3b");
+#endif
+}
+
+// void glColor3bv (const GLbyte *v);
+static inline void qglColor3bv(const GLbyte *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor3bv(v=%p)\n", v);
+#endif
+ glColor3bv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor3bv");
+#endif
+}
+
+// void glColor3d (GLdouble red, GLdouble green, GLdouble blue);
+static inline void qglColor3d(GLdouble red, GLdouble green, GLdouble blue)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor3d(red=%f, green=%f, blue=%f)\n", red, green, blue);
+#endif
+ glColor3d(red, green, blue);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor3d");
+#endif
+}
+
+// void glColor3dv (const GLdouble *v);
+static inline void qglColor3dv(const GLdouble *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor3dv(v=%p)\n", v);
+#endif
+ glColor3dv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor3dv");
+#endif
+}
+
+// void glColor3f (GLfloat red, GLfloat green, GLfloat blue);
+static inline void qglColor3f(GLfloat red, GLfloat green, GLfloat blue)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor3f(red=%f, green=%f, blue=%f)\n", red, green, blue);
+#endif
+ glColor3f(red, green, blue);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor3f");
+#endif
+}
+
+// void glColor3fv (const GLfloat *v);
+static inline void qglColor3fv(const GLfloat *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor3fv(v=%p)\n", v);
+#endif
+ glColor3fv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor3fv");
+#endif
+}
+
+// void glColor3i (GLint red, GLint green, GLint blue);
+static inline void qglColor3i(GLint red, GLint green, GLint blue)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor3i(red=%ld, green=%ld, blue=%ld)\n", red, green, blue);
+#endif
+ glColor3i(red, green, blue);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor3i");
+#endif
+}
+
+// void glColor3iv (const GLint *v);
+static inline void qglColor3iv(const GLint *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor3iv(v=%p)\n", v);
+#endif
+ glColor3iv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor3iv");
+#endif
+}
+
+// void glColor3s (GLshort red, GLshort green, GLshort blue);
+static inline void qglColor3s(GLshort red, GLshort green, GLshort blue)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor3s(red=%d, green=%d, blue=%d)\n", red, green, blue);
+#endif
+ glColor3s(red, green, blue);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor3s");
+#endif
+}
+
+// void glColor3sv (const GLshort *v);
+static inline void qglColor3sv(const GLshort *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor3sv(v=%p)\n", v);
+#endif
+ glColor3sv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor3sv");
+#endif
+}
+
+// void glColor3ub (GLubyte red, GLubyte green, GLubyte blue);
+static inline void qglColor3ub(GLubyte red, GLubyte green, GLubyte blue)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor3ub(red=%u, green=%u, blue=%u)\n", red, green, blue);
+#endif
+ glColor3ub(red, green, blue);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor3ub");
+#endif
+}
+
+// void glColor3ubv (const GLubyte *v);
+static inline void qglColor3ubv(const GLubyte *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor3ubv(v=%p)\n", v);
+#endif
+ glColor3ubv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor3ubv");
+#endif
+}
+
+// void glColor3ui (GLuint red, GLuint green, GLuint blue);
+static inline void qglColor3ui(GLuint red, GLuint green, GLuint blue)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor3ui(red=%lu, green=%lu, blue=%lu)\n", red, green, blue);
+#endif
+ glColor3ui(red, green, blue);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor3ui");
+#endif
+}
+
+// void glColor3uiv (const GLuint *v);
+static inline void qglColor3uiv(const GLuint *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor3uiv(v=%p)\n", v);
+#endif
+ glColor3uiv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor3uiv");
+#endif
+}
+
+// void glColor3us (GLushort red, GLushort green, GLushort blue);
+static inline void qglColor3us(GLushort red, GLushort green, GLushort blue)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor3us(red=%u, green=%u, blue=%u)\n", red, green, blue);
+#endif
+ glColor3us(red, green, blue);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor3us");
+#endif
+}
+
+// void glColor3usv (const GLushort *v);
+static inline void qglColor3usv(const GLushort *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor3usv(v=%p)\n", v);
+#endif
+ glColor3usv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor3usv");
+#endif
+}
+
+// void glColor4b (GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha);
+static inline void qglColor4b(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor4b(red=%d, green=%d, blue=%d, alpha=%d)\n", red, green, blue, alpha);
+#endif
+ glColor4b(red, green, blue, alpha);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor4b");
+#endif
+}
+
+// void glColor4bv (const GLbyte *v);
+static inline void qglColor4bv(const GLbyte *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor4bv(v=%p)\n", v);
+#endif
+ glColor4bv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor4bv");
+#endif
+}
+
+// void glColor4d (GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha);
+static inline void qglColor4d(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor4d(red=%f, green=%f, blue=%f, alpha=%f)\n", red, green, blue, alpha);
+#endif
+ glColor4d(red, green, blue, alpha);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor4d");
+#endif
+}
+
+// void glColor4dv (const GLdouble *v);
+static inline void qglColor4dv(const GLdouble *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor4dv(v=%p)\n", v);
+#endif
+ glColor4dv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor4dv");
+#endif
+}
+
+// void glColor4f (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+static inline void qglColor4f(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor4f(red=%f, green=%f, blue=%f, alpha=%f)\n", red, green, blue, alpha);
+#endif
+ glColor4f(red, green, blue, alpha);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor4f");
+#endif
+}
+
+// void glColor4fv (const GLfloat *v);
+static inline void qglColor4fv(const GLfloat *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor4fv(v=%p)\n", v);
+#endif
+ glColor4fv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor4fv");
+#endif
+}
+
+// void glColor4i (GLint red, GLint green, GLint blue, GLint alpha);
+static inline void qglColor4i(GLint red, GLint green, GLint blue, GLint alpha)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor4i(red=%ld, green=%ld, blue=%ld, alpha=%ld)\n", red, green, blue, alpha);
+#endif
+ glColor4i(red, green, blue, alpha);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor4i");
+#endif
+}
+
+// void glColor4iv (const GLint *v);
+static inline void qglColor4iv(const GLint *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor4iv(v=%p)\n", v);
+#endif
+ glColor4iv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor4iv");
+#endif
+}
+
+// void glColor4s (GLshort red, GLshort green, GLshort blue, GLshort alpha);
+static inline void qglColor4s(GLshort red, GLshort green, GLshort blue, GLshort alpha)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor4s(red=%d, green=%d, blue=%d, alpha=%d)\n", red, green, blue, alpha);
+#endif
+ glColor4s(red, green, blue, alpha);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor4s");
+#endif
+}
+
+// void glColor4sv (const GLshort *v);
+static inline void qglColor4sv(const GLshort *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor4sv(v=%p)\n", v);
+#endif
+ glColor4sv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor4sv");
+#endif
+}
+
+// void glColor4ub (GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha);
+static inline void qglColor4ub(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor4ub(red=%u, green=%u, blue=%u, alpha=%u)\n", red, green, blue, alpha);
+#endif
+ glColor4ub(red, green, blue, alpha);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor4ub");
+#endif
+}
+
+// void glColor4ubv (const GLubyte *v);
+static inline void qglColor4ubv(const GLubyte *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor4ubv(v=%p)\n", v);
+#endif
+ glColor4ubv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor4ubv");
+#endif
+}
+
+// void glColor4ui (GLuint red, GLuint green, GLuint blue, GLuint alpha);
+static inline void qglColor4ui(GLuint red, GLuint green, GLuint blue, GLuint alpha)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor4ui(red=%lu, green=%lu, blue=%lu, alpha=%lu)\n", red, green, blue, alpha);
+#endif
+ glColor4ui(red, green, blue, alpha);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor4ui");
+#endif
+}
+
+// void glColor4uiv (const GLuint *v);
+static inline void qglColor4uiv(const GLuint *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor4uiv(v=%p)\n", v);
+#endif
+ glColor4uiv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor4uiv");
+#endif
+}
+
+// void glColor4us (GLushort red, GLushort green, GLushort blue, GLushort alpha);
+static inline void qglColor4us(GLushort red, GLushort green, GLushort blue, GLushort alpha)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor4us(red=%u, green=%u, blue=%u, alpha=%u)\n", red, green, blue, alpha);
+#endif
+ glColor4us(red, green, blue, alpha);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor4us");
+#endif
+}
+
+// void glColor4usv (const GLushort *v);
+static inline void qglColor4usv(const GLushort *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColor4usv(v=%p)\n", v);
+#endif
+ glColor4usv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColor4usv");
+#endif
+}
+
+// void glColorMask (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
+static inline void qglColorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColorMask(red=%u, green=%u, blue=%u, alpha=%u)\n", red, green, blue, alpha);
+#endif
+ glColorMask(red, green, blue, alpha);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColorMask");
+#endif
+}
+
+// void glColorMaterial (GLenum face, GLenum mode);
+static inline void qglColorMaterial(GLenum face, GLenum mode)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColorMaterial(face=%lu, mode=%lu)\n", face, mode);
+#endif
+ glColorMaterial(face, mode);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColorMaterial");
+#endif
+}
+
+// void glColorPointer (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+static inline void qglColorPointer(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glColorPointer(size=%ld, type=%lu, stride=%ld, pointer=%p)\n", size, type, stride, pointer);
+#endif
+ glColorPointer(size, type, stride, pointer);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glColorPointer");
+#endif
+}
+
+// void glCopyPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum type);
+static inline void qglCopyPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glCopyPixels(x=%ld, y=%ld, width=%ld, height=%ld, type=%lu)\n", x, y, width, height, type);
+#endif
+ glCopyPixels(x, y, width, height, type);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glCopyPixels");
+#endif
+}
+
+// void glCopyTexImage1D (GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLint border);
+static inline void qglCopyTexImage1D(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLint border)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glCopyTexImage1D(target=%lu, level=%ld, internalFormat=%lu, x=%ld, y=%ld, width=%ld, border=%ld)\n", target, level, internalFormat, x, y, width, border);
+#endif
+ glCopyTexImage1D(target, level, internalFormat, x, y, width, border);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glCopyTexImage1D");
+#endif
+}
+
+// void glCopyTexImage2D (GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+static inline void qglCopyTexImage2D(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glCopyTexImage2D(target=%lu, level=%ld, internalFormat=%lu, x=%ld, y=%ld, width=%ld, height=%ld, border=%ld)\n", target, level, internalFormat, x, y, width, height, border);
+#endif
+ glCopyTexImage2D(target, level, internalFormat, x, y, width, height, border);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glCopyTexImage2D");
+#endif
+}
+
+// void glCopyTexSubImage1D (GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
+static inline void qglCopyTexSubImage1D(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glCopyTexSubImage1D(target=%lu, level=%ld, xoffset=%ld, x=%ld, y=%ld, width=%ld)\n", target, level, xoffset, x, y, width);
+#endif
+ glCopyTexSubImage1D(target, level, xoffset, x, y, width);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glCopyTexSubImage1D");
+#endif
+}
+
+// void glCopyTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+static inline void qglCopyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glCopyTexSubImage2D(target=%lu, level=%ld, xoffset=%ld, yoffset=%ld, x=%ld, y=%ld, width=%ld, height=%ld)\n", target, level, xoffset, yoffset, x, y, width, height);
+#endif
+ glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glCopyTexSubImage2D");
+#endif
+}
+
+// void glCullFace (GLenum mode);
+static inline void qglCullFace(GLenum mode)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glCullFace(mode=%lu)\n", mode);
+#endif
+ glCullFace(mode);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glCullFace");
+#endif
+}
+
+// void glDeleteLists (GLuint list, GLsizei range);
+static inline void qglDeleteLists(GLuint list, GLsizei range)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glDeleteLists(list=%lu, range=%ld)\n", list, range);
+#endif
+ glDeleteLists(list, range);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glDeleteLists");
+#endif
+}
+
+// void glDeleteTextures (GLsizei n, const GLuint *textures);
+static inline void qglDeleteTextures(GLsizei n, const GLuint *textures)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glDeleteTextures(n=%ld, textures=%p)\n", n, textures);
+#endif
+ glDeleteTextures(n, textures);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glDeleteTextures");
+#endif
+}
+
+// void glDepthFunc (GLenum func);
+static inline void qglDepthFunc(GLenum func)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glDepthFunc(func=%lu)\n", func);
+#endif
+ glDepthFunc(func);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glDepthFunc");
+#endif
+}
+
+// void glDepthMask (GLboolean flag);
+static inline void qglDepthMask(GLboolean flag)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glDepthMask(flag=%u)\n", flag);
+#endif
+ glDepthMask(flag);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glDepthMask");
+#endif
+}
+
+// void glDepthRange (GLclampd zNear, GLclampd zFar);
+static inline void qglDepthRange(GLclampd zNear, GLclampd zFar)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glDepthRange(zNear=%f, zFar=%f)\n", zNear, zFar);
+#endif
+ glDepthRange(zNear, zFar);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glDepthRange");
+#endif
+}
+
+// void glDisable (GLenum cap);
+static inline void qglDisable(GLenum cap)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glDisable(cap=%lu)\n", cap);
+#endif
+ glDisable(cap);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glDisable");
+#endif
+}
+
+// void glDisableClientState (GLenum array);
+static inline void qglDisableClientState(GLenum array)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glDisableClientState(array=%lu)\n", array);
+#endif
+ glDisableClientState(array);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glDisableClientState");
+#endif
+}
+
+// void glDrawArrays (GLenum mode, GLint first, GLsizei count);
+static inline void qglDrawArrays(GLenum mode, GLint first, GLsizei count)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glDrawArrays(mode=%lu, first=%ld, count=%ld)\n", mode, first, count);
+#endif
+ glDrawArrays(mode, first, count);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glDrawArrays");
+#endif
+}
+
+// void glDrawBuffer (GLenum mode);
+static inline void qglDrawBuffer(GLenum mode)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glDrawBuffer(mode=%lu)\n", mode);
+#endif
+ glDrawBuffer(mode);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glDrawBuffer");
+#endif
+}
+
+// void glDrawElements (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices);
+static inline void qglDrawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glDrawElements(mode=%lu, count=%ld, type=%lu, indices=%p)\n", mode, count, type, indices);
+#endif
+ glDrawElements(mode, count, type, indices);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glDrawElements");
+#endif
+}
+
+// void glDrawPixels (GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+static inline void qglDrawPixels(GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glDrawPixels(width=%ld, height=%ld, format=%lu, type=%lu, pixels=%p)\n", width, height, format, type, pixels);
+#endif
+ glDrawPixels(width, height, format, type, pixels);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glDrawPixels");
+#endif
+}
+
+// void glEdgeFlag (GLboolean flag);
+static inline void qglEdgeFlag(GLboolean flag)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glEdgeFlag(flag=%u)\n", flag);
+#endif
+ glEdgeFlag(flag);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glEdgeFlag");
+#endif
+}
+
+// void glEdgeFlagPointer (GLsizei stride, const GLvoid *pointer);
+static inline void qglEdgeFlagPointer(GLsizei stride, const GLvoid *pointer)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glEdgeFlagPointer(stride=%ld, pointer=%p)\n", stride, pointer);
+#endif
+ glEdgeFlagPointer(stride, pointer);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glEdgeFlagPointer");
+#endif
+}
+
+// void glEdgeFlagv (const GLboolean *flag);
+static inline void qglEdgeFlagv(const GLboolean *flag)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glEdgeFlagv(flag=%p)\n", flag);
+#endif
+ glEdgeFlagv(flag);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glEdgeFlagv");
+#endif
+}
+
+// void glEnable (GLenum cap);
+static inline void qglEnable(GLenum cap)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glEnable(cap=%lu)\n", cap);
+#endif
+ glEnable(cap);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glEnable");
+#endif
+}
+
+// void glEnableClientState (GLenum array);
+static inline void qglEnableClientState(GLenum array)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glEnableClientState(array=%lu)\n", array);
+#endif
+ glEnableClientState(array);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glEnableClientState");
+#endif
+}
+
+// void glEnd (void);
+static inline void qglEnd(void)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glEnd(void)\n");
+#endif
+ glEnd();
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ QGLBeginStarted--;
+ if (!QGLBeginStarted)
+ QGLCheckError("glEnd");
+#endif
+}
+
+// void glEndList (void);
+static inline void qglEndList(void)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glEndList(void)\n");
+#endif
+ glEndList();
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glEndList");
+#endif
+}
+
+// void glEvalCoord1d (GLdouble u);
+static inline void qglEvalCoord1d(GLdouble u)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glEvalCoord1d(u=%f)\n", u);
+#endif
+ glEvalCoord1d(u);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glEvalCoord1d");
+#endif
+}
+
+// void glEvalCoord1dv (const GLdouble *u);
+static inline void qglEvalCoord1dv(const GLdouble *u)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glEvalCoord1dv(u=%p)\n", u);
+#endif
+ glEvalCoord1dv(u);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glEvalCoord1dv");
+#endif
+}
+
+// void glEvalCoord1f (GLfloat u);
+static inline void qglEvalCoord1f(GLfloat u)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glEvalCoord1f(u=%f)\n", u);
+#endif
+ glEvalCoord1f(u);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glEvalCoord1f");
+#endif
+}
+
+// void glEvalCoord1fv (const GLfloat *u);
+static inline void qglEvalCoord1fv(const GLfloat *u)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glEvalCoord1fv(u=%p)\n", u);
+#endif
+ glEvalCoord1fv(u);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glEvalCoord1fv");
+#endif
+}
+
+// void glEvalCoord2d (GLdouble u, GLdouble v);
+static inline void qglEvalCoord2d(GLdouble u, GLdouble v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glEvalCoord2d(u=%f, v=%f)\n", u, v);
+#endif
+ glEvalCoord2d(u, v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glEvalCoord2d");
+#endif
+}
+
+// void glEvalCoord2dv (const GLdouble *u);
+static inline void qglEvalCoord2dv(const GLdouble *u)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glEvalCoord2dv(u=%p)\n", u);
+#endif
+ glEvalCoord2dv(u);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glEvalCoord2dv");
+#endif
+}
+
+// void glEvalCoord2f (GLfloat u, GLfloat v);
+static inline void qglEvalCoord2f(GLfloat u, GLfloat v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glEvalCoord2f(u=%f, v=%f)\n", u, v);
+#endif
+ glEvalCoord2f(u, v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glEvalCoord2f");
+#endif
+}
+
+// void glEvalCoord2fv (const GLfloat *u);
+static inline void qglEvalCoord2fv(const GLfloat *u)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glEvalCoord2fv(u=%p)\n", u);
+#endif
+ glEvalCoord2fv(u);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glEvalCoord2fv");
+#endif
+}
+
+// void glEvalMesh1 (GLenum mode, GLint i1, GLint i2);
+static inline void qglEvalMesh1(GLenum mode, GLint i1, GLint i2)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glEvalMesh1(mode=%lu, i1=%ld, i2=%ld)\n", mode, i1, i2);
+#endif
+ glEvalMesh1(mode, i1, i2);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glEvalMesh1");
+#endif
+}
+
+// void glEvalMesh2 (GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2);
+static inline void qglEvalMesh2(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glEvalMesh2(mode=%lu, i1=%ld, i2=%ld, j1=%ld, j2=%ld)\n", mode, i1, i2, j1, j2);
+#endif
+ glEvalMesh2(mode, i1, i2, j1, j2);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glEvalMesh2");
+#endif
+}
+
+// void glEvalPoint1 (GLint i);
+static inline void qglEvalPoint1(GLint i)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glEvalPoint1(i=%ld)\n", i);
+#endif
+ glEvalPoint1(i);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glEvalPoint1");
+#endif
+}
+
+// void glEvalPoint2 (GLint i, GLint j);
+static inline void qglEvalPoint2(GLint i, GLint j)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glEvalPoint2(i=%ld, j=%ld)\n", i, j);
+#endif
+ glEvalPoint2(i, j);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glEvalPoint2");
+#endif
+}
+
+// void glFeedbackBuffer (GLsizei size, GLenum type, GLfloat *buffer);
+static inline void qglFeedbackBuffer(GLsizei size, GLenum type, GLfloat *buffer)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glFeedbackBuffer(size=%ld, type=%lu, buffer=%p)\n", size, type, buffer);
+#endif
+ glFeedbackBuffer(size, type, buffer);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glFeedbackBuffer");
+#endif
+}
+
+// void glFinish (void);
+static inline void qglFinish(void)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glFinish(void)\n");
+#endif
+ glFinish();
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glFinish");
+#endif
+}
+
+// void glFlush (void);
+static inline void qglFlush(void)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glFlush(void)\n");
+#endif
+ glFlush();
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glFlush");
+#endif
+}
+
+// void glFogf (GLenum pname, GLfloat param);
+static inline void qglFogf(GLenum pname, GLfloat param)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glFogf(pname=%lu, param=%f)\n", pname, param);
+#endif
+ glFogf(pname, param);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glFogf");
+#endif
+}
+
+// void glFogfv (GLenum pname, const GLfloat *params);
+static inline void qglFogfv(GLenum pname, const GLfloat *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glFogfv(pname=%lu, params=%p)\n", pname, params);
+#endif
+ glFogfv(pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glFogfv");
+#endif
+}
+
+// void glFogi (GLenum pname, GLint param);
+static inline void qglFogi(GLenum pname, GLint param)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glFogi(pname=%lu, param=%ld)\n", pname, param);
+#endif
+ glFogi(pname, param);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glFogi");
+#endif
+}
+
+// void glFogiv (GLenum pname, const GLint *params);
+static inline void qglFogiv(GLenum pname, const GLint *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glFogiv(pname=%lu, params=%p)\n", pname, params);
+#endif
+ glFogiv(pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glFogiv");
+#endif
+}
+
+// void glFrontFace (GLenum mode);
+static inline void qglFrontFace(GLenum mode)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glFrontFace(mode=%lu)\n", mode);
+#endif
+ glFrontFace(mode);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glFrontFace");
+#endif
+}
+
+// void glFrustum (GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+static inline void qglFrustum(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glFrustum(left=%f, right=%f, bottom=%f, top=%f, zNear=%f, zFar=%f)\n", left, right, bottom, top, zNear, zFar);
+#endif
+ glFrustum(left, right, bottom, top, zNear, zFar);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glFrustum");
+#endif
+}
+
+// GLuint glGenLists (GLsizei range);
+static inline GLuint qglGenLists(GLsizei range)
+{
+ GLuint returnValue;
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGenLists(range=%ld)\n", range);
+#endif
+ returnValue = glGenLists(range);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGenLists");
+#endif
+ return returnValue;
+}
+
+// void glGenTextures (GLsizei n, GLuint *textures);
+static inline void qglGenTextures(GLsizei n, GLuint *textures)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGenTextures(n=%ld, textures=%p)\n", n, textures);
+#endif
+ glGenTextures(n, textures);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGenTextures");
+#endif
+}
+
+// void glGetBooleanv (GLenum pname, GLboolean *params);
+static inline void qglGetBooleanv(GLenum pname, GLboolean *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetBooleanv(pname=%lu, params=%p)\n", pname, params);
+#endif
+ glGetBooleanv(pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetBooleanv");
+#endif
+}
+
+// void glGetClipPlane (GLenum plane, GLdouble *equation);
+static inline void qglGetClipPlane(GLenum plane, GLdouble *equation)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetClipPlane(plane=%lu, equation=%p)\n", plane, equation);
+#endif
+ glGetClipPlane(plane, equation);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetClipPlane");
+#endif
+}
+
+// void glGetDoublev (GLenum pname, GLdouble *params);
+static inline void qglGetDoublev(GLenum pname, GLdouble *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetDoublev(pname=%lu, params=%p)\n", pname, params);
+#endif
+ glGetDoublev(pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetDoublev");
+#endif
+}
+
+// GLenum glGetError (void);
+static inline GLenum qglGetError(void)
+{
+ GLenum returnValue;
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetError(void)\n");
+#endif
+ returnValue = glGetError();
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetError");
+#endif
+ return returnValue;
+}
+
+// void glGetFloatv (GLenum pname, GLfloat *params);
+static inline void qglGetFloatv(GLenum pname, GLfloat *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetFloatv(pname=%lu, params=%p)\n", pname, params);
+#endif
+ glGetFloatv(pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetFloatv");
+#endif
+}
+
+// void glGetIntegerv (GLenum pname, GLint *params);
+static inline void qglGetIntegerv(GLenum pname, GLint *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetIntegerv(pname=%lu, params=%p)\n", pname, params);
+#endif
+ glGetIntegerv(pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetIntegerv");
+#endif
+}
+
+// void glGetLightfv (GLenum light, GLenum pname, GLfloat *params);
+static inline void qglGetLightfv(GLenum light, GLenum pname, GLfloat *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetLightfv(light=%lu, pname=%lu, params=%p)\n", light, pname, params);
+#endif
+ glGetLightfv(light, pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetLightfv");
+#endif
+}
+
+// void glGetLightiv (GLenum light, GLenum pname, GLint *params);
+static inline void qglGetLightiv(GLenum light, GLenum pname, GLint *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetLightiv(light=%lu, pname=%lu, params=%p)\n", light, pname, params);
+#endif
+ glGetLightiv(light, pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetLightiv");
+#endif
+}
+
+// void glGetMapdv (GLenum target, GLenum query, GLdouble *v);
+static inline void qglGetMapdv(GLenum target, GLenum query, GLdouble *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetMapdv(target=%lu, query=%lu, v=%p)\n", target, query, v);
+#endif
+ glGetMapdv(target, query, v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetMapdv");
+#endif
+}
+
+// void glGetMapfv (GLenum target, GLenum query, GLfloat *v);
+static inline void qglGetMapfv(GLenum target, GLenum query, GLfloat *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetMapfv(target=%lu, query=%lu, v=%p)\n", target, query, v);
+#endif
+ glGetMapfv(target, query, v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetMapfv");
+#endif
+}
+
+// void glGetMapiv (GLenum target, GLenum query, GLint *v);
+static inline void qglGetMapiv(GLenum target, GLenum query, GLint *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetMapiv(target=%lu, query=%lu, v=%p)\n", target, query, v);
+#endif
+ glGetMapiv(target, query, v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetMapiv");
+#endif
+}
+
+// void glGetMaterialfv (GLenum face, GLenum pname, GLfloat *params);
+static inline void qglGetMaterialfv(GLenum face, GLenum pname, GLfloat *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetMaterialfv(face=%lu, pname=%lu, params=%p)\n", face, pname, params);
+#endif
+ glGetMaterialfv(face, pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetMaterialfv");
+#endif
+}
+
+// void glGetMaterialiv (GLenum face, GLenum pname, GLint *params);
+static inline void qglGetMaterialiv(GLenum face, GLenum pname, GLint *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetMaterialiv(face=%lu, pname=%lu, params=%p)\n", face, pname, params);
+#endif
+ glGetMaterialiv(face, pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetMaterialiv");
+#endif
+}
+
+// void glGetPixelMapfv (GLenum map, GLfloat *values);
+static inline void qglGetPixelMapfv(GLenum map, GLfloat *values)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetPixelMapfv(map=%lu, values=%p)\n", map, values);
+#endif
+ glGetPixelMapfv(map, values);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetPixelMapfv");
+#endif
+}
+
+// void glGetPixelMapuiv (GLenum map, GLuint *values);
+static inline void qglGetPixelMapuiv(GLenum map, GLuint *values)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetPixelMapuiv(map=%lu, values=%p)\n", map, values);
+#endif
+ glGetPixelMapuiv(map, values);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetPixelMapuiv");
+#endif
+}
+
+// void glGetPixelMapusv (GLenum map, GLushort *values);
+static inline void qglGetPixelMapusv(GLenum map, GLushort *values)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetPixelMapusv(map=%lu, values=%p)\n", map, values);
+#endif
+ glGetPixelMapusv(map, values);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetPixelMapusv");
+#endif
+}
+
+// void glGetPointerv (GLenum pname, GLvoid* *params);
+static inline void qglGetPointerv(GLenum pname, GLvoid* *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetPointerv(pname=%lu, params=%p)\n", pname, params);
+#endif
+ glGetPointerv(pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetPointerv");
+#endif
+}
+
+// void glGetPolygonStipple (GLubyte *mask);
+static inline void qglGetPolygonStipple(GLubyte *mask)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetPolygonStipple(mask=%p)\n", mask);
+#endif
+ glGetPolygonStipple(mask);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetPolygonStipple");
+#endif
+}
+
+// const GLubyte * glGetString (GLenum name);
+static inline const GLubyte * qglGetString(GLenum name)
+{
+ const GLubyte * returnValue;
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetString(name=%lu)\n", name);
+#endif
+ returnValue = glGetString(name);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetString");
+#endif
+ return returnValue;
+}
+
+// void glGetTexEnvfv (GLenum target, GLenum pname, GLfloat *params);
+static inline void qglGetTexEnvfv(GLenum target, GLenum pname, GLfloat *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetTexEnvfv(target=%lu, pname=%lu, params=%p)\n", target, pname, params);
+#endif
+ glGetTexEnvfv(target, pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetTexEnvfv");
+#endif
+}
+
+// void glGetTexEnviv (GLenum target, GLenum pname, GLint *params);
+static inline void qglGetTexEnviv(GLenum target, GLenum pname, GLint *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetTexEnviv(target=%lu, pname=%lu, params=%p)\n", target, pname, params);
+#endif
+ glGetTexEnviv(target, pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetTexEnviv");
+#endif
+}
+
+// void glGetTexGendv (GLenum coord, GLenum pname, GLdouble *params);
+static inline void qglGetTexGendv(GLenum coord, GLenum pname, GLdouble *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetTexGendv(coord=%lu, pname=%lu, params=%p)\n", coord, pname, params);
+#endif
+ glGetTexGendv(coord, pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetTexGendv");
+#endif
+}
+
+// void glGetTexGenfv (GLenum coord, GLenum pname, GLfloat *params);
+static inline void qglGetTexGenfv(GLenum coord, GLenum pname, GLfloat *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetTexGenfv(coord=%lu, pname=%lu, params=%p)\n", coord, pname, params);
+#endif
+ glGetTexGenfv(coord, pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetTexGenfv");
+#endif
+}
+
+// void glGetTexGeniv (GLenum coord, GLenum pname, GLint *params);
+static inline void qglGetTexGeniv(GLenum coord, GLenum pname, GLint *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetTexGeniv(coord=%lu, pname=%lu, params=%p)\n", coord, pname, params);
+#endif
+ glGetTexGeniv(coord, pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetTexGeniv");
+#endif
+}
+
+// void glGetTexImage (GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels);
+static inline void qglGetTexImage(GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetTexImage(target=%lu, level=%ld, format=%lu, type=%lu, pixels=%p)\n", target, level, format, type, pixels);
+#endif
+ glGetTexImage(target, level, format, type, pixels);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetTexImage");
+#endif
+}
+
+// void glGetTexLevelParameterfv (GLenum target, GLint level, GLenum pname, GLfloat *params);
+static inline void qglGetTexLevelParameterfv(GLenum target, GLint level, GLenum pname, GLfloat *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetTexLevelParameterfv(target=%lu, level=%ld, pname=%lu, params=%p)\n", target, level, pname, params);
+#endif
+ glGetTexLevelParameterfv(target, level, pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetTexLevelParameterfv");
+#endif
+}
+
+// void glGetTexLevelParameteriv (GLenum target, GLint level, GLenum pname, GLint *params);
+static inline void qglGetTexLevelParameteriv(GLenum target, GLint level, GLenum pname, GLint *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetTexLevelParameteriv(target=%lu, level=%ld, pname=%lu, params=%p)\n", target, level, pname, params);
+#endif
+ glGetTexLevelParameteriv(target, level, pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetTexLevelParameteriv");
+#endif
+}
+
+// void glGetTexParameterfv (GLenum target, GLenum pname, GLfloat *params);
+static inline void qglGetTexParameterfv(GLenum target, GLenum pname, GLfloat *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetTexParameterfv(target=%lu, pname=%lu, params=%p)\n", target, pname, params);
+#endif
+ glGetTexParameterfv(target, pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetTexParameterfv");
+#endif
+}
+
+// void glGetTexParameteriv (GLenum target, GLenum pname, GLint *params);
+static inline void qglGetTexParameteriv(GLenum target, GLenum pname, GLint *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glGetTexParameteriv(target=%lu, pname=%lu, params=%p)\n", target, pname, params);
+#endif
+ glGetTexParameteriv(target, pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glGetTexParameteriv");
+#endif
+}
+
+// void glHint (GLenum target, GLenum mode);
+static inline void qglHint(GLenum target, GLenum mode)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glHint(target=%lu, mode=%lu)\n", target, mode);
+#endif
+ glHint(target, mode);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glHint");
+#endif
+}
+
+// void glIndexMask (GLuint mask);
+static inline void qglIndexMask(GLuint mask)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glIndexMask(mask=%lu)\n", mask);
+#endif
+ glIndexMask(mask);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glIndexMask");
+#endif
+}
+
+// void glIndexPointer (GLenum type, GLsizei stride, const GLvoid *pointer);
+static inline void qglIndexPointer(GLenum type, GLsizei stride, const GLvoid *pointer)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glIndexPointer(type=%lu, stride=%ld, pointer=%p)\n", type, stride, pointer);
+#endif
+ glIndexPointer(type, stride, pointer);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glIndexPointer");
+#endif
+}
+
+// void glIndexd (GLdouble c);
+static inline void qglIndexd(GLdouble c)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glIndexd(c=%f)\n", c);
+#endif
+ glIndexd(c);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glIndexd");
+#endif
+}
+
+// void glIndexdv (const GLdouble *c);
+static inline void qglIndexdv(const GLdouble *c)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glIndexdv(c=%p)\n", c);
+#endif
+ glIndexdv(c);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glIndexdv");
+#endif
+}
+
+// void glIndexf (GLfloat c);
+static inline void qglIndexf(GLfloat c)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glIndexf(c=%f)\n", c);
+#endif
+ glIndexf(c);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glIndexf");
+#endif
+}
+
+// void glIndexfv (const GLfloat *c);
+static inline void qglIndexfv(const GLfloat *c)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glIndexfv(c=%p)\n", c);
+#endif
+ glIndexfv(c);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glIndexfv");
+#endif
+}
+
+// void glIndexi (GLint c);
+static inline void qglIndexi(GLint c)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glIndexi(c=%ld)\n", c);
+#endif
+ glIndexi(c);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glIndexi");
+#endif
+}
+
+// void glIndexiv (const GLint *c);
+static inline void qglIndexiv(const GLint *c)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glIndexiv(c=%p)\n", c);
+#endif
+ glIndexiv(c);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glIndexiv");
+#endif
+}
+
+// void glIndexs (GLshort c);
+static inline void qglIndexs(GLshort c)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glIndexs(c=%d)\n", c);
+#endif
+ glIndexs(c);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glIndexs");
+#endif
+}
+
+// void glIndexsv (const GLshort *c);
+static inline void qglIndexsv(const GLshort *c)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glIndexsv(c=%p)\n", c);
+#endif
+ glIndexsv(c);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glIndexsv");
+#endif
+}
+
+// void glIndexub (GLubyte c);
+static inline void qglIndexub(GLubyte c)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glIndexub(c=%u)\n", c);
+#endif
+ glIndexub(c);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glIndexub");
+#endif
+}
+
+// void glIndexubv (const GLubyte *c);
+static inline void qglIndexubv(const GLubyte *c)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glIndexubv(c=%p)\n", c);
+#endif
+ glIndexubv(c);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glIndexubv");
+#endif
+}
+
+// void glInitNames (void);
+static inline void qglInitNames(void)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glInitNames(void)\n");
+#endif
+ glInitNames();
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glInitNames");
+#endif
+}
+
+// void glInterleavedArrays (GLenum format, GLsizei stride, const GLvoid *pointer);
+static inline void qglInterleavedArrays(GLenum format, GLsizei stride, const GLvoid *pointer)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glInterleavedArrays(format=%lu, stride=%ld, pointer=%p)\n", format, stride, pointer);
+#endif
+ glInterleavedArrays(format, stride, pointer);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glInterleavedArrays");
+#endif
+}
+
+// GLboolean glIsEnabled (GLenum cap);
+static inline GLboolean qglIsEnabled(GLenum cap)
+{
+ GLboolean returnValue;
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glIsEnabled(cap=%lu)\n", cap);
+#endif
+ returnValue = glIsEnabled(cap);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glIsEnabled");
+#endif
+ return returnValue;
+}
+
+// GLboolean glIsList (GLuint list);
+static inline GLboolean qglIsList(GLuint list)
+{
+ GLboolean returnValue;
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glIsList(list=%lu)\n", list);
+#endif
+ returnValue = glIsList(list);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glIsList");
+#endif
+ return returnValue;
+}
+
+// GLboolean glIsTexture (GLuint texture);
+static inline GLboolean qglIsTexture(GLuint texture)
+{
+ GLboolean returnValue;
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glIsTexture(texture=%lu)\n", texture);
+#endif
+ returnValue = glIsTexture(texture);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glIsTexture");
+#endif
+ return returnValue;
+}
+
+// void glLightModelf (GLenum pname, GLfloat param);
+static inline void qglLightModelf(GLenum pname, GLfloat param)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glLightModelf(pname=%lu, param=%f)\n", pname, param);
+#endif
+ glLightModelf(pname, param);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glLightModelf");
+#endif
+}
+
+// void glLightModelfv (GLenum pname, const GLfloat *params);
+static inline void qglLightModelfv(GLenum pname, const GLfloat *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glLightModelfv(pname=%lu, params=%p)\n", pname, params);
+#endif
+ glLightModelfv(pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glLightModelfv");
+#endif
+}
+
+// void glLightModeli (GLenum pname, GLint param);
+static inline void qglLightModeli(GLenum pname, GLint param)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glLightModeli(pname=%lu, param=%ld)\n", pname, param);
+#endif
+ glLightModeli(pname, param);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glLightModeli");
+#endif
+}
+
+// void glLightModeliv (GLenum pname, const GLint *params);
+static inline void qglLightModeliv(GLenum pname, const GLint *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glLightModeliv(pname=%lu, params=%p)\n", pname, params);
+#endif
+ glLightModeliv(pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glLightModeliv");
+#endif
+}
+
+// void glLightf (GLenum light, GLenum pname, GLfloat param);
+static inline void qglLightf(GLenum light, GLenum pname, GLfloat param)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glLightf(light=%lu, pname=%lu, param=%f)\n", light, pname, param);
+#endif
+ glLightf(light, pname, param);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glLightf");
+#endif
+}
+
+// void glLightfv (GLenum light, GLenum pname, const GLfloat *params);
+static inline void qglLightfv(GLenum light, GLenum pname, const GLfloat *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glLightfv(light=%lu, pname=%lu, params=%p)\n", light, pname, params);
+#endif
+ glLightfv(light, pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glLightfv");
+#endif
+}
+
+// void glLighti (GLenum light, GLenum pname, GLint param);
+static inline void qglLighti(GLenum light, GLenum pname, GLint param)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glLighti(light=%lu, pname=%lu, param=%ld)\n", light, pname, param);
+#endif
+ glLighti(light, pname, param);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glLighti");
+#endif
+}
+
+// void glLightiv (GLenum light, GLenum pname, const GLint *params);
+static inline void qglLightiv(GLenum light, GLenum pname, const GLint *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glLightiv(light=%lu, pname=%lu, params=%p)\n", light, pname, params);
+#endif
+ glLightiv(light, pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glLightiv");
+#endif
+}
+
+// void glLineStipple (GLint factor, GLushort pattern);
+static inline void qglLineStipple(GLint factor, GLushort pattern)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glLineStipple(factor=%ld, pattern=%u)\n", factor, pattern);
+#endif
+ glLineStipple(factor, pattern);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glLineStipple");
+#endif
+}
+
+// void glLineWidth (GLfloat width);
+static inline void qglLineWidth(GLfloat width)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glLineWidth(width=%f)\n", width);
+#endif
+ glLineWidth(width);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glLineWidth");
+#endif
+}
+
+// void glListBase (GLuint base);
+static inline void qglListBase(GLuint base)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glListBase(base=%lu)\n", base);
+#endif
+ glListBase(base);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glListBase");
+#endif
+}
+
+// void glLoadIdentity (void);
+static inline void qglLoadIdentity(void)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glLoadIdentity(void)\n");
+#endif
+ glLoadIdentity();
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glLoadIdentity");
+#endif
+}
+
+// void glLoadMatrixd (const GLdouble *m);
+static inline void qglLoadMatrixd(const GLdouble *m)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glLoadMatrixd(m=%p)\n", m);
+#endif
+ glLoadMatrixd(m);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glLoadMatrixd");
+#endif
+}
+
+// void glLoadMatrixf (const GLfloat *m);
+static inline void qglLoadMatrixf(const GLfloat *m)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glLoadMatrixf(m=%p)\n", m);
+#endif
+ glLoadMatrixf(m);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glLoadMatrixf");
+#endif
+}
+
+// void glLoadName (GLuint name);
+static inline void qglLoadName(GLuint name)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glLoadName(name=%lu)\n", name);
+#endif
+ glLoadName(name);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glLoadName");
+#endif
+}
+
+// void glLogicOp (GLenum opcode);
+static inline void qglLogicOp(GLenum opcode)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glLogicOp(opcode=%lu)\n", opcode);
+#endif
+ glLogicOp(opcode);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glLogicOp");
+#endif
+}
+
+// void glMap1d (GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points);
+static inline void qglMap1d(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glMap1d(target=%lu, u1=%f, u2=%f, stride=%ld, order=%ld, points=%p)\n", target, u1, u2, stride, order, points);
+#endif
+ glMap1d(target, u1, u2, stride, order, points);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glMap1d");
+#endif
+}
+
+// void glMap1f (GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points);
+static inline void qglMap1f(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glMap1f(target=%lu, u1=%f, u2=%f, stride=%ld, order=%ld, points=%p)\n", target, u1, u2, stride, order, points);
+#endif
+ glMap1f(target, u1, u2, stride, order, points);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glMap1f");
+#endif
+}
+
+// void glMap2d (GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points);
+static inline void qglMap2d(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glMap2d(target=%lu, u1=%f, u2=%f, ustride=%ld, uorder=%ld, v1=%f, v2=%f, vstride=%ld, vorder=%ld, points=%p)\n", target, u1, u2, ustride, uorder, v1, v2, vstride, vorder, points);
+#endif
+ glMap2d(target, u1, u2, ustride, uorder, v1, v2, vstride, vorder, points);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glMap2d");
+#endif
+}
+
+// void glMap2f (GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points);
+static inline void qglMap2f(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glMap2f(target=%lu, u1=%f, u2=%f, ustride=%ld, uorder=%ld, v1=%f, v2=%f, vstride=%ld, vorder=%ld, points=%p)\n", target, u1, u2, ustride, uorder, v1, v2, vstride, vorder, points);
+#endif
+ glMap2f(target, u1, u2, ustride, uorder, v1, v2, vstride, vorder, points);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glMap2f");
+#endif
+}
+
+// void glMapGrid1d (GLint un, GLdouble u1, GLdouble u2);
+static inline void qglMapGrid1d(GLint un, GLdouble u1, GLdouble u2)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glMapGrid1d(un=%ld, u1=%f, u2=%f)\n", un, u1, u2);
+#endif
+ glMapGrid1d(un, u1, u2);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glMapGrid1d");
+#endif
+}
+
+// void glMapGrid1f (GLint un, GLfloat u1, GLfloat u2);
+static inline void qglMapGrid1f(GLint un, GLfloat u1, GLfloat u2)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glMapGrid1f(un=%ld, u1=%f, u2=%f)\n", un, u1, u2);
+#endif
+ glMapGrid1f(un, u1, u2);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glMapGrid1f");
+#endif
+}
+
+// void glMapGrid2d (GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2);
+static inline void qglMapGrid2d(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glMapGrid2d(un=%ld, u1=%f, u2=%f, vn=%ld, v1=%f, v2=%f)\n", un, u1, u2, vn, v1, v2);
+#endif
+ glMapGrid2d(un, u1, u2, vn, v1, v2);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glMapGrid2d");
+#endif
+}
+
+// void glMapGrid2f (GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2);
+static inline void qglMapGrid2f(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glMapGrid2f(un=%ld, u1=%f, u2=%f, vn=%ld, v1=%f, v2=%f)\n", un, u1, u2, vn, v1, v2);
+#endif
+ glMapGrid2f(un, u1, u2, vn, v1, v2);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glMapGrid2f");
+#endif
+}
+
+// void glMaterialf (GLenum face, GLenum pname, GLfloat param);
+static inline void qglMaterialf(GLenum face, GLenum pname, GLfloat param)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glMaterialf(face=%lu, pname=%lu, param=%f)\n", face, pname, param);
+#endif
+ glMaterialf(face, pname, param);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glMaterialf");
+#endif
+}
+
+// void glMaterialfv (GLenum face, GLenum pname, const GLfloat *params);
+static inline void qglMaterialfv(GLenum face, GLenum pname, const GLfloat *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glMaterialfv(face=%lu, pname=%lu, params=%p)\n", face, pname, params);
+#endif
+ glMaterialfv(face, pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glMaterialfv");
+#endif
+}
+
+// void glMateriali (GLenum face, GLenum pname, GLint param);
+static inline void qglMateriali(GLenum face, GLenum pname, GLint param)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glMateriali(face=%lu, pname=%lu, param=%ld)\n", face, pname, param);
+#endif
+ glMateriali(face, pname, param);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glMateriali");
+#endif
+}
+
+// void glMaterialiv (GLenum face, GLenum pname, const GLint *params);
+static inline void qglMaterialiv(GLenum face, GLenum pname, const GLint *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glMaterialiv(face=%lu, pname=%lu, params=%p)\n", face, pname, params);
+#endif
+ glMaterialiv(face, pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glMaterialiv");
+#endif
+}
+
+// void glMatrixMode (GLenum mode);
+static inline void qglMatrixMode(GLenum mode)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glMatrixMode(mode=%lu)\n", mode);
+#endif
+ glMatrixMode(mode);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glMatrixMode");
+#endif
+}
+
+// void glMultMatrixd (const GLdouble *m);
+static inline void qglMultMatrixd(const GLdouble *m)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glMultMatrixd(m=%p)\n", m);
+#endif
+ glMultMatrixd(m);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glMultMatrixd");
+#endif
+}
+
+// void glMultMatrixf (const GLfloat *m);
+static inline void qglMultMatrixf(const GLfloat *m)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glMultMatrixf(m=%p)\n", m);
+#endif
+ glMultMatrixf(m);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glMultMatrixf");
+#endif
+}
+
+// void glNewList (GLuint list, GLenum mode);
+static inline void qglNewList(GLuint list, GLenum mode)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glNewList(list=%lu, mode=%lu)\n", list, mode);
+#endif
+ glNewList(list, mode);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glNewList");
+#endif
+}
+
+// void glNormal3b (GLbyte nx, GLbyte ny, GLbyte nz);
+static inline void qglNormal3b(GLbyte nx, GLbyte ny, GLbyte nz)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glNormal3b(nx=%d, ny=%d, nz=%d)\n", nx, ny, nz);
+#endif
+ glNormal3b(nx, ny, nz);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glNormal3b");
+#endif
+}
+
+// void glNormal3bv (const GLbyte *v);
+static inline void qglNormal3bv(const GLbyte *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glNormal3bv(v=%p)\n", v);
+#endif
+ glNormal3bv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glNormal3bv");
+#endif
+}
+
+// void glNormal3d (GLdouble nx, GLdouble ny, GLdouble nz);
+static inline void qglNormal3d(GLdouble nx, GLdouble ny, GLdouble nz)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glNormal3d(nx=%f, ny=%f, nz=%f)\n", nx, ny, nz);
+#endif
+ glNormal3d(nx, ny, nz);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glNormal3d");
+#endif
+}
+
+// void glNormal3dv (const GLdouble *v);
+static inline void qglNormal3dv(const GLdouble *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glNormal3dv(v=%p)\n", v);
+#endif
+ glNormal3dv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glNormal3dv");
+#endif
+}
+
+// void glNormal3f (GLfloat nx, GLfloat ny, GLfloat nz);
+static inline void qglNormal3f(GLfloat nx, GLfloat ny, GLfloat nz)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glNormal3f(nx=%f, ny=%f, nz=%f)\n", nx, ny, nz);
+#endif
+ glNormal3f(nx, ny, nz);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glNormal3f");
+#endif
+}
+
+// void glNormal3fv (const GLfloat *v);
+static inline void qglNormal3fv(const GLfloat *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glNormal3fv(v=%p)\n", v);
+#endif
+ glNormal3fv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glNormal3fv");
+#endif
+}
+
+// void glNormal3i (GLint nx, GLint ny, GLint nz);
+static inline void qglNormal3i(GLint nx, GLint ny, GLint nz)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glNormal3i(nx=%ld, ny=%ld, nz=%ld)\n", nx, ny, nz);
+#endif
+ glNormal3i(nx, ny, nz);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glNormal3i");
+#endif
+}
+
+// void glNormal3iv (const GLint *v);
+static inline void qglNormal3iv(const GLint *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glNormal3iv(v=%p)\n", v);
+#endif
+ glNormal3iv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glNormal3iv");
+#endif
+}
+
+// void glNormal3s (GLshort nx, GLshort ny, GLshort nz);
+static inline void qglNormal3s(GLshort nx, GLshort ny, GLshort nz)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glNormal3s(nx=%d, ny=%d, nz=%d)\n", nx, ny, nz);
+#endif
+ glNormal3s(nx, ny, nz);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glNormal3s");
+#endif
+}
+
+// void glNormal3sv (const GLshort *v);
+static inline void qglNormal3sv(const GLshort *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glNormal3sv(v=%p)\n", v);
+#endif
+ glNormal3sv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glNormal3sv");
+#endif
+}
+
+// void glNormalPointer (GLenum type, GLsizei stride, const GLvoid *pointer);
+static inline void qglNormalPointer(GLenum type, GLsizei stride, const GLvoid *pointer)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glNormalPointer(type=%lu, stride=%ld, pointer=%p)\n", type, stride, pointer);
+#endif
+ glNormalPointer(type, stride, pointer);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glNormalPointer");
+#endif
+}
+
+// void glOrtho (GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+static inline void qglOrtho(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glOrtho(left=%f, right=%f, bottom=%f, top=%f, zNear=%f, zFar=%f)\n", left, right, bottom, top, zNear, zFar);
+#endif
+ glOrtho(left, right, bottom, top, zNear, zFar);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glOrtho");
+#endif
+}
+
+// void glPassThrough (GLfloat token);
+static inline void qglPassThrough(GLfloat token)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glPassThrough(token=%f)\n", token);
+#endif
+ glPassThrough(token);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glPassThrough");
+#endif
+}
+
+// void glPixelMapfv (GLenum map, GLsizei mapsize, const GLfloat *values);
+static inline void qglPixelMapfv(GLenum map, GLsizei mapsize, const GLfloat *values)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glPixelMapfv(map=%lu, mapsize=%ld, values=%p)\n", map, mapsize, values);
+#endif
+ glPixelMapfv(map, mapsize, values);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glPixelMapfv");
+#endif
+}
+
+// void glPixelMapuiv (GLenum map, GLsizei mapsize, const GLuint *values);
+static inline void qglPixelMapuiv(GLenum map, GLsizei mapsize, const GLuint *values)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glPixelMapuiv(map=%lu, mapsize=%ld, values=%p)\n", map, mapsize, values);
+#endif
+ glPixelMapuiv(map, mapsize, values);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glPixelMapuiv");
+#endif
+}
+
+// void glPixelMapusv (GLenum map, GLsizei mapsize, const GLushort *values);
+static inline void qglPixelMapusv(GLenum map, GLsizei mapsize, const GLushort *values)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glPixelMapusv(map=%lu, mapsize=%ld, values=%p)\n", map, mapsize, values);
+#endif
+ glPixelMapusv(map, mapsize, values);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glPixelMapusv");
+#endif
+}
+
+// void glPixelStoref (GLenum pname, GLfloat param);
+static inline void qglPixelStoref(GLenum pname, GLfloat param)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glPixelStoref(pname=%lu, param=%f)\n", pname, param);
+#endif
+ glPixelStoref(pname, param);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glPixelStoref");
+#endif
+}
+
+// void glPixelStorei (GLenum pname, GLint param);
+static inline void qglPixelStorei(GLenum pname, GLint param)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glPixelStorei(pname=%lu, param=%ld)\n", pname, param);
+#endif
+ glPixelStorei(pname, param);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glPixelStorei");
+#endif
+}
+
+// void glPixelTransferf (GLenum pname, GLfloat param);
+static inline void qglPixelTransferf(GLenum pname, GLfloat param)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glPixelTransferf(pname=%lu, param=%f)\n", pname, param);
+#endif
+ glPixelTransferf(pname, param);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glPixelTransferf");
+#endif
+}
+
+// void glPixelTransferi (GLenum pname, GLint param);
+static inline void qglPixelTransferi(GLenum pname, GLint param)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glPixelTransferi(pname=%lu, param=%ld)\n", pname, param);
+#endif
+ glPixelTransferi(pname, param);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glPixelTransferi");
+#endif
+}
+
+// void glPixelZoom (GLfloat xfactor, GLfloat yfactor);
+static inline void qglPixelZoom(GLfloat xfactor, GLfloat yfactor)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glPixelZoom(xfactor=%f, yfactor=%f)\n", xfactor, yfactor);
+#endif
+ glPixelZoom(xfactor, yfactor);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glPixelZoom");
+#endif
+}
+
+// void glPointSize (GLfloat size);
+static inline void qglPointSize(GLfloat size)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glPointSize(size=%f)\n", size);
+#endif
+ glPointSize(size);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glPointSize");
+#endif
+}
+
+// void glPolygonMode (GLenum face, GLenum mode);
+static inline void qglPolygonMode(GLenum face, GLenum mode)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glPolygonMode(face=%lu, mode=%lu)\n", face, mode);
+#endif
+ glPolygonMode(face, mode);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glPolygonMode");
+#endif
+}
+
+// void glPolygonOffset (GLfloat factor, GLfloat units);
+static inline void qglPolygonOffset(GLfloat factor, GLfloat units)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glPolygonOffset(factor=%f, units=%f)\n", factor, units);
+#endif
+ glPolygonOffset(factor, units);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glPolygonOffset");
+#endif
+}
+
+// void glPolygonStipple (const GLubyte *mask);
+static inline void qglPolygonStipple(const GLubyte *mask)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glPolygonStipple(mask=%p)\n", mask);
+#endif
+ glPolygonStipple(mask);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glPolygonStipple");
+#endif
+}
+
+// void glPopAttrib (void);
+static inline void qglPopAttrib(void)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glPopAttrib(void)\n");
+#endif
+ glPopAttrib();
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glPopAttrib");
+#endif
+}
+
+// void glPopClientAttrib (void);
+static inline void qglPopClientAttrib(void)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glPopClientAttrib(void)\n");
+#endif
+ glPopClientAttrib();
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glPopClientAttrib");
+#endif
+}
+
+// void glPopMatrix (void);
+static inline void qglPopMatrix(void)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glPopMatrix(void)\n");
+#endif
+ glPopMatrix();
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glPopMatrix");
+#endif
+}
+
+// void glPopName (void);
+static inline void qglPopName(void)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glPopName(void)\n");
+#endif
+ glPopName();
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glPopName");
+#endif
+}
+
+// void glPrioritizeTextures (GLsizei n, const GLuint *textures, const GLclampf *priorities);
+static inline void qglPrioritizeTextures(GLsizei n, const GLuint *textures, const GLclampf *priorities)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glPrioritizeTextures(n=%ld, textures=%p, priorities=%p)\n", n, textures, priorities);
+#endif
+ glPrioritizeTextures(n, textures, priorities);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glPrioritizeTextures");
+#endif
+}
+
+// void glPushAttrib (GLbitfield mask);
+static inline void qglPushAttrib(GLbitfield mask)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glPushAttrib(mask=%lu)\n", mask);
+#endif
+ glPushAttrib(mask);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glPushAttrib");
+#endif
+}
+
+// void glPushClientAttrib (GLbitfield mask);
+static inline void qglPushClientAttrib(GLbitfield mask)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glPushClientAttrib(mask=%lu)\n", mask);
+#endif
+ glPushClientAttrib(mask);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glPushClientAttrib");
+#endif
+}
+
+// void glPushMatrix (void);
+static inline void qglPushMatrix(void)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glPushMatrix(void)\n");
+#endif
+ glPushMatrix();
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glPushMatrix");
+#endif
+}
+
+// void glPushName (GLuint name);
+static inline void qglPushName(GLuint name)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glPushName(name=%lu)\n", name);
+#endif
+ glPushName(name);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glPushName");
+#endif
+}
+
+// void glRasterPos2d (GLdouble x, GLdouble y);
+static inline void qglRasterPos2d(GLdouble x, GLdouble y)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRasterPos2d(x=%f, y=%f)\n", x, y);
+#endif
+ glRasterPos2d(x, y);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRasterPos2d");
+#endif
+}
+
+// void glRasterPos2dv (const GLdouble *v);
+static inline void qglRasterPos2dv(const GLdouble *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRasterPos2dv(v=%p)\n", v);
+#endif
+ glRasterPos2dv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRasterPos2dv");
+#endif
+}
+
+// void glRasterPos2f (GLfloat x, GLfloat y);
+static inline void qglRasterPos2f(GLfloat x, GLfloat y)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRasterPos2f(x=%f, y=%f)\n", x, y);
+#endif
+ glRasterPos2f(x, y);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRasterPos2f");
+#endif
+}
+
+// void glRasterPos2fv (const GLfloat *v);
+static inline void qglRasterPos2fv(const GLfloat *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRasterPos2fv(v=%p)\n", v);
+#endif
+ glRasterPos2fv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRasterPos2fv");
+#endif
+}
+
+// void glRasterPos2i (GLint x, GLint y);
+static inline void qglRasterPos2i(GLint x, GLint y)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRasterPos2i(x=%ld, y=%ld)\n", x, y);
+#endif
+ glRasterPos2i(x, y);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRasterPos2i");
+#endif
+}
+
+// void glRasterPos2iv (const GLint *v);
+static inline void qglRasterPos2iv(const GLint *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRasterPos2iv(v=%p)\n", v);
+#endif
+ glRasterPos2iv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRasterPos2iv");
+#endif
+}
+
+// void glRasterPos2s (GLshort x, GLshort y);
+static inline void qglRasterPos2s(GLshort x, GLshort y)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRasterPos2s(x=%d, y=%d)\n", x, y);
+#endif
+ glRasterPos2s(x, y);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRasterPos2s");
+#endif
+}
+
+// void glRasterPos2sv (const GLshort *v);
+static inline void qglRasterPos2sv(const GLshort *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRasterPos2sv(v=%p)\n", v);
+#endif
+ glRasterPos2sv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRasterPos2sv");
+#endif
+}
+
+// void glRasterPos3d (GLdouble x, GLdouble y, GLdouble z);
+static inline void qglRasterPos3d(GLdouble x, GLdouble y, GLdouble z)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRasterPos3d(x=%f, y=%f, z=%f)\n", x, y, z);
+#endif
+ glRasterPos3d(x, y, z);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRasterPos3d");
+#endif
+}
+
+// void glRasterPos3dv (const GLdouble *v);
+static inline void qglRasterPos3dv(const GLdouble *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRasterPos3dv(v=%p)\n", v);
+#endif
+ glRasterPos3dv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRasterPos3dv");
+#endif
+}
+
+// void glRasterPos3f (GLfloat x, GLfloat y, GLfloat z);
+static inline void qglRasterPos3f(GLfloat x, GLfloat y, GLfloat z)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRasterPos3f(x=%f, y=%f, z=%f)\n", x, y, z);
+#endif
+ glRasterPos3f(x, y, z);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRasterPos3f");
+#endif
+}
+
+// void glRasterPos3fv (const GLfloat *v);
+static inline void qglRasterPos3fv(const GLfloat *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRasterPos3fv(v=%p)\n", v);
+#endif
+ glRasterPos3fv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRasterPos3fv");
+#endif
+}
+
+// void glRasterPos3i (GLint x, GLint y, GLint z);
+static inline void qglRasterPos3i(GLint x, GLint y, GLint z)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRasterPos3i(x=%ld, y=%ld, z=%ld)\n", x, y, z);
+#endif
+ glRasterPos3i(x, y, z);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRasterPos3i");
+#endif
+}
+
+// void glRasterPos3iv (const GLint *v);
+static inline void qglRasterPos3iv(const GLint *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRasterPos3iv(v=%p)\n", v);
+#endif
+ glRasterPos3iv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRasterPos3iv");
+#endif
+}
+
+// void glRasterPos3s (GLshort x, GLshort y, GLshort z);
+static inline void qglRasterPos3s(GLshort x, GLshort y, GLshort z)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRasterPos3s(x=%d, y=%d, z=%d)\n", x, y, z);
+#endif
+ glRasterPos3s(x, y, z);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRasterPos3s");
+#endif
+}
+
+// void glRasterPos3sv (const GLshort *v);
+static inline void qglRasterPos3sv(const GLshort *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRasterPos3sv(v=%p)\n", v);
+#endif
+ glRasterPos3sv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRasterPos3sv");
+#endif
+}
+
+// void glRasterPos4d (GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+static inline void qglRasterPos4d(GLdouble x, GLdouble y, GLdouble z, GLdouble w)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRasterPos4d(x=%f, y=%f, z=%f, w=%f)\n", x, y, z, w);
+#endif
+ glRasterPos4d(x, y, z, w);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRasterPos4d");
+#endif
+}
+
+// void glRasterPos4dv (const GLdouble *v);
+static inline void qglRasterPos4dv(const GLdouble *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRasterPos4dv(v=%p)\n", v);
+#endif
+ glRasterPos4dv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRasterPos4dv");
+#endif
+}
+
+// void glRasterPos4f (GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+static inline void qglRasterPos4f(GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRasterPos4f(x=%f, y=%f, z=%f, w=%f)\n", x, y, z, w);
+#endif
+ glRasterPos4f(x, y, z, w);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRasterPos4f");
+#endif
+}
+
+// void glRasterPos4fv (const GLfloat *v);
+static inline void qglRasterPos4fv(const GLfloat *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRasterPos4fv(v=%p)\n", v);
+#endif
+ glRasterPos4fv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRasterPos4fv");
+#endif
+}
+
+// void glRasterPos4i (GLint x, GLint y, GLint z, GLint w);
+static inline void qglRasterPos4i(GLint x, GLint y, GLint z, GLint w)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRasterPos4i(x=%ld, y=%ld, z=%ld, w=%ld)\n", x, y, z, w);
+#endif
+ glRasterPos4i(x, y, z, w);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRasterPos4i");
+#endif
+}
+
+// void glRasterPos4iv (const GLint *v);
+static inline void qglRasterPos4iv(const GLint *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRasterPos4iv(v=%p)\n", v);
+#endif
+ glRasterPos4iv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRasterPos4iv");
+#endif
+}
+
+// void glRasterPos4s (GLshort x, GLshort y, GLshort z, GLshort w);
+static inline void qglRasterPos4s(GLshort x, GLshort y, GLshort z, GLshort w)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRasterPos4s(x=%d, y=%d, z=%d, w=%d)\n", x, y, z, w);
+#endif
+ glRasterPos4s(x, y, z, w);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRasterPos4s");
+#endif
+}
+
+// void glRasterPos4sv (const GLshort *v);
+static inline void qglRasterPos4sv(const GLshort *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRasterPos4sv(v=%p)\n", v);
+#endif
+ glRasterPos4sv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRasterPos4sv");
+#endif
+}
+
+// void glReadBuffer (GLenum mode);
+static inline void qglReadBuffer(GLenum mode)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glReadBuffer(mode=%lu)\n", mode);
+#endif
+ glReadBuffer(mode);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glReadBuffer");
+#endif
+}
+
+// void glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels);
+static inline void qglReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glReadPixels(x=%ld, y=%ld, width=%ld, height=%ld, format=%lu, type=%lu, pixels=%p)\n", x, y, width, height, format, type, pixels);
+#endif
+ glReadPixels(x, y, width, height, format, type, pixels);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glReadPixels");
+#endif
+}
+
+// void glRectd (GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2);
+static inline void qglRectd(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRectd(x1=%f, y1=%f, x2=%f, y2=%f)\n", x1, y1, x2, y2);
+#endif
+ glRectd(x1, y1, x2, y2);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRectd");
+#endif
+}
+
+// void glRectdv (const GLdouble *v1, const GLdouble *v2);
+static inline void qglRectdv(const GLdouble *v1, const GLdouble *v2)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRectdv(v1=%p, v2=%p)\n", v1, v2);
+#endif
+ glRectdv(v1, v2);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRectdv");
+#endif
+}
+
+// void glRectf (GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2);
+static inline void qglRectf(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRectf(x1=%f, y1=%f, x2=%f, y2=%f)\n", x1, y1, x2, y2);
+#endif
+ glRectf(x1, y1, x2, y2);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRectf");
+#endif
+}
+
+// void glRectfv (const GLfloat *v1, const GLfloat *v2);
+static inline void qglRectfv(const GLfloat *v1, const GLfloat *v2)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRectfv(v1=%p, v2=%p)\n", v1, v2);
+#endif
+ glRectfv(v1, v2);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRectfv");
+#endif
+}
+
+// void glRecti (GLint x1, GLint y1, GLint x2, GLint y2);
+static inline void qglRecti(GLint x1, GLint y1, GLint x2, GLint y2)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRecti(x1=%ld, y1=%ld, x2=%ld, y2=%ld)\n", x1, y1, x2, y2);
+#endif
+ glRecti(x1, y1, x2, y2);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRecti");
+#endif
+}
+
+// void glRectiv (const GLint *v1, const GLint *v2);
+static inline void qglRectiv(const GLint *v1, const GLint *v2)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRectiv(v1=%p, v2=%p)\n", v1, v2);
+#endif
+ glRectiv(v1, v2);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRectiv");
+#endif
+}
+
+// void glRects (GLshort x1, GLshort y1, GLshort x2, GLshort y2);
+static inline void qglRects(GLshort x1, GLshort y1, GLshort x2, GLshort y2)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRects(x1=%d, y1=%d, x2=%d, y2=%d)\n", x1, y1, x2, y2);
+#endif
+ glRects(x1, y1, x2, y2);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRects");
+#endif
+}
+
+// void glRectsv (const GLshort *v1, const GLshort *v2);
+static inline void qglRectsv(const GLshort *v1, const GLshort *v2)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRectsv(v1=%p, v2=%p)\n", v1, v2);
+#endif
+ glRectsv(v1, v2);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRectsv");
+#endif
+}
+
+// GLint glRenderMode (GLenum mode);
+static inline GLint qglRenderMode(GLenum mode)
+{
+ GLint returnValue;
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRenderMode(mode=%lu)\n", mode);
+#endif
+ returnValue = glRenderMode(mode);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRenderMode");
+#endif
+ return returnValue;
+}
+
+// void glRotated (GLdouble angle, GLdouble x, GLdouble y, GLdouble z);
+static inline void qglRotated(GLdouble angle, GLdouble x, GLdouble y, GLdouble z)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRotated(angle=%f, x=%f, y=%f, z=%f)\n", angle, x, y, z);
+#endif
+ glRotated(angle, x, y, z);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRotated");
+#endif
+}
+
+// void glRotatef (GLfloat angle, GLfloat x, GLfloat y, GLfloat z);
+static inline void qglRotatef(GLfloat angle, GLfloat x, GLfloat y, GLfloat z)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glRotatef(angle=%f, x=%f, y=%f, z=%f)\n", angle, x, y, z);
+#endif
+ glRotatef(angle, x, y, z);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glRotatef");
+#endif
+}
+
+// void glScaled (GLdouble x, GLdouble y, GLdouble z);
+static inline void qglScaled(GLdouble x, GLdouble y, GLdouble z)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glScaled(x=%f, y=%f, z=%f)\n", x, y, z);
+#endif
+ glScaled(x, y, z);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glScaled");
+#endif
+}
+
+// void glScalef (GLfloat x, GLfloat y, GLfloat z);
+static inline void qglScalef(GLfloat x, GLfloat y, GLfloat z)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glScalef(x=%f, y=%f, z=%f)\n", x, y, z);
+#endif
+ glScalef(x, y, z);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glScalef");
+#endif
+}
+
+// void glScissor (GLint x, GLint y, GLsizei width, GLsizei height);
+static inline void qglScissor(GLint x, GLint y, GLsizei width, GLsizei height)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glScissor(x=%ld, y=%ld, width=%ld, height=%ld)\n", x, y, width, height);
+#endif
+ glScissor(x, y, width, height);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glScissor");
+#endif
+}
+
+// void glSelectBuffer (GLsizei size, GLuint *buffer);
+static inline void qglSelectBuffer(GLsizei size, GLuint *buffer)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glSelectBuffer(size=%ld, buffer=%p)\n", size, buffer);
+#endif
+ glSelectBuffer(size, buffer);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glSelectBuffer");
+#endif
+}
+
+// void glShadeModel (GLenum mode);
+static inline void qglShadeModel(GLenum mode)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glShadeModel(mode=%lu)\n", mode);
+#endif
+ glShadeModel(mode);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glShadeModel");
+#endif
+}
+
+// void glStencilFunc (GLenum func, GLint ref, GLuint mask);
+static inline void qglStencilFunc(GLenum func, GLint ref, GLuint mask)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glStencilFunc(func=%lu, ref=%ld, mask=%lu)\n", func, ref, mask);
+#endif
+ glStencilFunc(func, ref, mask);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glStencilFunc");
+#endif
+}
+
+// void glStencilMask (GLuint mask);
+static inline void qglStencilMask(GLuint mask)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glStencilMask(mask=%lu)\n", mask);
+#endif
+ glStencilMask(mask);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glStencilMask");
+#endif
+}
+
+// void glStencilOp (GLenum fail, GLenum zfail, GLenum zpass);
+static inline void qglStencilOp(GLenum fail, GLenum zfail, GLenum zpass)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glStencilOp(fail=%lu, zfail=%lu, zpass=%lu)\n", fail, zfail, zpass);
+#endif
+ glStencilOp(fail, zfail, zpass);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glStencilOp");
+#endif
+}
+
+// void glTexCoord1d (GLdouble s);
+static inline void qglTexCoord1d(GLdouble s)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord1d(s=%f)\n", s);
+#endif
+ glTexCoord1d(s);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord1d");
+#endif
+}
+
+// void glTexCoord1dv (const GLdouble *v);
+static inline void qglTexCoord1dv(const GLdouble *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord1dv(v=%p)\n", v);
+#endif
+ glTexCoord1dv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord1dv");
+#endif
+}
+
+// void glTexCoord1f (GLfloat s);
+static inline void qglTexCoord1f(GLfloat s)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord1f(s=%f)\n", s);
+#endif
+ glTexCoord1f(s);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord1f");
+#endif
+}
+
+// void glTexCoord1fv (const GLfloat *v);
+static inline void qglTexCoord1fv(const GLfloat *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord1fv(v=%p)\n", v);
+#endif
+ glTexCoord1fv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord1fv");
+#endif
+}
+
+// void glTexCoord1i (GLint s);
+static inline void qglTexCoord1i(GLint s)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord1i(s=%ld)\n", s);
+#endif
+ glTexCoord1i(s);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord1i");
+#endif
+}
+
+// void glTexCoord1iv (const GLint *v);
+static inline void qglTexCoord1iv(const GLint *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord1iv(v=%p)\n", v);
+#endif
+ glTexCoord1iv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord1iv");
+#endif
+}
+
+// void glTexCoord1s (GLshort s);
+static inline void qglTexCoord1s(GLshort s)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord1s(s=%d)\n", s);
+#endif
+ glTexCoord1s(s);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord1s");
+#endif
+}
+
+// void glTexCoord1sv (const GLshort *v);
+static inline void qglTexCoord1sv(const GLshort *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord1sv(v=%p)\n", v);
+#endif
+ glTexCoord1sv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord1sv");
+#endif
+}
+
+// void glTexCoord2d (GLdouble s, GLdouble t);
+static inline void qglTexCoord2d(GLdouble s, GLdouble t)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord2d(s=%f, t=%f)\n", s, t);
+#endif
+ glTexCoord2d(s, t);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord2d");
+#endif
+}
+
+// void glTexCoord2dv (const GLdouble *v);
+static inline void qglTexCoord2dv(const GLdouble *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord2dv(v=%p)\n", v);
+#endif
+ glTexCoord2dv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord2dv");
+#endif
+}
+
+// void glTexCoord2f (GLfloat s, GLfloat t);
+static inline void qglTexCoord2f(GLfloat s, GLfloat t)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord2f(s=%f, t=%f)\n", s, t);
+#endif
+ glTexCoord2f(s, t);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord2f");
+#endif
+}
+
+// void glTexCoord2fv (const GLfloat *v);
+static inline void qglTexCoord2fv(const GLfloat *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord2fv(v=%p)\n", v);
+#endif
+ glTexCoord2fv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord2fv");
+#endif
+}
+
+// void glTexCoord2i (GLint s, GLint t);
+static inline void qglTexCoord2i(GLint s, GLint t)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord2i(s=%ld, t=%ld)\n", s, t);
+#endif
+ glTexCoord2i(s, t);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord2i");
+#endif
+}
+
+// void glTexCoord2iv (const GLint *v);
+static inline void qglTexCoord2iv(const GLint *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord2iv(v=%p)\n", v);
+#endif
+ glTexCoord2iv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord2iv");
+#endif
+}
+
+// void glTexCoord2s (GLshort s, GLshort t);
+static inline void qglTexCoord2s(GLshort s, GLshort t)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord2s(s=%d, t=%d)\n", s, t);
+#endif
+ glTexCoord2s(s, t);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord2s");
+#endif
+}
+
+// void glTexCoord2sv (const GLshort *v);
+static inline void qglTexCoord2sv(const GLshort *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord2sv(v=%p)\n", v);
+#endif
+ glTexCoord2sv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord2sv");
+#endif
+}
+
+// void glTexCoord3d (GLdouble s, GLdouble t, GLdouble r);
+static inline void qglTexCoord3d(GLdouble s, GLdouble t, GLdouble r)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord3d(s=%f, t=%f, r=%f)\n", s, t, r);
+#endif
+ glTexCoord3d(s, t, r);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord3d");
+#endif
+}
+
+// void glTexCoord3dv (const GLdouble *v);
+static inline void qglTexCoord3dv(const GLdouble *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord3dv(v=%p)\n", v);
+#endif
+ glTexCoord3dv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord3dv");
+#endif
+}
+
+// void glTexCoord3f (GLfloat s, GLfloat t, GLfloat r);
+static inline void qglTexCoord3f(GLfloat s, GLfloat t, GLfloat r)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord3f(s=%f, t=%f, r=%f)\n", s, t, r);
+#endif
+ glTexCoord3f(s, t, r);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord3f");
+#endif
+}
+
+// void glTexCoord3fv (const GLfloat *v);
+static inline void qglTexCoord3fv(const GLfloat *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord3fv(v=%p)\n", v);
+#endif
+ glTexCoord3fv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord3fv");
+#endif
+}
+
+// void glTexCoord3i (GLint s, GLint t, GLint r);
+static inline void qglTexCoord3i(GLint s, GLint t, GLint r)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord3i(s=%ld, t=%ld, r=%ld)\n", s, t, r);
+#endif
+ glTexCoord3i(s, t, r);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord3i");
+#endif
+}
+
+// void glTexCoord3iv (const GLint *v);
+static inline void qglTexCoord3iv(const GLint *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord3iv(v=%p)\n", v);
+#endif
+ glTexCoord3iv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord3iv");
+#endif
+}
+
+// void glTexCoord3s (GLshort s, GLshort t, GLshort r);
+static inline void qglTexCoord3s(GLshort s, GLshort t, GLshort r)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord3s(s=%d, t=%d, r=%d)\n", s, t, r);
+#endif
+ glTexCoord3s(s, t, r);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord3s");
+#endif
+}
+
+// void glTexCoord3sv (const GLshort *v);
+static inline void qglTexCoord3sv(const GLshort *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord3sv(v=%p)\n", v);
+#endif
+ glTexCoord3sv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord3sv");
+#endif
+}
+
+// void glTexCoord4d (GLdouble s, GLdouble t, GLdouble r, GLdouble q);
+static inline void qglTexCoord4d(GLdouble s, GLdouble t, GLdouble r, GLdouble q)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord4d(s=%f, t=%f, r=%f, q=%f)\n", s, t, r, q);
+#endif
+ glTexCoord4d(s, t, r, q);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord4d");
+#endif
+}
+
+// void glTexCoord4dv (const GLdouble *v);
+static inline void qglTexCoord4dv(const GLdouble *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord4dv(v=%p)\n", v);
+#endif
+ glTexCoord4dv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord4dv");
+#endif
+}
+
+// void glTexCoord4f (GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+static inline void qglTexCoord4f(GLfloat s, GLfloat t, GLfloat r, GLfloat q)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord4f(s=%f, t=%f, r=%f, q=%f)\n", s, t, r, q);
+#endif
+ glTexCoord4f(s, t, r, q);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord4f");
+#endif
+}
+
+// void glTexCoord4fv (const GLfloat *v);
+static inline void qglTexCoord4fv(const GLfloat *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord4fv(v=%p)\n", v);
+#endif
+ glTexCoord4fv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord4fv");
+#endif
+}
+
+// void glTexCoord4i (GLint s, GLint t, GLint r, GLint q);
+static inline void qglTexCoord4i(GLint s, GLint t, GLint r, GLint q)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord4i(s=%ld, t=%ld, r=%ld, q=%ld)\n", s, t, r, q);
+#endif
+ glTexCoord4i(s, t, r, q);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord4i");
+#endif
+}
+
+// void glTexCoord4iv (const GLint *v);
+static inline void qglTexCoord4iv(const GLint *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord4iv(v=%p)\n", v);
+#endif
+ glTexCoord4iv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord4iv");
+#endif
+}
+
+// void glTexCoord4s (GLshort s, GLshort t, GLshort r, GLshort q);
+static inline void qglTexCoord4s(GLshort s, GLshort t, GLshort r, GLshort q)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord4s(s=%d, t=%d, r=%d, q=%d)\n", s, t, r, q);
+#endif
+ glTexCoord4s(s, t, r, q);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord4s");
+#endif
+}
+
+// void glTexCoord4sv (const GLshort *v);
+static inline void qglTexCoord4sv(const GLshort *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoord4sv(v=%p)\n", v);
+#endif
+ glTexCoord4sv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoord4sv");
+#endif
+}
+
+// void glTexCoordPointer (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+static inline void qglTexCoordPointer(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexCoordPointer(size=%ld, type=%lu, stride=%ld, pointer=%p)\n", size, type, stride, pointer);
+#endif
+ glTexCoordPointer(size, type, stride, pointer);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexCoordPointer");
+#endif
+}
+
+// void glTexEnvf (GLenum target, GLenum pname, GLfloat param);
+static inline void qglTexEnvf(GLenum target, GLenum pname, GLfloat param)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexEnvf(target=%lu, pname=%lu, param=%f)\n", target, pname, param);
+#endif
+ glTexEnvf(target, pname, param);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexEnvf");
+#endif
+}
+
+// void glTexEnvfv (GLenum target, GLenum pname, const GLfloat *params);
+static inline void qglTexEnvfv(GLenum target, GLenum pname, const GLfloat *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexEnvfv(target=%lu, pname=%lu, params=%p)\n", target, pname, params);
+#endif
+ glTexEnvfv(target, pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexEnvfv");
+#endif
+}
+
+// void glTexEnvi (GLenum target, GLenum pname, GLint param);
+static inline void qglTexEnvi(GLenum target, GLenum pname, GLint param)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexEnvi(target=%lu, pname=%lu, param=%ld)\n", target, pname, param);
+#endif
+ glTexEnvi(target, pname, param);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexEnvi");
+#endif
+}
+
+// void glTexEnviv (GLenum target, GLenum pname, const GLint *params);
+static inline void qglTexEnviv(GLenum target, GLenum pname, const GLint *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexEnviv(target=%lu, pname=%lu, params=%p)\n", target, pname, params);
+#endif
+ glTexEnviv(target, pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexEnviv");
+#endif
+}
+
+// void glTexGend (GLenum coord, GLenum pname, GLdouble param);
+static inline void qglTexGend(GLenum coord, GLenum pname, GLdouble param)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexGend(coord=%lu, pname=%lu, param=%f)\n", coord, pname, param);
+#endif
+ glTexGend(coord, pname, param);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexGend");
+#endif
+}
+
+// void glTexGendv (GLenum coord, GLenum pname, const GLdouble *params);
+static inline void qglTexGendv(GLenum coord, GLenum pname, const GLdouble *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexGendv(coord=%lu, pname=%lu, params=%p)\n", coord, pname, params);
+#endif
+ glTexGendv(coord, pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexGendv");
+#endif
+}
+
+// void glTexGenf (GLenum coord, GLenum pname, GLfloat param);
+static inline void qglTexGenf(GLenum coord, GLenum pname, GLfloat param)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexGenf(coord=%lu, pname=%lu, param=%f)\n", coord, pname, param);
+#endif
+ glTexGenf(coord, pname, param);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexGenf");
+#endif
+}
+
+// void glTexGenfv (GLenum coord, GLenum pname, const GLfloat *params);
+static inline void qglTexGenfv(GLenum coord, GLenum pname, const GLfloat *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexGenfv(coord=%lu, pname=%lu, params=%p)\n", coord, pname, params);
+#endif
+ glTexGenfv(coord, pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexGenfv");
+#endif
+}
+
+// void glTexGeni (GLenum coord, GLenum pname, GLint param);
+static inline void qglTexGeni(GLenum coord, GLenum pname, GLint param)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexGeni(coord=%lu, pname=%lu, param=%ld)\n", coord, pname, param);
+#endif
+ glTexGeni(coord, pname, param);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexGeni");
+#endif
+}
+
+// void glTexGeniv (GLenum coord, GLenum pname, const GLint *params);
+static inline void qglTexGeniv(GLenum coord, GLenum pname, const GLint *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexGeniv(coord=%lu, pname=%lu, params=%p)\n", coord, pname, params);
+#endif
+ glTexGeniv(coord, pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexGeniv");
+#endif
+}
+
+// void glTexImage1D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+static inline void qglTexImage1D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexImage1D(target=%lu, level=%ld, internalformat=%ld, width=%ld, border=%ld, format=%lu, type=%lu, pixels=%p)\n", target, level, internalformat, width, border, format, type, pixels);
+#endif
+ glTexImage1D(target, level, internalformat, width, border, format, type, pixels);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexImage1D");
+#endif
+}
+
+// void glTexImage2D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+static inline void qglTexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexImage2D(target=%lu, level=%ld, internalformat=%ld, width=%ld, height=%ld, border=%ld, format=%lu, type=%lu, pixels=%p)\n", target, level, internalformat, width, height, border, format, type, pixels);
+#endif
+ glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexImage2D");
+#endif
+}
+
+// void glTexParameterf (GLenum target, GLenum pname, GLfloat param);
+static inline void qglTexParameterf(GLenum target, GLenum pname, GLfloat param)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexParameterf(target=%lu, pname=%lu, param=%f)\n", target, pname, param);
+#endif
+ glTexParameterf(target, pname, param);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexParameterf");
+#endif
+}
+
+// void glTexParameterfv (GLenum target, GLenum pname, const GLfloat *params);
+static inline void qglTexParameterfv(GLenum target, GLenum pname, const GLfloat *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexParameterfv(target=%lu, pname=%lu, params=%p)\n", target, pname, params);
+#endif
+ glTexParameterfv(target, pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexParameterfv");
+#endif
+}
+
+// void glTexParameteri (GLenum target, GLenum pname, GLint param);
+static inline void qglTexParameteri(GLenum target, GLenum pname, GLint param)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexParameteri(target=%lu, pname=%lu, param=%ld)\n", target, pname, param);
+#endif
+ glTexParameteri(target, pname, param);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexParameteri");
+#endif
+}
+
+// void glTexParameteriv (GLenum target, GLenum pname, const GLint *params);
+static inline void qglTexParameteriv(GLenum target, GLenum pname, const GLint *params)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexParameteriv(target=%lu, pname=%lu, params=%p)\n", target, pname, params);
+#endif
+ glTexParameteriv(target, pname, params);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexParameteriv");
+#endif
+}
+
+// void glTexSubImage1D (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels);
+static inline void qglTexSubImage1D(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexSubImage1D(target=%lu, level=%ld, xoffset=%ld, width=%ld, format=%lu, type=%lu, pixels=%p)\n", target, level, xoffset, width, format, type, pixels);
+#endif
+ glTexSubImage1D(target, level, xoffset, width, format, type, pixels);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexSubImage1D");
+#endif
+}
+
+// void glTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+static inline void qglTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTexSubImage2D(target=%lu, level=%ld, xoffset=%ld, yoffset=%ld, width=%ld, height=%ld, format=%lu, type=%lu, pixels=%p)\n", target, level, xoffset, yoffset, width, height, format, type, pixels);
+#endif
+ glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTexSubImage2D");
+#endif
+}
+
+// void glTranslated (GLdouble x, GLdouble y, GLdouble z);
+static inline void qglTranslated(GLdouble x, GLdouble y, GLdouble z)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTranslated(x=%f, y=%f, z=%f)\n", x, y, z);
+#endif
+ glTranslated(x, y, z);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTranslated");
+#endif
+}
+
+// void glTranslatef (GLfloat x, GLfloat y, GLfloat z);
+static inline void qglTranslatef(GLfloat x, GLfloat y, GLfloat z)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glTranslatef(x=%f, y=%f, z=%f)\n", x, y, z);
+#endif
+ glTranslatef(x, y, z);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glTranslatef");
+#endif
+}
+
+// void glVertex2d (GLdouble x, GLdouble y);
+static inline void qglVertex2d(GLdouble x, GLdouble y)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertex2d(x=%f, y=%f)\n", x, y);
+#endif
+ glVertex2d(x, y);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertex2d");
+#endif
+}
+
+// void glVertex2dv (const GLdouble *v);
+static inline void qglVertex2dv(const GLdouble *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertex2dv(v=%p)\n", v);
+#endif
+ glVertex2dv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertex2dv");
+#endif
+}
+
+// void glVertex2f (GLfloat x, GLfloat y);
+static inline void qglVertex2f(GLfloat x, GLfloat y)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertex2f(x=%f, y=%f)\n", x, y);
+#endif
+ glVertex2f(x, y);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertex2f");
+#endif
+}
+
+// void glVertex2fv (const GLfloat *v);
+static inline void qglVertex2fv(const GLfloat *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertex2fv(v=%p)\n", v);
+#endif
+ glVertex2fv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertex2fv");
+#endif
+}
+
+// void glVertex2i (GLint x, GLint y);
+static inline void qglVertex2i(GLint x, GLint y)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertex2i(x=%ld, y=%ld)\n", x, y);
+#endif
+ glVertex2i(x, y);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertex2i");
+#endif
+}
+
+// void glVertex2iv (const GLint *v);
+static inline void qglVertex2iv(const GLint *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertex2iv(v=%p)\n", v);
+#endif
+ glVertex2iv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertex2iv");
+#endif
+}
+
+// void glVertex2s (GLshort x, GLshort y);
+static inline void qglVertex2s(GLshort x, GLshort y)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertex2s(x=%d, y=%d)\n", x, y);
+#endif
+ glVertex2s(x, y);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertex2s");
+#endif
+}
+
+// void glVertex2sv (const GLshort *v);
+static inline void qglVertex2sv(const GLshort *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertex2sv(v=%p)\n", v);
+#endif
+ glVertex2sv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertex2sv");
+#endif
+}
+
+// void glVertex3d (GLdouble x, GLdouble y, GLdouble z);
+static inline void qglVertex3d(GLdouble x, GLdouble y, GLdouble z)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertex3d(x=%f, y=%f, z=%f)\n", x, y, z);
+#endif
+ glVertex3d(x, y, z);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertex3d");
+#endif
+}
+
+// void glVertex3dv (const GLdouble *v);
+static inline void qglVertex3dv(const GLdouble *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertex3dv(v=%p)\n", v);
+#endif
+ glVertex3dv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertex3dv");
+#endif
+}
+
+// void glVertex3f (GLfloat x, GLfloat y, GLfloat z);
+static inline void qglVertex3f(GLfloat x, GLfloat y, GLfloat z)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertex3f(x=%f, y=%f, z=%f)\n", x, y, z);
+#endif
+ glVertex3f(x, y, z);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertex3f");
+#endif
+}
+
+// void glVertex3fv (const GLfloat *v);
+static inline void qglVertex3fv(const GLfloat *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertex3fv(v=%p)\n", v);
+#endif
+ glVertex3fv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertex3fv");
+#endif
+}
+
+// void glVertex3i (GLint x, GLint y, GLint z);
+static inline void qglVertex3i(GLint x, GLint y, GLint z)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertex3i(x=%ld, y=%ld, z=%ld)\n", x, y, z);
+#endif
+ glVertex3i(x, y, z);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertex3i");
+#endif
+}
+
+// void glVertex3iv (const GLint *v);
+static inline void qglVertex3iv(const GLint *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertex3iv(v=%p)\n", v);
+#endif
+ glVertex3iv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertex3iv");
+#endif
+}
+
+// void glVertex3s (GLshort x, GLshort y, GLshort z);
+static inline void qglVertex3s(GLshort x, GLshort y, GLshort z)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertex3s(x=%d, y=%d, z=%d)\n", x, y, z);
+#endif
+ glVertex3s(x, y, z);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertex3s");
+#endif
+}
+
+// void glVertex3sv (const GLshort *v);
+static inline void qglVertex3sv(const GLshort *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertex3sv(v=%p)\n", v);
+#endif
+ glVertex3sv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertex3sv");
+#endif
+}
+
+// void glVertex4d (GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+static inline void qglVertex4d(GLdouble x, GLdouble y, GLdouble z, GLdouble w)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertex4d(x=%f, y=%f, z=%f, w=%f)\n", x, y, z, w);
+#endif
+ glVertex4d(x, y, z, w);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertex4d");
+#endif
+}
+
+// void glVertex4dv (const GLdouble *v);
+static inline void qglVertex4dv(const GLdouble *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertex4dv(v=%p)\n", v);
+#endif
+ glVertex4dv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertex4dv");
+#endif
+}
+
+// void glVertex4f (GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+static inline void qglVertex4f(GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertex4f(x=%f, y=%f, z=%f, w=%f)\n", x, y, z, w);
+#endif
+ glVertex4f(x, y, z, w);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertex4f");
+#endif
+}
+
+// void glVertex4fv (const GLfloat *v);
+static inline void qglVertex4fv(const GLfloat *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertex4fv(v=%p)\n", v);
+#endif
+ glVertex4fv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertex4fv");
+#endif
+}
+
+// void glVertex4i (GLint x, GLint y, GLint z, GLint w);
+static inline void qglVertex4i(GLint x, GLint y, GLint z, GLint w)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertex4i(x=%ld, y=%ld, z=%ld, w=%ld)\n", x, y, z, w);
+#endif
+ glVertex4i(x, y, z, w);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertex4i");
+#endif
+}
+
+// void glVertex4iv (const GLint *v);
+static inline void qglVertex4iv(const GLint *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertex4iv(v=%p)\n", v);
+#endif
+ glVertex4iv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertex4iv");
+#endif
+}
+
+// void glVertex4s (GLshort x, GLshort y, GLshort z, GLshort w);
+static inline void qglVertex4s(GLshort x, GLshort y, GLshort z, GLshort w)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertex4s(x=%d, y=%d, z=%d, w=%d)\n", x, y, z, w);
+#endif
+ glVertex4s(x, y, z, w);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertex4s");
+#endif
+}
+
+// void glVertex4sv (const GLshort *v);
+static inline void qglVertex4sv(const GLshort *v)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertex4sv(v=%p)\n", v);
+#endif
+ glVertex4sv(v);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertex4sv");
+#endif
+}
+
+// void glVertexPointer (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+static inline void qglVertexPointer(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glVertexPointer(size=%ld, type=%lu, stride=%ld, pointer=%p)\n", size, type, stride, pointer);
+#endif
+ glVertexPointer(size, type, stride, pointer);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glVertexPointer");
+#endif
+}
+
+// void glViewport (GLint x, GLint y, GLsizei width, GLsizei height);
+static inline void qglViewport(GLint x, GLint y, GLsizei width, GLsizei height)
+{
+#if !defined(NDEBUG) && defined(QGL_LOG_GL_CALLS)
+ if (QGLLogGLCalls)
+ fprintf(QGLDebugFile(), "glViewport(x=%ld, y=%ld, width=%ld, height=%ld)\n", x, y, width, height);
+#endif
+ glViewport(x, y, width, height);
+#if !defined(NDEBUG) && defined(QGL_CHECK_GL_ERRORS)
+ if (!QGLBeginStarted)
+ QGLCheckError("glViewport");
+#endif
+}
+
+// Prevent calls to the 'normal' GL functions
+#define glAccum CALL_THE_QGL_VERSION_OF_glAccum
+#define glAlphaFunc CALL_THE_QGL_VERSION_OF_glAlphaFunc
+#define glAreTexturesResident CALL_THE_QGL_VERSION_OF_glAreTexturesResident
+#define glArrayElement CALL_THE_QGL_VERSION_OF_glArrayElement
+#define glBegin CALL_THE_QGL_VERSION_OF_glBegin
+#define glBindTexture CALL_THE_QGL_VERSION_OF_glBindTexture
+#define glBitmap CALL_THE_QGL_VERSION_OF_glBitmap
+#define glBlendFunc CALL_THE_QGL_VERSION_OF_glBlendFunc
+#define glCallList CALL_THE_QGL_VERSION_OF_glCallList
+#define glCallLists CALL_THE_QGL_VERSION_OF_glCallLists
+#define glClear CALL_THE_QGL_VERSION_OF_glClear
+#define glClearAccum CALL_THE_QGL_VERSION_OF_glClearAccum
+#define glClearColor CALL_THE_QGL_VERSION_OF_glClearColor
+#define glClearDepth CALL_THE_QGL_VERSION_OF_glClearDepth
+#define glClearIndex CALL_THE_QGL_VERSION_OF_glClearIndex
+#define glClearStencil CALL_THE_QGL_VERSION_OF_glClearStencil
+#define glClipPlane CALL_THE_QGL_VERSION_OF_glClipPlane
+#define glColor3b CALL_THE_QGL_VERSION_OF_glColor3b
+#define glColor3bv CALL_THE_QGL_VERSION_OF_glColor3bv
+#define glColor3d CALL_THE_QGL_VERSION_OF_glColor3d
+#define glColor3dv CALL_THE_QGL_VERSION_OF_glColor3dv
+#define glColor3f CALL_THE_QGL_VERSION_OF_glColor3f
+#define glColor3fv CALL_THE_QGL_VERSION_OF_glColor3fv
+#define glColor3i CALL_THE_QGL_VERSION_OF_glColor3i
+#define glColor3iv CALL_THE_QGL_VERSION_OF_glColor3iv
+#define glColor3s CALL_THE_QGL_VERSION_OF_glColor3s
+#define glColor3sv CALL_THE_QGL_VERSION_OF_glColor3sv
+#define glColor3ub CALL_THE_QGL_VERSION_OF_glColor3ub
+#define glColor3ubv CALL_THE_QGL_VERSION_OF_glColor3ubv
+#define glColor3ui CALL_THE_QGL_VERSION_OF_glColor3ui
+#define glColor3uiv CALL_THE_QGL_VERSION_OF_glColor3uiv
+#define glColor3us CALL_THE_QGL_VERSION_OF_glColor3us
+#define glColor3usv CALL_THE_QGL_VERSION_OF_glColor3usv
+#define glColor4b CALL_THE_QGL_VERSION_OF_glColor4b
+#define glColor4bv CALL_THE_QGL_VERSION_OF_glColor4bv
+#define glColor4d CALL_THE_QGL_VERSION_OF_glColor4d
+#define glColor4dv CALL_THE_QGL_VERSION_OF_glColor4dv
+#define glColor4f CALL_THE_QGL_VERSION_OF_glColor4f
+#define glColor4fv CALL_THE_QGL_VERSION_OF_glColor4fv
+#define glColor4i CALL_THE_QGL_VERSION_OF_glColor4i
+#define glColor4iv CALL_THE_QGL_VERSION_OF_glColor4iv
+#define glColor4s CALL_THE_QGL_VERSION_OF_glColor4s
+#define glColor4sv CALL_THE_QGL_VERSION_OF_glColor4sv
+#define glColor4ub CALL_THE_QGL_VERSION_OF_glColor4ub
+#define glColor4ubv CALL_THE_QGL_VERSION_OF_glColor4ubv
+#define glColor4ui CALL_THE_QGL_VERSION_OF_glColor4ui
+#define glColor4uiv CALL_THE_QGL_VERSION_OF_glColor4uiv
+#define glColor4us CALL_THE_QGL_VERSION_OF_glColor4us
+#define glColor4usv CALL_THE_QGL_VERSION_OF_glColor4usv
+#define glColorMask CALL_THE_QGL_VERSION_OF_glColorMask
+#define glColorMaterial CALL_THE_QGL_VERSION_OF_glColorMaterial
+#define glColorPointer CALL_THE_QGL_VERSION_OF_glColorPointer
+#define glCopyPixels CALL_THE_QGL_VERSION_OF_glCopyPixels
+#define glCopyTexImage1D CALL_THE_QGL_VERSION_OF_glCopyTexImage1D
+#define glCopyTexImage2D CALL_THE_QGL_VERSION_OF_glCopyTexImage2D
+#define glCopyTexSubImage1D CALL_THE_QGL_VERSION_OF_glCopyTexSubImage1D
+#define glCopyTexSubImage2D CALL_THE_QGL_VERSION_OF_glCopyTexSubImage2D
+#define glCullFace CALL_THE_QGL_VERSION_OF_glCullFace
+#define glDeleteLists CALL_THE_QGL_VERSION_OF_glDeleteLists
+#define glDeleteTextures CALL_THE_QGL_VERSION_OF_glDeleteTextures
+#define glDepthFunc CALL_THE_QGL_VERSION_OF_glDepthFunc
+#define glDepthMask CALL_THE_QGL_VERSION_OF_glDepthMask
+#define glDepthRange CALL_THE_QGL_VERSION_OF_glDepthRange
+#define glDisable CALL_THE_QGL_VERSION_OF_glDisable
+#define glDisableClientState CALL_THE_QGL_VERSION_OF_glDisableClientState
+#define glDrawArrays CALL_THE_QGL_VERSION_OF_glDrawArrays
+#define glDrawBuffer CALL_THE_QGL_VERSION_OF_glDrawBuffer
+#define glDrawElements CALL_THE_QGL_VERSION_OF_glDrawElements
+#define glDrawPixels CALL_THE_QGL_VERSION_OF_glDrawPixels
+#define glEdgeFlag CALL_THE_QGL_VERSION_OF_glEdgeFlag
+#define glEdgeFlagPointer CALL_THE_QGL_VERSION_OF_glEdgeFlagPointer
+#define glEdgeFlagv CALL_THE_QGL_VERSION_OF_glEdgeFlagv
+#define glEnable CALL_THE_QGL_VERSION_OF_glEnable
+#define glEnableClientState CALL_THE_QGL_VERSION_OF_glEnableClientState
+#define glEnd CALL_THE_QGL_VERSION_OF_glEnd
+#define glEndList CALL_THE_QGL_VERSION_OF_glEndList
+#define glEvalCoord1d CALL_THE_QGL_VERSION_OF_glEvalCoord1d
+#define glEvalCoord1dv CALL_THE_QGL_VERSION_OF_glEvalCoord1dv
+#define glEvalCoord1f CALL_THE_QGL_VERSION_OF_glEvalCoord1f
+#define glEvalCoord1fv CALL_THE_QGL_VERSION_OF_glEvalCoord1fv
+#define glEvalCoord2d CALL_THE_QGL_VERSION_OF_glEvalCoord2d
+#define glEvalCoord2dv CALL_THE_QGL_VERSION_OF_glEvalCoord2dv
+#define glEvalCoord2f CALL_THE_QGL_VERSION_OF_glEvalCoord2f
+#define glEvalCoord2fv CALL_THE_QGL_VERSION_OF_glEvalCoord2fv
+#define glEvalMesh1 CALL_THE_QGL_VERSION_OF_glEvalMesh1
+#define glEvalMesh2 CALL_THE_QGL_VERSION_OF_glEvalMesh2
+#define glEvalPoint1 CALL_THE_QGL_VERSION_OF_glEvalPoint1
+#define glEvalPoint2 CALL_THE_QGL_VERSION_OF_glEvalPoint2
+#define glFeedbackBuffer CALL_THE_QGL_VERSION_OF_glFeedbackBuffer
+#define glFinish CALL_THE_QGL_VERSION_OF_glFinish
+#define glFlush CALL_THE_QGL_VERSION_OF_glFlush
+#define glFogf CALL_THE_QGL_VERSION_OF_glFogf
+#define glFogfv CALL_THE_QGL_VERSION_OF_glFogfv
+#define glFogi CALL_THE_QGL_VERSION_OF_glFogi
+#define glFogiv CALL_THE_QGL_VERSION_OF_glFogiv
+#define glFrontFace CALL_THE_QGL_VERSION_OF_glFrontFace
+#define glFrustum CALL_THE_QGL_VERSION_OF_glFrustum
+#define glGenLists CALL_THE_QGL_VERSION_OF_glGenLists
+#define glGenTextures CALL_THE_QGL_VERSION_OF_glGenTextures
+#define glGetBooleanv CALL_THE_QGL_VERSION_OF_glGetBooleanv
+#define glGetClipPlane CALL_THE_QGL_VERSION_OF_glGetClipPlane
+#define glGetDoublev CALL_THE_QGL_VERSION_OF_glGetDoublev
+#define glGetError CALL_THE_QGL_VERSION_OF_glGetError
+#define glGetFloatv CALL_THE_QGL_VERSION_OF_glGetFloatv
+#define glGetIntegerv CALL_THE_QGL_VERSION_OF_glGetIntegerv
+#define glGetLightfv CALL_THE_QGL_VERSION_OF_glGetLightfv
+#define glGetLightiv CALL_THE_QGL_VERSION_OF_glGetLightiv
+#define glGetMapdv CALL_THE_QGL_VERSION_OF_glGetMapdv
+#define glGetMapfv CALL_THE_QGL_VERSION_OF_glGetMapfv
+#define glGetMapiv CALL_THE_QGL_VERSION_OF_glGetMapiv
+#define glGetMaterialfv CALL_THE_QGL_VERSION_OF_glGetMaterialfv
+#define glGetMaterialiv CALL_THE_QGL_VERSION_OF_glGetMaterialiv
+#define glGetPixelMapfv CALL_THE_QGL_VERSION_OF_glGetPixelMapfv
+#define glGetPixelMapuiv CALL_THE_QGL_VERSION_OF_glGetPixelMapuiv
+#define glGetPixelMapusv CALL_THE_QGL_VERSION_OF_glGetPixelMapusv
+#define glGetPointerv CALL_THE_QGL_VERSION_OF_glGetPointerv
+#define glGetPolygonStipple CALL_THE_QGL_VERSION_OF_glGetPolygonStipple
+#define glGetString CALL_THE_QGL_VERSION_OF_glGetString
+#define glGetTexEnvfv CALL_THE_QGL_VERSION_OF_glGetTexEnvfv
+#define glGetTexEnviv CALL_THE_QGL_VERSION_OF_glGetTexEnviv
+#define glGetTexGendv CALL_THE_QGL_VERSION_OF_glGetTexGendv
+#define glGetTexGenfv CALL_THE_QGL_VERSION_OF_glGetTexGenfv
+#define glGetTexGeniv CALL_THE_QGL_VERSION_OF_glGetTexGeniv
+#define glGetTexImage CALL_THE_QGL_VERSION_OF_glGetTexImage
+#define glGetTexLevelParameterfv CALL_THE_QGL_VERSION_OF_glGetTexLevelParameterfv
+#define glGetTexLevelParameteriv CALL_THE_QGL_VERSION_OF_glGetTexLevelParameteriv
+#define glGetTexParameterfv CALL_THE_QGL_VERSION_OF_glGetTexParameterfv
+#define glGetTexParameteriv CALL_THE_QGL_VERSION_OF_glGetTexParameteriv
+#define glHint CALL_THE_QGL_VERSION_OF_glHint
+#define glIndexMask CALL_THE_QGL_VERSION_OF_glIndexMask
+#define glIndexPointer CALL_THE_QGL_VERSION_OF_glIndexPointer
+#define glIndexd CALL_THE_QGL_VERSION_OF_glIndexd
+#define glIndexdv CALL_THE_QGL_VERSION_OF_glIndexdv
+#define glIndexf CALL_THE_QGL_VERSION_OF_glIndexf
+#define glIndexfv CALL_THE_QGL_VERSION_OF_glIndexfv
+#define glIndexi CALL_THE_QGL_VERSION_OF_glIndexi
+#define glIndexiv CALL_THE_QGL_VERSION_OF_glIndexiv
+#define glIndexs CALL_THE_QGL_VERSION_OF_glIndexs
+#define glIndexsv CALL_THE_QGL_VERSION_OF_glIndexsv
+#define glIndexub CALL_THE_QGL_VERSION_OF_glIndexub
+#define glIndexubv CALL_THE_QGL_VERSION_OF_glIndexubv
+#define glInitNames CALL_THE_QGL_VERSION_OF_glInitNames
+#define glInterleavedArrays CALL_THE_QGL_VERSION_OF_glInterleavedArrays
+#define glIsEnabled CALL_THE_QGL_VERSION_OF_glIsEnabled
+#define glIsList CALL_THE_QGL_VERSION_OF_glIsList
+#define glIsTexture CALL_THE_QGL_VERSION_OF_glIsTexture
+#define glLightModelf CALL_THE_QGL_VERSION_OF_glLightModelf
+#define glLightModelfv CALL_THE_QGL_VERSION_OF_glLightModelfv
+#define glLightModeli CALL_THE_QGL_VERSION_OF_glLightModeli
+#define glLightModeliv CALL_THE_QGL_VERSION_OF_glLightModeliv
+#define glLightf CALL_THE_QGL_VERSION_OF_glLightf
+#define glLightfv CALL_THE_QGL_VERSION_OF_glLightfv
+#define glLighti CALL_THE_QGL_VERSION_OF_glLighti
+#define glLightiv CALL_THE_QGL_VERSION_OF_glLightiv
+#define glLineStipple CALL_THE_QGL_VERSION_OF_glLineStipple
+#define glLineWidth CALL_THE_QGL_VERSION_OF_glLineWidth
+#define glListBase CALL_THE_QGL_VERSION_OF_glListBase
+#define glLoadIdentity CALL_THE_QGL_VERSION_OF_glLoadIdentity
+#define glLoadMatrixd CALL_THE_QGL_VERSION_OF_glLoadMatrixd
+#define glLoadMatrixf CALL_THE_QGL_VERSION_OF_glLoadMatrixf
+#define glLoadName CALL_THE_QGL_VERSION_OF_glLoadName
+#define glLogicOp CALL_THE_QGL_VERSION_OF_glLogicOp
+#define glMap1d CALL_THE_QGL_VERSION_OF_glMap1d
+#define glMap1f CALL_THE_QGL_VERSION_OF_glMap1f
+#define glMap2d CALL_THE_QGL_VERSION_OF_glMap2d
+#define glMap2f CALL_THE_QGL_VERSION_OF_glMap2f
+#define glMapGrid1d CALL_THE_QGL_VERSION_OF_glMapGrid1d
+#define glMapGrid1f CALL_THE_QGL_VERSION_OF_glMapGrid1f
+#define glMapGrid2d CALL_THE_QGL_VERSION_OF_glMapGrid2d
+#define glMapGrid2f CALL_THE_QGL_VERSION_OF_glMapGrid2f
+#define glMaterialf CALL_THE_QGL_VERSION_OF_glMaterialf
+#define glMaterialfv CALL_THE_QGL_VERSION_OF_glMaterialfv
+#define glMateriali CALL_THE_QGL_VERSION_OF_glMateriali
+#define glMaterialiv CALL_THE_QGL_VERSION_OF_glMaterialiv
+#define glMatrixMode CALL_THE_QGL_VERSION_OF_glMatrixMode
+#define glMultMatrixd CALL_THE_QGL_VERSION_OF_glMultMatrixd
+#define glMultMatrixf CALL_THE_QGL_VERSION_OF_glMultMatrixf
+#define glNewList CALL_THE_QGL_VERSION_OF_glNewList
+#define glNormal3b CALL_THE_QGL_VERSION_OF_glNormal3b
+#define glNormal3bv CALL_THE_QGL_VERSION_OF_glNormal3bv
+#define glNormal3d CALL_THE_QGL_VERSION_OF_glNormal3d
+#define glNormal3dv CALL_THE_QGL_VERSION_OF_glNormal3dv
+#define glNormal3f CALL_THE_QGL_VERSION_OF_glNormal3f
+#define glNormal3fv CALL_THE_QGL_VERSION_OF_glNormal3fv
+#define glNormal3i CALL_THE_QGL_VERSION_OF_glNormal3i
+#define glNormal3iv CALL_THE_QGL_VERSION_OF_glNormal3iv
+#define glNormal3s CALL_THE_QGL_VERSION_OF_glNormal3s
+#define glNormal3sv CALL_THE_QGL_VERSION_OF_glNormal3sv
+#define glNormalPointer CALL_THE_QGL_VERSION_OF_glNormalPointer
+#define glOrtho CALL_THE_QGL_VERSION_OF_glOrtho
+#define glPassThrough CALL_THE_QGL_VERSION_OF_glPassThrough
+#define glPixelMapfv CALL_THE_QGL_VERSION_OF_glPixelMapfv
+#define glPixelMapuiv CALL_THE_QGL_VERSION_OF_glPixelMapuiv
+#define glPixelMapusv CALL_THE_QGL_VERSION_OF_glPixelMapusv
+#define glPixelStoref CALL_THE_QGL_VERSION_OF_glPixelStoref
+#define glPixelStorei CALL_THE_QGL_VERSION_OF_glPixelStorei
+#define glPixelTransferf CALL_THE_QGL_VERSION_OF_glPixelTransferf
+#define glPixelTransferi CALL_THE_QGL_VERSION_OF_glPixelTransferi
+#define glPixelZoom CALL_THE_QGL_VERSION_OF_glPixelZoom
+#define glPointSize CALL_THE_QGL_VERSION_OF_glPointSize
+#define glPolygonMode CALL_THE_QGL_VERSION_OF_glPolygonMode
+#define glPolygonOffset CALL_THE_QGL_VERSION_OF_glPolygonOffset
+#define glPolygonStipple CALL_THE_QGL_VERSION_OF_glPolygonStipple
+#define glPopAttrib CALL_THE_QGL_VERSION_OF_glPopAttrib
+#define glPopClientAttrib CALL_THE_QGL_VERSION_OF_glPopClientAttrib
+#define glPopMatrix CALL_THE_QGL_VERSION_OF_glPopMatrix
+#define glPopName CALL_THE_QGL_VERSION_OF_glPopName
+#define glPrioritizeTextures CALL_THE_QGL_VERSION_OF_glPrioritizeTextures
+#define glPushAttrib CALL_THE_QGL_VERSION_OF_glPushAttrib
+#define glPushClientAttrib CALL_THE_QGL_VERSION_OF_glPushClientAttrib
+#define glPushMatrix CALL_THE_QGL_VERSION_OF_glPushMatrix
+#define glPushName CALL_THE_QGL_VERSION_OF_glPushName
+#define glRasterPos2d CALL_THE_QGL_VERSION_OF_glRasterPos2d
+#define glRasterPos2dv CALL_THE_QGL_VERSION_OF_glRasterPos2dv
+#define glRasterPos2f CALL_THE_QGL_VERSION_OF_glRasterPos2f
+#define glRasterPos2fv CALL_THE_QGL_VERSION_OF_glRasterPos2fv
+#define glRasterPos2i CALL_THE_QGL_VERSION_OF_glRasterPos2i
+#define glRasterPos2iv CALL_THE_QGL_VERSION_OF_glRasterPos2iv
+#define glRasterPos2s CALL_THE_QGL_VERSION_OF_glRasterPos2s
+#define glRasterPos2sv CALL_THE_QGL_VERSION_OF_glRasterPos2sv
+#define glRasterPos3d CALL_THE_QGL_VERSION_OF_glRasterPos3d
+#define glRasterPos3dv CALL_THE_QGL_VERSION_OF_glRasterPos3dv
+#define glRasterPos3f CALL_THE_QGL_VERSION_OF_glRasterPos3f
+#define glRasterPos3fv CALL_THE_QGL_VERSION_OF_glRasterPos3fv
+#define glRasterPos3i CALL_THE_QGL_VERSION_OF_glRasterPos3i
+#define glRasterPos3iv CALL_THE_QGL_VERSION_OF_glRasterPos3iv
+#define glRasterPos3s CALL_THE_QGL_VERSION_OF_glRasterPos3s
+#define glRasterPos3sv CALL_THE_QGL_VERSION_OF_glRasterPos3sv
+#define glRasterPos4d CALL_THE_QGL_VERSION_OF_glRasterPos4d
+#define glRasterPos4dv CALL_THE_QGL_VERSION_OF_glRasterPos4dv
+#define glRasterPos4f CALL_THE_QGL_VERSION_OF_glRasterPos4f
+#define glRasterPos4fv CALL_THE_QGL_VERSION_OF_glRasterPos4fv
+#define glRasterPos4i CALL_THE_QGL_VERSION_OF_glRasterPos4i
+#define glRasterPos4iv CALL_THE_QGL_VERSION_OF_glRasterPos4iv
+#define glRasterPos4s CALL_THE_QGL_VERSION_OF_glRasterPos4s
+#define glRasterPos4sv CALL_THE_QGL_VERSION_OF_glRasterPos4sv
+#define glReadBuffer CALL_THE_QGL_VERSION_OF_glReadBuffer
+#define glReadPixels CALL_THE_QGL_VERSION_OF_glReadPixels
+#define glRectd CALL_THE_QGL_VERSION_OF_glRectd
+#define glRectdv CALL_THE_QGL_VERSION_OF_glRectdv
+#define glRectf CALL_THE_QGL_VERSION_OF_glRectf
+#define glRectfv CALL_THE_QGL_VERSION_OF_glRectfv
+#define glRecti CALL_THE_QGL_VERSION_OF_glRecti
+#define glRectiv CALL_THE_QGL_VERSION_OF_glRectiv
+#define glRects CALL_THE_QGL_VERSION_OF_glRects
+#define glRectsv CALL_THE_QGL_VERSION_OF_glRectsv
+#define glRenderMode CALL_THE_QGL_VERSION_OF_glRenderMode
+#define glRotated CALL_THE_QGL_VERSION_OF_glRotated
+#define glRotatef CALL_THE_QGL_VERSION_OF_glRotatef
+#define glScaled CALL_THE_QGL_VERSION_OF_glScaled
+#define glScalef CALL_THE_QGL_VERSION_OF_glScalef
+#define glScissor CALL_THE_QGL_VERSION_OF_glScissor
+#define glSelectBuffer CALL_THE_QGL_VERSION_OF_glSelectBuffer
+#define glShadeModel CALL_THE_QGL_VERSION_OF_glShadeModel
+#define glStencilFunc CALL_THE_QGL_VERSION_OF_glStencilFunc
+#define glStencilMask CALL_THE_QGL_VERSION_OF_glStencilMask
+#define glStencilOp CALL_THE_QGL_VERSION_OF_glStencilOp
+#define glTexCoord1d CALL_THE_QGL_VERSION_OF_glTexCoord1d
+#define glTexCoord1dv CALL_THE_QGL_VERSION_OF_glTexCoord1dv
+#define glTexCoord1f CALL_THE_QGL_VERSION_OF_glTexCoord1f
+#define glTexCoord1fv CALL_THE_QGL_VERSION_OF_glTexCoord1fv
+#define glTexCoord1i CALL_THE_QGL_VERSION_OF_glTexCoord1i
+#define glTexCoord1iv CALL_THE_QGL_VERSION_OF_glTexCoord1iv
+#define glTexCoord1s CALL_THE_QGL_VERSION_OF_glTexCoord1s
+#define glTexCoord1sv CALL_THE_QGL_VERSION_OF_glTexCoord1sv
+#define glTexCoord2d CALL_THE_QGL_VERSION_OF_glTexCoord2d
+#define glTexCoord2dv CALL_THE_QGL_VERSION_OF_glTexCoord2dv
+#define glTexCoord2f CALL_THE_QGL_VERSION_OF_glTexCoord2f
+#define glTexCoord2fv CALL_THE_QGL_VERSION_OF_glTexCoord2fv
+#define glTexCoord2i CALL_THE_QGL_VERSION_OF_glTexCoord2i
+#define glTexCoord2iv CALL_THE_QGL_VERSION_OF_glTexCoord2iv
+#define glTexCoord2s CALL_THE_QGL_VERSION_OF_glTexCoord2s
+#define glTexCoord2sv CALL_THE_QGL_VERSION_OF_glTexCoord2sv
+#define glTexCoord3d CALL_THE_QGL_VERSION_OF_glTexCoord3d
+#define glTexCoord3dv CALL_THE_QGL_VERSION_OF_glTexCoord3dv
+#define glTexCoord3f CALL_THE_QGL_VERSION_OF_glTexCoord3f
+#define glTexCoord3fv CALL_THE_QGL_VERSION_OF_glTexCoord3fv
+#define glTexCoord3i CALL_THE_QGL_VERSION_OF_glTexCoord3i
+#define glTexCoord3iv CALL_THE_QGL_VERSION_OF_glTexCoord3iv
+#define glTexCoord3s CALL_THE_QGL_VERSION_OF_glTexCoord3s
+#define glTexCoord3sv CALL_THE_QGL_VERSION_OF_glTexCoord3sv
+#define glTexCoord4d CALL_THE_QGL_VERSION_OF_glTexCoord4d
+#define glTexCoord4dv CALL_THE_QGL_VERSION_OF_glTexCoord4dv
+#define glTexCoord4f CALL_THE_QGL_VERSION_OF_glTexCoord4f
+#define glTexCoord4fv CALL_THE_QGL_VERSION_OF_glTexCoord4fv
+#define glTexCoord4i CALL_THE_QGL_VERSION_OF_glTexCoord4i
+#define glTexCoord4iv CALL_THE_QGL_VERSION_OF_glTexCoord4iv
+#define glTexCoord4s CALL_THE_QGL_VERSION_OF_glTexCoord4s
+#define glTexCoord4sv CALL_THE_QGL_VERSION_OF_glTexCoord4sv
+#define glTexCoordPointer CALL_THE_QGL_VERSION_OF_glTexCoordPointer
+#define glTexEnvf CALL_THE_QGL_VERSION_OF_glTexEnvf
+#define glTexEnvfv CALL_THE_QGL_VERSION_OF_glTexEnvfv
+#define glTexEnvi CALL_THE_QGL_VERSION_OF_glTexEnvi
+#define glTexEnviv CALL_THE_QGL_VERSION_OF_glTexEnviv
+#define glTexGend CALL_THE_QGL_VERSION_OF_glTexGend
+#define glTexGendv CALL_THE_QGL_VERSION_OF_glTexGendv
+#define glTexGenf CALL_THE_QGL_VERSION_OF_glTexGenf
+#define glTexGenfv CALL_THE_QGL_VERSION_OF_glTexGenfv
+#define glTexGeni CALL_THE_QGL_VERSION_OF_glTexGeni
+#define glTexGeniv CALL_THE_QGL_VERSION_OF_glTexGeniv
+#define glTexImage1D CALL_THE_QGL_VERSION_OF_glTexImage1D
+#define glTexImage2D CALL_THE_QGL_VERSION_OF_glTexImage2D
+#define glTexParameterf CALL_THE_QGL_VERSION_OF_glTexParameterf
+#define glTexParameterfv CALL_THE_QGL_VERSION_OF_glTexParameterfv
+#define glTexParameteri CALL_THE_QGL_VERSION_OF_glTexParameteri
+#define glTexParameteriv CALL_THE_QGL_VERSION_OF_glTexParameteriv
+#define glTexSubImage1D CALL_THE_QGL_VERSION_OF_glTexSubImage1D
+#define glTexSubImage2D CALL_THE_QGL_VERSION_OF_glTexSubImage2D
+#define glTranslated CALL_THE_QGL_VERSION_OF_glTranslated
+#define glTranslatef CALL_THE_QGL_VERSION_OF_glTranslatef
+#define glVertex2d CALL_THE_QGL_VERSION_OF_glVertex2d
+#define glVertex2dv CALL_THE_QGL_VERSION_OF_glVertex2dv
+#define glVertex2f CALL_THE_QGL_VERSION_OF_glVertex2f
+#define glVertex2fv CALL_THE_QGL_VERSION_OF_glVertex2fv
+#define glVertex2i CALL_THE_QGL_VERSION_OF_glVertex2i
+#define glVertex2iv CALL_THE_QGL_VERSION_OF_glVertex2iv
+#define glVertex2s CALL_THE_QGL_VERSION_OF_glVertex2s
+#define glVertex2sv CALL_THE_QGL_VERSION_OF_glVertex2sv
+#define glVertex3d CALL_THE_QGL_VERSION_OF_glVertex3d
+#define glVertex3dv CALL_THE_QGL_VERSION_OF_glVertex3dv
+#define glVertex3f CALL_THE_QGL_VERSION_OF_glVertex3f
+#define glVertex3fv CALL_THE_QGL_VERSION_OF_glVertex3fv
+#define glVertex3i CALL_THE_QGL_VERSION_OF_glVertex3i
+#define glVertex3iv CALL_THE_QGL_VERSION_OF_glVertex3iv
+#define glVertex3s CALL_THE_QGL_VERSION_OF_glVertex3s
+#define glVertex3sv CALL_THE_QGL_VERSION_OF_glVertex3sv
+#define glVertex4d CALL_THE_QGL_VERSION_OF_glVertex4d
+#define glVertex4dv CALL_THE_QGL_VERSION_OF_glVertex4dv
+#define glVertex4f CALL_THE_QGL_VERSION_OF_glVertex4f
+#define glVertex4fv CALL_THE_QGL_VERSION_OF_glVertex4fv
+#define glVertex4i CALL_THE_QGL_VERSION_OF_glVertex4i
+#define glVertex4iv CALL_THE_QGL_VERSION_OF_glVertex4iv
+#define glVertex4s CALL_THE_QGL_VERSION_OF_glVertex4s
+#define glVertex4sv CALL_THE_QGL_VERSION_OF_glVertex4sv
+#define glVertexPointer CALL_THE_QGL_VERSION_OF_glVertexPointer
+#define glViewport CALL_THE_QGL_VERSION_OF_glViewport
diff --git a/code/macosx/macosx_sndcore.m b/code/macosx/macosx_sndcore.m
new file mode 100755
index 0000000..a37ab0e
--- /dev/null
+++ b/code/macosx/macosx_sndcore.m
@@ -0,0 +1,325 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+// mac_snddma.c
+// all other sound mixing is portable
+
+#include "../client/snd_local.h"
+
+#include <CoreServices/CoreServices.h>
+#include <CoreAudio/AudioHardware.h>
+#include <QuickTime/QuickTime.h>
+
+// For 'ri'
+#include "../renderer/tr_local.h"
+
+#import <Foundation/NSData.h>
+#import <Foundation/NSString.h>
+
+static unsigned int submissionChunk;
+static unsigned int maxMixedSamples;
+static short *s_mixedSamples;
+static int s_chunkCount; // number of chunks submitted
+static qboolean s_isRunning;
+
+static AudioDeviceID outputDeviceID;
+static AudioStreamBasicDescription outputStreamBasicDescription;
+
+/*
+===============
+audioDeviceIOProc
+===============
+*/
+
+OSStatus audioDeviceIOProc(AudioDeviceID inDevice,
+ const AudioTimeStamp *inNow,
+ const AudioBufferList *inInputData,
+ const AudioTimeStamp *inInputTime,
+ AudioBufferList *outOutputData,
+ const AudioTimeStamp *inOutputTime,
+ void *inClientData)
+{
+ int offset;
+ short *samples;
+ unsigned int sampleIndex;
+ float *outBuffer;
+ float scale, temp;
+
+ offset = ( s_chunkCount * submissionChunk ) % maxMixedSamples;
+ samples = s_mixedSamples + offset;
+
+ assert(outOutputData->mNumberBuffers == 1);
+ assert(outOutputData->mBuffers[0].mNumberChannels == 2);
+ //assert(outOutputData->mBuffers[0].mDataByteSize == (dma.submission_chunk * sizeof(float)));
+
+ outBuffer = (float *)outOutputData->mBuffers[0].mData;
+
+ // If we have run out of samples, return silence
+ if (s_chunkCount * submissionChunk > dma.channels * s_paintedtime) {
+ memset(outBuffer, 0, sizeof(*outBuffer) * dma.submission_chunk);
+ } else {
+ scale = (1.0f / SHRT_MAX);
+ if (outputStreamBasicDescription.mSampleRate == 44100 && dma.speed == 22050) {
+ for (sampleIndex = 0; sampleIndex < dma.submission_chunk; sampleIndex+=2) {
+ // Convert the samples from shorts to floats. Scale the floats to be [-1..1].
+ temp = samples[sampleIndex + 0] * scale;
+ outBuffer[(sampleIndex<<1)+0] = temp;
+ outBuffer[(sampleIndex<<1)+2] = temp;
+
+ temp = samples[sampleIndex + 1] * scale;
+ outBuffer[(sampleIndex<<1)+1] = temp;
+ outBuffer[(sampleIndex<<1)+3] = temp;
+ }
+ } else if (outputStreamBasicDescription.mSampleRate == 44100 && dma.speed == 11025) {
+ for (sampleIndex = 0; sampleIndex < dma.submission_chunk; sampleIndex+=4) {
+ // Convert the samples from shorts to floats. Scale the floats to be [-1..1].
+ temp = samples[sampleIndex + 0] * scale;
+ outBuffer[(sampleIndex<<1)+0] = temp;
+ outBuffer[(sampleIndex<<1)+2] = temp;
+ outBuffer[(sampleIndex<<1)+4] = temp;
+ outBuffer[(sampleIndex<<1)+6] = temp;
+
+ temp = samples[sampleIndex + 1] * scale;
+ outBuffer[(sampleIndex<<1)+1] = temp;
+ outBuffer[(sampleIndex<<1)+3] = temp;
+ outBuffer[(sampleIndex<<1)+5] = temp;
+ outBuffer[(sampleIndex<<1)+7] = temp;
+ }
+ } else {
+ for (sampleIndex = 0; sampleIndex < dma.submission_chunk; sampleIndex++) {
+ // Convert the samples from shorts to floats. Scale the floats to be [-1..1].
+ outBuffer[sampleIndex] = samples[sampleIndex] * scale;
+ }
+ }
+ }
+
+ s_chunkCount++; // this is the next buffer we will submit
+ return 0;
+}
+
+
+/*
+===============
+S_MakeTestPattern
+===============
+*/
+void S_MakeTestPattern( void ) {
+ int i;
+ float v;
+ int sample;
+
+ for ( i = 0 ; i < dma.samples / 2 ; i ++ ) {
+ v = sin( M_PI * 2 * i / 64 );
+ sample = v * 0x4000;
+ ((short *)dma.buffer)[i*2] = sample;
+ ((short *)dma.buffer)[i*2+1] = sample;
+ }
+}
+
+/*
+===============
+SNDDMA_Init
+===============
+*/
+qboolean SNDDMA_Init(void)
+{
+ cvar_t *bufferSize;
+ cvar_t *chunkSize;
+ OSStatus status;
+ UInt32 propertySize, bufferByteCount;
+
+ if (s_isRunning)
+ return qtrue;
+
+ chunkSize = ri.Cvar_Get( "s_chunksize", "2048", CVAR_ARCHIVE );
+ bufferSize = ri.Cvar_Get( "s_buffersize", "16384", CVAR_ARCHIVE );
+ Com_Printf(" Chunk size = %d\n", chunkSize->integer);
+ Com_Printf("Buffer size = %d\n", bufferSize->integer);
+
+ if (!chunkSize->integer)
+ ri.Error(ERR_FATAL, "s_chunksize must be non-zero\n");
+ if (!bufferSize->integer)
+ ri.Error(ERR_FATAL, "s_buffersize must be non-zero\n");
+ if (chunkSize->integer >= bufferSize->integer)
+ ri.Error(ERR_FATAL, "s_chunksize must be less than s_buffersize\n");
+ if (bufferSize->integer % chunkSize->integer)
+ ri.Error(ERR_FATAL, "s_buffersize must be an even multiple of s_chunksize\n");
+
+ // Get the output device
+ propertySize = sizeof(outputDeviceID);
+ status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &propertySize, &outputDeviceID);
+ if (status) {
+ Com_Printf("AudioHardwareGetProperty returned %d\n", status);
+ return qfalse;
+ }
+
+ if (outputDeviceID == kAudioDeviceUnknown) {
+ Com_Printf("AudioHardwareGetProperty: outputDeviceID is kAudioDeviceUnknown\n");
+ return qfalse;
+ }
+
+ // Configure the output device
+ propertySize = sizeof(bufferByteCount);
+ bufferByteCount = chunkSize->integer * sizeof(float);
+ status = AudioDeviceSetProperty(outputDeviceID, NULL, 0, NO, kAudioDevicePropertyBufferSize, propertySize, &bufferByteCount);
+ if (status) {
+ Com_Printf("AudioDeviceSetProperty: returned %d when setting kAudioDevicePropertyBufferSize to %d\n", status, chunkSize->integer);
+ return qfalse;
+ }
+
+ propertySize = sizeof(bufferByteCount);
+ status = AudioDeviceGetProperty(outputDeviceID, 0, NO, kAudioDevicePropertyBufferSize, &propertySize, &bufferByteCount);
+ if (status) {
+ Com_Printf("AudioDeviceGetProperty: returned %d when setting kAudioDevicePropertyBufferSize\n", status);
+ return qfalse;
+ }
+
+ // Print out the device status
+ propertySize = sizeof(outputStreamBasicDescription);
+ status = AudioDeviceGetProperty(outputDeviceID, 0, NO, kAudioDevicePropertyStreamFormat, &propertySize, &outputStreamBasicDescription);
+ if (status) {
+ Com_Printf("AudioDeviceGetProperty: returned %d when getting kAudioDevicePropertyStreamFormat\n", status);
+ return qfalse;
+ }
+
+ Com_Printf("Hardware format:\n");
+ Com_Printf(" %f mSampleRate\n", outputStreamBasicDescription.mSampleRate);
+ Com_Printf(" %c%c%c%c mFormatID\n",
+ (outputStreamBasicDescription.mFormatID & 0xff000000) >> 24,
+ (outputStreamBasicDescription.mFormatID & 0x00ff0000) >> 16,
+ (outputStreamBasicDescription.mFormatID & 0x0000ff00) >> 8,
+ (outputStreamBasicDescription.mFormatID & 0x000000ff) >> 0);
+ Com_Printf(" %5d mBytesPerPacket\n", outputStreamBasicDescription.mBytesPerPacket);
+ Com_Printf(" %5d mFramesPerPacket\n", outputStreamBasicDescription.mFramesPerPacket);
+ Com_Printf(" %5d mBytesPerFrame\n", outputStreamBasicDescription.mBytesPerFrame);
+ Com_Printf(" %5d mChannelsPerFrame\n", outputStreamBasicDescription.mChannelsPerFrame);
+ Com_Printf(" %5d mBitsPerChannel\n", outputStreamBasicDescription.mBitsPerChannel);
+
+ if(outputStreamBasicDescription.mFormatID != kAudioFormatLinearPCM) {
+ Com_Printf("Default Audio Device doesn't support Linear PCM!");
+ return qfalse;
+ }
+
+ // Start sound running
+ status = AudioDeviceAddIOProc(outputDeviceID, audioDeviceIOProc, NULL);
+ if (status) {
+ Com_Printf("AudioDeviceAddIOProc: returned %d\n", status);
+ return qfalse;
+ }
+
+ submissionChunk = chunkSize->integer;
+ if (outputStreamBasicDescription.mSampleRate == 44100) {
+ submissionChunk = chunkSize->integer/2;
+ }
+ maxMixedSamples = bufferSize->integer;
+ s_mixedSamples = calloc(1, sizeof(*s_mixedSamples) * maxMixedSamples);
+ Com_Printf("Chunk Count = %d\n", (maxMixedSamples / submissionChunk));
+
+ // Tell the main app what we expect from it
+ dma.samples = maxMixedSamples;
+ dma.submission_chunk = submissionChunk;
+ dma.samplebits = 16;
+ dma.buffer = (byte *)s_mixedSamples;
+ dma.channels = outputStreamBasicDescription.mChannelsPerFrame;
+ dma.speed = 22050; //(unsigned long)outputStreamBasicDescription.mSampleRate;
+
+ // We haven't enqueued anything yet
+ s_chunkCount = 0;
+
+ status = AudioDeviceStart(outputDeviceID, audioDeviceIOProc);
+ if (status) {
+ Com_Printf("AudioDeviceStart: returned %d\n", status);
+ return qfalse;
+ }
+
+ s_isRunning = qtrue;
+
+ return qtrue;
+}
+
+/*
+===============
+SNDDMA_GetBufferDuration
+===============
+*/
+float SNDDMA_GetBufferDuration(void)
+{
+ return (float)dma.samples / (float)(dma.channels * dma.speed);
+}
+
+/*
+===============
+SNDDMA_GetDMAPos
+===============
+*/
+int SNDDMA_GetDMAPos(void)
+{
+ return s_chunkCount * dma.submission_chunk;
+}
+
+/*
+===============
+SNDDMA_Shutdown
+===============
+*/
+void SNDDMA_Shutdown(void)
+{
+ OSStatus status;
+
+ if (!s_isRunning)
+ return;
+
+ status = AudioDeviceStop(outputDeviceID, audioDeviceIOProc);
+ if (status) {
+ Com_Printf("AudioDeviceStop: returned %d\n", status);
+ return;
+ }
+
+ s_isRunning = qfalse;
+
+ status = AudioDeviceRemoveIOProc(outputDeviceID, audioDeviceIOProc);
+ if (status) {
+ Com_Printf("AudioDeviceRemoveIOProc: returned %d\n", status);
+ return;
+ }
+
+ free(s_mixedSamples);
+ s_mixedSamples = NULL;
+ dma.samples = NULL;
+}
+
+/*
+===============
+SNDDMA_BeginPainting
+===============
+*/
+void SNDDMA_BeginPainting(void) {
+}
+
+/*
+===============
+SNDDMA_Submit
+===============
+*/
+void SNDDMA_Submit(void) {
+}
+
diff --git a/code/macosx/macosx_snddma.m b/code/macosx/macosx_snddma.m
new file mode 100755
index 0000000..670a447
--- /dev/null
+++ b/code/macosx/macosx_snddma.m
@@ -0,0 +1,205 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+// mac_snddma.c
+// all other sound mixing is portable
+
+#include "../client/snd_local.h"
+#include <Carbon/Carbon.h>
+
+// For 'ri'
+#include "../renderer/tr_local.h"
+
+#import <Foundation/NSZone.h>
+
+// TJW - Different versions of SoundManager have different DMA buffer sizes. On MacOS X DP2,
+// the buffer size is 8K. On MacOS 9 it is much smaller. The SoundManager guy at Apple says
+// that the size of the buffer will be decreasing for final release to help get rid of latency.
+//#define MAX_MIXED_SAMPLES (0x8000 * 64)
+//#define SUBMISSION_CHUNK (0x100 * 64)
+
+// Original MacOS 9 sizes
+//#define MAX_MIXED_SAMPLES 0x8000
+//#define SUBMISSION_CHUNK 0x100
+
+
+static unsigned int submissionChunk;
+static unsigned int maxMixedSamples;
+
+static short *s_mixedSamples;
+static int s_chunkCount; // number of chunks submitted
+static SndChannel *s_sndChan;
+static ExtSoundHeader s_sndHeader;
+
+/*
+===============
+S_Callback
+===============
+*/
+void S_Callback( SndChannel *sc, SndCommand *cmd )
+{
+ SndCommand mySndCmd;
+ SndCommand mySndCmd2;
+ int offset;
+
+ offset = ( s_chunkCount * submissionChunk ) & (maxMixedSamples-1);
+
+ // queue up another sound buffer
+ memset( &s_sndHeader, 0, sizeof( s_sndHeader ) );
+ s_sndHeader.samplePtr = (void *)(s_mixedSamples + offset);
+ s_sndHeader.numChannels = 2;
+ s_sndHeader.sampleRate = rate22khz;
+ s_sndHeader.loopStart = 0;
+ s_sndHeader.loopEnd = 0;
+ s_sndHeader.encode = extSH;
+ s_sndHeader.baseFrequency = 1;
+ s_sndHeader.numFrames = submissionChunk / 2;
+ s_sndHeader.markerChunk = NULL;
+ s_sndHeader.instrumentChunks = NULL;
+ s_sndHeader.AESRecording = NULL;
+ s_sndHeader.sampleSize = 16;
+
+ mySndCmd.cmd = bufferCmd;
+ mySndCmd.param1 = 0;
+ mySndCmd.param2 = (int)&s_sndHeader;
+ SndDoCommand( sc, &mySndCmd, true );
+
+ // and another callback
+ mySndCmd2.cmd = callBackCmd;
+ mySndCmd2.param1 = 0;
+ mySndCmd2.param2 = 0;
+ SndDoCommand( sc, &mySndCmd2, true );
+
+ s_chunkCount++; // this is the next buffer we will submit
+}
+
+/*
+===============
+S_MakeTestPattern
+===============
+*/
+void S_MakeTestPattern( void ) {
+ int i;
+ float v;
+ int sample;
+
+ for ( i = 0 ; i < dma.samples / 2 ; i ++ ) {
+ v = sin( M_PI * 2 * i / 64 );
+ sample = v * 0x4000;
+ ((short *)dma.buffer)[i*2] = sample;
+ ((short *)dma.buffer)[i*2+1] = sample;
+ }
+}
+
+/*
+===============
+SNDDMA_Init
+===============
+*/
+qboolean SNDDMA_Init(void)
+{
+ int err;
+ cvar_t *bufferSize;
+ cvar_t *chunkSize;
+
+ chunkSize = ri.Cvar_Get( "s_chunksize", "8192", CVAR_ARCHIVE );
+ bufferSize = ri.Cvar_Get( "s_buffersize", "65536", CVAR_ARCHIVE );
+
+ if (!chunkSize->integer) {
+ ri.Error(ERR_FATAL, "snd_chunkSize must be non-zero\n");
+ }
+
+ if (!bufferSize->integer) {
+ ri.Error(ERR_FATAL, "snd_bufferSize must be non-zero\n");
+ }
+
+ if (chunkSize->integer >= bufferSize->integer) {
+ ri.Error(ERR_FATAL, "snd_chunkSize must be less than snd_bufferSize\n");
+ }
+
+ if (bufferSize->integer % chunkSize->integer) {
+ ri.Error(ERR_FATAL, "snd_bufferSize must be an even multiple of snd_chunkSize\n");
+ }
+
+ // create a sound channel
+ s_sndChan = NULL;
+ err = SndNewChannel( &s_sndChan, sampledSynth, initStereo, NewSndCallBackProc(S_Callback) );
+ if ( err ) {
+ return false;
+ }
+
+ submissionChunk = chunkSize->integer;
+ maxMixedSamples = bufferSize->integer;
+
+ s_mixedSamples = NSZoneMalloc(NULL, sizeof(*s_mixedSamples) * maxMixedSamples);
+
+ dma.channels = 2;
+ dma.samples = maxMixedSamples;
+ dma.submission_chunk = submissionChunk;
+ dma.samplebits = 16;
+ dma.speed = 22050;
+ dma.buffer = (byte *)s_mixedSamples;
+
+ // que up the first submission-chunk sized buffer
+ s_chunkCount = 0;
+
+ S_Callback( s_sndChan, NULL );
+
+ return qtrue;
+}
+
+/*
+===============
+SNDDMA_GetDMAPos
+===============
+*/
+int SNDDMA_GetDMAPos(void) {
+ return s_chunkCount * submissionChunk;
+}
+
+/*
+===============
+SNDDMA_Shutdown
+===============
+*/
+void SNDDMA_Shutdown(void) {
+ if ( s_sndChan ) {
+ SndDisposeChannel( s_sndChan, true );
+ s_sndChan = NULL;
+ }
+}
+
+/*
+===============
+SNDDMA_BeginPainting
+===============
+*/
+void SNDDMA_BeginPainting(void) {
+}
+
+/*
+===============
+SNDDMA_Submit
+===============
+*/
+void SNDDMA_Submit(void) {
+}
diff --git a/code/macosx/macosx_sys.m b/code/macosx/macosx_sys.m
new file mode 100755
index 0000000..0d8d035
--- /dev/null
+++ b/code/macosx/macosx_sys.m
@@ -0,0 +1,537 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#import "../client/client.h"
+#import "macosx_local.h"
+
+#import "dlfcn.h"
+#import "Q3Controller.h"
+
+#import <AppKit/AppKit.h>
+#import <IOKit/IOKitLib.h>
+#import <IOKit/IOBSD.h>
+#import <IOKit/storage/IOCDMedia.h>
+#import <mach/mach_error.h>
+
+#import <sys/types.h>
+#import <unistd.h>
+#import <sys/param.h>
+#import <sys/mount.h>
+#import <sys/sysctl.h>
+
+#ifdef OMNI_TIMER
+#import "macosx_timers.h"
+#endif
+
+qboolean stdin_active = qfalse;
+
+//===========================================================================
+
+int main(int argc, const char *argv[]) {
+#ifdef DEDICATED
+ Q3Controller *controller;
+
+ stdin_active = qtrue;
+ controller = [[Q3Controller alloc] init];
+ [controller quakeMain];
+ return 0;
+#else
+ return NSApplicationMain(argc, argv);
+#endif
+}
+
+//===========================================================================
+
+/*
+=================
+Sys_UnloadDll
+
+=================
+*/
+void Sys_UnloadDll( void *dllHandle ) {
+ if ( !dllHandle ) {
+ return;
+ }
+ dlclose( dllHandle );
+}
+
+/*
+=================
+Sys_LoadDll
+
+Used to load a development dll instead of a virtual machine
+=================
+*/
+extern char *FS_BuildOSPath( const char *base, const char *game, const char *qpath );
+
+void * QDECL Sys_LoadDll( const char *name, char *fqpath , int (QDECL **entryPoint)(int, ...),
+ int (QDECL *systemcalls)(int, ...) ) {
+ void *libHandle;
+ void (*dllEntry)( int (*syscallptr)(int, ...) );
+ NSString *bundlePath, *libraryPath;
+ const char *path;
+
+ // TTimo
+ // I don't understand the search strategy here. How can the Quake3 bundle know about the location
+ // of the other bundles? is that configured somewhere in XCode?
+ /*
+ bundlePath = [[NSBundle mainBundle] pathForResource: [NSString stringWithCString: name] ofType: @"bundle"];
+ libraryPath = [NSString stringWithFormat: @"%@/Contents/MacOS/%s", bundlePath, name];
+ */
+ libraryPath = [NSString stringWithFormat: @"%s.bundle/Contents/MacOS/%s", name, name];
+ if (!libraryPath)
+ return NULL;
+
+ path = [libraryPath cString];
+ Com_Printf("Loading '%s'.\n", path);
+ libHandle = dlopen( [libraryPath cString], RTLD_LAZY );
+ if (!libHandle) {
+ libHandle = dlopen( name, RTLD_LAZY );
+ if (!libHandle) {
+ Com_Printf("Error loading dll: %s\n", dlerror());
+ return NULL;
+ }
+ }
+
+ dllEntry = dlsym( libHandle, "_dllEntry" );
+ if (!dllEntry) {
+ Com_Printf("Error loading dll: No dllEntry symbol.\n");
+ dlclose(libHandle);
+ return NULL;
+ }
+
+ *entryPoint = dlsym( libHandle, "_vmMain" );
+ if (!*entryPoint) {
+ Com_Printf("Error loading dll: No vmMain symbol.\n");
+ dlclose(libHandle);
+ return NULL;
+ }
+
+ dllEntry(systemcalls);
+ return libHandle;
+}
+
+//===========================================================================
+
+char *Sys_GetClipboardData(void) // FIXME
+{
+ NSPasteboard *pasteboard;
+ NSArray *pasteboardTypes;
+
+ pasteboard = [NSPasteboard generalPasteboard];
+ pasteboardTypes = [pasteboard types];
+ if ([pasteboardTypes containsObject:NSStringPboardType]) {
+ NSString *clipboardString;
+
+ clipboardString = [pasteboard stringForType:NSStringPboardType];
+ if (clipboardString && [clipboardString length] > 0) {
+ return strdup([clipboardString cString]);
+ }
+ }
+ return NULL;
+}
+
+char *Sys_GetWholeClipboard ( void )
+{
+ return NULL;
+}
+
+void Sys_SetClipboard (const char *contents)
+{
+}
+
+
+/*
+==================
+Sys_FunctionCheckSum
+==================
+*/
+int Sys_FunctionCheckSum(void *f1) {
+ return 0;
+}
+
+/*
+==================
+Sys_MonkeyShouldBeSpanked
+==================
+*/
+int Sys_MonkeyShouldBeSpanked( void ) {
+ return 0;
+}
+
+//===========================================================================
+
+void Sys_BeginProfiling(void)
+{
+}
+
+void Sys_EndProfiling(void)
+{
+}
+
+//===========================================================================
+
+/*
+================
+Sys_Init
+
+The cvar and file system has been setup, so configurations are loaded
+================
+*/
+void Sys_Init(void)
+{
+#ifdef OMNI_TIMER
+ InitializeTimers();
+ OTStackPushRoot(rootNode);
+#endif
+
+ NET_Init();
+ Sys_InitInput();
+}
+
+/*
+=================
+Sys_Shutdown
+=================
+*/
+void Sys_Shutdown(void)
+{
+ Com_Printf( "----- Sys_Shutdown -----\n" );
+ Sys_EndProfiling();
+ Sys_ShutdownInput();
+ Com_Printf( "------------------------\n" );
+}
+
+void Sys_Error(const char *error, ...)
+{
+ va_list argptr;
+ NSString *formattedString;
+
+ Sys_Shutdown();
+
+ va_start(argptr,error);
+ formattedString = [[NSString alloc] initWithFormat:[NSString stringWithCString:error] arguments:argptr];
+ va_end(argptr);
+
+ NSLog(@"Sys_Error: %@", formattedString);
+ NSRunAlertPanel(@"Quake 3 Error", formattedString, nil, nil, nil);
+
+ Sys_Quit();
+}
+
+void Sys_Quit(void)
+{
+ Sys_Shutdown();
+ [NSApp terminate:nil];
+}
+
+/*
+================
+Sys_Print
+
+This is called for all console output, even if the game is running
+full screen and the dedicated console window is hidden.
+================
+*/
+
+char *ansiColors[8] =
+ { "\033[30m" , /* ANSI Black */
+ "\033[31m" , /* ANSI Red */
+ "\033[32m" , /* ANSI Green */
+ "\033[33m" , /* ANSI Yellow */
+ "\033[34m" , /* ANSI Blue */
+ "\033[36m" , /* ANSI Cyan */
+ "\033[35m" , /* ANSI Magenta */
+ "\033[37m" }; /* ANSI White */
+
+void Sys_Print(const char *text)
+{
+#if 0
+ /* Okay, this is a stupid hack, but what the hell, I was bored. ;) */
+ const char *scan = text;
+ int index;
+
+ /* Make sure terminal mode is reset at the start of the line... */
+ fputs("\033[0m", stdout);
+
+ while(*scan) {
+ /* See if we have a color control code. If so, snarf the character,
+ print what we have so far, print the ANSI Terminal color code,
+ skip over the color control code and continue */
+ if(Q_IsColorString(scan)) {
+ index = ColorIndex(scan[1]);
+
+ /* Flush current message */
+ if(scan != text) {
+ fwrite(text, scan - text, 1, stdout);
+ }
+
+ /* Write ANSI color code */
+ fputs(ansiColors[index], stdout);
+
+ /* Reset search */
+ text = scan+2;
+ scan = text;
+ continue;
+ }
+ scan++;
+ }
+
+ /* Flush whatever's left */
+ fputs(text, stdout);
+
+ /* Make sure terminal mode is reset at the end of the line too... */
+ fputs("\033[0m", stdout);
+
+#else
+ fputs(text, stdout);
+#endif
+}
+
+
+
+/*
+================
+Sys_CheckCD
+
+Return true if the proper CD is in the drive
+================
+*/
+
+qboolean Sys_ObjectIsCDRomDevice(io_object_t object)
+{
+ CFStringRef value;
+ kern_return_t krc;
+ CFDictionaryRef properties;
+ qboolean isCDROM = qfalse;
+ io_iterator_t parentIterator;
+ io_object_t parent;
+
+ krc = IORegistryEntryCreateCFProperties(object, &properties, kCFAllocatorDefault, (IOOptionBits)0);
+ if (krc != KERN_SUCCESS) {
+ fprintf(stderr, "IORegistryEntryCreateCFProperties returned 0x%08x -- %s\n", krc, mach_error_string(krc));
+ return qfalse;
+ }
+
+ //NSLog(@"properties = %@", properties);
+
+ // See if this is a CD-ROM
+ value = CFDictionaryGetValue(properties, CFSTR(kIOCDMediaTypeKey));
+ if (value && CFStringCompare(value, CFSTR("CD-ROM"), 0) == kCFCompareEqualTo)
+ isCDROM = qtrue;
+ CFRelease(properties);
+
+ // If it isn't check each of its parents. It seems that the parent enumerator only returns the immediate parent. Maybe the plural indicates that an object can have multiple direct parents. So, we'll call ourselves recursively for each parent.
+ if (!isCDROM) {
+ krc = IORegistryEntryGetParentIterator(object, kIOServicePlane, &parentIterator);
+ if (krc != KERN_SUCCESS) {
+ fprintf(stderr, "IOServiceGetMatchingServices returned 0x%08x -- %s\n",
+ krc, mach_error_string(krc));
+ } else {
+ while (!isCDROM && (parent = IOIteratorNext(parentIterator))) {
+ if (Sys_ObjectIsCDRomDevice(parent))
+ isCDROM = qtrue;
+ IOObjectRelease(parent);
+ }
+
+ IOObjectRelease(parentIterator);
+ }
+ }
+
+ //NSLog(@"Sys_ObjectIsCDRomDevice -> %d", isCDROM);
+ return isCDROM;
+}
+
+qboolean Sys_IsCDROMDevice(const char *deviceName)
+{
+ kern_return_t krc;
+ io_iterator_t deviceIterator;
+ mach_port_t masterPort;
+ io_object_t object;
+ qboolean isCDROM = qfalse;
+
+ krc = IOMasterPort(bootstrap_port, &masterPort);
+ if (krc != KERN_SUCCESS) {
+ fprintf(stderr, "IOMasterPort returned 0x%08x -- %s\n", krc, mach_error_string(krc));
+ return qfalse;
+ }
+
+ // Get an iterator for this BSD device. If it is a CD, it will likely only be one partition of the larger CD-ROM device.
+ krc = IOServiceGetMatchingServices(masterPort,
+ IOBSDNameMatching(masterPort, 0, deviceName),
+ &deviceIterator);
+ if (krc != KERN_SUCCESS) {
+ fprintf(stderr, "IOServiceGetMatchingServices returned 0x%08x -- %s\n",
+ krc, mach_error_string(krc));
+ return qfalse;
+ }
+
+ while (!isCDROM && (object = IOIteratorNext(deviceIterator))) {
+ if (Sys_ObjectIsCDRomDevice(object)) {
+ isCDROM = qtrue;
+ }
+ IOObjectRelease(object);
+ }
+
+ IOObjectRelease(deviceIterator);
+
+ //NSLog(@"Sys_IsCDROMDevice -> %d", isCDROM);
+ return isCDROM;
+}
+
+qboolean Sys_CheckCD( void )
+{
+ // DO NOT just return success here if we have a library directory.
+ // Actually look for the CD.
+
+ // We'll look through the actual mount points rather than just looking
+ // for a particular directory since (a) the mount point may change
+ // between OS version (/foo in Public Beta, /Volumes/foo after Public Beta)
+ // and (b) this way someone can't just create a directory and warez the files.
+
+ unsigned int mountCount;
+ struct statfs *mounts;
+
+ mountCount = getmntinfo(&mounts, MNT_NOWAIT);
+ if (mountCount <= 0) {
+ perror("getmntinfo");
+#if 1 // Q3:TA doesn't need a CD, but we still need to locate it to allow for partial installs
+ return qtrue;
+#else
+ return qfalse;
+#endif
+ }
+
+ while (mountCount--) {
+ const char *lastComponent;
+
+ if ((mounts[mountCount].f_flags & MNT_RDONLY) != MNT_RDONLY) {
+ // Should have been a read only CD... this isn't it
+ continue;
+ }
+
+ if ((mounts[mountCount].f_flags & MNT_LOCAL) != MNT_LOCAL) {
+ // Should have been a local filesystem
+ continue;
+ }
+
+ lastComponent = strrchr(mounts[mountCount].f_mntonname, '/');
+ if (!lastComponent) {
+ // No slash in the mount point! How is that possible?
+ continue;
+ }
+
+ // Skip the slash and look for the game name
+ lastComponent++;
+ if ((strcasecmp(lastComponent, "Quake3") != 0)) {
+ continue;
+ }
+
+
+#if 0
+ fprintf(stderr, "f_bsize: %d\n", mounts[mountCount].f_bsize);
+ fprintf(stderr, "f_blocks: %d\n", mounts[mountCount].f_blocks);
+ fprintf(stderr, "type: %d\n", mounts[mountCount].f_type);
+ fprintf(stderr, "flags: %d\n", mounts[mountCount].f_flags);
+ fprintf(stderr, "fstype: %s\n", mounts[mountCount].f_fstypename);
+ fprintf(stderr, "f_mntonname: %s\n", mounts[mountCount].f_mntonname);
+ fprintf(stderr, "f_mntfromname: %s\n", mounts[mountCount].f_mntfromname);
+ fprintf(stderr, "\n\n");
+#endif
+
+ lastComponent = strrchr(mounts[mountCount].f_mntfromname, '/');
+ if (!lastComponent) {
+ // No slash in the device name! How is that possible?
+ continue;
+ }
+ lastComponent++;
+ if (!Sys_IsCDROMDevice(lastComponent))
+ continue;
+
+ // This looks good
+ Sys_SetDefaultCDPath(mounts[mountCount].f_mntonname);
+ return qtrue;
+ }
+
+#if 1 // Q3:TA doesn't need a CD, but we still need to locate it to allow for partial installs
+ return qtrue;
+#else
+ return qfalse;
+#endif
+}
+
+
+//===================================================================
+
+void Sys_BeginStreamedFile( fileHandle_t f, int readAhead ) {
+}
+
+void Sys_EndStreamedFile( fileHandle_t f ) {
+}
+
+int Sys_StreamedRead( void *buffer, int size, int count, fileHandle_t f ) {
+ return FS_Read( buffer, size * count, f );
+}
+
+void Sys_StreamSeek( fileHandle_t f, int offset, int origin ) {
+ FS_Seek( f, offset, origin );
+}
+
+
+void OutputDebugString(char * s)
+{
+#ifdef DEBUG
+ fprintf(stderr, "%s", s);
+#endif
+}
+
+/*
+==================
+Sys_LowPhysicalMemory()
+==================
+*/
+#define MEM_THRESHOLD 96*1024*1024
+
+qboolean Sys_LowPhysicalMemory()
+{
+ return NSRealMemoryAvailable() <= MEM_THRESHOLD;
+}
+
+static unsigned int _Sys_ProcessorCount = 0;
+
+unsigned int Sys_ProcessorCount()
+{
+ if (!_Sys_ProcessorCount) {
+ int name[] = {CTL_HW, HW_NCPU};
+ size_t size;
+
+ size = sizeof(_Sys_ProcessorCount);
+ if (sysctl(name, 2, &_Sys_ProcessorCount, &size, NULL, 0) < 0) {
+ perror("sysctl");
+ _Sys_ProcessorCount = 1;
+ } else {
+ Com_Printf("System processor count is %d\n", _Sys_ProcessorCount);
+ }
+ }
+
+ return _Sys_ProcessorCount;
+}
+
diff --git a/code/macosx/macosx_timers.h b/code/macosx/macosx_timers.h
new file mode 100755
index 0000000..a176fe8
--- /dev/null
+++ b/code/macosx/macosx_timers.h
@@ -0,0 +1,56 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifdef OMNI_TIMER
+
+#import <OmniTimer/OmniTimer.h>
+
+#define OTSTART(node) OTStackPush(node)
+#define OTSTOP(node) OTStackPop()
+
+extern OTStackNode *rootNode;
+extern OTStackNode *markFragmentsNode1;
+extern OTStackNode *markFragmentsNode2;
+extern OTStackNode *markFragmentsGrid;
+extern OTStackNode *markFragmentsNode4;
+extern OTStackNode *addMarkFragmentsNode;
+extern OTStackNode *chopPolyNode;
+extern OTStackNode *boxTraceNode;
+extern OTStackNode *boxOnPlaneSideNode;
+extern OTStackNode *recursiveWorldNode;
+extern OTStackNode *surfaceAnimNode;
+extern OTStackNode *surfaceFaceNode;
+extern OTStackNode *surfaceMeshNode;
+extern OTStackNode *surfaceEndNode;
+extern OTStackNode *shadowEndNode;
+extern OTStackNode *stageIteratorGenericNode;
+extern OTStackNode *computeColorAndTexNode;
+extern OTStackNode *mp3DecodeNode;
+
+extern void InitializeTimers();
+
+#else
+
+#define OTSTART(node)
+#define OTSTOP(node)
+
+#endif
+
diff --git a/code/macosx/macosx_timers.m b/code/macosx/macosx_timers.m
new file mode 100755
index 0000000..fad50c2
--- /dev/null
+++ b/code/macosx/macosx_timers.m
@@ -0,0 +1,75 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifdef OMNI_TIMER
+
+#import "macosx_timers.h"
+
+#import <Foundation/NSString.h>
+#import <stdio.h>
+
+OTStackNode *rootNode;
+OTStackNode *markFragmentsNode1;
+OTStackNode *markFragmentsNode2;
+OTStackNode *markFragmentsGrid;
+OTStackNode *markFragmentsNode4;
+OTStackNode *addMarkFragmentsNode;
+OTStackNode *chopPolyNode;
+OTStackNode *boxTraceNode;
+OTStackNode *boxOnPlaneSideNode;
+OTStackNode *recursiveWorldNode;
+OTStackNode *surfaceAnimNode;
+OTStackNode *surfaceFaceNode;
+OTStackNode *surfaceMeshNode;
+OTStackNode *surfaceEndNode;
+OTStackNode *shadowEndNode;
+OTStackNode *stageIteratorGenericNode;
+OTStackNode *computeColorAndTexNode;
+OTStackNode *mp3DecodeNode;
+
+void InitializeTimers()
+{
+ const char *env;
+
+ OTSetup();
+
+ rootNode = OTStackNodeCreate("root");
+ markFragmentsNode1 = OTStackNodeCreate("R_MarkFragments 1");
+ markFragmentsNode2 = OTStackNodeCreate("R_MarkFragments 2");
+ markFragmentsGrid = OTStackNodeCreate("R_MarkFragmentsGrid");
+ markFragmentsNode4 = OTStackNodeCreate("R_MarkFragments 4");
+ addMarkFragmentsNode = OTStackNodeCreate("R_AddMarkFragments");
+ chopPolyNode = OTStackNodeCreate("R_ChopPolyBehindPlane");
+ boxTraceNode = OTStackNodeCreate("CM_BoxTrace");
+ boxOnPlaneSideNode = OTStackNodeCreate("BoxOnPlaneSide");
+ recursiveWorldNode = OTStackNodeCreate("R_RecursiveWorldNode");
+ surfaceAnimNode = OTStackNodeCreate("RB_SurfaceAnim");
+ surfaceFaceNode = OTStackNodeCreate("RB_SurfaceFace");
+ surfaceMeshNode = OTStackNodeCreate("RB_SurfaceMesh");
+ surfaceEndNode = OTStackNodeCreate("RB_EndSurface");
+ shadowEndNode = OTStackNodeCreate("RB_ShadowTessEnd");
+ stageIteratorGenericNode = OTStackNodeCreate("RB_StageIteratorGeneric");
+ computeColorAndTexNode = OTStackNodeCreate("ComputeColors & ComputeTexCoords");
+ mp3DecodeNode = OTStackNodeCreate("MP3Stream_Decode");
+}
+
+#endif // OMNI_TIMER
+
diff --git a/code/macosx/timedemo.zsh b/code/macosx/timedemo.zsh
new file mode 100755
index 0000000..d3de235
--- /dev/null
+++ b/code/macosx/timedemo.zsh
@@ -0,0 +1,26 @@
+#!/bin/zsh
+
+buildRoot=./build
+executable=$buildRoot/Quake3.app/Contents/MacOS/Quake3
+ls -l $executable
+
+flags="$flags +set timedemo 1"
+flags="$flags +set s_initsound 0"
+flags="$flags +set vm_cgame 1"
+flags="$flags +set vm_game 1"
+flags="$flags +set r_texturebits 16"
+flags="$flags +set r_depthbits 16"
+flags="$flags +set r_colorbits 16"
+flags="$flags +set stencilbits 8"
+
+flags="$flags +set r_appleTransformHint 1"
+
+echo flags=$flags
+
+function demo {
+ echo Demo $*
+ $executable $flags +demo $* |& egrep "(seconds|VM)"
+}
+
+demo foo
+
diff --git a/code/null/mac_net.c b/code/null/mac_net.c
new file mode 100755
index 0000000..175535a
--- /dev/null
+++ b/code/null/mac_net.c
@@ -0,0 +1,65 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "../game/q_shared.h"
+#include "../qcommon/qcommon.h"
+
+/*
+=============
+NET_StringToAdr
+
+localhost
+idnewt
+idnewt:28000
+192.246.40.70
+192.246.40.70:28000
+=============
+*/
+qboolean NET_StringToAdr (char *s, netadr_t *a)
+{
+ if (!strcmp (s, "localhost")) {
+ memset (a, 0, sizeof(*a));
+ a->type = NA_LOOPBACK;
+ return true;
+ }
+
+ return false;
+}
+
+/*
+==================
+Sys_SendPacket
+==================
+*/
+void Sys_SendPacket( int length, void *data, netadr_t to ) {
+}
+
+/*
+==================
+Sys_GetPacket
+
+Never called by the game logic, just the system event queing
+==================
+*/
+qboolean Sys_GetPacket ( netadr_t *net_from, msg_t *net_message ) {
+ return false;
+}
diff --git a/code/null/null_client.c b/code/null/null_client.c
new file mode 100755
index 0000000..2a495cd
--- /dev/null
+++ b/code/null/null_client.c
@@ -0,0 +1,91 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "../client/client.h"
+
+cvar_t *cl_shownet;
+
+void CL_Shutdown( void ) {
+}
+
+void CL_Init( void ) {
+ cl_shownet = Cvar_Get ("cl_shownet", "0", CVAR_TEMP );
+}
+
+void CL_MouseEvent( int dx, int dy, int time ) {
+}
+
+void Key_WriteBindings( fileHandle_t f ) {
+}
+
+void CL_Frame ( int msec ) {
+}
+
+void CL_PacketEvent( netadr_t from, msg_t *msg ) {
+}
+
+void CL_CharEvent( int key ) {
+}
+
+void CL_Disconnect( qboolean showMainMenu ) {
+}
+
+void CL_MapLoading( void ) {
+}
+
+qboolean CL_GameCommand( void ) {
+ return qfalse; // bk001204 - non-void
+}
+
+void CL_KeyEvent (int key, qboolean down, unsigned time) {
+}
+
+qboolean UI_GameCommand( void ) {
+ return qfalse;
+}
+
+void CL_ForwardCommandToServer( const char *string ) {
+}
+
+void CL_ConsolePrint( char *txt ) {
+}
+
+void CL_JoystickEvent( int axis, int value, int time ) {
+}
+
+void CL_InitKeyCommands( void ) {
+}
+
+void CL_CDDialog( void ) {
+}
+
+void CL_FlushMemory( void ) {
+}
+
+void CL_StartHunkUsers( void ) {
+}
+
+// bk001119 - added new dummy for sv_init.c
+void CL_ShutdownAll(void) {};
+
+// bk001208 - added new dummy (RC4)
+qboolean CL_CDKeyValidate( const char *key, const char *checksum ) { return qtrue; }
diff --git a/code/null/null_glimp.c b/code/null/null_glimp.c
new file mode 100755
index 0000000..4ebe417
--- /dev/null
+++ b/code/null/null_glimp.c
@@ -0,0 +1,56 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "../renderer/tr_local.h"
+
+
+qboolean ( * qwglSwapIntervalEXT)( int interval );
+void ( * qglMultiTexCoord2fARB )( GLenum texture, float s, float t );
+void ( * qglActiveTextureARB )( GLenum texture );
+void ( * qglClientActiveTextureARB )( GLenum texture );
+
+
+void ( * qglLockArraysEXT)( int, int);
+void ( * qglUnlockArraysEXT) ( void );
+
+
+void GLimp_EndFrame( void ) {
+}
+
+int GLimp_Init( void )
+{
+}
+
+void GLimp_Shutdown( void ) {
+}
+
+void GLimp_EnableLogging( qboolean enable ) {
+}
+
+void GLimp_LogComment( char *comment ) {
+}
+
+qboolean QGL_Init( const char *dllname ) {
+ return qtrue;
+}
+
+void QGL_Shutdown( void ) {
+}
diff --git a/code/null/null_input.c b/code/null/null_input.c
new file mode 100755
index 0000000..e0efa24
--- /dev/null
+++ b/code/null/null_input.c
@@ -0,0 +1,35 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "../client/client.h"
+
+void IN_Init( void ) {
+}
+
+void IN_Frame (void) {
+}
+
+void IN_Shutdown( void ) {
+}
+
+void Sys_SendKeyEvents (void) {
+}
+
diff --git a/code/null/null_main.c b/code/null/null_main.c
new file mode 100755
index 0000000..e07fd9a
--- /dev/null
+++ b/code/null/null_main.c
@@ -0,0 +1,116 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// sys_null.h -- null system driver to aid porting efforts
+
+#include <errno.h>
+#include <stdio.h>
+#include "../qcommon/qcommon.h"
+
+int sys_curtime;
+
+
+//===================================================================
+
+void Sys_BeginStreamedFile( FILE *f, int readAhead ) {
+}
+
+void Sys_EndStreamedFile( FILE *f ) {
+}
+
+int Sys_StreamedRead( void *buffer, int size, int count, FILE *f ) {
+ return fread( buffer, size, count, f );
+}
+
+void Sys_StreamSeek( FILE *f, int offset, int origin ) {
+ fseek( f, offset, origin );
+}
+
+
+//===================================================================
+
+
+void Sys_mkdir ( const char *path ) {
+}
+
+void Sys_Error (char *error, ...) {
+ va_list argptr;
+
+ printf ("Sys_Error: ");
+ va_start (argptr,error);
+ vprintf (error,argptr);
+ va_end (argptr);
+ printf ("\n");
+
+ exit (1);
+}
+
+void Sys_Quit (void) {
+ exit (0);
+}
+
+void Sys_UnloadGame (void) {
+}
+
+void *Sys_GetGameAPI (void *parms) {
+ return NULL;
+}
+
+char *Sys_GetClipboardData( void ) {
+ return NULL;
+}
+
+int Sys_Milliseconds (void) {
+ return 0;
+}
+
+void Sys_Mkdir (char *path) {
+}
+
+char *Sys_FindFirst (char *path, unsigned musthave, unsigned canthave) {
+ return NULL;
+}
+
+char *Sys_FindNext (unsigned musthave, unsigned canthave) {
+ return NULL;
+}
+
+void Sys_FindClose (void) {
+}
+
+void Sys_Init (void) {
+}
+
+
+void Sys_EarlyOutput( char *string ) {
+ printf( "%s", string );
+}
+
+
+void main (int argc, char **argv) {
+ Com_Init (argc, argv);
+
+ while (1) {
+ Com_Frame( );
+ }
+}
+
+
diff --git a/code/null/null_net.c b/code/null/null_net.c
new file mode 100755
index 0000000..c375419
--- /dev/null
+++ b/code/null/null_net.c
@@ -0,0 +1,64 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "../qcommon/qcommon.h"
+
+/*
+=============
+NET_StringToAdr
+
+localhost
+idnewt
+idnewt:28000
+192.246.40.70
+192.246.40.70:28000
+=============
+*/
+qboolean NET_StringToAdr (char *s, netadr_t *a)
+{
+ if (!strcmp (s, "localhost")) {
+ memset (a, 0, sizeof(*a));
+ a->type = NA_LOOPBACK;
+ return true;
+ }
+
+ return false;
+}
+
+/*
+==================
+Sys_SendPacket
+==================
+*/
+void Sys_SendPacket( int length, void *data, netadr_t to ) {
+}
+
+/*
+==================
+Sys_GetPacket
+
+Never called by the game logic, just the system event queing
+==================
+*/
+qboolean Sys_GetPacket ( netadr_t *net_from, msg_t *net_message ) {
+ return false;
+}
diff --git a/code/null/null_snddma.c b/code/null/null_snddma.c
new file mode 100755
index 0000000..bdbfbf5
--- /dev/null
+++ b/code/null/null_snddma.c
@@ -0,0 +1,60 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+// snddma_null.c
+// all other sound mixing is portable
+
+#include "../client/client.h"
+
+qboolean SNDDMA_Init(void)
+{
+ return qfalse;
+}
+
+int SNDDMA_GetDMAPos(void)
+{
+ return 0;
+}
+
+void SNDDMA_Shutdown(void)
+{
+}
+
+void SNDDMA_BeginPainting (void)
+{
+}
+
+void SNDDMA_Submit(void)
+{
+}
+
+// bk001119 - added boolean flag, match client/snd_public.h
+sfxHandle_t S_RegisterSound( const char *name, qboolean compressed )
+{
+ return 0;
+}
+
+void S_StartLocalSound( sfxHandle_t sfxHandle, int channelNum ) {
+}
+
+void S_ClearSoundBuffer( void ) {
+}
diff --git a/code/opts.lnt b/code/opts.lnt
new file mode 100755
index 0000000..7f238de
--- /dev/null
+++ b/code/opts.lnt
@@ -0,0 +1,26 @@
+-e64 // type mismatch (enum to int)
+-e641 // converting enum to int
+-e734 // loss of precision
+-e736 // loss of precision
+-e747 // float to double prototype coersion
+-e534 // ignoring return value
+-e524 // loss of precision (float to int)
+-e732 // loss of sign (float to unsigned char)
+-e702 // shift right of signed quantity
+-e737 // loss of sign bit (int to unsigned int)
+-e713 // loss of precision (unsigned int to int)
+-e701 // shift left of signed quantity
+
+-e765 // external could be made static
+
+-d__LINT__
+-ig:\quake3\bin_nt\supplement\ansi
+-ig:\quake3\bin_nt\supplement
+-igame
+-ibotai
+-icgame
+-igame
+-iserver
+-iclient
+-iqcommon
+-irenderer
diff --git a/code/q3_ui/Conscript b/code/q3_ui/Conscript
new file mode 100755
index 0000000..2387e25
--- /dev/null
+++ b/code/q3_ui/Conscript
@@ -0,0 +1,93 @@
+# Q3 ui building
+
+# qvm building against native:
+# only native has ui_syscalls.c
+# qvm uses a ui_syscalls.asm with equ stubs
+# qvm has additional bg_lib.c
+
+Import qw( BASE_CFLAGS TARGET_DIR INSTALL_DIR NO_VM NO_SO CC CXX LINK );
+
+$env = new cons(
+ # the code has the very bad habit of doing things like #include "../ui/ui_shared.h"
+ # this seems to confuse the dependency analysis, explicit toplevel includes seem to fix
+ CPPPATH => '#cgame:#game:#q3_ui',
+ CC => $CC,
+ CXX => $CXX,
+ LINK => $LINK,
+ ENV => { PATH => $ENV{PATH}, HOME => $ENV{HOME} },
+ CFLAGS => $BASE_CFLAGS . '-fPIC',
+ LDFLAGS => '-shared -ldl -lm'
+);
+
+# qvm building
+# we heavily customize the cons environment
+$vm_env = new cons(
+ # the code has the very bad habit of doing things like #include "../ui/ui_shared.h"
+ # this seems to confuse the dependency analysis, explicit toplevel includes seem to fix
+ CPPPATH => '#cgame:#game:#q3_ui',
+ CC => 'q3lcc',
+ CCCOM => '%CC %CFLAGS %_IFLAGS -c %< -o %>',
+ SUFOBJ => '.asm',
+ LINK => 'q3asm',
+ CFLAGS => '-DQ3_VM -S -Wf-target=bytecode -Wf-g',
+ # need to know where to find the compiler tools
+ ENV => { PATH => $ENV{PATH} . ":./qvmtools", },
+);
+
+# the file with vmMain function MUST be the first one of the list
+@FILES = qw(
+ ui_main.c
+ ../game/bg_misc.c
+ ../game/q_math.c
+ ../game/q_shared.c
+ ui_addbots.c
+ ui_atoms.c
+ ui_cdkey.c
+ ui_cinematics.c
+ ui_confirm.c
+ ui_connect.c
+ ui_controls2.c
+ ui_credits.c
+ ui_demo2.c
+ ui_display.c
+ ui_gameinfo.c
+ ui_ingame.c
+ ui_menu.c
+ ui_mfield.c
+ ui_mods.c
+ ui_network.c
+ ui_options.c
+ ui_playermodel.c
+ ui_players.c
+ ui_playersettings.c
+ ui_preferences.c
+ ui_qmenu.c
+ ui_removebots.c
+ ui_serverinfo.c
+ ui_servers2.c
+ ui_setup.c
+ ui_sound.c
+ ui_sparena.c
+ ui_specifyserver.c
+ ui_splevel.c
+ ui_sppostgame.c
+ ui_spskill.c
+ ui_startserver.c
+ ui_team.c
+ ui_teamorders.c
+ ui_video.c
+ );
+$FILESREF = \@FILES;
+
+if ($NO_SO eq 0)
+{
+ Program $env 'uii386.so', @$FILESREF, '../ui/ui_syscalls.c';
+ Install $env $INSTALL_DIR, 'uii386.so';
+}
+if ($NO_VM eq 0)
+{
+ Depends $vm_env 'ui.qvm', '#qvmtools/q3lcc';
+ Depends $vm_env 'ui.qvm', '#qvmtools/q3asm';
+ Program $vm_env 'ui.qvm', @$FILESREF, '../game/bg_lib.c', '../ui/ui_syscalls.asm';
+ Install $vm_env $INSTALL_DIR . '/vm', 'ui.qvm';
+}
diff --git a/code/q3_ui/compile.bat b/code/q3_ui/compile.bat
new file mode 100755
index 0000000..8299251
--- /dev/null
+++ b/code/q3_ui/compile.bat
@@ -0,0 +1,2 @@
+lcc -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\ui %1
+
diff --git a/code/q3_ui/keycodes.h b/code/q3_ui/keycodes.h
new file mode 100755
index 0000000..a1a0f1f
--- /dev/null
+++ b/code/q3_ui/keycodes.h
@@ -0,0 +1,163 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#ifndef __KEYCODES_H__
+#define __KEYCODES_H__
+
+//
+// these are the key numbers that should be passed to KeyEvent
+//
+
+// normal keys should be passed as lowercased ascii
+
+typedef enum {
+ K_TAB = 9,
+ K_ENTER = 13,
+ K_ESCAPE = 27,
+ K_SPACE = 32,
+
+ K_BACKSPACE = 127,
+
+ K_COMMAND = 128,
+ K_CAPSLOCK,
+ K_POWER,
+ K_PAUSE,
+
+ K_UPARROW,
+ K_DOWNARROW,
+ K_LEFTARROW,
+ K_RIGHTARROW,
+
+ K_ALT,
+ K_CTRL,
+ K_SHIFT,
+ K_INS,
+ K_DEL,
+ K_PGDN,
+ K_PGUP,
+ K_HOME,
+ K_END,
+
+ K_F1,
+ K_F2,
+ K_F3,
+ K_F4,
+ K_F5,
+ K_F6,
+ K_F7,
+ K_F8,
+ K_F9,
+ K_F10,
+ K_F11,
+ K_F12,
+ K_F13,
+ K_F14,
+ K_F15,
+
+ K_KP_HOME,
+ K_KP_UPARROW,
+ K_KP_PGUP,
+ K_KP_LEFTARROW,
+ K_KP_5,
+ K_KP_RIGHTARROW,
+ K_KP_END,
+ K_KP_DOWNARROW,
+ K_KP_PGDN,
+ K_KP_ENTER,
+ K_KP_INS,
+ K_KP_DEL,
+ K_KP_SLASH,
+ K_KP_MINUS,
+ K_KP_PLUS,
+ K_KP_NUMLOCK,
+ K_KP_STAR,
+ K_KP_EQUALS,
+
+ K_MOUSE1,
+ K_MOUSE2,
+ K_MOUSE3,
+ K_MOUSE4,
+ K_MOUSE5,
+
+ K_MWHEELDOWN,
+ K_MWHEELUP,
+
+ K_JOY1,
+ K_JOY2,
+ K_JOY3,
+ K_JOY4,
+ K_JOY5,
+ K_JOY6,
+ K_JOY7,
+ K_JOY8,
+ K_JOY9,
+ K_JOY10,
+ K_JOY11,
+ K_JOY12,
+ K_JOY13,
+ K_JOY14,
+ K_JOY15,
+ K_JOY16,
+ K_JOY17,
+ K_JOY18,
+ K_JOY19,
+ K_JOY20,
+ K_JOY21,
+ K_JOY22,
+ K_JOY23,
+ K_JOY24,
+ K_JOY25,
+ K_JOY26,
+ K_JOY27,
+ K_JOY28,
+ K_JOY29,
+ K_JOY30,
+ K_JOY31,
+ K_JOY32,
+
+ K_AUX1,
+ K_AUX2,
+ K_AUX3,
+ K_AUX4,
+ K_AUX5,
+ K_AUX6,
+ K_AUX7,
+ K_AUX8,
+ K_AUX9,
+ K_AUX10,
+ K_AUX11,
+ K_AUX12,
+ K_AUX13,
+ K_AUX14,
+ K_AUX15,
+ K_AUX16,
+
+ K_LAST_KEY // this had better be <256!
+} keyNum_t;
+
+
+// The menu code needs to get both key and char events, but
+// to avoid duplicating the paths, the char events are just
+// distinguished by or'ing in K_CHAR_FLAG (ugly)
+#define K_CHAR_FLAG 1024
+
+#endif
diff --git a/code/q3_ui/q3_ui.bat b/code/q3_ui/q3_ui.bat
new file mode 100755
index 0000000..b86f4f6
--- /dev/null
+++ b/code/q3_ui/q3_ui.bat
@@ -0,0 +1,100 @@
+rem make sure we have a safe environement
+set LIBRARY=
+set INCLUDE=
+
+mkdir vm
+cd vm
+
+set cc=lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui %1
+
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_main.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_cdkey.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_ingame.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_serverinfo.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_confirm.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_setup.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../../game/bg_misc.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../../game/bg_lib.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../../game/q_math.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../../game/q_shared.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_gameinfo.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_atoms.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_connect.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_controls2.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_demo2.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_mfield.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_credits.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_menu.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_options.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_display.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_sound.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_network.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_playermodel.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_players.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_playersettings.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_preferences.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_qmenu.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_servers2.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_sparena.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_specifyserver.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_splevel.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_sppostgame.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_startserver.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_team.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_video.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_cinematics.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_spskill.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_addbots.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_removebots.c
+@if errorlevel 1 goto quit
+rem lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_loadconfig.c
+rem @if errorlevel 1 goto quit
+rem lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_saveconfig.c
+rem @if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_teamorders.c
+@if errorlevel 1 goto quit
+lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\q3_ui ../ui_mods.c
+@if errorlevel 1 goto quit
+
+
+q3asm -f ../q3_ui
+:quit
+cd ..
diff --git a/code/q3_ui/q3_ui.q3asm b/code/q3_ui/q3_ui.q3asm
new file mode 100755
index 0000000..09ec962
--- /dev/null
+++ b/code/q3_ui/q3_ui.q3asm
@@ -0,0 +1,43 @@
+-o "\quake3\baseq3\vm\ui"
+ui_main
+..\..\ui\ui_syscalls
+ui_gameinfo
+ui_atoms
+ui_cinematics
+ui_connect
+ui_controls2
+ui_demo2
+ui_mfield
+ui_credits
+ui_menu
+ui_ingame
+ui_confirm
+ui_setup
+ui_options
+ui_display
+ui_sound
+ui_network
+ui_playermodel
+ui_players
+ui_playersettings
+ui_preferences
+ui_qmenu
+ui_serverinfo
+ui_servers2
+ui_sparena
+ui_specifyserver
+ui_sppostgame
+ui_splevel
+ui_spskill
+ui_startserver
+ui_team
+ui_video
+ui_addbots
+ui_removebots
+ui_teamorders
+ui_cdkey
+ui_mods
+bg_misc
+bg_lib
+q_math
+q_shared
diff --git a/code/q3_ui/q3_ui.sh b/code/q3_ui/q3_ui.sh
new file mode 100755
index 0000000..377d16e
--- /dev/null
+++ b/code/q3_ui/q3_ui.sh
@@ -0,0 +1,55 @@
+#!/bin/sh
+
+mkdir -p vm
+cd vm
+
+CC="q3lcc -DQ3_VM -S -Wf-target=bytecode -Wf-g -I../../cgame -I../../game -I../../q3_ui "
+
+$CC ../ui_main.c
+$CC ../ui_cdkey.c
+$CC ../ui_ingame.c
+$CC ../ui_confirm.c
+$CC ../ui_setup.c
+$CC ../../game/bg_misc.c
+$CC ../../game/bg_lib.c
+$CC ../../game/q_math.c
+$CC ../../game/q_shared.c
+$CC ../ui_gameinfo.c
+$CC ../ui_atoms.c
+$CC ../ui_connect.c
+$CC ../ui_controls2.c
+$CC ../ui_demo2.c
+$CC ../ui_mfield.c
+$CC ../ui_credits.c
+$CC ../ui_menu.c
+$CC ../ui_options.c
+$CC ../ui_display.c
+$CC ../ui_sound.c
+$CC ../ui_network.c
+$CC ../ui_playermodel.c
+$CC ../ui_players.c
+$CC ../ui_playersettings.c
+$CC ../ui_preferences.c
+$CC ../ui_qmenu.c
+$CC ../ui_serverinfo.c
+$CC ../ui_servers2.c
+$CC ../ui_sparena.c
+$CC ../ui_specifyserver.c
+$CC ../ui_splevel.c
+$CC ../ui_sppostgame.c
+$CC ../ui_startserver.c
+$CC ../ui_syscalls.c
+$CC ../ui_team.c
+$CC ../ui_video.c
+$CC ../ui_cinematics.c
+$CC ../ui_spskill.c
+$CC ../ui_addbots.c
+$CC ../ui_removebots.c
+$CC ../ui_loadconfig.c
+$CC ../ui_saveconfig.c
+$CC ../ui_teamorders.c
+$CC ../ui_mods.c
+
+q3asm -f ../q3_ui
+
+cd ..
diff --git a/code/q3_ui/q3_ui.vcproj b/code/q3_ui/q3_ui.vcproj
new file mode 100755
index 0000000..8c1d78d
--- /dev/null
+++ b/code/q3_ui/q3_ui.vcproj
@@ -0,0 +1,2008 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+ ProjectType="Visual C++"
+ Version="7.10"
+ Name="q3_ui"
+ SccProjectName="&quot;$/MissionPack/code/q3_ui&quot;, VFLAAAAA"
+ SccLocalPath=".">
+ <Platforms>
+ <Platform
+ Name="Win32"/>
+ </Platforms>
+ <Configurations>
+ <Configuration
+ Name="Debug TA|Win32"
+ OutputDirectory=".\Debug_TA"
+ IntermediateDirectory=".\Debug_TA"
+ ConfigurationType="2"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ OptimizeForProcessor="1"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;UI_EXPORTS"
+ BasicRuntimeChecks="3"
+ RuntimeLibrary="1"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile="Debug/q3_ui.pch"
+ AssemblerListingLocation=".\Debug_TA/"
+ ObjectFile="Debug/"
+ ProgramDataBaseFileName="Debug/"
+ BrowseInformation="1"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="odbc32.lib odbccp32.lib"
+ OutputFile="../Debug_TA/uix86_old.dll"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ ModuleDefinitionFile=".\ui.def"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile="../Debug_TA/ui.pdb"
+ GenerateMapFile="TRUE"
+ MapFileName="Debug_TA/uix86.map"
+ BaseAddress="0x40000000"
+ ImportLibrary="Debug_TA/uix86.lib"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="_DEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\Debug_TA/q3_ui.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Release TA|Win32"
+ OutputDirectory=".\Release_TA"
+ IntermediateDirectory=".\Release_TA"
+ ConfigurationType="2"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;Q3_UI_EXPORTS"
+ StringPooling="TRUE"
+ RuntimeLibrary="0"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Release_TA/q3_ui.pch"
+ AssemblerListingLocation=".\Release_TA/"
+ ObjectFile=".\Release_TA/"
+ ProgramDataBaseFileName=".\Release_TA/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="odbc32.lib odbccp32.lib"
+ OutputFile="../Release_TA/uix86_old.dll"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ ModuleDefinitionFile=".\ui.def"
+ ProgramDatabaseFile=".\Release_TA/uix86_old.pdb"
+ ImportLibrary="Release_TA/q3_ui.lib"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="NDEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\Release_TA/q3_ui.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Release|Win32"
+ OutputDirectory=".\Release"
+ IntermediateDirectory=".\Release"
+ ConfigurationType="2"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;Q3_UI_EXPORTS"
+ StringPooling="TRUE"
+ RuntimeLibrary="0"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Release/q3_ui.pch"
+ AssemblerListingLocation=".\Release/"
+ ObjectFile=".\Release/"
+ ProgramDataBaseFileName=".\Release/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ OutputFile="../Release/uix86.dll"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ ModuleDefinitionFile=".\ui.def"
+ ProgramDatabaseFile=".\Release/uix86.pdb"
+ ImportLibrary=".\Release/uix86.lib"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="NDEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\Release/q3_ui.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Debug|Win32"
+ OutputDirectory=".\q3_ui___Win32_Debug"
+ IntermediateDirectory=".\q3_ui___Win32_Debug"
+ ConfigurationType="2"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ OptimizeForProcessor="1"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;UI_EXPORTS"
+ BasicRuntimeChecks="3"
+ RuntimeLibrary="1"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile="Debug/q3_ui.pch"
+ AssemblerListingLocation=".\q3_ui___Win32_Debug/"
+ ObjectFile="Debug/"
+ ProgramDataBaseFileName="Debug/"
+ BrowseInformation="1"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="odbc32.lib odbccp32.lib"
+ OutputFile="../Debug/uix86.dll"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ ModuleDefinitionFile=".\ui.def"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile="../Debug/ui.pdb"
+ GenerateMapFile="TRUE"
+ MapFileName="Debug/uix86.map"
+ BaseAddress="0x40000000"
+ ImportLibrary="Debug/uix86.lib"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="_DEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\q3_ui___Win32_Debug/q3_ui.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ </Configurations>
+ <References>
+ </References>
+ <Files>
+ <Filter
+ Name="Source Files"
+ Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat">
+ <File
+ RelativePath="..\game\bg_misc.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\game\q_math.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\game\q_shared.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui.def">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_addbots.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_atoms.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_cdkey.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_cinematics.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_confirm.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_connect.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_controls2.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_credits.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_demo2.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_display.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_gameinfo.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_ingame.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_loadconfig.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_main.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_menu.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_mfield.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_mods.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_network.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_options.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_playermodel.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_players.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_playersettings.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_preferences.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_qmenu.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_removebots.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_saveconfig.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_serverinfo.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_servers2.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_setup.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_sound.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_sparena.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_specifyserver.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_splevel.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_sppostgame.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_spreset.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_spskill.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_startserver.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ui\ui_syscalls.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_team.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_teamorders.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_video.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;Q3_UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <Filter
+ Name="Header Files"
+ Filter="h;hpp;hxx;hm;inl">
+ <File
+ RelativePath="keycodes.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\game\q_shared.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_local.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_public.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <Filter
+ Name="Resource Files"
+ Filter="ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe">
+ </Filter>
+ </Files>
+ <Globals>
+ </Globals>
+</VisualStudioProject>
diff --git a/code/q3_ui/ui.def b/code/q3_ui/ui.def
new file mode 100755
index 0000000..01861ba
--- /dev/null
+++ b/code/q3_ui/ui.def
@@ -0,0 +1,3 @@
+EXPORTS
+ vmMain
+ dllEntry
diff --git a/code/q3_ui/ui.q3asm b/code/q3_ui/ui.q3asm
new file mode 100755
index 0000000..80936bd
--- /dev/null
+++ b/code/q3_ui/ui.q3asm
@@ -0,0 +1,45 @@
+-o "\quake3\baseq3\vm\ui"
+ui_main
+..\ui_syscalls
+ui_gameinfo
+ui_atoms
+ui_cinematics
+ui_connect
+ui_controls2
+ui_demo2
+ui_mfield
+ui_credits
+ui_menu
+ui_ingame
+ui_confirm
+ui_setup
+ui_options
+ui_display
+ui_sound
+ui_network
+ui_playermodel
+ui_players
+ui_playersettings
+ui_preferences
+ui_qmenu
+ui_serverinfo
+ui_servers2
+ui_sparena
+ui_specifyserver
+ui_sppostgame
+ui_splevel
+ui_spskill
+ui_startserver
+ui_team
+ui_video
+ui_addbots
+ui_removebots
+ui_teamorders
+ui_loadconfig
+ui_saveconfig
+ui_cdkey
+ui_mods
+bg_misc
+bg_lib
+q_math
+q_shared
diff --git a/code/q3_ui/ui_addbots.c b/code/q3_ui/ui_addbots.c
new file mode 100755
index 0000000..ba906f3
--- /dev/null
+++ b/code/q3_ui/ui_addbots.c
@@ -0,0 +1,412 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*
+=======================================================================
+
+ADD BOTS MENU
+
+=======================================================================
+*/
+
+
+#include "ui_local.h"
+
+
+#define ART_BACK0 "menu/art/back_0"
+#define ART_BACK1 "menu/art/back_1"
+#define ART_FIGHT0 "menu/art/accept_0"
+#define ART_FIGHT1 "menu/art/accept_1"
+#define ART_BACKGROUND "menu/art/addbotframe"
+#define ART_ARROWS "menu/art/arrows_vert_0"
+#define ART_ARROWUP "menu/art/arrows_vert_top"
+#define ART_ARROWDOWN "menu/art/arrows_vert_bot"
+
+#define ID_BACK 10
+#define ID_GO 11
+#define ID_LIST 12
+#define ID_UP 13
+#define ID_DOWN 14
+#define ID_SKILL 15
+#define ID_TEAM 16
+#define ID_BOTNAME0 20
+#define ID_BOTNAME1 21
+#define ID_BOTNAME2 22
+#define ID_BOTNAME3 23
+#define ID_BOTNAME4 24
+#define ID_BOTNAME5 25
+#define ID_BOTNAME6 26
+
+
+typedef struct {
+ menuframework_s menu;
+ menubitmap_s arrows;
+ menubitmap_s up;
+ menubitmap_s down;
+ menutext_s bots[7];
+ menulist_s skill;
+ menulist_s team;
+ menubitmap_s go;
+ menubitmap_s back;
+
+ int numBots;
+ int delay;
+ int baseBotNum;
+ int selectedBotNum;
+ int sortedBotNums[MAX_BOTS];
+ char botnames[7][32];
+} addBotsMenuInfo_t;
+
+static addBotsMenuInfo_t addBotsMenuInfo;
+
+
+/*
+=================
+UI_AddBotsMenu_FightEvent
+=================
+*/
+static void UI_AddBotsMenu_FightEvent( void* ptr, int event ) {
+ const char *team;
+ int skill;
+
+ if (event != QM_ACTIVATED) {
+ return;
+ }
+
+ team = addBotsMenuInfo.team.itemnames[addBotsMenuInfo.team.curvalue];
+ skill = addBotsMenuInfo.skill.curvalue + 1;
+
+ trap_Cmd_ExecuteText( EXEC_APPEND, va("addbot %s %i %s %i\n",
+ addBotsMenuInfo.botnames[addBotsMenuInfo.selectedBotNum], skill, team, addBotsMenuInfo.delay) );
+
+ addBotsMenuInfo.delay += 1500;
+}
+
+
+/*
+=================
+UI_AddBotsMenu_BotEvent
+=================
+*/
+static void UI_AddBotsMenu_BotEvent( void* ptr, int event ) {
+ if (event != QM_ACTIVATED) {
+ return;
+ }
+
+ addBotsMenuInfo.bots[addBotsMenuInfo.selectedBotNum].color = color_orange;
+ addBotsMenuInfo.selectedBotNum = ((menucommon_s*)ptr)->id - ID_BOTNAME0;
+ addBotsMenuInfo.bots[addBotsMenuInfo.selectedBotNum].color = color_white;
+}
+
+
+/*
+=================
+UI_AddBotsMenu_BackEvent
+=================
+*/
+static void UI_AddBotsMenu_BackEvent( void* ptr, int event ) {
+ if (event != QM_ACTIVATED) {
+ return;
+ }
+ UI_PopMenu();
+}
+
+
+/*
+=================
+UI_AddBotsMenu_SetBotNames
+=================
+*/
+static void UI_AddBotsMenu_SetBotNames( void ) {
+ int n;
+ const char *info;
+
+ for ( n = 0; n < 7; n++ ) {
+ info = UI_GetBotInfoByNumber( addBotsMenuInfo.sortedBotNums[addBotsMenuInfo.baseBotNum + n] );
+ Q_strncpyz( addBotsMenuInfo.botnames[n], Info_ValueForKey( info, "name" ), sizeof(addBotsMenuInfo.botnames[n]) );
+ }
+
+}
+
+
+/*
+=================
+UI_AddBotsMenu_UpEvent
+=================
+*/
+static void UI_AddBotsMenu_UpEvent( void* ptr, int event ) {
+ if (event != QM_ACTIVATED) {
+ return;
+ }
+
+ if( addBotsMenuInfo.baseBotNum > 0 ) {
+ addBotsMenuInfo.baseBotNum--;
+ UI_AddBotsMenu_SetBotNames();
+ }
+}
+
+
+/*
+=================
+UI_AddBotsMenu_DownEvent
+=================
+*/
+static void UI_AddBotsMenu_DownEvent( void* ptr, int event ) {
+ if (event != QM_ACTIVATED) {
+ return;
+ }
+
+ if( addBotsMenuInfo.baseBotNum + 7 < addBotsMenuInfo.numBots ) {
+ addBotsMenuInfo.baseBotNum++;
+ UI_AddBotsMenu_SetBotNames();
+ }
+}
+
+
+/*
+=================
+UI_AddBotsMenu_GetSortedBotNums
+=================
+*/
+static int QDECL UI_AddBotsMenu_SortCompare( const void *arg1, const void *arg2 ) {
+ int num1, num2;
+ const char *info1, *info2;
+ const char *name1, *name2;
+
+ num1 = *(int *)arg1;
+ num2 = *(int *)arg2;
+
+ info1 = UI_GetBotInfoByNumber( num1 );
+ info2 = UI_GetBotInfoByNumber( num2 );
+
+ name1 = Info_ValueForKey( info1, "name" );
+ name2 = Info_ValueForKey( info2, "name" );
+
+ return Q_stricmp( name1, name2 );
+}
+
+static void UI_AddBotsMenu_GetSortedBotNums( void ) {
+ int n;
+
+ // initialize the array
+ for( n = 0; n < addBotsMenuInfo.numBots; n++ ) {
+ addBotsMenuInfo.sortedBotNums[n] = n;
+ }
+
+ qsort( addBotsMenuInfo.sortedBotNums, addBotsMenuInfo.numBots, sizeof(addBotsMenuInfo.sortedBotNums[0]), UI_AddBotsMenu_SortCompare );
+}
+
+
+/*
+=================
+UI_AddBotsMenu_Draw
+=================
+*/
+static void UI_AddBotsMenu_Draw( void ) {
+ UI_DrawBannerString( 320, 16, "ADD BOTS", UI_CENTER, color_white );
+ UI_DrawNamedPic( 320-233, 240-166, 466, 332, ART_BACKGROUND );
+
+ // standard menu drawing
+ Menu_Draw( &addBotsMenuInfo.menu );
+}
+
+
+/*
+=================
+UI_AddBotsMenu_Init
+=================
+*/
+static const char *skillNames[] = {
+ "I Can Win",
+ "Bring It On",
+ "Hurt Me Plenty",
+ "Hardcore",
+ "Nightmare!",
+ 0
+};
+
+static const char *teamNames1[] = {
+ "Free",
+ 0
+};
+
+static const char *teamNames2[] = {
+ "Red",
+ "Blue",
+ 0
+};
+
+static void UI_AddBotsMenu_Init( void ) {
+ int n;
+ int y;
+ int gametype;
+ int count;
+ char info[MAX_INFO_STRING];
+
+ trap_GetConfigString(CS_SERVERINFO, info, MAX_INFO_STRING);
+ gametype = atoi( Info_ValueForKey( info,"g_gametype" ) );
+
+ memset( &addBotsMenuInfo, 0 ,sizeof(addBotsMenuInfo) );
+ addBotsMenuInfo.menu.draw = UI_AddBotsMenu_Draw;
+ addBotsMenuInfo.menu.fullscreen = qfalse;
+ addBotsMenuInfo.menu.wrapAround = qtrue;
+ addBotsMenuInfo.delay = 1000;
+
+ UI_AddBots_Cache();
+
+ addBotsMenuInfo.numBots = UI_GetNumBots();
+ count = addBotsMenuInfo.numBots < 7 ? addBotsMenuInfo.numBots : 7;
+
+ addBotsMenuInfo.arrows.generic.type = MTYPE_BITMAP;
+ addBotsMenuInfo.arrows.generic.name = ART_ARROWS;
+ addBotsMenuInfo.arrows.generic.flags = QMF_INACTIVE;
+ addBotsMenuInfo.arrows.generic.x = 200;
+ addBotsMenuInfo.arrows.generic.y = 128;
+ addBotsMenuInfo.arrows.width = 64;
+ addBotsMenuInfo.arrows.height = 128;
+
+ addBotsMenuInfo.up.generic.type = MTYPE_BITMAP;
+ addBotsMenuInfo.up.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ addBotsMenuInfo.up.generic.x = 200;
+ addBotsMenuInfo.up.generic.y = 128;
+ addBotsMenuInfo.up.generic.id = ID_UP;
+ addBotsMenuInfo.up.generic.callback = UI_AddBotsMenu_UpEvent;
+ addBotsMenuInfo.up.width = 64;
+ addBotsMenuInfo.up.height = 64;
+ addBotsMenuInfo.up.focuspic = ART_ARROWUP;
+
+ addBotsMenuInfo.down.generic.type = MTYPE_BITMAP;
+ addBotsMenuInfo.down.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ addBotsMenuInfo.down.generic.x = 200;
+ addBotsMenuInfo.down.generic.y = 128+64;
+ addBotsMenuInfo.down.generic.id = ID_DOWN;
+ addBotsMenuInfo.down.generic.callback = UI_AddBotsMenu_DownEvent;
+ addBotsMenuInfo.down.width = 64;
+ addBotsMenuInfo.down.height = 64;
+ addBotsMenuInfo.down.focuspic = ART_ARROWDOWN;
+
+ for( n = 0, y = 120; n < count; n++, y += 20 ) {
+ addBotsMenuInfo.bots[n].generic.type = MTYPE_PTEXT;
+ addBotsMenuInfo.bots[n].generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ addBotsMenuInfo.bots[n].generic.id = ID_BOTNAME0 + n;
+ addBotsMenuInfo.bots[n].generic.x = 320 - 56;
+ addBotsMenuInfo.bots[n].generic.y = y;
+ addBotsMenuInfo.bots[n].generic.callback = UI_AddBotsMenu_BotEvent;
+ addBotsMenuInfo.bots[n].string = addBotsMenuInfo.botnames[n];
+ addBotsMenuInfo.bots[n].color = color_orange;
+ addBotsMenuInfo.bots[n].style = UI_LEFT|UI_SMALLFONT;
+ }
+
+ y += 12;
+ addBotsMenuInfo.skill.generic.type = MTYPE_SPINCONTROL;
+ addBotsMenuInfo.skill.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ addBotsMenuInfo.skill.generic.x = 320;
+ addBotsMenuInfo.skill.generic.y = y;
+ addBotsMenuInfo.skill.generic.name = "Skill:";
+ addBotsMenuInfo.skill.generic.id = ID_SKILL;
+ addBotsMenuInfo.skill.itemnames = skillNames;
+ addBotsMenuInfo.skill.curvalue = Com_Clamp( 0, 4, (int)trap_Cvar_VariableValue( "g_spSkill" ) - 1 );
+
+ y += SMALLCHAR_HEIGHT;
+ addBotsMenuInfo.team.generic.type = MTYPE_SPINCONTROL;
+ addBotsMenuInfo.team.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ addBotsMenuInfo.team.generic.x = 320;
+ addBotsMenuInfo.team.generic.y = y;
+ addBotsMenuInfo.team.generic.name = "Team: ";
+ addBotsMenuInfo.team.generic.id = ID_TEAM;
+ if( gametype >= GT_TEAM ) {
+ addBotsMenuInfo.team.itemnames = teamNames2;
+ }
+ else {
+ addBotsMenuInfo.team.itemnames = teamNames1;
+ addBotsMenuInfo.team.generic.flags = QMF_GRAYED;
+ }
+
+ addBotsMenuInfo.go.generic.type = MTYPE_BITMAP;
+ addBotsMenuInfo.go.generic.name = ART_FIGHT0;
+ addBotsMenuInfo.go.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ addBotsMenuInfo.go.generic.id = ID_GO;
+ addBotsMenuInfo.go.generic.callback = UI_AddBotsMenu_FightEvent;
+ addBotsMenuInfo.go.generic.x = 320+128-128;
+ addBotsMenuInfo.go.generic.y = 256+128-64;
+ addBotsMenuInfo.go.width = 128;
+ addBotsMenuInfo.go.height = 64;
+ addBotsMenuInfo.go.focuspic = ART_FIGHT1;
+
+ addBotsMenuInfo.back.generic.type = MTYPE_BITMAP;
+ addBotsMenuInfo.back.generic.name = ART_BACK0;
+ addBotsMenuInfo.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ addBotsMenuInfo.back.generic.id = ID_BACK;
+ addBotsMenuInfo.back.generic.callback = UI_AddBotsMenu_BackEvent;
+ addBotsMenuInfo.back.generic.x = 320-128;
+ addBotsMenuInfo.back.generic.y = 256+128-64;
+ addBotsMenuInfo.back.width = 128;
+ addBotsMenuInfo.back.height = 64;
+ addBotsMenuInfo.back.focuspic = ART_BACK1;
+
+ addBotsMenuInfo.baseBotNum = 0;
+ addBotsMenuInfo.selectedBotNum = 0;
+ addBotsMenuInfo.bots[0].color = color_white;
+
+ UI_AddBotsMenu_GetSortedBotNums();
+ UI_AddBotsMenu_SetBotNames();
+
+ Menu_AddItem( &addBotsMenuInfo.menu, &addBotsMenuInfo.arrows );
+
+ Menu_AddItem( &addBotsMenuInfo.menu, &addBotsMenuInfo.up );
+ Menu_AddItem( &addBotsMenuInfo.menu, &addBotsMenuInfo.down );
+ for( n = 0; n < count; n++ ) {
+ Menu_AddItem( &addBotsMenuInfo.menu, &addBotsMenuInfo.bots[n] );
+ }
+ Menu_AddItem( &addBotsMenuInfo.menu, &addBotsMenuInfo.skill );
+ Menu_AddItem( &addBotsMenuInfo.menu, &addBotsMenuInfo.team );
+ Menu_AddItem( &addBotsMenuInfo.menu, &addBotsMenuInfo.go );
+ Menu_AddItem( &addBotsMenuInfo.menu, &addBotsMenuInfo.back );
+}
+
+
+/*
+=================
+UI_AddBots_Cache
+=================
+*/
+void UI_AddBots_Cache( void ) {
+ trap_R_RegisterShaderNoMip( ART_BACK0 );
+ trap_R_RegisterShaderNoMip( ART_BACK1 );
+ trap_R_RegisterShaderNoMip( ART_FIGHT0 );
+ trap_R_RegisterShaderNoMip( ART_FIGHT1 );
+ trap_R_RegisterShaderNoMip( ART_BACKGROUND );
+ trap_R_RegisterShaderNoMip( ART_ARROWS );
+ trap_R_RegisterShaderNoMip( ART_ARROWUP );
+ trap_R_RegisterShaderNoMip( ART_ARROWDOWN );
+}
+
+
+/*
+=================
+UI_AddBotsMenu
+=================
+*/
+void UI_AddBotsMenu( void ) {
+ UI_AddBotsMenu_Init();
+ UI_PushMenu( &addBotsMenuInfo.menu );
+}
diff --git a/code/q3_ui/ui_atoms.c b/code/q3_ui/ui_atoms.c
new file mode 100755
index 0000000..4a2177d
--- /dev/null
+++ b/code/q3_ui/ui_atoms.c
@@ -0,0 +1,1267 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/**********************************************************************
+ UI_ATOMS.C
+
+ User interface building blocks and support functions.
+**********************************************************************/
+#include "ui_local.h"
+
+uiStatic_t uis;
+qboolean m_entersound; // after a frame, so caching won't disrupt the sound
+
+// these are here so the functions in q_shared.c can link
+#ifndef UI_HARD_LINKED
+
+void QDECL Com_Error( int level, const char *error, ... ) {
+ va_list argptr;
+ char text[1024];
+
+ va_start (argptr, error);
+ vsprintf (text, error, argptr);
+ va_end (argptr);
+
+ trap_Error( va("%s", text) );
+}
+
+void QDECL Com_Printf( const char *msg, ... ) {
+ va_list argptr;
+ char text[1024];
+
+ va_start (argptr, msg);
+ vsprintf (text, msg, argptr);
+ va_end (argptr);
+
+ trap_Print( va("%s", text) );
+}
+
+#endif
+
+/*
+=================
+UI_ClampCvar
+=================
+*/
+float UI_ClampCvar( float min, float max, float value )
+{
+ if ( value < min ) return min;
+ if ( value > max ) return max;
+ return value;
+}
+
+/*
+=================
+UI_StartDemoLoop
+=================
+*/
+void UI_StartDemoLoop( void ) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, "d1\n" );
+}
+
+/*
+=================
+UI_PushMenu
+=================
+*/
+void UI_PushMenu( menuframework_s *menu )
+{
+ int i;
+ menucommon_s* item;
+
+ // avoid stacking menus invoked by hotkeys
+ for (i=0 ; i<uis.menusp ; i++)
+ {
+ if (uis.stack[i] == menu)
+ {
+ uis.menusp = i;
+ break;
+ }
+ }
+
+ if (i == uis.menusp)
+ {
+ if (uis.menusp >= MAX_MENUDEPTH)
+ trap_Error("UI_PushMenu: menu stack overflow");
+
+ uis.stack[uis.menusp++] = menu;
+ }
+
+ uis.activemenu = menu;
+
+ // default cursor position
+ menu->cursor = 0;
+ menu->cursor_prev = 0;
+
+ m_entersound = qtrue;
+
+ trap_Key_SetCatcher( KEYCATCH_UI );
+
+ // force first available item to have focus
+ for (i=0; i<menu->nitems; i++)
+ {
+ item = (menucommon_s *)menu->items[i];
+ if (!(item->flags & (QMF_GRAYED|QMF_MOUSEONLY|QMF_INACTIVE)))
+ {
+ menu->cursor_prev = -1;
+ Menu_SetCursor( menu, i );
+ break;
+ }
+ }
+
+ uis.firstdraw = qtrue;
+}
+
+/*
+=================
+UI_PopMenu
+=================
+*/
+void UI_PopMenu (void)
+{
+ trap_S_StartLocalSound( menu_out_sound, CHAN_LOCAL_SOUND );
+
+ uis.menusp--;
+
+ if (uis.menusp < 0)
+ trap_Error ("UI_PopMenu: menu stack underflow");
+
+ if (uis.menusp) {
+ uis.activemenu = uis.stack[uis.menusp-1];
+ uis.firstdraw = qtrue;
+ }
+ else {
+ UI_ForceMenuOff ();
+ }
+}
+
+void UI_ForceMenuOff (void)
+{
+ uis.menusp = 0;
+ uis.activemenu = NULL;
+
+ trap_Key_SetCatcher( trap_Key_GetCatcher() & ~KEYCATCH_UI );
+ trap_Key_ClearStates();
+ trap_Cvar_Set( "cl_paused", "0" );
+}
+
+/*
+=================
+UI_LerpColor
+=================
+*/
+void UI_LerpColor(vec4_t a, vec4_t b, vec4_t c, float t)
+{
+ int i;
+
+ // lerp and clamp each component
+ for (i=0; i<4; i++)
+ {
+ c[i] = a[i] + t*(b[i]-a[i]);
+ if (c[i] < 0)
+ c[i] = 0;
+ else if (c[i] > 1.0)
+ c[i] = 1.0;
+ }
+}
+
+/*
+=================
+UI_DrawProportionalString2
+=================
+*/
+static int propMap[128][3] = {
+{0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1},
+{0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1},
+
+{0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1},
+{0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1},
+
+{0, 0, PROP_SPACE_WIDTH}, // SPACE
+{11, 122, 7}, // !
+{154, 181, 14}, // "
+{55, 122, 17}, // #
+{79, 122, 18}, // $
+{101, 122, 23}, // %
+{153, 122, 18}, // &
+{9, 93, 7}, // '
+{207, 122, 8}, // (
+{230, 122, 9}, // )
+{177, 122, 18}, // *
+{30, 152, 18}, // +
+{85, 181, 7}, // ,
+{34, 93, 11}, // -
+{110, 181, 6}, // .
+{130, 152, 14}, // /
+
+{22, 64, 17}, // 0
+{41, 64, 12}, // 1
+{58, 64, 17}, // 2
+{78, 64, 18}, // 3
+{98, 64, 19}, // 4
+{120, 64, 18}, // 5
+{141, 64, 18}, // 6
+{204, 64, 16}, // 7
+{162, 64, 17}, // 8
+{182, 64, 18}, // 9
+{59, 181, 7}, // :
+{35,181, 7}, // ;
+{203, 152, 14}, // <
+{56, 93, 14}, // =
+{228, 152, 14}, // >
+{177, 181, 18}, // ?
+
+{28, 122, 22}, // @
+{5, 4, 18}, // A
+{27, 4, 18}, // B
+{48, 4, 18}, // C
+{69, 4, 17}, // D
+{90, 4, 13}, // E
+{106, 4, 13}, // F
+{121, 4, 18}, // G
+{143, 4, 17}, // H
+{164, 4, 8}, // I
+{175, 4, 16}, // J
+{195, 4, 18}, // K
+{216, 4, 12}, // L
+{230, 4, 23}, // M
+{6, 34, 18}, // N
+{27, 34, 18}, // O
+
+{48, 34, 18}, // P
+{68, 34, 18}, // Q
+{90, 34, 17}, // R
+{110, 34, 18}, // S
+{130, 34, 14}, // T
+{146, 34, 18}, // U
+{166, 34, 19}, // V
+{185, 34, 29}, // W
+{215, 34, 18}, // X
+{234, 34, 18}, // Y
+{5, 64, 14}, // Z
+{60, 152, 7}, // [
+{106, 151, 13}, // '\'
+{83, 152, 7}, // ]
+{128, 122, 17}, // ^
+{4, 152, 21}, // _
+
+{134, 181, 5}, // '
+{5, 4, 18}, // A
+{27, 4, 18}, // B
+{48, 4, 18}, // C
+{69, 4, 17}, // D
+{90, 4, 13}, // E
+{106, 4, 13}, // F
+{121, 4, 18}, // G
+{143, 4, 17}, // H
+{164, 4, 8}, // I
+{175, 4, 16}, // J
+{195, 4, 18}, // K
+{216, 4, 12}, // L
+{230, 4, 23}, // M
+{6, 34, 18}, // N
+{27, 34, 18}, // O
+
+{48, 34, 18}, // P
+{68, 34, 18}, // Q
+{90, 34, 17}, // R
+{110, 34, 18}, // S
+{130, 34, 14}, // T
+{146, 34, 18}, // U
+{166, 34, 19}, // V
+{185, 34, 29}, // W
+{215, 34, 18}, // X
+{234, 34, 18}, // Y
+{5, 64, 14}, // Z
+{153, 152, 13}, // {
+{11, 181, 5}, // |
+{180, 152, 13}, // }
+{79, 93, 17}, // ~
+{0, 0, -1} // DEL
+};
+
+static int propMapB[26][3] = {
+{11, 12, 33},
+{49, 12, 31},
+{85, 12, 31},
+{120, 12, 30},
+{156, 12, 21},
+{183, 12, 21},
+{207, 12, 32},
+
+{13, 55, 30},
+{49, 55, 13},
+{66, 55, 29},
+{101, 55, 31},
+{135, 55, 21},
+{158, 55, 40},
+{204, 55, 32},
+
+{12, 97, 31},
+{48, 97, 31},
+{82, 97, 30},
+{118, 97, 30},
+{153, 97, 30},
+{185, 97, 25},
+{213, 97, 30},
+
+{11, 139, 32},
+{42, 139, 51},
+{93, 139, 32},
+{126, 139, 31},
+{158, 139, 25},
+};
+
+#define PROPB_GAP_WIDTH 4
+#define PROPB_SPACE_WIDTH 12
+#define PROPB_HEIGHT 36
+
+// bk001205 - code below duplicated in cgame/cg_drawtools.c
+// bk001205 - FIXME: does this belong in ui_shared.c?
+/*
+=================
+UI_DrawBannerString
+=================
+*/
+static void UI_DrawBannerString2( int x, int y, const char* str, vec4_t color )
+{
+ const char* s;
+ unsigned char ch; // bk001204 - unsigned
+ float ax;
+ float ay;
+ float aw;
+ float ah;
+ float frow;
+ float fcol;
+ float fwidth;
+ float fheight;
+
+ // draw the colored text
+ trap_R_SetColor( color );
+
+ ax = x * uis.scale + uis.bias;
+ ay = y * uis.scale;
+
+ s = str;
+ while ( *s )
+ {
+ ch = *s & 127;
+ if ( ch == ' ' ) {
+ ax += ((float)PROPB_SPACE_WIDTH + (float)PROPB_GAP_WIDTH)* uis.scale;
+ }
+ else if ( ch >= 'A' && ch <= 'Z' ) {
+ ch -= 'A';
+ fcol = (float)propMapB[ch][0] / 256.0f;
+ frow = (float)propMapB[ch][1] / 256.0f;
+ fwidth = (float)propMapB[ch][2] / 256.0f;
+ fheight = (float)PROPB_HEIGHT / 256.0f;
+ aw = (float)propMapB[ch][2] * uis.scale;
+ ah = (float)PROPB_HEIGHT * uis.scale;
+ trap_R_DrawStretchPic( ax, ay, aw, ah, fcol, frow, fcol+fwidth, frow+fheight, uis.charsetPropB );
+ ax += (aw + (float)PROPB_GAP_WIDTH * uis.scale);
+ }
+ s++;
+ }
+
+ trap_R_SetColor( NULL );
+}
+
+void UI_DrawBannerString( int x, int y, const char* str, int style, vec4_t color ) {
+ const char * s;
+ int ch;
+ int width;
+ vec4_t drawcolor;
+
+ // find the width of the drawn text
+ s = str;
+ width = 0;
+ while ( *s ) {
+ ch = *s;
+ if ( ch == ' ' ) {
+ width += PROPB_SPACE_WIDTH;
+ }
+ else if ( ch >= 'A' && ch <= 'Z' ) {
+ width += propMapB[ch - 'A'][2] + PROPB_GAP_WIDTH;
+ }
+ s++;
+ }
+ width -= PROPB_GAP_WIDTH;
+
+ switch( style & UI_FORMATMASK ) {
+ case UI_CENTER:
+ x -= width / 2;
+ break;
+
+ case UI_RIGHT:
+ x -= width;
+ break;
+
+ case UI_LEFT:
+ default:
+ break;
+ }
+
+ if ( style & UI_DROPSHADOW ) {
+ drawcolor[0] = drawcolor[1] = drawcolor[2] = 0;
+ drawcolor[3] = color[3];
+ UI_DrawBannerString2( x+2, y+2, str, drawcolor );
+ }
+
+ UI_DrawBannerString2( x, y, str, color );
+}
+
+
+int UI_ProportionalStringWidth( const char* str ) {
+ const char * s;
+ int ch;
+ int charWidth;
+ int width;
+
+ s = str;
+ width = 0;
+ while ( *s ) {
+ ch = *s & 127;
+ charWidth = propMap[ch][2];
+ if ( charWidth != -1 ) {
+ width += charWidth;
+ width += PROP_GAP_WIDTH;
+ }
+ s++;
+ }
+
+ width -= PROP_GAP_WIDTH;
+ return width;
+}
+
+static void UI_DrawProportionalString2( int x, int y, const char* str, vec4_t color, float sizeScale, qhandle_t charset )
+{
+ const char* s;
+ unsigned char ch; // bk001204 - unsigned
+ float ax;
+ float ay;
+ float aw = 0; // bk001204 - init
+ float ah;
+ float frow;
+ float fcol;
+ float fwidth;
+ float fheight;
+
+ // draw the colored text
+ trap_R_SetColor( color );
+
+ ax = x * uis.scale + uis.bias;
+ ay = y * uis.scale;
+
+ s = str;
+ while ( *s )
+ {
+ ch = *s & 127;
+ if ( ch == ' ' ) {
+ aw = (float)PROP_SPACE_WIDTH * uis.scale * sizeScale;
+ }
+ else if ( propMap[ch][2] != -1 ) {
+ fcol = (float)propMap[ch][0] / 256.0f;
+ frow = (float)propMap[ch][1] / 256.0f;
+ fwidth = (float)propMap[ch][2] / 256.0f;
+ fheight = (float)PROP_HEIGHT / 256.0f;
+ aw = (float)propMap[ch][2] * uis.scale * sizeScale;
+ ah = (float)PROP_HEIGHT * uis.scale * sizeScale;
+ trap_R_DrawStretchPic( ax, ay, aw, ah, fcol, frow, fcol+fwidth, frow+fheight, charset );
+ }
+
+ ax += (aw + (float)PROP_GAP_WIDTH * uis.scale * sizeScale);
+ s++;
+ }
+
+ trap_R_SetColor( NULL );
+}
+
+/*
+=================
+UI_ProportionalSizeScale
+=================
+*/
+float UI_ProportionalSizeScale( int style ) {
+ if( style & UI_SMALLFONT ) {
+ return PROP_SMALL_SIZE_SCALE;
+ }
+
+ return 1.00;
+}
+
+
+/*
+=================
+UI_DrawProportionalString
+=================
+*/
+void UI_DrawProportionalString( int x, int y, const char* str, int style, vec4_t color ) {
+ vec4_t drawcolor;
+ int width;
+ float sizeScale;
+
+ sizeScale = UI_ProportionalSizeScale( style );
+
+ switch( style & UI_FORMATMASK ) {
+ case UI_CENTER:
+ width = UI_ProportionalStringWidth( str ) * sizeScale;
+ x -= width / 2;
+ break;
+
+ case UI_RIGHT:
+ width = UI_ProportionalStringWidth( str ) * sizeScale;
+ x -= width;
+ break;
+
+ case UI_LEFT:
+ default:
+ break;
+ }
+
+ if ( style & UI_DROPSHADOW ) {
+ drawcolor[0] = drawcolor[1] = drawcolor[2] = 0;
+ drawcolor[3] = color[3];
+ UI_DrawProportionalString2( x+2, y+2, str, drawcolor, sizeScale, uis.charsetProp );
+ }
+
+ if ( style & UI_INVERSE ) {
+ drawcolor[0] = color[0] * 0.7;
+ drawcolor[1] = color[1] * 0.7;
+ drawcolor[2] = color[2] * 0.7;
+ drawcolor[3] = color[3];
+ UI_DrawProportionalString2( x, y, str, drawcolor, sizeScale, uis.charsetProp );
+ return;
+ }
+
+ if ( style & UI_PULSE ) {
+ drawcolor[0] = color[0] * 0.7;
+ drawcolor[1] = color[1] * 0.7;
+ drawcolor[2] = color[2] * 0.7;
+ drawcolor[3] = color[3];
+ UI_DrawProportionalString2( x, y, str, color, sizeScale, uis.charsetProp );
+
+ drawcolor[0] = color[0];
+ drawcolor[1] = color[1];
+ drawcolor[2] = color[2];
+ drawcolor[3] = 0.5 + 0.5 * sin( uis.realtime / PULSE_DIVISOR );
+ UI_DrawProportionalString2( x, y, str, drawcolor, sizeScale, uis.charsetPropGlow );
+ return;
+ }
+
+ UI_DrawProportionalString2( x, y, str, color, sizeScale, uis.charsetProp );
+}
+
+/*
+=================
+UI_DrawProportionalString_Wrapped
+=================
+*/
+void UI_DrawProportionalString_AutoWrapped( int x, int y, int xmax, int ystep, const char* str, int style, vec4_t color ) {
+ int width;
+ char *s1,*s2,*s3;
+ char c_bcp;
+ char buf[1024];
+ float sizeScale;
+
+ if (!str || str[0]=='\0')
+ return;
+
+ sizeScale = UI_ProportionalSizeScale( style );
+
+ Q_strncpyz(buf, str, sizeof(buf));
+ s1 = s2 = s3 = buf;
+
+ while (1) {
+ do {
+ s3++;
+ } while (*s3!=' ' && *s3!='\0');
+ c_bcp = *s3;
+ *s3 = '\0';
+ width = UI_ProportionalStringWidth(s1) * sizeScale;
+ *s3 = c_bcp;
+ if (width > xmax) {
+ if (s1==s2)
+ {
+ // fuck, don't have a clean cut, we'll overflow
+ s2 = s3;
+ }
+ *s2 = '\0';
+ UI_DrawProportionalString(x, y, s1, style, color);
+ y += ystep;
+ if (c_bcp == '\0')
+ {
+ // that was the last word
+ // we could start a new loop, but that wouldn't be much use
+ // even if the word is too long, we would overflow it (see above)
+ // so just print it now if needed
+ s2++;
+ if (*s2 != '\0') // if we are printing an overflowing line we have s2 == s3
+ UI_DrawProportionalString(x, y, s2, style, color);
+ break;
+ }
+ s2++;
+ s1 = s2;
+ s3 = s2;
+ }
+ else
+ {
+ s2 = s3;
+ if (c_bcp == '\0') // we reached the end
+ {
+ UI_DrawProportionalString(x, y, s1, style, color);
+ break;
+ }
+ }
+ }
+}
+
+/*
+=================
+UI_DrawString2
+=================
+*/
+static void UI_DrawString2( int x, int y, const char* str, vec4_t color, int charw, int charh )
+{
+ const char* s;
+ char ch;
+ int forceColor = qfalse; //APSFIXME;
+ vec4_t tempcolor;
+ float ax;
+ float ay;
+ float aw;
+ float ah;
+ float frow;
+ float fcol;
+
+ if (y < -charh)
+ // offscreen
+ return;
+
+ // draw the colored text
+ trap_R_SetColor( color );
+
+ ax = x * uis.scale + uis.bias;
+ ay = y * uis.scale;
+ aw = charw * uis.scale;
+ ah = charh * uis.scale;
+
+ s = str;
+ while ( *s )
+ {
+ if ( Q_IsColorString( s ) )
+ {
+ if ( !forceColor )
+ {
+ memcpy( tempcolor, g_color_table[ColorIndex(s[1])], sizeof( tempcolor ) );
+ tempcolor[3] = color[3];
+ trap_R_SetColor( tempcolor );
+ }
+ s += 2;
+ continue;
+ }
+
+ ch = *s & 255;
+ if (ch != ' ')
+ {
+ frow = (ch>>4)*0.0625;
+ fcol = (ch&15)*0.0625;
+ trap_R_DrawStretchPic( ax, ay, aw, ah, fcol, frow, fcol + 0.0625, frow + 0.0625, uis.charset );
+ }
+
+ ax += aw;
+ s++;
+ }
+
+ trap_R_SetColor( NULL );
+}
+
+/*
+=================
+UI_DrawString
+=================
+*/
+void UI_DrawString( int x, int y, const char* str, int style, vec4_t color )
+{
+ int len;
+ int charw;
+ int charh;
+ vec4_t newcolor;
+ vec4_t lowlight;
+ float *drawcolor;
+ vec4_t dropcolor;
+
+ if( !str ) {
+ return;
+ }
+
+ if ((style & UI_BLINK) && ((uis.realtime/BLINK_DIVISOR) & 1))
+ return;
+
+ if (style & UI_SMALLFONT)
+ {
+ charw = SMALLCHAR_WIDTH;
+ charh = SMALLCHAR_HEIGHT;
+ }
+ else if (style & UI_GIANTFONT)
+ {
+ charw = GIANTCHAR_WIDTH;
+ charh = GIANTCHAR_HEIGHT;
+ }
+ else
+ {
+ charw = BIGCHAR_WIDTH;
+ charh = BIGCHAR_HEIGHT;
+ }
+
+ if (style & UI_PULSE)
+ {
+ lowlight[0] = 0.8*color[0];
+ lowlight[1] = 0.8*color[1];
+ lowlight[2] = 0.8*color[2];
+ lowlight[3] = 0.8*color[3];
+ UI_LerpColor(color,lowlight,newcolor,0.5+0.5*sin(uis.realtime/PULSE_DIVISOR));
+ drawcolor = newcolor;
+ }
+ else
+ drawcolor = color;
+
+ switch (style & UI_FORMATMASK)
+ {
+ case UI_CENTER:
+ // center justify at x
+ len = strlen(str);
+ x = x - len*charw/2;
+ break;
+
+ case UI_RIGHT:
+ // right justify at x
+ len = strlen(str);
+ x = x - len*charw;
+ break;
+
+ default:
+ // left justify at x
+ break;
+ }
+
+ if ( style & UI_DROPSHADOW )
+ {
+ dropcolor[0] = dropcolor[1] = dropcolor[2] = 0;
+ dropcolor[3] = drawcolor[3];
+ UI_DrawString2(x+2,y+2,str,dropcolor,charw,charh);
+ }
+
+ UI_DrawString2(x,y,str,drawcolor,charw,charh);
+}
+
+/*
+=================
+UI_DrawChar
+=================
+*/
+void UI_DrawChar( int x, int y, int ch, int style, vec4_t color )
+{
+ char buff[2];
+
+ buff[0] = ch;
+ buff[1] = '\0';
+
+ UI_DrawString( x, y, buff, style, color );
+}
+
+qboolean UI_IsFullscreen( void ) {
+ if ( uis.activemenu && ( trap_Key_GetCatcher() & KEYCATCH_UI ) ) {
+ return uis.activemenu->fullscreen;
+ }
+
+ return qfalse;
+}
+
+static void NeedCDAction( qboolean result ) {
+ if ( !result ) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, "quit\n" );
+ }
+}
+
+static void NeedCDKeyAction( qboolean result ) {
+ if ( !result ) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, "quit\n" );
+ }
+}
+
+void UI_SetActiveMenu( uiMenuCommand_t menu ) {
+ // this should be the ONLY way the menu system is brought up
+ // enusure minumum menu data is cached
+ Menu_Cache();
+
+ switch ( menu ) {
+ case UIMENU_NONE:
+ UI_ForceMenuOff();
+ return;
+ case UIMENU_MAIN:
+ UI_MainMenu();
+ return;
+ case UIMENU_NEED_CD:
+ UI_ConfirmMenu( "Insert the CD", (voidfunc_f)NULL, NeedCDAction );
+ return;
+ case UIMENU_BAD_CD_KEY:
+ UI_ConfirmMenu( "Bad CD Key", (voidfunc_f)NULL, NeedCDKeyAction );
+ return;
+ case UIMENU_INGAME:
+ /*
+ //GRank
+ UI_RankingsMenu();
+ return;
+ */
+ trap_Cvar_Set( "cl_paused", "1" );
+ UI_InGameMenu();
+ return;
+
+ // bk001204
+ case UIMENU_TEAM:
+ case UIMENU_POSTGAME:
+ default:
+#ifndef NDEBUG
+ Com_Printf("UI_SetActiveMenu: bad enum %d\n", menu );
+#endif
+ break;
+ }
+}
+
+/*
+=================
+UI_KeyEvent
+=================
+*/
+void UI_KeyEvent( int key, int down ) {
+ sfxHandle_t s;
+
+ if (!uis.activemenu) {
+ return;
+ }
+
+ if (!down) {
+ return;
+ }
+
+ if (uis.activemenu->key)
+ s = uis.activemenu->key( key );
+ else
+ s = Menu_DefaultKey( uis.activemenu, key );
+
+ if ((s > 0) && (s != menu_null_sound))
+ trap_S_StartLocalSound( s, CHAN_LOCAL_SOUND );
+}
+
+/*
+=================
+UI_MouseEvent
+=================
+*/
+void UI_MouseEvent( int dx, int dy )
+{
+ int i;
+ menucommon_s* m;
+
+ if (!uis.activemenu)
+ return;
+
+ // update mouse screen position
+ uis.cursorx += dx;
+ if (uis.cursorx < 0)
+ uis.cursorx = 0;
+ else if (uis.cursorx > SCREEN_WIDTH)
+ uis.cursorx = SCREEN_WIDTH;
+
+ uis.cursory += dy;
+ if (uis.cursory < 0)
+ uis.cursory = 0;
+ else if (uis.cursory > SCREEN_HEIGHT)
+ uis.cursory = SCREEN_HEIGHT;
+
+ // region test the active menu items
+ for (i=0; i<uis.activemenu->nitems; i++)
+ {
+ m = (menucommon_s*)uis.activemenu->items[i];
+
+ if (m->flags & (QMF_GRAYED|QMF_INACTIVE))
+ continue;
+
+ if ((uis.cursorx < m->left) ||
+ (uis.cursorx > m->right) ||
+ (uis.cursory < m->top) ||
+ (uis.cursory > m->bottom))
+ {
+ // cursor out of item bounds
+ continue;
+ }
+
+ // set focus to item at cursor
+ if (uis.activemenu->cursor != i)
+ {
+ Menu_SetCursor( uis.activemenu, i );
+ ((menucommon_s*)(uis.activemenu->items[uis.activemenu->cursor_prev]))->flags &= ~QMF_HASMOUSEFOCUS;
+
+ if ( !(((menucommon_s*)(uis.activemenu->items[uis.activemenu->cursor]))->flags & QMF_SILENT ) ) {
+ trap_S_StartLocalSound( menu_move_sound, CHAN_LOCAL_SOUND );
+ }
+ }
+
+ ((menucommon_s*)(uis.activemenu->items[uis.activemenu->cursor]))->flags |= QMF_HASMOUSEFOCUS;
+ return;
+ }
+
+ if (uis.activemenu->nitems > 0) {
+ // out of any region
+ ((menucommon_s*)(uis.activemenu->items[uis.activemenu->cursor]))->flags &= ~QMF_HASMOUSEFOCUS;
+ }
+}
+
+char *UI_Argv( int arg ) {
+ static char buffer[MAX_STRING_CHARS];
+
+ trap_Argv( arg, buffer, sizeof( buffer ) );
+
+ return buffer;
+}
+
+
+char *UI_Cvar_VariableString( const char *var_name ) {
+ static char buffer[MAX_STRING_CHARS];
+
+ trap_Cvar_VariableStringBuffer( var_name, buffer, sizeof( buffer ) );
+
+ return buffer;
+}
+
+
+/*
+=================
+UI_Cache
+=================
+*/
+void UI_Cache_f( void ) {
+ MainMenu_Cache();
+ InGame_Cache();
+ ConfirmMenu_Cache();
+ PlayerModel_Cache();
+ PlayerSettings_Cache();
+ Controls_Cache();
+ Demos_Cache();
+ UI_CinematicsMenu_Cache();
+ Preferences_Cache();
+ ServerInfo_Cache();
+ SpecifyServer_Cache();
+ ArenaServers_Cache();
+ StartServer_Cache();
+ ServerOptions_Cache();
+ DriverInfo_Cache();
+ GraphicsOptions_Cache();
+ UI_DisplayOptionsMenu_Cache();
+ UI_SoundOptionsMenu_Cache();
+ UI_NetworkOptionsMenu_Cache();
+ UI_SPLevelMenu_Cache();
+ UI_SPSkillMenu_Cache();
+ UI_SPPostgameMenu_Cache();
+ TeamMain_Cache();
+ UI_AddBots_Cache();
+ UI_RemoveBots_Cache();
+ UI_SetupMenu_Cache();
+// UI_LoadConfig_Cache();
+// UI_SaveConfigMenu_Cache();
+ UI_BotSelectMenu_Cache();
+ UI_CDKeyMenu_Cache();
+ UI_ModsMenu_Cache();
+
+}
+
+
+/*
+=================
+UI_ConsoleCommand
+=================
+*/
+qboolean UI_ConsoleCommand( int realTime ) {
+ char *cmd;
+
+ cmd = UI_Argv( 0 );
+
+ // ensure minimum menu data is available
+ Menu_Cache();
+
+ if ( Q_stricmp (cmd, "levelselect") == 0 ) {
+ UI_SPLevelMenu_f();
+ return qtrue;
+ }
+
+ if ( Q_stricmp (cmd, "postgame") == 0 ) {
+ UI_SPPostgameMenu_f();
+ return qtrue;
+ }
+
+ if ( Q_stricmp (cmd, "ui_cache") == 0 ) {
+ UI_Cache_f();
+ return qtrue;
+ }
+
+ if ( Q_stricmp (cmd, "ui_cinematics") == 0 ) {
+ UI_CinematicsMenu_f();
+ return qtrue;
+ }
+
+ if ( Q_stricmp (cmd, "ui_teamOrders") == 0 ) {
+ UI_TeamOrdersMenu_f();
+ return qtrue;
+ }
+
+ if ( Q_stricmp (cmd, "iamacheater") == 0 ) {
+ UI_SPUnlock_f();
+ return qtrue;
+ }
+
+ if ( Q_stricmp (cmd, "iamamonkey") == 0 ) {
+ UI_SPUnlockMedals_f();
+ return qtrue;
+ }
+
+ if ( Q_stricmp (cmd, "ui_cdkey") == 0 ) {
+ UI_CDKeyMenu_f();
+ return qtrue;
+ }
+
+ return qfalse;
+}
+
+/*
+=================
+UI_Shutdown
+=================
+*/
+void UI_Shutdown( void ) {
+}
+
+/*
+=================
+UI_Init
+=================
+*/
+void UI_Init( void ) {
+ UI_RegisterCvars();
+
+ UI_InitGameinfo();
+
+ // cache redundant calulations
+ trap_GetGlconfig( &uis.glconfig );
+
+ // for 640x480 virtualized screen
+ uis.scale = uis.glconfig.vidHeight * (1.0/480.0);
+ if ( uis.glconfig.vidWidth * 480 > uis.glconfig.vidHeight * 640 ) {
+ // wide screen
+ uis.bias = 0.5 * ( uis.glconfig.vidWidth - ( uis.glconfig.vidHeight * (640.0/480.0) ) );
+ }
+ else {
+ // no wide screen
+ uis.bias = 0;
+ }
+
+ // initialize the menu system
+ Menu_Cache();
+
+ uis.activemenu = NULL;
+ uis.menusp = 0;
+}
+
+/*
+================
+UI_AdjustFrom640
+
+Adjusted for resolution and screen aspect ratio
+================
+*/
+void UI_AdjustFrom640( float *x, float *y, float *w, float *h ) {
+ // expect valid pointers
+ *x = *x * uis.scale + uis.bias;
+ *y *= uis.scale;
+ *w *= uis.scale;
+ *h *= uis.scale;
+}
+
+void UI_DrawNamedPic( float x, float y, float width, float height, const char *picname ) {
+ qhandle_t hShader;
+
+ hShader = trap_R_RegisterShaderNoMip( picname );
+ UI_AdjustFrom640( &x, &y, &width, &height );
+ trap_R_DrawStretchPic( x, y, width, height, 0, 0, 1, 1, hShader );
+}
+
+void UI_DrawHandlePic( float x, float y, float w, float h, qhandle_t hShader ) {
+ float s0;
+ float s1;
+ float t0;
+ float t1;
+
+ if( w < 0 ) { // flip about vertical
+ w = -w;
+ s0 = 1;
+ s1 = 0;
+ }
+ else {
+ s0 = 0;
+ s1 = 1;
+ }
+
+ if( h < 0 ) { // flip about horizontal
+ h = -h;
+ t0 = 1;
+ t1 = 0;
+ }
+ else {
+ t0 = 0;
+ t1 = 1;
+ }
+
+ UI_AdjustFrom640( &x, &y, &w, &h );
+ trap_R_DrawStretchPic( x, y, w, h, s0, t0, s1, t1, hShader );
+}
+
+/*
+================
+UI_FillRect
+
+Coordinates are 640*480 virtual values
+=================
+*/
+void UI_FillRect( float x, float y, float width, float height, const float *color ) {
+ trap_R_SetColor( color );
+
+ UI_AdjustFrom640( &x, &y, &width, &height );
+ trap_R_DrawStretchPic( x, y, width, height, 0, 0, 0, 0, uis.whiteShader );
+
+ trap_R_SetColor( NULL );
+}
+
+/*
+================
+UI_DrawRect
+
+Coordinates are 640*480 virtual values
+=================
+*/
+void UI_DrawRect( float x, float y, float width, float height, const float *color ) {
+ trap_R_SetColor( color );
+
+ UI_AdjustFrom640( &x, &y, &width, &height );
+
+ trap_R_DrawStretchPic( x, y, width, 1, 0, 0, 0, 0, uis.whiteShader );
+ trap_R_DrawStretchPic( x, y, 1, height, 0, 0, 0, 0, uis.whiteShader );
+ trap_R_DrawStretchPic( x, y + height - 1, width, 1, 0, 0, 0, 0, uis.whiteShader );
+ trap_R_DrawStretchPic( x + width - 1, y, 1, height, 0, 0, 0, 0, uis.whiteShader );
+
+ trap_R_SetColor( NULL );
+}
+
+void UI_SetColor( const float *rgba ) {
+ trap_R_SetColor( rgba );
+}
+
+void UI_UpdateScreen( void ) {
+ trap_UpdateScreen();
+}
+
+/*
+=================
+UI_Refresh
+=================
+*/
+void UI_Refresh( int realtime )
+{
+ uis.frametime = realtime - uis.realtime;
+ uis.realtime = realtime;
+
+ if ( !( trap_Key_GetCatcher() & KEYCATCH_UI ) ) {
+ return;
+ }
+
+ UI_UpdateCvars();
+
+ if ( uis.activemenu )
+ {
+ if (uis.activemenu->fullscreen)
+ {
+ // draw the background
+ if( uis.activemenu->showlogo ) {
+ UI_DrawHandlePic( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, uis.menuBackShader );
+ }
+ else {
+ UI_DrawHandlePic( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, uis.menuBackNoLogoShader );
+ }
+ }
+
+ if (uis.activemenu->draw)
+ uis.activemenu->draw();
+ else
+ Menu_Draw( uis.activemenu );
+
+ if( uis.firstdraw ) {
+ UI_MouseEvent( 0, 0 );
+ uis.firstdraw = qfalse;
+ }
+ }
+
+ // draw cursor
+ UI_SetColor( NULL );
+ UI_DrawHandlePic( uis.cursorx-16, uis.cursory-16, 32, 32, uis.cursor);
+
+#ifndef NDEBUG
+ if (uis.debug)
+ {
+ // cursor coordinates
+ UI_DrawString( 0, 0, va("(%d,%d)",uis.cursorx,uis.cursory), UI_LEFT|UI_SMALLFONT, colorRed );
+ }
+#endif
+
+ // delay playing the enter sound until after the
+ // menu has been drawn, to avoid delay while
+ // caching images
+ if (m_entersound)
+ {
+ trap_S_StartLocalSound( menu_in_sound, CHAN_LOCAL_SOUND );
+ m_entersound = qfalse;
+ }
+}
+
+void UI_DrawTextBox (int x, int y, int width, int lines)
+{
+ UI_FillRect( x + BIGCHAR_WIDTH/2, y + BIGCHAR_HEIGHT/2, ( width + 1 ) * BIGCHAR_WIDTH, ( lines + 1 ) * BIGCHAR_HEIGHT, colorBlack );
+ UI_DrawRect( x + BIGCHAR_WIDTH/2, y + BIGCHAR_HEIGHT/2, ( width + 1 ) * BIGCHAR_WIDTH, ( lines + 1 ) * BIGCHAR_HEIGHT, colorWhite );
+}
+
+qboolean UI_CursorInRect (int x, int y, int width, int height)
+{
+ if (uis.cursorx < x ||
+ uis.cursory < y ||
+ uis.cursorx > x+width ||
+ uis.cursory > y+height)
+ return qfalse;
+
+ return qtrue;
+}
diff --git a/code/q3_ui/ui_cdkey.c b/code/q3_ui/ui_cdkey.c
new file mode 100755
index 0000000..0b1f718
--- /dev/null
+++ b/code/q3_ui/ui_cdkey.c
@@ -0,0 +1,291 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*
+=======================================================================
+
+CD KEY MENU
+
+=======================================================================
+*/
+
+
+#include "ui_local.h"
+
+
+#define ART_FRAME "menu/art/cut_frame"
+#define ART_ACCEPT0 "menu/art/accept_0"
+#define ART_ACCEPT1 "menu/art/accept_1"
+#define ART_BACK0 "menu/art/back_0"
+#define ART_BACK1 "menu/art/back_1"
+
+#define ID_CDKEY 10
+#define ID_ACCEPT 11
+#define ID_BACK 12
+
+
+typedef struct {
+ menuframework_s menu;
+
+ menutext_s banner;
+ menubitmap_s frame;
+
+ menufield_s cdkey;
+
+ menubitmap_s accept;
+ menubitmap_s back;
+} cdkeyMenuInfo_t;
+
+static cdkeyMenuInfo_t cdkeyMenuInfo;
+
+
+/*
+===============
+UI_CDKeyMenu_Event
+===============
+*/
+static void UI_CDKeyMenu_Event( void *ptr, int event ) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+
+ switch( ((menucommon_s*)ptr)->id ) {
+ case ID_ACCEPT:
+ if( cdkeyMenuInfo.cdkey.field.buffer[0] ) {
+ trap_SetCDKey( cdkeyMenuInfo.cdkey.field.buffer );
+ }
+ UI_PopMenu();
+ break;
+
+ case ID_BACK:
+ UI_PopMenu();
+ break;
+ }
+}
+
+
+/*
+=================
+UI_CDKeyMenu_PreValidateKey
+=================
+*/
+static int UI_CDKeyMenu_PreValidateKey( const char *key ) {
+ char ch;
+
+ if( strlen( key ) != 16 ) {
+ return 1;
+ }
+
+ while( ( ch = *key++ ) ) {
+ switch( ch ) {
+ case '2':
+ case '3':
+ case '7':
+ case 'a':
+ case 'b':
+ case 'c':
+ case 'd':
+ case 'g':
+ case 'h':
+ case 'j':
+ case 'l':
+ case 'p':
+ case 'r':
+ case 's':
+ case 't':
+ case 'w':
+ continue;
+ default:
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+
+/*
+=================
+UI_CDKeyMenu_DrawKey
+=================
+*/
+static void UI_CDKeyMenu_DrawKey( void *self ) {
+ menufield_s *f;
+ qboolean focus;
+ int style;
+ char c;
+ float *color;
+ int x, y;
+ int val;
+
+ f = (menufield_s *)self;
+
+ focus = (f->generic.parent->cursor == f->generic.menuPosition);
+
+ style = UI_LEFT;
+ if( focus ) {
+ color = color_yellow;
+ }
+ else {
+ color = color_orange;
+ }
+
+ x = 320 - 8 * BIGCHAR_WIDTH;
+ y = 240 - BIGCHAR_HEIGHT / 2;
+ UI_FillRect( x, y, 16 * BIGCHAR_WIDTH, BIGCHAR_HEIGHT, listbar_color );
+ UI_DrawString( x, y, f->field.buffer, style, color );
+
+ // draw cursor if we have focus
+ if( focus ) {
+ if ( trap_Key_GetOverstrikeMode() ) {
+ c = 11;
+ } else {
+ c = 10;
+ }
+
+ style &= ~UI_PULSE;
+ style |= UI_BLINK;
+
+ UI_DrawChar( x + f->field.cursor * BIGCHAR_WIDTH, y, c, style, color_white );
+ }
+
+ val = UI_CDKeyMenu_PreValidateKey( f->field.buffer );
+ if( val == 1 ) {
+ UI_DrawProportionalString( 320, 376, "Please enter your CD Key", UI_CENTER|UI_SMALLFONT, color_yellow );
+ }
+ else if ( val == 0 ) {
+ UI_DrawProportionalString( 320, 376, "The CD Key appears to be valid, thank you", UI_CENTER|UI_SMALLFONT, color_white );
+ }
+ else {
+ UI_DrawProportionalString( 320, 376, "The CD Key is not valid", UI_CENTER|UI_SMALLFONT, color_red );
+ }
+}
+
+
+/*
+===============
+UI_CDKeyMenu_Init
+===============
+*/
+static void UI_CDKeyMenu_Init( void ) {
+ trap_Cvar_Set( "ui_cdkeychecked", "1" );
+
+ UI_CDKeyMenu_Cache();
+
+ memset( &cdkeyMenuInfo, 0, sizeof(cdkeyMenuInfo) );
+ cdkeyMenuInfo.menu.wrapAround = qtrue;
+ cdkeyMenuInfo.menu.fullscreen = qtrue;
+
+ cdkeyMenuInfo.banner.generic.type = MTYPE_BTEXT;
+ cdkeyMenuInfo.banner.generic.x = 320;
+ cdkeyMenuInfo.banner.generic.y = 16;
+ cdkeyMenuInfo.banner.string = "CD KEY";
+ cdkeyMenuInfo.banner.color = color_white;
+ cdkeyMenuInfo.banner.style = UI_CENTER;
+
+ cdkeyMenuInfo.frame.generic.type = MTYPE_BITMAP;
+ cdkeyMenuInfo.frame.generic.name = ART_FRAME;
+ cdkeyMenuInfo.frame.generic.flags = QMF_INACTIVE;
+ cdkeyMenuInfo.frame.generic.x = 142;
+ cdkeyMenuInfo.frame.generic.y = 118;
+ cdkeyMenuInfo.frame.width = 359;
+ cdkeyMenuInfo.frame.height = 256;
+
+ cdkeyMenuInfo.cdkey.generic.type = MTYPE_FIELD;
+ cdkeyMenuInfo.cdkey.generic.name = "CD Key:";
+ cdkeyMenuInfo.cdkey.generic.flags = QMF_LOWERCASE;
+ cdkeyMenuInfo.cdkey.generic.x = 320 - BIGCHAR_WIDTH * 2.5;
+ cdkeyMenuInfo.cdkey.generic.y = 240 - BIGCHAR_HEIGHT / 2;
+ cdkeyMenuInfo.cdkey.field.widthInChars = 16;
+ cdkeyMenuInfo.cdkey.field.maxchars = 16;
+ cdkeyMenuInfo.cdkey.generic.ownerdraw = UI_CDKeyMenu_DrawKey;
+
+ cdkeyMenuInfo.accept.generic.type = MTYPE_BITMAP;
+ cdkeyMenuInfo.accept.generic.name = ART_ACCEPT0;
+ cdkeyMenuInfo.accept.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ cdkeyMenuInfo.accept.generic.id = ID_ACCEPT;
+ cdkeyMenuInfo.accept.generic.callback = UI_CDKeyMenu_Event;
+ cdkeyMenuInfo.accept.generic.x = 640;
+ cdkeyMenuInfo.accept.generic.y = 480-64;
+ cdkeyMenuInfo.accept.width = 128;
+ cdkeyMenuInfo.accept.height = 64;
+ cdkeyMenuInfo.accept.focuspic = ART_ACCEPT1;
+
+ cdkeyMenuInfo.back.generic.type = MTYPE_BITMAP;
+ cdkeyMenuInfo.back.generic.name = ART_BACK0;
+ cdkeyMenuInfo.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ cdkeyMenuInfo.back.generic.id = ID_BACK;
+ cdkeyMenuInfo.back.generic.callback = UI_CDKeyMenu_Event;
+ cdkeyMenuInfo.back.generic.x = 0;
+ cdkeyMenuInfo.back.generic.y = 480-64;
+ cdkeyMenuInfo.back.width = 128;
+ cdkeyMenuInfo.back.height = 64;
+ cdkeyMenuInfo.back.focuspic = ART_BACK1;
+
+ Menu_AddItem( &cdkeyMenuInfo.menu, &cdkeyMenuInfo.banner );
+ Menu_AddItem( &cdkeyMenuInfo.menu, &cdkeyMenuInfo.frame );
+ Menu_AddItem( &cdkeyMenuInfo.menu, &cdkeyMenuInfo.cdkey );
+ Menu_AddItem( &cdkeyMenuInfo.menu, &cdkeyMenuInfo.accept );
+ if( uis.menusp ) {
+ Menu_AddItem( &cdkeyMenuInfo.menu, &cdkeyMenuInfo.back );
+ }
+
+ trap_GetCDKey( cdkeyMenuInfo.cdkey.field.buffer, cdkeyMenuInfo.cdkey.field.maxchars + 1 );
+ if( trap_VerifyCDKey( cdkeyMenuInfo.cdkey.field.buffer, NULL ) == qfalse ) {
+ cdkeyMenuInfo.cdkey.field.buffer[0] = 0;
+ }
+}
+
+
+/*
+=================
+UI_CDKeyMenu_Cache
+=================
+*/
+void UI_CDKeyMenu_Cache( void ) {
+ trap_R_RegisterShaderNoMip( ART_ACCEPT0 );
+ trap_R_RegisterShaderNoMip( ART_ACCEPT1 );
+ trap_R_RegisterShaderNoMip( ART_BACK0 );
+ trap_R_RegisterShaderNoMip( ART_BACK1 );
+ trap_R_RegisterShaderNoMip( ART_FRAME );
+}
+
+
+/*
+===============
+UI_CDKeyMenu
+===============
+*/
+void UI_CDKeyMenu( void ) {
+ UI_CDKeyMenu_Init();
+ UI_PushMenu( &cdkeyMenuInfo.menu );
+}
+
+
+/*
+===============
+UI_CDKeyMenu_f
+===============
+*/
+void UI_CDKeyMenu_f( void ) {
+ UI_CDKeyMenu();
+}
diff --git a/code/q3_ui/ui_cinematics.c b/code/q3_ui/ui_cinematics.c
new file mode 100755
index 0000000..6092b4a
--- /dev/null
+++ b/code/q3_ui/ui_cinematics.c
@@ -0,0 +1,350 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#include "ui_local.h"
+
+
+#define ART_BACK0 "menu/art/back_0"
+#define ART_BACK1 "menu/art/back_1"
+#define ART_FRAMEL "menu/art/frame2_l"
+#define ART_FRAMER "menu/art/frame1_r"
+
+#define VERTICAL_SPACING 30
+
+#define ID_BACK 10
+#define ID_CIN_IDLOGO 11
+#define ID_CIN_INTRO 12
+#define ID_CIN_TIER1 13
+#define ID_CIN_TIER2 14
+#define ID_CIN_TIER3 15
+#define ID_CIN_TIER4 16
+#define ID_CIN_TIER5 17
+#define ID_CIN_TIER6 18
+#define ID_CIN_TIER7 19
+#define ID_CIN_END 20
+
+
+typedef struct {
+ menuframework_s menu;
+ menutext_s banner;
+ menubitmap_s framel;
+ menubitmap_s framer;
+ menutext_s cin_idlogo;
+ menutext_s cin_intro;
+ menutext_s cin_tier1;
+ menutext_s cin_tier2;
+ menutext_s cin_tier3;
+ menutext_s cin_tier4;
+ menutext_s cin_tier5;
+ menutext_s cin_tier6;
+ menutext_s cin_tier7;
+ menutext_s cin_end;
+ menubitmap_s back;
+} cinematicsMenuInfo_t;
+
+static cinematicsMenuInfo_t cinematicsMenuInfo;
+
+static char *cinematics[] = {
+ "idlogo",
+ "intro",
+ "tier1",
+ "tier2",
+ "tier3",
+ "tier4",
+ "tier5",
+ "tier6",
+ "tier7",
+ "end"
+};
+
+/*
+===============
+UI_CinematicsMenu_BackEvent
+===============
+*/
+static void UI_CinematicsMenu_BackEvent( void *ptr, int event ) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+ UI_PopMenu();
+}
+
+
+/*
+===============
+UI_CinematicsMenu_Event
+===============
+*/
+static void UI_CinematicsMenu_Event( void *ptr, int event ) {
+ int n;
+
+ if (event != QM_ACTIVATED)
+ return;
+
+ n = ((menucommon_s*)ptr)->id - ID_CIN_IDLOGO;
+ trap_Cvar_Set( "nextmap", va( "ui_cinematics %i", n ) );
+ if( uis.demoversion && ((menucommon_s*)ptr)->id == ID_CIN_END ) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, "disconnect; cinematic demoEnd.RoQ 1\n" );
+ }
+ else {
+ trap_Cmd_ExecuteText( EXEC_APPEND, va( "disconnect; cinematic %s.RoQ\n", cinematics[n] ) );
+ }
+}
+
+
+/*
+===============
+UI_CinematicsMenu_Init
+===============
+*/
+static void UI_CinematicsMenu_Init( void ) {
+ int y;
+
+ UI_CinematicsMenu_Cache();
+
+ memset( &cinematicsMenuInfo, 0, sizeof(cinematicsMenuInfo) );
+ cinematicsMenuInfo.menu.fullscreen = qtrue;
+
+ cinematicsMenuInfo.banner.generic.type = MTYPE_BTEXT;
+ cinematicsMenuInfo.banner.generic.x = 320;
+ cinematicsMenuInfo.banner.generic.y = 16;
+ cinematicsMenuInfo.banner.string = "CINEMATICS";
+ cinematicsMenuInfo.banner.color = color_white;
+ cinematicsMenuInfo.banner.style = UI_CENTER;
+
+ cinematicsMenuInfo.framel.generic.type = MTYPE_BITMAP;
+ cinematicsMenuInfo.framel.generic.name = ART_FRAMEL;
+ cinematicsMenuInfo.framel.generic.flags = QMF_INACTIVE;
+ cinematicsMenuInfo.framel.generic.x = 0;
+ cinematicsMenuInfo.framel.generic.y = 78;
+ cinematicsMenuInfo.framel.width = 256;
+ cinematicsMenuInfo.framel.height = 329;
+
+ cinematicsMenuInfo.framer.generic.type = MTYPE_BITMAP;
+ cinematicsMenuInfo.framer.generic.name = ART_FRAMER;
+ cinematicsMenuInfo.framer.generic.flags = QMF_INACTIVE;
+ cinematicsMenuInfo.framer.generic.x = 376;
+ cinematicsMenuInfo.framer.generic.y = 76;
+ cinematicsMenuInfo.framer.width = 256;
+ cinematicsMenuInfo.framer.height = 334;
+
+ y = 100;
+ cinematicsMenuInfo.cin_idlogo.generic.type = MTYPE_PTEXT;
+ cinematicsMenuInfo.cin_idlogo.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ cinematicsMenuInfo.cin_idlogo.generic.x = 320;
+ cinematicsMenuInfo.cin_idlogo.generic.y = y;
+ cinematicsMenuInfo.cin_idlogo.generic.id = ID_CIN_IDLOGO;
+ cinematicsMenuInfo.cin_idlogo.generic.callback = UI_CinematicsMenu_Event;
+ cinematicsMenuInfo.cin_idlogo.string = "ID LOGO";
+ cinematicsMenuInfo.cin_idlogo.color = color_red;
+ cinematicsMenuInfo.cin_idlogo.style = UI_CENTER;
+
+ y += VERTICAL_SPACING;
+ cinematicsMenuInfo.cin_intro.generic.type = MTYPE_PTEXT;
+ cinematicsMenuInfo.cin_intro.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ cinematicsMenuInfo.cin_intro.generic.x = 320;
+ cinematicsMenuInfo.cin_intro.generic.y = y;
+ cinematicsMenuInfo.cin_intro.generic.id = ID_CIN_INTRO;
+ cinematicsMenuInfo.cin_intro.generic.callback = UI_CinematicsMenu_Event;
+ cinematicsMenuInfo.cin_intro.string = "INTRO";
+ cinematicsMenuInfo.cin_intro.color = color_red;
+ cinematicsMenuInfo.cin_intro.style = UI_CENTER;
+ if( uis.demoversion ) {
+ cinematicsMenuInfo.cin_intro.generic.flags |= QMF_GRAYED;
+ }
+
+ y += VERTICAL_SPACING;
+ cinematicsMenuInfo.cin_tier1.generic.type = MTYPE_PTEXT;
+ cinematicsMenuInfo.cin_tier1.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ cinematicsMenuInfo.cin_tier1.generic.x = 320;
+ cinematicsMenuInfo.cin_tier1.generic.y = y;
+ cinematicsMenuInfo.cin_tier1.generic.id = ID_CIN_TIER1;
+ cinematicsMenuInfo.cin_tier1.generic.callback = UI_CinematicsMenu_Event;
+ cinematicsMenuInfo.cin_tier1.string = "Tier 1";
+ cinematicsMenuInfo.cin_tier1.color = color_red;
+ cinematicsMenuInfo.cin_tier1.style = UI_CENTER;
+ if( !UI_CanShowTierVideo( 1 ) ) {
+ cinematicsMenuInfo.cin_tier1.generic.flags |= QMF_GRAYED;
+ }
+
+ y += VERTICAL_SPACING;
+ cinematicsMenuInfo.cin_tier2.generic.type = MTYPE_PTEXT;
+ cinematicsMenuInfo.cin_tier2.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ cinematicsMenuInfo.cin_tier2.generic.x = 320;
+ cinematicsMenuInfo.cin_tier2.generic.y = y;
+ cinematicsMenuInfo.cin_tier2.generic.id = ID_CIN_TIER2;
+ cinematicsMenuInfo.cin_tier2.generic.callback = UI_CinematicsMenu_Event;
+ cinematicsMenuInfo.cin_tier2.string = "Tier 2";
+ cinematicsMenuInfo.cin_tier2.color = color_red;
+ cinematicsMenuInfo.cin_tier2.style = UI_CENTER;
+ if( !UI_CanShowTierVideo( 2 ) ) {
+ cinematicsMenuInfo.cin_tier2.generic.flags |= QMF_GRAYED;
+ }
+
+ y += VERTICAL_SPACING;
+ cinematicsMenuInfo.cin_tier3.generic.type = MTYPE_PTEXT;
+ cinematicsMenuInfo.cin_tier3.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ cinematicsMenuInfo.cin_tier3.generic.x = 320;
+ cinematicsMenuInfo.cin_tier3.generic.y = y;
+ cinematicsMenuInfo.cin_tier3.generic.id = ID_CIN_TIER3;
+ cinematicsMenuInfo.cin_tier3.generic.callback = UI_CinematicsMenu_Event;
+ cinematicsMenuInfo.cin_tier3.string = "Tier 3";
+ cinematicsMenuInfo.cin_tier3.color = color_red;
+ cinematicsMenuInfo.cin_tier3.style = UI_CENTER;
+ if( !UI_CanShowTierVideo( 3 ) ) {
+ cinematicsMenuInfo.cin_tier3.generic.flags |= QMF_GRAYED;
+ }
+
+ y += VERTICAL_SPACING;
+ cinematicsMenuInfo.cin_tier4.generic.type = MTYPE_PTEXT;
+ cinematicsMenuInfo.cin_tier4.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ cinematicsMenuInfo.cin_tier4.generic.x = 320;
+ cinematicsMenuInfo.cin_tier4.generic.y = y;
+ cinematicsMenuInfo.cin_tier4.generic.id = ID_CIN_TIER4;
+ cinematicsMenuInfo.cin_tier4.generic.callback = UI_CinematicsMenu_Event;
+ cinematicsMenuInfo.cin_tier4.string = "Tier 4";
+ cinematicsMenuInfo.cin_tier4.color = color_red;
+ cinematicsMenuInfo.cin_tier4.style = UI_CENTER;
+ if( !UI_CanShowTierVideo( 4 ) ) {
+ cinematicsMenuInfo.cin_tier4.generic.flags |= QMF_GRAYED;
+ }
+
+ y += VERTICAL_SPACING;
+ cinematicsMenuInfo.cin_tier5.generic.type = MTYPE_PTEXT;
+ cinematicsMenuInfo.cin_tier5.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ cinematicsMenuInfo.cin_tier5.generic.x = 320;
+ cinematicsMenuInfo.cin_tier5.generic.y = y;
+ cinematicsMenuInfo.cin_tier5.generic.id = ID_CIN_TIER5;
+ cinematicsMenuInfo.cin_tier5.generic.callback = UI_CinematicsMenu_Event;
+ cinematicsMenuInfo.cin_tier5.string = "Tier 5";
+ cinematicsMenuInfo.cin_tier5.color = color_red;
+ cinematicsMenuInfo.cin_tier5.style = UI_CENTER;
+ if( !UI_CanShowTierVideo( 5 ) ) {
+ cinematicsMenuInfo.cin_tier5.generic.flags |= QMF_GRAYED;
+ }
+
+ y += VERTICAL_SPACING;
+ cinematicsMenuInfo.cin_tier6.generic.type = MTYPE_PTEXT;
+ cinematicsMenuInfo.cin_tier6.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ cinematicsMenuInfo.cin_tier6.generic.x = 320;
+ cinematicsMenuInfo.cin_tier6.generic.y = y;
+ cinematicsMenuInfo.cin_tier6.generic.id = ID_CIN_TIER6;
+ cinematicsMenuInfo.cin_tier6.generic.callback = UI_CinematicsMenu_Event;
+ cinematicsMenuInfo.cin_tier6.string = "Tier 6";
+ cinematicsMenuInfo.cin_tier6.color = color_red;
+ cinematicsMenuInfo.cin_tier6.style = UI_CENTER;
+ if( !UI_CanShowTierVideo( 6 ) ) {
+ cinematicsMenuInfo.cin_tier6.generic.flags |= QMF_GRAYED;
+ }
+
+ y += VERTICAL_SPACING;
+ cinematicsMenuInfo.cin_tier7.generic.type = MTYPE_PTEXT;
+ cinematicsMenuInfo.cin_tier7.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ cinematicsMenuInfo.cin_tier7.generic.x = 320;
+ cinematicsMenuInfo.cin_tier7.generic.y = y;
+ cinematicsMenuInfo.cin_tier7.generic.id = ID_CIN_TIER7;
+ cinematicsMenuInfo.cin_tier7.generic.callback = UI_CinematicsMenu_Event;
+ cinematicsMenuInfo.cin_tier7.string = "Tier 7";
+ cinematicsMenuInfo.cin_tier7.color = color_red;
+ cinematicsMenuInfo.cin_tier7.style = UI_CENTER;
+ if( !UI_CanShowTierVideo( 7 ) ) {
+ cinematicsMenuInfo.cin_tier7.generic.flags |= QMF_GRAYED;
+ }
+
+ y += VERTICAL_SPACING;
+ cinematicsMenuInfo.cin_end.generic.type = MTYPE_PTEXT;
+ cinematicsMenuInfo.cin_end.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ cinematicsMenuInfo.cin_end.generic.x = 320;
+ cinematicsMenuInfo.cin_end.generic.y = y;
+ cinematicsMenuInfo.cin_end.generic.id = ID_CIN_END;
+ cinematicsMenuInfo.cin_end.generic.callback = UI_CinematicsMenu_Event;
+ cinematicsMenuInfo.cin_end.string = "END";
+ cinematicsMenuInfo.cin_end.color = color_red;
+ cinematicsMenuInfo.cin_end.style = UI_CENTER;
+ if( !UI_CanShowTierVideo( 8 ) ) {
+ cinematicsMenuInfo.cin_end.generic.flags |= QMF_GRAYED;
+ }
+
+ cinematicsMenuInfo.back.generic.type = MTYPE_BITMAP;
+ cinematicsMenuInfo.back.generic.name = ART_BACK0;
+ cinematicsMenuInfo.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ cinematicsMenuInfo.back.generic.id = ID_BACK;
+ cinematicsMenuInfo.back.generic.callback = UI_CinematicsMenu_BackEvent;
+ cinematicsMenuInfo.back.generic.x = 0;
+ cinematicsMenuInfo.back.generic.y = 480-64;
+ cinematicsMenuInfo.back.width = 128;
+ cinematicsMenuInfo.back.height = 64;
+ cinematicsMenuInfo.back.focuspic = ART_BACK1;
+
+ Menu_AddItem( &cinematicsMenuInfo.menu, &cinematicsMenuInfo.banner );
+ Menu_AddItem( &cinematicsMenuInfo.menu, &cinematicsMenuInfo.framel );
+ Menu_AddItem( &cinematicsMenuInfo.menu, &cinematicsMenuInfo.framer );
+ Menu_AddItem( &cinematicsMenuInfo.menu, &cinematicsMenuInfo.cin_idlogo );
+ Menu_AddItem( &cinematicsMenuInfo.menu, &cinematicsMenuInfo.cin_intro );
+ Menu_AddItem( &cinematicsMenuInfo.menu, &cinematicsMenuInfo.cin_tier1 );
+ Menu_AddItem( &cinematicsMenuInfo.menu, &cinematicsMenuInfo.cin_tier2 );
+ Menu_AddItem( &cinematicsMenuInfo.menu, &cinematicsMenuInfo.cin_tier3 );
+ Menu_AddItem( &cinematicsMenuInfo.menu, &cinematicsMenuInfo.cin_tier4 );
+ Menu_AddItem( &cinematicsMenuInfo.menu, &cinematicsMenuInfo.cin_tier5 );
+ Menu_AddItem( &cinematicsMenuInfo.menu, &cinematicsMenuInfo.cin_tier6 );
+ Menu_AddItem( &cinematicsMenuInfo.menu, &cinematicsMenuInfo.cin_tier7 );
+ Menu_AddItem( &cinematicsMenuInfo.menu, &cinematicsMenuInfo.cin_end );
+ Menu_AddItem( &cinematicsMenuInfo.menu, &cinematicsMenuInfo.back );
+}
+
+
+/*
+=================
+UI_CinematicsMenu_Cache
+=================
+*/
+void UI_CinematicsMenu_Cache( void ) {
+ trap_R_RegisterShaderNoMip( ART_BACK0 );
+ trap_R_RegisterShaderNoMip( ART_BACK1 );
+ trap_R_RegisterShaderNoMip( ART_FRAMEL );
+ trap_R_RegisterShaderNoMip( ART_FRAMER );
+}
+
+
+/*
+===============
+UI_CinematicsMenu
+===============
+*/
+void UI_CinematicsMenu( void ) {
+ UI_CinematicsMenu_Init();
+ UI_PushMenu( &cinematicsMenuInfo.menu );
+}
+
+
+/*
+===============
+UI_CinematicsMenu_f
+===============
+*/
+void UI_CinematicsMenu_f( void ) {
+ int n;
+
+ n = atoi( UI_Argv( 1 ) );
+ UI_CinematicsMenu();
+ Menu_SetCursorToItem( &cinematicsMenuInfo.menu, cinematicsMenuInfo.menu.items[n + 3] );
+}
diff --git a/code/q3_ui/ui_confirm.c b/code/q3_ui/ui_confirm.c
new file mode 100755
index 0000000..c58071b
--- /dev/null
+++ b/code/q3_ui/ui_confirm.c
@@ -0,0 +1,293 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*
+=======================================================================
+
+CONFIRMATION MENU
+
+=======================================================================
+*/
+
+
+#include "ui_local.h"
+
+
+#define ART_CONFIRM_FRAME "menu/art/cut_frame"
+
+#define ID_CONFIRM_NO 10
+#define ID_CONFIRM_YES 11
+
+
+typedef struct {
+ menuframework_s menu;
+
+ menutext_s no;
+ menutext_s yes;
+
+ int slashX;
+ const char * question;
+ void (*draw)( void );
+ void (*action)( qboolean result );
+
+ int style;
+ const char **lines;
+} confirmMenu_t;
+
+
+static confirmMenu_t s_confirm;
+
+
+/*
+=================
+ConfirmMenu_Event
+=================
+*/
+static void ConfirmMenu_Event( void* ptr, int event ) {
+ qboolean result;
+
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+
+ UI_PopMenu();
+
+ if( ((menucommon_s*)ptr)->id == ID_CONFIRM_NO ) {
+ result = qfalse;
+ }
+ else {
+ result = qtrue;
+ }
+
+ if( s_confirm.action ) {
+ s_confirm.action( result );
+ }
+}
+
+
+/*
+=================
+ConfirmMenu_Key
+=================
+*/
+static sfxHandle_t ConfirmMenu_Key( int key ) {
+ switch ( key ) {
+ case K_KP_LEFTARROW:
+ case K_LEFTARROW:
+ case K_KP_RIGHTARROW:
+ case K_RIGHTARROW:
+ key = K_TAB;
+ break;
+
+ case 'n':
+ case 'N':
+ ConfirmMenu_Event( &s_confirm.no, QM_ACTIVATED );
+ break;
+
+ case 'y':
+ case 'Y':
+ ConfirmMenu_Event( &s_confirm.yes, QM_ACTIVATED );
+ break;
+ }
+
+ return Menu_DefaultKey( &s_confirm.menu, key );
+}
+
+
+/*
+=================
+MessaheMenu_Draw
+=================
+*/
+static void MessageMenu_Draw( void ) {
+ int i,y;
+
+ UI_DrawNamedPic( 142, 118, 359, 256, ART_CONFIRM_FRAME );
+
+ y = 188;
+ for(i=0; s_confirm.lines[i]; i++)
+ {
+ UI_DrawProportionalString( 320, y, s_confirm.lines[i], s_confirm.style, color_red );
+ y += 18;
+ }
+
+ Menu_Draw( &s_confirm.menu );
+
+ if( s_confirm.draw ) {
+ s_confirm.draw();
+ }
+}
+
+/*
+=================
+ConfirmMenu_Draw
+=================
+*/
+static void ConfirmMenu_Draw( void ) {
+ UI_DrawNamedPic( 142, 118, 359, 256, ART_CONFIRM_FRAME );
+ UI_DrawProportionalString( 320, 204, s_confirm.question, s_confirm.style, color_red );
+ UI_DrawProportionalString( s_confirm.slashX, 265, "/", UI_LEFT|UI_INVERSE, color_red );
+
+ Menu_Draw( &s_confirm.menu );
+
+ if( s_confirm.draw ) {
+ s_confirm.draw();
+ }
+}
+
+
+/*
+=================
+ConfirmMenu_Cache
+=================
+*/
+void ConfirmMenu_Cache( void ) {
+ trap_R_RegisterShaderNoMip( ART_CONFIRM_FRAME );
+}
+
+
+/*
+=================
+UI_ConfirmMenu_Stlye
+=================
+*/
+void UI_ConfirmMenu_Style( const char *question, int style, void (*draw)( void ), void (*action)( qboolean result ) ) {
+ uiClientState_t cstate;
+ int n1, n2, n3;
+ int l1, l2, l3;
+
+ // zero set all our globals
+ memset( &s_confirm, 0, sizeof(s_confirm) );
+
+ ConfirmMenu_Cache();
+
+ n1 = UI_ProportionalStringWidth( "YES/NO" );
+ n2 = UI_ProportionalStringWidth( "YES" ) + PROP_GAP_WIDTH;
+ n3 = UI_ProportionalStringWidth( "/" ) + PROP_GAP_WIDTH;
+ l1 = 320 - ( n1 / 2 );
+ l2 = l1 + n2;
+ l3 = l2 + n3;
+ s_confirm.slashX = l2;
+
+ s_confirm.question = question;
+ s_confirm.draw = draw;
+ s_confirm.action = action;
+ s_confirm.style = style;
+
+ s_confirm.menu.draw = ConfirmMenu_Draw;
+ s_confirm.menu.key = ConfirmMenu_Key;
+ s_confirm.menu.wrapAround = qtrue;
+
+ trap_GetClientState( &cstate );
+ if ( cstate.connState >= CA_CONNECTED ) {
+ s_confirm.menu.fullscreen = qfalse;
+ }
+ else {
+ s_confirm.menu.fullscreen = qtrue;
+ }
+
+ s_confirm.yes.generic.type = MTYPE_PTEXT;
+ s_confirm.yes.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_confirm.yes.generic.callback = ConfirmMenu_Event;
+ s_confirm.yes.generic.id = ID_CONFIRM_YES;
+ s_confirm.yes.generic.x = l1;
+ s_confirm.yes.generic.y = 264;
+ s_confirm.yes.string = "YES";
+ s_confirm.yes.color = color_red;
+ s_confirm.yes.style = UI_LEFT;
+
+ s_confirm.no.generic.type = MTYPE_PTEXT;
+ s_confirm.no.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_confirm.no.generic.callback = ConfirmMenu_Event;
+ s_confirm.no.generic.id = ID_CONFIRM_NO;
+ s_confirm.no.generic.x = l3;
+ s_confirm.no.generic.y = 264;
+ s_confirm.no.string = "NO";
+ s_confirm.no.color = color_red;
+ s_confirm.no.style = UI_LEFT;
+
+ Menu_AddItem( &s_confirm.menu, &s_confirm.yes );
+ Menu_AddItem( &s_confirm.menu, &s_confirm.no );
+
+ UI_PushMenu( &s_confirm.menu );
+
+ Menu_SetCursorToItem( &s_confirm.menu, &s_confirm.no );
+}
+
+/*
+=================
+UI_ConfirmMenu
+=================
+*/
+void UI_ConfirmMenu( const char *question, void (*draw)( void ), void (*action)( qboolean result ) ) {
+ UI_ConfirmMenu_Style(question, UI_CENTER|UI_INVERSE, draw, action);
+}
+
+/*
+=================
+UI_Message
+hacked over from Confirm stuff
+=================
+*/
+void UI_Message( const char **lines ) {
+ uiClientState_t cstate;
+ int n1, l1;
+
+ // zero set all our globals
+ memset( &s_confirm, 0, sizeof(s_confirm) );
+
+ ConfirmMenu_Cache();
+
+ n1 = UI_ProportionalStringWidth( "OK" );
+ l1 = 320 - ( n1 / 2 );
+
+ s_confirm.lines = lines;
+ s_confirm.style = UI_CENTER|UI_INVERSE|UI_SMALLFONT;
+
+ s_confirm.menu.draw = MessageMenu_Draw;
+ s_confirm.menu.key = ConfirmMenu_Key;
+ s_confirm.menu.wrapAround = qtrue;
+
+ trap_GetClientState( &cstate );
+ if ( cstate.connState >= CA_CONNECTED ) {
+ s_confirm.menu.fullscreen = qfalse;
+ }
+ else {
+ s_confirm.menu.fullscreen = qtrue;
+ }
+
+ s_confirm.yes.generic.type = MTYPE_PTEXT;
+ s_confirm.yes.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_confirm.yes.generic.callback = ConfirmMenu_Event;
+ s_confirm.yes.generic.id = ID_CONFIRM_YES;
+ s_confirm.yes.generic.x = l1;
+ s_confirm.yes.generic.y = 280;
+ s_confirm.yes.string = "OK";
+ s_confirm.yes.color = color_red;
+ s_confirm.yes.style = UI_LEFT;
+
+ Menu_AddItem( &s_confirm.menu, &s_confirm.yes );
+
+ UI_PushMenu( &s_confirm.menu );
+
+ Menu_SetCursorToItem( &s_confirm.menu, &s_confirm.yes );
+}
diff --git a/code/q3_ui/ui_connect.c b/code/q3_ui/ui_connect.c
new file mode 100755
index 0000000..a348db2
--- /dev/null
+++ b/code/q3_ui/ui_connect.c
@@ -0,0 +1,282 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#include "ui_local.h"
+
+/*
+===============================================================================
+
+CONNECTION SCREEN
+
+===============================================================================
+*/
+
+qboolean passwordNeeded = qtrue;
+menufield_s passwordField;
+
+static connstate_t lastConnState;
+static char lastLoadingText[MAX_INFO_VALUE];
+
+static void UI_ReadableSize ( char *buf, int bufsize, int value )
+{
+ if (value > 1024*1024*1024 ) { // gigs
+ Com_sprintf( buf, bufsize, "%d", value / (1024*1024*1024) );
+ Com_sprintf( buf+strlen(buf), bufsize-strlen(buf), ".%02d GB",
+ (value % (1024*1024*1024))*100 / (1024*1024*1024) );
+ } else if (value > 1024*1024 ) { // megs
+ Com_sprintf( buf, bufsize, "%d", value / (1024*1024) );
+ Com_sprintf( buf+strlen(buf), bufsize-strlen(buf), ".%02d MB",
+ (value % (1024*1024))*100 / (1024*1024) );
+ } else if (value > 1024 ) { // kilos
+ Com_sprintf( buf, bufsize, "%d KB", value / 1024 );
+ } else { // bytes
+ Com_sprintf( buf, bufsize, "%d bytes", value );
+ }
+}
+
+// Assumes time is in msec
+static void UI_PrintTime ( char *buf, int bufsize, int time ) {
+ time /= 1000; // change to seconds
+
+ if (time > 3600) { // in the hours range
+ Com_sprintf( buf, bufsize, "%d hr %d min", time / 3600, (time % 3600) / 60 );
+ } else if (time > 60) { // mins
+ Com_sprintf( buf, bufsize, "%d min %d sec", time / 60, time % 60 );
+ } else { // secs
+ Com_sprintf( buf, bufsize, "%d sec", time );
+ }
+}
+
+static void UI_DisplayDownloadInfo( const char *downloadName ) {
+ static char dlText[] = "Downloading:";
+ static char etaText[] = "Estimated time left:";
+ static char xferText[] = "Transfer rate:";
+
+ int downloadSize, downloadCount, downloadTime;
+ char dlSizeBuf[64], totalSizeBuf[64], xferRateBuf[64], dlTimeBuf[64];
+ int xferRate;
+ int width, leftWidth;
+ int style = UI_LEFT|UI_SMALLFONT|UI_DROPSHADOW;
+ const char *s;
+
+ downloadSize = trap_Cvar_VariableValue( "cl_downloadSize" );
+ downloadCount = trap_Cvar_VariableValue( "cl_downloadCount" );
+ downloadTime = trap_Cvar_VariableValue( "cl_downloadTime" );
+
+#if 0 // bk010104
+ fprintf( stderr, "\n\n-----------------------------------------------\n");
+ fprintf( stderr, "DB: downloadSize: %16d\n", downloadSize );
+ fprintf( stderr, "DB: downloadCount: %16d\n", downloadCount );
+ fprintf( stderr, "DB: downloadTime: %16d\n", downloadTime );
+ fprintf( stderr, "DB: UI realtime: %16d\n", uis.realtime ); // bk
+ fprintf( stderr, "DB: UI frametime: %16d\n", uis.frametime ); // bk
+#endif
+
+ leftWidth = width = UI_ProportionalStringWidth( dlText ) * UI_ProportionalSizeScale( style );
+ width = UI_ProportionalStringWidth( etaText ) * UI_ProportionalSizeScale( style );
+ if (width > leftWidth) leftWidth = width;
+ width = UI_ProportionalStringWidth( xferText ) * UI_ProportionalSizeScale( style );
+ if (width > leftWidth) leftWidth = width;
+ leftWidth += 16;
+
+ UI_DrawProportionalString( 8, 128, dlText, style, color_white );
+ UI_DrawProportionalString( 8, 160, etaText, style, color_white );
+ UI_DrawProportionalString( 8, 224, xferText, style, color_white );
+
+ if (downloadSize > 0) {
+ s = va( "%s (%d%%)", downloadName, downloadCount * 100 / downloadSize );
+ } else {
+ s = downloadName;
+ }
+
+ UI_DrawProportionalString( leftWidth, 128, s, style, color_white );
+
+ UI_ReadableSize( dlSizeBuf, sizeof dlSizeBuf, downloadCount );
+ UI_ReadableSize( totalSizeBuf, sizeof totalSizeBuf, downloadSize );
+
+ if (downloadCount < 4096 || !downloadTime) {
+ UI_DrawProportionalString( leftWidth, 160, "estimating", style, color_white );
+ UI_DrawProportionalString( leftWidth, 192,
+ va("(%s of %s copied)", dlSizeBuf, totalSizeBuf), style, color_white );
+ } else {
+ // bk010108
+ //float elapsedTime = (float)(uis.realtime - downloadTime); // current - start (msecs)
+ //elapsedTime = elapsedTime * 0.001f; // in seconds
+ //if ( elapsedTime <= 0.0f ) elapsedTime == 0.0f;
+ if ( (uis.realtime - downloadTime) / 1000) {
+ xferRate = downloadCount / ((uis.realtime - downloadTime) / 1000);
+ //xferRate = (int)( ((float)downloadCount) / elapsedTime);
+ } else {
+ xferRate = 0;
+ }
+
+ //fprintf( stderr, "DB: elapsedTime: %16.8f\n", elapsedTime ); // bk
+ //fprintf( stderr, "DB: xferRate: %16d\n", xferRate ); // bk
+
+ UI_ReadableSize( xferRateBuf, sizeof xferRateBuf, xferRate );
+
+ // Extrapolate estimated completion time
+ if (downloadSize && xferRate) {
+ int n = downloadSize / xferRate; // estimated time for entire d/l in secs
+
+ // We do it in K (/1024) because we'd overflow around 4MB
+ n = (n - (((downloadCount/1024) * n) / (downloadSize/1024))) * 1000;
+
+ UI_PrintTime ( dlTimeBuf, sizeof dlTimeBuf, n ); // bk010104
+ //(n - (((downloadCount/1024) * n) / (downloadSize/1024))) * 1000);
+
+ UI_DrawProportionalString( leftWidth, 160,
+ dlTimeBuf, style, color_white );
+ UI_DrawProportionalString( leftWidth, 192,
+ va("(%s of %s copied)", dlSizeBuf, totalSizeBuf), style, color_white );
+ } else {
+ UI_DrawProportionalString( leftWidth, 160,
+ "estimating", style, color_white );
+ if (downloadSize) {
+ UI_DrawProportionalString( leftWidth, 192,
+ va("(%s of %s copied)", dlSizeBuf, totalSizeBuf), style, color_white );
+ } else {
+ UI_DrawProportionalString( leftWidth, 192,
+ va("(%s copied)", dlSizeBuf), style, color_white );
+ }
+ }
+
+ if (xferRate) {
+ UI_DrawProportionalString( leftWidth, 224,
+ va("%s/Sec", xferRateBuf), style, color_white );
+ }
+ }
+}
+
+/*
+========================
+UI_DrawConnectScreen
+
+This will also be overlaid on the cgame info screen during loading
+to prevent it from blinking away too rapidly on local or lan games.
+========================
+*/
+void UI_DrawConnectScreen( qboolean overlay ) {
+ char *s;
+ uiClientState_t cstate;
+ char info[MAX_INFO_VALUE];
+
+ Menu_Cache();
+
+ if ( !overlay ) {
+ // draw the dialog background
+ UI_SetColor( color_white );
+ UI_DrawHandlePic( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, uis.menuBackShader );
+ }
+
+ // see what information we should display
+ trap_GetClientState( &cstate );
+
+ info[0] = '\0';
+ if( trap_GetConfigString( CS_SERVERINFO, info, sizeof(info) ) ) {
+ UI_DrawProportionalString( 320, 16, va( "Loading %s", Info_ValueForKey( info, "mapname" ) ), UI_BIGFONT|UI_CENTER|UI_DROPSHADOW, color_white );
+ }
+
+ UI_DrawProportionalString( 320, 64, va("Connecting to %s", cstate.servername), UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, menu_text_color );
+ //UI_DrawProportionalString( 320, 96, "Press Esc to abort", UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, menu_text_color );
+
+ // display global MOTD at bottom
+ UI_DrawProportionalString( SCREEN_WIDTH/2, SCREEN_HEIGHT-32,
+ Info_ValueForKey( cstate.updateInfoString, "motd" ), UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, menu_text_color );
+
+ // print any server info (server full, bad version, etc)
+ if ( cstate.connState < CA_CONNECTED ) {
+ UI_DrawProportionalString_AutoWrapped( 320, 192, 630, 20, cstate.messageString, UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, menu_text_color );
+ }
+
+#if 0
+ // display password field
+ if ( passwordNeeded ) {
+ s_ingame_menu.x = SCREEN_WIDTH * 0.50 - 128;
+ s_ingame_menu.nitems = 0;
+ s_ingame_menu.wrapAround = qtrue;
+
+ passwordField.generic.type = MTYPE_FIELD;
+ passwordField.generic.name = "Password:";
+ passwordField.generic.callback = 0;
+ passwordField.generic.x = 10;
+ passwordField.generic.y = 180;
+ Field_Clear( &passwordField.field );
+ passwordField.width = 256;
+ passwordField.field.widthInChars = 16;
+ Q_strncpyz( passwordField.field.buffer, Cvar_VariableString("password"),
+ sizeof(passwordField.field.buffer) );
+
+ Menu_AddItem( &s_ingame_menu, ( void * ) &s_customize_player_action );
+
+ MField_Draw( &passwordField );
+ }
+#endif
+
+ if ( lastConnState > cstate.connState ) {
+ lastLoadingText[0] = '\0';
+ }
+ lastConnState = cstate.connState;
+
+ switch ( cstate.connState ) {
+ case CA_CONNECTING:
+ s = va("Awaiting challenge...%i", cstate.connectPacketCount);
+ break;
+ case CA_CHALLENGING:
+ s = va("Awaiting connection...%i", cstate.connectPacketCount);
+ break;
+ case CA_CONNECTED: {
+ char downloadName[MAX_INFO_VALUE];
+
+ trap_Cvar_VariableStringBuffer( "cl_downloadName", downloadName, sizeof(downloadName) );
+ if (*downloadName) {
+ UI_DisplayDownloadInfo( downloadName );
+ return;
+ }
+ }
+ s = "Awaiting gamestate...";
+ break;
+ case CA_LOADING:
+ return;
+ case CA_PRIMED:
+ return;
+ default:
+ return;
+ }
+
+ UI_DrawProportionalString( 320, 128, s, UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, color_white );
+
+ // password required / connection rejected information goes here
+}
+
+
+/*
+===================
+UI_KeyConnect
+===================
+*/
+void UI_KeyConnect( int key ) {
+ if ( key == K_ESCAPE ) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, "disconnect\n" );
+ return;
+ }
+}
diff --git a/code/q3_ui/ui_controls2.c b/code/q3_ui/ui_controls2.c
new file mode 100755
index 0000000..f6dc59f
--- /dev/null
+++ b/code/q3_ui/ui_controls2.c
@@ -0,0 +1,1667 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*
+=======================================================================
+
+CONTROLS MENU
+
+=======================================================================
+*/
+
+
+#include "ui_local.h"
+
+#define ART_BACK0 "menu/art/back_0"
+#define ART_BACK1 "menu/art/back_1"
+#define ART_FRAMEL "menu/art/frame2_l"
+#define ART_FRAMER "menu/art/frame1_r"
+
+
+typedef struct {
+ char *command;
+ char *label;
+ int id;
+ int anim;
+ int defaultbind1;
+ int defaultbind2;
+ int bind1;
+ int bind2;
+} bind_t;
+
+typedef struct
+{
+ char* name;
+ float defaultvalue;
+ float value;
+} configcvar_t;
+
+#define SAVE_NOOP 0
+#define SAVE_YES 1
+#define SAVE_NO 2
+#define SAVE_CANCEL 3
+
+// control sections
+#define C_MOVEMENT 0
+#define C_LOOKING 1
+#define C_WEAPONS 2
+#define C_MISC 3
+#define C_MAX 4
+
+#define ID_MOVEMENT 100
+#define ID_LOOKING 101
+#define ID_WEAPONS 102
+#define ID_MISC 103
+#define ID_DEFAULTS 104
+#define ID_BACK 105
+#define ID_SAVEANDEXIT 106
+#define ID_EXIT 107
+
+// bindable actions
+#define ID_SHOWSCORES 0
+#define ID_USEITEM 1
+#define ID_SPEED 2
+#define ID_FORWARD 3
+#define ID_BACKPEDAL 4
+#define ID_MOVELEFT 5
+#define ID_MOVERIGHT 6
+#define ID_MOVEUP 7
+#define ID_MOVEDOWN 8
+#define ID_LEFT 9
+#define ID_RIGHT 10
+#define ID_STRAFE 11
+#define ID_LOOKUP 12
+#define ID_LOOKDOWN 13
+#define ID_MOUSELOOK 14
+#define ID_CENTERVIEW 15
+#define ID_ZOOMVIEW 16
+#define ID_WEAPON1 17
+#define ID_WEAPON2 18
+#define ID_WEAPON3 19
+#define ID_WEAPON4 20
+#define ID_WEAPON5 21
+#define ID_WEAPON6 22
+#define ID_WEAPON7 23
+#define ID_WEAPON8 24
+#define ID_WEAPON9 25
+#define ID_ATTACK 26
+#define ID_WEAPPREV 27
+#define ID_WEAPNEXT 28
+#define ID_GESTURE 29
+#define ID_CHAT 30
+#define ID_CHAT2 31
+#define ID_CHAT3 32
+#define ID_CHAT4 33
+
+// all others
+#define ID_FREELOOK 34
+#define ID_INVERTMOUSE 35
+#define ID_ALWAYSRUN 36
+#define ID_AUTOSWITCH 37
+#define ID_MOUSESPEED 38
+#define ID_JOYENABLE 39
+#define ID_JOYTHRESHOLD 40
+#define ID_SMOOTHMOUSE 41
+
+#define ANIM_IDLE 0
+#define ANIM_RUN 1
+#define ANIM_WALK 2
+#define ANIM_BACK 3
+#define ANIM_JUMP 4
+#define ANIM_CROUCH 5
+#define ANIM_STEPLEFT 6
+#define ANIM_STEPRIGHT 7
+#define ANIM_TURNLEFT 8
+#define ANIM_TURNRIGHT 9
+#define ANIM_LOOKUP 10
+#define ANIM_LOOKDOWN 11
+#define ANIM_WEAPON1 12
+#define ANIM_WEAPON2 13
+#define ANIM_WEAPON3 14
+#define ANIM_WEAPON4 15
+#define ANIM_WEAPON5 16
+#define ANIM_WEAPON6 17
+#define ANIM_WEAPON7 18
+#define ANIM_WEAPON8 19
+#define ANIM_WEAPON9 20
+#define ANIM_WEAPON10 21
+#define ANIM_ATTACK 22
+#define ANIM_GESTURE 23
+#define ANIM_DIE 24
+#define ANIM_CHAT 25
+
+typedef struct
+{
+ menuframework_s menu;
+
+ menutext_s banner;
+ menubitmap_s framel;
+ menubitmap_s framer;
+ menubitmap_s player;
+
+ menutext_s movement;
+ menutext_s looking;
+ menutext_s weapons;
+ menutext_s misc;
+
+ menuaction_s walkforward;
+ menuaction_s backpedal;
+ menuaction_s stepleft;
+ menuaction_s stepright;
+ menuaction_s moveup;
+ menuaction_s movedown;
+ menuaction_s turnleft;
+ menuaction_s turnright;
+ menuaction_s sidestep;
+ menuaction_s run;
+ menuaction_s machinegun;
+ menuaction_s chainsaw;
+ menuaction_s shotgun;
+ menuaction_s grenadelauncher;
+ menuaction_s rocketlauncher;
+ menuaction_s lightning;
+ menuaction_s railgun;
+ menuaction_s plasma;
+ menuaction_s bfg;
+ menuaction_s attack;
+ menuaction_s prevweapon;
+ menuaction_s nextweapon;
+ menuaction_s lookup;
+ menuaction_s lookdown;
+ menuaction_s mouselook;
+ menuradiobutton_s freelook;
+ menuaction_s centerview;
+ menuaction_s zoomview;
+ menuaction_s gesture;
+ menuradiobutton_s invertmouse;
+ menuslider_s sensitivity;
+ menuradiobutton_s smoothmouse;
+ menuradiobutton_s alwaysrun;
+ menuaction_s showscores;
+ menuradiobutton_s autoswitch;
+ menuaction_s useitem;
+ playerInfo_t playerinfo;
+ qboolean changesmade;
+ menuaction_s chat;
+ menuaction_s chat2;
+ menuaction_s chat3;
+ menuaction_s chat4;
+ menuradiobutton_s joyenable;
+ menuslider_s joythreshold;
+ int section;
+ qboolean waitingforkey;
+ char playerModel[64];
+ vec3_t playerViewangles;
+ vec3_t playerMoveangles;
+ int playerLegs;
+ int playerTorso;
+ int playerWeapon;
+ qboolean playerChat;
+
+ menubitmap_s back;
+ menutext_s name;
+} controls_t;
+
+static controls_t s_controls;
+
+static vec4_t controls_binding_color = {1.00f, 0.43f, 0.00f, 1.00f}; // bk: Win32 C4305
+
+static bind_t g_bindings[] =
+{
+ {"+scores", "show scores", ID_SHOWSCORES, ANIM_IDLE, K_TAB, -1, -1, -1},
+ {"+button2", "use item", ID_USEITEM, ANIM_IDLE, K_ENTER, -1, -1, -1},
+ {"+speed", "run / walk", ID_SPEED, ANIM_RUN, K_SHIFT, -1, -1, -1},
+ {"+forward", "walk forward", ID_FORWARD, ANIM_WALK, K_UPARROW, -1, -1, -1},
+ {"+back", "backpedal", ID_BACKPEDAL, ANIM_BACK, K_DOWNARROW, -1, -1, -1},
+ {"+moveleft", "step left", ID_MOVELEFT, ANIM_STEPLEFT, ',', -1, -1, -1},
+ {"+moveright", "step right", ID_MOVERIGHT, ANIM_STEPRIGHT, '.', -1, -1, -1},
+ {"+moveup", "up / jump", ID_MOVEUP, ANIM_JUMP, K_SPACE, -1, -1, -1},
+ {"+movedown", "down / crouch", ID_MOVEDOWN, ANIM_CROUCH, 'c', -1, -1, -1},
+ {"+left", "turn left", ID_LEFT, ANIM_TURNLEFT, K_LEFTARROW, -1, -1, -1},
+ {"+right", "turn right", ID_RIGHT, ANIM_TURNRIGHT, K_RIGHTARROW, -1, -1, -1},
+ {"+strafe", "sidestep / turn", ID_STRAFE, ANIM_IDLE, K_ALT, -1, -1, -1},
+ {"+lookup", "look up", ID_LOOKUP, ANIM_LOOKUP, K_PGDN, -1, -1, -1},
+ {"+lookdown", "look down", ID_LOOKDOWN, ANIM_LOOKDOWN, K_DEL, -1, -1, -1},
+ {"+mlook", "mouse look", ID_MOUSELOOK, ANIM_IDLE, '/', -1, -1, -1},
+ {"centerview", "center view", ID_CENTERVIEW, ANIM_IDLE, K_END, -1, -1, -1},
+ {"+zoom", "zoom view", ID_ZOOMVIEW, ANIM_IDLE, -1, -1, -1, -1},
+ {"weapon 1", "gauntlet", ID_WEAPON1, ANIM_WEAPON1, '1', -1, -1, -1},
+ {"weapon 2", "machinegun", ID_WEAPON2, ANIM_WEAPON2, '2', -1, -1, -1},
+ {"weapon 3", "shotgun", ID_WEAPON3, ANIM_WEAPON3, '3', -1, -1, -1},
+ {"weapon 4", "grenade launcher", ID_WEAPON4, ANIM_WEAPON4, '4', -1, -1, -1},
+ {"weapon 5", "rocket launcher", ID_WEAPON5, ANIM_WEAPON5, '5', -1, -1, -1},
+ {"weapon 6", "lightning", ID_WEAPON6, ANIM_WEAPON6, '6', -1, -1, -1},
+ {"weapon 7", "railgun", ID_WEAPON7, ANIM_WEAPON7, '7', -1, -1, -1},
+ {"weapon 8", "plasma gun", ID_WEAPON8, ANIM_WEAPON8, '8', -1, -1, -1},
+ {"weapon 9", "BFG", ID_WEAPON9, ANIM_WEAPON9, '9', -1, -1, -1},
+ {"+attack", "attack", ID_ATTACK, ANIM_ATTACK, K_CTRL, -1, -1, -1},
+ {"weapprev", "prev weapon", ID_WEAPPREV, ANIM_IDLE, '[', -1, -1, -1},
+ {"weapnext", "next weapon", ID_WEAPNEXT, ANIM_IDLE, ']', -1, -1, -1},
+ {"+button3", "gesture", ID_GESTURE, ANIM_GESTURE, K_MOUSE3, -1, -1, -1},
+ {"messagemode", "chat", ID_CHAT, ANIM_CHAT, 't', -1, -1, -1},
+ {"messagemode2", "chat - team", ID_CHAT2, ANIM_CHAT, -1, -1, -1, -1},
+ {"messagemode3", "chat - target", ID_CHAT3, ANIM_CHAT, -1, -1, -1, -1},
+ {"messagemode4", "chat - attacker", ID_CHAT4, ANIM_CHAT, -1, -1, -1, -1},
+ {(char*)NULL, (char*)NULL, 0, 0, -1, -1, -1, -1},
+};
+
+static configcvar_t g_configcvars[] =
+{
+ {"cl_run", 0, 0},
+ {"m_pitch", 0, 0},
+ {"cg_autoswitch", 0, 0},
+ {"sensitivity", 0, 0},
+ {"in_joystick", 0, 0},
+ {"joy_threshold", 0, 0},
+ {"m_filter", 0, 0},
+ {"cl_freelook", 0, 0},
+ {NULL, 0, 0}
+};
+
+static menucommon_s *g_movement_controls[] =
+{
+ (menucommon_s *)&s_controls.alwaysrun,
+ (menucommon_s *)&s_controls.run,
+ (menucommon_s *)&s_controls.walkforward,
+ (menucommon_s *)&s_controls.backpedal,
+ (menucommon_s *)&s_controls.stepleft,
+ (menucommon_s *)&s_controls.stepright,
+ (menucommon_s *)&s_controls.moveup,
+ (menucommon_s *)&s_controls.movedown,
+ (menucommon_s *)&s_controls.turnleft,
+ (menucommon_s *)&s_controls.turnright,
+ (menucommon_s *)&s_controls.sidestep,
+ NULL
+};
+
+static menucommon_s *g_weapons_controls[] = {
+ (menucommon_s *)&s_controls.attack,
+ (menucommon_s *)&s_controls.nextweapon,
+ (menucommon_s *)&s_controls.prevweapon,
+ (menucommon_s *)&s_controls.autoswitch,
+ (menucommon_s *)&s_controls.chainsaw,
+ (menucommon_s *)&s_controls.machinegun,
+ (menucommon_s *)&s_controls.shotgun,
+ (menucommon_s *)&s_controls.grenadelauncher,
+ (menucommon_s *)&s_controls.rocketlauncher,
+ (menucommon_s *)&s_controls.lightning,
+ (menucommon_s *)&s_controls.railgun,
+ (menucommon_s *)&s_controls.plasma,
+ (menucommon_s *)&s_controls.bfg,
+ NULL,
+};
+
+static menucommon_s *g_looking_controls[] = {
+ (menucommon_s *)&s_controls.sensitivity,
+ (menucommon_s *)&s_controls.smoothmouse,
+ (menucommon_s *)&s_controls.invertmouse,
+ (menucommon_s *)&s_controls.lookup,
+ (menucommon_s *)&s_controls.lookdown,
+ (menucommon_s *)&s_controls.mouselook,
+ (menucommon_s *)&s_controls.freelook,
+ (menucommon_s *)&s_controls.centerview,
+ (menucommon_s *)&s_controls.zoomview,
+ (menucommon_s *)&s_controls.joyenable,
+ (menucommon_s *)&s_controls.joythreshold,
+ NULL,
+};
+
+static menucommon_s *g_misc_controls[] = {
+ (menucommon_s *)&s_controls.showscores,
+ (menucommon_s *)&s_controls.useitem,
+ (menucommon_s *)&s_controls.gesture,
+ (menucommon_s *)&s_controls.chat,
+ (menucommon_s *)&s_controls.chat2,
+ (menucommon_s *)&s_controls.chat3,
+ (menucommon_s *)&s_controls.chat4,
+ NULL,
+};
+
+static menucommon_s **g_controls[] = {
+ g_movement_controls,
+ g_looking_controls,
+ g_weapons_controls,
+ g_misc_controls,
+};
+
+/*
+=================
+Controls_InitCvars
+=================
+*/
+static void Controls_InitCvars( void )
+{
+ int i;
+ configcvar_t* cvarptr;
+
+ cvarptr = g_configcvars;
+ for (i=0; ;i++,cvarptr++)
+ {
+ if (!cvarptr->name)
+ break;
+
+ // get current value
+ cvarptr->value = trap_Cvar_VariableValue( cvarptr->name );
+
+ // get default value
+ trap_Cvar_Reset( cvarptr->name );
+ cvarptr->defaultvalue = trap_Cvar_VariableValue( cvarptr->name );
+
+ // restore current value
+ trap_Cvar_SetValue( cvarptr->name, cvarptr->value );
+ }
+}
+
+/*
+=================
+Controls_GetCvarDefault
+=================
+*/
+static float Controls_GetCvarDefault( char* name )
+{
+ configcvar_t* cvarptr;
+ int i;
+
+ cvarptr = g_configcvars;
+ for (i=0; ;i++,cvarptr++)
+ {
+ if (!cvarptr->name)
+ return (0);
+
+ if (!strcmp(cvarptr->name,name))
+ break;
+ }
+
+ return (cvarptr->defaultvalue);
+}
+
+/*
+=================
+Controls_GetCvarValue
+=================
+*/
+static float Controls_GetCvarValue( char* name )
+{
+ configcvar_t* cvarptr;
+ int i;
+
+ cvarptr = g_configcvars;
+ for (i=0; ;i++,cvarptr++)
+ {
+ if (!cvarptr->name)
+ return (0);
+
+ if (!strcmp(cvarptr->name,name))
+ break;
+ }
+
+ return (cvarptr->value);
+}
+
+
+/*
+=================
+Controls_UpdateModel
+=================
+*/
+static void Controls_UpdateModel( int anim ) {
+ VectorClear( s_controls.playerViewangles );
+ VectorClear( s_controls.playerMoveangles );
+ s_controls.playerViewangles[YAW] = 180 - 30;
+ s_controls.playerMoveangles[YAW] = s_controls.playerViewangles[YAW];
+ s_controls.playerLegs = LEGS_IDLE;
+ s_controls.playerTorso = TORSO_STAND;
+ s_controls.playerWeapon = -1;
+ s_controls.playerChat = qfalse;
+
+ switch( anim ) {
+ case ANIM_RUN:
+ s_controls.playerLegs = LEGS_RUN;
+ break;
+
+ case ANIM_WALK:
+ s_controls.playerLegs = LEGS_WALK;
+ break;
+
+ case ANIM_BACK:
+ s_controls.playerLegs = LEGS_BACK;
+ break;
+
+ case ANIM_JUMP:
+ s_controls.playerLegs = LEGS_JUMP;
+ break;
+
+ case ANIM_CROUCH:
+ s_controls.playerLegs = LEGS_IDLECR;
+ break;
+
+ case ANIM_TURNLEFT:
+ s_controls.playerViewangles[YAW] += 90;
+ break;
+
+ case ANIM_TURNRIGHT:
+ s_controls.playerViewangles[YAW] -= 90;
+ break;
+
+ case ANIM_STEPLEFT:
+ s_controls.playerLegs = LEGS_WALK;
+ s_controls.playerMoveangles[YAW] = s_controls.playerViewangles[YAW] + 90;
+ break;
+
+ case ANIM_STEPRIGHT:
+ s_controls.playerLegs = LEGS_WALK;
+ s_controls.playerMoveangles[YAW] = s_controls.playerViewangles[YAW] - 90;
+ break;
+
+ case ANIM_LOOKUP:
+ s_controls.playerViewangles[PITCH] = -45;
+ break;
+
+ case ANIM_LOOKDOWN:
+ s_controls.playerViewangles[PITCH] = 45;
+ break;
+
+ case ANIM_WEAPON1:
+ s_controls.playerWeapon = WP_GAUNTLET;
+ break;
+
+ case ANIM_WEAPON2:
+ s_controls.playerWeapon = WP_MACHINEGUN;
+ break;
+
+ case ANIM_WEAPON3:
+ s_controls.playerWeapon = WP_SHOTGUN;
+ break;
+
+ case ANIM_WEAPON4:
+ s_controls.playerWeapon = WP_GRENADE_LAUNCHER;
+ break;
+
+ case ANIM_WEAPON5:
+ s_controls.playerWeapon = WP_ROCKET_LAUNCHER;
+ break;
+
+ case ANIM_WEAPON6:
+ s_controls.playerWeapon = WP_LIGHTNING;
+ break;
+
+ case ANIM_WEAPON7:
+ s_controls.playerWeapon = WP_RAILGUN;
+ break;
+
+ case ANIM_WEAPON8:
+ s_controls.playerWeapon = WP_PLASMAGUN;
+ break;
+
+ case ANIM_WEAPON9:
+ s_controls.playerWeapon = WP_BFG;
+ break;
+
+ case ANIM_WEAPON10:
+ s_controls.playerWeapon = WP_GRAPPLING_HOOK;
+ break;
+
+ case ANIM_ATTACK:
+ s_controls.playerTorso = TORSO_ATTACK;
+ break;
+
+ case ANIM_GESTURE:
+ s_controls.playerTorso = TORSO_GESTURE;
+ break;
+
+ case ANIM_DIE:
+ s_controls.playerLegs = BOTH_DEATH1;
+ s_controls.playerTorso = BOTH_DEATH1;
+ s_controls.playerWeapon = WP_NONE;
+ break;
+
+ case ANIM_CHAT:
+ s_controls.playerChat = qtrue;
+ break;
+
+ default:
+ break;
+ }
+
+ UI_PlayerInfo_SetInfo( &s_controls.playerinfo, s_controls.playerLegs, s_controls.playerTorso, s_controls.playerViewangles, s_controls.playerMoveangles, s_controls.playerWeapon, s_controls.playerChat );
+}
+
+
+/*
+=================
+Controls_Update
+=================
+*/
+static void Controls_Update( void ) {
+ int i;
+ int j;
+ int y;
+ menucommon_s **controls;
+ menucommon_s *control;
+
+ // disable all controls in all groups
+ for( i = 0; i < C_MAX; i++ ) {
+ controls = g_controls[i];
+ // bk001204 - parentheses
+ for( j = 0; (control = controls[j]) ; j++ ) {
+ control->flags |= (QMF_HIDDEN|QMF_INACTIVE);
+ }
+ }
+
+ controls = g_controls[s_controls.section];
+
+ // enable controls in active group (and count number of items for vertical centering)
+ // bk001204 - parentheses
+ for( j = 0; (control = controls[j]) ; j++ ) {
+ control->flags &= ~(QMF_GRAYED|QMF_HIDDEN|QMF_INACTIVE);
+ }
+
+ // position controls
+ y = ( SCREEN_HEIGHT - j * SMALLCHAR_HEIGHT ) / 2;
+ // bk001204 - parentheses
+ for( j = 0; (control = controls[j]) ; j++, y += SMALLCHAR_HEIGHT ) {
+ control->x = 320;
+ control->y = y;
+ control->left = 320 - 19*SMALLCHAR_WIDTH;
+ control->right = 320 + 21*SMALLCHAR_WIDTH;
+ control->top = y;
+ control->bottom = y + SMALLCHAR_HEIGHT;
+ }
+
+ if( s_controls.waitingforkey ) {
+ // disable everybody
+ for( i = 0; i < s_controls.menu.nitems; i++ ) {
+ ((menucommon_s*)(s_controls.menu.items[i]))->flags |= QMF_GRAYED;
+ }
+
+ // enable action item
+ ((menucommon_s*)(s_controls.menu.items[s_controls.menu.cursor]))->flags &= ~QMF_GRAYED;
+
+ // don't gray out player's name
+ s_controls.name.generic.flags &= ~QMF_GRAYED;
+
+ return;
+ }
+
+ // enable everybody
+ for( i = 0; i < s_controls.menu.nitems; i++ ) {
+ ((menucommon_s*)(s_controls.menu.items[i]))->flags &= ~QMF_GRAYED;
+ }
+
+ // makes sure flags are right on the group selection controls
+ s_controls.looking.generic.flags &= ~(QMF_GRAYED|QMF_HIGHLIGHT|QMF_HIGHLIGHT_IF_FOCUS);
+ s_controls.movement.generic.flags &= ~(QMF_GRAYED|QMF_HIGHLIGHT|QMF_HIGHLIGHT_IF_FOCUS);
+ s_controls.weapons.generic.flags &= ~(QMF_GRAYED|QMF_HIGHLIGHT|QMF_HIGHLIGHT_IF_FOCUS);
+ s_controls.misc.generic.flags &= ~(QMF_GRAYED|QMF_HIGHLIGHT|QMF_HIGHLIGHT_IF_FOCUS);
+
+ s_controls.looking.generic.flags |= QMF_PULSEIFFOCUS;
+ s_controls.movement.generic.flags |= QMF_PULSEIFFOCUS;
+ s_controls.weapons.generic.flags |= QMF_PULSEIFFOCUS;
+ s_controls.misc.generic.flags |= QMF_PULSEIFFOCUS;
+
+ // set buttons
+ switch( s_controls.section ) {
+ case C_MOVEMENT:
+ s_controls.movement.generic.flags &= ~QMF_PULSEIFFOCUS;
+ s_controls.movement.generic.flags |= (QMF_HIGHLIGHT|QMF_HIGHLIGHT_IF_FOCUS);
+ break;
+
+ case C_LOOKING:
+ s_controls.looking.generic.flags &= ~QMF_PULSEIFFOCUS;
+ s_controls.looking.generic.flags |= (QMF_HIGHLIGHT|QMF_HIGHLIGHT_IF_FOCUS);
+ break;
+
+ case C_WEAPONS:
+ s_controls.weapons.generic.flags &= ~QMF_PULSEIFFOCUS;
+ s_controls.weapons.generic.flags |= (QMF_HIGHLIGHT|QMF_HIGHLIGHT_IF_FOCUS);
+ break;
+
+ case C_MISC:
+ s_controls.misc.generic.flags &= ~QMF_PULSEIFFOCUS;
+ s_controls.misc.generic.flags |= (QMF_HIGHLIGHT|QMF_HIGHLIGHT_IF_FOCUS);
+ break;
+ }
+}
+
+
+/*
+=================
+Controls_DrawKeyBinding
+=================
+*/
+static void Controls_DrawKeyBinding( void *self )
+{
+ menuaction_s* a;
+ int x;
+ int y;
+ int b1;
+ int b2;
+ qboolean c;
+ char name[32];
+ char name2[32];
+
+ a = (menuaction_s*) self;
+
+ x = a->generic.x;
+ y = a->generic.y;
+
+ c = (Menu_ItemAtCursor( a->generic.parent ) == a);
+
+ b1 = g_bindings[a->generic.id].bind1;
+ if (b1 == -1)
+ strcpy(name,"???");
+ else
+ {
+ trap_Key_KeynumToStringBuf( b1, name, 32 );
+ Q_strupr(name);
+
+ b2 = g_bindings[a->generic.id].bind2;
+ if (b2 != -1)
+ {
+ trap_Key_KeynumToStringBuf( b2, name2, 32 );
+ Q_strupr(name2);
+
+ strcat( name, " or " );
+ strcat( name, name2 );
+ }
+ }
+
+ if (c)
+ {
+ UI_FillRect( a->generic.left, a->generic.top, a->generic.right-a->generic.left+1, a->generic.bottom-a->generic.top+1, listbar_color );
+
+ UI_DrawString( x - SMALLCHAR_WIDTH, y, g_bindings[a->generic.id].label, UI_RIGHT|UI_SMALLFONT, text_color_highlight );
+ UI_DrawString( x + SMALLCHAR_WIDTH, y, name, UI_LEFT|UI_SMALLFONT|UI_PULSE, text_color_highlight );
+
+ if (s_controls.waitingforkey)
+ {
+ UI_DrawChar( x, y, '=', UI_CENTER|UI_BLINK|UI_SMALLFONT, text_color_highlight);
+ UI_DrawString(SCREEN_WIDTH * 0.50, SCREEN_HEIGHT * 0.80, "Waiting for new key ... ESCAPE to cancel", UI_SMALLFONT|UI_CENTER|UI_PULSE, colorWhite );
+ }
+ else
+ {
+ UI_DrawChar( x, y, 13, UI_CENTER|UI_BLINK|UI_SMALLFONT, text_color_highlight);
+ UI_DrawString(SCREEN_WIDTH * 0.50, SCREEN_HEIGHT * 0.78, "Press ENTER or CLICK to change", UI_SMALLFONT|UI_CENTER, colorWhite );
+ UI_DrawString(SCREEN_WIDTH * 0.50, SCREEN_HEIGHT * 0.82, "Press BACKSPACE to clear", UI_SMALLFONT|UI_CENTER, colorWhite );
+ }
+ }
+ else
+ {
+ if (a->generic.flags & QMF_GRAYED)
+ {
+ UI_DrawString( x - SMALLCHAR_WIDTH, y, g_bindings[a->generic.id].label, UI_RIGHT|UI_SMALLFONT, text_color_disabled );
+ UI_DrawString( x + SMALLCHAR_WIDTH, y, name, UI_LEFT|UI_SMALLFONT, text_color_disabled );
+ }
+ else
+ {
+ UI_DrawString( x - SMALLCHAR_WIDTH, y, g_bindings[a->generic.id].label, UI_RIGHT|UI_SMALLFONT, controls_binding_color );
+ UI_DrawString( x + SMALLCHAR_WIDTH, y, name, UI_LEFT|UI_SMALLFONT, controls_binding_color );
+ }
+ }
+}
+
+/*
+=================
+Controls_StatusBar
+=================
+*/
+static void Controls_StatusBar( void *self )
+{
+ UI_DrawString(SCREEN_WIDTH * 0.50, SCREEN_HEIGHT * 0.80, "Use Arrow Keys or CLICK to change", UI_SMALLFONT|UI_CENTER, colorWhite );
+}
+
+
+/*
+=================
+Controls_DrawPlayer
+=================
+*/
+static void Controls_DrawPlayer( void *self ) {
+ menubitmap_s *b;
+ char buf[MAX_QPATH];
+
+ trap_Cvar_VariableStringBuffer( "model", buf, sizeof( buf ) );
+ if ( strcmp( buf, s_controls.playerModel ) != 0 ) {
+ UI_PlayerInfo_SetModel( &s_controls.playerinfo, buf );
+ strcpy( s_controls.playerModel, buf );
+ Controls_UpdateModel( ANIM_IDLE );
+ }
+
+ b = (menubitmap_s*) self;
+ UI_DrawPlayer( b->generic.x, b->generic.y, b->width, b->height, &s_controls.playerinfo, uis.realtime/2 );
+}
+
+
+/*
+=================
+Controls_GetKeyAssignment
+=================
+*/
+static void Controls_GetKeyAssignment (char *command, int *twokeys)
+{
+ int count;
+ int j;
+ char b[256];
+
+ twokeys[0] = twokeys[1] = -1;
+ count = 0;
+
+ for ( j = 0; j < 256; j++ )
+ {
+ trap_Key_GetBindingBuf( j, b, 256 );
+ if ( *b == 0 ) {
+ continue;
+ }
+ if ( !Q_stricmp( b, command ) ) {
+ twokeys[count] = j;
+ count++;
+ if (count == 2)
+ break;
+ }
+ }
+}
+
+/*
+=================
+Controls_GetConfig
+=================
+*/
+static void Controls_GetConfig( void )
+{
+ int i;
+ int twokeys[2];
+ bind_t* bindptr;
+
+ // put the bindings into a local store
+ bindptr = g_bindings;
+
+ // iterate each command, get its numeric binding
+ for (i=0; ;i++,bindptr++)
+ {
+ if (!bindptr->label)
+ break;
+
+ Controls_GetKeyAssignment(bindptr->command, twokeys);
+
+ bindptr->bind1 = twokeys[0];
+ bindptr->bind2 = twokeys[1];
+ }
+
+ s_controls.invertmouse.curvalue = Controls_GetCvarValue( "m_pitch" ) < 0;
+ s_controls.smoothmouse.curvalue = UI_ClampCvar( 0, 1, Controls_GetCvarValue( "m_filter" ) );
+ s_controls.alwaysrun.curvalue = UI_ClampCvar( 0, 1, Controls_GetCvarValue( "cl_run" ) );
+ s_controls.autoswitch.curvalue = UI_ClampCvar( 0, 1, Controls_GetCvarValue( "cg_autoswitch" ) );
+ s_controls.sensitivity.curvalue = UI_ClampCvar( 2, 30, Controls_GetCvarValue( "sensitivity" ) );
+ s_controls.joyenable.curvalue = UI_ClampCvar( 0, 1, Controls_GetCvarValue( "in_joystick" ) );
+ s_controls.joythreshold.curvalue = UI_ClampCvar( 0.05f, 0.75f, Controls_GetCvarValue( "joy_threshold" ) );
+ s_controls.freelook.curvalue = UI_ClampCvar( 0, 1, Controls_GetCvarValue( "cl_freelook" ) );
+}
+
+/*
+=================
+Controls_SetConfig
+=================
+*/
+static void Controls_SetConfig( void )
+{
+ int i;
+ bind_t* bindptr;
+
+ // set the bindings from the local store
+ bindptr = g_bindings;
+
+ // iterate each command, get its numeric binding
+ for (i=0; ;i++,bindptr++)
+ {
+ if (!bindptr->label)
+ break;
+
+ if (bindptr->bind1 != -1)
+ {
+ trap_Key_SetBinding( bindptr->bind1, bindptr->command );
+
+ if (bindptr->bind2 != -1)
+ trap_Key_SetBinding( bindptr->bind2, bindptr->command );
+ }
+ }
+
+ if ( s_controls.invertmouse.curvalue )
+ trap_Cvar_SetValue( "m_pitch", -fabs( trap_Cvar_VariableValue( "m_pitch" ) ) );
+ else
+ trap_Cvar_SetValue( "m_pitch", fabs( trap_Cvar_VariableValue( "m_pitch" ) ) );
+
+ trap_Cvar_SetValue( "m_filter", s_controls.smoothmouse.curvalue );
+ trap_Cvar_SetValue( "cl_run", s_controls.alwaysrun.curvalue );
+ trap_Cvar_SetValue( "cg_autoswitch", s_controls.autoswitch.curvalue );
+ trap_Cvar_SetValue( "sensitivity", s_controls.sensitivity.curvalue );
+ trap_Cvar_SetValue( "in_joystick", s_controls.joyenable.curvalue );
+ trap_Cvar_SetValue( "joy_threshold", s_controls.joythreshold.curvalue );
+ trap_Cvar_SetValue( "cl_freelook", s_controls.freelook.curvalue );
+ trap_Cmd_ExecuteText( EXEC_APPEND, "in_restart\n" );
+}
+
+/*
+=================
+Controls_SetDefaults
+=================
+*/
+static void Controls_SetDefaults( void )
+{
+ int i;
+ bind_t* bindptr;
+
+ // set the bindings from the local store
+ bindptr = g_bindings;
+
+ // iterate each command, set its default binding
+ for (i=0; ;i++,bindptr++)
+ {
+ if (!bindptr->label)
+ break;
+
+ bindptr->bind1 = bindptr->defaultbind1;
+ bindptr->bind2 = bindptr->defaultbind2;
+ }
+
+ s_controls.invertmouse.curvalue = Controls_GetCvarDefault( "m_pitch" ) < 0;
+ s_controls.smoothmouse.curvalue = Controls_GetCvarDefault( "m_filter" );
+ s_controls.alwaysrun.curvalue = Controls_GetCvarDefault( "cl_run" );
+ s_controls.autoswitch.curvalue = Controls_GetCvarDefault( "cg_autoswitch" );
+ s_controls.sensitivity.curvalue = Controls_GetCvarDefault( "sensitivity" );
+ s_controls.joyenable.curvalue = Controls_GetCvarDefault( "in_joystick" );
+ s_controls.joythreshold.curvalue = Controls_GetCvarDefault( "joy_threshold" );
+ s_controls.freelook.curvalue = Controls_GetCvarDefault( "cl_freelook" );
+}
+
+/*
+=================
+Controls_MenuKey
+=================
+*/
+static sfxHandle_t Controls_MenuKey( int key )
+{
+ int id;
+ int i;
+ qboolean found;
+ bind_t* bindptr;
+ found = qfalse;
+
+ if (!s_controls.waitingforkey)
+ {
+ switch (key)
+ {
+ case K_BACKSPACE:
+ case K_DEL:
+ case K_KP_DEL:
+ key = -1;
+ break;
+
+ case K_MOUSE2:
+ case K_ESCAPE:
+ if (s_controls.changesmade)
+ Controls_SetConfig();
+ goto ignorekey;
+
+ default:
+ goto ignorekey;
+ }
+ }
+ else
+ {
+ if (key & K_CHAR_FLAG)
+ goto ignorekey;
+
+ switch (key)
+ {
+ case K_ESCAPE:
+ s_controls.waitingforkey = qfalse;
+ Controls_Update();
+ return (menu_out_sound);
+
+ case '`':
+ goto ignorekey;
+ }
+ }
+
+ s_controls.changesmade = qtrue;
+
+ if (key != -1)
+ {
+ // remove from any other bind
+ bindptr = g_bindings;
+ for (i=0; ;i++,bindptr++)
+ {
+ if (!bindptr->label)
+ break;
+
+ if (bindptr->bind2 == key)
+ bindptr->bind2 = -1;
+
+ if (bindptr->bind1 == key)
+ {
+ bindptr->bind1 = bindptr->bind2;
+ bindptr->bind2 = -1;
+ }
+ }
+ }
+
+ // assign key to local store
+ id = ((menucommon_s*)(s_controls.menu.items[s_controls.menu.cursor]))->id;
+ bindptr = g_bindings;
+ for (i=0; ;i++,bindptr++)
+ {
+ if (!bindptr->label)
+ break;
+
+ if (bindptr->id == id)
+ {
+ found = qtrue;
+ if (key == -1)
+ {
+ if( bindptr->bind1 != -1 ) {
+ trap_Key_SetBinding( bindptr->bind1, "" );
+ bindptr->bind1 = -1;
+ }
+ if( bindptr->bind2 != -1 ) {
+ trap_Key_SetBinding( bindptr->bind2, "" );
+ bindptr->bind2 = -1;
+ }
+ }
+ else if (bindptr->bind1 == -1) {
+ bindptr->bind1 = key;
+ }
+ else if (bindptr->bind1 != key && bindptr->bind2 == -1) {
+ bindptr->bind2 = key;
+ }
+ else
+ {
+ trap_Key_SetBinding( bindptr->bind1, "" );
+ trap_Key_SetBinding( bindptr->bind2, "" );
+ bindptr->bind1 = key;
+ bindptr->bind2 = -1;
+ }
+ break;
+ }
+ }
+
+ s_controls.waitingforkey = qfalse;
+
+ if (found)
+ {
+ Controls_Update();
+ return (menu_out_sound);
+ }
+
+ignorekey:
+ return Menu_DefaultKey( &s_controls.menu, key );
+}
+
+/*
+=================
+Controls_ResetDefaults_Action
+=================
+*/
+static void Controls_ResetDefaults_Action( qboolean result ) {
+ if( !result ) {
+ return;
+ }
+
+ s_controls.changesmade = qtrue;
+ Controls_SetDefaults();
+ Controls_Update();
+}
+
+/*
+=================
+Controls_ResetDefaults_Draw
+=================
+*/
+static void Controls_ResetDefaults_Draw( void ) {
+ UI_DrawProportionalString( SCREEN_WIDTH/2, 356 + PROP_HEIGHT * 0, "WARNING: This will reset all", UI_CENTER|UI_SMALLFONT, color_yellow );
+ UI_DrawProportionalString( SCREEN_WIDTH/2, 356 + PROP_HEIGHT * 1, "controls to their default values.", UI_CENTER|UI_SMALLFONT, color_yellow );
+}
+
+/*
+=================
+Controls_MenuEvent
+=================
+*/
+static void Controls_MenuEvent( void* ptr, int event )
+{
+ switch (((menucommon_s*)ptr)->id)
+ {
+ case ID_MOVEMENT:
+ if (event == QM_ACTIVATED)
+ {
+ s_controls.section = C_MOVEMENT;
+ Controls_Update();
+ }
+ break;
+
+ case ID_LOOKING:
+ if (event == QM_ACTIVATED)
+ {
+ s_controls.section = C_LOOKING;
+ Controls_Update();
+ }
+ break;
+
+ case ID_WEAPONS:
+ if (event == QM_ACTIVATED)
+ {
+ s_controls.section = C_WEAPONS;
+ Controls_Update();
+ }
+ break;
+
+ case ID_MISC:
+ if (event == QM_ACTIVATED)
+ {
+ s_controls.section = C_MISC;
+ Controls_Update();
+ }
+ break;
+
+ case ID_DEFAULTS:
+ if (event == QM_ACTIVATED)
+ {
+ UI_ConfirmMenu( "SET TO DEFAULTS?", Controls_ResetDefaults_Draw, Controls_ResetDefaults_Action );
+ }
+ break;
+
+ case ID_BACK:
+ if (event == QM_ACTIVATED)
+ {
+ if (s_controls.changesmade)
+ Controls_SetConfig();
+ UI_PopMenu();
+ }
+ break;
+
+ case ID_SAVEANDEXIT:
+ if (event == QM_ACTIVATED)
+ {
+ Controls_SetConfig();
+ UI_PopMenu();
+ }
+ break;
+
+ case ID_EXIT:
+ if (event == QM_ACTIVATED)
+ {
+ UI_PopMenu();
+ }
+ break;
+
+ case ID_FREELOOK:
+ case ID_MOUSESPEED:
+ case ID_INVERTMOUSE:
+ case ID_SMOOTHMOUSE:
+ case ID_ALWAYSRUN:
+ case ID_AUTOSWITCH:
+ case ID_JOYENABLE:
+ case ID_JOYTHRESHOLD:
+ if (event == QM_ACTIVATED)
+ {
+ s_controls.changesmade = qtrue;
+ }
+ break;
+ }
+}
+
+/*
+=================
+Controls_ActionEvent
+=================
+*/
+static void Controls_ActionEvent( void* ptr, int event )
+{
+ if (event == QM_LOSTFOCUS)
+ {
+ Controls_UpdateModel( ANIM_IDLE );
+ }
+ else if (event == QM_GOTFOCUS)
+ {
+ Controls_UpdateModel( g_bindings[((menucommon_s*)ptr)->id].anim );
+ }
+ else if ((event == QM_ACTIVATED) && !s_controls.waitingforkey)
+ {
+ s_controls.waitingforkey = 1;
+ Controls_Update();
+ }
+}
+
+/*
+=================
+Controls_InitModel
+=================
+*/
+static void Controls_InitModel( void )
+{
+ memset( &s_controls.playerinfo, 0, sizeof(playerInfo_t) );
+
+ UI_PlayerInfo_SetModel( &s_controls.playerinfo, UI_Cvar_VariableString( "model" ) );
+
+ Controls_UpdateModel( ANIM_IDLE );
+}
+
+/*
+=================
+Controls_InitWeapons
+=================
+*/
+static void Controls_InitWeapons( void ) {
+ gitem_t * item;
+
+ for ( item = bg_itemlist + 1 ; item->classname ; item++ ) {
+ if ( item->giType != IT_WEAPON ) {
+ continue;
+ }
+ trap_R_RegisterModel( item->world_model[0] );
+ }
+}
+
+/*
+=================
+Controls_MenuInit
+=================
+*/
+static void Controls_MenuInit( void )
+{
+ static char playername[32];
+
+ // zero set all our globals
+ memset( &s_controls, 0 ,sizeof(controls_t) );
+
+ Controls_Cache();
+
+ s_controls.menu.key = Controls_MenuKey;
+ s_controls.menu.wrapAround = qtrue;
+ s_controls.menu.fullscreen = qtrue;
+
+ s_controls.banner.generic.type = MTYPE_BTEXT;
+ s_controls.banner.generic.flags = QMF_CENTER_JUSTIFY;
+ s_controls.banner.generic.x = 320;
+ s_controls.banner.generic.y = 16;
+ s_controls.banner.string = "CONTROLS";
+ s_controls.banner.color = color_white;
+ s_controls.banner.style = UI_CENTER;
+
+ s_controls.framel.generic.type = MTYPE_BITMAP;
+ s_controls.framel.generic.name = ART_FRAMEL;
+ s_controls.framel.generic.flags = QMF_LEFT_JUSTIFY|QMF_INACTIVE;
+ s_controls.framel.generic.x = 0;
+ s_controls.framel.generic.y = 78;
+ s_controls.framel.width = 256;
+ s_controls.framel.height = 329;
+
+ s_controls.framer.generic.type = MTYPE_BITMAP;
+ s_controls.framer.generic.name = ART_FRAMER;
+ s_controls.framer.generic.flags = QMF_LEFT_JUSTIFY|QMF_INACTIVE;
+ s_controls.framer.generic.x = 376;
+ s_controls.framer.generic.y = 76;
+ s_controls.framer.width = 256;
+ s_controls.framer.height = 334;
+
+ s_controls.looking.generic.type = MTYPE_PTEXT;
+ s_controls.looking.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_controls.looking.generic.id = ID_LOOKING;
+ s_controls.looking.generic.callback = Controls_MenuEvent;
+ s_controls.looking.generic.x = 152;
+ s_controls.looking.generic.y = 240 - 2 * PROP_HEIGHT;
+ s_controls.looking.string = "LOOK";
+ s_controls.looking.style = UI_RIGHT;
+ s_controls.looking.color = color_red;
+
+ s_controls.movement.generic.type = MTYPE_PTEXT;
+ s_controls.movement.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_controls.movement.generic.id = ID_MOVEMENT;
+ s_controls.movement.generic.callback = Controls_MenuEvent;
+ s_controls.movement.generic.x = 152;
+ s_controls.movement.generic.y = 240 - PROP_HEIGHT;
+ s_controls.movement.string = "MOVE";
+ s_controls.movement.style = UI_RIGHT;
+ s_controls.movement.color = color_red;
+
+ s_controls.weapons.generic.type = MTYPE_PTEXT;
+ s_controls.weapons.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_controls.weapons.generic.id = ID_WEAPONS;
+ s_controls.weapons.generic.callback = Controls_MenuEvent;
+ s_controls.weapons.generic.x = 152;
+ s_controls.weapons.generic.y = 240;
+ s_controls.weapons.string = "SHOOT";
+ s_controls.weapons.style = UI_RIGHT;
+ s_controls.weapons.color = color_red;
+
+ s_controls.misc.generic.type = MTYPE_PTEXT;
+ s_controls.misc.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_controls.misc.generic.id = ID_MISC;
+ s_controls.misc.generic.callback = Controls_MenuEvent;
+ s_controls.misc.generic.x = 152;
+ s_controls.misc.generic.y = 240 + PROP_HEIGHT;
+ s_controls.misc.string = "MISC";
+ s_controls.misc.style = UI_RIGHT;
+ s_controls.misc.color = color_red;
+
+ s_controls.back.generic.type = MTYPE_BITMAP;
+ s_controls.back.generic.name = ART_BACK0;
+ s_controls.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_controls.back.generic.x = 0;
+ s_controls.back.generic.y = 480-64;
+ s_controls.back.generic.id = ID_BACK;
+ s_controls.back.generic.callback = Controls_MenuEvent;
+ s_controls.back.width = 128;
+ s_controls.back.height = 64;
+ s_controls.back.focuspic = ART_BACK1;
+
+ s_controls.player.generic.type = MTYPE_BITMAP;
+ s_controls.player.generic.flags = QMF_INACTIVE;
+ s_controls.player.generic.ownerdraw = Controls_DrawPlayer;
+ s_controls.player.generic.x = 400;
+ s_controls.player.generic.y = -40;
+ s_controls.player.width = 32*10;
+ s_controls.player.height = 56*10;
+
+ s_controls.walkforward.generic.type = MTYPE_ACTION;
+ s_controls.walkforward.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.walkforward.generic.callback = Controls_ActionEvent;
+ s_controls.walkforward.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.walkforward.generic.id = ID_FORWARD;
+
+ s_controls.backpedal.generic.type = MTYPE_ACTION;
+ s_controls.backpedal.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.backpedal.generic.callback = Controls_ActionEvent;
+ s_controls.backpedal.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.backpedal.generic.id = ID_BACKPEDAL;
+
+ s_controls.stepleft.generic.type = MTYPE_ACTION;
+ s_controls.stepleft.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.stepleft.generic.callback = Controls_ActionEvent;
+ s_controls.stepleft.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.stepleft.generic.id = ID_MOVELEFT;
+
+ s_controls.stepright.generic.type = MTYPE_ACTION;
+ s_controls.stepright.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.stepright.generic.callback = Controls_ActionEvent;
+ s_controls.stepright.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.stepright.generic.id = ID_MOVERIGHT;
+
+ s_controls.moveup.generic.type = MTYPE_ACTION;
+ s_controls.moveup.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.moveup.generic.callback = Controls_ActionEvent;
+ s_controls.moveup.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.moveup.generic.id = ID_MOVEUP;
+
+ s_controls.movedown.generic.type = MTYPE_ACTION;
+ s_controls.movedown.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.movedown.generic.callback = Controls_ActionEvent;
+ s_controls.movedown.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.movedown.generic.id = ID_MOVEDOWN;
+
+ s_controls.turnleft.generic.type = MTYPE_ACTION;
+ s_controls.turnleft.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.turnleft.generic.callback = Controls_ActionEvent;
+ s_controls.turnleft.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.turnleft.generic.id = ID_LEFT;
+
+ s_controls.turnright.generic.type = MTYPE_ACTION;
+ s_controls.turnright.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.turnright.generic.callback = Controls_ActionEvent;
+ s_controls.turnright.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.turnright.generic.id = ID_RIGHT;
+
+ s_controls.sidestep.generic.type = MTYPE_ACTION;
+ s_controls.sidestep.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.sidestep.generic.callback = Controls_ActionEvent;
+ s_controls.sidestep.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.sidestep.generic.id = ID_STRAFE;
+
+ s_controls.run.generic.type = MTYPE_ACTION;
+ s_controls.run.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.run.generic.callback = Controls_ActionEvent;
+ s_controls.run.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.run.generic.id = ID_SPEED;
+
+ s_controls.chainsaw.generic.type = MTYPE_ACTION;
+ s_controls.chainsaw.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.chainsaw.generic.callback = Controls_ActionEvent;
+ s_controls.chainsaw.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.chainsaw.generic.id = ID_WEAPON1;
+
+ s_controls.machinegun.generic.type = MTYPE_ACTION;
+ s_controls.machinegun.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.machinegun.generic.callback = Controls_ActionEvent;
+ s_controls.machinegun.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.machinegun.generic.id = ID_WEAPON2;
+
+ s_controls.shotgun.generic.type = MTYPE_ACTION;
+ s_controls.shotgun.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.shotgun.generic.callback = Controls_ActionEvent;
+ s_controls.shotgun.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.shotgun.generic.id = ID_WEAPON3;
+
+ s_controls.grenadelauncher.generic.type = MTYPE_ACTION;
+ s_controls.grenadelauncher.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.grenadelauncher.generic.callback = Controls_ActionEvent;
+ s_controls.grenadelauncher.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.grenadelauncher.generic.id = ID_WEAPON4;
+
+ s_controls.rocketlauncher.generic.type = MTYPE_ACTION;
+ s_controls.rocketlauncher.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.rocketlauncher.generic.callback = Controls_ActionEvent;
+ s_controls.rocketlauncher.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.rocketlauncher.generic.id = ID_WEAPON5;
+
+ s_controls.lightning.generic.type = MTYPE_ACTION;
+ s_controls.lightning.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.lightning.generic.callback = Controls_ActionEvent;
+ s_controls.lightning.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.lightning.generic.id = ID_WEAPON6;
+
+ s_controls.railgun.generic.type = MTYPE_ACTION;
+ s_controls.railgun.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.railgun.generic.callback = Controls_ActionEvent;
+ s_controls.railgun.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.railgun.generic.id = ID_WEAPON7;
+
+ s_controls.plasma.generic.type = MTYPE_ACTION;
+ s_controls.plasma.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.plasma.generic.callback = Controls_ActionEvent;
+ s_controls.plasma.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.plasma.generic.id = ID_WEAPON8;
+
+ s_controls.bfg.generic.type = MTYPE_ACTION;
+ s_controls.bfg.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.bfg.generic.callback = Controls_ActionEvent;
+ s_controls.bfg.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.bfg.generic.id = ID_WEAPON9;
+
+ s_controls.attack.generic.type = MTYPE_ACTION;
+ s_controls.attack.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.attack.generic.callback = Controls_ActionEvent;
+ s_controls.attack.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.attack.generic.id = ID_ATTACK;
+
+ s_controls.prevweapon.generic.type = MTYPE_ACTION;
+ s_controls.prevweapon.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.prevweapon.generic.callback = Controls_ActionEvent;
+ s_controls.prevweapon.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.prevweapon.generic.id = ID_WEAPPREV;
+
+ s_controls.nextweapon.generic.type = MTYPE_ACTION;
+ s_controls.nextweapon.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.nextweapon.generic.callback = Controls_ActionEvent;
+ s_controls.nextweapon.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.nextweapon.generic.id = ID_WEAPNEXT;
+
+ s_controls.lookup.generic.type = MTYPE_ACTION;
+ s_controls.lookup.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.lookup.generic.callback = Controls_ActionEvent;
+ s_controls.lookup.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.lookup.generic.id = ID_LOOKUP;
+
+ s_controls.lookdown.generic.type = MTYPE_ACTION;
+ s_controls.lookdown.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.lookdown.generic.callback = Controls_ActionEvent;
+ s_controls.lookdown.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.lookdown.generic.id = ID_LOOKDOWN;
+
+ s_controls.mouselook.generic.type = MTYPE_ACTION;
+ s_controls.mouselook.generic.flags = QMF_LEFT_JUSTIFY|QMF_HIGHLIGHT_IF_FOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.mouselook.generic.callback = Controls_ActionEvent;
+ s_controls.mouselook.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.mouselook.generic.id = ID_MOUSELOOK;
+
+ s_controls.freelook.generic.type = MTYPE_RADIOBUTTON;
+ s_controls.freelook.generic.flags = QMF_SMALLFONT;
+ s_controls.freelook.generic.x = SCREEN_WIDTH/2;
+ s_controls.freelook.generic.name = "free look";
+ s_controls.freelook.generic.id = ID_FREELOOK;
+ s_controls.freelook.generic.callback = Controls_MenuEvent;
+ s_controls.freelook.generic.statusbar = Controls_StatusBar;
+
+ s_controls.centerview.generic.type = MTYPE_ACTION;
+ s_controls.centerview.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.centerview.generic.callback = Controls_ActionEvent;
+ s_controls.centerview.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.centerview.generic.id = ID_CENTERVIEW;
+
+ s_controls.zoomview.generic.type = MTYPE_ACTION;
+ s_controls.zoomview.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.zoomview.generic.callback = Controls_ActionEvent;
+ s_controls.zoomview.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.zoomview.generic.id = ID_ZOOMVIEW;
+
+ s_controls.useitem.generic.type = MTYPE_ACTION;
+ s_controls.useitem.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.useitem.generic.callback = Controls_ActionEvent;
+ s_controls.useitem.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.useitem.generic.id = ID_USEITEM;
+
+ s_controls.showscores.generic.type = MTYPE_ACTION;
+ s_controls.showscores.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.showscores.generic.callback = Controls_ActionEvent;
+ s_controls.showscores.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.showscores.generic.id = ID_SHOWSCORES;
+
+ s_controls.invertmouse.generic.type = MTYPE_RADIOBUTTON;
+ s_controls.invertmouse.generic.flags = QMF_SMALLFONT;
+ s_controls.invertmouse.generic.x = SCREEN_WIDTH/2;
+ s_controls.invertmouse.generic.name = "invert mouse";
+ s_controls.invertmouse.generic.id = ID_INVERTMOUSE;
+ s_controls.invertmouse.generic.callback = Controls_MenuEvent;
+ s_controls.invertmouse.generic.statusbar = Controls_StatusBar;
+
+ s_controls.smoothmouse.generic.type = MTYPE_RADIOBUTTON;
+ s_controls.smoothmouse.generic.flags = QMF_SMALLFONT;
+ s_controls.smoothmouse.generic.x = SCREEN_WIDTH/2;
+ s_controls.smoothmouse.generic.name = "smooth mouse";
+ s_controls.smoothmouse.generic.id = ID_SMOOTHMOUSE;
+ s_controls.smoothmouse.generic.callback = Controls_MenuEvent;
+ s_controls.smoothmouse.generic.statusbar = Controls_StatusBar;
+
+ s_controls.alwaysrun.generic.type = MTYPE_RADIOBUTTON;
+ s_controls.alwaysrun.generic.flags = QMF_SMALLFONT;
+ s_controls.alwaysrun.generic.x = SCREEN_WIDTH/2;
+ s_controls.alwaysrun.generic.name = "always run";
+ s_controls.alwaysrun.generic.id = ID_ALWAYSRUN;
+ s_controls.alwaysrun.generic.callback = Controls_MenuEvent;
+ s_controls.alwaysrun.generic.statusbar = Controls_StatusBar;
+
+ s_controls.autoswitch.generic.type = MTYPE_RADIOBUTTON;
+ s_controls.autoswitch.generic.flags = QMF_SMALLFONT;
+ s_controls.autoswitch.generic.x = SCREEN_WIDTH/2;
+ s_controls.autoswitch.generic.name = "autoswitch weapons";
+ s_controls.autoswitch.generic.id = ID_AUTOSWITCH;
+ s_controls.autoswitch.generic.callback = Controls_MenuEvent;
+ s_controls.autoswitch.generic.statusbar = Controls_StatusBar;
+
+ s_controls.sensitivity.generic.type = MTYPE_SLIDER;
+ s_controls.sensitivity.generic.x = SCREEN_WIDTH/2;
+ s_controls.sensitivity.generic.flags = QMF_SMALLFONT;
+ s_controls.sensitivity.generic.name = "mouse speed";
+ s_controls.sensitivity.generic.id = ID_MOUSESPEED;
+ s_controls.sensitivity.generic.callback = Controls_MenuEvent;
+ s_controls.sensitivity.minvalue = 2;
+ s_controls.sensitivity.maxvalue = 30;
+ s_controls.sensitivity.generic.statusbar = Controls_StatusBar;
+
+ s_controls.gesture.generic.type = MTYPE_ACTION;
+ s_controls.gesture.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.gesture.generic.callback = Controls_ActionEvent;
+ s_controls.gesture.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.gesture.generic.id = ID_GESTURE;
+
+ s_controls.chat.generic.type = MTYPE_ACTION;
+ s_controls.chat.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.chat.generic.callback = Controls_ActionEvent;
+ s_controls.chat.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.chat.generic.id = ID_CHAT;
+
+ s_controls.chat2.generic.type = MTYPE_ACTION;
+ s_controls.chat2.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.chat2.generic.callback = Controls_ActionEvent;
+ s_controls.chat2.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.chat2.generic.id = ID_CHAT2;
+
+ s_controls.chat3.generic.type = MTYPE_ACTION;
+ s_controls.chat3.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.chat3.generic.callback = Controls_ActionEvent;
+ s_controls.chat3.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.chat3.generic.id = ID_CHAT3;
+
+ s_controls.chat4.generic.type = MTYPE_ACTION;
+ s_controls.chat4.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_GRAYED|QMF_HIDDEN;
+ s_controls.chat4.generic.callback = Controls_ActionEvent;
+ s_controls.chat4.generic.ownerdraw = Controls_DrawKeyBinding;
+ s_controls.chat4.generic.id = ID_CHAT4;
+
+ s_controls.joyenable.generic.type = MTYPE_RADIOBUTTON;
+ s_controls.joyenable.generic.flags = QMF_SMALLFONT;
+ s_controls.joyenable.generic.x = SCREEN_WIDTH/2;
+ s_controls.joyenable.generic.name = "joystick";
+ s_controls.joyenable.generic.id = ID_JOYENABLE;
+ s_controls.joyenable.generic.callback = Controls_MenuEvent;
+ s_controls.joyenable.generic.statusbar = Controls_StatusBar;
+
+ s_controls.joythreshold.generic.type = MTYPE_SLIDER;
+ s_controls.joythreshold.generic.x = SCREEN_WIDTH/2;
+ s_controls.joythreshold.generic.flags = QMF_SMALLFONT;
+ s_controls.joythreshold.generic.name = "joystick threshold";
+ s_controls.joythreshold.generic.id = ID_JOYTHRESHOLD;
+ s_controls.joythreshold.generic.callback = Controls_MenuEvent;
+ s_controls.joythreshold.minvalue = 0.05f;
+ s_controls.joythreshold.maxvalue = 0.75f;
+ s_controls.joythreshold.generic.statusbar = Controls_StatusBar;
+
+ s_controls.name.generic.type = MTYPE_PTEXT;
+ s_controls.name.generic.flags = QMF_CENTER_JUSTIFY|QMF_INACTIVE;
+ s_controls.name.generic.x = 320;
+ s_controls.name.generic.y = 440;
+ s_controls.name.string = playername;
+ s_controls.name.style = UI_CENTER;
+ s_controls.name.color = text_color_normal;
+
+ Menu_AddItem( &s_controls.menu, &s_controls.banner );
+ Menu_AddItem( &s_controls.menu, &s_controls.framel );
+ Menu_AddItem( &s_controls.menu, &s_controls.framer );
+ Menu_AddItem( &s_controls.menu, &s_controls.player );
+ Menu_AddItem( &s_controls.menu, &s_controls.name );
+
+ Menu_AddItem( &s_controls.menu, &s_controls.looking );
+ Menu_AddItem( &s_controls.menu, &s_controls.movement );
+ Menu_AddItem( &s_controls.menu, &s_controls.weapons );
+ Menu_AddItem( &s_controls.menu, &s_controls.misc );
+
+ Menu_AddItem( &s_controls.menu, &s_controls.sensitivity );
+ Menu_AddItem( &s_controls.menu, &s_controls.smoothmouse );
+ Menu_AddItem( &s_controls.menu, &s_controls.invertmouse );
+ Menu_AddItem( &s_controls.menu, &s_controls.lookup );
+ Menu_AddItem( &s_controls.menu, &s_controls.lookdown );
+ Menu_AddItem( &s_controls.menu, &s_controls.mouselook );
+ Menu_AddItem( &s_controls.menu, &s_controls.freelook );
+ Menu_AddItem( &s_controls.menu, &s_controls.centerview );
+ Menu_AddItem( &s_controls.menu, &s_controls.zoomview );
+ Menu_AddItem( &s_controls.menu, &s_controls.joyenable );
+ Menu_AddItem( &s_controls.menu, &s_controls.joythreshold );
+
+ Menu_AddItem( &s_controls.menu, &s_controls.alwaysrun );
+ Menu_AddItem( &s_controls.menu, &s_controls.run );
+ Menu_AddItem( &s_controls.menu, &s_controls.walkforward );
+ Menu_AddItem( &s_controls.menu, &s_controls.backpedal );
+ Menu_AddItem( &s_controls.menu, &s_controls.stepleft );
+ Menu_AddItem( &s_controls.menu, &s_controls.stepright );
+ Menu_AddItem( &s_controls.menu, &s_controls.moveup );
+ Menu_AddItem( &s_controls.menu, &s_controls.movedown );
+ Menu_AddItem( &s_controls.menu, &s_controls.turnleft );
+ Menu_AddItem( &s_controls.menu, &s_controls.turnright );
+ Menu_AddItem( &s_controls.menu, &s_controls.sidestep );
+
+ Menu_AddItem( &s_controls.menu, &s_controls.attack );
+ Menu_AddItem( &s_controls.menu, &s_controls.nextweapon );
+ Menu_AddItem( &s_controls.menu, &s_controls.prevweapon );
+ Menu_AddItem( &s_controls.menu, &s_controls.autoswitch );
+ Menu_AddItem( &s_controls.menu, &s_controls.chainsaw );
+ Menu_AddItem( &s_controls.menu, &s_controls.machinegun );
+ Menu_AddItem( &s_controls.menu, &s_controls.shotgun );
+ Menu_AddItem( &s_controls.menu, &s_controls.grenadelauncher );
+ Menu_AddItem( &s_controls.menu, &s_controls.rocketlauncher );
+ Menu_AddItem( &s_controls.menu, &s_controls.lightning );
+ Menu_AddItem( &s_controls.menu, &s_controls.railgun );
+ Menu_AddItem( &s_controls.menu, &s_controls.plasma );
+ Menu_AddItem( &s_controls.menu, &s_controls.bfg );
+
+ Menu_AddItem( &s_controls.menu, &s_controls.showscores );
+ Menu_AddItem( &s_controls.menu, &s_controls.useitem );
+ Menu_AddItem( &s_controls.menu, &s_controls.gesture );
+ Menu_AddItem( &s_controls.menu, &s_controls.chat );
+ Menu_AddItem( &s_controls.menu, &s_controls.chat2 );
+ Menu_AddItem( &s_controls.menu, &s_controls.chat3 );
+ Menu_AddItem( &s_controls.menu, &s_controls.chat4 );
+
+ Menu_AddItem( &s_controls.menu, &s_controls.back );
+
+ trap_Cvar_VariableStringBuffer( "name", s_controls.name.string, 16 );
+ Q_CleanStr( s_controls.name.string );
+
+ // initialize the configurable cvars
+ Controls_InitCvars();
+
+ // initialize the current config
+ Controls_GetConfig();
+
+ // intialize the model
+ Controls_InitModel();
+
+ // intialize the weapons
+ Controls_InitWeapons ();
+
+ // initial default section
+ s_controls.section = C_LOOKING;
+
+ // update the ui
+ Controls_Update();
+}
+
+
+/*
+=================
+Controls_Cache
+=================
+*/
+void Controls_Cache( void ) {
+ trap_R_RegisterShaderNoMip( ART_BACK0 );
+ trap_R_RegisterShaderNoMip( ART_BACK1 );
+ trap_R_RegisterShaderNoMip( ART_FRAMEL );
+ trap_R_RegisterShaderNoMip( ART_FRAMER );
+}
+
+
+/*
+=================
+UI_ControlsMenu
+=================
+*/
+void UI_ControlsMenu( void ) {
+ Controls_MenuInit();
+ UI_PushMenu( &s_controls.menu );
+}
diff --git a/code/q3_ui/ui_credits.c b/code/q3_ui/ui_credits.c
new file mode 100755
index 0000000..266e00b
--- /dev/null
+++ b/code/q3_ui/ui_credits.c
@@ -0,0 +1,129 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*
+=======================================================================
+
+CREDITS
+
+=======================================================================
+*/
+
+
+#include "ui_local.h"
+
+
+typedef struct {
+ menuframework_s menu;
+} creditsmenu_t;
+
+static creditsmenu_t s_credits;
+
+
+/*
+=================
+UI_CreditMenu_Key
+=================
+*/
+static sfxHandle_t UI_CreditMenu_Key( int key ) {
+ if( key & K_CHAR_FLAG ) {
+ return 0;
+ }
+
+ trap_Cmd_ExecuteText( EXEC_APPEND, "quit\n" );
+ return 0;
+}
+
+
+/*
+===============
+UI_CreditMenu_Draw
+===============
+*/
+static void UI_CreditMenu_Draw( void ) {
+ int y;
+
+ y = 12;
+ UI_DrawProportionalString( 320, y, "id Software is:", UI_CENTER|UI_SMALLFONT, color_white );
+
+ y += 1.42 * PROP_HEIGHT * PROP_SMALL_SIZE_SCALE;
+ UI_DrawProportionalString( 320, y, "Programming", UI_CENTER|UI_SMALLFONT, color_white );
+ y += PROP_HEIGHT * PROP_SMALL_SIZE_SCALE;
+ UI_DrawProportionalString( 320, y, "John Carmack, Robert A. Duffy, Jim Dose'", UI_CENTER|UI_SMALLFONT, color_white );
+
+ y += 1.42 * PROP_HEIGHT * PROP_SMALL_SIZE_SCALE;
+ UI_DrawProportionalString( 320, y, "Art", UI_CENTER|UI_SMALLFONT, color_white );
+ y += PROP_HEIGHT * PROP_SMALL_SIZE_SCALE;
+ UI_DrawProportionalString( 320, y, "Adrian Carmack, Kevin Cloud,", UI_CENTER|UI_SMALLFONT, color_white );
+ y += PROP_HEIGHT * PROP_SMALL_SIZE_SCALE;
+ UI_DrawProportionalString( 320, y, "Kenneth Scott, Seneca Menard, Fred Nilsson", UI_CENTER|UI_SMALLFONT, color_white );
+
+ y += 1.42 * PROP_HEIGHT * PROP_SMALL_SIZE_SCALE;
+ UI_DrawProportionalString( 320, y, "Game Designer", UI_CENTER|UI_SMALLFONT, color_white );
+ y += PROP_HEIGHT * PROP_SMALL_SIZE_SCALE;
+ UI_DrawProportionalString( 320, y, "Graeme Devine", UI_CENTER|UI_SMALLFONT, color_white );
+
+ y += 1.42 * PROP_HEIGHT * PROP_SMALL_SIZE_SCALE;
+ UI_DrawProportionalString( 320, y, "Level Design", UI_CENTER|UI_SMALLFONT, color_white );
+ y += PROP_HEIGHT * PROP_SMALL_SIZE_SCALE;
+ UI_DrawProportionalString( 320, y, "Tim Willits, Christian Antkow, Paul Jaquays", UI_CENTER|UI_SMALLFONT, color_white );
+
+ y += 1.42 * PROP_HEIGHT * PROP_SMALL_SIZE_SCALE;
+ UI_DrawProportionalString( 320, y, "CEO", UI_CENTER|UI_SMALLFONT, color_white );
+ y += PROP_HEIGHT * PROP_SMALL_SIZE_SCALE;
+ UI_DrawProportionalString( 320, y, "Todd Hollenshead", UI_CENTER|UI_SMALLFONT, color_white );
+
+ y += 1.42 * PROP_HEIGHT * PROP_SMALL_SIZE_SCALE;
+ UI_DrawProportionalString( 320, y, "Director of Business Development", UI_CENTER|UI_SMALLFONT, color_white );
+ y += PROP_HEIGHT * PROP_SMALL_SIZE_SCALE;
+ UI_DrawProportionalString( 320, y, "Marty Stratton", UI_CENTER|UI_SMALLFONT, color_white );
+
+ y += 1.42 * PROP_HEIGHT * PROP_SMALL_SIZE_SCALE;
+ UI_DrawProportionalString( 320, y, "Biz Assist and id Mom", UI_CENTER|UI_SMALLFONT, color_white );
+ y += PROP_HEIGHT * PROP_SMALL_SIZE_SCALE;
+ UI_DrawProportionalString( 320, y, "Donna Jackson", UI_CENTER|UI_SMALLFONT, color_white );
+
+ y += 1.42 * PROP_HEIGHT * PROP_SMALL_SIZE_SCALE;
+ UI_DrawProportionalString( 320, y, "Development Assistance", UI_CENTER|UI_SMALLFONT, color_white );
+ y += PROP_HEIGHT * PROP_SMALL_SIZE_SCALE;
+ UI_DrawProportionalString( 320, y, "Eric Webb", UI_CENTER|UI_SMALLFONT, color_white );
+
+ y += 1.35 * PROP_HEIGHT * PROP_SMALL_SIZE_SCALE;
+ UI_DrawString( 320, y, "To order: 1-800-idgames www.quake3arena.com www.idsoftware.com", UI_CENTER|UI_SMALLFONT, color_red );
+ y += SMALLCHAR_HEIGHT;
+ UI_DrawString( 320, y, "Quake III Arena(c) 1999-2000, Id Software, Inc. All Rights Reserved", UI_CENTER|UI_SMALLFONT, color_red );
+}
+
+
+/*
+===============
+UI_CreditMenu
+===============
+*/
+void UI_CreditMenu( void ) {
+ memset( &s_credits, 0 ,sizeof(s_credits) );
+
+ s_credits.menu.draw = UI_CreditMenu_Draw;
+ s_credits.menu.key = UI_CreditMenu_Key;
+ s_credits.menu.fullscreen = qtrue;
+ UI_PushMenu ( &s_credits.menu );
+}
diff --git a/code/q3_ui/ui_demo2.c b/code/q3_ui/ui_demo2.c
new file mode 100755
index 0000000..57b5955
--- /dev/null
+++ b/code/q3_ui/ui_demo2.c
@@ -0,0 +1,291 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*
+=======================================================================
+
+DEMOS MENU
+
+=======================================================================
+*/
+
+
+#include "ui_local.h"
+
+
+#define ART_BACK0 "menu/art/back_0"
+#define ART_BACK1 "menu/art/back_1"
+#define ART_GO0 "menu/art/play_0"
+#define ART_GO1 "menu/art/play_1"
+#define ART_FRAMEL "menu/art/frame2_l"
+#define ART_FRAMER "menu/art/frame1_r"
+#define ART_ARROWS "menu/art/arrows_horz_0"
+#define ART_ARROWLEFT "menu/art/arrows_horz_left"
+#define ART_ARROWRIGHT "menu/art/arrows_horz_right"
+
+#define MAX_DEMOS 128
+#define NAMEBUFSIZE ( MAX_DEMOS * 16 )
+
+#define ID_BACK 10
+#define ID_GO 11
+#define ID_LIST 12
+#define ID_RIGHT 13
+#define ID_LEFT 14
+
+#define ARROWS_WIDTH 128
+#define ARROWS_HEIGHT 48
+
+
+typedef struct {
+ menuframework_s menu;
+
+ menutext_s banner;
+ menubitmap_s framel;
+ menubitmap_s framer;
+
+ menulist_s list;
+
+ menubitmap_s arrows;
+ menubitmap_s left;
+ menubitmap_s right;
+ menubitmap_s back;
+ menubitmap_s go;
+
+ int numDemos;
+ char names[NAMEBUFSIZE];
+ char *demolist[MAX_DEMOS];
+} demos_t;
+
+static demos_t s_demos;
+
+
+/*
+===============
+Demos_MenuEvent
+===============
+*/
+static void Demos_MenuEvent( void *ptr, int event ) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+
+ switch( ((menucommon_s*)ptr)->id ) {
+ case ID_GO:
+ UI_ForceMenuOff ();
+ trap_Cmd_ExecuteText( EXEC_APPEND, va( "demo %s\n",
+ s_demos.list.itemnames[s_demos.list.curvalue]) );
+ break;
+
+ case ID_BACK:
+ UI_PopMenu();
+ break;
+
+ case ID_LEFT:
+ ScrollList_Key( &s_demos.list, K_LEFTARROW );
+ break;
+
+ case ID_RIGHT:
+ ScrollList_Key( &s_demos.list, K_RIGHTARROW );
+ break;
+ }
+}
+
+
+/*
+=================
+UI_DemosMenu_Key
+=================
+*/
+static sfxHandle_t UI_DemosMenu_Key( int key ) {
+ menucommon_s *item;
+
+ item = Menu_ItemAtCursor( &s_demos.menu );
+
+ return Menu_DefaultKey( &s_demos.menu, key );
+}
+
+
+/*
+===============
+Demos_MenuInit
+===============
+*/
+static void Demos_MenuInit( void ) {
+ int i;
+ int len;
+ char *demoname, extension[32];
+
+ memset( &s_demos, 0 ,sizeof(demos_t) );
+ s_demos.menu.key = UI_DemosMenu_Key;
+
+ Demos_Cache();
+
+ s_demos.menu.fullscreen = qtrue;
+ s_demos.menu.wrapAround = qtrue;
+
+ s_demos.banner.generic.type = MTYPE_BTEXT;
+ s_demos.banner.generic.x = 320;
+ s_demos.banner.generic.y = 16;
+ s_demos.banner.string = "DEMOS";
+ s_demos.banner.color = color_white;
+ s_demos.banner.style = UI_CENTER;
+
+ s_demos.framel.generic.type = MTYPE_BITMAP;
+ s_demos.framel.generic.name = ART_FRAMEL;
+ s_demos.framel.generic.flags = QMF_INACTIVE;
+ s_demos.framel.generic.x = 0;
+ s_demos.framel.generic.y = 78;
+ s_demos.framel.width = 256;
+ s_demos.framel.height = 329;
+
+ s_demos.framer.generic.type = MTYPE_BITMAP;
+ s_demos.framer.generic.name = ART_FRAMER;
+ s_demos.framer.generic.flags = QMF_INACTIVE;
+ s_demos.framer.generic.x = 376;
+ s_demos.framer.generic.y = 76;
+ s_demos.framer.width = 256;
+ s_demos.framer.height = 334;
+
+ s_demos.arrows.generic.type = MTYPE_BITMAP;
+ s_demos.arrows.generic.name = ART_ARROWS;
+ s_demos.arrows.generic.flags = QMF_INACTIVE;
+ s_demos.arrows.generic.x = 320-ARROWS_WIDTH/2;
+ s_demos.arrows.generic.y = 400;
+ s_demos.arrows.width = ARROWS_WIDTH;
+ s_demos.arrows.height = ARROWS_HEIGHT;
+
+ s_demos.left.generic.type = MTYPE_BITMAP;
+ s_demos.left.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_MOUSEONLY;
+ s_demos.left.generic.x = 320-ARROWS_WIDTH/2;
+ s_demos.left.generic.y = 400;
+ s_demos.left.generic.id = ID_LEFT;
+ s_demos.left.generic.callback = Demos_MenuEvent;
+ s_demos.left.width = ARROWS_WIDTH/2;
+ s_demos.left.height = ARROWS_HEIGHT;
+ s_demos.left.focuspic = ART_ARROWLEFT;
+
+ s_demos.right.generic.type = MTYPE_BITMAP;
+ s_demos.right.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_MOUSEONLY;
+ s_demos.right.generic.x = 320;
+ s_demos.right.generic.y = 400;
+ s_demos.right.generic.id = ID_RIGHT;
+ s_demos.right.generic.callback = Demos_MenuEvent;
+ s_demos.right.width = ARROWS_WIDTH/2;
+ s_demos.right.height = ARROWS_HEIGHT;
+ s_demos.right.focuspic = ART_ARROWRIGHT;
+
+ s_demos.back.generic.type = MTYPE_BITMAP;
+ s_demos.back.generic.name = ART_BACK0;
+ s_demos.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_demos.back.generic.id = ID_BACK;
+ s_demos.back.generic.callback = Demos_MenuEvent;
+ s_demos.back.generic.x = 0;
+ s_demos.back.generic.y = 480-64;
+ s_demos.back.width = 128;
+ s_demos.back.height = 64;
+ s_demos.back.focuspic = ART_BACK1;
+
+ s_demos.go.generic.type = MTYPE_BITMAP;
+ s_demos.go.generic.name = ART_GO0;
+ s_demos.go.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_demos.go.generic.id = ID_GO;
+ s_demos.go.generic.callback = Demos_MenuEvent;
+ s_demos.go.generic.x = 640;
+ s_demos.go.generic.y = 480-64;
+ s_demos.go.width = 128;
+ s_demos.go.height = 64;
+ s_demos.go.focuspic = ART_GO1;
+
+ s_demos.list.generic.type = MTYPE_SCROLLLIST;
+ s_demos.list.generic.flags = QMF_PULSEIFFOCUS;
+ s_demos.list.generic.callback = Demos_MenuEvent;
+ s_demos.list.generic.id = ID_LIST;
+ s_demos.list.generic.x = 118;
+ s_demos.list.generic.y = 130;
+ s_demos.list.width = 16;
+ s_demos.list.height = 14;
+ Com_sprintf(extension, sizeof(extension), "dm_%d", (int)trap_Cvar_VariableValue( "protocol" ) );
+ s_demos.list.numitems = trap_FS_GetFileList( "demos", extension, s_demos.names, NAMEBUFSIZE );
+ s_demos.list.itemnames = (const char **)s_demos.demolist;
+ s_demos.list.columns = 3;
+
+ if (!s_demos.list.numitems) {
+ strcpy( s_demos.names, "No Demos Found." );
+ s_demos.list.numitems = 1;
+
+ //degenerate case, not selectable
+ s_demos.go.generic.flags |= (QMF_INACTIVE|QMF_HIDDEN);
+ }
+ else if (s_demos.list.numitems > MAX_DEMOS)
+ s_demos.list.numitems = MAX_DEMOS;
+
+ demoname = s_demos.names;
+ for ( i = 0; i < s_demos.list.numitems; i++ ) {
+ s_demos.list.itemnames[i] = demoname;
+
+ // strip extension
+ len = strlen( demoname );
+ if (!Q_stricmp(demoname + len - 4,".dm3"))
+ demoname[len-4] = '\0';
+
+ Q_strupr(demoname);
+
+ demoname += len + 1;
+ }
+
+ Menu_AddItem( &s_demos.menu, &s_demos.banner );
+ Menu_AddItem( &s_demos.menu, &s_demos.framel );
+ Menu_AddItem( &s_demos.menu, &s_demos.framer );
+ Menu_AddItem( &s_demos.menu, &s_demos.list );
+ Menu_AddItem( &s_demos.menu, &s_demos.arrows );
+ Menu_AddItem( &s_demos.menu, &s_demos.left );
+ Menu_AddItem( &s_demos.menu, &s_demos.right );
+ Menu_AddItem( &s_demos.menu, &s_demos.back );
+ Menu_AddItem( &s_demos.menu, &s_demos.go );
+}
+
+/*
+=================
+Demos_Cache
+=================
+*/
+void Demos_Cache( void ) {
+ trap_R_RegisterShaderNoMip( ART_BACK0 );
+ trap_R_RegisterShaderNoMip( ART_BACK1 );
+ trap_R_RegisterShaderNoMip( ART_GO0 );
+ trap_R_RegisterShaderNoMip( ART_GO1 );
+ trap_R_RegisterShaderNoMip( ART_FRAMEL );
+ trap_R_RegisterShaderNoMip( ART_FRAMER );
+ trap_R_RegisterShaderNoMip( ART_ARROWS );
+ trap_R_RegisterShaderNoMip( ART_ARROWLEFT );
+ trap_R_RegisterShaderNoMip( ART_ARROWRIGHT );
+}
+
+/*
+===============
+UI_DemosMenu
+===============
+*/
+void UI_DemosMenu( void ) {
+ Demos_MenuInit();
+ UI_PushMenu( &s_demos.menu );
+}
diff --git a/code/q3_ui/ui_display.c b/code/q3_ui/ui_display.c
new file mode 100755
index 0000000..9a8a49f
--- /dev/null
+++ b/code/q3_ui/ui_display.c
@@ -0,0 +1,265 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*
+=======================================================================
+
+DISPLAY OPTIONS MENU
+
+=======================================================================
+*/
+
+#include "ui_local.h"
+
+
+#define ART_FRAMEL "menu/art/frame2_l"
+#define ART_FRAMER "menu/art/frame1_r"
+#define ART_BACK0 "menu/art/back_0"
+#define ART_BACK1 "menu/art/back_1"
+
+#define ID_GRAPHICS 10
+#define ID_DISPLAY 11
+#define ID_SOUND 12
+#define ID_NETWORK 13
+#define ID_BRIGHTNESS 14
+#define ID_SCREENSIZE 15
+#define ID_BACK 16
+
+
+typedef struct {
+ menuframework_s menu;
+
+ menutext_s banner;
+ menubitmap_s framel;
+ menubitmap_s framer;
+
+ menutext_s graphics;
+ menutext_s display;
+ menutext_s sound;
+ menutext_s network;
+
+ menuslider_s brightness;
+ menuslider_s screensize;
+
+ menubitmap_s back;
+} displayOptionsInfo_t;
+
+static displayOptionsInfo_t displayOptionsInfo;
+
+
+/*
+=================
+UI_DisplayOptionsMenu_Event
+=================
+*/
+static void UI_DisplayOptionsMenu_Event( void* ptr, int event ) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+
+ switch( ((menucommon_s*)ptr)->id ) {
+ case ID_GRAPHICS:
+ UI_PopMenu();
+ UI_GraphicsOptionsMenu();
+ break;
+
+ case ID_DISPLAY:
+ break;
+
+ case ID_SOUND:
+ UI_PopMenu();
+ UI_SoundOptionsMenu();
+ break;
+
+ case ID_NETWORK:
+ UI_PopMenu();
+ UI_NetworkOptionsMenu();
+ break;
+
+ case ID_BRIGHTNESS:
+ trap_Cvar_SetValue( "r_gamma", displayOptionsInfo.brightness.curvalue / 10.0f );
+ break;
+
+ case ID_SCREENSIZE:
+ trap_Cvar_SetValue( "cg_viewsize", displayOptionsInfo.screensize.curvalue * 10 );
+ break;
+
+ case ID_BACK:
+ UI_PopMenu();
+ break;
+ }
+}
+
+
+/*
+===============
+UI_DisplayOptionsMenu_Init
+===============
+*/
+static void UI_DisplayOptionsMenu_Init( void ) {
+ int y;
+
+ memset( &displayOptionsInfo, 0, sizeof(displayOptionsInfo) );
+
+ UI_DisplayOptionsMenu_Cache();
+ displayOptionsInfo.menu.wrapAround = qtrue;
+ displayOptionsInfo.menu.fullscreen = qtrue;
+
+ displayOptionsInfo.banner.generic.type = MTYPE_BTEXT;
+ displayOptionsInfo.banner.generic.flags = QMF_CENTER_JUSTIFY;
+ displayOptionsInfo.banner.generic.x = 320;
+ displayOptionsInfo.banner.generic.y = 16;
+ displayOptionsInfo.banner.string = "SYSTEM SETUP";
+ displayOptionsInfo.banner.color = color_white;
+ displayOptionsInfo.banner.style = UI_CENTER;
+
+ displayOptionsInfo.framel.generic.type = MTYPE_BITMAP;
+ displayOptionsInfo.framel.generic.name = ART_FRAMEL;
+ displayOptionsInfo.framel.generic.flags = QMF_INACTIVE;
+ displayOptionsInfo.framel.generic.x = 0;
+ displayOptionsInfo.framel.generic.y = 78;
+ displayOptionsInfo.framel.width = 256;
+ displayOptionsInfo.framel.height = 329;
+
+ displayOptionsInfo.framer.generic.type = MTYPE_BITMAP;
+ displayOptionsInfo.framer.generic.name = ART_FRAMER;
+ displayOptionsInfo.framer.generic.flags = QMF_INACTIVE;
+ displayOptionsInfo.framer.generic.x = 376;
+ displayOptionsInfo.framer.generic.y = 76;
+ displayOptionsInfo.framer.width = 256;
+ displayOptionsInfo.framer.height = 334;
+
+ displayOptionsInfo.graphics.generic.type = MTYPE_PTEXT;
+ displayOptionsInfo.graphics.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ displayOptionsInfo.graphics.generic.id = ID_GRAPHICS;
+ displayOptionsInfo.graphics.generic.callback = UI_DisplayOptionsMenu_Event;
+ displayOptionsInfo.graphics.generic.x = 216;
+ displayOptionsInfo.graphics.generic.y = 240 - 2 * PROP_HEIGHT;
+ displayOptionsInfo.graphics.string = "GRAPHICS";
+ displayOptionsInfo.graphics.style = UI_RIGHT;
+ displayOptionsInfo.graphics.color = color_red;
+
+ displayOptionsInfo.display.generic.type = MTYPE_PTEXT;
+ displayOptionsInfo.display.generic.flags = QMF_RIGHT_JUSTIFY;
+ displayOptionsInfo.display.generic.id = ID_DISPLAY;
+ displayOptionsInfo.display.generic.callback = UI_DisplayOptionsMenu_Event;
+ displayOptionsInfo.display.generic.x = 216;
+ displayOptionsInfo.display.generic.y = 240 - PROP_HEIGHT;
+ displayOptionsInfo.display.string = "DISPLAY";
+ displayOptionsInfo.display.style = UI_RIGHT;
+ displayOptionsInfo.display.color = color_red;
+
+ displayOptionsInfo.sound.generic.type = MTYPE_PTEXT;
+ displayOptionsInfo.sound.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ displayOptionsInfo.sound.generic.id = ID_SOUND;
+ displayOptionsInfo.sound.generic.callback = UI_DisplayOptionsMenu_Event;
+ displayOptionsInfo.sound.generic.x = 216;
+ displayOptionsInfo.sound.generic.y = 240;
+ displayOptionsInfo.sound.string = "SOUND";
+ displayOptionsInfo.sound.style = UI_RIGHT;
+ displayOptionsInfo.sound.color = color_red;
+
+ displayOptionsInfo.network.generic.type = MTYPE_PTEXT;
+ displayOptionsInfo.network.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ displayOptionsInfo.network.generic.id = ID_NETWORK;
+ displayOptionsInfo.network.generic.callback = UI_DisplayOptionsMenu_Event;
+ displayOptionsInfo.network.generic.x = 216;
+ displayOptionsInfo.network.generic.y = 240 + PROP_HEIGHT;
+ displayOptionsInfo.network.string = "NETWORK";
+ displayOptionsInfo.network.style = UI_RIGHT;
+ displayOptionsInfo.network.color = color_red;
+
+ y = 240 - 1 * (BIGCHAR_HEIGHT+2);
+ displayOptionsInfo.brightness.generic.type = MTYPE_SLIDER;
+ displayOptionsInfo.brightness.generic.name = "Brightness:";
+ displayOptionsInfo.brightness.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ displayOptionsInfo.brightness.generic.callback = UI_DisplayOptionsMenu_Event;
+ displayOptionsInfo.brightness.generic.id = ID_BRIGHTNESS;
+ displayOptionsInfo.brightness.generic.x = 400;
+ displayOptionsInfo.brightness.generic.y = y;
+ displayOptionsInfo.brightness.minvalue = 5;
+ displayOptionsInfo.brightness.maxvalue = 20;
+ if( !uis.glconfig.deviceSupportsGamma ) {
+ displayOptionsInfo.brightness.generic.flags |= QMF_GRAYED;
+ }
+
+ y += BIGCHAR_HEIGHT+2;
+ displayOptionsInfo.screensize.generic.type = MTYPE_SLIDER;
+ displayOptionsInfo.screensize.generic.name = "Screen Size:";
+ displayOptionsInfo.screensize.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ displayOptionsInfo.screensize.generic.callback = UI_DisplayOptionsMenu_Event;
+ displayOptionsInfo.screensize.generic.id = ID_SCREENSIZE;
+ displayOptionsInfo.screensize.generic.x = 400;
+ displayOptionsInfo.screensize.generic.y = y;
+ displayOptionsInfo.screensize.minvalue = 3;
+ displayOptionsInfo.screensize.maxvalue = 10;
+
+ displayOptionsInfo.back.generic.type = MTYPE_BITMAP;
+ displayOptionsInfo.back.generic.name = ART_BACK0;
+ displayOptionsInfo.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ displayOptionsInfo.back.generic.callback = UI_DisplayOptionsMenu_Event;
+ displayOptionsInfo.back.generic.id = ID_BACK;
+ displayOptionsInfo.back.generic.x = 0;
+ displayOptionsInfo.back.generic.y = 480-64;
+ displayOptionsInfo.back.width = 128;
+ displayOptionsInfo.back.height = 64;
+ displayOptionsInfo.back.focuspic = ART_BACK1;
+
+ Menu_AddItem( &displayOptionsInfo.menu, ( void * ) &displayOptionsInfo.banner );
+ Menu_AddItem( &displayOptionsInfo.menu, ( void * ) &displayOptionsInfo.framel );
+ Menu_AddItem( &displayOptionsInfo.menu, ( void * ) &displayOptionsInfo.framer );
+ Menu_AddItem( &displayOptionsInfo.menu, ( void * ) &displayOptionsInfo.graphics );
+ Menu_AddItem( &displayOptionsInfo.menu, ( void * ) &displayOptionsInfo.display );
+ Menu_AddItem( &displayOptionsInfo.menu, ( void * ) &displayOptionsInfo.sound );
+ Menu_AddItem( &displayOptionsInfo.menu, ( void * ) &displayOptionsInfo.network );
+ Menu_AddItem( &displayOptionsInfo.menu, ( void * ) &displayOptionsInfo.brightness );
+ Menu_AddItem( &displayOptionsInfo.menu, ( void * ) &displayOptionsInfo.screensize );
+ Menu_AddItem( &displayOptionsInfo.menu, ( void * ) &displayOptionsInfo.back );
+
+ displayOptionsInfo.brightness.curvalue = trap_Cvar_VariableValue("r_gamma") * 10;
+ displayOptionsInfo.screensize.curvalue = trap_Cvar_VariableValue( "cg_viewsize")/10;
+}
+
+
+/*
+===============
+UI_DisplayOptionsMenu_Cache
+===============
+*/
+void UI_DisplayOptionsMenu_Cache( void ) {
+ trap_R_RegisterShaderNoMip( ART_FRAMEL );
+ trap_R_RegisterShaderNoMip( ART_FRAMER );
+ trap_R_RegisterShaderNoMip( ART_BACK0 );
+ trap_R_RegisterShaderNoMip( ART_BACK1 );
+}
+
+
+/*
+===============
+UI_DisplayOptionsMenu
+===============
+*/
+void UI_DisplayOptionsMenu( void ) {
+ UI_DisplayOptionsMenu_Init();
+ UI_PushMenu( &displayOptionsInfo.menu );
+ Menu_SetCursorToItem( &displayOptionsInfo.menu, &displayOptionsInfo.display );
+}
diff --git a/code/q3_ui/ui_gameinfo.c b/code/q3_ui/ui_gameinfo.c
new file mode 100755
index 0000000..29beddd
--- /dev/null
+++ b/code/q3_ui/ui_gameinfo.c
@@ -0,0 +1,820 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+//
+// gameinfo.c
+//
+
+#include "ui_local.h"
+
+
+//
+// arena and bot info
+//
+
+#define POOLSIZE 128 * 1024
+
+int ui_numBots;
+static char *ui_botInfos[MAX_BOTS];
+
+static int ui_numArenas;
+static char *ui_arenaInfos[MAX_ARENAS];
+
+static int ui_numSinglePlayerArenas;
+static int ui_numSpecialSinglePlayerArenas;
+
+static char memoryPool[POOLSIZE];
+static int allocPoint, outOfMemory;
+
+
+/*
+===============
+UI_Alloc
+===============
+*/
+void *UI_Alloc( int size ) {
+ char *p;
+
+ if ( allocPoint + size > POOLSIZE ) {
+ outOfMemory = qtrue;
+ return NULL;
+ }
+
+ p = &memoryPool[allocPoint];
+
+ allocPoint += ( size + 31 ) & ~31;
+
+ return p;
+}
+
+/*
+===============
+UI_InitMemory
+===============
+*/
+void UI_InitMemory( void ) {
+ allocPoint = 0;
+ outOfMemory = qfalse;
+}
+
+/*
+===============
+UI_ParseInfos
+===============
+*/
+int UI_ParseInfos( char *buf, int max, char *infos[] ) {
+ char *token;
+ int count;
+ char key[MAX_TOKEN_CHARS];
+ char info[MAX_INFO_STRING];
+
+ count = 0;
+
+ while ( 1 ) {
+ token = COM_Parse( &buf );
+ if ( !token[0] ) {
+ break;
+ }
+ if ( strcmp( token, "{" ) ) {
+ Com_Printf( "Missing { in info file\n" );
+ break;
+ }
+
+ if ( count == max ) {
+ Com_Printf( "Max infos exceeded\n" );
+ break;
+ }
+
+ info[0] = '\0';
+ while ( 1 ) {
+ token = COM_ParseExt( &buf, qtrue );
+ if ( !token[0] ) {
+ Com_Printf( "Unexpected end of info file\n" );
+ break;
+ }
+ if ( !strcmp( token, "}" ) ) {
+ break;
+ }
+ Q_strncpyz( key, token, sizeof( key ) );
+
+ token = COM_ParseExt( &buf, qfalse );
+ if ( !token[0] ) {
+ strcpy( token, "<NULL>" );
+ }
+ Info_SetValueForKey( info, key, token );
+ }
+ //NOTE: extra space for arena number
+ infos[count] = UI_Alloc(strlen(info) + strlen("\\num\\") + strlen(va("%d", MAX_ARENAS)) + 1);
+ if (infos[count]) {
+ strcpy(infos[count], info);
+ count++;
+ }
+ }
+ return count;
+}
+
+/*
+===============
+UI_LoadArenasFromFile
+===============
+*/
+static void UI_LoadArenasFromFile( char *filename ) {
+ int len;
+ fileHandle_t f;
+ char buf[MAX_ARENAS_TEXT];
+
+ len = trap_FS_FOpenFile( filename, &f, FS_READ );
+ if ( !f ) {
+ trap_Print( va( S_COLOR_RED "file not found: %s\n", filename ) );
+ return;
+ }
+ if ( len >= MAX_ARENAS_TEXT ) {
+ trap_Print( va( S_COLOR_RED "file too large: %s is %i, max allowed is %i", filename, len, MAX_ARENAS_TEXT ) );
+ trap_FS_FCloseFile( f );
+ return;
+ }
+
+ trap_FS_Read( buf, len, f );
+ buf[len] = 0;
+ trap_FS_FCloseFile( f );
+
+ ui_numArenas += UI_ParseInfos( buf, MAX_ARENAS - ui_numArenas, &ui_arenaInfos[ui_numArenas] );
+}
+
+/*
+===============
+UI_LoadArenas
+===============
+*/
+static void UI_LoadArenas( void ) {
+ int numdirs;
+ vmCvar_t arenasFile;
+ char filename[128];
+ char dirlist[1024];
+ char* dirptr;
+ int i, n;
+ int dirlen;
+ char *type;
+ char *tag;
+ int singlePlayerNum, specialNum, otherNum;
+
+ ui_numArenas = 0;
+
+ trap_Cvar_Register( &arenasFile, "g_arenasFile", "", CVAR_INIT|CVAR_ROM );
+ if( *arenasFile.string ) {
+ UI_LoadArenasFromFile(arenasFile.string);
+ }
+ else {
+ UI_LoadArenasFromFile("scripts/arenas.txt");
+ }
+
+ // get all arenas from .arena files
+ numdirs = trap_FS_GetFileList("scripts", ".arena", dirlist, 1024 );
+ dirptr = dirlist;
+ for (i = 0; i < numdirs; i++, dirptr += dirlen+1) {
+ dirlen = strlen(dirptr);
+ strcpy(filename, "scripts/");
+ strcat(filename, dirptr);
+ UI_LoadArenasFromFile(filename);
+ }
+ trap_Print( va( "%i arenas parsed\n", ui_numArenas ) );
+ if (outOfMemory) trap_Print(S_COLOR_YELLOW"WARNING: not anough memory in pool to load all arenas\n");
+
+ // set initial numbers
+ for( n = 0; n < ui_numArenas; n++ ) {
+ Info_SetValueForKey( ui_arenaInfos[n], "num", va( "%i", n ) );
+ }
+
+ // go through and count single players levels
+ ui_numSinglePlayerArenas = 0;
+ ui_numSpecialSinglePlayerArenas = 0;
+ for( n = 0; n < ui_numArenas; n++ ) {
+ // determine type
+ type = Info_ValueForKey( ui_arenaInfos[n], "type" );
+
+ // if no type specified, it will be treated as "ffa"
+ if( !*type ) {
+ continue;
+ }
+
+ if( strstr( type, "single" ) ) {
+ // check for special single player arenas (training, final)
+ tag = Info_ValueForKey( ui_arenaInfos[n], "special" );
+ if( *tag ) {
+ ui_numSpecialSinglePlayerArenas++;
+ continue;
+ }
+
+ ui_numSinglePlayerArenas++;
+ }
+ }
+
+ n = ui_numSinglePlayerArenas % ARENAS_PER_TIER;
+ if( n != 0 ) {
+ ui_numSinglePlayerArenas -= n;
+ trap_Print( va( "%i arenas ignored to make count divisible by %i\n", n, ARENAS_PER_TIER ) );
+ }
+
+ // go through once more and assign number to the levels
+ singlePlayerNum = 0;
+ specialNum = singlePlayerNum + ui_numSinglePlayerArenas;
+ otherNum = specialNum + ui_numSpecialSinglePlayerArenas;
+ for( n = 0; n < ui_numArenas; n++ ) {
+ // determine type
+ type = Info_ValueForKey( ui_arenaInfos[n], "type" );
+
+ // if no type specified, it will be treated as "ffa"
+ if( *type ) {
+ if( strstr( type, "single" ) ) {
+ // check for special single player arenas (training, final)
+ tag = Info_ValueForKey( ui_arenaInfos[n], "special" );
+ if( *tag ) {
+ Info_SetValueForKey( ui_arenaInfos[n], "num", va( "%i", specialNum++ ) );
+ continue;
+ }
+
+ Info_SetValueForKey( ui_arenaInfos[n], "num", va( "%i", singlePlayerNum++ ) );
+ continue;
+ }
+ }
+
+ Info_SetValueForKey( ui_arenaInfos[n], "num", va( "%i", otherNum++ ) );
+ }
+}
+
+/*
+===============
+UI_GetArenaInfoByNumber
+===============
+*/
+const char *UI_GetArenaInfoByNumber( int num ) {
+ int n;
+ char *value;
+
+ if( num < 0 || num >= ui_numArenas ) {
+ trap_Print( va( S_COLOR_RED "Invalid arena number: %i\n", num ) );
+ return NULL;
+ }
+
+ for( n = 0; n < ui_numArenas; n++ ) {
+ value = Info_ValueForKey( ui_arenaInfos[n], "num" );
+ if( *value && atoi(value) == num ) {
+ return ui_arenaInfos[n];
+ }
+ }
+
+ return NULL;
+}
+
+
+/*
+===============
+UI_GetArenaInfoByNumber
+===============
+*/
+const char *UI_GetArenaInfoByMap( const char *map ) {
+ int n;
+
+ for( n = 0; n < ui_numArenas; n++ ) {
+ if( Q_stricmp( Info_ValueForKey( ui_arenaInfos[n], "map" ), map ) == 0 ) {
+ return ui_arenaInfos[n];
+ }
+ }
+
+ return NULL;
+}
+
+
+/*
+===============
+UI_GetSpecialArenaInfo
+===============
+*/
+const char *UI_GetSpecialArenaInfo( const char *tag ) {
+ int n;
+
+ for( n = 0; n < ui_numArenas; n++ ) {
+ if( Q_stricmp( Info_ValueForKey( ui_arenaInfos[n], "special" ), tag ) == 0 ) {
+ return ui_arenaInfos[n];
+ }
+ }
+
+ return NULL;
+}
+
+/*
+===============
+UI_LoadBotsFromFile
+===============
+*/
+static void UI_LoadBotsFromFile( char *filename ) {
+ int len;
+ fileHandle_t f;
+ char buf[MAX_BOTS_TEXT];
+
+ len = trap_FS_FOpenFile( filename, &f, FS_READ );
+ if ( !f ) {
+ trap_Print( va( S_COLOR_RED "file not found: %s\n", filename ) );
+ return;
+ }
+ if ( len >= MAX_BOTS_TEXT ) {
+ trap_Print( va( S_COLOR_RED "file too large: %s is %i, max allowed is %i", filename, len, MAX_BOTS_TEXT ) );
+ trap_FS_FCloseFile( f );
+ return;
+ }
+
+ trap_FS_Read( buf, len, f );
+ buf[len] = 0;
+ trap_FS_FCloseFile( f );
+
+ ui_numBots += UI_ParseInfos( buf, MAX_BOTS - ui_numBots, &ui_botInfos[ui_numBots] );
+ if (outOfMemory) trap_Print(S_COLOR_YELLOW"WARNING: not anough memory in pool to load all bots\n");
+}
+
+/*
+===============
+UI_LoadBots
+===============
+*/
+static void UI_LoadBots( void ) {
+ vmCvar_t botsFile;
+ int numdirs;
+ char filename[128];
+ char dirlist[1024];
+ char* dirptr;
+ int i;
+ int dirlen;
+
+ ui_numBots = 0;
+
+ trap_Cvar_Register( &botsFile, "g_botsFile", "", CVAR_INIT|CVAR_ROM );
+ if( *botsFile.string ) {
+ UI_LoadBotsFromFile(botsFile.string);
+ }
+ else {
+ UI_LoadBotsFromFile("scripts/bots.txt");
+ }
+
+ // get all bots from .bot files
+ numdirs = trap_FS_GetFileList("scripts", ".bot", dirlist, 1024 );
+ dirptr = dirlist;
+ for (i = 0; i < numdirs; i++, dirptr += dirlen+1) {
+ dirlen = strlen(dirptr);
+ strcpy(filename, "scripts/");
+ strcat(filename, dirptr);
+ UI_LoadBotsFromFile(filename);
+ }
+ trap_Print( va( "%i bots parsed\n", ui_numBots ) );
+}
+
+
+/*
+===============
+UI_GetBotInfoByNumber
+===============
+*/
+char *UI_GetBotInfoByNumber( int num ) {
+ if( num < 0 || num >= ui_numBots ) {
+ trap_Print( va( S_COLOR_RED "Invalid bot number: %i\n", num ) );
+ return NULL;
+ }
+ return ui_botInfos[num];
+}
+
+
+/*
+===============
+UI_GetBotInfoByName
+===============
+*/
+char *UI_GetBotInfoByName( const char *name ) {
+ int n;
+ char *value;
+
+ for ( n = 0; n < ui_numBots ; n++ ) {
+ value = Info_ValueForKey( ui_botInfos[n], "name" );
+ if ( !Q_stricmp( value, name ) ) {
+ return ui_botInfos[n];
+ }
+ }
+
+ return NULL;
+}
+
+
+//
+// single player game info
+//
+
+/*
+===============
+UI_GetBestScore
+
+Returns the player's best finish on a given level, 0 if the have not played the level
+===============
+*/
+void UI_GetBestScore( int level, int *score, int *skill ) {
+ int n;
+ int skillScore;
+ int bestScore;
+ int bestScoreSkill;
+ char arenaKey[16];
+ char scores[MAX_INFO_VALUE];
+
+ if( !score || !skill ) {
+ return;
+ }
+
+ if( level < 0 || level > ui_numArenas ) {
+ return;
+ }
+
+ bestScore = 0;
+ bestScoreSkill = 0;
+
+ for( n = 1; n <= 5; n++ ) {
+ trap_Cvar_VariableStringBuffer( va( "g_spScores%i", n ), scores, MAX_INFO_VALUE );
+
+ Com_sprintf( arenaKey, sizeof( arenaKey ), "l%i", level );
+ skillScore = atoi( Info_ValueForKey( scores, arenaKey ) );
+
+ if( skillScore < 1 || skillScore > 8 ) {
+ continue;
+ }
+
+ if( !bestScore || skillScore <= bestScore ) {
+ bestScore = skillScore;
+ bestScoreSkill = n;
+ }
+ }
+
+ *score = bestScore;
+ *skill = bestScoreSkill;
+}
+
+
+/*
+===============
+UI_SetBestScore
+
+Set the player's best finish for a level
+===============
+*/
+void UI_SetBestScore( int level, int score ) {
+ int skill;
+ int oldScore;
+ char arenaKey[16];
+ char scores[MAX_INFO_VALUE];
+
+ // validate score
+ if( score < 1 || score > 8 ) {
+ return;
+ }
+
+ // validate skill
+ skill = (int)trap_Cvar_VariableValue( "g_spSkill" );
+ if( skill < 1 || skill > 5 ) {
+ return;
+ }
+
+ // get scores
+ trap_Cvar_VariableStringBuffer( va( "g_spScores%i", skill ), scores, MAX_INFO_VALUE );
+
+ // see if this is better
+ Com_sprintf( arenaKey, sizeof( arenaKey ), "l%i", level );
+ oldScore = atoi( Info_ValueForKey( scores, arenaKey ) );
+ if( oldScore && oldScore <= score ) {
+ return;
+ }
+
+ // update scores
+ Info_SetValueForKey( scores, arenaKey, va( "%i", score ) );
+ trap_Cvar_Set( va( "g_spScores%i", skill ), scores );
+}
+
+
+/*
+===============
+UI_LogAwardData
+===============
+*/
+void UI_LogAwardData( int award, int data ) {
+ char key[16];
+ char awardData[MAX_INFO_VALUE];
+ int oldValue;
+
+ if( data == 0 ) {
+ return;
+ }
+
+ if( award > AWARD_PERFECT ) {
+ trap_Print( va( S_COLOR_RED "Bad award %i in UI_LogAwardData\n", award ) );
+ return;
+ }
+
+ trap_Cvar_VariableStringBuffer( "g_spAwards", awardData, sizeof(awardData) );
+
+ Com_sprintf( key, sizeof(key), "a%i", award );
+ oldValue = atoi( Info_ValueForKey( awardData, key ) );
+
+ Info_SetValueForKey( awardData, key, va( "%i", oldValue + data ) );
+ trap_Cvar_Set( "g_spAwards", awardData );
+}
+
+
+/*
+===============
+UI_GetAwardLevel
+===============
+*/
+int UI_GetAwardLevel( int award ) {
+ char key[16];
+ char awardData[MAX_INFO_VALUE];
+
+ trap_Cvar_VariableStringBuffer( "g_spAwards", awardData, sizeof(awardData) );
+
+ Com_sprintf( key, sizeof(key), "a%i", award );
+ return atoi( Info_ValueForKey( awardData, key ) );
+}
+
+
+/*
+===============
+UI_TierCompleted
+===============
+*/
+int UI_TierCompleted( int levelWon ) {
+ int level;
+ int n;
+ int tier;
+ int score;
+ int skill;
+ const char *info;
+
+ tier = levelWon / ARENAS_PER_TIER;
+ level = tier * ARENAS_PER_TIER;
+
+ if( tier == UI_GetNumSPTiers() ) {
+ info = UI_GetSpecialArenaInfo( "training" );
+ if( levelWon == atoi( Info_ValueForKey( info, "num" ) ) ) {
+ return 0;
+ }
+ info = UI_GetSpecialArenaInfo( "final" );
+ if( !info || levelWon == atoi( Info_ValueForKey( info, "num" ) ) ) {
+ return tier + 1;
+ }
+ return -1;
+ }
+
+ for( n = 0; n < ARENAS_PER_TIER; n++, level++ ) {
+ UI_GetBestScore( level, &score, &skill );
+ if ( score != 1 ) {
+ return -1;
+ }
+ }
+ return tier + 1;
+}
+
+
+/*
+===============
+UI_ShowTierVideo
+===============
+*/
+qboolean UI_ShowTierVideo( int tier ) {
+ char key[16];
+ char videos[MAX_INFO_VALUE];
+
+ if( tier <= 0 ) {
+ return qfalse;
+ }
+
+ trap_Cvar_VariableStringBuffer( "g_spVideos", videos, sizeof(videos) );
+
+ Com_sprintf( key, sizeof(key), "tier%i", tier );
+ if( atoi( Info_ValueForKey( videos, key ) ) ) {
+ return qfalse;
+ }
+
+ Info_SetValueForKey( videos, key, va( "%i", 1 ) );
+ trap_Cvar_Set( "g_spVideos", videos );
+
+ return qtrue;
+}
+
+
+/*
+===============
+UI_CanShowTierVideo
+===============
+*/
+qboolean UI_CanShowTierVideo( int tier ) {
+ char key[16];
+ char videos[MAX_INFO_VALUE];
+
+ if( !tier ) {
+ return qfalse;
+ }
+
+ if( uis.demoversion && tier != 8 ) {
+ return qfalse;
+ }
+
+ trap_Cvar_VariableStringBuffer( "g_spVideos", videos, sizeof(videos) );
+
+ Com_sprintf( key, sizeof(key), "tier%i", tier );
+ if( atoi( Info_ValueForKey( videos, key ) ) ) {
+ return qtrue;
+ }
+
+ return qfalse;
+}
+
+
+/*
+===============
+UI_GetCurrentGame
+
+Returns the next level the player has not won
+===============
+*/
+int UI_GetCurrentGame( void ) {
+ int level;
+ int rank;
+ int skill;
+ const char *info;
+
+ info = UI_GetSpecialArenaInfo( "training" );
+ if( info ) {
+ level = atoi( Info_ValueForKey( info, "num" ) );
+ UI_GetBestScore( level, &rank, &skill );
+ if ( !rank || rank > 1 ) {
+ return level;
+ }
+ }
+
+ for( level = 0; level < ui_numSinglePlayerArenas; level++ ) {
+ UI_GetBestScore( level, &rank, &skill );
+ if ( !rank || rank > 1 ) {
+ return level;
+ }
+ }
+
+ info = UI_GetSpecialArenaInfo( "final" );
+ if( !info ) {
+ return -1;
+ }
+ return atoi( Info_ValueForKey( info, "num" ) );
+}
+
+
+/*
+===============
+UI_NewGame
+
+Clears the scores and sets the difficutly level
+===============
+*/
+void UI_NewGame( void ) {
+ trap_Cvar_Set( "g_spScores1", "" );
+ trap_Cvar_Set( "g_spScores2", "" );
+ trap_Cvar_Set( "g_spScores3", "" );
+ trap_Cvar_Set( "g_spScores4", "" );
+ trap_Cvar_Set( "g_spScores5", "" );
+ trap_Cvar_Set( "g_spAwards", "" );
+ trap_Cvar_Set( "g_spVideos", "" );
+}
+
+
+/*
+===============
+UI_GetNumArenas
+===============
+*/
+int UI_GetNumArenas( void ) {
+ return ui_numArenas;
+}
+
+
+/*
+===============
+UI_GetNumSPArenas
+===============
+*/
+int UI_GetNumSPArenas( void ) {
+ return ui_numSinglePlayerArenas;
+}
+
+
+/*
+===============
+UI_GetNumSPTiers
+===============
+*/
+int UI_GetNumSPTiers( void ) {
+ return ui_numSinglePlayerArenas / ARENAS_PER_TIER;
+}
+
+
+/*
+===============
+UI_GetNumBots
+===============
+*/
+int UI_GetNumBots( void ) {
+ return ui_numBots;
+}
+
+
+/*
+===============
+UI_SPUnlock_f
+===============
+*/
+void UI_SPUnlock_f( void ) {
+ char arenaKey[16];
+ char scores[MAX_INFO_VALUE];
+ int level;
+ int tier;
+
+ // get scores for skill 1
+ trap_Cvar_VariableStringBuffer( "g_spScores1", scores, MAX_INFO_VALUE );
+
+ // update scores
+ for( level = 0; level < ui_numSinglePlayerArenas + ui_numSpecialSinglePlayerArenas; level++ ) {
+ Com_sprintf( arenaKey, sizeof( arenaKey ), "l%i", level );
+ Info_SetValueForKey( scores, arenaKey, "1" );
+ }
+ trap_Cvar_Set( "g_spScores1", scores );
+
+ // unlock cinematics
+ for( tier = 1; tier <= 8; tier++ ) {
+ UI_ShowTierVideo( tier );
+ }
+
+ trap_Print( "All levels unlocked at skill level 1\n" );
+
+ UI_SPLevelMenu_ReInit();
+}
+
+
+/*
+===============
+UI_SPUnlockMedals_f
+===============
+*/
+void UI_SPUnlockMedals_f( void ) {
+ int n;
+ char key[16];
+ char awardData[MAX_INFO_VALUE];
+
+ trap_Cvar_VariableStringBuffer( "g_spAwards", awardData, MAX_INFO_VALUE );
+
+ for( n = 0; n < 6; n++ ) {
+ Com_sprintf( key, sizeof(key), "a%i", n );
+ Info_SetValueForKey( awardData, key, "100" );
+ }
+
+ trap_Cvar_Set( "g_spAwards", awardData );
+
+ trap_Print( "All levels unlocked at 100\n" );
+}
+
+
+/*
+===============
+UI_InitGameinfo
+===============
+*/
+void UI_InitGameinfo( void ) {
+
+ UI_InitMemory();
+ UI_LoadArenas();
+ UI_LoadBots();
+
+ if( (trap_Cvar_VariableValue( "fs_restrict" )) || (ui_numSpecialSinglePlayerArenas == 0 && ui_numSinglePlayerArenas == 4) ) {
+ uis.demoversion = qtrue;
+ }
+ else {
+ uis.demoversion = qfalse;
+ }
+}
diff --git a/code/q3_ui/ui_ingame.c b/code/q3_ui/ui_ingame.c
new file mode 100755
index 0000000..c5c6b06
--- /dev/null
+++ b/code/q3_ui/ui_ingame.c
@@ -0,0 +1,349 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*
+=======================================================================
+
+INGAME MENU
+
+=======================================================================
+*/
+
+
+#include "ui_local.h"
+
+
+#define INGAME_FRAME "menu/art/addbotframe"
+//#define INGAME_FRAME "menu/art/cut_frame"
+#define INGAME_MENU_VERTICAL_SPACING 28
+
+#define ID_TEAM 10
+#define ID_ADDBOTS 11
+#define ID_REMOVEBOTS 12
+#define ID_SETUP 13
+#define ID_SERVERINFO 14
+#define ID_LEAVEARENA 15
+#define ID_RESTART 16
+#define ID_QUIT 17
+#define ID_RESUME 18
+#define ID_TEAMORDERS 19
+
+
+typedef struct {
+ menuframework_s menu;
+
+ menubitmap_s frame;
+ menutext_s team;
+ menutext_s setup;
+ menutext_s server;
+ menutext_s leave;
+ menutext_s restart;
+ menutext_s addbots;
+ menutext_s removebots;
+ menutext_s teamorders;
+ menutext_s quit;
+ menutext_s resume;
+} ingamemenu_t;
+
+static ingamemenu_t s_ingame;
+
+
+/*
+=================
+InGame_RestartAction
+=================
+*/
+static void InGame_RestartAction( qboolean result ) {
+ if( !result ) {
+ return;
+ }
+
+ UI_PopMenu();
+ trap_Cmd_ExecuteText( EXEC_APPEND, "map_restart 0\n" );
+}
+
+
+/*
+=================
+InGame_QuitAction
+=================
+*/
+static void InGame_QuitAction( qboolean result ) {
+ if( !result ) {
+ return;
+ }
+ UI_PopMenu();
+ UI_CreditMenu();
+}
+
+
+/*
+=================
+InGame_Event
+=================
+*/
+void InGame_Event( void *ptr, int notification ) {
+ if( notification != QM_ACTIVATED ) {
+ return;
+ }
+
+ switch( ((menucommon_s*)ptr)->id ) {
+ case ID_TEAM:
+ UI_TeamMainMenu();
+ break;
+
+ case ID_SETUP:
+ UI_SetupMenu();
+ break;
+
+ case ID_LEAVEARENA:
+ trap_Cmd_ExecuteText( EXEC_APPEND, "disconnect\n" );
+ break;
+
+ case ID_RESTART:
+ UI_ConfirmMenu( "RESTART ARENA?", (voidfunc_f)NULL, InGame_RestartAction );
+ break;
+
+ case ID_QUIT:
+ UI_ConfirmMenu( "EXIT GAME?", (voidfunc_f)NULL, InGame_QuitAction );
+ break;
+
+ case ID_SERVERINFO:
+ UI_ServerInfoMenu();
+ break;
+
+ case ID_ADDBOTS:
+ UI_AddBotsMenu();
+ break;
+
+ case ID_REMOVEBOTS:
+ UI_RemoveBotsMenu();
+ break;
+
+ case ID_TEAMORDERS:
+ UI_TeamOrdersMenu();
+ break;
+
+ case ID_RESUME:
+ UI_PopMenu();
+ break;
+ }
+}
+
+
+/*
+=================
+InGame_MenuInit
+=================
+*/
+void InGame_MenuInit( void ) {
+ int y;
+ uiClientState_t cs;
+ char info[MAX_INFO_STRING];
+ int team;
+
+ memset( &s_ingame, 0 ,sizeof(ingamemenu_t) );
+
+ InGame_Cache();
+
+ s_ingame.menu.wrapAround = qtrue;
+ s_ingame.menu.fullscreen = qfalse;
+
+ s_ingame.frame.generic.type = MTYPE_BITMAP;
+ s_ingame.frame.generic.flags = QMF_INACTIVE;
+ s_ingame.frame.generic.name = INGAME_FRAME;
+ s_ingame.frame.generic.x = 320-233;//142;
+ s_ingame.frame.generic.y = 240-166;//118;
+ s_ingame.frame.width = 466;//359;
+ s_ingame.frame.height = 332;//256;
+
+ //y = 96;
+ y = 88;
+ s_ingame.team.generic.type = MTYPE_PTEXT;
+ s_ingame.team.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_ingame.team.generic.x = 320;
+ s_ingame.team.generic.y = y;
+ s_ingame.team.generic.id = ID_TEAM;
+ s_ingame.team.generic.callback = InGame_Event;
+ s_ingame.team.string = "START";
+ s_ingame.team.color = color_red;
+ s_ingame.team.style = UI_CENTER|UI_SMALLFONT;
+
+ y += INGAME_MENU_VERTICAL_SPACING;
+ s_ingame.addbots.generic.type = MTYPE_PTEXT;
+ s_ingame.addbots.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_ingame.addbots.generic.x = 320;
+ s_ingame.addbots.generic.y = y;
+ s_ingame.addbots.generic.id = ID_ADDBOTS;
+ s_ingame.addbots.generic.callback = InGame_Event;
+ s_ingame.addbots.string = "ADD BOTS";
+ s_ingame.addbots.color = color_red;
+ s_ingame.addbots.style = UI_CENTER|UI_SMALLFONT;
+ if( !trap_Cvar_VariableValue( "sv_running" ) || !trap_Cvar_VariableValue( "bot_enable" ) || (trap_Cvar_VariableValue( "g_gametype" ) == GT_SINGLE_PLAYER)) {
+ s_ingame.addbots.generic.flags |= QMF_GRAYED;
+ }
+
+ y += INGAME_MENU_VERTICAL_SPACING;
+ s_ingame.removebots.generic.type = MTYPE_PTEXT;
+ s_ingame.removebots.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_ingame.removebots.generic.x = 320;
+ s_ingame.removebots.generic.y = y;
+ s_ingame.removebots.generic.id = ID_REMOVEBOTS;
+ s_ingame.removebots.generic.callback = InGame_Event;
+ s_ingame.removebots.string = "REMOVE BOTS";
+ s_ingame.removebots.color = color_red;
+ s_ingame.removebots.style = UI_CENTER|UI_SMALLFONT;
+ if( !trap_Cvar_VariableValue( "sv_running" ) || !trap_Cvar_VariableValue( "bot_enable" ) || (trap_Cvar_VariableValue( "g_gametype" ) == GT_SINGLE_PLAYER)) {
+ s_ingame.removebots.generic.flags |= QMF_GRAYED;
+ }
+
+ y += INGAME_MENU_VERTICAL_SPACING;
+ s_ingame.teamorders.generic.type = MTYPE_PTEXT;
+ s_ingame.teamorders.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_ingame.teamorders.generic.x = 320;
+ s_ingame.teamorders.generic.y = y;
+ s_ingame.teamorders.generic.id = ID_TEAMORDERS;
+ s_ingame.teamorders.generic.callback = InGame_Event;
+ s_ingame.teamorders.string = "TEAM ORDERS";
+ s_ingame.teamorders.color = color_red;
+ s_ingame.teamorders.style = UI_CENTER|UI_SMALLFONT;
+ if( !(trap_Cvar_VariableValue( "g_gametype" ) >= GT_TEAM) ) {
+ s_ingame.teamorders.generic.flags |= QMF_GRAYED;
+ }
+ else {
+ trap_GetClientState( &cs );
+ trap_GetConfigString( CS_PLAYERS + cs.clientNum, info, MAX_INFO_STRING );
+ team = atoi( Info_ValueForKey( info, "t" ) );
+ if( team == TEAM_SPECTATOR ) {
+ s_ingame.teamorders.generic.flags |= QMF_GRAYED;
+ }
+ }
+
+ y += INGAME_MENU_VERTICAL_SPACING;
+ s_ingame.setup.generic.type = MTYPE_PTEXT;
+ s_ingame.setup.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_ingame.setup.generic.x = 320;
+ s_ingame.setup.generic.y = y;
+ s_ingame.setup.generic.id = ID_SETUP;
+ s_ingame.setup.generic.callback = InGame_Event;
+ s_ingame.setup.string = "SETUP";
+ s_ingame.setup.color = color_red;
+ s_ingame.setup.style = UI_CENTER|UI_SMALLFONT;
+
+ y += INGAME_MENU_VERTICAL_SPACING;
+ s_ingame.server.generic.type = MTYPE_PTEXT;
+ s_ingame.server.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_ingame.server.generic.x = 320;
+ s_ingame.server.generic.y = y;
+ s_ingame.server.generic.id = ID_SERVERINFO;
+ s_ingame.server.generic.callback = InGame_Event;
+ s_ingame.server.string = "SERVER INFO";
+ s_ingame.server.color = color_red;
+ s_ingame.server.style = UI_CENTER|UI_SMALLFONT;
+
+ y += INGAME_MENU_VERTICAL_SPACING;
+ s_ingame.restart.generic.type = MTYPE_PTEXT;
+ s_ingame.restart.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_ingame.restart.generic.x = 320;
+ s_ingame.restart.generic.y = y;
+ s_ingame.restart.generic.id = ID_RESTART;
+ s_ingame.restart.generic.callback = InGame_Event;
+ s_ingame.restart.string = "RESTART ARENA";
+ s_ingame.restart.color = color_red;
+ s_ingame.restart.style = UI_CENTER|UI_SMALLFONT;
+ if( !trap_Cvar_VariableValue( "sv_running" ) ) {
+ s_ingame.restart.generic.flags |= QMF_GRAYED;
+ }
+
+ y += INGAME_MENU_VERTICAL_SPACING;
+ s_ingame.resume.generic.type = MTYPE_PTEXT;
+ s_ingame.resume.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_ingame.resume.generic.x = 320;
+ s_ingame.resume.generic.y = y;
+ s_ingame.resume.generic.id = ID_RESUME;
+ s_ingame.resume.generic.callback = InGame_Event;
+ s_ingame.resume.string = "RESUME GAME";
+ s_ingame.resume.color = color_red;
+ s_ingame.resume.style = UI_CENTER|UI_SMALLFONT;
+
+ y += INGAME_MENU_VERTICAL_SPACING;
+ s_ingame.leave.generic.type = MTYPE_PTEXT;
+ s_ingame.leave.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_ingame.leave.generic.x = 320;
+ s_ingame.leave.generic.y = y;
+ s_ingame.leave.generic.id = ID_LEAVEARENA;
+ s_ingame.leave.generic.callback = InGame_Event;
+ s_ingame.leave.string = "LEAVE ARENA";
+ s_ingame.leave.color = color_red;
+ s_ingame.leave.style = UI_CENTER|UI_SMALLFONT;
+
+ y += INGAME_MENU_VERTICAL_SPACING;
+ s_ingame.quit.generic.type = MTYPE_PTEXT;
+ s_ingame.quit.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_ingame.quit.generic.x = 320;
+ s_ingame.quit.generic.y = y;
+ s_ingame.quit.generic.id = ID_QUIT;
+ s_ingame.quit.generic.callback = InGame_Event;
+ s_ingame.quit.string = "EXIT GAME";
+ s_ingame.quit.color = color_red;
+ s_ingame.quit.style = UI_CENTER|UI_SMALLFONT;
+
+ Menu_AddItem( &s_ingame.menu, &s_ingame.frame );
+ Menu_AddItem( &s_ingame.menu, &s_ingame.team );
+ Menu_AddItem( &s_ingame.menu, &s_ingame.addbots );
+ Menu_AddItem( &s_ingame.menu, &s_ingame.removebots );
+ Menu_AddItem( &s_ingame.menu, &s_ingame.teamorders );
+ Menu_AddItem( &s_ingame.menu, &s_ingame.setup );
+ Menu_AddItem( &s_ingame.menu, &s_ingame.server );
+ Menu_AddItem( &s_ingame.menu, &s_ingame.restart );
+ Menu_AddItem( &s_ingame.menu, &s_ingame.resume );
+ Menu_AddItem( &s_ingame.menu, &s_ingame.leave );
+ Menu_AddItem( &s_ingame.menu, &s_ingame.quit );
+}
+
+
+/*
+=================
+InGame_Cache
+=================
+*/
+void InGame_Cache( void ) {
+ trap_R_RegisterShaderNoMip( INGAME_FRAME );
+}
+
+
+/*
+=================
+UI_InGameMenu
+=================
+*/
+void UI_InGameMenu( void ) {
+ // force as top level menu
+ uis.menusp = 0;
+
+ // set menu cursor to a nice location
+ uis.cursorx = 319;
+ uis.cursory = 80;
+
+ InGame_MenuInit();
+ UI_PushMenu( &s_ingame.menu );
+}
diff --git a/code/q3_ui/ui_loadconfig.c b/code/q3_ui/ui_loadconfig.c
new file mode 100755
index 0000000..24aff9f
--- /dev/null
+++ b/code/q3_ui/ui_loadconfig.c
@@ -0,0 +1,274 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*
+=============================================================================
+
+LOAD CONFIG MENU
+
+=============================================================================
+*/
+
+#include "ui_local.h"
+
+
+#define ART_BACK0 "menu/art/back_0"
+#define ART_BACK1 "menu/art/back_1"
+#define ART_FIGHT0 "menu/art/load_0"
+#define ART_FIGHT1 "menu/art/load_1"
+#define ART_FRAMEL "menu/art/frame2_l"
+#define ART_FRAMER "menu/art/frame1_r"
+#define ART_ARROWS "menu/art/arrows_horz_0"
+#define ART_ARROWLEFT "menu/art/arrows_horz_left"
+#define ART_ARROWRIGHT "menu/art/arrows_horz_right"
+
+#define MAX_CONFIGS 128
+#define NAMEBUFSIZE ( MAX_CONFIGS * 16 )
+
+#define ID_BACK 10
+#define ID_GO 11
+#define ID_LIST 12
+#define ID_LEFT 13
+#define ID_RIGHT 14
+
+#define ARROWS_WIDTH 128
+#define ARROWS_HEIGHT 48
+
+
+typedef struct {
+ menuframework_s menu;
+
+ menutext_s banner;
+ menubitmap_s framel;
+ menubitmap_s framer;
+
+ menulist_s list;
+
+ menubitmap_s arrows;
+ menubitmap_s left;
+ menubitmap_s right;
+ menubitmap_s back;
+ menubitmap_s go;
+
+ char names[NAMEBUFSIZE];
+ char* configlist[MAX_CONFIGS];
+} configs_t;
+
+static configs_t s_configs;
+
+
+/*
+===============
+LoadConfig_MenuEvent
+===============
+*/
+static void LoadConfig_MenuEvent( void *ptr, int event ) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+
+ switch ( ((menucommon_s*)ptr)->id ) {
+ case ID_GO:
+ trap_Cmd_ExecuteText( EXEC_APPEND, va( "exec %s\n", s_configs.list.itemnames[s_configs.list.curvalue] ) );
+ UI_PopMenu();
+ break;
+
+ case ID_BACK:
+ UI_PopMenu();
+ break;
+
+ case ID_LEFT:
+ ScrollList_Key( &s_configs.list, K_LEFTARROW );
+ break;
+
+ case ID_RIGHT:
+ ScrollList_Key( &s_configs.list, K_RIGHTARROW );
+ break;
+ }
+}
+
+
+/*
+===============
+LoadConfig_MenuInit
+===============
+*/
+static void LoadConfig_MenuInit( void ) {
+ int i;
+ int len;
+ char *configname;
+
+ UI_LoadConfig_Cache();
+
+ memset( &s_configs, 0 ,sizeof(configs_t) );
+ s_configs.menu.wrapAround = qtrue;
+ s_configs.menu.fullscreen = qtrue;
+
+ s_configs.banner.generic.type = MTYPE_BTEXT;
+ s_configs.banner.generic.x = 320;
+ s_configs.banner.generic.y = 16;
+ s_configs.banner.string = "LOAD CONFIG";
+ s_configs.banner.color = color_white;
+ s_configs.banner.style = UI_CENTER;
+
+ s_configs.framel.generic.type = MTYPE_BITMAP;
+ s_configs.framel.generic.name = ART_FRAMEL;
+ s_configs.framel.generic.flags = QMF_INACTIVE;
+ s_configs.framel.generic.x = 0;
+ s_configs.framel.generic.y = 78;
+ s_configs.framel.width = 256;
+ s_configs.framel.height = 329;
+
+ s_configs.framer.generic.type = MTYPE_BITMAP;
+ s_configs.framer.generic.name = ART_FRAMER;
+ s_configs.framer.generic.flags = QMF_INACTIVE;
+ s_configs.framer.generic.x = 376;
+ s_configs.framer.generic.y = 76;
+ s_configs.framer.width = 256;
+ s_configs.framer.height = 334;
+
+ s_configs.arrows.generic.type = MTYPE_BITMAP;
+ s_configs.arrows.generic.name = ART_ARROWS;
+ s_configs.arrows.generic.flags = QMF_INACTIVE;
+ s_configs.arrows.generic.x = 320-ARROWS_WIDTH/2;
+ s_configs.arrows.generic.y = 400;
+ s_configs.arrows.width = ARROWS_WIDTH;
+ s_configs.arrows.height = ARROWS_HEIGHT;
+
+ s_configs.left.generic.type = MTYPE_BITMAP;
+ s_configs.left.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_MOUSEONLY;
+ s_configs.left.generic.x = 320-ARROWS_WIDTH/2;
+ s_configs.left.generic.y = 400;
+ s_configs.left.generic.id = ID_LEFT;
+ s_configs.left.generic.callback = LoadConfig_MenuEvent;
+ s_configs.left.width = ARROWS_WIDTH/2;
+ s_configs.left.height = ARROWS_HEIGHT;
+ s_configs.left.focuspic = ART_ARROWLEFT;
+
+ s_configs.right.generic.type = MTYPE_BITMAP;
+ s_configs.right.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_MOUSEONLY;
+ s_configs.right.generic.x = 320;
+ s_configs.right.generic.y = 400;
+ s_configs.right.generic.id = ID_RIGHT;
+ s_configs.right.generic.callback = LoadConfig_MenuEvent;
+ s_configs.right.width = ARROWS_WIDTH/2;
+ s_configs.right.height = ARROWS_HEIGHT;
+ s_configs.right.focuspic = ART_ARROWRIGHT;
+
+ s_configs.back.generic.type = MTYPE_BITMAP;
+ s_configs.back.generic.name = ART_BACK0;
+ s_configs.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_configs.back.generic.id = ID_BACK;
+ s_configs.back.generic.callback = LoadConfig_MenuEvent;
+ s_configs.back.generic.x = 0;
+ s_configs.back.generic.y = 480-64;
+ s_configs.back.width = 128;
+ s_configs.back.height = 64;
+ s_configs.back.focuspic = ART_BACK1;
+
+ s_configs.go.generic.type = MTYPE_BITMAP;
+ s_configs.go.generic.name = ART_FIGHT0;
+ s_configs.go.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_configs.go.generic.id = ID_GO;
+ s_configs.go.generic.callback = LoadConfig_MenuEvent;
+ s_configs.go.generic.x = 640;
+ s_configs.go.generic.y = 480-64;
+ s_configs.go.width = 128;
+ s_configs.go.height = 64;
+ s_configs.go.focuspic = ART_FIGHT1;
+
+ // scan for configs
+ s_configs.list.generic.type = MTYPE_SCROLLLIST;
+ s_configs.list.generic.flags = QMF_PULSEIFFOCUS;
+ s_configs.list.generic.callback = LoadConfig_MenuEvent;
+ s_configs.list.generic.id = ID_LIST;
+ s_configs.list.generic.x = 118;
+ s_configs.list.generic.y = 130;
+ s_configs.list.width = 16;
+ s_configs.list.height = 14;
+ s_configs.list.numitems = trap_FS_GetFileList( "", "cfg", s_configs.names, NAMEBUFSIZE );
+ s_configs.list.itemnames = (const char **)s_configs.configlist;
+ s_configs.list.columns = 3;
+
+ if (!s_configs.list.numitems) {
+ strcpy(s_configs.names,"No Files Found.");
+ s_configs.list.numitems = 1;
+
+ //degenerate case, not selectable
+ s_configs.go.generic.flags |= (QMF_INACTIVE|QMF_HIDDEN);
+ }
+ else if (s_configs.list.numitems > MAX_CONFIGS)
+ s_configs.list.numitems = MAX_CONFIGS;
+
+ configname = s_configs.names;
+ for ( i = 0; i < s_configs.list.numitems; i++ ) {
+ s_configs.list.itemnames[i] = configname;
+
+ // strip extension
+ len = strlen( configname );
+ if (!Q_stricmp(configname + len - 4,".cfg"))
+ configname[len-4] = '\0';
+
+ Q_strupr(configname);
+
+ configname += len + 1;
+ }
+
+ Menu_AddItem( &s_configs.menu, &s_configs.banner );
+ Menu_AddItem( &s_configs.menu, &s_configs.framel );
+ Menu_AddItem( &s_configs.menu, &s_configs.framer );
+ Menu_AddItem( &s_configs.menu, &s_configs.list );
+ Menu_AddItem( &s_configs.menu, &s_configs.arrows );
+ Menu_AddItem( &s_configs.menu, &s_configs.left );
+ Menu_AddItem( &s_configs.menu, &s_configs.right );
+ Menu_AddItem( &s_configs.menu, &s_configs.back );
+ Menu_AddItem( &s_configs.menu, &s_configs.go );
+}
+
+/*
+=================
+UI_LoadConfig_Cache
+=================
+*/
+void UI_LoadConfig_Cache( void ) {
+ trap_R_RegisterShaderNoMip( ART_BACK0 );
+ trap_R_RegisterShaderNoMip( ART_BACK1 );
+ trap_R_RegisterShaderNoMip( ART_FIGHT0 );
+ trap_R_RegisterShaderNoMip( ART_FIGHT1 );
+ trap_R_RegisterShaderNoMip( ART_FRAMEL );
+ trap_R_RegisterShaderNoMip( ART_FRAMER );
+ trap_R_RegisterShaderNoMip( ART_ARROWS );
+ trap_R_RegisterShaderNoMip( ART_ARROWLEFT );
+ trap_R_RegisterShaderNoMip( ART_ARROWRIGHT );
+}
+
+
+/*
+===============
+UI_LoadConfigMenu
+===============
+*/
+void UI_LoadConfigMenu( void ) {
+ LoadConfig_MenuInit();
+ UI_PushMenu( &s_configs.menu );
+}
+
diff --git a/code/q3_ui/ui_local.h b/code/q3_ui/ui_local.h
new file mode 100755
index 0000000..71ea0de
--- /dev/null
+++ b/code/q3_ui/ui_local.h
@@ -0,0 +1,800 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#ifndef __UI_LOCAL_H__
+#define __UI_LOCAL_H__
+
+#include "../game/q_shared.h"
+#include "../cgame/tr_types.h"
+//NOTE: include the ui_public.h from the new UI
+#include "../ui/ui_public.h" // bk001205 - yes, do have to use this
+//redefine to old API version
+#undef UI_API_VERSION
+#define UI_API_VERSION 4
+#include "keycodes.h"
+#include "../game/bg_public.h"
+
+typedef void (*voidfunc_f)(void);
+
+extern vmCvar_t ui_ffa_fraglimit;
+extern vmCvar_t ui_ffa_timelimit;
+
+extern vmCvar_t ui_tourney_fraglimit;
+extern vmCvar_t ui_tourney_timelimit;
+
+extern vmCvar_t ui_team_fraglimit;
+extern vmCvar_t ui_team_timelimit;
+extern vmCvar_t ui_team_friendly;
+
+extern vmCvar_t ui_ctf_capturelimit;
+extern vmCvar_t ui_ctf_timelimit;
+extern vmCvar_t ui_ctf_friendly;
+
+extern vmCvar_t ui_arenasFile;
+extern vmCvar_t ui_botsFile;
+extern vmCvar_t ui_spScores1;
+extern vmCvar_t ui_spScores2;
+extern vmCvar_t ui_spScores3;
+extern vmCvar_t ui_spScores4;
+extern vmCvar_t ui_spScores5;
+extern vmCvar_t ui_spAwards;
+extern vmCvar_t ui_spVideos;
+extern vmCvar_t ui_spSkill;
+
+extern vmCvar_t ui_spSelection;
+
+extern vmCvar_t ui_browserMaster;
+extern vmCvar_t ui_browserGameType;
+extern vmCvar_t ui_browserSortKey;
+extern vmCvar_t ui_browserShowFull;
+extern vmCvar_t ui_browserShowEmpty;
+
+extern vmCvar_t ui_brassTime;
+extern vmCvar_t ui_drawCrosshair;
+extern vmCvar_t ui_drawCrosshairNames;
+extern vmCvar_t ui_marks;
+
+extern vmCvar_t ui_server1;
+extern vmCvar_t ui_server2;
+extern vmCvar_t ui_server3;
+extern vmCvar_t ui_server4;
+extern vmCvar_t ui_server5;
+extern vmCvar_t ui_server6;
+extern vmCvar_t ui_server7;
+extern vmCvar_t ui_server8;
+extern vmCvar_t ui_server9;
+extern vmCvar_t ui_server10;
+extern vmCvar_t ui_server11;
+extern vmCvar_t ui_server12;
+extern vmCvar_t ui_server13;
+extern vmCvar_t ui_server14;
+extern vmCvar_t ui_server15;
+extern vmCvar_t ui_server16;
+
+extern vmCvar_t ui_cdkey;
+extern vmCvar_t ui_cdkeychecked;
+
+
+//
+// ui_qmenu.c
+//
+
+#define RCOLUMN_OFFSET ( BIGCHAR_WIDTH )
+#define LCOLUMN_OFFSET (-BIGCHAR_WIDTH )
+
+#define SLIDER_RANGE 10
+#define MAX_EDIT_LINE 256
+
+#define MAX_MENUDEPTH 8
+#define MAX_MENUITEMS 64
+
+#define MTYPE_NULL 0
+#define MTYPE_SLIDER 1
+#define MTYPE_ACTION 2
+#define MTYPE_SPINCONTROL 3
+#define MTYPE_FIELD 4
+#define MTYPE_RADIOBUTTON 5
+#define MTYPE_BITMAP 6
+#define MTYPE_TEXT 7
+#define MTYPE_SCROLLLIST 8
+#define MTYPE_PTEXT 9
+#define MTYPE_BTEXT 10
+
+#define QMF_BLINK 0x00000001
+#define QMF_SMALLFONT 0x00000002
+#define QMF_LEFT_JUSTIFY 0x00000004
+#define QMF_CENTER_JUSTIFY 0x00000008
+#define QMF_RIGHT_JUSTIFY 0x00000010
+#define QMF_NUMBERSONLY 0x00000020 // edit field is only numbers
+#define QMF_HIGHLIGHT 0x00000040
+#define QMF_HIGHLIGHT_IF_FOCUS 0x00000080 // steady focus
+#define QMF_PULSEIFFOCUS 0x00000100 // pulse if focus
+#define QMF_HASMOUSEFOCUS 0x00000200
+#define QMF_NOONOFFTEXT 0x00000400
+#define QMF_MOUSEONLY 0x00000800 // only mouse input allowed
+#define QMF_HIDDEN 0x00001000 // skips drawing
+#define QMF_GRAYED 0x00002000 // grays and disables
+#define QMF_INACTIVE 0x00004000 // disables any input
+#define QMF_NODEFAULTINIT 0x00008000 // skip default initialization
+#define QMF_OWNERDRAW 0x00010000
+#define QMF_PULSE 0x00020000
+#define QMF_LOWERCASE 0x00040000 // edit field is all lower case
+#define QMF_UPPERCASE 0x00080000 // edit field is all upper case
+#define QMF_SILENT 0x00100000
+
+// callback notifications
+#define QM_GOTFOCUS 1
+#define QM_LOSTFOCUS 2
+#define QM_ACTIVATED 3
+
+typedef struct _tag_menuframework
+{
+ int cursor;
+ int cursor_prev;
+
+ int nitems;
+ void *items[MAX_MENUITEMS];
+
+ void (*draw) (void);
+ sfxHandle_t (*key) (int key);
+
+ qboolean wrapAround;
+ qboolean fullscreen;
+ qboolean showlogo;
+} menuframework_s;
+
+typedef struct
+{
+ int type;
+ const char *name;
+ int id;
+ int x, y;
+ int left;
+ int top;
+ int right;
+ int bottom;
+ menuframework_s *parent;
+ int menuPosition;
+ unsigned flags;
+
+ void (*callback)( void *self, int event );
+ void (*statusbar)( void *self );
+ void (*ownerdraw)( void *self );
+} menucommon_s;
+
+typedef struct {
+ int cursor;
+ int scroll;
+ int widthInChars;
+ char buffer[MAX_EDIT_LINE];
+ int maxchars;
+} mfield_t;
+
+typedef struct
+{
+ menucommon_s generic;
+ mfield_t field;
+} menufield_s;
+
+typedef struct
+{
+ menucommon_s generic;
+
+ float minvalue;
+ float maxvalue;
+ float curvalue;
+
+ float range;
+} menuslider_s;
+
+typedef struct
+{
+ menucommon_s generic;
+
+ int oldvalue;
+ int curvalue;
+ int numitems;
+ int top;
+
+ const char **itemnames;
+
+ int width;
+ int height;
+ int columns;
+ int seperation;
+} menulist_s;
+
+typedef struct
+{
+ menucommon_s generic;
+} menuaction_s;
+
+typedef struct
+{
+ menucommon_s generic;
+ int curvalue;
+} menuradiobutton_s;
+
+typedef struct
+{
+ menucommon_s generic;
+ char* focuspic;
+ char* errorpic;
+ qhandle_t shader;
+ qhandle_t focusshader;
+ int width;
+ int height;
+ float* focuscolor;
+} menubitmap_s;
+
+typedef struct
+{
+ menucommon_s generic;
+ char* string;
+ int style;
+ float* color;
+} menutext_s;
+
+extern void Menu_Cache( void );
+extern void Menu_Focus( menucommon_s *m );
+extern void Menu_AddItem( menuframework_s *menu, void *item );
+extern void Menu_AdjustCursor( menuframework_s *menu, int dir );
+extern void Menu_Draw( menuframework_s *menu );
+extern void *Menu_ItemAtCursor( menuframework_s *m );
+extern sfxHandle_t Menu_ActivateItem( menuframework_s *s, menucommon_s* item );
+extern void Menu_SetCursor( menuframework_s *s, int cursor );
+extern void Menu_SetCursorToItem( menuframework_s *m, void* ptr );
+extern sfxHandle_t Menu_DefaultKey( menuframework_s *s, int key );
+extern void Bitmap_Init( menubitmap_s *b );
+extern void Bitmap_Draw( menubitmap_s *b );
+extern void ScrollList_Draw( menulist_s *l );
+extern sfxHandle_t ScrollList_Key( menulist_s *l, int key );
+extern sfxHandle_t menu_in_sound;
+extern sfxHandle_t menu_move_sound;
+extern sfxHandle_t menu_out_sound;
+extern sfxHandle_t menu_buzz_sound;
+extern sfxHandle_t menu_null_sound;
+extern sfxHandle_t weaponChangeSound;
+extern vec4_t menu_text_color;
+extern vec4_t menu_grayed_color;
+extern vec4_t menu_dark_color;
+extern vec4_t menu_highlight_color;
+extern vec4_t menu_red_color;
+extern vec4_t menu_black_color;
+extern vec4_t menu_dim_color;
+extern vec4_t color_black;
+extern vec4_t color_white;
+extern vec4_t color_yellow;
+extern vec4_t color_blue;
+extern vec4_t color_orange;
+extern vec4_t color_red;
+extern vec4_t color_dim;
+extern vec4_t name_color;
+extern vec4_t list_color;
+extern vec4_t listbar_color;
+extern vec4_t text_color_disabled;
+extern vec4_t text_color_normal;
+extern vec4_t text_color_highlight;
+
+extern char *ui_medalNames[];
+extern char *ui_medalPicNames[];
+extern char *ui_medalSounds[];
+
+//
+// ui_mfield.c
+//
+extern void MField_Clear( mfield_t *edit );
+extern void MField_KeyDownEvent( mfield_t *edit, int key );
+extern void MField_CharEvent( mfield_t *edit, int ch );
+extern void MField_Draw( mfield_t *edit, int x, int y, int style, vec4_t color );
+extern void MenuField_Init( menufield_s* m );
+extern void MenuField_Draw( menufield_s *f );
+extern sfxHandle_t MenuField_Key( menufield_s* m, int* key );
+
+//
+// ui_menu.c
+//
+extern void MainMenu_Cache( void );
+extern void UI_MainMenu(void);
+extern void UI_RegisterCvars( void );
+extern void UI_UpdateCvars( void );
+
+//
+// ui_credits.c
+//
+extern void UI_CreditMenu( void );
+
+//
+// ui_ingame.c
+//
+extern void InGame_Cache( void );
+extern void UI_InGameMenu(void);
+
+//
+// ui_confirm.c
+//
+extern void ConfirmMenu_Cache( void );
+extern void UI_ConfirmMenu( const char *question, void (*draw)( void ), void (*action)( qboolean result ) );
+extern void UI_ConfirmMenu_Style( const char *question, int style, void (*draw)( void ), void (*action)( qboolean result ) );
+extern void UI_Message( const char **lines );
+
+//
+// ui_setup.c
+//
+extern void UI_SetupMenu_Cache( void );
+extern void UI_SetupMenu(void);
+
+//
+// ui_team.c
+//
+extern void UI_TeamMainMenu( void );
+extern void TeamMain_Cache( void );
+
+//
+// ui_connect.c
+//
+extern void UI_DrawConnectScreen( qboolean overlay );
+
+//
+// ui_controls2.c
+//
+extern void UI_ControlsMenu( void );
+extern void Controls_Cache( void );
+
+//
+// ui_demo2.c
+//
+extern void UI_DemosMenu( void );
+extern void Demos_Cache( void );
+
+//
+// ui_cinematics.c
+//
+extern void UI_CinematicsMenu( void );
+extern void UI_CinematicsMenu_f( void );
+extern void UI_CinematicsMenu_Cache( void );
+
+//
+// ui_mods.c
+//
+extern void UI_ModsMenu( void );
+extern void UI_ModsMenu_Cache( void );
+
+//
+// ui_cdkey.c
+//
+extern void UI_CDKeyMenu( void );
+extern void UI_CDKeyMenu_Cache( void );
+extern void UI_CDKeyMenu_f( void );
+
+//
+// ui_playermodel.c
+//
+extern void UI_PlayerModelMenu( void );
+extern void PlayerModel_Cache( void );
+
+//
+// ui_playersettings.c
+//
+extern void UI_PlayerSettingsMenu( void );
+extern void PlayerSettings_Cache( void );
+
+//
+// ui_preferences.c
+//
+extern void UI_PreferencesMenu( void );
+extern void Preferences_Cache( void );
+
+//
+// ui_specifyleague.c
+//
+extern void UI_SpecifyLeagueMenu( void );
+extern void SpecifyLeague_Cache( void );
+
+//
+// ui_specifyserver.c
+//
+extern void UI_SpecifyServerMenu( void );
+extern void SpecifyServer_Cache( void );
+
+//
+// ui_servers2.c
+//
+#define MAX_FAVORITESERVERS 16
+
+extern void UI_ArenaServersMenu( void );
+extern void ArenaServers_Cache( void );
+
+//
+// ui_startserver.c
+//
+extern void UI_StartServerMenu( qboolean multiplayer );
+extern void StartServer_Cache( void );
+extern void ServerOptions_Cache( void );
+extern void UI_BotSelectMenu( char *bot );
+extern void UI_BotSelectMenu_Cache( void );
+
+//
+// ui_serverinfo.c
+//
+extern void UI_ServerInfoMenu( void );
+extern void ServerInfo_Cache( void );
+
+//
+// ui_video.c
+//
+extern void UI_GraphicsOptionsMenu( void );
+extern void GraphicsOptions_Cache( void );
+extern void DriverInfo_Cache( void );
+
+//
+// ui_players.c
+//
+
+//FIXME ripped from cg_local.h
+typedef struct {
+ int oldFrame;
+ int oldFrameTime; // time when ->oldFrame was exactly on
+
+ int frame;
+ int frameTime; // time when ->frame will be exactly on
+
+ float backlerp;
+
+ float yawAngle;
+ qboolean yawing;
+ float pitchAngle;
+ qboolean pitching;
+
+ int animationNumber; // may include ANIM_TOGGLEBIT
+ animation_t *animation;
+ int animationTime; // time when the first frame of the animation will be exact
+} lerpFrame_t;
+
+typedef struct {
+ // model info
+ qhandle_t legsModel;
+ qhandle_t legsSkin;
+ lerpFrame_t legs;
+
+ qhandle_t torsoModel;
+ qhandle_t torsoSkin;
+ lerpFrame_t torso;
+
+ qhandle_t headModel;
+ qhandle_t headSkin;
+
+ animation_t animations[MAX_ANIMATIONS];
+
+ qhandle_t weaponModel;
+ qhandle_t barrelModel;
+ qhandle_t flashModel;
+ vec3_t flashDlightColor;
+ int muzzleFlashTime;
+
+ // currently in use drawing parms
+ vec3_t viewAngles;
+ vec3_t moveAngles;
+ weapon_t currentWeapon;
+ int legsAnim;
+ int torsoAnim;
+
+ // animation vars
+ weapon_t weapon;
+ weapon_t lastWeapon;
+ weapon_t pendingWeapon;
+ int weaponTimer;
+ int pendingLegsAnim;
+ int torsoAnimationTimer;
+
+ int pendingTorsoAnim;
+ int legsAnimationTimer;
+
+ qboolean chat;
+ qboolean newModel;
+
+ qboolean barrelSpinning;
+ float barrelAngle;
+ int barrelTime;
+
+ int realWeapon;
+} playerInfo_t;
+
+void UI_DrawPlayer( float x, float y, float w, float h, playerInfo_t *pi, int time );
+void UI_PlayerInfo_SetModel( playerInfo_t *pi, const char *model );
+void UI_PlayerInfo_SetInfo( playerInfo_t *pi, int legsAnim, int torsoAnim, vec3_t viewAngles, vec3_t moveAngles, weapon_t weaponNum, qboolean chat );
+qboolean UI_RegisterClientModelname( playerInfo_t *pi, const char *modelSkinName );
+
+//
+// ui_atoms.c
+//
+typedef struct {
+ int frametime;
+ int realtime;
+ int cursorx;
+ int cursory;
+ int menusp;
+ menuframework_s* activemenu;
+ menuframework_s* stack[MAX_MENUDEPTH];
+ glconfig_t glconfig;
+ qboolean debug;
+ qhandle_t whiteShader;
+ qhandle_t menuBackShader;
+ qhandle_t menuBackNoLogoShader;
+ qhandle_t charset;
+ qhandle_t charsetProp;
+ qhandle_t charsetPropGlow;
+ qhandle_t charsetPropB;
+ qhandle_t cursor;
+ qhandle_t rb_on;
+ qhandle_t rb_off;
+ float scale;
+ float bias;
+ qboolean demoversion;
+ qboolean firstdraw;
+} uiStatic_t;
+
+extern void UI_Init( void );
+extern void UI_Shutdown( void );
+extern void UI_KeyEvent( int key, int down );
+extern void UI_MouseEvent( int dx, int dy );
+extern void UI_Refresh( int realtime );
+extern qboolean UI_ConsoleCommand( int realTime );
+extern float UI_ClampCvar( float min, float max, float value );
+extern void UI_DrawNamedPic( float x, float y, float width, float height, const char *picname );
+extern void UI_DrawHandlePic( float x, float y, float w, float h, qhandle_t hShader );
+extern void UI_FillRect( float x, float y, float width, float height, const float *color );
+extern void UI_DrawRect( float x, float y, float width, float height, const float *color );
+extern void UI_UpdateScreen( void );
+extern void UI_SetColor( const float *rgba );
+extern void UI_LerpColor(vec4_t a, vec4_t b, vec4_t c, float t);
+extern void UI_DrawBannerString( int x, int y, const char* str, int style, vec4_t color );
+extern float UI_ProportionalSizeScale( int style );
+extern void UI_DrawProportionalString( int x, int y, const char* str, int style, vec4_t color );
+extern void UI_DrawProportionalString_AutoWrapped( int x, int ystart, int xmax, int ystep, const char* str, int style, vec4_t color );
+extern int UI_ProportionalStringWidth( const char* str );
+extern void UI_DrawString( int x, int y, const char* str, int style, vec4_t color );
+extern void UI_DrawChar( int x, int y, int ch, int style, vec4_t color );
+extern qboolean UI_CursorInRect (int x, int y, int width, int height);
+extern void UI_AdjustFrom640( float *x, float *y, float *w, float *h );
+extern void UI_DrawTextBox (int x, int y, int width, int lines);
+extern qboolean UI_IsFullscreen( void );
+extern void UI_SetActiveMenu( uiMenuCommand_t menu );
+extern void UI_PushMenu ( menuframework_s *menu );
+extern void UI_PopMenu (void);
+extern void UI_ForceMenuOff (void);
+extern char *UI_Argv( int arg );
+extern char *UI_Cvar_VariableString( const char *var_name );
+extern void UI_Refresh( int time );
+extern void UI_StartDemoLoop( void );
+extern qboolean m_entersound;
+extern uiStatic_t uis;
+
+//
+// ui_spLevel.c
+//
+void UI_SPLevelMenu_Cache( void );
+void UI_SPLevelMenu( void );
+void UI_SPLevelMenu_f( void );
+void UI_SPLevelMenu_ReInit( void );
+
+//
+// ui_spArena.c
+//
+void UI_SPArena_Start( const char *arenaInfo );
+
+//
+// ui_spPostgame.c
+//
+void UI_SPPostgameMenu_Cache( void );
+void UI_SPPostgameMenu_f( void );
+
+//
+// ui_spSkill.c
+//
+void UI_SPSkillMenu( const char *arenaInfo );
+void UI_SPSkillMenu_Cache( void );
+
+//
+// ui_syscalls.c
+//
+void trap_Print( const char *string );
+void trap_Error( const char *string );
+int trap_Milliseconds( void );
+void trap_Cvar_Register( vmCvar_t *vmCvar, const char *varName, const char *defaultValue, int flags );
+void trap_Cvar_Update( vmCvar_t *vmCvar );
+void trap_Cvar_Set( const char *var_name, const char *value );
+float trap_Cvar_VariableValue( const char *var_name );
+void trap_Cvar_VariableStringBuffer( const char *var_name, char *buffer, int bufsize );
+void trap_Cvar_SetValue( const char *var_name, float value );
+void trap_Cvar_Reset( const char *name );
+void trap_Cvar_Create( const char *var_name, const char *var_value, int flags );
+void trap_Cvar_InfoStringBuffer( int bit, char *buffer, int bufsize );
+int trap_Argc( void );
+void trap_Argv( int n, char *buffer, int bufferLength );
+void trap_Cmd_ExecuteText( int exec_when, const char *text ); // don't use EXEC_NOW!
+int trap_FS_FOpenFile( const char *qpath, fileHandle_t *f, fsMode_t mode );
+void trap_FS_Read( void *buffer, int len, fileHandle_t f );
+void trap_FS_Write( const void *buffer, int len, fileHandle_t f );
+void trap_FS_FCloseFile( fileHandle_t f );
+int trap_FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize );
+int trap_FS_Seek( fileHandle_t f, long offset, int origin ); // fsOrigin_t
+qhandle_t trap_R_RegisterModel( const char *name );
+qhandle_t trap_R_RegisterSkin( const char *name );
+qhandle_t trap_R_RegisterShaderNoMip( const char *name );
+void trap_R_ClearScene( void );
+void trap_R_AddRefEntityToScene( const refEntity_t *re );
+void trap_R_AddPolyToScene( qhandle_t hShader , int numVerts, const polyVert_t *verts );
+void trap_R_AddLightToScene( const vec3_t org, float intensity, float r, float g, float b );
+void trap_R_RenderScene( const refdef_t *fd );
+void trap_R_SetColor( const float *rgba );
+void trap_R_DrawStretchPic( float x, float y, float w, float h, float s1, float t1, float s2, float t2, qhandle_t hShader );
+void trap_UpdateScreen( void );
+int trap_CM_LerpTag( orientation_t *tag, clipHandle_t mod, int startFrame, int endFrame, float frac, const char *tagName );
+void trap_S_StartLocalSound( sfxHandle_t sfx, int channelNum );
+sfxHandle_t trap_S_RegisterSound( const char *sample, qboolean compressed );
+void trap_Key_KeynumToStringBuf( int keynum, char *buf, int buflen );
+void trap_Key_GetBindingBuf( int keynum, char *buf, int buflen );
+void trap_Key_SetBinding( int keynum, const char *binding );
+qboolean trap_Key_IsDown( int keynum );
+qboolean trap_Key_GetOverstrikeMode( void );
+void trap_Key_SetOverstrikeMode( qboolean state );
+void trap_Key_ClearStates( void );
+int trap_Key_GetCatcher( void );
+void trap_Key_SetCatcher( int catcher );
+void trap_GetClipboardData( char *buf, int bufsize );
+void trap_GetClientState( uiClientState_t *state );
+void trap_GetGlconfig( glconfig_t *glconfig );
+int trap_GetConfigString( int index, char* buff, int buffsize );
+int trap_LAN_GetServerCount( int source );
+void trap_LAN_GetServerAddressString( int source, int n, char *buf, int buflen );
+void trap_LAN_GetServerInfo( int source, int n, char *buf, int buflen );
+int trap_LAN_GetPingQueueCount( void );
+int trap_LAN_ServerStatus( const char *serverAddress, char *serverStatus, int maxLen );
+void trap_LAN_ClearPing( int n );
+void trap_LAN_GetPing( int n, char *buf, int buflen, int *pingtime );
+void trap_LAN_GetPingInfo( int n, char *buf, int buflen );
+int trap_MemoryRemaining( void );
+void trap_GetCDKey( char *buf, int buflen );
+void trap_SetCDKey( char *buf );
+
+qboolean trap_VerifyCDKey( const char *key, const char *chksum); // bk001208 - RC4
+
+void trap_SetPbClStatus( int status );
+
+//
+// ui_addbots.c
+//
+void UI_AddBots_Cache( void );
+void UI_AddBotsMenu( void );
+
+//
+// ui_removebots.c
+//
+void UI_RemoveBots_Cache( void );
+void UI_RemoveBotsMenu( void );
+
+//
+// ui_teamorders.c
+//
+extern void UI_TeamOrdersMenu( void );
+extern void UI_TeamOrdersMenu_f( void );
+extern void UI_TeamOrdersMenu_Cache( void );
+
+//
+// ui_loadconfig.c
+//
+void UI_LoadConfig_Cache( void );
+void UI_LoadConfigMenu( void );
+
+//
+// ui_saveconfig.c
+//
+void UI_SaveConfigMenu_Cache( void );
+void UI_SaveConfigMenu( void );
+
+//
+// ui_display.c
+//
+void UI_DisplayOptionsMenu_Cache( void );
+void UI_DisplayOptionsMenu( void );
+
+//
+// ui_sound.c
+//
+void UI_SoundOptionsMenu_Cache( void );
+void UI_SoundOptionsMenu( void );
+
+//
+// ui_network.c
+//
+void UI_NetworkOptionsMenu_Cache( void );
+void UI_NetworkOptionsMenu( void );
+
+//
+// ui_gameinfo.c
+//
+typedef enum {
+ AWARD_ACCURACY,
+ AWARD_IMPRESSIVE,
+ AWARD_EXCELLENT,
+ AWARD_GAUNTLET,
+ AWARD_FRAGS,
+ AWARD_PERFECT
+} awardType_t;
+
+const char *UI_GetArenaInfoByNumber( int num );
+const char *UI_GetArenaInfoByMap( const char *map );
+const char *UI_GetSpecialArenaInfo( const char *tag );
+int UI_GetNumArenas( void );
+int UI_GetNumSPArenas( void );
+int UI_GetNumSPTiers( void );
+
+char *UI_GetBotInfoByNumber( int num );
+char *UI_GetBotInfoByName( const char *name );
+int UI_GetNumBots( void );
+
+void UI_GetBestScore( int level, int *score, int *skill );
+void UI_SetBestScore( int level, int score );
+int UI_TierCompleted( int levelWon );
+qboolean UI_ShowTierVideo( int tier );
+qboolean UI_CanShowTierVideo( int tier );
+int UI_GetCurrentGame( void );
+void UI_NewGame( void );
+void UI_LogAwardData( int award, int data );
+int UI_GetAwardLevel( int award );
+
+void UI_SPUnlock_f( void );
+void UI_SPUnlockMedals_f( void );
+
+void UI_InitGameinfo( void );
+
+//GRank
+
+//
+// ui_rankings.c
+//
+void Rankings_DrawText( void* self );
+void Rankings_DrawName( void* self );
+void Rankings_DrawPassword( void* self );
+void Rankings_Cache( void );
+void UI_RankingsMenu( void );
+
+//
+// ui_login.c
+//
+void Login_Cache( void );
+void UI_LoginMenu( void );
+
+//
+// ui_signup.c
+//
+void Signup_Cache( void );
+void UI_SignupMenu( void );
+
+//
+// ui_rankstatus.c
+//
+void RankStatus_Cache( void );
+void UI_RankStatusMenu( void );
+
+#endif
diff --git a/code/q3_ui/ui_login.c b/code/q3_ui/ui_login.c
new file mode 100755
index 0000000..86b7584
--- /dev/null
+++ b/code/q3_ui/ui_login.c
@@ -0,0 +1,208 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+//
+// ui_login.c
+//
+
+#include "ui_local.h"
+
+
+#define LOGIN_FRAME "menu/art/cut_frame"
+
+#define ID_NAME 100
+#define ID_NAME_BOX 101
+#define ID_PASSWORD 102
+#define ID_PASSWORD_BOX 103
+#define ID_LOGIN 104
+#define ID_CANCEL 105
+
+
+typedef struct
+{
+ menuframework_s menu;
+ menubitmap_s frame;
+ menutext_s name;
+ menufield_s name_box;
+ menutext_s password;
+ menufield_s password_box;
+ menutext_s login;
+ menutext_s cancel;
+} login_t;
+
+static login_t s_login;
+
+static menuframework_s s_login_menu;
+static menuaction_s s_login_login;
+static menuaction_s s_login_cancel;
+
+static vec4_t s_login_color_prompt = {1.00, 0.43, 0.00, 1.00};
+
+/*
+===============
+Login_MenuEvent
+===============
+*/
+static void Login_MenuEvent( void* ptr, int event ) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+
+ switch( ((menucommon_s*)ptr)->id ) {
+ case ID_LOGIN:
+ // set name ``
+ //trap_Cvar_Set( "name", s_login.name_box.field.buffer );
+ /*
+ trap_Cvar_Set( "rank_name", s_login.name_box.field.buffer );
+ trap_Cvar_Set( "rank_pwd", s_login.password_box.field.buffer );
+ */
+
+ // login
+ trap_CL_UI_RankUserLogin(
+ s_login.name_box.field.buffer,
+ s_login.password_box.field.buffer );
+
+ UI_ForceMenuOff();
+ break;
+
+ case ID_CANCEL:
+ UI_PopMenu();
+ break;
+ }
+}
+
+
+/*
+===============
+Login_MenuInit
+===============
+*/
+void Login_MenuInit( void ) {
+ int y;
+
+ memset( &s_login, 0, sizeof(s_login) );
+
+ Login_Cache();
+
+ s_login.menu.wrapAround = qtrue;
+ s_login.menu.fullscreen = qfalse;
+
+ s_login.frame.generic.type = MTYPE_BITMAP;
+ s_login.frame.generic.flags = QMF_INACTIVE;
+ s_login.frame.generic.name = LOGIN_FRAME;
+ s_login.frame.generic.x = 142; //320-233;
+ s_login.frame.generic.y = 118; //240-166;
+ s_login.frame.width = 359; //466;
+ s_login.frame.height = 256; //332;
+
+ y = 214;
+
+ s_login.name.generic.type = MTYPE_PTEXT;
+ s_login.name.generic.flags = QMF_RIGHT_JUSTIFY|QMF_INACTIVE;
+ s_login.name.generic.id = ID_NAME;
+ s_login.name.generic.x = 310;
+ s_login.name.generic.y = y;
+ s_login.name.string = "NAME";
+ s_login.name.style = UI_RIGHT|UI_SMALLFONT;
+ s_login.name.color = s_login_color_prompt;
+
+ s_login.name_box.generic.type = MTYPE_FIELD;
+ s_login.name_box.generic.ownerdraw = Rankings_DrawName;
+ s_login.name_box.generic.name = "";
+ s_login.name_box.generic.flags = 0;
+ s_login.name_box.generic.x = 330;
+ s_login.name_box.generic.y = y;
+ s_login.name_box.field.widthInChars = 16;
+ s_login.name_box.field.maxchars = 16;
+ y += 20;
+
+ s_login.password.generic.type = MTYPE_PTEXT;
+ s_login.password.generic.flags = QMF_RIGHT_JUSTIFY|QMF_INACTIVE;
+ s_login.password.generic.id = ID_PASSWORD;
+ s_login.password.generic.x = 310;
+ s_login.password.generic.y = y;
+ s_login.password.string = "PASSWORD";
+ s_login.password.style = UI_RIGHT|UI_SMALLFONT;
+ s_login.password.color = s_login_color_prompt;
+
+ s_login.password_box.generic.type = MTYPE_FIELD;
+ s_login.password_box.generic.ownerdraw = Rankings_DrawPassword;
+ s_login.password_box.generic.name = "";
+ s_login.password_box.generic.flags = 0;
+ s_login.password_box.generic.x = 330;
+ s_login.password_box.generic.y = y;
+ s_login.password_box.field.widthInChars = 16;
+ s_login.password_box.field.maxchars = 16;
+ y += 40;
+
+ s_login.login.generic.type = MTYPE_PTEXT;
+ s_login.login.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_login.login.generic.id = ID_LOGIN;
+ s_login.login.generic.callback = Login_MenuEvent;
+ s_login.login.generic.x = 310;
+ s_login.login.generic.y = y;
+ s_login.login.string = "LOGIN";
+ s_login.login.style = UI_RIGHT|UI_SMALLFONT;
+ s_login.login.color = colorRed;
+
+ s_login.cancel.generic.type = MTYPE_PTEXT;
+ s_login.cancel.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_login.cancel.generic.id = ID_CANCEL;
+ s_login.cancel.generic.callback = Login_MenuEvent;
+ s_login.cancel.generic.x = 330;
+ s_login.cancel.generic.y = y;
+ s_login.cancel.string = "CANCEL";
+ s_login.cancel.style = UI_LEFT|UI_SMALLFONT;
+ s_login.cancel.color = colorRed;
+ y += 20;
+
+ Menu_AddItem( &s_login.menu, (void*) &s_login.frame );
+ Menu_AddItem( &s_login.menu, (void*) &s_login.name );
+ Menu_AddItem( &s_login.menu, (void*) &s_login.name_box );
+ Menu_AddItem( &s_login.menu, (void*) &s_login.password );
+ Menu_AddItem( &s_login.menu, (void*) &s_login.password_box );
+ Menu_AddItem( &s_login.menu, (void*) &s_login.login );
+ Menu_AddItem( &s_login.menu, (void*) &s_login.cancel );
+}
+
+
+/*
+===============
+Login_Cache
+===============
+*/
+void Login_Cache( void ) {
+ trap_R_RegisterShaderNoMip( LOGIN_FRAME );
+}
+
+
+/*
+===============
+UI_LoginMenu
+===============
+*/
+void UI_LoginMenu( void ) {
+ Login_MenuInit();
+ UI_PushMenu ( &s_login.menu );
+}
+
+
diff --git a/code/q3_ui/ui_main.c b/code/q3_ui/ui_main.c
new file mode 100755
index 0000000..465e6ec
--- /dev/null
+++ b/code/q3_ui/ui_main.c
@@ -0,0 +1,249 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*
+=======================================================================
+
+USER INTERFACE MAIN
+
+=======================================================================
+*/
+
+
+#include "ui_local.h"
+
+
+/*
+================
+vmMain
+
+This is the only way control passes into the module.
+This must be the very first function compiled into the .qvm file
+================
+*/
+int vmMain( int command, int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11 ) {
+ switch ( command ) {
+ case UI_GETAPIVERSION:
+ return UI_API_VERSION;
+
+ case UI_INIT:
+ UI_Init();
+ return 0;
+
+ case UI_SHUTDOWN:
+ UI_Shutdown();
+ return 0;
+
+ case UI_KEY_EVENT:
+ UI_KeyEvent( arg0, arg1 );
+ return 0;
+
+ case UI_MOUSE_EVENT:
+ UI_MouseEvent( arg0, arg1 );
+ return 0;
+
+ case UI_REFRESH:
+ UI_Refresh( arg0 );
+ return 0;
+
+ case UI_IS_FULLSCREEN:
+ return UI_IsFullscreen();
+
+ case UI_SET_ACTIVE_MENU:
+ UI_SetActiveMenu( arg0 );
+ return 0;
+
+ case UI_CONSOLE_COMMAND:
+ return UI_ConsoleCommand(arg0);
+
+ case UI_DRAW_CONNECT_SCREEN:
+ UI_DrawConnectScreen( arg0 );
+ return 0;
+ case UI_HASUNIQUECDKEY: // mod authors need to observe this
+ return qtrue; // bk010117 - change this to qfalse for mods!
+ }
+
+ return -1;
+}
+
+
+/*
+================
+cvars
+================
+*/
+
+typedef struct {
+ vmCvar_t *vmCvar;
+ char *cvarName;
+ char *defaultString;
+ int cvarFlags;
+} cvarTable_t;
+
+vmCvar_t ui_ffa_fraglimit;
+vmCvar_t ui_ffa_timelimit;
+
+vmCvar_t ui_tourney_fraglimit;
+vmCvar_t ui_tourney_timelimit;
+
+vmCvar_t ui_team_fraglimit;
+vmCvar_t ui_team_timelimit;
+vmCvar_t ui_team_friendly;
+
+vmCvar_t ui_ctf_capturelimit;
+vmCvar_t ui_ctf_timelimit;
+vmCvar_t ui_ctf_friendly;
+
+vmCvar_t ui_arenasFile;
+vmCvar_t ui_botsFile;
+vmCvar_t ui_spScores1;
+vmCvar_t ui_spScores2;
+vmCvar_t ui_spScores3;
+vmCvar_t ui_spScores4;
+vmCvar_t ui_spScores5;
+vmCvar_t ui_spAwards;
+vmCvar_t ui_spVideos;
+vmCvar_t ui_spSkill;
+
+vmCvar_t ui_spSelection;
+
+vmCvar_t ui_browserMaster;
+vmCvar_t ui_browserGameType;
+vmCvar_t ui_browserSortKey;
+vmCvar_t ui_browserShowFull;
+vmCvar_t ui_browserShowEmpty;
+
+vmCvar_t ui_brassTime;
+vmCvar_t ui_drawCrosshair;
+vmCvar_t ui_drawCrosshairNames;
+vmCvar_t ui_marks;
+
+vmCvar_t ui_server1;
+vmCvar_t ui_server2;
+vmCvar_t ui_server3;
+vmCvar_t ui_server4;
+vmCvar_t ui_server5;
+vmCvar_t ui_server6;
+vmCvar_t ui_server7;
+vmCvar_t ui_server8;
+vmCvar_t ui_server9;
+vmCvar_t ui_server10;
+vmCvar_t ui_server11;
+vmCvar_t ui_server12;
+vmCvar_t ui_server13;
+vmCvar_t ui_server14;
+vmCvar_t ui_server15;
+vmCvar_t ui_server16;
+
+vmCvar_t ui_cdkeychecked;
+
+// bk001129 - made static to avoid aliasing.
+static cvarTable_t cvarTable[] = {
+ { &ui_ffa_fraglimit, "ui_ffa_fraglimit", "20", CVAR_ARCHIVE },
+ { &ui_ffa_timelimit, "ui_ffa_timelimit", "0", CVAR_ARCHIVE },
+
+ { &ui_tourney_fraglimit, "ui_tourney_fraglimit", "0", CVAR_ARCHIVE },
+ { &ui_tourney_timelimit, "ui_tourney_timelimit", "15", CVAR_ARCHIVE },
+
+ { &ui_team_fraglimit, "ui_team_fraglimit", "0", CVAR_ARCHIVE },
+ { &ui_team_timelimit, "ui_team_timelimit", "20", CVAR_ARCHIVE },
+ { &ui_team_friendly, "ui_team_friendly", "1", CVAR_ARCHIVE },
+
+ { &ui_ctf_capturelimit, "ui_ctf_capturelimit", "8", CVAR_ARCHIVE },
+ { &ui_ctf_timelimit, "ui_ctf_timelimit", "30", CVAR_ARCHIVE },
+ { &ui_ctf_friendly, "ui_ctf_friendly", "0", CVAR_ARCHIVE },
+
+ { &ui_arenasFile, "g_arenasFile", "", CVAR_INIT|CVAR_ROM },
+ { &ui_botsFile, "g_botsFile", "", CVAR_INIT|CVAR_ROM },
+ { &ui_spScores1, "g_spScores1", "", CVAR_ARCHIVE | CVAR_ROM },
+ { &ui_spScores2, "g_spScores2", "", CVAR_ARCHIVE | CVAR_ROM },
+ { &ui_spScores3, "g_spScores3", "", CVAR_ARCHIVE | CVAR_ROM },
+ { &ui_spScores4, "g_spScores4", "", CVAR_ARCHIVE | CVAR_ROM },
+ { &ui_spScores5, "g_spScores5", "", CVAR_ARCHIVE | CVAR_ROM },
+ { &ui_spAwards, "g_spAwards", "", CVAR_ARCHIVE | CVAR_ROM },
+ { &ui_spVideos, "g_spVideos", "", CVAR_ARCHIVE | CVAR_ROM },
+ { &ui_spSkill, "g_spSkill", "2", CVAR_ARCHIVE | CVAR_LATCH },
+
+ { &ui_spSelection, "ui_spSelection", "", CVAR_ROM },
+
+ { &ui_browserMaster, "ui_browserMaster", "0", CVAR_ARCHIVE },
+ { &ui_browserGameType, "ui_browserGameType", "0", CVAR_ARCHIVE },
+ { &ui_browserSortKey, "ui_browserSortKey", "4", CVAR_ARCHIVE },
+ { &ui_browserShowFull, "ui_browserShowFull", "1", CVAR_ARCHIVE },
+ { &ui_browserShowEmpty, "ui_browserShowEmpty", "1", CVAR_ARCHIVE },
+
+ { &ui_brassTime, "cg_brassTime", "2500", CVAR_ARCHIVE },
+ { &ui_drawCrosshair, "cg_drawCrosshair", "4", CVAR_ARCHIVE },
+ { &ui_drawCrosshairNames, "cg_drawCrosshairNames", "1", CVAR_ARCHIVE },
+ { &ui_marks, "cg_marks", "1", CVAR_ARCHIVE },
+
+ { &ui_server1, "server1", "", CVAR_ARCHIVE },
+ { &ui_server2, "server2", "", CVAR_ARCHIVE },
+ { &ui_server3, "server3", "", CVAR_ARCHIVE },
+ { &ui_server4, "server4", "", CVAR_ARCHIVE },
+ { &ui_server5, "server5", "", CVAR_ARCHIVE },
+ { &ui_server6, "server6", "", CVAR_ARCHIVE },
+ { &ui_server7, "server7", "", CVAR_ARCHIVE },
+ { &ui_server8, "server8", "", CVAR_ARCHIVE },
+ { &ui_server9, "server9", "", CVAR_ARCHIVE },
+ { &ui_server10, "server10", "", CVAR_ARCHIVE },
+ { &ui_server11, "server11", "", CVAR_ARCHIVE },
+ { &ui_server12, "server12", "", CVAR_ARCHIVE },
+ { &ui_server13, "server13", "", CVAR_ARCHIVE },
+ { &ui_server14, "server14", "", CVAR_ARCHIVE },
+ { &ui_server15, "server15", "", CVAR_ARCHIVE },
+ { &ui_server16, "server16", "", CVAR_ARCHIVE },
+
+ { &ui_cdkeychecked, "ui_cdkeychecked", "0", CVAR_ROM }
+};
+
+// bk001129 - made static to avoid aliasing
+static int cvarTableSize = sizeof(cvarTable) / sizeof(cvarTable[0]);
+
+
+/*
+=================
+UI_RegisterCvars
+=================
+*/
+void UI_RegisterCvars( void ) {
+ int i;
+ cvarTable_t *cv;
+
+ for ( i = 0, cv = cvarTable ; i < cvarTableSize ; i++, cv++ ) {
+ trap_Cvar_Register( cv->vmCvar, cv->cvarName, cv->defaultString, cv->cvarFlags );
+ }
+}
+
+/*
+=================
+UI_UpdateCvars
+=================
+*/
+void UI_UpdateCvars( void ) {
+ int i;
+ cvarTable_t *cv;
+
+ for ( i = 0, cv = cvarTable ; i < cvarTableSize ; i++, cv++ ) {
+ trap_Cvar_Update( cv->vmCvar );
+ }
+}
diff --git a/code/q3_ui/ui_menu.c b/code/q3_ui/ui_menu.c
new file mode 100755
index 0000000..682c5a8
--- /dev/null
+++ b/code/q3_ui/ui_menu.c
@@ -0,0 +1,419 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*
+=======================================================================
+
+MAIN MENU
+
+=======================================================================
+*/
+
+
+#include "ui_local.h"
+
+
+#define ID_SINGLEPLAYER 10
+#define ID_MULTIPLAYER 11
+#define ID_SETUP 12
+#define ID_DEMOS 13
+#define ID_CINEMATICS 14
+#define ID_TEAMARENA 15
+#define ID_MODS 16
+#define ID_EXIT 17
+
+#define MAIN_BANNER_MODEL "models/mapobjects/banner/banner5.md3"
+#define MAIN_MENU_VERTICAL_SPACING 34
+
+
+typedef struct {
+ menuframework_s menu;
+
+ menutext_s singleplayer;
+ menutext_s multiplayer;
+ menutext_s setup;
+ menutext_s demos;
+ menutext_s cinematics;
+ menutext_s teamArena;
+ menutext_s mods;
+ menutext_s exit;
+
+ qhandle_t bannerModel;
+} mainmenu_t;
+
+
+static mainmenu_t s_main;
+
+typedef struct {
+ menuframework_s menu;
+ char errorMessage[4096];
+} errorMessage_t;
+
+static errorMessage_t s_errorMessage;
+
+/*
+=================
+MainMenu_ExitAction
+=================
+*/
+static void MainMenu_ExitAction( qboolean result ) {
+ if( !result ) {
+ return;
+ }
+ UI_PopMenu();
+ UI_CreditMenu();
+}
+
+
+
+/*
+=================
+Main_MenuEvent
+=================
+*/
+void Main_MenuEvent (void* ptr, int event) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+
+ switch( ((menucommon_s*)ptr)->id ) {
+ case ID_SINGLEPLAYER:
+ UI_SPLevelMenu();
+ break;
+
+ case ID_MULTIPLAYER:
+ UI_ArenaServersMenu();
+ break;
+
+ case ID_SETUP:
+ UI_SetupMenu();
+ break;
+
+ case ID_DEMOS:
+ UI_DemosMenu();
+ break;
+
+ case ID_CINEMATICS:
+ UI_CinematicsMenu();
+ break;
+
+ case ID_MODS:
+ UI_ModsMenu();
+ break;
+
+ case ID_TEAMARENA:
+ trap_Cvar_Set( "fs_game", "missionpack");
+ trap_Cmd_ExecuteText( EXEC_APPEND, "vid_restart;" );
+ break;
+
+ case ID_EXIT:
+ UI_ConfirmMenu( "EXIT GAME?", NULL, MainMenu_ExitAction );
+ break;
+ }
+}
+
+
+/*
+===============
+MainMenu_Cache
+===============
+*/
+void MainMenu_Cache( void ) {
+ s_main.bannerModel = trap_R_RegisterModel( MAIN_BANNER_MODEL );
+}
+
+sfxHandle_t ErrorMessage_Key(int key)
+{
+ trap_Cvar_Set( "com_errorMessage", "" );
+ UI_MainMenu();
+ return (menu_null_sound);
+}
+
+/*
+===============
+Main_MenuDraw
+TTimo: this function is common to the main menu and errorMessage menu
+===============
+*/
+
+static void Main_MenuDraw( void ) {
+ refdef_t refdef;
+ refEntity_t ent;
+ vec3_t origin;
+ vec3_t angles;
+ float adjust;
+ float x, y, w, h;
+ vec4_t color = {0.5, 0, 0, 1};
+
+ // setup the refdef
+
+ memset( &refdef, 0, sizeof( refdef ) );
+
+ refdef.rdflags = RDF_NOWORLDMODEL;
+
+ AxisClear( refdef.viewaxis );
+
+ x = 0;
+ y = 0;
+ w = 640;
+ h = 120;
+ UI_AdjustFrom640( &x, &y, &w, &h );
+ refdef.x = x;
+ refdef.y = y;
+ refdef.width = w;
+ refdef.height = h;
+
+ adjust = 0; // JDC: Kenneth asked me to stop this 1.0 * sin( (float)uis.realtime / 1000 );
+ refdef.fov_x = 60 + adjust;
+ refdef.fov_y = 19.6875 + adjust;
+
+ refdef.time = uis.realtime;
+
+ origin[0] = 300;
+ origin[1] = 0;
+ origin[2] = -32;
+
+ trap_R_ClearScene();
+
+ // add the model
+
+ memset( &ent, 0, sizeof(ent) );
+
+ adjust = 5.0 * sin( (float)uis.realtime / 5000 );
+ VectorSet( angles, 0, 180 + adjust, 0 );
+ AnglesToAxis( angles, ent.axis );
+ ent.hModel = s_main.bannerModel;
+ VectorCopy( origin, ent.origin );
+ VectorCopy( origin, ent.lightingOrigin );
+ ent.renderfx = RF_LIGHTING_ORIGIN | RF_NOSHADOW;
+ VectorCopy( ent.origin, ent.oldorigin );
+
+ trap_R_AddRefEntityToScene( &ent );
+
+ trap_R_RenderScene( &refdef );
+
+ if (strlen(s_errorMessage.errorMessage))
+ {
+ UI_DrawProportionalString_AutoWrapped( 320, 192, 600, 20, s_errorMessage.errorMessage, UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, menu_text_color );
+ }
+ else
+ {
+ // standard menu drawing
+ Menu_Draw( &s_main.menu );
+ }
+
+ if (uis.demoversion) {
+ UI_DrawProportionalString( 320, 372, "DEMO FOR MATURE AUDIENCES DEMO", UI_CENTER|UI_SMALLFONT, color );
+ UI_DrawString( 320, 400, "Quake III Arena(c) 1999-2000, Id Software, Inc. All Rights Reserved", UI_CENTER|UI_SMALLFONT, color );
+ } else {
+ UI_DrawString( 320, 450, "Quake III Arena(c) 1999-2000, Id Software, Inc. All Rights Reserved", UI_CENTER|UI_SMALLFONT, color );
+ }
+}
+
+
+/*
+===============
+UI_TeamArenaExists
+===============
+*/
+static qboolean UI_TeamArenaExists( void ) {
+ int numdirs;
+ char dirlist[2048];
+ char *dirptr;
+ char *descptr;
+ int i;
+ int dirlen;
+
+ numdirs = trap_FS_GetFileList( "$modlist", "", dirlist, sizeof(dirlist) );
+ dirptr = dirlist;
+ for( i = 0; i < numdirs; i++ ) {
+ dirlen = strlen( dirptr ) + 1;
+ descptr = dirptr + dirlen;
+ if (Q_stricmp(dirptr, "missionpack") == 0) {
+ return qtrue;
+ }
+ dirptr += dirlen + strlen(descptr) + 1;
+ }
+ return qfalse;
+}
+
+
+/*
+===============
+UI_MainMenu
+
+The main menu only comes up when not in a game,
+so make sure that the attract loop server is down
+and that local cinematics are killed
+===============
+*/
+void UI_MainMenu( void ) {
+ int y;
+ qboolean teamArena = qfalse;
+ int style = UI_CENTER | UI_DROPSHADOW;
+
+ trap_Cvar_Set( "sv_killserver", "1" );
+
+ if( !uis.demoversion && !ui_cdkeychecked.integer ) {
+ char key[17];
+
+ trap_GetCDKey( key, sizeof(key) );
+ if( trap_VerifyCDKey( key, NULL ) == qfalse ) {
+ UI_CDKeyMenu();
+ return;
+ }
+ }
+
+ memset( &s_main, 0 ,sizeof(mainmenu_t) );
+ memset( &s_errorMessage, 0 ,sizeof(errorMessage_t) );
+
+ // com_errorMessage would need that too
+ MainMenu_Cache();
+
+ trap_Cvar_VariableStringBuffer( "com_errorMessage", s_errorMessage.errorMessage, sizeof(s_errorMessage.errorMessage) );
+ if (strlen(s_errorMessage.errorMessage))
+ {
+ s_errorMessage.menu.draw = Main_MenuDraw;
+ s_errorMessage.menu.key = ErrorMessage_Key;
+ s_errorMessage.menu.fullscreen = qtrue;
+ s_errorMessage.menu.wrapAround = qtrue;
+ s_errorMessage.menu.showlogo = qtrue;
+
+ trap_Key_SetCatcher( KEYCATCH_UI );
+ uis.menusp = 0;
+ UI_PushMenu ( &s_errorMessage.menu );
+
+ return;
+ }
+
+ s_main.menu.draw = Main_MenuDraw;
+ s_main.menu.fullscreen = qtrue;
+ s_main.menu.wrapAround = qtrue;
+ s_main.menu.showlogo = qtrue;
+
+ y = 134;
+ s_main.singleplayer.generic.type = MTYPE_PTEXT;
+ s_main.singleplayer.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_main.singleplayer.generic.x = 320;
+ s_main.singleplayer.generic.y = y;
+ s_main.singleplayer.generic.id = ID_SINGLEPLAYER;
+ s_main.singleplayer.generic.callback = Main_MenuEvent;
+ s_main.singleplayer.string = "SINGLE PLAYER";
+ s_main.singleplayer.color = color_red;
+ s_main.singleplayer.style = style;
+
+ y += MAIN_MENU_VERTICAL_SPACING;
+ s_main.multiplayer.generic.type = MTYPE_PTEXT;
+ s_main.multiplayer.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_main.multiplayer.generic.x = 320;
+ s_main.multiplayer.generic.y = y;
+ s_main.multiplayer.generic.id = ID_MULTIPLAYER;
+ s_main.multiplayer.generic.callback = Main_MenuEvent;
+ s_main.multiplayer.string = "MULTIPLAYER";
+ s_main.multiplayer.color = color_red;
+ s_main.multiplayer.style = style;
+
+ y += MAIN_MENU_VERTICAL_SPACING;
+ s_main.setup.generic.type = MTYPE_PTEXT;
+ s_main.setup.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_main.setup.generic.x = 320;
+ s_main.setup.generic.y = y;
+ s_main.setup.generic.id = ID_SETUP;
+ s_main.setup.generic.callback = Main_MenuEvent;
+ s_main.setup.string = "SETUP";
+ s_main.setup.color = color_red;
+ s_main.setup.style = style;
+
+ y += MAIN_MENU_VERTICAL_SPACING;
+ s_main.demos.generic.type = MTYPE_PTEXT;
+ s_main.demos.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_main.demos.generic.x = 320;
+ s_main.demos.generic.y = y;
+ s_main.demos.generic.id = ID_DEMOS;
+ s_main.demos.generic.callback = Main_MenuEvent;
+ s_main.demos.string = "DEMOS";
+ s_main.demos.color = color_red;
+ s_main.demos.style = style;
+
+ y += MAIN_MENU_VERTICAL_SPACING;
+ s_main.cinematics.generic.type = MTYPE_PTEXT;
+ s_main.cinematics.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_main.cinematics.generic.x = 320;
+ s_main.cinematics.generic.y = y;
+ s_main.cinematics.generic.id = ID_CINEMATICS;
+ s_main.cinematics.generic.callback = Main_MenuEvent;
+ s_main.cinematics.string = "CINEMATICS";
+ s_main.cinematics.color = color_red;
+ s_main.cinematics.style = style;
+
+ if (UI_TeamArenaExists()) {
+ teamArena = qtrue;
+ y += MAIN_MENU_VERTICAL_SPACING;
+ s_main.teamArena.generic.type = MTYPE_PTEXT;
+ s_main.teamArena.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_main.teamArena.generic.x = 320;
+ s_main.teamArena.generic.y = y;
+ s_main.teamArena.generic.id = ID_TEAMARENA;
+ s_main.teamArena.generic.callback = Main_MenuEvent;
+ s_main.teamArena.string = "TEAM ARENA";
+ s_main.teamArena.color = color_red;
+ s_main.teamArena.style = style;
+ }
+
+ y += MAIN_MENU_VERTICAL_SPACING;
+ s_main.mods.generic.type = MTYPE_PTEXT;
+ s_main.mods.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_main.mods.generic.x = 320;
+ s_main.mods.generic.y = y;
+ s_main.mods.generic.id = ID_MODS;
+ s_main.mods.generic.callback = Main_MenuEvent;
+ s_main.mods.string = "MODS";
+ s_main.mods.color = color_red;
+ s_main.mods.style = style;
+
+ y += MAIN_MENU_VERTICAL_SPACING;
+ s_main.exit.generic.type = MTYPE_PTEXT;
+ s_main.exit.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_main.exit.generic.x = 320;
+ s_main.exit.generic.y = y;
+ s_main.exit.generic.id = ID_EXIT;
+ s_main.exit.generic.callback = Main_MenuEvent;
+ s_main.exit.string = "EXIT";
+ s_main.exit.color = color_red;
+ s_main.exit.style = style;
+
+ Menu_AddItem( &s_main.menu, &s_main.singleplayer );
+ Menu_AddItem( &s_main.menu, &s_main.multiplayer );
+ Menu_AddItem( &s_main.menu, &s_main.setup );
+ Menu_AddItem( &s_main.menu, &s_main.demos );
+ Menu_AddItem( &s_main.menu, &s_main.cinematics );
+ if (teamArena) {
+ Menu_AddItem( &s_main.menu, &s_main.teamArena );
+ }
+ Menu_AddItem( &s_main.menu, &s_main.mods );
+ Menu_AddItem( &s_main.menu, &s_main.exit );
+
+ trap_Key_SetCatcher( KEYCATCH_UI );
+ uis.menusp = 0;
+ UI_PushMenu ( &s_main.menu );
+
+}
diff --git a/code/q3_ui/ui_mfield.c b/code/q3_ui/ui_mfield.c
new file mode 100755
index 0000000..927e6c2
--- /dev/null
+++ b/code/q3_ui/ui_mfield.c
@@ -0,0 +1,439 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#include "ui_local.h"
+
+/*
+===================
+MField_Draw
+
+Handles horizontal scrolling and cursor blinking
+x, y, are in pixels
+===================
+*/
+void MField_Draw( mfield_t *edit, int x, int y, int style, vec4_t color ) {
+ int len;
+ int charw;
+ int drawLen;
+ int prestep;
+ int cursorChar;
+ char str[MAX_STRING_CHARS];
+
+ drawLen = edit->widthInChars;
+ len = strlen( edit->buffer ) + 1;
+
+ // guarantee that cursor will be visible
+ if ( len <= drawLen ) {
+ prestep = 0;
+ } else {
+ if ( edit->scroll + drawLen > len ) {
+ edit->scroll = len - drawLen;
+ if ( edit->scroll < 0 ) {
+ edit->scroll = 0;
+ }
+ }
+ prestep = edit->scroll;
+ }
+
+ if ( prestep + drawLen > len ) {
+ drawLen = len - prestep;
+ }
+
+ // extract <drawLen> characters from the field at <prestep>
+ if ( drawLen >= MAX_STRING_CHARS ) {
+ trap_Error( "drawLen >= MAX_STRING_CHARS" );
+ }
+ memcpy( str, edit->buffer + prestep, drawLen );
+ str[ drawLen ] = 0;
+
+ UI_DrawString( x, y, str, style, color );
+
+ // draw the cursor
+ if (!(style & UI_PULSE)) {
+ return;
+ }
+
+ if ( trap_Key_GetOverstrikeMode() ) {
+ cursorChar = 11;
+ } else {
+ cursorChar = 10;
+ }
+
+ style &= ~UI_PULSE;
+ style |= UI_BLINK;
+
+ if (style & UI_SMALLFONT)
+ {
+ charw = SMALLCHAR_WIDTH;
+ }
+ else if (style & UI_GIANTFONT)
+ {
+ charw = GIANTCHAR_WIDTH;
+ }
+ else
+ {
+ charw = BIGCHAR_WIDTH;
+ }
+
+ if (style & UI_CENTER)
+ {
+ len = strlen(str);
+ x = x - len*charw/2;
+ }
+ else if (style & UI_RIGHT)
+ {
+ len = strlen(str);
+ x = x - len*charw;
+ }
+
+ UI_DrawChar( x + ( edit->cursor - prestep ) * charw, y, cursorChar, style & ~(UI_CENTER|UI_RIGHT), color );
+}
+
+/*
+================
+MField_Paste
+================
+*/
+void MField_Paste( mfield_t *edit ) {
+ char pasteBuffer[64];
+ int pasteLen, i;
+
+ trap_GetClipboardData( pasteBuffer, 64 );
+
+ // send as if typed, so insert / overstrike works properly
+ pasteLen = strlen( pasteBuffer );
+ for ( i = 0 ; i < pasteLen ; i++ ) {
+ MField_CharEvent( edit, pasteBuffer[i] );
+ }
+}
+
+/*
+=================
+MField_KeyDownEvent
+
+Performs the basic line editing functions for the console,
+in-game talk, and menu fields
+
+Key events are used for non-printable characters, others are gotten from char events.
+=================
+*/
+void MField_KeyDownEvent( mfield_t *edit, int key ) {
+ int len;
+
+ // shift-insert is paste
+ if ( ( ( key == K_INS ) || ( key == K_KP_INS ) ) && trap_Key_IsDown( K_SHIFT ) ) {
+ MField_Paste( edit );
+ return;
+ }
+
+ len = strlen( edit->buffer );
+
+ if ( key == K_DEL || key == K_KP_DEL ) {
+ if ( edit->cursor < len ) {
+ memmove( edit->buffer + edit->cursor,
+ edit->buffer + edit->cursor + 1, len - edit->cursor );
+ }
+ return;
+ }
+
+ if ( key == K_RIGHTARROW || key == K_KP_RIGHTARROW )
+ {
+ if ( edit->cursor < len ) {
+ edit->cursor++;
+ }
+ if ( edit->cursor >= edit->scroll + edit->widthInChars && edit->cursor <= len )
+ {
+ edit->scroll++;
+ }
+ return;
+ }
+
+ if ( key == K_LEFTARROW || key == K_KP_LEFTARROW )
+ {
+ if ( edit->cursor > 0 ) {
+ edit->cursor--;
+ }
+ if ( edit->cursor < edit->scroll )
+ {
+ edit->scroll--;
+ }
+ return;
+ }
+
+ if ( key == K_HOME || key == K_KP_HOME || ( tolower(key) == 'a' && trap_Key_IsDown( K_CTRL ) ) ) {
+ edit->cursor = 0;
+ edit->scroll = 0;
+ return;
+ }
+
+ if ( key == K_END || key == K_KP_END || ( tolower(key) == 'e' && trap_Key_IsDown( K_CTRL ) ) ) {
+ edit->cursor = len;
+ edit->scroll = len - edit->widthInChars + 1;
+ if (edit->scroll < 0)
+ edit->scroll = 0;
+ return;
+ }
+
+ if ( key == K_INS || key == K_KP_INS ) {
+ trap_Key_SetOverstrikeMode( !trap_Key_GetOverstrikeMode() );
+ return;
+ }
+}
+
+/*
+==================
+MField_CharEvent
+==================
+*/
+void MField_CharEvent( mfield_t *edit, int ch ) {
+ int len;
+
+ if ( ch == 'v' - 'a' + 1 ) { // ctrl-v is paste
+ MField_Paste( edit );
+ return;
+ }
+
+ if ( ch == 'c' - 'a' + 1 ) { // ctrl-c clears the field
+ MField_Clear( edit );
+ return;
+ }
+
+ len = strlen( edit->buffer );
+
+ if ( ch == 'h' - 'a' + 1 ) { // ctrl-h is backspace
+ if ( edit->cursor > 0 ) {
+ memmove( edit->buffer + edit->cursor - 1,
+ edit->buffer + edit->cursor, len + 1 - edit->cursor );
+ edit->cursor--;
+ if ( edit->cursor < edit->scroll )
+ {
+ edit->scroll--;
+ }
+ }
+ return;
+ }
+
+ if ( ch == 'a' - 'a' + 1 ) { // ctrl-a is home
+ edit->cursor = 0;
+ edit->scroll = 0;
+ return;
+ }
+
+ if ( ch == 'e' - 'a' + 1 ) { // ctrl-e is end
+ edit->cursor = len;
+ edit->scroll = edit->cursor - edit->widthInChars + 1;
+ if (edit->scroll < 0)
+ edit->scroll = 0;
+ return;
+ }
+
+ //
+ // ignore any other non printable chars
+ //
+ if ( ch < 32 ) {
+ return;
+ }
+
+ if ( !trap_Key_GetOverstrikeMode() ) {
+ if ((edit->cursor == MAX_EDIT_LINE - 1) || (edit->maxchars && edit->cursor >= edit->maxchars))
+ return;
+ } else {
+ // insert mode
+ if (( len == MAX_EDIT_LINE - 1 ) || (edit->maxchars && len >= edit->maxchars))
+ return;
+ memmove( edit->buffer + edit->cursor + 1, edit->buffer + edit->cursor, len + 1 - edit->cursor );
+ }
+
+ edit->buffer[edit->cursor] = ch;
+ if (!edit->maxchars || edit->cursor < edit->maxchars-1)
+ edit->cursor++;
+
+ if ( edit->cursor >= edit->widthInChars )
+ {
+ edit->scroll++;
+ }
+
+ if ( edit->cursor == len + 1) {
+ edit->buffer[edit->cursor] = 0;
+ }
+}
+
+/*
+==================
+MField_Clear
+==================
+*/
+void MField_Clear( mfield_t *edit ) {
+ edit->buffer[0] = 0;
+ edit->cursor = 0;
+ edit->scroll = 0;
+}
+
+/*
+==================
+MenuField_Init
+==================
+*/
+void MenuField_Init( menufield_s* m ) {
+ int l;
+ int w;
+ int h;
+
+ MField_Clear( &m->field );
+
+ if (m->generic.flags & QMF_SMALLFONT)
+ {
+ w = SMALLCHAR_WIDTH;
+ h = SMALLCHAR_HEIGHT;
+ }
+ else
+ {
+ w = BIGCHAR_WIDTH;
+ h = BIGCHAR_HEIGHT;
+ }
+
+ if (m->generic.name) {
+ l = (strlen( m->generic.name )+1) * w;
+ }
+ else {
+ l = 0;
+ }
+
+ m->generic.left = m->generic.x - l;
+ m->generic.top = m->generic.y;
+ m->generic.right = m->generic.x + w + m->field.widthInChars*w;
+ m->generic.bottom = m->generic.y + h;
+}
+
+/*
+==================
+MenuField_Draw
+==================
+*/
+void MenuField_Draw( menufield_s *f )
+{
+ int x;
+ int y;
+ int w;
+ int h;
+ int style;
+ qboolean focus;
+ float *color;
+
+ x = f->generic.x;
+ y = f->generic.y;
+
+ if (f->generic.flags & QMF_SMALLFONT)
+ {
+ w = SMALLCHAR_WIDTH;
+ h = SMALLCHAR_HEIGHT;
+ style = UI_SMALLFONT;
+ }
+ else
+ {
+ w = BIGCHAR_WIDTH;
+ h = BIGCHAR_HEIGHT;
+ style = UI_BIGFONT;
+ }
+
+ if (Menu_ItemAtCursor( f->generic.parent ) == f) {
+ focus = qtrue;
+ style |= UI_PULSE;
+ }
+ else {
+ focus = qfalse;
+ }
+
+ if (f->generic.flags & QMF_GRAYED)
+ color = text_color_disabled;
+ else if (focus)
+ color = text_color_highlight;
+ else
+ color = text_color_normal;
+
+ if ( focus )
+ {
+ // draw cursor
+ UI_FillRect( f->generic.left, f->generic.top, f->generic.right-f->generic.left+1, f->generic.bottom-f->generic.top+1, listbar_color );
+ UI_DrawChar( x, y, 13, UI_CENTER|UI_BLINK|style, color);
+ }
+
+ if ( f->generic.name ) {
+ UI_DrawString( x - w, y, f->generic.name, style|UI_RIGHT, color );
+ }
+
+ MField_Draw( &f->field, x + w, y, style, color );
+}
+
+/*
+==================
+MenuField_Key
+==================
+*/
+sfxHandle_t MenuField_Key( menufield_s* m, int* key )
+{
+ int keycode;
+
+ keycode = *key;
+
+ switch ( keycode )
+ {
+ case K_KP_ENTER:
+ case K_ENTER:
+ case K_JOY1:
+ case K_JOY2:
+ case K_JOY3:
+ case K_JOY4:
+ // have enter go to next cursor point
+ *key = K_TAB;
+ break;
+
+ case K_TAB:
+ case K_KP_DOWNARROW:
+ case K_DOWNARROW:
+ case K_KP_UPARROW:
+ case K_UPARROW:
+ break;
+
+ default:
+ if ( keycode & K_CHAR_FLAG )
+ {
+ keycode &= ~K_CHAR_FLAG;
+
+ if ((m->generic.flags & QMF_UPPERCASE) && Q_islower( keycode ))
+ keycode -= 'a' - 'A';
+ else if ((m->generic.flags & QMF_LOWERCASE) && Q_isupper( keycode ))
+ keycode -= 'A' - 'a';
+ else if ((m->generic.flags & QMF_NUMBERSONLY) && Q_isalpha( keycode ))
+ return (menu_buzz_sound);
+
+ MField_CharEvent( &m->field, keycode);
+ }
+ else
+ MField_KeyDownEvent( &m->field, keycode );
+ break;
+ }
+
+ return (0);
+}
+
+
diff --git a/code/q3_ui/ui_mods.c b/code/q3_ui/ui_mods.c
new file mode 100755
index 0000000..2c6b82d
--- /dev/null
+++ b/code/q3_ui/ui_mods.c
@@ -0,0 +1,283 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#include "ui_local.h"
+
+#define ART_BACK0 "menu/art/back_0"
+#define ART_BACK1 "menu/art/back_1"
+#define ART_FIGHT0 "menu/art/load_0"
+#define ART_FIGHT1 "menu/art/load_1"
+#define ART_FRAMEL "menu/art/frame2_l"
+#define ART_FRAMER "menu/art/frame1_r"
+
+#define MAX_MODS 64
+#define NAMEBUFSIZE ( MAX_MODS * 48 )
+#define GAMEBUFSIZE ( MAX_MODS * 16 )
+
+#define ID_BACK 10
+#define ID_GO 11
+#define ID_LIST 12
+
+
+typedef struct {
+ menuframework_s menu;
+
+ menutext_s banner;
+ menubitmap_s framel;
+ menubitmap_s framer;
+
+ menulist_s list;
+
+ menubitmap_s back;
+ menubitmap_s go;
+
+ char description[NAMEBUFSIZE];
+ char fs_game[GAMEBUFSIZE];
+
+ char *descriptionPtr;
+ char *fs_gamePtr;
+
+ char *descriptionList[MAX_MODS];
+ char *fs_gameList[MAX_MODS];
+} mods_t;
+
+static mods_t s_mods;
+
+
+/*
+===============
+UI_Mods_MenuEvent
+===============
+*/
+static void UI_Mods_MenuEvent( void *ptr, int event ) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+
+ switch ( ((menucommon_s*)ptr)->id ) {
+ case ID_GO:
+ trap_Cvar_Set( "fs_game", s_mods.fs_gameList[s_mods.list.curvalue] );
+ trap_Cmd_ExecuteText( EXEC_APPEND, "vid_restart;" );
+ UI_PopMenu();
+ break;
+
+ case ID_BACK:
+ UI_PopMenu();
+ break;
+ }
+}
+
+
+/*
+===============
+UI_Mods_ParseInfos
+===============
+*/
+static void UI_Mods_ParseInfos( char *modDir, char *modDesc ) {
+ s_mods.fs_gameList[s_mods.list.numitems] = s_mods.fs_gamePtr;
+ Q_strncpyz( s_mods.fs_gamePtr, modDir, 16 );
+
+ s_mods.descriptionList[s_mods.list.numitems] = s_mods.descriptionPtr;
+ Q_strncpyz( s_mods.descriptionPtr, modDesc, 48 );
+
+ s_mods.list.itemnames[s_mods.list.numitems] = s_mods.descriptionPtr;
+ s_mods.descriptionPtr += strlen( s_mods.descriptionPtr ) + 1;
+ s_mods.fs_gamePtr += strlen( s_mods.fs_gamePtr ) + 1;
+ s_mods.list.numitems++;
+}
+
+
+#if 0 // bk001204 - unused
+/*
+===============
+UI_Mods_LoadModsFromFile
+===============
+*/
+static void UI_Mods_LoadModsFromFile( char *filename ) {
+ int len;
+ fileHandle_t f;
+ char buf[1024];
+
+ len = trap_FS_FOpenFile( filename, &f, FS_READ );
+ if ( !f ) {
+ trap_Print( va( S_COLOR_RED "file not found: %s\n", filename ) );
+ return;
+ }
+ if ( len >= sizeof(buf) ) {
+ trap_Print( va( S_COLOR_RED "file too large: %s is %i, max allowed is %i", filename, len, sizeof(buf) ) );
+ trap_FS_FCloseFile( f );
+ return;
+ }
+
+ trap_FS_Read( buf, len, f );
+ buf[len] = 0;
+ trap_FS_FCloseFile( f );
+
+ len = strlen( filename );
+ if( !Q_stricmp(filename + len - 4,".mod") ) {
+ filename[len-4] = '\0';
+ }
+
+ UI_Mods_ParseInfos( filename, buf );
+}
+#endif
+
+
+/*
+===============
+UI_Mods_LoadMods
+===============
+*/
+static void UI_Mods_LoadMods( void ) {
+ int numdirs;
+ char dirlist[2048];
+ char *dirptr;
+ char *descptr;
+ int i;
+ int dirlen;
+
+ s_mods.list.itemnames = (const char **)s_mods.descriptionList;
+ s_mods.descriptionPtr = s_mods.description;
+ s_mods.fs_gamePtr = s_mods.fs_game;
+
+ // always start off with baseq3
+ s_mods.list.numitems = 1;
+ s_mods.list.itemnames[0] = s_mods.descriptionList[0] = "Quake III Arena";
+ s_mods.fs_gameList[0] = "";
+
+ numdirs = trap_FS_GetFileList( "$modlist", "", dirlist, sizeof(dirlist) );
+ dirptr = dirlist;
+ for( i = 0; i < numdirs; i++ ) {
+ dirlen = strlen( dirptr ) + 1;
+ descptr = dirptr + dirlen;
+ UI_Mods_ParseInfos( dirptr, descptr);
+ dirptr += dirlen + strlen(descptr) + 1;
+ }
+
+ trap_Print( va( "%i mods parsed\n", s_mods.list.numitems ) );
+ if (s_mods.list.numitems > MAX_MODS) {
+ s_mods.list.numitems = MAX_MODS;
+ }
+}
+
+
+/*
+===============
+UI_Mods_MenuInit
+===============
+*/
+static void UI_Mods_MenuInit( void ) {
+ UI_ModsMenu_Cache();
+
+ memset( &s_mods, 0 ,sizeof(mods_t) );
+ s_mods.menu.wrapAround = qtrue;
+ s_mods.menu.fullscreen = qtrue;
+
+ s_mods.banner.generic.type = MTYPE_BTEXT;
+ s_mods.banner.generic.x = 320;
+ s_mods.banner.generic.y = 16;
+ s_mods.banner.string = "MODS";
+ s_mods.banner.color = color_white;
+ s_mods.banner.style = UI_CENTER;
+
+ s_mods.framel.generic.type = MTYPE_BITMAP;
+ s_mods.framel.generic.name = ART_FRAMEL;
+ s_mods.framel.generic.flags = QMF_INACTIVE;
+ s_mods.framel.generic.x = 0;
+ s_mods.framel.generic.y = 78;
+ s_mods.framel.width = 256;
+ s_mods.framel.height = 329;
+
+ s_mods.framer.generic.type = MTYPE_BITMAP;
+ s_mods.framer.generic.name = ART_FRAMER;
+ s_mods.framer.generic.flags = QMF_INACTIVE;
+ s_mods.framer.generic.x = 376;
+ s_mods.framer.generic.y = 76;
+ s_mods.framer.width = 256;
+ s_mods.framer.height = 334;
+
+ s_mods.back.generic.type = MTYPE_BITMAP;
+ s_mods.back.generic.name = ART_BACK0;
+ s_mods.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_mods.back.generic.id = ID_BACK;
+ s_mods.back.generic.callback = UI_Mods_MenuEvent;
+ s_mods.back.generic.x = 0;
+ s_mods.back.generic.y = 480-64;
+ s_mods.back.width = 128;
+ s_mods.back.height = 64;
+ s_mods.back.focuspic = ART_BACK1;
+
+ s_mods.go.generic.type = MTYPE_BITMAP;
+ s_mods.go.generic.name = ART_FIGHT0;
+ s_mods.go.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_mods.go.generic.id = ID_GO;
+ s_mods.go.generic.callback = UI_Mods_MenuEvent;
+ s_mods.go.generic.x = 640;
+ s_mods.go.generic.y = 480-64;
+ s_mods.go.width = 128;
+ s_mods.go.height = 64;
+ s_mods.go.focuspic = ART_FIGHT1;
+
+ // scan for mods
+ s_mods.list.generic.type = MTYPE_SCROLLLIST;
+ s_mods.list.generic.flags = QMF_PULSEIFFOCUS|QMF_CENTER_JUSTIFY;
+ s_mods.list.generic.callback = UI_Mods_MenuEvent;
+ s_mods.list.generic.id = ID_LIST;
+ s_mods.list.generic.x = 320;
+ s_mods.list.generic.y = 130;
+ s_mods.list.width = 48;
+ s_mods.list.height = 14;
+
+ UI_Mods_LoadMods();
+
+ Menu_AddItem( &s_mods.menu, &s_mods.banner );
+ Menu_AddItem( &s_mods.menu, &s_mods.framel );
+ Menu_AddItem( &s_mods.menu, &s_mods.framer );
+ Menu_AddItem( &s_mods.menu, &s_mods.list );
+ Menu_AddItem( &s_mods.menu, &s_mods.back );
+ Menu_AddItem( &s_mods.menu, &s_mods.go );
+}
+
+/*
+=================
+UI_Mods_Cache
+=================
+*/
+void UI_ModsMenu_Cache( void ) {
+ trap_R_RegisterShaderNoMip( ART_BACK0 );
+ trap_R_RegisterShaderNoMip( ART_BACK1 );
+ trap_R_RegisterShaderNoMip( ART_FIGHT0 );
+ trap_R_RegisterShaderNoMip( ART_FIGHT1 );
+ trap_R_RegisterShaderNoMip( ART_FRAMEL );
+ trap_R_RegisterShaderNoMip( ART_FRAMER );
+}
+
+
+/*
+===============
+UI_ModsMenu
+===============
+*/
+void UI_ModsMenu( void ) {
+ UI_Mods_MenuInit();
+ UI_PushMenu( &s_mods.menu );
+}
diff --git a/code/q3_ui/ui_network.c b/code/q3_ui/ui_network.c
new file mode 100755
index 0000000..30019e8
--- /dev/null
+++ b/code/q3_ui/ui_network.c
@@ -0,0 +1,281 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*
+=======================================================================
+
+NETWORK OPTIONS MENU
+
+=======================================================================
+*/
+
+#include "ui_local.h"
+
+
+#define ART_FRAMEL "menu/art/frame2_l"
+#define ART_FRAMER "menu/art/frame1_r"
+#define ART_BACK0 "menu/art/back_0"
+#define ART_BACK1 "menu/art/back_1"
+
+#define ID_GRAPHICS 10
+#define ID_DISPLAY 11
+#define ID_SOUND 12
+#define ID_NETWORK 13
+#define ID_RATE 14
+#define ID_BACK 15
+
+
+static const char *rate_items[] = {
+ "<= 28.8K",
+ "33.6K",
+ "56K",
+ "ISDN",
+ "LAN/Cable/xDSL",
+ 0
+};
+
+typedef struct {
+ menuframework_s menu;
+
+ menutext_s banner;
+ menubitmap_s framel;
+ menubitmap_s framer;
+
+ menutext_s graphics;
+ menutext_s display;
+ menutext_s sound;
+ menutext_s network;
+
+ menulist_s rate;
+
+ menubitmap_s back;
+} networkOptionsInfo_t;
+
+static networkOptionsInfo_t networkOptionsInfo;
+
+
+/*
+=================
+UI_NetworkOptionsMenu_Event
+=================
+*/
+static void UI_NetworkOptionsMenu_Event( void* ptr, int event ) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+
+ switch( ((menucommon_s*)ptr)->id ) {
+ case ID_GRAPHICS:
+ UI_PopMenu();
+ UI_GraphicsOptionsMenu();
+ break;
+
+ case ID_DISPLAY:
+ UI_PopMenu();
+ UI_DisplayOptionsMenu();
+ break;
+
+ case ID_SOUND:
+ UI_PopMenu();
+ UI_SoundOptionsMenu();
+ break;
+
+ case ID_NETWORK:
+ break;
+
+ case ID_RATE:
+ if( networkOptionsInfo.rate.curvalue == 0 ) {
+ trap_Cvar_SetValue( "rate", 2500 );
+ }
+ else if( networkOptionsInfo.rate.curvalue == 1 ) {
+ trap_Cvar_SetValue( "rate", 3000 );
+ }
+ else if( networkOptionsInfo.rate.curvalue == 2 ) {
+ trap_Cvar_SetValue( "rate", 4000 );
+ }
+ else if( networkOptionsInfo.rate.curvalue == 3 ) {
+ trap_Cvar_SetValue( "rate", 5000 );
+ }
+ else if( networkOptionsInfo.rate.curvalue == 4 ) {
+ trap_Cvar_SetValue( "rate", 25000 );
+ }
+ break;
+
+ case ID_BACK:
+ UI_PopMenu();
+ break;
+ }
+}
+
+
+/*
+===============
+UI_NetworkOptionsMenu_Init
+===============
+*/
+static void UI_NetworkOptionsMenu_Init( void ) {
+ int y;
+ int rate;
+
+ memset( &networkOptionsInfo, 0, sizeof(networkOptionsInfo) );
+
+ UI_NetworkOptionsMenu_Cache();
+ networkOptionsInfo.menu.wrapAround = qtrue;
+ networkOptionsInfo.menu.fullscreen = qtrue;
+
+ networkOptionsInfo.banner.generic.type = MTYPE_BTEXT;
+ networkOptionsInfo.banner.generic.flags = QMF_CENTER_JUSTIFY;
+ networkOptionsInfo.banner.generic.x = 320;
+ networkOptionsInfo.banner.generic.y = 16;
+ networkOptionsInfo.banner.string = "SYSTEM SETUP";
+ networkOptionsInfo.banner.color = color_white;
+ networkOptionsInfo.banner.style = UI_CENTER;
+
+ networkOptionsInfo.framel.generic.type = MTYPE_BITMAP;
+ networkOptionsInfo.framel.generic.name = ART_FRAMEL;
+ networkOptionsInfo.framel.generic.flags = QMF_INACTIVE;
+ networkOptionsInfo.framel.generic.x = 0;
+ networkOptionsInfo.framel.generic.y = 78;
+ networkOptionsInfo.framel.width = 256;
+ networkOptionsInfo.framel.height = 329;
+
+ networkOptionsInfo.framer.generic.type = MTYPE_BITMAP;
+ networkOptionsInfo.framer.generic.name = ART_FRAMER;
+ networkOptionsInfo.framer.generic.flags = QMF_INACTIVE;
+ networkOptionsInfo.framer.generic.x = 376;
+ networkOptionsInfo.framer.generic.y = 76;
+ networkOptionsInfo.framer.width = 256;
+ networkOptionsInfo.framer.height = 334;
+
+ networkOptionsInfo.graphics.generic.type = MTYPE_PTEXT;
+ networkOptionsInfo.graphics.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ networkOptionsInfo.graphics.generic.id = ID_GRAPHICS;
+ networkOptionsInfo.graphics.generic.callback = UI_NetworkOptionsMenu_Event;
+ networkOptionsInfo.graphics.generic.x = 216;
+ networkOptionsInfo.graphics.generic.y = 240 - 2 * PROP_HEIGHT;
+ networkOptionsInfo.graphics.string = "GRAPHICS";
+ networkOptionsInfo.graphics.style = UI_RIGHT;
+ networkOptionsInfo.graphics.color = color_red;
+
+ networkOptionsInfo.display.generic.type = MTYPE_PTEXT;
+ networkOptionsInfo.display.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ networkOptionsInfo.display.generic.id = ID_DISPLAY;
+ networkOptionsInfo.display.generic.callback = UI_NetworkOptionsMenu_Event;
+ networkOptionsInfo.display.generic.x = 216;
+ networkOptionsInfo.display.generic.y = 240 - PROP_HEIGHT;
+ networkOptionsInfo.display.string = "DISPLAY";
+ networkOptionsInfo.display.style = UI_RIGHT;
+ networkOptionsInfo.display.color = color_red;
+
+ networkOptionsInfo.sound.generic.type = MTYPE_PTEXT;
+ networkOptionsInfo.sound.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ networkOptionsInfo.sound.generic.id = ID_SOUND;
+ networkOptionsInfo.sound.generic.callback = UI_NetworkOptionsMenu_Event;
+ networkOptionsInfo.sound.generic.x = 216;
+ networkOptionsInfo.sound.generic.y = 240;
+ networkOptionsInfo.sound.string = "SOUND";
+ networkOptionsInfo.sound.style = UI_RIGHT;
+ networkOptionsInfo.sound.color = color_red;
+
+ networkOptionsInfo.network.generic.type = MTYPE_PTEXT;
+ networkOptionsInfo.network.generic.flags = QMF_RIGHT_JUSTIFY;
+ networkOptionsInfo.network.generic.id = ID_NETWORK;
+ networkOptionsInfo.network.generic.callback = UI_NetworkOptionsMenu_Event;
+ networkOptionsInfo.network.generic.x = 216;
+ networkOptionsInfo.network.generic.y = 240 + PROP_HEIGHT;
+ networkOptionsInfo.network.string = "NETWORK";
+ networkOptionsInfo.network.style = UI_RIGHT;
+ networkOptionsInfo.network.color = color_red;
+
+ y = 240 - 1 * (BIGCHAR_HEIGHT+2);
+ networkOptionsInfo.rate.generic.type = MTYPE_SPINCONTROL;
+ networkOptionsInfo.rate.generic.name = "Data Rate:";
+ networkOptionsInfo.rate.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ networkOptionsInfo.rate.generic.callback = UI_NetworkOptionsMenu_Event;
+ networkOptionsInfo.rate.generic.id = ID_RATE;
+ networkOptionsInfo.rate.generic.x = 400;
+ networkOptionsInfo.rate.generic.y = y;
+ networkOptionsInfo.rate.itemnames = rate_items;
+
+ networkOptionsInfo.back.generic.type = MTYPE_BITMAP;
+ networkOptionsInfo.back.generic.name = ART_BACK0;
+ networkOptionsInfo.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ networkOptionsInfo.back.generic.callback = UI_NetworkOptionsMenu_Event;
+ networkOptionsInfo.back.generic.id = ID_BACK;
+ networkOptionsInfo.back.generic.x = 0;
+ networkOptionsInfo.back.generic.y = 480-64;
+ networkOptionsInfo.back.width = 128;
+ networkOptionsInfo.back.height = 64;
+ networkOptionsInfo.back.focuspic = ART_BACK1;
+
+ Menu_AddItem( &networkOptionsInfo.menu, ( void * ) &networkOptionsInfo.banner );
+ Menu_AddItem( &networkOptionsInfo.menu, ( void * ) &networkOptionsInfo.framel );
+ Menu_AddItem( &networkOptionsInfo.menu, ( void * ) &networkOptionsInfo.framer );
+ Menu_AddItem( &networkOptionsInfo.menu, ( void * ) &networkOptionsInfo.graphics );
+ Menu_AddItem( &networkOptionsInfo.menu, ( void * ) &networkOptionsInfo.display );
+ Menu_AddItem( &networkOptionsInfo.menu, ( void * ) &networkOptionsInfo.sound );
+ Menu_AddItem( &networkOptionsInfo.menu, ( void * ) &networkOptionsInfo.network );
+ Menu_AddItem( &networkOptionsInfo.menu, ( void * ) &networkOptionsInfo.rate );
+ Menu_AddItem( &networkOptionsInfo.menu, ( void * ) &networkOptionsInfo.back );
+
+ rate = trap_Cvar_VariableValue( "rate" );
+ if( rate <= 2500 ) {
+ networkOptionsInfo.rate.curvalue = 0;
+ }
+ else if( rate <= 3000 ) {
+ networkOptionsInfo.rate.curvalue = 1;
+ }
+ else if( rate <= 4000 ) {
+ networkOptionsInfo.rate.curvalue = 2;
+ }
+ else if( rate <= 5000 ) {
+ networkOptionsInfo.rate.curvalue = 3;
+ }
+ else {
+ networkOptionsInfo.rate.curvalue = 4;
+ }
+}
+
+
+/*
+===============
+UI_NetworkOptionsMenu_Cache
+===============
+*/
+void UI_NetworkOptionsMenu_Cache( void ) {
+ trap_R_RegisterShaderNoMip( ART_FRAMEL );
+ trap_R_RegisterShaderNoMip( ART_FRAMER );
+ trap_R_RegisterShaderNoMip( ART_BACK0 );
+ trap_R_RegisterShaderNoMip( ART_BACK1 );
+}
+
+
+/*
+===============
+UI_NetworkOptionsMenu
+===============
+*/
+void UI_NetworkOptionsMenu( void ) {
+ UI_NetworkOptionsMenu_Init();
+ UI_PushMenu( &networkOptionsInfo.menu );
+ Menu_SetCursorToItem( &networkOptionsInfo.menu, &networkOptionsInfo.network );
+}
diff --git a/code/q3_ui/ui_options.c b/code/q3_ui/ui_options.c
new file mode 100755
index 0000000..d65afb0
--- /dev/null
+++ b/code/q3_ui/ui_options.c
@@ -0,0 +1,229 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+/*
+=======================================================================
+
+SYSTEM CONFIGURATION MENU
+
+=======================================================================
+*/
+
+#include "ui_local.h"
+
+
+#define ART_FRAMEL "menu/art/frame2_l"
+#define ART_FRAMER "menu/art/frame1_r"
+#define ART_BACK0 "menu/art/back_0"
+#define ART_BACK1 "menu/art/back_1"
+
+#define ID_GRAPHICS 10
+#define ID_DISPLAY 11
+#define ID_SOUND 12
+#define ID_NETWORK 13
+#define ID_BACK 14
+
+#define VERTICAL_SPACING 34
+
+typedef struct {
+ menuframework_s menu;
+
+ menutext_s banner;
+ menubitmap_s framel;
+ menubitmap_s framer;
+
+ menutext_s graphics;
+ menutext_s display;
+ menutext_s sound;
+ menutext_s network;
+ menubitmap_s back;
+} optionsmenu_t;
+
+static optionsmenu_t s_options;
+
+
+/*
+=================
+Options_Event
+=================
+*/
+static void Options_Event( void* ptr, int event ) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+
+ switch( ((menucommon_s*)ptr)->id ) {
+ case ID_GRAPHICS:
+ UI_GraphicsOptionsMenu();
+ break;
+
+ case ID_DISPLAY:
+ UI_DisplayOptionsMenu();
+ break;
+
+ case ID_SOUND:
+ UI_SoundOptionsMenu();
+ break;
+
+ case ID_NETWORK:
+ UI_NetworkOptionsMenu();
+ break;
+
+ case ID_BACK:
+ UI_PopMenu();
+ break;
+ }
+}
+
+
+/*
+===============
+SystemConfig_Cache
+===============
+*/
+void SystemConfig_Cache( void ) {
+ trap_R_RegisterShaderNoMip( ART_FRAMEL );
+ trap_R_RegisterShaderNoMip( ART_FRAMER );
+ trap_R_RegisterShaderNoMip( ART_BACK0 );
+ trap_R_RegisterShaderNoMip( ART_BACK1 );
+}
+
+/*
+===============
+Options_MenuInit
+===============
+*/
+void Options_MenuInit( void ) {
+ int y;
+ uiClientState_t cstate;
+
+ memset( &s_options, 0, sizeof(optionsmenu_t) );
+
+ SystemConfig_Cache();
+ s_options.menu.wrapAround = qtrue;
+
+ trap_GetClientState( &cstate );
+ if ( cstate.connState >= CA_CONNECTED ) {
+ s_options.menu.fullscreen = qfalse;
+ }
+ else {
+ s_options.menu.fullscreen = qtrue;
+ }
+
+ s_options.banner.generic.type = MTYPE_BTEXT;
+ s_options.banner.generic.flags = QMF_CENTER_JUSTIFY;
+ s_options.banner.generic.x = 320;
+ s_options.banner.generic.y = 16;
+ s_options.banner.string = "SYSTEM SETUP";
+ s_options.banner.color = color_white;
+ s_options.banner.style = UI_CENTER;
+
+ s_options.framel.generic.type = MTYPE_BITMAP;
+ s_options.framel.generic.name = ART_FRAMEL;
+ s_options.framel.generic.flags = QMF_INACTIVE;
+ s_options.framel.generic.x = 8;
+ s_options.framel.generic.y = 76;
+ s_options.framel.width = 256;
+ s_options.framel.height = 334;
+
+ s_options.framer.generic.type = MTYPE_BITMAP;
+ s_options.framer.generic.name = ART_FRAMER;
+ s_options.framer.generic.flags = QMF_INACTIVE;
+ s_options.framer.generic.x = 376;
+ s_options.framer.generic.y = 76;
+ s_options.framer.width = 256;
+ s_options.framer.height = 334;
+
+ y = 168;
+ s_options.graphics.generic.type = MTYPE_PTEXT;
+ s_options.graphics.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_options.graphics.generic.callback = Options_Event;
+ s_options.graphics.generic.id = ID_GRAPHICS;
+ s_options.graphics.generic.x = 320;
+ s_options.graphics.generic.y = y;
+ s_options.graphics.string = "GRAPHICS";
+ s_options.graphics.color = color_red;
+ s_options.graphics.style = UI_CENTER;
+
+ y += VERTICAL_SPACING;
+ s_options.display.generic.type = MTYPE_PTEXT;
+ s_options.display.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_options.display.generic.callback = Options_Event;
+ s_options.display.generic.id = ID_DISPLAY;
+ s_options.display.generic.x = 320;
+ s_options.display.generic.y = y;
+ s_options.display.string = "DISPLAY";
+ s_options.display.color = color_red;
+ s_options.display.style = UI_CENTER;
+
+ y += VERTICAL_SPACING;
+ s_options.sound.generic.type = MTYPE_PTEXT;
+ s_options.sound.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_options.sound.generic.callback = Options_Event;
+ s_options.sound.generic.id = ID_SOUND;
+ s_options.sound.generic.x = 320;
+ s_options.sound.generic.y = y;
+ s_options.sound.string = "SOUND";
+ s_options.sound.color = color_red;
+ s_options.sound.style = UI_CENTER;
+
+ y += VERTICAL_SPACING;
+ s_options.network.generic.type = MTYPE_PTEXT;
+ s_options.network.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_options.network.generic.callback = Options_Event;
+ s_options.network.generic.id = ID_NETWORK;
+ s_options.network.generic.x = 320;
+ s_options.network.generic.y = y;
+ s_options.network.string = "NETWORK";
+ s_options.network.color = color_red;
+ s_options.network.style = UI_CENTER;
+
+ s_options.back.generic.type = MTYPE_BITMAP;
+ s_options.back.generic.name = ART_BACK0;
+ s_options.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_options.back.generic.callback = Options_Event;
+ s_options.back.generic.id = ID_BACK;
+ s_options.back.generic.x = 0;
+ s_options.back.generic.y = 480-64;
+ s_options.back.width = 128;
+ s_options.back.height = 64;
+ s_options.back.focuspic = ART_BACK1;
+
+ Menu_AddItem( &s_options.menu, ( void * ) &s_options.banner );
+ Menu_AddItem( &s_options.menu, ( void * ) &s_options.framel );
+ Menu_AddItem( &s_options.menu, ( void * ) &s_options.framer );
+ Menu_AddItem( &s_options.menu, ( void * ) &s_options.graphics );
+ Menu_AddItem( &s_options.menu, ( void * ) &s_options.display );
+ Menu_AddItem( &s_options.menu, ( void * ) &s_options.sound );
+ Menu_AddItem( &s_options.menu, ( void * ) &s_options.network );
+ Menu_AddItem( &s_options.menu, ( void * ) &s_options.back );
+}
+
+
+/*
+===============
+UI_SystemConfigMenu
+===============
+*/
+void UI_SystemConfigMenu( void ) {
+ Options_MenuInit();
+ UI_PushMenu ( &s_options.menu );
+}
diff --git a/code/q3_ui/ui_playermodel.c b/code/q3_ui/ui_playermodel.c
new file mode 100755
index 0000000..316d5ec
--- /dev/null
+++ b/code/q3_ui/ui_playermodel.c
@@ -0,0 +1,731 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#include "ui_local.h"
+
+#define MODEL_BACK0 "menu/art/back_0"
+#define MODEL_BACK1 "menu/art/back_1"
+#define MODEL_SELECT "menu/art/opponents_select"
+#define MODEL_SELECTED "menu/art/opponents_selected"
+#define MODEL_FRAMEL "menu/art/frame1_l"
+#define MODEL_FRAMER "menu/art/frame1_r"
+#define MODEL_PORTS "menu/art/player_models_ports"
+#define MODEL_ARROWS "menu/art/gs_arrows_0"
+#define MODEL_ARROWSL "menu/art/gs_arrows_l"
+#define MODEL_ARROWSR "menu/art/gs_arrows_r"
+
+#define LOW_MEMORY (5 * 1024 * 1024)
+
+static char* playermodel_artlist[] =
+{
+ MODEL_BACK0,
+ MODEL_BACK1,
+ MODEL_SELECT,
+ MODEL_SELECTED,
+ MODEL_FRAMEL,
+ MODEL_FRAMER,
+ MODEL_PORTS,
+ MODEL_ARROWS,
+ MODEL_ARROWSL,
+ MODEL_ARROWSR,
+ NULL
+};
+
+#define PLAYERGRID_COLS 4
+#define PLAYERGRID_ROWS 4
+#define MAX_MODELSPERPAGE (PLAYERGRID_ROWS*PLAYERGRID_COLS)
+
+#define MAX_PLAYERMODELS 256
+
+#define ID_PLAYERPIC0 0
+#define ID_PLAYERPIC1 1
+#define ID_PLAYERPIC2 2
+#define ID_PLAYERPIC3 3
+#define ID_PLAYERPIC4 4
+#define ID_PLAYERPIC5 5
+#define ID_PLAYERPIC6 6
+#define ID_PLAYERPIC7 7
+#define ID_PLAYERPIC8 8
+#define ID_PLAYERPIC9 9
+#define ID_PLAYERPIC10 10
+#define ID_PLAYERPIC11 11
+#define ID_PLAYERPIC12 12
+#define ID_PLAYERPIC13 13
+#define ID_PLAYERPIC14 14
+#define ID_PLAYERPIC15 15
+#define ID_PREVPAGE 100
+#define ID_NEXTPAGE 101
+#define ID_BACK 102
+
+typedef struct
+{
+ menuframework_s menu;
+ menubitmap_s pics[MAX_MODELSPERPAGE];
+ menubitmap_s picbuttons[MAX_MODELSPERPAGE];
+ menubitmap_s framel;
+ menubitmap_s framer;
+ menubitmap_s ports;
+ menutext_s banner;
+ menubitmap_s back;
+ menubitmap_s player;
+ menubitmap_s arrows;
+ menubitmap_s left;
+ menubitmap_s right;
+ menutext_s modelname;
+ menutext_s skinname;
+ menutext_s playername;
+ playerInfo_t playerinfo;
+ int nummodels;
+ char modelnames[MAX_PLAYERMODELS][128];
+ int modelpage;
+ int numpages;
+ char modelskin[64];
+ int selectedmodel;
+} playermodel_t;
+
+static playermodel_t s_playermodel;
+
+/*
+=================
+PlayerModel_UpdateGrid
+=================
+*/
+static void PlayerModel_UpdateGrid( void )
+{
+ int i;
+ int j;
+
+ j = s_playermodel.modelpage * MAX_MODELSPERPAGE;
+ for (i=0; i<PLAYERGRID_ROWS*PLAYERGRID_COLS; i++,j++)
+ {
+ if (j < s_playermodel.nummodels)
+ {
+ // model/skin portrait
+ s_playermodel.pics[i].generic.name = s_playermodel.modelnames[j];
+ s_playermodel.picbuttons[i].generic.flags &= ~QMF_INACTIVE;
+ }
+ else
+ {
+ // dead slot
+ s_playermodel.pics[i].generic.name = NULL;
+ s_playermodel.picbuttons[i].generic.flags |= QMF_INACTIVE;
+ }
+
+ s_playermodel.pics[i].generic.flags &= ~QMF_HIGHLIGHT;
+ s_playermodel.pics[i].shader = 0;
+ s_playermodel.picbuttons[i].generic.flags |= QMF_PULSEIFFOCUS;
+ }
+
+ if (s_playermodel.selectedmodel/MAX_MODELSPERPAGE == s_playermodel.modelpage)
+ {
+ // set selected model
+ i = s_playermodel.selectedmodel % MAX_MODELSPERPAGE;
+
+ s_playermodel.pics[i].generic.flags |= QMF_HIGHLIGHT;
+ s_playermodel.picbuttons[i].generic.flags &= ~QMF_PULSEIFFOCUS;
+ }
+
+ if (s_playermodel.numpages > 1)
+ {
+ if (s_playermodel.modelpage > 0)
+ s_playermodel.left.generic.flags &= ~QMF_INACTIVE;
+ else
+ s_playermodel.left.generic.flags |= QMF_INACTIVE;
+
+ if (s_playermodel.modelpage < s_playermodel.numpages-1)
+ s_playermodel.right.generic.flags &= ~QMF_INACTIVE;
+ else
+ s_playermodel.right.generic.flags |= QMF_INACTIVE;
+ }
+ else
+ {
+ // hide left/right markers
+ s_playermodel.left.generic.flags |= QMF_INACTIVE;
+ s_playermodel.right.generic.flags |= QMF_INACTIVE;
+ }
+}
+
+/*
+=================
+PlayerModel_UpdateModel
+=================
+*/
+static void PlayerModel_UpdateModel( void )
+{
+ vec3_t viewangles;
+ vec3_t moveangles;
+
+ memset( &s_playermodel.playerinfo, 0, sizeof(playerInfo_t) );
+
+ viewangles[YAW] = 180 - 30;
+ viewangles[PITCH] = 0;
+ viewangles[ROLL] = 0;
+ VectorClear( moveangles );
+
+ UI_PlayerInfo_SetModel( &s_playermodel.playerinfo, s_playermodel.modelskin );
+ UI_PlayerInfo_SetInfo( &s_playermodel.playerinfo, LEGS_IDLE, TORSO_STAND, viewangles, moveangles, WP_MACHINEGUN, qfalse );
+}
+
+/*
+=================
+PlayerModel_SaveChanges
+=================
+*/
+static void PlayerModel_SaveChanges( void )
+{
+ trap_Cvar_Set( "model", s_playermodel.modelskin );
+ trap_Cvar_Set( "headmodel", s_playermodel.modelskin );
+ trap_Cvar_Set( "team_model", s_playermodel.modelskin );
+ trap_Cvar_Set( "team_headmodel", s_playermodel.modelskin );
+}
+
+/*
+=================
+PlayerModel_MenuEvent
+=================
+*/
+static void PlayerModel_MenuEvent( void* ptr, int event )
+{
+ if (event != QM_ACTIVATED)
+ return;
+
+ switch (((menucommon_s*)ptr)->id)
+ {
+ case ID_PREVPAGE:
+ if (s_playermodel.modelpage > 0)
+ {
+ s_playermodel.modelpage--;
+ PlayerModel_UpdateGrid();
+ }
+ break;
+
+ case ID_NEXTPAGE:
+ if (s_playermodel.modelpage < s_playermodel.numpages-1)
+ {
+ s_playermodel.modelpage++;
+ PlayerModel_UpdateGrid();
+ }
+ break;
+
+ case ID_BACK:
+ PlayerModel_SaveChanges();
+ UI_PopMenu();
+ break;
+ }
+}
+
+/*
+=================
+PlayerModel_MenuKey
+=================
+*/
+static sfxHandle_t PlayerModel_MenuKey( int key )
+{
+ menucommon_s* m;
+ int picnum;
+
+ switch (key)
+ {
+ case K_KP_LEFTARROW:
+ case K_LEFTARROW:
+ m = Menu_ItemAtCursor(&s_playermodel.menu);
+ picnum = m->id - ID_PLAYERPIC0;
+ if (picnum >= 0 && picnum <= 15)
+ {
+ if (picnum > 0)
+ {
+ Menu_SetCursor(&s_playermodel.menu,s_playermodel.menu.cursor-1);
+ return (menu_move_sound);
+
+ }
+ else if (s_playermodel.modelpage > 0)
+ {
+ s_playermodel.modelpage--;
+ Menu_SetCursor(&s_playermodel.menu,s_playermodel.menu.cursor+15);
+ PlayerModel_UpdateGrid();
+ return (menu_move_sound);
+ }
+ else
+ return (menu_buzz_sound);
+ }
+ break;
+
+ case K_KP_RIGHTARROW:
+ case K_RIGHTARROW:
+ m = Menu_ItemAtCursor(&s_playermodel.menu);
+ picnum = m->id - ID_PLAYERPIC0;
+ if (picnum >= 0 && picnum <= 15)
+ {
+ if ((picnum < 15) && (s_playermodel.modelpage*MAX_MODELSPERPAGE + picnum+1 < s_playermodel.nummodels))
+ {
+ Menu_SetCursor(&s_playermodel.menu,s_playermodel.menu.cursor+1);
+ return (menu_move_sound);
+ }
+ else if ((picnum == 15) && (s_playermodel.modelpage < s_playermodel.numpages-1))
+ {
+ s_playermodel.modelpage++;
+ Menu_SetCursor(&s_playermodel.menu,s_playermodel.menu.cursor-15);
+ PlayerModel_UpdateGrid();
+ return (menu_move_sound);
+ }
+ else
+ return (menu_buzz_sound);
+ }
+ break;
+
+ case K_MOUSE2:
+ case K_ESCAPE:
+ PlayerModel_SaveChanges();
+ break;
+ }
+
+ return ( Menu_DefaultKey( &s_playermodel.menu, key ) );
+}
+
+/*
+=================
+PlayerModel_PicEvent
+=================
+*/
+static void PlayerModel_PicEvent( void* ptr, int event )
+{
+ int modelnum;
+ int maxlen;
+ char* buffptr;
+ char* pdest;
+ int i;
+
+ if (event != QM_ACTIVATED)
+ return;
+
+ for (i=0; i<PLAYERGRID_ROWS*PLAYERGRID_COLS; i++)
+ {
+ // reset
+ s_playermodel.pics[i].generic.flags &= ~QMF_HIGHLIGHT;
+ s_playermodel.picbuttons[i].generic.flags |= QMF_PULSEIFFOCUS;
+ }
+
+ // set selected
+ i = ((menucommon_s*)ptr)->id - ID_PLAYERPIC0;
+ s_playermodel.pics[i].generic.flags |= QMF_HIGHLIGHT;
+ s_playermodel.picbuttons[i].generic.flags &= ~QMF_PULSEIFFOCUS;
+
+ // get model and strip icon_
+ modelnum = s_playermodel.modelpage*MAX_MODELSPERPAGE + i;
+ buffptr = s_playermodel.modelnames[modelnum] + strlen("models/players/");
+ pdest = strstr(buffptr,"icon_");
+ if (pdest)
+ {
+ // track the whole model/skin name
+ Q_strncpyz(s_playermodel.modelskin,buffptr,pdest-buffptr+1);
+ strcat(s_playermodel.modelskin,pdest + 5);
+
+ // seperate the model name
+ maxlen = pdest-buffptr;
+ if (maxlen > 16)
+ maxlen = 16;
+ Q_strncpyz( s_playermodel.modelname.string, buffptr, maxlen );
+ Q_strupr( s_playermodel.modelname.string );
+
+ // seperate the skin name
+ maxlen = strlen(pdest+5)+1;
+ if (maxlen > 16)
+ maxlen = 16;
+ Q_strncpyz( s_playermodel.skinname.string, pdest+5, maxlen );
+ Q_strupr( s_playermodel.skinname.string );
+
+ s_playermodel.selectedmodel = modelnum;
+
+ if( trap_MemoryRemaining() > LOW_MEMORY ) {
+ PlayerModel_UpdateModel();
+ }
+ }
+}
+
+/*
+=================
+PlayerModel_DrawPlayer
+=================
+*/
+static void PlayerModel_DrawPlayer( void *self )
+{
+ menubitmap_s* b;
+
+ b = (menubitmap_s*) self;
+
+ if( trap_MemoryRemaining() <= LOW_MEMORY ) {
+ UI_DrawProportionalString( b->generic.x, b->generic.y + b->height / 2, "LOW MEMORY", UI_LEFT, color_red );
+ return;
+ }
+
+ UI_DrawPlayer( b->generic.x, b->generic.y, b->width, b->height, &s_playermodel.playerinfo, uis.realtime/2 );
+}
+
+/*
+=================
+PlayerModel_BuildList
+=================
+*/
+static void PlayerModel_BuildList( void )
+{
+ int numdirs;
+ int numfiles;
+ char dirlist[2048];
+ char filelist[2048];
+ char skinname[64];
+ char* dirptr;
+ char* fileptr;
+ int i;
+ int j;
+ int dirlen;
+ int filelen;
+ qboolean precache;
+
+ precache = trap_Cvar_VariableValue("com_buildscript");
+
+ s_playermodel.modelpage = 0;
+ s_playermodel.nummodels = 0;
+
+ // iterate directory of all player models
+ numdirs = trap_FS_GetFileList("models/players", "/", dirlist, 2048 );
+ dirptr = dirlist;
+ for (i=0; i<numdirs && s_playermodel.nummodels < MAX_PLAYERMODELS; i++,dirptr+=dirlen+1)
+ {
+ dirlen = strlen(dirptr);
+
+ if (dirlen && dirptr[dirlen-1]=='/') dirptr[dirlen-1]='\0';
+
+ if (!strcmp(dirptr,".") || !strcmp(dirptr,".."))
+ continue;
+
+ // iterate all skin files in directory
+ numfiles = trap_FS_GetFileList( va("models/players/%s",dirptr), "tga", filelist, 2048 );
+ fileptr = filelist;
+ for (j=0; j<numfiles && s_playermodel.nummodels < MAX_PLAYERMODELS;j++,fileptr+=filelen+1)
+ {
+ filelen = strlen(fileptr);
+
+ COM_StripExtension(fileptr,skinname);
+
+ // look for icon_????
+ if (!Q_stricmpn(skinname,"icon_",5))
+ {
+ Com_sprintf( s_playermodel.modelnames[s_playermodel.nummodels++],
+ sizeof( s_playermodel.modelnames[s_playermodel.nummodels] ),
+ "models/players/%s/%s", dirptr, skinname );
+ //if (s_playermodel.nummodels >= MAX_PLAYERMODELS)
+ // return;
+ }
+
+ if( precache ) {
+ trap_S_RegisterSound( va( "sound/player/announce/%s_wins.wav", skinname), qfalse );
+ }
+ }
+ }
+
+ //APSFIXME - Degenerate no models case
+
+ s_playermodel.numpages = s_playermodel.nummodels/MAX_MODELSPERPAGE;
+ if (s_playermodel.nummodels % MAX_MODELSPERPAGE)
+ s_playermodel.numpages++;
+}
+
+/*
+=================
+PlayerModel_SetMenuItems
+=================
+*/
+static void PlayerModel_SetMenuItems( void )
+{
+ int i;
+ int maxlen;
+ char modelskin[64];
+ char* buffptr;
+ char* pdest;
+
+ // name
+ trap_Cvar_VariableStringBuffer( "name", s_playermodel.playername.string, 16 );
+ Q_CleanStr( s_playermodel.playername.string );
+
+ // model
+ trap_Cvar_VariableStringBuffer( "model", s_playermodel.modelskin, 64 );
+
+ // find model in our list
+ for (i=0; i<s_playermodel.nummodels; i++)
+ {
+ // strip icon_
+ buffptr = s_playermodel.modelnames[i] + strlen("models/players/");
+ pdest = strstr(buffptr,"icon_");
+ if (pdest)
+ {
+ Q_strncpyz(modelskin,buffptr,pdest-buffptr+1);
+ strcat(modelskin,pdest + 5);
+ }
+ else
+ continue;
+
+ if (!Q_stricmp( s_playermodel.modelskin, modelskin ))
+ {
+ // found pic, set selection here
+ s_playermodel.selectedmodel = i;
+ s_playermodel.modelpage = i/MAX_MODELSPERPAGE;
+
+ // seperate the model name
+ maxlen = pdest-buffptr;
+ if (maxlen > 16)
+ maxlen = 16;
+ Q_strncpyz( s_playermodel.modelname.string, buffptr, maxlen );
+ Q_strupr( s_playermodel.modelname.string );
+
+ // seperate the skin name
+ maxlen = strlen(pdest+5)+1;
+ if (maxlen > 16)
+ maxlen = 16;
+ Q_strncpyz( s_playermodel.skinname.string, pdest+5, maxlen );
+ Q_strupr( s_playermodel.skinname.string );
+ break;
+ }
+ }
+}
+
+/*
+=================
+PlayerModel_MenuInit
+=================
+*/
+static void PlayerModel_MenuInit( void )
+{
+ int i;
+ int j;
+ int k;
+ int x;
+ int y;
+ static char playername[32];
+ static char modelname[32];
+ static char skinname[32];
+
+ // zero set all our globals
+ memset( &s_playermodel, 0 ,sizeof(playermodel_t) );
+
+ PlayerModel_Cache();
+
+ s_playermodel.menu.key = PlayerModel_MenuKey;
+ s_playermodel.menu.wrapAround = qtrue;
+ s_playermodel.menu.fullscreen = qtrue;
+
+ s_playermodel.banner.generic.type = MTYPE_BTEXT;
+ s_playermodel.banner.generic.x = 320;
+ s_playermodel.banner.generic.y = 16;
+ s_playermodel.banner.string = "PLAYER MODEL";
+ s_playermodel.banner.color = color_white;
+ s_playermodel.banner.style = UI_CENTER;
+
+ s_playermodel.framel.generic.type = MTYPE_BITMAP;
+ s_playermodel.framel.generic.name = MODEL_FRAMEL;
+ s_playermodel.framel.generic.flags = QMF_LEFT_JUSTIFY|QMF_INACTIVE;
+ s_playermodel.framel.generic.x = 0;
+ s_playermodel.framel.generic.y = 78;
+ s_playermodel.framel.width = 256;
+ s_playermodel.framel.height = 329;
+
+ s_playermodel.framer.generic.type = MTYPE_BITMAP;
+ s_playermodel.framer.generic.name = MODEL_FRAMER;
+ s_playermodel.framer.generic.flags = QMF_LEFT_JUSTIFY|QMF_INACTIVE;
+ s_playermodel.framer.generic.x = 376;
+ s_playermodel.framer.generic.y = 76;
+ s_playermodel.framer.width = 256;
+ s_playermodel.framer.height = 334;
+
+ s_playermodel.ports.generic.type = MTYPE_BITMAP;
+ s_playermodel.ports.generic.name = MODEL_PORTS;
+ s_playermodel.ports.generic.flags = QMF_LEFT_JUSTIFY|QMF_INACTIVE;
+ s_playermodel.ports.generic.x = 50;
+ s_playermodel.ports.generic.y = 59;
+ s_playermodel.ports.width = 274;
+ s_playermodel.ports.height = 274;
+
+ y = 59;
+ for (i=0,k=0; i<PLAYERGRID_ROWS; i++)
+ {
+ x = 50;
+ for (j=0; j<PLAYERGRID_COLS; j++,k++)
+ {
+ s_playermodel.pics[k].generic.type = MTYPE_BITMAP;
+ s_playermodel.pics[k].generic.flags = QMF_LEFT_JUSTIFY|QMF_INACTIVE;
+ s_playermodel.pics[k].generic.x = x;
+ s_playermodel.pics[k].generic.y = y;
+ s_playermodel.pics[k].width = 64;
+ s_playermodel.pics[k].height = 64;
+ s_playermodel.pics[k].focuspic = MODEL_SELECTED;
+ s_playermodel.pics[k].focuscolor = colorRed;
+
+ s_playermodel.picbuttons[k].generic.type = MTYPE_BITMAP;
+ s_playermodel.picbuttons[k].generic.flags = QMF_LEFT_JUSTIFY|QMF_NODEFAULTINIT|QMF_PULSEIFFOCUS;
+ s_playermodel.picbuttons[k].generic.id = ID_PLAYERPIC0+k;
+ s_playermodel.picbuttons[k].generic.callback = PlayerModel_PicEvent;
+ s_playermodel.picbuttons[k].generic.x = x - 16;
+ s_playermodel.picbuttons[k].generic.y = y - 16;
+ s_playermodel.picbuttons[k].generic.left = x;
+ s_playermodel.picbuttons[k].generic.top = y;
+ s_playermodel.picbuttons[k].generic.right = x + 64;
+ s_playermodel.picbuttons[k].generic.bottom = y + 64;
+ s_playermodel.picbuttons[k].width = 128;
+ s_playermodel.picbuttons[k].height = 128;
+ s_playermodel.picbuttons[k].focuspic = MODEL_SELECT;
+ s_playermodel.picbuttons[k].focuscolor = colorRed;
+
+ x += 64+6;
+ }
+ y += 64+6;
+ }
+
+ s_playermodel.playername.generic.type = MTYPE_PTEXT;
+ s_playermodel.playername.generic.flags = QMF_CENTER_JUSTIFY|QMF_INACTIVE;
+ s_playermodel.playername.generic.x = 320;
+ s_playermodel.playername.generic.y = 440;
+ s_playermodel.playername.string = playername;
+ s_playermodel.playername.style = UI_CENTER;
+ s_playermodel.playername.color = text_color_normal;
+
+ s_playermodel.modelname.generic.type = MTYPE_PTEXT;
+ s_playermodel.modelname.generic.flags = QMF_CENTER_JUSTIFY|QMF_INACTIVE;
+ s_playermodel.modelname.generic.x = 497;
+ s_playermodel.modelname.generic.y = 54;
+ s_playermodel.modelname.string = modelname;
+ s_playermodel.modelname.style = UI_CENTER;
+ s_playermodel.modelname.color = text_color_normal;
+
+ s_playermodel.skinname.generic.type = MTYPE_PTEXT;
+ s_playermodel.skinname.generic.flags = QMF_CENTER_JUSTIFY|QMF_INACTIVE;
+ s_playermodel.skinname.generic.x = 497;
+ s_playermodel.skinname.generic.y = 394;
+ s_playermodel.skinname.string = skinname;
+ s_playermodel.skinname.style = UI_CENTER;
+ s_playermodel.skinname.color = text_color_normal;
+
+ s_playermodel.player.generic.type = MTYPE_BITMAP;
+ s_playermodel.player.generic.flags = QMF_INACTIVE;
+ s_playermodel.player.generic.ownerdraw = PlayerModel_DrawPlayer;
+ s_playermodel.player.generic.x = 400;
+ s_playermodel.player.generic.y = -40;
+ s_playermodel.player.width = 32*10;
+ s_playermodel.player.height = 56*10;
+
+ s_playermodel.arrows.generic.type = MTYPE_BITMAP;
+ s_playermodel.arrows.generic.name = MODEL_ARROWS;
+ s_playermodel.arrows.generic.flags = QMF_INACTIVE;
+ s_playermodel.arrows.generic.x = 125;
+ s_playermodel.arrows.generic.y = 340;
+ s_playermodel.arrows.width = 128;
+ s_playermodel.arrows.height = 32;
+
+ s_playermodel.left.generic.type = MTYPE_BITMAP;
+ s_playermodel.left.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_playermodel.left.generic.callback = PlayerModel_MenuEvent;
+ s_playermodel.left.generic.id = ID_PREVPAGE;
+ s_playermodel.left.generic.x = 125;
+ s_playermodel.left.generic.y = 340;
+ s_playermodel.left.width = 64;
+ s_playermodel.left.height = 32;
+ s_playermodel.left.focuspic = MODEL_ARROWSL;
+
+ s_playermodel.right.generic.type = MTYPE_BITMAP;
+ s_playermodel.right.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_playermodel.right.generic.callback = PlayerModel_MenuEvent;
+ s_playermodel.right.generic.id = ID_NEXTPAGE;
+ s_playermodel.right.generic.x = 125+61;
+ s_playermodel.right.generic.y = 340;
+ s_playermodel.right.width = 64;
+ s_playermodel.right.height = 32;
+ s_playermodel.right.focuspic = MODEL_ARROWSR;
+
+ s_playermodel.back.generic.type = MTYPE_BITMAP;
+ s_playermodel.back.generic.name = MODEL_BACK0;
+ s_playermodel.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_playermodel.back.generic.callback = PlayerModel_MenuEvent;
+ s_playermodel.back.generic.id = ID_BACK;
+ s_playermodel.back.generic.x = 0;
+ s_playermodel.back.generic.y = 480-64;
+ s_playermodel.back.width = 128;
+ s_playermodel.back.height = 64;
+ s_playermodel.back.focuspic = MODEL_BACK1;
+
+ Menu_AddItem( &s_playermodel.menu, &s_playermodel.banner );
+ Menu_AddItem( &s_playermodel.menu, &s_playermodel.framel );
+ Menu_AddItem( &s_playermodel.menu, &s_playermodel.framer );
+ Menu_AddItem( &s_playermodel.menu, &s_playermodel.ports );
+ Menu_AddItem( &s_playermodel.menu, &s_playermodel.playername );
+ Menu_AddItem( &s_playermodel.menu, &s_playermodel.modelname );
+ Menu_AddItem( &s_playermodel.menu, &s_playermodel.skinname );
+
+ for (i=0; i<MAX_MODELSPERPAGE; i++)
+ {
+ Menu_AddItem( &s_playermodel.menu, &s_playermodel.pics[i] );
+ Menu_AddItem( &s_playermodel.menu, &s_playermodel.picbuttons[i] );
+ }
+
+ Menu_AddItem( &s_playermodel.menu, &s_playermodel.player );
+ Menu_AddItem( &s_playermodel.menu, &s_playermodel.arrows );
+ Menu_AddItem( &s_playermodel.menu, &s_playermodel.left );
+ Menu_AddItem( &s_playermodel.menu, &s_playermodel.right );
+ Menu_AddItem( &s_playermodel.menu, &s_playermodel.back );
+
+ // find all available models
+// PlayerModel_BuildList();
+
+ // set initial states
+ PlayerModel_SetMenuItems();
+
+ // update user interface
+ PlayerModel_UpdateGrid();
+ PlayerModel_UpdateModel();
+}
+
+/*
+=================
+PlayerModel_Cache
+=================
+*/
+void PlayerModel_Cache( void )
+{
+ int i;
+
+ for( i = 0; playermodel_artlist[i]; i++ ) {
+ trap_R_RegisterShaderNoMip( playermodel_artlist[i] );
+ }
+
+ PlayerModel_BuildList();
+ for( i = 0; i < s_playermodel.nummodels; i++ ) {
+ trap_R_RegisterShaderNoMip( s_playermodel.modelnames[i] );
+ }
+}
+
+void UI_PlayerModelMenu(void)
+{
+ PlayerModel_MenuInit();
+
+ UI_PushMenu( &s_playermodel.menu );
+
+ Menu_SetCursorToItem( &s_playermodel.menu, &s_playermodel.pics[s_playermodel.selectedmodel % MAX_MODELSPERPAGE] );
+}
+
+
diff --git a/code/q3_ui/ui_players.c b/code/q3_ui/ui_players.c
new file mode 100755
index 0000000..e4b98ff
--- /dev/null
+++ b/code/q3_ui/ui_players.c
@@ -0,0 +1,1248 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// ui_players.c
+
+#include "ui_local.h"
+
+
+#define UI_TIMER_GESTURE 2300
+#define UI_TIMER_JUMP 1000
+#define UI_TIMER_LAND 130
+#define UI_TIMER_WEAPON_SWITCH 300
+#define UI_TIMER_ATTACK 500
+#define UI_TIMER_MUZZLE_FLASH 20
+#define UI_TIMER_WEAPON_DELAY 250
+
+#define JUMP_HEIGHT 56
+
+#define SWINGSPEED 0.3f
+
+#define SPIN_SPEED 0.9f
+#define COAST_TIME 1000
+
+
+static int dp_realtime;
+static float jumpHeight;
+
+
+/*
+===============
+UI_PlayerInfo_SetWeapon
+===============
+*/
+static void UI_PlayerInfo_SetWeapon( playerInfo_t *pi, weapon_t weaponNum ) {
+ gitem_t * item;
+ char path[MAX_QPATH];
+
+ pi->currentWeapon = weaponNum;
+tryagain:
+ pi->realWeapon = weaponNum;
+ pi->weaponModel = 0;
+ pi->barrelModel = 0;
+ pi->flashModel = 0;
+
+ if ( weaponNum == WP_NONE ) {
+ return;
+ }
+
+ for ( item = bg_itemlist + 1; item->classname ; item++ ) {
+ if ( item->giType != IT_WEAPON ) {
+ continue;
+ }
+ if ( item->giTag == weaponNum ) {
+ break;
+ }
+ }
+
+ if ( item->classname ) {
+ pi->weaponModel = trap_R_RegisterModel( item->world_model[0] );
+ }
+
+ if( pi->weaponModel == 0 ) {
+ if( weaponNum == WP_MACHINEGUN ) {
+ weaponNum = WP_NONE;
+ goto tryagain;
+ }
+ weaponNum = WP_MACHINEGUN;
+ goto tryagain;
+ }
+
+ if ( weaponNum == WP_MACHINEGUN || weaponNum == WP_GAUNTLET || weaponNum == WP_BFG ) {
+ strcpy( path, item->world_model[0] );
+ COM_StripExtension( path, path );
+ strcat( path, "_barrel.md3" );
+ pi->barrelModel = trap_R_RegisterModel( path );
+ }
+
+ strcpy( path, item->world_model[0] );
+ COM_StripExtension( path, path );
+ strcat( path, "_flash.md3" );
+ pi->flashModel = trap_R_RegisterModel( path );
+
+ switch( weaponNum ) {
+ case WP_GAUNTLET:
+ MAKERGB( pi->flashDlightColor, 0.6f, 0.6f, 1 );
+ break;
+
+ case WP_MACHINEGUN:
+ MAKERGB( pi->flashDlightColor, 1, 1, 0 );
+ break;
+
+ case WP_SHOTGUN:
+ MAKERGB( pi->flashDlightColor, 1, 1, 0 );
+ break;
+
+ case WP_GRENADE_LAUNCHER:
+ MAKERGB( pi->flashDlightColor, 1, 0.7f, 0.5f );
+ break;
+
+ case WP_ROCKET_LAUNCHER:
+ MAKERGB( pi->flashDlightColor, 1, 0.75f, 0 );
+ break;
+
+ case WP_LIGHTNING:
+ MAKERGB( pi->flashDlightColor, 0.6f, 0.6f, 1 );
+ break;
+
+ case WP_RAILGUN:
+ MAKERGB( pi->flashDlightColor, 1, 0.5f, 0 );
+ break;
+
+ case WP_PLASMAGUN:
+ MAKERGB( pi->flashDlightColor, 0.6f, 0.6f, 1 );
+ break;
+
+ case WP_BFG:
+ MAKERGB( pi->flashDlightColor, 1, 0.7f, 1 );
+ break;
+
+ case WP_GRAPPLING_HOOK:
+ MAKERGB( pi->flashDlightColor, 0.6f, 0.6f, 1 );
+ break;
+
+ default:
+ MAKERGB( pi->flashDlightColor, 1, 1, 1 );
+ break;
+ }
+}
+
+
+/*
+===============
+UI_ForceLegsAnim
+===============
+*/
+static void UI_ForceLegsAnim( playerInfo_t *pi, int anim ) {
+ pi->legsAnim = ( ( pi->legsAnim & ANIM_TOGGLEBIT ) ^ ANIM_TOGGLEBIT ) | anim;
+
+ if ( anim == LEGS_JUMP ) {
+ pi->legsAnimationTimer = UI_TIMER_JUMP;
+ }
+}
+
+
+/*
+===============
+UI_SetLegsAnim
+===============
+*/
+static void UI_SetLegsAnim( playerInfo_t *pi, int anim ) {
+ if ( pi->pendingLegsAnim ) {
+ anim = pi->pendingLegsAnim;
+ pi->pendingLegsAnim = 0;
+ }
+ UI_ForceLegsAnim( pi, anim );
+}
+
+
+/*
+===============
+UI_ForceTorsoAnim
+===============
+*/
+static void UI_ForceTorsoAnim( playerInfo_t *pi, int anim ) {
+ pi->torsoAnim = ( ( pi->torsoAnim & ANIM_TOGGLEBIT ) ^ ANIM_TOGGLEBIT ) | anim;
+
+ if ( anim == TORSO_GESTURE ) {
+ pi->torsoAnimationTimer = UI_TIMER_GESTURE;
+ }
+
+ if ( anim == TORSO_ATTACK || anim == TORSO_ATTACK2 ) {
+ pi->torsoAnimationTimer = UI_TIMER_ATTACK;
+ }
+}
+
+
+/*
+===============
+UI_SetTorsoAnim
+===============
+*/
+static void UI_SetTorsoAnim( playerInfo_t *pi, int anim ) {
+ if ( pi->pendingTorsoAnim ) {
+ anim = pi->pendingTorsoAnim;
+ pi->pendingTorsoAnim = 0;
+ }
+
+ UI_ForceTorsoAnim( pi, anim );
+}
+
+
+/*
+===============
+UI_TorsoSequencing
+===============
+*/
+static void UI_TorsoSequencing( playerInfo_t *pi ) {
+ int currentAnim;
+
+ currentAnim = pi->torsoAnim & ~ANIM_TOGGLEBIT;
+
+ if ( pi->weapon != pi->currentWeapon ) {
+ if ( currentAnim != TORSO_DROP ) {
+ pi->torsoAnimationTimer = UI_TIMER_WEAPON_SWITCH;
+ UI_ForceTorsoAnim( pi, TORSO_DROP );
+ }
+ }
+
+ if ( pi->torsoAnimationTimer > 0 ) {
+ return;
+ }
+
+ if( currentAnim == TORSO_GESTURE ) {
+ UI_SetTorsoAnim( pi, TORSO_STAND );
+ return;
+ }
+
+ if( currentAnim == TORSO_ATTACK || currentAnim == TORSO_ATTACK2 ) {
+ UI_SetTorsoAnim( pi, TORSO_STAND );
+ return;
+ }
+
+ if ( currentAnim == TORSO_DROP ) {
+ UI_PlayerInfo_SetWeapon( pi, pi->weapon );
+ pi->torsoAnimationTimer = UI_TIMER_WEAPON_SWITCH;
+ UI_ForceTorsoAnim( pi, TORSO_RAISE );
+ return;
+ }
+
+ if ( currentAnim == TORSO_RAISE ) {
+ UI_SetTorsoAnim( pi, TORSO_STAND );
+ return;
+ }
+}
+
+
+/*
+===============
+UI_LegsSequencing
+===============
+*/
+static void UI_LegsSequencing( playerInfo_t *pi ) {
+ int currentAnim;
+
+ currentAnim = pi->legsAnim & ~ANIM_TOGGLEBIT;
+
+ if ( pi->legsAnimationTimer > 0 ) {
+ if ( currentAnim == LEGS_JUMP ) {
+ jumpHeight = JUMP_HEIGHT * sin( M_PI * ( UI_TIMER_JUMP - pi->legsAnimationTimer ) / UI_TIMER_JUMP );
+ }
+ return;
+ }
+
+ if ( currentAnim == LEGS_JUMP ) {
+ UI_ForceLegsAnim( pi, LEGS_LAND );
+ pi->legsAnimationTimer = UI_TIMER_LAND;
+ jumpHeight = 0;
+ return;
+ }
+
+ if ( currentAnim == LEGS_LAND ) {
+ UI_SetLegsAnim( pi, LEGS_IDLE );
+ return;
+ }
+}
+
+
+/*
+======================
+UI_PositionEntityOnTag
+======================
+*/
+static void UI_PositionEntityOnTag( refEntity_t *entity, const refEntity_t *parent,
+ clipHandle_t parentModel, char *tagName ) {
+ int i;
+ orientation_t lerped;
+
+ // lerp the tag
+ trap_CM_LerpTag( &lerped, parentModel, parent->oldframe, parent->frame,
+ 1.0 - parent->backlerp, tagName );
+
+ // FIXME: allow origin offsets along tag?
+ VectorCopy( parent->origin, entity->origin );
+ for ( i = 0 ; i < 3 ; i++ ) {
+ VectorMA( entity->origin, lerped.origin[i], parent->axis[i], entity->origin );
+ }
+
+ // cast away const because of compiler problems
+ MatrixMultiply( lerped.axis, ((refEntity_t*)parent)->axis, entity->axis );
+ entity->backlerp = parent->backlerp;
+}
+
+
+/*
+======================
+UI_PositionRotatedEntityOnTag
+======================
+*/
+static void UI_PositionRotatedEntityOnTag( refEntity_t *entity, const refEntity_t *parent,
+ clipHandle_t parentModel, char *tagName ) {
+ int i;
+ orientation_t lerped;
+ vec3_t tempAxis[3];
+
+ // lerp the tag
+ trap_CM_LerpTag( &lerped, parentModel, parent->oldframe, parent->frame,
+ 1.0 - parent->backlerp, tagName );
+
+ // FIXME: allow origin offsets along tag?
+ VectorCopy( parent->origin, entity->origin );
+ for ( i = 0 ; i < 3 ; i++ ) {
+ VectorMA( entity->origin, lerped.origin[i], parent->axis[i], entity->origin );
+ }
+
+ // cast away const because of compiler problems
+ MatrixMultiply( entity->axis, ((refEntity_t *)parent)->axis, tempAxis );
+ MatrixMultiply( lerped.axis, tempAxis, entity->axis );
+}
+
+
+/*
+===============
+UI_SetLerpFrameAnimation
+===============
+*/
+static void UI_SetLerpFrameAnimation( playerInfo_t *ci, lerpFrame_t *lf, int newAnimation ) {
+ animation_t *anim;
+
+ lf->animationNumber = newAnimation;
+ newAnimation &= ~ANIM_TOGGLEBIT;
+
+ if ( newAnimation < 0 || newAnimation >= MAX_ANIMATIONS ) {
+ trap_Error( va("Bad animation number: %i", newAnimation) );
+ }
+
+ anim = &ci->animations[ newAnimation ];
+
+ lf->animation = anim;
+ lf->animationTime = lf->frameTime + anim->initialLerp;
+}
+
+
+/*
+===============
+UI_RunLerpFrame
+===============
+*/
+static void UI_RunLerpFrame( playerInfo_t *ci, lerpFrame_t *lf, int newAnimation ) {
+ int f;
+ animation_t *anim;
+
+ // see if the animation sequence is switching
+ if ( newAnimation != lf->animationNumber || !lf->animation ) {
+ UI_SetLerpFrameAnimation( ci, lf, newAnimation );
+ }
+
+ // if we have passed the current frame, move it to
+ // oldFrame and calculate a new frame
+ if ( dp_realtime >= lf->frameTime ) {
+ lf->oldFrame = lf->frame;
+ lf->oldFrameTime = lf->frameTime;
+
+ // get the next frame based on the animation
+ anim = lf->animation;
+ if ( dp_realtime < lf->animationTime ) {
+ lf->frameTime = lf->animationTime; // initial lerp
+ } else {
+ lf->frameTime = lf->oldFrameTime + anim->frameLerp;
+ }
+ f = ( lf->frameTime - lf->animationTime ) / anim->frameLerp;
+ if ( f >= anim->numFrames ) {
+ f -= anim->numFrames;
+ if ( anim->loopFrames ) {
+ f %= anim->loopFrames;
+ f += anim->numFrames - anim->loopFrames;
+ } else {
+ f = anim->numFrames - 1;
+ // the animation is stuck at the end, so it
+ // can immediately transition to another sequence
+ lf->frameTime = dp_realtime;
+ }
+ }
+ lf->frame = anim->firstFrame + f;
+ if ( dp_realtime > lf->frameTime ) {
+ lf->frameTime = dp_realtime;
+ }
+ }
+
+ if ( lf->frameTime > dp_realtime + 200 ) {
+ lf->frameTime = dp_realtime;
+ }
+
+ if ( lf->oldFrameTime > dp_realtime ) {
+ lf->oldFrameTime = dp_realtime;
+ }
+ // calculate current lerp value
+ if ( lf->frameTime == lf->oldFrameTime ) {
+ lf->backlerp = 0;
+ } else {
+ lf->backlerp = 1.0 - (float)( dp_realtime - lf->oldFrameTime ) / ( lf->frameTime - lf->oldFrameTime );
+ }
+}
+
+
+/*
+===============
+UI_PlayerAnimation
+===============
+*/
+static void UI_PlayerAnimation( playerInfo_t *pi, int *legsOld, int *legs, float *legsBackLerp,
+ int *torsoOld, int *torso, float *torsoBackLerp ) {
+
+ // legs animation
+ pi->legsAnimationTimer -= uis.frametime;
+ if ( pi->legsAnimationTimer < 0 ) {
+ pi->legsAnimationTimer = 0;
+ }
+
+ UI_LegsSequencing( pi );
+
+ if ( pi->legs.yawing && ( pi->legsAnim & ~ANIM_TOGGLEBIT ) == LEGS_IDLE ) {
+ UI_RunLerpFrame( pi, &pi->legs, LEGS_TURN );
+ } else {
+ UI_RunLerpFrame( pi, &pi->legs, pi->legsAnim );
+ }
+ *legsOld = pi->legs.oldFrame;
+ *legs = pi->legs.frame;
+ *legsBackLerp = pi->legs.backlerp;
+
+ // torso animation
+ pi->torsoAnimationTimer -= uis.frametime;
+ if ( pi->torsoAnimationTimer < 0 ) {
+ pi->torsoAnimationTimer = 0;
+ }
+
+ UI_TorsoSequencing( pi );
+
+ UI_RunLerpFrame( pi, &pi->torso, pi->torsoAnim );
+ *torsoOld = pi->torso.oldFrame;
+ *torso = pi->torso.frame;
+ *torsoBackLerp = pi->torso.backlerp;
+}
+
+
+/*
+==================
+UI_SwingAngles
+==================
+*/
+static void UI_SwingAngles( float destination, float swingTolerance, float clampTolerance,
+ float speed, float *angle, qboolean *swinging ) {
+ float swing;
+ float move;
+ float scale;
+
+ if ( !*swinging ) {
+ // see if a swing should be started
+ swing = AngleSubtract( *angle, destination );
+ if ( swing > swingTolerance || swing < -swingTolerance ) {
+ *swinging = qtrue;
+ }
+ }
+
+ if ( !*swinging ) {
+ return;
+ }
+
+ // modify the speed depending on the delta
+ // so it doesn't seem so linear
+ swing = AngleSubtract( destination, *angle );
+ scale = fabs( swing );
+ if ( scale < swingTolerance * 0.5 ) {
+ scale = 0.5;
+ } else if ( scale < swingTolerance ) {
+ scale = 1.0;
+ } else {
+ scale = 2.0;
+ }
+
+ // swing towards the destination angle
+ if ( swing >= 0 ) {
+ move = uis.frametime * scale * speed;
+ if ( move >= swing ) {
+ move = swing;
+ *swinging = qfalse;
+ }
+ *angle = AngleMod( *angle + move );
+ } else if ( swing < 0 ) {
+ move = uis.frametime * scale * -speed;
+ if ( move <= swing ) {
+ move = swing;
+ *swinging = qfalse;
+ }
+ *angle = AngleMod( *angle + move );
+ }
+
+ // clamp to no more than tolerance
+ swing = AngleSubtract( destination, *angle );
+ if ( swing > clampTolerance ) {
+ *angle = AngleMod( destination - (clampTolerance - 1) );
+ } else if ( swing < -clampTolerance ) {
+ *angle = AngleMod( destination + (clampTolerance - 1) );
+ }
+}
+
+
+/*
+======================
+UI_MovedirAdjustment
+======================
+*/
+static float UI_MovedirAdjustment( playerInfo_t *pi ) {
+ vec3_t relativeAngles;
+ vec3_t moveVector;
+
+ VectorSubtract( pi->viewAngles, pi->moveAngles, relativeAngles );
+ AngleVectors( relativeAngles, moveVector, NULL, NULL );
+ if ( Q_fabs( moveVector[0] ) < 0.01 ) {
+ moveVector[0] = 0.0;
+ }
+ if ( Q_fabs( moveVector[1] ) < 0.01 ) {
+ moveVector[1] = 0.0;
+ }
+
+ if ( moveVector[1] == 0 && moveVector[0] > 0 ) {
+ return 0;
+ }
+ if ( moveVector[1] < 0 && moveVector[0] > 0 ) {
+ return 22;
+ }
+ if ( moveVector[1] < 0 && moveVector[0] == 0 ) {
+ return 45;
+ }
+ if ( moveVector[1] < 0 && moveVector[0] < 0 ) {
+ return -22;
+ }
+ if ( moveVector[1] == 0 && moveVector[0] < 0 ) {
+ return 0;
+ }
+ if ( moveVector[1] > 0 && moveVector[0] < 0 ) {
+ return 22;
+ }
+ if ( moveVector[1] > 0 && moveVector[0] == 0 ) {
+ return -45;
+ }
+
+ return -22;
+}
+
+
+/*
+===============
+UI_PlayerAngles
+===============
+*/
+static void UI_PlayerAngles( playerInfo_t *pi, vec3_t legs[3], vec3_t torso[3], vec3_t head[3] ) {
+ vec3_t legsAngles, torsoAngles, headAngles;
+ float dest;
+ float adjust;
+
+ VectorCopy( pi->viewAngles, headAngles );
+ headAngles[YAW] = AngleMod( headAngles[YAW] );
+ VectorClear( legsAngles );
+ VectorClear( torsoAngles );
+
+ // --------- yaw -------------
+
+ // allow yaw to drift a bit
+ if ( ( pi->legsAnim & ~ANIM_TOGGLEBIT ) != LEGS_IDLE
+ || ( pi->torsoAnim & ~ANIM_TOGGLEBIT ) != TORSO_STAND ) {
+ // if not standing still, always point all in the same direction
+ pi->torso.yawing = qtrue; // always center
+ pi->torso.pitching = qtrue; // always center
+ pi->legs.yawing = qtrue; // always center
+ }
+
+ // adjust legs for movement dir
+ adjust = UI_MovedirAdjustment( pi );
+ legsAngles[YAW] = headAngles[YAW] + adjust;
+ torsoAngles[YAW] = headAngles[YAW] + 0.25 * adjust;
+
+
+ // torso
+ UI_SwingAngles( torsoAngles[YAW], 25, 90, SWINGSPEED, &pi->torso.yawAngle, &pi->torso.yawing );
+ UI_SwingAngles( legsAngles[YAW], 40, 90, SWINGSPEED, &pi->legs.yawAngle, &pi->legs.yawing );
+
+ torsoAngles[YAW] = pi->torso.yawAngle;
+ legsAngles[YAW] = pi->legs.yawAngle;
+
+ // --------- pitch -------------
+
+ // only show a fraction of the pitch angle in the torso
+ if ( headAngles[PITCH] > 180 ) {
+ dest = (-360 + headAngles[PITCH]) * 0.75;
+ } else {
+ dest = headAngles[PITCH] * 0.75;
+ }
+ UI_SwingAngles( dest, 15, 30, 0.1f, &pi->torso.pitchAngle, &pi->torso.pitching );
+ torsoAngles[PITCH] = pi->torso.pitchAngle;
+
+ // pull the angles back out of the hierarchial chain
+ AnglesSubtract( headAngles, torsoAngles, headAngles );
+ AnglesSubtract( torsoAngles, legsAngles, torsoAngles );
+ AnglesToAxis( legsAngles, legs );
+ AnglesToAxis( torsoAngles, torso );
+ AnglesToAxis( headAngles, head );
+}
+
+
+/*
+===============
+UI_PlayerFloatSprite
+===============
+*/
+static void UI_PlayerFloatSprite( playerInfo_t *pi, vec3_t origin, qhandle_t shader ) {
+ refEntity_t ent;
+
+ memset( &ent, 0, sizeof( ent ) );
+ VectorCopy( origin, ent.origin );
+ ent.origin[2] += 48;
+ ent.reType = RT_SPRITE;
+ ent.customShader = shader;
+ ent.radius = 10;
+ ent.renderfx = 0;
+ trap_R_AddRefEntityToScene( &ent );
+}
+
+
+/*
+======================
+UI_MachinegunSpinAngle
+======================
+*/
+float UI_MachinegunSpinAngle( playerInfo_t *pi ) {
+ int delta;
+ float angle;
+ float speed;
+ int torsoAnim;
+
+ delta = dp_realtime - pi->barrelTime;
+ if ( pi->barrelSpinning ) {
+ angle = pi->barrelAngle + delta * SPIN_SPEED;
+ } else {
+ if ( delta > COAST_TIME ) {
+ delta = COAST_TIME;
+ }
+
+ speed = 0.5 * ( SPIN_SPEED + (float)( COAST_TIME - delta ) / COAST_TIME );
+ angle = pi->barrelAngle + delta * speed;
+ }
+
+ torsoAnim = pi->torsoAnim & ~ANIM_TOGGLEBIT;
+ if( torsoAnim == TORSO_ATTACK2 ) {
+ torsoAnim = TORSO_ATTACK;
+ }
+ if ( pi->barrelSpinning == !(torsoAnim == TORSO_ATTACK) ) {
+ pi->barrelTime = dp_realtime;
+ pi->barrelAngle = AngleMod( angle );
+ pi->barrelSpinning = !!(torsoAnim == TORSO_ATTACK);
+ }
+
+ return angle;
+}
+
+
+/*
+===============
+UI_DrawPlayer
+===============
+*/
+void UI_DrawPlayer( float x, float y, float w, float h, playerInfo_t *pi, int time ) {
+ refdef_t refdef;
+ refEntity_t legs;
+ refEntity_t torso;
+ refEntity_t head;
+ refEntity_t gun;
+ refEntity_t barrel;
+ refEntity_t flash;
+ vec3_t origin;
+ int renderfx;
+ vec3_t mins = {-16, -16, -24};
+ vec3_t maxs = {16, 16, 32};
+ float len;
+ float xx;
+
+ if ( !pi->legsModel || !pi->torsoModel || !pi->headModel || !pi->animations[0].numFrames ) {
+ return;
+ }
+
+ dp_realtime = time;
+
+ if ( pi->pendingWeapon != -1 && dp_realtime > pi->weaponTimer ) {
+ pi->weapon = pi->pendingWeapon;
+ pi->lastWeapon = pi->pendingWeapon;
+ pi->pendingWeapon = -1;
+ pi->weaponTimer = 0;
+ if( pi->currentWeapon != pi->weapon ) {
+ trap_S_StartLocalSound( weaponChangeSound, CHAN_LOCAL );
+ }
+ }
+
+ UI_AdjustFrom640( &x, &y, &w, &h );
+
+ y -= jumpHeight;
+
+ memset( &refdef, 0, sizeof( refdef ) );
+ memset( &legs, 0, sizeof(legs) );
+ memset( &torso, 0, sizeof(torso) );
+ memset( &head, 0, sizeof(head) );
+
+ refdef.rdflags = RDF_NOWORLDMODEL;
+
+ AxisClear( refdef.viewaxis );
+
+ refdef.x = x;
+ refdef.y = y;
+ refdef.width = w;
+ refdef.height = h;
+
+ refdef.fov_x = (int)((float)refdef.width / 640.0f * 90.0f);
+ xx = refdef.width / tan( refdef.fov_x / 360 * M_PI );
+ refdef.fov_y = atan2( refdef.height, xx );
+ refdef.fov_y *= ( 360 / M_PI );
+
+ // calculate distance so the player nearly fills the box
+ len = 0.7 * ( maxs[2] - mins[2] );
+ origin[0] = len / tan( DEG2RAD(refdef.fov_x) * 0.5 );
+ origin[1] = 0.5 * ( mins[1] + maxs[1] );
+ origin[2] = -0.5 * ( mins[2] + maxs[2] );
+
+ refdef.time = dp_realtime;
+
+ trap_R_ClearScene();
+
+ // get the rotation information
+ UI_PlayerAngles( pi, legs.axis, torso.axis, head.axis );
+
+ // get the animation state (after rotation, to allow feet shuffle)
+ UI_PlayerAnimation( pi, &legs.oldframe, &legs.frame, &legs.backlerp,
+ &torso.oldframe, &torso.frame, &torso.backlerp );
+
+ renderfx = RF_LIGHTING_ORIGIN | RF_NOSHADOW;
+
+ //
+ // add the legs
+ //
+ legs.hModel = pi->legsModel;
+ legs.customSkin = pi->legsSkin;
+
+ VectorCopy( origin, legs.origin );
+
+ VectorCopy( origin, legs.lightingOrigin );
+ legs.renderfx = renderfx;
+ VectorCopy (legs.origin, legs.oldorigin);
+
+ trap_R_AddRefEntityToScene( &legs );
+
+ if (!legs.hModel) {
+ return;
+ }
+
+ //
+ // add the torso
+ //
+ torso.hModel = pi->torsoModel;
+ if (!torso.hModel) {
+ return;
+ }
+
+ torso.customSkin = pi->torsoSkin;
+
+ VectorCopy( origin, torso.lightingOrigin );
+
+ UI_PositionRotatedEntityOnTag( &torso, &legs, pi->legsModel, "tag_torso");
+
+ torso.renderfx = renderfx;
+
+ trap_R_AddRefEntityToScene( &torso );
+
+ //
+ // add the head
+ //
+ head.hModel = pi->headModel;
+ if (!head.hModel) {
+ return;
+ }
+ head.customSkin = pi->headSkin;
+
+ VectorCopy( origin, head.lightingOrigin );
+
+ UI_PositionRotatedEntityOnTag( &head, &torso, pi->torsoModel, "tag_head");
+
+ head.renderfx = renderfx;
+
+ trap_R_AddRefEntityToScene( &head );
+
+ //
+ // add the gun
+ //
+ if ( pi->currentWeapon != WP_NONE ) {
+ memset( &gun, 0, sizeof(gun) );
+ gun.hModel = pi->weaponModel;
+ VectorCopy( origin, gun.lightingOrigin );
+ UI_PositionEntityOnTag( &gun, &torso, pi->torsoModel, "tag_weapon");
+ gun.renderfx = renderfx;
+ trap_R_AddRefEntityToScene( &gun );
+ }
+
+ //
+ // add the spinning barrel
+ //
+ if ( pi->realWeapon == WP_MACHINEGUN || pi->realWeapon == WP_GAUNTLET || pi->realWeapon == WP_BFG ) {
+ vec3_t angles;
+
+ memset( &barrel, 0, sizeof(barrel) );
+ VectorCopy( origin, barrel.lightingOrigin );
+ barrel.renderfx = renderfx;
+
+ barrel.hModel = pi->barrelModel;
+ angles[YAW] = 0;
+ angles[PITCH] = 0;
+ angles[ROLL] = UI_MachinegunSpinAngle( pi );
+ if( pi->realWeapon == WP_GAUNTLET || pi->realWeapon == WP_BFG ) {
+ angles[PITCH] = angles[ROLL];
+ angles[ROLL] = 0;
+ }
+ AnglesToAxis( angles, barrel.axis );
+
+ UI_PositionRotatedEntityOnTag( &barrel, &gun, pi->weaponModel, "tag_barrel");
+
+ trap_R_AddRefEntityToScene( &barrel );
+ }
+
+ //
+ // add muzzle flash
+ //
+ if ( dp_realtime <= pi->muzzleFlashTime ) {
+ if ( pi->flashModel ) {
+ memset( &flash, 0, sizeof(flash) );
+ flash.hModel = pi->flashModel;
+ VectorCopy( origin, flash.lightingOrigin );
+ UI_PositionEntityOnTag( &flash, &gun, pi->weaponModel, "tag_flash");
+ flash.renderfx = renderfx;
+ trap_R_AddRefEntityToScene( &flash );
+ }
+
+ // make a dlight for the flash
+ if ( pi->flashDlightColor[0] || pi->flashDlightColor[1] || pi->flashDlightColor[2] ) {
+ trap_R_AddLightToScene( flash.origin, 200 + (rand()&31), pi->flashDlightColor[0],
+ pi->flashDlightColor[1], pi->flashDlightColor[2] );
+ }
+ }
+
+ //
+ // add the chat icon
+ //
+ if ( pi->chat ) {
+ UI_PlayerFloatSprite( pi, origin, trap_R_RegisterShaderNoMip( "sprites/balloon3" ) );
+ }
+
+ //
+ // add an accent light
+ //
+ origin[0] -= 100; // + = behind, - = in front
+ origin[1] += 100; // + = left, - = right
+ origin[2] += 100; // + = above, - = below
+ trap_R_AddLightToScene( origin, 500, 1.0, 1.0, 1.0 );
+
+ origin[0] -= 100;
+ origin[1] -= 100;
+ origin[2] -= 100;
+ trap_R_AddLightToScene( origin, 500, 1.0, 0.0, 0.0 );
+
+ trap_R_RenderScene( &refdef );
+}
+
+
+/*
+==========================
+UI_RegisterClientSkin
+==========================
+*/
+static qboolean UI_RegisterClientSkin( playerInfo_t *pi, const char *modelName, const char *skinName ) {
+ char filename[MAX_QPATH];
+
+ Com_sprintf( filename, sizeof( filename ), "models/players/%s/lower_%s.skin", modelName, skinName );
+ pi->legsSkin = trap_R_RegisterSkin( filename );
+
+ Com_sprintf( filename, sizeof( filename ), "models/players/%s/upper_%s.skin", modelName, skinName );
+ pi->torsoSkin = trap_R_RegisterSkin( filename );
+
+ Com_sprintf( filename, sizeof( filename ), "models/players/%s/head_%s.skin", modelName, skinName );
+ pi->headSkin = trap_R_RegisterSkin( filename );
+
+ if ( !pi->legsSkin || !pi->torsoSkin || !pi->headSkin ) {
+ return qfalse;
+ }
+
+ return qtrue;
+}
+
+
+/*
+======================
+UI_ParseAnimationFile
+======================
+*/
+static qboolean UI_ParseAnimationFile( const char *filename, animation_t *animations ) {
+ char *text_p, *prev;
+ int len;
+ int i;
+ char *token;
+ float fps;
+ int skip;
+ char text[20000];
+ fileHandle_t f;
+
+ memset( animations, 0, sizeof( animation_t ) * MAX_ANIMATIONS );
+
+ // load the file
+ len = trap_FS_FOpenFile( filename, &f, FS_READ );
+ if ( len <= 0 ) {
+ return qfalse;
+ }
+ if ( len >= ( sizeof( text ) - 1 ) ) {
+ Com_Printf( "File %s too long\n", filename );
+ return qfalse;
+ }
+ trap_FS_Read( text, len, f );
+ text[len] = 0;
+ trap_FS_FCloseFile( f );
+
+ // parse the text
+ text_p = text;
+ skip = 0; // quite the compiler warning
+
+ // read optional parameters
+ while ( 1 ) {
+ prev = text_p; // so we can unget
+ token = COM_Parse( &text_p );
+ if ( !token ) {
+ break;
+ }
+ if ( !Q_stricmp( token, "footsteps" ) ) {
+ token = COM_Parse( &text_p );
+ if ( !token ) {
+ break;
+ }
+ continue;
+ } else if ( !Q_stricmp( token, "headoffset" ) ) {
+ for ( i = 0 ; i < 3 ; i++ ) {
+ token = COM_Parse( &text_p );
+ if ( !token ) {
+ break;
+ }
+ }
+ continue;
+ } else if ( !Q_stricmp( token, "sex" ) ) {
+ token = COM_Parse( &text_p );
+ if ( !token ) {
+ break;
+ }
+ continue;
+ }
+
+ // if it is a number, start parsing animations
+ if ( token[0] >= '0' && token[0] <= '9' ) {
+ text_p = prev; // unget the token
+ break;
+ }
+
+ Com_Printf( "unknown token '%s' is %s\n", token, filename );
+ }
+
+ // read information for each frame
+ for ( i = 0 ; i < MAX_ANIMATIONS ; i++ ) {
+
+ token = COM_Parse( &text_p );
+ if ( !token ) {
+ break;
+ }
+ animations[i].firstFrame = atoi( token );
+ // leg only frames are adjusted to not count the upper body only frames
+ if ( i == LEGS_WALKCR ) {
+ skip = animations[LEGS_WALKCR].firstFrame - animations[TORSO_GESTURE].firstFrame;
+ }
+ if ( i >= LEGS_WALKCR ) {
+ animations[i].firstFrame -= skip;
+ }
+
+ token = COM_Parse( &text_p );
+ if ( !token ) {
+ break;
+ }
+ animations[i].numFrames = atoi( token );
+
+ token = COM_Parse( &text_p );
+ if ( !token ) {
+ break;
+ }
+ animations[i].loopFrames = atoi( token );
+
+ token = COM_Parse( &text_p );
+ if ( !token ) {
+ break;
+ }
+ fps = atof( token );
+ if ( fps == 0 ) {
+ fps = 1;
+ }
+ animations[i].frameLerp = 1000 / fps;
+ animations[i].initialLerp = 1000 / fps;
+ }
+
+ if ( i != MAX_ANIMATIONS ) {
+ Com_Printf( "Error parsing animation file: %s", filename );
+ return qfalse;
+ }
+
+ return qtrue;
+}
+
+
+/*
+==========================
+UI_RegisterClientModelname
+==========================
+*/
+qboolean UI_RegisterClientModelname( playerInfo_t *pi, const char *modelSkinName ) {
+ char modelName[MAX_QPATH];
+ char skinName[MAX_QPATH];
+ char filename[MAX_QPATH];
+ char *slash;
+
+ pi->torsoModel = 0;
+ pi->headModel = 0;
+
+ if ( !modelSkinName[0] ) {
+ return qfalse;
+ }
+
+ Q_strncpyz( modelName, modelSkinName, sizeof( modelName ) );
+
+ slash = strchr( modelName, '/' );
+ if ( !slash ) {
+ // modelName did not include a skin name
+ Q_strncpyz( skinName, "default", sizeof( skinName ) );
+ } else {
+ Q_strncpyz( skinName, slash + 1, sizeof( skinName ) );
+ // truncate modelName
+ *slash = 0;
+ }
+
+ // load cmodels before models so filecache works
+
+ Com_sprintf( filename, sizeof( filename ), "models/players/%s/lower.md3", modelName );
+ pi->legsModel = trap_R_RegisterModel( filename );
+ if ( !pi->legsModel ) {
+ Com_Printf( "Failed to load model file %s\n", filename );
+ return qfalse;
+ }
+
+ Com_sprintf( filename, sizeof( filename ), "models/players/%s/upper.md3", modelName );
+ pi->torsoModel = trap_R_RegisterModel( filename );
+ if ( !pi->torsoModel ) {
+ Com_Printf( "Failed to load model file %s\n", filename );
+ return qfalse;
+ }
+
+ Com_sprintf( filename, sizeof( filename ), "models/players/%s/head.md3", modelName );
+ pi->headModel = trap_R_RegisterModel( filename );
+ if ( !pi->headModel ) {
+ Com_Printf( "Failed to load model file %s\n", filename );
+ return qfalse;
+ }
+
+ // if any skins failed to load, fall back to default
+ if ( !UI_RegisterClientSkin( pi, modelName, skinName ) ) {
+ if ( !UI_RegisterClientSkin( pi, modelName, "default" ) ) {
+ Com_Printf( "Failed to load skin file: %s : %s\n", modelName, skinName );
+ return qfalse;
+ }
+ }
+
+ // load the animations
+ Com_sprintf( filename, sizeof( filename ), "models/players/%s/animation.cfg", modelName );
+ if ( !UI_ParseAnimationFile( filename, pi->animations ) ) {
+ Com_Printf( "Failed to load animation file %s\n", filename );
+ return qfalse;
+ }
+
+ return qtrue;
+}
+
+
+/*
+===============
+UI_PlayerInfo_SetModel
+===============
+*/
+void UI_PlayerInfo_SetModel( playerInfo_t *pi, const char *model ) {
+ memset( pi, 0, sizeof(*pi) );
+ UI_RegisterClientModelname( pi, model );
+ pi->weapon = WP_MACHINEGUN;
+ pi->currentWeapon = pi->weapon;
+ pi->lastWeapon = pi->weapon;
+ pi->pendingWeapon = -1;
+ pi->weaponTimer = 0;
+ pi->chat = qfalse;
+ pi->newModel = qtrue;
+ UI_PlayerInfo_SetWeapon( pi, pi->weapon );
+}
+
+
+/*
+===============
+UI_PlayerInfo_SetInfo
+===============
+*/
+void UI_PlayerInfo_SetInfo( playerInfo_t *pi, int legsAnim, int torsoAnim, vec3_t viewAngles, vec3_t moveAngles, weapon_t weaponNumber, qboolean chat ) {
+ int currentAnim;
+ weapon_t weaponNum;
+
+ pi->chat = chat;
+
+ // view angles
+ VectorCopy( viewAngles, pi->viewAngles );
+
+ // move angles
+ VectorCopy( moveAngles, pi->moveAngles );
+
+ if ( pi->newModel ) {
+ pi->newModel = qfalse;
+
+ jumpHeight = 0;
+ pi->pendingLegsAnim = 0;
+ UI_ForceLegsAnim( pi, legsAnim );
+ pi->legs.yawAngle = viewAngles[YAW];
+ pi->legs.yawing = qfalse;
+
+ pi->pendingTorsoAnim = 0;
+ UI_ForceTorsoAnim( pi, torsoAnim );
+ pi->torso.yawAngle = viewAngles[YAW];
+ pi->torso.yawing = qfalse;
+
+ if ( weaponNumber != -1 ) {
+ pi->weapon = weaponNumber;
+ pi->currentWeapon = weaponNumber;
+ pi->lastWeapon = weaponNumber;
+ pi->pendingWeapon = -1;
+ pi->weaponTimer = 0;
+ UI_PlayerInfo_SetWeapon( pi, pi->weapon );
+ }
+
+ return;
+ }
+
+ // weapon
+ if ( weaponNumber == -1 ) {
+ pi->pendingWeapon = -1;
+ pi->weaponTimer = 0;
+ }
+ else if ( weaponNumber != WP_NONE ) {
+ pi->pendingWeapon = weaponNumber;
+ pi->weaponTimer = dp_realtime + UI_TIMER_WEAPON_DELAY;
+ }
+ weaponNum = pi->lastWeapon;
+ pi->weapon = weaponNum;
+
+ if ( torsoAnim == BOTH_DEATH1 || legsAnim == BOTH_DEATH1 ) {
+ torsoAnim = legsAnim = BOTH_DEATH1;
+ pi->weapon = pi->currentWeapon = WP_NONE;
+ UI_PlayerInfo_SetWeapon( pi, pi->weapon );
+
+ jumpHeight = 0;
+ pi->pendingLegsAnim = 0;
+ UI_ForceLegsAnim( pi, legsAnim );
+
+ pi->pendingTorsoAnim = 0;
+ UI_ForceTorsoAnim( pi, torsoAnim );
+
+ return;
+ }
+
+ // leg animation
+ currentAnim = pi->legsAnim & ~ANIM_TOGGLEBIT;
+ if ( legsAnim != LEGS_JUMP && ( currentAnim == LEGS_JUMP || currentAnim == LEGS_LAND ) ) {
+ pi->pendingLegsAnim = legsAnim;
+ }
+ else if ( legsAnim != currentAnim ) {
+ jumpHeight = 0;
+ pi->pendingLegsAnim = 0;
+ UI_ForceLegsAnim( pi, legsAnim );
+ }
+
+ // torso animation
+ if ( torsoAnim == TORSO_STAND || torsoAnim == TORSO_STAND2 ) {
+ if ( weaponNum == WP_NONE || weaponNum == WP_GAUNTLET ) {
+ torsoAnim = TORSO_STAND2;
+ }
+ else {
+ torsoAnim = TORSO_STAND;
+ }
+ }
+
+ if ( torsoAnim == TORSO_ATTACK || torsoAnim == TORSO_ATTACK2 ) {
+ if ( weaponNum == WP_NONE || weaponNum == WP_GAUNTLET ) {
+ torsoAnim = TORSO_ATTACK2;
+ }
+ else {
+ torsoAnim = TORSO_ATTACK;
+ }
+ pi->muzzleFlashTime = dp_realtime + UI_TIMER_MUZZLE_FLASH;
+ //FIXME play firing sound here
+ }
+
+ currentAnim = pi->torsoAnim & ~ANIM_TOGGLEBIT;
+
+ if ( weaponNum != pi->currentWeapon || currentAnim == TORSO_RAISE || currentAnim == TORSO_DROP ) {
+ pi->pendingTorsoAnim = torsoAnim;
+ }
+ else if ( ( currentAnim == TORSO_GESTURE || currentAnim == TORSO_ATTACK ) && ( torsoAnim != currentAnim ) ) {
+ pi->pendingTorsoAnim = torsoAnim;
+ }
+ else if ( torsoAnim != currentAnim ) {
+ pi->pendingTorsoAnim = 0;
+ UI_ForceTorsoAnim( pi, torsoAnim );
+ }
+}
diff --git a/code/q3_ui/ui_playersettings.c b/code/q3_ui/ui_playersettings.c
new file mode 100755
index 0000000..c299f75
--- /dev/null
+++ b/code/q3_ui/ui_playersettings.c
@@ -0,0 +1,513 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#include "ui_local.h"
+
+#define ART_FRAMEL "menu/art/frame2_l"
+#define ART_FRAMER "menu/art/frame1_r"
+#define ART_MODEL0 "menu/art/model_0"
+#define ART_MODEL1 "menu/art/model_1"
+#define ART_BACK0 "menu/art/back_0"
+#define ART_BACK1 "menu/art/back_1"
+#define ART_FX_BASE "menu/art/fx_base"
+#define ART_FX_BLUE "menu/art/fx_blue"
+#define ART_FX_CYAN "menu/art/fx_cyan"
+#define ART_FX_GREEN "menu/art/fx_grn"
+#define ART_FX_RED "menu/art/fx_red"
+#define ART_FX_TEAL "menu/art/fx_teal"
+#define ART_FX_WHITE "menu/art/fx_white"
+#define ART_FX_YELLOW "menu/art/fx_yel"
+
+#define ID_NAME 10
+#define ID_HANDICAP 11
+#define ID_EFFECTS 12
+#define ID_BACK 13
+#define ID_MODEL 14
+
+#define MAX_NAMELENGTH 20
+
+
+typedef struct {
+ menuframework_s menu;
+
+ menutext_s banner;
+ menubitmap_s framel;
+ menubitmap_s framer;
+ menubitmap_s player;
+
+ menufield_s name;
+ menulist_s handicap;
+ menulist_s effects;
+
+ menubitmap_s back;
+ menubitmap_s model;
+ menubitmap_s item_null;
+
+ qhandle_t fxBasePic;
+ qhandle_t fxPic[7];
+ playerInfo_t playerinfo;
+ int current_fx;
+ char playerModel[MAX_QPATH];
+} playersettings_t;
+
+static playersettings_t s_playersettings;
+
+static int gamecodetoui[] = {4,2,3,0,5,1,6};
+static int uitogamecode[] = {4,6,2,3,1,5,7};
+
+static const char *handicap_items[] = {
+ "None",
+ "95",
+ "90",
+ "85",
+ "80",
+ "75",
+ "70",
+ "65",
+ "60",
+ "55",
+ "50",
+ "45",
+ "40",
+ "35",
+ "30",
+ "25",
+ "20",
+ "15",
+ "10",
+ "5",
+ 0
+};
+
+
+/*
+=================
+PlayerSettings_DrawName
+=================
+*/
+static void PlayerSettings_DrawName( void *self ) {
+ menufield_s *f;
+ qboolean focus;
+ int style;
+ char *txt;
+ char c;
+ float *color;
+ int n;
+ int basex, x, y;
+ char name[32];
+
+ f = (menufield_s*)self;
+ basex = f->generic.x;
+ y = f->generic.y;
+ focus = (f->generic.parent->cursor == f->generic.menuPosition);
+
+ style = UI_LEFT|UI_SMALLFONT;
+ color = text_color_normal;
+ if( focus ) {
+ style |= UI_PULSE;
+ color = text_color_highlight;
+ }
+
+ UI_DrawProportionalString( basex, y, "Name", style, color );
+
+ // draw the actual name
+ basex += 64;
+ y += PROP_HEIGHT;
+ txt = f->field.buffer;
+ color = g_color_table[ColorIndex(COLOR_WHITE)];
+ x = basex;
+ while ( (c = *txt) != 0 ) {
+ if ( !focus && Q_IsColorString( txt ) ) {
+ n = ColorIndex( *(txt+1) );
+ if( n == 0 ) {
+ n = 7;
+ }
+ color = g_color_table[n];
+ txt += 2;
+ continue;
+ }
+ UI_DrawChar( x, y, c, style, color );
+ txt++;
+ x += SMALLCHAR_WIDTH;
+ }
+
+ // draw cursor if we have focus
+ if( focus ) {
+ if ( trap_Key_GetOverstrikeMode() ) {
+ c = 11;
+ } else {
+ c = 10;
+ }
+
+ style &= ~UI_PULSE;
+ style |= UI_BLINK;
+
+ UI_DrawChar( basex + f->field.cursor * SMALLCHAR_WIDTH, y, c, style, color_white );
+ }
+
+ // draw at bottom also using proportional font
+ Q_strncpyz( name, f->field.buffer, sizeof(name) );
+ Q_CleanStr( name );
+ UI_DrawProportionalString( 320, 440, name, UI_CENTER|UI_BIGFONT, text_color_normal );
+}
+
+
+/*
+=================
+PlayerSettings_DrawHandicap
+=================
+*/
+static void PlayerSettings_DrawHandicap( void *self ) {
+ menulist_s *item;
+ qboolean focus;
+ int style;
+ float *color;
+
+ item = (menulist_s *)self;
+ focus = (item->generic.parent->cursor == item->generic.menuPosition);
+
+ style = UI_LEFT|UI_SMALLFONT;
+ color = text_color_normal;
+ if( focus ) {
+ style |= UI_PULSE;
+ color = text_color_highlight;
+ }
+
+ UI_DrawProportionalString( item->generic.x, item->generic.y, "Handicap", style, color );
+ UI_DrawProportionalString( item->generic.x + 64, item->generic.y + PROP_HEIGHT, handicap_items[item->curvalue], style, color );
+}
+
+
+/*
+=================
+PlayerSettings_DrawEffects
+=================
+*/
+static void PlayerSettings_DrawEffects( void *self ) {
+ menulist_s *item;
+ qboolean focus;
+ int style;
+ float *color;
+
+ item = (menulist_s *)self;
+ focus = (item->generic.parent->cursor == item->generic.menuPosition);
+
+ style = UI_LEFT|UI_SMALLFONT;
+ color = text_color_normal;
+ if( focus ) {
+ style |= UI_PULSE;
+ color = text_color_highlight;
+ }
+
+ UI_DrawProportionalString( item->generic.x, item->generic.y, "Effects", style, color );
+
+ UI_DrawHandlePic( item->generic.x + 64, item->generic.y + PROP_HEIGHT + 8, 128, 8, s_playersettings.fxBasePic );
+ UI_DrawHandlePic( item->generic.x + 64 + item->curvalue * 16 + 8, item->generic.y + PROP_HEIGHT + 6, 16, 12, s_playersettings.fxPic[item->curvalue] );
+}
+
+
+/*
+=================
+PlayerSettings_DrawPlayer
+=================
+*/
+static void PlayerSettings_DrawPlayer( void *self ) {
+ menubitmap_s *b;
+ vec3_t viewangles;
+ char buf[MAX_QPATH];
+
+ trap_Cvar_VariableStringBuffer( "model", buf, sizeof( buf ) );
+ if ( strcmp( buf, s_playersettings.playerModel ) != 0 ) {
+ UI_PlayerInfo_SetModel( &s_playersettings.playerinfo, buf );
+ strcpy( s_playersettings.playerModel, buf );
+
+ viewangles[YAW] = 180 - 30;
+ viewangles[PITCH] = 0;
+ viewangles[ROLL] = 0;
+ UI_PlayerInfo_SetInfo( &s_playersettings.playerinfo, LEGS_IDLE, TORSO_STAND, viewangles, vec3_origin, WP_MACHINEGUN, qfalse );
+ }
+
+ b = (menubitmap_s*) self;
+ UI_DrawPlayer( b->generic.x, b->generic.y, b->width, b->height, &s_playersettings.playerinfo, uis.realtime/2 );
+}
+
+
+/*
+=================
+PlayerSettings_SaveChanges
+=================
+*/
+static void PlayerSettings_SaveChanges( void ) {
+ // name
+ trap_Cvar_Set( "name", s_playersettings.name.field.buffer );
+
+ // handicap
+ trap_Cvar_SetValue( "handicap", 100 - s_playersettings.handicap.curvalue * 5 );
+
+ // effects color
+ trap_Cvar_SetValue( "color1", uitogamecode[s_playersettings.effects.curvalue] );
+}
+
+
+/*
+=================
+PlayerSettings_MenuKey
+=================
+*/
+static sfxHandle_t PlayerSettings_MenuKey( int key ) {
+ if( key == K_MOUSE2 || key == K_ESCAPE ) {
+ PlayerSettings_SaveChanges();
+ }
+ return Menu_DefaultKey( &s_playersettings.menu, key );
+}
+
+
+/*
+=================
+PlayerSettings_SetMenuItems
+=================
+*/
+static void PlayerSettings_SetMenuItems( void ) {
+ vec3_t viewangles;
+ int c;
+ int h;
+
+ // name
+ Q_strncpyz( s_playersettings.name.field.buffer, UI_Cvar_VariableString("name"), sizeof(s_playersettings.name.field.buffer) );
+
+ // effects color
+ c = trap_Cvar_VariableValue( "color1" ) - 1;
+ if( c < 0 || c > 6 ) {
+ c = 6;
+ }
+ s_playersettings.effects.curvalue = gamecodetoui[c];
+
+ // model/skin
+ memset( &s_playersettings.playerinfo, 0, sizeof(playerInfo_t) );
+
+ viewangles[YAW] = 180 - 30;
+ viewangles[PITCH] = 0;
+ viewangles[ROLL] = 0;
+
+ UI_PlayerInfo_SetModel( &s_playersettings.playerinfo, UI_Cvar_VariableString( "model" ) );
+ UI_PlayerInfo_SetInfo( &s_playersettings.playerinfo, LEGS_IDLE, TORSO_STAND, viewangles, vec3_origin, WP_MACHINEGUN, qfalse );
+
+ // handicap
+ h = Com_Clamp( 5, 100, trap_Cvar_VariableValue("handicap") );
+ s_playersettings.handicap.curvalue = 20 - h / 5;
+}
+
+
+/*
+=================
+PlayerSettings_MenuEvent
+=================
+*/
+static void PlayerSettings_MenuEvent( void* ptr, int event ) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+
+ switch( ((menucommon_s*)ptr)->id ) {
+ case ID_HANDICAP:
+ trap_Cvar_Set( "handicap", va( "%i", 100 - 25 * s_playersettings.handicap.curvalue ) );
+ break;
+
+ case ID_MODEL:
+ PlayerSettings_SaveChanges();
+ UI_PlayerModelMenu();
+ break;
+
+ case ID_BACK:
+ PlayerSettings_SaveChanges();
+ UI_PopMenu();
+ break;
+ }
+}
+
+
+/*
+=================
+PlayerSettings_MenuInit
+=================
+*/
+static void PlayerSettings_MenuInit( void ) {
+ int y;
+
+ memset(&s_playersettings,0,sizeof(playersettings_t));
+
+ PlayerSettings_Cache();
+
+ s_playersettings.menu.key = PlayerSettings_MenuKey;
+ s_playersettings.menu.wrapAround = qtrue;
+ s_playersettings.menu.fullscreen = qtrue;
+
+ s_playersettings.banner.generic.type = MTYPE_BTEXT;
+ s_playersettings.banner.generic.x = 320;
+ s_playersettings.banner.generic.y = 16;
+ s_playersettings.banner.string = "PLAYER SETTINGS";
+ s_playersettings.banner.color = color_white;
+ s_playersettings.banner.style = UI_CENTER;
+
+ s_playersettings.framel.generic.type = MTYPE_BITMAP;
+ s_playersettings.framel.generic.name = ART_FRAMEL;
+ s_playersettings.framel.generic.flags = QMF_LEFT_JUSTIFY|QMF_INACTIVE;
+ s_playersettings.framel.generic.x = 0;
+ s_playersettings.framel.generic.y = 78;
+ s_playersettings.framel.width = 256;
+ s_playersettings.framel.height = 329;
+
+ s_playersettings.framer.generic.type = MTYPE_BITMAP;
+ s_playersettings.framer.generic.name = ART_FRAMER;
+ s_playersettings.framer.generic.flags = QMF_LEFT_JUSTIFY|QMF_INACTIVE;
+ s_playersettings.framer.generic.x = 376;
+ s_playersettings.framer.generic.y = 76;
+ s_playersettings.framer.width = 256;
+ s_playersettings.framer.height = 334;
+
+ y = 144;
+ s_playersettings.name.generic.type = MTYPE_FIELD;
+ s_playersettings.name.generic.flags = QMF_NODEFAULTINIT;
+ s_playersettings.name.generic.ownerdraw = PlayerSettings_DrawName;
+ s_playersettings.name.field.widthInChars = MAX_NAMELENGTH;
+ s_playersettings.name.field.maxchars = MAX_NAMELENGTH;
+ s_playersettings.name.generic.x = 192;
+ s_playersettings.name.generic.y = y;
+ s_playersettings.name.generic.left = 192 - 8;
+ s_playersettings.name.generic.top = y - 8;
+ s_playersettings.name.generic.right = 192 + 200;
+ s_playersettings.name.generic.bottom = y + 2 * PROP_HEIGHT;
+
+ y += 3 * PROP_HEIGHT;
+ s_playersettings.handicap.generic.type = MTYPE_SPINCONTROL;
+ s_playersettings.handicap.generic.flags = QMF_NODEFAULTINIT;
+ s_playersettings.handicap.generic.id = ID_HANDICAP;
+ s_playersettings.handicap.generic.ownerdraw = PlayerSettings_DrawHandicap;
+ s_playersettings.handicap.generic.x = 192;
+ s_playersettings.handicap.generic.y = y;
+ s_playersettings.handicap.generic.left = 192 - 8;
+ s_playersettings.handicap.generic.top = y - 8;
+ s_playersettings.handicap.generic.right = 192 + 200;
+ s_playersettings.handicap.generic.bottom = y + 2 * PROP_HEIGHT;
+ s_playersettings.handicap.numitems = 20;
+
+ y += 3 * PROP_HEIGHT;
+ s_playersettings.effects.generic.type = MTYPE_SPINCONTROL;
+ s_playersettings.effects.generic.flags = QMF_NODEFAULTINIT;
+ s_playersettings.effects.generic.id = ID_EFFECTS;
+ s_playersettings.effects.generic.ownerdraw = PlayerSettings_DrawEffects;
+ s_playersettings.effects.generic.x = 192;
+ s_playersettings.effects.generic.y = y;
+ s_playersettings.effects.generic.left = 192 - 8;
+ s_playersettings.effects.generic.top = y - 8;
+ s_playersettings.effects.generic.right = 192 + 200;
+ s_playersettings.effects.generic.bottom = y + 2* PROP_HEIGHT;
+ s_playersettings.effects.numitems = 7;
+
+ s_playersettings.model.generic.type = MTYPE_BITMAP;
+ s_playersettings.model.generic.name = ART_MODEL0;
+ s_playersettings.model.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_playersettings.model.generic.id = ID_MODEL;
+ s_playersettings.model.generic.callback = PlayerSettings_MenuEvent;
+ s_playersettings.model.generic.x = 640;
+ s_playersettings.model.generic.y = 480-64;
+ s_playersettings.model.width = 128;
+ s_playersettings.model.height = 64;
+ s_playersettings.model.focuspic = ART_MODEL1;
+
+ s_playersettings.player.generic.type = MTYPE_BITMAP;
+ s_playersettings.player.generic.flags = QMF_INACTIVE;
+ s_playersettings.player.generic.ownerdraw = PlayerSettings_DrawPlayer;
+ s_playersettings.player.generic.x = 400;
+ s_playersettings.player.generic.y = -40;
+ s_playersettings.player.width = 32*10;
+ s_playersettings.player.height = 56*10;
+
+ s_playersettings.back.generic.type = MTYPE_BITMAP;
+ s_playersettings.back.generic.name = ART_BACK0;
+ s_playersettings.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_playersettings.back.generic.id = ID_BACK;
+ s_playersettings.back.generic.callback = PlayerSettings_MenuEvent;
+ s_playersettings.back.generic.x = 0;
+ s_playersettings.back.generic.y = 480-64;
+ s_playersettings.back.width = 128;
+ s_playersettings.back.height = 64;
+ s_playersettings.back.focuspic = ART_BACK1;
+
+ s_playersettings.item_null.generic.type = MTYPE_BITMAP;
+ s_playersettings.item_null.generic.flags = QMF_LEFT_JUSTIFY|QMF_MOUSEONLY|QMF_SILENT;
+ s_playersettings.item_null.generic.x = 0;
+ s_playersettings.item_null.generic.y = 0;
+ s_playersettings.item_null.width = 640;
+ s_playersettings.item_null.height = 480;
+
+ Menu_AddItem( &s_playersettings.menu, &s_playersettings.banner );
+ Menu_AddItem( &s_playersettings.menu, &s_playersettings.framel );
+ Menu_AddItem( &s_playersettings.menu, &s_playersettings.framer );
+
+ Menu_AddItem( &s_playersettings.menu, &s_playersettings.name );
+ Menu_AddItem( &s_playersettings.menu, &s_playersettings.handicap );
+ Menu_AddItem( &s_playersettings.menu, &s_playersettings.effects );
+ Menu_AddItem( &s_playersettings.menu, &s_playersettings.model );
+ Menu_AddItem( &s_playersettings.menu, &s_playersettings.back );
+
+ Menu_AddItem( &s_playersettings.menu, &s_playersettings.player );
+
+ Menu_AddItem( &s_playersettings.menu, &s_playersettings.item_null );
+
+ PlayerSettings_SetMenuItems();
+}
+
+
+/*
+=================
+PlayerSettings_Cache
+=================
+*/
+void PlayerSettings_Cache( void ) {
+ trap_R_RegisterShaderNoMip( ART_FRAMEL );
+ trap_R_RegisterShaderNoMip( ART_FRAMER );
+ trap_R_RegisterShaderNoMip( ART_MODEL0 );
+ trap_R_RegisterShaderNoMip( ART_MODEL1 );
+ trap_R_RegisterShaderNoMip( ART_BACK0 );
+ trap_R_RegisterShaderNoMip( ART_BACK1 );
+
+ s_playersettings.fxBasePic = trap_R_RegisterShaderNoMip( ART_FX_BASE );
+ s_playersettings.fxPic[0] = trap_R_RegisterShaderNoMip( ART_FX_RED );
+ s_playersettings.fxPic[1] = trap_R_RegisterShaderNoMip( ART_FX_YELLOW );
+ s_playersettings.fxPic[2] = trap_R_RegisterShaderNoMip( ART_FX_GREEN );
+ s_playersettings.fxPic[3] = trap_R_RegisterShaderNoMip( ART_FX_TEAL );
+ s_playersettings.fxPic[4] = trap_R_RegisterShaderNoMip( ART_FX_BLUE );
+ s_playersettings.fxPic[5] = trap_R_RegisterShaderNoMip( ART_FX_CYAN );
+ s_playersettings.fxPic[6] = trap_R_RegisterShaderNoMip( ART_FX_WHITE );
+}
+
+
+/*
+=================
+UI_PlayerSettingsMenu
+=================
+*/
+void UI_PlayerSettingsMenu( void ) {
+ PlayerSettings_MenuInit();
+ UI_PushMenu( &s_playersettings.menu );
+}
diff --git a/code/q3_ui/ui_preferences.c b/code/q3_ui/ui_preferences.c
new file mode 100755
index 0000000..c83ba6a
--- /dev/null
+++ b/code/q3_ui/ui_preferences.c
@@ -0,0 +1,419 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*
+=======================================================================
+
+GAME OPTIONS MENU
+
+=======================================================================
+*/
+
+
+#include "ui_local.h"
+
+
+#define ART_FRAMEL "menu/art/frame2_l"
+#define ART_FRAMER "menu/art/frame1_r"
+#define ART_BACK0 "menu/art/back_0"
+#define ART_BACK1 "menu/art/back_1"
+
+#define PREFERENCES_X_POS 360
+
+#define ID_CROSSHAIR 127
+#define ID_SIMPLEITEMS 128
+#define ID_HIGHQUALITYSKY 129
+#define ID_EJECTINGBRASS 130
+#define ID_WALLMARKS 131
+#define ID_DYNAMICLIGHTS 132
+#define ID_IDENTIFYTARGET 133
+#define ID_SYNCEVERYFRAME 134
+#define ID_FORCEMODEL 135
+#define ID_DRAWTEAMOVERLAY 136
+#define ID_ALLOWDOWNLOAD 137
+#define ID_BACK 138
+
+#define NUM_CROSSHAIRS 10
+
+
+typedef struct {
+ menuframework_s menu;
+
+ menutext_s banner;
+ menubitmap_s framel;
+ menubitmap_s framer;
+
+ menulist_s crosshair;
+ menuradiobutton_s simpleitems;
+ menuradiobutton_s brass;
+ menuradiobutton_s wallmarks;
+ menuradiobutton_s dynamiclights;
+ menuradiobutton_s identifytarget;
+ menuradiobutton_s highqualitysky;
+ menuradiobutton_s synceveryframe;
+ menuradiobutton_s forcemodel;
+ menulist_s drawteamoverlay;
+ menuradiobutton_s allowdownload;
+ menubitmap_s back;
+
+ qhandle_t crosshairShader[NUM_CROSSHAIRS];
+} preferences_t;
+
+static preferences_t s_preferences;
+
+static const char *teamoverlay_names[] =
+{
+ "off",
+ "upper right",
+ "lower right",
+ "lower left",
+ 0
+};
+
+static void Preferences_SetMenuItems( void ) {
+ s_preferences.crosshair.curvalue = (int)trap_Cvar_VariableValue( "cg_drawCrosshair" ) % NUM_CROSSHAIRS;
+ s_preferences.simpleitems.curvalue = trap_Cvar_VariableValue( "cg_simpleItems" ) != 0;
+ s_preferences.brass.curvalue = trap_Cvar_VariableValue( "cg_brassTime" ) != 0;
+ s_preferences.wallmarks.curvalue = trap_Cvar_VariableValue( "cg_marks" ) != 0;
+ s_preferences.identifytarget.curvalue = trap_Cvar_VariableValue( "cg_drawCrosshairNames" ) != 0;
+ s_preferences.dynamiclights.curvalue = trap_Cvar_VariableValue( "r_dynamiclight" ) != 0;
+ s_preferences.highqualitysky.curvalue = trap_Cvar_VariableValue ( "r_fastsky" ) == 0;
+ s_preferences.synceveryframe.curvalue = trap_Cvar_VariableValue( "r_finish" ) != 0;
+ s_preferences.forcemodel.curvalue = trap_Cvar_VariableValue( "cg_forcemodel" ) != 0;
+ s_preferences.drawteamoverlay.curvalue = Com_Clamp( 0, 3, trap_Cvar_VariableValue( "cg_drawTeamOverlay" ) );
+ s_preferences.allowdownload.curvalue = trap_Cvar_VariableValue( "cl_allowDownload" ) != 0;
+}
+
+
+static void Preferences_Event( void* ptr, int notification ) {
+ if( notification != QM_ACTIVATED ) {
+ return;
+ }
+
+ switch( ((menucommon_s*)ptr)->id ) {
+ case ID_CROSSHAIR:
+ s_preferences.crosshair.curvalue++;
+ if( s_preferences.crosshair.curvalue == NUM_CROSSHAIRS ) {
+ s_preferences.crosshair.curvalue = 0;
+ }
+ trap_Cvar_SetValue( "cg_drawCrosshair", s_preferences.crosshair.curvalue );
+ break;
+
+ case ID_SIMPLEITEMS:
+ trap_Cvar_SetValue( "cg_simpleItems", s_preferences.simpleitems.curvalue );
+ break;
+
+ case ID_HIGHQUALITYSKY:
+ trap_Cvar_SetValue( "r_fastsky", !s_preferences.highqualitysky.curvalue );
+ break;
+
+ case ID_EJECTINGBRASS:
+ if ( s_preferences.brass.curvalue )
+ trap_Cvar_Reset( "cg_brassTime" );
+ else
+ trap_Cvar_SetValue( "cg_brassTime", 0 );
+ break;
+
+ case ID_WALLMARKS:
+ trap_Cvar_SetValue( "cg_marks", s_preferences.wallmarks.curvalue );
+ break;
+
+ case ID_DYNAMICLIGHTS:
+ trap_Cvar_SetValue( "r_dynamiclight", s_preferences.dynamiclights.curvalue );
+ break;
+
+ case ID_IDENTIFYTARGET:
+ trap_Cvar_SetValue( "cg_drawCrosshairNames", s_preferences.identifytarget.curvalue );
+ break;
+
+ case ID_SYNCEVERYFRAME:
+ trap_Cvar_SetValue( "r_finish", s_preferences.synceveryframe.curvalue );
+ break;
+
+ case ID_FORCEMODEL:
+ trap_Cvar_SetValue( "cg_forcemodel", s_preferences.forcemodel.curvalue );
+ break;
+
+ case ID_DRAWTEAMOVERLAY:
+ trap_Cvar_SetValue( "cg_drawTeamOverlay", s_preferences.drawteamoverlay.curvalue );
+ break;
+
+ case ID_ALLOWDOWNLOAD:
+ trap_Cvar_SetValue( "cl_allowDownload", s_preferences.allowdownload.curvalue );
+ trap_Cvar_SetValue( "sv_allowDownload", s_preferences.allowdownload.curvalue );
+ break;
+
+ case ID_BACK:
+ UI_PopMenu();
+ break;
+ }
+}
+
+
+/*
+=================
+Crosshair_Draw
+=================
+*/
+static void Crosshair_Draw( void *self ) {
+ menulist_s *s;
+ float *color;
+ int x, y;
+ int style;
+ qboolean focus;
+
+ s = (menulist_s *)self;
+ x = s->generic.x;
+ y = s->generic.y;
+
+ style = UI_SMALLFONT;
+ focus = (s->generic.parent->cursor == s->generic.menuPosition);
+
+ if ( s->generic.flags & QMF_GRAYED )
+ color = text_color_disabled;
+ else if ( focus )
+ {
+ color = text_color_highlight;
+ style |= UI_PULSE;
+ }
+ else if ( s->generic.flags & QMF_BLINK )
+ {
+ color = text_color_highlight;
+ style |= UI_BLINK;
+ }
+ else
+ color = text_color_normal;
+
+ if ( focus )
+ {
+ // draw cursor
+ UI_FillRect( s->generic.left, s->generic.top, s->generic.right-s->generic.left+1, s->generic.bottom-s->generic.top+1, listbar_color );
+ UI_DrawChar( x, y, 13, UI_CENTER|UI_BLINK|UI_SMALLFONT, color);
+ }
+
+ UI_DrawString( x - SMALLCHAR_WIDTH, y, s->generic.name, style|UI_RIGHT, color );
+ if( !s->curvalue ) {
+ return;
+ }
+ UI_DrawHandlePic( x + SMALLCHAR_WIDTH, y - 4, 24, 24, s_preferences.crosshairShader[s->curvalue] );
+}
+
+
+static void Preferences_MenuInit( void ) {
+ int y;
+
+ memset( &s_preferences, 0 ,sizeof(preferences_t) );
+
+ Preferences_Cache();
+
+ s_preferences.menu.wrapAround = qtrue;
+ s_preferences.menu.fullscreen = qtrue;
+
+ s_preferences.banner.generic.type = MTYPE_BTEXT;
+ s_preferences.banner.generic.x = 320;
+ s_preferences.banner.generic.y = 16;
+ s_preferences.banner.string = "GAME OPTIONS";
+ s_preferences.banner.color = color_white;
+ s_preferences.banner.style = UI_CENTER;
+
+ s_preferences.framel.generic.type = MTYPE_BITMAP;
+ s_preferences.framel.generic.name = ART_FRAMEL;
+ s_preferences.framel.generic.flags = QMF_INACTIVE;
+ s_preferences.framel.generic.x = 0;
+ s_preferences.framel.generic.y = 78;
+ s_preferences.framel.width = 256;
+ s_preferences.framel.height = 329;
+
+ s_preferences.framer.generic.type = MTYPE_BITMAP;
+ s_preferences.framer.generic.name = ART_FRAMER;
+ s_preferences.framer.generic.flags = QMF_INACTIVE;
+ s_preferences.framer.generic.x = 376;
+ s_preferences.framer.generic.y = 76;
+ s_preferences.framer.width = 256;
+ s_preferences.framer.height = 334;
+
+ y = 144;
+ s_preferences.crosshair.generic.type = MTYPE_TEXT;
+ s_preferences.crosshair.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT|QMF_NODEFAULTINIT|QMF_OWNERDRAW;
+ s_preferences.crosshair.generic.x = PREFERENCES_X_POS;
+ s_preferences.crosshair.generic.y = y;
+ s_preferences.crosshair.generic.name = "Crosshair:";
+ s_preferences.crosshair.generic.callback = Preferences_Event;
+ s_preferences.crosshair.generic.ownerdraw = Crosshair_Draw;
+ s_preferences.crosshair.generic.id = ID_CROSSHAIR;
+ s_preferences.crosshair.generic.top = y - 4;
+ s_preferences.crosshair.generic.bottom = y + 20;
+ s_preferences.crosshair.generic.left = PREFERENCES_X_POS - ( ( strlen(s_preferences.crosshair.generic.name) + 1 ) * SMALLCHAR_WIDTH );
+ s_preferences.crosshair.generic.right = PREFERENCES_X_POS + 48;
+
+ y += BIGCHAR_HEIGHT+2+4;
+ s_preferences.simpleitems.generic.type = MTYPE_RADIOBUTTON;
+ s_preferences.simpleitems.generic.name = "Simple Items:";
+ s_preferences.simpleitems.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_preferences.simpleitems.generic.callback = Preferences_Event;
+ s_preferences.simpleitems.generic.id = ID_SIMPLEITEMS;
+ s_preferences.simpleitems.generic.x = PREFERENCES_X_POS;
+ s_preferences.simpleitems.generic.y = y;
+
+ y += BIGCHAR_HEIGHT;
+ s_preferences.wallmarks.generic.type = MTYPE_RADIOBUTTON;
+ s_preferences.wallmarks.generic.name = "Marks on Walls:";
+ s_preferences.wallmarks.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_preferences.wallmarks.generic.callback = Preferences_Event;
+ s_preferences.wallmarks.generic.id = ID_WALLMARKS;
+ s_preferences.wallmarks.generic.x = PREFERENCES_X_POS;
+ s_preferences.wallmarks.generic.y = y;
+
+ y += BIGCHAR_HEIGHT+2;
+ s_preferences.brass.generic.type = MTYPE_RADIOBUTTON;
+ s_preferences.brass.generic.name = "Ejecting Brass:";
+ s_preferences.brass.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_preferences.brass.generic.callback = Preferences_Event;
+ s_preferences.brass.generic.id = ID_EJECTINGBRASS;
+ s_preferences.brass.generic.x = PREFERENCES_X_POS;
+ s_preferences.brass.generic.y = y;
+
+ y += BIGCHAR_HEIGHT+2;
+ s_preferences.dynamiclights.generic.type = MTYPE_RADIOBUTTON;
+ s_preferences.dynamiclights.generic.name = "Dynamic Lights:";
+ s_preferences.dynamiclights.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_preferences.dynamiclights.generic.callback = Preferences_Event;
+ s_preferences.dynamiclights.generic.id = ID_DYNAMICLIGHTS;
+ s_preferences.dynamiclights.generic.x = PREFERENCES_X_POS;
+ s_preferences.dynamiclights.generic.y = y;
+
+ y += BIGCHAR_HEIGHT+2;
+ s_preferences.identifytarget.generic.type = MTYPE_RADIOBUTTON;
+ s_preferences.identifytarget.generic.name = "Identify Target:";
+ s_preferences.identifytarget.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_preferences.identifytarget.generic.callback = Preferences_Event;
+ s_preferences.identifytarget.generic.id = ID_IDENTIFYTARGET;
+ s_preferences.identifytarget.generic.x = PREFERENCES_X_POS;
+ s_preferences.identifytarget.generic.y = y;
+
+ y += BIGCHAR_HEIGHT+2;
+ s_preferences.highqualitysky.generic.type = MTYPE_RADIOBUTTON;
+ s_preferences.highqualitysky.generic.name = "High Quality Sky:";
+ s_preferences.highqualitysky.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_preferences.highqualitysky.generic.callback = Preferences_Event;
+ s_preferences.highqualitysky.generic.id = ID_HIGHQUALITYSKY;
+ s_preferences.highqualitysky.generic.x = PREFERENCES_X_POS;
+ s_preferences.highqualitysky.generic.y = y;
+
+ y += BIGCHAR_HEIGHT+2;
+ s_preferences.synceveryframe.generic.type = MTYPE_RADIOBUTTON;
+ s_preferences.synceveryframe.generic.name = "Sync Every Frame:";
+ s_preferences.synceveryframe.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_preferences.synceveryframe.generic.callback = Preferences_Event;
+ s_preferences.synceveryframe.generic.id = ID_SYNCEVERYFRAME;
+ s_preferences.synceveryframe.generic.x = PREFERENCES_X_POS;
+ s_preferences.synceveryframe.generic.y = y;
+
+ y += BIGCHAR_HEIGHT+2;
+ s_preferences.forcemodel.generic.type = MTYPE_RADIOBUTTON;
+ s_preferences.forcemodel.generic.name = "Force Player Models:";
+ s_preferences.forcemodel.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_preferences.forcemodel.generic.callback = Preferences_Event;
+ s_preferences.forcemodel.generic.id = ID_FORCEMODEL;
+ s_preferences.forcemodel.generic.x = PREFERENCES_X_POS;
+ s_preferences.forcemodel.generic.y = y;
+
+ y += BIGCHAR_HEIGHT+2;
+ s_preferences.drawteamoverlay.generic.type = MTYPE_SPINCONTROL;
+ s_preferences.drawteamoverlay.generic.name = "Draw Team Overlay:";
+ s_preferences.drawteamoverlay.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_preferences.drawteamoverlay.generic.callback = Preferences_Event;
+ s_preferences.drawteamoverlay.generic.id = ID_DRAWTEAMOVERLAY;
+ s_preferences.drawteamoverlay.generic.x = PREFERENCES_X_POS;
+ s_preferences.drawteamoverlay.generic.y = y;
+ s_preferences.drawteamoverlay.itemnames = teamoverlay_names;
+
+ y += BIGCHAR_HEIGHT+2;
+ s_preferences.allowdownload.generic.type = MTYPE_RADIOBUTTON;
+ s_preferences.allowdownload.generic.name = "Automatic Downloading:";
+ s_preferences.allowdownload.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_preferences.allowdownload.generic.callback = Preferences_Event;
+ s_preferences.allowdownload.generic.id = ID_ALLOWDOWNLOAD;
+ s_preferences.allowdownload.generic.x = PREFERENCES_X_POS;
+ s_preferences.allowdownload.generic.y = y;
+
+ y += BIGCHAR_HEIGHT+2;
+ s_preferences.back.generic.type = MTYPE_BITMAP;
+ s_preferences.back.generic.name = ART_BACK0;
+ s_preferences.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_preferences.back.generic.callback = Preferences_Event;
+ s_preferences.back.generic.id = ID_BACK;
+ s_preferences.back.generic.x = 0;
+ s_preferences.back.generic.y = 480-64;
+ s_preferences.back.width = 128;
+ s_preferences.back.height = 64;
+ s_preferences.back.focuspic = ART_BACK1;
+
+ Menu_AddItem( &s_preferences.menu, &s_preferences.banner );
+ Menu_AddItem( &s_preferences.menu, &s_preferences.framel );
+ Menu_AddItem( &s_preferences.menu, &s_preferences.framer );
+
+ Menu_AddItem( &s_preferences.menu, &s_preferences.crosshair );
+ Menu_AddItem( &s_preferences.menu, &s_preferences.simpleitems );
+ Menu_AddItem( &s_preferences.menu, &s_preferences.wallmarks );
+ Menu_AddItem( &s_preferences.menu, &s_preferences.brass );
+ Menu_AddItem( &s_preferences.menu, &s_preferences.dynamiclights );
+ Menu_AddItem( &s_preferences.menu, &s_preferences.identifytarget );
+ Menu_AddItem( &s_preferences.menu, &s_preferences.highqualitysky );
+ Menu_AddItem( &s_preferences.menu, &s_preferences.synceveryframe );
+ Menu_AddItem( &s_preferences.menu, &s_preferences.forcemodel );
+ Menu_AddItem( &s_preferences.menu, &s_preferences.drawteamoverlay );
+ Menu_AddItem( &s_preferences.menu, &s_preferences.allowdownload );
+
+ Menu_AddItem( &s_preferences.menu, &s_preferences.back );
+
+ Preferences_SetMenuItems();
+}
+
+
+/*
+===============
+Preferences_Cache
+===============
+*/
+void Preferences_Cache( void ) {
+ int n;
+
+ trap_R_RegisterShaderNoMip( ART_FRAMEL );
+ trap_R_RegisterShaderNoMip( ART_FRAMER );
+ trap_R_RegisterShaderNoMip( ART_BACK0 );
+ trap_R_RegisterShaderNoMip( ART_BACK1 );
+ for( n = 0; n < NUM_CROSSHAIRS; n++ ) {
+ s_preferences.crosshairShader[n] = trap_R_RegisterShaderNoMip( va("gfx/2d/crosshair%c", 'a' + n ) );
+ }
+}
+
+
+/*
+===============
+UI_PreferencesMenu
+===============
+*/
+void UI_PreferencesMenu( void ) {
+ Preferences_MenuInit();
+ UI_PushMenu( &s_preferences.menu );
+}
diff --git a/code/q3_ui/ui_qmenu.c b/code/q3_ui/ui_qmenu.c
new file mode 100755
index 0000000..400448a
--- /dev/null
+++ b/code/q3_ui/ui_qmenu.c
@@ -0,0 +1,1746 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/**********************************************************************
+ UI_QMENU.C
+
+ Quake's menu framework system.
+**********************************************************************/
+#include "ui_local.h"
+
+sfxHandle_t menu_in_sound;
+sfxHandle_t menu_move_sound;
+sfxHandle_t menu_out_sound;
+sfxHandle_t menu_buzz_sound;
+sfxHandle_t menu_null_sound;
+sfxHandle_t weaponChangeSound;
+
+static qhandle_t sliderBar;
+static qhandle_t sliderButton_0;
+static qhandle_t sliderButton_1;
+
+vec4_t menu_text_color = {1.0f, 1.0f, 1.0f, 1.0f};
+vec4_t menu_dim_color = {0.0f, 0.0f, 0.0f, 0.75f};
+vec4_t color_black = {0.00f, 0.00f, 0.00f, 1.00f};
+vec4_t color_white = {1.00f, 1.00f, 1.00f, 1.00f};
+vec4_t color_yellow = {1.00f, 1.00f, 0.00f, 1.00f};
+vec4_t color_blue = {0.00f, 0.00f, 1.00f, 1.00f};
+vec4_t color_lightOrange = {1.00f, 0.68f, 0.00f, 1.00f };
+vec4_t color_orange = {1.00f, 0.43f, 0.00f, 1.00f};
+vec4_t color_red = {1.00f, 0.00f, 0.00f, 1.00f};
+vec4_t color_dim = {0.00f, 0.00f, 0.00f, 0.25f};
+
+// current color scheme
+vec4_t pulse_color = {1.00f, 1.00f, 1.00f, 1.00f};
+vec4_t text_color_disabled = {0.50f, 0.50f, 0.50f, 1.00f}; // light gray
+vec4_t text_color_normal = {1.00f, 0.43f, 0.00f, 1.00f}; // light orange
+vec4_t text_color_highlight = {1.00f, 1.00f, 0.00f, 1.00f}; // bright yellow
+vec4_t listbar_color = {1.00f, 0.43f, 0.00f, 0.30f}; // transluscent orange
+vec4_t text_color_status = {1.00f, 1.00f, 1.00f, 1.00f}; // bright white
+
+// action widget
+static void Action_Init( menuaction_s *a );
+static void Action_Draw( menuaction_s *a );
+
+// radio button widget
+static void RadioButton_Init( menuradiobutton_s *rb );
+static void RadioButton_Draw( menuradiobutton_s *rb );
+static sfxHandle_t RadioButton_Key( menuradiobutton_s *rb, int key );
+
+// slider widget
+static void Slider_Init( menuslider_s *s );
+static sfxHandle_t Slider_Key( menuslider_s *s, int key );
+static void Slider_Draw( menuslider_s *s );
+
+// spin control widget
+static void SpinControl_Init( menulist_s *s );
+static void SpinControl_Draw( menulist_s *s );
+static sfxHandle_t SpinControl_Key( menulist_s *l, int key );
+
+// text widget
+static void Text_Init( menutext_s *b );
+static void Text_Draw( menutext_s *b );
+
+// scrolllist widget
+static void ScrollList_Init( menulist_s *l );
+sfxHandle_t ScrollList_Key( menulist_s *l, int key );
+
+// proportional text widget
+static void PText_Init( menutext_s *b );
+static void PText_Draw( menutext_s *b );
+
+// proportional banner text widget
+static void BText_Init( menutext_s *b );
+static void BText_Draw( menutext_s *b );
+
+/*
+=================
+Text_Init
+=================
+*/
+static void Text_Init( menutext_s *t )
+{
+ t->generic.flags |= QMF_INACTIVE;
+}
+
+/*
+=================
+Text_Draw
+=================
+*/
+static void Text_Draw( menutext_s *t )
+{
+ int x;
+ int y;
+ char buff[512];
+ float* color;
+
+ x = t->generic.x;
+ y = t->generic.y;
+
+ buff[0] = '\0';
+
+ // possible label
+ if (t->generic.name)
+ strcpy(buff,t->generic.name);
+
+ // possible value
+ if (t->string)
+ strcat(buff,t->string);
+
+ if (t->generic.flags & QMF_GRAYED)
+ color = text_color_disabled;
+ else
+ color = t->color;
+
+ UI_DrawString( x, y, buff, t->style, color );
+}
+
+/*
+=================
+BText_Init
+=================
+*/
+static void BText_Init( menutext_s *t )
+{
+ t->generic.flags |= QMF_INACTIVE;
+}
+
+/*
+=================
+BText_Draw
+=================
+*/
+static void BText_Draw( menutext_s *t )
+{
+ int x;
+ int y;
+ float* color;
+
+ x = t->generic.x;
+ y = t->generic.y;
+
+ if (t->generic.flags & QMF_GRAYED)
+ color = text_color_disabled;
+ else
+ color = t->color;
+
+ UI_DrawBannerString( x, y, t->string, t->style, color );
+}
+
+/*
+=================
+PText_Init
+=================
+*/
+static void PText_Init( menutext_s *t )
+{
+ int x;
+ int y;
+ int w;
+ int h;
+ float sizeScale;
+
+ sizeScale = UI_ProportionalSizeScale( t->style );
+
+ x = t->generic.x;
+ y = t->generic.y;
+ w = UI_ProportionalStringWidth( t->string ) * sizeScale;
+ h = PROP_HEIGHT * sizeScale;
+
+ if( t->generic.flags & QMF_RIGHT_JUSTIFY ) {
+ x -= w;
+ }
+ else if( t->generic.flags & QMF_CENTER_JUSTIFY ) {
+ x -= w / 2;
+ }
+
+ t->generic.left = x - PROP_GAP_WIDTH * sizeScale;
+ t->generic.right = x + w + PROP_GAP_WIDTH * sizeScale;
+ t->generic.top = y;
+ t->generic.bottom = y + h;
+}
+
+/*
+=================
+PText_Draw
+=================
+*/
+static void PText_Draw( menutext_s *t )
+{
+ int x;
+ int y;
+ float * color;
+ int style;
+
+ x = t->generic.x;
+ y = t->generic.y;
+
+ if (t->generic.flags & QMF_GRAYED)
+ color = text_color_disabled;
+ else
+ color = t->color;
+
+ style = t->style;
+ if( t->generic.flags & QMF_PULSEIFFOCUS ) {
+ if( Menu_ItemAtCursor( t->generic.parent ) == t ) {
+ style |= UI_PULSE;
+ }
+ else {
+ style |= UI_INVERSE;
+ }
+ }
+
+ UI_DrawProportionalString( x, y, t->string, style, color );
+}
+
+/*
+=================
+Bitmap_Init
+=================
+*/
+void Bitmap_Init( menubitmap_s *b )
+{
+ int x;
+ int y;
+ int w;
+ int h;
+
+ x = b->generic.x;
+ y = b->generic.y;
+ w = b->width;
+ h = b->height;
+ if( w < 0 ) {
+ w = -w;
+ }
+ if( h < 0 ) {
+ h = -h;
+ }
+
+ if (b->generic.flags & QMF_RIGHT_JUSTIFY)
+ {
+ x = x - w;
+ }
+ else if (b->generic.flags & QMF_CENTER_JUSTIFY)
+ {
+ x = x - w/2;
+ }
+
+ b->generic.left = x;
+ b->generic.right = x + w;
+ b->generic.top = y;
+ b->generic.bottom = y + h;
+
+ b->shader = 0;
+ b->focusshader = 0;
+}
+
+/*
+=================
+Bitmap_Draw
+=================
+*/
+void Bitmap_Draw( menubitmap_s *b )
+{
+ float x;
+ float y;
+ float w;
+ float h;
+ vec4_t tempcolor;
+ float* color;
+
+ x = b->generic.x;
+ y = b->generic.y;
+ w = b->width;
+ h = b->height;
+
+ if (b->generic.flags & QMF_RIGHT_JUSTIFY)
+ {
+ x = x - w;
+ }
+ else if (b->generic.flags & QMF_CENTER_JUSTIFY)
+ {
+ x = x - w/2;
+ }
+
+ // used to refresh shader
+ if (b->generic.name && !b->shader)
+ {
+ b->shader = trap_R_RegisterShaderNoMip( b->generic.name );
+ if (!b->shader && b->errorpic)
+ b->shader = trap_R_RegisterShaderNoMip( b->errorpic );
+ }
+
+ if (b->focuspic && !b->focusshader)
+ b->focusshader = trap_R_RegisterShaderNoMip( b->focuspic );
+
+ if (b->generic.flags & QMF_GRAYED)
+ {
+ if (b->shader)
+ {
+ trap_R_SetColor( colorMdGrey );
+ UI_DrawHandlePic( x, y, w, h, b->shader );
+ trap_R_SetColor( NULL );
+ }
+ }
+ else
+ {
+ if (b->shader)
+ UI_DrawHandlePic( x, y, w, h, b->shader );
+
+ // bk001204 - parentheses
+ if ( ( (b->generic.flags & QMF_PULSE)
+ || (b->generic.flags & QMF_PULSEIFFOCUS) )
+ && (Menu_ItemAtCursor( b->generic.parent ) == b))
+ {
+ if (b->focuscolor)
+ {
+ tempcolor[0] = b->focuscolor[0];
+ tempcolor[1] = b->focuscolor[1];
+ tempcolor[2] = b->focuscolor[2];
+ color = tempcolor;
+ }
+ else
+ color = pulse_color;
+ color[3] = 0.5+0.5*sin(uis.realtime/PULSE_DIVISOR);
+
+ trap_R_SetColor( color );
+ UI_DrawHandlePic( x, y, w, h, b->focusshader );
+ trap_R_SetColor( NULL );
+ }
+ else if ((b->generic.flags & QMF_HIGHLIGHT) || ((b->generic.flags & QMF_HIGHLIGHT_IF_FOCUS) && (Menu_ItemAtCursor( b->generic.parent ) == b)))
+ {
+ if (b->focuscolor)
+ {
+ trap_R_SetColor( b->focuscolor );
+ UI_DrawHandlePic( x, y, w, h, b->focusshader );
+ trap_R_SetColor( NULL );
+ }
+ else
+ UI_DrawHandlePic( x, y, w, h, b->focusshader );
+ }
+ }
+}
+
+/*
+=================
+Action_Init
+=================
+*/
+static void Action_Init( menuaction_s *a )
+{
+ int len;
+
+ // calculate bounds
+ if (a->generic.name)
+ len = strlen(a->generic.name);
+ else
+ len = 0;
+
+ // left justify text
+ a->generic.left = a->generic.x;
+ a->generic.right = a->generic.x + len*BIGCHAR_WIDTH;
+ a->generic.top = a->generic.y;
+ a->generic.bottom = a->generic.y + BIGCHAR_HEIGHT;
+}
+
+/*
+=================
+Action_Draw
+=================
+*/
+static void Action_Draw( menuaction_s *a )
+{
+ int x, y;
+ int style;
+ float* color;
+
+ style = 0;
+ color = menu_text_color;
+ if ( a->generic.flags & QMF_GRAYED )
+ {
+ color = text_color_disabled;
+ }
+ else if (( a->generic.flags & QMF_PULSEIFFOCUS ) && ( a->generic.parent->cursor == a->generic.menuPosition ))
+ {
+ color = text_color_highlight;
+ style = UI_PULSE;
+ }
+ else if (( a->generic.flags & QMF_HIGHLIGHT_IF_FOCUS ) && ( a->generic.parent->cursor == a->generic.menuPosition ))
+ {
+ color = text_color_highlight;
+ }
+ else if ( a->generic.flags & QMF_BLINK )
+ {
+ style = UI_BLINK;
+ color = text_color_highlight;
+ }
+
+ x = a->generic.x;
+ y = a->generic.y;
+
+ UI_DrawString( x, y, a->generic.name, UI_LEFT|style, color );
+
+ if ( a->generic.parent->cursor == a->generic.menuPosition )
+ {
+ // draw cursor
+ UI_DrawChar( x - BIGCHAR_WIDTH, y, 13, UI_LEFT|UI_BLINK, color);
+ }
+}
+
+/*
+=================
+RadioButton_Init
+=================
+*/
+static void RadioButton_Init( menuradiobutton_s *rb )
+{
+ int len;
+
+ // calculate bounds
+ if (rb->generic.name)
+ len = strlen(rb->generic.name);
+ else
+ len = 0;
+
+ rb->generic.left = rb->generic.x - (len+1)*SMALLCHAR_WIDTH;
+ rb->generic.right = rb->generic.x + 6*SMALLCHAR_WIDTH;
+ rb->generic.top = rb->generic.y;
+ rb->generic.bottom = rb->generic.y + SMALLCHAR_HEIGHT;
+}
+
+/*
+=================
+RadioButton_Key
+=================
+*/
+static sfxHandle_t RadioButton_Key( menuradiobutton_s *rb, int key )
+{
+ switch (key)
+ {
+ case K_MOUSE1:
+ if (!(rb->generic.flags & QMF_HASMOUSEFOCUS))
+ break;
+
+ case K_JOY1:
+ case K_JOY2:
+ case K_JOY3:
+ case K_JOY4:
+ case K_ENTER:
+ case K_KP_ENTER:
+ case K_KP_LEFTARROW:
+ case K_LEFTARROW:
+ case K_KP_RIGHTARROW:
+ case K_RIGHTARROW:
+ rb->curvalue = !rb->curvalue;
+ if ( rb->generic.callback )
+ rb->generic.callback( rb, QM_ACTIVATED );
+
+ return (menu_move_sound);
+ }
+
+ // key not handled
+ return 0;
+}
+
+/*
+=================
+RadioButton_Draw
+=================
+*/
+static void RadioButton_Draw( menuradiobutton_s *rb )
+{
+ int x;
+ int y;
+ float *color;
+ int style;
+ qboolean focus;
+
+ x = rb->generic.x;
+ y = rb->generic.y;
+
+ focus = (rb->generic.parent->cursor == rb->generic.menuPosition);
+
+ if ( rb->generic.flags & QMF_GRAYED )
+ {
+ color = text_color_disabled;
+ style = UI_LEFT|UI_SMALLFONT;
+ }
+ else if ( focus )
+ {
+ color = text_color_highlight;
+ style = UI_LEFT|UI_PULSE|UI_SMALLFONT;
+ }
+ else
+ {
+ color = text_color_normal;
+ style = UI_LEFT|UI_SMALLFONT;
+ }
+
+ if ( focus )
+ {
+ // draw cursor
+ UI_FillRect( rb->generic.left, rb->generic.top, rb->generic.right-rb->generic.left+1, rb->generic.bottom-rb->generic.top+1, listbar_color );
+ UI_DrawChar( x, y, 13, UI_CENTER|UI_BLINK|UI_SMALLFONT, color);
+ }
+
+ if ( rb->generic.name )
+ UI_DrawString( x - SMALLCHAR_WIDTH, y, rb->generic.name, UI_RIGHT|UI_SMALLFONT, color );
+
+ if ( !rb->curvalue )
+ {
+ UI_DrawHandlePic( x + SMALLCHAR_WIDTH, y + 2, 16, 16, uis.rb_off);
+ UI_DrawString( x + SMALLCHAR_WIDTH + 16, y, "off", style, color );
+ }
+ else
+ {
+ UI_DrawHandlePic( x + SMALLCHAR_WIDTH, y + 2, 16, 16, uis.rb_on );
+ UI_DrawString( x + SMALLCHAR_WIDTH + 16, y, "on", style, color );
+ }
+}
+
+/*
+=================
+Slider_Init
+=================
+*/
+static void Slider_Init( menuslider_s *s )
+{
+ int len;
+
+ // calculate bounds
+ if (s->generic.name)
+ len = strlen(s->generic.name);
+ else
+ len = 0;
+
+ s->generic.left = s->generic.x - (len+1)*SMALLCHAR_WIDTH;
+ s->generic.right = s->generic.x + (SLIDER_RANGE+2+1)*SMALLCHAR_WIDTH;
+ s->generic.top = s->generic.y;
+ s->generic.bottom = s->generic.y + SMALLCHAR_HEIGHT;
+}
+
+/*
+=================
+Slider_Key
+=================
+*/
+static sfxHandle_t Slider_Key( menuslider_s *s, int key )
+{
+ sfxHandle_t sound;
+ int x;
+ int oldvalue;
+
+ switch (key)
+ {
+ case K_MOUSE1:
+ x = uis.cursorx - s->generic.x - 2*SMALLCHAR_WIDTH;
+ oldvalue = s->curvalue;
+ s->curvalue = (x/(float)(SLIDER_RANGE*SMALLCHAR_WIDTH)) * (s->maxvalue-s->minvalue) + s->minvalue;
+
+ if (s->curvalue < s->minvalue)
+ s->curvalue = s->minvalue;
+ else if (s->curvalue > s->maxvalue)
+ s->curvalue = s->maxvalue;
+ if (s->curvalue != oldvalue)
+ sound = menu_move_sound;
+ else
+ sound = 0;
+ break;
+
+ case K_KP_LEFTARROW:
+ case K_LEFTARROW:
+ if (s->curvalue > s->minvalue)
+ {
+ s->curvalue--;
+ sound = menu_move_sound;
+ }
+ else
+ sound = menu_buzz_sound;
+ break;
+
+ case K_KP_RIGHTARROW:
+ case K_RIGHTARROW:
+ if (s->curvalue < s->maxvalue)
+ {
+ s->curvalue++;
+ sound = menu_move_sound;
+ }
+ else
+ sound = menu_buzz_sound;
+ break;
+
+ default:
+ // key not handled
+ sound = 0;
+ break;
+ }
+
+ if ( sound && s->generic.callback )
+ s->generic.callback( s, QM_ACTIVATED );
+
+ return (sound);
+}
+
+#if 1
+/*
+=================
+Slider_Draw
+=================
+*/
+static void Slider_Draw( menuslider_s *s ) {
+ int x;
+ int y;
+ int style;
+ float *color;
+ int button;
+ qboolean focus;
+
+ x = s->generic.x;
+ y = s->generic.y;
+ focus = (s->generic.parent->cursor == s->generic.menuPosition);
+
+ if( s->generic.flags & QMF_GRAYED ) {
+ color = text_color_disabled;
+ style = UI_SMALLFONT;
+ }
+ else if( focus ) {
+ color = text_color_highlight;
+ style = UI_SMALLFONT | UI_PULSE;
+ }
+ else {
+ color = text_color_normal;
+ style = UI_SMALLFONT;
+ }
+
+ // draw label
+ UI_DrawString( x - SMALLCHAR_WIDTH, y, s->generic.name, UI_RIGHT|style, color );
+
+ // draw slider
+ UI_SetColor( color );
+ UI_DrawHandlePic( x + SMALLCHAR_WIDTH, y, 96, 16, sliderBar );
+ UI_SetColor( NULL );
+
+ // clamp thumb
+ if( s->maxvalue > s->minvalue ) {
+ s->range = ( s->curvalue - s->minvalue ) / ( float ) ( s->maxvalue - s->minvalue );
+ if( s->range < 0 ) {
+ s->range = 0;
+ }
+ else if( s->range > 1) {
+ s->range = 1;
+ }
+ }
+ else {
+ s->range = 0;
+ }
+
+ // draw thumb
+ if( style & UI_PULSE) {
+ button = sliderButton_1;
+ }
+ else {
+ button = sliderButton_0;
+ }
+
+ UI_DrawHandlePic( (int)( x + 2*SMALLCHAR_WIDTH + (SLIDER_RANGE-1)*SMALLCHAR_WIDTH* s->range ) - 2, y - 2, 12, 20, button );
+}
+#else
+/*
+=================
+Slider_Draw
+=================
+*/
+static void Slider_Draw( menuslider_s *s )
+{
+ float *color;
+ int style;
+ int i;
+ int x;
+ int y;
+ qboolean focus;
+
+ x = s->generic.x;
+ y = s->generic.y;
+ focus = (s->generic.parent->cursor == s->generic.menuPosition);
+
+ style = UI_SMALLFONT;
+ if ( s->generic.flags & QMF_GRAYED )
+ {
+ color = text_color_disabled;
+ }
+ else if (focus)
+ {
+ color = text_color_highlight;
+ style |= UI_PULSE;
+ }
+ else
+ {
+ color = text_color_normal;
+ }
+
+ if ( focus )
+ {
+ // draw cursor
+ UI_FillRect( s->generic.left, s->generic.top, s->generic.right-s->generic.left+1, s->generic.bottom-s->generic.top+1, listbar_color );
+ UI_DrawChar( x, y, 13, UI_CENTER|UI_BLINK|UI_SMALLFONT, color);
+ }
+
+ // draw label
+ UI_DrawString( x - SMALLCHAR_WIDTH, y, s->generic.name, UI_RIGHT|style, color );
+
+ // draw slider
+ UI_DrawChar( x + SMALLCHAR_WIDTH, y, 128, UI_LEFT|style, color);
+ for ( i = 0; i < SLIDER_RANGE; i++ )
+ UI_DrawChar( x + (i+2)*SMALLCHAR_WIDTH, y, 129, UI_LEFT|style, color);
+ UI_DrawChar( x + (i+2)*SMALLCHAR_WIDTH, y, 130, UI_LEFT|style, color);
+
+ // clamp thumb
+ if (s->maxvalue > s->minvalue)
+ {
+ s->range = ( s->curvalue - s->minvalue ) / ( float ) ( s->maxvalue - s->minvalue );
+ if ( s->range < 0)
+ s->range = 0;
+ else if ( s->range > 1)
+ s->range = 1;
+ }
+ else
+ s->range = 0;
+
+ // draw thumb
+ if (style & UI_PULSE) {
+ style &= ~UI_PULSE;
+ style |= UI_BLINK;
+ }
+ UI_DrawChar( (int)( x + 2*SMALLCHAR_WIDTH + (SLIDER_RANGE-1)*SMALLCHAR_WIDTH* s->range ), y, 131, UI_LEFT|style, color);
+}
+#endif
+
+/*
+=================
+SpinControl_Init
+=================
+*/
+static void SpinControl_Init( menulist_s *s ) {
+ int len;
+ int l;
+ const char* str;
+
+ if (s->generic.name)
+ len = strlen(s->generic.name) * SMALLCHAR_WIDTH;
+ else
+ len = 0;
+
+ s->generic.left = s->generic.x - SMALLCHAR_WIDTH - len;
+
+ len = s->numitems = 0;
+ while ( (str = s->itemnames[s->numitems]) != 0 )
+ {
+ l = strlen(str);
+ if (l > len)
+ len = l;
+
+ s->numitems++;
+ }
+
+ s->generic.top = s->generic.y;
+ s->generic.right = s->generic.x + (len+1)*SMALLCHAR_WIDTH;
+ s->generic.bottom = s->generic.y + SMALLCHAR_HEIGHT;
+}
+
+/*
+=================
+SpinControl_Key
+=================
+*/
+static sfxHandle_t SpinControl_Key( menulist_s *s, int key )
+{
+ sfxHandle_t sound;
+
+ sound = 0;
+ switch (key)
+ {
+ case K_MOUSE1:
+ s->curvalue++;
+ if (s->curvalue >= s->numitems)
+ s->curvalue = 0;
+ sound = menu_move_sound;
+ break;
+
+ case K_KP_LEFTARROW:
+ case K_LEFTARROW:
+ if (s->curvalue > 0)
+ {
+ s->curvalue--;
+ sound = menu_move_sound;
+ }
+ else
+ sound = menu_buzz_sound;
+ break;
+
+ case K_KP_RIGHTARROW:
+ case K_RIGHTARROW:
+ if (s->curvalue < s->numitems-1)
+ {
+ s->curvalue++;
+ sound = menu_move_sound;
+ }
+ else
+ sound = menu_buzz_sound;
+ break;
+ }
+
+ if ( sound && s->generic.callback )
+ s->generic.callback( s, QM_ACTIVATED );
+
+ return (sound);
+}
+
+/*
+=================
+SpinControl_Draw
+=================
+*/
+static void SpinControl_Draw( menulist_s *s )
+{
+ float *color;
+ int x,y;
+ int style;
+ qboolean focus;
+
+ x = s->generic.x;
+ y = s->generic.y;
+
+ style = UI_SMALLFONT;
+ focus = (s->generic.parent->cursor == s->generic.menuPosition);
+
+ if ( s->generic.flags & QMF_GRAYED )
+ color = text_color_disabled;
+ else if ( focus )
+ {
+ color = text_color_highlight;
+ style |= UI_PULSE;
+ }
+ else if ( s->generic.flags & QMF_BLINK )
+ {
+ color = text_color_highlight;
+ style |= UI_BLINK;
+ }
+ else
+ color = text_color_normal;
+
+ if ( focus )
+ {
+ // draw cursor
+ UI_FillRect( s->generic.left, s->generic.top, s->generic.right-s->generic.left+1, s->generic.bottom-s->generic.top+1, listbar_color );
+ UI_DrawChar( x, y, 13, UI_CENTER|UI_BLINK|UI_SMALLFONT, color);
+ }
+
+ UI_DrawString( x - SMALLCHAR_WIDTH, y, s->generic.name, style|UI_RIGHT, color );
+ UI_DrawString( x + SMALLCHAR_WIDTH, y, s->itemnames[s->curvalue], style|UI_LEFT, color );
+}
+
+/*
+=================
+ScrollList_Init
+=================
+*/
+static void ScrollList_Init( menulist_s *l )
+{
+ int w;
+
+ l->oldvalue = 0;
+ l->curvalue = 0;
+ l->top = 0;
+
+ if( !l->columns ) {
+ l->columns = 1;
+ l->seperation = 0;
+ }
+ else if( !l->seperation ) {
+ l->seperation = 3;
+ }
+
+ w = ( (l->width + l->seperation) * l->columns - l->seperation) * SMALLCHAR_WIDTH;
+
+ l->generic.left = l->generic.x;
+ l->generic.top = l->generic.y;
+ l->generic.right = l->generic.x + w;
+ l->generic.bottom = l->generic.y + l->height * SMALLCHAR_HEIGHT;
+
+ if( l->generic.flags & QMF_CENTER_JUSTIFY ) {
+ l->generic.left -= w / 2;
+ l->generic.right -= w / 2;
+ }
+}
+
+/*
+=================
+ScrollList_Key
+=================
+*/
+sfxHandle_t ScrollList_Key( menulist_s *l, int key )
+{
+ int x;
+ int y;
+ int w;
+ int i;
+ int j;
+ int c;
+ int cursorx;
+ int cursory;
+ int column;
+ int index;
+
+ switch (key)
+ {
+ case K_MOUSE1:
+ if (l->generic.flags & QMF_HASMOUSEFOCUS)
+ {
+ // check scroll region
+ x = l->generic.x;
+ y = l->generic.y;
+ w = ( (l->width + l->seperation) * l->columns - l->seperation) * SMALLCHAR_WIDTH;
+ if( l->generic.flags & QMF_CENTER_JUSTIFY ) {
+ x -= w / 2;
+ }
+ if (UI_CursorInRect( x, y, w, l->height*SMALLCHAR_HEIGHT ))
+ {
+ cursorx = (uis.cursorx - x)/SMALLCHAR_WIDTH;
+ column = cursorx / (l->width + l->seperation);
+ cursory = (uis.cursory - y)/SMALLCHAR_HEIGHT;
+ index = column * l->height + cursory;
+ if (l->top + index < l->numitems)
+ {
+ l->oldvalue = l->curvalue;
+ l->curvalue = l->top + index;
+
+ if (l->oldvalue != l->curvalue && l->generic.callback)
+ {
+ l->generic.callback( l, QM_GOTFOCUS );
+ return (menu_move_sound);
+ }
+ }
+ }
+
+ // absorbed, silent sound effect
+ return (menu_null_sound);
+ }
+ break;
+
+ case K_KP_HOME:
+ case K_HOME:
+ l->oldvalue = l->curvalue;
+ l->curvalue = 0;
+ l->top = 0;
+
+ if (l->oldvalue != l->curvalue && l->generic.callback)
+ {
+ l->generic.callback( l, QM_GOTFOCUS );
+ return (menu_move_sound);
+ }
+ return (menu_buzz_sound);
+
+ case K_KP_END:
+ case K_END:
+ l->oldvalue = l->curvalue;
+ l->curvalue = l->numitems-1;
+ if( l->columns > 1 ) {
+ c = (l->curvalue / l->height + 1) * l->height;
+ l->top = c - (l->columns * l->height);
+ }
+ else {
+ l->top = l->curvalue - (l->height - 1);
+ }
+ if (l->top < 0)
+ l->top = 0;
+
+ if (l->oldvalue != l->curvalue && l->generic.callback)
+ {
+ l->generic.callback( l, QM_GOTFOCUS );
+ return (menu_move_sound);
+ }
+ return (menu_buzz_sound);
+
+ case K_PGUP:
+ case K_KP_PGUP:
+ if( l->columns > 1 ) {
+ return menu_null_sound;
+ }
+
+ if (l->curvalue > 0)
+ {
+ l->oldvalue = l->curvalue;
+ l->curvalue -= l->height-1;
+ if (l->curvalue < 0)
+ l->curvalue = 0;
+ l->top = l->curvalue;
+ if (l->top < 0)
+ l->top = 0;
+
+ if (l->generic.callback)
+ l->generic.callback( l, QM_GOTFOCUS );
+
+ return (menu_move_sound);
+ }
+ return (menu_buzz_sound);
+
+ case K_PGDN:
+ case K_KP_PGDN:
+ if( l->columns > 1 ) {
+ return menu_null_sound;
+ }
+
+ if (l->curvalue < l->numitems-1)
+ {
+ l->oldvalue = l->curvalue;
+ l->curvalue += l->height-1;
+ if (l->curvalue > l->numitems-1)
+ l->curvalue = l->numitems-1;
+ l->top = l->curvalue - (l->height-1);
+ if (l->top < 0)
+ l->top = 0;
+
+ if (l->generic.callback)
+ l->generic.callback( l, QM_GOTFOCUS );
+
+ return (menu_move_sound);
+ }
+ return (menu_buzz_sound);
+
+ case K_KP_UPARROW:
+ case K_UPARROW:
+ if( l->curvalue == 0 ) {
+ return menu_buzz_sound;
+ }
+
+ l->oldvalue = l->curvalue;
+ l->curvalue--;
+
+ if( l->curvalue < l->top ) {
+ if( l->columns == 1 ) {
+ l->top--;
+ }
+ else {
+ l->top -= l->height;
+ }
+ }
+
+ if( l->generic.callback ) {
+ l->generic.callback( l, QM_GOTFOCUS );
+ }
+
+ return (menu_move_sound);
+
+ case K_KP_DOWNARROW:
+ case K_DOWNARROW:
+ if( l->curvalue == l->numitems - 1 ) {
+ return menu_buzz_sound;
+ }
+
+ l->oldvalue = l->curvalue;
+ l->curvalue++;
+
+ if( l->curvalue >= l->top + l->columns * l->height ) {
+ if( l->columns == 1 ) {
+ l->top++;
+ }
+ else {
+ l->top += l->height;
+ }
+ }
+
+ if( l->generic.callback ) {
+ l->generic.callback( l, QM_GOTFOCUS );
+ }
+
+ return menu_move_sound;
+
+ case K_KP_LEFTARROW:
+ case K_LEFTARROW:
+ if( l->columns == 1 ) {
+ return menu_null_sound;
+ }
+
+ if( l->curvalue < l->height ) {
+ return menu_buzz_sound;
+ }
+
+ l->oldvalue = l->curvalue;
+ l->curvalue -= l->height;
+
+ if( l->curvalue < l->top ) {
+ l->top -= l->height;
+ }
+
+ if( l->generic.callback ) {
+ l->generic.callback( l, QM_GOTFOCUS );
+ }
+
+ return menu_move_sound;
+
+ case K_KP_RIGHTARROW:
+ case K_RIGHTARROW:
+ if( l->columns == 1 ) {
+ return menu_null_sound;
+ }
+
+ c = l->curvalue + l->height;
+
+ if( c >= l->numitems ) {
+ return menu_buzz_sound;
+ }
+
+ l->oldvalue = l->curvalue;
+ l->curvalue = c;
+
+ if( l->curvalue > l->top + l->columns * l->height - 1 ) {
+ l->top += l->height;
+ }
+
+ if( l->generic.callback ) {
+ l->generic.callback( l, QM_GOTFOCUS );
+ }
+
+ return menu_move_sound;
+ }
+
+ // cycle look for ascii key inside list items
+ if ( !Q_isprint( key ) )
+ return (0);
+
+ // force to lower for case insensitive compare
+ if ( Q_isupper( key ) )
+ {
+ key -= 'A' - 'a';
+ }
+
+ // iterate list items
+ for (i=1; i<=l->numitems; i++)
+ {
+ j = (l->curvalue + i) % l->numitems;
+ c = l->itemnames[j][0];
+ if ( Q_isupper( c ) )
+ {
+ c -= 'A' - 'a';
+ }
+
+ if (c == key)
+ {
+ // set current item, mimic windows listbox scroll behavior
+ if (j < l->top)
+ {
+ // behind top most item, set this as new top
+ l->top = j;
+ }
+ else if (j > l->top+l->height-1)
+ {
+ // past end of list box, do page down
+ l->top = (j+1) - l->height;
+ }
+
+ if (l->curvalue != j)
+ {
+ l->oldvalue = l->curvalue;
+ l->curvalue = j;
+ if (l->generic.callback)
+ l->generic.callback( l, QM_GOTFOCUS );
+ return ( menu_move_sound );
+ }
+
+ return (menu_buzz_sound);
+ }
+ }
+
+ return (menu_buzz_sound);
+}
+
+/*
+=================
+ScrollList_Draw
+=================
+*/
+void ScrollList_Draw( menulist_s *l )
+{
+ int x;
+ int u;
+ int y;
+ int i;
+ int base;
+ int column;
+ float* color;
+ qboolean hasfocus;
+ int style;
+
+ hasfocus = (l->generic.parent->cursor == l->generic.menuPosition);
+
+ x = l->generic.x;
+ for( column = 0; column < l->columns; column++ ) {
+ y = l->generic.y;
+ base = l->top + column * l->height;
+ for( i = base; i < base + l->height; i++) {
+ if (i >= l->numitems)
+ break;
+
+ if (i == l->curvalue)
+ {
+ u = x - 2;
+ if( l->generic.flags & QMF_CENTER_JUSTIFY ) {
+ u -= (l->width * SMALLCHAR_WIDTH) / 2 + 1;
+ }
+
+ UI_FillRect(u,y,l->width*SMALLCHAR_WIDTH,SMALLCHAR_HEIGHT+2,listbar_color);
+ color = text_color_highlight;
+
+ if (hasfocus)
+ style = UI_PULSE|UI_LEFT|UI_SMALLFONT;
+ else
+ style = UI_LEFT|UI_SMALLFONT;
+ }
+ else
+ {
+ color = text_color_normal;
+ style = UI_LEFT|UI_SMALLFONT;
+ }
+ if( l->generic.flags & QMF_CENTER_JUSTIFY ) {
+ style |= UI_CENTER;
+ }
+
+ UI_DrawString(
+ x,
+ y,
+ l->itemnames[i],
+ style,
+ color);
+
+ y += SMALLCHAR_HEIGHT;
+ }
+ x += (l->width + l->seperation) * SMALLCHAR_WIDTH;
+ }
+}
+
+/*
+=================
+Menu_AddItem
+=================
+*/
+void Menu_AddItem( menuframework_s *menu, void *item )
+{
+ menucommon_s *itemptr;
+
+ if (menu->nitems >= MAX_MENUITEMS)
+ trap_Error ("Menu_AddItem: excessive items");
+
+ menu->items[menu->nitems] = item;
+ ((menucommon_s*)menu->items[menu->nitems])->parent = menu;
+ ((menucommon_s*)menu->items[menu->nitems])->menuPosition = menu->nitems;
+ ((menucommon_s*)menu->items[menu->nitems])->flags &= ~QMF_HASMOUSEFOCUS;
+
+ // perform any item specific initializations
+ itemptr = (menucommon_s*)item;
+ if (!(itemptr->flags & QMF_NODEFAULTINIT))
+ {
+ switch (itemptr->type)
+ {
+ case MTYPE_ACTION:
+ Action_Init((menuaction_s*)item);
+ break;
+
+ case MTYPE_FIELD:
+ MenuField_Init((menufield_s*)item);
+ break;
+
+ case MTYPE_SPINCONTROL:
+ SpinControl_Init((menulist_s*)item);
+ break;
+
+ case MTYPE_RADIOBUTTON:
+ RadioButton_Init((menuradiobutton_s*)item);
+ break;
+
+ case MTYPE_SLIDER:
+ Slider_Init((menuslider_s*)item);
+ break;
+
+ case MTYPE_BITMAP:
+ Bitmap_Init((menubitmap_s*)item);
+ break;
+
+ case MTYPE_TEXT:
+ Text_Init((menutext_s*)item);
+ break;
+
+ case MTYPE_SCROLLLIST:
+ ScrollList_Init((menulist_s*)item);
+ break;
+
+ case MTYPE_PTEXT:
+ PText_Init((menutext_s*)item);
+ break;
+
+ case MTYPE_BTEXT:
+ BText_Init((menutext_s*)item);
+ break;
+
+ default:
+ trap_Error( va("Menu_Init: unknown type %d", itemptr->type) );
+ }
+ }
+
+ menu->nitems++;
+}
+
+/*
+=================
+Menu_CursorMoved
+=================
+*/
+void Menu_CursorMoved( menuframework_s *m )
+{
+ void (*callback)( void *self, int notification );
+
+ if (m->cursor_prev == m->cursor)
+ return;
+
+ if (m->cursor_prev >= 0 && m->cursor_prev < m->nitems)
+ {
+ callback = ((menucommon_s*)(m->items[m->cursor_prev]))->callback;
+ if (callback)
+ callback(m->items[m->cursor_prev],QM_LOSTFOCUS);
+ }
+
+ if (m->cursor >= 0 && m->cursor < m->nitems)
+ {
+ callback = ((menucommon_s*)(m->items[m->cursor]))->callback;
+ if (callback)
+ callback(m->items[m->cursor],QM_GOTFOCUS);
+ }
+}
+
+/*
+=================
+Menu_SetCursor
+=================
+*/
+void Menu_SetCursor( menuframework_s *m, int cursor )
+{
+ if (((menucommon_s*)(m->items[cursor]))->flags & (QMF_GRAYED|QMF_INACTIVE))
+ {
+ // cursor can't go there
+ return;
+ }
+
+ m->cursor_prev = m->cursor;
+ m->cursor = cursor;
+
+ Menu_CursorMoved( m );
+}
+
+/*
+=================
+Menu_SetCursorToItem
+=================
+*/
+void Menu_SetCursorToItem( menuframework_s *m, void* ptr )
+{
+ int i;
+
+ for (i=0; i<m->nitems; i++)
+ {
+ if (m->items[i] == ptr)
+ {
+ Menu_SetCursor( m, i );
+ return;
+ }
+ }
+}
+
+/*
+** Menu_AdjustCursor
+**
+** This function takes the given menu, the direction, and attempts
+** to adjust the menu's cursor so that it's at the next available
+** slot.
+*/
+void Menu_AdjustCursor( menuframework_s *m, int dir ) {
+ menucommon_s *item = NULL;
+ qboolean wrapped = qfalse;
+
+wrap:
+ while ( m->cursor >= 0 && m->cursor < m->nitems ) {
+ item = ( menucommon_s * ) m->items[m->cursor];
+ if (( item->flags & (QMF_GRAYED|QMF_MOUSEONLY|QMF_INACTIVE) ) ) {
+ m->cursor += dir;
+ }
+ else {
+ break;
+ }
+ }
+
+ if ( dir == 1 ) {
+ if ( m->cursor >= m->nitems ) {
+ if ( m->wrapAround ) {
+ if ( wrapped ) {
+ m->cursor = m->cursor_prev;
+ return;
+ }
+ m->cursor = 0;
+ wrapped = qtrue;
+ goto wrap;
+ }
+ m->cursor = m->cursor_prev;
+ }
+ }
+ else {
+ if ( m->cursor < 0 ) {
+ if ( m->wrapAround ) {
+ if ( wrapped ) {
+ m->cursor = m->cursor_prev;
+ return;
+ }
+ m->cursor = m->nitems - 1;
+ wrapped = qtrue;
+ goto wrap;
+ }
+ m->cursor = m->cursor_prev;
+ }
+ }
+}
+
+/*
+=================
+Menu_Draw
+=================
+*/
+void Menu_Draw( menuframework_s *menu )
+{
+ int i;
+ menucommon_s *itemptr;
+
+ // draw menu
+ for (i=0; i<menu->nitems; i++)
+ {
+ itemptr = (menucommon_s*)menu->items[i];
+
+ if (itemptr->flags & QMF_HIDDEN)
+ continue;
+
+ if (itemptr->ownerdraw)
+ {
+ // total subclassing, owner draws everything
+ itemptr->ownerdraw( itemptr );
+ }
+ else
+ {
+ switch (itemptr->type)
+ {
+ case MTYPE_RADIOBUTTON:
+ RadioButton_Draw( (menuradiobutton_s*)itemptr );
+ break;
+
+ case MTYPE_FIELD:
+ MenuField_Draw( (menufield_s*)itemptr );
+ break;
+
+ case MTYPE_SLIDER:
+ Slider_Draw( (menuslider_s*)itemptr );
+ break;
+
+ case MTYPE_SPINCONTROL:
+ SpinControl_Draw( (menulist_s*)itemptr );
+ break;
+
+ case MTYPE_ACTION:
+ Action_Draw( (menuaction_s*)itemptr );
+ break;
+
+ case MTYPE_BITMAP:
+ Bitmap_Draw( (menubitmap_s*)itemptr );
+ break;
+
+ case MTYPE_TEXT:
+ Text_Draw( (menutext_s*)itemptr );
+ break;
+
+ case MTYPE_SCROLLLIST:
+ ScrollList_Draw( (menulist_s*)itemptr );
+ break;
+
+ case MTYPE_PTEXT:
+ PText_Draw( (menutext_s*)itemptr );
+ break;
+
+ case MTYPE_BTEXT:
+ BText_Draw( (menutext_s*)itemptr );
+ break;
+
+ default:
+ trap_Error( va("Menu_Draw: unknown type %d", itemptr->type) );
+ }
+ }
+#ifndef NDEBUG
+ if( uis.debug ) {
+ int x;
+ int y;
+ int w;
+ int h;
+
+ if( !( itemptr->flags & QMF_INACTIVE ) ) {
+ x = itemptr->left;
+ y = itemptr->top;
+ w = itemptr->right - itemptr->left + 1;
+ h = itemptr->bottom - itemptr->top + 1;
+
+ if (itemptr->flags & QMF_HASMOUSEFOCUS) {
+ UI_DrawRect(x, y, w, h, colorYellow );
+ }
+ else {
+ UI_DrawRect(x, y, w, h, colorWhite );
+ }
+ }
+ }
+#endif
+ }
+
+ itemptr = Menu_ItemAtCursor( menu );
+ if ( itemptr && itemptr->statusbar)
+ itemptr->statusbar( ( void * ) itemptr );
+}
+
+/*
+=================
+Menu_ItemAtCursor
+=================
+*/
+void *Menu_ItemAtCursor( menuframework_s *m )
+{
+ if ( m->cursor < 0 || m->cursor >= m->nitems )
+ return 0;
+
+ return m->items[m->cursor];
+}
+
+/*
+=================
+Menu_ActivateItem
+=================
+*/
+sfxHandle_t Menu_ActivateItem( menuframework_s *s, menucommon_s* item ) {
+ if ( item->callback ) {
+ item->callback( item, QM_ACTIVATED );
+ if( !( item->flags & QMF_SILENT ) ) {
+ return menu_move_sound;
+ }
+ }
+
+ return 0;
+}
+
+/*
+=================
+Menu_DefaultKey
+=================
+*/
+sfxHandle_t Menu_DefaultKey( menuframework_s *m, int key )
+{
+ sfxHandle_t sound = 0;
+ menucommon_s *item;
+ int cursor_prev;
+
+ // menu system keys
+ switch ( key )
+ {
+ case K_MOUSE2:
+ case K_ESCAPE:
+ UI_PopMenu();
+ return menu_out_sound;
+ }
+
+ if (!m || !m->nitems)
+ return 0;
+
+ // route key stimulus to widget
+ item = Menu_ItemAtCursor( m );
+ if (item && !(item->flags & (QMF_GRAYED|QMF_INACTIVE)))
+ {
+ switch (item->type)
+ {
+ case MTYPE_SPINCONTROL:
+ sound = SpinControl_Key( (menulist_s*)item, key );
+ break;
+
+ case MTYPE_RADIOBUTTON:
+ sound = RadioButton_Key( (menuradiobutton_s*)item, key );
+ break;
+
+ case MTYPE_SLIDER:
+ sound = Slider_Key( (menuslider_s*)item, key );
+ break;
+
+ case MTYPE_SCROLLLIST:
+ sound = ScrollList_Key( (menulist_s*)item, key );
+ break;
+
+ case MTYPE_FIELD:
+ sound = MenuField_Key( (menufield_s*)item, &key );
+ break;
+ }
+
+ if (sound) {
+ // key was handled
+ return sound;
+ }
+ }
+
+ // default handling
+ switch ( key )
+ {
+#ifndef NDEBUG
+ case K_F11:
+ uis.debug ^= 1;
+ break;
+
+ case K_F12:
+ trap_Cmd_ExecuteText(EXEC_APPEND, "screenshot\n");
+ break;
+#endif
+ case K_KP_UPARROW:
+ case K_UPARROW:
+ cursor_prev = m->cursor;
+ m->cursor_prev = m->cursor;
+ m->cursor--;
+ Menu_AdjustCursor( m, -1 );
+ if ( cursor_prev != m->cursor ) {
+ Menu_CursorMoved( m );
+ sound = menu_move_sound;
+ }
+ break;
+
+ case K_TAB:
+ case K_KP_DOWNARROW:
+ case K_DOWNARROW:
+ cursor_prev = m->cursor;
+ m->cursor_prev = m->cursor;
+ m->cursor++;
+ Menu_AdjustCursor( m, 1 );
+ if ( cursor_prev != m->cursor ) {
+ Menu_CursorMoved( m );
+ sound = menu_move_sound;
+ }
+ break;
+
+ case K_MOUSE1:
+ case K_MOUSE3:
+ if (item)
+ if ((item->flags & QMF_HASMOUSEFOCUS) && !(item->flags & (QMF_GRAYED|QMF_INACTIVE)))
+ return (Menu_ActivateItem( m, item ));
+ break;
+
+ case K_JOY1:
+ case K_JOY2:
+ case K_JOY3:
+ case K_JOY4:
+ case K_AUX1:
+ case K_AUX2:
+ case K_AUX3:
+ case K_AUX4:
+ case K_AUX5:
+ case K_AUX6:
+ case K_AUX7:
+ case K_AUX8:
+ case K_AUX9:
+ case K_AUX10:
+ case K_AUX11:
+ case K_AUX12:
+ case K_AUX13:
+ case K_AUX14:
+ case K_AUX15:
+ case K_AUX16:
+ case K_KP_ENTER:
+ case K_ENTER:
+ if (item)
+ if (!(item->flags & (QMF_MOUSEONLY|QMF_GRAYED|QMF_INACTIVE)))
+ return (Menu_ActivateItem( m, item ));
+ break;
+ }
+
+ return sound;
+}
+
+/*
+=================
+Menu_Cache
+=================
+*/
+void Menu_Cache( void )
+{
+ uis.charset = trap_R_RegisterShaderNoMip( "gfx/2d/bigchars" );
+ uis.charsetProp = trap_R_RegisterShaderNoMip( "menu/art/font1_prop.tga" );
+ uis.charsetPropGlow = trap_R_RegisterShaderNoMip( "menu/art/font1_prop_glo.tga" );
+ uis.charsetPropB = trap_R_RegisterShaderNoMip( "menu/art/font2_prop.tga" );
+ uis.cursor = trap_R_RegisterShaderNoMip( "menu/art/3_cursor2" );
+ uis.rb_on = trap_R_RegisterShaderNoMip( "menu/art/switch_on" );
+ uis.rb_off = trap_R_RegisterShaderNoMip( "menu/art/switch_off" );
+
+ uis.whiteShader = trap_R_RegisterShaderNoMip( "white" );
+ if ( uis.glconfig.hardwareType == GLHW_RAGEPRO ) {
+ // the blend effect turns to shit with the normal
+ uis.menuBackShader = trap_R_RegisterShaderNoMip( "menubackRagePro" );
+ } else {
+ uis.menuBackShader = trap_R_RegisterShaderNoMip( "menuback" );
+ }
+ uis.menuBackNoLogoShader = trap_R_RegisterShaderNoMip( "menubacknologo" );
+
+ menu_in_sound = trap_S_RegisterSound( "sound/misc/menu1.wav", qfalse );
+ menu_move_sound = trap_S_RegisterSound( "sound/misc/menu2.wav", qfalse );
+ menu_out_sound = trap_S_RegisterSound( "sound/misc/menu3.wav", qfalse );
+ menu_buzz_sound = trap_S_RegisterSound( "sound/misc/menu4.wav", qfalse );
+ weaponChangeSound = trap_S_RegisterSound( "sound/weapons/change.wav", qfalse );
+
+ // need a nonzero sound, make an empty sound for this
+ menu_null_sound = -1;
+
+ sliderBar = trap_R_RegisterShaderNoMip( "menu/art/slider2" );
+ sliderButton_0 = trap_R_RegisterShaderNoMip( "menu/art/sliderbutt_0" );
+ sliderButton_1 = trap_R_RegisterShaderNoMip( "menu/art/sliderbutt_1" );
+}
+
diff --git a/code/q3_ui/ui_rankings.c b/code/q3_ui/ui_rankings.c
new file mode 100755
index 0000000..762e964
--- /dev/null
+++ b/code/q3_ui/ui_rankings.c
@@ -0,0 +1,420 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+//
+// ui_rankings.c
+//
+
+#include "ui_local.h"
+
+
+#define RANKINGS_FRAME "menu/art/cut_frame"
+
+#define ID_LOGIN 100
+#define ID_LOGOUT 101
+#define ID_CREATE 102
+#define ID_SPECTATE 103
+#define ID_SETUP 104
+#define ID_LEAVE 105
+
+
+typedef struct
+{
+ menuframework_s menu;
+ menubitmap_s frame;
+ menutext_s login;
+ menutext_s logout;
+ menutext_s create;
+ menutext_s spectate;
+ menutext_s setup;
+ menutext_s leave;
+} rankings_t;
+
+static rankings_t s_rankings;
+
+static menuframework_s s_rankings_menu;
+static menuaction_s s_rankings_login;
+static menuaction_s s_rankings_logout;
+static menuaction_s s_rankings_create;
+static menuaction_s s_rankings_spectate;
+static menuaction_s s_rankings_setup;
+static menuaction_s s_rankings_leave;
+
+
+/*
+===============
+Rankings_DrawText
+===============
+*/
+void Rankings_DrawText( void* self )
+{
+ menufield_s *f;
+ qboolean focus;
+ int style;
+ char *txt;
+ char c;
+ float *color;
+ int basex, x, y;
+
+ f = (menufield_s*)self;
+ basex = f->generic.x;
+ y = f->generic.y + 4;
+ focus = (f->generic.parent->cursor == f->generic.menuPosition);
+
+ style = UI_LEFT|UI_SMALLFONT;
+ color = text_color_normal;
+ if( focus ) {
+ style |= UI_PULSE;
+ color = text_color_highlight;
+ }
+
+ // draw the actual text
+ txt = f->field.buffer;
+ color = g_color_table[ColorIndex(COLOR_WHITE)];
+ x = basex;
+ while ( (c = *txt) != 0 ) {
+ UI_DrawChar( x, y, c, style, color );
+ txt++;
+ x += SMALLCHAR_WIDTH;
+ }
+
+ // draw cursor if we have focus
+ if( focus ) {
+ if ( trap_Key_GetOverstrikeMode() ) {
+ c = 11;
+ } else {
+ c = 10;
+ }
+
+ style &= ~UI_PULSE;
+ style |= UI_BLINK;
+
+ UI_DrawChar( basex + f->field.cursor * SMALLCHAR_WIDTH, y, c, style, color_white );
+ }
+}
+
+/*
+===============
+Rankings_DrawName
+===============
+*/
+void Rankings_DrawName( void* self )
+{
+ menufield_s *f;
+ int length;
+ char* p;
+
+ f = (menufield_s*)self;
+
+ // GRANK_FIXME - enforce valid characters
+ for( p = f->field.buffer; *p != '\0'; p++ )
+ {
+ //if( ispunct(*p) || isspace(*p) )
+ if( !( ( (*p) >= '0' && (*p) <= '9') || Q_isalpha(*p)) )
+ {
+ *p = '\0';
+ }
+ }
+
+ // strip color codes
+ Q_CleanStr( f->field.buffer );
+ length = strlen( f->field.buffer );
+ if( f->field.cursor > length )
+ {
+ f->field.cursor = length;
+ }
+
+ Rankings_DrawText( f );
+}
+
+#if 0 // old version
+/*
+===============
+Rankings_DrawName
+===============
+*/
+void Rankings_DrawName( void* self )
+{
+ menufield_s* f;
+ int length;
+
+ f = (menufield_s*)self;
+
+ // strip color codes
+ Q_CleanStr( f->field.buffer );
+ length = strlen( f->field.buffer );
+ if( f->field.cursor > length )
+ {
+ f->field.cursor = length;
+ }
+
+ // show beginning of long names
+ /*
+ if( Menu_ItemAtCursor( f->generic.parent ) != f )
+ {
+ if( f->field.scroll > 0 )
+ {
+ f->field.cursor = 0;
+ f->field.scroll = 0;
+ }
+ }
+ */
+
+ MenuField_Draw( f );
+}
+#endif
+
+/*
+===============
+Rankings_DrawPassword
+===============
+*/
+void Rankings_DrawPassword( void* self )
+{
+ menufield_s* f;
+ char password[MAX_EDIT_LINE];
+ int length;
+ int i;
+ char* p;
+
+ f = (menufield_s*)self;
+
+ // GRANK_FIXME - enforce valid characters
+ for( p = f->field.buffer; *p != '\0'; p++ )
+ {
+ //if( ispunct(*p) || isspace(*p) )
+ if( !( ( (*p) >= '0' && (*p) <= '9') || Q_isalpha(*p)) )
+ {
+ *p = '\0';
+ }
+ }
+
+ length = strlen( f->field.buffer );
+ if( f->field.cursor > length )
+ {
+ f->field.cursor = length;
+ }
+
+ // save password
+ Q_strncpyz( password, f->field.buffer, sizeof(password) );
+
+ // mask password with *
+ for( i = 0; i < length; i++ )
+ {
+ f->field.buffer[i] = '*';
+ }
+
+ // draw masked password
+ Rankings_DrawText( f );
+ //MenuField_Draw( f );
+
+ // restore password
+ Q_strncpyz( f->field.buffer, password, sizeof(f->field.buffer) );
+}
+
+/*
+===============
+Rankings_MenuEvent
+===============
+*/
+static void Rankings_MenuEvent( void* ptr, int event ) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+
+ switch( ((menucommon_s*)ptr)->id ) {
+ case ID_LOGIN:
+ UI_LoginMenu();
+ break;
+
+ case ID_LOGOUT:
+ // server side masqueraded player logout first
+ trap_CL_UI_RankUserRequestLogout();
+ UI_ForceMenuOff();
+ break;
+
+ case ID_CREATE:
+ UI_SignupMenu();
+ break;
+
+ case ID_SPECTATE:
+ trap_Cmd_ExecuteText( EXEC_APPEND, "cmd rank_spectate\n" );
+ UI_ForceMenuOff();
+ break;
+
+ case ID_SETUP:
+ UI_SetupMenu();
+ break;
+
+ case ID_LEAVE:
+ trap_Cmd_ExecuteText( EXEC_APPEND, "disconnect\n" );
+ UI_ForceMenuOff();
+ break;
+
+ }
+}
+
+
+/*
+===============
+Rankings_MenuInit
+===============
+*/
+void Rankings_MenuInit( void ) {
+ grank_status_t status;
+ int y;
+
+ memset( &s_rankings, 0, sizeof(s_rankings) );
+
+ Rankings_Cache();
+
+ s_rankings.menu.wrapAround = qtrue;
+ s_rankings.menu.fullscreen = qfalse;
+
+ s_rankings.frame.generic.type = MTYPE_BITMAP;
+ s_rankings.frame.generic.flags = QMF_INACTIVE;
+ s_rankings.frame.generic.name = RANKINGS_FRAME;
+ s_rankings.frame.generic.x = 142;
+ s_rankings.frame.generic.y = 118;
+ s_rankings.frame.width = 359;
+ s_rankings.frame.height = 256;
+
+ y = 194;
+
+ s_rankings.login.generic.type = MTYPE_PTEXT;
+ s_rankings.login.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_rankings.login.generic.id = ID_LOGIN;
+ s_rankings.login.generic.callback = Rankings_MenuEvent;
+ s_rankings.login.generic.x = 320;
+ s_rankings.login.generic.y = y;
+ s_rankings.login.string = "LOGIN";
+ s_rankings.login.style = UI_CENTER|UI_SMALLFONT;
+ s_rankings.login.color = colorRed;
+ y += 20;
+
+ s_rankings.logout.generic.type = MTYPE_PTEXT;
+ s_rankings.logout.generic.flags = QMF_HIDDEN|QMF_INACTIVE|QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_rankings.logout.generic.id = ID_LOGOUT;
+ s_rankings.logout.generic.callback = Rankings_MenuEvent;
+ s_rankings.logout.generic.x = 320;
+ s_rankings.logout.generic.y = y;
+ s_rankings.logout.string = "LOGOUT";
+ s_rankings.logout.style = UI_CENTER|UI_SMALLFONT;
+ s_rankings.logout.color = colorRed;
+
+ s_rankings.create.generic.type = MTYPE_PTEXT;
+ s_rankings.create.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_rankings.create.generic.id = ID_CREATE;
+ s_rankings.create.generic.callback = Rankings_MenuEvent;
+ s_rankings.create.generic.x = 320;
+ s_rankings.create.generic.y = y;
+ s_rankings.create.string = "SIGN UP";
+ s_rankings.create.style = UI_CENTER|UI_SMALLFONT;
+ s_rankings.create.color = colorRed;
+ y += 20;
+
+ s_rankings.spectate.generic.type = MTYPE_PTEXT;
+ s_rankings.spectate.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_rankings.spectate.generic.id = ID_SPECTATE;
+ s_rankings.spectate.generic.callback = Rankings_MenuEvent;
+ s_rankings.spectate.generic.x = 320;
+ s_rankings.spectate.generic.y = y;
+ s_rankings.spectate.string = "SPECTATE";
+ s_rankings.spectate.style = UI_CENTER|UI_SMALLFONT;
+ s_rankings.spectate.color = colorRed;
+ y += 20;
+
+ s_rankings.setup.generic.type = MTYPE_PTEXT;
+ s_rankings.setup.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_rankings.setup.generic.id = ID_SETUP;
+ s_rankings.setup.generic.callback = Rankings_MenuEvent;
+ s_rankings.setup.generic.x = 320;
+ s_rankings.setup.generic.y = y;
+ s_rankings.setup.string = "SETUP";
+ s_rankings.setup.style = UI_CENTER|UI_SMALLFONT;
+ s_rankings.setup.color = colorRed;
+ y += 20;
+
+ s_rankings.leave.generic.type = MTYPE_PTEXT;
+ s_rankings.leave.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_rankings.leave.generic.id = ID_LEAVE;
+ s_rankings.leave.generic.callback = Rankings_MenuEvent;
+ s_rankings.leave.generic.x = 320;
+ s_rankings.leave.generic.y = y;
+ s_rankings.leave.string = "LEAVE ARENA";
+ s_rankings.leave.style = UI_CENTER|UI_SMALLFONT;
+ s_rankings.leave.color = colorRed;
+ y += 20;
+
+ status = (grank_status_t)trap_Cvar_VariableValue("client_status");
+ if( (status != QGR_STATUS_NEW) && (status != QGR_STATUS_SPECTATOR) )
+ {
+ s_rankings.login.generic.flags |= QMF_HIDDEN | QMF_INACTIVE;
+ s_rankings.create.generic.flags |= QMF_HIDDEN | QMF_INACTIVE;
+ s_rankings.spectate.generic.flags |= QMF_HIDDEN | QMF_INACTIVE;
+
+ s_rankings.logout.generic.flags &= ~(QMF_HIDDEN | QMF_INACTIVE);
+ }
+
+ if ( (status == QGR_STATUS_VALIDATING) ||
+ (status == QGR_STATUS_PENDING) ||
+ (status == QGR_STATUS_LEAVING) )
+ {
+ s_rankings.login.generic.flags |= QMF_GRAYED;
+ s_rankings.create.generic.flags |= QMF_GRAYED;
+ s_rankings.logout.generic.flags |= QMF_GRAYED;
+ }
+
+ //GRank FIXME -- don't need setup option any more
+ s_rankings.setup.generic.flags |= QMF_HIDDEN | QMF_INACTIVE;
+
+ Menu_AddItem( &s_rankings.menu, (void*) &s_rankings.frame );
+ Menu_AddItem( &s_rankings.menu, (void*) &s_rankings.login );
+ Menu_AddItem( &s_rankings.menu, (void*) &s_rankings.logout );
+ Menu_AddItem( &s_rankings.menu, (void*) &s_rankings.create );
+ Menu_AddItem( &s_rankings.menu, (void*) &s_rankings.spectate );
+ Menu_AddItem( &s_rankings.menu, (void*) &s_rankings.setup );
+ Menu_AddItem( &s_rankings.menu, (void*) &s_rankings.leave );
+}
+
+
+/*
+===============
+Rankings_Cache
+===============
+*/
+void Rankings_Cache( void ) {
+ trap_R_RegisterShaderNoMip( RANKINGS_FRAME );
+}
+
+
+/*
+===============
+UI_RankingsMenu
+===============
+*/
+void UI_RankingsMenu( void ) {
+ Rankings_MenuInit();
+ UI_PushMenu ( &s_rankings.menu );
+}
+
+
diff --git a/code/q3_ui/ui_rankstatus.c b/code/q3_ui/ui_rankstatus.c
new file mode 100755
index 0000000..3563364
--- /dev/null
+++ b/code/q3_ui/ui_rankstatus.c
@@ -0,0 +1,209 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+//
+// ui_rankstatus.c
+//
+
+#include "ui_local.h"
+
+
+#define RANKSTATUS_FRAME "menu/art/cut_frame"
+
+#define ID_MESSAGE 100
+#define ID_OK 101
+
+
+typedef struct
+{
+ menuframework_s menu;
+ menubitmap_s frame;
+ menutext_s message;
+ menutext_s ok;
+} rankstatus_t;
+
+static rankstatus_t s_rankstatus;
+
+static menuframework_s s_rankstatus_menu;
+static menuaction_s s_rankstatus_ok;
+
+static grank_status_t s_status = 0;
+static char* s_rankstatus_message = NULL;
+
+static vec4_t s_rankingstatus_color_prompt = {1.00, 0.43, 0.00, 1.00};
+
+/*
+===============
+RankStatus_MenuEvent
+===============
+*/
+static void RankStatus_MenuEvent( void* ptr, int event ) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+
+ switch( ((menucommon_s*)ptr)->id ) {
+ case ID_OK:
+ UI_PopMenu();
+
+ switch( s_status )
+ {
+ case QGR_STATUS_NO_USER:
+ UI_RankingsMenu();
+ break;
+ case QGR_STATUS_BAD_PASSWORD:
+ UI_RankingsMenu();
+ UI_LoginMenu();
+ break;
+ case QGR_STATUS_USER_EXISTS:
+ UI_RankingsMenu();
+ UI_SignupMenu();
+ break;
+ case QGR_STATUS_NO_MEMBERSHIP:
+ UI_RankingsMenu();
+ break;
+ case QGR_STATUS_TIMEOUT:
+ UI_RankingsMenu();
+ break;
+ case QGR_STATUS_INVALIDUSER:
+ UI_RankingsMenu();
+ break;
+ case QGR_STATUS_ERROR:
+ UI_RankingsMenu();
+ break;
+ default:
+ break;
+ }
+
+ break;
+ }
+}
+
+
+/*
+===============
+RankStatus_MenuInit
+===============
+*/
+void RankStatus_MenuInit( void ) {
+ int y;
+
+ memset( &s_rankstatus, 0, sizeof(s_rankstatus) );
+
+ RankStatus_Cache();
+
+ s_rankstatus.menu.wrapAround = qtrue;
+ s_rankstatus.menu.fullscreen = qfalse;
+
+ s_rankstatus.frame.generic.type = MTYPE_BITMAP;
+ s_rankstatus.frame.generic.flags = QMF_INACTIVE;
+ s_rankstatus.frame.generic.name = RANKSTATUS_FRAME;
+ s_rankstatus.frame.generic.x = 142; //320-233;
+ s_rankstatus.frame.generic.y = 118; //240-166;
+ s_rankstatus.frame.width = 359; //466;
+ s_rankstatus.frame.height = 256; //332;
+
+ y = 214;
+
+ s_rankstatus.message.generic.type = MTYPE_PTEXT;
+ s_rankstatus.message.generic.flags = QMF_CENTER_JUSTIFY|QMF_INACTIVE;
+ s_rankstatus.message.generic.id = ID_MESSAGE;
+ s_rankstatus.message.generic.x = 320;
+ s_rankstatus.message.generic.y = y;
+ s_rankstatus.message.string = s_rankstatus_message;
+ s_rankstatus.message.style = UI_CENTER|UI_SMALLFONT;
+ s_rankstatus.message.color = s_rankingstatus_color_prompt;
+ y += 40;
+
+ s_rankstatus.ok.generic.type = MTYPE_PTEXT;
+ s_rankstatus.ok.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_rankstatus.ok.generic.id = ID_OK;
+ s_rankstatus.ok.generic.callback = RankStatus_MenuEvent;
+ s_rankstatus.ok.generic.x = 320;
+ s_rankstatus.ok.generic.y = y;
+ s_rankstatus.ok.string = "OK";
+ s_rankstatus.ok.style = UI_CENTER|UI_SMALLFONT;
+ s_rankstatus.ok.color = colorRed;
+
+ Menu_AddItem( &s_rankstatus.menu, (void*) &s_rankstatus.frame );
+ Menu_AddItem( &s_rankstatus.menu, (void*) &s_rankstatus.message );
+ Menu_AddItem( &s_rankstatus.menu, (void*) &s_rankstatus.ok );
+}
+
+
+/*
+===============
+RankStatus_Cache
+===============
+*/
+void RankStatus_Cache( void ) {
+ trap_R_RegisterShaderNoMip( RANKSTATUS_FRAME );
+}
+
+
+/*
+===============
+UI_RankStatusMenu
+===============
+*/
+void UI_RankStatusMenu( void ) {
+
+ s_status = (grank_status_t)trap_Cvar_VariableValue("client_status");
+
+ switch( s_status )
+ {
+ case QGR_STATUS_NEW:
+ return;
+ case QGR_STATUS_PENDING:
+ // GRANK_FIXME
+ return;
+ case QGR_STATUS_NO_USER:
+ // GRANK_FIXME - get this when user exists
+ s_rankstatus_message = "Username unavailable";
+ break;
+ case QGR_STATUS_BAD_PASSWORD:
+ s_rankstatus_message = "Invalid password";
+ break;
+ case QGR_STATUS_TIMEOUT:
+ s_rankstatus_message = "Timed out";
+ break;
+ case QGR_STATUS_NO_MEMBERSHIP:
+ s_rankstatus_message = "No membership";
+ break;
+ case QGR_STATUS_INVALIDUSER:
+ s_rankstatus_message = "Validation failed";
+ break;
+ case QGR_STATUS_ERROR:
+ s_rankstatus_message = "Error";
+ break;
+ case QGR_STATUS_SPECTATOR:
+ case QGR_STATUS_ACTIVE:
+ UI_ForceMenuOff();
+ return;
+ default:
+ return;
+ }
+ RankStatus_MenuInit();
+ trap_CL_UI_RankUserReset();
+ UI_PushMenu ( &s_rankstatus.menu );
+}
+
diff --git a/code/q3_ui/ui_removebots.c b/code/q3_ui/ui_removebots.c
new file mode 100755
index 0000000..8d13fdc
--- /dev/null
+++ b/code/q3_ui/ui_removebots.c
@@ -0,0 +1,342 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*
+=======================================================================
+
+REMOVE BOTS MENU
+
+=======================================================================
+*/
+
+
+#include "ui_local.h"
+
+
+#define ART_BACKGROUND "menu/art/addbotframe"
+#define ART_BACK0 "menu/art/back_0"
+#define ART_BACK1 "menu/art/back_1"
+#define ART_DELETE0 "menu/art/delete_0"
+#define ART_DELETE1 "menu/art/delete_1"
+#define ART_ARROWS "menu/art/arrows_vert_0"
+#define ART_ARROWUP "menu/art/arrows_vert_top"
+#define ART_ARROWDOWN "menu/art/arrows_vert_bot"
+
+#define ID_UP 10
+#define ID_DOWN 11
+#define ID_DELETE 12
+#define ID_BACK 13
+#define ID_BOTNAME0 20
+#define ID_BOTNAME1 21
+#define ID_BOTNAME2 22
+#define ID_BOTNAME3 23
+#define ID_BOTNAME4 24
+#define ID_BOTNAME5 25
+#define ID_BOTNAME6 26
+
+
+typedef struct {
+ menuframework_s menu;
+
+ menutext_s banner;
+ menubitmap_s background;
+
+ menubitmap_s arrows;
+ menubitmap_s up;
+ menubitmap_s down;
+
+ menutext_s bots[7];
+
+ menubitmap_s delete;
+ menubitmap_s back;
+
+ int numBots;
+ int baseBotNum;
+ int selectedBotNum;
+ char botnames[7][32];
+ int botClientNums[MAX_BOTS];
+} removeBotsMenuInfo_t;
+
+static removeBotsMenuInfo_t removeBotsMenuInfo;
+
+
+/*
+=================
+UI_RemoveBotsMenu_SetBotNames
+=================
+*/
+static void UI_RemoveBotsMenu_SetBotNames( void ) {
+ int n;
+ char info[MAX_INFO_STRING];
+
+ for ( n = 0; (n < 7) && (removeBotsMenuInfo.baseBotNum + n < removeBotsMenuInfo.numBots); n++ ) {
+ trap_GetConfigString( CS_PLAYERS + removeBotsMenuInfo.botClientNums[removeBotsMenuInfo.baseBotNum + n], info, MAX_INFO_STRING );
+ Q_strncpyz( removeBotsMenuInfo.botnames[n], Info_ValueForKey( info, "n" ), sizeof(removeBotsMenuInfo.botnames[n]) );
+ Q_CleanStr( removeBotsMenuInfo.botnames[n] );
+ }
+
+}
+
+
+/*
+=================
+UI_RemoveBotsMenu_DeleteEvent
+=================
+*/
+static void UI_RemoveBotsMenu_DeleteEvent( void* ptr, int event ) {
+ if (event != QM_ACTIVATED) {
+ return;
+ }
+
+ trap_Cmd_ExecuteText( EXEC_APPEND, va("clientkick %i\n", removeBotsMenuInfo.botClientNums[removeBotsMenuInfo.baseBotNum + removeBotsMenuInfo.selectedBotNum]) );
+}
+
+
+/*
+=================
+UI_RemoveBotsMenu_BotEvent
+=================
+*/
+static void UI_RemoveBotsMenu_BotEvent( void* ptr, int event ) {
+ if (event != QM_ACTIVATED) {
+ return;
+ }
+
+ removeBotsMenuInfo.bots[removeBotsMenuInfo.selectedBotNum].color = color_orange;
+ removeBotsMenuInfo.selectedBotNum = ((menucommon_s*)ptr)->id - ID_BOTNAME0;
+ removeBotsMenuInfo.bots[removeBotsMenuInfo.selectedBotNum].color = color_white;
+}
+
+
+/*
+=================
+UI_RemoveAddBotsMenu_BackEvent
+=================
+*/
+static void UI_RemoveBotsMenu_BackEvent( void* ptr, int event ) {
+ if (event != QM_ACTIVATED) {
+ return;
+ }
+ UI_PopMenu();
+}
+
+
+/*
+=================
+UI_RemoveBotsMenu_UpEvent
+=================
+*/
+static void UI_RemoveBotsMenu_UpEvent( void* ptr, int event ) {
+ if (event != QM_ACTIVATED) {
+ return;
+ }
+
+ if( removeBotsMenuInfo.baseBotNum > 0 ) {
+ removeBotsMenuInfo.baseBotNum--;
+ UI_RemoveBotsMenu_SetBotNames();
+ }
+}
+
+
+/*
+=================
+UI_RemoveBotsMenu_DownEvent
+=================
+*/
+static void UI_RemoveBotsMenu_DownEvent( void* ptr, int event ) {
+ if (event != QM_ACTIVATED) {
+ return;
+ }
+
+ if( removeBotsMenuInfo.baseBotNum + 7 < removeBotsMenuInfo.numBots ) {
+ removeBotsMenuInfo.baseBotNum++;
+ UI_RemoveBotsMenu_SetBotNames();
+ }
+}
+
+
+/*
+=================
+UI_RemoveBotsMenu_GetBots
+=================
+*/
+static void UI_RemoveBotsMenu_GetBots( void ) {
+ int numPlayers;
+ int isBot;
+ int n;
+ char info[MAX_INFO_STRING];
+
+ trap_GetConfigString( CS_SERVERINFO, info, sizeof(info) );
+ numPlayers = atoi( Info_ValueForKey( info, "sv_maxclients" ) );
+ removeBotsMenuInfo.numBots = 0;
+
+ for( n = 0; n < numPlayers; n++ ) {
+ trap_GetConfigString( CS_PLAYERS + n, info, MAX_INFO_STRING );
+
+ isBot = atoi( Info_ValueForKey( info, "skill" ) );
+ if( !isBot ) {
+ continue;
+ }
+
+ removeBotsMenuInfo.botClientNums[removeBotsMenuInfo.numBots] = n;
+ removeBotsMenuInfo.numBots++;
+ }
+}
+
+
+/*
+=================
+UI_RemoveBots_Cache
+=================
+*/
+void UI_RemoveBots_Cache( void ) {
+ trap_R_RegisterShaderNoMip( ART_BACKGROUND );
+ trap_R_RegisterShaderNoMip( ART_BACK0 );
+ trap_R_RegisterShaderNoMip( ART_BACK1 );
+ trap_R_RegisterShaderNoMip( ART_DELETE0 );
+ trap_R_RegisterShaderNoMip( ART_DELETE1 );
+}
+
+
+/*
+=================
+UI_RemoveBotsMenu_Init
+=================
+*/
+static void UI_RemoveBotsMenu_Init( void ) {
+ int n;
+ int count;
+ int y;
+
+ memset( &removeBotsMenuInfo, 0 ,sizeof(removeBotsMenuInfo) );
+ removeBotsMenuInfo.menu.fullscreen = qfalse;
+ removeBotsMenuInfo.menu.wrapAround = qtrue;
+
+ UI_RemoveBots_Cache();
+
+ UI_RemoveBotsMenu_GetBots();
+ UI_RemoveBotsMenu_SetBotNames();
+ count = removeBotsMenuInfo.numBots < 7 ? removeBotsMenuInfo.numBots : 7;
+
+ removeBotsMenuInfo.banner.generic.type = MTYPE_BTEXT;
+ removeBotsMenuInfo.banner.generic.x = 320;
+ removeBotsMenuInfo.banner.generic.y = 16;
+ removeBotsMenuInfo.banner.string = "REMOVE BOTS";
+ removeBotsMenuInfo.banner.color = color_white;
+ removeBotsMenuInfo.banner.style = UI_CENTER;
+
+ removeBotsMenuInfo.background.generic.type = MTYPE_BITMAP;
+ removeBotsMenuInfo.background.generic.name = ART_BACKGROUND;
+ removeBotsMenuInfo.background.generic.flags = QMF_INACTIVE;
+ removeBotsMenuInfo.background.generic.x = 320-233;
+ removeBotsMenuInfo.background.generic.y = 240-166;
+ removeBotsMenuInfo.background.width = 466;
+ removeBotsMenuInfo.background.height = 332;
+
+ removeBotsMenuInfo.arrows.generic.type = MTYPE_BITMAP;
+ removeBotsMenuInfo.arrows.generic.name = ART_ARROWS;
+ removeBotsMenuInfo.arrows.generic.flags = QMF_INACTIVE;
+ removeBotsMenuInfo.arrows.generic.x = 200;
+ removeBotsMenuInfo.arrows.generic.y = 128;
+ removeBotsMenuInfo.arrows.width = 64;
+ removeBotsMenuInfo.arrows.height = 128;
+
+ removeBotsMenuInfo.up.generic.type = MTYPE_BITMAP;
+ removeBotsMenuInfo.up.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ removeBotsMenuInfo.up.generic.x = 200;
+ removeBotsMenuInfo.up.generic.y = 128;
+ removeBotsMenuInfo.up.generic.id = ID_UP;
+ removeBotsMenuInfo.up.generic.callback = UI_RemoveBotsMenu_UpEvent;
+ removeBotsMenuInfo.up.width = 64;
+ removeBotsMenuInfo.up.height = 64;
+ removeBotsMenuInfo.up.focuspic = ART_ARROWUP;
+
+ removeBotsMenuInfo.down.generic.type = MTYPE_BITMAP;
+ removeBotsMenuInfo.down.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ removeBotsMenuInfo.down.generic.x = 200;
+ removeBotsMenuInfo.down.generic.y = 128+64;
+ removeBotsMenuInfo.down.generic.id = ID_DOWN;
+ removeBotsMenuInfo.down.generic.callback = UI_RemoveBotsMenu_DownEvent;
+ removeBotsMenuInfo.down.width = 64;
+ removeBotsMenuInfo.down.height = 64;
+ removeBotsMenuInfo.down.focuspic = ART_ARROWDOWN;
+
+ for( n = 0, y = 120; n < count; n++, y += 20 ) {
+ removeBotsMenuInfo.bots[n].generic.type = MTYPE_PTEXT;
+ removeBotsMenuInfo.bots[n].generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ removeBotsMenuInfo.bots[n].generic.id = ID_BOTNAME0 + n;
+ removeBotsMenuInfo.bots[n].generic.x = 320 - 56;
+ removeBotsMenuInfo.bots[n].generic.y = y;
+ removeBotsMenuInfo.bots[n].generic.callback = UI_RemoveBotsMenu_BotEvent;
+ removeBotsMenuInfo.bots[n].string = removeBotsMenuInfo.botnames[n];
+ removeBotsMenuInfo.bots[n].color = color_orange;
+ removeBotsMenuInfo.bots[n].style = UI_LEFT|UI_SMALLFONT;
+ }
+
+ removeBotsMenuInfo.delete.generic.type = MTYPE_BITMAP;
+ removeBotsMenuInfo.delete.generic.name = ART_DELETE0;
+ removeBotsMenuInfo.delete.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ removeBotsMenuInfo.delete.generic.id = ID_DELETE;
+ removeBotsMenuInfo.delete.generic.callback = UI_RemoveBotsMenu_DeleteEvent;
+ removeBotsMenuInfo.delete.generic.x = 320+128-128;
+ removeBotsMenuInfo.delete.generic.y = 256+128-64;
+ removeBotsMenuInfo.delete.width = 128;
+ removeBotsMenuInfo.delete.height = 64;
+ removeBotsMenuInfo.delete.focuspic = ART_DELETE1;
+
+ removeBotsMenuInfo.back.generic.type = MTYPE_BITMAP;
+ removeBotsMenuInfo.back.generic.name = ART_BACK0;
+ removeBotsMenuInfo.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ removeBotsMenuInfo.back.generic.id = ID_BACK;
+ removeBotsMenuInfo.back.generic.callback = UI_RemoveBotsMenu_BackEvent;
+ removeBotsMenuInfo.back.generic.x = 320-128;
+ removeBotsMenuInfo.back.generic.y = 256+128-64;
+ removeBotsMenuInfo.back.width = 128;
+ removeBotsMenuInfo.back.height = 64;
+ removeBotsMenuInfo.back.focuspic = ART_BACK1;
+
+ Menu_AddItem( &removeBotsMenuInfo.menu, &removeBotsMenuInfo.background );
+ Menu_AddItem( &removeBotsMenuInfo.menu, &removeBotsMenuInfo.banner );
+ Menu_AddItem( &removeBotsMenuInfo.menu, &removeBotsMenuInfo.arrows );
+ Menu_AddItem( &removeBotsMenuInfo.menu, &removeBotsMenuInfo.up );
+ Menu_AddItem( &removeBotsMenuInfo.menu, &removeBotsMenuInfo.down );
+ for( n = 0; n < count; n++ ) {
+ Menu_AddItem( &removeBotsMenuInfo.menu, &removeBotsMenuInfo.bots[n] );
+ }
+ Menu_AddItem( &removeBotsMenuInfo.menu, &removeBotsMenuInfo.delete );
+ Menu_AddItem( &removeBotsMenuInfo.menu, &removeBotsMenuInfo.back );
+
+ removeBotsMenuInfo.baseBotNum = 0;
+ removeBotsMenuInfo.selectedBotNum = 0;
+ removeBotsMenuInfo.bots[0].color = color_white;
+}
+
+
+/*
+=================
+UI_RemoveBotsMenu
+=================
+*/
+void UI_RemoveBotsMenu( void ) {
+ UI_RemoveBotsMenu_Init();
+ UI_PushMenu( &removeBotsMenuInfo.menu );
+}
diff --git a/code/q3_ui/ui_saveconfig.c b/code/q3_ui/ui_saveconfig.c
new file mode 100755
index 0000000..d13b676
--- /dev/null
+++ b/code/q3_ui/ui_saveconfig.c
@@ -0,0 +1,212 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*
+=============================================================================
+
+SAVE CONFIG MENU
+
+=============================================================================
+*/
+
+#include "ui_local.h"
+
+
+#define ART_BACK0 "menu/art/back_0"
+#define ART_BACK1 "menu/art/back_1"
+#define ART_SAVE0 "menu/art/save_0"
+#define ART_SAVE1 "menu/art/save_1"
+#define ART_BACKGROUND "menu/art/cut_frame"
+
+#define ID_NAME 10
+#define ID_BACK 11
+#define ID_SAVE 12
+
+
+typedef struct {
+ menuframework_s menu;
+
+ menutext_s banner;
+ menubitmap_s background;
+ menufield_s savename;
+ menubitmap_s back;
+ menubitmap_s save;
+} saveConfig_t;
+
+static saveConfig_t saveConfig;
+
+
+/*
+===============
+UI_SaveConfigMenu_BackEvent
+===============
+*/
+static void UI_SaveConfigMenu_BackEvent( void *ptr, int event ) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+
+ UI_PopMenu();
+}
+
+
+/*
+===============
+UI_SaveConfigMenu_SaveEvent
+===============
+*/
+static void UI_SaveConfigMenu_SaveEvent( void *ptr, int event ) {
+ char configname[MAX_QPATH];
+
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+
+ if( !saveConfig.savename.field.buffer[0] ) {
+ return;
+ }
+
+ COM_StripExtension(saveConfig.savename.field.buffer, configname );
+ trap_Cmd_ExecuteText( EXEC_APPEND, va( "writeconfig %s.cfg\n", configname ) );
+ UI_PopMenu();
+}
+
+
+/*
+===============
+UI_SaveConfigMenu_SavenameDraw
+===============
+*/
+static void UI_SaveConfigMenu_SavenameDraw( void *self ) {
+ menufield_s *f;
+ int style;
+ float *color;
+
+ f = (menufield_s *)self;
+
+ if( f == Menu_ItemAtCursor( &saveConfig.menu ) ) {
+ style = UI_LEFT|UI_PULSE|UI_SMALLFONT;
+ color = text_color_highlight;
+ }
+ else {
+ style = UI_LEFT|UI_SMALLFONT;
+ color = colorRed;
+ }
+
+ UI_DrawProportionalString( 320, 192, "Enter filename:", UI_CENTER|UI_SMALLFONT, color_orange );
+ UI_FillRect( f->generic.x, f->generic.y, f->field.widthInChars*SMALLCHAR_WIDTH, SMALLCHAR_HEIGHT, colorBlack );
+ MField_Draw( &f->field, f->generic.x, f->generic.y, style, color );
+}
+
+
+/*
+=================
+UI_SaveConfigMenu_Init
+=================
+*/
+static void UI_SaveConfigMenu_Init( void ) {
+ memset( &saveConfig, 0, sizeof(saveConfig) );
+
+ UI_SaveConfigMenu_Cache();
+ saveConfig.menu.wrapAround = qtrue;
+ saveConfig.menu.fullscreen = qtrue;
+
+ saveConfig.banner.generic.type = MTYPE_BTEXT;
+ saveConfig.banner.generic.x = 320;
+ saveConfig.banner.generic.y = 16;
+ saveConfig.banner.string = "SAVE CONFIG";
+ saveConfig.banner.color = color_white;
+ saveConfig.banner.style = UI_CENTER;
+
+ saveConfig.background.generic.type = MTYPE_BITMAP;
+ saveConfig.background.generic.name = ART_BACKGROUND;
+ saveConfig.background.generic.flags = QMF_INACTIVE;
+ saveConfig.background.generic.x = 142;
+ saveConfig.background.generic.y = 118;
+ saveConfig.background.width = 359;
+ saveConfig.background.height = 256;
+
+ saveConfig.savename.generic.type = MTYPE_FIELD;
+ saveConfig.savename.generic.flags = QMF_NODEFAULTINIT|QMF_UPPERCASE;
+ saveConfig.savename.generic.ownerdraw = UI_SaveConfigMenu_SavenameDraw;
+ saveConfig.savename.field.widthInChars = 20;
+ saveConfig.savename.field.maxchars = 20;
+ saveConfig.savename.generic.x = 240;
+ saveConfig.savename.generic.y = 155+72;
+ saveConfig.savename.generic.left = 240;
+ saveConfig.savename.generic.top = 155+72;
+ saveConfig.savename.generic.right = 233 + 20*SMALLCHAR_WIDTH;
+ saveConfig.savename.generic.bottom = 155+72 + SMALLCHAR_HEIGHT+2;
+
+ saveConfig.back.generic.type = MTYPE_BITMAP;
+ saveConfig.back.generic.name = ART_BACK0;
+ saveConfig.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ saveConfig.back.generic.id = ID_BACK;
+ saveConfig.back.generic.callback = UI_SaveConfigMenu_BackEvent;
+ saveConfig.back.generic.x = 0;
+ saveConfig.back.generic.y = 480-64;
+ saveConfig.back.width = 128;
+ saveConfig.back.height = 64;
+ saveConfig.back.focuspic = ART_BACK1;
+
+ saveConfig.save.generic.type = MTYPE_BITMAP;
+ saveConfig.save.generic.name = ART_SAVE0;
+ saveConfig.save.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ saveConfig.save.generic.id = ID_SAVE;
+ saveConfig.save.generic.callback = UI_SaveConfigMenu_SaveEvent;
+ saveConfig.save.generic.x = 640;
+ saveConfig.save.generic.y = 480-64;
+ saveConfig.save.width = 128;
+ saveConfig.save.height = 64;
+ saveConfig.save.focuspic = ART_SAVE1;
+
+ Menu_AddItem( &saveConfig.menu, &saveConfig.banner );
+ Menu_AddItem( &saveConfig.menu, &saveConfig.background );
+ Menu_AddItem( &saveConfig.menu, &saveConfig.savename );
+ Menu_AddItem( &saveConfig.menu, &saveConfig.back );
+ Menu_AddItem( &saveConfig.menu, &saveConfig.save );
+}
+
+
+/*
+=================
+UI_SaveConfigMenu_Cache
+=================
+*/
+void UI_SaveConfigMenu_Cache( void ) {
+ trap_R_RegisterShaderNoMip( ART_BACK0 );
+ trap_R_RegisterShaderNoMip( ART_BACK1 );
+ trap_R_RegisterShaderNoMip( ART_SAVE0 );
+ trap_R_RegisterShaderNoMip( ART_SAVE1 );
+ trap_R_RegisterShaderNoMip( ART_BACKGROUND );
+}
+
+
+/*
+===============
+UI_SaveConfigMenu
+===============
+*/
+void UI_SaveConfigMenu( void ) {
+ UI_SaveConfigMenu_Init();
+ UI_PushMenu( &saveConfig.menu );
+}
diff --git a/code/q3_ui/ui_serverinfo.c b/code/q3_ui/ui_serverinfo.c
new file mode 100755
index 0000000..61f4ad8
--- /dev/null
+++ b/code/q3_ui/ui_serverinfo.c
@@ -0,0 +1,272 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#include "ui_local.h"
+
+#define SERVERINFO_FRAMEL "menu/art/frame2_l"
+#define SERVERINFO_FRAMER "menu/art/frame1_r"
+#define SERVERINFO_BACK0 "menu/art/back_0"
+#define SERVERINFO_BACK1 "menu/art/back_1"
+
+static char* serverinfo_artlist[] =
+{
+ SERVERINFO_FRAMEL,
+ SERVERINFO_FRAMER,
+ SERVERINFO_BACK0,
+ SERVERINFO_BACK1,
+ NULL
+};
+
+#define ID_ADD 100
+#define ID_BACK 101
+
+typedef struct
+{
+ menuframework_s menu;
+ menutext_s banner;
+ menubitmap_s framel;
+ menubitmap_s framer;
+ menubitmap_s back;
+ menutext_s add;
+ char info[MAX_INFO_STRING];
+ int numlines;
+} serverinfo_t;
+
+static serverinfo_t s_serverinfo;
+
+
+/*
+=================
+Favorites_Add
+
+Add current server to favorites
+=================
+*/
+void Favorites_Add( void )
+{
+ char adrstr[128];
+ char serverbuff[128];
+ int i;
+ int best;
+
+ trap_Cvar_VariableStringBuffer( "cl_currentServerAddress", serverbuff, sizeof(serverbuff) );
+ if (!serverbuff[0])
+ return;
+
+ best = 0;
+ for (i=0; i<MAX_FAVORITESERVERS; i++)
+ {
+ trap_Cvar_VariableStringBuffer( va("server%d",i+1), adrstr, sizeof(adrstr) );
+ if (!Q_stricmp(serverbuff,adrstr))
+ {
+ // already in list
+ return;
+ }
+
+ // use first empty or non-numeric available slot
+ if ((adrstr[0] < '0' || adrstr[0] > '9' ) && !best)
+ best = i+1;
+ }
+
+ if (best)
+ trap_Cvar_Set( va("server%d",best), serverbuff);
+}
+
+
+/*
+=================
+ServerInfo_Event
+=================
+*/
+static void ServerInfo_Event( void* ptr, int event )
+{
+ switch (((menucommon_s*)ptr)->id)
+ {
+ case ID_ADD:
+ if (event != QM_ACTIVATED)
+ break;
+
+ Favorites_Add();
+ UI_PopMenu();
+ break;
+
+ case ID_BACK:
+ if (event != QM_ACTIVATED)
+ break;
+
+ UI_PopMenu();
+ break;
+ }
+}
+
+/*
+=================
+ServerInfo_MenuDraw
+=================
+*/
+static void ServerInfo_MenuDraw( void )
+{
+ const char *s;
+ char key[MAX_INFO_KEY];
+ char value[MAX_INFO_VALUE];
+ int y;
+
+ y = SCREEN_HEIGHT/2 - s_serverinfo.numlines*(SMALLCHAR_HEIGHT)/2 - 20;
+ s = s_serverinfo.info;
+ while ( s ) {
+ Info_NextPair( &s, key, value );
+ if ( !key[0] ) {
+ break;
+ }
+
+ Q_strcat( key, MAX_INFO_KEY, ":" );
+
+ UI_DrawString(SCREEN_WIDTH*0.50 - 8,y,key,UI_RIGHT|UI_SMALLFONT,color_red);
+ UI_DrawString(SCREEN_WIDTH*0.50 + 8,y,value,UI_LEFT|UI_SMALLFONT,text_color_normal);
+
+ y += SMALLCHAR_HEIGHT;
+ }
+
+ Menu_Draw( &s_serverinfo.menu );
+}
+
+/*
+=================
+ServerInfo_MenuKey
+=================
+*/
+static sfxHandle_t ServerInfo_MenuKey( int key )
+{
+ return ( Menu_DefaultKey( &s_serverinfo.menu, key ) );
+}
+
+/*
+=================
+ServerInfo_Cache
+=================
+*/
+void ServerInfo_Cache( void )
+{
+ int i;
+
+ // touch all our pics
+ for (i=0; ;i++)
+ {
+ if (!serverinfo_artlist[i])
+ break;
+ trap_R_RegisterShaderNoMip(serverinfo_artlist[i]);
+ }
+}
+
+/*
+=================
+UI_ServerInfoMenu
+=================
+*/
+void UI_ServerInfoMenu( void )
+{
+ const char *s;
+ char key[MAX_INFO_KEY];
+ char value[MAX_INFO_VALUE];
+
+ // zero set all our globals
+ memset( &s_serverinfo, 0 ,sizeof(serverinfo_t) );
+
+ ServerInfo_Cache();
+
+ s_serverinfo.menu.draw = ServerInfo_MenuDraw;
+ s_serverinfo.menu.key = ServerInfo_MenuKey;
+ s_serverinfo.menu.wrapAround = qtrue;
+ s_serverinfo.menu.fullscreen = qtrue;
+
+ s_serverinfo.banner.generic.type = MTYPE_BTEXT;
+ s_serverinfo.banner.generic.x = 320;
+ s_serverinfo.banner.generic.y = 16;
+ s_serverinfo.banner.string = "SERVER INFO";
+ s_serverinfo.banner.color = color_white;
+ s_serverinfo.banner.style = UI_CENTER;
+
+ s_serverinfo.framel.generic.type = MTYPE_BITMAP;
+ s_serverinfo.framel.generic.name = SERVERINFO_FRAMEL;
+ s_serverinfo.framel.generic.flags = QMF_INACTIVE;
+ s_serverinfo.framel.generic.x = 0;
+ s_serverinfo.framel.generic.y = 78;
+ s_serverinfo.framel.width = 256;
+ s_serverinfo.framel.height = 329;
+
+ s_serverinfo.framer.generic.type = MTYPE_BITMAP;
+ s_serverinfo.framer.generic.name = SERVERINFO_FRAMER;
+ s_serverinfo.framer.generic.flags = QMF_INACTIVE;
+ s_serverinfo.framer.generic.x = 376;
+ s_serverinfo.framer.generic.y = 76;
+ s_serverinfo.framer.width = 256;
+ s_serverinfo.framer.height = 334;
+
+ s_serverinfo.add.generic.type = MTYPE_PTEXT;
+ s_serverinfo.add.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_serverinfo.add.generic.callback = ServerInfo_Event;
+ s_serverinfo.add.generic.id = ID_ADD;
+ s_serverinfo.add.generic.x = 320;
+ s_serverinfo.add.generic.y = 371;
+ s_serverinfo.add.string = "ADD TO FAVORITES";
+ s_serverinfo.add.style = UI_CENTER|UI_SMALLFONT;
+ s_serverinfo.add.color = color_red;
+ if( trap_Cvar_VariableValue( "sv_running" ) ) {
+ s_serverinfo.add.generic.flags |= QMF_GRAYED;
+ }
+
+ s_serverinfo.back.generic.type = MTYPE_BITMAP;
+ s_serverinfo.back.generic.name = SERVERINFO_BACK0;
+ s_serverinfo.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_serverinfo.back.generic.callback = ServerInfo_Event;
+ s_serverinfo.back.generic.id = ID_BACK;
+ s_serverinfo.back.generic.x = 0;
+ s_serverinfo.back.generic.y = 480-64;
+ s_serverinfo.back.width = 128;
+ s_serverinfo.back.height = 64;
+ s_serverinfo.back.focuspic = SERVERINFO_BACK1;
+
+ trap_GetConfigString( CS_SERVERINFO, s_serverinfo.info, MAX_INFO_STRING );
+
+ s_serverinfo.numlines = 0;
+ s = s_serverinfo.info;
+ while ( s ) {
+ Info_NextPair( &s, key, value );
+ if ( !key[0] ) {
+ break;
+ }
+ s_serverinfo.numlines++;
+ }
+
+ if (s_serverinfo.numlines > 16)
+ s_serverinfo.numlines = 16;
+
+ Menu_AddItem( &s_serverinfo.menu, (void*) &s_serverinfo.banner );
+ Menu_AddItem( &s_serverinfo.menu, (void*) &s_serverinfo.framel );
+ Menu_AddItem( &s_serverinfo.menu, (void*) &s_serverinfo.framer );
+ Menu_AddItem( &s_serverinfo.menu, (void*) &s_serverinfo.add );
+ Menu_AddItem( &s_serverinfo.menu, (void*) &s_serverinfo.back );
+
+ UI_PushMenu( &s_serverinfo.menu );
+}
+
+
diff --git a/code/q3_ui/ui_servers2.c b/code/q3_ui/ui_servers2.c
new file mode 100755
index 0000000..d20fb6f
--- /dev/null
+++ b/code/q3_ui/ui_servers2.c
@@ -0,0 +1,1640 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*
+=======================================================================
+
+MULTIPLAYER MENU (SERVER BROWSER)
+
+=======================================================================
+*/
+
+
+#include "ui_local.h"
+
+
+#define MAX_GLOBALSERVERS 128
+#define MAX_PINGREQUESTS 32
+#define MAX_ADDRESSLENGTH 64
+#define MAX_HOSTNAMELENGTH 22
+#define MAX_MAPNAMELENGTH 16
+#define MAX_LISTBOXITEMS 128
+#define MAX_LOCALSERVERS 128
+#define MAX_STATUSLENGTH 64
+#define MAX_LEAGUELENGTH 28
+#define MAX_LISTBOXWIDTH 68
+
+#define ART_BACK0 "menu/art/back_0"
+#define ART_BACK1 "menu/art/back_1"
+#define ART_CREATE0 "menu/art/create_0"
+#define ART_CREATE1 "menu/art/create_1"
+#define ART_SPECIFY0 "menu/art/specify_0"
+#define ART_SPECIFY1 "menu/art/specify_1"
+#define ART_REFRESH0 "menu/art/refresh_0"
+#define ART_REFRESH1 "menu/art/refresh_1"
+#define ART_CONNECT0 "menu/art/fight_0"
+#define ART_CONNECT1 "menu/art/fight_1"
+#define ART_ARROWS0 "menu/art/arrows_vert_0"
+#define ART_ARROWS_UP "menu/art/arrows_vert_top"
+#define ART_ARROWS_DOWN "menu/art/arrows_vert_bot"
+#define ART_UNKNOWNMAP "menu/art/unknownmap"
+#define ART_REMOVE0 "menu/art/delete_0"
+#define ART_REMOVE1 "menu/art/delete_1"
+#define ART_PUNKBUSTER "menu/art/pblogo"
+
+#define ID_MASTER 10
+#define ID_GAMETYPE 11
+#define ID_SORTKEY 12
+#define ID_SHOW_FULL 13
+#define ID_SHOW_EMPTY 14
+#define ID_LIST 15
+#define ID_SCROLL_UP 16
+#define ID_SCROLL_DOWN 17
+#define ID_BACK 18
+#define ID_REFRESH 19
+#define ID_SPECIFY 20
+#define ID_CREATE 21
+#define ID_CONNECT 22
+#define ID_REMOVE 23
+#define ID_PUNKBUSTER 24
+
+#define GR_LOGO 30
+#define GR_LETTERS 31
+
+#define AS_LOCAL 0
+#define AS_MPLAYER 1
+#define AS_GLOBAL 2
+#define AS_FAVORITES 3
+
+#define SORT_HOST 0
+#define SORT_MAP 1
+#define SORT_CLIENTS 2
+#define SORT_GAME 3
+#define SORT_PING 4
+
+#define GAMES_ALL 0
+#define GAMES_FFA 1
+#define GAMES_TEAMPLAY 2
+#define GAMES_TOURNEY 3
+#define GAMES_CTF 4
+
+static const char *master_items[] = {
+ "Local",
+ "Internet",
+ "Favorites",
+ 0
+};
+
+static const char *servertype_items[] = {
+ "All",
+ "Free For All",
+ "Team Deathmatch",
+ "Tournament",
+ "Capture the Flag",
+ 0
+};
+
+static const char *sortkey_items[] = {
+ "Server Name",
+ "Map Name",
+ "Open Player Spots",
+ "Game Type",
+ "Ping Time",
+ 0
+};
+
+static char* gamenames[] = {
+ "DM ", // deathmatch
+ "1v1", // tournament
+ "SP ", // single player
+ "Team DM", // team deathmatch
+ "CTF", // capture the flag
+ "One Flag CTF", // one flag ctf
+ "OverLoad", // Overload
+ "Harvester", // Harvester
+ "Rocket Arena 3", // Rocket Arena 3
+ "Q3F", // Q3F
+ "Urban Terror", // Urban Terror
+ "OSP", // Orange Smoothie Productions
+ "???", // unknown
+ 0
+};
+
+static char* netnames[] = {
+ "???",
+ "UDP",
+ "IPX",
+ NULL
+};
+
+static char quake3worldMessage[] = "Visit www.quake3world.com - News, Community, Events, Files";
+
+const char* punkbuster_items[] = {
+ "Disabled",
+ "Enabled",
+ NULL
+};
+
+const char* punkbuster_msg[] = {
+ "PunkBuster will be",
+ "disabled the next time",
+ "Quake III Arena",
+ "is started.",
+ NULL
+};
+
+typedef struct {
+ char adrstr[MAX_ADDRESSLENGTH];
+ int start;
+} pinglist_t;
+
+typedef struct servernode_s {
+ char adrstr[MAX_ADDRESSLENGTH];
+ char hostname[MAX_HOSTNAMELENGTH+3];
+ char mapname[MAX_MAPNAMELENGTH];
+ int numclients;
+ int maxclients;
+ int pingtime;
+ int gametype;
+ char gamename[12];
+ int nettype;
+ int minPing;
+ int maxPing;
+ qboolean bPB;
+
+} servernode_t;
+
+typedef struct {
+ char buff[MAX_LISTBOXWIDTH];
+ servernode_t* servernode;
+} table_t;
+
+typedef struct {
+ menuframework_s menu;
+
+ menutext_s banner;
+
+ menulist_s master;
+ menulist_s gametype;
+ menulist_s sortkey;
+ menuradiobutton_s showfull;
+ menuradiobutton_s showempty;
+
+ menulist_s list;
+ menubitmap_s mappic;
+ menubitmap_s arrows;
+ menubitmap_s up;
+ menubitmap_s down;
+ menutext_s status;
+ menutext_s statusbar;
+
+ menubitmap_s remove;
+ menubitmap_s back;
+ menubitmap_s refresh;
+ menubitmap_s specify;
+ menubitmap_s create;
+ menubitmap_s go;
+
+ pinglist_t pinglist[MAX_PINGREQUESTS];
+ table_t table[MAX_LISTBOXITEMS];
+ char* items[MAX_LISTBOXITEMS];
+ int numqueriedservers;
+ int *numservers;
+ servernode_t *serverlist;
+ int currentping;
+ qboolean refreshservers;
+ int nextpingtime;
+ int maxservers;
+ int refreshtime;
+ char favoriteaddresses[MAX_FAVORITESERVERS][MAX_ADDRESSLENGTH];
+ int numfavoriteaddresses;
+
+ menulist_s punkbuster;
+ menubitmap_s pblogo;
+} arenaservers_t;
+
+static arenaservers_t g_arenaservers;
+
+
+static servernode_t g_globalserverlist[MAX_GLOBALSERVERS];
+static int g_numglobalservers;
+static servernode_t g_localserverlist[MAX_LOCALSERVERS];
+static int g_numlocalservers;
+static servernode_t g_favoriteserverlist[MAX_FAVORITESERVERS];
+static int g_numfavoriteservers;
+static servernode_t g_mplayerserverlist[MAX_GLOBALSERVERS];
+static int g_nummplayerservers;
+static int g_servertype;
+static int g_gametype;
+static int g_sortkey;
+static int g_emptyservers;
+static int g_fullservers;
+
+
+/*
+=================
+ArenaServers_MaxPing
+=================
+*/
+static int ArenaServers_MaxPing( void ) {
+ int maxPing;
+
+ maxPing = (int)trap_Cvar_VariableValue( "cl_maxPing" );
+ if( maxPing < 100 ) {
+ maxPing = 100;
+ }
+ return maxPing;
+}
+
+
+/*
+=================
+ArenaServers_Compare
+=================
+*/
+static int QDECL ArenaServers_Compare( const void *arg1, const void *arg2 ) {
+ float f1;
+ float f2;
+ servernode_t* t1;
+ servernode_t* t2;
+
+ t1 = (servernode_t *)arg1;
+ t2 = (servernode_t *)arg2;
+
+ switch( g_sortkey ) {
+ case SORT_HOST:
+ return Q_stricmp( t1->hostname, t2->hostname );
+
+ case SORT_MAP:
+ return Q_stricmp( t1->mapname, t2->mapname );
+
+ case SORT_CLIENTS:
+ f1 = t1->maxclients - t1->numclients;
+ if( f1 < 0 ) {
+ f1 = 0;
+ }
+
+ f2 = t2->maxclients - t2->numclients;
+ if( f2 < 0 ) {
+ f2 = 0;
+ }
+
+ if( f1 < f2 ) {
+ return 1;
+ }
+ if( f1 == f2 ) {
+ return 0;
+ }
+ return -1;
+
+ case SORT_GAME:
+ if( t1->gametype < t2->gametype ) {
+ return -1;
+ }
+ if( t1->gametype == t2->gametype ) {
+ return 0;
+ }
+ return 1;
+
+ case SORT_PING:
+ if( t1->pingtime < t2->pingtime ) {
+ return -1;
+ }
+ if( t1->pingtime > t2->pingtime ) {
+ return 1;
+ }
+ return Q_stricmp( t1->hostname, t2->hostname );
+ }
+
+ return 0;
+}
+
+
+/*
+=================
+ArenaServers_Go
+=================
+*/
+static void ArenaServers_Go( void ) {
+ servernode_t* servernode;
+
+ servernode = g_arenaservers.table[g_arenaservers.list.curvalue].servernode;
+ if( servernode ) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, va( "connect %s\n", servernode->adrstr ) );
+ }
+}
+
+
+/*
+=================
+ArenaServers_UpdatePicture
+=================
+*/
+static void ArenaServers_UpdatePicture( void ) {
+ static char picname[64];
+ servernode_t* servernodeptr;
+
+ if( !g_arenaservers.list.numitems ) {
+ g_arenaservers.mappic.generic.name = NULL;
+ }
+ else {
+ servernodeptr = g_arenaservers.table[g_arenaservers.list.curvalue].servernode;
+ Com_sprintf( picname, sizeof(picname), "levelshots/%s.tga", servernodeptr->mapname );
+ g_arenaservers.mappic.generic.name = picname;
+
+ }
+
+ // force shader update during draw
+ g_arenaservers.mappic.shader = 0;
+}
+
+
+/*
+=================
+ArenaServers_UpdateMenu
+=================
+*/
+static void ArenaServers_UpdateMenu( void ) {
+ int i;
+ int j;
+ int count;
+ char* buff;
+ servernode_t* servernodeptr;
+ table_t* tableptr;
+ char *pingColor;
+
+ if( g_arenaservers.numqueriedservers > 0 ) {
+ // servers found
+ if( g_arenaservers.refreshservers && ( g_arenaservers.currentping <= g_arenaservers.numqueriedservers ) ) {
+ // show progress
+ Com_sprintf( g_arenaservers.status.string, MAX_STATUSLENGTH, "%d of %d Arena Servers.", g_arenaservers.currentping, g_arenaservers.numqueriedservers);
+ g_arenaservers.statusbar.string = "Press SPACE to stop";
+ qsort( g_arenaservers.serverlist, *g_arenaservers.numservers, sizeof( servernode_t ), ArenaServers_Compare);
+ }
+ else {
+ // all servers pinged - enable controls
+ g_arenaservers.master.generic.flags &= ~QMF_GRAYED;
+ g_arenaservers.gametype.generic.flags &= ~QMF_GRAYED;
+ g_arenaservers.sortkey.generic.flags &= ~QMF_GRAYED;
+ g_arenaservers.showempty.generic.flags &= ~QMF_GRAYED;
+ g_arenaservers.showfull.generic.flags &= ~QMF_GRAYED;
+ g_arenaservers.list.generic.flags &= ~QMF_GRAYED;
+ g_arenaservers.refresh.generic.flags &= ~QMF_GRAYED;
+ g_arenaservers.go.generic.flags &= ~QMF_GRAYED;
+ g_arenaservers.punkbuster.generic.flags &= ~QMF_GRAYED;
+
+ // update status bar
+ if( g_servertype == AS_GLOBAL || g_servertype == AS_MPLAYER ) {
+ g_arenaservers.statusbar.string = quake3worldMessage;
+ }
+ else {
+ g_arenaservers.statusbar.string = "";
+ }
+
+ }
+ }
+ else {
+ // no servers found
+ if( g_arenaservers.refreshservers ) {
+ strcpy( g_arenaservers.status.string,"Scanning For Servers." );
+ g_arenaservers.statusbar.string = "Press SPACE to stop";
+
+ // disable controls during refresh
+ g_arenaservers.master.generic.flags |= QMF_GRAYED;
+ g_arenaservers.gametype.generic.flags |= QMF_GRAYED;
+ g_arenaservers.sortkey.generic.flags |= QMF_GRAYED;
+ g_arenaservers.showempty.generic.flags |= QMF_GRAYED;
+ g_arenaservers.showfull.generic.flags |= QMF_GRAYED;
+ g_arenaservers.list.generic.flags |= QMF_GRAYED;
+ g_arenaservers.refresh.generic.flags |= QMF_GRAYED;
+ g_arenaservers.go.generic.flags |= QMF_GRAYED;
+ g_arenaservers.punkbuster.generic.flags |= QMF_GRAYED;
+ }
+ else {
+ if( g_arenaservers.numqueriedservers < 0 ) {
+ strcpy(g_arenaservers.status.string,"No Response From Master Server." );
+ }
+ else {
+ strcpy(g_arenaservers.status.string,"No Servers Found." );
+ }
+
+ // update status bar
+ if( g_servertype == AS_GLOBAL || g_servertype == AS_MPLAYER ) {
+ g_arenaservers.statusbar.string = quake3worldMessage;
+ }
+ else {
+ g_arenaservers.statusbar.string = "";
+ }
+
+ // end of refresh - set control state
+ g_arenaservers.master.generic.flags &= ~QMF_GRAYED;
+ g_arenaservers.gametype.generic.flags &= ~QMF_GRAYED;
+ g_arenaservers.sortkey.generic.flags &= ~QMF_GRAYED;
+ g_arenaservers.showempty.generic.flags &= ~QMF_GRAYED;
+ g_arenaservers.showfull.generic.flags &= ~QMF_GRAYED;
+ g_arenaservers.list.generic.flags |= QMF_GRAYED;
+ g_arenaservers.refresh.generic.flags &= ~QMF_GRAYED;
+ g_arenaservers.go.generic.flags |= QMF_GRAYED;
+ g_arenaservers.punkbuster.generic.flags &= ~QMF_GRAYED;
+ }
+
+ // zero out list box
+ g_arenaservers.list.numitems = 0;
+ g_arenaservers.list.curvalue = 0;
+ g_arenaservers.list.top = 0;
+
+ // update picture
+ ArenaServers_UpdatePicture();
+ return;
+ }
+
+ // build list box strings - apply culling filters
+ servernodeptr = g_arenaservers.serverlist;
+ count = *g_arenaservers.numservers;
+ for( i = 0, j = 0; i < count; i++, servernodeptr++ ) {
+ tableptr = &g_arenaservers.table[j];
+ tableptr->servernode = servernodeptr;
+ buff = tableptr->buff;
+
+ // can only cull valid results
+ if( !g_emptyservers && !servernodeptr->numclients ) {
+ continue;
+ }
+
+ if( !g_fullservers && ( servernodeptr->numclients == servernodeptr->maxclients ) ) {
+ continue;
+ }
+
+ switch( g_gametype ) {
+ case GAMES_ALL:
+ break;
+
+ case GAMES_FFA:
+ if( servernodeptr->gametype != GT_FFA ) {
+ continue;
+ }
+ break;
+
+ case GAMES_TEAMPLAY:
+ if( servernodeptr->gametype != GT_TEAM ) {
+ continue;
+ }
+ break;
+
+ case GAMES_TOURNEY:
+ if( servernodeptr->gametype != GT_TOURNAMENT ) {
+ continue;
+ }
+ break;
+
+ case GAMES_CTF:
+ if( servernodeptr->gametype != GT_CTF ) {
+ continue;
+ }
+ break;
+ }
+
+ if( servernodeptr->pingtime < servernodeptr->minPing ) {
+ pingColor = S_COLOR_BLUE;
+ }
+ else if( servernodeptr->maxPing && servernodeptr->pingtime > servernodeptr->maxPing ) {
+ pingColor = S_COLOR_BLUE;
+ }
+ else if( servernodeptr->pingtime < 200 ) {
+ pingColor = S_COLOR_GREEN;
+ }
+ else if( servernodeptr->pingtime < 400 ) {
+ pingColor = S_COLOR_YELLOW;
+ }
+ else {
+ pingColor = S_COLOR_RED;
+ }
+
+ Com_sprintf( buff, MAX_LISTBOXWIDTH, "%-20.20s %-12.12s %2d/%2d %-8.8s %3s %s%3d " S_COLOR_YELLOW "%s",
+ servernodeptr->hostname, servernodeptr->mapname, servernodeptr->numclients,
+ servernodeptr->maxclients, servernodeptr->gamename,
+ netnames[servernodeptr->nettype], pingColor, servernodeptr->pingtime, servernodeptr->bPB ? "Yes" : "No" );
+ j++;
+ }
+
+ g_arenaservers.list.numitems = j;
+ g_arenaservers.list.curvalue = 0;
+ g_arenaservers.list.top = 0;
+
+ // update picture
+ ArenaServers_UpdatePicture();
+}
+
+
+/*
+=================
+ArenaServers_Remove
+=================
+*/
+static void ArenaServers_Remove( void )
+{
+ int i;
+ servernode_t* servernodeptr;
+ table_t* tableptr;
+
+ if (!g_arenaservers.list.numitems)
+ return;
+
+ // remove selected item from display list
+ // items are in scattered order due to sort and cull
+ // perform delete on list box contents, resync all lists
+
+ tableptr = &g_arenaservers.table[g_arenaservers.list.curvalue];
+ servernodeptr = tableptr->servernode;
+
+ // find address in master list
+ for (i=0; i<g_arenaservers.numfavoriteaddresses; i++)
+ if (!Q_stricmp(g_arenaservers.favoriteaddresses[i],servernodeptr->adrstr))
+ break;
+
+ // delete address from master list
+ if (i <= g_arenaservers.numfavoriteaddresses-1)
+ {
+ if (i < g_arenaservers.numfavoriteaddresses-1)
+ {
+ // shift items up
+ memcpy( &g_arenaservers.favoriteaddresses[i], &g_arenaservers.favoriteaddresses[i+1], (g_arenaservers.numfavoriteaddresses - i - 1)*sizeof(MAX_ADDRESSLENGTH));
+ }
+ g_arenaservers.numfavoriteaddresses--;
+ }
+
+ // find address in server list
+ for (i=0; i<g_numfavoriteservers; i++)
+ if (&g_favoriteserverlist[i] == servernodeptr)
+ break;
+
+ // delete address from server list
+ if (i <= g_numfavoriteservers-1)
+ {
+ if (i < g_numfavoriteservers-1)
+ {
+ // shift items up
+ memcpy( &g_favoriteserverlist[i], &g_favoriteserverlist[i+1], (g_numfavoriteservers - i - 1)*sizeof(servernode_t));
+ }
+ g_numfavoriteservers--;
+ }
+
+ g_arenaservers.numqueriedservers = g_arenaservers.numfavoriteaddresses;
+ g_arenaservers.currentping = g_arenaservers.numfavoriteaddresses;
+}
+
+
+/*
+=================
+ArenaServers_Insert
+=================
+*/
+static void ArenaServers_Insert( char* adrstr, char* info, int pingtime )
+{
+ servernode_t* servernodeptr;
+ char* s;
+ int i;
+
+
+ if ((pingtime >= ArenaServers_MaxPing()) && (g_servertype != AS_FAVORITES))
+ {
+ // slow global or local servers do not get entered
+ return;
+ }
+
+ if (*g_arenaservers.numservers >= g_arenaservers.maxservers) {
+ // list full;
+ servernodeptr = g_arenaservers.serverlist+(*g_arenaservers.numservers)-1;
+ } else {
+ // next slot
+ servernodeptr = g_arenaservers.serverlist+(*g_arenaservers.numservers);
+ (*g_arenaservers.numservers)++;
+ }
+
+ Q_strncpyz( servernodeptr->adrstr, adrstr, MAX_ADDRESSLENGTH );
+
+ Q_strncpyz( servernodeptr->hostname, Info_ValueForKey( info, "hostname"), MAX_HOSTNAMELENGTH );
+ Q_CleanStr( servernodeptr->hostname );
+ Q_strupr( servernodeptr->hostname );
+
+ Q_strncpyz( servernodeptr->mapname, Info_ValueForKey( info, "mapname"), MAX_MAPNAMELENGTH );
+ Q_CleanStr( servernodeptr->mapname );
+ Q_strupr( servernodeptr->mapname );
+
+ servernodeptr->numclients = atoi( Info_ValueForKey( info, "clients") );
+ servernodeptr->maxclients = atoi( Info_ValueForKey( info, "sv_maxclients") );
+ servernodeptr->pingtime = pingtime;
+ servernodeptr->minPing = atoi( Info_ValueForKey( info, "minPing") );
+ servernodeptr->maxPing = atoi( Info_ValueForKey( info, "maxPing") );
+ servernodeptr->bPB = atoi( Info_ValueForKey( info, "punkbuster") );
+
+ /*
+ s = Info_ValueForKey( info, "nettype" );
+ for (i=0; ;i++)
+ {
+ if (!netnames[i])
+ {
+ servernodeptr->nettype = 0;
+ break;
+ }
+ else if (!Q_stricmp( netnames[i], s ))
+ {
+ servernodeptr->nettype = i;
+ break;
+ }
+ }
+ */
+ servernodeptr->nettype = atoi(Info_ValueForKey(info, "nettype"));
+
+ s = Info_ValueForKey( info, "game");
+ i = atoi( Info_ValueForKey( info, "gametype") );
+ if( i < 0 ) {
+ i = 0;
+ }
+ else if( i > 11 ) {
+ i = 12;
+ }
+ if( *s ) {
+ servernodeptr->gametype = i;//-1;
+ Q_strncpyz( servernodeptr->gamename, s, sizeof(servernodeptr->gamename) );
+ }
+ else {
+ servernodeptr->gametype = i;
+ Q_strncpyz( servernodeptr->gamename, gamenames[i], sizeof(servernodeptr->gamename) );
+ }
+}
+
+
+/*
+=================
+ArenaServers_InsertFavorites
+
+Insert nonresponsive address book entries into display lists.
+=================
+*/
+void ArenaServers_InsertFavorites( void )
+{
+ int i;
+ int j;
+ char info[MAX_INFO_STRING];
+
+ // resync existing results with new or deleted cvars
+ info[0] = '\0';
+ Info_SetValueForKey( info, "hostname", "No Response" );
+ for (i=0; i<g_arenaservers.numfavoriteaddresses; i++)
+ {
+ // find favorite address in refresh list
+ for (j=0; j<g_numfavoriteservers; j++)
+ if (!Q_stricmp(g_arenaservers.favoriteaddresses[i],g_favoriteserverlist[j].adrstr))
+ break;
+
+ if ( j >= g_numfavoriteservers)
+ {
+ // not in list, add it
+ ArenaServers_Insert( g_arenaservers.favoriteaddresses[i], info, ArenaServers_MaxPing() );
+ }
+ }
+}
+
+
+/*
+=================
+ArenaServers_LoadFavorites
+
+Load cvar address book entries into local lists.
+=================
+*/
+void ArenaServers_LoadFavorites( void )
+{
+ int i;
+ int j;
+ int numtempitems;
+ char emptyinfo[MAX_INFO_STRING];
+ char adrstr[MAX_ADDRESSLENGTH];
+ servernode_t templist[MAX_FAVORITESERVERS];
+ qboolean found;
+
+ found = qfalse;
+ emptyinfo[0] = '\0';
+
+ // copy the old
+ memcpy( templist, g_favoriteserverlist, sizeof(servernode_t)*MAX_FAVORITESERVERS );
+ numtempitems = g_numfavoriteservers;
+
+ // clear the current for sync
+ memset( g_favoriteserverlist, 0, sizeof(servernode_t)*MAX_FAVORITESERVERS );
+ g_numfavoriteservers = 0;
+
+ // resync existing results with new or deleted cvars
+ for (i=0; i<MAX_FAVORITESERVERS; i++)
+ {
+ trap_Cvar_VariableStringBuffer( va("server%d",i+1), adrstr, MAX_ADDRESSLENGTH );
+ if (!adrstr[0])
+ continue;
+
+ // quick sanity check to avoid slow domain name resolving
+ // first character must be numeric
+ if (adrstr[0] < '0' || adrstr[0] > '9')
+ continue;
+
+ // favorite server addresses must be maintained outside refresh list
+ // this mimics local and global netadr's stored in client
+ // these can be fetched to fill ping list
+ strcpy( g_arenaservers.favoriteaddresses[g_numfavoriteservers], adrstr );
+
+ // find this server in the old list
+ for (j=0; j<numtempitems; j++)
+ if (!Q_stricmp( templist[j].adrstr, adrstr ))
+ break;
+
+ if (j < numtempitems)
+ {
+ // found server - add exisiting results
+ memcpy( &g_favoriteserverlist[g_numfavoriteservers], &templist[j], sizeof(servernode_t) );
+ found = qtrue;
+ }
+ else
+ {
+ // add new server
+ Q_strncpyz( g_favoriteserverlist[g_numfavoriteservers].adrstr, adrstr, MAX_ADDRESSLENGTH );
+ g_favoriteserverlist[g_numfavoriteservers].pingtime = ArenaServers_MaxPing();
+ }
+
+ g_numfavoriteservers++;
+ }
+
+ g_arenaservers.numfavoriteaddresses = g_numfavoriteservers;
+
+ if (!found)
+ {
+ // no results were found, reset server list
+ // list will be automatically refreshed when selected
+ g_numfavoriteservers = 0;
+ }
+}
+
+
+/*
+=================
+ArenaServers_StopRefresh
+=================
+*/
+static void ArenaServers_StopRefresh( void )
+{
+ if (!g_arenaservers.refreshservers)
+ // not currently refreshing
+ return;
+
+ g_arenaservers.refreshservers = qfalse;
+
+ if (g_servertype == AS_FAVORITES)
+ {
+ // nonresponsive favorites must be shown
+ ArenaServers_InsertFavorites();
+ }
+
+ // final tally
+ if (g_arenaservers.numqueriedservers >= 0)
+ {
+ g_arenaservers.currentping = *g_arenaservers.numservers;
+ g_arenaservers.numqueriedservers = *g_arenaservers.numservers;
+ }
+
+ // sort
+ qsort( g_arenaservers.serverlist, *g_arenaservers.numservers, sizeof( servernode_t ), ArenaServers_Compare);
+
+ ArenaServers_UpdateMenu();
+}
+
+
+/*
+=================
+ArenaServers_DoRefresh
+=================
+*/
+static void ArenaServers_DoRefresh( void )
+{
+ int i;
+ int j;
+ int time;
+ int maxPing;
+ char adrstr[MAX_ADDRESSLENGTH];
+ char info[MAX_INFO_STRING];
+
+ if (uis.realtime < g_arenaservers.refreshtime)
+ {
+ if (g_servertype != AS_FAVORITES) {
+ if (g_servertype == AS_LOCAL) {
+ if (!trap_LAN_GetServerCount(g_servertype)) {
+ return;
+ }
+ }
+ if (trap_LAN_GetServerCount(g_servertype) < 0) {
+ // still waiting for response
+ return;
+ }
+ }
+ }
+
+ if (uis.realtime < g_arenaservers.nextpingtime)
+ {
+ // wait for time trigger
+ return;
+ }
+
+ // trigger at 10Hz intervals
+ g_arenaservers.nextpingtime = uis.realtime + 10;
+
+ // process ping results
+ maxPing = ArenaServers_MaxPing();
+ for (i=0; i<MAX_PINGREQUESTS; i++)
+ {
+ trap_LAN_GetPing( i, adrstr, MAX_ADDRESSLENGTH, &time );
+ if (!adrstr[0])
+ {
+ // ignore empty or pending pings
+ continue;
+ }
+
+ // find ping result in our local list
+ for (j=0; j<MAX_PINGREQUESTS; j++)
+ if (!Q_stricmp( adrstr, g_arenaservers.pinglist[j].adrstr ))
+ break;
+
+ if (j < MAX_PINGREQUESTS)
+ {
+ // found it
+ if (!time)
+ {
+ time = uis.realtime - g_arenaservers.pinglist[j].start;
+ if (time < maxPing)
+ {
+ // still waiting
+ continue;
+ }
+ }
+
+ if (time > maxPing)
+ {
+ // stale it out
+ info[0] = '\0';
+ time = maxPing;
+ }
+ else
+ {
+ trap_LAN_GetPingInfo( i, info, MAX_INFO_STRING );
+ }
+
+ // insert ping results
+ ArenaServers_Insert( adrstr, info, time );
+
+ // clear this query from internal list
+ g_arenaservers.pinglist[j].adrstr[0] = '\0';
+ }
+
+ // clear this query from external list
+ trap_LAN_ClearPing( i );
+ }
+
+ // get results of servers query
+ // counts can increase as servers respond
+ if (g_servertype == AS_FAVORITES) {
+ g_arenaservers.numqueriedservers = g_arenaservers.numfavoriteaddresses;
+ } else {
+ g_arenaservers.numqueriedservers = trap_LAN_GetServerCount(g_servertype);
+ }
+
+// if (g_arenaservers.numqueriedservers > g_arenaservers.maxservers)
+// g_arenaservers.numqueriedservers = g_arenaservers.maxservers;
+
+ // send ping requests in reasonable bursts
+ // iterate ping through all found servers
+ for (i=0; i<MAX_PINGREQUESTS && g_arenaservers.currentping < g_arenaservers.numqueriedservers; i++)
+ {
+ if (trap_LAN_GetPingQueueCount() >= MAX_PINGREQUESTS)
+ {
+ // ping queue is full
+ break;
+ }
+
+ // find empty slot
+ for (j=0; j<MAX_PINGREQUESTS; j++)
+ if (!g_arenaservers.pinglist[j].adrstr[0])
+ break;
+
+ if (j >= MAX_PINGREQUESTS)
+ // no empty slots available yet - wait for timeout
+ break;
+
+ // get an address to ping
+
+ if (g_servertype == AS_FAVORITES) {
+ strcpy( adrstr, g_arenaservers.favoriteaddresses[g_arenaservers.currentping] );
+ } else {
+ trap_LAN_GetServerAddressString(g_servertype, g_arenaservers.currentping, adrstr, MAX_ADDRESSLENGTH );
+ }
+
+ strcpy( g_arenaservers.pinglist[j].adrstr, adrstr );
+ g_arenaservers.pinglist[j].start = uis.realtime;
+
+ trap_Cmd_ExecuteText( EXEC_NOW, va( "ping %s\n", adrstr ) );
+
+ // advance to next server
+ g_arenaservers.currentping++;
+ }
+
+ if (!trap_LAN_GetPingQueueCount())
+ {
+ // all pings completed
+ ArenaServers_StopRefresh();
+ return;
+ }
+
+ // update the user interface with ping status
+ ArenaServers_UpdateMenu();
+}
+
+
+/*
+=================
+ArenaServers_StartRefresh
+=================
+*/
+static void ArenaServers_StartRefresh( void )
+{
+ int i;
+ char myargs[32], protocol[32];
+
+ memset( g_arenaservers.serverlist, 0, g_arenaservers.maxservers*sizeof(table_t) );
+
+ for (i=0; i<MAX_PINGREQUESTS; i++)
+ {
+ g_arenaservers.pinglist[i].adrstr[0] = '\0';
+ trap_LAN_ClearPing( i );
+ }
+
+ g_arenaservers.refreshservers = qtrue;
+ g_arenaservers.currentping = 0;
+ g_arenaservers.nextpingtime = 0;
+ *g_arenaservers.numservers = 0;
+ g_arenaservers.numqueriedservers = 0;
+
+ // allow max 5 seconds for responses
+ g_arenaservers.refreshtime = uis.realtime + 5000;
+
+ // place menu in zeroed state
+ ArenaServers_UpdateMenu();
+
+ if( g_servertype == AS_LOCAL ) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, "localservers\n" );
+ return;
+ }
+
+ if( g_servertype == AS_GLOBAL || g_servertype == AS_MPLAYER ) {
+ if( g_servertype == AS_GLOBAL ) {
+ i = 0;
+ }
+ else {
+ i = 1;
+ }
+
+ switch( g_arenaservers.gametype.curvalue ) {
+ default:
+ case GAMES_ALL:
+ myargs[0] = 0;
+ break;
+
+ case GAMES_FFA:
+ strcpy( myargs, " ffa" );
+ break;
+
+ case GAMES_TEAMPLAY:
+ strcpy( myargs, " team" );
+ break;
+
+ case GAMES_TOURNEY:
+ strcpy( myargs, " tourney" );
+ break;
+
+ case GAMES_CTF:
+ strcpy( myargs, " ctf" );
+ break;
+ }
+
+
+ if (g_emptyservers) {
+ strcat(myargs, " empty");
+ }
+
+ if (g_fullservers) {
+ strcat(myargs, " full");
+ }
+
+ protocol[0] = '\0';
+ trap_Cvar_VariableStringBuffer( "debug_protocol", protocol, sizeof(protocol) );
+ if (strlen(protocol)) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, va( "globalservers %d %s%s\n", i, protocol, myargs ));
+ }
+ else {
+ trap_Cmd_ExecuteText( EXEC_APPEND, va( "globalservers %d %d%s\n", i, (int)trap_Cvar_VariableValue( "protocol" ), myargs ) );
+ }
+ }
+}
+
+
+/*
+=================
+ArenaServers_SaveChanges
+=================
+*/
+void ArenaServers_SaveChanges( void )
+{
+ int i;
+
+ for (i=0; i<g_arenaservers.numfavoriteaddresses; i++)
+ trap_Cvar_Set( va("server%d",i+1), g_arenaservers.favoriteaddresses[i] );
+
+ for (; i<MAX_FAVORITESERVERS; i++)
+ trap_Cvar_Set( va("server%d",i+1), "" );
+}
+
+
+/*
+=================
+ArenaServers_Sort
+=================
+*/
+void ArenaServers_Sort( int type ) {
+ if( g_sortkey == type ) {
+ return;
+ }
+
+ g_sortkey = type;
+ qsort( g_arenaservers.serverlist, *g_arenaservers.numservers, sizeof( servernode_t ), ArenaServers_Compare);
+}
+
+
+/*
+=================
+ArenaServers_SetType
+=================
+*/
+void ArenaServers_SetType( int type )
+{
+ if (g_servertype == type)
+ return;
+
+ g_servertype = type;
+
+ switch( type ) {
+ default:
+ case AS_LOCAL:
+ g_arenaservers.remove.generic.flags |= (QMF_INACTIVE|QMF_HIDDEN);
+ g_arenaservers.serverlist = g_localserverlist;
+ g_arenaservers.numservers = &g_numlocalservers;
+ g_arenaservers.maxservers = MAX_LOCALSERVERS;
+ break;
+
+ case AS_GLOBAL:
+ g_arenaservers.remove.generic.flags |= (QMF_INACTIVE|QMF_HIDDEN);
+ g_arenaservers.serverlist = g_globalserverlist;
+ g_arenaservers.numservers = &g_numglobalservers;
+ g_arenaservers.maxservers = MAX_GLOBALSERVERS;
+ break;
+
+ case AS_FAVORITES:
+ g_arenaservers.remove.generic.flags &= ~(QMF_INACTIVE|QMF_HIDDEN);
+ g_arenaservers.serverlist = g_favoriteserverlist;
+ g_arenaservers.numservers = &g_numfavoriteservers;
+ g_arenaservers.maxservers = MAX_FAVORITESERVERS;
+ break;
+
+ case AS_MPLAYER:
+ g_arenaservers.remove.generic.flags |= (QMF_INACTIVE|QMF_HIDDEN);
+ g_arenaservers.serverlist = g_mplayerserverlist;
+ g_arenaservers.numservers = &g_nummplayerservers;
+ g_arenaservers.maxservers = MAX_GLOBALSERVERS;
+ break;
+
+ }
+
+ if( !*g_arenaservers.numservers ) {
+ ArenaServers_StartRefresh();
+ }
+ else {
+ // avoid slow operation, use existing results
+ g_arenaservers.currentping = *g_arenaservers.numservers;
+ g_arenaservers.numqueriedservers = *g_arenaservers.numservers;
+ ArenaServers_UpdateMenu();
+ }
+ strcpy(g_arenaservers.status.string,"hit refresh to update");
+}
+
+/*
+=================
+PunkBuster_Confirm
+=================
+*/
+static void Punkbuster_ConfirmEnable( qboolean result ) {
+ if (result)
+ {
+ trap_SetPbClStatus(1);
+ }
+ g_arenaservers.punkbuster.curvalue = Com_Clamp( 0, 1, trap_Cvar_VariableValue( "cl_punkbuster" ) );
+}
+
+static void Punkbuster_ConfirmDisable( qboolean result ) {
+ if (result)
+ {
+ trap_SetPbClStatus(0);
+ UI_Message( punkbuster_msg );
+ }
+ g_arenaservers.punkbuster.curvalue = Com_Clamp( 0, 1, trap_Cvar_VariableValue( "cl_punkbuster" ) );
+}
+
+/*
+=================
+ArenaServers_Event
+=================
+*/
+static void ArenaServers_Event( void* ptr, int event ) {
+ int id;
+ int value;
+
+ id = ((menucommon_s*)ptr)->id;
+
+ if( event != QM_ACTIVATED && id != ID_LIST ) {
+ return;
+ }
+
+ switch( id ) {
+ case ID_MASTER:
+ value = g_arenaservers.master.curvalue;
+ if (value >= 1)
+ {
+ value++;
+ }
+ trap_Cvar_SetValue( "ui_browserMaster", value );
+ ArenaServers_SetType( value );
+ break;
+
+ case ID_GAMETYPE:
+ trap_Cvar_SetValue( "ui_browserGameType", g_arenaservers.gametype.curvalue );
+ g_gametype = g_arenaservers.gametype.curvalue;
+ ArenaServers_UpdateMenu();
+ break;
+
+ case ID_SORTKEY:
+ trap_Cvar_SetValue( "ui_browserSortKey", g_arenaservers.sortkey.curvalue );
+ ArenaServers_Sort( g_arenaservers.sortkey.curvalue );
+ ArenaServers_UpdateMenu();
+ break;
+
+ case ID_SHOW_FULL:
+ trap_Cvar_SetValue( "ui_browserShowFull", g_arenaservers.showfull.curvalue );
+ g_fullservers = g_arenaservers.showfull.curvalue;
+ ArenaServers_UpdateMenu();
+ break;
+
+ case ID_SHOW_EMPTY:
+ trap_Cvar_SetValue( "ui_browserShowEmpty", g_arenaservers.showempty.curvalue );
+ g_emptyservers = g_arenaservers.showempty.curvalue;
+ ArenaServers_UpdateMenu();
+ break;
+
+ case ID_LIST:
+ if( event == QM_GOTFOCUS ) {
+ ArenaServers_UpdatePicture();
+ }
+ break;
+
+ case ID_SCROLL_UP:
+ ScrollList_Key( &g_arenaservers.list, K_UPARROW );
+ break;
+
+ case ID_SCROLL_DOWN:
+ ScrollList_Key( &g_arenaservers.list, K_DOWNARROW );
+ break;
+
+ case ID_BACK:
+ ArenaServers_StopRefresh();
+ ArenaServers_SaveChanges();
+ UI_PopMenu();
+ break;
+
+ case ID_REFRESH:
+ ArenaServers_StartRefresh();
+ break;
+
+ case ID_SPECIFY:
+ UI_SpecifyServerMenu();
+ break;
+
+ case ID_CREATE:
+ UI_StartServerMenu( qtrue );
+ break;
+
+ case ID_CONNECT:
+ ArenaServers_Go();
+ break;
+
+ case ID_REMOVE:
+ ArenaServers_Remove();
+ ArenaServers_UpdateMenu();
+ break;
+
+ case ID_PUNKBUSTER:
+ if (g_arenaservers.punkbuster.curvalue)
+ {
+ UI_ConfirmMenu_Style( "Enable Punkbuster?", UI_CENTER|UI_INVERSE|UI_SMALLFONT, (voidfunc_f)NULL, Punkbuster_ConfirmEnable );
+ }
+ else
+ {
+ UI_ConfirmMenu_Style( "Disable Punkbuster?", UI_CENTER|UI_INVERSE|UI_SMALLFONT, (voidfunc_f)NULL, Punkbuster_ConfirmDisable );
+ }
+ break;
+ }
+}
+
+
+/*
+=================
+ArenaServers_MenuDraw
+=================
+*/
+static void ArenaServers_MenuDraw( void )
+{
+ if (g_arenaservers.refreshservers)
+ ArenaServers_DoRefresh();
+
+ Menu_Draw( &g_arenaservers.menu );
+}
+
+
+/*
+=================
+ArenaServers_MenuKey
+=================
+*/
+static sfxHandle_t ArenaServers_MenuKey( int key ) {
+ if( key == K_SPACE && g_arenaservers.refreshservers ) {
+ ArenaServers_StopRefresh();
+ return menu_move_sound;
+ }
+
+ if( ( key == K_DEL || key == K_KP_DEL ) && ( g_servertype == AS_FAVORITES ) &&
+ ( Menu_ItemAtCursor( &g_arenaservers.menu) == &g_arenaservers.list ) ) {
+ ArenaServers_Remove();
+ ArenaServers_UpdateMenu();
+ return menu_move_sound;
+ }
+
+ if( key == K_MOUSE2 || key == K_ESCAPE ) {
+ ArenaServers_StopRefresh();
+ ArenaServers_SaveChanges();
+ }
+
+
+ return Menu_DefaultKey( &g_arenaservers.menu, key );
+}
+
+
+/*
+=================
+ArenaServers_MenuInit
+=================
+*/
+static void ArenaServers_MenuInit( void ) {
+ int i;
+ int type;
+ int y;
+ int value;
+ static char statusbuffer[MAX_STATUSLENGTH];
+
+ // zero set all our globals
+ memset( &g_arenaservers, 0 ,sizeof(arenaservers_t) );
+
+ ArenaServers_Cache();
+
+ g_arenaservers.menu.fullscreen = qtrue;
+ g_arenaservers.menu.wrapAround = qtrue;
+ g_arenaservers.menu.draw = ArenaServers_MenuDraw;
+ g_arenaservers.menu.key = ArenaServers_MenuKey;
+
+ g_arenaservers.banner.generic.type = MTYPE_BTEXT;
+ g_arenaservers.banner.generic.flags = QMF_CENTER_JUSTIFY;
+ g_arenaservers.banner.generic.x = 320;
+ g_arenaservers.banner.generic.y = 16;
+ g_arenaservers.banner.string = "ARENA SERVERS";
+ g_arenaservers.banner.style = UI_CENTER;
+ g_arenaservers.banner.color = color_white;
+
+ y = 80;
+ g_arenaservers.master.generic.type = MTYPE_SPINCONTROL;
+ g_arenaservers.master.generic.name = "Servers:";
+ g_arenaservers.master.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ g_arenaservers.master.generic.callback = ArenaServers_Event;
+ g_arenaservers.master.generic.id = ID_MASTER;
+ g_arenaservers.master.generic.x = 320;
+ g_arenaservers.master.generic.y = y;
+ g_arenaservers.master.itemnames = master_items;
+
+ y += SMALLCHAR_HEIGHT;
+ g_arenaservers.gametype.generic.type = MTYPE_SPINCONTROL;
+ g_arenaservers.gametype.generic.name = "Game Type:";
+ g_arenaservers.gametype.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ g_arenaservers.gametype.generic.callback = ArenaServers_Event;
+ g_arenaservers.gametype.generic.id = ID_GAMETYPE;
+ g_arenaservers.gametype.generic.x = 320;
+ g_arenaservers.gametype.generic.y = y;
+ g_arenaservers.gametype.itemnames = servertype_items;
+
+ y += SMALLCHAR_HEIGHT;
+ g_arenaservers.sortkey.generic.type = MTYPE_SPINCONTROL;
+ g_arenaservers.sortkey.generic.name = "Sort By:";
+ g_arenaservers.sortkey.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ g_arenaservers.sortkey.generic.callback = ArenaServers_Event;
+ g_arenaservers.sortkey.generic.id = ID_SORTKEY;
+ g_arenaservers.sortkey.generic.x = 320;
+ g_arenaservers.sortkey.generic.y = y;
+ g_arenaservers.sortkey.itemnames = sortkey_items;
+
+ y += SMALLCHAR_HEIGHT;
+ g_arenaservers.showfull.generic.type = MTYPE_RADIOBUTTON;
+ g_arenaservers.showfull.generic.name = "Show Full:";
+ g_arenaservers.showfull.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ g_arenaservers.showfull.generic.callback = ArenaServers_Event;
+ g_arenaservers.showfull.generic.id = ID_SHOW_FULL;
+ g_arenaservers.showfull.generic.x = 320;
+ g_arenaservers.showfull.generic.y = y;
+
+ y += SMALLCHAR_HEIGHT;
+ g_arenaservers.showempty.generic.type = MTYPE_RADIOBUTTON;
+ g_arenaservers.showempty.generic.name = "Show Empty:";
+ g_arenaservers.showempty.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ g_arenaservers.showempty.generic.callback = ArenaServers_Event;
+ g_arenaservers.showempty.generic.id = ID_SHOW_EMPTY;
+ g_arenaservers.showempty.generic.x = 320;
+ g_arenaservers.showempty.generic.y = y;
+
+ y += 3 * SMALLCHAR_HEIGHT;
+ g_arenaservers.list.generic.type = MTYPE_SCROLLLIST;
+ g_arenaservers.list.generic.flags = QMF_HIGHLIGHT_IF_FOCUS;
+ g_arenaservers.list.generic.id = ID_LIST;
+ g_arenaservers.list.generic.callback = ArenaServers_Event;
+ g_arenaservers.list.generic.x = 72;
+ g_arenaservers.list.generic.y = y;
+ g_arenaservers.list.width = MAX_LISTBOXWIDTH;
+ g_arenaservers.list.height = 11;
+ g_arenaservers.list.itemnames = (const char **)g_arenaservers.items;
+ for( i = 0; i < MAX_LISTBOXITEMS; i++ ) {
+ g_arenaservers.items[i] = g_arenaservers.table[i].buff;
+ }
+
+ g_arenaservers.mappic.generic.type = MTYPE_BITMAP;
+ g_arenaservers.mappic.generic.flags = QMF_LEFT_JUSTIFY|QMF_INACTIVE;
+ g_arenaservers.mappic.generic.x = 72;
+ g_arenaservers.mappic.generic.y = 80;
+ g_arenaservers.mappic.width = 128;
+ g_arenaservers.mappic.height = 96;
+ g_arenaservers.mappic.errorpic = ART_UNKNOWNMAP;
+
+ g_arenaservers.arrows.generic.type = MTYPE_BITMAP;
+ g_arenaservers.arrows.generic.name = ART_ARROWS0;
+ g_arenaservers.arrows.generic.flags = QMF_LEFT_JUSTIFY|QMF_INACTIVE;
+ g_arenaservers.arrows.generic.callback = ArenaServers_Event;
+ g_arenaservers.arrows.generic.x = 512+48;
+ g_arenaservers.arrows.generic.y = 240-64+16;
+ g_arenaservers.arrows.width = 64;
+ g_arenaservers.arrows.height = 128;
+
+ g_arenaservers.up.generic.type = MTYPE_BITMAP;
+ g_arenaservers.up.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_MOUSEONLY;
+ g_arenaservers.up.generic.callback = ArenaServers_Event;
+ g_arenaservers.up.generic.id = ID_SCROLL_UP;
+ g_arenaservers.up.generic.x = 512+48;
+ g_arenaservers.up.generic.y = 240-64+16;
+ g_arenaservers.up.width = 64;
+ g_arenaservers.up.height = 64;
+ g_arenaservers.up.focuspic = ART_ARROWS_UP;
+
+ g_arenaservers.down.generic.type = MTYPE_BITMAP;
+ g_arenaservers.down.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_MOUSEONLY;
+ g_arenaservers.down.generic.callback = ArenaServers_Event;
+ g_arenaservers.down.generic.id = ID_SCROLL_DOWN;
+ g_arenaservers.down.generic.x = 512+48;
+ g_arenaservers.down.generic.y = 240+16;
+ g_arenaservers.down.width = 64;
+ g_arenaservers.down.height = 64;
+ g_arenaservers.down.focuspic = ART_ARROWS_DOWN;
+
+ y = 376;
+ g_arenaservers.status.generic.type = MTYPE_TEXT;
+ g_arenaservers.status.generic.x = 320;
+ g_arenaservers.status.generic.y = y;
+ g_arenaservers.status.string = statusbuffer;
+ g_arenaservers.status.style = UI_CENTER|UI_SMALLFONT;
+ g_arenaservers.status.color = menu_text_color;
+
+ y += SMALLCHAR_HEIGHT;
+ g_arenaservers.statusbar.generic.type = MTYPE_TEXT;
+ g_arenaservers.statusbar.generic.x = 320;
+ g_arenaservers.statusbar.generic.y = y;
+ g_arenaservers.statusbar.string = "";
+ g_arenaservers.statusbar.style = UI_CENTER|UI_SMALLFONT;
+ g_arenaservers.statusbar.color = text_color_normal;
+
+ g_arenaservers.remove.generic.type = MTYPE_BITMAP;
+ g_arenaservers.remove.generic.name = ART_REMOVE0;
+ g_arenaservers.remove.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ g_arenaservers.remove.generic.callback = ArenaServers_Event;
+ g_arenaservers.remove.generic.id = ID_REMOVE;
+ g_arenaservers.remove.generic.x = 450;
+ g_arenaservers.remove.generic.y = 86;
+ g_arenaservers.remove.width = 96;
+ g_arenaservers.remove.height = 48;
+ g_arenaservers.remove.focuspic = ART_REMOVE1;
+
+ g_arenaservers.back.generic.type = MTYPE_BITMAP;
+ g_arenaservers.back.generic.name = ART_BACK0;
+ g_arenaservers.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ g_arenaservers.back.generic.callback = ArenaServers_Event;
+ g_arenaservers.back.generic.id = ID_BACK;
+ g_arenaservers.back.generic.x = 0;
+ g_arenaservers.back.generic.y = 480-64;
+ g_arenaservers.back.width = 128;
+ g_arenaservers.back.height = 64;
+ g_arenaservers.back.focuspic = ART_BACK1;
+
+ g_arenaservers.specify.generic.type = MTYPE_BITMAP;
+ g_arenaservers.specify.generic.name = ART_SPECIFY0;
+ g_arenaservers.specify.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ g_arenaservers.specify.generic.callback = ArenaServers_Event;
+ g_arenaservers.specify.generic.id = ID_SPECIFY;
+ g_arenaservers.specify.generic.x = 128;
+ g_arenaservers.specify.generic.y = 480-64;
+ g_arenaservers.specify.width = 128;
+ g_arenaservers.specify.height = 64;
+ g_arenaservers.specify.focuspic = ART_SPECIFY1;
+
+ g_arenaservers.refresh.generic.type = MTYPE_BITMAP;
+ g_arenaservers.refresh.generic.name = ART_REFRESH0;
+ g_arenaservers.refresh.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ g_arenaservers.refresh.generic.callback = ArenaServers_Event;
+ g_arenaservers.refresh.generic.id = ID_REFRESH;
+ g_arenaservers.refresh.generic.x = 256;
+ g_arenaservers.refresh.generic.y = 480-64;
+ g_arenaservers.refresh.width = 128;
+ g_arenaservers.refresh.height = 64;
+ g_arenaservers.refresh.focuspic = ART_REFRESH1;
+
+ g_arenaservers.create.generic.type = MTYPE_BITMAP;
+ g_arenaservers.create.generic.name = ART_CREATE0;
+ g_arenaservers.create.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ g_arenaservers.create.generic.callback = ArenaServers_Event;
+ g_arenaservers.create.generic.id = ID_CREATE;
+ g_arenaservers.create.generic.x = 384;
+ g_arenaservers.create.generic.y = 480-64;
+ g_arenaservers.create.width = 128;
+ g_arenaservers.create.height = 64;
+ g_arenaservers.create.focuspic = ART_CREATE1;
+
+ g_arenaservers.go.generic.type = MTYPE_BITMAP;
+ g_arenaservers.go.generic.name = ART_CONNECT0;
+ g_arenaservers.go.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ g_arenaservers.go.generic.callback = ArenaServers_Event;
+ g_arenaservers.go.generic.id = ID_CONNECT;
+ g_arenaservers.go.generic.x = 640;
+ g_arenaservers.go.generic.y = 480-64;
+ g_arenaservers.go.width = 128;
+ g_arenaservers.go.height = 64;
+ g_arenaservers.go.focuspic = ART_CONNECT1;
+
+ g_arenaservers.punkbuster.generic.type = MTYPE_SPINCONTROL;
+ g_arenaservers.punkbuster.generic.name = "Punkbuster:";
+ g_arenaservers.punkbuster.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ g_arenaservers.punkbuster.generic.callback = ArenaServers_Event;
+ g_arenaservers.punkbuster.generic.id = ID_PUNKBUSTER;
+ g_arenaservers.punkbuster.generic.x = 480+32;
+ g_arenaservers.punkbuster.generic.y = 144;
+ g_arenaservers.punkbuster.itemnames = punkbuster_items;
+
+ g_arenaservers.pblogo.generic.type = MTYPE_BITMAP;
+ g_arenaservers.pblogo.generic.name = ART_PUNKBUSTER;
+ g_arenaservers.pblogo.generic.flags = QMF_LEFT_JUSTIFY|QMF_INACTIVE;
+ g_arenaservers.pblogo.generic.x = 526;
+ g_arenaservers.pblogo.generic.y = 176;
+ g_arenaservers.pblogo.width = 32;
+ g_arenaservers.pblogo.height = 16;
+ g_arenaservers.pblogo.errorpic = ART_UNKNOWNMAP;
+
+ Menu_AddItem( &g_arenaservers.menu, (void*) &g_arenaservers.banner );
+
+ Menu_AddItem( &g_arenaservers.menu, (void*) &g_arenaservers.master );
+ Menu_AddItem( &g_arenaservers.menu, (void*) &g_arenaservers.gametype );
+ Menu_AddItem( &g_arenaservers.menu, (void*) &g_arenaservers.sortkey );
+ Menu_AddItem( &g_arenaservers.menu, (void*) &g_arenaservers.showfull);
+ Menu_AddItem( &g_arenaservers.menu, (void*) &g_arenaservers.showempty );
+
+ Menu_AddItem( &g_arenaservers.menu, (void*) &g_arenaservers.mappic );
+ Menu_AddItem( &g_arenaservers.menu, (void*) &g_arenaservers.list );
+ Menu_AddItem( &g_arenaservers.menu, (void*) &g_arenaservers.status );
+ Menu_AddItem( &g_arenaservers.menu, (void*) &g_arenaservers.statusbar );
+ Menu_AddItem( &g_arenaservers.menu, (void*) &g_arenaservers.arrows );
+ Menu_AddItem( &g_arenaservers.menu, (void*) &g_arenaservers.up );
+ Menu_AddItem( &g_arenaservers.menu, (void*) &g_arenaservers.down );
+
+ Menu_AddItem( &g_arenaservers.menu, (void*) &g_arenaservers.remove );
+ Menu_AddItem( &g_arenaservers.menu, (void*) &g_arenaservers.back );
+ Menu_AddItem( &g_arenaservers.menu, (void*) &g_arenaservers.specify );
+ Menu_AddItem( &g_arenaservers.menu, (void*) &g_arenaservers.refresh );
+ Menu_AddItem( &g_arenaservers.menu, (void*) &g_arenaservers.create );
+ Menu_AddItem( &g_arenaservers.menu, (void*) &g_arenaservers.go );
+
+ Menu_AddItem( &g_arenaservers.menu, (void*) &g_arenaservers.punkbuster );
+ Menu_AddItem( &g_arenaservers.menu, (void*) &g_arenaservers.pblogo );
+
+ ArenaServers_LoadFavorites();
+
+ g_servertype = Com_Clamp( 0, 3, ui_browserMaster.integer );
+ // hack to get rid of MPlayer stuff
+ value = g_servertype;
+ if (value >= 1)
+ value--;
+ g_arenaservers.master.curvalue = value;
+
+ g_gametype = Com_Clamp( 0, 4, ui_browserGameType.integer );
+ g_arenaservers.gametype.curvalue = g_gametype;
+
+ g_sortkey = Com_Clamp( 0, 4, ui_browserSortKey.integer );
+ g_arenaservers.sortkey.curvalue = g_sortkey;
+
+ g_fullservers = Com_Clamp( 0, 1, ui_browserShowFull.integer );
+ g_arenaservers.showfull.curvalue = g_fullservers;
+
+ g_emptyservers = Com_Clamp( 0, 1, ui_browserShowEmpty.integer );
+ g_arenaservers.showempty.curvalue = g_emptyservers;
+
+ g_arenaservers.punkbuster.curvalue = Com_Clamp( 0, 1, trap_Cvar_VariableValue( "cl_punkbuster" ) );
+
+ // force to initial state and refresh
+ type = g_servertype;
+ g_servertype = -1;
+ ArenaServers_SetType( type );
+
+ trap_Cvar_Register(NULL, "debug_protocol", "", 0 );
+}
+
+
+/*
+=================
+ArenaServers_Cache
+=================
+*/
+void ArenaServers_Cache( void ) {
+ trap_R_RegisterShaderNoMip( ART_BACK0 );
+ trap_R_RegisterShaderNoMip( ART_BACK1 );
+ trap_R_RegisterShaderNoMip( ART_CREATE0 );
+ trap_R_RegisterShaderNoMip( ART_CREATE1 );
+ trap_R_RegisterShaderNoMip( ART_SPECIFY0 );
+ trap_R_RegisterShaderNoMip( ART_SPECIFY1 );
+ trap_R_RegisterShaderNoMip( ART_REFRESH0 );
+ trap_R_RegisterShaderNoMip( ART_REFRESH1 );
+ trap_R_RegisterShaderNoMip( ART_CONNECT0 );
+ trap_R_RegisterShaderNoMip( ART_CONNECT1 );
+ trap_R_RegisterShaderNoMip( ART_ARROWS0 );
+ trap_R_RegisterShaderNoMip( ART_ARROWS_UP );
+ trap_R_RegisterShaderNoMip( ART_ARROWS_DOWN );
+ trap_R_RegisterShaderNoMip( ART_UNKNOWNMAP );
+ trap_R_RegisterShaderNoMip( ART_PUNKBUSTER );
+}
+
+
+/*
+=================
+UI_ArenaServersMenu
+=================
+*/
+void UI_ArenaServersMenu( void ) {
+ ArenaServers_MenuInit();
+ UI_PushMenu( &g_arenaservers.menu );
+}
diff --git a/code/q3_ui/ui_setup.c b/code/q3_ui/ui_setup.c
new file mode 100755
index 0000000..25e01d5
--- /dev/null
+++ b/code/q3_ui/ui_setup.c
@@ -0,0 +1,327 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*
+=======================================================================
+
+SETUP MENU
+
+=======================================================================
+*/
+
+
+#include "ui_local.h"
+
+
+#define SETUP_MENU_VERTICAL_SPACING 34
+
+#define ART_BACK0 "menu/art/back_0"
+#define ART_BACK1 "menu/art/back_1"
+#define ART_FRAMEL "menu/art/frame2_l"
+#define ART_FRAMER "menu/art/frame1_r"
+
+#define ID_CUSTOMIZEPLAYER 10
+#define ID_CUSTOMIZECONTROLS 11
+#define ID_SYSTEMCONFIG 12
+#define ID_GAME 13
+#define ID_CDKEY 14
+#define ID_LOAD 15
+#define ID_SAVE 16
+#define ID_DEFAULTS 17
+#define ID_BACK 18
+
+
+typedef struct {
+ menuframework_s menu;
+
+ menutext_s banner;
+ menubitmap_s framel;
+ menubitmap_s framer;
+ menutext_s setupplayer;
+ menutext_s setupcontrols;
+ menutext_s setupsystem;
+ menutext_s game;
+ menutext_s cdkey;
+// menutext_s load;
+// menutext_s save;
+ menutext_s defaults;
+ menubitmap_s back;
+} setupMenuInfo_t;
+
+static setupMenuInfo_t setupMenuInfo;
+
+
+/*
+=================
+Setup_ResetDefaults_Action
+=================
+*/
+static void Setup_ResetDefaults_Action( qboolean result ) {
+ if( !result ) {
+ return;
+ }
+ trap_Cmd_ExecuteText( EXEC_APPEND, "exec default.cfg\n");
+ trap_Cmd_ExecuteText( EXEC_APPEND, "cvar_restart\n");
+ trap_Cmd_ExecuteText( EXEC_APPEND, "vid_restart\n" );
+}
+
+
+/*
+=================
+Setup_ResetDefaults_Draw
+=================
+*/
+static void Setup_ResetDefaults_Draw( void ) {
+ UI_DrawProportionalString( SCREEN_WIDTH/2, 356 + PROP_HEIGHT * 0, "WARNING: This will reset *ALL*", UI_CENTER|UI_SMALLFONT, color_yellow );
+ UI_DrawProportionalString( SCREEN_WIDTH/2, 356 + PROP_HEIGHT * 1, "options to their default values.", UI_CENTER|UI_SMALLFONT, color_yellow );
+}
+
+
+/*
+===============
+UI_SetupMenu_Event
+===============
+*/
+static void UI_SetupMenu_Event( void *ptr, int event ) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+
+ switch( ((menucommon_s*)ptr)->id ) {
+ case ID_CUSTOMIZEPLAYER:
+ UI_PlayerSettingsMenu();
+ break;
+
+ case ID_CUSTOMIZECONTROLS:
+ UI_ControlsMenu();
+ break;
+
+ case ID_SYSTEMCONFIG:
+ UI_GraphicsOptionsMenu();
+ break;
+
+ case ID_GAME:
+ UI_PreferencesMenu();
+ break;
+
+ case ID_CDKEY:
+ UI_CDKeyMenu();
+ break;
+
+// case ID_LOAD:
+// UI_LoadConfigMenu();
+// break;
+
+// case ID_SAVE:
+// UI_SaveConfigMenu();
+// break;
+
+ case ID_DEFAULTS:
+ UI_ConfirmMenu( "SET TO DEFAULTS?", Setup_ResetDefaults_Draw, Setup_ResetDefaults_Action );
+ break;
+
+ case ID_BACK:
+ UI_PopMenu();
+ break;
+ }
+}
+
+
+/*
+===============
+UI_SetupMenu_Init
+===============
+*/
+static void UI_SetupMenu_Init( void ) {
+ int y;
+
+ UI_SetupMenu_Cache();
+
+ memset( &setupMenuInfo, 0, sizeof(setupMenuInfo) );
+ setupMenuInfo.menu.wrapAround = qtrue;
+ setupMenuInfo.menu.fullscreen = qtrue;
+
+ setupMenuInfo.banner.generic.type = MTYPE_BTEXT;
+ setupMenuInfo.banner.generic.x = 320;
+ setupMenuInfo.banner.generic.y = 16;
+ setupMenuInfo.banner.string = "SETUP";
+ setupMenuInfo.banner.color = color_white;
+ setupMenuInfo.banner.style = UI_CENTER;
+
+ setupMenuInfo.framel.generic.type = MTYPE_BITMAP;
+ setupMenuInfo.framel.generic.name = ART_FRAMEL;
+ setupMenuInfo.framel.generic.flags = QMF_INACTIVE;
+ setupMenuInfo.framel.generic.x = 0;
+ setupMenuInfo.framel.generic.y = 78;
+ setupMenuInfo.framel.width = 256;
+ setupMenuInfo.framel.height = 329;
+
+ setupMenuInfo.framer.generic.type = MTYPE_BITMAP;
+ setupMenuInfo.framer.generic.name = ART_FRAMER;
+ setupMenuInfo.framer.generic.flags = QMF_INACTIVE;
+ setupMenuInfo.framer.generic.x = 376;
+ setupMenuInfo.framer.generic.y = 76;
+ setupMenuInfo.framer.width = 256;
+ setupMenuInfo.framer.height = 334;
+
+ y = 134;
+ setupMenuInfo.setupplayer.generic.type = MTYPE_PTEXT;
+ setupMenuInfo.setupplayer.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ setupMenuInfo.setupplayer.generic.x = 320;
+ setupMenuInfo.setupplayer.generic.y = y;
+ setupMenuInfo.setupplayer.generic.id = ID_CUSTOMIZEPLAYER;
+ setupMenuInfo.setupplayer.generic.callback = UI_SetupMenu_Event;
+ setupMenuInfo.setupplayer.string = "PLAYER";
+ setupMenuInfo.setupplayer.color = color_red;
+ setupMenuInfo.setupplayer.style = UI_CENTER;
+
+ y += SETUP_MENU_VERTICAL_SPACING;
+ setupMenuInfo.setupcontrols.generic.type = MTYPE_PTEXT;
+ setupMenuInfo.setupcontrols.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ setupMenuInfo.setupcontrols.generic.x = 320;
+ setupMenuInfo.setupcontrols.generic.y = y;
+ setupMenuInfo.setupcontrols.generic.id = ID_CUSTOMIZECONTROLS;
+ setupMenuInfo.setupcontrols.generic.callback = UI_SetupMenu_Event;
+ setupMenuInfo.setupcontrols.string = "CONTROLS";
+ setupMenuInfo.setupcontrols.color = color_red;
+ setupMenuInfo.setupcontrols.style = UI_CENTER;
+
+ y += SETUP_MENU_VERTICAL_SPACING;
+ setupMenuInfo.setupsystem.generic.type = MTYPE_PTEXT;
+ setupMenuInfo.setupsystem.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ setupMenuInfo.setupsystem.generic.x = 320;
+ setupMenuInfo.setupsystem.generic.y = y;
+ setupMenuInfo.setupsystem.generic.id = ID_SYSTEMCONFIG;
+ setupMenuInfo.setupsystem.generic.callback = UI_SetupMenu_Event;
+ setupMenuInfo.setupsystem.string = "SYSTEM";
+ setupMenuInfo.setupsystem.color = color_red;
+ setupMenuInfo.setupsystem.style = UI_CENTER;
+
+ y += SETUP_MENU_VERTICAL_SPACING;
+ setupMenuInfo.game.generic.type = MTYPE_PTEXT;
+ setupMenuInfo.game.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ setupMenuInfo.game.generic.x = 320;
+ setupMenuInfo.game.generic.y = y;
+ setupMenuInfo.game.generic.id = ID_GAME;
+ setupMenuInfo.game.generic.callback = UI_SetupMenu_Event;
+ setupMenuInfo.game.string = "GAME OPTIONS";
+ setupMenuInfo.game.color = color_red;
+ setupMenuInfo.game.style = UI_CENTER;
+
+ y += SETUP_MENU_VERTICAL_SPACING;
+ setupMenuInfo.cdkey.generic.type = MTYPE_PTEXT;
+ setupMenuInfo.cdkey.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ setupMenuInfo.cdkey.generic.x = 320;
+ setupMenuInfo.cdkey.generic.y = y;
+ setupMenuInfo.cdkey.generic.id = ID_CDKEY;
+ setupMenuInfo.cdkey.generic.callback = UI_SetupMenu_Event;
+ setupMenuInfo.cdkey.string = "CD Key";
+ setupMenuInfo.cdkey.color = color_red;
+ setupMenuInfo.cdkey.style = UI_CENTER;
+
+ if( !trap_Cvar_VariableValue( "cl_paused" ) ) {
+#if 0
+ y += SETUP_MENU_VERTICAL_SPACING;
+ setupMenuInfo.load.generic.type = MTYPE_PTEXT;
+ setupMenuInfo.load.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ setupMenuInfo.load.generic.x = 320;
+ setupMenuInfo.load.generic.y = y;
+ setupMenuInfo.load.generic.id = ID_LOAD;
+ setupMenuInfo.load.generic.callback = UI_SetupMenu_Event;
+ setupMenuInfo.load.string = "LOAD";
+ setupMenuInfo.load.color = color_red;
+ setupMenuInfo.load.style = UI_CENTER;
+
+ y += SETUP_MENU_VERTICAL_SPACING;
+ setupMenuInfo.save.generic.type = MTYPE_PTEXT;
+ setupMenuInfo.save.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ setupMenuInfo.save.generic.x = 320;
+ setupMenuInfo.save.generic.y = y;
+ setupMenuInfo.save.generic.id = ID_SAVE;
+ setupMenuInfo.save.generic.callback = UI_SetupMenu_Event;
+ setupMenuInfo.save.string = "SAVE";
+ setupMenuInfo.save.color = color_red;
+ setupMenuInfo.save.style = UI_CENTER;
+#endif
+
+ y += SETUP_MENU_VERTICAL_SPACING;
+ setupMenuInfo.defaults.generic.type = MTYPE_PTEXT;
+ setupMenuInfo.defaults.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ setupMenuInfo.defaults.generic.x = 320;
+ setupMenuInfo.defaults.generic.y = y;
+ setupMenuInfo.defaults.generic.id = ID_DEFAULTS;
+ setupMenuInfo.defaults.generic.callback = UI_SetupMenu_Event;
+ setupMenuInfo.defaults.string = "DEFAULTS";
+ setupMenuInfo.defaults.color = color_red;
+ setupMenuInfo.defaults.style = UI_CENTER;
+ }
+
+ setupMenuInfo.back.generic.type = MTYPE_BITMAP;
+ setupMenuInfo.back.generic.name = ART_BACK0;
+ setupMenuInfo.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ setupMenuInfo.back.generic.id = ID_BACK;
+ setupMenuInfo.back.generic.callback = UI_SetupMenu_Event;
+ setupMenuInfo.back.generic.x = 0;
+ setupMenuInfo.back.generic.y = 480-64;
+ setupMenuInfo.back.width = 128;
+ setupMenuInfo.back.height = 64;
+ setupMenuInfo.back.focuspic = ART_BACK1;
+
+ Menu_AddItem( &setupMenuInfo.menu, &setupMenuInfo.banner );
+ Menu_AddItem( &setupMenuInfo.menu, &setupMenuInfo.framel );
+ Menu_AddItem( &setupMenuInfo.menu, &setupMenuInfo.framer );
+ Menu_AddItem( &setupMenuInfo.menu, &setupMenuInfo.setupplayer );
+ Menu_AddItem( &setupMenuInfo.menu, &setupMenuInfo.setupcontrols );
+ Menu_AddItem( &setupMenuInfo.menu, &setupMenuInfo.setupsystem );
+ Menu_AddItem( &setupMenuInfo.menu, &setupMenuInfo.game );
+ Menu_AddItem( &setupMenuInfo.menu, &setupMenuInfo.cdkey );
+// Menu_AddItem( &setupMenuInfo.menu, &setupMenuInfo.load );
+// Menu_AddItem( &setupMenuInfo.menu, &setupMenuInfo.save );
+ if( !trap_Cvar_VariableValue( "cl_paused" ) ) {
+ Menu_AddItem( &setupMenuInfo.menu, &setupMenuInfo.defaults );
+ }
+ Menu_AddItem( &setupMenuInfo.menu, &setupMenuInfo.back );
+}
+
+
+/*
+=================
+UI_SetupMenu_Cache
+=================
+*/
+void UI_SetupMenu_Cache( void ) {
+ trap_R_RegisterShaderNoMip( ART_BACK0 );
+ trap_R_RegisterShaderNoMip( ART_BACK1 );
+ trap_R_RegisterShaderNoMip( ART_FRAMEL );
+ trap_R_RegisterShaderNoMip( ART_FRAMER );
+}
+
+
+/*
+===============
+UI_SetupMenu
+===============
+*/
+void UI_SetupMenu( void ) {
+ UI_SetupMenu_Init();
+ UI_PushMenu( &setupMenuInfo.menu );
+}
diff --git a/code/q3_ui/ui_signup.c b/code/q3_ui/ui_signup.c
new file mode 100755
index 0000000..efe9529
--- /dev/null
+++ b/code/q3_ui/ui_signup.c
@@ -0,0 +1,286 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+//
+// ui_signup.c
+//
+
+#include "ui_local.h"
+
+
+#define SIGNUP_FRAME "menu/art/cut_frame"
+
+#define ID_NAME 100
+#define ID_NAME_BOX 101
+#define ID_PASSWORD 102
+#define ID_PASSWORD_BOX 103
+#define ID_AGAIN 104
+#define ID_AGAIN_BOX 105
+#define ID_EMAIL 106
+#define ID_EMAIL_BOX 107
+#define ID_SIGNUP 108
+#define ID_CANCEL 109
+
+
+typedef struct
+{
+ menuframework_s menu;
+ menubitmap_s frame;
+ menutext_s name;
+ menufield_s name_box;
+ menutext_s password;
+ menufield_s password_box;
+ menutext_s again;
+ menufield_s again_box;
+ menutext_s email;
+ menufield_s email_box;
+ menutext_s signup;
+ menutext_s cancel;
+} signup_t;
+
+static signup_t s_signup;
+
+static menuframework_s s_signup_menu;
+static menuaction_s s_signup_signup;
+static menuaction_s s_signup_cancel;
+
+static vec4_t s_signup_color_prompt = {1.00, 0.43, 0.00, 1.00};
+
+/*
+===============
+Signup_MenuEvent
+===============
+*/
+static void Signup_MenuEvent( void* ptr, int event ) {
+ //char cmd[1024];
+
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+
+ switch( ((menucommon_s*)ptr)->id ) {
+ case ID_SIGNUP:
+ if( strcmp(s_signup.password_box.field.buffer,
+ s_signup.again_box.field.buffer) != 0 )
+ {
+ // GRANK_FIXME - password mismatch
+ break;
+ }
+ // set name
+ //trap_Cvar_Set( "name", s_signup.name_box.field.buffer );
+ /*
+ trap_Cvar_Set( "rank_name", s_signup.name_box.field.buffer );
+ trap_Cvar_Set( "rank_pwd", s_signup.password_box.field.buffer );
+ */
+
+ // create account
+ /*
+ sprintf( cmd, "cmd rank_create \"%s\" \"%s\" \"%s\"\n",
+ s_signup.name_box.field.buffer,
+ s_signup.password_box.field.buffer,
+ s_signup.email_box.field.buffer );
+ trap_Cmd_ExecuteText( EXEC_APPEND, cmd );
+ */
+ trap_CL_UI_RankUserCreate(
+ s_signup.name_box.field.buffer,
+ s_signup.password_box.field.buffer,
+ s_signup.email_box.field.buffer );
+
+ UI_ForceMenuOff();
+ break;
+
+ case ID_CANCEL:
+ UI_PopMenu();
+ break;
+ }
+}
+
+/*
+===============
+Signup_MenuInit
+===============
+*/
+void Signup_MenuInit( void ) {
+ grank_status_t status;
+ int y;
+
+ memset( &s_signup, 0, sizeof(s_signup) );
+
+ Signup_Cache();
+
+ s_signup.menu.wrapAround = qtrue;
+ s_signup.menu.fullscreen = qfalse;
+
+ s_signup.frame.generic.type = MTYPE_BITMAP;
+ s_signup.frame.generic.flags = QMF_INACTIVE;
+ s_signup.frame.generic.name = SIGNUP_FRAME;
+ s_signup.frame.generic.x = 142; //320-233;
+ s_signup.frame.generic.y = 118; //240-166;
+ s_signup.frame.width = 359; //466;
+ s_signup.frame.height = 256; //332;
+
+ y = 194;
+
+ s_signup.name.generic.type = MTYPE_PTEXT;
+ s_signup.name.generic.flags = QMF_RIGHT_JUSTIFY|QMF_INACTIVE;
+ s_signup.name.generic.id = ID_NAME;
+ s_signup.name.generic.x = 310;
+ s_signup.name.generic.y = y;
+ s_signup.name.string = "NAME";
+ s_signup.name.style = UI_RIGHT|UI_SMALLFONT;
+ s_signup.name.color = s_signup_color_prompt;
+
+ s_signup.name_box.generic.type = MTYPE_FIELD;
+ s_signup.name_box.generic.ownerdraw = Rankings_DrawName;
+ s_signup.name_box.generic.name = "";
+ s_signup.name_box.generic.flags = 0;
+ s_signup.name_box.generic.x = 330;
+ s_signup.name_box.generic.y = y;
+ s_signup.name_box.field.widthInChars = 16;
+ s_signup.name_box.field.maxchars = 16;
+ y += 20;
+
+ s_signup.password.generic.type = MTYPE_PTEXT;
+ s_signup.password.generic.flags = QMF_RIGHT_JUSTIFY|QMF_INACTIVE;
+ s_signup.password.generic.id = ID_PASSWORD;
+ s_signup.password.generic.x = 310;
+ s_signup.password.generic.y = y;
+ s_signup.password.string = "PASSWORD";
+ s_signup.password.style = UI_RIGHT|UI_SMALLFONT;
+ s_signup.password.color = s_signup_color_prompt;
+
+ s_signup.password_box.generic.type = MTYPE_FIELD;
+ s_signup.password_box.generic.ownerdraw = Rankings_DrawPassword;
+ s_signup.password_box.generic.name = "";
+ s_signup.password_box.generic.flags = 0;
+ s_signup.password_box.generic.x = 330;
+ s_signup.password_box.generic.y = y;
+ s_signup.password_box.field.widthInChars = 16;
+ s_signup.password_box.field.maxchars = 16;
+ y += 20;
+
+ s_signup.again.generic.type = MTYPE_PTEXT;
+ s_signup.again.generic.flags = QMF_RIGHT_JUSTIFY|QMF_INACTIVE;
+ s_signup.again.generic.id = ID_AGAIN;
+ s_signup.again.generic.x = 310;
+ s_signup.again.generic.y = y;
+ s_signup.again.string = "(AGAIN)";
+ s_signup.again.style = UI_RIGHT|UI_SMALLFONT;
+ s_signup.again.color = s_signup_color_prompt;
+
+ s_signup.again_box.generic.type = MTYPE_FIELD;
+ s_signup.again_box.generic.ownerdraw = Rankings_DrawPassword;
+ s_signup.again_box.generic.name = "";
+ s_signup.again_box.generic.flags = 0;
+ s_signup.again_box.generic.x = 330;
+ s_signup.again_box.generic.y = y;
+ s_signup.again_box.field.widthInChars = 16;
+ s_signup.again_box.field.maxchars = 16;
+ y += 20;
+
+ s_signup.email.generic.type = MTYPE_PTEXT;
+ s_signup.email.generic.flags = QMF_RIGHT_JUSTIFY|QMF_INACTIVE;
+ s_signup.email.generic.id = ID_EMAIL;
+ s_signup.email.generic.x = 310;
+ s_signup.email.generic.y = y;
+ s_signup.email.string = "EMAIL";
+ s_signup.email.style = UI_RIGHT|UI_SMALLFONT;
+ s_signup.email.color = s_signup_color_prompt;
+
+ s_signup.email_box.generic.type = MTYPE_FIELD;
+ s_signup.email_box.generic.ownerdraw = Rankings_DrawText;
+ s_signup.email_box.generic.name = "";
+ s_signup.email_box.generic.flags = 0;
+ s_signup.email_box.generic.x = 330;
+ s_signup.email_box.generic.y = y;
+ s_signup.email_box.field.widthInChars = 16;
+ s_signup.email_box.field.maxchars = MAX_EDIT_LINE;
+ y += 40;
+
+ s_signup.signup.generic.type = MTYPE_PTEXT;
+ s_signup.signup.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_signup.signup.generic.id = ID_SIGNUP;
+ s_signup.signup.generic.callback = Signup_MenuEvent;
+ s_signup.signup.generic.x = 310;
+ s_signup.signup.generic.y = y;
+ s_signup.signup.string = "SIGN UP";
+ s_signup.signup.style = UI_RIGHT|UI_SMALLFONT;
+ s_signup.signup.color = colorRed;
+
+ s_signup.cancel.generic.type = MTYPE_PTEXT;
+ s_signup.cancel.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_signup.cancel.generic.id = ID_CANCEL;
+ s_signup.cancel.generic.callback = Signup_MenuEvent;
+ s_signup.cancel.generic.x = 330;
+ s_signup.cancel.generic.y = y;
+ s_signup.cancel.string = "CANCEL";
+ s_signup.cancel.style = UI_LEFT|UI_SMALLFONT;
+ s_signup.cancel.color = colorRed;
+ y += 20;
+
+ status = (grank_status_t)trap_Cvar_VariableValue("client_status");
+ if( (status != QGR_STATUS_NEW) && (status != QGR_STATUS_SPECTATOR) )
+ {
+ s_signup.name_box.generic.flags |= QMF_INACTIVE;
+ s_signup.password_box.generic.flags |= QMF_INACTIVE;
+ s_signup.again_box.generic.flags |= QMF_INACTIVE;
+ s_signup.email_box.generic.flags |= QMF_INACTIVE;
+ s_signup.signup.generic.flags |= QMF_INACTIVE;
+
+ s_signup.signup.color = colorMdGrey;
+ }
+
+ Menu_AddItem( &s_signup.menu, (void*) &s_signup.frame );
+ Menu_AddItem( &s_signup.menu, (void*) &s_signup.name );
+ Menu_AddItem( &s_signup.menu, (void*) &s_signup.name_box );
+ Menu_AddItem( &s_signup.menu, (void*) &s_signup.password );
+ Menu_AddItem( &s_signup.menu, (void*) &s_signup.password_box );
+ Menu_AddItem( &s_signup.menu, (void*) &s_signup.again );
+ Menu_AddItem( &s_signup.menu, (void*) &s_signup.again_box );
+ Menu_AddItem( &s_signup.menu, (void*) &s_signup.email );
+ Menu_AddItem( &s_signup.menu, (void*) &s_signup.email_box );
+ Menu_AddItem( &s_signup.menu, (void*) &s_signup.signup );
+ Menu_AddItem( &s_signup.menu, (void*) &s_signup.cancel );
+}
+
+
+/*
+===============
+Signup_Cache
+===============
+*/
+void Signup_Cache( void ) {
+ trap_R_RegisterShaderNoMip( SIGNUP_FRAME );
+}
+
+
+/*
+===============
+UI_SignupMenu
+===============
+*/
+void UI_SignupMenu( void ) {
+ Signup_MenuInit();
+ UI_PushMenu ( &s_signup.menu );
+}
+
+
diff --git a/code/q3_ui/ui_sound.c b/code/q3_ui/ui_sound.c
new file mode 100755
index 0000000..60040f0
--- /dev/null
+++ b/code/q3_ui/ui_sound.c
@@ -0,0 +1,316 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*
+=======================================================================
+
+SOUND OPTIONS MENU
+
+=======================================================================
+*/
+
+#include "ui_local.h"
+
+
+#define ART_FRAMEL "menu/art/frame2_l"
+#define ART_FRAMER "menu/art/frame1_r"
+#define ART_BACK0 "menu/art/back_0"
+#define ART_BACK1 "menu/art/back_1"
+
+#define ID_GRAPHICS 10
+#define ID_DISPLAY 11
+#define ID_SOUND 12
+#define ID_NETWORK 13
+#define ID_EFFECTSVOLUME 14
+#define ID_MUSICVOLUME 15
+#define ID_QUALITY 16
+//#define ID_A3D 17
+#define ID_BACK 18
+
+
+static const char *quality_items[] = {
+ "Low", "High", 0
+};
+
+typedef struct {
+ menuframework_s menu;
+
+ menutext_s banner;
+ menubitmap_s framel;
+ menubitmap_s framer;
+
+ menutext_s graphics;
+ menutext_s display;
+ menutext_s sound;
+ menutext_s network;
+
+ menuslider_s sfxvolume;
+ menuslider_s musicvolume;
+ menulist_s quality;
+// menuradiobutton_s a3d;
+
+ menubitmap_s back;
+} soundOptionsInfo_t;
+
+static soundOptionsInfo_t soundOptionsInfo;
+
+
+/*
+=================
+UI_SoundOptionsMenu_Event
+=================
+*/
+static void UI_SoundOptionsMenu_Event( void* ptr, int event ) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+
+ switch( ((menucommon_s*)ptr)->id ) {
+ case ID_GRAPHICS:
+ UI_PopMenu();
+ UI_GraphicsOptionsMenu();
+ break;
+
+ case ID_DISPLAY:
+ UI_PopMenu();
+ UI_DisplayOptionsMenu();
+ break;
+
+ case ID_SOUND:
+ break;
+
+ case ID_NETWORK:
+ UI_PopMenu();
+ UI_NetworkOptionsMenu();
+ break;
+
+ case ID_EFFECTSVOLUME:
+ trap_Cvar_SetValue( "s_volume", soundOptionsInfo.sfxvolume.curvalue / 10 );
+ break;
+
+ case ID_MUSICVOLUME:
+ trap_Cvar_SetValue( "s_musicvolume", soundOptionsInfo.musicvolume.curvalue / 10 );
+ break;
+
+ case ID_QUALITY:
+ if( soundOptionsInfo.quality.curvalue ) {
+ trap_Cvar_SetValue( "s_khz", 22 );
+ trap_Cvar_SetValue( "s_compression", 0 );
+ }
+ else {
+ trap_Cvar_SetValue( "s_khz", 11 );
+ trap_Cvar_SetValue( "s_compression", 1 );
+ }
+ UI_ForceMenuOff();
+ trap_Cmd_ExecuteText( EXEC_APPEND, "snd_restart\n" );
+ break;
+/*
+ case ID_A3D:
+ if( soundOptionsInfo.a3d.curvalue ) {
+ trap_Cmd_ExecuteText( EXEC_NOW, "s_enable_a3d\n" );
+ }
+ else {
+ trap_Cmd_ExecuteText( EXEC_NOW, "s_disable_a3d\n" );
+ }
+ soundOptionsInfo.a3d.curvalue = (int)trap_Cvar_VariableValue( "s_usingA3D" );
+ break;
+*/
+ case ID_BACK:
+ UI_PopMenu();
+ break;
+ }
+}
+
+
+/*
+===============
+UI_SoundOptionsMenu_Init
+===============
+*/
+static void UI_SoundOptionsMenu_Init( void ) {
+ int y;
+
+ memset( &soundOptionsInfo, 0, sizeof(soundOptionsInfo) );
+
+ UI_SoundOptionsMenu_Cache();
+ soundOptionsInfo.menu.wrapAround = qtrue;
+ soundOptionsInfo.menu.fullscreen = qtrue;
+
+ soundOptionsInfo.banner.generic.type = MTYPE_BTEXT;
+ soundOptionsInfo.banner.generic.flags = QMF_CENTER_JUSTIFY;
+ soundOptionsInfo.banner.generic.x = 320;
+ soundOptionsInfo.banner.generic.y = 16;
+ soundOptionsInfo.banner.string = "SYSTEM SETUP";
+ soundOptionsInfo.banner.color = color_white;
+ soundOptionsInfo.banner.style = UI_CENTER;
+
+ soundOptionsInfo.framel.generic.type = MTYPE_BITMAP;
+ soundOptionsInfo.framel.generic.name = ART_FRAMEL;
+ soundOptionsInfo.framel.generic.flags = QMF_INACTIVE;
+ soundOptionsInfo.framel.generic.x = 0;
+ soundOptionsInfo.framel.generic.y = 78;
+ soundOptionsInfo.framel.width = 256;
+ soundOptionsInfo.framel.height = 329;
+
+ soundOptionsInfo.framer.generic.type = MTYPE_BITMAP;
+ soundOptionsInfo.framer.generic.name = ART_FRAMER;
+ soundOptionsInfo.framer.generic.flags = QMF_INACTIVE;
+ soundOptionsInfo.framer.generic.x = 376;
+ soundOptionsInfo.framer.generic.y = 76;
+ soundOptionsInfo.framer.width = 256;
+ soundOptionsInfo.framer.height = 334;
+
+ soundOptionsInfo.graphics.generic.type = MTYPE_PTEXT;
+ soundOptionsInfo.graphics.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ soundOptionsInfo.graphics.generic.id = ID_GRAPHICS;
+ soundOptionsInfo.graphics.generic.callback = UI_SoundOptionsMenu_Event;
+ soundOptionsInfo.graphics.generic.x = 216;
+ soundOptionsInfo.graphics.generic.y = 240 - 2 * PROP_HEIGHT;
+ soundOptionsInfo.graphics.string = "GRAPHICS";
+ soundOptionsInfo.graphics.style = UI_RIGHT;
+ soundOptionsInfo.graphics.color = color_red;
+
+ soundOptionsInfo.display.generic.type = MTYPE_PTEXT;
+ soundOptionsInfo.display.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ soundOptionsInfo.display.generic.id = ID_DISPLAY;
+ soundOptionsInfo.display.generic.callback = UI_SoundOptionsMenu_Event;
+ soundOptionsInfo.display.generic.x = 216;
+ soundOptionsInfo.display.generic.y = 240 - PROP_HEIGHT;
+ soundOptionsInfo.display.string = "DISPLAY";
+ soundOptionsInfo.display.style = UI_RIGHT;
+ soundOptionsInfo.display.color = color_red;
+
+ soundOptionsInfo.sound.generic.type = MTYPE_PTEXT;
+ soundOptionsInfo.sound.generic.flags = QMF_RIGHT_JUSTIFY;
+ soundOptionsInfo.sound.generic.id = ID_SOUND;
+ soundOptionsInfo.sound.generic.callback = UI_SoundOptionsMenu_Event;
+ soundOptionsInfo.sound.generic.x = 216;
+ soundOptionsInfo.sound.generic.y = 240;
+ soundOptionsInfo.sound.string = "SOUND";
+ soundOptionsInfo.sound.style = UI_RIGHT;
+ soundOptionsInfo.sound.color = color_red;
+
+ soundOptionsInfo.network.generic.type = MTYPE_PTEXT;
+ soundOptionsInfo.network.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ soundOptionsInfo.network.generic.id = ID_NETWORK;
+ soundOptionsInfo.network.generic.callback = UI_SoundOptionsMenu_Event;
+ soundOptionsInfo.network.generic.x = 216;
+ soundOptionsInfo.network.generic.y = 240 + PROP_HEIGHT;
+ soundOptionsInfo.network.string = "NETWORK";
+ soundOptionsInfo.network.style = UI_RIGHT;
+ soundOptionsInfo.network.color = color_red;
+
+ y = 240 - 1.5 * (BIGCHAR_HEIGHT + 2);
+ soundOptionsInfo.sfxvolume.generic.type = MTYPE_SLIDER;
+ soundOptionsInfo.sfxvolume.generic.name = "Effects Volume:";
+ soundOptionsInfo.sfxvolume.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ soundOptionsInfo.sfxvolume.generic.callback = UI_SoundOptionsMenu_Event;
+ soundOptionsInfo.sfxvolume.generic.id = ID_EFFECTSVOLUME;
+ soundOptionsInfo.sfxvolume.generic.x = 400;
+ soundOptionsInfo.sfxvolume.generic.y = y;
+ soundOptionsInfo.sfxvolume.minvalue = 0;
+ soundOptionsInfo.sfxvolume.maxvalue = 10;
+
+ y += BIGCHAR_HEIGHT+2;
+ soundOptionsInfo.musicvolume.generic.type = MTYPE_SLIDER;
+ soundOptionsInfo.musicvolume.generic.name = "Music Volume:";
+ soundOptionsInfo.musicvolume.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ soundOptionsInfo.musicvolume.generic.callback = UI_SoundOptionsMenu_Event;
+ soundOptionsInfo.musicvolume.generic.id = ID_MUSICVOLUME;
+ soundOptionsInfo.musicvolume.generic.x = 400;
+ soundOptionsInfo.musicvolume.generic.y = y;
+ soundOptionsInfo.musicvolume.minvalue = 0;
+ soundOptionsInfo.musicvolume.maxvalue = 10;
+
+ y += BIGCHAR_HEIGHT+2;
+ soundOptionsInfo.quality.generic.type = MTYPE_SPINCONTROL;
+ soundOptionsInfo.quality.generic.name = "Sound Quality:";
+ soundOptionsInfo.quality.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ soundOptionsInfo.quality.generic.callback = UI_SoundOptionsMenu_Event;
+ soundOptionsInfo.quality.generic.id = ID_QUALITY;
+ soundOptionsInfo.quality.generic.x = 400;
+ soundOptionsInfo.quality.generic.y = y;
+ soundOptionsInfo.quality.itemnames = quality_items;
+/*
+ y += BIGCHAR_HEIGHT+2;
+ soundOptionsInfo.a3d.generic.type = MTYPE_RADIOBUTTON;
+ soundOptionsInfo.a3d.generic.name = "A3D:";
+ soundOptionsInfo.a3d.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ soundOptionsInfo.a3d.generic.callback = UI_SoundOptionsMenu_Event;
+ soundOptionsInfo.a3d.generic.id = ID_A3D;
+ soundOptionsInfo.a3d.generic.x = 400;
+ soundOptionsInfo.a3d.generic.y = y;
+*/
+ soundOptionsInfo.back.generic.type = MTYPE_BITMAP;
+ soundOptionsInfo.back.generic.name = ART_BACK0;
+ soundOptionsInfo.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ soundOptionsInfo.back.generic.callback = UI_SoundOptionsMenu_Event;
+ soundOptionsInfo.back.generic.id = ID_BACK;
+ soundOptionsInfo.back.generic.x = 0;
+ soundOptionsInfo.back.generic.y = 480-64;
+ soundOptionsInfo.back.width = 128;
+ soundOptionsInfo.back.height = 64;
+ soundOptionsInfo.back.focuspic = ART_BACK1;
+
+ Menu_AddItem( &soundOptionsInfo.menu, ( void * ) &soundOptionsInfo.banner );
+ Menu_AddItem( &soundOptionsInfo.menu, ( void * ) &soundOptionsInfo.framel );
+ Menu_AddItem( &soundOptionsInfo.menu, ( void * ) &soundOptionsInfo.framer );
+ Menu_AddItem( &soundOptionsInfo.menu, ( void * ) &soundOptionsInfo.graphics );
+ Menu_AddItem( &soundOptionsInfo.menu, ( void * ) &soundOptionsInfo.display );
+ Menu_AddItem( &soundOptionsInfo.menu, ( void * ) &soundOptionsInfo.sound );
+ Menu_AddItem( &soundOptionsInfo.menu, ( void * ) &soundOptionsInfo.network );
+ Menu_AddItem( &soundOptionsInfo.menu, ( void * ) &soundOptionsInfo.sfxvolume );
+ Menu_AddItem( &soundOptionsInfo.menu, ( void * ) &soundOptionsInfo.musicvolume );
+ Menu_AddItem( &soundOptionsInfo.menu, ( void * ) &soundOptionsInfo.quality );
+// Menu_AddItem( &soundOptionsInfo.menu, ( void * ) &soundOptionsInfo.a3d );
+ Menu_AddItem( &soundOptionsInfo.menu, ( void * ) &soundOptionsInfo.back );
+
+ soundOptionsInfo.sfxvolume.curvalue = trap_Cvar_VariableValue( "s_volume" ) * 10;
+ soundOptionsInfo.musicvolume.curvalue = trap_Cvar_VariableValue( "s_musicvolume" ) * 10;
+ soundOptionsInfo.quality.curvalue = !trap_Cvar_VariableValue( "s_compression" );
+// soundOptionsInfo.a3d.curvalue = (int)trap_Cvar_VariableValue( "s_usingA3D" );
+}
+
+
+/*
+===============
+UI_SoundOptionsMenu_Cache
+===============
+*/
+void UI_SoundOptionsMenu_Cache( void ) {
+ trap_R_RegisterShaderNoMip( ART_FRAMEL );
+ trap_R_RegisterShaderNoMip( ART_FRAMER );
+ trap_R_RegisterShaderNoMip( ART_BACK0 );
+ trap_R_RegisterShaderNoMip( ART_BACK1 );
+}
+
+
+/*
+===============
+UI_SoundOptionsMenu
+===============
+*/
+void UI_SoundOptionsMenu( void ) {
+ UI_SoundOptionsMenu_Init();
+ UI_PushMenu( &soundOptionsInfo.menu );
+ Menu_SetCursorToItem( &soundOptionsInfo.menu, &soundOptionsInfo.sound );
+}
diff --git a/code/q3_ui/ui_sparena.c b/code/q3_ui/ui_sparena.c
new file mode 100755
index 0000000..44970f6
--- /dev/null
+++ b/code/q3_ui/ui_sparena.c
@@ -0,0 +1,50 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#include "ui_local.h"
+
+void UI_SPArena_Start( const char *arenaInfo ) {
+ char *map;
+ int level;
+ int n;
+ char *txt;
+
+ n = (int)trap_Cvar_VariableValue( "sv_maxclients" );
+ if ( n < 8 ) {
+ trap_Cvar_SetValue( "sv_maxclients", 8 );
+ }
+
+ level = atoi( Info_ValueForKey( arenaInfo, "num" ) );
+ txt = Info_ValueForKey( arenaInfo, "special" );
+ if( txt[0] ) {
+ if( Q_stricmp( txt, "training" ) == 0 ) {
+ level = -4;
+ }
+ else if( Q_stricmp( txt, "final" ) == 0 ) {
+ level = UI_GetNumSPTiers() * ARENAS_PER_TIER;
+ }
+ }
+ trap_Cvar_SetValue( "ui_spSelection", level );
+
+ map = Info_ValueForKey( arenaInfo, "map" );
+ trap_Cmd_ExecuteText( EXEC_APPEND, va( "spmap %s\n", map ) );
+}
diff --git a/code/q3_ui/ui_specifyleague.c b/code/q3_ui/ui_specifyleague.c
new file mode 100755
index 0000000..4e0a8b0
--- /dev/null
+++ b/code/q3_ui/ui_specifyleague.c
@@ -0,0 +1,333 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#include "ui_local.h"
+
+/*********************************************************************************
+ SPECIFY SERVER
+*********************************************************************************/
+
+#define MAX_LISTBOXITEMS 128
+#define MAX_LISTBOXWIDTH 40
+#define MAX_LEAGUENAME 80
+
+#define SPECIFYLEAGUE_FRAMEL "menu/art/frame2_l"
+#define SPECIFYLEAGUE_FRAMER "menu/art/frame1_r"
+#define SPECIFYLEAGUE_BACK0 "menu/art/back_0"
+#define SPECIFYLEAGUE_BACK1 "menu/art/back_1"
+#define SPECIFYLEAGUE_ARROWS0 "menu/art/arrows_vert_0"
+#define SPECIFYLEAGUE_UP "menu/art/arrows_vert_top"
+#define SPECIFYLEAGUE_DOWN "menu/art/arrows_vert_bot"
+#define GLOBALRANKINGS_LOGO "menu/art/gr/grlogo"
+#define GLOBALRANKINGS_LETTERS "menu/art/gr/grletters"
+
+#define ID_SPECIFYLEAGUENAME 100
+#define ID_SPECIFYLEAGUELIST 101
+#define ID_SPECIFYLEAGUEUP 102
+#define ID_SPECIFYLEAGUEDOWN 103
+#define ID_SPECIFYLEAGUEBACK 104
+
+static char* specifyleague_artlist[] =
+{
+ SPECIFYLEAGUE_FRAMEL,
+ SPECIFYLEAGUE_FRAMER,
+ SPECIFYLEAGUE_ARROWS0,
+ SPECIFYLEAGUE_UP,
+ SPECIFYLEAGUE_DOWN,
+ SPECIFYLEAGUE_BACK0,
+ SPECIFYLEAGUE_BACK1,
+ GLOBALRANKINGS_LOGO,
+ GLOBALRANKINGS_LETTERS,
+ NULL
+};
+
+static char playername[80];
+
+typedef struct
+{
+ menuframework_s menu;
+ menutext_s banner;
+ menubitmap_s framel;
+ menubitmap_s framer;
+ menufield_s rankname;
+ menulist_s list;
+ menubitmap_s arrows;
+ menubitmap_s up;
+ menubitmap_s down;
+ menubitmap_s back;
+ menubitmap_s grlogo;
+ menubitmap_s grletters;
+} specifyleague_t;
+
+static specifyleague_t s_specifyleague;
+
+
+typedef struct {
+ char buff[MAX_LISTBOXWIDTH];
+ char leaguename[MAX_LEAGUENAME];
+} table_t;
+
+table_t league_table[MAX_LISTBOXITEMS];
+char *leaguename_items[MAX_LISTBOXITEMS];
+
+
+static void SpecifyLeague_GetList()
+{
+ int count = 0;
+ int i;
+ /* The Player Name has changed. We need to perform another search */
+ Q_strncpyz( playername,
+ s_specifyleague.rankname.field.buffer,
+ sizeof(playername) );
+
+ count = trap_CL_UI_RankGetLeauges( playername );
+
+ for(i = 0; i < count; i++)
+ {
+ char s[MAX_LEAGUENAME];
+ const char *var;
+ var = va( "leaguename%i", i+1 );
+ trap_Cvar_VariableStringBuffer( var, s, sizeof(s) );
+ Q_strncpyz(league_table[i].leaguename, s, sizeof(league_table[i].leaguename) );
+ Q_strncpyz(league_table[i].buff, league_table[i].leaguename, sizeof(league_table[i].buff) );
+ }
+
+ s_specifyleague.list.numitems = count;
+}
+
+/*
+=================
+SpecifyLeague_Event
+=================
+*/
+static void SpecifyLeague_Event( void* ptr, int event )
+{
+ int id;
+ id = ((menucommon_s*)ptr)->id;
+ //if( event != QM_ACTIVATED && id != ID_SPECIFYLEAGUELIST ) {
+ // return;
+ //}
+
+ switch (id)
+ {
+ case ID_SPECIFYLEAGUELIST:
+ if( event == QM_GOTFOCUS ) {
+ //ArenaServers_UpdatePicture();
+ }
+ break;
+
+ case ID_SPECIFYLEAGUEUP:
+ if( event == QM_ACTIVATED )
+ ScrollList_Key( &s_specifyleague.list, K_UPARROW );
+ break;
+
+ case ID_SPECIFYLEAGUEDOWN:
+ if( event == QM_ACTIVATED )
+ ScrollList_Key( &s_specifyleague.list, K_DOWNARROW );
+ break;
+
+ case ID_SPECIFYLEAGUENAME:
+ if( (event == QM_LOSTFOCUS) &&
+ (Q_strncmp(playername,
+ s_specifyleague.rankname.field.buffer,
+ strlen(s_specifyleague.rankname.field.buffer)) != 0))
+ {
+ SpecifyLeague_GetList();
+ }
+ break;
+
+ case ID_SPECIFYLEAGUEBACK:
+ if( event == QM_ACTIVATED )
+ {
+ trap_Cvar_Set( "sv_leagueName", league_table[s_specifyleague.list.curvalue].leaguename);
+ UI_PopMenu();
+ }
+ break;
+ }
+}
+
+/*
+=================
+SpecifyLeague_MenuInit
+=================
+*/
+void SpecifyLeague_MenuInit( void )
+{
+ int i;
+ // zero set all our globals
+ memset( &s_specifyleague, 0 ,sizeof(specifyleague_t) );
+
+ SpecifyLeague_Cache();
+
+ s_specifyleague.menu.wrapAround = qtrue;
+ s_specifyleague.menu.fullscreen = qtrue;
+
+ s_specifyleague.banner.generic.type = MTYPE_BTEXT;
+ s_specifyleague.banner.generic.x = 320;
+ s_specifyleague.banner.generic.y = 16;
+ s_specifyleague.banner.string = "CHOOSE LEAGUE";
+ s_specifyleague.banner.color = color_white;
+ s_specifyleague.banner.style = UI_CENTER;
+
+ s_specifyleague.framel.generic.type = MTYPE_BITMAP;
+ s_specifyleague.framel.generic.name = SPECIFYLEAGUE_FRAMEL;
+ s_specifyleague.framel.generic.flags = QMF_INACTIVE;
+ s_specifyleague.framel.generic.x = 0;
+ s_specifyleague.framel.generic.y = 78;
+ s_specifyleague.framel.width = 256;
+ s_specifyleague.framel.height = 334;
+
+ s_specifyleague.framer.generic.type = MTYPE_BITMAP;
+ s_specifyleague.framer.generic.name = SPECIFYLEAGUE_FRAMER;
+ s_specifyleague.framer.generic.flags = QMF_INACTIVE;
+ s_specifyleague.framer.generic.x = 376;
+ s_specifyleague.framer.generic.y = 76;
+ s_specifyleague.framer.width = 256;
+ s_specifyleague.framer.height = 334;
+
+ s_specifyleague.grlogo.generic.type = MTYPE_BITMAP;
+ s_specifyleague.grlogo.generic.name = GLOBALRANKINGS_LOGO;
+ s_specifyleague.grlogo.generic.flags = QMF_INACTIVE;
+ s_specifyleague.grlogo.generic.x = 0;
+ s_specifyleague.grlogo.generic.y = 0;
+ s_specifyleague.grlogo.width = 64;
+ s_specifyleague.grlogo.height = 128;
+
+ s_specifyleague.rankname.generic.type = MTYPE_FIELD;
+ s_specifyleague.rankname.generic.name = "Player Name:";
+ s_specifyleague.rankname.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_specifyleague.rankname.generic.callback = SpecifyLeague_Event;
+ s_specifyleague.rankname.generic.id = ID_SPECIFYLEAGUENAME;
+ s_specifyleague.rankname.generic.x = 226;
+ s_specifyleague.rankname.generic.y = 128;
+ s_specifyleague.rankname.field.widthInChars = 32;
+ s_specifyleague.rankname.field.maxchars = 80;
+
+ s_specifyleague.list.generic.type = MTYPE_SCROLLLIST;
+ s_specifyleague.list.generic.flags = QMF_HIGHLIGHT_IF_FOCUS;
+ s_specifyleague.list.generic.id = ID_SPECIFYLEAGUELIST;
+ s_specifyleague.list.generic.callback = SpecifyLeague_Event;
+ s_specifyleague.list.generic.x = 160;
+ s_specifyleague.list.generic.y = 200;
+ s_specifyleague.list.width = MAX_LISTBOXWIDTH;
+ s_specifyleague.list.height = 8;
+ s_specifyleague.list.itemnames = (const char **)leaguename_items;
+ s_specifyleague.list.numitems = 0;
+ for( i = 0; i < MAX_LISTBOXITEMS; i++ ) {
+ league_table[i].buff[0] = 0;
+ league_table[i].leaguename[0] = 0;
+ leaguename_items[i] = league_table[i].buff;
+ }
+
+ s_specifyleague.arrows.generic.type = MTYPE_BITMAP;
+ s_specifyleague.arrows.generic.name = SPECIFYLEAGUE_ARROWS0;
+ s_specifyleague.arrows.generic.flags = QMF_LEFT_JUSTIFY|QMF_INACTIVE;
+ s_specifyleague.arrows.generic.callback = SpecifyLeague_Event;
+ s_specifyleague.arrows.generic.x = 512;
+ s_specifyleague.arrows.generic.y = 240-64+16;
+ s_specifyleague.arrows.width = 64;
+ s_specifyleague.arrows.height = 128;
+
+ s_specifyleague.up.generic.type = MTYPE_BITMAP;
+ s_specifyleague.up.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_MOUSEONLY;
+ s_specifyleague.up.generic.callback = SpecifyLeague_Event;
+ s_specifyleague.up.generic.id = ID_SPECIFYLEAGUEUP;
+ s_specifyleague.up.generic.x = 512;
+ s_specifyleague.up.generic.y = 240-64+16;
+ s_specifyleague.up.width = 64;
+ s_specifyleague.up.height = 64;
+ s_specifyleague.up.focuspic = SPECIFYLEAGUE_UP;
+
+ s_specifyleague.down.generic.type = MTYPE_BITMAP;
+ s_specifyleague.down.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_MOUSEONLY;
+ s_specifyleague.down.generic.callback = SpecifyLeague_Event;
+ s_specifyleague.down.generic.id = ID_SPECIFYLEAGUEDOWN;
+ s_specifyleague.down.generic.x = 512;
+ s_specifyleague.down.generic.y = 240+16;
+ s_specifyleague.down.width = 64;
+ s_specifyleague.down.height = 64;
+ s_specifyleague.down.focuspic = SPECIFYLEAGUE_DOWN;
+
+ s_specifyleague.back.generic.type = MTYPE_BITMAP;
+ s_specifyleague.back.generic.name = SPECIFYLEAGUE_BACK0;
+ s_specifyleague.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_specifyleague.back.generic.callback = SpecifyLeague_Event;
+ s_specifyleague.back.generic.id = ID_SPECIFYLEAGUEBACK;
+ s_specifyleague.back.generic.x = 0;
+ s_specifyleague.back.generic.y = 480-64;
+ s_specifyleague.back.width = 128;
+ s_specifyleague.back.height = 64;
+ s_specifyleague.back.focuspic = SPECIFYLEAGUE_BACK1;
+
+ Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.banner );
+ Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.framel );
+ Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.framer );
+ Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.grlogo );
+ Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.rankname );
+ Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.list );
+ Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.arrows );
+ Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.up );
+ Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.down );
+ Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.back );
+
+
+ // initialize any menu variables
+ Q_strncpyz( s_specifyleague.rankname.field.buffer,
+ UI_Cvar_VariableString("name"),
+ sizeof(s_specifyleague.rankname.field.buffer) );
+
+ Q_strncpyz( playername,
+ UI_Cvar_VariableString("name"),
+ sizeof(playername) );
+
+ SpecifyLeague_GetList();
+}
+
+/*
+=================
+SpecifyLeague_Cache
+=================
+*/
+void SpecifyLeague_Cache( void )
+{
+ int i;
+
+ // touch all our pics
+ for (i=0; ;i++)
+ {
+ if (!specifyleague_artlist[i])
+ break;
+ trap_R_RegisterShaderNoMip(specifyleague_artlist[i]);
+ }
+}
+
+/*
+=================
+UI_SpecifyLeagueMenu
+=================
+*/
+void UI_SpecifyLeagueMenu( void )
+{
+ SpecifyLeague_MenuInit();
+ UI_PushMenu( &s_specifyleague.menu );
+}
+
diff --git a/code/q3_ui/ui_specifyserver.c b/code/q3_ui/ui_specifyserver.c
new file mode 100755
index 0000000..2df4418
--- /dev/null
+++ b/code/q3_ui/ui_specifyserver.c
@@ -0,0 +1,213 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#include "ui_local.h"
+
+/*********************************************************************************
+ SPECIFY SERVER
+*********************************************************************************/
+
+#define SPECIFYSERVER_FRAMEL "menu/art/frame2_l"
+#define SPECIFYSERVER_FRAMER "menu/art/frame1_r"
+#define SPECIFYSERVER_BACK0 "menu/art/back_0"
+#define SPECIFYSERVER_BACK1 "menu/art/back_1"
+#define SPECIFYSERVER_FIGHT0 "menu/art/fight_0"
+#define SPECIFYSERVER_FIGHT1 "menu/art/fight_1"
+
+#define ID_SPECIFYSERVERBACK 102
+#define ID_SPECIFYSERVERGO 103
+
+static char* specifyserver_artlist[] =
+{
+ SPECIFYSERVER_FRAMEL,
+ SPECIFYSERVER_FRAMER,
+ SPECIFYSERVER_BACK0,
+ SPECIFYSERVER_BACK1,
+ SPECIFYSERVER_FIGHT0,
+ SPECIFYSERVER_FIGHT1,
+ NULL
+};
+
+typedef struct
+{
+ menuframework_s menu;
+ menutext_s banner;
+ menubitmap_s framel;
+ menubitmap_s framer;
+ menufield_s domain;
+ menufield_s port;
+ menubitmap_s go;
+ menubitmap_s back;
+} specifyserver_t;
+
+static specifyserver_t s_specifyserver;
+
+/*
+=================
+SpecifyServer_Event
+=================
+*/
+static void SpecifyServer_Event( void* ptr, int event )
+{
+ char buff[256];
+
+ switch (((menucommon_s*)ptr)->id)
+ {
+ case ID_SPECIFYSERVERGO:
+ if (event != QM_ACTIVATED)
+ break;
+
+ if (s_specifyserver.domain.field.buffer[0])
+ {
+ strcpy(buff,s_specifyserver.domain.field.buffer);
+ if (s_specifyserver.port.field.buffer[0])
+ Com_sprintf( buff+strlen(buff), 128, ":%s", s_specifyserver.port.field.buffer );
+
+ trap_Cmd_ExecuteText( EXEC_APPEND, va( "connect %s\n", buff ) );
+ }
+ break;
+
+ case ID_SPECIFYSERVERBACK:
+ if (event != QM_ACTIVATED)
+ break;
+
+ UI_PopMenu();
+ break;
+ }
+}
+
+/*
+=================
+SpecifyServer_MenuInit
+=================
+*/
+void SpecifyServer_MenuInit( void )
+{
+ // zero set all our globals
+ memset( &s_specifyserver, 0 ,sizeof(specifyserver_t) );
+
+ SpecifyServer_Cache();
+
+ s_specifyserver.menu.wrapAround = qtrue;
+ s_specifyserver.menu.fullscreen = qtrue;
+
+ s_specifyserver.banner.generic.type = MTYPE_BTEXT;
+ s_specifyserver.banner.generic.x = 320;
+ s_specifyserver.banner.generic.y = 16;
+ s_specifyserver.banner.string = "SPECIFY SERVER";
+ s_specifyserver.banner.color = color_white;
+ s_specifyserver.banner.style = UI_CENTER;
+
+ s_specifyserver.framel.generic.type = MTYPE_BITMAP;
+ s_specifyserver.framel.generic.name = SPECIFYSERVER_FRAMEL;
+ s_specifyserver.framel.generic.flags = QMF_INACTIVE;
+ s_specifyserver.framel.generic.x = 0;
+ s_specifyserver.framel.generic.y = 78;
+ s_specifyserver.framel.width = 256;
+ s_specifyserver.framel.height = 329;
+
+ s_specifyserver.framer.generic.type = MTYPE_BITMAP;
+ s_specifyserver.framer.generic.name = SPECIFYSERVER_FRAMER;
+ s_specifyserver.framer.generic.flags = QMF_INACTIVE;
+ s_specifyserver.framer.generic.x = 376;
+ s_specifyserver.framer.generic.y = 76;
+ s_specifyserver.framer.width = 256;
+ s_specifyserver.framer.height = 334;
+
+ s_specifyserver.domain.generic.type = MTYPE_FIELD;
+ s_specifyserver.domain.generic.name = "Address:";
+ s_specifyserver.domain.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_specifyserver.domain.generic.x = 206;
+ s_specifyserver.domain.generic.y = 220;
+ s_specifyserver.domain.field.widthInChars = 38;
+ s_specifyserver.domain.field.maxchars = 80;
+
+ s_specifyserver.port.generic.type = MTYPE_FIELD;
+ s_specifyserver.port.generic.name = "Port:";
+ s_specifyserver.port.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT|QMF_NUMBERSONLY;
+ s_specifyserver.port.generic.x = 206;
+ s_specifyserver.port.generic.y = 250;
+ s_specifyserver.port.field.widthInChars = 6;
+ s_specifyserver.port.field.maxchars = 5;
+
+ s_specifyserver.go.generic.type = MTYPE_BITMAP;
+ s_specifyserver.go.generic.name = SPECIFYSERVER_FIGHT0;
+ s_specifyserver.go.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_specifyserver.go.generic.callback = SpecifyServer_Event;
+ s_specifyserver.go.generic.id = ID_SPECIFYSERVERGO;
+ s_specifyserver.go.generic.x = 640;
+ s_specifyserver.go.generic.y = 480-64;
+ s_specifyserver.go.width = 128;
+ s_specifyserver.go.height = 64;
+ s_specifyserver.go.focuspic = SPECIFYSERVER_FIGHT1;
+
+ s_specifyserver.back.generic.type = MTYPE_BITMAP;
+ s_specifyserver.back.generic.name = SPECIFYSERVER_BACK0;
+ s_specifyserver.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_specifyserver.back.generic.callback = SpecifyServer_Event;
+ s_specifyserver.back.generic.id = ID_SPECIFYSERVERBACK;
+ s_specifyserver.back.generic.x = 0;
+ s_specifyserver.back.generic.y = 480-64;
+ s_specifyserver.back.width = 128;
+ s_specifyserver.back.height = 64;
+ s_specifyserver.back.focuspic = SPECIFYSERVER_BACK1;
+
+ Menu_AddItem( &s_specifyserver.menu, &s_specifyserver.banner );
+ Menu_AddItem( &s_specifyserver.menu, &s_specifyserver.framel );
+ Menu_AddItem( &s_specifyserver.menu, &s_specifyserver.framer );
+ Menu_AddItem( &s_specifyserver.menu, &s_specifyserver.domain );
+ Menu_AddItem( &s_specifyserver.menu, &s_specifyserver.port );
+ Menu_AddItem( &s_specifyserver.menu, &s_specifyserver.go );
+ Menu_AddItem( &s_specifyserver.menu, &s_specifyserver.back );
+
+ Com_sprintf( s_specifyserver.port.field.buffer, 6, "%i", 27960 );
+}
+
+/*
+=================
+SpecifyServer_Cache
+=================
+*/
+void SpecifyServer_Cache( void )
+{
+ int i;
+
+ // touch all our pics
+ for (i=0; ;i++)
+ {
+ if (!specifyserver_artlist[i])
+ break;
+ trap_R_RegisterShaderNoMip(specifyserver_artlist[i]);
+ }
+}
+
+/*
+=================
+UI_SpecifyServerMenu
+=================
+*/
+void UI_SpecifyServerMenu( void )
+{
+ SpecifyServer_MenuInit();
+ UI_PushMenu( &s_specifyserver.menu );
+}
+
diff --git a/code/q3_ui/ui_splevel.c b/code/q3_ui/ui_splevel.c
new file mode 100755
index 0000000..0c57500
--- /dev/null
+++ b/code/q3_ui/ui_splevel.c
@@ -0,0 +1,1008 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*
+=============================================================================
+
+SINGLE PLAYER LEVEL SELECT MENU
+
+=============================================================================
+*/
+
+#include "ui_local.h"
+
+
+#define ART_LEVELFRAME_FOCUS "menu/art/maps_select"
+#define ART_LEVELFRAME_SELECTED "menu/art/maps_selected"
+#define ART_ARROW "menu/art/narrow_0"
+#define ART_ARROW_FOCUS "menu/art/narrow_1"
+#define ART_MAP_UNKNOWN "menu/art/unknownmap"
+#define ART_MAP_COMPLETE1 "menu/art/level_complete1"
+#define ART_MAP_COMPLETE2 "menu/art/level_complete2"
+#define ART_MAP_COMPLETE3 "menu/art/level_complete3"
+#define ART_MAP_COMPLETE4 "menu/art/level_complete4"
+#define ART_MAP_COMPLETE5 "menu/art/level_complete5"
+#define ART_BACK0 "menu/art/back_0"
+#define ART_BACK1 "menu/art/back_1"
+#define ART_FIGHT0 "menu/art/fight_0"
+#define ART_FIGHT1 "menu/art/fight_1"
+#define ART_RESET0 "menu/art/reset_0"
+#define ART_RESET1 "menu/art/reset_1"
+#define ART_CUSTOM0 "menu/art/skirmish_0"
+#define ART_CUSTOM1 "menu/art/skirmish_1"
+
+#define ID_LEFTARROW 10
+#define ID_PICTURE0 11
+#define ID_PICTURE1 12
+#define ID_PICTURE2 13
+#define ID_PICTURE3 14
+#define ID_RIGHTARROW 15
+#define ID_PLAYERPIC 16
+#define ID_AWARD1 17
+#define ID_AWARD2 18
+#define ID_AWARD3 19
+#define ID_AWARD4 20
+#define ID_AWARD5 21
+#define ID_AWARD6 22
+#define ID_BACK 23
+#define ID_RESET 24
+#define ID_CUSTOM 25
+#define ID_NEXT 26
+
+#define PLAYER_Y 314
+#define AWARDS_Y (PLAYER_Y + 26)
+
+
+typedef struct {
+ menuframework_s menu;
+ menutext_s item_banner;
+ menubitmap_s item_leftarrow;
+ menubitmap_s item_maps[4];
+ menubitmap_s item_rightarrow;
+ menubitmap_s item_player;
+ menubitmap_s item_awards[6];
+ menubitmap_s item_back;
+ menubitmap_s item_reset;
+ menubitmap_s item_custom;
+ menubitmap_s item_next;
+ menubitmap_s item_null;
+
+ qboolean reinit;
+
+ const char * selectedArenaInfo;
+ int numMaps;
+ char levelPicNames[4][MAX_QPATH];
+ char levelNames[4][16];
+ int levelScores[4];
+ int levelScoresSkill[4];
+ qhandle_t levelSelectedPic;
+ qhandle_t levelFocusPic;
+ qhandle_t levelCompletePic[5];
+
+ char playerModel[MAX_QPATH];
+ char playerPicName[MAX_QPATH];
+ int awardLevels[6];
+ sfxHandle_t awardSounds[6];
+
+ int numBots;
+ qhandle_t botPics[7];
+ char botNames[7][10];
+} levelMenuInfo_t;
+
+static levelMenuInfo_t levelMenuInfo;
+
+static int selectedArenaSet;
+static int selectedArena;
+static int currentSet;
+static int currentGame;
+static int trainingTier;
+static int finalTier;
+static int minTier;
+static int maxTier;
+
+
+/*
+=================
+PlayerIcon
+=================
+*/
+static void PlayerIcon( const char *modelAndSkin, char *iconName, int iconNameMaxSize ) {
+ char *skin;
+ char model[MAX_QPATH];
+
+ Q_strncpyz( model, modelAndSkin, sizeof(model));
+ skin = Q_strrchr( model, '/' );
+ if ( skin ) {
+ *skin++ = '\0';
+ }
+ else {
+ skin = "default";
+ }
+
+ Com_sprintf(iconName, iconNameMaxSize, "models/players/%s/icon_%s.tga", model, skin );
+
+ if( !trap_R_RegisterShaderNoMip( iconName ) && Q_stricmp( skin, "default" ) != 0 ) {
+ Com_sprintf(iconName, iconNameMaxSize, "models/players/%s/icon_default.tga", model );
+ }
+}
+
+
+/*
+=================
+PlayerIconhandle
+=================
+*/
+static qhandle_t PlayerIconHandle( const char *modelAndSkin ) {
+ char iconName[MAX_QPATH];
+
+ PlayerIcon( modelAndSkin, iconName, sizeof(iconName) );
+ return trap_R_RegisterShaderNoMip( iconName );
+}
+
+
+/*
+=================
+UI_SPLevelMenu_SetBots
+=================
+*/
+static void UI_SPLevelMenu_SetBots( void ) {
+ char *p;
+ char *bot;
+ char *botInfo;
+ char bots[MAX_INFO_STRING];
+
+ levelMenuInfo.numBots = 0;
+ if ( selectedArenaSet > currentSet ) {
+ return;
+ }
+
+ Q_strncpyz( bots, Info_ValueForKey( levelMenuInfo.selectedArenaInfo, "bots" ), sizeof(bots) );
+
+ p = &bots[0];
+ while( *p && levelMenuInfo.numBots < 7 ) {
+ //skip spaces
+ while( *p && *p == ' ' ) {
+ p++;
+ }
+ if( !p ) {
+ break;
+ }
+
+ // mark start of bot name
+ bot = p;
+
+ // skip until space of null
+ while( *p && *p != ' ' ) {
+ p++;
+ }
+ if( *p ) {
+ *p++ = 0;
+ }
+
+ botInfo = UI_GetBotInfoByName( bot );
+ if( botInfo ) {
+ levelMenuInfo.botPics[levelMenuInfo.numBots] = PlayerIconHandle( Info_ValueForKey( botInfo, "model" ) );
+ Q_strncpyz( levelMenuInfo.botNames[levelMenuInfo.numBots], Info_ValueForKey( botInfo, "name" ), 10 );
+ }
+ else {
+ levelMenuInfo.botPics[levelMenuInfo.numBots] = 0;
+ Q_strncpyz( levelMenuInfo.botNames[levelMenuInfo.numBots], bot, 10 );
+ }
+ Q_CleanStr( levelMenuInfo.botNames[levelMenuInfo.numBots] );
+ levelMenuInfo.numBots++;
+ }
+}
+
+
+/*
+=================
+UI_SPLevelMenu_SetMenuItems
+=================
+*/
+static void UI_SPLevelMenu_SetMenuArena( int n, int level, const char *arenaInfo ) {
+ char map[MAX_QPATH];
+
+ Q_strncpyz( map, Info_ValueForKey( arenaInfo, "map" ), sizeof(map) );
+
+ Q_strncpyz( levelMenuInfo.levelNames[n], map, sizeof(levelMenuInfo.levelNames[n]) );
+ Q_strupr( levelMenuInfo.levelNames[n] );
+
+ UI_GetBestScore( level, &levelMenuInfo.levelScores[n], &levelMenuInfo.levelScoresSkill[n] );
+ if( levelMenuInfo.levelScores[n] > 8 ) {
+ levelMenuInfo.levelScores[n] = 8;
+ }
+
+ strcpy( levelMenuInfo.levelPicNames[n], va( "levelshots/%s.tga", map ) );
+ if( !trap_R_RegisterShaderNoMip( levelMenuInfo.levelPicNames[n] ) ) {
+ strcpy( levelMenuInfo.levelPicNames[n], ART_MAP_UNKNOWN );
+ }
+ levelMenuInfo.item_maps[n].shader = 0;
+ if ( selectedArenaSet > currentSet ) {
+ levelMenuInfo.item_maps[n].generic.flags |= QMF_GRAYED;
+ }
+ else {
+ levelMenuInfo.item_maps[n].generic.flags &= ~QMF_GRAYED;
+ }
+
+ levelMenuInfo.item_maps[n].generic.flags &= ~QMF_INACTIVE;
+}
+
+static void UI_SPLevelMenu_SetMenuItems( void ) {
+ int n;
+ int level;
+ const char *arenaInfo;
+
+ if ( selectedArenaSet > currentSet ) {
+ selectedArena = -1;
+ }
+ else if ( selectedArena == -1 ) {
+ selectedArena = 0;
+ }
+
+ if( selectedArenaSet == trainingTier || selectedArenaSet == finalTier ) {
+ selectedArena = 0;
+ }
+
+ if( selectedArena != -1 ) {
+ trap_Cvar_SetValue( "ui_spSelection", selectedArenaSet * ARENAS_PER_TIER + selectedArena );
+ }
+
+ if( selectedArenaSet == trainingTier ) {
+ arenaInfo = UI_GetSpecialArenaInfo( "training" );
+ level = atoi( Info_ValueForKey( arenaInfo, "num" ) );
+ UI_SPLevelMenu_SetMenuArena( 0, level, arenaInfo );
+ levelMenuInfo.selectedArenaInfo = arenaInfo;
+
+ levelMenuInfo.item_maps[0].generic.x = 256;
+ Bitmap_Init( &levelMenuInfo.item_maps[0] );
+ levelMenuInfo.item_maps[0].generic.bottom += 32;
+ levelMenuInfo.numMaps = 1;
+
+ levelMenuInfo.item_maps[1].generic.flags |= QMF_INACTIVE;
+ levelMenuInfo.item_maps[2].generic.flags |= QMF_INACTIVE;
+ levelMenuInfo.item_maps[3].generic.flags |= QMF_INACTIVE;
+ levelMenuInfo.levelPicNames[1][0] = 0;
+ levelMenuInfo.levelPicNames[2][0] = 0;
+ levelMenuInfo.levelPicNames[3][0] = 0;
+ levelMenuInfo.item_maps[1].shader = 0;
+ levelMenuInfo.item_maps[2].shader = 0;
+ levelMenuInfo.item_maps[3].shader = 0;
+ }
+ else if( selectedArenaSet == finalTier ) {
+ arenaInfo = UI_GetSpecialArenaInfo( "final" );
+ level = atoi( Info_ValueForKey( arenaInfo, "num" ) );
+ UI_SPLevelMenu_SetMenuArena( 0, level, arenaInfo );
+ levelMenuInfo.selectedArenaInfo = arenaInfo;
+
+ levelMenuInfo.item_maps[0].generic.x = 256;
+ Bitmap_Init( &levelMenuInfo.item_maps[0] );
+ levelMenuInfo.item_maps[0].generic.bottom += 32;
+ levelMenuInfo.numMaps = 1;
+
+ levelMenuInfo.item_maps[1].generic.flags |= QMF_INACTIVE;
+ levelMenuInfo.item_maps[2].generic.flags |= QMF_INACTIVE;
+ levelMenuInfo.item_maps[3].generic.flags |= QMF_INACTIVE;
+ levelMenuInfo.levelPicNames[1][0] = 0;
+ levelMenuInfo.levelPicNames[2][0] = 0;
+ levelMenuInfo.levelPicNames[3][0] = 0;
+ levelMenuInfo.item_maps[1].shader = 0;
+ levelMenuInfo.item_maps[2].shader = 0;
+ levelMenuInfo.item_maps[3].shader = 0;
+ }
+ else {
+ levelMenuInfo.item_maps[0].generic.x = 46;
+ Bitmap_Init( &levelMenuInfo.item_maps[0] );
+ levelMenuInfo.item_maps[0].generic.bottom += 18;
+ levelMenuInfo.numMaps = 4;
+
+ for ( n = 0; n < 4; n++ ) {
+ level = selectedArenaSet * ARENAS_PER_TIER + n;
+ arenaInfo = UI_GetArenaInfoByNumber( level );
+ UI_SPLevelMenu_SetMenuArena( n, level, arenaInfo );
+ }
+
+ if( selectedArena != -1 ) {
+ levelMenuInfo.selectedArenaInfo = UI_GetArenaInfoByNumber( selectedArenaSet * ARENAS_PER_TIER + selectedArena );
+ }
+ }
+
+ // enable/disable arrows when they are valid/invalid
+ if ( selectedArenaSet == minTier ) {
+ levelMenuInfo.item_leftarrow.generic.flags |= ( QMF_INACTIVE | QMF_HIDDEN );
+ }
+ else {
+ levelMenuInfo.item_leftarrow.generic.flags &= ~( QMF_INACTIVE | QMF_HIDDEN );
+ }
+
+ if ( selectedArenaSet == maxTier ) {
+ levelMenuInfo.item_rightarrow.generic.flags |= ( QMF_INACTIVE | QMF_HIDDEN );
+ }
+ else {
+ levelMenuInfo.item_rightarrow.generic.flags &= ~( QMF_INACTIVE | QMF_HIDDEN );
+ }
+
+ UI_SPLevelMenu_SetBots();
+}
+
+
+/*
+=================
+UI_SPLevelMenu_ResetEvent
+=================
+*/
+static void UI_SPLevelMenu_ResetDraw( void ) {
+ UI_DrawProportionalString( SCREEN_WIDTH/2, 356 + PROP_HEIGHT * 0, "WARNING: This resets all of the", UI_CENTER|UI_SMALLFONT, color_yellow );
+ UI_DrawProportionalString( SCREEN_WIDTH/2, 356 + PROP_HEIGHT * 1, "single player game variables.", UI_CENTER|UI_SMALLFONT, color_yellow );
+ UI_DrawProportionalString( SCREEN_WIDTH/2, 356 + PROP_HEIGHT * 2, "Do this only if you want to", UI_CENTER|UI_SMALLFONT, color_yellow );
+ UI_DrawProportionalString( SCREEN_WIDTH/2, 356 + PROP_HEIGHT * 3, "start over from the beginning.", UI_CENTER|UI_SMALLFONT, color_yellow );
+}
+
+static void UI_SPLevelMenu_ResetAction( qboolean result ) {
+ if( !result ) {
+ return;
+ }
+
+ // clear game variables
+ UI_NewGame();
+ trap_Cvar_SetValue( "ui_spSelection", -4 );
+
+ // make the level select menu re-initialize
+ UI_PopMenu();
+ UI_SPLevelMenu();
+}
+
+static void UI_SPLevelMenu_ResetEvent( void* ptr, int event )
+{
+ if (event != QM_ACTIVATED) {
+ return;
+ }
+
+ UI_ConfirmMenu( "RESET GAME?", UI_SPLevelMenu_ResetDraw, UI_SPLevelMenu_ResetAction );
+}
+
+
+/*
+=================
+UI_SPLevelMenu_LevelEvent
+=================
+*/
+static void UI_SPLevelMenu_LevelEvent( void* ptr, int notification ) {
+ if (notification != QM_ACTIVATED) {
+ return;
+ }
+
+ if ( selectedArenaSet == trainingTier || selectedArenaSet == finalTier ) {
+ return;
+ }
+
+ selectedArena = ((menucommon_s*)ptr)->id - ID_PICTURE0;
+ levelMenuInfo.selectedArenaInfo = UI_GetArenaInfoByNumber( selectedArenaSet * ARENAS_PER_TIER + selectedArena );
+ UI_SPLevelMenu_SetBots();
+
+ trap_Cvar_SetValue( "ui_spSelection", selectedArenaSet * ARENAS_PER_TIER + selectedArena );
+}
+
+
+/*
+=================
+UI_SPLevelMenu_LeftArrowEvent
+=================
+*/
+static void UI_SPLevelMenu_LeftArrowEvent( void* ptr, int notification ) {
+ if (notification != QM_ACTIVATED) {
+ return;
+ }
+
+ if ( selectedArenaSet == minTier ) {
+ return;
+ }
+
+ selectedArenaSet--;
+ UI_SPLevelMenu_SetMenuItems();
+}
+
+
+/*
+=================
+UI_SPLevelMenu_RightArrowEvent
+=================
+*/
+static void UI_SPLevelMenu_RightArrowEvent( void* ptr, int notification ) {
+ if (notification != QM_ACTIVATED) {
+ return;
+ }
+
+ if ( selectedArenaSet == maxTier ) {
+ return;
+ }
+
+ selectedArenaSet++;
+ UI_SPLevelMenu_SetMenuItems();
+}
+
+
+/*
+=================
+UI_SPLevelMenu_PlayerEvent
+=================
+*/
+static void UI_SPLevelMenu_PlayerEvent( void* ptr, int notification ) {
+ if (notification != QM_ACTIVATED) {
+ return;
+ }
+
+ UI_PlayerSettingsMenu();
+}
+
+
+/*
+=================
+UI_SPLevelMenu_AwardEvent
+=================
+*/
+static void UI_SPLevelMenu_AwardEvent( void* ptr, int notification ) {
+ int n;
+
+ if (notification != QM_ACTIVATED) {
+ return;
+ }
+
+ n = ((menucommon_s*)ptr)->id - ID_AWARD1;
+ trap_S_StartLocalSound( levelMenuInfo.awardSounds[n], CHAN_ANNOUNCER );
+}
+
+
+/*
+=================
+UI_SPLevelMenu_NextEvent
+=================
+*/
+static void UI_SPLevelMenu_NextEvent( void* ptr, int notification ) {
+ if (notification != QM_ACTIVATED) {
+ return;
+ }
+
+ if ( selectedArenaSet > currentSet ) {
+ return;
+ }
+
+ if ( selectedArena == -1 ) {
+ selectedArena = 0;
+ }
+
+ UI_SPSkillMenu( levelMenuInfo.selectedArenaInfo );
+}
+
+
+/*
+=================
+UI_SPLevelMenu_BackEvent
+=================
+*/
+static void UI_SPLevelMenu_BackEvent( void* ptr, int notification ) {
+ if (notification != QM_ACTIVATED) {
+ return;
+ }
+
+ if ( selectedArena == -1 ) {
+ selectedArena = 0;
+ }
+
+ UI_PopMenu();
+}
+
+
+/*
+=================
+UI_SPLevelMenu_CustomEvent
+=================
+*/
+static void UI_SPLevelMenu_CustomEvent( void* ptr, int notification ) {
+ if (notification != QM_ACTIVATED) {
+ return;
+ }
+
+ UI_StartServerMenu( qfalse );
+}
+
+
+/*
+=================
+UI_SPLevelMenu_MenuDraw
+=================
+*/
+#define LEVEL_DESC_LEFT_MARGIN 332
+
+static void UI_SPLevelMenu_MenuDraw( void ) {
+ int n, i;
+ int x, y;
+ vec4_t color;
+ int level;
+// int fraglimit;
+ int pad;
+ char buf[MAX_INFO_VALUE];
+ char string[64];
+
+ if( levelMenuInfo.reinit ) {
+ UI_PopMenu();
+ UI_SPLevelMenu();
+ return;
+ }
+
+ // draw player name
+ trap_Cvar_VariableStringBuffer( "name", string, 32 );
+ Q_CleanStr( string );
+ UI_DrawProportionalString( 320, PLAYER_Y, string, UI_CENTER|UI_SMALLFONT, color_orange );
+
+ // check for model changes
+ trap_Cvar_VariableStringBuffer( "model", buf, sizeof(buf) );
+ if( Q_stricmp( buf, levelMenuInfo.playerModel ) != 0 ) {
+ Q_strncpyz( levelMenuInfo.playerModel, buf, sizeof(levelMenuInfo.playerModel) );
+ PlayerIcon( levelMenuInfo.playerModel, levelMenuInfo.playerPicName, sizeof(levelMenuInfo.playerPicName) );
+ levelMenuInfo.item_player.shader = 0;
+ }
+
+ // standard menu drawing
+ Menu_Draw( &levelMenuInfo.menu );
+
+ // draw player award levels
+ y = AWARDS_Y;
+ i = 0;
+ for( n = 0; n < 6; n++ ) {
+ level = levelMenuInfo.awardLevels[n];
+ if( level > 0 ) {
+ if( i & 1 ) {
+ x = 224 - (i - 1 ) / 2 * (48 + 16);
+ }
+ else {
+ x = 368 + i / 2 * (48 + 16);
+ }
+ i++;
+
+ if( level == 1 ) {
+ continue;
+ }
+
+ if( level >= 1000000 ) {
+ Com_sprintf( string, sizeof(string), "%im", level / 1000000 );
+ }
+ else if( level >= 1000 ) {
+ Com_sprintf( string, sizeof(string), "%ik", level / 1000 );
+ }
+ else {
+ Com_sprintf( string, sizeof(string), "%i", level );
+ }
+
+ UI_DrawString( x + 24, y + 48, string, UI_CENTER, color_yellow );
+ }
+ }
+
+ UI_DrawProportionalString( 18, 38, va( "Tier %i", selectedArenaSet + 1 ), UI_LEFT|UI_SMALLFONT, color_orange );
+
+ for ( n = 0; n < levelMenuInfo.numMaps; n++ ) {
+ x = levelMenuInfo.item_maps[n].generic.x;
+ y = levelMenuInfo.item_maps[n].generic.y;
+ UI_FillRect( x, y + 96, 128, 18, color_black );
+ }
+
+ if ( selectedArenaSet > currentSet ) {
+ UI_DrawProportionalString( 320, 216, "ACCESS DENIED", UI_CENTER|UI_BIGFONT, color_red );
+ return;
+ }
+
+ // show levelshots for levels of current tier
+ Vector4Copy( color_white, color );
+ color[3] = 0.5+0.5*sin(uis.realtime/PULSE_DIVISOR);
+ for ( n = 0; n < levelMenuInfo.numMaps; n++ ) {
+ x = levelMenuInfo.item_maps[n].generic.x;
+ y = levelMenuInfo.item_maps[n].generic.y;
+
+ UI_DrawString( x + 64, y + 96, levelMenuInfo.levelNames[n], UI_CENTER|UI_SMALLFONT, color_orange );
+
+ if( levelMenuInfo.levelScores[n] == 1 ) {
+ UI_DrawHandlePic( x, y, 128, 96, levelMenuInfo.levelCompletePic[levelMenuInfo.levelScoresSkill[n] - 1] );
+ }
+
+ if ( n == selectedArena ) {
+ if( Menu_ItemAtCursor( &levelMenuInfo.menu ) == &levelMenuInfo.item_maps[n] ) {
+ trap_R_SetColor( color );
+ }
+ UI_DrawHandlePic( x-1, y-1, 130, 130 - 14, levelMenuInfo.levelSelectedPic );
+ trap_R_SetColor( NULL );
+ }
+ else if( Menu_ItemAtCursor( &levelMenuInfo.menu ) == &levelMenuInfo.item_maps[n] ) {
+ trap_R_SetColor( color );
+ UI_DrawHandlePic( x-31, y-30, 256, 256-27, levelMenuInfo.levelFocusPic);
+ trap_R_SetColor( NULL );
+ }
+ }
+
+ // show map name and long name of selected level
+ y = 192;
+ Q_strncpyz( buf, Info_ValueForKey( levelMenuInfo.selectedArenaInfo, "map" ), 20 );
+ Q_strupr( buf );
+ Com_sprintf( string, sizeof(string), "%s: %s", buf, Info_ValueForKey( levelMenuInfo.selectedArenaInfo, "longname" ) );
+ UI_DrawProportionalString( 320, y, string, UI_CENTER|UI_SMALLFONT, color_orange );
+
+// fraglimit = atoi( Info_ValueForKey( levelMenuInfo.selectedArenaInfo, "fraglimit" ) );
+// UI_DrawString( 18, 212, va("Frags %i", fraglimit) , UI_LEFT|UI_SMALLFONT, color_orange );
+
+ // draw bot opponents
+ y += 24;
+ pad = (7 - levelMenuInfo.numBots) * (64 + 26) / 2;
+ for( n = 0; n < levelMenuInfo.numBots; n++ ) {
+ x = 18 + pad + (64 + 26) * n;
+ if( levelMenuInfo.botPics[n] ) {
+ UI_DrawHandlePic( x, y, 64, 64, levelMenuInfo.botPics[n]);
+ }
+ else {
+ UI_FillRect( x, y, 64, 64, color_black );
+ UI_DrawProportionalString( x+22, y+18, "?", UI_BIGFONT, color_orange );
+ }
+ UI_DrawString( x, y + 64, levelMenuInfo.botNames[n], UI_SMALLFONT|UI_LEFT, color_orange );
+ }
+}
+
+
+/*
+=================
+UI_SPLevelMenu_Cache
+=================
+*/
+void UI_SPLevelMenu_Cache( void ) {
+ int n;
+
+ trap_R_RegisterShaderNoMip( ART_LEVELFRAME_FOCUS );
+ trap_R_RegisterShaderNoMip( ART_LEVELFRAME_SELECTED );
+ trap_R_RegisterShaderNoMip( ART_ARROW );
+ trap_R_RegisterShaderNoMip( ART_ARROW_FOCUS );
+ trap_R_RegisterShaderNoMip( ART_MAP_UNKNOWN );
+ trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE1 );
+ trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE2 );
+ trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE3 );
+ trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE4 );
+ trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE5 );
+ trap_R_RegisterShaderNoMip( ART_BACK0 );
+ trap_R_RegisterShaderNoMip( ART_BACK1 );
+ trap_R_RegisterShaderNoMip( ART_FIGHT0 );
+ trap_R_RegisterShaderNoMip( ART_FIGHT1 );
+ trap_R_RegisterShaderNoMip( ART_RESET0 );
+ trap_R_RegisterShaderNoMip( ART_RESET1 );
+ trap_R_RegisterShaderNoMip( ART_CUSTOM0 );
+ trap_R_RegisterShaderNoMip( ART_CUSTOM1 );
+
+ for( n = 0; n < 6; n++ ) {
+ trap_R_RegisterShaderNoMip( ui_medalPicNames[n] );
+ levelMenuInfo.awardSounds[n] = trap_S_RegisterSound( ui_medalSounds[n], qfalse );
+ }
+
+ levelMenuInfo.levelSelectedPic = trap_R_RegisterShaderNoMip( ART_LEVELFRAME_SELECTED );
+ levelMenuInfo.levelFocusPic = trap_R_RegisterShaderNoMip( ART_LEVELFRAME_FOCUS );
+ levelMenuInfo.levelCompletePic[0] = trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE1 );
+ levelMenuInfo.levelCompletePic[1] = trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE2 );
+ levelMenuInfo.levelCompletePic[2] = trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE3 );
+ levelMenuInfo.levelCompletePic[3] = trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE4 );
+ levelMenuInfo.levelCompletePic[4] = trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE5 );
+}
+
+
+/*
+=================
+UI_SPLevelMenu_Init
+=================
+*/
+static void UI_SPLevelMenu_Init( void ) {
+ int skill;
+ int n;
+ int x, y;
+ int count;
+ char buf[MAX_QPATH];
+
+ skill = (int)trap_Cvar_VariableValue( "g_spSkill" );
+ if( skill < 1 || skill > 5 ) {
+ trap_Cvar_Set( "g_spSkill", "2" );
+ skill = 2;
+ }
+
+ memset( &levelMenuInfo, 0, sizeof(levelMenuInfo) );
+ levelMenuInfo.menu.fullscreen = qtrue;
+ levelMenuInfo.menu.wrapAround = qtrue;
+ levelMenuInfo.menu.draw = UI_SPLevelMenu_MenuDraw;
+
+ UI_SPLevelMenu_Cache();
+
+ levelMenuInfo.item_banner.generic.type = MTYPE_BTEXT;
+ levelMenuInfo.item_banner.generic.x = 320;
+ levelMenuInfo.item_banner.generic.y = 16;
+ levelMenuInfo.item_banner.string = "CHOOSE LEVEL";
+ levelMenuInfo.item_banner.color = color_red;
+ levelMenuInfo.item_banner.style = UI_CENTER;
+
+ levelMenuInfo.item_leftarrow.generic.type = MTYPE_BITMAP;
+ levelMenuInfo.item_leftarrow.generic.name = ART_ARROW;
+ levelMenuInfo.item_leftarrow.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ levelMenuInfo.item_leftarrow.generic.x = 18;
+ levelMenuInfo.item_leftarrow.generic.y = 64;
+ levelMenuInfo.item_leftarrow.generic.callback = UI_SPLevelMenu_LeftArrowEvent;
+ levelMenuInfo.item_leftarrow.generic.id = ID_LEFTARROW;
+ levelMenuInfo.item_leftarrow.width = 16;
+ levelMenuInfo.item_leftarrow.height = 114;
+ levelMenuInfo.item_leftarrow.focuspic = ART_ARROW_FOCUS;
+
+ levelMenuInfo.item_maps[0].generic.type = MTYPE_BITMAP;
+ levelMenuInfo.item_maps[0].generic.name = levelMenuInfo.levelPicNames[0];
+ levelMenuInfo.item_maps[0].generic.flags = QMF_LEFT_JUSTIFY;
+ levelMenuInfo.item_maps[0].generic.x = 46;
+ levelMenuInfo.item_maps[0].generic.y = 64;
+ levelMenuInfo.item_maps[0].generic.id = ID_PICTURE0;
+ levelMenuInfo.item_maps[0].generic.callback = UI_SPLevelMenu_LevelEvent;
+ levelMenuInfo.item_maps[0].width = 128;
+ levelMenuInfo.item_maps[0].height = 96;
+
+ levelMenuInfo.item_maps[1].generic.type = MTYPE_BITMAP;
+ levelMenuInfo.item_maps[1].generic.name = levelMenuInfo.levelPicNames[1];
+ levelMenuInfo.item_maps[1].generic.flags = QMF_LEFT_JUSTIFY;
+ levelMenuInfo.item_maps[1].generic.x = 186;
+ levelMenuInfo.item_maps[1].generic.y = 64;
+ levelMenuInfo.item_maps[1].generic.id = ID_PICTURE1;
+ levelMenuInfo.item_maps[1].generic.callback = UI_SPLevelMenu_LevelEvent;
+ levelMenuInfo.item_maps[1].width = 128;
+ levelMenuInfo.item_maps[1].height = 96;
+
+ levelMenuInfo.item_maps[2].generic.type = MTYPE_BITMAP;
+ levelMenuInfo.item_maps[2].generic.name = levelMenuInfo.levelPicNames[2];
+ levelMenuInfo.item_maps[2].generic.flags = QMF_LEFT_JUSTIFY;
+ levelMenuInfo.item_maps[2].generic.x = 326;
+ levelMenuInfo.item_maps[2].generic.y = 64;
+ levelMenuInfo.item_maps[2].generic.id = ID_PICTURE2;
+ levelMenuInfo.item_maps[2].generic.callback = UI_SPLevelMenu_LevelEvent;
+ levelMenuInfo.item_maps[2].width = 128;
+ levelMenuInfo.item_maps[2].height = 96;
+
+ levelMenuInfo.item_maps[3].generic.type = MTYPE_BITMAP;
+ levelMenuInfo.item_maps[3].generic.name = levelMenuInfo.levelPicNames[3];
+ levelMenuInfo.item_maps[3].generic.flags = QMF_LEFT_JUSTIFY;
+ levelMenuInfo.item_maps[3].generic.x = 466;
+ levelMenuInfo.item_maps[3].generic.y = 64;
+ levelMenuInfo.item_maps[3].generic.id = ID_PICTURE3;
+ levelMenuInfo.item_maps[3].generic.callback = UI_SPLevelMenu_LevelEvent;
+ levelMenuInfo.item_maps[3].width = 128;
+ levelMenuInfo.item_maps[3].height = 96;
+
+ levelMenuInfo.item_rightarrow.generic.type = MTYPE_BITMAP;
+ levelMenuInfo.item_rightarrow.generic.name = ART_ARROW;
+ levelMenuInfo.item_rightarrow.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ levelMenuInfo.item_rightarrow.generic.x = 606;
+ levelMenuInfo.item_rightarrow.generic.y = 64;
+ levelMenuInfo.item_rightarrow.generic.callback = UI_SPLevelMenu_RightArrowEvent;
+ levelMenuInfo.item_rightarrow.generic.id = ID_RIGHTARROW;
+ levelMenuInfo.item_rightarrow.width = -16;
+ levelMenuInfo.item_rightarrow.height = 114;
+ levelMenuInfo.item_rightarrow.focuspic = ART_ARROW_FOCUS;
+
+ trap_Cvar_VariableStringBuffer( "model", levelMenuInfo.playerModel, sizeof(levelMenuInfo.playerModel) );
+ PlayerIcon( levelMenuInfo.playerModel, levelMenuInfo.playerPicName, sizeof(levelMenuInfo.playerPicName) );
+ levelMenuInfo.item_player.generic.type = MTYPE_BITMAP;
+ levelMenuInfo.item_player.generic.name = levelMenuInfo.playerPicName;
+ levelMenuInfo.item_player.generic.flags = QMF_LEFT_JUSTIFY|QMF_MOUSEONLY;
+ levelMenuInfo.item_player.generic.x = 288;
+ levelMenuInfo.item_player.generic.y = AWARDS_Y;
+ levelMenuInfo.item_player.generic.id = ID_PLAYERPIC;
+ levelMenuInfo.item_player.generic.callback = UI_SPLevelMenu_PlayerEvent;
+ levelMenuInfo.item_player.width = 64;
+ levelMenuInfo.item_player.height = 64;
+
+ for( n = 0; n < 6; n++ ) {
+ levelMenuInfo.awardLevels[n] = UI_GetAwardLevel( n );
+ }
+ levelMenuInfo.awardLevels[AWARD_FRAGS] = 100 * (levelMenuInfo.awardLevels[AWARD_FRAGS] / 100);
+
+ y = AWARDS_Y;
+ count = 0;
+ for( n = 0; n < 6; n++ ) {
+ if( levelMenuInfo.awardLevels[n] ) {
+ if( count & 1 ) {
+ x = 224 - (count - 1 ) / 2 * (48 + 16);
+ }
+ else {
+ x = 368 + count / 2 * (48 + 16);
+ }
+
+ levelMenuInfo.item_awards[count].generic.type = MTYPE_BITMAP;
+ levelMenuInfo.item_awards[count].generic.name = ui_medalPicNames[n];
+ levelMenuInfo.item_awards[count].generic.flags = QMF_LEFT_JUSTIFY|QMF_SILENT|QMF_MOUSEONLY;
+ levelMenuInfo.item_awards[count].generic.x = x;
+ levelMenuInfo.item_awards[count].generic.y = y;
+ levelMenuInfo.item_awards[count].generic.id = ID_AWARD1 + n;
+ levelMenuInfo.item_awards[count].generic.callback = UI_SPLevelMenu_AwardEvent;
+ levelMenuInfo.item_awards[count].width = 48;
+ levelMenuInfo.item_awards[count].height = 48;
+ count++;
+ }
+ }
+
+ levelMenuInfo.item_back.generic.type = MTYPE_BITMAP;
+ levelMenuInfo.item_back.generic.name = ART_BACK0;
+ levelMenuInfo.item_back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ levelMenuInfo.item_back.generic.x = 0;
+ levelMenuInfo.item_back.generic.y = 480-64;
+ levelMenuInfo.item_back.generic.callback = UI_SPLevelMenu_BackEvent;
+ levelMenuInfo.item_back.generic.id = ID_BACK;
+ levelMenuInfo.item_back.width = 128;
+ levelMenuInfo.item_back.height = 64;
+ levelMenuInfo.item_back.focuspic = ART_BACK1;
+
+ levelMenuInfo.item_reset.generic.type = MTYPE_BITMAP;
+ levelMenuInfo.item_reset.generic.name = ART_RESET0;
+ levelMenuInfo.item_reset.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ levelMenuInfo.item_reset.generic.x = 170;
+ levelMenuInfo.item_reset.generic.y = 480-64;
+ levelMenuInfo.item_reset.generic.callback = UI_SPLevelMenu_ResetEvent;
+ levelMenuInfo.item_reset.generic.id = ID_RESET;
+ levelMenuInfo.item_reset.width = 128;
+ levelMenuInfo.item_reset.height = 64;
+ levelMenuInfo.item_reset.focuspic = ART_RESET1;
+
+ levelMenuInfo.item_custom.generic.type = MTYPE_BITMAP;
+ levelMenuInfo.item_custom.generic.name = ART_CUSTOM0;
+ levelMenuInfo.item_custom.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ levelMenuInfo.item_custom.generic.x = 342;
+ levelMenuInfo.item_custom.generic.y = 480-64;
+ levelMenuInfo.item_custom.generic.callback = UI_SPLevelMenu_CustomEvent;
+ levelMenuInfo.item_custom.generic.id = ID_CUSTOM;
+ levelMenuInfo.item_custom.width = 128;
+ levelMenuInfo.item_custom.height = 64;
+ levelMenuInfo.item_custom.focuspic = ART_CUSTOM1;
+
+ levelMenuInfo.item_next.generic.type = MTYPE_BITMAP;
+ levelMenuInfo.item_next.generic.name = ART_FIGHT0;
+ levelMenuInfo.item_next.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ levelMenuInfo.item_next.generic.x = 640;
+ levelMenuInfo.item_next.generic.y = 480-64;
+ levelMenuInfo.item_next.generic.callback = UI_SPLevelMenu_NextEvent;
+ levelMenuInfo.item_next.generic.id = ID_NEXT;
+ levelMenuInfo.item_next.width = 128;
+ levelMenuInfo.item_next.height = 64;
+ levelMenuInfo.item_next.focuspic = ART_FIGHT1;
+
+ levelMenuInfo.item_null.generic.type = MTYPE_BITMAP;
+ levelMenuInfo.item_null.generic.flags = QMF_LEFT_JUSTIFY|QMF_MOUSEONLY|QMF_SILENT;
+ levelMenuInfo.item_null.generic.x = 0;
+ levelMenuInfo.item_null.generic.y = 0;
+ levelMenuInfo.item_null.width = 640;
+ levelMenuInfo.item_null.height = 480;
+
+ Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_banner );
+
+ Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_leftarrow );
+ Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_maps[0] );
+ Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_maps[1] );
+ Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_maps[2] );
+ Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_maps[3] );
+ levelMenuInfo.item_maps[0].generic.bottom += 18;
+ levelMenuInfo.item_maps[1].generic.bottom += 18;
+ levelMenuInfo.item_maps[2].generic.bottom += 18;
+ levelMenuInfo.item_maps[3].generic.bottom += 18;
+ Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_rightarrow );
+
+ Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_player );
+
+ for( n = 0; n < count; n++ ) {
+ Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_awards[n] );
+ }
+ Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_back );
+ Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_reset );
+ Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_custom );
+ Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_next );
+ Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_null );
+
+ trap_Cvar_VariableStringBuffer( "ui_spSelection", buf, sizeof(buf) );
+ if( *buf ) {
+ n = atoi( buf );
+ selectedArenaSet = n / ARENAS_PER_TIER;
+ selectedArena = n % ARENAS_PER_TIER;
+ }
+ else {
+ selectedArenaSet = currentSet;
+ selectedArena = currentGame;
+ }
+
+ UI_SPLevelMenu_SetMenuItems();
+}
+
+
+/*
+=================
+UI_SPLevelMenu
+=================
+*/
+void UI_SPLevelMenu( void ) {
+ int level;
+ int trainingLevel;
+ const char *arenaInfo;
+
+ trainingTier = -1;
+ arenaInfo = UI_GetSpecialArenaInfo( "training" );
+ if( arenaInfo ) {
+ minTier = trainingTier;
+ trainingLevel = atoi( Info_ValueForKey( arenaInfo, "num" ) );
+ }
+ else {
+ minTier = 0;
+ trainingLevel = -2;
+ }
+
+ finalTier = UI_GetNumSPTiers();
+ arenaInfo = UI_GetSpecialArenaInfo( "final" );
+ if( arenaInfo ) {
+ maxTier = finalTier;
+ }
+ else {
+ maxTier = finalTier - 1;
+ if( maxTier < minTier ) {
+ maxTier = minTier;
+ }
+ }
+
+ level = UI_GetCurrentGame();
+ if ( level == -1 ) {
+ level = UI_GetNumSPArenas() - 1;
+ if( maxTier == finalTier ) {
+ level++;
+ }
+ }
+
+ if( level == trainingLevel ) {
+ currentSet = -1;
+ currentGame = 0;
+ }
+ else {
+ currentSet = level / ARENAS_PER_TIER;
+ currentGame = level % ARENAS_PER_TIER;
+ }
+
+ UI_SPLevelMenu_Init();
+ UI_PushMenu( &levelMenuInfo.menu );
+ Menu_SetCursorToItem( &levelMenuInfo.menu, &levelMenuInfo.item_next );
+}
+
+
+/*
+=================
+UI_SPLevelMenu_f
+=================
+*/
+void UI_SPLevelMenu_f( void ) {
+ trap_Key_SetCatcher( KEYCATCH_UI );
+ uis.menusp = 0;
+ UI_SPLevelMenu();
+}
+
+
+/*
+=================
+UI_SPLevelMenu_ReInit
+=================
+*/
+void UI_SPLevelMenu_ReInit( void ) {
+ levelMenuInfo.reinit = qtrue;
+}
diff --git a/code/q3_ui/ui_sppostgame.c b/code/q3_ui/ui_sppostgame.c
new file mode 100755
index 0000000..0f65af8
--- /dev/null
+++ b/code/q3_ui/ui_sppostgame.c
@@ -0,0 +1,644 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*
+=============================================================================
+
+SINGLE PLAYER POSTGAME MENU
+
+=============================================================================
+*/
+
+#include "ui_local.h"
+
+#define MAX_SCOREBOARD_CLIENTS 8
+
+#define AWARD_PRESENTATION_TIME 2000
+
+#define ART_MENU0 "menu/art/menu_0"
+#define ART_MENU1 "menu/art/menu_1"
+#define ART_REPLAY0 "menu/art/replay_0"
+#define ART_REPLAY1 "menu/art/replay_1"
+#define ART_NEXT0 "menu/art/next_0"
+#define ART_NEXT1 "menu/art/next_1"
+
+#define ID_AGAIN 10
+#define ID_NEXT 11
+#define ID_MENU 12
+
+typedef struct {
+ menuframework_s menu;
+ menubitmap_s item_again;
+ menubitmap_s item_next;
+ menubitmap_s item_menu;
+
+ int phase;
+ int ignoreKeysTime;
+ int starttime;
+ int scoreboardtime;
+ int serverId;
+
+ int clientNums[MAX_SCOREBOARD_CLIENTS];
+ int ranks[MAX_SCOREBOARD_CLIENTS];
+ int scores[MAX_SCOREBOARD_CLIENTS];
+
+ char placeNames[3][64];
+
+ int level;
+ int numClients;
+ int won;
+ int numAwards;
+ int awardsEarned[6];
+ int awardsLevels[6];
+ qboolean playedSound[6];
+ int lastTier;
+ sfxHandle_t winnerSound;
+} postgameMenuInfo_t;
+
+static postgameMenuInfo_t postgameMenuInfo;
+static char arenainfo[MAX_INFO_VALUE];
+
+char *ui_medalNames[] = {"Accuracy", "Impressive", "Excellent", "Gauntlet", "Frags", "Perfect"};
+char *ui_medalPicNames[] = {
+ "menu/medals/medal_accuracy",
+ "menu/medals/medal_impressive",
+ "menu/medals/medal_excellent",
+ "menu/medals/medal_gauntlet",
+ "menu/medals/medal_frags",
+ "menu/medals/medal_victory"
+};
+char *ui_medalSounds[] = {
+ "sound/feedback/accuracy.wav",
+ "sound/feedback/impressive_a.wav",
+ "sound/feedback/excellent_a.wav",
+ "sound/feedback/gauntlet.wav",
+ "sound/feedback/frags.wav",
+ "sound/feedback/perfect.wav"
+};
+
+
+/*
+=================
+UI_SPPostgameMenu_AgainEvent
+=================
+*/
+static void UI_SPPostgameMenu_AgainEvent( void* ptr, int event )
+{
+ if (event != QM_ACTIVATED) {
+ return;
+ }
+ UI_PopMenu();
+ trap_Cmd_ExecuteText( EXEC_APPEND, "map_restart 0\n" );
+}
+
+
+/*
+=================
+UI_SPPostgameMenu_NextEvent
+=================
+*/
+static void UI_SPPostgameMenu_NextEvent( void* ptr, int event ) {
+ int currentSet;
+ int levelSet;
+ int level;
+ int currentLevel;
+ const char *arenaInfo;
+
+ if (event != QM_ACTIVATED) {
+ return;
+ }
+ UI_PopMenu();
+
+ // handle specially if we just won the training map
+ if( postgameMenuInfo.won == 0 ) {
+ level = 0;
+ }
+ else {
+ level = postgameMenuInfo.level + 1;
+ }
+ levelSet = level / ARENAS_PER_TIER;
+
+ currentLevel = UI_GetCurrentGame();
+ if( currentLevel == -1 ) {
+ currentLevel = postgameMenuInfo.level;
+ }
+ currentSet = currentLevel / ARENAS_PER_TIER;
+
+ if( levelSet > currentSet || levelSet == UI_GetNumSPTiers() ) {
+ level = currentLevel;
+ }
+
+ arenaInfo = UI_GetArenaInfoByNumber( level );
+ if ( !arenaInfo ) {
+ return;
+ }
+
+ UI_SPArena_Start( arenaInfo );
+}
+
+
+/*
+=================
+UI_SPPostgameMenu_MenuEvent
+=================
+*/
+static void UI_SPPostgameMenu_MenuEvent( void* ptr, int event )
+{
+ if (event != QM_ACTIVATED) {
+ return;
+ }
+ UI_PopMenu();
+ trap_Cmd_ExecuteText( EXEC_APPEND, "disconnect; levelselect\n" );
+}
+
+
+/*
+=================
+UI_SPPostgameMenu_MenuKey
+=================
+*/
+static sfxHandle_t UI_SPPostgameMenu_MenuKey( int key ) {
+ if ( uis.realtime < postgameMenuInfo.ignoreKeysTime ) {
+ return 0;
+ }
+
+ if( postgameMenuInfo.phase == 1 ) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, "abort_podium\n" );
+ postgameMenuInfo.phase = 2;
+ postgameMenuInfo.starttime = uis.realtime;
+ postgameMenuInfo.ignoreKeysTime = uis.realtime + 250;
+ return 0;
+ }
+
+ if( postgameMenuInfo.phase == 2 ) {
+ postgameMenuInfo.phase = 3;
+ postgameMenuInfo.starttime = uis.realtime;
+ postgameMenuInfo.ignoreKeysTime = uis.realtime + 250;
+ return 0;
+ }
+
+ if( key == K_ESCAPE || key == K_MOUSE2 ) {
+ return 0;
+ }
+
+ return Menu_DefaultKey( &postgameMenuInfo.menu, key );
+}
+
+
+static int medalLocations[6] = {144, 448, 88, 504, 32, 560};
+
+static void UI_SPPostgameMenu_DrawAwardsMedals( int max ) {
+ int n;
+ int medal;
+ int amount;
+ int x, y;
+ char buf[16];
+
+ for( n = 0; n < max; n++ ) {
+ x = medalLocations[n];
+ y = 64;
+ medal = postgameMenuInfo.awardsEarned[n];
+ amount = postgameMenuInfo.awardsLevels[n];
+
+ UI_DrawNamedPic( x, y, 48, 48, ui_medalPicNames[medal] );
+
+ if( medal == AWARD_ACCURACY ) {
+ Com_sprintf( buf, sizeof(buf), "%i%%", amount );
+ }
+ else {
+ if( amount == 1 ) {
+ continue;
+ }
+ Com_sprintf( buf, sizeof(buf), "%i", amount );
+ }
+
+ UI_DrawString( x + 24, y + 52, buf, UI_CENTER, color_yellow );
+ }
+}
+
+
+static void UI_SPPostgameMenu_DrawAwardsPresentation( int timer ) {
+ int awardNum;
+ int atimer;
+ vec4_t color;
+
+ awardNum = timer / AWARD_PRESENTATION_TIME;
+ atimer = timer % AWARD_PRESENTATION_TIME;
+
+ color[0] = color[1] = color[2] = 1.0f;
+ color[3] = (float)( AWARD_PRESENTATION_TIME - atimer ) / (float)AWARD_PRESENTATION_TIME;
+ UI_DrawProportionalString( 320, 64, ui_medalNames[postgameMenuInfo.awardsEarned[awardNum]], UI_CENTER, color );
+
+ UI_SPPostgameMenu_DrawAwardsMedals( awardNum + 1 );
+
+ if( !postgameMenuInfo.playedSound[awardNum] ) {
+ postgameMenuInfo.playedSound[awardNum] = qtrue;
+ trap_S_StartLocalSound( trap_S_RegisterSound( ui_medalSounds[postgameMenuInfo.awardsEarned[awardNum]], qfalse ), CHAN_ANNOUNCER );
+ }
+}
+
+
+/*
+=================
+UI_SPPostgameMenu_MenuDrawScoreLine
+=================
+*/
+static void UI_SPPostgameMenu_MenuDrawScoreLine( int n, int y ) {
+ int rank;
+ char name[64];
+ char info[MAX_INFO_STRING];
+
+ if( n > (postgameMenuInfo.numClients + 1) ) {
+ n -= (postgameMenuInfo.numClients + 2);
+ }
+
+ if( n >= postgameMenuInfo.numClients ) {
+ return;
+ }
+
+ rank = postgameMenuInfo.ranks[n];
+ if( rank & RANK_TIED_FLAG ) {
+ UI_DrawString( 640 - 31 * SMALLCHAR_WIDTH, y, "(tie)", UI_LEFT|UI_SMALLFONT, color_white );
+ rank &= ~RANK_TIED_FLAG;
+ }
+ trap_GetConfigString( CS_PLAYERS + postgameMenuInfo.clientNums[n], info, MAX_INFO_STRING );
+ Q_strncpyz( name, Info_ValueForKey( info, "n" ), sizeof(name) );
+ Q_CleanStr( name );
+
+ UI_DrawString( 640 - 25 * SMALLCHAR_WIDTH, y, va( "#%i: %-16s %2i", rank + 1, name, postgameMenuInfo.scores[n] ), UI_LEFT|UI_SMALLFONT, color_white );
+}
+
+
+/*
+=================
+UI_SPPostgameMenu_MenuDraw
+=================
+*/
+static void UI_SPPostgameMenu_MenuDraw( void ) {
+ int timer;
+ int serverId;
+ int n;
+ char info[MAX_INFO_STRING];
+
+ trap_GetConfigString( CS_SYSTEMINFO, info, sizeof(info) );
+ serverId = atoi( Info_ValueForKey( info, "sv_serverid" ) );
+ if( serverId != postgameMenuInfo.serverId ) {
+ UI_PopMenu();
+ return;
+ }
+
+ // phase 1
+ if ( postgameMenuInfo.numClients > 2 ) {
+ UI_DrawProportionalString( 510, 480 - 64 - PROP_HEIGHT, postgameMenuInfo.placeNames[2], UI_CENTER, color_white );
+ }
+ UI_DrawProportionalString( 130, 480 - 64 - PROP_HEIGHT, postgameMenuInfo.placeNames[1], UI_CENTER, color_white );
+ UI_DrawProportionalString( 320, 480 - 64 - 2 * PROP_HEIGHT, postgameMenuInfo.placeNames[0], UI_CENTER, color_white );
+
+ if( postgameMenuInfo.phase == 1 ) {
+ timer = uis.realtime - postgameMenuInfo.starttime;
+
+ if( timer >= 1000 && postgameMenuInfo.winnerSound ) {
+ trap_S_StartLocalSound( postgameMenuInfo.winnerSound, CHAN_ANNOUNCER );
+ postgameMenuInfo.winnerSound = 0;
+ }
+
+ if( timer < 5000 ) {
+ return;
+ }
+ postgameMenuInfo.phase = 2;
+ postgameMenuInfo.starttime = uis.realtime;
+ }
+
+ // phase 2
+ if( postgameMenuInfo.phase == 2 ) {
+ timer = uis.realtime - postgameMenuInfo.starttime;
+ if( timer >= ( postgameMenuInfo.numAwards * AWARD_PRESENTATION_TIME ) ) {
+
+ if( timer < 5000 ) {
+ return;
+ }
+
+ postgameMenuInfo.phase = 3;
+ postgameMenuInfo.starttime = uis.realtime;
+ }
+ else {
+ UI_SPPostgameMenu_DrawAwardsPresentation( timer );
+ }
+ }
+
+ // phase 3
+ if( postgameMenuInfo.phase == 3 ) {
+ if( uis.demoversion ) {
+ if( postgameMenuInfo.won == 1 && UI_ShowTierVideo( 8 )) {
+ trap_Cvar_Set( "nextmap", "" );
+ trap_Cmd_ExecuteText( EXEC_APPEND, "disconnect; cinematic demoEnd.RoQ\n" );
+ return;
+ }
+ }
+ else if( postgameMenuInfo.won > -1 && UI_ShowTierVideo( postgameMenuInfo.won + 1 )) {
+ if( postgameMenuInfo.won == postgameMenuInfo.lastTier ) {
+ trap_Cvar_Set( "nextmap", "" );
+ trap_Cmd_ExecuteText( EXEC_APPEND, "disconnect; cinematic end.RoQ\n" );
+ return;
+ }
+
+ trap_Cvar_SetValue( "ui_spSelection", postgameMenuInfo.won * ARENAS_PER_TIER );
+ trap_Cvar_Set( "nextmap", "levelselect" );
+ trap_Cmd_ExecuteText( EXEC_APPEND, va( "disconnect; cinematic tier%i.RoQ\n", postgameMenuInfo.won + 1 ) );
+ return;
+ }
+
+ postgameMenuInfo.item_again.generic.flags &= ~QMF_INACTIVE;
+ postgameMenuInfo.item_next.generic.flags &= ~QMF_INACTIVE;
+ postgameMenuInfo.item_menu.generic.flags &= ~QMF_INACTIVE;
+
+ UI_SPPostgameMenu_DrawAwardsMedals( postgameMenuInfo.numAwards );
+
+ Menu_Draw( &postgameMenuInfo.menu );
+ }
+
+ // draw the scoreboard
+ if( !trap_Cvar_VariableValue( "ui_spScoreboard" ) ) {
+ return;
+ }
+
+ timer = uis.realtime - postgameMenuInfo.scoreboardtime;
+ if( postgameMenuInfo.numClients <= 3 ) {
+ n = 0;
+ }
+ else {
+ n = timer / 1500 % (postgameMenuInfo.numClients + 2);
+ }
+ UI_SPPostgameMenu_MenuDrawScoreLine( n, 0 );
+ UI_SPPostgameMenu_MenuDrawScoreLine( n + 1, 0 + SMALLCHAR_HEIGHT );
+ UI_SPPostgameMenu_MenuDrawScoreLine( n + 2, 0 + 2 * SMALLCHAR_HEIGHT );
+}
+
+
+/*
+=================
+UI_SPPostgameMenu_Cache
+=================
+*/
+void UI_SPPostgameMenu_Cache( void ) {
+ int n;
+ qboolean buildscript;
+
+ buildscript = trap_Cvar_VariableValue("com_buildscript");
+
+ trap_R_RegisterShaderNoMip( ART_MENU0 );
+ trap_R_RegisterShaderNoMip( ART_MENU1 );
+ trap_R_RegisterShaderNoMip( ART_REPLAY0 );
+ trap_R_RegisterShaderNoMip( ART_REPLAY1 );
+ trap_R_RegisterShaderNoMip( ART_NEXT0 );
+ trap_R_RegisterShaderNoMip( ART_NEXT1 );
+ for( n = 0; n < 6; n++ ) {
+ trap_R_RegisterShaderNoMip( ui_medalPicNames[n] );
+ trap_S_RegisterSound( ui_medalSounds[n], qfalse );
+ }
+
+ if( buildscript ) {
+ trap_S_RegisterSound( "music/loss.wav", qfalse );
+ trap_S_RegisterSound( "music/win.wav", qfalse );
+ trap_S_RegisterSound( "sound/player/announce/youwin.wav", qfalse );
+ }
+}
+
+
+/*
+=================
+UI_SPPostgameMenu_Init
+=================
+*/
+static void UI_SPPostgameMenu_Init( void ) {
+ postgameMenuInfo.menu.wrapAround = qtrue;
+ postgameMenuInfo.menu.key = UI_SPPostgameMenu_MenuKey;
+ postgameMenuInfo.menu.draw = UI_SPPostgameMenu_MenuDraw;
+ postgameMenuInfo.ignoreKeysTime = uis.realtime + 1500;
+
+ UI_SPPostgameMenu_Cache();
+
+ postgameMenuInfo.item_menu.generic.type = MTYPE_BITMAP;
+ postgameMenuInfo.item_menu.generic.name = ART_MENU0;
+ postgameMenuInfo.item_menu.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_INACTIVE;
+ postgameMenuInfo.item_menu.generic.x = 0;
+ postgameMenuInfo.item_menu.generic.y = 480-64;
+ postgameMenuInfo.item_menu.generic.callback = UI_SPPostgameMenu_MenuEvent;
+ postgameMenuInfo.item_menu.generic.id = ID_MENU;
+ postgameMenuInfo.item_menu.width = 128;
+ postgameMenuInfo.item_menu.height = 64;
+ postgameMenuInfo.item_menu.focuspic = ART_MENU1;
+
+ postgameMenuInfo.item_again.generic.type = MTYPE_BITMAP;
+ postgameMenuInfo.item_again.generic.name = ART_REPLAY0;
+ postgameMenuInfo.item_again.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS|QMF_INACTIVE;
+ postgameMenuInfo.item_again.generic.x = 320;
+ postgameMenuInfo.item_again.generic.y = 480-64;
+ postgameMenuInfo.item_again.generic.callback = UI_SPPostgameMenu_AgainEvent;
+ postgameMenuInfo.item_again.generic.id = ID_AGAIN;
+ postgameMenuInfo.item_again.width = 128;
+ postgameMenuInfo.item_again.height = 64;
+ postgameMenuInfo.item_again.focuspic = ART_REPLAY1;
+
+ postgameMenuInfo.item_next.generic.type = MTYPE_BITMAP;
+ postgameMenuInfo.item_next.generic.name = ART_NEXT0;
+ postgameMenuInfo.item_next.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_INACTIVE;
+ postgameMenuInfo.item_next.generic.x = 640;
+ postgameMenuInfo.item_next.generic.y = 480-64;
+ postgameMenuInfo.item_next.generic.callback = UI_SPPostgameMenu_NextEvent;
+ postgameMenuInfo.item_next.generic.id = ID_NEXT;
+ postgameMenuInfo.item_next.width = 128;
+ postgameMenuInfo.item_next.height = 64;
+ postgameMenuInfo.item_next.focuspic = ART_NEXT1;
+
+ Menu_AddItem( &postgameMenuInfo.menu, ( void * )&postgameMenuInfo.item_menu );
+ Menu_AddItem( &postgameMenuInfo.menu, ( void * )&postgameMenuInfo.item_again );
+ Menu_AddItem( &postgameMenuInfo.menu, ( void * )&postgameMenuInfo.item_next );
+}
+
+
+static void Prepname( int index ) {
+ int len;
+ char name[64];
+ char info[MAX_INFO_STRING];
+
+ trap_GetConfigString( CS_PLAYERS + postgameMenuInfo.clientNums[index], info, MAX_INFO_STRING );
+ Q_strncpyz( name, Info_ValueForKey( info, "n" ), sizeof(name) );
+ Q_CleanStr( name );
+ len = strlen( name );
+
+ while( len && UI_ProportionalStringWidth( name ) > 256 ) {
+ len--;
+ name[len] = 0;
+ }
+
+ Q_strncpyz( postgameMenuInfo.placeNames[index], name, sizeof(postgameMenuInfo.placeNames[index]) );
+}
+
+
+/*
+=================
+UI_SPPostgameMenu_f
+=================
+*/
+void UI_SPPostgameMenu_f( void ) {
+ int playerGameRank;
+ int playerClientNum;
+ int n;
+ int oldFrags, newFrags;
+ const char *arena;
+ int awardValues[6];
+ char map[MAX_QPATH];
+ char info[MAX_INFO_STRING];
+
+ memset( &postgameMenuInfo, 0, sizeof(postgameMenuInfo) );
+
+ trap_GetConfigString( CS_SYSTEMINFO, info, sizeof(info) );
+ postgameMenuInfo.serverId = atoi( Info_ValueForKey( info, "sv_serverid" ) );
+
+ trap_GetConfigString( CS_SERVERINFO, info, sizeof(info) );
+ Q_strncpyz( map, Info_ValueForKey( info, "mapname" ), sizeof(map) );
+ arena = UI_GetArenaInfoByMap( map );
+ if ( !arena ) {
+ return;
+ }
+ Q_strncpyz( arenainfo, arena, sizeof(arenainfo) );
+
+ postgameMenuInfo.level = atoi( Info_ValueForKey( arenainfo, "num" ) );
+
+ postgameMenuInfo.numClients = atoi( UI_Argv( 1 ) );
+ playerClientNum = atoi( UI_Argv( 2 ) );
+ playerGameRank = 8; // in case they ended game as a spectator
+
+ if( postgameMenuInfo.numClients > MAX_SCOREBOARD_CLIENTS ) {
+ postgameMenuInfo.numClients = MAX_SCOREBOARD_CLIENTS;
+ }
+
+ for( n = 0; n < postgameMenuInfo.numClients; n++ ) {
+ postgameMenuInfo.clientNums[n] = atoi( UI_Argv( 8 + n * 3 + 1 ) );
+ postgameMenuInfo.ranks[n] = atoi( UI_Argv( 8 + n * 3 + 2 ) );
+ postgameMenuInfo.scores[n] = atoi( UI_Argv( 8 + n * 3 + 3 ) );
+
+ if( postgameMenuInfo.clientNums[n] == playerClientNum ) {
+ playerGameRank = (postgameMenuInfo.ranks[n] & ~RANK_TIED_FLAG) + 1;
+ }
+ }
+
+ UI_SetBestScore( postgameMenuInfo.level, playerGameRank );
+
+ // process award stats and prepare presentation data
+ awardValues[AWARD_ACCURACY] = atoi( UI_Argv( 3 ) );
+ awardValues[AWARD_IMPRESSIVE] = atoi( UI_Argv( 4 ) );
+ awardValues[AWARD_EXCELLENT] = atoi( UI_Argv( 5 ) );
+ awardValues[AWARD_GAUNTLET] = atoi( UI_Argv( 6 ) );
+ awardValues[AWARD_FRAGS] = atoi( UI_Argv( 7 ) );
+ awardValues[AWARD_PERFECT] = atoi( UI_Argv( 8 ) );
+
+ postgameMenuInfo.numAwards = 0;
+
+ if( awardValues[AWARD_ACCURACY] >= 50 ) {
+ UI_LogAwardData( AWARD_ACCURACY, 1 );
+ postgameMenuInfo.awardsEarned[postgameMenuInfo.numAwards] = AWARD_ACCURACY;
+ postgameMenuInfo.awardsLevels[postgameMenuInfo.numAwards] = awardValues[AWARD_ACCURACY];
+ postgameMenuInfo.numAwards++;
+ }
+
+ if( awardValues[AWARD_IMPRESSIVE] ) {
+ UI_LogAwardData( AWARD_IMPRESSIVE, awardValues[AWARD_IMPRESSIVE] );
+ postgameMenuInfo.awardsEarned[postgameMenuInfo.numAwards] = AWARD_IMPRESSIVE;
+ postgameMenuInfo.awardsLevels[postgameMenuInfo.numAwards] = awardValues[AWARD_IMPRESSIVE];
+ postgameMenuInfo.numAwards++;
+ }
+
+ if( awardValues[AWARD_EXCELLENT] ) {
+ UI_LogAwardData( AWARD_EXCELLENT, awardValues[AWARD_EXCELLENT] );
+ postgameMenuInfo.awardsEarned[postgameMenuInfo.numAwards] = AWARD_EXCELLENT;
+ postgameMenuInfo.awardsLevels[postgameMenuInfo.numAwards] = awardValues[AWARD_EXCELLENT];
+ postgameMenuInfo.numAwards++;
+ }
+
+ if( awardValues[AWARD_GAUNTLET] ) {
+ UI_LogAwardData( AWARD_GAUNTLET, awardValues[AWARD_GAUNTLET] );
+ postgameMenuInfo.awardsEarned[postgameMenuInfo.numAwards] = AWARD_GAUNTLET;
+ postgameMenuInfo.awardsLevels[postgameMenuInfo.numAwards] = awardValues[AWARD_GAUNTLET];
+ postgameMenuInfo.numAwards++;
+ }
+
+ oldFrags = UI_GetAwardLevel( AWARD_FRAGS ) / 100;
+ UI_LogAwardData( AWARD_FRAGS, awardValues[AWARD_FRAGS] );
+ newFrags = UI_GetAwardLevel( AWARD_FRAGS ) / 100;
+ if( newFrags > oldFrags ) {
+ postgameMenuInfo.awardsEarned[postgameMenuInfo.numAwards] = AWARD_FRAGS;
+ postgameMenuInfo.awardsLevels[postgameMenuInfo.numAwards] = newFrags * 100;
+ postgameMenuInfo.numAwards++;
+ }
+
+ if( awardValues[AWARD_PERFECT] ) {
+ UI_LogAwardData( AWARD_PERFECT, 1 );
+ postgameMenuInfo.awardsEarned[postgameMenuInfo.numAwards] = AWARD_PERFECT;
+ postgameMenuInfo.awardsLevels[postgameMenuInfo.numAwards] = 1;
+ postgameMenuInfo.numAwards++;
+ }
+
+ if ( playerGameRank == 1 ) {
+ postgameMenuInfo.won = UI_TierCompleted( postgameMenuInfo.level );
+ }
+ else {
+ postgameMenuInfo.won = -1;
+ }
+
+ postgameMenuInfo.starttime = uis.realtime;
+ postgameMenuInfo.scoreboardtime = uis.realtime;
+
+ trap_Key_SetCatcher( KEYCATCH_UI );
+ uis.menusp = 0;
+
+ UI_SPPostgameMenu_Init();
+ UI_PushMenu( &postgameMenuInfo.menu );
+
+ if ( playerGameRank == 1 ) {
+ Menu_SetCursorToItem( &postgameMenuInfo.menu, &postgameMenuInfo.item_next );
+ }
+ else {
+ Menu_SetCursorToItem( &postgameMenuInfo.menu, &postgameMenuInfo.item_again );
+ }
+
+ Prepname( 0 );
+ Prepname( 1 );
+ Prepname( 2 );
+
+ if ( playerGameRank != 1 ) {
+ postgameMenuInfo.winnerSound = trap_S_RegisterSound( va( "sound/player/announce/%s_wins.wav", postgameMenuInfo.placeNames[0] ), qfalse );
+ trap_Cmd_ExecuteText( EXEC_APPEND, "music music/loss\n" );
+ }
+ else {
+ postgameMenuInfo.winnerSound = trap_S_RegisterSound( "sound/player/announce/youwin.wav", qfalse );
+ trap_Cmd_ExecuteText( EXEC_APPEND, "music music/win\n" );
+ }
+
+ postgameMenuInfo.phase = 1;
+
+ postgameMenuInfo.lastTier = UI_GetNumSPTiers();
+ if ( UI_GetSpecialArenaInfo( "final" ) ) {
+ postgameMenuInfo.lastTier++;
+ }
+}
diff --git a/code/q3_ui/ui_spreset.c b/code/q3_ui/ui_spreset.c
new file mode 100755
index 0000000..0dc3634
--- /dev/null
+++ b/code/q3_ui/ui_spreset.c
@@ -0,0 +1,194 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+/*
+=======================================================================
+
+RESET MENU
+
+=======================================================================
+*/
+
+#include "ui_local.h"
+
+
+#define ART_FRAME "menu/art/cut_frame"
+
+#define ID_NO 100
+#define ID_YES 101
+
+typedef struct
+{
+ menuframework_s menu;
+ menutext_s no;
+ menutext_s yes;
+ int slashX;
+} resetMenu_t;
+
+static resetMenu_t s_reset;
+
+
+/*
+=================
+Reset_MenuEvent
+=================
+*/
+void Reset_MenuEvent(void* ptr, int event) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+
+ UI_PopMenu();
+
+ if( ((menucommon_s*)ptr)->id == ID_NO ) {
+ return;
+ }
+
+ // reset the game, pop the level menu and restart it so it updates
+ UI_NewGame();
+ trap_Cvar_SetValue( "ui_spSelection", 0 );
+ UI_PopMenu();
+ UI_SPLevelMenu();
+}
+
+
+/*
+=================
+Reset_MenuKey
+=================
+*/
+static sfxHandle_t Reset_MenuKey( int key ) {
+ switch ( key ) {
+ case K_KP_LEFTARROW:
+ case K_LEFTARROW:
+ case K_KP_RIGHTARROW:
+ case K_RIGHTARROW:
+ key = K_TAB;
+ break;
+
+ case 'n':
+ case 'N':
+ Reset_MenuEvent( &s_reset.no, QM_ACTIVATED );
+ break;
+
+ case 'y':
+ case 'Y':
+ Reset_MenuEvent( &s_reset.yes, QM_ACTIVATED );
+ break;
+ }
+
+ return Menu_DefaultKey( &s_reset.menu, key );
+}
+
+
+/*
+=================
+Reset_MenuDraw
+=================
+*/
+static void Reset_MenuDraw( void ) {
+ UI_DrawNamedPic( 142, 118, 359, 256, ART_FRAME );
+ UI_DrawProportionalString( 320, 194 + 10, "RESET GAME?", UI_CENTER|UI_INVERSE, color_red );
+ UI_DrawProportionalString( s_reset.slashX, 265, "/", UI_LEFT|UI_INVERSE, color_red );
+ Menu_Draw( &s_reset.menu );
+
+ UI_DrawProportionalString( SCREEN_WIDTH/2, 356 + PROP_HEIGHT * 0, "WARNING: This resets all of the", UI_CENTER|UI_SMALLFONT, color_yellow );
+ UI_DrawProportionalString( SCREEN_WIDTH/2, 356 + PROP_HEIGHT * 1, "single player game variables.", UI_CENTER|UI_SMALLFONT, color_yellow );
+ UI_DrawProportionalString( SCREEN_WIDTH/2, 356 + PROP_HEIGHT * 2, "Do this only if you want to", UI_CENTER|UI_SMALLFONT, color_yellow );
+ UI_DrawProportionalString( SCREEN_WIDTH/2, 356 + PROP_HEIGHT * 3, "start over from the beginning.", UI_CENTER|UI_SMALLFONT, color_yellow );
+}
+
+
+/*
+=================
+Reset_Cache
+=================
+*/
+void Reset_Cache( void ) {
+ trap_R_RegisterShaderNoMip( ART_FRAME );
+}
+
+
+/*
+=================
+UI_ResetMenu
+=================
+*/
+void UI_ResetMenu(void) {
+ uiClientState_t cstate;
+ int n1, n2, n3;
+ int l1, l2, l3;
+
+ // zero set all our globals
+ memset( &s_reset, 0, sizeof(s_reset) );
+
+ Reset_Cache();
+
+ n1 = UI_ProportionalStringWidth( "YES/NO" );
+ n2 = UI_ProportionalStringWidth( "YES" ) + PROP_GAP_WIDTH;
+ n3 = UI_ProportionalStringWidth( "/" ) + PROP_GAP_WIDTH;
+ l1 = 320 - ( n1 / 2 );
+ l2 = l1 + n2;
+ l3 = l2 + n3;
+ s_reset.slashX = l2;
+
+ s_reset.menu.draw = Reset_MenuDraw;
+ s_reset.menu.key = Reset_MenuKey;
+ s_reset.menu.wrapAround = qtrue;
+
+ trap_GetClientState( &cstate );
+
+ if ( cstate.connState >= CA_CONNECTED ) {
+ // float on top of running game
+ s_reset.menu.fullscreen = qfalse;
+ }
+ else {
+ // game not running
+ s_reset.menu.fullscreen = qtrue;
+ }
+
+ s_reset.yes.generic.type = MTYPE_PTEXT;
+ s_reset.yes.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_reset.yes.generic.callback = Reset_MenuEvent;
+ s_reset.yes.generic.id = ID_YES;
+ s_reset.yes.generic.x = l1;
+ s_reset.yes.generic.y = 264;
+ s_reset.yes.string = "YES";
+ s_reset.yes.color = color_red;
+ s_reset.yes.style = UI_LEFT;
+
+ s_reset.no.generic.type = MTYPE_PTEXT;
+ s_reset.no.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_reset.no.generic.callback = Reset_MenuEvent;
+ s_reset.no.generic.id = ID_NO;
+ s_reset.no.generic.x = l3;
+ s_reset.no.generic.y = 264;
+ s_reset.no.string = "NO";
+ s_reset.no.color = color_red;
+ s_reset.no.style = UI_LEFT;
+
+ Menu_AddItem( &s_reset.menu, &s_reset.yes );
+ Menu_AddItem( &s_reset.menu, &s_reset.no );
+
+ UI_PushMenu( &s_reset.menu );
+
+ Menu_SetCursorToItem( &s_reset.menu, &s_reset.no );
+}
diff --git a/code/q3_ui/ui_spskill.c b/code/q3_ui/ui_spskill.c
new file mode 100755
index 0000000..934d832
--- /dev/null
+++ b/code/q3_ui/ui_spskill.c
@@ -0,0 +1,329 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*
+=============================================================================
+
+SINGLE PLAYER SKILL MENU
+
+=============================================================================
+*/
+
+#include "ui_local.h"
+
+
+#define ART_FRAME "menu/art/cut_frame"
+#define ART_BACK "menu/art/back_0.tga"
+#define ART_BACK_FOCUS "menu/art/back_1.tga"
+#define ART_FIGHT "menu/art/fight_0"
+#define ART_FIGHT_FOCUS "menu/art/fight_1"
+#define ART_MAP_COMPLETE1 "menu/art/level_complete1"
+#define ART_MAP_COMPLETE2 "menu/art/level_complete2"
+#define ART_MAP_COMPLETE3 "menu/art/level_complete3"
+#define ART_MAP_COMPLETE4 "menu/art/level_complete4"
+#define ART_MAP_COMPLETE5 "menu/art/level_complete5"
+
+#define ID_BABY 10
+#define ID_EASY 11
+#define ID_MEDIUM 12
+#define ID_HARD 13
+#define ID_NIGHTMARE 14
+#define ID_BACK 15
+#define ID_FIGHT 16
+
+
+typedef struct {
+ menuframework_s menu;
+
+ menubitmap_s art_frame;
+ menutext_s art_banner;
+
+ menutext_s item_baby;
+ menutext_s item_easy;
+ menutext_s item_medium;
+ menutext_s item_hard;
+ menutext_s item_nightmare;
+
+ menubitmap_s art_skillPic;
+ menubitmap_s item_back;
+ menubitmap_s item_fight;
+
+ const char *arenaInfo;
+ qhandle_t skillpics[5];
+ sfxHandle_t nightmareSound;
+ sfxHandle_t silenceSound;
+} skillMenuInfo_t;
+
+static skillMenuInfo_t skillMenuInfo;
+
+
+static void SetSkillColor( int skill, vec4_t color ) {
+ switch( skill ) {
+ case 1:
+ skillMenuInfo.item_baby.color = color;
+ break;
+ case 2:
+ skillMenuInfo.item_easy.color = color;
+ break;
+ case 3:
+ skillMenuInfo.item_medium.color = color;
+ break;
+ case 4:
+ skillMenuInfo.item_hard.color = color;
+ break;
+ case 5:
+ skillMenuInfo.item_nightmare.color = color;
+ break;
+ default:
+ break;
+ }
+}
+
+
+/*
+=================
+UI_SPSkillMenu_SkillEvent
+=================
+*/
+static void UI_SPSkillMenu_SkillEvent( void *ptr, int notification ) {
+ int id;
+ int skill;
+
+ if (notification != QM_ACTIVATED)
+ return;
+
+ SetSkillColor( (int)trap_Cvar_VariableValue( "g_spSkill" ), color_red );
+
+ id = ((menucommon_s*)ptr)->id;
+ skill = id - ID_BABY + 1;
+ trap_Cvar_SetValue( "g_spSkill", skill );
+
+ SetSkillColor( skill, color_white );
+ skillMenuInfo.art_skillPic.shader = skillMenuInfo.skillpics[skill - 1];
+
+ if( id == ID_NIGHTMARE ) {
+ trap_S_StartLocalSound( skillMenuInfo.nightmareSound, CHAN_ANNOUNCER );
+ }
+ else {
+ trap_S_StartLocalSound( skillMenuInfo.silenceSound, CHAN_ANNOUNCER );
+ }
+}
+
+
+/*
+=================
+UI_SPSkillMenu_FightEvent
+=================
+*/
+static void UI_SPSkillMenu_FightEvent( void *ptr, int notification ) {
+ if (notification != QM_ACTIVATED)
+ return;
+
+ UI_SPArena_Start( skillMenuInfo.arenaInfo );
+}
+
+
+/*
+=================
+UI_SPSkillMenu_BackEvent
+=================
+*/
+static void UI_SPSkillMenu_BackEvent( void* ptr, int notification ) {
+ if (notification != QM_ACTIVATED) {
+ return;
+ }
+
+ trap_S_StartLocalSound( skillMenuInfo.silenceSound, CHAN_ANNOUNCER );
+ UI_PopMenu();
+}
+
+
+/*
+=================
+UI_SPSkillMenu_Key
+=================
+*/
+static sfxHandle_t UI_SPSkillMenu_Key( int key ) {
+ if( key == K_MOUSE2 || key == K_ESCAPE ) {
+ trap_S_StartLocalSound( skillMenuInfo.silenceSound, CHAN_ANNOUNCER );
+ }
+ return Menu_DefaultKey( &skillMenuInfo.menu, key );
+}
+
+
+/*
+=================
+UI_SPSkillMenu_Cache
+=================
+*/
+void UI_SPSkillMenu_Cache( void ) {
+ trap_R_RegisterShaderNoMip( ART_FRAME );
+ trap_R_RegisterShaderNoMip( ART_BACK );
+ trap_R_RegisterShaderNoMip( ART_BACK_FOCUS );
+ trap_R_RegisterShaderNoMip( ART_FIGHT );
+ trap_R_RegisterShaderNoMip( ART_FIGHT_FOCUS );
+ skillMenuInfo.skillpics[0] = trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE1 );
+ skillMenuInfo.skillpics[1] = trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE2 );
+ skillMenuInfo.skillpics[2] = trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE3 );
+ skillMenuInfo.skillpics[3] = trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE4 );
+ skillMenuInfo.skillpics[4] = trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE5 );
+
+ skillMenuInfo.nightmareSound = trap_S_RegisterSound( "sound/misc/nightmare.wav", qfalse );
+ skillMenuInfo.silenceSound = trap_S_RegisterSound( "sound/misc/silence.wav", qfalse );
+}
+
+
+/*
+=================
+UI_SPSkillMenu_Init
+=================
+*/
+static void UI_SPSkillMenu_Init( void ) {
+ int skill;
+
+ memset( &skillMenuInfo, 0, sizeof(skillMenuInfo) );
+ skillMenuInfo.menu.fullscreen = qtrue;
+ skillMenuInfo.menu.key = UI_SPSkillMenu_Key;
+
+ UI_SPSkillMenu_Cache();
+
+ skillMenuInfo.art_frame.generic.type = MTYPE_BITMAP;
+ skillMenuInfo.art_frame.generic.name = ART_FRAME;
+ skillMenuInfo.art_frame.generic.flags = QMF_LEFT_JUSTIFY|QMF_INACTIVE;
+ skillMenuInfo.art_frame.generic.x = 142;
+ skillMenuInfo.art_frame.generic.y = 118;
+ skillMenuInfo.art_frame.width = 359;
+ skillMenuInfo.art_frame.height = 256;
+
+ skillMenuInfo.art_banner.generic.type = MTYPE_BTEXT;
+ skillMenuInfo.art_banner.generic.flags = QMF_CENTER_JUSTIFY;
+ skillMenuInfo.art_banner.generic.x = 320;
+ skillMenuInfo.art_banner.generic.y = 16;
+ skillMenuInfo.art_banner.string = "DIFFICULTY";
+ skillMenuInfo.art_banner.color = color_white;
+ skillMenuInfo.art_banner.style = UI_CENTER;
+
+ skillMenuInfo.item_baby.generic.type = MTYPE_PTEXT;
+ skillMenuInfo.item_baby.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ skillMenuInfo.item_baby.generic.x = 320;
+ skillMenuInfo.item_baby.generic.y = 170;
+ skillMenuInfo.item_baby.generic.callback = UI_SPSkillMenu_SkillEvent;
+ skillMenuInfo.item_baby.generic.id = ID_BABY;
+ skillMenuInfo.item_baby.string = "I Can Win";
+ skillMenuInfo.item_baby.color = color_red;
+ skillMenuInfo.item_baby.style = UI_CENTER;
+
+ skillMenuInfo.item_easy.generic.type = MTYPE_PTEXT;
+ skillMenuInfo.item_easy.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ skillMenuInfo.item_easy.generic.x = 320;
+ skillMenuInfo.item_easy.generic.y = 198;
+ skillMenuInfo.item_easy.generic.callback = UI_SPSkillMenu_SkillEvent;
+ skillMenuInfo.item_easy.generic.id = ID_EASY;
+ skillMenuInfo.item_easy.string = "Bring It On";
+ skillMenuInfo.item_easy.color = color_red;
+ skillMenuInfo.item_easy.style = UI_CENTER;
+
+ skillMenuInfo.item_medium.generic.type = MTYPE_PTEXT;
+ skillMenuInfo.item_medium.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ skillMenuInfo.item_medium.generic.x = 320;
+ skillMenuInfo.item_medium.generic.y = 227;
+ skillMenuInfo.item_medium.generic.callback = UI_SPSkillMenu_SkillEvent;
+ skillMenuInfo.item_medium.generic.id = ID_MEDIUM;
+ skillMenuInfo.item_medium.string = "Hurt Me Plenty";
+ skillMenuInfo.item_medium.color = color_red;
+ skillMenuInfo.item_medium.style = UI_CENTER;
+
+ skillMenuInfo.item_hard.generic.type = MTYPE_PTEXT;
+ skillMenuInfo.item_hard.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ skillMenuInfo.item_hard.generic.x = 320;
+ skillMenuInfo.item_hard.generic.y = 255;
+ skillMenuInfo.item_hard.generic.callback = UI_SPSkillMenu_SkillEvent;
+ skillMenuInfo.item_hard.generic.id = ID_HARD;
+ skillMenuInfo.item_hard.string = "Hardcore";
+ skillMenuInfo.item_hard.color = color_red;
+ skillMenuInfo.item_hard.style = UI_CENTER;
+
+ skillMenuInfo.item_nightmare.generic.type = MTYPE_PTEXT;
+ skillMenuInfo.item_nightmare.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ skillMenuInfo.item_nightmare.generic.x = 320;
+ skillMenuInfo.item_nightmare.generic.y = 283;
+ skillMenuInfo.item_nightmare.generic.callback = UI_SPSkillMenu_SkillEvent;
+ skillMenuInfo.item_nightmare.generic.id = ID_NIGHTMARE;
+ skillMenuInfo.item_nightmare.string = "NIGHTMARE!";
+ skillMenuInfo.item_nightmare.color = color_red;
+ skillMenuInfo.item_nightmare.style = UI_CENTER;
+
+ skillMenuInfo.item_back.generic.type = MTYPE_BITMAP;
+ skillMenuInfo.item_back.generic.name = ART_BACK;
+ skillMenuInfo.item_back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ skillMenuInfo.item_back.generic.x = 0;
+ skillMenuInfo.item_back.generic.y = 480-64;
+ skillMenuInfo.item_back.generic.callback = UI_SPSkillMenu_BackEvent;
+ skillMenuInfo.item_back.generic.id = ID_BACK;
+ skillMenuInfo.item_back.width = 128;
+ skillMenuInfo.item_back.height = 64;
+ skillMenuInfo.item_back.focuspic = ART_BACK_FOCUS;
+
+ skillMenuInfo.art_skillPic.generic.type = MTYPE_BITMAP;
+ skillMenuInfo.art_skillPic.generic.flags = QMF_LEFT_JUSTIFY|QMF_INACTIVE;
+ skillMenuInfo.art_skillPic.generic.x = 320-64;
+ skillMenuInfo.art_skillPic.generic.y = 368;
+ skillMenuInfo.art_skillPic.width = 128;
+ skillMenuInfo.art_skillPic.height = 96;
+
+ skillMenuInfo.item_fight.generic.type = MTYPE_BITMAP;
+ skillMenuInfo.item_fight.generic.name = ART_FIGHT;
+ skillMenuInfo.item_fight.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ skillMenuInfo.item_fight.generic.callback = UI_SPSkillMenu_FightEvent;
+ skillMenuInfo.item_fight.generic.id = ID_FIGHT;
+ skillMenuInfo.item_fight.generic.x = 640;
+ skillMenuInfo.item_fight.generic.y = 480-64;
+ skillMenuInfo.item_fight.width = 128;
+ skillMenuInfo.item_fight.height = 64;
+ skillMenuInfo.item_fight.focuspic = ART_FIGHT_FOCUS;
+
+ Menu_AddItem( &skillMenuInfo.menu, ( void * )&skillMenuInfo.art_frame );
+ Menu_AddItem( &skillMenuInfo.menu, ( void * )&skillMenuInfo.art_banner );
+ Menu_AddItem( &skillMenuInfo.menu, ( void * )&skillMenuInfo.item_baby );
+ Menu_AddItem( &skillMenuInfo.menu, ( void * )&skillMenuInfo.item_easy );
+ Menu_AddItem( &skillMenuInfo.menu, ( void * )&skillMenuInfo.item_medium );
+ Menu_AddItem( &skillMenuInfo.menu, ( void * )&skillMenuInfo.item_hard );
+ Menu_AddItem( &skillMenuInfo.menu, ( void * )&skillMenuInfo.item_nightmare );
+ Menu_AddItem( &skillMenuInfo.menu, ( void * )&skillMenuInfo.art_skillPic );
+ Menu_AddItem( &skillMenuInfo.menu, ( void * )&skillMenuInfo.item_back );
+ Menu_AddItem( &skillMenuInfo.menu, ( void * )&skillMenuInfo.item_fight );
+
+ skill = (int)Com_Clamp( 1, 5, trap_Cvar_VariableValue( "g_spSkill" ) );
+ SetSkillColor( skill, color_white );
+ skillMenuInfo.art_skillPic.shader = skillMenuInfo.skillpics[skill - 1];
+ if( skill == 5 ) {
+ trap_S_StartLocalSound( skillMenuInfo.nightmareSound, CHAN_ANNOUNCER );
+ }
+}
+
+
+void UI_SPSkillMenu( const char *arenaInfo ) {
+ UI_SPSkillMenu_Init();
+ skillMenuInfo.arenaInfo = arenaInfo;
+ UI_PushMenu( &skillMenuInfo.menu );
+ Menu_SetCursorToItem( &skillMenuInfo.menu, &skillMenuInfo.item_fight );
+}
diff --git a/code/q3_ui/ui_startserver.c b/code/q3_ui/ui_startserver.c
new file mode 100755
index 0000000..5bc3680
--- /dev/null
+++ b/code/q3_ui/ui_startserver.c
@@ -0,0 +1,1968 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*
+=============================================================================
+
+START SERVER MENU *****
+
+=============================================================================
+*/
+
+
+#include "ui_local.h"
+
+
+#define GAMESERVER_BACK0 "menu/art/back_0"
+#define GAMESERVER_BACK1 "menu/art/back_1"
+#define GAMESERVER_NEXT0 "menu/art/next_0"
+#define GAMESERVER_NEXT1 "menu/art/next_1"
+#define GAMESERVER_FRAMEL "menu/art/frame2_l"
+#define GAMESERVER_FRAMER "menu/art/frame1_r"
+#define GAMESERVER_SELECT "menu/art/maps_select"
+#define GAMESERVER_SELECTED "menu/art/maps_selected"
+#define GAMESERVER_FIGHT0 "menu/art/fight_0"
+#define GAMESERVER_FIGHT1 "menu/art/fight_1"
+#define GAMESERVER_UNKNOWNMAP "menu/art/unknownmap"
+#define GAMESERVER_ARROWS "menu/art/gs_arrows_0"
+#define GAMESERVER_ARROWSL "menu/art/gs_arrows_l"
+#define GAMESERVER_ARROWSR "menu/art/gs_arrows_r"
+
+#define MAX_MAPROWS 2
+#define MAX_MAPCOLS 2
+#define MAX_MAPSPERPAGE 4
+
+#define MAX_SERVERSTEXT 8192
+
+#define MAX_SERVERMAPS 64
+#define MAX_NAMELENGTH 16
+
+#define ID_GAMETYPE 10
+#define ID_PICTURES 11 // 12, 13, 14
+#define ID_PREVPAGE 15
+#define ID_NEXTPAGE 16
+#define ID_STARTSERVERBACK 17
+#define ID_STARTSERVERNEXT 18
+
+typedef struct {
+ menuframework_s menu;
+
+ menutext_s banner;
+ menubitmap_s framel;
+ menubitmap_s framer;
+
+ menulist_s gametype;
+ menubitmap_s mappics[MAX_MAPSPERPAGE];
+ menubitmap_s mapbuttons[MAX_MAPSPERPAGE];
+ menubitmap_s arrows;
+ menubitmap_s prevpage;
+ menubitmap_s nextpage;
+ menubitmap_s back;
+ menubitmap_s next;
+
+ menutext_s mapname;
+ menubitmap_s item_null;
+
+ qboolean multiplayer;
+ int currentmap;
+ int nummaps;
+ int page;
+ int maxpages;
+ char maplist[MAX_SERVERMAPS][MAX_NAMELENGTH];
+ int mapGamebits[MAX_SERVERMAPS];
+} startserver_t;
+
+static startserver_t s_startserver;
+
+static const char *gametype_items[] = {
+ "Free For All",
+ "Team Deathmatch",
+ "Tournament",
+ "Capture the Flag",
+ 0
+};
+
+static int gametype_remap[] = {GT_FFA, GT_TEAM, GT_TOURNAMENT, GT_CTF};
+static int gametype_remap2[] = {0, 2, 0, 1, 3};
+
+// use ui_servers2.c definition
+extern const char* punkbuster_items[];
+
+static void UI_ServerOptionsMenu( qboolean multiplayer );
+
+
+/*
+=================
+GametypeBits
+=================
+*/
+static int GametypeBits( char *string ) {
+ int bits;
+ char *p;
+ char *token;
+
+ bits = 0;
+ p = string;
+ while( 1 ) {
+ token = COM_ParseExt( &p, qfalse );
+ if( token[0] == 0 ) {
+ break;
+ }
+
+ if( Q_stricmp( token, "ffa" ) == 0 ) {
+ bits |= 1 << GT_FFA;
+ continue;
+ }
+
+ if( Q_stricmp( token, "tourney" ) == 0 ) {
+ bits |= 1 << GT_TOURNAMENT;
+ continue;
+ }
+
+ if( Q_stricmp( token, "single" ) == 0 ) {
+ bits |= 1 << GT_SINGLE_PLAYER;
+ continue;
+ }
+
+ if( Q_stricmp( token, "team" ) == 0 ) {
+ bits |= 1 << GT_TEAM;
+ continue;
+ }
+
+ if( Q_stricmp( token, "ctf" ) == 0 ) {
+ bits |= 1 << GT_CTF;
+ continue;
+ }
+ }
+
+ return bits;
+}
+
+
+/*
+=================
+StartServer_Update
+=================
+*/
+static void StartServer_Update( void ) {
+ int i;
+ int top;
+ static char picname[MAX_MAPSPERPAGE][64];
+
+ top = s_startserver.page*MAX_MAPSPERPAGE;
+
+ for (i=0; i<MAX_MAPSPERPAGE; i++)
+ {
+ if (top+i >= s_startserver.nummaps)
+ break;
+
+ Com_sprintf( picname[i], sizeof(picname[i]), "levelshots/%s", s_startserver.maplist[top+i] );
+
+ s_startserver.mappics[i].generic.flags &= ~QMF_HIGHLIGHT;
+ s_startserver.mappics[i].generic.name = picname[i];
+ s_startserver.mappics[i].shader = 0;
+
+ // reset
+ s_startserver.mapbuttons[i].generic.flags |= QMF_PULSEIFFOCUS;
+ s_startserver.mapbuttons[i].generic.flags &= ~QMF_INACTIVE;
+ }
+
+ for (; i<MAX_MAPSPERPAGE; i++)
+ {
+ s_startserver.mappics[i].generic.flags &= ~QMF_HIGHLIGHT;
+ s_startserver.mappics[i].generic.name = NULL;
+ s_startserver.mappics[i].shader = 0;
+
+ // disable
+ s_startserver.mapbuttons[i].generic.flags &= ~QMF_PULSEIFFOCUS;
+ s_startserver.mapbuttons[i].generic.flags |= QMF_INACTIVE;
+ }
+
+
+ // no servers to start
+ if( !s_startserver.nummaps ) {
+ s_startserver.next.generic.flags |= QMF_INACTIVE;
+
+ // set the map name
+ strcpy( s_startserver.mapname.string, "NO MAPS FOUND" );
+ }
+ else {
+ // set the highlight
+ s_startserver.next.generic.flags &= ~QMF_INACTIVE;
+ i = s_startserver.currentmap - top;
+ if ( i >=0 && i < MAX_MAPSPERPAGE )
+ {
+ s_startserver.mappics[i].generic.flags |= QMF_HIGHLIGHT;
+ s_startserver.mapbuttons[i].generic.flags &= ~QMF_PULSEIFFOCUS;
+ }
+
+ // set the map name
+ strcpy( s_startserver.mapname.string, s_startserver.maplist[s_startserver.currentmap] );
+ }
+
+ Q_strupr( s_startserver.mapname.string );
+}
+
+
+/*
+=================
+StartServer_MapEvent
+=================
+*/
+static void StartServer_MapEvent( void* ptr, int event ) {
+ if( event != QM_ACTIVATED) {
+ return;
+ }
+
+ s_startserver.currentmap = (s_startserver.page*MAX_MAPSPERPAGE) + (((menucommon_s*)ptr)->id - ID_PICTURES);
+ StartServer_Update();
+}
+
+
+/*
+=================
+StartServer_GametypeEvent
+=================
+*/
+static void StartServer_GametypeEvent( void* ptr, int event ) {
+ int i;
+ int count;
+ int gamebits;
+ int matchbits;
+ const char *info;
+
+ if( event != QM_ACTIVATED) {
+ return;
+ }
+
+ count = UI_GetNumArenas();
+ s_startserver.nummaps = 0;
+ matchbits = 1 << gametype_remap[s_startserver.gametype.curvalue];
+ if( gametype_remap[s_startserver.gametype.curvalue] == GT_FFA ) {
+ matchbits |= ( 1 << GT_SINGLE_PLAYER );
+ }
+ for( i = 0; i < count; i++ ) {
+ info = UI_GetArenaInfoByNumber( i );
+
+ gamebits = GametypeBits( Info_ValueForKey( info, "type") );
+ if( !( gamebits & matchbits ) ) {
+ continue;
+ }
+
+ Q_strncpyz( s_startserver.maplist[s_startserver.nummaps], Info_ValueForKey( info, "map"), MAX_NAMELENGTH );
+ Q_strupr( s_startserver.maplist[s_startserver.nummaps] );
+ s_startserver.mapGamebits[s_startserver.nummaps] = gamebits;
+ s_startserver.nummaps++;
+ }
+ s_startserver.maxpages = (s_startserver.nummaps + MAX_MAPSPERPAGE-1)/MAX_MAPSPERPAGE;
+ s_startserver.page = 0;
+ s_startserver.currentmap = 0;
+
+ StartServer_Update();
+}
+
+
+/*
+=================
+StartServer_MenuEvent
+=================
+*/
+static void StartServer_MenuEvent( void* ptr, int event ) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+
+ switch( ((menucommon_s*)ptr)->id ) {
+ case ID_PREVPAGE:
+ if( s_startserver.page > 0 ) {
+ s_startserver.page--;
+ StartServer_Update();
+ }
+ break;
+
+ case ID_NEXTPAGE:
+ if( s_startserver.page < s_startserver.maxpages - 1 ) {
+ s_startserver.page++;
+ StartServer_Update();
+ }
+ break;
+
+ case ID_STARTSERVERNEXT:
+ trap_Cvar_SetValue( "g_gameType", gametype_remap[s_startserver.gametype.curvalue] );
+ UI_ServerOptionsMenu( s_startserver.multiplayer );
+ break;
+
+ case ID_STARTSERVERBACK:
+ UI_PopMenu();
+ break;
+ }
+}
+
+
+/*
+===============
+StartServer_LevelshotDraw
+===============
+*/
+static void StartServer_LevelshotDraw( void *self ) {
+ menubitmap_s *b;
+ int x;
+ int y;
+ int w;
+ int h;
+ int n;
+
+ b = (menubitmap_s *)self;
+
+ if( !b->generic.name ) {
+ return;
+ }
+
+ if( b->generic.name && !b->shader ) {
+ b->shader = trap_R_RegisterShaderNoMip( b->generic.name );
+ if( !b->shader && b->errorpic ) {
+ b->shader = trap_R_RegisterShaderNoMip( b->errorpic );
+ }
+ }
+
+ if( b->focuspic && !b->focusshader ) {
+ b->focusshader = trap_R_RegisterShaderNoMip( b->focuspic );
+ }
+
+ x = b->generic.x;
+ y = b->generic.y;
+ w = b->width;
+ h = b->height;
+ if( b->shader ) {
+ UI_DrawHandlePic( x, y, w, h, b->shader );
+ }
+
+ x = b->generic.x;
+ y = b->generic.y + b->height;
+ UI_FillRect( x, y, b->width, 28, colorBlack );
+
+ x += b->width / 2;
+ y += 4;
+ n = s_startserver.page * MAX_MAPSPERPAGE + b->generic.id - ID_PICTURES;
+ UI_DrawString( x, y, s_startserver.maplist[n], UI_CENTER|UI_SMALLFONT, color_orange );
+
+ x = b->generic.x;
+ y = b->generic.y;
+ w = b->width;
+ h = b->height + 28;
+ if( b->generic.flags & QMF_HIGHLIGHT ) {
+ UI_DrawHandlePic( x, y, w, h, b->focusshader );
+ }
+}
+
+
+/*
+=================
+StartServer_MenuInit
+=================
+*/
+static void StartServer_MenuInit( void ) {
+ int i;
+ int x;
+ int y;
+ static char mapnamebuffer[64];
+
+ // zero set all our globals
+ memset( &s_startserver, 0 ,sizeof(startserver_t) );
+
+ StartServer_Cache();
+
+ s_startserver.menu.wrapAround = qtrue;
+ s_startserver.menu.fullscreen = qtrue;
+
+ s_startserver.banner.generic.type = MTYPE_BTEXT;
+ s_startserver.banner.generic.x = 320;
+ s_startserver.banner.generic.y = 16;
+ s_startserver.banner.string = "GAME SERVER";
+ s_startserver.banner.color = color_white;
+ s_startserver.banner.style = UI_CENTER;
+
+ s_startserver.framel.generic.type = MTYPE_BITMAP;
+ s_startserver.framel.generic.name = GAMESERVER_FRAMEL;
+ s_startserver.framel.generic.flags = QMF_INACTIVE;
+ s_startserver.framel.generic.x = 0;
+ s_startserver.framel.generic.y = 78;
+ s_startserver.framel.width = 256;
+ s_startserver.framel.height = 329;
+
+ s_startserver.framer.generic.type = MTYPE_BITMAP;
+ s_startserver.framer.generic.name = GAMESERVER_FRAMER;
+ s_startserver.framer.generic.flags = QMF_INACTIVE;
+ s_startserver.framer.generic.x = 376;
+ s_startserver.framer.generic.y = 76;
+ s_startserver.framer.width = 256;
+ s_startserver.framer.height = 334;
+
+ s_startserver.gametype.generic.type = MTYPE_SPINCONTROL;
+ s_startserver.gametype.generic.name = "Game Type:";
+ s_startserver.gametype.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_startserver.gametype.generic.callback = StartServer_GametypeEvent;
+ s_startserver.gametype.generic.id = ID_GAMETYPE;
+ s_startserver.gametype.generic.x = 320 - 24;
+ s_startserver.gametype.generic.y = 368;
+ s_startserver.gametype.itemnames = gametype_items;
+
+ for (i=0; i<MAX_MAPSPERPAGE; i++)
+ {
+ x = (i % MAX_MAPCOLS) * (128+8) + 188;
+ y = (i / MAX_MAPROWS) * (128+8) + 96;
+
+ s_startserver.mappics[i].generic.type = MTYPE_BITMAP;
+ s_startserver.mappics[i].generic.flags = QMF_LEFT_JUSTIFY|QMF_INACTIVE;
+ s_startserver.mappics[i].generic.x = x;
+ s_startserver.mappics[i].generic.y = y;
+ s_startserver.mappics[i].generic.id = ID_PICTURES+i;
+ s_startserver.mappics[i].width = 128;
+ s_startserver.mappics[i].height = 96;
+ s_startserver.mappics[i].focuspic = GAMESERVER_SELECTED;
+ s_startserver.mappics[i].errorpic = GAMESERVER_UNKNOWNMAP;
+ s_startserver.mappics[i].generic.ownerdraw = StartServer_LevelshotDraw;
+
+ s_startserver.mapbuttons[i].generic.type = MTYPE_BITMAP;
+ s_startserver.mapbuttons[i].generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_NODEFAULTINIT;
+ s_startserver.mapbuttons[i].generic.id = ID_PICTURES+i;
+ s_startserver.mapbuttons[i].generic.callback = StartServer_MapEvent;
+ s_startserver.mapbuttons[i].generic.x = x - 30;
+ s_startserver.mapbuttons[i].generic.y = y - 32;
+ s_startserver.mapbuttons[i].width = 256;
+ s_startserver.mapbuttons[i].height = 248;
+ s_startserver.mapbuttons[i].generic.left = x;
+ s_startserver.mapbuttons[i].generic.top = y;
+ s_startserver.mapbuttons[i].generic.right = x + 128;
+ s_startserver.mapbuttons[i].generic.bottom = y + 128;
+ s_startserver.mapbuttons[i].focuspic = GAMESERVER_SELECT;
+ }
+
+ s_startserver.arrows.generic.type = MTYPE_BITMAP;
+ s_startserver.arrows.generic.name = GAMESERVER_ARROWS;
+ s_startserver.arrows.generic.flags = QMF_INACTIVE;
+ s_startserver.arrows.generic.x = 260;
+ s_startserver.arrows.generic.y = 400;
+ s_startserver.arrows.width = 128;
+ s_startserver.arrows.height = 32;
+
+ s_startserver.prevpage.generic.type = MTYPE_BITMAP;
+ s_startserver.prevpage.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_startserver.prevpage.generic.callback = StartServer_MenuEvent;
+ s_startserver.prevpage.generic.id = ID_PREVPAGE;
+ s_startserver.prevpage.generic.x = 260;
+ s_startserver.prevpage.generic.y = 400;
+ s_startserver.prevpage.width = 64;
+ s_startserver.prevpage.height = 32;
+ s_startserver.prevpage.focuspic = GAMESERVER_ARROWSL;
+
+ s_startserver.nextpage.generic.type = MTYPE_BITMAP;
+ s_startserver.nextpage.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_startserver.nextpage.generic.callback = StartServer_MenuEvent;
+ s_startserver.nextpage.generic.id = ID_NEXTPAGE;
+ s_startserver.nextpage.generic.x = 321;
+ s_startserver.nextpage.generic.y = 400;
+ s_startserver.nextpage.width = 64;
+ s_startserver.nextpage.height = 32;
+ s_startserver.nextpage.focuspic = GAMESERVER_ARROWSR;
+
+ s_startserver.mapname.generic.type = MTYPE_PTEXT;
+ s_startserver.mapname.generic.flags = QMF_CENTER_JUSTIFY|QMF_INACTIVE;
+ s_startserver.mapname.generic.x = 320;
+ s_startserver.mapname.generic.y = 440;
+ s_startserver.mapname.string = mapnamebuffer;
+ s_startserver.mapname.style = UI_CENTER|UI_BIGFONT;
+ s_startserver.mapname.color = text_color_normal;
+
+ s_startserver.back.generic.type = MTYPE_BITMAP;
+ s_startserver.back.generic.name = GAMESERVER_BACK0;
+ s_startserver.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_startserver.back.generic.callback = StartServer_MenuEvent;
+ s_startserver.back.generic.id = ID_STARTSERVERBACK;
+ s_startserver.back.generic.x = 0;
+ s_startserver.back.generic.y = 480-64;
+ s_startserver.back.width = 128;
+ s_startserver.back.height = 64;
+ s_startserver.back.focuspic = GAMESERVER_BACK1;
+
+ s_startserver.next.generic.type = MTYPE_BITMAP;
+ s_startserver.next.generic.name = GAMESERVER_NEXT0;
+ s_startserver.next.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_startserver.next.generic.callback = StartServer_MenuEvent;
+ s_startserver.next.generic.id = ID_STARTSERVERNEXT;
+ s_startserver.next.generic.x = 640;
+ s_startserver.next.generic.y = 480-64;
+ s_startserver.next.width = 128;
+ s_startserver.next.height = 64;
+ s_startserver.next.focuspic = GAMESERVER_NEXT1;
+
+ s_startserver.item_null.generic.type = MTYPE_BITMAP;
+ s_startserver.item_null.generic.flags = QMF_LEFT_JUSTIFY|QMF_MOUSEONLY|QMF_SILENT;
+ s_startserver.item_null.generic.x = 0;
+ s_startserver.item_null.generic.y = 0;
+ s_startserver.item_null.width = 640;
+ s_startserver.item_null.height = 480;
+
+ Menu_AddItem( &s_startserver.menu, &s_startserver.banner );
+ Menu_AddItem( &s_startserver.menu, &s_startserver.framel );
+ Menu_AddItem( &s_startserver.menu, &s_startserver.framer );
+
+ Menu_AddItem( &s_startserver.menu, &s_startserver.gametype );
+ for (i=0; i<MAX_MAPSPERPAGE; i++)
+ {
+ Menu_AddItem( &s_startserver.menu, &s_startserver.mappics[i] );
+ Menu_AddItem( &s_startserver.menu, &s_startserver.mapbuttons[i] );
+ }
+
+ Menu_AddItem( &s_startserver.menu, &s_startserver.arrows );
+ Menu_AddItem( &s_startserver.menu, &s_startserver.prevpage );
+ Menu_AddItem( &s_startserver.menu, &s_startserver.nextpage );
+ Menu_AddItem( &s_startserver.menu, &s_startserver.back );
+ Menu_AddItem( &s_startserver.menu, &s_startserver.next );
+ Menu_AddItem( &s_startserver.menu, &s_startserver.mapname );
+ Menu_AddItem( &s_startserver.menu, &s_startserver.item_null );
+
+ StartServer_GametypeEvent( NULL, QM_ACTIVATED );
+}
+
+
+/*
+=================
+StartServer_Cache
+=================
+*/
+void StartServer_Cache( void )
+{
+ int i;
+ const char *info;
+ qboolean precache;
+ char picname[64];
+
+ trap_R_RegisterShaderNoMip( GAMESERVER_BACK0 );
+ trap_R_RegisterShaderNoMip( GAMESERVER_BACK1 );
+ trap_R_RegisterShaderNoMip( GAMESERVER_NEXT0 );
+ trap_R_RegisterShaderNoMip( GAMESERVER_NEXT1 );
+ trap_R_RegisterShaderNoMip( GAMESERVER_FRAMEL );
+ trap_R_RegisterShaderNoMip( GAMESERVER_FRAMER );
+ trap_R_RegisterShaderNoMip( GAMESERVER_SELECT );
+ trap_R_RegisterShaderNoMip( GAMESERVER_SELECTED );
+ trap_R_RegisterShaderNoMip( GAMESERVER_UNKNOWNMAP );
+ trap_R_RegisterShaderNoMip( GAMESERVER_ARROWS );
+ trap_R_RegisterShaderNoMip( GAMESERVER_ARROWSL );
+ trap_R_RegisterShaderNoMip( GAMESERVER_ARROWSR );
+
+ precache = trap_Cvar_VariableValue("com_buildscript");
+
+ s_startserver.nummaps = UI_GetNumArenas();
+
+ for( i = 0; i < s_startserver.nummaps; i++ ) {
+ info = UI_GetArenaInfoByNumber( i );
+
+ Q_strncpyz( s_startserver.maplist[i], Info_ValueForKey( info, "map"), MAX_NAMELENGTH );
+ Q_strupr( s_startserver.maplist[i] );
+ s_startserver.mapGamebits[i] = GametypeBits( Info_ValueForKey( info, "type") );
+
+ if( precache ) {
+ Com_sprintf( picname, sizeof(picname), "levelshots/%s", s_startserver.maplist[i] );
+ trap_R_RegisterShaderNoMip(picname);
+ }
+ }
+
+ s_startserver.maxpages = (s_startserver.nummaps + MAX_MAPSPERPAGE-1)/MAX_MAPSPERPAGE;
+}
+
+
+/*
+=================
+UI_StartServerMenu
+=================
+*/
+void UI_StartServerMenu( qboolean multiplayer ) {
+ StartServer_MenuInit();
+ s_startserver.multiplayer = multiplayer;
+ UI_PushMenu( &s_startserver.menu );
+}
+
+
+
+/*
+=============================================================================
+
+SERVER OPTIONS MENU *****
+
+=============================================================================
+*/
+
+#define ID_PLAYER_TYPE 20
+#define ID_MAXCLIENTS 21
+#define ID_DEDICATED 22
+#define ID_GO 23
+#define ID_BACK 24
+
+#define PLAYER_SLOTS 12
+
+
+typedef struct {
+ menuframework_s menu;
+
+ menutext_s banner;
+
+ menubitmap_s mappic;
+ menubitmap_s picframe;
+
+ menulist_s dedicated;
+ menufield_s timelimit;
+ menufield_s fraglimit;
+ menufield_s flaglimit;
+ menuradiobutton_s friendlyfire;
+ menufield_s hostname;
+ menuradiobutton_s pure;
+ menulist_s botSkill;
+
+ menutext_s player0;
+ menulist_s playerType[PLAYER_SLOTS];
+ menutext_s playerName[PLAYER_SLOTS];
+ menulist_s playerTeam[PLAYER_SLOTS];
+
+ menubitmap_s go;
+ menubitmap_s next;
+ menubitmap_s back;
+
+ qboolean multiplayer;
+ int gametype;
+ char mapnamebuffer[32];
+ char playerNameBuffers[PLAYER_SLOTS][16];
+
+ qboolean newBot;
+ int newBotIndex;
+ char newBotName[16];
+
+ menulist_s punkbuster;
+} serveroptions_t;
+
+static serveroptions_t s_serveroptions;
+
+static const char *dedicated_list[] = {
+ "No",
+ "LAN",
+ "Internet",
+ 0
+};
+
+static const char *playerType_list[] = {
+ "Open",
+ "Bot",
+ "----",
+ 0
+};
+
+static const char *playerTeam_list[] = {
+ "Blue",
+ "Red",
+ 0
+};
+
+static const char *botSkill_list[] = {
+ "I Can Win",
+ "Bring It On",
+ "Hurt Me Plenty",
+ "Hardcore",
+ "Nightmare!",
+ 0
+};
+
+
+/*
+=================
+BotAlreadySelected
+=================
+*/
+static qboolean BotAlreadySelected( const char *checkName ) {
+ int n;
+
+ for( n = 1; n < PLAYER_SLOTS; n++ ) {
+ if( s_serveroptions.playerType[n].curvalue != 1 ) {
+ continue;
+ }
+ if( (s_serveroptions.gametype >= GT_TEAM) &&
+ (s_serveroptions.playerTeam[n].curvalue != s_serveroptions.playerTeam[s_serveroptions.newBotIndex].curvalue ) ) {
+ continue;
+ }
+ if( Q_stricmp( checkName, s_serveroptions.playerNameBuffers[n] ) == 0 ) {
+ return qtrue;
+ }
+ }
+
+ return qfalse;
+}
+
+
+/*
+=================
+ServerOptions_Start
+=================
+*/
+static void ServerOptions_Start( void ) {
+ int timelimit;
+ int fraglimit;
+ int maxclients;
+ int dedicated;
+ int friendlyfire;
+ int flaglimit;
+ int pure;
+ int skill;
+ int n;
+ char buf[64];
+
+
+ timelimit = atoi( s_serveroptions.timelimit.field.buffer );
+ fraglimit = atoi( s_serveroptions.fraglimit.field.buffer );
+ flaglimit = atoi( s_serveroptions.flaglimit.field.buffer );
+ dedicated = s_serveroptions.dedicated.curvalue;
+ friendlyfire = s_serveroptions.friendlyfire.curvalue;
+ pure = s_serveroptions.pure.curvalue;
+ skill = s_serveroptions.botSkill.curvalue + 1;
+
+ //set maxclients
+ for( n = 0, maxclients = 0; n < PLAYER_SLOTS; n++ ) {
+ if( s_serveroptions.playerType[n].curvalue == 2 ) {
+ continue;
+ }
+ if( (s_serveroptions.playerType[n].curvalue == 1) && (s_serveroptions.playerNameBuffers[n][0] == 0) ) {
+ continue;
+ }
+ maxclients++;
+ }
+
+ switch( s_serveroptions.gametype ) {
+ case GT_FFA:
+ default:
+ trap_Cvar_SetValue( "ui_ffa_fraglimit", fraglimit );
+ trap_Cvar_SetValue( "ui_ffa_timelimit", timelimit );
+ break;
+
+ case GT_TOURNAMENT:
+ trap_Cvar_SetValue( "ui_tourney_fraglimit", fraglimit );
+ trap_Cvar_SetValue( "ui_tourney_timelimit", timelimit );
+ break;
+
+ case GT_TEAM:
+ trap_Cvar_SetValue( "ui_team_fraglimit", fraglimit );
+ trap_Cvar_SetValue( "ui_team_timelimit", timelimit );
+ trap_Cvar_SetValue( "ui_team_friendlt", friendlyfire );
+ break;
+
+ case GT_CTF:
+ trap_Cvar_SetValue( "ui_ctf_fraglimit", fraglimit );
+ trap_Cvar_SetValue( "ui_ctf_timelimit", timelimit );
+ trap_Cvar_SetValue( "ui_ctf_friendlt", friendlyfire );
+ break;
+ }
+
+ trap_Cvar_SetValue( "sv_maxclients", Com_Clamp( 0, 12, maxclients ) );
+ trap_Cvar_SetValue( "dedicated", Com_Clamp( 0, 2, dedicated ) );
+ trap_Cvar_SetValue ("timelimit", Com_Clamp( 0, timelimit, timelimit ) );
+ trap_Cvar_SetValue ("fraglimit", Com_Clamp( 0, fraglimit, fraglimit ) );
+ trap_Cvar_SetValue ("capturelimit", Com_Clamp( 0, flaglimit, flaglimit ) );
+ trap_Cvar_SetValue( "g_friendlyfire", friendlyfire );
+ trap_Cvar_SetValue( "sv_pure", pure );
+ trap_Cvar_Set("sv_hostname", s_serveroptions.hostname.field.buffer );
+
+ trap_Cvar_SetValue( "sv_punkbuster", s_serveroptions.punkbuster.curvalue );
+
+ // the wait commands will allow the dedicated to take effect
+ trap_Cmd_ExecuteText( EXEC_APPEND, va( "wait ; wait ; map %s\n", s_startserver.maplist[s_startserver.currentmap] ) );
+
+ // add bots
+ trap_Cmd_ExecuteText( EXEC_APPEND, "wait 3\n" );
+ for( n = 1; n < PLAYER_SLOTS; n++ ) {
+ if( s_serveroptions.playerType[n].curvalue != 1 ) {
+ continue;
+ }
+ if( s_serveroptions.playerNameBuffers[n][0] == 0 ) {
+ continue;
+ }
+ if( s_serveroptions.playerNameBuffers[n][0] == '-' ) {
+ continue;
+ }
+ if( s_serveroptions.gametype >= GT_TEAM ) {
+ Com_sprintf( buf, sizeof(buf), "addbot %s %i %s\n", s_serveroptions.playerNameBuffers[n], skill,
+ playerTeam_list[s_serveroptions.playerTeam[n].curvalue] );
+ }
+ else {
+ Com_sprintf( buf, sizeof(buf), "addbot %s %i\n", s_serveroptions.playerNameBuffers[n], skill );
+ }
+ trap_Cmd_ExecuteText( EXEC_APPEND, buf );
+ }
+
+ // set player's team
+ if( dedicated == 0 && s_serveroptions.gametype >= GT_TEAM ) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, va( "wait 5; team %s\n", playerTeam_list[s_serveroptions.playerTeam[0].curvalue] ) );
+ }
+}
+
+
+/*
+=================
+ServerOptions_InitPlayerItems
+=================
+*/
+static void ServerOptions_InitPlayerItems( void ) {
+ int n;
+ int v;
+
+ // init types
+ if( s_serveroptions.multiplayer ) {
+ v = 0; // open
+ }
+ else {
+ v = 1; // bot
+ }
+
+ for( n = 0; n < PLAYER_SLOTS; n++ ) {
+ s_serveroptions.playerType[n].curvalue = v;
+ }
+
+ if( s_serveroptions.multiplayer && (s_serveroptions.gametype < GT_TEAM) ) {
+ for( n = 8; n < PLAYER_SLOTS; n++ ) {
+ s_serveroptions.playerType[n].curvalue = 2;
+ }
+ }
+
+ // if not a dedicated server, first slot is reserved for the human on the server
+ if( s_serveroptions.dedicated.curvalue == 0 ) {
+ // human
+ s_serveroptions.playerType[0].generic.flags |= QMF_INACTIVE;
+ s_serveroptions.playerType[0].curvalue = 0;
+ trap_Cvar_VariableStringBuffer( "name", s_serveroptions.playerNameBuffers[0], sizeof(s_serveroptions.playerNameBuffers[0]) );
+ Q_CleanStr( s_serveroptions.playerNameBuffers[0] );
+ }
+
+ // init teams
+ if( s_serveroptions.gametype >= GT_TEAM ) {
+ for( n = 0; n < (PLAYER_SLOTS / 2); n++ ) {
+ s_serveroptions.playerTeam[n].curvalue = 0;
+ }
+ for( ; n < PLAYER_SLOTS; n++ ) {
+ s_serveroptions.playerTeam[n].curvalue = 1;
+ }
+ }
+ else {
+ for( n = 0; n < PLAYER_SLOTS; n++ ) {
+ s_serveroptions.playerTeam[n].generic.flags |= (QMF_INACTIVE|QMF_HIDDEN);
+ }
+ }
+}
+
+
+/*
+=================
+ServerOptions_SetPlayerItems
+=================
+*/
+static void ServerOptions_SetPlayerItems( void ) {
+ int start;
+ int n;
+
+ // types
+// for( n = 0; n < PLAYER_SLOTS; n++ ) {
+// if( (!s_serveroptions.multiplayer) && (n > 0) && (s_serveroptions.playerType[n].curvalue == 0) ) {
+// s_serveroptions.playerType[n].curvalue = 1;
+// }
+// }
+
+ // names
+ if( s_serveroptions.dedicated.curvalue == 0 ) {
+ s_serveroptions.player0.string = "Human";
+ s_serveroptions.playerName[0].generic.flags &= ~QMF_HIDDEN;
+
+ start = 1;
+ }
+ else {
+ s_serveroptions.player0.string = "Open";
+ start = 0;
+ }
+ for( n = start; n < PLAYER_SLOTS; n++ ) {
+ if( s_serveroptions.playerType[n].curvalue == 1 ) {
+ s_serveroptions.playerName[n].generic.flags &= ~(QMF_INACTIVE|QMF_HIDDEN);
+ }
+ else {
+ s_serveroptions.playerName[n].generic.flags |= (QMF_INACTIVE|QMF_HIDDEN);
+ }
+ }
+
+ // teams
+ if( s_serveroptions.gametype < GT_TEAM ) {
+ return;
+ }
+ for( n = start; n < PLAYER_SLOTS; n++ ) {
+ if( s_serveroptions.playerType[n].curvalue == 2 ) {
+ s_serveroptions.playerTeam[n].generic.flags |= (QMF_INACTIVE|QMF_HIDDEN);
+ }
+ else {
+ s_serveroptions.playerTeam[n].generic.flags &= ~(QMF_INACTIVE|QMF_HIDDEN);
+ }
+ }
+}
+
+
+/*
+=================
+ServerOptions_Event
+=================
+*/
+static void ServerOptions_Event( void* ptr, int event ) {
+ switch( ((menucommon_s*)ptr)->id ) {
+
+ //if( event != QM_ACTIVATED && event != QM_LOSTFOCUS) {
+ // return;
+ //}
+ case ID_PLAYER_TYPE:
+ if( event != QM_ACTIVATED ) {
+ break;
+ }
+ ServerOptions_SetPlayerItems();
+ break;
+
+ case ID_MAXCLIENTS:
+ case ID_DEDICATED:
+ ServerOptions_SetPlayerItems();
+ break;
+ case ID_GO:
+ if( event != QM_ACTIVATED ) {
+ break;
+ }
+ ServerOptions_Start();
+ break;
+
+ case ID_STARTSERVERNEXT:
+ if( event != QM_ACTIVATED ) {
+ break;
+ }
+ break;
+ case ID_BACK:
+ if( event != QM_ACTIVATED ) {
+ break;
+ }
+ UI_PopMenu();
+ break;
+ }
+}
+
+
+static void ServerOptions_PlayerNameEvent( void* ptr, int event ) {
+ int n;
+
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+ n = ((menutext_s*)ptr)->generic.id;
+ s_serveroptions.newBotIndex = n;
+ UI_BotSelectMenu( s_serveroptions.playerNameBuffers[n] );
+}
+
+
+/*
+=================
+ServerOptions_StatusBar
+=================
+*/
+static void ServerOptions_StatusBar( void* ptr ) {
+ switch( ((menucommon_s*)ptr)->id ) {
+ default:
+ UI_DrawString( 320, 440, "0 = NO LIMIT", UI_CENTER|UI_SMALLFONT, colorWhite );
+ break;
+ }
+}
+
+
+/*
+===============
+ServerOptions_LevelshotDraw
+===============
+*/
+static void ServerOptions_LevelshotDraw( void *self ) {
+ menubitmap_s *b;
+ int x;
+ int y;
+
+ // strange place for this, but it works
+ if( s_serveroptions.newBot ) {
+ Q_strncpyz( s_serveroptions.playerNameBuffers[s_serveroptions.newBotIndex], s_serveroptions.newBotName, 16 );
+ s_serveroptions.newBot = qfalse;
+ }
+
+ b = (menubitmap_s *)self;
+
+ Bitmap_Draw( b );
+
+ x = b->generic.x;
+ y = b->generic.y + b->height;
+ UI_FillRect( x, y, b->width, 40, colorBlack );
+
+ x += b->width / 2;
+ y += 4;
+ UI_DrawString( x, y, s_serveroptions.mapnamebuffer, UI_CENTER|UI_SMALLFONT, color_orange );
+
+ y += SMALLCHAR_HEIGHT;
+ UI_DrawString( x, y, gametype_items[gametype_remap2[s_serveroptions.gametype]], UI_CENTER|UI_SMALLFONT, color_orange );
+}
+
+
+static void ServerOptions_InitBotNames( void ) {
+ int count;
+ int n;
+ const char *arenaInfo;
+ const char *botInfo;
+ char *p;
+ char *bot;
+ char bots[MAX_INFO_STRING];
+
+ if( s_serveroptions.gametype >= GT_TEAM ) {
+ Q_strncpyz( s_serveroptions.playerNameBuffers[1], "grunt", 16 );
+ Q_strncpyz( s_serveroptions.playerNameBuffers[2], "major", 16 );
+ if( s_serveroptions.gametype == GT_TEAM ) {
+ Q_strncpyz( s_serveroptions.playerNameBuffers[3], "visor", 16 );
+ }
+ else {
+ s_serveroptions.playerType[3].curvalue = 2;
+ }
+ s_serveroptions.playerType[4].curvalue = 2;
+ s_serveroptions.playerType[5].curvalue = 2;
+
+ Q_strncpyz( s_serveroptions.playerNameBuffers[6], "sarge", 16 );
+ Q_strncpyz( s_serveroptions.playerNameBuffers[7], "grunt", 16 );
+ Q_strncpyz( s_serveroptions.playerNameBuffers[8], "major", 16 );
+ if( s_serveroptions.gametype == GT_TEAM ) {
+ Q_strncpyz( s_serveroptions.playerNameBuffers[9], "visor", 16 );
+ }
+ else {
+ s_serveroptions.playerType[9].curvalue = 2;
+ }
+ s_serveroptions.playerType[10].curvalue = 2;
+ s_serveroptions.playerType[11].curvalue = 2;
+
+ return;
+ }
+
+ count = 1; // skip the first slot, reserved for a human
+
+ // get info for this map
+ arenaInfo = UI_GetArenaInfoByMap( s_serveroptions.mapnamebuffer );
+
+ // get the bot info - we'll seed with them if any are listed
+ Q_strncpyz( bots, Info_ValueForKey( arenaInfo, "bots" ), sizeof(bots) );
+ p = &bots[0];
+ while( *p && count < PLAYER_SLOTS ) {
+ //skip spaces
+ while( *p && *p == ' ' ) {
+ p++;
+ }
+ if( !p ) {
+ break;
+ }
+
+ // mark start of bot name
+ bot = p;
+
+ // skip until space of null
+ while( *p && *p != ' ' ) {
+ p++;
+ }
+ if( *p ) {
+ *p++ = 0;
+ }
+
+ botInfo = UI_GetBotInfoByName( bot );
+ bot = Info_ValueForKey( botInfo, "name" );
+
+ Q_strncpyz( s_serveroptions.playerNameBuffers[count], bot, sizeof(s_serveroptions.playerNameBuffers[count]) );
+ count++;
+ }
+
+ // set the rest of the bot slots to "---"
+ for( n = count; n < PLAYER_SLOTS; n++ ) {
+ strcpy( s_serveroptions.playerNameBuffers[n], "--------" );
+ }
+
+ // pad up to #8 as open slots
+ for( ;count < 8; count++ ) {
+ s_serveroptions.playerType[count].curvalue = 0;
+ }
+
+ // close off the rest by default
+ for( ;count < PLAYER_SLOTS; count++ ) {
+ if( s_serveroptions.playerType[count].curvalue == 1 ) {
+ s_serveroptions.playerType[count].curvalue = 2;
+ }
+ }
+}
+
+
+/*
+=================
+ServerOptions_SetMenuItems
+=================
+*/
+static void ServerOptions_SetMenuItems( void ) {
+ static char picname[64];
+
+ switch( s_serveroptions.gametype ) {
+ case GT_FFA:
+ default:
+ Com_sprintf( s_serveroptions.fraglimit.field.buffer, 4, "%i", (int)Com_Clamp( 0, 999, trap_Cvar_VariableValue( "ui_ffa_fraglimit" ) ) );
+ Com_sprintf( s_serveroptions.timelimit.field.buffer, 4, "%i", (int)Com_Clamp( 0, 999, trap_Cvar_VariableValue( "ui_ffa_timelimit" ) ) );
+ break;
+
+ case GT_TOURNAMENT:
+ Com_sprintf( s_serveroptions.fraglimit.field.buffer, 4, "%i", (int)Com_Clamp( 0, 999, trap_Cvar_VariableValue( "ui_tourney_fraglimit" ) ) );
+ Com_sprintf( s_serveroptions.timelimit.field.buffer, 4, "%i", (int)Com_Clamp( 0, 999, trap_Cvar_VariableValue( "ui_tourney_timelimit" ) ) );
+ break;
+
+ case GT_TEAM:
+ Com_sprintf( s_serveroptions.fraglimit.field.buffer, 4, "%i", (int)Com_Clamp( 0, 999, trap_Cvar_VariableValue( "ui_team_fraglimit" ) ) );
+ Com_sprintf( s_serveroptions.timelimit.field.buffer, 4, "%i", (int)Com_Clamp( 0, 999, trap_Cvar_VariableValue( "ui_team_timelimit" ) ) );
+ s_serveroptions.friendlyfire.curvalue = (int)Com_Clamp( 0, 1, trap_Cvar_VariableValue( "ui_team_friendly" ) );
+ break;
+
+ case GT_CTF:
+ Com_sprintf( s_serveroptions.flaglimit.field.buffer, 4, "%i", (int)Com_Clamp( 0, 100, trap_Cvar_VariableValue( "ui_ctf_capturelimit" ) ) );
+ Com_sprintf( s_serveroptions.timelimit.field.buffer, 4, "%i", (int)Com_Clamp( 0, 999, trap_Cvar_VariableValue( "ui_ctf_timelimit" ) ) );
+ s_serveroptions.friendlyfire.curvalue = (int)Com_Clamp( 0, 1, trap_Cvar_VariableValue( "ui_ctf_friendly" ) );
+ break;
+ }
+
+ Q_strncpyz( s_serveroptions.hostname.field.buffer, UI_Cvar_VariableString( "sv_hostname" ), sizeof( s_serveroptions.hostname.field.buffer ) );
+ s_serveroptions.pure.curvalue = Com_Clamp( 0, 1, trap_Cvar_VariableValue( "sv_pure" ) );
+
+ // set the map pic
+ Com_sprintf( picname, 64, "levelshots/%s", s_startserver.maplist[s_startserver.currentmap] );
+ s_serveroptions.mappic.generic.name = picname;
+
+ // set the map name
+ strcpy( s_serveroptions.mapnamebuffer, s_startserver.mapname.string );
+ Q_strupr( s_serveroptions.mapnamebuffer );
+
+ // get the player selections initialized
+ ServerOptions_InitPlayerItems();
+ ServerOptions_SetPlayerItems();
+
+ // seed bot names
+ ServerOptions_InitBotNames();
+ ServerOptions_SetPlayerItems();
+}
+
+/*
+=================
+PlayerName_Draw
+=================
+*/
+static void PlayerName_Draw( void *item ) {
+ menutext_s *s;
+ float *color;
+ int x, y;
+ int style;
+ qboolean focus;
+
+ s = (menutext_s *)item;
+
+ x = s->generic.x;
+ y = s->generic.y;
+
+ style = UI_SMALLFONT;
+ focus = (s->generic.parent->cursor == s->generic.menuPosition);
+
+ if ( s->generic.flags & QMF_GRAYED )
+ color = text_color_disabled;
+ else if ( focus )
+ {
+ color = text_color_highlight;
+ style |= UI_PULSE;
+ }
+ else if ( s->generic.flags & QMF_BLINK )
+ {
+ color = text_color_highlight;
+ style |= UI_BLINK;
+ }
+ else
+ color = text_color_normal;
+
+ if ( focus )
+ {
+ // draw cursor
+ UI_FillRect( s->generic.left, s->generic.top, s->generic.right-s->generic.left+1, s->generic.bottom-s->generic.top+1, listbar_color );
+ UI_DrawChar( x, y, 13, UI_CENTER|UI_BLINK|UI_SMALLFONT, color);
+ }
+
+ UI_DrawString( x - SMALLCHAR_WIDTH, y, s->generic.name, style|UI_RIGHT, color );
+ UI_DrawString( x + SMALLCHAR_WIDTH, y, s->string, style|UI_LEFT, color );
+}
+
+
+/*
+=================
+ServerOptions_MenuInit
+=================
+*/
+#define OPTIONS_X 456
+
+static void ServerOptions_MenuInit( qboolean multiplayer ) {
+ int y;
+ int n;
+
+ memset( &s_serveroptions, 0 ,sizeof(serveroptions_t) );
+ s_serveroptions.multiplayer = multiplayer;
+ s_serveroptions.gametype = (int)Com_Clamp( 0, 5, trap_Cvar_VariableValue( "g_gameType" ) );
+ s_serveroptions.punkbuster.curvalue = Com_Clamp( 0, 1, trap_Cvar_VariableValue( "sv_punkbuster" ) );
+
+ ServerOptions_Cache();
+
+ s_serveroptions.menu.wrapAround = qtrue;
+ s_serveroptions.menu.fullscreen = qtrue;
+
+ s_serveroptions.banner.generic.type = MTYPE_BTEXT;
+ s_serveroptions.banner.generic.x = 320;
+ s_serveroptions.banner.generic.y = 16;
+ s_serveroptions.banner.string = "GAME SERVER";
+ s_serveroptions.banner.color = color_white;
+ s_serveroptions.banner.style = UI_CENTER;
+
+ s_serveroptions.mappic.generic.type = MTYPE_BITMAP;
+ s_serveroptions.mappic.generic.flags = QMF_LEFT_JUSTIFY|QMF_INACTIVE;
+ s_serveroptions.mappic.generic.x = 352;
+ s_serveroptions.mappic.generic.y = 80;
+ s_serveroptions.mappic.width = 160;
+ s_serveroptions.mappic.height = 120;
+ s_serveroptions.mappic.errorpic = GAMESERVER_UNKNOWNMAP;
+ s_serveroptions.mappic.generic.ownerdraw = ServerOptions_LevelshotDraw;
+
+ s_serveroptions.picframe.generic.type = MTYPE_BITMAP;
+ s_serveroptions.picframe.generic.flags = QMF_LEFT_JUSTIFY|QMF_INACTIVE|QMF_HIGHLIGHT;
+ s_serveroptions.picframe.generic.x = 352 - 38;
+ s_serveroptions.picframe.generic.y = 80 - 40;
+ s_serveroptions.picframe.width = 320;
+ s_serveroptions.picframe.height = 320;
+ s_serveroptions.picframe.focuspic = GAMESERVER_SELECT;
+
+ y = 272;
+ if( s_serveroptions.gametype != GT_CTF ) {
+ s_serveroptions.fraglimit.generic.type = MTYPE_FIELD;
+ s_serveroptions.fraglimit.generic.name = "Frag Limit:";
+ s_serveroptions.fraglimit.generic.flags = QMF_NUMBERSONLY|QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_serveroptions.fraglimit.generic.x = OPTIONS_X;
+ s_serveroptions.fraglimit.generic.y = y;
+ s_serveroptions.fraglimit.generic.statusbar = ServerOptions_StatusBar;
+ s_serveroptions.fraglimit.field.widthInChars = 3;
+ s_serveroptions.fraglimit.field.maxchars = 3;
+ }
+ else {
+ s_serveroptions.flaglimit.generic.type = MTYPE_FIELD;
+ s_serveroptions.flaglimit.generic.name = "Capture Limit:";
+ s_serveroptions.flaglimit.generic.flags = QMF_NUMBERSONLY|QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_serveroptions.flaglimit.generic.x = OPTIONS_X;
+ s_serveroptions.flaglimit.generic.y = y;
+ s_serveroptions.flaglimit.generic.statusbar = ServerOptions_StatusBar;
+ s_serveroptions.flaglimit.field.widthInChars = 3;
+ s_serveroptions.flaglimit.field.maxchars = 3;
+ }
+
+ y += BIGCHAR_HEIGHT+2;
+ s_serveroptions.timelimit.generic.type = MTYPE_FIELD;
+ s_serveroptions.timelimit.generic.name = "Time Limit:";
+ s_serveroptions.timelimit.generic.flags = QMF_NUMBERSONLY|QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_serveroptions.timelimit.generic.x = OPTIONS_X;
+ s_serveroptions.timelimit.generic.y = y;
+ s_serveroptions.timelimit.generic.statusbar = ServerOptions_StatusBar;
+ s_serveroptions.timelimit.field.widthInChars = 3;
+ s_serveroptions.timelimit.field.maxchars = 3;
+
+ if( s_serveroptions.gametype >= GT_TEAM ) {
+ y += BIGCHAR_HEIGHT+2;
+ s_serveroptions.friendlyfire.generic.type = MTYPE_RADIOBUTTON;
+ s_serveroptions.friendlyfire.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_serveroptions.friendlyfire.generic.x = OPTIONS_X;
+ s_serveroptions.friendlyfire.generic.y = y;
+ s_serveroptions.friendlyfire.generic.name = "Friendly Fire:";
+ }
+
+ y += BIGCHAR_HEIGHT+2;
+ s_serveroptions.pure.generic.type = MTYPE_RADIOBUTTON;
+ s_serveroptions.pure.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_serveroptions.pure.generic.x = OPTIONS_X;
+ s_serveroptions.pure.generic.y = y;
+ s_serveroptions.pure.generic.name = "Pure Server:";
+
+ if( s_serveroptions.multiplayer ) {
+ y += BIGCHAR_HEIGHT+2;
+ s_serveroptions.dedicated.generic.type = MTYPE_SPINCONTROL;
+ s_serveroptions.dedicated.generic.id = ID_DEDICATED;
+ s_serveroptions.dedicated.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_serveroptions.dedicated.generic.callback = ServerOptions_Event;
+ s_serveroptions.dedicated.generic.x = OPTIONS_X;
+ s_serveroptions.dedicated.generic.y = y;
+ s_serveroptions.dedicated.generic.name = "Dedicated:";
+ s_serveroptions.dedicated.itemnames = dedicated_list;
+ }
+
+ if( s_serveroptions.multiplayer ) {
+ y += BIGCHAR_HEIGHT+2;
+ s_serveroptions.hostname.generic.type = MTYPE_FIELD;
+ s_serveroptions.hostname.generic.name = "Hostname:";
+ s_serveroptions.hostname.generic.flags = QMF_SMALLFONT;
+ s_serveroptions.hostname.generic.x = OPTIONS_X;
+ s_serveroptions.hostname.generic.y = y;
+ s_serveroptions.hostname.field.widthInChars = 18;
+ s_serveroptions.hostname.field.maxchars = 64;
+ }
+
+ y += BIGCHAR_HEIGHT+2;
+ s_serveroptions.punkbuster.generic.type = MTYPE_SPINCONTROL;
+ s_serveroptions.punkbuster.generic.name = "Punkbuster:";
+ s_serveroptions.punkbuster.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_serveroptions.punkbuster.generic.id = 0;
+ s_serveroptions.punkbuster.generic.x = OPTIONS_X;
+ s_serveroptions.punkbuster.generic.y = y;
+ s_serveroptions.punkbuster.itemnames = punkbuster_items;
+
+ y = 80;
+ s_serveroptions.botSkill.generic.type = MTYPE_SPINCONTROL;
+ s_serveroptions.botSkill.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_serveroptions.botSkill.generic.name = "Bot Skill: ";
+ s_serveroptions.botSkill.generic.x = 32 + (strlen(s_serveroptions.botSkill.generic.name) + 2 ) * SMALLCHAR_WIDTH;
+ s_serveroptions.botSkill.generic.y = y;
+ s_serveroptions.botSkill.itemnames = botSkill_list;
+ s_serveroptions.botSkill.curvalue = 1;
+
+ y += ( 2 * SMALLCHAR_HEIGHT );
+ s_serveroptions.player0.generic.type = MTYPE_TEXT;
+ s_serveroptions.player0.generic.flags = QMF_SMALLFONT;
+ s_serveroptions.player0.generic.x = 32 + SMALLCHAR_WIDTH;
+ s_serveroptions.player0.generic.y = y;
+ s_serveroptions.player0.color = color_orange;
+ s_serveroptions.player0.style = UI_LEFT|UI_SMALLFONT;
+
+ for( n = 0; n < PLAYER_SLOTS; n++ ) {
+ s_serveroptions.playerType[n].generic.type = MTYPE_SPINCONTROL;
+ s_serveroptions.playerType[n].generic.flags = QMF_SMALLFONT;
+ s_serveroptions.playerType[n].generic.id = ID_PLAYER_TYPE;
+ s_serveroptions.playerType[n].generic.callback = ServerOptions_Event;
+ s_serveroptions.playerType[n].generic.x = 32;
+ s_serveroptions.playerType[n].generic.y = y;
+ s_serveroptions.playerType[n].itemnames = playerType_list;
+
+ s_serveroptions.playerName[n].generic.type = MTYPE_TEXT;
+ s_serveroptions.playerName[n].generic.flags = QMF_SMALLFONT;
+ s_serveroptions.playerName[n].generic.x = 96;
+ s_serveroptions.playerName[n].generic.y = y;
+ s_serveroptions.playerName[n].generic.callback = ServerOptions_PlayerNameEvent;
+ s_serveroptions.playerName[n].generic.id = n;
+ s_serveroptions.playerName[n].generic.ownerdraw = PlayerName_Draw;
+ s_serveroptions.playerName[n].color = color_orange;
+ s_serveroptions.playerName[n].style = UI_SMALLFONT;
+ s_serveroptions.playerName[n].string = s_serveroptions.playerNameBuffers[n];
+ s_serveroptions.playerName[n].generic.top = s_serveroptions.playerName[n].generic.y;
+ s_serveroptions.playerName[n].generic.bottom = s_serveroptions.playerName[n].generic.y + SMALLCHAR_HEIGHT;
+ s_serveroptions.playerName[n].generic.left = s_serveroptions.playerName[n].generic.x - SMALLCHAR_HEIGHT/ 2;
+ s_serveroptions.playerName[n].generic.right = s_serveroptions.playerName[n].generic.x + 16 * SMALLCHAR_WIDTH;
+
+ s_serveroptions.playerTeam[n].generic.type = MTYPE_SPINCONTROL;
+ s_serveroptions.playerTeam[n].generic.flags = QMF_SMALLFONT;
+ s_serveroptions.playerTeam[n].generic.x = 240;
+ s_serveroptions.playerTeam[n].generic.y = y;
+ s_serveroptions.playerTeam[n].itemnames = playerTeam_list;
+
+ y += ( SMALLCHAR_HEIGHT + 4 );
+ }
+
+ s_serveroptions.back.generic.type = MTYPE_BITMAP;
+ s_serveroptions.back.generic.name = GAMESERVER_BACK0;
+ s_serveroptions.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_serveroptions.back.generic.callback = ServerOptions_Event;
+ s_serveroptions.back.generic.id = ID_BACK;
+ s_serveroptions.back.generic.x = 0;
+ s_serveroptions.back.generic.y = 480-64;
+ s_serveroptions.back.width = 128;
+ s_serveroptions.back.height = 64;
+ s_serveroptions.back.focuspic = GAMESERVER_BACK1;
+
+ s_serveroptions.next.generic.type = MTYPE_BITMAP;
+ s_serveroptions.next.generic.name = GAMESERVER_NEXT0;
+ s_serveroptions.next.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_INACTIVE|QMF_GRAYED|QMF_HIDDEN;
+ s_serveroptions.next.generic.callback = ServerOptions_Event;
+ s_serveroptions.next.generic.id = ID_STARTSERVERNEXT;
+ s_serveroptions.next.generic.x = 640;
+ s_serveroptions.next.generic.y = 480-64-72;
+ s_serveroptions.next.generic.statusbar = ServerOptions_StatusBar;
+ s_serveroptions.next.width = 128;
+ s_serveroptions.next.height = 64;
+ s_serveroptions.next.focuspic = GAMESERVER_NEXT1;
+
+ s_serveroptions.go.generic.type = MTYPE_BITMAP;
+ s_serveroptions.go.generic.name = GAMESERVER_FIGHT0;
+ s_serveroptions.go.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_serveroptions.go.generic.callback = ServerOptions_Event;
+ s_serveroptions.go.generic.id = ID_GO;
+ s_serveroptions.go.generic.x = 640;
+ s_serveroptions.go.generic.y = 480-64;
+ s_serveroptions.go.width = 128;
+ s_serveroptions.go.height = 64;
+ s_serveroptions.go.focuspic = GAMESERVER_FIGHT1;
+
+ Menu_AddItem( &s_serveroptions.menu, &s_serveroptions.banner );
+
+ Menu_AddItem( &s_serveroptions.menu, &s_serveroptions.mappic );
+ Menu_AddItem( &s_serveroptions.menu, &s_serveroptions.picframe );
+
+ Menu_AddItem( &s_serveroptions.menu, &s_serveroptions.botSkill );
+ Menu_AddItem( &s_serveroptions.menu, &s_serveroptions.player0 );
+ for( n = 0; n < PLAYER_SLOTS; n++ ) {
+ if( n != 0 ) {
+ Menu_AddItem( &s_serveroptions.menu, &s_serveroptions.playerType[n] );
+ }
+ Menu_AddItem( &s_serveroptions.menu, &s_serveroptions.playerName[n] );
+ if( s_serveroptions.gametype >= GT_TEAM ) {
+ Menu_AddItem( &s_serveroptions.menu, &s_serveroptions.playerTeam[n] );
+ }
+ }
+
+ if( s_serveroptions.gametype != GT_CTF ) {
+ Menu_AddItem( &s_serveroptions.menu, &s_serveroptions.fraglimit );
+ }
+ else {
+ Menu_AddItem( &s_serveroptions.menu, &s_serveroptions.flaglimit );
+ }
+ Menu_AddItem( &s_serveroptions.menu, &s_serveroptions.timelimit );
+ if( s_serveroptions.gametype >= GT_TEAM ) {
+ Menu_AddItem( &s_serveroptions.menu, &s_serveroptions.friendlyfire );
+ }
+ Menu_AddItem( &s_serveroptions.menu, &s_serveroptions.pure );
+ if( s_serveroptions.multiplayer ) {
+ Menu_AddItem( &s_serveroptions.menu, &s_serveroptions.dedicated );
+ }
+ if( s_serveroptions.multiplayer ) {
+ Menu_AddItem( &s_serveroptions.menu, &s_serveroptions.hostname );
+ }
+
+ Menu_AddItem( &s_serveroptions.menu, &s_serveroptions.back );
+ Menu_AddItem( &s_serveroptions.menu, &s_serveroptions.next );
+ Menu_AddItem( &s_serveroptions.menu, &s_serveroptions.go );
+
+ Menu_AddItem( &s_serveroptions.menu, (void*) &s_serveroptions.punkbuster );
+
+ ServerOptions_SetMenuItems();
+}
+
+/*
+=================
+ServerOptions_Cache
+=================
+*/
+void ServerOptions_Cache( void ) {
+ trap_R_RegisterShaderNoMip( GAMESERVER_BACK0 );
+ trap_R_RegisterShaderNoMip( GAMESERVER_BACK1 );
+ trap_R_RegisterShaderNoMip( GAMESERVER_FIGHT0 );
+ trap_R_RegisterShaderNoMip( GAMESERVER_FIGHT1 );
+ trap_R_RegisterShaderNoMip( GAMESERVER_SELECT );
+ trap_R_RegisterShaderNoMip( GAMESERVER_UNKNOWNMAP );
+}
+
+
+/*
+=================
+UI_ServerOptionsMenu
+=================
+*/
+static void UI_ServerOptionsMenu( qboolean multiplayer ) {
+ ServerOptions_MenuInit( multiplayer );
+ UI_PushMenu( &s_serveroptions.menu );
+}
+
+
+
+/*
+=============================================================================
+
+BOT SELECT MENU *****
+
+=============================================================================
+*/
+
+
+#define BOTSELECT_BACK0 "menu/art/back_0"
+#define BOTSELECT_BACK1 "menu/art/back_1"
+#define BOTSELECT_ACCEPT0 "menu/art/accept_0"
+#define BOTSELECT_ACCEPT1 "menu/art/accept_1"
+#define BOTSELECT_SELECT "menu/art/opponents_select"
+#define BOTSELECT_SELECTED "menu/art/opponents_selected"
+#define BOTSELECT_ARROWS "menu/art/gs_arrows_0"
+#define BOTSELECT_ARROWSL "menu/art/gs_arrows_l"
+#define BOTSELECT_ARROWSR "menu/art/gs_arrows_r"
+
+#define PLAYERGRID_COLS 4
+#define PLAYERGRID_ROWS 4
+#define MAX_MODELSPERPAGE (PLAYERGRID_ROWS * PLAYERGRID_COLS)
+
+
+typedef struct {
+ menuframework_s menu;
+
+ menutext_s banner;
+
+ menubitmap_s pics[MAX_MODELSPERPAGE];
+ menubitmap_s picbuttons[MAX_MODELSPERPAGE];
+ menutext_s picnames[MAX_MODELSPERPAGE];
+
+ menubitmap_s arrows;
+ menubitmap_s left;
+ menubitmap_s right;
+
+ menubitmap_s go;
+ menubitmap_s back;
+
+ int numBots;
+ int modelpage;
+ int numpages;
+ int selectedmodel;
+ int sortedBotNums[MAX_BOTS];
+ char boticons[MAX_MODELSPERPAGE][MAX_QPATH];
+ char botnames[MAX_MODELSPERPAGE][16];
+} botSelectInfo_t;
+
+static botSelectInfo_t botSelectInfo;
+
+
+/*
+=================
+UI_BotSelectMenu_SortCompare
+=================
+*/
+static int QDECL UI_BotSelectMenu_SortCompare( const void *arg1, const void *arg2 ) {
+ int num1, num2;
+ const char *info1, *info2;
+ const char *name1, *name2;
+
+ num1 = *(int *)arg1;
+ num2 = *(int *)arg2;
+
+ info1 = UI_GetBotInfoByNumber( num1 );
+ info2 = UI_GetBotInfoByNumber( num2 );
+
+ name1 = Info_ValueForKey( info1, "name" );
+ name2 = Info_ValueForKey( info2, "name" );
+
+ return Q_stricmp( name1, name2 );
+}
+
+
+/*
+=================
+UI_BotSelectMenu_BuildList
+=================
+*/
+static void UI_BotSelectMenu_BuildList( void ) {
+ int n;
+
+ botSelectInfo.modelpage = 0;
+ botSelectInfo.numBots = UI_GetNumBots();
+ botSelectInfo.numpages = botSelectInfo.numBots / MAX_MODELSPERPAGE;
+ if( botSelectInfo.numBots % MAX_MODELSPERPAGE ) {
+ botSelectInfo.numpages++;
+ }
+
+ // initialize the array
+ for( n = 0; n < botSelectInfo.numBots; n++ ) {
+ botSelectInfo.sortedBotNums[n] = n;
+ }
+
+ // now sort it
+ qsort( botSelectInfo.sortedBotNums, botSelectInfo.numBots, sizeof(botSelectInfo.sortedBotNums[0]), UI_BotSelectMenu_SortCompare );
+}
+
+
+/*
+=================
+ServerPlayerIcon
+=================
+*/
+static void ServerPlayerIcon( const char *modelAndSkin, char *iconName, int iconNameMaxSize ) {
+ char *skin;
+ char model[MAX_QPATH];
+
+ Q_strncpyz( model, modelAndSkin, sizeof(model));
+ skin = Q_strrchr( model, '/' );
+ if ( skin ) {
+ *skin++ = '\0';
+ }
+ else {
+ skin = "default";
+ }
+
+ Com_sprintf(iconName, iconNameMaxSize, "models/players/%s/icon_%s.tga", model, skin );
+
+ if( !trap_R_RegisterShaderNoMip( iconName ) && Q_stricmp( skin, "default" ) != 0 ) {
+ Com_sprintf(iconName, iconNameMaxSize, "models/players/%s/icon_default.tga", model );
+ }
+}
+
+
+/*
+=================
+UI_BotSelectMenu_UpdateGrid
+=================
+*/
+static void UI_BotSelectMenu_UpdateGrid( void ) {
+ const char *info;
+ int i;
+ int j;
+
+ j = botSelectInfo.modelpage * MAX_MODELSPERPAGE;
+ for( i = 0; i < (PLAYERGRID_ROWS * PLAYERGRID_COLS); i++, j++) {
+ if( j < botSelectInfo.numBots ) {
+ info = UI_GetBotInfoByNumber( botSelectInfo.sortedBotNums[j] );
+ ServerPlayerIcon( Info_ValueForKey( info, "model" ), botSelectInfo.boticons[i], MAX_QPATH );
+ Q_strncpyz( botSelectInfo.botnames[i], Info_ValueForKey( info, "name" ), 16 );
+ Q_CleanStr( botSelectInfo.botnames[i] );
+ botSelectInfo.pics[i].generic.name = botSelectInfo.boticons[i];
+ if( BotAlreadySelected( botSelectInfo.botnames[i] ) ) {
+ botSelectInfo.picnames[i].color = color_red;
+ }
+ else {
+ botSelectInfo.picnames[i].color = color_orange;
+ }
+ botSelectInfo.picbuttons[i].generic.flags &= ~QMF_INACTIVE;
+ }
+ else {
+ // dead slot
+ botSelectInfo.pics[i].generic.name = NULL;
+ botSelectInfo.picbuttons[i].generic.flags |= QMF_INACTIVE;
+ botSelectInfo.botnames[i][0] = 0;
+ }
+
+ botSelectInfo.pics[i].generic.flags &= ~QMF_HIGHLIGHT;
+ botSelectInfo.pics[i].shader = 0;
+ botSelectInfo.picbuttons[i].generic.flags |= QMF_PULSEIFFOCUS;
+ }
+
+ // set selected model
+ i = botSelectInfo.selectedmodel % MAX_MODELSPERPAGE;
+ botSelectInfo.pics[i].generic.flags |= QMF_HIGHLIGHT;
+ botSelectInfo.picbuttons[i].generic.flags &= ~QMF_PULSEIFFOCUS;
+
+ if( botSelectInfo.numpages > 1 ) {
+ if( botSelectInfo.modelpage > 0 ) {
+ botSelectInfo.left.generic.flags &= ~QMF_INACTIVE;
+ }
+ else {
+ botSelectInfo.left.generic.flags |= QMF_INACTIVE;
+ }
+
+ if( botSelectInfo.modelpage < (botSelectInfo.numpages - 1) ) {
+ botSelectInfo.right.generic.flags &= ~QMF_INACTIVE;
+ }
+ else {
+ botSelectInfo.right.generic.flags |= QMF_INACTIVE;
+ }
+ }
+ else {
+ // hide left/right markers
+ botSelectInfo.left.generic.flags |= QMF_INACTIVE;
+ botSelectInfo.right.generic.flags |= QMF_INACTIVE;
+ }
+}
+
+
+/*
+=================
+UI_BotSelectMenu_Default
+=================
+*/
+static void UI_BotSelectMenu_Default( char *bot ) {
+ const char *botInfo;
+ const char *test;
+ int n;
+ int i;
+
+ for( n = 0; n < botSelectInfo.numBots; n++ ) {
+ botInfo = UI_GetBotInfoByNumber( n );
+ test = Info_ValueForKey( botInfo, "name" );
+ if( Q_stricmp( bot, test ) == 0 ) {
+ break;
+ }
+ }
+ if( n == botSelectInfo.numBots ) {
+ botSelectInfo.selectedmodel = 0;
+ return;
+ }
+
+ for( i = 0; i < botSelectInfo.numBots; i++ ) {
+ if( botSelectInfo.sortedBotNums[i] == n ) {
+ break;
+ }
+ }
+ if( i == botSelectInfo.numBots ) {
+ botSelectInfo.selectedmodel = 0;
+ return;
+ }
+
+ botSelectInfo.selectedmodel = i;
+}
+
+
+/*
+=================
+UI_BotSelectMenu_LeftEvent
+=================
+*/
+static void UI_BotSelectMenu_LeftEvent( void* ptr, int event ) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+ if( botSelectInfo.modelpage > 0 ) {
+ botSelectInfo.modelpage--;
+ botSelectInfo.selectedmodel = botSelectInfo.modelpage * MAX_MODELSPERPAGE;
+ UI_BotSelectMenu_UpdateGrid();
+ }
+}
+
+
+/*
+=================
+UI_BotSelectMenu_RightEvent
+=================
+*/
+static void UI_BotSelectMenu_RightEvent( void* ptr, int event ) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+ if( botSelectInfo.modelpage < botSelectInfo.numpages - 1 ) {
+ botSelectInfo.modelpage++;
+ botSelectInfo.selectedmodel = botSelectInfo.modelpage * MAX_MODELSPERPAGE;
+ UI_BotSelectMenu_UpdateGrid();
+ }
+}
+
+
+/*
+=================
+UI_BotSelectMenu_BotEvent
+=================
+*/
+static void UI_BotSelectMenu_BotEvent( void* ptr, int event ) {
+ int i;
+
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+
+ for( i = 0; i < (PLAYERGRID_ROWS * PLAYERGRID_COLS); i++ ) {
+ botSelectInfo.pics[i].generic.flags &= ~QMF_HIGHLIGHT;
+ botSelectInfo.picbuttons[i].generic.flags |= QMF_PULSEIFFOCUS;
+ }
+
+ // set selected
+ i = ((menucommon_s*)ptr)->id;
+ botSelectInfo.pics[i].generic.flags |= QMF_HIGHLIGHT;
+ botSelectInfo.picbuttons[i].generic.flags &= ~QMF_PULSEIFFOCUS;
+ botSelectInfo.selectedmodel = botSelectInfo.modelpage * MAX_MODELSPERPAGE + i;
+}
+
+
+/*
+=================
+UI_BotSelectMenu_BackEvent
+=================
+*/
+static void UI_BotSelectMenu_BackEvent( void* ptr, int event ) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+ UI_PopMenu();
+}
+
+
+/*
+=================
+UI_BotSelectMenu_SelectEvent
+=================
+*/
+static void UI_BotSelectMenu_SelectEvent( void* ptr, int event ) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+ UI_PopMenu();
+
+ s_serveroptions.newBot = qtrue;
+ Q_strncpyz( s_serveroptions.newBotName, botSelectInfo.botnames[botSelectInfo.selectedmodel % MAX_MODELSPERPAGE], 16 );
+}
+
+
+/*
+=================
+UI_BotSelectMenu_Cache
+=================
+*/
+void UI_BotSelectMenu_Cache( void ) {
+ trap_R_RegisterShaderNoMip( BOTSELECT_BACK0 );
+ trap_R_RegisterShaderNoMip( BOTSELECT_BACK1 );
+ trap_R_RegisterShaderNoMip( BOTSELECT_ACCEPT0 );
+ trap_R_RegisterShaderNoMip( BOTSELECT_ACCEPT1 );
+ trap_R_RegisterShaderNoMip( BOTSELECT_SELECT );
+ trap_R_RegisterShaderNoMip( BOTSELECT_SELECTED );
+ trap_R_RegisterShaderNoMip( BOTSELECT_ARROWS );
+ trap_R_RegisterShaderNoMip( BOTSELECT_ARROWSL );
+ trap_R_RegisterShaderNoMip( BOTSELECT_ARROWSR );
+}
+
+
+static void UI_BotSelectMenu_Init( char *bot ) {
+ int i, j, k;
+ int x, y;
+
+ memset( &botSelectInfo, 0 ,sizeof(botSelectInfo) );
+ botSelectInfo.menu.wrapAround = qtrue;
+ botSelectInfo.menu.fullscreen = qtrue;
+
+ UI_BotSelectMenu_Cache();
+
+ botSelectInfo.banner.generic.type = MTYPE_BTEXT;
+ botSelectInfo.banner.generic.x = 320;
+ botSelectInfo.banner.generic.y = 16;
+ botSelectInfo.banner.string = "SELECT BOT";
+ botSelectInfo.banner.color = color_white;
+ botSelectInfo.banner.style = UI_CENTER;
+
+ y = 80;
+ for( i = 0, k = 0; i < PLAYERGRID_ROWS; i++) {
+ x = 180;
+ for( j = 0; j < PLAYERGRID_COLS; j++, k++ ) {
+ botSelectInfo.pics[k].generic.type = MTYPE_BITMAP;
+ botSelectInfo.pics[k].generic.flags = QMF_LEFT_JUSTIFY|QMF_INACTIVE;
+ botSelectInfo.pics[k].generic.x = x;
+ botSelectInfo.pics[k].generic.y = y;
+ botSelectInfo.pics[k].generic.name = botSelectInfo.boticons[k];
+ botSelectInfo.pics[k].width = 64;
+ botSelectInfo.pics[k].height = 64;
+ botSelectInfo.pics[k].focuspic = BOTSELECT_SELECTED;
+ botSelectInfo.pics[k].focuscolor = colorRed;
+
+ botSelectInfo.picbuttons[k].generic.type = MTYPE_BITMAP;
+ botSelectInfo.picbuttons[k].generic.flags = QMF_LEFT_JUSTIFY|QMF_NODEFAULTINIT|QMF_PULSEIFFOCUS;
+ botSelectInfo.picbuttons[k].generic.callback = UI_BotSelectMenu_BotEvent;
+ botSelectInfo.picbuttons[k].generic.id = k;
+ botSelectInfo.picbuttons[k].generic.x = x - 16;
+ botSelectInfo.picbuttons[k].generic.y = y - 16;
+ botSelectInfo.picbuttons[k].generic.left = x;
+ botSelectInfo.picbuttons[k].generic.top = y;
+ botSelectInfo.picbuttons[k].generic.right = x + 64;
+ botSelectInfo.picbuttons[k].generic.bottom = y + 64;
+ botSelectInfo.picbuttons[k].width = 128;
+ botSelectInfo.picbuttons[k].height = 128;
+ botSelectInfo.picbuttons[k].focuspic = BOTSELECT_SELECT;
+ botSelectInfo.picbuttons[k].focuscolor = colorRed;
+
+ botSelectInfo.picnames[k].generic.type = MTYPE_TEXT;
+ botSelectInfo.picnames[k].generic.flags = QMF_SMALLFONT;
+ botSelectInfo.picnames[k].generic.x = x + 32;
+ botSelectInfo.picnames[k].generic.y = y + 64;
+ botSelectInfo.picnames[k].string = botSelectInfo.botnames[k];
+ botSelectInfo.picnames[k].color = color_orange;
+ botSelectInfo.picnames[k].style = UI_CENTER|UI_SMALLFONT;
+
+ x += (64 + 6);
+ }
+ y += (64 + SMALLCHAR_HEIGHT + 6);
+ }
+
+ botSelectInfo.arrows.generic.type = MTYPE_BITMAP;
+ botSelectInfo.arrows.generic.name = BOTSELECT_ARROWS;
+ botSelectInfo.arrows.generic.flags = QMF_INACTIVE;
+ botSelectInfo.arrows.generic.x = 260;
+ botSelectInfo.arrows.generic.y = 440;
+ botSelectInfo.arrows.width = 128;
+ botSelectInfo.arrows.height = 32;
+
+ botSelectInfo.left.generic.type = MTYPE_BITMAP;
+ botSelectInfo.left.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ botSelectInfo.left.generic.callback = UI_BotSelectMenu_LeftEvent;
+ botSelectInfo.left.generic.x = 260;
+ botSelectInfo.left.generic.y = 440;
+ botSelectInfo.left.width = 64;
+ botSelectInfo.left.height = 32;
+ botSelectInfo.left.focuspic = BOTSELECT_ARROWSL;
+
+ botSelectInfo.right.generic.type = MTYPE_BITMAP;
+ botSelectInfo.right.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ botSelectInfo.right.generic.callback = UI_BotSelectMenu_RightEvent;
+ botSelectInfo.right.generic.x = 321;
+ botSelectInfo.right.generic.y = 440;
+ botSelectInfo.right.width = 64;
+ botSelectInfo.right.height = 32;
+ botSelectInfo.right.focuspic = BOTSELECT_ARROWSR;
+
+ botSelectInfo.back.generic.type = MTYPE_BITMAP;
+ botSelectInfo.back.generic.name = BOTSELECT_BACK0;
+ botSelectInfo.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ botSelectInfo.back.generic.callback = UI_BotSelectMenu_BackEvent;
+ botSelectInfo.back.generic.x = 0;
+ botSelectInfo.back.generic.y = 480-64;
+ botSelectInfo.back.width = 128;
+ botSelectInfo.back.height = 64;
+ botSelectInfo.back.focuspic = BOTSELECT_BACK1;
+
+ botSelectInfo.go.generic.type = MTYPE_BITMAP;
+ botSelectInfo.go.generic.name = BOTSELECT_ACCEPT0;
+ botSelectInfo.go.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ botSelectInfo.go.generic.callback = UI_BotSelectMenu_SelectEvent;
+ botSelectInfo.go.generic.x = 640;
+ botSelectInfo.go.generic.y = 480-64;
+ botSelectInfo.go.width = 128;
+ botSelectInfo.go.height = 64;
+ botSelectInfo.go.focuspic = BOTSELECT_ACCEPT1;
+
+ Menu_AddItem( &botSelectInfo.menu, &botSelectInfo.banner );
+ for( i = 0; i < MAX_MODELSPERPAGE; i++ ) {
+ Menu_AddItem( &botSelectInfo.menu, &botSelectInfo.pics[i] );
+ Menu_AddItem( &botSelectInfo.menu, &botSelectInfo.picbuttons[i] );
+ Menu_AddItem( &botSelectInfo.menu, &botSelectInfo.picnames[i] );
+ }
+ Menu_AddItem( &botSelectInfo.menu, &botSelectInfo.arrows );
+ Menu_AddItem( &botSelectInfo.menu, &botSelectInfo.left );
+ Menu_AddItem( &botSelectInfo.menu, &botSelectInfo.right );
+ Menu_AddItem( &botSelectInfo.menu, &botSelectInfo.back );
+ Menu_AddItem( &botSelectInfo.menu, &botSelectInfo.go );
+
+ UI_BotSelectMenu_BuildList();
+ UI_BotSelectMenu_Default( bot );
+ botSelectInfo.modelpage = botSelectInfo.selectedmodel / MAX_MODELSPERPAGE;
+ UI_BotSelectMenu_UpdateGrid();
+}
+
+
+/*
+=================
+UI_BotSelectMenu
+=================
+*/
+void UI_BotSelectMenu( char *bot ) {
+ UI_BotSelectMenu_Init( bot );
+ UI_PushMenu( &botSelectInfo.menu );
+}
diff --git a/code/q3_ui/ui_team.c b/code/q3_ui/ui_team.c
new file mode 100755
index 0000000..1ea1bd1
--- /dev/null
+++ b/code/q3_ui/ui_team.c
@@ -0,0 +1,210 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+//
+// ui_team.c
+//
+
+#include "ui_local.h"
+
+
+#define TEAMMAIN_FRAME "menu/art/cut_frame"
+
+#define ID_JOINRED 100
+#define ID_JOINBLUE 101
+#define ID_JOINGAME 102
+#define ID_SPECTATE 103
+
+
+typedef struct
+{
+ menuframework_s menu;
+ menubitmap_s frame;
+ menutext_s joinred;
+ menutext_s joinblue;
+ menutext_s joingame;
+ menutext_s spectate;
+} teammain_t;
+
+static teammain_t s_teammain;
+
+// bk001204 - unused
+//static menuframework_s s_teammain_menu;
+//static menuaction_s s_teammain_orders;
+//static menuaction_s s_teammain_voice;
+//static menuaction_s s_teammain_joinred;
+//static menuaction_s s_teammain_joinblue;
+//static menuaction_s s_teammain_joingame;
+//static menuaction_s s_teammain_spectate;
+
+
+/*
+===============
+TeamMain_MenuEvent
+===============
+*/
+static void TeamMain_MenuEvent( void* ptr, int event ) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+
+ switch( ((menucommon_s*)ptr)->id ) {
+ case ID_JOINRED:
+ trap_Cmd_ExecuteText( EXEC_APPEND, "cmd team red\n" );
+ UI_ForceMenuOff();
+ break;
+
+ case ID_JOINBLUE:
+ trap_Cmd_ExecuteText( EXEC_APPEND, "cmd team blue\n" );
+ UI_ForceMenuOff();
+ break;
+
+ case ID_JOINGAME:
+ trap_Cmd_ExecuteText( EXEC_APPEND, "cmd team free\n" );
+ UI_ForceMenuOff();
+ break;
+
+ case ID_SPECTATE:
+ trap_Cmd_ExecuteText( EXEC_APPEND, "cmd team spectator\n" );
+ UI_ForceMenuOff();
+ break;
+ }
+}
+
+
+/*
+===============
+TeamMain_MenuInit
+===============
+*/
+void TeamMain_MenuInit( void ) {
+ int y;
+ int gametype;
+ char info[MAX_INFO_STRING];
+
+ memset( &s_teammain, 0, sizeof(s_teammain) );
+
+ TeamMain_Cache();
+
+ s_teammain.menu.wrapAround = qtrue;
+ s_teammain.menu.fullscreen = qfalse;
+
+ s_teammain.frame.generic.type = MTYPE_BITMAP;
+ s_teammain.frame.generic.flags = QMF_INACTIVE;
+ s_teammain.frame.generic.name = TEAMMAIN_FRAME;
+ s_teammain.frame.generic.x = 142;
+ s_teammain.frame.generic.y = 118;
+ s_teammain.frame.width = 359;
+ s_teammain.frame.height = 256;
+
+ y = 194;
+
+ s_teammain.joinred.generic.type = MTYPE_PTEXT;
+ s_teammain.joinred.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_teammain.joinred.generic.id = ID_JOINRED;
+ s_teammain.joinred.generic.callback = TeamMain_MenuEvent;
+ s_teammain.joinred.generic.x = 320;
+ s_teammain.joinred.generic.y = y;
+ s_teammain.joinred.string = "JOIN RED";
+ s_teammain.joinred.style = UI_CENTER|UI_SMALLFONT;
+ s_teammain.joinred.color = colorRed;
+ y += 20;
+
+ s_teammain.joinblue.generic.type = MTYPE_PTEXT;
+ s_teammain.joinblue.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_teammain.joinblue.generic.id = ID_JOINBLUE;
+ s_teammain.joinblue.generic.callback = TeamMain_MenuEvent;
+ s_teammain.joinblue.generic.x = 320;
+ s_teammain.joinblue.generic.y = y;
+ s_teammain.joinblue.string = "JOIN BLUE";
+ s_teammain.joinblue.style = UI_CENTER|UI_SMALLFONT;
+ s_teammain.joinblue.color = colorRed;
+ y += 20;
+
+ s_teammain.joingame.generic.type = MTYPE_PTEXT;
+ s_teammain.joingame.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_teammain.joingame.generic.id = ID_JOINGAME;
+ s_teammain.joingame.generic.callback = TeamMain_MenuEvent;
+ s_teammain.joingame.generic.x = 320;
+ s_teammain.joingame.generic.y = y;
+ s_teammain.joingame.string = "JOIN GAME";
+ s_teammain.joingame.style = UI_CENTER|UI_SMALLFONT;
+ s_teammain.joingame.color = colorRed;
+ y += 20;
+
+ s_teammain.spectate.generic.type = MTYPE_PTEXT;
+ s_teammain.spectate.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_teammain.spectate.generic.id = ID_SPECTATE;
+ s_teammain.spectate.generic.callback = TeamMain_MenuEvent;
+ s_teammain.spectate.generic.x = 320;
+ s_teammain.spectate.generic.y = y;
+ s_teammain.spectate.string = "SPECTATE";
+ s_teammain.spectate.style = UI_CENTER|UI_SMALLFONT;
+ s_teammain.spectate.color = colorRed;
+ y += 20;
+
+ trap_GetConfigString(CS_SERVERINFO, info, MAX_INFO_STRING);
+ gametype = atoi( Info_ValueForKey( info,"g_gametype" ) );
+
+ // set initial states
+ switch( gametype ) {
+ case GT_SINGLE_PLAYER:
+ case GT_FFA:
+ case GT_TOURNAMENT:
+ s_teammain.joinred.generic.flags |= QMF_GRAYED;
+ s_teammain.joinblue.generic.flags |= QMF_GRAYED;
+ break;
+
+ default:
+ case GT_TEAM:
+ case GT_CTF:
+ s_teammain.joingame.generic.flags |= QMF_GRAYED;
+ break;
+ }
+
+ Menu_AddItem( &s_teammain.menu, (void*) &s_teammain.frame );
+ Menu_AddItem( &s_teammain.menu, (void*) &s_teammain.joinred );
+ Menu_AddItem( &s_teammain.menu, (void*) &s_teammain.joinblue );
+ Menu_AddItem( &s_teammain.menu, (void*) &s_teammain.joingame );
+ Menu_AddItem( &s_teammain.menu, (void*) &s_teammain.spectate );
+}
+
+
+/*
+===============
+TeamMain_Cache
+===============
+*/
+void TeamMain_Cache( void ) {
+ trap_R_RegisterShaderNoMip( TEAMMAIN_FRAME );
+}
+
+
+/*
+===============
+UI_TeamMainMenu
+===============
+*/
+void UI_TeamMainMenu( void ) {
+ TeamMain_MenuInit();
+ UI_PushMenu ( &s_teammain.menu );
+}
diff --git a/code/q3_ui/ui_teamorders.c b/code/q3_ui/ui_teamorders.c
new file mode 100755
index 0000000..3187402
--- /dev/null
+++ b/code/q3_ui/ui_teamorders.c
@@ -0,0 +1,449 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*
+=======================================================================
+
+TEAM ORDERS MENU
+
+=======================================================================
+*/
+
+
+#include "ui_local.h"
+
+
+#define ART_FRAME "menu/art/addbotframe"
+#define ART_BACK0 "menu/art/back_0"
+#define ART_BACK1 "menu/art/back_1"
+
+#define ID_LIST_BOTS 10
+#define ID_LIST_CTF_ORDERS 11
+#define ID_LIST_TEAM_ORDERS 12
+
+
+typedef struct {
+ menuframework_s menu;
+
+ menutext_s banner;
+ menubitmap_s frame;
+
+ menulist_s list;
+
+ menubitmap_s back;
+
+ int gametype;
+ int numBots;
+ int selectedBot;
+ char *bots[9];
+ char botNames[9][16];
+} teamOrdersMenuInfo_t;
+
+static teamOrdersMenuInfo_t teamOrdersMenuInfo;
+
+#define NUM_CTF_ORDERS 7
+static const char *ctfOrders[] = {
+ "I Am the Leader",
+ "Defend the Base",
+ "Follow Me",
+ "Get Enemy Flag",
+ "Camp Here",
+ "Report",
+ "I Relinquish Command",
+ NULL
+};
+static const char *ctfMessages[] = {
+ "i am the leader",
+ "%s defend the base",
+ "%s follow me",
+ "%s get enemy flag",
+ "%s camp here",
+ "%s report",
+ "i stop being the leader",
+ NULL
+};
+
+#define NUM_TEAM_ORDERS 6
+static const char *teamOrders[] = {
+ "I Am the Leader",
+ "Follow Me",
+ "Roam",
+ "Camp Here",
+ "Report",
+ "I Relinquish Command",
+ NULL
+};
+static const char *teamMessages[] = {
+ "i am the leader",
+ "%s follow me",
+ "%s roam",
+ "%s camp here",
+ "%s report",
+ "i stop being the leader",
+ NULL
+};
+
+
+/*
+===============
+UI_TeamOrdersMenu_BackEvent
+===============
+*/
+static void UI_TeamOrdersMenu_BackEvent( void *ptr, int event ) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+ UI_PopMenu();
+}
+
+
+/*
+===============
+UI_TeamOrdersMenu_SetList
+===============
+*/
+static void UI_TeamOrdersMenu_SetList( int id ) {
+ switch( id ) {
+ default:
+ case ID_LIST_BOTS:
+ teamOrdersMenuInfo.list.generic.id = id;
+ teamOrdersMenuInfo.list.numitems = teamOrdersMenuInfo.numBots;
+ teamOrdersMenuInfo.list.itemnames = (const char **)teamOrdersMenuInfo.bots;
+ break;
+
+ case ID_LIST_CTF_ORDERS:
+ teamOrdersMenuInfo.list.generic.id = id;
+ teamOrdersMenuInfo.list.numitems = NUM_CTF_ORDERS;
+ teamOrdersMenuInfo.list.itemnames = ctfOrders;
+ break;
+
+ case ID_LIST_TEAM_ORDERS:
+ teamOrdersMenuInfo.list.generic.id = id;
+ teamOrdersMenuInfo.list.numitems = NUM_TEAM_ORDERS;
+ teamOrdersMenuInfo.list.itemnames = teamOrders;
+ break;
+ }
+
+ teamOrdersMenuInfo.list.generic.bottom = teamOrdersMenuInfo.list.generic.top + teamOrdersMenuInfo.list.numitems * PROP_HEIGHT;
+}
+
+
+/*
+=================
+UI_TeamOrdersMenu_Key
+=================
+*/
+sfxHandle_t UI_TeamOrdersMenu_Key( int key ) {
+ menulist_s *l;
+ int x;
+ int y;
+ int index;
+
+ l = (menulist_s *)Menu_ItemAtCursor( &teamOrdersMenuInfo.menu );
+ if( l != &teamOrdersMenuInfo.list ) {
+ return Menu_DefaultKey( &teamOrdersMenuInfo.menu, key );
+ }
+
+ switch( key ) {
+ case K_MOUSE1:
+ x = l->generic.left;
+ y = l->generic.top;
+ if( UI_CursorInRect( x, y, l->generic.right - x, l->generic.bottom - y ) ) {
+ index = (uis.cursory - y) / PROP_HEIGHT;
+ l->oldvalue = l->curvalue;
+ l->curvalue = index;
+
+ if( l->generic.callback ) {
+ l->generic.callback( l, QM_ACTIVATED );
+ return menu_move_sound;
+ }
+ }
+ return menu_null_sound;
+
+ case K_KP_UPARROW:
+ case K_UPARROW:
+ l->oldvalue = l->curvalue;
+
+ if( l->curvalue == 0 ) {
+ l->curvalue = l->numitems - 1;
+ }
+ else {
+ l->curvalue--;
+ }
+ return menu_move_sound;
+
+ case K_KP_DOWNARROW:
+ case K_DOWNARROW:
+ l->oldvalue = l->curvalue;
+
+ if( l->curvalue == l->numitems - 1 ) {
+ l->curvalue = 0;;
+ }
+ else {
+ l->curvalue++;
+ }
+ return menu_move_sound;
+ }
+
+ return Menu_DefaultKey( &teamOrdersMenuInfo.menu, key );
+}
+
+
+/*
+=================
+UI_TeamOrdersMenu_ListDraw
+=================
+*/
+static void UI_TeamOrdersMenu_ListDraw( void *self ) {
+ menulist_s *l;
+ int x;
+ int y;
+ int i;
+ float *color;
+ qboolean hasfocus;
+ int style;
+
+ l = (menulist_s *)self;
+
+ hasfocus = (l->generic.parent->cursor == l->generic.menuPosition);
+
+ x = 320;//l->generic.x;
+ y = l->generic.y;
+ for( i = 0; i < l->numitems; i++ ) {
+ style = UI_LEFT|UI_SMALLFONT|UI_CENTER;
+ if( i == l->curvalue ) {
+ color = color_yellow;
+ if( hasfocus ) {
+ style |= UI_PULSE;
+ }
+ }
+ else {
+ color = color_orange;
+ }
+
+ UI_DrawProportionalString( x, y, l->itemnames[i], style, color );
+ y += PROP_HEIGHT;
+ }
+}
+
+
+/*
+===============
+UI_TeamOrdersMenu_ListEvent
+===============
+*/
+static void UI_TeamOrdersMenu_ListEvent( void *ptr, int event ) {
+ int id;
+ int selection;
+ char message[256];
+
+ if (event != QM_ACTIVATED)
+ return;
+
+ id = ((menulist_s *)ptr)->generic.id;
+ selection = ((menulist_s *)ptr)->curvalue;
+
+ if( id == ID_LIST_BOTS ) {
+ teamOrdersMenuInfo.selectedBot = selection;
+ if( teamOrdersMenuInfo.gametype == GT_CTF ) {
+ UI_TeamOrdersMenu_SetList( ID_LIST_CTF_ORDERS );
+ }
+ else {
+ UI_TeamOrdersMenu_SetList( ID_LIST_TEAM_ORDERS );
+ }
+ return;
+ }
+
+ if( id == ID_LIST_CTF_ORDERS ) {
+ Com_sprintf( message, sizeof(message), ctfMessages[selection], teamOrdersMenuInfo.botNames[teamOrdersMenuInfo.selectedBot] );
+ }
+ else {
+ Com_sprintf( message, sizeof(message), teamMessages[selection], teamOrdersMenuInfo.botNames[teamOrdersMenuInfo.selectedBot] );
+ }
+
+ trap_Cmd_ExecuteText( EXEC_APPEND, va( "say_team \"%s\"\n", message ) );
+ UI_PopMenu();
+}
+
+
+/*
+===============
+UI_TeamOrdersMenu_BuildBotList
+===============
+*/
+static void UI_TeamOrdersMenu_BuildBotList( void ) {
+ uiClientState_t cs;
+ int numPlayers;
+ int isBot;
+ int n;
+ char playerTeam;
+ char botTeam;
+ char info[MAX_INFO_STRING];
+
+ for( n = 0; n < 9; n++ ) {
+ teamOrdersMenuInfo.bots[n] = teamOrdersMenuInfo.botNames[n];
+ }
+
+ trap_GetClientState( &cs );
+
+ Q_strncpyz( teamOrdersMenuInfo.botNames[0], "Everyone", 16 );
+ teamOrdersMenuInfo.numBots = 1;
+
+ trap_GetConfigString( CS_SERVERINFO, info, sizeof(info) );
+ numPlayers = atoi( Info_ValueForKey( info, "sv_maxclients" ) );
+ teamOrdersMenuInfo.gametype = atoi( Info_ValueForKey( info, "g_gametype" ) );
+
+ for( n = 0; n < numPlayers && teamOrdersMenuInfo.numBots < 9; n++ ) {
+ trap_GetConfigString( CS_PLAYERS + n, info, MAX_INFO_STRING );
+
+ playerTeam = TEAM_SPECTATOR; // bk001204 = possible uninit use
+
+ if( n == cs.clientNum ) {
+ playerTeam = *Info_ValueForKey( info, "t" );
+ continue;
+ }
+
+ isBot = atoi( Info_ValueForKey( info, "skill" ) );
+ if( !isBot ) {
+ continue;
+ }
+
+ botTeam = *Info_ValueForKey( info, "t" );
+ if( botTeam != playerTeam ) {
+ continue;
+ }
+
+ Q_strncpyz( teamOrdersMenuInfo.botNames[teamOrdersMenuInfo.numBots], Info_ValueForKey( info, "n" ), 16 );
+ Q_CleanStr( teamOrdersMenuInfo.botNames[teamOrdersMenuInfo.numBots] );
+ teamOrdersMenuInfo.numBots++;
+ }
+}
+
+
+/*
+===============
+UI_TeamOrdersMenu_Init
+===============
+*/
+static void UI_TeamOrdersMenu_Init( void ) {
+ UI_TeamOrdersMenu_Cache();
+
+ memset( &teamOrdersMenuInfo, 0, sizeof(teamOrdersMenuInfo) );
+ teamOrdersMenuInfo.menu.fullscreen = qfalse;
+ teamOrdersMenuInfo.menu.key = UI_TeamOrdersMenu_Key;
+
+ UI_TeamOrdersMenu_BuildBotList();
+
+ teamOrdersMenuInfo.banner.generic.type = MTYPE_BTEXT;
+ teamOrdersMenuInfo.banner.generic.x = 320;
+ teamOrdersMenuInfo.banner.generic.y = 16;
+ teamOrdersMenuInfo.banner.string = "TEAM ORDERS";
+ teamOrdersMenuInfo.banner.color = color_white;
+ teamOrdersMenuInfo.banner.style = UI_CENTER;
+
+ teamOrdersMenuInfo.frame.generic.type = MTYPE_BITMAP;
+ teamOrdersMenuInfo.frame.generic.flags = QMF_INACTIVE;
+ teamOrdersMenuInfo.frame.generic.name = ART_FRAME;
+ teamOrdersMenuInfo.frame.generic.x = 320-233;
+ teamOrdersMenuInfo.frame.generic.y = 240-166;
+ teamOrdersMenuInfo.frame.width = 466;
+ teamOrdersMenuInfo.frame.height = 332;
+
+ teamOrdersMenuInfo.list.generic.type = MTYPE_SCROLLLIST;
+ teamOrdersMenuInfo.list.generic.flags = QMF_PULSEIFFOCUS;
+ teamOrdersMenuInfo.list.generic.ownerdraw = UI_TeamOrdersMenu_ListDraw;
+ teamOrdersMenuInfo.list.generic.callback = UI_TeamOrdersMenu_ListEvent;
+ teamOrdersMenuInfo.list.generic.x = 320-64;
+ teamOrdersMenuInfo.list.generic.y = 120;
+
+ teamOrdersMenuInfo.back.generic.type = MTYPE_BITMAP;
+ teamOrdersMenuInfo.back.generic.name = ART_BACK0;
+ teamOrdersMenuInfo.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ teamOrdersMenuInfo.back.generic.callback = UI_TeamOrdersMenu_BackEvent;
+ teamOrdersMenuInfo.back.generic.x = 0;
+ teamOrdersMenuInfo.back.generic.y = 480-64;
+ teamOrdersMenuInfo.back.width = 128;
+ teamOrdersMenuInfo.back.height = 64;
+ teamOrdersMenuInfo.back.focuspic = ART_BACK1;
+
+ Menu_AddItem( &teamOrdersMenuInfo.menu, &teamOrdersMenuInfo.banner );
+ Menu_AddItem( &teamOrdersMenuInfo.menu, &teamOrdersMenuInfo.frame );
+ Menu_AddItem( &teamOrdersMenuInfo.menu, &teamOrdersMenuInfo.list );
+ Menu_AddItem( &teamOrdersMenuInfo.menu, &teamOrdersMenuInfo.back );
+
+ teamOrdersMenuInfo.list.generic.left = 220;
+ teamOrdersMenuInfo.list.generic.top = teamOrdersMenuInfo.list.generic.y;
+ teamOrdersMenuInfo.list.generic.right = 420;
+ UI_TeamOrdersMenu_SetList( ID_LIST_BOTS );
+}
+
+
+/*
+=================
+UI_TeamOrdersMenu_Cache
+=================
+*/
+void UI_TeamOrdersMenu_Cache( void ) {
+ trap_R_RegisterShaderNoMip( ART_FRAME );
+ trap_R_RegisterShaderNoMip( ART_BACK0 );
+ trap_R_RegisterShaderNoMip( ART_BACK1 );
+}
+
+
+/*
+===============
+UI_TeamOrdersMenu
+===============
+*/
+void UI_TeamOrdersMenu( void ) {
+ UI_TeamOrdersMenu_Init();
+ UI_PushMenu( &teamOrdersMenuInfo.menu );
+}
+
+
+/*
+===============
+UI_TeamOrdersMenu_f
+===============
+*/
+void UI_TeamOrdersMenu_f( void ) {
+ uiClientState_t cs;
+ char info[MAX_INFO_STRING];
+ int team;
+
+ // make sure it's a team game
+ trap_GetConfigString( CS_SERVERINFO, info, sizeof(info) );
+ teamOrdersMenuInfo.gametype = atoi( Info_ValueForKey( info, "g_gametype" ) );
+ if( teamOrdersMenuInfo.gametype < GT_TEAM ) {
+ return;
+ }
+
+ // not available to spectators
+ trap_GetClientState( &cs );
+ trap_GetConfigString( CS_PLAYERS + cs.clientNum, info, MAX_INFO_STRING );
+ team = atoi( Info_ValueForKey( info, "t" ) );
+ if( team == TEAM_SPECTATOR ) {
+ return;
+ }
+
+ UI_TeamOrdersMenu();
+}
diff --git a/code/q3_ui/ui_video.c b/code/q3_ui/ui_video.c
new file mode 100755
index 0000000..8784245
--- /dev/null
+++ b/code/q3_ui/ui_video.c
@@ -0,0 +1,1070 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#include "ui_local.h"
+
+void GraphicsOptions_MenuInit( void );
+
+/*
+=======================================================================
+
+DRIVER INFORMATION MENU
+
+=======================================================================
+*/
+
+
+#define DRIVERINFO_FRAMEL "menu/art/frame2_l"
+#define DRIVERINFO_FRAMER "menu/art/frame1_r"
+#define DRIVERINFO_BACK0 "menu/art/back_0"
+#define DRIVERINFO_BACK1 "menu/art/back_1"
+
+static char* driverinfo_artlist[] =
+{
+ DRIVERINFO_FRAMEL,
+ DRIVERINFO_FRAMER,
+ DRIVERINFO_BACK0,
+ DRIVERINFO_BACK1,
+ NULL,
+};
+
+#define ID_DRIVERINFOBACK 100
+
+typedef struct
+{
+ menuframework_s menu;
+ menutext_s banner;
+ menubitmap_s back;
+ menubitmap_s framel;
+ menubitmap_s framer;
+ char stringbuff[1024];
+ char* strings[64];
+ int numstrings;
+} driverinfo_t;
+
+static driverinfo_t s_driverinfo;
+
+/*
+=================
+DriverInfo_Event
+=================
+*/
+static void DriverInfo_Event( void* ptr, int event )
+{
+ if (event != QM_ACTIVATED)
+ return;
+
+ switch (((menucommon_s*)ptr)->id)
+ {
+ case ID_DRIVERINFOBACK:
+ UI_PopMenu();
+ break;
+ }
+}
+
+/*
+=================
+DriverInfo_MenuDraw
+=================
+*/
+static void DriverInfo_MenuDraw( void )
+{
+ int i;
+ int y;
+
+ Menu_Draw( &s_driverinfo.menu );
+
+ UI_DrawString( 320, 80, "VENDOR", UI_CENTER|UI_SMALLFONT, color_red );
+ UI_DrawString( 320, 152, "PIXELFORMAT", UI_CENTER|UI_SMALLFONT, color_red );
+ UI_DrawString( 320, 192, "EXTENSIONS", UI_CENTER|UI_SMALLFONT, color_red );
+
+ UI_DrawString( 320, 80+16, uis.glconfig.vendor_string, UI_CENTER|UI_SMALLFONT, text_color_normal );
+ UI_DrawString( 320, 96+16, uis.glconfig.version_string, UI_CENTER|UI_SMALLFONT, text_color_normal );
+ UI_DrawString( 320, 112+16, uis.glconfig.renderer_string, UI_CENTER|UI_SMALLFONT, text_color_normal );
+ UI_DrawString( 320, 152+16, va ("color(%d-bits) Z(%d-bits) stencil(%d-bits)", uis.glconfig.colorBits, uis.glconfig.depthBits, uis.glconfig.stencilBits), UI_CENTER|UI_SMALLFONT, text_color_normal );
+
+ // double column
+ y = 192+16;
+ for (i=0; i<s_driverinfo.numstrings/2; i++) {
+ UI_DrawString( 320-4, y, s_driverinfo.strings[i*2], UI_RIGHT|UI_SMALLFONT, text_color_normal );
+ UI_DrawString( 320+4, y, s_driverinfo.strings[i*2+1], UI_LEFT|UI_SMALLFONT, text_color_normal );
+ y += SMALLCHAR_HEIGHT;
+ }
+
+ if (s_driverinfo.numstrings & 1)
+ UI_DrawString( 320, y, s_driverinfo.strings[s_driverinfo.numstrings-1], UI_CENTER|UI_SMALLFONT, text_color_normal );
+}
+
+/*
+=================
+DriverInfo_Cache
+=================
+*/
+void DriverInfo_Cache( void )
+{
+ int i;
+
+ // touch all our pics
+ for (i=0; ;i++)
+ {
+ if (!driverinfo_artlist[i])
+ break;
+ trap_R_RegisterShaderNoMip(driverinfo_artlist[i]);
+ }
+}
+
+/*
+=================
+UI_DriverInfo_Menu
+=================
+*/
+static void UI_DriverInfo_Menu( void )
+{
+ char* eptr;
+ int i;
+ int len;
+
+ // zero set all our globals
+ memset( &s_driverinfo, 0 ,sizeof(driverinfo_t) );
+
+ DriverInfo_Cache();
+
+ s_driverinfo.menu.fullscreen = qtrue;
+ s_driverinfo.menu.draw = DriverInfo_MenuDraw;
+
+ s_driverinfo.banner.generic.type = MTYPE_BTEXT;
+ s_driverinfo.banner.generic.x = 320;
+ s_driverinfo.banner.generic.y = 16;
+ s_driverinfo.banner.string = "DRIVER INFO";
+ s_driverinfo.banner.color = color_white;
+ s_driverinfo.banner.style = UI_CENTER;
+
+ s_driverinfo.framel.generic.type = MTYPE_BITMAP;
+ s_driverinfo.framel.generic.name = DRIVERINFO_FRAMEL;
+ s_driverinfo.framel.generic.flags = QMF_INACTIVE;
+ s_driverinfo.framel.generic.x = 0;
+ s_driverinfo.framel.generic.y = 78;
+ s_driverinfo.framel.width = 256;
+ s_driverinfo.framel.height = 329;
+
+ s_driverinfo.framer.generic.type = MTYPE_BITMAP;
+ s_driverinfo.framer.generic.name = DRIVERINFO_FRAMER;
+ s_driverinfo.framer.generic.flags = QMF_INACTIVE;
+ s_driverinfo.framer.generic.x = 376;
+ s_driverinfo.framer.generic.y = 76;
+ s_driverinfo.framer.width = 256;
+ s_driverinfo.framer.height = 334;
+
+ s_driverinfo.back.generic.type = MTYPE_BITMAP;
+ s_driverinfo.back.generic.name = DRIVERINFO_BACK0;
+ s_driverinfo.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_driverinfo.back.generic.callback = DriverInfo_Event;
+ s_driverinfo.back.generic.id = ID_DRIVERINFOBACK;
+ s_driverinfo.back.generic.x = 0;
+ s_driverinfo.back.generic.y = 480-64;
+ s_driverinfo.back.width = 128;
+ s_driverinfo.back.height = 64;
+ s_driverinfo.back.focuspic = DRIVERINFO_BACK1;
+
+ // TTimo: overflow with particularly long GL extensions (such as the gf3)
+ // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=399
+ // NOTE: could have pushed the size of stringbuff, but the list is already out of the screen
+ // (no matter what your resolution)
+ Q_strncpyz(s_driverinfo.stringbuff, uis.glconfig.extensions_string, 1024);
+
+ // build null terminated extension strings
+ eptr = s_driverinfo.stringbuff;
+ while ( s_driverinfo.numstrings<40 && *eptr )
+ {
+ while ( *eptr && *eptr == ' ' )
+ *eptr++ = '\0';
+
+ // track start of valid string
+ if (*eptr && *eptr != ' ')
+ s_driverinfo.strings[s_driverinfo.numstrings++] = eptr;
+
+ while ( *eptr && *eptr != ' ' )
+ eptr++;
+ }
+
+ // safety length strings for display
+ for (i=0; i<s_driverinfo.numstrings; i++) {
+ len = strlen(s_driverinfo.strings[i]);
+ if (len > 32) {
+ s_driverinfo.strings[i][len-1] = '>';
+ s_driverinfo.strings[i][len] = '\0';
+ }
+ }
+
+ Menu_AddItem( &s_driverinfo.menu, &s_driverinfo.banner );
+ Menu_AddItem( &s_driverinfo.menu, &s_driverinfo.framel );
+ Menu_AddItem( &s_driverinfo.menu, &s_driverinfo.framer );
+ Menu_AddItem( &s_driverinfo.menu, &s_driverinfo.back );
+
+ UI_PushMenu( &s_driverinfo.menu );
+}
+
+/*
+=======================================================================
+
+GRAPHICS OPTIONS MENU
+
+=======================================================================
+*/
+
+#define GRAPHICSOPTIONS_FRAMEL "menu/art/frame2_l"
+#define GRAPHICSOPTIONS_FRAMER "menu/art/frame1_r"
+#define GRAPHICSOPTIONS_BACK0 "menu/art/back_0"
+#define GRAPHICSOPTIONS_BACK1 "menu/art/back_1"
+#define GRAPHICSOPTIONS_ACCEPT0 "menu/art/accept_0"
+#define GRAPHICSOPTIONS_ACCEPT1 "menu/art/accept_1"
+
+static const char *s_drivers[] =
+{
+ OPENGL_DRIVER_NAME,
+ _3DFX_DRIVER_NAME,
+ 0
+};
+
+#define ID_BACK2 101
+#define ID_FULLSCREEN 102
+#define ID_LIST 103
+#define ID_MODE 104
+#define ID_DRIVERINFO 105
+#define ID_GRAPHICS 106
+#define ID_DISPLAY 107
+#define ID_SOUND 108
+#define ID_NETWORK 109
+
+typedef struct {
+ menuframework_s menu;
+
+ menutext_s banner;
+ menubitmap_s framel;
+ menubitmap_s framer;
+
+ menutext_s graphics;
+ menutext_s display;
+ menutext_s sound;
+ menutext_s network;
+
+ menulist_s list;
+ menulist_s mode;
+ menulist_s driver;
+ menuslider_s tq;
+ menulist_s fs;
+ menulist_s lighting;
+ menulist_s allow_extensions;
+ menulist_s texturebits;
+ menulist_s colordepth;
+ menulist_s geometry;
+ menulist_s filter;
+ menutext_s driverinfo;
+
+ menubitmap_s apply;
+ menubitmap_s back;
+} graphicsoptions_t;
+
+typedef struct
+{
+ int mode;
+ qboolean fullscreen;
+ int tq;
+ int lighting;
+ int colordepth;
+ int texturebits;
+ int geometry;
+ int filter;
+ int driver;
+ qboolean extensions;
+} InitialVideoOptions_s;
+
+static InitialVideoOptions_s s_ivo;
+static graphicsoptions_t s_graphicsoptions;
+
+static InitialVideoOptions_s s_ivo_templates[] =
+{
+ {
+ 4, qtrue, 2, 0, 2, 2, 1, 1, 0, qtrue // JDC: this was tq 3
+ },
+ {
+ 3, qtrue, 2, 0, 0, 0, 1, 0, 0, qtrue
+ },
+ {
+ 2, qtrue, 1, 0, 1, 0, 0, 0, 0, qtrue
+ },
+ {
+ 2, qtrue, 1, 1, 1, 0, 0, 0, 0, qtrue
+ },
+ {
+ 3, qtrue, 1, 0, 0, 0, 1, 0, 0, qtrue
+ }
+};
+
+#define NUM_IVO_TEMPLATES ( sizeof( s_ivo_templates ) / sizeof( s_ivo_templates[0] ) )
+
+/*
+=================
+GraphicsOptions_GetInitialVideo
+=================
+*/
+static void GraphicsOptions_GetInitialVideo( void )
+{
+ s_ivo.colordepth = s_graphicsoptions.colordepth.curvalue;
+ s_ivo.driver = s_graphicsoptions.driver.curvalue;
+ s_ivo.mode = s_graphicsoptions.mode.curvalue;
+ s_ivo.fullscreen = s_graphicsoptions.fs.curvalue;
+ s_ivo.extensions = s_graphicsoptions.allow_extensions.curvalue;
+ s_ivo.tq = s_graphicsoptions.tq.curvalue;
+ s_ivo.lighting = s_graphicsoptions.lighting.curvalue;
+ s_ivo.geometry = s_graphicsoptions.geometry.curvalue;
+ s_ivo.filter = s_graphicsoptions.filter.curvalue;
+ s_ivo.texturebits = s_graphicsoptions.texturebits.curvalue;
+}
+
+/*
+=================
+GraphicsOptions_CheckConfig
+=================
+*/
+static void GraphicsOptions_CheckConfig( void )
+{
+ int i;
+
+ for ( i = 0; i < NUM_IVO_TEMPLATES; i++ )
+ {
+ if ( s_ivo_templates[i].colordepth != s_graphicsoptions.colordepth.curvalue )
+ continue;
+ if ( s_ivo_templates[i].driver != s_graphicsoptions.driver.curvalue )
+ continue;
+ if ( s_ivo_templates[i].mode != s_graphicsoptions.mode.curvalue )
+ continue;
+ if ( s_ivo_templates[i].fullscreen != s_graphicsoptions.fs.curvalue )
+ continue;
+ if ( s_ivo_templates[i].tq != s_graphicsoptions.tq.curvalue )
+ continue;
+ if ( s_ivo_templates[i].lighting != s_graphicsoptions.lighting.curvalue )
+ continue;
+ if ( s_ivo_templates[i].geometry != s_graphicsoptions.geometry.curvalue )
+ continue;
+ if ( s_ivo_templates[i].filter != s_graphicsoptions.filter.curvalue )
+ continue;
+// if ( s_ivo_templates[i].texturebits != s_graphicsoptions.texturebits.curvalue )
+// continue;
+ s_graphicsoptions.list.curvalue = i;
+ return;
+ }
+ s_graphicsoptions.list.curvalue = 4;
+}
+
+/*
+=================
+GraphicsOptions_UpdateMenuItems
+=================
+*/
+static void GraphicsOptions_UpdateMenuItems( void )
+{
+ if ( s_graphicsoptions.driver.curvalue == 1 )
+ {
+ s_graphicsoptions.fs.curvalue = 1;
+ s_graphicsoptions.fs.generic.flags |= QMF_GRAYED;
+ s_graphicsoptions.colordepth.curvalue = 1;
+ }
+ else
+ {
+ s_graphicsoptions.fs.generic.flags &= ~QMF_GRAYED;
+ }
+
+ if ( s_graphicsoptions.fs.curvalue == 0 || s_graphicsoptions.driver.curvalue == 1 )
+ {
+ s_graphicsoptions.colordepth.curvalue = 0;
+ s_graphicsoptions.colordepth.generic.flags |= QMF_GRAYED;
+ }
+ else
+ {
+ s_graphicsoptions.colordepth.generic.flags &= ~QMF_GRAYED;
+ }
+
+ if ( s_graphicsoptions.allow_extensions.curvalue == 0 )
+ {
+ if ( s_graphicsoptions.texturebits.curvalue == 0 )
+ {
+ s_graphicsoptions.texturebits.curvalue = 1;
+ }
+ }
+
+ s_graphicsoptions.apply.generic.flags |= QMF_HIDDEN|QMF_INACTIVE;
+
+ if ( s_ivo.mode != s_graphicsoptions.mode.curvalue )
+ {
+ s_graphicsoptions.apply.generic.flags &= ~(QMF_HIDDEN|QMF_INACTIVE);
+ }
+ if ( s_ivo.fullscreen != s_graphicsoptions.fs.curvalue )
+ {
+ s_graphicsoptions.apply.generic.flags &= ~(QMF_HIDDEN|QMF_INACTIVE);
+ }
+ if ( s_ivo.extensions != s_graphicsoptions.allow_extensions.curvalue )
+ {
+ s_graphicsoptions.apply.generic.flags &= ~(QMF_HIDDEN|QMF_INACTIVE);
+ }
+ if ( s_ivo.tq != s_graphicsoptions.tq.curvalue )
+ {
+ s_graphicsoptions.apply.generic.flags &= ~(QMF_HIDDEN|QMF_INACTIVE);
+ }
+ if ( s_ivo.lighting != s_graphicsoptions.lighting.curvalue )
+ {
+ s_graphicsoptions.apply.generic.flags &= ~(QMF_HIDDEN|QMF_INACTIVE);
+ }
+ if ( s_ivo.colordepth != s_graphicsoptions.colordepth.curvalue )
+ {
+ s_graphicsoptions.apply.generic.flags &= ~(QMF_HIDDEN|QMF_INACTIVE);
+ }
+ if ( s_ivo.driver != s_graphicsoptions.driver.curvalue )
+ {
+ s_graphicsoptions.apply.generic.flags &= ~(QMF_HIDDEN|QMF_INACTIVE);
+ }
+ if ( s_ivo.texturebits != s_graphicsoptions.texturebits.curvalue )
+ {
+ s_graphicsoptions.apply.generic.flags &= ~(QMF_HIDDEN|QMF_INACTIVE);
+ }
+ if ( s_ivo.geometry != s_graphicsoptions.geometry.curvalue )
+ {
+ s_graphicsoptions.apply.generic.flags &= ~(QMF_HIDDEN|QMF_INACTIVE);
+ }
+ if ( s_ivo.filter != s_graphicsoptions.filter.curvalue )
+ {
+ s_graphicsoptions.apply.generic.flags &= ~(QMF_HIDDEN|QMF_INACTIVE);
+ }
+
+ GraphicsOptions_CheckConfig();
+}
+
+/*
+=================
+GraphicsOptions_ApplyChanges
+=================
+*/
+static void GraphicsOptions_ApplyChanges( void *unused, int notification )
+{
+ if (notification != QM_ACTIVATED)
+ return;
+
+ switch ( s_graphicsoptions.texturebits.curvalue )
+ {
+ case 0:
+ trap_Cvar_SetValue( "r_texturebits", 0 );
+ break;
+ case 1:
+ trap_Cvar_SetValue( "r_texturebits", 16 );
+ break;
+ case 2:
+ trap_Cvar_SetValue( "r_texturebits", 32 );
+ break;
+ }
+ trap_Cvar_SetValue( "r_picmip", 3 - s_graphicsoptions.tq.curvalue );
+ trap_Cvar_SetValue( "r_allowExtensions", s_graphicsoptions.allow_extensions.curvalue );
+ trap_Cvar_SetValue( "r_mode", s_graphicsoptions.mode.curvalue );
+ trap_Cvar_SetValue( "r_fullscreen", s_graphicsoptions.fs.curvalue );
+ trap_Cvar_Set( "r_glDriver", ( char * ) s_drivers[s_graphicsoptions.driver.curvalue] );
+ switch ( s_graphicsoptions.colordepth.curvalue )
+ {
+ case 0:
+ trap_Cvar_SetValue( "r_colorbits", 0 );
+ trap_Cvar_SetValue( "r_depthbits", 0 );
+ trap_Cvar_SetValue( "r_stencilbits", 0 );
+ break;
+ case 1:
+ trap_Cvar_SetValue( "r_colorbits", 16 );
+ trap_Cvar_SetValue( "r_depthbits", 16 );
+ trap_Cvar_SetValue( "r_stencilbits", 0 );
+ break;
+ case 2:
+ trap_Cvar_SetValue( "r_colorbits", 32 );
+ trap_Cvar_SetValue( "r_depthbits", 24 );
+ break;
+ }
+ trap_Cvar_SetValue( "r_vertexLight", s_graphicsoptions.lighting.curvalue );
+
+ if ( s_graphicsoptions.geometry.curvalue == 2 )
+ {
+ trap_Cvar_SetValue( "r_lodBias", 0 );
+ trap_Cvar_SetValue( "r_subdivisions", 4 );
+ }
+ else if ( s_graphicsoptions.geometry.curvalue == 1 )
+ {
+ trap_Cvar_SetValue( "r_lodBias", 1 );
+ trap_Cvar_SetValue( "r_subdivisions", 12 );
+ }
+ else
+ {
+ trap_Cvar_SetValue( "r_lodBias", 1 );
+ trap_Cvar_SetValue( "r_subdivisions", 20 );
+ }
+
+ if ( s_graphicsoptions.filter.curvalue )
+ {
+ trap_Cvar_Set( "r_textureMode", "GL_LINEAR_MIPMAP_LINEAR" );
+ }
+ else
+ {
+ trap_Cvar_Set( "r_textureMode", "GL_LINEAR_MIPMAP_NEAREST" );
+ }
+
+ trap_Cmd_ExecuteText( EXEC_APPEND, "vid_restart\n" );
+}
+
+/*
+=================
+GraphicsOptions_Event
+=================
+*/
+static void GraphicsOptions_Event( void* ptr, int event ) {
+ InitialVideoOptions_s *ivo;
+
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+
+ switch( ((menucommon_s*)ptr)->id ) {
+ case ID_MODE:
+ // clamp 3dfx video modes
+ if ( s_graphicsoptions.driver.curvalue == 1 )
+ {
+ if ( s_graphicsoptions.mode.curvalue < 2 )
+ s_graphicsoptions.mode.curvalue = 2;
+ else if ( s_graphicsoptions.mode.curvalue > 6 )
+ s_graphicsoptions.mode.curvalue = 6;
+ }
+ break;
+
+ case ID_LIST:
+ ivo = &s_ivo_templates[s_graphicsoptions.list.curvalue];
+
+ s_graphicsoptions.mode.curvalue = ivo->mode;
+ s_graphicsoptions.tq.curvalue = ivo->tq;
+ s_graphicsoptions.lighting.curvalue = ivo->lighting;
+ s_graphicsoptions.colordepth.curvalue = ivo->colordepth;
+ s_graphicsoptions.texturebits.curvalue = ivo->texturebits;
+ s_graphicsoptions.geometry.curvalue = ivo->geometry;
+ s_graphicsoptions.filter.curvalue = ivo->filter;
+ s_graphicsoptions.fs.curvalue = ivo->fullscreen;
+ break;
+
+ case ID_DRIVERINFO:
+ UI_DriverInfo_Menu();
+ break;
+
+ case ID_BACK2:
+ UI_PopMenu();
+ break;
+
+ case ID_GRAPHICS:
+ break;
+
+ case ID_DISPLAY:
+ UI_PopMenu();
+ UI_DisplayOptionsMenu();
+ break;
+
+ case ID_SOUND:
+ UI_PopMenu();
+ UI_SoundOptionsMenu();
+ break;
+
+ case ID_NETWORK:
+ UI_PopMenu();
+ UI_NetworkOptionsMenu();
+ break;
+ }
+}
+
+
+/*
+================
+GraphicsOptions_TQEvent
+================
+*/
+static void GraphicsOptions_TQEvent( void *ptr, int event ) {
+ if( event != QM_ACTIVATED ) {
+ return;
+ }
+ s_graphicsoptions.tq.curvalue = (int)(s_graphicsoptions.tq.curvalue + 0.5);
+}
+
+
+/*
+================
+GraphicsOptions_MenuDraw
+================
+*/
+void GraphicsOptions_MenuDraw (void)
+{
+//APSFIX - rework this
+ GraphicsOptions_UpdateMenuItems();
+
+ Menu_Draw( &s_graphicsoptions.menu );
+}
+
+/*
+=================
+GraphicsOptions_SetMenuItems
+=================
+*/
+static void GraphicsOptions_SetMenuItems( void )
+{
+ s_graphicsoptions.mode.curvalue = trap_Cvar_VariableValue( "r_mode" );
+ if ( s_graphicsoptions.mode.curvalue < 0 )
+ {
+ s_graphicsoptions.mode.curvalue = 3;
+ }
+ s_graphicsoptions.fs.curvalue = trap_Cvar_VariableValue("r_fullscreen");
+ s_graphicsoptions.allow_extensions.curvalue = trap_Cvar_VariableValue("r_allowExtensions");
+ s_graphicsoptions.tq.curvalue = 3-trap_Cvar_VariableValue( "r_picmip");
+ if ( s_graphicsoptions.tq.curvalue < 0 )
+ {
+ s_graphicsoptions.tq.curvalue = 0;
+ }
+ else if ( s_graphicsoptions.tq.curvalue > 3 )
+ {
+ s_graphicsoptions.tq.curvalue = 3;
+ }
+
+ s_graphicsoptions.lighting.curvalue = trap_Cvar_VariableValue( "r_vertexLight" ) != 0;
+ switch ( ( int ) trap_Cvar_VariableValue( "r_texturebits" ) )
+ {
+ default:
+ case 0:
+ s_graphicsoptions.texturebits.curvalue = 0;
+ break;
+ case 16:
+ s_graphicsoptions.texturebits.curvalue = 1;
+ break;
+ case 32:
+ s_graphicsoptions.texturebits.curvalue = 2;
+ break;
+ }
+
+ if ( !Q_stricmp( UI_Cvar_VariableString( "r_textureMode" ), "GL_LINEAR_MIPMAP_NEAREST" ) )
+ {
+ s_graphicsoptions.filter.curvalue = 0;
+ }
+ else
+ {
+ s_graphicsoptions.filter.curvalue = 1;
+ }
+
+ if ( trap_Cvar_VariableValue( "r_lodBias" ) > 0 )
+ {
+ if ( trap_Cvar_VariableValue( "r_subdivisions" ) >= 20 )
+ {
+ s_graphicsoptions.geometry.curvalue = 0;
+ }
+ else
+ {
+ s_graphicsoptions.geometry.curvalue = 1;
+ }
+ }
+ else
+ {
+ s_graphicsoptions.geometry.curvalue = 2;
+ }
+
+ switch ( ( int ) trap_Cvar_VariableValue( "r_colorbits" ) )
+ {
+ default:
+ case 0:
+ s_graphicsoptions.colordepth.curvalue = 0;
+ break;
+ case 16:
+ s_graphicsoptions.colordepth.curvalue = 1;
+ break;
+ case 32:
+ s_graphicsoptions.colordepth.curvalue = 2;
+ break;
+ }
+
+ if ( s_graphicsoptions.fs.curvalue == 0 )
+ {
+ s_graphicsoptions.colordepth.curvalue = 0;
+ }
+ if ( s_graphicsoptions.driver.curvalue == 1 )
+ {
+ s_graphicsoptions.colordepth.curvalue = 1;
+ }
+}
+
+/*
+================
+GraphicsOptions_MenuInit
+================
+*/
+void GraphicsOptions_MenuInit( void )
+{
+ static const char *s_driver_names[] =
+ {
+ "Default",
+ "Voodoo",
+ 0
+ };
+
+ static const char *tq_names[] =
+ {
+ "Default",
+ "16 bit",
+ "32 bit",
+ 0
+ };
+
+ static const char *s_graphics_options_names[] =
+ {
+ "High Quality",
+ "Normal",
+ "Fast",
+ "Fastest",
+ "Custom",
+ 0
+ };
+
+ static const char *lighting_names[] =
+ {
+ "Lightmap",
+ "Vertex",
+ 0
+ };
+
+ static const char *colordepth_names[] =
+ {
+ "Default",
+ "16 bit",
+ "32 bit",
+ 0
+ };
+
+ static const char *resolutions[] =
+ {
+ "320x240",
+ "400x300",
+ "512x384",
+ "640x480",
+ "800x600",
+ "960x720",
+ "1024x768",
+ "1152x864",
+ "1280x1024",
+ "1600x1200",
+ "2048x1536",
+ "856x480 wide screen",
+ 0
+ };
+ static const char *filter_names[] =
+ {
+ "Bilinear",
+ "Trilinear",
+ 0
+ };
+ static const char *quality_names[] =
+ {
+ "Low",
+ "Medium",
+ "High",
+ 0
+ };
+ static const char *enabled_names[] =
+ {
+ "Off",
+ "On",
+ 0
+ };
+
+ int y;
+
+ // zero set all our globals
+ memset( &s_graphicsoptions, 0 ,sizeof(graphicsoptions_t) );
+
+ GraphicsOptions_Cache();
+
+ s_graphicsoptions.menu.wrapAround = qtrue;
+ s_graphicsoptions.menu.fullscreen = qtrue;
+ s_graphicsoptions.menu.draw = GraphicsOptions_MenuDraw;
+
+ s_graphicsoptions.banner.generic.type = MTYPE_BTEXT;
+ s_graphicsoptions.banner.generic.x = 320;
+ s_graphicsoptions.banner.generic.y = 16;
+ s_graphicsoptions.banner.string = "SYSTEM SETUP";
+ s_graphicsoptions.banner.color = color_white;
+ s_graphicsoptions.banner.style = UI_CENTER;
+
+ s_graphicsoptions.framel.generic.type = MTYPE_BITMAP;
+ s_graphicsoptions.framel.generic.name = GRAPHICSOPTIONS_FRAMEL;
+ s_graphicsoptions.framel.generic.flags = QMF_INACTIVE;
+ s_graphicsoptions.framel.generic.x = 0;
+ s_graphicsoptions.framel.generic.y = 78;
+ s_graphicsoptions.framel.width = 256;
+ s_graphicsoptions.framel.height = 329;
+
+ s_graphicsoptions.framer.generic.type = MTYPE_BITMAP;
+ s_graphicsoptions.framer.generic.name = GRAPHICSOPTIONS_FRAMER;
+ s_graphicsoptions.framer.generic.flags = QMF_INACTIVE;
+ s_graphicsoptions.framer.generic.x = 376;
+ s_graphicsoptions.framer.generic.y = 76;
+ s_graphicsoptions.framer.width = 256;
+ s_graphicsoptions.framer.height = 334;
+
+ s_graphicsoptions.graphics.generic.type = MTYPE_PTEXT;
+ s_graphicsoptions.graphics.generic.flags = QMF_RIGHT_JUSTIFY;
+ s_graphicsoptions.graphics.generic.id = ID_GRAPHICS;
+ s_graphicsoptions.graphics.generic.callback = GraphicsOptions_Event;
+ s_graphicsoptions.graphics.generic.x = 216;
+ s_graphicsoptions.graphics.generic.y = 240 - 2 * PROP_HEIGHT;
+ s_graphicsoptions.graphics.string = "GRAPHICS";
+ s_graphicsoptions.graphics.style = UI_RIGHT;
+ s_graphicsoptions.graphics.color = color_red;
+
+ s_graphicsoptions.display.generic.type = MTYPE_PTEXT;
+ s_graphicsoptions.display.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_graphicsoptions.display.generic.id = ID_DISPLAY;
+ s_graphicsoptions.display.generic.callback = GraphicsOptions_Event;
+ s_graphicsoptions.display.generic.x = 216;
+ s_graphicsoptions.display.generic.y = 240 - PROP_HEIGHT;
+ s_graphicsoptions.display.string = "DISPLAY";
+ s_graphicsoptions.display.style = UI_RIGHT;
+ s_graphicsoptions.display.color = color_red;
+
+ s_graphicsoptions.sound.generic.type = MTYPE_PTEXT;
+ s_graphicsoptions.sound.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_graphicsoptions.sound.generic.id = ID_SOUND;
+ s_graphicsoptions.sound.generic.callback = GraphicsOptions_Event;
+ s_graphicsoptions.sound.generic.x = 216;
+ s_graphicsoptions.sound.generic.y = 240;
+ s_graphicsoptions.sound.string = "SOUND";
+ s_graphicsoptions.sound.style = UI_RIGHT;
+ s_graphicsoptions.sound.color = color_red;
+
+ s_graphicsoptions.network.generic.type = MTYPE_PTEXT;
+ s_graphicsoptions.network.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_graphicsoptions.network.generic.id = ID_NETWORK;
+ s_graphicsoptions.network.generic.callback = GraphicsOptions_Event;
+ s_graphicsoptions.network.generic.x = 216;
+ s_graphicsoptions.network.generic.y = 240 + PROP_HEIGHT;
+ s_graphicsoptions.network.string = "NETWORK";
+ s_graphicsoptions.network.style = UI_RIGHT;
+ s_graphicsoptions.network.color = color_red;
+
+ y = 240 - 6 * (BIGCHAR_HEIGHT + 2);
+ s_graphicsoptions.list.generic.type = MTYPE_SPINCONTROL;
+ s_graphicsoptions.list.generic.name = "Graphics Settings:";
+ s_graphicsoptions.list.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_graphicsoptions.list.generic.x = 400;
+ s_graphicsoptions.list.generic.y = y;
+ s_graphicsoptions.list.generic.callback = GraphicsOptions_Event;
+ s_graphicsoptions.list.generic.id = ID_LIST;
+ s_graphicsoptions.list.itemnames = s_graphics_options_names;
+ y += 2 * ( BIGCHAR_HEIGHT + 2 );
+
+ s_graphicsoptions.driver.generic.type = MTYPE_SPINCONTROL;
+ s_graphicsoptions.driver.generic.name = "GL Driver:";
+ s_graphicsoptions.driver.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_graphicsoptions.driver.generic.x = 400;
+ s_graphicsoptions.driver.generic.y = y;
+ s_graphicsoptions.driver.itemnames = s_driver_names;
+ s_graphicsoptions.driver.curvalue = (uis.glconfig.driverType == GLDRV_VOODOO);
+ y += BIGCHAR_HEIGHT+2;
+
+ // references/modifies "r_allowExtensions"
+ s_graphicsoptions.allow_extensions.generic.type = MTYPE_SPINCONTROL;
+ s_graphicsoptions.allow_extensions.generic.name = "GL Extensions:";
+ s_graphicsoptions.allow_extensions.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_graphicsoptions.allow_extensions.generic.x = 400;
+ s_graphicsoptions.allow_extensions.generic.y = y;
+ s_graphicsoptions.allow_extensions.itemnames = enabled_names;
+ y += BIGCHAR_HEIGHT+2;
+
+ // references/modifies "r_mode"
+ s_graphicsoptions.mode.generic.type = MTYPE_SPINCONTROL;
+ s_graphicsoptions.mode.generic.name = "Video Mode:";
+ s_graphicsoptions.mode.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_graphicsoptions.mode.generic.x = 400;
+ s_graphicsoptions.mode.generic.y = y;
+ s_graphicsoptions.mode.itemnames = resolutions;
+ s_graphicsoptions.mode.generic.callback = GraphicsOptions_Event;
+ s_graphicsoptions.mode.generic.id = ID_MODE;
+ y += BIGCHAR_HEIGHT+2;
+
+ // references "r_colorbits"
+ s_graphicsoptions.colordepth.generic.type = MTYPE_SPINCONTROL;
+ s_graphicsoptions.colordepth.generic.name = "Color Depth:";
+ s_graphicsoptions.colordepth.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_graphicsoptions.colordepth.generic.x = 400;
+ s_graphicsoptions.colordepth.generic.y = y;
+ s_graphicsoptions.colordepth.itemnames = colordepth_names;
+ y += BIGCHAR_HEIGHT+2;
+
+ // references/modifies "r_fullscreen"
+ s_graphicsoptions.fs.generic.type = MTYPE_SPINCONTROL;
+ s_graphicsoptions.fs.generic.name = "Fullscreen:";
+ s_graphicsoptions.fs.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_graphicsoptions.fs.generic.x = 400;
+ s_graphicsoptions.fs.generic.y = y;
+ s_graphicsoptions.fs.itemnames = enabled_names;
+ y += BIGCHAR_HEIGHT+2;
+
+ // references/modifies "r_vertexLight"
+ s_graphicsoptions.lighting.generic.type = MTYPE_SPINCONTROL;
+ s_graphicsoptions.lighting.generic.name = "Lighting:";
+ s_graphicsoptions.lighting.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_graphicsoptions.lighting.generic.x = 400;
+ s_graphicsoptions.lighting.generic.y = y;
+ s_graphicsoptions.lighting.itemnames = lighting_names;
+ y += BIGCHAR_HEIGHT+2;
+
+ // references/modifies "r_lodBias" & "subdivisions"
+ s_graphicsoptions.geometry.generic.type = MTYPE_SPINCONTROL;
+ s_graphicsoptions.geometry.generic.name = "Geometric Detail:";
+ s_graphicsoptions.geometry.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_graphicsoptions.geometry.generic.x = 400;
+ s_graphicsoptions.geometry.generic.y = y;
+ s_graphicsoptions.geometry.itemnames = quality_names;
+ y += BIGCHAR_HEIGHT+2;
+
+ // references/modifies "r_picmip"
+ s_graphicsoptions.tq.generic.type = MTYPE_SLIDER;
+ s_graphicsoptions.tq.generic.name = "Texture Detail:";
+ s_graphicsoptions.tq.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_graphicsoptions.tq.generic.x = 400;
+ s_graphicsoptions.tq.generic.y = y;
+ s_graphicsoptions.tq.minvalue = 0;
+ s_graphicsoptions.tq.maxvalue = 3;
+ s_graphicsoptions.tq.generic.callback = GraphicsOptions_TQEvent;
+ y += BIGCHAR_HEIGHT+2;
+
+ // references/modifies "r_textureBits"
+ s_graphicsoptions.texturebits.generic.type = MTYPE_SPINCONTROL;
+ s_graphicsoptions.texturebits.generic.name = "Texture Quality:";
+ s_graphicsoptions.texturebits.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_graphicsoptions.texturebits.generic.x = 400;
+ s_graphicsoptions.texturebits.generic.y = y;
+ s_graphicsoptions.texturebits.itemnames = tq_names;
+ y += BIGCHAR_HEIGHT+2;
+
+ // references/modifies "r_textureMode"
+ s_graphicsoptions.filter.generic.type = MTYPE_SPINCONTROL;
+ s_graphicsoptions.filter.generic.name = "Texture Filter:";
+ s_graphicsoptions.filter.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
+ s_graphicsoptions.filter.generic.x = 400;
+ s_graphicsoptions.filter.generic.y = y;
+ s_graphicsoptions.filter.itemnames = filter_names;
+ y += 2*BIGCHAR_HEIGHT;
+
+ s_graphicsoptions.driverinfo.generic.type = MTYPE_PTEXT;
+ s_graphicsoptions.driverinfo.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_graphicsoptions.driverinfo.generic.callback = GraphicsOptions_Event;
+ s_graphicsoptions.driverinfo.generic.id = ID_DRIVERINFO;
+ s_graphicsoptions.driverinfo.generic.x = 320;
+ s_graphicsoptions.driverinfo.generic.y = y;
+ s_graphicsoptions.driverinfo.string = "Driver Info";
+ s_graphicsoptions.driverinfo.style = UI_CENTER|UI_SMALLFONT;
+ s_graphicsoptions.driverinfo.color = color_red;
+ y += BIGCHAR_HEIGHT+2;
+
+ s_graphicsoptions.back.generic.type = MTYPE_BITMAP;
+ s_graphicsoptions.back.generic.name = GRAPHICSOPTIONS_BACK0;
+ s_graphicsoptions.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
+ s_graphicsoptions.back.generic.callback = GraphicsOptions_Event;
+ s_graphicsoptions.back.generic.id = ID_BACK2;
+ s_graphicsoptions.back.generic.x = 0;
+ s_graphicsoptions.back.generic.y = 480-64;
+ s_graphicsoptions.back.width = 128;
+ s_graphicsoptions.back.height = 64;
+ s_graphicsoptions.back.focuspic = GRAPHICSOPTIONS_BACK1;
+
+ s_graphicsoptions.apply.generic.type = MTYPE_BITMAP;
+ s_graphicsoptions.apply.generic.name = GRAPHICSOPTIONS_ACCEPT0;
+ s_graphicsoptions.apply.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_HIDDEN|QMF_INACTIVE;
+ s_graphicsoptions.apply.generic.callback = GraphicsOptions_ApplyChanges;
+ s_graphicsoptions.apply.generic.x = 640;
+ s_graphicsoptions.apply.generic.y = 480-64;
+ s_graphicsoptions.apply.width = 128;
+ s_graphicsoptions.apply.height = 64;
+ s_graphicsoptions.apply.focuspic = GRAPHICSOPTIONS_ACCEPT1;
+
+ Menu_AddItem( &s_graphicsoptions.menu, ( void * ) &s_graphicsoptions.banner );
+ Menu_AddItem( &s_graphicsoptions.menu, ( void * ) &s_graphicsoptions.framel );
+ Menu_AddItem( &s_graphicsoptions.menu, ( void * ) &s_graphicsoptions.framer );
+
+ Menu_AddItem( &s_graphicsoptions.menu, ( void * ) &s_graphicsoptions.graphics );
+ Menu_AddItem( &s_graphicsoptions.menu, ( void * ) &s_graphicsoptions.display );
+ Menu_AddItem( &s_graphicsoptions.menu, ( void * ) &s_graphicsoptions.sound );
+ Menu_AddItem( &s_graphicsoptions.menu, ( void * ) &s_graphicsoptions.network );
+
+ Menu_AddItem( &s_graphicsoptions.menu, ( void * ) &s_graphicsoptions.list );
+ Menu_AddItem( &s_graphicsoptions.menu, ( void * ) &s_graphicsoptions.driver );
+ Menu_AddItem( &s_graphicsoptions.menu, ( void * ) &s_graphicsoptions.allow_extensions );
+ Menu_AddItem( &s_graphicsoptions.menu, ( void * ) &s_graphicsoptions.mode );
+ Menu_AddItem( &s_graphicsoptions.menu, ( void * ) &s_graphicsoptions.colordepth );
+ Menu_AddItem( &s_graphicsoptions.menu, ( void * ) &s_graphicsoptions.fs );
+ Menu_AddItem( &s_graphicsoptions.menu, ( void * ) &s_graphicsoptions.lighting );
+ Menu_AddItem( &s_graphicsoptions.menu, ( void * ) &s_graphicsoptions.geometry );
+ Menu_AddItem( &s_graphicsoptions.menu, ( void * ) &s_graphicsoptions.tq );
+ Menu_AddItem( &s_graphicsoptions.menu, ( void * ) &s_graphicsoptions.texturebits );
+ Menu_AddItem( &s_graphicsoptions.menu, ( void * ) &s_graphicsoptions.filter );
+ Menu_AddItem( &s_graphicsoptions.menu, ( void * ) &s_graphicsoptions.driverinfo );
+
+ Menu_AddItem( &s_graphicsoptions.menu, ( void * ) &s_graphicsoptions.back );
+ Menu_AddItem( &s_graphicsoptions.menu, ( void * ) &s_graphicsoptions.apply );
+
+ GraphicsOptions_SetMenuItems();
+ GraphicsOptions_GetInitialVideo();
+
+ if ( uis.glconfig.driverType == GLDRV_ICD &&
+ uis.glconfig.hardwareType == GLHW_3DFX_2D3D )
+ {
+ s_graphicsoptions.driver.generic.flags |= QMF_HIDDEN|QMF_INACTIVE;
+ }
+}
+
+
+/*
+=================
+GraphicsOptions_Cache
+=================
+*/
+void GraphicsOptions_Cache( void ) {
+ trap_R_RegisterShaderNoMip( GRAPHICSOPTIONS_FRAMEL );
+ trap_R_RegisterShaderNoMip( GRAPHICSOPTIONS_FRAMER );
+ trap_R_RegisterShaderNoMip( GRAPHICSOPTIONS_BACK0 );
+ trap_R_RegisterShaderNoMip( GRAPHICSOPTIONS_BACK1 );
+ trap_R_RegisterShaderNoMip( GRAPHICSOPTIONS_ACCEPT0 );
+ trap_R_RegisterShaderNoMip( GRAPHICSOPTIONS_ACCEPT1 );
+}
+
+
+/*
+=================
+UI_GraphicsOptionsMenu
+=================
+*/
+void UI_GraphicsOptionsMenu( void ) {
+ GraphicsOptions_MenuInit();
+ UI_PushMenu( &s_graphicsoptions.menu );
+ Menu_SetCursorToItem( &s_graphicsoptions.menu, &s_graphicsoptions.graphics );
+}
+
diff --git a/code/qcommon/cm_load.c b/code/qcommon/cm_load.c
new file mode 100755
index 0000000..58b4703
--- /dev/null
+++ b/code/qcommon/cm_load.c
@@ -0,0 +1,839 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// cmodel.c -- model loading
+
+#include "cm_local.h"
+
+#ifdef BSPC
+
+#include "../bspc/l_qfiles.h"
+
+void SetPlaneSignbits (cplane_t *out) {
+ int bits, j;
+
+ // for fast box on planeside test
+ bits = 0;
+ for (j=0 ; j<3 ; j++) {
+ if (out->normal[j] < 0) {
+ bits |= 1<<j;
+ }
+ }
+ out->signbits = bits;
+}
+#endif //BSPC
+
+// to allow boxes to be treated as brush models, we allocate
+// some extra indexes along with those needed by the map
+#define BOX_BRUSHES 1
+#define BOX_SIDES 6
+#define BOX_LEAFS 2
+#define BOX_PLANES 12
+
+#define LL(x) x=LittleLong(x)
+
+
+clipMap_t cm;
+int c_pointcontents;
+int c_traces, c_brush_traces, c_patch_traces;
+
+
+byte *cmod_base;
+
+#ifndef BSPC
+cvar_t *cm_noAreas;
+cvar_t *cm_noCurves;
+cvar_t *cm_playerCurveClip;
+#endif
+
+cmodel_t box_model;
+cplane_t *box_planes;
+cbrush_t *box_brush;
+
+
+
+void CM_InitBoxHull (void);
+void CM_FloodAreaConnections (void);
+
+
+/*
+===============================================================================
+
+ MAP LOADING
+
+===============================================================================
+*/
+
+/*
+=================
+CMod_LoadShaders
+=================
+*/
+void CMod_LoadShaders( lump_t *l ) {
+ dshader_t *in, *out;
+ int i, count;
+
+ in = (void *)(cmod_base + l->fileofs);
+ if (l->filelen % sizeof(*in)) {
+ Com_Error (ERR_DROP, "CMod_LoadShaders: funny lump size");
+ }
+ count = l->filelen / sizeof(*in);
+
+ if (count < 1) {
+ Com_Error (ERR_DROP, "Map with no shaders");
+ }
+ cm.shaders = Hunk_Alloc( count * sizeof( *cm.shaders ), h_high );
+ cm.numShaders = count;
+
+ Com_Memcpy( cm.shaders, in, count * sizeof( *cm.shaders ) );
+
+ out = cm.shaders;
+ for ( i=0 ; i<count ; i++, in++, out++ ) {
+ out->contentFlags = LittleLong( out->contentFlags );
+ out->surfaceFlags = LittleLong( out->surfaceFlags );
+ }
+}
+
+
+/*
+=================
+CMod_LoadSubmodels
+=================
+*/
+void CMod_LoadSubmodels( lump_t *l ) {
+ dmodel_t *in;
+ cmodel_t *out;
+ int i, j, count;
+ int *indexes;
+
+ in = (void *)(cmod_base + l->fileofs);
+ if (l->filelen % sizeof(*in))
+ Com_Error (ERR_DROP, "CMod_LoadSubmodels: funny lump size");
+ count = l->filelen / sizeof(*in);
+
+ if (count < 1)
+ Com_Error (ERR_DROP, "Map with no models");
+ cm.cmodels = Hunk_Alloc( count * sizeof( *cm.cmodels ), h_high );
+ cm.numSubModels = count;
+
+ if ( count > MAX_SUBMODELS ) {
+ Com_Error( ERR_DROP, "MAX_SUBMODELS exceeded" );
+ }
+
+ for ( i=0 ; i<count ; i++, in++, out++)
+ {
+ out = &cm.cmodels[i];
+
+ for (j=0 ; j<3 ; j++)
+ { // spread the mins / maxs by a pixel
+ out->mins[j] = LittleFloat (in->mins[j]) - 1;
+ out->maxs[j] = LittleFloat (in->maxs[j]) + 1;
+ }
+
+ if ( i == 0 ) {
+ continue; // world model doesn't need other info
+ }
+
+ // make a "leaf" just to hold the model's brushes and surfaces
+ out->leaf.numLeafBrushes = LittleLong( in->numBrushes );
+ indexes = Hunk_Alloc( out->leaf.numLeafBrushes * 4, h_high );
+ out->leaf.firstLeafBrush = indexes - cm.leafbrushes;
+ for ( j = 0 ; j < out->leaf.numLeafBrushes ; j++ ) {
+ indexes[j] = LittleLong( in->firstBrush ) + j;
+ }
+
+ out->leaf.numLeafSurfaces = LittleLong( in->numSurfaces );
+ indexes = Hunk_Alloc( out->leaf.numLeafSurfaces * 4, h_high );
+ out->leaf.firstLeafSurface = indexes - cm.leafsurfaces;
+ for ( j = 0 ; j < out->leaf.numLeafSurfaces ; j++ ) {
+ indexes[j] = LittleLong( in->firstSurface ) + j;
+ }
+ }
+}
+
+
+/*
+=================
+CMod_LoadNodes
+
+=================
+*/
+void CMod_LoadNodes( lump_t *l ) {
+ dnode_t *in;
+ int child;
+ cNode_t *out;
+ int i, j, count;
+
+ in = (void *)(cmod_base + l->fileofs);
+ if (l->filelen % sizeof(*in))
+ Com_Error (ERR_DROP, "MOD_LoadBmodel: funny lump size");
+ count = l->filelen / sizeof(*in);
+
+ if (count < 1)
+ Com_Error (ERR_DROP, "Map has no nodes");
+ cm.nodes = Hunk_Alloc( count * sizeof( *cm.nodes ), h_high );
+ cm.numNodes = count;
+
+ out = cm.nodes;
+
+ for (i=0 ; i<count ; i++, out++, in++)
+ {
+ out->plane = cm.planes + LittleLong( in->planeNum );
+ for (j=0 ; j<2 ; j++)
+ {
+ child = LittleLong (in->children[j]);
+ out->children[j] = child;
+ }
+ }
+
+}
+
+/*
+=================
+CM_BoundBrush
+
+=================
+*/
+void CM_BoundBrush( cbrush_t *b ) {
+ b->bounds[0][0] = -b->sides[0].plane->dist;
+ b->bounds[1][0] = b->sides[1].plane->dist;
+
+ b->bounds[0][1] = -b->sides[2].plane->dist;
+ b->bounds[1][1] = b->sides[3].plane->dist;
+
+ b->bounds[0][2] = -b->sides[4].plane->dist;
+ b->bounds[1][2] = b->sides[5].plane->dist;
+}
+
+
+/*
+=================
+CMod_LoadBrushes
+
+=================
+*/
+void CMod_LoadBrushes( lump_t *l ) {
+ dbrush_t *in;
+ cbrush_t *out;
+ int i, count;
+
+ in = (void *)(cmod_base + l->fileofs);
+ if (l->filelen % sizeof(*in)) {
+ Com_Error (ERR_DROP, "MOD_LoadBmodel: funny lump size");
+ }
+ count = l->filelen / sizeof(*in);
+
+ cm.brushes = Hunk_Alloc( ( BOX_BRUSHES + count ) * sizeof( *cm.brushes ), h_high );
+ cm.numBrushes = count;
+
+ out = cm.brushes;
+
+ for ( i=0 ; i<count ; i++, out++, in++ ) {
+ out->sides = cm.brushsides + LittleLong(in->firstSide);
+ out->numsides = LittleLong(in->numSides);
+
+ out->shaderNum = LittleLong( in->shaderNum );
+ if ( out->shaderNum < 0 || out->shaderNum >= cm.numShaders ) {
+ Com_Error( ERR_DROP, "CMod_LoadBrushes: bad shaderNum: %i", out->shaderNum );
+ }
+ out->contents = cm.shaders[out->shaderNum].contentFlags;
+
+ CM_BoundBrush( out );
+ }
+
+}
+
+/*
+=================
+CMod_LoadLeafs
+=================
+*/
+void CMod_LoadLeafs (lump_t *l)
+{
+ int i;
+ cLeaf_t *out;
+ dleaf_t *in;
+ int count;
+
+ in = (void *)(cmod_base + l->fileofs);
+ if (l->filelen % sizeof(*in))
+ Com_Error (ERR_DROP, "MOD_LoadBmodel: funny lump size");
+ count = l->filelen / sizeof(*in);
+
+ if (count < 1)
+ Com_Error (ERR_DROP, "Map with no leafs");
+
+ cm.leafs = Hunk_Alloc( ( BOX_LEAFS + count ) * sizeof( *cm.leafs ), h_high );
+ cm.numLeafs = count;
+
+ out = cm.leafs;
+ for ( i=0 ; i<count ; i++, in++, out++)
+ {
+ out->cluster = LittleLong (in->cluster);
+ out->area = LittleLong (in->area);
+ out->firstLeafBrush = LittleLong (in->firstLeafBrush);
+ out->numLeafBrushes = LittleLong (in->numLeafBrushes);
+ out->firstLeafSurface = LittleLong (in->firstLeafSurface);
+ out->numLeafSurfaces = LittleLong (in->numLeafSurfaces);
+
+ if (out->cluster >= cm.numClusters)
+ cm.numClusters = out->cluster + 1;
+ if (out->area >= cm.numAreas)
+ cm.numAreas = out->area + 1;
+ }
+
+ cm.areas = Hunk_Alloc( cm.numAreas * sizeof( *cm.areas ), h_high );
+ cm.areaPortals = Hunk_Alloc( cm.numAreas * cm.numAreas * sizeof( *cm.areaPortals ), h_high );
+}
+
+/*
+=================
+CMod_LoadPlanes
+=================
+*/
+void CMod_LoadPlanes (lump_t *l)
+{
+ int i, j;
+ cplane_t *out;
+ dplane_t *in;
+ int count;
+ int bits;
+
+ in = (void *)(cmod_base + l->fileofs);
+ if (l->filelen % sizeof(*in))
+ Com_Error (ERR_DROP, "MOD_LoadBmodel: funny lump size");
+ count = l->filelen / sizeof(*in);
+
+ if (count < 1)
+ Com_Error (ERR_DROP, "Map with no planes");
+ cm.planes = Hunk_Alloc( ( BOX_PLANES + count ) * sizeof( *cm.planes ), h_high );
+ cm.numPlanes = count;
+
+ out = cm.planes;
+
+ for ( i=0 ; i<count ; i++, in++, out++)
+ {
+ bits = 0;
+ for (j=0 ; j<3 ; j++)
+ {
+ out->normal[j] = LittleFloat (in->normal[j]);
+ if (out->normal[j] < 0)
+ bits |= 1<<j;
+ }
+
+ out->dist = LittleFloat (in->dist);
+ out->type = PlaneTypeForNormal( out->normal );
+ out->signbits = bits;
+ }
+}
+
+/*
+=================
+CMod_LoadLeafBrushes
+=================
+*/
+void CMod_LoadLeafBrushes (lump_t *l)
+{
+ int i;
+ int *out;
+ int *in;
+ int count;
+
+ in = (void *)(cmod_base + l->fileofs);
+ if (l->filelen % sizeof(*in))
+ Com_Error (ERR_DROP, "MOD_LoadBmodel: funny lump size");
+ count = l->filelen / sizeof(*in);
+
+ cm.leafbrushes = Hunk_Alloc( (count + BOX_BRUSHES) * sizeof( *cm.leafbrushes ), h_high );
+ cm.numLeafBrushes = count;
+
+ out = cm.leafbrushes;
+
+ for ( i=0 ; i<count ; i++, in++, out++) {
+ *out = LittleLong (*in);
+ }
+}
+
+/*
+=================
+CMod_LoadLeafSurfaces
+=================
+*/
+void CMod_LoadLeafSurfaces( lump_t *l )
+{
+ int i;
+ int *out;
+ int *in;
+ int count;
+
+ in = (void *)(cmod_base + l->fileofs);
+ if (l->filelen % sizeof(*in))
+ Com_Error (ERR_DROP, "MOD_LoadBmodel: funny lump size");
+ count = l->filelen / sizeof(*in);
+
+ cm.leafsurfaces = Hunk_Alloc( count * sizeof( *cm.leafsurfaces ), h_high );
+ cm.numLeafSurfaces = count;
+
+ out = cm.leafsurfaces;
+
+ for ( i=0 ; i<count ; i++, in++, out++) {
+ *out = LittleLong (*in);
+ }
+}
+
+/*
+=================
+CMod_LoadBrushSides
+=================
+*/
+void CMod_LoadBrushSides (lump_t *l)
+{
+ int i;
+ cbrushside_t *out;
+ dbrushside_t *in;
+ int count;
+ int num;
+
+ in = (void *)(cmod_base + l->fileofs);
+ if ( l->filelen % sizeof(*in) ) {
+ Com_Error (ERR_DROP, "MOD_LoadBmodel: funny lump size");
+ }
+ count = l->filelen / sizeof(*in);
+
+ cm.brushsides = Hunk_Alloc( ( BOX_SIDES + count ) * sizeof( *cm.brushsides ), h_high );
+ cm.numBrushSides = count;
+
+ out = cm.brushsides;
+
+ for ( i=0 ; i<count ; i++, in++, out++) {
+ num = LittleLong( in->planeNum );
+ out->plane = &cm.planes[num];
+ out->shaderNum = LittleLong( in->shaderNum );
+ if ( out->shaderNum < 0 || out->shaderNum >= cm.numShaders ) {
+ Com_Error( ERR_DROP, "CMod_LoadBrushSides: bad shaderNum: %i", out->shaderNum );
+ }
+ out->surfaceFlags = cm.shaders[out->shaderNum].surfaceFlags;
+ }
+}
+
+
+/*
+=================
+CMod_LoadEntityString
+=================
+*/
+void CMod_LoadEntityString( lump_t *l ) {
+ cm.entityString = Hunk_Alloc( l->filelen, h_high );
+ cm.numEntityChars = l->filelen;
+ Com_Memcpy (cm.entityString, cmod_base + l->fileofs, l->filelen);
+}
+
+/*
+=================
+CMod_LoadVisibility
+=================
+*/
+#define VIS_HEADER 8
+void CMod_LoadVisibility( lump_t *l ) {
+ int len;
+ byte *buf;
+
+ len = l->filelen;
+ if ( !len ) {
+ cm.clusterBytes = ( cm.numClusters + 31 ) & ~31;
+ cm.visibility = Hunk_Alloc( cm.clusterBytes, h_high );
+ Com_Memset( cm.visibility, 255, cm.clusterBytes );
+ return;
+ }
+ buf = cmod_base + l->fileofs;
+
+ cm.vised = qtrue;
+ cm.visibility = Hunk_Alloc( len, h_high );
+ cm.numClusters = LittleLong( ((int *)buf)[0] );
+ cm.clusterBytes = LittleLong( ((int *)buf)[1] );
+ Com_Memcpy (cm.visibility, buf + VIS_HEADER, len - VIS_HEADER );
+}
+
+//==================================================================
+
+
+/*
+=================
+CMod_LoadPatches
+=================
+*/
+#define MAX_PATCH_VERTS 1024
+void CMod_LoadPatches( lump_t *surfs, lump_t *verts ) {
+ drawVert_t *dv, *dv_p;
+ dsurface_t *in;
+ int count;
+ int i, j;
+ int c;
+ cPatch_t *patch;
+ vec3_t points[MAX_PATCH_VERTS];
+ int width, height;
+ int shaderNum;
+
+ in = (void *)(cmod_base + surfs->fileofs);
+ if (surfs->filelen % sizeof(*in))
+ Com_Error (ERR_DROP, "MOD_LoadBmodel: funny lump size");
+ cm.numSurfaces = count = surfs->filelen / sizeof(*in);
+ cm.surfaces = Hunk_Alloc( cm.numSurfaces * sizeof( cm.surfaces[0] ), h_high );
+
+ dv = (void *)(cmod_base + verts->fileofs);
+ if (verts->filelen % sizeof(*dv))
+ Com_Error (ERR_DROP, "MOD_LoadBmodel: funny lump size");
+
+ // scan through all the surfaces, but only load patches,
+ // not planar faces
+ for ( i = 0 ; i < count ; i++, in++ ) {
+ if ( LittleLong( in->surfaceType ) != MST_PATCH ) {
+ continue; // ignore other surfaces
+ }
+ // FIXME: check for non-colliding patches
+
+ cm.surfaces[ i ] = patch = Hunk_Alloc( sizeof( *patch ), h_high );
+
+ // load the full drawverts onto the stack
+ width = LittleLong( in->patchWidth );
+ height = LittleLong( in->patchHeight );
+ c = width * height;
+ if ( c > MAX_PATCH_VERTS ) {
+ Com_Error( ERR_DROP, "ParseMesh: MAX_PATCH_VERTS" );
+ }
+
+ dv_p = dv + LittleLong( in->firstVert );
+ for ( j = 0 ; j < c ; j++, dv_p++ ) {
+ points[j][0] = LittleFloat( dv_p->xyz[0] );
+ points[j][1] = LittleFloat( dv_p->xyz[1] );
+ points[j][2] = LittleFloat( dv_p->xyz[2] );
+ }
+
+ shaderNum = LittleLong( in->shaderNum );
+ patch->contents = cm.shaders[shaderNum].contentFlags;
+ patch->surfaceFlags = cm.shaders[shaderNum].surfaceFlags;
+
+ // create the internal facet structure
+ patch->pc = CM_GeneratePatchCollide( width, height, points );
+ }
+}
+
+//==================================================================
+
+unsigned CM_LumpChecksum(lump_t *lump) {
+ return LittleLong (Com_BlockChecksum (cmod_base + lump->fileofs, lump->filelen));
+}
+
+unsigned CM_Checksum(dheader_t *header) {
+ unsigned checksums[16];
+ checksums[0] = CM_LumpChecksum(&header->lumps[LUMP_SHADERS]);
+ checksums[1] = CM_LumpChecksum(&header->lumps[LUMP_LEAFS]);
+ checksums[2] = CM_LumpChecksum(&header->lumps[LUMP_LEAFBRUSHES]);
+ checksums[3] = CM_LumpChecksum(&header->lumps[LUMP_LEAFSURFACES]);
+ checksums[4] = CM_LumpChecksum(&header->lumps[LUMP_PLANES]);
+ checksums[5] = CM_LumpChecksum(&header->lumps[LUMP_BRUSHSIDES]);
+ checksums[6] = CM_LumpChecksum(&header->lumps[LUMP_BRUSHES]);
+ checksums[7] = CM_LumpChecksum(&header->lumps[LUMP_MODELS]);
+ checksums[8] = CM_LumpChecksum(&header->lumps[LUMP_NODES]);
+ checksums[9] = CM_LumpChecksum(&header->lumps[LUMP_SURFACES]);
+ checksums[10] = CM_LumpChecksum(&header->lumps[LUMP_DRAWVERTS]);
+
+ return LittleLong(Com_BlockChecksum(checksums, 11 * 4));
+}
+
+/*
+==================
+CM_LoadMap
+
+Loads in the map and all submodels
+==================
+*/
+void CM_LoadMap( const char *name, qboolean clientload, int *checksum ) {
+ int *buf;
+ int i;
+ dheader_t header;
+ int length;
+ static unsigned last_checksum;
+
+ if ( !name || !name[0] ) {
+ Com_Error( ERR_DROP, "CM_LoadMap: NULL name" );
+ }
+
+#ifndef BSPC
+ cm_noAreas = Cvar_Get ("cm_noAreas", "0", CVAR_CHEAT);
+ cm_noCurves = Cvar_Get ("cm_noCurves", "0", CVAR_CHEAT);
+ cm_playerCurveClip = Cvar_Get ("cm_playerCurveClip", "1", CVAR_ARCHIVE|CVAR_CHEAT );
+#endif
+ Com_DPrintf( "CM_LoadMap( %s, %i )\n", name, clientload );
+
+ if ( !strcmp( cm.name, name ) && clientload ) {
+ *checksum = last_checksum;
+ return;
+ }
+
+ // free old stuff
+ Com_Memset( &cm, 0, sizeof( cm ) );
+ CM_ClearLevelPatches();
+
+ if ( !name[0] ) {
+ cm.numLeafs = 1;
+ cm.numClusters = 1;
+ cm.numAreas = 1;
+ cm.cmodels = Hunk_Alloc( sizeof( *cm.cmodels ), h_high );
+ *checksum = 0;
+ return;
+ }
+
+ //
+ // load the file
+ //
+#ifndef BSPC
+ length = FS_ReadFile( name, (void **)&buf );
+#else
+ length = LoadQuakeFile((quakefile_t *) name, (void **)&buf);
+#endif
+
+ if ( !buf ) {
+ Com_Error (ERR_DROP, "Couldn't load %s", name);
+ }
+
+ last_checksum = LittleLong (Com_BlockChecksum (buf, length));
+ *checksum = last_checksum;
+
+ header = *(dheader_t *)buf;
+ for (i=0 ; i<sizeof(dheader_t)/4 ; i++) {
+ ((int *)&header)[i] = LittleLong ( ((int *)&header)[i]);
+ }
+
+ if ( header.version != BSP_VERSION ) {
+ Com_Error (ERR_DROP, "CM_LoadMap: %s has wrong version number (%i should be %i)"
+ , name, header.version, BSP_VERSION );
+ }
+
+ cmod_base = (byte *)buf;
+
+ // load into heap
+ CMod_LoadShaders( &header.lumps[LUMP_SHADERS] );
+ CMod_LoadLeafs (&header.lumps[LUMP_LEAFS]);
+ CMod_LoadLeafBrushes (&header.lumps[LUMP_LEAFBRUSHES]);
+ CMod_LoadLeafSurfaces (&header.lumps[LUMP_LEAFSURFACES]);
+ CMod_LoadPlanes (&header.lumps[LUMP_PLANES]);
+ CMod_LoadBrushSides (&header.lumps[LUMP_BRUSHSIDES]);
+ CMod_LoadBrushes (&header.lumps[LUMP_BRUSHES]);
+ CMod_LoadSubmodels (&header.lumps[LUMP_MODELS]);
+ CMod_LoadNodes (&header.lumps[LUMP_NODES]);
+ CMod_LoadEntityString (&header.lumps[LUMP_ENTITIES]);
+ CMod_LoadVisibility( &header.lumps[LUMP_VISIBILITY] );
+ CMod_LoadPatches( &header.lumps[LUMP_SURFACES], &header.lumps[LUMP_DRAWVERTS] );
+
+ // we are NOT freeing the file, because it is cached for the ref
+ FS_FreeFile (buf);
+
+ CM_InitBoxHull ();
+
+ CM_FloodAreaConnections ();
+
+ // allow this to be cached if it is loaded by the server
+ if ( !clientload ) {
+ Q_strncpyz( cm.name, name, sizeof( cm.name ) );
+ }
+}
+
+/*
+==================
+CM_ClearMap
+==================
+*/
+void CM_ClearMap( void ) {
+ Com_Memset( &cm, 0, sizeof( cm ) );
+ CM_ClearLevelPatches();
+}
+
+/*
+==================
+CM_ClipHandleToModel
+==================
+*/
+cmodel_t *CM_ClipHandleToModel( clipHandle_t handle ) {
+ if ( handle < 0 ) {
+ Com_Error( ERR_DROP, "CM_ClipHandleToModel: bad handle %i", handle );
+ }
+ if ( handle < cm.numSubModels ) {
+ return &cm.cmodels[handle];
+ }
+ if ( handle == BOX_MODEL_HANDLE ) {
+ return &box_model;
+ }
+ if ( handle < MAX_SUBMODELS ) {
+ Com_Error( ERR_DROP, "CM_ClipHandleToModel: bad handle %i < %i < %i",
+ cm.numSubModels, handle, MAX_SUBMODELS );
+ }
+ Com_Error( ERR_DROP, "CM_ClipHandleToModel: bad handle %i", handle + MAX_SUBMODELS );
+
+ return NULL;
+
+}
+
+/*
+==================
+CM_InlineModel
+==================
+*/
+clipHandle_t CM_InlineModel( int index ) {
+ if ( index < 0 || index >= cm.numSubModels ) {
+ Com_Error (ERR_DROP, "CM_InlineModel: bad number");
+ }
+ return index;
+}
+
+int CM_NumClusters( void ) {
+ return cm.numClusters;
+}
+
+int CM_NumInlineModels( void ) {
+ return cm.numSubModels;
+}
+
+char *CM_EntityString( void ) {
+ return cm.entityString;
+}
+
+int CM_LeafCluster( int leafnum ) {
+ if (leafnum < 0 || leafnum >= cm.numLeafs) {
+ Com_Error (ERR_DROP, "CM_LeafCluster: bad number");
+ }
+ return cm.leafs[leafnum].cluster;
+}
+
+int CM_LeafArea( int leafnum ) {
+ if ( leafnum < 0 || leafnum >= cm.numLeafs ) {
+ Com_Error (ERR_DROP, "CM_LeafArea: bad number");
+ }
+ return cm.leafs[leafnum].area;
+}
+
+//=======================================================================
+
+
+/*
+===================
+CM_InitBoxHull
+
+Set up the planes and nodes so that the six floats of a bounding box
+can just be stored out and get a proper clipping hull structure.
+===================
+*/
+void CM_InitBoxHull (void)
+{
+ int i;
+ int side;
+ cplane_t *p;
+ cbrushside_t *s;
+
+ box_planes = &cm.planes[cm.numPlanes];
+
+ box_brush = &cm.brushes[cm.numBrushes];
+ box_brush->numsides = 6;
+ box_brush->sides = cm.brushsides + cm.numBrushSides;
+ box_brush->contents = CONTENTS_BODY;
+
+ box_model.leaf.numLeafBrushes = 1;
+// box_model.leaf.firstLeafBrush = cm.numBrushes;
+ box_model.leaf.firstLeafBrush = cm.numLeafBrushes;
+ cm.leafbrushes[cm.numLeafBrushes] = cm.numBrushes;
+
+ for (i=0 ; i<6 ; i++)
+ {
+ side = i&1;
+
+ // brush sides
+ s = &cm.brushsides[cm.numBrushSides+i];
+ s->plane = cm.planes + (cm.numPlanes+i*2+side);
+ s->surfaceFlags = 0;
+
+ // planes
+ p = &box_planes[i*2];
+ p->type = i>>1;
+ p->signbits = 0;
+ VectorClear (p->normal);
+ p->normal[i>>1] = 1;
+
+ p = &box_planes[i*2+1];
+ p->type = 3 + (i>>1);
+ p->signbits = 0;
+ VectorClear (p->normal);
+ p->normal[i>>1] = -1;
+
+ SetPlaneSignbits( p );
+ }
+}
+
+/*
+===================
+CM_TempBoxModel
+
+To keep everything totally uniform, bounding boxes are turned into small
+BSP trees instead of being compared directly.
+Capsules are handled differently though.
+===================
+*/
+clipHandle_t CM_TempBoxModel( const vec3_t mins, const vec3_t maxs, int capsule ) {
+
+ VectorCopy( mins, box_model.mins );
+ VectorCopy( maxs, box_model.maxs );
+
+ if ( capsule ) {
+ return CAPSULE_MODEL_HANDLE;
+ }
+
+ box_planes[0].dist = maxs[0];
+ box_planes[1].dist = -maxs[0];
+ box_planes[2].dist = mins[0];
+ box_planes[3].dist = -mins[0];
+ box_planes[4].dist = maxs[1];
+ box_planes[5].dist = -maxs[1];
+ box_planes[6].dist = mins[1];
+ box_planes[7].dist = -mins[1];
+ box_planes[8].dist = maxs[2];
+ box_planes[9].dist = -maxs[2];
+ box_planes[10].dist = mins[2];
+ box_planes[11].dist = -mins[2];
+
+ VectorCopy( mins, box_brush->bounds[0] );
+ VectorCopy( maxs, box_brush->bounds[1] );
+
+ return BOX_MODEL_HANDLE;
+}
+
+/*
+===================
+CM_ModelBounds
+===================
+*/
+void CM_ModelBounds( clipHandle_t model, vec3_t mins, vec3_t maxs ) {
+ cmodel_t *cmod;
+
+ cmod = CM_ClipHandleToModel( model );
+ VectorCopy( cmod->mins, mins );
+ VectorCopy( cmod->maxs, maxs );
+}
+
+
diff --git a/code/qcommon/cm_local.h b/code/qcommon/cm_local.h
new file mode 100755
index 0000000..938cba0
--- /dev/null
+++ b/code/qcommon/cm_local.h
@@ -0,0 +1,194 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "../game/q_shared.h"
+#include "qcommon.h"
+#include "cm_polylib.h"
+
+#define MAX_SUBMODELS 256
+#define BOX_MODEL_HANDLE 255
+#define CAPSULE_MODEL_HANDLE 254
+
+
+typedef struct {
+ cplane_t *plane;
+ int children[2]; // negative numbers are leafs
+} cNode_t;
+
+typedef struct {
+ int cluster;
+ int area;
+
+ int firstLeafBrush;
+ int numLeafBrushes;
+
+ int firstLeafSurface;
+ int numLeafSurfaces;
+} cLeaf_t;
+
+typedef struct cmodel_s {
+ vec3_t mins, maxs;
+ cLeaf_t leaf; // submodels don't reference the main tree
+} cmodel_t;
+
+typedef struct {
+ cplane_t *plane;
+ int surfaceFlags;
+ int shaderNum;
+} cbrushside_t;
+
+typedef struct {
+ int shaderNum; // the shader that determined the contents
+ int contents;
+ vec3_t bounds[2];
+ int numsides;
+ cbrushside_t *sides;
+ int checkcount; // to avoid repeated testings
+} cbrush_t;
+
+
+typedef struct {
+ int checkcount; // to avoid repeated testings
+ int surfaceFlags;
+ int contents;
+ struct patchCollide_s *pc;
+} cPatch_t;
+
+
+typedef struct {
+ int floodnum;
+ int floodvalid;
+} cArea_t;
+
+typedef struct {
+ char name[MAX_QPATH];
+
+ int numShaders;
+ dshader_t *shaders;
+
+ int numBrushSides;
+ cbrushside_t *brushsides;
+
+ int numPlanes;
+ cplane_t *planes;
+
+ int numNodes;
+ cNode_t *nodes;
+
+ int numLeafs;
+ cLeaf_t *leafs;
+
+ int numLeafBrushes;
+ int *leafbrushes;
+
+ int numLeafSurfaces;
+ int *leafsurfaces;
+
+ int numSubModels;
+ cmodel_t *cmodels;
+
+ int numBrushes;
+ cbrush_t *brushes;
+
+ int numClusters;
+ int clusterBytes;
+ byte *visibility;
+ qboolean vised; // if false, visibility is just a single cluster of ffs
+
+ int numEntityChars;
+ char *entityString;
+
+ int numAreas;
+ cArea_t *areas;
+ int *areaPortals; // [ numAreas*numAreas ] reference counts
+
+ int numSurfaces;
+ cPatch_t **surfaces; // non-patches will be NULL
+
+ int floodvalid;
+ int checkcount; // incremented on each trace
+} clipMap_t;
+
+
+// keep 1/8 unit away to keep the position valid before network snapping
+// and to avoid various numeric issues
+#define SURFACE_CLIP_EPSILON (0.125)
+
+extern clipMap_t cm;
+extern int c_pointcontents;
+extern int c_traces, c_brush_traces, c_patch_traces;
+extern cvar_t *cm_noAreas;
+extern cvar_t *cm_noCurves;
+extern cvar_t *cm_playerCurveClip;
+
+// cm_test.c
+
+// Used for oriented capsule collision detection
+typedef struct
+{
+ qboolean use;
+ float radius;
+ float halfheight;
+ vec3_t offset;
+} sphere_t;
+
+typedef struct {
+ vec3_t start;
+ vec3_t end;
+ vec3_t size[2]; // size of the box being swept through the model
+ vec3_t offsets[8]; // [signbits][x] = either size[0][x] or size[1][x]
+ float maxOffset; // longest corner length from origin
+ vec3_t extents; // greatest of abs(size[0]) and abs(size[1])
+ vec3_t bounds[2]; // enclosing box of start and end surrounding by size
+ vec3_t modelOrigin;// origin of the model tracing through
+ int contents; // ored contents of the model tracing through
+ qboolean isPoint; // optimized case
+ trace_t trace; // returned from trace call
+ sphere_t sphere; // sphere for oriendted capsule collision
+} traceWork_t;
+
+typedef struct leafList_s {
+ int count;
+ int maxcount;
+ qboolean overflowed;
+ int *list;
+ vec3_t bounds[2];
+ int lastLeaf; // for overflows where each leaf can't be stored individually
+ void (*storeLeafs)( struct leafList_s *ll, int nodenum );
+} leafList_t;
+
+
+int CM_BoxBrushes( const vec3_t mins, const vec3_t maxs, cbrush_t **list, int listsize );
+
+void CM_StoreLeafs( leafList_t *ll, int nodenum );
+void CM_StoreBrushes( leafList_t *ll, int nodenum );
+
+void CM_BoxLeafnums_r( leafList_t *ll, int nodenum );
+
+cmodel_t *CM_ClipHandleToModel( clipHandle_t handle );
+
+// cm_patch.c
+
+struct patchCollide_s *CM_GeneratePatchCollide( int width, int height, vec3_t *points );
+void CM_TraceThroughPatchCollide( traceWork_t *tw, const struct patchCollide_s *pc );
+qboolean CM_PositionTestInPatchCollide( traceWork_t *tw, const struct patchCollide_s *pc );
+void CM_ClearLevelPatches( void );
diff --git a/code/qcommon/cm_patch.c b/code/qcommon/cm_patch.c
new file mode 100755
index 0000000..3235b1f
--- /dev/null
+++ b/code/qcommon/cm_patch.c
@@ -0,0 +1,1771 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "cm_local.h"
+#include "cm_patch.h"
+
+/*
+
+This file does not reference any globals, and has these entry points:
+
+void CM_ClearLevelPatches( void );
+struct patchCollide_s *CM_GeneratePatchCollide( int width, int height, const vec3_t *points );
+void CM_TraceThroughPatchCollide( traceWork_t *tw, const struct patchCollide_s *pc );
+qboolean CM_PositionTestInPatchCollide( traceWork_t *tw, const struct patchCollide_s *pc );
+void CM_DrawDebugSurface( void (*drawPoly)(int color, int numPoints, flaot *points) );
+
+
+WARNING: this may misbehave with meshes that have rows or columns that only
+degenerate a few triangles. Completely degenerate rows and columns are handled
+properly.
+*/
+
+/*
+#define MAX_FACETS 1024
+#define MAX_PATCH_PLANES 2048
+
+typedef struct {
+ float plane[4];
+ int signbits; // signx + (signy<<1) + (signz<<2), used as lookup during collision
+} patchPlane_t;
+
+typedef struct {
+ int surfacePlane;
+ int numBorders; // 3 or four + 6 axial bevels + 4 or 3 * 4 edge bevels
+ int borderPlanes[4+6+16];
+ int borderInward[4+6+16];
+ qboolean borderNoAdjust[4+6+16];
+} facet_t;
+
+typedef struct patchCollide_s {
+ vec3_t bounds[2];
+ int numPlanes; // surface planes plus edge planes
+ patchPlane_t *planes;
+ int numFacets;
+ facet_t *facets;
+} patchCollide_t;
+
+
+#define MAX_GRID_SIZE 129
+
+typedef struct {
+ int width;
+ int height;
+ qboolean wrapWidth;
+ qboolean wrapHeight;
+ vec3_t points[MAX_GRID_SIZE][MAX_GRID_SIZE]; // [width][height]
+} cGrid_t;
+
+#define SUBDIVIDE_DISTANCE 16 //4 // never more than this units away from curve
+#define PLANE_TRI_EPSILON 0.1
+#define WRAP_POINT_EPSILON 0.1
+*/
+
+int c_totalPatchBlocks;
+int c_totalPatchSurfaces;
+int c_totalPatchEdges;
+
+static const patchCollide_t *debugPatchCollide;
+static const facet_t *debugFacet;
+static qboolean debugBlock;
+static vec3_t debugBlockPoints[4];
+
+/*
+=================
+CM_ClearLevelPatches
+=================
+*/
+void CM_ClearLevelPatches( void ) {
+ debugPatchCollide = NULL;
+ debugFacet = NULL;
+}
+
+/*
+=================
+CM_SignbitsForNormal
+=================
+*/
+static int CM_SignbitsForNormal( vec3_t normal ) {
+ int bits, j;
+
+ bits = 0;
+ for (j=0 ; j<3 ; j++) {
+ if ( normal[j] < 0 ) {
+ bits |= 1<<j;
+ }
+ }
+ return bits;
+}
+
+/*
+=====================
+CM_PlaneFromPoints
+
+Returns false if the triangle is degenrate.
+The normal will point out of the clock for clockwise ordered points
+=====================
+*/
+static qboolean CM_PlaneFromPoints( vec4_t plane, vec3_t a, vec3_t b, vec3_t c ) {
+ vec3_t d1, d2;
+
+ VectorSubtract( b, a, d1 );
+ VectorSubtract( c, a, d2 );
+ CrossProduct( d2, d1, plane );
+ if ( VectorNormalize( plane ) == 0 ) {
+ return qfalse;
+ }
+
+ plane[3] = DotProduct( a, plane );
+ return qtrue;
+}
+
+
+/*
+================================================================================
+
+GRID SUBDIVISION
+
+================================================================================
+*/
+
+/*
+=================
+CM_NeedsSubdivision
+
+Returns true if the given quadratic curve is not flat enough for our
+collision detection purposes
+=================
+*/
+static qboolean CM_NeedsSubdivision( vec3_t a, vec3_t b, vec3_t c ) {
+ vec3_t cmid;
+ vec3_t lmid;
+ vec3_t delta;
+ float dist;
+ int i;
+
+ // calculate the linear midpoint
+ for ( i = 0 ; i < 3 ; i++ ) {
+ lmid[i] = 0.5*(a[i] + c[i]);
+ }
+
+ // calculate the exact curve midpoint
+ for ( i = 0 ; i < 3 ; i++ ) {
+ cmid[i] = 0.5 * ( 0.5*(a[i] + b[i]) + 0.5*(b[i] + c[i]) );
+ }
+
+ // see if the curve is far enough away from the linear mid
+ VectorSubtract( cmid, lmid, delta );
+ dist = VectorLength( delta );
+
+ return dist >= SUBDIVIDE_DISTANCE;
+}
+
+/*
+===============
+CM_Subdivide
+
+a, b, and c are control points.
+the subdivided sequence will be: a, out1, out2, out3, c
+===============
+*/
+static void CM_Subdivide( vec3_t a, vec3_t b, vec3_t c, vec3_t out1, vec3_t out2, vec3_t out3 ) {
+ int i;
+
+ for ( i = 0 ; i < 3 ; i++ ) {
+ out1[i] = 0.5 * (a[i] + b[i]);
+ out3[i] = 0.5 * (b[i] + c[i]);
+ out2[i] = 0.5 * (out1[i] + out3[i]);
+ }
+}
+
+/*
+=================
+CM_TransposeGrid
+
+Swaps the rows and columns in place
+=================
+*/
+static void CM_TransposeGrid( cGrid_t *grid ) {
+ int i, j, l;
+ vec3_t temp;
+ qboolean tempWrap;
+
+ if ( grid->width > grid->height ) {
+ for ( i = 0 ; i < grid->height ; i++ ) {
+ for ( j = i + 1 ; j < grid->width ; j++ ) {
+ if ( j < grid->height ) {
+ // swap the value
+ VectorCopy( grid->points[i][j], temp );
+ VectorCopy( grid->points[j][i], grid->points[i][j] );
+ VectorCopy( temp, grid->points[j][i] );
+ } else {
+ // just copy
+ VectorCopy( grid->points[j][i], grid->points[i][j] );
+ }
+ }
+ }
+ } else {
+ for ( i = 0 ; i < grid->width ; i++ ) {
+ for ( j = i + 1 ; j < grid->height ; j++ ) {
+ if ( j < grid->width ) {
+ // swap the value
+ VectorCopy( grid->points[j][i], temp );
+ VectorCopy( grid->points[i][j], grid->points[j][i] );
+ VectorCopy( temp, grid->points[i][j] );
+ } else {
+ // just copy
+ VectorCopy( grid->points[i][j], grid->points[j][i] );
+ }
+ }
+ }
+ }
+
+ l = grid->width;
+ grid->width = grid->height;
+ grid->height = l;
+
+ tempWrap = grid->wrapWidth;
+ grid->wrapWidth = grid->wrapHeight;
+ grid->wrapHeight = tempWrap;
+}
+
+/*
+===================
+CM_SetGridWrapWidth
+
+If the left and right columns are exactly equal, set grid->wrapWidth qtrue
+===================
+*/
+static void CM_SetGridWrapWidth( cGrid_t *grid ) {
+ int i, j;
+ float d;
+
+ for ( i = 0 ; i < grid->height ; i++ ) {
+ for ( j = 0 ; j < 3 ; j++ ) {
+ d = grid->points[0][i][j] - grid->points[grid->width-1][i][j];
+ if ( d < -WRAP_POINT_EPSILON || d > WRAP_POINT_EPSILON ) {
+ break;
+ }
+ }
+ if ( j != 3 ) {
+ break;
+ }
+ }
+ if ( i == grid->height ) {
+ grid->wrapWidth = qtrue;
+ } else {
+ grid->wrapWidth = qfalse;
+ }
+}
+
+/*
+=================
+CM_SubdivideGridColumns
+
+Adds columns as necessary to the grid until
+all the aproximating points are within SUBDIVIDE_DISTANCE
+from the true curve
+=================
+*/
+static void CM_SubdivideGridColumns( cGrid_t *grid ) {
+ int i, j, k;
+
+ for ( i = 0 ; i < grid->width - 2 ; ) {
+ // grid->points[i][x] is an interpolating control point
+ // grid->points[i+1][x] is an aproximating control point
+ // grid->points[i+2][x] is an interpolating control point
+
+ //
+ // first see if we can collapse the aproximating collumn away
+ //
+ for ( j = 0 ; j < grid->height ; j++ ) {
+ if ( CM_NeedsSubdivision( grid->points[i][j], grid->points[i+1][j], grid->points[i+2][j] ) ) {
+ break;
+ }
+ }
+ if ( j == grid->height ) {
+ // all of the points were close enough to the linear midpoints
+ // that we can collapse the entire column away
+ for ( j = 0 ; j < grid->height ; j++ ) {
+ // remove the column
+ for ( k = i + 2 ; k < grid->width ; k++ ) {
+ VectorCopy( grid->points[k][j], grid->points[k-1][j] );
+ }
+ }
+
+ grid->width--;
+
+ // go to the next curve segment
+ i++;
+ continue;
+ }
+
+ //
+ // we need to subdivide the curve
+ //
+ for ( j = 0 ; j < grid->height ; j++ ) {
+ vec3_t prev, mid, next;
+
+ // save the control points now
+ VectorCopy( grid->points[i][j], prev );
+ VectorCopy( grid->points[i+1][j], mid );
+ VectorCopy( grid->points[i+2][j], next );
+
+ // make room for two additional columns in the grid
+ // columns i+1 will be replaced, column i+2 will become i+4
+ // i+1, i+2, and i+3 will be generated
+ for ( k = grid->width - 1 ; k > i + 1 ; k-- ) {
+ VectorCopy( grid->points[k][j], grid->points[k+2][j] );
+ }
+
+ // generate the subdivided points
+ CM_Subdivide( prev, mid, next, grid->points[i+1][j], grid->points[i+2][j], grid->points[i+3][j] );
+ }
+
+ grid->width += 2;
+
+ // the new aproximating point at i+1 may need to be removed
+ // or subdivided farther, so don't advance i
+ }
+}
+
+/*
+======================
+CM_ComparePoints
+======================
+*/
+#define POINT_EPSILON 0.1
+static qboolean CM_ComparePoints( float *a, float *b ) {
+ float d;
+
+ d = a[0] - b[0];
+ if ( d < -POINT_EPSILON || d > POINT_EPSILON ) {
+ return qfalse;
+ }
+ d = a[1] - b[1];
+ if ( d < -POINT_EPSILON || d > POINT_EPSILON ) {
+ return qfalse;
+ }
+ d = a[2] - b[2];
+ if ( d < -POINT_EPSILON || d > POINT_EPSILON ) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+/*
+=================
+CM_RemoveDegenerateColumns
+
+If there are any identical columns, remove them
+=================
+*/
+static void CM_RemoveDegenerateColumns( cGrid_t *grid ) {
+ int i, j, k;
+
+ for ( i = 0 ; i < grid->width - 1 ; i++ ) {
+ for ( j = 0 ; j < grid->height ; j++ ) {
+ if ( !CM_ComparePoints( grid->points[i][j], grid->points[i+1][j] ) ) {
+ break;
+ }
+ }
+
+ if ( j != grid->height ) {
+ continue; // not degenerate
+ }
+
+ for ( j = 0 ; j < grid->height ; j++ ) {
+ // remove the column
+ for ( k = i + 2 ; k < grid->width ; k++ ) {
+ VectorCopy( grid->points[k][j], grid->points[k-1][j] );
+ }
+ }
+ grid->width--;
+
+ // check against the next column
+ i--;
+ }
+}
+
+/*
+================================================================================
+
+PATCH COLLIDE GENERATION
+
+================================================================================
+*/
+
+static int numPlanes;
+static patchPlane_t planes[MAX_PATCH_PLANES];
+
+static int numFacets;
+static facet_t facets[MAX_PATCH_PLANES]; //maybe MAX_FACETS ??
+
+#define NORMAL_EPSILON 0.0001
+#define DIST_EPSILON 0.02
+
+/*
+==================
+CM_PlaneEqual
+==================
+*/
+int CM_PlaneEqual(patchPlane_t *p, float plane[4], int *flipped) {
+ float invplane[4];
+
+ if (
+ fabs(p->plane[0] - plane[0]) < NORMAL_EPSILON
+ && fabs(p->plane[1] - plane[1]) < NORMAL_EPSILON
+ && fabs(p->plane[2] - plane[2]) < NORMAL_EPSILON
+ && fabs(p->plane[3] - plane[3]) < DIST_EPSILON )
+ {
+ *flipped = qfalse;
+ return qtrue;
+ }
+
+ VectorNegate(plane, invplane);
+ invplane[3] = -plane[3];
+
+ if (
+ fabs(p->plane[0] - invplane[0]) < NORMAL_EPSILON
+ && fabs(p->plane[1] - invplane[1]) < NORMAL_EPSILON
+ && fabs(p->plane[2] - invplane[2]) < NORMAL_EPSILON
+ && fabs(p->plane[3] - invplane[3]) < DIST_EPSILON )
+ {
+ *flipped = qtrue;
+ return qtrue;
+ }
+
+ return qfalse;
+}
+
+/*
+==================
+CM_SnapVector
+==================
+*/
+void CM_SnapVector(vec3_t normal) {
+ int i;
+
+ for (i=0 ; i<3 ; i++)
+ {
+ if ( fabs(normal[i] - 1) < NORMAL_EPSILON )
+ {
+ VectorClear (normal);
+ normal[i] = 1;
+ break;
+ }
+ if ( fabs(normal[i] - -1) < NORMAL_EPSILON )
+ {
+ VectorClear (normal);
+ normal[i] = -1;
+ break;
+ }
+ }
+}
+
+/*
+==================
+CM_FindPlane2
+==================
+*/
+int CM_FindPlane2(float plane[4], int *flipped) {
+ int i;
+
+ // see if the points are close enough to an existing plane
+ for ( i = 0 ; i < numPlanes ; i++ ) {
+ if (CM_PlaneEqual(&planes[i], plane, flipped)) return i;
+ }
+
+ // add a new plane
+ if ( numPlanes == MAX_PATCH_PLANES ) {
+ Com_Error( ERR_DROP, "MAX_PATCH_PLANES" );
+ }
+
+ Vector4Copy( plane, planes[numPlanes].plane );
+ planes[numPlanes].signbits = CM_SignbitsForNormal( plane );
+
+ numPlanes++;
+
+ *flipped = qfalse;
+
+ return numPlanes-1;
+}
+
+/*
+==================
+CM_FindPlane
+==================
+*/
+static int CM_FindPlane( float *p1, float *p2, float *p3 ) {
+ float plane[4];
+ int i;
+ float d;
+
+ if ( !CM_PlaneFromPoints( plane, p1, p2, p3 ) ) {
+ return -1;
+ }
+
+ // see if the points are close enough to an existing plane
+ for ( i = 0 ; i < numPlanes ; i++ ) {
+ if ( DotProduct( plane, planes[i].plane ) < 0 ) {
+ continue; // allow backwards planes?
+ }
+
+ d = DotProduct( p1, planes[i].plane ) - planes[i].plane[3];
+ if ( d < -PLANE_TRI_EPSILON || d > PLANE_TRI_EPSILON ) {
+ continue;
+ }
+
+ d = DotProduct( p2, planes[i].plane ) - planes[i].plane[3];
+ if ( d < -PLANE_TRI_EPSILON || d > PLANE_TRI_EPSILON ) {
+ continue;
+ }
+
+ d = DotProduct( p3, planes[i].plane ) - planes[i].plane[3];
+ if ( d < -PLANE_TRI_EPSILON || d > PLANE_TRI_EPSILON ) {
+ continue;
+ }
+
+ // found it
+ return i;
+ }
+
+ // add a new plane
+ if ( numPlanes == MAX_PATCH_PLANES ) {
+ Com_Error( ERR_DROP, "MAX_PATCH_PLANES" );
+ }
+
+ Vector4Copy( plane, planes[numPlanes].plane );
+ planes[numPlanes].signbits = CM_SignbitsForNormal( plane );
+
+ numPlanes++;
+
+ return numPlanes-1;
+}
+
+/*
+==================
+CM_PointOnPlaneSide
+==================
+*/
+static int CM_PointOnPlaneSide( float *p, int planeNum ) {
+ float *plane;
+ float d;
+
+ if ( planeNum == -1 ) {
+ return SIDE_ON;
+ }
+ plane = planes[ planeNum ].plane;
+
+ d = DotProduct( p, plane ) - plane[3];
+
+ if ( d > PLANE_TRI_EPSILON ) {
+ return SIDE_FRONT;
+ }
+
+ if ( d < -PLANE_TRI_EPSILON ) {
+ return SIDE_BACK;
+ }
+
+ return SIDE_ON;
+}
+
+/*
+==================
+CM_GridPlane
+==================
+*/
+static int CM_GridPlane( int gridPlanes[MAX_GRID_SIZE][MAX_GRID_SIZE][2], int i, int j, int tri ) {
+ int p;
+
+ p = gridPlanes[i][j][tri];
+ if ( p != -1 ) {
+ return p;
+ }
+ p = gridPlanes[i][j][!tri];
+ if ( p != -1 ) {
+ return p;
+ }
+
+ // should never happen
+ Com_Printf( "WARNING: CM_GridPlane unresolvable\n" );
+ return -1;
+}
+
+/*
+==================
+CM_EdgePlaneNum
+==================
+*/
+static int CM_EdgePlaneNum( cGrid_t *grid, int gridPlanes[MAX_GRID_SIZE][MAX_GRID_SIZE][2], int i, int j, int k ) {
+ float *p1, *p2;
+ vec3_t up;
+ int p;
+
+ switch ( k ) {
+ case 0: // top border
+ p1 = grid->points[i][j];
+ p2 = grid->points[i+1][j];
+ p = CM_GridPlane( gridPlanes, i, j, 0 );
+ VectorMA( p1, 4, planes[ p ].plane, up );
+ return CM_FindPlane( p1, p2, up );
+
+ case 2: // bottom border
+ p1 = grid->points[i][j+1];
+ p2 = grid->points[i+1][j+1];
+ p = CM_GridPlane( gridPlanes, i, j, 1 );
+ VectorMA( p1, 4, planes[ p ].plane, up );
+ return CM_FindPlane( p2, p1, up );
+
+ case 3: // left border
+ p1 = grid->points[i][j];
+ p2 = grid->points[i][j+1];
+ p = CM_GridPlane( gridPlanes, i, j, 1 );
+ VectorMA( p1, 4, planes[ p ].plane, up );
+ return CM_FindPlane( p2, p1, up );
+
+ case 1: // right border
+ p1 = grid->points[i+1][j];
+ p2 = grid->points[i+1][j+1];
+ p = CM_GridPlane( gridPlanes, i, j, 0 );
+ VectorMA( p1, 4, planes[ p ].plane, up );
+ return CM_FindPlane( p1, p2, up );
+
+ case 4: // diagonal out of triangle 0
+ p1 = grid->points[i+1][j+1];
+ p2 = grid->points[i][j];
+ p = CM_GridPlane( gridPlanes, i, j, 0 );
+ VectorMA( p1, 4, planes[ p ].plane, up );
+ return CM_FindPlane( p1, p2, up );
+
+ case 5: // diagonal out of triangle 1
+ p1 = grid->points[i][j];
+ p2 = grid->points[i+1][j+1];
+ p = CM_GridPlane( gridPlanes, i, j, 1 );
+ VectorMA( p1, 4, planes[ p ].plane, up );
+ return CM_FindPlane( p1, p2, up );
+
+ }
+
+ Com_Error( ERR_DROP, "CM_EdgePlaneNum: bad k" );
+ return -1;
+}
+
+/*
+===================
+CM_SetBorderInward
+===================
+*/
+static void CM_SetBorderInward( facet_t *facet, cGrid_t *grid, int gridPlanes[MAX_GRID_SIZE][MAX_GRID_SIZE][2],
+ int i, int j, int which ) {
+ int k, l;
+ float *points[4];
+ int numPoints;
+
+ switch ( which ) {
+ case -1:
+ points[0] = grid->points[i][j];
+ points[1] = grid->points[i+1][j];
+ points[2] = grid->points[i+1][j+1];
+ points[3] = grid->points[i][j+1];
+ numPoints = 4;
+ break;
+ case 0:
+ points[0] = grid->points[i][j];
+ points[1] = grid->points[i+1][j];
+ points[2] = grid->points[i+1][j+1];
+ numPoints = 3;
+ break;
+ case 1:
+ points[0] = grid->points[i+1][j+1];
+ points[1] = grid->points[i][j+1];
+ points[2] = grid->points[i][j];
+ numPoints = 3;
+ break;
+ default:
+ Com_Error( ERR_FATAL, "CM_SetBorderInward: bad parameter" );
+ numPoints = 0;
+ break;
+ }
+
+ for ( k = 0 ; k < facet->numBorders ; k++ ) {
+ int front, back;
+
+ front = 0;
+ back = 0;
+
+ for ( l = 0 ; l < numPoints ; l++ ) {
+ int side;
+
+ side = CM_PointOnPlaneSide( points[l], facet->borderPlanes[k] );
+ if ( side == SIDE_FRONT ) {
+ front++;
+ } if ( side == SIDE_BACK ) {
+ back++;
+ }
+ }
+
+ if ( front && !back ) {
+ facet->borderInward[k] = qtrue;
+ } else if ( back && !front ) {
+ facet->borderInward[k] = qfalse;
+ } else if ( !front && !back ) {
+ // flat side border
+ facet->borderPlanes[k] = -1;
+ } else {
+ // bisecting side border
+ Com_DPrintf( "WARNING: CM_SetBorderInward: mixed plane sides\n" );
+ facet->borderInward[k] = qfalse;
+ if ( !debugBlock ) {
+ debugBlock = qtrue;
+ VectorCopy( grid->points[i][j], debugBlockPoints[0] );
+ VectorCopy( grid->points[i+1][j], debugBlockPoints[1] );
+ VectorCopy( grid->points[i+1][j+1], debugBlockPoints[2] );
+ VectorCopy( grid->points[i][j+1], debugBlockPoints[3] );
+ }
+ }
+ }
+}
+
+/*
+==================
+CM_ValidateFacet
+
+If the facet isn't bounded by its borders, we screwed up.
+==================
+*/
+static qboolean CM_ValidateFacet( facet_t *facet ) {
+ float plane[4];
+ int j;
+ winding_t *w;
+ vec3_t bounds[2];
+
+ if ( facet->surfacePlane == -1 ) {
+ return qfalse;
+ }
+
+ Vector4Copy( planes[ facet->surfacePlane ].plane, plane );
+ w = BaseWindingForPlane( plane, plane[3] );
+ for ( j = 0 ; j < facet->numBorders && w ; j++ ) {
+ if ( facet->borderPlanes[j] == -1 ) {
+ return qfalse;
+ }
+ Vector4Copy( planes[ facet->borderPlanes[j] ].plane, plane );
+ if ( !facet->borderInward[j] ) {
+ VectorSubtract( vec3_origin, plane, plane );
+ plane[3] = -plane[3];
+ }
+ ChopWindingInPlace( &w, plane, plane[3], 0.1f );
+ }
+
+ if ( !w ) {
+ return qfalse; // winding was completely chopped away
+ }
+
+ // see if the facet is unreasonably large
+ WindingBounds( w, bounds[0], bounds[1] );
+ FreeWinding( w );
+
+ for ( j = 0 ; j < 3 ; j++ ) {
+ if ( bounds[1][j] - bounds[0][j] > MAX_MAP_BOUNDS ) {
+ return qfalse; // we must be missing a plane
+ }
+ if ( bounds[0][j] >= MAX_MAP_BOUNDS ) {
+ return qfalse;
+ }
+ if ( bounds[1][j] <= -MAX_MAP_BOUNDS ) {
+ return qfalse;
+ }
+ }
+ return qtrue; // winding is fine
+}
+
+/*
+==================
+CM_AddFacetBevels
+==================
+*/
+void CM_AddFacetBevels( facet_t *facet ) {
+
+ int i, j, k, l;
+ int axis, dir, order, flipped;
+ float plane[4], d, newplane[4];
+ winding_t *w, *w2;
+ vec3_t mins, maxs, vec, vec2;
+
+ Vector4Copy( planes[ facet->surfacePlane ].plane, plane );
+
+ w = BaseWindingForPlane( plane, plane[3] );
+ for ( j = 0 ; j < facet->numBorders && w ; j++ ) {
+ if (facet->borderPlanes[j] == facet->surfacePlane) continue;
+ Vector4Copy( planes[ facet->borderPlanes[j] ].plane, plane );
+
+ if ( !facet->borderInward[j] ) {
+ VectorSubtract( vec3_origin, plane, plane );
+ plane[3] = -plane[3];
+ }
+
+ ChopWindingInPlace( &w, plane, plane[3], 0.1f );
+ }
+ if ( !w ) {
+ return;
+ }
+
+ WindingBounds(w, mins, maxs);
+
+ // add the axial planes
+ order = 0;
+ for ( axis = 0 ; axis < 3 ; axis++ )
+ {
+ for ( dir = -1 ; dir <= 1 ; dir += 2, order++ )
+ {
+ VectorClear(plane);
+ plane[axis] = dir;
+ if (dir == 1) {
+ plane[3] = maxs[axis];
+ }
+ else {
+ plane[3] = -mins[axis];
+ }
+ //if it's the surface plane
+ if (CM_PlaneEqual(&planes[facet->surfacePlane], plane, &flipped)) {
+ continue;
+ }
+ // see if the plane is allready present
+ for ( i = 0 ; i < facet->numBorders ; i++ ) {
+ if (CM_PlaneEqual(&planes[facet->borderPlanes[i]], plane, &flipped))
+ break;
+ }
+
+ if ( i == facet->numBorders ) {
+ if (facet->numBorders > 4 + 6 + 16) Com_Printf("ERROR: too many bevels\n");
+ facet->borderPlanes[facet->numBorders] = CM_FindPlane2(plane, &flipped);
+ facet->borderNoAdjust[facet->numBorders] = 0;
+ facet->borderInward[facet->numBorders] = flipped;
+ facet->numBorders++;
+ }
+ }
+ }
+ //
+ // add the edge bevels
+ //
+ // test the non-axial plane edges
+ for ( j = 0 ; j < w->numpoints ; j++ )
+ {
+ k = (j+1)%w->numpoints;
+ VectorSubtract (w->p[j], w->p[k], vec);
+ //if it's a degenerate edge
+ if (VectorNormalize (vec) < 0.5)
+ continue;
+ CM_SnapVector(vec);
+ for ( k = 0; k < 3 ; k++ )
+ if ( vec[k] == -1 || vec[k] == 1 )
+ break; // axial
+ if ( k < 3 )
+ continue; // only test non-axial edges
+
+ // try the six possible slanted axials from this edge
+ for ( axis = 0 ; axis < 3 ; axis++ )
+ {
+ for ( dir = -1 ; dir <= 1 ; dir += 2 )
+ {
+ // construct a plane
+ VectorClear (vec2);
+ vec2[axis] = dir;
+ CrossProduct (vec, vec2, plane);
+ if (VectorNormalize (plane) < 0.5)
+ continue;
+ plane[3] = DotProduct (w->p[j], plane);
+
+ // if all the points of the facet winding are
+ // behind this plane, it is a proper edge bevel
+ for ( l = 0 ; l < w->numpoints ; l++ )
+ {
+ d = DotProduct (w->p[l], plane) - plane[3];
+ if (d > 0.1)
+ break; // point in front
+ }
+ if ( l < w->numpoints )
+ continue;
+
+ //if it's the surface plane
+ if (CM_PlaneEqual(&planes[facet->surfacePlane], plane, &flipped)) {
+ continue;
+ }
+ // see if the plane is allready present
+ for ( i = 0 ; i < facet->numBorders ; i++ ) {
+ if (CM_PlaneEqual(&planes[facet->borderPlanes[i]], plane, &flipped)) {
+ break;
+ }
+ }
+
+ if ( i == facet->numBorders ) {
+ if (facet->numBorders > 4 + 6 + 16) Com_Printf("ERROR: too many bevels\n");
+ facet->borderPlanes[facet->numBorders] = CM_FindPlane2(plane, &flipped);
+
+ for ( k = 0 ; k < facet->numBorders ; k++ ) {
+ if (facet->borderPlanes[facet->numBorders] ==
+ facet->borderPlanes[k]) Com_Printf("WARNING: bevel plane already used\n");
+ }
+
+ facet->borderNoAdjust[facet->numBorders] = 0;
+ facet->borderInward[facet->numBorders] = flipped;
+ //
+ w2 = CopyWinding(w);
+ Vector4Copy(planes[facet->borderPlanes[facet->numBorders]].plane, newplane);
+ if (!facet->borderInward[facet->numBorders])
+ {
+ VectorNegate(newplane, newplane);
+ newplane[3] = -newplane[3];
+ } //end if
+ ChopWindingInPlace( &w2, newplane, newplane[3], 0.1f );
+ if (!w2) {
+ Com_DPrintf("WARNING: CM_AddFacetBevels... invalid bevel\n");
+ continue;
+ }
+ else {
+ FreeWinding(w2);
+ }
+ //
+ facet->numBorders++;
+ //already got a bevel
+// break;
+ }
+ }
+ }
+ }
+ FreeWinding( w );
+
+#ifndef BSPC
+ //add opposite plane
+ facet->borderPlanes[facet->numBorders] = facet->surfacePlane;
+ facet->borderNoAdjust[facet->numBorders] = 0;
+ facet->borderInward[facet->numBorders] = qtrue;
+ facet->numBorders++;
+#endif //BSPC
+
+}
+
+typedef enum {
+ EN_TOP,
+ EN_RIGHT,
+ EN_BOTTOM,
+ EN_LEFT
+} edgeName_t;
+
+/*
+==================
+CM_PatchCollideFromGrid
+==================
+*/
+static void CM_PatchCollideFromGrid( cGrid_t *grid, patchCollide_t *pf ) {
+ int i, j;
+ float *p1, *p2, *p3;
+ MAC_STATIC int gridPlanes[MAX_GRID_SIZE][MAX_GRID_SIZE][2];
+ facet_t *facet;
+ int borders[4];
+ int noAdjust[4];
+
+ numPlanes = 0;
+ numFacets = 0;
+
+ // find the planes for each triangle of the grid
+ for ( i = 0 ; i < grid->width - 1 ; i++ ) {
+ for ( j = 0 ; j < grid->height - 1 ; j++ ) {
+ p1 = grid->points[i][j];
+ p2 = grid->points[i+1][j];
+ p3 = grid->points[i+1][j+1];
+ gridPlanes[i][j][0] = CM_FindPlane( p1, p2, p3 );
+
+ p1 = grid->points[i+1][j+1];
+ p2 = grid->points[i][j+1];
+ p3 = grid->points[i][j];
+ gridPlanes[i][j][1] = CM_FindPlane( p1, p2, p3 );
+ }
+ }
+
+ // create the borders for each facet
+ for ( i = 0 ; i < grid->width - 1 ; i++ ) {
+ for ( j = 0 ; j < grid->height - 1 ; j++ ) {
+
+ borders[EN_TOP] = -1;
+ if ( j > 0 ) {
+ borders[EN_TOP] = gridPlanes[i][j-1][1];
+ } else if ( grid->wrapHeight ) {
+ borders[EN_TOP] = gridPlanes[i][grid->height-2][1];
+ }
+ noAdjust[EN_TOP] = ( borders[EN_TOP] == gridPlanes[i][j][0] );
+ if ( borders[EN_TOP] == -1 || noAdjust[EN_TOP] ) {
+ borders[EN_TOP] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 0 );
+ }
+
+ borders[EN_BOTTOM] = -1;
+ if ( j < grid->height - 2 ) {
+ borders[EN_BOTTOM] = gridPlanes[i][j+1][0];
+ } else if ( grid->wrapHeight ) {
+ borders[EN_BOTTOM] = gridPlanes[i][0][0];
+ }
+ noAdjust[EN_BOTTOM] = ( borders[EN_BOTTOM] == gridPlanes[i][j][1] );
+ if ( borders[EN_BOTTOM] == -1 || noAdjust[EN_BOTTOM] ) {
+ borders[EN_BOTTOM] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 2 );
+ }
+
+ borders[EN_LEFT] = -1;
+ if ( i > 0 ) {
+ borders[EN_LEFT] = gridPlanes[i-1][j][0];
+ } else if ( grid->wrapWidth ) {
+ borders[EN_LEFT] = gridPlanes[grid->width-2][j][0];
+ }
+ noAdjust[EN_LEFT] = ( borders[EN_LEFT] == gridPlanes[i][j][1] );
+ if ( borders[EN_LEFT] == -1 || noAdjust[EN_LEFT] ) {
+ borders[EN_LEFT] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 3 );
+ }
+
+ borders[EN_RIGHT] = -1;
+ if ( i < grid->width - 2 ) {
+ borders[EN_RIGHT] = gridPlanes[i+1][j][1];
+ } else if ( grid->wrapWidth ) {
+ borders[EN_RIGHT] = gridPlanes[0][j][1];
+ }
+ noAdjust[EN_RIGHT] = ( borders[EN_RIGHT] == gridPlanes[i][j][0] );
+ if ( borders[EN_RIGHT] == -1 || noAdjust[EN_RIGHT] ) {
+ borders[EN_RIGHT] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 1 );
+ }
+
+ if ( numFacets == MAX_FACETS ) {
+ Com_Error( ERR_DROP, "MAX_FACETS" );
+ }
+ facet = &facets[numFacets];
+ Com_Memset( facet, 0, sizeof( *facet ) );
+
+ if ( gridPlanes[i][j][0] == gridPlanes[i][j][1] ) {
+ if ( gridPlanes[i][j][0] == -1 ) {
+ continue; // degenrate
+ }
+ facet->surfacePlane = gridPlanes[i][j][0];
+ facet->numBorders = 4;
+ facet->borderPlanes[0] = borders[EN_TOP];
+ facet->borderNoAdjust[0] = noAdjust[EN_TOP];
+ facet->borderPlanes[1] = borders[EN_RIGHT];
+ facet->borderNoAdjust[1] = noAdjust[EN_RIGHT];
+ facet->borderPlanes[2] = borders[EN_BOTTOM];
+ facet->borderNoAdjust[2] = noAdjust[EN_BOTTOM];
+ facet->borderPlanes[3] = borders[EN_LEFT];
+ facet->borderNoAdjust[3] = noAdjust[EN_LEFT];
+ CM_SetBorderInward( facet, grid, gridPlanes, i, j, -1 );
+ if ( CM_ValidateFacet( facet ) ) {
+ CM_AddFacetBevels( facet );
+ numFacets++;
+ }
+ } else {
+ // two seperate triangles
+ facet->surfacePlane = gridPlanes[i][j][0];
+ facet->numBorders = 3;
+ facet->borderPlanes[0] = borders[EN_TOP];
+ facet->borderNoAdjust[0] = noAdjust[EN_TOP];
+ facet->borderPlanes[1] = borders[EN_RIGHT];
+ facet->borderNoAdjust[1] = noAdjust[EN_RIGHT];
+ facet->borderPlanes[2] = gridPlanes[i][j][1];
+ if ( facet->borderPlanes[2] == -1 ) {
+ facet->borderPlanes[2] = borders[EN_BOTTOM];
+ if ( facet->borderPlanes[2] == -1 ) {
+ facet->borderPlanes[2] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 4 );
+ }
+ }
+ CM_SetBorderInward( facet, grid, gridPlanes, i, j, 0 );
+ if ( CM_ValidateFacet( facet ) ) {
+ CM_AddFacetBevels( facet );
+ numFacets++;
+ }
+
+ if ( numFacets == MAX_FACETS ) {
+ Com_Error( ERR_DROP, "MAX_FACETS" );
+ }
+ facet = &facets[numFacets];
+ Com_Memset( facet, 0, sizeof( *facet ) );
+
+ facet->surfacePlane = gridPlanes[i][j][1];
+ facet->numBorders = 3;
+ facet->borderPlanes[0] = borders[EN_BOTTOM];
+ facet->borderNoAdjust[0] = noAdjust[EN_BOTTOM];
+ facet->borderPlanes[1] = borders[EN_LEFT];
+ facet->borderNoAdjust[1] = noAdjust[EN_LEFT];
+ facet->borderPlanes[2] = gridPlanes[i][j][0];
+ if ( facet->borderPlanes[2] == -1 ) {
+ facet->borderPlanes[2] = borders[EN_TOP];
+ if ( facet->borderPlanes[2] == -1 ) {
+ facet->borderPlanes[2] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 5 );
+ }
+ }
+ CM_SetBorderInward( facet, grid, gridPlanes, i, j, 1 );
+ if ( CM_ValidateFacet( facet ) ) {
+ CM_AddFacetBevels( facet );
+ numFacets++;
+ }
+ }
+ }
+ }
+
+ // copy the results out
+ pf->numPlanes = numPlanes;
+ pf->numFacets = numFacets;
+ pf->facets = Hunk_Alloc( numFacets * sizeof( *pf->facets ), h_high );
+ Com_Memcpy( pf->facets, facets, numFacets * sizeof( *pf->facets ) );
+ pf->planes = Hunk_Alloc( numPlanes * sizeof( *pf->planes ), h_high );
+ Com_Memcpy( pf->planes, planes, numPlanes * sizeof( *pf->planes ) );
+}
+
+
+/*
+===================
+CM_GeneratePatchCollide
+
+Creates an internal structure that will be used to perform
+collision detection with a patch mesh.
+
+Points is packed as concatenated rows.
+===================
+*/
+struct patchCollide_s *CM_GeneratePatchCollide( int width, int height, vec3_t *points ) {
+ patchCollide_t *pf;
+ MAC_STATIC cGrid_t grid;
+ int i, j;
+
+ if ( width <= 2 || height <= 2 || !points ) {
+ Com_Error( ERR_DROP, "CM_GeneratePatchFacets: bad parameters: (%i, %i, %p)",
+ width, height, points );
+ }
+
+ if ( !(width & 1) || !(height & 1) ) {
+ Com_Error( ERR_DROP, "CM_GeneratePatchFacets: even sizes are invalid for quadratic meshes" );
+ }
+
+ if ( width > MAX_GRID_SIZE || height > MAX_GRID_SIZE ) {
+ Com_Error( ERR_DROP, "CM_GeneratePatchFacets: source is > MAX_GRID_SIZE" );
+ }
+
+ // build a grid
+ grid.width = width;
+ grid.height = height;
+ grid.wrapWidth = qfalse;
+ grid.wrapHeight = qfalse;
+ for ( i = 0 ; i < width ; i++ ) {
+ for ( j = 0 ; j < height ; j++ ) {
+ VectorCopy( points[j*width + i], grid.points[i][j] );
+ }
+ }
+
+ // subdivide the grid
+ CM_SetGridWrapWidth( &grid );
+ CM_SubdivideGridColumns( &grid );
+ CM_RemoveDegenerateColumns( &grid );
+
+ CM_TransposeGrid( &grid );
+
+ CM_SetGridWrapWidth( &grid );
+ CM_SubdivideGridColumns( &grid );
+ CM_RemoveDegenerateColumns( &grid );
+
+ // we now have a grid of points exactly on the curve
+ // the aproximate surface defined by these points will be
+ // collided against
+ pf = Hunk_Alloc( sizeof( *pf ), h_high );
+ ClearBounds( pf->bounds[0], pf->bounds[1] );
+ for ( i = 0 ; i < grid.width ; i++ ) {
+ for ( j = 0 ; j < grid.height ; j++ ) {
+ AddPointToBounds( grid.points[i][j], pf->bounds[0], pf->bounds[1] );
+ }
+ }
+
+ c_totalPatchBlocks += ( grid.width - 1 ) * ( grid.height - 1 );
+
+ // generate a bsp tree for the surface
+ CM_PatchCollideFromGrid( &grid, pf );
+
+ // expand by one unit for epsilon purposes
+ pf->bounds[0][0] -= 1;
+ pf->bounds[0][1] -= 1;
+ pf->bounds[0][2] -= 1;
+
+ pf->bounds[1][0] += 1;
+ pf->bounds[1][1] += 1;
+ pf->bounds[1][2] += 1;
+
+ return pf;
+}
+
+/*
+================================================================================
+
+TRACE TESTING
+
+================================================================================
+*/
+
+/*
+====================
+CM_TracePointThroughPatchCollide
+
+ special case for point traces because the patch collide "brushes" have no volume
+====================
+*/
+void CM_TracePointThroughPatchCollide( traceWork_t *tw, const struct patchCollide_s *pc ) {
+ qboolean frontFacing[MAX_PATCH_PLANES];
+ float intersection[MAX_PATCH_PLANES];
+ float intersect;
+ const patchPlane_t *planes;
+ const facet_t *facet;
+ int i, j, k;
+ float offset;
+ float d1, d2;
+#ifndef BSPC
+ static cvar_t *cv;
+#endif //BSPC
+
+#ifndef BSPC
+ if ( !cm_playerCurveClip->integer || !tw->isPoint ) {
+ return;
+ }
+#endif
+
+ // determine the trace's relationship to all planes
+ planes = pc->planes;
+ for ( i = 0 ; i < pc->numPlanes ; i++, planes++ ) {
+ offset = DotProduct( tw->offsets[ planes->signbits ], planes->plane );
+ d1 = DotProduct( tw->start, planes->plane ) - planes->plane[3] + offset;
+ d2 = DotProduct( tw->end, planes->plane ) - planes->plane[3] + offset;
+ if ( d1 <= 0 ) {
+ frontFacing[i] = qfalse;
+ } else {
+ frontFacing[i] = qtrue;
+ }
+ if ( d1 == d2 ) {
+ intersection[i] = 99999;
+ } else {
+ intersection[i] = d1 / ( d1 - d2 );
+ if ( intersection[i] <= 0 ) {
+ intersection[i] = 99999;
+ }
+ }
+ }
+
+
+ // see if any of the surface planes are intersected
+ facet = pc->facets;
+ for ( i = 0 ; i < pc->numFacets ; i++, facet++ ) {
+ if ( !frontFacing[facet->surfacePlane] ) {
+ continue;
+ }
+ intersect = intersection[facet->surfacePlane];
+ if ( intersect < 0 ) {
+ continue; // surface is behind the starting point
+ }
+ if ( intersect > tw->trace.fraction ) {
+ continue; // already hit something closer
+ }
+ for ( j = 0 ; j < facet->numBorders ; j++ ) {
+ k = facet->borderPlanes[j];
+ if ( frontFacing[k] ^ facet->borderInward[j] ) {
+ if ( intersection[k] > intersect ) {
+ break;
+ }
+ } else {
+ if ( intersection[k] < intersect ) {
+ break;
+ }
+ }
+ }
+ if ( j == facet->numBorders ) {
+ // we hit this facet
+#ifndef BSPC
+ if (!cv) {
+ cv = Cvar_Get( "r_debugSurfaceUpdate", "1", 0 );
+ }
+ if (cv->integer) {
+ debugPatchCollide = pc;
+ debugFacet = facet;
+ }
+#endif //BSPC
+ planes = &pc->planes[facet->surfacePlane];
+
+ // calculate intersection with a slight pushoff
+ offset = DotProduct( tw->offsets[ planes->signbits ], planes->plane );
+ d1 = DotProduct( tw->start, planes->plane ) - planes->plane[3] + offset;
+ d2 = DotProduct( tw->end, planes->plane ) - planes->plane[3] + offset;
+ tw->trace.fraction = ( d1 - SURFACE_CLIP_EPSILON ) / ( d1 - d2 );
+
+ if ( tw->trace.fraction < 0 ) {
+ tw->trace.fraction = 0;
+ }
+
+ VectorCopy( planes->plane, tw->trace.plane.normal );
+ tw->trace.plane.dist = planes->plane[3];
+ }
+ }
+}
+
+/*
+====================
+CM_CheckFacetPlane
+====================
+*/
+int CM_CheckFacetPlane(float *plane, vec3_t start, vec3_t end, float *enterFrac, float *leaveFrac, int *hit) {
+ float d1, d2, f;
+
+ *hit = qfalse;
+
+ d1 = DotProduct( start, plane ) - plane[3];
+ d2 = DotProduct( end, plane ) - plane[3];
+
+ // if completely in front of face, no intersection with the entire facet
+ if (d1 > 0 && ( d2 >= SURFACE_CLIP_EPSILON || d2 >= d1 ) ) {
+ return qfalse;
+ }
+
+ // if it doesn't cross the plane, the plane isn't relevent
+ if (d1 <= 0 && d2 <= 0 ) {
+ return qtrue;
+ }
+
+ // crosses face
+ if (d1 > d2) { // enter
+ f = (d1-SURFACE_CLIP_EPSILON) / (d1-d2);
+ if ( f < 0 ) {
+ f = 0;
+ }
+ //always favor previous plane hits and thus also the surface plane hit
+ if (f > *enterFrac) {
+ *enterFrac = f;
+ *hit = qtrue;
+ }
+ } else { // leave
+ f = (d1+SURFACE_CLIP_EPSILON) / (d1-d2);
+ if ( f > 1 ) {
+ f = 1;
+ }
+ if (f < *leaveFrac) {
+ *leaveFrac = f;
+ }
+ }
+ return qtrue;
+}
+
+/*
+====================
+CM_TraceThroughPatchCollide
+====================
+*/
+void CM_TraceThroughPatchCollide( traceWork_t *tw, const struct patchCollide_s *pc ) {
+ int i, j, hit, hitnum;
+ float offset, enterFrac, leaveFrac, t;
+ patchPlane_t *planes;
+ facet_t *facet;
+ float plane[4], bestplane[4];
+ vec3_t startp, endp;
+#ifndef BSPC
+ static cvar_t *cv;
+#endif //BSPC
+
+ if (tw->isPoint) {
+ CM_TracePointThroughPatchCollide( tw, pc );
+ return;
+ }
+
+ facet = pc->facets;
+ for ( i = 0 ; i < pc->numFacets ; i++, facet++ ) {
+ enterFrac = -1.0;
+ leaveFrac = 1.0;
+ hitnum = -1;
+ //
+ planes = &pc->planes[ facet->surfacePlane ];
+ VectorCopy(planes->plane, plane);
+ plane[3] = planes->plane[3];
+ if ( tw->sphere.use ) {
+ // adjust the plane distance apropriately for radius
+ plane[3] += tw->sphere.radius;
+
+ // find the closest point on the capsule to the plane
+ t = DotProduct( plane, tw->sphere.offset );
+ if ( t > 0.0f ) {
+ VectorSubtract( tw->start, tw->sphere.offset, startp );
+ VectorSubtract( tw->end, tw->sphere.offset, endp );
+ }
+ else {
+ VectorAdd( tw->start, tw->sphere.offset, startp );
+ VectorAdd( tw->end, tw->sphere.offset, endp );
+ }
+ }
+ else {
+ offset = DotProduct( tw->offsets[ planes->signbits ], plane);
+ plane[3] -= offset;
+ VectorCopy( tw->start, startp );
+ VectorCopy( tw->end, endp );
+ }
+
+ if (!CM_CheckFacetPlane(plane, startp, endp, &enterFrac, &leaveFrac, &hit)) {
+ continue;
+ }
+ if (hit) {
+ Vector4Copy(plane, bestplane);
+ }
+
+ for ( j = 0; j < facet->numBorders; j++ ) {
+ planes = &pc->planes[ facet->borderPlanes[j] ];
+ if (facet->borderInward[j]) {
+ VectorNegate(planes->plane, plane);
+ plane[3] = -planes->plane[3];
+ }
+ else {
+ VectorCopy(planes->plane, plane);
+ plane[3] = planes->plane[3];
+ }
+ if ( tw->sphere.use ) {
+ // adjust the plane distance apropriately for radius
+ plane[3] += tw->sphere.radius;
+
+ // find the closest point on the capsule to the plane
+ t = DotProduct( plane, tw->sphere.offset );
+ if ( t > 0.0f ) {
+ VectorSubtract( tw->start, tw->sphere.offset, startp );
+ VectorSubtract( tw->end, tw->sphere.offset, endp );
+ }
+ else {
+ VectorAdd( tw->start, tw->sphere.offset, startp );
+ VectorAdd( tw->end, tw->sphere.offset, endp );
+ }
+ }
+ else {
+ // NOTE: this works even though the plane might be flipped because the bbox is centered
+ offset = DotProduct( tw->offsets[ planes->signbits ], plane);
+ plane[3] += fabs(offset);
+ VectorCopy( tw->start, startp );
+ VectorCopy( tw->end, endp );
+ }
+
+ if (!CM_CheckFacetPlane(plane, startp, endp, &enterFrac, &leaveFrac, &hit)) {
+ break;
+ }
+ if (hit) {
+ hitnum = j;
+ Vector4Copy(plane, bestplane);
+ }
+ }
+ if (j < facet->numBorders) continue;
+ //never clip against the back side
+ if (hitnum == facet->numBorders - 1) continue;
+
+ if (enterFrac < leaveFrac && enterFrac >= 0) {
+ if (enterFrac < tw->trace.fraction) {
+ if (enterFrac < 0) {
+ enterFrac = 0;
+ }
+#ifndef BSPC
+ if (!cv) {
+ cv = Cvar_Get( "r_debugSurfaceUpdate", "1", 0 );
+ }
+ if (cv && cv->integer) {
+ debugPatchCollide = pc;
+ debugFacet = facet;
+ }
+#endif //BSPC
+
+ tw->trace.fraction = enterFrac;
+ VectorCopy( bestplane, tw->trace.plane.normal );
+ tw->trace.plane.dist = bestplane[3];
+ }
+ }
+ }
+}
+
+
+/*
+=======================================================================
+
+POSITION TEST
+
+=======================================================================
+*/
+
+/*
+====================
+CM_PositionTestInPatchCollide
+====================
+*/
+qboolean CM_PositionTestInPatchCollide( traceWork_t *tw, const struct patchCollide_s *pc ) {
+ int i, j;
+ float offset, t;
+ patchPlane_t *planes;
+ facet_t *facet;
+ float plane[4];
+ vec3_t startp;
+
+ if (tw->isPoint) {
+ return qfalse;
+ }
+ //
+ facet = pc->facets;
+ for ( i = 0 ; i < pc->numFacets ; i++, facet++ ) {
+ planes = &pc->planes[ facet->surfacePlane ];
+ VectorCopy(planes->plane, plane);
+ plane[3] = planes->plane[3];
+ if ( tw->sphere.use ) {
+ // adjust the plane distance apropriately for radius
+ plane[3] += tw->sphere.radius;
+
+ // find the closest point on the capsule to the plane
+ t = DotProduct( plane, tw->sphere.offset );
+ if ( t > 0 ) {
+ VectorSubtract( tw->start, tw->sphere.offset, startp );
+ }
+ else {
+ VectorAdd( tw->start, tw->sphere.offset, startp );
+ }
+ }
+ else {
+ offset = DotProduct( tw->offsets[ planes->signbits ], plane);
+ plane[3] -= offset;
+ VectorCopy( tw->start, startp );
+ }
+
+ if ( DotProduct( plane, startp ) - plane[3] > 0.0f ) {
+ continue;
+ }
+
+ for ( j = 0; j < facet->numBorders; j++ ) {
+ planes = &pc->planes[ facet->borderPlanes[j] ];
+ if (facet->borderInward[j]) {
+ VectorNegate(planes->plane, plane);
+ plane[3] = -planes->plane[3];
+ }
+ else {
+ VectorCopy(planes->plane, plane);
+ plane[3] = planes->plane[3];
+ }
+ if ( tw->sphere.use ) {
+ // adjust the plane distance apropriately for radius
+ plane[3] += tw->sphere.radius;
+
+ // find the closest point on the capsule to the plane
+ t = DotProduct( plane, tw->sphere.offset );
+ if ( t > 0.0f ) {
+ VectorSubtract( tw->start, tw->sphere.offset, startp );
+ }
+ else {
+ VectorAdd( tw->start, tw->sphere.offset, startp );
+ }
+ }
+ else {
+ // NOTE: this works even though the plane might be flipped because the bbox is centered
+ offset = DotProduct( tw->offsets[ planes->signbits ], plane);
+ plane[3] += fabs(offset);
+ VectorCopy( tw->start, startp );
+ }
+
+ if ( DotProduct( plane, startp ) - plane[3] > 0.0f ) {
+ break;
+ }
+ }
+ if (j < facet->numBorders) {
+ continue;
+ }
+ // inside this patch facet
+ return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+=======================================================================
+
+DEBUGGING
+
+=======================================================================
+*/
+
+
+/*
+==================
+CM_DrawDebugSurface
+
+Called from the renderer
+==================
+*/
+#ifndef BSPC
+void BotDrawDebugPolygons(void (*drawPoly)(int color, int numPoints, float *points), int value);
+#endif
+
+void CM_DrawDebugSurface( void (*drawPoly)(int color, int numPoints, float *points) ) {
+ static cvar_t *cv;
+#ifndef BSPC
+ static cvar_t *cv2;
+#endif
+ const patchCollide_t *pc;
+ facet_t *facet;
+ winding_t *w;
+ int i, j, k, n;
+ int curplanenum, planenum, curinward, inward;
+ float plane[4];
+ vec3_t mins = {-15, -15, -28}, maxs = {15, 15, 28};
+ //vec3_t mins = {0, 0, 0}, maxs = {0, 0, 0};
+ vec3_t v1, v2;
+
+#ifndef BSPC
+ if ( !cv2 )
+ {
+ cv2 = Cvar_Get( "r_debugSurface", "0", 0 );
+ }
+
+ if (cv2->integer != 1)
+ {
+ BotDrawDebugPolygons(drawPoly, cv2->integer);
+ return;
+ }
+#endif
+
+ if ( !debugPatchCollide ) {
+ return;
+ }
+
+#ifndef BSPC
+ if ( !cv ) {
+ cv = Cvar_Get( "cm_debugSize", "2", 0 );
+ }
+#endif
+ pc = debugPatchCollide;
+
+ for ( i = 0, facet = pc->facets ; i < pc->numFacets ; i++, facet++ ) {
+
+ for ( k = 0 ; k < facet->numBorders + 1; k++ ) {
+ //
+ if (k < facet->numBorders) {
+ planenum = facet->borderPlanes[k];
+ inward = facet->borderInward[k];
+ }
+ else {
+ planenum = facet->surfacePlane;
+ inward = qfalse;
+ //continue;
+ }
+
+ Vector4Copy( pc->planes[ planenum ].plane, plane );
+
+ //planenum = facet->surfacePlane;
+ if ( inward ) {
+ VectorSubtract( vec3_origin, plane, plane );
+ plane[3] = -plane[3];
+ }
+
+ plane[3] += cv->value;
+ //*
+ for (n = 0; n < 3; n++)
+ {
+ if (plane[n] > 0) v1[n] = maxs[n];
+ else v1[n] = mins[n];
+ } //end for
+ VectorNegate(plane, v2);
+ plane[3] += fabs(DotProduct(v1, v2));
+ //*/
+
+ w = BaseWindingForPlane( plane, plane[3] );
+ for ( j = 0 ; j < facet->numBorders + 1 && w; j++ ) {
+ //
+ if (j < facet->numBorders) {
+ curplanenum = facet->borderPlanes[j];
+ curinward = facet->borderInward[j];
+ }
+ else {
+ curplanenum = facet->surfacePlane;
+ curinward = qfalse;
+ //continue;
+ }
+ //
+ if (curplanenum == planenum) continue;
+
+ Vector4Copy( pc->planes[ curplanenum ].plane, plane );
+ if ( !curinward ) {
+ VectorSubtract( vec3_origin, plane, plane );
+ plane[3] = -plane[3];
+ }
+ // if ( !facet->borderNoAdjust[j] ) {
+ plane[3] -= cv->value;
+ // }
+ for (n = 0; n < 3; n++)
+ {
+ if (plane[n] > 0) v1[n] = maxs[n];
+ else v1[n] = mins[n];
+ } //end for
+ VectorNegate(plane, v2);
+ plane[3] -= fabs(DotProduct(v1, v2));
+
+ ChopWindingInPlace( &w, plane, plane[3], 0.1f );
+ }
+ if ( w ) {
+ if ( facet == debugFacet ) {
+ drawPoly( 4, w->numpoints, w->p[0] );
+ //Com_Printf("blue facet has %d border planes\n", facet->numBorders);
+ } else {
+ drawPoly( 1, w->numpoints, w->p[0] );
+ }
+ FreeWinding( w );
+ }
+ else
+ Com_Printf("winding chopped away by border planes\n");
+ }
+ }
+
+ // draw the debug block
+ {
+ vec3_t v[3];
+
+ VectorCopy( debugBlockPoints[0], v[0] );
+ VectorCopy( debugBlockPoints[1], v[1] );
+ VectorCopy( debugBlockPoints[2], v[2] );
+ drawPoly( 2, 3, v[0] );
+
+ VectorCopy( debugBlockPoints[2], v[0] );
+ VectorCopy( debugBlockPoints[3], v[1] );
+ VectorCopy( debugBlockPoints[0], v[2] );
+ drawPoly( 2, 3, v[0] );
+ }
+
+#if 0
+ vec3_t v[4];
+
+ v[0][0] = pc->bounds[1][0];
+ v[0][1] = pc->bounds[1][1];
+ v[0][2] = pc->bounds[1][2];
+
+ v[1][0] = pc->bounds[1][0];
+ v[1][1] = pc->bounds[0][1];
+ v[1][2] = pc->bounds[1][2];
+
+ v[2][0] = pc->bounds[0][0];
+ v[2][1] = pc->bounds[0][1];
+ v[2][2] = pc->bounds[1][2];
+
+ v[3][0] = pc->bounds[0][0];
+ v[3][1] = pc->bounds[1][1];
+ v[3][2] = pc->bounds[1][2];
+
+ drawPoly( 4, v[0] );
+#endif
+}
diff --git a/code/qcommon/cm_patch.h b/code/qcommon/cm_patch.h
new file mode 100755
index 0000000..637bf3f
--- /dev/null
+++ b/code/qcommon/cm_patch.h
@@ -0,0 +1,103 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+//#define CULL_BBOX
+
+/*
+
+This file does not reference any globals, and has these entry points:
+
+void CM_ClearLevelPatches( void );
+struct patchCollide_s *CM_GeneratePatchCollide( int width, int height, const vec3_t *points );
+void CM_TraceThroughPatchCollide( traceWork_t *tw, const struct patchCollide_s *pc );
+qboolean CM_PositionTestInPatchCollide( traceWork_t *tw, const struct patchCollide_s *pc );
+void CM_DrawDebugSurface( void (*drawPoly)(int color, int numPoints, flaot *points) );
+
+
+Issues for collision against curved surfaces:
+
+Surface edges need to be handled differently than surface planes
+
+Plane expansion causes raw surfaces to expand past expanded bounding box
+
+Position test of a volume against a surface is tricky.
+
+Position test of a point against a surface is not well defined, because the surface has no volume.
+
+
+Tracing leading edge points instead of volumes?
+Position test by tracing corner to corner? (8*7 traces -- ouch)
+
+coplanar edges
+triangulated patches
+degenerate patches
+
+ endcaps
+ degenerate
+
+WARNING: this may misbehave with meshes that have rows or columns that only
+degenerate a few triangles. Completely degenerate rows and columns are handled
+properly.
+*/
+
+
+#define MAX_FACETS 1024
+#define MAX_PATCH_PLANES 2048
+
+typedef struct {
+ float plane[4];
+ int signbits; // signx + (signy<<1) + (signz<<2), used as lookup during collision
+} patchPlane_t;
+
+typedef struct {
+ int surfacePlane;
+ int numBorders; // 3 or four + 6 axial bevels + 4 or 3 * 4 edge bevels
+ int borderPlanes[4+6+16];
+ int borderInward[4+6+16];
+ qboolean borderNoAdjust[4+6+16];
+} facet_t;
+
+typedef struct patchCollide_s {
+ vec3_t bounds[2];
+ int numPlanes; // surface planes plus edge planes
+ patchPlane_t *planes;
+ int numFacets;
+ facet_t *facets;
+} patchCollide_t;
+
+
+#define MAX_GRID_SIZE 129
+
+typedef struct {
+ int width;
+ int height;
+ qboolean wrapWidth;
+ qboolean wrapHeight;
+ vec3_t points[MAX_GRID_SIZE][MAX_GRID_SIZE]; // [width][height]
+} cGrid_t;
+
+#define SUBDIVIDE_DISTANCE 16 //4 // never more than this units away from curve
+#define PLANE_TRI_EPSILON 0.1
+#define WRAP_POINT_EPSILON 0.1
+
+
+struct patchCollide_s *CM_GeneratePatchCollide( int width, int height, vec3_t *points );
diff --git a/code/qcommon/cm_polylib.c b/code/qcommon/cm_polylib.c
new file mode 100755
index 0000000..5dc9e1c
--- /dev/null
+++ b/code/qcommon/cm_polylib.c
@@ -0,0 +1,737 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+// this is only used for visualization tools in cm_ debug functions
+
+
+#include "cm_local.h"
+
+
+// counters are only bumped when running single threaded,
+// because they are an awefull coherence problem
+int c_active_windings;
+int c_peak_windings;
+int c_winding_allocs;
+int c_winding_points;
+
+void pw(winding_t *w)
+{
+ int i;
+ for (i=0 ; i<w->numpoints ; i++)
+ printf ("(%5.1f, %5.1f, %5.1f)\n",w->p[i][0], w->p[i][1],w->p[i][2]);
+}
+
+
+/*
+=============
+AllocWinding
+=============
+*/
+winding_t *AllocWinding (int points)
+{
+ winding_t *w;
+ int s;
+
+ c_winding_allocs++;
+ c_winding_points += points;
+ c_active_windings++;
+ if (c_active_windings > c_peak_windings)
+ c_peak_windings = c_active_windings;
+
+ s = sizeof(vec_t)*3*points + sizeof(int);
+ w = Z_Malloc (s);
+ Com_Memset (w, 0, s);
+ return w;
+}
+
+void FreeWinding (winding_t *w)
+{
+ if (*(unsigned *)w == 0xdeaddead)
+ Com_Error (ERR_FATAL, "FreeWinding: freed a freed winding");
+ *(unsigned *)w = 0xdeaddead;
+
+ c_active_windings--;
+ Z_Free (w);
+}
+
+/*
+============
+RemoveColinearPoints
+============
+*/
+int c_removed;
+
+void RemoveColinearPoints (winding_t *w)
+{
+ int i, j, k;
+ vec3_t v1, v2;
+ int nump;
+ vec3_t p[MAX_POINTS_ON_WINDING];
+
+ nump = 0;
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ j = (i+1)%w->numpoints;
+ k = (i+w->numpoints-1)%w->numpoints;
+ VectorSubtract (w->p[j], w->p[i], v1);
+ VectorSubtract (w->p[i], w->p[k], v2);
+ VectorNormalize2(v1,v1);
+ VectorNormalize2(v2,v2);
+ if (DotProduct(v1, v2) < 0.999)
+ {
+ VectorCopy (w->p[i], p[nump]);
+ nump++;
+ }
+ }
+
+ if (nump == w->numpoints)
+ return;
+
+ c_removed += w->numpoints - nump;
+ w->numpoints = nump;
+ Com_Memcpy (w->p, p, nump*sizeof(p[0]));
+}
+
+/*
+============
+WindingPlane
+============
+*/
+void WindingPlane (winding_t *w, vec3_t normal, vec_t *dist)
+{
+ vec3_t v1, v2;
+
+ VectorSubtract (w->p[1], w->p[0], v1);
+ VectorSubtract (w->p[2], w->p[0], v2);
+ CrossProduct (v2, v1, normal);
+ VectorNormalize2(normal, normal);
+ *dist = DotProduct (w->p[0], normal);
+
+}
+
+/*
+=============
+WindingArea
+=============
+*/
+vec_t WindingArea (winding_t *w)
+{
+ int i;
+ vec3_t d1, d2, cross;
+ vec_t total;
+
+ total = 0;
+ for (i=2 ; i<w->numpoints ; i++)
+ {
+ VectorSubtract (w->p[i-1], w->p[0], d1);
+ VectorSubtract (w->p[i], w->p[0], d2);
+ CrossProduct (d1, d2, cross);
+ total += 0.5 * VectorLength ( cross );
+ }
+ return total;
+}
+
+/*
+=============
+WindingBounds
+=============
+*/
+void WindingBounds (winding_t *w, vec3_t mins, vec3_t maxs)
+{
+ vec_t v;
+ int i,j;
+
+ mins[0] = mins[1] = mins[2] = MAX_MAP_BOUNDS;
+ maxs[0] = maxs[1] = maxs[2] = -MAX_MAP_BOUNDS;
+
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ for (j=0 ; j<3 ; j++)
+ {
+ v = w->p[i][j];
+ if (v < mins[j])
+ mins[j] = v;
+ if (v > maxs[j])
+ maxs[j] = v;
+ }
+ }
+}
+
+/*
+=============
+WindingCenter
+=============
+*/
+void WindingCenter (winding_t *w, vec3_t center)
+{
+ int i;
+ float scale;
+
+ VectorCopy (vec3_origin, center);
+ for (i=0 ; i<w->numpoints ; i++)
+ VectorAdd (w->p[i], center, center);
+
+ scale = 1.0/w->numpoints;
+ VectorScale (center, scale, center);
+}
+
+/*
+=================
+BaseWindingForPlane
+=================
+*/
+winding_t *BaseWindingForPlane (vec3_t normal, vec_t dist)
+{
+ int i, x;
+ vec_t max, v;
+ vec3_t org, vright, vup;
+ winding_t *w;
+
+// find the major axis
+
+ max = -MAX_MAP_BOUNDS;
+ x = -1;
+ for (i=0 ; i<3; i++)
+ {
+ v = fabs(normal[i]);
+ if (v > max)
+ {
+ x = i;
+ max = v;
+ }
+ }
+ if (x==-1)
+ Com_Error (ERR_DROP, "BaseWindingForPlane: no axis found");
+
+ VectorCopy (vec3_origin, vup);
+ switch (x)
+ {
+ case 0:
+ case 1:
+ vup[2] = 1;
+ break;
+ case 2:
+ vup[0] = 1;
+ break;
+ }
+
+ v = DotProduct (vup, normal);
+ VectorMA (vup, -v, normal, vup);
+ VectorNormalize2(vup, vup);
+
+ VectorScale (normal, dist, org);
+
+ CrossProduct (vup, normal, vright);
+
+ VectorScale (vup, MAX_MAP_BOUNDS, vup);
+ VectorScale (vright, MAX_MAP_BOUNDS, vright);
+
+// project a really big axis aligned box onto the plane
+ w = AllocWinding (4);
+
+ VectorSubtract (org, vright, w->p[0]);
+ VectorAdd (w->p[0], vup, w->p[0]);
+
+ VectorAdd (org, vright, w->p[1]);
+ VectorAdd (w->p[1], vup, w->p[1]);
+
+ VectorAdd (org, vright, w->p[2]);
+ VectorSubtract (w->p[2], vup, w->p[2]);
+
+ VectorSubtract (org, vright, w->p[3]);
+ VectorSubtract (w->p[3], vup, w->p[3]);
+
+ w->numpoints = 4;
+
+ return w;
+}
+
+/*
+==================
+CopyWinding
+==================
+*/
+winding_t *CopyWinding (winding_t *w)
+{
+ int size;
+ winding_t *c;
+
+ c = AllocWinding (w->numpoints);
+ size = (int)((winding_t *)0)->p[w->numpoints];
+ Com_Memcpy (c, w, size);
+ return c;
+}
+
+/*
+==================
+ReverseWinding
+==================
+*/
+winding_t *ReverseWinding (winding_t *w)
+{
+ int i;
+ winding_t *c;
+
+ c = AllocWinding (w->numpoints);
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ VectorCopy (w->p[w->numpoints-1-i], c->p[i]);
+ }
+ c->numpoints = w->numpoints;
+ return c;
+}
+
+
+/*
+=============
+ClipWindingEpsilon
+=============
+*/
+void ClipWindingEpsilon (winding_t *in, vec3_t normal, vec_t dist,
+ vec_t epsilon, winding_t **front, winding_t **back)
+{
+ vec_t dists[MAX_POINTS_ON_WINDING+4];
+ int sides[MAX_POINTS_ON_WINDING+4];
+ int counts[3];
+ static vec_t dot; // VC 4.2 optimizer bug if not static
+ int i, j;
+ vec_t *p1, *p2;
+ vec3_t mid;
+ winding_t *f, *b;
+ int maxpts;
+
+ counts[0] = counts[1] = counts[2] = 0;
+
+// determine sides for each point
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ dot = DotProduct (in->p[i], normal);
+ dot -= dist;
+ dists[i] = dot;
+ if (dot > epsilon)
+ sides[i] = SIDE_FRONT;
+ else if (dot < -epsilon)
+ sides[i] = SIDE_BACK;
+ else
+ {
+ sides[i] = SIDE_ON;
+ }
+ counts[sides[i]]++;
+ }
+ sides[i] = sides[0];
+ dists[i] = dists[0];
+
+ *front = *back = NULL;
+
+ if (!counts[0])
+ {
+ *back = CopyWinding (in);
+ return;
+ }
+ if (!counts[1])
+ {
+ *front = CopyWinding (in);
+ return;
+ }
+
+ maxpts = in->numpoints+4; // cant use counts[0]+2 because
+ // of fp grouping errors
+
+ *front = f = AllocWinding (maxpts);
+ *back = b = AllocWinding (maxpts);
+
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ p1 = in->p[i];
+
+ if (sides[i] == SIDE_ON)
+ {
+ VectorCopy (p1, f->p[f->numpoints]);
+ f->numpoints++;
+ VectorCopy (p1, b->p[b->numpoints]);
+ b->numpoints++;
+ continue;
+ }
+
+ if (sides[i] == SIDE_FRONT)
+ {
+ VectorCopy (p1, f->p[f->numpoints]);
+ f->numpoints++;
+ }
+ if (sides[i] == SIDE_BACK)
+ {
+ VectorCopy (p1, b->p[b->numpoints]);
+ b->numpoints++;
+ }
+
+ if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i])
+ continue;
+
+ // generate a split point
+ p2 = in->p[(i+1)%in->numpoints];
+
+ dot = dists[i] / (dists[i]-dists[i+1]);
+ for (j=0 ; j<3 ; j++)
+ { // avoid round off error when possible
+ if (normal[j] == 1)
+ mid[j] = dist;
+ else if (normal[j] == -1)
+ mid[j] = -dist;
+ else
+ mid[j] = p1[j] + dot*(p2[j]-p1[j]);
+ }
+
+ VectorCopy (mid, f->p[f->numpoints]);
+ f->numpoints++;
+ VectorCopy (mid, b->p[b->numpoints]);
+ b->numpoints++;
+ }
+
+ if (f->numpoints > maxpts || b->numpoints > maxpts)
+ Com_Error (ERR_DROP, "ClipWinding: points exceeded estimate");
+ if (f->numpoints > MAX_POINTS_ON_WINDING || b->numpoints > MAX_POINTS_ON_WINDING)
+ Com_Error (ERR_DROP, "ClipWinding: MAX_POINTS_ON_WINDING");
+}
+
+
+/*
+=============
+ChopWindingInPlace
+=============
+*/
+void ChopWindingInPlace (winding_t **inout, vec3_t normal, vec_t dist, vec_t epsilon)
+{
+ winding_t *in;
+ vec_t dists[MAX_POINTS_ON_WINDING+4];
+ int sides[MAX_POINTS_ON_WINDING+4];
+ int counts[3];
+ static vec_t dot; // VC 4.2 optimizer bug if not static
+ int i, j;
+ vec_t *p1, *p2;
+ vec3_t mid;
+ winding_t *f;
+ int maxpts;
+
+ in = *inout;
+ counts[0] = counts[1] = counts[2] = 0;
+
+// determine sides for each point
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ dot = DotProduct (in->p[i], normal);
+ dot -= dist;
+ dists[i] = dot;
+ if (dot > epsilon)
+ sides[i] = SIDE_FRONT;
+ else if (dot < -epsilon)
+ sides[i] = SIDE_BACK;
+ else
+ {
+ sides[i] = SIDE_ON;
+ }
+ counts[sides[i]]++;
+ }
+ sides[i] = sides[0];
+ dists[i] = dists[0];
+
+ if (!counts[0])
+ {
+ FreeWinding (in);
+ *inout = NULL;
+ return;
+ }
+ if (!counts[1])
+ return; // inout stays the same
+
+ maxpts = in->numpoints+4; // cant use counts[0]+2 because
+ // of fp grouping errors
+
+ f = AllocWinding (maxpts);
+
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ p1 = in->p[i];
+
+ if (sides[i] == SIDE_ON)
+ {
+ VectorCopy (p1, f->p[f->numpoints]);
+ f->numpoints++;
+ continue;
+ }
+
+ if (sides[i] == SIDE_FRONT)
+ {
+ VectorCopy (p1, f->p[f->numpoints]);
+ f->numpoints++;
+ }
+
+ if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i])
+ continue;
+
+ // generate a split point
+ p2 = in->p[(i+1)%in->numpoints];
+
+ dot = dists[i] / (dists[i]-dists[i+1]);
+ for (j=0 ; j<3 ; j++)
+ { // avoid round off error when possible
+ if (normal[j] == 1)
+ mid[j] = dist;
+ else if (normal[j] == -1)
+ mid[j] = -dist;
+ else
+ mid[j] = p1[j] + dot*(p2[j]-p1[j]);
+ }
+
+ VectorCopy (mid, f->p[f->numpoints]);
+ f->numpoints++;
+ }
+
+ if (f->numpoints > maxpts)
+ Com_Error (ERR_DROP, "ClipWinding: points exceeded estimate");
+ if (f->numpoints > MAX_POINTS_ON_WINDING)
+ Com_Error (ERR_DROP, "ClipWinding: MAX_POINTS_ON_WINDING");
+
+ FreeWinding (in);
+ *inout = f;
+}
+
+
+/*
+=================
+ChopWinding
+
+Returns the fragment of in that is on the front side
+of the cliping plane. The original is freed.
+=================
+*/
+winding_t *ChopWinding (winding_t *in, vec3_t normal, vec_t dist)
+{
+ winding_t *f, *b;
+
+ ClipWindingEpsilon (in, normal, dist, ON_EPSILON, &f, &b);
+ FreeWinding (in);
+ if (b)
+ FreeWinding (b);
+ return f;
+}
+
+
+/*
+=================
+CheckWinding
+
+=================
+*/
+void CheckWinding (winding_t *w)
+{
+ int i, j;
+ vec_t *p1, *p2;
+ vec_t d, edgedist;
+ vec3_t dir, edgenormal, facenormal;
+ vec_t area;
+ vec_t facedist;
+
+ if (w->numpoints < 3)
+ Com_Error (ERR_DROP, "CheckWinding: %i points",w->numpoints);
+
+ area = WindingArea(w);
+ if (area < 1)
+ Com_Error (ERR_DROP, "CheckWinding: %f area", area);
+
+ WindingPlane (w, facenormal, &facedist);
+
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ p1 = w->p[i];
+
+ for (j=0 ; j<3 ; j++)
+ if (p1[j] > MAX_MAP_BOUNDS || p1[j] < -MAX_MAP_BOUNDS)
+ Com_Error (ERR_DROP, "CheckFace: BUGUS_RANGE: %f",p1[j]);
+
+ j = i+1 == w->numpoints ? 0 : i+1;
+
+ // check the point is on the face plane
+ d = DotProduct (p1, facenormal) - facedist;
+ if (d < -ON_EPSILON || d > ON_EPSILON)
+ Com_Error (ERR_DROP, "CheckWinding: point off plane");
+
+ // check the edge isnt degenerate
+ p2 = w->p[j];
+ VectorSubtract (p2, p1, dir);
+
+ if (VectorLength (dir) < ON_EPSILON)
+ Com_Error (ERR_DROP, "CheckWinding: degenerate edge");
+
+ CrossProduct (facenormal, dir, edgenormal);
+ VectorNormalize2 (edgenormal, edgenormal);
+ edgedist = DotProduct (p1, edgenormal);
+ edgedist += ON_EPSILON;
+
+ // all other points must be on front side
+ for (j=0 ; j<w->numpoints ; j++)
+ {
+ if (j == i)
+ continue;
+ d = DotProduct (w->p[j], edgenormal);
+ if (d > edgedist)
+ Com_Error (ERR_DROP, "CheckWinding: non-convex");
+ }
+ }
+}
+
+
+/*
+============
+WindingOnPlaneSide
+============
+*/
+int WindingOnPlaneSide (winding_t *w, vec3_t normal, vec_t dist)
+{
+ qboolean front, back;
+ int i;
+ vec_t d;
+
+ front = qfalse;
+ back = qfalse;
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ d = DotProduct (w->p[i], normal) - dist;
+ if (d < -ON_EPSILON)
+ {
+ if (front)
+ return SIDE_CROSS;
+ back = qtrue;
+ continue;
+ }
+ if (d > ON_EPSILON)
+ {
+ if (back)
+ return SIDE_CROSS;
+ front = qtrue;
+ continue;
+ }
+ }
+
+ if (back)
+ return SIDE_BACK;
+ if (front)
+ return SIDE_FRONT;
+ return SIDE_ON;
+}
+
+
+/*
+=================
+AddWindingToConvexHull
+
+Both w and *hull are on the same plane
+=================
+*/
+#define MAX_HULL_POINTS 128
+void AddWindingToConvexHull( winding_t *w, winding_t **hull, vec3_t normal ) {
+ int i, j, k;
+ float *p, *copy;
+ vec3_t dir;
+ float d;
+ int numHullPoints, numNew;
+ vec3_t hullPoints[MAX_HULL_POINTS];
+ vec3_t newHullPoints[MAX_HULL_POINTS];
+ vec3_t hullDirs[MAX_HULL_POINTS];
+ qboolean hullSide[MAX_HULL_POINTS];
+ qboolean outside;
+
+ if ( !*hull ) {
+ *hull = CopyWinding( w );
+ return;
+ }
+
+ numHullPoints = (*hull)->numpoints;
+ Com_Memcpy( hullPoints, (*hull)->p, numHullPoints * sizeof(vec3_t) );
+
+ for ( i = 0 ; i < w->numpoints ; i++ ) {
+ p = w->p[i];
+
+ // calculate hull side vectors
+ for ( j = 0 ; j < numHullPoints ; j++ ) {
+ k = ( j + 1 ) % numHullPoints;
+
+ VectorSubtract( hullPoints[k], hullPoints[j], dir );
+ VectorNormalize2( dir, dir );
+ CrossProduct( normal, dir, hullDirs[j] );
+ }
+
+ outside = qfalse;
+ for ( j = 0 ; j < numHullPoints ; j++ ) {
+ VectorSubtract( p, hullPoints[j], dir );
+ d = DotProduct( dir, hullDirs[j] );
+ if ( d >= ON_EPSILON ) {
+ outside = qtrue;
+ }
+ if ( d >= -ON_EPSILON ) {
+ hullSide[j] = qtrue;
+ } else {
+ hullSide[j] = qfalse;
+ }
+ }
+
+ // if the point is effectively inside, do nothing
+ if ( !outside ) {
+ continue;
+ }
+
+ // find the back side to front side transition
+ for ( j = 0 ; j < numHullPoints ; j++ ) {
+ if ( !hullSide[ j % numHullPoints ] && hullSide[ (j + 1) % numHullPoints ] ) {
+ break;
+ }
+ }
+ if ( j == numHullPoints ) {
+ continue;
+ }
+
+ // insert the point here
+ VectorCopy( p, newHullPoints[0] );
+ numNew = 1;
+
+ // copy over all points that aren't double fronts
+ j = (j+1)%numHullPoints;
+ for ( k = 0 ; k < numHullPoints ; k++ ) {
+ if ( hullSide[ (j+k) % numHullPoints ] && hullSide[ (j+k+1) % numHullPoints ] ) {
+ continue;
+ }
+ copy = hullPoints[ (j+k+1) % numHullPoints ];
+ VectorCopy( copy, newHullPoints[numNew] );
+ numNew++;
+ }
+
+ numHullPoints = numNew;
+ Com_Memcpy( hullPoints, newHullPoints, numHullPoints * sizeof(vec3_t) );
+ }
+
+ FreeWinding( *hull );
+ w = AllocWinding( numHullPoints );
+ w->numpoints = numHullPoints;
+ *hull = w;
+ Com_Memcpy( w->p, hullPoints, numHullPoints * sizeof(vec3_t) );
+}
+
+
diff --git a/code/qcommon/cm_polylib.h b/code/qcommon/cm_polylib.h
new file mode 100755
index 0000000..cef7997
--- /dev/null
+++ b/code/qcommon/cm_polylib.h
@@ -0,0 +1,68 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+// this is only used for visualization tools in cm_ debug functions
+
+typedef struct
+{
+ int numpoints;
+ vec3_t p[4]; // variable sized
+} winding_t;
+
+#define MAX_POINTS_ON_WINDING 64
+
+#define SIDE_FRONT 0
+#define SIDE_BACK 1
+#define SIDE_ON 2
+#define SIDE_CROSS 3
+
+#define CLIP_EPSILON 0.1f
+
+#define MAX_MAP_BOUNDS 65535
+
+// you can define on_epsilon in the makefile as tighter
+#ifndef ON_EPSILON
+#define ON_EPSILON 0.1f
+#endif
+
+winding_t *AllocWinding (int points);
+vec_t WindingArea (winding_t *w);
+void WindingCenter (winding_t *w, vec3_t center);
+void ClipWindingEpsilon (winding_t *in, vec3_t normal, vec_t dist,
+ vec_t epsilon, winding_t **front, winding_t **back);
+winding_t *ChopWinding (winding_t *in, vec3_t normal, vec_t dist);
+winding_t *CopyWinding (winding_t *w);
+winding_t *ReverseWinding (winding_t *w);
+winding_t *BaseWindingForPlane (vec3_t normal, vec_t dist);
+void CheckWinding (winding_t *w);
+void WindingPlane (winding_t *w, vec3_t normal, vec_t *dist);
+void RemoveColinearPoints (winding_t *w);
+int WindingOnPlaneSide (winding_t *w, vec3_t normal, vec_t dist);
+void FreeWinding (winding_t *w);
+void WindingBounds (winding_t *w, vec3_t mins, vec3_t maxs);
+
+void AddWindingToConvexHull( winding_t *w, winding_t **hull, vec3_t normal );
+
+void ChopWindingInPlace (winding_t **w, vec3_t normal, vec_t dist, vec_t epsilon);
+// frees the original if clipped
+
+void pw(winding_t *w);
diff --git a/code/qcommon/cm_public.h b/code/qcommon/cm_public.h
new file mode 100755
index 0000000..f539d08
--- /dev/null
+++ b/code/qcommon/cm_public.h
@@ -0,0 +1,76 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qfiles.h"
+
+
+void CM_LoadMap( const char *name, qboolean clientload, int *checksum);
+void CM_ClearMap( void );
+clipHandle_t CM_InlineModel( int index ); // 0 = world, 1 + are bmodels
+clipHandle_t CM_TempBoxModel( const vec3_t mins, const vec3_t maxs, int capsule );
+
+void CM_ModelBounds( clipHandle_t model, vec3_t mins, vec3_t maxs );
+
+int CM_NumClusters (void);
+int CM_NumInlineModels( void );
+char *CM_EntityString (void);
+
+// returns an ORed contents mask
+int CM_PointContents( const vec3_t p, clipHandle_t model );
+int CM_TransformedPointContents( const vec3_t p, clipHandle_t model, const vec3_t origin, const vec3_t angles );
+
+void CM_BoxTrace ( trace_t *results, const vec3_t start, const vec3_t end,
+ vec3_t mins, vec3_t maxs,
+ clipHandle_t model, int brushmask, int capsule );
+void CM_TransformedBoxTrace( trace_t *results, const vec3_t start, const vec3_t end,
+ vec3_t mins, vec3_t maxs,
+ clipHandle_t model, int brushmask,
+ const vec3_t origin, const vec3_t angles, int capsule );
+
+byte *CM_ClusterPVS (int cluster);
+
+int CM_PointLeafnum( const vec3_t p );
+
+// only returns non-solid leafs
+// overflow if return listsize and if *lastLeaf != list[listsize-1]
+int CM_BoxLeafnums( const vec3_t mins, const vec3_t maxs, int *list,
+ int listsize, int *lastLeaf );
+
+int CM_LeafCluster (int leafnum);
+int CM_LeafArea (int leafnum);
+
+void CM_AdjustAreaPortalState( int area1, int area2, qboolean open );
+qboolean CM_AreasConnected( int area1, int area2 );
+
+int CM_WriteAreaBits( byte *buffer, int area );
+
+// cm_tag.c
+int CM_LerpTag( orientation_t *tag, clipHandle_t model, int startFrame, int endFrame,
+ float frac, const char *tagName );
+
+
+// cm_marks.c
+int CM_MarkFragments( int numPoints, const vec3_t *points, const vec3_t projection,
+ int maxPoints, vec3_t pointBuffer, int maxFragments, markFragment_t *fragmentBuffer );
+
+// cm_patch.c
+void CM_DrawDebugSurface( void (*drawPoly)(int color, int numPoints, float *points) );
diff --git a/code/qcommon/cm_test.c b/code/qcommon/cm_test.c
new file mode 100755
index 0000000..ef18e60
--- /dev/null
+++ b/code/qcommon/cm_test.c
@@ -0,0 +1,478 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "cm_local.h"
+
+
+/*
+==================
+CM_PointLeafnum_r
+
+==================
+*/
+int CM_PointLeafnum_r( const vec3_t p, int num ) {
+ float d;
+ cNode_t *node;
+ cplane_t *plane;
+
+ while (num >= 0)
+ {
+ node = cm.nodes + num;
+ plane = node->plane;
+
+ if (plane->type < 3)
+ d = p[plane->type] - plane->dist;
+ else
+ d = DotProduct (plane->normal, p) - plane->dist;
+ if (d < 0)
+ num = node->children[1];
+ else
+ num = node->children[0];
+ }
+
+ c_pointcontents++; // optimize counter
+
+ return -1 - num;
+}
+
+int CM_PointLeafnum( const vec3_t p ) {
+ if ( !cm.numNodes ) { // map not loaded
+ return 0;
+ }
+ return CM_PointLeafnum_r (p, 0);
+}
+
+
+/*
+======================================================================
+
+LEAF LISTING
+
+======================================================================
+*/
+
+
+void CM_StoreLeafs( leafList_t *ll, int nodenum ) {
+ int leafNum;
+
+ leafNum = -1 - nodenum;
+
+ // store the lastLeaf even if the list is overflowed
+ if ( cm.leafs[ leafNum ].cluster != -1 ) {
+ ll->lastLeaf = leafNum;
+ }
+
+ if ( ll->count >= ll->maxcount) {
+ ll->overflowed = qtrue;
+ return;
+ }
+ ll->list[ ll->count++ ] = leafNum;
+}
+
+void CM_StoreBrushes( leafList_t *ll, int nodenum ) {
+ int i, k;
+ int leafnum;
+ int brushnum;
+ cLeaf_t *leaf;
+ cbrush_t *b;
+
+ leafnum = -1 - nodenum;
+
+ leaf = &cm.leafs[leafnum];
+
+ for ( k = 0 ; k < leaf->numLeafBrushes ; k++ ) {
+ brushnum = cm.leafbrushes[leaf->firstLeafBrush+k];
+ b = &cm.brushes[brushnum];
+ if ( b->checkcount == cm.checkcount ) {
+ continue; // already checked this brush in another leaf
+ }
+ b->checkcount = cm.checkcount;
+ for ( i = 0 ; i < 3 ; i++ ) {
+ if ( b->bounds[0][i] >= ll->bounds[1][i] || b->bounds[1][i] <= ll->bounds[0][i] ) {
+ break;
+ }
+ }
+ if ( i != 3 ) {
+ continue;
+ }
+ if ( ll->count >= ll->maxcount) {
+ ll->overflowed = qtrue;
+ return;
+ }
+ ((cbrush_t **)ll->list)[ ll->count++ ] = b;
+ }
+#if 0
+ // store patches?
+ for ( k = 0 ; k < leaf->numLeafSurfaces ; k++ ) {
+ patch = cm.surfaces[ cm.leafsurfaces[ leaf->firstleafsurface + k ] ];
+ if ( !patch ) {
+ continue;
+ }
+ }
+#endif
+}
+
+/*
+=============
+CM_BoxLeafnums
+
+Fills in a list of all the leafs touched
+=============
+*/
+void CM_BoxLeafnums_r( leafList_t *ll, int nodenum ) {
+ cplane_t *plane;
+ cNode_t *node;
+ int s;
+
+ while (1) {
+ if (nodenum < 0) {
+ ll->storeLeafs( ll, nodenum );
+ return;
+ }
+
+ node = &cm.nodes[nodenum];
+ plane = node->plane;
+ s = BoxOnPlaneSide( ll->bounds[0], ll->bounds[1], plane );
+ if (s == 1) {
+ nodenum = node->children[0];
+ } else if (s == 2) {
+ nodenum = node->children[1];
+ } else {
+ // go down both
+ CM_BoxLeafnums_r( ll, node->children[0] );
+ nodenum = node->children[1];
+ }
+
+ }
+}
+
+/*
+==================
+CM_BoxLeafnums
+==================
+*/
+int CM_BoxLeafnums( const vec3_t mins, const vec3_t maxs, int *list, int listsize, int *lastLeaf) {
+ leafList_t ll;
+
+ cm.checkcount++;
+
+ VectorCopy( mins, ll.bounds[0] );
+ VectorCopy( maxs, ll.bounds[1] );
+ ll.count = 0;
+ ll.maxcount = listsize;
+ ll.list = list;
+ ll.storeLeafs = CM_StoreLeafs;
+ ll.lastLeaf = 0;
+ ll.overflowed = qfalse;
+
+ CM_BoxLeafnums_r( &ll, 0 );
+
+ *lastLeaf = ll.lastLeaf;
+ return ll.count;
+}
+
+/*
+==================
+CM_BoxBrushes
+==================
+*/
+int CM_BoxBrushes( const vec3_t mins, const vec3_t maxs, cbrush_t **list, int listsize ) {
+ leafList_t ll;
+
+ cm.checkcount++;
+
+ VectorCopy( mins, ll.bounds[0] );
+ VectorCopy( maxs, ll.bounds[1] );
+ ll.count = 0;
+ ll.maxcount = listsize;
+ ll.list = (void *)list;
+ ll.storeLeafs = CM_StoreBrushes;
+ ll.lastLeaf = 0;
+ ll.overflowed = qfalse;
+
+ CM_BoxLeafnums_r( &ll, 0 );
+
+ return ll.count;
+}
+
+
+//====================================================================
+
+
+/*
+==================
+CM_PointContents
+
+==================
+*/
+int CM_PointContents( const vec3_t p, clipHandle_t model ) {
+ int leafnum;
+ int i, k;
+ int brushnum;
+ cLeaf_t *leaf;
+ cbrush_t *b;
+ int contents;
+ float d;
+ cmodel_t *clipm;
+
+ if (!cm.numNodes) { // map not loaded
+ return 0;
+ }
+
+ if ( model ) {
+ clipm = CM_ClipHandleToModel( model );
+ leaf = &clipm->leaf;
+ } else {
+ leafnum = CM_PointLeafnum_r (p, 0);
+ leaf = &cm.leafs[leafnum];
+ }
+
+ contents = 0;
+ for (k=0 ; k<leaf->numLeafBrushes ; k++) {
+ brushnum = cm.leafbrushes[leaf->firstLeafBrush+k];
+ b = &cm.brushes[brushnum];
+
+ // see if the point is in the brush
+ for ( i = 0 ; i < b->numsides ; i++ ) {
+ d = DotProduct( p, b->sides[i].plane->normal );
+// FIXME test for Cash
+// if ( d >= b->sides[i].plane->dist ) {
+ if ( d > b->sides[i].plane->dist ) {
+ break;
+ }
+ }
+
+ if ( i == b->numsides ) {
+ contents |= b->contents;
+ }
+ }
+
+ return contents;
+}
+
+/*
+==================
+CM_TransformedPointContents
+
+Handles offseting and rotation of the end points for moving and
+rotating entities
+==================
+*/
+int CM_TransformedPointContents( const vec3_t p, clipHandle_t model, const vec3_t origin, const vec3_t angles) {
+ vec3_t p_l;
+ vec3_t temp;
+ vec3_t forward, right, up;
+
+ // subtract origin offset
+ VectorSubtract (p, origin, p_l);
+
+ // rotate start and end into the models frame of reference
+ if ( model != BOX_MODEL_HANDLE &&
+ (angles[0] || angles[1] || angles[2]) )
+ {
+ AngleVectors (angles, forward, right, up);
+
+ VectorCopy (p_l, temp);
+ p_l[0] = DotProduct (temp, forward);
+ p_l[1] = -DotProduct (temp, right);
+ p_l[2] = DotProduct (temp, up);
+ }
+
+ return CM_PointContents( p_l, model );
+}
+
+
+
+/*
+===============================================================================
+
+PVS
+
+===============================================================================
+*/
+
+byte *CM_ClusterPVS (int cluster) {
+ if (cluster < 0 || cluster >= cm.numClusters || !cm.vised ) {
+ return cm.visibility;
+ }
+
+ return cm.visibility + cluster * cm.clusterBytes;
+}
+
+
+
+/*
+===============================================================================
+
+AREAPORTALS
+
+===============================================================================
+*/
+
+void CM_FloodArea_r( int areaNum, int floodnum) {
+ int i;
+ cArea_t *area;
+ int *con;
+
+ area = &cm.areas[ areaNum ];
+
+ if ( area->floodvalid == cm.floodvalid ) {
+ if (area->floodnum == floodnum)
+ return;
+ Com_Error (ERR_DROP, "FloodArea_r: reflooded");
+ }
+
+ area->floodnum = floodnum;
+ area->floodvalid = cm.floodvalid;
+ con = cm.areaPortals + areaNum * cm.numAreas;
+ for ( i=0 ; i < cm.numAreas ; i++ ) {
+ if ( con[i] > 0 ) {
+ CM_FloodArea_r( i, floodnum );
+ }
+ }
+}
+
+/*
+====================
+CM_FloodAreaConnections
+
+====================
+*/
+void CM_FloodAreaConnections( void ) {
+ int i;
+ cArea_t *area;
+ int floodnum;
+
+ // all current floods are now invalid
+ cm.floodvalid++;
+ floodnum = 0;
+
+ for (i = 0 ; i < cm.numAreas ; i++) {
+ area = &cm.areas[i];
+ if (area->floodvalid == cm.floodvalid) {
+ continue; // already flooded into
+ }
+ floodnum++;
+ CM_FloodArea_r (i, floodnum);
+ }
+
+}
+
+/*
+====================
+CM_AdjustAreaPortalState
+
+====================
+*/
+void CM_AdjustAreaPortalState( int area1, int area2, qboolean open ) {
+ if ( area1 < 0 || area2 < 0 ) {
+ return;
+ }
+
+ if ( area1 >= cm.numAreas || area2 >= cm.numAreas ) {
+ Com_Error (ERR_DROP, "CM_ChangeAreaPortalState: bad area number");
+ }
+
+ if ( open ) {
+ cm.areaPortals[ area1 * cm.numAreas + area2 ]++;
+ cm.areaPortals[ area2 * cm.numAreas + area1 ]++;
+ } else {
+ cm.areaPortals[ area1 * cm.numAreas + area2 ]--;
+ cm.areaPortals[ area2 * cm.numAreas + area1 ]--;
+ if ( cm.areaPortals[ area2 * cm.numAreas + area1 ] < 0 ) {
+ Com_Error (ERR_DROP, "CM_AdjustAreaPortalState: negative reference count");
+ }
+ }
+
+ CM_FloodAreaConnections ();
+}
+
+/*
+====================
+CM_AreasConnected
+
+====================
+*/
+qboolean CM_AreasConnected( int area1, int area2 ) {
+#ifndef BSPC
+ if ( cm_noAreas->integer ) {
+ return qtrue;
+ }
+#endif
+
+ if ( area1 < 0 || area2 < 0 ) {
+ return qfalse;
+ }
+
+ if (area1 >= cm.numAreas || area2 >= cm.numAreas) {
+ Com_Error (ERR_DROP, "area >= cm.numAreas");
+ }
+
+ if (cm.areas[area1].floodnum == cm.areas[area2].floodnum) {
+ return qtrue;
+ }
+ return qfalse;
+}
+
+
+/*
+=================
+CM_WriteAreaBits
+
+Writes a bit vector of all the areas
+that are in the same flood as the area parameter
+Returns the number of bytes needed to hold all the bits.
+
+The bits are OR'd in, so you can CM_WriteAreaBits from multiple
+viewpoints and get the union of all visible areas.
+
+This is used to cull non-visible entities from snapshots
+=================
+*/
+int CM_WriteAreaBits (byte *buffer, int area)
+{
+ int i;
+ int floodnum;
+ int bytes;
+
+ bytes = (cm.numAreas+7)>>3;
+
+#ifndef BSPC
+ if (cm_noAreas->integer || area == -1)
+#else
+ if ( area == -1)
+#endif
+ { // for debugging, send everything
+ Com_Memset (buffer, 255, bytes);
+ }
+ else
+ {
+ floodnum = cm.areas[area].floodnum;
+ for (i=0 ; i<cm.numAreas ; i++)
+ {
+ if (cm.areas[i].floodnum == floodnum || area == -1)
+ buffer[i>>3] |= 1<<(i&7);
+ }
+ }
+
+ return bytes;
+}
+
diff --git a/code/qcommon/cm_trace.c b/code/qcommon/cm_trace.c
new file mode 100755
index 0000000..372204c
--- /dev/null
+++ b/code/qcommon/cm_trace.c
@@ -0,0 +1,1471 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "cm_local.h"
+
+// always use bbox vs. bbox collision and never capsule vs. bbox or vice versa
+//#define ALWAYS_BBOX_VS_BBOX
+// always use capsule vs. capsule collision and never capsule vs. bbox or vice versa
+//#define ALWAYS_CAPSULE_VS_CAPSULE
+
+//#define CAPSULE_DEBUG
+
+/*
+===============================================================================
+
+BASIC MATH
+
+===============================================================================
+*/
+
+/*
+================
+RotatePoint
+================
+*/
+void RotatePoint(vec3_t point, /*const*/ vec3_t matrix[3]) { // bk: FIXME
+ vec3_t tvec;
+
+ VectorCopy(point, tvec);
+ point[0] = DotProduct(matrix[0], tvec);
+ point[1] = DotProduct(matrix[1], tvec);
+ point[2] = DotProduct(matrix[2], tvec);
+}
+
+/*
+================
+TransposeMatrix
+================
+*/
+void TransposeMatrix(/*const*/ vec3_t matrix[3], vec3_t transpose[3]) { // bk: FIXME
+ int i, j;
+ for (i = 0; i < 3; i++) {
+ for (j = 0; j < 3; j++) {
+ transpose[i][j] = matrix[j][i];
+ }
+ }
+}
+
+/*
+================
+CreateRotationMatrix
+================
+*/
+void CreateRotationMatrix(const vec3_t angles, vec3_t matrix[3]) {
+ AngleVectors(angles, matrix[0], matrix[1], matrix[2]);
+ VectorInverse(matrix[1]);
+}
+
+/*
+================
+CM_ProjectPointOntoVector
+================
+*/
+void CM_ProjectPointOntoVector( vec3_t point, vec3_t vStart, vec3_t vDir, vec3_t vProj )
+{
+ vec3_t pVec;
+
+ VectorSubtract( point, vStart, pVec );
+ // project onto the directional vector for this segment
+ VectorMA( vStart, DotProduct( pVec, vDir ), vDir, vProj );
+}
+
+/*
+================
+CM_DistanceFromLineSquared
+================
+*/
+float CM_DistanceFromLineSquared(vec3_t p, vec3_t lp1, vec3_t lp2, vec3_t dir) {
+ vec3_t proj, t;
+ int j;
+
+ CM_ProjectPointOntoVector(p, lp1, dir, proj);
+ for (j = 0; j < 3; j++)
+ if ((proj[j] > lp1[j] && proj[j] > lp2[j]) ||
+ (proj[j] < lp1[j] && proj[j] < lp2[j]))
+ break;
+ if (j < 3) {
+ if (fabs(proj[j] - lp1[j]) < fabs(proj[j] - lp2[j]))
+ VectorSubtract(p, lp1, t);
+ else
+ VectorSubtract(p, lp2, t);
+ return VectorLengthSquared(t);
+ }
+ VectorSubtract(p, proj, t);
+ return VectorLengthSquared(t);
+}
+
+/*
+================
+CM_VectorDistanceSquared
+================
+*/
+float CM_VectorDistanceSquared(vec3_t p1, vec3_t p2) {
+ vec3_t dir;
+
+ VectorSubtract(p2, p1, dir);
+ return VectorLengthSquared(dir);
+}
+
+/*
+================
+SquareRootFloat
+================
+*/
+float SquareRootFloat(float number) {
+ long i;
+ float x, y;
+ const float f = 1.5F;
+
+ x = number * 0.5F;
+ y = number;
+ i = * ( long * ) &y;
+ i = 0x5f3759df - ( i >> 1 );
+ y = * ( float * ) &i;
+ y = y * ( f - ( x * y * y ) );
+ y = y * ( f - ( x * y * y ) );
+ return number * y;
+}
+
+
+/*
+===============================================================================
+
+POSITION TESTING
+
+===============================================================================
+*/
+
+/*
+================
+CM_TestBoxInBrush
+================
+*/
+void CM_TestBoxInBrush( traceWork_t *tw, cbrush_t *brush ) {
+ int i;
+ cplane_t *plane;
+ float dist;
+ float d1;
+ cbrushside_t *side;
+ float t;
+ vec3_t startp;
+
+ if (!brush->numsides) {
+ return;
+ }
+
+ // special test for axial
+ if ( tw->bounds[0][0] > brush->bounds[1][0]
+ || tw->bounds[0][1] > brush->bounds[1][1]
+ || tw->bounds[0][2] > brush->bounds[1][2]
+ || tw->bounds[1][0] < brush->bounds[0][0]
+ || tw->bounds[1][1] < brush->bounds[0][1]
+ || tw->bounds[1][2] < brush->bounds[0][2]
+ ) {
+ return;
+ }
+
+ if ( tw->sphere.use ) {
+ // the first six planes are the axial planes, so we only
+ // need to test the remainder
+ for ( i = 6 ; i < brush->numsides ; i++ ) {
+ side = brush->sides + i;
+ plane = side->plane;
+
+ // adjust the plane distance apropriately for radius
+ dist = plane->dist + tw->sphere.radius;
+ // find the closest point on the capsule to the plane
+ t = DotProduct( plane->normal, tw->sphere.offset );
+ if ( t > 0 )
+ {
+ VectorSubtract( tw->start, tw->sphere.offset, startp );
+ }
+ else
+ {
+ VectorAdd( tw->start, tw->sphere.offset, startp );
+ }
+ d1 = DotProduct( startp, plane->normal ) - dist;
+ // if completely in front of face, no intersection
+ if ( d1 > 0 ) {
+ return;
+ }
+ }
+ } else {
+ // the first six planes are the axial planes, so we only
+ // need to test the remainder
+ for ( i = 6 ; i < brush->numsides ; i++ ) {
+ side = brush->sides + i;
+ plane = side->plane;
+
+ // adjust the plane distance apropriately for mins/maxs
+ dist = plane->dist - DotProduct( tw->offsets[ plane->signbits ], plane->normal );
+
+ d1 = DotProduct( tw->start, plane->normal ) - dist;
+
+ // if completely in front of face, no intersection
+ if ( d1 > 0 ) {
+ return;
+ }
+ }
+ }
+
+ // inside this brush
+ tw->trace.startsolid = tw->trace.allsolid = qtrue;
+ tw->trace.fraction = 0;
+ tw->trace.contents = brush->contents;
+}
+
+
+
+/*
+================
+CM_TestInLeaf
+================
+*/
+void CM_TestInLeaf( traceWork_t *tw, cLeaf_t *leaf ) {
+ int k;
+ int brushnum;
+ cbrush_t *b;
+ cPatch_t *patch;
+
+ // test box position against all brushes in the leaf
+ for (k=0 ; k<leaf->numLeafBrushes ; k++) {
+ brushnum = cm.leafbrushes[leaf->firstLeafBrush+k];
+ b = &cm.brushes[brushnum];
+ if (b->checkcount == cm.checkcount) {
+ continue; // already checked this brush in another leaf
+ }
+ b->checkcount = cm.checkcount;
+
+ if ( !(b->contents & tw->contents)) {
+ continue;
+ }
+
+ CM_TestBoxInBrush( tw, b );
+ if ( tw->trace.allsolid ) {
+ return;
+ }
+ }
+
+ // test against all patches
+#ifdef BSPC
+ if (1) {
+#else
+ if ( !cm_noCurves->integer ) {
+#endif //BSPC
+ for ( k = 0 ; k < leaf->numLeafSurfaces ; k++ ) {
+ patch = cm.surfaces[ cm.leafsurfaces[ leaf->firstLeafSurface + k ] ];
+ if ( !patch ) {
+ continue;
+ }
+ if ( patch->checkcount == cm.checkcount ) {
+ continue; // already checked this brush in another leaf
+ }
+ patch->checkcount = cm.checkcount;
+
+ if ( !(patch->contents & tw->contents)) {
+ continue;
+ }
+
+ if ( CM_PositionTestInPatchCollide( tw, patch->pc ) ) {
+ tw->trace.startsolid = tw->trace.allsolid = qtrue;
+ tw->trace.fraction = 0;
+ tw->trace.contents = patch->contents;
+ return;
+ }
+ }
+ }
+}
+
+/*
+==================
+CM_TestCapsuleInCapsule
+
+capsule inside capsule check
+==================
+*/
+void CM_TestCapsuleInCapsule( traceWork_t *tw, clipHandle_t model ) {
+ int i;
+ vec3_t mins, maxs;
+ vec3_t top, bottom;
+ vec3_t p1, p2, tmp;
+ vec3_t offset, symetricSize[2];
+ float radius, halfwidth, halfheight, offs, r;
+
+ CM_ModelBounds(model, mins, maxs);
+
+ VectorAdd(tw->start, tw->sphere.offset, top);
+ VectorSubtract(tw->start, tw->sphere.offset, bottom);
+ for ( i = 0 ; i < 3 ; i++ ) {
+ offset[i] = ( mins[i] + maxs[i] ) * 0.5;
+ symetricSize[0][i] = mins[i] - offset[i];
+ symetricSize[1][i] = maxs[i] - offset[i];
+ }
+ halfwidth = symetricSize[ 1 ][ 0 ];
+ halfheight = symetricSize[ 1 ][ 2 ];
+ radius = ( halfwidth > halfheight ) ? halfheight : halfwidth;
+ offs = halfheight - radius;
+
+ r = Square(tw->sphere.radius + radius);
+ // check if any of the spheres overlap
+ VectorCopy(offset, p1);
+ p1[2] += offs;
+ VectorSubtract(p1, top, tmp);
+ if ( VectorLengthSquared(tmp) < r ) {
+ tw->trace.startsolid = tw->trace.allsolid = qtrue;
+ tw->trace.fraction = 0;
+ }
+ VectorSubtract(p1, bottom, tmp);
+ if ( VectorLengthSquared(tmp) < r ) {
+ tw->trace.startsolid = tw->trace.allsolid = qtrue;
+ tw->trace.fraction = 0;
+ }
+ VectorCopy(offset, p2);
+ p2[2] -= offs;
+ VectorSubtract(p2, top, tmp);
+ if ( VectorLengthSquared(tmp) < r ) {
+ tw->trace.startsolid = tw->trace.allsolid = qtrue;
+ tw->trace.fraction = 0;
+ }
+ VectorSubtract(p2, bottom, tmp);
+ if ( VectorLengthSquared(tmp) < r ) {
+ tw->trace.startsolid = tw->trace.allsolid = qtrue;
+ tw->trace.fraction = 0;
+ }
+ // if between cylinder up and lower bounds
+ if ( (top[2] >= p1[2] && top[2] <= p2[2]) ||
+ (bottom[2] >= p1[2] && bottom[2] <= p2[2]) ) {
+ // 2d coordinates
+ top[2] = p1[2] = 0;
+ // if the cylinders overlap
+ VectorSubtract(top, p1, tmp);
+ if ( VectorLengthSquared(tmp) < r ) {
+ tw->trace.startsolid = tw->trace.allsolid = qtrue;
+ tw->trace.fraction = 0;
+ }
+ }
+}
+
+/*
+==================
+CM_TestBoundingBoxInCapsule
+
+bounding box inside capsule check
+==================
+*/
+void CM_TestBoundingBoxInCapsule( traceWork_t *tw, clipHandle_t model ) {
+ vec3_t mins, maxs, offset, size[2];
+ clipHandle_t h;
+ cmodel_t *cmod;
+ int i;
+
+ // mins maxs of the capsule
+ CM_ModelBounds(model, mins, maxs);
+
+ // offset for capsule center
+ for ( i = 0 ; i < 3 ; i++ ) {
+ offset[i] = ( mins[i] + maxs[i] ) * 0.5;
+ size[0][i] = mins[i] - offset[i];
+ size[1][i] = maxs[i] - offset[i];
+ tw->start[i] -= offset[i];
+ tw->end[i] -= offset[i];
+ }
+
+ // replace the bounding box with the capsule
+ tw->sphere.use = qtrue;
+ tw->sphere.radius = ( size[1][0] > size[1][2] ) ? size[1][2]: size[1][0];
+ tw->sphere.halfheight = size[1][2];
+ VectorSet( tw->sphere.offset, 0, 0, size[1][2] - tw->sphere.radius );
+
+ // replace the capsule with the bounding box
+ h = CM_TempBoxModel(tw->size[0], tw->size[1], qfalse);
+ // calculate collision
+ cmod = CM_ClipHandleToModel( h );
+ CM_TestInLeaf( tw, &cmod->leaf );
+}
+
+/*
+==================
+CM_PositionTest
+==================
+*/
+#define MAX_POSITION_LEAFS 1024
+void CM_PositionTest( traceWork_t *tw ) {
+ int leafs[MAX_POSITION_LEAFS];
+ int i;
+ leafList_t ll;
+
+ // identify the leafs we are touching
+ VectorAdd( tw->start, tw->size[0], ll.bounds[0] );
+ VectorAdd( tw->start, tw->size[1], ll.bounds[1] );
+
+ for (i=0 ; i<3 ; i++) {
+ ll.bounds[0][i] -= 1;
+ ll.bounds[1][i] += 1;
+ }
+
+ ll.count = 0;
+ ll.maxcount = MAX_POSITION_LEAFS;
+ ll.list = leafs;
+ ll.storeLeafs = CM_StoreLeafs;
+ ll.lastLeaf = 0;
+ ll.overflowed = qfalse;
+
+ cm.checkcount++;
+
+ CM_BoxLeafnums_r( &ll, 0 );
+
+
+ cm.checkcount++;
+
+ // test the contents of the leafs
+ for (i=0 ; i < ll.count ; i++) {
+ CM_TestInLeaf( tw, &cm.leafs[leafs[i]] );
+ if ( tw->trace.allsolid ) {
+ break;
+ }
+ }
+}
+
+/*
+===============================================================================
+
+TRACING
+
+===============================================================================
+*/
+
+
+/*
+================
+CM_TraceThroughPatch
+================
+*/
+
+void CM_TraceThroughPatch( traceWork_t *tw, cPatch_t *patch ) {
+ float oldFrac;
+
+ c_patch_traces++;
+
+ oldFrac = tw->trace.fraction;
+
+ CM_TraceThroughPatchCollide( tw, patch->pc );
+
+ if ( tw->trace.fraction < oldFrac ) {
+ tw->trace.surfaceFlags = patch->surfaceFlags;
+ tw->trace.contents = patch->contents;
+ }
+}
+
+/*
+================
+CM_TraceThroughBrush
+================
+*/
+void CM_TraceThroughBrush( traceWork_t *tw, cbrush_t *brush ) {
+ int i;
+ cplane_t *plane, *clipplane;
+ float dist;
+ float enterFrac, leaveFrac;
+ float d1, d2;
+ qboolean getout, startout;
+ float f;
+ cbrushside_t *side, *leadside;
+ float t;
+ vec3_t startp;
+ vec3_t endp;
+
+ enterFrac = -1.0;
+ leaveFrac = 1.0;
+ clipplane = NULL;
+
+ if ( !brush->numsides ) {
+ return;
+ }
+
+ c_brush_traces++;
+
+ getout = qfalse;
+ startout = qfalse;
+
+ leadside = NULL;
+
+ if ( tw->sphere.use ) {
+ //
+ // compare the trace against all planes of the brush
+ // find the latest time the trace crosses a plane towards the interior
+ // and the earliest time the trace crosses a plane towards the exterior
+ //
+ for (i = 0; i < brush->numsides; i++) {
+ side = brush->sides + i;
+ plane = side->plane;
+
+ // adjust the plane distance apropriately for radius
+ dist = plane->dist + tw->sphere.radius;
+
+ // find the closest point on the capsule to the plane
+ t = DotProduct( plane->normal, tw->sphere.offset );
+ if ( t > 0 )
+ {
+ VectorSubtract( tw->start, tw->sphere.offset, startp );
+ VectorSubtract( tw->end, tw->sphere.offset, endp );
+ }
+ else
+ {
+ VectorAdd( tw->start, tw->sphere.offset, startp );
+ VectorAdd( tw->end, tw->sphere.offset, endp );
+ }
+
+ d1 = DotProduct( startp, plane->normal ) - dist;
+ d2 = DotProduct( endp, plane->normal ) - dist;
+
+ if (d2 > 0) {
+ getout = qtrue; // endpoint is not in solid
+ }
+ if (d1 > 0) {
+ startout = qtrue;
+ }
+
+ // if completely in front of face, no intersection with the entire brush
+ if (d1 > 0 && ( d2 >= SURFACE_CLIP_EPSILON || d2 >= d1 ) ) {
+ return;
+ }
+
+ // if it doesn't cross the plane, the plane isn't relevent
+ if (d1 <= 0 && d2 <= 0 ) {
+ continue;
+ }
+
+ // crosses face
+ if (d1 > d2) { // enter
+ f = (d1-SURFACE_CLIP_EPSILON) / (d1-d2);
+ if ( f < 0 ) {
+ f = 0;
+ }
+ if (f > enterFrac) {
+ enterFrac = f;
+ clipplane = plane;
+ leadside = side;
+ }
+ } else { // leave
+ f = (d1+SURFACE_CLIP_EPSILON) / (d1-d2);
+ if ( f > 1 ) {
+ f = 1;
+ }
+ if (f < leaveFrac) {
+ leaveFrac = f;
+ }
+ }
+ }
+ } else {
+ //
+ // compare the trace against all planes of the brush
+ // find the latest time the trace crosses a plane towards the interior
+ // and the earliest time the trace crosses a plane towards the exterior
+ //
+ for (i = 0; i < brush->numsides; i++) {
+ side = brush->sides + i;
+ plane = side->plane;
+
+ // adjust the plane distance apropriately for mins/maxs
+ dist = plane->dist - DotProduct( tw->offsets[ plane->signbits ], plane->normal );
+
+ d1 = DotProduct( tw->start, plane->normal ) - dist;
+ d2 = DotProduct( tw->end, plane->normal ) - dist;
+
+ if (d2 > 0) {
+ getout = qtrue; // endpoint is not in solid
+ }
+ if (d1 > 0) {
+ startout = qtrue;
+ }
+
+ // if completely in front of face, no intersection with the entire brush
+ if (d1 > 0 && ( d2 >= SURFACE_CLIP_EPSILON || d2 >= d1 ) ) {
+ return;
+ }
+
+ // if it doesn't cross the plane, the plane isn't relevent
+ if (d1 <= 0 && d2 <= 0 ) {
+ continue;
+ }
+
+ // crosses face
+ if (d1 > d2) { // enter
+ f = (d1-SURFACE_CLIP_EPSILON) / (d1-d2);
+ if ( f < 0 ) {
+ f = 0;
+ }
+ if (f > enterFrac) {
+ enterFrac = f;
+ clipplane = plane;
+ leadside = side;
+ }
+ } else { // leave
+ f = (d1+SURFACE_CLIP_EPSILON) / (d1-d2);
+ if ( f > 1 ) {
+ f = 1;
+ }
+ if (f < leaveFrac) {
+ leaveFrac = f;
+ }
+ }
+ }
+ }
+
+ //
+ // all planes have been checked, and the trace was not
+ // completely outside the brush
+ //
+ if (!startout) { // original point was inside brush
+ tw->trace.startsolid = qtrue;
+ if (!getout) {
+ tw->trace.allsolid = qtrue;
+ tw->trace.fraction = 0;
+ tw->trace.contents = brush->contents;
+ }
+ return;
+ }
+
+ if (enterFrac < leaveFrac) {
+ if (enterFrac > -1 && enterFrac < tw->trace.fraction) {
+ if (enterFrac < 0) {
+ enterFrac = 0;
+ }
+ tw->trace.fraction = enterFrac;
+ tw->trace.plane = *clipplane;
+ tw->trace.surfaceFlags = leadside->surfaceFlags;
+ tw->trace.contents = brush->contents;
+ }
+ }
+}
+
+/*
+================
+CM_TraceThroughLeaf
+================
+*/
+void CM_TraceThroughLeaf( traceWork_t *tw, cLeaf_t *leaf ) {
+ int k;
+ int brushnum;
+ cbrush_t *b;
+ cPatch_t *patch;
+
+ // trace line against all brushes in the leaf
+ for ( k = 0 ; k < leaf->numLeafBrushes ; k++ ) {
+ brushnum = cm.leafbrushes[leaf->firstLeafBrush+k];
+
+ b = &cm.brushes[brushnum];
+ if ( b->checkcount == cm.checkcount ) {
+ continue; // already checked this brush in another leaf
+ }
+ b->checkcount = cm.checkcount;
+
+ if ( !(b->contents & tw->contents) ) {
+ continue;
+ }
+
+ CM_TraceThroughBrush( tw, b );
+ if ( !tw->trace.fraction ) {
+ return;
+ }
+ }
+
+ // trace line against all patches in the leaf
+#ifdef BSPC
+ if (1) {
+#else
+ if ( !cm_noCurves->integer ) {
+#endif
+ for ( k = 0 ; k < leaf->numLeafSurfaces ; k++ ) {
+ patch = cm.surfaces[ cm.leafsurfaces[ leaf->firstLeafSurface + k ] ];
+ if ( !patch ) {
+ continue;
+ }
+ if ( patch->checkcount == cm.checkcount ) {
+ continue; // already checked this patch in another leaf
+ }
+ patch->checkcount = cm.checkcount;
+
+ if ( !(patch->contents & tw->contents) ) {
+ continue;
+ }
+
+ CM_TraceThroughPatch( tw, patch );
+ if ( !tw->trace.fraction ) {
+ return;
+ }
+ }
+ }
+}
+
+#define RADIUS_EPSILON 1.0f
+
+/*
+================
+CM_TraceThroughSphere
+
+get the first intersection of the ray with the sphere
+================
+*/
+void CM_TraceThroughSphere( traceWork_t *tw, vec3_t origin, float radius, vec3_t start, vec3_t end ) {
+ float l1, l2, length, scale, fraction;
+ float a, b, c, d, sqrtd;
+ vec3_t v1, dir, intersection;
+
+ // if inside the sphere
+ VectorSubtract(start, origin, dir);
+ l1 = VectorLengthSquared(dir);
+ if (l1 < Square(radius)) {
+ tw->trace.fraction = 0;
+ tw->trace.startsolid = qtrue;
+ // test for allsolid
+ VectorSubtract(end, origin, dir);
+ l1 = VectorLengthSquared(dir);
+ if (l1 < Square(radius)) {
+ tw->trace.allsolid = qtrue;
+ }
+ return;
+ }
+ //
+ VectorSubtract(end, start, dir);
+ length = VectorNormalize(dir);
+ //
+ l1 = CM_DistanceFromLineSquared(origin, start, end, dir);
+ VectorSubtract(end, origin, v1);
+ l2 = VectorLengthSquared(v1);
+ // if no intersection with the sphere and the end point is at least an epsilon away
+ if (l1 >= Square(radius) && l2 > Square(radius+SURFACE_CLIP_EPSILON)) {
+ return;
+ }
+ //
+ // | origin - (start + t * dir) | = radius
+ // a = dir[0]^2 + dir[1]^2 + dir[2]^2;
+ // b = 2 * (dir[0] * (start[0] - origin[0]) + dir[1] * (start[1] - origin[1]) + dir[2] * (start[2] - origin[2]));
+ // c = (start[0] - origin[0])^2 + (start[1] - origin[1])^2 + (start[2] - origin[2])^2 - radius^2;
+ //
+ VectorSubtract(start, origin, v1);
+ // dir is normalized so a = 1
+ a = 1.0f;//dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2];
+ b = 2.0f * (dir[0] * v1[0] + dir[1] * v1[1] + dir[2] * v1[2]);
+ c = v1[0] * v1[0] + v1[1] * v1[1] + v1[2] * v1[2] - (radius+RADIUS_EPSILON) * (radius+RADIUS_EPSILON);
+
+ d = b * b - 4.0f * c;// * a;
+ if (d > 0) {
+ sqrtd = SquareRootFloat(d);
+ // = (- b + sqrtd) * 0.5f; // / (2.0f * a);
+ fraction = (- b - sqrtd) * 0.5f; // / (2.0f * a);
+ //
+ if (fraction < 0) {
+ fraction = 0;
+ }
+ else {
+ fraction /= length;
+ }
+ if ( fraction < tw->trace.fraction ) {
+ tw->trace.fraction = fraction;
+ VectorSubtract(end, start, dir);
+ VectorMA(start, fraction, dir, intersection);
+ VectorSubtract(intersection, origin, dir);
+ #ifdef CAPSULE_DEBUG
+ l2 = VectorLength(dir);
+ if (l2 < radius) {
+ int bah = 1;
+ }
+ #endif
+ scale = 1 / (radius+RADIUS_EPSILON);
+ VectorScale(dir, scale, dir);
+ VectorCopy(dir, tw->trace.plane.normal);
+ VectorAdd( tw->modelOrigin, intersection, intersection);
+ tw->trace.plane.dist = DotProduct(tw->trace.plane.normal, intersection);
+ tw->trace.contents = CONTENTS_BODY;
+ }
+ }
+ else if (d == 0) {
+ //t1 = (- b ) / 2;
+ // slide along the sphere
+ }
+ // no intersection at all
+}
+
+/*
+================
+CM_TraceThroughVerticalCylinder
+
+get the first intersection of the ray with the cylinder
+the cylinder extends halfheight above and below the origin
+================
+*/
+void CM_TraceThroughVerticalCylinder( traceWork_t *tw, vec3_t origin, float radius, float halfheight, vec3_t start, vec3_t end) {
+ float length, scale, fraction, l1, l2;
+ float a, b, c, d, sqrtd;
+ vec3_t v1, dir, start2d, end2d, org2d, intersection;
+
+ // 2d coordinates
+ VectorSet(start2d, start[0], start[1], 0);
+ VectorSet(end2d, end[0], end[1], 0);
+ VectorSet(org2d, origin[0], origin[1], 0);
+ // if between lower and upper cylinder bounds
+ if (start[2] <= origin[2] + halfheight &&
+ start[2] >= origin[2] - halfheight) {
+ // if inside the cylinder
+ VectorSubtract(start2d, org2d, dir);
+ l1 = VectorLengthSquared(dir);
+ if (l1 < Square(radius)) {
+ tw->trace.fraction = 0;
+ tw->trace.startsolid = qtrue;
+ VectorSubtract(end2d, org2d, dir);
+ l1 = VectorLengthSquared(dir);
+ if (l1 < Square(radius)) {
+ tw->trace.allsolid = qtrue;
+ }
+ return;
+ }
+ }
+ //
+ VectorSubtract(end2d, start2d, dir);
+ length = VectorNormalize(dir);
+ //
+ l1 = CM_DistanceFromLineSquared(org2d, start2d, end2d, dir);
+ VectorSubtract(end2d, org2d, v1);
+ l2 = VectorLengthSquared(v1);
+ // if no intersection with the cylinder and the end point is at least an epsilon away
+ if (l1 >= Square(radius) && l2 > Square(radius+SURFACE_CLIP_EPSILON)) {
+ return;
+ }
+ //
+ //
+ // (start[0] - origin[0] - t * dir[0]) ^ 2 + (start[1] - origin[1] - t * dir[1]) ^ 2 = radius ^ 2
+ // (v1[0] + t * dir[0]) ^ 2 + (v1[1] + t * dir[1]) ^ 2 = radius ^ 2;
+ // v1[0] ^ 2 + 2 * v1[0] * t * dir[0] + (t * dir[0]) ^ 2 +
+ // v1[1] ^ 2 + 2 * v1[1] * t * dir[1] + (t * dir[1]) ^ 2 = radius ^ 2
+ // t ^ 2 * (dir[0] ^ 2 + dir[1] ^ 2) + t * (2 * v1[0] * dir[0] + 2 * v1[1] * dir[1]) +
+ // v1[0] ^ 2 + v1[1] ^ 2 - radius ^ 2 = 0
+ //
+ VectorSubtract(start, origin, v1);
+ // dir is normalized so we can use a = 1
+ a = 1.0f;// * (dir[0] * dir[0] + dir[1] * dir[1]);
+ b = 2.0f * (v1[0] * dir[0] + v1[1] * dir[1]);
+ c = v1[0] * v1[0] + v1[1] * v1[1] - (radius+RADIUS_EPSILON) * (radius+RADIUS_EPSILON);
+
+ d = b * b - 4.0f * c;// * a;
+ if (d > 0) {
+ sqrtd = SquareRootFloat(d);
+ // = (- b + sqrtd) * 0.5f;// / (2.0f * a);
+ fraction = (- b - sqrtd) * 0.5f;// / (2.0f * a);
+ //
+ if (fraction < 0) {
+ fraction = 0;
+ }
+ else {
+ fraction /= length;
+ }
+ if ( fraction < tw->trace.fraction ) {
+ VectorSubtract(end, start, dir);
+ VectorMA(start, fraction, dir, intersection);
+ // if the intersection is between the cylinder lower and upper bound
+ if (intersection[2] <= origin[2] + halfheight &&
+ intersection[2] >= origin[2] - halfheight) {
+ //
+ tw->trace.fraction = fraction;
+ VectorSubtract(intersection, origin, dir);
+ dir[2] = 0;
+ #ifdef CAPSULE_DEBUG
+ l2 = VectorLength(dir);
+ if (l2 <= radius) {
+ int bah = 1;
+ }
+ #endif
+ scale = 1 / (radius+RADIUS_EPSILON);
+ VectorScale(dir, scale, dir);
+ VectorCopy(dir, tw->trace.plane.normal);
+ VectorAdd( tw->modelOrigin, intersection, intersection);
+ tw->trace.plane.dist = DotProduct(tw->trace.plane.normal, intersection);
+ tw->trace.contents = CONTENTS_BODY;
+ }
+ }
+ }
+ else if (d == 0) {
+ //t[0] = (- b ) / 2 * a;
+ // slide along the cylinder
+ }
+ // no intersection at all
+}
+
+/*
+================
+CM_TraceCapsuleThroughCapsule
+
+capsule vs. capsule collision (not rotated)
+================
+*/
+void CM_TraceCapsuleThroughCapsule( traceWork_t *tw, clipHandle_t model ) {
+ int i;
+ vec3_t mins, maxs;
+ vec3_t top, bottom, starttop, startbottom, endtop, endbottom;
+ vec3_t offset, symetricSize[2];
+ float radius, halfwidth, halfheight, offs, h;
+
+ CM_ModelBounds(model, mins, maxs);
+ // test trace bounds vs. capsule bounds
+ if ( tw->bounds[0][0] > maxs[0] + RADIUS_EPSILON
+ || tw->bounds[0][1] > maxs[1] + RADIUS_EPSILON
+ || tw->bounds[0][2] > maxs[2] + RADIUS_EPSILON
+ || tw->bounds[1][0] < mins[0] - RADIUS_EPSILON
+ || tw->bounds[1][1] < mins[1] - RADIUS_EPSILON
+ || tw->bounds[1][2] < mins[2] - RADIUS_EPSILON
+ ) {
+ return;
+ }
+ // top origin and bottom origin of each sphere at start and end of trace
+ VectorAdd(tw->start, tw->sphere.offset, starttop);
+ VectorSubtract(tw->start, tw->sphere.offset, startbottom);
+ VectorAdd(tw->end, tw->sphere.offset, endtop);
+ VectorSubtract(tw->end, tw->sphere.offset, endbottom);
+
+ // calculate top and bottom of the capsule spheres to collide with
+ for ( i = 0 ; i < 3 ; i++ ) {
+ offset[i] = ( mins[i] + maxs[i] ) * 0.5;
+ symetricSize[0][i] = mins[i] - offset[i];
+ symetricSize[1][i] = maxs[i] - offset[i];
+ }
+ halfwidth = symetricSize[ 1 ][ 0 ];
+ halfheight = symetricSize[ 1 ][ 2 ];
+ radius = ( halfwidth > halfheight ) ? halfheight : halfwidth;
+ offs = halfheight - radius;
+ VectorCopy(offset, top);
+ top[2] += offs;
+ VectorCopy(offset, bottom);
+ bottom[2] -= offs;
+ // expand radius of spheres
+ radius += tw->sphere.radius;
+ // if there is horizontal movement
+ if ( tw->start[0] != tw->end[0] || tw->start[1] != tw->end[1] ) {
+ // height of the expanded cylinder is the height of both cylinders minus the radius of both spheres
+ h = halfheight + tw->sphere.halfheight - radius;
+ // if the cylinder has a height
+ if ( h > 0 ) {
+ // test for collisions between the cylinders
+ CM_TraceThroughVerticalCylinder(tw, offset, radius, h, tw->start, tw->end);
+ }
+ }
+ // test for collision between the spheres
+ CM_TraceThroughSphere(tw, top, radius, startbottom, endbottom);
+ CM_TraceThroughSphere(tw, bottom, radius, starttop, endtop);
+}
+
+/*
+================
+CM_TraceBoundingBoxThroughCapsule
+
+bounding box vs. capsule collision
+================
+*/
+void CM_TraceBoundingBoxThroughCapsule( traceWork_t *tw, clipHandle_t model ) {
+ vec3_t mins, maxs, offset, size[2];
+ clipHandle_t h;
+ cmodel_t *cmod;
+ int i;
+
+ // mins maxs of the capsule
+ CM_ModelBounds(model, mins, maxs);
+
+ // offset for capsule center
+ for ( i = 0 ; i < 3 ; i++ ) {
+ offset[i] = ( mins[i] + maxs[i] ) * 0.5;
+ size[0][i] = mins[i] - offset[i];
+ size[1][i] = maxs[i] - offset[i];
+ tw->start[i] -= offset[i];
+ tw->end[i] -= offset[i];
+ }
+
+ // replace the bounding box with the capsule
+ tw->sphere.use = qtrue;
+ tw->sphere.radius = ( size[1][0] > size[1][2] ) ? size[1][2]: size[1][0];
+ tw->sphere.halfheight = size[1][2];
+ VectorSet( tw->sphere.offset, 0, 0, size[1][2] - tw->sphere.radius );
+
+ // replace the capsule with the bounding box
+ h = CM_TempBoxModel(tw->size[0], tw->size[1], qfalse);
+ // calculate collision
+ cmod = CM_ClipHandleToModel( h );
+ CM_TraceThroughLeaf( tw, &cmod->leaf );
+}
+
+//=========================================================================================
+
+/*
+==================
+CM_TraceThroughTree
+
+Traverse all the contacted leafs from the start to the end position.
+If the trace is a point, they will be exactly in order, but for larger
+trace volumes it is possible to hit something in a later leaf with
+a smaller intercept fraction.
+==================
+*/
+void CM_TraceThroughTree( traceWork_t *tw, int num, float p1f, float p2f, vec3_t p1, vec3_t p2) {
+ cNode_t *node;
+ cplane_t *plane;
+ float t1, t2, offset;
+ float frac, frac2;
+ float idist;
+ vec3_t mid;
+ int side;
+ float midf;
+
+ if (tw->trace.fraction <= p1f) {
+ return; // already hit something nearer
+ }
+
+ // if < 0, we are in a leaf node
+ if (num < 0) {
+ CM_TraceThroughLeaf( tw, &cm.leafs[-1-num] );
+ return;
+ }
+
+ //
+ // find the point distances to the seperating plane
+ // and the offset for the size of the box
+ //
+ node = cm.nodes + num;
+ plane = node->plane;
+
+ // adjust the plane distance apropriately for mins/maxs
+ if ( plane->type < 3 ) {
+ t1 = p1[plane->type] - plane->dist;
+ t2 = p2[plane->type] - plane->dist;
+ offset = tw->extents[plane->type];
+ } else {
+ t1 = DotProduct (plane->normal, p1) - plane->dist;
+ t2 = DotProduct (plane->normal, p2) - plane->dist;
+ if ( tw->isPoint ) {
+ offset = 0;
+ } else {
+#if 0 // bk010201 - DEAD
+ // an axial brush right behind a slanted bsp plane
+ // will poke through when expanded, so adjust
+ // by sqrt(3)
+ offset = fabs(tw->extents[0]*plane->normal[0]) +
+ fabs(tw->extents[1]*plane->normal[1]) +
+ fabs(tw->extents[2]*plane->normal[2]);
+
+ offset *= 2;
+ offset = tw->maxOffset;
+#endif
+ // this is silly
+ offset = 2048;
+ }
+ }
+
+ // see which sides we need to consider
+ if ( t1 >= offset + 1 && t2 >= offset + 1 ) {
+ CM_TraceThroughTree( tw, node->children[0], p1f, p2f, p1, p2 );
+ return;
+ }
+ if ( t1 < -offset - 1 && t2 < -offset - 1 ) {
+ CM_TraceThroughTree( tw, node->children[1], p1f, p2f, p1, p2 );
+ return;
+ }
+
+ // put the crosspoint SURFACE_CLIP_EPSILON pixels on the near side
+ if ( t1 < t2 ) {
+ idist = 1.0/(t1-t2);
+ side = 1;
+ frac2 = (t1 + offset + SURFACE_CLIP_EPSILON)*idist;
+ frac = (t1 - offset + SURFACE_CLIP_EPSILON)*idist;
+ } else if (t1 > t2) {
+ idist = 1.0/(t1-t2);
+ side = 0;
+ frac2 = (t1 - offset - SURFACE_CLIP_EPSILON)*idist;
+ frac = (t1 + offset + SURFACE_CLIP_EPSILON)*idist;
+ } else {
+ side = 0;
+ frac = 1;
+ frac2 = 0;
+ }
+
+ // move up to the node
+ if ( frac < 0 ) {
+ frac = 0;
+ }
+ if ( frac > 1 ) {
+ frac = 1;
+ }
+
+ midf = p1f + (p2f - p1f)*frac;
+
+ mid[0] = p1[0] + frac*(p2[0] - p1[0]);
+ mid[1] = p1[1] + frac*(p2[1] - p1[1]);
+ mid[2] = p1[2] + frac*(p2[2] - p1[2]);
+
+ CM_TraceThroughTree( tw, node->children[side], p1f, midf, p1, mid );
+
+
+ // go past the node
+ if ( frac2 < 0 ) {
+ frac2 = 0;
+ }
+ if ( frac2 > 1 ) {
+ frac2 = 1;
+ }
+
+ midf = p1f + (p2f - p1f)*frac2;
+
+ mid[0] = p1[0] + frac2*(p2[0] - p1[0]);
+ mid[1] = p1[1] + frac2*(p2[1] - p1[1]);
+ mid[2] = p1[2] + frac2*(p2[2] - p1[2]);
+
+ CM_TraceThroughTree( tw, node->children[side^1], midf, p2f, mid, p2 );
+}
+
+
+//======================================================================
+
+
+/*
+==================
+CM_Trace
+==================
+*/
+void CM_Trace( trace_t *results, const vec3_t start, const vec3_t end, vec3_t mins, vec3_t maxs,
+ clipHandle_t model, const vec3_t origin, int brushmask, int capsule, sphere_t *sphere ) {
+ int i;
+ traceWork_t tw;
+ vec3_t offset;
+ cmodel_t *cmod;
+
+ cmod = CM_ClipHandleToModel( model );
+
+ cm.checkcount++; // for multi-check avoidance
+
+ c_traces++; // for statistics, may be zeroed
+
+ // fill in a default trace
+ Com_Memset( &tw, 0, sizeof(tw) );
+ tw.trace.fraction = 1; // assume it goes the entire distance until shown otherwise
+ VectorCopy(origin, tw.modelOrigin);
+
+ if (!cm.numNodes) {
+ *results = tw.trace;
+
+ return; // map not loaded, shouldn't happen
+ }
+
+ // allow NULL to be passed in for 0,0,0
+ if ( !mins ) {
+ mins = vec3_origin;
+ }
+ if ( !maxs ) {
+ maxs = vec3_origin;
+ }
+
+ // set basic parms
+ tw.contents = brushmask;
+
+ // adjust so that mins and maxs are always symetric, which
+ // avoids some complications with plane expanding of rotated
+ // bmodels
+ for ( i = 0 ; i < 3 ; i++ ) {
+ offset[i] = ( mins[i] + maxs[i] ) * 0.5;
+ tw.size[0][i] = mins[i] - offset[i];
+ tw.size[1][i] = maxs[i] - offset[i];
+ tw.start[i] = start[i] + offset[i];
+ tw.end[i] = end[i] + offset[i];
+ }
+
+ // if a sphere is already specified
+ if ( sphere ) {
+ tw.sphere = *sphere;
+ }
+ else {
+ tw.sphere.use = capsule;
+ tw.sphere.radius = ( tw.size[1][0] > tw.size[1][2] ) ? tw.size[1][2]: tw.size[1][0];
+ tw.sphere.halfheight = tw.size[1][2];
+ VectorSet( tw.sphere.offset, 0, 0, tw.size[1][2] - tw.sphere.radius );
+ }
+
+ tw.maxOffset = tw.size[1][0] + tw.size[1][1] + tw.size[1][2];
+
+ // tw.offsets[signbits] = vector to apropriate corner from origin
+ tw.offsets[0][0] = tw.size[0][0];
+ tw.offsets[0][1] = tw.size[0][1];
+ tw.offsets[0][2] = tw.size[0][2];
+
+ tw.offsets[1][0] = tw.size[1][0];
+ tw.offsets[1][1] = tw.size[0][1];
+ tw.offsets[1][2] = tw.size[0][2];
+
+ tw.offsets[2][0] = tw.size[0][0];
+ tw.offsets[2][1] = tw.size[1][1];
+ tw.offsets[2][2] = tw.size[0][2];
+
+ tw.offsets[3][0] = tw.size[1][0];
+ tw.offsets[3][1] = tw.size[1][1];
+ tw.offsets[3][2] = tw.size[0][2];
+
+ tw.offsets[4][0] = tw.size[0][0];
+ tw.offsets[4][1] = tw.size[0][1];
+ tw.offsets[4][2] = tw.size[1][2];
+
+ tw.offsets[5][0] = tw.size[1][0];
+ tw.offsets[5][1] = tw.size[0][1];
+ tw.offsets[5][2] = tw.size[1][2];
+
+ tw.offsets[6][0] = tw.size[0][0];
+ tw.offsets[6][1] = tw.size[1][1];
+ tw.offsets[6][2] = tw.size[1][2];
+
+ tw.offsets[7][0] = tw.size[1][0];
+ tw.offsets[7][1] = tw.size[1][1];
+ tw.offsets[7][2] = tw.size[1][2];
+
+ //
+ // calculate bounds
+ //
+ if ( tw.sphere.use ) {
+ for ( i = 0 ; i < 3 ; i++ ) {
+ if ( tw.start[i] < tw.end[i] ) {
+ tw.bounds[0][i] = tw.start[i] - fabs(tw.sphere.offset[i]) - tw.sphere.radius;
+ tw.bounds[1][i] = tw.end[i] + fabs(tw.sphere.offset[i]) + tw.sphere.radius;
+ } else {
+ tw.bounds[0][i] = tw.end[i] - fabs(tw.sphere.offset[i]) - tw.sphere.radius;
+ tw.bounds[1][i] = tw.start[i] + fabs(tw.sphere.offset[i]) + tw.sphere.radius;
+ }
+ }
+ }
+ else {
+ for ( i = 0 ; i < 3 ; i++ ) {
+ if ( tw.start[i] < tw.end[i] ) {
+ tw.bounds[0][i] = tw.start[i] + tw.size[0][i];
+ tw.bounds[1][i] = tw.end[i] + tw.size[1][i];
+ } else {
+ tw.bounds[0][i] = tw.end[i] + tw.size[0][i];
+ tw.bounds[1][i] = tw.start[i] + tw.size[1][i];
+ }
+ }
+ }
+
+ //
+ // check for position test special case
+ //
+ if (start[0] == end[0] && start[1] == end[1] && start[2] == end[2]) {
+ if ( model ) {
+#ifdef ALWAYS_BBOX_VS_BBOX // bk010201 - FIXME - compile time flag?
+ if ( model == BOX_MODEL_HANDLE || model == CAPSULE_MODEL_HANDLE) {
+ tw.sphere.use = qfalse;
+ CM_TestInLeaf( &tw, &cmod->leaf );
+ }
+ else
+#elif defined(ALWAYS_CAPSULE_VS_CAPSULE)
+ if ( model == BOX_MODEL_HANDLE || model == CAPSULE_MODEL_HANDLE) {
+ CM_TestCapsuleInCapsule( &tw, model );
+ }
+ else
+#endif
+ if ( model == CAPSULE_MODEL_HANDLE ) {
+ if ( tw.sphere.use ) {
+ CM_TestCapsuleInCapsule( &tw, model );
+ }
+ else {
+ CM_TestBoundingBoxInCapsule( &tw, model );
+ }
+ }
+ else {
+ CM_TestInLeaf( &tw, &cmod->leaf );
+ }
+ } else {
+ CM_PositionTest( &tw );
+ }
+ } else {
+ //
+ // check for point special case
+ //
+ if ( tw.size[0][0] == 0 && tw.size[0][1] == 0 && tw.size[0][2] == 0 ) {
+ tw.isPoint = qtrue;
+ VectorClear( tw.extents );
+ } else {
+ tw.isPoint = qfalse;
+ tw.extents[0] = tw.size[1][0];
+ tw.extents[1] = tw.size[1][1];
+ tw.extents[2] = tw.size[1][2];
+ }
+
+ //
+ // general sweeping through world
+ //
+ if ( model ) {
+#ifdef ALWAYS_BBOX_VS_BBOX
+ if ( model == BOX_MODEL_HANDLE || model == CAPSULE_MODEL_HANDLE) {
+ tw.sphere.use = qfalse;
+ CM_TraceThroughLeaf( &tw, &cmod->leaf );
+ }
+ else
+#elif defined(ALWAYS_CAPSULE_VS_CAPSULE)
+ if ( model == BOX_MODEL_HANDLE || model == CAPSULE_MODEL_HANDLE) {
+ CM_TraceCapsuleThroughCapsule( &tw, model );
+ }
+ else
+#endif
+ if ( model == CAPSULE_MODEL_HANDLE ) {
+ if ( tw.sphere.use ) {
+ CM_TraceCapsuleThroughCapsule( &tw, model );
+ }
+ else {
+ CM_TraceBoundingBoxThroughCapsule( &tw, model );
+ }
+ }
+ else {
+ CM_TraceThroughLeaf( &tw, &cmod->leaf );
+ }
+ } else {
+ CM_TraceThroughTree( &tw, 0, 0, 1, tw.start, tw.end );
+ }
+ }
+
+ // generate endpos from the original, unmodified start/end
+ if ( tw.trace.fraction == 1 ) {
+ VectorCopy (end, tw.trace.endpos);
+ } else {
+ for ( i=0 ; i<3 ; i++ ) {
+ tw.trace.endpos[i] = start[i] + tw.trace.fraction * (end[i] - start[i]);
+ }
+ }
+
+ // If allsolid is set (was entirely inside something solid), the plane is not valid.
+ // If fraction == 1.0, we never hit anything, and thus the plane is not valid.
+ // Otherwise, the normal on the plane should have unit length
+ assert(tw.trace.allsolid ||
+ tw.trace.fraction == 1.0 ||
+ VectorLengthSquared(tw.trace.plane.normal) > 0.9999);
+ *results = tw.trace;
+}
+
+/*
+==================
+CM_BoxTrace
+==================
+*/
+void CM_BoxTrace( trace_t *results, const vec3_t start, const vec3_t end,
+ vec3_t mins, vec3_t maxs,
+ clipHandle_t model, int brushmask, int capsule ) {
+ CM_Trace( results, start, end, mins, maxs, model, vec3_origin, brushmask, capsule, NULL );
+}
+
+/*
+==================
+CM_TransformedBoxTrace
+
+Handles offseting and rotation of the end points for moving and
+rotating entities
+==================
+*/
+void CM_TransformedBoxTrace( trace_t *results, const vec3_t start, const vec3_t end,
+ vec3_t mins, vec3_t maxs,
+ clipHandle_t model, int brushmask,
+ const vec3_t origin, const vec3_t angles, int capsule ) {
+ trace_t trace;
+ vec3_t start_l, end_l;
+ qboolean rotated;
+ vec3_t offset;
+ vec3_t symetricSize[2];
+ vec3_t matrix[3], transpose[3];
+ int i;
+ float halfwidth;
+ float halfheight;
+ float t;
+ sphere_t sphere;
+
+ if ( !mins ) {
+ mins = vec3_origin;
+ }
+ if ( !maxs ) {
+ maxs = vec3_origin;
+ }
+
+ // adjust so that mins and maxs are always symetric, which
+ // avoids some complications with plane expanding of rotated
+ // bmodels
+ for ( i = 0 ; i < 3 ; i++ ) {
+ offset[i] = ( mins[i] + maxs[i] ) * 0.5;
+ symetricSize[0][i] = mins[i] - offset[i];
+ symetricSize[1][i] = maxs[i] - offset[i];
+ start_l[i] = start[i] + offset[i];
+ end_l[i] = end[i] + offset[i];
+ }
+
+ // subtract origin offset
+ VectorSubtract( start_l, origin, start_l );
+ VectorSubtract( end_l, origin, end_l );
+
+ // rotate start and end into the models frame of reference
+ if ( model != BOX_MODEL_HANDLE &&
+ (angles[0] || angles[1] || angles[2]) ) {
+ rotated = qtrue;
+ } else {
+ rotated = qfalse;
+ }
+
+ halfwidth = symetricSize[ 1 ][ 0 ];
+ halfheight = symetricSize[ 1 ][ 2 ];
+
+ sphere.use = capsule;
+ sphere.radius = ( halfwidth > halfheight ) ? halfheight : halfwidth;
+ sphere.halfheight = halfheight;
+ t = halfheight - sphere.radius;
+
+ if (rotated) {
+ // rotation on trace line (start-end) instead of rotating the bmodel
+ // NOTE: This is still incorrect for bounding boxes because the actual bounding
+ // box that is swept through the model is not rotated. We cannot rotate
+ // the bounding box or the bmodel because that would make all the brush
+ // bevels invalid.
+ // However this is correct for capsules since a capsule itself is rotated too.
+ CreateRotationMatrix(angles, matrix);
+ RotatePoint(start_l, matrix);
+ RotatePoint(end_l, matrix);
+ // rotated sphere offset for capsule
+ sphere.offset[0] = matrix[0][ 2 ] * t;
+ sphere.offset[1] = -matrix[1][ 2 ] * t;
+ sphere.offset[2] = matrix[2][ 2 ] * t;
+ }
+ else {
+ VectorSet( sphere.offset, 0, 0, t );
+ }
+
+ // sweep the box through the model
+ CM_Trace( &trace, start_l, end_l, symetricSize[0], symetricSize[1], model, origin, brushmask, capsule, &sphere );
+
+ // if the bmodel was rotated and there was a collision
+ if ( rotated && trace.fraction != 1.0 ) {
+ // rotation of bmodel collision plane
+ TransposeMatrix(matrix, transpose);
+ RotatePoint(trace.plane.normal, transpose);
+ }
+
+ // re-calculate the end position of the trace because the trace.endpos
+ // calculated by CM_Trace could be rotated and have an offset
+ trace.endpos[0] = start[0] + trace.fraction * (end[0] - start[0]);
+ trace.endpos[1] = start[1] + trace.fraction * (end[1] - start[1]);
+ trace.endpos[2] = start[2] + trace.fraction * (end[2] - start[2]);
+
+ *results = trace;
+}
diff --git a/code/qcommon/cmd.c b/code/qcommon/cmd.c
new file mode 100755
index 0000000..08285f5
--- /dev/null
+++ b/code/qcommon/cmd.c
@@ -0,0 +1,715 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// cmd.c -- Quake script command processing module
+
+#include "../game/q_shared.h"
+#include "qcommon.h"
+
+#define MAX_CMD_BUFFER 16384
+#define MAX_CMD_LINE 1024
+
+typedef struct {
+ byte *data;
+ int maxsize;
+ int cursize;
+} cmd_t;
+
+int cmd_wait;
+cmd_t cmd_text;
+byte cmd_text_buf[MAX_CMD_BUFFER];
+
+
+//=============================================================================
+
+/*
+============
+Cmd_Wait_f
+
+Causes execution of the remainder of the command buffer to be delayed until
+next frame. This allows commands like:
+bind g "cmd use rocket ; +attack ; wait ; -attack ; cmd use blaster"
+============
+*/
+void Cmd_Wait_f( void ) {
+ if ( Cmd_Argc() == 2 ) {
+ cmd_wait = atoi( Cmd_Argv( 1 ) );
+ } else {
+ cmd_wait = 1;
+ }
+}
+
+
+/*
+=============================================================================
+
+ COMMAND BUFFER
+
+=============================================================================
+*/
+
+/*
+============
+Cbuf_Init
+============
+*/
+void Cbuf_Init (void)
+{
+ cmd_text.data = cmd_text_buf;
+ cmd_text.maxsize = MAX_CMD_BUFFER;
+ cmd_text.cursize = 0;
+}
+
+/*
+============
+Cbuf_AddText
+
+Adds command text at the end of the buffer, does NOT add a final \n
+============
+*/
+void Cbuf_AddText( const char *text ) {
+ int l;
+
+ l = strlen (text);
+
+ if (cmd_text.cursize + l >= cmd_text.maxsize)
+ {
+ Com_Printf ("Cbuf_AddText: overflow\n");
+ return;
+ }
+ Com_Memcpy(&cmd_text.data[cmd_text.cursize], text, l);
+ cmd_text.cursize += l;
+}
+
+
+/*
+============
+Cbuf_InsertText
+
+Adds command text immediately after the current command
+Adds a \n to the text
+============
+*/
+void Cbuf_InsertText( const char *text ) {
+ int len;
+ int i;
+
+ len = strlen( text ) + 1;
+ if ( len + cmd_text.cursize > cmd_text.maxsize ) {
+ Com_Printf( "Cbuf_InsertText overflowed\n" );
+ return;
+ }
+
+ // move the existing command text
+ for ( i = cmd_text.cursize - 1 ; i >= 0 ; i-- ) {
+ cmd_text.data[ i + len ] = cmd_text.data[ i ];
+ }
+
+ // copy the new text in
+ Com_Memcpy( cmd_text.data, text, len - 1 );
+
+ // add a \n
+ cmd_text.data[ len - 1 ] = '\n';
+
+ cmd_text.cursize += len;
+}
+
+
+/*
+============
+Cbuf_ExecuteText
+============
+*/
+void Cbuf_ExecuteText (int exec_when, const char *text)
+{
+ switch (exec_when)
+ {
+ case EXEC_NOW:
+ if (text && strlen(text) > 0) {
+ Cmd_ExecuteString (text);
+ } else {
+ Cbuf_Execute();
+ }
+ break;
+ case EXEC_INSERT:
+ Cbuf_InsertText (text);
+ break;
+ case EXEC_APPEND:
+ Cbuf_AddText (text);
+ break;
+ default:
+ Com_Error (ERR_FATAL, "Cbuf_ExecuteText: bad exec_when");
+ }
+}
+
+/*
+============
+Cbuf_Execute
+============
+*/
+void Cbuf_Execute (void)
+{
+ int i;
+ char *text;
+ char line[MAX_CMD_LINE];
+ int quotes;
+
+ while (cmd_text.cursize)
+ {
+ if ( cmd_wait ) {
+ // skip out while text still remains in buffer, leaving it
+ // for next frame
+ cmd_wait--;
+ break;
+ }
+
+ // find a \n or ; line break
+ text = (char *)cmd_text.data;
+
+ quotes = 0;
+ for (i=0 ; i< cmd_text.cursize ; i++)
+ {
+ if (text[i] == '"')
+ quotes++;
+ if ( !(quotes&1) && text[i] == ';')
+ break; // don't break if inside a quoted string
+ if (text[i] == '\n' || text[i] == '\r' )
+ break;
+ }
+
+ if( i >= (MAX_CMD_LINE - 1)) {
+ i = MAX_CMD_LINE - 1;
+ }
+
+ Com_Memcpy (line, text, i);
+ line[i] = 0;
+
+// delete the text from the command buffer and move remaining commands down
+// this is necessary because commands (exec) can insert data at the
+// beginning of the text buffer
+
+ if (i == cmd_text.cursize)
+ cmd_text.cursize = 0;
+ else
+ {
+ i++;
+ cmd_text.cursize -= i;
+ memmove (text, text+i, cmd_text.cursize);
+ }
+
+// execute the command line
+
+ Cmd_ExecuteString (line);
+ }
+}
+
+
+/*
+==============================================================================
+
+ SCRIPT COMMANDS
+
+==============================================================================
+*/
+
+
+/*
+===============
+Cmd_Exec_f
+===============
+*/
+void Cmd_Exec_f( void ) {
+ char *f;
+ int len;
+ char filename[MAX_QPATH];
+
+ if (Cmd_Argc () != 2) {
+ Com_Printf ("exec <filename> : execute a script file\n");
+ return;
+ }
+
+ Q_strncpyz( filename, Cmd_Argv(1), sizeof( filename ) );
+ COM_DefaultExtension( filename, sizeof( filename ), ".cfg" );
+ len = FS_ReadFile( filename, (void **)&f);
+ if (!f) {
+ Com_Printf ("couldn't exec %s\n",Cmd_Argv(1));
+ return;
+ }
+ Com_Printf ("execing %s\n",Cmd_Argv(1));
+
+ Cbuf_InsertText (f);
+
+ FS_FreeFile (f);
+}
+
+
+/*
+===============
+Cmd_Vstr_f
+
+Inserts the current value of a variable as command text
+===============
+*/
+void Cmd_Vstr_f( void ) {
+ char *v;
+
+ if (Cmd_Argc () != 2) {
+ Com_Printf ("vstr <variablename> : execute a variable command\n");
+ return;
+ }
+
+ v = Cvar_VariableString( Cmd_Argv( 1 ) );
+ Cbuf_InsertText( va("%s\n", v ) );
+}
+
+
+/*
+===============
+Cmd_Echo_f
+
+Just prints the rest of the line to the console
+===============
+*/
+void Cmd_Echo_f (void)
+{
+ int i;
+
+ for (i=1 ; i<Cmd_Argc() ; i++)
+ Com_Printf ("%s ",Cmd_Argv(i));
+ Com_Printf ("\n");
+}
+
+
+/*
+=============================================================================
+
+ COMMAND EXECUTION
+
+=============================================================================
+*/
+
+typedef struct cmd_function_s
+{
+ struct cmd_function_s *next;
+ char *name;
+ xcommand_t function;
+} cmd_function_t;
+
+
+static int cmd_argc;
+static char *cmd_argv[MAX_STRING_TOKENS]; // points into cmd_tokenized
+static char cmd_tokenized[BIG_INFO_STRING+MAX_STRING_TOKENS]; // will have 0 bytes inserted
+static char cmd_cmd[BIG_INFO_STRING]; // the original command we received (no token processing)
+
+static cmd_function_t *cmd_functions; // possible commands to execute
+
+/*
+============
+Cmd_Argc
+============
+*/
+int Cmd_Argc( void ) {
+ return cmd_argc;
+}
+
+/*
+============
+Cmd_Argv
+============
+*/
+char *Cmd_Argv( int arg ) {
+ if ( (unsigned)arg >= cmd_argc ) {
+ return "";
+ }
+ return cmd_argv[arg];
+}
+
+/*
+============
+Cmd_ArgvBuffer
+
+The interpreted versions use this because
+they can't have pointers returned to them
+============
+*/
+void Cmd_ArgvBuffer( int arg, char *buffer, int bufferLength ) {
+ Q_strncpyz( buffer, Cmd_Argv( arg ), bufferLength );
+}
+
+
+/*
+============
+Cmd_Args
+
+Returns a single string containing argv(1) to argv(argc()-1)
+============
+*/
+char *Cmd_Args( void ) {
+ static char cmd_args[MAX_STRING_CHARS];
+ int i;
+
+ cmd_args[0] = 0;
+ for ( i = 1 ; i < cmd_argc ; i++ ) {
+ strcat( cmd_args, cmd_argv[i] );
+ if ( i != cmd_argc-1 ) {
+ strcat( cmd_args, " " );
+ }
+ }
+
+ return cmd_args;
+}
+
+/*
+============
+Cmd_Args
+
+Returns a single string containing argv(arg) to argv(argc()-1)
+============
+*/
+char *Cmd_ArgsFrom( int arg ) {
+ static char cmd_args[BIG_INFO_STRING];
+ int i;
+
+ cmd_args[0] = 0;
+ if (arg < 0)
+ arg = 0;
+ for ( i = arg ; i < cmd_argc ; i++ ) {
+ strcat( cmd_args, cmd_argv[i] );
+ if ( i != cmd_argc-1 ) {
+ strcat( cmd_args, " " );
+ }
+ }
+
+ return cmd_args;
+}
+
+/*
+============
+Cmd_ArgsBuffer
+
+The interpreted versions use this because
+they can't have pointers returned to them
+============
+*/
+void Cmd_ArgsBuffer( char *buffer, int bufferLength ) {
+ Q_strncpyz( buffer, Cmd_Args(), bufferLength );
+}
+
+/*
+============
+Cmd_Cmd
+
+Retrieve the unmodified command string
+For rcon use when you want to transmit without altering quoting
+https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=543
+============
+*/
+char *Cmd_Cmd()
+{
+ return cmd_cmd;
+}
+
+/*
+============
+Cmd_TokenizeString
+
+Parses the given string into command line tokens.
+The text is copied to a seperate buffer and 0 characters
+are inserted in the apropriate place, The argv array
+will point into this temporary buffer.
+============
+*/
+// NOTE TTimo define that to track tokenization issues
+//#define TKN_DBG
+void Cmd_TokenizeString( const char *text_in ) {
+ const char *text;
+ char *textOut;
+
+#ifdef TKN_DBG
+ // FIXME TTimo blunt hook to try to find the tokenization of userinfo
+ Com_DPrintf("Cmd_TokenizeString: %s\n", text_in);
+#endif
+
+ // clear previous args
+ cmd_argc = 0;
+
+ if ( !text_in ) {
+ return;
+ }
+
+ Q_strncpyz( cmd_cmd, text_in, sizeof(cmd_cmd) );
+
+ text = text_in;
+ textOut = cmd_tokenized;
+
+ while ( 1 ) {
+ if ( cmd_argc == MAX_STRING_TOKENS ) {
+ return; // this is usually something malicious
+ }
+
+ while ( 1 ) {
+ // skip whitespace
+ while ( *text && *text <= ' ' ) {
+ text++;
+ }
+ if ( !*text ) {
+ return; // all tokens parsed
+ }
+
+ // skip // comments
+ if ( text[0] == '/' && text[1] == '/' ) {
+ return; // all tokens parsed
+ }
+
+ // skip /* */ comments
+ if ( text[0] == '/' && text[1] =='*' ) {
+ while ( *text && ( text[0] != '*' || text[1] != '/' ) ) {
+ text++;
+ }
+ if ( !*text ) {
+ return; // all tokens parsed
+ }
+ text += 2;
+ } else {
+ break; // we are ready to parse a token
+ }
+ }
+
+ // handle quoted strings
+ // NOTE TTimo this doesn't handle \" escaping
+ if ( *text == '"' ) {
+ cmd_argv[cmd_argc] = textOut;
+ cmd_argc++;
+ text++;
+ while ( *text && *text != '"' ) {
+ *textOut++ = *text++;
+ }
+ *textOut++ = 0;
+ if ( !*text ) {
+ return; // all tokens parsed
+ }
+ text++;
+ continue;
+ }
+
+ // regular token
+ cmd_argv[cmd_argc] = textOut;
+ cmd_argc++;
+
+ // skip until whitespace, quote, or command
+ while ( *text > ' ' ) {
+ if ( text[0] == '"' ) {
+ break;
+ }
+
+ if ( text[0] == '/' && text[1] == '/' ) {
+ break;
+ }
+
+ // skip /* */ comments
+ if ( text[0] == '/' && text[1] =='*' ) {
+ break;
+ }
+
+ *textOut++ = *text++;
+ }
+
+ *textOut++ = 0;
+
+ if ( !*text ) {
+ return; // all tokens parsed
+ }
+ }
+
+}
+
+
+/*
+============
+Cmd_AddCommand
+============
+*/
+void Cmd_AddCommand( const char *cmd_name, xcommand_t function ) {
+ cmd_function_t *cmd;
+
+ // fail if the command already exists
+ for ( cmd = cmd_functions ; cmd ; cmd=cmd->next ) {
+ if ( !strcmp( cmd_name, cmd->name ) ) {
+ // allow completion-only commands to be silently doubled
+ if ( function != NULL ) {
+ Com_Printf ("Cmd_AddCommand: %s already defined\n", cmd_name);
+ }
+ return;
+ }
+ }
+
+ // use a small malloc to avoid zone fragmentation
+ cmd = S_Malloc (sizeof(cmd_function_t));
+ cmd->name = CopyString( cmd_name );
+ cmd->function = function;
+ cmd->next = cmd_functions;
+ cmd_functions = cmd;
+}
+
+/*
+============
+Cmd_RemoveCommand
+============
+*/
+void Cmd_RemoveCommand( const char *cmd_name ) {
+ cmd_function_t *cmd, **back;
+
+ back = &cmd_functions;
+ while( 1 ) {
+ cmd = *back;
+ if ( !cmd ) {
+ // command wasn't active
+ return;
+ }
+ if ( !strcmp( cmd_name, cmd->name ) ) {
+ *back = cmd->next;
+ if (cmd->name) {
+ Z_Free(cmd->name);
+ }
+ Z_Free (cmd);
+ return;
+ }
+ back = &cmd->next;
+ }
+}
+
+
+/*
+============
+Cmd_CommandCompletion
+============
+*/
+void Cmd_CommandCompletion( void(*callback)(const char *s) ) {
+ cmd_function_t *cmd;
+
+ for (cmd=cmd_functions ; cmd ; cmd=cmd->next) {
+ callback( cmd->name );
+ }
+}
+
+
+/*
+============
+Cmd_ExecuteString
+
+A complete command line has been parsed, so try to execute it
+============
+*/
+void Cmd_ExecuteString( const char *text ) {
+ cmd_function_t *cmd, **prev;
+
+ // execute the command line
+ Cmd_TokenizeString( text );
+ if ( !Cmd_Argc() ) {
+ return; // no tokens
+ }
+
+ // check registered command functions
+ for ( prev = &cmd_functions ; *prev ; prev = &cmd->next ) {
+ cmd = *prev;
+ if ( !Q_stricmp( cmd_argv[0],cmd->name ) ) {
+ // rearrange the links so that the command will be
+ // near the head of the list next time it is used
+ *prev = cmd->next;
+ cmd->next = cmd_functions;
+ cmd_functions = cmd;
+
+ // perform the action
+ if ( !cmd->function ) {
+ // let the cgame or game handle it
+ break;
+ } else {
+ cmd->function ();
+ }
+ return;
+ }
+ }
+
+ // check cvars
+ if ( Cvar_Command() ) {
+ return;
+ }
+
+ // check client game commands
+ if ( com_cl_running && com_cl_running->integer && CL_GameCommand() ) {
+ return;
+ }
+
+ // check server game commands
+ if ( com_sv_running && com_sv_running->integer && SV_GameCommand() ) {
+ return;
+ }
+
+ // check ui commands
+ if ( com_cl_running && com_cl_running->integer && UI_GameCommand() ) {
+ return;
+ }
+
+ // send it as a server command if we are connected
+ // this will usually result in a chat message
+ CL_ForwardCommandToServer ( text );
+}
+
+/*
+============
+Cmd_List_f
+============
+*/
+void Cmd_List_f (void)
+{
+ cmd_function_t *cmd;
+ int i;
+ char *match;
+
+ if ( Cmd_Argc() > 1 ) {
+ match = Cmd_Argv( 1 );
+ } else {
+ match = NULL;
+ }
+
+ i = 0;
+ for (cmd=cmd_functions ; cmd ; cmd=cmd->next) {
+ if (match && !Com_Filter(match, cmd->name, qfalse)) continue;
+
+ Com_Printf ("%s\n", cmd->name);
+ i++;
+ }
+ Com_Printf ("%i commands\n", i);
+}
+
+/*
+============
+Cmd_Init
+============
+*/
+void Cmd_Init (void) {
+ Cmd_AddCommand ("cmdlist",Cmd_List_f);
+ Cmd_AddCommand ("exec",Cmd_Exec_f);
+ Cmd_AddCommand ("vstr",Cmd_Vstr_f);
+ Cmd_AddCommand ("echo",Cmd_Echo_f);
+ Cmd_AddCommand ("wait", Cmd_Wait_f);
+}
+
diff --git a/code/qcommon/cmd.c.save b/code/qcommon/cmd.c.save
new file mode 100755
index 0000000..0bf9602
--- /dev/null
+++ b/code/qcommon/cmd.c.save
@@ -0,0 +1,636 @@
+// cmd.c -- Quake script command processing module
+
+#include "../game/q_shared.h"
+#include "qcommon.h"
+
+#define MAX_CMD_BUFFER 8192
+int cmd_wait;
+msg_t cmd_text;
+byte cmd_text_buf[MAX_CMD_BUFFER];
+char cmd_defer_text_buf[MAX_CMD_BUFFER];
+
+
+//=============================================================================
+
+/*
+============
+Cmd_Wait_f
+
+Causes execution of the remainder of the command buffer to be delayed until
+next frame. This allows commands like:
+bind g "cmd use rocket ; +attack ; wait ; -attack ; cmd use blaster"
+============
+*/
+void Cmd_Wait_f( void ) {
+ if ( Cmd_Argc() == 2 ) {
+ cmd_wait = atoi( Cmd_Argv( 1 ) );
+ } else {
+ cmd_wait = 1;
+ }
+}
+
+
+/*
+=============================================================================
+
+ COMMAND BUFFER
+
+=============================================================================
+*/
+
+/*
+============
+Cbuf_Init
+============
+*/
+void Cbuf_Init (void)
+{
+ MSG_Init (&cmd_text, cmd_text_buf, sizeof(cmd_text_buf));
+}
+
+/*
+============
+Cbuf_AddText
+
+Adds command text at the end of the buffer, does NOT add a final \n
+============
+*/
+void Cbuf_AddText( const char *text ) {
+ int l;
+
+ l = strlen (text);
+
+ if (cmd_text.cursize + l >= cmd_text.maxsize)
+ {
+ Com_Printf ("Cbuf_AddText: overflow\n");
+ return;
+ }
+ MSG_WriteData (&cmd_text, text, strlen (text));
+}
+
+
+/*
+============
+Cbuf_InsertText
+
+Adds command text immediately after the current command
+Adds a \n to the text
+============
+*/
+void Cbuf_InsertText( const char *text ) {
+ int len;
+ int i;
+
+ len = strlen( text ) + 1;
+ if ( len + cmd_text.cursize > cmd_text.maxsize ) {
+ Com_Printf( "Cbuf_InsertText overflowed\n" );
+ return;
+ }
+
+ // move the existing command text
+ for ( i = cmd_text.cursize - 1 ; i >= 0 ; i-- ) {
+ cmd_text.data[ i + len ] = cmd_text.data[ i ];
+ }
+
+ // copy the new text in
+ memcpy( cmd_text.data, text, len - 1 );
+
+ // add a \n
+ cmd_text.data[ len - 1 ] = '\n';
+
+ cmd_text.cursize += len;
+}
+
+
+/*
+============
+Cbuf_ExecuteText
+============
+*/
+void Cbuf_ExecuteText (int exec_when, const char *text)
+{
+ switch (exec_when)
+ {
+ case EXEC_NOW:
+ Cmd_ExecuteString (text);
+ break;
+ case EXEC_INSERT:
+ Cbuf_InsertText (text);
+ break;
+ case EXEC_APPEND:
+ Cbuf_AddText (text);
+ break;
+ default:
+ Com_Error (ERR_FATAL, "Cbuf_ExecuteText: bad exec_when");
+ }
+}
+
+/*
+============
+Cbuf_Execute
+============
+*/
+void Cbuf_Execute (void)
+{
+ int i;
+ char *text;
+ char line[MAX_CMD_BUFFER];
+ int quotes;
+
+ while (cmd_text.cursize)
+ {
+ if ( cmd_wait ) {
+ // skip out while text still remains in buffer, leaving it
+ // for next frame
+ cmd_wait--;
+ break;
+ }
+
+ // find a \n or ; line break
+ text = (char *)cmd_text.data;
+
+ quotes = 0;
+ for (i=0 ; i< cmd_text.cursize ; i++)
+ {
+ if (text[i] == '"')
+ quotes++;
+ if ( !(quotes&1) && text[i] == ';')
+ break; // don't break if inside a quoted string
+ if (text[i] == '\n' || text[i] == '\r' )
+ break;
+ }
+
+
+ memcpy (line, text, i);
+ line[i] = 0;
+
+// delete the text from the command buffer and move remaining commands down
+// this is necessary because commands (exec) can insert data at the
+// beginning of the text buffer
+
+ if (i == cmd_text.cursize)
+ cmd_text.cursize = 0;
+ else
+ {
+ i++;
+ cmd_text.cursize -= i;
+ memmove (text, text+i, cmd_text.cursize);
+ text[cmd_text.cursize] = 0;
+ }
+
+// execute the command line
+ Cmd_ExecuteString (line);
+ }
+}
+
+
+/*
+==============================================================================
+
+ SCRIPT COMMANDS
+
+==============================================================================
+*/
+
+
+/*
+===============
+Cmd_Exec_f
+===============
+*/
+void Cmd_Exec_f( void ) {
+ fileHandle_t f;
+ int len;
+ char filename[MAX_QPATH];
+ char *buffer;
+
+ if (Cmd_Argc () != 2) {
+ Com_Printf ("exec <filename> : execute a script file\n");
+ return;
+ }
+
+ Q_strncpyz( filename, Cmd_Argv(1), sizeof( filename ) );
+ COM_DefaultExtension( filename, sizeof( filename ), ".cfg" );
+ len = FS_FOpenFileRead( filename, &f, qfalse );
+ if ( len <= 0 ) {
+ Com_Printf ("Couldn't read %s.\n", filename );
+ return;
+ }
+
+ buffer = Z_Malloc(len+1);
+
+ if (FS_Read(buffer, len, f) == len) {
+ FS_FCloseFile( f );
+ buffer[len] = 0;
+ Com_Printf ("execing %s\n",Cmd_Argv(1));
+ Cbuf_InsertText (buffer);
+ }
+ else {
+ Com_Printf ("couldn't exec %s\n",Cmd_Argv(1));
+ }
+
+ Z_Free(buffer);
+}
+
+
+/*
+===============
+Cmd_Vstr_f
+
+Inserts the current value of a variable as command text
+===============
+*/
+void Cmd_Vstr_f( void ) {
+ char *v;
+
+ if (Cmd_Argc () != 2) {
+ Com_Printf ("vstr <variablename> : execute a variable command\n");
+ return;
+ }
+
+ v = Cvar_VariableString( Cmd_Argv( 1 ) );
+ Cbuf_InsertText( va("%s\n", v ) );
+}
+
+
+/*
+===============
+Cmd_Echo_f
+
+Just prints the rest of the line to the console
+===============
+*/
+void Cmd_Echo_f (void)
+{
+ int i;
+
+ for (i=1 ; i<Cmd_Argc() ; i++)
+ Com_Printf ("%s ",Cmd_Argv(i));
+ Com_Printf ("\n");
+}
+
+
+/*
+=============================================================================
+
+ COMMAND EXECUTION
+
+=============================================================================
+*/
+
+typedef struct cmd_function_s
+{
+ struct cmd_function_s *next;
+ char *name;
+ xcommand_t function;
+} cmd_function_t;
+
+
+static int cmd_argc;
+static char *cmd_argv[MAX_STRING_TOKENS]; // points into cmd_tokenized
+static char cmd_tokenized[MAX_STRING_CHARS+MAX_STRING_TOKENS]; // will have 0 bytes inserted
+
+static cmd_function_t *cmd_functions; // possible commands to execute
+
+/*
+============
+Cmd_Argc
+============
+*/
+int Cmd_Argc( void ) {
+ return cmd_argc;
+}
+
+/*
+============
+Cmd_Argv
+============
+*/
+char *Cmd_Argv( int arg ) {
+ if ( (unsigned)arg >= cmd_argc ) {
+ return "";
+ }
+ return cmd_argv[arg];
+}
+
+/*
+============
+Cmd_ArgvBuffer
+
+The interpreted versions use this because
+they can't have pointers returned to them
+============
+*/
+void Cmd_ArgvBuffer( int arg, char *buffer, int bufferLength ) {
+ Q_strncpyz( buffer, Cmd_Argv( arg ), bufferLength );
+}
+
+
+/*
+============
+Cmd_Args
+
+Returns a single string containing argv(1) to argv(argc()-1)
+============
+*/
+char *Cmd_Args( void ) {
+ static char cmd_args[MAX_STRING_CHARS];
+ int i;
+
+ cmd_args[0] = 0;
+ for ( i = 1 ; i < cmd_argc ; i++ ) {
+ strcat( cmd_args, cmd_argv[i] );
+ if ( i != cmd_argc ) {
+ strcat( cmd_args, " " );
+ }
+ }
+
+ return cmd_args;
+}
+
+
+/*
+============
+Cmd_ArgsBuffer
+
+The interpreted versions use this because
+they can't have pointers returned to them
+============
+*/
+void Cmd_ArgsBuffer( char *buffer, int bufferLength ) {
+ Q_strncpyz( buffer, Cmd_Args(), bufferLength );
+}
+
+
+/*
+============
+Cmd_TokenizeString
+
+Parses the given string into command line tokens.
+The text is copied to a seperate buffer and 0 characters
+are inserted in the apropriate place, The argv array
+will point into this temporary buffer.
+============
+*/
+void Cmd_TokenizeString( const char *text_in ) {
+ const char *text;
+ char *textOut;
+
+ // clear previous args
+ cmd_argc = 0;
+
+ if ( !text_in ) {
+ return;
+ }
+
+ text = text_in;
+ textOut = cmd_tokenized;
+
+ while ( 1 ) {
+ if ( cmd_argc == MAX_STRING_TOKENS ) {
+ return; // this is usually something malicious
+ }
+
+ while ( 1 ) {
+ // skip whitespace
+ while ( *text && *text <= ' ' ) {
+ text++;
+ }
+ if ( !*text ) {
+ return; // all tokens parsed
+ }
+
+ // skip // comments
+ if ( text[0] == '/' && text[1] == '/' ) {
+ return; // all tokens parsed
+ }
+
+ // skip /* */ comments
+ if ( text[0] == '/' && text[1] =='*' ) {
+ while ( *text && ( text[0] != '*' || text[1] != '/' ) ) {
+ text++;
+ }
+ if ( !*text ) {
+ return; // all tokens parsed
+ }
+ text += 2;
+ } else {
+ break; // we are ready to parse a token
+ }
+ }
+
+ // handle quoted strings
+ if ( *text == '"' ) {
+ cmd_argv[cmd_argc] = textOut;
+ cmd_argc++;
+ text++;
+ while ( *text && *text != '"' ) {
+ *textOut++ = *text++;
+ }
+ *textOut++ = 0;
+ if ( !*text ) {
+ return; // all tokens parsed
+ }
+ text++;
+ continue;
+ }
+
+ // regular token
+ cmd_argv[cmd_argc] = textOut;
+ cmd_argc++;
+
+ // skip until whitespace, quote, or command
+ while ( *text > ' ' ) {
+ if ( text[0] == '"' ) {
+ break;
+ }
+
+ if ( text[0] == '/' && text[1] == '/' ) {
+ break;
+ }
+
+ // skip /* */ comments
+ if ( text[0] == '/' && text[1] =='*' ) {
+ break;
+ }
+
+ *textOut++ = *text++;
+ }
+
+ *textOut++ = 0;
+
+ if ( !*text ) {
+ return; // all tokens parsed
+ }
+ }
+
+}
+
+
+/*
+============
+Cmd_AddCommand
+============
+*/
+void Cmd_AddCommand( const char *cmd_name, xcommand_t function ) {
+ cmd_function_t *cmd;
+
+ // fail if the command already exists
+ for ( cmd = cmd_functions ; cmd ; cmd=cmd->next ) {
+ if ( !strcmp( cmd_name, cmd->name ) ) {
+ // allow completion-only commands to be silently doubled
+ if ( function != NULL ) {
+ Com_Printf ("Cmd_AddCommand: %s already defined\n", cmd_name);
+ }
+ return;
+ }
+ }
+
+ cmd = Z_Malloc (sizeof(cmd_function_t));
+ cmd->name = CopyString( cmd_name );
+ cmd->function = function;
+ cmd->next = cmd_functions;
+ cmd_functions = cmd;
+}
+
+/*
+============
+Cmd_RemoveCommand
+============
+*/
+void Cmd_RemoveCommand( const char *cmd_name ) {
+ cmd_function_t *cmd, **back;
+
+ back = &cmd_functions;
+ while( 1 ) {
+ cmd = *back;
+ if ( !cmd ) {
+ // command wasn't active
+ return;
+ }
+ if ( !strcmp( cmd_name, cmd->name ) ) {
+ *back = cmd->next;
+ Z_Free (cmd);
+ return;
+ }
+ back = &cmd->next;
+ }
+}
+
+
+/*
+============
+Cmd_CommandCompletion
+============
+*/
+void Cmd_CommandCompletion( void(*callback)(const char *s) ) {
+ cmd_function_t *cmd;
+
+ for (cmd=cmd_functions ; cmd ; cmd=cmd->next) {
+ callback( cmd->name );
+ }
+}
+
+
+/*
+============
+Cmd_ExecuteString
+
+A complete command line has been parsed, so try to execute it
+============
+*/
+void Cmd_ExecuteString( const char *text ) {
+ cmd_function_t *cmd, **prev;
+
+ // execute the command line
+ Cmd_TokenizeString( text );
+ if ( !Cmd_Argc() ) {
+ return; // no tokens
+ }
+
+ // check registered command functions
+ for ( prev = &cmd_functions ; *prev ; prev = &cmd->next ) {
+ cmd = *prev;
+ if ( !Q_stricmp( cmd_argv[0],cmd->name ) ) {
+ // rearrange the links so that the command will be
+ // near the head of the list next time it is used
+ *prev = cmd->next;
+ cmd->next = cmd_functions;
+ cmd_functions = cmd;
+
+ // perform the action
+ if ( !cmd->function ) {
+ // let the cgame or game handle it
+ break;
+ } else {
+ cmd->function ();
+ }
+ return;
+ }
+ }
+
+ // check cvars
+ if ( Cvar_Command() ) {
+ return;
+ }
+
+ // check client game commands
+ if ( com_cl_running && com_cl_running->integer && CL_GameCommand() ) {
+ return;
+ }
+
+ // check server game commands
+ if ( com_sv_running && com_sv_running->integer && SV_GameCommand() ) {
+ return;
+ }
+
+ // check ui commands
+ if ( com_cl_running && com_cl_running->integer && UI_GameCommand() ) {
+ return;
+ }
+
+ // send it as a server command if we are connected
+ // this will usually result in a chat message
+ CL_ForwardCommandToServer ();
+}
+
+/*
+============
+Cmd_List_f
+============
+*/
+void Cmd_List_f (void)
+{
+ cmd_function_t *cmd;
+ int i;
+ char *match;
+
+ if ( Cmd_Argc() > 1 ) {
+ match = Cmd_Argv( 1 );
+ } else {
+ match = NULL;
+ }
+
+ i = 0;
+ for (cmd=cmd_functions ; cmd ; cmd=cmd->next) {
+ if (match && !Com_Filter(match, cmd->name, qfalse)) continue;
+
+ Com_Printf ("%s\n", cmd->name);
+ i++;
+ }
+ Com_Printf ("%i commands\n", i);
+}
+
+/*
+============
+Cmd_Init
+============
+*/
+void Cmd_Init (void) {
+ Cmd_AddCommand ("cmdlist",Cmd_List_f);
+ Cmd_AddCommand ("exec",Cmd_Exec_f);
+ Cmd_AddCommand ("vstr",Cmd_Vstr_f);
+ Cmd_AddCommand ("echo",Cmd_Echo_f);
+ Cmd_AddCommand ("wait", Cmd_Wait_f);
+}
+
diff --git a/code/qcommon/common.c b/code/qcommon/common.c
new file mode 100755
index 0000000..24acc5b
--- /dev/null
+++ b/code/qcommon/common.c
@@ -0,0 +1,3317 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// common.c -- misc functions used in client and server
+
+#include "../game/q_shared.h"
+#include "qcommon.h"
+#include <setjmp.h>
+#ifdef __linux__
+#include <netinet/in.h>
+#else
+#if defined(MACOS_X)
+#include <netinet/in.h>
+#else
+#include <winsock.h>
+#endif
+#endif
+
+int demo_protocols[] =
+{ 66, 67, 68, 0 };
+
+#define MAX_NUM_ARGVS 50
+
+#define MIN_DEDICATED_COMHUNKMEGS 1
+#define MIN_COMHUNKMEGS 56
+#ifdef MACOS_X
+#define DEF_COMHUNKMEGS "64"
+#define DEF_COMZONEMEGS "24"
+#else
+#define DEF_COMHUNKMEGS "56"
+#define DEF_COMZONEMEGS "16"
+#endif
+
+int com_argc;
+char *com_argv[MAX_NUM_ARGVS+1];
+
+jmp_buf abortframe; // an ERR_DROP occured, exit the entire frame
+
+
+FILE *debuglogfile;
+static fileHandle_t logfile;
+fileHandle_t com_journalFile; // events are written here
+fileHandle_t com_journalDataFile; // config files are written here
+
+cvar_t *com_viewlog;
+cvar_t *com_speeds;
+cvar_t *com_developer;
+cvar_t *com_dedicated;
+cvar_t *com_timescale;
+cvar_t *com_fixedtime;
+cvar_t *com_dropsim; // 0.0 to 1.0, simulated packet drops
+cvar_t *com_journal;
+cvar_t *com_maxfps;
+cvar_t *com_timedemo;
+cvar_t *com_sv_running;
+cvar_t *com_cl_running;
+cvar_t *com_logfile; // 1 = buffer log, 2 = flush after each print
+cvar_t *com_showtrace;
+cvar_t *com_version;
+cvar_t *com_blood;
+cvar_t *com_buildScript; // for automated data building scripts
+cvar_t *com_introPlayed;
+cvar_t *cl_paused;
+cvar_t *sv_paused;
+cvar_t *com_cameraMode;
+#if defined(_WIN32) && defined(_DEBUG)
+cvar_t *com_noErrorInterrupt;
+#endif
+
+// com_speeds times
+int time_game;
+int time_frontend; // renderer frontend time
+int time_backend; // renderer backend time
+
+int com_frameTime;
+int com_frameMsec;
+int com_frameNumber;
+
+qboolean com_errorEntered;
+qboolean com_fullyInitialized;
+
+char com_errorMessage[MAXPRINTMSG];
+
+void Com_WriteConfig_f( void );
+void CIN_CloseAllVideos();
+
+//============================================================================
+
+static char *rd_buffer;
+static int rd_buffersize;
+static void (*rd_flush)( char *buffer );
+
+void Com_BeginRedirect (char *buffer, int buffersize, void (*flush)( char *) )
+{
+ if (!buffer || !buffersize || !flush)
+ return;
+ rd_buffer = buffer;
+ rd_buffersize = buffersize;
+ rd_flush = flush;
+
+ *rd_buffer = 0;
+}
+
+void Com_EndRedirect (void)
+{
+ if ( rd_flush ) {
+ rd_flush(rd_buffer);
+ }
+
+ rd_buffer = NULL;
+ rd_buffersize = 0;
+ rd_flush = NULL;
+}
+
+/*
+=============
+Com_Printf
+
+Both client and server can use this, and it will output
+to the apropriate place.
+
+A raw string should NEVER be passed as fmt, because of "%f" type crashers.
+=============
+*/
+void QDECL Com_Printf( const char *fmt, ... ) {
+ va_list argptr;
+ char msg[MAXPRINTMSG];
+ static qboolean opening_qconsole = qfalse;
+
+ va_start (argptr,fmt);
+ Q_vsnprintf (msg, sizeof(msg), fmt, argptr);
+ va_end (argptr);
+
+ if ( rd_buffer ) {
+ if ((strlen (msg) + strlen(rd_buffer)) > (rd_buffersize - 1)) {
+ rd_flush(rd_buffer);
+ *rd_buffer = 0;
+ }
+ Q_strcat(rd_buffer, rd_buffersize, msg);
+ // TTimo nooo .. that would defeat the purpose
+ //rd_flush(rd_buffer);
+ //*rd_buffer = 0;
+ return;
+ }
+
+ // echo to console if we're not a dedicated server
+ if ( com_dedicated && !com_dedicated->integer ) {
+ CL_ConsolePrint( msg );
+ }
+
+ // echo to dedicated console and early console
+ Sys_Print( msg );
+
+ // logfile
+ if ( com_logfile && com_logfile->integer ) {
+ // TTimo: only open the qconsole.log if the filesystem is in an initialized state
+ // also, avoid recursing in the qconsole.log opening (i.e. if fs_debug is on)
+ if ( !logfile && FS_Initialized() && !opening_qconsole) {
+ struct tm *newtime;
+ time_t aclock;
+
+ opening_qconsole = qtrue;
+
+ time( &aclock );
+ newtime = localtime( &aclock );
+
+ logfile = FS_FOpenFileWrite( "qconsole.log" );
+ Com_Printf( "logfile opened on %s\n", asctime( newtime ) );
+ if ( com_logfile->integer > 1 ) {
+ // force it to not buffer so we get valid
+ // data even if we are crashing
+ FS_ForceFlush(logfile);
+ }
+
+ opening_qconsole = qfalse;
+ }
+ if ( logfile && FS_Initialized()) {
+ FS_Write(msg, strlen(msg), logfile);
+ }
+ }
+}
+
+
+/*
+================
+Com_DPrintf
+
+A Com_Printf that only shows up if the "developer" cvar is set
+================
+*/
+void QDECL Com_DPrintf( const char *fmt, ...) {
+ va_list argptr;
+ char msg[MAXPRINTMSG];
+
+ if ( !com_developer || !com_developer->integer ) {
+ return; // don't confuse non-developers with techie stuff...
+ }
+
+ va_start (argptr,fmt);
+ Q_vsnprintf (msg, sizeof(msg), fmt, argptr);
+ va_end (argptr);
+
+ Com_Printf ("%s", msg);
+}
+
+/*
+=============
+Com_Error
+
+Both client and server can use this, and it will
+do the apropriate things.
+=============
+*/
+void QDECL Com_Error( int code, const char *fmt, ... ) {
+ va_list argptr;
+ static int lastErrorTime;
+ static int errorCount;
+ int currentTime;
+
+#if defined(_WIN32) && defined(_DEBUG)
+ if ( code != ERR_DISCONNECT && code != ERR_NEED_CD ) {
+ if (!com_noErrorInterrupt->integer) {
+ __asm {
+ int 0x03
+ }
+ }
+ }
+#endif
+
+ // when we are running automated scripts, make sure we
+ // know if anything failed
+ if ( com_buildScript && com_buildScript->integer ) {
+ code = ERR_FATAL;
+ }
+
+ // make sure we can get at our local stuff
+ FS_PureServerSetLoadedPaks( "", "" );
+
+ // if we are getting a solid stream of ERR_DROP, do an ERR_FATAL
+ currentTime = Sys_Milliseconds();
+ if ( currentTime - lastErrorTime < 100 ) {
+ if ( ++errorCount > 3 ) {
+ code = ERR_FATAL;
+ }
+ } else {
+ errorCount = 0;
+ }
+ lastErrorTime = currentTime;
+
+ if ( com_errorEntered ) {
+ Sys_Error( "recursive error after: %s", com_errorMessage );
+ }
+ com_errorEntered = qtrue;
+
+ va_start (argptr,fmt);
+ vsprintf (com_errorMessage,fmt,argptr);
+ va_end (argptr);
+
+ if ( code != ERR_DISCONNECT && code != ERR_NEED_CD ) {
+ Cvar_Set("com_errorMessage", com_errorMessage);
+ }
+
+ if ( code == ERR_SERVERDISCONNECT ) {
+ CL_Disconnect( qtrue );
+ CL_FlushMemory( );
+ com_errorEntered = qfalse;
+ longjmp (abortframe, -1);
+ } else if ( code == ERR_DROP || code == ERR_DISCONNECT ) {
+ Com_Printf ("********************\nERROR: %s\n********************\n", com_errorMessage);
+ SV_Shutdown (va("Server crashed: %s\n", com_errorMessage));
+ CL_Disconnect( qtrue );
+ CL_FlushMemory( );
+ com_errorEntered = qfalse;
+ longjmp (abortframe, -1);
+ } else if ( code == ERR_NEED_CD ) {
+ SV_Shutdown( "Server didn't have CD\n" );
+ if ( com_cl_running && com_cl_running->integer ) {
+ CL_Disconnect( qtrue );
+ CL_FlushMemory( );
+ com_errorEntered = qfalse;
+ CL_CDDialog();
+ } else {
+ Com_Printf("Server didn't have CD\n" );
+ }
+ longjmp (abortframe, -1);
+ } else {
+ CL_Shutdown ();
+ SV_Shutdown (va("Server fatal crashed: %s\n", com_errorMessage));
+ }
+
+ Com_Shutdown ();
+
+ Sys_Error ("%s", com_errorMessage);
+}
+
+
+/*
+=============
+Com_Quit_f
+
+Both client and server can use this, and it will
+do the apropriate things.
+=============
+*/
+void Com_Quit_f( void ) {
+ // don't try to shutdown if we are in a recursive error
+ if ( !com_errorEntered ) {
+ SV_Shutdown ("Server quit\n");
+ CL_Shutdown ();
+ Com_Shutdown ();
+ FS_Shutdown(qtrue);
+ }
+ Sys_Quit ();
+}
+
+
+
+/*
+============================================================================
+
+COMMAND LINE FUNCTIONS
+
++ characters seperate the commandLine string into multiple console
+command lines.
+
+All of these are valid:
+
+quake3 +set test blah +map test
+quake3 set test blah+map test
+quake3 set test blah + map test
+
+============================================================================
+*/
+
+#define MAX_CONSOLE_LINES 32
+int com_numConsoleLines;
+char *com_consoleLines[MAX_CONSOLE_LINES];
+
+/*
+==================
+Com_ParseCommandLine
+
+Break it up into multiple console lines
+==================
+*/
+void Com_ParseCommandLine( char *commandLine ) {
+ int inq = 0;
+ com_consoleLines[0] = commandLine;
+ com_numConsoleLines = 1;
+
+ while ( *commandLine ) {
+ if (*commandLine == '"') {
+ inq = !inq;
+ }
+ // look for a + seperating character
+ // if commandLine came from a file, we might have real line seperators
+ if ( (*commandLine == '+' && !inq) || *commandLine == '\n' || *commandLine == '\r' ) {
+ if ( com_numConsoleLines == MAX_CONSOLE_LINES ) {
+ return;
+ }
+ com_consoleLines[com_numConsoleLines] = commandLine + 1;
+ com_numConsoleLines++;
+ *commandLine = 0;
+ }
+ commandLine++;
+ }
+}
+
+
+/*
+===================
+Com_SafeMode
+
+Check for "safe" on the command line, which will
+skip loading of q3config.cfg
+===================
+*/
+qboolean Com_SafeMode( void ) {
+ int i;
+
+ for ( i = 0 ; i < com_numConsoleLines ; i++ ) {
+ Cmd_TokenizeString( com_consoleLines[i] );
+ if ( !Q_stricmp( Cmd_Argv(0), "safe" )
+ || !Q_stricmp( Cmd_Argv(0), "cvar_restart" ) ) {
+ com_consoleLines[i][0] = 0;
+ return qtrue;
+ }
+ }
+ return qfalse;
+}
+
+
+/*
+===============
+Com_StartupVariable
+
+Searches for command line parameters that are set commands.
+If match is not NULL, only that cvar will be looked for.
+That is necessary because cddir and basedir need to be set
+before the filesystem is started, but all other sets shouls
+be after execing the config and default.
+===============
+*/
+void Com_StartupVariable( const char *match ) {
+ int i;
+ char *s;
+ cvar_t *cv;
+
+ for (i=0 ; i < com_numConsoleLines ; i++) {
+ Cmd_TokenizeString( com_consoleLines[i] );
+ if ( strcmp( Cmd_Argv(0), "set" ) ) {
+ continue;
+ }
+
+ s = Cmd_Argv(1);
+ if ( !match || !strcmp( s, match ) ) {
+ Cvar_Set( s, Cmd_Argv(2) );
+ cv = Cvar_Get( s, "", 0 );
+ cv->flags |= CVAR_USER_CREATED;
+// com_consoleLines[i] = 0;
+ }
+ }
+}
+
+
+/*
+=================
+Com_AddStartupCommands
+
+Adds command line parameters as script statements
+Commands are seperated by + signs
+
+Returns qtrue if any late commands were added, which
+will keep the demoloop from immediately starting
+=================
+*/
+qboolean Com_AddStartupCommands( void ) {
+ int i;
+ qboolean added;
+
+ added = qfalse;
+ // quote every token, so args with semicolons can work
+ for (i=0 ; i < com_numConsoleLines ; i++) {
+ if ( !com_consoleLines[i] || !com_consoleLines[i][0] ) {
+ continue;
+ }
+
+ // set commands won't override menu startup
+ if ( Q_stricmpn( com_consoleLines[i], "set", 3 ) ) {
+ added = qtrue;
+ }
+ Cbuf_AddText( com_consoleLines[i] );
+ Cbuf_AddText( "\n" );
+ }
+
+ return added;
+}
+
+
+//============================================================================
+
+void Info_Print( const char *s ) {
+ char key[512];
+ char value[512];
+ char *o;
+ int l;
+
+ if (*s == '\\')
+ s++;
+ while (*s)
+ {
+ o = key;
+ while (*s && *s != '\\')
+ *o++ = *s++;
+
+ l = o - key;
+ if (l < 20)
+ {
+ Com_Memset (o, ' ', 20-l);
+ key[20] = 0;
+ }
+ else
+ *o = 0;
+ Com_Printf ("%s", key);
+
+ if (!*s)
+ {
+ Com_Printf ("MISSING VALUE\n");
+ return;
+ }
+
+ o = value;
+ s++;
+ while (*s && *s != '\\')
+ *o++ = *s++;
+ *o = 0;
+
+ if (*s)
+ s++;
+ Com_Printf ("%s\n", value);
+ }
+}
+
+/*
+============
+Com_StringContains
+============
+*/
+char *Com_StringContains(char *str1, char *str2, int casesensitive) {
+ int len, i, j;
+
+ len = strlen(str1) - strlen(str2);
+ for (i = 0; i <= len; i++, str1++) {
+ for (j = 0; str2[j]; j++) {
+ if (casesensitive) {
+ if (str1[j] != str2[j]) {
+ break;
+ }
+ }
+ else {
+ if (toupper(str1[j]) != toupper(str2[j])) {
+ break;
+ }
+ }
+ }
+ if (!str2[j]) {
+ return str1;
+ }
+ }
+ return NULL;
+}
+
+/*
+============
+Com_Filter
+============
+*/
+int Com_Filter(char *filter, char *name, int casesensitive)
+{
+ char buf[MAX_TOKEN_CHARS];
+ char *ptr;
+ int i, found;
+
+ while(*filter) {
+ if (*filter == '*') {
+ filter++;
+ for (i = 0; *filter; i++) {
+ if (*filter == '*' || *filter == '?') break;
+ buf[i] = *filter;
+ filter++;
+ }
+ buf[i] = '\0';
+ if (strlen(buf)) {
+ ptr = Com_StringContains(name, buf, casesensitive);
+ if (!ptr) return qfalse;
+ name = ptr + strlen(buf);
+ }
+ }
+ else if (*filter == '?') {
+ filter++;
+ name++;
+ }
+ else if (*filter == '[' && *(filter+1) == '[') {
+ filter++;
+ }
+ else if (*filter == '[') {
+ filter++;
+ found = qfalse;
+ while(*filter && !found) {
+ if (*filter == ']' && *(filter+1) != ']') break;
+ if (*(filter+1) == '-' && *(filter+2) && (*(filter+2) != ']' || *(filter+3) == ']')) {
+ if (casesensitive) {
+ if (*name >= *filter && *name <= *(filter+2)) found = qtrue;
+ }
+ else {
+ if (toupper(*name) >= toupper(*filter) &&
+ toupper(*name) <= toupper(*(filter+2))) found = qtrue;
+ }
+ filter += 3;
+ }
+ else {
+ if (casesensitive) {
+ if (*filter == *name) found = qtrue;
+ }
+ else {
+ if (toupper(*filter) == toupper(*name)) found = qtrue;
+ }
+ filter++;
+ }
+ }
+ if (!found) return qfalse;
+ while(*filter) {
+ if (*filter == ']' && *(filter+1) != ']') break;
+ filter++;
+ }
+ filter++;
+ name++;
+ }
+ else {
+ if (casesensitive) {
+ if (*filter != *name) return qfalse;
+ }
+ else {
+ if (toupper(*filter) != toupper(*name)) return qfalse;
+ }
+ filter++;
+ name++;
+ }
+ }
+ return qtrue;
+}
+
+/*
+============
+Com_FilterPath
+============
+*/
+int Com_FilterPath(char *filter, char *name, int casesensitive)
+{
+ int i;
+ char new_filter[MAX_QPATH];
+ char new_name[MAX_QPATH];
+
+ for (i = 0; i < MAX_QPATH-1 && filter[i]; i++) {
+ if ( filter[i] == '\\' || filter[i] == ':' ) {
+ new_filter[i] = '/';
+ }
+ else {
+ new_filter[i] = filter[i];
+ }
+ }
+ new_filter[i] = '\0';
+ for (i = 0; i < MAX_QPATH-1 && name[i]; i++) {
+ if ( name[i] == '\\' || name[i] == ':' ) {
+ new_name[i] = '/';
+ }
+ else {
+ new_name[i] = name[i];
+ }
+ }
+ new_name[i] = '\0';
+ return Com_Filter(new_filter, new_name, casesensitive);
+}
+
+/*
+============
+Com_HashKey
+============
+*/
+int Com_HashKey(char *string, int maxlen) {
+ int register hash, i;
+
+ hash = 0;
+ for (i = 0; i < maxlen && string[i] != '\0'; i++) {
+ hash += string[i] * (119 + i);
+ }
+ hash = (hash ^ (hash >> 10) ^ (hash >> 20));
+ return hash;
+}
+
+/*
+================
+Com_RealTime
+================
+*/
+int Com_RealTime(qtime_t *qtime) {
+ time_t t;
+ struct tm *tms;
+
+ t = time(NULL);
+ if (!qtime)
+ return t;
+ tms = localtime(&t);
+ if (tms) {
+ qtime->tm_sec = tms->tm_sec;
+ qtime->tm_min = tms->tm_min;
+ qtime->tm_hour = tms->tm_hour;
+ qtime->tm_mday = tms->tm_mday;
+ qtime->tm_mon = tms->tm_mon;
+ qtime->tm_year = tms->tm_year;
+ qtime->tm_wday = tms->tm_wday;
+ qtime->tm_yday = tms->tm_yday;
+ qtime->tm_isdst = tms->tm_isdst;
+ }
+ return t;
+}
+
+
+/*
+==============================================================================
+
+ ZONE MEMORY ALLOCATION
+
+There is never any space between memblocks, and there will never be two
+contiguous free memblocks.
+
+The rover can be left pointing at a non-empty block
+
+The zone calls are pretty much only used for small strings and structures,
+all big things are allocated on the hunk.
+==============================================================================
+*/
+
+#define ZONEID 0x1d4a11
+#define MINFRAGMENT 64
+
+typedef struct zonedebug_s {
+ char *label;
+ char *file;
+ int line;
+ int allocSize;
+} zonedebug_t;
+
+typedef struct memblock_s {
+ int size; // including the header and possibly tiny fragments
+ int tag; // a tag of 0 is a free block
+ struct memblock_s *next, *prev;
+ int id; // should be ZONEID
+#ifdef ZONE_DEBUG
+ zonedebug_t d;
+#endif
+} memblock_t;
+
+typedef struct {
+ int size; // total bytes malloced, including header
+ int used; // total bytes used
+ memblock_t blocklist; // start / end cap for linked list
+ memblock_t *rover;
+} memzone_t;
+
+// main zone for all "dynamic" memory allocation
+memzone_t *mainzone;
+// we also have a small zone for small allocations that would only
+// fragment the main zone (think of cvar and cmd strings)
+memzone_t *smallzone;
+
+void Z_CheckHeap( void );
+
+/*
+========================
+Z_ClearZone
+========================
+*/
+void Z_ClearZone( memzone_t *zone, int size ) {
+ memblock_t *block;
+
+ // set the entire zone to one free block
+
+ zone->blocklist.next = zone->blocklist.prev = block =
+ (memblock_t *)( (byte *)zone + sizeof(memzone_t) );
+ zone->blocklist.tag = 1; // in use block
+ zone->blocklist.id = 0;
+ zone->blocklist.size = 0;
+ zone->rover = block;
+ zone->size = size;
+ zone->used = 0;
+
+ block->prev = block->next = &zone->blocklist;
+ block->tag = 0; // free block
+ block->id = ZONEID;
+ block->size = size - sizeof(memzone_t);
+}
+
+/*
+========================
+Z_AvailableZoneMemory
+========================
+*/
+int Z_AvailableZoneMemory( memzone_t *zone ) {
+ return zone->size - zone->used;
+}
+
+/*
+========================
+Z_AvailableMemory
+========================
+*/
+int Z_AvailableMemory( void ) {
+ return Z_AvailableZoneMemory( mainzone );
+}
+
+/*
+========================
+Z_Free
+========================
+*/
+void Z_Free( void *ptr ) {
+ memblock_t *block, *other;
+ memzone_t *zone;
+
+ if (!ptr) {
+ Com_Error( ERR_DROP, "Z_Free: NULL pointer" );
+ }
+
+ block = (memblock_t *) ( (byte *)ptr - sizeof(memblock_t));
+ if (block->id != ZONEID) {
+ Com_Error( ERR_FATAL, "Z_Free: freed a pointer without ZONEID" );
+ }
+ if (block->tag == 0) {
+ Com_Error( ERR_FATAL, "Z_Free: freed a freed pointer" );
+ }
+ // if static memory
+ if (block->tag == TAG_STATIC) {
+ return;
+ }
+
+ // check the memory trash tester
+ if ( *(int *)((byte *)block + block->size - 4 ) != ZONEID ) {
+ Com_Error( ERR_FATAL, "Z_Free: memory block wrote past end" );
+ }
+
+ if (block->tag == TAG_SMALL) {
+ zone = smallzone;
+ }
+ else {
+ zone = mainzone;
+ }
+
+ zone->used -= block->size;
+ // set the block to something that should cause problems
+ // if it is referenced...
+ Com_Memset( ptr, 0xaa, block->size - sizeof( *block ) );
+
+ block->tag = 0; // mark as free
+
+ other = block->prev;
+ if (!other->tag) {
+ // merge with previous free block
+ other->size += block->size;
+ other->next = block->next;
+ other->next->prev = other;
+ if (block == zone->rover) {
+ zone->rover = other;
+ }
+ block = other;
+ }
+
+ zone->rover = block;
+
+ other = block->next;
+ if ( !other->tag ) {
+ // merge the next free block onto the end
+ block->size += other->size;
+ block->next = other->next;
+ block->next->prev = block;
+ if (other == zone->rover) {
+ zone->rover = block;
+ }
+ }
+}
+
+
+/*
+================
+Z_FreeTags
+================
+*/
+void Z_FreeTags( int tag ) {
+ int count;
+ memzone_t *zone;
+
+ if ( tag == TAG_SMALL ) {
+ zone = smallzone;
+ }
+ else {
+ zone = mainzone;
+ }
+ count = 0;
+ // use the rover as our pointer, because
+ // Z_Free automatically adjusts it
+ zone->rover = zone->blocklist.next;
+ do {
+ if ( zone->rover->tag == tag ) {
+ count++;
+ Z_Free( (void *)(zone->rover + 1) );
+ continue;
+ }
+ zone->rover = zone->rover->next;
+ } while ( zone->rover != &zone->blocklist );
+}
+
+
+/*
+================
+Z_TagMalloc
+================
+*/
+#ifdef ZONE_DEBUG
+void *Z_TagMallocDebug( int size, int tag, char *label, char *file, int line ) {
+#else
+void *Z_TagMalloc( int size, int tag ) {
+#endif
+ int extra, allocSize;
+ memblock_t *start, *rover, *new, *base;
+ memzone_t *zone;
+
+ if (!tag) {
+ Com_Error( ERR_FATAL, "Z_TagMalloc: tried to use a 0 tag" );
+ }
+
+ if ( tag == TAG_SMALL ) {
+ zone = smallzone;
+ }
+ else {
+ zone = mainzone;
+ }
+
+ allocSize = size;
+ //
+ // scan through the block list looking for the first free block
+ // of sufficient size
+ //
+ size += sizeof(memblock_t); // account for size of block header
+ size += 4; // space for memory trash tester
+ size = (size + 3) & ~3; // align to 32 bit boundary
+
+ base = rover = zone->rover;
+ start = base->prev;
+
+ do {
+ if (rover == start) {
+#ifdef ZONE_DEBUG
+ Z_LogHeap();
+#endif
+ // scaned all the way around the list
+ Com_Error( ERR_FATAL, "Z_Malloc: failed on allocation of %i bytes from the %s zone",
+ size, zone == smallzone ? "small" : "main");
+ return NULL;
+ }
+ if (rover->tag) {
+ base = rover = rover->next;
+ } else {
+ rover = rover->next;
+ }
+ } while (base->tag || base->size < size);
+
+ //
+ // found a block big enough
+ //
+ extra = base->size - size;
+ if (extra > MINFRAGMENT) {
+ // there will be a free fragment after the allocated block
+ new = (memblock_t *) ((byte *)base + size );
+ new->size = extra;
+ new->tag = 0; // free block
+ new->prev = base;
+ new->id = ZONEID;
+ new->next = base->next;
+ new->next->prev = new;
+ base->next = new;
+ base->size = size;
+ }
+
+ base->tag = tag; // no longer a free block
+
+ zone->rover = base->next; // next allocation will start looking here
+ zone->used += base->size; //
+
+ base->id = ZONEID;
+
+#ifdef ZONE_DEBUG
+ base->d.label = label;
+ base->d.file = file;
+ base->d.line = line;
+ base->d.allocSize = allocSize;
+#endif
+
+ // marker for memory trash testing
+ *(int *)((byte *)base + base->size - 4) = ZONEID;
+
+ return (void *) ((byte *)base + sizeof(memblock_t));
+}
+
+/*
+========================
+Z_Malloc
+========================
+*/
+#ifdef ZONE_DEBUG
+void *Z_MallocDebug( int size, char *label, char *file, int line ) {
+#else
+void *Z_Malloc( int size ) {
+#endif
+ void *buf;
+
+ //Z_CheckHeap (); // DEBUG
+
+#ifdef ZONE_DEBUG
+ buf = Z_TagMallocDebug( size, TAG_GENERAL, label, file, line );
+#else
+ buf = Z_TagMalloc( size, TAG_GENERAL );
+#endif
+ Com_Memset( buf, 0, size );
+
+ return buf;
+}
+
+#ifdef ZONE_DEBUG
+void *S_MallocDebug( int size, char *label, char *file, int line ) {
+ return Z_TagMallocDebug( size, TAG_SMALL, label, file, line );
+}
+#else
+void *S_Malloc( int size ) {
+ return Z_TagMalloc( size, TAG_SMALL );
+}
+#endif
+
+/*
+========================
+Z_CheckHeap
+========================
+*/
+void Z_CheckHeap( void ) {
+ memblock_t *block;
+
+ for (block = mainzone->blocklist.next ; ; block = block->next) {
+ if (block->next == &mainzone->blocklist) {
+ break; // all blocks have been hit
+ }
+ if ( (byte *)block + block->size != (byte *)block->next)
+ Com_Error( ERR_FATAL, "Z_CheckHeap: block size does not touch the next block\n" );
+ if ( block->next->prev != block) {
+ Com_Error( ERR_FATAL, "Z_CheckHeap: next block doesn't have proper back link\n" );
+ }
+ if ( !block->tag && !block->next->tag ) {
+ Com_Error( ERR_FATAL, "Z_CheckHeap: two consecutive free blocks\n" );
+ }
+ }
+}
+
+/*
+========================
+Z_LogZoneHeap
+========================
+*/
+void Z_LogZoneHeap( memzone_t *zone, char *name ) {
+#ifdef ZONE_DEBUG
+ char dump[32], *ptr;
+ int i, j;
+#endif
+ memblock_t *block;
+ char buf[4096];
+ int size, allocSize, numBlocks;
+
+ if (!logfile || !FS_Initialized())
+ return;
+ size = allocSize = numBlocks = 0;
+ Com_sprintf(buf, sizeof(buf), "\r\n================\r\n%s log\r\n================\r\n", name);
+ FS_Write(buf, strlen(buf), logfile);
+ for (block = zone->blocklist.next ; block->next != &zone->blocklist; block = block->next) {
+ if (block->tag) {
+#ifdef ZONE_DEBUG
+ ptr = ((char *) block) + sizeof(memblock_t);
+ j = 0;
+ for (i = 0; i < 20 && i < block->d.allocSize; i++) {
+ if (ptr[i] >= 32 && ptr[i] < 127) {
+ dump[j++] = ptr[i];
+ }
+ else {
+ dump[j++] = '_';
+ }
+ }
+ dump[j] = '\0';
+ Com_sprintf(buf, sizeof(buf), "size = %8d: %s, line: %d (%s) [%s]\r\n", block->d.allocSize, block->d.file, block->d.line, block->d.label, dump);
+ FS_Write(buf, strlen(buf), logfile);
+ allocSize += block->d.allocSize;
+#endif
+ size += block->size;
+ numBlocks++;
+ }
+ }
+#ifdef ZONE_DEBUG
+ // subtract debug memory
+ size -= numBlocks * sizeof(zonedebug_t);
+#else
+ allocSize = numBlocks * sizeof(memblock_t); // + 32 bit alignment
+#endif
+ Com_sprintf(buf, sizeof(buf), "%d %s memory in %d blocks\r\n", size, name, numBlocks);
+ FS_Write(buf, strlen(buf), logfile);
+ Com_sprintf(buf, sizeof(buf), "%d %s memory overhead\r\n", size - allocSize, name);
+ FS_Write(buf, strlen(buf), logfile);
+}
+
+/*
+========================
+Z_LogHeap
+========================
+*/
+void Z_LogHeap( void ) {
+ Z_LogZoneHeap( mainzone, "MAIN" );
+ Z_LogZoneHeap( smallzone, "SMALL" );
+}
+
+// static mem blocks to reduce a lot of small zone overhead
+typedef struct memstatic_s {
+ memblock_t b;
+ byte mem[2];
+} memstatic_t;
+
+// bk001204 - initializer brackets
+memstatic_t emptystring =
+ { {(sizeof(memblock_t)+2 + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'\0', '\0'} };
+memstatic_t numberstring[] = {
+ { {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'0', '\0'} },
+ { {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'1', '\0'} },
+ { {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'2', '\0'} },
+ { {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'3', '\0'} },
+ { {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'4', '\0'} },
+ { {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'5', '\0'} },
+ { {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'6', '\0'} },
+ { {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'7', '\0'} },
+ { {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'8', '\0'} },
+ { {(sizeof(memstatic_t) + 3) & ~3, TAG_STATIC, NULL, NULL, ZONEID}, {'9', '\0'} }
+};
+
+/*
+========================
+CopyString
+
+ NOTE: never write over the memory CopyString returns because
+ memory from a memstatic_t might be returned
+========================
+*/
+char *CopyString( const char *in ) {
+ char *out;
+
+ if (!in[0]) {
+ return ((char *)&emptystring) + sizeof(memblock_t);
+ }
+ else if (!in[1]) {
+ if (in[0] >= '0' && in[0] <= '9') {
+ return ((char *)&numberstring[in[0]-'0']) + sizeof(memblock_t);
+ }
+ }
+ out = S_Malloc (strlen(in)+1);
+ strcpy (out, in);
+ return out;
+}
+
+/*
+==============================================================================
+
+Goals:
+ reproducable without history effects -- no out of memory errors on weird map to map changes
+ allow restarting of the client without fragmentation
+ minimize total pages in use at run time
+ minimize total pages needed during load time
+
+ Single block of memory with stack allocators coming from both ends towards the middle.
+
+ One side is designated the temporary memory allocator.
+
+ Temporary memory can be allocated and freed in any order.
+
+ A highwater mark is kept of the most in use at any time.
+
+ When there is no temporary memory allocated, the permanent and temp sides
+ can be switched, allowing the already touched temp memory to be used for
+ permanent storage.
+
+ Temp memory must never be allocated on two ends at once, or fragmentation
+ could occur.
+
+ If we have any in-use temp memory, additional temp allocations must come from
+ that side.
+
+ If not, we can choose to make either side the new temp side and push future
+ permanent allocations to the other side. Permanent allocations should be
+ kept on the side that has the current greatest wasted highwater mark.
+
+==============================================================================
+*/
+
+
+#define HUNK_MAGIC 0x89537892
+#define HUNK_FREE_MAGIC 0x89537893
+
+typedef struct {
+ int magic;
+ int size;
+} hunkHeader_t;
+
+typedef struct {
+ int mark;
+ int permanent;
+ int temp;
+ int tempHighwater;
+} hunkUsed_t;
+
+typedef struct hunkblock_s {
+ int size;
+ byte printed;
+ struct hunkblock_s *next;
+ char *label;
+ char *file;
+ int line;
+} hunkblock_t;
+
+static hunkblock_t *hunkblocks;
+
+static hunkUsed_t hunk_low, hunk_high;
+static hunkUsed_t *hunk_permanent, *hunk_temp;
+
+static byte *s_hunkData = NULL;
+static int s_hunkTotal;
+
+static int s_zoneTotal;
+static int s_smallZoneTotal;
+
+
+/*
+=================
+Com_Meminfo_f
+=================
+*/
+void Com_Meminfo_f( void ) {
+ memblock_t *block;
+ int zoneBytes, zoneBlocks;
+ int smallZoneBytes, smallZoneBlocks;
+ int botlibBytes, rendererBytes;
+ int unused;
+
+ zoneBytes = 0;
+ botlibBytes = 0;
+ rendererBytes = 0;
+ zoneBlocks = 0;
+ for (block = mainzone->blocklist.next ; ; block = block->next) {
+ if ( Cmd_Argc() != 1 ) {
+ Com_Printf ("block:%p size:%7i tag:%3i\n",
+ block, block->size, block->tag);
+ }
+ if ( block->tag ) {
+ zoneBytes += block->size;
+ zoneBlocks++;
+ if ( block->tag == TAG_BOTLIB ) {
+ botlibBytes += block->size;
+ } else if ( block->tag == TAG_RENDERER ) {
+ rendererBytes += block->size;
+ }
+ }
+
+ if (block->next == &mainzone->blocklist) {
+ break; // all blocks have been hit
+ }
+ if ( (byte *)block + block->size != (byte *)block->next) {
+ Com_Printf ("ERROR: block size does not touch the next block\n");
+ }
+ if ( block->next->prev != block) {
+ Com_Printf ("ERROR: next block doesn't have proper back link\n");
+ }
+ if ( !block->tag && !block->next->tag ) {
+ Com_Printf ("ERROR: two consecutive free blocks\n");
+ }
+ }
+
+ smallZoneBytes = 0;
+ smallZoneBlocks = 0;
+ for (block = smallzone->blocklist.next ; ; block = block->next) {
+ if ( block->tag ) {
+ smallZoneBytes += block->size;
+ smallZoneBlocks++;
+ }
+
+ if (block->next == &smallzone->blocklist) {
+ break; // all blocks have been hit
+ }
+ }
+
+ Com_Printf( "%8i bytes total hunk\n", s_hunkTotal );
+ Com_Printf( "%8i bytes total zone\n", s_zoneTotal );
+ Com_Printf( "\n" );
+ Com_Printf( "%8i low mark\n", hunk_low.mark );
+ Com_Printf( "%8i low permanent\n", hunk_low.permanent );
+ if ( hunk_low.temp != hunk_low.permanent ) {
+ Com_Printf( "%8i low temp\n", hunk_low.temp );
+ }
+ Com_Printf( "%8i low tempHighwater\n", hunk_low.tempHighwater );
+ Com_Printf( "\n" );
+ Com_Printf( "%8i high mark\n", hunk_high.mark );
+ Com_Printf( "%8i high permanent\n", hunk_high.permanent );
+ if ( hunk_high.temp != hunk_high.permanent ) {
+ Com_Printf( "%8i high temp\n", hunk_high.temp );
+ }
+ Com_Printf( "%8i high tempHighwater\n", hunk_high.tempHighwater );
+ Com_Printf( "\n" );
+ Com_Printf( "%8i total hunk in use\n", hunk_low.permanent + hunk_high.permanent );
+ unused = 0;
+ if ( hunk_low.tempHighwater > hunk_low.permanent ) {
+ unused += hunk_low.tempHighwater - hunk_low.permanent;
+ }
+ if ( hunk_high.tempHighwater > hunk_high.permanent ) {
+ unused += hunk_high.tempHighwater - hunk_high.permanent;
+ }
+ Com_Printf( "%8i unused highwater\n", unused );
+ Com_Printf( "\n" );
+ Com_Printf( "%8i bytes in %i zone blocks\n", zoneBytes, zoneBlocks );
+ Com_Printf( " %8i bytes in dynamic botlib\n", botlibBytes );
+ Com_Printf( " %8i bytes in dynamic renderer\n", rendererBytes );
+ Com_Printf( " %8i bytes in dynamic other\n", zoneBytes - ( botlibBytes + rendererBytes ) );
+ Com_Printf( " %8i bytes in small Zone memory\n", smallZoneBytes );
+}
+
+/*
+===============
+Com_TouchMemory
+
+Touch all known used data to make sure it is paged in
+===============
+*/
+void Com_TouchMemory( void ) {
+ int start, end;
+ int i, j;
+ int sum;
+ memblock_t *block;
+
+ Z_CheckHeap();
+
+ start = Sys_Milliseconds();
+
+ sum = 0;
+
+ j = hunk_low.permanent >> 2;
+ for ( i = 0 ; i < j ; i+=64 ) { // only need to touch each page
+ sum += ((int *)s_hunkData)[i];
+ }
+
+ i = ( s_hunkTotal - hunk_high.permanent ) >> 2;
+ j = hunk_high.permanent >> 2;
+ for ( ; i < j ; i+=64 ) { // only need to touch each page
+ sum += ((int *)s_hunkData)[i];
+ }
+
+ for (block = mainzone->blocklist.next ; ; block = block->next) {
+ if ( block->tag ) {
+ j = block->size >> 2;
+ for ( i = 0 ; i < j ; i+=64 ) { // only need to touch each page
+ sum += ((int *)block)[i];
+ }
+ }
+ if ( block->next == &mainzone->blocklist ) {
+ break; // all blocks have been hit
+ }
+ }
+
+ end = Sys_Milliseconds();
+
+ Com_Printf( "Com_TouchMemory: %i msec\n", end - start );
+}
+
+
+
+/*
+=================
+Com_InitZoneMemory
+=================
+*/
+void Com_InitSmallZoneMemory( void ) {
+ s_smallZoneTotal = 512 * 1024;
+ // bk001205 - was malloc
+ smallzone = calloc( s_smallZoneTotal, 1 );
+ if ( !smallzone ) {
+ Com_Error( ERR_FATAL, "Small zone data failed to allocate %1.1f megs", (float)s_smallZoneTotal / (1024*1024) );
+ }
+ Z_ClearZone( smallzone, s_smallZoneTotal );
+
+ return;
+}
+
+void Com_InitZoneMemory( void ) {
+ cvar_t *cv;
+ // allocate the random block zone
+ cv = Cvar_Get( "com_zoneMegs", DEF_COMZONEMEGS, CVAR_LATCH | CVAR_ARCHIVE );
+
+ if ( cv->integer < 20 ) {
+ s_zoneTotal = 1024 * 1024 * 16;
+ } else {
+ s_zoneTotal = cv->integer * 1024 * 1024;
+ }
+
+ // bk001205 - was malloc
+ mainzone = calloc( s_zoneTotal, 1 );
+ if ( !mainzone ) {
+ Com_Error( ERR_FATAL, "Zone data failed to allocate %i megs", s_zoneTotal / (1024*1024) );
+ }
+ Z_ClearZone( mainzone, s_zoneTotal );
+
+}
+
+/*
+=================
+Hunk_Log
+=================
+*/
+void Hunk_Log( void) {
+ hunkblock_t *block;
+ char buf[4096];
+ int size, numBlocks;
+
+ if (!logfile || !FS_Initialized())
+ return;
+ size = 0;
+ numBlocks = 0;
+ Com_sprintf(buf, sizeof(buf), "\r\n================\r\nHunk log\r\n================\r\n");
+ FS_Write(buf, strlen(buf), logfile);
+ for (block = hunkblocks ; block; block = block->next) {
+#ifdef HUNK_DEBUG
+ Com_sprintf(buf, sizeof(buf), "size = %8d: %s, line: %d (%s)\r\n", block->size, block->file, block->line, block->label);
+ FS_Write(buf, strlen(buf), logfile);
+#endif
+ size += block->size;
+ numBlocks++;
+ }
+ Com_sprintf(buf, sizeof(buf), "%d Hunk memory\r\n", size);
+ FS_Write(buf, strlen(buf), logfile);
+ Com_sprintf(buf, sizeof(buf), "%d hunk blocks\r\n", numBlocks);
+ FS_Write(buf, strlen(buf), logfile);
+}
+
+/*
+=================
+Hunk_SmallLog
+=================
+*/
+void Hunk_SmallLog( void) {
+ hunkblock_t *block, *block2;
+ char buf[4096];
+ int size, locsize, numBlocks;
+
+ if (!logfile || !FS_Initialized())
+ return;
+ for (block = hunkblocks ; block; block = block->next) {
+ block->printed = qfalse;
+ }
+ size = 0;
+ numBlocks = 0;
+ Com_sprintf(buf, sizeof(buf), "\r\n================\r\nHunk Small log\r\n================\r\n");
+ FS_Write(buf, strlen(buf), logfile);
+ for (block = hunkblocks; block; block = block->next) {
+ if (block->printed) {
+ continue;
+ }
+ locsize = block->size;
+ for (block2 = block->next; block2; block2 = block2->next) {
+ if (block->line != block2->line) {
+ continue;
+ }
+ if (Q_stricmp(block->file, block2->file)) {
+ continue;
+ }
+ size += block2->size;
+ locsize += block2->size;
+ block2->printed = qtrue;
+ }
+#ifdef HUNK_DEBUG
+ Com_sprintf(buf, sizeof(buf), "size = %8d: %s, line: %d (%s)\r\n", locsize, block->file, block->line, block->label);
+ FS_Write(buf, strlen(buf), logfile);
+#endif
+ size += block->size;
+ numBlocks++;
+ }
+ Com_sprintf(buf, sizeof(buf), "%d Hunk memory\r\n", size);
+ FS_Write(buf, strlen(buf), logfile);
+ Com_sprintf(buf, sizeof(buf), "%d hunk blocks\r\n", numBlocks);
+ FS_Write(buf, strlen(buf), logfile);
+}
+
+/*
+=================
+Com_InitZoneMemory
+=================
+*/
+void Com_InitHunkMemory( void ) {
+ cvar_t *cv;
+ int nMinAlloc;
+ char *pMsg = NULL;
+
+ // make sure the file system has allocated and "not" freed any temp blocks
+ // this allows the config and product id files ( journal files too ) to be loaded
+ // by the file system without redunant routines in the file system utilizing different
+ // memory systems
+ if (FS_LoadStack() != 0) {
+ Com_Error( ERR_FATAL, "Hunk initialization failed. File system load stack not zero");
+ }
+
+ // allocate the stack based hunk allocator
+ cv = Cvar_Get( "com_hunkMegs", DEF_COMHUNKMEGS, CVAR_LATCH | CVAR_ARCHIVE );
+
+ // if we are not dedicated min allocation is 56, otherwise min is 1
+ if (com_dedicated && com_dedicated->integer) {
+ nMinAlloc = MIN_DEDICATED_COMHUNKMEGS;
+ pMsg = "Minimum com_hunkMegs for a dedicated server is %i, allocating %i megs.\n";
+ }
+ else {
+ nMinAlloc = MIN_COMHUNKMEGS;
+ pMsg = "Minimum com_hunkMegs is %i, allocating %i megs.\n";
+ }
+
+ if ( cv->integer < nMinAlloc ) {
+ s_hunkTotal = 1024 * 1024 * nMinAlloc;
+ Com_Printf(pMsg, nMinAlloc, s_hunkTotal / (1024 * 1024));
+ } else {
+ s_hunkTotal = cv->integer * 1024 * 1024;
+ }
+
+
+ // bk001205 - was malloc
+ s_hunkData = calloc( s_hunkTotal + 31, 1 );
+ if ( !s_hunkData ) {
+ Com_Error( ERR_FATAL, "Hunk data failed to allocate %i megs", s_hunkTotal / (1024*1024) );
+ }
+ // cacheline align
+ s_hunkData = (byte *) ( ( (int)s_hunkData + 31 ) & ~31 );
+ Hunk_Clear();
+
+ Cmd_AddCommand( "meminfo", Com_Meminfo_f );
+#ifdef ZONE_DEBUG
+ Cmd_AddCommand( "zonelog", Z_LogHeap );
+#endif
+#ifdef HUNK_DEBUG
+ Cmd_AddCommand( "hunklog", Hunk_Log );
+ Cmd_AddCommand( "hunksmalllog", Hunk_SmallLog );
+#endif
+}
+
+/*
+====================
+Hunk_MemoryRemaining
+====================
+*/
+int Hunk_MemoryRemaining( void ) {
+ int low, high;
+
+ low = hunk_low.permanent > hunk_low.temp ? hunk_low.permanent : hunk_low.temp;
+ high = hunk_high.permanent > hunk_high.temp ? hunk_high.permanent : hunk_high.temp;
+
+ return s_hunkTotal - ( low + high );
+}
+
+/*
+===================
+Hunk_SetMark
+
+The server calls this after the level and game VM have been loaded
+===================
+*/
+void Hunk_SetMark( void ) {
+ hunk_low.mark = hunk_low.permanent;
+ hunk_high.mark = hunk_high.permanent;
+}
+
+/*
+=================
+Hunk_ClearToMark
+
+The client calls this before starting a vid_restart or snd_restart
+=================
+*/
+void Hunk_ClearToMark( void ) {
+ hunk_low.permanent = hunk_low.temp = hunk_low.mark;
+ hunk_high.permanent = hunk_high.temp = hunk_high.mark;
+}
+
+/*
+=================
+Hunk_CheckMark
+=================
+*/
+qboolean Hunk_CheckMark( void ) {
+ if( hunk_low.mark || hunk_high.mark ) {
+ return qtrue;
+ }
+ return qfalse;
+}
+
+void CL_ShutdownCGame( void );
+void CL_ShutdownUI( void );
+void SV_ShutdownGameProgs( void );
+
+/*
+=================
+Hunk_Clear
+
+The server calls this before shutting down or loading a new map
+=================
+*/
+void Hunk_Clear( void ) {
+
+#ifndef DEDICATED
+ CL_ShutdownCGame();
+ CL_ShutdownUI();
+#endif
+ SV_ShutdownGameProgs();
+#ifndef DEDICATED
+ CIN_CloseAllVideos();
+#endif
+ hunk_low.mark = 0;
+ hunk_low.permanent = 0;
+ hunk_low.temp = 0;
+ hunk_low.tempHighwater = 0;
+
+ hunk_high.mark = 0;
+ hunk_high.permanent = 0;
+ hunk_high.temp = 0;
+ hunk_high.tempHighwater = 0;
+
+ hunk_permanent = &hunk_low;
+ hunk_temp = &hunk_high;
+
+ Com_Printf( "Hunk_Clear: reset the hunk ok\n" );
+ VM_Clear();
+#ifdef HUNK_DEBUG
+ hunkblocks = NULL;
+#endif
+}
+
+static void Hunk_SwapBanks( void ) {
+ hunkUsed_t *swap;
+
+ // can't swap banks if there is any temp already allocated
+ if ( hunk_temp->temp != hunk_temp->permanent ) {
+ return;
+ }
+
+ // if we have a larger highwater mark on this side, start making
+ // our permanent allocations here and use the other side for temp
+ if ( hunk_temp->tempHighwater - hunk_temp->permanent >
+ hunk_permanent->tempHighwater - hunk_permanent->permanent ) {
+ swap = hunk_temp;
+ hunk_temp = hunk_permanent;
+ hunk_permanent = swap;
+ }
+}
+
+/*
+=================
+Hunk_Alloc
+
+Allocate permanent (until the hunk is cleared) memory
+=================
+*/
+#ifdef HUNK_DEBUG
+void *Hunk_AllocDebug( int size, ha_pref preference, char *label, char *file, int line ) {
+#else
+void *Hunk_Alloc( int size, ha_pref preference ) {
+#endif
+ void *buf;
+
+ if ( s_hunkData == NULL)
+ {
+ Com_Error( ERR_FATAL, "Hunk_Alloc: Hunk memory system not initialized" );
+ }
+
+ // can't do preference if there is any temp allocated
+ if (preference == h_dontcare || hunk_temp->temp != hunk_temp->permanent) {
+ Hunk_SwapBanks();
+ } else {
+ if (preference == h_low && hunk_permanent != &hunk_low) {
+ Hunk_SwapBanks();
+ } else if (preference == h_high && hunk_permanent != &hunk_high) {
+ Hunk_SwapBanks();
+ }
+ }
+
+#ifdef HUNK_DEBUG
+ size += sizeof(hunkblock_t);
+#endif
+
+ // round to cacheline
+ size = (size+31)&~31;
+
+ if ( hunk_low.temp + hunk_high.temp + size > s_hunkTotal ) {
+#ifdef HUNK_DEBUG
+ Hunk_Log();
+ Hunk_SmallLog();
+#endif
+ Com_Error( ERR_DROP, "Hunk_Alloc failed on %i", size );
+ }
+
+ if ( hunk_permanent == &hunk_low ) {
+ buf = (void *)(s_hunkData + hunk_permanent->permanent);
+ hunk_permanent->permanent += size;
+ } else {
+ hunk_permanent->permanent += size;
+ buf = (void *)(s_hunkData + s_hunkTotal - hunk_permanent->permanent );
+ }
+
+ hunk_permanent->temp = hunk_permanent->permanent;
+
+ Com_Memset( buf, 0, size );
+
+#ifdef HUNK_DEBUG
+ {
+ hunkblock_t *block;
+
+ block = (hunkblock_t *) buf;
+ block->size = size - sizeof(hunkblock_t);
+ block->file = file;
+ block->label = label;
+ block->line = line;
+ block->next = hunkblocks;
+ hunkblocks = block;
+ buf = ((byte *) buf) + sizeof(hunkblock_t);
+ }
+#endif
+ return buf;
+}
+
+/*
+=================
+Hunk_AllocateTempMemory
+
+This is used by the file loading system.
+Multiple files can be loaded in temporary memory.
+When the files-in-use count reaches zero, all temp memory will be deleted
+=================
+*/
+void *Hunk_AllocateTempMemory( int size ) {
+ void *buf;
+ hunkHeader_t *hdr;
+
+ // return a Z_Malloc'd block if the hunk has not been initialized
+ // this allows the config and product id files ( journal files too ) to be loaded
+ // by the file system without redunant routines in the file system utilizing different
+ // memory systems
+ if ( s_hunkData == NULL )
+ {
+ return Z_Malloc(size);
+ }
+
+ Hunk_SwapBanks();
+
+ size = ( (size+3)&~3 ) + sizeof( hunkHeader_t );
+
+ if ( hunk_temp->temp + hunk_permanent->permanent + size > s_hunkTotal ) {
+ Com_Error( ERR_DROP, "Hunk_AllocateTempMemory: failed on %i", size );
+ }
+
+ if ( hunk_temp == &hunk_low ) {
+ buf = (void *)(s_hunkData + hunk_temp->temp);
+ hunk_temp->temp += size;
+ } else {
+ hunk_temp->temp += size;
+ buf = (void *)(s_hunkData + s_hunkTotal - hunk_temp->temp );
+ }
+
+ if ( hunk_temp->temp > hunk_temp->tempHighwater ) {
+ hunk_temp->tempHighwater = hunk_temp->temp;
+ }
+
+ hdr = (hunkHeader_t *)buf;
+ buf = (void *)(hdr+1);
+
+ hdr->magic = HUNK_MAGIC;
+ hdr->size = size;
+
+ // don't bother clearing, because we are going to load a file over it
+ return buf;
+}
+
+
+/*
+==================
+Hunk_FreeTempMemory
+==================
+*/
+void Hunk_FreeTempMemory( void *buf ) {
+ hunkHeader_t *hdr;
+
+ // free with Z_Free if the hunk has not been initialized
+ // this allows the config and product id files ( journal files too ) to be loaded
+ // by the file system without redunant routines in the file system utilizing different
+ // memory systems
+ if ( s_hunkData == NULL )
+ {
+ Z_Free(buf);
+ return;
+ }
+
+
+ hdr = ( (hunkHeader_t *)buf ) - 1;
+ if ( hdr->magic != HUNK_MAGIC ) {
+ Com_Error( ERR_FATAL, "Hunk_FreeTempMemory: bad magic" );
+ }
+
+ hdr->magic = HUNK_FREE_MAGIC;
+
+ // this only works if the files are freed in stack order,
+ // otherwise the memory will stay around until Hunk_ClearTempMemory
+ if ( hunk_temp == &hunk_low ) {
+ if ( hdr == (void *)(s_hunkData + hunk_temp->temp - hdr->size ) ) {
+ hunk_temp->temp -= hdr->size;
+ } else {
+ Com_Printf( "Hunk_FreeTempMemory: not the final block\n" );
+ }
+ } else {
+ if ( hdr == (void *)(s_hunkData + s_hunkTotal - hunk_temp->temp ) ) {
+ hunk_temp->temp -= hdr->size;
+ } else {
+ Com_Printf( "Hunk_FreeTempMemory: not the final block\n" );
+ }
+ }
+}
+
+
+/*
+=================
+Hunk_ClearTempMemory
+
+The temp space is no longer needed. If we have left more
+touched but unused memory on this side, have future
+permanent allocs use this side.
+=================
+*/
+void Hunk_ClearTempMemory( void ) {
+ if ( s_hunkData != NULL ) {
+ hunk_temp->temp = hunk_temp->permanent;
+ }
+}
+
+/*
+=================
+Hunk_Trash
+=================
+*/
+void Hunk_Trash( void ) {
+ int length, i, rnd;
+ char *buf, value;
+
+ return;
+
+ if ( s_hunkData == NULL )
+ return;
+
+#ifdef _DEBUG
+ Com_Error(ERR_DROP, "hunk trashed\n");
+ return;
+#endif
+
+ Cvar_Set("com_jp", "1");
+ Hunk_SwapBanks();
+
+ if ( hunk_permanent == &hunk_low ) {
+ buf = (void *)(s_hunkData + hunk_permanent->permanent);
+ } else {
+ buf = (void *)(s_hunkData + s_hunkTotal - hunk_permanent->permanent );
+ }
+ length = hunk_permanent->permanent;
+
+ if (length > 0x7FFFF) {
+ //randomly trash data within buf
+ rnd = random() * (length - 0x7FFFF);
+ value = 31;
+ for (i = 0; i < 0x7FFFF; i++) {
+ value *= 109;
+ buf[rnd+i] ^= value;
+ }
+ }
+}
+
+/*
+===================================================================
+
+EVENTS AND JOURNALING
+
+In addition to these events, .cfg files are also copied to the
+journaled file
+===================================================================
+*/
+
+// bk001129 - here we go again: upped from 64
+// FIXME TTimo blunt upping from 256 to 1024
+// https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=5
+#define MAX_PUSHED_EVENTS 1024
+// bk001129 - init, also static
+static int com_pushedEventsHead = 0;
+static int com_pushedEventsTail = 0;
+// bk001129 - static
+static sysEvent_t com_pushedEvents[MAX_PUSHED_EVENTS];
+
+/*
+=================
+Com_InitJournaling
+=================
+*/
+void Com_InitJournaling( void ) {
+ Com_StartupVariable( "journal" );
+ com_journal = Cvar_Get ("journal", "0", CVAR_INIT);
+ if ( !com_journal->integer ) {
+ return;
+ }
+
+ if ( com_journal->integer == 1 ) {
+ Com_Printf( "Journaling events\n");
+ com_journalFile = FS_FOpenFileWrite( "journal.dat" );
+ com_journalDataFile = FS_FOpenFileWrite( "journaldata.dat" );
+ } else if ( com_journal->integer == 2 ) {
+ Com_Printf( "Replaying journaled events\n");
+ FS_FOpenFileRead( "journal.dat", &com_journalFile, qtrue );
+ FS_FOpenFileRead( "journaldata.dat", &com_journalDataFile, qtrue );
+ }
+
+ if ( !com_journalFile || !com_journalDataFile ) {
+ Cvar_Set( "com_journal", "0" );
+ com_journalFile = 0;
+ com_journalDataFile = 0;
+ Com_Printf( "Couldn't open journal files\n" );
+ }
+}
+
+/*
+=================
+Com_GetRealEvent
+=================
+*/
+sysEvent_t Com_GetRealEvent( void ) {
+ int r;
+ sysEvent_t ev;
+
+ // either get an event from the system or the journal file
+ if ( com_journal->integer == 2 ) {
+ r = FS_Read( &ev, sizeof(ev), com_journalFile );
+ if ( r != sizeof(ev) ) {
+ Com_Error( ERR_FATAL, "Error reading from journal file" );
+ }
+ if ( ev.evPtrLength ) {
+ ev.evPtr = Z_Malloc( ev.evPtrLength );
+ r = FS_Read( ev.evPtr, ev.evPtrLength, com_journalFile );
+ if ( r != ev.evPtrLength ) {
+ Com_Error( ERR_FATAL, "Error reading from journal file" );
+ }
+ }
+ } else {
+ ev = Sys_GetEvent();
+
+ // write the journal value out if needed
+ if ( com_journal->integer == 1 ) {
+ r = FS_Write( &ev, sizeof(ev), com_journalFile );
+ if ( r != sizeof(ev) ) {
+ Com_Error( ERR_FATAL, "Error writing to journal file" );
+ }
+ if ( ev.evPtrLength ) {
+ r = FS_Write( ev.evPtr, ev.evPtrLength, com_journalFile );
+ if ( r != ev.evPtrLength ) {
+ Com_Error( ERR_FATAL, "Error writing to journal file" );
+ }
+ }
+ }
+ }
+
+ return ev;
+}
+
+
+/*
+=================
+Com_InitPushEvent
+=================
+*/
+// bk001129 - added
+void Com_InitPushEvent( void ) {
+ // clear the static buffer array
+ // this requires SE_NONE to be accepted as a valid but NOP event
+ memset( com_pushedEvents, 0, sizeof(com_pushedEvents) );
+ // reset counters while we are at it
+ // beware: GetEvent might still return an SE_NONE from the buffer
+ com_pushedEventsHead = 0;
+ com_pushedEventsTail = 0;
+}
+
+
+/*
+=================
+Com_PushEvent
+=================
+*/
+void Com_PushEvent( sysEvent_t *event ) {
+ sysEvent_t *ev;
+ static int printedWarning = 0; // bk001129 - init, bk001204 - explicit int
+
+ ev = &com_pushedEvents[ com_pushedEventsHead & (MAX_PUSHED_EVENTS-1) ];
+
+ if ( com_pushedEventsHead - com_pushedEventsTail >= MAX_PUSHED_EVENTS ) {
+
+ // don't print the warning constantly, or it can give time for more...
+ if ( !printedWarning ) {
+ printedWarning = qtrue;
+ Com_Printf( "WARNING: Com_PushEvent overflow\n" );
+ }
+
+ if ( ev->evPtr ) {
+ Z_Free( ev->evPtr );
+ }
+ com_pushedEventsTail++;
+ } else {
+ printedWarning = qfalse;
+ }
+
+ *ev = *event;
+ com_pushedEventsHead++;
+}
+
+/*
+=================
+Com_GetEvent
+=================
+*/
+sysEvent_t Com_GetEvent( void ) {
+ if ( com_pushedEventsHead > com_pushedEventsTail ) {
+ com_pushedEventsTail++;
+ return com_pushedEvents[ (com_pushedEventsTail-1) & (MAX_PUSHED_EVENTS-1) ];
+ }
+ return Com_GetRealEvent();
+}
+
+/*
+=================
+Com_RunAndTimeServerPacket
+=================
+*/
+void Com_RunAndTimeServerPacket( netadr_t *evFrom, msg_t *buf ) {
+ int t1, t2, msec;
+
+ t1 = 0;
+
+ if ( com_speeds->integer ) {
+ t1 = Sys_Milliseconds ();
+ }
+
+ SV_PacketEvent( *evFrom, buf );
+
+ if ( com_speeds->integer ) {
+ t2 = Sys_Milliseconds ();
+ msec = t2 - t1;
+ if ( com_speeds->integer == 3 ) {
+ Com_Printf( "SV_PacketEvent time: %i\n", msec );
+ }
+ }
+}
+
+/*
+=================
+Com_EventLoop
+
+Returns last event time
+=================
+*/
+int Com_EventLoop( void ) {
+ sysEvent_t ev;
+ netadr_t evFrom;
+ byte bufData[MAX_MSGLEN];
+ msg_t buf;
+
+ MSG_Init( &buf, bufData, sizeof( bufData ) );
+
+ while ( 1 ) {
+ ev = Com_GetEvent();
+
+ // if no more events are available
+ if ( ev.evType == SE_NONE ) {
+ // manually send packet events for the loopback channel
+ while ( NET_GetLoopPacket( NS_CLIENT, &evFrom, &buf ) ) {
+ CL_PacketEvent( evFrom, &buf );
+ }
+
+ while ( NET_GetLoopPacket( NS_SERVER, &evFrom, &buf ) ) {
+ // if the server just shut down, flush the events
+ if ( com_sv_running->integer ) {
+ Com_RunAndTimeServerPacket( &evFrom, &buf );
+ }
+ }
+
+ return ev.evTime;
+ }
+
+
+ switch ( ev.evType ) {
+ default:
+ // bk001129 - was ev.evTime
+ Com_Error( ERR_FATAL, "Com_EventLoop: bad event type %i", ev.evType );
+ break;
+ case SE_NONE:
+ break;
+ case SE_KEY:
+ CL_KeyEvent( ev.evValue, ev.evValue2, ev.evTime );
+ break;
+ case SE_CHAR:
+ CL_CharEvent( ev.evValue );
+ break;
+ case SE_MOUSE:
+ CL_MouseEvent( ev.evValue, ev.evValue2, ev.evTime );
+ break;
+ case SE_JOYSTICK_AXIS:
+ CL_JoystickEvent( ev.evValue, ev.evValue2, ev.evTime );
+ break;
+ case SE_CONSOLE:
+ Cbuf_AddText( (char *)ev.evPtr );
+ Cbuf_AddText( "\n" );
+ break;
+ case SE_PACKET:
+ // this cvar allows simulation of connections that
+ // drop a lot of packets. Note that loopback connections
+ // don't go through here at all.
+ if ( com_dropsim->value > 0 ) {
+ static int seed;
+
+ if ( Q_random( &seed ) < com_dropsim->value ) {
+ break; // drop this packet
+ }
+ }
+
+ evFrom = *(netadr_t *)ev.evPtr;
+ buf.cursize = ev.evPtrLength - sizeof( evFrom );
+
+ // we must copy the contents of the message out, because
+ // the event buffers are only large enough to hold the
+ // exact payload, but channel messages need to be large
+ // enough to hold fragment reassembly
+ if ( (unsigned)buf.cursize > buf.maxsize ) {
+ Com_Printf("Com_EventLoop: oversize packet\n");
+ continue;
+ }
+ Com_Memcpy( buf.data, (byte *)((netadr_t *)ev.evPtr + 1), buf.cursize );
+ if ( com_sv_running->integer ) {
+ Com_RunAndTimeServerPacket( &evFrom, &buf );
+ } else {
+ CL_PacketEvent( evFrom, &buf );
+ }
+ break;
+ }
+
+ // free any block data
+ if ( ev.evPtr ) {
+ Z_Free( ev.evPtr );
+ }
+ }
+
+ return 0; // never reached
+}
+
+/*
+================
+Com_Milliseconds
+
+Can be used for profiling, but will be journaled accurately
+================
+*/
+int Com_Milliseconds (void) {
+ sysEvent_t ev;
+
+ // get events and push them until we get a null event with the current time
+ do {
+
+ ev = Com_GetRealEvent();
+ if ( ev.evType != SE_NONE ) {
+ Com_PushEvent( &ev );
+ }
+ } while ( ev.evType != SE_NONE );
+
+ return ev.evTime;
+}
+
+//============================================================================
+
+/*
+=============
+Com_Error_f
+
+Just throw a fatal error to
+test error shutdown procedures
+=============
+*/
+static void Com_Error_f (void) {
+ if ( Cmd_Argc() > 1 ) {
+ Com_Error( ERR_DROP, "Testing drop error" );
+ } else {
+ Com_Error( ERR_FATAL, "Testing fatal error" );
+ }
+}
+
+
+/*
+=============
+Com_Freeze_f
+
+Just freeze in place for a given number of seconds to test
+error recovery
+=============
+*/
+static void Com_Freeze_f (void) {
+ float s;
+ int start, now;
+
+ if ( Cmd_Argc() != 2 ) {
+ Com_Printf( "freeze <seconds>\n" );
+ return;
+ }
+ s = atof( Cmd_Argv(1) );
+
+ start = Com_Milliseconds();
+
+ while ( 1 ) {
+ now = Com_Milliseconds();
+ if ( ( now - start ) * 0.001 > s ) {
+ break;
+ }
+ }
+}
+
+/*
+=================
+Com_Crash_f
+
+A way to force a bus error for development reasons
+=================
+*/
+static void Com_Crash_f( void ) {
+ * ( int * ) 0 = 0x12345678;
+}
+
+// TTimo: centralizing the cl_cdkey stuff after I discovered a buffer overflow problem with the dedicated server version
+// not sure it's necessary to have different defaults for regular and dedicated, but I don't want to risk it
+// https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=470
+#ifndef DEDICATED
+char cl_cdkey[34] = " ";
+#else
+char cl_cdkey[34] = "123456789";
+#endif
+
+/*
+=================
+Com_ReadCDKey
+=================
+*/
+qboolean CL_CDKeyValidate( const char *key, const char *checksum );
+void Com_ReadCDKey( const char *filename ) {
+ fileHandle_t f;
+ char buffer[33];
+ char fbuffer[MAX_OSPATH];
+
+ sprintf(fbuffer, "%s/q3key", filename);
+
+ FS_SV_FOpenFileRead( fbuffer, &f );
+ if ( !f ) {
+ Q_strncpyz( cl_cdkey, " ", 17 );
+ return;
+ }
+
+ Com_Memset( buffer, 0, sizeof(buffer) );
+
+ FS_Read( buffer, 16, f );
+ FS_FCloseFile( f );
+
+ if (CL_CDKeyValidate(buffer, NULL)) {
+ Q_strncpyz( cl_cdkey, buffer, 17 );
+ } else {
+ Q_strncpyz( cl_cdkey, " ", 17 );
+ }
+}
+
+/*
+=================
+Com_AppendCDKey
+=================
+*/
+void Com_AppendCDKey( const char *filename ) {
+ fileHandle_t f;
+ char buffer[33];
+ char fbuffer[MAX_OSPATH];
+
+ sprintf(fbuffer, "%s/q3key", filename);
+
+ FS_SV_FOpenFileRead( fbuffer, &f );
+ if (!f) {
+ Q_strncpyz( &cl_cdkey[16], " ", 17 );
+ return;
+ }
+
+ Com_Memset( buffer, 0, sizeof(buffer) );
+
+ FS_Read( buffer, 16, f );
+ FS_FCloseFile( f );
+
+ if (CL_CDKeyValidate(buffer, NULL)) {
+ strcat( &cl_cdkey[16], buffer );
+ } else {
+ Q_strncpyz( &cl_cdkey[16], " ", 17 );
+ }
+}
+
+#ifndef DEDICATED // bk001204
+/*
+=================
+Com_WriteCDKey
+=================
+*/
+static void Com_WriteCDKey( const char *filename, const char *ikey ) {
+ fileHandle_t f;
+ char fbuffer[MAX_OSPATH];
+ char key[17];
+
+
+ sprintf(fbuffer, "%s/q3key", filename);
+
+
+ Q_strncpyz( key, ikey, 17 );
+
+ if(!CL_CDKeyValidate(key, NULL) ) {
+ return;
+ }
+
+ f = FS_SV_FOpenFileWrite( fbuffer );
+ if ( !f ) {
+ Com_Printf ("Couldn't write %s.\n", filename );
+ return;
+ }
+
+ FS_Write( key, 16, f );
+
+ FS_Printf( f, "\n// generated by quake, do not modify\r\n" );
+ FS_Printf( f, "// Do not give this file to ANYONE.\r\n" );
+ FS_Printf( f, "// id Software and Activision will NOT ask you to send this file to them.\r\n");
+
+ FS_FCloseFile( f );
+}
+#endif
+
+
+/*
+=================
+Com_Init
+=================
+*/
+void Com_Init( char *commandLine ) {
+ char *s;
+
+ Com_Printf( "%s %s %s\n", Q3_VERSION, CPUSTRING, __DATE__ );
+
+ if ( setjmp (abortframe) ) {
+ Sys_Error ("Error during initialization");
+ }
+
+ // bk001129 - do this before anything else decides to push events
+ Com_InitPushEvent();
+
+ Com_InitSmallZoneMemory();
+ Cvar_Init ();
+
+ // prepare enough of the subsystems to handle
+ // cvar and command buffer management
+ Com_ParseCommandLine( commandLine );
+
+// Swap_Init ();
+ Cbuf_Init ();
+
+ Com_InitZoneMemory();
+ Cmd_Init ();
+
+ // override anything from the config files with command line args
+ Com_StartupVariable( NULL );
+
+ // get the developer cvar set as early as possible
+ Com_StartupVariable( "developer" );
+
+ // done early so bind command exists
+ CL_InitKeyCommands();
+
+ FS_InitFilesystem ();
+
+ Com_InitJournaling();
+
+ Cbuf_AddText ("exec default.cfg\n");
+
+ // skip the q3config.cfg if "safe" is on the command line
+ if ( !Com_SafeMode() ) {
+ Cbuf_AddText ("exec q3config.cfg\n");
+ }
+
+ Cbuf_AddText ("exec autoexec.cfg\n");
+
+ Cbuf_Execute ();
+
+ // override anything from the config files with command line args
+ Com_StartupVariable( NULL );
+
+ // get dedicated here for proper hunk megs initialization
+#ifdef DEDICATED
+ com_dedicated = Cvar_Get ("dedicated", "1", CVAR_ROM);
+#else
+ com_dedicated = Cvar_Get ("dedicated", "0", CVAR_LATCH);
+#endif
+ // allocate the stack based hunk allocator
+ Com_InitHunkMemory();
+
+ // if any archived cvars are modified after this, we will trigger a writing
+ // of the config file
+ cvar_modifiedFlags &= ~CVAR_ARCHIVE;
+
+ //
+ // init commands and vars
+ //
+ com_maxfps = Cvar_Get ("com_maxfps", "85", CVAR_ARCHIVE);
+ com_blood = Cvar_Get ("com_blood", "1", CVAR_ARCHIVE);
+
+ com_developer = Cvar_Get ("developer", "0", CVAR_TEMP );
+ com_logfile = Cvar_Get ("logfile", "0", CVAR_TEMP );
+
+ com_timescale = Cvar_Get ("timescale", "1", CVAR_CHEAT | CVAR_SYSTEMINFO );
+ com_fixedtime = Cvar_Get ("fixedtime", "0", CVAR_CHEAT);
+ com_showtrace = Cvar_Get ("com_showtrace", "0", CVAR_CHEAT);
+ com_dropsim = Cvar_Get ("com_dropsim", "0", CVAR_CHEAT);
+ com_viewlog = Cvar_Get( "viewlog", "0", CVAR_CHEAT );
+ com_speeds = Cvar_Get ("com_speeds", "0", 0);
+ com_timedemo = Cvar_Get ("timedemo", "0", CVAR_CHEAT);
+ com_cameraMode = Cvar_Get ("com_cameraMode", "0", CVAR_CHEAT);
+
+ cl_paused = Cvar_Get ("cl_paused", "0", CVAR_ROM);
+ sv_paused = Cvar_Get ("sv_paused", "0", CVAR_ROM);
+ com_sv_running = Cvar_Get ("sv_running", "0", CVAR_ROM);
+ com_cl_running = Cvar_Get ("cl_running", "0", CVAR_ROM);
+ com_buildScript = Cvar_Get( "com_buildScript", "0", 0 );
+
+ com_introPlayed = Cvar_Get( "com_introplayed", "0", CVAR_ARCHIVE);
+
+#if defined(_WIN32) && defined(_DEBUG)
+ com_noErrorInterrupt = Cvar_Get( "com_noErrorInterrupt", "0", 0 );
+#endif
+
+ if ( com_dedicated->integer ) {
+ if ( !com_viewlog->integer ) {
+ Cvar_Set( "viewlog", "1" );
+ }
+ }
+
+ if ( com_developer && com_developer->integer ) {
+ Cmd_AddCommand ("error", Com_Error_f);
+ Cmd_AddCommand ("crash", Com_Crash_f );
+ Cmd_AddCommand ("freeze", Com_Freeze_f);
+ }
+ Cmd_AddCommand ("quit", Com_Quit_f);
+ Cmd_AddCommand ("changeVectors", MSG_ReportChangeVectors_f );
+ Cmd_AddCommand ("writeconfig", Com_WriteConfig_f );
+
+ s = va("%s %s %s", Q3_VERSION, CPUSTRING, __DATE__ );
+ com_version = Cvar_Get ("version", s, CVAR_ROM | CVAR_SERVERINFO );
+
+ Sys_Init();
+ Netchan_Init( Com_Milliseconds() & 0xffff ); // pick a port value that should be nice and random
+ VM_Init();
+ SV_Init();
+
+ com_dedicated->modified = qfalse;
+ if ( !com_dedicated->integer ) {
+ CL_Init();
+ Sys_ShowConsole( com_viewlog->integer, qfalse );
+ }
+
+ // set com_frameTime so that if a map is started on the
+ // command line it will still be able to count on com_frameTime
+ // being random enough for a serverid
+ com_frameTime = Com_Milliseconds();
+
+ // add + commands from command line
+ if ( !Com_AddStartupCommands() ) {
+ // if the user didn't give any commands, run default action
+ if ( !com_dedicated->integer ) {
+ Cbuf_AddText ("cinematic idlogo.RoQ\n");
+ if( !com_introPlayed->integer ) {
+ Cvar_Set( com_introPlayed->name, "1" );
+ Cvar_Set( "nextmap", "cinematic intro.RoQ" );
+ }
+ }
+ }
+
+ // start in full screen ui mode
+ Cvar_Set("r_uiFullScreen", "1");
+
+ CL_StartHunkUsers();
+
+ // make sure single player is off by default
+ Cvar_Set("ui_singlePlayerActive", "0");
+
+ com_fullyInitialized = qtrue;
+ Com_Printf ("--- Common Initialization Complete ---\n");
+}
+
+//==================================================================
+
+void Com_WriteConfigToFile( const char *filename ) {
+ fileHandle_t f;
+
+ f = FS_FOpenFileWrite( filename );
+ if ( !f ) {
+ Com_Printf ("Couldn't write %s.\n", filename );
+ return;
+ }
+
+ FS_Printf (f, "// generated by quake, do not modify\n");
+ Key_WriteBindings (f);
+ Cvar_WriteVariables (f);
+ FS_FCloseFile( f );
+}
+
+
+/*
+===============
+Com_WriteConfiguration
+
+Writes key bindings and archived cvars to config file if modified
+===============
+*/
+void Com_WriteConfiguration( void ) {
+#ifndef DEDICATED // bk001204
+ cvar_t *fs;
+#endif
+ // if we are quiting without fully initializing, make sure
+ // we don't write out anything
+ if ( !com_fullyInitialized ) {
+ return;
+ }
+
+ if ( !(cvar_modifiedFlags & CVAR_ARCHIVE ) ) {
+ return;
+ }
+ cvar_modifiedFlags &= ~CVAR_ARCHIVE;
+
+ Com_WriteConfigToFile( "q3config.cfg" );
+
+ // bk001119 - tentative "not needed for dedicated"
+#ifndef DEDICATED
+ fs = Cvar_Get ("fs_game", "", CVAR_INIT|CVAR_SYSTEMINFO );
+ if (UI_usesUniqueCDKey() && fs && fs->string[0] != 0) {
+ Com_WriteCDKey( fs->string, &cl_cdkey[16] );
+ } else {
+ Com_WriteCDKey( "baseq3", cl_cdkey );
+ }
+#endif
+}
+
+
+/*
+===============
+Com_WriteConfig_f
+
+Write the config file to a specific name
+===============
+*/
+void Com_WriteConfig_f( void ) {
+ char filename[MAX_QPATH];
+
+ if ( Cmd_Argc() != 2 ) {
+ Com_Printf( "Usage: writeconfig <filename>\n" );
+ return;
+ }
+
+ Q_strncpyz( filename, Cmd_Argv(1), sizeof( filename ) );
+ COM_DefaultExtension( filename, sizeof( filename ), ".cfg" );
+ Com_Printf( "Writing %s.\n", filename );
+ Com_WriteConfigToFile( filename );
+}
+
+/*
+================
+Com_ModifyMsec
+================
+*/
+int Com_ModifyMsec( int msec ) {
+ int clampTime;
+
+ //
+ // modify time for debugging values
+ //
+ if ( com_fixedtime->integer ) {
+ msec = com_fixedtime->integer;
+ } else if ( com_timescale->value ) {
+ msec *= com_timescale->value;
+ } else if (com_cameraMode->integer) {
+ msec *= com_timescale->value;
+ }
+
+ // don't let it scale below 1 msec
+ if ( msec < 1 && com_timescale->value) {
+ msec = 1;
+ }
+
+ if ( com_dedicated->integer ) {
+ // dedicated servers don't want to clamp for a much longer
+ // period, because it would mess up all the client's views
+ // of time.
+ if ( msec > 500 ) {
+ Com_Printf( "Hitch warning: %i msec frame time\n", msec );
+ }
+ clampTime = 5000;
+ } else
+ if ( !com_sv_running->integer ) {
+ // clients of remote servers do not want to clamp time, because
+ // it would skew their view of the server's time temporarily
+ clampTime = 5000;
+ } else {
+ // for local single player gaming
+ // we may want to clamp the time to prevent players from
+ // flying off edges when something hitches.
+ clampTime = 200;
+ }
+
+ if ( msec > clampTime ) {
+ msec = clampTime;
+ }
+
+ return msec;
+}
+
+/*
+=================
+Com_Frame
+=================
+*/
+void Com_Frame( void ) {
+
+ int msec, minMsec;
+ static int lastTime;
+ int key;
+
+ int timeBeforeFirstEvents;
+ int timeBeforeServer;
+ int timeBeforeEvents;
+ int timeBeforeClient;
+ int timeAfter;
+
+
+
+
+
+ if ( setjmp (abortframe) ) {
+ return; // an ERR_DROP was thrown
+ }
+
+ // bk001204 - init to zero.
+ // also: might be clobbered by `longjmp' or `vfork'
+ timeBeforeFirstEvents =0;
+ timeBeforeServer =0;
+ timeBeforeEvents =0;
+ timeBeforeClient = 0;
+ timeAfter = 0;
+
+
+ // old net chan encryption key
+ key = 0x87243987;
+
+ // write config file if anything changed
+ Com_WriteConfiguration();
+
+ // if "viewlog" has been modified, show or hide the log console
+ if ( com_viewlog->modified ) {
+ if ( !com_dedicated->value ) {
+ Sys_ShowConsole( com_viewlog->integer, qfalse );
+ }
+ com_viewlog->modified = qfalse;
+ }
+
+ //
+ // main event loop
+ //
+ if ( com_speeds->integer ) {
+ timeBeforeFirstEvents = Sys_Milliseconds ();
+ }
+
+ // we may want to spin here if things are going too fast
+ if ( !com_dedicated->integer && com_maxfps->integer > 0 && !com_timedemo->integer ) {
+ minMsec = 1000 / com_maxfps->integer;
+ } else {
+ minMsec = 1;
+ }
+ do {
+ com_frameTime = Com_EventLoop();
+ if ( lastTime > com_frameTime ) {
+ lastTime = com_frameTime; // possible on first frame
+ }
+ msec = com_frameTime - lastTime;
+ } while ( msec < minMsec );
+ Cbuf_Execute ();
+
+ lastTime = com_frameTime;
+
+ // mess with msec if needed
+ com_frameMsec = msec;
+ msec = Com_ModifyMsec( msec );
+
+ //
+ // server side
+ //
+ if ( com_speeds->integer ) {
+ timeBeforeServer = Sys_Milliseconds ();
+ }
+
+ SV_Frame( msec );
+
+ // if "dedicated" has been modified, start up
+ // or shut down the client system.
+ // Do this after the server may have started,
+ // but before the client tries to auto-connect
+ if ( com_dedicated->modified ) {
+ // get the latched value
+ Cvar_Get( "dedicated", "0", 0 );
+ com_dedicated->modified = qfalse;
+ if ( !com_dedicated->integer ) {
+ CL_Init();
+ Sys_ShowConsole( com_viewlog->integer, qfalse );
+ } else {
+ CL_Shutdown();
+ Sys_ShowConsole( 1, qtrue );
+ }
+ }
+
+ //
+ // client system
+ //
+ if ( !com_dedicated->integer ) {
+ //
+ // run event loop a second time to get server to client packets
+ // without a frame of latency
+ //
+ if ( com_speeds->integer ) {
+ timeBeforeEvents = Sys_Milliseconds ();
+ }
+ Com_EventLoop();
+ Cbuf_Execute ();
+
+
+ //
+ // client side
+ //
+ if ( com_speeds->integer ) {
+ timeBeforeClient = Sys_Milliseconds ();
+ }
+
+ CL_Frame( msec );
+
+ if ( com_speeds->integer ) {
+ timeAfter = Sys_Milliseconds ();
+ }
+ }
+
+ //
+ // report timing information
+ //
+ if ( com_speeds->integer ) {
+ int all, sv, ev, cl;
+
+ all = timeAfter - timeBeforeServer;
+ sv = timeBeforeEvents - timeBeforeServer;
+ ev = timeBeforeServer - timeBeforeFirstEvents + timeBeforeClient - timeBeforeEvents;
+ cl = timeAfter - timeBeforeClient;
+ sv -= time_game;
+ cl -= time_frontend + time_backend;
+
+ Com_Printf ("frame:%i all:%3i sv:%3i ev:%3i cl:%3i gm:%3i rf:%3i bk:%3i\n",
+ com_frameNumber, all, sv, ev, cl, time_game, time_frontend, time_backend );
+ }
+
+ //
+ // trace optimization tracking
+ //
+ if ( com_showtrace->integer ) {
+
+ extern int c_traces, c_brush_traces, c_patch_traces;
+ extern int c_pointcontents;
+
+ Com_Printf ("%4i traces (%ib %ip) %4i points\n", c_traces,
+ c_brush_traces, c_patch_traces, c_pointcontents);
+ c_traces = 0;
+ c_brush_traces = 0;
+ c_patch_traces = 0;
+ c_pointcontents = 0;
+ }
+
+ // old net chan encryption key
+ key = lastTime * 0x87243987;
+
+ com_frameNumber++;
+}
+
+/*
+=================
+Com_Shutdown
+=================
+*/
+void Com_Shutdown (void) {
+ if (logfile) {
+ FS_FCloseFile (logfile);
+ logfile = 0;
+ }
+
+ if ( com_journalFile ) {
+ FS_FCloseFile( com_journalFile );
+ com_journalFile = 0;
+ }
+
+}
+
+#if !( defined __VECTORC )
+#if !( defined __linux__ || defined __FreeBSD__ ) // r010123 - include FreeBSD
+#if ((!id386) && (!defined __i386__)) // rcg010212 - for PPC
+
+void Com_Memcpy (void* dest, const void* src, const size_t count)
+{
+ memcpy(dest, src, count);
+}
+
+void Com_Memset (void* dest, const int val, const size_t count)
+{
+ memset(dest, val, count);
+}
+
+#else
+
+typedef enum
+{
+ PRE_READ, // prefetch assuming that buffer is used for reading only
+ PRE_WRITE, // prefetch assuming that buffer is used for writing only
+ PRE_READ_WRITE // prefetch assuming that buffer is used for both reading and writing
+} e_prefetch;
+
+void Com_Prefetch (const void *s, const unsigned int bytes, e_prefetch type);
+
+#define EMMS_INSTRUCTION __asm emms
+
+void _copyDWord (unsigned int* dest, const unsigned int constant, const unsigned int count) {
+ __asm
+ {
+ mov edx,dest
+ mov eax,constant
+ mov ecx,count
+ and ecx,~7
+ jz padding
+ sub ecx,8
+ jmp loopu
+ align 16
+loopu:
+ test [edx+ecx*4 + 28],ebx // fetch next block destination to L1 cache
+ mov [edx+ecx*4 + 0],eax
+ mov [edx+ecx*4 + 4],eax
+ mov [edx+ecx*4 + 8],eax
+ mov [edx+ecx*4 + 12],eax
+ mov [edx+ecx*4 + 16],eax
+ mov [edx+ecx*4 + 20],eax
+ mov [edx+ecx*4 + 24],eax
+ mov [edx+ecx*4 + 28],eax
+ sub ecx,8
+ jge loopu
+padding: mov ecx,count
+ mov ebx,ecx
+ and ecx,7
+ jz outta
+ and ebx,~7
+ lea edx,[edx+ebx*4] // advance dest pointer
+ test [edx+0],eax // fetch destination to L1 cache
+ cmp ecx,4
+ jl skip4
+ mov [edx+0],eax
+ mov [edx+4],eax
+ mov [edx+8],eax
+ mov [edx+12],eax
+ add edx,16
+ sub ecx,4
+skip4: cmp ecx,2
+ jl skip2
+ mov [edx+0],eax
+ mov [edx+4],eax
+ add edx,8
+ sub ecx,2
+skip2: cmp ecx,1
+ jl outta
+ mov [edx+0],eax
+outta:
+ }
+}
+
+// optimized memory copy routine that handles all alignment
+// cases and block sizes efficiently
+void Com_Memcpy (void* dest, const void* src, const size_t count) {
+ Com_Prefetch (src, count, PRE_READ);
+ __asm
+ {
+ push edi
+ push esi
+ mov ecx,count
+ cmp ecx,0 // count = 0 check (just to be on the safe side)
+ je outta
+ mov edx,dest
+ mov ebx,src
+ cmp ecx,32 // padding only?
+ jl padding
+
+ mov edi,ecx
+ and edi,~31 // edi = count&~31
+ sub edi,32
+
+ align 16
+loopMisAligned:
+ mov eax,[ebx + edi + 0 + 0*8]
+ mov esi,[ebx + edi + 4 + 0*8]
+ mov [edx+edi+0 + 0*8],eax
+ mov [edx+edi+4 + 0*8],esi
+ mov eax,[ebx + edi + 0 + 1*8]
+ mov esi,[ebx + edi + 4 + 1*8]
+ mov [edx+edi+0 + 1*8],eax
+ mov [edx+edi+4 + 1*8],esi
+ mov eax,[ebx + edi + 0 + 2*8]
+ mov esi,[ebx + edi + 4 + 2*8]
+ mov [edx+edi+0 + 2*8],eax
+ mov [edx+edi+4 + 2*8],esi
+ mov eax,[ebx + edi + 0 + 3*8]
+ mov esi,[ebx + edi + 4 + 3*8]
+ mov [edx+edi+0 + 3*8],eax
+ mov [edx+edi+4 + 3*8],esi
+ sub edi,32
+ jge loopMisAligned
+
+ mov edi,ecx
+ and edi,~31
+ add ebx,edi // increase src pointer
+ add edx,edi // increase dst pointer
+ and ecx,31 // new count
+ jz outta // if count = 0, get outta here
+
+padding:
+ cmp ecx,16
+ jl skip16
+ mov eax,dword ptr [ebx]
+ mov dword ptr [edx],eax
+ mov eax,dword ptr [ebx+4]
+ mov dword ptr [edx+4],eax
+ mov eax,dword ptr [ebx+8]
+ mov dword ptr [edx+8],eax
+ mov eax,dword ptr [ebx+12]
+ mov dword ptr [edx+12],eax
+ sub ecx,16
+ add ebx,16
+ add edx,16
+skip16:
+ cmp ecx,8
+ jl skip8
+ mov eax,dword ptr [ebx]
+ mov dword ptr [edx],eax
+ mov eax,dword ptr [ebx+4]
+ sub ecx,8
+ mov dword ptr [edx+4],eax
+ add ebx,8
+ add edx,8
+skip8:
+ cmp ecx,4
+ jl skip4
+ mov eax,dword ptr [ebx] // here 4-7 bytes
+ add ebx,4
+ sub ecx,4
+ mov dword ptr [edx],eax
+ add edx,4
+skip4: // 0-3 remaining bytes
+ cmp ecx,2
+ jl skip2
+ mov ax,word ptr [ebx] // two bytes
+ cmp ecx,3 // less than 3?
+ mov word ptr [edx],ax
+ jl outta
+ mov al,byte ptr [ebx+2] // last byte
+ mov byte ptr [edx+2],al
+ jmp outta
+skip2:
+ cmp ecx,1
+ jl outta
+ mov al,byte ptr [ebx]
+ mov byte ptr [edx],al
+outta:
+ pop esi
+ pop edi
+ }
+}
+
+void Com_Memset (void* dest, const int val, const size_t count)
+{
+ unsigned int fillval;
+
+ if (count < 8)
+ {
+ __asm
+ {
+ mov edx,dest
+ mov eax, val
+ mov ah,al
+ mov ebx,eax
+ and ebx, 0xffff
+ shl eax,16
+ add eax,ebx // eax now contains pattern
+ mov ecx,count
+ cmp ecx,4
+ jl skip4
+ mov [edx],eax // copy first dword
+ add edx,4
+ sub ecx,4
+ skip4: cmp ecx,2
+ jl skip2
+ mov word ptr [edx],ax // copy 2 bytes
+ add edx,2
+ sub ecx,2
+ skip2: cmp ecx,0
+ je skip1
+ mov byte ptr [edx],al // copy single byte
+ skip1:
+ }
+ return;
+ }
+
+ fillval = val;
+
+ fillval = fillval|(fillval<<8);
+ fillval = fillval|(fillval<<16); // fill dword with 8-bit pattern
+
+ _copyDWord ((unsigned int*)(dest),fillval, count/4);
+
+ __asm // padding of 0-3 bytes
+ {
+ mov ecx,count
+ mov eax,ecx
+ and ecx,3
+ jz skipA
+ and eax,~3
+ mov ebx,dest
+ add ebx,eax
+ mov eax,fillval
+ cmp ecx,2
+ jl skipB
+ mov word ptr [ebx],ax
+ cmp ecx,2
+ je skipA
+ mov byte ptr [ebx+2],al
+ jmp skipA
+skipB:
+ cmp ecx,0
+ je skipA
+ mov byte ptr [ebx],al
+skipA:
+ }
+}
+
+qboolean Com_Memcmp (const void *src0, const void *src1, const unsigned int count)
+{
+ unsigned int i;
+ // MMX version anyone?
+
+ if (count >= 16)
+ {
+ unsigned int *dw = (unsigned int*)(src0);
+ unsigned int *sw = (unsigned int*)(src1);
+
+ unsigned int nm2 = count/16;
+ for (i = 0; i < nm2; i+=4)
+ {
+ unsigned int tmp = (dw[i+0]-sw[i+0])|(dw[i+1]-sw[i+1])|
+ (dw[i+2]-sw[i+2])|(dw[i+3]-sw[i+3]);
+ if (tmp)
+ return qfalse;
+ }
+ }
+ if (count & 15)
+ {
+ byte *d = (byte*)src0;
+ byte *s = (byte*)src1;
+ for (i = count & 0xfffffff0; i < count; i++)
+ if (d[i]!=s[i])
+ return qfalse;
+ }
+
+ return qtrue;
+}
+
+void Com_Prefetch (const void *s, const unsigned int bytes, e_prefetch type)
+{
+ // write buffer prefetching is performed only if
+ // the processor benefits from it. Read and read/write
+ // prefetching is always performed.
+
+ switch (type)
+ {
+ case PRE_WRITE : break;
+ case PRE_READ:
+ case PRE_READ_WRITE:
+
+ __asm
+ {
+ mov ebx,s
+ mov ecx,bytes
+ cmp ecx,4096 // clamp to 4kB
+ jle skipClamp
+ mov ecx,4096
+skipClamp:
+ add ecx,0x1f
+ shr ecx,5 // number of cache lines
+ jz skip
+ jmp loopie
+
+ align 16
+ loopie: test byte ptr [ebx],al
+ add ebx,32
+ dec ecx
+ jnz loopie
+ skip:
+ }
+
+ break;
+ }
+}
+#endif
+#endif
+#endif // bk001208 - memset/memcpy assembly, Q_acos needed (RC4)
+//------------------------------------------------------------------------
+
+
+/*
+=====================
+Q_acos
+
+the msvc acos doesn't always return a value between -PI and PI:
+
+int i;
+i = 1065353246;
+acos(*(float*) &i) == -1.#IND0
+
+ This should go in q_math but it is too late to add new traps
+ to game and ui
+=====================
+*/
+float Q_acos(float c) {
+ float angle;
+
+ angle = acos(c);
+
+ if (angle > M_PI) {
+ return (float)M_PI;
+ }
+ if (angle < -M_PI) {
+ return (float)M_PI;
+ }
+ return angle;
+}
+
+/*
+===========================================
+command line completion
+===========================================
+*/
+
+/*
+==================
+Field_Clear
+==================
+*/
+void Field_Clear( field_t *edit ) {
+ memset(edit->buffer, 0, MAX_EDIT_LINE);
+ edit->cursor = 0;
+ edit->scroll = 0;
+}
+
+static const char *completionString;
+static char shortestMatch[MAX_TOKEN_CHARS];
+static int matchCount;
+// field we are working on, passed to Field_CompleteCommand (&g_consoleCommand for instance)
+static field_t *completionField;
+
+/*
+===============
+FindMatches
+
+===============
+*/
+static void FindMatches( const char *s ) {
+ int i;
+
+ if ( Q_stricmpn( s, completionString, strlen( completionString ) ) ) {
+ return;
+ }
+ matchCount++;
+ if ( matchCount == 1 ) {
+ Q_strncpyz( shortestMatch, s, sizeof( shortestMatch ) );
+ return;
+ }
+
+ // cut shortestMatch to the amount common with s
+ for ( i = 0 ; s[i] ; i++ ) {
+ if ( tolower(shortestMatch[i]) != tolower(s[i]) ) {
+ shortestMatch[i] = 0;
+ }
+ }
+}
+
+/*
+===============
+PrintMatches
+
+===============
+*/
+static void PrintMatches( const char *s ) {
+ if ( !Q_stricmpn( s, shortestMatch, strlen( shortestMatch ) ) ) {
+ Com_Printf( " %s\n", s );
+ }
+}
+
+static void keyConcatArgs( void ) {
+ int i;
+ char *arg;
+
+ for ( i = 1 ; i < Cmd_Argc() ; i++ ) {
+ Q_strcat( completionField->buffer, sizeof( completionField->buffer ), " " );
+ arg = Cmd_Argv( i );
+ while (*arg) {
+ if (*arg == ' ') {
+ Q_strcat( completionField->buffer, sizeof( completionField->buffer ), "\"");
+ break;
+ }
+ arg++;
+ }
+ Q_strcat( completionField->buffer, sizeof( completionField->buffer ), Cmd_Argv( i ) );
+ if (*arg == ' ') {
+ Q_strcat( completionField->buffer, sizeof( completionField->buffer ), "\"");
+ }
+ }
+}
+
+static void ConcatRemaining( const char *src, const char *start ) {
+ char *str;
+
+ str = strstr(src, start);
+ if (!str) {
+ keyConcatArgs();
+ return;
+ }
+
+ str += strlen(start);
+ Q_strcat( completionField->buffer, sizeof( completionField->buffer ), str);
+}
+
+/*
+===============
+Field_CompleteCommand
+
+perform Tab expansion
+NOTE TTimo this was originally client code only
+ moved to common code when writing tty console for *nix dedicated server
+===============
+*/
+void Field_CompleteCommand( field_t *field ) {
+ field_t temp;
+
+ completionField = field;
+
+ // only look at the first token for completion purposes
+ Cmd_TokenizeString( completionField->buffer );
+
+ completionString = Cmd_Argv(0);
+ if ( completionString[0] == '\\' || completionString[0] == '/' ) {
+ completionString++;
+ }
+ matchCount = 0;
+ shortestMatch[0] = 0;
+
+ if ( strlen( completionString ) == 0 ) {
+ return;
+ }
+
+ Cmd_CommandCompletion( FindMatches );
+ Cvar_CommandCompletion( FindMatches );
+
+ if ( matchCount == 0 ) {
+ return; // no matches
+ }
+
+ Com_Memcpy(&temp, completionField, sizeof(field_t));
+
+ if ( matchCount == 1 ) {
+ Com_sprintf( completionField->buffer, sizeof( completionField->buffer ), "\\%s", shortestMatch );
+ if ( Cmd_Argc() == 1 ) {
+ Q_strcat( completionField->buffer, sizeof( completionField->buffer ), " " );
+ } else {
+ ConcatRemaining( temp.buffer, completionString );
+ }
+ completionField->cursor = strlen( completionField->buffer );
+ return;
+ }
+
+ // multiple matches, complete to shortest
+ Com_sprintf( completionField->buffer, sizeof( completionField->buffer ), "\\%s", shortestMatch );
+ completionField->cursor = strlen( completionField->buffer );
+ ConcatRemaining( temp.buffer, completionString );
+
+ Com_Printf( "]%s\n", completionField->buffer );
+
+ // run through again, printing matches
+ Cmd_CommandCompletion( PrintMatches );
+ Cvar_CommandCompletion( PrintMatches );
+}
diff --git a/code/qcommon/cvar.c b/code/qcommon/cvar.c
new file mode 100755
index 0000000..864969c
--- /dev/null
+++ b/code/qcommon/cvar.c
@@ -0,0 +1,906 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// cvar.c -- dynamic variable tracking
+
+#include "../game/q_shared.h"
+#include "qcommon.h"
+
+cvar_t *cvar_vars;
+cvar_t *cvar_cheats;
+int cvar_modifiedFlags;
+
+#define MAX_CVARS 1024
+cvar_t cvar_indexes[MAX_CVARS];
+int cvar_numIndexes;
+
+#define FILE_HASH_SIZE 256
+static cvar_t* hashTable[FILE_HASH_SIZE];
+
+cvar_t *Cvar_Set2( const char *var_name, const char *value, qboolean force);
+
+/*
+================
+return a hash value for the filename
+================
+*/
+static long generateHashValue( const char *fname ) {
+ int i;
+ long hash;
+ char letter;
+
+ hash = 0;
+ i = 0;
+ while (fname[i] != '\0') {
+ letter = tolower(fname[i]);
+ hash+=(long)(letter)*(i+119);
+ i++;
+ }
+ hash &= (FILE_HASH_SIZE-1);
+ return hash;
+}
+
+/*
+============
+Cvar_ValidateString
+============
+*/
+static qboolean Cvar_ValidateString( const char *s ) {
+ if ( !s ) {
+ return qfalse;
+ }
+ if ( strchr( s, '\\' ) ) {
+ return qfalse;
+ }
+ if ( strchr( s, '\"' ) ) {
+ return qfalse;
+ }
+ if ( strchr( s, ';' ) ) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+/*
+============
+Cvar_FindVar
+============
+*/
+static cvar_t *Cvar_FindVar( const char *var_name ) {
+ cvar_t *var;
+ long hash;
+
+ hash = generateHashValue(var_name);
+
+ for (var=hashTable[hash] ; var ; var=var->hashNext) {
+ if (!Q_stricmp(var_name, var->name)) {
+ return var;
+ }
+ }
+
+ return NULL;
+}
+
+/*
+============
+Cvar_VariableValue
+============
+*/
+float Cvar_VariableValue( const char *var_name ) {
+ cvar_t *var;
+
+ var = Cvar_FindVar (var_name);
+ if (!var)
+ return 0;
+ return var->value;
+}
+
+
+/*
+============
+Cvar_VariableIntegerValue
+============
+*/
+int Cvar_VariableIntegerValue( const char *var_name ) {
+ cvar_t *var;
+
+ var = Cvar_FindVar (var_name);
+ if (!var)
+ return 0;
+ return var->integer;
+}
+
+
+/*
+============
+Cvar_VariableString
+============
+*/
+char *Cvar_VariableString( const char *var_name ) {
+ cvar_t *var;
+
+ var = Cvar_FindVar (var_name);
+ if (!var)
+ return "";
+ return var->string;
+}
+
+
+/*
+============
+Cvar_VariableStringBuffer
+============
+*/
+void Cvar_VariableStringBuffer( const char *var_name, char *buffer, int bufsize ) {
+ cvar_t *var;
+
+ var = Cvar_FindVar (var_name);
+ if (!var) {
+ *buffer = 0;
+ }
+ else {
+ Q_strncpyz( buffer, var->string, bufsize );
+ }
+}
+
+
+/*
+============
+Cvar_CommandCompletion
+============
+*/
+void Cvar_CommandCompletion( void(*callback)(const char *s) ) {
+ cvar_t *cvar;
+
+ for ( cvar = cvar_vars ; cvar ; cvar = cvar->next ) {
+ callback( cvar->name );
+ }
+}
+
+
+/*
+============
+Cvar_Get
+
+If the variable already exists, the value will not be set unless CVAR_ROM
+The flags will be or'ed in if the variable exists.
+============
+*/
+cvar_t *Cvar_Get( const char *var_name, const char *var_value, int flags ) {
+ cvar_t *var;
+ long hash;
+
+ if ( !var_name || ! var_value ) {
+ Com_Error( ERR_FATAL, "Cvar_Get: NULL parameter" );
+ }
+
+ if ( !Cvar_ValidateString( var_name ) ) {
+ Com_Printf("invalid cvar name string: %s\n", var_name );
+ var_name = "BADNAME";
+ }
+
+#if 0 // FIXME: values with backslash happen
+ if ( !Cvar_ValidateString( var_value ) ) {
+ Com_Printf("invalid cvar value string: %s\n", var_value );
+ var_value = "BADVALUE";
+ }
+#endif
+
+ var = Cvar_FindVar (var_name);
+ if ( var ) {
+ // if the C code is now specifying a variable that the user already
+ // set a value for, take the new value as the reset value
+ if ( ( var->flags & CVAR_USER_CREATED ) && !( flags & CVAR_USER_CREATED )
+ && var_value[0] ) {
+ var->flags &= ~CVAR_USER_CREATED;
+ Z_Free( var->resetString );
+ var->resetString = CopyString( var_value );
+
+ // ZOID--needs to be set so that cvars the game sets as
+ // SERVERINFO get sent to clients
+ cvar_modifiedFlags |= flags;
+ }
+
+ var->flags |= flags;
+ // only allow one non-empty reset string without a warning
+ if ( !var->resetString[0] ) {
+ // we don't have a reset string yet
+ Z_Free( var->resetString );
+ var->resetString = CopyString( var_value );
+ } else if ( var_value[0] && strcmp( var->resetString, var_value ) ) {
+ Com_DPrintf( "Warning: cvar \"%s\" given initial values: \"%s\" and \"%s\"\n",
+ var_name, var->resetString, var_value );
+ }
+ // if we have a latched string, take that value now
+ if ( var->latchedString ) {
+ char *s;
+
+ s = var->latchedString;
+ var->latchedString = NULL; // otherwise cvar_set2 would free it
+ Cvar_Set2( var_name, s, qtrue );
+ Z_Free( s );
+ }
+
+// use a CVAR_SET for rom sets, get won't override
+#if 0
+ // CVAR_ROM always overrides
+ if ( flags & CVAR_ROM ) {
+ Cvar_Set2( var_name, var_value, qtrue );
+ }
+#endif
+ return var;
+ }
+
+ //
+ // allocate a new cvar
+ //
+ if ( cvar_numIndexes >= MAX_CVARS ) {
+ Com_Error( ERR_FATAL, "MAX_CVARS" );
+ }
+ var = &cvar_indexes[cvar_numIndexes];
+ cvar_numIndexes++;
+ var->name = CopyString (var_name);
+ var->string = CopyString (var_value);
+ var->modified = qtrue;
+ var->modificationCount = 1;
+ var->value = atof (var->string);
+ var->integer = atoi(var->string);
+ var->resetString = CopyString( var_value );
+
+ // link the variable in
+ var->next = cvar_vars;
+ cvar_vars = var;
+
+ var->flags = flags;
+
+ hash = generateHashValue(var_name);
+ var->hashNext = hashTable[hash];
+ hashTable[hash] = var;
+
+ return var;
+}
+
+/*
+============
+Cvar_Set2
+============
+*/
+cvar_t *Cvar_Set2( const char *var_name, const char *value, qboolean force ) {
+ cvar_t *var;
+
+ Com_DPrintf( "Cvar_Set2: %s %s\n", var_name, value );
+
+ if ( !Cvar_ValidateString( var_name ) ) {
+ Com_Printf("invalid cvar name string: %s\n", var_name );
+ var_name = "BADNAME";
+ }
+
+#if 0 // FIXME
+ if ( value && !Cvar_ValidateString( value ) ) {
+ Com_Printf("invalid cvar value string: %s\n", value );
+ var_value = "BADVALUE";
+ }
+#endif
+
+ var = Cvar_FindVar (var_name);
+ if (!var) {
+ if ( !value ) {
+ return NULL;
+ }
+ // create it
+ if ( !force ) {
+ return Cvar_Get( var_name, value, CVAR_USER_CREATED );
+ } else {
+ return Cvar_Get (var_name, value, 0);
+ }
+ }
+
+ if (!value ) {
+ value = var->resetString;
+ }
+
+ if (!strcmp(value,var->string)) {
+ return var;
+ }
+ // note what types of cvars have been modified (userinfo, archive, serverinfo, systeminfo)
+ cvar_modifiedFlags |= var->flags;
+
+ if (!force)
+ {
+ if (var->flags & CVAR_ROM)
+ {
+ Com_Printf ("%s is read only.\n", var_name);
+ return var;
+ }
+
+ if (var->flags & CVAR_INIT)
+ {
+ Com_Printf ("%s is write protected.\n", var_name);
+ return var;
+ }
+
+ if (var->flags & CVAR_LATCH)
+ {
+ if (var->latchedString)
+ {
+ if (strcmp(value, var->latchedString) == 0)
+ return var;
+ Z_Free (var->latchedString);
+ }
+ else
+ {
+ if (strcmp(value, var->string) == 0)
+ return var;
+ }
+
+ Com_Printf ("%s will be changed upon restarting.\n", var_name);
+ var->latchedString = CopyString(value);
+ var->modified = qtrue;
+ var->modificationCount++;
+ return var;
+ }
+
+ if ( (var->flags & CVAR_CHEAT) && !cvar_cheats->integer )
+ {
+ Com_Printf ("%s is cheat protected.\n", var_name);
+ return var;
+ }
+
+ }
+ else
+ {
+ if (var->latchedString)
+ {
+ Z_Free (var->latchedString);
+ var->latchedString = NULL;
+ }
+ }
+
+ if (!strcmp(value, var->string))
+ return var; // not changed
+
+ var->modified = qtrue;
+ var->modificationCount++;
+
+ Z_Free (var->string); // free the old value string
+
+ var->string = CopyString(value);
+ var->value = atof (var->string);
+ var->integer = atoi (var->string);
+
+ return var;
+}
+
+/*
+============
+Cvar_Set
+============
+*/
+void Cvar_Set( const char *var_name, const char *value) {
+ Cvar_Set2 (var_name, value, qtrue);
+}
+
+/*
+============
+Cvar_SetLatched
+============
+*/
+void Cvar_SetLatched( const char *var_name, const char *value) {
+ Cvar_Set2 (var_name, value, qfalse);
+}
+
+/*
+============
+Cvar_SetValue
+============
+*/
+void Cvar_SetValue( const char *var_name, float value) {
+ char val[32];
+
+ if ( value == (int)value ) {
+ Com_sprintf (val, sizeof(val), "%i",(int)value);
+ } else {
+ Com_sprintf (val, sizeof(val), "%f",value);
+ }
+ Cvar_Set (var_name, val);
+}
+
+
+/*
+============
+Cvar_Reset
+============
+*/
+void Cvar_Reset( const char *var_name ) {
+ Cvar_Set2( var_name, NULL, qfalse );
+}
+
+
+/*
+============
+Cvar_SetCheatState
+
+Any testing variables will be reset to the safe values
+============
+*/
+void Cvar_SetCheatState( void ) {
+ cvar_t *var;
+
+ // set all default vars to the safe value
+ for ( var = cvar_vars ; var ; var = var->next ) {
+ if ( var->flags & CVAR_CHEAT ) {
+ // the CVAR_LATCHED|CVAR_CHEAT vars might escape the reset here
+ // because of a different var->latchedString
+ if (var->latchedString)
+ {
+ Z_Free(var->latchedString);
+ var->latchedString = NULL;
+ }
+ if (strcmp(var->resetString,var->string)) {
+ Cvar_Set( var->name, var->resetString );
+ }
+ }
+ }
+}
+
+/*
+============
+Cvar_Command
+
+Handles variable inspection and changing from the console
+============
+*/
+qboolean Cvar_Command( void ) {
+ cvar_t *v;
+
+ // check variables
+ v = Cvar_FindVar (Cmd_Argv(0));
+ if (!v) {
+ return qfalse;
+ }
+
+ // perform a variable print or set
+ if ( Cmd_Argc() == 1 ) {
+ Com_Printf ("\"%s\" is:\"%s" S_COLOR_WHITE "\" default:\"%s" S_COLOR_WHITE "\"\n", v->name, v->string, v->resetString );
+ if ( v->latchedString ) {
+ Com_Printf( "latched: \"%s\"\n", v->latchedString );
+ }
+ return qtrue;
+ }
+
+ // set the value if forcing isn't required
+ Cvar_Set2 (v->name, Cmd_Argv(1), qfalse);
+ return qtrue;
+}
+
+
+/*
+============
+Cvar_Toggle_f
+
+Toggles a cvar for easy single key binding
+============
+*/
+void Cvar_Toggle_f( void ) {
+ int v;
+
+ if ( Cmd_Argc() != 2 ) {
+ Com_Printf ("usage: toggle <variable>\n");
+ return;
+ }
+
+ v = Cvar_VariableValue( Cmd_Argv( 1 ) );
+ v = !v;
+
+ Cvar_Set2 (Cmd_Argv(1), va("%i", v), qfalse);
+}
+
+/*
+============
+Cvar_Set_f
+
+Allows setting and defining of arbitrary cvars from console, even if they
+weren't declared in C code.
+============
+*/
+void Cvar_Set_f( void ) {
+ int i, c, l, len;
+ char combined[MAX_STRING_TOKENS];
+
+ c = Cmd_Argc();
+ if ( c < 3 ) {
+ Com_Printf ("usage: set <variable> <value>\n");
+ return;
+ }
+
+ combined[0] = 0;
+ l = 0;
+ for ( i = 2 ; i < c ; i++ ) {
+ len = strlen ( Cmd_Argv( i ) + 1 );
+ if ( l + len >= MAX_STRING_TOKENS - 2 ) {
+ break;
+ }
+ strcat( combined, Cmd_Argv( i ) );
+ if ( i != c-1 ) {
+ strcat( combined, " " );
+ }
+ l += len;
+ }
+ Cvar_Set2 (Cmd_Argv(1), combined, qfalse);
+}
+
+/*
+============
+Cvar_SetU_f
+
+As Cvar_Set, but also flags it as userinfo
+============
+*/
+void Cvar_SetU_f( void ) {
+ cvar_t *v;
+
+ if ( Cmd_Argc() != 3 ) {
+ Com_Printf ("usage: setu <variable> <value>\n");
+ return;
+ }
+ Cvar_Set_f();
+ v = Cvar_FindVar( Cmd_Argv( 1 ) );
+ if ( !v ) {
+ return;
+ }
+ v->flags |= CVAR_USERINFO;
+}
+
+/*
+============
+Cvar_SetS_f
+
+As Cvar_Set, but also flags it as userinfo
+============
+*/
+void Cvar_SetS_f( void ) {
+ cvar_t *v;
+
+ if ( Cmd_Argc() != 3 ) {
+ Com_Printf ("usage: sets <variable> <value>\n");
+ return;
+ }
+ Cvar_Set_f();
+ v = Cvar_FindVar( Cmd_Argv( 1 ) );
+ if ( !v ) {
+ return;
+ }
+ v->flags |= CVAR_SERVERINFO;
+}
+
+/*
+============
+Cvar_SetA_f
+
+As Cvar_Set, but also flags it as archived
+============
+*/
+void Cvar_SetA_f( void ) {
+ cvar_t *v;
+
+ if ( Cmd_Argc() != 3 ) {
+ Com_Printf ("usage: seta <variable> <value>\n");
+ return;
+ }
+ Cvar_Set_f();
+ v = Cvar_FindVar( Cmd_Argv( 1 ) );
+ if ( !v ) {
+ return;
+ }
+ v->flags |= CVAR_ARCHIVE;
+}
+
+/*
+============
+Cvar_Reset_f
+============
+*/
+void Cvar_Reset_f( void ) {
+ if ( Cmd_Argc() != 2 ) {
+ Com_Printf ("usage: reset <variable>\n");
+ return;
+ }
+ Cvar_Reset( Cmd_Argv( 1 ) );
+}
+
+/*
+============
+Cvar_WriteVariables
+
+Appends lines containing "set variable value" for all variables
+with the archive flag set to qtrue.
+============
+*/
+void Cvar_WriteVariables( fileHandle_t f ) {
+ cvar_t *var;
+ char buffer[1024];
+
+ for (var = cvar_vars ; var ; var = var->next) {
+ if( Q_stricmp( var->name, "cl_cdkey" ) == 0 ) {
+ continue;
+ }
+ if( var->flags & CVAR_ARCHIVE ) {
+ // write the latched value, even if it hasn't taken effect yet
+ if ( var->latchedString ) {
+ Com_sprintf (buffer, sizeof(buffer), "seta %s \"%s\"\n", var->name, var->latchedString);
+ } else {
+ Com_sprintf (buffer, sizeof(buffer), "seta %s \"%s\"\n", var->name, var->string);
+ }
+ FS_Printf (f, "%s", buffer);
+ }
+ }
+}
+
+/*
+============
+Cvar_List_f
+============
+*/
+void Cvar_List_f( void ) {
+ cvar_t *var;
+ int i;
+ char *match;
+
+ if ( Cmd_Argc() > 1 ) {
+ match = Cmd_Argv( 1 );
+ } else {
+ match = NULL;
+ }
+
+ i = 0;
+ for (var = cvar_vars ; var ; var = var->next, i++)
+ {
+ if (match && !Com_Filter(match, var->name, qfalse)) continue;
+
+ if (var->flags & CVAR_SERVERINFO) {
+ Com_Printf("S");
+ } else {
+ Com_Printf(" ");
+ }
+ if (var->flags & CVAR_USERINFO) {
+ Com_Printf("U");
+ } else {
+ Com_Printf(" ");
+ }
+ if (var->flags & CVAR_ROM) {
+ Com_Printf("R");
+ } else {
+ Com_Printf(" ");
+ }
+ if (var->flags & CVAR_INIT) {
+ Com_Printf("I");
+ } else {
+ Com_Printf(" ");
+ }
+ if (var->flags & CVAR_ARCHIVE) {
+ Com_Printf("A");
+ } else {
+ Com_Printf(" ");
+ }
+ if (var->flags & CVAR_LATCH) {
+ Com_Printf("L");
+ } else {
+ Com_Printf(" ");
+ }
+ if (var->flags & CVAR_CHEAT) {
+ Com_Printf("C");
+ } else {
+ Com_Printf(" ");
+ }
+
+ Com_Printf (" %s \"%s\"\n", var->name, var->string);
+ }
+
+ Com_Printf ("\n%i total cvars\n", i);
+ Com_Printf ("%i cvar indexes\n", cvar_numIndexes);
+}
+
+/*
+============
+Cvar_Restart_f
+
+Resets all cvars to their hardcoded values
+============
+*/
+void Cvar_Restart_f( void ) {
+ cvar_t *var;
+ cvar_t **prev;
+
+ prev = &cvar_vars;
+ while ( 1 ) {
+ var = *prev;
+ if ( !var ) {
+ break;
+ }
+
+ // don't mess with rom values, or some inter-module
+ // communication will get broken (com_cl_running, etc)
+ if ( var->flags & ( CVAR_ROM | CVAR_INIT | CVAR_NORESTART ) ) {
+ prev = &var->next;
+ continue;
+ }
+
+ // throw out any variables the user created
+ if ( var->flags & CVAR_USER_CREATED ) {
+ *prev = var->next;
+ if ( var->name ) {
+ Z_Free( var->name );
+ }
+ if ( var->string ) {
+ Z_Free( var->string );
+ }
+ if ( var->latchedString ) {
+ Z_Free( var->latchedString );
+ }
+ if ( var->resetString ) {
+ Z_Free( var->resetString );
+ }
+ // clear the var completely, since we
+ // can't remove the index from the list
+ Com_Memset( var, 0, sizeof( var ) );
+ continue;
+ }
+
+ Cvar_Set( var->name, var->resetString );
+
+ prev = &var->next;
+ }
+}
+
+
+
+/*
+=====================
+Cvar_InfoString
+=====================
+*/
+char *Cvar_InfoString( int bit ) {
+ static char info[MAX_INFO_STRING];
+ cvar_t *var;
+
+ info[0] = 0;
+
+ for (var = cvar_vars ; var ; var = var->next) {
+ if (var->flags & bit) {
+ Info_SetValueForKey (info, var->name, var->string);
+ }
+ }
+ return info;
+}
+
+/*
+=====================
+Cvar_InfoString_Big
+
+ handles large info strings ( CS_SYSTEMINFO )
+=====================
+*/
+char *Cvar_InfoString_Big( int bit ) {
+ static char info[BIG_INFO_STRING];
+ cvar_t *var;
+
+ info[0] = 0;
+
+ for (var = cvar_vars ; var ; var = var->next) {
+ if (var->flags & bit) {
+ Info_SetValueForKey_Big (info, var->name, var->string);
+ }
+ }
+ return info;
+}
+
+
+
+/*
+=====================
+Cvar_InfoStringBuffer
+=====================
+*/
+void Cvar_InfoStringBuffer( int bit, char* buff, int buffsize ) {
+ Q_strncpyz(buff,Cvar_InfoString(bit),buffsize);
+}
+
+/*
+=====================
+Cvar_Register
+
+basically a slightly modified Cvar_Get for the interpreted modules
+=====================
+*/
+void Cvar_Register( vmCvar_t *vmCvar, const char *varName, const char *defaultValue, int flags ) {
+ cvar_t *cv;
+
+ cv = Cvar_Get( varName, defaultValue, flags );
+ if ( !vmCvar ) {
+ return;
+ }
+ vmCvar->handle = cv - cvar_indexes;
+ vmCvar->modificationCount = -1;
+ Cvar_Update( vmCvar );
+}
+
+
+/*
+=====================
+Cvar_Register
+
+updates an interpreted modules' version of a cvar
+=====================
+*/
+void Cvar_Update( vmCvar_t *vmCvar ) {
+ cvar_t *cv = NULL; // bk001129
+ assert(vmCvar); // bk
+
+ if ( (unsigned)vmCvar->handle >= cvar_numIndexes ) {
+ Com_Error( ERR_DROP, "Cvar_Update: handle out of range" );
+ }
+
+ cv = cvar_indexes + vmCvar->handle;
+
+ if ( cv->modificationCount == vmCvar->modificationCount ) {
+ return;
+ }
+ if ( !cv->string ) {
+ return; // variable might have been cleared by a cvar_restart
+ }
+ vmCvar->modificationCount = cv->modificationCount;
+ // bk001129 - mismatches.
+ if ( strlen(cv->string)+1 > MAX_CVAR_VALUE_STRING )
+ Com_Error( ERR_DROP, "Cvar_Update: src %s length %d exceeds MAX_CVAR_VALUE_STRING",
+ cv->string,
+ strlen(cv->string),
+ sizeof(vmCvar->string) );
+ // bk001212 - Q_strncpyz guarantees zero padding and dest[MAX_CVAR_VALUE_STRING-1]==0
+ // bk001129 - paranoia. Never trust the destination string.
+ // bk001129 - beware, sizeof(char*) is always 4 (for cv->string).
+ // sizeof(vmCvar->string) always MAX_CVAR_VALUE_STRING
+ //Q_strncpyz( vmCvar->string, cv->string, sizeof( vmCvar->string ) ); // id
+ Q_strncpyz( vmCvar->string, cv->string, MAX_CVAR_VALUE_STRING );
+
+ vmCvar->value = cv->value;
+ vmCvar->integer = cv->integer;
+}
+
+
+/*
+============
+Cvar_Init
+
+Reads in all archived cvars
+============
+*/
+void Cvar_Init (void) {
+ cvar_cheats = Cvar_Get("sv_cheats", "1", CVAR_ROM | CVAR_SYSTEMINFO );
+
+ Cmd_AddCommand ("toggle", Cvar_Toggle_f);
+ Cmd_AddCommand ("set", Cvar_Set_f);
+ Cmd_AddCommand ("sets", Cvar_SetS_f);
+ Cmd_AddCommand ("setu", Cvar_SetU_f);
+ Cmd_AddCommand ("seta", Cvar_SetA_f);
+ Cmd_AddCommand ("reset", Cvar_Reset_f);
+ Cmd_AddCommand ("cvarlist", Cvar_List_f);
+ Cmd_AddCommand ("cvar_restart", Cvar_Restart_f);
+}
diff --git a/code/qcommon/files.c b/code/qcommon/files.c
new file mode 100755
index 0000000..f27d2f2
--- /dev/null
+++ b/code/qcommon/files.c
@@ -0,0 +1,3419 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+/*****************************************************************************
+ * name: files.c
+ *
+ * desc: handle based filesystem for Quake III Arena
+ *
+ * $Archive: /MissionPack/code/qcommon/files.c $
+ *
+ *****************************************************************************/
+
+
+#include "../game/q_shared.h"
+#include "qcommon.h"
+#include "unzip.h"
+
+/*
+=============================================================================
+
+QUAKE3 FILESYSTEM
+
+All of Quake's data access is through a hierarchical file system, but the contents of
+the file system can be transparently merged from several sources.
+
+A "qpath" is a reference to game file data. MAX_ZPATH is 256 characters, which must include
+a terminating zero. "..", "\\", and ":" are explicitly illegal in qpaths to prevent any
+references outside the quake directory system.
+
+The "base path" is the path to the directory holding all the game directories and usually
+the executable. It defaults to ".", but can be overridden with a "+set fs_basepath c:\quake3"
+command line to allow code debugging in a different directory. Basepath cannot
+be modified at all after startup. Any files that are created (demos, screenshots,
+etc) will be created reletive to the base path, so base path should usually be writable.
+
+The "cd path" is the path to an alternate hierarchy that will be searched if a file
+is not located in the base path. A user can do a partial install that copies some
+data to a base path created on their hard drive and leave the rest on the cd. Files
+are never writen to the cd path. It defaults to a value set by the installer, like
+"e:\quake3", but it can be overridden with "+set ds_cdpath g:\quake3".
+
+If a user runs the game directly from a CD, the base path would be on the CD. This
+should still function correctly, but all file writes will fail (harmlessly).
+
+The "home path" is the path used for all write access. On win32 systems we have "base path"
+== "home path", but on *nix systems the base installation is usually readonly, and
+"home path" points to ~/.q3a or similar
+
+The user can also install custom mods and content in "home path", so it should be searched
+along with "home path" and "cd path" for game content.
+
+
+The "base game" is the directory under the paths where data comes from by default, and
+can be either "baseq3" or "demoq3".
+
+The "current game" may be the same as the base game, or it may be the name of another
+directory under the paths that should be searched for files before looking in the base game.
+This is the basis for addons.
+
+Clients automatically set the game directory after receiving a gamestate from a server,
+so only servers need to worry about +set fs_game.
+
+No other directories outside of the base game and current game will ever be referenced by
+filesystem functions.
+
+To save disk space and speed loading, directory trees can be collapsed into zip files.
+The files use a ".pk3" extension to prevent users from unzipping them accidentally, but
+otherwise the are simply normal uncompressed zip files. A game directory can have multiple
+zip files of the form "pak0.pk3", "pak1.pk3", etc. Zip files are searched in decending order
+from the highest number to the lowest, and will always take precedence over the filesystem.
+This allows a pk3 distributed as a patch to override all existing data.
+
+Because we will have updated executables freely available online, there is no point to
+trying to restrict demo / oem versions of the game with code changes. Demo / oem versions
+should be exactly the same executables as release versions, but with different data that
+automatically restricts where game media can come from to prevent add-ons from working.
+
+After the paths are initialized, quake will look for the product.txt file. If not
+found and verified, the game will run in restricted mode. In restricted mode, only
+files contained in demoq3/pak0.pk3 will be available for loading, and only if the zip header is
+verified to not have been modified. A single exception is made for q3config.cfg. Files
+can still be written out in restricted mode, so screenshots and demos are allowed.
+Restricted mode can be tested by setting "+set fs_restrict 1" on the command line, even
+if there is a valid product.txt under the basepath or cdpath.
+
+If not running in restricted mode, and a file is not found in any local filesystem,
+an attempt will be made to download it and save it under the base path.
+
+If the "fs_copyfiles" cvar is set to 1, then every time a file is sourced from the cd
+path, it will be copied over to the base path. This is a development aid to help build
+test releases and to copy working sets over slow network links.
+
+File search order: when FS_FOpenFileRead gets called it will go through the fs_searchpaths
+structure and stop on the first successful hit. fs_searchpaths is built with successive
+calls to FS_AddGameDirectory
+
+Additionaly, we search in several subdirectories:
+current game is the current mode
+base game is a variable to allow mods based on other mods
+(such as baseq3 + missionpack content combination in a mod for instance)
+BASEGAME is the hardcoded base game ("baseq3")
+
+e.g. the qpath "sound/newstuff/test.wav" would be searched for in the following places:
+
+home path + current game's zip files
+home path + current game's directory
+base path + current game's zip files
+base path + current game's directory
+cd path + current game's zip files
+cd path + current game's directory
+
+home path + base game's zip file
+home path + base game's directory
+base path + base game's zip file
+base path + base game's directory
+cd path + base game's zip file
+cd path + base game's directory
+
+home path + BASEGAME's zip file
+home path + BASEGAME's directory
+base path + BASEGAME's zip file
+base path + BASEGAME's directory
+cd path + BASEGAME's zip file
+cd path + BASEGAME's directory
+
+server download, to be written to home path + current game's directory
+
+
+The filesystem can be safely shutdown and reinitialized with different
+basedir / cddir / game combinations, but all other subsystems that rely on it
+(sound, video) must also be forced to restart.
+
+Because the same files are loaded by both the clip model (CM_) and renderer (TR_)
+subsystems, a simple single-file caching scheme is used. The CM_ subsystems will
+load the file with a request to cache. Only one file will be kept cached at a time,
+so any models that are going to be referenced by both subsystems should alternate
+between the CM_ load function and the ref load function.
+
+TODO: A qpath that starts with a leading slash will always refer to the base game, even if another
+game is currently active. This allows character models, skins, and sounds to be downloaded
+to a common directory no matter which game is active.
+
+How to prevent downloading zip files?
+Pass pk3 file names in systeminfo, and download before FS_Restart()?
+
+Aborting a download disconnects the client from the server.
+
+How to mark files as downloadable? Commercial add-ons won't be downloadable.
+
+Non-commercial downloads will want to download the entire zip file.
+the game would have to be reset to actually read the zip in
+
+Auto-update information
+
+Path separators
+
+Casing
+
+ separate server gamedir and client gamedir, so if the user starts
+ a local game after having connected to a network game, it won't stick
+ with the network game.
+
+ allow menu options for game selection?
+
+Read / write config to floppy option.
+
+Different version coexistance?
+
+When building a pak file, make sure a q3config.cfg isn't present in it,
+or configs will never get loaded from disk!
+
+ todo:
+
+ downloading (outside fs?)
+ game directory passing and restarting
+
+=============================================================================
+
+*/
+
+#define DEMOGAME "demota"
+
+// every time a new demo pk3 file is built, this checksum must be updated.
+// the easiest way to get it is to just run the game and see what it spits out
+#define DEMO_PAK_CHECKSUM 437558517u
+
+// if this is defined, the executable positively won't work with any paks other
+// than the demo pak, even if productid is present. This is only used for our
+// last demo release to prevent the mac and linux users from using the demo
+// executable with the production windows pak before the mac/linux products
+// hit the shelves a little later
+// NOW defined in build files
+//#define PRE_RELEASE_TADEMO
+
+#define MAX_ZPATH 256
+#define MAX_SEARCH_PATHS 4096
+#define MAX_FILEHASH_SIZE 1024
+
+typedef struct fileInPack_s {
+ char *name; // name of the file
+ unsigned long pos; // file info position in zip
+ struct fileInPack_s* next; // next file in the hash
+} fileInPack_t;
+
+typedef struct {
+ char pakFilename[MAX_OSPATH]; // c:\quake3\baseq3\pak0.pk3
+ char pakBasename[MAX_OSPATH]; // pak0
+ char pakGamename[MAX_OSPATH]; // baseq3
+ unzFile handle; // handle to zip file
+ int checksum; // regular checksum
+ int pure_checksum; // checksum for pure
+ int numfiles; // number of files in pk3
+ int referenced; // referenced file flags
+ int hashSize; // hash table size (power of 2)
+ fileInPack_t* *hashTable; // hash table
+ fileInPack_t* buildBuffer; // buffer with the filenames etc.
+} pack_t;
+
+typedef struct {
+ char path[MAX_OSPATH]; // c:\quake3
+ char gamedir[MAX_OSPATH]; // baseq3
+} directory_t;
+
+typedef struct searchpath_s {
+ struct searchpath_s *next;
+
+ pack_t *pack; // only one of pack / dir will be non NULL
+ directory_t *dir;
+} searchpath_t;
+
+static char fs_gamedir[MAX_OSPATH]; // this will be a single file name with no separators
+static cvar_t *fs_debug;
+static cvar_t *fs_homepath;
+static cvar_t *fs_basepath;
+static cvar_t *fs_basegame;
+static cvar_t *fs_cdpath;
+static cvar_t *fs_copyfiles;
+static cvar_t *fs_gamedirvar;
+static cvar_t *fs_restrict;
+static searchpath_t *fs_searchpaths;
+static int fs_readCount; // total bytes read
+static int fs_loadCount; // total files read
+static int fs_loadStack; // total files in memory
+static int fs_packFiles; // total number of files in packs
+
+static int fs_fakeChkSum;
+static int fs_checksumFeed;
+
+typedef union qfile_gus {
+ FILE* o;
+ unzFile z;
+} qfile_gut;
+
+typedef struct qfile_us {
+ qfile_gut file;
+ qboolean unique;
+} qfile_ut;
+
+typedef struct {
+ qfile_ut handleFiles;
+ qboolean handleSync;
+ int baseOffset;
+ int fileSize;
+ int zipFilePos;
+ qboolean zipFile;
+ qboolean streamed;
+ char name[MAX_ZPATH];
+} fileHandleData_t;
+
+static fileHandleData_t fsh[MAX_FILE_HANDLES];
+
+// TTimo - https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540
+// wether we did a reorder on the current search path when joining the server
+static qboolean fs_reordered;
+
+// never load anything from pk3 files that are not present at the server when pure
+static int fs_numServerPaks;
+static int fs_serverPaks[MAX_SEARCH_PATHS]; // checksums
+static char *fs_serverPakNames[MAX_SEARCH_PATHS]; // pk3 names
+
+// only used for autodownload, to make sure the client has at least
+// all the pk3 files that are referenced at the server side
+static int fs_numServerReferencedPaks;
+static int fs_serverReferencedPaks[MAX_SEARCH_PATHS]; // checksums
+static char *fs_serverReferencedPakNames[MAX_SEARCH_PATHS]; // pk3 names
+
+// last valid game folder used
+char lastValidBase[MAX_OSPATH];
+char lastValidGame[MAX_OSPATH];
+
+// productId: This file is copyright 1999 Id Software, and may not be duplicated except during a licensed installation of the full commercial version of Quake 3:Arena
+static byte fs_scrambledProductId[152] = {
+220, 129, 255, 108, 244, 163, 171, 55, 133, 65, 199, 36, 140, 222, 53, 99, 65, 171, 175, 232, 236, 193, 210, 250, 169, 104, 231, 231, 21, 201, 170, 208, 135, 175, 130, 136, 85, 215, 71, 23, 96, 32, 96, 83, 44, 240, 219, 138, 184, 215, 73, 27, 196, 247, 55, 139, 148, 68, 78, 203, 213, 238, 139, 23, 45, 205, 118, 186, 236, 230, 231, 107, 212, 1, 10, 98, 30, 20, 116, 180, 216, 248, 166, 35, 45, 22, 215, 229, 35, 116, 250, 167, 117, 3, 57, 55, 201, 229, 218, 222, 128, 12, 141, 149, 32, 110, 168, 215, 184, 53, 31, 147, 62, 12, 138, 67, 132, 54, 125, 6, 221, 148, 140, 4, 21, 44, 198, 3, 126, 12, 100, 236, 61, 42, 44, 251, 15, 135, 14, 134, 89, 92, 177, 246, 152, 106, 124, 78, 118, 80, 28, 42
+};
+
+#ifdef FS_MISSING
+FILE* missingFiles = NULL;
+#endif
+
+/*
+==============
+FS_Initialized
+==============
+*/
+
+qboolean FS_Initialized() {
+ return (fs_searchpaths != NULL);
+}
+
+/*
+=================
+FS_PakIsPure
+=================
+*/
+qboolean FS_PakIsPure( pack_t *pack ) {
+ int i;
+
+ if ( fs_numServerPaks ) {
+ for ( i = 0 ; i < fs_numServerPaks ; i++ ) {
+ // FIXME: also use hashed file names
+ // NOTE TTimo: a pk3 with same checksum but different name would be validated too
+ // I don't see this as allowing for any exploit, it would only happen if the client does manips of it's file names 'not a bug'
+ if ( pack->checksum == fs_serverPaks[i] ) {
+ return qtrue; // on the aproved list
+ }
+ }
+ return qfalse; // not on the pure server pak list
+ }
+ return qtrue;
+}
+
+
+/*
+=================
+FS_LoadStack
+return load stack
+=================
+*/
+int FS_LoadStack()
+{
+ return fs_loadStack;
+}
+
+/*
+================
+return a hash value for the filename
+================
+*/
+static long FS_HashFileName( const char *fname, int hashSize ) {
+ int i;
+ long hash;
+ char letter;
+
+ hash = 0;
+ i = 0;
+ while (fname[i] != '\0') {
+ letter = tolower(fname[i]);
+ if (letter =='.') break; // don't include extension
+ if (letter =='\\') letter = '/'; // damn path names
+ if (letter == PATH_SEP) letter = '/'; // damn path names
+ hash+=(long)(letter)*(i+119);
+ i++;
+ }
+ hash = (hash ^ (hash >> 10) ^ (hash >> 20));
+ hash &= (hashSize-1);
+ return hash;
+}
+
+static fileHandle_t FS_HandleForFile(void) {
+ int i;
+
+ for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
+ if ( fsh[i].handleFiles.file.o == NULL ) {
+ return i;
+ }
+ }
+ Com_Error( ERR_DROP, "FS_HandleForFile: none free" );
+ return 0;
+}
+
+static FILE *FS_FileForHandle( fileHandle_t f ) {
+ if ( f < 0 || f > MAX_FILE_HANDLES ) {
+ Com_Error( ERR_DROP, "FS_FileForHandle: out of reange" );
+ }
+ if (fsh[f].zipFile == qtrue) {
+ Com_Error( ERR_DROP, "FS_FileForHandle: can't get FILE on zip file" );
+ }
+ if ( ! fsh[f].handleFiles.file.o ) {
+ Com_Error( ERR_DROP, "FS_FileForHandle: NULL" );
+ }
+
+ return fsh[f].handleFiles.file.o;
+}
+
+void FS_ForceFlush( fileHandle_t f ) {
+ FILE *file;
+
+ file = FS_FileForHandle(f);
+ setvbuf( file, NULL, _IONBF, 0 );
+}
+
+/*
+================
+FS_filelength
+
+If this is called on a non-unique FILE (from a pak file),
+it will return the size of the pak file, not the expected
+size of the file.
+================
+*/
+int FS_filelength( fileHandle_t f ) {
+ int pos;
+ int end;
+ FILE* h;
+
+ h = FS_FileForHandle(f);
+ pos = ftell (h);
+ fseek (h, 0, SEEK_END);
+ end = ftell (h);
+ fseek (h, pos, SEEK_SET);
+
+ return end;
+}
+
+/*
+====================
+FS_ReplaceSeparators
+
+Fix things up differently for win/unix/mac
+====================
+*/
+static void FS_ReplaceSeparators( char *path ) {
+ char *s;
+
+ for ( s = path ; *s ; s++ ) {
+ if ( *s == '/' || *s == '\\' ) {
+ *s = PATH_SEP;
+ }
+ }
+}
+
+/*
+===================
+FS_BuildOSPath
+
+Qpath may have either forward or backwards slashes
+===================
+*/
+char *FS_BuildOSPath( const char *base, const char *game, const char *qpath ) {
+ char temp[MAX_OSPATH];
+ static char ospath[2][MAX_OSPATH];
+ static int toggle;
+
+ toggle ^= 1; // flip-flop to allow two returns without clash
+
+ if( !game || !game[0] ) {
+ game = fs_gamedir;
+ }
+
+ Com_sprintf( temp, sizeof(temp), "/%s/%s", game, qpath );
+ FS_ReplaceSeparators( temp );
+ Com_sprintf( ospath[toggle], sizeof( ospath[0] ), "%s%s", base, temp );
+
+ return ospath[toggle];
+}
+
+
+/*
+============
+FS_CreatePath
+
+Creates any directories needed to store the given filename
+============
+*/
+static qboolean FS_CreatePath (char *OSPath) {
+ char *ofs;
+
+ // make absolutely sure that it can't back up the path
+ // FIXME: is c: allowed???
+ if ( strstr( OSPath, ".." ) || strstr( OSPath, "::" ) ) {
+ Com_Printf( "WARNING: refusing to create relative path \"%s\"\n", OSPath );
+ return qtrue;
+ }
+
+ for (ofs = OSPath+1 ; *ofs ; ofs++) {
+ if (*ofs == PATH_SEP) {
+ // create the directory
+ *ofs = 0;
+ Sys_Mkdir (OSPath);
+ *ofs = PATH_SEP;
+ }
+ }
+ return qfalse;
+}
+
+/*
+=================
+FS_CopyFile
+
+Copy a fully specified file from one place to another
+=================
+*/
+static void FS_CopyFile( char *fromOSPath, char *toOSPath ) {
+ FILE *f;
+ int len;
+ byte *buf;
+
+ Com_Printf( "copy %s to %s\n", fromOSPath, toOSPath );
+
+ if (strstr(fromOSPath, "journal.dat") || strstr(fromOSPath, "journaldata.dat")) {
+ Com_Printf( "Ignoring journal files\n");
+ return;
+ }
+
+ f = fopen( fromOSPath, "rb" );
+ if ( !f ) {
+ return;
+ }
+ fseek (f, 0, SEEK_END);
+ len = ftell (f);
+ fseek (f, 0, SEEK_SET);
+
+ // we are using direct malloc instead of Z_Malloc here, so it
+ // probably won't work on a mac... Its only for developers anyway...
+ buf = malloc( len );
+ if (fread( buf, 1, len, f ) != len)
+ Com_Error( ERR_FATAL, "Short read in FS_Copyfiles()\n" );
+ fclose( f );
+
+ if( FS_CreatePath( toOSPath ) ) {
+ return;
+ }
+
+ f = fopen( toOSPath, "wb" );
+ if ( !f ) {
+ return;
+ }
+ if (fwrite( buf, 1, len, f ) != len)
+ Com_Error( ERR_FATAL, "Short write in FS_Copyfiles()\n" );
+ fclose( f );
+ free( buf );
+}
+
+/*
+===========
+FS_Remove
+
+===========
+*/
+static void FS_Remove( const char *osPath ) {
+ remove( osPath );
+}
+
+/*
+================
+FS_FileExists
+
+Tests if the file exists in the current gamedir, this DOES NOT
+search the paths. This is to determine if opening a file to write
+(which always goes into the current gamedir) will cause any overwrites.
+NOTE TTimo: this goes with FS_FOpenFileWrite for opening the file afterwards
+================
+*/
+qboolean FS_FileExists( const char *file )
+{
+ FILE *f;
+ char *testpath;
+
+ testpath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, file );
+
+ f = fopen( testpath, "rb" );
+ if (f) {
+ fclose( f );
+ return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+================
+FS_SV_FileExists
+
+Tests if the file exists
+================
+*/
+qboolean FS_SV_FileExists( const char *file )
+{
+ FILE *f;
+ char *testpath;
+
+ testpath = FS_BuildOSPath( fs_homepath->string, file, "");
+ testpath[strlen(testpath)-1] = '\0';
+
+ f = fopen( testpath, "rb" );
+ if (f) {
+ fclose( f );
+ return qtrue;
+ }
+ return qfalse;
+}
+
+
+/*
+===========
+FS_SV_FOpenFileWrite
+
+===========
+*/
+fileHandle_t FS_SV_FOpenFileWrite( const char *filename ) {
+ char *ospath;
+ fileHandle_t f;
+
+ if ( !fs_searchpaths ) {
+ Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
+ }
+
+ ospath = FS_BuildOSPath( fs_homepath->string, filename, "" );
+ ospath[strlen(ospath)-1] = '\0';
+
+ f = FS_HandleForFile();
+ fsh[f].zipFile = qfalse;
+
+ if ( fs_debug->integer ) {
+ Com_Printf( "FS_SV_FOpenFileWrite: %s\n", ospath );
+ }
+
+ if( FS_CreatePath( ospath ) ) {
+ return 0;
+ }
+
+ Com_DPrintf( "writing to: %s\n", ospath );
+ fsh[f].handleFiles.file.o = fopen( ospath, "wb" );
+
+ Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
+
+ fsh[f].handleSync = qfalse;
+ if (!fsh[f].handleFiles.file.o) {
+ f = 0;
+ }
+ return f;
+}
+
+/*
+===========
+FS_SV_FOpenFileRead
+search for a file somewhere below the home path, base path or cd path
+we search in that order, matching FS_SV_FOpenFileRead order
+===========
+*/
+int FS_SV_FOpenFileRead( const char *filename, fileHandle_t *fp ) {
+ char *ospath;
+ fileHandle_t f = 0;
+
+ if ( !fs_searchpaths ) {
+ Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
+ }
+
+ f = FS_HandleForFile();
+ fsh[f].zipFile = qfalse;
+
+ Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
+
+ // don't let sound stutter
+ S_ClearSoundBuffer();
+
+ // search homepath
+ ospath = FS_BuildOSPath( fs_homepath->string, filename, "" );
+ // remove trailing slash
+ ospath[strlen(ospath)-1] = '\0';
+
+ if ( fs_debug->integer ) {
+ Com_Printf( "FS_SV_FOpenFileRead (fs_homepath): %s\n", ospath );
+ }
+
+ fsh[f].handleFiles.file.o = fopen( ospath, "rb" );
+ fsh[f].handleSync = qfalse;
+ if (!fsh[f].handleFiles.file.o)
+ {
+ // NOTE TTimo on non *nix systems, fs_homepath == fs_basepath, might want to avoid
+ if (Q_stricmp(fs_homepath->string,fs_basepath->string))
+ {
+ // search basepath
+ ospath = FS_BuildOSPath( fs_basepath->string, filename, "" );
+ ospath[strlen(ospath)-1] = '\0';
+
+ if ( fs_debug->integer )
+ {
+ Com_Printf( "FS_SV_FOpenFileRead (fs_basepath): %s\n", ospath );
+ }
+
+ fsh[f].handleFiles.file.o = fopen( ospath, "rb" );
+ fsh[f].handleSync = qfalse;
+
+ if ( !fsh[f].handleFiles.file.o )
+ {
+ f = 0;
+ }
+ }
+ }
+
+ if (!fsh[f].handleFiles.file.o) {
+ // search cd path
+ ospath = FS_BuildOSPath( fs_cdpath->string, filename, "" );
+ ospath[strlen(ospath)-1] = '\0';
+
+ if (fs_debug->integer)
+ {
+ Com_Printf( "FS_SV_FOpenFileRead (fs_cdpath) : %s\n", ospath );
+ }
+
+ fsh[f].handleFiles.file.o = fopen( ospath, "rb" );
+ fsh[f].handleSync = qfalse;
+
+ if( !fsh[f].handleFiles.file.o ) {
+ f = 0;
+ }
+ }
+
+ *fp = f;
+ if (f) {
+ return FS_filelength(f);
+ }
+ return 0;
+}
+
+
+/*
+===========
+FS_SV_Rename
+
+===========
+*/
+void FS_SV_Rename( const char *from, const char *to ) {
+ char *from_ospath, *to_ospath;
+
+ if ( !fs_searchpaths ) {
+ Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
+ }
+
+ // don't let sound stutter
+ S_ClearSoundBuffer();
+
+ from_ospath = FS_BuildOSPath( fs_homepath->string, from, "" );
+ to_ospath = FS_BuildOSPath( fs_homepath->string, to, "" );
+ from_ospath[strlen(from_ospath)-1] = '\0';
+ to_ospath[strlen(to_ospath)-1] = '\0';
+
+ if ( fs_debug->integer ) {
+ Com_Printf( "FS_SV_Rename: %s --> %s\n", from_ospath, to_ospath );
+ }
+
+ if (rename( from_ospath, to_ospath )) {
+ // Failed, try copying it and deleting the original
+ FS_CopyFile ( from_ospath, to_ospath );
+ FS_Remove ( from_ospath );
+ }
+}
+
+
+
+/*
+===========
+FS_Rename
+
+===========
+*/
+void FS_Rename( const char *from, const char *to ) {
+ char *from_ospath, *to_ospath;
+
+ if ( !fs_searchpaths ) {
+ Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
+ }
+
+ // don't let sound stutter
+ S_ClearSoundBuffer();
+
+ from_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, from );
+ to_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, to );
+
+ if ( fs_debug->integer ) {
+ Com_Printf( "FS_Rename: %s --> %s\n", from_ospath, to_ospath );
+ }
+
+ if (rename( from_ospath, to_ospath )) {
+ // Failed, try copying it and deleting the original
+ FS_CopyFile ( from_ospath, to_ospath );
+ FS_Remove ( from_ospath );
+ }
+}
+
+/*
+==============
+FS_FCloseFile
+
+If the FILE pointer is an open pak file, leave it open.
+
+For some reason, other dll's can't just cal fclose()
+on files returned by FS_FOpenFile...
+==============
+*/
+void FS_FCloseFile( fileHandle_t f ) {
+ if ( !fs_searchpaths ) {
+ Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
+ }
+
+ if (fsh[f].streamed) {
+ Sys_EndStreamedFile(f);
+ }
+ if (fsh[f].zipFile == qtrue) {
+ unzCloseCurrentFile( fsh[f].handleFiles.file.z );
+ if ( fsh[f].handleFiles.unique ) {
+ unzClose( fsh[f].handleFiles.file.z );
+ }
+ Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) );
+ return;
+ }
+
+ // we didn't find it as a pak, so close it as a unique file
+ if (fsh[f].handleFiles.file.o) {
+ fclose (fsh[f].handleFiles.file.o);
+ }
+ Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) );
+}
+
+/*
+===========
+FS_FOpenFileWrite
+
+===========
+*/
+fileHandle_t FS_FOpenFileWrite( const char *filename ) {
+ char *ospath;
+ fileHandle_t f;
+
+ if ( !fs_searchpaths ) {
+ Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
+ }
+
+ f = FS_HandleForFile();
+ fsh[f].zipFile = qfalse;
+
+ ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
+
+ if ( fs_debug->integer ) {
+ Com_Printf( "FS_FOpenFileWrite: %s\n", ospath );
+ }
+
+ if( FS_CreatePath( ospath ) ) {
+ return 0;
+ }
+
+ // enabling the following line causes a recursive function call loop
+ // when running with +set logfile 1 +set developer 1
+ //Com_DPrintf( "writing to: %s\n", ospath );
+ fsh[f].handleFiles.file.o = fopen( ospath, "wb" );
+
+ Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
+
+ fsh[f].handleSync = qfalse;
+ if (!fsh[f].handleFiles.file.o) {
+ f = 0;
+ }
+ return f;
+}
+
+/*
+===========
+FS_FOpenFileAppend
+
+===========
+*/
+fileHandle_t FS_FOpenFileAppend( const char *filename ) {
+ char *ospath;
+ fileHandle_t f;
+
+ if ( !fs_searchpaths ) {
+ Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
+ }
+
+ f = FS_HandleForFile();
+ fsh[f].zipFile = qfalse;
+
+ Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
+
+ // don't let sound stutter
+ S_ClearSoundBuffer();
+
+ ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename );
+
+ if ( fs_debug->integer ) {
+ Com_Printf( "FS_FOpenFileAppend: %s\n", ospath );
+ }
+
+ if( FS_CreatePath( ospath ) ) {
+ return 0;
+ }
+
+ fsh[f].handleFiles.file.o = fopen( ospath, "ab" );
+ fsh[f].handleSync = qfalse;
+ if (!fsh[f].handleFiles.file.o) {
+ f = 0;
+ }
+ return f;
+}
+
+/*
+===========
+FS_FilenameCompare
+
+Ignore case and seprator char distinctions
+===========
+*/
+qboolean FS_FilenameCompare( const char *s1, const char *s2 ) {
+ int c1, c2;
+
+ do {
+ c1 = *s1++;
+ c2 = *s2++;
+
+ if (c1 >= 'a' && c1 <= 'z') {
+ c1 -= ('a' - 'A');
+ }
+ if (c2 >= 'a' && c2 <= 'z') {
+ c2 -= ('a' - 'A');
+ }
+
+ if ( c1 == '\\' || c1 == ':' ) {
+ c1 = '/';
+ }
+ if ( c2 == '\\' || c2 == ':' ) {
+ c2 = '/';
+ }
+
+ if (c1 != c2) {
+ return -1; // strings not equal
+ }
+ } while (c1);
+
+ return 0; // strings are equal
+}
+
+/*
+===========
+FS_ShiftedStrStr
+===========
+*/
+char *FS_ShiftedStrStr(const char *string, const char *substring, int shift) {
+ char buf[MAX_STRING_TOKENS];
+ int i;
+
+ for (i = 0; substring[i]; i++) {
+ buf[i] = substring[i] + shift;
+ }
+ buf[i] = '\0';
+ return strstr(string, buf);
+}
+
+/*
+===========
+FS_FOpenFileRead
+
+Finds the file in the search path.
+Returns filesize and an open FILE pointer.
+Used for streaming data out of either a
+separate file or a ZIP file.
+===========
+*/
+extern qboolean com_fullyInitialized;
+
+int FS_FOpenFileRead( const char *filename, fileHandle_t *file, qboolean uniqueFILE ) {
+ searchpath_t *search;
+ char *netpath;
+ pack_t *pak;
+ fileInPack_t *pakFile;
+ directory_t *dir;
+ long hash;
+ unz_s *zfi;
+ FILE *temp;
+ int l;
+ char demoExt[16];
+
+ hash = 0;
+
+ if ( !fs_searchpaths ) {
+ Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
+ }
+
+ if ( file == NULL ) {
+ // just wants to see if file is there
+ for ( search = fs_searchpaths ; search ; search = search->next ) {
+ //
+ if ( search->pack ) {
+ hash = FS_HashFileName(filename, search->pack->hashSize);
+ }
+ // is the element a pak file?
+ if ( search->pack && search->pack->hashTable[hash] ) {
+ // look through all the pak file elements
+ pak = search->pack;
+ pakFile = pak->hashTable[hash];
+ do {
+ // case and separator insensitive comparisons
+ if ( !FS_FilenameCompare( pakFile->name, filename ) ) {
+ // found it!
+ return qtrue;
+ }
+ pakFile = pakFile->next;
+ } while(pakFile != NULL);
+ } else if ( search->dir ) {
+ dir = search->dir;
+
+ netpath = FS_BuildOSPath( dir->path, dir->gamedir, filename );
+ temp = fopen (netpath, "rb");
+ if ( !temp ) {
+ continue;
+ }
+ fclose(temp);
+ return qtrue;
+ }
+ }
+ return qfalse;
+ }
+
+ if ( !filename ) {
+ Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed\n" );
+ }
+
+ Com_sprintf (demoExt, sizeof(demoExt), ".dm_%d",PROTOCOL_VERSION );
+ // qpaths are not supposed to have a leading slash
+ if ( filename[0] == '/' || filename[0] == '\\' ) {
+ filename++;
+ }
+
+ // make absolutely sure that it can't back up the path.
+ // The searchpaths do guarantee that something will always
+ // be prepended, so we don't need to worry about "c:" or "//limbo"
+ if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) {
+ *file = 0;
+ return -1;
+ }
+
+ // make sure the q3key file is only readable by the quake3.exe at initialization
+ // any other time the key should only be accessed in memory using the provided functions
+ if( com_fullyInitialized && strstr( filename, "q3key" ) ) {
+ *file = 0;
+ return -1;
+ }
+
+ //
+ // search through the path, one element at a time
+ //
+
+ *file = FS_HandleForFile();
+ fsh[*file].handleFiles.unique = uniqueFILE;
+
+ for ( search = fs_searchpaths ; search ; search = search->next ) {
+ //
+ if ( search->pack ) {
+ hash = FS_HashFileName(filename, search->pack->hashSize);
+ }
+ // is the element a pak file?
+ if ( search->pack && search->pack->hashTable[hash] ) {
+ // disregard if it doesn't match one of the allowed pure pak files
+ if ( !FS_PakIsPure(search->pack) ) {
+ continue;
+ }
+
+ // look through all the pak file elements
+ pak = search->pack;
+ pakFile = pak->hashTable[hash];
+ do {
+ // case and separator insensitive comparisons
+ if ( !FS_FilenameCompare( pakFile->name, filename ) ) {
+ // found it!
+
+ // mark the pak as having been referenced and mark specifics on cgame and ui
+ // shaders, txt, arena files by themselves do not count as a reference as
+ // these are loaded from all pk3s
+ // from every pk3 file..
+ l = strlen( filename );
+ if ( !(pak->referenced & FS_GENERAL_REF)) {
+ if ( Q_stricmp(filename + l - 7, ".shader") != 0 &&
+ Q_stricmp(filename + l - 4, ".txt") != 0 &&
+ Q_stricmp(filename + l - 4, ".cfg") != 0 &&
+ Q_stricmp(filename + l - 7, ".config") != 0 &&
+ strstr(filename, "levelshots") == NULL &&
+ Q_stricmp(filename + l - 4, ".bot") != 0 &&
+ Q_stricmp(filename + l - 6, ".arena") != 0 &&
+ Q_stricmp(filename + l - 5, ".menu") != 0) {
+ pak->referenced |= FS_GENERAL_REF;
+ }
+ }
+
+ // qagame.qvm - 13
+ // dTZT`X!di`
+ if (!(pak->referenced & FS_QAGAME_REF) && FS_ShiftedStrStr(filename, "dTZT`X!di`", 13)) {
+ pak->referenced |= FS_QAGAME_REF;
+ }
+ // cgame.qvm - 7
+ // \`Zf^'jof
+ if (!(pak->referenced & FS_CGAME_REF) && FS_ShiftedStrStr(filename , "\\`Zf^'jof", 7)) {
+ pak->referenced |= FS_CGAME_REF;
+ }
+ // ui.qvm - 5
+ // pd)lqh
+ if (!(pak->referenced & FS_UI_REF) && FS_ShiftedStrStr(filename , "pd)lqh", 5)) {
+ pak->referenced |= FS_UI_REF;
+ }
+
+ if ( uniqueFILE ) {
+ // open a new file on the pakfile
+ fsh[*file].handleFiles.file.z = unzReOpen (pak->pakFilename, pak->handle);
+ if (fsh[*file].handleFiles.file.z == NULL) {
+ Com_Error (ERR_FATAL, "Couldn't reopen %s", pak->pakFilename);
+ }
+ } else {
+ fsh[*file].handleFiles.file.z = pak->handle;
+ }
+ Q_strncpyz( fsh[*file].name, filename, sizeof( fsh[*file].name ) );
+ fsh[*file].zipFile = qtrue;
+ zfi = (unz_s *)fsh[*file].handleFiles.file.z;
+ // in case the file was new
+ temp = zfi->file;
+ // set the file position in the zip file (also sets the current file info)
+ unzSetCurrentFileInfoPosition(pak->handle, pakFile->pos);
+ // copy the file info into the unzip structure
+ Com_Memcpy( zfi, pak->handle, sizeof(unz_s) );
+ // we copy this back into the structure
+ zfi->file = temp;
+ // open the file in the zip
+ unzOpenCurrentFile( fsh[*file].handleFiles.file.z );
+ fsh[*file].zipFilePos = pakFile->pos;
+
+ if ( fs_debug->integer ) {
+ Com_Printf( "FS_FOpenFileRead: %s (found in '%s')\n",
+ filename, pak->pakFilename );
+ }
+ return zfi->cur_file_info.uncompressed_size;
+ }
+ pakFile = pakFile->next;
+ } while(pakFile != NULL);
+ } else if ( search->dir ) {
+ // check a file in the directory tree
+
+ // if we are running restricted, the only files we
+ // will allow to come from the directory are .cfg files
+ l = strlen( filename );
+ // FIXME TTimo I'm not sure about the fs_numServerPaks test
+ // if you are using FS_ReadFile to find out if a file exists,
+ // this test can make the search fail although the file is in the directory
+ // I had the problem on https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=8
+ // turned out I used FS_FileExists instead
+ if ( fs_restrict->integer || fs_numServerPaks ) {
+
+ if ( Q_stricmp( filename + l - 4, ".cfg" ) // for config files
+ && Q_stricmp( filename + l - 5, ".menu" ) // menu files
+ && Q_stricmp( filename + l - 5, ".game" ) // menu files
+ && Q_stricmp( filename + l - strlen(demoExt), demoExt ) // menu files
+ && Q_stricmp( filename + l - 4, ".dat" ) ) { // for journal files
+ continue;
+ }
+ }
+
+ dir = search->dir;
+
+ netpath = FS_BuildOSPath( dir->path, dir->gamedir, filename );
+ fsh[*file].handleFiles.file.o = fopen (netpath, "rb");
+ if ( !fsh[*file].handleFiles.file.o ) {
+ continue;
+ }
+
+ if ( Q_stricmp( filename + l - 4, ".cfg" ) // for config files
+ && Q_stricmp( filename + l - 5, ".menu" ) // menu files
+ && Q_stricmp( filename + l - 5, ".game" ) // menu files
+ && Q_stricmp( filename + l - strlen(demoExt), demoExt ) // menu files
+ && Q_stricmp( filename + l - 4, ".dat" ) ) { // for journal files
+ fs_fakeChkSum = random();
+ }
+
+ Q_strncpyz( fsh[*file].name, filename, sizeof( fsh[*file].name ) );
+ fsh[*file].zipFile = qfalse;
+ if ( fs_debug->integer ) {
+ Com_Printf( "FS_FOpenFileRead: %s (found in '%s/%s')\n", filename,
+ dir->path, dir->gamedir );
+ }
+
+ // if we are getting it from the cdpath, optionally copy it
+ // to the basepath
+ if ( fs_copyfiles->integer && !Q_stricmp( dir->path, fs_cdpath->string ) ) {
+ char *copypath;
+
+ copypath = FS_BuildOSPath( fs_basepath->string, dir->gamedir, filename );
+ FS_CopyFile( netpath, copypath );
+ }
+
+ return FS_filelength (*file);
+ }
+ }
+
+ Com_DPrintf ("Can't find %s\n", filename);
+#ifdef FS_MISSING
+ if (missingFiles) {
+ fprintf(missingFiles, "%s\n", filename);
+ }
+#endif
+ *file = 0;
+ return -1;
+}
+
+
+/*
+=================
+FS_Read
+
+Properly handles partial reads
+=================
+*/
+int FS_Read2( void *buffer, int len, fileHandle_t f ) {
+ if ( !fs_searchpaths ) {
+ Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
+ }
+
+ if ( !f ) {
+ return 0;
+ }
+ if (fsh[f].streamed) {
+ int r;
+ fsh[f].streamed = qfalse;
+ r = Sys_StreamedRead( buffer, len, 1, f);
+ fsh[f].streamed = qtrue;
+ return r;
+ } else {
+ return FS_Read( buffer, len, f);
+ }
+}
+
+int FS_Read( void *buffer, int len, fileHandle_t f ) {
+ int block, remaining;
+ int read;
+ byte *buf;
+ int tries;
+
+ if ( !fs_searchpaths ) {
+ Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
+ }
+
+ if ( !f ) {
+ return 0;
+ }
+
+ buf = (byte *)buffer;
+ fs_readCount += len;
+
+ if (fsh[f].zipFile == qfalse) {
+ remaining = len;
+ tries = 0;
+ while (remaining) {
+ block = remaining;
+ read = fread (buf, 1, block, fsh[f].handleFiles.file.o);
+ if (read == 0) {
+ // we might have been trying to read from a CD, which
+ // sometimes returns a 0 read on windows
+ if (!tries) {
+ tries = 1;
+ } else {
+ return len-remaining; //Com_Error (ERR_FATAL, "FS_Read: 0 bytes read");
+ }
+ }
+
+ if (read == -1) {
+ Com_Error (ERR_FATAL, "FS_Read: -1 bytes read");
+ }
+
+ remaining -= read;
+ buf += read;
+ }
+ return len;
+ } else {
+ return unzReadCurrentFile(fsh[f].handleFiles.file.z, buffer, len);
+ }
+}
+
+/*
+=================
+FS_Write
+
+Properly handles partial writes
+=================
+*/
+int FS_Write( const void *buffer, int len, fileHandle_t h ) {
+ int block, remaining;
+ int written;
+ byte *buf;
+ int tries;
+ FILE *f;
+
+ if ( !fs_searchpaths ) {
+ Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
+ }
+
+ if ( !h ) {
+ return 0;
+ }
+
+ f = FS_FileForHandle(h);
+ buf = (byte *)buffer;
+
+ remaining = len;
+ tries = 0;
+ while (remaining) {
+ block = remaining;
+ written = fwrite (buf, 1, block, f);
+ if (written == 0) {
+ if (!tries) {
+ tries = 1;
+ } else {
+ Com_Printf( "FS_Write: 0 bytes written\n" );
+ return 0;
+ }
+ }
+
+ if (written == -1) {
+ Com_Printf( "FS_Write: -1 bytes written\n" );
+ return 0;
+ }
+
+ remaining -= written;
+ buf += written;
+ }
+ if ( fsh[h].handleSync ) {
+ fflush( f );
+ }
+ return len;
+}
+
+void QDECL FS_Printf( fileHandle_t h, const char *fmt, ... ) {
+ va_list argptr;
+ char msg[MAXPRINTMSG];
+
+ va_start (argptr,fmt);
+ Q_vsnprintf (msg, sizeof(msg), fmt, argptr);
+ va_end (argptr);
+
+ FS_Write(msg, strlen(msg), h);
+}
+
+/*
+=================
+FS_Seek
+
+=================
+*/
+int FS_Seek( fileHandle_t f, long offset, int origin ) {
+ int _origin;
+ char foo[65536];
+
+ if ( !fs_searchpaths ) {
+ Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
+ return -1;
+ }
+
+ if (fsh[f].streamed) {
+ fsh[f].streamed = qfalse;
+ Sys_StreamSeek( f, offset, origin );
+ fsh[f].streamed = qtrue;
+ }
+
+ if (fsh[f].zipFile == qtrue) {
+ if (offset == 0 && origin == FS_SEEK_SET) {
+ // set the file position in the zip file (also sets the current file info)
+ unzSetCurrentFileInfoPosition(fsh[f].handleFiles.file.z, fsh[f].zipFilePos);
+ return unzOpenCurrentFile(fsh[f].handleFiles.file.z);
+ } else if (offset<65536) {
+ // set the file position in the zip file (also sets the current file info)
+ unzSetCurrentFileInfoPosition(fsh[f].handleFiles.file.z, fsh[f].zipFilePos);
+ unzOpenCurrentFile(fsh[f].handleFiles.file.z);
+ return FS_Read(foo, offset, f);
+ } else {
+ Com_Error( ERR_FATAL, "ZIP FILE FSEEK NOT YET IMPLEMENTED\n" );
+ return -1;
+ }
+ } else {
+ FILE *file;
+ file = FS_FileForHandle(f);
+ switch( origin ) {
+ case FS_SEEK_CUR:
+ _origin = SEEK_CUR;
+ break;
+ case FS_SEEK_END:
+ _origin = SEEK_END;
+ break;
+ case FS_SEEK_SET:
+ _origin = SEEK_SET;
+ break;
+ default:
+ _origin = SEEK_CUR;
+ Com_Error( ERR_FATAL, "Bad origin in FS_Seek\n" );
+ break;
+ }
+
+ return fseek( file, offset, _origin );
+ }
+}
+
+
+/*
+======================================================================================
+
+CONVENIENCE FUNCTIONS FOR ENTIRE FILES
+
+======================================================================================
+*/
+
+int FS_FileIsInPAK(const char *filename, int *pChecksum ) {
+ searchpath_t *search;
+ pack_t *pak;
+ fileInPack_t *pakFile;
+ long hash = 0;
+
+ if ( !fs_searchpaths ) {
+ Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
+ }
+
+ if ( !filename ) {
+ Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed\n" );
+ }
+
+ // qpaths are not supposed to have a leading slash
+ if ( filename[0] == '/' || filename[0] == '\\' ) {
+ filename++;
+ }
+
+ // make absolutely sure that it can't back up the path.
+ // The searchpaths do guarantee that something will always
+ // be prepended, so we don't need to worry about "c:" or "//limbo"
+ if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) {
+ return -1;
+ }
+
+ //
+ // search through the path, one element at a time
+ //
+
+ for ( search = fs_searchpaths ; search ; search = search->next ) {
+ //
+ if (search->pack) {
+ hash = FS_HashFileName(filename, search->pack->hashSize);
+ }
+ // is the element a pak file?
+ if ( search->pack && search->pack->hashTable[hash] ) {
+ // disregard if it doesn't match one of the allowed pure pak files
+ if ( !FS_PakIsPure(search->pack) ) {
+ continue;
+ }
+
+ // look through all the pak file elements
+ pak = search->pack;
+ pakFile = pak->hashTable[hash];
+ do {
+ // case and separator insensitive comparisons
+ if ( !FS_FilenameCompare( pakFile->name, filename ) ) {
+ if (pChecksum) {
+ *pChecksum = pak->pure_checksum;
+ }
+ return 1;
+ }
+ pakFile = pakFile->next;
+ } while(pakFile != NULL);
+ }
+ }
+ return -1;
+}
+
+/*
+============
+FS_ReadFile
+
+Filename are relative to the quake search path
+a null buffer will just return the file length without loading
+============
+*/
+int FS_ReadFile( const char *qpath, void **buffer ) {
+ fileHandle_t h;
+ byte* buf;
+ qboolean isConfig;
+ int len;
+
+ if ( !fs_searchpaths ) {
+ Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
+ }
+
+ if ( !qpath || !qpath[0] ) {
+ Com_Error( ERR_FATAL, "FS_ReadFile with empty name\n" );
+ }
+
+ buf = NULL; // quiet compiler warning
+
+ // if this is a .cfg file and we are playing back a journal, read
+ // it from the journal file
+ if ( strstr( qpath, ".cfg" ) ) {
+ isConfig = qtrue;
+ if ( com_journal && com_journal->integer == 2 ) {
+ int r;
+
+ Com_DPrintf( "Loading %s from journal file.\n", qpath );
+ r = FS_Read( &len, sizeof( len ), com_journalDataFile );
+ if ( r != sizeof( len ) ) {
+ if (buffer != NULL) *buffer = NULL;
+ return -1;
+ }
+ // if the file didn't exist when the journal was created
+ if (!len) {
+ if (buffer == NULL) {
+ return 1; // hack for old journal files
+ }
+ *buffer = NULL;
+ return -1;
+ }
+ if (buffer == NULL) {
+ return len;
+ }
+
+ buf = Hunk_AllocateTempMemory(len+1);
+ *buffer = buf;
+
+ r = FS_Read( buf, len, com_journalDataFile );
+ if ( r != len ) {
+ Com_Error( ERR_FATAL, "Read from journalDataFile failed" );
+ }
+
+ fs_loadCount++;
+ fs_loadStack++;
+
+ // guarantee that it will have a trailing 0 for string operations
+ buf[len] = 0;
+
+ return len;
+ }
+ } else {
+ isConfig = qfalse;
+ }
+
+ // look for it in the filesystem or pack files
+ len = FS_FOpenFileRead( qpath, &h, qfalse );
+ if ( h == 0 ) {
+ if ( buffer ) {
+ *buffer = NULL;
+ }
+ // if we are journalling and it is a config file, write a zero to the journal file
+ if ( isConfig && com_journal && com_journal->integer == 1 ) {
+ Com_DPrintf( "Writing zero for %s to journal file.\n", qpath );
+ len = 0;
+ FS_Write( &len, sizeof( len ), com_journalDataFile );
+ FS_Flush( com_journalDataFile );
+ }
+ return -1;
+ }
+
+ if ( !buffer ) {
+ if ( isConfig && com_journal && com_journal->integer == 1 ) {
+ Com_DPrintf( "Writing len for %s to journal file.\n", qpath );
+ FS_Write( &len, sizeof( len ), com_journalDataFile );
+ FS_Flush( com_journalDataFile );
+ }
+ FS_FCloseFile( h);
+ return len;
+ }
+
+ fs_loadCount++;
+ fs_loadStack++;
+
+ buf = Hunk_AllocateTempMemory(len+1);
+ *buffer = buf;
+
+ FS_Read (buf, len, h);
+
+ // guarantee that it will have a trailing 0 for string operations
+ buf[len] = 0;
+ FS_FCloseFile( h );
+
+ // if we are journalling and it is a config file, write it to the journal file
+ if ( isConfig && com_journal && com_journal->integer == 1 ) {
+ Com_DPrintf( "Writing %s to journal file.\n", qpath );
+ FS_Write( &len, sizeof( len ), com_journalDataFile );
+ FS_Write( buf, len, com_journalDataFile );
+ FS_Flush( com_journalDataFile );
+ }
+ return len;
+}
+
+/*
+=============
+FS_FreeFile
+=============
+*/
+void FS_FreeFile( void *buffer ) {
+ if ( !fs_searchpaths ) {
+ Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
+ }
+ if ( !buffer ) {
+ Com_Error( ERR_FATAL, "FS_FreeFile( NULL )" );
+ }
+ fs_loadStack--;
+
+ Hunk_FreeTempMemory( buffer );
+
+ // if all of our temp files are free, clear all of our space
+ if ( fs_loadStack == 0 ) {
+ Hunk_ClearTempMemory();
+ }
+}
+
+/*
+============
+FS_WriteFile
+
+Filename are reletive to the quake search path
+============
+*/
+void FS_WriteFile( const char *qpath, const void *buffer, int size ) {
+ fileHandle_t f;
+
+ if ( !fs_searchpaths ) {
+ Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
+ }
+
+ if ( !qpath || !buffer ) {
+ Com_Error( ERR_FATAL, "FS_WriteFile: NULL parameter" );
+ }
+
+ f = FS_FOpenFileWrite( qpath );
+ if ( !f ) {
+ Com_Printf( "Failed to open %s\n", qpath );
+ return;
+ }
+
+ FS_Write( buffer, size, f );
+
+ FS_FCloseFile( f );
+}
+
+
+
+/*
+==========================================================================
+
+ZIP FILE LOADING
+
+==========================================================================
+*/
+
+/*
+=================
+FS_LoadZipFile
+
+Creates a new pak_t in the search chain for the contents
+of a zip file.
+=================
+*/
+static pack_t *FS_LoadZipFile( char *zipfile, const char *basename )
+{
+ fileInPack_t *buildBuffer;
+ pack_t *pack;
+ unzFile uf;
+ int err;
+ unz_global_info gi;
+ char filename_inzip[MAX_ZPATH];
+ unz_file_info file_info;
+ int i, len;
+ long hash;
+ int fs_numHeaderLongs;
+ int *fs_headerLongs;
+ char *namePtr;
+
+ fs_numHeaderLongs = 0;
+
+ uf = unzOpen(zipfile);
+ err = unzGetGlobalInfo (uf,&gi);
+
+ if (err != UNZ_OK)
+ return NULL;
+
+ fs_packFiles += gi.number_entry;
+
+ len = 0;
+ unzGoToFirstFile(uf);
+ for (i = 0; i < gi.number_entry; i++)
+ {
+ err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0);
+ if (err != UNZ_OK) {
+ break;
+ }
+ len += strlen(filename_inzip) + 1;
+ unzGoToNextFile(uf);
+ }
+
+ buildBuffer = Z_Malloc( (gi.number_entry * sizeof( fileInPack_t )) + len );
+ namePtr = ((char *) buildBuffer) + gi.number_entry * sizeof( fileInPack_t );
+ fs_headerLongs = Z_Malloc( gi.number_entry * sizeof(int) );
+
+ // get the hash table size from the number of files in the zip
+ // because lots of custom pk3 files have less than 32 or 64 files
+ for (i = 1; i <= MAX_FILEHASH_SIZE; i <<= 1) {
+ if (i > gi.number_entry) {
+ break;
+ }
+ }
+
+ pack = Z_Malloc( sizeof( pack_t ) + i * sizeof(fileInPack_t *) );
+ pack->hashSize = i;
+ pack->hashTable = (fileInPack_t **) (((char *) pack) + sizeof( pack_t ));
+ for(i = 0; i < pack->hashSize; i++) {
+ pack->hashTable[i] = NULL;
+ }
+
+ Q_strncpyz( pack->pakFilename, zipfile, sizeof( pack->pakFilename ) );
+ Q_strncpyz( pack->pakBasename, basename, sizeof( pack->pakBasename ) );
+
+ // strip .pk3 if needed
+ if ( strlen( pack->pakBasename ) > 4 && !Q_stricmp( pack->pakBasename + strlen( pack->pakBasename ) - 4, ".pk3" ) ) {
+ pack->pakBasename[strlen( pack->pakBasename ) - 4] = 0;
+ }
+
+ pack->handle = uf;
+ pack->numfiles = gi.number_entry;
+ unzGoToFirstFile(uf);
+
+ for (i = 0; i < gi.number_entry; i++)
+ {
+ err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0);
+ if (err != UNZ_OK) {
+ break;
+ }
+ if (file_info.uncompressed_size > 0) {
+ fs_headerLongs[fs_numHeaderLongs++] = LittleLong(file_info.crc);
+ }
+ Q_strlwr( filename_inzip );
+ hash = FS_HashFileName(filename_inzip, pack->hashSize);
+ buildBuffer[i].name = namePtr;
+ strcpy( buildBuffer[i].name, filename_inzip );
+ namePtr += strlen(filename_inzip) + 1;
+ // store the file position in the zip
+ unzGetCurrentFileInfoPosition(uf, &buildBuffer[i].pos);
+ //
+ buildBuffer[i].next = pack->hashTable[hash];
+ pack->hashTable[hash] = &buildBuffer[i];
+ unzGoToNextFile(uf);
+ }
+
+ pack->checksum = Com_BlockChecksum( fs_headerLongs, 4 * fs_numHeaderLongs );
+ pack->pure_checksum = Com_BlockChecksumKey( fs_headerLongs, 4 * fs_numHeaderLongs, LittleLong(fs_checksumFeed) );
+ pack->checksum = LittleLong( pack->checksum );
+ pack->pure_checksum = LittleLong( pack->pure_checksum );
+
+ Z_Free(fs_headerLongs);
+
+ pack->buildBuffer = buildBuffer;
+ return pack;
+}
+
+/*
+=================================================================================
+
+DIRECTORY SCANNING FUNCTIONS
+
+=================================================================================
+*/
+
+#define MAX_FOUND_FILES 0x1000
+
+static int FS_ReturnPath( const char *zname, char *zpath, int *depth ) {
+ int len, at, newdep;
+
+ newdep = 0;
+ zpath[0] = 0;
+ len = 0;
+ at = 0;
+
+ while(zname[at] != 0)
+ {
+ if (zname[at]=='/' || zname[at]=='\\') {
+ len = at;
+ newdep++;
+ }
+ at++;
+ }
+ strcpy(zpath, zname);
+ zpath[len] = 0;
+ *depth = newdep;
+
+ return len;
+}
+
+/*
+==================
+FS_AddFileToList
+==================
+*/
+static int FS_AddFileToList( char *name, char *list[MAX_FOUND_FILES], int nfiles ) {
+ int i;
+
+ if ( nfiles == MAX_FOUND_FILES - 1 ) {
+ return nfiles;
+ }
+ for ( i = 0 ; i < nfiles ; i++ ) {
+ if ( !Q_stricmp( name, list[i] ) ) {
+ return nfiles; // allready in list
+ }
+ }
+ list[nfiles] = CopyString( name );
+ nfiles++;
+
+ return nfiles;
+}
+
+/*
+===============
+FS_ListFilteredFiles
+
+Returns a uniqued list of files that match the given criteria
+from all search paths
+===============
+*/
+char **FS_ListFilteredFiles( const char *path, const char *extension, char *filter, int *numfiles ) {
+ int nfiles;
+ char **listCopy;
+ char *list[MAX_FOUND_FILES];
+ searchpath_t *search;
+ int i;
+ int pathLength;
+ int extensionLength;
+ int length, pathDepth, temp;
+ pack_t *pak;
+ fileInPack_t *buildBuffer;
+ char zpath[MAX_ZPATH];
+
+ if ( !fs_searchpaths ) {
+ Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
+ }
+
+ if ( !path ) {
+ *numfiles = 0;
+ return NULL;
+ }
+ if ( !extension ) {
+ extension = "";
+ }
+
+ pathLength = strlen( path );
+ if ( path[pathLength-1] == '\\' || path[pathLength-1] == '/' ) {
+ pathLength--;
+ }
+ extensionLength = strlen( extension );
+ nfiles = 0;
+ FS_ReturnPath(path, zpath, &pathDepth);
+
+ //
+ // search through the path, one element at a time, adding to list
+ //
+ for (search = fs_searchpaths ; search ; search = search->next) {
+ // is the element a pak file?
+ if (search->pack) {
+
+ //ZOID: If we are pure, don't search for files on paks that
+ // aren't on the pure list
+ if ( !FS_PakIsPure(search->pack) ) {
+ continue;
+ }
+
+ // look through all the pak file elements
+ pak = search->pack;
+ buildBuffer = pak->buildBuffer;
+ for (i = 0; i < pak->numfiles; i++) {
+ char *name;
+ int zpathLen, depth;
+
+ // check for directory match
+ name = buildBuffer[i].name;
+ //
+ if (filter) {
+ // case insensitive
+ if (!Com_FilterPath( filter, name, qfalse ))
+ continue;
+ // unique the match
+ nfiles = FS_AddFileToList( name, list, nfiles );
+ }
+ else {
+
+ zpathLen = FS_ReturnPath(name, zpath, &depth);
+
+ if ( (depth-pathDepth)>2 || pathLength > zpathLen || Q_stricmpn( name, path, pathLength ) ) {
+ continue;
+ }
+
+ // check for extension match
+ length = strlen( name );
+ if ( length < extensionLength ) {
+ continue;
+ }
+
+ if ( Q_stricmp( name + length - extensionLength, extension ) ) {
+ continue;
+ }
+ // unique the match
+
+ temp = pathLength;
+ if (pathLength) {
+ temp++; // include the '/'
+ }
+ nfiles = FS_AddFileToList( name + temp, list, nfiles );
+ }
+ }
+ } else if (search->dir) { // scan for files in the filesystem
+ char *netpath;
+ int numSysFiles;
+ char **sysFiles;
+ char *name;
+
+ // don't scan directories for files if we are pure or restricted
+ if ( fs_restrict->integer || fs_numServerPaks ) {
+ continue;
+ } else {
+ netpath = FS_BuildOSPath( search->dir->path, search->dir->gamedir, path );
+ sysFiles = Sys_ListFiles( netpath, extension, filter, &numSysFiles, qfalse );
+ for ( i = 0 ; i < numSysFiles ; i++ ) {
+ // unique the match
+ name = sysFiles[i];
+ nfiles = FS_AddFileToList( name, list, nfiles );
+ }
+ Sys_FreeFileList( sysFiles );
+ }
+ }
+ }
+
+ // return a copy of the list
+ *numfiles = nfiles;
+
+ if ( !nfiles ) {
+ return NULL;
+ }
+
+ listCopy = Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ) );
+ for ( i = 0 ; i < nfiles ; i++ ) {
+ listCopy[i] = list[i];
+ }
+ listCopy[i] = NULL;
+
+ return listCopy;
+}
+
+/*
+=================
+FS_ListFiles
+=================
+*/
+char **FS_ListFiles( const char *path, const char *extension, int *numfiles ) {
+ return FS_ListFilteredFiles( path, extension, NULL, numfiles );
+}
+
+/*
+=================
+FS_FreeFileList
+=================
+*/
+void FS_FreeFileList( char **list ) {
+ int i;
+
+ if ( !fs_searchpaths ) {
+ Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
+ }
+
+ if ( !list ) {
+ return;
+ }
+
+ for ( i = 0 ; list[i] ; i++ ) {
+ Z_Free( list[i] );
+ }
+
+ Z_Free( list );
+}
+
+
+/*
+================
+FS_GetFileList
+================
+*/
+int FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize ) {
+ int nFiles, i, nTotal, nLen;
+ char **pFiles = NULL;
+
+ *listbuf = 0;
+ nFiles = 0;
+ nTotal = 0;
+
+ if (Q_stricmp(path, "$modlist") == 0) {
+ return FS_GetModList(listbuf, bufsize);
+ }
+
+ pFiles = FS_ListFiles(path, extension, &nFiles);
+
+ for (i =0; i < nFiles; i++) {
+ nLen = strlen(pFiles[i]) + 1;
+ if (nTotal + nLen + 1 < bufsize) {
+ strcpy(listbuf, pFiles[i]);
+ listbuf += nLen;
+ nTotal += nLen;
+ }
+ else {
+ nFiles = i;
+ break;
+ }
+ }
+
+ FS_FreeFileList(pFiles);
+
+ return nFiles;
+}
+
+/*
+=======================
+Sys_ConcatenateFileLists
+
+mkv: Naive implementation. Concatenates three lists into a
+ new list, and frees the old lists from the heap.
+bk001129 - from cvs1.17 (mkv)
+
+FIXME TTimo those two should move to common.c next to Sys_ListFiles
+=======================
+ */
+static unsigned int Sys_CountFileList(char **list)
+{
+ int i = 0;
+
+ if (list)
+ {
+ while (*list)
+ {
+ list++;
+ i++;
+ }
+ }
+ return i;
+}
+
+static char** Sys_ConcatenateFileLists( char **list0, char **list1, char **list2 )
+{
+ int totalLength = 0;
+ char** cat = NULL, **dst, **src;
+
+ totalLength += Sys_CountFileList(list0);
+ totalLength += Sys_CountFileList(list1);
+ totalLength += Sys_CountFileList(list2);
+
+ /* Create new list. */
+ dst = cat = Z_Malloc( ( totalLength + 1 ) * sizeof( char* ) );
+
+ /* Copy over lists. */
+ if (list0)
+ {
+ for (src = list0; *src; src++, dst++)
+ *dst = *src;
+ }
+ if (list1)
+ {
+ for (src = list1; *src; src++, dst++)
+ *dst = *src;
+ }
+ if (list2)
+ {
+ for (src = list2; *src; src++, dst++)
+ *dst = *src;
+ }
+
+ // Terminate the list
+ *dst = NULL;
+
+ // Free our old lists.
+ // NOTE: not freeing their content, it's been merged in dst and still being used
+ if (list0) Z_Free( list0 );
+ if (list1) Z_Free( list1 );
+ if (list2) Z_Free( list2 );
+
+ return cat;
+}
+
+/*
+================
+FS_GetModList
+
+Returns a list of mod directory names
+A mod directory is a peer to baseq3 with a pk3 in it
+The directories are searched in base path, cd path and home path
+================
+*/
+int FS_GetModList( char *listbuf, int bufsize ) {
+ int nMods, i, j, nTotal, nLen, nPaks, nPotential, nDescLen;
+ char **pFiles = NULL;
+ char **pPaks = NULL;
+ char *name, *path;
+ char descPath[MAX_OSPATH];
+ fileHandle_t descHandle;
+
+ int dummy;
+ char **pFiles0 = NULL;
+ char **pFiles1 = NULL;
+ char **pFiles2 = NULL;
+ qboolean bDrop = qfalse;
+
+ *listbuf = 0;
+ nMods = nPotential = nTotal = 0;
+
+ pFiles0 = Sys_ListFiles( fs_homepath->string, NULL, NULL, &dummy, qtrue );
+ pFiles1 = Sys_ListFiles( fs_basepath->string, NULL, NULL, &dummy, qtrue );
+ pFiles2 = Sys_ListFiles( fs_cdpath->string, NULL, NULL, &dummy, qtrue );
+ // we searched for mods in the three paths
+ // it is likely that we have duplicate names now, which we will cleanup below
+ pFiles = Sys_ConcatenateFileLists( pFiles0, pFiles1, pFiles2 );
+ nPotential = Sys_CountFileList(pFiles);
+
+ for ( i = 0 ; i < nPotential ; i++ ) {
+ name = pFiles[i];
+ // NOTE: cleaner would involve more changes
+ // ignore duplicate mod directories
+ if (i!=0) {
+ bDrop = qfalse;
+ for(j=0; j<i; j++)
+ {
+ if (Q_stricmp(pFiles[j],name)==0) {
+ // this one can be dropped
+ bDrop = qtrue;
+ break;
+ }
+ }
+ }
+ if (bDrop) {
+ continue;
+ }
+ // we drop "baseq3" "." and ".."
+ if (Q_stricmp(name, "baseq3") && Q_stricmpn(name, ".", 1)) {
+ // now we need to find some .pk3 files to validate the mod
+ // NOTE TTimo: (actually I'm not sure why .. what if it's a mod under developement with no .pk3?)
+ // we didn't keep the information when we merged the directory names, as to what OS Path it was found under
+ // so it could be in base path, cd path or home path
+ // we will try each three of them here (yes, it's a bit messy)
+ path = FS_BuildOSPath( fs_basepath->string, name, "" );
+ nPaks = 0;
+ pPaks = Sys_ListFiles(path, ".pk3", NULL, &nPaks, qfalse);
+ Sys_FreeFileList( pPaks ); // we only use Sys_ListFiles to check wether .pk3 files are present
+
+ /* Try on cd path */
+ if( nPaks <= 0 ) {
+ path = FS_BuildOSPath( fs_cdpath->string, name, "" );
+ nPaks = 0;
+ pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse );
+ Sys_FreeFileList( pPaks );
+ }
+
+ /* try on home path */
+ if ( nPaks <= 0 )
+ {
+ path = FS_BuildOSPath( fs_homepath->string, name, "" );
+ nPaks = 0;
+ pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse );
+ Sys_FreeFileList( pPaks );
+ }
+
+ if (nPaks > 0) {
+ nLen = strlen(name) + 1;
+ // nLen is the length of the mod path
+ // we need to see if there is a description available
+ descPath[0] = '\0';
+ strcpy(descPath, name);
+ strcat(descPath, "/description.txt");
+ nDescLen = FS_SV_FOpenFileRead( descPath, &descHandle );
+ if ( nDescLen > 0 && descHandle) {
+ FILE *file;
+ file = FS_FileForHandle(descHandle);
+ Com_Memset( descPath, 0, sizeof( descPath ) );
+ nDescLen = fread(descPath, 1, 48, file);
+ if (nDescLen >= 0) {
+ descPath[nDescLen] = '\0';
+ }
+ FS_FCloseFile(descHandle);
+ } else {
+ strcpy(descPath, name);
+ }
+ nDescLen = strlen(descPath) + 1;
+
+ if (nTotal + nLen + 1 + nDescLen + 1 < bufsize) {
+ strcpy(listbuf, name);
+ listbuf += nLen;
+ strcpy(listbuf, descPath);
+ listbuf += nDescLen;
+ nTotal += nLen + nDescLen;
+ nMods++;
+ }
+ else {
+ break;
+ }
+ }
+ }
+ }
+ Sys_FreeFileList( pFiles );
+
+ return nMods;
+}
+
+
+
+
+//============================================================================
+
+/*
+================
+FS_Dir_f
+================
+*/
+void FS_Dir_f( void ) {
+ char *path;
+ char *extension;
+ char **dirnames;
+ int ndirs;
+ int i;
+
+ if ( Cmd_Argc() < 2 || Cmd_Argc() > 3 ) {
+ Com_Printf( "usage: dir <directory> [extension]\n" );
+ return;
+ }
+
+ if ( Cmd_Argc() == 2 ) {
+ path = Cmd_Argv( 1 );
+ extension = "";
+ } else {
+ path = Cmd_Argv( 1 );
+ extension = Cmd_Argv( 2 );
+ }
+
+ Com_Printf( "Directory of %s %s\n", path, extension );
+ Com_Printf( "---------------\n" );
+
+ dirnames = FS_ListFiles( path, extension, &ndirs );
+
+ for ( i = 0; i < ndirs; i++ ) {
+ Com_Printf( "%s\n", dirnames[i] );
+ }
+ FS_FreeFileList( dirnames );
+}
+
+/*
+===========
+FS_ConvertPath
+===========
+*/
+void FS_ConvertPath( char *s ) {
+ while (*s) {
+ if ( *s == '\\' || *s == ':' ) {
+ *s = '/';
+ }
+ s++;
+ }
+}
+
+/*
+===========
+FS_PathCmp
+
+Ignore case and seprator char distinctions
+===========
+*/
+int FS_PathCmp( const char *s1, const char *s2 ) {
+ int c1, c2;
+
+ do {
+ c1 = *s1++;
+ c2 = *s2++;
+
+ if (c1 >= 'a' && c1 <= 'z') {
+ c1 -= ('a' - 'A');
+ }
+ if (c2 >= 'a' && c2 <= 'z') {
+ c2 -= ('a' - 'A');
+ }
+
+ if ( c1 == '\\' || c1 == ':' ) {
+ c1 = '/';
+ }
+ if ( c2 == '\\' || c2 == ':' ) {
+ c2 = '/';
+ }
+
+ if (c1 < c2) {
+ return -1; // strings not equal
+ }
+ if (c1 > c2) {
+ return 1;
+ }
+ } while (c1);
+
+ return 0; // strings are equal
+}
+
+/*
+================
+FS_SortFileList
+================
+*/
+void FS_SortFileList(char **filelist, int numfiles) {
+ int i, j, k, numsortedfiles;
+ char **sortedlist;
+
+ sortedlist = Z_Malloc( ( numfiles + 1 ) * sizeof( *sortedlist ) );
+ sortedlist[0] = NULL;
+ numsortedfiles = 0;
+ for (i = 0; i < numfiles; i++) {
+ for (j = 0; j < numsortedfiles; j++) {
+ if (FS_PathCmp(filelist[i], sortedlist[j]) < 0) {
+ break;
+ }
+ }
+ for (k = numsortedfiles; k > j; k--) {
+ sortedlist[k] = sortedlist[k-1];
+ }
+ sortedlist[j] = filelist[i];
+ numsortedfiles++;
+ }
+ Com_Memcpy(filelist, sortedlist, numfiles * sizeof( *filelist ) );
+ Z_Free(sortedlist);
+}
+
+/*
+================
+FS_NewDir_f
+================
+*/
+void FS_NewDir_f( void ) {
+ char *filter;
+ char **dirnames;
+ int ndirs;
+ int i;
+
+ if ( Cmd_Argc() < 2 ) {
+ Com_Printf( "usage: fdir <filter>\n" );
+ Com_Printf( "example: fdir *q3dm*.bsp\n");
+ return;
+ }
+
+ filter = Cmd_Argv( 1 );
+
+ Com_Printf( "---------------\n" );
+
+ dirnames = FS_ListFilteredFiles( "", "", filter, &ndirs );
+
+ FS_SortFileList(dirnames, ndirs);
+
+ for ( i = 0; i < ndirs; i++ ) {
+ FS_ConvertPath(dirnames[i]);
+ Com_Printf( "%s\n", dirnames[i] );
+ }
+ Com_Printf( "%d files listed\n", ndirs );
+ FS_FreeFileList( dirnames );
+}
+
+/*
+============
+FS_Path_f
+
+============
+*/
+void FS_Path_f( void ) {
+ searchpath_t *s;
+ int i;
+
+ Com_Printf ("Current search path:\n");
+ for (s = fs_searchpaths; s; s = s->next) {
+ if (s->pack) {
+ Com_Printf ("%s (%i files)\n", s->pack->pakFilename, s->pack->numfiles);
+ if ( fs_numServerPaks ) {
+ if ( !FS_PakIsPure(s->pack) ) {
+ Com_Printf( " not on the pure list\n" );
+ } else {
+ Com_Printf( " on the pure list\n" );
+ }
+ }
+ } else {
+ Com_Printf ("%s/%s\n", s->dir->path, s->dir->gamedir );
+ }
+ }
+
+
+ Com_Printf( "\n" );
+ for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
+ if ( fsh[i].handleFiles.file.o ) {
+ Com_Printf( "handle %i: %s\n", i, fsh[i].name );
+ }
+ }
+}
+
+/*
+============
+FS_TouchFile_f
+
+The only purpose of this function is to allow game script files to copy
+arbitrary files furing an "fs_copyfiles 1" run.
+============
+*/
+void FS_TouchFile_f( void ) {
+ fileHandle_t f;
+
+ if ( Cmd_Argc() != 2 ) {
+ Com_Printf( "Usage: touchFile <file>\n" );
+ return;
+ }
+
+ FS_FOpenFileRead( Cmd_Argv( 1 ), &f, qfalse );
+ if ( f ) {
+ FS_FCloseFile( f );
+ }
+}
+
+//===========================================================================
+
+
+static int QDECL paksort( const void *a, const void *b ) {
+ char *aa, *bb;
+
+ aa = *(char **)a;
+ bb = *(char **)b;
+
+ return FS_PathCmp( aa, bb );
+}
+
+/*
+================
+FS_AddGameDirectory
+
+Sets fs_gamedir, adds the directory to the head of the path,
+then loads the zip headers
+================
+*/
+#define MAX_PAKFILES 1024
+static void FS_AddGameDirectory( const char *path, const char *dir ) {
+ searchpath_t *sp;
+ int i;
+ searchpath_t *search;
+ pack_t *pak;
+ char *pakfile;
+ int numfiles;
+ char **pakfiles;
+ char *sorted[MAX_PAKFILES];
+
+ // this fixes the case where fs_basepath is the same as fs_cdpath
+ // which happens on full installs
+ for ( sp = fs_searchpaths ; sp ; sp = sp->next ) {
+ if ( sp->dir && !Q_stricmp(sp->dir->path, path) && !Q_stricmp(sp->dir->gamedir, dir)) {
+ return; // we've already got this one
+ }
+ }
+
+ Q_strncpyz( fs_gamedir, dir, sizeof( fs_gamedir ) );
+
+ //
+ // add the directory to the search path
+ //
+ search = Z_Malloc (sizeof(searchpath_t));
+ search->dir = Z_Malloc( sizeof( *search->dir ) );
+
+ Q_strncpyz( search->dir->path, path, sizeof( search->dir->path ) );
+ Q_strncpyz( search->dir->gamedir, dir, sizeof( search->dir->gamedir ) );
+ search->next = fs_searchpaths;
+ fs_searchpaths = search;
+
+ // find all pak files in this directory
+ pakfile = FS_BuildOSPath( path, dir, "" );
+ pakfile[ strlen(pakfile) - 1 ] = 0; // strip the trailing slash
+
+ pakfiles = Sys_ListFiles( pakfile, ".pk3", NULL, &numfiles, qfalse );
+
+ // sort them so that later alphabetic matches override
+ // earlier ones. This makes pak1.pk3 override pak0.pk3
+ if ( numfiles > MAX_PAKFILES ) {
+ numfiles = MAX_PAKFILES;
+ }
+ for ( i = 0 ; i < numfiles ; i++ ) {
+ sorted[i] = pakfiles[i];
+ }
+
+ qsort( sorted, numfiles, 4, paksort );
+
+ for ( i = 0 ; i < numfiles ; i++ ) {
+ pakfile = FS_BuildOSPath( path, dir, sorted[i] );
+ if ( ( pak = FS_LoadZipFile( pakfile, sorted[i] ) ) == 0 )
+ continue;
+ // store the game name for downloading
+ strcpy(pak->pakGamename, dir);
+
+ search = Z_Malloc (sizeof(searchpath_t));
+ search->pack = pak;
+ search->next = fs_searchpaths;
+ fs_searchpaths = search;
+ }
+
+ // done
+ Sys_FreeFileList( pakfiles );
+}
+
+/*
+================
+FS_idPak
+================
+*/
+qboolean FS_idPak( char *pak, char *base ) {
+ int i;
+
+ for (i = 0; i < NUM_ID_PAKS; i++) {
+ if ( !FS_FilenameCompare(pak, va("%s/pak%d", base, i)) ) {
+ break;
+ }
+ }
+ if (i < NUM_ID_PAKS) {
+ return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+================
+FS_ComparePaks
+
+----------------
+dlstring == qtrue
+
+Returns a list of pak files that we should download from the server. They all get stored
+in the current gamedir and an FS_Restart will be fired up after we download them all.
+
+The string is the format:
+
+@remotename@localname [repeat]
+
+static int fs_numServerReferencedPaks;
+static int fs_serverReferencedPaks[MAX_SEARCH_PATHS];
+static char *fs_serverReferencedPakNames[MAX_SEARCH_PATHS];
+
+----------------
+dlstring == qfalse
+
+we are not interested in a download string format, we want something human-readable
+(this is used for diagnostics while connecting to a pure server)
+
+================
+*/
+qboolean FS_ComparePaks( char *neededpaks, int len, qboolean dlstring ) {
+ searchpath_t *sp;
+ qboolean havepak, badchecksum;
+ int i;
+
+ if ( !fs_numServerReferencedPaks ) {
+ return qfalse; // Server didn't send any pack information along
+ }
+
+ *neededpaks = 0;
+
+ for ( i = 0 ; i < fs_numServerReferencedPaks ; i++ ) {
+ // Ok, see if we have this pak file
+ badchecksum = qfalse;
+ havepak = qfalse;
+
+ // never autodownload any of the id paks
+ if ( FS_idPak(fs_serverReferencedPakNames[i], "baseq3") || FS_idPak(fs_serverReferencedPakNames[i], "missionpack") ) {
+ continue;
+ }
+
+ for ( sp = fs_searchpaths ; sp ; sp = sp->next ) {
+ if ( sp->pack && sp->pack->checksum == fs_serverReferencedPaks[i] ) {
+ havepak = qtrue; // This is it!
+ break;
+ }
+ }
+
+ if ( !havepak && fs_serverReferencedPakNames[i] && *fs_serverReferencedPakNames[i] ) {
+ // Don't got it
+
+ if (dlstring)
+ {
+ // Remote name
+ Q_strcat( neededpaks, len, "@");
+ Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
+ Q_strcat( neededpaks, len, ".pk3" );
+
+ // Local name
+ Q_strcat( neededpaks, len, "@");
+ // Do we have one with the same name?
+ if ( FS_SV_FileExists( va( "%s.pk3", fs_serverReferencedPakNames[i] ) ) )
+ {
+ char st[MAX_ZPATH];
+ // We already have one called this, we need to download it to another name
+ // Make something up with the checksum in it
+ Com_sprintf( st, sizeof( st ), "%s.%08x.pk3", fs_serverReferencedPakNames[i], fs_serverReferencedPaks[i] );
+ Q_strcat( neededpaks, len, st );
+ } else
+ {
+ Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
+ Q_strcat( neededpaks, len, ".pk3" );
+ }
+ }
+ else
+ {
+ Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
+ Q_strcat( neededpaks, len, ".pk3" );
+ // Do we have one with the same name?
+ if ( FS_SV_FileExists( va( "%s.pk3", fs_serverReferencedPakNames[i] ) ) )
+ {
+ Q_strcat( neededpaks, len, " (local file exists with wrong checksum)");
+ }
+ Q_strcat( neededpaks, len, "\n");
+ }
+ }
+ }
+
+ if ( *neededpaks ) {
+ return qtrue;
+ }
+
+ return qfalse; // We have them all
+}
+
+/*
+================
+FS_Shutdown
+
+Frees all resources and closes all files
+================
+*/
+void FS_Shutdown( qboolean closemfp ) {
+ searchpath_t *p, *next;
+ int i;
+
+ for(i = 0; i < MAX_FILE_HANDLES; i++) {
+ if (fsh[i].fileSize) {
+ FS_FCloseFile(i);
+ }
+ }
+
+ // free everything
+ for ( p = fs_searchpaths ; p ; p = next ) {
+ next = p->next;
+
+ if ( p->pack ) {
+ unzClose(p->pack->handle);
+ Z_Free( p->pack->buildBuffer );
+ Z_Free( p->pack );
+ }
+ if ( p->dir ) {
+ Z_Free( p->dir );
+ }
+ Z_Free( p );
+ }
+
+ // any FS_ calls will now be an error until reinitialized
+ fs_searchpaths = NULL;
+
+ Cmd_RemoveCommand( "path" );
+ Cmd_RemoveCommand( "dir" );
+ Cmd_RemoveCommand( "fdir" );
+ Cmd_RemoveCommand( "touchFile" );
+
+#ifdef FS_MISSING
+ if (closemfp) {
+ fclose(missingFiles);
+ }
+#endif
+}
+
+void Com_AppendCDKey( const char *filename );
+void Com_ReadCDKey( const char *filename );
+
+/*
+================
+FS_ReorderPurePaks
+NOTE TTimo: the reordering that happens here is not reflected in the cvars (\cvarlist *pak*)
+ this can lead to misleading situations, see https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540
+================
+*/
+static void FS_ReorderPurePaks()
+{
+ searchpath_t *s;
+ int i;
+ searchpath_t **p_insert_index, // for linked list reordering
+ **p_previous; // when doing the scan
+
+ // only relevant when connected to pure server
+ if ( !fs_numServerPaks )
+ return;
+
+ fs_reordered = qfalse;
+
+ p_insert_index = &fs_searchpaths; // we insert in order at the beginning of the list
+ for ( i = 0 ; i < fs_numServerPaks ; i++ ) {
+ p_previous = p_insert_index; // track the pointer-to-current-item
+ for (s = *p_insert_index; s; s = s->next) {
+ // the part of the list before p_insert_index has been sorted already
+ if (s->pack && fs_serverPaks[i] == s->pack->checksum) {
+ fs_reordered = qtrue;
+ // move this element to the insert list
+ *p_previous = s->next;
+ s->next = *p_insert_index;
+ *p_insert_index = s;
+ // increment insert list
+ p_insert_index = &s->next;
+ break; // iterate to next server pack
+ }
+ p_previous = &s->next;
+ }
+ }
+}
+
+/*
+================
+FS_Startup
+================
+*/
+static void FS_Startup( const char *gameName ) {
+ const char *homePath;
+ cvar_t *fs;
+
+ Com_Printf( "----- FS_Startup -----\n" );
+
+ fs_debug = Cvar_Get( "fs_debug", "0", 0 );
+ fs_copyfiles = Cvar_Get( "fs_copyfiles", "0", CVAR_INIT );
+ fs_cdpath = Cvar_Get ("fs_cdpath", Sys_DefaultCDPath(), CVAR_INIT );
+ fs_basepath = Cvar_Get ("fs_basepath", Sys_DefaultInstallPath(), CVAR_INIT );
+ fs_basegame = Cvar_Get ("fs_basegame", "", CVAR_INIT );
+ homePath = Sys_DefaultHomePath();
+ if (!homePath || !homePath[0]) {
+ homePath = fs_basepath->string;
+ }
+ fs_homepath = Cvar_Get ("fs_homepath", homePath, CVAR_INIT );
+ fs_gamedirvar = Cvar_Get ("fs_game", "", CVAR_INIT|CVAR_SYSTEMINFO );
+ fs_restrict = Cvar_Get ("fs_restrict", "", CVAR_INIT );
+
+ // add search path elements in reverse priority order
+ if (fs_cdpath->string[0]) {
+ FS_AddGameDirectory( fs_cdpath->string, gameName );
+ }
+ if (fs_basepath->string[0]) {
+ FS_AddGameDirectory( fs_basepath->string, gameName );
+ }
+ // fs_homepath is somewhat particular to *nix systems, only add if relevant
+ // NOTE: same filtering below for mods and basegame
+ if (fs_basepath->string[0] && Q_stricmp(fs_homepath->string,fs_basepath->string)) {
+ FS_AddGameDirectory ( fs_homepath->string, gameName );
+ }
+
+ // check for additional base game so mods can be based upon other mods
+ if ( fs_basegame->string[0] && !Q_stricmp( gameName, BASEGAME ) && Q_stricmp( fs_basegame->string, gameName ) ) {
+ if (fs_cdpath->string[0]) {
+ FS_AddGameDirectory(fs_cdpath->string, fs_basegame->string);
+ }
+ if (fs_basepath->string[0]) {
+ FS_AddGameDirectory(fs_basepath->string, fs_basegame->string);
+ }
+ if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string,fs_basepath->string)) {
+ FS_AddGameDirectory(fs_homepath->string, fs_basegame->string);
+ }
+ }
+
+ // check for additional game folder for mods
+ if ( fs_gamedirvar->string[0] && !Q_stricmp( gameName, BASEGAME ) && Q_stricmp( fs_gamedirvar->string, gameName ) ) {
+ if (fs_cdpath->string[0]) {
+ FS_AddGameDirectory(fs_cdpath->string, fs_gamedirvar->string);
+ }
+ if (fs_basepath->string[0]) {
+ FS_AddGameDirectory(fs_basepath->string, fs_gamedirvar->string);
+ }
+ if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string,fs_basepath->string)) {
+ FS_AddGameDirectory(fs_homepath->string, fs_gamedirvar->string);
+ }
+ }
+
+ Com_ReadCDKey( "baseq3" );
+ fs = Cvar_Get ("fs_game", "", CVAR_INIT|CVAR_SYSTEMINFO );
+ if (fs && fs->string[0] != 0) {
+ Com_AppendCDKey( fs->string );
+ }
+
+ // add our commands
+ Cmd_AddCommand ("path", FS_Path_f);
+ Cmd_AddCommand ("dir", FS_Dir_f );
+ Cmd_AddCommand ("fdir", FS_NewDir_f );
+ Cmd_AddCommand ("touchFile", FS_TouchFile_f );
+
+ // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=506
+ // reorder the pure pk3 files according to server order
+ FS_ReorderPurePaks();
+
+ // print the current search paths
+ FS_Path_f();
+
+ fs_gamedirvar->modified = qfalse; // We just loaded, it's not modified
+
+ Com_Printf( "----------------------\n" );
+
+#ifdef FS_MISSING
+ if (missingFiles == NULL) {
+ missingFiles = fopen( "\\missing.txt", "ab" );
+ }
+#endif
+ Com_Printf( "%d files in pk3 files\n", fs_packFiles );
+}
+
+
+/*
+===================
+FS_SetRestrictions
+
+Looks for product keys and restricts media add on ability
+if the full version is not found
+===================
+*/
+static void FS_SetRestrictions( void ) {
+ searchpath_t *path;
+
+#ifndef PRE_RELEASE_DEMO
+ char *productId;
+
+ // if fs_restrict is set, don't even look for the id file,
+ // which allows the demo release to be tested even if
+ // the full game is present
+ if ( !fs_restrict->integer ) {
+ // look for the full game id
+ FS_ReadFile( "productid.txt", (void **)&productId );
+ if ( productId ) {
+ // check against the hardcoded string
+ int seed, i;
+
+ seed = 5000;
+ for ( i = 0 ; i < sizeof( fs_scrambledProductId ) ; i++ ) {
+ if ( ( fs_scrambledProductId[i] ^ (seed&255) ) != productId[i] ) {
+ break;
+ }
+ seed = (69069 * seed + 1);
+ }
+
+ FS_FreeFile( productId );
+
+ if ( i == sizeof( fs_scrambledProductId ) ) {
+ return; // no restrictions
+ }
+ Com_Error( ERR_FATAL, "Invalid product identification" );
+ }
+ }
+#endif
+ Cvar_Set( "fs_restrict", "1" );
+
+ Com_Printf( "\nRunning in restricted demo mode.\n\n" );
+
+ // restart the filesystem with just the demo directory
+ FS_Shutdown(qfalse);
+ FS_Startup( DEMOGAME );
+
+ // make sure that the pak file has the header checksum we expect
+ for ( path = fs_searchpaths ; path ; path = path->next ) {
+ if ( path->pack ) {
+ // a tiny attempt to keep the checksum from being scannable from the exe
+ if ( (path->pack->checksum ^ 0x02261994u) != (DEMO_PAK_CHECKSUM ^ 0x02261994u) ) {
+ Com_Error( ERR_FATAL, "Corrupted pak0.pk3: %u", path->pack->checksum );
+ }
+ }
+ }
+}
+
+/*
+=====================
+FS_GamePureChecksum
+
+Returns the checksum of the pk3 from which the server loaded the qagame.qvm
+=====================
+*/
+const char *FS_GamePureChecksum( void ) {
+ static char info[MAX_STRING_TOKENS];
+ searchpath_t *search;
+
+ info[0] = 0;
+
+ for ( search = fs_searchpaths ; search ; search = search->next ) {
+ // is the element a pak file?
+ if ( search->pack ) {
+ if (search->pack->referenced & FS_QAGAME_REF) {
+ Com_sprintf(info, sizeof(info), "%d", search->pack->checksum);
+ }
+ }
+ }
+
+ return info;
+}
+
+/*
+=====================
+FS_LoadedPakChecksums
+
+Returns a space separated string containing the checksums of all loaded pk3 files.
+Servers with sv_pure set will get this string and pass it to clients.
+=====================
+*/
+const char *FS_LoadedPakChecksums( void ) {
+ static char info[BIG_INFO_STRING];
+ searchpath_t *search;
+
+ info[0] = 0;
+
+ for ( search = fs_searchpaths ; search ; search = search->next ) {
+ // is the element a pak file?
+ if ( !search->pack ) {
+ continue;
+ }
+
+ Q_strcat( info, sizeof( info ), va("%i ", search->pack->checksum ) );
+ }
+
+ return info;
+}
+
+/*
+=====================
+FS_LoadedPakNames
+
+Returns a space separated string containing the names of all loaded pk3 files.
+Servers with sv_pure set will get this string and pass it to clients.
+=====================
+*/
+const char *FS_LoadedPakNames( void ) {
+ static char info[BIG_INFO_STRING];
+ searchpath_t *search;
+
+ info[0] = 0;
+
+ for ( search = fs_searchpaths ; search ; search = search->next ) {
+ // is the element a pak file?
+ if ( !search->pack ) {
+ continue;
+ }
+
+ if (*info) {
+ Q_strcat(info, sizeof( info ), " " );
+ }
+ Q_strcat( info, sizeof( info ), search->pack->pakBasename );
+ }
+
+ return info;
+}
+
+/*
+=====================
+FS_LoadedPakPureChecksums
+
+Returns a space separated string containing the pure checksums of all loaded pk3 files.
+Servers with sv_pure use these checksums to compare with the checksums the clients send
+back to the server.
+=====================
+*/
+const char *FS_LoadedPakPureChecksums( void ) {
+ static char info[BIG_INFO_STRING];
+ searchpath_t *search;
+
+ info[0] = 0;
+
+ for ( search = fs_searchpaths ; search ; search = search->next ) {
+ // is the element a pak file?
+ if ( !search->pack ) {
+ continue;
+ }
+
+ Q_strcat( info, sizeof( info ), va("%i ", search->pack->pure_checksum ) );
+ }
+
+ return info;
+}
+
+/*
+=====================
+FS_ReferencedPakChecksums
+
+Returns a space separated string containing the checksums of all referenced pk3 files.
+The server will send this to the clients so they can check which files should be auto-downloaded.
+=====================
+*/
+const char *FS_ReferencedPakChecksums( void ) {
+ static char info[BIG_INFO_STRING];
+ searchpath_t *search;
+
+ info[0] = 0;
+
+
+ for ( search = fs_searchpaths ; search ; search = search->next ) {
+ // is the element a pak file?
+ if ( search->pack ) {
+ if (search->pack->referenced || Q_stricmpn(search->pack->pakGamename, BASEGAME, strlen(BASEGAME))) {
+ Q_strcat( info, sizeof( info ), va("%i ", search->pack->checksum ) );
+ }
+ }
+ }
+
+ return info;
+}
+
+/*
+=====================
+FS_ReferencedPakPureChecksums
+
+Returns a space separated string containing the pure checksums of all referenced pk3 files.
+Servers with sv_pure set will get this string back from clients for pure validation
+
+The string has a specific order, "cgame ui @ ref1 ref2 ref3 ..."
+=====================
+*/
+const char *FS_ReferencedPakPureChecksums( void ) {
+ static char info[BIG_INFO_STRING];
+ searchpath_t *search;
+ int nFlags, numPaks, checksum;
+
+ info[0] = 0;
+
+ checksum = fs_checksumFeed;
+ numPaks = 0;
+ for (nFlags = FS_CGAME_REF; nFlags; nFlags = nFlags >> 1) {
+ if (nFlags & FS_GENERAL_REF) {
+ // add a delimter between must haves and general refs
+ //Q_strcat(info, sizeof(info), "@ ");
+ info[strlen(info)+1] = '\0';
+ info[strlen(info)+2] = '\0';
+ info[strlen(info)] = '@';
+ info[strlen(info)] = ' ';
+ }
+ for ( search = fs_searchpaths ; search ; search = search->next ) {
+ // is the element a pak file and has it been referenced based on flag?
+ if ( search->pack && (search->pack->referenced & nFlags)) {
+ Q_strcat( info, sizeof( info ), va("%i ", search->pack->pure_checksum ) );
+ if (nFlags & (FS_CGAME_REF | FS_UI_REF)) {
+ break;
+ }
+ checksum ^= search->pack->pure_checksum;
+ numPaks++;
+ }
+ }
+ if (fs_fakeChkSum != 0) {
+ // only added if a non-pure file is referenced
+ Q_strcat( info, sizeof( info ), va("%i ", fs_fakeChkSum ) );
+ }
+ }
+ // last checksum is the encoded number of referenced pk3s
+ checksum ^= numPaks;
+ Q_strcat( info, sizeof( info ), va("%i ", checksum ) );
+
+ return info;
+}
+
+/*
+=====================
+FS_ReferencedPakNames
+
+Returns a space separated string containing the names of all referenced pk3 files.
+The server will send this to the clients so they can check which files should be auto-downloaded.
+=====================
+*/
+const char *FS_ReferencedPakNames( void ) {
+ static char info[BIG_INFO_STRING];
+ searchpath_t *search;
+
+ info[0] = 0;
+
+ // we want to return ALL pk3's from the fs_game path
+ // and referenced one's from baseq3
+ for ( search = fs_searchpaths ; search ; search = search->next ) {
+ // is the element a pak file?
+ if ( search->pack ) {
+ if (*info) {
+ Q_strcat(info, sizeof( info ), " " );
+ }
+ if (search->pack->referenced || Q_stricmpn(search->pack->pakGamename, BASEGAME, strlen(BASEGAME))) {
+ Q_strcat( info, sizeof( info ), search->pack->pakGamename );
+ Q_strcat( info, sizeof( info ), "/" );
+ Q_strcat( info, sizeof( info ), search->pack->pakBasename );
+ }
+ }
+ }
+
+ return info;
+}
+
+/*
+=====================
+FS_ClearPakReferences
+=====================
+*/
+void FS_ClearPakReferences( int flags ) {
+ searchpath_t *search;
+
+ if ( !flags ) {
+ flags = -1;
+ }
+ for ( search = fs_searchpaths; search; search = search->next ) {
+ // is the element a pak file and has it been referenced?
+ if ( search->pack ) {
+ search->pack->referenced &= ~flags;
+ }
+ }
+}
+
+
+/*
+=====================
+FS_PureServerSetLoadedPaks
+
+If the string is empty, all data sources will be allowed.
+If not empty, only pk3 files that match one of the space
+separated checksums will be checked for files, with the
+exception of .cfg and .dat files.
+=====================
+*/
+void FS_PureServerSetLoadedPaks( const char *pakSums, const char *pakNames ) {
+ int i, c, d;
+
+ Cmd_TokenizeString( pakSums );
+
+ c = Cmd_Argc();
+ if ( c > MAX_SEARCH_PATHS ) {
+ c = MAX_SEARCH_PATHS;
+ }
+
+ fs_numServerPaks = c;
+
+ for ( i = 0 ; i < c ; i++ ) {
+ fs_serverPaks[i] = atoi( Cmd_Argv( i ) );
+ }
+
+ if (fs_numServerPaks) {
+ Com_DPrintf( "Connected to a pure server.\n" );
+ }
+ else
+ {
+ if (fs_reordered)
+ {
+ // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540
+ // force a restart to make sure the search order will be correct
+ Com_DPrintf( "FS search reorder is required\n" );
+ FS_Restart(fs_checksumFeed);
+ return;
+ }
+ }
+
+ for ( i = 0 ; i < c ; i++ ) {
+ if (fs_serverPakNames[i]) {
+ Z_Free(fs_serverPakNames[i]);
+ }
+ fs_serverPakNames[i] = NULL;
+ }
+ if ( pakNames && *pakNames ) {
+ Cmd_TokenizeString( pakNames );
+
+ d = Cmd_Argc();
+ if ( d > MAX_SEARCH_PATHS ) {
+ d = MAX_SEARCH_PATHS;
+ }
+
+ for ( i = 0 ; i < d ; i++ ) {
+ fs_serverPakNames[i] = CopyString( Cmd_Argv( i ) );
+ }
+ }
+}
+
+/*
+=====================
+FS_PureServerSetReferencedPaks
+
+The checksums and names of the pk3 files referenced at the server
+are sent to the client and stored here. The client will use these
+checksums to see if any pk3 files need to be auto-downloaded.
+=====================
+*/
+void FS_PureServerSetReferencedPaks( const char *pakSums, const char *pakNames ) {
+ int i, c, d;
+
+ Cmd_TokenizeString( pakSums );
+
+ c = Cmd_Argc();
+ if ( c > MAX_SEARCH_PATHS ) {
+ c = MAX_SEARCH_PATHS;
+ }
+
+ fs_numServerReferencedPaks = c;
+
+ for ( i = 0 ; i < c ; i++ ) {
+ fs_serverReferencedPaks[i] = atoi( Cmd_Argv( i ) );
+ }
+
+ for ( i = 0 ; i < c ; i++ ) {
+ if (fs_serverReferencedPakNames[i]) {
+ Z_Free(fs_serverReferencedPakNames[i]);
+ }
+ fs_serverReferencedPakNames[i] = NULL;
+ }
+ if ( pakNames && *pakNames ) {
+ Cmd_TokenizeString( pakNames );
+
+ d = Cmd_Argc();
+ if ( d > MAX_SEARCH_PATHS ) {
+ d = MAX_SEARCH_PATHS;
+ }
+
+ for ( i = 0 ; i < d ; i++ ) {
+ fs_serverReferencedPakNames[i] = CopyString( Cmd_Argv( i ) );
+ }
+ }
+}
+
+/*
+================
+FS_InitFilesystem
+
+Called only at inital startup, not when the filesystem
+is resetting due to a game change
+================
+*/
+void FS_InitFilesystem( void ) {
+ // allow command line parms to override our defaults
+ // we have to specially handle this, because normal command
+ // line variable sets don't happen until after the filesystem
+ // has already been initialized
+ Com_StartupVariable( "fs_cdpath" );
+ Com_StartupVariable( "fs_basepath" );
+ Com_StartupVariable( "fs_homepath" );
+ Com_StartupVariable( "fs_game" );
+ Com_StartupVariable( "fs_copyfiles" );
+ Com_StartupVariable( "fs_restrict" );
+
+ // try to start up normally
+ FS_Startup( BASEGAME );
+
+ // see if we are going to allow add-ons
+ FS_SetRestrictions();
+
+ // if we can't find default.cfg, assume that the paths are
+ // busted and error out now, rather than getting an unreadable
+ // graphics screen when the font fails to load
+ if ( FS_ReadFile( "default.cfg", NULL ) <= 0 ) {
+ Com_Error( ERR_FATAL, "Couldn't load default.cfg" );
+ // bk001208 - SafeMode see below, FIXME?
+ }
+
+ Q_strncpyz(lastValidBase, fs_basepath->string, sizeof(lastValidBase));
+ Q_strncpyz(lastValidGame, fs_gamedirvar->string, sizeof(lastValidGame));
+
+ // bk001208 - SafeMode see below, FIXME?
+}
+
+
+/*
+================
+FS_Restart
+================
+*/
+void FS_Restart( int checksumFeed ) {
+
+ // free anything we currently have loaded
+ FS_Shutdown(qfalse);
+
+ // set the checksum feed
+ fs_checksumFeed = checksumFeed;
+
+ // clear pak references
+ FS_ClearPakReferences(0);
+
+ // try to start up normally
+ FS_Startup( BASEGAME );
+
+ // see if we are going to allow add-ons
+ FS_SetRestrictions();
+
+ // if we can't find default.cfg, assume that the paths are
+ // busted and error out now, rather than getting an unreadable
+ // graphics screen when the font fails to load
+ if ( FS_ReadFile( "default.cfg", NULL ) <= 0 ) {
+ // this might happen when connecting to a pure server not using BASEGAME/pak0.pk3
+ // (for instance a TA demo server)
+ if (lastValidBase[0]) {
+ FS_PureServerSetLoadedPaks("", "");
+ Cvar_Set("fs_basepath", lastValidBase);
+ Cvar_Set("fs_gamedirvar", lastValidGame);
+ lastValidBase[0] = '\0';
+ lastValidGame[0] = '\0';
+ Cvar_Set( "fs_restrict", "0" );
+ FS_Restart(checksumFeed);
+ Com_Error( ERR_DROP, "Invalid game folder\n" );
+ return;
+ }
+ Com_Error( ERR_FATAL, "Couldn't load default.cfg" );
+ }
+
+ // bk010116 - new check before safeMode
+ if ( Q_stricmp(fs_gamedirvar->string, lastValidGame) ) {
+ // skip the q3config.cfg if "safe" is on the command line
+ if ( !Com_SafeMode() ) {
+ Cbuf_AddText ("exec q3config.cfg\n");
+ }
+ }
+
+ Q_strncpyz(lastValidBase, fs_basepath->string, sizeof(lastValidBase));
+ Q_strncpyz(lastValidGame, fs_gamedirvar->string, sizeof(lastValidGame));
+
+}
+
+/*
+=================
+FS_ConditionalRestart
+restart if necessary
+=================
+*/
+qboolean FS_ConditionalRestart( int checksumFeed ) {
+ if( fs_gamedirvar->modified || checksumFeed != fs_checksumFeed ) {
+ FS_Restart( checksumFeed );
+ return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+========================================================================================
+
+Handle based file calls for virtual machines
+
+========================================================================================
+*/
+
+int FS_FOpenFileByMode( const char *qpath, fileHandle_t *f, fsMode_t mode ) {
+ int r;
+ qboolean sync;
+
+ sync = qfalse;
+
+ switch( mode ) {
+ case FS_READ:
+ r = FS_FOpenFileRead( qpath, f, qtrue );
+ break;
+ case FS_WRITE:
+ *f = FS_FOpenFileWrite( qpath );
+ r = 0;
+ if (*f == 0) {
+ r = -1;
+ }
+ break;
+ case FS_APPEND_SYNC:
+ sync = qtrue;
+ case FS_APPEND:
+ *f = FS_FOpenFileAppend( qpath );
+ r = 0;
+ if (*f == 0) {
+ r = -1;
+ }
+ break;
+ default:
+ Com_Error( ERR_FATAL, "FSH_FOpenFile: bad mode" );
+ return -1;
+ }
+
+ if (!f) {
+ return r;
+ }
+
+ if ( *f ) {
+ if (fsh[*f].zipFile == qtrue) {
+ fsh[*f].baseOffset = unztell(fsh[*f].handleFiles.file.z);
+ } else {
+ fsh[*f].baseOffset = ftell(fsh[*f].handleFiles.file.o);
+ }
+ fsh[*f].fileSize = r;
+ fsh[*f].streamed = qfalse;
+
+ if (mode == FS_READ) {
+ Sys_BeginStreamedFile( *f, 0x4000 );
+ fsh[*f].streamed = qtrue;
+ }
+ }
+ fsh[*f].handleSync = sync;
+
+ return r;
+}
+
+int FS_FTell( fileHandle_t f ) {
+ int pos;
+ if (fsh[f].zipFile == qtrue) {
+ pos = unztell(fsh[f].handleFiles.file.z);
+ } else {
+ pos = ftell(fsh[f].handleFiles.file.o);
+ }
+ return pos;
+}
+
+void FS_Flush( fileHandle_t f ) {
+ fflush(fsh[f].handleFiles.file.o);
+}
+
diff --git a/code/qcommon/huffman.c b/code/qcommon/huffman.c
new file mode 100755
index 0000000..da8f945
--- /dev/null
+++ b/code/qcommon/huffman.c
@@ -0,0 +1,437 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/* This is based on the Adaptive Huffman algorithm described in Sayood's Data
+ * Compression book. The ranks are not actually stored, but implicitly defined
+ * by the location of a node within a doubly-linked list */
+
+#include "../game/q_shared.h"
+#include "qcommon.h"
+
+static int bloc = 0;
+
+void Huff_putBit( int bit, byte *fout, int *offset) {
+ bloc = *offset;
+ if ((bloc&7) == 0) {
+ fout[(bloc>>3)] = 0;
+ }
+ fout[(bloc>>3)] |= bit << (bloc&7);
+ bloc++;
+ *offset = bloc;
+}
+
+int Huff_getBit( byte *fin, int *offset) {
+ int t;
+ bloc = *offset;
+ t = (fin[(bloc>>3)] >> (bloc&7)) & 0x1;
+ bloc++;
+ *offset = bloc;
+ return t;
+}
+
+/* Add a bit to the output file (buffered) */
+static void add_bit (char bit, byte *fout) {
+ if ((bloc&7) == 0) {
+ fout[(bloc>>3)] = 0;
+ }
+ fout[(bloc>>3)] |= bit << (bloc&7);
+ bloc++;
+}
+
+/* Receive one bit from the input file (buffered) */
+static int get_bit (byte *fin) {
+ int t;
+ t = (fin[(bloc>>3)] >> (bloc&7)) & 0x1;
+ bloc++;
+ return t;
+}
+
+static node_t **get_ppnode(huff_t* huff) {
+ node_t **tppnode;
+ if (!huff->freelist) {
+ return &(huff->nodePtrs[huff->blocPtrs++]);
+ } else {
+ tppnode = huff->freelist;
+ huff->freelist = (node_t **)*tppnode;
+ return tppnode;
+ }
+}
+
+static void free_ppnode(huff_t* huff, node_t **ppnode) {
+ *ppnode = (node_t *)huff->freelist;
+ huff->freelist = ppnode;
+}
+
+/* Swap the location of these two nodes in the tree */
+static void swap (huff_t* huff, node_t *node1, node_t *node2) {
+ node_t *par1, *par2;
+
+ par1 = node1->parent;
+ par2 = node2->parent;
+
+ if (par1) {
+ if (par1->left == node1) {
+ par1->left = node2;
+ } else {
+ par1->right = node2;
+ }
+ } else {
+ huff->tree = node2;
+ }
+
+ if (par2) {
+ if (par2->left == node2) {
+ par2->left = node1;
+ } else {
+ par2->right = node1;
+ }
+ } else {
+ huff->tree = node1;
+ }
+
+ node1->parent = par2;
+ node2->parent = par1;
+}
+
+/* Swap these two nodes in the linked list (update ranks) */
+static void swaplist(node_t *node1, node_t *node2) {
+ node_t *par1;
+
+ par1 = node1->next;
+ node1->next = node2->next;
+ node2->next = par1;
+
+ par1 = node1->prev;
+ node1->prev = node2->prev;
+ node2->prev = par1;
+
+ if (node1->next == node1) {
+ node1->next = node2;
+ }
+ if (node2->next == node2) {
+ node2->next = node1;
+ }
+ if (node1->next) {
+ node1->next->prev = node1;
+ }
+ if (node2->next) {
+ node2->next->prev = node2;
+ }
+ if (node1->prev) {
+ node1->prev->next = node1;
+ }
+ if (node2->prev) {
+ node2->prev->next = node2;
+ }
+}
+
+/* Do the increments */
+static void increment(huff_t* huff, node_t *node) {
+ node_t *lnode;
+
+ if (!node) {
+ return;
+ }
+
+ if (node->next != NULL && node->next->weight == node->weight) {
+ lnode = *node->head;
+ if (lnode != node->parent) {
+ swap(huff, lnode, node);
+ }
+ swaplist(lnode, node);
+ }
+ if (node->prev && node->prev->weight == node->weight) {
+ *node->head = node->prev;
+ } else {
+ *node->head = NULL;
+ free_ppnode(huff, node->head);
+ }
+ node->weight++;
+ if (node->next && node->next->weight == node->weight) {
+ node->head = node->next->head;
+ } else {
+ node->head = get_ppnode(huff);
+ *node->head = node;
+ }
+ if (node->parent) {
+ increment(huff, node->parent);
+ if (node->prev == node->parent) {
+ swaplist(node, node->parent);
+ if (*node->head == node) {
+ *node->head = node->parent;
+ }
+ }
+ }
+}
+
+void Huff_addRef(huff_t* huff, byte ch) {
+ node_t *tnode, *tnode2;
+ if (huff->loc[ch] == NULL) { /* if this is the first transmission of this node */
+ tnode = &(huff->nodeList[huff->blocNode++]);
+ tnode2 = &(huff->nodeList[huff->blocNode++]);
+
+ tnode2->symbol = INTERNAL_NODE;
+ tnode2->weight = 1;
+ tnode2->next = huff->lhead->next;
+ if (huff->lhead->next) {
+ huff->lhead->next->prev = tnode2;
+ if (huff->lhead->next->weight == 1) {
+ tnode2->head = huff->lhead->next->head;
+ } else {
+ tnode2->head = get_ppnode(huff);
+ *tnode2->head = tnode2;
+ }
+ } else {
+ tnode2->head = get_ppnode(huff);
+ *tnode2->head = tnode2;
+ }
+ huff->lhead->next = tnode2;
+ tnode2->prev = huff->lhead;
+
+ tnode->symbol = ch;
+ tnode->weight = 1;
+ tnode->next = huff->lhead->next;
+ if (huff->lhead->next) {
+ huff->lhead->next->prev = tnode;
+ if (huff->lhead->next->weight == 1) {
+ tnode->head = huff->lhead->next->head;
+ } else {
+ /* this should never happen */
+ tnode->head = get_ppnode(huff);
+ *tnode->head = tnode2;
+ }
+ } else {
+ /* this should never happen */
+ tnode->head = get_ppnode(huff);
+ *tnode->head = tnode;
+ }
+ huff->lhead->next = tnode;
+ tnode->prev = huff->lhead;
+ tnode->left = tnode->right = NULL;
+
+ if (huff->lhead->parent) {
+ if (huff->lhead->parent->left == huff->lhead) { /* lhead is guaranteed to by the NYT */
+ huff->lhead->parent->left = tnode2;
+ } else {
+ huff->lhead->parent->right = tnode2;
+ }
+ } else {
+ huff->tree = tnode2;
+ }
+
+ tnode2->right = tnode;
+ tnode2->left = huff->lhead;
+
+ tnode2->parent = huff->lhead->parent;
+ huff->lhead->parent = tnode->parent = tnode2;
+
+ huff->loc[ch] = tnode;
+
+ increment(huff, tnode2->parent);
+ } else {
+ increment(huff, huff->loc[ch]);
+ }
+}
+
+/* Get a symbol */
+int Huff_Receive (node_t *node, int *ch, byte *fin) {
+ while (node && node->symbol == INTERNAL_NODE) {
+ if (get_bit(fin)) {
+ node = node->right;
+ } else {
+ node = node->left;
+ }
+ }
+ if (!node) {
+ return 0;
+// Com_Error(ERR_DROP, "Illegal tree!\n");
+ }
+ return (*ch = node->symbol);
+}
+
+/* Get a symbol */
+void Huff_offsetReceive (node_t *node, int *ch, byte *fin, int *offset) {
+ bloc = *offset;
+ while (node && node->symbol == INTERNAL_NODE) {
+ if (get_bit(fin)) {
+ node = node->right;
+ } else {
+ node = node->left;
+ }
+ }
+ if (!node) {
+ *ch = 0;
+ return;
+// Com_Error(ERR_DROP, "Illegal tree!\n");
+ }
+ *ch = node->symbol;
+ *offset = bloc;
+}
+
+/* Send the prefix code for this node */
+static void send(node_t *node, node_t *child, byte *fout) {
+ if (node->parent) {
+ send(node->parent, node, fout);
+ }
+ if (child) {
+ if (node->right == child) {
+ add_bit(1, fout);
+ } else {
+ add_bit(0, fout);
+ }
+ }
+}
+
+/* Send a symbol */
+void Huff_transmit (huff_t *huff, int ch, byte *fout) {
+ int i;
+ if (huff->loc[ch] == NULL) {
+ /* node_t hasn't been transmitted, send a NYT, then the symbol */
+ Huff_transmit(huff, NYT, fout);
+ for (i = 7; i >= 0; i--) {
+ add_bit((char)((ch >> i) & 0x1), fout);
+ }
+ } else {
+ send(huff->loc[ch], NULL, fout);
+ }
+}
+
+void Huff_offsetTransmit (huff_t *huff, int ch, byte *fout, int *offset) {
+ bloc = *offset;
+ send(huff->loc[ch], NULL, fout);
+ *offset = bloc;
+}
+
+void Huff_Decompress(msg_t *mbuf, int offset) {
+ int ch, cch, i, j, size;
+ byte seq[65536];
+ byte* buffer;
+ huff_t huff;
+
+ size = mbuf->cursize - offset;
+ buffer = mbuf->data + offset;
+
+ if ( size <= 0 ) {
+ return;
+ }
+
+ Com_Memset(&huff, 0, sizeof(huff_t));
+ // Initialize the tree & list with the NYT node
+ huff.tree = huff.lhead = huff.ltail = huff.loc[NYT] = &(huff.nodeList[huff.blocNode++]);
+ huff.tree->symbol = NYT;
+ huff.tree->weight = 0;
+ huff.lhead->next = huff.lhead->prev = NULL;
+ huff.tree->parent = huff.tree->left = huff.tree->right = NULL;
+
+ cch = buffer[0]*256 + buffer[1];
+ // don't overflow with bad messages
+ if ( cch > mbuf->maxsize - offset ) {
+ cch = mbuf->maxsize - offset;
+ }
+ bloc = 16;
+
+ for ( j = 0; j < cch; j++ ) {
+ ch = 0;
+ // don't overflow reading from the messages
+ // FIXME: would it be better to have a overflow check in get_bit ?
+ if ( (bloc >> 3) > size ) {
+ seq[j] = 0;
+ break;
+ }
+ Huff_Receive(huff.tree, &ch, buffer); /* Get a character */
+ if ( ch == NYT ) { /* We got a NYT, get the symbol associated with it */
+ ch = 0;
+ for ( i = 0; i < 8; i++ ) {
+ ch = (ch<<1) + get_bit(buffer);
+ }
+ }
+
+ seq[j] = ch; /* Write symbol */
+
+ Huff_addRef(&huff, (byte)ch); /* Increment node */
+ }
+ mbuf->cursize = cch + offset;
+ Com_Memcpy(mbuf->data + offset, seq, cch);
+}
+
+extern int oldsize;
+
+void Huff_Compress(msg_t *mbuf, int offset) {
+ int i, ch, size;
+ byte seq[65536];
+ byte* buffer;
+ huff_t huff;
+
+ size = mbuf->cursize - offset;
+ buffer = mbuf->data+ + offset;
+
+ if (size<=0) {
+ return;
+ }
+
+ Com_Memset(&huff, 0, sizeof(huff_t));
+ // Add the NYT (not yet transmitted) node into the tree/list */
+ huff.tree = huff.lhead = huff.loc[NYT] = &(huff.nodeList[huff.blocNode++]);
+ huff.tree->symbol = NYT;
+ huff.tree->weight = 0;
+ huff.lhead->next = huff.lhead->prev = NULL;
+ huff.tree->parent = huff.tree->left = huff.tree->right = NULL;
+ huff.loc[NYT] = huff.tree;
+
+ seq[0] = (size>>8);
+ seq[1] = size&0xff;
+
+ bloc = 16;
+
+ for (i=0; i<size; i++ ) {
+ ch = buffer[i];
+ Huff_transmit(&huff, ch, seq); /* Transmit symbol */
+ Huff_addRef(&huff, (byte)ch); /* Do update */
+ }
+
+ bloc += 8; // next byte
+
+ mbuf->cursize = (bloc>>3) + offset;
+ Com_Memcpy(mbuf->data+offset, seq, (bloc>>3));
+}
+
+void Huff_Init(huffman_t *huff) {
+
+ Com_Memset(&huff->compressor, 0, sizeof(huff_t));
+ Com_Memset(&huff->decompressor, 0, sizeof(huff_t));
+
+ // Initialize the tree & list with the NYT node
+ huff->decompressor.tree = huff->decompressor.lhead = huff->decompressor.ltail = huff->decompressor.loc[NYT] = &(huff->decompressor.nodeList[huff->decompressor.blocNode++]);
+ huff->decompressor.tree->symbol = NYT;
+ huff->decompressor.tree->weight = 0;
+ huff->decompressor.lhead->next = huff->decompressor.lhead->prev = NULL;
+ huff->decompressor.tree->parent = huff->decompressor.tree->left = huff->decompressor.tree->right = NULL;
+
+ // Add the NYT (not yet transmitted) node into the tree/list */
+ huff->compressor.tree = huff->compressor.lhead = huff->compressor.loc[NYT] = &(huff->compressor.nodeList[huff->compressor.blocNode++]);
+ huff->compressor.tree->symbol = NYT;
+ huff->compressor.tree->weight = 0;
+ huff->compressor.lhead->next = huff->compressor.lhead->prev = NULL;
+ huff->compressor.tree->parent = huff->compressor.tree->left = huff->compressor.tree->right = NULL;
+ huff->compressor.loc[NYT] = huff->compressor.tree;
+}
+
diff --git a/code/qcommon/md4.c b/code/qcommon/md4.c
new file mode 100755
index 0000000..22fe320
--- /dev/null
+++ b/code/qcommon/md4.c
@@ -0,0 +1,299 @@
+/* GLOBAL.H - RSAREF types and constants */
+
+#include <string.h>
+#if defined(_WIN32)
+#pragma warning(disable : 4711) // selected for automatic inline expansion
+#endif
+
+/* POINTER defines a generic pointer type */
+typedef unsigned char *POINTER;
+
+/* UINT2 defines a two byte word */
+typedef unsigned short int UINT2;
+
+/* UINT4 defines a four byte word */
+typedef unsigned long int UINT4;
+
+
+/* MD4.H - header file for MD4C.C */
+
+/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991.
+
+All rights reserved.
+
+License to copy and use this software is granted provided that it is identified as the “RSA Data Security, Inc. MD4 Message-Digest Algorithm” in all material mentioning or referencing this software or this function.
+License is also granted to make and use derivative works provided that such works are identified as “derived from the RSA Data Security, Inc. MD4 Message-Digest Algorithm” in all material mentioning or referencing the derived work.
+RSA Data Security, Inc. makes no representations concerning either the merchantability of this software or the suitability of this software for any particular purpose. It is provided “as is” without express or implied warranty of any kind.
+
+These notices must be retained in any copies of any part of this documentation and/or software. */
+
+/* MD4 context. */
+typedef struct {
+ UINT4 state[4]; /* state (ABCD) */
+ UINT4 count[2]; /* number of bits, modulo 2^64 (lsb first) */
+ unsigned char buffer[64]; /* input buffer */
+} MD4_CTX;
+
+void MD4Init (MD4_CTX *);
+void MD4Update (MD4_CTX *, const unsigned char *, unsigned int);
+void MD4Final (unsigned char [16], MD4_CTX *);
+
+#ifndef __VECTORC
+void Com_Memset (void* dest, const int val, const size_t count);
+void Com_Memcpy (void* dest, const void* src, const size_t count);
+#else
+#define Com_Memset memset
+#define Com_Memcpy memcpy
+#endif
+
+/* MD4C.C - RSA Data Security, Inc., MD4 message-digest algorithm */
+/* Copyright (C) 1990-2, RSA Data Security, Inc. All rights reserved.
+
+License to copy and use this software is granted provided that it is identified as the
+RSA Data Security, Inc. MD4 Message-Digest Algorithm
+ in all material mentioning or referencing this software or this function.
+License is also granted to make and use derivative works provided that such works are identified as
+derived from the RSA Data Security, Inc. MD4 Message-Digest Algorithm
+in all material mentioning or referencing the derived work.
+RSA Data Security, Inc. makes no representations concerning either the merchantability of this software or the suitability of this software for any particular purpose. It is provided
+as is without express or implied warranty of any kind.
+
+These notices must be retained in any copies of any part of this documentation and/or software. */
+
+/* Constants for MD4Transform routine. */
+#define S11 3
+#define S12 7
+#define S13 11
+#define S14 19
+#define S21 3
+#define S22 5
+#define S23 9
+#define S24 13
+#define S31 3
+#define S32 9
+#define S33 11
+#define S34 15
+
+static void MD4Transform (UINT4 [4], const unsigned char [64]);
+static void Encode (unsigned char *, UINT4 *, unsigned int);
+static void Decode (UINT4 *, const unsigned char *, unsigned int);
+
+static unsigned char PADDING[64] = {
+0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+};
+
+/* F, G and H are basic MD4 functions. */
+#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
+#define G(x, y, z) (((x) & (y)) | ((x) & (z)) | ((y) & (z)))
+#define H(x, y, z) ((x) ^ (y) ^ (z))
+
+/* ROTATE_LEFT rotates x left n bits. */
+#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
+
+/* FF, GG and HH are transformations for rounds 1, 2 and 3 */
+/* Rotation is separate from addition to prevent recomputation */
+#define FF(a, b, c, d, x, s) {(a) += F ((b), (c), (d)) + (x); (a) = ROTATE_LEFT ((a), (s));}
+
+#define GG(a, b, c, d, x, s) {(a) += G ((b), (c), (d)) + (x) + (UINT4)0x5a827999; (a) = ROTATE_LEFT ((a), (s));}
+
+#define HH(a, b, c, d, x, s) {(a) += H ((b), (c), (d)) + (x) + (UINT4)0x6ed9eba1; (a) = ROTATE_LEFT ((a), (s));}
+
+
+/* MD4 initialization. Begins an MD4 operation, writing a new context. */
+void MD4Init (MD4_CTX *context)
+{
+ context->count[0] = context->count[1] = 0;
+
+/* Load magic initialization constants.*/
+context->state[0] = 0x67452301;
+context->state[1] = 0xefcdab89;
+context->state[2] = 0x98badcfe;
+context->state[3] = 0x10325476;
+}
+
+/* MD4 block update operation. Continues an MD4 message-digest operation, processing another message block, and updating the context. */
+void MD4Update (MD4_CTX *context, const unsigned char *input, unsigned int inputLen)
+{
+ unsigned int i, index, partLen;
+
+ /* Compute number of bytes mod 64 */
+ index = (unsigned int)((context->count[0] >> 3) & 0x3F);
+
+ /* Update number of bits */
+ if ((context->count[0] += ((UINT4)inputLen << 3))< ((UINT4)inputLen << 3))
+ context->count[1]++;
+
+ context->count[1] += ((UINT4)inputLen >> 29);
+
+ partLen = 64 - index;
+
+ /* Transform as many times as possible.*/
+ if (inputLen >= partLen)
+ {
+ Com_Memcpy((POINTER)&context->buffer[index], (POINTER)input, partLen);
+ MD4Transform (context->state, context->buffer);
+
+ for (i = partLen; i + 63 < inputLen; i += 64)
+ MD4Transform (context->state, &input[i]);
+
+ index = 0;
+ }
+ else
+ i = 0;
+
+ /* Buffer remaining input */
+ Com_Memcpy ((POINTER)&context->buffer[index], (POINTER)&input[i], inputLen-i);
+}
+
+
+/* MD4 finalization. Ends an MD4 message-digest operation, writing the the message digest and zeroizing the context. */
+void MD4Final (unsigned char digest[16], MD4_CTX *context)
+{
+ unsigned char bits[8];
+ unsigned int index, padLen;
+
+ /* Save number of bits */
+ Encode (bits, context->count, 8);
+
+ /* Pad out to 56 mod 64.*/
+ index = (unsigned int)((context->count[0] >> 3) & 0x3f);
+ padLen = (index < 56) ? (56 - index) : (120 - index);
+ MD4Update (context, PADDING, padLen);
+
+ /* Append length (before padding) */
+ MD4Update (context, bits, 8);
+
+ /* Store state in digest */
+ Encode (digest, context->state, 16);
+
+ /* Zeroize sensitive information.*/
+ Com_Memset ((POINTER)context, 0, sizeof (*context));
+}
+
+
+/* MD4 basic transformation. Transforms state based on block. */
+static void MD4Transform (UINT4 state[4], const unsigned char block[64])
+{
+ UINT4 a = state[0], b = state[1], c = state[2], d = state[3], x[16];
+
+ Decode (x, block, 64);
+
+/* Round 1 */
+FF (a, b, c, d, x[ 0], S11); /* 1 */
+FF (d, a, b, c, x[ 1], S12); /* 2 */
+FF (c, d, a, b, x[ 2], S13); /* 3 */
+FF (b, c, d, a, x[ 3], S14); /* 4 */
+FF (a, b, c, d, x[ 4], S11); /* 5 */
+FF (d, a, b, c, x[ 5], S12); /* 6 */
+FF (c, d, a, b, x[ 6], S13); /* 7 */
+FF (b, c, d, a, x[ 7], S14); /* 8 */
+FF (a, b, c, d, x[ 8], S11); /* 9 */
+FF (d, a, b, c, x[ 9], S12); /* 10 */
+FF (c, d, a, b, x[10], S13); /* 11 */
+FF (b, c, d, a, x[11], S14); /* 12 */
+FF (a, b, c, d, x[12], S11); /* 13 */
+FF (d, a, b, c, x[13], S12); /* 14 */
+FF (c, d, a, b, x[14], S13); /* 15 */
+FF (b, c, d, a, x[15], S14); /* 16 */
+
+/* Round 2 */
+GG (a, b, c, d, x[ 0], S21); /* 17 */
+GG (d, a, b, c, x[ 4], S22); /* 18 */
+GG (c, d, a, b, x[ 8], S23); /* 19 */
+GG (b, c, d, a, x[12], S24); /* 20 */
+GG (a, b, c, d, x[ 1], S21); /* 21 */
+GG (d, a, b, c, x[ 5], S22); /* 22 */
+GG (c, d, a, b, x[ 9], S23); /* 23 */
+GG (b, c, d, a, x[13], S24); /* 24 */
+GG (a, b, c, d, x[ 2], S21); /* 25 */
+GG (d, a, b, c, x[ 6], S22); /* 26 */
+GG (c, d, a, b, x[10], S23); /* 27 */
+GG (b, c, d, a, x[14], S24); /* 28 */
+GG (a, b, c, d, x[ 3], S21); /* 29 */
+GG (d, a, b, c, x[ 7], S22); /* 30 */
+GG (c, d, a, b, x[11], S23); /* 31 */
+GG (b, c, d, a, x[15], S24); /* 32 */
+
+/* Round 3 */
+HH (a, b, c, d, x[ 0], S31); /* 33 */
+HH (d, a, b, c, x[ 8], S32); /* 34 */
+HH (c, d, a, b, x[ 4], S33); /* 35 */
+HH (b, c, d, a, x[12], S34); /* 36 */
+HH (a, b, c, d, x[ 2], S31); /* 37 */
+HH (d, a, b, c, x[10], S32); /* 38 */
+HH (c, d, a, b, x[ 6], S33); /* 39 */
+HH (b, c, d, a, x[14], S34); /* 40 */
+HH (a, b, c, d, x[ 1], S31); /* 41 */
+HH (d, a, b, c, x[ 9], S32); /* 42 */
+HH (c, d, a, b, x[ 5], S33); /* 43 */
+HH (b, c, d, a, x[13], S34); /* 44 */
+HH (a, b, c, d, x[ 3], S31); /* 45 */
+HH (d, a, b, c, x[11], S32); /* 46 */
+HH (c, d, a, b, x[ 7], S33); /* 47 */
+HH (b, c, d, a, x[15], S34); /* 48 */
+
+state[0] += a;
+state[1] += b;
+state[2] += c;
+state[3] += d;
+
+ /* Zeroize sensitive information.*/
+ Com_Memset ((POINTER)x, 0, sizeof (x));
+}
+
+
+/* Encodes input (UINT4) into output (unsigned char). Assumes len is a multiple of 4. */
+static void Encode (unsigned char *output, UINT4 *input, unsigned int len)
+{
+ unsigned int i, j;
+
+ for (i = 0, j = 0; j < len; i++, j += 4) {
+ output[j] = (unsigned char)(input[i] & 0xff);
+ output[j+1] = (unsigned char)((input[i] >> 8) & 0xff);
+ output[j+2] = (unsigned char)((input[i] >> 16) & 0xff);
+ output[j+3] = (unsigned char)((input[i] >> 24) & 0xff);
+ }
+}
+
+
+/* Decodes input (unsigned char) into output (UINT4). Assumes len is a multiple of 4. */
+static void Decode (UINT4 *output, const unsigned char *input, unsigned int len)
+{
+unsigned int i, j;
+
+for (i = 0, j = 0; j < len; i++, j += 4)
+ output[i] = ((UINT4)input[j]) | (((UINT4)input[j+1]) << 8) | (((UINT4)input[j+2]) << 16) | (((UINT4)input[j+3]) << 24);
+}
+
+//===================================================================
+
+unsigned Com_BlockChecksum (void *buffer, int length)
+{
+ int digest[4];
+ unsigned val;
+ MD4_CTX ctx;
+
+ MD4Init (&ctx);
+ MD4Update (&ctx, (unsigned char *)buffer, length);
+ MD4Final ( (unsigned char *)digest, &ctx);
+
+ val = digest[0] ^ digest[1] ^ digest[2] ^ digest[3];
+
+ return val;
+}
+
+unsigned Com_BlockChecksumKey (void *buffer, int length, int key)
+{
+ int digest[4];
+ unsigned val;
+ MD4_CTX ctx;
+
+ MD4Init (&ctx);
+ MD4Update (&ctx, (unsigned char *)&key, 4);
+ MD4Update (&ctx, (unsigned char *)buffer, length);
+ MD4Final ( (unsigned char *)digest, &ctx);
+
+ val = digest[0] ^ digest[1] ^ digest[2] ^ digest[3];
+
+ return val;
+}
diff --git a/code/qcommon/msg.c b/code/qcommon/msg.c
new file mode 100755
index 0000000..27891cc
--- /dev/null
+++ b/code/qcommon/msg.c
@@ -0,0 +1,1757 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "../game/q_shared.h"
+#include "qcommon.h"
+
+static huffman_t msgHuff;
+
+static qboolean msgInit = qfalse;
+
+int pcount[256];
+
+/*
+==============================================================================
+
+ MESSAGE IO FUNCTIONS
+
+Handles byte ordering and avoids alignment errors
+==============================================================================
+*/
+
+int oldsize = 0;
+
+void MSG_initHuffman();
+
+void MSG_Init( msg_t *buf, byte *data, int length ) {
+ if (!msgInit) {
+ MSG_initHuffman();
+ }
+ Com_Memset (buf, 0, sizeof(*buf));
+ buf->data = data;
+ buf->maxsize = length;
+}
+
+void MSG_InitOOB( msg_t *buf, byte *data, int length ) {
+ if (!msgInit) {
+ MSG_initHuffman();
+ }
+ Com_Memset (buf, 0, sizeof(*buf));
+ buf->data = data;
+ buf->maxsize = length;
+ buf->oob = qtrue;
+}
+
+void MSG_Clear( msg_t *buf ) {
+ buf->cursize = 0;
+ buf->overflowed = qfalse;
+ buf->bit = 0; //<- in bits
+}
+
+
+void MSG_Bitstream( msg_t *buf ) {
+ buf->oob = qfalse;
+}
+
+void MSG_BeginReading( msg_t *msg ) {
+ msg->readcount = 0;
+ msg->bit = 0;
+ msg->oob = qfalse;
+}
+
+void MSG_BeginReadingOOB( msg_t *msg ) {
+ msg->readcount = 0;
+ msg->bit = 0;
+ msg->oob = qtrue;
+}
+
+void MSG_Copy(msg_t *buf, byte *data, int length, msg_t *src)
+{
+ if (length<src->cursize) {
+ Com_Error( ERR_DROP, "MSG_Copy: can't copy into a smaller msg_t buffer");
+ }
+ Com_Memcpy(buf, src, sizeof(msg_t));
+ buf->data = data;
+ Com_Memcpy(buf->data, src->data, src->cursize);
+}
+
+/*
+=============================================================================
+
+bit functions
+
+=============================================================================
+*/
+
+int overflows;
+
+// negative bit values include signs
+void MSG_WriteBits( msg_t *msg, int value, int bits ) {
+ int i;
+// FILE* fp;
+
+ oldsize += bits;
+
+ // this isn't an exact overflow check, but close enough
+ if ( msg->maxsize - msg->cursize < 4 ) {
+ msg->overflowed = qtrue;
+ return;
+ }
+
+ if ( bits == 0 || bits < -31 || bits > 32 ) {
+ Com_Error( ERR_DROP, "MSG_WriteBits: bad bits %i", bits );
+ }
+
+ // check for overflows
+ if ( bits != 32 ) {
+ if ( bits > 0 ) {
+ if ( value > ( ( 1 << bits ) - 1 ) || value < 0 ) {
+ overflows++;
+ }
+ } else {
+ int r;
+
+ r = 1 << (bits-1);
+
+ if ( value > r - 1 || value < -r ) {
+ overflows++;
+ }
+ }
+ }
+ if ( bits < 0 ) {
+ bits = -bits;
+ }
+ if (msg->oob) {
+ if (bits==8) {
+ msg->data[msg->cursize] = value;
+ msg->cursize += 1;
+ msg->bit += 8;
+ } else if (bits==16) {
+ unsigned short *sp = (unsigned short *)&msg->data[msg->cursize];
+ *sp = LittleShort(value);
+ msg->cursize += 2;
+ msg->bit += 16;
+ } else if (bits==32) {
+ unsigned int *ip = (unsigned int *)&msg->data[msg->cursize];
+ *ip = LittleLong(value);
+ msg->cursize += 4;
+ msg->bit += 8;
+ } else {
+ Com_Error(ERR_DROP, "can't read %d bits\n", bits);
+ }
+ } else {
+// fp = fopen("c:\\netchan.bin", "a");
+ value &= (0xffffffff>>(32-bits));
+ if (bits&7) {
+ int nbits;
+ nbits = bits&7;
+ for(i=0;i<nbits;i++) {
+ Huff_putBit((value&1), msg->data, &msg->bit);
+ value = (value>>1);
+ }
+ bits = bits - nbits;
+ }
+ if (bits) {
+ for(i=0;i<bits;i+=8) {
+// fwrite(bp, 1, 1, fp);
+ Huff_offsetTransmit (&msgHuff.compressor, (value&0xff), msg->data, &msg->bit);
+ value = (value>>8);
+ }
+ }
+ msg->cursize = (msg->bit>>3)+1;
+// fclose(fp);
+ }
+}
+
+int MSG_ReadBits( msg_t *msg, int bits ) {
+ int value;
+ int get;
+ qboolean sgn;
+ int i, nbits;
+// FILE* fp;
+
+ value = 0;
+
+ if ( bits < 0 ) {
+ bits = -bits;
+ sgn = qtrue;
+ } else {
+ sgn = qfalse;
+ }
+
+ if (msg->oob) {
+ if (bits==8) {
+ value = msg->data[msg->readcount];
+ msg->readcount += 1;
+ msg->bit += 8;
+ } else if (bits==16) {
+ unsigned short *sp = (unsigned short *)&msg->data[msg->readcount];
+ value = LittleShort(*sp);
+ msg->readcount += 2;
+ msg->bit += 16;
+ } else if (bits==32) {
+ unsigned int *ip = (unsigned int *)&msg->data[msg->readcount];
+ value = LittleLong(*ip);
+ msg->readcount += 4;
+ msg->bit += 32;
+ } else {
+ Com_Error(ERR_DROP, "can't read %d bits\n", bits);
+ }
+ } else {
+ nbits = 0;
+ if (bits&7) {
+ nbits = bits&7;
+ for(i=0;i<nbits;i++) {
+ value |= (Huff_getBit(msg->data, &msg->bit)<<i);
+ }
+ bits = bits - nbits;
+ }
+ if (bits) {
+// fp = fopen("c:\\netchan.bin", "a");
+ for(i=0;i<bits;i+=8) {
+ Huff_offsetReceive (msgHuff.decompressor.tree, &get, msg->data, &msg->bit);
+// fwrite(&get, 1, 1, fp);
+ value |= (get<<(i+nbits));
+ }
+// fclose(fp);
+ }
+ msg->readcount = (msg->bit>>3)+1;
+ }
+ if ( sgn ) {
+ if ( value & ( 1 << ( bits - 1 ) ) ) {
+ value |= -1 ^ ( ( 1 << bits ) - 1 );
+ }
+ }
+
+ return value;
+}
+
+
+
+//================================================================================
+
+//
+// writing functions
+//
+
+void MSG_WriteChar( msg_t *sb, int c ) {
+#ifdef PARANOID
+ if (c < -128 || c > 127)
+ Com_Error (ERR_FATAL, "MSG_WriteChar: range error");
+#endif
+
+ MSG_WriteBits( sb, c, 8 );
+}
+
+void MSG_WriteByte( msg_t *sb, int c ) {
+#ifdef PARANOID
+ if (c < 0 || c > 255)
+ Com_Error (ERR_FATAL, "MSG_WriteByte: range error");
+#endif
+
+ MSG_WriteBits( sb, c, 8 );
+}
+
+void MSG_WriteData( msg_t *buf, const void *data, int length ) {
+ int i;
+ for(i=0;i<length;i++) {
+ MSG_WriteByte(buf, ((byte *)data)[i]);
+ }
+}
+
+void MSG_WriteShort( msg_t *sb, int c ) {
+#ifdef PARANOID
+ if (c < ((short)0x8000) || c > (short)0x7fff)
+ Com_Error (ERR_FATAL, "MSG_WriteShort: range error");
+#endif
+
+ MSG_WriteBits( sb, c, 16 );
+}
+
+void MSG_WriteLong( msg_t *sb, int c ) {
+ MSG_WriteBits( sb, c, 32 );
+}
+
+void MSG_WriteFloat( msg_t *sb, float f ) {
+ union {
+ float f;
+ int l;
+ } dat;
+
+ dat.f = f;
+ MSG_WriteBits( sb, dat.l, 32 );
+}
+
+void MSG_WriteString( msg_t *sb, const char *s ) {
+ if ( !s ) {
+ MSG_WriteData (sb, "", 1);
+ } else {
+ int l,i;
+ char string[MAX_STRING_CHARS];
+
+ l = strlen( s );
+ if ( l >= MAX_STRING_CHARS ) {
+ Com_Printf( "MSG_WriteString: MAX_STRING_CHARS" );
+ MSG_WriteData (sb, "", 1);
+ return;
+ }
+ Q_strncpyz( string, s, sizeof( string ) );
+
+ // get rid of 0xff chars, because old clients don't like them
+ for ( i = 0 ; i < l ; i++ ) {
+ if ( ((byte *)string)[i] > 127 ) {
+ string[i] = '.';
+ }
+ }
+
+ MSG_WriteData (sb, string, l+1);
+ }
+}
+
+void MSG_WriteBigString( msg_t *sb, const char *s ) {
+ if ( !s ) {
+ MSG_WriteData (sb, "", 1);
+ } else {
+ int l,i;
+ char string[BIG_INFO_STRING];
+
+ l = strlen( s );
+ if ( l >= BIG_INFO_STRING ) {
+ Com_Printf( "MSG_WriteString: BIG_INFO_STRING" );
+ MSG_WriteData (sb, "", 1);
+ return;
+ }
+ Q_strncpyz( string, s, sizeof( string ) );
+
+ // get rid of 0xff chars, because old clients don't like them
+ for ( i = 0 ; i < l ; i++ ) {
+ if ( ((byte *)string)[i] > 127 ) {
+ string[i] = '.';
+ }
+ }
+
+ MSG_WriteData (sb, string, l+1);
+ }
+}
+
+void MSG_WriteAngle( msg_t *sb, float f ) {
+ MSG_WriteByte (sb, (int)(f*256/360) & 255);
+}
+
+void MSG_WriteAngle16( msg_t *sb, float f ) {
+ MSG_WriteShort (sb, ANGLE2SHORT(f));
+}
+
+
+//============================================================
+
+//
+// reading functions
+//
+
+// returns -1 if no more characters are available
+int MSG_ReadChar (msg_t *msg ) {
+ int c;
+
+ c = (signed char)MSG_ReadBits( msg, 8 );
+ if ( msg->readcount > msg->cursize ) {
+ c = -1;
+ }
+
+ return c;
+}
+
+int MSG_ReadByte( msg_t *msg ) {
+ int c;
+
+ c = (unsigned char)MSG_ReadBits( msg, 8 );
+ if ( msg->readcount > msg->cursize ) {
+ c = -1;
+ }
+ return c;
+}
+
+int MSG_ReadShort( msg_t *msg ) {
+ int c;
+
+ c = (short)MSG_ReadBits( msg, 16 );
+ if ( msg->readcount > msg->cursize ) {
+ c = -1;
+ }
+
+ return c;
+}
+
+int MSG_ReadLong( msg_t *msg ) {
+ int c;
+
+ c = MSG_ReadBits( msg, 32 );
+ if ( msg->readcount > msg->cursize ) {
+ c = -1;
+ }
+
+ return c;
+}
+
+float MSG_ReadFloat( msg_t *msg ) {
+ union {
+ byte b[4];
+ float f;
+ int l;
+ } dat;
+
+ dat.l = MSG_ReadBits( msg, 32 );
+ if ( msg->readcount > msg->cursize ) {
+ dat.f = -1;
+ }
+
+ return dat.f;
+}
+
+char *MSG_ReadString( msg_t *msg ) {
+ static char string[MAX_STRING_CHARS];
+ int l,c;
+
+ l = 0;
+ do {
+ c = MSG_ReadByte(msg); // use ReadByte so -1 is out of bounds
+ if ( c == -1 || c == 0 ) {
+ break;
+ }
+ // translate all fmt spec to avoid crash bugs
+ if ( c == '%' ) {
+ c = '.';
+ }
+ // don't allow higher ascii values
+ if ( c > 127 ) {
+ c = '.';
+ }
+
+ string[l] = c;
+ l++;
+ } while (l < sizeof(string)-1);
+
+ string[l] = 0;
+
+ return string;
+}
+
+char *MSG_ReadBigString( msg_t *msg ) {
+ static char string[BIG_INFO_STRING];
+ int l,c;
+
+ l = 0;
+ do {
+ c = MSG_ReadByte(msg); // use ReadByte so -1 is out of bounds
+ if ( c == -1 || c == 0 ) {
+ break;
+ }
+ // translate all fmt spec to avoid crash bugs
+ if ( c == '%' ) {
+ c = '.';
+ }
+
+ string[l] = c;
+ l++;
+ } while (l < sizeof(string)-1);
+
+ string[l] = 0;
+
+ return string;
+}
+
+char *MSG_ReadStringLine( msg_t *msg ) {
+ static char string[MAX_STRING_CHARS];
+ int l,c;
+
+ l = 0;
+ do {
+ c = MSG_ReadByte(msg); // use ReadByte so -1 is out of bounds
+ if (c == -1 || c == 0 || c == '\n') {
+ break;
+ }
+ // translate all fmt spec to avoid crash bugs
+ if ( c == '%' ) {
+ c = '.';
+ }
+ string[l] = c;
+ l++;
+ } while (l < sizeof(string)-1);
+
+ string[l] = 0;
+
+ return string;
+}
+
+float MSG_ReadAngle16( msg_t *msg ) {
+ return SHORT2ANGLE(MSG_ReadShort(msg));
+}
+
+void MSG_ReadData( msg_t *msg, void *data, int len ) {
+ int i;
+
+ for (i=0 ; i<len ; i++) {
+ ((byte *)data)[i] = MSG_ReadByte (msg);
+ }
+}
+
+
+/*
+=============================================================================
+
+delta functions
+
+=============================================================================
+*/
+
+extern cvar_t *cl_shownet;
+
+#define LOG(x) if( cl_shownet->integer == 4 ) { Com_Printf("%s ", x ); };
+
+void MSG_WriteDelta( msg_t *msg, int oldV, int newV, int bits ) {
+ if ( oldV == newV ) {
+ MSG_WriteBits( msg, 0, 1 );
+ return;
+ }
+ MSG_WriteBits( msg, 1, 1 );
+ MSG_WriteBits( msg, newV, bits );
+}
+
+int MSG_ReadDelta( msg_t *msg, int oldV, int bits ) {
+ if ( MSG_ReadBits( msg, 1 ) ) {
+ return MSG_ReadBits( msg, bits );
+ }
+ return oldV;
+}
+
+void MSG_WriteDeltaFloat( msg_t *msg, float oldV, float newV ) {
+ if ( oldV == newV ) {
+ MSG_WriteBits( msg, 0, 1 );
+ return;
+ }
+ MSG_WriteBits( msg, 1, 1 );
+ MSG_WriteBits( msg, *(int *)&newV, 32 );
+}
+
+float MSG_ReadDeltaFloat( msg_t *msg, float oldV ) {
+ if ( MSG_ReadBits( msg, 1 ) ) {
+ float newV;
+
+ *(int *)&newV = MSG_ReadBits( msg, 32 );
+ return newV;
+ }
+ return oldV;
+}
+
+/*
+=============================================================================
+
+delta functions with keys
+
+=============================================================================
+*/
+
+int kbitmask[32] = {
+ 0x00000001, 0x00000003, 0x00000007, 0x0000000F,
+ 0x0000001F, 0x0000003F, 0x0000007F, 0x000000FF,
+ 0x000001FF, 0x000003FF, 0x000007FF, 0x00000FFF,
+ 0x00001FFF, 0x00003FFF, 0x00007FFF, 0x0000FFFF,
+ 0x0001FFFF, 0x0003FFFF, 0x0007FFFF, 0x000FFFFF,
+ 0x001FFFFf, 0x003FFFFF, 0x007FFFFF, 0x00FFFFFF,
+ 0x01FFFFFF, 0x03FFFFFF, 0x07FFFFFF, 0x0FFFFFFF,
+ 0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF, 0xFFFFFFFF,
+};
+
+void MSG_WriteDeltaKey( msg_t *msg, int key, int oldV, int newV, int bits ) {
+ if ( oldV == newV ) {
+ MSG_WriteBits( msg, 0, 1 );
+ return;
+ }
+ MSG_WriteBits( msg, 1, 1 );
+ MSG_WriteBits( msg, newV ^ key, bits );
+}
+
+int MSG_ReadDeltaKey( msg_t *msg, int key, int oldV, int bits ) {
+ if ( MSG_ReadBits( msg, 1 ) ) {
+ return MSG_ReadBits( msg, bits ) ^ (key & kbitmask[bits]);
+ }
+ return oldV;
+}
+
+void MSG_WriteDeltaKeyFloat( msg_t *msg, int key, float oldV, float newV ) {
+ if ( oldV == newV ) {
+ MSG_WriteBits( msg, 0, 1 );
+ return;
+ }
+ MSG_WriteBits( msg, 1, 1 );
+ MSG_WriteBits( msg, (*(int *)&newV) ^ key, 32 );
+}
+
+float MSG_ReadDeltaKeyFloat( msg_t *msg, int key, float oldV ) {
+ if ( MSG_ReadBits( msg, 1 ) ) {
+ float newV;
+
+ *(int *)&newV = MSG_ReadBits( msg, 32 ) ^ key;
+ return newV;
+ }
+ return oldV;
+}
+
+
+/*
+============================================================================
+
+usercmd_t communication
+
+============================================================================
+*/
+
+// ms is allways sent, the others are optional
+#define CM_ANGLE1 (1<<0)
+#define CM_ANGLE2 (1<<1)
+#define CM_ANGLE3 (1<<2)
+#define CM_FORWARD (1<<3)
+#define CM_SIDE (1<<4)
+#define CM_UP (1<<5)
+#define CM_BUTTONS (1<<6)
+#define CM_WEAPON (1<<7)
+
+/*
+=====================
+MSG_WriteDeltaUsercmd
+=====================
+*/
+void MSG_WriteDeltaUsercmd( msg_t *msg, usercmd_t *from, usercmd_t *to ) {
+ if ( to->serverTime - from->serverTime < 256 ) {
+ MSG_WriteBits( msg, 1, 1 );
+ MSG_WriteBits( msg, to->serverTime - from->serverTime, 8 );
+ } else {
+ MSG_WriteBits( msg, 0, 1 );
+ MSG_WriteBits( msg, to->serverTime, 32 );
+ }
+ MSG_WriteDelta( msg, from->angles[0], to->angles[0], 16 );
+ MSG_WriteDelta( msg, from->angles[1], to->angles[1], 16 );
+ MSG_WriteDelta( msg, from->angles[2], to->angles[2], 16 );
+ MSG_WriteDelta( msg, from->forwardmove, to->forwardmove, 8 );
+ MSG_WriteDelta( msg, from->rightmove, to->rightmove, 8 );
+ MSG_WriteDelta( msg, from->upmove, to->upmove, 8 );
+ MSG_WriteDelta( msg, from->buttons, to->buttons, 16 );
+ MSG_WriteDelta( msg, from->weapon, to->weapon, 8 );
+}
+
+
+/*
+=====================
+MSG_ReadDeltaUsercmd
+=====================
+*/
+void MSG_ReadDeltaUsercmd( msg_t *msg, usercmd_t *from, usercmd_t *to ) {
+ if ( MSG_ReadBits( msg, 1 ) ) {
+ to->serverTime = from->serverTime + MSG_ReadBits( msg, 8 );
+ } else {
+ to->serverTime = MSG_ReadBits( msg, 32 );
+ }
+ to->angles[0] = MSG_ReadDelta( msg, from->angles[0], 16);
+ to->angles[1] = MSG_ReadDelta( msg, from->angles[1], 16);
+ to->angles[2] = MSG_ReadDelta( msg, from->angles[2], 16);
+ to->forwardmove = MSG_ReadDelta( msg, from->forwardmove, 8);
+ to->rightmove = MSG_ReadDelta( msg, from->rightmove, 8);
+ to->upmove = MSG_ReadDelta( msg, from->upmove, 8);
+ to->buttons = MSG_ReadDelta( msg, from->buttons, 16);
+ to->weapon = MSG_ReadDelta( msg, from->weapon, 8);
+}
+
+/*
+=====================
+MSG_WriteDeltaUsercmd
+=====================
+*/
+void MSG_WriteDeltaUsercmdKey( msg_t *msg, int key, usercmd_t *from, usercmd_t *to ) {
+ if ( to->serverTime - from->serverTime < 256 ) {
+ MSG_WriteBits( msg, 1, 1 );
+ MSG_WriteBits( msg, to->serverTime - from->serverTime, 8 );
+ } else {
+ MSG_WriteBits( msg, 0, 1 );
+ MSG_WriteBits( msg, to->serverTime, 32 );
+ }
+ if (from->angles[0] == to->angles[0] &&
+ from->angles[1] == to->angles[1] &&
+ from->angles[2] == to->angles[2] &&
+ from->forwardmove == to->forwardmove &&
+ from->rightmove == to->rightmove &&
+ from->upmove == to->upmove &&
+ from->buttons == to->buttons &&
+ from->weapon == to->weapon) {
+ MSG_WriteBits( msg, 0, 1 ); // no change
+ oldsize += 7;
+ return;
+ }
+ key ^= to->serverTime;
+ MSG_WriteBits( msg, 1, 1 );
+ MSG_WriteDeltaKey( msg, key, from->angles[0], to->angles[0], 16 );
+ MSG_WriteDeltaKey( msg, key, from->angles[1], to->angles[1], 16 );
+ MSG_WriteDeltaKey( msg, key, from->angles[2], to->angles[2], 16 );
+ MSG_WriteDeltaKey( msg, key, from->forwardmove, to->forwardmove, 8 );
+ MSG_WriteDeltaKey( msg, key, from->rightmove, to->rightmove, 8 );
+ MSG_WriteDeltaKey( msg, key, from->upmove, to->upmove, 8 );
+ MSG_WriteDeltaKey( msg, key, from->buttons, to->buttons, 16 );
+ MSG_WriteDeltaKey( msg, key, from->weapon, to->weapon, 8 );
+}
+
+
+/*
+=====================
+MSG_ReadDeltaUsercmd
+=====================
+*/
+void MSG_ReadDeltaUsercmdKey( msg_t *msg, int key, usercmd_t *from, usercmd_t *to ) {
+ if ( MSG_ReadBits( msg, 1 ) ) {
+ to->serverTime = from->serverTime + MSG_ReadBits( msg, 8 );
+ } else {
+ to->serverTime = MSG_ReadBits( msg, 32 );
+ }
+ if ( MSG_ReadBits( msg, 1 ) ) {
+ key ^= to->serverTime;
+ to->angles[0] = MSG_ReadDeltaKey( msg, key, from->angles[0], 16);
+ to->angles[1] = MSG_ReadDeltaKey( msg, key, from->angles[1], 16);
+ to->angles[2] = MSG_ReadDeltaKey( msg, key, from->angles[2], 16);
+ to->forwardmove = MSG_ReadDeltaKey( msg, key, from->forwardmove, 8);
+ to->rightmove = MSG_ReadDeltaKey( msg, key, from->rightmove, 8);
+ to->upmove = MSG_ReadDeltaKey( msg, key, from->upmove, 8);
+ to->buttons = MSG_ReadDeltaKey( msg, key, from->buttons, 16);
+ to->weapon = MSG_ReadDeltaKey( msg, key, from->weapon, 8);
+ } else {
+ to->angles[0] = from->angles[0];
+ to->angles[1] = from->angles[1];
+ to->angles[2] = from->angles[2];
+ to->forwardmove = from->forwardmove;
+ to->rightmove = from->rightmove;
+ to->upmove = from->upmove;
+ to->buttons = from->buttons;
+ to->weapon = from->weapon;
+ }
+}
+
+/*
+=============================================================================
+
+entityState_t communication
+
+=============================================================================
+*/
+
+/*
+=================
+MSG_ReportChangeVectors_f
+
+Prints out a table from the current statistics for copying to code
+=================
+*/
+void MSG_ReportChangeVectors_f( void ) {
+ int i;
+ for(i=0;i<256;i++) {
+ if (pcount[i]) {
+ Com_Printf("%d used %d\n", i, pcount[i]);
+ }
+ }
+}
+
+typedef struct {
+ char *name;
+ int offset;
+ int bits; // 0 = float
+} netField_t;
+
+// using the stringizing operator to save typing...
+#define NETF(x) #x,(int)&((entityState_t*)0)->x
+
+netField_t entityStateFields[] =
+{
+{ NETF(pos.trTime), 32 },
+{ NETF(pos.trBase[0]), 0 },
+{ NETF(pos.trBase[1]), 0 },
+{ NETF(pos.trDelta[0]), 0 },
+{ NETF(pos.trDelta[1]), 0 },
+{ NETF(pos.trBase[2]), 0 },
+{ NETF(apos.trBase[1]), 0 },
+{ NETF(pos.trDelta[2]), 0 },
+{ NETF(apos.trBase[0]), 0 },
+{ NETF(event), 10 },
+{ NETF(angles2[1]), 0 },
+{ NETF(eType), 8 },
+{ NETF(torsoAnim), 8 },
+{ NETF(eventParm), 8 },
+{ NETF(legsAnim), 8 },
+{ NETF(groundEntityNum), GENTITYNUM_BITS },
+{ NETF(pos.trType), 8 },
+{ NETF(eFlags), 19 },
+{ NETF(otherEntityNum), GENTITYNUM_BITS },
+{ NETF(weapon), 8 },
+{ NETF(clientNum), 8 },
+{ NETF(angles[1]), 0 },
+{ NETF(pos.trDuration), 32 },
+{ NETF(apos.trType), 8 },
+{ NETF(origin[0]), 0 },
+{ NETF(origin[1]), 0 },
+{ NETF(origin[2]), 0 },
+{ NETF(solid), 24 },
+{ NETF(powerups), 16 },
+{ NETF(modelindex), 8 },
+{ NETF(otherEntityNum2), GENTITYNUM_BITS },
+{ NETF(loopSound), 8 },
+{ NETF(generic1), 8 },
+{ NETF(origin2[2]), 0 },
+{ NETF(origin2[0]), 0 },
+{ NETF(origin2[1]), 0 },
+{ NETF(modelindex2), 8 },
+{ NETF(angles[0]), 0 },
+{ NETF(time), 32 },
+{ NETF(apos.trTime), 32 },
+{ NETF(apos.trDuration), 32 },
+{ NETF(apos.trBase[2]), 0 },
+{ NETF(apos.trDelta[0]), 0 },
+{ NETF(apos.trDelta[1]), 0 },
+{ NETF(apos.trDelta[2]), 0 },
+{ NETF(time2), 32 },
+{ NETF(angles[2]), 0 },
+{ NETF(angles2[0]), 0 },
+{ NETF(angles2[2]), 0 },
+{ NETF(constantLight), 32 },
+{ NETF(frame), 16 }
+};
+
+
+// if (int)f == f and (int)f + ( 1<<(FLOAT_INT_BITS-1) ) < ( 1 << FLOAT_INT_BITS )
+// the float will be sent with FLOAT_INT_BITS, otherwise all 32 bits will be sent
+#define FLOAT_INT_BITS 13
+#define FLOAT_INT_BIAS (1<<(FLOAT_INT_BITS-1))
+
+/*
+==================
+MSG_WriteDeltaEntity
+
+Writes part of a packetentities message, including the entity number.
+Can delta from either a baseline or a previous packet_entity
+If to is NULL, a remove entity update will be sent
+If force is not set, then nothing at all will be generated if the entity is
+identical, under the assumption that the in-order delta code will catch it.
+==================
+*/
+void MSG_WriteDeltaEntity( msg_t *msg, struct entityState_s *from, struct entityState_s *to,
+ qboolean force ) {
+ int i, lc;
+ int numFields;
+ netField_t *field;
+ int trunc;
+ float fullFloat;
+ int *fromF, *toF;
+
+ numFields = sizeof(entityStateFields)/sizeof(entityStateFields[0]);
+
+ // all fields should be 32 bits to avoid any compiler packing issues
+ // the "number" field is not part of the field list
+ // if this assert fails, someone added a field to the entityState_t
+ // struct without updating the message fields
+ assert( numFields + 1 == sizeof( *from )/4 );
+
+ // a NULL to is a delta remove message
+ if ( to == NULL ) {
+ if ( from == NULL ) {
+ return;
+ }
+ MSG_WriteBits( msg, from->number, GENTITYNUM_BITS );
+ MSG_WriteBits( msg, 1, 1 );
+ return;
+ }
+
+ if ( to->number < 0 || to->number >= MAX_GENTITIES ) {
+ Com_Error (ERR_FATAL, "MSG_WriteDeltaEntity: Bad entity number: %i", to->number );
+ }
+
+ lc = 0;
+ // build the change vector as bytes so it is endien independent
+ for ( i = 0, field = entityStateFields ; i < numFields ; i++, field++ ) {
+ fromF = (int *)( (byte *)from + field->offset );
+ toF = (int *)( (byte *)to + field->offset );
+ if ( *fromF != *toF ) {
+ lc = i+1;
+ }
+ }
+
+ if ( lc == 0 ) {
+ // nothing at all changed
+ if ( !force ) {
+ return; // nothing at all
+ }
+ // write two bits for no change
+ MSG_WriteBits( msg, to->number, GENTITYNUM_BITS );
+ MSG_WriteBits( msg, 0, 1 ); // not removed
+ MSG_WriteBits( msg, 0, 1 ); // no delta
+ return;
+ }
+
+ MSG_WriteBits( msg, to->number, GENTITYNUM_BITS );
+ MSG_WriteBits( msg, 0, 1 ); // not removed
+ MSG_WriteBits( msg, 1, 1 ); // we have a delta
+
+ MSG_WriteByte( msg, lc ); // # of changes
+
+ oldsize += numFields;
+
+ for ( i = 0, field = entityStateFields ; i < lc ; i++, field++ ) {
+ fromF = (int *)( (byte *)from + field->offset );
+ toF = (int *)( (byte *)to + field->offset );
+
+ if ( *fromF == *toF ) {
+ MSG_WriteBits( msg, 0, 1 ); // no change
+ continue;
+ }
+
+ MSG_WriteBits( msg, 1, 1 ); // changed
+
+ if ( field->bits == 0 ) {
+ // float
+ fullFloat = *(float *)toF;
+ trunc = (int)fullFloat;
+
+ if (fullFloat == 0.0f) {
+ MSG_WriteBits( msg, 0, 1 );
+ oldsize += FLOAT_INT_BITS;
+ } else {
+ MSG_WriteBits( msg, 1, 1 );
+ if ( trunc == fullFloat && trunc + FLOAT_INT_BIAS >= 0 &&
+ trunc + FLOAT_INT_BIAS < ( 1 << FLOAT_INT_BITS ) ) {
+ // send as small integer
+ MSG_WriteBits( msg, 0, 1 );
+ MSG_WriteBits( msg, trunc + FLOAT_INT_BIAS, FLOAT_INT_BITS );
+ } else {
+ // send as full floating point value
+ MSG_WriteBits( msg, 1, 1 );
+ MSG_WriteBits( msg, *toF, 32 );
+ }
+ }
+ } else {
+ if (*toF == 0) {
+ MSG_WriteBits( msg, 0, 1 );
+ } else {
+ MSG_WriteBits( msg, 1, 1 );
+ // integer
+ MSG_WriteBits( msg, *toF, field->bits );
+ }
+ }
+ }
+}
+
+/*
+==================
+MSG_ReadDeltaEntity
+
+The entity number has already been read from the message, which
+is how the from state is identified.
+
+If the delta removes the entity, entityState_t->number will be set to MAX_GENTITIES-1
+
+Can go from either a baseline or a previous packet_entity
+==================
+*/
+extern cvar_t *cl_shownet;
+
+void MSG_ReadDeltaEntity( msg_t *msg, entityState_t *from, entityState_t *to,
+ int number) {
+ int i, lc;
+ int numFields;
+ netField_t *field;
+ int *fromF, *toF;
+ int print;
+ int trunc;
+ int startBit, endBit;
+
+ if ( number < 0 || number >= MAX_GENTITIES) {
+ Com_Error( ERR_DROP, "Bad delta entity number: %i", number );
+ }
+
+ if ( msg->bit == 0 ) {
+ startBit = msg->readcount * 8 - GENTITYNUM_BITS;
+ } else {
+ startBit = ( msg->readcount - 1 ) * 8 + msg->bit - GENTITYNUM_BITS;
+ }
+
+ // check for a remove
+ if ( MSG_ReadBits( msg, 1 ) == 1 ) {
+ Com_Memset( to, 0, sizeof( *to ) );
+ to->number = MAX_GENTITIES - 1;
+ if ( cl_shownet->integer >= 2 || cl_shownet->integer == -1 ) {
+ Com_Printf( "%3i: #%-3i remove\n", msg->readcount, number );
+ }
+ return;
+ }
+
+ // check for no delta
+ if ( MSG_ReadBits( msg, 1 ) == 0 ) {
+ *to = *from;
+ to->number = number;
+ return;
+ }
+
+ numFields = sizeof(entityStateFields)/sizeof(entityStateFields[0]);
+ lc = MSG_ReadByte(msg);
+
+ // shownet 2/3 will interleave with other printed info, -1 will
+ // just print the delta records`
+ if ( cl_shownet->integer >= 2 || cl_shownet->integer == -1 ) {
+ print = 1;
+ Com_Printf( "%3i: #%-3i ", msg->readcount, to->number );
+ } else {
+ print = 0;
+ }
+
+ to->number = number;
+
+ for ( i = 0, field = entityStateFields ; i < lc ; i++, field++ ) {
+ fromF = (int *)( (byte *)from + field->offset );
+ toF = (int *)( (byte *)to + field->offset );
+
+ if ( ! MSG_ReadBits( msg, 1 ) ) {
+ // no change
+ *toF = *fromF;
+ } else {
+ if ( field->bits == 0 ) {
+ // float
+ if ( MSG_ReadBits( msg, 1 ) == 0 ) {
+ *(float *)toF = 0.0f;
+ } else {
+ if ( MSG_ReadBits( msg, 1 ) == 0 ) {
+ // integral float
+ trunc = MSG_ReadBits( msg, FLOAT_INT_BITS );
+ // bias to allow equal parts positive and negative
+ trunc -= FLOAT_INT_BIAS;
+ *(float *)toF = trunc;
+ if ( print ) {
+ Com_Printf( "%s:%i ", field->name, trunc );
+ }
+ } else {
+ // full floating point value
+ *toF = MSG_ReadBits( msg, 32 );
+ if ( print ) {
+ Com_Printf( "%s:%f ", field->name, *(float *)toF );
+ }
+ }
+ }
+ } else {
+ if ( MSG_ReadBits( msg, 1 ) == 0 ) {
+ *toF = 0;
+ } else {
+ // integer
+ *toF = MSG_ReadBits( msg, field->bits );
+ if ( print ) {
+ Com_Printf( "%s:%i ", field->name, *toF );
+ }
+ }
+ }
+// pcount[i]++;
+ }
+ }
+ for ( i = lc, field = &entityStateFields[lc] ; i < numFields ; i++, field++ ) {
+ fromF = (int *)( (byte *)from + field->offset );
+ toF = (int *)( (byte *)to + field->offset );
+ // no change
+ *toF = *fromF;
+ }
+
+ if ( print ) {
+ if ( msg->bit == 0 ) {
+ endBit = msg->readcount * 8 - GENTITYNUM_BITS;
+ } else {
+ endBit = ( msg->readcount - 1 ) * 8 + msg->bit - GENTITYNUM_BITS;
+ }
+ Com_Printf( " (%i bits)\n", endBit - startBit );
+ }
+}
+
+
+/*
+============================================================================
+
+plyer_state_t communication
+
+============================================================================
+*/
+
+// using the stringizing operator to save typing...
+#define PSF(x) #x,(int)&((playerState_t*)0)->x
+
+netField_t playerStateFields[] =
+{
+{ PSF(commandTime), 32 },
+{ PSF(origin[0]), 0 },
+{ PSF(origin[1]), 0 },
+{ PSF(bobCycle), 8 },
+{ PSF(velocity[0]), 0 },
+{ PSF(velocity[1]), 0 },
+{ PSF(viewangles[1]), 0 },
+{ PSF(viewangles[0]), 0 },
+{ PSF(weaponTime), -16 },
+{ PSF(origin[2]), 0 },
+{ PSF(velocity[2]), 0 },
+{ PSF(legsTimer), 8 },
+{ PSF(pm_time), -16 },
+{ PSF(eventSequence), 16 },
+{ PSF(torsoAnim), 8 },
+{ PSF(movementDir), 4 },
+{ PSF(events[0]), 8 },
+{ PSF(legsAnim), 8 },
+{ PSF(events[1]), 8 },
+{ PSF(pm_flags), 16 },
+{ PSF(groundEntityNum), GENTITYNUM_BITS },
+{ PSF(weaponstate), 4 },
+{ PSF(eFlags), 16 },
+{ PSF(externalEvent), 10 },
+{ PSF(gravity), 16 },
+{ PSF(speed), 16 },
+{ PSF(delta_angles[1]), 16 },
+{ PSF(externalEventParm), 8 },
+{ PSF(viewheight), -8 },
+{ PSF(damageEvent), 8 },
+{ PSF(damageYaw), 8 },
+{ PSF(damagePitch), 8 },
+{ PSF(damageCount), 8 },
+{ PSF(generic1), 8 },
+{ PSF(pm_type), 8 },
+{ PSF(delta_angles[0]), 16 },
+{ PSF(delta_angles[2]), 16 },
+{ PSF(torsoTimer), 12 },
+{ PSF(eventParms[0]), 8 },
+{ PSF(eventParms[1]), 8 },
+{ PSF(clientNum), 8 },
+{ PSF(weapon), 5 },
+{ PSF(viewangles[2]), 0 },
+{ PSF(grapplePoint[0]), 0 },
+{ PSF(grapplePoint[1]), 0 },
+{ PSF(grapplePoint[2]), 0 },
+{ PSF(jumppad_ent), 10 },
+{ PSF(loopSound), 16 }
+};
+
+/*
+=============
+MSG_WriteDeltaPlayerstate
+
+=============
+*/
+void MSG_WriteDeltaPlayerstate( msg_t *msg, struct playerState_s *from, struct playerState_s *to ) {
+ int i;
+ playerState_t dummy;
+ int statsbits;
+ int persistantbits;
+ int ammobits;
+ int powerupbits;
+ int numFields;
+ int c;
+ netField_t *field;
+ int *fromF, *toF;
+ float fullFloat;
+ int trunc, lc;
+
+ if (!from) {
+ from = &dummy;
+ Com_Memset (&dummy, 0, sizeof(dummy));
+ }
+
+ c = msg->cursize;
+
+ numFields = sizeof( playerStateFields ) / sizeof( playerStateFields[0] );
+
+ lc = 0;
+ for ( i = 0, field = playerStateFields ; i < numFields ; i++, field++ ) {
+ fromF = (int *)( (byte *)from + field->offset );
+ toF = (int *)( (byte *)to + field->offset );
+ if ( *fromF != *toF ) {
+ lc = i+1;
+ }
+ }
+
+ MSG_WriteByte( msg, lc ); // # of changes
+
+ oldsize += numFields - lc;
+
+ for ( i = 0, field = playerStateFields ; i < lc ; i++, field++ ) {
+ fromF = (int *)( (byte *)from + field->offset );
+ toF = (int *)( (byte *)to + field->offset );
+
+ if ( *fromF == *toF ) {
+ MSG_WriteBits( msg, 0, 1 ); // no change
+ continue;
+ }
+
+ MSG_WriteBits( msg, 1, 1 ); // changed
+// pcount[i]++;
+
+ if ( field->bits == 0 ) {
+ // float
+ fullFloat = *(float *)toF;
+ trunc = (int)fullFloat;
+
+ if ( trunc == fullFloat && trunc + FLOAT_INT_BIAS >= 0 &&
+ trunc + FLOAT_INT_BIAS < ( 1 << FLOAT_INT_BITS ) ) {
+ // send as small integer
+ MSG_WriteBits( msg, 0, 1 );
+ MSG_WriteBits( msg, trunc + FLOAT_INT_BIAS, FLOAT_INT_BITS );
+ } else {
+ // send as full floating point value
+ MSG_WriteBits( msg, 1, 1 );
+ MSG_WriteBits( msg, *toF, 32 );
+ }
+ } else {
+ // integer
+ MSG_WriteBits( msg, *toF, field->bits );
+ }
+ }
+ c = msg->cursize - c;
+
+
+ //
+ // send the arrays
+ //
+ statsbits = 0;
+ for (i=0 ; i<16 ; i++) {
+ if (to->stats[i] != from->stats[i]) {
+ statsbits |= 1<<i;
+ }
+ }
+ persistantbits = 0;
+ for (i=0 ; i<16 ; i++) {
+ if (to->persistant[i] != from->persistant[i]) {
+ persistantbits |= 1<<i;
+ }
+ }
+ ammobits = 0;
+ for (i=0 ; i<16 ; i++) {
+ if (to->ammo[i] != from->ammo[i]) {
+ ammobits |= 1<<i;
+ }
+ }
+ powerupbits = 0;
+ for (i=0 ; i<16 ; i++) {
+ if (to->powerups[i] != from->powerups[i]) {
+ powerupbits |= 1<<i;
+ }
+ }
+
+ if (!statsbits && !persistantbits && !ammobits && !powerupbits) {
+ MSG_WriteBits( msg, 0, 1 ); // no change
+ oldsize += 4;
+ return;
+ }
+ MSG_WriteBits( msg, 1, 1 ); // changed
+
+ if ( statsbits ) {
+ MSG_WriteBits( msg, 1, 1 ); // changed
+ MSG_WriteShort( msg, statsbits );
+ for (i=0 ; i<16 ; i++)
+ if (statsbits & (1<<i) )
+ MSG_WriteShort (msg, to->stats[i]);
+ } else {
+ MSG_WriteBits( msg, 0, 1 ); // no change
+ }
+
+
+ if ( persistantbits ) {
+ MSG_WriteBits( msg, 1, 1 ); // changed
+ MSG_WriteShort( msg, persistantbits );
+ for (i=0 ; i<16 ; i++)
+ if (persistantbits & (1<<i) )
+ MSG_WriteShort (msg, to->persistant[i]);
+ } else {
+ MSG_WriteBits( msg, 0, 1 ); // no change
+ }
+
+
+ if ( ammobits ) {
+ MSG_WriteBits( msg, 1, 1 ); // changed
+ MSG_WriteShort( msg, ammobits );
+ for (i=0 ; i<16 ; i++)
+ if (ammobits & (1<<i) )
+ MSG_WriteShort (msg, to->ammo[i]);
+ } else {
+ MSG_WriteBits( msg, 0, 1 ); // no change
+ }
+
+
+ if ( powerupbits ) {
+ MSG_WriteBits( msg, 1, 1 ); // changed
+ MSG_WriteShort( msg, powerupbits );
+ for (i=0 ; i<16 ; i++)
+ if (powerupbits & (1<<i) )
+ MSG_WriteLong( msg, to->powerups[i] );
+ } else {
+ MSG_WriteBits( msg, 0, 1 ); // no change
+ }
+}
+
+
+/*
+===================
+MSG_ReadDeltaPlayerstate
+===================
+*/
+void MSG_ReadDeltaPlayerstate (msg_t *msg, playerState_t *from, playerState_t *to ) {
+ int i, lc;
+ int bits;
+ netField_t *field;
+ int numFields;
+ int startBit, endBit;
+ int print;
+ int *fromF, *toF;
+ int trunc;
+ playerState_t dummy;
+
+ if ( !from ) {
+ from = &dummy;
+ Com_Memset( &dummy, 0, sizeof( dummy ) );
+ }
+ *to = *from;
+
+ if ( msg->bit == 0 ) {
+ startBit = msg->readcount * 8 - GENTITYNUM_BITS;
+ } else {
+ startBit = ( msg->readcount - 1 ) * 8 + msg->bit - GENTITYNUM_BITS;
+ }
+
+ // shownet 2/3 will interleave with other printed info, -2 will
+ // just print the delta records
+ if ( cl_shownet->integer >= 2 || cl_shownet->integer == -2 ) {
+ print = 1;
+ Com_Printf( "%3i: playerstate ", msg->readcount );
+ } else {
+ print = 0;
+ }
+
+ numFields = sizeof( playerStateFields ) / sizeof( playerStateFields[0] );
+ lc = MSG_ReadByte(msg);
+
+ for ( i = 0, field = playerStateFields ; i < lc ; i++, field++ ) {
+ fromF = (int *)( (byte *)from + field->offset );
+ toF = (int *)( (byte *)to + field->offset );
+
+ if ( ! MSG_ReadBits( msg, 1 ) ) {
+ // no change
+ *toF = *fromF;
+ } else {
+ if ( field->bits == 0 ) {
+ // float
+ if ( MSG_ReadBits( msg, 1 ) == 0 ) {
+ // integral float
+ trunc = MSG_ReadBits( msg, FLOAT_INT_BITS );
+ // bias to allow equal parts positive and negative
+ trunc -= FLOAT_INT_BIAS;
+ *(float *)toF = trunc;
+ if ( print ) {
+ Com_Printf( "%s:%i ", field->name, trunc );
+ }
+ } else {
+ // full floating point value
+ *toF = MSG_ReadBits( msg, 32 );
+ if ( print ) {
+ Com_Printf( "%s:%f ", field->name, *(float *)toF );
+ }
+ }
+ } else {
+ // integer
+ *toF = MSG_ReadBits( msg, field->bits );
+ if ( print ) {
+ Com_Printf( "%s:%i ", field->name, *toF );
+ }
+ }
+ }
+ }
+ for ( i=lc,field = &playerStateFields[lc];i<numFields; i++, field++) {
+ fromF = (int *)( (byte *)from + field->offset );
+ toF = (int *)( (byte *)to + field->offset );
+ // no change
+ *toF = *fromF;
+ }
+
+
+ // read the arrays
+ if (MSG_ReadBits( msg, 1 ) ) {
+ // parse stats
+ if ( MSG_ReadBits( msg, 1 ) ) {
+ LOG("PS_STATS");
+ bits = MSG_ReadShort (msg);
+ for (i=0 ; i<16 ; i++) {
+ if (bits & (1<<i) ) {
+ to->stats[i] = MSG_ReadShort(msg);
+ }
+ }
+ }
+
+ // parse persistant stats
+ if ( MSG_ReadBits( msg, 1 ) ) {
+ LOG("PS_PERSISTANT");
+ bits = MSG_ReadShort (msg);
+ for (i=0 ; i<16 ; i++) {
+ if (bits & (1<<i) ) {
+ to->persistant[i] = MSG_ReadShort(msg);
+ }
+ }
+ }
+
+ // parse ammo
+ if ( MSG_ReadBits( msg, 1 ) ) {
+ LOG("PS_AMMO");
+ bits = MSG_ReadShort (msg);
+ for (i=0 ; i<16 ; i++) {
+ if (bits & (1<<i) ) {
+ to->ammo[i] = MSG_ReadShort(msg);
+ }
+ }
+ }
+
+ // parse powerups
+ if ( MSG_ReadBits( msg, 1 ) ) {
+ LOG("PS_POWERUPS");
+ bits = MSG_ReadShort (msg);
+ for (i=0 ; i<16 ; i++) {
+ if (bits & (1<<i) ) {
+ to->powerups[i] = MSG_ReadLong(msg);
+ }
+ }
+ }
+ }
+
+ if ( print ) {
+ if ( msg->bit == 0 ) {
+ endBit = msg->readcount * 8 - GENTITYNUM_BITS;
+ } else {
+ endBit = ( msg->readcount - 1 ) * 8 + msg->bit - GENTITYNUM_BITS;
+ }
+ Com_Printf( " (%i bits)\n", endBit - startBit );
+ }
+}
+
+int msg_hData[256] = {
+250315, // 0
+41193, // 1
+6292, // 2
+7106, // 3
+3730, // 4
+3750, // 5
+6110, // 6
+23283, // 7
+33317, // 8
+6950, // 9
+7838, // 10
+9714, // 11
+9257, // 12
+17259, // 13
+3949, // 14
+1778, // 15
+8288, // 16
+1604, // 17
+1590, // 18
+1663, // 19
+1100, // 20
+1213, // 21
+1238, // 22
+1134, // 23
+1749, // 24
+1059, // 25
+1246, // 26
+1149, // 27
+1273, // 28
+4486, // 29
+2805, // 30
+3472, // 31
+21819, // 32
+1159, // 33
+1670, // 34
+1066, // 35
+1043, // 36
+1012, // 37
+1053, // 38
+1070, // 39
+1726, // 40
+888, // 41
+1180, // 42
+850, // 43
+960, // 44
+780, // 45
+1752, // 46
+3296, // 47
+10630, // 48
+4514, // 49
+5881, // 50
+2685, // 51
+4650, // 52
+3837, // 53
+2093, // 54
+1867, // 55
+2584, // 56
+1949, // 57
+1972, // 58
+940, // 59
+1134, // 60
+1788, // 61
+1670, // 62
+1206, // 63
+5719, // 64
+6128, // 65
+7222, // 66
+6654, // 67
+3710, // 68
+3795, // 69
+1492, // 70
+1524, // 71
+2215, // 72
+1140, // 73
+1355, // 74
+971, // 75
+2180, // 76
+1248, // 77
+1328, // 78
+1195, // 79
+1770, // 80
+1078, // 81
+1264, // 82
+1266, // 83
+1168, // 84
+965, // 85
+1155, // 86
+1186, // 87
+1347, // 88
+1228, // 89
+1529, // 90
+1600, // 91
+2617, // 92
+2048, // 93
+2546, // 94
+3275, // 95
+2410, // 96
+3585, // 97
+2504, // 98
+2800, // 99
+2675, // 100
+6146, // 101
+3663, // 102
+2840, // 103
+14253, // 104
+3164, // 105
+2221, // 106
+1687, // 107
+3208, // 108
+2739, // 109
+3512, // 110
+4796, // 111
+4091, // 112
+3515, // 113
+5288, // 114
+4016, // 115
+7937, // 116
+6031, // 117
+5360, // 118
+3924, // 119
+4892, // 120
+3743, // 121
+4566, // 122
+4807, // 123
+5852, // 124
+6400, // 125
+6225, // 126
+8291, // 127
+23243, // 128
+7838, // 129
+7073, // 130
+8935, // 131
+5437, // 132
+4483, // 133
+3641, // 134
+5256, // 135
+5312, // 136
+5328, // 137
+5370, // 138
+3492, // 139
+2458, // 140
+1694, // 141
+1821, // 142
+2121, // 143
+1916, // 144
+1149, // 145
+1516, // 146
+1367, // 147
+1236, // 148
+1029, // 149
+1258, // 150
+1104, // 151
+1245, // 152
+1006, // 153
+1149, // 154
+1025, // 155
+1241, // 156
+952, // 157
+1287, // 158
+997, // 159
+1713, // 160
+1009, // 161
+1187, // 162
+879, // 163
+1099, // 164
+929, // 165
+1078, // 166
+951, // 167
+1656, // 168
+930, // 169
+1153, // 170
+1030, // 171
+1262, // 172
+1062, // 173
+1214, // 174
+1060, // 175
+1621, // 176
+930, // 177
+1106, // 178
+912, // 179
+1034, // 180
+892, // 181
+1158, // 182
+990, // 183
+1175, // 184
+850, // 185
+1121, // 186
+903, // 187
+1087, // 188
+920, // 189
+1144, // 190
+1056, // 191
+3462, // 192
+2240, // 193
+4397, // 194
+12136, // 195
+7758, // 196
+1345, // 197
+1307, // 198
+3278, // 199
+1950, // 200
+886, // 201
+1023, // 202
+1112, // 203
+1077, // 204
+1042, // 205
+1061, // 206
+1071, // 207
+1484, // 208
+1001, // 209
+1096, // 210
+915, // 211
+1052, // 212
+995, // 213
+1070, // 214
+876, // 215
+1111, // 216
+851, // 217
+1059, // 218
+805, // 219
+1112, // 220
+923, // 221
+1103, // 222
+817, // 223
+1899, // 224
+1872, // 225
+976, // 226
+841, // 227
+1127, // 228
+956, // 229
+1159, // 230
+950, // 231
+7791, // 232
+954, // 233
+1289, // 234
+933, // 235
+1127, // 236
+3207, // 237
+1020, // 238
+927, // 239
+1355, // 240
+768, // 241
+1040, // 242
+745, // 243
+952, // 244
+805, // 245
+1073, // 246
+740, // 247
+1013, // 248
+805, // 249
+1008, // 250
+796, // 251
+996, // 252
+1057, // 253
+11457, // 254
+13504, // 255
+};
+
+void MSG_initHuffman() {
+ int i,j;
+
+ msgInit = qtrue;
+ Huff_Init(&msgHuff);
+ for(i=0;i<256;i++) {
+ for (j=0;j<msg_hData[i];j++) {
+ Huff_addRef(&msgHuff.compressor, (byte)i); // Do update
+ Huff_addRef(&msgHuff.decompressor, (byte)i); // Do update
+ }
+ }
+}
+
+/*
+void MSG_NUinitHuffman() {
+ byte *data;
+ int size, i, ch;
+ int array[256];
+
+ msgInit = qtrue;
+
+ Huff_Init(&msgHuff);
+ // load it in
+ size = FS_ReadFile( "netchan/netchan.bin", (void **)&data );
+
+ for(i=0;i<256;i++) {
+ array[i] = 0;
+ }
+ for(i=0;i<size;i++) {
+ ch = data[i];
+ Huff_addRef(&msgHuff.compressor, ch); // Do update
+ Huff_addRef(&msgHuff.decompressor, ch); // Do update
+ array[ch]++;
+ }
+ Com_Printf("msg_hData {\n");
+ for(i=0;i<256;i++) {
+ if (array[i] == 0) {
+ Huff_addRef(&msgHuff.compressor, i); // Do update
+ Huff_addRef(&msgHuff.decompressor, i); // Do update
+ }
+ Com_Printf("%d, // %d\n", array[i], i);
+ }
+ Com_Printf("};\n");
+ FS_FreeFile( data );
+ Cbuf_AddText( "condump dump.txt\n" );
+}
+*/
+
+//===========================================================================
diff --git a/code/qcommon/net_chan.c b/code/qcommon/net_chan.c
new file mode 100755
index 0000000..a88b90b
--- /dev/null
+++ b/code/qcommon/net_chan.c
@@ -0,0 +1,742 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "../game/q_shared.h"
+#include "qcommon.h"
+
+/*
+
+packet header
+-------------
+4 outgoing sequence. high bit will be set if this is a fragmented message
+[2 qport (only for client to server)]
+[2 fragment start byte]
+[2 fragment length. if < FRAGMENT_SIZE, this is the last fragment]
+
+if the sequence number is -1, the packet should be handled as an out-of-band
+message instead of as part of a netcon.
+
+All fragments will have the same sequence numbers.
+
+The qport field is a workaround for bad address translating routers that
+sometimes remap the client's source port on a packet during gameplay.
+
+If the base part of the net address matches and the qport matches, then the
+channel matches even if the IP port differs. The IP port should be updated
+to the new value before sending out any replies.
+
+*/
+
+
+#define MAX_PACKETLEN 1400 // max size of a network packet
+
+#define FRAGMENT_SIZE (MAX_PACKETLEN - 100)
+#define PACKET_HEADER 10 // two ints and a short
+
+#define FRAGMENT_BIT (1<<31)
+
+cvar_t *showpackets;
+cvar_t *showdrop;
+cvar_t *qport;
+
+static char *netsrcString[2] = {
+ "client",
+ "server"
+};
+
+/*
+===============
+Netchan_Init
+
+===============
+*/
+void Netchan_Init( int port ) {
+ port &= 0xffff;
+ showpackets = Cvar_Get ("showpackets", "0", CVAR_TEMP );
+ showdrop = Cvar_Get ("showdrop", "0", CVAR_TEMP );
+ qport = Cvar_Get ("net_qport", va("%i", port), CVAR_INIT );
+}
+
+/*
+==============
+Netchan_Setup
+
+called to open a channel to a remote system
+==============
+*/
+void Netchan_Setup( netsrc_t sock, netchan_t *chan, netadr_t adr, int qport ) {
+ Com_Memset (chan, 0, sizeof(*chan));
+
+ chan->sock = sock;
+ chan->remoteAddress = adr;
+ chan->qport = qport;
+ chan->incomingSequence = 0;
+ chan->outgoingSequence = 1;
+}
+
+// TTimo: unused, commenting out to make gcc happy
+#if 0
+/*
+==============
+Netchan_ScramblePacket
+
+A probably futile attempt to make proxy hacking somewhat
+more difficult.
+==============
+*/
+#define SCRAMBLE_START 6
+static void Netchan_ScramblePacket( msg_t *buf ) {
+ unsigned seed;
+ int i, j, c, mask, temp;
+ int seq[MAX_PACKETLEN];
+
+ seed = ( LittleLong( *(unsigned *)buf->data ) * 3 ) ^ ( buf->cursize * 123 );
+ c = buf->cursize;
+ if ( c <= SCRAMBLE_START ) {
+ return;
+ }
+ if ( c > MAX_PACKETLEN ) {
+ Com_Error( ERR_DROP, "MAX_PACKETLEN" );
+ }
+
+ // generate a sequence of "random" numbers
+ for (i = 0 ; i < c ; i++) {
+ seed = (119 * seed + 1);
+ seq[i] = seed;
+ }
+
+ // transpose each character
+ for ( mask = 1 ; mask < c-SCRAMBLE_START ; mask = ( mask << 1 ) + 1 ) {
+ }
+ mask >>= 1;
+ for (i = SCRAMBLE_START ; i < c ; i++) {
+ j = SCRAMBLE_START + ( seq[i] & mask );
+ temp = buf->data[j];
+ buf->data[j] = buf->data[i];
+ buf->data[i] = temp;
+ }
+
+ // byte xor the data after the header
+ for (i = SCRAMBLE_START ; i < c ; i++) {
+ buf->data[i] ^= seq[i];
+ }
+}
+
+static void Netchan_UnScramblePacket( msg_t *buf ) {
+ unsigned seed;
+ int i, j, c, mask, temp;
+ int seq[MAX_PACKETLEN];
+
+ seed = ( LittleLong( *(unsigned *)buf->data ) * 3 ) ^ ( buf->cursize * 123 );
+ c = buf->cursize;
+ if ( c <= SCRAMBLE_START ) {
+ return;
+ }
+ if ( c > MAX_PACKETLEN ) {
+ Com_Error( ERR_DROP, "MAX_PACKETLEN" );
+ }
+
+ // generate a sequence of "random" numbers
+ for (i = 0 ; i < c ; i++) {
+ seed = (119 * seed + 1);
+ seq[i] = seed;
+ }
+
+ // byte xor the data after the header
+ for (i = SCRAMBLE_START ; i < c ; i++) {
+ buf->data[i] ^= seq[i];
+ }
+
+ // transpose each character in reverse order
+ for ( mask = 1 ; mask < c-SCRAMBLE_START ; mask = ( mask << 1 ) + 1 ) {
+ }
+ mask >>= 1;
+ for (i = c-1 ; i >= SCRAMBLE_START ; i--) {
+ j = SCRAMBLE_START + ( seq[i] & mask );
+ temp = buf->data[j];
+ buf->data[j] = buf->data[i];
+ buf->data[i] = temp;
+ }
+}
+#endif
+
+/*
+=================
+Netchan_TransmitNextFragment
+
+Send one fragment of the current message
+=================
+*/
+void Netchan_TransmitNextFragment( netchan_t *chan ) {
+ msg_t send;
+ byte send_buf[MAX_PACKETLEN];
+ int fragmentLength;
+
+ // write the packet header
+ MSG_InitOOB (&send, send_buf, sizeof(send_buf)); // <-- only do the oob here
+
+ MSG_WriteLong( &send, chan->outgoingSequence | FRAGMENT_BIT );
+
+ // send the qport if we are a client
+ if ( chan->sock == NS_CLIENT ) {
+ MSG_WriteShort( &send, qport->integer );
+ }
+
+ // copy the reliable message to the packet first
+ fragmentLength = FRAGMENT_SIZE;
+ if ( chan->unsentFragmentStart + fragmentLength > chan->unsentLength ) {
+ fragmentLength = chan->unsentLength - chan->unsentFragmentStart;
+ }
+
+ MSG_WriteShort( &send, chan->unsentFragmentStart );
+ MSG_WriteShort( &send, fragmentLength );
+ MSG_WriteData( &send, chan->unsentBuffer + chan->unsentFragmentStart, fragmentLength );
+
+ // send the datagram
+ NET_SendPacket( chan->sock, send.cursize, send.data, chan->remoteAddress );
+
+ if ( showpackets->integer ) {
+ Com_Printf ("%s send %4i : s=%i fragment=%i,%i\n"
+ , netsrcString[ chan->sock ]
+ , send.cursize
+ , chan->outgoingSequence
+ , chan->unsentFragmentStart, fragmentLength);
+ }
+
+ chan->unsentFragmentStart += fragmentLength;
+
+ // this exit condition is a little tricky, because a packet
+ // that is exactly the fragment length still needs to send
+ // a second packet of zero length so that the other side
+ // can tell there aren't more to follow
+ if ( chan->unsentFragmentStart == chan->unsentLength && fragmentLength != FRAGMENT_SIZE ) {
+ chan->outgoingSequence++;
+ chan->unsentFragments = qfalse;
+ }
+}
+
+
+/*
+===============
+Netchan_Transmit
+
+Sends a message to a connection, fragmenting if necessary
+A 0 length will still generate a packet.
+================
+*/
+void Netchan_Transmit( netchan_t *chan, int length, const byte *data ) {
+ msg_t send;
+ byte send_buf[MAX_PACKETLEN];
+
+ if ( length > MAX_MSGLEN ) {
+ Com_Error( ERR_DROP, "Netchan_Transmit: length = %i", length );
+ }
+ chan->unsentFragmentStart = 0;
+
+ // fragment large reliable messages
+ if ( length >= FRAGMENT_SIZE ) {
+ chan->unsentFragments = qtrue;
+ chan->unsentLength = length;
+ Com_Memcpy( chan->unsentBuffer, data, length );
+
+ // only send the first fragment now
+ Netchan_TransmitNextFragment( chan );
+
+ return;
+ }
+
+ // write the packet header
+ MSG_InitOOB (&send, send_buf, sizeof(send_buf));
+
+ MSG_WriteLong( &send, chan->outgoingSequence );
+ chan->outgoingSequence++;
+
+ // send the qport if we are a client
+ if ( chan->sock == NS_CLIENT ) {
+ MSG_WriteShort( &send, qport->integer );
+ }
+
+ MSG_WriteData( &send, data, length );
+
+ // send the datagram
+ NET_SendPacket( chan->sock, send.cursize, send.data, chan->remoteAddress );
+
+ if ( showpackets->integer ) {
+ Com_Printf( "%s send %4i : s=%i ack=%i\n"
+ , netsrcString[ chan->sock ]
+ , send.cursize
+ , chan->outgoingSequence - 1
+ , chan->incomingSequence );
+ }
+}
+
+/*
+=================
+Netchan_Process
+
+Returns qfalse if the message should not be processed due to being
+out of order or a fragment.
+
+Msg must be large enough to hold MAX_MSGLEN, because if this is the
+final fragment of a multi-part message, the entire thing will be
+copied out.
+=================
+*/
+qboolean Netchan_Process( netchan_t *chan, msg_t *msg ) {
+ int sequence;
+ int qport;
+ int fragmentStart, fragmentLength;
+ qboolean fragmented;
+
+ // XOR unscramble all data in the packet after the header
+// Netchan_UnScramblePacket( msg );
+
+ // get sequence numbers
+ MSG_BeginReadingOOB( msg );
+ sequence = MSG_ReadLong( msg );
+
+ // check for fragment information
+ if ( sequence & FRAGMENT_BIT ) {
+ sequence &= ~FRAGMENT_BIT;
+ fragmented = qtrue;
+ } else {
+ fragmented = qfalse;
+ }
+
+ // read the qport if we are a server
+ if ( chan->sock == NS_SERVER ) {
+ qport = MSG_ReadShort( msg );
+ }
+
+ // read the fragment information
+ if ( fragmented ) {
+ fragmentStart = MSG_ReadShort( msg );
+ fragmentLength = MSG_ReadShort( msg );
+ } else {
+ fragmentStart = 0; // stop warning message
+ fragmentLength = 0;
+ }
+
+ if ( showpackets->integer ) {
+ if ( fragmented ) {
+ Com_Printf( "%s recv %4i : s=%i fragment=%i,%i\n"
+ , netsrcString[ chan->sock ]
+ , msg->cursize
+ , sequence
+ , fragmentStart, fragmentLength );
+ } else {
+ Com_Printf( "%s recv %4i : s=%i\n"
+ , netsrcString[ chan->sock ]
+ , msg->cursize
+ , sequence );
+ }
+ }
+
+ //
+ // discard out of order or duplicated packets
+ //
+ if ( sequence <= chan->incomingSequence ) {
+ if ( showdrop->integer || showpackets->integer ) {
+ Com_Printf( "%s:Out of order packet %i at %i\n"
+ , NET_AdrToString( chan->remoteAddress )
+ , sequence
+ , chan->incomingSequence );
+ }
+ return qfalse;
+ }
+
+ //
+ // dropped packets don't keep the message from being used
+ //
+ chan->dropped = sequence - (chan->incomingSequence+1);
+ if ( chan->dropped > 0 ) {
+ if ( showdrop->integer || showpackets->integer ) {
+ Com_Printf( "%s:Dropped %i packets at %i\n"
+ , NET_AdrToString( chan->remoteAddress )
+ , chan->dropped
+ , sequence );
+ }
+ }
+
+
+ //
+ // if this is the final framgent of a reliable message,
+ // bump incoming_reliable_sequence
+ //
+ if ( fragmented ) {
+ // TTimo
+ // make sure we add the fragments in correct order
+ // either a packet was dropped, or we received this one too soon
+ // we don't reconstruct the fragments. we will wait till this fragment gets to us again
+ // (NOTE: we could probably try to rebuild by out of order chunks if needed)
+ if ( sequence != chan->fragmentSequence ) {
+ chan->fragmentSequence = sequence;
+ chan->fragmentLength = 0;
+ }
+
+ // if we missed a fragment, dump the message
+ if ( fragmentStart != chan->fragmentLength ) {
+ if ( showdrop->integer || showpackets->integer ) {
+ Com_Printf( "%s:Dropped a message fragment\n"
+ , NET_AdrToString( chan->remoteAddress )
+ , sequence);
+ }
+ // we can still keep the part that we have so far,
+ // so we don't need to clear chan->fragmentLength
+ return qfalse;
+ }
+
+ // copy the fragment to the fragment buffer
+ if ( fragmentLength < 0 || msg->readcount + fragmentLength > msg->cursize ||
+ chan->fragmentLength + fragmentLength > sizeof( chan->fragmentBuffer ) ) {
+ if ( showdrop->integer || showpackets->integer ) {
+ Com_Printf ("%s:illegal fragment length\n"
+ , NET_AdrToString (chan->remoteAddress ) );
+ }
+ return qfalse;
+ }
+
+ Com_Memcpy( chan->fragmentBuffer + chan->fragmentLength,
+ msg->data + msg->readcount, fragmentLength );
+
+ chan->fragmentLength += fragmentLength;
+
+ // if this wasn't the last fragment, don't process anything
+ if ( fragmentLength == FRAGMENT_SIZE ) {
+ return qfalse;
+ }
+
+ if ( chan->fragmentLength > msg->maxsize ) {
+ Com_Printf( "%s:fragmentLength %i > msg->maxsize\n"
+ , NET_AdrToString (chan->remoteAddress ),
+ chan->fragmentLength );
+ return qfalse;
+ }
+
+ // copy the full message over the partial fragment
+
+ // make sure the sequence number is still there
+ *(int *)msg->data = LittleLong( sequence );
+
+ Com_Memcpy( msg->data + 4, chan->fragmentBuffer, chan->fragmentLength );
+ msg->cursize = chan->fragmentLength + 4;
+ chan->fragmentLength = 0;
+ msg->readcount = 4; // past the sequence number
+ msg->bit = 32; // past the sequence number
+
+ // TTimo
+ // clients were not acking fragmented messages
+ chan->incomingSequence = sequence;
+
+ return qtrue;
+ }
+
+ //
+ // the message can now be read from the current message pointer
+ //
+ chan->incomingSequence = sequence;
+
+ return qtrue;
+}
+
+
+//==============================================================================
+
+/*
+===================
+NET_CompareBaseAdr
+
+Compares without the port
+===================
+*/
+qboolean NET_CompareBaseAdr (netadr_t a, netadr_t b)
+{
+ if (a.type != b.type)
+ return qfalse;
+
+ if (a.type == NA_LOOPBACK)
+ return qtrue;
+
+ if (a.type == NA_IP)
+ {
+ if (a.ip[0] == b.ip[0] && a.ip[1] == b.ip[1] && a.ip[2] == b.ip[2] && a.ip[3] == b.ip[3])
+ return qtrue;
+ return qfalse;
+ }
+
+ if (a.type == NA_IPX)
+ {
+ if ((memcmp(a.ipx, b.ipx, 10) == 0))
+ return qtrue;
+ return qfalse;
+ }
+
+
+ Com_Printf ("NET_CompareBaseAdr: bad address type\n");
+ return qfalse;
+}
+
+const char *NET_AdrToString (netadr_t a)
+{
+ static char s[64];
+
+ if (a.type == NA_LOOPBACK) {
+ Com_sprintf (s, sizeof(s), "loopback");
+ } else if (a.type == NA_BOT) {
+ Com_sprintf (s, sizeof(s), "bot");
+ } else if (a.type == NA_IP) {
+ Com_sprintf (s, sizeof(s), "%i.%i.%i.%i:%hu",
+ a.ip[0], a.ip[1], a.ip[2], a.ip[3], BigShort(a.port));
+ } else {
+ Com_sprintf (s, sizeof(s), "%02x%02x%02x%02x.%02x%02x%02x%02x%02x%02x:%hu",
+ a.ipx[0], a.ipx[1], a.ipx[2], a.ipx[3], a.ipx[4], a.ipx[5], a.ipx[6], a.ipx[7], a.ipx[8], a.ipx[9],
+ BigShort(a.port));
+ }
+
+ return s;
+}
+
+
+qboolean NET_CompareAdr (netadr_t a, netadr_t b)
+{
+ if (a.type != b.type)
+ return qfalse;
+
+ if (a.type == NA_LOOPBACK)
+ return qtrue;
+
+ if (a.type == NA_IP)
+ {
+ if (a.ip[0] == b.ip[0] && a.ip[1] == b.ip[1] && a.ip[2] == b.ip[2] && a.ip[3] == b.ip[3] && a.port == b.port)
+ return qtrue;
+ return qfalse;
+ }
+
+ if (a.type == NA_IPX)
+ {
+ if ((memcmp(a.ipx, b.ipx, 10) == 0) && a.port == b.port)
+ return qtrue;
+ return qfalse;
+ }
+
+ Com_Printf ("NET_CompareAdr: bad address type\n");
+ return qfalse;
+}
+
+
+qboolean NET_IsLocalAddress( netadr_t adr ) {
+ return adr.type == NA_LOOPBACK;
+}
+
+
+
+/*
+=============================================================================
+
+LOOPBACK BUFFERS FOR LOCAL PLAYER
+
+=============================================================================
+*/
+
+// there needs to be enough loopback messages to hold a complete
+// gamestate of maximum size
+#define MAX_LOOPBACK 16
+
+typedef struct {
+ byte data[MAX_PACKETLEN];
+ int datalen;
+} loopmsg_t;
+
+typedef struct {
+ loopmsg_t msgs[MAX_LOOPBACK];
+ int get, send;
+} loopback_t;
+
+loopback_t loopbacks[2];
+
+
+qboolean NET_GetLoopPacket (netsrc_t sock, netadr_t *net_from, msg_t *net_message)
+{
+ int i;
+ loopback_t *loop;
+
+ loop = &loopbacks[sock];
+
+ if (loop->send - loop->get > MAX_LOOPBACK)
+ loop->get = loop->send - MAX_LOOPBACK;
+
+ if (loop->get >= loop->send)
+ return qfalse;
+
+ i = loop->get & (MAX_LOOPBACK-1);
+ loop->get++;
+
+ Com_Memcpy (net_message->data, loop->msgs[i].data, loop->msgs[i].datalen);
+ net_message->cursize = loop->msgs[i].datalen;
+ Com_Memset (net_from, 0, sizeof(*net_from));
+ net_from->type = NA_LOOPBACK;
+ return qtrue;
+
+}
+
+
+void NET_SendLoopPacket (netsrc_t sock, int length, const void *data, netadr_t to)
+{
+ int i;
+ loopback_t *loop;
+
+ loop = &loopbacks[sock^1];
+
+ i = loop->send & (MAX_LOOPBACK-1);
+ loop->send++;
+
+ Com_Memcpy (loop->msgs[i].data, data, length);
+ loop->msgs[i].datalen = length;
+}
+
+//=============================================================================
+
+
+void NET_SendPacket( netsrc_t sock, int length, const void *data, netadr_t to ) {
+
+ // sequenced packets are shown in netchan, so just show oob
+ if ( showpackets->integer && *(int *)data == -1 ) {
+ Com_Printf ("send packet %4i\n", length);
+ }
+
+ if ( to.type == NA_LOOPBACK ) {
+ NET_SendLoopPacket (sock, length, data, to);
+ return;
+ }
+ if ( to.type == NA_BOT ) {
+ return;
+ }
+ if ( to.type == NA_BAD ) {
+ return;
+ }
+
+ Sys_SendPacket( length, data, to );
+}
+
+/*
+===============
+NET_OutOfBandPrint
+
+Sends a text message in an out-of-band datagram
+================
+*/
+void QDECL NET_OutOfBandPrint( netsrc_t sock, netadr_t adr, const char *format, ... ) {
+ va_list argptr;
+ char string[MAX_MSGLEN];
+
+
+ // set the header
+ string[0] = -1;
+ string[1] = -1;
+ string[2] = -1;
+ string[3] = -1;
+
+ va_start( argptr, format );
+ vsprintf( string+4, format, argptr );
+ va_end( argptr );
+
+ // send the datagram
+ NET_SendPacket( sock, strlen( string ), string, adr );
+}
+
+/*
+===============
+NET_OutOfBandPrint
+
+Sends a data message in an out-of-band datagram (only used for "connect")
+================
+*/
+void QDECL NET_OutOfBandData( netsrc_t sock, netadr_t adr, byte *format, int len ) {
+ byte string[MAX_MSGLEN*2];
+ int i;
+ msg_t mbuf;
+
+ // set the header
+ string[0] = 0xff;
+ string[1] = 0xff;
+ string[2] = 0xff;
+ string[3] = 0xff;
+
+ for(i=0;i<len;i++) {
+ string[i+4] = format[i];
+ }
+
+ mbuf.data = string;
+ mbuf.cursize = len+4;
+ Huff_Compress( &mbuf, 12);
+ // send the datagram
+ NET_SendPacket( sock, mbuf.cursize, mbuf.data, adr );
+}
+
+/*
+=============
+NET_StringToAdr
+
+Traps "localhost" for loopback, passes everything else to system
+=============
+*/
+qboolean NET_StringToAdr( const char *s, netadr_t *a ) {
+ qboolean r;
+ char base[MAX_STRING_CHARS];
+ char *port;
+
+ if (!strcmp (s, "localhost")) {
+ Com_Memset (a, 0, sizeof(*a));
+ a->type = NA_LOOPBACK;
+ return qtrue;
+ }
+
+ // look for a port number
+ Q_strncpyz( base, s, sizeof( base ) );
+ port = strstr( base, ":" );
+ if ( port ) {
+ *port = 0;
+ port++;
+ }
+
+ r = Sys_StringToAdr( base, a );
+
+ if ( !r ) {
+ a->type = NA_BAD;
+ return qfalse;
+ }
+
+ // inet_addr returns this if out of range
+ if ( a->ip[0] == 255 && a->ip[1] == 255 && a->ip[2] == 255 && a->ip[3] == 255 ) {
+ a->type = NA_BAD;
+ return qfalse;
+ }
+
+ if ( port ) {
+ a->port = BigShort( (short)atoi( port ) );
+ } else {
+ a->port = BigShort( PORT_SERVER );
+ }
+
+ return qtrue;
+}
+
diff --git a/code/qcommon/qcommon.h b/code/qcommon/qcommon.h
new file mode 100755
index 0000000..3e72f59
--- /dev/null
+++ b/code/qcommon/qcommon.h
@@ -0,0 +1,1067 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// qcommon.h -- definitions common between client and server, but not game.or ref modules
+#ifndef _QCOMMON_H_
+#define _QCOMMON_H_
+
+#include "../qcommon/cm_public.h"
+
+//#define PRE_RELEASE_DEMO
+
+//============================================================================
+
+//
+// msg.c
+//
+typedef struct {
+ qboolean allowoverflow; // if false, do a Com_Error
+ qboolean overflowed; // set to true if the buffer size failed (with allowoverflow set)
+ qboolean oob; // set to true if the buffer size failed (with allowoverflow set)
+ byte *data;
+ int maxsize;
+ int cursize;
+ int readcount;
+ int bit; // for bitwise reads and writes
+} msg_t;
+
+void MSG_Init (msg_t *buf, byte *data, int length);
+void MSG_InitOOB( msg_t *buf, byte *data, int length );
+void MSG_Clear (msg_t *buf);
+void MSG_WriteData (msg_t *buf, const void *data, int length);
+void MSG_Bitstream( msg_t *buf );
+
+// TTimo
+// copy a msg_t in case we need to store it as is for a bit
+// (as I needed this to keep an msg_t from a static var for later use)
+// sets data buffer as MSG_Init does prior to do the copy
+void MSG_Copy(msg_t *buf, byte *data, int length, msg_t *src);
+
+struct usercmd_s;
+struct entityState_s;
+struct playerState_s;
+
+void MSG_WriteBits( msg_t *msg, int value, int bits );
+
+void MSG_WriteChar (msg_t *sb, int c);
+void MSG_WriteByte (msg_t *sb, int c);
+void MSG_WriteShort (msg_t *sb, int c);
+void MSG_WriteLong (msg_t *sb, int c);
+void MSG_WriteFloat (msg_t *sb, float f);
+void MSG_WriteString (msg_t *sb, const char *s);
+void MSG_WriteBigString (msg_t *sb, const char *s);
+void MSG_WriteAngle16 (msg_t *sb, float f);
+
+void MSG_BeginReading (msg_t *sb);
+void MSG_BeginReadingOOB(msg_t *sb);
+
+int MSG_ReadBits( msg_t *msg, int bits );
+
+int MSG_ReadChar (msg_t *sb);
+int MSG_ReadByte (msg_t *sb);
+int MSG_ReadShort (msg_t *sb);
+int MSG_ReadLong (msg_t *sb);
+float MSG_ReadFloat (msg_t *sb);
+char *MSG_ReadString (msg_t *sb);
+char *MSG_ReadBigString (msg_t *sb);
+char *MSG_ReadStringLine (msg_t *sb);
+float MSG_ReadAngle16 (msg_t *sb);
+void MSG_ReadData (msg_t *sb, void *buffer, int size);
+
+
+void MSG_WriteDeltaUsercmd( msg_t *msg, struct usercmd_s *from, struct usercmd_s *to );
+void MSG_ReadDeltaUsercmd( msg_t *msg, struct usercmd_s *from, struct usercmd_s *to );
+
+void MSG_WriteDeltaUsercmdKey( msg_t *msg, int key, usercmd_t *from, usercmd_t *to );
+void MSG_ReadDeltaUsercmdKey( msg_t *msg, int key, usercmd_t *from, usercmd_t *to );
+
+void MSG_WriteDeltaEntity( msg_t *msg, struct entityState_s *from, struct entityState_s *to
+ , qboolean force );
+void MSG_ReadDeltaEntity( msg_t *msg, entityState_t *from, entityState_t *to,
+ int number );
+
+void MSG_WriteDeltaPlayerstate( msg_t *msg, struct playerState_s *from, struct playerState_s *to );
+void MSG_ReadDeltaPlayerstate( msg_t *msg, struct playerState_s *from, struct playerState_s *to );
+
+
+void MSG_ReportChangeVectors_f( void );
+
+//============================================================================
+
+/*
+==============================================================
+
+NET
+
+==============================================================
+*/
+
+#define PACKET_BACKUP 32 // number of old messages that must be kept on client and
+ // server for delta comrpession and ping estimation
+#define PACKET_MASK (PACKET_BACKUP-1)
+
+#define MAX_PACKET_USERCMDS 32 // max number of usercmd_t in a packet
+
+#define PORT_ANY -1
+
+#define MAX_RELIABLE_COMMANDS 64 // max string commands buffered for restransmit
+
+typedef enum {
+ NA_BOT,
+ NA_BAD, // an address lookup failed
+ NA_LOOPBACK,
+ NA_BROADCAST,
+ NA_IP,
+ NA_IPX,
+ NA_BROADCAST_IPX
+} netadrtype_t;
+
+typedef enum {
+ NS_CLIENT,
+ NS_SERVER
+} netsrc_t;
+
+typedef struct {
+ netadrtype_t type;
+
+ byte ip[4];
+ byte ipx[10];
+
+ unsigned short port;
+} netadr_t;
+
+void NET_Init( void );
+void NET_Shutdown( void );
+void NET_Restart( void );
+void NET_Config( qboolean enableNetworking );
+
+void NET_SendPacket (netsrc_t sock, int length, const void *data, netadr_t to);
+void QDECL NET_OutOfBandPrint( netsrc_t net_socket, netadr_t adr, const char *format, ...);
+void QDECL NET_OutOfBandData( netsrc_t sock, netadr_t adr, byte *format, int len );
+
+qboolean NET_CompareAdr (netadr_t a, netadr_t b);
+qboolean NET_CompareBaseAdr (netadr_t a, netadr_t b);
+qboolean NET_IsLocalAddress (netadr_t adr);
+const char *NET_AdrToString (netadr_t a);
+qboolean NET_StringToAdr ( const char *s, netadr_t *a);
+qboolean NET_GetLoopPacket (netsrc_t sock, netadr_t *net_from, msg_t *net_message);
+void NET_Sleep(int msec);
+
+
+#define MAX_MSGLEN 16384 // max length of a message, which may
+ // be fragmented into multiple packets
+
+#define MAX_DOWNLOAD_WINDOW 8 // max of eight download frames
+#define MAX_DOWNLOAD_BLKSIZE 2048 // 2048 byte block chunks
+
+
+/*
+Netchan handles packet fragmentation and out of order / duplicate suppression
+*/
+
+typedef struct {
+ netsrc_t sock;
+
+ int dropped; // between last packet and previous
+
+ netadr_t remoteAddress;
+ int qport; // qport value to write when transmitting
+
+ // sequencing variables
+ int incomingSequence;
+ int outgoingSequence;
+
+ // incoming fragment assembly buffer
+ int fragmentSequence;
+ int fragmentLength;
+ byte fragmentBuffer[MAX_MSGLEN];
+
+ // outgoing fragment buffer
+ // we need to space out the sending of large fragmented messages
+ qboolean unsentFragments;
+ int unsentFragmentStart;
+ int unsentLength;
+ byte unsentBuffer[MAX_MSGLEN];
+} netchan_t;
+
+void Netchan_Init( int qport );
+void Netchan_Setup( netsrc_t sock, netchan_t *chan, netadr_t adr, int qport );
+
+void Netchan_Transmit( netchan_t *chan, int length, const byte *data );
+void Netchan_TransmitNextFragment( netchan_t *chan );
+
+qboolean Netchan_Process( netchan_t *chan, msg_t *msg );
+
+
+/*
+==============================================================
+
+PROTOCOL
+
+==============================================================
+*/
+
+#define PROTOCOL_VERSION 68
+// 1.31 - 67
+
+// maintain a list of compatible protocols for demo playing
+// NOTE: that stuff only works with two digits protocols
+extern int demo_protocols[];
+
+#define UPDATE_SERVER_NAME "update.quake3arena.com"
+// override on command line, config files etc.
+#ifndef MASTER_SERVER_NAME
+#define MASTER_SERVER_NAME "master.quake3arena.com"
+#endif
+#ifndef AUTHORIZE_SERVER_NAME
+#define AUTHORIZE_SERVER_NAME "authorize.quake3arena.com"
+#endif
+
+#define PORT_MASTER 27950
+#define PORT_UPDATE 27951
+#ifndef PORT_AUTHORIZE
+#define PORT_AUTHORIZE 27952
+#endif
+#define PORT_SERVER 27960
+#define NUM_SERVER_PORTS 4 // broadcast scan this many ports after
+ // PORT_SERVER so a single machine can
+ // run multiple servers
+
+
+// the svc_strings[] array in cl_parse.c should mirror this
+//
+// server to client
+//
+enum svc_ops_e {
+ svc_bad,
+ svc_nop,
+ svc_gamestate,
+ svc_configstring, // [short] [string] only in gamestate messages
+ svc_baseline, // only in gamestate messages
+ svc_serverCommand, // [string] to be executed by client game module
+ svc_download, // [short] size [size bytes]
+ svc_snapshot,
+ svc_EOF
+};
+
+
+//
+// client to server
+//
+enum clc_ops_e {
+ clc_bad,
+ clc_nop,
+ clc_move, // [[usercmd_t]
+ clc_moveNoDelta, // [[usercmd_t]
+ clc_clientCommand, // [string] message
+ clc_EOF
+};
+
+/*
+==============================================================
+
+VIRTUAL MACHINE
+
+==============================================================
+*/
+
+typedef struct vm_s vm_t;
+
+typedef enum {
+ VMI_NATIVE,
+ VMI_BYTECODE,
+ VMI_COMPILED
+} vmInterpret_t;
+
+typedef enum {
+ TRAP_MEMSET = 100,
+ TRAP_MEMCPY,
+ TRAP_STRNCPY,
+ TRAP_SIN,
+ TRAP_COS,
+ TRAP_ATAN2,
+ TRAP_SQRT,
+ TRAP_MATRIXMULTIPLY,
+ TRAP_ANGLEVECTORS,
+ TRAP_PERPENDICULARVECTOR,
+ TRAP_FLOOR,
+ TRAP_CEIL,
+
+ TRAP_TESTPRINTINT,
+ TRAP_TESTPRINTFLOAT
+} sharedTraps_t;
+
+void VM_Init( void );
+vm_t *VM_Create( const char *module, int (*systemCalls)(int *),
+ vmInterpret_t interpret );
+// module should be bare: "cgame", not "cgame.dll" or "vm/cgame.qvm"
+
+void VM_Free( vm_t *vm );
+void VM_Clear(void);
+vm_t *VM_Restart( vm_t *vm );
+
+int QDECL VM_Call( vm_t *vm, int callNum, ... );
+
+void VM_Debug( int level );
+
+void *VM_ArgPtr( int intValue );
+void *VM_ExplicitArgPtr( vm_t *vm, int intValue );
+
+/*
+==============================================================
+
+CMD
+
+Command text buffering and command execution
+
+==============================================================
+*/
+
+/*
+
+Any number of commands can be added in a frame, from several different sources.
+Most commands come from either keybindings or console line input, but entire text
+files can be execed.
+
+*/
+
+void Cbuf_Init (void);
+// allocates an initial text buffer that will grow as needed
+
+void Cbuf_AddText( const char *text );
+// Adds command text at the end of the buffer, does NOT add a final \n
+
+void Cbuf_ExecuteText( int exec_when, const char *text );
+// this can be used in place of either Cbuf_AddText or Cbuf_InsertText
+
+void Cbuf_Execute (void);
+// Pulls off \n terminated lines of text from the command buffer and sends
+// them through Cmd_ExecuteString. Stops when the buffer is empty.
+// Normally called once per frame, but may be explicitly invoked.
+// Do not call inside a command function, or current args will be destroyed.
+
+//===========================================================================
+
+/*
+
+Command execution takes a null terminated string, breaks it into tokens,
+then searches for a command or variable that matches the first token.
+
+*/
+
+typedef void (*xcommand_t) (void);
+
+void Cmd_Init (void);
+
+void Cmd_AddCommand( const char *cmd_name, xcommand_t function );
+// called by the init functions of other parts of the program to
+// register commands and functions to call for them.
+// The cmd_name is referenced later, so it should not be in temp memory
+// if function is NULL, the command will be forwarded to the server
+// as a clc_clientCommand instead of executed locally
+
+void Cmd_RemoveCommand( const char *cmd_name );
+
+void Cmd_CommandCompletion( void(*callback)(const char *s) );
+// callback with each valid string
+
+int Cmd_Argc (void);
+char *Cmd_Argv (int arg);
+void Cmd_ArgvBuffer( int arg, char *buffer, int bufferLength );
+char *Cmd_Args (void);
+char *Cmd_ArgsFrom( int arg );
+void Cmd_ArgsBuffer( char *buffer, int bufferLength );
+char *Cmd_Cmd (void);
+// The functions that execute commands get their parameters with these
+// functions. Cmd_Argv () will return an empty string, not a NULL
+// if arg > argc, so string operations are allways safe.
+
+void Cmd_TokenizeString( const char *text );
+// Takes a null terminated string. Does not need to be /n terminated.
+// breaks the string up into arg tokens.
+
+void Cmd_ExecuteString( const char *text );
+// Parses a single line of text into arguments and tries to execute it
+// as if it was typed at the console
+
+
+/*
+==============================================================
+
+CVAR
+
+==============================================================
+*/
+
+/*
+
+cvar_t variables are used to hold scalar or string variables that can be changed
+or displayed at the console or prog code as well as accessed directly
+in C code.
+
+The user can access cvars from the console in three ways:
+r_draworder prints the current value
+r_draworder 0 sets the current value to 0
+set r_draworder 0 as above, but creates the cvar if not present
+
+Cvars are restricted from having the same names as commands to keep this
+interface from being ambiguous.
+
+The are also occasionally used to communicated information between different
+modules of the program.
+
+*/
+
+cvar_t *Cvar_Get( const char *var_name, const char *value, int flags );
+// creates the variable if it doesn't exist, or returns the existing one
+// if it exists, the value will not be changed, but flags will be ORed in
+// that allows variables to be unarchived without needing bitflags
+// if value is "", the value will not override a previously set value.
+
+void Cvar_Register( vmCvar_t *vmCvar, const char *varName, const char *defaultValue, int flags );
+// basically a slightly modified Cvar_Get for the interpreted modules
+
+void Cvar_Update( vmCvar_t *vmCvar );
+// updates an interpreted modules' version of a cvar
+
+void Cvar_Set( const char *var_name, const char *value );
+// will create the variable with no flags if it doesn't exist
+
+void Cvar_SetLatched( const char *var_name, const char *value);
+// don't set the cvar immediately
+
+void Cvar_SetValue( const char *var_name, float value );
+// expands value to a string and calls Cvar_Set
+
+float Cvar_VariableValue( const char *var_name );
+int Cvar_VariableIntegerValue( const char *var_name );
+// returns 0 if not defined or non numeric
+
+char *Cvar_VariableString( const char *var_name );
+void Cvar_VariableStringBuffer( const char *var_name, char *buffer, int bufsize );
+// returns an empty string if not defined
+
+void Cvar_CommandCompletion( void(*callback)(const char *s) );
+// callback with each valid string
+
+void Cvar_Reset( const char *var_name );
+
+void Cvar_SetCheatState( void );
+// reset all testing vars to a safe value
+
+qboolean Cvar_Command( void );
+// called by Cmd_ExecuteString when Cmd_Argv(0) doesn't match a known
+// command. Returns true if the command was a variable reference that
+// was handled. (print or change)
+
+void Cvar_WriteVariables( fileHandle_t f );
+// writes lines containing "set variable value" for all variables
+// with the archive flag set to true.
+
+void Cvar_Init( void );
+
+char *Cvar_InfoString( int bit );
+char *Cvar_InfoString_Big( int bit );
+// returns an info string containing all the cvars that have the given bit set
+// in their flags ( CVAR_USERINFO, CVAR_SERVERINFO, CVAR_SYSTEMINFO, etc )
+void Cvar_InfoStringBuffer( int bit, char *buff, int buffsize );
+
+void Cvar_Restart_f( void );
+
+extern int cvar_modifiedFlags;
+// whenever a cvar is modifed, its flags will be OR'd into this, so
+// a single check can determine if any CVAR_USERINFO, CVAR_SERVERINFO,
+// etc, variables have been modified since the last check. The bit
+// can then be cleared to allow another change detection.
+
+/*
+==============================================================
+
+FILESYSTEM
+
+No stdio calls should be used by any part of the game, because
+we need to deal with all sorts of directory and seperator char
+issues.
+==============================================================
+*/
+
+// referenced flags
+// these are in loop specific order so don't change the order
+#define FS_GENERAL_REF 0x01
+#define FS_UI_REF 0x02
+#define FS_CGAME_REF 0x04
+#define FS_QAGAME_REF 0x08
+// number of id paks that will never be autodownloaded from baseq3
+#define NUM_ID_PAKS 9
+
+#define MAX_FILE_HANDLES 64
+
+#define BASEGAME "baseq3"
+
+qboolean FS_Initialized();
+
+void FS_InitFilesystem (void);
+void FS_Shutdown( qboolean closemfp );
+
+qboolean FS_ConditionalRestart( int checksumFeed );
+void FS_Restart( int checksumFeed );
+// shutdown and restart the filesystem so changes to fs_gamedir can take effect
+
+char **FS_ListFiles( const char *directory, const char *extension, int *numfiles );
+// directory should not have either a leading or trailing /
+// if extension is "/", only subdirectories will be returned
+// the returned files will not include any directories or /
+
+void FS_FreeFileList( char **list );
+
+qboolean FS_FileExists( const char *file );
+
+int FS_LoadStack();
+
+int FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize );
+int FS_GetModList( char *listbuf, int bufsize );
+
+fileHandle_t FS_FOpenFileWrite( const char *qpath );
+// will properly create any needed paths and deal with seperater character issues
+
+int FS_filelength( fileHandle_t f );
+fileHandle_t FS_SV_FOpenFileWrite( const char *filename );
+int FS_SV_FOpenFileRead( const char *filename, fileHandle_t *fp );
+void FS_SV_Rename( const char *from, const char *to );
+int FS_FOpenFileRead( const char *qpath, fileHandle_t *file, qboolean uniqueFILE );
+// if uniqueFILE is true, then a new FILE will be fopened even if the file
+// is found in an already open pak file. If uniqueFILE is false, you must call
+// FS_FCloseFile instead of fclose, otherwise the pak FILE would be improperly closed
+// It is generally safe to always set uniqueFILE to true, because the majority of
+// file IO goes through FS_ReadFile, which Does The Right Thing already.
+
+int FS_FileIsInPAK(const char *filename, int *pChecksum );
+// returns 1 if a file is in the PAK file, otherwise -1
+
+int FS_Write( const void *buffer, int len, fileHandle_t f );
+
+int FS_Read2( void *buffer, int len, fileHandle_t f );
+int FS_Read( void *buffer, int len, fileHandle_t f );
+// properly handles partial reads and reads from other dlls
+
+void FS_FCloseFile( fileHandle_t f );
+// note: you can't just fclose from another DLL, due to MS libc issues
+
+int FS_ReadFile( const char *qpath, void **buffer );
+// returns the length of the file
+// a null buffer will just return the file length without loading
+// as a quick check for existance. -1 length == not present
+// A 0 byte will always be appended at the end, so string ops are safe.
+// the buffer should be considered read-only, because it may be cached
+// for other uses.
+
+void FS_ForceFlush( fileHandle_t f );
+// forces flush on files we're writing to.
+
+void FS_FreeFile( void *buffer );
+// frees the memory returned by FS_ReadFile
+
+void FS_WriteFile( const char *qpath, const void *buffer, int size );
+// writes a complete file, creating any subdirectories needed
+
+int FS_filelength( fileHandle_t f );
+// doesn't work for files that are opened from a pack file
+
+int FS_FTell( fileHandle_t f );
+// where are we?
+
+void FS_Flush( fileHandle_t f );
+
+void QDECL FS_Printf( fileHandle_t f, const char *fmt, ... );
+// like fprintf
+
+int FS_FOpenFileByMode( const char *qpath, fileHandle_t *f, fsMode_t mode );
+// opens a file for reading, writing, or appending depending on the value of mode
+
+int FS_Seek( fileHandle_t f, long offset, int origin );
+// seek on a file (doesn't work for zip files!!!!!!!!)
+
+qboolean FS_FilenameCompare( const char *s1, const char *s2 );
+
+const char *FS_GamePureChecksum( void );
+// Returns the checksum of the pk3 from which the server loaded the qagame.qvm
+
+const char *FS_LoadedPakNames( void );
+const char *FS_LoadedPakChecksums( void );
+const char *FS_LoadedPakPureChecksums( void );
+// Returns a space separated string containing the checksums of all loaded pk3 files.
+// Servers with sv_pure set will get this string and pass it to clients.
+
+const char *FS_ReferencedPakNames( void );
+const char *FS_ReferencedPakChecksums( void );
+const char *FS_ReferencedPakPureChecksums( void );
+// Returns a space separated string containing the checksums of all loaded
+// AND referenced pk3 files. Servers with sv_pure set will get this string
+// back from clients for pure validation
+
+void FS_ClearPakReferences( int flags );
+// clears referenced booleans on loaded pk3s
+
+void FS_PureServerSetReferencedPaks( const char *pakSums, const char *pakNames );
+void FS_PureServerSetLoadedPaks( const char *pakSums, const char *pakNames );
+// If the string is empty, all data sources will be allowed.
+// If not empty, only pk3 files that match one of the space
+// separated checksums will be checked for files, with the
+// sole exception of .cfg files.
+
+qboolean FS_idPak( char *pak, char *base );
+qboolean FS_ComparePaks( char *neededpaks, int len, qboolean dlstring );
+
+void FS_Rename( const char *from, const char *to );
+
+/*
+==============================================================
+
+Edit fields and command line history/completion
+
+==============================================================
+*/
+
+#define MAX_EDIT_LINE 256
+typedef struct {
+ int cursor;
+ int scroll;
+ int widthInChars;
+ char buffer[MAX_EDIT_LINE];
+} field_t;
+
+void Field_Clear( field_t *edit );
+void Field_CompleteCommand( field_t *edit );
+
+/*
+==============================================================
+
+MISC
+
+==============================================================
+*/
+
+// TTimo
+// vsnprintf is ISO/IEC 9899:1999
+// abstracting this to make it portable
+#ifdef WIN32
+#define Q_vsnprintf _vsnprintf
+#else
+// TODO: do we need Mac define?
+#define Q_vsnprintf vsnprintf
+#endif
+
+// centralizing the declarations for cl_cdkey
+// https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=470
+extern char cl_cdkey[34];
+
+// returnbed by Sys_GetProcessorId
+#define CPUID_GENERIC 0 // any unrecognized processor
+
+#define CPUID_AXP 0x10
+
+#define CPUID_INTEL_UNSUPPORTED 0x20 // Intel 386/486
+#define CPUID_INTEL_PENTIUM 0x21 // Intel Pentium or PPro
+#define CPUID_INTEL_MMX 0x22 // Intel Pentium/MMX or P2/MMX
+#define CPUID_INTEL_KATMAI 0x23 // Intel Katmai
+
+#define CPUID_AMD_3DNOW 0x30 // AMD K6 3DNOW!
+
+// TTimo
+// centralized and cleaned, that's the max string you can send to a Com_Printf / Com_DPrintf (above gets truncated)
+#define MAXPRINTMSG 4096
+
+char *CopyString( const char *in );
+void Info_Print( const char *s );
+
+void Com_BeginRedirect (char *buffer, int buffersize, void (*flush)(char *));
+void Com_EndRedirect( void );
+void QDECL Com_Printf( const char *fmt, ... );
+void QDECL Com_DPrintf( const char *fmt, ... );
+void QDECL Com_Error( int code, const char *fmt, ... );
+void Com_Quit_f( void );
+int Com_EventLoop( void );
+int Com_Milliseconds( void ); // will be journaled properly
+unsigned Com_BlockChecksum( const void *buffer, int length );
+unsigned Com_BlockChecksumKey (void *buffer, int length, int key);
+int Com_HashKey(char *string, int maxlen);
+int Com_Filter(char *filter, char *name, int casesensitive);
+int Com_FilterPath(char *filter, char *name, int casesensitive);
+int Com_RealTime(qtime_t *qtime);
+qboolean Com_SafeMode( void );
+
+void Com_StartupVariable( const char *match );
+// checks for and removes command line "+set var arg" constructs
+// if match is NULL, all set commands will be executed, otherwise
+// only a set with the exact name. Only used during startup.
+
+
+extern cvar_t *com_developer;
+extern cvar_t *com_dedicated;
+extern cvar_t *com_speeds;
+extern cvar_t *com_timescale;
+extern cvar_t *com_sv_running;
+extern cvar_t *com_cl_running;
+extern cvar_t *com_viewlog; // 0 = hidden, 1 = visible, 2 = minimized
+extern cvar_t *com_version;
+extern cvar_t *com_blood;
+extern cvar_t *com_buildScript; // for building release pak files
+extern cvar_t *com_journal;
+extern cvar_t *com_cameraMode;
+
+// both client and server must agree to pause
+extern cvar_t *cl_paused;
+extern cvar_t *sv_paused;
+
+// com_speeds times
+extern int time_game;
+extern int time_frontend;
+extern int time_backend; // renderer backend time
+
+extern int com_frameTime;
+extern int com_frameMsec;
+
+extern qboolean com_errorEntered;
+
+extern fileHandle_t com_journalFile;
+extern fileHandle_t com_journalDataFile;
+
+typedef enum {
+ TAG_FREE,
+ TAG_GENERAL,
+ TAG_BOTLIB,
+ TAG_RENDERER,
+ TAG_SMALL,
+ TAG_STATIC
+} memtag_t;
+
+/*
+
+--- low memory ----
+server vm
+server clipmap
+---mark---
+renderer initialization (shaders, etc)
+UI vm
+cgame vm
+renderer map
+renderer models
+
+---free---
+
+temp file loading
+--- high memory ---
+
+*/
+
+#if defined(_DEBUG) && !defined(BSPC)
+ #define ZONE_DEBUG
+#endif
+
+#ifdef ZONE_DEBUG
+#define Z_TagMalloc(size, tag) Z_TagMallocDebug(size, tag, #size, __FILE__, __LINE__)
+#define Z_Malloc(size) Z_MallocDebug(size, #size, __FILE__, __LINE__)
+#define S_Malloc(size) S_MallocDebug(size, #size, __FILE__, __LINE__)
+void *Z_TagMallocDebug( int size, int tag, char *label, char *file, int line ); // NOT 0 filled memory
+void *Z_MallocDebug( int size, char *label, char *file, int line ); // returns 0 filled memory
+void *S_MallocDebug( int size, char *label, char *file, int line ); // returns 0 filled memory
+#else
+void *Z_TagMalloc( int size, int tag ); // NOT 0 filled memory
+void *Z_Malloc( int size ); // returns 0 filled memory
+void *S_Malloc( int size ); // NOT 0 filled memory only for small allocations
+#endif
+void Z_Free( void *ptr );
+void Z_FreeTags( int tag );
+int Z_AvailableMemory( void );
+void Z_LogHeap( void );
+
+void Hunk_Clear( void );
+void Hunk_ClearToMark( void );
+void Hunk_SetMark( void );
+qboolean Hunk_CheckMark( void );
+void Hunk_ClearTempMemory( void );
+void *Hunk_AllocateTempMemory( int size );
+void Hunk_FreeTempMemory( void *buf );
+int Hunk_MemoryRemaining( void );
+void Hunk_Log( void);
+void Hunk_Trash( void );
+
+void Com_TouchMemory( void );
+
+// commandLine should not include the executable name (argv[0])
+void Com_Init( char *commandLine );
+void Com_Frame( void );
+void Com_Shutdown( void );
+
+
+/*
+==============================================================
+
+CLIENT / SERVER SYSTEMS
+
+==============================================================
+*/
+
+//
+// client interface
+//
+void CL_InitKeyCommands( void );
+// the keyboard binding interface must be setup before execing
+// config files, but the rest of client startup will happen later
+
+void CL_Init( void );
+void CL_Disconnect( qboolean showMainMenu );
+void CL_Shutdown( void );
+void CL_Frame( int msec );
+qboolean CL_GameCommand( void );
+void CL_KeyEvent (int key, qboolean down, unsigned time);
+
+void CL_CharEvent( int key );
+// char events are for field typing, not game control
+
+void CL_MouseEvent( int dx, int dy, int time );
+
+void CL_JoystickEvent( int axis, int value, int time );
+
+void CL_PacketEvent( netadr_t from, msg_t *msg );
+
+void CL_ConsolePrint( char *text );
+
+void CL_MapLoading( void );
+// do a screen update before starting to load a map
+// when the server is going to load a new map, the entire hunk
+// will be cleared, so the client must shutdown cgame, ui, and
+// the renderer
+
+void CL_ForwardCommandToServer( const char *string );
+// adds the current command line as a clc_clientCommand to the client message.
+// things like godmode, noclip, etc, are commands directed to the server,
+// so when they are typed in at the console, they will need to be forwarded.
+
+void CL_CDDialog( void );
+// bring up the "need a cd to play" dialog
+
+void CL_ShutdownAll( void );
+// shutdown all the client stuff
+
+void CL_FlushMemory( void );
+// dump all memory on an error
+
+void CL_StartHunkUsers( void );
+// start all the client stuff using the hunk
+
+void Key_WriteBindings( fileHandle_t f );
+// for writing the config files
+
+void S_ClearSoundBuffer( void );
+// call before filesystem access
+
+void SCR_DebugGraph (float value, int color); // FIXME: move logging to common?
+
+
+//
+// server interface
+//
+void SV_Init( void );
+void SV_Shutdown( char *finalmsg );
+void SV_Frame( int msec );
+void SV_PacketEvent( netadr_t from, msg_t *msg );
+qboolean SV_GameCommand( void );
+
+
+//
+// UI interface
+//
+qboolean UI_GameCommand( void );
+qboolean UI_usesUniqueCDKey();
+
+/*
+==============================================================
+
+NON-PORTABLE SYSTEM SERVICES
+
+==============================================================
+*/
+
+typedef enum {
+ AXIS_SIDE,
+ AXIS_FORWARD,
+ AXIS_UP,
+ AXIS_ROLL,
+ AXIS_YAW,
+ AXIS_PITCH,
+ MAX_JOYSTICK_AXIS
+} joystickAxis_t;
+
+typedef enum {
+ // bk001129 - make sure SE_NONE is zero
+ SE_NONE = 0, // evTime is still valid
+ SE_KEY, // evValue is a key code, evValue2 is the down flag
+ SE_CHAR, // evValue is an ascii char
+ SE_MOUSE, // evValue and evValue2 are reletive signed x / y moves
+ SE_JOYSTICK_AXIS, // evValue is an axis number and evValue2 is the current state (-127 to 127)
+ SE_CONSOLE, // evPtr is a char*
+ SE_PACKET // evPtr is a netadr_t followed by data bytes to evPtrLength
+} sysEventType_t;
+
+typedef struct {
+ int evTime;
+ sysEventType_t evType;
+ int evValue, evValue2;
+ int evPtrLength; // bytes of data pointed to by evPtr, for journaling
+ void *evPtr; // this must be manually freed if not NULL
+} sysEvent_t;
+
+sysEvent_t Sys_GetEvent( void );
+
+void Sys_Init (void);
+
+// general development dll loading for virtual machine testing
+// fqpath param added 7/20/02 by T.Ray - Sys_LoadDll is only called in vm.c at this time
+void * QDECL Sys_LoadDll( const char *name, char *fqpath , int (QDECL **entryPoint)(int, ...),
+ int (QDECL *systemcalls)(int, ...) );
+void Sys_UnloadDll( void *dllHandle );
+
+void Sys_UnloadGame( void );
+void *Sys_GetGameAPI( void *parms );
+
+void Sys_UnloadCGame( void );
+void *Sys_GetCGameAPI( void );
+
+void Sys_UnloadUI( void );
+void *Sys_GetUIAPI( void );
+
+//bot libraries
+void Sys_UnloadBotLib( void );
+void *Sys_GetBotLibAPI( void *parms );
+
+char *Sys_GetCurrentUser( void );
+
+void QDECL Sys_Error( const char *error, ...);
+void Sys_Quit (void);
+char *Sys_GetClipboardData( void ); // note that this isn't journaled...
+
+void Sys_Print( const char *msg );
+
+// Sys_Milliseconds should only be used for profiling purposes,
+// any game related timing information should come from event timestamps
+int Sys_Milliseconds (void);
+
+void Sys_SnapVector( float *v );
+
+// the system console is shown when a dedicated server is running
+void Sys_DisplaySystemConsole( qboolean show );
+
+int Sys_GetProcessorId( void );
+
+void Sys_BeginStreamedFile( fileHandle_t f, int readahead );
+void Sys_EndStreamedFile( fileHandle_t f );
+int Sys_StreamedRead( void *buffer, int size, int count, fileHandle_t f );
+void Sys_StreamSeek( fileHandle_t f, int offset, int origin );
+
+void Sys_ShowConsole( int level, qboolean quitOnClose );
+void Sys_SetErrorText( const char *text );
+
+void Sys_SendPacket( int length, const void *data, netadr_t to );
+
+qboolean Sys_StringToAdr( const char *s, netadr_t *a );
+//Does NOT parse port numbers, only base addresses.
+
+qboolean Sys_IsLANAddress (netadr_t adr);
+void Sys_ShowIP(void);
+
+qboolean Sys_CheckCD( void );
+
+void Sys_Mkdir( const char *path );
+char *Sys_Cwd( void );
+void Sys_SetDefaultCDPath(const char *path);
+char *Sys_DefaultCDPath(void);
+void Sys_SetDefaultInstallPath(const char *path);
+char *Sys_DefaultInstallPath(void);
+void Sys_SetDefaultHomePath(const char *path);
+char *Sys_DefaultHomePath(void);
+
+char **Sys_ListFiles( const char *directory, const char *extension, char *filter, int *numfiles, qboolean wantsubs );
+void Sys_FreeFileList( char **list );
+
+void Sys_BeginProfiling( void );
+void Sys_EndProfiling( void );
+
+qboolean Sys_LowPhysicalMemory();
+unsigned int Sys_ProcessorCount();
+
+int Sys_MonkeyShouldBeSpanked( void );
+
+/* This is based on the Adaptive Huffman algorithm described in Sayood's Data
+ * Compression book. The ranks are not actually stored, but implicitly defined
+ * by the location of a node within a doubly-linked list */
+
+#define NYT HMAX /* NYT = Not Yet Transmitted */
+#define INTERNAL_NODE (HMAX+1)
+
+typedef struct nodetype {
+ struct nodetype *left, *right, *parent; /* tree structure */
+ struct nodetype *next, *prev; /* doubly-linked list */
+ struct nodetype **head; /* highest ranked node in block */
+ int weight;
+ int symbol;
+} node_t;
+
+#define HMAX 256 /* Maximum symbol */
+
+typedef struct {
+ int blocNode;
+ int blocPtrs;
+
+ node_t* tree;
+ node_t* lhead;
+ node_t* ltail;
+ node_t* loc[HMAX+1];
+ node_t** freelist;
+
+ node_t nodeList[768];
+ node_t* nodePtrs[768];
+} huff_t;
+
+typedef struct {
+ huff_t compressor;
+ huff_t decompressor;
+} huffman_t;
+
+void Huff_Compress(msg_t *buf, int offset);
+void Huff_Decompress(msg_t *buf, int offset);
+void Huff_Init(huffman_t *huff);
+void Huff_addRef(huff_t* huff, byte ch);
+int Huff_Receive (node_t *node, int *ch, byte *fin);
+void Huff_transmit (huff_t *huff, int ch, byte *fout);
+void Huff_offsetReceive (node_t *node, int *ch, byte *fin, int *offset);
+void Huff_offsetTransmit (huff_t *huff, int ch, byte *fout, int *offset);
+void Huff_putBit( int bit, byte *fout, int *offset);
+int Huff_getBit( byte *fout, int *offset);
+
+extern huffman_t clientHuffTables;
+
+#define SV_ENCODE_START 4
+#define SV_DECODE_START 12
+#define CL_ENCODE_START 12
+#define CL_DECODE_START 4
+
+#endif // _QCOMMON_H_
diff --git a/code/qcommon/qfiles.h b/code/qcommon/qfiles.h
new file mode 100755
index 0000000..d206f3b
--- /dev/null
+++ b/code/qcommon/qfiles.h
@@ -0,0 +1,488 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __QFILES_H__
+#define __QFILES_H__
+
+//
+// qfiles.h: quake file formats
+// This file must be identical in the quake and utils directories
+//
+
+// surface geometry should not exceed these limits
+#define SHADER_MAX_VERTEXES 1000
+#define SHADER_MAX_INDEXES (6*SHADER_MAX_VERTEXES)
+
+
+// the maximum size of game relative pathnames
+#define MAX_QPATH 64
+
+/*
+========================================================================
+
+QVM files
+
+========================================================================
+*/
+
+#define VM_MAGIC 0x12721444
+typedef struct {
+ int vmMagic;
+
+ int instructionCount;
+
+ int codeOffset;
+ int codeLength;
+
+ int dataOffset;
+ int dataLength;
+ int litLength; // ( dataLength - litLength ) should be byteswapped on load
+ int bssLength; // zero filled memory appended to datalength
+} vmHeader_t;
+
+
+/*
+========================================================================
+
+PCX files are used for 8 bit images
+
+========================================================================
+*/
+
+typedef struct {
+ char manufacturer;
+ char version;
+ char encoding;
+ char bits_per_pixel;
+ unsigned short xmin,ymin,xmax,ymax;
+ unsigned short hres,vres;
+ unsigned char palette[48];
+ char reserved;
+ char color_planes;
+ unsigned short bytes_per_line;
+ unsigned short palette_type;
+ char filler[58];
+ unsigned char data; // unbounded
+} pcx_t;
+
+
+/*
+========================================================================
+
+TGA files are used for 24/32 bit images
+
+========================================================================
+*/
+
+typedef struct _TargaHeader {
+ unsigned char id_length, colormap_type, image_type;
+ unsigned short colormap_index, colormap_length;
+ unsigned char colormap_size;
+ unsigned short x_origin, y_origin, width, height;
+ unsigned char pixel_size, attributes;
+} TargaHeader;
+
+
+
+/*
+========================================================================
+
+.MD3 triangle model file format
+
+========================================================================
+*/
+
+#define MD3_IDENT (('3'<<24)+('P'<<16)+('D'<<8)+'I')
+#define MD3_VERSION 15
+
+// limits
+#define MD3_MAX_LODS 3
+#define MD3_MAX_TRIANGLES 8192 // per surface
+#define MD3_MAX_VERTS 4096 // per surface
+#define MD3_MAX_SHADERS 256 // per surface
+#define MD3_MAX_FRAMES 1024 // per model
+#define MD3_MAX_SURFACES 32 // per model
+#define MD3_MAX_TAGS 16 // per frame
+
+// vertex scales
+#define MD3_XYZ_SCALE (1.0/64)
+
+typedef struct md3Frame_s {
+ vec3_t bounds[2];
+ vec3_t localOrigin;
+ float radius;
+ char name[16];
+} md3Frame_t;
+
+typedef struct md3Tag_s {
+ char name[MAX_QPATH]; // tag name
+ vec3_t origin;
+ vec3_t axis[3];
+} md3Tag_t;
+
+/*
+** md3Surface_t
+**
+** CHUNK SIZE
+** header sizeof( md3Surface_t )
+** shaders sizeof( md3Shader_t ) * numShaders
+** triangles[0] sizeof( md3Triangle_t ) * numTriangles
+** st sizeof( md3St_t ) * numVerts
+** XyzNormals sizeof( md3XyzNormal_t ) * numVerts * numFrames
+*/
+typedef struct {
+ int ident; //
+
+ char name[MAX_QPATH]; // polyset name
+
+ int flags;
+ int numFrames; // all surfaces in a model should have the same
+
+ int numShaders; // all surfaces in a model should have the same
+ int numVerts;
+
+ int numTriangles;
+ int ofsTriangles;
+
+ int ofsShaders; // offset from start of md3Surface_t
+ int ofsSt; // texture coords are common for all frames
+ int ofsXyzNormals; // numVerts * numFrames
+
+ int ofsEnd; // next surface follows
+} md3Surface_t;
+
+typedef struct {
+ char name[MAX_QPATH];
+ int shaderIndex; // for in-game use
+} md3Shader_t;
+
+typedef struct {
+ int indexes[3];
+} md3Triangle_t;
+
+typedef struct {
+ float st[2];
+} md3St_t;
+
+typedef struct {
+ short xyz[3];
+ short normal;
+} md3XyzNormal_t;
+
+typedef struct {
+ int ident;
+ int version;
+
+ char name[MAX_QPATH]; // model name
+
+ int flags;
+
+ int numFrames;
+ int numTags;
+ int numSurfaces;
+
+ int numSkins;
+
+ int ofsFrames; // offset for first frame
+ int ofsTags; // numFrames * numTags
+ int ofsSurfaces; // first surface, others follow
+
+ int ofsEnd; // end of file
+} md3Header_t;
+
+/*
+==============================================================================
+
+MD4 file format
+
+==============================================================================
+*/
+
+#define MD4_IDENT (('4'<<24)+('P'<<16)+('D'<<8)+'I')
+#define MD4_VERSION 1
+#define MD4_MAX_BONES 128
+
+typedef struct {
+ int boneIndex; // these are indexes into the boneReferences,
+ float boneWeight; // not the global per-frame bone list
+ vec3_t offset;
+} md4Weight_t;
+
+typedef struct {
+ vec3_t normal;
+ vec2_t texCoords;
+ int numWeights;
+ md4Weight_t weights[1]; // variable sized
+} md4Vertex_t;
+
+typedef struct {
+ int indexes[3];
+} md4Triangle_t;
+
+typedef struct {
+ int ident;
+
+ char name[MAX_QPATH]; // polyset name
+ char shader[MAX_QPATH];
+ int shaderIndex; // for in-game use
+
+ int ofsHeader; // this will be a negative number
+
+ int numVerts;
+ int ofsVerts;
+
+ int numTriangles;
+ int ofsTriangles;
+
+ // Bone references are a set of ints representing all the bones
+ // present in any vertex weights for this surface. This is
+ // needed because a model may have surfaces that need to be
+ // drawn at different sort times, and we don't want to have
+ // to re-interpolate all the bones for each surface.
+ int numBoneReferences;
+ int ofsBoneReferences;
+
+ int ofsEnd; // next surface follows
+} md4Surface_t;
+
+typedef struct {
+ float matrix[3][4];
+} md4Bone_t;
+
+typedef struct {
+ vec3_t bounds[2]; // bounds of all surfaces of all LOD's for this frame
+ vec3_t localOrigin; // midpoint of bounds, used for sphere cull
+ float radius; // dist from localOrigin to corner
+ md4Bone_t bones[1]; // [numBones]
+} md4Frame_t;
+
+typedef struct {
+ int numSurfaces;
+ int ofsSurfaces; // first surface, others follow
+ int ofsEnd; // next lod follows
+} md4LOD_t;
+
+typedef struct {
+ int ident;
+ int version;
+
+ char name[MAX_QPATH]; // model name
+
+ // frames and bones are shared by all levels of detail
+ int numFrames;
+ int numBones;
+ int ofsBoneNames; // char name[ MAX_QPATH ]
+ int ofsFrames; // md4Frame_t[numFrames]
+
+ // each level of detail has completely separate sets of surfaces
+ int numLODs;
+ int ofsLODs;
+
+ int ofsEnd; // end of file
+} md4Header_t;
+
+
+/*
+==============================================================================
+
+ .BSP file format
+
+==============================================================================
+*/
+
+
+#define BSP_IDENT (('P'<<24)+('S'<<16)+('B'<<8)+'I')
+ // little-endian "IBSP"
+
+#define BSP_VERSION 46
+
+
+// there shouldn't be any problem with increasing these values at the
+// expense of more memory allocation in the utilities
+#define MAX_MAP_MODELS 0x400
+#define MAX_MAP_BRUSHES 0x8000
+#define MAX_MAP_ENTITIES 0x800
+#define MAX_MAP_ENTSTRING 0x40000
+#define MAX_MAP_SHADERS 0x400
+
+#define MAX_MAP_AREAS 0x100 // MAX_MAP_AREA_BYTES in q_shared must match!
+#define MAX_MAP_FOGS 0x100
+#define MAX_MAP_PLANES 0x20000
+#define MAX_MAP_NODES 0x20000
+#define MAX_MAP_BRUSHSIDES 0x20000
+#define MAX_MAP_LEAFS 0x20000
+#define MAX_MAP_LEAFFACES 0x20000
+#define MAX_MAP_LEAFBRUSHES 0x40000
+#define MAX_MAP_PORTALS 0x20000
+#define MAX_MAP_LIGHTING 0x800000
+#define MAX_MAP_LIGHTGRID 0x800000
+#define MAX_MAP_VISIBILITY 0x200000
+
+#define MAX_MAP_DRAW_SURFS 0x20000
+#define MAX_MAP_DRAW_VERTS 0x80000
+#define MAX_MAP_DRAW_INDEXES 0x80000
+
+
+// key / value pair sizes in the entities lump
+#define MAX_KEY 32
+#define MAX_VALUE 1024
+
+// the editor uses these predefined yaw angles to orient entities up or down
+#define ANGLE_UP -1
+#define ANGLE_DOWN -2
+
+#define LIGHTMAP_WIDTH 128
+#define LIGHTMAP_HEIGHT 128
+
+#define MAX_WORLD_COORD ( 128*1024 )
+#define MIN_WORLD_COORD ( -128*1024 )
+#define WORLD_SIZE ( MAX_WORLD_COORD - MIN_WORLD_COORD )
+
+//=============================================================================
+
+
+typedef struct {
+ int fileofs, filelen;
+} lump_t;
+
+#define LUMP_ENTITIES 0
+#define LUMP_SHADERS 1
+#define LUMP_PLANES 2
+#define LUMP_NODES 3
+#define LUMP_LEAFS 4
+#define LUMP_LEAFSURFACES 5
+#define LUMP_LEAFBRUSHES 6
+#define LUMP_MODELS 7
+#define LUMP_BRUSHES 8
+#define LUMP_BRUSHSIDES 9
+#define LUMP_DRAWVERTS 10
+#define LUMP_DRAWINDEXES 11
+#define LUMP_FOGS 12
+#define LUMP_SURFACES 13
+#define LUMP_LIGHTMAPS 14
+#define LUMP_LIGHTGRID 15
+#define LUMP_VISIBILITY 16
+#define HEADER_LUMPS 17
+
+typedef struct {
+ int ident;
+ int version;
+
+ lump_t lumps[HEADER_LUMPS];
+} dheader_t;
+
+typedef struct {
+ float mins[3], maxs[3];
+ int firstSurface, numSurfaces;
+ int firstBrush, numBrushes;
+} dmodel_t;
+
+typedef struct {
+ char shader[MAX_QPATH];
+ int surfaceFlags;
+ int contentFlags;
+} dshader_t;
+
+// planes x^1 is allways the opposite of plane x
+
+typedef struct {
+ float normal[3];
+ float dist;
+} dplane_t;
+
+typedef struct {
+ int planeNum;
+ int children[2]; // negative numbers are -(leafs+1), not nodes
+ int mins[3]; // for frustom culling
+ int maxs[3];
+} dnode_t;
+
+typedef struct {
+ int cluster; // -1 = opaque cluster (do I still store these?)
+ int area;
+
+ int mins[3]; // for frustum culling
+ int maxs[3];
+
+ int firstLeafSurface;
+ int numLeafSurfaces;
+
+ int firstLeafBrush;
+ int numLeafBrushes;
+} dleaf_t;
+
+typedef struct {
+ int planeNum; // positive plane side faces out of the leaf
+ int shaderNum;
+} dbrushside_t;
+
+typedef struct {
+ int firstSide;
+ int numSides;
+ int shaderNum; // the shader that determines the contents flags
+} dbrush_t;
+
+typedef struct {
+ char shader[MAX_QPATH];
+ int brushNum;
+ int visibleSide; // the brush side that ray tests need to clip against (-1 == none)
+} dfog_t;
+
+typedef struct {
+ vec3_t xyz;
+ float st[2];
+ float lightmap[2];
+ vec3_t normal;
+ byte color[4];
+} drawVert_t;
+
+typedef enum {
+ MST_BAD,
+ MST_PLANAR,
+ MST_PATCH,
+ MST_TRIANGLE_SOUP,
+ MST_FLARE
+} mapSurfaceType_t;
+
+typedef struct {
+ int shaderNum;
+ int fogNum;
+ int surfaceType;
+
+ int firstVert;
+ int numVerts;
+
+ int firstIndex;
+ int numIndexes;
+
+ int lightmapNum;
+ int lightmapX, lightmapY;
+ int lightmapWidth, lightmapHeight;
+
+ vec3_t lightmapOrigin;
+ vec3_t lightmapVecs[3]; // for patches, [0] and [1] are lodbounds
+
+ int patchWidth;
+ int patchHeight;
+} dsurface_t;
+
+
+#endif
diff --git a/code/qcommon/unzip.c b/code/qcommon/unzip.c
new file mode 100755
index 0000000..dd9d92e
--- /dev/null
+++ b/code/qcommon/unzip.c
@@ -0,0 +1,4299 @@
+/*****************************************************************************
+ * name: unzip.c
+ *
+ * desc: IO on .zip files using portions of zlib
+ *
+ * $Archive: /MissionPack/code/qcommon/unzip.c $
+ *
+ *****************************************************************************/
+
+#include "../client/client.h"
+#include "unzip.h"
+
+/* unzip.h -- IO for uncompress .zip files using zlib
+ Version 0.15 beta, Mar 19th, 1998,
+
+ Copyright (C) 1998 Gilles Vollant
+
+ This unzip package allow extract file from .ZIP file, compatible with PKZip 2.04g
+ WinZip, InfoZip tools and compatible.
+ Encryption and multi volume ZipFile (span) are not supported.
+ Old compressions used by old PKZip 1.x are not supported
+
+ THIS IS AN ALPHA VERSION. AT THIS STAGE OF DEVELOPPEMENT, SOMES API OR STRUCTURE
+ CAN CHANGE IN FUTURE VERSION !!
+ I WAIT FEEDBACK at mail info@winimage.com
+ Visit also http://www.winimage.com/zLibDll/unzip.htm for evolution
+
+ Condition of use and distribution are the same than zlib :
+
+ This software is provided 'as-is', without any express or implied
+ warranty. In no event will the authors be held liable for any damages
+ arising from the use of this software.
+
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
+
+
+*/
+/* for more info about .ZIP format, see
+ ftp://ftp.cdrom.com/pub/infozip/doc/appnote-970311-iz.zip
+ PkWare has also a specification at :
+ ftp://ftp.pkware.com/probdesc.zip */
+
+/* zlib.h -- interface of the 'zlib' general purpose compression library
+ version 1.1.3, July 9th, 1998
+
+ Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler
+
+ This software is provided 'as-is', without any express or implied
+ warranty. In no event will the authors be held liable for any damages
+ arising from the use of this software.
+
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
+
+ Jean-loup Gailly Mark Adler
+ jloup@gzip.org madler@alumni.caltech.edu
+
+
+ The data format used by the zlib library is described by RFCs (Request for
+ Comments) 1950 to 1952 in the files ftp://ds.internic.net/rfc/rfc1950.txt
+ (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
+*/
+
+/* zconf.h -- configuration of the zlib compression library
+ * Copyright (C) 1995-1998 Jean-loup Gailly.
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+
+#ifndef _ZCONF_H
+#define _ZCONF_H
+
+/* Maximum value for memLevel in deflateInit2 */
+#ifndef MAX_MEM_LEVEL
+# ifdef MAXSEG_64K
+# define MAX_MEM_LEVEL 8
+# else
+# define MAX_MEM_LEVEL 9
+# endif
+#endif
+
+/* Maximum value for windowBits in deflateInit2 and inflateInit2.
+ * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
+ * created by gzip. (Files created by minigzip can still be extracted by
+ * gzip.)
+ */
+#ifndef MAX_WBITS
+# define MAX_WBITS 15 /* 32K LZ77 window */
+#endif
+
+/* The memory requirements for deflate are (in bytes):
+ (1 << (windowBits+2)) + (1 << (memLevel+9))
+ that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
+ plus a few kilobytes for small objects. For example, if you want to reduce
+ the default memory requirements from 256K to 128K, compile with
+ make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
+ Of course this will generally degrade compression (there's no free lunch).
+
+ The memory requirements for inflate are (in bytes) 1 << windowBits
+ that is, 32K for windowBits=15 (default value) plus a few kilobytes
+ for small objects.
+*/
+
+ /* Type declarations */
+
+#ifndef OF /* function prototypes */
+#define OF(args) args
+#endif
+
+typedef unsigned char Byte; /* 8 bits */
+typedef unsigned int uInt; /* 16 bits or more */
+typedef unsigned long uLong; /* 32 bits or more */
+typedef Byte *voidp;
+
+#ifndef SEEK_SET
+# define SEEK_SET 0 /* Seek from beginning of file. */
+# define SEEK_CUR 1 /* Seek from current position. */
+# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
+#endif
+
+#endif /* _ZCONF_H */
+
+#define ZLIB_VERSION "1.1.3"
+
+/*
+ The 'zlib' compression library provides in-memory compression and
+ decompression functions, including integrity checks of the uncompressed
+ data. This version of the library supports only one compression method
+ (deflation) but other algorithms will be added later and will have the same
+ stream interface.
+
+ Compression can be done in a single step if the buffers are large
+ enough (for example if an input file is mmap'ed), or can be done by
+ repeated calls of the compression function. In the latter case, the
+ application must provide more input and/or consume the output
+ (providing more output space) before each call.
+
+ The library also supports reading and writing files in gzip (.gz) format
+ with an interface similar to that of stdio.
+
+ The library does not install any signal handler. The decoder checks
+ the consistency of the compressed data, so the library should never
+ crash even in case of corrupted input.
+*/
+
+/*
+ The application must update next_in and avail_in when avail_in has
+ dropped to zero. It must update next_out and avail_out when avail_out
+ has dropped to zero. The application must initialize zalloc, zfree and
+ opaque before calling the init function. All other fields are set by the
+ compression library and must not be updated by the application.
+
+ The opaque value provided by the application will be passed as the first
+ parameter for calls of zalloc and zfree. This can be useful for custom
+ memory management. The compression library attaches no meaning to the
+ opaque value.
+
+ zalloc must return Z_NULL if there is not enough memory for the object.
+ If zlib is used in a multi-threaded application, zalloc and zfree must be
+ thread safe.
+
+ On 16-bit systems, the functions zalloc and zfree must be able to allocate
+ exactly 65536 bytes, but will not be required to allocate more than this
+ if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
+ pointers returned by zalloc for objects of exactly 65536 bytes *must*
+ have their offset normalized to zero. The default allocation function
+ provided by this library ensures this (see zutil.c). To reduce memory
+ requirements and avoid any allocation of 64K objects, at the expense of
+ compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
+
+ The fields total_in and total_out can be used for statistics or
+ progress reports. After compression, total_in holds the total size of
+ the uncompressed data and may be saved for use in the decompressor
+ (particularly if the decompressor wants to decompress everything in
+ a single step).
+*/
+
+ /* constants */
+
+#define Z_NO_FLUSH 0
+#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
+#define Z_SYNC_FLUSH 2
+#define Z_FULL_FLUSH 3
+#define Z_FINISH 4
+/* Allowed flush values; see deflate() below for details */
+
+#define Z_OK 0
+#define Z_STREAM_END 1
+#define Z_NEED_DICT 2
+#define Z_ERRNO (-1)
+#define Z_STREAM_ERROR (-2)
+#define Z_DATA_ERROR (-3)
+#define Z_MEM_ERROR (-4)
+#define Z_BUF_ERROR (-5)
+#define Z_VERSION_ERROR (-6)
+/* Return codes for the compression/decompression functions. Negative
+ * values are errors, positive values are used for special but normal events.
+ */
+
+#define Z_NO_COMPRESSION 0
+#define Z_BEST_SPEED 1
+#define Z_BEST_COMPRESSION 9
+#define Z_DEFAULT_COMPRESSION (-1)
+/* compression levels */
+
+#define Z_FILTERED 1
+#define Z_HUFFMAN_ONLY 2
+#define Z_DEFAULT_STRATEGY 0
+/* compression strategy; see deflateInit2() below for details */
+
+#define Z_BINARY 0
+#define Z_ASCII 1
+#define Z_UNKNOWN 2
+/* Possible values of the data_type field */
+
+#define Z_DEFLATED 8
+/* The deflate compression method (the only one supported in this version) */
+
+#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
+
+#define zlib_version zlibVersion()
+/* for compatibility with versions < 1.0.2 */
+
+ /* basic functions */
+
+// static const char * zlibVersion OF((void));
+/* The application can compare zlibVersion and ZLIB_VERSION for consistency.
+ If the first character differs, the library code actually used is
+ not compatible with the zlib.h header file used by the application.
+ This check is automatically made by deflateInit and inflateInit.
+ */
+
+/*
+int deflateInit OF((z_streamp strm, int level));
+
+ Initializes the internal stream state for compression. The fields
+ zalloc, zfree and opaque must be initialized before by the caller.
+ If zalloc and zfree are set to Z_NULL, deflateInit updates them to
+ use default allocation functions.
+
+ The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
+ 1 gives best speed, 9 gives best compression, 0 gives no compression at
+ all (the input data is simply copied a block at a time).
+ Z_DEFAULT_COMPRESSION requests a default compromise between speed and
+ compression (currently equivalent to level 6).
+
+ deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
+ enough memory, Z_STREAM_ERROR if level is not a valid compression level,
+ Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
+ with the version assumed by the caller (ZLIB_VERSION).
+ msg is set to null if there is no error message. deflateInit does not
+ perform any compression: this will be done by deflate().
+*/
+
+
+// static int deflate OF((z_streamp strm, int flush));
+/*
+ deflate compresses as much data as possible, and stops when the input
+ buffer becomes empty or the output buffer becomes full. It may introduce some
+ output latency (reading input without producing any output) except when
+ forced to flush.
+
+ The detailed semantics are as follows. deflate performs one or both of the
+ following actions:
+
+ - Compress more input starting at next_in and update next_in and avail_in
+ accordingly. If not all input can be processed (because there is not
+ enough room in the output buffer), next_in and avail_in are updated and
+ processing will resume at this point for the next call of deflate().
+
+ - Provide more output starting at next_out and update next_out and avail_out
+ accordingly. This action is forced if the parameter flush is non zero.
+ Forcing flush frequently degrades the compression ratio, so this parameter
+ should be set only when necessary (in interactive applications).
+ Some output may be provided even if flush is not set.
+
+ Before the call of deflate(), the application should ensure that at least
+ one of the actions is possible, by providing more input and/or consuming
+ more output, and updating avail_in or avail_out accordingly; avail_out
+ should never be zero before the call. The application can consume the
+ compressed output when it wants, for example when the output buffer is full
+ (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
+ and with zero avail_out, it must be called again after making room in the
+ output buffer because there might be more output pending.
+
+ If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
+ flushed to the output buffer and the output is aligned on a byte boundary, so
+ that the decompressor can get all input data available so far. (In particular
+ avail_in is zero after the call if enough output space has been provided
+ before the call.) Flushing may degrade compression for some compression
+ algorithms and so it should be used only when necessary.
+
+ If flush is set to Z_FULL_FLUSH, all output is flushed as with
+ Z_SYNC_FLUSH, and the compression state is reset so that decompression can
+ restart from this point if previous compressed data has been damaged or if
+ random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
+ the compression.
+
+ If deflate returns with avail_out == 0, this function must be called again
+ with the same value of the flush parameter and more output space (updated
+ avail_out), until the flush is complete (deflate returns with non-zero
+ avail_out).
+
+ If the parameter flush is set to Z_FINISH, pending input is processed,
+ pending output is flushed and deflate returns with Z_STREAM_END if there
+ was enough output space; if deflate returns with Z_OK, this function must be
+ called again with Z_FINISH and more output space (updated avail_out) but no
+ more input data, until it returns with Z_STREAM_END or an error. After
+ deflate has returned Z_STREAM_END, the only possible operations on the
+ stream are deflateReset or deflateEnd.
+
+ Z_FINISH can be used immediately after deflateInit if all the compression
+ is to be done in a single step. In this case, avail_out must be at least
+ 0.1% larger than avail_in plus 12 bytes. If deflate does not return
+ Z_STREAM_END, then it must be called again as described above.
+
+ deflate() sets strm->adler to the adler32 checksum of all input read
+ so (that is, total_in bytes).
+
+ deflate() may update data_type if it can make a good guess about
+ the input data type (Z_ASCII or Z_BINARY). In doubt, the data is considered
+ binary. This field is only for information purposes and does not affect
+ the compression algorithm in any manner.
+
+ deflate() returns Z_OK if some progress has been made (more input
+ processed or more output produced), Z_STREAM_END if all input has been
+ consumed and all output has been produced (only when flush is set to
+ Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
+ if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
+ (for example avail_in or avail_out was zero).
+*/
+
+
+// static int deflateEnd OF((z_streamp strm));
+/*
+ All dynamically allocated data structures for this stream are freed.
+ This function discards any unprocessed input and does not flush any
+ pending output.
+
+ deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
+ stream state was inconsistent, Z_DATA_ERROR if the stream was freed
+ prematurely (some input or output was discarded). In the error case,
+ msg may be set but then points to a static string (which must not be
+ deallocated).
+*/
+
+
+/*
+int inflateInit OF((z_streamp strm));
+
+ Initializes the internal stream state for decompression. The fields
+ next_in, avail_in, zalloc, zfree and opaque must be initialized before by
+ the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
+ value depends on the compression method), inflateInit determines the
+ compression method from the zlib header and allocates all data structures
+ accordingly; otherwise the allocation will be deferred to the first call of
+ inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
+ use default allocation functions.
+
+ inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
+ memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
+ version assumed by the caller. msg is set to null if there is no error
+ message. inflateInit does not perform any decompression apart from reading
+ the zlib header if present: this will be done by inflate(). (So next_in and
+ avail_in may be modified, but next_out and avail_out are unchanged.)
+*/
+
+
+static int inflate OF((z_streamp strm, int flush));
+/*
+ inflate decompresses as much data as possible, and stops when the input
+ buffer becomes empty or the output buffer becomes full. It may some
+ introduce some output latency (reading input without producing any output)
+ except when forced to flush.
+
+ The detailed semantics are as follows. inflate performs one or both of the
+ following actions:
+
+ - Decompress more input starting at next_in and update next_in and avail_in
+ accordingly. If not all input can be processed (because there is not
+ enough room in the output buffer), next_in is updated and processing
+ will resume at this point for the next call of inflate().
+
+ - Provide more output starting at next_out and update next_out and avail_out
+ accordingly. inflate() provides as much output as possible, until there
+ is no more input data or no more space in the output buffer (see below
+ about the flush parameter).
+
+ Before the call of inflate(), the application should ensure that at least
+ one of the actions is possible, by providing more input and/or consuming
+ more output, and updating the next_* and avail_* values accordingly.
+ The application can consume the uncompressed output when it wants, for
+ example when the output buffer is full (avail_out == 0), or after each
+ call of inflate(). If inflate returns Z_OK and with zero avail_out, it
+ must be called again after making room in the output buffer because there
+ might be more output pending.
+
+ If the parameter flush is set to Z_SYNC_FLUSH, inflate flushes as much
+ output as possible to the output buffer. The flushing behavior of inflate is
+ not specified for values of the flush parameter other than Z_SYNC_FLUSH
+ and Z_FINISH, but the current implementation actually flushes as much output
+ as possible anyway.
+
+ inflate() should normally be called until it returns Z_STREAM_END or an
+ error. However if all decompression is to be performed in a single step
+ (a single call of inflate), the parameter flush should be set to
+ Z_FINISH. In this case all pending input is processed and all pending
+ output is flushed; avail_out must be large enough to hold all the
+ uncompressed data. (The size of the uncompressed data may have been saved
+ by the compressor for this purpose.) The next operation on this stream must
+ be inflateEnd to deallocate the decompression state. The use of Z_FINISH
+ is never required, but can be used to inform inflate that a faster routine
+ may be used for the single inflate() call.
+
+ If a preset dictionary is needed at this point (see inflateSetDictionary
+ below), inflate sets strm-adler to the adler32 checksum of the
+ dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise
+ it sets strm->adler to the adler32 checksum of all output produced
+ so (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or
+ an error code as described below. At the end of the stream, inflate()
+ checks that its computed adler32 checksum is equal to that saved by the
+ compressor and returns Z_STREAM_END only if the checksum is correct.
+
+ inflate() returns Z_OK if some progress has been made (more input processed
+ or more output produced), Z_STREAM_END if the end of the compressed data has
+ been reached and all uncompressed output has been produced, Z_NEED_DICT if a
+ preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
+ corrupted (input stream not conforming to the zlib format or incorrect
+ adler32 checksum), Z_STREAM_ERROR if the stream structure was inconsistent
+ (for example if next_in or next_out was NULL), Z_MEM_ERROR if there was not
+ enough memory, Z_BUF_ERROR if no progress is possible or if there was not
+ enough room in the output buffer when Z_FINISH is used. In the Z_DATA_ERROR
+ case, the application may then call inflateSync to look for a good
+ compression block.
+*/
+
+
+static int inflateEnd OF((z_streamp strm));
+/*
+ All dynamically allocated data structures for this stream are freed.
+ This function discards any unprocessed input and does not flush any
+ pending output.
+
+ inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
+ was inconsistent. In the error case, msg may be set but then points to a
+ static string (which must not be deallocated).
+*/
+
+ /* Advanced functions */
+
+/*
+ The following functions are needed only in some special applications.
+*/
+
+/*
+int deflateInit2 OF((z_streamp strm,
+ int level,
+ int method,
+ int windowBits,
+ int memLevel,
+ int strategy));
+
+ This is another version of deflateInit with more compression options. The
+ fields next_in, zalloc, zfree and opaque must be initialized before by
+ the caller.
+
+ The method parameter is the compression method. It must be Z_DEFLATED in
+ this version of the library.
+
+ The windowBits parameter is the base two logarithm of the window size
+ (the size of the history buffer). It should be in the range 8..15 for this
+ version of the library. Larger values of this parameter result in better
+ compression at the expense of memory usage. The default value is 15 if
+ deflateInit is used instead.
+
+ The memLevel parameter specifies how much memory should be allocated
+ for the internal compression state. memLevel=1 uses minimum memory but
+ is slow and reduces compression ratio; memLevel=9 uses maximum memory
+ for optimal speed. The default value is 8. See zconf.h for total memory
+ usage as a function of windowBits and memLevel.
+
+ The strategy parameter is used to tune the compression algorithm. Use the
+ value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
+ filter (or predictor), or Z_HUFFMAN_ONLY to force Huffman encoding only (no
+ string match). Filtered data consists mostly of small values with a
+ somewhat random distribution. In this case, the compression algorithm is
+ tuned to compress them better. The effect of Z_FILTERED is to force more
+ Huffman coding and less string matching; it is somewhat intermediate
+ between Z_DEFAULT and Z_HUFFMAN_ONLY. The strategy parameter only affects
+ the compression ratio but not the correctness of the compressed output even
+ if it is not set appropriately.
+
+ deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+ memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
+ method). msg is set to null if there is no error message. deflateInit2 does
+ not perform any compression: this will be done by deflate().
+*/
+
+/*
+static int deflateSetDictionary OF((z_streamp strm,
+ const Byte *dictionary,
+ uInt dictLength));
+*/
+/*
+ Initializes the compression dictionary from the given byte sequence
+ without producing any compressed output. This function must be called
+ immediately after deflateInit, deflateInit2 or deflateReset, before any
+ call of deflate. The compressor and decompressor must use exactly the same
+ dictionary (see inflateSetDictionary).
+
+ The dictionary should consist of strings (byte sequences) that are likely
+ to be encountered later in the data to be compressed, with the most commonly
+ used strings preferably put towards the end of the dictionary. Using a
+ dictionary is most useful when the data to be compressed is short and can be
+ predicted with good accuracy; the data can then be compressed better than
+ with the default empty dictionary.
+
+ Depending on the size of the compression data structures selected by
+ deflateInit or deflateInit2, a part of the dictionary may in effect be
+ discarded, for example if the dictionary is larger than the window size in
+ deflate or deflate2. Thus the strings most likely to be useful should be
+ put at the end of the dictionary, not at the front.
+
+ Upon return of this function, strm->adler is set to the Adler32 value
+ of the dictionary; the decompressor may later use this value to determine
+ which dictionary has been used by the compressor. (The Adler32 value
+ applies to the whole dictionary even if only a subset of the dictionary is
+ actually used by the compressor.)
+
+ deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
+ parameter is invalid (such as NULL dictionary) or the stream state is
+ inconsistent (for example if deflate has already been called for this stream
+ or if the compression method is bsort). deflateSetDictionary does not
+ perform any compression: this will be done by deflate().
+*/
+
+/*
+static int deflateCopy OF((z_streamp dest,
+ z_streamp source));
+*/
+/*
+ Sets the destination stream as a complete copy of the source stream.
+
+ This function can be useful when several compression strategies will be
+ tried, for example when there are several ways of pre-processing the input
+ data with a filter. The streams that will be discarded should then be freed
+ by calling deflateEnd. Note that deflateCopy duplicates the internal
+ compression state which can be quite large, so this strategy is slow and
+ can consume lots of memory.
+
+ deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
+ enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
+ (such as zalloc being NULL). msg is left unchanged in both source and
+ destination.
+*/
+
+// static int deflateReset OF((z_streamp strm));
+/*
+ This function is equivalent to deflateEnd followed by deflateInit,
+ but does not free and reallocate all the internal compression state.
+ The stream will keep the same compression level and any other attributes
+ that may have been set by deflateInit2.
+
+ deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
+ stream state was inconsistent (such as zalloc or state being NULL).
+*/
+
+/*
+static int deflateParams OF((z_streamp strm,
+ int level,
+ int strategy));
+*/
+/*
+ Dynamically update the compression level and compression strategy. The
+ interpretation of level and strategy is as in deflateInit2. This can be
+ used to switch between compression and straight copy of the input data, or
+ to switch to a different kind of input data requiring a different
+ strategy. If the compression level is changed, the input available so far
+ is compressed with the old level (and may be flushed); the new level will
+ take effect only at the next call of deflate().
+
+ Before the call of deflateParams, the stream state must be set as for
+ a call of deflate(), since the currently available input may have to
+ be compressed and flushed. In particular, strm->avail_out must be non-zero.
+
+ deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
+ stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
+ if strm->avail_out was zero.
+*/
+
+/*
+int inflateInit2 OF((z_streamp strm,
+ int windowBits));
+
+ This is another version of inflateInit with an extra parameter. The
+ fields next_in, avail_in, zalloc, zfree and opaque must be initialized
+ before by the caller.
+
+ The windowBits parameter is the base two logarithm of the maximum window
+ size (the size of the history buffer). It should be in the range 8..15 for
+ this version of the library. The default value is 15 if inflateInit is used
+ instead. If a compressed stream with a larger window size is given as
+ input, inflate() will return with the error code Z_DATA_ERROR instead of
+ trying to allocate a larger window.
+
+ inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+ memory, Z_STREAM_ERROR if a parameter is invalid (such as a negative
+ memLevel). msg is set to null if there is no error message. inflateInit2
+ does not perform any decompression apart from reading the zlib header if
+ present: this will be done by inflate(). (So next_in and avail_in may be
+ modified, but next_out and avail_out are unchanged.)
+*/
+
+/*
+static int inflateSetDictionary OF((z_streamp strm,
+ const Byte *dictionary,
+ uInt dictLength));
+*/
+/*
+ Initializes the decompression dictionary from the given uncompressed byte
+ sequence. This function must be called immediately after a call of inflate
+ if this call returned Z_NEED_DICT. The dictionary chosen by the compressor
+ can be determined from the Adler32 value returned by this call of
+ inflate. The compressor and decompressor must use exactly the same
+ dictionary (see deflateSetDictionary).
+
+ inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
+ parameter is invalid (such as NULL dictionary) or the stream state is
+ inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
+ expected one (incorrect Adler32 value). inflateSetDictionary does not
+ perform any decompression: this will be done by subsequent calls of
+ inflate().
+*/
+
+// static int inflateSync OF((z_streamp strm));
+/*
+ Skips invalid compressed data until a full flush point (see above the
+ description of deflate with Z_FULL_FLUSH) can be found, or until all
+ available input is skipped. No output is provided.
+
+ inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
+ if no more input was provided, Z_DATA_ERROR if no flush point has been found,
+ or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
+ case, the application may save the current current value of total_in which
+ indicates where valid compressed data was found. In the error case, the
+ application may repeatedly call inflateSync, providing more input each time,
+ until success or end of the input data.
+*/
+
+static int inflateReset OF((z_streamp strm));
+/*
+ This function is equivalent to inflateEnd followed by inflateInit,
+ but does not free and reallocate all the internal decompression state.
+ The stream will keep attributes that may have been set by inflateInit2.
+
+ inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
+ stream state was inconsistent (such as zalloc or state being NULL).
+*/
+
+
+ /* utility functions */
+
+/*
+ The following utility functions are implemented on top of the
+ basic stream-oriented functions. To simplify the interface, some
+ default options are assumed (compression level and memory usage,
+ standard memory allocation functions). The source code of these
+ utility functions can easily be modified if you need special options.
+*/
+
+/*
+static int compress OF((Byte *dest, uLong *destLen,
+ const Byte *source, uLong sourceLen));
+*/
+/*
+ Compresses the source buffer into the destination buffer. sourceLen is
+ the byte length of the source buffer. Upon entry, destLen is the total
+ size of the destination buffer, which must be at least 0.1% larger than
+ sourceLen plus 12 bytes. Upon exit, destLen is the actual size of the
+ compressed buffer.
+ This function can be used to compress a whole file at once if the
+ input file is mmap'ed.
+ compress returns Z_OK if success, Z_MEM_ERROR if there was not
+ enough memory, Z_BUF_ERROR if there was not enough room in the output
+ buffer.
+*/
+
+/*
+static int compress2 OF((Byte *dest, uLong *destLen,
+ const Byte *source, uLong sourceLen,
+ int level));
+*/
+/*
+ Compresses the source buffer into the destination buffer. The level
+ parameter has the same meaning as in deflateInit. sourceLen is the byte
+ length of the source buffer. Upon entry, destLen is the total size of the
+ destination buffer, which must be at least 0.1% larger than sourceLen plus
+ 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
+
+ compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+ memory, Z_BUF_ERROR if there was not enough room in the output buffer,
+ Z_STREAM_ERROR if the level parameter is invalid.
+*/
+
+/*
+static int uncompress OF((Byte *dest, uLong *destLen,
+ const Byte *source, uLong sourceLen));
+*/
+/*
+ Decompresses the source buffer into the destination buffer. sourceLen is
+ the byte length of the source buffer. Upon entry, destLen is the total
+ size of the destination buffer, which must be large enough to hold the
+ entire uncompressed data. (The size of the uncompressed data must have
+ been saved previously by the compressor and transmitted to the decompressor
+ by some mechanism outside the scope of this compression library.)
+ Upon exit, destLen is the actual size of the compressed buffer.
+ This function can be used to decompress a whole file at once if the
+ input file is mmap'ed.
+
+ uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
+ enough memory, Z_BUF_ERROR if there was not enough room in the output
+ buffer, or Z_DATA_ERROR if the input data was corrupted.
+*/
+
+
+typedef voidp gzFile;
+
+gzFile gzopen OF((const char *path, const char *mode));
+/*
+ Opens a gzip (.gz) file for reading or writing. The mode parameter
+ is as in fopen ("rb" or "wb") but can also include a compression level
+ ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
+ Huffman only compression as in "wb1h". (See the description
+ of deflateInit2 for more information about the strategy parameter.)
+
+ gzopen can be used to read a file which is not in gzip format; in this
+ case gzread will directly read from the file without decompression.
+
+ gzopen returns NULL if the file could not be opened or if there was
+ insufficient memory to allocate the (de)compression state; errno
+ can be checked to distinguish the two cases (if errno is zero, the
+ zlib error is Z_MEM_ERROR). */
+
+gzFile gzdopen OF((int fd, const char *mode));
+/*
+ gzdopen() associates a gzFile with the file descriptor fd. File
+ descriptors are obtained from calls like open, dup, creat, pipe or
+ fileno (in the file has been previously opened with fopen).
+ The mode parameter is as in gzopen.
+ The next call of gzclose on the returned gzFile will also close the
+ file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
+ descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
+ gzdopen returns NULL if there was insufficient memory to allocate
+ the (de)compression state.
+*/
+
+int gzsetparams OF((gzFile file, int level, int strategy));
+/*
+ Dynamically update the compression level or strategy. See the description
+ of deflateInit2 for the meaning of these parameters.
+ gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
+ opened for writing.
+*/
+
+int gzread OF((gzFile file, voidp buf, unsigned len));
+/*
+ Reads the given number of uncompressed bytes from the compressed file.
+ If the input file was not in gzip format, gzread copies the given number
+ of bytes into the buffer.
+ gzread returns the number of uncompressed bytes actually read (0 for
+ end of file, -1 for error). */
+
+int gzwrite OF((gzFile file,
+ const voidp buf, unsigned len));
+/*
+ Writes the given number of uncompressed bytes into the compressed file.
+ gzwrite returns the number of uncompressed bytes actually written
+ (0 in case of error).
+*/
+
+int QDECL gzprintf OF((gzFile file, const char *format, ...));
+/*
+ Converts, formats, and writes the args to the compressed file under
+ control of the format string, as in fprintf. gzprintf returns the number of
+ uncompressed bytes actually written (0 in case of error).
+*/
+
+int gzputs OF((gzFile file, const char *s));
+/*
+ Writes the given null-terminated string to the compressed file, excluding
+ the terminating null character.
+ gzputs returns the number of characters written, or -1 in case of error.
+*/
+
+char * gzgets OF((gzFile file, char *buf, int len));
+/*
+ Reads bytes from the compressed file until len-1 characters are read, or
+ a newline character is read and transferred to buf, or an end-of-file
+ condition is encountered. The string is then terminated with a null
+ character.
+ gzgets returns buf, or Z_NULL in case of error.
+*/
+
+int gzputc OF((gzFile file, int c));
+/*
+ Writes c, converted to an unsigned char, into the compressed file.
+ gzputc returns the value that was written, or -1 in case of error.
+*/
+
+int gzgetc OF((gzFile file));
+/*
+ Reads one byte from the compressed file. gzgetc returns this byte
+ or -1 in case of end of file or error.
+*/
+
+int gzflush OF((gzFile file, int flush));
+/*
+ Flushes all pending output into the compressed file. The parameter
+ flush is as in the deflate() function. The return value is the zlib
+ error number (see function gzerror below). gzflush returns Z_OK if
+ the flush parameter is Z_FINISH and all output could be flushed.
+ gzflush should be called only when strictly necessary because it can
+ degrade compression.
+*/
+
+long gzseek OF((gzFile file,
+ long offset, int whence));
+/*
+ Sets the starting position for the next gzread or gzwrite on the
+ given compressed file. The offset represents a number of bytes in the
+ uncompressed data stream. The whence parameter is defined as in lseek(2);
+ the value SEEK_END is not supported.
+ If the file is opened for reading, this function is emulated but can be
+ extremely slow. If the file is opened for writing, only forward seeks are
+ supported; gzseek then compresses a sequence of zeroes up to the new
+ starting position.
+
+ gzseek returns the resulting offset location as measured in bytes from
+ the beginning of the uncompressed stream, or -1 in case of error, in
+ particular if the file is opened for writing and the new starting position
+ would be before the current position.
+*/
+
+int gzrewind OF((gzFile file));
+/*
+ Rewinds the given file. This function is supported only for reading.
+
+ gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
+*/
+
+long gztell OF((gzFile file));
+/*
+ Returns the starting position for the next gzread or gzwrite on the
+ given compressed file. This position represents a number of bytes in the
+ uncompressed data stream.
+
+ gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
+*/
+
+int gzeof OF((gzFile file));
+/*
+ Returns 1 when EOF has previously been detected reading the given
+ input stream, otherwise zero.
+*/
+
+int gzclose OF((gzFile file));
+/*
+ Flushes all pending output if necessary, closes the compressed file
+ and deallocates all the (de)compression state. The return value is the zlib
+ error number (see function gzerror below).
+*/
+
+// static const char * gzerror OF((gzFile file, int *errnum));
+/*
+ Returns the error message for the last error which occurred on the
+ given compressed file. errnum is set to zlib error number. If an
+ error occurred in the file system and not in the compression library,
+ errnum is set to Z_ERRNO and the application may consult errno
+ to get the exact error code.
+*/
+
+ /* checksum functions */
+
+/*
+ These functions are not related to compression but are exported
+ anyway because they might be useful in applications using the
+ compression library.
+*/
+
+static uLong adler32 OF((uLong adler, const Byte *buf, uInt len));
+
+/*
+ Update a running Adler-32 checksum with the bytes buf[0..len-1] and
+ return the updated checksum. If buf is NULL, this function returns
+ the required initial value for the checksum.
+ An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
+ much faster. Usage example:
+
+ uLong adler = adler32(0L, Z_NULL, 0);
+
+ while (read_buffer(buffer, length) != EOF) {
+ adler = adler32(adler, buffer, length);
+ }
+ if (adler != original_adler) error();
+*/
+
+ /* various hacks, don't look :) */
+
+/* deflateInit and inflateInit are macros to allow checking the zlib version
+ * and the compiler's view of z_stream:
+ */
+/*
+static int deflateInit_ OF((z_streamp strm, int level,
+ const char *version, int stream_size));
+static int inflateInit_ OF((z_streamp strm,
+ const char *version, int stream_size));
+static int deflateInit2_ OF((z_streamp strm, int level, int method,
+ int windowBits, int memLevel,
+ int strategy, const char *version,
+ int stream_size));
+*/
+static int inflateInit2_ OF((z_streamp strm, int windowBits,
+ const char *version, int stream_size));
+
+#define deflateInit(strm, level) \
+ deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
+#define inflateInit(strm) \
+ inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
+#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
+ deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
+ (strategy), ZLIB_VERSION, sizeof(z_stream))
+#define inflateInit2(strm, windowBits) \
+ inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
+
+
+// static const char * zError OF((int err));
+// static int inflateSyncPoint OF((z_streamp z));
+// static const uLong * get_crc_table OF((void));
+
+typedef unsigned char uch;
+typedef unsigned short ush;
+typedef unsigned long ulg;
+
+// static const char *z_errmsg[10]; /* indexed by 2-zlib_error */
+/* (size given to avoid silly warnings with Visual C++) */
+
+#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
+
+#define ERR_RETURN(strm,err) \
+ return (strm->msg = (char*)ERR_MSG(err), (err))
+/* To be used only when the state is known to be valid */
+
+ /* common constants */
+
+#ifndef DEF_WBITS
+# define DEF_WBITS MAX_WBITS
+#endif
+/* default windowBits for decompression. MAX_WBITS is for compression only */
+
+#if MAX_MEM_LEVEL >= 8
+# define DEF_MEM_LEVEL 8
+#else
+# define DEF_MEM_LEVEL MAX_MEM_LEVEL
+#endif
+/* default memLevel */
+
+#define STORED_BLOCK 0
+#define STATIC_TREES 1
+#define DYN_TREES 2
+/* The three kinds of block type */
+
+#define MIN_MATCH 3
+#define MAX_MATCH 258
+/* The minimum and maximum match lengths */
+
+#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
+
+ /* target dependencies */
+
+ /* Common defaults */
+
+#ifndef OS_CODE
+# define OS_CODE 0x03 /* assume Unix */
+#endif
+
+#ifndef F_OPEN
+# define F_OPEN(name, mode) fopen((name), (mode))
+#endif
+
+ /* functions */
+
+#ifdef HAVE_STRERROR
+ extern char *strerror OF((int));
+# define zstrerror(errnum) strerror(errnum)
+#else
+# define zstrerror(errnum) ""
+#endif
+
+#define zmemcpy Com_Memcpy
+#define zmemcmp memcmp
+#define zmemzero(dest, len) Com_Memset(dest, 0, len)
+
+/* Diagnostic functions */
+#ifdef _ZIP_DEBUG_
+ int z_verbose = 0;
+# define Assert(cond,msg) assert(cond);
+ //{if(!(cond)) Sys_Error(msg);}
+# define Trace(x) {if (z_verbose>=0) Sys_Error x ;}
+# define Tracev(x) {if (z_verbose>0) Sys_Error x ;}
+# define Tracevv(x) {if (z_verbose>1) Sys_Error x ;}
+# define Tracec(c,x) {if (z_verbose>0 && (c)) Sys_Error x ;}
+# define Tracecv(c,x) {if (z_verbose>1 && (c)) Sys_Error x ;}
+#else
+# define Assert(cond,msg)
+# define Trace(x)
+# define Tracev(x)
+# define Tracevv(x)
+# define Tracec(c,x)
+# define Tracecv(c,x)
+#endif
+
+
+typedef uLong (*check_func) OF((uLong check, const Byte *buf, uInt len));
+static voidp zcalloc OF((voidp opaque, unsigned items, unsigned size));
+static void zcfree OF((voidp opaque, voidp ptr));
+
+#define ZALLOC(strm, items, size) \
+ (*((strm)->zalloc))((strm)->opaque, (items), (size))
+#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidp)(addr))
+#define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
+
+
+#if !defined(unix) && !defined(CASESENSITIVITYDEFAULT_YES) && \
+ !defined(CASESENSITIVITYDEFAULT_NO)
+#define CASESENSITIVITYDEFAULT_NO
+#endif
+
+
+#ifndef UNZ_BUFSIZE
+#define UNZ_BUFSIZE (65536)
+#endif
+
+#ifndef UNZ_MAXFILENAMEINZIP
+#define UNZ_MAXFILENAMEINZIP (256)
+#endif
+
+#ifndef ALLOC
+# define ALLOC(size) (Z_Malloc(size))
+#endif
+#ifndef TRYFREE
+# define TRYFREE(p) {if (p) Z_Free(p);}
+#endif
+
+#define SIZECENTRALDIRITEM (0x2e)
+#define SIZEZIPLOCALHEADER (0x1e)
+
+
+
+/* ===========================================================================
+ Read a byte from a gz_stream; update next_in and avail_in. Return EOF
+ for end of file.
+ IN assertion: the stream s has been sucessfully opened for reading.
+*/
+
+/*
+static int unzlocal_getByte(FILE *fin,int *pi)
+{
+ unsigned char c;
+ int err = fread(&c, 1, 1, fin);
+ if (err==1)
+ {
+ *pi = (int)c;
+ return UNZ_OK;
+ }
+ else
+ {
+ if (ferror(fin))
+ return UNZ_ERRNO;
+ else
+ return UNZ_EOF;
+ }
+}
+*/
+
+/* ===========================================================================
+ Reads a long in LSB order from the given gz_stream. Sets
+*/
+static int unzlocal_getShort (FILE* fin, uLong *pX)
+{
+ short v;
+
+ fread( &v, sizeof(v), 1, fin );
+
+ *pX = LittleShort( v);
+ return UNZ_OK;
+
+/*
+ uLong x ;
+ int i;
+ int err;
+
+ err = unzlocal_getByte(fin,&i);
+ x = (uLong)i;
+
+ if (err==UNZ_OK)
+ err = unzlocal_getByte(fin,&i);
+ x += ((uLong)i)<<8;
+
+ if (err==UNZ_OK)
+ *pX = x;
+ else
+ *pX = 0;
+ return err;
+*/
+}
+
+static int unzlocal_getLong (FILE *fin, uLong *pX)
+{
+ int v;
+
+ fread( &v, sizeof(v), 1, fin );
+
+ *pX = LittleLong( v);
+ return UNZ_OK;
+
+/*
+ uLong x ;
+ int i;
+ int err;
+
+ err = unzlocal_getByte(fin,&i);
+ x = (uLong)i;
+
+ if (err==UNZ_OK)
+ err = unzlocal_getByte(fin,&i);
+ x += ((uLong)i)<<8;
+
+ if (err==UNZ_OK)
+ err = unzlocal_getByte(fin,&i);
+ x += ((uLong)i)<<16;
+
+ if (err==UNZ_OK)
+ err = unzlocal_getByte(fin,&i);
+ x += ((uLong)i)<<24;
+
+ if (err==UNZ_OK)
+ *pX = x;
+ else
+ *pX = 0;
+ return err;
+*/
+}
+
+
+/* My own strcmpi / strcasecmp */
+static int strcmpcasenosensitive_internal (const char* fileName1,const char* fileName2)
+{
+ for (;;)
+ {
+ char c1=*(fileName1++);
+ char c2=*(fileName2++);
+ if ((c1>='a') && (c1<='z'))
+ c1 -= 0x20;
+ if ((c2>='a') && (c2<='z'))
+ c2 -= 0x20;
+ if (c1=='\0')
+ return ((c2=='\0') ? 0 : -1);
+ if (c2=='\0')
+ return 1;
+ if (c1<c2)
+ return -1;
+ if (c1>c2)
+ return 1;
+ }
+}
+
+
+#ifdef CASESENSITIVITYDEFAULT_NO
+#define CASESENSITIVITYDEFAULTVALUE 2
+#else
+#define CASESENSITIVITYDEFAULTVALUE 1
+#endif
+
+#ifndef STRCMPCASENOSENTIVEFUNCTION
+#define STRCMPCASENOSENTIVEFUNCTION strcmpcasenosensitive_internal
+#endif
+
+/*
+ Compare two filename (fileName1,fileName2).
+ If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp)
+ If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi
+ or strcasecmp)
+ If iCaseSenisivity = 0, case sensitivity is defaut of your operating system
+ (like 1 on Unix, 2 on Windows)
+
+*/
+extern int unzStringFileNameCompare (const char* fileName1,const char* fileName2,int iCaseSensitivity)
+{
+ if (iCaseSensitivity==0)
+ iCaseSensitivity=CASESENSITIVITYDEFAULTVALUE;
+
+ if (iCaseSensitivity==1)
+ return strcmp(fileName1,fileName2);
+
+ return STRCMPCASENOSENTIVEFUNCTION(fileName1,fileName2);
+}
+
+#define BUFREADCOMMENT (0x400)
+
+/*
+ Locate the Central directory of a zipfile (at the end, just before
+ the global comment)
+*/
+extern uLong unzlocal_SearchCentralDir(FILE *fin)
+{
+ unsigned char* buf;
+ uLong uSizeFile;
+ uLong uBackRead;
+ uLong uMaxBack=0xffff; /* maximum size of global comment */
+ uLong uPosFound=0;
+
+ if (fseek(fin,0,SEEK_END) != 0)
+ return 0;
+
+
+ uSizeFile = ftell( fin );
+
+ if (uMaxBack>uSizeFile)
+ uMaxBack = uSizeFile;
+
+ buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4);
+ if (buf==NULL)
+ return 0;
+
+ uBackRead = 4;
+ while (uBackRead<uMaxBack)
+ {
+ uLong uReadSize,uReadPos ;
+ int i;
+ if (uBackRead+BUFREADCOMMENT>uMaxBack)
+ uBackRead = uMaxBack;
+ else
+ uBackRead+=BUFREADCOMMENT;
+ uReadPos = uSizeFile-uBackRead ;
+
+ uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ?
+ (BUFREADCOMMENT+4) : (uSizeFile-uReadPos);
+ if (fseek(fin,uReadPos,SEEK_SET)!=0)
+ break;
+
+ if (fread(buf,(uInt)uReadSize,1,fin)!=1)
+ break;
+
+ for (i=(int)uReadSize-3; (i--)>0;)
+ if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) &&
+ ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06))
+ {
+ uPosFound = uReadPos+i;
+ break;
+ }
+
+ if (uPosFound!=0)
+ break;
+ }
+ TRYFREE(buf);
+ return uPosFound;
+}
+
+extern unzFile unzReOpen (const char* path, unzFile file)
+{
+ unz_s *s;
+ FILE * fin;
+
+ fin=fopen(path,"rb");
+ if (fin==NULL)
+ return NULL;
+
+ s=(unz_s*)ALLOC(sizeof(unz_s));
+ Com_Memcpy(s, (unz_s*)file, sizeof(unz_s));
+
+ s->file = fin;
+ return (unzFile)s;
+}
+
+/*
+ Open a Zip file. path contain the full pathname (by example,
+ on a Windows NT computer "c:\\test\\zlib109.zip" or on an Unix computer
+ "zlib/zlib109.zip".
+ If the zipfile cannot be opened (file don't exist or in not valid), the
+ return value is NULL.
+ Else, the return value is a unzFile Handle, usable with other function
+ of this unzip package.
+*/
+extern unzFile unzOpen (const char* path)
+{
+ unz_s us;
+ unz_s *s;
+ uLong central_pos,uL;
+ FILE * fin ;
+
+ uLong number_disk; /* number of the current dist, used for
+ spaning ZIP, unsupported, always 0*/
+ uLong number_disk_with_CD; /* number the the disk with central dir, used
+ for spaning ZIP, unsupported, always 0*/
+ uLong number_entry_CD; /* total number of entries in
+ the central dir
+ (same than number_entry on nospan) */
+
+ int err=UNZ_OK;
+
+ fin=fopen(path,"rb");
+ if (fin==NULL)
+ return NULL;
+
+ central_pos = unzlocal_SearchCentralDir(fin);
+ if (central_pos==0)
+ err=UNZ_ERRNO;
+
+ if (fseek(fin,central_pos,SEEK_SET)!=0)
+ err=UNZ_ERRNO;
+
+ /* the signature, already checked */
+ if (unzlocal_getLong(fin,&uL)!=UNZ_OK)
+ err=UNZ_ERRNO;
+
+ /* number of this disk */
+ if (unzlocal_getShort(fin,&number_disk)!=UNZ_OK)
+ err=UNZ_ERRNO;
+
+ /* number of the disk with the start of the central directory */
+ if (unzlocal_getShort(fin,&number_disk_with_CD)!=UNZ_OK)
+ err=UNZ_ERRNO;
+
+ /* total number of entries in the central dir on this disk */
+ if (unzlocal_getShort(fin,&us.gi.number_entry)!=UNZ_OK)
+ err=UNZ_ERRNO;
+
+ /* total number of entries in the central dir */
+ if (unzlocal_getShort(fin,&number_entry_CD)!=UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if ((number_entry_CD!=us.gi.number_entry) ||
+ (number_disk_with_CD!=0) ||
+ (number_disk!=0))
+ err=UNZ_BADZIPFILE;
+
+ /* size of the central directory */
+ if (unzlocal_getLong(fin,&us.size_central_dir)!=UNZ_OK)
+ err=UNZ_ERRNO;
+
+ /* offset of start of central directory with respect to the
+ starting disk number */
+ if (unzlocal_getLong(fin,&us.offset_central_dir)!=UNZ_OK)
+ err=UNZ_ERRNO;
+
+ /* zipfile comment length */
+ if (unzlocal_getShort(fin,&us.gi.size_comment)!=UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if ((central_pos<us.offset_central_dir+us.size_central_dir) &&
+ (err==UNZ_OK))
+ err=UNZ_BADZIPFILE;
+
+ if (err!=UNZ_OK)
+ {
+ fclose(fin);
+ return NULL;
+ }
+
+ us.file=fin;
+ us.byte_before_the_zipfile = central_pos -
+ (us.offset_central_dir+us.size_central_dir);
+ us.central_pos = central_pos;
+ us.pfile_in_zip_read = NULL;
+
+
+ s=(unz_s*)ALLOC(sizeof(unz_s));
+ *s=us;
+// unzGoToFirstFile((unzFile)s);
+ return (unzFile)s;
+}
+
+
+/*
+ Close a ZipFile opened with unzipOpen.
+ If there is files inside the .Zip opened with unzipOpenCurrentFile (see later),
+ these files MUST be closed with unzipCloseCurrentFile before call unzipClose.
+ return UNZ_OK if there is no problem. */
+extern int unzClose (unzFile file)
+{
+ unz_s* s;
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+
+ if (s->pfile_in_zip_read!=NULL)
+ unzCloseCurrentFile(file);
+
+ fclose(s->file);
+ TRYFREE(s);
+ return UNZ_OK;
+}
+
+
+/*
+ Write info about the ZipFile in the *pglobal_info structure.
+ No preparation of the structure is needed
+ return UNZ_OK if there is no problem. */
+extern int unzGetGlobalInfo (unzFile file,unz_global_info *pglobal_info)
+{
+ unz_s* s;
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+ *pglobal_info=s->gi;
+ return UNZ_OK;
+}
+
+
+/*
+ Translate date/time from Dos format to tm_unz (readable more easilty)
+*/
+static void unzlocal_DosDateToTmuDate (uLong ulDosDate, tm_unz* ptm)
+{
+ uLong uDate;
+ uDate = (uLong)(ulDosDate>>16);
+ ptm->tm_mday = (uInt)(uDate&0x1f) ;
+ ptm->tm_mon = (uInt)((((uDate)&0x1E0)/0x20)-1) ;
+ ptm->tm_year = (uInt)(((uDate&0x0FE00)/0x0200)+1980) ;
+
+ ptm->tm_hour = (uInt) ((ulDosDate &0xF800)/0x800);
+ ptm->tm_min = (uInt) ((ulDosDate&0x7E0)/0x20) ;
+ ptm->tm_sec = (uInt) (2*(ulDosDate&0x1f)) ;
+}
+
+/*
+ Get Info about the current file in the zipfile, with internal only info
+*/
+static int unzlocal_GetCurrentFileInfoInternal (unzFile file,
+ unz_file_info *pfile_info,
+ unz_file_info_internal
+ *pfile_info_internal,
+ char *szFileName,
+ uLong fileNameBufferSize,
+ void *extraField,
+ uLong extraFieldBufferSize,
+ char *szComment,
+ uLong commentBufferSize)
+{
+ unz_s* s;
+ unz_file_info file_info;
+ unz_file_info_internal file_info_internal;
+ int err=UNZ_OK;
+ uLong uMagic;
+ long lSeek=0;
+
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+ if (fseek(s->file,s->pos_in_central_dir+s->byte_before_the_zipfile,SEEK_SET)!=0)
+ err=UNZ_ERRNO;
+
+
+ /* we check the magic */
+ if (err==UNZ_OK) {
+ if (unzlocal_getLong(s->file,&uMagic) != UNZ_OK)
+ err=UNZ_ERRNO;
+ else if (uMagic!=0x02014b50)
+ err=UNZ_BADZIPFILE;
+ }
+ if (unzlocal_getShort(s->file,&file_info.version) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getShort(s->file,&file_info.version_needed) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getShort(s->file,&file_info.flag) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getShort(s->file,&file_info.compression_method) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getLong(s->file,&file_info.dosDate) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ unzlocal_DosDateToTmuDate(file_info.dosDate,&file_info.tmu_date);
+
+ if (unzlocal_getLong(s->file,&file_info.crc) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getLong(s->file,&file_info.compressed_size) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getLong(s->file,&file_info.uncompressed_size) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getShort(s->file,&file_info.size_filename) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getShort(s->file,&file_info.size_file_extra) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getShort(s->file,&file_info.size_file_comment) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getShort(s->file,&file_info.disk_num_start) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getShort(s->file,&file_info.internal_fa) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getLong(s->file,&file_info.external_fa) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getLong(s->file,&file_info_internal.offset_curfile) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ lSeek+=file_info.size_filename;
+ if ((err==UNZ_OK) && (szFileName!=NULL))
+ {
+ uLong uSizeRead ;
+ if (file_info.size_filename<fileNameBufferSize)
+ {
+ *(szFileName+file_info.size_filename)='\0';
+ uSizeRead = file_info.size_filename;
+ }
+ else
+ uSizeRead = fileNameBufferSize;
+
+ if ((file_info.size_filename>0) && (fileNameBufferSize>0))
+ if (fread(szFileName,(uInt)uSizeRead,1,s->file)!=1)
+ err=UNZ_ERRNO;
+ lSeek -= uSizeRead;
+ }
+
+
+ if ((err==UNZ_OK) && (extraField!=NULL))
+ {
+ uLong uSizeRead ;
+ if (file_info.size_file_extra<extraFieldBufferSize)
+ uSizeRead = file_info.size_file_extra;
+ else
+ uSizeRead = extraFieldBufferSize;
+
+ if (lSeek!=0) {
+ if (fseek(s->file,lSeek,SEEK_CUR)==0)
+ lSeek=0;
+ else
+ err=UNZ_ERRNO;
+ }
+ if ((file_info.size_file_extra>0) && (extraFieldBufferSize>0)) {
+ if (fread(extraField,(uInt)uSizeRead,1,s->file)!=1)
+ err=UNZ_ERRNO;
+ }
+ lSeek += file_info.size_file_extra - uSizeRead;
+ }
+ else
+ lSeek+=file_info.size_file_extra;
+
+
+ if ((err==UNZ_OK) && (szComment!=NULL))
+ {
+ uLong uSizeRead ;
+ if (file_info.size_file_comment<commentBufferSize)
+ {
+ *(szComment+file_info.size_file_comment)='\0';
+ uSizeRead = file_info.size_file_comment;
+ }
+ else
+ uSizeRead = commentBufferSize;
+
+ if (lSeek!=0) {
+ if (fseek(s->file,lSeek,SEEK_CUR)==0)
+ lSeek=0;
+ else
+ err=UNZ_ERRNO;
+ }
+ if ((file_info.size_file_comment>0) && (commentBufferSize>0)) {
+ if (fread(szComment,(uInt)uSizeRead,1,s->file)!=1)
+ err=UNZ_ERRNO;
+ }
+ lSeek+=file_info.size_file_comment - uSizeRead;
+ }
+ else
+ lSeek+=file_info.size_file_comment;
+
+ if ((err==UNZ_OK) && (pfile_info!=NULL))
+ *pfile_info=file_info;
+
+ if ((err==UNZ_OK) && (pfile_info_internal!=NULL))
+ *pfile_info_internal=file_info_internal;
+
+ return err;
+}
+
+
+
+/*
+ Write info about the ZipFile in the *pglobal_info structure.
+ No preparation of the structure is needed
+ return UNZ_OK if there is no problem.
+*/
+extern int unzGetCurrentFileInfo ( unzFile file, unz_file_info *pfile_info,
+ char *szFileName, uLong fileNameBufferSize,
+ void *extraField, uLong extraFieldBufferSize,
+ char *szComment, uLong commentBufferSize)
+{
+ return unzlocal_GetCurrentFileInfoInternal(file,pfile_info,NULL,
+ szFileName,fileNameBufferSize,
+ extraField,extraFieldBufferSize,
+ szComment,commentBufferSize);
+}
+
+/*
+ Set the current file of the zipfile to the first file.
+ return UNZ_OK if there is no problem
+*/
+extern int unzGoToFirstFile (unzFile file)
+{
+ int err=UNZ_OK;
+ unz_s* s;
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+ s->pos_in_central_dir=s->offset_central_dir;
+ s->num_file=0;
+ err=unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info,
+ &s->cur_file_info_internal,
+ NULL,0,NULL,0,NULL,0);
+ s->current_file_ok = (err == UNZ_OK);
+ return err;
+}
+
+
+/*
+ Set the current file of the zipfile to the next file.
+ return UNZ_OK if there is no problem
+ return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest.
+*/
+extern int unzGoToNextFile (unzFile file)
+{
+ unz_s* s;
+ int err;
+
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+ if (!s->current_file_ok)
+ return UNZ_END_OF_LIST_OF_FILE;
+ if (s->num_file+1==s->gi.number_entry)
+ return UNZ_END_OF_LIST_OF_FILE;
+
+ s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename +
+ s->cur_file_info.size_file_extra + s->cur_file_info.size_file_comment ;
+ s->num_file++;
+ err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info,
+ &s->cur_file_info_internal,
+ NULL,0,NULL,0,NULL,0);
+ s->current_file_ok = (err == UNZ_OK);
+ return err;
+}
+
+/*
+ Get the position of the info of the current file in the zip.
+ return UNZ_OK if there is no problem
+*/
+extern int unzGetCurrentFileInfoPosition (unzFile file, unsigned long *pos )
+{
+ unz_s* s;
+
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+
+ *pos = s->pos_in_central_dir;
+ return UNZ_OK;
+}
+
+/*
+ Set the position of the info of the current file in the zip.
+ return UNZ_OK if there is no problem
+*/
+extern int unzSetCurrentFileInfoPosition (unzFile file, unsigned long pos )
+{
+ unz_s* s;
+ int err;
+
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+
+ s->pos_in_central_dir = pos;
+ err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info,
+ &s->cur_file_info_internal,
+ NULL,0,NULL,0,NULL,0);
+ s->current_file_ok = (err == UNZ_OK);
+ return UNZ_OK;
+}
+
+/*
+ Try locate the file szFileName in the zipfile.
+ For the iCaseSensitivity signification, see unzipStringFileNameCompare
+
+ return value :
+ UNZ_OK if the file is found. It becomes the current file.
+ UNZ_END_OF_LIST_OF_FILE if the file is not found
+*/
+extern int unzLocateFile (unzFile file, const char *szFileName, int iCaseSensitivity)
+{
+ unz_s* s;
+ int err;
+
+
+ uLong num_fileSaved;
+ uLong pos_in_central_dirSaved;
+
+
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+
+ if (strlen(szFileName)>=UNZ_MAXFILENAMEINZIP)
+ return UNZ_PARAMERROR;
+
+ s=(unz_s*)file;
+ if (!s->current_file_ok)
+ return UNZ_END_OF_LIST_OF_FILE;
+
+ num_fileSaved = s->num_file;
+ pos_in_central_dirSaved = s->pos_in_central_dir;
+
+ err = unzGoToFirstFile(file);
+
+ while (err == UNZ_OK)
+ {
+ char szCurrentFileName[UNZ_MAXFILENAMEINZIP+1];
+ unzGetCurrentFileInfo(file,NULL,
+ szCurrentFileName,sizeof(szCurrentFileName)-1,
+ NULL,0,NULL,0);
+ if (unzStringFileNameCompare(szCurrentFileName,
+ szFileName,iCaseSensitivity)==0)
+ return UNZ_OK;
+ err = unzGoToNextFile(file);
+ }
+
+ s->num_file = num_fileSaved ;
+ s->pos_in_central_dir = pos_in_central_dirSaved ;
+ return err;
+}
+
+
+/*
+ Read the static header of the current zipfile
+ Check the coherency of the static header and info in the end of central
+ directory about this file
+ store in *piSizeVar the size of extra info in static header
+ (filename and size of extra field data)
+*/
+static int unzlocal_CheckCurrentFileCoherencyHeader (unz_s* s, uInt* piSizeVar,
+ uLong *poffset_local_extrafield,
+ uInt *psize_local_extrafield)
+{
+ uLong uMagic,uData,uFlags;
+ uLong size_filename;
+ uLong size_extra_field;
+ int err=UNZ_OK;
+
+ *piSizeVar = 0;
+ *poffset_local_extrafield = 0;
+ *psize_local_extrafield = 0;
+
+ if (fseek(s->file,s->cur_file_info_internal.offset_curfile +
+ s->byte_before_the_zipfile,SEEK_SET)!=0)
+ return UNZ_ERRNO;
+
+
+ if (err==UNZ_OK) {
+ if (unzlocal_getLong(s->file,&uMagic) != UNZ_OK)
+ err=UNZ_ERRNO;
+ else if (uMagic!=0x04034b50)
+ err=UNZ_BADZIPFILE;
+ }
+ if (unzlocal_getShort(s->file,&uData) != UNZ_OK)
+ err=UNZ_ERRNO;
+/*
+ else if ((err==UNZ_OK) && (uData!=s->cur_file_info.wVersion))
+ err=UNZ_BADZIPFILE;
+*/
+ if (unzlocal_getShort(s->file,&uFlags) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getShort(s->file,&uData) != UNZ_OK)
+ err=UNZ_ERRNO;
+ else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compression_method))
+ err=UNZ_BADZIPFILE;
+
+ if ((err==UNZ_OK) && (s->cur_file_info.compression_method!=0) &&
+ (s->cur_file_info.compression_method!=Z_DEFLATED))
+ err=UNZ_BADZIPFILE;
+
+ if (unzlocal_getLong(s->file,&uData) != UNZ_OK) /* date/time */
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getLong(s->file,&uData) != UNZ_OK) /* crc */
+ err=UNZ_ERRNO;
+ else if ((err==UNZ_OK) && (uData!=s->cur_file_info.crc) &&
+ ((uFlags & 8)==0))
+ err=UNZ_BADZIPFILE;
+
+ if (unzlocal_getLong(s->file,&uData) != UNZ_OK) /* size compr */
+ err=UNZ_ERRNO;
+ else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compressed_size) &&
+ ((uFlags & 8)==0))
+ err=UNZ_BADZIPFILE;
+
+ if (unzlocal_getLong(s->file,&uData) != UNZ_OK) /* size uncompr */
+ err=UNZ_ERRNO;
+ else if ((err==UNZ_OK) && (uData!=s->cur_file_info.uncompressed_size) &&
+ ((uFlags & 8)==0))
+ err=UNZ_BADZIPFILE;
+
+
+ if (unzlocal_getShort(s->file,&size_filename) != UNZ_OK)
+ err=UNZ_ERRNO;
+ else if ((err==UNZ_OK) && (size_filename!=s->cur_file_info.size_filename))
+ err=UNZ_BADZIPFILE;
+
+ *piSizeVar += (uInt)size_filename;
+
+ if (unzlocal_getShort(s->file,&size_extra_field) != UNZ_OK)
+ err=UNZ_ERRNO;
+ *poffset_local_extrafield= s->cur_file_info_internal.offset_curfile +
+ SIZEZIPLOCALHEADER + size_filename;
+ *psize_local_extrafield = (uInt)size_extra_field;
+
+ *piSizeVar += (uInt)size_extra_field;
+
+ return err;
+}
+
+/*
+ Open for reading data the current file in the zipfile.
+ If there is no error and the file is opened, the return value is UNZ_OK.
+*/
+extern int unzOpenCurrentFile (unzFile file)
+{
+ int err=UNZ_OK;
+ int Store;
+ uInt iSizeVar;
+ unz_s* s;
+ file_in_zip_read_info_s* pfile_in_zip_read_info;
+ uLong offset_local_extrafield; /* offset of the static extra field */
+ uInt size_local_extrafield; /* size of the static extra field */
+
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+ if (!s->current_file_ok)
+ return UNZ_PARAMERROR;
+
+ if (s->pfile_in_zip_read != NULL)
+ unzCloseCurrentFile(file);
+
+ if (unzlocal_CheckCurrentFileCoherencyHeader(s,&iSizeVar,
+ &offset_local_extrafield,&size_local_extrafield)!=UNZ_OK)
+ return UNZ_BADZIPFILE;
+
+ pfile_in_zip_read_info = (file_in_zip_read_info_s*)
+ ALLOC(sizeof(file_in_zip_read_info_s));
+ if (pfile_in_zip_read_info==NULL)
+ return UNZ_INTERNALERROR;
+
+ pfile_in_zip_read_info->read_buffer=(char*)ALLOC(UNZ_BUFSIZE);
+ pfile_in_zip_read_info->offset_local_extrafield = offset_local_extrafield;
+ pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield;
+ pfile_in_zip_read_info->pos_local_extrafield=0;
+
+ if (pfile_in_zip_read_info->read_buffer==NULL)
+ {
+ TRYFREE(pfile_in_zip_read_info);
+ return UNZ_INTERNALERROR;
+ }
+
+ pfile_in_zip_read_info->stream_initialised=0;
+
+ if ((s->cur_file_info.compression_method!=0) &&
+ (s->cur_file_info.compression_method!=Z_DEFLATED))
+ err=UNZ_BADZIPFILE;
+ Store = s->cur_file_info.compression_method==0;
+
+ pfile_in_zip_read_info->crc32_wait=s->cur_file_info.crc;
+ pfile_in_zip_read_info->crc32=0;
+ pfile_in_zip_read_info->compression_method =
+ s->cur_file_info.compression_method;
+ pfile_in_zip_read_info->file=s->file;
+ pfile_in_zip_read_info->byte_before_the_zipfile=s->byte_before_the_zipfile;
+
+ pfile_in_zip_read_info->stream.total_out = 0;
+
+ if (!Store)
+ {
+ pfile_in_zip_read_info->stream.zalloc = (alloc_func)0;
+ pfile_in_zip_read_info->stream.zfree = (free_func)0;
+ pfile_in_zip_read_info->stream.opaque = (voidp)0;
+
+ err=inflateInit2(&pfile_in_zip_read_info->stream, -MAX_WBITS);
+ if (err == Z_OK)
+ pfile_in_zip_read_info->stream_initialised=1;
+ /* windowBits is passed < 0 to tell that there is no zlib header.
+ * Note that in this case inflate *requires* an extra "dummy" byte
+ * after the compressed stream in order to complete decompression and
+ * return Z_STREAM_END.
+ * In unzip, i don't wait absolutely Z_STREAM_END because I known the
+ * size of both compressed and uncompressed data
+ */
+ }
+ pfile_in_zip_read_info->rest_read_compressed =
+ s->cur_file_info.compressed_size ;
+ pfile_in_zip_read_info->rest_read_uncompressed =
+ s->cur_file_info.uncompressed_size ;
+
+
+ pfile_in_zip_read_info->pos_in_zipfile =
+ s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER +
+ iSizeVar;
+
+ pfile_in_zip_read_info->stream.avail_in = (uInt)0;
+
+
+ s->pfile_in_zip_read = pfile_in_zip_read_info;
+ return UNZ_OK;
+}
+
+
+/*
+ Read bytes from the current file.
+ buf contain buffer where data must be copied
+ len the size of buf.
+
+ return the number of byte copied if somes bytes are copied
+ return 0 if the end of file was reached
+ return <0 with error code if there is an error
+ (UNZ_ERRNO for IO error, or zLib error for uncompress error)
+*/
+extern int unzReadCurrentFile (unzFile file, void *buf, unsigned len)
+{
+ int err=UNZ_OK;
+ uInt iRead = 0;
+ unz_s* s;
+ file_in_zip_read_info_s* pfile_in_zip_read_info;
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+ pfile_in_zip_read_info=s->pfile_in_zip_read;
+
+ if (pfile_in_zip_read_info==NULL)
+ return UNZ_PARAMERROR;
+
+
+ if ((pfile_in_zip_read_info->read_buffer == NULL))
+ return UNZ_END_OF_LIST_OF_FILE;
+ if (len==0)
+ return 0;
+
+ pfile_in_zip_read_info->stream.next_out = (Byte*)buf;
+
+ pfile_in_zip_read_info->stream.avail_out = (uInt)len;
+
+ if (len>pfile_in_zip_read_info->rest_read_uncompressed)
+ pfile_in_zip_read_info->stream.avail_out =
+ (uInt)pfile_in_zip_read_info->rest_read_uncompressed;
+
+ while (pfile_in_zip_read_info->stream.avail_out>0)
+ {
+ if ((pfile_in_zip_read_info->stream.avail_in==0) &&
+ (pfile_in_zip_read_info->rest_read_compressed>0))
+ {
+ uInt uReadThis = UNZ_BUFSIZE;
+ if (pfile_in_zip_read_info->rest_read_compressed<uReadThis)
+ uReadThis = (uInt)pfile_in_zip_read_info->rest_read_compressed;
+ if (uReadThis == 0)
+ return UNZ_EOF;
+ if (s->cur_file_info.compressed_size == pfile_in_zip_read_info->rest_read_compressed)
+ if (fseek(pfile_in_zip_read_info->file,
+ pfile_in_zip_read_info->pos_in_zipfile +
+ pfile_in_zip_read_info->byte_before_the_zipfile,SEEK_SET)!=0)
+ return UNZ_ERRNO;
+ if (fread(pfile_in_zip_read_info->read_buffer,uReadThis,1,
+ pfile_in_zip_read_info->file)!=1)
+ return UNZ_ERRNO;
+ pfile_in_zip_read_info->pos_in_zipfile += uReadThis;
+
+ pfile_in_zip_read_info->rest_read_compressed-=uReadThis;
+
+ pfile_in_zip_read_info->stream.next_in =
+ (Byte*)pfile_in_zip_read_info->read_buffer;
+ pfile_in_zip_read_info->stream.avail_in = (uInt)uReadThis;
+ }
+
+ if (pfile_in_zip_read_info->compression_method==0)
+ {
+ uInt uDoCopy,i ;
+ if (pfile_in_zip_read_info->stream.avail_out <
+ pfile_in_zip_read_info->stream.avail_in)
+ uDoCopy = pfile_in_zip_read_info->stream.avail_out ;
+ else
+ uDoCopy = pfile_in_zip_read_info->stream.avail_in ;
+
+ for (i=0;i<uDoCopy;i++)
+ *(pfile_in_zip_read_info->stream.next_out+i) =
+ *(pfile_in_zip_read_info->stream.next_in+i);
+
+// pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32,
+// pfile_in_zip_read_info->stream.next_out,
+// uDoCopy);
+ pfile_in_zip_read_info->rest_read_uncompressed-=uDoCopy;
+ pfile_in_zip_read_info->stream.avail_in -= uDoCopy;
+ pfile_in_zip_read_info->stream.avail_out -= uDoCopy;
+ pfile_in_zip_read_info->stream.next_out += uDoCopy;
+ pfile_in_zip_read_info->stream.next_in += uDoCopy;
+ pfile_in_zip_read_info->stream.total_out += uDoCopy;
+ iRead += uDoCopy;
+ }
+ else
+ {
+ uLong uTotalOutBefore,uTotalOutAfter;
+ const Byte *bufBefore;
+ uLong uOutThis;
+ int flush=Z_SYNC_FLUSH;
+
+ uTotalOutBefore = pfile_in_zip_read_info->stream.total_out;
+ bufBefore = pfile_in_zip_read_info->stream.next_out;
+
+ /*
+ if ((pfile_in_zip_read_info->rest_read_uncompressed ==
+ pfile_in_zip_read_info->stream.avail_out) &&
+ (pfile_in_zip_read_info->rest_read_compressed == 0))
+ flush = Z_FINISH;
+ */
+ err=inflate(&pfile_in_zip_read_info->stream,flush);
+
+ uTotalOutAfter = pfile_in_zip_read_info->stream.total_out;
+ uOutThis = uTotalOutAfter-uTotalOutBefore;
+
+// pfile_in_zip_read_info->crc32 =
+// crc32(pfile_in_zip_read_info->crc32,bufBefore,
+// (uInt)(uOutThis));
+
+ pfile_in_zip_read_info->rest_read_uncompressed -=
+ uOutThis;
+
+ iRead += (uInt)(uTotalOutAfter - uTotalOutBefore);
+
+ if (err==Z_STREAM_END)
+ return (iRead==0) ? UNZ_EOF : iRead;
+ if (err!=Z_OK)
+ break;
+ }
+ }
+
+ if (err==Z_OK)
+ return iRead;
+ return err;
+}
+
+
+/*
+ Give the current position in uncompressed data
+*/
+extern long unztell (unzFile file)
+{
+ unz_s* s;
+ file_in_zip_read_info_s* pfile_in_zip_read_info;
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+ pfile_in_zip_read_info=s->pfile_in_zip_read;
+
+ if (pfile_in_zip_read_info==NULL)
+ return UNZ_PARAMERROR;
+
+ return (long)pfile_in_zip_read_info->stream.total_out;
+}
+
+
+/*
+ return 1 if the end of file was reached, 0 elsewhere
+*/
+extern int unzeof (unzFile file)
+{
+ unz_s* s;
+ file_in_zip_read_info_s* pfile_in_zip_read_info;
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+ pfile_in_zip_read_info=s->pfile_in_zip_read;
+
+ if (pfile_in_zip_read_info==NULL)
+ return UNZ_PARAMERROR;
+
+ if (pfile_in_zip_read_info->rest_read_uncompressed == 0)
+ return 1;
+ else
+ return 0;
+}
+
+
+
+/*
+ Read extra field from the current file (opened by unzOpenCurrentFile)
+ This is the static-header version of the extra field (sometimes, there is
+ more info in the static-header version than in the central-header)
+
+ if buf==NULL, it return the size of the static extra field that can be read
+
+ if buf!=NULL, len is the size of the buffer, the extra header is copied in
+ buf.
+ the return value is the number of bytes copied in buf, or (if <0)
+ the error code
+*/
+extern int unzGetLocalExtrafield (unzFile file,void *buf,unsigned len)
+{
+ unz_s* s;
+ file_in_zip_read_info_s* pfile_in_zip_read_info;
+ uInt read_now;
+ uLong size_to_read;
+
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+ pfile_in_zip_read_info=s->pfile_in_zip_read;
+
+ if (pfile_in_zip_read_info==NULL)
+ return UNZ_PARAMERROR;
+
+ size_to_read = (pfile_in_zip_read_info->size_local_extrafield -
+ pfile_in_zip_read_info->pos_local_extrafield);
+
+ if (buf==NULL)
+ return (int)size_to_read;
+
+ if (len>size_to_read)
+ read_now = (uInt)size_to_read;
+ else
+ read_now = (uInt)len ;
+
+ if (read_now==0)
+ return 0;
+
+ if (fseek(pfile_in_zip_read_info->file,
+ pfile_in_zip_read_info->offset_local_extrafield +
+ pfile_in_zip_read_info->pos_local_extrafield,SEEK_SET)!=0)
+ return UNZ_ERRNO;
+
+ if (fread(buf,(uInt)size_to_read,1,pfile_in_zip_read_info->file)!=1)
+ return UNZ_ERRNO;
+
+ return (int)read_now;
+}
+
+/*
+ Close the file in zip opened with unzipOpenCurrentFile
+ Return UNZ_CRCERROR if all the file was read but the CRC is not good
+*/
+extern int unzCloseCurrentFile (unzFile file)
+{
+ int err=UNZ_OK;
+
+ unz_s* s;
+ file_in_zip_read_info_s* pfile_in_zip_read_info;
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+ pfile_in_zip_read_info=s->pfile_in_zip_read;
+
+ if (pfile_in_zip_read_info==NULL)
+ return UNZ_PARAMERROR;
+
+/*
+ if (pfile_in_zip_read_info->rest_read_uncompressed == 0)
+ {
+ if (pfile_in_zip_read_info->crc32 != pfile_in_zip_read_info->crc32_wait)
+ err=UNZ_CRCERROR;
+ }
+*/
+
+ TRYFREE(pfile_in_zip_read_info->read_buffer);
+ pfile_in_zip_read_info->read_buffer = NULL;
+ if (pfile_in_zip_read_info->stream_initialised)
+ inflateEnd(&pfile_in_zip_read_info->stream);
+
+ pfile_in_zip_read_info->stream_initialised = 0;
+ TRYFREE(pfile_in_zip_read_info);
+
+ s->pfile_in_zip_read=NULL;
+
+ return err;
+}
+
+
+/*
+ Get the global comment string of the ZipFile, in the szComment buffer.
+ uSizeBuf is the size of the szComment buffer.
+ return the number of byte copied or an error code <0
+*/
+extern int unzGetGlobalComment (unzFile file, char *szComment, uLong uSizeBuf)
+{
+ unz_s* s;
+ uLong uReadThis ;
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+
+ uReadThis = uSizeBuf;
+ if (uReadThis>s->gi.size_comment)
+ uReadThis = s->gi.size_comment;
+
+ if (fseek(s->file,s->central_pos+22,SEEK_SET)!=0)
+ return UNZ_ERRNO;
+
+ if (uReadThis>0)
+ {
+ *szComment='\0';
+ if (fread(szComment,(uInt)uReadThis,1,s->file)!=1)
+ return UNZ_ERRNO;
+ }
+
+ if ((szComment != NULL) && (uSizeBuf > s->gi.size_comment))
+ *(szComment+s->gi.size_comment)='\0';
+ return (int)uReadThis;
+}
+
+/* infblock.h -- header to use infblock.c
+ * Copyright (C) 1995-1998 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+ part of the implementation of the compression library and is
+ subject to change. Applications should only use zlib.h.
+ */
+
+struct inflate_blocks_state;
+typedef struct inflate_blocks_state inflate_blocks_statef;
+
+static inflate_blocks_statef * inflate_blocks_new OF((
+ z_streamp z,
+ check_func c, /* check function */
+ uInt w)); /* window size */
+
+static int inflate_blocks OF((
+ inflate_blocks_statef *,
+ z_streamp ,
+ int)); /* initial return code */
+
+static void inflate_blocks_reset OF((
+ inflate_blocks_statef *,
+ z_streamp ,
+ uLong *)); /* check value on output */
+
+static int inflate_blocks_free OF((
+ inflate_blocks_statef *,
+ z_streamp));
+
+#if 0
+static void inflate_set_dictionary OF((
+ inflate_blocks_statef *s,
+ const Byte *d, /* dictionary */
+ uInt n)); /* dictionary length */
+
+static int inflate_blocks_sync_point OF((
+ inflate_blocks_statef *s));
+#endif
+
+/* simplify the use of the inflate_huft type with some defines */
+#define exop word.what.Exop
+#define bits word.what.Bits
+
+/* Table for deflate from PKZIP's appnote.txt. */
+static const uInt border[] = { /* Order of the bit length code lengths */
+ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
+
+/* inftrees.h -- header to use inftrees.c
+ * Copyright (C) 1995-1998 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+ part of the implementation of the compression library and is
+ subject to change. Applications should only use zlib.h.
+ */
+
+/* Huffman code lookup table entry--this entry is four bytes for machines
+ that have 16-bit pointers (e.g. PC's in the small or medium model). */
+
+typedef struct inflate_huft_s inflate_huft;
+
+struct inflate_huft_s {
+ union {
+ struct {
+ Byte Exop; /* number of extra bits or operation */
+ Byte Bits; /* number of bits in this code or subcode */
+ } what;
+ uInt pad; /* pad structure to a power of 2 (4 bytes for */
+ } word; /* 16-bit, 8 bytes for 32-bit int's) */
+ uInt base; /* literal, length base, distance base,
+ or table offset */
+};
+
+/* Maximum size of dynamic tree. The maximum found in a long but non-
+ exhaustive search was 1004 huft structures (850 for length/literals
+ and 154 for distances, the latter actually the result of an
+ exhaustive search). The actual maximum is not known, but the
+ value below is more than safe. */
+#define MANY 1440
+
+static int inflate_trees_bits OF((
+ uInt *, /* 19 code lengths */
+ uInt *, /* bits tree desired/actual depth */
+ inflate_huft * *, /* bits tree result */
+ inflate_huft *, /* space for trees */
+ z_streamp)); /* for messages */
+
+static int inflate_trees_dynamic OF((
+ uInt, /* number of literal/length codes */
+ uInt, /* number of distance codes */
+ uInt *, /* that many (total) code lengths */
+ uInt *, /* literal desired/actual bit depth */
+ uInt *, /* distance desired/actual bit depth */
+ inflate_huft * *, /* literal/length tree result */
+ inflate_huft * *, /* distance tree result */
+ inflate_huft *, /* space for trees */
+ z_streamp)); /* for messages */
+
+static int inflate_trees_fixed OF((
+ uInt *, /* literal desired/actual bit depth */
+ uInt *, /* distance desired/actual bit depth */
+ inflate_huft * *, /* literal/length tree result */
+ inflate_huft * *, /* distance tree result */
+ z_streamp)); /* for memory allocation */
+
+
+/* infcodes.h -- header to use infcodes.c
+ * Copyright (C) 1995-1998 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+ part of the implementation of the compression library and is
+ subject to change. Applications should only use zlib.h.
+ */
+
+struct inflate_codes_state;
+typedef struct inflate_codes_state inflate_codes_statef;
+
+static inflate_codes_statef *inflate_codes_new OF((
+ uInt, uInt,
+ inflate_huft *, inflate_huft *,
+ z_streamp ));
+
+static int inflate_codes OF((
+ inflate_blocks_statef *,
+ z_streamp ,
+ int));
+
+static void inflate_codes_free OF((
+ inflate_codes_statef *,
+ z_streamp ));
+
+/* infutil.h -- types and macros common to blocks and codes
+ * Copyright (C) 1995-1998 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+ part of the implementation of the compression library and is
+ subject to change. Applications should only use zlib.h.
+ */
+
+#ifndef _INFUTIL_H
+#define _INFUTIL_H
+
+typedef enum {
+ TYPE, /* get type bits (3, including end bit) */
+ LENS, /* get lengths for stored */
+ STORED, /* processing stored block */
+ TABLE, /* get table lengths */
+ BTREE, /* get bit lengths tree for a dynamic block */
+ DTREE, /* get length, distance trees for a dynamic block */
+ CODES, /* processing fixed or dynamic block */
+ DRY, /* output remaining window bytes */
+ DONE, /* finished last block, done */
+ BAD} /* got a data error--stuck here */
+inflate_block_mode;
+
+/* inflate blocks semi-private state */
+struct inflate_blocks_state {
+
+ /* mode */
+ inflate_block_mode mode; /* current inflate_block mode */
+
+ /* mode dependent information */
+ union {
+ uInt left; /* if STORED, bytes left to copy */
+ struct {
+ uInt table; /* table lengths (14 bits) */
+ uInt index; /* index into blens (or border) */
+ uInt *blens; /* bit lengths of codes */
+ uInt bb; /* bit length tree depth */
+ inflate_huft *tb; /* bit length decoding tree */
+ } trees; /* if DTREE, decoding info for trees */
+ struct {
+ inflate_codes_statef
+ *codes;
+ } decode; /* if CODES, current state */
+ } sub; /* submode */
+ uInt last; /* true if this block is the last block */
+
+ /* mode independent information */
+ uInt bitk; /* bits in bit buffer */
+ uLong bitb; /* bit buffer */
+ inflate_huft *hufts; /* single malloc for tree space */
+ Byte *window; /* sliding window */
+ Byte *end; /* one byte after sliding window */
+ Byte *read; /* window read pointer */
+ Byte *write; /* window write pointer */
+ check_func checkfn; /* check function */
+ uLong check; /* check on output */
+
+};
+
+
+/* defines for inflate input/output */
+/* update pointers and return */
+#define UPDBITS {s->bitb=b;s->bitk=k;}
+#define UPDIN {z->avail_in=n;z->total_in+=p-z->next_in;z->next_in=p;}
+#define UPDOUT {s->write=q;}
+#define UPDATE {UPDBITS UPDIN UPDOUT}
+#define LEAVE {UPDATE return inflate_flush(s,z,r);}
+/* get bytes and bits */
+#define LOADIN {p=z->next_in;n=z->avail_in;b=s->bitb;k=s->bitk;}
+#define NEEDBYTE {if(n)r=Z_OK;else LEAVE}
+#define NEXTBYTE (n--,*p++)
+#define NEEDBITS(j) {while(k<(j)){NEEDBYTE;b|=((uLong)NEXTBYTE)<<k;k+=8;}}
+#define DUMPBITS(j) {b>>=(j);k-=(j);}
+/* output bytes */
+#define WAVAIL (uInt)(q<s->read?s->read-q-1:s->end-q)
+#define LOADOUT {q=s->write;m=(uInt)WAVAIL;}
+#define WRAP {if(q==s->end&&s->read!=s->window){q=s->window;m=(uInt)WAVAIL;}}
+#define FLUSH {UPDOUT r=inflate_flush(s,z,r); LOADOUT}
+#define NEEDOUT {if(m==0){WRAP if(m==0){FLUSH WRAP if(m==0) LEAVE}}r=Z_OK;}
+#define OUTBYTE(a) {*q++=(Byte)(a);m--;}
+/* load static pointers */
+#define LOAD {LOADIN LOADOUT}
+
+/* masks for lower bits (size given to avoid silly warnings with Visual C++) */
+static uInt inflate_mask[17];
+
+/* copy as much as possible from the sliding window to the output area */
+static int inflate_flush OF((
+ inflate_blocks_statef *,
+ z_streamp ,
+ int));
+
+#endif
+
+
+/*
+ Notes beyond the 1.93a appnote.txt:
+
+ 1. Distance pointers never point before the beginning of the output
+ stream.
+ 2. Distance pointers can point back across blocks, up to 32k away.
+ 3. There is an implied maximum of 7 bits for the bit length table and
+ 15 bits for the actual data.
+ 4. If only one code exists, then it is encoded using one bit. (Zero
+ would be more efficient, but perhaps a little confusing.) If two
+ codes exist, they are coded using one bit each (0 and 1).
+ 5. There is no way of sending zero distance codes--a dummy must be
+ sent if there are none. (History: a pre 2.0 version of PKZIP would
+ store blocks with no distance codes, but this was discovered to be
+ too harsh a criterion.) Valid only for 1.93a. 2.04c does allow
+ zero distance codes, which is sent as one code of zero bits in
+ length.
+ 6. There are up to 286 literal/length codes. Code 256 represents the
+ end-of-block. Note however that the static length tree defines
+ 288 codes just to fill out the Huffman codes. Codes 286 and 287
+ cannot be used though, since there is no length base or extra bits
+ defined for them. Similarily, there are up to 30 distance codes.
+ However, static trees define 32 codes (all 5 bits) to fill out the
+ Huffman codes, but the last two had better not show up in the data.
+ 7. Unzip can check dynamic Huffman blocks for complete code sets.
+ The exception is that a single code would not be complete (see #4).
+ 8. The five bits following the block type is really the number of
+ literal codes sent minus 257.
+ 9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
+ (1+6+6). Therefore, to output three times the length, you output
+ three codes (1+1+1), whereas to output four times the same length,
+ you only need two codes (1+3). Hmm.
+ 10. In the tree reconstruction algorithm, Code = Code + Increment
+ only if BitLength(i) is not zero. (Pretty obvious.)
+ 11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19)
+ 12. Note: length code 284 can represent 227-258, but length code 285
+ really is 258. The last length deserves its own, short code
+ since it gets used a lot in very redundant files. The length
+ 258 is special since 258 - 3 (the min match length) is 255.
+ 13. The literal/length and distance code bit lengths are read as a
+ single stream of lengths. It is possible (and advantageous) for
+ a repeat code (16, 17, or 18) to go across the boundary between
+ the two sets of lengths.
+ */
+
+
+void inflate_blocks_reset(inflate_blocks_statef *s, z_streamp z, uLong *c)
+{
+ if (c != Z_NULL)
+ *c = s->check;
+ if (s->mode == BTREE || s->mode == DTREE)
+ ZFREE(z, s->sub.trees.blens);
+ if (s->mode == CODES)
+ inflate_codes_free(s->sub.decode.codes, z);
+ s->mode = TYPE;
+ s->bitk = 0;
+ s->bitb = 0;
+ s->read = s->write = s->window;
+ if (s->checkfn != Z_NULL)
+ z->adler = s->check = (*s->checkfn)(0L, (const Byte *)Z_NULL, 0);
+ Tracev(("inflate: blocks reset\n"));
+}
+
+
+inflate_blocks_statef *inflate_blocks_new(z_streamp z, check_func c, uInt w)
+{
+ inflate_blocks_statef *s;
+
+ if ((s = (inflate_blocks_statef *)ZALLOC
+ (z,1,sizeof(struct inflate_blocks_state))) == Z_NULL)
+ return s;
+ if ((s->hufts =
+ (inflate_huft *)ZALLOC(z, sizeof(inflate_huft), MANY)) == Z_NULL)
+ {
+ ZFREE(z, s);
+ return Z_NULL;
+ }
+ if ((s->window = (Byte *)ZALLOC(z, 1, w)) == Z_NULL)
+ {
+ ZFREE(z, s->hufts);
+ ZFREE(z, s);
+ return Z_NULL;
+ }
+ s->end = s->window + w;
+ s->checkfn = c;
+ s->mode = TYPE;
+ Tracev(("inflate: blocks allocated\n"));
+ inflate_blocks_reset(s, z, Z_NULL);
+ return s;
+}
+
+
+int inflate_blocks(inflate_blocks_statef *s, z_streamp z, int r)
+{
+ uInt t; /* temporary storage */
+ uLong b; /* bit buffer */
+ uInt k; /* bits in bit buffer */
+ Byte *p; /* input data pointer */
+ uInt n; /* bytes available there */
+ Byte *q; /* output window write pointer */
+ uInt m; /* bytes to end of window or read pointer */
+
+ /* copy input/output information to locals (UPDATE macro restores) */
+ LOAD
+
+ /* process input based on current state */
+ while (1) switch (s->mode)
+ {
+ case TYPE:
+ NEEDBITS(3)
+ t = (uInt)b & 7;
+ s->last = t & 1;
+ switch (t >> 1)
+ {
+ case 0: /* stored */
+ Tracev(("inflate: stored block%s\n",
+ s->last ? " (last)" : ""));
+ DUMPBITS(3)
+ t = k & 7; /* go to byte boundary */
+ DUMPBITS(t)
+ s->mode = LENS; /* get length of stored block */
+ break;
+ case 1: /* fixed */
+ Tracev(("inflate: fixed codes block%s\n",
+ s->last ? " (last)" : ""));
+ {
+ uInt bl, bd;
+ inflate_huft *tl, *td;
+ inflate_trees_fixed(&bl, &bd, &tl, &td, z);
+ s->sub.decode.codes = inflate_codes_new(bl, bd, tl, td, z);
+ if (s->sub.decode.codes == Z_NULL)
+ {
+ r = Z_MEM_ERROR;
+ LEAVE
+ }
+ }
+ DUMPBITS(3)
+ s->mode = CODES;
+ break;
+ case 2: /* dynamic */
+ Tracev(("inflate: dynamic codes block%s\n",
+ s->last ? " (last)" : ""));
+ DUMPBITS(3)
+ s->mode = TABLE;
+ break;
+ case 3: /* illegal */
+ DUMPBITS(3)
+ s->mode = BAD;
+ z->msg = (char*)"invalid block type";
+ r = Z_DATA_ERROR;
+ LEAVE
+ }
+ break;
+ case LENS:
+ NEEDBITS(32)
+ if ((((~b) >> 16) & 0xffff) != (b & 0xffff))
+ {
+ s->mode = BAD;
+ z->msg = (char*)"invalid stored block lengths";
+ r = Z_DATA_ERROR;
+ LEAVE
+ }
+ s->sub.left = (uInt)b & 0xffff;
+ b = k = 0; /* dump bits */
+ Tracev(("inflate: stored length %u\n", s->sub.left));
+ s->mode = s->sub.left ? STORED : (s->last ? DRY : TYPE);
+ break;
+ case STORED:
+ if (n == 0)
+ LEAVE
+ NEEDOUT
+ t = s->sub.left;
+ if (t > n) t = n;
+ if (t > m) t = m;
+ zmemcpy(q, p, t);
+ p += t; n -= t;
+ q += t; m -= t;
+ if ((s->sub.left -= t) != 0)
+ break;
+ Tracev(("inflate: stored end, %lu total out\n",
+ z->total_out + (q >= s->read ? q - s->read :
+ (s->end - s->read) + (q - s->window))));
+ s->mode = s->last ? DRY : TYPE;
+ break;
+ case TABLE:
+ NEEDBITS(14)
+ s->sub.trees.table = t = (uInt)b & 0x3fff;
+#ifndef PKZIP_BUG_WORKAROUND
+ if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29)
+ {
+ s->mode = BAD;
+ z->msg = (char*)"too many length or distance symbols";
+ r = Z_DATA_ERROR;
+ LEAVE
+ }
+#endif
+ t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f);
+ if ((s->sub.trees.blens = (uInt*)ZALLOC(z, t, sizeof(uInt))) == Z_NULL)
+ {
+ r = Z_MEM_ERROR;
+ LEAVE
+ }
+ DUMPBITS(14)
+ s->sub.trees.index = 0;
+ Tracev(("inflate: table sizes ok\n"));
+ s->mode = BTREE;
+ case BTREE:
+ while (s->sub.trees.index < 4 + (s->sub.trees.table >> 10))
+ {
+ NEEDBITS(3)
+ s->sub.trees.blens[border[s->sub.trees.index++]] = (uInt)b & 7;
+ DUMPBITS(3)
+ }
+ while (s->sub.trees.index < 19)
+ s->sub.trees.blens[border[s->sub.trees.index++]] = 0;
+ s->sub.trees.bb = 7;
+ t = inflate_trees_bits(s->sub.trees.blens, &s->sub.trees.bb,
+ &s->sub.trees.tb, s->hufts, z);
+ if (t != Z_OK)
+ {
+ ZFREE(z, s->sub.trees.blens);
+ r = t;
+ if (r == Z_DATA_ERROR)
+ s->mode = BAD;
+ LEAVE
+ }
+ s->sub.trees.index = 0;
+ Tracev(("inflate: bits tree ok\n"));
+ s->mode = DTREE;
+ case DTREE:
+ while (t = s->sub.trees.table,
+ s->sub.trees.index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f))
+ {
+ inflate_huft *h;
+ uInt i, j, c;
+
+ t = s->sub.trees.bb;
+ NEEDBITS(t)
+ h = s->sub.trees.tb + ((uInt)b & inflate_mask[t]);
+ t = h->bits;
+ c = h->base;
+ if (c < 16)
+ {
+ DUMPBITS(t)
+ s->sub.trees.blens[s->sub.trees.index++] = c;
+ }
+ else /* c == 16..18 */
+ {
+ i = c == 18 ? 7 : c - 14;
+ j = c == 18 ? 11 : 3;
+ NEEDBITS(t + i)
+ DUMPBITS(t)
+ j += (uInt)b & inflate_mask[i];
+ DUMPBITS(i)
+ i = s->sub.trees.index;
+ t = s->sub.trees.table;
+ if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) ||
+ (c == 16 && i < 1))
+ {
+ ZFREE(z, s->sub.trees.blens);
+ s->mode = BAD;
+ z->msg = (char*)"invalid bit length repeat";
+ r = Z_DATA_ERROR;
+ LEAVE
+ }
+ c = c == 16 ? s->sub.trees.blens[i - 1] : 0;
+ do {
+ s->sub.trees.blens[i++] = c;
+ } while (--j);
+ s->sub.trees.index = i;
+ }
+ }
+ s->sub.trees.tb = Z_NULL;
+ {
+ uInt bl, bd;
+ inflate_huft *tl, *td;
+ inflate_codes_statef *c;
+
+ tl = NULL;
+ td = NULL;
+ bl = 9; /* must be <= 9 for lookahead assumptions */
+ bd = 6; /* must be <= 9 for lookahead assumptions */
+ t = s->sub.trees.table;
+ t = inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f),
+ s->sub.trees.blens, &bl, &bd, &tl, &td,
+ s->hufts, z);
+ ZFREE(z, s->sub.trees.blens);
+ if (t != Z_OK)
+ {
+ if (t == (uInt)Z_DATA_ERROR)
+ s->mode = BAD;
+ r = t;
+ LEAVE
+ }
+ Tracev(("inflate: trees ok\n"));
+ if ((c = inflate_codes_new(bl, bd, tl, td, z)) == Z_NULL)
+ {
+ r = Z_MEM_ERROR;
+ LEAVE
+ }
+ s->sub.decode.codes = c;
+ }
+ s->mode = CODES;
+ case CODES:
+ UPDATE
+ if ((r = inflate_codes(s, z, r)) != Z_STREAM_END)
+ return inflate_flush(s, z, r);
+ r = Z_OK;
+ inflate_codes_free(s->sub.decode.codes, z);
+ LOAD
+ Tracev(("inflate: codes end, %lu total out\n",
+ z->total_out + (q >= s->read ? q - s->read :
+ (s->end - s->read) + (q - s->window))));
+ if (!s->last)
+ {
+ s->mode = TYPE;
+ break;
+ }
+ s->mode = DRY;
+ case DRY:
+ FLUSH
+ if (s->read != s->write)
+ LEAVE
+ s->mode = DONE;
+ case DONE:
+ r = Z_STREAM_END;
+ LEAVE
+ case BAD:
+ r = Z_DATA_ERROR;
+ LEAVE
+ default:
+ r = Z_STREAM_ERROR;
+ LEAVE
+ }
+}
+
+
+int inflate_blocks_free(inflate_blocks_statef *s, z_streamp z)
+{
+ inflate_blocks_reset(s, z, Z_NULL);
+ ZFREE(z, s->window);
+ ZFREE(z, s->hufts);
+ ZFREE(z, s);
+ Tracev(("inflate: blocks freed\n"));
+ return Z_OK;
+}
+
+#if 0
+void inflate_set_dictionary(inflate_blocks_statef *s, const Byte *d, uInt n)
+{
+ zmemcpy(s->window, d, n);
+ s->read = s->write = s->window + n;
+}
+
+/* Returns true if inflate is currently at the end of a block generated
+ * by Z_SYNC_FLUSH or Z_FULL_FLUSH.
+ * IN assertion: s != Z_NULL
+ */
+int inflate_blocks_sync_point(inflate_blocks_statef *s)
+{
+ return s->mode == LENS;
+}
+#endif
+
+
+/* And'ing with mask[n] masks the lower n bits */
+static uInt inflate_mask[17] = {
+ 0x0000,
+ 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
+ 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
+};
+
+
+/* copy as much as possible from the sliding window to the output area */
+int inflate_flush(inflate_blocks_statef *s, z_streamp z, int r)
+{
+ uInt n;
+ Byte *p;
+ Byte *q;
+
+ /* static copies of source and destination pointers */
+ p = z->next_out;
+ q = s->read;
+
+ /* compute number of bytes to copy as as end of window */
+ n = (uInt)((q <= s->write ? s->write : s->end) - q);
+ if (n > z->avail_out) n = z->avail_out;
+ if (n && r == Z_BUF_ERROR) r = Z_OK;
+
+ /* update counters */
+ z->avail_out -= n;
+ z->total_out += n;
+
+ /* update check information */
+ if (s->checkfn != Z_NULL)
+ z->adler = s->check = (*s->checkfn)(s->check, q, n);
+
+ /* copy as as end of window */
+ zmemcpy(p, q, n);
+ p += n;
+ q += n;
+
+ /* see if more to copy at beginning of window */
+ if (q == s->end)
+ {
+ /* wrap pointers */
+ q = s->window;
+ if (s->write == s->end)
+ s->write = s->window;
+
+ /* compute bytes to copy */
+ n = (uInt)(s->write - q);
+ if (n > z->avail_out) n = z->avail_out;
+ if (n && r == Z_BUF_ERROR) r = Z_OK;
+
+ /* update counters */
+ z->avail_out -= n;
+ z->total_out += n;
+
+ /* update check information */
+ if (s->checkfn != Z_NULL)
+ z->adler = s->check = (*s->checkfn)(s->check, q, n);
+
+ /* copy */
+ zmemcpy(p, q, n);
+ p += n;
+ q += n;
+ }
+
+ /* update pointers */
+ z->next_out = p;
+ s->read = q;
+
+ /* done */
+ return r;
+}
+
+/* inftrees.c -- generate Huffman trees for efficient decoding
+ * Copyright (C) 1995-1998 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+static const char inflate_copyright[] =
+ " inflate 1.1.3 Copyright 1995-1998 Mark Adler ";
+/*
+ If you use the zlib library in a product, an acknowledgment is welcome
+ in the documentation of your product. If for some reason you cannot
+ include such an acknowledgment, I would appreciate that you keep this
+ copyright string in the executable of your product.
+ */
+
+/* simplify the use of the inflate_huft type with some defines */
+#define exop word.what.Exop
+#define bits word.what.Bits
+
+
+static int huft_build OF((
+ uInt *, /* code lengths in bits */
+ uInt, /* number of codes */
+ uInt, /* number of "simple" codes */
+ const uInt *, /* list of base values for non-simple codes */
+ const uInt *, /* list of extra bits for non-simple codes */
+ inflate_huft **, /* result: starting table */
+ uInt *, /* maximum lookup bits (returns actual) */
+ inflate_huft *, /* space for trees */
+ uInt *, /* hufts used in space */
+ uInt * )); /* space for values */
+
+/* Tables for deflate from PKZIP's appnote.txt. */
+static const uInt cplens[31] = { /* Copy lengths for literal codes 257..285 */
+ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
+ 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
+ /* see note #13 above about 258 */
+static const uInt cplext[31] = { /* Extra bits for literal codes 257..285 */
+ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
+ 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112}; /* 112==invalid */
+static const uInt cpdist[30] = { /* Copy offsets for distance codes 0..29 */
+ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
+ 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
+ 8193, 12289, 16385, 24577};
+static const uInt cpdext[30] = { /* Extra bits for distance codes */
+ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
+ 7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
+ 12, 12, 13, 13};
+
+/*
+ Huffman code decoding is performed using a multi-level table lookup.
+ The fastest way to decode is to simply build a lookup table whose
+ size is determined by the longest code. However, the time it takes
+ to build this table can also be a factor if the data being decoded
+ is not very long. The most common codes are necessarily the
+ shortest codes, so those codes dominate the decoding time, and hence
+ the speed. The idea is you can have a shorter table that decodes the
+ shorter, more probable codes, and then point to subsidiary tables for
+ the longer codes. The time it costs to decode the longer codes is
+ then traded against the time it takes to make longer tables.
+
+ This results of this trade are in the variables lbits and dbits
+ below. lbits is the number of bits the first level table for literal/
+ length codes can decode in one step, and dbits is the same thing for
+ the distance codes. Subsequent tables are also less than or equal to
+ those sizes. These values may be adjusted either when all of the
+ codes are shorter than that, in which case the longest code length in
+ bits is used, or when the shortest code is *longer* than the requested
+ table size, in which case the length of the shortest code in bits is
+ used.
+
+ There are two different values for the two tables, since they code a
+ different number of possibilities each. The literal/length table
+ codes 286 possible values, or in a flat code, a little over eight
+ bits. The distance table codes 30 possible values, or a little less
+ than five bits, flat. The optimum values for speed end up being
+ about one bit more than those, so lbits is 8+1 and dbits is 5+1.
+ The optimum values may differ though from machine to machine, and
+ possibly even between compilers. Your mileage may vary.
+ */
+
+
+/* If BMAX needs to be larger than 16, then h and x[] should be uLong. */
+#define BMAX 15 /* maximum bit length of any code */
+
+static int huft_build(uInt *b, uInt n, uInt s, const uInt *d, const uInt *e, inflate_huft ** t, uInt *m, inflate_huft *hp, uInt *hn, uInt *v)
+//uInt *b; /* code lengths in bits (all assumed <= BMAX) */
+//uInt n; /* number of codes (assumed <= 288) */
+//uInt s; /* number of simple-valued codes (0..s-1) */
+//const uInt *d; /* list of base values for non-simple codes */
+//const uInt *e; /* list of extra bits for non-simple codes */
+//inflate_huft ** t; /* result: starting table */
+//uInt *m; /* maximum lookup bits, returns actual */
+//inflate_huft *hp; /* space for trees */
+//uInt *hn; /* hufts used in space */
+//uInt *v; /* working area: values in order of bit length */
+/* Given a list of code lengths and a maximum table size, make a set of
+ tables to decode that set of codes. Return Z_OK on success, Z_BUF_ERROR
+ if the given code set is incomplete (the tables are still built in this
+ case), Z_DATA_ERROR if the input is invalid (an over-subscribed set of
+ lengths), or Z_MEM_ERROR if not enough memory. */
+{
+
+ uInt a; /* counter for codes of length k */
+ uInt c[BMAX+1]; /* bit length count table */
+ uInt f; /* i repeats in table every f entries */
+ int g; /* maximum code length */
+ int h; /* table level */
+ register uInt i; /* counter, current code */
+ register uInt j; /* counter */
+ register int k; /* number of bits in current code */
+ int l; /* bits per table (returned in m) */
+ uInt mask; /* (1 << w) - 1, to avoid cc -O bug on HP */
+ register uInt *p; /* pointer into c[], b[], or v[] */
+ inflate_huft *q; /* points to current table */
+ struct inflate_huft_s r; /* table entry for structure assignment */
+ inflate_huft *u[BMAX]; /* table stack */
+ register int w; /* bits before this table == (l * h) */
+ uInt x[BMAX+1]; /* bit offsets, then code stack */
+ uInt *xp; /* pointer into x */
+ int y; /* number of dummy codes added */
+ uInt z; /* number of entries in current table */
+
+
+ /* Generate counts for each bit length */
+ p = c;
+#define C0 *p++ = 0;
+#define C2 C0 C0 C0 C0
+#define C4 C2 C2 C2 C2
+ C4 /* clear c[]--assume BMAX+1 is 16 */
+ p = b; i = n;
+ do {
+ c[*p++]++; /* assume all entries <= BMAX */
+ } while (--i);
+ if (c[0] == n) /* null input--all zero length codes */
+ {
+ *t = (inflate_huft *)Z_NULL;
+ *m = 0;
+ return Z_OK;
+ }
+
+
+ /* Find minimum and maximum length, bound *m by those */
+ l = *m;
+ for (j = 1; j <= BMAX; j++)
+ if (c[j])
+ break;
+ k = j; /* minimum code length */
+ if ((uInt)l < j)
+ l = j;
+ for (i = BMAX; i; i--)
+ if (c[i])
+ break;
+ g = i; /* maximum code length */
+ if ((uInt)l > i)
+ l = i;
+ *m = l;
+
+
+ /* Adjust last length count to fill out codes, if needed */
+ for (y = 1 << j; j < i; j++, y <<= 1)
+ if ((y -= c[j]) < 0)
+ return Z_DATA_ERROR;
+ if ((y -= c[i]) < 0)
+ return Z_DATA_ERROR;
+ c[i] += y;
+
+
+ /* Generate starting offsets into the value table for each length */
+ x[1] = j = 0;
+ p = c + 1; xp = x + 2;
+ while (--i) { /* note that i == g from above */
+ *xp++ = (j += *p++);
+ }
+
+
+ /* Make a table of values in order of bit lengths */
+ p = b; i = 0;
+ do {
+ if ((j = *p++) != 0)
+ v[x[j]++] = i;
+ } while (++i < n);
+ n = x[g]; /* set n to length of v */
+
+
+ /* Generate the Huffman codes and for each, make the table entries */
+ x[0] = i = 0; /* first Huffman code is zero */
+ p = v; /* grab values in bit order */
+ h = -1; /* no tables yet--level -1 */
+ w = -l; /* bits decoded == (l * h) */
+ u[0] = (inflate_huft *)Z_NULL; /* just to keep compilers happy */
+ q = (inflate_huft *)Z_NULL; /* ditto */
+ z = 0; /* ditto */
+
+ /* go through the bit lengths (k already is bits in shortest code) */
+ for (; k <= g; k++)
+ {
+ a = c[k];
+ while (a--)
+ {
+ /* here i is the Huffman code of length k bits for value *p */
+ /* make tables up to required level */
+ while (k > w + l)
+ {
+ h++;
+ w += l; /* previous table always l bits */
+
+ /* compute minimum size table less than or equal to l bits */
+ z = g - w;
+ z = z > (uInt)l ? l : z; /* table size upper limit */
+ if ((f = 1 << (j = k - w)) > a + 1) /* try a k-w bit table */
+ { /* too few codes for k-w bit table */
+ f -= a + 1; /* deduct codes from patterns left */
+ xp = c + k;
+ if (j < z)
+ while (++j < z) /* try smaller tables up to z bits */
+ {
+ if ((f <<= 1) <= *++xp)
+ break; /* enough codes to use up j bits */
+ f -= *xp; /* else deduct codes from patterns */
+ }
+ }
+ z = 1 << j; /* table entries for j-bit table */
+
+ /* allocate new table */
+ if (*hn + z > MANY) /* (note: doesn't matter for fixed) */
+ return Z_MEM_ERROR; /* not enough memory */
+ u[h] = q = hp + *hn;
+ *hn += z;
+
+ /* connect to last table, if there is one */
+ if (h)
+ {
+ x[h] = i; /* save pattern for backing up */
+ r.bits = (Byte)l; /* bits to dump before this table */
+ r.exop = (Byte)j; /* bits in this table */
+ j = i >> (w - l);
+ r.base = (uInt)(q - u[h-1] - j); /* offset to this table */
+ u[h-1][j] = r; /* connect to last table */
+ }
+ else
+ *t = q; /* first table is returned result */
+ }
+
+ /* set up table entry in r */
+ r.bits = (Byte)(k - w);
+ if (p >= v + n)
+ r.exop = 128 + 64; /* out of values--invalid code */
+ else if (*p < s)
+ {
+ r.exop = (Byte)(*p < 256 ? 0 : 32 + 64); /* 256 is end-of-block */
+ r.base = *p++; /* simple code is just the value */
+ }
+ else
+ {
+ r.exop = (Byte)(e[*p - s] + 16 + 64);/* non-simple--look up in lists */
+ r.base = d[*p++ - s];
+ }
+
+ /* fill code-like entries with r */
+ f = 1 << (k - w);
+ for (j = i >> w; j < z; j += f)
+ q[j] = r;
+
+ /* backwards increment the k-bit code i */
+ for (j = 1 << (k - 1); i & j; j >>= 1)
+ i ^= j;
+ i ^= j;
+
+ /* backup over finished tables */
+ mask = (1 << w) - 1; /* needed on HP, cc -O bug */
+ while ((i & mask) != x[h])
+ {
+ h--; /* don't need to update q */
+ w -= l;
+ mask = (1 << w) - 1;
+ }
+ }
+ }
+
+
+ /* Return Z_BUF_ERROR if we were given an incomplete table */
+ return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK;
+}
+
+
+int inflate_trees_bits(uInt *c, uInt *bb, inflate_huft * *tb, inflate_huft *hp, z_streamp z)
+//uInt *c; /* 19 code lengths */
+//uInt *bb; /* bits tree desired/actual depth */
+//inflate_huft * *tb; /* bits tree result */
+//inflate_huft *hp; /* space for trees */
+//z_streamp z; /* for messages */
+{
+ int r;
+ uInt hn = 0; /* hufts used in space */
+ uInt *v; /* work area for huft_build */
+
+ if ((v = (uInt*)ZALLOC(z, 19, sizeof(uInt))) == Z_NULL)
+ return Z_MEM_ERROR;
+ r = huft_build(c, 19, 19, (uInt*)Z_NULL, (uInt*)Z_NULL,
+ tb, bb, hp, &hn, v);
+ if (r == Z_DATA_ERROR)
+ z->msg = (char*)"oversubscribed dynamic bit lengths tree";
+ else if (r == Z_BUF_ERROR || *bb == 0)
+ {
+ z->msg = (char*)"incomplete dynamic bit lengths tree";
+ r = Z_DATA_ERROR;
+ }
+ ZFREE(z, v);
+ return r;
+}
+
+
+int inflate_trees_dynamic(uInt nl, uInt nd, uInt *c, uInt *bl, uInt *bd, inflate_huft * *tl, inflate_huft * *td, inflate_huft *hp, z_streamp z)
+//uInt nl; /* number of literal/length codes */
+//uInt nd; /* number of distance codes */
+//uInt *c; /* that many (total) code lengths */
+//uInt *bl; /* literal desired/actual bit depth */
+//uInt *bd; /* distance desired/actual bit depth */
+//inflate_huft * *tl; /* literal/length tree result */
+//inflate_huft * *td; /* distance tree result */
+//inflate_huft *hp; /* space for trees */
+//z_streamp z; /* for messages */
+{
+ int r;
+ uInt hn = 0; /* hufts used in space */
+ uInt *v; /* work area for huft_build */
+
+ /* allocate work area */
+ if ((v = (uInt*)ZALLOC(z, 288, sizeof(uInt))) == Z_NULL)
+ return Z_MEM_ERROR;
+
+ /* build literal/length tree */
+ r = huft_build(c, nl, 257, cplens, cplext, tl, bl, hp, &hn, v);
+ if (r != Z_OK || *bl == 0)
+ {
+ if (r == Z_DATA_ERROR)
+ z->msg = (char*)"oversubscribed literal/length tree";
+ else if (r != Z_MEM_ERROR)
+ {
+ z->msg = (char*)"incomplete literal/length tree";
+ r = Z_DATA_ERROR;
+ }
+ ZFREE(z, v);
+ return r;
+ }
+
+ /* build distance tree */
+ r = huft_build(c + nl, nd, 0, cpdist, cpdext, td, bd, hp, &hn, v);
+ if (r != Z_OK || (*bd == 0 && nl > 257))
+ {
+ if (r == Z_DATA_ERROR)
+ z->msg = (char*)"oversubscribed distance tree";
+ else if (r == Z_BUF_ERROR) {
+#ifdef PKZIP_BUG_WORKAROUND
+ r = Z_OK;
+ }
+#else
+ z->msg = (char*)"incomplete distance tree";
+ r = Z_DATA_ERROR;
+ }
+ else if (r != Z_MEM_ERROR)
+ {
+ z->msg = (char*)"empty distance tree with lengths";
+ r = Z_DATA_ERROR;
+ }
+ ZFREE(z, v);
+ return r;
+#endif
+ }
+
+ /* done */
+ ZFREE(z, v);
+ return Z_OK;
+}
+
+/* inffixed.h -- table for decoding fixed codes
+ * Generated automatically by the maketree.c program
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+ part of the implementation of the compression library and is
+ subject to change. Applications should only use zlib.h.
+ */
+
+static uInt fixed_bl = 9;
+static uInt fixed_bd = 5;
+static inflate_huft fixed_tl[] = {
+ {{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115},
+ {{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},192},
+ {{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},160},
+ {{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},224},
+ {{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},144},
+ {{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},208},
+ {{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},176},
+ {{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},240},
+ {{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227},
+ {{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},200},
+ {{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},168},
+ {{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},232},
+ {{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},152},
+ {{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},216},
+ {{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},184},
+ {{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},248},
+ {{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163},
+ {{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},196},
+ {{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},164},
+ {{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},228},
+ {{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},148},
+ {{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},212},
+ {{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},180},
+ {{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},244},
+ {{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0},
+ {{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},204},
+ {{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},172},
+ {{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},236},
+ {{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},156},
+ {{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},220},
+ {{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},188},
+ {{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},252},
+ {{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131},
+ {{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},194},
+ {{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},162},
+ {{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},226},
+ {{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},146},
+ {{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},210},
+ {{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},178},
+ {{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},242},
+ {{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258},
+ {{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},202},
+ {{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},170},
+ {{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},234},
+ {{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},154},
+ {{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},218},
+ {{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},186},
+ {{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},250},
+ {{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195},
+ {{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},198},
+ {{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},166},
+ {{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},230},
+ {{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},150},
+ {{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},214},
+ {{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},182},
+ {{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},246},
+ {{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0},
+ {{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},206},
+ {{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},174},
+ {{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},238},
+ {{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},158},
+ {{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},222},
+ {{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},190},
+ {{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},254},
+ {{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115},
+ {{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},193},
+ {{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},161},
+ {{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},225},
+ {{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},145},
+ {{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},209},
+ {{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},177},
+ {{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},241},
+ {{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227},
+ {{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},201},
+ {{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},169},
+ {{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},233},
+ {{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},153},
+ {{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},217},
+ {{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},185},
+ {{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},249},
+ {{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163},
+ {{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},197},
+ {{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},165},
+ {{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},229},
+ {{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},149},
+ {{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},213},
+ {{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},181},
+ {{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},245},
+ {{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0},
+ {{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},205},
+ {{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},173},
+ {{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},237},
+ {{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},157},
+ {{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},221},
+ {{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},189},
+ {{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},253},
+ {{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131},
+ {{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},195},
+ {{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},163},
+ {{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},227},
+ {{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},147},
+ {{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},211},
+ {{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},179},
+ {{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},243},
+ {{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258},
+ {{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},203},
+ {{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},171},
+ {{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},235},
+ {{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},155},
+ {{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},219},
+ {{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},187},
+ {{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},251},
+ {{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195},
+ {{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},199},
+ {{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},167},
+ {{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},231},
+ {{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},151},
+ {{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},215},
+ {{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},183},
+ {{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},247},
+ {{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0},
+ {{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},207},
+ {{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},175},
+ {{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},239},
+ {{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},159},
+ {{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},223},
+ {{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},191},
+ {{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},255}
+ };
+static inflate_huft fixed_td[] = {
+ {{{80,5}},1}, {{{87,5}},257}, {{{83,5}},17}, {{{91,5}},4097},
+ {{{81,5}},5}, {{{89,5}},1025}, {{{85,5}},65}, {{{93,5}},16385},
+ {{{80,5}},3}, {{{88,5}},513}, {{{84,5}},33}, {{{92,5}},8193},
+ {{{82,5}},9}, {{{90,5}},2049}, {{{86,5}},129}, {{{192,5}},24577},
+ {{{80,5}},2}, {{{87,5}},385}, {{{83,5}},25}, {{{91,5}},6145},
+ {{{81,5}},7}, {{{89,5}},1537}, {{{85,5}},97}, {{{93,5}},24577},
+ {{{80,5}},4}, {{{88,5}},769}, {{{84,5}},49}, {{{92,5}},12289},
+ {{{82,5}},13}, {{{90,5}},3073}, {{{86,5}},193}, {{{192,5}},24577}
+ };
+
+int inflate_trees_fixed(uInt *bl, uInt *bd, inflate_huft * *tl, inflate_huft * *td, z_streamp z)
+//uInt *bl; /* literal desired/actual bit depth */
+//uInt *bd; /* distance desired/actual bit depth */
+//inflate_huft * *tl; /* literal/length tree result */
+//inflate_huft * *td; /* distance tree result */
+//z_streamp z; /* for memory allocation */
+{
+ *bl = fixed_bl;
+ *bd = fixed_bd;
+ *tl = fixed_tl;
+ *td = fixed_td;
+ return Z_OK;
+}
+
+/* simplify the use of the inflate_huft type with some defines */
+#define exop word.what.Exop
+#define bits word.what.Bits
+
+/* macros for bit input with no checking and for returning unused bytes */
+#define GRABBITS(j) {while(k<(j)){b|=((uLong)NEXTBYTE)<<k;k+=8;}}
+#define UNGRAB {c=z->avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3;}
+
+/* Called with number of bytes left to write in window at least 258
+ (the maximum string length) and number of input bytes available
+ at least ten. The ten bytes are six bytes for the longest length/
+ distance pair plus four bytes for overloading the bit buffer. */
+
+static int inflate_fast(uInt bl, uInt bd, inflate_huft *tl, inflate_huft *td, inflate_blocks_statef *s, z_streamp z)
+{
+ inflate_huft *t; /* temporary pointer */
+ uInt e; /* extra bits or operation */
+ uLong b; /* bit buffer */
+ uInt k; /* bits in bit buffer */
+ Byte *p; /* input data pointer */
+ uInt n; /* bytes available there */
+ Byte *q; /* output window write pointer */
+ uInt m; /* bytes to end of window or read pointer */
+ uInt ml; /* mask for literal/length tree */
+ uInt md; /* mask for distance tree */
+ uInt c; /* bytes to copy */
+ uInt d; /* distance back to copy from */
+ Byte *r; /* copy source pointer */
+
+ /* load input, output, bit values */
+ LOAD
+
+ /* initialize masks */
+ ml = inflate_mask[bl];
+ md = inflate_mask[bd];
+
+ /* do until not enough input or output space for fast loop */
+ do { /* assume called with m >= 258 && n >= 10 */
+ /* get literal/length code */
+ GRABBITS(20) /* max bits for literal/length code */
+ if ((e = (t = tl + ((uInt)b & ml))->exop) == 0)
+ {
+ DUMPBITS(t->bits)
+ Tracevv((t->base >= 0x20 && t->base < 0x7f ?
+ "inflate: * literal '%c'\n" :
+ "inflate: * literal 0x%02x\n", t->base));
+ *q++ = (Byte)t->base;
+ m--;
+ continue;
+ }
+ do {
+ DUMPBITS(t->bits)
+ if (e & 16)
+ {
+ /* get extra bits for length */
+ e &= 15;
+ c = t->base + ((uInt)b & inflate_mask[e]);
+ DUMPBITS(e)
+ Tracevv(("inflate: * length %u\n", c));
+
+ /* decode distance base of block to copy */
+ GRABBITS(15); /* max bits for distance code */
+ e = (t = td + ((uInt)b & md))->exop;
+ do {
+ DUMPBITS(t->bits)
+ if (e & 16)
+ {
+ /* get extra bits to add to distance base */
+ e &= 15;
+ GRABBITS(e) /* get extra bits (up to 13) */
+ d = t->base + ((uInt)b & inflate_mask[e]);
+ DUMPBITS(e)
+ Tracevv(("inflate: * distance %u\n", d));
+
+ /* do the copy */
+ m -= c;
+ if ((uInt)(q - s->window) >= d) /* offset before dest */
+ { /* just copy */
+ r = q - d;
+ *q++ = *r++; c--; /* minimum count is three, */
+ *q++ = *r++; c--; /* so unroll loop a little */
+ }
+ else /* else offset after destination */
+ {
+ e = d - (uInt)(q - s->window); /* bytes from offset to end */
+ r = s->end - e; /* pointer to offset */
+ if (c > e) /* if source crosses, */
+ {
+ c -= e; /* copy to end of window */
+ do {
+ *q++ = *r++;
+ } while (--e);
+ r = s->window; /* copy rest from start of window */
+ }
+ }
+ do { /* copy all or what's left */
+ *q++ = *r++;
+ } while (--c);
+ break;
+ }
+ else if ((e & 64) == 0)
+ {
+ t += t->base;
+ e = (t += ((uInt)b & inflate_mask[e]))->exop;
+ }
+ else
+ {
+ z->msg = (char*)"invalid distance code";
+ UNGRAB
+ UPDATE
+ return Z_DATA_ERROR;
+ }
+ } while (1);
+ break;
+ }
+ if ((e & 64) == 0)
+ {
+ t += t->base;
+ if ((e = (t += ((uInt)b & inflate_mask[e]))->exop) == 0)
+ {
+ DUMPBITS(t->bits)
+ Tracevv((t->base >= 0x20 && t->base < 0x7f ?
+ "inflate: * literal '%c'\n" :
+ "inflate: * literal 0x%02x\n", t->base));
+ *q++ = (Byte)t->base;
+ m--;
+ break;
+ }
+ }
+ else if (e & 32)
+ {
+ Tracevv(("inflate: * end of block\n"));
+ UNGRAB
+ UPDATE
+ return Z_STREAM_END;
+ }
+ else
+ {
+ z->msg = (char*)"invalid literal/length code";
+ UNGRAB
+ UPDATE
+ return Z_DATA_ERROR;
+ }
+ } while (1);
+ } while (m >= 258 && n >= 10);
+
+ /* not enough input or output--restore pointers and return */
+ UNGRAB
+ UPDATE
+ return Z_OK;
+}
+
+/* infcodes.c -- process literals and length/distance pairs
+ * Copyright (C) 1995-1998 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* simplify the use of the inflate_huft type with some defines */
+#define exop word.what.Exop
+#define bits word.what.Bits
+
+typedef enum { /* waiting for "i:"=input, "o:"=output, "x:"=nothing */
+ START, /* x: set up for LEN */
+ LEN, /* i: get length/literal/eob next */
+ LENEXT, /* i: getting length extra (have base) */
+ DIST, /* i: get distance next */
+ DISTEXT, /* i: getting distance extra */
+ COPY, /* o: copying bytes in window, waiting for space */
+ LIT, /* o: got literal, waiting for output space */
+ WASH, /* o: got eob, possibly still output waiting */
+ END, /* x: got eob and all data flushed */
+ BADCODE} /* x: got error */
+inflate_codes_mode;
+
+/* inflate codes private state */
+struct inflate_codes_state {
+
+ /* mode */
+ inflate_codes_mode mode; /* current inflate_codes mode */
+
+ /* mode dependent information */
+ uInt len;
+ union {
+ struct {
+ inflate_huft *tree; /* pointer into tree */
+ uInt need; /* bits needed */
+ } code; /* if LEN or DIST, where in tree */
+ uInt lit; /* if LIT, literal */
+ struct {
+ uInt get; /* bits to get for extra */
+ uInt dist; /* distance back to copy from */
+ } copy; /* if EXT or COPY, where and how much */
+ } sub; /* submode */
+
+ /* mode independent information */
+ Byte lbits; /* ltree bits decoded per branch */
+ Byte dbits; /* dtree bits decoder per branch */
+ inflate_huft *ltree; /* literal/length/eob tree */
+ inflate_huft *dtree; /* distance tree */
+
+};
+
+
+inflate_codes_statef *inflate_codes_new(uInt bl, uInt bd, inflate_huft *tl, inflate_huft *td, z_streamp z)
+{
+ inflate_codes_statef *c;
+
+ if ((c = (inflate_codes_statef *)
+ ZALLOC(z,1,sizeof(struct inflate_codes_state))) != Z_NULL)
+ {
+ c->mode = START;
+ c->lbits = (Byte)bl;
+ c->dbits = (Byte)bd;
+ c->ltree = tl;
+ c->dtree = td;
+ Tracev(("inflate: codes new\n"));
+ }
+ return c;
+}
+
+
+int inflate_codes(inflate_blocks_statef *s, z_streamp z, int r)
+{
+ uInt j; /* temporary storage */
+ inflate_huft *t; /* temporary pointer */
+ uInt e; /* extra bits or operation */
+ uLong b; /* bit buffer */
+ uInt k; /* bits in bit buffer */
+ Byte *p; /* input data pointer */
+ uInt n; /* bytes available there */
+ Byte *q; /* output window write pointer */
+ uInt m; /* bytes to end of window or read pointer */
+ Byte *f; /* pointer to copy strings from */
+ inflate_codes_statef *c = s->sub.decode.codes; /* codes state */
+
+ /* copy input/output information to locals (UPDATE macro restores) */
+ LOAD
+
+ /* process input and output based on current state */
+ while (1) switch (c->mode)
+ { /* waiting for "i:"=input, "o:"=output, "x:"=nothing */
+ case START: /* x: set up for LEN */
+#ifndef SLOW
+ if (m >= 258 && n >= 10)
+ {
+ UPDATE
+ r = inflate_fast(c->lbits, c->dbits, c->ltree, c->dtree, s, z);
+ LOAD
+ if (r != Z_OK)
+ {
+ c->mode = r == Z_STREAM_END ? WASH : BADCODE;
+ break;
+ }
+ }
+#endif /* !SLOW */
+ c->sub.code.need = c->lbits;
+ c->sub.code.tree = c->ltree;
+ c->mode = LEN;
+ case LEN: /* i: get length/literal/eob next */
+ j = c->sub.code.need;
+ NEEDBITS(j)
+ t = c->sub.code.tree + ((uInt)b & inflate_mask[j]);
+ DUMPBITS(t->bits)
+ e = (uInt)(t->exop);
+ if (e == 0) /* literal */
+ {
+ c->sub.lit = t->base;
+ Tracevv((t->base >= 0x20 && t->base < 0x7f ?
+ "inflate: literal '%c'\n" :
+ "inflate: literal 0x%02x\n", t->base));
+ c->mode = LIT;
+ break;
+ }
+ if (e & 16) /* length */
+ {
+ c->sub.copy.get = e & 15;
+ c->len = t->base;
+ c->mode = LENEXT;
+ break;
+ }
+ if ((e & 64) == 0) /* next table */
+ {
+ c->sub.code.need = e;
+ c->sub.code.tree = t + t->base;
+ break;
+ }
+ if (e & 32) /* end of block */
+ {
+ Tracevv(("inflate: end of block\n"));
+ c->mode = WASH;
+ break;
+ }
+ c->mode = BADCODE; /* invalid code */
+ z->msg = (char*)"invalid literal/length code";
+ r = Z_DATA_ERROR;
+ LEAVE
+ case LENEXT: /* i: getting length extra (have base) */
+ j = c->sub.copy.get;
+ NEEDBITS(j)
+ c->len += (uInt)b & inflate_mask[j];
+ DUMPBITS(j)
+ c->sub.code.need = c->dbits;
+ c->sub.code.tree = c->dtree;
+ Tracevv(("inflate: length %u\n", c->len));
+ c->mode = DIST;
+ case DIST: /* i: get distance next */
+ j = c->sub.code.need;
+ NEEDBITS(j)
+ t = c->sub.code.tree + ((uInt)b & inflate_mask[j]);
+ DUMPBITS(t->bits)
+ e = (uInt)(t->exop);
+ if (e & 16) /* distance */
+ {
+ c->sub.copy.get = e & 15;
+ c->sub.copy.dist = t->base;
+ c->mode = DISTEXT;
+ break;
+ }
+ if ((e & 64) == 0) /* next table */
+ {
+ c->sub.code.need = e;
+ c->sub.code.tree = t + t->base;
+ break;
+ }
+ c->mode = BADCODE; /* invalid code */
+ z->msg = (char*)"invalid distance code";
+ r = Z_DATA_ERROR;
+ LEAVE
+ case DISTEXT: /* i: getting distance extra */
+ j = c->sub.copy.get;
+ NEEDBITS(j)
+ c->sub.copy.dist += (uInt)b & inflate_mask[j];
+ DUMPBITS(j)
+ Tracevv(("inflate: distance %u\n", c->sub.copy.dist));
+ c->mode = COPY;
+ case COPY: /* o: copying bytes in window, waiting for space */
+#ifndef __TURBOC__ /* Turbo C bug for following expression */
+ f = (uInt)(q - s->window) < c->sub.copy.dist ?
+ s->end - (c->sub.copy.dist - (q - s->window)) :
+ q - c->sub.copy.dist;
+#else
+ f = q - c->sub.copy.dist;
+ if ((uInt)(q - s->window) < c->sub.copy.dist)
+ f = s->end - (c->sub.copy.dist - (uInt)(q - s->window));
+#endif
+ while (c->len)
+ {
+ NEEDOUT
+ OUTBYTE(*f++)
+ if (f == s->end)
+ f = s->window;
+ c->len--;
+ }
+ c->mode = START;
+ break;
+ case LIT: /* o: got literal, waiting for output space */
+ NEEDOUT
+ OUTBYTE(c->sub.lit)
+ c->mode = START;
+ break;
+ case WASH: /* o: got eob, possibly more output */
+ if (k > 7) /* return unused byte, if any */
+ {
+ Assert(k < 16, "inflate_codes grabbed too many bytes")
+ k -= 8;
+ n++;
+ p--; /* can always return one */
+ }
+ FLUSH
+ if (s->read != s->write)
+ LEAVE
+ c->mode = END;
+ case END:
+ r = Z_STREAM_END;
+ LEAVE
+ case BADCODE: /* x: got error */
+ r = Z_DATA_ERROR;
+ LEAVE
+ default:
+ r = Z_STREAM_ERROR;
+ LEAVE
+ }
+#ifdef NEED_DUMMY_RETURN
+ return Z_STREAM_ERROR; /* Some dumb compilers complain without this */
+#endif
+}
+
+
+void inflate_codes_free(inflate_codes_statef *c, z_streamp z)
+{
+ ZFREE(z, c);
+ Tracev(("inflate: codes free\n"));
+}
+
+/* adler32.c -- compute the Adler-32 checksum of a data stream
+ * Copyright (C) 1995-1998 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+#define BASE 65521L /* largest prime smaller than 65536 */
+#define NMAX 5552
+/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
+
+#undef DO1
+#undef DO2
+#undef DO4
+#undef DO8
+
+#define DO1(buf,i) {s1 += buf[i]; s2 += s1;}
+#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
+#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
+#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
+#define DO16(buf) DO8(buf,0); DO8(buf,8);
+
+/* ========================================================================= */
+static uLong adler32(uLong adler, const Byte *buf, uInt len)
+{
+ unsigned long s1 = adler & 0xffff;
+ unsigned long s2 = (adler >> 16) & 0xffff;
+ int k;
+
+ if (buf == Z_NULL) return 1L;
+
+ while (len > 0) {
+ k = len < NMAX ? len : NMAX;
+ len -= k;
+ while (k >= 16) {
+ DO16(buf);
+ buf += 16;
+ k -= 16;
+ }
+ if (k != 0) do {
+ s1 += *buf++;
+ s2 += s1;
+ } while (--k);
+ s1 %= BASE;
+ s2 %= BASE;
+ }
+ return (s2 << 16) | s1;
+}
+
+
+/* infblock.h -- header to use infblock.c
+ * Copyright (C) 1995-1998 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+ part of the implementation of the compression library and is
+ subject to change. Applications should only use zlib.h.
+ */
+
+static inflate_blocks_statef * inflate_blocks_new OF((
+ z_streamp z,
+ check_func c, /* check function */
+ uInt w)); /* window size */
+
+static int inflate_blocks OF((
+ inflate_blocks_statef *,
+ z_streamp ,
+ int)); /* initial return code */
+
+static void inflate_blocks_reset OF((
+ inflate_blocks_statef *,
+ z_streamp ,
+ uLong *)); /* check value on output */
+
+static int inflate_blocks_free OF((
+ inflate_blocks_statef *,
+ z_streamp));
+
+#if 0
+static void inflate_set_dictionary OF((
+ inflate_blocks_statef *s,
+ const Byte *d, /* dictionary */
+ uInt n)); /* dictionary length */
+
+static int inflate_blocks_sync_point OF((
+ inflate_blocks_statef *s));
+#endif
+
+typedef enum {
+ imMETHOD, /* waiting for method byte */
+ imFLAG, /* waiting for flag byte */
+ imDICT4, /* four dictionary check bytes to go */
+ imDICT3, /* three dictionary check bytes to go */
+ imDICT2, /* two dictionary check bytes to go */
+ imDICT1, /* one dictionary check byte to go */
+ imDICT0, /* waiting for inflateSetDictionary */
+ imBLOCKS, /* decompressing blocks */
+ imCHECK4, /* four check bytes to go */
+ imCHECK3, /* three check bytes to go */
+ imCHECK2, /* two check bytes to go */
+ imCHECK1, /* one check byte to go */
+ imDONE, /* finished check, done */
+ imBAD} /* got an error--stay here */
+inflate_mode;
+
+/* inflate private state */
+struct internal_state {
+
+ /* mode */
+ inflate_mode mode; /* current inflate mode */
+
+ /* mode dependent information */
+ union {
+ uInt method; /* if FLAGS, method byte */
+ struct {
+ uLong was; /* computed check value */
+ uLong need; /* stream check value */
+ } check; /* if CHECK, check values to compare */
+ uInt marker; /* if BAD, inflateSync's marker bytes count */
+ } sub; /* submode */
+
+ /* mode independent information */
+ int nowrap; /* flag for no wrapper */
+ uInt wbits; /* log2(window size) (8..15, defaults to 15) */
+ inflate_blocks_statef
+ *blocks; /* current inflate_blocks state */
+
+};
+
+
+int inflateReset(z_streamp z)
+{
+ if (z == Z_NULL || z->state == Z_NULL)
+ return Z_STREAM_ERROR;
+ z->total_in = z->total_out = 0;
+ z->msg = Z_NULL;
+ z->state->mode = z->state->nowrap ? imBLOCKS : imMETHOD;
+ inflate_blocks_reset(z->state->blocks, z, Z_NULL);
+ Tracev(("inflate: reset\n"));
+ return Z_OK;
+}
+
+
+int inflateEnd(z_streamp z)
+{
+ if (z == Z_NULL || z->state == Z_NULL || z->zfree == Z_NULL)
+ return Z_STREAM_ERROR;
+ if (z->state->blocks != Z_NULL)
+ inflate_blocks_free(z->state->blocks, z);
+ ZFREE(z, z->state);
+ z->state = Z_NULL;
+ Tracev(("inflate: end\n"));
+ return Z_OK;
+}
+
+
+
+int inflateInit2_(z_streamp z, int w, const char *version, int stream_size)
+{
+ if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
+ stream_size != sizeof(z_stream))
+ return Z_VERSION_ERROR;
+
+ /* initialize state */
+ if (z == Z_NULL)
+ return Z_STREAM_ERROR;
+ z->msg = Z_NULL;
+ if (z->zalloc == Z_NULL)
+ {
+ z->zalloc = (void *(*)(void *, unsigned, unsigned))zcalloc;
+ z->opaque = (voidp)0;
+ }
+ if (z->zfree == Z_NULL) z->zfree = (void (*)(void *, void *))zcfree;
+ if ((z->state = (struct internal_state *)
+ ZALLOC(z,1,sizeof(struct internal_state))) == Z_NULL)
+ return Z_MEM_ERROR;
+ z->state->blocks = Z_NULL;
+
+ /* handle undocumented nowrap option (no zlib header or check) */
+ z->state->nowrap = 0;
+ if (w < 0)
+ {
+ w = - w;
+ z->state->nowrap = 1;
+ }
+
+ /* set window size */
+ if (w < 8 || w > 15)
+ {
+ inflateEnd(z);
+ return Z_STREAM_ERROR;
+ }
+ z->state->wbits = (uInt)w;
+
+ /* create inflate_blocks state */
+ if ((z->state->blocks =
+ inflate_blocks_new(z, z->state->nowrap ? Z_NULL : adler32, (uInt)1 << w))
+ == Z_NULL)
+ {
+ inflateEnd(z);
+ return Z_MEM_ERROR;
+ }
+ Tracev(("inflate: allocated\n"));
+
+ /* reset state */
+ inflateReset(z);
+ return Z_OK;
+}
+
+#if 0
+int inflateInit_(z_streamp z, const char *version, int stream_size)
+{
+ return inflateInit2_(z, DEF_WBITS, version, stream_size);
+}
+#endif
+
+#define iNEEDBYTE {if(z->avail_in==0)return r;r=f;}
+#define iNEXTBYTE (z->avail_in--,z->total_in++,*z->next_in++)
+
+int inflate(z_streamp z, int f)
+{
+ int r;
+ uInt b;
+
+ if (z == Z_NULL || z->state == Z_NULL || z->next_in == Z_NULL)
+ return Z_STREAM_ERROR;
+ f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK;
+ r = Z_BUF_ERROR;
+ while (1) switch (z->state->mode)
+ {
+ case imMETHOD:
+ iNEEDBYTE
+ if (((z->state->sub.method = iNEXTBYTE) & 0xf) != Z_DEFLATED)
+ {
+ z->state->mode = imBAD;
+ z->msg = (char*)"unknown compression method";
+ z->state->sub.marker = 5; /* can't try inflateSync */
+ break;
+ }
+ if ((z->state->sub.method >> 4) + 8 > z->state->wbits)
+ {
+ z->state->mode = imBAD;
+ z->msg = (char*)"invalid window size";
+ z->state->sub.marker = 5; /* can't try inflateSync */
+ break;
+ }
+ z->state->mode = imFLAG;
+ case imFLAG:
+ iNEEDBYTE
+ b = iNEXTBYTE;
+ if (((z->state->sub.method << 8) + b) % 31)
+ {
+ z->state->mode = imBAD;
+ z->msg = (char*)"incorrect header check";
+ z->state->sub.marker = 5; /* can't try inflateSync */
+ break;
+ }
+ Tracev(("inflate: zlib header ok\n"));
+ if (!(b & PRESET_DICT))
+ {
+ z->state->mode = imBLOCKS;
+ break;
+ }
+ z->state->mode = imDICT4;
+ case imDICT4:
+ iNEEDBYTE
+ z->state->sub.check.need = (uLong)iNEXTBYTE << 24;
+ z->state->mode = imDICT3;
+ case imDICT3:
+ iNEEDBYTE
+ z->state->sub.check.need += (uLong)iNEXTBYTE << 16;
+ z->state->mode = imDICT2;
+ case imDICT2:
+ iNEEDBYTE
+ z->state->sub.check.need += (uLong)iNEXTBYTE << 8;
+ z->state->mode = imDICT1;
+ case imDICT1:
+ iNEEDBYTE
+ z->state->sub.check.need += (uLong)iNEXTBYTE;
+ z->adler = z->state->sub.check.need;
+ z->state->mode = imDICT0;
+ return Z_NEED_DICT;
+ case imDICT0:
+ z->state->mode = imBAD;
+ z->msg = (char*)"need dictionary";
+ z->state->sub.marker = 0; /* can try inflateSync */
+ return Z_STREAM_ERROR;
+ case imBLOCKS:
+ r = inflate_blocks(z->state->blocks, z, r);
+ if (r == Z_DATA_ERROR)
+ {
+ z->state->mode = imBAD;
+ z->state->sub.marker = 0; /* can try inflateSync */
+ break;
+ }
+ if (r == Z_OK)
+ r = f;
+ if (r != Z_STREAM_END)
+ return r;
+ r = f;
+ inflate_blocks_reset(z->state->blocks, z, &z->state->sub.check.was);
+ if (z->state->nowrap)
+ {
+ z->state->mode = imDONE;
+ break;
+ }
+ z->state->mode = imCHECK4;
+ case imCHECK4:
+ iNEEDBYTE
+ z->state->sub.check.need = (uLong)iNEXTBYTE << 24;
+ z->state->mode = imCHECK3;
+ case imCHECK3:
+ iNEEDBYTE
+ z->state->sub.check.need += (uLong)iNEXTBYTE << 16;
+ z->state->mode = imCHECK2;
+ case imCHECK2:
+ iNEEDBYTE
+ z->state->sub.check.need += (uLong)iNEXTBYTE << 8;
+ z->state->mode = imCHECK1;
+ case imCHECK1:
+ iNEEDBYTE
+ z->state->sub.check.need += (uLong)iNEXTBYTE;
+
+ if (z->state->sub.check.was != z->state->sub.check.need)
+ {
+ z->state->mode = imBAD;
+ z->msg = (char*)"incorrect data check";
+ z->state->sub.marker = 5; /* can't try inflateSync */
+ break;
+ }
+ Tracev(("inflate: zlib check ok\n"));
+ z->state->mode = imDONE;
+ case imDONE:
+ return Z_STREAM_END;
+ case imBAD:
+ return Z_DATA_ERROR;
+ default:
+ return Z_STREAM_ERROR;
+ }
+#ifdef NEED_DUMMY_RETURN
+ return Z_STREAM_ERROR; /* Some dumb compilers complain without this */
+#endif
+}
+
+// defined but not used
+#if 0
+int inflateSetDictionary(z_streamp z, const Byte *dictionary, uInt dictLength)
+{
+ uInt length = dictLength;
+
+ if (z == Z_NULL || z->state == Z_NULL || z->state->mode != imDICT0)
+ return Z_STREAM_ERROR;
+
+ if (adler32(1L, dictionary, dictLength) != z->adler) return Z_DATA_ERROR;
+ z->adler = 1L;
+
+ if (length >= ((uInt)1<<z->state->wbits))
+ {
+ length = (1<<z->state->wbits)-1;
+ dictionary += dictLength - length;
+ }
+ inflate_set_dictionary(z->state->blocks, dictionary, length);
+ z->state->mode = imBLOCKS;
+ return Z_OK;
+}
+
+int inflateSync(z_streamp z)
+{
+ uInt n; /* number of bytes to look at */
+ Byte *p; /* pointer to bytes */
+ uInt m; /* number of marker bytes found in a row */
+ uLong r, w; /* temporaries to save total_in and total_out */
+
+ /* set up */
+ if (z == Z_NULL || z->state == Z_NULL)
+ return Z_STREAM_ERROR;
+ if (z->state->mode != imBAD)
+ {
+ z->state->mode = imBAD;
+ z->state->sub.marker = 0;
+ }
+ if ((n = z->avail_in) == 0)
+ return Z_BUF_ERROR;
+ p = z->next_in;
+ m = z->state->sub.marker;
+
+ /* search */
+ while (n && m < 4)
+ {
+ static const Byte mark[4] = {0, 0, 0xff, 0xff};
+ if (*p == mark[m])
+ m++;
+ else if (*p)
+ m = 0;
+ else
+ m = 4 - m;
+ p++, n--;
+ }
+
+ /* restore */
+ z->total_in += p - z->next_in;
+ z->next_in = p;
+ z->avail_in = n;
+ z->state->sub.marker = m;
+
+ /* return no joy or set up to restart on a new block */
+ if (m != 4)
+ return Z_DATA_ERROR;
+ r = z->total_in; w = z->total_out;
+ inflateReset(z);
+ z->total_in = r; z->total_out = w;
+ z->state->mode = imBLOCKS;
+ return Z_OK;
+}
+
+/* Returns true if inflate is currently at the end of a block generated
+ * by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
+ * implementation to provide an additional safety check. PPP uses Z_SYNC_FLUSH
+ * but removes the length bytes of the resulting empty stored block. When
+ * decompressing, PPP checks that at the end of input packet, inflate is
+ * waiting for these length bytes.
+ */
+int inflateSyncPoint(z_streamp z)
+{
+ if (z == Z_NULL || z->state == Z_NULL || z->state->blocks == Z_NULL)
+ return Z_STREAM_ERROR;
+ return inflate_blocks_sync_point(z->state->blocks);
+}
+#endif
+
+voidp zcalloc (voidp opaque, unsigned items, unsigned size)
+{
+ if (opaque) items += size - size; /* make compiler happy */
+ return (voidp)Z_Malloc(items*size);
+}
+
+void zcfree (voidp opaque, voidp ptr)
+{
+ Z_Free(ptr);
+ if (opaque) return; /* make compiler happy */
+}
+
+
diff --git a/code/qcommon/unzip.h b/code/qcommon/unzip.h
new file mode 100755
index 0000000..53cb66b
--- /dev/null
+++ b/code/qcommon/unzip.h
@@ -0,0 +1,336 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#if defined(STRICTUNZIP) || defined(STRICTZIPUNZIP)
+/* like the STRICT of WIN32, we define a pointer that cannot be converted
+ from (void*) without cast */
+typedef struct TagunzFile__ { int unused; } unzFile__;
+typedef unzFile__ *unzFile;
+#else
+typedef void* unzFile;
+#endif
+
+/* tm_unz contain date/time info */
+typedef struct tm_unz_s
+{
+ unsigned int tm_sec; /* seconds after the minute - [0,59] */
+ unsigned int tm_min; /* minutes after the hour - [0,59] */
+ unsigned int tm_hour; /* hours since midnight - [0,23] */
+ unsigned int tm_mday; /* day of the month - [1,31] */
+ unsigned int tm_mon; /* months since January - [0,11] */
+ unsigned int tm_year; /* years - [1980..2044] */
+} tm_unz;
+
+/* unz_global_info structure contain global data about the ZIPfile
+ These data comes from the end of central dir */
+typedef struct unz_global_info_s
+{
+ unsigned long number_entry; /* total number of entries in the central dir on this disk */
+ unsigned long size_comment; /* size of the global comment of the zipfile */
+} unz_global_info;
+
+
+/* unz_file_info contain information about a file in the zipfile */
+typedef struct unz_file_info_s
+{
+ unsigned long version; /* version made by 2 unsigned chars */
+ unsigned long version_needed; /* version needed to extract 2 unsigned chars */
+ unsigned long flag; /* general purpose bit flag 2 unsigned chars */
+ unsigned long compression_method; /* compression method 2 unsigned chars */
+ unsigned long dosDate; /* last mod file date in Dos fmt 4 unsigned chars */
+ unsigned long crc; /* crc-32 4 unsigned chars */
+ unsigned long compressed_size; /* compressed size 4 unsigned chars */
+ unsigned long uncompressed_size; /* uncompressed size 4 unsigned chars */
+ unsigned long size_filename; /* filename length 2 unsigned chars */
+ unsigned long size_file_extra; /* extra field length 2 unsigned chars */
+ unsigned long size_file_comment; /* file comment length 2 unsigned chars */
+
+ unsigned long disk_num_start; /* disk number start 2 unsigned chars */
+ unsigned long internal_fa; /* internal file attributes 2 unsigned chars */
+ unsigned long external_fa; /* external file attributes 4 unsigned chars */
+
+ tm_unz tmu_date;
+} unz_file_info;
+
+/* unz_file_info_interntal contain internal info about a file in zipfile*/
+typedef struct unz_file_info_internal_s
+{
+ unsigned long offset_curfile;/* relative offset of static header 4 unsigned chars */
+} unz_file_info_internal;
+
+typedef void* (*alloc_func) (void* opaque, unsigned int items, unsigned int size);
+typedef void (*free_func) (void* opaque, void* address);
+
+struct internal_state;
+
+typedef struct z_stream_s {
+ unsigned char *next_in; /* next input unsigned char */
+ unsigned int avail_in; /* number of unsigned chars available at next_in */
+ unsigned long total_in; /* total nb of input unsigned chars read so */
+
+ unsigned char *next_out; /* next output unsigned char should be put there */
+ unsigned int avail_out; /* remaining free space at next_out */
+ unsigned long total_out; /* total nb of unsigned chars output so */
+
+ char *msg; /* last error message, NULL if no error */
+ struct internal_state *state; /* not visible by applications */
+
+ alloc_func zalloc; /* used to allocate the internal state */
+ free_func zfree; /* used to free the internal state */
+ unsigned char* opaque; /* private data object passed to zalloc and zfree */
+
+ int data_type; /* best guess about the data type: ascii or binary */
+ unsigned long adler; /* adler32 value of the uncompressed data */
+ unsigned long reserved; /* reserved for future use */
+} z_stream;
+
+typedef z_stream *z_streamp;
+
+
+/* file_in_zip_read_info_s contain internal information about a file in zipfile,
+ when reading and decompress it */
+typedef struct
+{
+ char *read_buffer; /* internal buffer for compressed data */
+ z_stream stream; /* zLib stream structure for inflate */
+
+ unsigned long pos_in_zipfile; /* position in unsigned char on the zipfile, for fseek*/
+ unsigned long stream_initialised; /* flag set if stream structure is initialised*/
+
+ unsigned long offset_local_extrafield;/* offset of the static extra field */
+ unsigned int size_local_extrafield;/* size of the static extra field */
+ unsigned long pos_local_extrafield; /* position in the static extra field in read*/
+
+ unsigned long crc32; /* crc32 of all data uncompressed */
+ unsigned long crc32_wait; /* crc32 we must obtain after decompress all */
+ unsigned long rest_read_compressed; /* number of unsigned char to be decompressed */
+ unsigned long rest_read_uncompressed;/*number of unsigned char to be obtained after decomp*/
+ FILE* file; /* io structore of the zipfile */
+ unsigned long compression_method; /* compression method (0==store) */
+ unsigned long byte_before_the_zipfile;/* unsigned char before the zipfile, (>0 for sfx)*/
+} file_in_zip_read_info_s;
+
+
+/* unz_s contain internal information about the zipfile
+*/
+typedef struct
+{
+ FILE* file; /* io structore of the zipfile */
+ unz_global_info gi; /* public global information */
+ unsigned long byte_before_the_zipfile;/* unsigned char before the zipfile, (>0 for sfx)*/
+ unsigned long num_file; /* number of the current file in the zipfile*/
+ unsigned long pos_in_central_dir; /* pos of the current file in the central dir*/
+ unsigned long current_file_ok; /* flag about the usability of the current file*/
+ unsigned long central_pos; /* position of the beginning of the central dir*/
+
+ unsigned long size_central_dir; /* size of the central directory */
+ unsigned long offset_central_dir; /* offset of start of central directory with
+ respect to the starting disk number */
+
+ unz_file_info cur_file_info; /* public info about the current file in zip*/
+ unz_file_info_internal cur_file_info_internal; /* private info about it*/
+ file_in_zip_read_info_s* pfile_in_zip_read; /* structure about the current
+ file if we are decompressing it */
+ unsigned char* tmpFile;
+ int tmpPos,tmpSize;
+} unz_s;
+
+#define UNZ_OK (0)
+#define UNZ_END_OF_LIST_OF_FILE (-100)
+#define UNZ_ERRNO (Z_ERRNO)
+#define UNZ_EOF (0)
+#define UNZ_PARAMERROR (-102)
+#define UNZ_BADZIPFILE (-103)
+#define UNZ_INTERNALERROR (-104)
+#define UNZ_CRCERROR (-105)
+
+#define UNZ_CASESENSITIVE 1
+#define UNZ_NOTCASESENSITIVE 2
+#define UNZ_OSDEFAULTCASE 0
+
+extern int unzStringFileNameCompare (const char* fileName1, const char* fileName2, int iCaseSensitivity);
+
+/*
+ Compare two filename (fileName1,fileName2).
+ If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp)
+ If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi
+ or strcasecmp)
+ If iCaseSenisivity = 0, case sensitivity is defaut of your operating system
+ (like 1 on Unix, 2 on Windows)
+*/
+
+extern unzFile unzOpen (const char *path);
+extern unzFile unzReOpen (const char* path, unzFile file);
+
+/*
+ Open a Zip file. path contain the full pathname (by example,
+ on a Windows NT computer "c:\\zlib\\zlib111.zip" or on an Unix computer
+ "zlib/zlib111.zip".
+ If the zipfile cannot be opened (file don't exist or in not valid), the
+ return value is NULL.
+ Else, the return value is a unzFile Handle, usable with other function
+ of this unzip package.
+*/
+
+extern int unzClose (unzFile file);
+
+/*
+ Close a ZipFile opened with unzipOpen.
+ If there is files inside the .Zip opened with unzOpenCurrentFile (see later),
+ these files MUST be closed with unzipCloseCurrentFile before call unzipClose.
+ return UNZ_OK if there is no problem. */
+
+extern int unzGetGlobalInfo (unzFile file, unz_global_info *pglobal_info);
+
+/*
+ Write info about the ZipFile in the *pglobal_info structure.
+ No preparation of the structure is needed
+ return UNZ_OK if there is no problem. */
+
+
+extern int unzGetGlobalComment (unzFile file, char *szComment, unsigned long uSizeBuf);
+
+/*
+ Get the global comment string of the ZipFile, in the szComment buffer.
+ uSizeBuf is the size of the szComment buffer.
+ return the number of unsigned char copied or an error code <0
+*/
+
+
+/***************************************************************************/
+/* Unzip package allow you browse the directory of the zipfile */
+
+extern int unzGoToFirstFile (unzFile file);
+
+/*
+ Set the current file of the zipfile to the first file.
+ return UNZ_OK if there is no problem
+*/
+
+extern int unzGoToNextFile (unzFile file);
+
+/*
+ Set the current file of the zipfile to the next file.
+ return UNZ_OK if there is no problem
+ return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest.
+*/
+
+extern int unzGetCurrentFileInfoPosition (unzFile file, unsigned long *pos );
+
+/*
+ Get the position of the info of the current file in the zip.
+ return UNZ_OK if there is no problem
+*/
+
+extern int unzSetCurrentFileInfoPosition (unzFile file, unsigned long pos );
+
+/*
+ Set the position of the info of the current file in the zip.
+ return UNZ_OK if there is no problem
+*/
+
+extern int unzLocateFile (unzFile file, const char *szFileName, int iCaseSensitivity);
+
+/*
+ Try locate the file szFileName in the zipfile.
+ For the iCaseSensitivity signification, see unzStringFileNameCompare
+
+ return value :
+ UNZ_OK if the file is found. It becomes the current file.
+ UNZ_END_OF_LIST_OF_FILE if the file is not found
+*/
+
+
+extern int unzGetCurrentFileInfo (unzFile file, unz_file_info *pfile_info, char *szFileName, unsigned long fileNameBufferSize, void *extraField, unsigned long extraFieldBufferSize, char *szComment, unsigned long commentBufferSize);
+
+/*
+ Get Info about the current file
+ if pfile_info!=NULL, the *pfile_info structure will contain somes info about
+ the current file
+ if szFileName!=NULL, the filemane string will be copied in szFileName
+ (fileNameBufferSize is the size of the buffer)
+ if extraField!=NULL, the extra field information will be copied in extraField
+ (extraFieldBufferSize is the size of the buffer).
+ This is the Central-header version of the extra field
+ if szComment!=NULL, the comment string of the file will be copied in szComment
+ (commentBufferSize is the size of the buffer)
+*/
+
+/***************************************************************************/
+/* for reading the content of the current zipfile, you can open it, read data
+ from it, and close it (you can close it before reading all the file)
+ */
+
+extern int unzOpenCurrentFile (unzFile file);
+
+/*
+ Open for reading data the current file in the zipfile.
+ If there is no error, the return value is UNZ_OK.
+*/
+
+extern int unzCloseCurrentFile (unzFile file);
+
+/*
+ Close the file in zip opened with unzOpenCurrentFile
+ Return UNZ_CRCERROR if all the file was read but the CRC is not good
+*/
+
+
+extern int unzReadCurrentFile (unzFile file, void* buf, unsigned len);
+
+/*
+ Read unsigned chars from the current file (opened by unzOpenCurrentFile)
+ buf contain buffer where data must be copied
+ len the size of buf.
+
+ return the number of unsigned char copied if somes unsigned chars are copied
+ return 0 if the end of file was reached
+ return <0 with error code if there is an error
+ (UNZ_ERRNO for IO error, or zLib error for uncompress error)
+*/
+
+extern long unztell(unzFile file);
+
+/*
+ Give the current position in uncompressed data
+*/
+
+extern int unzeof (unzFile file);
+
+/*
+ return 1 if the end of file was reached, 0 elsewhere
+*/
+
+extern int unzGetLocalExtrafield (unzFile file, void* buf, unsigned len);
+
+/*
+ Read extra field from the current file (opened by unzOpenCurrentFile)
+ This is the local-header version of the extra field (sometimes, there is
+ more info in the local-header version than in the central-header)
+
+ if buf==NULL, it return the size of the local extra field
+
+ if buf!=NULL, len is the size of the buffer, the extra header is copied in
+ buf.
+ the return value is the number of unsigned chars copied in buf, or (if <0)
+ the error code
+*/
diff --git a/code/qcommon/vm.c b/code/qcommon/vm.c
new file mode 100755
index 0000000..923c6ec
--- /dev/null
+++ b/code/qcommon/vm.c
@@ -0,0 +1,835 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// vm.c -- virtual machine
+
+/*
+
+
+intermix code and data
+symbol table
+
+a dll has one imported function: VM_SystemCall
+and one exported function: Perform
+
+
+*/
+
+#include "vm_local.h"
+
+
+vm_t *currentVM = NULL; // bk001212
+vm_t *lastVM = NULL; // bk001212
+int vm_debugLevel;
+
+#define MAX_VM 3
+vm_t vmTable[MAX_VM];
+
+
+void VM_VmInfo_f( void );
+void VM_VmProfile_f( void );
+
+
+// converts a VM pointer to a C pointer and
+// checks to make sure that the range is acceptable
+void *VM_VM2C( vmptr_t p, int length ) {
+ return (void *)p;
+}
+
+void VM_Debug( int level ) {
+ vm_debugLevel = level;
+}
+
+/*
+==============
+VM_Init
+==============
+*/
+void VM_Init( void ) {
+ Cvar_Get( "vm_cgame", "2", CVAR_ARCHIVE ); // !@# SHIP WITH SET TO 2
+ Cvar_Get( "vm_game", "2", CVAR_ARCHIVE ); // !@# SHIP WITH SET TO 2
+ Cvar_Get( "vm_ui", "2", CVAR_ARCHIVE ); // !@# SHIP WITH SET TO 2
+
+ Cmd_AddCommand ("vmprofile", VM_VmProfile_f );
+ Cmd_AddCommand ("vminfo", VM_VmInfo_f );
+
+ Com_Memset( vmTable, 0, sizeof( vmTable ) );
+}
+
+
+/*
+===============
+VM_ValueToSymbol
+
+Assumes a program counter value
+===============
+*/
+const char *VM_ValueToSymbol( vm_t *vm, int value ) {
+ vmSymbol_t *sym;
+ static char text[MAX_TOKEN_CHARS];
+
+ sym = vm->symbols;
+ if ( !sym ) {
+ return "NO SYMBOLS";
+ }
+
+ // find the symbol
+ while ( sym->next && sym->next->symValue <= value ) {
+ sym = sym->next;
+ }
+
+ if ( value == sym->symValue ) {
+ return sym->symName;
+ }
+
+ Com_sprintf( text, sizeof( text ), "%s+%i", sym->symName, value - sym->symValue );
+
+ return text;
+}
+
+/*
+===============
+VM_ValueToFunctionSymbol
+
+For profiling, find the symbol behind this value
+===============
+*/
+vmSymbol_t *VM_ValueToFunctionSymbol( vm_t *vm, int value ) {
+ vmSymbol_t *sym;
+ static vmSymbol_t nullSym;
+
+ sym = vm->symbols;
+ if ( !sym ) {
+ return &nullSym;
+ }
+
+ while ( sym->next && sym->next->symValue <= value ) {
+ sym = sym->next;
+ }
+
+ return sym;
+}
+
+
+/*
+===============
+VM_SymbolToValue
+===============
+*/
+int VM_SymbolToValue( vm_t *vm, const char *symbol ) {
+ vmSymbol_t *sym;
+
+ for ( sym = vm->symbols ; sym ; sym = sym->next ) {
+ if ( !strcmp( symbol, sym->symName ) ) {
+ return sym->symValue;
+ }
+ }
+ return 0;
+}
+
+
+/*
+=====================
+VM_SymbolForCompiledPointer
+=====================
+*/
+const char *VM_SymbolForCompiledPointer( vm_t *vm, void *code ) {
+ int i;
+
+ if ( code < (void *)vm->codeBase ) {
+ return "Before code block";
+ }
+ if ( code >= (void *)(vm->codeBase + vm->codeLength) ) {
+ return "After code block";
+ }
+
+ // find which original instruction it is after
+ for ( i = 0 ; i < vm->codeLength ; i++ ) {
+ if ( (void *)vm->instructionPointers[i] > code ) {
+ break;
+ }
+ }
+ i--;
+
+ // now look up the bytecode instruction pointer
+ return VM_ValueToSymbol( vm, i );
+}
+
+
+
+/*
+===============
+ParseHex
+===============
+*/
+int ParseHex( const char *text ) {
+ int value;
+ int c;
+
+ value = 0;
+ while ( ( c = *text++ ) != 0 ) {
+ if ( c >= '0' && c <= '9' ) {
+ value = value * 16 + c - '0';
+ continue;
+ }
+ if ( c >= 'a' && c <= 'f' ) {
+ value = value * 16 + 10 + c - 'a';
+ continue;
+ }
+ if ( c >= 'A' && c <= 'F' ) {
+ value = value * 16 + 10 + c - 'A';
+ continue;
+ }
+ }
+
+ return value;
+}
+
+/*
+===============
+VM_LoadSymbols
+===============
+*/
+void VM_LoadSymbols( vm_t *vm ) {
+ int len;
+ char *mapfile, *text_p, *token;
+ char name[MAX_QPATH];
+ char symbols[MAX_QPATH];
+ vmSymbol_t **prev, *sym;
+ int count;
+ int value;
+ int chars;
+ int segment;
+ int numInstructions;
+
+ // don't load symbols if not developer
+ if ( !com_developer->integer ) {
+ return;
+ }
+
+ COM_StripExtension( vm->name, name );
+ Com_sprintf( symbols, sizeof( symbols ), "vm/%s.map", name );
+ len = FS_ReadFile( symbols, (void **)&mapfile );
+ if ( !mapfile ) {
+ Com_Printf( "Couldn't load symbol file: %s\n", symbols );
+ return;
+ }
+
+ numInstructions = vm->instructionPointersLength >> 2;
+
+ // parse the symbols
+ text_p = mapfile;
+ prev = &vm->symbols;
+ count = 0;
+
+ while ( 1 ) {
+ token = COM_Parse( &text_p );
+ if ( !token[0] ) {
+ break;
+ }
+ segment = ParseHex( token );
+ if ( segment ) {
+ COM_Parse( &text_p );
+ COM_Parse( &text_p );
+ continue; // only load code segment values
+ }
+
+ token = COM_Parse( &text_p );
+ if ( !token[0] ) {
+ Com_Printf( "WARNING: incomplete line at end of file\n" );
+ break;
+ }
+ value = ParseHex( token );
+
+ token = COM_Parse( &text_p );
+ if ( !token[0] ) {
+ Com_Printf( "WARNING: incomplete line at end of file\n" );
+ break;
+ }
+ chars = strlen( token );
+ sym = Hunk_Alloc( sizeof( *sym ) + chars, h_high );
+ *prev = sym;
+ prev = &sym->next;
+ sym->next = NULL;
+
+ // convert value from an instruction number to a code offset
+ if ( value >= 0 && value < numInstructions ) {
+ value = vm->instructionPointers[value];
+ }
+
+ sym->symValue = value;
+ Q_strncpyz( sym->symName, token, chars + 1 );
+
+ count++;
+ }
+
+ vm->numSymbols = count;
+ Com_Printf( "%i symbols parsed from %s\n", count, symbols );
+ FS_FreeFile( mapfile );
+}
+
+/*
+============
+VM_DllSyscall
+
+Dlls will call this directly
+
+ rcg010206 The horror; the horror.
+
+ The syscall mechanism relies on stack manipulation to get it's args.
+ This is likely due to C's inability to pass "..." parameters to
+ a function in one clean chunk. On PowerPC Linux, these parameters
+ are not necessarily passed on the stack, so while (&arg[0] == arg)
+ is true, (&arg[1] == 2nd function parameter) is not necessarily
+ accurate, as arg's value might have been stored to the stack or
+ other piece of scratch memory to give it a valid address, but the
+ next parameter might still be sitting in a register.
+
+ Quake's syscall system also assumes that the stack grows downward,
+ and that any needed types can be squeezed, safely, into a signed int.
+
+ This hack below copies all needed values for an argument to a
+ array in memory, so that Quake can get the correct values. This can
+ also be used on systems where the stack grows upwards, as the
+ presumably standard and safe stdargs.h macros are used.
+
+ As for having enough space in a signed int for your datatypes, well,
+ it might be better to wait for DOOM 3 before you start porting. :)
+
+ The original code, while probably still inherently dangerous, seems
+ to work well enough for the platforms it already works on. Rather
+ than add the performance hit for those platforms, the original code
+ is still in use there.
+
+ For speed, we just grab 15 arguments, and don't worry about exactly
+ how many the syscall actually needs; the extra is thrown away.
+
+============
+*/
+int QDECL VM_DllSyscall( int arg, ... ) {
+#if ((defined __linux__) && (defined __powerpc__))
+ // rcg010206 - see commentary above
+ int args[16];
+ int i;
+ va_list ap;
+
+ args[0] = arg;
+
+ va_start(ap, arg);
+ for (i = 1; i < sizeof (args) / sizeof (args[i]); i++)
+ args[i] = va_arg(ap, int);
+ va_end(ap);
+
+ return currentVM->systemCall( args );
+#else // original id code
+ return currentVM->systemCall( &arg );
+#endif
+}
+
+/*
+=================
+VM_Restart
+
+Reload the data, but leave everything else in place
+This allows a server to do a map_restart without changing memory allocation
+=================
+*/
+vm_t *VM_Restart( vm_t *vm ) {
+ vmHeader_t *header;
+ int length;
+ int dataLength;
+ int i;
+ char filename[MAX_QPATH];
+
+ // DLL's can't be restarted in place
+ if ( vm->dllHandle ) {
+ char name[MAX_QPATH];
+ int (*systemCall)( int *parms );
+
+ systemCall = vm->systemCall;
+ Q_strncpyz( name, vm->name, sizeof( name ) );
+
+ VM_Free( vm );
+
+ vm = VM_Create( name, systemCall, VMI_NATIVE );
+ return vm;
+ }
+
+ // load the image
+ Com_Printf( "VM_Restart()\n", filename );
+ Com_sprintf( filename, sizeof(filename), "vm/%s.qvm", vm->name );
+ Com_Printf( "Loading vm file %s.\n", filename );
+ length = FS_ReadFile( filename, (void **)&header );
+ if ( !header ) {
+ Com_Error( ERR_DROP, "VM_Restart failed.\n" );
+ }
+
+ // byte swap the header
+ for ( i = 0 ; i < sizeof( *header ) / 4 ; i++ ) {
+ ((int *)header)[i] = LittleLong( ((int *)header)[i] );
+ }
+
+ // validate
+ if ( header->vmMagic != VM_MAGIC
+ || header->bssLength < 0
+ || header->dataLength < 0
+ || header->litLength < 0
+ || header->codeLength <= 0 ) {
+ VM_Free( vm );
+ Com_Error( ERR_FATAL, "%s has bad header", filename );
+ }
+
+ // round up to next power of 2 so all data operations can
+ // be mask protected
+ dataLength = header->dataLength + header->litLength + header->bssLength;
+ for ( i = 0 ; dataLength > ( 1 << i ) ; i++ ) {
+ }
+ dataLength = 1 << i;
+
+ // clear the data
+ Com_Memset( vm->dataBase, 0, dataLength );
+
+ // copy the intialized data
+ Com_Memcpy( vm->dataBase, (byte *)header + header->dataOffset, header->dataLength + header->litLength );
+
+ // byte swap the longs
+ for ( i = 0 ; i < header->dataLength ; i += 4 ) {
+ *(int *)(vm->dataBase + i) = LittleLong( *(int *)(vm->dataBase + i ) );
+ }
+
+ // free the original file
+ FS_FreeFile( header );
+
+ return vm;
+}
+
+/*
+================
+VM_Create
+
+If image ends in .qvm it will be interpreted, otherwise
+it will attempt to load as a system dll
+================
+*/
+
+#define STACK_SIZE 0x20000
+
+vm_t *VM_Create( const char *module, int (*systemCalls)(int *),
+ vmInterpret_t interpret ) {
+ vm_t *vm;
+ vmHeader_t *header;
+ int length;
+ int dataLength;
+ int i, remaining;
+ char filename[MAX_QPATH];
+
+ if ( !module || !module[0] || !systemCalls ) {
+ Com_Error( ERR_FATAL, "VM_Create: bad parms" );
+ }
+
+ remaining = Hunk_MemoryRemaining();
+
+ // see if we already have the VM
+ for ( i = 0 ; i < MAX_VM ; i++ ) {
+ if (!Q_stricmp(vmTable[i].name, module)) {
+ vm = &vmTable[i];
+ return vm;
+ }
+ }
+
+ // find a free vm
+ for ( i = 0 ; i < MAX_VM ; i++ ) {
+ if ( !vmTable[i].name[0] ) {
+ break;
+ }
+ }
+
+ if ( i == MAX_VM ) {
+ Com_Error( ERR_FATAL, "VM_Create: no free vm_t" );
+ }
+
+ vm = &vmTable[i];
+
+ Q_strncpyz( vm->name, module, sizeof( vm->name ) );
+ vm->systemCall = systemCalls;
+
+ // never allow dll loading with a demo
+ if ( interpret == VMI_NATIVE ) {
+ if ( Cvar_VariableValue( "fs_restrict" ) ) {
+ interpret = VMI_COMPILED;
+ }
+ }
+
+ if ( interpret == VMI_NATIVE ) {
+ // try to load as a system dll
+ Com_Printf( "Loading dll file %s.\n", vm->name );
+ vm->dllHandle = Sys_LoadDll( module, vm->fqpath , &vm->entryPoint, VM_DllSyscall );
+ if ( vm->dllHandle ) {
+ return vm;
+ }
+
+ Com_Printf( "Failed to load dll, looking for qvm.\n" );
+ interpret = VMI_COMPILED;
+ }
+
+ // load the image
+ Com_sprintf( filename, sizeof(filename), "vm/%s.qvm", vm->name );
+ Com_Printf( "Loading vm file %s.\n", filename );
+ length = FS_ReadFile( filename, (void **)&header );
+ if ( !header ) {
+ Com_Printf( "Failed.\n" );
+ VM_Free( vm );
+ return NULL;
+ }
+
+ // byte swap the header
+ for ( i = 0 ; i < sizeof( *header ) / 4 ; i++ ) {
+ ((int *)header)[i] = LittleLong( ((int *)header)[i] );
+ }
+
+ // validate
+ if ( header->vmMagic != VM_MAGIC
+ || header->bssLength < 0
+ || header->dataLength < 0
+ || header->litLength < 0
+ || header->codeLength <= 0 ) {
+ VM_Free( vm );
+ Com_Error( ERR_FATAL, "%s has bad header", filename );
+ }
+
+ // round up to next power of 2 so all data operations can
+ // be mask protected
+ dataLength = header->dataLength + header->litLength + header->bssLength;
+ for ( i = 0 ; dataLength > ( 1 << i ) ; i++ ) {
+ }
+ dataLength = 1 << i;
+
+ // allocate zero filled space for initialized and uninitialized data
+ vm->dataBase = Hunk_Alloc( dataLength, h_high );
+ vm->dataMask = dataLength - 1;
+
+ // copy the intialized data
+ Com_Memcpy( vm->dataBase, (byte *)header + header->dataOffset, header->dataLength + header->litLength );
+
+ // byte swap the longs
+ for ( i = 0 ; i < header->dataLength ; i += 4 ) {
+ *(int *)(vm->dataBase + i) = LittleLong( *(int *)(vm->dataBase + i ) );
+ }
+
+ // allocate space for the jump targets, which will be filled in by the compile/prep functions
+ vm->instructionPointersLength = header->instructionCount * 4;
+ vm->instructionPointers = Hunk_Alloc( vm->instructionPointersLength, h_high );
+
+ // copy or compile the instructions
+ vm->codeLength = header->codeLength;
+
+ if ( interpret >= VMI_COMPILED ) {
+ vm->compiled = qtrue;
+ VM_Compile( vm, header );
+ } else {
+ vm->compiled = qfalse;
+ VM_PrepareInterpreter( vm, header );
+ }
+
+ // free the original file
+ FS_FreeFile( header );
+
+ // load the map file
+ VM_LoadSymbols( vm );
+
+ // the stack is implicitly at the end of the image
+ vm->programStack = vm->dataMask + 1;
+ vm->stackBottom = vm->programStack - STACK_SIZE;
+
+ Com_Printf("%s loaded in %d bytes on the hunk\n", module, remaining - Hunk_MemoryRemaining());
+
+ return vm;
+}
+
+/*
+==============
+VM_Free
+==============
+*/
+void VM_Free( vm_t *vm ) {
+
+ if ( vm->dllHandle ) {
+ Sys_UnloadDll( vm->dllHandle );
+ Com_Memset( vm, 0, sizeof( *vm ) );
+ }
+#if 0 // now automatically freed by hunk
+ if ( vm->codeBase ) {
+ Z_Free( vm->codeBase );
+ }
+ if ( vm->dataBase ) {
+ Z_Free( vm->dataBase );
+ }
+ if ( vm->instructionPointers ) {
+ Z_Free( vm->instructionPointers );
+ }
+#endif
+ Com_Memset( vm, 0, sizeof( *vm ) );
+
+ currentVM = NULL;
+ lastVM = NULL;
+}
+
+void VM_Clear(void) {
+ int i;
+ for (i=0;i<MAX_VM; i++) {
+ if ( vmTable[i].dllHandle ) {
+ Sys_UnloadDll( vmTable[i].dllHandle );
+ }
+ Com_Memset( &vmTable[i], 0, sizeof( vm_t ) );
+ }
+ currentVM = NULL;
+ lastVM = NULL;
+}
+
+void *VM_ArgPtr( int intValue ) {
+ if ( !intValue ) {
+ return NULL;
+ }
+ // bk001220 - currentVM is missing on reconnect
+ if ( currentVM==NULL )
+ return NULL;
+
+ if ( currentVM->entryPoint ) {
+ return (void *)(currentVM->dataBase + intValue);
+ }
+ else {
+ return (void *)(currentVM->dataBase + (intValue & currentVM->dataMask));
+ }
+}
+
+void *VM_ExplicitArgPtr( vm_t *vm, int intValue ) {
+ if ( !intValue ) {
+ return NULL;
+ }
+
+ // bk010124 - currentVM is missing on reconnect here as well?
+ if ( currentVM==NULL )
+ return NULL;
+
+ //
+ if ( vm->entryPoint ) {
+ return (void *)(vm->dataBase + intValue);
+ }
+ else {
+ return (void *)(vm->dataBase + (intValue & vm->dataMask));
+ }
+}
+
+
+/*
+==============
+VM_Call
+
+
+Upon a system call, the stack will look like:
+
+sp+32 parm1
+sp+28 parm0
+sp+24 return value
+sp+20 return address
+sp+16 local1
+sp+14 local0
+sp+12 arg1
+sp+8 arg0
+sp+4 return stack
+sp return address
+
+An interpreted function will immediately execute
+an OP_ENTER instruction, which will subtract space for
+locals from sp
+==============
+*/
+#define MAX_STACK 256
+#define STACK_MASK (MAX_STACK-1)
+
+int QDECL VM_Call( vm_t *vm, int callnum, ... ) {
+ vm_t *oldVM;
+ int r;
+ int i;
+ int args[16];
+ va_list ap;
+
+
+ if ( !vm ) {
+ Com_Error( ERR_FATAL, "VM_Call with NULL vm" );
+ }
+
+ oldVM = currentVM;
+ currentVM = vm;
+ lastVM = vm;
+
+ if ( vm_debugLevel ) {
+ Com_Printf( "VM_Call( %i )\n", callnum );
+ }
+
+ // if we have a dll loaded, call it directly
+ if ( vm->entryPoint ) {
+ //rcg010207 - see dissertation at top of VM_DllSyscall() in this file.
+ va_start(ap, callnum);
+ for (i = 0; i < sizeof (args) / sizeof (args[i]); i++) {
+ args[i] = va_arg(ap, int);
+ }
+ va_end(ap);
+
+ r = vm->entryPoint( callnum, args[0], args[1], args[2], args[3],
+ args[4], args[5], args[6], args[7],
+ args[8], args[9], args[10], args[11],
+ args[12], args[13], args[14], args[15]);
+ } else if ( vm->compiled ) {
+ r = VM_CallCompiled( vm, &callnum );
+ } else {
+ r = VM_CallInterpreted( vm, &callnum );
+ }
+
+ if ( oldVM != NULL ) // bk001220 - assert(currentVM!=NULL) for oldVM==NULL
+ currentVM = oldVM;
+ return r;
+}
+
+//=================================================================
+
+static int QDECL VM_ProfileSort( const void *a, const void *b ) {
+ vmSymbol_t *sa, *sb;
+
+ sa = *(vmSymbol_t **)a;
+ sb = *(vmSymbol_t **)b;
+
+ if ( sa->profileCount < sb->profileCount ) {
+ return -1;
+ }
+ if ( sa->profileCount > sb->profileCount ) {
+ return 1;
+ }
+ return 0;
+}
+
+/*
+==============
+VM_VmProfile_f
+
+==============
+*/
+void VM_VmProfile_f( void ) {
+ vm_t *vm;
+ vmSymbol_t **sorted, *sym;
+ int i;
+ double total;
+
+ if ( !lastVM ) {
+ return;
+ }
+
+ vm = lastVM;
+
+ if ( !vm->numSymbols ) {
+ return;
+ }
+
+ sorted = Z_Malloc( vm->numSymbols * sizeof( *sorted ) );
+ sorted[0] = vm->symbols;
+ total = sorted[0]->profileCount;
+ for ( i = 1 ; i < vm->numSymbols ; i++ ) {
+ sorted[i] = sorted[i-1]->next;
+ total += sorted[i]->profileCount;
+ }
+
+ qsort( sorted, vm->numSymbols, sizeof( *sorted ), VM_ProfileSort );
+
+ for ( i = 0 ; i < vm->numSymbols ; i++ ) {
+ int perc;
+
+ sym = sorted[i];
+
+ perc = 100 * (float) sym->profileCount / total;
+ Com_Printf( "%2i%% %9i %s\n", perc, sym->profileCount, sym->symName );
+ sym->profileCount = 0;
+ }
+
+ Com_Printf(" %9.0f total\n", total );
+
+ Z_Free( sorted );
+}
+
+/*
+==============
+VM_VmInfo_f
+
+==============
+*/
+void VM_VmInfo_f( void ) {
+ vm_t *vm;
+ int i;
+
+ Com_Printf( "Registered virtual machines:\n" );
+ for ( i = 0 ; i < MAX_VM ; i++ ) {
+ vm = &vmTable[i];
+ if ( !vm->name[0] ) {
+ break;
+ }
+ Com_Printf( "%s : ", vm->name );
+ if ( vm->dllHandle ) {
+ Com_Printf( "native\n" );
+ continue;
+ }
+ if ( vm->compiled ) {
+ Com_Printf( "compiled on load\n" );
+ } else {
+ Com_Printf( "interpreted\n" );
+ }
+ Com_Printf( " code length : %7i\n", vm->codeLength );
+ Com_Printf( " table length: %7i\n", vm->instructionPointersLength );
+ Com_Printf( " data length : %7i\n", vm->dataMask + 1 );
+ }
+}
+
+/*
+===============
+VM_LogSyscalls
+
+Insert calls to this while debugging the vm compiler
+===============
+*/
+void VM_LogSyscalls( int *args ) {
+ static int callnum;
+ static FILE *f;
+
+ if ( !f ) {
+ f = fopen("syscalls.log", "w" );
+ }
+ callnum++;
+ fprintf(f, "%i: %i (%i) = %i %i %i %i\n", callnum, args - (int *)currentVM->dataBase,
+ args[0], args[1], args[2], args[3], args[4] );
+}
+
+
+
+#ifdef oDLL_ONLY // bk010215 - for DLL_ONLY dedicated servers/builds w/o VM
+int VM_CallCompiled( vm_t *vm, int *args ) {
+ return(0);
+}
+
+void VM_Compile( vm_t *vm, vmHeader_t *header ) {}
+#endif // DLL_ONLY
diff --git a/code/qcommon/vm_interpreted.c b/code/qcommon/vm_interpreted.c
new file mode 100755
index 0000000..f52b5d4
--- /dev/null
+++ b/code/qcommon/vm_interpreted.c
@@ -0,0 +1,889 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "vm_local.h"
+
+#ifdef DEBUG_VM // bk001204
+static char *opnames[256] = {
+ "OP_UNDEF",
+
+ "OP_IGNORE",
+
+ "OP_BREAK",
+
+ "OP_ENTER",
+ "OP_LEAVE",
+ "OP_CALL",
+ "OP_PUSH",
+ "OP_POP",
+
+ "OP_CONST",
+
+ "OP_LOCAL",
+
+ "OP_JUMP",
+
+ //-------------------
+
+ "OP_EQ",
+ "OP_NE",
+
+ "OP_LTI",
+ "OP_LEI",
+ "OP_GTI",
+ "OP_GEI",
+
+ "OP_LTU",
+ "OP_LEU",
+ "OP_GTU",
+ "OP_GEU",
+
+ "OP_EQF",
+ "OP_NEF",
+
+ "OP_LTF",
+ "OP_LEF",
+ "OP_GTF",
+ "OP_GEF",
+
+ //-------------------
+
+ "OP_LOAD1",
+ "OP_LOAD2",
+ "OP_LOAD4",
+ "OP_STORE1",
+ "OP_STORE2",
+ "OP_STORE4",
+ "OP_ARG",
+
+ "OP_BLOCK_COPY",
+
+ //-------------------
+
+ "OP_SEX8",
+ "OP_SEX16",
+
+ "OP_NEGI",
+ "OP_ADD",
+ "OP_SUB",
+ "OP_DIVI",
+ "OP_DIVU",
+ "OP_MODI",
+ "OP_MODU",
+ "OP_MULI",
+ "OP_MULU",
+
+ "OP_BAND",
+ "OP_BOR",
+ "OP_BXOR",
+ "OP_BCOM",
+
+ "OP_LSH",
+ "OP_RSHI",
+ "OP_RSHU",
+
+ "OP_NEGF",
+ "OP_ADDF",
+ "OP_SUBF",
+ "OP_DIVF",
+ "OP_MULF",
+
+ "OP_CVIF",
+ "OP_CVFI"
+};
+#endif
+
+#if idppc
+ #if defined(__GNUC__)
+ static inline unsigned int loadWord(void *addr) {
+ unsigned int word;
+
+ asm("lwbrx %0,0,%1" : "=r" (word) : "r" (addr));
+ return word;
+ }
+ #else
+ #define loadWord(addr) __lwbrx(addr,0)
+ #endif
+#else
+ #define loadWord(addr) *((int *)addr)
+#endif
+
+char *VM_Indent( vm_t *vm ) {
+ static char *string = " ";
+ if ( vm->callLevel > 20 ) {
+ return string;
+ }
+ return string + 2 * ( 20 - vm->callLevel );
+}
+
+void VM_StackTrace( vm_t *vm, int programCounter, int programStack ) {
+ int count;
+
+ count = 0;
+ do {
+ Com_Printf( "%s\n", VM_ValueToSymbol( vm, programCounter ) );
+ programStack = *(int *)&vm->dataBase[programStack+4];
+ programCounter = *(int *)&vm->dataBase[programStack];
+ } while ( programCounter != -1 && ++count < 32 );
+
+}
+
+
+/*
+====================
+VM_PrepareInterpreter
+====================
+*/
+void VM_PrepareInterpreter( vm_t *vm, vmHeader_t *header ) {
+ int op;
+ int pc;
+ byte *code;
+ int instruction;
+ int *codeBase;
+
+ vm->codeBase = Hunk_Alloc( vm->codeLength*4, h_high ); // we're now int aligned
+// memcpy( vm->codeBase, (byte *)header + header->codeOffset, vm->codeLength );
+
+ // we don't need to translate the instructions, but we still need
+ // to find each instructions starting point for jumps
+ pc = 0;
+ instruction = 0;
+ code = (byte *)header + header->codeOffset;
+ codeBase = (int *)vm->codeBase;
+
+ while ( instruction < header->instructionCount ) {
+ vm->instructionPointers[ instruction ] = pc;
+ instruction++;
+
+ op = code[ pc ];
+ codeBase[pc] = op;
+ if ( pc > header->codeLength ) {
+ Com_Error( ERR_FATAL, "VM_PrepareInterpreter: pc > header->codeLength" );
+ }
+
+ pc++;
+
+ // these are the only opcodes that aren't a single byte
+ switch ( op ) {
+ case OP_ENTER:
+ case OP_CONST:
+ case OP_LOCAL:
+ case OP_LEAVE:
+ case OP_EQ:
+ case OP_NE:
+ case OP_LTI:
+ case OP_LEI:
+ case OP_GTI:
+ case OP_GEI:
+ case OP_LTU:
+ case OP_LEU:
+ case OP_GTU:
+ case OP_GEU:
+ case OP_EQF:
+ case OP_NEF:
+ case OP_LTF:
+ case OP_LEF:
+ case OP_GTF:
+ case OP_GEF:
+ case OP_BLOCK_COPY:
+ codeBase[pc+0] = loadWord(&code[pc]);
+ pc += 4;
+ break;
+ case OP_ARG:
+ codeBase[pc+0] = code[pc];
+ pc += 1;
+ break;
+ default:
+ break;
+ }
+
+ }
+ pc = 0;
+ instruction = 0;
+ code = (byte *)header + header->codeOffset;
+ codeBase = (int *)vm->codeBase;
+
+ while ( instruction < header->instructionCount ) {
+ op = code[ pc ];
+ instruction++;
+ pc++;
+ switch ( op ) {
+ case OP_ENTER:
+ case OP_CONST:
+ case OP_LOCAL:
+ case OP_LEAVE:
+ case OP_EQ:
+ case OP_NE:
+ case OP_LTI:
+ case OP_LEI:
+ case OP_GTI:
+ case OP_GEI:
+ case OP_LTU:
+ case OP_LEU:
+ case OP_GTU:
+ case OP_GEU:
+ case OP_EQF:
+ case OP_NEF:
+ case OP_LTF:
+ case OP_LEF:
+ case OP_GTF:
+ case OP_GEF:
+ case OP_BLOCK_COPY:
+ switch(op) {
+ case OP_EQ:
+ case OP_NE:
+ case OP_LTI:
+ case OP_LEI:
+ case OP_GTI:
+ case OP_GEI:
+ case OP_LTU:
+ case OP_LEU:
+ case OP_GTU:
+ case OP_GEU:
+ case OP_EQF:
+ case OP_NEF:
+ case OP_LTF:
+ case OP_LEF:
+ case OP_GTF:
+ case OP_GEF:
+ codeBase[pc] = vm->instructionPointers[codeBase[pc]];
+ break;
+ default:
+ break;
+ }
+ pc += 4;
+ break;
+ case OP_ARG:
+ pc += 1;
+ break;
+ default:
+ break;
+ }
+
+ }
+}
+
+/*
+==============
+VM_Call
+
+
+Upon a system call, the stack will look like:
+
+sp+32 parm1
+sp+28 parm0
+sp+24 return stack
+sp+20 return address
+sp+16 local1
+sp+14 local0
+sp+12 arg1
+sp+8 arg0
+sp+4 return stack
+sp return address
+
+An interpreted function will immediately execute
+an OP_ENTER instruction, which will subtract space for
+locals from sp
+==============
+*/
+#define MAX_STACK 256
+#define STACK_MASK (MAX_STACK-1)
+//#define DEBUG_VM
+
+#define DEBUGSTR va("%s%i", VM_Indent(vm), opStack-stack )
+
+int VM_CallInterpreted( vm_t *vm, int *args ) {
+ int stack[MAX_STACK];
+ int *opStack;
+ int programCounter;
+ int programStack;
+ int stackOnEntry;
+ byte *image;
+ int *codeImage;
+ int v1;
+ int dataMask;
+#ifdef DEBUG_VM
+ vmSymbol_t *profileSymbol;
+#endif
+
+ // interpret the code
+ vm->currentlyInterpreting = qtrue;
+
+ // we might be called recursively, so this might not be the very top
+ programStack = stackOnEntry = vm->programStack;
+
+#ifdef DEBUG_VM
+ profileSymbol = VM_ValueToFunctionSymbol( vm, 0 );
+ // uncomment this for debugging breakpoints
+ vm->breakFunction = 0;
+#endif
+ // set up the stack frame
+
+ image = vm->dataBase;
+ codeImage = (int *)vm->codeBase;
+ dataMask = vm->dataMask;
+
+ // leave a free spot at start of stack so
+ // that as long as opStack is valid, opStack-1 will
+ // not corrupt anything
+ opStack = stack;
+ programCounter = 0;
+
+ programStack -= 48;
+
+ *(int *)&image[ programStack + 44] = args[9];
+ *(int *)&image[ programStack + 40] = args[8];
+ *(int *)&image[ programStack + 36] = args[7];
+ *(int *)&image[ programStack + 32] = args[6];
+ *(int *)&image[ programStack + 28] = args[5];
+ *(int *)&image[ programStack + 24] = args[4];
+ *(int *)&image[ programStack + 20] = args[3];
+ *(int *)&image[ programStack + 16] = args[2];
+ *(int *)&image[ programStack + 12] = args[1];
+ *(int *)&image[ programStack + 8 ] = args[0];
+ *(int *)&image[ programStack + 4 ] = 0; // return stack
+ *(int *)&image[ programStack ] = -1; // will terminate the loop on return
+
+ vm->callLevel = 0;
+
+ VM_Debug(0);
+
+// vm_debugLevel=2;
+ // main interpreter loop, will exit when a LEAVE instruction
+ // grabs the -1 program counter
+
+#define r2 codeImage[programCounter]
+
+ while ( 1 ) {
+ int opcode, r0, r1;
+// unsigned int r2;
+
+nextInstruction:
+ r0 = ((int *)opStack)[0];
+ r1 = ((int *)opStack)[-1];
+nextInstruction2:
+ opcode = codeImage[ programCounter++ ];
+#ifdef DEBUG_VM
+ if ( (unsigned)programCounter > vm->codeLength ) {
+ Com_Error( ERR_DROP, "VM pc out of range" );
+ }
+
+ if ( opStack < stack ) {
+ Com_Error( ERR_DROP, "VM opStack underflow" );
+ }
+ if ( opStack >= stack+MAX_STACK ) {
+ Com_Error( ERR_DROP, "VM opStack overflow" );
+ }
+
+ if ( programStack <= vm->stackBottom ) {
+ Com_Error( ERR_DROP, "VM stack overflow" );
+ }
+
+ if ( programStack & 3 ) {
+ Com_Error( ERR_DROP, "VM program stack misaligned" );
+ }
+
+ if ( vm_debugLevel > 1 ) {
+ Com_Printf( "%s %s\n", DEBUGSTR, opnames[opcode] );
+ }
+ profileSymbol->profileCount++;
+#endif
+
+ switch ( opcode ) {
+#ifdef DEBUG_VM
+ default:
+ Com_Error( ERR_DROP, "Bad VM instruction" ); // this should be scanned on load!
+#endif
+ case OP_BREAK:
+ vm->breakCount++;
+ goto nextInstruction2;
+ case OP_CONST:
+ opStack++;
+ r1 = r0;
+ r0 = *opStack = r2;
+
+ programCounter += 4;
+ goto nextInstruction2;
+ case OP_LOCAL:
+ opStack++;
+ r1 = r0;
+ r0 = *opStack = r2+programStack;
+
+ programCounter += 4;
+ goto nextInstruction2;
+
+ case OP_LOAD4:
+#ifdef DEBUG_VM
+ if ( *opStack & 3 ) {
+ Com_Error( ERR_DROP, "OP_LOAD4 misaligned" );
+ }
+#endif
+ r0 = *opStack = *(int *)&image[ r0&dataMask ];
+ goto nextInstruction2;
+ case OP_LOAD2:
+ r0 = *opStack = *(unsigned short *)&image[ r0&dataMask ];
+ goto nextInstruction2;
+ case OP_LOAD1:
+ r0 = *opStack = image[ r0&dataMask ];
+ goto nextInstruction2;
+
+ case OP_STORE4:
+ *(int *)&image[ r1&(dataMask & ~3) ] = r0;
+ opStack -= 2;
+ goto nextInstruction;
+ case OP_STORE2:
+ *(short *)&image[ r1&(dataMask & ~1) ] = r0;
+ opStack -= 2;
+ goto nextInstruction;
+ case OP_STORE1:
+ image[ r1&dataMask ] = r0;
+ opStack -= 2;
+ goto nextInstruction;
+
+ case OP_ARG:
+ // single byte offset from programStack
+ *(int *)&image[ codeImage[programCounter] + programStack ] = r0;
+ opStack--;
+ programCounter += 1;
+ goto nextInstruction;
+
+ case OP_BLOCK_COPY:
+ {
+ int *src, *dest;
+ int i, count, srci, desti;
+
+ count = r2;
+ // MrE: copy range check
+ srci = r0 & dataMask;
+ desti = r1 & dataMask;
+ count = ((srci + count) & dataMask) - srci;
+ count = ((desti + count) & dataMask) - desti;
+
+ src = (int *)&image[ r0&dataMask ];
+ dest = (int *)&image[ r1&dataMask ];
+ if ( ( (int)src | (int)dest | count ) & 3 ) {
+ Com_Error( ERR_DROP, "OP_BLOCK_COPY not dword aligned" );
+ }
+ count >>= 2;
+ for ( i = count-1 ; i>= 0 ; i-- ) {
+ dest[i] = src[i];
+ }
+ programCounter += 4;
+ opStack -= 2;
+ }
+ goto nextInstruction;
+
+ case OP_CALL:
+ // save current program counter
+ *(int *)&image[ programStack ] = programCounter;
+
+ // jump to the location on the stack
+ programCounter = r0;
+ opStack--;
+ if ( programCounter < 0 ) {
+ // system call
+ int r;
+ int temp;
+#ifdef DEBUG_VM
+ int stomped;
+
+ if ( vm_debugLevel ) {
+ Com_Printf( "%s---> systemcall(%i)\n", DEBUGSTR, -1 - programCounter );
+ }
+#endif
+ // save the stack to allow recursive VM entry
+ temp = vm->callLevel;
+ vm->programStack = programStack - 4;
+#ifdef DEBUG_VM
+ stomped = *(int *)&image[ programStack + 4 ];
+#endif
+ *(int *)&image[ programStack + 4 ] = -1 - programCounter;
+
+//VM_LogSyscalls( (int *)&image[ programStack + 4 ] );
+ r = vm->systemCall( (int *)&image[ programStack + 4 ] );
+
+#ifdef DEBUG_VM
+ // this is just our stack frame pointer, only needed
+ // for debugging
+ *(int *)&image[ programStack + 4 ] = stomped;
+#endif
+
+ // save return value
+ opStack++;
+ *opStack = r;
+ programCounter = *(int *)&image[ programStack ];
+ vm->callLevel = temp;
+#ifdef DEBUG_VM
+ if ( vm_debugLevel ) {
+ Com_Printf( "%s<--- %s\n", DEBUGSTR, VM_ValueToSymbol( vm, programCounter ) );
+ }
+#endif
+ } else {
+ programCounter = vm->instructionPointers[ programCounter ];
+ }
+ goto nextInstruction;
+
+ // push and pop are only needed for discarded or bad function return values
+ case OP_PUSH:
+ opStack++;
+ goto nextInstruction;
+ case OP_POP:
+ opStack--;
+ goto nextInstruction;
+
+ case OP_ENTER:
+#ifdef DEBUG_VM
+ profileSymbol = VM_ValueToFunctionSymbol( vm, programCounter );
+#endif
+ // get size of stack frame
+ v1 = r2;
+
+ programCounter += 4;
+ programStack -= v1;
+#ifdef DEBUG_VM
+ // save old stack frame for debugging traces
+ *(int *)&image[programStack+4] = programStack + v1;
+ if ( vm_debugLevel ) {
+ Com_Printf( "%s---> %s\n", DEBUGSTR, VM_ValueToSymbol( vm, programCounter - 5 ) );
+ if ( vm->breakFunction && programCounter - 5 == vm->breakFunction ) {
+ // this is to allow setting breakpoints here in the debugger
+ vm->breakCount++;
+// vm_debugLevel = 2;
+// VM_StackTrace( vm, programCounter, programStack );
+ }
+ vm->callLevel++;
+ }
+#endif
+ goto nextInstruction;
+ case OP_LEAVE:
+ // remove our stack frame
+ v1 = r2;
+
+ programStack += v1;
+
+ // grab the saved program counter
+ programCounter = *(int *)&image[ programStack ];
+#ifdef DEBUG_VM
+ profileSymbol = VM_ValueToFunctionSymbol( vm, programCounter );
+ if ( vm_debugLevel ) {
+ vm->callLevel--;
+ Com_Printf( "%s<--- %s\n", DEBUGSTR, VM_ValueToSymbol( vm, programCounter ) );
+ }
+#endif
+ // check for leaving the VM
+ if ( programCounter == -1 ) {
+ goto done;
+ }
+ goto nextInstruction;
+
+ /*
+ ===================================================================
+ BRANCHES
+ ===================================================================
+ */
+
+ case OP_JUMP:
+ programCounter = r0;
+ programCounter = vm->instructionPointers[ programCounter ];
+ opStack--;
+ goto nextInstruction;
+
+ case OP_EQ:
+ opStack -= 2;
+ if ( r1 == r0 ) {
+ programCounter = r2; //vm->instructionPointers[r2];
+ goto nextInstruction;
+ } else {
+ programCounter += 4;
+ goto nextInstruction;
+ }
+
+ case OP_NE:
+ opStack -= 2;
+ if ( r1 != r0 ) {
+ programCounter = r2; //vm->instructionPointers[r2];
+ goto nextInstruction;
+ } else {
+ programCounter += 4;
+ goto nextInstruction;
+ }
+
+ case OP_LTI:
+ opStack -= 2;
+ if ( r1 < r0 ) {
+ programCounter = r2; //vm->instructionPointers[r2];
+ goto nextInstruction;
+ } else {
+ programCounter += 4;
+ goto nextInstruction;
+ }
+
+ case OP_LEI:
+ opStack -= 2;
+ if ( r1 <= r0 ) {
+ programCounter = r2; //vm->instructionPointers[r2];
+ goto nextInstruction;
+ } else {
+ programCounter += 4;
+ goto nextInstruction;
+ }
+
+ case OP_GTI:
+ opStack -= 2;
+ if ( r1 > r0 ) {
+ programCounter = r2; //vm->instructionPointers[r2];
+ goto nextInstruction;
+ } else {
+ programCounter += 4;
+ goto nextInstruction;
+ }
+
+ case OP_GEI:
+ opStack -= 2;
+ if ( r1 >= r0 ) {
+ programCounter = r2; //vm->instructionPointers[r2];
+ goto nextInstruction;
+ } else {
+ programCounter += 4;
+ goto nextInstruction;
+ }
+
+ case OP_LTU:
+ opStack -= 2;
+ if ( ((unsigned)r1) < ((unsigned)r0) ) {
+ programCounter = r2; //vm->instructionPointers[r2];
+ goto nextInstruction;
+ } else {
+ programCounter += 4;
+ goto nextInstruction;
+ }
+
+ case OP_LEU:
+ opStack -= 2;
+ if ( ((unsigned)r1) <= ((unsigned)r0) ) {
+ programCounter = r2; //vm->instructionPointers[r2];
+ goto nextInstruction;
+ } else {
+ programCounter += 4;
+ goto nextInstruction;
+ }
+
+ case OP_GTU:
+ opStack -= 2;
+ if ( ((unsigned)r1) > ((unsigned)r0) ) {
+ programCounter = r2; //vm->instructionPointers[r2];
+ goto nextInstruction;
+ } else {
+ programCounter += 4;
+ goto nextInstruction;
+ }
+
+ case OP_GEU:
+ opStack -= 2;
+ if ( ((unsigned)r1) >= ((unsigned)r0) ) {
+ programCounter = r2; //vm->instructionPointers[r2];
+ goto nextInstruction;
+ } else {
+ programCounter += 4;
+ goto nextInstruction;
+ }
+
+ case OP_EQF:
+ if ( ((float *)opStack)[-1] == *(float *)opStack ) {
+ programCounter = r2; //vm->instructionPointers[r2];
+ opStack -= 2;
+ goto nextInstruction;
+ } else {
+ programCounter += 4;
+ opStack -= 2;
+ goto nextInstruction;
+ }
+
+ case OP_NEF:
+ if ( ((float *)opStack)[-1] != *(float *)opStack ) {
+ programCounter = r2; //vm->instructionPointers[r2];
+ opStack -= 2;
+ goto nextInstruction;
+ } else {
+ programCounter += 4;
+ opStack -= 2;
+ goto nextInstruction;
+ }
+
+ case OP_LTF:
+ if ( ((float *)opStack)[-1] < *(float *)opStack ) {
+ programCounter = r2; //vm->instructionPointers[r2];
+ opStack -= 2;
+ goto nextInstruction;
+ } else {
+ programCounter += 4;
+ opStack -= 2;
+ goto nextInstruction;
+ }
+
+ case OP_LEF:
+ if ( ((float *)opStack)[-1] <= *(float *)opStack ) {
+ programCounter = r2; //vm->instructionPointers[r2];
+ opStack -= 2;
+ goto nextInstruction;
+ } else {
+ programCounter += 4;
+ opStack -= 2;
+ goto nextInstruction;
+ }
+
+ case OP_GTF:
+ if ( ((float *)opStack)[-1] > *(float *)opStack ) {
+ programCounter = r2; //vm->instructionPointers[r2];
+ opStack -= 2;
+ goto nextInstruction;
+ } else {
+ programCounter += 4;
+ opStack -= 2;
+ goto nextInstruction;
+ }
+
+ case OP_GEF:
+ if ( ((float *)opStack)[-1] >= *(float *)opStack ) {
+ programCounter = r2; //vm->instructionPointers[r2];
+ opStack -= 2;
+ goto nextInstruction;
+ } else {
+ programCounter += 4;
+ opStack -= 2;
+ goto nextInstruction;
+ }
+
+
+ //===================================================================
+
+ case OP_NEGI:
+ *opStack = -r0;
+ goto nextInstruction;
+ case OP_ADD:
+ opStack[-1] = r1 + r0;
+ opStack--;
+ goto nextInstruction;
+ case OP_SUB:
+ opStack[-1] = r1 - r0;
+ opStack--;
+ goto nextInstruction;
+ case OP_DIVI:
+ opStack[-1] = r1 / r0;
+ opStack--;
+ goto nextInstruction;
+ case OP_DIVU:
+ opStack[-1] = ((unsigned)r1) / ((unsigned)r0);
+ opStack--;
+ goto nextInstruction;
+ case OP_MODI:
+ opStack[-1] = r1 % r0;
+ opStack--;
+ goto nextInstruction;
+ case OP_MODU:
+ opStack[-1] = ((unsigned)r1) % (unsigned)r0;
+ opStack--;
+ goto nextInstruction;
+ case OP_MULI:
+ opStack[-1] = r1 * r0;
+ opStack--;
+ goto nextInstruction;
+ case OP_MULU:
+ opStack[-1] = ((unsigned)r1) * ((unsigned)r0);
+ opStack--;
+ goto nextInstruction;
+
+ case OP_BAND:
+ opStack[-1] = ((unsigned)r1) & ((unsigned)r0);
+ opStack--;
+ goto nextInstruction;
+ case OP_BOR:
+ opStack[-1] = ((unsigned)r1) | ((unsigned)r0);
+ opStack--;
+ goto nextInstruction;
+ case OP_BXOR:
+ opStack[-1] = ((unsigned)r1) ^ ((unsigned)r0);
+ opStack--;
+ goto nextInstruction;
+ case OP_BCOM:
+ opStack[-1] = ~ ((unsigned)r0);
+ goto nextInstruction;
+
+ case OP_LSH:
+ opStack[-1] = r1 << r0;
+ opStack--;
+ goto nextInstruction;
+ case OP_RSHI:
+ opStack[-1] = r1 >> r0;
+ opStack--;
+ goto nextInstruction;
+ case OP_RSHU:
+ opStack[-1] = ((unsigned)r1) >> r0;
+ opStack--;
+ goto nextInstruction;
+
+ case OP_NEGF:
+ *(float *)opStack = -*(float *)opStack;
+ goto nextInstruction;
+ case OP_ADDF:
+ *(float *)(opStack-1) = *(float *)(opStack-1) + *(float *)opStack;
+ opStack--;
+ goto nextInstruction;
+ case OP_SUBF:
+ *(float *)(opStack-1) = *(float *)(opStack-1) - *(float *)opStack;
+ opStack--;
+ goto nextInstruction;
+ case OP_DIVF:
+ *(float *)(opStack-1) = *(float *)(opStack-1) / *(float *)opStack;
+ opStack--;
+ goto nextInstruction;
+ case OP_MULF:
+ *(float *)(opStack-1) = *(float *)(opStack-1) * *(float *)opStack;
+ opStack--;
+ goto nextInstruction;
+
+ case OP_CVIF:
+ *(float *)opStack = (float)*opStack;
+ goto nextInstruction;
+ case OP_CVFI:
+ *opStack = (int) *(float *)opStack;
+ goto nextInstruction;
+ case OP_SEX8:
+ *opStack = (signed char)*opStack;
+ goto nextInstruction;
+ case OP_SEX16:
+ *opStack = (short)*opStack;
+ goto nextInstruction;
+ }
+ }
+
+done:
+ vm->currentlyInterpreting = qfalse;
+
+ if ( opStack != &stack[1] ) {
+ Com_Error( ERR_DROP, "Interpreter error: opStack = %i", opStack - stack );
+ }
+
+ vm->programStack = stackOnEntry;
+
+ // return the result
+ return *opStack;
+}
diff --git a/code/qcommon/vm_local.h b/code/qcommon/vm_local.h
new file mode 100755
index 0000000..c62bfc2
--- /dev/null
+++ b/code/qcommon/vm_local.h
@@ -0,0 +1,180 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "../game/q_shared.h"
+#include "qcommon.h"
+
+typedef enum {
+ OP_UNDEF,
+
+ OP_IGNORE,
+
+ OP_BREAK,
+
+ OP_ENTER,
+ OP_LEAVE,
+ OP_CALL,
+ OP_PUSH,
+ OP_POP,
+
+ OP_CONST,
+ OP_LOCAL,
+
+ OP_JUMP,
+
+ //-------------------
+
+ OP_EQ,
+ OP_NE,
+
+ OP_LTI,
+ OP_LEI,
+ OP_GTI,
+ OP_GEI,
+
+ OP_LTU,
+ OP_LEU,
+ OP_GTU,
+ OP_GEU,
+
+ OP_EQF,
+ OP_NEF,
+
+ OP_LTF,
+ OP_LEF,
+ OP_GTF,
+ OP_GEF,
+
+ //-------------------
+
+ OP_LOAD1,
+ OP_LOAD2,
+ OP_LOAD4,
+ OP_STORE1,
+ OP_STORE2,
+ OP_STORE4, // *(stack[top-1]) = stack[top]
+ OP_ARG,
+
+ OP_BLOCK_COPY,
+
+ //-------------------
+
+ OP_SEX8,
+ OP_SEX16,
+
+ OP_NEGI,
+ OP_ADD,
+ OP_SUB,
+ OP_DIVI,
+ OP_DIVU,
+ OP_MODI,
+ OP_MODU,
+ OP_MULI,
+ OP_MULU,
+
+ OP_BAND,
+ OP_BOR,
+ OP_BXOR,
+ OP_BCOM,
+
+ OP_LSH,
+ OP_RSHI,
+ OP_RSHU,
+
+ OP_NEGF,
+ OP_ADDF,
+ OP_SUBF,
+ OP_DIVF,
+ OP_MULF,
+
+ OP_CVIF,
+ OP_CVFI
+} opcode_t;
+
+
+
+typedef int vmptr_t;
+
+typedef struct vmSymbol_s {
+ struct vmSymbol_s *next;
+ int symValue;
+ int profileCount;
+ char symName[1]; // variable sized
+} vmSymbol_t;
+
+#define VM_OFFSET_PROGRAM_STACK 0
+#define VM_OFFSET_SYSTEM_CALL 4
+
+struct vm_s {
+ // DO NOT MOVE OR CHANGE THESE WITHOUT CHANGING THE VM_OFFSET_* DEFINES
+ // USED BY THE ASM CODE
+ int programStack; // the vm may be recursively entered
+ int (*systemCall)( int *parms );
+
+ //------------------------------------
+
+ char name[MAX_QPATH];
+
+ // for dynamic linked modules
+ void *dllHandle;
+ int (QDECL *entryPoint)( int callNum, ... );
+
+ // for interpreted modules
+ qboolean currentlyInterpreting;
+
+ qboolean compiled;
+ byte *codeBase;
+ int codeLength;
+
+ int *instructionPointers;
+ int instructionPointersLength;
+
+ byte *dataBase;
+ int dataMask;
+
+ int stackBottom; // if programStack < stackBottom, error
+
+ int numSymbols;
+ struct vmSymbol_s *symbols;
+
+ int callLevel; // for debug indenting
+ int breakFunction; // increment breakCount on function entry to this
+ int breakCount;
+
+// fqpath member added 7/20/02 by T.Ray
+ char fqpath[MAX_QPATH+1] ;
+};
+
+
+extern vm_t *currentVM;
+extern int vm_debugLevel;
+
+void VM_Compile( vm_t *vm, vmHeader_t *header );
+int VM_CallCompiled( vm_t *vm, int *args );
+
+void VM_PrepareInterpreter( vm_t *vm, vmHeader_t *header );
+int VM_CallInterpreted( vm_t *vm, int *args );
+
+vmSymbol_t *VM_ValueToFunctionSymbol( vm_t *vm, int value );
+int VM_SymbolToValue( vm_t *vm, const char *symbol );
+const char *VM_ValueToSymbol( vm_t *vm, int value );
+void VM_LogSyscalls( int *args );
+
diff --git a/code/qcommon/vm_ppc.c b/code/qcommon/vm_ppc.c
new file mode 100755
index 0000000..bea8257
--- /dev/null
+++ b/code/qcommon/vm_ppc.c
@@ -0,0 +1,1479 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// vm_ppc.c
+// ppc dynamic compiler
+
+#include "vm_local.h"
+
+#pragma opt_pointer_analysis off
+
+
+typedef enum {
+ R_REAL_STACK = 1,
+ // registers 3-11 are the parameter passing registers
+
+ // state
+ R_STACK = 3, // local
+ R_OPSTACK, // global
+
+ // constants
+ R_MEMBASE, // global
+ R_MEMMASK,
+ R_ASMCALL, // global
+ R_INSTRUCTIONS, // global
+ R_NUM_INSTRUCTIONS, // global
+ R_CVM, // currentVM
+
+ // temps
+ R_TOP = 11,
+ R_SECOND = 12,
+ R_EA = 2 // effective address calculation
+
+} regNums_t;
+
+#define RG_REAL_STACK r1
+#define RG_STACK r3
+#define RG_OPSTACK r4
+#define RG_MEMBASE r5
+#define RG_MEMMASK r6
+#define RG_ASMCALL r7
+#define RG_INSTRUCTIONS r8
+#define RG_NUM_INSTRUCTIONS r9
+#define RG_CVM r10
+#define RG_TOP r12
+#define RG_SECOND r13
+#define RG_EA r14
+
+// this doesn't have the low order bits set for instructions i'm not using...
+typedef enum {
+ PPC_TDI = 0x08000000,
+ PPC_TWI = 0x0c000000,
+ PPC_MULLI = 0x1c000000,
+ PPC_SUBFIC = 0x20000000,
+ PPC_CMPI = 0x28000000,
+ PPC_CMPLI = 0x2c000000,
+ PPC_ADDIC = 0x30000000,
+ PPC_ADDIC_ = 0x34000000,
+ PPC_ADDI = 0x38000000,
+ PPC_ADDIS = 0x3c000000,
+ PPC_BC = 0x40000000,
+ PPC_SC = 0x44000000,
+ PPC_B = 0x48000000,
+
+ PPC_MCRF = 0x4c000000,
+ PPC_BCLR = 0x4c000020,
+ PPC_RFID = 0x4c000000,
+ PPC_CRNOR = 0x4c000000,
+ PPC_RFI = 0x4c000000,
+ PPC_CRANDC = 0x4c000000,
+ PPC_ISYNC = 0x4c000000,
+ PPC_CRXOR = 0x4c000000,
+ PPC_CRNAND = 0x4c000000,
+ PPC_CREQV = 0x4c000000,
+ PPC_CRORC = 0x4c000000,
+ PPC_CROR = 0x4c000000,
+//------------
+ PPC_BCCTR = 0x4c000420,
+ PPC_RLWIMI = 0x50000000,
+ PPC_RLWINM = 0x54000000,
+ PPC_RLWNM = 0x5c000000,
+ PPC_ORI = 0x60000000,
+ PPC_ORIS = 0x64000000,
+ PPC_XORI = 0x68000000,
+ PPC_XORIS = 0x6c000000,
+ PPC_ANDI_ = 0x70000000,
+ PPC_ANDIS_ = 0x74000000,
+ PPC_RLDICL = 0x78000000,
+ PPC_RLDICR = 0x78000000,
+ PPC_RLDIC = 0x78000000,
+ PPC_RLDIMI = 0x78000000,
+ PPC_RLDCL = 0x78000000,
+ PPC_RLDCR = 0x78000000,
+ PPC_CMP = 0x7c000000,
+ PPC_TW = 0x7c000000,
+ PPC_SUBFC = 0x7c000010,
+ PPC_MULHDU = 0x7c000000,
+ PPC_ADDC = 0x7c000014,
+ PPC_MULHWU = 0x7c000000,
+ PPC_MFCR = 0x7c000000,
+ PPC_LWAR = 0x7c000000,
+ PPC_LDX = 0x7c000000,
+ PPC_LWZX = 0x7c00002e,
+ PPC_SLW = 0x7c000030,
+ PPC_CNTLZW = 0x7c000000,
+ PPC_SLD = 0x7c000000,
+ PPC_AND = 0x7c000038,
+ PPC_CMPL = 0x7c000040,
+ PPC_SUBF = 0x7c000050,
+ PPC_LDUX = 0x7c000000,
+//------------
+ PPC_DCBST = 0x7c000000,
+ PPC_LWZUX = 0x7c00006c,
+ PPC_CNTLZD = 0x7c000000,
+ PPC_ANDC = 0x7c000000,
+ PPC_TD = 0x7c000000,
+ PPC_MULHD = 0x7c000000,
+ PPC_MULHW = 0x7c000000,
+ PPC_MTSRD = 0x7c000000,
+ PPC_MFMSR = 0x7c000000,
+ PPC_LDARX = 0x7c000000,
+ PPC_DCBF = 0x7c000000,
+ PPC_LBZX = 0x7c0000ae,
+ PPC_NEG = 0x7c000000,
+ PPC_MTSRDIN = 0x7c000000,
+ PPC_LBZUX = 0x7c000000,
+ PPC_NOR = 0x7c0000f8,
+ PPC_SUBFE = 0x7c000000,
+ PPC_ADDE = 0x7c000000,
+ PPC_MTCRF = 0x7c000000,
+ PPC_MTMSR = 0x7c000000,
+ PPC_STDX = 0x7c000000,
+ PPC_STWCX_ = 0x7c000000,
+ PPC_STWX = 0x7c00012e,
+ PPC_MTMSRD = 0x7c000000,
+ PPC_STDUX = 0x7c000000,
+ PPC_STWUX = 0x7c00016e,
+ PPC_SUBFZE = 0x7c000000,
+ PPC_ADDZE = 0x7c000000,
+ PPC_MTSR = 0x7c000000,
+ PPC_STDCX_ = 0x7c000000,
+ PPC_STBX = 0x7c0001ae,
+ PPC_SUBFME = 0x7c000000,
+ PPC_MULLD = 0x7c000000,
+//------------
+ PPC_ADDME = 0x7c000000,
+ PPC_MULLW = 0x7c0001d6,
+ PPC_MTSRIN = 0x7c000000,
+ PPC_DCBTST = 0x7c000000,
+ PPC_STBUX = 0x7c000000,
+ PPC_ADD = 0x7c000214,
+ PPC_DCBT = 0x7c000000,
+ PPC_LHZX = 0x7c00022e,
+ PPC_EQV = 0x7c000000,
+ PPC_TLBIE = 0x7c000000,
+ PPC_ECIWX = 0x7c000000,
+ PPC_LHZUX = 0x7c000000,
+ PPC_XOR = 0x7c000278,
+ PPC_MFSPR = 0x7c0002a6,
+ PPC_LWAX = 0x7c000000,
+ PPC_LHAX = 0x7c000000,
+ PPC_TLBIA = 0x7c000000,
+ PPC_MFTB = 0x7c000000,
+ PPC_LWAUX = 0x7c000000,
+ PPC_LHAUX = 0x7c000000,
+ PPC_STHX = 0x7c00032e,
+ PPC_ORC = 0x7c000338,
+ PPC_SRADI = 0x7c000000,
+ PPC_SLBIE = 0x7c000000,
+ PPC_ECOWX = 0x7c000000,
+ PPC_STHUX = 0x7c000000,
+ PPC_OR = 0x7c000378,
+ PPC_DIVDU = 0x7c000000,
+ PPC_DIVWU = 0x7c000396,
+ PPC_MTSPR = 0x7c0003a6,
+ PPC_DCBI = 0x7c000000,
+ PPC_NAND = 0x7c000000,
+ PPC_DIVD = 0x7c000000,
+//------------
+ PPC_DIVW = 0x7c0003d6,
+ PPC_SLBIA = 0x7c000000,
+ PPC_MCRXR = 0x7c000000,
+ PPC_LSWX = 0x7c000000,
+ PPC_LWBRX = 0x7c000000,
+ PPC_LFSX = 0x7c000000,
+ PPC_SRW = 0x7c000430,
+ PPC_SRD = 0x7c000000,
+ PPC_TLBSYNC = 0x7c000000,
+ PPC_LFSUX = 0x7c000000,
+ PPC_MFSR = 0x7c000000,
+ PPC_LSWI = 0x7c000000,
+ PPC_SYNC = 0x7c000000,
+ PPC_LFDX = 0x7c000000,
+ PPC_LFDUX = 0x7c000000,
+ PPC_MFSRIN = 0x7c000000,
+ PPC_STSWX = 0x7c000000,
+ PPC_STWBRX = 0x7c000000,
+ PPC_STFSX = 0x7c000000,
+ PPC_STFSUX = 0x7c000000,
+ PPC_STSWI = 0x7c000000,
+ PPC_STFDX = 0x7c000000,
+ PPC_DCBA = 0x7c000000,
+ PPC_STFDUX = 0x7c000000,
+ PPC_LHBRX = 0x7c000000,
+ PPC_SRAW = 0x7c000630,
+ PPC_SRAD = 0x7c000000,
+ PPC_SRAWI = 0x7c000000,
+ PPC_EIEIO = 0x7c000000,
+ PPC_STHBRX = 0x7c000000,
+ PPC_EXTSH = 0x7c000734,
+ PPC_EXTSB = 0x7c000774,
+ PPC_ICBI = 0x7c000000,
+//------------
+ PPC_STFIWX = 0x7c0007ae,
+ PPC_EXTSW = 0x7c000000,
+ PPC_DCBZ = 0x7c000000,
+ PPC_LWZ = 0x80000000,
+ PPC_LWZU = 0x84000000,
+ PPC_LBZ = 0x88000000,
+ PPC_LBZU = 0x8c000000,
+ PPC_STW = 0x90000000,
+ PPC_STWU = 0x94000000,
+ PPC_STB = 0x98000000,
+ PPC_STBU = 0x9c000000,
+ PPC_LHZ = 0xa0000000,
+ PPC_LHZU = 0xa4000000,
+ PPC_LHA = 0xa8000000,
+ PPC_LHAU = 0xac000000,
+ PPC_STH = 0xb0000000,
+ PPC_STHU = 0xb4000000,
+ PPC_LMW = 0xb8000000,
+ PPC_STMW = 0xbc000000,
+ PPC_LFS = 0xc0000000,
+ PPC_LFSU = 0xc4000000,
+ PPC_LFD = 0xc8000000,
+ PPC_LFDU = 0xcc000000,
+ PPC_STFS = 0xd0000000,
+ PPC_STFSU = 0xd4000000,
+ PPC_STFD = 0xd8000000,
+ PPC_STFDU = 0xdc000000,
+ PPC_LD = 0xe8000000,
+ PPC_LDU = 0xe8000001,
+ PPC_LWA = 0xe8000002,
+ PPC_FDIVS = 0xec000024,
+ PPC_FSUBS = 0xec000028,
+ PPC_FADDS = 0xec00002a,
+//------------
+ PPC_FSQRTS = 0xec000000,
+ PPC_FRES = 0xec000000,
+ PPC_FMULS = 0xec000032,
+ PPC_FMSUBS = 0xec000000,
+ PPC_FMADDS = 0xec000000,
+ PPC_FNMSUBS = 0xec000000,
+ PPC_FNMADDS = 0xec000000,
+ PPC_STD = 0xf8000000,
+ PPC_STDU = 0xf8000001,
+ PPC_FCMPU = 0xfc000000,
+ PPC_FRSP = 0xfc000018,
+ PPC_FCTIW = 0xfc000000,
+ PPC_FCTIWZ = 0xfc00001e,
+ PPC_FDIV = 0xfc000000,
+ PPC_FSUB = 0xfc000028,
+ PPC_FADD = 0xfc000000,
+ PPC_FSQRT = 0xfc000000,
+ PPC_FSEL = 0xfc000000,
+ PPC_FMUL = 0xfc000000,
+ PPC_FRSQRTE = 0xfc000000,
+ PPC_FMSUB = 0xfc000000,
+ PPC_FMADD = 0xfc000000,
+ PPC_FNMSUB = 0xfc000000,
+ PPC_FNMADD = 0xfc000000,
+ PPC_FCMPO = 0xfc000000,
+ PPC_MTFSB1 = 0xfc000000,
+ PPC_FNEG = 0xfc000050,
+ PPC_MCRFS = 0xfc000000,
+ PPC_MTFSB0 = 0xfc000000,
+ PPC_FMR = 0xfc000000,
+ PPC_MTFSFI = 0xfc000000,
+ PPC_FNABS = 0xfc000000,
+ PPC_FABS = 0xfc000000,
+//------------
+ PPC_MFFS = 0xfc000000,
+ PPC_MTFSF = 0xfc000000,
+ PPC_FCTID = 0xfc000000,
+ PPC_FCTIDZ = 0xfc000000,
+ PPC_FCFID = 0xfc000000
+
+} ppcOpcodes_t;
+
+
+// the newly generated code
+static unsigned *buf;
+static int compiledOfs; // in dwords
+
+// fromt the original bytecode
+static byte *code;
+static int pc;
+
+void AsmCall( void );
+
+double itofConvert[2];
+
+static int Constant4( void ) {
+ int v;
+
+ v = code[pc] | (code[pc+1]<<8) | (code[pc+2]<<16) | (code[pc+3]<<24);
+ pc += 4;
+ return v;
+}
+
+static int Constant1( void ) {
+ int v;
+
+ v = code[pc];
+ pc += 1;
+ return v;
+}
+
+static void Emit4( int i ) {
+ buf[ compiledOfs ] = i;
+ compiledOfs++;
+}
+
+static void Inst( int opcode, int destReg, int aReg, int bReg ) {
+ unsigned r;
+
+ r = opcode | ( destReg << 21 ) | ( aReg << 16 ) | ( bReg << 11 ) ;
+ buf[ compiledOfs ] = r;
+ compiledOfs++;
+}
+
+static void Inst4( int opcode, int destReg, int aReg, int bReg, int cReg ) {
+ unsigned r;
+
+ r = opcode | ( destReg << 21 ) | ( aReg << 16 ) | ( bReg << 11 ) | ( cReg << 6 );
+ buf[ compiledOfs ] = r;
+ compiledOfs++;
+}
+
+static void InstImm( int opcode, int destReg, int aReg, int immediate ) {
+ unsigned r;
+
+ if ( immediate > 32767 || immediate < -32768 ) {
+ Com_Error( ERR_FATAL, "VM_Compile: immediate value %i out of range, opcode %x,%d,%d", immediate, opcode, destReg, aReg );
+ }
+ r = opcode | ( destReg << 21 ) | ( aReg << 16 ) | ( immediate & 0xffff );
+ buf[ compiledOfs ] = r;
+ compiledOfs++;
+}
+
+static void InstImmU( int opcode, int destReg, int aReg, int immediate ) {
+ unsigned r;
+
+ if ( immediate > 0xffff || immediate < 0 ) {
+ Com_Error( ERR_FATAL, "VM_Compile: immediate value %i out of range", immediate );
+ }
+ r = opcode | ( destReg << 21 ) | ( aReg << 16 ) | ( immediate & 0xffff );
+ buf[ compiledOfs ] = r;
+ compiledOfs++;
+}
+
+static qboolean rtopped;
+static int pop0, pop1, oc0, oc1;
+static vm_t *tvm;
+static int instruction;
+static byte *jused;
+static int pass;
+
+static void ltop() {
+ if (rtopped == qfalse) {
+ InstImm( PPC_LWZ, R_TOP, R_OPSTACK, 0 ); // get value from opstack
+ }
+}
+
+static void ltopandsecond() {
+ if (pass>=0 && buf[compiledOfs-1] == (PPC_STWU | R_TOP<<21 | R_OPSTACK<<16 | 4 ) && jused[instruction]==0 ) {
+ compiledOfs--;
+ if (!pass) {
+ tvm->instructionPointers[instruction] = compiledOfs * 4;
+ }
+ InstImm( PPC_LWZ, R_SECOND, R_OPSTACK, 0 ); // get value from opstack
+ InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -4 );
+ } else if (pass>=0 && buf[compiledOfs-1] == (PPC_STW | R_TOP<<21 | R_OPSTACK<<16 | 0 ) && jused[instruction]==0 ) {
+ compiledOfs--;
+ if (!pass) {
+ tvm->instructionPointers[instruction] = compiledOfs * 4;
+ }
+ InstImm( PPC_LWZ, R_SECOND, R_OPSTACK, -4 ); // get value from opstack
+ InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -8 );
+ } else {
+ ltop(); // get value from opstack
+ InstImm( PPC_LWZ, R_SECOND, R_OPSTACK, -4 ); // get value from opstack
+ InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -8 );
+ }
+ rtopped = qfalse;
+}
+
+// TJW: Unused
+#if 0
+static void fltop() {
+ if (rtopped == qfalse) {
+ InstImm( PPC_LFS, R_TOP, R_OPSTACK, 0 ); // get value from opstack
+ }
+}
+#endif
+
+static void fltopandsecond() {
+ InstImm( PPC_LFS, R_TOP, R_OPSTACK, 0 ); // get value from opstack
+ InstImm( PPC_LFS, R_SECOND, R_OPSTACK, -4 ); // get value from opstack
+ InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -8 );
+ rtopped = qfalse;
+ return;
+}
+
+/*
+=================
+VM_Compile
+=================
+*/
+void VM_Compile( vm_t *vm, vmHeader_t *header ) {
+ int op;
+ int maxLength;
+ int v;
+ int i;
+
+ // set up the into-to-float variables
+ ((int *)itofConvert)[0] = 0x43300000;
+ ((int *)itofConvert)[1] = 0x80000000;
+ ((int *)itofConvert)[2] = 0x43300000;
+
+ // allocate a very large temp buffer, we will shrink it later
+ maxLength = header->codeLength * 8;
+ buf = Z_Malloc( maxLength );
+ jused = Z_Malloc(header->instructionCount + 2);
+ Com_Memset(jused, 0, header->instructionCount+2);
+
+ // compile everything twice, so the second pass will have valid instruction
+ // pointers for branches
+ for ( pass = -1 ; pass < 2 ; pass++ ) {
+
+ rtopped = qfalse;
+ // translate all instructions
+ pc = 0;
+
+ pop0 = 343545;
+ pop1 = 2443545;
+ oc0 = -2343535;
+ oc1 = 24353454;
+ tvm = vm;
+ code = (byte *)header + header->codeOffset;
+ compiledOfs = 0;
+#ifndef __GNUC__
+ // metrowerks seems to require this header in front of functions
+ Emit4( (int)(buf+2) );
+ Emit4( 0 );
+#endif
+
+ for ( instruction = 0 ; instruction < header->instructionCount ; instruction++ ) {
+ if ( compiledOfs*4 > maxLength - 16 ) {
+ Com_Error( ERR_DROP, "VM_Compile: maxLength exceeded" );
+ }
+
+ op = code[ pc ];
+ if ( !pass ) {
+ vm->instructionPointers[ instruction ] = compiledOfs * 4;
+ }
+ pc++;
+ switch ( op ) {
+ case 0:
+ break;
+ case OP_BREAK:
+ InstImmU( PPC_ADDI, R_TOP, 0, 0 );
+ InstImm( PPC_LWZ, R_TOP, R_TOP, 0 ); // *(int *)0 to crash to debugger
+ rtopped = qfalse;
+ break;
+ case OP_ENTER:
+ InstImm( PPC_ADDI, R_STACK, R_STACK, -Constant4() ); // sub R_STACK, R_STACK, imm
+ rtopped = qfalse;
+ break;
+ case OP_CONST:
+ v = Constant4();
+ if (code[pc] == OP_LOAD4 || code[pc] == OP_LOAD2 || code[pc] == OP_LOAD1) {
+ v &= vm->dataMask;
+ }
+ if ( v < 32768 && v >= -32768 ) {
+ InstImmU( PPC_ADDI, R_TOP, 0, v & 0xffff );
+ } else {
+ InstImmU( PPC_ADDIS, R_TOP, 0, (v >> 16)&0xffff );
+ if ( v & 0xffff ) {
+ InstImmU( PPC_ORI, R_TOP, R_TOP, v & 0xffff );
+ }
+ }
+ if (code[pc] == OP_LOAD4) {
+ Inst( PPC_LWZX, R_TOP, R_TOP, R_MEMBASE ); // load from memory base
+ pc++;
+ instruction++;
+ } else if (code[pc] == OP_LOAD2) {
+ Inst( PPC_LHZX, R_TOP, R_TOP, R_MEMBASE ); // load from memory base
+ pc++;
+ instruction++;
+ } else if (code[pc] == OP_LOAD1) {
+ Inst( PPC_LBZX, R_TOP, R_TOP, R_MEMBASE ); // load from memory base
+ pc++;
+ instruction++;
+ }
+ if (code[pc] == OP_STORE4) {
+ InstImm( PPC_LWZ, R_SECOND, R_OPSTACK, 0 ); // get value from opstack
+ InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -4 );
+ //Inst( PPC_AND, R_MEMMASK, R_SECOND, R_SECOND ); // mask it
+ Inst( PPC_STWX, R_TOP, R_SECOND, R_MEMBASE ); // store from memory base
+ pc++;
+ instruction++;
+ rtopped = qfalse;
+ break;
+ } else if (code[pc] == OP_STORE2) {
+ InstImm( PPC_LWZ, R_SECOND, R_OPSTACK, 0 ); // get value from opstack
+ InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -4 );
+ //Inst( PPC_AND, R_MEMMASK, R_SECOND, R_SECOND ); // mask it
+ Inst( PPC_STHX, R_TOP, R_SECOND, R_MEMBASE ); // store from memory base
+ pc++;
+ instruction++;
+ rtopped = qfalse;
+ break;
+ } else if (code[pc] == OP_STORE1) {
+ InstImm( PPC_LWZ, R_SECOND, R_OPSTACK, 0 ); // get value from opstack
+ InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -4 );
+ //Inst( PPC_AND, R_MEMMASK, R_SECOND, R_SECOND ); // mask it
+ Inst( PPC_STBX, R_TOP, R_SECOND, R_MEMBASE ); // store from memory base
+ pc++;
+ instruction++;
+ rtopped = qfalse;
+ break;
+ }
+ if (code[pc] == OP_JUMP) {
+ jused[v] = 1;
+ }
+ InstImm( PPC_STWU, R_TOP, R_OPSTACK, 4 );
+ rtopped = qtrue;
+ break;
+ case OP_LOCAL:
+ oc0 = oc1;
+ oc1 = Constant4();
+ if (code[pc] == OP_LOAD4 || code[pc] == OP_LOAD2 || code[pc] == OP_LOAD1) {
+ oc1 &= vm->dataMask;
+ }
+ InstImm( PPC_ADDI, R_TOP, R_STACK, oc1 );
+ if (code[pc] == OP_LOAD4) {
+ Inst( PPC_LWZX, R_TOP, R_TOP, R_MEMBASE ); // load from memory base
+ pc++;
+ instruction++;
+ } else if (code[pc] == OP_LOAD2) {
+ Inst( PPC_LHZX, R_TOP, R_TOP, R_MEMBASE ); // load from memory base
+ pc++;
+ instruction++;
+ } else if (code[pc] == OP_LOAD1) {
+ Inst( PPC_LBZX, R_TOP, R_TOP, R_MEMBASE ); // load from memory base
+ pc++;
+ instruction++;
+ }
+ if (code[pc] == OP_STORE4) {
+ InstImm( PPC_LWZ, R_SECOND, R_OPSTACK, 0 ); // get value from opstack
+ InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -4 );
+ //Inst( PPC_AND, R_MEMMASK, R_SECOND, R_SECOND ); // mask it
+ Inst( PPC_STWX, R_TOP, R_SECOND, R_MEMBASE ); // store from memory base
+ pc++;
+ instruction++;
+ rtopped = qfalse;
+ break;
+ } else if (code[pc] == OP_STORE2) {
+ InstImm( PPC_LWZ, R_SECOND, R_OPSTACK, 0 ); // get value from opstack
+ InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -4 );
+ //Inst( PPC_AND, R_MEMMASK, R_SECOND, R_SECOND ); // mask it
+ Inst( PPC_STHX, R_TOP, R_SECOND, R_MEMBASE ); // store from memory base
+ pc++;
+ instruction++;
+ rtopped = qfalse;
+ break;
+ } else if (code[pc] == OP_STORE1) {
+ InstImm( PPC_LWZ, R_SECOND, R_OPSTACK, 0 ); // get value from opstack
+ InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -4 );
+ //Inst( PPC_AND, R_MEMMASK, R_SECOND, R_SECOND ); // mask it
+ Inst( PPC_STBX, R_TOP, R_SECOND, R_MEMBASE ); // store from memory base
+ pc++;
+ instruction++;
+ rtopped = qfalse;
+ break;
+ }
+ InstImm( PPC_STWU, R_TOP, R_OPSTACK, 4 );
+ rtopped = qtrue;
+ break;
+ case OP_ARG:
+ ltop(); // get value from opstack
+ InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -4 );
+ InstImm( PPC_ADDI, R_EA, R_STACK, Constant1() ); // location to put it
+ Inst( PPC_STWX, R_TOP, R_EA, R_MEMBASE );
+ rtopped = qfalse;
+ break;
+ case OP_CALL:
+ Inst( PPC_MFSPR, R_SECOND, 8, 0 ); // move from link register
+ InstImm( PPC_STWU, R_SECOND, R_REAL_STACK, -16 ); // save off the old return address
+
+ Inst( PPC_MTSPR, R_ASMCALL, 9, 0 ); // move to count register
+ Inst( PPC_BCCTR | 1, 20, 0, 0 ); // jump and link to the count register
+
+ InstImm( PPC_LWZ, R_SECOND, R_REAL_STACK, 0 ); // fetch the old return address
+ InstImm( PPC_ADDI, R_REAL_STACK, R_REAL_STACK, 16 );
+ Inst( PPC_MTSPR, R_SECOND, 8, 0 ); // move to link register
+ rtopped = qfalse;
+ break;
+ case OP_PUSH:
+ InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, 4 );
+ rtopped = qfalse;
+ break;
+ case OP_POP:
+ InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -4 );
+ rtopped = qfalse;
+ break;
+ case OP_LEAVE:
+ InstImm( PPC_ADDI, R_STACK, R_STACK, Constant4() ); // add R_STACK, R_STACK, imm
+ Inst( PPC_BCLR, 20, 0, 0 ); // branch unconditionally to link register
+ rtopped = qfalse;
+ break;
+ case OP_LOAD4:
+ ltop(); // get value from opstack
+ //Inst( PPC_AND, R_MEMMASK, R_TOP, R_TOP ); // mask it
+ Inst( PPC_LWZX, R_TOP, R_TOP, R_MEMBASE ); // load from memory base
+ InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 );
+ rtopped = qtrue;
+ break;
+ case OP_LOAD2:
+ ltop(); // get value from opstack
+ //Inst( PPC_AND, R_MEMMASK, R_TOP, R_TOP ); // mask it
+ Inst( PPC_LHZX, R_TOP, R_TOP, R_MEMBASE ); // load from memory base
+ InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 );
+ rtopped = qtrue;
+ break;
+ case OP_LOAD1:
+ ltop(); // get value from opstack
+ //Inst( PPC_AND, R_MEMMASK, R_TOP, R_TOP ); // mask it
+ Inst( PPC_LBZX, R_TOP, R_TOP, R_MEMBASE ); // load from memory base
+ InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 );
+ rtopped = qtrue;
+ break;
+ case OP_STORE4:
+ ltopandsecond(); // get value from opstack
+ //Inst( PPC_AND, R_MEMMASK, R_SECOND, R_SECOND ); // mask it
+ Inst( PPC_STWX, R_TOP, R_SECOND, R_MEMBASE ); // store from memory base
+ rtopped = qfalse;
+ break;
+ case OP_STORE2:
+ ltopandsecond(); // get value from opstack
+ //Inst( PPC_AND, R_MEMMASK, R_SECOND, R_SECOND ); // mask it
+ Inst( PPC_STHX, R_TOP, R_SECOND, R_MEMBASE ); // store from memory base
+ rtopped = qfalse;
+ break;
+ case OP_STORE1:
+ ltopandsecond(); // get value from opstack
+ //Inst( PPC_AND, R_MEMMASK, R_SECOND, R_SECOND ); // mask it
+ Inst( PPC_STBX, R_TOP, R_SECOND, R_MEMBASE ); // store from memory base
+ rtopped = qfalse;
+ break;
+
+ case OP_EQ:
+ ltopandsecond(); // get value from opstack
+ Inst( PPC_CMP, 0, R_SECOND, R_TOP );
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( PPC_BC, 4, 2, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4(PPC_B | (v&0x3ffffff) );
+ rtopped = qfalse;
+ break;
+ case OP_NE:
+ ltopandsecond(); // get value from opstack
+ Inst( PPC_CMP, 0, R_SECOND, R_TOP );
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( PPC_BC, 12, 2, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4(PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( PPC_BC, 4, 2, v );
+
+ rtopped = qfalse;
+ break;
+ case OP_LTI:
+ ltopandsecond(); // get value from opstack
+ Inst( PPC_CMP, 0, R_SECOND, R_TOP );
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( PPC_BC, 4, 0, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4(PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( PPC_BC, 12, 0, v );
+ rtopped = qfalse;
+ break;
+ case OP_LEI:
+ ltopandsecond(); // get value from opstack
+ Inst( PPC_CMP, 0, R_SECOND, R_TOP );
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( PPC_BC, 12, 1, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4(PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( PPC_BC, 4, 1, v );
+ rtopped = qfalse;
+ break;
+ case OP_GTI:
+ ltopandsecond(); // get value from opstack
+ Inst( PPC_CMP, 0, R_SECOND, R_TOP );
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( PPC_BC, 4, 1, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4(PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( PPC_BC, 12, 1, v );
+ rtopped = qfalse;
+ break;
+ case OP_GEI:
+ ltopandsecond(); // get value from opstack
+ Inst( PPC_CMP, 0, R_SECOND, R_TOP );
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( PPC_BC, 12, 0, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4(PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( PPC_BC, 4, 0, v );
+ rtopped = qfalse;
+ break;
+ case OP_LTU:
+ ltopandsecond(); // get value from opstack
+ Inst( PPC_CMPL, 0, R_SECOND, R_TOP );
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( PPC_BC, 4, 0, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4(PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( PPC_BC, 12, 0, v );
+ rtopped = qfalse;
+ break;
+ case OP_LEU:
+ ltopandsecond(); // get value from opstack
+ Inst( PPC_CMPL, 0, R_SECOND, R_TOP );
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( PPC_BC, 12, 1, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4(PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( PPC_BC, 4, 1, v );
+ rtopped = qfalse;
+ break;
+ case OP_GTU:
+ ltopandsecond(); // get value from opstack
+ Inst( PPC_CMPL, 0, R_SECOND, R_TOP );
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( PPC_BC, 4, 1, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4(PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( PPC_BC, 12, 1, v );
+ rtopped = qfalse;
+ break;
+ case OP_GEU:
+ ltopandsecond(); // get value from opstack
+ Inst( PPC_CMPL, 0, R_SECOND, R_TOP );
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( PPC_BC, 12, 0, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4(PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( PPC_BC, 4, 0, v );
+ rtopped = qfalse;
+ break;
+
+ case OP_EQF:
+ fltopandsecond(); // get value from opstack
+ Inst( PPC_FCMPU, 0, R_TOP, R_SECOND );
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( PPC_BC, 4, 2, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4(PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( PPC_BC, 12, 2, v );
+ rtopped = qfalse;
+ break;
+ case OP_NEF:
+ fltopandsecond(); // get value from opstack
+ Inst( PPC_FCMPU, 0, R_TOP, R_SECOND );
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( PPC_BC, 12, 2, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4(PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( PPC_BC, 4, 2, v );
+ rtopped = qfalse;
+ break;
+ case OP_LTF:
+ fltopandsecond(); // get value from opstack
+ Inst( PPC_FCMPU, 0, R_SECOND, R_TOP );
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( PPC_BC, 4, 0, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4(PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( PPC_BC, 12, 0, v );
+ rtopped = qfalse;
+ break;
+ case OP_LEF:
+ fltopandsecond(); // get value from opstack
+ Inst( PPC_FCMPU, 0, R_SECOND, R_TOP );
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( PPC_BC, 12, 1, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4(PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( PPC_BC, 4, 1, v );
+ rtopped = qfalse;
+ break;
+ case OP_GTF:
+ fltopandsecond(); // get value from opstack
+ Inst( PPC_FCMPU, 0, R_SECOND, R_TOP );
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( PPC_BC, 4, 1, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4(PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( PPC_BC, 12, 1, v );
+ rtopped = qfalse;
+ break;
+ case OP_GEF:
+ fltopandsecond(); // get value from opstack
+ Inst( PPC_FCMPU, 0, R_SECOND, R_TOP );
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( PPC_BC, 12, 0, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4(PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( PPC_BC, 4, 0, v );
+ rtopped = qfalse;
+ break;
+
+ case OP_NEGI:
+ ltop(); // get value from opstack
+ InstImm( PPC_SUBFIC, R_TOP, R_TOP, 0 );
+ InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack
+ rtopped = qtrue;
+ break;
+ case OP_ADD:
+ ltop(); // get value from opstack
+ InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack
+ Inst( PPC_ADD, R_TOP, R_TOP, R_SECOND );
+ InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack
+ rtopped = qtrue;
+ break;
+ case OP_SUB:
+ ltop(); // get value from opstack
+ InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack
+ Inst( PPC_SUBF, R_TOP, R_TOP, R_SECOND );
+ InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack
+ rtopped = qtrue;
+ break;
+ case OP_DIVI:
+ ltop(); // get value from opstack
+ InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack
+ Inst( PPC_DIVW, R_TOP, R_SECOND, R_TOP );
+ InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack
+ rtopped = qtrue;
+ break;
+ case OP_DIVU:
+ ltop(); // get value from opstack
+ InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack
+ Inst( PPC_DIVWU, R_TOP, R_SECOND, R_TOP );
+ InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack
+ rtopped = qtrue;
+ break;
+ case OP_MODI:
+ ltop(); // get value from opstack
+ InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack
+ Inst( PPC_DIVW, R_EA, R_SECOND, R_TOP );
+ Inst( PPC_MULLW, R_EA, R_TOP, R_EA );
+ Inst( PPC_SUBF, R_TOP, R_EA, R_SECOND );
+ InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack
+ rtopped = qtrue;
+ break;
+ case OP_MODU:
+ ltop(); // get value from opstack
+ InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack
+ Inst( PPC_DIVWU, R_EA, R_SECOND, R_TOP );
+ Inst( PPC_MULLW, R_EA, R_TOP, R_EA );
+ Inst( PPC_SUBF, R_TOP, R_EA, R_SECOND );
+ InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack
+ rtopped = qtrue;
+ break;
+ case OP_MULI:
+ case OP_MULU:
+ ltop(); // get value from opstack
+ InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack
+ Inst( PPC_MULLW, R_TOP, R_SECOND, R_TOP );
+ InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack
+ rtopped = qtrue;
+ break;
+ case OP_BAND:
+ ltop(); // get value from opstack
+ InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack
+ Inst( PPC_AND, R_SECOND, R_TOP, R_TOP );
+ InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack
+ rtopped = qtrue;
+ break;
+ case OP_BOR:
+ ltop(); // get value from opstack
+ InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack
+ Inst( PPC_OR, R_SECOND, R_TOP, R_TOP );
+ InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack
+ rtopped = qtrue;
+ break;
+ case OP_BXOR:
+ ltop(); // get value from opstack
+ InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack
+ Inst( PPC_XOR, R_SECOND, R_TOP, R_TOP );
+ InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack
+ rtopped = qtrue;
+ break;
+ case OP_BCOM:
+ ltop(); // get value from opstack
+ Inst( PPC_NOR, R_TOP, R_TOP, R_TOP );
+ InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack
+ rtopped = qtrue;
+ break;
+ case OP_LSH:
+ ltop(); // get value from opstack
+ InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack
+ Inst( PPC_SLW, R_SECOND, R_TOP, R_TOP );
+ InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack
+ rtopped = qtrue;
+ break;
+ case OP_RSHI:
+ ltop(); // get value from opstack
+ InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack
+ Inst( PPC_SRAW, R_SECOND, R_TOP, R_TOP );
+ InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack
+ rtopped = qtrue;
+ break;
+ case OP_RSHU:
+ ltop(); // get value from opstack
+ InstImm( PPC_LWZU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack
+ Inst( PPC_SRW, R_SECOND, R_TOP, R_TOP );
+ InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 ); // save value to opstack
+ rtopped = qtrue;
+ break;
+
+ case OP_NEGF:
+ InstImm( PPC_LFS, R_TOP, R_OPSTACK, 0 ); // get value from opstack
+ Inst( PPC_FNEG, R_TOP, 0, R_TOP );
+ InstImm( PPC_STFS, R_TOP, R_OPSTACK, 0 ); // save value to opstack
+ rtopped = qfalse;
+ break;
+ case OP_ADDF:
+ InstImm( PPC_LFS, R_TOP, R_OPSTACK, 0 ); // get value from opstack
+ InstImm( PPC_LFSU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack
+ Inst( PPC_FADDS, R_TOP, R_SECOND, R_TOP );
+ InstImm( PPC_STFS, R_TOP, R_OPSTACK, 0 ); // save value to opstack
+ rtopped = qfalse;
+ break;
+ case OP_SUBF:
+ InstImm( PPC_LFS, R_TOP, R_OPSTACK, 0 ); // get value from opstack
+ InstImm( PPC_LFSU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack
+ Inst( PPC_FSUBS, R_TOP, R_SECOND, R_TOP );
+ InstImm( PPC_STFS, R_TOP, R_OPSTACK, 0 ); // save value to opstack
+ rtopped = qfalse;
+ break;
+ case OP_DIVF:
+ InstImm( PPC_LFS, R_TOP, R_OPSTACK, 0 ); // get value from opstack
+ InstImm( PPC_LFSU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack
+ Inst( PPC_FDIVS, R_TOP, R_SECOND, R_TOP );
+ InstImm( PPC_STFS, R_TOP, R_OPSTACK, 0 ); // save value to opstack
+ rtopped = qfalse;
+ break;
+ case OP_MULF:
+ InstImm( PPC_LFS, R_TOP, R_OPSTACK, 0 ); // get value from opstack
+ InstImm( PPC_LFSU, R_SECOND, R_OPSTACK, -4 ); // get value from opstack
+ Inst4( PPC_FMULS, R_TOP, R_SECOND, 0, R_TOP );
+ InstImm( PPC_STFS, R_TOP, R_OPSTACK, 0 ); // save value to opstack
+ rtopped = qfalse;
+ break;
+
+ case OP_CVIF:
+ v = (int)&itofConvert;
+ InstImmU( PPC_ADDIS, R_EA, 0, (v >> 16)&0xffff );
+ InstImmU( PPC_ORI, R_EA, R_EA, v & 0xffff );
+ InstImm( PPC_LWZ, R_TOP, R_OPSTACK, 0 ); // get value from opstack
+ InstImmU( PPC_XORIS, R_TOP, R_TOP, 0x8000 );
+ InstImm( PPC_STW, R_TOP, R_EA, 12 );
+ InstImm( PPC_LFD, R_TOP, R_EA, 0 );
+ InstImm( PPC_LFD, R_SECOND, R_EA, 8 );
+ Inst( PPC_FSUB, R_TOP, R_SECOND, R_TOP );
+ // Inst( PPC_FRSP, R_TOP, 0, R_TOP );
+ InstImm( PPC_STFS, R_TOP, R_OPSTACK, 0 ); // save value to opstack
+ rtopped = qfalse;
+ break;
+ case OP_CVFI:
+ InstImm( PPC_LFS, R_TOP, R_OPSTACK, 0 ); // get value from opstack
+ Inst( PPC_FCTIWZ, R_TOP, 0, R_TOP );
+ Inst( PPC_STFIWX, R_TOP, 0, R_OPSTACK ); // save value to opstack
+ rtopped = qfalse;
+ break;
+ case OP_SEX8:
+ ltop(); // get value from opstack
+ Inst( PPC_EXTSB, R_TOP, R_TOP, 0 );
+ InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 );
+ rtopped = qtrue;
+ break;
+ case OP_SEX16:
+ ltop(); // get value from opstack
+ Inst( PPC_EXTSH, R_TOP, R_TOP, 0 );
+ InstImm( PPC_STW, R_TOP, R_OPSTACK, 0 );
+ rtopped = qtrue;
+ break;
+
+ case OP_BLOCK_COPY:
+ v = Constant4() >> 2;
+ ltop(); // source
+ InstImm( PPC_LWZ, R_SECOND, R_OPSTACK, -4 ); // dest
+ InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -8 );
+ InstImmU( PPC_ADDI, R_EA, 0, v ); // count
+ // FIXME: range check
+ Inst( PPC_MTSPR, R_EA, 9, 0 ); // move to count register
+
+ Inst( PPC_ADD, R_TOP, R_TOP, R_MEMBASE );
+ InstImm( PPC_ADDI, R_TOP, R_TOP, -4 );
+ Inst( PPC_ADD, R_SECOND, R_SECOND, R_MEMBASE );
+ InstImm( PPC_ADDI, R_SECOND, R_SECOND, -4 );
+
+ InstImm( PPC_LWZU, R_EA, R_TOP, 4 ); // source
+ InstImm( PPC_STWU, R_EA, R_SECOND, 4 ); // dest
+ Inst( PPC_BC | 0xfff8 , 16, 0, 0 ); // loop
+ rtopped = qfalse;
+ break;
+
+ case OP_JUMP:
+ ltop(); // get value from opstack
+ InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -4 );
+ Inst( PPC_RLWINM | ( 29 << 1 ), R_TOP, R_TOP, 2 );
+ // FIXME: range check
+ Inst( PPC_LWZX, R_TOP, R_TOP, R_INSTRUCTIONS );
+ Inst( PPC_MTSPR, R_TOP, 9, 0 ); // move to count register
+ Inst( PPC_BCCTR, 20, 0, 0 ); // jump to the count register
+ rtopped = qfalse;
+ break;
+ default:
+ Com_Error( ERR_DROP, "VM_CompilePPC: bad opcode %i at instruction %i, offset %i", op, instruction, pc );
+ }
+ pop0 = pop1;
+ pop1 = op;
+ }
+
+ Com_Printf( "VM file %s pass %d compiled to %i bytes of code\n", vm->name, (pass+1), compiledOfs*4 );
+
+ if ( pass == 0 ) {
+ // copy to an exact size buffer on the hunk
+ vm->codeLength = compiledOfs * 4;
+ vm->codeBase = Hunk_Alloc( vm->codeLength, h_low );
+ Com_Memcpy( vm->codeBase, buf, vm->codeLength );
+ Z_Free( buf );
+
+ // offset all the instruction pointers for the new location
+ for ( i = 0 ; i < header->instructionCount ; i++ ) {
+ vm->instructionPointers[i] += (int)vm->codeBase;
+ }
+
+ // go back over it in place now to fixup reletive jump targets
+ buf = (unsigned *)vm->codeBase;
+ }
+ }
+ Z_Free( jused );
+}
+
+/*
+==============
+VM_CallCompiled
+
+This function is called directly by the generated code
+==============
+*/
+int VM_CallCompiled( vm_t *vm, int *args ) {
+ int stack[1024];
+ int programStack;
+ int stackOnEntry;
+ byte *image;
+
+ currentVM = vm;
+
+ // interpret the code
+ vm->currentlyInterpreting = qtrue;
+
+ // we might be called recursively, so this might not be the very top
+ programStack = vm->programStack;
+ stackOnEntry = programStack;
+ image = vm->dataBase;
+
+ // set up the stack frame
+ programStack -= 48;
+
+ *(int *)&image[ programStack + 44] = args[9];
+ *(int *)&image[ programStack + 40] = args[8];
+ *(int *)&image[ programStack + 36] = args[7];
+ *(int *)&image[ programStack + 32] = args[6];
+ *(int *)&image[ programStack + 28] = args[5];
+ *(int *)&image[ programStack + 24] = args[4];
+ *(int *)&image[ programStack + 20] = args[3];
+ *(int *)&image[ programStack + 16] = args[2];
+ *(int *)&image[ programStack + 12] = args[1];
+ *(int *)&image[ programStack + 8 ] = args[0];
+ *(int *)&image[ programStack + 4 ] = 0; // return stack
+ *(int *)&image[ programStack ] = -1; // will terminate the loop on return
+
+ // off we go into generated code...
+ // the PPC calling standard says the parms will all go into R3 - R11, so
+ // no special asm code is needed here
+#ifdef __GNUC__
+ ((void(*)(int, int, int, int, int, int, int, int))(vm->codeBase))(
+ programStack, (int)&stack,
+ (int)image, vm->dataMask, (int)&AsmCall,
+ (int)vm->instructionPointers, vm->instructionPointersLength,
+ (int)vm );
+#else
+ ((void(*)(int, int, int, int, int, int, int, int))(vm->codeBase))(
+ programStack, (int)&stack,
+ (int)image, vm->dataMask, *(int *)&AsmCall /* skip function pointer header */,
+ (int)vm->instructionPointers, vm->instructionPointersLength,
+ (int)vm );
+#endif
+ vm->programStack = stackOnEntry;
+
+ vm->currentlyInterpreting = qfalse;
+
+ return stack[1];
+}
+
+
+/*
+==================
+AsmCall
+
+Put this at end of file because gcc messes up debug line numbers
+==================
+*/
+#ifdef __GNUC__
+
+void AsmCall( void ) {
+asm (
+ // pop off the destination instruction
+" lwz r12,0(r4) \n" // RG_TOP, 0(RG_OPSTACK)
+" addi r4,r4,-4 \n" // RG_OPSTACK, RG_OPSTACK, -4 \n"
+
+ // see if it is a system trap
+" cmpwi r12,0 \n" // RG_TOP, 0 \n"
+" bc 12,0, systemTrap \n"
+
+ // calling another VM function, so lookup in instructionPointers
+" slwi r12,r12,2 \n" // RG_TOP,RG_TOP,2
+ // FIXME: range check
+" lwzx r12, r8, r12 \n" // RG_TOP, RG_INSTRUCTIONS(RG_TOP)
+" mtctr r12 \n" // RG_TOP
+);
+
+#if defined(MACOS_X) && defined(__OPTIMIZE__)
+ // On Mac OS X, gcc doesn't push a frame when we are optimized, so trying to tear it down results in grave disorder.
+#warning Mac OS X optimization on, not popping GCC AsmCall frame
+#else
+ // Mac OS X Server and unoptimized compiles include a GCC AsmCall frame
+ asm (
+" lwz r1,0(r1) \n" // pop off the GCC AsmCall frame
+" lmw r30,-8(r1) \n"
+);
+#endif
+
+asm (
+" bcctr 20,0 \n" // when it hits a leave, it will branch to the current link register
+
+ // calling a system trap
+"systemTrap: \n"
+ // convert to positive system call number
+" subfic r12,r12,-1 \n"
+
+ // save all our registers, including the current link register
+" mflr r13 \n" // RG_SECOND // copy off our link register
+" addi r1,r1,-92 \n" // required 24 byets of linkage, 32 bytes of parameter, plus our saves
+" stw r3,56(r1) \n" // RG_STACK, -36(REAL_STACK)
+" stw r4,60(r1) \n" // RG_OPSTACK, 4(RG_REAL_STACK)
+" stw r5,64(r1) \n" // RG_MEMBASE, 8(RG_REAL_STACK)
+" stw r6,68(r1) \n" // RG_MEMMASK, 12(RG_REAL_STACK)
+" stw r7,72(r1) \n" // RG_ASMCALL, 16(RG_REAL_STACK)
+" stw r8,76(r1) \n" // RG_INSTRUCTIONS, 20(RG_REAL_STACK)
+" stw r9,80(r1) \n" // RG_NUM_INSTRUCTIONS, 24(RG_REAL_STACK)
+" stw r10,84(r1) \n" // RG_VM, 28(RG_REAL_STACK)
+" stw r13,88(r1) \n" // RG_SECOND, 32(RG_REAL_STACK) // link register
+
+ // save the vm stack position to allow recursive VM entry
+" addi r13,r3,-4 \n" // RG_TOP, RG_STACK, -4
+" stw r13,0(r10) \n" //RG_TOP, VM_OFFSET_PROGRAM_STACK(RG_VM)
+
+ // save the system call number as the 0th parameter
+" add r3,r3,r5 \n" // r3, RG_STACK, RG_MEMBASE // r3 is the first parameter to vm->systemCalls
+" stwu r12,4(r3) \n" // RG_TOP, 4(r3)
+
+ // make the system call with the address of all the VM parms as a parameter
+ // vm->systemCalls( &parms )
+" lwz r12,4(r10) \n" // RG_TOP, VM_OFFSET_SYSTEM_CALL(RG_VM)
+" mtctr r12 \n" // RG_TOP
+" bcctrl 20,0 \n"
+" mr r12,r3 \n" // RG_TOP, r3
+
+ // pop our saved registers
+" lwz r3,56(r1) \n" // RG_STACK, 0(RG_REAL_STACK)
+" lwz r4,60(r1) \n" // RG_OPSTACK, 4(RG_REAL_STACK)
+" lwz r5,64(r1) \n" // RG_MEMBASE, 8(RG_REAL_STACK)
+" lwz r6,68(r1) \n" // RG_MEMMASK, 12(RG_REAL_STACK)
+" lwz r7,72(r1) \n" // RG_ASMCALL, 16(RG_REAL_STACK)
+" lwz r8,76(r1) \n" // RG_INSTRUCTIONS, 20(RG_REAL_STACK)
+" lwz r9,80(r1) \n" // RG_NUM_INSTRUCTIONS, 24(RG_REAL_STACK)
+" lwz r10,84(r1) \n" // RG_VM, 28(RG_REAL_STACK)
+" lwz r13,88(r1) \n" // RG_SECOND, 32(RG_REAL_STACK)
+" addi r1,r1,92 \n" // RG_REAL_STACK, RG_REAL_STACK, 36
+
+ // restore the old link register
+" mtlr r13 \n" // RG_SECOND
+
+ // save off the return value
+" stwu r12,4(r4) \n" // RG_TOP, 0(RG_OPSTACK)
+
+ // GCC adds its own prolog / epilog code
+ );
+}
+#else
+
+// codewarrior version
+
+void asm AsmCall( void ) {
+
+ // pop off the destination instruction
+
+ lwz r12,0(r4) // RG_TOP, 0(RG_OPSTACK)
+
+ addi r4,r4,-4 // RG_OPSTACK, RG_OPSTACK, -4
+
+
+
+ // see if it is a system trap
+
+ cmpwi r12,0 // RG_TOP, 0
+
+ bc 12,0, systemTrap
+
+
+
+ // calling another VM function, so lookup in instructionPointers
+
+ slwi r12,r12,2 // RG_TOP,RG_TOP,2
+
+ // FIXME: range check
+
+ lwzx r12, r8, r12 // RG_TOP, RG_INSTRUCTIONS(RG_TOP)
+
+ mtctr r12 // RG_TOP
+
+
+
+ bcctr 20,0 // when it hits a leave, it will branch to the current link register
+
+
+
+ // calling a system trap
+
+systemTrap:
+
+ // convert to positive system call number
+
+ subfic r12,r12,-1
+
+
+
+ // save all our registers, including the current link register
+
+ mflr r13 // RG_SECOND // copy off our link register
+
+ addi r1,r1,-92 // required 24 byets of linkage, 32 bytes of parameter, plus our saves
+
+ stw r3,56(r1) // RG_STACK, -36(REAL_STACK)
+
+ stw r4,60(r1) // RG_OPSTACK, 4(RG_REAL_STACK)
+
+ stw r5,64(r1) // RG_MEMBASE, 8(RG_REAL_STACK)
+
+ stw r6,68(r1) // RG_MEMMASK, 12(RG_REAL_STACK)
+
+ stw r7,72(r1) // RG_ASMCALL, 16(RG_REAL_STACK)
+
+ stw r8,76(r1) // RG_INSTRUCTIONS, 20(RG_REAL_STACK)
+
+ stw r9,80(r1) // RG_NUM_INSTRUCTIONS, 24(RG_REAL_STACK)
+
+ stw r10,84(r1) // RG_VM, 28(RG_REAL_STACK)
+
+ stw r13,88(r1) // RG_SECOND, 32(RG_REAL_STACK) // link register
+
+
+
+ // save the vm stack position to allow recursive VM entry
+
+ addi r13,r3,-4 // RG_TOP, RG_STACK, -4
+
+ stw r13,0(r10) //RG_TOP, VM_OFFSET_PROGRAM_STACK(RG_VM)
+
+
+
+ // save the system call number as the 0th parameter
+
+ add r3,r3,r5 // r3, RG_STACK, RG_MEMBASE // r3 is the first parameter to vm->systemCalls
+
+ stwu r12,4(r3) // RG_TOP, 4(r3)
+
+
+
+ // make the system call with the address of all the VM parms as a parameter
+
+ // vm->systemCalls( &parms )
+
+ lwz r12,4(r10) // RG_TOP, VM_OFFSET_SYSTEM_CALL(RG_VM)
+
+
+
+ // perform macos cross fragment fixup crap
+
+ lwz r9,0(r12)
+
+ stw r2,52(r1) // save old TOC
+
+ lwz r2,4(r12)
+
+
+
+ mtctr r9 // RG_TOP
+
+ bcctrl 20,0
+
+
+
+ lwz r2,52(r1) // restore TOC
+
+
+
+ mr r12,r3 // RG_TOP, r3
+
+
+
+ // pop our saved registers
+
+ lwz r3,56(r1) // RG_STACK, 0(RG_REAL_STACK)
+
+ lwz r4,60(r1) // RG_OPSTACK, 4(RG_REAL_STACK)
+
+ lwz r5,64(r1) // RG_MEMBASE, 8(RG_REAL_STACK)
+
+ lwz r6,68(r1) // RG_MEMMASK, 12(RG_REAL_STACK)
+
+ lwz r7,72(r1) // RG_ASMCALL, 16(RG_REAL_STACK)
+
+ lwz r8,76(r1) // RG_INSTRUCTIONS, 20(RG_REAL_STACK)
+
+ lwz r9,80(r1) // RG_NUM_INSTRUCTIONS, 24(RG_REAL_STACK)
+
+ lwz r10,84(r1) // RG_VM, 28(RG_REAL_STACK)
+
+ lwz r13,88(r1) // RG_SECOND, 32(RG_REAL_STACK)
+
+ addi r1,r1,92 // RG_REAL_STACK, RG_REAL_STACK, 36
+
+
+
+ // restore the old link register
+
+ mtlr r13 // RG_SECOND
+
+
+
+ // save off the return value
+
+ stwu r12,4(r4) // RG_TOP, 0(RG_OPSTACK)
+
+
+
+ blr
+
+}
+
+
+
+
+#endif
diff --git a/code/qcommon/vm_ppc_new.c b/code/qcommon/vm_ppc_new.c
new file mode 100755
index 0000000..b03d4d6
--- /dev/null
+++ b/code/qcommon/vm_ppc_new.c
@@ -0,0 +1,2119 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// vm_ppc.c
+// ppc dynamic compiler
+
+#include "vm_local.h"
+
+#pragma opt_pointer_analysis off
+
+#define DEBUG_VM 0
+
+#if DEBUG_VM
+static char *opnames[256] = {
+ "OP_UNDEF",
+
+ "OP_IGNORE",
+
+ "OP_BREAK",
+
+ "OP_ENTER",
+ "OP_LEAVE",
+ "OP_CALL",
+ "OP_PUSH",
+ "OP_POP",
+
+ "OP_CONST",
+
+ "OP_LOCAL",
+
+ "OP_JUMP",
+
+ //-------------------
+
+ "OP_EQ",
+ "OP_NE",
+
+ "OP_LTI",
+ "OP_LEI",
+ "OP_GTI",
+ "OP_GEI",
+
+ "OP_LTU",
+ "OP_LEU",
+ "OP_GTU",
+ "OP_GEU",
+
+ "OP_EQF",
+ "OP_NEF",
+
+ "OP_LTF",
+ "OP_LEF",
+ "OP_GTF",
+ "OP_GEF",
+
+ //-------------------
+
+ "OP_LOAD1",
+ "OP_LOAD2",
+ "OP_LOAD4",
+ "OP_STORE1",
+ "OP_STORE2",
+ "OP_STORE4",
+ "OP_ARG",
+
+ "OP_BLOCK_COPY",
+
+ //-------------------
+
+ "OP_SEX8",
+ "OP_SEX16",
+
+ "OP_NEGI",
+ "OP_ADD",
+ "OP_SUB",
+ "OP_DIVI",
+ "OP_DIVU",
+ "OP_MODI",
+ "OP_MODU",
+ "OP_MULI",
+ "OP_MULU",
+
+ "OP_BAND",
+ "OP_BOR",
+ "OP_BXOR",
+ "OP_BCOM",
+
+ "OP_LSH",
+ "OP_RSHI",
+ "OP_RSHU",
+
+ "OP_NEGF",
+ "OP_ADDF",
+ "OP_SUBF",
+ "OP_DIVF",
+ "OP_MULF",
+
+ "OP_CVIF",
+ "OP_CVFI"
+};
+#endif
+
+typedef enum {
+ R_REAL_STACK = 1,
+ // registers 3-11 are the parameter passing registers
+
+ // state
+ R_STACK = 3, // local
+ R_OPSTACK, // global
+
+ // constants
+ R_MEMBASE, // global
+ R_MEMMASK,
+ R_ASMCALL, // global
+ R_INSTRUCTIONS, // global
+ R_NUM_INSTRUCTIONS, // global
+ R_CVM, // currentVM
+
+ // temps
+ R_TOP = 11,
+ R_SECOND = 12,
+ R_EA = 2 // effective address calculation
+
+} regNums_t;
+
+#define RG_REAL_STACK r1
+#define RG_STACK r3
+#define RG_OPSTACK r4
+#define RG_MEMBASE r5
+#define RG_MEMMASK r6
+#define RG_ASMCALL r7
+#define RG_INSTRUCTIONS r8
+#define RG_NUM_INSTRUCTIONS r9
+#define RG_CVM r10
+#define RG_TOP r12
+#define RG_SECOND r13
+#define RG_EA r14
+
+// The deepest value I saw in the Quake3 games was 9.
+#define OP_STACK_MAX_DEPTH 12
+
+// These are all volatile and thus must be saved
+// upon entry to the VM code.
+static int opStackIntRegisters[OP_STACK_MAX_DEPTH] =
+{
+ 16, 17, 18, 19,
+ 20, 21, 22, 23,
+ 24, 25, 26, 27
+};
+
+static unsigned int *opStackLoadInstructionAddr[OP_STACK_MAX_DEPTH];
+
+// We use different registers for the floating point
+// operand stack (these are volatile in the PPC ABI)
+static int opStackFloatRegisters[OP_STACK_MAX_DEPTH] =
+{
+ 0, 1, 2, 3,
+ 4, 5, 6, 7,
+ 8, 9, 10, 11
+};
+
+static int opStackRegType[OP_STACK_MAX_DEPTH] =
+{
+ 0, 0, 0, 0,
+ 0, 0, 0, 0,
+ 0, 0, 0, 0
+};
+
+// this doesn't have the low order bits set for instructions i'm not using...
+typedef enum {
+ PPC_TDI = 0x08000000,
+ PPC_TWI = 0x0c000000,
+ PPC_MULLI = 0x1c000000,
+ PPC_SUBFIC = 0x20000000,
+ PPC_CMPI = 0x28000000,
+ PPC_CMPLI = 0x2c000000,
+ PPC_ADDIC = 0x30000000,
+ PPC_ADDIC_ = 0x34000000,
+ PPC_ADDI = 0x38000000,
+ PPC_ADDIS = 0x3c000000,
+ PPC_BC = 0x40000000,
+ PPC_SC = 0x44000000,
+ PPC_B = 0x48000000,
+
+ PPC_MCRF = 0x4c000000,
+ PPC_BCLR = 0x4c000020,
+ PPC_RFID = 0x4c000000,
+ PPC_CRNOR = 0x4c000000,
+ PPC_RFI = 0x4c000000,
+ PPC_CRANDC = 0x4c000000,
+ PPC_ISYNC = 0x4c000000,
+ PPC_CRXOR = 0x4c000000,
+ PPC_CRNAND = 0x4c000000,
+ PPC_CREQV = 0x4c000000,
+ PPC_CRORC = 0x4c000000,
+ PPC_CROR = 0x4c000000,
+//------------
+ PPC_BCCTR = 0x4c000420,
+ PPC_RLWIMI = 0x50000000,
+ PPC_RLWINM = 0x54000000,
+ PPC_RLWNM = 0x5c000000,
+ PPC_ORI = 0x60000000,
+ PPC_ORIS = 0x64000000,
+ PPC_XORI = 0x68000000,
+ PPC_XORIS = 0x6c000000,
+ PPC_ANDI_ = 0x70000000,
+ PPC_ANDIS_ = 0x74000000,
+ PPC_RLDICL = 0x78000000,
+ PPC_RLDICR = 0x78000000,
+ PPC_RLDIC = 0x78000000,
+ PPC_RLDIMI = 0x78000000,
+ PPC_RLDCL = 0x78000000,
+ PPC_RLDCR = 0x78000000,
+ PPC_CMP = 0x7c000000,
+ PPC_TW = 0x7c000000,
+ PPC_SUBFC = 0x7c000010,
+ PPC_MULHDU = 0x7c000000,
+ PPC_ADDC = 0x7c000014,
+ PPC_MULHWU = 0x7c000000,
+ PPC_MFCR = 0x7c000000,
+ PPC_LWAR = 0x7c000000,
+ PPC_LDX = 0x7c000000,
+ PPC_LWZX = 0x7c00002e,
+ PPC_SLW = 0x7c000030,
+ PPC_CNTLZW = 0x7c000000,
+ PPC_SLD = 0x7c000000,
+ PPC_AND = 0x7c000038,
+ PPC_CMPL = 0x7c000040,
+ PPC_SUBF = 0x7c000050,
+ PPC_LDUX = 0x7c000000,
+//------------
+ PPC_DCBST = 0x7c000000,
+ PPC_LWZUX = 0x7c00006c,
+ PPC_CNTLZD = 0x7c000000,
+ PPC_ANDC = 0x7c000000,
+ PPC_TD = 0x7c000000,
+ PPC_MULHD = 0x7c000000,
+ PPC_MULHW = 0x7c000000,
+ PPC_MTSRD = 0x7c000000,
+ PPC_MFMSR = 0x7c000000,
+ PPC_LDARX = 0x7c000000,
+ PPC_DCBF = 0x7c000000,
+ PPC_LBZX = 0x7c0000ae,
+ PPC_NEG = 0x7c000000,
+ PPC_MTSRDIN = 0x7c000000,
+ PPC_LBZUX = 0x7c000000,
+ PPC_NOR = 0x7c0000f8,
+ PPC_SUBFE = 0x7c000000,
+ PPC_ADDE = 0x7c000000,
+ PPC_MTCRF = 0x7c000000,
+ PPC_MTMSR = 0x7c000000,
+ PPC_STDX = 0x7c000000,
+ PPC_STWCX_ = 0x7c000000,
+ PPC_STWX = 0x7c00012e,
+ PPC_MTMSRD = 0x7c000000,
+ PPC_STDUX = 0x7c000000,
+ PPC_STWUX = 0x7c00016e,
+ PPC_SUBFZE = 0x7c000000,
+ PPC_ADDZE = 0x7c000000,
+ PPC_MTSR = 0x7c000000,
+ PPC_STDCX_ = 0x7c000000,
+ PPC_STBX = 0x7c0001ae,
+ PPC_SUBFME = 0x7c000000,
+ PPC_MULLD = 0x7c000000,
+//------------
+ PPC_ADDME = 0x7c000000,
+ PPC_MULLW = 0x7c0001d6,
+ PPC_MTSRIN = 0x7c000000,
+ PPC_DCBTST = 0x7c000000,
+ PPC_STBUX = 0x7c000000,
+ PPC_ADD = 0x7c000214,
+ PPC_DCBT = 0x7c000000,
+ PPC_LHZX = 0x7c00022e,
+ PPC_EQV = 0x7c000000,
+ PPC_TLBIE = 0x7c000000,
+ PPC_ECIWX = 0x7c000000,
+ PPC_LHZUX = 0x7c000000,
+ PPC_XOR = 0x7c000278,
+ PPC_MFSPR = 0x7c0002a6,
+ PPC_LWAX = 0x7c000000,
+ PPC_LHAX = 0x7c000000,
+ PPC_TLBIA = 0x7c000000,
+ PPC_MFTB = 0x7c000000,
+ PPC_LWAUX = 0x7c000000,
+ PPC_LHAUX = 0x7c000000,
+ PPC_STHX = 0x7c00032e,
+ PPC_ORC = 0x7c000338,
+ PPC_SRADI = 0x7c000000,
+ PPC_SLBIE = 0x7c000000,
+ PPC_ECOWX = 0x7c000000,
+ PPC_STHUX = 0x7c000000,
+ PPC_OR = 0x7c000378,
+ PPC_DIVDU = 0x7c000000,
+ PPC_DIVWU = 0x7c000396,
+ PPC_MTSPR = 0x7c0003a6,
+ PPC_DCBI = 0x7c000000,
+ PPC_NAND = 0x7c000000,
+ PPC_DIVD = 0x7c000000,
+//------------
+ PPC_DIVW = 0x7c0003d6,
+ PPC_SLBIA = 0x7c000000,
+ PPC_MCRXR = 0x7c000000,
+ PPC_LSWX = 0x7c000000,
+ PPC_LWBRX = 0x7c000000,
+ PPC_LFSX = 0x7c00042e,
+ PPC_SRW = 0x7c000430,
+ PPC_SRD = 0x7c000000,
+ PPC_TLBSYNC = 0x7c000000,
+ PPC_LFSUX = 0x7c000000,
+ PPC_MFSR = 0x7c000000,
+ PPC_LSWI = 0x7c000000,
+ PPC_SYNC = 0x7c000000,
+ PPC_LFDX = 0x7c000000,
+ PPC_LFDUX = 0x7c000000,
+ PPC_MFSRIN = 0x7c000000,
+ PPC_STSWX = 0x7c000000,
+ PPC_STWBRX = 0x7c000000,
+ PPC_STFSX = 0x7c00052e,
+ PPC_STFSUX = 0x7c000000,
+ PPC_STSWI = 0x7c000000,
+ PPC_STFDX = 0x7c000000,
+ PPC_DCBA = 0x7c000000,
+ PPC_STFDUX = 0x7c000000,
+ PPC_LHBRX = 0x7c000000,
+ PPC_SRAW = 0x7c000630,
+ PPC_SRAD = 0x7c000000,
+ PPC_SRAWI = 0x7c000000,
+ PPC_EIEIO = 0x7c000000,
+ PPC_STHBRX = 0x7c000000,
+ PPC_EXTSH = 0x7c000734,
+ PPC_EXTSB = 0x7c000774,
+ PPC_ICBI = 0x7c000000,
+//------------
+ PPC_STFIWX = 0x7c0007ae,
+ PPC_EXTSW = 0x7c000000,
+ PPC_DCBZ = 0x7c000000,
+ PPC_LWZ = 0x80000000,
+ PPC_LWZU = 0x84000000,
+ PPC_LBZ = 0x88000000,
+ PPC_LBZU = 0x8c000000,
+ PPC_STW = 0x90000000,
+ PPC_STWU = 0x94000000,
+ PPC_STB = 0x98000000,
+ PPC_STBU = 0x9c000000,
+ PPC_LHZ = 0xa0000000,
+ PPC_LHZU = 0xa4000000,
+ PPC_LHA = 0xa8000000,
+ PPC_LHAU = 0xac000000,
+ PPC_STH = 0xb0000000,
+ PPC_STHU = 0xb4000000,
+ PPC_LMW = 0xb8000000,
+ PPC_STMW = 0xbc000000,
+ PPC_LFS = 0xc0000000,
+ PPC_LFSU = 0xc4000000,
+ PPC_LFD = 0xc8000000,
+ PPC_LFDU = 0xcc000000,
+ PPC_STFS = 0xd0000000,
+ PPC_STFSU = 0xd4000000,
+ PPC_STFD = 0xd8000000,
+ PPC_STFDU = 0xdc000000,
+ PPC_LD = 0xe8000000,
+ PPC_LDU = 0xe8000001,
+ PPC_LWA = 0xe8000002,
+ PPC_FDIVS = 0xec000024,
+ PPC_FSUBS = 0xec000028,
+ PPC_FADDS = 0xec00002a,
+//------------
+ PPC_FSQRTS = 0xec000000,
+ PPC_FRES = 0xec000000,
+ PPC_FMULS = 0xec000032,
+ PPC_FMSUBS = 0xec000000,
+ PPC_FMADDS = 0xec000000,
+ PPC_FNMSUBS = 0xec000000,
+ PPC_FNMADDS = 0xec000000,
+ PPC_STD = 0xf8000000,
+ PPC_STDU = 0xf8000001,
+ PPC_FCMPU = 0xfc000000,
+ PPC_FRSP = 0xfc000018,
+ PPC_FCTIW = 0xfc000000,
+ PPC_FCTIWZ = 0xfc00001e,
+ PPC_FDIV = 0xfc000000,
+ PPC_FSUB = 0xfc000028,
+ PPC_FADD = 0xfc000000,
+ PPC_FSQRT = 0xfc000000,
+ PPC_FSEL = 0xfc000000,
+ PPC_FMUL = 0xfc000000,
+ PPC_FRSQRTE = 0xfc000000,
+ PPC_FMSUB = 0xfc000000,
+ PPC_FMADD = 0xfc000000,
+ PPC_FNMSUB = 0xfc000000,
+ PPC_FNMADD = 0xfc000000,
+ PPC_FCMPO = 0xfc000000,
+ PPC_MTFSB1 = 0xfc000000,
+ PPC_FNEG = 0xfc000050,
+ PPC_MCRFS = 0xfc000000,
+ PPC_MTFSB0 = 0xfc000000,
+ PPC_FMR = 0xfc000000,
+ PPC_MTFSFI = 0xfc000000,
+ PPC_FNABS = 0xfc000000,
+ PPC_FABS = 0xfc000000,
+//------------
+ PPC_MFFS = 0xfc000000,
+ PPC_MTFSF = 0xfc000000,
+ PPC_FCTID = 0xfc000000,
+ PPC_FCTIDZ = 0xfc000000,
+ PPC_FCFID = 0xfc000000
+
+} ppcOpcodes_t;
+
+
+// the newly generated code
+static unsigned *buf;
+static int compiledOfs; // in dwords
+static int pass;
+
+// fromt the original bytecode
+static byte *code;
+static int pc;
+
+void AsmCall( void );
+
+double itofConvert[2];
+
+static int Constant4( void ) {
+ int v;
+
+ v = code[pc] | (code[pc+1]<<8) | (code[pc+2]<<16) | (code[pc+3]<<24);
+ pc += 4;
+ return v;
+}
+
+static int Constant1( void ) {
+ int v;
+
+ v = code[pc];
+ pc += 1;
+ return v;
+}
+
+static void Emit4( char *opname, int i ) {
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("\t\t\t%p %s\t%08lx\n",&buf[compiledOfs],opname,i&0x3ffffff);
+ #endif
+ buf[ compiledOfs ] = i;
+ compiledOfs++;
+}
+
+static void Inst( char *opname, int opcode, int destReg, int aReg, int bReg ) {
+ unsigned r;
+
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("\t\t\t%p %s\tr%d,r%d,r%d\n",&buf[compiledOfs],opname,destReg,aReg,bReg);
+ #endif
+ r = opcode | ( destReg << 21 ) | ( aReg << 16 ) | ( bReg << 11 ) ;
+ buf[ compiledOfs ] = r;
+ compiledOfs++;
+}
+
+static void Inst4( char *opname, int opcode, int destReg, int aReg, int bReg, int cReg ) {
+ unsigned r;
+
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("\t\t\t%p %s\tr%d,r%d,r%d,r%d\n",&buf[compiledOfs],opname,destReg,aReg,bReg,cReg);
+ #endif
+ r = opcode | ( destReg << 21 ) | ( aReg << 16 ) | ( bReg << 11 ) | ( cReg << 6 );
+ buf[ compiledOfs ] = r;
+ compiledOfs++;
+}
+
+static void InstImm( char *opname, int opcode, int destReg, int aReg, int immediate ) {
+ unsigned r;
+
+ if ( immediate > 32767 || immediate < -32768 ) {
+ Com_Error( ERR_FATAL, "VM_Compile: immediate value %i out of range, opcode %x,%d,%d", immediate, opcode, destReg, aReg );
+ }
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("\t\t\t%p %s\tr%d,r%d,0x%x\n",&buf[compiledOfs],opname,destReg,aReg,immediate);
+ #endif
+ r = opcode | ( destReg << 21 ) | ( aReg << 16 ) | ( immediate & 0xffff );
+ buf[ compiledOfs ] = r;
+ compiledOfs++;
+}
+
+static void InstImmU( char *opname, int opcode, int destReg, int aReg, int immediate ) {
+ unsigned r;
+
+ if ( immediate > 0xffff || immediate < 0 ) {
+ Com_Error( ERR_FATAL, "VM_Compile: immediate value %i out of range", immediate );
+ }
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("\t\t\t%p %s\tr%d,r%d,0x%x\n",&buf[compiledOfs],opname,destReg,aReg,immediate);
+ #endif
+ r = opcode | ( destReg << 21 ) | ( aReg << 16 ) | ( immediate & 0xffff );
+ buf[ compiledOfs ] = r;
+ compiledOfs++;
+}
+
+static int pop0, pop1, oc0, oc1;
+static vm_t *tvm;
+static int instruction;
+static byte *jused;
+
+static void ltop() {
+// if (rtopped == qfalse) {
+// InstImm( PPC_LWZ, R_TOP, R_OPSTACK, 0 ); // get value from opstack
+// }
+}
+
+static void ltopandsecond() {
+#if 0
+ if (pass>=0 && buf[compiledOfs-1] == (PPC_STWU | R_TOP<<21 | R_OPSTACK<<16 | 4 ) && jused[instruction]==0 ) {
+ compiledOfs--;
+ if (!pass) {
+ tvm->instructionPointers[instruction] = compiledOfs * 4;
+ }
+ InstImm( PPC_LWZ, R_SECOND, R_OPSTACK, 0 ); // get value from opstack
+ InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -4 );
+ } else if (pass>=0 && buf[compiledOfs-1] == (PPC_STW | R_TOP<<21 | R_OPSTACK<<16 | 0 ) && jused[instruction]==0 ) {
+ compiledOfs--;
+ if (!pass) {
+ tvm->instructionPointers[instruction] = compiledOfs * 4;
+ }
+ InstImm( PPC_LWZ, R_SECOND, R_OPSTACK, -4 ); // get value from opstack
+ InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -8 );
+ } else {
+ ltop(); // get value from opstack
+ InstImm( PPC_LWZ, R_SECOND, R_OPSTACK, -4 ); // get value from opstack
+ InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -8 );
+ }
+ rtopped = qfalse;
+#endif
+}
+
+static void spillOpStack(int depth)
+{
+ // Store out each register on the operand stack to it's correct location.
+ int i;
+
+ for(i = 0; i < depth; i++)
+ {
+ assert(opStackRegType[i]);
+ assert(opStackRegType[i] == 1);
+ switch(opStackRegType[i])
+ {
+ case 1: // Integer register
+ InstImm( "stw", PPC_STW, opStackIntRegisters[i], R_OPSTACK, i*4+4);
+ break;
+ case 2: // Float register
+ InstImm( "stfs", PPC_STFS, opStackFloatRegisters[i], R_OPSTACK, i*4+4);
+ break;
+ }
+ opStackRegType[i] = 0;
+ }
+}
+
+static void loadOpStack(int depth)
+{
+ // Back off operand stack pointer and reload all operands.
+// InstImm( "addi", PPC_ADDI, R_OPSTACK, R_OPSTACK, -(depth)*4 );
+
+ int i;
+
+ for(i = 0; i < depth; i++)
+ {
+ assert(opStackRegType[i] == 0);
+ // For now we're stuck reloading everything as an integer.
+ opStackLoadInstructionAddr[i] = &buf[compiledOfs];
+ InstImm( "lwz", PPC_LWZ, opStackIntRegisters[i], R_OPSTACK, i*4+4);
+ opStackRegType[i] = 1;
+ }
+}
+
+static void makeInteger(int depth)
+{
+ // This should really never be necessary...
+ assert(opStackRegType[depth] == 1);
+ //assert(opStackRegType[depth] == 2);
+ if(opStackRegType[depth] == 2)
+ {
+ unsigned instruction;
+ assert(opStackLoadInstructionAddr[depth]);
+
+ printf("patching float load at %p to int load\n",opStackLoadInstructionAddr[depth]);
+ // Repatch load instruction to use LFS instead of LWZ
+ instruction = *opStackLoadInstructionAddr[depth];
+ instruction &= ~PPC_LFSX;
+ instruction |= PPC_LWZX;
+ *opStackLoadInstructionAddr[depth] = instruction;
+ opStackLoadInstructionAddr[depth] = 0;
+ opStackRegType[depth] = 1;
+ #if 0
+ InstImm( "stfs", PPC_STFS, opStackFloatRegisters[depth], R_OPSTACK, depth*4+4);
+ // For XXX make sure we force enough NOPs to get the load into
+ // another dispatch group to avoid pipeline flush.
+ Inst( "ori", PPC_ORI, 0, 0, 0 );
+ Inst( "ori", PPC_ORI, 0, 0, 0 );
+ Inst( "ori", PPC_ORI, 0, 0, 0 );
+ Inst( "ori", PPC_ORI, 0, 0, 0 );
+ InstImm( "lwz", PPC_LWZ, opStackIntRegisters[depth], R_OPSTACK, depth*4+4);
+ opStackRegType[depth] = 1;
+ #endif
+ }
+}
+
+static void makeFloat(int depth)
+{
+ //assert(opStackRegType[depth] == 1);
+ if(opStackRegType[depth] == 1)
+ {
+ unsigned instruction;
+ unsigned destReg, aReg, bReg, imm;
+
+ if(opStackLoadInstructionAddr[depth])
+ {
+ // Repatch load instruction to use LFS instead of LWZ
+ instruction = *opStackLoadInstructionAddr[depth];
+ // Figure out if it's LWZ or LWZX
+ if((instruction & 0xfc000000) == PPC_LWZ)
+ {
+ //printf("patching LWZ at %p to LFS at depth %ld\n",opStackLoadInstructionAddr[depth],depth);
+ //printf("old instruction: %08lx\n",instruction);
+ // Extract registers
+ destReg = (instruction >> 21) & 31;
+ aReg = (instruction >> 16) & 31;
+ imm = instruction & 0xffff;
+
+ // Calculate correct FP register to use.
+ // THIS ASSUMES REGISTER USAGE FOR THE STACK IS n, n+1, n+2, etc!
+ //printf("old dest: %ld\n",destReg);
+ destReg = (destReg - opStackIntRegisters[0]) + opStackFloatRegisters[0];
+ instruction = PPC_LFS | ( destReg << 21 ) | ( aReg << 16 ) | imm ;
+ //printf("new dest: %ld\n",destReg);
+ //printf("new instruction: %08lx\n",instruction);
+ }
+ else
+ {
+ //printf("patching LWZX at %p to LFSX at depth %ld\n",opStackLoadInstructionAddr[depth],depth);
+ //printf("old instruction: %08lx\n",instruction);
+ // Extract registers
+ destReg = (instruction >> 21) & 31;
+ aReg = (instruction >> 16) & 31;
+ bReg = (instruction >> 11) & 31;
+ // Calculate correct FP register to use.
+ // THIS ASSUMES REGISTER USAGE FOR THE STACK IS n, n+1, n+2, etc!
+ //printf("old dest: %ld\n",destReg);
+ destReg = (destReg - opStackIntRegisters[0]) + opStackFloatRegisters[0];
+ instruction = PPC_LFSX | ( destReg << 21 ) | ( aReg << 16 ) | ( bReg << 11 ) ;
+ //printf("new dest: %ld\n",destReg);
+ //printf("new instruction: %08lx\n",instruction);
+ }
+ *opStackLoadInstructionAddr[depth] = instruction;
+ opStackLoadInstructionAddr[depth] = 0;
+ }
+ else
+ {
+ //printf("doing float constant load at %p for depth %ld\n",&buf[compiledOfs],depth);
+ // It was likely loaded as a constant so we have to save/load it. A more
+ // interesting implementation might be to generate code to do a "PC relative"
+ // load from the VM code region.
+ InstImm( "stw", PPC_STW, opStackIntRegisters[depth], R_OPSTACK, depth*4+4);
+ // For XXX make sure we force enough NOPs to get the load into
+ // another dispatch group to avoid pipeline flush.
+ Inst( "ori", PPC_ORI, 0, 0, 0 );
+ Inst( "ori", PPC_ORI, 0, 0, 0 );
+ Inst( "ori", PPC_ORI, 0, 0, 0 );
+ Inst( "ori", PPC_ORI, 0, 0, 0 );
+ InstImm( "lfs", PPC_LFS, opStackFloatRegisters[depth], R_OPSTACK, depth*4+4);
+ }
+ opStackRegType[depth] = 2;
+ }
+}
+
+// TJW: Unused
+#if 0
+static void fltop() {
+ if (rtopped == qfalse) {
+ InstImm( PPC_LFS, R_TOP, R_OPSTACK, 0 ); // get value from opstack
+ }
+}
+#endif
+
+#if 0
+static void fltopandsecond() {
+ InstImm( PPC_LFS, R_TOP, R_OPSTACK, 0 ); // get value from opstack
+ InstImm( PPC_LFS, R_SECOND, R_OPSTACK, -4 ); // get value from opstack
+ InstImm( PPC_ADDI, R_OPSTACK, R_OPSTACK, -8 );
+ rtopped = qfalse;
+ return;
+}
+#endif
+
+#define assertInteger(depth) assert(opStackRegType[depth] == 1)
+
+/*
+=================
+VM_Compile
+=================
+*/
+void VM_Compile( vm_t *vm, vmHeader_t *header ) {
+ int op;
+ int maxLength;
+ int v;
+ int i;
+ int opStackDepth;
+
+ int mainFunction;
+
+ // set up the into-to-float variables
+ ((int *)itofConvert)[0] = 0x43300000;
+ ((int *)itofConvert)[1] = 0x80000000;
+ ((int *)itofConvert)[2] = 0x43300000;
+
+ // allocate a very large temp buffer, we will shrink it later
+ maxLength = header->codeLength * 8;
+ buf = Z_Malloc( maxLength );
+ jused = Z_Malloc(header->instructionCount + 2);
+ Com_Memset(jused, 0, header->instructionCount+2);
+
+ // compile everything twice, so the second pass will have valid instruction
+ // pointers for branches
+ for ( pass = -1 ; pass < 2 ; pass++ ) {
+
+ // translate all instructions
+ pc = 0;
+ mainFunction = 0;
+ opStackDepth = 0;
+
+ pop0 = 343545;
+ pop1 = 2443545;
+ oc0 = -2343535;
+ oc1 = 24353454;
+ tvm = vm;
+ code = (byte *)header + header->codeOffset;
+ compiledOfs = 0;
+#ifndef __GNUC__
+ // metrowerks seems to require this header in front of functions
+ Emit4( (int)(buf+2) );
+ Emit4( 0 );
+#endif
+
+ for ( instruction = 0 ; instruction < header->instructionCount ; instruction++ ) {
+ if ( compiledOfs*4 > maxLength - 16 ) {
+ Com_Error( ERR_DROP, "VM_Compile: maxLength exceeded" );
+ }
+
+ op = code[ pc ];
+ if ( !pass ) {
+ vm->instructionPointers[ instruction ] = compiledOfs * 4;
+ }
+ pc++;
+ switch ( op ) {
+ case 0:
+ break;
+ case OP_BREAK:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08lx BREAK\n",instruction);
+ #endif
+ InstImmU( "addi", PPC_ADDI, R_TOP, 0, 0 );
+ InstImm( "lwz", PPC_LWZ, R_TOP, R_TOP, 0 ); // *(int *)0 to crash to debugger
+ break;
+ case OP_ENTER:
+ opStackDepth = 0;
+ v = Constant4();
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x ENTER\t%04x\n",instruction,v);
+ #endif
+ opStackRegType[opStackDepth] = 0;
+ mainFunction++;
+ if(mainFunction == 1)
+ {
+ // Main VM entry point is the first thing we compile, so save off operand stack
+ // registers here. This avoids issues with trying to trick the native compiler
+ // into doing it, and properly matches the PowerPC ABI
+ InstImm( "addi", PPC_ADDI, R_REAL_STACK, R_REAL_STACK, -OP_STACK_MAX_DEPTH*4 ); // sub R_STACK, R_STACK, imm
+ for(i = 0; i < OP_STACK_MAX_DEPTH; i++)
+ InstImm( "stw", PPC_STW, opStackIntRegisters[i], R_REAL_STACK, i*4);
+ }
+ InstImm( "addi", PPC_ADDI, R_STACK, R_STACK, -v ); // sub R_STACK, R_STACK, imm
+ break;
+ case OP_CONST:
+ v = Constant4();
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x CONST\t%08x\n",instruction,v);
+ #endif
+ opStackLoadInstructionAddr[opStackDepth] = 0;
+ if ( v < 32768 && v >= -32768 ) {
+ InstImmU( "addi", PPC_ADDI, opStackIntRegisters[opStackDepth], 0, v & 0xffff );
+ } else {
+ InstImmU( "addis", PPC_ADDIS, opStackIntRegisters[opStackDepth], 0, (v >> 16)&0xffff );
+ if ( v & 0xffff ) {
+ InstImmU( "ori", PPC_ORI, opStackIntRegisters[opStackDepth], opStackIntRegisters[opStackDepth], v & 0xffff );
+ }
+ }
+ opStackRegType[opStackDepth] = 1;
+ opStackDepth += 1;
+ if (code[pc] == OP_JUMP) {
+ jused[v] = 1;
+ }
+ break;
+ case OP_LOCAL:
+ oc1 = Constant4();
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x LOCAL\t%08x\n",instruction,oc1);
+ #endif
+ if (code[pc] == OP_LOAD4 || code[pc] == OP_LOAD2 || code[pc] == OP_LOAD1) {
+ oc1 &= vm->dataMask;
+ }
+ InstImm( "addi", PPC_ADDI, opStackIntRegisters[opStackDepth], R_STACK, oc1 );
+ opStackRegType[opStackDepth] = 1;
+ opStackLoadInstructionAddr[opStackDepth] = 0;
+ opStackDepth += 1;
+ break;
+ case OP_ARG:
+ v = Constant1();
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x ARG \t%08x\n",instruction,v);
+ #endif
+ InstImm( "addi", PPC_ADDI, R_EA, R_STACK, v ); // location to put it
+ if(opStackRegType[opStackDepth-1] == 1)
+ Inst( "stwx", PPC_STWX, opStackIntRegisters[opStackDepth-1], R_EA, R_MEMBASE );
+ else
+ Inst( "stfsx", PPC_STFSX, opStackFloatRegisters[opStackDepth-1], R_EA, R_MEMBASE );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackDepth -= 1;
+
+ break;
+ case OP_CALL:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x CALL\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assert(opStackDepth > 0);
+ Inst( "mflr", PPC_MFSPR, R_SECOND, 8, 0 ); // move from link register
+ InstImm( "stwu", PPC_STWU, R_SECOND, R_REAL_STACK, -16 ); // save off the old return address
+
+ // Spill operand stack registers.
+ spillOpStack(opStackDepth);
+
+ // We need to leave R_OPSTACK pointing to the top entry on the stack, which is the call address.
+ // It will be consumed (and R4 decremented) by the AsmCall code.
+ InstImm( "addi", PPC_ADDI, R_OPSTACK, R_OPSTACK, opStackDepth*4);
+
+ Inst( "mtctr", PPC_MTSPR, R_ASMCALL, 9, 0 ); // move to count register
+ Inst( "bctrl", PPC_BCCTR | 1, 20, 0, 0 ); // jump and link to the count register
+
+ // R4 now points to the top of the operand stack, which has the return value in it. We want to
+ // back off the pointer to point to the base of our local operand stack and then reload the stack.
+
+ InstImm("addi", PPC_ADDI, R_OPSTACK, R_OPSTACK, -opStackDepth*4);
+
+ // Reload operand stack.
+ loadOpStack(opStackDepth);
+
+ InstImm( "lwz", PPC_LWZ, R_SECOND, R_REAL_STACK, 0 ); // fetch the old return address
+ InstImm( "addi", PPC_ADDI, R_REAL_STACK, R_REAL_STACK, 16 );
+ Inst( "mtlr", PPC_MTSPR, R_SECOND, 8, 0 ); // move to link register
+ break;
+ case OP_PUSH:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x PUSH\n",instruction);
+ #endif
+ opStackRegType[opStackDepth] = 1; // Garbage int value.
+ opStackDepth += 1;
+ break;
+ case OP_POP:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x POP\n",instruction);
+ #endif
+ opStackDepth -= 1;
+ opStackRegType[opStackDepth] = 0; // ??
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ break;
+ case OP_LEAVE:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x LEAVE\n",instruction);
+ #endif
+ assert(opStackDepth == 1);
+ assert(opStackRegType[0] != 0);
+ // Save return value onto top of op stack. We also have to increment R_OPSTACK
+ switch(opStackRegType[0])
+ {
+ case 1: // Integer register
+ InstImm( "stw", PPC_STWU, opStackIntRegisters[0], R_OPSTACK, 4);
+ break;
+ case 2: // Float register
+ InstImm( "stfs", PPC_STFSU, opStackFloatRegisters[0], R_OPSTACK, 4);
+ break;
+ }
+ InstImm( "addi", PPC_ADDI, R_STACK, R_STACK, Constant4() ); // add R_STACK, R_STACK, imm
+ if(mainFunction == 1)
+ {
+ for(i = 0; i < OP_STACK_MAX_DEPTH; i++)
+ InstImm( "lwz", PPC_LWZ, opStackIntRegisters[i], R_REAL_STACK, i*4);
+ InstImm( "addi", PPC_ADDI, R_REAL_STACK, R_REAL_STACK, OP_STACK_MAX_DEPTH*4 );
+ }
+ opStackDepth--;
+ opStackRegType[opStackDepth] = 0;
+ opStackLoadInstructionAddr[opStackDepth] = 0;
+ Inst( "blr", PPC_BCLR, 20, 0, 0 ); // branch unconditionally to link register
+ break;
+ case OP_LOAD4:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x LOAD4\n",instruction);
+ #endif
+ // We should try to figure out whether to use LWZX or LFSX based
+ // on some kind of code analysis after subsequent passes. I think what
+ // we could do is store the compiled load instruction address along with
+ // the register type. When we hit the first mismatched operator, we go back
+ // and patch the load. Since LCC's operand stack should be at 0 depth by the
+ // time we hit a branch, this should work fairly well. FIXME FIXME FIXME.
+ assertInteger(opStackDepth-1);
+ opStackLoadInstructionAddr[opStackDepth-1] = &buf[ compiledOfs ];
+ Inst( "lwzx", PPC_LWZX, opStackIntRegisters[opStackDepth-1], opStackIntRegisters[opStackDepth-1], R_MEMBASE );// load from memory base
+ opStackRegType[opStackDepth-1] = 1;
+ break;
+ case OP_LOAD2:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x LOAD2\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ Inst( "lhzx", PPC_LHZX, opStackIntRegisters[opStackDepth-1], opStackIntRegisters[opStackDepth-1], R_MEMBASE );// load from memory base
+ opStackRegType[opStackDepth-1] = 1;
+ break;
+ case OP_LOAD1:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x LOAD1\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ Inst( "lbzx", PPC_LBZX, opStackIntRegisters[opStackDepth-1], opStackIntRegisters[opStackDepth-1], R_MEMBASE );// load from memory base
+ opStackRegType[opStackDepth-1] = 1;
+ break;
+ case OP_STORE4:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x STORE4\n",instruction);
+ #endif
+ assertInteger(opStackDepth-2);
+ if(opStackRegType[opStackDepth-1] == 1)
+ Inst( "stwx", PPC_STWX, opStackIntRegisters[opStackDepth-1],
+ opStackIntRegisters[opStackDepth-2], R_MEMBASE ); // store from memory base
+ else
+ Inst( "stfsx", PPC_STFSX, opStackFloatRegisters[opStackDepth-1],
+ opStackIntRegisters[opStackDepth-2], R_MEMBASE ); // store from memory base
+ opStackRegType[opStackDepth-1] = 0;
+ opStackRegType[opStackDepth-2] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-2] = 0;
+ opStackDepth -= 2;
+ break;
+ case OP_STORE2:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x STORE2\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "sthx", PPC_STHX, opStackIntRegisters[opStackDepth-1],
+ opStackIntRegisters[opStackDepth-2], R_MEMBASE ); // store from memory base
+ opStackRegType[opStackDepth-1] = 0;
+ opStackRegType[opStackDepth-2] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-2] = 0;
+ opStackDepth -= 2;
+ break;
+ case OP_STORE1:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x STORE1\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "stbx", PPC_STBX, opStackIntRegisters[opStackDepth-1],
+ opStackIntRegisters[opStackDepth-2], R_MEMBASE ); // store from memory base
+ opStackRegType[opStackDepth-1] = 0;
+ opStackRegType[opStackDepth-2] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-2] = 0;
+ opStackDepth -= 2;
+ break;
+
+ case OP_EQ:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x EQ\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "cmp", PPC_CMP, 0, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackRegType[opStackDepth-2] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-2] = 0;
+ opStackDepth -= 2;
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( "bc", PPC_BC, 4, 2, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4("b", PPC_B | (v&0x3ffffff) );
+ break;
+ case OP_NE:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x NE\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "cmp", PPC_CMP, 0, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackRegType[opStackDepth-2] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-2] = 0;
+ opStackDepth -= 2;
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( "bc", PPC_BC, 12, 2, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4("b", PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( "bc", PPC_BC, 4, 2, v );
+
+ break;
+ case OP_LTI:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x LTI\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "cmp", PPC_CMP, 0, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackRegType[opStackDepth-2] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-2] = 0;
+ opStackDepth -= 2;
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( "bc", PPC_BC, 4, 0, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4("b", PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( "bc", PPC_BC, 12, 0, v );
+ break;
+ case OP_LEI:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x LEI\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "cmp", PPC_CMP, 0, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackRegType[opStackDepth-2] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-2] = 0;
+ opStackDepth -= 2;
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( "bc", PPC_BC, 12, 1, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4("b", PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( "bc", PPC_BC, 4, 1, v );
+ break;
+ case OP_GTI:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x GTI\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "cmp", PPC_CMP, 0, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackRegType[opStackDepth-2] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-2] = 0;
+ opStackDepth -= 2;
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( "bc", PPC_BC, 4, 1, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4("b", PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( "bc", PPC_BC, 12, 1, v );
+ break;
+ case OP_GEI:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x GEI\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "cmp", PPC_CMP, 0, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackRegType[opStackDepth-2] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-2] = 0;
+ opStackDepth -= 2;
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( "bc", PPC_BC, 12, 0, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4("b", PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( "bc", PPC_BC, 4, 0, v );
+ break;
+ case OP_LTU:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x LTU\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "cmp", PPC_CMP, 0, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackRegType[opStackDepth-2] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-2] = 0;
+ opStackDepth -= 2;
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( "bc", PPC_BC, 4, 0, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4("b", PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( "bc", PPC_BC, 12, 0, v );
+ break;
+ case OP_LEU:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x LEU\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "cmp", PPC_CMP, 0, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackRegType[opStackDepth-2] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-2] = 0;
+ opStackDepth -= 2;
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( "bc", PPC_BC, 12, 1, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4("b", PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( "bc", PPC_BC, 4, 1, v );
+ break;
+ case OP_GTU:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x GTU\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "cmp", PPC_CMP, 0, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackRegType[opStackDepth-2] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-2] = 0;
+ opStackDepth -= 2;
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( "bc", PPC_BC, 4, 1, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4("b", PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( "bc", PPC_BC, 12, 1, v );
+ break;
+ case OP_GEU:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x GEU\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "cmp", PPC_CMP, 0, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackRegType[opStackDepth-2] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-2] = 0;
+ opStackDepth -= 2;
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( "bc", PPC_BC, 12, 0, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4("b", PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( "bc", PPC_BC, 4, 0, v );
+ break;
+
+ case OP_EQF:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x EQF\n",instruction);
+ #endif
+ makeFloat(opStackDepth-1);
+ makeFloat(opStackDepth-2);
+ Inst( "fcmpu", PPC_FCMPU, 0, opStackFloatRegisters[opStackDepth-2], opStackFloatRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackRegType[opStackDepth-2] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-2] = 0;
+ opStackDepth -= 2;
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( "bc", PPC_BC, 4, 2, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4("b", PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( "bc", PPC_BC, 12, 2, v );
+ break;
+ case OP_NEF:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x NEF\n",instruction);
+ #endif
+ makeFloat(opStackDepth-1);
+ makeFloat(opStackDepth-2);
+ Inst( "fcmpu", PPC_FCMPU, 0, opStackFloatRegisters[opStackDepth-2], opStackFloatRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackRegType[opStackDepth-2] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-2] = 0;
+ opStackDepth -= 2;
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( "bc", PPC_BC, 12, 2, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4("b", PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( "bc", PPC_BC, 4, 2, v );
+ break;
+ case OP_LTF:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x LTF\n",instruction);
+ #endif
+ makeFloat(opStackDepth-1);
+ makeFloat(opStackDepth-2);
+ Inst( "fcmpu", PPC_FCMPU, 0, opStackFloatRegisters[opStackDepth-2], opStackFloatRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackRegType[opStackDepth-2] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-2] = 0;
+ opStackDepth -= 2;
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( "bc", PPC_BC, 4, 0, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4("b", PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( "bc", PPC_BC, 12, 0, v );
+ break;
+ case OP_LEF:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x LEF\n",instruction);
+ #endif
+ makeFloat(opStackDepth-1);
+ makeFloat(opStackDepth-2);
+ Inst( "fcmpu", PPC_FCMPU, 0, opStackFloatRegisters[opStackDepth-2], opStackFloatRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackRegType[opStackDepth-2] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-2] = 0;
+ opStackDepth -= 2;
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( "bc", PPC_BC, 12, 1, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4("b", PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( "bc", PPC_BC, 4, 1, v );
+ break;
+ case OP_GTF:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x GTF\n",instruction);
+ #endif
+ makeFloat(opStackDepth-1);
+ makeFloat(opStackDepth-2);
+ Inst( "fcmpu", PPC_FCMPU, 0, opStackFloatRegisters[opStackDepth-2], opStackFloatRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackRegType[opStackDepth-2] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-2] = 0;
+ opStackDepth -= 2;
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( "bc", PPC_BC, 4, 1, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4("b", PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( "bc", PPC_BC, 12, 1, v );
+ break;
+ case OP_GEF:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x GEF\n",instruction);
+ #endif
+ makeFloat(opStackDepth-1);
+ makeFloat(opStackDepth-2);
+ Inst( "fcmpu", PPC_FCMPU, 0, opStackFloatRegisters[opStackDepth-2], opStackFloatRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackRegType[opStackDepth-2] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-2] = 0;
+ opStackDepth -= 2;
+ i = Constant4();
+ jused[i] = 1;
+ InstImm( "bc", PPC_BC, 12, 0, 8 );
+ if ( pass==1 ) {
+ v = vm->instructionPointers[ i ] - (int)&buf[compiledOfs];
+ } else {
+ v = 0;
+ }
+ Emit4("b", PPC_B | (unsigned int)(v&0x3ffffff) );
+// InstImm( "bc", PPC_BC, 4, 0, v );
+ break;
+
+ case OP_NEGI:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x NEGI\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ InstImm( "subfic", PPC_SUBFIC, opStackIntRegisters[opStackDepth-1], opStackIntRegisters[opStackDepth-1], 0 );
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ break;
+ case OP_ADD:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x ADD\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "add", PPC_ADD, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-1], opStackIntRegisters[opStackDepth-2] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackDepth -= 1;
+ break;
+ case OP_SUB:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x SUB\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "subf", PPC_SUBF, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-1], opStackIntRegisters[opStackDepth-2] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackDepth -= 1;
+ break;
+ case OP_DIVI:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x DIVI\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "divw", PPC_DIVW, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackDepth -= 1;
+ break;
+ case OP_DIVU:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x DIVU\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "divwu", PPC_DIVWU, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackDepth -= 1;
+ break;
+ case OP_MODI:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x MODI\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "divw", PPC_DIVW, R_EA, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-1] );
+ Inst( "mullw", PPC_MULLW, R_EA, opStackIntRegisters[opStackDepth-1], R_EA );
+ Inst( "subf", PPC_SUBF, opStackIntRegisters[opStackDepth-2], R_EA, opStackIntRegisters[opStackDepth-2] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackDepth -= 1;
+ break;
+ case OP_MODU:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x MODU\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "divwu", PPC_DIVWU, R_EA, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-1] );
+ Inst( "mullw", PPC_MULLW, R_EA, opStackIntRegisters[opStackDepth-1], R_EA );
+ Inst( "subf", PPC_SUBF, opStackIntRegisters[opStackDepth-2], R_EA, opStackIntRegisters[opStackDepth-2] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackDepth -= 1;
+ break;
+ case OP_MULI:
+ case OP_MULU:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x MULI\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "mullw", PPC_MULLW, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-1], opStackIntRegisters[opStackDepth-2] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackDepth -= 1;
+ break;
+ case OP_BAND:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x BAND\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "and", PPC_AND, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackDepth -= 1;
+ break;
+ case OP_BOR:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x BOR\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "or", PPC_OR, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackDepth -= 1;
+ break;
+ case OP_BXOR:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x BXOR\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "xor", PPC_XOR, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackDepth -= 1;
+ break;
+ case OP_BCOM:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x BCOM\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ Inst( "nor", PPC_NOR, opStackIntRegisters[opStackDepth-1], opStackIntRegisters[opStackDepth-1], opStackIntRegisters[opStackDepth-1] );
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ break;
+ case OP_LSH:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x LSH\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "slw", PPC_SLW, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackDepth -= 1;
+ break;
+ case OP_RSHI:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x RSHI\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "sraw", PPC_SRAW, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackDepth -= 1;
+ break;
+ case OP_RSHU:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x RSHU\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ Inst( "srw", PPC_SRW, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackDepth -= 1;
+ break;
+
+ case OP_NEGF:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x NEGF\n",instruction);
+ #endif
+ makeFloat(opStackDepth-1);
+ Inst( "fneg", PPC_FNEG, opStackFloatRegisters[opStackDepth-1], 0, opStackFloatRegisters[opStackDepth-1] );
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ break;
+ case OP_ADDF:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x ADDF\n",instruction);
+ #endif
+ makeFloat(opStackDepth-1);
+ makeFloat(opStackDepth-2);
+ Inst( "fadds", PPC_FADDS, opStackFloatRegisters[opStackDepth-2], opStackFloatRegisters[opStackDepth-2], opStackFloatRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackDepth -= 1;
+ break;
+ case OP_SUBF:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x SUBF\n",instruction);
+ #endif
+ makeFloat(opStackDepth-1);
+ makeFloat(opStackDepth-2);
+ Inst( "fsubs", PPC_FSUBS, opStackFloatRegisters[opStackDepth-2], opStackFloatRegisters[opStackDepth-2], opStackFloatRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackDepth -= 1;
+ break;
+ case OP_DIVF:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x DIVF\n",instruction);
+ #endif
+ makeFloat(opStackDepth-1);
+ makeFloat(opStackDepth-2);
+ Inst( "fdivs", PPC_FDIVS, opStackFloatRegisters[opStackDepth-2], opStackFloatRegisters[opStackDepth-2], opStackFloatRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackDepth -= 1;
+ break;
+ case OP_MULF:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x MULF\n",instruction);
+ #endif
+ makeFloat(opStackDepth-1);
+ makeFloat(opStackDepth-2);
+ Inst4( "fmuls", PPC_FMULS, opStackFloatRegisters[opStackDepth-2], opStackFloatRegisters[opStackDepth-2], 0, opStackFloatRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackDepth -= 1;
+ break;
+
+ case OP_CVIF:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x CVIF\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ //makeInteger(opStackDepth-1);
+ v = (int)&itofConvert;
+ InstImmU( "addis", PPC_ADDIS, R_EA, 0, (v >> 16)&0xffff );
+ InstImmU( "ori", PPC_ORI, R_EA, R_EA, v & 0xffff );
+ InstImmU( "xoris", PPC_XORIS, opStackIntRegisters[opStackDepth-1], opStackIntRegisters[opStackDepth-1], 0x8000 );
+ InstImm( "stw", PPC_STW, opStackIntRegisters[opStackDepth-1], R_EA, 12 );
+ InstImm( "lfd", PPC_LFD, opStackFloatRegisters[opStackDepth-1], R_EA, 0 );
+ Inst( "ori", PPC_ORI, 0, 0, 0);
+ Inst( "ori", PPC_ORI, 0, 0, 0);
+ Inst( "ori", PPC_ORI, 0, 0, 0);
+ InstImm( "lfd", PPC_LFD, 13, R_EA, 8 );
+ Inst( "fsub", PPC_FSUB, opStackFloatRegisters[opStackDepth-1], 13, opStackFloatRegisters[opStackDepth-1] );
+ opStackRegType[opStackDepth-1] = 2;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ // Inst( PPC_FRSP, R_TOP, 0, R_TOP );
+ break;
+ case OP_CVFI:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x CVFI\n",instruction);
+ #endif
+ makeFloat(opStackDepth-1);
+
+ InstImm( "addi", PPC_ADDI, R_OPSTACK, R_OPSTACK, opStackDepth*4);
+
+ Inst( "fctiwz", PPC_FCTIWZ, opStackFloatRegisters[opStackDepth-1], 0, opStackFloatRegisters[opStackDepth-1] );
+ Inst( "stfiwx", PPC_STFIWX, opStackFloatRegisters[opStackDepth-1], 0, R_OPSTACK ); // save value to opstack (dummy area now)
+ Inst( "ori", PPC_ORI, 0, 0, 0);
+ Inst( "ori", PPC_ORI, 0, 0, 0);
+ Inst( "ori", PPC_ORI, 0, 0, 0);
+ Inst( "ori", PPC_ORI, 0, 0, 0);
+ InstImm( "lwz", PPC_LWZ, opStackIntRegisters[opStackDepth-1], R_OPSTACK, 0 );
+
+ InstImm( "addi", PPC_ADDI, R_OPSTACK, R_OPSTACK, -opStackDepth*4);
+
+ opStackRegType[opStackDepth-1] = 1;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ break;
+ case OP_SEX8:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x SEX8\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ Inst( "extsb", PPC_EXTSB, opStackIntRegisters[opStackDepth-1], opStackIntRegisters[opStackDepth-1], 0 );
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ break;
+ case OP_SEX16:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x SEX16\n",instruction);
+ #endif
+ assertInteger(opStackDepth-1);
+ Inst( "extsh", PPC_EXTSH, opStackIntRegisters[opStackDepth-1], opStackIntRegisters[opStackDepth-1], 0 );
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ break;
+
+ case OP_BLOCK_COPY:
+ v = Constant4() >> 2;
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x BLOCK_COPY\t%08lx\n",instruction,v<<2);
+ #endif
+ assert(opStackDepth >= 2);
+ assertInteger(opStackDepth-1);
+ assertInteger(opStackDepth-2);
+ InstImmU( "addi", PPC_ADDI, R_EA, 0, v ); // count
+ // FIXME: range check
+ Inst( "mtctr", PPC_MTSPR, R_EA, 9, 0 ); // move to count register
+
+ Inst( "add", PPC_ADD, opStackIntRegisters[opStackDepth-1], opStackIntRegisters[opStackDepth-1], R_MEMBASE );
+ InstImm( "addi", PPC_ADDI, opStackIntRegisters[opStackDepth-1], opStackIntRegisters[opStackDepth-1], -4 );
+ Inst( "add", PPC_ADD, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-2], R_MEMBASE );
+ InstImm( "addi", PPC_ADDI, opStackIntRegisters[opStackDepth-2], opStackIntRegisters[opStackDepth-2], -4 );
+
+ InstImm( "lwzu", PPC_LWZU, R_EA, opStackIntRegisters[opStackDepth-1], 4 ); // source
+ InstImm( "stwu", PPC_STWU, R_EA, opStackIntRegisters[opStackDepth-2], 4 ); // dest
+ Inst( "b", PPC_BC | 0xfff8 , 16, 0, 0 ); // loop
+ opStackRegType[opStackDepth-1] = 0;
+ opStackRegType[opStackDepth-2] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-2] = 0;
+ opStackDepth -= 2;
+ break;
+
+ case OP_JUMP:
+ #if DEBUG_VM
+ if(pass == 1)
+ printf("%08x JUMP\n",instruction);
+ #endif
+ assert(opStackDepth == 1);
+ assertInteger(opStackDepth-1);
+
+ Inst( "rlwinm", PPC_RLWINM | ( 29 << 1 ), opStackIntRegisters[opStackDepth-1], opStackIntRegisters[opStackDepth-1], 2 );
+ // FIXME: range check
+ Inst( "lwzx", PPC_LWZX, opStackIntRegisters[opStackDepth-1], opStackIntRegisters[opStackDepth-1], R_INSTRUCTIONS );
+ Inst( "mtctr", PPC_MTSPR, opStackIntRegisters[opStackDepth-1], 9, 0 ); // move to count register
+ Inst( "bctr", PPC_BCCTR, 20, 0, 0 ); // jump to the count register
+ opStackRegType[opStackDepth-1] = 0;
+ opStackLoadInstructionAddr[opStackDepth-1] = 0;
+ opStackDepth -= 1;
+ break;
+ default:
+ Com_Error( ERR_DROP, "VM_CompilePPC: bad opcode %i at instruction %i, offset %i", op, instruction, pc );
+ }
+ pop0 = pop1;
+ pop1 = op;
+ assert(opStackDepth >= 0);
+ assert(opStackDepth < OP_STACK_MAX_DEPTH);
+
+ //printf("%4d\t%s\n",opStackDepth,opnames[op]);
+ }
+
+ Com_Printf( "VM file %s pass %d compiled to %i bytes of code\n", vm->name, (pass+1), compiledOfs*4 );
+
+ if ( pass == 0 ) {
+ // copy to an exact size buffer on the hunk
+ vm->codeLength = compiledOfs * 4;
+ vm->codeBase = Hunk_Alloc( vm->codeLength, h_low );
+ Com_Memcpy( vm->codeBase, buf, vm->codeLength );
+
+ //printf("codeBase: %p\n",vm->codeBase);
+
+ Z_Free( buf );
+
+ // offset all the instruction pointers for the new location
+ for ( i = 0 ; i < header->instructionCount ; i++ ) {
+ vm->instructionPointers[i] += (int)vm->codeBase;
+ //printf("%08x %08lx\n",i,vm->instructionPointers[i]);
+ }
+
+ // go back over it in place now to fixup reletive jump targets
+ buf = (unsigned *)vm->codeBase;
+ }
+ }
+ if(0)
+ {
+ char buf[256];
+ printf("wait..\n");
+ gets(buf);
+ }
+ Z_Free( jused );
+}
+
+/*
+==============
+VM_CallCompiled
+
+This function is called directly by the generated code
+==============
+*/
+int VM_CallCompiled( vm_t *vm, int *args ) {
+ int stack[1024];
+ int programStack;
+ int stackOnEntry;
+ byte *image;
+
+ currentVM = vm;
+
+ //printf("VM_CallCompiled: %p %08lx %08lx %08lx\n",
+ // vm, args[0],args[1],args[2]);
+
+ // interpret the code
+ vm->currentlyInterpreting = qtrue;
+
+ // we might be called recursively, so this might not be the very top
+ programStack = vm->programStack;
+ stackOnEntry = programStack;
+ image = vm->dataBase;
+
+ // set up the stack frame
+ programStack -= 48;
+
+ *(int *)&image[ programStack + 44] = args[9];
+ *(int *)&image[ programStack + 40] = args[8];
+ *(int *)&image[ programStack + 36] = args[7];
+ *(int *)&image[ programStack + 32] = args[6];
+ *(int *)&image[ programStack + 28] = args[5];
+ *(int *)&image[ programStack + 24] = args[4];
+ *(int *)&image[ programStack + 20] = args[3];
+ *(int *)&image[ programStack + 16] = args[2];
+ *(int *)&image[ programStack + 12] = args[1];
+ *(int *)&image[ programStack + 8 ] = args[0];
+ *(int *)&image[ programStack + 4 ] = 0; // return stack
+ *(int *)&image[ programStack ] = -1; // will terminate the loop on return
+
+ // Cheesy... manually save registers used by VM call...
+ // off we go into generated code...
+ // the PPC calling standard says the parms will all go into R3 - R11, so
+ // no special asm code is needed here
+#ifdef __GNUC__
+ ((void(*)(int, int, int, int, int, int, int, int))(vm->codeBase))(
+ programStack, (int)&stack,
+ (int)image, vm->dataMask, (int)&AsmCall,
+ (int)vm->instructionPointers, vm->instructionPointersLength,
+ (int)vm );
+#else
+ ((void(*)(int, int, int, int, int, int, int, int))(vm->codeBase))(
+ programStack, (int)&stack,
+ (int)image, vm->dataMask, *(int *)&AsmCall /* skip function pointer header */,
+ (int)vm->instructionPointers, vm->instructionPointersLength,
+ (int)vm );
+#endif
+ vm->programStack = stackOnEntry;
+
+ vm->currentlyInterpreting = qfalse;
+
+ return stack[1];
+}
+
+
+/*
+==================
+AsmCall
+
+Put this at end of file because gcc messes up debug line numbers
+==================
+*/
+#ifdef __GNUC__
+
+void AsmCall( void ) {
+asm (
+ // pop off the destination instruction
+" lwz r12,0(r4) \n" // RG_TOP, 0(RG_OPSTACK)
+" addi r4,r4,-4 \n" // RG_OPSTACK, RG_OPSTACK, -4 \n"
+
+ // see if it is a system trap
+" cmpwi r12,0 \n" // RG_TOP, 0 \n"
+" bc 12,0, systemTrap \n"
+
+ // calling another VM function, so lookup in instructionPointers
+" slwi r12,r12,2 \n" // RG_TOP,RG_TOP,2
+ // FIXME: range check
+" lwzx r12, r8, r12 \n" // RG_TOP, RG_INSTRUCTIONS(RG_TOP)
+" mtctr r12 \n" // RG_TOP
+);
+
+#if defined(MACOS_X) && defined(__OPTIMIZE__)
+ // On Mac OS X, gcc doesn't push a frame when we are optimized, so trying to tear it down results in grave disorder.
+#warning Mac OS X optimization on, not popping GCC AsmCall frame
+#else
+ // Mac OS X Server and unoptimized compiles include a GCC AsmCall frame
+ asm (
+" lwz r1,0(r1) \n" // pop off the GCC AsmCall frame
+" lmw r30,-8(r1) \n"
+);
+#endif
+
+asm (
+" bcctr 20,0 \n" // when it hits a leave, it will branch to the current link register
+
+ // calling a system trap
+"systemTrap: \n"
+ // convert to positive system call number
+" subfic r12,r12,-1 \n"
+
+ // save all our registers, including the current link register
+" mflr r13 \n" // RG_SECOND // copy off our link register
+" addi r1,r1,-92 \n" // required 24 byets of linkage, 32 bytes of parameter, plus our saves
+" stw r3,56(r1) \n" // RG_STACK, -36(REAL_STACK)
+" stw r4,60(r1) \n" // RG_OPSTACK, 4(RG_REAL_STACK)
+" stw r5,64(r1) \n" // RG_MEMBASE, 8(RG_REAL_STACK)
+" stw r6,68(r1) \n" // RG_MEMMASK, 12(RG_REAL_STACK)
+" stw r7,72(r1) \n" // RG_ASMCALL, 16(RG_REAL_STACK)
+" stw r8,76(r1) \n" // RG_INSTRUCTIONS, 20(RG_REAL_STACK)
+" stw r9,80(r1) \n" // RG_NUM_INSTRUCTIONS, 24(RG_REAL_STACK)
+" stw r10,84(r1) \n" // RG_VM, 28(RG_REAL_STACK)
+" stw r13,88(r1) \n" // RG_SECOND, 32(RG_REAL_STACK) // link register
+
+ // save the vm stack position to allow recursive VM entry
+" addi r13,r3,-4 \n" // RG_TOP, RG_STACK, -4
+" stw r13,0(r10) \n" //RG_TOP, VM_OFFSET_PROGRAM_STACK(RG_VM)
+
+ // save the system call number as the 0th parameter
+" add r3,r3,r5 \n" // r3, RG_STACK, RG_MEMBASE // r3 is the first parameter to vm->systemCalls
+" stwu r12,4(r3) \n" // RG_TOP, 4(r3)
+
+ // make the system call with the address of all the VM parms as a parameter
+ // vm->systemCalls( &parms )
+" lwz r12,4(r10) \n" // RG_TOP, VM_OFFSET_SYSTEM_CALL(RG_VM)
+" mtctr r12 \n" // RG_TOP
+" bcctrl 20,0 \n"
+" mr r12,r3 \n" // RG_TOP, r3
+
+ // pop our saved registers
+" lwz r3,56(r1) \n" // RG_STACK, 0(RG_REAL_STACK)
+" lwz r4,60(r1) \n" // RG_OPSTACK, 4(RG_REAL_STACK)
+" lwz r5,64(r1) \n" // RG_MEMBASE, 8(RG_REAL_STACK)
+" lwz r6,68(r1) \n" // RG_MEMMASK, 12(RG_REAL_STACK)
+" lwz r7,72(r1) \n" // RG_ASMCALL, 16(RG_REAL_STACK)
+" lwz r8,76(r1) \n" // RG_INSTRUCTIONS, 20(RG_REAL_STACK)
+" lwz r9,80(r1) \n" // RG_NUM_INSTRUCTIONS, 24(RG_REAL_STACK)
+" lwz r10,84(r1) \n" // RG_VM, 28(RG_REAL_STACK)
+" lwz r13,88(r1) \n" // RG_SECOND, 32(RG_REAL_STACK)
+" addi r1,r1,92 \n" // RG_REAL_STACK, RG_REAL_STACK, 36
+
+ // restore the old link register
+" mtlr r13 \n" // RG_SECOND
+
+ // save off the return value
+" stwu r12,4(r4) \n" // RG_TOP, 0(RG_OPSTACK)
+
+ // GCC adds its own prolog / epliog code
+ );
+}
+#else
+
+// codewarrior version
+
+void asm AsmCall( void ) {
+
+ // pop off the destination instruction
+
+ lwz r12,0(r4) // RG_TOP, 0(RG_OPSTACK)
+
+ addi r4,r4,-4 // RG_OPSTACK, RG_OPSTACK, -4
+
+
+
+ // see if it is a system trap
+
+ cmpwi r12,0 // RG_TOP, 0
+
+ bc 12,0, systemTrap
+
+
+
+ // calling another VM function, so lookup in instructionPointers
+
+ slwi r12,r12,2 // RG_TOP,RG_TOP,2
+
+ // FIXME: range check
+
+ lwzx r12, r8, r12 // RG_TOP, RG_INSTRUCTIONS(RG_TOP)
+
+ mtctr r12 // RG_TOP
+
+
+
+ bcctr 20,0 // when it hits a leave, it will branch to the current link register
+
+
+
+ // calling a system trap
+
+systemTrap:
+
+ // convert to positive system call number
+
+ subfic r12,r12,-1
+
+
+
+ // save all our registers, including the current link register
+
+ mflr r13 // RG_SECOND // copy off our link register
+
+ addi r1,r1,-92 // required 24 byets of linkage, 32 bytes of parameter, plus our saves
+
+ stw r3,56(r1) // RG_STACK, -36(REAL_STACK)
+
+ stw r4,60(r1) // RG_OPSTACK, 4(RG_REAL_STACK)
+
+ stw r5,64(r1) // RG_MEMBASE, 8(RG_REAL_STACK)
+
+ stw r6,68(r1) // RG_MEMMASK, 12(RG_REAL_STACK)
+
+ stw r7,72(r1) // RG_ASMCALL, 16(RG_REAL_STACK)
+
+ stw r8,76(r1) // RG_INSTRUCTIONS, 20(RG_REAL_STACK)
+
+ stw r9,80(r1) // RG_NUM_INSTRUCTIONS, 24(RG_REAL_STACK)
+
+ stw r10,84(r1) // RG_VM, 28(RG_REAL_STACK)
+
+ stw r13,88(r1) // RG_SECOND, 32(RG_REAL_STACK) // link register
+
+
+
+ // save the vm stack position to allow recursive VM entry
+
+ addi r13,r3,-4 // RG_TOP, RG_STACK, -4
+
+ stw r13,0(r10) //RG_TOP, VM_OFFSET_PROGRAM_STACK(RG_VM)
+
+
+
+ // save the system call number as the 0th parameter
+
+ add r3,r3,r5 // r3, RG_STACK, RG_MEMBASE // r3 is the first parameter to vm->systemCalls
+
+ stwu r12,4(r3) // RG_TOP, 4(r3)
+
+
+
+ // make the system call with the address of all the VM parms as a parameter
+
+ // vm->systemCalls( &parms )
+
+ lwz r12,4(r10) // RG_TOP, VM_OFFSET_SYSTEM_CALL(RG_VM)
+
+
+
+ // perform macos cross fragment fixup crap
+
+ lwz r9,0(r12)
+
+ stw r2,52(r1) // save old TOC
+
+ lwz r2,4(r12)
+
+
+
+ mtctr r9 // RG_TOP
+
+ bcctrl 20,0
+
+
+
+ lwz r2,52(r1) // restore TOC
+
+
+
+ mr r12,r3 // RG_TOP, r3
+
+
+
+ // pop our saved registers
+
+ lwz r3,56(r1) // RG_STACK, 0(RG_REAL_STACK)
+
+ lwz r4,60(r1) // RG_OPSTACK, 4(RG_REAL_STACK)
+
+ lwz r5,64(r1) // RG_MEMBASE, 8(RG_REAL_STACK)
+
+ lwz r6,68(r1) // RG_MEMMASK, 12(RG_REAL_STACK)
+
+ lwz r7,72(r1) // RG_ASMCALL, 16(RG_REAL_STACK)
+
+ lwz r8,76(r1) // RG_INSTRUCTIONS, 20(RG_REAL_STACK)
+
+ lwz r9,80(r1) // RG_NUM_INSTRUCTIONS, 24(RG_REAL_STACK)
+
+ lwz r10,84(r1) // RG_VM, 28(RG_REAL_STACK)
+
+ lwz r13,88(r1) // RG_SECOND, 32(RG_REAL_STACK)
+
+ addi r1,r1,92 // RG_REAL_STACK, RG_REAL_STACK, 36
+
+
+
+ // restore the old link register
+
+ mtlr r13 // RG_SECOND
+
+
+
+ // save off the return value
+
+ stwu r12,4(r4) // RG_TOP, 0(RG_OPSTACK)
+
+
+
+ blr
+
+}
+
+
+
+
+#endif
diff --git a/code/qcommon/vm_x86.c b/code/qcommon/vm_x86.c
new file mode 100755
index 0000000..92a812e
--- /dev/null
+++ b/code/qcommon/vm_x86.c
@@ -0,0 +1,1196 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// vm_x86.c -- load time compiler and execution environment for x86
+
+#include "vm_local.h"
+
+#ifdef __FreeBSD__ // rb0101023
+#include <sys/types.h>
+#endif
+
+#ifndef _WIN32
+#include <sys/mman.h> // for PROT_ stuff
+#endif
+
+/*
+
+ eax scratch
+ ebx scratch
+ ecx scratch (required for shifts)
+ edx scratch (required for divisions)
+ esi program stack
+ edi opstack
+
+*/
+
+// TTimo: initialised the statics, this fixes a crash when entering a compiled VM
+static byte *buf = NULL;
+static byte *jused = NULL;
+static int compiledOfs = 0;
+static byte *code = NULL;
+static int pc = 0;
+
+static int *instructionPointers = NULL;
+
+#define FTOL_PTR
+
+#ifdef _WIN32
+
+#if defined( FTOL_PTR )
+int _ftol( float );
+static int ftolPtr = (int)_ftol;
+#endif
+
+void AsmCall( void );
+static int asmCallPtr = (int)AsmCall;
+
+#else // _WIN32
+
+#if defined( FTOL_PTR )
+// bk001213 - BEWARE: does not work! UI menu etc. broken - stack!
+// bk001119 - added: int gftol( float x ) { return (int)x; }
+
+int qftol( void ); // bk001213 - label, see unix/ftol.nasm
+int qftol027F( void ); // bk001215 - fixed FPU control variants
+int qftol037F( void );
+int qftol0E7F( void ); // bk010102 - fixed bogus bits (duh)
+int qftol0F7F( void );
+
+
+static int ftolPtr = (int)qftol0F7F;
+#endif // FTOL_PTR
+
+void doAsmCall( void );
+static int asmCallPtr = (int)doAsmCall;
+#endif // !_WIN32
+
+
+static int callMask = 0; // bk001213 - init
+
+static int instruction, pass;
+static int lastConst = 0;
+static int oc0, oc1, pop0, pop1;
+
+typedef enum
+{
+ LAST_COMMAND_NONE = 0,
+ LAST_COMMAND_MOV_EDI_EAX,
+ LAST_COMMAND_SUB_DI_4,
+ LAST_COMMAND_SUB_DI_8,
+} ELastCommand;
+
+static ELastCommand LastCommand;
+
+/*
+=================
+AsmCall
+=================
+*/
+#ifdef _WIN32
+__declspec( naked ) void AsmCall( void ) {
+int programStack;
+int *opStack;
+int syscallNum;
+vm_t* savedVM;
+
+__asm {
+ mov eax, dword ptr [edi]
+ sub edi, 4
+ or eax,eax
+ jl systemCall
+ // calling another vm function
+ shl eax,2
+ add eax, dword ptr [instructionPointers]
+ call dword ptr [eax]
+ mov eax, dword ptr [edi]
+ and eax, [callMask]
+ ret
+systemCall:
+
+ // convert negative num to system call number
+ // and store right before the first arg
+ neg eax
+ dec eax
+
+ push ebp
+ mov ebp, esp
+ sub esp, __LOCAL_SIZE
+
+ mov dword ptr syscallNum, eax // so C code can get at it
+ mov dword ptr programStack, esi // so C code can get at it
+ mov dword ptr opStack, edi
+
+ push ecx
+ push esi // we may call recursively, so the
+ push edi // statics aren't guaranteed to be around
+}
+
+ savedVM = currentVM;
+
+ // save the stack to allow recursive VM entry
+ currentVM->programStack = programStack - 4;
+ *(int *)((byte *)currentVM->dataBase + programStack + 4) = syscallNum;
+//VM_LogSyscalls( (int *)((byte *)currentVM->dataBase + programStack + 4) );
+ *(opStack+1) = currentVM->systemCall( (int *)((byte *)currentVM->dataBase + programStack + 4) );
+
+ currentVM = savedVM;
+
+_asm {
+ pop edi
+ pop esi
+ pop ecx
+ add edi, 4 // we added the return value
+
+ mov esp, ebp
+ pop ebp
+
+ ret
+}
+
+}
+
+#else //!_WIN32
+
+static int callProgramStack;
+static int *callOpStack;
+static int callSyscallNum;
+
+void callAsmCall(void)
+{
+ vm_t *savedVM;
+ int *callOpStack2;
+
+ savedVM = currentVM;
+ callOpStack2 = callOpStack;
+
+ // save the stack to allow recursive VM entry
+ currentVM->programStack = callProgramStack - 4;
+ *(int *)((byte *)currentVM->dataBase + callProgramStack + 4) = callSyscallNum;
+//VM_LogSyscalls( (int *)((byte *)currentVM->dataBase + programStack + 4) );
+ *(callOpStack2+1) = currentVM->systemCall( (int *)((byte *)currentVM->dataBase + callProgramStack + 4) );
+
+ currentVM = savedVM;
+}
+
+void AsmCall( void ) {
+ __asm__("doAsmCall: \n\t" \
+ " movl (%%edi),%%eax \n\t" \
+ " subl $4,%%edi \n\t" \
+ " orl %%eax,%%eax \n\t" \
+ " jl systemCall \n\t" \
+ " shll $2,%%eax \n\t" \
+ " addl %3,%%eax \n\t" \
+ " call *(%%eax) \n\t" \
+ " movl (%%edi),%%eax \n\t" \
+ " andl callMask, %%eax \n\t" \
+ " jmp doret \n\t" \
+ "systemCall: \n\t" \
+ " negl %%eax \n\t" \
+ " decl %%eax \n\t" \
+ " movl %%eax,%0 \n\t" \
+ " movl %%esi,%1 \n\t" \
+ " movl %%edi,%2 \n\t" \
+ " pushl %%ecx \n\t" \
+ " pushl %%esi \n\t" \
+ " pushl %%edi \n\t" \
+ " call callAsmCall \n\t" \
+ " popl %%edi \n\t" \
+ " popl %%esi \n\t" \
+ " popl %%ecx \n\t" \
+ " addl $4,%%edi \n\t" \
+ "doret: \n\t" \
+ " ret \n\t" \
+ : "=rm" (callSyscallNum), "=rm" (callProgramStack), "=rm" (callOpStack) \
+ : "rm" (instructionPointers) \
+ : "ax", "di", "si", "cx" \
+ );
+}
+#endif
+
+static int Constant4( void ) {
+ int v;
+
+ v = code[pc] | (code[pc+1]<<8) | (code[pc+2]<<16) | (code[pc+3]<<24);
+ pc += 4;
+ return v;
+}
+
+static int Constant1( void ) {
+ int v;
+
+ v = code[pc];
+ pc += 1;
+ return v;
+}
+
+static void Emit1( int v )
+{
+ buf[ compiledOfs ] = v;
+ compiledOfs++;
+
+ LastCommand = LAST_COMMAND_NONE;
+}
+
+#if 0
+static void Emit2( int v ) {
+ Emit1( v & 255 );
+ Emit1( ( v >> 8 ) & 255 );
+}
+#endif
+
+static void Emit4( int v ) {
+ Emit1( v & 255 );
+ Emit1( ( v >> 8 ) & 255 );
+ Emit1( ( v >> 16 ) & 255 );
+ Emit1( ( v >> 24 ) & 255 );
+}
+
+static int Hex( int c ) {
+ if ( c >= 'a' && c <= 'f' ) {
+ return 10 + c - 'a';
+ }
+ if ( c >= 'A' && c <= 'F' ) {
+ return 10 + c - 'A';
+ }
+ if ( c >= '0' && c <= '9' ) {
+ return c - '0';
+ }
+
+ Com_Error( ERR_DROP, "Hex: bad char '%c'", c );
+
+ return 0;
+}
+static void EmitString( const char *string ) {
+ int c1, c2;
+ int v;
+
+ while ( 1 ) {
+ c1 = string[0];
+ c2 = string[1];
+
+ v = ( Hex( c1 ) << 4 ) | Hex( c2 );
+ Emit1( v );
+
+ if ( !string[2] ) {
+ break;
+ }
+ string += 3;
+ }
+}
+
+
+
+static void EmitCommand(ELastCommand command)
+{
+ switch(command)
+ {
+ case LAST_COMMAND_MOV_EDI_EAX:
+ EmitString( "89 07" ); // mov dword ptr [edi], eax
+ break;
+
+ case LAST_COMMAND_SUB_DI_4:
+ EmitString( "83 EF 04" ); // sub edi, 4
+ break;
+
+ case LAST_COMMAND_SUB_DI_8:
+ EmitString( "83 EF 08" ); // sub edi, 8
+ break;
+ default:
+ break;
+ }
+ LastCommand = command;
+}
+
+static void EmitAddEDI4(vm_t *vm) {
+ if (LastCommand == LAST_COMMAND_SUB_DI_4 && jused[instruction-1] == 0)
+ { // sub di,4
+ compiledOfs -= 3;
+ vm->instructionPointers[ instruction-1 ] = compiledOfs;
+ return;
+ }
+ if (LastCommand == LAST_COMMAND_SUB_DI_8 && jused[instruction-1] == 0)
+ { // sub di,8
+ compiledOfs -= 3;
+ vm->instructionPointers[ instruction-1 ] = compiledOfs;
+ EmitString( "83 EF 04" ); // sub edi,4
+ return;
+ }
+ EmitString( "83 C7 04" ); // add edi,4
+}
+
+static void EmitMovEAXEDI(vm_t *vm) {
+ if (LastCommand == LAST_COMMAND_MOV_EDI_EAX)
+ { // mov [edi], eax
+ compiledOfs -= 2;
+ vm->instructionPointers[ instruction-1 ] = compiledOfs;
+ return;
+ }
+ if (pop1 == OP_DIVI || pop1 == OP_DIVU || pop1 == OP_MULI || pop1 == OP_MULU ||
+ pop1 == OP_STORE4 || pop1 == OP_STORE2 || pop1 == OP_STORE1 )
+ {
+ return;
+ }
+ if (pop1 == OP_CONST && buf[compiledOfs-6] == 0xC7 && buf[compiledOfs-5] == 0x07 )
+ { // mov edi, 0x123456
+ compiledOfs -= 6;
+ vm->instructionPointers[ instruction-1 ] = compiledOfs;
+ EmitString( "B8" ); // mov eax, 0x12345678
+ Emit4( lastConst );
+ return;
+ }
+ EmitString( "8B 07" ); // mov eax, dword ptr [edi]
+}
+
+qboolean EmitMovEBXEDI(vm_t *vm, int andit) {
+ if (LastCommand == LAST_COMMAND_MOV_EDI_EAX)
+ { // mov [edi], eax
+ compiledOfs -= 2;
+ vm->instructionPointers[ instruction-1 ] = compiledOfs;
+ EmitString( "8B D8"); // mov bx, eax
+ return qfalse;
+ }
+ if (pop1 == OP_DIVI || pop1 == OP_DIVU || pop1 == OP_MULI || pop1 == OP_MULU ||
+ pop1 == OP_STORE4 || pop1 == OP_STORE2 || pop1 == OP_STORE1 )
+ {
+ EmitString( "8B D8"); // mov bx, eax
+ return qfalse;
+ }
+ if (pop1 == OP_CONST && buf[compiledOfs-6] == 0xC7 && buf[compiledOfs-5] == 0x07 )
+ { // mov edi, 0x123456
+ compiledOfs -= 6;
+ vm->instructionPointers[ instruction-1 ] = compiledOfs;
+ EmitString( "BB" ); // mov ebx, 0x12345678
+ if (andit) {
+ Emit4( lastConst & andit );
+ } else {
+ Emit4( lastConst );
+ }
+ return qtrue;
+ }
+
+ EmitString( "8B 1F" ); // mov ebx, dword ptr [edi]
+ return qfalse;
+}
+
+/*
+=================
+VM_Compile
+=================
+*/
+void VM_Compile( vm_t *vm, vmHeader_t *header ) {
+ int op;
+ int maxLength;
+ int v;
+ int i;
+ qboolean opt;
+
+ // allocate a very large temp buffer, we will shrink it later
+ maxLength = header->codeLength * 8;
+ buf = Z_Malloc( maxLength );
+ jused = Z_Malloc(header->instructionCount + 2 );
+
+ Com_Memset(jused, 0, header->instructionCount+2);
+
+ for(pass=0;pass<2;pass++) {
+ oc0 = -23423;
+ oc1 = -234354;
+ pop0 = -43435;
+ pop1 = -545455;
+
+ // translate all instructions
+ pc = 0;
+ instruction = 0;
+ code = (byte *)header + header->codeOffset;
+ compiledOfs = 0;
+
+ LastCommand = LAST_COMMAND_NONE;
+
+ while ( instruction < header->instructionCount ) {
+ if ( compiledOfs > maxLength - 16 ) {
+ Com_Error( ERR_FATAL, "VM_CompileX86: maxLength exceeded" );
+ }
+
+ vm->instructionPointers[ instruction ] = compiledOfs;
+ instruction++;
+
+ if ( pc > header->codeLength ) {
+ Com_Error( ERR_FATAL, "VM_CompileX86: pc > header->codeLength" );
+ }
+
+ op = code[ pc ];
+ pc++;
+ switch ( op ) {
+ case 0:
+ break;
+ case OP_BREAK:
+ EmitString( "CC" ); // int 3
+ break;
+ case OP_ENTER:
+ EmitString( "81 EE" ); // sub esi, 0x12345678
+ Emit4( Constant4() );
+ break;
+ case OP_CONST:
+ if (code[pc+4] == OP_LOAD4) {
+ EmitAddEDI4(vm);
+ EmitString( "BB" ); // mov ebx, 0x12345678
+ Emit4( (Constant4()&vm->dataMask) + (int)vm->dataBase);
+ EmitString( "8B 03" ); // mov eax, dword ptr [ebx]
+ EmitCommand(LAST_COMMAND_MOV_EDI_EAX); // mov dword ptr [edi], eax
+ pc++; // OP_LOAD4
+ instruction += 1;
+ break;
+ }
+ if (code[pc+4] == OP_LOAD2) {
+ EmitAddEDI4(vm);
+ EmitString( "BB" ); // mov ebx, 0x12345678
+ Emit4( (Constant4()&vm->dataMask) + (int)vm->dataBase);
+ EmitString( "0F B7 03" ); // movzx eax, word ptr [ebx]
+ EmitCommand(LAST_COMMAND_MOV_EDI_EAX); // mov dword ptr [edi], eax
+ pc++; // OP_LOAD4
+ instruction += 1;
+ break;
+ }
+ if (code[pc+4] == OP_LOAD1) {
+ EmitAddEDI4(vm);
+ EmitString( "BB" ); // mov ebx, 0x12345678
+ Emit4( (Constant4()&vm->dataMask) + (int)vm->dataBase);
+ EmitString( "0F B6 03" ); // movzx eax, byte ptr [ebx]
+ EmitCommand(LAST_COMMAND_MOV_EDI_EAX); // mov dword ptr [edi], eax
+ pc++; // OP_LOAD4
+ instruction += 1;
+ break;
+ }
+ if (code[pc+4] == OP_STORE4) {
+ opt = EmitMovEBXEDI(vm, (vm->dataMask & ~3));
+ EmitString( "B8" ); // mov eax, 0x12345678
+ Emit4( Constant4() );
+// if (!opt) {
+// EmitString( "81 E3" ); // and ebx, 0x12345678
+// Emit4( vm->dataMask & ~3 );
+// }
+ EmitString( "89 83" ); // mov dword ptr [ebx+0x12345678], eax
+ Emit4( (int)vm->dataBase );
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ pc++; // OP_STORE4
+ instruction += 1;
+ break;
+ }
+ if (code[pc+4] == OP_STORE2) {
+ opt = EmitMovEBXEDI(vm, (vm->dataMask & ~1));
+ EmitString( "B8" ); // mov eax, 0x12345678
+ Emit4( Constant4() );
+// if (!opt) {
+// EmitString( "81 E3" ); // and ebx, 0x12345678
+// Emit4( vm->dataMask & ~1 );
+// }
+ EmitString( "66 89 83" ); // mov word ptr [ebx+0x12345678], eax
+ Emit4( (int)vm->dataBase );
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ pc++; // OP_STORE4
+ instruction += 1;
+ break;
+ }
+ if (code[pc+4] == OP_STORE1) {
+ opt = EmitMovEBXEDI(vm, vm->dataMask);
+ EmitString( "B8" ); // mov eax, 0x12345678
+ Emit4( Constant4() );
+// if (!opt) {
+// EmitString( "81 E3" ); // and ebx, 0x12345678
+// Emit4( vm->dataMask );
+// }
+ EmitString( "88 83" ); // mov byte ptr [ebx+0x12345678], eax
+ Emit4( (int)vm->dataBase );
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ pc++; // OP_STORE4
+ instruction += 1;
+ break;
+ }
+ if (code[pc+4] == OP_ADD) {
+ EmitString( "81 07" ); // add dword ptr [edi], 0x1234567
+ Emit4( Constant4() );
+ pc++; // OP_ADD
+ instruction += 1;
+ break;
+ }
+ if (code[pc+4] == OP_SUB) {
+ EmitString( "81 2F" ); // sub dword ptr [edi], 0x1234567
+ Emit4( Constant4() );
+ pc++; // OP_ADD
+ instruction += 1;
+ break;
+ }
+ EmitAddEDI4(vm);
+ EmitString( "C7 07" ); // mov dword ptr [edi], 0x12345678
+ lastConst = Constant4();
+ Emit4( lastConst );
+ if (code[pc] == OP_JUMP) {
+ jused[lastConst] = 1;
+ }
+ break;
+ case OP_LOCAL:
+ EmitAddEDI4(vm);
+ EmitString( "8D 86" ); // lea eax, [0x12345678 + esi]
+ oc0 = oc1;
+ oc1 = Constant4();
+ Emit4( oc1 );
+ EmitCommand(LAST_COMMAND_MOV_EDI_EAX); // mov dword ptr [edi], eax
+ break;
+ case OP_ARG:
+ EmitMovEAXEDI(vm); // mov eax,dword ptr [edi]
+ EmitString( "89 86" ); // mov dword ptr [esi+database],eax
+ // FIXME: range check
+ Emit4( Constant1() + (int)vm->dataBase );
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ break;
+ case OP_CALL:
+ EmitString( "C7 86" ); // mov dword ptr [esi+database],0x12345678
+ Emit4( (int)vm->dataBase );
+ Emit4( pc );
+ EmitString( "FF 15" ); // call asmCallPtr
+ Emit4( (int)&asmCallPtr );
+ break;
+ case OP_PUSH:
+ EmitAddEDI4(vm);
+ break;
+ case OP_POP:
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ break;
+ case OP_LEAVE:
+ v = Constant4();
+ EmitString( "81 C6" ); // add esi, 0x12345678
+ Emit4( v );
+ EmitString( "C3" ); // ret
+ break;
+ case OP_LOAD4:
+ if (code[pc] == OP_CONST && code[pc+5] == OP_ADD && code[pc+6] == OP_STORE4) {
+ if (oc0 == oc1 && pop0 == OP_LOCAL && pop1 == OP_LOCAL) {
+ compiledOfs -= 11;
+ vm->instructionPointers[ instruction-1 ] = compiledOfs;
+ }
+ pc++; // OP_CONST
+ v = Constant4();
+ EmitMovEBXEDI(vm, vm->dataMask);
+ if (v == 1 && oc0 == oc1 && pop0 == OP_LOCAL && pop1 == OP_LOCAL) {
+ EmitString( "FF 83"); // inc dword ptr [ebx + 0x12345678]
+ Emit4( (int)vm->dataBase );
+ } else {
+ EmitString( "8B 83" ); // mov eax, dword ptr [ebx + 0x12345678]
+ Emit4( (int)vm->dataBase );
+ EmitString( "05" ); // add eax, const
+ Emit4( v );
+ if (oc0 == oc1 && pop0 == OP_LOCAL && pop1 == OP_LOCAL) {
+ EmitString( "89 83" ); // mov dword ptr [ebx+0x12345678], eax
+ Emit4( (int)vm->dataBase );
+ } else {
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ EmitString( "8B 1F" ); // mov ebx, dword ptr [edi]
+ EmitString( "89 83" ); // mov dword ptr [ebx+0x12345678], eax
+ Emit4( (int)vm->dataBase );
+ }
+ }
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ pc++; // OP_ADD
+ pc++; // OP_STORE
+ instruction += 3;
+ break;
+ }
+
+ if (code[pc] == OP_CONST && code[pc+5] == OP_SUB && code[pc+6] == OP_STORE4) {
+ if (oc0 == oc1 && pop0 == OP_LOCAL && pop1 == OP_LOCAL) {
+ compiledOfs -= 11;
+ vm->instructionPointers[ instruction-1 ] = compiledOfs;
+ }
+ EmitMovEBXEDI(vm, vm->dataMask);
+ EmitString( "8B 83" ); // mov eax, dword ptr [ebx + 0x12345678]
+ Emit4( (int)vm->dataBase );
+ pc++; // OP_CONST
+ v = Constant4();
+ if (v == 1 && oc0 == oc1 && pop0 == OP_LOCAL && pop1 == OP_LOCAL) {
+ EmitString( "FF 8B"); // dec dword ptr [ebx + 0x12345678]
+ Emit4( (int)vm->dataBase );
+ } else {
+ EmitString( "2D" ); // sub eax, const
+ Emit4( v );
+ if (oc0 == oc1 && pop0 == OP_LOCAL && pop1 == OP_LOCAL) {
+ EmitString( "89 83" ); // mov dword ptr [ebx+0x12345678], eax
+ Emit4( (int)vm->dataBase );
+ } else {
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ EmitString( "8B 1F" ); // mov ebx, dword ptr [edi]
+ EmitString( "89 83" ); // mov dword ptr [ebx+0x12345678], eax
+ Emit4( (int)vm->dataBase );
+ }
+ }
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ pc++; // OP_SUB
+ pc++; // OP_STORE
+ instruction += 3;
+ break;
+ }
+
+ if (buf[compiledOfs-2] == 0x89 && buf[compiledOfs-1] == 0x07) {
+ compiledOfs -= 2;
+ vm->instructionPointers[ instruction-1 ] = compiledOfs;
+ EmitString( "8B 80"); // mov eax, dword ptr [eax + 0x1234567]
+ Emit4( (int)vm->dataBase );
+ EmitCommand(LAST_COMMAND_MOV_EDI_EAX); // mov dword ptr [edi], eax
+ break;
+ }
+ EmitMovEBXEDI(vm, vm->dataMask);
+ EmitString( "8B 83" ); // mov eax, dword ptr [ebx + 0x12345678]
+ Emit4( (int)vm->dataBase );
+ EmitCommand(LAST_COMMAND_MOV_EDI_EAX); // mov dword ptr [edi], eax
+ break;
+ case OP_LOAD2:
+ EmitMovEBXEDI(vm, vm->dataMask);
+ EmitString( "0F B7 83" ); // movzx eax, word ptr [ebx + 0x12345678]
+ Emit4( (int)vm->dataBase );
+ EmitCommand(LAST_COMMAND_MOV_EDI_EAX); // mov dword ptr [edi], eax
+ break;
+ case OP_LOAD1:
+ EmitMovEBXEDI(vm, vm->dataMask);
+ EmitString( "0F B6 83" ); // movzx eax, byte ptr [ebx + 0x12345678]
+ Emit4( (int)vm->dataBase );
+ EmitCommand(LAST_COMMAND_MOV_EDI_EAX); // mov dword ptr [edi], eax
+ break;
+ case OP_STORE4:
+ EmitMovEAXEDI(vm);
+ EmitString( "8B 5F FC" ); // mov ebx, dword ptr [edi-4]
+// if (pop1 != OP_CALL) {
+// EmitString( "81 E3" ); // and ebx, 0x12345678
+// Emit4( vm->dataMask & ~3 );
+// }
+ EmitString( "89 83" ); // mov dword ptr [ebx+0x12345678], eax
+ Emit4( (int)vm->dataBase );
+ EmitCommand(LAST_COMMAND_SUB_DI_8); // sub edi, 8
+ break;
+ case OP_STORE2:
+ EmitMovEAXEDI(vm);
+ EmitString( "8B 5F FC" ); // mov ebx, dword ptr [edi-4]
+// EmitString( "81 E3" ); // and ebx, 0x12345678
+// Emit4( vm->dataMask & ~1 );
+ EmitString( "66 89 83" ); // mov word ptr [ebx+0x12345678], eax
+ Emit4( (int)vm->dataBase );
+ EmitCommand(LAST_COMMAND_SUB_DI_8); // sub edi, 8
+ break;
+ case OP_STORE1:
+ EmitMovEAXEDI(vm);
+ EmitString( "8B 5F FC" ); // mov ebx, dword ptr [edi-4]
+// EmitString( "81 E3" ); // and ebx, 0x12345678
+// Emit4( vm->dataMask );
+ EmitString( "88 83" ); // mov byte ptr [ebx+0x12345678], eax
+ Emit4( (int)vm->dataBase );
+ EmitCommand(LAST_COMMAND_SUB_DI_8); // sub edi, 8
+ break;
+
+ case OP_EQ:
+ EmitCommand(LAST_COMMAND_SUB_DI_8); // sub edi, 8
+ EmitString( "8B 47 04" ); // mov eax, dword ptr [edi+4]
+ EmitString( "3B 47 08" ); // cmp eax, dword ptr [edi+8]
+ EmitString( "75 06" ); // jne +6
+ EmitString( "FF 25" ); // jmp [0x12345678]
+ v = Constant4();
+ jused[v] = 1;
+ Emit4( (int)vm->instructionPointers + v*4 );
+ break;
+ case OP_NE:
+ EmitCommand(LAST_COMMAND_SUB_DI_8); // sub edi, 8
+ EmitString( "8B 47 04" ); // mov eax, dword ptr [edi+4]
+ EmitString( "3B 47 08" ); // cmp eax, dword ptr [edi+8]
+ EmitString( "74 06" ); // je +6
+ EmitString( "FF 25" ); // jmp [0x12345678]
+ v = Constant4();
+ jused[v] = 1;
+ Emit4( (int)vm->instructionPointers + v*4 );
+ break;
+ case OP_LTI:
+ EmitCommand(LAST_COMMAND_SUB_DI_8); // sub edi, 8
+ EmitString( "8B 47 04" ); // mov eax, dword ptr [edi+4]
+ EmitString( "3B 47 08" ); // cmp eax, dword ptr [edi+8]
+ EmitString( "7D 06" ); // jnl +6
+ EmitString( "FF 25" ); // jmp [0x12345678]
+ v = Constant4();
+ jused[v] = 1;
+ Emit4( (int)vm->instructionPointers + v*4 );
+ break;
+ case OP_LEI:
+ EmitCommand(LAST_COMMAND_SUB_DI_8); // sub edi, 8
+ EmitString( "8B 47 04" ); // mov eax, dword ptr [edi+4]
+ EmitString( "3B 47 08" ); // cmp eax, dword ptr [edi+8]
+ EmitString( "7F 06" ); // jnle +6
+ EmitString( "FF 25" ); // jmp [0x12345678]
+ v = Constant4();
+ jused[v] = 1;
+ Emit4( (int)vm->instructionPointers + v*4 );
+ break;
+ case OP_GTI:
+ EmitCommand(LAST_COMMAND_SUB_DI_8); // sub edi, 8
+ EmitString( "8B 47 04" ); // mov eax, dword ptr [edi+4]
+ EmitString( "3B 47 08" ); // cmp eax, dword ptr [edi+8]
+ EmitString( "7E 06" ); // jng +6
+ EmitString( "FF 25" ); // jmp [0x12345678]
+ v = Constant4();
+ jused[v] = 1;
+ Emit4( (int)vm->instructionPointers + v*4 );
+ break;
+ case OP_GEI:
+ EmitCommand(LAST_COMMAND_SUB_DI_8); // sub edi, 8
+ EmitString( "8B 47 04" ); // mov eax, dword ptr [edi+4]
+ EmitString( "3B 47 08" ); // cmp eax, dword ptr [edi+8]
+ EmitString( "7C 06" ); // jnge +6
+ EmitString( "FF 25" ); // jmp [0x12345678]
+ v = Constant4();
+ jused[v] = 1;
+ Emit4( (int)vm->instructionPointers + v*4 );
+ break;
+ case OP_LTU:
+ EmitCommand(LAST_COMMAND_SUB_DI_8); // sub edi, 8
+ EmitString( "8B 47 04" ); // mov eax, dword ptr [edi+4]
+ EmitString( "3B 47 08" ); // cmp eax, dword ptr [edi+8]
+ EmitString( "73 06" ); // jnb +6
+ EmitString( "FF 25" ); // jmp [0x12345678]
+ v = Constant4();
+ jused[v] = 1;
+ Emit4( (int)vm->instructionPointers + v*4 );
+ break;
+ case OP_LEU:
+ EmitCommand(LAST_COMMAND_SUB_DI_8); // sub edi, 8
+ EmitString( "8B 47 04" ); // mov eax, dword ptr [edi+4]
+ EmitString( "3B 47 08" ); // cmp eax, dword ptr [edi+8]
+ EmitString( "77 06" ); // jnbe +6
+ EmitString( "FF 25" ); // jmp [0x12345678]
+ v = Constant4();
+ jused[v] = 1;
+ Emit4( (int)vm->instructionPointers + v*4 );
+ break;
+ case OP_GTU:
+ EmitCommand(LAST_COMMAND_SUB_DI_8); // sub edi, 8
+ EmitString( "8B 47 04" ); // mov eax, dword ptr [edi+4]
+ EmitString( "3B 47 08" ); // cmp eax, dword ptr [edi+8]
+ EmitString( "76 06" ); // jna +6
+ EmitString( "FF 25" ); // jmp [0x12345678]
+ v = Constant4();
+ jused[v] = 1;
+ Emit4( (int)vm->instructionPointers + v*4 );
+ break;
+ case OP_GEU:
+ EmitCommand(LAST_COMMAND_SUB_DI_8); // sub edi, 8
+ EmitString( "8B 47 04" ); // mov eax, dword ptr [edi+4]
+ EmitString( "3B 47 08" ); // cmp eax, dword ptr [edi+8]
+ EmitString( "72 06" ); // jnae +6
+ EmitString( "FF 25" ); // jmp [0x12345678]
+ v = Constant4();
+ jused[v] = 1;
+ Emit4( (int)vm->instructionPointers + v*4 );
+ break;
+ case OP_EQF:
+ EmitCommand(LAST_COMMAND_SUB_DI_8); // sub edi, 8
+ EmitString( "D9 47 04" ); // fld dword ptr [edi+4]
+ EmitString( "D8 5F 08" ); // fcomp dword ptr [edi+8]
+ EmitString( "DF E0" ); // fnstsw ax
+ EmitString( "F6 C4 40" ); // test ah,0x40
+ EmitString( "74 06" ); // je +6
+ EmitString( "FF 25" ); // jmp [0x12345678]
+ v = Constant4();
+ jused[v] = 1;
+ Emit4( (int)vm->instructionPointers + v*4 );
+ break;
+ case OP_NEF:
+ EmitCommand(LAST_COMMAND_SUB_DI_8); // sub edi, 8
+ EmitString( "D9 47 04" ); // fld dword ptr [edi+4]
+ EmitString( "D8 5F 08" ); // fcomp dword ptr [edi+8]
+ EmitString( "DF E0" ); // fnstsw ax
+ EmitString( "F6 C4 40" ); // test ah,0x40
+ EmitString( "75 06" ); // jne +6
+ EmitString( "FF 25" ); // jmp [0x12345678]
+ v = Constant4();
+ jused[v] = 1;
+ Emit4( (int)vm->instructionPointers + v*4 );
+ break;
+ case OP_LTF:
+ EmitCommand(LAST_COMMAND_SUB_DI_8); // sub edi, 8
+ EmitString( "D9 47 04" ); // fld dword ptr [edi+4]
+ EmitString( "D8 5F 08" ); // fcomp dword ptr [edi+8]
+ EmitString( "DF E0" ); // fnstsw ax
+ EmitString( "F6 C4 01" ); // test ah,0x01
+ EmitString( "74 06" ); // je +6
+ EmitString( "FF 25" ); // jmp [0x12345678]
+ v = Constant4();
+ jused[v] = 1;
+ Emit4( (int)vm->instructionPointers + v*4 );
+ break;
+ case OP_LEF:
+ EmitCommand(LAST_COMMAND_SUB_DI_8); // sub edi, 8
+ EmitString( "D9 47 04" ); // fld dword ptr [edi+4]
+ EmitString( "D8 5F 08" ); // fcomp dword ptr [edi+8]
+ EmitString( "DF E0" ); // fnstsw ax
+ EmitString( "F6 C4 41" ); // test ah,0x41
+ EmitString( "74 06" ); // je +6
+ EmitString( "FF 25" ); // jmp [0x12345678]
+ v = Constant4();
+ jused[v] = 1;
+ Emit4( (int)vm->instructionPointers + v*4 );
+ break;
+ case OP_GTF:
+ EmitCommand(LAST_COMMAND_SUB_DI_8); // sub edi, 8
+ EmitString( "D9 47 04" ); // fld dword ptr [edi+4]
+ EmitString( "D8 5F 08" ); // fcomp dword ptr [edi+8]
+ EmitString( "DF E0" ); // fnstsw ax
+ EmitString( "F6 C4 41" ); // test ah,0x41
+ EmitString( "75 06" ); // jne +6
+ EmitString( "FF 25" ); // jmp [0x12345678]
+ v = Constant4();
+ jused[v] = 1;
+ Emit4( (int)vm->instructionPointers + v*4 );
+ break;
+ case OP_GEF:
+ EmitCommand(LAST_COMMAND_SUB_DI_8); // sub edi, 8
+ EmitString( "D9 47 04" ); // fld dword ptr [edi+4]
+ EmitString( "D8 5F 08" ); // fcomp dword ptr [edi+8]
+ EmitString( "DF E0" ); // fnstsw ax
+ EmitString( "F6 C4 01" ); // test ah,0x01
+ EmitString( "75 06" ); // jne +6
+ EmitString( "FF 25" ); // jmp [0x12345678]
+ v = Constant4();
+ jused[v] = 1;
+ Emit4( (int)vm->instructionPointers + v*4 );
+ break;
+ case OP_NEGI:
+ EmitString( "F7 1F" ); // neg dword ptr [edi]
+ break;
+ case OP_ADD:
+ EmitMovEAXEDI(vm); // mov eax, dword ptr [edi]
+ EmitString( "01 47 FC" ); // add dword ptr [edi-4],eax
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ break;
+ case OP_SUB:
+ EmitMovEAXEDI(vm); // mov eax, dword ptr [edi]
+ EmitString( "29 47 FC" ); // sub dword ptr [edi-4],eax
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ break;
+ case OP_DIVI:
+ EmitString( "8B 47 FC" ); // mov eax,dword ptr [edi-4]
+ EmitString( "99" ); // cdq
+ EmitString( "F7 3F" ); // idiv dword ptr [edi]
+ EmitString( "89 47 FC" ); // mov dword ptr [edi-4],eax
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ break;
+ case OP_DIVU:
+ EmitString( "8B 47 FC" ); // mov eax,dword ptr [edi-4]
+ EmitString( "33 D2" ); // xor edx, edx
+ EmitString( "F7 37" ); // div dword ptr [edi]
+ EmitString( "89 47 FC" ); // mov dword ptr [edi-4],eax
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ break;
+ case OP_MODI:
+ EmitString( "8B 47 FC" ); // mov eax,dword ptr [edi-4]
+ EmitString( "99" ); // cdq
+ EmitString( "F7 3F" ); // idiv dword ptr [edi]
+ EmitString( "89 57 FC" ); // mov dword ptr [edi-4],edx
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ break;
+ case OP_MODU:
+ EmitString( "8B 47 FC" ); // mov eax,dword ptr [edi-4]
+ EmitString( "33 D2" ); // xor edx, edx
+ EmitString( "F7 37" ); // div dword ptr [edi]
+ EmitString( "89 57 FC" ); // mov dword ptr [edi-4],edx
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ break;
+ case OP_MULI:
+ EmitString( "8B 47 FC" ); // mov eax,dword ptr [edi-4]
+ EmitString( "F7 2F" ); // imul dword ptr [edi]
+ EmitString( "89 47 FC" ); // mov dword ptr [edi-4],eax
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ break;
+ case OP_MULU:
+ EmitString( "8B 47 FC" ); // mov eax,dword ptr [edi-4]
+ EmitString( "F7 27" ); // mul dword ptr [edi]
+ EmitString( "89 47 FC" ); // mov dword ptr [edi-4],eax
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ break;
+ case OP_BAND:
+ EmitMovEAXEDI(vm); // mov eax, dword ptr [edi]
+ EmitString( "21 47 FC" ); // and dword ptr [edi-4],eax
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ break;
+ case OP_BOR:
+ EmitMovEAXEDI(vm); // mov eax, dword ptr [edi]
+ EmitString( "09 47 FC" ); // or dword ptr [edi-4],eax
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ break;
+ case OP_BXOR:
+ EmitMovEAXEDI(vm); // mov eax, dword ptr [edi]
+ EmitString( "31 47 FC" ); // xor dword ptr [edi-4],eax
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ break;
+ case OP_BCOM:
+ EmitString( "F7 17" ); // not dword ptr [edi]
+ break;
+ case OP_LSH:
+ EmitString( "8B 0F" ); // mov ecx, dword ptr [edi]
+ EmitString( "D3 67 FC" ); // shl dword ptr [edi-4], cl
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ break;
+ case OP_RSHI:
+ EmitString( "8B 0F" ); // mov ecx, dword ptr [edi]
+ EmitString( "D3 7F FC" ); // sar dword ptr [edi-4], cl
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ break;
+ case OP_RSHU:
+ EmitString( "8B 0F" ); // mov ecx, dword ptr [edi]
+ EmitString( "D3 6F FC" ); // shr dword ptr [edi-4], cl
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ break;
+ case OP_NEGF:
+ EmitString( "D9 07" ); // fld dword ptr [edi]
+ EmitString( "D9 E0" ); // fchs
+ EmitString( "D9 1F" ); // fstp dword ptr [edi]
+ break;
+ case OP_ADDF:
+ EmitString( "D9 47 FC" ); // fld dword ptr [edi-4]
+ EmitString( "D8 07" ); // fadd dword ptr [edi]
+ EmitString( "D9 5F FC" ); // fstp dword ptr [edi-4]
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ break;
+ case OP_SUBF:
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ EmitString( "D9 07" ); // fld dword ptr [edi]
+ EmitString( "D8 67 04" ); // fsub dword ptr [edi+4]
+ EmitString( "D9 1F" ); // fstp dword ptr [edi]
+ break;
+ case OP_DIVF:
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ EmitString( "D9 07" ); // fld dword ptr [edi]
+ EmitString( "D8 77 04" ); // fdiv dword ptr [edi+4]
+ EmitString( "D9 1F" ); // fstp dword ptr [edi]
+ break;
+ case OP_MULF:
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ EmitString( "D9 07" ); // fld dword ptr [edi]
+ EmitString( "D8 4f 04" ); // fmul dword ptr [edi+4]
+ EmitString( "D9 1F" ); // fstp dword ptr [edi]
+ break;
+ case OP_CVIF:
+ EmitString( "DB 07" ); // fild dword ptr [edi]
+ EmitString( "D9 1F" ); // fstp dword ptr [edi]
+ break;
+ case OP_CVFI:
+#ifndef FTOL_PTR // WHENHELLISFROZENOVER // bk001213 - was used in 1.17
+ // not IEEE complient, but simple and fast
+ EmitString( "D9 07" ); // fld dword ptr [edi]
+ EmitString( "DB 1F" ); // fistp dword ptr [edi]
+#else // FTOL_PTR
+ // call the library conversion function
+ EmitString( "D9 07" ); // fld dword ptr [edi]
+ EmitString( "FF 15" ); // call ftolPtr
+ Emit4( (int)&ftolPtr );
+ EmitCommand(LAST_COMMAND_MOV_EDI_EAX); // mov dword ptr [edi], eax
+#endif
+ break;
+ case OP_SEX8:
+ EmitString( "0F BE 07" ); // movsx eax, byte ptr [edi]
+ EmitCommand(LAST_COMMAND_MOV_EDI_EAX); // mov dword ptr [edi], eax
+ break;
+ case OP_SEX16:
+ EmitString( "0F BF 07" ); // movsx eax, word ptr [edi]
+ EmitCommand(LAST_COMMAND_MOV_EDI_EAX); // mov dword ptr [edi], eax
+ break;
+
+ case OP_BLOCK_COPY:
+ // FIXME: range check
+ EmitString( "56" ); // push esi
+ EmitString( "57" ); // push edi
+ EmitString( "8B 37" ); // mov esi,[edi]
+ EmitString( "8B 7F FC" ); // mov edi,[edi-4]
+ EmitString( "B9" ); // mov ecx,0x12345678
+ Emit4( Constant4() >> 2 );
+ EmitString( "B8" ); // mov eax, datamask
+ Emit4( vm->dataMask );
+ EmitString( "BB" ); // mov ebx, database
+ Emit4( (int)vm->dataBase );
+ EmitString( "23 F0" ); // and esi, eax
+ EmitString( "03 F3" ); // add esi, ebx
+ EmitString( "23 F8" ); // and edi, eax
+ EmitString( "03 FB" ); // add edi, ebx
+ EmitString( "F3 A5" ); // rep movsd
+ EmitString( "5F" ); // pop edi
+ EmitString( "5E" ); // pop esi
+ EmitCommand(LAST_COMMAND_SUB_DI_8); // sub edi, 8
+ break;
+
+ case OP_JUMP:
+ EmitCommand(LAST_COMMAND_SUB_DI_4); // sub edi, 4
+ EmitString( "8B 47 04" ); // mov eax,dword ptr [edi+4]
+ // FIXME: range check
+ EmitString( "FF 24 85" ); // jmp dword ptr [instructionPointers + eax * 4]
+ Emit4( (int)vm->instructionPointers );
+ break;
+ default:
+ Com_Error( ERR_DROP, "VM_CompileX86: bad opcode %i at offset %i", op, pc );
+ }
+ pop0 = pop1;
+ pop1 = op;
+ }
+ }
+
+ // copy to an exact size buffer on the hunk
+ vm->codeLength = compiledOfs;
+ vm->codeBase = Hunk_Alloc( compiledOfs, h_low );
+ Com_Memcpy( vm->codeBase, buf, compiledOfs );
+ Z_Free( buf );
+ Z_Free( jused );
+ Com_Printf( "VM file %s compiled to %i bytes of code\n", vm->name, compiledOfs );
+
+ // offset all the instruction pointers for the new location
+ for ( i = 0 ; i < header->instructionCount ; i++ ) {
+ vm->instructionPointers[i] += (int)vm->codeBase;
+ }
+
+#if 0 // ndef _WIN32
+ // Must make the newly generated code executable
+ {
+ int r;
+ unsigned long addr;
+ int psize = getpagesize();
+
+ addr = ((int)vm->codeBase & ~(psize-1)) - psize;
+
+ r = mprotect((char*)addr, vm->codeLength + (int)vm->codeBase - addr + psize,
+ PROT_READ | PROT_WRITE | PROT_EXEC );
+
+ if (r < 0)
+ Com_Error( ERR_FATAL, "mprotect failed to change PROT_EXEC" );
+ }
+#endif
+
+}
+
+/*
+==============
+VM_CallCompiled
+
+This function is called directly by the generated code
+==============
+*/
+#ifndef DLL_ONLY // bk010215 - for DLL_ONLY dedicated servers/builds w/o VM
+int VM_CallCompiled( vm_t *vm, int *args ) {
+ int stack[1024];
+ int programCounter;
+ int programStack;
+ int stackOnEntry;
+ byte *image;
+ void *entryPoint;
+ void *opStack;
+ int *oldInstructionPointers;
+
+ oldInstructionPointers = instructionPointers;
+
+ currentVM = vm;
+ instructionPointers = vm->instructionPointers;
+
+ // interpret the code
+ vm->currentlyInterpreting = qtrue;
+
+ callMask = vm->dataMask;
+
+ // we might be called recursively, so this might not be the very top
+ programStack = vm->programStack;
+ stackOnEntry = programStack;
+
+ // set up the stack frame
+ image = vm->dataBase;
+
+ programCounter = 0;
+
+ programStack -= 48;
+
+ *(int *)&image[ programStack + 44] = args[9];
+ *(int *)&image[ programStack + 40] = args[8];
+ *(int *)&image[ programStack + 36] = args[7];
+ *(int *)&image[ programStack + 32] = args[6];
+ *(int *)&image[ programStack + 28] = args[5];
+ *(int *)&image[ programStack + 24] = args[4];
+ *(int *)&image[ programStack + 20] = args[3];
+ *(int *)&image[ programStack + 16] = args[2];
+ *(int *)&image[ programStack + 12] = args[1];
+ *(int *)&image[ programStack + 8 ] = args[0];
+ *(int *)&image[ programStack + 4 ] = 0; // return stack
+ *(int *)&image[ programStack ] = -1; // will terminate the loop on return
+
+ // off we go into generated code...
+ entryPoint = vm->codeBase;
+ opStack = &stack;
+
+#ifdef _WIN32
+ __asm {
+ pushad
+ mov esi, programStack;
+ mov edi, opStack
+ call entryPoint
+ mov programStack, esi
+ mov opStack, edi
+ popad
+ }
+#else
+ {
+ static int memProgramStack;
+ static void *memOpStack;
+ static void *memEntryPoint;
+
+ memProgramStack = programStack;
+ memOpStack = opStack;
+ memEntryPoint = entryPoint;
+
+ __asm__(" pushal \r\n" \
+ " movl %0,%%esi \r\n" \
+ " movl %1,%%edi \r\n" \
+ " call *%2 \r\n" \
+ " movl %%esi,%0 \r\n" \
+ " movl %%edi,%1 \r\n" \
+ " popal \r\n" \
+ : "=m" (memProgramStack), "=m" (memOpStack) \
+ : "m" (memEntryPoint), "0" (memProgramStack), "1" (memOpStack) \
+ : "si", "di" \
+ );
+
+ programStack = memProgramStack;
+ opStack = memOpStack;
+ }
+#endif
+
+ if ( opStack != &stack[1] ) {
+ Com_Error( ERR_DROP, "opStack corrupted in compiled code" );
+ }
+ if ( programStack != stackOnEntry - 48 ) {
+ Com_Error( ERR_DROP, "programStack corrupted in compiled code" );
+ }
+
+ vm->programStack = stackOnEntry;
+
+ // in case we were recursively called by another vm
+ instructionPointers = oldInstructionPointers;
+
+ return *(int *)opStack;
+}
+#endif // !DLL_ONLY
+
+
diff --git a/code/quake3.sln b/code/quake3.sln
new file mode 100755
index 0000000..7d370b8
--- /dev/null
+++ b/code/quake3.sln
@@ -0,0 +1,145 @@
+Microsoft Visual Studio Solution File, Format Version 8.00
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Splines", "splines\Splines.vcproj", "{DBAF2C53-3858-455D-A1AE-3FC093515314}"
+ ProjectSection(ProjectDependencies) = postProject
+ EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "botlib", "botlib\botlib.vcproj", "{A410161F-AE9F-485D-A01F-5294891430A6}"
+ ProjectSection(ProjectDependencies) = postProject
+ EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cgame", "cgame\cgame.vcproj", "{C878E295-CB82-4B40-8ECF-5CE5525466FA}"
+ ProjectSection(ProjectDependencies) = postProject
+ EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "game", "game\game.vcproj", "{F9EE10DA-2404-4154-B904-F93C936C040A}"
+ ProjectSection(ProjectDependencies) = postProject
+ EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "q3_ui", "q3_ui\q3_ui.vcproj", "{D454C4C7-7765-4149-ABAD-05FDEB9D94F8}"
+ ProjectSection(ProjectDependencies) = postProject
+ EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "quake3", "quake3.vcproj", "{81CB51C4-B434-4E12-B69B-BAEE102F2852}"
+ ProjectSection(ProjectDependencies) = postProject
+ {A410161F-AE9F-485D-A01F-5294891430A6} = {A410161F-AE9F-485D-A01F-5294891430A6}
+ {DBAF2C53-3858-455D-A1AE-3FC093515314} = {DBAF2C53-3858-455D-A1AE-3FC093515314}
+ {AB424155-FBED-4D8D-B007-5B6CF93EA395} = {AB424155-FBED-4D8D-B007-5B6CF93EA395}
+ EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "renderer", "renderer\renderer.vcproj", "{AB424155-FBED-4D8D-B007-5B6CF93EA395}"
+ ProjectSection(ProjectDependencies) = postProject
+ EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ui", "ui\ui.vcproj", "{A8EAC38E-C7DA-42F8-811D-77FD092B9D19}"
+ ProjectSection(ProjectDependencies) = postProject
+ EndProjectSection
+EndProject
+Global
+ GlobalSection(SourceCodeControl) = preSolution
+ SccNumberOfProjects = 8
+ SccProjectUniqueName0 = splines\\Splines.vcproj
+ SccProjectName0 = \u0022$/MissionPack/code/Splines\u0022,\u0020WJNAAAAA
+ SccLocalPath0 = splines
+ SccProvider0 = MSSCCI:Perforce\u0020SCM
+ SccProjectUniqueName1 = botlib\\botlib.vcproj
+ SccProjectName1 = \u0022$/MissionPack/code/botlib\u0022,\u0020HBAAAAAA
+ SccLocalPath1 = botlib
+ SccProvider1 = MSSCCI:Perforce\u0020SCM
+ SccProjectUniqueName2 = cgame\\cgame.vcproj
+ SccProjectName2 = \u0022$/MissionPack/code/cgame\u0022,\u0020NPAAAAAA
+ SccLocalPath2 = cgame
+ SccProvider2 = MSSCCI:Perforce\u0020SCM
+ SccProjectUniqueName3 = game\\game.vcproj
+ SccProjectName3 = \u0022$/MissionPack/code/game\u0022,\u0020CYAAAAAA
+ SccLocalPath3 = game
+ SccProvider3 = MSSCCI:Perforce\u0020SCM
+ SccProjectUniqueName4 = q3_ui\\q3_ui.vcproj
+ SccProjectName4 = \u0022$/MissionPack/code/q3_ui\u0022,\u0020VFLAAAAA
+ SccLocalPath4 = q3_ui
+ SccProvider4 = MSSCCI:Perforce\u0020SCM
+ SccProjectUniqueName5 = quake3.vcproj
+ SccProjectName5 = \u0022$/MissionPack/code\u0022,\u0020CAAAAAAA
+ SccLocalPath5 = .
+ SccProvider5 = MSSCCI:Perforce\u0020SCM
+ SccProjectUniqueName6 = renderer\\renderer.vcproj
+ SccProjectName6 = \u0022$/MissionPack/code/renderer\u0022,\u0020EJBAAAAA
+ SccLocalPath6 = renderer
+ SccProvider6 = MSSCCI:Perforce\u0020SCM
+ SccProjectUniqueName7 = ui\\ui.vcproj
+ SccProjectName7 = \u0022$/MissionPack/code/ui\u0022,\u0020AOBAAAAA
+ SccLocalPath7 = ui
+ SccProvider7 = MSSCCI:Perforce\u0020SCM
+ EndGlobalSection
+ GlobalSection(SolutionConfiguration) = preSolution
+ Debug = Debug
+ Debug TA = Debug TA
+ Release = Release
+ Release TA = Release TA
+ EndGlobalSection
+ GlobalSection(ProjectConfiguration) = postSolution
+ {DBAF2C53-3858-455D-A1AE-3FC093515314}.Debug.ActiveCfg = Debug|Win32
+ {DBAF2C53-3858-455D-A1AE-3FC093515314}.Debug.Build.0 = Debug|Win32
+ {DBAF2C53-3858-455D-A1AE-3FC093515314}.Debug TA.ActiveCfg = Debug|Win32
+ {DBAF2C53-3858-455D-A1AE-3FC093515314}.Debug TA.Build.0 = Debug|Win32
+ {DBAF2C53-3858-455D-A1AE-3FC093515314}.Release.ActiveCfg = Release|Win32
+ {DBAF2C53-3858-455D-A1AE-3FC093515314}.Release.Build.0 = Release|Win32
+ {DBAF2C53-3858-455D-A1AE-3FC093515314}.Release TA.ActiveCfg = Release|Win32
+ {DBAF2C53-3858-455D-A1AE-3FC093515314}.Release TA.Build.0 = Release|Win32
+ {A410161F-AE9F-485D-A01F-5294891430A6}.Debug.ActiveCfg = Debug|Win32
+ {A410161F-AE9F-485D-A01F-5294891430A6}.Debug.Build.0 = Debug|Win32
+ {A410161F-AE9F-485D-A01F-5294891430A6}.Debug TA.ActiveCfg = Debug TA|Win32
+ {A410161F-AE9F-485D-A01F-5294891430A6}.Debug TA.Build.0 = Debug TA|Win32
+ {A410161F-AE9F-485D-A01F-5294891430A6}.Release.ActiveCfg = Release|Win32
+ {A410161F-AE9F-485D-A01F-5294891430A6}.Release.Build.0 = Release|Win32
+ {A410161F-AE9F-485D-A01F-5294891430A6}.Release TA.ActiveCfg = Release TA|Win32
+ {A410161F-AE9F-485D-A01F-5294891430A6}.Release TA.Build.0 = Release TA|Win32
+ {C878E295-CB82-4B40-8ECF-5CE5525466FA}.Debug.ActiveCfg = Debug|Win32
+ {C878E295-CB82-4B40-8ECF-5CE5525466FA}.Debug.Build.0 = Debug|Win32
+ {C878E295-CB82-4B40-8ECF-5CE5525466FA}.Debug TA.ActiveCfg = Debug TA|Win32
+ {C878E295-CB82-4B40-8ECF-5CE5525466FA}.Debug TA.Build.0 = Debug TA|Win32
+ {C878E295-CB82-4B40-8ECF-5CE5525466FA}.Release.ActiveCfg = Release|Win32
+ {C878E295-CB82-4B40-8ECF-5CE5525466FA}.Release.Build.0 = Release|Win32
+ {C878E295-CB82-4B40-8ECF-5CE5525466FA}.Release TA.ActiveCfg = Release TA|Win32
+ {C878E295-CB82-4B40-8ECF-5CE5525466FA}.Release TA.Build.0 = Release TA|Win32
+ {F9EE10DA-2404-4154-B904-F93C936C040A}.Debug.ActiveCfg = Debug|Win32
+ {F9EE10DA-2404-4154-B904-F93C936C040A}.Debug.Build.0 = Debug|Win32
+ {F9EE10DA-2404-4154-B904-F93C936C040A}.Debug TA.ActiveCfg = Debug TA|Win32
+ {F9EE10DA-2404-4154-B904-F93C936C040A}.Debug TA.Build.0 = Debug TA|Win32
+ {F9EE10DA-2404-4154-B904-F93C936C040A}.Release.ActiveCfg = Release|Win32
+ {F9EE10DA-2404-4154-B904-F93C936C040A}.Release.Build.0 = Release|Win32
+ {F9EE10DA-2404-4154-B904-F93C936C040A}.Release TA.ActiveCfg = Release TA|Win32
+ {F9EE10DA-2404-4154-B904-F93C936C040A}.Release TA.Build.0 = Release TA|Win32
+ {D454C4C7-7765-4149-ABAD-05FDEB9D94F8}.Debug.ActiveCfg = Debug|Win32
+ {D454C4C7-7765-4149-ABAD-05FDEB9D94F8}.Debug.Build.0 = Debug|Win32
+ {D454C4C7-7765-4149-ABAD-05FDEB9D94F8}.Debug TA.ActiveCfg = Debug TA|Win32
+ {D454C4C7-7765-4149-ABAD-05FDEB9D94F8}.Release.ActiveCfg = Release|Win32
+ {D454C4C7-7765-4149-ABAD-05FDEB9D94F8}.Release.Build.0 = Release|Win32
+ {D454C4C7-7765-4149-ABAD-05FDEB9D94F8}.Release TA.ActiveCfg = Release TA|Win32
+ {81CB51C4-B434-4E12-B69B-BAEE102F2852}.Debug.ActiveCfg = Debug|Win32
+ {81CB51C4-B434-4E12-B69B-BAEE102F2852}.Debug.Build.0 = Debug|Win32
+ {81CB51C4-B434-4E12-B69B-BAEE102F2852}.Debug TA.ActiveCfg = Debug TA|Win32
+ {81CB51C4-B434-4E12-B69B-BAEE102F2852}.Debug TA.Build.0 = Debug TA|Win32
+ {81CB51C4-B434-4E12-B69B-BAEE102F2852}.Release.ActiveCfg = Release|Win32
+ {81CB51C4-B434-4E12-B69B-BAEE102F2852}.Release.Build.0 = Release|Win32
+ {81CB51C4-B434-4E12-B69B-BAEE102F2852}.Release TA.ActiveCfg = Release TA|Win32
+ {81CB51C4-B434-4E12-B69B-BAEE102F2852}.Release TA.Build.0 = Release TA|Win32
+ {AB424155-FBED-4D8D-B007-5B6CF93EA395}.Debug.ActiveCfg = Debug|Win32
+ {AB424155-FBED-4D8D-B007-5B6CF93EA395}.Debug.Build.0 = Debug|Win32
+ {AB424155-FBED-4D8D-B007-5B6CF93EA395}.Debug TA.ActiveCfg = Debug TA|Win32
+ {AB424155-FBED-4D8D-B007-5B6CF93EA395}.Debug TA.Build.0 = Debug TA|Win32
+ {AB424155-FBED-4D8D-B007-5B6CF93EA395}.Release.ActiveCfg = Release|Win32
+ {AB424155-FBED-4D8D-B007-5B6CF93EA395}.Release.Build.0 = Release|Win32
+ {AB424155-FBED-4D8D-B007-5B6CF93EA395}.Release TA.ActiveCfg = Release TA|Win32
+ {AB424155-FBED-4D8D-B007-5B6CF93EA395}.Release TA.Build.0 = Release TA|Win32
+ {A8EAC38E-C7DA-42F8-811D-77FD092B9D19}.Debug.ActiveCfg = Debug|Win32
+ {A8EAC38E-C7DA-42F8-811D-77FD092B9D19}.Debug TA.ActiveCfg = Debug TA|Win32
+ {A8EAC38E-C7DA-42F8-811D-77FD092B9D19}.Debug TA.Build.0 = Debug TA|Win32
+ {A8EAC38E-C7DA-42F8-811D-77FD092B9D19}.Release.ActiveCfg = Release|Win32
+ {A8EAC38E-C7DA-42F8-811D-77FD092B9D19}.Release TA.ActiveCfg = Release TA|Win32
+ {A8EAC38E-C7DA-42F8-811D-77FD092B9D19}.Release TA.Build.0 = Release TA|Win32
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ EndGlobalSection
+ GlobalSection(ExtensibilityAddIns) = postSolution
+ EndGlobalSection
+EndGlobal
diff --git a/code/quake3.vcproj b/code/quake3.vcproj
new file mode 100755
index 0000000..3a8ca7f
--- /dev/null
+++ b/code/quake3.vcproj
@@ -0,0 +1,3463 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+ ProjectType="Visual C++"
+ Version="7.10"
+ Name="quake3"
+ SccProjectName="&quot;$/MissionPack/code&quot;, CAAAAAAA"
+ SccAuxPath=""
+ SccLocalPath="."
+ SccProvider="MSSCCI:Perforce SCM">
+ <Platforms>
+ <Platform
+ Name="Win32"/>
+ </Platforms>
+ <Configurations>
+ <Configuration
+ Name="Release TA|Win32"
+ OutputDirectory=".\Release_TA"
+ IntermediateDirectory=".\Release_TA"
+ ConfigurationType="1"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="2"
+ OptimizeForProcessor="2"
+ PreprocessorDefinitions="_WIN32;WIN32;NDEBUG;_WINDOWS"
+ StringPooling="TRUE"
+ RuntimeLibrary="4"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Release_TA/quake3.pch"
+ AssemblerListingLocation=".\Release_TA/"
+ ObjectFile=".\Release_TA/"
+ ProgramDataBaseFileName=".\Release_TA/"
+ BrowseInformation="1"
+ WarningLevel="4"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="winmm.lib wsock32.lib"
+ OutputFile=".\Release_TA/quake3.exe"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ ProgramDatabaseFile="Release_TA/quake3.pdb"
+ GenerateMapFile="TRUE"
+ MapFileName="Release_TA/quake3.map"
+ SubSystem="2"
+ StackReserveSize="8388608"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="NDEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\Release_TA/quake3.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"
+ Description="Post build processing.."
+ CommandLine="rem bash -c &quot;perl ./unix/cons -- release-TA&quot;"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Debug|Win32"
+ OutputDirectory=".\Debug"
+ IntermediateDirectory=".\Debug"
+ ConfigurationType="1"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ OptimizeForProcessor="1"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS"
+ RuntimeLibrary="1"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Debug/quake3.pch"
+ AssemblerListingLocation=".\Debug/"
+ ObjectFile=".\Debug/"
+ ProgramDataBaseFileName=".\Debug/"
+ BrowseInformation="1"
+ BrowseInformationFile=".\Debug/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="winmm.lib wsock32.lib"
+ OutputFile=".\Debug/quake3.exe"
+ LinkIncremental="2"
+ SuppressStartupBanner="TRUE"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile=".\Debug/quake3.pdb"
+ GenerateMapFile="TRUE"
+ MapFileName=".\Debug/quake3.map"
+ SubSystem="2"
+ StackReserveSize="8388608"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="_DEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\Debug/quake3.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"
+ Description="Post build processing.."
+ CommandLine="rem bash -c &quot;perl ./unix/cons -- debug&quot;"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"
+ ResourceOutputFileName="win32\winquake.res"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Release TA DEMO|Win32"
+ OutputDirectory=".\quake3___Win32_Release_TA_DEMO"
+ IntermediateDirectory=".\quake3___Win32_Release_TA_DEMO"
+ ConfigurationType="1"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="2"
+ OptimizeForProcessor="2"
+ PreprocessorDefinitions="_WIN32;WIN32;NDEBUG;_WINDOWS;PRE_RELEASE_TADEMO;PRE_RELEASE_DEMO"
+ StringPooling="TRUE"
+ RuntimeLibrary="4"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\quake3___Win32_Release_TA_DEMO/quake3.pch"
+ AssemblerListingLocation=".\quake3___Win32_Release_TA_DEMO/"
+ ObjectFile=".\quake3___Win32_Release_TA_DEMO/"
+ ProgramDataBaseFileName=".\quake3___Win32_Release_TA_DEMO/"
+ WarningLevel="4"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="2"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="winmm.lib wsock32.lib"
+ OutputFile=".\quake3___Win32_Release_TA_DEMO/quake3.exe"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile="Release_TA/quake3.pdb"
+ GenerateMapFile="TRUE"
+ MapFileName="Release_TA/quake3.map"
+ SubSystem="2"
+ StackReserveSize="8388608"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="NDEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\quake3___Win32_Release_TA_DEMO/quake3.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Release|Win32"
+ OutputDirectory=".\Release"
+ IntermediateDirectory=".\Release"
+ ConfigurationType="1"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="2"
+ OptimizeForProcessor="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS"
+ StringPooling="TRUE"
+ RuntimeLibrary="4"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Release/quake3.pch"
+ AssemblerListingLocation=".\Release/"
+ ObjectFile=".\Release/"
+ ProgramDataBaseFileName=".\Release/"
+ WarningLevel="4"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="winmm.lib wsock32.lib"
+ OutputFile=".\Release/quake3.exe"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile=".\Release/quake3.pdb"
+ GenerateMapFile="TRUE"
+ MapFileName=".\Release/quake3.map"
+ SubSystem="2"
+ StackReserveSize="8388608"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="NDEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\Release/quake3.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Debug TA DEMO|Win32"
+ OutputDirectory=".\quake3___Win32_Debug_TA_DEMO"
+ IntermediateDirectory=".\quake3___Win32_Debug_TA_DEMO"
+ ConfigurationType="1"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ OptimizeForProcessor="1"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;PRE_RELEASE_TADEMO;PRE_RELEASE_DEMO"
+ RuntimeLibrary="1"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\quake3___Win32_Debug_TA_DEMO/quake3.pch"
+ AssemblerListingLocation=".\quake3___Win32_Debug_TA_DEMO/"
+ ObjectFile=".\quake3___Win32_Debug_TA_DEMO/"
+ ProgramDataBaseFileName=".\quake3___Win32_Debug_TA_DEMO/"
+ BrowseInformation="1"
+ BrowseInformationFile=".\quake3___Win32_Debug_TA_DEMO/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="winmm.lib wsock32.lib"
+ OutputFile=".\quake3___Win32_Debug_TA_DEMO/quake3.exe"
+ LinkIncremental="2"
+ SuppressStartupBanner="TRUE"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile=".\quake3___Win32_Debug_TA_DEMO/quake3.pdb"
+ GenerateMapFile="TRUE"
+ MapFileName="Debug_TA/quake3.map"
+ SubSystem="2"
+ StackReserveSize="8388608"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="_DEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\quake3___Win32_Debug_TA_DEMO/quake3.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"
+ ResourceOutputFileName="win32\winquake.res"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="vector|Win32"
+ OutputDirectory=".\quake3___Win32_vector0"
+ IntermediateDirectory=".\quake3___Win32_vector0"
+ ConfigurationType="1"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE">
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalOptions="/vec /vec:stats /vec:pii /vec:o10 /vec:yes "
+ Optimization="2"
+ InlineFunctionExpansion="2"
+ OptimizeForProcessor="2"
+ PreprocessorDefinitions="_WIN32;WIN32;NDEBUG;_WINDOWS"
+ StringPooling="TRUE"
+ RuntimeLibrary="4"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\quake3___Win32_vector0/quake3.pch"
+ AssemblerListingLocation=".\quake3___Win32_vector0/"
+ ObjectFile=".\quake3___Win32_vector0/"
+ ProgramDataBaseFileName=".\quake3___Win32_vector0/"
+ WarningLevel="4"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="3"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="winmm.lib wsock32.lib"
+ OutputFile=".\quake3___Win32_vector0/quake3.exe"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile="Release_TA/quake3.pdb"
+ GenerateMapFile="TRUE"
+ MapFileName="Release_TA/quake3.map"
+ SubSystem="2"
+ StackReserveSize="8388608"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="NDEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\quake3___Win32_vector0/quake3.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Debug TA|Win32"
+ OutputDirectory=".\Debug_TA"
+ IntermediateDirectory=".\Debug_TA"
+ ConfigurationType="1"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ OptimizeForProcessor="1"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS"
+ RuntimeLibrary="1"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Debug_TA/quake3.pch"
+ AssemblerListingLocation=".\Debug_TA/"
+ ObjectFile=".\Debug_TA/"
+ ProgramDataBaseFileName=".\Debug_TA/"
+ BrowseInformation="1"
+ BrowseInformationFile=".\Debug_TA/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="winmm.lib wsock32.lib"
+ OutputFile=".\Debug_TA/quake3.exe"
+ LinkIncremental="2"
+ SuppressStartupBanner="TRUE"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile=".\Debug_TA/quake3.pdb"
+ GenerateMapFile="TRUE"
+ MapFileName="Debug_TA/quake3.map"
+ SubSystem="2"
+ StackReserveSize="8388608"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="_DEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\Debug_TA/quake3.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"
+ Description="Post build processing.."
+ CommandLine="rem bash -c &quot;perl ./unix/cons -- debug-TA&quot;"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"
+ ResourceOutputFileName="win32\winquake.res"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ </Configurations>
+ <References>
+ </References>
+ <Files>
+ <Filter
+ Name="Source Files"
+ Filter="cpp;c;cxx;rc;def;r;odl;hpj;bat;for;f90">
+ <File
+ RelativePath="client\cl_cgame.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="client\cl_cin.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="client\cl_console.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="client\cl_input.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="client\cl_keys.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="client\cl_main.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="client\cl_net_chan.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="client\cl_parse.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="client\cl_scrn.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="client\cl_ui.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="qcommon\cm_load.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="qcommon\cm_patch.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="qcommon\cm_polylib.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="qcommon\cm_test.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="qcommon\cm_trace.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="qcommon\cmd.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="qcommon\common.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="qcommon\cvar.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="qcommon\files.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="qcommon\huffman.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="qcommon\md4.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="qcommon\msg.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="qcommon\net_chan.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="game\q_math.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="game\q_shared.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="client\snd_adpcm.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="client\snd_dma.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="client\snd_mem.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="client\snd_mix.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="client\snd_wavelet.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="server\sv_bot.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="server\sv_ccmds.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="server\sv_client.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="server\sv_game.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="server\sv_init.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="server\sv_main.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="server\sv_net_chan.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="server\sv_snapshot.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="server\sv_world.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="qcommon\unzip.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="qcommon\vm.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="qcommon\vm_interpreted.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="qcommon\vm_x86.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="win32\win_input.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="win32\win_main.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="win32\win_net.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="win32\win_shared.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="win32\win_snd.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="win32\win_syscon.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="win32\win_wndproc.c">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <Filter
+ Name="Header Files"
+ Filter="h;hpp;hxx;hm;inl;fi;fd">
+ <File
+ RelativePath="game\bg_public.h">
+ </File>
+ <File
+ RelativePath="cgame\cg_public.h">
+ </File>
+ <File
+ RelativePath="client\client.h">
+ </File>
+ <File
+ RelativePath="qcommon\cm_local.h">
+ </File>
+ <File
+ RelativePath="qcommon\cm_patch.h">
+ </File>
+ <File
+ RelativePath="qcommon\cm_polylib.h">
+ </File>
+ <File
+ RelativePath="qcommon\cm_public.h">
+ </File>
+ <File
+ RelativePath="game\g_public.h">
+ </File>
+ <File
+ RelativePath="ui\keycodes.h">
+ </File>
+ <File
+ RelativePath="client\keys.h">
+ </File>
+ <File
+ RelativePath="game\q_shared.h">
+ </File>
+ <File
+ RelativePath="qcommon\qcommon.h">
+ </File>
+ <File
+ RelativePath="qcommon\qfiles.h">
+ </File>
+ <File
+ RelativePath="renderer\qgl.h">
+ </File>
+ <File
+ RelativePath="win32\resource.h">
+ </File>
+ <File
+ RelativePath="server\server.h">
+ </File>
+ <File
+ RelativePath="client\snd_local.h">
+ </File>
+ <File
+ RelativePath="client\snd_public.h">
+ </File>
+ <File
+ RelativePath="game\surfaceflags.h">
+ </File>
+ <File
+ RelativePath="renderer\tr_local.h">
+ </File>
+ <File
+ RelativePath="renderer\tr_public.h">
+ </File>
+ <File
+ RelativePath="cgame\tr_types.h">
+ </File>
+ <File
+ RelativePath="ui\ui_public.h">
+ </File>
+ <File
+ RelativePath="qcommon\unzip.h">
+ </File>
+ <File
+ RelativePath="qcommon\vm_local.h">
+ </File>
+ <File
+ RelativePath="win32\win_local.h">
+ </File>
+ </Filter>
+ <Filter
+ Name="Resource Files"
+ Filter="ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe">
+ <File
+ RelativePath="win32\cursor2.cur">
+ </File>
+ <File
+ RelativePath="win32\cursor3.cur">
+ </File>
+ <File
+ RelativePath="win32\qe3.ico">
+ </File>
+ <File
+ RelativePath="win32\winquake.rc">
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions=""
+ AdditionalIncludeDirectories="win32"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions=""
+ AdditionalIncludeDirectories="win32"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA DEMO|Win32">
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions=""
+ AdditionalIncludeDirectories="win32"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions=""
+ AdditionalIncludeDirectories="win32"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA DEMO|Win32">
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions=""
+ AdditionalIncludeDirectories="win32"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions=""
+ AdditionalIncludeDirectories="win32"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions=""
+ AdditionalIncludeDirectories="win32"/>
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <File
+ RelativePath="unix\ChangeLog">
+ </File>
+ <File
+ RelativePath="unix\Conscript-pk3">
+ </File>
+ <File
+ RelativePath="Construct">
+ </File>
+ </Files>
+ <Globals>
+ </Globals>
+</VisualStudioProject>
diff --git a/code/renderer.lnt b/code/renderer.lnt
new file mode 100755
index 0000000..3be0efc
--- /dev/null
+++ b/code/renderer.lnt
@@ -0,0 +1,27 @@
+opts.lnt
+
+renderer\tr_bsp.c
+renderer\tr_calc.c
+renderer\tr_calc_c.c
+renderer\tr_curve.c
+renderer\tr_draw.c
+renderer\tr_image.c
+renderer\tr_init.c
+renderer\tr_light.c
+renderer\tr_main.c
+renderer\tr_mesh.c
+renderer\tr_misc.c
+renderer\tr_model.c
+renderer\tr_noise.c
+renderer\tr_shade.c
+renderer\tr_shader.c
+renderer\tr_sky.c
+renderer\tr_stripify.c
+renderer\tr_subdivide.c
+renderer\tr_surf.c
+renderer\tr_world.c
+
+game\q_math.c
+game\q_shared.c
+
+null\null_glimp.c
diff --git a/code/renderer/qgl.h b/code/renderer/qgl.h
new file mode 100755
index 0000000..5087b2e
--- /dev/null
+++ b/code/renderer/qgl.h
@@ -0,0 +1,572 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+/*
+** QGL.H
+*/
+
+#ifndef __QGL_H__
+#define __QGL_H__
+
+#if defined( __LINT__ )
+
+#include <GL/gl.h>
+
+#elif defined( _WIN32 )
+
+#pragma warning (disable: 4201)
+#pragma warning (disable: 4214)
+#pragma warning (disable: 4514)
+#pragma warning (disable: 4032)
+#pragma warning (disable: 4201)
+#pragma warning (disable: 4214)
+#include <windows.h>
+#include <gl/gl.h>
+
+#elif defined(MACOS_X)
+
+#include "macosx_glimp.h"
+
+#elif defined( __linux__ )
+
+#include <GL/gl.h>
+#include <GL/glx.h>
+// bk001129 - from cvs1.17 (mkv)
+#if defined(__FX__)
+#include <GL/fxmesa.h>
+#endif
+
+#elif defined( __FreeBSD__ ) // rb010123
+
+#include <GL/gl.h>
+#include <GL/glx.h>
+#if defined(__FX__)
+#include <GL/fxmesa.h>
+#endif
+
+#else
+
+#include <gl.h>
+
+#endif
+
+#ifndef APIENTRY
+#define APIENTRY
+#endif
+#ifndef WINAPI
+#define WINAPI
+#endif
+
+
+//===========================================================================
+
+/*
+** multitexture extension definitions
+*/
+#define GL_ACTIVE_TEXTURE_ARB 0x84E0
+#define GL_CLIENT_ACTIVE_TEXTURE_ARB 0x84E1
+#define GL_MAX_ACTIVE_TEXTURES_ARB 0x84E2
+
+#define GL_TEXTURE0_ARB 0x84C0
+#define GL_TEXTURE1_ARB 0x84C1
+#define GL_TEXTURE2_ARB 0x84C2
+#define GL_TEXTURE3_ARB 0x84C3
+
+// NOTE: some Linux platforms would need those prototypes
+#if defined(MACOS_X)
+typedef void (APIENTRY * PFNGLMULTITEXCOORD1DARBPROC) (GLenum target, GLdouble s);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD1DVARBPROC) (GLenum target, const GLdouble *v);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD1FARBPROC) (GLenum target, GLfloat s);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD1FVARBPROC) (GLenum target, const GLfloat *v);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD1IARBPROC) (GLenum target, GLint s);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD1IVARBPROC) (GLenum target, const GLint *v);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD1SARBPROC) (GLenum target, GLshort s);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD1SVARBPROC) (GLenum target, const GLshort *v);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD2DARBPROC) (GLenum target, GLdouble s, GLdouble t);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD2DVARBPROC) (GLenum target, const GLdouble *v);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD2FARBPROC) (GLenum target, GLfloat s, GLfloat t);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD2FVARBPROC) (GLenum target, const GLfloat *v);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD2IARBPROC) (GLenum target, GLint s, GLint t);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD2IVARBPROC) (GLenum target, const GLint *v);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD2SARBPROC) (GLenum target, GLshort s, GLshort t);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD2SVARBPROC) (GLenum target, const GLshort *v);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD3DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD3DVARBPROC) (GLenum target, const GLdouble *v);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD3FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD3FVARBPROC) (GLenum target, const GLfloat *v);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD3IARBPROC) (GLenum target, GLint s, GLint t, GLint r);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD3IVARBPROC) (GLenum target, const GLint *v);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD3SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD3SVARBPROC) (GLenum target, const GLshort *v);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD4DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD4DVARBPROC) (GLenum target, const GLdouble *v);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD4FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD4FVARBPROC) (GLenum target, const GLfloat *v);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD4IARBPROC) (GLenum target, GLint s, GLint t, GLint r, GLint q);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD4IVARBPROC) (GLenum target, const GLint *v);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD4SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q);
+typedef void (APIENTRY * PFNGLMULTITEXCOORD4SVARBPROC) (GLenum target, const GLshort *v);
+typedef void (APIENTRY * PFNGLACTIVETEXTUREARBPROC) (GLenum target);
+typedef void (APIENTRY * PFNGLCLIENTACTIVETEXTUREARBPROC) (GLenum target);
+#endif
+
+// TTimo - VC7 / XP ?
+#ifdef WIN32
+typedef void (APIENTRY * PFNGLMULTITEXCOORD2FARBPROC) (GLenum target, GLfloat s, GLfloat t);
+typedef void (APIENTRY * PFNGLACTIVETEXTUREARBPROC) (GLenum target);
+typedef void (APIENTRY * PFNGLCLIENTACTIVETEXTUREARBPROC) (GLenum target);
+#endif
+
+/*
+** extension constants
+*/
+
+
+// S3TC compression constants
+#define GL_RGB_S3TC 0x83A0
+#define GL_RGB4_S3TC 0x83A1
+
+
+// extensions will be function pointers on all platforms
+
+extern void ( APIENTRY * qglMultiTexCoord2fARB )( GLenum texture, GLfloat s, GLfloat t );
+extern void ( APIENTRY * qglActiveTextureARB )( GLenum texture );
+extern void ( APIENTRY * qglClientActiveTextureARB )( GLenum texture );
+
+extern void ( APIENTRY * qglLockArraysEXT) (GLint, GLint);
+extern void ( APIENTRY * qglUnlockArraysEXT) (void);
+
+//===========================================================================
+
+// non-windows systems will just redefine qgl* to gl*
+#if !defined( _WIN32 ) && !defined(MACOS_X) && !defined( __linux__ ) && !defined( __FreeBSD__ ) // rb010123
+
+#include "qgl_linked.h"
+
+#elif defined(MACOS_X)
+// This includes #ifdefs for optional logging and GL error checking after every GL call as well as #defines to prevent incorrect usage of the non-'qgl' versions of the GL API.
+#include "macosx_qgl.h"
+
+#else
+
+// windows systems use a function pointer for each call so we can load minidrivers
+
+extern void ( APIENTRY * qglAccum )(GLenum op, GLfloat value);
+extern void ( APIENTRY * qglAlphaFunc )(GLenum func, GLclampf ref);
+extern GLboolean ( APIENTRY * qglAreTexturesResident )(GLsizei n, const GLuint *textures, GLboolean *residences);
+extern void ( APIENTRY * qglArrayElement )(GLint i);
+extern void ( APIENTRY * qglBegin )(GLenum mode);
+extern void ( APIENTRY * qglBindTexture )(GLenum target, GLuint texture);
+extern void ( APIENTRY * qglBitmap )(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap);
+extern void ( APIENTRY * qglBlendFunc )(GLenum sfactor, GLenum dfactor);
+extern void ( APIENTRY * qglCallList )(GLuint list);
+extern void ( APIENTRY * qglCallLists )(GLsizei n, GLenum type, const GLvoid *lists);
+extern void ( APIENTRY * qglClear )(GLbitfield mask);
+extern void ( APIENTRY * qglClearAccum )(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+extern void ( APIENTRY * qglClearColor )(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+extern void ( APIENTRY * qglClearDepth )(GLclampd depth);
+extern void ( APIENTRY * qglClearIndex )(GLfloat c);
+extern void ( APIENTRY * qglClearStencil )(GLint s);
+extern void ( APIENTRY * qglClipPlane )(GLenum plane, const GLdouble *equation);
+extern void ( APIENTRY * qglColor3b )(GLbyte red, GLbyte green, GLbyte blue);
+extern void ( APIENTRY * qglColor3bv )(const GLbyte *v);
+extern void ( APIENTRY * qglColor3d )(GLdouble red, GLdouble green, GLdouble blue);
+extern void ( APIENTRY * qglColor3dv )(const GLdouble *v);
+extern void ( APIENTRY * qglColor3f )(GLfloat red, GLfloat green, GLfloat blue);
+extern void ( APIENTRY * qglColor3fv )(const GLfloat *v);
+extern void ( APIENTRY * qglColor3i )(GLint red, GLint green, GLint blue);
+extern void ( APIENTRY * qglColor3iv )(const GLint *v);
+extern void ( APIENTRY * qglColor3s )(GLshort red, GLshort green, GLshort blue);
+extern void ( APIENTRY * qglColor3sv )(const GLshort *v);
+extern void ( APIENTRY * qglColor3ub )(GLubyte red, GLubyte green, GLubyte blue);
+extern void ( APIENTRY * qglColor3ubv )(const GLubyte *v);
+extern void ( APIENTRY * qglColor3ui )(GLuint red, GLuint green, GLuint blue);
+extern void ( APIENTRY * qglColor3uiv )(const GLuint *v);
+extern void ( APIENTRY * qglColor3us )(GLushort red, GLushort green, GLushort blue);
+extern void ( APIENTRY * qglColor3usv )(const GLushort *v);
+extern void ( APIENTRY * qglColor4b )(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha);
+extern void ( APIENTRY * qglColor4bv )(const GLbyte *v);
+extern void ( APIENTRY * qglColor4d )(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha);
+extern void ( APIENTRY * qglColor4dv )(const GLdouble *v);
+extern void ( APIENTRY * qglColor4f )(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+extern void ( APIENTRY * qglColor4fv )(const GLfloat *v);
+extern void ( APIENTRY * qglColor4i )(GLint red, GLint green, GLint blue, GLint alpha);
+extern void ( APIENTRY * qglColor4iv )(const GLint *v);
+extern void ( APIENTRY * qglColor4s )(GLshort red, GLshort green, GLshort blue, GLshort alpha);
+extern void ( APIENTRY * qglColor4sv )(const GLshort *v);
+extern void ( APIENTRY * qglColor4ub )(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha);
+extern void ( APIENTRY * qglColor4ubv )(const GLubyte *v);
+extern void ( APIENTRY * qglColor4ui )(GLuint red, GLuint green, GLuint blue, GLuint alpha);
+extern void ( APIENTRY * qglColor4uiv )(const GLuint *v);
+extern void ( APIENTRY * qglColor4us )(GLushort red, GLushort green, GLushort blue, GLushort alpha);
+extern void ( APIENTRY * qglColor4usv )(const GLushort *v);
+extern void ( APIENTRY * qglColorMask )(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
+extern void ( APIENTRY * qglColorMaterial )(GLenum face, GLenum mode);
+extern void ( APIENTRY * qglColorPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+extern void ( APIENTRY * qglCopyPixels )(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type);
+extern void ( APIENTRY * qglCopyTexImage1D )(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLint border);
+extern void ( APIENTRY * qglCopyTexImage2D )(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+extern void ( APIENTRY * qglCopyTexSubImage1D )(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
+extern void ( APIENTRY * qglCopyTexSubImage2D )(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+extern void ( APIENTRY * qglCullFace )(GLenum mode);
+extern void ( APIENTRY * qglDeleteLists )(GLuint list, GLsizei range);
+extern void ( APIENTRY * qglDeleteTextures )(GLsizei n, const GLuint *textures);
+extern void ( APIENTRY * qglDepthFunc )(GLenum func);
+extern void ( APIENTRY * qglDepthMask )(GLboolean flag);
+extern void ( APIENTRY * qglDepthRange )(GLclampd zNear, GLclampd zFar);
+extern void ( APIENTRY * qglDisable )(GLenum cap);
+extern void ( APIENTRY * qglDisableClientState )(GLenum array);
+extern void ( APIENTRY * qglDrawArrays )(GLenum mode, GLint first, GLsizei count);
+extern void ( APIENTRY * qglDrawBuffer )(GLenum mode);
+extern void ( APIENTRY * qglDrawElements )(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices);
+extern void ( APIENTRY * qglDrawPixels )(GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+extern void ( APIENTRY * qglEdgeFlag )(GLboolean flag);
+extern void ( APIENTRY * qglEdgeFlagPointer )(GLsizei stride, const GLvoid *pointer);
+extern void ( APIENTRY * qglEdgeFlagv )(const GLboolean *flag);
+extern void ( APIENTRY * qglEnable )(GLenum cap);
+extern void ( APIENTRY * qglEnableClientState )(GLenum array);
+extern void ( APIENTRY * qglEnd )(void);
+extern void ( APIENTRY * qglEndList )(void);
+extern void ( APIENTRY * qglEvalCoord1d )(GLdouble u);
+extern void ( APIENTRY * qglEvalCoord1dv )(const GLdouble *u);
+extern void ( APIENTRY * qglEvalCoord1f )(GLfloat u);
+extern void ( APIENTRY * qglEvalCoord1fv )(const GLfloat *u);
+extern void ( APIENTRY * qglEvalCoord2d )(GLdouble u, GLdouble v);
+extern void ( APIENTRY * qglEvalCoord2dv )(const GLdouble *u);
+extern void ( APIENTRY * qglEvalCoord2f )(GLfloat u, GLfloat v);
+extern void ( APIENTRY * qglEvalCoord2fv )(const GLfloat *u);
+extern void ( APIENTRY * qglEvalMesh1 )(GLenum mode, GLint i1, GLint i2);
+extern void ( APIENTRY * qglEvalMesh2 )(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2);
+extern void ( APIENTRY * qglEvalPoint1 )(GLint i);
+extern void ( APIENTRY * qglEvalPoint2 )(GLint i, GLint j);
+extern void ( APIENTRY * qglFeedbackBuffer )(GLsizei size, GLenum type, GLfloat *buffer);
+extern void ( APIENTRY * qglFinish )(void);
+extern void ( APIENTRY * qglFlush )(void);
+extern void ( APIENTRY * qglFogf )(GLenum pname, GLfloat param);
+extern void ( APIENTRY * qglFogfv )(GLenum pname, const GLfloat *params);
+extern void ( APIENTRY * qglFogi )(GLenum pname, GLint param);
+extern void ( APIENTRY * qglFogiv )(GLenum pname, const GLint *params);
+extern void ( APIENTRY * qglFrontFace )(GLenum mode);
+extern void ( APIENTRY * qglFrustum )(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+extern GLuint ( APIENTRY * qglGenLists )(GLsizei range);
+extern void ( APIENTRY * qglGenTextures )(GLsizei n, GLuint *textures);
+extern void ( APIENTRY * qglGetBooleanv )(GLenum pname, GLboolean *params);
+extern void ( APIENTRY * qglGetClipPlane )(GLenum plane, GLdouble *equation);
+extern void ( APIENTRY * qglGetDoublev )(GLenum pname, GLdouble *params);
+extern GLenum ( APIENTRY * qglGetError )(void);
+extern void ( APIENTRY * qglGetFloatv )(GLenum pname, GLfloat *params);
+extern void ( APIENTRY * qglGetIntegerv )(GLenum pname, GLint *params);
+extern void ( APIENTRY * qglGetLightfv )(GLenum light, GLenum pname, GLfloat *params);
+extern void ( APIENTRY * qglGetLightiv )(GLenum light, GLenum pname, GLint *params);
+extern void ( APIENTRY * qglGetMapdv )(GLenum target, GLenum query, GLdouble *v);
+extern void ( APIENTRY * qglGetMapfv )(GLenum target, GLenum query, GLfloat *v);
+extern void ( APIENTRY * qglGetMapiv )(GLenum target, GLenum query, GLint *v);
+extern void ( APIENTRY * qglGetMaterialfv )(GLenum face, GLenum pname, GLfloat *params);
+extern void ( APIENTRY * qglGetMaterialiv )(GLenum face, GLenum pname, GLint *params);
+extern void ( APIENTRY * qglGetPixelMapfv )(GLenum map, GLfloat *values);
+extern void ( APIENTRY * qglGetPixelMapuiv )(GLenum map, GLuint *values);
+extern void ( APIENTRY * qglGetPixelMapusv )(GLenum map, GLushort *values);
+extern void ( APIENTRY * qglGetPointerv )(GLenum pname, GLvoid* *params);
+extern void ( APIENTRY * qglGetPolygonStipple )(GLubyte *mask);
+extern const GLubyte * ( APIENTRY * qglGetString )(GLenum name);
+extern void ( APIENTRY * qglGetTexEnvfv )(GLenum target, GLenum pname, GLfloat *params);
+extern void ( APIENTRY * qglGetTexEnviv )(GLenum target, GLenum pname, GLint *params);
+extern void ( APIENTRY * qglGetTexGendv )(GLenum coord, GLenum pname, GLdouble *params);
+extern void ( APIENTRY * qglGetTexGenfv )(GLenum coord, GLenum pname, GLfloat *params);
+extern void ( APIENTRY * qglGetTexGeniv )(GLenum coord, GLenum pname, GLint *params);
+extern void ( APIENTRY * qglGetTexImage )(GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels);
+extern void ( APIENTRY * qglGetTexLevelParameterfv )(GLenum target, GLint level, GLenum pname, GLfloat *params);
+extern void ( APIENTRY * qglGetTexLevelParameteriv )(GLenum target, GLint level, GLenum pname, GLint *params);
+extern void ( APIENTRY * qglGetTexParameterfv )(GLenum target, GLenum pname, GLfloat *params);
+extern void ( APIENTRY * qglGetTexParameteriv )(GLenum target, GLenum pname, GLint *params);
+extern void ( APIENTRY * qglHint )(GLenum target, GLenum mode);
+extern void ( APIENTRY * qglIndexMask )(GLuint mask);
+extern void ( APIENTRY * qglIndexPointer )(GLenum type, GLsizei stride, const GLvoid *pointer);
+extern void ( APIENTRY * qglIndexd )(GLdouble c);
+extern void ( APIENTRY * qglIndexdv )(const GLdouble *c);
+extern void ( APIENTRY * qglIndexf )(GLfloat c);
+extern void ( APIENTRY * qglIndexfv )(const GLfloat *c);
+extern void ( APIENTRY * qglIndexi )(GLint c);
+extern void ( APIENTRY * qglIndexiv )(const GLint *c);
+extern void ( APIENTRY * qglIndexs )(GLshort c);
+extern void ( APIENTRY * qglIndexsv )(const GLshort *c);
+extern void ( APIENTRY * qglIndexub )(GLubyte c);
+extern void ( APIENTRY * qglIndexubv )(const GLubyte *c);
+extern void ( APIENTRY * qglInitNames )(void);
+extern void ( APIENTRY * qglInterleavedArrays )(GLenum format, GLsizei stride, const GLvoid *pointer);
+extern GLboolean ( APIENTRY * qglIsEnabled )(GLenum cap);
+extern GLboolean ( APIENTRY * qglIsList )(GLuint list);
+extern GLboolean ( APIENTRY * qglIsTexture )(GLuint texture);
+extern void ( APIENTRY * qglLightModelf )(GLenum pname, GLfloat param);
+extern void ( APIENTRY * qglLightModelfv )(GLenum pname, const GLfloat *params);
+extern void ( APIENTRY * qglLightModeli )(GLenum pname, GLint param);
+extern void ( APIENTRY * qglLightModeliv )(GLenum pname, const GLint *params);
+extern void ( APIENTRY * qglLightf )(GLenum light, GLenum pname, GLfloat param);
+extern void ( APIENTRY * qglLightfv )(GLenum light, GLenum pname, const GLfloat *params);
+extern void ( APIENTRY * qglLighti )(GLenum light, GLenum pname, GLint param);
+extern void ( APIENTRY * qglLightiv )(GLenum light, GLenum pname, const GLint *params);
+extern void ( APIENTRY * qglLineStipple )(GLint factor, GLushort pattern);
+extern void ( APIENTRY * qglLineWidth )(GLfloat width);
+extern void ( APIENTRY * qglListBase )(GLuint base);
+extern void ( APIENTRY * qglLoadIdentity )(void);
+extern void ( APIENTRY * qglLoadMatrixd )(const GLdouble *m);
+extern void ( APIENTRY * qglLoadMatrixf )(const GLfloat *m);
+extern void ( APIENTRY * qglLoadName )(GLuint name);
+extern void ( APIENTRY * qglLogicOp )(GLenum opcode);
+extern void ( APIENTRY * qglMap1d )(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points);
+extern void ( APIENTRY * qglMap1f )(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points);
+extern void ( APIENTRY * qglMap2d )(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points);
+extern void ( APIENTRY * qglMap2f )(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points);
+extern void ( APIENTRY * qglMapGrid1d )(GLint un, GLdouble u1, GLdouble u2);
+extern void ( APIENTRY * qglMapGrid1f )(GLint un, GLfloat u1, GLfloat u2);
+extern void ( APIENTRY * qglMapGrid2d )(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2);
+extern void ( APIENTRY * qglMapGrid2f )(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2);
+extern void ( APIENTRY * qglMaterialf )(GLenum face, GLenum pname, GLfloat param);
+extern void ( APIENTRY * qglMaterialfv )(GLenum face, GLenum pname, const GLfloat *params);
+extern void ( APIENTRY * qglMateriali )(GLenum face, GLenum pname, GLint param);
+extern void ( APIENTRY * qglMaterialiv )(GLenum face, GLenum pname, const GLint *params);
+extern void ( APIENTRY * qglMatrixMode )(GLenum mode);
+extern void ( APIENTRY * qglMultMatrixd )(const GLdouble *m);
+extern void ( APIENTRY * qglMultMatrixf )(const GLfloat *m);
+extern void ( APIENTRY * qglNewList )(GLuint list, GLenum mode);
+extern void ( APIENTRY * qglNormal3b )(GLbyte nx, GLbyte ny, GLbyte nz);
+extern void ( APIENTRY * qglNormal3bv )(const GLbyte *v);
+extern void ( APIENTRY * qglNormal3d )(GLdouble nx, GLdouble ny, GLdouble nz);
+extern void ( APIENTRY * qglNormal3dv )(const GLdouble *v);
+extern void ( APIENTRY * qglNormal3f )(GLfloat nx, GLfloat ny, GLfloat nz);
+extern void ( APIENTRY * qglNormal3fv )(const GLfloat *v);
+extern void ( APIENTRY * qglNormal3i )(GLint nx, GLint ny, GLint nz);
+extern void ( APIENTRY * qglNormal3iv )(const GLint *v);
+extern void ( APIENTRY * qglNormal3s )(GLshort nx, GLshort ny, GLshort nz);
+extern void ( APIENTRY * qglNormal3sv )(const GLshort *v);
+extern void ( APIENTRY * qglNormalPointer )(GLenum type, GLsizei stride, const GLvoid *pointer);
+extern void ( APIENTRY * qglOrtho )(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+extern void ( APIENTRY * qglPassThrough )(GLfloat token);
+extern void ( APIENTRY * qglPixelMapfv )(GLenum map, GLsizei mapsize, const GLfloat *values);
+extern void ( APIENTRY * qglPixelMapuiv )(GLenum map, GLsizei mapsize, const GLuint *values);
+extern void ( APIENTRY * qglPixelMapusv )(GLenum map, GLsizei mapsize, const GLushort *values);
+extern void ( APIENTRY * qglPixelStoref )(GLenum pname, GLfloat param);
+extern void ( APIENTRY * qglPixelStorei )(GLenum pname, GLint param);
+extern void ( APIENTRY * qglPixelTransferf )(GLenum pname, GLfloat param);
+extern void ( APIENTRY * qglPixelTransferi )(GLenum pname, GLint param);
+extern void ( APIENTRY * qglPixelZoom )(GLfloat xfactor, GLfloat yfactor);
+extern void ( APIENTRY * qglPointSize )(GLfloat size);
+extern void ( APIENTRY * qglPolygonMode )(GLenum face, GLenum mode);
+extern void ( APIENTRY * qglPolygonOffset )(GLfloat factor, GLfloat units);
+extern void ( APIENTRY * qglPolygonStipple )(const GLubyte *mask);
+extern void ( APIENTRY * qglPopAttrib )(void);
+extern void ( APIENTRY * qglPopClientAttrib )(void);
+extern void ( APIENTRY * qglPopMatrix )(void);
+extern void ( APIENTRY * qglPopName )(void);
+extern void ( APIENTRY * qglPrioritizeTextures )(GLsizei n, const GLuint *textures, const GLclampf *priorities);
+extern void ( APIENTRY * qglPushAttrib )(GLbitfield mask);
+extern void ( APIENTRY * qglPushClientAttrib )(GLbitfield mask);
+extern void ( APIENTRY * qglPushMatrix )(void);
+extern void ( APIENTRY * qglPushName )(GLuint name);
+extern void ( APIENTRY * qglRasterPos2d )(GLdouble x, GLdouble y);
+extern void ( APIENTRY * qglRasterPos2dv )(const GLdouble *v);
+extern void ( APIENTRY * qglRasterPos2f )(GLfloat x, GLfloat y);
+extern void ( APIENTRY * qglRasterPos2fv )(const GLfloat *v);
+extern void ( APIENTRY * qglRasterPos2i )(GLint x, GLint y);
+extern void ( APIENTRY * qglRasterPos2iv )(const GLint *v);
+extern void ( APIENTRY * qglRasterPos2s )(GLshort x, GLshort y);
+extern void ( APIENTRY * qglRasterPos2sv )(const GLshort *v);
+extern void ( APIENTRY * qglRasterPos3d )(GLdouble x, GLdouble y, GLdouble z);
+extern void ( APIENTRY * qglRasterPos3dv )(const GLdouble *v);
+extern void ( APIENTRY * qglRasterPos3f )(GLfloat x, GLfloat y, GLfloat z);
+extern void ( APIENTRY * qglRasterPos3fv )(const GLfloat *v);
+extern void ( APIENTRY * qglRasterPos3i )(GLint x, GLint y, GLint z);
+extern void ( APIENTRY * qglRasterPos3iv )(const GLint *v);
+extern void ( APIENTRY * qglRasterPos3s )(GLshort x, GLshort y, GLshort z);
+extern void ( APIENTRY * qglRasterPos3sv )(const GLshort *v);
+extern void ( APIENTRY * qglRasterPos4d )(GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+extern void ( APIENTRY * qglRasterPos4dv )(const GLdouble *v);
+extern void ( APIENTRY * qglRasterPos4f )(GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+extern void ( APIENTRY * qglRasterPos4fv )(const GLfloat *v);
+extern void ( APIENTRY * qglRasterPos4i )(GLint x, GLint y, GLint z, GLint w);
+extern void ( APIENTRY * qglRasterPos4iv )(const GLint *v);
+extern void ( APIENTRY * qglRasterPos4s )(GLshort x, GLshort y, GLshort z, GLshort w);
+extern void ( APIENTRY * qglRasterPos4sv )(const GLshort *v);
+extern void ( APIENTRY * qglReadBuffer )(GLenum mode);
+extern void ( APIENTRY * qglReadPixels )(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels);
+extern void ( APIENTRY * qglRectd )(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2);
+extern void ( APIENTRY * qglRectdv )(const GLdouble *v1, const GLdouble *v2);
+extern void ( APIENTRY * qglRectf )(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2);
+extern void ( APIENTRY * qglRectfv )(const GLfloat *v1, const GLfloat *v2);
+extern void ( APIENTRY * qglRecti )(GLint x1, GLint y1, GLint x2, GLint y2);
+extern void ( APIENTRY * qglRectiv )(const GLint *v1, const GLint *v2);
+extern void ( APIENTRY * qglRects )(GLshort x1, GLshort y1, GLshort x2, GLshort y2);
+extern void ( APIENTRY * qglRectsv )(const GLshort *v1, const GLshort *v2);
+extern GLint ( APIENTRY * qglRenderMode )(GLenum mode);
+extern void ( APIENTRY * qglRotated )(GLdouble angle, GLdouble x, GLdouble y, GLdouble z);
+extern void ( APIENTRY * qglRotatef )(GLfloat angle, GLfloat x, GLfloat y, GLfloat z);
+extern void ( APIENTRY * qglScaled )(GLdouble x, GLdouble y, GLdouble z);
+extern void ( APIENTRY * qglScalef )(GLfloat x, GLfloat y, GLfloat z);
+extern void ( APIENTRY * qglScissor )(GLint x, GLint y, GLsizei width, GLsizei height);
+extern void ( APIENTRY * qglSelectBuffer )(GLsizei size, GLuint *buffer);
+extern void ( APIENTRY * qglShadeModel )(GLenum mode);
+extern void ( APIENTRY * qglStencilFunc )(GLenum func, GLint ref, GLuint mask);
+extern void ( APIENTRY * qglStencilMask )(GLuint mask);
+extern void ( APIENTRY * qglStencilOp )(GLenum fail, GLenum zfail, GLenum zpass);
+extern void ( APIENTRY * qglTexCoord1d )(GLdouble s);
+extern void ( APIENTRY * qglTexCoord1dv )(const GLdouble *v);
+extern void ( APIENTRY * qglTexCoord1f )(GLfloat s);
+extern void ( APIENTRY * qglTexCoord1fv )(const GLfloat *v);
+extern void ( APIENTRY * qglTexCoord1i )(GLint s);
+extern void ( APIENTRY * qglTexCoord1iv )(const GLint *v);
+extern void ( APIENTRY * qglTexCoord1s )(GLshort s);
+extern void ( APIENTRY * qglTexCoord1sv )(const GLshort *v);
+extern void ( APIENTRY * qglTexCoord2d )(GLdouble s, GLdouble t);
+extern void ( APIENTRY * qglTexCoord2dv )(const GLdouble *v);
+extern void ( APIENTRY * qglTexCoord2f )(GLfloat s, GLfloat t);
+extern void ( APIENTRY * qglTexCoord2fv )(const GLfloat *v);
+extern void ( APIENTRY * qglTexCoord2i )(GLint s, GLint t);
+extern void ( APIENTRY * qglTexCoord2iv )(const GLint *v);
+extern void ( APIENTRY * qglTexCoord2s )(GLshort s, GLshort t);
+extern void ( APIENTRY * qglTexCoord2sv )(const GLshort *v);
+extern void ( APIENTRY * qglTexCoord3d )(GLdouble s, GLdouble t, GLdouble r);
+extern void ( APIENTRY * qglTexCoord3dv )(const GLdouble *v);
+extern void ( APIENTRY * qglTexCoord3f )(GLfloat s, GLfloat t, GLfloat r);
+extern void ( APIENTRY * qglTexCoord3fv )(const GLfloat *v);
+extern void ( APIENTRY * qglTexCoord3i )(GLint s, GLint t, GLint r);
+extern void ( APIENTRY * qglTexCoord3iv )(const GLint *v);
+extern void ( APIENTRY * qglTexCoord3s )(GLshort s, GLshort t, GLshort r);
+extern void ( APIENTRY * qglTexCoord3sv )(const GLshort *v);
+extern void ( APIENTRY * qglTexCoord4d )(GLdouble s, GLdouble t, GLdouble r, GLdouble q);
+extern void ( APIENTRY * qglTexCoord4dv )(const GLdouble *v);
+extern void ( APIENTRY * qglTexCoord4f )(GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+extern void ( APIENTRY * qglTexCoord4fv )(const GLfloat *v);
+extern void ( APIENTRY * qglTexCoord4i )(GLint s, GLint t, GLint r, GLint q);
+extern void ( APIENTRY * qglTexCoord4iv )(const GLint *v);
+extern void ( APIENTRY * qglTexCoord4s )(GLshort s, GLshort t, GLshort r, GLshort q);
+extern void ( APIENTRY * qglTexCoord4sv )(const GLshort *v);
+extern void ( APIENTRY * qglTexCoordPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+extern void ( APIENTRY * qglTexEnvf )(GLenum target, GLenum pname, GLfloat param);
+extern void ( APIENTRY * qglTexEnvfv )(GLenum target, GLenum pname, const GLfloat *params);
+extern void ( APIENTRY * qglTexEnvi )(GLenum target, GLenum pname, GLint param);
+extern void ( APIENTRY * qglTexEnviv )(GLenum target, GLenum pname, const GLint *params);
+extern void ( APIENTRY * qglTexGend )(GLenum coord, GLenum pname, GLdouble param);
+extern void ( APIENTRY * qglTexGendv )(GLenum coord, GLenum pname, const GLdouble *params);
+extern void ( APIENTRY * qglTexGenf )(GLenum coord, GLenum pname, GLfloat param);
+extern void ( APIENTRY * qglTexGenfv )(GLenum coord, GLenum pname, const GLfloat *params);
+extern void ( APIENTRY * qglTexGeni )(GLenum coord, GLenum pname, GLint param);
+extern void ( APIENTRY * qglTexGeniv )(GLenum coord, GLenum pname, const GLint *params);
+extern void ( APIENTRY * qglTexImage1D )(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+extern void ( APIENTRY * qglTexImage2D )(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+extern void ( APIENTRY * qglTexParameterf )(GLenum target, GLenum pname, GLfloat param);
+extern void ( APIENTRY * qglTexParameterfv )(GLenum target, GLenum pname, const GLfloat *params);
+extern void ( APIENTRY * qglTexParameteri )(GLenum target, GLenum pname, GLint param);
+extern void ( APIENTRY * qglTexParameteriv )(GLenum target, GLenum pname, const GLint *params);
+extern void ( APIENTRY * qglTexSubImage1D )(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels);
+extern void ( APIENTRY * qglTexSubImage2D )(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+extern void ( APIENTRY * qglTranslated )(GLdouble x, GLdouble y, GLdouble z);
+extern void ( APIENTRY * qglTranslatef )(GLfloat x, GLfloat y, GLfloat z);
+extern void ( APIENTRY * qglVertex2d )(GLdouble x, GLdouble y);
+extern void ( APIENTRY * qglVertex2dv )(const GLdouble *v);
+extern void ( APIENTRY * qglVertex2f )(GLfloat x, GLfloat y);
+extern void ( APIENTRY * qglVertex2fv )(const GLfloat *v);
+extern void ( APIENTRY * qglVertex2i )(GLint x, GLint y);
+extern void ( APIENTRY * qglVertex2iv )(const GLint *v);
+extern void ( APIENTRY * qglVertex2s )(GLshort x, GLshort y);
+extern void ( APIENTRY * qglVertex2sv )(const GLshort *v);
+extern void ( APIENTRY * qglVertex3d )(GLdouble x, GLdouble y, GLdouble z);
+extern void ( APIENTRY * qglVertex3dv )(const GLdouble *v);
+extern void ( APIENTRY * qglVertex3f )(GLfloat x, GLfloat y, GLfloat z);
+extern void ( APIENTRY * qglVertex3fv )(const GLfloat *v);
+extern void ( APIENTRY * qglVertex3i )(GLint x, GLint y, GLint z);
+extern void ( APIENTRY * qglVertex3iv )(const GLint *v);
+extern void ( APIENTRY * qglVertex3s )(GLshort x, GLshort y, GLshort z);
+extern void ( APIENTRY * qglVertex3sv )(const GLshort *v);
+extern void ( APIENTRY * qglVertex4d )(GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+extern void ( APIENTRY * qglVertex4dv )(const GLdouble *v);
+extern void ( APIENTRY * qglVertex4f )(GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+extern void ( APIENTRY * qglVertex4fv )(const GLfloat *v);
+extern void ( APIENTRY * qglVertex4i )(GLint x, GLint y, GLint z, GLint w);
+extern void ( APIENTRY * qglVertex4iv )(const GLint *v);
+extern void ( APIENTRY * qglVertex4s )(GLshort x, GLshort y, GLshort z, GLshort w);
+extern void ( APIENTRY * qglVertex4sv )(const GLshort *v);
+extern void ( APIENTRY * qglVertexPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+extern void ( APIENTRY * qglViewport )(GLint x, GLint y, GLsizei width, GLsizei height);
+
+#if defined( _WIN32 )
+
+extern int ( WINAPI * qwglChoosePixelFormat )(HDC, CONST PIXELFORMATDESCRIPTOR *);
+extern int ( WINAPI * qwglDescribePixelFormat) (HDC, int, UINT, LPPIXELFORMATDESCRIPTOR);
+extern int ( WINAPI * qwglGetPixelFormat)(HDC);
+extern BOOL ( WINAPI * qwglSetPixelFormat)(HDC, int, CONST PIXELFORMATDESCRIPTOR *);
+extern BOOL ( WINAPI * qwglSwapBuffers)(HDC);
+
+extern BOOL ( WINAPI * qwglGetDeviceGammaRamp3DFX)( HDC, LPVOID );
+extern BOOL ( WINAPI * qwglSetDeviceGammaRamp3DFX)( HDC, LPVOID );
+
+extern BOOL ( WINAPI * qwglCopyContext)(HGLRC, HGLRC, UINT);
+extern HGLRC ( WINAPI * qwglCreateContext)(HDC);
+extern HGLRC ( WINAPI * qwglCreateLayerContext)(HDC, int);
+extern BOOL ( WINAPI * qwglDeleteContext)(HGLRC);
+extern HGLRC ( WINAPI * qwglGetCurrentContext)(VOID);
+extern HDC ( WINAPI * qwglGetCurrentDC)(VOID);
+extern PROC ( WINAPI * qwglGetProcAddress)(LPCSTR);
+extern BOOL ( WINAPI * qwglMakeCurrent)(HDC, HGLRC);
+extern BOOL ( WINAPI * qwglShareLists)(HGLRC, HGLRC);
+extern BOOL ( WINAPI * qwglUseFontBitmaps)(HDC, DWORD, DWORD, DWORD);
+
+extern BOOL ( WINAPI * qwglUseFontOutlines)(HDC, DWORD, DWORD, DWORD, FLOAT,
+ FLOAT, int, LPGLYPHMETRICSFLOAT);
+
+extern BOOL ( WINAPI * qwglDescribeLayerPlane)(HDC, int, int, UINT,
+ LPLAYERPLANEDESCRIPTOR);
+extern int ( WINAPI * qwglSetLayerPaletteEntries)(HDC, int, int, int,
+ CONST COLORREF *);
+extern int ( WINAPI * qwglGetLayerPaletteEntries)(HDC, int, int, int,
+ COLORREF *);
+extern BOOL ( WINAPI * qwglRealizeLayerPalette)(HDC, int, BOOL);
+extern BOOL ( WINAPI * qwglSwapLayerBuffers)(HDC, UINT);
+
+extern BOOL ( WINAPI * qwglSwapIntervalEXT)( int interval );
+
+#endif // _WIN32
+
+#if ( (defined __linux__ ) || (defined __FreeBSD__ ) ) // rb010123
+
+//FX Mesa Functions
+// bk001129 - from cvs1.17 (mkv)
+#if defined (__FX__)
+extern fxMesaContext (*qfxMesaCreateContext)(GLuint win, GrScreenResolution_t, GrScreenRefresh_t, const GLint attribList[]);
+extern fxMesaContext (*qfxMesaCreateBestContext)(GLuint win, GLint width, GLint height, const GLint attribList[]);
+extern void (*qfxMesaDestroyContext)(fxMesaContext ctx);
+extern void (*qfxMesaMakeCurrent)(fxMesaContext ctx);
+extern fxMesaContext (*qfxMesaGetCurrentContext)(void);
+extern void (*qfxMesaSwapBuffers)(void);
+#endif
+
+//GLX Functions
+extern XVisualInfo * (*qglXChooseVisual)( Display *dpy, int screen, int *attribList );
+extern GLXContext (*qglXCreateContext)( Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct );
+extern void (*qglXDestroyContext)( Display *dpy, GLXContext ctx );
+extern Bool (*qglXMakeCurrent)( Display *dpy, GLXDrawable drawable, GLXContext ctx);
+extern void (*qglXCopyContext)( Display *dpy, GLXContext src, GLXContext dst, GLuint mask );
+extern void (*qglXSwapBuffers)( Display *dpy, GLXDrawable drawable );
+
+#endif // __linux__ || __FreeBSD__ // rb010123
+
+#endif // _WIN32 && __linux__
+
+#endif
diff --git a/code/renderer/qgl_linked.h b/code/renderer/qgl_linked.h
new file mode 100755
index 0000000..6028a74
--- /dev/null
+++ b/code/renderer/qgl_linked.h
@@ -0,0 +1,357 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#define qglAccum glAccum
+#define qglAlphaFunc glAlphaFunc
+#define qglAreTexturesResident glAreTexturesResident
+#define qglArrayElement glArrayElement
+#define qglBegin glBegin
+#define qglBindTexture glBindTexture
+#define qglBitmap glBitmap
+#define qglBlendFunc glBlendFunc
+#define qglCallList glCallList
+#define qglCallLists glCallLists
+#define qglClear glClear
+#define qglClearAccum glClearAccum
+#define qglClearColor glClearColor
+#define qglClearDepth glClearDepth
+#define qglClearIndex glClearIndex
+#define qglClearStencil glClearStencil
+#define qglClipPlane glClipPlane
+#define qglColor3b glColor3b
+#define qglColor3bv glColor3bv
+#define qglColor3d glColor3d
+#define qglColor3dv glColor3dv
+#define qglColor3f glColor3f
+#define qglColor3fv glColor3fv
+#define qglColor3i glColor3i
+#define qglColor3iv glColor3iv
+#define qglColor3s glColor3s
+#define qglColor3sv glColor3sv
+#define qglColor3ub glColor3ub
+#define qglColor3ubv glColor3ubv
+#define qglColor3ui glColor3ui
+#define qglColor3uiv glColor3uiv
+#define qglColor3us glColor3us
+#define qglColor3usv glColor3usv
+#define qglColor4b glColor4b
+#define qglColor4bv glColor4bv
+#define qglColor4d glColor4d
+#define qglColor4dv glColor4dv
+#define qglColor4f glColor4f
+#define qglColor4fv glColor4fv
+#define qglColor4i glColor4i
+#define qglColor4iv glColor4iv
+#define qglColor4s glColor4s
+#define qglColor4sv glColor4sv
+#define qglColor4ub glColor4ub
+#define qglColor4ubv glColor4ubv
+#define qglColor4ui glColor4ui
+#define qglColor4uiv glColor4uiv
+#define qglColor4us glColor4us
+#define qglColor4usv glColor4usv
+#define qglColorMask glColorMask
+#define qglColorMaterial glColorMaterial
+#define qglColorPointer glColorPointer
+#define qglCopyPixels glCopyPixels
+#define qglCopyTexImage1D glCopyTexImage1D
+#define qglCopyTexImage2D glCopyTexImage2D
+#define qglCopyTexSubImage1D glCopyTexSubImage1D
+#define qglCopyTexSubImage2D glCopyTexSubImage2D
+#define qglCullFace glCullFace
+#define qglDeleteLists glDeleteLists
+#define qglDeleteTextures glDeleteTextures
+#define qglDepthFunc glDepthFunc
+#define qglDepthMask glDepthMask
+#define qglDepthRange glDepthRange
+#define qglDisable glDisable
+#define qglDisableClientState glDisableClientState
+#define qglDrawArrays glDrawArrays
+#define qglDrawBuffer glDrawBuffer
+#define qglDrawElements glDrawElements
+#define qglDrawPixels glDrawPixels
+#define qglEdgeFlag glEdgeFlag
+#define qglEdgeFlagPointer glEdgeFlagPointer
+#define qglEdgeFlagv glEdgeFlagv
+#define qglEnable glEnable
+#define qglEnableClientState glEnableClientState
+#define qglEnd glEnd
+#define qglEndList glEndList
+#define qglEvalCoord1d glEvalCoord1d
+#define qglEvalCoord1dv glEvalCoord1dv
+#define qglEvalCoord1f glEvalCoord1f
+#define qglEvalCoord1fv glEvalCoord1fv
+#define qglEvalCoord2d glEvalCoord2d
+#define qglEvalCoord2dv glEvalCoord2dv
+#define qglEvalCoord2f glEvalCoord2f
+#define qglEvalCoord2fv glEvalCoord2fv
+#define qglEvalMesh1 glEvalMesh1
+#define qglEvalMesh2 glEvalMesh2
+#define qglEvalPoint1 glEvalPoint1
+#define qglEvalPoint2 glEvalPoint2
+#define qglFeedbackBuffer glFeedbackBuffer
+#define qglFinish glFinish
+#define qglFlush glFlush
+#define qglFogf glFogf
+#define qglFogfv glFogfv
+#define qglFogi glFogi
+#define qglFogiv glFogiv
+#define qglFrontFace glFrontFace
+#define qglFrustum glFrustum
+#define qglGenLists glGenLists
+#define qglGenTextures glGenTextures
+#define qglGetBooleanv glGetBooleanv
+#define qglGetClipPlane glGetClipPlane
+#define qglGetDoublev glGetDoublev
+#define qglGetError glGetError
+#define qglGetFloatv glGetFloatv
+#define qglGetIntegerv glGetIntegerv
+#define qglGetLightfv glGetLightfv
+#define qglGetLightiv glGetLightiv
+#define qglGetMapdv glGetMapdv
+#define qglGetMapfv glGetMapfv
+#define qglGetMapiv glGetMapiv
+#define qglGetMaterialfv glGetMaterialfv
+#define qglGetMaterialiv glGetMaterialiv
+#define qglGetPixelMapfv glGetPixelMapfv
+#define qglGetPixelMapuiv glGetPixelMapuiv
+#define qglGetPixelMapusv glGetPixelMapusv
+#define qglGetPointerv glGetPointerv
+#define qglGetPolygonStipple glGetPolygonStipple
+#define qglGetString glGetString
+#define qglGetTexGendv glGetTexGendv
+#define qglGetTexGenfv glGetTexGenfv
+#define qglGetTexGeniv glGetTexGeniv
+#define qglGetTexImage glGetTexImage
+#define qglGetTexLevelParameterfv glGetTexLevelParameterfv
+#define qglGetTexLevelParameteriv glGetTexLevelParameteriv
+#define qglGetTexParameterfv glGetTexParameterfv
+#define qglGetTexParameteriv glGetTexParameteriv
+#define qglHint glHint
+#define qglIndexMask glIndexMask
+#define qglIndexPointer glIndexPointer
+#define qglIndexd glIndexd
+#define qglIndexdv glIndexdv
+#define qglIndexf glIndexf
+#define qglIndexfv glIndexfv
+#define qglIndexi glIndexi
+#define qglIndexiv glIndexiv
+#define qglIndexs glIndexs
+#define qglIndexsv glIndexsv
+#define qglIndexub glIndexub
+#define qglIndexubv glIndexubv
+#define qglInitNames glInitNames
+#define qglInterleavedArrays glInterleavedArrays
+#define qglIsEnabled glIsEnabled
+#define qglIsList glIsList
+#define qglIsTexture glIsTexture
+#define qglLightModelf glLightModelf
+#define qglLightModelfv glLightModelfv
+#define qglLightModeli glLightModeli
+#define qglLightModeliv glLightModeliv
+#define qglLightf glLightf
+#define qglLightfv glLightfv
+#define qglLighti glLighti
+#define qglLightiv glLightiv
+#define qglLineStipple glLineStipple
+#define qglLineWidth glLineWidth
+#define qglListBase glListBase
+#define qglLoadIdentity glLoadIdentity
+#define qglLoadMatrixd glLoadMatrixd
+#define qglLoadMatrixf glLoadMatrixf
+#define qglLoadName glLoadName
+#define qglLogicOp glLogicOp
+#define qglMap1d glMap1d
+#define qglMap1f glMap1f
+#define qglMap2d glMap2d
+#define qglMap2f glMap2f
+#define qglMapGrid1d glMapGrid1d
+#define qglMapGrid1f glMapGrid1f
+#define qglMapGrid2d glMapGrid2d
+#define qglMapGrid2f glMapGrid2f
+#define qglMaterialf glMaterialf
+#define qglMaterialfv glMaterialfv
+#define qglMateriali glMateriali
+#define qglMaterialiv glMaterialiv
+#define qglMatrixMode glMatrixMode
+#define qglMultMatrixd glMultMatrixd
+#define qglMultMatrixf glMultMatrixf
+#define qglNewList glNewList
+#define qglNormal3b glNormal3b
+#define qglNormal3bv glNormal3bv
+#define qglNormal3d glNormal3d
+#define qglNormal3dv glNormal3dv
+#define qglNormal3f glNormal3f
+#define qglNormal3fv glNormal3fv
+#define qglNormal3i glNormal3i
+#define qglNormal3iv glNormal3iv
+#define qglNormal3s glNormal3s
+#define qglNormal3sv glNormal3sv
+#define qglNormalPointer glNormalPointer
+#define qglOrtho glOrtho
+#define qglPassThrough glPassThrough
+#define qglPixelMapfv glPixelMapfv
+#define qglPixelMapuiv glPixelMapuiv
+#define qglPixelMapusv glPixelMapusv
+#define qglPixelStoref glPixelStoref
+#define qglPixelStorei glPixelStorei
+#define qglPixelTransferf glPixelTransferf
+#define qglPixelTransferi glPixelTransferi
+#define qglPixelZoom glPixelZoom
+#define qglPointSize glPointSize
+#define qglPolygonMode glPolygonMode
+#define qglPolygonOffset glPolygonOffset
+#define qglPolygonStipple glPolygonStipple
+#define qglPopAttrib glPopAttrib
+#define qglPopClientAttrib glPopClientAttrib
+#define qglPopMatrix glPopMatrix
+#define qglPopName glPopName
+#define qglPrioritizeTextures glPrioritizeTextures
+#define qglPushAttrib glPushAttrib
+#define qglPushClientAttrib glPushClientAttrib
+#define qglPushMatrix glPushMatrix
+#define qglPushName glPushName
+#define qglRasterPos2d glRasterPos2d
+#define qglRasterPos2dv glRasterPos2dv
+#define qglRasterPos2f glRasterPos2f
+#define qglRasterPos2fv glRasterPos2fv
+#define qglRasterPos2i glRasterPos2i
+#define qglRasterPos2iv glRasterPos2iv
+#define qglRasterPos2s glRasterPos2s
+#define qglRasterPos2sv glRasterPos2sv
+#define qglRasterPos3d glRasterPos3d
+#define qglRasterPos3dv glRasterPos3dv
+#define qglRasterPos3f glRasterPos3f
+#define qglRasterPos3fv glRasterPos3fv
+#define qglRasterPos3i glRasterPos3i
+#define qglRasterPos3iv glRasterPos3iv
+#define qglRasterPos3s glRasterPos3s
+#define qglRasterPos3sv glRasterPos3sv
+#define qglRasterPos4d glRasterPos4d
+#define qglRasterPos4dv glRasterPos4dv
+#define qglRasterPos4f glRasterPos4f
+#define qglRasterPos4fv glRasterPos4fv
+#define qglRasterPos4i glRasterPos4i
+#define qglRasterPos4iv glRasterPos4iv
+#define qglRasterPos4s glRasterPos4s
+#define qglRasterPos4sv glRasterPos4sv
+#define qglReadBuffer glReadBuffer
+#define qglReadPixels glReadPixels
+#define qglRectd glRectd
+#define qglRectdv glRectdv
+#define qglRectf glRectf
+#define qglRectfv glRectfv
+#define qglRecti glRecti
+#define qglRectiv glRectiv
+#define qglRects glRects
+#define qglRectsv glRectsv
+#define qglRenderMode glRenderMode
+#define qglRotated glRotated
+#define qglRotatef glRotatef
+#define qglScaled glScaled
+#define qglScalef glScalef
+#define qglScissor glScissor
+#define qglSelectBuffer glSelectBuffer
+#define qglShadeModel glShadeModel
+#define qglStencilFunc glStencilFunc
+#define qglStencilMask glStencilMask
+#define qglStencilOp glStencilOp
+#define qglTexCoord1d glTexCoord1d
+#define qglTexCoord1dv glTexCoord1dv
+#define qglTexCoord1f glTexCoord1f
+#define qglTexCoord1fv glTexCoord1fv
+#define qglTexCoord1i glTexCoord1i
+#define qglTexCoord1iv glTexCoord1iv
+#define qglTexCoord1s glTexCoord1s
+#define qglTexCoord1sv glTexCoord1sv
+#define qglTexCoord2d glTexCoord2d
+#define qglTexCoord2dv glTexCoord2dv
+#define qglTexCoord2f glTexCoord2f
+#define qglTexCoord2fv glTexCoord2fv
+#define qglTexCoord2i glTexCoord2i
+#define qglTexCoord2iv glTexCoord2iv
+#define qglTexCoord2s glTexCoord2s
+#define qglTexCoord2sv glTexCoord2sv
+#define qglTexCoord3d glTexCoord3d
+#define qglTexCoord3dv glTexCoord3dv
+#define qglTexCoord3f glTexCoord3f
+#define qglTexCoord3fv glTexCoord3fv
+#define qglTexCoord3i glTexCoord3i
+#define qglTexCoord3iv glTexCoord3iv
+#define qglTexCoord3s glTexCoord3s
+#define qglTexCoord3sv glTexCoord3sv
+#define qglTexCoord4d glTexCoord4d
+#define qglTexCoord4dv glTexCoord4dv
+#define qglTexCoord4f glTexCoord4f
+#define qglTexCoord4fv glTexCoord4fv
+#define qglTexCoord4i glTexCoord4i
+#define qglTexCoord4iv glTexCoord4iv
+#define qglTexCoord4s glTexCoord4s
+#define qglTexCoord4sv glTexCoord4sv
+#define qglTexCoordPointer glTexCoordPointer
+#define qglTexEnvf glTexEnvf
+#define qglTexEnvfv glTexEnvfv
+#define qglTexEnvi glTexEnvi
+#define qglTexEnviv glTexEnviv
+#define qglTexGend glTexGend
+#define qglTexGendv glTexGendv
+#define qglTexGenf glTexGenf
+#define qglTexGenfv glTexGenfv
+#define qglTexGeni glTexGeni
+#define qglTexGeniv glTexGeniv
+#define qglTexImage1D glTexImage1D
+#define qglTexImage2D glTexImage2D
+#define qglTexParameterf glTexParameterf
+#define qglTexParameterfv glTexParameterfv
+#define qglTexParameteri glTexParameteri
+#define qglTexParameteriv glTexParameteriv
+#define qglTexSubImage1D glTexSubImage1D
+#define qglTexSubImage2D glTexSubImage2D
+#define qglTranslated glTranslated
+#define qglTranslatef glTranslatef
+#define qglVertex2d glVertex2d
+#define qglVertex2dv glVertex2dv
+#define qglVertex2f glVertex2f
+#define qglVertex2fv glVertex2fv
+#define qglVertex2i glVertex2i
+#define qglVertex2iv glVertex2iv
+#define qglVertex2s glVertex2s
+#define qglVertex2sv glVertex2sv
+#define qglVertex3d glVertex3d
+#define qglVertex3dv glVertex3dv
+#define qglVertex3f glVertex3f
+#define qglVertex3fv glVertex3fv
+#define qglVertex3i glVertex3i
+#define qglVertex3iv glVertex3iv
+#define qglVertex3s glVertex3s
+#define qglVertex3sv glVertex3sv
+#define qglVertex4d glVertex4d
+#define qglVertex4dv glVertex4dv
+#define qglVertex4f glVertex4f
+#define qglVertex4fv glVertex4fv
+#define qglVertex4i glVertex4i
+#define qglVertex4iv glVertex4iv
+#define qglVertex4s glVertex4s
+#define qglVertex4sv glVertex4sv
+#define qglVertexPointer glVertexPointer
+#define qglViewport glViewport
+
diff --git a/code/renderer/ref_trin.def b/code/renderer/ref_trin.def
new file mode 100755
index 0000000..2fefbd3
--- /dev/null
+++ b/code/renderer/ref_trin.def
@@ -0,0 +1,2 @@
+EXPORTS
+ GetRefAPI
diff --git a/code/renderer/renderer.vcproj b/code/renderer/renderer.vcproj
new file mode 100755
index 0000000..edbd1ec
--- /dev/null
+++ b/code/renderer/renderer.vcproj
@@ -0,0 +1,6112 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+ ProjectType="Visual C++"
+ Version="7.10"
+ Name="renderer"
+ SccProjectName="&quot;$/MissionPack/code/renderer&quot;, EJBAAAAA"
+ SccLocalPath=".">
+ <Platforms>
+ <Platform
+ Name="Win32"/>
+ </Platforms>
+ <Configurations>
+ <Configuration
+ Name="Debug TA|Win32"
+ OutputDirectory=".\Debug_TA"
+ IntermediateDirectory=".\Debug_TA"
+ ConfigurationType="4"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ OptimizeForProcessor="1"
+ PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
+ BasicRuntimeChecks="3"
+ RuntimeLibrary="1"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Debug_TA/renderer.pch"
+ AssemblerListingLocation=".\Debug_TA/"
+ ObjectFile=".\Debug_TA/"
+ ProgramDataBaseFileName=".\Debug_TA/"
+ BrowseInformation="1"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile=".\Debug_TA\renderer.lib"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCMIDLTool"/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Release|Win32"
+ OutputDirectory=".\Release"
+ IntermediateDirectory=".\Release"
+ ConfigurationType="4"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="2"
+ OptimizeForProcessor="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
+ StringPooling="TRUE"
+ RuntimeLibrary="4"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Release/renderer.pch"
+ AssemblerListingLocation=".\Release/"
+ ObjectFile=".\Release/"
+ ProgramDataBaseFileName=".\Release/"
+ WarningLevel="4"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile=".\Release\renderer.lib"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCMIDLTool"/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Debug|Win32"
+ OutputDirectory=".\Debug"
+ IntermediateDirectory=".\Debug"
+ ConfigurationType="4"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ OptimizeForProcessor="1"
+ PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
+ BasicRuntimeChecks="3"
+ RuntimeLibrary="1"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Debug/renderer.pch"
+ AssemblerListingLocation=".\Debug/"
+ ObjectFile=".\Debug/"
+ ProgramDataBaseFileName=".\Debug/"
+ BrowseInformation="1"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile=".\Debug\renderer.lib"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCMIDLTool"/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Release TA|Win32"
+ OutputDirectory=".\Release_TA"
+ IntermediateDirectory=".\Release_TA"
+ ConfigurationType="4"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="2"
+ OptimizeForProcessor="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
+ StringPooling="TRUE"
+ RuntimeLibrary="4"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Release_TA/renderer.pch"
+ AssemblerListingLocation=".\Release_TA/"
+ ObjectFile=".\Release_TA/"
+ ProgramDataBaseFileName=".\Release_TA/"
+ WarningLevel="4"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile=".\Release_TA\renderer.lib"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCMIDLTool"/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="vector|Win32"
+ OutputDirectory=".\renderer___Win32_vector0"
+ IntermediateDirectory=".\renderer___Win32_vector0"
+ ConfigurationType="4"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalOptions="/vec /vec:stats /vec:pii /vec:o10 /vec:yes "
+ Optimization="2"
+ InlineFunctionExpansion="2"
+ OptimizeForProcessor="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
+ StringPooling="TRUE"
+ RuntimeLibrary="4"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\renderer___Win32_vector0/renderer.pch"
+ AssemblerListingLocation=".\renderer___Win32_vector0/"
+ ObjectFile=".\renderer___Win32_vector0/"
+ ProgramDataBaseFileName=".\renderer___Win32_vector0/"
+ WarningLevel="4"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile=".\renderer___Win32_vector0\renderer.lib"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCMIDLTool"/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ </Configurations>
+ <References>
+ </References>
+ <Files>
+ <Filter
+ Name="Source Files"
+ Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat">
+ <File
+ RelativePath="ref_trin.def">
+ </File>
+ <File
+ RelativePath="tr_animation.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tr_backend.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tr_bsp.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tr_cmds.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tr_curve.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tr_flares.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tr_font.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tr_image.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tr_init.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tr_light.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tr_main.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tr_marks.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tr_mesh.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tr_model.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tr_noise.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tr_scene.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tr_shade.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tr_shade_calc.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tr_shader.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tr_shadows.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tr_sky.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tr_surface.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tr_world.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\win32\win_gamma.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\win32\win_glimp.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\win32\win_qgl.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <Filter
+ Name="Header Files"
+ Filter="h;hpp;hxx;hm;inl">
+ <File
+ RelativePath="..\qcommon\cm_public.h">
+ </File>
+ <File
+ RelativePath="..\win32\glw_win.h">
+ </File>
+ <File
+ RelativePath="..\game\q_shared.h">
+ </File>
+ <File
+ RelativePath="..\qcommon\qcommon.h">
+ </File>
+ <File
+ RelativePath="..\qcommon\qfiles.h">
+ </File>
+ <File
+ RelativePath="qgl.h">
+ </File>
+ <File
+ RelativePath="..\game\surfaceflags.h">
+ </File>
+ <File
+ RelativePath="tr_local.h">
+ </File>
+ <File
+ RelativePath="tr_public.h">
+ </File>
+ <File
+ RelativePath="..\cgame\tr_types.h">
+ </File>
+ <File
+ RelativePath="..\win32\win_local.h">
+ </File>
+ </Filter>
+ <Filter
+ Name="jpeg"
+ Filter="">
+ <Filter
+ Name="Source Files No. 1"
+ Filter="">
+ <File
+ RelativePath="..\jpeg-6\jcapimin.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jccoefct.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jccolor.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jcdctmgr.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jchuff.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jcinit.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jcmainct.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jcmarker.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jcmaster.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jcomapi.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jcparam.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jcphuff.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jcprepct.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jcsample.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jctrans.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jdapimin.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jdapistd.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jdatadst.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jdatasrc.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jdcoefct.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jdcolor.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jddctmgr.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jdhuff.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jdinput.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jdmainct.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jdmarker.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jdmaster.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jdpostct.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jdsample.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jdtrans.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jerror.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jfdctflt.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jidctflt.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jmemmgr.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jmemnobs.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jutils.c">
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <Filter
+ Name="Header Files No. 1"
+ Filter="">
+ <File
+ RelativePath="..\jpeg-6\jchuff.h">
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jconfig.h">
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jdct.h">
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jdhuff.h">
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jerror.h">
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jinclude.h">
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jmemsys.h">
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jmorecfg.h">
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jpegint.h">
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jpeglib.h">
+ </File>
+ <File
+ RelativePath="..\jpeg-6\jversion.h">
+ </File>
+ </Filter>
+ </Filter>
+ <Filter
+ Name="FreeType2"
+ Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat">
+ <File
+ RelativePath="..\ft2\ahangles.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ahglobal.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ahglyph.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ahhint.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ahmodule.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ahoptim.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftcalc.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftdebug.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftextend.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftglyph.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftgrays.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftinit.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftlist.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftmm.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftnames.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftobjs.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftoutln.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftraster.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftrend1.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftsmooth.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftstream.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftsystem.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\sfdriver.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\sfobjs.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ttcmap.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ttdriver.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ttgload.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ttinterp.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ttload.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ttobjs.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ttpload.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ttpost.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ttsbit.c">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <Filter
+ Name="Include files"
+ Filter="*.h">
+ <File
+ RelativePath="..\ft2\ahangles.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ahglobal.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ahglyph.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ahhint.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ahloader.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ahmodule.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ahoptim.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ahtypes.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\autohint.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\freetype.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftbbox.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftcalc.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftconfig.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftdebug.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftdriver.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\fterrors.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftextend.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftglyph.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftimage.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftlist.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftmemory.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftmm.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftmodule.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftnames.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftobjs.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftoption.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftoutln.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftrender.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftstream.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ftsystem.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\fttypes.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\psnames.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\sfnt.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\t1errors.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\t1tables.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\t1types.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\t2errors.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\t2types.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ttdriver.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\tterrors.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ttgload.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ttinterp.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ttnameid.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ttobjs.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\ttpload.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\tttables.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\tttags.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\ft2\tttypes.h">
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ </Filter>
+ </Filter>
+ </Files>
+ <Globals>
+ </Globals>
+</VisualStudioProject>
diff --git a/code/renderer/tr_animation.c b/code/renderer/tr_animation.c
new file mode 100755
index 0000000..6a6f800
--- /dev/null
+++ b/code/renderer/tr_animation.c
@@ -0,0 +1,171 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "tr_local.h"
+
+/*
+
+All bones should be an identity orientation to display the mesh exactly
+as it is specified.
+
+For all other frames, the bones represent the transformation from the
+orientation of the bone in the base frame to the orientation in this
+frame.
+
+*/
+
+/*
+==============
+R_AddAnimSurfaces
+==============
+*/
+void R_AddAnimSurfaces( trRefEntity_t *ent ) {
+ md4Header_t *header;
+ md4Surface_t *surface;
+ md4LOD_t *lod;
+ shader_t *shader;
+ int i;
+
+ header = tr.currentModel->md4;
+ lod = (md4LOD_t *)( (byte *)header + header->ofsLODs );
+
+ surface = (md4Surface_t *)( (byte *)lod + lod->ofsSurfaces );
+ for ( i = 0 ; i < lod->numSurfaces ; i++ ) {
+ shader = R_GetShaderByHandle( surface->shaderIndex );
+ R_AddDrawSurf( (void *)surface, shader, 0 /*fogNum*/, qfalse );
+ surface = (md4Surface_t *)( (byte *)surface + surface->ofsEnd );
+ }
+}
+
+
+/*
+==============
+RB_SurfaceAnim
+==============
+*/
+void RB_SurfaceAnim( md4Surface_t *surface ) {
+ int i, j, k;
+ float frontlerp, backlerp;
+ int *triangles;
+ int indexes;
+ int baseIndex, baseVertex;
+ int numVerts;
+ md4Vertex_t *v;
+ md4Bone_t bones[MD4_MAX_BONES];
+ md4Bone_t *bonePtr, *bone;
+ md4Header_t *header;
+ md4Frame_t *frame;
+ md4Frame_t *oldFrame;
+ int frameSize;
+
+
+ if ( backEnd.currentEntity->e.oldframe == backEnd.currentEntity->e.frame ) {
+ backlerp = 0;
+ frontlerp = 1;
+ } else {
+ backlerp = backEnd.currentEntity->e.backlerp;
+ frontlerp = 1.0f - backlerp;
+ }
+ header = (md4Header_t *)((byte *)surface + surface->ofsHeader);
+
+ frameSize = (int)( &((md4Frame_t *)0)->bones[ header->numBones ] );
+
+ frame = (md4Frame_t *)((byte *)header + header->ofsFrames +
+ backEnd.currentEntity->e.frame * frameSize );
+ oldFrame = (md4Frame_t *)((byte *)header + header->ofsFrames +
+ backEnd.currentEntity->e.oldframe * frameSize );
+
+ RB_CheckOverflow( surface->numVerts, surface->numTriangles * 3 );
+
+ triangles = (int *) ((byte *)surface + surface->ofsTriangles);
+ indexes = surface->numTriangles * 3;
+ baseIndex = tess.numIndexes;
+ baseVertex = tess.numVertexes;
+ for (j = 0 ; j < indexes ; j++) {
+ tess.indexes[baseIndex + j] = baseIndex + triangles[j];
+ }
+ tess.numIndexes += indexes;
+
+ //
+ // lerp all the needed bones
+ //
+ if ( !backlerp ) {
+ // no lerping needed
+ bonePtr = frame->bones;
+ } else {
+ bonePtr = bones;
+ for ( i = 0 ; i < header->numBones*12 ; i++ ) {
+ ((float *)bonePtr)[i] = frontlerp * ((float *)frame->bones)[i]
+ + backlerp * ((float *)oldFrame->bones)[i];
+ }
+ }
+
+ //
+ // deform the vertexes by the lerped bones
+ //
+ numVerts = surface->numVerts;
+ // FIXME
+ // This makes TFC's skeletons work. Shouldn't be necessary anymore, but left
+ // in for reference.
+ //v = (md4Vertex_t *) ((byte *)surface + surface->ofsVerts + 12);
+ v = (md4Vertex_t *) ((byte *)surface + surface->ofsVerts);
+ for ( j = 0; j < numVerts; j++ ) {
+ vec3_t tempVert, tempNormal;
+ md4Weight_t *w;
+
+ VectorClear( tempVert );
+ VectorClear( tempNormal );
+ w = v->weights;
+ for ( k = 0 ; k < v->numWeights ; k++, w++ ) {
+ bone = bonePtr + w->boneIndex;
+
+ tempVert[0] += w->boneWeight * ( DotProduct( bone->matrix[0], w->offset ) + bone->matrix[0][3] );
+ tempVert[1] += w->boneWeight * ( DotProduct( bone->matrix[1], w->offset ) + bone->matrix[1][3] );
+ tempVert[2] += w->boneWeight * ( DotProduct( bone->matrix[2], w->offset ) + bone->matrix[2][3] );
+
+ tempNormal[0] += w->boneWeight * DotProduct( bone->matrix[0], v->normal );
+ tempNormal[1] += w->boneWeight * DotProduct( bone->matrix[1], v->normal );
+ tempNormal[2] += w->boneWeight * DotProduct( bone->matrix[2], v->normal );
+ }
+
+ tess.xyz[baseVertex + j][0] = tempVert[0];
+ tess.xyz[baseVertex + j][1] = tempVert[1];
+ tess.xyz[baseVertex + j][2] = tempVert[2];
+
+ tess.normal[baseVertex + j][0] = tempNormal[0];
+ tess.normal[baseVertex + j][1] = tempNormal[1];
+ tess.normal[baseVertex + j][2] = tempNormal[2];
+
+ tess.texCoords[baseVertex + j][0][0] = v->texCoords[0];
+ tess.texCoords[baseVertex + j][0][1] = v->texCoords[1];
+
+ // FIXME
+ // This makes TFC's skeletons work. Shouldn't be necessary anymore, but left
+ // in for reference.
+ //v = (md4Vertex_t *)( ( byte * )&v->weights[v->numWeights] + 12 );
+ v = (md4Vertex_t *)&v->weights[v->numWeights];
+ }
+
+ tess.numVertexes += surface->numVerts;
+}
+
+
diff --git a/code/renderer/tr_backend.c b/code/renderer/tr_backend.c
new file mode 100755
index 0000000..4fff190
--- /dev/null
+++ b/code/renderer/tr_backend.c
@@ -0,0 +1,1143 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "tr_local.h"
+
+backEndData_t *backEndData[SMP_FRAMES];
+backEndState_t backEnd;
+
+
+static float s_flipMatrix[16] = {
+ // convert from our coordinate system (looking down X)
+ // to OpenGL's coordinate system (looking down -Z)
+ 0, 0, -1, 0,
+ -1, 0, 0, 0,
+ 0, 1, 0, 0,
+ 0, 0, 0, 1
+};
+
+
+/*
+** GL_Bind
+*/
+void GL_Bind( image_t *image ) {
+ int texnum;
+
+ if ( !image ) {
+ ri.Printf( PRINT_WARNING, "GL_Bind: NULL image\n" );
+ texnum = tr.defaultImage->texnum;
+ } else {
+ texnum = image->texnum;
+ }
+
+ if ( r_nobind->integer && tr.dlightImage ) { // performance evaluation option
+ texnum = tr.dlightImage->texnum;
+ }
+
+ if ( glState.currenttextures[glState.currenttmu] != texnum ) {
+ image->frameUsed = tr.frameCount;
+ glState.currenttextures[glState.currenttmu] = texnum;
+ qglBindTexture (GL_TEXTURE_2D, texnum);
+ }
+}
+
+/*
+** GL_SelectTexture
+*/
+void GL_SelectTexture( int unit )
+{
+ if ( glState.currenttmu == unit )
+ {
+ return;
+ }
+
+ if ( unit == 0 )
+ {
+ qglActiveTextureARB( GL_TEXTURE0_ARB );
+ GLimp_LogComment( "glActiveTextureARB( GL_TEXTURE0_ARB )\n" );
+ qglClientActiveTextureARB( GL_TEXTURE0_ARB );
+ GLimp_LogComment( "glClientActiveTextureARB( GL_TEXTURE0_ARB )\n" );
+ }
+ else if ( unit == 1 )
+ {
+ qglActiveTextureARB( GL_TEXTURE1_ARB );
+ GLimp_LogComment( "glActiveTextureARB( GL_TEXTURE1_ARB )\n" );
+ qglClientActiveTextureARB( GL_TEXTURE1_ARB );
+ GLimp_LogComment( "glClientActiveTextureARB( GL_TEXTURE1_ARB )\n" );
+ } else {
+ ri.Error( ERR_DROP, "GL_SelectTexture: unit = %i", unit );
+ }
+
+ glState.currenttmu = unit;
+}
+
+
+/*
+** GL_BindMultitexture
+*/
+void GL_BindMultitexture( image_t *image0, GLuint env0, image_t *image1, GLuint env1 ) {
+ int texnum0, texnum1;
+
+ texnum0 = image0->texnum;
+ texnum1 = image1->texnum;
+
+ if ( r_nobind->integer && tr.dlightImage ) { // performance evaluation option
+ texnum0 = texnum1 = tr.dlightImage->texnum;
+ }
+
+ if ( glState.currenttextures[1] != texnum1 ) {
+ GL_SelectTexture( 1 );
+ image1->frameUsed = tr.frameCount;
+ glState.currenttextures[1] = texnum1;
+ qglBindTexture( GL_TEXTURE_2D, texnum1 );
+ }
+ if ( glState.currenttextures[0] != texnum0 ) {
+ GL_SelectTexture( 0 );
+ image0->frameUsed = tr.frameCount;
+ glState.currenttextures[0] = texnum0;
+ qglBindTexture( GL_TEXTURE_2D, texnum0 );
+ }
+}
+
+
+/*
+** GL_Cull
+*/
+void GL_Cull( int cullType ) {
+ if ( glState.faceCulling == cullType ) {
+ return;
+ }
+
+ glState.faceCulling = cullType;
+
+ if ( cullType == CT_TWO_SIDED )
+ {
+ qglDisable( GL_CULL_FACE );
+ }
+ else
+ {
+ qglEnable( GL_CULL_FACE );
+
+ if ( cullType == CT_BACK_SIDED )
+ {
+ if ( backEnd.viewParms.isMirror )
+ {
+ qglCullFace( GL_FRONT );
+ }
+ else
+ {
+ qglCullFace( GL_BACK );
+ }
+ }
+ else
+ {
+ if ( backEnd.viewParms.isMirror )
+ {
+ qglCullFace( GL_BACK );
+ }
+ else
+ {
+ qglCullFace( GL_FRONT );
+ }
+ }
+ }
+}
+
+/*
+** GL_TexEnv
+*/
+void GL_TexEnv( int env )
+{
+ if ( env == glState.texEnv[glState.currenttmu] )
+ {
+ return;
+ }
+
+ glState.texEnv[glState.currenttmu] = env;
+
+
+ switch ( env )
+ {
+ case GL_MODULATE:
+ qglTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
+ break;
+ case GL_REPLACE:
+ qglTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE );
+ break;
+ case GL_DECAL:
+ qglTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL );
+ break;
+ case GL_ADD:
+ qglTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD );
+ break;
+ default:
+ ri.Error( ERR_DROP, "GL_TexEnv: invalid env '%d' passed\n", env );
+ break;
+ }
+}
+
+/*
+** GL_State
+**
+** This routine is responsible for setting the most commonly changed state
+** in Q3.
+*/
+void GL_State( unsigned long stateBits )
+{
+ unsigned long diff = stateBits ^ glState.glStateBits;
+
+ if ( !diff )
+ {
+ return;
+ }
+
+ //
+ // check depthFunc bits
+ //
+ if ( diff & GLS_DEPTHFUNC_EQUAL )
+ {
+ if ( stateBits & GLS_DEPTHFUNC_EQUAL )
+ {
+ qglDepthFunc( GL_EQUAL );
+ }
+ else
+ {
+ qglDepthFunc( GL_LEQUAL );
+ }
+ }
+
+ //
+ // check blend bits
+ //
+ if ( diff & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) )
+ {
+ GLenum srcFactor, dstFactor;
+
+ if ( stateBits & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) )
+ {
+ switch ( stateBits & GLS_SRCBLEND_BITS )
+ {
+ case GLS_SRCBLEND_ZERO:
+ srcFactor = GL_ZERO;
+ break;
+ case GLS_SRCBLEND_ONE:
+ srcFactor = GL_ONE;
+ break;
+ case GLS_SRCBLEND_DST_COLOR:
+ srcFactor = GL_DST_COLOR;
+ break;
+ case GLS_SRCBLEND_ONE_MINUS_DST_COLOR:
+ srcFactor = GL_ONE_MINUS_DST_COLOR;
+ break;
+ case GLS_SRCBLEND_SRC_ALPHA:
+ srcFactor = GL_SRC_ALPHA;
+ break;
+ case GLS_SRCBLEND_ONE_MINUS_SRC_ALPHA:
+ srcFactor = GL_ONE_MINUS_SRC_ALPHA;
+ break;
+ case GLS_SRCBLEND_DST_ALPHA:
+ srcFactor = GL_DST_ALPHA;
+ break;
+ case GLS_SRCBLEND_ONE_MINUS_DST_ALPHA:
+ srcFactor = GL_ONE_MINUS_DST_ALPHA;
+ break;
+ case GLS_SRCBLEND_ALPHA_SATURATE:
+ srcFactor = GL_SRC_ALPHA_SATURATE;
+ break;
+ default:
+ srcFactor = GL_ONE; // to get warning to shut up
+ ri.Error( ERR_DROP, "GL_State: invalid src blend state bits\n" );
+ break;
+ }
+
+ switch ( stateBits & GLS_DSTBLEND_BITS )
+ {
+ case GLS_DSTBLEND_ZERO:
+ dstFactor = GL_ZERO;
+ break;
+ case GLS_DSTBLEND_ONE:
+ dstFactor = GL_ONE;
+ break;
+ case GLS_DSTBLEND_SRC_COLOR:
+ dstFactor = GL_SRC_COLOR;
+ break;
+ case GLS_DSTBLEND_ONE_MINUS_SRC_COLOR:
+ dstFactor = GL_ONE_MINUS_SRC_COLOR;
+ break;
+ case GLS_DSTBLEND_SRC_ALPHA:
+ dstFactor = GL_SRC_ALPHA;
+ break;
+ case GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA:
+ dstFactor = GL_ONE_MINUS_SRC_ALPHA;
+ break;
+ case GLS_DSTBLEND_DST_ALPHA:
+ dstFactor = GL_DST_ALPHA;
+ break;
+ case GLS_DSTBLEND_ONE_MINUS_DST_ALPHA:
+ dstFactor = GL_ONE_MINUS_DST_ALPHA;
+ break;
+ default:
+ dstFactor = GL_ONE; // to get warning to shut up
+ ri.Error( ERR_DROP, "GL_State: invalid dst blend state bits\n" );
+ break;
+ }
+
+ qglEnable( GL_BLEND );
+ qglBlendFunc( srcFactor, dstFactor );
+ }
+ else
+ {
+ qglDisable( GL_BLEND );
+ }
+ }
+
+ //
+ // check depthmask
+ //
+ if ( diff & GLS_DEPTHMASK_TRUE )
+ {
+ if ( stateBits & GLS_DEPTHMASK_TRUE )
+ {
+ qglDepthMask( GL_TRUE );
+ }
+ else
+ {
+ qglDepthMask( GL_FALSE );
+ }
+ }
+
+ //
+ // fill/line mode
+ //
+ if ( diff & GLS_POLYMODE_LINE )
+ {
+ if ( stateBits & GLS_POLYMODE_LINE )
+ {
+ qglPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
+ }
+ else
+ {
+ qglPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
+ }
+ }
+
+ //
+ // depthtest
+ //
+ if ( diff & GLS_DEPTHTEST_DISABLE )
+ {
+ if ( stateBits & GLS_DEPTHTEST_DISABLE )
+ {
+ qglDisable( GL_DEPTH_TEST );
+ }
+ else
+ {
+ qglEnable( GL_DEPTH_TEST );
+ }
+ }
+
+ //
+ // alpha test
+ //
+ if ( diff & GLS_ATEST_BITS )
+ {
+ switch ( stateBits & GLS_ATEST_BITS )
+ {
+ case 0:
+ qglDisable( GL_ALPHA_TEST );
+ break;
+ case GLS_ATEST_GT_0:
+ qglEnable( GL_ALPHA_TEST );
+ qglAlphaFunc( GL_GREATER, 0.0f );
+ break;
+ case GLS_ATEST_LT_80:
+ qglEnable( GL_ALPHA_TEST );
+ qglAlphaFunc( GL_LESS, 0.5f );
+ break;
+ case GLS_ATEST_GE_80:
+ qglEnable( GL_ALPHA_TEST );
+ qglAlphaFunc( GL_GEQUAL, 0.5f );
+ break;
+ default:
+ assert( 0 );
+ break;
+ }
+ }
+
+ glState.glStateBits = stateBits;
+}
+
+
+
+/*
+================
+RB_Hyperspace
+
+A player has predicted a teleport, but hasn't arrived yet
+================
+*/
+static void RB_Hyperspace( void ) {
+ float c;
+
+ if ( !backEnd.isHyperspace ) {
+ // do initialization shit
+ }
+
+ c = ( backEnd.refdef.time & 255 ) / 255.0f;
+ qglClearColor( c, c, c, 1 );
+ qglClear( GL_COLOR_BUFFER_BIT );
+
+ backEnd.isHyperspace = qtrue;
+}
+
+
+static void SetViewportAndScissor( void ) {
+ qglMatrixMode(GL_PROJECTION);
+ qglLoadMatrixf( backEnd.viewParms.projectionMatrix );
+ qglMatrixMode(GL_MODELVIEW);
+
+ // set the window clipping
+ qglViewport( backEnd.viewParms.viewportX, backEnd.viewParms.viewportY,
+ backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight );
+ qglScissor( backEnd.viewParms.viewportX, backEnd.viewParms.viewportY,
+ backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight );
+}
+
+/*
+=================
+RB_BeginDrawingView
+
+Any mirrored or portaled views have already been drawn, so prepare
+to actually render the visible surfaces for this view
+=================
+*/
+void RB_BeginDrawingView (void) {
+ int clearBits = 0;
+
+ // sync with gl if needed
+ if ( r_finish->integer == 1 && !glState.finishCalled ) {
+ qglFinish ();
+ glState.finishCalled = qtrue;
+ }
+ if ( r_finish->integer == 0 ) {
+ glState.finishCalled = qtrue;
+ }
+
+ // we will need to change the projection matrix before drawing
+ // 2D images again
+ backEnd.projection2D = qfalse;
+
+ //
+ // set the modelview matrix for the viewer
+ //
+ SetViewportAndScissor();
+
+ // ensures that depth writes are enabled for the depth clear
+ GL_State( GLS_DEFAULT );
+ // clear relevant buffers
+ clearBits = GL_DEPTH_BUFFER_BIT;
+
+ if ( r_measureOverdraw->integer || r_shadows->integer == 2 )
+ {
+ clearBits |= GL_STENCIL_BUFFER_BIT;
+ }
+ if ( r_fastsky->integer && !( backEnd.refdef.rdflags & RDF_NOWORLDMODEL ) )
+ {
+ clearBits |= GL_COLOR_BUFFER_BIT; // FIXME: only if sky shaders have been used
+#ifdef _DEBUG
+ qglClearColor( 0.8f, 0.7f, 0.4f, 1.0f ); // FIXME: get color of sky
+#else
+ qglClearColor( 0.0f, 0.0f, 0.0f, 1.0f ); // FIXME: get color of sky
+#endif
+ }
+ qglClear( clearBits );
+
+ if ( ( backEnd.refdef.rdflags & RDF_HYPERSPACE ) )
+ {
+ RB_Hyperspace();
+ return;
+ }
+ else
+ {
+ backEnd.isHyperspace = qfalse;
+ }
+
+ glState.faceCulling = -1; // force face culling to set next time
+
+ // we will only draw a sun if there was sky rendered in this view
+ backEnd.skyRenderedThisView = qfalse;
+
+ // clip to the plane of the portal
+ if ( backEnd.viewParms.isPortal ) {
+ float plane[4];
+ double plane2[4];
+
+ plane[0] = backEnd.viewParms.portalPlane.normal[0];
+ plane[1] = backEnd.viewParms.portalPlane.normal[1];
+ plane[2] = backEnd.viewParms.portalPlane.normal[2];
+ plane[3] = backEnd.viewParms.portalPlane.dist;
+
+ plane2[0] = DotProduct (backEnd.viewParms.or.axis[0], plane);
+ plane2[1] = DotProduct (backEnd.viewParms.or.axis[1], plane);
+ plane2[2] = DotProduct (backEnd.viewParms.or.axis[2], plane);
+ plane2[3] = DotProduct (plane, backEnd.viewParms.or.origin) - plane[3];
+
+ qglLoadMatrixf( s_flipMatrix );
+ qglClipPlane (GL_CLIP_PLANE0, plane2);
+ qglEnable (GL_CLIP_PLANE0);
+ } else {
+ qglDisable (GL_CLIP_PLANE0);
+ }
+}
+
+
+#define MAC_EVENT_PUMP_MSEC 5
+
+/*
+==================
+RB_RenderDrawSurfList
+==================
+*/
+void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) {
+ shader_t *shader, *oldShader;
+ int fogNum, oldFogNum;
+ int entityNum, oldEntityNum;
+ int dlighted, oldDlighted;
+ qboolean depthRange, oldDepthRange;
+ int i;
+ drawSurf_t *drawSurf;
+ int oldSort;
+ float originalTime;
+#ifdef __MACOS__
+ int macEventTime;
+
+ Sys_PumpEvents(); // crutch up the mac's limited buffer queue size
+
+ // we don't want to pump the event loop too often and waste time, so
+ // we are going to check every shader change
+ macEventTime = ri.Milliseconds() + MAC_EVENT_PUMP_MSEC;
+#endif
+
+ // save original time for entity shader offsets
+ originalTime = backEnd.refdef.floatTime;
+
+ // clear the z buffer, set the modelview, etc
+ RB_BeginDrawingView ();
+
+ // draw everything
+ oldEntityNum = -1;
+ backEnd.currentEntity = &tr.worldEntity;
+ oldShader = NULL;
+ oldFogNum = -1;
+ oldDepthRange = qfalse;
+ oldDlighted = qfalse;
+ oldSort = -1;
+ depthRange = qfalse;
+
+ backEnd.pc.c_surfaces += numDrawSurfs;
+
+ for (i = 0, drawSurf = drawSurfs ; i < numDrawSurfs ; i++, drawSurf++) {
+ if ( drawSurf->sort == oldSort ) {
+ // fast path, same as previous sort
+ rb_surfaceTable[ *drawSurf->surface ]( drawSurf->surface );
+ continue;
+ }
+ oldSort = drawSurf->sort;
+ R_DecomposeSort( drawSurf->sort, &entityNum, &shader, &fogNum, &dlighted );
+
+ //
+ // change the tess parameters if needed
+ // a "entityMergable" shader is a shader that can have surfaces from seperate
+ // entities merged into a single batch, like smoke and blood puff sprites
+ if (shader != oldShader || fogNum != oldFogNum || dlighted != oldDlighted
+ || ( entityNum != oldEntityNum && !shader->entityMergable ) ) {
+ if (oldShader != NULL) {
+#ifdef __MACOS__ // crutch up the mac's limited buffer queue size
+ int t;
+
+ t = ri.Milliseconds();
+ if ( t > macEventTime ) {
+ macEventTime = t + MAC_EVENT_PUMP_MSEC;
+ Sys_PumpEvents();
+ }
+#endif
+ RB_EndSurface();
+ }
+ RB_BeginSurface( shader, fogNum );
+ oldShader = shader;
+ oldFogNum = fogNum;
+ oldDlighted = dlighted;
+ }
+
+ //
+ // change the modelview matrix if needed
+ //
+ if ( entityNum != oldEntityNum ) {
+ depthRange = qfalse;
+
+ if ( entityNum != ENTITYNUM_WORLD ) {
+ backEnd.currentEntity = &backEnd.refdef.entities[entityNum];
+ backEnd.refdef.floatTime = originalTime - backEnd.currentEntity->e.shaderTime;
+ // we have to reset the shaderTime as well otherwise image animations start
+ // from the wrong frame
+ tess.shaderTime = backEnd.refdef.floatTime - tess.shader->timeOffset;
+
+ // set up the transformation matrix
+ R_RotateForEntity( backEnd.currentEntity, &backEnd.viewParms, &backEnd.or );
+
+ // set up the dynamic lighting if needed
+ if ( backEnd.currentEntity->needDlights ) {
+ R_TransformDlights( backEnd.refdef.num_dlights, backEnd.refdef.dlights, &backEnd.or );
+ }
+
+ if ( backEnd.currentEntity->e.renderfx & RF_DEPTHHACK ) {
+ // hack the depth range to prevent view model from poking into walls
+ depthRange = qtrue;
+ }
+ } else {
+ backEnd.currentEntity = &tr.worldEntity;
+ backEnd.refdef.floatTime = originalTime;
+ backEnd.or = backEnd.viewParms.world;
+ // we have to reset the shaderTime as well otherwise image animations on
+ // the world (like water) continue with the wrong frame
+ tess.shaderTime = backEnd.refdef.floatTime - tess.shader->timeOffset;
+ R_TransformDlights( backEnd.refdef.num_dlights, backEnd.refdef.dlights, &backEnd.or );
+ }
+
+ qglLoadMatrixf( backEnd.or.modelMatrix );
+
+ //
+ // change depthrange if needed
+ //
+ if ( oldDepthRange != depthRange ) {
+ if ( depthRange ) {
+ qglDepthRange (0, 0.3);
+ } else {
+ qglDepthRange (0, 1);
+ }
+ oldDepthRange = depthRange;
+ }
+
+ oldEntityNum = entityNum;
+ }
+
+ // add the triangles for this surface
+ rb_surfaceTable[ *drawSurf->surface ]( drawSurf->surface );
+ }
+
+ backEnd.refdef.floatTime = originalTime;
+
+ // draw the contents of the last shader batch
+ if (oldShader != NULL) {
+ RB_EndSurface();
+ }
+
+ // go back to the world modelview matrix
+ qglLoadMatrixf( backEnd.viewParms.world.modelMatrix );
+ if ( depthRange ) {
+ qglDepthRange (0, 1);
+ }
+
+#if 0
+ RB_DrawSun();
+#endif
+ // darken down any stencil shadows
+ RB_ShadowFinish();
+
+ // add light flares on lights that aren't obscured
+ RB_RenderFlares();
+
+#ifdef __MACOS__
+ Sys_PumpEvents(); // crutch up the mac's limited buffer queue size
+#endif
+}
+
+
+/*
+============================================================================
+
+RENDER BACK END THREAD FUNCTIONS
+
+============================================================================
+*/
+
+/*
+================
+RB_SetGL2D
+
+================
+*/
+void RB_SetGL2D (void) {
+ backEnd.projection2D = qtrue;
+
+ // set 2D virtual screen size
+ qglViewport( 0, 0, glConfig.vidWidth, glConfig.vidHeight );
+ qglScissor( 0, 0, glConfig.vidWidth, glConfig.vidHeight );
+ qglMatrixMode(GL_PROJECTION);
+ qglLoadIdentity ();
+ qglOrtho (0, glConfig.vidWidth, glConfig.vidHeight, 0, 0, 1);
+ qglMatrixMode(GL_MODELVIEW);
+ qglLoadIdentity ();
+
+ GL_State( GLS_DEPTHTEST_DISABLE |
+ GLS_SRCBLEND_SRC_ALPHA |
+ GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA );
+
+ qglDisable( GL_CULL_FACE );
+ qglDisable( GL_CLIP_PLANE0 );
+
+ // set time for 2D shaders
+ backEnd.refdef.time = ri.Milliseconds();
+ backEnd.refdef.floatTime = backEnd.refdef.time * 0.001f;
+}
+
+
+/*
+=============
+RE_StretchRaw
+
+FIXME: not exactly backend
+Stretches a raw 32 bit power of 2 bitmap image over the given screen rectangle.
+Used for cinematics.
+=============
+*/
+void RE_StretchRaw (int x, int y, int w, int h, int cols, int rows, const byte *data, int client, qboolean dirty) {
+ int i, j;
+ int start, end;
+
+ if ( !tr.registered ) {
+ return;
+ }
+ R_SyncRenderThread();
+
+ // we definately want to sync every frame for the cinematics
+ qglFinish();
+
+ start = end = 0;
+ if ( r_speeds->integer ) {
+ start = ri.Milliseconds();
+ }
+
+ // make sure rows and cols are powers of 2
+ for ( i = 0 ; ( 1 << i ) < cols ; i++ ) {
+ }
+ for ( j = 0 ; ( 1 << j ) < rows ; j++ ) {
+ }
+ if ( ( 1 << i ) != cols || ( 1 << j ) != rows) {
+ ri.Error (ERR_DROP, "Draw_StretchRaw: size not a power of 2: %i by %i", cols, rows);
+ }
+
+ GL_Bind( tr.scratchImage[client] );
+
+ // if the scratchImage isn't in the format we want, specify it as a new texture
+ if ( cols != tr.scratchImage[client]->width || rows != tr.scratchImage[client]->height ) {
+ tr.scratchImage[client]->width = tr.scratchImage[client]->uploadWidth = cols;
+ tr.scratchImage[client]->height = tr.scratchImage[client]->uploadHeight = rows;
+ qglTexImage2D( GL_TEXTURE_2D, 0, GL_RGB8, cols, rows, 0, GL_RGBA, GL_UNSIGNED_BYTE, data );
+ qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
+ qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
+ qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
+ qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );
+ } else {
+ if (dirty) {
+ // otherwise, just subimage upload it so that drivers can tell we are going to be changing
+ // it and don't try and do a texture compression
+ qglTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, cols, rows, GL_RGBA, GL_UNSIGNED_BYTE, data );
+ }
+ }
+
+ if ( r_speeds->integer ) {
+ end = ri.Milliseconds();
+ ri.Printf( PRINT_ALL, "qglTexSubImage2D %i, %i: %i msec\n", cols, rows, end - start );
+ }
+
+ RB_SetGL2D();
+
+ qglColor3f( tr.identityLight, tr.identityLight, tr.identityLight );
+
+ qglBegin (GL_QUADS);
+ qglTexCoord2f ( 0.5f / cols, 0.5f / rows );
+ qglVertex2f (x, y);
+ qglTexCoord2f ( ( cols - 0.5f ) / cols , 0.5f / rows );
+ qglVertex2f (x+w, y);
+ qglTexCoord2f ( ( cols - 0.5f ) / cols, ( rows - 0.5f ) / rows );
+ qglVertex2f (x+w, y+h);
+ qglTexCoord2f ( 0.5f / cols, ( rows - 0.5f ) / rows );
+ qglVertex2f (x, y+h);
+ qglEnd ();
+}
+
+void RE_UploadCinematic (int w, int h, int cols, int rows, const byte *data, int client, qboolean dirty) {
+
+ GL_Bind( tr.scratchImage[client] );
+
+ // if the scratchImage isn't in the format we want, specify it as a new texture
+ if ( cols != tr.scratchImage[client]->width || rows != tr.scratchImage[client]->height ) {
+ tr.scratchImage[client]->width = tr.scratchImage[client]->uploadWidth = cols;
+ tr.scratchImage[client]->height = tr.scratchImage[client]->uploadHeight = rows;
+ qglTexImage2D( GL_TEXTURE_2D, 0, GL_RGB8, cols, rows, 0, GL_RGBA, GL_UNSIGNED_BYTE, data );
+ qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
+ qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
+ qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
+ qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );
+ } else {
+ if (dirty) {
+ // otherwise, just subimage upload it so that drivers can tell we are going to be changing
+ // it and don't try and do a texture compression
+ qglTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, cols, rows, GL_RGBA, GL_UNSIGNED_BYTE, data );
+ }
+ }
+}
+
+
+/*
+=============
+RB_SetColor
+
+=============
+*/
+const void *RB_SetColor( const void *data ) {
+ const setColorCommand_t *cmd;
+
+ cmd = (const setColorCommand_t *)data;
+
+ backEnd.color2D[0] = cmd->color[0] * 255;
+ backEnd.color2D[1] = cmd->color[1] * 255;
+ backEnd.color2D[2] = cmd->color[2] * 255;
+ backEnd.color2D[3] = cmd->color[3] * 255;
+
+ return (const void *)(cmd + 1);
+}
+
+/*
+=============
+RB_StretchPic
+=============
+*/
+const void *RB_StretchPic ( const void *data ) {
+ const stretchPicCommand_t *cmd;
+ shader_t *shader;
+ int numVerts, numIndexes;
+
+ cmd = (const stretchPicCommand_t *)data;
+
+ if ( !backEnd.projection2D ) {
+ RB_SetGL2D();
+ }
+
+ shader = cmd->shader;
+ if ( shader != tess.shader ) {
+ if ( tess.numIndexes ) {
+ RB_EndSurface();
+ }
+ backEnd.currentEntity = &backEnd.entity2D;
+ RB_BeginSurface( shader, 0 );
+ }
+
+ RB_CHECKOVERFLOW( 4, 6 );
+ numVerts = tess.numVertexes;
+ numIndexes = tess.numIndexes;
+
+ tess.numVertexes += 4;
+ tess.numIndexes += 6;
+
+ tess.indexes[ numIndexes ] = numVerts + 3;
+ tess.indexes[ numIndexes + 1 ] = numVerts + 0;
+ tess.indexes[ numIndexes + 2 ] = numVerts + 2;
+ tess.indexes[ numIndexes + 3 ] = numVerts + 2;
+ tess.indexes[ numIndexes + 4 ] = numVerts + 0;
+ tess.indexes[ numIndexes + 5 ] = numVerts + 1;
+
+ *(int *)tess.vertexColors[ numVerts ] =
+ *(int *)tess.vertexColors[ numVerts + 1 ] =
+ *(int *)tess.vertexColors[ numVerts + 2 ] =
+ *(int *)tess.vertexColors[ numVerts + 3 ] = *(int *)backEnd.color2D;
+
+ tess.xyz[ numVerts ][0] = cmd->x;
+ tess.xyz[ numVerts ][1] = cmd->y;
+ tess.xyz[ numVerts ][2] = 0;
+
+ tess.texCoords[ numVerts ][0][0] = cmd->s1;
+ tess.texCoords[ numVerts ][0][1] = cmd->t1;
+
+ tess.xyz[ numVerts + 1 ][0] = cmd->x + cmd->w;
+ tess.xyz[ numVerts + 1 ][1] = cmd->y;
+ tess.xyz[ numVerts + 1 ][2] = 0;
+
+ tess.texCoords[ numVerts + 1 ][0][0] = cmd->s2;
+ tess.texCoords[ numVerts + 1 ][0][1] = cmd->t1;
+
+ tess.xyz[ numVerts + 2 ][0] = cmd->x + cmd->w;
+ tess.xyz[ numVerts + 2 ][1] = cmd->y + cmd->h;
+ tess.xyz[ numVerts + 2 ][2] = 0;
+
+ tess.texCoords[ numVerts + 2 ][0][0] = cmd->s2;
+ tess.texCoords[ numVerts + 2 ][0][1] = cmd->t2;
+
+ tess.xyz[ numVerts + 3 ][0] = cmd->x;
+ tess.xyz[ numVerts + 3 ][1] = cmd->y + cmd->h;
+ tess.xyz[ numVerts + 3 ][2] = 0;
+
+ tess.texCoords[ numVerts + 3 ][0][0] = cmd->s1;
+ tess.texCoords[ numVerts + 3 ][0][1] = cmd->t2;
+
+ return (const void *)(cmd + 1);
+}
+
+
+/*
+=============
+RB_DrawSurfs
+
+=============
+*/
+const void *RB_DrawSurfs( const void *data ) {
+ const drawSurfsCommand_t *cmd;
+
+ // finish any 2D drawing if needed
+ if ( tess.numIndexes ) {
+ RB_EndSurface();
+ }
+
+ cmd = (const drawSurfsCommand_t *)data;
+
+ backEnd.refdef = cmd->refdef;
+ backEnd.viewParms = cmd->viewParms;
+
+ RB_RenderDrawSurfList( cmd->drawSurfs, cmd->numDrawSurfs );
+
+ return (const void *)(cmd + 1);
+}
+
+
+/*
+=============
+RB_DrawBuffer
+
+=============
+*/
+const void *RB_DrawBuffer( const void *data ) {
+ const drawBufferCommand_t *cmd;
+
+ cmd = (const drawBufferCommand_t *)data;
+
+ qglDrawBuffer( cmd->buffer );
+
+ // clear screen for debugging
+ if ( r_clear->integer ) {
+ qglClearColor( 1, 0, 0.5, 1 );
+ qglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
+ }
+
+ return (const void *)(cmd + 1);
+}
+
+/*
+===============
+RB_ShowImages
+
+Draw all the images to the screen, on top of whatever
+was there. This is used to test for texture thrashing.
+
+Also called by RE_EndRegistration
+===============
+*/
+void RB_ShowImages( void ) {
+ int i;
+ image_t *image;
+ float x, y, w, h;
+ int start, end;
+
+ if ( !backEnd.projection2D ) {
+ RB_SetGL2D();
+ }
+
+ qglClear( GL_COLOR_BUFFER_BIT );
+
+ qglFinish();
+
+ start = ri.Milliseconds();
+
+ for ( i=0 ; i<tr.numImages ; i++ ) {
+ image = tr.images[i];
+
+ w = glConfig.vidWidth / 20;
+ h = glConfig.vidHeight / 15;
+ x = i % 20 * w;
+ y = i / 20 * h;
+
+ // show in proportional size in mode 2
+ if ( r_showImages->integer == 2 ) {
+ w *= image->uploadWidth / 512.0f;
+ h *= image->uploadHeight / 512.0f;
+ }
+
+ GL_Bind( image );
+ qglBegin (GL_QUADS);
+ qglTexCoord2f( 0, 0 );
+ qglVertex2f( x, y );
+ qglTexCoord2f( 1, 0 );
+ qglVertex2f( x + w, y );
+ qglTexCoord2f( 1, 1 );
+ qglVertex2f( x + w, y + h );
+ qglTexCoord2f( 0, 1 );
+ qglVertex2f( x, y + h );
+ qglEnd();
+ }
+
+ qglFinish();
+
+ end = ri.Milliseconds();
+ ri.Printf( PRINT_ALL, "%i msec to draw all images\n", end - start );
+
+}
+
+
+/*
+=============
+RB_SwapBuffers
+
+=============
+*/
+const void *RB_SwapBuffers( const void *data ) {
+ const swapBuffersCommand_t *cmd;
+
+ // finish any 2D drawing if needed
+ if ( tess.numIndexes ) {
+ RB_EndSurface();
+ }
+
+ // texture swapping test
+ if ( r_showImages->integer ) {
+ RB_ShowImages();
+ }
+
+ cmd = (const swapBuffersCommand_t *)data;
+
+ // we measure overdraw by reading back the stencil buffer and
+ // counting up the number of increments that have happened
+ if ( r_measureOverdraw->integer ) {
+ int i;
+ long sum = 0;
+ unsigned char *stencilReadback;
+
+ stencilReadback = ri.Hunk_AllocateTempMemory( glConfig.vidWidth * glConfig.vidHeight );
+ qglReadPixels( 0, 0, glConfig.vidWidth, glConfig.vidHeight, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, stencilReadback );
+
+ for ( i = 0; i < glConfig.vidWidth * glConfig.vidHeight; i++ ) {
+ sum += stencilReadback[i];
+ }
+
+ backEnd.pc.c_overDraw += sum;
+ ri.Hunk_FreeTempMemory( stencilReadback );
+ }
+
+
+ if ( !glState.finishCalled ) {
+ qglFinish();
+ }
+
+ GLimp_LogComment( "***************** RB_SwapBuffers *****************\n\n\n" );
+
+ GLimp_EndFrame();
+
+ backEnd.projection2D = qfalse;
+
+ return (const void *)(cmd + 1);
+}
+
+/*
+====================
+RB_ExecuteRenderCommands
+
+This function will be called synchronously if running without
+smp extensions, or asynchronously by another thread.
+====================
+*/
+void RB_ExecuteRenderCommands( const void *data ) {
+ int t1, t2;
+
+ t1 = ri.Milliseconds ();
+
+ if ( !r_smp->integer || data == backEndData[0]->commands.cmds ) {
+ backEnd.smpFrame = 0;
+ } else {
+ backEnd.smpFrame = 1;
+ }
+
+ while ( 1 ) {
+ switch ( *(const int *)data ) {
+ case RC_SET_COLOR:
+ data = RB_SetColor( data );
+ break;
+ case RC_STRETCH_PIC:
+ data = RB_StretchPic( data );
+ break;
+ case RC_DRAW_SURFS:
+ data = RB_DrawSurfs( data );
+ break;
+ case RC_DRAW_BUFFER:
+ data = RB_DrawBuffer( data );
+ break;
+ case RC_SWAP_BUFFERS:
+ data = RB_SwapBuffers( data );
+ break;
+ case RC_SCREENSHOT:
+ data = RB_TakeScreenshotCmd( data );
+ break;
+
+ case RC_END_OF_LIST:
+ default:
+ // stop rendering on this thread
+ t2 = ri.Milliseconds ();
+ backEnd.pc.msec = t2 - t1;
+ return;
+ }
+ }
+
+}
+
+
+/*
+================
+RB_RenderThread
+================
+*/
+void RB_RenderThread( void ) {
+ const void *data;
+
+ // wait for either a rendering command or a quit command
+ while ( 1 ) {
+ // sleep until we have work to do
+ data = GLimp_RendererSleep();
+
+ if ( !data ) {
+ return; // all done, renderer is shutting down
+ }
+
+ renderThreadActive = qtrue;
+
+ RB_ExecuteRenderCommands( data );
+
+ renderThreadActive = qfalse;
+ }
+}
+
diff --git a/code/renderer/tr_bsp.c b/code/renderer/tr_bsp.c
new file mode 100755
index 0000000..5aefb24
--- /dev/null
+++ b/code/renderer/tr_bsp.c
@@ -0,0 +1,1862 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// tr_map.c
+
+#include "tr_local.h"
+
+/*
+
+Loads and prepares a map file for scene rendering.
+
+A single entry point:
+
+void RE_LoadWorldMap( const char *name );
+
+*/
+
+static world_t s_worldData;
+static byte *fileBase;
+
+int c_subdivisions;
+int c_gridVerts;
+
+//===============================================================================
+
+static void HSVtoRGB( float h, float s, float v, float rgb[3] )
+{
+ int i;
+ float f;
+ float p, q, t;
+
+ h *= 5;
+
+ i = floor( h );
+ f = h - i;
+
+ p = v * ( 1 - s );
+ q = v * ( 1 - s * f );
+ t = v * ( 1 - s * ( 1 - f ) );
+
+ switch ( i )
+ {
+ case 0:
+ rgb[0] = v;
+ rgb[1] = t;
+ rgb[2] = p;
+ break;
+ case 1:
+ rgb[0] = q;
+ rgb[1] = v;
+ rgb[2] = p;
+ break;
+ case 2:
+ rgb[0] = p;
+ rgb[1] = v;
+ rgb[2] = t;
+ break;
+ case 3:
+ rgb[0] = p;
+ rgb[1] = q;
+ rgb[2] = v;
+ break;
+ case 4:
+ rgb[0] = t;
+ rgb[1] = p;
+ rgb[2] = v;
+ break;
+ case 5:
+ rgb[0] = v;
+ rgb[1] = p;
+ rgb[2] = q;
+ break;
+ }
+}
+
+/*
+===============
+R_ColorShiftLightingBytes
+
+===============
+*/
+static void R_ColorShiftLightingBytes( byte in[4], byte out[4] ) {
+ int shift, r, g, b;
+
+ // shift the color data based on overbright range
+ shift = r_mapOverBrightBits->integer - tr.overbrightBits;
+
+ // shift the data based on overbright range
+ r = in[0] << shift;
+ g = in[1] << shift;
+ b = in[2] << shift;
+
+ // normalize by color instead of saturating to white
+ if ( ( r | g | b ) > 255 ) {
+ int max;
+
+ max = r > g ? r : g;
+ max = max > b ? max : b;
+ r = r * 255 / max;
+ g = g * 255 / max;
+ b = b * 255 / max;
+ }
+
+ out[0] = r;
+ out[1] = g;
+ out[2] = b;
+ out[3] = in[3];
+}
+
+/*
+===============
+R_LoadLightmaps
+
+===============
+*/
+#define LIGHTMAP_SIZE 128
+static void R_LoadLightmaps( lump_t *l ) {
+ byte *buf, *buf_p;
+ int len;
+ MAC_STATIC byte image[LIGHTMAP_SIZE*LIGHTMAP_SIZE*4];
+ int i, j;
+ float maxIntensity = 0;
+ double sumIntensity = 0;
+
+ len = l->filelen;
+ if ( !len ) {
+ return;
+ }
+ buf = fileBase + l->fileofs;
+
+ // we are about to upload textures
+ R_SyncRenderThread();
+
+ // create all the lightmaps
+ tr.numLightmaps = len / (LIGHTMAP_SIZE * LIGHTMAP_SIZE * 3);
+ if ( tr.numLightmaps == 1 ) {
+ //FIXME: HACK: maps with only one lightmap turn up fullbright for some reason.
+ //this avoids this, but isn't the correct solution.
+ tr.numLightmaps++;
+ }
+
+ // if we are in r_vertexLight mode, we don't need the lightmaps at all
+ if ( r_vertexLight->integer || glConfig.hardwareType == GLHW_PERMEDIA2 ) {
+ return;
+ }
+
+ for ( i = 0 ; i < tr.numLightmaps ; i++ ) {
+ // expand the 24 bit on-disk to 32 bit
+ buf_p = buf + i * LIGHTMAP_SIZE*LIGHTMAP_SIZE * 3;
+
+ if ( r_lightmap->integer == 2 )
+ { // color code by intensity as development tool (FIXME: check range)
+ for ( j = 0; j < LIGHTMAP_SIZE * LIGHTMAP_SIZE; j++ )
+ {
+ float r = buf_p[j*3+0];
+ float g = buf_p[j*3+1];
+ float b = buf_p[j*3+2];
+ float intensity;
+ float out[3];
+
+ intensity = 0.33f * r + 0.685f * g + 0.063f * b;
+
+ if ( intensity > 255 )
+ intensity = 1.0f;
+ else
+ intensity /= 255.0f;
+
+ if ( intensity > maxIntensity )
+ maxIntensity = intensity;
+
+ HSVtoRGB( intensity, 1.00, 0.50, out );
+
+ image[j*4+0] = out[0] * 255;
+ image[j*4+1] = out[1] * 255;
+ image[j*4+2] = out[2] * 255;
+ image[j*4+3] = 255;
+
+ sumIntensity += intensity;
+ }
+ } else {
+ for ( j = 0 ; j < LIGHTMAP_SIZE * LIGHTMAP_SIZE; j++ ) {
+ R_ColorShiftLightingBytes( &buf_p[j*3], &image[j*4] );
+ image[j*4+3] = 255;
+ }
+ }
+ tr.lightmaps[i] = R_CreateImage( va("*lightmap%d",i), image,
+ LIGHTMAP_SIZE, LIGHTMAP_SIZE, qfalse, qfalse, GL_CLAMP );
+ }
+
+ if ( r_lightmap->integer == 2 ) {
+ ri.Printf( PRINT_ALL, "Brightest lightmap value: %d\n", ( int ) ( maxIntensity * 255 ) );
+ }
+}
+
+
+/*
+=================
+RE_SetWorldVisData
+
+This is called by the clipmodel subsystem so we can share the 1.8 megs of
+space in big maps...
+=================
+*/
+void RE_SetWorldVisData( const byte *vis ) {
+ tr.externalVisData = vis;
+}
+
+
+/*
+=================
+R_LoadVisibility
+=================
+*/
+static void R_LoadVisibility( lump_t *l ) {
+ int len;
+ byte *buf;
+
+ len = ( s_worldData.numClusters + 63 ) & ~63;
+ s_worldData.novis = ri.Hunk_Alloc( len, h_low );
+ Com_Memset( s_worldData.novis, 0xff, len );
+
+ len = l->filelen;
+ if ( !len ) {
+ return;
+ }
+ buf = fileBase + l->fileofs;
+
+ s_worldData.numClusters = LittleLong( ((int *)buf)[0] );
+ s_worldData.clusterBytes = LittleLong( ((int *)buf)[1] );
+
+ // CM_Load should have given us the vis data to share, so
+ // we don't need to allocate another copy
+ if ( tr.externalVisData ) {
+ s_worldData.vis = tr.externalVisData;
+ } else {
+ byte *dest;
+
+ dest = ri.Hunk_Alloc( len - 8, h_low );
+ Com_Memcpy( dest, buf + 8, len - 8 );
+ s_worldData.vis = dest;
+ }
+}
+
+//===============================================================================
+
+
+/*
+===============
+ShaderForShaderNum
+===============
+*/
+static shader_t *ShaderForShaderNum( int shaderNum, int lightmapNum ) {
+ shader_t *shader;
+ dshader_t *dsh;
+
+ shaderNum = LittleLong( shaderNum );
+ if ( shaderNum < 0 || shaderNum >= s_worldData.numShaders ) {
+ ri.Error( ERR_DROP, "ShaderForShaderNum: bad num %i", shaderNum );
+ }
+ dsh = &s_worldData.shaders[ shaderNum ];
+
+ if ( r_vertexLight->integer || glConfig.hardwareType == GLHW_PERMEDIA2 ) {
+ lightmapNum = LIGHTMAP_BY_VERTEX;
+ }
+
+ if ( r_fullbright->integer ) {
+ lightmapNum = LIGHTMAP_WHITEIMAGE;
+ }
+
+ shader = R_FindShader( dsh->shader, lightmapNum, qtrue );
+
+ // if the shader had errors, just use default shader
+ if ( shader->defaultShader ) {
+ return tr.defaultShader;
+ }
+
+ return shader;
+}
+
+/*
+===============
+ParseFace
+===============
+*/
+static void ParseFace( dsurface_t *ds, drawVert_t *verts, msurface_t *surf, int *indexes ) {
+ int i, j;
+ srfSurfaceFace_t *cv;
+ int numPoints, numIndexes;
+ int lightmapNum;
+ int sfaceSize, ofsIndexes;
+
+ lightmapNum = LittleLong( ds->lightmapNum );
+
+ // get fog volume
+ surf->fogIndex = LittleLong( ds->fogNum ) + 1;
+
+ // get shader value
+ surf->shader = ShaderForShaderNum( ds->shaderNum, lightmapNum );
+ if ( r_singleShader->integer && !surf->shader->isSky ) {
+ surf->shader = tr.defaultShader;
+ }
+
+ numPoints = LittleLong( ds->numVerts );
+ if (numPoints > MAX_FACE_POINTS) {
+ ri.Printf( PRINT_WARNING, "WARNING: MAX_FACE_POINTS exceeded: %i\n", numPoints);
+ numPoints = MAX_FACE_POINTS;
+ surf->shader = tr.defaultShader;
+ }
+
+ numIndexes = LittleLong( ds->numIndexes );
+
+ // create the srfSurfaceFace_t
+ sfaceSize = ( int ) &((srfSurfaceFace_t *)0)->points[numPoints];
+ ofsIndexes = sfaceSize;
+ sfaceSize += sizeof( int ) * numIndexes;
+
+ cv = ri.Hunk_Alloc( sfaceSize, h_low );
+ cv->surfaceType = SF_FACE;
+ cv->numPoints = numPoints;
+ cv->numIndices = numIndexes;
+ cv->ofsIndices = ofsIndexes;
+
+ verts += LittleLong( ds->firstVert );
+ for ( i = 0 ; i < numPoints ; i++ ) {
+ for ( j = 0 ; j < 3 ; j++ ) {
+ cv->points[i][j] = LittleFloat( verts[i].xyz[j] );
+ }
+ for ( j = 0 ; j < 2 ; j++ ) {
+ cv->points[i][3+j] = LittleFloat( verts[i].st[j] );
+ cv->points[i][5+j] = LittleFloat( verts[i].lightmap[j] );
+ }
+ R_ColorShiftLightingBytes( verts[i].color, (byte *)&cv->points[i][7] );
+ }
+
+ indexes += LittleLong( ds->firstIndex );
+ for ( i = 0 ; i < numIndexes ; i++ ) {
+ ((int *)((byte *)cv + cv->ofsIndices ))[i] = LittleLong( indexes[ i ] );
+ }
+
+ // take the plane information from the lightmap vector
+ for ( i = 0 ; i < 3 ; i++ ) {
+ cv->plane.normal[i] = LittleFloat( ds->lightmapVecs[2][i] );
+ }
+ cv->plane.dist = DotProduct( cv->points[0], cv->plane.normal );
+ SetPlaneSignbits( &cv->plane );
+ cv->plane.type = PlaneTypeForNormal( cv->plane.normal );
+
+ surf->data = (surfaceType_t *)cv;
+}
+
+
+/*
+===============
+ParseMesh
+===============
+*/
+static void ParseMesh ( dsurface_t *ds, drawVert_t *verts, msurface_t *surf ) {
+ srfGridMesh_t *grid;
+ int i, j;
+ int width, height, numPoints;
+ MAC_STATIC drawVert_t points[MAX_PATCH_SIZE*MAX_PATCH_SIZE];
+ int lightmapNum;
+ vec3_t bounds[2];
+ vec3_t tmpVec;
+ static surfaceType_t skipData = SF_SKIP;
+
+ lightmapNum = LittleLong( ds->lightmapNum );
+
+ // get fog volume
+ surf->fogIndex = LittleLong( ds->fogNum ) + 1;
+
+ // get shader value
+ surf->shader = ShaderForShaderNum( ds->shaderNum, lightmapNum );
+ if ( r_singleShader->integer && !surf->shader->isSky ) {
+ surf->shader = tr.defaultShader;
+ }
+
+ // we may have a nodraw surface, because they might still need to
+ // be around for movement clipping
+ if ( s_worldData.shaders[ LittleLong( ds->shaderNum ) ].surfaceFlags & SURF_NODRAW ) {
+ surf->data = &skipData;
+ return;
+ }
+
+ width = LittleLong( ds->patchWidth );
+ height = LittleLong( ds->patchHeight );
+
+ verts += LittleLong( ds->firstVert );
+ numPoints = width * height;
+ for ( i = 0 ; i < numPoints ; i++ ) {
+ for ( j = 0 ; j < 3 ; j++ ) {
+ points[i].xyz[j] = LittleFloat( verts[i].xyz[j] );
+ points[i].normal[j] = LittleFloat( verts[i].normal[j] );
+ }
+ for ( j = 0 ; j < 2 ; j++ ) {
+ points[i].st[j] = LittleFloat( verts[i].st[j] );
+ points[i].lightmap[j] = LittleFloat( verts[i].lightmap[j] );
+ }
+ R_ColorShiftLightingBytes( verts[i].color, points[i].color );
+ }
+
+ // pre-tesseleate
+ grid = R_SubdividePatchToGrid( width, height, points );
+ surf->data = (surfaceType_t *)grid;
+
+ // copy the level of detail origin, which is the center
+ // of the group of all curves that must subdivide the same
+ // to avoid cracking
+ for ( i = 0 ; i < 3 ; i++ ) {
+ bounds[0][i] = LittleFloat( ds->lightmapVecs[0][i] );
+ bounds[1][i] = LittleFloat( ds->lightmapVecs[1][i] );
+ }
+ VectorAdd( bounds[0], bounds[1], bounds[1] );
+ VectorScale( bounds[1], 0.5f, grid->lodOrigin );
+ VectorSubtract( bounds[0], grid->lodOrigin, tmpVec );
+ grid->lodRadius = VectorLength( tmpVec );
+}
+
+/*
+===============
+ParseTriSurf
+===============
+*/
+static void ParseTriSurf( dsurface_t *ds, drawVert_t *verts, msurface_t *surf, int *indexes ) {
+ srfTriangles_t *tri;
+ int i, j;
+ int numVerts, numIndexes;
+
+ // get fog volume
+ surf->fogIndex = LittleLong( ds->fogNum ) + 1;
+
+ // get shader
+ surf->shader = ShaderForShaderNum( ds->shaderNum, LIGHTMAP_BY_VERTEX );
+ if ( r_singleShader->integer && !surf->shader->isSky ) {
+ surf->shader = tr.defaultShader;
+ }
+
+ numVerts = LittleLong( ds->numVerts );
+ numIndexes = LittleLong( ds->numIndexes );
+
+ tri = ri.Hunk_Alloc( sizeof( *tri ) + numVerts * sizeof( tri->verts[0] )
+ + numIndexes * sizeof( tri->indexes[0] ), h_low );
+ tri->surfaceType = SF_TRIANGLES;
+ tri->numVerts = numVerts;
+ tri->numIndexes = numIndexes;
+ tri->verts = (drawVert_t *)(tri + 1);
+ tri->indexes = (int *)(tri->verts + tri->numVerts );
+
+ surf->data = (surfaceType_t *)tri;
+
+ // copy vertexes
+ ClearBounds( tri->bounds[0], tri->bounds[1] );
+ verts += LittleLong( ds->firstVert );
+ for ( i = 0 ; i < numVerts ; i++ ) {
+ for ( j = 0 ; j < 3 ; j++ ) {
+ tri->verts[i].xyz[j] = LittleFloat( verts[i].xyz[j] );
+ tri->verts[i].normal[j] = LittleFloat( verts[i].normal[j] );
+ }
+ AddPointToBounds( tri->verts[i].xyz, tri->bounds[0], tri->bounds[1] );
+ for ( j = 0 ; j < 2 ; j++ ) {
+ tri->verts[i].st[j] = LittleFloat( verts[i].st[j] );
+ tri->verts[i].lightmap[j] = LittleFloat( verts[i].lightmap[j] );
+ }
+
+ R_ColorShiftLightingBytes( verts[i].color, tri->verts[i].color );
+ }
+
+ // copy indexes
+ indexes += LittleLong( ds->firstIndex );
+ for ( i = 0 ; i < numIndexes ; i++ ) {
+ tri->indexes[i] = LittleLong( indexes[i] );
+ if ( tri->indexes[i] < 0 || tri->indexes[i] >= numVerts ) {
+ ri.Error( ERR_DROP, "Bad index in triangle surface" );
+ }
+ }
+}
+
+/*
+===============
+ParseFlare
+===============
+*/
+static void ParseFlare( dsurface_t *ds, drawVert_t *verts, msurface_t *surf, int *indexes ) {
+ srfFlare_t *flare;
+ int i;
+
+ // get fog volume
+ surf->fogIndex = LittleLong( ds->fogNum ) + 1;
+
+ // get shader
+ surf->shader = ShaderForShaderNum( ds->shaderNum, LIGHTMAP_BY_VERTEX );
+ if ( r_singleShader->integer && !surf->shader->isSky ) {
+ surf->shader = tr.defaultShader;
+ }
+
+ flare = ri.Hunk_Alloc( sizeof( *flare ), h_low );
+ flare->surfaceType = SF_FLARE;
+
+ surf->data = (surfaceType_t *)flare;
+
+ for ( i = 0 ; i < 3 ; i++ ) {
+ flare->origin[i] = LittleFloat( ds->lightmapOrigin[i] );
+ flare->color[i] = LittleFloat( ds->lightmapVecs[0][i] );
+ flare->normal[i] = LittleFloat( ds->lightmapVecs[2][i] );
+ }
+}
+
+
+/*
+=================
+R_MergedWidthPoints
+
+returns true if there are grid points merged on a width edge
+=================
+*/
+int R_MergedWidthPoints(srfGridMesh_t *grid, int offset) {
+ int i, j;
+
+ for (i = 1; i < grid->width-1; i++) {
+ for (j = i + 1; j < grid->width-1; j++) {
+ if ( fabs(grid->verts[i + offset].xyz[0] - grid->verts[j + offset].xyz[0]) > .1) continue;
+ if ( fabs(grid->verts[i + offset].xyz[1] - grid->verts[j + offset].xyz[1]) > .1) continue;
+ if ( fabs(grid->verts[i + offset].xyz[2] - grid->verts[j + offset].xyz[2]) > .1) continue;
+ return qtrue;
+ }
+ }
+ return qfalse;
+}
+
+/*
+=================
+R_MergedHeightPoints
+
+returns true if there are grid points merged on a height edge
+=================
+*/
+int R_MergedHeightPoints(srfGridMesh_t *grid, int offset) {
+ int i, j;
+
+ for (i = 1; i < grid->height-1; i++) {
+ for (j = i + 1; j < grid->height-1; j++) {
+ if ( fabs(grid->verts[grid->width * i + offset].xyz[0] - grid->verts[grid->width * j + offset].xyz[0]) > .1) continue;
+ if ( fabs(grid->verts[grid->width * i + offset].xyz[1] - grid->verts[grid->width * j + offset].xyz[1]) > .1) continue;
+ if ( fabs(grid->verts[grid->width * i + offset].xyz[2] - grid->verts[grid->width * j + offset].xyz[2]) > .1) continue;
+ return qtrue;
+ }
+ }
+ return qfalse;
+}
+
+/*
+=================
+R_FixSharedVertexLodError_r
+
+NOTE: never sync LoD through grid edges with merged points!
+
+FIXME: write generalized version that also avoids cracks between a patch and one that meets half way?
+=================
+*/
+void R_FixSharedVertexLodError_r( int start, srfGridMesh_t *grid1 ) {
+ int j, k, l, m, n, offset1, offset2, touch;
+ srfGridMesh_t *grid2;
+
+ for ( j = start; j < s_worldData.numsurfaces; j++ ) {
+ //
+ grid2 = (srfGridMesh_t *) s_worldData.surfaces[j].data;
+ // if this surface is not a grid
+ if ( grid2->surfaceType != SF_GRID ) continue;
+ // if the LOD errors are already fixed for this patch
+ if ( grid2->lodFixed == 2 ) continue;
+ // grids in the same LOD group should have the exact same lod radius
+ if ( grid1->lodRadius != grid2->lodRadius ) continue;
+ // grids in the same LOD group should have the exact same lod origin
+ if ( grid1->lodOrigin[0] != grid2->lodOrigin[0] ) continue;
+ if ( grid1->lodOrigin[1] != grid2->lodOrigin[1] ) continue;
+ if ( grid1->lodOrigin[2] != grid2->lodOrigin[2] ) continue;
+ //
+ touch = qfalse;
+ for (n = 0; n < 2; n++) {
+ //
+ if (n) offset1 = (grid1->height-1) * grid1->width;
+ else offset1 = 0;
+ if (R_MergedWidthPoints(grid1, offset1)) continue;
+ for (k = 1; k < grid1->width-1; k++) {
+ for (m = 0; m < 2; m++) {
+
+ if (m) offset2 = (grid2->height-1) * grid2->width;
+ else offset2 = 0;
+ if (R_MergedWidthPoints(grid2, offset2)) continue;
+ for ( l = 1; l < grid2->width-1; l++) {
+ //
+ if ( fabs(grid1->verts[k + offset1].xyz[0] - grid2->verts[l + offset2].xyz[0]) > .1) continue;
+ if ( fabs(grid1->verts[k + offset1].xyz[1] - grid2->verts[l + offset2].xyz[1]) > .1) continue;
+ if ( fabs(grid1->verts[k + offset1].xyz[2] - grid2->verts[l + offset2].xyz[2]) > .1) continue;
+ // ok the points are equal and should have the same lod error
+ grid2->widthLodError[l] = grid1->widthLodError[k];
+ touch = qtrue;
+ }
+ }
+ for (m = 0; m < 2; m++) {
+
+ if (m) offset2 = grid2->width-1;
+ else offset2 = 0;
+ if (R_MergedHeightPoints(grid2, offset2)) continue;
+ for ( l = 1; l < grid2->height-1; l++) {
+ //
+ if ( fabs(grid1->verts[k + offset1].xyz[0] - grid2->verts[grid2->width * l + offset2].xyz[0]) > .1) continue;
+ if ( fabs(grid1->verts[k + offset1].xyz[1] - grid2->verts[grid2->width * l + offset2].xyz[1]) > .1) continue;
+ if ( fabs(grid1->verts[k + offset1].xyz[2] - grid2->verts[grid2->width * l + offset2].xyz[2]) > .1) continue;
+ // ok the points are equal and should have the same lod error
+ grid2->heightLodError[l] = grid1->widthLodError[k];
+ touch = qtrue;
+ }
+ }
+ }
+ }
+ for (n = 0; n < 2; n++) {
+ //
+ if (n) offset1 = grid1->width-1;
+ else offset1 = 0;
+ if (R_MergedHeightPoints(grid1, offset1)) continue;
+ for (k = 1; k < grid1->height-1; k++) {
+ for (m = 0; m < 2; m++) {
+
+ if (m) offset2 = (grid2->height-1) * grid2->width;
+ else offset2 = 0;
+ if (R_MergedWidthPoints(grid2, offset2)) continue;
+ for ( l = 1; l < grid2->width-1; l++) {
+ //
+ if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[0] - grid2->verts[l + offset2].xyz[0]) > .1) continue;
+ if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[1] - grid2->verts[l + offset2].xyz[1]) > .1) continue;
+ if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[2] - grid2->verts[l + offset2].xyz[2]) > .1) continue;
+ // ok the points are equal and should have the same lod error
+ grid2->widthLodError[l] = grid1->heightLodError[k];
+ touch = qtrue;
+ }
+ }
+ for (m = 0; m < 2; m++) {
+
+ if (m) offset2 = grid2->width-1;
+ else offset2 = 0;
+ if (R_MergedHeightPoints(grid2, offset2)) continue;
+ for ( l = 1; l < grid2->height-1; l++) {
+ //
+ if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[0] - grid2->verts[grid2->width * l + offset2].xyz[0]) > .1) continue;
+ if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[1] - grid2->verts[grid2->width * l + offset2].xyz[1]) > .1) continue;
+ if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[2] - grid2->verts[grid2->width * l + offset2].xyz[2]) > .1) continue;
+ // ok the points are equal and should have the same lod error
+ grid2->heightLodError[l] = grid1->heightLodError[k];
+ touch = qtrue;
+ }
+ }
+ }
+ }
+ if (touch) {
+ grid2->lodFixed = 2;
+ R_FixSharedVertexLodError_r ( start, grid2 );
+ //NOTE: this would be correct but makes things really slow
+ //grid2->lodFixed = 1;
+ }
+ }
+}
+
+/*
+=================
+R_FixSharedVertexLodError
+
+This function assumes that all patches in one group are nicely stitched together for the highest LoD.
+If this is not the case this function will still do its job but won't fix the highest LoD cracks.
+=================
+*/
+void R_FixSharedVertexLodError( void ) {
+ int i;
+ srfGridMesh_t *grid1;
+
+ for ( i = 0; i < s_worldData.numsurfaces; i++ ) {
+ //
+ grid1 = (srfGridMesh_t *) s_worldData.surfaces[i].data;
+ // if this surface is not a grid
+ if ( grid1->surfaceType != SF_GRID )
+ continue;
+ //
+ if ( grid1->lodFixed )
+ continue;
+ //
+ grid1->lodFixed = 2;
+ // recursively fix other patches in the same LOD group
+ R_FixSharedVertexLodError_r( i + 1, grid1);
+ }
+}
+
+
+/*
+===============
+R_StitchPatches
+===============
+*/
+int R_StitchPatches( int grid1num, int grid2num ) {
+ float *v1, *v2;
+ srfGridMesh_t *grid1, *grid2;
+ int k, l, m, n, offset1, offset2, row, column;
+
+ grid1 = (srfGridMesh_t *) s_worldData.surfaces[grid1num].data;
+ grid2 = (srfGridMesh_t *) s_worldData.surfaces[grid2num].data;
+ for (n = 0; n < 2; n++) {
+ //
+ if (n) offset1 = (grid1->height-1) * grid1->width;
+ else offset1 = 0;
+ if (R_MergedWidthPoints(grid1, offset1))
+ continue;
+ for (k = 0; k < grid1->width-2; k += 2) {
+
+ for (m = 0; m < 2; m++) {
+
+ if ( grid2->width >= MAX_GRID_SIZE )
+ break;
+ if (m) offset2 = (grid2->height-1) * grid2->width;
+ else offset2 = 0;
+ for ( l = 0; l < grid2->width-1; l++) {
+ //
+ v1 = grid1->verts[k + offset1].xyz;
+ v2 = grid2->verts[l + offset2].xyz;
+ if ( fabs(v1[0] - v2[0]) > .1)
+ continue;
+ if ( fabs(v1[1] - v2[1]) > .1)
+ continue;
+ if ( fabs(v1[2] - v2[2]) > .1)
+ continue;
+
+ v1 = grid1->verts[k + 2 + offset1].xyz;
+ v2 = grid2->verts[l + 1 + offset2].xyz;
+ if ( fabs(v1[0] - v2[0]) > .1)
+ continue;
+ if ( fabs(v1[1] - v2[1]) > .1)
+ continue;
+ if ( fabs(v1[2] - v2[2]) > .1)
+ continue;
+ //
+ v1 = grid2->verts[l + offset2].xyz;
+ v2 = grid2->verts[l + 1 + offset2].xyz;
+ if ( fabs(v1[0] - v2[0]) < .01 &&
+ fabs(v1[1] - v2[1]) < .01 &&
+ fabs(v1[2] - v2[2]) < .01)
+ continue;
+ //
+ //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" );
+ // insert column into grid2 right after after column l
+ if (m) row = grid2->height-1;
+ else row = 0;
+ grid2 = R_GridInsertColumn( grid2, l+1, row,
+ grid1->verts[k + 1 + offset1].xyz, grid1->widthLodError[k+1]);
+ grid2->lodStitched = qfalse;
+ s_worldData.surfaces[grid2num].data = (void *) grid2;
+ return qtrue;
+ }
+ }
+ for (m = 0; m < 2; m++) {
+
+ if (grid2->height >= MAX_GRID_SIZE)
+ break;
+ if (m) offset2 = grid2->width-1;
+ else offset2 = 0;
+ for ( l = 0; l < grid2->height-1; l++) {
+ //
+ v1 = grid1->verts[k + offset1].xyz;
+ v2 = grid2->verts[grid2->width * l + offset2].xyz;
+ if ( fabs(v1[0] - v2[0]) > .1)
+ continue;
+ if ( fabs(v1[1] - v2[1]) > .1)
+ continue;
+ if ( fabs(v1[2] - v2[2]) > .1)
+ continue;
+
+ v1 = grid1->verts[k + 2 + offset1].xyz;
+ v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz;
+ if ( fabs(v1[0] - v2[0]) > .1)
+ continue;
+ if ( fabs(v1[1] - v2[1]) > .1)
+ continue;
+ if ( fabs(v1[2] - v2[2]) > .1)
+ continue;
+ //
+ v1 = grid2->verts[grid2->width * l + offset2].xyz;
+ v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz;
+ if ( fabs(v1[0] - v2[0]) < .01 &&
+ fabs(v1[1] - v2[1]) < .01 &&
+ fabs(v1[2] - v2[2]) < .01)
+ continue;
+ //
+ //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" );
+ // insert row into grid2 right after after row l
+ if (m) column = grid2->width-1;
+ else column = 0;
+ grid2 = R_GridInsertRow( grid2, l+1, column,
+ grid1->verts[k + 1 + offset1].xyz, grid1->widthLodError[k+1]);
+ grid2->lodStitched = qfalse;
+ s_worldData.surfaces[grid2num].data = (void *) grid2;
+ return qtrue;
+ }
+ }
+ }
+ }
+ for (n = 0; n < 2; n++) {
+ //
+ if (n) offset1 = grid1->width-1;
+ else offset1 = 0;
+ if (R_MergedHeightPoints(grid1, offset1))
+ continue;
+ for (k = 0; k < grid1->height-2; k += 2) {
+ for (m = 0; m < 2; m++) {
+
+ if ( grid2->width >= MAX_GRID_SIZE )
+ break;
+ if (m) offset2 = (grid2->height-1) * grid2->width;
+ else offset2 = 0;
+ for ( l = 0; l < grid2->width-1; l++) {
+ //
+ v1 = grid1->verts[grid1->width * k + offset1].xyz;
+ v2 = grid2->verts[l + offset2].xyz;
+ if ( fabs(v1[0] - v2[0]) > .1)
+ continue;
+ if ( fabs(v1[1] - v2[1]) > .1)
+ continue;
+ if ( fabs(v1[2] - v2[2]) > .1)
+ continue;
+
+ v1 = grid1->verts[grid1->width * (k + 2) + offset1].xyz;
+ v2 = grid2->verts[l + 1 + offset2].xyz;
+ if ( fabs(v1[0] - v2[0]) > .1)
+ continue;
+ if ( fabs(v1[1] - v2[1]) > .1)
+ continue;
+ if ( fabs(v1[2] - v2[2]) > .1)
+ continue;
+ //
+ v1 = grid2->verts[l + offset2].xyz;
+ v2 = grid2->verts[(l + 1) + offset2].xyz;
+ if ( fabs(v1[0] - v2[0]) < .01 &&
+ fabs(v1[1] - v2[1]) < .01 &&
+ fabs(v1[2] - v2[2]) < .01)
+ continue;
+ //
+ //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" );
+ // insert column into grid2 right after after column l
+ if (m) row = grid2->height-1;
+ else row = 0;
+ grid2 = R_GridInsertColumn( grid2, l+1, row,
+ grid1->verts[grid1->width * (k + 1) + offset1].xyz, grid1->heightLodError[k+1]);
+ grid2->lodStitched = qfalse;
+ s_worldData.surfaces[grid2num].data = (void *) grid2;
+ return qtrue;
+ }
+ }
+ for (m = 0; m < 2; m++) {
+
+ if (grid2->height >= MAX_GRID_SIZE)
+ break;
+ if (m) offset2 = grid2->width-1;
+ else offset2 = 0;
+ for ( l = 0; l < grid2->height-1; l++) {
+ //
+ v1 = grid1->verts[grid1->width * k + offset1].xyz;
+ v2 = grid2->verts[grid2->width * l + offset2].xyz;
+ if ( fabs(v1[0] - v2[0]) > .1)
+ continue;
+ if ( fabs(v1[1] - v2[1]) > .1)
+ continue;
+ if ( fabs(v1[2] - v2[2]) > .1)
+ continue;
+
+ v1 = grid1->verts[grid1->width * (k + 2) + offset1].xyz;
+ v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz;
+ if ( fabs(v1[0] - v2[0]) > .1)
+ continue;
+ if ( fabs(v1[1] - v2[1]) > .1)
+ continue;
+ if ( fabs(v1[2] - v2[2]) > .1)
+ continue;
+ //
+ v1 = grid2->verts[grid2->width * l + offset2].xyz;
+ v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz;
+ if ( fabs(v1[0] - v2[0]) < .01 &&
+ fabs(v1[1] - v2[1]) < .01 &&
+ fabs(v1[2] - v2[2]) < .01)
+ continue;
+ //
+ //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" );
+ // insert row into grid2 right after after row l
+ if (m) column = grid2->width-1;
+ else column = 0;
+ grid2 = R_GridInsertRow( grid2, l+1, column,
+ grid1->verts[grid1->width * (k + 1) + offset1].xyz, grid1->heightLodError[k+1]);
+ grid2->lodStitched = qfalse;
+ s_worldData.surfaces[grid2num].data = (void *) grid2;
+ return qtrue;
+ }
+ }
+ }
+ }
+ for (n = 0; n < 2; n++) {
+ //
+ if (n) offset1 = (grid1->height-1) * grid1->width;
+ else offset1 = 0;
+ if (R_MergedWidthPoints(grid1, offset1))
+ continue;
+ for (k = grid1->width-1; k > 1; k -= 2) {
+
+ for (m = 0; m < 2; m++) {
+
+ if ( grid2->width >= MAX_GRID_SIZE )
+ break;
+ if (m) offset2 = (grid2->height-1) * grid2->width;
+ else offset2 = 0;
+ for ( l = 0; l < grid2->width-1; l++) {
+ //
+ v1 = grid1->verts[k + offset1].xyz;
+ v2 = grid2->verts[l + offset2].xyz;
+ if ( fabs(v1[0] - v2[0]) > .1)
+ continue;
+ if ( fabs(v1[1] - v2[1]) > .1)
+ continue;
+ if ( fabs(v1[2] - v2[2]) > .1)
+ continue;
+
+ v1 = grid1->verts[k - 2 + offset1].xyz;
+ v2 = grid2->verts[l + 1 + offset2].xyz;
+ if ( fabs(v1[0] - v2[0]) > .1)
+ continue;
+ if ( fabs(v1[1] - v2[1]) > .1)
+ continue;
+ if ( fabs(v1[2] - v2[2]) > .1)
+ continue;
+ //
+ v1 = grid2->verts[l + offset2].xyz;
+ v2 = grid2->verts[(l + 1) + offset2].xyz;
+ if ( fabs(v1[0] - v2[0]) < .01 &&
+ fabs(v1[1] - v2[1]) < .01 &&
+ fabs(v1[2] - v2[2]) < .01)
+ continue;
+ //
+ //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" );
+ // insert column into grid2 right after after column l
+ if (m) row = grid2->height-1;
+ else row = 0;
+ grid2 = R_GridInsertColumn( grid2, l+1, row,
+ grid1->verts[k - 1 + offset1].xyz, grid1->widthLodError[k+1]);
+ grid2->lodStitched = qfalse;
+ s_worldData.surfaces[grid2num].data = (void *) grid2;
+ return qtrue;
+ }
+ }
+ for (m = 0; m < 2; m++) {
+
+ if (grid2->height >= MAX_GRID_SIZE)
+ break;
+ if (m) offset2 = grid2->width-1;
+ else offset2 = 0;
+ for ( l = 0; l < grid2->height-1; l++) {
+ //
+ v1 = grid1->verts[k + offset1].xyz;
+ v2 = grid2->verts[grid2->width * l + offset2].xyz;
+ if ( fabs(v1[0] - v2[0]) > .1)
+ continue;
+ if ( fabs(v1[1] - v2[1]) > .1)
+ continue;
+ if ( fabs(v1[2] - v2[2]) > .1)
+ continue;
+
+ v1 = grid1->verts[k - 2 + offset1].xyz;
+ v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz;
+ if ( fabs(v1[0] - v2[0]) > .1)
+ continue;
+ if ( fabs(v1[1] - v2[1]) > .1)
+ continue;
+ if ( fabs(v1[2] - v2[2]) > .1)
+ continue;
+ //
+ v1 = grid2->verts[grid2->width * l + offset2].xyz;
+ v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz;
+ if ( fabs(v1[0] - v2[0]) < .01 &&
+ fabs(v1[1] - v2[1]) < .01 &&
+ fabs(v1[2] - v2[2]) < .01)
+ continue;
+ //
+ //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" );
+ // insert row into grid2 right after after row l
+ if (m) column = grid2->width-1;
+ else column = 0;
+ grid2 = R_GridInsertRow( grid2, l+1, column,
+ grid1->verts[k - 1 + offset1].xyz, grid1->widthLodError[k+1]);
+ if (!grid2)
+ break;
+ grid2->lodStitched = qfalse;
+ s_worldData.surfaces[grid2num].data = (void *) grid2;
+ return qtrue;
+ }
+ }
+ }
+ }
+ for (n = 0; n < 2; n++) {
+ //
+ if (n) offset1 = grid1->width-1;
+ else offset1 = 0;
+ if (R_MergedHeightPoints(grid1, offset1))
+ continue;
+ for (k = grid1->height-1; k > 1; k -= 2) {
+ for (m = 0; m < 2; m++) {
+
+ if ( grid2->width >= MAX_GRID_SIZE )
+ break;
+ if (m) offset2 = (grid2->height-1) * grid2->width;
+ else offset2 = 0;
+ for ( l = 0; l < grid2->width-1; l++) {
+ //
+ v1 = grid1->verts[grid1->width * k + offset1].xyz;
+ v2 = grid2->verts[l + offset2].xyz;
+ if ( fabs(v1[0] - v2[0]) > .1)
+ continue;
+ if ( fabs(v1[1] - v2[1]) > .1)
+ continue;
+ if ( fabs(v1[2] - v2[2]) > .1)
+ continue;
+
+ v1 = grid1->verts[grid1->width * (k - 2) + offset1].xyz;
+ v2 = grid2->verts[l + 1 + offset2].xyz;
+ if ( fabs(v1[0] - v2[0]) > .1)
+ continue;
+ if ( fabs(v1[1] - v2[1]) > .1)
+ continue;
+ if ( fabs(v1[2] - v2[2]) > .1)
+ continue;
+ //
+ v1 = grid2->verts[l + offset2].xyz;
+ v2 = grid2->verts[(l + 1) + offset2].xyz;
+ if ( fabs(v1[0] - v2[0]) < .01 &&
+ fabs(v1[1] - v2[1]) < .01 &&
+ fabs(v1[2] - v2[2]) < .01)
+ continue;
+ //
+ //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" );
+ // insert column into grid2 right after after column l
+ if (m) row = grid2->height-1;
+ else row = 0;
+ grid2 = R_GridInsertColumn( grid2, l+1, row,
+ grid1->verts[grid1->width * (k - 1) + offset1].xyz, grid1->heightLodError[k+1]);
+ grid2->lodStitched = qfalse;
+ s_worldData.surfaces[grid2num].data = (void *) grid2;
+ return qtrue;
+ }
+ }
+ for (m = 0; m < 2; m++) {
+
+ if (grid2->height >= MAX_GRID_SIZE)
+ break;
+ if (m) offset2 = grid2->width-1;
+ else offset2 = 0;
+ for ( l = 0; l < grid2->height-1; l++) {
+ //
+ v1 = grid1->verts[grid1->width * k + offset1].xyz;
+ v2 = grid2->verts[grid2->width * l + offset2].xyz;
+ if ( fabs(v1[0] - v2[0]) > .1)
+ continue;
+ if ( fabs(v1[1] - v2[1]) > .1)
+ continue;
+ if ( fabs(v1[2] - v2[2]) > .1)
+ continue;
+
+ v1 = grid1->verts[grid1->width * (k - 2) + offset1].xyz;
+ v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz;
+ if ( fabs(v1[0] - v2[0]) > .1)
+ continue;
+ if ( fabs(v1[1] - v2[1]) > .1)
+ continue;
+ if ( fabs(v1[2] - v2[2]) > .1)
+ continue;
+ //
+ v1 = grid2->verts[grid2->width * l + offset2].xyz;
+ v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz;
+ if ( fabs(v1[0] - v2[0]) < .01 &&
+ fabs(v1[1] - v2[1]) < .01 &&
+ fabs(v1[2] - v2[2]) < .01)
+ continue;
+ //
+ //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" );
+ // insert row into grid2 right after after row l
+ if (m) column = grid2->width-1;
+ else column = 0;
+ grid2 = R_GridInsertRow( grid2, l+1, column,
+ grid1->verts[grid1->width * (k - 1) + offset1].xyz, grid1->heightLodError[k+1]);
+ grid2->lodStitched = qfalse;
+ s_worldData.surfaces[grid2num].data = (void *) grid2;
+ return qtrue;
+ }
+ }
+ }
+ }
+ return qfalse;
+}
+
+/*
+===============
+R_TryStitchPatch
+
+This function will try to stitch patches in the same LoD group together for the highest LoD.
+
+Only single missing vertice cracks will be fixed.
+
+Vertices will be joined at the patch side a crack is first found, at the other side
+of the patch (on the same row or column) the vertices will not be joined and cracks
+might still appear at that side.
+===============
+*/
+int R_TryStitchingPatch( int grid1num ) {
+ int j, numstitches;
+ srfGridMesh_t *grid1, *grid2;
+
+ numstitches = 0;
+ grid1 = (srfGridMesh_t *) s_worldData.surfaces[grid1num].data;
+ for ( j = 0; j < s_worldData.numsurfaces; j++ ) {
+ //
+ grid2 = (srfGridMesh_t *) s_worldData.surfaces[j].data;
+ // if this surface is not a grid
+ if ( grid2->surfaceType != SF_GRID ) continue;
+ // grids in the same LOD group should have the exact same lod radius
+ if ( grid1->lodRadius != grid2->lodRadius ) continue;
+ // grids in the same LOD group should have the exact same lod origin
+ if ( grid1->lodOrigin[0] != grid2->lodOrigin[0] ) continue;
+ if ( grid1->lodOrigin[1] != grid2->lodOrigin[1] ) continue;
+ if ( grid1->lodOrigin[2] != grid2->lodOrigin[2] ) continue;
+ //
+ while (R_StitchPatches(grid1num, j))
+ {
+ numstitches++;
+ }
+ }
+ return numstitches;
+}
+
+/*
+===============
+R_StitchAllPatches
+===============
+*/
+void R_StitchAllPatches( void ) {
+ int i, stitched, numstitches;
+ srfGridMesh_t *grid1;
+
+ numstitches = 0;
+ do
+ {
+ stitched = qfalse;
+ for ( i = 0; i < s_worldData.numsurfaces; i++ ) {
+ //
+ grid1 = (srfGridMesh_t *) s_worldData.surfaces[i].data;
+ // if this surface is not a grid
+ if ( grid1->surfaceType != SF_GRID )
+ continue;
+ //
+ if ( grid1->lodStitched )
+ continue;
+ //
+ grid1->lodStitched = qtrue;
+ stitched = qtrue;
+ //
+ numstitches += R_TryStitchingPatch( i );
+ }
+ }
+ while (stitched);
+ ri.Printf( PRINT_ALL, "stitched %d LoD cracks\n", numstitches );
+}
+
+/*
+===============
+R_MovePatchSurfacesToHunk
+===============
+*/
+void R_MovePatchSurfacesToHunk(void) {
+ int i, size;
+ srfGridMesh_t *grid, *hunkgrid;
+
+ for ( i = 0; i < s_worldData.numsurfaces; i++ ) {
+ //
+ grid = (srfGridMesh_t *) s_worldData.surfaces[i].data;
+ // if this surface is not a grid
+ if ( grid->surfaceType != SF_GRID )
+ continue;
+ //
+ size = (grid->width * grid->height - 1) * sizeof( drawVert_t ) + sizeof( *grid );
+ hunkgrid = ri.Hunk_Alloc( size, h_low );
+ Com_Memcpy(hunkgrid, grid, size);
+
+ hunkgrid->widthLodError = ri.Hunk_Alloc( grid->width * 4, h_low );
+ Com_Memcpy( hunkgrid->widthLodError, grid->widthLodError, grid->width * 4 );
+
+ hunkgrid->heightLodError = ri.Hunk_Alloc( grid->height * 4, h_low );
+ Com_Memcpy( grid->heightLodError, grid->heightLodError, grid->height * 4 );
+
+ R_FreeSurfaceGridMesh( grid );
+
+ s_worldData.surfaces[i].data = (void *) hunkgrid;
+ }
+}
+
+/*
+===============
+R_LoadSurfaces
+===============
+*/
+static void R_LoadSurfaces( lump_t *surfs, lump_t *verts, lump_t *indexLump ) {
+ dsurface_t *in;
+ msurface_t *out;
+ drawVert_t *dv;
+ int *indexes;
+ int count;
+ int numFaces, numMeshes, numTriSurfs, numFlares;
+ int i;
+
+ numFaces = 0;
+ numMeshes = 0;
+ numTriSurfs = 0;
+ numFlares = 0;
+
+ in = (void *)(fileBase + surfs->fileofs);
+ if (surfs->filelen % sizeof(*in))
+ ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",s_worldData.name);
+ count = surfs->filelen / sizeof(*in);
+
+ dv = (void *)(fileBase + verts->fileofs);
+ if (verts->filelen % sizeof(*dv))
+ ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",s_worldData.name);
+
+ indexes = (void *)(fileBase + indexLump->fileofs);
+ if ( indexLump->filelen % sizeof(*indexes))
+ ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",s_worldData.name);
+
+ out = ri.Hunk_Alloc ( count * sizeof(*out), h_low );
+
+ s_worldData.surfaces = out;
+ s_worldData.numsurfaces = count;
+
+ for ( i = 0 ; i < count ; i++, in++, out++ ) {
+ switch ( LittleLong( in->surfaceType ) ) {
+ case MST_PATCH:
+ ParseMesh ( in, dv, out );
+ numMeshes++;
+ break;
+ case MST_TRIANGLE_SOUP:
+ ParseTriSurf( in, dv, out, indexes );
+ numTriSurfs++;
+ break;
+ case MST_PLANAR:
+ ParseFace( in, dv, out, indexes );
+ numFaces++;
+ break;
+ case MST_FLARE:
+ ParseFlare( in, dv, out, indexes );
+ numFlares++;
+ break;
+ default:
+ ri.Error( ERR_DROP, "Bad surfaceType" );
+ }
+ }
+
+#ifdef PATCH_STITCHING
+ R_StitchAllPatches();
+#endif
+
+ R_FixSharedVertexLodError();
+
+#ifdef PATCH_STITCHING
+ R_MovePatchSurfacesToHunk();
+#endif
+
+ ri.Printf( PRINT_ALL, "...loaded %d faces, %i meshes, %i trisurfs, %i flares\n",
+ numFaces, numMeshes, numTriSurfs, numFlares );
+}
+
+
+
+/*
+=================
+R_LoadSubmodels
+=================
+*/
+static void R_LoadSubmodels( lump_t *l ) {
+ dmodel_t *in;
+ bmodel_t *out;
+ int i, j, count;
+
+ in = (void *)(fileBase + l->fileofs);
+ if (l->filelen % sizeof(*in))
+ ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",s_worldData.name);
+ count = l->filelen / sizeof(*in);
+
+ s_worldData.bmodels = out = ri.Hunk_Alloc( count * sizeof(*out), h_low );
+
+ for ( i=0 ; i<count ; i++, in++, out++ ) {
+ model_t *model;
+
+ model = R_AllocModel();
+
+ assert( model != NULL ); // this should never happen
+
+ model->type = MOD_BRUSH;
+ model->bmodel = out;
+ Com_sprintf( model->name, sizeof( model->name ), "*%d", i );
+
+ for (j=0 ; j<3 ; j++) {
+ out->bounds[0][j] = LittleFloat (in->mins[j]);
+ out->bounds[1][j] = LittleFloat (in->maxs[j]);
+ }
+
+ out->firstSurface = s_worldData.surfaces + LittleLong( in->firstSurface );
+ out->numSurfaces = LittleLong( in->numSurfaces );
+ }
+}
+
+
+
+//==================================================================
+
+/*
+=================
+R_SetParent
+=================
+*/
+static void R_SetParent (mnode_t *node, mnode_t *parent)
+{
+ node->parent = parent;
+ if (node->contents != -1)
+ return;
+ R_SetParent (node->children[0], node);
+ R_SetParent (node->children[1], node);
+}
+
+/*
+=================
+R_LoadNodesAndLeafs
+=================
+*/
+static void R_LoadNodesAndLeafs (lump_t *nodeLump, lump_t *leafLump) {
+ int i, j, p;
+ dnode_t *in;
+ dleaf_t *inLeaf;
+ mnode_t *out;
+ int numNodes, numLeafs;
+
+ in = (void *)(fileBase + nodeLump->fileofs);
+ if (nodeLump->filelen % sizeof(dnode_t) ||
+ leafLump->filelen % sizeof(dleaf_t) ) {
+ ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",s_worldData.name);
+ }
+ numNodes = nodeLump->filelen / sizeof(dnode_t);
+ numLeafs = leafLump->filelen / sizeof(dleaf_t);
+
+ out = ri.Hunk_Alloc ( (numNodes + numLeafs) * sizeof(*out), h_low);
+
+ s_worldData.nodes = out;
+ s_worldData.numnodes = numNodes + numLeafs;
+ s_worldData.numDecisionNodes = numNodes;
+
+ // load nodes
+ for ( i=0 ; i<numNodes; i++, in++, out++)
+ {
+ for (j=0 ; j<3 ; j++)
+ {
+ out->mins[j] = LittleLong (in->mins[j]);
+ out->maxs[j] = LittleLong (in->maxs[j]);
+ }
+
+ p = LittleLong(in->planeNum);
+ out->plane = s_worldData.planes + p;
+
+ out->contents = CONTENTS_NODE; // differentiate from leafs
+
+ for (j=0 ; j<2 ; j++)
+ {
+ p = LittleLong (in->children[j]);
+ if (p >= 0)
+ out->children[j] = s_worldData.nodes + p;
+ else
+ out->children[j] = s_worldData.nodes + numNodes + (-1 - p);
+ }
+ }
+
+ // load leafs
+ inLeaf = (void *)(fileBase + leafLump->fileofs);
+ for ( i=0 ; i<numLeafs ; i++, inLeaf++, out++)
+ {
+ for (j=0 ; j<3 ; j++)
+ {
+ out->mins[j] = LittleLong (inLeaf->mins[j]);
+ out->maxs[j] = LittleLong (inLeaf->maxs[j]);
+ }
+
+ out->cluster = LittleLong(inLeaf->cluster);
+ out->area = LittleLong(inLeaf->area);
+
+ if ( out->cluster >= s_worldData.numClusters ) {
+ s_worldData.numClusters = out->cluster + 1;
+ }
+
+ out->firstmarksurface = s_worldData.marksurfaces +
+ LittleLong(inLeaf->firstLeafSurface);
+ out->nummarksurfaces = LittleLong(inLeaf->numLeafSurfaces);
+ }
+
+ // chain decendants
+ R_SetParent (s_worldData.nodes, NULL);
+}
+
+//=============================================================================
+
+/*
+=================
+R_LoadShaders
+=================
+*/
+static void R_LoadShaders( lump_t *l ) {
+ int i, count;
+ dshader_t *in, *out;
+
+ in = (void *)(fileBase + l->fileofs);
+ if (l->filelen % sizeof(*in))
+ ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",s_worldData.name);
+ count = l->filelen / sizeof(*in);
+ out = ri.Hunk_Alloc ( count*sizeof(*out), h_low );
+
+ s_worldData.shaders = out;
+ s_worldData.numShaders = count;
+
+ Com_Memcpy( out, in, count*sizeof(*out) );
+
+ for ( i=0 ; i<count ; i++ ) {
+ out[i].surfaceFlags = LittleLong( out[i].surfaceFlags );
+ out[i].contentFlags = LittleLong( out[i].contentFlags );
+ }
+}
+
+
+/*
+=================
+R_LoadMarksurfaces
+=================
+*/
+static void R_LoadMarksurfaces (lump_t *l)
+{
+ int i, j, count;
+ int *in;
+ msurface_t **out;
+
+ in = (void *)(fileBase + l->fileofs);
+ if (l->filelen % sizeof(*in))
+ ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",s_worldData.name);
+ count = l->filelen / sizeof(*in);
+ out = ri.Hunk_Alloc ( count*sizeof(*out), h_low);
+
+ s_worldData.marksurfaces = out;
+ s_worldData.nummarksurfaces = count;
+
+ for ( i=0 ; i<count ; i++)
+ {
+ j = LittleLong(in[i]);
+ out[i] = s_worldData.surfaces + j;
+ }
+}
+
+
+/*
+=================
+R_LoadPlanes
+=================
+*/
+static void R_LoadPlanes( lump_t *l ) {
+ int i, j;
+ cplane_t *out;
+ dplane_t *in;
+ int count;
+ int bits;
+
+ in = (void *)(fileBase + l->fileofs);
+ if (l->filelen % sizeof(*in))
+ ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",s_worldData.name);
+ count = l->filelen / sizeof(*in);
+ out = ri.Hunk_Alloc ( count*2*sizeof(*out), h_low);
+
+ s_worldData.planes = out;
+ s_worldData.numplanes = count;
+
+ for ( i=0 ; i<count ; i++, in++, out++) {
+ bits = 0;
+ for (j=0 ; j<3 ; j++) {
+ out->normal[j] = LittleFloat (in->normal[j]);
+ if (out->normal[j] < 0) {
+ bits |= 1<<j;
+ }
+ }
+
+ out->dist = LittleFloat (in->dist);
+ out->type = PlaneTypeForNormal( out->normal );
+ out->signbits = bits;
+ }
+}
+
+/*
+=================
+R_LoadFogs
+
+=================
+*/
+static void R_LoadFogs( lump_t *l, lump_t *brushesLump, lump_t *sidesLump ) {
+ int i;
+ fog_t *out;
+ dfog_t *fogs;
+ dbrush_t *brushes, *brush;
+ dbrushside_t *sides;
+ int count, brushesCount, sidesCount;
+ int sideNum;
+ int planeNum;
+ shader_t *shader;
+ float d;
+ int firstSide;
+
+ fogs = (void *)(fileBase + l->fileofs);
+ if (l->filelen % sizeof(*fogs)) {
+ ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",s_worldData.name);
+ }
+ count = l->filelen / sizeof(*fogs);
+
+ // create fog strucutres for them
+ s_worldData.numfogs = count + 1;
+ s_worldData.fogs = ri.Hunk_Alloc ( s_worldData.numfogs*sizeof(*out), h_low);
+ out = s_worldData.fogs + 1;
+
+ if ( !count ) {
+ return;
+ }
+
+ brushes = (void *)(fileBase + brushesLump->fileofs);
+ if (brushesLump->filelen % sizeof(*brushes)) {
+ ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",s_worldData.name);
+ }
+ brushesCount = brushesLump->filelen / sizeof(*brushes);
+
+ sides = (void *)(fileBase + sidesLump->fileofs);
+ if (sidesLump->filelen % sizeof(*sides)) {
+ ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",s_worldData.name);
+ }
+ sidesCount = sidesLump->filelen / sizeof(*sides);
+
+ for ( i=0 ; i<count ; i++, fogs++) {
+ out->originalBrushNumber = LittleLong( fogs->brushNum );
+
+ if ( (unsigned)out->originalBrushNumber >= brushesCount ) {
+ ri.Error( ERR_DROP, "fog brushNumber out of range" );
+ }
+ brush = brushes + out->originalBrushNumber;
+
+ firstSide = LittleLong( brush->firstSide );
+
+ if ( (unsigned)firstSide > sidesCount - 6 ) {
+ ri.Error( ERR_DROP, "fog brush sideNumber out of range" );
+ }
+
+ // brushes are always sorted with the axial sides first
+ sideNum = firstSide + 0;
+ planeNum = LittleLong( sides[ sideNum ].planeNum );
+ out->bounds[0][0] = -s_worldData.planes[ planeNum ].dist;
+
+ sideNum = firstSide + 1;
+ planeNum = LittleLong( sides[ sideNum ].planeNum );
+ out->bounds[1][0] = s_worldData.planes[ planeNum ].dist;
+
+ sideNum = firstSide + 2;
+ planeNum = LittleLong( sides[ sideNum ].planeNum );
+ out->bounds[0][1] = -s_worldData.planes[ planeNum ].dist;
+
+ sideNum = firstSide + 3;
+ planeNum = LittleLong( sides[ sideNum ].planeNum );
+ out->bounds[1][1] = s_worldData.planes[ planeNum ].dist;
+
+ sideNum = firstSide + 4;
+ planeNum = LittleLong( sides[ sideNum ].planeNum );
+ out->bounds[0][2] = -s_worldData.planes[ planeNum ].dist;
+
+ sideNum = firstSide + 5;
+ planeNum = LittleLong( sides[ sideNum ].planeNum );
+ out->bounds[1][2] = s_worldData.planes[ planeNum ].dist;
+
+ // get information from the shader for fog parameters
+ shader = R_FindShader( fogs->shader, LIGHTMAP_NONE, qtrue );
+
+ out->parms = shader->fogParms;
+
+ out->colorInt = ColorBytes4 ( shader->fogParms.color[0] * tr.identityLight,
+ shader->fogParms.color[1] * tr.identityLight,
+ shader->fogParms.color[2] * tr.identityLight, 1.0 );
+
+ d = shader->fogParms.depthForOpaque < 1 ? 1 : shader->fogParms.depthForOpaque;
+ out->tcScale = 1.0f / ( d * 8 );
+
+ // set the gradient vector
+ sideNum = LittleLong( fogs->visibleSide );
+
+ if ( sideNum == -1 ) {
+ out->hasSurface = qfalse;
+ } else {
+ out->hasSurface = qtrue;
+ planeNum = LittleLong( sides[ firstSide + sideNum ].planeNum );
+ VectorSubtract( vec3_origin, s_worldData.planes[ planeNum ].normal, out->surface );
+ out->surface[3] = -s_worldData.planes[ planeNum ].dist;
+ }
+
+ out++;
+ }
+
+}
+
+
+/*
+================
+R_LoadLightGrid
+
+================
+*/
+void R_LoadLightGrid( lump_t *l ) {
+ int i;
+ vec3_t maxs;
+ int numGridPoints;
+ world_t *w;
+ float *wMins, *wMaxs;
+
+ w = &s_worldData;
+
+ w->lightGridInverseSize[0] = 1.0f / w->lightGridSize[0];
+ w->lightGridInverseSize[1] = 1.0f / w->lightGridSize[1];
+ w->lightGridInverseSize[2] = 1.0f / w->lightGridSize[2];
+
+ wMins = w->bmodels[0].bounds[0];
+ wMaxs = w->bmodels[0].bounds[1];
+
+ for ( i = 0 ; i < 3 ; i++ ) {
+ w->lightGridOrigin[i] = w->lightGridSize[i] * ceil( wMins[i] / w->lightGridSize[i] );
+ maxs[i] = w->lightGridSize[i] * floor( wMaxs[i] / w->lightGridSize[i] );
+ w->lightGridBounds[i] = (maxs[i] - w->lightGridOrigin[i])/w->lightGridSize[i] + 1;
+ }
+
+ numGridPoints = w->lightGridBounds[0] * w->lightGridBounds[1] * w->lightGridBounds[2];
+
+ if ( l->filelen != numGridPoints * 8 ) {
+ ri.Printf( PRINT_WARNING, "WARNING: light grid mismatch\n" );
+ w->lightGridData = NULL;
+ return;
+ }
+
+ w->lightGridData = ri.Hunk_Alloc( l->filelen, h_low );
+ Com_Memcpy( w->lightGridData, (void *)(fileBase + l->fileofs), l->filelen );
+
+ // deal with overbright bits
+ for ( i = 0 ; i < numGridPoints ; i++ ) {
+ R_ColorShiftLightingBytes( &w->lightGridData[i*8], &w->lightGridData[i*8] );
+ R_ColorShiftLightingBytes( &w->lightGridData[i*8+3], &w->lightGridData[i*8+3] );
+ }
+}
+
+/*
+================
+R_LoadEntities
+================
+*/
+void R_LoadEntities( lump_t *l ) {
+ char *p, *token, *s;
+ char keyname[MAX_TOKEN_CHARS];
+ char value[MAX_TOKEN_CHARS];
+ world_t *w;
+
+ w = &s_worldData;
+ w->lightGridSize[0] = 64;
+ w->lightGridSize[1] = 64;
+ w->lightGridSize[2] = 128;
+
+ p = (char *)(fileBase + l->fileofs);
+
+ // store for reference by the cgame
+ w->entityString = ri.Hunk_Alloc( l->filelen + 1, h_low );
+ strcpy( w->entityString, p );
+ w->entityParsePoint = w->entityString;
+
+ token = COM_ParseExt( &p, qtrue );
+ if (!*token || *token != '{') {
+ return;
+ }
+
+ // only parse the world spawn
+ while ( 1 ) {
+ // parse key
+ token = COM_ParseExt( &p, qtrue );
+
+ if ( !*token || *token == '}' ) {
+ break;
+ }
+ Q_strncpyz(keyname, token, sizeof(keyname));
+
+ // parse value
+ token = COM_ParseExt( &p, qtrue );
+
+ if ( !*token || *token == '}' ) {
+ break;
+ }
+ Q_strncpyz(value, token, sizeof(value));
+
+ // check for remapping of shaders for vertex lighting
+ s = "vertexremapshader";
+ if (!Q_strncmp(keyname, s, strlen(s)) ) {
+ s = strchr(value, ';');
+ if (!s) {
+ ri.Printf( PRINT_WARNING, "WARNING: no semi colon in vertexshaderremap '%s'\n", value );
+ break;
+ }
+ *s++ = 0;
+ if (r_vertexLight->integer) {
+ R_RemapShader(value, s, "0");
+ }
+ continue;
+ }
+ // check for remapping of shaders
+ s = "remapshader";
+ if (!Q_strncmp(keyname, s, strlen(s)) ) {
+ s = strchr(value, ';');
+ if (!s) {
+ ri.Printf( PRINT_WARNING, "WARNING: no semi colon in shaderremap '%s'\n", value );
+ break;
+ }
+ *s++ = 0;
+ R_RemapShader(value, s, "0");
+ continue;
+ }
+ // check for a different grid size
+ if (!Q_stricmp(keyname, "gridsize")) {
+ sscanf(value, "%f %f %f", &w->lightGridSize[0], &w->lightGridSize[1], &w->lightGridSize[2] );
+ continue;
+ }
+ }
+}
+
+/*
+=================
+R_GetEntityToken
+=================
+*/
+qboolean R_GetEntityToken( char *buffer, int size ) {
+ const char *s;
+
+ s = COM_Parse( &s_worldData.entityParsePoint );
+ Q_strncpyz( buffer, s, size );
+ if ( !s_worldData.entityParsePoint || !s[0] ) {
+ s_worldData.entityParsePoint = s_worldData.entityString;
+ return qfalse;
+ } else {
+ return qtrue;
+ }
+}
+
+/*
+=================
+RE_LoadWorldMap
+
+Called directly from cgame
+=================
+*/
+void RE_LoadWorldMap( const char *name ) {
+ int i;
+ dheader_t *header;
+ byte *buffer;
+ byte *startMarker;
+
+ if ( tr.worldMapLoaded ) {
+ ri.Error( ERR_DROP, "ERROR: attempted to redundantly load world map\n" );
+ }
+
+ // set default sun direction to be used if it isn't
+ // overridden by a shader
+ tr.sunDirection[0] = 0.45f;
+ tr.sunDirection[1] = 0.3f;
+ tr.sunDirection[2] = 0.9f;
+
+ VectorNormalize( tr.sunDirection );
+
+ tr.worldMapLoaded = qtrue;
+
+ // load it
+ ri.FS_ReadFile( name, (void **)&buffer );
+ if ( !buffer ) {
+ ri.Error (ERR_DROP, "RE_LoadWorldMap: %s not found", name);
+ }
+
+ // clear tr.world so if the level fails to load, the next
+ // try will not look at the partially loaded version
+ tr.world = NULL;
+
+ Com_Memset( &s_worldData, 0, sizeof( s_worldData ) );
+ Q_strncpyz( s_worldData.name, name, sizeof( s_worldData.name ) );
+
+ Q_strncpyz( s_worldData.baseName, COM_SkipPath( s_worldData.name ), sizeof( s_worldData.name ) );
+ COM_StripExtension( s_worldData.baseName, s_worldData.baseName );
+
+ startMarker = ri.Hunk_Alloc(0, h_low);
+ c_gridVerts = 0;
+
+ header = (dheader_t *)buffer;
+ fileBase = (byte *)header;
+
+ i = LittleLong (header->version);
+ if ( i != BSP_VERSION ) {
+ ri.Error (ERR_DROP, "RE_LoadWorldMap: %s has wrong version number (%i should be %i)",
+ name, i, BSP_VERSION);
+ }
+
+ // swap all the lumps
+ for (i=0 ; i<sizeof(dheader_t)/4 ; i++) {
+ ((int *)header)[i] = LittleLong ( ((int *)header)[i]);
+ }
+
+ // load into heap
+ R_LoadShaders( &header->lumps[LUMP_SHADERS] );
+ R_LoadLightmaps( &header->lumps[LUMP_LIGHTMAPS] );
+ R_LoadPlanes (&header->lumps[LUMP_PLANES]);
+ R_LoadFogs( &header->lumps[LUMP_FOGS], &header->lumps[LUMP_BRUSHES], &header->lumps[LUMP_BRUSHSIDES] );
+ R_LoadSurfaces( &header->lumps[LUMP_SURFACES], &header->lumps[LUMP_DRAWVERTS], &header->lumps[LUMP_DRAWINDEXES] );
+ R_LoadMarksurfaces (&header->lumps[LUMP_LEAFSURFACES]);
+ R_LoadNodesAndLeafs (&header->lumps[LUMP_NODES], &header->lumps[LUMP_LEAFS]);
+ R_LoadSubmodels (&header->lumps[LUMP_MODELS]);
+ R_LoadVisibility( &header->lumps[LUMP_VISIBILITY] );
+ R_LoadEntities( &header->lumps[LUMP_ENTITIES] );
+ R_LoadLightGrid( &header->lumps[LUMP_LIGHTGRID] );
+
+ s_worldData.dataSize = (byte *)ri.Hunk_Alloc(0, h_low) - startMarker;
+
+ // only set tr.world now that we know the entire level has loaded properly
+ tr.world = &s_worldData;
+
+ ri.FS_FreeFile( buffer );
+}
+
diff --git a/code/renderer/tr_cmds.c b/code/renderer/tr_cmds.c
new file mode 100755
index 0000000..3808dc3
--- /dev/null
+++ b/code/renderer/tr_cmds.c
@@ -0,0 +1,447 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "tr_local.h"
+
+volatile renderCommandList_t *renderCommandList;
+
+volatile qboolean renderThreadActive;
+
+
+/*
+=====================
+R_PerformanceCounters
+=====================
+*/
+void R_PerformanceCounters( void ) {
+ if ( !r_speeds->integer ) {
+ // clear the counters even if we aren't printing
+ Com_Memset( &tr.pc, 0, sizeof( tr.pc ) );
+ Com_Memset( &backEnd.pc, 0, sizeof( backEnd.pc ) );
+ return;
+ }
+
+ if (r_speeds->integer == 1) {
+ ri.Printf (PRINT_ALL, "%i/%i shaders/surfs %i leafs %i verts %i/%i tris %.2f mtex %.2f dc\n",
+ backEnd.pc.c_shaders, backEnd.pc.c_surfaces, tr.pc.c_leafs, backEnd.pc.c_vertexes,
+ backEnd.pc.c_indexes/3, backEnd.pc.c_totalIndexes/3,
+ R_SumOfUsedImages()/(1000000.0f), backEnd.pc.c_overDraw / (float)(glConfig.vidWidth * glConfig.vidHeight) );
+ } else if (r_speeds->integer == 2) {
+ ri.Printf (PRINT_ALL, "(patch) %i sin %i sclip %i sout %i bin %i bclip %i bout\n",
+ tr.pc.c_sphere_cull_patch_in, tr.pc.c_sphere_cull_patch_clip, tr.pc.c_sphere_cull_patch_out,
+ tr.pc.c_box_cull_patch_in, tr.pc.c_box_cull_patch_clip, tr.pc.c_box_cull_patch_out );
+ ri.Printf (PRINT_ALL, "(md3) %i sin %i sclip %i sout %i bin %i bclip %i bout\n",
+ tr.pc.c_sphere_cull_md3_in, tr.pc.c_sphere_cull_md3_clip, tr.pc.c_sphere_cull_md3_out,
+ tr.pc.c_box_cull_md3_in, tr.pc.c_box_cull_md3_clip, tr.pc.c_box_cull_md3_out );
+ } else if (r_speeds->integer == 3) {
+ ri.Printf (PRINT_ALL, "viewcluster: %i\n", tr.viewCluster );
+ } else if (r_speeds->integer == 4) {
+ if ( backEnd.pc.c_dlightVertexes ) {
+ ri.Printf (PRINT_ALL, "dlight srf:%i culled:%i verts:%i tris:%i\n",
+ tr.pc.c_dlightSurfaces, tr.pc.c_dlightSurfacesCulled,
+ backEnd.pc.c_dlightVertexes, backEnd.pc.c_dlightIndexes / 3 );
+ }
+ }
+ else if (r_speeds->integer == 5 )
+ {
+ ri.Printf( PRINT_ALL, "zFar: %.0f\n", tr.viewParms.zFar );
+ }
+ else if (r_speeds->integer == 6 )
+ {
+ ri.Printf( PRINT_ALL, "flare adds:%i tests:%i renders:%i\n",
+ backEnd.pc.c_flareAdds, backEnd.pc.c_flareTests, backEnd.pc.c_flareRenders );
+ }
+
+ Com_Memset( &tr.pc, 0, sizeof( tr.pc ) );
+ Com_Memset( &backEnd.pc, 0, sizeof( backEnd.pc ) );
+}
+
+
+/*
+====================
+R_InitCommandBuffers
+====================
+*/
+void R_InitCommandBuffers( void ) {
+ glConfig.smpActive = qfalse;
+ if ( r_smp->integer ) {
+ ri.Printf( PRINT_ALL, "Trying SMP acceleration...\n" );
+ if ( GLimp_SpawnRenderThread( RB_RenderThread ) ) {
+ ri.Printf( PRINT_ALL, "...succeeded.\n" );
+ glConfig.smpActive = qtrue;
+ } else {
+ ri.Printf( PRINT_ALL, "...failed.\n" );
+ }
+ }
+}
+
+/*
+====================
+R_ShutdownCommandBuffers
+====================
+*/
+void R_ShutdownCommandBuffers( void ) {
+ // kill the rendering thread
+ if ( glConfig.smpActive ) {
+ GLimp_WakeRenderer( NULL );
+ glConfig.smpActive = qfalse;
+ }
+}
+
+/*
+====================
+R_IssueRenderCommands
+====================
+*/
+int c_blockedOnRender;
+int c_blockedOnMain;
+
+void R_IssueRenderCommands( qboolean runPerformanceCounters ) {
+ renderCommandList_t *cmdList;
+
+ cmdList = &backEndData[tr.smpFrame]->commands;
+ assert(cmdList); // bk001205
+ // add an end-of-list command
+ *(int *)(cmdList->cmds + cmdList->used) = RC_END_OF_LIST;
+
+ // clear it out, in case this is a sync and not a buffer flip
+ cmdList->used = 0;
+
+ if ( glConfig.smpActive ) {
+ // if the render thread is not idle, wait for it
+ if ( renderThreadActive ) {
+ c_blockedOnRender++;
+ if ( r_showSmp->integer ) {
+ ri.Printf( PRINT_ALL, "R" );
+ }
+ } else {
+ c_blockedOnMain++;
+ if ( r_showSmp->integer ) {
+ ri.Printf( PRINT_ALL, "." );
+ }
+ }
+
+ // sleep until the renderer has completed
+ GLimp_FrontEndSleep();
+ }
+
+ // at this point, the back end thread is idle, so it is ok
+ // to look at it's performance counters
+ if ( runPerformanceCounters ) {
+ R_PerformanceCounters();
+ }
+
+ // actually start the commands going
+ if ( !r_skipBackEnd->integer ) {
+ // let it start on the new batch
+ if ( !glConfig.smpActive ) {
+ RB_ExecuteRenderCommands( cmdList->cmds );
+ } else {
+ GLimp_WakeRenderer( cmdList );
+ }
+ }
+}
+
+
+/*
+====================
+R_SyncRenderThread
+
+Issue any pending commands and wait for them to complete.
+After exiting, the render thread will have completed its work
+and will remain idle and the main thread is free to issue
+OpenGL calls until R_IssueRenderCommands is called.
+====================
+*/
+void R_SyncRenderThread( void ) {
+ if ( !tr.registered ) {
+ return;
+ }
+ R_IssueRenderCommands( qfalse );
+
+ if ( !glConfig.smpActive ) {
+ return;
+ }
+ GLimp_FrontEndSleep();
+}
+
+/*
+============
+R_GetCommandBuffer
+
+make sure there is enough command space, waiting on the
+render thread if needed.
+============
+*/
+void *R_GetCommandBuffer( int bytes ) {
+ renderCommandList_t *cmdList;
+
+ cmdList = &backEndData[tr.smpFrame]->commands;
+
+ // always leave room for the end of list command
+ if ( cmdList->used + bytes + 4 > MAX_RENDER_COMMANDS ) {
+ if ( bytes > MAX_RENDER_COMMANDS - 4 ) {
+ ri.Error( ERR_FATAL, "R_GetCommandBuffer: bad size %i", bytes );
+ }
+ // if we run out of room, just start dropping commands
+ return NULL;
+ }
+
+ cmdList->used += bytes;
+
+ return cmdList->cmds + cmdList->used - bytes;
+}
+
+
+/*
+=============
+R_AddDrawSurfCmd
+
+=============
+*/
+void R_AddDrawSurfCmd( drawSurf_t *drawSurfs, int numDrawSurfs ) {
+ drawSurfsCommand_t *cmd;
+
+ cmd = R_GetCommandBuffer( sizeof( *cmd ) );
+ if ( !cmd ) {
+ return;
+ }
+ cmd->commandId = RC_DRAW_SURFS;
+
+ cmd->drawSurfs = drawSurfs;
+ cmd->numDrawSurfs = numDrawSurfs;
+
+ cmd->refdef = tr.refdef;
+ cmd->viewParms = tr.viewParms;
+}
+
+
+/*
+=============
+RE_SetColor
+
+Passing NULL will set the color to white
+=============
+*/
+void RE_SetColor( const float *rgba ) {
+ setColorCommand_t *cmd;
+
+ if ( !tr.registered ) {
+ return;
+ }
+ cmd = R_GetCommandBuffer( sizeof( *cmd ) );
+ if ( !cmd ) {
+ return;
+ }
+ cmd->commandId = RC_SET_COLOR;
+ if ( !rgba ) {
+ static float colorWhite[4] = { 1, 1, 1, 1 };
+
+ rgba = colorWhite;
+ }
+
+ cmd->color[0] = rgba[0];
+ cmd->color[1] = rgba[1];
+ cmd->color[2] = rgba[2];
+ cmd->color[3] = rgba[3];
+}
+
+
+/*
+=============
+RE_StretchPic
+=============
+*/
+void RE_StretchPic ( float x, float y, float w, float h,
+ float s1, float t1, float s2, float t2, qhandle_t hShader ) {
+ stretchPicCommand_t *cmd;
+
+ if (!tr.registered) {
+ return;
+ }
+ cmd = R_GetCommandBuffer( sizeof( *cmd ) );
+ if ( !cmd ) {
+ return;
+ }
+ cmd->commandId = RC_STRETCH_PIC;
+ cmd->shader = R_GetShaderByHandle( hShader );
+ cmd->x = x;
+ cmd->y = y;
+ cmd->w = w;
+ cmd->h = h;
+ cmd->s1 = s1;
+ cmd->t1 = t1;
+ cmd->s2 = s2;
+ cmd->t2 = t2;
+}
+
+
+/*
+====================
+RE_BeginFrame
+
+If running in stereo, RE_BeginFrame will be called twice
+for each RE_EndFrame
+====================
+*/
+void RE_BeginFrame( stereoFrame_t stereoFrame ) {
+ drawBufferCommand_t *cmd;
+
+ if ( !tr.registered ) {
+ return;
+ }
+ glState.finishCalled = qfalse;
+
+ tr.frameCount++;
+ tr.frameSceneNum = 0;
+
+ //
+ // do overdraw measurement
+ //
+ if ( r_measureOverdraw->integer )
+ {
+ if ( glConfig.stencilBits < 4 )
+ {
+ ri.Printf( PRINT_ALL, "Warning: not enough stencil bits to measure overdraw: %d\n", glConfig.stencilBits );
+ ri.Cvar_Set( "r_measureOverdraw", "0" );
+ r_measureOverdraw->modified = qfalse;
+ }
+ else if ( r_shadows->integer == 2 )
+ {
+ ri.Printf( PRINT_ALL, "Warning: stencil shadows and overdraw measurement are mutually exclusive\n" );
+ ri.Cvar_Set( "r_measureOverdraw", "0" );
+ r_measureOverdraw->modified = qfalse;
+ }
+ else
+ {
+ R_SyncRenderThread();
+ qglEnable( GL_STENCIL_TEST );
+ qglStencilMask( ~0U );
+ qglClearStencil( 0U );
+ qglStencilFunc( GL_ALWAYS, 0U, ~0U );
+ qglStencilOp( GL_KEEP, GL_INCR, GL_INCR );
+ }
+ r_measureOverdraw->modified = qfalse;
+ }
+ else
+ {
+ // this is only reached if it was on and is now off
+ if ( r_measureOverdraw->modified ) {
+ R_SyncRenderThread();
+ qglDisable( GL_STENCIL_TEST );
+ }
+ r_measureOverdraw->modified = qfalse;
+ }
+
+ //
+ // texturemode stuff
+ //
+ if ( r_textureMode->modified ) {
+ R_SyncRenderThread();
+ GL_TextureMode( r_textureMode->string );
+ r_textureMode->modified = qfalse;
+ }
+
+ //
+ // gamma stuff
+ //
+ if ( r_gamma->modified ) {
+ r_gamma->modified = qfalse;
+
+ R_SyncRenderThread();
+ R_SetColorMappings();
+ }
+
+ // check for errors
+ if ( !r_ignoreGLErrors->integer ) {
+ int err;
+
+ R_SyncRenderThread();
+ if ( ( err = qglGetError() ) != GL_NO_ERROR ) {
+ ri.Error( ERR_FATAL, "RE_BeginFrame() - glGetError() failed (0x%x)!\n", err );
+ }
+ }
+
+ //
+ // draw buffer stuff
+ //
+ cmd = R_GetCommandBuffer( sizeof( *cmd ) );
+ if ( !cmd ) {
+ return;
+ }
+ cmd->commandId = RC_DRAW_BUFFER;
+
+ if ( glConfig.stereoEnabled ) {
+ if ( stereoFrame == STEREO_LEFT ) {
+ cmd->buffer = (int)GL_BACK_LEFT;
+ } else if ( stereoFrame == STEREO_RIGHT ) {
+ cmd->buffer = (int)GL_BACK_RIGHT;
+ } else {
+ ri.Error( ERR_FATAL, "RE_BeginFrame: Stereo is enabled, but stereoFrame was %i", stereoFrame );
+ }
+ } else {
+ if ( stereoFrame != STEREO_CENTER ) {
+ ri.Error( ERR_FATAL, "RE_BeginFrame: Stereo is disabled, but stereoFrame was %i", stereoFrame );
+ }
+ if ( !Q_stricmp( r_drawBuffer->string, "GL_FRONT" ) ) {
+ cmd->buffer = (int)GL_FRONT;
+ } else {
+ cmd->buffer = (int)GL_BACK;
+ }
+ }
+}
+
+
+/*
+=============
+RE_EndFrame
+
+Returns the number of msec spent in the back end
+=============
+*/
+void RE_EndFrame( int *frontEndMsec, int *backEndMsec ) {
+ swapBuffersCommand_t *cmd;
+
+ if ( !tr.registered ) {
+ return;
+ }
+ cmd = R_GetCommandBuffer( sizeof( *cmd ) );
+ if ( !cmd ) {
+ return;
+ }
+ cmd->commandId = RC_SWAP_BUFFERS;
+
+ R_IssueRenderCommands( qtrue );
+
+ // use the other buffers next frame, because another CPU
+ // may still be rendering into the current ones
+ R_ToggleSmpFrame();
+
+ if ( frontEndMsec ) {
+ *frontEndMsec = tr.frontEndMsec;
+ }
+ tr.frontEndMsec = 0;
+ if ( backEndMsec ) {
+ *backEndMsec = backEnd.pc.msec;
+ }
+ backEnd.pc.msec = 0;
+}
+
diff --git a/code/renderer/tr_curve.c b/code/renderer/tr_curve.c
new file mode 100755
index 0000000..91a9e62
--- /dev/null
+++ b/code/renderer/tr_curve.c
@@ -0,0 +1,624 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "tr_local.h"
+
+/*
+
+This file does all of the processing necessary to turn a raw grid of points
+read from the map file into a srfGridMesh_t ready for rendering.
+
+The level of detail solution is direction independent, based only on subdivided
+distance from the true curve.
+
+Only a single entry point:
+
+srfGridMesh_t *R_SubdividePatchToGrid( int width, int height,
+ drawVert_t points[MAX_PATCH_SIZE*MAX_PATCH_SIZE] ) {
+
+*/
+
+
+/*
+============
+LerpDrawVert
+============
+*/
+static void LerpDrawVert( drawVert_t *a, drawVert_t *b, drawVert_t *out ) {
+ out->xyz[0] = 0.5f * (a->xyz[0] + b->xyz[0]);
+ out->xyz[1] = 0.5f * (a->xyz[1] + b->xyz[1]);
+ out->xyz[2] = 0.5f * (a->xyz[2] + b->xyz[2]);
+
+ out->st[0] = 0.5f * (a->st[0] + b->st[0]);
+ out->st[1] = 0.5f * (a->st[1] + b->st[1]);
+
+ out->lightmap[0] = 0.5f * (a->lightmap[0] + b->lightmap[0]);
+ out->lightmap[1] = 0.5f * (a->lightmap[1] + b->lightmap[1]);
+
+ out->color[0] = (a->color[0] + b->color[0]) >> 1;
+ out->color[1] = (a->color[1] + b->color[1]) >> 1;
+ out->color[2] = (a->color[2] + b->color[2]) >> 1;
+ out->color[3] = (a->color[3] + b->color[3]) >> 1;
+}
+
+/*
+============
+Transpose
+============
+*/
+static void Transpose( int width, int height, drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE] ) {
+ int i, j;
+ drawVert_t temp;
+
+ if ( width > height ) {
+ for ( i = 0 ; i < height ; i++ ) {
+ for ( j = i + 1 ; j < width ; j++ ) {
+ if ( j < height ) {
+ // swap the value
+ temp = ctrl[j][i];
+ ctrl[j][i] = ctrl[i][j];
+ ctrl[i][j] = temp;
+ } else {
+ // just copy
+ ctrl[j][i] = ctrl[i][j];
+ }
+ }
+ }
+ } else {
+ for ( i = 0 ; i < width ; i++ ) {
+ for ( j = i + 1 ; j < height ; j++ ) {
+ if ( j < width ) {
+ // swap the value
+ temp = ctrl[i][j];
+ ctrl[i][j] = ctrl[j][i];
+ ctrl[j][i] = temp;
+ } else {
+ // just copy
+ ctrl[i][j] = ctrl[j][i];
+ }
+ }
+ }
+ }
+
+}
+
+
+/*
+=================
+MakeMeshNormals
+
+Handles all the complicated wrapping and degenerate cases
+=================
+*/
+static void MakeMeshNormals( int width, int height, drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE] ) {
+ int i, j, k, dist;
+ vec3_t normal;
+ vec3_t sum;
+ int count;
+ vec3_t base;
+ vec3_t delta;
+ int x, y;
+ drawVert_t *dv;
+ vec3_t around[8], temp;
+ qboolean good[8];
+ qboolean wrapWidth, wrapHeight;
+ float len;
+static int neighbors[8][2] = {
+ {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1}, {-1,-1}, {-1,0}, {-1,1}
+ };
+
+ wrapWidth = qfalse;
+ for ( i = 0 ; i < height ; i++ ) {
+ VectorSubtract( ctrl[i][0].xyz, ctrl[i][width-1].xyz, delta );
+ len = VectorLengthSquared( delta );
+ if ( len > 1.0 ) {
+ break;
+ }
+ }
+ if ( i == height ) {
+ wrapWidth = qtrue;
+ }
+
+ wrapHeight = qfalse;
+ for ( i = 0 ; i < width ; i++ ) {
+ VectorSubtract( ctrl[0][i].xyz, ctrl[height-1][i].xyz, delta );
+ len = VectorLengthSquared( delta );
+ if ( len > 1.0 ) {
+ break;
+ }
+ }
+ if ( i == width) {
+ wrapHeight = qtrue;
+ }
+
+
+ for ( i = 0 ; i < width ; i++ ) {
+ for ( j = 0 ; j < height ; j++ ) {
+ count = 0;
+ dv = &ctrl[j][i];
+ VectorCopy( dv->xyz, base );
+ for ( k = 0 ; k < 8 ; k++ ) {
+ VectorClear( around[k] );
+ good[k] = qfalse;
+
+ for ( dist = 1 ; dist <= 3 ; dist++ ) {
+ x = i + neighbors[k][0] * dist;
+ y = j + neighbors[k][1] * dist;
+ if ( wrapWidth ) {
+ if ( x < 0 ) {
+ x = width - 1 + x;
+ } else if ( x >= width ) {
+ x = 1 + x - width;
+ }
+ }
+ if ( wrapHeight ) {
+ if ( y < 0 ) {
+ y = height - 1 + y;
+ } else if ( y >= height ) {
+ y = 1 + y - height;
+ }
+ }
+
+ if ( x < 0 || x >= width || y < 0 || y >= height ) {
+ break; // edge of patch
+ }
+ VectorSubtract( ctrl[y][x].xyz, base, temp );
+ if ( VectorNormalize2( temp, temp ) == 0 ) {
+ continue; // degenerate edge, get more dist
+ } else {
+ good[k] = qtrue;
+ VectorCopy( temp, around[k] );
+ break; // good edge
+ }
+ }
+ }
+
+ VectorClear( sum );
+ for ( k = 0 ; k < 8 ; k++ ) {
+ if ( !good[k] || !good[(k+1)&7] ) {
+ continue; // didn't get two points
+ }
+ CrossProduct( around[(k+1)&7], around[k], normal );
+ if ( VectorNormalize2( normal, normal ) == 0 ) {
+ continue;
+ }
+ VectorAdd( normal, sum, sum );
+ count++;
+ }
+ if ( count == 0 ) {
+//printf("bad normal\n");
+ count = 1;
+ }
+ VectorNormalize2( sum, dv->normal );
+ }
+ }
+}
+
+
+/*
+============
+InvertCtrl
+============
+*/
+static void InvertCtrl( int width, int height, drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE] ) {
+ int i, j;
+ drawVert_t temp;
+
+ for ( i = 0 ; i < height ; i++ ) {
+ for ( j = 0 ; j < width/2 ; j++ ) {
+ temp = ctrl[i][j];
+ ctrl[i][j] = ctrl[i][width-1-j];
+ ctrl[i][width-1-j] = temp;
+ }
+ }
+}
+
+
+/*
+=================
+InvertErrorTable
+=================
+*/
+static void InvertErrorTable( float errorTable[2][MAX_GRID_SIZE], int width, int height ) {
+ int i;
+ float copy[2][MAX_GRID_SIZE];
+
+ Com_Memcpy( copy, errorTable, sizeof( copy ) );
+
+ for ( i = 0 ; i < width ; i++ ) {
+ errorTable[1][i] = copy[0][i]; //[width-1-i];
+ }
+
+ for ( i = 0 ; i < height ; i++ ) {
+ errorTable[0][i] = copy[1][height-1-i];
+ }
+
+}
+
+/*
+==================
+PutPointsOnCurve
+==================
+*/
+static void PutPointsOnCurve( drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE],
+ int width, int height ) {
+ int i, j;
+ drawVert_t prev, next;
+
+ for ( i = 0 ; i < width ; i++ ) {
+ for ( j = 1 ; j < height ; j += 2 ) {
+ LerpDrawVert( &ctrl[j][i], &ctrl[j+1][i], &prev );
+ LerpDrawVert( &ctrl[j][i], &ctrl[j-1][i], &next );
+ LerpDrawVert( &prev, &next, &ctrl[j][i] );
+ }
+ }
+
+
+ for ( j = 0 ; j < height ; j++ ) {
+ for ( i = 1 ; i < width ; i += 2 ) {
+ LerpDrawVert( &ctrl[j][i], &ctrl[j][i+1], &prev );
+ LerpDrawVert( &ctrl[j][i], &ctrl[j][i-1], &next );
+ LerpDrawVert( &prev, &next, &ctrl[j][i] );
+ }
+ }
+}
+
+/*
+=================
+R_CreateSurfaceGridMesh
+=================
+*/
+srfGridMesh_t *R_CreateSurfaceGridMesh(int width, int height,
+ drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE], float errorTable[2][MAX_GRID_SIZE] ) {
+ int i, j, size;
+ drawVert_t *vert;
+ vec3_t tmpVec;
+ srfGridMesh_t *grid;
+
+ // copy the results out to a grid
+ size = (width * height - 1) * sizeof( drawVert_t ) + sizeof( *grid );
+
+#ifdef PATCH_STITCHING
+ grid = /*ri.Hunk_Alloc*/ ri.Malloc( size );
+ Com_Memset(grid, 0, size);
+
+ grid->widthLodError = /*ri.Hunk_Alloc*/ ri.Malloc( width * 4 );
+ Com_Memcpy( grid->widthLodError, errorTable[0], width * 4 );
+
+ grid->heightLodError = /*ri.Hunk_Alloc*/ ri.Malloc( height * 4 );
+ Com_Memcpy( grid->heightLodError, errorTable[1], height * 4 );
+#else
+ grid = ri.Hunk_Alloc( size );
+ Com_Memset(grid, 0, size);
+
+ grid->widthLodError = ri.Hunk_Alloc( width * 4 );
+ Com_Memcpy( grid->widthLodError, errorTable[0], width * 4 );
+
+ grid->heightLodError = ri.Hunk_Alloc( height * 4 );
+ Com_Memcpy( grid->heightLodError, errorTable[1], height * 4 );
+#endif
+
+ grid->width = width;
+ grid->height = height;
+ grid->surfaceType = SF_GRID;
+ ClearBounds( grid->meshBounds[0], grid->meshBounds[1] );
+ for ( i = 0 ; i < width ; i++ ) {
+ for ( j = 0 ; j < height ; j++ ) {
+ vert = &grid->verts[j*width+i];
+ *vert = ctrl[j][i];
+ AddPointToBounds( vert->xyz, grid->meshBounds[0], grid->meshBounds[1] );
+ }
+ }
+
+ // compute local origin and bounds
+ VectorAdd( grid->meshBounds[0], grid->meshBounds[1], grid->localOrigin );
+ VectorScale( grid->localOrigin, 0.5f, grid->localOrigin );
+ VectorSubtract( grid->meshBounds[0], grid->localOrigin, tmpVec );
+ grid->meshRadius = VectorLength( tmpVec );
+
+ VectorCopy( grid->localOrigin, grid->lodOrigin );
+ grid->lodRadius = grid->meshRadius;
+ //
+ return grid;
+}
+
+/*
+=================
+R_FreeSurfaceGridMesh
+=================
+*/
+void R_FreeSurfaceGridMesh( srfGridMesh_t *grid ) {
+ ri.Free(grid->widthLodError);
+ ri.Free(grid->heightLodError);
+ ri.Free(grid);
+}
+
+/*
+=================
+R_SubdividePatchToGrid
+=================
+*/
+srfGridMesh_t *R_SubdividePatchToGrid( int width, int height,
+ drawVert_t points[MAX_PATCH_SIZE*MAX_PATCH_SIZE] ) {
+ int i, j, k, l;
+ drawVert_t prev, next, mid;
+ float len, maxLen;
+ int dir;
+ int t;
+ MAC_STATIC drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE];
+ float errorTable[2][MAX_GRID_SIZE];
+
+ for ( i = 0 ; i < width ; i++ ) {
+ for ( j = 0 ; j < height ; j++ ) {
+ ctrl[j][i] = points[j*width+i];
+ }
+ }
+
+ for ( dir = 0 ; dir < 2 ; dir++ ) {
+
+ for ( j = 0 ; j < MAX_GRID_SIZE ; j++ ) {
+ errorTable[dir][j] = 0;
+ }
+
+ // horizontal subdivisions
+ for ( j = 0 ; j + 2 < width ; j += 2 ) {
+ // check subdivided midpoints against control points
+
+ // FIXME: also check midpoints of adjacent patches against the control points
+ // this would basically stitch all patches in the same LOD group together.
+
+ maxLen = 0;
+ for ( i = 0 ; i < height ; i++ ) {
+ vec3_t midxyz;
+ vec3_t midxyz2;
+ vec3_t dir;
+ vec3_t projected;
+ float d;
+
+ // calculate the point on the curve
+ for ( l = 0 ; l < 3 ; l++ ) {
+ midxyz[l] = (ctrl[i][j].xyz[l] + ctrl[i][j+1].xyz[l] * 2
+ + ctrl[i][j+2].xyz[l] ) * 0.25f;
+ }
+
+ // see how far off the line it is
+ // using dist-from-line will not account for internal
+ // texture warping, but it gives a lot less polygons than
+ // dist-from-midpoint
+ VectorSubtract( midxyz, ctrl[i][j].xyz, midxyz );
+ VectorSubtract( ctrl[i][j+2].xyz, ctrl[i][j].xyz, dir );
+ VectorNormalize( dir );
+
+ d = DotProduct( midxyz, dir );
+ VectorScale( dir, d, projected );
+ VectorSubtract( midxyz, projected, midxyz2);
+ len = VectorLengthSquared( midxyz2 ); // we will do the sqrt later
+ if ( len > maxLen ) {
+ maxLen = len;
+ }
+ }
+
+ maxLen = sqrt(maxLen);
+
+ // if all the points are on the lines, remove the entire columns
+ if ( maxLen < 0.1f ) {
+ errorTable[dir][j+1] = 999;
+ continue;
+ }
+
+ // see if we want to insert subdivided columns
+ if ( width + 2 > MAX_GRID_SIZE ) {
+ errorTable[dir][j+1] = 1.0f/maxLen;
+ continue; // can't subdivide any more
+ }
+
+ if ( maxLen <= r_subdivisions->value ) {
+ errorTable[dir][j+1] = 1.0f/maxLen;
+ continue; // didn't need subdivision
+ }
+
+ errorTable[dir][j+2] = 1.0f/maxLen;
+
+ // insert two columns and replace the peak
+ width += 2;
+ for ( i = 0 ; i < height ; i++ ) {
+ LerpDrawVert( &ctrl[i][j], &ctrl[i][j+1], &prev );
+ LerpDrawVert( &ctrl[i][j+1], &ctrl[i][j+2], &next );
+ LerpDrawVert( &prev, &next, &mid );
+
+ for ( k = width - 1 ; k > j + 3 ; k-- ) {
+ ctrl[i][k] = ctrl[i][k-2];
+ }
+ ctrl[i][j + 1] = prev;
+ ctrl[i][j + 2] = mid;
+ ctrl[i][j + 3] = next;
+ }
+
+ // back up and recheck this set again, it may need more subdivision
+ j -= 2;
+
+ }
+
+ Transpose( width, height, ctrl );
+ t = width;
+ width = height;
+ height = t;
+ }
+
+
+ // put all the aproximating points on the curve
+ PutPointsOnCurve( ctrl, width, height );
+
+ // cull out any rows or columns that are colinear
+ for ( i = 1 ; i < width-1 ; i++ ) {
+ if ( errorTable[0][i] != 999 ) {
+ continue;
+ }
+ for ( j = i+1 ; j < width ; j++ ) {
+ for ( k = 0 ; k < height ; k++ ) {
+ ctrl[k][j-1] = ctrl[k][j];
+ }
+ errorTable[0][j-1] = errorTable[0][j];
+ }
+ width--;
+ }
+
+ for ( i = 1 ; i < height-1 ; i++ ) {
+ if ( errorTable[1][i] != 999 ) {
+ continue;
+ }
+ for ( j = i+1 ; j < height ; j++ ) {
+ for ( k = 0 ; k < width ; k++ ) {
+ ctrl[j-1][k] = ctrl[j][k];
+ }
+ errorTable[1][j-1] = errorTable[1][j];
+ }
+ height--;
+ }
+
+#if 1
+ // flip for longest tristrips as an optimization
+ // the results should be visually identical with or
+ // without this step
+ if ( height > width ) {
+ Transpose( width, height, ctrl );
+ InvertErrorTable( errorTable, width, height );
+ t = width;
+ width = height;
+ height = t;
+ InvertCtrl( width, height, ctrl );
+ }
+#endif
+
+ // calculate normals
+ MakeMeshNormals( width, height, ctrl );
+
+ return R_CreateSurfaceGridMesh( width, height, ctrl, errorTable );
+}
+
+/*
+===============
+R_GridInsertColumn
+===============
+*/
+srfGridMesh_t *R_GridInsertColumn( srfGridMesh_t *grid, int column, int row, vec3_t point, float loderror ) {
+ int i, j;
+ int width, height, oldwidth;
+ MAC_STATIC drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE];
+ float errorTable[2][MAX_GRID_SIZE];
+ float lodRadius;
+ vec3_t lodOrigin;
+
+ oldwidth = 0;
+ width = grid->width + 1;
+ if (width > MAX_GRID_SIZE)
+ return NULL;
+ height = grid->height;
+ for (i = 0; i < width; i++) {
+ if (i == column) {
+ //insert new column
+ for (j = 0; j < grid->height; j++) {
+ LerpDrawVert( &grid->verts[j * grid->width + i-1], &grid->verts[j * grid->width + i], &ctrl[j][i] );
+ if (j == row)
+ VectorCopy(point, ctrl[j][i].xyz);
+ }
+ errorTable[0][i] = loderror;
+ continue;
+ }
+ errorTable[0][i] = grid->widthLodError[oldwidth];
+ for (j = 0; j < grid->height; j++) {
+ ctrl[j][i] = grid->verts[j * grid->width + oldwidth];
+ }
+ oldwidth++;
+ }
+ for (j = 0; j < grid->height; j++) {
+ errorTable[1][j] = grid->heightLodError[j];
+ }
+ // put all the aproximating points on the curve
+ //PutPointsOnCurve( ctrl, width, height );
+ // calculate normals
+ MakeMeshNormals( width, height, ctrl );
+
+ VectorCopy(grid->lodOrigin, lodOrigin);
+ lodRadius = grid->lodRadius;
+ // free the old grid
+ R_FreeSurfaceGridMesh(grid);
+ // create a new grid
+ grid = R_CreateSurfaceGridMesh( width, height, ctrl, errorTable );
+ grid->lodRadius = lodRadius;
+ VectorCopy(lodOrigin, grid->lodOrigin);
+ return grid;
+}
+
+/*
+===============
+R_GridInsertRow
+===============
+*/
+srfGridMesh_t *R_GridInsertRow( srfGridMesh_t *grid, int row, int column, vec3_t point, float loderror ) {
+ int i, j;
+ int width, height, oldheight;
+ MAC_STATIC drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE];
+ float errorTable[2][MAX_GRID_SIZE];
+ float lodRadius;
+ vec3_t lodOrigin;
+
+ oldheight = 0;
+ width = grid->width;
+ height = grid->height + 1;
+ if (height > MAX_GRID_SIZE)
+ return NULL;
+ for (i = 0; i < height; i++) {
+ if (i == row) {
+ //insert new row
+ for (j = 0; j < grid->width; j++) {
+ LerpDrawVert( &grid->verts[(i-1) * grid->width + j], &grid->verts[i * grid->width + j], &ctrl[i][j] );
+ if (j == column)
+ VectorCopy(point, ctrl[i][j].xyz);
+ }
+ errorTable[1][i] = loderror;
+ continue;
+ }
+ errorTable[1][i] = grid->heightLodError[oldheight];
+ for (j = 0; j < grid->width; j++) {
+ ctrl[i][j] = grid->verts[oldheight * grid->width + j];
+ }
+ oldheight++;
+ }
+ for (j = 0; j < grid->width; j++) {
+ errorTable[0][j] = grid->widthLodError[j];
+ }
+ // put all the aproximating points on the curve
+ //PutPointsOnCurve( ctrl, width, height );
+ // calculate normals
+ MakeMeshNormals( width, height, ctrl );
+
+ VectorCopy(grid->lodOrigin, lodOrigin);
+ lodRadius = grid->lodRadius;
+ // free the old grid
+ R_FreeSurfaceGridMesh(grid);
+ // create a new grid
+ grid = R_CreateSurfaceGridMesh( width, height, ctrl, errorTable );
+ grid->lodRadius = lodRadius;
+ VectorCopy(lodOrigin, grid->lodOrigin);
+ return grid;
+}
diff --git a/code/renderer/tr_flares.c b/code/renderer/tr_flares.c
new file mode 100755
index 0000000..3ef4c58
--- /dev/null
+++ b/code/renderer/tr_flares.c
@@ -0,0 +1,447 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// tr_flares.c
+
+#include "tr_local.h"
+
+/*
+=============================================================================
+
+LIGHT FLARES
+
+A light flare is an effect that takes place inside the eye when bright light
+sources are visible. The size of the flare reletive to the screen is nearly
+constant, irrespective of distance, but the intensity should be proportional to the
+projected area of the light source.
+
+A surface that has been flagged as having a light flare will calculate the depth
+buffer value that it's midpoint should have when the surface is added.
+
+After all opaque surfaces have been rendered, the depth buffer is read back for
+each flare in view. If the point has not been obscured by a closer surface, the
+flare should be drawn.
+
+Surfaces that have a repeated texture should never be flagged as flaring, because
+there will only be a single flare added at the midpoint of the polygon.
+
+To prevent abrupt popping, the intensity of the flare is interpolated up and
+down as it changes visibility. This involves scene to scene state, unlike almost
+all other aspects of the renderer, and is complicated by the fact that a single
+frame may have multiple scenes.
+
+RB_RenderFlares() will be called once per view (twice in a mirrored scene, potentially
+up to five or more times in a frame with 3D status bar icons).
+
+=============================================================================
+*/
+
+
+// flare states maintain visibility over multiple frames for fading
+// layers: view, mirror, menu
+typedef struct flare_s {
+ struct flare_s *next; // for active chain
+
+ int addedFrame;
+
+ qboolean inPortal; // true if in a portal view of the scene
+ int frameSceneNum;
+ void *surface;
+ int fogNum;
+
+ int fadeTime;
+
+ qboolean visible; // state of last test
+ float drawIntensity; // may be non 0 even if !visible due to fading
+
+ int windowX, windowY;
+ float eyeZ;
+
+ vec3_t color;
+} flare_t;
+
+#define MAX_FLARES 128
+
+flare_t r_flareStructs[MAX_FLARES];
+flare_t *r_activeFlares, *r_inactiveFlares;
+
+/*
+==================
+R_ClearFlares
+==================
+*/
+void R_ClearFlares( void ) {
+ int i;
+
+ Com_Memset( r_flareStructs, 0, sizeof( r_flareStructs ) );
+ r_activeFlares = NULL;
+ r_inactiveFlares = NULL;
+
+ for ( i = 0 ; i < MAX_FLARES ; i++ ) {
+ r_flareStructs[i].next = r_inactiveFlares;
+ r_inactiveFlares = &r_flareStructs[i];
+ }
+}
+
+
+/*
+==================
+RB_AddFlare
+
+This is called at surface tesselation time
+==================
+*/
+void RB_AddFlare( void *surface, int fogNum, vec3_t point, vec3_t color, vec3_t normal ) {
+ int i;
+ flare_t *f, *oldest;
+ vec3_t local;
+ float d;
+ vec4_t eye, clip, normalized, window;
+
+ backEnd.pc.c_flareAdds++;
+
+ // if the point is off the screen, don't bother adding it
+ // calculate screen coordinates and depth
+ R_TransformModelToClip( point, backEnd.or.modelMatrix,
+ backEnd.viewParms.projectionMatrix, eye, clip );
+
+ // check to see if the point is completely off screen
+ for ( i = 0 ; i < 3 ; i++ ) {
+ if ( clip[i] >= clip[3] || clip[i] <= -clip[3] ) {
+ return;
+ }
+ }
+
+ R_TransformClipToWindow( clip, &backEnd.viewParms, normalized, window );
+
+ if ( window[0] < 0 || window[0] >= backEnd.viewParms.viewportWidth
+ || window[1] < 0 || window[1] >= backEnd.viewParms.viewportHeight ) {
+ return; // shouldn't happen, since we check the clip[] above, except for FP rounding
+ }
+
+ // see if a flare with a matching surface, scene, and view exists
+ oldest = r_flareStructs;
+ for ( f = r_activeFlares ; f ; f = f->next ) {
+ if ( f->surface == surface && f->frameSceneNum == backEnd.viewParms.frameSceneNum
+ && f->inPortal == backEnd.viewParms.isPortal ) {
+ break;
+ }
+ }
+
+ // allocate a new one
+ if (!f ) {
+ if ( !r_inactiveFlares ) {
+ // the list is completely full
+ return;
+ }
+ f = r_inactiveFlares;
+ r_inactiveFlares = r_inactiveFlares->next;
+ f->next = r_activeFlares;
+ r_activeFlares = f;
+
+ f->surface = surface;
+ f->frameSceneNum = backEnd.viewParms.frameSceneNum;
+ f->inPortal = backEnd.viewParms.isPortal;
+ f->addedFrame = -1;
+ }
+
+ if ( f->addedFrame != backEnd.viewParms.frameCount - 1 ) {
+ f->visible = qfalse;
+ f->fadeTime = backEnd.refdef.time - 2000;
+ }
+
+ f->addedFrame = backEnd.viewParms.frameCount;
+ f->fogNum = fogNum;
+
+ VectorCopy( color, f->color );
+
+ // fade the intensity of the flare down as the
+ // light surface turns away from the viewer
+ if ( normal ) {
+ VectorSubtract( backEnd.viewParms.or.origin, point, local );
+ VectorNormalizeFast( local );
+ d = DotProduct( local, normal );
+ VectorScale( f->color, d, f->color );
+ }
+
+ // save info needed to test
+ f->windowX = backEnd.viewParms.viewportX + window[0];
+ f->windowY = backEnd.viewParms.viewportY + window[1];
+
+ f->eyeZ = eye[2];
+}
+
+/*
+==================
+RB_AddDlightFlares
+==================
+*/
+void RB_AddDlightFlares( void ) {
+ dlight_t *l;
+ int i, j, k;
+ fog_t *fog;
+
+ if ( !r_flares->integer ) {
+ return;
+ }
+
+ l = backEnd.refdef.dlights;
+ fog = tr.world->fogs;
+ for (i=0 ; i<backEnd.refdef.num_dlights ; i++, l++) {
+
+ // find which fog volume the light is in
+ for ( j = 1 ; j < tr.world->numfogs ; j++ ) {
+ fog = &tr.world->fogs[j];
+ for ( k = 0 ; k < 3 ; k++ ) {
+ if ( l->origin[k] < fog->bounds[0][k] || l->origin[k] > fog->bounds[1][k] ) {
+ break;
+ }
+ }
+ if ( k == 3 ) {
+ break;
+ }
+ }
+ if ( j == tr.world->numfogs ) {
+ j = 0;
+ }
+
+ RB_AddFlare( (void *)l, j, l->origin, l->color, NULL );
+ }
+}
+
+/*
+===============================================================================
+
+FLARE BACK END
+
+===============================================================================
+*/
+
+/*
+==================
+RB_TestFlare
+==================
+*/
+void RB_TestFlare( flare_t *f ) {
+ float depth;
+ qboolean visible;
+ float fade;
+ float screenZ;
+
+ backEnd.pc.c_flareTests++;
+
+ // doing a readpixels is as good as doing a glFinish(), so
+ // don't bother with another sync
+ glState.finishCalled = qfalse;
+
+ // read back the z buffer contents
+ qglReadPixels( f->windowX, f->windowY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth );
+
+ screenZ = backEnd.viewParms.projectionMatrix[14] /
+ ( ( 2*depth - 1 ) * backEnd.viewParms.projectionMatrix[11] - backEnd.viewParms.projectionMatrix[10] );
+
+ visible = ( -f->eyeZ - -screenZ ) < 24;
+
+ if ( visible ) {
+ if ( !f->visible ) {
+ f->visible = qtrue;
+ f->fadeTime = backEnd.refdef.time - 1;
+ }
+ fade = ( ( backEnd.refdef.time - f->fadeTime ) /1000.0f ) * r_flareFade->value;
+ } else {
+ if ( f->visible ) {
+ f->visible = qfalse;
+ f->fadeTime = backEnd.refdef.time - 1;
+ }
+ fade = 1.0f - ( ( backEnd.refdef.time - f->fadeTime ) / 1000.0f ) * r_flareFade->value;
+ }
+
+ if ( fade < 0 ) {
+ fade = 0;
+ }
+ if ( fade > 1 ) {
+ fade = 1;
+ }
+
+ f->drawIntensity = fade;
+}
+
+
+/*
+==================
+RB_RenderFlare
+==================
+*/
+void RB_RenderFlare( flare_t *f ) {
+ float size;
+ vec3_t color;
+ int iColor[3];
+
+ backEnd.pc.c_flareRenders++;
+
+ VectorScale( f->color, f->drawIntensity*tr.identityLight, color );
+ iColor[0] = color[0] * 255;
+ iColor[1] = color[1] * 255;
+ iColor[2] = color[2] * 255;
+
+ size = backEnd.viewParms.viewportWidth * ( r_flareSize->value/640.0f + 8 / -f->eyeZ );
+
+ RB_BeginSurface( tr.flareShader, f->fogNum );
+
+ // FIXME: use quadstamp?
+ tess.xyz[tess.numVertexes][0] = f->windowX - size;
+ tess.xyz[tess.numVertexes][1] = f->windowY - size;
+ tess.texCoords[tess.numVertexes][0][0] = 0;
+ tess.texCoords[tess.numVertexes][0][1] = 0;
+ tess.vertexColors[tess.numVertexes][0] = iColor[0];
+ tess.vertexColors[tess.numVertexes][1] = iColor[1];
+ tess.vertexColors[tess.numVertexes][2] = iColor[2];
+ tess.vertexColors[tess.numVertexes][3] = 255;
+ tess.numVertexes++;
+
+ tess.xyz[tess.numVertexes][0] = f->windowX - size;
+ tess.xyz[tess.numVertexes][1] = f->windowY + size;
+ tess.texCoords[tess.numVertexes][0][0] = 0;
+ tess.texCoords[tess.numVertexes][0][1] = 1;
+ tess.vertexColors[tess.numVertexes][0] = iColor[0];
+ tess.vertexColors[tess.numVertexes][1] = iColor[1];
+ tess.vertexColors[tess.numVertexes][2] = iColor[2];
+ tess.vertexColors[tess.numVertexes][3] = 255;
+ tess.numVertexes++;
+
+ tess.xyz[tess.numVertexes][0] = f->windowX + size;
+ tess.xyz[tess.numVertexes][1] = f->windowY + size;
+ tess.texCoords[tess.numVertexes][0][0] = 1;
+ tess.texCoords[tess.numVertexes][0][1] = 1;
+ tess.vertexColors[tess.numVertexes][0] = iColor[0];
+ tess.vertexColors[tess.numVertexes][1] = iColor[1];
+ tess.vertexColors[tess.numVertexes][2] = iColor[2];
+ tess.vertexColors[tess.numVertexes][3] = 255;
+ tess.numVertexes++;
+
+ tess.xyz[tess.numVertexes][0] = f->windowX + size;
+ tess.xyz[tess.numVertexes][1] = f->windowY - size;
+ tess.texCoords[tess.numVertexes][0][0] = 1;
+ tess.texCoords[tess.numVertexes][0][1] = 0;
+ tess.vertexColors[tess.numVertexes][0] = iColor[0];
+ tess.vertexColors[tess.numVertexes][1] = iColor[1];
+ tess.vertexColors[tess.numVertexes][2] = iColor[2];
+ tess.vertexColors[tess.numVertexes][3] = 255;
+ tess.numVertexes++;
+
+ tess.indexes[tess.numIndexes++] = 0;
+ tess.indexes[tess.numIndexes++] = 1;
+ tess.indexes[tess.numIndexes++] = 2;
+ tess.indexes[tess.numIndexes++] = 0;
+ tess.indexes[tess.numIndexes++] = 2;
+ tess.indexes[tess.numIndexes++] = 3;
+
+ RB_EndSurface();
+}
+
+/*
+==================
+RB_RenderFlares
+
+Because flares are simulating an occular effect, they should be drawn after
+everything (all views) in the entire frame has been drawn.
+
+Because of the way portals use the depth buffer to mark off areas, the
+needed information would be lost after each view, so we are forced to draw
+flares after each view.
+
+The resulting artifact is that flares in mirrors or portals don't dim properly
+when occluded by something in the main view, and portal flares that should
+extend past the portal edge will be overwritten.
+==================
+*/
+void RB_RenderFlares (void) {
+ flare_t *f;
+ flare_t **prev;
+ qboolean draw;
+
+ if ( !r_flares->integer ) {
+ return;
+ }
+
+// RB_AddDlightFlares();
+
+ // perform z buffer readback on each flare in this view
+ draw = qfalse;
+ prev = &r_activeFlares;
+ while ( ( f = *prev ) != NULL ) {
+ // throw out any flares that weren't added last frame
+ if ( f->addedFrame < backEnd.viewParms.frameCount - 1 ) {
+ *prev = f->next;
+ f->next = r_inactiveFlares;
+ r_inactiveFlares = f;
+ continue;
+ }
+
+ // don't draw any here that aren't from this scene / portal
+ f->drawIntensity = 0;
+ if ( f->frameSceneNum == backEnd.viewParms.frameSceneNum
+ && f->inPortal == backEnd.viewParms.isPortal ) {
+ RB_TestFlare( f );
+ if ( f->drawIntensity ) {
+ draw = qtrue;
+ } else {
+ // this flare has completely faded out, so remove it from the chain
+ *prev = f->next;
+ f->next = r_inactiveFlares;
+ r_inactiveFlares = f;
+ continue;
+ }
+ }
+
+ prev = &f->next;
+ }
+
+ if ( !draw ) {
+ return; // none visible
+ }
+
+ if ( backEnd.viewParms.isPortal ) {
+ qglDisable (GL_CLIP_PLANE0);
+ }
+
+ qglPushMatrix();
+ qglLoadIdentity();
+ qglMatrixMode( GL_PROJECTION );
+ qglPushMatrix();
+ qglLoadIdentity();
+ qglOrtho( backEnd.viewParms.viewportX, backEnd.viewParms.viewportX + backEnd.viewParms.viewportWidth,
+ backEnd.viewParms.viewportY, backEnd.viewParms.viewportY + backEnd.viewParms.viewportHeight,
+ -99999, 99999 );
+
+ for ( f = r_activeFlares ; f ; f = f->next ) {
+ if ( f->frameSceneNum == backEnd.viewParms.frameSceneNum
+ && f->inPortal == backEnd.viewParms.isPortal
+ && f->drawIntensity ) {
+ RB_RenderFlare( f );
+ }
+ }
+
+ qglPopMatrix();
+ qglMatrixMode( GL_MODELVIEW );
+ qglPopMatrix();
+}
+
diff --git a/code/renderer/tr_font.c b/code/renderer/tr_font.c
new file mode 100755
index 0000000..a40c935
--- /dev/null
+++ b/code/renderer/tr_font.c
@@ -0,0 +1,542 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// tr_font.c
+//
+//
+// The font system uses FreeType 2.x to render TrueType fonts for use within the game.
+// As of this writing ( Nov, 2000 ) Team Arena uses these fonts for all of the ui and
+// about 90% of the cgame presentation. A few areas of the CGAME were left uses the old
+// fonts since the code is shared with standard Q3A.
+//
+// If you include this font rendering code in a commercial product you MUST include the
+// following somewhere with your product, see www.freetype.org for specifics or changes.
+// The Freetype code also uses some hinting techniques that MIGHT infringe on patents
+// held by apple so be aware of that also.
+//
+// As of Q3A 1.25+ and Team Arena, we are shipping the game with the font rendering code
+// disabled. This removes any potential patent issues and it keeps us from having to
+// distribute an actual TrueTrype font which is 1. expensive to do and 2. seems to require
+// an act of god to accomplish.
+//
+// What we did was pre-render the fonts using FreeType ( which is why we leave the FreeType
+// credit in the credits ) and then saved off the glyph data and then hand touched up the
+// font bitmaps so they scale a bit better in GL.
+//
+// There are limitations in the way fonts are saved and reloaded in that it is based on
+// point size and not name. So if you pre-render Helvetica in 18 point and Impact in 18 point
+// you will end up with a single 18 point data file and image set. Typically you will want to
+// choose 3 sizes to best approximate the scaling you will be doing in the ui scripting system
+//
+// In the UI Scripting code, a scale of 1.0 is equal to a 48 point font. In Team Arena, we
+// use three or four scales, most of them exactly equaling the specific rendered size. We
+// rendered three sizes in Team Arena, 12, 16, and 20.
+//
+// To generate new font data you need to go through the following steps.
+// 1. delete the fontImage_x_xx.tga files and fontImage_xx.dat files from the fonts path.
+// 2. in a ui script, specificy a font, smallFont, and bigFont keyword with font name and
+// point size. the original TrueType fonts must exist in fonts at this point.
+// 3. run the game, you should see things normally.
+// 4. Exit the game and there will be three dat files and at least three tga files. The
+// tga's are in 256x256 pages so if it takes three images to render a 24 point font you
+// will end up with fontImage_0_24.tga through fontImage_2_24.tga
+// 5. You will need to flip the tga's in Photoshop as the tga output code writes them upside
+// down.
+// 6. In future runs of the game, the system looks for these images and data files when a s
+// specific point sized font is rendered and loads them for use.
+// 7. Because of the original beta nature of the FreeType code you will probably want to hand
+// touch the font bitmaps.
+//
+// Currently a define in the project turns on or off the FreeType code which is currently
+// defined out. To pre-render new fonts you need enable the define ( BUILD_FREETYPE ) and
+// uncheck the exclude from build check box in the FreeType2 area of the Renderer project.
+
+
+#include "tr_local.h"
+#include "../qcommon/qcommon.h"
+
+#ifdef BUILD_FREETYPE
+#include "../ft2/fterrors.h"
+#include "../ft2/ftsystem.h"
+#include "../ft2/ftimage.h"
+#include "../ft2/freetype.h"
+#include "../ft2/ftoutln.h"
+
+#define _FLOOR(x) ((x) & -64)
+#define _CEIL(x) (((x)+63) & -64)
+#define _TRUNC(x) ((x) >> 6)
+
+FT_Library ftLibrary = NULL;
+#endif
+
+#define MAX_FONTS 6
+static int registeredFontCount = 0;
+static fontInfo_t registeredFont[MAX_FONTS];
+
+#ifdef BUILD_FREETYPE
+void R_GetGlyphInfo(FT_GlyphSlot glyph, int *left, int *right, int *width, int *top, int *bottom, int *height, int *pitch) {
+
+ *left = _FLOOR( glyph->metrics.horiBearingX );
+ *right = _CEIL( glyph->metrics.horiBearingX + glyph->metrics.width );
+ *width = _TRUNC(*right - *left);
+
+ *top = _CEIL( glyph->metrics.horiBearingY );
+ *bottom = _FLOOR( glyph->metrics.horiBearingY - glyph->metrics.height );
+ *height = _TRUNC( *top - *bottom );
+ *pitch = ( qtrue ? (*width+3) & -4 : (*width+7) >> 3 );
+}
+
+
+FT_Bitmap *R_RenderGlyph(FT_GlyphSlot glyph, glyphInfo_t* glyphOut) {
+
+ FT_Bitmap *bit2;
+ int left, right, width, top, bottom, height, pitch, size;
+
+ R_GetGlyphInfo(glyph, &left, &right, &width, &top, &bottom, &height, &pitch);
+
+ if ( glyph->format == ft_glyph_format_outline ) {
+ size = pitch*height;
+
+ bit2 = Z_Malloc(sizeof(FT_Bitmap));
+
+ bit2->width = width;
+ bit2->rows = height;
+ bit2->pitch = pitch;
+ bit2->pixel_mode = ft_pixel_mode_grays;
+ //bit2->pixel_mode = ft_pixel_mode_mono;
+ bit2->buffer = Z_Malloc(pitch*height);
+ bit2->num_grays = 256;
+
+ Com_Memset( bit2->buffer, 0, size );
+
+ FT_Outline_Translate( &glyph->outline, -left, -bottom );
+
+ FT_Outline_Get_Bitmap( ftLibrary, &glyph->outline, bit2 );
+
+ glyphOut->height = height;
+ glyphOut->pitch = pitch;
+ glyphOut->top = (glyph->metrics.horiBearingY >> 6) + 1;
+ glyphOut->bottom = bottom;
+
+ return bit2;
+ }
+ else {
+ ri.Printf(PRINT_ALL, "Non-outline fonts are not supported\n");
+ }
+ return NULL;
+}
+
+void WriteTGA (char *filename, byte *data, int width, int height) {
+ byte *buffer;
+ int i, c;
+
+ buffer = Z_Malloc(width*height*4 + 18);
+ Com_Memset (buffer, 0, 18);
+ buffer[2] = 2; // uncompressed type
+ buffer[12] = width&255;
+ buffer[13] = width>>8;
+ buffer[14] = height&255;
+ buffer[15] = height>>8;
+ buffer[16] = 32; // pixel size
+
+ // swap rgb to bgr
+ c = 18 + width * height * 4;
+ for (i=18 ; i<c ; i+=4)
+ {
+ buffer[i] = data[i-18+2]; // blue
+ buffer[i+1] = data[i-18+1]; // green
+ buffer[i+2] = data[i-18+0]; // red
+ buffer[i+3] = data[i-18+3]; // alpha
+ }
+
+ ri.FS_WriteFile(filename, buffer, c);
+
+ //f = fopen (filename, "wb");
+ //fwrite (buffer, 1, c, f);
+ //fclose (f);
+
+ Z_Free (buffer);
+}
+
+static glyphInfo_t *RE_ConstructGlyphInfo(unsigned char *imageOut, int *xOut, int *yOut, int *maxHeight, FT_Face face, const unsigned char c, qboolean calcHeight) {
+ int i;
+ static glyphInfo_t glyph;
+ unsigned char *src, *dst;
+ float scaled_width, scaled_height;
+ FT_Bitmap *bitmap = NULL;
+
+ Com_Memset(&glyph, 0, sizeof(glyphInfo_t));
+ // make sure everything is here
+ if (face != NULL) {
+ FT_Load_Glyph(face, FT_Get_Char_Index( face, c), FT_LOAD_DEFAULT );
+ bitmap = R_RenderGlyph(face->glyph, &glyph);
+ if (bitmap) {
+ glyph.xSkip = (face->glyph->metrics.horiAdvance >> 6) + 1;
+ } else {
+ return &glyph;
+ }
+
+ if (glyph.height > *maxHeight) {
+ *maxHeight = glyph.height;
+ }
+
+ if (calcHeight) {
+ Z_Free(bitmap->buffer);
+ Z_Free(bitmap);
+ return &glyph;
+ }
+
+/*
+ // need to convert to power of 2 sizes so we do not get
+ // any scaling from the gl upload
+ for (scaled_width = 1 ; scaled_width < glyph.pitch ; scaled_width<<=1)
+ ;
+ for (scaled_height = 1 ; scaled_height < glyph.height ; scaled_height<<=1)
+ ;
+*/
+
+ scaled_width = glyph.pitch;
+ scaled_height = glyph.height;
+
+ // we need to make sure we fit
+ if (*xOut + scaled_width + 1 >= 255) {
+ if (*yOut + *maxHeight + 1 >= 255) {
+ *yOut = -1;
+ *xOut = -1;
+ Z_Free(bitmap->buffer);
+ Z_Free(bitmap);
+ return &glyph;
+ } else {
+ *xOut = 0;
+ *yOut += *maxHeight + 1;
+ }
+ } else if (*yOut + *maxHeight + 1 >= 255) {
+ *yOut = -1;
+ *xOut = -1;
+ Z_Free(bitmap->buffer);
+ Z_Free(bitmap);
+ return &glyph;
+ }
+
+
+ src = bitmap->buffer;
+ dst = imageOut + (*yOut * 256) + *xOut;
+
+ if (bitmap->pixel_mode == ft_pixel_mode_mono) {
+ for (i = 0; i < glyph.height; i++) {
+ int j;
+ unsigned char *_src = src;
+ unsigned char *_dst = dst;
+ unsigned char mask = 0x80;
+ unsigned char val = *_src;
+ for (j = 0; j < glyph.pitch; j++) {
+ if (mask == 0x80) {
+ val = *_src++;
+ }
+ if (val & mask) {
+ *_dst = 0xff;
+ }
+ mask >>= 1;
+
+ if ( mask == 0 ) {
+ mask = 0x80;
+ }
+ _dst++;
+ }
+
+ src += glyph.pitch;
+ dst += 256;
+
+ }
+ } else {
+ for (i = 0; i < glyph.height; i++) {
+ Com_Memcpy(dst, src, glyph.pitch);
+ src += glyph.pitch;
+ dst += 256;
+ }
+ }
+
+ // we now have an 8 bit per pixel grey scale bitmap
+ // that is width wide and pf->ftSize->metrics.y_ppem tall
+
+ glyph.imageHeight = scaled_height;
+ glyph.imageWidth = scaled_width;
+ glyph.s = (float)*xOut / 256;
+ glyph.t = (float)*yOut / 256;
+ glyph.s2 = glyph.s + (float)scaled_width / 256;
+ glyph.t2 = glyph.t + (float)scaled_height / 256;
+
+ *xOut += scaled_width + 1;
+ }
+
+ Z_Free(bitmap->buffer);
+ Z_Free(bitmap);
+
+ return &glyph;
+}
+#endif
+
+static int fdOffset;
+static byte *fdFile;
+
+int readInt() {
+ int i = fdFile[fdOffset]+(fdFile[fdOffset+1]<<8)+(fdFile[fdOffset+2]<<16)+(fdFile[fdOffset+3]<<24);
+ fdOffset += 4;
+ return i;
+}
+
+typedef union {
+ byte fred[4];
+ float ffred;
+} poor;
+
+float readFloat() {
+ poor me;
+#if idppc
+ me.fred[0] = fdFile[fdOffset+3];
+ me.fred[1] = fdFile[fdOffset+2];
+ me.fred[2] = fdFile[fdOffset+1];
+ me.fred[3] = fdFile[fdOffset+0];
+#else
+ me.fred[0] = fdFile[fdOffset+0];
+ me.fred[1] = fdFile[fdOffset+1];
+ me.fred[2] = fdFile[fdOffset+2];
+ me.fred[3] = fdFile[fdOffset+3];
+#endif
+ fdOffset += 4;
+ return me.ffred;
+}
+
+void RE_RegisterFont(const char *fontName, int pointSize, fontInfo_t *font) {
+#ifdef BUILD_FREETYPE
+ FT_Face face;
+ int j, k, xOut, yOut, lastStart, imageNumber;
+ int scaledSize, newSize, maxHeight, left, satLevels;
+ unsigned char *out, *imageBuff;
+ glyphInfo_t *glyph;
+ image_t *image;
+ qhandle_t h;
+ float max;
+#endif
+ void *faceData;
+ int i, len;
+ char name[1024];
+ float dpi = 72; //
+ float glyphScale = 72.0f / dpi; // change the scale to be relative to 1 based on 72 dpi ( so dpi of 144 means a scale of .5 )
+
+ if (pointSize <= 0) {
+ pointSize = 12;
+ }
+ // we also need to adjust the scale based on point size relative to 48 points as the ui scaling is based on a 48 point font
+ glyphScale *= 48.0f / pointSize;
+
+ // make sure the render thread is stopped
+ R_SyncRenderThread();
+
+ if (registeredFontCount >= MAX_FONTS) {
+ ri.Printf(PRINT_ALL, "RE_RegisterFont: Too many fonts registered already.\n");
+ return;
+ }
+
+ Com_sprintf(name, sizeof(name), "fonts/fontImage_%i.dat",pointSize);
+ for (i = 0; i < registeredFontCount; i++) {
+ if (Q_stricmp(name, registeredFont[i].name) == 0) {
+ Com_Memcpy(font, &registeredFont[i], sizeof(fontInfo_t));
+ return;
+ }
+ }
+
+ len = ri.FS_ReadFile(name, NULL);
+ if (len == sizeof(fontInfo_t)) {
+ ri.FS_ReadFile(name, &faceData);
+ fdOffset = 0;
+ fdFile = faceData;
+ for(i=0; i<GLYPHS_PER_FONT; i++) {
+ font->glyphs[i].height = readInt();
+ font->glyphs[i].top = readInt();
+ font->glyphs[i].bottom = readInt();
+ font->glyphs[i].pitch = readInt();
+ font->glyphs[i].xSkip = readInt();
+ font->glyphs[i].imageWidth = readInt();
+ font->glyphs[i].imageHeight = readInt();
+ font->glyphs[i].s = readFloat();
+ font->glyphs[i].t = readFloat();
+ font->glyphs[i].s2 = readFloat();
+ font->glyphs[i].t2 = readFloat();
+ font->glyphs[i].glyph = readInt();
+ Com_Memcpy(font->glyphs[i].shaderName, &fdFile[fdOffset], 32);
+ fdOffset += 32;
+ }
+ font->glyphScale = readFloat();
+ Com_Memcpy(font->name, &fdFile[fdOffset], MAX_QPATH);
+
+// Com_Memcpy(font, faceData, sizeof(fontInfo_t));
+ Q_strncpyz(font->name, name, sizeof(font->name));
+ for (i = GLYPH_START; i < GLYPH_END; i++) {
+ font->glyphs[i].glyph = RE_RegisterShaderNoMip(font->glyphs[i].shaderName);
+ }
+ Com_Memcpy(&registeredFont[registeredFontCount++], font, sizeof(fontInfo_t));
+ return;
+ }
+
+#ifndef BUILD_FREETYPE
+ ri.Printf(PRINT_ALL, "RE_RegisterFont: FreeType code not available\n");
+#else
+ if (ftLibrary == NULL) {
+ ri.Printf(PRINT_ALL, "RE_RegisterFont: FreeType not initialized.\n");
+ return;
+ }
+
+ len = ri.FS_ReadFile(fontName, &faceData);
+ if (len <= 0) {
+ ri.Printf(PRINT_ALL, "RE_RegisterFont: Unable to read font file\n");
+ return;
+ }
+
+ // allocate on the stack first in case we fail
+ if (FT_New_Memory_Face( ftLibrary, faceData, len, 0, &face )) {
+ ri.Printf(PRINT_ALL, "RE_RegisterFont: FreeType2, unable to allocate new face.\n");
+ return;
+ }
+
+
+ if (FT_Set_Char_Size( face, pointSize << 6, pointSize << 6, dpi, dpi)) {
+ ri.Printf(PRINT_ALL, "RE_RegisterFont: FreeType2, Unable to set face char size.\n");
+ return;
+ }
+
+ //*font = &registeredFonts[registeredFontCount++];
+
+ // make a 256x256 image buffer, once it is full, register it, clean it and keep going
+ // until all glyphs are rendered
+
+ out = Z_Malloc(1024*1024);
+ if (out == NULL) {
+ ri.Printf(PRINT_ALL, "RE_RegisterFont: Z_Malloc failure during output image creation.\n");
+ return;
+ }
+ Com_Memset(out, 0, 1024*1024);
+
+ maxHeight = 0;
+
+ for (i = GLYPH_START; i < GLYPH_END; i++) {
+ glyph = RE_ConstructGlyphInfo(out, &xOut, &yOut, &maxHeight, face, (unsigned char)i, qtrue);
+ }
+
+ xOut = 0;
+ yOut = 0;
+ i = GLYPH_START;
+ lastStart = i;
+ imageNumber = 0;
+
+ while ( i <= GLYPH_END ) {
+
+ glyph = RE_ConstructGlyphInfo(out, &xOut, &yOut, &maxHeight, face, (unsigned char)i, qfalse);
+
+ if (xOut == -1 || yOut == -1 || i == GLYPH_END) {
+ // ran out of room
+ // we need to create an image from the bitmap, set all the handles in the glyphs to this point
+ //
+
+ scaledSize = 256*256;
+ newSize = scaledSize * 4;
+ imageBuff = Z_Malloc(newSize);
+ left = 0;
+ max = 0;
+ satLevels = 255;
+ for ( k = 0; k < (scaledSize) ; k++ ) {
+ if (max < out[k]) {
+ max = out[k];
+ }
+ }
+
+ if (max > 0) {
+ max = 255/max;
+ }
+
+ for ( k = 0; k < (scaledSize) ; k++ ) {
+ imageBuff[left++] = 255;
+ imageBuff[left++] = 255;
+ imageBuff[left++] = 255;
+
+ imageBuff[left++] = ((float)out[k] * max);
+ }
+
+ Com_sprintf (name, sizeof(name), "fonts/fontImage_%i_%i.tga", imageNumber++, pointSize);
+ if (r_saveFontData->integer) {
+ WriteTGA(name, imageBuff, 256, 256);
+ }
+
+ //Com_sprintf (name, sizeof(name), "fonts/fontImage_%i_%i", imageNumber++, pointSize);
+ image = R_CreateImage(name, imageBuff, 256, 256, qfalse, qfalse, GL_CLAMP);
+ h = RE_RegisterShaderFromImage(name, LIGHTMAP_2D, image, qfalse);
+ for (j = lastStart; j < i; j++) {
+ font->glyphs[j].glyph = h;
+ Q_strncpyz(font->glyphs[j].shaderName, name, sizeof(font->glyphs[j].shaderName));
+ }
+ lastStart = i;
+ Com_Memset(out, 0, 1024*1024);
+ xOut = 0;
+ yOut = 0;
+ Z_Free(imageBuff);
+ i++;
+ } else {
+ Com_Memcpy(&font->glyphs[i], glyph, sizeof(glyphInfo_t));
+ i++;
+ }
+ }
+
+ registeredFont[registeredFontCount].glyphScale = glyphScale;
+ font->glyphScale = glyphScale;
+ Com_Memcpy(&registeredFont[registeredFontCount++], font, sizeof(fontInfo_t));
+
+ if (r_saveFontData->integer) {
+ ri.FS_WriteFile(va("fonts/fontImage_%i.dat", pointSize), font, sizeof(fontInfo_t));
+ }
+
+ Z_Free(out);
+
+ ri.FS_FreeFile(faceData);
+#endif
+}
+
+
+
+void R_InitFreeType() {
+#ifdef BUILD_FREETYPE
+ if (FT_Init_FreeType( &ftLibrary )) {
+ ri.Printf(PRINT_ALL, "R_InitFreeType: Unable to initialize FreeType.\n");
+ }
+#endif
+ registeredFontCount = 0;
+}
+
+
+void R_DoneFreeType() {
+#ifdef BUILD_FREETYPE
+ if (ftLibrary) {
+ FT_Done_FreeType( ftLibrary );
+ ftLibrary = NULL;
+ }
+#endif
+ registeredFontCount = 0;
+}
+
diff --git a/code/renderer/tr_image.c b/code/renderer/tr_image.c
new file mode 100755
index 0000000..11e7913
--- /dev/null
+++ b/code/renderer/tr_image.c
@@ -0,0 +1,2520 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// tr_image.c
+#include "tr_local.h"
+
+/*
+ * Include file for users of JPEG library.
+ * You will need to have included system headers that define at least
+ * the typedefs FILE and size_t before you can include jpeglib.h.
+ * (stdio.h is sufficient on ANSI-conforming systems.)
+ * You may also wish to include "jerror.h".
+ */
+
+#define JPEG_INTERNALS
+#include "../jpeg-6/jpeglib.h"
+
+
+static void LoadBMP( const char *name, byte **pic, int *width, int *height );
+static void LoadTGA( const char *name, byte **pic, int *width, int *height );
+static void LoadJPG( const char *name, byte **pic, int *width, int *height );
+
+static byte s_intensitytable[256];
+static unsigned char s_gammatable[256];
+
+int gl_filter_min = GL_LINEAR_MIPMAP_NEAREST;
+int gl_filter_max = GL_LINEAR;
+
+#define FILE_HASH_SIZE 1024
+static image_t* hashTable[FILE_HASH_SIZE];
+
+/*
+** R_GammaCorrect
+*/
+void R_GammaCorrect( byte *buffer, int bufSize ) {
+ int i;
+
+ for ( i = 0; i < bufSize; i++ ) {
+ buffer[i] = s_gammatable[buffer[i]];
+ }
+}
+
+typedef struct {
+ char *name;
+ int minimize, maximize;
+} textureMode_t;
+
+textureMode_t modes[] = {
+ {"GL_NEAREST", GL_NEAREST, GL_NEAREST},
+ {"GL_LINEAR", GL_LINEAR, GL_LINEAR},
+ {"GL_NEAREST_MIPMAP_NEAREST", GL_NEAREST_MIPMAP_NEAREST, GL_NEAREST},
+ {"GL_LINEAR_MIPMAP_NEAREST", GL_LINEAR_MIPMAP_NEAREST, GL_LINEAR},
+ {"GL_NEAREST_MIPMAP_LINEAR", GL_NEAREST_MIPMAP_LINEAR, GL_NEAREST},
+ {"GL_LINEAR_MIPMAP_LINEAR", GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR}
+};
+
+/*
+================
+return a hash value for the filename
+================
+*/
+static long generateHashValue( const char *fname ) {
+ int i;
+ long hash;
+ char letter;
+
+ hash = 0;
+ i = 0;
+ while (fname[i] != '\0') {
+ letter = tolower(fname[i]);
+ if (letter =='.') break; // don't include extension
+ if (letter =='\\') letter = '/'; // damn path names
+ hash+=(long)(letter)*(i+119);
+ i++;
+ }
+ hash &= (FILE_HASH_SIZE-1);
+ return hash;
+}
+
+/*
+===============
+GL_TextureMode
+===============
+*/
+void GL_TextureMode( const char *string ) {
+ int i;
+ image_t *glt;
+
+ for ( i=0 ; i< 6 ; i++ ) {
+ if ( !Q_stricmp( modes[i].name, string ) ) {
+ break;
+ }
+ }
+
+ // hack to prevent trilinear from being set on voodoo,
+ // because their driver freaks...
+ if ( i == 5 && glConfig.hardwareType == GLHW_3DFX_2D3D ) {
+ ri.Printf( PRINT_ALL, "Refusing to set trilinear on a voodoo.\n" );
+ i = 3;
+ }
+
+
+ if ( i == 6 ) {
+ ri.Printf (PRINT_ALL, "bad filter name\n");
+ return;
+ }
+
+ gl_filter_min = modes[i].minimize;
+ gl_filter_max = modes[i].maximize;
+
+ // change all the existing mipmap texture objects
+ for ( i = 0 ; i < tr.numImages ; i++ ) {
+ glt = tr.images[ i ];
+ if ( glt->mipmap ) {
+ GL_Bind (glt);
+ qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min);
+ qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max);
+ }
+ }
+}
+
+/*
+===============
+R_SumOfUsedImages
+===============
+*/
+int R_SumOfUsedImages( void ) {
+ int total;
+ int i;
+
+ total = 0;
+ for ( i = 0; i < tr.numImages; i++ ) {
+ if ( tr.images[i]->frameUsed == tr.frameCount ) {
+ total += tr.images[i]->uploadWidth * tr.images[i]->uploadHeight;
+ }
+ }
+
+ return total;
+}
+
+/*
+===============
+R_ImageList_f
+===============
+*/
+void R_ImageList_f( void ) {
+ int i;
+ image_t *image;
+ int texels;
+ const char *yesno[] = {
+ "no ", "yes"
+ };
+
+ ri.Printf (PRINT_ALL, "\n -w-- -h-- -mm- -TMU- -if-- wrap --name-------\n");
+ texels = 0;
+
+ for ( i = 0 ; i < tr.numImages ; i++ ) {
+ image = tr.images[ i ];
+
+ texels += image->uploadWidth*image->uploadHeight;
+ ri.Printf (PRINT_ALL, "%4i: %4i %4i %s %d ",
+ i, image->uploadWidth, image->uploadHeight, yesno[image->mipmap], image->TMU );
+ switch ( image->internalFormat ) {
+ case 1:
+ ri.Printf( PRINT_ALL, "I " );
+ break;
+ case 2:
+ ri.Printf( PRINT_ALL, "IA " );
+ break;
+ case 3:
+ ri.Printf( PRINT_ALL, "RGB " );
+ break;
+ case 4:
+ ri.Printf( PRINT_ALL, "RGBA " );
+ break;
+ case GL_RGBA8:
+ ri.Printf( PRINT_ALL, "RGBA8" );
+ break;
+ case GL_RGB8:
+ ri.Printf( PRINT_ALL, "RGB8" );
+ break;
+ case GL_RGB4_S3TC:
+ ri.Printf( PRINT_ALL, "S3TC " );
+ break;
+ case GL_RGBA4:
+ ri.Printf( PRINT_ALL, "RGBA4" );
+ break;
+ case GL_RGB5:
+ ri.Printf( PRINT_ALL, "RGB5 " );
+ break;
+ default:
+ ri.Printf( PRINT_ALL, "???? " );
+ }
+
+ switch ( image->wrapClampMode ) {
+ case GL_REPEAT:
+ ri.Printf( PRINT_ALL, "rept " );
+ break;
+ case GL_CLAMP:
+ ri.Printf( PRINT_ALL, "clmp " );
+ break;
+ default:
+ ri.Printf( PRINT_ALL, "%4i ", image->wrapClampMode );
+ break;
+ }
+
+ ri.Printf( PRINT_ALL, " %s\n", image->imgName );
+ }
+ ri.Printf (PRINT_ALL, " ---------\n");
+ ri.Printf (PRINT_ALL, " %i total texels (not including mipmaps)\n", texels);
+ ri.Printf (PRINT_ALL, " %i total images\n\n", tr.numImages );
+}
+
+//=======================================================================
+
+/*
+================
+ResampleTexture
+
+Used to resample images in a more general than quartering fashion.
+
+This will only be filtered properly if the resampled size
+is greater than half the original size.
+
+If a larger shrinking is needed, use the mipmap function
+before or after.
+================
+*/
+static void ResampleTexture( unsigned *in, int inwidth, int inheight, unsigned *out,
+ int outwidth, int outheight ) {
+ int i, j;
+ unsigned *inrow, *inrow2;
+ unsigned frac, fracstep;
+ unsigned p1[2048], p2[2048];
+ byte *pix1, *pix2, *pix3, *pix4;
+
+ if (outwidth>2048)
+ ri.Error(ERR_DROP, "ResampleTexture: max width");
+
+ fracstep = inwidth*0x10000/outwidth;
+
+ frac = fracstep>>2;
+ for ( i=0 ; i<outwidth ; i++ ) {
+ p1[i] = 4*(frac>>16);
+ frac += fracstep;
+ }
+ frac = 3*(fracstep>>2);
+ for ( i=0 ; i<outwidth ; i++ ) {
+ p2[i] = 4*(frac>>16);
+ frac += fracstep;
+ }
+
+ for (i=0 ; i<outheight ; i++, out += outwidth) {
+ inrow = in + inwidth*(int)((i+0.25)*inheight/outheight);
+ inrow2 = in + inwidth*(int)((i+0.75)*inheight/outheight);
+ frac = fracstep >> 1;
+ for (j=0 ; j<outwidth ; j++) {
+ pix1 = (byte *)inrow + p1[j];
+ pix2 = (byte *)inrow + p2[j];
+ pix3 = (byte *)inrow2 + p1[j];
+ pix4 = (byte *)inrow2 + p2[j];
+ ((byte *)(out+j))[0] = (pix1[0] + pix2[0] + pix3[0] + pix4[0])>>2;
+ ((byte *)(out+j))[1] = (pix1[1] + pix2[1] + pix3[1] + pix4[1])>>2;
+ ((byte *)(out+j))[2] = (pix1[2] + pix2[2] + pix3[2] + pix4[2])>>2;
+ ((byte *)(out+j))[3] = (pix1[3] + pix2[3] + pix3[3] + pix4[3])>>2;
+ }
+ }
+}
+
+/*
+================
+R_LightScaleTexture
+
+Scale up the pixel values in a texture to increase the
+lighting range
+================
+*/
+void R_LightScaleTexture (unsigned *in, int inwidth, int inheight, qboolean only_gamma )
+{
+ if ( only_gamma )
+ {
+ if ( !glConfig.deviceSupportsGamma )
+ {
+ int i, c;
+ byte *p;
+
+ p = (byte *)in;
+
+ c = inwidth*inheight;
+ for (i=0 ; i<c ; i++, p+=4)
+ {
+ p[0] = s_gammatable[p[0]];
+ p[1] = s_gammatable[p[1]];
+ p[2] = s_gammatable[p[2]];
+ }
+ }
+ }
+ else
+ {
+ int i, c;
+ byte *p;
+
+ p = (byte *)in;
+
+ c = inwidth*inheight;
+
+ if ( glConfig.deviceSupportsGamma )
+ {
+ for (i=0 ; i<c ; i++, p+=4)
+ {
+ p[0] = s_intensitytable[p[0]];
+ p[1] = s_intensitytable[p[1]];
+ p[2] = s_intensitytable[p[2]];
+ }
+ }
+ else
+ {
+ for (i=0 ; i<c ; i++, p+=4)
+ {
+ p[0] = s_gammatable[s_intensitytable[p[0]]];
+ p[1] = s_gammatable[s_intensitytable[p[1]]];
+ p[2] = s_gammatable[s_intensitytable[p[2]]];
+ }
+ }
+ }
+}
+
+
+/*
+================
+R_MipMap2
+
+Operates in place, quartering the size of the texture
+Proper linear filter
+================
+*/
+static void R_MipMap2( unsigned *in, int inWidth, int inHeight ) {
+ int i, j, k;
+ byte *outpix;
+ int inWidthMask, inHeightMask;
+ int total;
+ int outWidth, outHeight;
+ unsigned *temp;
+
+ outWidth = inWidth >> 1;
+ outHeight = inHeight >> 1;
+ temp = ri.Hunk_AllocateTempMemory( outWidth * outHeight * 4 );
+
+ inWidthMask = inWidth - 1;
+ inHeightMask = inHeight - 1;
+
+ for ( i = 0 ; i < outHeight ; i++ ) {
+ for ( j = 0 ; j < outWidth ; j++ ) {
+ outpix = (byte *) ( temp + i * outWidth + j );
+ for ( k = 0 ; k < 4 ; k++ ) {
+ total =
+ 1 * ((byte *)&in[ ((i*2-1)&inHeightMask)*inWidth + ((j*2-1)&inWidthMask) ])[k] +
+ 2 * ((byte *)&in[ ((i*2-1)&inHeightMask)*inWidth + ((j*2)&inWidthMask) ])[k] +
+ 2 * ((byte *)&in[ ((i*2-1)&inHeightMask)*inWidth + ((j*2+1)&inWidthMask) ])[k] +
+ 1 * ((byte *)&in[ ((i*2-1)&inHeightMask)*inWidth + ((j*2+2)&inWidthMask) ])[k] +
+
+ 2 * ((byte *)&in[ ((i*2)&inHeightMask)*inWidth + ((j*2-1)&inWidthMask) ])[k] +
+ 4 * ((byte *)&in[ ((i*2)&inHeightMask)*inWidth + ((j*2)&inWidthMask) ])[k] +
+ 4 * ((byte *)&in[ ((i*2)&inHeightMask)*inWidth + ((j*2+1)&inWidthMask) ])[k] +
+ 2 * ((byte *)&in[ ((i*2)&inHeightMask)*inWidth + ((j*2+2)&inWidthMask) ])[k] +
+
+ 2 * ((byte *)&in[ ((i*2+1)&inHeightMask)*inWidth + ((j*2-1)&inWidthMask) ])[k] +
+ 4 * ((byte *)&in[ ((i*2+1)&inHeightMask)*inWidth + ((j*2)&inWidthMask) ])[k] +
+ 4 * ((byte *)&in[ ((i*2+1)&inHeightMask)*inWidth + ((j*2+1)&inWidthMask) ])[k] +
+ 2 * ((byte *)&in[ ((i*2+1)&inHeightMask)*inWidth + ((j*2+2)&inWidthMask) ])[k] +
+
+ 1 * ((byte *)&in[ ((i*2+2)&inHeightMask)*inWidth + ((j*2-1)&inWidthMask) ])[k] +
+ 2 * ((byte *)&in[ ((i*2+2)&inHeightMask)*inWidth + ((j*2)&inWidthMask) ])[k] +
+ 2 * ((byte *)&in[ ((i*2+2)&inHeightMask)*inWidth + ((j*2+1)&inWidthMask) ])[k] +
+ 1 * ((byte *)&in[ ((i*2+2)&inHeightMask)*inWidth + ((j*2+2)&inWidthMask) ])[k];
+ outpix[k] = total / 36;
+ }
+ }
+ }
+
+ Com_Memcpy( in, temp, outWidth * outHeight * 4 );
+ ri.Hunk_FreeTempMemory( temp );
+}
+
+/*
+================
+R_MipMap
+
+Operates in place, quartering the size of the texture
+================
+*/
+static void R_MipMap (byte *in, int width, int height) {
+ int i, j;
+ byte *out;
+ int row;
+
+ if ( !r_simpleMipMaps->integer ) {
+ R_MipMap2( (unsigned *)in, width, height );
+ return;
+ }
+
+ if ( width == 1 && height == 1 ) {
+ return;
+ }
+
+ row = width * 4;
+ out = in;
+ width >>= 1;
+ height >>= 1;
+
+ if ( width == 0 || height == 0 ) {
+ width += height; // get largest
+ for (i=0 ; i<width ; i++, out+=4, in+=8 ) {
+ out[0] = ( in[0] + in[4] )>>1;
+ out[1] = ( in[1] + in[5] )>>1;
+ out[2] = ( in[2] + in[6] )>>1;
+ out[3] = ( in[3] + in[7] )>>1;
+ }
+ return;
+ }
+
+ for (i=0 ; i<height ; i++, in+=row) {
+ for (j=0 ; j<width ; j++, out+=4, in+=8) {
+ out[0] = (in[0] + in[4] + in[row+0] + in[row+4])>>2;
+ out[1] = (in[1] + in[5] + in[row+1] + in[row+5])>>2;
+ out[2] = (in[2] + in[6] + in[row+2] + in[row+6])>>2;
+ out[3] = (in[3] + in[7] + in[row+3] + in[row+7])>>2;
+ }
+ }
+}
+
+
+/*
+==================
+R_BlendOverTexture
+
+Apply a color blend over a set of pixels
+==================
+*/
+static void R_BlendOverTexture( byte *data, int pixelCount, byte blend[4] ) {
+ int i;
+ int inverseAlpha;
+ int premult[3];
+
+ inverseAlpha = 255 - blend[3];
+ premult[0] = blend[0] * blend[3];
+ premult[1] = blend[1] * blend[3];
+ premult[2] = blend[2] * blend[3];
+
+ for ( i = 0 ; i < pixelCount ; i++, data+=4 ) {
+ data[0] = ( data[0] * inverseAlpha + premult[0] ) >> 9;
+ data[1] = ( data[1] * inverseAlpha + premult[1] ) >> 9;
+ data[2] = ( data[2] * inverseAlpha + premult[2] ) >> 9;
+ }
+}
+
+byte mipBlendColors[16][4] = {
+ {0,0,0,0},
+ {255,0,0,128},
+ {0,255,0,128},
+ {0,0,255,128},
+ {255,0,0,128},
+ {0,255,0,128},
+ {0,0,255,128},
+ {255,0,0,128},
+ {0,255,0,128},
+ {0,0,255,128},
+ {255,0,0,128},
+ {0,255,0,128},
+ {0,0,255,128},
+ {255,0,0,128},
+ {0,255,0,128},
+ {0,0,255,128},
+};
+
+
+/*
+===============
+Upload32
+
+===============
+*/
+extern qboolean charSet;
+static void Upload32( unsigned *data,
+ int width, int height,
+ qboolean mipmap,
+ qboolean picmip,
+ qboolean lightMap,
+ int *format,
+ int *pUploadWidth, int *pUploadHeight )
+{
+ int samples;
+ unsigned *scaledBuffer = NULL;
+ unsigned *resampledBuffer = NULL;
+ int scaled_width, scaled_height;
+ int i, c;
+ byte *scan;
+ GLenum internalFormat = GL_RGB;
+ float rMax = 0, gMax = 0, bMax = 0;
+
+ //
+ // convert to exact power of 2 sizes
+ //
+ for (scaled_width = 1 ; scaled_width < width ; scaled_width<<=1)
+ ;
+ for (scaled_height = 1 ; scaled_height < height ; scaled_height<<=1)
+ ;
+ if ( r_roundImagesDown->integer && scaled_width > width )
+ scaled_width >>= 1;
+ if ( r_roundImagesDown->integer && scaled_height > height )
+ scaled_height >>= 1;
+
+ if ( scaled_width != width || scaled_height != height ) {
+ resampledBuffer = ri.Hunk_AllocateTempMemory( scaled_width * scaled_height * 4 );
+ ResampleTexture (data, width, height, resampledBuffer, scaled_width, scaled_height);
+ data = resampledBuffer;
+ width = scaled_width;
+ height = scaled_height;
+ }
+
+ //
+ // perform optional picmip operation
+ //
+ if ( picmip ) {
+ scaled_width >>= r_picmip->integer;
+ scaled_height >>= r_picmip->integer;
+ }
+
+ //
+ // clamp to minimum size
+ //
+ if (scaled_width < 1) {
+ scaled_width = 1;
+ }
+ if (scaled_height < 1) {
+ scaled_height = 1;
+ }
+
+ //
+ // clamp to the current upper OpenGL limit
+ // scale both axis down equally so we don't have to
+ // deal with a half mip resampling
+ //
+ while ( scaled_width > glConfig.maxTextureSize
+ || scaled_height > glConfig.maxTextureSize ) {
+ scaled_width >>= 1;
+ scaled_height >>= 1;
+ }
+
+ scaledBuffer = ri.Hunk_AllocateTempMemory( sizeof( unsigned ) * scaled_width * scaled_height );
+
+ //
+ // scan the texture for each channel's max values
+ // and verify if the alpha channel is being used or not
+ //
+ c = width*height;
+ scan = ((byte *)data);
+ samples = 3;
+ if (!lightMap) {
+ for ( i = 0; i < c; i++ )
+ {
+ if ( scan[i*4+0] > rMax )
+ {
+ rMax = scan[i*4+0];
+ }
+ if ( scan[i*4+1] > gMax )
+ {
+ gMax = scan[i*4+1];
+ }
+ if ( scan[i*4+2] > bMax )
+ {
+ bMax = scan[i*4+2];
+ }
+ if ( scan[i*4 + 3] != 255 )
+ {
+ samples = 4;
+ break;
+ }
+ }
+ // select proper internal format
+ if ( samples == 3 )
+ {
+ if ( glConfig.textureCompression == TC_S3TC )
+ {
+ internalFormat = GL_RGB4_S3TC;
+ }
+ else if ( r_texturebits->integer == 16 )
+ {
+ internalFormat = GL_RGB5;
+ }
+ else if ( r_texturebits->integer == 32 )
+ {
+ internalFormat = GL_RGB8;
+ }
+ else
+ {
+ internalFormat = 3;
+ }
+ }
+ else if ( samples == 4 )
+ {
+ if ( r_texturebits->integer == 16 )
+ {
+ internalFormat = GL_RGBA4;
+ }
+ else if ( r_texturebits->integer == 32 )
+ {
+ internalFormat = GL_RGBA8;
+ }
+ else
+ {
+ internalFormat = 4;
+ }
+ }
+ } else {
+ internalFormat = 3;
+ }
+ // copy or resample data as appropriate for first MIP level
+ if ( ( scaled_width == width ) &&
+ ( scaled_height == height ) ) {
+ if (!mipmap)
+ {
+ qglTexImage2D (GL_TEXTURE_2D, 0, internalFormat, scaled_width, scaled_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
+ *pUploadWidth = scaled_width;
+ *pUploadHeight = scaled_height;
+ *format = internalFormat;
+
+ goto done;
+ }
+ Com_Memcpy (scaledBuffer, data, width*height*4);
+ }
+ else
+ {
+ // use the normal mip-mapping function to go down from here
+ while ( width > scaled_width || height > scaled_height ) {
+ R_MipMap( (byte *)data, width, height );
+ width >>= 1;
+ height >>= 1;
+ if ( width < 1 ) {
+ width = 1;
+ }
+ if ( height < 1 ) {
+ height = 1;
+ }
+ }
+ Com_Memcpy( scaledBuffer, data, width * height * 4 );
+ }
+
+ R_LightScaleTexture (scaledBuffer, scaled_width, scaled_height, !mipmap );
+
+ *pUploadWidth = scaled_width;
+ *pUploadHeight = scaled_height;
+ *format = internalFormat;
+
+ qglTexImage2D (GL_TEXTURE_2D, 0, internalFormat, scaled_width, scaled_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, scaledBuffer );
+
+ if (mipmap)
+ {
+ int miplevel;
+
+ miplevel = 0;
+ while (scaled_width > 1 || scaled_height > 1)
+ {
+ R_MipMap( (byte *)scaledBuffer, scaled_width, scaled_height );
+ scaled_width >>= 1;
+ scaled_height >>= 1;
+ if (scaled_width < 1)
+ scaled_width = 1;
+ if (scaled_height < 1)
+ scaled_height = 1;
+ miplevel++;
+
+ if ( r_colorMipLevels->integer ) {
+ R_BlendOverTexture( (byte *)scaledBuffer, scaled_width * scaled_height, mipBlendColors[miplevel] );
+ }
+
+ qglTexImage2D (GL_TEXTURE_2D, miplevel, internalFormat, scaled_width, scaled_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, scaledBuffer );
+ }
+ }
+done:
+
+ if (mipmap)
+ {
+ qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min);
+ qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max);
+ }
+ else
+ {
+ qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
+ qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
+ }
+
+ GL_CheckErrors();
+
+ if ( scaledBuffer != 0 )
+ ri.Hunk_FreeTempMemory( scaledBuffer );
+ if ( resampledBuffer != 0 )
+ ri.Hunk_FreeTempMemory( resampledBuffer );
+}
+
+
+/*
+================
+R_CreateImage
+
+This is the only way any image_t are created
+================
+*/
+image_t *R_CreateImage( const char *name, const byte *pic, int width, int height,
+ qboolean mipmap, qboolean allowPicmip, int glWrapClampMode ) {
+ image_t *image;
+ qboolean isLightmap = qfalse;
+ long hash;
+
+ if (strlen(name) >= MAX_QPATH ) {
+ ri.Error (ERR_DROP, "R_CreateImage: \"%s\" is too long\n", name);
+ }
+ if ( !strncmp( name, "*lightmap", 9 ) ) {
+ isLightmap = qtrue;
+ }
+
+ if ( tr.numImages == MAX_DRAWIMAGES ) {
+ ri.Error( ERR_DROP, "R_CreateImage: MAX_DRAWIMAGES hit\n");
+ }
+
+ image = tr.images[tr.numImages] = ri.Hunk_Alloc( sizeof( image_t ), h_low );
+ image->texnum = 1024 + tr.numImages;
+ tr.numImages++;
+
+ image->mipmap = mipmap;
+ image->allowPicmip = allowPicmip;
+
+ strcpy (image->imgName, name);
+
+ image->width = width;
+ image->height = height;
+ image->wrapClampMode = glWrapClampMode;
+
+ // lightmaps are always allocated on TMU 1
+ if ( qglActiveTextureARB && isLightmap ) {
+ image->TMU = 1;
+ } else {
+ image->TMU = 0;
+ }
+
+ if ( qglActiveTextureARB ) {
+ GL_SelectTexture( image->TMU );
+ }
+
+ GL_Bind(image);
+
+ Upload32( (unsigned *)pic, image->width, image->height,
+ image->mipmap,
+ allowPicmip,
+ isLightmap,
+ &image->internalFormat,
+ &image->uploadWidth,
+ &image->uploadHeight );
+
+ qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, glWrapClampMode );
+ qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, glWrapClampMode );
+
+ qglBindTexture( GL_TEXTURE_2D, 0 );
+
+ if ( image->TMU == 1 ) {
+ GL_SelectTexture( 0 );
+ }
+
+ hash = generateHashValue(name);
+ image->next = hashTable[hash];
+ hashTable[hash] = image;
+
+ return image;
+}
+
+
+/*
+=========================================================
+
+BMP LOADING
+
+=========================================================
+*/
+typedef struct
+{
+ char id[2];
+ unsigned long fileSize;
+ unsigned long reserved0;
+ unsigned long bitmapDataOffset;
+ unsigned long bitmapHeaderSize;
+ unsigned long width;
+ unsigned long height;
+ unsigned short planes;
+ unsigned short bitsPerPixel;
+ unsigned long compression;
+ unsigned long bitmapDataSize;
+ unsigned long hRes;
+ unsigned long vRes;
+ unsigned long colors;
+ unsigned long importantColors;
+ unsigned char palette[256][4];
+} BMPHeader_t;
+
+static void LoadBMP( const char *name, byte **pic, int *width, int *height )
+{
+ int columns, rows, numPixels;
+ byte *pixbuf;
+ int row, column;
+ byte *buf_p;
+ byte *buffer;
+ int length;
+ BMPHeader_t bmpHeader;
+ byte *bmpRGBA;
+
+ *pic = NULL;
+
+ //
+ // load the file
+ //
+ length = ri.FS_ReadFile( ( char * ) name, (void **)&buffer);
+ if (!buffer) {
+ return;
+ }
+
+ buf_p = buffer;
+
+ bmpHeader.id[0] = *buf_p++;
+ bmpHeader.id[1] = *buf_p++;
+ bmpHeader.fileSize = LittleLong( * ( long * ) buf_p );
+ buf_p += 4;
+ bmpHeader.reserved0 = LittleLong( * ( long * ) buf_p );
+ buf_p += 4;
+ bmpHeader.bitmapDataOffset = LittleLong( * ( long * ) buf_p );
+ buf_p += 4;
+ bmpHeader.bitmapHeaderSize = LittleLong( * ( long * ) buf_p );
+ buf_p += 4;
+ bmpHeader.width = LittleLong( * ( long * ) buf_p );
+ buf_p += 4;
+ bmpHeader.height = LittleLong( * ( long * ) buf_p );
+ buf_p += 4;
+ bmpHeader.planes = LittleShort( * ( short * ) buf_p );
+ buf_p += 2;
+ bmpHeader.bitsPerPixel = LittleShort( * ( short * ) buf_p );
+ buf_p += 2;
+ bmpHeader.compression = LittleLong( * ( long * ) buf_p );
+ buf_p += 4;
+ bmpHeader.bitmapDataSize = LittleLong( * ( long * ) buf_p );
+ buf_p += 4;
+ bmpHeader.hRes = LittleLong( * ( long * ) buf_p );
+ buf_p += 4;
+ bmpHeader.vRes = LittleLong( * ( long * ) buf_p );
+ buf_p += 4;
+ bmpHeader.colors = LittleLong( * ( long * ) buf_p );
+ buf_p += 4;
+ bmpHeader.importantColors = LittleLong( * ( long * ) buf_p );
+ buf_p += 4;
+
+ Com_Memcpy( bmpHeader.palette, buf_p, sizeof( bmpHeader.palette ) );
+
+ if ( bmpHeader.bitsPerPixel == 8 )
+ buf_p += 1024;
+
+ if ( bmpHeader.id[0] != 'B' && bmpHeader.id[1] != 'M' )
+ {
+ ri.Error( ERR_DROP, "LoadBMP: only Windows-style BMP files supported (%s)\n", name );
+ }
+ if ( bmpHeader.fileSize != length )
+ {
+ ri.Error( ERR_DROP, "LoadBMP: header size does not match file size (%d vs. %d) (%s)\n", bmpHeader.fileSize, length, name );
+ }
+ if ( bmpHeader.compression != 0 )
+ {
+ ri.Error( ERR_DROP, "LoadBMP: only uncompressed BMP files supported (%s)\n", name );
+ }
+ if ( bmpHeader.bitsPerPixel < 8 )
+ {
+ ri.Error( ERR_DROP, "LoadBMP: monochrome and 4-bit BMP files not supported (%s)\n", name );
+ }
+
+ columns = bmpHeader.width;
+ rows = bmpHeader.height;
+ if ( rows < 0 )
+ rows = -rows;
+ numPixels = columns * rows;
+
+ if ( width )
+ *width = columns;
+ if ( height )
+ *height = rows;
+
+ bmpRGBA = ri.Malloc( numPixels * 4 );
+ *pic = bmpRGBA;
+
+
+ for ( row = rows-1; row >= 0; row-- )
+ {
+ pixbuf = bmpRGBA + row*columns*4;
+
+ for ( column = 0; column < columns; column++ )
+ {
+ unsigned char red, green, blue, alpha;
+ int palIndex;
+ unsigned short shortPixel;
+
+ switch ( bmpHeader.bitsPerPixel )
+ {
+ case 8:
+ palIndex = *buf_p++;
+ *pixbuf++ = bmpHeader.palette[palIndex][2];
+ *pixbuf++ = bmpHeader.palette[palIndex][1];
+ *pixbuf++ = bmpHeader.palette[palIndex][0];
+ *pixbuf++ = 0xff;
+ break;
+ case 16:
+ shortPixel = * ( unsigned short * ) pixbuf;
+ pixbuf += 2;
+ *pixbuf++ = ( shortPixel & ( 31 << 10 ) ) >> 7;
+ *pixbuf++ = ( shortPixel & ( 31 << 5 ) ) >> 2;
+ *pixbuf++ = ( shortPixel & ( 31 ) ) << 3;
+ *pixbuf++ = 0xff;
+ break;
+
+ case 24:
+ blue = *buf_p++;
+ green = *buf_p++;
+ red = *buf_p++;
+ *pixbuf++ = red;
+ *pixbuf++ = green;
+ *pixbuf++ = blue;
+ *pixbuf++ = 255;
+ break;
+ case 32:
+ blue = *buf_p++;
+ green = *buf_p++;
+ red = *buf_p++;
+ alpha = *buf_p++;
+ *pixbuf++ = red;
+ *pixbuf++ = green;
+ *pixbuf++ = blue;
+ *pixbuf++ = alpha;
+ break;
+ default:
+ ri.Error( ERR_DROP, "LoadBMP: illegal pixel_size '%d' in file '%s'\n", bmpHeader.bitsPerPixel, name );
+ break;
+ }
+ }
+ }
+
+ ri.FS_FreeFile( buffer );
+
+}
+
+
+/*
+=================================================================
+
+PCX LOADING
+
+=================================================================
+*/
+
+
+/*
+==============
+LoadPCX
+==============
+*/
+static void LoadPCX ( const char *filename, byte **pic, byte **palette, int *width, int *height)
+{
+ byte *raw;
+ pcx_t *pcx;
+ int x, y;
+ int len;
+ int dataByte, runLength;
+ byte *out, *pix;
+ int xmax, ymax;
+
+ *pic = NULL;
+ *palette = NULL;
+
+ //
+ // load the file
+ //
+ len = ri.FS_ReadFile( ( char * ) filename, (void **)&raw);
+ if (!raw) {
+ return;
+ }
+
+ //
+ // parse the PCX file
+ //
+ pcx = (pcx_t *)raw;
+ raw = &pcx->data;
+
+ xmax = LittleShort(pcx->xmax);
+ ymax = LittleShort(pcx->ymax);
+
+ if (pcx->manufacturer != 0x0a
+ || pcx->version != 5
+ || pcx->encoding != 1
+ || pcx->bits_per_pixel != 8
+ || xmax >= 1024
+ || ymax >= 1024)
+ {
+ ri.Printf (PRINT_ALL, "Bad pcx file %s (%i x %i) (%i x %i)\n", filename, xmax+1, ymax+1, pcx->xmax, pcx->ymax);
+ return;
+ }
+
+ out = ri.Malloc ( (ymax+1) * (xmax+1) );
+
+ *pic = out;
+
+ pix = out;
+
+ if (palette)
+ {
+ *palette = ri.Malloc(768);
+ Com_Memcpy (*palette, (byte *)pcx + len - 768, 768);
+ }
+
+ if (width)
+ *width = xmax+1;
+ if (height)
+ *height = ymax+1;
+// FIXME: use bytes_per_line here?
+
+ for (y=0 ; y<=ymax ; y++, pix += xmax+1)
+ {
+ for (x=0 ; x<=xmax ; )
+ {
+ dataByte = *raw++;
+
+ if((dataByte & 0xC0) == 0xC0)
+ {
+ runLength = dataByte & 0x3F;
+ dataByte = *raw++;
+ }
+ else
+ runLength = 1;
+
+ while(runLength-- > 0)
+ pix[x++] = dataByte;
+ }
+
+ }
+
+ if ( raw - (byte *)pcx > len)
+ {
+ ri.Printf (PRINT_DEVELOPER, "PCX file %s was malformed", filename);
+ ri.Free (*pic);
+ *pic = NULL;
+ }
+
+ ri.FS_FreeFile (pcx);
+}
+
+
+/*
+==============
+LoadPCX32
+==============
+*/
+static void LoadPCX32 ( const char *filename, byte **pic, int *width, int *height) {
+ byte *palette;
+ byte *pic8;
+ int i, c, p;
+ byte *pic32;
+
+ LoadPCX (filename, &pic8, &palette, width, height);
+ if (!pic8) {
+ *pic = NULL;
+ return;
+ }
+
+ c = (*width) * (*height);
+ pic32 = *pic = ri.Malloc(4 * c );
+ for (i = 0 ; i < c ; i++) {
+ p = pic8[i];
+ pic32[0] = palette[p*3];
+ pic32[1] = palette[p*3 + 1];
+ pic32[2] = palette[p*3 + 2];
+ pic32[3] = 255;
+ pic32 += 4;
+ }
+
+ ri.Free (pic8);
+ ri.Free (palette);
+}
+
+/*
+=========================================================
+
+TARGA LOADING
+
+=========================================================
+*/
+
+/*
+=============
+LoadTGA
+=============
+*/
+static void LoadTGA ( const char *name, byte **pic, int *width, int *height)
+{
+ int columns, rows, numPixels;
+ byte *pixbuf;
+ int row, column;
+ byte *buf_p;
+ byte *buffer;
+ TargaHeader targa_header;
+ byte *targa_rgba;
+
+ *pic = NULL;
+
+ //
+ // load the file
+ //
+ ri.FS_ReadFile ( ( char * ) name, (void **)&buffer);
+ if (!buffer) {
+ return;
+ }
+
+ buf_p = buffer;
+
+ targa_header.id_length = *buf_p++;
+ targa_header.colormap_type = *buf_p++;
+ targa_header.image_type = *buf_p++;
+
+ targa_header.colormap_index = LittleShort ( *(short *)buf_p );
+ buf_p += 2;
+ targa_header.colormap_length = LittleShort ( *(short *)buf_p );
+ buf_p += 2;
+ targa_header.colormap_size = *buf_p++;
+ targa_header.x_origin = LittleShort ( *(short *)buf_p );
+ buf_p += 2;
+ targa_header.y_origin = LittleShort ( *(short *)buf_p );
+ buf_p += 2;
+ targa_header.width = LittleShort ( *(short *)buf_p );
+ buf_p += 2;
+ targa_header.height = LittleShort ( *(short *)buf_p );
+ buf_p += 2;
+ targa_header.pixel_size = *buf_p++;
+ targa_header.attributes = *buf_p++;
+
+ if (targa_header.image_type!=2
+ && targa_header.image_type!=10
+ && targa_header.image_type != 3 )
+ {
+ ri.Error (ERR_DROP, "LoadTGA: Only type 2 (RGB), 3 (gray), and 10 (RGB) TGA images supported\n");
+ }
+
+ if ( targa_header.colormap_type != 0 )
+ {
+ ri.Error( ERR_DROP, "LoadTGA: colormaps not supported\n" );
+ }
+
+ if ( ( targa_header.pixel_size != 32 && targa_header.pixel_size != 24 ) && targa_header.image_type != 3 )
+ {
+ ri.Error (ERR_DROP, "LoadTGA: Only 32 or 24 bit images supported (no colormaps)\n");
+ }
+
+ columns = targa_header.width;
+ rows = targa_header.height;
+ numPixels = columns * rows;
+
+ if (width)
+ *width = columns;
+ if (height)
+ *height = rows;
+
+ targa_rgba = ri.Malloc (numPixels*4);
+ *pic = targa_rgba;
+
+ if (targa_header.id_length != 0)
+ buf_p += targa_header.id_length; // skip TARGA image comment
+
+ if ( targa_header.image_type==2 || targa_header.image_type == 3 )
+ {
+ // Uncompressed RGB or gray scale image
+ for(row=rows-1; row>=0; row--)
+ {
+ pixbuf = targa_rgba + row*columns*4;
+ for(column=0; column<columns; column++)
+ {
+ unsigned char red,green,blue,alphabyte;
+ switch (targa_header.pixel_size)
+ {
+
+ case 8:
+ blue = *buf_p++;
+ green = blue;
+ red = blue;
+ *pixbuf++ = red;
+ *pixbuf++ = green;
+ *pixbuf++ = blue;
+ *pixbuf++ = 255;
+ break;
+
+ case 24:
+ blue = *buf_p++;
+ green = *buf_p++;
+ red = *buf_p++;
+ *pixbuf++ = red;
+ *pixbuf++ = green;
+ *pixbuf++ = blue;
+ *pixbuf++ = 255;
+ break;
+ case 32:
+ blue = *buf_p++;
+ green = *buf_p++;
+ red = *buf_p++;
+ alphabyte = *buf_p++;
+ *pixbuf++ = red;
+ *pixbuf++ = green;
+ *pixbuf++ = blue;
+ *pixbuf++ = alphabyte;
+ break;
+ default:
+ ri.Error( ERR_DROP, "LoadTGA: illegal pixel_size '%d' in file '%s'\n", targa_header.pixel_size, name );
+ break;
+ }
+ }
+ }
+ }
+ else if (targa_header.image_type==10) { // Runlength encoded RGB images
+ unsigned char red,green,blue,alphabyte,packetHeader,packetSize,j;
+
+ red = 0;
+ green = 0;
+ blue = 0;
+ alphabyte = 0xff;
+
+ for(row=rows-1; row>=0; row--) {
+ pixbuf = targa_rgba + row*columns*4;
+ for(column=0; column<columns; ) {
+ packetHeader= *buf_p++;
+ packetSize = 1 + (packetHeader & 0x7f);
+ if (packetHeader & 0x80) { // run-length packet
+ switch (targa_header.pixel_size) {
+ case 24:
+ blue = *buf_p++;
+ green = *buf_p++;
+ red = *buf_p++;
+ alphabyte = 255;
+ break;
+ case 32:
+ blue = *buf_p++;
+ green = *buf_p++;
+ red = *buf_p++;
+ alphabyte = *buf_p++;
+ break;
+ default:
+ ri.Error( ERR_DROP, "LoadTGA: illegal pixel_size '%d' in file '%s'\n", targa_header.pixel_size, name );
+ break;
+ }
+
+ for(j=0;j<packetSize;j++) {
+ *pixbuf++=red;
+ *pixbuf++=green;
+ *pixbuf++=blue;
+ *pixbuf++=alphabyte;
+ column++;
+ if (column==columns) { // run spans across rows
+ column=0;
+ if (row>0)
+ row--;
+ else
+ goto breakOut;
+ pixbuf = targa_rgba + row*columns*4;
+ }
+ }
+ }
+ else { // non run-length packet
+ for(j=0;j<packetSize;j++) {
+ switch (targa_header.pixel_size) {
+ case 24:
+ blue = *buf_p++;
+ green = *buf_p++;
+ red = *buf_p++;
+ *pixbuf++ = red;
+ *pixbuf++ = green;
+ *pixbuf++ = blue;
+ *pixbuf++ = 255;
+ break;
+ case 32:
+ blue = *buf_p++;
+ green = *buf_p++;
+ red = *buf_p++;
+ alphabyte = *buf_p++;
+ *pixbuf++ = red;
+ *pixbuf++ = green;
+ *pixbuf++ = blue;
+ *pixbuf++ = alphabyte;
+ break;
+ default:
+ ri.Error( ERR_DROP, "LoadTGA: illegal pixel_size '%d' in file '%s'\n", targa_header.pixel_size, name );
+ break;
+ }
+ column++;
+ if (column==columns) { // pixel packet run spans across rows
+ column=0;
+ if (row>0)
+ row--;
+ else
+ goto breakOut;
+ pixbuf = targa_rgba + row*columns*4;
+ }
+ }
+ }
+ }
+ breakOut:;
+ }
+ }
+
+#if 0
+ // TTimo: this is the chunk of code to ensure a behavior that meets TGA specs
+ // bk0101024 - fix from Leonardo
+ // bit 5 set => top-down
+ if (targa_header.attributes & 0x20) {
+ unsigned char *flip = (unsigned char*)malloc (columns*4);
+ unsigned char *src, *dst;
+
+ for (row = 0; row < rows/2; row++) {
+ src = targa_rgba + row * 4 * columns;
+ dst = targa_rgba + (rows - row - 1) * 4 * columns;
+
+ memcpy (flip, src, columns*4);
+ memcpy (src, dst, columns*4);
+ memcpy (dst, flip, columns*4);
+ }
+ free (flip);
+ }
+#endif
+ // instead we just print a warning
+ if (targa_header.attributes & 0x20) {
+ ri.Printf( PRINT_WARNING, "WARNING: '%s' TGA file header declares top-down image, ignoring\n", name);
+ }
+
+ ri.FS_FreeFile (buffer);
+}
+
+static void LoadJPG( const char *filename, unsigned char **pic, int *width, int *height ) {
+ /* This struct contains the JPEG decompression parameters and pointers to
+ * working space (which is allocated as needed by the JPEG library).
+ */
+ struct jpeg_decompress_struct cinfo;
+ /* We use our private extension JPEG error handler.
+ * Note that this struct must live as long as the main JPEG parameter
+ * struct, to avoid dangling-pointer problems.
+ */
+ /* This struct represents a JPEG error handler. It is declared separately
+ * because applications often want to supply a specialized error handler
+ * (see the second half of this file for an example). But here we just
+ * take the easy way out and use the standard error handler, which will
+ * print a message on stderr and call exit() if compression fails.
+ * Note that this struct must live as long as the main JPEG parameter
+ * struct, to avoid dangling-pointer problems.
+ */
+ struct jpeg_error_mgr jerr;
+ /* More stuff */
+ JSAMPARRAY buffer; /* Output row buffer */
+ int row_stride; /* physical row width in output buffer */
+ unsigned char *out;
+ byte *fbuffer;
+ byte *bbuf;
+
+ /* In this example we want to open the input file before doing anything else,
+ * so that the setjmp() error recovery below can assume the file is open.
+ * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
+ * requires it in order to read binary files.
+ */
+
+ ri.FS_ReadFile ( ( char * ) filename, (void **)&fbuffer);
+ if (!fbuffer) {
+ return;
+ }
+
+ /* Step 1: allocate and initialize JPEG decompression object */
+
+ /* We have to set up the error handler first, in case the initialization
+ * step fails. (Unlikely, but it could happen if you are out of memory.)
+ * This routine fills in the contents of struct jerr, and returns jerr's
+ * address which we place into the link field in cinfo.
+ */
+ cinfo.err = jpeg_std_error(&jerr);
+
+ /* Now we can initialize the JPEG decompression object. */
+ jpeg_create_decompress(&cinfo);
+
+ /* Step 2: specify data source (eg, a file) */
+
+ jpeg_stdio_src(&cinfo, fbuffer);
+
+ /* Step 3: read file parameters with jpeg_read_header() */
+
+ (void) jpeg_read_header(&cinfo, TRUE);
+ /* We can ignore the return value from jpeg_read_header since
+ * (a) suspension is not possible with the stdio data source, and
+ * (b) we passed TRUE to reject a tables-only JPEG file as an error.
+ * See libjpeg.doc for more info.
+ */
+
+ /* Step 4: set parameters for decompression */
+
+ /* In this example, we don't need to change any of the defaults set by
+ * jpeg_read_header(), so we do nothing here.
+ */
+
+ /* Step 5: Start decompressor */
+
+ (void) jpeg_start_decompress(&cinfo);
+ /* We can ignore the return value since suspension is not possible
+ * with the stdio data source.
+ */
+
+ /* We may need to do some setup of our own at this point before reading
+ * the data. After jpeg_start_decompress() we have the correct scaled
+ * output image dimensions available, as well as the output colormap
+ * if we asked for color quantization.
+ * In this example, we need to make an output work buffer of the right size.
+ */
+ /* JSAMPLEs per row in output buffer */
+ row_stride = cinfo.output_width * cinfo.output_components;
+
+ out = ri.Malloc(cinfo.output_width*cinfo.output_height*cinfo.output_components);
+
+ *pic = out;
+ *width = cinfo.output_width;
+ *height = cinfo.output_height;
+
+ /* Step 6: while (scan lines remain to be read) */
+ /* jpeg_read_scanlines(...); */
+
+ /* Here we use the library's state variable cinfo.output_scanline as the
+ * loop counter, so that we don't have to keep track ourselves.
+ */
+ while (cinfo.output_scanline < cinfo.output_height) {
+ /* jpeg_read_scanlines expects an array of pointers to scanlines.
+ * Here the array is only one element long, but you could ask for
+ * more than one scanline at a time if that's more convenient.
+ */
+ bbuf = ((out+(row_stride*cinfo.output_scanline)));
+ buffer = &bbuf;
+ (void) jpeg_read_scanlines(&cinfo, buffer, 1);
+ }
+
+ // clear all the alphas to 255
+ {
+ int i, j;
+ byte *buf;
+
+ buf = *pic;
+
+ j = cinfo.output_width * cinfo.output_height * 4;
+ for ( i = 3 ; i < j ; i+=4 ) {
+ buf[i] = 255;
+ }
+ }
+
+ /* Step 7: Finish decompression */
+
+ (void) jpeg_finish_decompress(&cinfo);
+ /* We can ignore the return value since suspension is not possible
+ * with the stdio data source.
+ */
+
+ /* Step 8: Release JPEG decompression object */
+
+ /* This is an important step since it will release a good deal of memory. */
+ jpeg_destroy_decompress(&cinfo);
+
+ /* After finish_decompress, we can close the input file.
+ * Here we postpone it until after no more JPEG errors are possible,
+ * so as to simplify the setjmp error logic above. (Actually, I don't
+ * think that jpeg_destroy can do an error exit, but why assume anything...)
+ */
+ ri.FS_FreeFile (fbuffer);
+
+ /* At this point you may want to check to see whether any corrupt-data
+ * warnings occurred (test whether jerr.pub.num_warnings is nonzero).
+ */
+
+ /* And we're done! */
+}
+
+
+/* Expanded data destination object for stdio output */
+
+typedef struct {
+ struct jpeg_destination_mgr pub; /* public fields */
+
+ byte* outfile; /* target stream */
+ int size;
+} my_destination_mgr;
+
+typedef my_destination_mgr * my_dest_ptr;
+
+
+/*
+ * Initialize destination --- called by jpeg_start_compress
+ * before any data is actually written.
+ */
+
+void init_destination (j_compress_ptr cinfo)
+{
+ my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
+
+ dest->pub.next_output_byte = dest->outfile;
+ dest->pub.free_in_buffer = dest->size;
+}
+
+
+/*
+ * Empty the output buffer --- called whenever buffer fills up.
+ *
+ * In typical applications, this should write the entire output buffer
+ * (ignoring the current state of next_output_byte & free_in_buffer),
+ * reset the pointer & count to the start of the buffer, and return TRUE
+ * indicating that the buffer has been dumped.
+ *
+ * In applications that need to be able to suspend compression due to output
+ * overrun, a FALSE return indicates that the buffer cannot be emptied now.
+ * In this situation, the compressor will return to its caller (possibly with
+ * an indication that it has not accepted all the supplied scanlines). The
+ * application should resume compression after it has made more room in the
+ * output buffer. Note that there are substantial restrictions on the use of
+ * suspension --- see the documentation.
+ *
+ * When suspending, the compressor will back up to a convenient restart point
+ * (typically the start of the current MCU). next_output_byte & free_in_buffer
+ * indicate where the restart point will be if the current call returns FALSE.
+ * Data beyond this point will be regenerated after resumption, so do not
+ * write it out when emptying the buffer externally.
+ */
+
+boolean empty_output_buffer (j_compress_ptr cinfo)
+{
+ return TRUE;
+}
+
+
+/*
+ * Compression initialization.
+ * Before calling this, all parameters and a data destination must be set up.
+ *
+ * We require a write_all_tables parameter as a failsafe check when writing
+ * multiple datastreams from the same compression object. Since prior runs
+ * will have left all the tables marked sent_table=TRUE, a subsequent run
+ * would emit an abbreviated stream (no tables) by default. This may be what
+ * is wanted, but for safety's sake it should not be the default behavior:
+ * programmers should have to make a deliberate choice to emit abbreviated
+ * images. Therefore the documentation and examples should encourage people
+ * to pass write_all_tables=TRUE; then it will take active thought to do the
+ * wrong thing.
+ */
+
+GLOBAL void
+jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
+{
+ if (cinfo->global_state != CSTATE_START)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+ if (write_all_tables)
+ jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
+
+ /* (Re)initialize error mgr and destination modules */
+ (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
+ (*cinfo->dest->init_destination) (cinfo);
+ /* Perform master selection of active modules */
+ jinit_compress_master(cinfo);
+ /* Set up for the first pass */
+ (*cinfo->master->prepare_for_pass) (cinfo);
+ /* Ready for application to drive first pass through jpeg_write_scanlines
+ * or jpeg_write_raw_data.
+ */
+ cinfo->next_scanline = 0;
+ cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
+}
+
+
+/*
+ * Write some scanlines of data to the JPEG compressor.
+ *
+ * The return value will be the number of lines actually written.
+ * This should be less than the supplied num_lines only in case that
+ * the data destination module has requested suspension of the compressor,
+ * or if more than image_height scanlines are passed in.
+ *
+ * Note: we warn about excess calls to jpeg_write_scanlines() since
+ * this likely signals an application programmer error. However,
+ * excess scanlines passed in the last valid call are *silently* ignored,
+ * so that the application need not adjust num_lines for end-of-image
+ * when using a multiple-scanline buffer.
+ */
+
+GLOBAL JDIMENSION
+jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
+ JDIMENSION num_lines)
+{
+ JDIMENSION row_ctr, rows_left;
+
+ if (cinfo->global_state != CSTATE_SCANNING)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ if (cinfo->next_scanline >= cinfo->image_height)
+ WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
+
+ /* Call progress monitor hook if present */
+ if (cinfo->progress != NULL) {
+ cinfo->progress->pass_counter = (long) cinfo->next_scanline;
+ cinfo->progress->pass_limit = (long) cinfo->image_height;
+ (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+ }
+
+ /* Give master control module another chance if this is first call to
+ * jpeg_write_scanlines. This lets output of the frame/scan headers be
+ * delayed so that application can write COM, etc, markers between
+ * jpeg_start_compress and jpeg_write_scanlines.
+ */
+ if (cinfo->master->call_pass_startup)
+ (*cinfo->master->pass_startup) (cinfo);
+
+ /* Ignore any extra scanlines at bottom of image. */
+ rows_left = cinfo->image_height - cinfo->next_scanline;
+ if (num_lines > rows_left)
+ num_lines = rows_left;
+
+ row_ctr = 0;
+ (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
+ cinfo->next_scanline += row_ctr;
+ return row_ctr;
+}
+
+/*
+ * Terminate destination --- called by jpeg_finish_compress
+ * after all data has been written. Usually needs to flush buffer.
+ *
+ * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
+ * application must deal with any cleanup that should happen even
+ * for error exit.
+ */
+
+static int hackSize;
+
+void term_destination (j_compress_ptr cinfo)
+{
+ my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
+ size_t datacount = dest->size - dest->pub.free_in_buffer;
+ hackSize = datacount;
+}
+
+
+/*
+ * Prepare for output to a stdio stream.
+ * The caller must have already opened the stream, and is responsible
+ * for closing it after finishing compression.
+ */
+
+void jpegDest (j_compress_ptr cinfo, byte* outfile, int size)
+{
+ my_dest_ptr dest;
+
+ /* The destination object is made permanent so that multiple JPEG images
+ * can be written to the same file without re-executing jpeg_stdio_dest.
+ * This makes it dangerous to use this manager and a different destination
+ * manager serially with the same JPEG object, because their private object
+ * sizes may be different. Caveat programmer.
+ */
+ if (cinfo->dest == NULL) { /* first time for this JPEG object? */
+ cinfo->dest = (struct jpeg_destination_mgr *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ sizeof(my_destination_mgr));
+ }
+
+ dest = (my_dest_ptr) cinfo->dest;
+ dest->pub.init_destination = init_destination;
+ dest->pub.empty_output_buffer = empty_output_buffer;
+ dest->pub.term_destination = term_destination;
+ dest->outfile = outfile;
+ dest->size = size;
+}
+
+void SaveJPG(char * filename, int quality, int image_width, int image_height, unsigned char *image_buffer) {
+ /* This struct contains the JPEG compression parameters and pointers to
+ * working space (which is allocated as needed by the JPEG library).
+ * It is possible to have several such structures, representing multiple
+ * compression/decompression processes, in existence at once. We refer
+ * to any one struct (and its associated working data) as a "JPEG object".
+ */
+ struct jpeg_compress_struct cinfo;
+ /* This struct represents a JPEG error handler. It is declared separately
+ * because applications often want to supply a specialized error handler
+ * (see the second half of this file for an example). But here we just
+ * take the easy way out and use the standard error handler, which will
+ * print a message on stderr and call exit() if compression fails.
+ * Note that this struct must live as long as the main JPEG parameter
+ * struct, to avoid dangling-pointer problems.
+ */
+ struct jpeg_error_mgr jerr;
+ /* More stuff */
+ JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
+ int row_stride; /* physical row width in image buffer */
+ unsigned char *out;
+
+ /* Step 1: allocate and initialize JPEG compression object */
+
+ /* We have to set up the error handler first, in case the initialization
+ * step fails. (Unlikely, but it could happen if you are out of memory.)
+ * This routine fills in the contents of struct jerr, and returns jerr's
+ * address which we place into the link field in cinfo.
+ */
+ cinfo.err = jpeg_std_error(&jerr);
+ /* Now we can initialize the JPEG compression object. */
+ jpeg_create_compress(&cinfo);
+
+ /* Step 2: specify data destination (eg, a file) */
+ /* Note: steps 2 and 3 can be done in either order. */
+
+ /* Here we use the library-supplied code to send compressed data to a
+ * stdio stream. You can also write your own code to do something else.
+ * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
+ * requires it in order to write binary files.
+ */
+ out = ri.Hunk_AllocateTempMemory(image_width*image_height*4);
+ jpegDest(&cinfo, out, image_width*image_height*4);
+
+ /* Step 3: set parameters for compression */
+
+ /* First we supply a description of the input image.
+ * Four fields of the cinfo struct must be filled in:
+ */
+ cinfo.image_width = image_width; /* image width and height, in pixels */
+ cinfo.image_height = image_height;
+ cinfo.input_components = 4; /* # of color components per pixel */
+ cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
+ /* Now use the library's routine to set default compression parameters.
+ * (You must set at least cinfo.in_color_space before calling this,
+ * since the defaults depend on the source color space.)
+ */
+ jpeg_set_defaults(&cinfo);
+ /* Now you can set any non-default parameters you wish to.
+ * Here we just illustrate the use of quality (quantization table) scaling:
+ */
+ jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
+
+ /* Step 4: Start compressor */
+
+ /* TRUE ensures that we will write a complete interchange-JPEG file.
+ * Pass TRUE unless you are very sure of what you're doing.
+ */
+ jpeg_start_compress(&cinfo, TRUE);
+
+ /* Step 5: while (scan lines remain to be written) */
+ /* jpeg_write_scanlines(...); */
+
+ /* Here we use the library's state variable cinfo.next_scanline as the
+ * loop counter, so that we don't have to keep track ourselves.
+ * To keep things simple, we pass one scanline per call; you can pass
+ * more if you wish, though.
+ */
+ row_stride = image_width * 4; /* JSAMPLEs per row in image_buffer */
+
+ while (cinfo.next_scanline < cinfo.image_height) {
+ /* jpeg_write_scanlines expects an array of pointers to scanlines.
+ * Here the array is only one element long, but you could pass
+ * more than one scanline at a time if that's more convenient.
+ */
+ row_pointer[0] = & image_buffer[((cinfo.image_height-1)*row_stride)-cinfo.next_scanline * row_stride];
+ (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
+ }
+
+ /* Step 6: Finish compression */
+
+ jpeg_finish_compress(&cinfo);
+ /* After finish_compress, we can close the output file. */
+ ri.FS_WriteFile( filename, out, hackSize );
+
+ ri.Hunk_FreeTempMemory(out);
+
+ /* Step 7: release JPEG compression object */
+
+ /* This is an important step since it will release a good deal of memory. */
+ jpeg_destroy_compress(&cinfo);
+
+ /* And we're done! */
+}
+
+//===================================================================
+
+/*
+=================
+R_LoadImage
+
+Loads any of the supported image types into a cannonical
+32 bit format.
+=================
+*/
+void R_LoadImage( const char *name, byte **pic, int *width, int *height ) {
+ int len;
+
+ *pic = NULL;
+ *width = 0;
+ *height = 0;
+
+ len = strlen(name);
+ if (len<5) {
+ return;
+ }
+
+ if ( !Q_stricmp( name+len-4, ".tga" ) ) {
+ LoadTGA( name, pic, width, height ); // try tga first
+ if (!*pic) { //
+ char altname[MAX_QPATH]; // try jpg in place of tga
+ strcpy( altname, name );
+ len = strlen( altname );
+ altname[len-3] = 'j';
+ altname[len-2] = 'p';
+ altname[len-1] = 'g';
+ LoadJPG( altname, pic, width, height );
+ }
+ } else if ( !Q_stricmp(name+len-4, ".pcx") ) {
+ LoadPCX32( name, pic, width, height );
+ } else if ( !Q_stricmp( name+len-4, ".bmp" ) ) {
+ LoadBMP( name, pic, width, height );
+ } else if ( !Q_stricmp( name+len-4, ".jpg" ) ) {
+ LoadJPG( name, pic, width, height );
+ }
+}
+
+
+/*
+===============
+R_FindImageFile
+
+Finds or loads the given image.
+Returns NULL if it fails, not a default image.
+==============
+*/
+image_t *R_FindImageFile( const char *name, qboolean mipmap, qboolean allowPicmip, int glWrapClampMode ) {
+ image_t *image;
+ int width, height;
+ byte *pic;
+ long hash;
+
+ if (!name) {
+ return NULL;
+ }
+
+ hash = generateHashValue(name);
+
+ //
+ // see if the image is already loaded
+ //
+ for (image=hashTable[hash]; image; image=image->next) {
+ if ( !strcmp( name, image->imgName ) ) {
+ // the white image can be used with any set of parms, but other mismatches are errors
+ if ( strcmp( name, "*white" ) ) {
+ if ( image->mipmap != mipmap ) {
+ ri.Printf( PRINT_DEVELOPER, "WARNING: reused image %s with mixed mipmap parm\n", name );
+ }
+ if ( image->allowPicmip != allowPicmip ) {
+ ri.Printf( PRINT_DEVELOPER, "WARNING: reused image %s with mixed allowPicmip parm\n", name );
+ }
+ if ( image->wrapClampMode != glWrapClampMode ) {
+ ri.Printf( PRINT_ALL, "WARNING: reused image %s with mixed glWrapClampMode parm\n", name );
+ }
+ }
+ return image;
+ }
+ }
+
+ //
+ // load the pic from disk
+ //
+ R_LoadImage( name, &pic, &width, &height );
+ if ( pic == NULL ) { // if we dont get a successful load
+ char altname[MAX_QPATH]; // copy the name
+ int len; //
+ strcpy( altname, name ); //
+ len = strlen( altname ); //
+ altname[len-3] = toupper(altname[len-3]); // and try upper case extension for unix systems
+ altname[len-2] = toupper(altname[len-2]); //
+ altname[len-1] = toupper(altname[len-1]); //
+ ri.Printf( PRINT_ALL, "trying %s...\n", altname ); //
+ R_LoadImage( altname, &pic, &width, &height ); //
+ if (pic == NULL) { // if that fails
+ return NULL; // bail
+ }
+ }
+
+ image = R_CreateImage( ( char * ) name, pic, width, height, mipmap, allowPicmip, glWrapClampMode );
+ ri.Free( pic );
+ return image;
+}
+
+
+/*
+================
+R_CreateDlightImage
+================
+*/
+#define DLIGHT_SIZE 16
+static void R_CreateDlightImage( void ) {
+ int x,y;
+ byte data[DLIGHT_SIZE][DLIGHT_SIZE][4];
+ int b;
+
+ // make a centered inverse-square falloff blob for dynamic lighting
+ for (x=0 ; x<DLIGHT_SIZE ; x++) {
+ for (y=0 ; y<DLIGHT_SIZE ; y++) {
+ float d;
+
+ d = ( DLIGHT_SIZE/2 - 0.5f - x ) * ( DLIGHT_SIZE/2 - 0.5f - x ) +
+ ( DLIGHT_SIZE/2 - 0.5f - y ) * ( DLIGHT_SIZE/2 - 0.5f - y );
+ b = 4000 / d;
+ if (b > 255) {
+ b = 255;
+ } else if ( b < 75 ) {
+ b = 0;
+ }
+ data[y][x][0] =
+ data[y][x][1] =
+ data[y][x][2] = b;
+ data[y][x][3] = 255;
+ }
+ }
+ tr.dlightImage = R_CreateImage("*dlight", (byte *)data, DLIGHT_SIZE, DLIGHT_SIZE, qfalse, qfalse, GL_CLAMP );
+}
+
+
+/*
+=================
+R_InitFogTable
+=================
+*/
+void R_InitFogTable( void ) {
+ int i;
+ float d;
+ float exp;
+
+ exp = 0.5;
+
+ for ( i = 0 ; i < FOG_TABLE_SIZE ; i++ ) {
+ d = pow ( (float)i/(FOG_TABLE_SIZE-1), exp );
+
+ tr.fogTable[i] = d;
+ }
+}
+
+/*
+================
+R_FogFactor
+
+Returns a 0.0 to 1.0 fog density value
+This is called for each texel of the fog texture on startup
+and for each vertex of transparent shaders in fog dynamically
+================
+*/
+float R_FogFactor( float s, float t ) {
+ float d;
+
+ s -= 1.0/512;
+ if ( s < 0 ) {
+ return 0;
+ }
+ if ( t < 1.0/32 ) {
+ return 0;
+ }
+ if ( t < 31.0/32 ) {
+ s *= (t - 1.0f/32.0f) / (30.0f/32.0f);
+ }
+
+ // we need to leave a lot of clamp range
+ s *= 8;
+
+ if ( s > 1.0 ) {
+ s = 1.0;
+ }
+
+ d = tr.fogTable[ (int)(s * (FOG_TABLE_SIZE-1)) ];
+
+ return d;
+}
+
+/*
+================
+R_CreateFogImage
+================
+*/
+#define FOG_S 256
+#define FOG_T 32
+static void R_CreateFogImage( void ) {
+ int x,y;
+ byte *data;
+ float g;
+ float d;
+ float borderColor[4];
+
+ data = ri.Hunk_AllocateTempMemory( FOG_S * FOG_T * 4 );
+
+ g = 2.0;
+
+ // S is distance, T is depth
+ for (x=0 ; x<FOG_S ; x++) {
+ for (y=0 ; y<FOG_T ; y++) {
+ d = R_FogFactor( ( x + 0.5f ) / FOG_S, ( y + 0.5f ) / FOG_T );
+
+ data[(y*FOG_S+x)*4+0] =
+ data[(y*FOG_S+x)*4+1] =
+ data[(y*FOG_S+x)*4+2] = 255;
+ data[(y*FOG_S+x)*4+3] = 255*d;
+ }
+ }
+ // standard openGL clamping doesn't really do what we want -- it includes
+ // the border color at the edges. OpenGL 1.2 has clamp-to-edge, which does
+ // what we want.
+ tr.fogImage = R_CreateImage("*fog", (byte *)data, FOG_S, FOG_T, qfalse, qfalse, GL_CLAMP );
+ ri.Hunk_FreeTempMemory( data );
+
+ borderColor[0] = 1.0;
+ borderColor[1] = 1.0;
+ borderColor[2] = 1.0;
+ borderColor[3] = 1;
+
+ qglTexParameterfv( GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor );
+}
+
+/*
+==================
+R_CreateDefaultImage
+==================
+*/
+#define DEFAULT_SIZE 16
+static void R_CreateDefaultImage( void ) {
+ int x;
+ byte data[DEFAULT_SIZE][DEFAULT_SIZE][4];
+
+ // the default image will be a box, to allow you to see the mapping coordinates
+ Com_Memset( data, 32, sizeof( data ) );
+ for ( x = 0 ; x < DEFAULT_SIZE ; x++ ) {
+ data[0][x][0] =
+ data[0][x][1] =
+ data[0][x][2] =
+ data[0][x][3] = 255;
+
+ data[x][0][0] =
+ data[x][0][1] =
+ data[x][0][2] =
+ data[x][0][3] = 255;
+
+ data[DEFAULT_SIZE-1][x][0] =
+ data[DEFAULT_SIZE-1][x][1] =
+ data[DEFAULT_SIZE-1][x][2] =
+ data[DEFAULT_SIZE-1][x][3] = 255;
+
+ data[x][DEFAULT_SIZE-1][0] =
+ data[x][DEFAULT_SIZE-1][1] =
+ data[x][DEFAULT_SIZE-1][2] =
+ data[x][DEFAULT_SIZE-1][3] = 255;
+ }
+ tr.defaultImage = R_CreateImage("*default", (byte *)data, DEFAULT_SIZE, DEFAULT_SIZE, qtrue, qfalse, GL_REPEAT );
+}
+
+/*
+==================
+R_CreateBuiltinImages
+==================
+*/
+void R_CreateBuiltinImages( void ) {
+ int x,y;
+ byte data[DEFAULT_SIZE][DEFAULT_SIZE][4];
+
+ R_CreateDefaultImage();
+
+ // we use a solid white image instead of disabling texturing
+ Com_Memset( data, 255, sizeof( data ) );
+ tr.whiteImage = R_CreateImage("*white", (byte *)data, 8, 8, qfalse, qfalse, GL_REPEAT );
+
+ // with overbright bits active, we need an image which is some fraction of full color,
+ // for default lightmaps, etc
+ for (x=0 ; x<DEFAULT_SIZE ; x++) {
+ for (y=0 ; y<DEFAULT_SIZE ; y++) {
+ data[y][x][0] =
+ data[y][x][1] =
+ data[y][x][2] = tr.identityLightByte;
+ data[y][x][3] = 255;
+ }
+ }
+
+ tr.identityLightImage = R_CreateImage("*identityLight", (byte *)data, 8, 8, qfalse, qfalse, GL_REPEAT );
+
+
+ for(x=0;x<32;x++) {
+ // scratchimage is usually used for cinematic drawing
+ tr.scratchImage[x] = R_CreateImage("*scratch", (byte *)data, DEFAULT_SIZE, DEFAULT_SIZE, qfalse, qtrue, GL_CLAMP );
+ }
+
+ R_CreateDlightImage();
+ R_CreateFogImage();
+}
+
+
+/*
+===============
+R_SetColorMappings
+===============
+*/
+void R_SetColorMappings( void ) {
+ int i, j;
+ float g;
+ int inf;
+ int shift;
+
+ // setup the overbright lighting
+ tr.overbrightBits = r_overBrightBits->integer;
+ if ( !glConfig.deviceSupportsGamma ) {
+ tr.overbrightBits = 0; // need hardware gamma for overbright
+ }
+
+ // never overbright in windowed mode
+ if ( !glConfig.isFullscreen )
+ {
+ tr.overbrightBits = 0;
+ }
+
+ // allow 2 overbright bits in 24 bit, but only 1 in 16 bit
+ if ( glConfig.colorBits > 16 ) {
+ if ( tr.overbrightBits > 2 ) {
+ tr.overbrightBits = 2;
+ }
+ } else {
+ if ( tr.overbrightBits > 1 ) {
+ tr.overbrightBits = 1;
+ }
+ }
+ if ( tr.overbrightBits < 0 ) {
+ tr.overbrightBits = 0;
+ }
+
+ tr.identityLight = 1.0f / ( 1 << tr.overbrightBits );
+ tr.identityLightByte = 255 * tr.identityLight;
+
+
+ if ( r_intensity->value <= 1 ) {
+ ri.Cvar_Set( "r_intensity", "1" );
+ }
+
+ if ( r_gamma->value < 0.5f ) {
+ ri.Cvar_Set( "r_gamma", "0.5" );
+ } else if ( r_gamma->value > 3.0f ) {
+ ri.Cvar_Set( "r_gamma", "3.0" );
+ }
+
+ g = r_gamma->value;
+
+ shift = tr.overbrightBits;
+
+ for ( i = 0; i < 256; i++ ) {
+ if ( g == 1 ) {
+ inf = i;
+ } else {
+ inf = 255 * pow ( i/255.0f, 1.0f / g ) + 0.5f;
+ }
+ inf <<= shift;
+ if (inf < 0) {
+ inf = 0;
+ }
+ if (inf > 255) {
+ inf = 255;
+ }
+ s_gammatable[i] = inf;
+ }
+
+ for (i=0 ; i<256 ; i++) {
+ j = i * r_intensity->value;
+ if (j > 255) {
+ j = 255;
+ }
+ s_intensitytable[i] = j;
+ }
+
+ if ( glConfig.deviceSupportsGamma )
+ {
+ GLimp_SetGamma( s_gammatable, s_gammatable, s_gammatable );
+ }
+}
+
+/*
+===============
+R_InitImages
+===============
+*/
+void R_InitImages( void ) {
+ Com_Memset(hashTable, 0, sizeof(hashTable));
+ // build brightness translation tables
+ R_SetColorMappings();
+
+ // create default texture and white texture
+ R_CreateBuiltinImages();
+}
+
+/*
+===============
+R_DeleteTextures
+===============
+*/
+void R_DeleteTextures( void ) {
+ int i;
+
+ for ( i=0; i<tr.numImages ; i++ ) {
+ qglDeleteTextures( 1, &tr.images[i]->texnum );
+ }
+ Com_Memset( tr.images, 0, sizeof( tr.images ) );
+
+ tr.numImages = 0;
+
+ Com_Memset( glState.currenttextures, 0, sizeof( glState.currenttextures ) );
+ if ( qglBindTexture ) {
+ if ( qglActiveTextureARB ) {
+ GL_SelectTexture( 1 );
+ qglBindTexture( GL_TEXTURE_2D, 0 );
+ GL_SelectTexture( 0 );
+ qglBindTexture( GL_TEXTURE_2D, 0 );
+ } else {
+ qglBindTexture( GL_TEXTURE_2D, 0 );
+ }
+ }
+}
+
+/*
+============================================================================
+
+SKINS
+
+============================================================================
+*/
+
+/*
+==================
+CommaParse
+
+This is unfortunate, but the skin files aren't
+compatable with our normal parsing rules.
+==================
+*/
+static char *CommaParse( char **data_p ) {
+ int c = 0, len;
+ char *data;
+ static char com_token[MAX_TOKEN_CHARS];
+
+ data = *data_p;
+ len = 0;
+ com_token[0] = 0;
+
+ // make sure incoming data is valid
+ if ( !data ) {
+ *data_p = NULL;
+ return com_token;
+ }
+
+ while ( 1 ) {
+ // skip whitespace
+ while( (c = *data) <= ' ') {
+ if( !c ) {
+ break;
+ }
+ data++;
+ }
+
+
+ c = *data;
+
+ // skip double slash comments
+ if ( c == '/' && data[1] == '/' )
+ {
+ while (*data && *data != '\n')
+ data++;
+ }
+ // skip /* */ comments
+ else if ( c=='/' && data[1] == '*' )
+ {
+ while ( *data && ( *data != '*' || data[1] != '/' ) )
+ {
+ data++;
+ }
+ if ( *data )
+ {
+ data += 2;
+ }
+ }
+ else
+ {
+ break;
+ }
+ }
+
+ if ( c == 0 ) {
+ return "";
+ }
+
+ // handle quoted strings
+ if (c == '\"')
+ {
+ data++;
+ while (1)
+ {
+ c = *data++;
+ if (c=='\"' || !c)
+ {
+ com_token[len] = 0;
+ *data_p = ( char * ) data;
+ return com_token;
+ }
+ if (len < MAX_TOKEN_CHARS)
+ {
+ com_token[len] = c;
+ len++;
+ }
+ }
+ }
+
+ // parse a regular word
+ do
+ {
+ if (len < MAX_TOKEN_CHARS)
+ {
+ com_token[len] = c;
+ len++;
+ }
+ data++;
+ c = *data;
+ } while (c>32 && c != ',' );
+
+ if (len == MAX_TOKEN_CHARS)
+ {
+// Com_Printf ("Token exceeded %i chars, discarded.\n", MAX_TOKEN_CHARS);
+ len = 0;
+ }
+ com_token[len] = 0;
+
+ *data_p = ( char * ) data;
+ return com_token;
+}
+
+
+/*
+===============
+RE_RegisterSkin
+
+===============
+*/
+qhandle_t RE_RegisterSkin( const char *name ) {
+ qhandle_t hSkin;
+ skin_t *skin;
+ skinSurface_t *surf;
+ char *text, *text_p;
+ char *token;
+ char surfName[MAX_QPATH];
+
+ if ( !name || !name[0] ) {
+ Com_Printf( "Empty name passed to RE_RegisterSkin\n" );
+ return 0;
+ }
+
+ if ( strlen( name ) >= MAX_QPATH ) {
+ Com_Printf( "Skin name exceeds MAX_QPATH\n" );
+ return 0;
+ }
+
+
+ // see if the skin is already loaded
+ for ( hSkin = 1; hSkin < tr.numSkins ; hSkin++ ) {
+ skin = tr.skins[hSkin];
+ if ( !Q_stricmp( skin->name, name ) ) {
+ if( skin->numSurfaces == 0 ) {
+ return 0; // default skin
+ }
+ return hSkin;
+ }
+ }
+
+ // allocate a new skin
+ if ( tr.numSkins == MAX_SKINS ) {
+ ri.Printf( PRINT_WARNING, "WARNING: RE_RegisterSkin( '%s' ) MAX_SKINS hit\n", name );
+ return 0;
+ }
+ tr.numSkins++;
+ skin = ri.Hunk_Alloc( sizeof( skin_t ), h_low );
+ tr.skins[hSkin] = skin;
+ Q_strncpyz( skin->name, name, sizeof( skin->name ) );
+ skin->numSurfaces = 0;
+
+ // make sure the render thread is stopped
+ R_SyncRenderThread();
+
+ // If not a .skin file, load as a single shader
+ if ( strcmp( name + strlen( name ) - 5, ".skin" ) ) {
+ skin->numSurfaces = 1;
+ skin->surfaces[0] = ri.Hunk_Alloc( sizeof(skin->surfaces[0]), h_low );
+ skin->surfaces[0]->shader = R_FindShader( name, LIGHTMAP_NONE, qtrue );
+ return hSkin;
+ }
+
+ // load and parse the skin file
+ ri.FS_ReadFile( name, (void **)&text );
+ if ( !text ) {
+ return 0;
+ }
+
+ text_p = text;
+ while ( text_p && *text_p ) {
+ // get surface name
+ token = CommaParse( &text_p );
+ Q_strncpyz( surfName, token, sizeof( surfName ) );
+
+ if ( !token[0] ) {
+ break;
+ }
+ // lowercase the surface name so skin compares are faster
+ Q_strlwr( surfName );
+
+ if ( *text_p == ',' ) {
+ text_p++;
+ }
+
+ if ( strstr( token, "tag_" ) ) {
+ continue;
+ }
+
+ // parse the shader name
+ token = CommaParse( &text_p );
+
+ surf = skin->surfaces[ skin->numSurfaces ] = ri.Hunk_Alloc( sizeof( *skin->surfaces[0] ), h_low );
+ Q_strncpyz( surf->name, surfName, sizeof( surf->name ) );
+ surf->shader = R_FindShader( token, LIGHTMAP_NONE, qtrue );
+ skin->numSurfaces++;
+ }
+
+ ri.FS_FreeFile( text );
+
+
+ // never let a skin have 0 shaders
+ if ( skin->numSurfaces == 0 ) {
+ return 0; // use default skin
+ }
+
+ return hSkin;
+}
+
+
+/*
+===============
+R_InitSkins
+===============
+*/
+void R_InitSkins( void ) {
+ skin_t *skin;
+
+ tr.numSkins = 1;
+
+ // make the default skin have all default shaders
+ skin = tr.skins[0] = ri.Hunk_Alloc( sizeof( skin_t ), h_low );
+ Q_strncpyz( skin->name, "<default skin>", sizeof( skin->name ) );
+ skin->numSurfaces = 1;
+ skin->surfaces[0] = ri.Hunk_Alloc( sizeof( *skin->surfaces ), h_low );
+ skin->surfaces[0]->shader = tr.defaultShader;
+}
+
+/*
+===============
+R_GetSkinByHandle
+===============
+*/
+skin_t *R_GetSkinByHandle( qhandle_t hSkin ) {
+ if ( hSkin < 1 || hSkin >= tr.numSkins ) {
+ return tr.skins[0];
+ }
+ return tr.skins[ hSkin ];
+}
+
+/*
+===============
+R_SkinList_f
+===============
+*/
+void R_SkinList_f( void ) {
+ int i, j;
+ skin_t *skin;
+
+ ri.Printf (PRINT_ALL, "------------------\n");
+
+ for ( i = 0 ; i < tr.numSkins ; i++ ) {
+ skin = tr.skins[i];
+
+ ri.Printf( PRINT_ALL, "%3i:%s\n", i, skin->name );
+ for ( j = 0 ; j < skin->numSurfaces ; j++ ) {
+ ri.Printf( PRINT_ALL, " %s = %s\n",
+ skin->surfaces[j]->name, skin->surfaces[j]->shader->name );
+ }
+ }
+ ri.Printf (PRINT_ALL, "------------------\n");
+}
+
diff --git a/code/renderer/tr_init.c b/code/renderer/tr_init.c
new file mode 100755
index 0000000..536ee48
--- /dev/null
+++ b/code/renderer/tr_init.c
@@ -0,0 +1,1217 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// tr_init.c -- functions that are not called every frame
+
+#include "tr_local.h"
+
+glconfig_t glConfig;
+glstate_t glState;
+
+static void GfxInfo_f( void );
+
+cvar_t *r_flareSize;
+cvar_t *r_flareFade;
+
+cvar_t *r_railWidth;
+cvar_t *r_railCoreWidth;
+cvar_t *r_railSegmentLength;
+
+cvar_t *r_ignoreFastPath;
+
+cvar_t *r_verbose;
+cvar_t *r_ignore;
+
+cvar_t *r_displayRefresh;
+
+cvar_t *r_detailTextures;
+
+cvar_t *r_znear;
+
+cvar_t *r_smp;
+cvar_t *r_showSmp;
+cvar_t *r_skipBackEnd;
+
+cvar_t *r_ignorehwgamma;
+cvar_t *r_measureOverdraw;
+
+cvar_t *r_inGameVideo;
+cvar_t *r_fastsky;
+cvar_t *r_drawSun;
+cvar_t *r_dynamiclight;
+cvar_t *r_dlightBacks;
+
+cvar_t *r_lodbias;
+cvar_t *r_lodscale;
+
+cvar_t *r_norefresh;
+cvar_t *r_drawentities;
+cvar_t *r_drawworld;
+cvar_t *r_speeds;
+cvar_t *r_fullbright;
+cvar_t *r_novis;
+cvar_t *r_nocull;
+cvar_t *r_facePlaneCull;
+cvar_t *r_showcluster;
+cvar_t *r_nocurves;
+
+cvar_t *r_allowExtensions;
+
+cvar_t *r_ext_compressed_textures;
+cvar_t *r_ext_gamma_control;
+cvar_t *r_ext_multitexture;
+cvar_t *r_ext_compiled_vertex_array;
+cvar_t *r_ext_texture_env_add;
+
+cvar_t *r_ignoreGLErrors;
+cvar_t *r_logFile;
+
+cvar_t *r_stencilbits;
+cvar_t *r_depthbits;
+cvar_t *r_colorbits;
+cvar_t *r_stereo;
+cvar_t *r_primitives;
+cvar_t *r_texturebits;
+
+cvar_t *r_drawBuffer;
+cvar_t *r_glDriver;
+cvar_t *r_lightmap;
+cvar_t *r_vertexLight;
+cvar_t *r_uiFullScreen;
+cvar_t *r_shadows;
+cvar_t *r_flares;
+cvar_t *r_mode;
+cvar_t *r_nobind;
+cvar_t *r_singleShader;
+cvar_t *r_roundImagesDown;
+cvar_t *r_colorMipLevels;
+cvar_t *r_picmip;
+cvar_t *r_showtris;
+cvar_t *r_showsky;
+cvar_t *r_shownormals;
+cvar_t *r_finish;
+cvar_t *r_clear;
+cvar_t *r_swapInterval;
+cvar_t *r_textureMode;
+cvar_t *r_offsetFactor;
+cvar_t *r_offsetUnits;
+cvar_t *r_gamma;
+cvar_t *r_intensity;
+cvar_t *r_lockpvs;
+cvar_t *r_noportals;
+cvar_t *r_portalOnly;
+
+cvar_t *r_subdivisions;
+cvar_t *r_lodCurveError;
+
+cvar_t *r_fullscreen;
+
+cvar_t *r_customwidth;
+cvar_t *r_customheight;
+cvar_t *r_customaspect;
+
+cvar_t *r_overBrightBits;
+cvar_t *r_mapOverBrightBits;
+
+cvar_t *r_debugSurface;
+cvar_t *r_simpleMipMaps;
+
+cvar_t *r_showImages;
+
+cvar_t *r_ambientScale;
+cvar_t *r_directedScale;
+cvar_t *r_debugLight;
+cvar_t *r_debugSort;
+cvar_t *r_printShaders;
+cvar_t *r_saveFontData;
+
+cvar_t *r_maxpolys;
+int max_polys;
+cvar_t *r_maxpolyverts;
+int max_polyverts;
+
+void ( APIENTRY * qglMultiTexCoord2fARB )( GLenum texture, GLfloat s, GLfloat t );
+void ( APIENTRY * qglActiveTextureARB )( GLenum texture );
+void ( APIENTRY * qglClientActiveTextureARB )( GLenum texture );
+
+void ( APIENTRY * qglLockArraysEXT)( GLint, GLint);
+void ( APIENTRY * qglUnlockArraysEXT) ( void );
+
+static void AssertCvarRange( cvar_t *cv, float minVal, float maxVal, qboolean shouldBeIntegral )
+{
+ if ( shouldBeIntegral )
+ {
+ if ( ( int ) cv->value != cv->integer )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: cvar '%s' must be integral (%f)\n", cv->name, cv->value );
+ ri.Cvar_Set( cv->name, va( "%d", cv->integer ) );
+ }
+ }
+
+ if ( cv->value < minVal )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: cvar '%s' out of range (%f < %f)\n", cv->name, cv->value, minVal );
+ ri.Cvar_Set( cv->name, va( "%f", minVal ) );
+ }
+ else if ( cv->value > maxVal )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: cvar '%s' out of range (%f > %f)\n", cv->name, cv->value, maxVal );
+ ri.Cvar_Set( cv->name, va( "%f", maxVal ) );
+ }
+}
+
+
+/*
+** InitOpenGL
+**
+** This function is responsible for initializing a valid OpenGL subsystem. This
+** is done by calling GLimp_Init (which gives us a working OGL subsystem) then
+** setting variables, checking GL constants, and reporting the gfx system config
+** to the user.
+*/
+static void InitOpenGL( void )
+{
+ char renderer_buffer[1024];
+
+ //
+ // initialize OS specific portions of the renderer
+ //
+ // GLimp_Init directly or indirectly references the following cvars:
+ // - r_fullscreen
+ // - r_glDriver
+ // - r_mode
+ // - r_(color|depth|stencil)bits
+ // - r_ignorehwgamma
+ // - r_gamma
+ //
+
+ if ( glConfig.vidWidth == 0 )
+ {
+ GLint temp;
+
+ GLimp_Init();
+
+ strcpy( renderer_buffer, glConfig.renderer_string );
+ Q_strlwr( renderer_buffer );
+
+ // OpenGL driver constants
+ qglGetIntegerv( GL_MAX_TEXTURE_SIZE, &temp );
+ glConfig.maxTextureSize = temp;
+
+ // stubbed or broken drivers may have reported 0...
+ if ( glConfig.maxTextureSize <= 0 )
+ {
+ glConfig.maxTextureSize = 0;
+ }
+ }
+
+ // init command buffers and SMP
+ R_InitCommandBuffers();
+
+ // print info
+ GfxInfo_f();
+
+ // set default state
+ GL_SetDefaultState();
+}
+
+/*
+==================
+GL_CheckErrors
+==================
+*/
+void GL_CheckErrors( void ) {
+ int err;
+ char s[64];
+
+ err = qglGetError();
+ if ( err == GL_NO_ERROR ) {
+ return;
+ }
+ if ( r_ignoreGLErrors->integer ) {
+ return;
+ }
+ switch( err ) {
+ case GL_INVALID_ENUM:
+ strcpy( s, "GL_INVALID_ENUM" );
+ break;
+ case GL_INVALID_VALUE:
+ strcpy( s, "GL_INVALID_VALUE" );
+ break;
+ case GL_INVALID_OPERATION:
+ strcpy( s, "GL_INVALID_OPERATION" );
+ break;
+ case GL_STACK_OVERFLOW:
+ strcpy( s, "GL_STACK_OVERFLOW" );
+ break;
+ case GL_STACK_UNDERFLOW:
+ strcpy( s, "GL_STACK_UNDERFLOW" );
+ break;
+ case GL_OUT_OF_MEMORY:
+ strcpy( s, "GL_OUT_OF_MEMORY" );
+ break;
+ default:
+ Com_sprintf( s, sizeof(s), "%i", err);
+ break;
+ }
+
+ ri.Error( ERR_FATAL, "GL_CheckErrors: %s", s );
+}
+
+
+/*
+** R_GetModeInfo
+*/
+typedef struct vidmode_s
+{
+ const char *description;
+ int width, height;
+ float pixelAspect; // pixel width / height
+} vidmode_t;
+
+vidmode_t r_vidModes[] =
+{
+ { "Mode 0: 320x240", 320, 240, 1 },
+ { "Mode 1: 400x300", 400, 300, 1 },
+ { "Mode 2: 512x384", 512, 384, 1 },
+ { "Mode 3: 640x480", 640, 480, 1 },
+ { "Mode 4: 800x600", 800, 600, 1 },
+ { "Mode 5: 960x720", 960, 720, 1 },
+ { "Mode 6: 1024x768", 1024, 768, 1 },
+ { "Mode 7: 1152x864", 1152, 864, 1 },
+ { "Mode 8: 1280x1024", 1280, 1024, 1 },
+ { "Mode 9: 1600x1200", 1600, 1200, 1 },
+ { "Mode 10: 2048x1536", 2048, 1536, 1 },
+ { "Mode 11: 856x480 (wide)",856, 480, 1 }
+};
+static int s_numVidModes = ( sizeof( r_vidModes ) / sizeof( r_vidModes[0] ) );
+
+qboolean R_GetModeInfo( int *width, int *height, float *windowAspect, int mode ) {
+ vidmode_t *vm;
+
+ if ( mode < -1 ) {
+ return qfalse;
+ }
+ if ( mode >= s_numVidModes ) {
+ return qfalse;
+ }
+
+ if ( mode == -1 ) {
+ *width = r_customwidth->integer;
+ *height = r_customheight->integer;
+ *windowAspect = r_customaspect->value;
+ return qtrue;
+ }
+
+ vm = &r_vidModes[mode];
+
+ *width = vm->width;
+ *height = vm->height;
+ *windowAspect = (float)vm->width / ( vm->height * vm->pixelAspect );
+
+ return qtrue;
+}
+
+/*
+** R_ModeList_f
+*/
+static void R_ModeList_f( void )
+{
+ int i;
+
+ ri.Printf( PRINT_ALL, "\n" );
+ for ( i = 0; i < s_numVidModes; i++ )
+ {
+ ri.Printf( PRINT_ALL, "%s\n", r_vidModes[i].description );
+ }
+ ri.Printf( PRINT_ALL, "\n" );
+}
+
+
+/*
+==============================================================================
+
+ SCREEN SHOTS
+
+NOTE TTimo
+some thoughts about the screenshots system:
+screenshots get written in fs_homepath + fs_gamedir
+vanilla q3 .. baseq3/screenshots/ *.tga
+team arena .. missionpack/screenshots/ *.tga
+
+two commands: "screenshot" and "screenshotJPEG"
+we use statics to store a count and start writing the first screenshot/screenshot????.tga (.jpg) available
+(with FS_FileExists / FS_FOpenFileWrite calls)
+FIXME: the statics don't get a reinit between fs_game changes
+
+==============================================================================
+*/
+
+/*
+==================
+RB_TakeScreenshot
+==================
+*/
+void RB_TakeScreenshot( int x, int y, int width, int height, char *fileName ) {
+ byte *buffer;
+ int i, c, temp;
+
+ buffer = ri.Hunk_AllocateTempMemory(glConfig.vidWidth*glConfig.vidHeight*3+18);
+
+ Com_Memset (buffer, 0, 18);
+ buffer[2] = 2; // uncompressed type
+ buffer[12] = width & 255;
+ buffer[13] = width >> 8;
+ buffer[14] = height & 255;
+ buffer[15] = height >> 8;
+ buffer[16] = 24; // pixel size
+
+ qglReadPixels( x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer+18 );
+
+ // swap rgb to bgr
+ c = 18 + width * height * 3;
+ for (i=18 ; i<c ; i+=3) {
+ temp = buffer[i];
+ buffer[i] = buffer[i+2];
+ buffer[i+2] = temp;
+ }
+
+ // gamma correct
+ if ( ( tr.overbrightBits > 0 ) && glConfig.deviceSupportsGamma ) {
+ R_GammaCorrect( buffer + 18, glConfig.vidWidth * glConfig.vidHeight * 3 );
+ }
+
+ ri.FS_WriteFile( fileName, buffer, c );
+
+ ri.Hunk_FreeTempMemory( buffer );
+}
+
+/*
+==================
+RB_TakeScreenshotJPEG
+==================
+*/
+void RB_TakeScreenshotJPEG( int x, int y, int width, int height, char *fileName ) {
+ byte *buffer;
+
+ buffer = ri.Hunk_AllocateTempMemory(glConfig.vidWidth*glConfig.vidHeight*4);
+
+ qglReadPixels( x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer );
+
+ // gamma correct
+ if ( ( tr.overbrightBits > 0 ) && glConfig.deviceSupportsGamma ) {
+ R_GammaCorrect( buffer, glConfig.vidWidth * glConfig.vidHeight * 4 );
+ }
+
+ ri.FS_WriteFile( fileName, buffer, 1 ); // create path
+ SaveJPG( fileName, 95, glConfig.vidWidth, glConfig.vidHeight, buffer);
+
+ ri.Hunk_FreeTempMemory( buffer );
+}
+
+/*
+==================
+RB_TakeScreenshotCmd
+==================
+*/
+const void *RB_TakeScreenshotCmd( const void *data ) {
+ const screenshotCommand_t *cmd;
+
+ cmd = (const screenshotCommand_t *)data;
+
+ if (cmd->jpeg)
+ RB_TakeScreenshotJPEG( cmd->x, cmd->y, cmd->width, cmd->height, cmd->fileName);
+ else
+ RB_TakeScreenshot( cmd->x, cmd->y, cmd->width, cmd->height, cmd->fileName);
+
+ return (const void *)(cmd + 1);
+}
+
+/*
+==================
+R_TakeScreenshot
+==================
+*/
+void R_TakeScreenshot( int x, int y, int width, int height, char *name, qboolean jpeg ) {
+ static char fileName[MAX_OSPATH]; // bad things if two screenshots per frame?
+ screenshotCommand_t *cmd;
+
+ cmd = R_GetCommandBuffer( sizeof( *cmd ) );
+ if ( !cmd ) {
+ return;
+ }
+ cmd->commandId = RC_SCREENSHOT;
+
+ cmd->x = x;
+ cmd->y = y;
+ cmd->width = width;
+ cmd->height = height;
+ Q_strncpyz( fileName, name, sizeof(fileName) );
+ cmd->fileName = fileName;
+ cmd->jpeg = jpeg;
+}
+
+/*
+==================
+R_ScreenshotFilename
+==================
+*/
+void R_ScreenshotFilename( int lastNumber, char *fileName ) {
+ int a,b,c,d;
+
+ if ( lastNumber < 0 || lastNumber > 9999 ) {
+ Com_sprintf( fileName, MAX_OSPATH, "screenshots/shot9999.tga" );
+ return;
+ }
+
+ a = lastNumber / 1000;
+ lastNumber -= a*1000;
+ b = lastNumber / 100;
+ lastNumber -= b*100;
+ c = lastNumber / 10;
+ lastNumber -= c*10;
+ d = lastNumber;
+
+ Com_sprintf( fileName, MAX_OSPATH, "screenshots/shot%i%i%i%i.tga"
+ , a, b, c, d );
+}
+
+/*
+==================
+R_ScreenshotFilename
+==================
+*/
+void R_ScreenshotFilenameJPEG( int lastNumber, char *fileName ) {
+ int a,b,c,d;
+
+ if ( lastNumber < 0 || lastNumber > 9999 ) {
+ Com_sprintf( fileName, MAX_OSPATH, "screenshots/shot9999.jpg" );
+ return;
+ }
+
+ a = lastNumber / 1000;
+ lastNumber -= a*1000;
+ b = lastNumber / 100;
+ lastNumber -= b*100;
+ c = lastNumber / 10;
+ lastNumber -= c*10;
+ d = lastNumber;
+
+ Com_sprintf( fileName, MAX_OSPATH, "screenshots/shot%i%i%i%i.jpg"
+ , a, b, c, d );
+}
+
+/*
+====================
+R_LevelShot
+
+levelshots are specialized 128*128 thumbnails for
+the menu system, sampled down from full screen distorted images
+====================
+*/
+void R_LevelShot( void ) {
+ char checkname[MAX_OSPATH];
+ byte *buffer;
+ byte *source;
+ byte *src, *dst;
+ int x, y;
+ int r, g, b;
+ float xScale, yScale;
+ int xx, yy;
+
+ sprintf( checkname, "levelshots/%s.tga", tr.world->baseName );
+
+ source = ri.Hunk_AllocateTempMemory( glConfig.vidWidth * glConfig.vidHeight * 3 );
+
+ buffer = ri.Hunk_AllocateTempMemory( 128 * 128*3 + 18);
+ Com_Memset (buffer, 0, 18);
+ buffer[2] = 2; // uncompressed type
+ buffer[12] = 128;
+ buffer[14] = 128;
+ buffer[16] = 24; // pixel size
+
+ qglReadPixels( 0, 0, glConfig.vidWidth, glConfig.vidHeight, GL_RGB, GL_UNSIGNED_BYTE, source );
+
+ // resample from source
+ xScale = glConfig.vidWidth / 512.0f;
+ yScale = glConfig.vidHeight / 384.0f;
+ for ( y = 0 ; y < 128 ; y++ ) {
+ for ( x = 0 ; x < 128 ; x++ ) {
+ r = g = b = 0;
+ for ( yy = 0 ; yy < 3 ; yy++ ) {
+ for ( xx = 0 ; xx < 4 ; xx++ ) {
+ src = source + 3 * ( glConfig.vidWidth * (int)( (y*3+yy)*yScale ) + (int)( (x*4+xx)*xScale ) );
+ r += src[0];
+ g += src[1];
+ b += src[2];
+ }
+ }
+ dst = buffer + 18 + 3 * ( y * 128 + x );
+ dst[0] = b / 12;
+ dst[1] = g / 12;
+ dst[2] = r / 12;
+ }
+ }
+
+ // gamma correct
+ if ( ( tr.overbrightBits > 0 ) && glConfig.deviceSupportsGamma ) {
+ R_GammaCorrect( buffer + 18, 128 * 128 * 3 );
+ }
+
+ ri.FS_WriteFile( checkname, buffer, 128 * 128*3 + 18 );
+
+ ri.Hunk_FreeTempMemory( buffer );
+ ri.Hunk_FreeTempMemory( source );
+
+ ri.Printf( PRINT_ALL, "Wrote %s\n", checkname );
+}
+
+/*
+==================
+R_ScreenShot_f
+
+screenshot
+screenshot [silent]
+screenshot [levelshot]
+screenshot [filename]
+
+Doesn't print the pacifier message if there is a second arg
+==================
+*/
+void R_ScreenShot_f (void) {
+ char checkname[MAX_OSPATH];
+ static int lastNumber = -1;
+ qboolean silent;
+
+ if ( !strcmp( ri.Cmd_Argv(1), "levelshot" ) ) {
+ R_LevelShot();
+ return;
+ }
+
+ if ( !strcmp( ri.Cmd_Argv(1), "silent" ) ) {
+ silent = qtrue;
+ } else {
+ silent = qfalse;
+ }
+
+ if ( ri.Cmd_Argc() == 2 && !silent ) {
+ // explicit filename
+ Com_sprintf( checkname, MAX_OSPATH, "screenshots/%s.tga", ri.Cmd_Argv( 1 ) );
+ } else {
+ // scan for a free filename
+
+ // if we have saved a previous screenshot, don't scan
+ // again, because recording demo avis can involve
+ // thousands of shots
+ if ( lastNumber == -1 ) {
+ lastNumber = 0;
+ }
+ // scan for a free number
+ for ( ; lastNumber <= 9999 ; lastNumber++ ) {
+ R_ScreenshotFilename( lastNumber, checkname );
+
+ if (!ri.FS_FileExists( checkname ))
+ {
+ break; // file doesn't exist
+ }
+ }
+
+ if ( lastNumber >= 9999 ) {
+ ri.Printf (PRINT_ALL, "ScreenShot: Couldn't create a file\n");
+ return;
+ }
+
+ lastNumber++;
+ }
+
+ R_TakeScreenshot( 0, 0, glConfig.vidWidth, glConfig.vidHeight, checkname, qfalse );
+
+ if ( !silent ) {
+ ri.Printf (PRINT_ALL, "Wrote %s\n", checkname);
+ }
+}
+
+void R_ScreenShotJPEG_f (void) {
+ char checkname[MAX_OSPATH];
+ static int lastNumber = -1;
+ qboolean silent;
+
+ if ( !strcmp( ri.Cmd_Argv(1), "levelshot" ) ) {
+ R_LevelShot();
+ return;
+ }
+
+ if ( !strcmp( ri.Cmd_Argv(1), "silent" ) ) {
+ silent = qtrue;
+ } else {
+ silent = qfalse;
+ }
+
+ if ( ri.Cmd_Argc() == 2 && !silent ) {
+ // explicit filename
+ Com_sprintf( checkname, MAX_OSPATH, "screenshots/%s.jpg", ri.Cmd_Argv( 1 ) );
+ } else {
+ // scan for a free filename
+
+ // if we have saved a previous screenshot, don't scan
+ // again, because recording demo avis can involve
+ // thousands of shots
+ if ( lastNumber == -1 ) {
+ lastNumber = 0;
+ }
+ // scan for a free number
+ for ( ; lastNumber <= 9999 ; lastNumber++ ) {
+ R_ScreenshotFilenameJPEG( lastNumber, checkname );
+
+ if (!ri.FS_FileExists( checkname ))
+ {
+ break; // file doesn't exist
+ }
+ }
+
+ if ( lastNumber == 10000 ) {
+ ri.Printf (PRINT_ALL, "ScreenShot: Couldn't create a file\n");
+ return;
+ }
+
+ lastNumber++;
+ }
+
+ R_TakeScreenshot( 0, 0, glConfig.vidWidth, glConfig.vidHeight, checkname, qtrue );
+
+ if ( !silent ) {
+ ri.Printf (PRINT_ALL, "Wrote %s\n", checkname);
+ }
+}
+
+//============================================================================
+
+/*
+** GL_SetDefaultState
+*/
+void GL_SetDefaultState( void )
+{
+ qglClearDepth( 1.0f );
+
+ qglCullFace(GL_FRONT);
+
+ qglColor4f (1,1,1,1);
+
+ // initialize downstream texture unit if we're running
+ // in a multitexture environment
+ if ( qglActiveTextureARB ) {
+ GL_SelectTexture( 1 );
+ GL_TextureMode( r_textureMode->string );
+ GL_TexEnv( GL_MODULATE );
+ qglDisable( GL_TEXTURE_2D );
+ GL_SelectTexture( 0 );
+ }
+
+ qglEnable(GL_TEXTURE_2D);
+ GL_TextureMode( r_textureMode->string );
+ GL_TexEnv( GL_MODULATE );
+
+ qglShadeModel( GL_SMOOTH );
+ qglDepthFunc( GL_LEQUAL );
+
+ // the vertex array is always enabled, but the color and texture
+ // arrays are enabled and disabled around the compiled vertex array call
+ qglEnableClientState (GL_VERTEX_ARRAY);
+
+ //
+ // make sure our GL state vector is set correctly
+ //
+ glState.glStateBits = GLS_DEPTHTEST_DISABLE | GLS_DEPTHMASK_TRUE;
+
+ qglPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
+ qglDepthMask( GL_TRUE );
+ qglDisable( GL_DEPTH_TEST );
+ qglEnable( GL_SCISSOR_TEST );
+ qglDisable( GL_CULL_FACE );
+ qglDisable( GL_BLEND );
+}
+
+
+/*
+================
+GfxInfo_f
+================
+*/
+void GfxInfo_f( void )
+{
+ cvar_t *sys_cpustring = ri.Cvar_Get( "sys_cpustring", "", 0 );
+ const char *enablestrings[] =
+ {
+ "disabled",
+ "enabled"
+ };
+ const char *fsstrings[] =
+ {
+ "windowed",
+ "fullscreen"
+ };
+
+ ri.Printf( PRINT_ALL, "\nGL_VENDOR: %s\n", glConfig.vendor_string );
+ ri.Printf( PRINT_ALL, "GL_RENDERER: %s\n", glConfig.renderer_string );
+ ri.Printf( PRINT_ALL, "GL_VERSION: %s\n", glConfig.version_string );
+ ri.Printf( PRINT_ALL, "GL_EXTENSIONS: %s\n", glConfig.extensions_string );
+ ri.Printf( PRINT_ALL, "GL_MAX_TEXTURE_SIZE: %d\n", glConfig.maxTextureSize );
+ ri.Printf( PRINT_ALL, "GL_MAX_ACTIVE_TEXTURES_ARB: %d\n", glConfig.maxActiveTextures );
+ ri.Printf( PRINT_ALL, "\nPIXELFORMAT: color(%d-bits) Z(%d-bit) stencil(%d-bits)\n", glConfig.colorBits, glConfig.depthBits, glConfig.stencilBits );
+ ri.Printf( PRINT_ALL, "MODE: %d, %d x %d %s hz:", r_mode->integer, glConfig.vidWidth, glConfig.vidHeight, fsstrings[r_fullscreen->integer == 1] );
+ if ( glConfig.displayFrequency )
+ {
+ ri.Printf( PRINT_ALL, "%d\n", glConfig.displayFrequency );
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "N/A\n" );
+ }
+ if ( glConfig.deviceSupportsGamma )
+ {
+ ri.Printf( PRINT_ALL, "GAMMA: hardware w/ %d overbright bits\n", tr.overbrightBits );
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "GAMMA: software w/ %d overbright bits\n", tr.overbrightBits );
+ }
+ ri.Printf( PRINT_ALL, "CPU: %s\n", sys_cpustring->string );
+
+ // rendering primitives
+ {
+ int primitives;
+
+ // default is to use triangles if compiled vertex arrays are present
+ ri.Printf( PRINT_ALL, "rendering primitives: " );
+ primitives = r_primitives->integer;
+ if ( primitives == 0 ) {
+ if ( qglLockArraysEXT ) {
+ primitives = 2;
+ } else {
+ primitives = 1;
+ }
+ }
+ if ( primitives == -1 ) {
+ ri.Printf( PRINT_ALL, "none\n" );
+ } else if ( primitives == 2 ) {
+ ri.Printf( PRINT_ALL, "single glDrawElements\n" );
+ } else if ( primitives == 1 ) {
+ ri.Printf( PRINT_ALL, "multiple glArrayElement\n" );
+ } else if ( primitives == 3 ) {
+ ri.Printf( PRINT_ALL, "multiple glColor4ubv + glTexCoord2fv + glVertex3fv\n" );
+ }
+ }
+
+ ri.Printf( PRINT_ALL, "texturemode: %s\n", r_textureMode->string );
+ ri.Printf( PRINT_ALL, "picmip: %d\n", r_picmip->integer );
+ ri.Printf( PRINT_ALL, "texture bits: %d\n", r_texturebits->integer );
+ ri.Printf( PRINT_ALL, "multitexture: %s\n", enablestrings[qglActiveTextureARB != 0] );
+ ri.Printf( PRINT_ALL, "compiled vertex arrays: %s\n", enablestrings[qglLockArraysEXT != 0 ] );
+ ri.Printf( PRINT_ALL, "texenv add: %s\n", enablestrings[glConfig.textureEnvAddAvailable != 0] );
+ ri.Printf( PRINT_ALL, "compressed textures: %s\n", enablestrings[glConfig.textureCompression!=TC_NONE] );
+ if ( r_vertexLight->integer || glConfig.hardwareType == GLHW_PERMEDIA2 )
+ {
+ ri.Printf( PRINT_ALL, "HACK: using vertex lightmap approximation\n" );
+ }
+ if ( glConfig.hardwareType == GLHW_RAGEPRO )
+ {
+ ri.Printf( PRINT_ALL, "HACK: ragePro approximations\n" );
+ }
+ if ( glConfig.hardwareType == GLHW_RIVA128 )
+ {
+ ri.Printf( PRINT_ALL, "HACK: riva128 approximations\n" );
+ }
+ if ( glConfig.smpActive ) {
+ ri.Printf( PRINT_ALL, "Using dual processor acceleration\n" );
+ }
+ if ( r_finish->integer ) {
+ ri.Printf( PRINT_ALL, "Forcing glFinish\n" );
+ }
+}
+
+/*
+===============
+R_Register
+===============
+*/
+void R_Register( void )
+{
+ //
+ // latched and archived variables
+ //
+ r_glDriver = ri.Cvar_Get( "r_glDriver", OPENGL_DRIVER_NAME, CVAR_ARCHIVE | CVAR_LATCH );
+ r_allowExtensions = ri.Cvar_Get( "r_allowExtensions", "1", CVAR_ARCHIVE | CVAR_LATCH );
+ r_ext_compressed_textures = ri.Cvar_Get( "r_ext_compressed_textures", "0", CVAR_ARCHIVE | CVAR_LATCH );
+ r_ext_gamma_control = ri.Cvar_Get( "r_ext_gamma_control", "1", CVAR_ARCHIVE | CVAR_LATCH );
+ r_ext_multitexture = ri.Cvar_Get( "r_ext_multitexture", "1", CVAR_ARCHIVE | CVAR_LATCH );
+ r_ext_compiled_vertex_array = ri.Cvar_Get( "r_ext_compiled_vertex_array", "1", CVAR_ARCHIVE | CVAR_LATCH);
+#ifdef __linux__ // broken on linux
+ r_ext_texture_env_add = ri.Cvar_Get( "r_ext_texture_env_add", "0", CVAR_ARCHIVE | CVAR_LATCH);
+#else
+ r_ext_texture_env_add = ri.Cvar_Get( "r_ext_texture_env_add", "1", CVAR_ARCHIVE | CVAR_LATCH);
+#endif
+
+ r_picmip = ri.Cvar_Get ("r_picmip", "1", CVAR_ARCHIVE | CVAR_LATCH );
+ r_roundImagesDown = ri.Cvar_Get ("r_roundImagesDown", "1", CVAR_ARCHIVE | CVAR_LATCH );
+ r_colorMipLevels = ri.Cvar_Get ("r_colorMipLevels", "0", CVAR_LATCH );
+ AssertCvarRange( r_picmip, 0, 16, qtrue );
+ r_detailTextures = ri.Cvar_Get( "r_detailtextures", "1", CVAR_ARCHIVE | CVAR_LATCH );
+ r_texturebits = ri.Cvar_Get( "r_texturebits", "0", CVAR_ARCHIVE | CVAR_LATCH );
+ r_colorbits = ri.Cvar_Get( "r_colorbits", "0", CVAR_ARCHIVE | CVAR_LATCH );
+ r_stereo = ri.Cvar_Get( "r_stereo", "0", CVAR_ARCHIVE | CVAR_LATCH );
+#ifdef __linux__
+ r_stencilbits = ri.Cvar_Get( "r_stencilbits", "0", CVAR_ARCHIVE | CVAR_LATCH );
+#else
+ r_stencilbits = ri.Cvar_Get( "r_stencilbits", "8", CVAR_ARCHIVE | CVAR_LATCH );
+#endif
+ r_depthbits = ri.Cvar_Get( "r_depthbits", "0", CVAR_ARCHIVE | CVAR_LATCH );
+ r_overBrightBits = ri.Cvar_Get ("r_overBrightBits", "1", CVAR_ARCHIVE | CVAR_LATCH );
+ r_ignorehwgamma = ri.Cvar_Get( "r_ignorehwgamma", "0", CVAR_ARCHIVE | CVAR_LATCH);
+ r_mode = ri.Cvar_Get( "r_mode", "3", CVAR_ARCHIVE | CVAR_LATCH );
+ r_fullscreen = ri.Cvar_Get( "r_fullscreen", "1", CVAR_ARCHIVE | CVAR_LATCH );
+ r_customwidth = ri.Cvar_Get( "r_customwidth", "1600", CVAR_ARCHIVE | CVAR_LATCH );
+ r_customheight = ri.Cvar_Get( "r_customheight", "1024", CVAR_ARCHIVE | CVAR_LATCH );
+ r_customaspect = ri.Cvar_Get( "r_customaspect", "1", CVAR_ARCHIVE | CVAR_LATCH );
+ r_simpleMipMaps = ri.Cvar_Get( "r_simpleMipMaps", "1", CVAR_ARCHIVE | CVAR_LATCH );
+ r_vertexLight = ri.Cvar_Get( "r_vertexLight", "0", CVAR_ARCHIVE | CVAR_LATCH );
+ r_uiFullScreen = ri.Cvar_Get( "r_uifullscreen", "0", 0);
+ r_subdivisions = ri.Cvar_Get ("r_subdivisions", "4", CVAR_ARCHIVE | CVAR_LATCH);
+#if (defined(MACOS_X) || defined(__linux__)) && defined(SMP)
+ // Default to using SMP on Mac OS X or Linux if we have multiple processors
+ r_smp = ri.Cvar_Get( "r_smp", Sys_ProcessorCount() > 1 ? "1" : "0", CVAR_ARCHIVE | CVAR_LATCH);
+#else
+ r_smp = ri.Cvar_Get( "r_smp", "0", CVAR_ARCHIVE | CVAR_LATCH);
+#endif
+ r_ignoreFastPath = ri.Cvar_Get( "r_ignoreFastPath", "1", CVAR_ARCHIVE | CVAR_LATCH );
+
+ //
+ // temporary latched variables that can only change over a restart
+ //
+ r_displayRefresh = ri.Cvar_Get( "r_displayRefresh", "0", CVAR_LATCH );
+ AssertCvarRange( r_displayRefresh, 0, 200, qtrue );
+ r_fullbright = ri.Cvar_Get ("r_fullbright", "0", CVAR_LATCH|CVAR_CHEAT );
+ r_mapOverBrightBits = ri.Cvar_Get ("r_mapOverBrightBits", "2", CVAR_LATCH );
+ r_intensity = ri.Cvar_Get ("r_intensity", "1", CVAR_LATCH );
+ r_singleShader = ri.Cvar_Get ("r_singleShader", "0", CVAR_CHEAT | CVAR_LATCH );
+
+ //
+ // archived variables that can change at any time
+ //
+ r_lodCurveError = ri.Cvar_Get( "r_lodCurveError", "250", CVAR_ARCHIVE|CVAR_CHEAT );
+ r_lodbias = ri.Cvar_Get( "r_lodbias", "0", CVAR_ARCHIVE );
+ r_flares = ri.Cvar_Get ("r_flares", "0", CVAR_ARCHIVE );
+ r_znear = ri.Cvar_Get( "r_znear", "4", CVAR_CHEAT );
+ AssertCvarRange( r_znear, 0.001f, 200, qtrue );
+ r_ignoreGLErrors = ri.Cvar_Get( "r_ignoreGLErrors", "1", CVAR_ARCHIVE );
+ r_fastsky = ri.Cvar_Get( "r_fastsky", "0", CVAR_ARCHIVE );
+ r_inGameVideo = ri.Cvar_Get( "r_inGameVideo", "1", CVAR_ARCHIVE );
+ r_drawSun = ri.Cvar_Get( "r_drawSun", "0", CVAR_ARCHIVE );
+ r_dynamiclight = ri.Cvar_Get( "r_dynamiclight", "1", CVAR_ARCHIVE );
+ r_dlightBacks = ri.Cvar_Get( "r_dlightBacks", "1", CVAR_ARCHIVE );
+ r_finish = ri.Cvar_Get ("r_finish", "0", CVAR_ARCHIVE);
+ r_textureMode = ri.Cvar_Get( "r_textureMode", "GL_LINEAR_MIPMAP_NEAREST", CVAR_ARCHIVE );
+ r_swapInterval = ri.Cvar_Get( "r_swapInterval", "0", CVAR_ARCHIVE );
+#ifdef __MACOS__
+ r_gamma = ri.Cvar_Get( "r_gamma", "1.2", CVAR_ARCHIVE );
+#else
+ r_gamma = ri.Cvar_Get( "r_gamma", "1", CVAR_ARCHIVE );
+#endif
+ r_facePlaneCull = ri.Cvar_Get ("r_facePlaneCull", "1", CVAR_ARCHIVE );
+
+ r_railWidth = ri.Cvar_Get( "r_railWidth", "16", CVAR_ARCHIVE );
+ r_railCoreWidth = ri.Cvar_Get( "r_railCoreWidth", "6", CVAR_ARCHIVE );
+ r_railSegmentLength = ri.Cvar_Get( "r_railSegmentLength", "32", CVAR_ARCHIVE );
+
+ r_primitives = ri.Cvar_Get( "r_primitives", "0", CVAR_ARCHIVE );
+
+ r_ambientScale = ri.Cvar_Get( "r_ambientScale", "0.6", CVAR_CHEAT );
+ r_directedScale = ri.Cvar_Get( "r_directedScale", "1", CVAR_CHEAT );
+
+ //
+ // temporary variables that can change at any time
+ //
+ r_showImages = ri.Cvar_Get( "r_showImages", "0", CVAR_TEMP );
+
+ r_debugLight = ri.Cvar_Get( "r_debuglight", "0", CVAR_TEMP );
+ r_debugSort = ri.Cvar_Get( "r_debugSort", "0", CVAR_CHEAT );
+ r_printShaders = ri.Cvar_Get( "r_printShaders", "0", 0 );
+ r_saveFontData = ri.Cvar_Get( "r_saveFontData", "0", 0 );
+
+ r_nocurves = ri.Cvar_Get ("r_nocurves", "0", CVAR_CHEAT );
+ r_drawworld = ri.Cvar_Get ("r_drawworld", "1", CVAR_CHEAT );
+ r_lightmap = ri.Cvar_Get ("r_lightmap", "0", 0 );
+ r_portalOnly = ri.Cvar_Get ("r_portalOnly", "0", CVAR_CHEAT );
+
+ r_flareSize = ri.Cvar_Get ("r_flareSize", "40", CVAR_CHEAT);
+ r_flareFade = ri.Cvar_Get ("r_flareFade", "7", CVAR_CHEAT);
+
+ r_showSmp = ri.Cvar_Get ("r_showSmp", "0", CVAR_CHEAT);
+ r_skipBackEnd = ri.Cvar_Get ("r_skipBackEnd", "0", CVAR_CHEAT);
+
+ r_measureOverdraw = ri.Cvar_Get( "r_measureOverdraw", "0", CVAR_CHEAT );
+ r_lodscale = ri.Cvar_Get( "r_lodscale", "5", CVAR_CHEAT );
+ r_norefresh = ri.Cvar_Get ("r_norefresh", "0", CVAR_CHEAT);
+ r_drawentities = ri.Cvar_Get ("r_drawentities", "1", CVAR_CHEAT );
+ r_ignore = ri.Cvar_Get( "r_ignore", "1", CVAR_CHEAT );
+ r_nocull = ri.Cvar_Get ("r_nocull", "0", CVAR_CHEAT);
+ r_novis = ri.Cvar_Get ("r_novis", "0", CVAR_CHEAT);
+ r_showcluster = ri.Cvar_Get ("r_showcluster", "0", CVAR_CHEAT);
+ r_speeds = ri.Cvar_Get ("r_speeds", "0", CVAR_CHEAT);
+ r_verbose = ri.Cvar_Get( "r_verbose", "0", CVAR_CHEAT );
+ r_logFile = ri.Cvar_Get( "r_logFile", "0", CVAR_CHEAT );
+ r_debugSurface = ri.Cvar_Get ("r_debugSurface", "0", CVAR_CHEAT);
+ r_nobind = ri.Cvar_Get ("r_nobind", "0", CVAR_CHEAT);
+ r_showtris = ri.Cvar_Get ("r_showtris", "0", CVAR_CHEAT);
+ r_showsky = ri.Cvar_Get ("r_showsky", "0", CVAR_CHEAT);
+ r_shownormals = ri.Cvar_Get ("r_shownormals", "0", CVAR_CHEAT);
+ r_clear = ri.Cvar_Get ("r_clear", "0", CVAR_CHEAT);
+ r_offsetFactor = ri.Cvar_Get( "r_offsetfactor", "-1", CVAR_CHEAT );
+ r_offsetUnits = ri.Cvar_Get( "r_offsetunits", "-2", CVAR_CHEAT );
+ r_drawBuffer = ri.Cvar_Get( "r_drawBuffer", "GL_BACK", CVAR_CHEAT );
+ r_lockpvs = ri.Cvar_Get ("r_lockpvs", "0", CVAR_CHEAT);
+ r_noportals = ri.Cvar_Get ("r_noportals", "0", CVAR_CHEAT);
+ r_shadows = ri.Cvar_Get( "cg_shadows", "1", 0 );
+
+ r_maxpolys = ri.Cvar_Get( "r_maxpolys", va("%d", MAX_POLYS), 0);
+ r_maxpolyverts = ri.Cvar_Get( "r_maxpolyverts", va("%d", MAX_POLYVERTS), 0);
+
+ // make sure all the commands added here are also
+ // removed in R_Shutdown
+ ri.Cmd_AddCommand( "imagelist", R_ImageList_f );
+ ri.Cmd_AddCommand( "shaderlist", R_ShaderList_f );
+ ri.Cmd_AddCommand( "skinlist", R_SkinList_f );
+ ri.Cmd_AddCommand( "modellist", R_Modellist_f );
+ ri.Cmd_AddCommand( "modelist", R_ModeList_f );
+ ri.Cmd_AddCommand( "screenshot", R_ScreenShot_f );
+ ri.Cmd_AddCommand( "screenshotJPEG", R_ScreenShotJPEG_f );
+ ri.Cmd_AddCommand( "gfxinfo", GfxInfo_f );
+}
+
+/*
+===============
+R_Init
+===============
+*/
+void R_Init( void ) {
+ int err;
+ int i;
+ byte *ptr;
+
+ ri.Printf( PRINT_ALL, "----- R_Init -----\n" );
+
+ // clear all our internal state
+ Com_Memset( &tr, 0, sizeof( tr ) );
+ Com_Memset( &backEnd, 0, sizeof( backEnd ) );
+ Com_Memset( &tess, 0, sizeof( tess ) );
+
+// Swap_Init();
+
+ if ( (int)tess.xyz & 15 ) {
+ Com_Printf( "WARNING: tess.xyz not 16 byte aligned\n" );
+ }
+ Com_Memset( tess.constantColor255, 255, sizeof( tess.constantColor255 ) );
+
+ //
+ // init function tables
+ //
+ for ( i = 0; i < FUNCTABLE_SIZE; i++ )
+ {
+ tr.sinTable[i] = sin( DEG2RAD( i * 360.0f / ( ( float ) ( FUNCTABLE_SIZE - 1 ) ) ) );
+ tr.squareTable[i] = ( i < FUNCTABLE_SIZE/2 ) ? 1.0f : -1.0f;
+ tr.sawToothTable[i] = (float)i / FUNCTABLE_SIZE;
+ tr.inverseSawToothTable[i] = 1.0f - tr.sawToothTable[i];
+
+ if ( i < FUNCTABLE_SIZE / 2 )
+ {
+ if ( i < FUNCTABLE_SIZE / 4 )
+ {
+ tr.triangleTable[i] = ( float ) i / ( FUNCTABLE_SIZE / 4 );
+ }
+ else
+ {
+ tr.triangleTable[i] = 1.0f - tr.triangleTable[i-FUNCTABLE_SIZE / 4];
+ }
+ }
+ else
+ {
+ tr.triangleTable[i] = -tr.triangleTable[i-FUNCTABLE_SIZE/2];
+ }
+ }
+
+ R_InitFogTable();
+
+ R_NoiseInit();
+
+ R_Register();
+
+ max_polys = r_maxpolys->integer;
+ if (max_polys < MAX_POLYS)
+ max_polys = MAX_POLYS;
+
+ max_polyverts = r_maxpolyverts->integer;
+ if (max_polyverts < MAX_POLYVERTS)
+ max_polyverts = MAX_POLYVERTS;
+
+ ptr = ri.Hunk_Alloc( sizeof( *backEndData[0] ) + sizeof(srfPoly_t) * max_polys + sizeof(polyVert_t) * max_polyverts, h_low);
+ backEndData[0] = (backEndData_t *) ptr;
+ backEndData[0]->polys = (srfPoly_t *) ((char *) ptr + sizeof( *backEndData[0] ));
+ backEndData[0]->polyVerts = (polyVert_t *) ((char *) ptr + sizeof( *backEndData[0] ) + sizeof(srfPoly_t) * max_polys);
+ if ( r_smp->integer ) {
+ ptr = ri.Hunk_Alloc( sizeof( *backEndData[1] ) + sizeof(srfPoly_t) * max_polys + sizeof(polyVert_t) * max_polyverts, h_low);
+ backEndData[1] = (backEndData_t *) ptr;
+ backEndData[1]->polys = (srfPoly_t *) ((char *) ptr + sizeof( *backEndData[1] ));
+ backEndData[1]->polyVerts = (polyVert_t *) ((char *) ptr + sizeof( *backEndData[1] ) + sizeof(srfPoly_t) * max_polys);
+ } else {
+ backEndData[1] = NULL;
+ }
+ R_ToggleSmpFrame();
+
+ InitOpenGL();
+
+ R_InitImages();
+
+ R_InitShaders();
+
+ R_InitSkins();
+
+ R_ModelInit();
+
+ R_InitFreeType();
+
+
+ err = qglGetError();
+ if ( err != GL_NO_ERROR )
+ ri.Printf (PRINT_ALL, "glGetError() = 0x%x\n", err);
+
+ ri.Printf( PRINT_ALL, "----- finished R_Init -----\n" );
+}
+
+/*
+===============
+RE_Shutdown
+===============
+*/
+void RE_Shutdown( qboolean destroyWindow ) {
+
+ ri.Printf( PRINT_ALL, "RE_Shutdown( %i )\n", destroyWindow );
+
+ ri.Cmd_RemoveCommand ("modellist");
+ ri.Cmd_RemoveCommand ("screenshotJPEG");
+ ri.Cmd_RemoveCommand ("screenshot");
+ ri.Cmd_RemoveCommand ("imagelist");
+ ri.Cmd_RemoveCommand ("shaderlist");
+ ri.Cmd_RemoveCommand ("skinlist");
+ ri.Cmd_RemoveCommand ("gfxinfo");
+ ri.Cmd_RemoveCommand( "modelist" );
+ ri.Cmd_RemoveCommand( "shaderstate" );
+
+
+ if ( tr.registered ) {
+ R_SyncRenderThread();
+ R_ShutdownCommandBuffers();
+ R_DeleteTextures();
+ }
+
+ R_DoneFreeType();
+
+ // shut down platform specific OpenGL stuff
+ if ( destroyWindow ) {
+ GLimp_Shutdown();
+ }
+
+ tr.registered = qfalse;
+}
+
+
+/*
+=============
+RE_EndRegistration
+
+Touch all images to make sure they are resident
+=============
+*/
+void RE_EndRegistration( void ) {
+ R_SyncRenderThread();
+ if (!Sys_LowPhysicalMemory()) {
+ RB_ShowImages();
+ }
+}
+
+
+/*
+@@@@@@@@@@@@@@@@@@@@@
+GetRefAPI
+
+@@@@@@@@@@@@@@@@@@@@@
+*/
+refexport_t *GetRefAPI ( int apiVersion, refimport_t *rimp ) {
+ static refexport_t re;
+
+ ri = *rimp;
+
+ Com_Memset( &re, 0, sizeof( re ) );
+
+ if ( apiVersion != REF_API_VERSION ) {
+ ri.Printf(PRINT_ALL, "Mismatched REF_API_VERSION: expected %i, got %i\n",
+ REF_API_VERSION, apiVersion );
+ return NULL;
+ }
+
+ // the RE_ functions are Renderer Entry points
+
+ re.Shutdown = RE_Shutdown;
+
+ re.BeginRegistration = RE_BeginRegistration;
+ re.RegisterModel = RE_RegisterModel;
+ re.RegisterSkin = RE_RegisterSkin;
+ re.RegisterShader = RE_RegisterShader;
+ re.RegisterShaderNoMip = RE_RegisterShaderNoMip;
+ re.LoadWorld = RE_LoadWorldMap;
+ re.SetWorldVisData = RE_SetWorldVisData;
+ re.EndRegistration = RE_EndRegistration;
+
+ re.BeginFrame = RE_BeginFrame;
+ re.EndFrame = RE_EndFrame;
+
+ re.MarkFragments = R_MarkFragments;
+ re.LerpTag = R_LerpTag;
+ re.ModelBounds = R_ModelBounds;
+
+ re.ClearScene = RE_ClearScene;
+ re.AddRefEntityToScene = RE_AddRefEntityToScene;
+ re.AddPolyToScene = RE_AddPolyToScene;
+ re.LightForPoint = R_LightForPoint;
+ re.AddLightToScene = RE_AddLightToScene;
+ re.AddAdditiveLightToScene = RE_AddAdditiveLightToScene;
+ re.RenderScene = RE_RenderScene;
+
+ re.SetColor = RE_SetColor;
+ re.DrawStretchPic = RE_StretchPic;
+ re.DrawStretchRaw = RE_StretchRaw;
+ re.UploadCinematic = RE_UploadCinematic;
+
+ re.RegisterFont = RE_RegisterFont;
+ re.RemapShader = R_RemapShader;
+ re.GetEntityToken = R_GetEntityToken;
+ re.inPVS = R_inPVS;
+
+ return &re;
+}
diff --git a/code/renderer/tr_light.c b/code/renderer/tr_light.c
new file mode 100755
index 0000000..01d046c
--- /dev/null
+++ b/code/renderer/tr_light.c
@@ -0,0 +1,395 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// tr_light.c
+
+#include "tr_local.h"
+
+#define DLIGHT_AT_RADIUS 16
+// at the edge of a dlight's influence, this amount of light will be added
+
+#define DLIGHT_MINIMUM_RADIUS 16
+// never calculate a range less than this to prevent huge light numbers
+
+
+/*
+===============
+R_TransformDlights
+
+Transforms the origins of an array of dlights.
+Used by both the front end (for DlightBmodel) and
+the back end (before doing the lighting calculation)
+===============
+*/
+void R_TransformDlights( int count, dlight_t *dl, orientationr_t *or) {
+ int i;
+ vec3_t temp;
+
+ for ( i = 0 ; i < count ; i++, dl++ ) {
+ VectorSubtract( dl->origin, or->origin, temp );
+ dl->transformed[0] = DotProduct( temp, or->axis[0] );
+ dl->transformed[1] = DotProduct( temp, or->axis[1] );
+ dl->transformed[2] = DotProduct( temp, or->axis[2] );
+ }
+}
+
+/*
+=============
+R_DlightBmodel
+
+Determine which dynamic lights may effect this bmodel
+=============
+*/
+void R_DlightBmodel( bmodel_t *bmodel ) {
+ int i, j;
+ dlight_t *dl;
+ int mask;
+ msurface_t *surf;
+
+ // transform all the lights
+ R_TransformDlights( tr.refdef.num_dlights, tr.refdef.dlights, &tr.or );
+
+ mask = 0;
+ for ( i=0 ; i<tr.refdef.num_dlights ; i++ ) {
+ dl = &tr.refdef.dlights[i];
+
+ // see if the point is close enough to the bounds to matter
+ for ( j = 0 ; j < 3 ; j++ ) {
+ if ( dl->transformed[j] - bmodel->bounds[1][j] > dl->radius ) {
+ break;
+ }
+ if ( bmodel->bounds[0][j] - dl->transformed[j] > dl->radius ) {
+ break;
+ }
+ }
+ if ( j < 3 ) {
+ continue;
+ }
+
+ // we need to check this light
+ mask |= 1 << i;
+ }
+
+ tr.currentEntity->needDlights = (mask != 0);
+
+ // set the dlight bits in all the surfaces
+ for ( i = 0 ; i < bmodel->numSurfaces ; i++ ) {
+ surf = bmodel->firstSurface + i;
+
+ if ( *surf->data == SF_FACE ) {
+ ((srfSurfaceFace_t *)surf->data)->dlightBits[ tr.smpFrame ] = mask;
+ } else if ( *surf->data == SF_GRID ) {
+ ((srfGridMesh_t *)surf->data)->dlightBits[ tr.smpFrame ] = mask;
+ } else if ( *surf->data == SF_TRIANGLES ) {
+ ((srfTriangles_t *)surf->data)->dlightBits[ tr.smpFrame ] = mask;
+ }
+ }
+}
+
+
+/*
+=============================================================================
+
+LIGHT SAMPLING
+
+=============================================================================
+*/
+
+extern cvar_t *r_ambientScale;
+extern cvar_t *r_directedScale;
+extern cvar_t *r_debugLight;
+
+/*
+=================
+R_SetupEntityLightingGrid
+
+=================
+*/
+static void R_SetupEntityLightingGrid( trRefEntity_t *ent ) {
+ vec3_t lightOrigin;
+ int pos[3];
+ int i, j;
+ byte *gridData;
+ float frac[3];
+ int gridStep[3];
+ vec3_t direction;
+ float totalFactor;
+
+ if ( ent->e.renderfx & RF_LIGHTING_ORIGIN ) {
+ // seperate lightOrigins are needed so an object that is
+ // sinking into the ground can still be lit, and so
+ // multi-part models can be lit identically
+ VectorCopy( ent->e.lightingOrigin, lightOrigin );
+ } else {
+ VectorCopy( ent->e.origin, lightOrigin );
+ }
+
+ VectorSubtract( lightOrigin, tr.world->lightGridOrigin, lightOrigin );
+ for ( i = 0 ; i < 3 ; i++ ) {
+ float v;
+
+ v = lightOrigin[i]*tr.world->lightGridInverseSize[i];
+ pos[i] = floor( v );
+ frac[i] = v - pos[i];
+ if ( pos[i] < 0 ) {
+ pos[i] = 0;
+ } else if ( pos[i] >= tr.world->lightGridBounds[i] - 1 ) {
+ pos[i] = tr.world->lightGridBounds[i] - 1;
+ }
+ }
+
+ VectorClear( ent->ambientLight );
+ VectorClear( ent->directedLight );
+ VectorClear( direction );
+
+ assert( tr.world->lightGridData ); // bk010103 - NULL with -nolight maps
+
+ // trilerp the light value
+ gridStep[0] = 8;
+ gridStep[1] = 8 * tr.world->lightGridBounds[0];
+ gridStep[2] = 8 * tr.world->lightGridBounds[0] * tr.world->lightGridBounds[1];
+ gridData = tr.world->lightGridData + pos[0] * gridStep[0]
+ + pos[1] * gridStep[1] + pos[2] * gridStep[2];
+
+ totalFactor = 0;
+ for ( i = 0 ; i < 8 ; i++ ) {
+ float factor;
+ byte *data;
+ int lat, lng;
+ vec3_t normal;
+ #if idppc
+ float d0, d1, d2, d3, d4, d5;
+ #endif
+ factor = 1.0;
+ data = gridData;
+ for ( j = 0 ; j < 3 ; j++ ) {
+ if ( i & (1<<j) ) {
+ factor *= frac[j];
+ data += gridStep[j];
+ } else {
+ factor *= (1.0f - frac[j]);
+ }
+ }
+
+ if ( !(data[0]+data[1]+data[2]) ) {
+ continue; // ignore samples in walls
+ }
+ totalFactor += factor;
+ #if idppc
+ d0 = data[0]; d1 = data[1]; d2 = data[2];
+ d3 = data[3]; d4 = data[4]; d5 = data[5];
+
+ ent->ambientLight[0] += factor * d0;
+ ent->ambientLight[1] += factor * d1;
+ ent->ambientLight[2] += factor * d2;
+
+ ent->directedLight[0] += factor * d3;
+ ent->directedLight[1] += factor * d4;
+ ent->directedLight[2] += factor * d5;
+ #else
+ ent->ambientLight[0] += factor * data[0];
+ ent->ambientLight[1] += factor * data[1];
+ ent->ambientLight[2] += factor * data[2];
+
+ ent->directedLight[0] += factor * data[3];
+ ent->directedLight[1] += factor * data[4];
+ ent->directedLight[2] += factor * data[5];
+ #endif
+ lat = data[7];
+ lng = data[6];
+ lat *= (FUNCTABLE_SIZE/256);
+ lng *= (FUNCTABLE_SIZE/256);
+
+ // decode X as cos( lat ) * sin( long )
+ // decode Y as sin( lat ) * sin( long )
+ // decode Z as cos( long )
+
+ normal[0] = tr.sinTable[(lat+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK] * tr.sinTable[lng];
+ normal[1] = tr.sinTable[lat] * tr.sinTable[lng];
+ normal[2] = tr.sinTable[(lng+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK];
+
+ VectorMA( direction, factor, normal, direction );
+ }
+
+ if ( totalFactor > 0 && totalFactor < 0.99 ) {
+ totalFactor = 1.0f / totalFactor;
+ VectorScale( ent->ambientLight, totalFactor, ent->ambientLight );
+ VectorScale( ent->directedLight, totalFactor, ent->directedLight );
+ }
+
+ VectorScale( ent->ambientLight, r_ambientScale->value, ent->ambientLight );
+ VectorScale( ent->directedLight, r_directedScale->value, ent->directedLight );
+
+ VectorNormalize2( direction, ent->lightDir );
+}
+
+
+/*
+===============
+LogLight
+===============
+*/
+static void LogLight( trRefEntity_t *ent ) {
+ int max1, max2;
+
+ if ( !(ent->e.renderfx & RF_FIRST_PERSON ) ) {
+ return;
+ }
+
+ max1 = ent->ambientLight[0];
+ if ( ent->ambientLight[1] > max1 ) {
+ max1 = ent->ambientLight[1];
+ } else if ( ent->ambientLight[2] > max1 ) {
+ max1 = ent->ambientLight[2];
+ }
+
+ max2 = ent->directedLight[0];
+ if ( ent->directedLight[1] > max2 ) {
+ max2 = ent->directedLight[1];
+ } else if ( ent->directedLight[2] > max2 ) {
+ max2 = ent->directedLight[2];
+ }
+
+ ri.Printf( PRINT_ALL, "amb:%i dir:%i\n", max1, max2 );
+}
+
+/*
+=================
+R_SetupEntityLighting
+
+Calculates all the lighting values that will be used
+by the Calc_* functions
+=================
+*/
+void R_SetupEntityLighting( const trRefdef_t *refdef, trRefEntity_t *ent ) {
+ int i;
+ dlight_t *dl;
+ float power;
+ vec3_t dir;
+ float d;
+ vec3_t lightDir;
+ vec3_t lightOrigin;
+
+ // lighting calculations
+ if ( ent->lightingCalculated ) {
+ return;
+ }
+ ent->lightingCalculated = qtrue;
+
+ //
+ // trace a sample point down to find ambient light
+ //
+ if ( ent->e.renderfx & RF_LIGHTING_ORIGIN ) {
+ // seperate lightOrigins are needed so an object that is
+ // sinking into the ground can still be lit, and so
+ // multi-part models can be lit identically
+ VectorCopy( ent->e.lightingOrigin, lightOrigin );
+ } else {
+ VectorCopy( ent->e.origin, lightOrigin );
+ }
+
+ // if NOWORLDMODEL, only use dynamic lights (menu system, etc)
+ if ( !(refdef->rdflags & RDF_NOWORLDMODEL )
+ && tr.world->lightGridData ) {
+ R_SetupEntityLightingGrid( ent );
+ } else {
+ ent->ambientLight[0] = ent->ambientLight[1] =
+ ent->ambientLight[2] = tr.identityLight * 150;
+ ent->directedLight[0] = ent->directedLight[1] =
+ ent->directedLight[2] = tr.identityLight * 150;
+ VectorCopy( tr.sunDirection, ent->lightDir );
+ }
+
+ // bonus items and view weapons have a fixed minimum add
+ if ( 1 /* ent->e.renderfx & RF_MINLIGHT */ ) {
+ // give everything a minimum light add
+ ent->ambientLight[0] += tr.identityLight * 32;
+ ent->ambientLight[1] += tr.identityLight * 32;
+ ent->ambientLight[2] += tr.identityLight * 32;
+ }
+
+ //
+ // modify the light by dynamic lights
+ //
+ d = VectorLength( ent->directedLight );
+ VectorScale( ent->lightDir, d, lightDir );
+
+ for ( i = 0 ; i < refdef->num_dlights ; i++ ) {
+ dl = &refdef->dlights[i];
+ VectorSubtract( dl->origin, lightOrigin, dir );
+ d = VectorNormalize( dir );
+
+ power = DLIGHT_AT_RADIUS * ( dl->radius * dl->radius );
+ if ( d < DLIGHT_MINIMUM_RADIUS ) {
+ d = DLIGHT_MINIMUM_RADIUS;
+ }
+ d = power / ( d * d );
+
+ VectorMA( ent->directedLight, d, dl->color, ent->directedLight );
+ VectorMA( lightDir, d, dir, lightDir );
+ }
+
+ // clamp ambient
+ for ( i = 0 ; i < 3 ; i++ ) {
+ if ( ent->ambientLight[i] > tr.identityLightByte ) {
+ ent->ambientLight[i] = tr.identityLightByte;
+ }
+ }
+
+ if ( r_debugLight->integer ) {
+ LogLight( ent );
+ }
+
+ // save out the byte packet version
+ ((byte *)&ent->ambientLightInt)[0] = myftol( ent->ambientLight[0] );
+ ((byte *)&ent->ambientLightInt)[1] = myftol( ent->ambientLight[1] );
+ ((byte *)&ent->ambientLightInt)[2] = myftol( ent->ambientLight[2] );
+ ((byte *)&ent->ambientLightInt)[3] = 0xff;
+
+ // transform the direction to local space
+ VectorNormalize( lightDir );
+ ent->lightDir[0] = DotProduct( lightDir, ent->e.axis[0] );
+ ent->lightDir[1] = DotProduct( lightDir, ent->e.axis[1] );
+ ent->lightDir[2] = DotProduct( lightDir, ent->e.axis[2] );
+}
+
+/*
+=================
+R_LightForPoint
+=================
+*/
+int R_LightForPoint( vec3_t point, vec3_t ambientLight, vec3_t directedLight, vec3_t lightDir )
+{
+ trRefEntity_t ent;
+
+ // bk010103 - this segfaults with -nolight maps
+ if ( tr.world->lightGridData == NULL )
+ return qfalse;
+
+ Com_Memset(&ent, 0, sizeof(ent));
+ VectorCopy( point, ent.e.origin );
+ R_SetupEntityLightingGrid( &ent );
+ VectorCopy(ent.ambientLight, ambientLight);
+ VectorCopy(ent.directedLight, directedLight);
+ VectorCopy(ent.lightDir, lightDir);
+
+ return qtrue;
+}
diff --git a/code/renderer/tr_local.h b/code/renderer/tr_local.h
new file mode 100755
index 0000000..1228661
--- /dev/null
+++ b/code/renderer/tr_local.h
@@ -0,0 +1,1609 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+
+#ifndef TR_LOCAL_H
+#define TR_LOCAL_H
+
+#include "../game/q_shared.h"
+#include "../qcommon/qfiles.h"
+#include "../qcommon/qcommon.h"
+#include "tr_public.h"
+#include "qgl.h"
+
+#define GL_INDEX_TYPE GL_UNSIGNED_INT
+typedef unsigned int glIndex_t;
+
+// fast float to int conversion
+#if id386 && !( (defined __linux__ || defined __FreeBSD__ ) && (defined __i386__ ) ) // rb010123
+long myftol( float f );
+#else
+#define myftol(x) ((int)(x))
+#endif
+
+
+// everything that is needed by the backend needs
+// to be double buffered to allow it to run in
+// parallel on a dual cpu machine
+#define SMP_FRAMES 2
+
+// 12 bits
+// see QSORT_SHADERNUM_SHIFT
+#define MAX_SHADERS 16384
+
+//#define MAX_SHADER_STATES 2048
+#define MAX_STATES_PER_SHADER 32
+#define MAX_STATE_NAME 32
+
+// can't be increased without changing bit packing for drawsurfs
+
+
+typedef struct dlight_s {
+ vec3_t origin;
+ vec3_t color; // range from 0.0 to 1.0, should be color normalized
+ float radius;
+
+ vec3_t transformed; // origin in local coordinate system
+ int additive; // texture detail is lost tho when the lightmap is dark
+} dlight_t;
+
+
+// a trRefEntity_t has all the information passed in by
+// the client game, as well as some locally derived info
+typedef struct {
+ refEntity_t e;
+
+ float axisLength; // compensate for non-normalized axis
+
+ qboolean needDlights; // true for bmodels that touch a dlight
+ qboolean lightingCalculated;
+ vec3_t lightDir; // normalized direction towards light
+ vec3_t ambientLight; // color normalized to 0-255
+ int ambientLightInt; // 32 bit rgba packed
+ vec3_t directedLight;
+} trRefEntity_t;
+
+
+typedef struct {
+ vec3_t origin; // in world coordinates
+ vec3_t axis[3]; // orientation in world
+ vec3_t viewOrigin; // viewParms->or.origin in local coordinates
+ float modelMatrix[16];
+} orientationr_t;
+
+typedef struct image_s {
+ char imgName[MAX_QPATH]; // game path, including extension
+ int width, height; // source image
+ int uploadWidth, uploadHeight; // after power of two and picmip but not including clamp to MAX_TEXTURE_SIZE
+ GLuint texnum; // gl texture binding
+
+ int frameUsed; // for texture usage in frame statistics
+
+ int internalFormat;
+ int TMU; // only needed for voodoo2
+
+ qboolean mipmap;
+ qboolean allowPicmip;
+ int wrapClampMode; // GL_CLAMP or GL_REPEAT
+
+ struct image_s* next;
+} image_t;
+
+//===============================================================================
+
+typedef enum {
+ SS_BAD,
+ SS_PORTAL, // mirrors, portals, viewscreens
+ SS_ENVIRONMENT, // sky box
+ SS_OPAQUE, // opaque
+
+ SS_DECAL, // scorch marks, etc.
+ SS_SEE_THROUGH, // ladders, grates, grills that may have small blended edges
+ // in addition to alpha test
+ SS_BANNER,
+
+ SS_FOG,
+
+ SS_UNDERWATER, // for items that should be drawn in front of the water plane
+
+ SS_BLEND0, // regular transparency and filters
+ SS_BLEND1, // generally only used for additive type effects
+ SS_BLEND2,
+ SS_BLEND3,
+
+ SS_BLEND6,
+ SS_STENCIL_SHADOW,
+ SS_ALMOST_NEAREST, // gun smoke puffs
+
+ SS_NEAREST // blood blobs
+} shaderSort_t;
+
+
+#define MAX_SHADER_STAGES 8
+
+typedef enum {
+ GF_NONE,
+
+ GF_SIN,
+ GF_SQUARE,
+ GF_TRIANGLE,
+ GF_SAWTOOTH,
+ GF_INVERSE_SAWTOOTH,
+
+ GF_NOISE
+
+} genFunc_t;
+
+
+typedef enum {
+ DEFORM_NONE,
+ DEFORM_WAVE,
+ DEFORM_NORMALS,
+ DEFORM_BULGE,
+ DEFORM_MOVE,
+ DEFORM_PROJECTION_SHADOW,
+ DEFORM_AUTOSPRITE,
+ DEFORM_AUTOSPRITE2,
+ DEFORM_TEXT0,
+ DEFORM_TEXT1,
+ DEFORM_TEXT2,
+ DEFORM_TEXT3,
+ DEFORM_TEXT4,
+ DEFORM_TEXT5,
+ DEFORM_TEXT6,
+ DEFORM_TEXT7
+} deform_t;
+
+typedef enum {
+ AGEN_IDENTITY,
+ AGEN_SKIP,
+ AGEN_ENTITY,
+ AGEN_ONE_MINUS_ENTITY,
+ AGEN_VERTEX,
+ AGEN_ONE_MINUS_VERTEX,
+ AGEN_LIGHTING_SPECULAR,
+ AGEN_WAVEFORM,
+ AGEN_PORTAL,
+ AGEN_CONST
+} alphaGen_t;
+
+typedef enum {
+ CGEN_BAD,
+ CGEN_IDENTITY_LIGHTING, // tr.identityLight
+ CGEN_IDENTITY, // always (1,1,1,1)
+ CGEN_ENTITY, // grabbed from entity's modulate field
+ CGEN_ONE_MINUS_ENTITY, // grabbed from 1 - entity.modulate
+ CGEN_EXACT_VERTEX, // tess.vertexColors
+ CGEN_VERTEX, // tess.vertexColors * tr.identityLight
+ CGEN_ONE_MINUS_VERTEX,
+ CGEN_WAVEFORM, // programmatically generated
+ CGEN_LIGHTING_DIFFUSE,
+ CGEN_FOG, // standard fog
+ CGEN_CONST // fixed color
+} colorGen_t;
+
+typedef enum {
+ TCGEN_BAD,
+ TCGEN_IDENTITY, // clear to 0,0
+ TCGEN_LIGHTMAP,
+ TCGEN_TEXTURE,
+ TCGEN_ENVIRONMENT_MAPPED,
+ TCGEN_FOG,
+ TCGEN_VECTOR // S and T from world coordinates
+} texCoordGen_t;
+
+typedef enum {
+ ACFF_NONE,
+ ACFF_MODULATE_RGB,
+ ACFF_MODULATE_RGBA,
+ ACFF_MODULATE_ALPHA
+} acff_t;
+
+typedef struct {
+ genFunc_t func;
+
+ float base;
+ float amplitude;
+ float phase;
+ float frequency;
+} waveForm_t;
+
+#define TR_MAX_TEXMODS 4
+
+typedef enum {
+ TMOD_NONE,
+ TMOD_TRANSFORM,
+ TMOD_TURBULENT,
+ TMOD_SCROLL,
+ TMOD_SCALE,
+ TMOD_STRETCH,
+ TMOD_ROTATE,
+ TMOD_ENTITY_TRANSLATE
+} texMod_t;
+
+#define MAX_SHADER_DEFORMS 3
+typedef struct {
+ deform_t deformation; // vertex coordinate modification type
+
+ vec3_t moveVector;
+ waveForm_t deformationWave;
+ float deformationSpread;
+
+ float bulgeWidth;
+ float bulgeHeight;
+ float bulgeSpeed;
+} deformStage_t;
+
+
+typedef struct {
+ texMod_t type;
+
+ // used for TMOD_TURBULENT and TMOD_STRETCH
+ waveForm_t wave;
+
+ // used for TMOD_TRANSFORM
+ float matrix[2][2]; // s' = s * m[0][0] + t * m[1][0] + trans[0]
+ float translate[2]; // t' = s * m[0][1] + t * m[0][1] + trans[1]
+
+ // used for TMOD_SCALE
+ float scale[2]; // s *= scale[0]
+ // t *= scale[1]
+
+ // used for TMOD_SCROLL
+ float scroll[2]; // s' = s + scroll[0] * time
+ // t' = t + scroll[1] * time
+
+ // + = clockwise
+ // - = counterclockwise
+ float rotateSpeed;
+
+} texModInfo_t;
+
+
+#define MAX_IMAGE_ANIMATIONS 8
+
+typedef struct {
+ image_t *image[MAX_IMAGE_ANIMATIONS];
+ int numImageAnimations;
+ float imageAnimationSpeed;
+
+ texCoordGen_t tcGen;
+ vec3_t tcGenVectors[2];
+
+ int numTexMods;
+ texModInfo_t *texMods;
+
+ int videoMapHandle;
+ qboolean isLightmap;
+ qboolean vertexLightmap;
+ qboolean isVideoMap;
+} textureBundle_t;
+
+#define NUM_TEXTURE_BUNDLES 2
+
+typedef struct {
+ qboolean active;
+
+ textureBundle_t bundle[NUM_TEXTURE_BUNDLES];
+
+ waveForm_t rgbWave;
+ colorGen_t rgbGen;
+
+ waveForm_t alphaWave;
+ alphaGen_t alphaGen;
+
+ byte constantColor[4]; // for CGEN_CONST and AGEN_CONST
+
+ unsigned stateBits; // GLS_xxxx mask
+
+ acff_t adjustColorsForFog;
+
+ qboolean isDetail;
+} shaderStage_t;
+
+struct shaderCommands_s;
+
+#define LIGHTMAP_2D -4 // shader is for 2D rendering
+#define LIGHTMAP_BY_VERTEX -3 // pre-lit triangle models
+#define LIGHTMAP_WHITEIMAGE -2
+#define LIGHTMAP_NONE -1
+
+typedef enum {
+ CT_FRONT_SIDED,
+ CT_BACK_SIDED,
+ CT_TWO_SIDED
+} cullType_t;
+
+typedef enum {
+ FP_NONE, // surface is translucent and will just be adjusted properly
+ FP_EQUAL, // surface is opaque but possibly alpha tested
+ FP_LE // surface is trnaslucent, but still needs a fog pass (fog surface)
+} fogPass_t;
+
+typedef struct {
+ float cloudHeight;
+ image_t *outerbox[6], *innerbox[6];
+} skyParms_t;
+
+typedef struct {
+ vec3_t color;
+ float depthForOpaque;
+} fogParms_t;
+
+
+typedef struct shader_s {
+ char name[MAX_QPATH]; // game path, including extension
+ int lightmapIndex; // for a shader to match, both name and lightmapIndex must match
+
+ int index; // this shader == tr.shaders[index]
+ int sortedIndex; // this shader == tr.sortedShaders[sortedIndex]
+
+ float sort; // lower numbered shaders draw before higher numbered
+
+ qboolean defaultShader; // we want to return index 0 if the shader failed to
+ // load for some reason, but R_FindShader should
+ // still keep a name allocated for it, so if
+ // something calls RE_RegisterShader again with
+ // the same name, we don't try looking for it again
+
+ qboolean explicitlyDefined; // found in a .shader file
+
+ int surfaceFlags; // if explicitlyDefined, this will have SURF_* flags
+ int contentFlags;
+
+ qboolean entityMergable; // merge across entites optimizable (smoke, blood)
+
+ qboolean isSky;
+ skyParms_t sky;
+ fogParms_t fogParms;
+
+ float portalRange; // distance to fog out at
+
+ int multitextureEnv; // 0, GL_MODULATE, GL_ADD (FIXME: put in stage)
+
+ cullType_t cullType; // CT_FRONT_SIDED, CT_BACK_SIDED, or CT_TWO_SIDED
+ qboolean polygonOffset; // set for decals and other items that must be offset
+ qboolean noMipMaps; // for console fonts, 2D elements, etc.
+ qboolean noPicMip; // for images that must always be full resolution
+
+ fogPass_t fogPass; // draw a blended pass, possibly with depth test equals
+
+ qboolean needsNormal; // not all shaders will need all data to be gathered
+ qboolean needsST1;
+ qboolean needsST2;
+ qboolean needsColor;
+
+ int numDeforms;
+ deformStage_t deforms[MAX_SHADER_DEFORMS];
+
+ int numUnfoggedPasses;
+ shaderStage_t *stages[MAX_SHADER_STAGES];
+
+ void (*optimalStageIteratorFunc)( void );
+
+ float clampTime; // time this shader is clamped to
+ float timeOffset; // current time offset for this shader
+
+ int numStates; // if non-zero this is a state shader
+ struct shader_s *currentShader; // current state if this is a state shader
+ struct shader_s *parentShader; // current state if this is a state shader
+ int currentState; // current state index for cycle purposes
+ long expireTime; // time in milliseconds this expires
+
+ struct shader_s *remappedShader; // current shader this one is remapped too
+
+ int shaderStates[MAX_STATES_PER_SHADER]; // index to valid shader states
+
+ struct shader_s *next;
+} shader_t;
+
+typedef struct shaderState_s {
+ char shaderName[MAX_QPATH]; // name of shader this state belongs to
+ char name[MAX_STATE_NAME]; // name of this state
+ char stateShader[MAX_QPATH]; // shader this name invokes
+ int cycleTime; // time this cycle lasts, <= 0 is forever
+ shader_t *shader;
+} shaderState_t;
+
+
+// trRefdef_t holds everything that comes in refdef_t,
+// as well as the locally generated scene information
+typedef struct {
+ int x, y, width, height;
+ float fov_x, fov_y;
+ vec3_t vieworg;
+ vec3_t viewaxis[3]; // transformation matrix
+
+ int time; // time in milliseconds for shader effects and other time dependent rendering issues
+ int rdflags; // RDF_NOWORLDMODEL, etc
+
+ // 1 bits will prevent the associated area from rendering at all
+ byte areamask[MAX_MAP_AREA_BYTES];
+ qboolean areamaskModified; // qtrue if areamask changed since last scene
+
+ float floatTime; // tr.refdef.time / 1000.0
+
+ // text messages for deform text shaders
+ char text[MAX_RENDER_STRINGS][MAX_RENDER_STRING_LENGTH];
+
+ int num_entities;
+ trRefEntity_t *entities;
+
+ int num_dlights;
+ struct dlight_s *dlights;
+
+ int numPolys;
+ struct srfPoly_s *polys;
+
+ int numDrawSurfs;
+ struct drawSurf_s *drawSurfs;
+
+
+} trRefdef_t;
+
+
+//=================================================================================
+
+// skins allow models to be retextured without modifying the model file
+typedef struct {
+ char name[MAX_QPATH];
+ shader_t *shader;
+} skinSurface_t;
+
+typedef struct skin_s {
+ char name[MAX_QPATH]; // game path, including extension
+ int numSurfaces;
+ skinSurface_t *surfaces[MD3_MAX_SURFACES];
+} skin_t;
+
+
+typedef struct {
+ int originalBrushNumber;
+ vec3_t bounds[2];
+
+ unsigned colorInt; // in packed byte format
+ float tcScale; // texture coordinate vector scales
+ fogParms_t parms;
+
+ // for clipping distance in fog when outside
+ qboolean hasSurface;
+ float surface[4];
+} fog_t;
+
+typedef struct {
+ orientationr_t or;
+ orientationr_t world;
+ vec3_t pvsOrigin; // may be different than or.origin for portals
+ qboolean isPortal; // true if this view is through a portal
+ qboolean isMirror; // the portal is a mirror, invert the face culling
+ int frameSceneNum; // copied from tr.frameSceneNum
+ int frameCount; // copied from tr.frameCount
+ cplane_t portalPlane; // clip anything behind this if mirroring
+ int viewportX, viewportY, viewportWidth, viewportHeight;
+ float fovX, fovY;
+ float projectionMatrix[16];
+ cplane_t frustum[4];
+ vec3_t visBounds[2];
+ float zFar;
+} viewParms_t;
+
+
+/*
+==============================================================================
+
+SURFACES
+
+==============================================================================
+*/
+
+// any changes in surfaceType must be mirrored in rb_surfaceTable[]
+typedef enum {
+ SF_BAD,
+ SF_SKIP, // ignore
+ SF_FACE,
+ SF_GRID,
+ SF_TRIANGLES,
+ SF_POLY,
+ SF_MD3,
+ SF_MD4,
+ SF_FLARE,
+ SF_ENTITY, // beams, rails, lightning, etc that can be determined by entity
+ SF_DISPLAY_LIST,
+
+ SF_NUM_SURFACE_TYPES,
+ SF_MAX = 0x7fffffff // ensures that sizeof( surfaceType_t ) == sizeof( int )
+} surfaceType_t;
+
+typedef struct drawSurf_s {
+ unsigned sort; // bit combination for fast compares
+ surfaceType_t *surface; // any of surface*_t
+} drawSurf_t;
+
+#define MAX_FACE_POINTS 64
+
+#define MAX_PATCH_SIZE 32 // max dimensions of a patch mesh in map file
+#define MAX_GRID_SIZE 65 // max dimensions of a grid mesh in memory
+
+// when cgame directly specifies a polygon, it becomes a srfPoly_t
+// as soon as it is called
+typedef struct srfPoly_s {
+ surfaceType_t surfaceType;
+ qhandle_t hShader;
+ int fogIndex;
+ int numVerts;
+ polyVert_t *verts;
+} srfPoly_t;
+
+typedef struct srfDisplayList_s {
+ surfaceType_t surfaceType;
+ int listNum;
+} srfDisplayList_t;
+
+
+typedef struct srfFlare_s {
+ surfaceType_t surfaceType;
+ vec3_t origin;
+ vec3_t normal;
+ vec3_t color;
+} srfFlare_t;
+
+typedef struct srfGridMesh_s {
+ surfaceType_t surfaceType;
+
+ // dynamic lighting information
+ int dlightBits[SMP_FRAMES];
+
+ // culling information
+ vec3_t meshBounds[2];
+ vec3_t localOrigin;
+ float meshRadius;
+
+ // lod information, which may be different
+ // than the culling information to allow for
+ // groups of curves that LOD as a unit
+ vec3_t lodOrigin;
+ float lodRadius;
+ int lodFixed;
+ int lodStitched;
+
+ // vertexes
+ int width, height;
+ float *widthLodError;
+ float *heightLodError;
+ drawVert_t verts[1]; // variable sized
+} srfGridMesh_t;
+
+
+
+#define VERTEXSIZE 8
+typedef struct {
+ surfaceType_t surfaceType;
+ cplane_t plane;
+
+ // dynamic lighting information
+ int dlightBits[SMP_FRAMES];
+
+ // triangle definitions (no normals at points)
+ int numPoints;
+ int numIndices;
+ int ofsIndices;
+ float points[1][VERTEXSIZE]; // variable sized
+ // there is a variable length list of indices here also
+} srfSurfaceFace_t;
+
+
+// misc_models in maps are turned into direct geometry by q3map
+typedef struct {
+ surfaceType_t surfaceType;
+
+ // dynamic lighting information
+ int dlightBits[SMP_FRAMES];
+
+ // culling information (FIXME: use this!)
+ vec3_t bounds[2];
+ vec3_t localOrigin;
+ float radius;
+
+ // triangle definitions
+ int numIndexes;
+ int *indexes;
+
+ int numVerts;
+ drawVert_t *verts;
+} srfTriangles_t;
+
+
+extern void (*rb_surfaceTable[SF_NUM_SURFACE_TYPES])(void *);
+
+/*
+==============================================================================
+
+BRUSH MODELS
+
+==============================================================================
+*/
+
+
+//
+// in memory representation
+//
+
+#define SIDE_FRONT 0
+#define SIDE_BACK 1
+#define SIDE_ON 2
+
+typedef struct msurface_s {
+ int viewCount; // if == tr.viewCount, already added
+ struct shader_s *shader;
+ int fogIndex;
+
+ surfaceType_t *data; // any of srf*_t
+} msurface_t;
+
+
+
+#define CONTENTS_NODE -1
+typedef struct mnode_s {
+ // common with leaf and node
+ int contents; // -1 for nodes, to differentiate from leafs
+ int visframe; // node needs to be traversed if current
+ vec3_t mins, maxs; // for bounding box culling
+ struct mnode_s *parent;
+
+ // node specific
+ cplane_t *plane;
+ struct mnode_s *children[2];
+
+ // leaf specific
+ int cluster;
+ int area;
+
+ msurface_t **firstmarksurface;
+ int nummarksurfaces;
+} mnode_t;
+
+typedef struct {
+ vec3_t bounds[2]; // for culling
+ msurface_t *firstSurface;
+ int numSurfaces;
+} bmodel_t;
+
+typedef struct {
+ char name[MAX_QPATH]; // ie: maps/tim_dm2.bsp
+ char baseName[MAX_QPATH]; // ie: tim_dm2
+
+ int dataSize;
+
+ int numShaders;
+ dshader_t *shaders;
+
+ bmodel_t *bmodels;
+
+ int numplanes;
+ cplane_t *planes;
+
+ int numnodes; // includes leafs
+ int numDecisionNodes;
+ mnode_t *nodes;
+
+ int numsurfaces;
+ msurface_t *surfaces;
+
+ int nummarksurfaces;
+ msurface_t **marksurfaces;
+
+ int numfogs;
+ fog_t *fogs;
+
+ vec3_t lightGridOrigin;
+ vec3_t lightGridSize;
+ vec3_t lightGridInverseSize;
+ int lightGridBounds[3];
+ byte *lightGridData;
+
+
+ int numClusters;
+ int clusterBytes;
+ const byte *vis; // may be passed in by CM_LoadMap to save space
+
+ byte *novis; // clusterBytes of 0xff
+
+ char *entityString;
+ char *entityParsePoint;
+} world_t;
+
+//======================================================================
+
+typedef enum {
+ MOD_BAD,
+ MOD_BRUSH,
+ MOD_MESH,
+ MOD_MD4
+} modtype_t;
+
+typedef struct model_s {
+ char name[MAX_QPATH];
+ modtype_t type;
+ int index; // model = tr.models[model->index]
+
+ int dataSize; // just for listing purposes
+ bmodel_t *bmodel; // only if type == MOD_BRUSH
+ md3Header_t *md3[MD3_MAX_LODS]; // only if type == MOD_MESH
+ md4Header_t *md4; // only if type == MOD_MD4
+
+ int numLods;
+} model_t;
+
+
+#define MAX_MOD_KNOWN 1024
+
+void R_ModelInit (void);
+model_t *R_GetModelByHandle( qhandle_t hModel );
+int R_LerpTag( orientation_t *tag, qhandle_t handle, int startFrame, int endFrame,
+ float frac, const char *tagName );
+void R_ModelBounds( qhandle_t handle, vec3_t mins, vec3_t maxs );
+
+void R_Modellist_f (void);
+
+//====================================================
+extern refimport_t ri;
+
+#define MAX_DRAWIMAGES 2048
+#define MAX_LIGHTMAPS 256
+#define MAX_SKINS 1024
+
+
+#define MAX_DRAWSURFS 0x10000
+#define DRAWSURF_MASK (MAX_DRAWSURFS-1)
+
+/*
+
+the drawsurf sort data is packed into a single 32 bit value so it can be
+compared quickly during the qsorting process
+
+the bits are allocated as follows:
+
+21 - 31 : sorted shader index
+11 - 20 : entity index
+2 - 6 : fog index
+//2 : used to be clipped flag REMOVED - 03.21.00 rad
+0 - 1 : dlightmap index
+
+ TTimo - 1.32
+17-31 : sorted shader index
+7-16 : entity index
+2-6 : fog index
+0-1 : dlightmap index
+*/
+#define QSORT_SHADERNUM_SHIFT 17
+#define QSORT_ENTITYNUM_SHIFT 7
+#define QSORT_FOGNUM_SHIFT 2
+
+extern int gl_filter_min, gl_filter_max;
+
+/*
+** performanceCounters_t
+*/
+typedef struct {
+ int c_sphere_cull_patch_in, c_sphere_cull_patch_clip, c_sphere_cull_patch_out;
+ int c_box_cull_patch_in, c_box_cull_patch_clip, c_box_cull_patch_out;
+ int c_sphere_cull_md3_in, c_sphere_cull_md3_clip, c_sphere_cull_md3_out;
+ int c_box_cull_md3_in, c_box_cull_md3_clip, c_box_cull_md3_out;
+
+ int c_leafs;
+ int c_dlightSurfaces;
+ int c_dlightSurfacesCulled;
+} frontEndCounters_t;
+
+#define FOG_TABLE_SIZE 256
+#define FUNCTABLE_SIZE 1024
+#define FUNCTABLE_SIZE2 10
+#define FUNCTABLE_MASK (FUNCTABLE_SIZE-1)
+
+
+// the renderer front end should never modify glstate_t
+typedef struct {
+ int currenttextures[2];
+ int currenttmu;
+ qboolean finishCalled;
+ int texEnv[2];
+ int faceCulling;
+ unsigned long glStateBits;
+} glstate_t;
+
+
+typedef struct {
+ int c_surfaces, c_shaders, c_vertexes, c_indexes, c_totalIndexes;
+ float c_overDraw;
+
+ int c_dlightVertexes;
+ int c_dlightIndexes;
+
+ int c_flareAdds;
+ int c_flareTests;
+ int c_flareRenders;
+
+ int msec; // total msec for backend run
+} backEndCounters_t;
+
+// all state modified by the back end is seperated
+// from the front end state
+typedef struct {
+ int smpFrame;
+ trRefdef_t refdef;
+ viewParms_t viewParms;
+ orientationr_t or;
+ backEndCounters_t pc;
+ qboolean isHyperspace;
+ trRefEntity_t *currentEntity;
+ qboolean skyRenderedThisView; // flag for drawing sun
+
+ qboolean projection2D; // if qtrue, drawstretchpic doesn't need to change modes
+ byte color2D[4];
+ qboolean vertexes2D; // shader needs to be finished
+ trRefEntity_t entity2D; // currentEntity will point at this when doing 2D rendering
+} backEndState_t;
+
+/*
+** trGlobals_t
+**
+** Most renderer globals are defined here.
+** backend functions should never modify any of these fields,
+** but may read fields that aren't dynamically modified
+** by the frontend.
+*/
+typedef struct {
+ qboolean registered; // cleared at shutdown, set at beginRegistration
+
+ int visCount; // incremented every time a new vis cluster is entered
+ int frameCount; // incremented every frame
+ int sceneCount; // incremented every scene
+ int viewCount; // incremented every view (twice a scene if portaled)
+ // and every R_MarkFragments call
+
+ int smpFrame; // toggles from 0 to 1 every endFrame
+
+ int frameSceneNum; // zeroed at RE_BeginFrame
+
+ qboolean worldMapLoaded;
+ world_t *world;
+
+ const byte *externalVisData; // from RE_SetWorldVisData, shared with CM_Load
+
+ image_t *defaultImage;
+ image_t *scratchImage[32];
+ image_t *fogImage;
+ image_t *dlightImage; // inverse-quare highlight for projective adding
+ image_t *flareImage;
+ image_t *whiteImage; // full of 0xff
+ image_t *identityLightImage; // full of tr.identityLightByte
+
+ shader_t *defaultShader;
+ shader_t *shadowShader;
+ shader_t *projectionShadowShader;
+
+ shader_t *flareShader;
+ shader_t *sunShader;
+
+ int numLightmaps;
+ image_t *lightmaps[MAX_LIGHTMAPS];
+
+ trRefEntity_t *currentEntity;
+ trRefEntity_t worldEntity; // point currentEntity at this when rendering world
+ int currentEntityNum;
+ int shiftedEntityNum; // currentEntityNum << QSORT_ENTITYNUM_SHIFT
+ model_t *currentModel;
+
+ viewParms_t viewParms;
+
+ float identityLight; // 1.0 / ( 1 << overbrightBits )
+ int identityLightByte; // identityLight * 255
+ int overbrightBits; // r_overbrightBits->integer, but set to 0 if no hw gamma
+
+ orientationr_t or; // for current entity
+
+ trRefdef_t refdef;
+
+ int viewCluster;
+
+ vec3_t sunLight; // from the sky shader for this level
+ vec3_t sunDirection;
+
+ frontEndCounters_t pc;
+ int frontEndMsec; // not in pc due to clearing issue
+
+ //
+ // put large tables at the end, so most elements will be
+ // within the +/32K indexed range on risc processors
+ //
+ model_t *models[MAX_MOD_KNOWN];
+ int numModels;
+
+ int numImages;
+ image_t *images[MAX_DRAWIMAGES];
+
+ // shader indexes from other modules will be looked up in tr.shaders[]
+ // shader indexes from drawsurfs will be looked up in sortedShaders[]
+ // lower indexed sortedShaders must be rendered first (opaque surfaces before translucent)
+ int numShaders;
+ shader_t *shaders[MAX_SHADERS];
+ shader_t *sortedShaders[MAX_SHADERS];
+
+ int numSkins;
+ skin_t *skins[MAX_SKINS];
+
+ float sinTable[FUNCTABLE_SIZE];
+ float squareTable[FUNCTABLE_SIZE];
+ float triangleTable[FUNCTABLE_SIZE];
+ float sawToothTable[FUNCTABLE_SIZE];
+ float inverseSawToothTable[FUNCTABLE_SIZE];
+ float fogTable[FOG_TABLE_SIZE];
+} trGlobals_t;
+
+extern backEndState_t backEnd;
+extern trGlobals_t tr;
+extern glconfig_t glConfig; // outside of TR since it shouldn't be cleared during ref re-init
+extern glstate_t glState; // outside of TR since it shouldn't be cleared during ref re-init
+
+
+//
+// cvars
+//
+extern cvar_t *r_flareSize;
+extern cvar_t *r_flareFade;
+
+extern cvar_t *r_railWidth;
+extern cvar_t *r_railCoreWidth;
+extern cvar_t *r_railSegmentLength;
+
+extern cvar_t *r_ignore; // used for debugging anything
+extern cvar_t *r_verbose; // used for verbose debug spew
+extern cvar_t *r_ignoreFastPath; // allows us to ignore our Tess fast paths
+
+extern cvar_t *r_znear; // near Z clip plane
+
+extern cvar_t *r_stencilbits; // number of desired stencil bits
+extern cvar_t *r_depthbits; // number of desired depth bits
+extern cvar_t *r_colorbits; // number of desired color bits, only relevant for fullscreen
+extern cvar_t *r_stereo; // desired pixelformat stereo flag
+extern cvar_t *r_texturebits; // number of desired texture bits
+ // 0 = use framebuffer depth
+ // 16 = use 16-bit textures
+ // 32 = use 32-bit textures
+ // all else = error
+
+extern cvar_t *r_measureOverdraw; // enables stencil buffer overdraw measurement
+
+extern cvar_t *r_lodbias; // push/pull LOD transitions
+extern cvar_t *r_lodscale;
+
+extern cvar_t *r_primitives; // "0" = based on compiled vertex array existance
+ // "1" = glDrawElemet tristrips
+ // "2" = glDrawElements triangles
+ // "-1" = no drawing
+
+extern cvar_t *r_inGameVideo; // controls whether in game video should be draw
+extern cvar_t *r_fastsky; // controls whether sky should be cleared or drawn
+extern cvar_t *r_drawSun; // controls drawing of sun quad
+extern cvar_t *r_dynamiclight; // dynamic lights enabled/disabled
+extern cvar_t *r_dlightBacks; // dlight non-facing surfaces for continuity
+
+extern cvar_t *r_norefresh; // bypasses the ref rendering
+extern cvar_t *r_drawentities; // disable/enable entity rendering
+extern cvar_t *r_drawworld; // disable/enable world rendering
+extern cvar_t *r_speeds; // various levels of information display
+extern cvar_t *r_detailTextures; // enables/disables detail texturing stages
+extern cvar_t *r_novis; // disable/enable usage of PVS
+extern cvar_t *r_nocull;
+extern cvar_t *r_facePlaneCull; // enables culling of planar surfaces with back side test
+extern cvar_t *r_nocurves;
+extern cvar_t *r_showcluster;
+
+extern cvar_t *r_mode; // video mode
+extern cvar_t *r_fullscreen;
+extern cvar_t *r_gamma;
+extern cvar_t *r_displayRefresh; // optional display refresh option
+extern cvar_t *r_ignorehwgamma; // overrides hardware gamma capabilities
+
+extern cvar_t *r_allowExtensions; // global enable/disable of OpenGL extensions
+extern cvar_t *r_ext_compressed_textures; // these control use of specific extensions
+extern cvar_t *r_ext_gamma_control;
+extern cvar_t *r_ext_texenv_op;
+extern cvar_t *r_ext_multitexture;
+extern cvar_t *r_ext_compiled_vertex_array;
+extern cvar_t *r_ext_texture_env_add;
+
+extern cvar_t *r_nobind; // turns off binding to appropriate textures
+extern cvar_t *r_singleShader; // make most world faces use default shader
+extern cvar_t *r_roundImagesDown;
+extern cvar_t *r_colorMipLevels; // development aid to see texture mip usage
+extern cvar_t *r_picmip; // controls picmip values
+extern cvar_t *r_finish;
+extern cvar_t *r_drawBuffer;
+extern cvar_t *r_glDriver;
+extern cvar_t *r_swapInterval;
+extern cvar_t *r_textureMode;
+extern cvar_t *r_offsetFactor;
+extern cvar_t *r_offsetUnits;
+
+extern cvar_t *r_fullbright; // avoid lightmap pass
+extern cvar_t *r_lightmap; // render lightmaps only
+extern cvar_t *r_vertexLight; // vertex lighting mode for better performance
+extern cvar_t *r_uiFullScreen; // ui is running fullscreen
+
+extern cvar_t *r_logFile; // number of frames to emit GL logs
+extern cvar_t *r_showtris; // enables wireframe rendering of the world
+extern cvar_t *r_showsky; // forces sky in front of all surfaces
+extern cvar_t *r_shownormals; // draws wireframe normals
+extern cvar_t *r_clear; // force screen clear every frame
+
+extern cvar_t *r_shadows; // controls shadows: 0 = none, 1 = blur, 2 = stencil, 3 = black planar projection
+extern cvar_t *r_flares; // light flares
+
+extern cvar_t *r_intensity;
+
+extern cvar_t *r_lockpvs;
+extern cvar_t *r_noportals;
+extern cvar_t *r_portalOnly;
+
+extern cvar_t *r_subdivisions;
+extern cvar_t *r_lodCurveError;
+extern cvar_t *r_smp;
+extern cvar_t *r_showSmp;
+extern cvar_t *r_skipBackEnd;
+
+extern cvar_t *r_ignoreGLErrors;
+
+extern cvar_t *r_overBrightBits;
+extern cvar_t *r_mapOverBrightBits;
+
+extern cvar_t *r_debugSurface;
+extern cvar_t *r_simpleMipMaps;
+
+extern cvar_t *r_showImages;
+extern cvar_t *r_debugSort;
+
+extern cvar_t *r_printShaders;
+extern cvar_t *r_saveFontData;
+
+//====================================================================
+
+float R_NoiseGet4f( float x, float y, float z, float t );
+void R_NoiseInit( void );
+
+void R_SwapBuffers( int );
+
+void R_RenderView( viewParms_t *parms );
+
+void R_AddMD3Surfaces( trRefEntity_t *e );
+void R_AddNullModelSurfaces( trRefEntity_t *e );
+void R_AddBeamSurfaces( trRefEntity_t *e );
+void R_AddRailSurfaces( trRefEntity_t *e, qboolean isUnderwater );
+void R_AddLightningBoltSurfaces( trRefEntity_t *e );
+
+void R_AddPolygonSurfaces( void );
+
+void R_DecomposeSort( unsigned sort, int *entityNum, shader_t **shader,
+ int *fogNum, int *dlightMap );
+
+void R_AddDrawSurf( surfaceType_t *surface, shader_t *shader, int fogIndex, int dlightMap );
+
+
+#define CULL_IN 0 // completely unclipped
+#define CULL_CLIP 1 // clipped by one or more planes
+#define CULL_OUT 2 // completely outside the clipping planes
+void R_LocalNormalToWorld (vec3_t local, vec3_t world);
+void R_LocalPointToWorld (vec3_t local, vec3_t world);
+int R_CullLocalBox (vec3_t bounds[2]);
+int R_CullPointAndRadius( vec3_t origin, float radius );
+int R_CullLocalPointAndRadius( vec3_t origin, float radius );
+
+void R_RotateForEntity( const trRefEntity_t *ent, const viewParms_t *viewParms, orientationr_t *or );
+
+/*
+** GL wrapper/helper functions
+*/
+void GL_Bind( image_t *image );
+void GL_SetDefaultState (void);
+void GL_SelectTexture( int unit );
+void GL_TextureMode( const char *string );
+void GL_CheckErrors( void );
+void GL_State( unsigned long stateVector );
+void GL_TexEnv( int env );
+void GL_Cull( int cullType );
+
+#define GLS_SRCBLEND_ZERO 0x00000001
+#define GLS_SRCBLEND_ONE 0x00000002
+#define GLS_SRCBLEND_DST_COLOR 0x00000003
+#define GLS_SRCBLEND_ONE_MINUS_DST_COLOR 0x00000004
+#define GLS_SRCBLEND_SRC_ALPHA 0x00000005
+#define GLS_SRCBLEND_ONE_MINUS_SRC_ALPHA 0x00000006
+#define GLS_SRCBLEND_DST_ALPHA 0x00000007
+#define GLS_SRCBLEND_ONE_MINUS_DST_ALPHA 0x00000008
+#define GLS_SRCBLEND_ALPHA_SATURATE 0x00000009
+#define GLS_SRCBLEND_BITS 0x0000000f
+
+#define GLS_DSTBLEND_ZERO 0x00000010
+#define GLS_DSTBLEND_ONE 0x00000020
+#define GLS_DSTBLEND_SRC_COLOR 0x00000030
+#define GLS_DSTBLEND_ONE_MINUS_SRC_COLOR 0x00000040
+#define GLS_DSTBLEND_SRC_ALPHA 0x00000050
+#define GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA 0x00000060
+#define GLS_DSTBLEND_DST_ALPHA 0x00000070
+#define GLS_DSTBLEND_ONE_MINUS_DST_ALPHA 0x00000080
+#define GLS_DSTBLEND_BITS 0x000000f0
+
+#define GLS_DEPTHMASK_TRUE 0x00000100
+
+#define GLS_POLYMODE_LINE 0x00001000
+
+#define GLS_DEPTHTEST_DISABLE 0x00010000
+#define GLS_DEPTHFUNC_EQUAL 0x00020000
+
+#define GLS_ATEST_GT_0 0x10000000
+#define GLS_ATEST_LT_80 0x20000000
+#define GLS_ATEST_GE_80 0x40000000
+#define GLS_ATEST_BITS 0x70000000
+
+#define GLS_DEFAULT GLS_DEPTHMASK_TRUE
+
+void RE_StretchRaw (int x, int y, int w, int h, int cols, int rows, const byte *data, int client, qboolean dirty);
+void RE_UploadCinematic (int w, int h, int cols, int rows, const byte *data, int client, qboolean dirty);
+
+void RE_BeginFrame( stereoFrame_t stereoFrame );
+void RE_BeginRegistration( glconfig_t *glconfig );
+void RE_LoadWorldMap( const char *mapname );
+void RE_SetWorldVisData( const byte *vis );
+qhandle_t RE_RegisterModel( const char *name );
+qhandle_t RE_RegisterSkin( const char *name );
+void RE_Shutdown( qboolean destroyWindow );
+
+qboolean R_GetEntityToken( char *buffer, int size );
+
+model_t *R_AllocModel( void );
+
+void R_Init( void );
+image_t *R_FindImageFile( const char *name, qboolean mipmap, qboolean allowPicmip, int glWrapClampMode );
+
+image_t *R_CreateImage( const char *name, const byte *pic, int width, int height, qboolean mipmap
+ , qboolean allowPicmip, int wrapClampMode );
+qboolean R_GetModeInfo( int *width, int *height, float *windowAspect, int mode );
+
+void R_SetColorMappings( void );
+void R_GammaCorrect( byte *buffer, int bufSize );
+
+void R_ImageList_f( void );
+void R_SkinList_f( void );
+// https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=516
+const void *RB_TakeScreenshotCmd( const void *data );
+void R_ScreenShot_f( void );
+
+void R_InitFogTable( void );
+float R_FogFactor( float s, float t );
+void R_InitImages( void );
+void R_DeleteTextures( void );
+int R_SumOfUsedImages( void );
+void R_InitSkins( void );
+skin_t *R_GetSkinByHandle( qhandle_t hSkin );
+
+
+//
+// tr_shader.c
+//
+qhandle_t RE_RegisterShaderLightMap( const char *name, int lightmapIndex );
+qhandle_t RE_RegisterShader( const char *name );
+qhandle_t RE_RegisterShaderNoMip( const char *name );
+qhandle_t RE_RegisterShaderFromImage(const char *name, int lightmapIndex, image_t *image, qboolean mipRawImage);
+
+shader_t *R_FindShader( const char *name, int lightmapIndex, qboolean mipRawImage );
+shader_t *R_GetShaderByHandle( qhandle_t hShader );
+shader_t *R_GetShaderByState( int index, long *cycleTime );
+shader_t *R_FindShaderByName( const char *name );
+void R_InitShaders( void );
+void R_ShaderList_f( void );
+void R_RemapShader(const char *oldShader, const char *newShader, const char *timeOffset);
+
+/*
+====================================================================
+
+IMPLEMENTATION SPECIFIC FUNCTIONS
+
+====================================================================
+*/
+
+void GLimp_Init( void );
+void GLimp_Shutdown( void );
+void GLimp_EndFrame( void );
+
+qboolean GLimp_SpawnRenderThread( void (*function)( void ) );
+void *GLimp_RendererSleep( void );
+void GLimp_FrontEndSleep( void );
+void GLimp_WakeRenderer( void *data );
+
+void GLimp_LogComment( char *comment );
+
+// NOTE TTimo linux works with float gamma value, not the gamma table
+// the params won't be used, getting the r_gamma cvar directly
+void GLimp_SetGamma( unsigned char red[256],
+ unsigned char green[256],
+ unsigned char blue[256] );
+
+
+/*
+====================================================================
+
+TESSELATOR/SHADER DECLARATIONS
+
+====================================================================
+*/
+typedef byte color4ub_t[4];
+
+typedef struct stageVars
+{
+ color4ub_t colors[SHADER_MAX_VERTEXES];
+ vec2_t texcoords[NUM_TEXTURE_BUNDLES][SHADER_MAX_VERTEXES];
+} stageVars_t;
+
+typedef struct shaderCommands_s
+{
+ glIndex_t indexes[SHADER_MAX_INDEXES];
+ vec4_t xyz[SHADER_MAX_VERTEXES];
+ vec4_t normal[SHADER_MAX_VERTEXES];
+ vec2_t texCoords[SHADER_MAX_VERTEXES][2];
+ color4ub_t vertexColors[SHADER_MAX_VERTEXES];
+ int vertexDlightBits[SHADER_MAX_VERTEXES];
+
+ stageVars_t svars;
+
+ color4ub_t constantColor255[SHADER_MAX_VERTEXES];
+
+ shader_t *shader;
+ float shaderTime;
+ int fogNum;
+
+ int dlightBits; // or together of all vertexDlightBits
+
+ int numIndexes;
+ int numVertexes;
+
+ // info extracted from current shader
+ int numPasses;
+ void (*currentStageIteratorFunc)( void );
+ shaderStage_t **xstages;
+} shaderCommands_t;
+
+extern shaderCommands_t tess;
+
+void RB_BeginSurface(shader_t *shader, int fogNum );
+void RB_EndSurface(void);
+void RB_CheckOverflow( int verts, int indexes );
+#define RB_CHECKOVERFLOW(v,i) if (tess.numVertexes + (v) >= SHADER_MAX_VERTEXES || tess.numIndexes + (i) >= SHADER_MAX_INDEXES ) {RB_CheckOverflow(v,i);}
+
+void RB_StageIteratorGeneric( void );
+void RB_StageIteratorSky( void );
+void RB_StageIteratorVertexLitTexture( void );
+void RB_StageIteratorLightmappedMultitexture( void );
+
+void RB_AddQuadStamp( vec3_t origin, vec3_t left, vec3_t up, byte *color );
+void RB_AddQuadStampExt( vec3_t origin, vec3_t left, vec3_t up, byte *color, float s1, float t1, float s2, float t2 );
+
+void RB_ShowImages( void );
+
+
+/*
+============================================================
+
+WORLD MAP
+
+============================================================
+*/
+
+void R_AddBrushModelSurfaces( trRefEntity_t *e );
+void R_AddWorldSurfaces( void );
+qboolean R_inPVS( const vec3_t p1, const vec3_t p2 );
+
+
+/*
+============================================================
+
+FLARES
+
+============================================================
+*/
+
+void R_ClearFlares( void );
+
+void RB_AddFlare( void *surface, int fogNum, vec3_t point, vec3_t color, vec3_t normal );
+void RB_AddDlightFlares( void );
+void RB_RenderFlares (void);
+
+/*
+============================================================
+
+LIGHTS
+
+============================================================
+*/
+
+void R_DlightBmodel( bmodel_t *bmodel );
+void R_SetupEntityLighting( const trRefdef_t *refdef, trRefEntity_t *ent );
+void R_TransformDlights( int count, dlight_t *dl, orientationr_t *or );
+int R_LightForPoint( vec3_t point, vec3_t ambientLight, vec3_t directedLight, vec3_t lightDir );
+
+
+/*
+============================================================
+
+SHADOWS
+
+============================================================
+*/
+
+void RB_ShadowTessEnd( void );
+void RB_ShadowFinish( void );
+void RB_ProjectionShadowDeform( void );
+
+/*
+============================================================
+
+SKIES
+
+============================================================
+*/
+
+void R_BuildCloudData( shaderCommands_t *shader );
+void R_InitSkyTexCoords( float cloudLayerHeight );
+void R_DrawSkyBox( shaderCommands_t *shader );
+void RB_DrawSun( void );
+void RB_ClipSkyPolygons( shaderCommands_t *shader );
+
+/*
+============================================================
+
+CURVE TESSELATION
+
+============================================================
+*/
+
+#define PATCH_STITCHING
+
+srfGridMesh_t *R_SubdividePatchToGrid( int width, int height,
+ drawVert_t points[MAX_PATCH_SIZE*MAX_PATCH_SIZE] );
+srfGridMesh_t *R_GridInsertColumn( srfGridMesh_t *grid, int column, int row, vec3_t point, float loderror );
+srfGridMesh_t *R_GridInsertRow( srfGridMesh_t *grid, int row, int column, vec3_t point, float loderror );
+void R_FreeSurfaceGridMesh( srfGridMesh_t *grid );
+
+/*
+============================================================
+
+MARKERS, POLYGON PROJECTION ON WORLD POLYGONS
+
+============================================================
+*/
+
+int R_MarkFragments( int numPoints, const vec3_t *points, const vec3_t projection,
+ int maxPoints, vec3_t pointBuffer, int maxFragments, markFragment_t *fragmentBuffer );
+
+
+/*
+============================================================
+
+SCENE GENERATION
+
+============================================================
+*/
+
+void R_ToggleSmpFrame( void );
+
+void RE_ClearScene( void );
+void RE_AddRefEntityToScene( const refEntity_t *ent );
+void RE_AddPolyToScene( qhandle_t hShader , int numVerts, const polyVert_t *verts, int num );
+void RE_AddLightToScene( const vec3_t org, float intensity, float r, float g, float b );
+void RE_AddAdditiveLightToScene( const vec3_t org, float intensity, float r, float g, float b );
+void RE_RenderScene( const refdef_t *fd );
+
+/*
+=============================================================
+
+ANIMATED MODELS
+
+=============================================================
+*/
+
+void R_MakeAnimModel( model_t *model );
+void R_AddAnimSurfaces( trRefEntity_t *ent );
+void RB_SurfaceAnim( md4Surface_t *surfType );
+
+/*
+=============================================================
+=============================================================
+*/
+void R_TransformModelToClip( const vec3_t src, const float *modelMatrix, const float *projectionMatrix,
+ vec4_t eye, vec4_t dst );
+void R_TransformClipToWindow( const vec4_t clip, const viewParms_t *view, vec4_t normalized, vec4_t window );
+
+void RB_DeformTessGeometry( void );
+
+void RB_CalcEnvironmentTexCoords( float *dstTexCoords );
+void RB_CalcFogTexCoords( float *dstTexCoords );
+void RB_CalcScrollTexCoords( const float scroll[2], float *dstTexCoords );
+void RB_CalcRotateTexCoords( float rotSpeed, float *dstTexCoords );
+void RB_CalcScaleTexCoords( const float scale[2], float *dstTexCoords );
+void RB_CalcTurbulentTexCoords( const waveForm_t *wf, float *dstTexCoords );
+void RB_CalcTransformTexCoords( const texModInfo_t *tmi, float *dstTexCoords );
+void RB_CalcModulateColorsByFog( unsigned char *dstColors );
+void RB_CalcModulateAlphasByFog( unsigned char *dstColors );
+void RB_CalcModulateRGBAsByFog( unsigned char *dstColors );
+void RB_CalcWaveAlpha( const waveForm_t *wf, unsigned char *dstColors );
+void RB_CalcWaveColor( const waveForm_t *wf, unsigned char *dstColors );
+void RB_CalcAlphaFromEntity( unsigned char *dstColors );
+void RB_CalcAlphaFromOneMinusEntity( unsigned char *dstColors );
+void RB_CalcStretchTexCoords( const waveForm_t *wf, float *texCoords );
+void RB_CalcColorFromEntity( unsigned char *dstColors );
+void RB_CalcColorFromOneMinusEntity( unsigned char *dstColors );
+void RB_CalcSpecularAlpha( unsigned char *alphas );
+void RB_CalcDiffuseColor( unsigned char *colors );
+
+/*
+=============================================================
+
+RENDERER BACK END FUNCTIONS
+
+=============================================================
+*/
+
+void RB_RenderThread( void );
+void RB_ExecuteRenderCommands( const void *data );
+
+/*
+=============================================================
+
+RENDERER BACK END COMMAND QUEUE
+
+=============================================================
+*/
+
+#define MAX_RENDER_COMMANDS 0x40000
+
+typedef struct {
+ byte cmds[MAX_RENDER_COMMANDS];
+ int used;
+} renderCommandList_t;
+
+typedef struct {
+ int commandId;
+ float color[4];
+} setColorCommand_t;
+
+typedef struct {
+ int commandId;
+ int buffer;
+} drawBufferCommand_t;
+
+typedef struct {
+ int commandId;
+ image_t *image;
+ int width;
+ int height;
+ void *data;
+} subImageCommand_t;
+
+typedef struct {
+ int commandId;
+} swapBuffersCommand_t;
+
+typedef struct {
+ int commandId;
+ int buffer;
+} endFrameCommand_t;
+
+typedef struct {
+ int commandId;
+ shader_t *shader;
+ float x, y;
+ float w, h;
+ float s1, t1;
+ float s2, t2;
+} stretchPicCommand_t;
+
+typedef struct {
+ int commandId;
+ trRefdef_t refdef;
+ viewParms_t viewParms;
+ drawSurf_t *drawSurfs;
+ int numDrawSurfs;
+} drawSurfsCommand_t;
+
+typedef struct {
+ int commandId;
+ int x;
+ int y;
+ int width;
+ int height;
+ char *fileName;
+ qboolean jpeg;
+} screenshotCommand_t;
+
+typedef enum {
+ RC_END_OF_LIST,
+ RC_SET_COLOR,
+ RC_STRETCH_PIC,
+ RC_DRAW_SURFS,
+ RC_DRAW_BUFFER,
+ RC_SWAP_BUFFERS,
+ RC_SCREENSHOT
+} renderCommand_t;
+
+
+// these are sort of arbitrary limits.
+// the limits apply to the sum of all scenes in a frame --
+// the main view, all the 3D icons, etc
+#define MAX_POLYS 600
+#define MAX_POLYVERTS 3000
+
+// all of the information needed by the back end must be
+// contained in a backEndData_t. This entire structure is
+// duplicated so the front and back end can run in parallel
+// on an SMP machine
+typedef struct {
+ drawSurf_t drawSurfs[MAX_DRAWSURFS];
+ dlight_t dlights[MAX_DLIGHTS];
+ trRefEntity_t entities[MAX_ENTITIES];
+ srfPoly_t *polys;//[MAX_POLYS];
+ polyVert_t *polyVerts;//[MAX_POLYVERTS];
+ renderCommandList_t commands;
+} backEndData_t;
+
+extern int max_polys;
+extern int max_polyverts;
+
+extern backEndData_t *backEndData[SMP_FRAMES]; // the second one may not be allocated
+
+extern volatile renderCommandList_t *renderCommandList;
+
+extern volatile qboolean renderThreadActive;
+
+
+void *R_GetCommandBuffer( int bytes );
+void RB_ExecuteRenderCommands( const void *data );
+
+void R_InitCommandBuffers( void );
+void R_ShutdownCommandBuffers( void );
+
+void R_SyncRenderThread( void );
+
+void R_AddDrawSurfCmd( drawSurf_t *drawSurfs, int numDrawSurfs );
+
+void RE_SetColor( const float *rgba );
+void RE_StretchPic ( float x, float y, float w, float h,
+ float s1, float t1, float s2, float t2, qhandle_t hShader );
+void RE_BeginFrame( stereoFrame_t stereoFrame );
+void RE_EndFrame( int *frontEndMsec, int *backEndMsec );
+void SaveJPG(char * filename, int quality, int image_width, int image_height, unsigned char *image_buffer);
+
+// font stuff
+void R_InitFreeType();
+void R_DoneFreeType();
+void RE_RegisterFont(const char *fontName, int pointSize, fontInfo_t *font);
+
+
+#endif //TR_LOCAL_H
diff --git a/code/renderer/tr_main.c b/code/renderer/tr_main.c
new file mode 100755
index 0000000..7b054ca
--- /dev/null
+++ b/code/renderer/tr_main.c
@@ -0,0 +1,1485 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// tr_main.c -- main control flow for each frame
+
+#include "tr_local.h"
+
+trGlobals_t tr;
+
+static float s_flipMatrix[16] = {
+ // convert from our coordinate system (looking down X)
+ // to OpenGL's coordinate system (looking down -Z)
+ 0, 0, -1, 0,
+ -1, 0, 0, 0,
+ 0, 1, 0, 0,
+ 0, 0, 0, 1
+};
+
+
+refimport_t ri;
+
+// entities that will have procedurally generated surfaces will just
+// point at this for their sorting surface
+surfaceType_t entitySurface = SF_ENTITY;
+
+/*
+=================
+R_CullLocalBox
+
+Returns CULL_IN, CULL_CLIP, or CULL_OUT
+=================
+*/
+int R_CullLocalBox (vec3_t bounds[2]) {
+ int i, j;
+ vec3_t transformed[8];
+ float dists[8];
+ vec3_t v;
+ cplane_t *frust;
+ int anyBack;
+ int front, back;
+
+ if ( r_nocull->integer ) {
+ return CULL_CLIP;
+ }
+
+ // transform into world space
+ for (i = 0 ; i < 8 ; i++) {
+ v[0] = bounds[i&1][0];
+ v[1] = bounds[(i>>1)&1][1];
+ v[2] = bounds[(i>>2)&1][2];
+
+ VectorCopy( tr.or.origin, transformed[i] );
+ VectorMA( transformed[i], v[0], tr.or.axis[0], transformed[i] );
+ VectorMA( transformed[i], v[1], tr.or.axis[1], transformed[i] );
+ VectorMA( transformed[i], v[2], tr.or.axis[2], transformed[i] );
+ }
+
+ // check against frustum planes
+ anyBack = 0;
+ for (i = 0 ; i < 4 ; i++) {
+ frust = &tr.viewParms.frustum[i];
+
+ front = back = 0;
+ for (j = 0 ; j < 8 ; j++) {
+ dists[j] = DotProduct(transformed[j], frust->normal);
+ if ( dists[j] > frust->dist ) {
+ front = 1;
+ if ( back ) {
+ break; // a point is in front
+ }
+ } else {
+ back = 1;
+ }
+ }
+ if ( !front ) {
+ // all points were behind one of the planes
+ return CULL_OUT;
+ }
+ anyBack |= back;
+ }
+
+ if ( !anyBack ) {
+ return CULL_IN; // completely inside frustum
+ }
+
+ return CULL_CLIP; // partially clipped
+}
+
+/*
+** R_CullLocalPointAndRadius
+*/
+int R_CullLocalPointAndRadius( vec3_t pt, float radius )
+{
+ vec3_t transformed;
+
+ R_LocalPointToWorld( pt, transformed );
+
+ return R_CullPointAndRadius( transformed, radius );
+}
+
+/*
+** R_CullPointAndRadius
+*/
+int R_CullPointAndRadius( vec3_t pt, float radius )
+{
+ int i;
+ float dist;
+ cplane_t *frust;
+ qboolean mightBeClipped = qfalse;
+
+ if ( r_nocull->integer ) {
+ return CULL_CLIP;
+ }
+
+ // check against frustum planes
+ for (i = 0 ; i < 4 ; i++)
+ {
+ frust = &tr.viewParms.frustum[i];
+
+ dist = DotProduct( pt, frust->normal) - frust->dist;
+ if ( dist < -radius )
+ {
+ return CULL_OUT;
+ }
+ else if ( dist <= radius )
+ {
+ mightBeClipped = qtrue;
+ }
+ }
+
+ if ( mightBeClipped )
+ {
+ return CULL_CLIP;
+ }
+
+ return CULL_IN; // completely inside frustum
+}
+
+
+/*
+=================
+R_LocalNormalToWorld
+
+=================
+*/
+void R_LocalNormalToWorld (vec3_t local, vec3_t world) {
+ world[0] = local[0] * tr.or.axis[0][0] + local[1] * tr.or.axis[1][0] + local[2] * tr.or.axis[2][0];
+ world[1] = local[0] * tr.or.axis[0][1] + local[1] * tr.or.axis[1][1] + local[2] * tr.or.axis[2][1];
+ world[2] = local[0] * tr.or.axis[0][2] + local[1] * tr.or.axis[1][2] + local[2] * tr.or.axis[2][2];
+}
+
+/*
+=================
+R_LocalPointToWorld
+
+=================
+*/
+void R_LocalPointToWorld (vec3_t local, vec3_t world) {
+ world[0] = local[0] * tr.or.axis[0][0] + local[1] * tr.or.axis[1][0] + local[2] * tr.or.axis[2][0] + tr.or.origin[0];
+ world[1] = local[0] * tr.or.axis[0][1] + local[1] * tr.or.axis[1][1] + local[2] * tr.or.axis[2][1] + tr.or.origin[1];
+ world[2] = local[0] * tr.or.axis[0][2] + local[1] * tr.or.axis[1][2] + local[2] * tr.or.axis[2][2] + tr.or.origin[2];
+}
+
+/*
+=================
+R_WorldToLocal
+
+=================
+*/
+void R_WorldToLocal (vec3_t world, vec3_t local) {
+ local[0] = DotProduct(world, tr.or.axis[0]);
+ local[1] = DotProduct(world, tr.or.axis[1]);
+ local[2] = DotProduct(world, tr.or.axis[2]);
+}
+
+/*
+==========================
+R_TransformModelToClip
+
+==========================
+*/
+void R_TransformModelToClip( const vec3_t src, const float *modelMatrix, const float *projectionMatrix,
+ vec4_t eye, vec4_t dst ) {
+ int i;
+
+ for ( i = 0 ; i < 4 ; i++ ) {
+ eye[i] =
+ src[0] * modelMatrix[ i + 0 * 4 ] +
+ src[1] * modelMatrix[ i + 1 * 4 ] +
+ src[2] * modelMatrix[ i + 2 * 4 ] +
+ 1 * modelMatrix[ i + 3 * 4 ];
+ }
+
+ for ( i = 0 ; i < 4 ; i++ ) {
+ dst[i] =
+ eye[0] * projectionMatrix[ i + 0 * 4 ] +
+ eye[1] * projectionMatrix[ i + 1 * 4 ] +
+ eye[2] * projectionMatrix[ i + 2 * 4 ] +
+ eye[3] * projectionMatrix[ i + 3 * 4 ];
+ }
+}
+
+/*
+==========================
+R_TransformClipToWindow
+
+==========================
+*/
+void R_TransformClipToWindow( const vec4_t clip, const viewParms_t *view, vec4_t normalized, vec4_t window ) {
+ normalized[0] = clip[0] / clip[3];
+ normalized[1] = clip[1] / clip[3];
+ normalized[2] = ( clip[2] + clip[3] ) / ( 2 * clip[3] );
+
+ window[0] = 0.5f * ( 1.0f + normalized[0] ) * view->viewportWidth;
+ window[1] = 0.5f * ( 1.0f + normalized[1] ) * view->viewportHeight;
+ window[2] = normalized[2];
+
+ window[0] = (int) ( window[0] + 0.5 );
+ window[1] = (int) ( window[1] + 0.5 );
+}
+
+
+/*
+==========================
+myGlMultMatrix
+
+==========================
+*/
+void myGlMultMatrix( const float *a, const float *b, float *out ) {
+ int i, j;
+
+ for ( i = 0 ; i < 4 ; i++ ) {
+ for ( j = 0 ; j < 4 ; j++ ) {
+ out[ i * 4 + j ] =
+ a [ i * 4 + 0 ] * b [ 0 * 4 + j ]
+ + a [ i * 4 + 1 ] * b [ 1 * 4 + j ]
+ + a [ i * 4 + 2 ] * b [ 2 * 4 + j ]
+ + a [ i * 4 + 3 ] * b [ 3 * 4 + j ];
+ }
+ }
+}
+
+/*
+=================
+R_RotateForEntity
+
+Generates an orientation for an entity and viewParms
+Does NOT produce any GL calls
+Called by both the front end and the back end
+=================
+*/
+void R_RotateForEntity( const trRefEntity_t *ent, const viewParms_t *viewParms,
+ orientationr_t *or ) {
+ float glMatrix[16];
+ vec3_t delta;
+ float axisLength;
+
+ if ( ent->e.reType != RT_MODEL ) {
+ *or = viewParms->world;
+ return;
+ }
+
+ VectorCopy( ent->e.origin, or->origin );
+
+ VectorCopy( ent->e.axis[0], or->axis[0] );
+ VectorCopy( ent->e.axis[1], or->axis[1] );
+ VectorCopy( ent->e.axis[2], or->axis[2] );
+
+ glMatrix[0] = or->axis[0][0];
+ glMatrix[4] = or->axis[1][0];
+ glMatrix[8] = or->axis[2][0];
+ glMatrix[12] = or->origin[0];
+
+ glMatrix[1] = or->axis[0][1];
+ glMatrix[5] = or->axis[1][1];
+ glMatrix[9] = or->axis[2][1];
+ glMatrix[13] = or->origin[1];
+
+ glMatrix[2] = or->axis[0][2];
+ glMatrix[6] = or->axis[1][2];
+ glMatrix[10] = or->axis[2][2];
+ glMatrix[14] = or->origin[2];
+
+ glMatrix[3] = 0;
+ glMatrix[7] = 0;
+ glMatrix[11] = 0;
+ glMatrix[15] = 1;
+
+ myGlMultMatrix( glMatrix, viewParms->world.modelMatrix, or->modelMatrix );
+
+ // calculate the viewer origin in the model's space
+ // needed for fog, specular, and environment mapping
+ VectorSubtract( viewParms->or.origin, or->origin, delta );
+
+ // compensate for scale in the axes if necessary
+ if ( ent->e.nonNormalizedAxes ) {
+ axisLength = VectorLength( ent->e.axis[0] );
+ if ( !axisLength ) {
+ axisLength = 0;
+ } else {
+ axisLength = 1.0f / axisLength;
+ }
+ } else {
+ axisLength = 1.0f;
+ }
+
+ or->viewOrigin[0] = DotProduct( delta, or->axis[0] ) * axisLength;
+ or->viewOrigin[1] = DotProduct( delta, or->axis[1] ) * axisLength;
+ or->viewOrigin[2] = DotProduct( delta, or->axis[2] ) * axisLength;
+}
+
+/*
+=================
+R_RotateForViewer
+
+Sets up the modelview matrix for a given viewParm
+=================
+*/
+void R_RotateForViewer (void)
+{
+ float viewerMatrix[16];
+ vec3_t origin;
+
+ Com_Memset (&tr.or, 0, sizeof(tr.or));
+ tr.or.axis[0][0] = 1;
+ tr.or.axis[1][1] = 1;
+ tr.or.axis[2][2] = 1;
+ VectorCopy (tr.viewParms.or.origin, tr.or.viewOrigin);
+
+ // transform by the camera placement
+ VectorCopy( tr.viewParms.or.origin, origin );
+
+ viewerMatrix[0] = tr.viewParms.or.axis[0][0];
+ viewerMatrix[4] = tr.viewParms.or.axis[0][1];
+ viewerMatrix[8] = tr.viewParms.or.axis[0][2];
+ viewerMatrix[12] = -origin[0] * viewerMatrix[0] + -origin[1] * viewerMatrix[4] + -origin[2] * viewerMatrix[8];
+
+ viewerMatrix[1] = tr.viewParms.or.axis[1][0];
+ viewerMatrix[5] = tr.viewParms.or.axis[1][1];
+ viewerMatrix[9] = tr.viewParms.or.axis[1][2];
+ viewerMatrix[13] = -origin[0] * viewerMatrix[1] + -origin[1] * viewerMatrix[5] + -origin[2] * viewerMatrix[9];
+
+ viewerMatrix[2] = tr.viewParms.or.axis[2][0];
+ viewerMatrix[6] = tr.viewParms.or.axis[2][1];
+ viewerMatrix[10] = tr.viewParms.or.axis[2][2];
+ viewerMatrix[14] = -origin[0] * viewerMatrix[2] + -origin[1] * viewerMatrix[6] + -origin[2] * viewerMatrix[10];
+
+ viewerMatrix[3] = 0;
+ viewerMatrix[7] = 0;
+ viewerMatrix[11] = 0;
+ viewerMatrix[15] = 1;
+
+ // convert from our coordinate system (looking down X)
+ // to OpenGL's coordinate system (looking down -Z)
+ myGlMultMatrix( viewerMatrix, s_flipMatrix, tr.or.modelMatrix );
+
+ tr.viewParms.world = tr.or;
+
+}
+
+/*
+** SetFarClip
+*/
+static void SetFarClip( void )
+{
+ float farthestCornerDistance = 0;
+ int i;
+
+ // if not rendering the world (icons, menus, etc)
+ // set a 2k far clip plane
+ if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) {
+ tr.viewParms.zFar = 2048;
+ return;
+ }
+
+ //
+ // set far clipping planes dynamically
+ //
+ farthestCornerDistance = 0;
+ for ( i = 0; i < 8; i++ )
+ {
+ vec3_t v;
+ vec3_t vecTo;
+ float distance;
+
+ if ( i & 1 )
+ {
+ v[0] = tr.viewParms.visBounds[0][0];
+ }
+ else
+ {
+ v[0] = tr.viewParms.visBounds[1][0];
+ }
+
+ if ( i & 2 )
+ {
+ v[1] = tr.viewParms.visBounds[0][1];
+ }
+ else
+ {
+ v[1] = tr.viewParms.visBounds[1][1];
+ }
+
+ if ( i & 4 )
+ {
+ v[2] = tr.viewParms.visBounds[0][2];
+ }
+ else
+ {
+ v[2] = tr.viewParms.visBounds[1][2];
+ }
+
+ VectorSubtract( v, tr.viewParms.or.origin, vecTo );
+
+ distance = vecTo[0] * vecTo[0] + vecTo[1] * vecTo[1] + vecTo[2] * vecTo[2];
+
+ if ( distance > farthestCornerDistance )
+ {
+ farthestCornerDistance = distance;
+ }
+ }
+ tr.viewParms.zFar = sqrt( farthestCornerDistance );
+}
+
+
+/*
+===============
+R_SetupProjection
+===============
+*/
+void R_SetupProjection( void ) {
+ float xmin, xmax, ymin, ymax;
+ float width, height, depth;
+ float zNear, zFar;
+
+ // dynamically compute far clip plane distance
+ SetFarClip();
+
+ //
+ // set up projection matrix
+ //
+ zNear = r_znear->value;
+ zFar = tr.viewParms.zFar;
+
+ ymax = zNear * tan( tr.refdef.fov_y * M_PI / 360.0f );
+ ymin = -ymax;
+
+ xmax = zNear * tan( tr.refdef.fov_x * M_PI / 360.0f );
+ xmin = -xmax;
+
+ width = xmax - xmin;
+ height = ymax - ymin;
+ depth = zFar - zNear;
+
+ tr.viewParms.projectionMatrix[0] = 2 * zNear / width;
+ tr.viewParms.projectionMatrix[4] = 0;
+ tr.viewParms.projectionMatrix[8] = ( xmax + xmin ) / width; // normally 0
+ tr.viewParms.projectionMatrix[12] = 0;
+
+ tr.viewParms.projectionMatrix[1] = 0;
+ tr.viewParms.projectionMatrix[5] = 2 * zNear / height;
+ tr.viewParms.projectionMatrix[9] = ( ymax + ymin ) / height; // normally 0
+ tr.viewParms.projectionMatrix[13] = 0;
+
+ tr.viewParms.projectionMatrix[2] = 0;
+ tr.viewParms.projectionMatrix[6] = 0;
+ tr.viewParms.projectionMatrix[10] = -( zFar + zNear ) / depth;
+ tr.viewParms.projectionMatrix[14] = -2 * zFar * zNear / depth;
+
+ tr.viewParms.projectionMatrix[3] = 0;
+ tr.viewParms.projectionMatrix[7] = 0;
+ tr.viewParms.projectionMatrix[11] = -1;
+ tr.viewParms.projectionMatrix[15] = 0;
+}
+
+/*
+=================
+R_SetupFrustum
+
+Setup that culling frustum planes for the current view
+=================
+*/
+void R_SetupFrustum (void) {
+ int i;
+ float xs, xc;
+ float ang;
+
+ ang = tr.viewParms.fovX / 180 * M_PI * 0.5f;
+ xs = sin( ang );
+ xc = cos( ang );
+
+ VectorScale( tr.viewParms.or.axis[0], xs, tr.viewParms.frustum[0].normal );
+ VectorMA( tr.viewParms.frustum[0].normal, xc, tr.viewParms.or.axis[1], tr.viewParms.frustum[0].normal );
+
+ VectorScale( tr.viewParms.or.axis[0], xs, tr.viewParms.frustum[1].normal );
+ VectorMA( tr.viewParms.frustum[1].normal, -xc, tr.viewParms.or.axis[1], tr.viewParms.frustum[1].normal );
+
+ ang = tr.viewParms.fovY / 180 * M_PI * 0.5f;
+ xs = sin( ang );
+ xc = cos( ang );
+
+ VectorScale( tr.viewParms.or.axis[0], xs, tr.viewParms.frustum[2].normal );
+ VectorMA( tr.viewParms.frustum[2].normal, xc, tr.viewParms.or.axis[2], tr.viewParms.frustum[2].normal );
+
+ VectorScale( tr.viewParms.or.axis[0], xs, tr.viewParms.frustum[3].normal );
+ VectorMA( tr.viewParms.frustum[3].normal, -xc, tr.viewParms.or.axis[2], tr.viewParms.frustum[3].normal );
+
+ for (i=0 ; i<4 ; i++) {
+ tr.viewParms.frustum[i].type = PLANE_NON_AXIAL;
+ tr.viewParms.frustum[i].dist = DotProduct (tr.viewParms.or.origin, tr.viewParms.frustum[i].normal);
+ SetPlaneSignbits( &tr.viewParms.frustum[i] );
+ }
+}
+
+
+/*
+=================
+R_MirrorPoint
+=================
+*/
+void R_MirrorPoint (vec3_t in, orientation_t *surface, orientation_t *camera, vec3_t out) {
+ int i;
+ vec3_t local;
+ vec3_t transformed;
+ float d;
+
+ VectorSubtract( in, surface->origin, local );
+
+ VectorClear( transformed );
+ for ( i = 0 ; i < 3 ; i++ ) {
+ d = DotProduct(local, surface->axis[i]);
+ VectorMA( transformed, d, camera->axis[i], transformed );
+ }
+
+ VectorAdd( transformed, camera->origin, out );
+}
+
+void R_MirrorVector (vec3_t in, orientation_t *surface, orientation_t *camera, vec3_t out) {
+ int i;
+ float d;
+
+ VectorClear( out );
+ for ( i = 0 ; i < 3 ; i++ ) {
+ d = DotProduct(in, surface->axis[i]);
+ VectorMA( out, d, camera->axis[i], out );
+ }
+}
+
+
+/*
+=============
+R_PlaneForSurface
+=============
+*/
+void R_PlaneForSurface (surfaceType_t *surfType, cplane_t *plane) {
+ srfTriangles_t *tri;
+ srfPoly_t *poly;
+ drawVert_t *v1, *v2, *v3;
+ vec4_t plane4;
+
+ if (!surfType) {
+ Com_Memset (plane, 0, sizeof(*plane));
+ plane->normal[0] = 1;
+ return;
+ }
+ switch (*surfType) {
+ case SF_FACE:
+ *plane = ((srfSurfaceFace_t *)surfType)->plane;
+ return;
+ case SF_TRIANGLES:
+ tri = (srfTriangles_t *)surfType;
+ v1 = tri->verts + tri->indexes[0];
+ v2 = tri->verts + tri->indexes[1];
+ v3 = tri->verts + tri->indexes[2];
+ PlaneFromPoints( plane4, v1->xyz, v2->xyz, v3->xyz );
+ VectorCopy( plane4, plane->normal );
+ plane->dist = plane4[3];
+ return;
+ case SF_POLY:
+ poly = (srfPoly_t *)surfType;
+ PlaneFromPoints( plane4, poly->verts[0].xyz, poly->verts[1].xyz, poly->verts[2].xyz );
+ VectorCopy( plane4, plane->normal );
+ plane->dist = plane4[3];
+ return;
+ default:
+ Com_Memset (plane, 0, sizeof(*plane));
+ plane->normal[0] = 1;
+ return;
+ }
+}
+
+/*
+=================
+R_GetPortalOrientation
+
+entityNum is the entity that the portal surface is a part of, which may
+be moving and rotating.
+
+Returns qtrue if it should be mirrored
+=================
+*/
+qboolean R_GetPortalOrientations( drawSurf_t *drawSurf, int entityNum,
+ orientation_t *surface, orientation_t *camera,
+ vec3_t pvsOrigin, qboolean *mirror ) {
+ int i;
+ cplane_t originalPlane, plane;
+ trRefEntity_t *e;
+ float d;
+ vec3_t transformed;
+
+ // create plane axis for the portal we are seeing
+ R_PlaneForSurface( drawSurf->surface, &originalPlane );
+
+ // rotate the plane if necessary
+ if ( entityNum != ENTITYNUM_WORLD ) {
+ tr.currentEntityNum = entityNum;
+ tr.currentEntity = &tr.refdef.entities[entityNum];
+
+ // get the orientation of the entity
+ R_RotateForEntity( tr.currentEntity, &tr.viewParms, &tr.or );
+
+ // rotate the plane, but keep the non-rotated version for matching
+ // against the portalSurface entities
+ R_LocalNormalToWorld( originalPlane.normal, plane.normal );
+ plane.dist = originalPlane.dist + DotProduct( plane.normal, tr.or.origin );
+
+ // translate the original plane
+ originalPlane.dist = originalPlane.dist + DotProduct( originalPlane.normal, tr.or.origin );
+ } else {
+ plane = originalPlane;
+ }
+
+ VectorCopy( plane.normal, surface->axis[0] );
+ PerpendicularVector( surface->axis[1], surface->axis[0] );
+ CrossProduct( surface->axis[0], surface->axis[1], surface->axis[2] );
+
+ // locate the portal entity closest to this plane.
+ // origin will be the origin of the portal, origin2 will be
+ // the origin of the camera
+ for ( i = 0 ; i < tr.refdef.num_entities ; i++ ) {
+ e = &tr.refdef.entities[i];
+ if ( e->e.reType != RT_PORTALSURFACE ) {
+ continue;
+ }
+
+ d = DotProduct( e->e.origin, originalPlane.normal ) - originalPlane.dist;
+ if ( d > 64 || d < -64) {
+ continue;
+ }
+
+ // get the pvsOrigin from the entity
+ VectorCopy( e->e.oldorigin, pvsOrigin );
+
+ // if the entity is just a mirror, don't use as a camera point
+ if ( e->e.oldorigin[0] == e->e.origin[0] &&
+ e->e.oldorigin[1] == e->e.origin[1] &&
+ e->e.oldorigin[2] == e->e.origin[2] ) {
+ VectorScale( plane.normal, plane.dist, surface->origin );
+ VectorCopy( surface->origin, camera->origin );
+ VectorSubtract( vec3_origin, surface->axis[0], camera->axis[0] );
+ VectorCopy( surface->axis[1], camera->axis[1] );
+ VectorCopy( surface->axis[2], camera->axis[2] );
+
+ *mirror = qtrue;
+ return qtrue;
+ }
+
+ // project the origin onto the surface plane to get
+ // an origin point we can rotate around
+ d = DotProduct( e->e.origin, plane.normal ) - plane.dist;
+ VectorMA( e->e.origin, -d, surface->axis[0], surface->origin );
+
+ // now get the camera origin and orientation
+ VectorCopy( e->e.oldorigin, camera->origin );
+ AxisCopy( e->e.axis, camera->axis );
+ VectorSubtract( vec3_origin, camera->axis[0], camera->axis[0] );
+ VectorSubtract( vec3_origin, camera->axis[1], camera->axis[1] );
+
+ // optionally rotate
+ if ( e->e.oldframe ) {
+ // if a speed is specified
+ if ( e->e.frame ) {
+ // continuous rotate
+ d = (tr.refdef.time/1000.0f) * e->e.frame;
+ VectorCopy( camera->axis[1], transformed );
+ RotatePointAroundVector( camera->axis[1], camera->axis[0], transformed, d );
+ CrossProduct( camera->axis[0], camera->axis[1], camera->axis[2] );
+ } else {
+ // bobbing rotate, with skinNum being the rotation offset
+ d = sin( tr.refdef.time * 0.003f );
+ d = e->e.skinNum + d * 4;
+ VectorCopy( camera->axis[1], transformed );
+ RotatePointAroundVector( camera->axis[1], camera->axis[0], transformed, d );
+ CrossProduct( camera->axis[0], camera->axis[1], camera->axis[2] );
+ }
+ }
+ else if ( e->e.skinNum ) {
+ d = e->e.skinNum;
+ VectorCopy( camera->axis[1], transformed );
+ RotatePointAroundVector( camera->axis[1], camera->axis[0], transformed, d );
+ CrossProduct( camera->axis[0], camera->axis[1], camera->axis[2] );
+ }
+ *mirror = qfalse;
+ return qtrue;
+ }
+
+ // if we didn't locate a portal entity, don't render anything.
+ // We don't want to just treat it as a mirror, because without a
+ // portal entity the server won't have communicated a proper entity set
+ // in the snapshot
+
+ // unfortunately, with local movement prediction it is easily possible
+ // to see a surface before the server has communicated the matching
+ // portal surface entity, so we don't want to print anything here...
+
+ //ri.Printf( PRINT_ALL, "Portal surface without a portal entity\n" );
+
+ return qfalse;
+}
+
+static qboolean IsMirror( const drawSurf_t *drawSurf, int entityNum )
+{
+ int i;
+ cplane_t originalPlane, plane;
+ trRefEntity_t *e;
+ float d;
+
+ // create plane axis for the portal we are seeing
+ R_PlaneForSurface( drawSurf->surface, &originalPlane );
+
+ // rotate the plane if necessary
+ if ( entityNum != ENTITYNUM_WORLD )
+ {
+ tr.currentEntityNum = entityNum;
+ tr.currentEntity = &tr.refdef.entities[entityNum];
+
+ // get the orientation of the entity
+ R_RotateForEntity( tr.currentEntity, &tr.viewParms, &tr.or );
+
+ // rotate the plane, but keep the non-rotated version for matching
+ // against the portalSurface entities
+ R_LocalNormalToWorld( originalPlane.normal, plane.normal );
+ plane.dist = originalPlane.dist + DotProduct( plane.normal, tr.or.origin );
+
+ // translate the original plane
+ originalPlane.dist = originalPlane.dist + DotProduct( originalPlane.normal, tr.or.origin );
+ }
+ else
+ {
+ plane = originalPlane;
+ }
+
+ // locate the portal entity closest to this plane.
+ // origin will be the origin of the portal, origin2 will be
+ // the origin of the camera
+ for ( i = 0 ; i < tr.refdef.num_entities ; i++ )
+ {
+ e = &tr.refdef.entities[i];
+ if ( e->e.reType != RT_PORTALSURFACE ) {
+ continue;
+ }
+
+ d = DotProduct( e->e.origin, originalPlane.normal ) - originalPlane.dist;
+ if ( d > 64 || d < -64) {
+ continue;
+ }
+
+ // if the entity is just a mirror, don't use as a camera point
+ if ( e->e.oldorigin[0] == e->e.origin[0] &&
+ e->e.oldorigin[1] == e->e.origin[1] &&
+ e->e.oldorigin[2] == e->e.origin[2] )
+ {
+ return qtrue;
+ }
+
+ return qfalse;
+ }
+ return qfalse;
+}
+
+/*
+** SurfIsOffscreen
+**
+** Determines if a surface is completely offscreen.
+*/
+static qboolean SurfIsOffscreen( const drawSurf_t *drawSurf, vec4_t clipDest[128] ) {
+ float shortest = 100000000;
+ int entityNum;
+ int numTriangles;
+ shader_t *shader;
+ int fogNum;
+ int dlighted;
+ vec4_t clip, eye;
+ int i;
+ unsigned int pointOr = 0;
+ unsigned int pointAnd = (unsigned int)~0;
+
+ if ( glConfig.smpActive ) { // FIXME! we can't do RB_BeginSurface/RB_EndSurface stuff with smp!
+ return qfalse;
+ }
+
+ R_RotateForViewer();
+
+ R_DecomposeSort( drawSurf->sort, &entityNum, &shader, &fogNum, &dlighted );
+ RB_BeginSurface( shader, fogNum );
+ rb_surfaceTable[ *drawSurf->surface ]( drawSurf->surface );
+
+ assert( tess.numVertexes < 128 );
+
+ for ( i = 0; i < tess.numVertexes; i++ )
+ {
+ int j;
+ unsigned int pointFlags = 0;
+
+ R_TransformModelToClip( tess.xyz[i], tr.or.modelMatrix, tr.viewParms.projectionMatrix, eye, clip );
+
+ for ( j = 0; j < 3; j++ )
+ {
+ if ( clip[j] >= clip[3] )
+ {
+ pointFlags |= (1 << (j*2));
+ }
+ else if ( clip[j] <= -clip[3] )
+ {
+ pointFlags |= ( 1 << (j*2+1));
+ }
+ }
+ pointAnd &= pointFlags;
+ pointOr |= pointFlags;
+ }
+
+ // trivially reject
+ if ( pointAnd )
+ {
+ return qtrue;
+ }
+
+ // determine if this surface is backfaced and also determine the distance
+ // to the nearest vertex so we can cull based on portal range. Culling
+ // based on vertex distance isn't 100% correct (we should be checking for
+ // range to the surface), but it's good enough for the types of portals
+ // we have in the game right now.
+ numTriangles = tess.numIndexes / 3;
+
+ for ( i = 0; i < tess.numIndexes; i += 3 )
+ {
+ vec3_t normal;
+ float dot;
+ float len;
+
+ VectorSubtract( tess.xyz[tess.indexes[i]], tr.viewParms.or.origin, normal );
+
+ len = VectorLengthSquared( normal ); // lose the sqrt
+ if ( len < shortest )
+ {
+ shortest = len;
+ }
+
+ if ( ( dot = DotProduct( normal, tess.normal[tess.indexes[i]] ) ) >= 0 )
+ {
+ numTriangles--;
+ }
+ }
+ if ( !numTriangles )
+ {
+ return qtrue;
+ }
+
+ // mirrors can early out at this point, since we don't do a fade over distance
+ // with them (although we could)
+ if ( IsMirror( drawSurf, entityNum ) )
+ {
+ return qfalse;
+ }
+
+ if ( shortest > (tess.shader->portalRange*tess.shader->portalRange) )
+ {
+ return qtrue;
+ }
+
+ return qfalse;
+}
+
+/*
+========================
+R_MirrorViewBySurface
+
+Returns qtrue if another view has been rendered
+========================
+*/
+qboolean R_MirrorViewBySurface (drawSurf_t *drawSurf, int entityNum) {
+ vec4_t clipDest[128];
+ viewParms_t newParms;
+ viewParms_t oldParms;
+ orientation_t surface, camera;
+
+ // don't recursively mirror
+ if (tr.viewParms.isPortal) {
+ ri.Printf( PRINT_DEVELOPER, "WARNING: recursive mirror/portal found\n" );
+ return qfalse;
+ }
+
+ if ( r_noportals->integer || (r_fastsky->integer == 1) ) {
+ return qfalse;
+ }
+
+ // trivially reject portal/mirror
+ if ( SurfIsOffscreen( drawSurf, clipDest ) ) {
+ return qfalse;
+ }
+
+ // save old viewParms so we can return to it after the mirror view
+ oldParms = tr.viewParms;
+
+ newParms = tr.viewParms;
+ newParms.isPortal = qtrue;
+ if ( !R_GetPortalOrientations( drawSurf, entityNum, &surface, &camera,
+ newParms.pvsOrigin, &newParms.isMirror ) ) {
+ return qfalse; // bad portal, no portalentity
+ }
+
+ R_MirrorPoint (oldParms.or.origin, &surface, &camera, newParms.or.origin );
+
+ VectorSubtract( vec3_origin, camera.axis[0], newParms.portalPlane.normal );
+ newParms.portalPlane.dist = DotProduct( camera.origin, newParms.portalPlane.normal );
+
+ R_MirrorVector (oldParms.or.axis[0], &surface, &camera, newParms.or.axis[0]);
+ R_MirrorVector (oldParms.or.axis[1], &surface, &camera, newParms.or.axis[1]);
+ R_MirrorVector (oldParms.or.axis[2], &surface, &camera, newParms.or.axis[2]);
+
+ // OPTIMIZE: restrict the viewport on the mirrored view
+
+ // render the mirror view
+ R_RenderView (&newParms);
+
+ tr.viewParms = oldParms;
+
+ return qtrue;
+}
+
+/*
+=================
+R_SpriteFogNum
+
+See if a sprite is inside a fog volume
+=================
+*/
+int R_SpriteFogNum( trRefEntity_t *ent ) {
+ int i, j;
+ fog_t *fog;
+
+ if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) {
+ return 0;
+ }
+
+ for ( i = 1 ; i < tr.world->numfogs ; i++ ) {
+ fog = &tr.world->fogs[i];
+ for ( j = 0 ; j < 3 ; j++ ) {
+ if ( ent->e.origin[j] - ent->e.radius >= fog->bounds[1][j] ) {
+ break;
+ }
+ if ( ent->e.origin[j] + ent->e.radius <= fog->bounds[0][j] ) {
+ break;
+ }
+ }
+ if ( j == 3 ) {
+ return i;
+ }
+ }
+
+ return 0;
+}
+
+/*
+==========================================================================================
+
+DRAWSURF SORTING
+
+==========================================================================================
+*/
+
+/*
+=================
+qsort replacement
+
+=================
+*/
+#define SWAP_DRAW_SURF(a,b) temp=((int *)a)[0];((int *)a)[0]=((int *)b)[0];((int *)b)[0]=temp; temp=((int *)a)[1];((int *)a)[1]=((int *)b)[1];((int *)b)[1]=temp;
+
+/* this parameter defines the cutoff between using quick sort and
+ insertion sort for arrays; arrays with lengths shorter or equal to the
+ below value use insertion sort */
+
+#define CUTOFF 8 /* testing shows that this is good value */
+
+static void shortsort( drawSurf_t *lo, drawSurf_t *hi ) {
+ drawSurf_t *p, *max;
+ int temp;
+
+ while (hi > lo) {
+ max = lo;
+ for (p = lo + 1; p <= hi; p++ ) {
+ if ( p->sort > max->sort ) {
+ max = p;
+ }
+ }
+ SWAP_DRAW_SURF(max, hi);
+ hi--;
+ }
+}
+
+
+/* sort the array between lo and hi (inclusive)
+FIXME: this was lifted and modified from the microsoft lib source...
+ */
+
+void qsortFast (
+ void *base,
+ unsigned num,
+ unsigned width
+ )
+{
+ char *lo, *hi; /* ends of sub-array currently sorting */
+ char *mid; /* points to middle of subarray */
+ char *loguy, *higuy; /* traveling pointers for partition step */
+ unsigned size; /* size of the sub-array */
+ char *lostk[30], *histk[30];
+ int stkptr; /* stack for saving sub-array to be processed */
+ int temp;
+
+ if ( sizeof(drawSurf_t) != 8 ) {
+ ri.Error( ERR_DROP, "change SWAP_DRAW_SURF macro" );
+ }
+
+ /* Note: the number of stack entries required is no more than
+ 1 + log2(size), so 30 is sufficient for any array */
+
+ if (num < 2 || width == 0)
+ return; /* nothing to do */
+
+ stkptr = 0; /* initialize stack */
+
+ lo = base;
+ hi = (char *)base + width * (num-1); /* initialize limits */
+
+ /* this entry point is for pseudo-recursion calling: setting
+ lo and hi and jumping to here is like recursion, but stkptr is
+ prserved, locals aren't, so we preserve stuff on the stack */
+recurse:
+
+ size = (hi - lo) / width + 1; /* number of el's to sort */
+
+ /* below a certain size, it is faster to use a O(n^2) sorting method */
+ if (size <= CUTOFF) {
+ shortsort((drawSurf_t *)lo, (drawSurf_t *)hi);
+ }
+ else {
+ /* First we pick a partititioning element. The efficiency of the
+ algorithm demands that we find one that is approximately the
+ median of the values, but also that we select one fast. Using
+ the first one produces bad performace if the array is already
+ sorted, so we use the middle one, which would require a very
+ wierdly arranged array for worst case performance. Testing shows
+ that a median-of-three algorithm does not, in general, increase
+ performance. */
+
+ mid = lo + (size / 2) * width; /* find middle element */
+ SWAP_DRAW_SURF(mid, lo); /* swap it to beginning of array */
+
+ /* We now wish to partition the array into three pieces, one
+ consisiting of elements <= partition element, one of elements
+ equal to the parition element, and one of element >= to it. This
+ is done below; comments indicate conditions established at every
+ step. */
+
+ loguy = lo;
+ higuy = hi + width;
+
+ /* Note that higuy decreases and loguy increases on every iteration,
+ so loop must terminate. */
+ for (;;) {
+ /* lo <= loguy < hi, lo < higuy <= hi + 1,
+ A[i] <= A[lo] for lo <= i <= loguy,
+ A[i] >= A[lo] for higuy <= i <= hi */
+
+ do {
+ loguy += width;
+ } while (loguy <= hi &&
+ ( ((drawSurf_t *)loguy)->sort <= ((drawSurf_t *)lo)->sort ) );
+
+ /* lo < loguy <= hi+1, A[i] <= A[lo] for lo <= i < loguy,
+ either loguy > hi or A[loguy] > A[lo] */
+
+ do {
+ higuy -= width;
+ } while (higuy > lo &&
+ ( ((drawSurf_t *)higuy)->sort >= ((drawSurf_t *)lo)->sort ) );
+
+ /* lo-1 <= higuy <= hi, A[i] >= A[lo] for higuy < i <= hi,
+ either higuy <= lo or A[higuy] < A[lo] */
+
+ if (higuy < loguy)
+ break;
+
+ /* if loguy > hi or higuy <= lo, then we would have exited, so
+ A[loguy] > A[lo], A[higuy] < A[lo],
+ loguy < hi, highy > lo */
+
+ SWAP_DRAW_SURF(loguy, higuy);
+
+ /* A[loguy] < A[lo], A[higuy] > A[lo]; so condition at top
+ of loop is re-established */
+ }
+
+ /* A[i] >= A[lo] for higuy < i <= hi,
+ A[i] <= A[lo] for lo <= i < loguy,
+ higuy < loguy, lo <= higuy <= hi
+ implying:
+ A[i] >= A[lo] for loguy <= i <= hi,
+ A[i] <= A[lo] for lo <= i <= higuy,
+ A[i] = A[lo] for higuy < i < loguy */
+
+ SWAP_DRAW_SURF(lo, higuy); /* put partition element in place */
+
+ /* OK, now we have the following:
+ A[i] >= A[higuy] for loguy <= i <= hi,
+ A[i] <= A[higuy] for lo <= i < higuy
+ A[i] = A[lo] for higuy <= i < loguy */
+
+ /* We've finished the partition, now we want to sort the subarrays
+ [lo, higuy-1] and [loguy, hi].
+ We do the smaller one first to minimize stack usage.
+ We only sort arrays of length 2 or more.*/
+
+ if ( higuy - 1 - lo >= hi - loguy ) {
+ if (lo + width < higuy) {
+ lostk[stkptr] = lo;
+ histk[stkptr] = higuy - width;
+ ++stkptr;
+ } /* save big recursion for later */
+
+ if (loguy < hi) {
+ lo = loguy;
+ goto recurse; /* do small recursion */
+ }
+ }
+ else {
+ if (loguy < hi) {
+ lostk[stkptr] = loguy;
+ histk[stkptr] = hi;
+ ++stkptr; /* save big recursion for later */
+ }
+
+ if (lo + width < higuy) {
+ hi = higuy - width;
+ goto recurse; /* do small recursion */
+ }
+ }
+ }
+
+ /* We have sorted the array, except for any pending sorts on the stack.
+ Check if there are any, and do them. */
+
+ --stkptr;
+ if (stkptr >= 0) {
+ lo = lostk[stkptr];
+ hi = histk[stkptr];
+ goto recurse; /* pop subarray from stack */
+ }
+ else
+ return; /* all subarrays done */
+}
+
+
+//==========================================================================================
+
+/*
+=================
+R_AddDrawSurf
+=================
+*/
+void R_AddDrawSurf( surfaceType_t *surface, shader_t *shader,
+ int fogIndex, int dlightMap ) {
+ int index;
+
+ // instead of checking for overflow, we just mask the index
+ // so it wraps around
+ index = tr.refdef.numDrawSurfs & DRAWSURF_MASK;
+ // the sort data is packed into a single 32 bit value so it can be
+ // compared quickly during the qsorting process
+ tr.refdef.drawSurfs[index].sort = (shader->sortedIndex << QSORT_SHADERNUM_SHIFT)
+ | tr.shiftedEntityNum | ( fogIndex << QSORT_FOGNUM_SHIFT ) | (int)dlightMap;
+ tr.refdef.drawSurfs[index].surface = surface;
+ tr.refdef.numDrawSurfs++;
+}
+
+/*
+=================
+R_DecomposeSort
+=================
+*/
+void R_DecomposeSort( unsigned sort, int *entityNum, shader_t **shader,
+ int *fogNum, int *dlightMap ) {
+ *fogNum = ( sort >> QSORT_FOGNUM_SHIFT ) & 31;
+ *shader = tr.sortedShaders[ ( sort >> QSORT_SHADERNUM_SHIFT ) & (MAX_SHADERS-1) ];
+ *entityNum = ( sort >> QSORT_ENTITYNUM_SHIFT ) & 1023;
+ *dlightMap = sort & 3;
+}
+
+/*
+=================
+R_SortDrawSurfs
+=================
+*/
+void R_SortDrawSurfs( drawSurf_t *drawSurfs, int numDrawSurfs ) {
+ shader_t *shader;
+ int fogNum;
+ int entityNum;
+ int dlighted;
+ int i;
+
+ // it is possible for some views to not have any surfaces
+ if ( numDrawSurfs < 1 ) {
+ // we still need to add it for hyperspace cases
+ R_AddDrawSurfCmd( drawSurfs, numDrawSurfs );
+ return;
+ }
+
+ // if we overflowed MAX_DRAWSURFS, the drawsurfs
+ // wrapped around in the buffer and we will be missing
+ // the first surfaces, not the last ones
+ if ( numDrawSurfs > MAX_DRAWSURFS ) {
+ numDrawSurfs = MAX_DRAWSURFS;
+ }
+
+ // sort the drawsurfs by sort type, then orientation, then shader
+ qsortFast (drawSurfs, numDrawSurfs, sizeof(drawSurf_t) );
+
+ // check for any pass through drawing, which
+ // may cause another view to be rendered first
+ for ( i = 0 ; i < numDrawSurfs ; i++ ) {
+ R_DecomposeSort( (drawSurfs+i)->sort, &entityNum, &shader, &fogNum, &dlighted );
+
+ if ( shader->sort > SS_PORTAL ) {
+ break;
+ }
+
+ // no shader should ever have this sort type
+ if ( shader->sort == SS_BAD ) {
+ ri.Error (ERR_DROP, "Shader '%s'with sort == SS_BAD", shader->name );
+ }
+
+ // if the mirror was completely clipped away, we may need to check another surface
+ if ( R_MirrorViewBySurface( (drawSurfs+i), entityNum) ) {
+ // this is a debug option to see exactly what is being mirrored
+ if ( r_portalOnly->integer ) {
+ return;
+ }
+ break; // only one mirror view at a time
+ }
+ }
+
+ R_AddDrawSurfCmd( drawSurfs, numDrawSurfs );
+}
+
+/*
+=============
+R_AddEntitySurfaces
+=============
+*/
+void R_AddEntitySurfaces (void) {
+ trRefEntity_t *ent;
+ shader_t *shader;
+
+ if ( !r_drawentities->integer ) {
+ return;
+ }
+
+ for ( tr.currentEntityNum = 0;
+ tr.currentEntityNum < tr.refdef.num_entities;
+ tr.currentEntityNum++ ) {
+ ent = tr.currentEntity = &tr.refdef.entities[tr.currentEntityNum];
+
+ ent->needDlights = qfalse;
+
+ // preshift the value we are going to OR into the drawsurf sort
+ tr.shiftedEntityNum = tr.currentEntityNum << QSORT_ENTITYNUM_SHIFT;
+
+ //
+ // the weapon model must be handled special --
+ // we don't want the hacked weapon position showing in
+ // mirrors, because the true body position will already be drawn
+ //
+ if ( (ent->e.renderfx & RF_FIRST_PERSON) && tr.viewParms.isPortal) {
+ continue;
+ }
+
+ // simple generated models, like sprites and beams, are not culled
+ switch ( ent->e.reType ) {
+ case RT_PORTALSURFACE:
+ break; // don't draw anything
+ case RT_SPRITE:
+ case RT_BEAM:
+ case RT_LIGHTNING:
+ case RT_RAIL_CORE:
+ case RT_RAIL_RINGS:
+ // self blood sprites, talk balloons, etc should not be drawn in the primary
+ // view. We can't just do this check for all entities, because md3
+ // entities may still want to cast shadows from them
+ if ( (ent->e.renderfx & RF_THIRD_PERSON) && !tr.viewParms.isPortal) {
+ continue;
+ }
+ shader = R_GetShaderByHandle( ent->e.customShader );
+ R_AddDrawSurf( &entitySurface, shader, R_SpriteFogNum( ent ), 0 );
+ break;
+
+ case RT_MODEL:
+ // we must set up parts of tr.or for model culling
+ R_RotateForEntity( ent, &tr.viewParms, &tr.or );
+
+ tr.currentModel = R_GetModelByHandle( ent->e.hModel );
+ if (!tr.currentModel) {
+ R_AddDrawSurf( &entitySurface, tr.defaultShader, 0, 0 );
+ } else {
+ switch ( tr.currentModel->type ) {
+ case MOD_MESH:
+ R_AddMD3Surfaces( ent );
+ break;
+ case MOD_MD4:
+ R_AddAnimSurfaces( ent );
+ break;
+ case MOD_BRUSH:
+ R_AddBrushModelSurfaces( ent );
+ break;
+ case MOD_BAD: // null model axis
+ if ( (ent->e.renderfx & RF_THIRD_PERSON) && !tr.viewParms.isPortal) {
+ break;
+ }
+ shader = R_GetShaderByHandle( ent->e.customShader );
+ R_AddDrawSurf( &entitySurface, tr.defaultShader, 0, 0 );
+ break;
+ default:
+ ri.Error( ERR_DROP, "R_AddEntitySurfaces: Bad modeltype" );
+ break;
+ }
+ }
+ break;
+ default:
+ ri.Error( ERR_DROP, "R_AddEntitySurfaces: Bad reType" );
+ }
+ }
+
+}
+
+
+/*
+====================
+R_GenerateDrawSurfs
+====================
+*/
+void R_GenerateDrawSurfs( void ) {
+ R_AddWorldSurfaces ();
+
+ R_AddPolygonSurfaces();
+
+ // set the projection matrix with the minimum zfar
+ // now that we have the world bounded
+ // this needs to be done before entities are
+ // added, because they use the projection
+ // matrix for lod calculation
+ R_SetupProjection ();
+
+ R_AddEntitySurfaces ();
+}
+
+/*
+================
+R_DebugPolygon
+================
+*/
+void R_DebugPolygon( int color, int numPoints, float *points ) {
+ int i;
+
+ GL_State( GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE );
+
+ // draw solid shade
+
+ qglColor3f( color&1, (color>>1)&1, (color>>2)&1 );
+ qglBegin( GL_POLYGON );
+ for ( i = 0 ; i < numPoints ; i++ ) {
+ qglVertex3fv( points + i * 3 );
+ }
+ qglEnd();
+
+ // draw wireframe outline
+ GL_State( GLS_POLYMODE_LINE | GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE );
+ qglDepthRange( 0, 0 );
+ qglColor3f( 1, 1, 1 );
+ qglBegin( GL_POLYGON );
+ for ( i = 0 ; i < numPoints ; i++ ) {
+ qglVertex3fv( points + i * 3 );
+ }
+ qglEnd();
+ qglDepthRange( 0, 1 );
+}
+
+/*
+====================
+R_DebugGraphics
+
+Visualization aid for movement clipping debugging
+====================
+*/
+void R_DebugGraphics( void ) {
+ if ( !r_debugSurface->integer ) {
+ return;
+ }
+
+ // the render thread can't make callbacks to the main thread
+ R_SyncRenderThread();
+
+ GL_Bind( tr.whiteImage);
+ GL_Cull( CT_FRONT_SIDED );
+ ri.CM_DrawDebugSurface( R_DebugPolygon );
+}
+
+
+/*
+================
+R_RenderView
+
+A view may be either the actual camera view,
+or a mirror / remote location
+================
+*/
+void R_RenderView (viewParms_t *parms) {
+ int firstDrawSurf;
+
+ if ( parms->viewportWidth <= 0 || parms->viewportHeight <= 0 ) {
+ return;
+ }
+
+ tr.viewCount++;
+
+ tr.viewParms = *parms;
+ tr.viewParms.frameSceneNum = tr.frameSceneNum;
+ tr.viewParms.frameCount = tr.frameCount;
+
+ firstDrawSurf = tr.refdef.numDrawSurfs;
+
+ tr.viewCount++;
+
+ // set viewParms.world
+ R_RotateForViewer ();
+
+ R_SetupFrustum ();
+
+ R_GenerateDrawSurfs();
+
+ R_SortDrawSurfs( tr.refdef.drawSurfs + firstDrawSurf, tr.refdef.numDrawSurfs - firstDrawSurf );
+
+ // draw main system development information (surface outlines, etc)
+ R_DebugGraphics();
+}
+
+
+
diff --git a/code/renderer/tr_marks.c b/code/renderer/tr_marks.c
new file mode 100755
index 0000000..f5f6e97
--- /dev/null
+++ b/code/renderer/tr_marks.c
@@ -0,0 +1,443 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// tr_marks.c -- polygon projection on the world polygons
+
+#include "tr_local.h"
+//#include "assert.h"
+
+#define MAX_VERTS_ON_POLY 64
+
+#define MARKER_OFFSET 0 // 1
+
+/*
+=============
+R_ChopPolyBehindPlane
+
+Out must have space for two more vertexes than in
+=============
+*/
+#define SIDE_FRONT 0
+#define SIDE_BACK 1
+#define SIDE_ON 2
+static void R_ChopPolyBehindPlane( int numInPoints, vec3_t inPoints[MAX_VERTS_ON_POLY],
+ int *numOutPoints, vec3_t outPoints[MAX_VERTS_ON_POLY],
+ vec3_t normal, vec_t dist, vec_t epsilon) {
+ float dists[MAX_VERTS_ON_POLY+4];
+ int sides[MAX_VERTS_ON_POLY+4];
+ int counts[3];
+ float dot;
+ int i, j;
+ float *p1, *p2, *clip;
+ float d;
+
+ // don't clip if it might overflow
+ if ( numInPoints >= MAX_VERTS_ON_POLY - 2 ) {
+ *numOutPoints = 0;
+ return;
+ }
+
+ counts[0] = counts[1] = counts[2] = 0;
+
+ // determine sides for each point
+ for ( i = 0 ; i < numInPoints ; i++ ) {
+ dot = DotProduct( inPoints[i], normal );
+ dot -= dist;
+ dists[i] = dot;
+ if ( dot > epsilon ) {
+ sides[i] = SIDE_FRONT;
+ } else if ( dot < -epsilon ) {
+ sides[i] = SIDE_BACK;
+ } else {
+ sides[i] = SIDE_ON;
+ }
+ counts[sides[i]]++;
+ }
+ sides[i] = sides[0];
+ dists[i] = dists[0];
+
+ *numOutPoints = 0;
+
+ if ( !counts[0] ) {
+ return;
+ }
+ if ( !counts[1] ) {
+ *numOutPoints = numInPoints;
+ Com_Memcpy( outPoints, inPoints, numInPoints * sizeof(vec3_t) );
+ return;
+ }
+
+ for ( i = 0 ; i < numInPoints ; i++ ) {
+ p1 = inPoints[i];
+ clip = outPoints[ *numOutPoints ];
+
+ if ( sides[i] == SIDE_ON ) {
+ VectorCopy( p1, clip );
+ (*numOutPoints)++;
+ continue;
+ }
+
+ if ( sides[i] == SIDE_FRONT ) {
+ VectorCopy( p1, clip );
+ (*numOutPoints)++;
+ clip = outPoints[ *numOutPoints ];
+ }
+
+ if ( sides[i+1] == SIDE_ON || sides[i+1] == sides[i] ) {
+ continue;
+ }
+
+ // generate a split point
+ p2 = inPoints[ (i+1) % numInPoints ];
+
+ d = dists[i] - dists[i+1];
+ if ( d == 0 ) {
+ dot = 0;
+ } else {
+ dot = dists[i] / d;
+ }
+
+ // clip xyz
+
+ for (j=0 ; j<3 ; j++) {
+ clip[j] = p1[j] + dot * ( p2[j] - p1[j] );
+ }
+
+ (*numOutPoints)++;
+ }
+}
+
+/*
+=================
+R_BoxSurfaces_r
+
+=================
+*/
+void R_BoxSurfaces_r(mnode_t *node, vec3_t mins, vec3_t maxs, surfaceType_t **list, int listsize, int *listlength, vec3_t dir) {
+
+ int s, c;
+ msurface_t *surf, **mark;
+
+ // do the tail recursion in a loop
+ while ( node->contents == -1 ) {
+ s = BoxOnPlaneSide( mins, maxs, node->plane );
+ if (s == 1) {
+ node = node->children[0];
+ } else if (s == 2) {
+ node = node->children[1];
+ } else {
+ R_BoxSurfaces_r(node->children[0], mins, maxs, list, listsize, listlength, dir);
+ node = node->children[1];
+ }
+ }
+
+ // add the individual surfaces
+ mark = node->firstmarksurface;
+ c = node->nummarksurfaces;
+ while (c--) {
+ //
+ if (*listlength >= listsize) break;
+ //
+ surf = *mark;
+ // check if the surface has NOIMPACT or NOMARKS set
+ if ( ( surf->shader->surfaceFlags & ( SURF_NOIMPACT | SURF_NOMARKS ) )
+ || ( surf->shader->contentFlags & CONTENTS_FOG ) ) {
+ surf->viewCount = tr.viewCount;
+ }
+ // extra check for surfaces to avoid list overflows
+ else if (*(surf->data) == SF_FACE) {
+ // the face plane should go through the box
+ s = BoxOnPlaneSide( mins, maxs, &(( srfSurfaceFace_t * ) surf->data)->plane );
+ if (s == 1 || s == 2) {
+ surf->viewCount = tr.viewCount;
+ } else if (DotProduct((( srfSurfaceFace_t * ) surf->data)->plane.normal, dir) > -0.5) {
+ // don't add faces that make sharp angles with the projection direction
+ surf->viewCount = tr.viewCount;
+ }
+ }
+ else if (*(surfaceType_t *) (surf->data) != SF_GRID) surf->viewCount = tr.viewCount;
+ // check the viewCount because the surface may have
+ // already been added if it spans multiple leafs
+ if (surf->viewCount != tr.viewCount) {
+ surf->viewCount = tr.viewCount;
+ list[*listlength] = (surfaceType_t *) surf->data;
+ (*listlength)++;
+ }
+ mark++;
+ }
+}
+
+/*
+=================
+R_AddMarkFragments
+
+=================
+*/
+void R_AddMarkFragments(int numClipPoints, vec3_t clipPoints[2][MAX_VERTS_ON_POLY],
+ int numPlanes, vec3_t *normals, float *dists,
+ int maxPoints, vec3_t pointBuffer,
+ int maxFragments, markFragment_t *fragmentBuffer,
+ int *returnedPoints, int *returnedFragments,
+ vec3_t mins, vec3_t maxs) {
+ int pingPong, i;
+ markFragment_t *mf;
+
+ // chop the surface by all the bounding planes of the to be projected polygon
+ pingPong = 0;
+
+ for ( i = 0 ; i < numPlanes ; i++ ) {
+
+ R_ChopPolyBehindPlane( numClipPoints, clipPoints[pingPong],
+ &numClipPoints, clipPoints[!pingPong],
+ normals[i], dists[i], 0.5 );
+ pingPong ^= 1;
+ if ( numClipPoints == 0 ) {
+ break;
+ }
+ }
+ // completely clipped away?
+ if ( numClipPoints == 0 ) {
+ return;
+ }
+
+ // add this fragment to the returned list
+ if ( numClipPoints + (*returnedPoints) > maxPoints ) {
+ return; // not enough space for this polygon
+ }
+ /*
+ // all the clip points should be within the bounding box
+ for ( i = 0 ; i < numClipPoints ; i++ ) {
+ int j;
+ for ( j = 0 ; j < 3 ; j++ ) {
+ if (clipPoints[pingPong][i][j] < mins[j] - 0.5) break;
+ if (clipPoints[pingPong][i][j] > maxs[j] + 0.5) break;
+ }
+ if (j < 3) break;
+ }
+ if (i < numClipPoints) return;
+ */
+
+ mf = fragmentBuffer + (*returnedFragments);
+ mf->firstPoint = (*returnedPoints);
+ mf->numPoints = numClipPoints;
+ Com_Memcpy( pointBuffer + (*returnedPoints) * 3, clipPoints[pingPong], numClipPoints * sizeof(vec3_t) );
+
+ (*returnedPoints) += numClipPoints;
+ (*returnedFragments)++;
+}
+
+/*
+=================
+R_MarkFragments
+
+=================
+*/
+int R_MarkFragments( int numPoints, const vec3_t *points, const vec3_t projection,
+ int maxPoints, vec3_t pointBuffer, int maxFragments, markFragment_t *fragmentBuffer ) {
+ int numsurfaces, numPlanes;
+ int i, j, k, m, n;
+ surfaceType_t *surfaces[64];
+ vec3_t mins, maxs;
+ int returnedFragments;
+ int returnedPoints;
+ vec3_t normals[MAX_VERTS_ON_POLY+2];
+ float dists[MAX_VERTS_ON_POLY+2];
+ vec3_t clipPoints[2][MAX_VERTS_ON_POLY];
+ int numClipPoints;
+ float *v;
+ srfSurfaceFace_t *surf;
+ srfGridMesh_t *cv;
+ drawVert_t *dv;
+ vec3_t normal;
+ vec3_t projectionDir;
+ vec3_t v1, v2;
+ int *indexes;
+
+ //increment view count for double check prevention
+ tr.viewCount++;
+
+ //
+ VectorNormalize2( projection, projectionDir );
+ // find all the brushes that are to be considered
+ ClearBounds( mins, maxs );
+ for ( i = 0 ; i < numPoints ; i++ ) {
+ vec3_t temp;
+
+ AddPointToBounds( points[i], mins, maxs );
+ VectorAdd( points[i], projection, temp );
+ AddPointToBounds( temp, mins, maxs );
+ // make sure we get all the leafs (also the one(s) in front of the hit surface)
+ VectorMA( points[i], -20, projectionDir, temp );
+ AddPointToBounds( temp, mins, maxs );
+ }
+
+ if (numPoints > MAX_VERTS_ON_POLY) numPoints = MAX_VERTS_ON_POLY;
+ // create the bounding planes for the to be projected polygon
+ for ( i = 0 ; i < numPoints ; i++ ) {
+ VectorSubtract(points[(i+1)%numPoints], points[i], v1);
+ VectorAdd(points[i], projection, v2);
+ VectorSubtract(points[i], v2, v2);
+ CrossProduct(v1, v2, normals[i]);
+ VectorNormalizeFast(normals[i]);
+ dists[i] = DotProduct(normals[i], points[i]);
+ }
+ // add near and far clipping planes for projection
+ VectorCopy(projectionDir, normals[numPoints]);
+ dists[numPoints] = DotProduct(normals[numPoints], points[0]) - 32;
+ VectorCopy(projectionDir, normals[numPoints+1]);
+ VectorInverse(normals[numPoints+1]);
+ dists[numPoints+1] = DotProduct(normals[numPoints+1], points[0]) - 20;
+ numPlanes = numPoints + 2;
+
+ numsurfaces = 0;
+ R_BoxSurfaces_r(tr.world->nodes, mins, maxs, surfaces, 64, &numsurfaces, projectionDir);
+ //assert(numsurfaces <= 64);
+ //assert(numsurfaces != 64);
+
+ returnedPoints = 0;
+ returnedFragments = 0;
+
+ for ( i = 0 ; i < numsurfaces ; i++ ) {
+
+ if (*surfaces[i] == SF_GRID) {
+
+ cv = (srfGridMesh_t *) surfaces[i];
+ for ( m = 0 ; m < cv->height - 1 ; m++ ) {
+ for ( n = 0 ; n < cv->width - 1 ; n++ ) {
+ // We triangulate the grid and chop all triangles within
+ // the bounding planes of the to be projected polygon.
+ // LOD is not taken into account, not such a big deal though.
+ //
+ // It's probably much nicer to chop the grid itself and deal
+ // with this grid as a normal SF_GRID surface so LOD will
+ // be applied. However the LOD of that chopped grid must
+ // be synced with the LOD of the original curve.
+ // One way to do this; the chopped grid shares vertices with
+ // the original curve. When LOD is applied to the original
+ // curve the unused vertices are flagged. Now the chopped curve
+ // should skip the flagged vertices. This still leaves the
+ // problems with the vertices at the chopped grid edges.
+ //
+ // To avoid issues when LOD applied to "hollow curves" (like
+ // the ones around many jump pads) we now just add a 2 unit
+ // offset to the triangle vertices.
+ // The offset is added in the vertex normal vector direction
+ // so all triangles will still fit together.
+ // The 2 unit offset should avoid pretty much all LOD problems.
+
+ numClipPoints = 3;
+
+ dv = cv->verts + m * cv->width + n;
+
+ VectorCopy(dv[0].xyz, clipPoints[0][0]);
+ VectorMA(clipPoints[0][0], MARKER_OFFSET, dv[0].normal, clipPoints[0][0]);
+ VectorCopy(dv[cv->width].xyz, clipPoints[0][1]);
+ VectorMA(clipPoints[0][1], MARKER_OFFSET, dv[cv->width].normal, clipPoints[0][1]);
+ VectorCopy(dv[1].xyz, clipPoints[0][2]);
+ VectorMA(clipPoints[0][2], MARKER_OFFSET, dv[1].normal, clipPoints[0][2]);
+ // check the normal of this triangle
+ VectorSubtract(clipPoints[0][0], clipPoints[0][1], v1);
+ VectorSubtract(clipPoints[0][2], clipPoints[0][1], v2);
+ CrossProduct(v1, v2, normal);
+ VectorNormalizeFast(normal);
+ if (DotProduct(normal, projectionDir) < -0.1) {
+ // add the fragments of this triangle
+ R_AddMarkFragments(numClipPoints, clipPoints,
+ numPlanes, normals, dists,
+ maxPoints, pointBuffer,
+ maxFragments, fragmentBuffer,
+ &returnedPoints, &returnedFragments, mins, maxs);
+
+ if ( returnedFragments == maxFragments ) {
+ return returnedFragments; // not enough space for more fragments
+ }
+ }
+
+ VectorCopy(dv[1].xyz, clipPoints[0][0]);
+ VectorMA(clipPoints[0][0], MARKER_OFFSET, dv[1].normal, clipPoints[0][0]);
+ VectorCopy(dv[cv->width].xyz, clipPoints[0][1]);
+ VectorMA(clipPoints[0][1], MARKER_OFFSET, dv[cv->width].normal, clipPoints[0][1]);
+ VectorCopy(dv[cv->width+1].xyz, clipPoints[0][2]);
+ VectorMA(clipPoints[0][2], MARKER_OFFSET, dv[cv->width+1].normal, clipPoints[0][2]);
+ // check the normal of this triangle
+ VectorSubtract(clipPoints[0][0], clipPoints[0][1], v1);
+ VectorSubtract(clipPoints[0][2], clipPoints[0][1], v2);
+ CrossProduct(v1, v2, normal);
+ VectorNormalizeFast(normal);
+ if (DotProduct(normal, projectionDir) < -0.05) {
+ // add the fragments of this triangle
+ R_AddMarkFragments(numClipPoints, clipPoints,
+ numPlanes, normals, dists,
+ maxPoints, pointBuffer,
+ maxFragments, fragmentBuffer,
+ &returnedPoints, &returnedFragments, mins, maxs);
+
+ if ( returnedFragments == maxFragments ) {
+ return returnedFragments; // not enough space for more fragments
+ }
+ }
+ }
+ }
+ }
+ else if (*surfaces[i] == SF_FACE) {
+
+ surf = ( srfSurfaceFace_t * ) surfaces[i];
+ // check the normal of this face
+ if (DotProduct(surf->plane.normal, projectionDir) > -0.5) {
+ continue;
+ }
+
+ /*
+ VectorSubtract(clipPoints[0][0], clipPoints[0][1], v1);
+ VectorSubtract(clipPoints[0][2], clipPoints[0][1], v2);
+ CrossProduct(v1, v2, normal);
+ VectorNormalize(normal);
+ if (DotProduct(normal, projectionDir) > -0.5) continue;
+ */
+ indexes = (int *)( (byte *)surf + surf->ofsIndices );
+ for ( k = 0 ; k < surf->numIndices ; k += 3 ) {
+ for ( j = 0 ; j < 3 ; j++ ) {
+ v = surf->points[0] + VERTEXSIZE * indexes[k+j];;
+ VectorMA( v, MARKER_OFFSET, surf->plane.normal, clipPoints[0][j] );
+ }
+ // add the fragments of this face
+ R_AddMarkFragments( 3 , clipPoints,
+ numPlanes, normals, dists,
+ maxPoints, pointBuffer,
+ maxFragments, fragmentBuffer,
+ &returnedPoints, &returnedFragments, mins, maxs);
+ if ( returnedFragments == maxFragments ) {
+ return returnedFragments; // not enough space for more fragments
+ }
+ }
+ continue;
+ }
+ else {
+ // ignore all other world surfaces
+ // might be cool to also project polygons on a triangle soup
+ // however this will probably create huge amounts of extra polys
+ // even more than the projection onto curves
+ continue;
+ }
+ }
+ return returnedFragments;
+}
+
diff --git a/code/renderer/tr_mesh.c b/code/renderer/tr_mesh.c
new file mode 100755
index 0000000..82f9f0c
--- /dev/null
+++ b/code/renderer/tr_mesh.c
@@ -0,0 +1,397 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// tr_mesh.c: triangle model functions
+
+#include "tr_local.h"
+
+static float ProjectRadius( float r, vec3_t location )
+{
+ float pr;
+ float dist;
+ float c;
+ vec3_t p;
+ float projected[4];
+
+ c = DotProduct( tr.viewParms.or.axis[0], tr.viewParms.or.origin );
+ dist = DotProduct( tr.viewParms.or.axis[0], location ) - c;
+
+ if ( dist <= 0 )
+ return 0;
+
+ p[0] = 0;
+ p[1] = fabs( r );
+ p[2] = -dist;
+
+ projected[0] = p[0] * tr.viewParms.projectionMatrix[0] +
+ p[1] * tr.viewParms.projectionMatrix[4] +
+ p[2] * tr.viewParms.projectionMatrix[8] +
+ tr.viewParms.projectionMatrix[12];
+
+ projected[1] = p[0] * tr.viewParms.projectionMatrix[1] +
+ p[1] * tr.viewParms.projectionMatrix[5] +
+ p[2] * tr.viewParms.projectionMatrix[9] +
+ tr.viewParms.projectionMatrix[13];
+
+ projected[2] = p[0] * tr.viewParms.projectionMatrix[2] +
+ p[1] * tr.viewParms.projectionMatrix[6] +
+ p[2] * tr.viewParms.projectionMatrix[10] +
+ tr.viewParms.projectionMatrix[14];
+
+ projected[3] = p[0] * tr.viewParms.projectionMatrix[3] +
+ p[1] * tr.viewParms.projectionMatrix[7] +
+ p[2] * tr.viewParms.projectionMatrix[11] +
+ tr.viewParms.projectionMatrix[15];
+
+
+ pr = projected[1] / projected[3];
+
+ if ( pr > 1.0f )
+ pr = 1.0f;
+
+ return pr;
+}
+
+/*
+=============
+R_CullModel
+=============
+*/
+static int R_CullModel( md3Header_t *header, trRefEntity_t *ent ) {
+ vec3_t bounds[2];
+ md3Frame_t *oldFrame, *newFrame;
+ int i;
+
+ // compute frame pointers
+ newFrame = ( md3Frame_t * ) ( ( byte * ) header + header->ofsFrames ) + ent->e.frame;
+ oldFrame = ( md3Frame_t * ) ( ( byte * ) header + header->ofsFrames ) + ent->e.oldframe;
+
+ // cull bounding sphere ONLY if this is not an upscaled entity
+ if ( !ent->e.nonNormalizedAxes )
+ {
+ if ( ent->e.frame == ent->e.oldframe )
+ {
+ switch ( R_CullLocalPointAndRadius( newFrame->localOrigin, newFrame->radius ) )
+ {
+ case CULL_OUT:
+ tr.pc.c_sphere_cull_md3_out++;
+ return CULL_OUT;
+
+ case CULL_IN:
+ tr.pc.c_sphere_cull_md3_in++;
+ return CULL_IN;
+
+ case CULL_CLIP:
+ tr.pc.c_sphere_cull_md3_clip++;
+ break;
+ }
+ }
+ else
+ {
+ int sphereCull, sphereCullB;
+
+ sphereCull = R_CullLocalPointAndRadius( newFrame->localOrigin, newFrame->radius );
+ if ( newFrame == oldFrame ) {
+ sphereCullB = sphereCull;
+ } else {
+ sphereCullB = R_CullLocalPointAndRadius( oldFrame->localOrigin, oldFrame->radius );
+ }
+
+ if ( sphereCull == sphereCullB )
+ {
+ if ( sphereCull == CULL_OUT )
+ {
+ tr.pc.c_sphere_cull_md3_out++;
+ return CULL_OUT;
+ }
+ else if ( sphereCull == CULL_IN )
+ {
+ tr.pc.c_sphere_cull_md3_in++;
+ return CULL_IN;
+ }
+ else
+ {
+ tr.pc.c_sphere_cull_md3_clip++;
+ }
+ }
+ }
+ }
+
+ // calculate a bounding box in the current coordinate system
+ for (i = 0 ; i < 3 ; i++) {
+ bounds[0][i] = oldFrame->bounds[0][i] < newFrame->bounds[0][i] ? oldFrame->bounds[0][i] : newFrame->bounds[0][i];
+ bounds[1][i] = oldFrame->bounds[1][i] > newFrame->bounds[1][i] ? oldFrame->bounds[1][i] : newFrame->bounds[1][i];
+ }
+
+ switch ( R_CullLocalBox( bounds ) )
+ {
+ case CULL_IN:
+ tr.pc.c_box_cull_md3_in++;
+ return CULL_IN;
+ case CULL_CLIP:
+ tr.pc.c_box_cull_md3_clip++;
+ return CULL_CLIP;
+ case CULL_OUT:
+ default:
+ tr.pc.c_box_cull_md3_out++;
+ return CULL_OUT;
+ }
+}
+
+
+/*
+=================
+R_ComputeLOD
+
+=================
+*/
+int R_ComputeLOD( trRefEntity_t *ent ) {
+ float radius;
+ float flod, lodscale;
+ float projectedRadius;
+ md3Frame_t *frame;
+ int lod;
+
+ if ( tr.currentModel->numLods < 2 )
+ {
+ // model has only 1 LOD level, skip computations and bias
+ lod = 0;
+ }
+ else
+ {
+ // multiple LODs exist, so compute projected bounding sphere
+ // and use that as a criteria for selecting LOD
+
+ frame = ( md3Frame_t * ) ( ( ( unsigned char * ) tr.currentModel->md3[0] ) + tr.currentModel->md3[0]->ofsFrames );
+
+ frame += ent->e.frame;
+
+ radius = RadiusFromBounds( frame->bounds[0], frame->bounds[1] );
+
+ if ( ( projectedRadius = ProjectRadius( radius, ent->e.origin ) ) != 0 )
+ {
+ lodscale = r_lodscale->value;
+ if (lodscale > 20) lodscale = 20;
+ flod = 1.0f - projectedRadius * lodscale;
+ }
+ else
+ {
+ // object intersects near view plane, e.g. view weapon
+ flod = 0;
+ }
+
+ flod *= tr.currentModel->numLods;
+ lod = myftol( flod );
+
+ if ( lod < 0 )
+ {
+ lod = 0;
+ }
+ else if ( lod >= tr.currentModel->numLods )
+ {
+ lod = tr.currentModel->numLods - 1;
+ }
+ }
+
+ lod += r_lodbias->integer;
+
+ if ( lod >= tr.currentModel->numLods )
+ lod = tr.currentModel->numLods - 1;
+ if ( lod < 0 )
+ lod = 0;
+
+ return lod;
+}
+
+/*
+=================
+R_ComputeFogNum
+
+=================
+*/
+int R_ComputeFogNum( md3Header_t *header, trRefEntity_t *ent ) {
+ int i, j;
+ fog_t *fog;
+ md3Frame_t *md3Frame;
+ vec3_t localOrigin;
+
+ if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) {
+ return 0;
+ }
+
+ // FIXME: non-normalized axis issues
+ md3Frame = ( md3Frame_t * ) ( ( byte * ) header + header->ofsFrames ) + ent->e.frame;
+ VectorAdd( ent->e.origin, md3Frame->localOrigin, localOrigin );
+ for ( i = 1 ; i < tr.world->numfogs ; i++ ) {
+ fog = &tr.world->fogs[i];
+ for ( j = 0 ; j < 3 ; j++ ) {
+ if ( localOrigin[j] - md3Frame->radius >= fog->bounds[1][j] ) {
+ break;
+ }
+ if ( localOrigin[j] + md3Frame->radius <= fog->bounds[0][j] ) {
+ break;
+ }
+ }
+ if ( j == 3 ) {
+ return i;
+ }
+ }
+
+ return 0;
+}
+
+/*
+=================
+R_AddMD3Surfaces
+
+=================
+*/
+void R_AddMD3Surfaces( trRefEntity_t *ent ) {
+ int i;
+ md3Header_t *header = 0;
+ md3Surface_t *surface = 0;
+ md3Shader_t *md3Shader = 0;
+ shader_t *shader = 0;
+ int cull;
+ int lod;
+ int fogNum;
+ qboolean personalModel;
+
+ // don't add third_person objects if not in a portal
+ personalModel = (ent->e.renderfx & RF_THIRD_PERSON) && !tr.viewParms.isPortal;
+
+ if ( ent->e.renderfx & RF_WRAP_FRAMES ) {
+ ent->e.frame %= tr.currentModel->md3[0]->numFrames;
+ ent->e.oldframe %= tr.currentModel->md3[0]->numFrames;
+ }
+
+ //
+ // Validate the frames so there is no chance of a crash.
+ // This will write directly into the entity structure, so
+ // when the surfaces are rendered, they don't need to be
+ // range checked again.
+ //
+ if ( (ent->e.frame >= tr.currentModel->md3[0]->numFrames)
+ || (ent->e.frame < 0)
+ || (ent->e.oldframe >= tr.currentModel->md3[0]->numFrames)
+ || (ent->e.oldframe < 0) ) {
+ ri.Printf( PRINT_DEVELOPER, "R_AddMD3Surfaces: no such frame %d to %d for '%s'\n",
+ ent->e.oldframe, ent->e.frame,
+ tr.currentModel->name );
+ ent->e.frame = 0;
+ ent->e.oldframe = 0;
+ }
+
+ //
+ // compute LOD
+ //
+ lod = R_ComputeLOD( ent );
+
+ header = tr.currentModel->md3[lod];
+
+ //
+ // cull the entire model if merged bounding box of both frames
+ // is outside the view frustum.
+ //
+ cull = R_CullModel ( header, ent );
+ if ( cull == CULL_OUT ) {
+ return;
+ }
+
+ //
+ // set up lighting now that we know we aren't culled
+ //
+ if ( !personalModel || r_shadows->integer > 1 ) {
+ R_SetupEntityLighting( &tr.refdef, ent );
+ }
+
+ //
+ // see if we are in a fog volume
+ //
+ fogNum = R_ComputeFogNum( header, ent );
+
+ //
+ // draw all surfaces
+ //
+ surface = (md3Surface_t *)( (byte *)header + header->ofsSurfaces );
+ for ( i = 0 ; i < header->numSurfaces ; i++ ) {
+
+ if ( ent->e.customShader ) {
+ shader = R_GetShaderByHandle( ent->e.customShader );
+ } else if ( ent->e.customSkin > 0 && ent->e.customSkin < tr.numSkins ) {
+ skin_t *skin;
+ int j;
+
+ skin = R_GetSkinByHandle( ent->e.customSkin );
+
+ // match the surface name to something in the skin file
+ shader = tr.defaultShader;
+ for ( j = 0 ; j < skin->numSurfaces ; j++ ) {
+ // the names have both been lowercased
+ if ( !strcmp( skin->surfaces[j]->name, surface->name ) ) {
+ shader = skin->surfaces[j]->shader;
+ break;
+ }
+ }
+ if (shader == tr.defaultShader) {
+ ri.Printf( PRINT_DEVELOPER, "WARNING: no shader for surface %s in skin %s\n", surface->name, skin->name);
+ }
+ else if (shader->defaultShader) {
+ ri.Printf( PRINT_DEVELOPER, "WARNING: shader %s in skin %s not found\n", shader->name, skin->name);
+ }
+ } else if ( surface->numShaders <= 0 ) {
+ shader = tr.defaultShader;
+ } else {
+ md3Shader = (md3Shader_t *) ( (byte *)surface + surface->ofsShaders );
+ md3Shader += ent->e.skinNum % surface->numShaders;
+ shader = tr.shaders[ md3Shader->shaderIndex ];
+ }
+
+
+ // we will add shadows even if the main object isn't visible in the view
+
+ // stencil shadows can't do personal models unless I polyhedron clip
+ if ( !personalModel
+ && r_shadows->integer == 2
+ && fogNum == 0
+ && !(ent->e.renderfx & ( RF_NOSHADOW | RF_DEPTHHACK ) )
+ && shader->sort == SS_OPAQUE ) {
+ R_AddDrawSurf( (void *)surface, tr.shadowShader, 0, qfalse );
+ }
+
+ // projection shadows work fine with personal models
+ if ( r_shadows->integer == 3
+ && fogNum == 0
+ && (ent->e.renderfx & RF_SHADOW_PLANE )
+ && shader->sort == SS_OPAQUE ) {
+ R_AddDrawSurf( (void *)surface, tr.projectionShadowShader, 0, qfalse );
+ }
+
+ // don't add third_person objects if not viewing through a portal
+ if ( !personalModel ) {
+ R_AddDrawSurf( (void *)surface, shader, fogNum, qfalse );
+ }
+
+ surface = (md3Surface_t *)( (byte *)surface + surface->ofsEnd );
+ }
+
+}
+
diff --git a/code/renderer/tr_model.c b/code/renderer/tr_model.c
new file mode 100755
index 0000000..990866f
--- /dev/null
+++ b/code/renderer/tr_model.c
@@ -0,0 +1,700 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// tr_models.c -- model loading and caching
+
+#include "tr_local.h"
+
+#define LL(x) x=LittleLong(x)
+
+static qboolean R_LoadMD3 (model_t *mod, int lod, void *buffer, const char *name );
+static qboolean R_LoadMD4 (model_t *mod, void *buffer, const char *name );
+
+model_t *loadmodel;
+
+/*
+** R_GetModelByHandle
+*/
+model_t *R_GetModelByHandle( qhandle_t index ) {
+ model_t *mod;
+
+ // out of range gets the defualt model
+ if ( index < 1 || index >= tr.numModels ) {
+ return tr.models[0];
+ }
+
+ mod = tr.models[index];
+
+ return mod;
+}
+
+//===============================================================================
+
+/*
+** R_AllocModel
+*/
+model_t *R_AllocModel( void ) {
+ model_t *mod;
+
+ if ( tr.numModels == MAX_MOD_KNOWN ) {
+ return NULL;
+ }
+
+ mod = ri.Hunk_Alloc( sizeof( *tr.models[tr.numModels] ), h_low );
+ mod->index = tr.numModels;
+ tr.models[tr.numModels] = mod;
+ tr.numModels++;
+
+ return mod;
+}
+
+/*
+====================
+RE_RegisterModel
+
+Loads in a model for the given name
+
+Zero will be returned if the model fails to load.
+An entry will be retained for failed models as an
+optimization to prevent disk rescanning if they are
+asked for again.
+====================
+*/
+qhandle_t RE_RegisterModel( const char *name ) {
+ model_t *mod;
+ unsigned *buf;
+ int lod;
+ int ident;
+ qboolean loaded;
+ qhandle_t hModel;
+ int numLoaded;
+
+ if ( !name || !name[0] ) {
+ ri.Printf( PRINT_ALL, "RE_RegisterModel: NULL name\n" );
+ return 0;
+ }
+
+ if ( strlen( name ) >= MAX_QPATH ) {
+ Com_Printf( "Model name exceeds MAX_QPATH\n" );
+ return 0;
+ }
+
+ //
+ // search the currently loaded models
+ //
+ for ( hModel = 1 ; hModel < tr.numModels; hModel++ ) {
+ mod = tr.models[hModel];
+ if ( !strcmp( mod->name, name ) ) {
+ if( mod->type == MOD_BAD ) {
+ return 0;
+ }
+ return hModel;
+ }
+ }
+
+ // allocate a new model_t
+
+ if ( ( mod = R_AllocModel() ) == NULL ) {
+ ri.Printf( PRINT_WARNING, "RE_RegisterModel: R_AllocModel() failed for '%s'\n", name);
+ return 0;
+ }
+
+ // only set the name after the model has been successfully loaded
+ Q_strncpyz( mod->name, name, sizeof( mod->name ) );
+
+
+ // make sure the render thread is stopped
+ R_SyncRenderThread();
+
+ mod->numLods = 0;
+
+ //
+ // load the files
+ //
+ numLoaded = 0;
+
+ for ( lod = MD3_MAX_LODS - 1 ; lod >= 0 ; lod-- ) {
+ char filename[1024];
+
+ strcpy( filename, name );
+
+ if ( lod != 0 ) {
+ char namebuf[80];
+
+ if ( strrchr( filename, '.' ) ) {
+ *strrchr( filename, '.' ) = 0;
+ }
+ sprintf( namebuf, "_%d.md3", lod );
+ strcat( filename, namebuf );
+ }
+
+ ri.FS_ReadFile( filename, (void **)&buf );
+ if ( !buf ) {
+ continue;
+ }
+
+ loadmodel = mod;
+
+ ident = LittleLong(*(unsigned *)buf);
+ if ( ident == MD4_IDENT ) {
+ loaded = R_LoadMD4( mod, buf, name );
+ } else {
+ if ( ident != MD3_IDENT ) {
+ ri.Printf (PRINT_WARNING,"RE_RegisterModel: unknown fileid for %s\n", name);
+ goto fail;
+ }
+
+ loaded = R_LoadMD3( mod, lod, buf, name );
+ }
+
+ ri.FS_FreeFile (buf);
+
+ if ( !loaded ) {
+ if ( lod == 0 ) {
+ goto fail;
+ } else {
+ break;
+ }
+ } else {
+ mod->numLods++;
+ numLoaded++;
+ // if we have a valid model and are biased
+ // so that we won't see any higher detail ones,
+ // stop loading them
+// if ( lod <= r_lodbias->integer ) {
+// break;
+// }
+ }
+ }
+
+ if ( numLoaded ) {
+ // duplicate into higher lod spots that weren't
+ // loaded, in case the user changes r_lodbias on the fly
+ for ( lod-- ; lod >= 0 ; lod-- ) {
+ mod->numLods++;
+ mod->md3[lod] = mod->md3[lod+1];
+ }
+
+ return mod->index;
+ }
+#ifdef _DEBUG
+ else {
+ ri.Printf (PRINT_WARNING,"RE_RegisterModel: couldn't load %s\n", name);
+ }
+#endif
+
+fail:
+ // we still keep the model_t around, so if the model name is asked for
+ // again, we won't bother scanning the filesystem
+ mod->type = MOD_BAD;
+ return 0;
+}
+
+
+/*
+=================
+R_LoadMD3
+=================
+*/
+static qboolean R_LoadMD3 (model_t *mod, int lod, void *buffer, const char *mod_name ) {
+ int i, j;
+ md3Header_t *pinmodel;
+ md3Frame_t *frame;
+ md3Surface_t *surf;
+ md3Shader_t *shader;
+ md3Triangle_t *tri;
+ md3St_t *st;
+ md3XyzNormal_t *xyz;
+ md3Tag_t *tag;
+ int version;
+ int size;
+
+ pinmodel = (md3Header_t *)buffer;
+
+ version = LittleLong (pinmodel->version);
+ if (version != MD3_VERSION) {
+ ri.Printf( PRINT_WARNING, "R_LoadMD3: %s has wrong version (%i should be %i)\n",
+ mod_name, version, MD3_VERSION);
+ return qfalse;
+ }
+
+ mod->type = MOD_MESH;
+ size = LittleLong(pinmodel->ofsEnd);
+ mod->dataSize += size;
+ mod->md3[lod] = ri.Hunk_Alloc( size, h_low );
+
+ Com_Memcpy (mod->md3[lod], buffer, LittleLong(pinmodel->ofsEnd) );
+
+ LL(mod->md3[lod]->ident);
+ LL(mod->md3[lod]->version);
+ LL(mod->md3[lod]->numFrames);
+ LL(mod->md3[lod]->numTags);
+ LL(mod->md3[lod]->numSurfaces);
+ LL(mod->md3[lod]->ofsFrames);
+ LL(mod->md3[lod]->ofsTags);
+ LL(mod->md3[lod]->ofsSurfaces);
+ LL(mod->md3[lod]->ofsEnd);
+
+ if ( mod->md3[lod]->numFrames < 1 ) {
+ ri.Printf( PRINT_WARNING, "R_LoadMD3: %s has no frames\n", mod_name );
+ return qfalse;
+ }
+
+ // swap all the frames
+ frame = (md3Frame_t *) ( (byte *)mod->md3[lod] + mod->md3[lod]->ofsFrames );
+ for ( i = 0 ; i < mod->md3[lod]->numFrames ; i++, frame++) {
+ frame->radius = LittleFloat( frame->radius );
+ for ( j = 0 ; j < 3 ; j++ ) {
+ frame->bounds[0][j] = LittleFloat( frame->bounds[0][j] );
+ frame->bounds[1][j] = LittleFloat( frame->bounds[1][j] );
+ frame->localOrigin[j] = LittleFloat( frame->localOrigin[j] );
+ }
+ }
+
+ // swap all the tags
+ tag = (md3Tag_t *) ( (byte *)mod->md3[lod] + mod->md3[lod]->ofsTags );
+ for ( i = 0 ; i < mod->md3[lod]->numTags * mod->md3[lod]->numFrames ; i++, tag++) {
+ for ( j = 0 ; j < 3 ; j++ ) {
+ tag->origin[j] = LittleFloat( tag->origin[j] );
+ tag->axis[0][j] = LittleFloat( tag->axis[0][j] );
+ tag->axis[1][j] = LittleFloat( tag->axis[1][j] );
+ tag->axis[2][j] = LittleFloat( tag->axis[2][j] );
+ }
+ }
+
+ // swap all the surfaces
+ surf = (md3Surface_t *) ( (byte *)mod->md3[lod] + mod->md3[lod]->ofsSurfaces );
+ for ( i = 0 ; i < mod->md3[lod]->numSurfaces ; i++) {
+
+ LL(surf->ident);
+ LL(surf->flags);
+ LL(surf->numFrames);
+ LL(surf->numShaders);
+ LL(surf->numTriangles);
+ LL(surf->ofsTriangles);
+ LL(surf->numVerts);
+ LL(surf->ofsShaders);
+ LL(surf->ofsSt);
+ LL(surf->ofsXyzNormals);
+ LL(surf->ofsEnd);
+
+ if ( surf->numVerts > SHADER_MAX_VERTEXES ) {
+ ri.Error (ERR_DROP, "R_LoadMD3: %s has more than %i verts on a surface (%i)",
+ mod_name, SHADER_MAX_VERTEXES, surf->numVerts );
+ }
+ if ( surf->numTriangles*3 > SHADER_MAX_INDEXES ) {
+ ri.Error (ERR_DROP, "R_LoadMD3: %s has more than %i triangles on a surface (%i)",
+ mod_name, SHADER_MAX_INDEXES / 3, surf->numTriangles );
+ }
+
+ // change to surface identifier
+ surf->ident = SF_MD3;
+
+ // lowercase the surface name so skin compares are faster
+ Q_strlwr( surf->name );
+
+ // strip off a trailing _1 or _2
+ // this is a crutch for q3data being a mess
+ j = strlen( surf->name );
+ if ( j > 2 && surf->name[j-2] == '_' ) {
+ surf->name[j-2] = 0;
+ }
+
+ // register the shaders
+ shader = (md3Shader_t *) ( (byte *)surf + surf->ofsShaders );
+ for ( j = 0 ; j < surf->numShaders ; j++, shader++ ) {
+ shader_t *sh;
+
+ sh = R_FindShader( shader->name, LIGHTMAP_NONE, qtrue );
+ if ( sh->defaultShader ) {
+ shader->shaderIndex = 0;
+ } else {
+ shader->shaderIndex = sh->index;
+ }
+ }
+
+ // swap all the triangles
+ tri = (md3Triangle_t *) ( (byte *)surf + surf->ofsTriangles );
+ for ( j = 0 ; j < surf->numTriangles ; j++, tri++ ) {
+ LL(tri->indexes[0]);
+ LL(tri->indexes[1]);
+ LL(tri->indexes[2]);
+ }
+
+ // swap all the ST
+ st = (md3St_t *) ( (byte *)surf + surf->ofsSt );
+ for ( j = 0 ; j < surf->numVerts ; j++, st++ ) {
+ st->st[0] = LittleFloat( st->st[0] );
+ st->st[1] = LittleFloat( st->st[1] );
+ }
+
+ // swap all the XyzNormals
+ xyz = (md3XyzNormal_t *) ( (byte *)surf + surf->ofsXyzNormals );
+ for ( j = 0 ; j < surf->numVerts * surf->numFrames ; j++, xyz++ )
+ {
+ xyz->xyz[0] = LittleShort( xyz->xyz[0] );
+ xyz->xyz[1] = LittleShort( xyz->xyz[1] );
+ xyz->xyz[2] = LittleShort( xyz->xyz[2] );
+
+ xyz->normal = LittleShort( xyz->normal );
+ }
+
+
+ // find the next surface
+ surf = (md3Surface_t *)( (byte *)surf + surf->ofsEnd );
+ }
+
+ return qtrue;
+}
+
+
+
+/*
+=================
+R_LoadMD4
+=================
+*/
+static qboolean R_LoadMD4( model_t *mod, void *buffer, const char *mod_name ) {
+ int i, j, k, lodindex;
+ md4Header_t *pinmodel, *md4;
+ md4Frame_t *frame;
+ md4LOD_t *lod;
+ md4Surface_t *surf;
+ md4Triangle_t *tri;
+ md4Vertex_t *v;
+ int version;
+ int size;
+ shader_t *sh;
+ int frameSize;
+
+ pinmodel = (md4Header_t *)buffer;
+
+ version = LittleLong (pinmodel->version);
+ if (version != MD4_VERSION) {
+ ri.Printf( PRINT_WARNING, "R_LoadMD4: %s has wrong version (%i should be %i)\n",
+ mod_name, version, MD4_VERSION);
+ return qfalse;
+ }
+
+ mod->type = MOD_MD4;
+ size = LittleLong(pinmodel->ofsEnd);
+ mod->dataSize += size;
+ md4 = mod->md4 = ri.Hunk_Alloc( size, h_low );
+
+ Com_Memcpy( md4, buffer, LittleLong(pinmodel->ofsEnd) );
+
+ LL(md4->ident);
+ LL(md4->version);
+ LL(md4->numFrames);
+ LL(md4->numBones);
+ LL(md4->numLODs);
+ LL(md4->ofsFrames);
+ LL(md4->ofsLODs);
+ LL(md4->ofsEnd);
+
+ if ( md4->numFrames < 1 ) {
+ ri.Printf( PRINT_WARNING, "R_LoadMD4: %s has no frames\n", mod_name );
+ return qfalse;
+ }
+
+ // we don't need to swap tags in the renderer, they aren't used
+
+ // swap all the frames
+ frameSize = (int)( &((md4Frame_t *)0)->bones[ md4->numBones ] );
+ for ( i = 0 ; i < md4->numFrames ; i++, frame++) {
+ frame = (md4Frame_t *) ( (byte *)md4 + md4->ofsFrames + i * frameSize );
+ frame->radius = LittleFloat( frame->radius );
+ for ( j = 0 ; j < 3 ; j++ ) {
+ frame->bounds[0][j] = LittleFloat( frame->bounds[0][j] );
+ frame->bounds[1][j] = LittleFloat( frame->bounds[1][j] );
+ frame->localOrigin[j] = LittleFloat( frame->localOrigin[j] );
+ }
+ for ( j = 0 ; j < md4->numBones * sizeof( md4Bone_t ) / 4 ; j++ ) {
+ ((float *)frame->bones)[j] = LittleFloat( ((float *)frame->bones)[j] );
+ }
+ }
+
+ // swap all the LOD's
+ lod = (md4LOD_t *) ( (byte *)md4 + md4->ofsLODs );
+ for ( lodindex = 0 ; lodindex < md4->numLODs ; lodindex++ ) {
+
+ // swap all the surfaces
+ surf = (md4Surface_t *) ( (byte *)lod + lod->ofsSurfaces );
+ for ( i = 0 ; i < lod->numSurfaces ; i++) {
+ LL(surf->ident);
+ LL(surf->numTriangles);
+ LL(surf->ofsTriangles);
+ LL(surf->numVerts);
+ LL(surf->ofsVerts);
+ LL(surf->ofsEnd);
+
+ if ( surf->numVerts > SHADER_MAX_VERTEXES ) {
+ ri.Error (ERR_DROP, "R_LoadMD3: %s has more than %i verts on a surface (%i)",
+ mod_name, SHADER_MAX_VERTEXES, surf->numVerts );
+ }
+ if ( surf->numTriangles*3 > SHADER_MAX_INDEXES ) {
+ ri.Error (ERR_DROP, "R_LoadMD3: %s has more than %i triangles on a surface (%i)",
+ mod_name, SHADER_MAX_INDEXES / 3, surf->numTriangles );
+ }
+
+ // change to surface identifier
+ surf->ident = SF_MD4;
+
+ // lowercase the surface name so skin compares are faster
+ Q_strlwr( surf->name );
+
+ // register the shaders
+ sh = R_FindShader( surf->shader, LIGHTMAP_NONE, qtrue );
+ if ( sh->defaultShader ) {
+ surf->shaderIndex = 0;
+ } else {
+ surf->shaderIndex = sh->index;
+ }
+
+ // swap all the triangles
+ tri = (md4Triangle_t *) ( (byte *)surf + surf->ofsTriangles );
+ for ( j = 0 ; j < surf->numTriangles ; j++, tri++ ) {
+ LL(tri->indexes[0]);
+ LL(tri->indexes[1]);
+ LL(tri->indexes[2]);
+ }
+
+ // swap all the vertexes
+ // FIXME
+ // This makes TFC's skeletons work. Shouldn't be necessary anymore, but left
+ // in for reference.
+ //v = (md4Vertex_t *) ( (byte *)surf + surf->ofsVerts + 12);
+ v = (md4Vertex_t *) ( (byte *)surf + surf->ofsVerts);
+ for ( j = 0 ; j < surf->numVerts ; j++ ) {
+ v->normal[0] = LittleFloat( v->normal[0] );
+ v->normal[1] = LittleFloat( v->normal[1] );
+ v->normal[2] = LittleFloat( v->normal[2] );
+
+ v->texCoords[0] = LittleFloat( v->texCoords[0] );
+ v->texCoords[1] = LittleFloat( v->texCoords[1] );
+
+ v->numWeights = LittleLong( v->numWeights );
+
+ for ( k = 0 ; k < v->numWeights ; k++ ) {
+ v->weights[k].boneIndex = LittleLong( v->weights[k].boneIndex );
+ v->weights[k].boneWeight = LittleFloat( v->weights[k].boneWeight );
+ v->weights[k].offset[0] = LittleFloat( v->weights[k].offset[0] );
+ v->weights[k].offset[1] = LittleFloat( v->weights[k].offset[1] );
+ v->weights[k].offset[2] = LittleFloat( v->weights[k].offset[2] );
+ }
+ // FIXME
+ // This makes TFC's skeletons work. Shouldn't be necessary anymore, but left
+ // in for reference.
+ //v = (md4Vertex_t *)( ( byte * )&v->weights[v->numWeights] + 12 );
+ v = (md4Vertex_t *)( ( byte * )&v->weights[v->numWeights]);
+ }
+
+ // find the next surface
+ surf = (md4Surface_t *)( (byte *)surf + surf->ofsEnd );
+ }
+
+ // find the next LOD
+ lod = (md4LOD_t *)( (byte *)lod + lod->ofsEnd );
+ }
+
+ return qtrue;
+}
+
+
+
+
+//=============================================================================
+
+/*
+** RE_BeginRegistration
+*/
+void RE_BeginRegistration( glconfig_t *glconfigOut ) {
+
+ R_Init();
+
+ *glconfigOut = glConfig;
+
+ R_SyncRenderThread();
+
+ tr.viewCluster = -1; // force markleafs to regenerate
+ R_ClearFlares();
+ RE_ClearScene();
+
+ tr.registered = qtrue;
+
+ // NOTE: this sucks, for some reason the first stretch pic is never drawn
+ // without this we'd see a white flash on a level load because the very
+ // first time the level shot would not be drawn
+ RE_StretchPic(0, 0, 0, 0, 0, 0, 1, 1, 0);
+}
+
+//=============================================================================
+
+/*
+===============
+R_ModelInit
+===============
+*/
+void R_ModelInit( void ) {
+ model_t *mod;
+
+ // leave a space for NULL model
+ tr.numModels = 0;
+
+ mod = R_AllocModel();
+ mod->type = MOD_BAD;
+}
+
+
+/*
+================
+R_Modellist_f
+================
+*/
+void R_Modellist_f( void ) {
+ int i, j;
+ model_t *mod;
+ int total;
+ int lods;
+
+ total = 0;
+ for ( i = 1 ; i < tr.numModels; i++ ) {
+ mod = tr.models[i];
+ lods = 1;
+ for ( j = 1 ; j < MD3_MAX_LODS ; j++ ) {
+ if ( mod->md3[j] && mod->md3[j] != mod->md3[j-1] ) {
+ lods++;
+ }
+ }
+ ri.Printf( PRINT_ALL, "%8i : (%i) %s\n",mod->dataSize, lods, mod->name );
+ total += mod->dataSize;
+ }
+ ri.Printf( PRINT_ALL, "%8i : Total models\n", total );
+
+#if 0 // not working right with new hunk
+ if ( tr.world ) {
+ ri.Printf( PRINT_ALL, "\n%8i : %s\n", tr.world->dataSize, tr.world->name );
+ }
+#endif
+}
+
+
+//=============================================================================
+
+
+/*
+================
+R_GetTag
+================
+*/
+static md3Tag_t *R_GetTag( md3Header_t *mod, int frame, const char *tagName ) {
+ md3Tag_t *tag;
+ int i;
+
+ if ( frame >= mod->numFrames ) {
+ // it is possible to have a bad frame while changing models, so don't error
+ frame = mod->numFrames - 1;
+ }
+
+ tag = (md3Tag_t *)((byte *)mod + mod->ofsTags) + frame * mod->numTags;
+ for ( i = 0 ; i < mod->numTags ; i++, tag++ ) {
+ if ( !strcmp( tag->name, tagName ) ) {
+ return tag; // found it
+ }
+ }
+
+ return NULL;
+}
+
+/*
+================
+R_LerpTag
+================
+*/
+int R_LerpTag( orientation_t *tag, qhandle_t handle, int startFrame, int endFrame,
+ float frac, const char *tagName ) {
+ md3Tag_t *start, *end;
+ int i;
+ float frontLerp, backLerp;
+ model_t *model;
+
+ model = R_GetModelByHandle( handle );
+ if ( !model->md3[0] ) {
+ AxisClear( tag->axis );
+ VectorClear( tag->origin );
+ return qfalse;
+ }
+
+ start = R_GetTag( model->md3[0], startFrame, tagName );
+ end = R_GetTag( model->md3[0], endFrame, tagName );
+ if ( !start || !end ) {
+ AxisClear( tag->axis );
+ VectorClear( tag->origin );
+ return qfalse;
+ }
+
+ frontLerp = frac;
+ backLerp = 1.0f - frac;
+
+ for ( i = 0 ; i < 3 ; i++ ) {
+ tag->origin[i] = start->origin[i] * backLerp + end->origin[i] * frontLerp;
+ tag->axis[0][i] = start->axis[0][i] * backLerp + end->axis[0][i] * frontLerp;
+ tag->axis[1][i] = start->axis[1][i] * backLerp + end->axis[1][i] * frontLerp;
+ tag->axis[2][i] = start->axis[2][i] * backLerp + end->axis[2][i] * frontLerp;
+ }
+ VectorNormalize( tag->axis[0] );
+ VectorNormalize( tag->axis[1] );
+ VectorNormalize( tag->axis[2] );
+ return qtrue;
+}
+
+
+/*
+====================
+R_ModelBounds
+====================
+*/
+void R_ModelBounds( qhandle_t handle, vec3_t mins, vec3_t maxs ) {
+ model_t *model;
+ md3Header_t *header;
+ md3Frame_t *frame;
+
+ model = R_GetModelByHandle( handle );
+
+ if ( model->bmodel ) {
+ VectorCopy( model->bmodel->bounds[0], mins );
+ VectorCopy( model->bmodel->bounds[1], maxs );
+ return;
+ }
+
+ if ( !model->md3[0] ) {
+ VectorClear( mins );
+ VectorClear( maxs );
+ return;
+ }
+
+ header = model->md3[0];
+
+ frame = (md3Frame_t *)( (byte *)header + header->ofsFrames );
+
+ VectorCopy( frame->bounds[0], mins );
+ VectorCopy( frame->bounds[1], maxs );
+}
diff --git a/code/renderer/tr_noise.c b/code/renderer/tr_noise.c
new file mode 100755
index 0000000..4aae947
--- /dev/null
+++ b/code/renderer/tr_noise.c
@@ -0,0 +1,95 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// tr_noise.c
+#include "tr_local.h"
+
+#define NOISE_SIZE 256
+#define NOISE_MASK ( NOISE_SIZE - 1 )
+
+#define VAL( a ) s_noise_perm[ ( a ) & ( NOISE_MASK )]
+#define INDEX( x, y, z, t ) VAL( x + VAL( y + VAL( z + VAL( t ) ) ) )
+
+static float s_noise_table[NOISE_SIZE];
+static int s_noise_perm[NOISE_SIZE];
+
+#define LERP( a, b, w ) ( a * ( 1.0f - w ) + b * w )
+
+static float GetNoiseValue( int x, int y, int z, int t )
+{
+ int index = INDEX( ( int ) x, ( int ) y, ( int ) z, ( int ) t );
+
+ return s_noise_table[index];
+}
+
+void R_NoiseInit( void )
+{
+ int i;
+
+ srand( 1001 );
+
+ for ( i = 0; i < NOISE_SIZE; i++ )
+ {
+ s_noise_table[i] = ( float ) ( ( ( rand() / ( float ) RAND_MAX ) * 2.0 - 1.0 ) );
+ s_noise_perm[i] = ( unsigned char ) ( rand() / ( float ) RAND_MAX * 255 );
+ }
+}
+
+float R_NoiseGet4f( float x, float y, float z, float t )
+{
+ int i;
+ int ix, iy, iz, it;
+ float fx, fy, fz, ft;
+ float front[4];
+ float back[4];
+ float fvalue, bvalue, value[2], finalvalue;
+
+ ix = ( int ) floor( x );
+ fx = x - ix;
+ iy = ( int ) floor( y );
+ fy = y - iy;
+ iz = ( int ) floor( z );
+ fz = z - iz;
+ it = ( int ) floor( t );
+ ft = t - it;
+
+ for ( i = 0; i < 2; i++ )
+ {
+ front[0] = GetNoiseValue( ix, iy, iz, it + i );
+ front[1] = GetNoiseValue( ix+1, iy, iz, it + i );
+ front[2] = GetNoiseValue( ix, iy+1, iz, it + i );
+ front[3] = GetNoiseValue( ix+1, iy+1, iz, it + i );
+
+ back[0] = GetNoiseValue( ix, iy, iz + 1, it + i );
+ back[1] = GetNoiseValue( ix+1, iy, iz + 1, it + i );
+ back[2] = GetNoiseValue( ix, iy+1, iz + 1, it + i );
+ back[3] = GetNoiseValue( ix+1, iy+1, iz + 1, it + i );
+
+ fvalue = LERP( LERP( front[0], front[1], fx ), LERP( front[2], front[3], fx ), fy );
+ bvalue = LERP( LERP( back[0], back[1], fx ), LERP( back[2], back[3], fx ), fy );
+
+ value[i] = LERP( fvalue, bvalue, fz );
+ }
+
+ finalvalue = LERP( value[0], value[1], ft );
+
+ return finalvalue;
+}
diff --git a/code/renderer/tr_public.h b/code/renderer/tr_public.h
new file mode 100755
index 0000000..197fa26
--- /dev/null
+++ b/code/renderer/tr_public.h
@@ -0,0 +1,167 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __TR_PUBLIC_H
+#define __TR_PUBLIC_H
+
+#include "../cgame/tr_types.h"
+
+#define REF_API_VERSION 8
+
+//
+// these are the functions exported by the refresh module
+//
+typedef struct {
+ // called before the library is unloaded
+ // if the system is just reconfiguring, pass destroyWindow = qfalse,
+ // which will keep the screen from flashing to the desktop.
+ void (*Shutdown)( qboolean destroyWindow );
+
+ // All data that will be used in a level should be
+ // registered before rendering any frames to prevent disk hits,
+ // but they can still be registered at a later time
+ // if necessary.
+ //
+ // BeginRegistration makes any existing media pointers invalid
+ // and returns the current gl configuration, including screen width
+ // and height, which can be used by the client to intelligently
+ // size display elements
+ void (*BeginRegistration)( glconfig_t *config );
+ qhandle_t (*RegisterModel)( const char *name );
+ qhandle_t (*RegisterSkin)( const char *name );
+ qhandle_t (*RegisterShader)( const char *name );
+ qhandle_t (*RegisterShaderNoMip)( const char *name );
+ void (*LoadWorld)( const char *name );
+
+ // the vis data is a large enough block of data that we go to the trouble
+ // of sharing it with the clipmodel subsystem
+ void (*SetWorldVisData)( const byte *vis );
+
+ // EndRegistration will draw a tiny polygon with each texture, forcing
+ // them to be loaded into card memory
+ void (*EndRegistration)( void );
+
+ // a scene is built up by calls to R_ClearScene and the various R_Add functions.
+ // Nothing is drawn until R_RenderScene is called.
+ void (*ClearScene)( void );
+ void (*AddRefEntityToScene)( const refEntity_t *re );
+ void (*AddPolyToScene)( qhandle_t hShader , int numVerts, const polyVert_t *verts, int num );
+ int (*LightForPoint)( vec3_t point, vec3_t ambientLight, vec3_t directedLight, vec3_t lightDir );
+ void (*AddLightToScene)( const vec3_t org, float intensity, float r, float g, float b );
+ void (*AddAdditiveLightToScene)( const vec3_t org, float intensity, float r, float g, float b );
+ void (*RenderScene)( const refdef_t *fd );
+
+ void (*SetColor)( const float *rgba ); // NULL = 1,1,1,1
+ void (*DrawStretchPic) ( float x, float y, float w, float h,
+ float s1, float t1, float s2, float t2, qhandle_t hShader ); // 0 = white
+
+ // Draw images for cinematic rendering, pass as 32 bit rgba
+ void (*DrawStretchRaw) (int x, int y, int w, int h, int cols, int rows, const byte *data, int client, qboolean dirty);
+ void (*UploadCinematic) (int w, int h, int cols, int rows, const byte *data, int client, qboolean dirty);
+
+ void (*BeginFrame)( stereoFrame_t stereoFrame );
+
+ // if the pointers are not NULL, timing info will be returned
+ void (*EndFrame)( int *frontEndMsec, int *backEndMsec );
+
+
+ int (*MarkFragments)( int numPoints, const vec3_t *points, const vec3_t projection,
+ int maxPoints, vec3_t pointBuffer, int maxFragments, markFragment_t *fragmentBuffer );
+
+ int (*LerpTag)( orientation_t *tag, qhandle_t model, int startFrame, int endFrame,
+ float frac, const char *tagName );
+ void (*ModelBounds)( qhandle_t model, vec3_t mins, vec3_t maxs );
+
+#ifdef __USEA3D
+ void (*A3D_RenderGeometry) (void *pVoidA3D, void *pVoidGeom, void *pVoidMat, void *pVoidGeomStatus);
+#endif
+ void (*RegisterFont)(const char *fontName, int pointSize, fontInfo_t *font);
+ void (*RemapShader)(const char *oldShader, const char *newShader, const char *offsetTime);
+ qboolean (*GetEntityToken)( char *buffer, int size );
+ qboolean (*inPVS)( const vec3_t p1, const vec3_t p2 );
+} refexport_t;
+
+//
+// these are the functions imported by the refresh module
+//
+typedef struct {
+ // print message on the local console
+ void (QDECL *Printf)( int printLevel, const char *fmt, ...);
+
+ // abort the game
+ void (QDECL *Error)( int errorLevel, const char *fmt, ...);
+
+ // milliseconds should only be used for profiling, never
+ // for anything game related. Get time from the refdef
+ int (*Milliseconds)( void );
+
+ // stack based memory allocation for per-level things that
+ // won't be freed
+#ifdef HUNK_DEBUG
+ void *(*Hunk_AllocDebug)( int size, ha_pref pref, char *label, char *file, int line );
+#else
+ void *(*Hunk_Alloc)( int size, ha_pref pref );
+#endif
+ void *(*Hunk_AllocateTempMemory)( int size );
+ void (*Hunk_FreeTempMemory)( void *block );
+
+ // dynamic memory allocator for things that need to be freed
+ void *(*Malloc)( int bytes );
+ void (*Free)( void *buf );
+
+ cvar_t *(*Cvar_Get)( const char *name, const char *value, int flags );
+ void (*Cvar_Set)( const char *name, const char *value );
+
+ void (*Cmd_AddCommand)( const char *name, void(*cmd)(void) );
+ void (*Cmd_RemoveCommand)( const char *name );
+
+ int (*Cmd_Argc) (void);
+ char *(*Cmd_Argv) (int i);
+
+ void (*Cmd_ExecuteText) (int exec_when, const char *text);
+
+ // visualization for debugging collision detection
+ void (*CM_DrawDebugSurface)( void (*drawPoly)(int color, int numPoints, float *points) );
+
+ // a -1 return means the file does not exist
+ // NULL can be passed for buf to just determine existance
+ int (*FS_FileIsInPAK)( const char *name, int *pCheckSum );
+ int (*FS_ReadFile)( const char *name, void **buf );
+ void (*FS_FreeFile)( void *buf );
+ char ** (*FS_ListFiles)( const char *name, const char *extension, int *numfilesfound );
+ void (*FS_FreeFileList)( char **filelist );
+ void (*FS_WriteFile)( const char *qpath, const void *buffer, int size );
+ qboolean (*FS_FileExists)( const char *file );
+
+ // cinematic stuff
+ void (*CIN_UploadCinematic)(int handle);
+ int (*CIN_PlayCinematic)( const char *arg0, int xpos, int ypos, int width, int height, int bits);
+ e_status (*CIN_RunCinematic) (int handle);
+
+} refimport_t;
+
+
+// this is the only function actually exported at the linker level
+// If the module can't init to a valid rendering state, NULL will be
+// returned.
+refexport_t*GetRefAPI( int apiVersion, refimport_t *rimp );
+
+#endif // __TR_PUBLIC_H
diff --git a/code/renderer/tr_scene.c b/code/renderer/tr_scene.c
new file mode 100755
index 0000000..24f569e
--- /dev/null
+++ b/code/renderer/tr_scene.c
@@ -0,0 +1,409 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "tr_local.h"
+
+int r_firstSceneDrawSurf;
+
+int r_numdlights;
+int r_firstSceneDlight;
+
+int r_numentities;
+int r_firstSceneEntity;
+
+int r_numpolys;
+int r_firstScenePoly;
+
+int r_numpolyverts;
+
+
+/*
+====================
+R_ToggleSmpFrame
+
+====================
+*/
+void R_ToggleSmpFrame( void ) {
+ if ( r_smp->integer ) {
+ // use the other buffers next frame, because another CPU
+ // may still be rendering into the current ones
+ tr.smpFrame ^= 1;
+ } else {
+ tr.smpFrame = 0;
+ }
+
+ backEndData[tr.smpFrame]->commands.used = 0;
+
+ r_firstSceneDrawSurf = 0;
+
+ r_numdlights = 0;
+ r_firstSceneDlight = 0;
+
+ r_numentities = 0;
+ r_firstSceneEntity = 0;
+
+ r_numpolys = 0;
+ r_firstScenePoly = 0;
+
+ r_numpolyverts = 0;
+}
+
+
+/*
+====================
+RE_ClearScene
+
+====================
+*/
+void RE_ClearScene( void ) {
+ r_firstSceneDlight = r_numdlights;
+ r_firstSceneEntity = r_numentities;
+ r_firstScenePoly = r_numpolys;
+}
+
+/*
+===========================================================================
+
+DISCRETE POLYS
+
+===========================================================================
+*/
+
+/*
+=====================
+R_AddPolygonSurfaces
+
+Adds all the scene's polys into this view's drawsurf list
+=====================
+*/
+void R_AddPolygonSurfaces( void ) {
+ int i;
+ shader_t *sh;
+ srfPoly_t *poly;
+
+ tr.currentEntityNum = ENTITYNUM_WORLD;
+ tr.shiftedEntityNum = tr.currentEntityNum << QSORT_ENTITYNUM_SHIFT;
+
+ for ( i = 0, poly = tr.refdef.polys; i < tr.refdef.numPolys ; i++, poly++ ) {
+ sh = R_GetShaderByHandle( poly->hShader );
+ R_AddDrawSurf( ( void * )poly, sh, poly->fogIndex, qfalse );
+ }
+}
+
+/*
+=====================
+RE_AddPolyToScene
+
+=====================
+*/
+void RE_AddPolyToScene( qhandle_t hShader, int numVerts, const polyVert_t *verts, int numPolys ) {
+ srfPoly_t *poly;
+ int i, j;
+ int fogIndex;
+ fog_t *fog;
+ vec3_t bounds[2];
+
+ if ( !tr.registered ) {
+ return;
+ }
+
+ if ( !hShader ) {
+ ri.Printf( PRINT_WARNING, "WARNING: RE_AddPolyToScene: NULL poly shader\n");
+ return;
+ }
+
+ for ( j = 0; j < numPolys; j++ ) {
+ if ( r_numpolyverts + numVerts > max_polyverts || r_numpolys >= max_polys ) {
+ /*
+ NOTE TTimo this was initially a PRINT_WARNING
+ but it happens a lot with high fighting scenes and particles
+ since we don't plan on changing the const and making for room for those effects
+ simply cut this message to developer only
+ */
+ ri.Printf( PRINT_DEVELOPER, "WARNING: RE_AddPolyToScene: r_max_polys or r_max_polyverts reached\n");
+ return;
+ }
+
+ poly = &backEndData[tr.smpFrame]->polys[r_numpolys];
+ poly->surfaceType = SF_POLY;
+ poly->hShader = hShader;
+ poly->numVerts = numVerts;
+ poly->verts = &backEndData[tr.smpFrame]->polyVerts[r_numpolyverts];
+
+ Com_Memcpy( poly->verts, &verts[numVerts*j], numVerts * sizeof( *verts ) );
+
+ if ( glConfig.hardwareType == GLHW_RAGEPRO ) {
+ poly->verts->modulate[0] = 255;
+ poly->verts->modulate[1] = 255;
+ poly->verts->modulate[2] = 255;
+ poly->verts->modulate[3] = 255;
+ }
+ // done.
+ r_numpolys++;
+ r_numpolyverts += numVerts;
+
+ // if no world is loaded
+ if ( tr.world == NULL ) {
+ fogIndex = 0;
+ }
+ // see if it is in a fog volume
+ else if ( tr.world->numfogs == 1 ) {
+ fogIndex = 0;
+ } else {
+ // find which fog volume the poly is in
+ VectorCopy( poly->verts[0].xyz, bounds[0] );
+ VectorCopy( poly->verts[0].xyz, bounds[1] );
+ for ( i = 1 ; i < poly->numVerts ; i++ ) {
+ AddPointToBounds( poly->verts[i].xyz, bounds[0], bounds[1] );
+ }
+ for ( fogIndex = 1 ; fogIndex < tr.world->numfogs ; fogIndex++ ) {
+ fog = &tr.world->fogs[fogIndex];
+ if ( bounds[1][0] >= fog->bounds[0][0]
+ && bounds[1][1] >= fog->bounds[0][1]
+ && bounds[1][2] >= fog->bounds[0][2]
+ && bounds[0][0] <= fog->bounds[1][0]
+ && bounds[0][1] <= fog->bounds[1][1]
+ && bounds[0][2] <= fog->bounds[1][2] ) {
+ break;
+ }
+ }
+ if ( fogIndex == tr.world->numfogs ) {
+ fogIndex = 0;
+ }
+ }
+ poly->fogIndex = fogIndex;
+ }
+}
+
+
+//=================================================================================
+
+
+/*
+=====================
+RE_AddRefEntityToScene
+
+=====================
+*/
+void RE_AddRefEntityToScene( const refEntity_t *ent ) {
+ if ( !tr.registered ) {
+ return;
+ }
+ // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=402
+ if ( r_numentities >= ENTITYNUM_WORLD ) {
+ return;
+ }
+ if ( ent->reType < 0 || ent->reType >= RT_MAX_REF_ENTITY_TYPE ) {
+ ri.Error( ERR_DROP, "RE_AddRefEntityToScene: bad reType %i", ent->reType );
+ }
+
+ backEndData[tr.smpFrame]->entities[r_numentities].e = *ent;
+ backEndData[tr.smpFrame]->entities[r_numentities].lightingCalculated = qfalse;
+
+ r_numentities++;
+}
+
+
+/*
+=====================
+RE_AddDynamicLightToScene
+
+=====================
+*/
+void RE_AddDynamicLightToScene( const vec3_t org, float intensity, float r, float g, float b, int additive ) {
+ dlight_t *dl;
+
+ if ( !tr.registered ) {
+ return;
+ }
+ if ( r_numdlights >= MAX_DLIGHTS ) {
+ return;
+ }
+ if ( intensity <= 0 ) {
+ return;
+ }
+ // these cards don't have the correct blend mode
+ if ( glConfig.hardwareType == GLHW_RIVA128 || glConfig.hardwareType == GLHW_PERMEDIA2 ) {
+ return;
+ }
+ dl = &backEndData[tr.smpFrame]->dlights[r_numdlights++];
+ VectorCopy (org, dl->origin);
+ dl->radius = intensity;
+ dl->color[0] = r;
+ dl->color[1] = g;
+ dl->color[2] = b;
+ dl->additive = additive;
+}
+
+/*
+=====================
+RE_AddLightToScene
+
+=====================
+*/
+void RE_AddLightToScene( const vec3_t org, float intensity, float r, float g, float b ) {
+ RE_AddDynamicLightToScene( org, intensity, r, g, b, qfalse );
+}
+
+/*
+=====================
+RE_AddAdditiveLightToScene
+
+=====================
+*/
+void RE_AddAdditiveLightToScene( const vec3_t org, float intensity, float r, float g, float b ) {
+ RE_AddDynamicLightToScene( org, intensity, r, g, b, qtrue );
+}
+
+/*
+@@@@@@@@@@@@@@@@@@@@@
+RE_RenderScene
+
+Draw a 3D view into a part of the window, then return
+to 2D drawing.
+
+Rendering a scene may require multiple views to be rendered
+to handle mirrors,
+@@@@@@@@@@@@@@@@@@@@@
+*/
+void RE_RenderScene( const refdef_t *fd ) {
+ viewParms_t parms;
+ int startTime;
+
+ if ( !tr.registered ) {
+ return;
+ }
+ GLimp_LogComment( "====== RE_RenderScene =====\n" );
+
+ if ( r_norefresh->integer ) {
+ return;
+ }
+
+ startTime = ri.Milliseconds();
+
+ if (!tr.world && !( fd->rdflags & RDF_NOWORLDMODEL ) ) {
+ ri.Error (ERR_DROP, "R_RenderScene: NULL worldmodel");
+ }
+
+ Com_Memcpy( tr.refdef.text, fd->text, sizeof( tr.refdef.text ) );
+
+ tr.refdef.x = fd->x;
+ tr.refdef.y = fd->y;
+ tr.refdef.width = fd->width;
+ tr.refdef.height = fd->height;
+ tr.refdef.fov_x = fd->fov_x;
+ tr.refdef.fov_y = fd->fov_y;
+
+ VectorCopy( fd->vieworg, tr.refdef.vieworg );
+ VectorCopy( fd->viewaxis[0], tr.refdef.viewaxis[0] );
+ VectorCopy( fd->viewaxis[1], tr.refdef.viewaxis[1] );
+ VectorCopy( fd->viewaxis[2], tr.refdef.viewaxis[2] );
+
+ tr.refdef.time = fd->time;
+ tr.refdef.rdflags = fd->rdflags;
+
+ // copy the areamask data over and note if it has changed, which
+ // will force a reset of the visible leafs even if the view hasn't moved
+ tr.refdef.areamaskModified = qfalse;
+ if ( ! (tr.refdef.rdflags & RDF_NOWORLDMODEL) ) {
+ int areaDiff;
+ int i;
+
+ // compare the area bits
+ areaDiff = 0;
+ for (i = 0 ; i < MAX_MAP_AREA_BYTES/4 ; i++) {
+ areaDiff |= ((int *)tr.refdef.areamask)[i] ^ ((int *)fd->areamask)[i];
+ ((int *)tr.refdef.areamask)[i] = ((int *)fd->areamask)[i];
+ }
+
+ if ( areaDiff ) {
+ // a door just opened or something
+ tr.refdef.areamaskModified = qtrue;
+ }
+ }
+
+
+ // derived info
+
+ tr.refdef.floatTime = tr.refdef.time * 0.001f;
+
+ tr.refdef.numDrawSurfs = r_firstSceneDrawSurf;
+ tr.refdef.drawSurfs = backEndData[tr.smpFrame]->drawSurfs;
+
+ tr.refdef.num_entities = r_numentities - r_firstSceneEntity;
+ tr.refdef.entities = &backEndData[tr.smpFrame]->entities[r_firstSceneEntity];
+
+ tr.refdef.num_dlights = r_numdlights - r_firstSceneDlight;
+ tr.refdef.dlights = &backEndData[tr.smpFrame]->dlights[r_firstSceneDlight];
+
+ tr.refdef.numPolys = r_numpolys - r_firstScenePoly;
+ tr.refdef.polys = &backEndData[tr.smpFrame]->polys[r_firstScenePoly];
+
+ // turn off dynamic lighting globally by clearing all the
+ // dlights if it needs to be disabled or if vertex lighting is enabled
+ if ( r_dynamiclight->integer == 0 ||
+ r_vertexLight->integer == 1 ||
+ glConfig.hardwareType == GLHW_PERMEDIA2 ) {
+ tr.refdef.num_dlights = 0;
+ }
+
+ // a single frame may have multiple scenes draw inside it --
+ // a 3D game view, 3D status bar renderings, 3D menus, etc.
+ // They need to be distinguished by the light flare code, because
+ // the visibility state for a given surface may be different in
+ // each scene / view.
+ tr.frameSceneNum++;
+ tr.sceneCount++;
+
+ // setup view parms for the initial view
+ //
+ // set up viewport
+ // The refdef takes 0-at-the-top y coordinates, so
+ // convert to GL's 0-at-the-bottom space
+ //
+ Com_Memset( &parms, 0, sizeof( parms ) );
+ parms.viewportX = tr.refdef.x;
+ parms.viewportY = glConfig.vidHeight - ( tr.refdef.y + tr.refdef.height );
+ parms.viewportWidth = tr.refdef.width;
+ parms.viewportHeight = tr.refdef.height;
+ parms.isPortal = qfalse;
+
+ parms.fovX = tr.refdef.fov_x;
+ parms.fovY = tr.refdef.fov_y;
+
+ VectorCopy( fd->vieworg, parms.or.origin );
+ VectorCopy( fd->viewaxis[0], parms.or.axis[0] );
+ VectorCopy( fd->viewaxis[1], parms.or.axis[1] );
+ VectorCopy( fd->viewaxis[2], parms.or.axis[2] );
+
+ VectorCopy( fd->vieworg, parms.pvsOrigin );
+
+ R_RenderView( &parms );
+
+ // the next scene rendered in this frame will tack on after this one
+ r_firstSceneDrawSurf = tr.refdef.numDrawSurfs;
+ r_firstSceneEntity = r_numentities;
+ r_firstSceneDlight = r_numdlights;
+ r_firstScenePoly = r_numpolys;
+
+ tr.frontEndMsec += ri.Milliseconds() - startTime;
+}
diff --git a/code/renderer/tr_shade.c b/code/renderer/tr_shade.c
new file mode 100755
index 0000000..eae4c1f
--- /dev/null
+++ b/code/renderer/tr_shade.c
@@ -0,0 +1,1361 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// tr_shade.c
+
+#include "tr_local.h"
+
+/*
+
+ THIS ENTIRE FILE IS BACK END
+
+ This file deals with applying shaders to surface data in the tess struct.
+*/
+
+/*
+================
+R_ArrayElementDiscrete
+
+This is just for OpenGL conformance testing, it should never be the fastest
+================
+*/
+static void APIENTRY R_ArrayElementDiscrete( GLint index ) {
+ qglColor4ubv( tess.svars.colors[ index ] );
+ if ( glState.currenttmu ) {
+ qglMultiTexCoord2fARB( 0, tess.svars.texcoords[ 0 ][ index ][0], tess.svars.texcoords[ 0 ][ index ][1] );
+ qglMultiTexCoord2fARB( 1, tess.svars.texcoords[ 1 ][ index ][0], tess.svars.texcoords[ 1 ][ index ][1] );
+ } else {
+ qglTexCoord2fv( tess.svars.texcoords[ 0 ][ index ] );
+ }
+ qglVertex3fv( tess.xyz[ index ] );
+}
+
+/*
+===================
+R_DrawStripElements
+
+===================
+*/
+static int c_vertexes; // for seeing how long our average strips are
+static int c_begins;
+static void R_DrawStripElements( int numIndexes, const glIndex_t *indexes, void ( APIENTRY *element )(GLint) ) {
+ int i;
+ int last[3] = { -1, -1, -1 };
+ qboolean even;
+
+ c_begins++;
+
+ if ( numIndexes <= 0 ) {
+ return;
+ }
+
+ qglBegin( GL_TRIANGLE_STRIP );
+
+ // prime the strip
+ element( indexes[0] );
+ element( indexes[1] );
+ element( indexes[2] );
+ c_vertexes += 3;
+
+ last[0] = indexes[0];
+ last[1] = indexes[1];
+ last[2] = indexes[2];
+
+ even = qfalse;
+
+ for ( i = 3; i < numIndexes; i += 3 )
+ {
+ // odd numbered triangle in potential strip
+ if ( !even )
+ {
+ // check previous triangle to see if we're continuing a strip
+ if ( ( indexes[i+0] == last[2] ) && ( indexes[i+1] == last[1] ) )
+ {
+ element( indexes[i+2] );
+ c_vertexes++;
+ assert( indexes[i+2] < tess.numVertexes );
+ even = qtrue;
+ }
+ // otherwise we're done with this strip so finish it and start
+ // a new one
+ else
+ {
+ qglEnd();
+
+ qglBegin( GL_TRIANGLE_STRIP );
+ c_begins++;
+
+ element( indexes[i+0] );
+ element( indexes[i+1] );
+ element( indexes[i+2] );
+
+ c_vertexes += 3;
+
+ even = qfalse;
+ }
+ }
+ else
+ {
+ // check previous triangle to see if we're continuing a strip
+ if ( ( last[2] == indexes[i+1] ) && ( last[0] == indexes[i+0] ) )
+ {
+ element( indexes[i+2] );
+ c_vertexes++;
+
+ even = qfalse;
+ }
+ // otherwise we're done with this strip so finish it and start
+ // a new one
+ else
+ {
+ qglEnd();
+
+ qglBegin( GL_TRIANGLE_STRIP );
+ c_begins++;
+
+ element( indexes[i+0] );
+ element( indexes[i+1] );
+ element( indexes[i+2] );
+ c_vertexes += 3;
+
+ even = qfalse;
+ }
+ }
+
+ // cache the last three vertices
+ last[0] = indexes[i+0];
+ last[1] = indexes[i+1];
+ last[2] = indexes[i+2];
+ }
+
+ qglEnd();
+}
+
+
+
+/*
+==================
+R_DrawElements
+
+Optionally performs our own glDrawElements that looks for strip conditions
+instead of using the single glDrawElements call that may be inefficient
+without compiled vertex arrays.
+==================
+*/
+static void R_DrawElements( int numIndexes, const glIndex_t *indexes ) {
+ int primitives;
+
+ primitives = r_primitives->integer;
+
+ // default is to use triangles if compiled vertex arrays are present
+ if ( primitives == 0 ) {
+ if ( qglLockArraysEXT ) {
+ primitives = 2;
+ } else {
+ primitives = 1;
+ }
+ }
+
+
+ if ( primitives == 2 ) {
+ qglDrawElements( GL_TRIANGLES,
+ numIndexes,
+ GL_INDEX_TYPE,
+ indexes );
+ return;
+ }
+
+ if ( primitives == 1 ) {
+ R_DrawStripElements( numIndexes, indexes, qglArrayElement );
+ return;
+ }
+
+ if ( primitives == 3 ) {
+ R_DrawStripElements( numIndexes, indexes, R_ArrayElementDiscrete );
+ return;
+ }
+
+ // anything else will cause no drawing
+}
+
+
+/*
+=============================================================
+
+SURFACE SHADERS
+
+=============================================================
+*/
+
+shaderCommands_t tess;
+static qboolean setArraysOnce;
+
+/*
+=================
+R_BindAnimatedImage
+
+=================
+*/
+static void R_BindAnimatedImage( textureBundle_t *bundle ) {
+ int index;
+
+ if ( bundle->isVideoMap ) {
+ ri.CIN_RunCinematic(bundle->videoMapHandle);
+ ri.CIN_UploadCinematic(bundle->videoMapHandle);
+ return;
+ }
+
+ if ( bundle->numImageAnimations <= 1 ) {
+ GL_Bind( bundle->image[0] );
+ return;
+ }
+
+ // it is necessary to do this messy calc to make sure animations line up
+ // exactly with waveforms of the same frequency
+ index = myftol( tess.shaderTime * bundle->imageAnimationSpeed * FUNCTABLE_SIZE );
+ index >>= FUNCTABLE_SIZE2;
+
+ if ( index < 0 ) {
+ index = 0; // may happen with shader time offsets
+ }
+ index %= bundle->numImageAnimations;
+
+ GL_Bind( bundle->image[ index ] );
+}
+
+/*
+================
+DrawTris
+
+Draws triangle outlines for debugging
+================
+*/
+static void DrawTris (shaderCommands_t *input) {
+ GL_Bind( tr.whiteImage );
+ qglColor3f (1,1,1);
+
+ GL_State( GLS_POLYMODE_LINE | GLS_DEPTHMASK_TRUE );
+ qglDepthRange( 0, 0 );
+
+ qglDisableClientState (GL_COLOR_ARRAY);
+ qglDisableClientState (GL_TEXTURE_COORD_ARRAY);
+
+ qglVertexPointer (3, GL_FLOAT, 16, input->xyz); // padded for SIMD
+
+ if (qglLockArraysEXT) {
+ qglLockArraysEXT(0, input->numVertexes);
+ GLimp_LogComment( "glLockArraysEXT\n" );
+ }
+
+ R_DrawElements( input->numIndexes, input->indexes );
+
+ if (qglUnlockArraysEXT) {
+ qglUnlockArraysEXT();
+ GLimp_LogComment( "glUnlockArraysEXT\n" );
+ }
+ qglDepthRange( 0, 1 );
+}
+
+
+/*
+================
+DrawNormals
+
+Draws vertex normals for debugging
+================
+*/
+static void DrawNormals (shaderCommands_t *input) {
+ int i;
+ vec3_t temp;
+
+ GL_Bind( tr.whiteImage );
+ qglColor3f (1,1,1);
+ qglDepthRange( 0, 0 ); // never occluded
+ GL_State( GLS_POLYMODE_LINE | GLS_DEPTHMASK_TRUE );
+
+ qglBegin (GL_LINES);
+ for (i = 0 ; i < input->numVertexes ; i++) {
+ qglVertex3fv (input->xyz[i]);
+ VectorMA (input->xyz[i], 2, input->normal[i], temp);
+ qglVertex3fv (temp);
+ }
+ qglEnd ();
+
+ qglDepthRange( 0, 1 );
+}
+
+/*
+==============
+RB_BeginSurface
+
+We must set some things up before beginning any tesselation,
+because a surface may be forced to perform a RB_End due
+to overflow.
+==============
+*/
+void RB_BeginSurface( shader_t *shader, int fogNum ) {
+
+ shader_t *state = (shader->remappedShader) ? shader->remappedShader : shader;
+
+ tess.numIndexes = 0;
+ tess.numVertexes = 0;
+ tess.shader = state;
+ tess.fogNum = fogNum;
+ tess.dlightBits = 0; // will be OR'd in by surface functions
+ tess.xstages = state->stages;
+ tess.numPasses = state->numUnfoggedPasses;
+ tess.currentStageIteratorFunc = state->optimalStageIteratorFunc;
+
+ tess.shaderTime = backEnd.refdef.floatTime - tess.shader->timeOffset;
+ if (tess.shader->clampTime && tess.shaderTime >= tess.shader->clampTime) {
+ tess.shaderTime = tess.shader->clampTime;
+ }
+
+
+}
+
+/*
+===================
+DrawMultitextured
+
+output = t0 * t1 or t0 + t1
+
+t0 = most upstream according to spec
+t1 = most downstream according to spec
+===================
+*/
+static void DrawMultitextured( shaderCommands_t *input, int stage ) {
+ shaderStage_t *pStage;
+
+ pStage = tess.xstages[stage];
+
+ GL_State( pStage->stateBits );
+
+ // this is an ugly hack to work around a GeForce driver
+ // bug with multitexture and clip planes
+ if ( backEnd.viewParms.isPortal ) {
+ qglPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
+ }
+
+ //
+ // base
+ //
+ GL_SelectTexture( 0 );
+ qglTexCoordPointer( 2, GL_FLOAT, 0, input->svars.texcoords[0] );
+ R_BindAnimatedImage( &pStage->bundle[0] );
+
+ //
+ // lightmap/secondary pass
+ //
+ GL_SelectTexture( 1 );
+ qglEnable( GL_TEXTURE_2D );
+ qglEnableClientState( GL_TEXTURE_COORD_ARRAY );
+
+ if ( r_lightmap->integer ) {
+ GL_TexEnv( GL_REPLACE );
+ } else {
+ GL_TexEnv( tess.shader->multitextureEnv );
+ }
+
+ qglTexCoordPointer( 2, GL_FLOAT, 0, input->svars.texcoords[1] );
+
+ R_BindAnimatedImage( &pStage->bundle[1] );
+
+ R_DrawElements( input->numIndexes, input->indexes );
+
+ //
+ // disable texturing on TEXTURE1, then select TEXTURE0
+ //
+ //qglDisableClientState( GL_TEXTURE_COORD_ARRAY );
+ qglDisable( GL_TEXTURE_2D );
+
+ GL_SelectTexture( 0 );
+}
+
+
+
+/*
+===================
+ProjectDlightTexture
+
+Perform dynamic lighting with another rendering pass
+===================
+*/
+static void ProjectDlightTexture( void ) {
+ int i, l;
+#if idppc_altivec
+ vec_t origin0, origin1, origin2;
+ float texCoords0, texCoords1;
+ vector float floatColorVec0, floatColorVec1;
+ vector float modulateVec, colorVec, zero;
+ vector short colorShort;
+ vector signed int colorInt;
+ vector unsigned char floatColorVecPerm, modulatePerm, colorChar;
+ vector unsigned char vSel = (vector unsigned char)(0x00, 0x00, 0x00, 0xff,
+ 0x00, 0x00, 0x00, 0xff,
+ 0x00, 0x00, 0x00, 0xff,
+ 0x00, 0x00, 0x00, 0xff);
+#else
+ vec3_t origin;
+#endif
+ float *texCoords;
+ byte *colors;
+ byte clipBits[SHADER_MAX_VERTEXES];
+ MAC_STATIC float texCoordsArray[SHADER_MAX_VERTEXES][2];
+ byte colorArray[SHADER_MAX_VERTEXES][4];
+ unsigned hitIndexes[SHADER_MAX_INDEXES];
+ int numIndexes;
+ float scale;
+ float radius;
+ vec3_t floatColor;
+ float modulate;
+
+ if ( !backEnd.refdef.num_dlights ) {
+ return;
+ }
+
+#if idppc_altivec
+ // There has to be a better way to do this so that floatColor
+ // and/or modulate are already 16-byte aligned.
+ floatColorVecPerm = vec_lvsl(0,(float *)floatColor);
+ modulatePerm = vec_lvsl(0,(float *)&modulate);
+ modulatePerm = (vector unsigned char)vec_splat((vector unsigned int)modulatePerm,0);
+ zero = (vector float)vec_splat_s8(0);
+#endif
+
+ for ( l = 0 ; l < backEnd.refdef.num_dlights ; l++ ) {
+ dlight_t *dl;
+
+ if ( !( tess.dlightBits & ( 1 << l ) ) ) {
+ continue; // this surface definately doesn't have any of this light
+ }
+ texCoords = texCoordsArray[0];
+ colors = colorArray[0];
+
+ dl = &backEnd.refdef.dlights[l];
+#if idppc_altivec
+ origin0 = dl->transformed[0];
+ origin1 = dl->transformed[1];
+ origin2 = dl->transformed[2];
+#else
+ VectorCopy( dl->transformed, origin );
+#endif
+ radius = dl->radius;
+ scale = 1.0f / radius;
+
+ floatColor[0] = dl->color[0] * 255.0f;
+ floatColor[1] = dl->color[1] * 255.0f;
+ floatColor[2] = dl->color[2] * 255.0f;
+#if idppc_altivec
+ floatColorVec0 = vec_ld(0, floatColor);
+ floatColorVec1 = vec_ld(11, floatColor);
+ floatColorVec0 = vec_perm(floatColorVec0,floatColorVec0,floatColorVecPerm);
+#endif
+ for ( i = 0 ; i < tess.numVertexes ; i++, texCoords += 2, colors += 4 ) {
+#if idppc_altivec
+ vec_t dist0, dist1, dist2;
+#else
+ vec3_t dist;
+#endif
+ int clip;
+
+ backEnd.pc.c_dlightVertexes++;
+
+#if idppc_altivec
+ //VectorSubtract( origin, tess.xyz[i], dist );
+ dist0 = origin0 - tess.xyz[i][0];
+ dist1 = origin1 - tess.xyz[i][1];
+ dist2 = origin2 - tess.xyz[i][2];
+ texCoords0 = 0.5f + dist0 * scale;
+ texCoords1 = 0.5f + dist1 * scale;
+
+ clip = 0;
+ if ( texCoords0 < 0.0f ) {
+ clip |= 1;
+ } else if ( texCoords0 > 1.0f ) {
+ clip |= 2;
+ }
+ if ( texCoords1 < 0.0f ) {
+ clip |= 4;
+ } else if ( texCoords1 > 1.0f ) {
+ clip |= 8;
+ }
+ texCoords[0] = texCoords0;
+ texCoords[1] = texCoords1;
+
+ // modulate the strength based on the height and color
+ if ( dist2 > radius ) {
+ clip |= 16;
+ modulate = 0.0f;
+ } else if ( dist2 < -radius ) {
+ clip |= 32;
+ modulate = 0.0f;
+ } else {
+ dist2 = Q_fabs(dist2);
+ if ( dist2 < radius * 0.5f ) {
+ modulate = 1.0f;
+ } else {
+ modulate = 2.0f * (radius - dist2) * scale;
+ }
+ }
+ clipBits[i] = clip;
+
+ modulateVec = vec_ld(0,(float *)&modulate);
+ modulateVec = vec_perm(modulateVec,modulateVec,modulatePerm);
+ colorVec = vec_madd(floatColorVec0,modulateVec,zero);
+ colorInt = vec_cts(colorVec,0); // RGBx
+ colorShort = vec_pack(colorInt,colorInt); // RGBxRGBx
+ colorChar = vec_packsu(colorShort,colorShort); // RGBxRGBxRGBxRGBx
+ colorChar = vec_sel(colorChar,vSel,vSel); // RGBARGBARGBARGBA replace alpha with 255
+ vec_ste((vector unsigned int)colorChar,0,(unsigned int *)colors); // store color
+#else
+ VectorSubtract( origin, tess.xyz[i], dist );
+ texCoords[0] = 0.5f + dist[0] * scale;
+ texCoords[1] = 0.5f + dist[1] * scale;
+
+ clip = 0;
+ if ( texCoords[0] < 0.0f ) {
+ clip |= 1;
+ } else if ( texCoords[0] > 1.0f ) {
+ clip |= 2;
+ }
+ if ( texCoords[1] < 0.0f ) {
+ clip |= 4;
+ } else if ( texCoords[1] > 1.0f ) {
+ clip |= 8;
+ }
+ // modulate the strength based on the height and color
+ if ( dist[2] > radius ) {
+ clip |= 16;
+ modulate = 0.0f;
+ } else if ( dist[2] < -radius ) {
+ clip |= 32;
+ modulate = 0.0f;
+ } else {
+ dist[2] = Q_fabs(dist[2]);
+ if ( dist[2] < radius * 0.5f ) {
+ modulate = 1.0f;
+ } else {
+ modulate = 2.0f * (radius - dist[2]) * scale;
+ }
+ }
+ clipBits[i] = clip;
+
+ colors[0] = myftol(floatColor[0] * modulate);
+ colors[1] = myftol(floatColor[1] * modulate);
+ colors[2] = myftol(floatColor[2] * modulate);
+ colors[3] = 255;
+#endif
+ }
+
+ // build a list of triangles that need light
+ numIndexes = 0;
+ for ( i = 0 ; i < tess.numIndexes ; i += 3 ) {
+ int a, b, c;
+
+ a = tess.indexes[i];
+ b = tess.indexes[i+1];
+ c = tess.indexes[i+2];
+ if ( clipBits[a] & clipBits[b] & clipBits[c] ) {
+ continue; // not lighted
+ }
+ hitIndexes[numIndexes] = a;
+ hitIndexes[numIndexes+1] = b;
+ hitIndexes[numIndexes+2] = c;
+ numIndexes += 3;
+ }
+
+ if ( !numIndexes ) {
+ continue;
+ }
+
+ qglEnableClientState( GL_TEXTURE_COORD_ARRAY );
+ qglTexCoordPointer( 2, GL_FLOAT, 0, texCoordsArray[0] );
+
+ qglEnableClientState( GL_COLOR_ARRAY );
+ qglColorPointer( 4, GL_UNSIGNED_BYTE, 0, colorArray );
+
+ GL_Bind( tr.dlightImage );
+ // include GLS_DEPTHFUNC_EQUAL so alpha tested surfaces don't add light
+ // where they aren't rendered
+ if ( dl->additive ) {
+ GL_State( GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_EQUAL );
+ }
+ else {
+ GL_State( GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_EQUAL );
+ }
+ R_DrawElements( numIndexes, hitIndexes );
+ backEnd.pc.c_totalIndexes += numIndexes;
+ backEnd.pc.c_dlightIndexes += numIndexes;
+ }
+}
+
+
+/*
+===================
+RB_FogPass
+
+Blends a fog texture on top of everything else
+===================
+*/
+static void RB_FogPass( void ) {
+ fog_t *fog;
+ int i;
+
+ qglEnableClientState( GL_COLOR_ARRAY );
+ qglColorPointer( 4, GL_UNSIGNED_BYTE, 0, tess.svars.colors );
+
+ qglEnableClientState( GL_TEXTURE_COORD_ARRAY);
+ qglTexCoordPointer( 2, GL_FLOAT, 0, tess.svars.texcoords[0] );
+
+ fog = tr.world->fogs + tess.fogNum;
+
+ for ( i = 0; i < tess.numVertexes; i++ ) {
+ * ( int * )&tess.svars.colors[i] = fog->colorInt;
+ }
+
+ RB_CalcFogTexCoords( ( float * ) tess.svars.texcoords[0] );
+
+ GL_Bind( tr.fogImage );
+
+ if ( tess.shader->fogPass == FP_EQUAL ) {
+ GL_State( GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA | GLS_DEPTHFUNC_EQUAL );
+ } else {
+ GL_State( GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA );
+ }
+
+ R_DrawElements( tess.numIndexes, tess.indexes );
+}
+
+/*
+===============
+ComputeColors
+===============
+*/
+static void ComputeColors( shaderStage_t *pStage )
+{
+ int i;
+
+ //
+ // rgbGen
+ //
+ switch ( pStage->rgbGen )
+ {
+ case CGEN_IDENTITY:
+ Com_Memset( tess.svars.colors, 0xff, tess.numVertexes * 4 );
+ break;
+ default:
+ case CGEN_IDENTITY_LIGHTING:
+ Com_Memset( tess.svars.colors, tr.identityLightByte, tess.numVertexes * 4 );
+ break;
+ case CGEN_LIGHTING_DIFFUSE:
+ RB_CalcDiffuseColor( ( unsigned char * ) tess.svars.colors );
+ break;
+ case CGEN_EXACT_VERTEX:
+ Com_Memcpy( tess.svars.colors, tess.vertexColors, tess.numVertexes * sizeof( tess.vertexColors[0] ) );
+ break;
+ case CGEN_CONST:
+ for ( i = 0; i < tess.numVertexes; i++ ) {
+ *(int *)tess.svars.colors[i] = *(int *)pStage->constantColor;
+ }
+ break;
+ case CGEN_VERTEX:
+ if ( tr.identityLight == 1 )
+ {
+ Com_Memcpy( tess.svars.colors, tess.vertexColors, tess.numVertexes * sizeof( tess.vertexColors[0] ) );
+ }
+ else
+ {
+ for ( i = 0; i < tess.numVertexes; i++ )
+ {
+ tess.svars.colors[i][0] = tess.vertexColors[i][0] * tr.identityLight;
+ tess.svars.colors[i][1] = tess.vertexColors[i][1] * tr.identityLight;
+ tess.svars.colors[i][2] = tess.vertexColors[i][2] * tr.identityLight;
+ tess.svars.colors[i][3] = tess.vertexColors[i][3];
+ }
+ }
+ break;
+ case CGEN_ONE_MINUS_VERTEX:
+ if ( tr.identityLight == 1 )
+ {
+ for ( i = 0; i < tess.numVertexes; i++ )
+ {
+ tess.svars.colors[i][0] = 255 - tess.vertexColors[i][0];
+ tess.svars.colors[i][1] = 255 - tess.vertexColors[i][1];
+ tess.svars.colors[i][2] = 255 - tess.vertexColors[i][2];
+ }
+ }
+ else
+ {
+ for ( i = 0; i < tess.numVertexes; i++ )
+ {
+ tess.svars.colors[i][0] = ( 255 - tess.vertexColors[i][0] ) * tr.identityLight;
+ tess.svars.colors[i][1] = ( 255 - tess.vertexColors[i][1] ) * tr.identityLight;
+ tess.svars.colors[i][2] = ( 255 - tess.vertexColors[i][2] ) * tr.identityLight;
+ }
+ }
+ break;
+ case CGEN_FOG:
+ {
+ fog_t *fog;
+
+ fog = tr.world->fogs + tess.fogNum;
+
+ for ( i = 0; i < tess.numVertexes; i++ ) {
+ * ( int * )&tess.svars.colors[i] = fog->colorInt;
+ }
+ }
+ break;
+ case CGEN_WAVEFORM:
+ RB_CalcWaveColor( &pStage->rgbWave, ( unsigned char * ) tess.svars.colors );
+ break;
+ case CGEN_ENTITY:
+ RB_CalcColorFromEntity( ( unsigned char * ) tess.svars.colors );
+ break;
+ case CGEN_ONE_MINUS_ENTITY:
+ RB_CalcColorFromOneMinusEntity( ( unsigned char * ) tess.svars.colors );
+ break;
+ }
+
+ //
+ // alphaGen
+ //
+ switch ( pStage->alphaGen )
+ {
+ case AGEN_SKIP:
+ break;
+ case AGEN_IDENTITY:
+ if ( pStage->rgbGen != CGEN_IDENTITY ) {
+ if ( ( pStage->rgbGen == CGEN_VERTEX && tr.identityLight != 1 ) ||
+ pStage->rgbGen != CGEN_VERTEX ) {
+ for ( i = 0; i < tess.numVertexes; i++ ) {
+ tess.svars.colors[i][3] = 0xff;
+ }
+ }
+ }
+ break;
+ case AGEN_CONST:
+ if ( pStage->rgbGen != CGEN_CONST ) {
+ for ( i = 0; i < tess.numVertexes; i++ ) {
+ tess.svars.colors[i][3] = pStage->constantColor[3];
+ }
+ }
+ break;
+ case AGEN_WAVEFORM:
+ RB_CalcWaveAlpha( &pStage->alphaWave, ( unsigned char * ) tess.svars.colors );
+ break;
+ case AGEN_LIGHTING_SPECULAR:
+ RB_CalcSpecularAlpha( ( unsigned char * ) tess.svars.colors );
+ break;
+ case AGEN_ENTITY:
+ RB_CalcAlphaFromEntity( ( unsigned char * ) tess.svars.colors );
+ break;
+ case AGEN_ONE_MINUS_ENTITY:
+ RB_CalcAlphaFromOneMinusEntity( ( unsigned char * ) tess.svars.colors );
+ break;
+ case AGEN_VERTEX:
+ if ( pStage->rgbGen != CGEN_VERTEX ) {
+ for ( i = 0; i < tess.numVertexes; i++ ) {
+ tess.svars.colors[i][3] = tess.vertexColors[i][3];
+ }
+ }
+ break;
+ case AGEN_ONE_MINUS_VERTEX:
+ for ( i = 0; i < tess.numVertexes; i++ )
+ {
+ tess.svars.colors[i][3] = 255 - tess.vertexColors[i][3];
+ }
+ break;
+ case AGEN_PORTAL:
+ {
+ unsigned char alpha;
+
+ for ( i = 0; i < tess.numVertexes; i++ )
+ {
+ float len;
+ vec3_t v;
+
+ VectorSubtract( tess.xyz[i], backEnd.viewParms.or.origin, v );
+ len = VectorLength( v );
+
+ len /= tess.shader->portalRange;
+
+ if ( len < 0 )
+ {
+ alpha = 0;
+ }
+ else if ( len > 1 )
+ {
+ alpha = 0xff;
+ }
+ else
+ {
+ alpha = len * 0xff;
+ }
+
+ tess.svars.colors[i][3] = alpha;
+ }
+ }
+ break;
+ }
+
+ //
+ // fog adjustment for colors to fade out as fog increases
+ //
+ if ( tess.fogNum )
+ {
+ switch ( pStage->adjustColorsForFog )
+ {
+ case ACFF_MODULATE_RGB:
+ RB_CalcModulateColorsByFog( ( unsigned char * ) tess.svars.colors );
+ break;
+ case ACFF_MODULATE_ALPHA:
+ RB_CalcModulateAlphasByFog( ( unsigned char * ) tess.svars.colors );
+ break;
+ case ACFF_MODULATE_RGBA:
+ RB_CalcModulateRGBAsByFog( ( unsigned char * ) tess.svars.colors );
+ break;
+ case ACFF_NONE:
+ break;
+ }
+ }
+}
+
+/*
+===============
+ComputeTexCoords
+===============
+*/
+static void ComputeTexCoords( shaderStage_t *pStage ) {
+ int i;
+ int b;
+
+ for ( b = 0; b < NUM_TEXTURE_BUNDLES; b++ ) {
+ int tm;
+
+ //
+ // generate the texture coordinates
+ //
+ switch ( pStage->bundle[b].tcGen )
+ {
+ case TCGEN_IDENTITY:
+ Com_Memset( tess.svars.texcoords[b], 0, sizeof( float ) * 2 * tess.numVertexes );
+ break;
+ case TCGEN_TEXTURE:
+ for ( i = 0 ; i < tess.numVertexes ; i++ ) {
+ tess.svars.texcoords[b][i][0] = tess.texCoords[i][0][0];
+ tess.svars.texcoords[b][i][1] = tess.texCoords[i][0][1];
+ }
+ break;
+ case TCGEN_LIGHTMAP:
+ for ( i = 0 ; i < tess.numVertexes ; i++ ) {
+ tess.svars.texcoords[b][i][0] = tess.texCoords[i][1][0];
+ tess.svars.texcoords[b][i][1] = tess.texCoords[i][1][1];
+ }
+ break;
+ case TCGEN_VECTOR:
+ for ( i = 0 ; i < tess.numVertexes ; i++ ) {
+ tess.svars.texcoords[b][i][0] = DotProduct( tess.xyz[i], pStage->bundle[b].tcGenVectors[0] );
+ tess.svars.texcoords[b][i][1] = DotProduct( tess.xyz[i], pStage->bundle[b].tcGenVectors[1] );
+ }
+ break;
+ case TCGEN_FOG:
+ RB_CalcFogTexCoords( ( float * ) tess.svars.texcoords[b] );
+ break;
+ case TCGEN_ENVIRONMENT_MAPPED:
+ RB_CalcEnvironmentTexCoords( ( float * ) tess.svars.texcoords[b] );
+ break;
+ case TCGEN_BAD:
+ return;
+ }
+
+ //
+ // alter texture coordinates
+ //
+ for ( tm = 0; tm < pStage->bundle[b].numTexMods ; tm++ ) {
+ switch ( pStage->bundle[b].texMods[tm].type )
+ {
+ case TMOD_NONE:
+ tm = TR_MAX_TEXMODS; // break out of for loop
+ break;
+
+ case TMOD_TURBULENT:
+ RB_CalcTurbulentTexCoords( &pStage->bundle[b].texMods[tm].wave,
+ ( float * ) tess.svars.texcoords[b] );
+ break;
+
+ case TMOD_ENTITY_TRANSLATE:
+ RB_CalcScrollTexCoords( backEnd.currentEntity->e.shaderTexCoord,
+ ( float * ) tess.svars.texcoords[b] );
+ break;
+
+ case TMOD_SCROLL:
+ RB_CalcScrollTexCoords( pStage->bundle[b].texMods[tm].scroll,
+ ( float * ) tess.svars.texcoords[b] );
+ break;
+
+ case TMOD_SCALE:
+ RB_CalcScaleTexCoords( pStage->bundle[b].texMods[tm].scale,
+ ( float * ) tess.svars.texcoords[b] );
+ break;
+
+ case TMOD_STRETCH:
+ RB_CalcStretchTexCoords( &pStage->bundle[b].texMods[tm].wave,
+ ( float * ) tess.svars.texcoords[b] );
+ break;
+
+ case TMOD_TRANSFORM:
+ RB_CalcTransformTexCoords( &pStage->bundle[b].texMods[tm],
+ ( float * ) tess.svars.texcoords[b] );
+ break;
+
+ case TMOD_ROTATE:
+ RB_CalcRotateTexCoords( pStage->bundle[b].texMods[tm].rotateSpeed,
+ ( float * ) tess.svars.texcoords[b] );
+ break;
+
+ default:
+ ri.Error( ERR_DROP, "ERROR: unknown texmod '%d' in shader '%s'\n", pStage->bundle[b].texMods[tm].type, tess.shader->name );
+ break;
+ }
+ }
+ }
+}
+
+/*
+** RB_IterateStagesGeneric
+*/
+static void RB_IterateStagesGeneric( shaderCommands_t *input )
+{
+ int stage;
+
+ for ( stage = 0; stage < MAX_SHADER_STAGES; stage++ )
+ {
+ shaderStage_t *pStage = tess.xstages[stage];
+
+ if ( !pStage )
+ {
+ break;
+ }
+
+ ComputeColors( pStage );
+ ComputeTexCoords( pStage );
+
+ if ( !setArraysOnce )
+ {
+ qglEnableClientState( GL_COLOR_ARRAY );
+ qglColorPointer( 4, GL_UNSIGNED_BYTE, 0, input->svars.colors );
+ }
+
+ //
+ // do multitexture
+ //
+ if ( pStage->bundle[1].image[0] != 0 )
+ {
+ DrawMultitextured( input, stage );
+ }
+ else
+ {
+ if ( !setArraysOnce )
+ {
+ qglTexCoordPointer( 2, GL_FLOAT, 0, input->svars.texcoords[0] );
+ }
+
+ //
+ // set state
+ //
+ if ( pStage->bundle[0].vertexLightmap && ( (r_vertexLight->integer && !r_uiFullScreen->integer) || glConfig.hardwareType == GLHW_PERMEDIA2 ) && r_lightmap->integer )
+ {
+ GL_Bind( tr.whiteImage );
+ }
+ else
+ R_BindAnimatedImage( &pStage->bundle[0] );
+
+ GL_State( pStage->stateBits );
+
+ //
+ // draw
+ //
+ R_DrawElements( input->numIndexes, input->indexes );
+ }
+ // allow skipping out to show just lightmaps during development
+ if ( r_lightmap->integer && ( pStage->bundle[0].isLightmap || pStage->bundle[1].isLightmap || pStage->bundle[0].vertexLightmap ) )
+ {
+ break;
+ }
+ }
+}
+
+
+/*
+** RB_StageIteratorGeneric
+*/
+void RB_StageIteratorGeneric( void )
+{
+ shaderCommands_t *input;
+
+ input = &tess;
+
+ RB_DeformTessGeometry();
+
+ //
+ // log this call
+ //
+ if ( r_logFile->integer )
+ {
+ // don't just call LogComment, or we will get
+ // a call to va() every frame!
+ GLimp_LogComment( va("--- RB_StageIteratorGeneric( %s ) ---\n", tess.shader->name) );
+ }
+
+ //
+ // set face culling appropriately
+ //
+ GL_Cull( input->shader->cullType );
+
+ // set polygon offset if necessary
+ if ( input->shader->polygonOffset )
+ {
+ qglEnable( GL_POLYGON_OFFSET_FILL );
+ qglPolygonOffset( r_offsetFactor->value, r_offsetUnits->value );
+ }
+
+ //
+ // if there is only a single pass then we can enable color
+ // and texture arrays before we compile, otherwise we need
+ // to avoid compiling those arrays since they will change
+ // during multipass rendering
+ //
+ if ( tess.numPasses > 1 || input->shader->multitextureEnv )
+ {
+ setArraysOnce = qfalse;
+ qglDisableClientState (GL_COLOR_ARRAY);
+ qglDisableClientState (GL_TEXTURE_COORD_ARRAY);
+ }
+ else
+ {
+ setArraysOnce = qtrue;
+
+ qglEnableClientState( GL_COLOR_ARRAY);
+ qglColorPointer( 4, GL_UNSIGNED_BYTE, 0, tess.svars.colors );
+
+ qglEnableClientState( GL_TEXTURE_COORD_ARRAY);
+ qglTexCoordPointer( 2, GL_FLOAT, 0, tess.svars.texcoords[0] );
+ }
+
+ //
+ // lock XYZ
+ //
+ qglVertexPointer (3, GL_FLOAT, 16, input->xyz); // padded for SIMD
+ if (qglLockArraysEXT)
+ {
+ qglLockArraysEXT(0, input->numVertexes);
+ GLimp_LogComment( "glLockArraysEXT\n" );
+ }
+
+ //
+ // enable color and texcoord arrays after the lock if necessary
+ //
+ if ( !setArraysOnce )
+ {
+ qglEnableClientState( GL_TEXTURE_COORD_ARRAY );
+ qglEnableClientState( GL_COLOR_ARRAY );
+ }
+
+ //
+ // call shader function
+ //
+ RB_IterateStagesGeneric( input );
+
+ //
+ // now do any dynamic lighting needed
+ //
+ if ( tess.dlightBits && tess.shader->sort <= SS_OPAQUE
+ && !(tess.shader->surfaceFlags & (SURF_NODLIGHT | SURF_SKY) ) ) {
+ ProjectDlightTexture();
+ }
+
+ //
+ // now do fog
+ //
+ if ( tess.fogNum && tess.shader->fogPass ) {
+ RB_FogPass();
+ }
+
+ //
+ // unlock arrays
+ //
+ if (qglUnlockArraysEXT)
+ {
+ qglUnlockArraysEXT();
+ GLimp_LogComment( "glUnlockArraysEXT\n" );
+ }
+
+ //
+ // reset polygon offset
+ //
+ if ( input->shader->polygonOffset )
+ {
+ qglDisable( GL_POLYGON_OFFSET_FILL );
+ }
+}
+
+
+/*
+** RB_StageIteratorVertexLitTexture
+*/
+void RB_StageIteratorVertexLitTexture( void )
+{
+ shaderCommands_t *input;
+ shader_t *shader;
+
+ input = &tess;
+
+ shader = input->shader;
+
+ //
+ // compute colors
+ //
+ RB_CalcDiffuseColor( ( unsigned char * ) tess.svars.colors );
+
+ //
+ // log this call
+ //
+ if ( r_logFile->integer )
+ {
+ // don't just call LogComment, or we will get
+ // a call to va() every frame!
+ GLimp_LogComment( va("--- RB_StageIteratorVertexLitTexturedUnfogged( %s ) ---\n", tess.shader->name) );
+ }
+
+ //
+ // set face culling appropriately
+ //
+ GL_Cull( input->shader->cullType );
+
+ //
+ // set arrays and lock
+ //
+ qglEnableClientState( GL_COLOR_ARRAY);
+ qglEnableClientState( GL_TEXTURE_COORD_ARRAY);
+
+ qglColorPointer( 4, GL_UNSIGNED_BYTE, 0, tess.svars.colors );
+ qglTexCoordPointer( 2, GL_FLOAT, 16, tess.texCoords[0][0] );
+ qglVertexPointer (3, GL_FLOAT, 16, input->xyz);
+
+ if ( qglLockArraysEXT )
+ {
+ qglLockArraysEXT(0, input->numVertexes);
+ GLimp_LogComment( "glLockArraysEXT\n" );
+ }
+
+ //
+ // call special shade routine
+ //
+ R_BindAnimatedImage( &tess.xstages[0]->bundle[0] );
+ GL_State( tess.xstages[0]->stateBits );
+ R_DrawElements( input->numIndexes, input->indexes );
+
+ //
+ // now do any dynamic lighting needed
+ //
+ if ( tess.dlightBits && tess.shader->sort <= SS_OPAQUE ) {
+ ProjectDlightTexture();
+ }
+
+ //
+ // now do fog
+ //
+ if ( tess.fogNum && tess.shader->fogPass ) {
+ RB_FogPass();
+ }
+
+ //
+ // unlock arrays
+ //
+ if (qglUnlockArraysEXT)
+ {
+ qglUnlockArraysEXT();
+ GLimp_LogComment( "glUnlockArraysEXT\n" );
+ }
+}
+
+//define REPLACE_MODE
+
+void RB_StageIteratorLightmappedMultitexture( void ) {
+ shaderCommands_t *input;
+
+ input = &tess;
+
+ //
+ // log this call
+ //
+ if ( r_logFile->integer ) {
+ // don't just call LogComment, or we will get
+ // a call to va() every frame!
+ GLimp_LogComment( va("--- RB_StageIteratorLightmappedMultitexture( %s ) ---\n", tess.shader->name) );
+ }
+
+ //
+ // set face culling appropriately
+ //
+ GL_Cull( input->shader->cullType );
+
+ //
+ // set color, pointers, and lock
+ //
+ GL_State( GLS_DEFAULT );
+ qglVertexPointer( 3, GL_FLOAT, 16, input->xyz );
+
+#ifdef REPLACE_MODE
+ qglDisableClientState( GL_COLOR_ARRAY );
+ qglColor3f( 1, 1, 1 );
+ qglShadeModel( GL_FLAT );
+#else
+ qglEnableClientState( GL_COLOR_ARRAY );
+ qglColorPointer( 4, GL_UNSIGNED_BYTE, 0, tess.constantColor255 );
+#endif
+
+ //
+ // select base stage
+ //
+ GL_SelectTexture( 0 );
+
+ qglEnableClientState( GL_TEXTURE_COORD_ARRAY );
+ R_BindAnimatedImage( &tess.xstages[0]->bundle[0] );
+ qglTexCoordPointer( 2, GL_FLOAT, 16, tess.texCoords[0][0] );
+
+ //
+ // configure second stage
+ //
+ GL_SelectTexture( 1 );
+ qglEnable( GL_TEXTURE_2D );
+ if ( r_lightmap->integer ) {
+ GL_TexEnv( GL_REPLACE );
+ } else {
+ GL_TexEnv( GL_MODULATE );
+ }
+ R_BindAnimatedImage( &tess.xstages[0]->bundle[1] );
+ qglEnableClientState( GL_TEXTURE_COORD_ARRAY );
+ qglTexCoordPointer( 2, GL_FLOAT, 16, tess.texCoords[0][1] );
+
+ //
+ // lock arrays
+ //
+ if ( qglLockArraysEXT ) {
+ qglLockArraysEXT(0, input->numVertexes);
+ GLimp_LogComment( "glLockArraysEXT\n" );
+ }
+
+ R_DrawElements( input->numIndexes, input->indexes );
+
+ //
+ // disable texturing on TEXTURE1, then select TEXTURE0
+ //
+ qglDisable( GL_TEXTURE_2D );
+ qglDisableClientState( GL_TEXTURE_COORD_ARRAY );
+
+ GL_SelectTexture( 0 );
+#ifdef REPLACE_MODE
+ GL_TexEnv( GL_MODULATE );
+ qglShadeModel( GL_SMOOTH );
+#endif
+
+ //
+ // now do any dynamic lighting needed
+ //
+ if ( tess.dlightBits && tess.shader->sort <= SS_OPAQUE ) {
+ ProjectDlightTexture();
+ }
+
+ //
+ // now do fog
+ //
+ if ( tess.fogNum && tess.shader->fogPass ) {
+ RB_FogPass();
+ }
+
+ //
+ // unlock arrays
+ //
+ if ( qglUnlockArraysEXT ) {
+ qglUnlockArraysEXT();
+ GLimp_LogComment( "glUnlockArraysEXT\n" );
+ }
+}
+
+/*
+** RB_EndSurface
+*/
+void RB_EndSurface( void ) {
+ shaderCommands_t *input;
+
+ input = &tess;
+
+ if (input->numIndexes == 0) {
+ return;
+ }
+
+ if (input->indexes[SHADER_MAX_INDEXES-1] != 0) {
+ ri.Error (ERR_DROP, "RB_EndSurface() - SHADER_MAX_INDEXES hit");
+ }
+ if (input->xyz[SHADER_MAX_VERTEXES-1][0] != 0) {
+ ri.Error (ERR_DROP, "RB_EndSurface() - SHADER_MAX_VERTEXES hit");
+ }
+
+ if ( tess.shader == tr.shadowShader ) {
+ RB_ShadowTessEnd();
+ return;
+ }
+
+ // for debugging of sort order issues, stop rendering after a given sort value
+ if ( r_debugSort->integer && r_debugSort->integer < tess.shader->sort ) {
+ return;
+ }
+
+ //
+ // update performance counters
+ //
+ backEnd.pc.c_shaders++;
+ backEnd.pc.c_vertexes += tess.numVertexes;
+ backEnd.pc.c_indexes += tess.numIndexes;
+ backEnd.pc.c_totalIndexes += tess.numIndexes * tess.numPasses;
+
+ //
+ // call off to shader specific tess end function
+ //
+ tess.currentStageIteratorFunc();
+
+ //
+ // draw debugging stuff
+ //
+ if ( r_showtris->integer ) {
+ DrawTris (input);
+ }
+ if ( r_shownormals->integer ) {
+ DrawNormals (input);
+ }
+ // clear shader so we can tell we don't have any unclosed surfaces
+ tess.numIndexes = 0;
+
+ GLimp_LogComment( "----------\n" );
+}
+
diff --git a/code/renderer/tr_shade_calc.c b/code/renderer/tr_shade_calc.c
new file mode 100755
index 0000000..f1f0e6d
--- /dev/null
+++ b/code/renderer/tr_shade_calc.c
@@ -0,0 +1,1205 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// tr_shade_calc.c
+
+#include "tr_local.h"
+
+
+#define WAVEVALUE( table, base, amplitude, phase, freq ) ((base) + table[ myftol( ( ( (phase) + tess.shaderTime * (freq) ) * FUNCTABLE_SIZE ) ) & FUNCTABLE_MASK ] * (amplitude))
+
+static float *TableForFunc( genFunc_t func )
+{
+ switch ( func )
+ {
+ case GF_SIN:
+ return tr.sinTable;
+ case GF_TRIANGLE:
+ return tr.triangleTable;
+ case GF_SQUARE:
+ return tr.squareTable;
+ case GF_SAWTOOTH:
+ return tr.sawToothTable;
+ case GF_INVERSE_SAWTOOTH:
+ return tr.inverseSawToothTable;
+ case GF_NONE:
+ default:
+ break;
+ }
+
+ ri.Error( ERR_DROP, "TableForFunc called with invalid function '%d' in shader '%s'\n", func, tess.shader->name );
+ return NULL;
+}
+
+/*
+** EvalWaveForm
+**
+** Evaluates a given waveForm_t, referencing backEnd.refdef.time directly
+*/
+static float EvalWaveForm( const waveForm_t *wf )
+{
+ float *table;
+
+ table = TableForFunc( wf->func );
+
+ return WAVEVALUE( table, wf->base, wf->amplitude, wf->phase, wf->frequency );
+}
+
+static float EvalWaveFormClamped( const waveForm_t *wf )
+{
+ float glow = EvalWaveForm( wf );
+
+ if ( glow < 0 )
+ {
+ return 0;
+ }
+
+ if ( glow > 1 )
+ {
+ return 1;
+ }
+
+ return glow;
+}
+
+/*
+** RB_CalcStretchTexCoords
+*/
+void RB_CalcStretchTexCoords( const waveForm_t *wf, float *st )
+{
+ float p;
+ texModInfo_t tmi;
+
+ p = 1.0f / EvalWaveForm( wf );
+
+ tmi.matrix[0][0] = p;
+ tmi.matrix[1][0] = 0;
+ tmi.translate[0] = 0.5f - 0.5f * p;
+
+ tmi.matrix[0][1] = 0;
+ tmi.matrix[1][1] = p;
+ tmi.translate[1] = 0.5f - 0.5f * p;
+
+ RB_CalcTransformTexCoords( &tmi, st );
+}
+
+/*
+====================================================================
+
+DEFORMATIONS
+
+====================================================================
+*/
+
+/*
+========================
+RB_CalcDeformVertexes
+
+========================
+*/
+void RB_CalcDeformVertexes( deformStage_t *ds )
+{
+ int i;
+ vec3_t offset;
+ float scale;
+ float *xyz = ( float * ) tess.xyz;
+ float *normal = ( float * ) tess.normal;
+ float *table;
+
+ if ( ds->deformationWave.frequency == 0 )
+ {
+ scale = EvalWaveForm( &ds->deformationWave );
+
+ for ( i = 0; i < tess.numVertexes; i++, xyz += 4, normal += 4 )
+ {
+ VectorScale( normal, scale, offset );
+
+ xyz[0] += offset[0];
+ xyz[1] += offset[1];
+ xyz[2] += offset[2];
+ }
+ }
+ else
+ {
+ table = TableForFunc( ds->deformationWave.func );
+
+ for ( i = 0; i < tess.numVertexes; i++, xyz += 4, normal += 4 )
+ {
+ float off = ( xyz[0] + xyz[1] + xyz[2] ) * ds->deformationSpread;
+
+ scale = WAVEVALUE( table, ds->deformationWave.base,
+ ds->deformationWave.amplitude,
+ ds->deformationWave.phase + off,
+ ds->deformationWave.frequency );
+
+ VectorScale( normal, scale, offset );
+
+ xyz[0] += offset[0];
+ xyz[1] += offset[1];
+ xyz[2] += offset[2];
+ }
+ }
+}
+
+/*
+=========================
+RB_CalcDeformNormals
+
+Wiggle the normals for wavy environment mapping
+=========================
+*/
+void RB_CalcDeformNormals( deformStage_t *ds ) {
+ int i;
+ float scale;
+ float *xyz = ( float * ) tess.xyz;
+ float *normal = ( float * ) tess.normal;
+
+ for ( i = 0; i < tess.numVertexes; i++, xyz += 4, normal += 4 ) {
+ scale = 0.98f;
+ scale = R_NoiseGet4f( xyz[0] * scale, xyz[1] * scale, xyz[2] * scale,
+ tess.shaderTime * ds->deformationWave.frequency );
+ normal[ 0 ] += ds->deformationWave.amplitude * scale;
+
+ scale = 0.98f;
+ scale = R_NoiseGet4f( 100 + xyz[0] * scale, xyz[1] * scale, xyz[2] * scale,
+ tess.shaderTime * ds->deformationWave.frequency );
+ normal[ 1 ] += ds->deformationWave.amplitude * scale;
+
+ scale = 0.98f;
+ scale = R_NoiseGet4f( 200 + xyz[0] * scale, xyz[1] * scale, xyz[2] * scale,
+ tess.shaderTime * ds->deformationWave.frequency );
+ normal[ 2 ] += ds->deformationWave.amplitude * scale;
+
+ VectorNormalizeFast( normal );
+ }
+}
+
+/*
+========================
+RB_CalcBulgeVertexes
+
+========================
+*/
+void RB_CalcBulgeVertexes( deformStage_t *ds ) {
+ int i;
+ const float *st = ( const float * ) tess.texCoords[0];
+ float *xyz = ( float * ) tess.xyz;
+ float *normal = ( float * ) tess.normal;
+ float now;
+
+ now = backEnd.refdef.time * ds->bulgeSpeed * 0.001f;
+
+ for ( i = 0; i < tess.numVertexes; i++, xyz += 4, st += 4, normal += 4 ) {
+ int off;
+ float scale;
+
+ off = (float)( FUNCTABLE_SIZE / (M_PI*2) ) * ( st[0] * ds->bulgeWidth + now );
+
+ scale = tr.sinTable[ off & FUNCTABLE_MASK ] * ds->bulgeHeight;
+
+ xyz[0] += normal[0] * scale;
+ xyz[1] += normal[1] * scale;
+ xyz[2] += normal[2] * scale;
+ }
+}
+
+
+/*
+======================
+RB_CalcMoveVertexes
+
+A deformation that can move an entire surface along a wave path
+======================
+*/
+void RB_CalcMoveVertexes( deformStage_t *ds ) {
+ int i;
+ float *xyz;
+ float *table;
+ float scale;
+ vec3_t offset;
+
+ table = TableForFunc( ds->deformationWave.func );
+
+ scale = WAVEVALUE( table, ds->deformationWave.base,
+ ds->deformationWave.amplitude,
+ ds->deformationWave.phase,
+ ds->deformationWave.frequency );
+
+ VectorScale( ds->moveVector, scale, offset );
+
+ xyz = ( float * ) tess.xyz;
+ for ( i = 0; i < tess.numVertexes; i++, xyz += 4 ) {
+ VectorAdd( xyz, offset, xyz );
+ }
+}
+
+
+/*
+=============
+DeformText
+
+Change a polygon into a bunch of text polygons
+=============
+*/
+void DeformText( const char *text ) {
+ int i;
+ vec3_t origin, width, height;
+ int len;
+ int ch;
+ byte color[4];
+ float bottom, top;
+ vec3_t mid;
+
+ height[0] = 0;
+ height[1] = 0;
+ height[2] = -1;
+ CrossProduct( tess.normal[0], height, width );
+
+ // find the midpoint of the box
+ VectorClear( mid );
+ bottom = 999999;
+ top = -999999;
+ for ( i = 0 ; i < 4 ; i++ ) {
+ VectorAdd( tess.xyz[i], mid, mid );
+ if ( tess.xyz[i][2] < bottom ) {
+ bottom = tess.xyz[i][2];
+ }
+ if ( tess.xyz[i][2] > top ) {
+ top = tess.xyz[i][2];
+ }
+ }
+ VectorScale( mid, 0.25f, origin );
+
+ // determine the individual character size
+ height[0] = 0;
+ height[1] = 0;
+ height[2] = ( top - bottom ) * 0.5f;
+
+ VectorScale( width, height[2] * -0.75f, width );
+
+ // determine the starting position
+ len = strlen( text );
+ VectorMA( origin, (len-1), width, origin );
+
+ // clear the shader indexes
+ tess.numIndexes = 0;
+ tess.numVertexes = 0;
+
+ color[0] = color[1] = color[2] = color[3] = 255;
+
+ // draw each character
+ for ( i = 0 ; i < len ; i++ ) {
+ ch = text[i];
+ ch &= 255;
+
+ if ( ch != ' ' ) {
+ int row, col;
+ float frow, fcol, size;
+
+ row = ch>>4;
+ col = ch&15;
+
+ frow = row*0.0625f;
+ fcol = col*0.0625f;
+ size = 0.0625f;
+
+ RB_AddQuadStampExt( origin, width, height, color, fcol, frow, fcol + size, frow + size );
+ }
+ VectorMA( origin, -2, width, origin );
+ }
+}
+
+/*
+==================
+GlobalVectorToLocal
+==================
+*/
+static void GlobalVectorToLocal( const vec3_t in, vec3_t out ) {
+ out[0] = DotProduct( in, backEnd.or.axis[0] );
+ out[1] = DotProduct( in, backEnd.or.axis[1] );
+ out[2] = DotProduct( in, backEnd.or.axis[2] );
+}
+
+/*
+=====================
+AutospriteDeform
+
+Assuming all the triangles for this shader are independant
+quads, rebuild them as forward facing sprites
+=====================
+*/
+static void AutospriteDeform( void ) {
+ int i;
+ int oldVerts;
+ float *xyz;
+ vec3_t mid, delta;
+ float radius;
+ vec3_t left, up;
+ vec3_t leftDir, upDir;
+
+ if ( tess.numVertexes & 3 ) {
+ ri.Printf( PRINT_WARNING, "Autosprite shader %s had odd vertex count", tess.shader->name );
+ }
+ if ( tess.numIndexes != ( tess.numVertexes >> 2 ) * 6 ) {
+ ri.Printf( PRINT_WARNING, "Autosprite shader %s had odd index count", tess.shader->name );
+ }
+
+ oldVerts = tess.numVertexes;
+ tess.numVertexes = 0;
+ tess.numIndexes = 0;
+
+ if ( backEnd.currentEntity != &tr.worldEntity ) {
+ GlobalVectorToLocal( backEnd.viewParms.or.axis[1], leftDir );
+ GlobalVectorToLocal( backEnd.viewParms.or.axis[2], upDir );
+ } else {
+ VectorCopy( backEnd.viewParms.or.axis[1], leftDir );
+ VectorCopy( backEnd.viewParms.or.axis[2], upDir );
+ }
+
+ for ( i = 0 ; i < oldVerts ; i+=4 ) {
+ // find the midpoint
+ xyz = tess.xyz[i];
+
+ mid[0] = 0.25f * (xyz[0] + xyz[4] + xyz[8] + xyz[12]);
+ mid[1] = 0.25f * (xyz[1] + xyz[5] + xyz[9] + xyz[13]);
+ mid[2] = 0.25f * (xyz[2] + xyz[6] + xyz[10] + xyz[14]);
+
+ VectorSubtract( xyz, mid, delta );
+ radius = VectorLength( delta ) * 0.707f; // / sqrt(2)
+
+ VectorScale( leftDir, radius, left );
+ VectorScale( upDir, radius, up );
+
+ if ( backEnd.viewParms.isMirror ) {
+ VectorSubtract( vec3_origin, left, left );
+ }
+
+ // compensate for scale in the axes if necessary
+ if ( backEnd.currentEntity->e.nonNormalizedAxes ) {
+ float axisLength;
+ axisLength = VectorLength( backEnd.currentEntity->e.axis[0] );
+ if ( !axisLength ) {
+ axisLength = 0;
+ } else {
+ axisLength = 1.0f / axisLength;
+ }
+ VectorScale(left, axisLength, left);
+ VectorScale(up, axisLength, up);
+ }
+
+ RB_AddQuadStamp( mid, left, up, tess.vertexColors[i] );
+ }
+}
+
+
+/*
+=====================
+Autosprite2Deform
+
+Autosprite2 will pivot a rectangular quad along the center of its long axis
+=====================
+*/
+int edgeVerts[6][2] = {
+ { 0, 1 },
+ { 0, 2 },
+ { 0, 3 },
+ { 1, 2 },
+ { 1, 3 },
+ { 2, 3 }
+};
+
+static void Autosprite2Deform( void ) {
+ int i, j, k;
+ int indexes;
+ float *xyz;
+ vec3_t forward;
+
+ if ( tess.numVertexes & 3 ) {
+ ri.Printf( PRINT_WARNING, "Autosprite2 shader %s had odd vertex count", tess.shader->name );
+ }
+ if ( tess.numIndexes != ( tess.numVertexes >> 2 ) * 6 ) {
+ ri.Printf( PRINT_WARNING, "Autosprite2 shader %s had odd index count", tess.shader->name );
+ }
+
+ if ( backEnd.currentEntity != &tr.worldEntity ) {
+ GlobalVectorToLocal( backEnd.viewParms.or.axis[0], forward );
+ } else {
+ VectorCopy( backEnd.viewParms.or.axis[0], forward );
+ }
+
+ // this is a lot of work for two triangles...
+ // we could precalculate a lot of it is an issue, but it would mess up
+ // the shader abstraction
+ for ( i = 0, indexes = 0 ; i < tess.numVertexes ; i+=4, indexes+=6 ) {
+ float lengths[2];
+ int nums[2];
+ vec3_t mid[2];
+ vec3_t major, minor;
+ float *v1, *v2;
+
+ // find the midpoint
+ xyz = tess.xyz[i];
+
+ // identify the two shortest edges
+ nums[0] = nums[1] = 0;
+ lengths[0] = lengths[1] = 999999;
+
+ for ( j = 0 ; j < 6 ; j++ ) {
+ float l;
+ vec3_t temp;
+
+ v1 = xyz + 4 * edgeVerts[j][0];
+ v2 = xyz + 4 * edgeVerts[j][1];
+
+ VectorSubtract( v1, v2, temp );
+
+ l = DotProduct( temp, temp );
+ if ( l < lengths[0] ) {
+ nums[1] = nums[0];
+ lengths[1] = lengths[0];
+ nums[0] = j;
+ lengths[0] = l;
+ } else if ( l < lengths[1] ) {
+ nums[1] = j;
+ lengths[1] = l;
+ }
+ }
+
+ for ( j = 0 ; j < 2 ; j++ ) {
+ v1 = xyz + 4 * edgeVerts[nums[j]][0];
+ v2 = xyz + 4 * edgeVerts[nums[j]][1];
+
+ mid[j][0] = 0.5f * (v1[0] + v2[0]);
+ mid[j][1] = 0.5f * (v1[1] + v2[1]);
+ mid[j][2] = 0.5f * (v1[2] + v2[2]);
+ }
+
+ // find the vector of the major axis
+ VectorSubtract( mid[1], mid[0], major );
+
+ // cross this with the view direction to get minor axis
+ CrossProduct( major, forward, minor );
+ VectorNormalize( minor );
+
+ // re-project the points
+ for ( j = 0 ; j < 2 ; j++ ) {
+ float l;
+
+ v1 = xyz + 4 * edgeVerts[nums[j]][0];
+ v2 = xyz + 4 * edgeVerts[nums[j]][1];
+
+ l = 0.5 * sqrt( lengths[j] );
+
+ // we need to see which direction this edge
+ // is used to determine direction of projection
+ for ( k = 0 ; k < 5 ; k++ ) {
+ if ( tess.indexes[ indexes + k ] == i + edgeVerts[nums[j]][0]
+ && tess.indexes[ indexes + k + 1 ] == i + edgeVerts[nums[j]][1] ) {
+ break;
+ }
+ }
+
+ if ( k == 5 ) {
+ VectorMA( mid[j], l, minor, v1 );
+ VectorMA( mid[j], -l, minor, v2 );
+ } else {
+ VectorMA( mid[j], -l, minor, v1 );
+ VectorMA( mid[j], l, minor, v2 );
+ }
+ }
+ }
+}
+
+
+/*
+=====================
+RB_DeformTessGeometry
+
+=====================
+*/
+void RB_DeformTessGeometry( void ) {
+ int i;
+ deformStage_t *ds;
+
+ for ( i = 0 ; i < tess.shader->numDeforms ; i++ ) {
+ ds = &tess.shader->deforms[ i ];
+
+ switch ( ds->deformation ) {
+ case DEFORM_NONE:
+ break;
+ case DEFORM_NORMALS:
+ RB_CalcDeformNormals( ds );
+ break;
+ case DEFORM_WAVE:
+ RB_CalcDeformVertexes( ds );
+ break;
+ case DEFORM_BULGE:
+ RB_CalcBulgeVertexes( ds );
+ break;
+ case DEFORM_MOVE:
+ RB_CalcMoveVertexes( ds );
+ break;
+ case DEFORM_PROJECTION_SHADOW:
+ RB_ProjectionShadowDeform();
+ break;
+ case DEFORM_AUTOSPRITE:
+ AutospriteDeform();
+ break;
+ case DEFORM_AUTOSPRITE2:
+ Autosprite2Deform();
+ break;
+ case DEFORM_TEXT0:
+ case DEFORM_TEXT1:
+ case DEFORM_TEXT2:
+ case DEFORM_TEXT3:
+ case DEFORM_TEXT4:
+ case DEFORM_TEXT5:
+ case DEFORM_TEXT6:
+ case DEFORM_TEXT7:
+ DeformText( backEnd.refdef.text[ds->deformation - DEFORM_TEXT0] );
+ break;
+ }
+ }
+}
+
+/*
+====================================================================
+
+COLORS
+
+====================================================================
+*/
+
+
+/*
+** RB_CalcColorFromEntity
+*/
+void RB_CalcColorFromEntity( unsigned char *dstColors )
+{
+ int i;
+ int *pColors = ( int * ) dstColors;
+ int c;
+
+ if ( !backEnd.currentEntity )
+ return;
+
+ c = * ( int * ) backEnd.currentEntity->e.shaderRGBA;
+
+ for ( i = 0; i < tess.numVertexes; i++, pColors++ )
+ {
+ *pColors = c;
+ }
+}
+
+/*
+** RB_CalcColorFromOneMinusEntity
+*/
+void RB_CalcColorFromOneMinusEntity( unsigned char *dstColors )
+{
+ int i;
+ int *pColors = ( int * ) dstColors;
+ unsigned char invModulate[3];
+ int c;
+
+ if ( !backEnd.currentEntity )
+ return;
+
+ invModulate[0] = 255 - backEnd.currentEntity->e.shaderRGBA[0];
+ invModulate[1] = 255 - backEnd.currentEntity->e.shaderRGBA[1];
+ invModulate[2] = 255 - backEnd.currentEntity->e.shaderRGBA[2];
+ invModulate[3] = 255 - backEnd.currentEntity->e.shaderRGBA[3]; // this trashes alpha, but the AGEN block fixes it
+
+ c = * ( int * ) invModulate;
+
+ for ( i = 0; i < tess.numVertexes; i++, pColors++ )
+ {
+ *pColors = * ( int * ) invModulate;
+ }
+}
+
+/*
+** RB_CalcAlphaFromEntity
+*/
+void RB_CalcAlphaFromEntity( unsigned char *dstColors )
+{
+ int i;
+
+ if ( !backEnd.currentEntity )
+ return;
+
+ dstColors += 3;
+
+ for ( i = 0; i < tess.numVertexes; i++, dstColors += 4 )
+ {
+ *dstColors = backEnd.currentEntity->e.shaderRGBA[3];
+ }
+}
+
+/*
+** RB_CalcAlphaFromOneMinusEntity
+*/
+void RB_CalcAlphaFromOneMinusEntity( unsigned char *dstColors )
+{
+ int i;
+
+ if ( !backEnd.currentEntity )
+ return;
+
+ dstColors += 3;
+
+ for ( i = 0; i < tess.numVertexes; i++, dstColors += 4 )
+ {
+ *dstColors = 0xff - backEnd.currentEntity->e.shaderRGBA[3];
+ }
+}
+
+/*
+** RB_CalcWaveColor
+*/
+void RB_CalcWaveColor( const waveForm_t *wf, unsigned char *dstColors )
+{
+ int i;
+ int v;
+ float glow;
+ int *colors = ( int * ) dstColors;
+ byte color[4];
+
+
+ if ( wf->func == GF_NOISE ) {
+ glow = wf->base + R_NoiseGet4f( 0, 0, 0, ( tess.shaderTime + wf->phase ) * wf->frequency ) * wf->amplitude;
+ } else {
+ glow = EvalWaveForm( wf ) * tr.identityLight;
+ }
+
+ if ( glow < 0 ) {
+ glow = 0;
+ }
+ else if ( glow > 1 ) {
+ glow = 1;
+ }
+
+ v = myftol( 255 * glow );
+ color[0] = color[1] = color[2] = v;
+ color[3] = 255;
+ v = *(int *)color;
+
+ for ( i = 0; i < tess.numVertexes; i++, colors++ ) {
+ *colors = v;
+ }
+}
+
+/*
+** RB_CalcWaveAlpha
+*/
+void RB_CalcWaveAlpha( const waveForm_t *wf, unsigned char *dstColors )
+{
+ int i;
+ int v;
+ float glow;
+
+ glow = EvalWaveFormClamped( wf );
+
+ v = 255 * glow;
+
+ for ( i = 0; i < tess.numVertexes; i++, dstColors += 4 )
+ {
+ dstColors[3] = v;
+ }
+}
+
+/*
+** RB_CalcModulateColorsByFog
+*/
+void RB_CalcModulateColorsByFog( unsigned char *colors ) {
+ int i;
+ float texCoords[SHADER_MAX_VERTEXES][2];
+
+ // calculate texcoords so we can derive density
+ // this is not wasted, because it would only have
+ // been previously called if the surface was opaque
+ RB_CalcFogTexCoords( texCoords[0] );
+
+ for ( i = 0; i < tess.numVertexes; i++, colors += 4 ) {
+ float f = 1.0 - R_FogFactor( texCoords[i][0], texCoords[i][1] );
+ colors[0] *= f;
+ colors[1] *= f;
+ colors[2] *= f;
+ }
+}
+
+/*
+** RB_CalcModulateAlphasByFog
+*/
+void RB_CalcModulateAlphasByFog( unsigned char *colors ) {
+ int i;
+ float texCoords[SHADER_MAX_VERTEXES][2];
+
+ // calculate texcoords so we can derive density
+ // this is not wasted, because it would only have
+ // been previously called if the surface was opaque
+ RB_CalcFogTexCoords( texCoords[0] );
+
+ for ( i = 0; i < tess.numVertexes; i++, colors += 4 ) {
+ float f = 1.0 - R_FogFactor( texCoords[i][0], texCoords[i][1] );
+ colors[3] *= f;
+ }
+}
+
+/*
+** RB_CalcModulateRGBAsByFog
+*/
+void RB_CalcModulateRGBAsByFog( unsigned char *colors ) {
+ int i;
+ float texCoords[SHADER_MAX_VERTEXES][2];
+
+ // calculate texcoords so we can derive density
+ // this is not wasted, because it would only have
+ // been previously called if the surface was opaque
+ RB_CalcFogTexCoords( texCoords[0] );
+
+ for ( i = 0; i < tess.numVertexes; i++, colors += 4 ) {
+ float f = 1.0 - R_FogFactor( texCoords[i][0], texCoords[i][1] );
+ colors[0] *= f;
+ colors[1] *= f;
+ colors[2] *= f;
+ colors[3] *= f;
+ }
+}
+
+
+/*
+====================================================================
+
+TEX COORDS
+
+====================================================================
+*/
+
+/*
+========================
+RB_CalcFogTexCoords
+
+To do the clipped fog plane really correctly, we should use
+projected textures, but I don't trust the drivers and it
+doesn't fit our shader data.
+========================
+*/
+void RB_CalcFogTexCoords( float *st ) {
+ int i;
+ float *v;
+ float s, t;
+ float eyeT;
+ qboolean eyeOutside;
+ fog_t *fog;
+ vec3_t local;
+ vec4_t fogDistanceVector, fogDepthVector;
+
+ fog = tr.world->fogs + tess.fogNum;
+
+ // all fogging distance is based on world Z units
+ VectorSubtract( backEnd.or.origin, backEnd.viewParms.or.origin, local );
+ fogDistanceVector[0] = -backEnd.or.modelMatrix[2];
+ fogDistanceVector[1] = -backEnd.or.modelMatrix[6];
+ fogDistanceVector[2] = -backEnd.or.modelMatrix[10];
+ fogDistanceVector[3] = DotProduct( local, backEnd.viewParms.or.axis[0] );
+
+ // scale the fog vectors based on the fog's thickness
+ fogDistanceVector[0] *= fog->tcScale;
+ fogDistanceVector[1] *= fog->tcScale;
+ fogDistanceVector[2] *= fog->tcScale;
+ fogDistanceVector[3] *= fog->tcScale;
+
+ // rotate the gradient vector for this orientation
+ if ( fog->hasSurface ) {
+ fogDepthVector[0] = fog->surface[0] * backEnd.or.axis[0][0] +
+ fog->surface[1] * backEnd.or.axis[0][1] + fog->surface[2] * backEnd.or.axis[0][2];
+ fogDepthVector[1] = fog->surface[0] * backEnd.or.axis[1][0] +
+ fog->surface[1] * backEnd.or.axis[1][1] + fog->surface[2] * backEnd.or.axis[1][2];
+ fogDepthVector[2] = fog->surface[0] * backEnd.or.axis[2][0] +
+ fog->surface[1] * backEnd.or.axis[2][1] + fog->surface[2] * backEnd.or.axis[2][2];
+ fogDepthVector[3] = -fog->surface[3] + DotProduct( backEnd.or.origin, fog->surface );
+
+ eyeT = DotProduct( backEnd.or.viewOrigin, fogDepthVector ) + fogDepthVector[3];
+ } else {
+ eyeT = 1; // non-surface fog always has eye inside
+ }
+
+ // see if the viewpoint is outside
+ // this is needed for clipping distance even for constant fog
+
+ if ( eyeT < 0 ) {
+ eyeOutside = qtrue;
+ } else {
+ eyeOutside = qfalse;
+ }
+
+ fogDistanceVector[3] += 1.0/512;
+
+ // calculate density for each point
+ for (i = 0, v = tess.xyz[0] ; i < tess.numVertexes ; i++, v += 4) {
+ // calculate the length in fog
+ s = DotProduct( v, fogDistanceVector ) + fogDistanceVector[3];
+ t = DotProduct( v, fogDepthVector ) + fogDepthVector[3];
+
+ // partially clipped fogs use the T axis
+ if ( eyeOutside ) {
+ if ( t < 1.0 ) {
+ t = 1.0/32; // point is outside, so no fogging
+ } else {
+ t = 1.0/32 + 30.0/32 * t / ( t - eyeT ); // cut the distance at the fog plane
+ }
+ } else {
+ if ( t < 0 ) {
+ t = 1.0/32; // point is outside, so no fogging
+ } else {
+ t = 31.0/32;
+ }
+ }
+
+ st[0] = s;
+ st[1] = t;
+ st += 2;
+ }
+}
+
+
+
+/*
+** RB_CalcEnvironmentTexCoords
+*/
+void RB_CalcEnvironmentTexCoords( float *st )
+{
+ int i;
+ float *v, *normal;
+ vec3_t viewer, reflected;
+ float d;
+
+ v = tess.xyz[0];
+ normal = tess.normal[0];
+
+ for (i = 0 ; i < tess.numVertexes ; i++, v += 4, normal += 4, st += 2 )
+ {
+ VectorSubtract (backEnd.or.viewOrigin, v, viewer);
+ VectorNormalizeFast (viewer);
+
+ d = DotProduct (normal, viewer);
+
+ reflected[0] = normal[0]*2*d - viewer[0];
+ reflected[1] = normal[1]*2*d - viewer[1];
+ reflected[2] = normal[2]*2*d - viewer[2];
+
+ st[0] = 0.5 + reflected[1] * 0.5;
+ st[1] = 0.5 - reflected[2] * 0.5;
+ }
+}
+
+/*
+** RB_CalcTurbulentTexCoords
+*/
+void RB_CalcTurbulentTexCoords( const waveForm_t *wf, float *st )
+{
+ int i;
+ float now;
+
+ now = ( wf->phase + tess.shaderTime * wf->frequency );
+
+ for ( i = 0; i < tess.numVertexes; i++, st += 2 )
+ {
+ float s = st[0];
+ float t = st[1];
+
+ st[0] = s + tr.sinTable[ ( ( int ) ( ( ( tess.xyz[i][0] + tess.xyz[i][2] )* 1.0/128 * 0.125 + now ) * FUNCTABLE_SIZE ) ) & ( FUNCTABLE_MASK ) ] * wf->amplitude;
+ st[1] = t + tr.sinTable[ ( ( int ) ( ( tess.xyz[i][1] * 1.0/128 * 0.125 + now ) * FUNCTABLE_SIZE ) ) & ( FUNCTABLE_MASK ) ] * wf->amplitude;
+ }
+}
+
+/*
+** RB_CalcScaleTexCoords
+*/
+void RB_CalcScaleTexCoords( const float scale[2], float *st )
+{
+ int i;
+
+ for ( i = 0; i < tess.numVertexes; i++, st += 2 )
+ {
+ st[0] *= scale[0];
+ st[1] *= scale[1];
+ }
+}
+
+/*
+** RB_CalcScrollTexCoords
+*/
+void RB_CalcScrollTexCoords( const float scrollSpeed[2], float *st )
+{
+ int i;
+ float timeScale = tess.shaderTime;
+ float adjustedScrollS, adjustedScrollT;
+
+ adjustedScrollS = scrollSpeed[0] * timeScale;
+ adjustedScrollT = scrollSpeed[1] * timeScale;
+
+ // clamp so coordinates don't continuously get larger, causing problems
+ // with hardware limits
+ adjustedScrollS = adjustedScrollS - floor( adjustedScrollS );
+ adjustedScrollT = adjustedScrollT - floor( adjustedScrollT );
+
+ for ( i = 0; i < tess.numVertexes; i++, st += 2 )
+ {
+ st[0] += adjustedScrollS;
+ st[1] += adjustedScrollT;
+ }
+}
+
+/*
+** RB_CalcTransformTexCoords
+*/
+void RB_CalcTransformTexCoords( const texModInfo_t *tmi, float *st )
+{
+ int i;
+
+ for ( i = 0; i < tess.numVertexes; i++, st += 2 )
+ {
+ float s = st[0];
+ float t = st[1];
+
+ st[0] = s * tmi->matrix[0][0] + t * tmi->matrix[1][0] + tmi->translate[0];
+ st[1] = s * tmi->matrix[0][1] + t * tmi->matrix[1][1] + tmi->translate[1];
+ }
+}
+
+/*
+** RB_CalcRotateTexCoords
+*/
+void RB_CalcRotateTexCoords( float degsPerSecond, float *st )
+{
+ float timeScale = tess.shaderTime;
+ float degs;
+ int index;
+ float sinValue, cosValue;
+ texModInfo_t tmi;
+
+ degs = -degsPerSecond * timeScale;
+ index = degs * ( FUNCTABLE_SIZE / 360.0f );
+
+ sinValue = tr.sinTable[ index & FUNCTABLE_MASK ];
+ cosValue = tr.sinTable[ ( index + FUNCTABLE_SIZE / 4 ) & FUNCTABLE_MASK ];
+
+ tmi.matrix[0][0] = cosValue;
+ tmi.matrix[1][0] = -sinValue;
+ tmi.translate[0] = 0.5 - 0.5 * cosValue + 0.5 * sinValue;
+
+ tmi.matrix[0][1] = sinValue;
+ tmi.matrix[1][1] = cosValue;
+ tmi.translate[1] = 0.5 - 0.5 * sinValue - 0.5 * cosValue;
+
+ RB_CalcTransformTexCoords( &tmi, st );
+}
+
+
+
+
+
+
+#if id386 && !( (defined __linux__ || defined __FreeBSD__ ) && (defined __i386__ ) ) // rb010123
+
+long myftol( float f ) {
+ static int tmp;
+ __asm fld f
+ __asm fistp tmp
+ __asm mov eax, tmp
+}
+
+#endif
+
+/*
+** RB_CalcSpecularAlpha
+**
+** Calculates specular coefficient and places it in the alpha channel
+*/
+vec3_t lightOrigin = { -960, 1980, 96 }; // FIXME: track dynamically
+
+void RB_CalcSpecularAlpha( unsigned char *alphas ) {
+ int i;
+ float *v, *normal;
+ vec3_t viewer, reflected;
+ float l, d;
+ int b;
+ vec3_t lightDir;
+ int numVertexes;
+
+ v = tess.xyz[0];
+ normal = tess.normal[0];
+
+ alphas += 3;
+
+ numVertexes = tess.numVertexes;
+ for (i = 0 ; i < numVertexes ; i++, v += 4, normal += 4, alphas += 4) {
+ float ilength;
+
+ VectorSubtract( lightOrigin, v, lightDir );
+// ilength = Q_rsqrt( DotProduct( lightDir, lightDir ) );
+ VectorNormalizeFast( lightDir );
+
+ // calculate the specular color
+ d = DotProduct (normal, lightDir);
+// d *= ilength;
+
+ // we don't optimize for the d < 0 case since this tends to
+ // cause visual artifacts such as faceted "snapping"
+ reflected[0] = normal[0]*2*d - lightDir[0];
+ reflected[1] = normal[1]*2*d - lightDir[1];
+ reflected[2] = normal[2]*2*d - lightDir[2];
+
+ VectorSubtract (backEnd.or.viewOrigin, v, viewer);
+ ilength = Q_rsqrt( DotProduct( viewer, viewer ) );
+ l = DotProduct (reflected, viewer);
+ l *= ilength;
+
+ if (l < 0) {
+ b = 0;
+ } else {
+ l = l*l;
+ l = l*l;
+ b = l * 255;
+ if (b > 255) {
+ b = 255;
+ }
+ }
+
+ *alphas = b;
+ }
+}
+
+/*
+** RB_CalcDiffuseColor
+**
+** The basic vertex lighting calc
+*/
+void RB_CalcDiffuseColor( unsigned char *colors )
+{
+ int i, j;
+ float *v, *normal;
+ float incoming;
+ trRefEntity_t *ent;
+ int ambientLightInt;
+ vec3_t ambientLight;
+ vec3_t lightDir;
+ vec3_t directedLight;
+ int numVertexes;
+#if idppc_altivec
+ vector unsigned char vSel = (vector unsigned char)(0x00, 0x00, 0x00, 0xff,
+ 0x00, 0x00, 0x00, 0xff,
+ 0x00, 0x00, 0x00, 0xff,
+ 0x00, 0x00, 0x00, 0xff);
+ vector float ambientLightVec;
+ vector float directedLightVec;
+ vector float lightDirVec;
+ vector float normalVec0, normalVec1;
+ vector float incomingVec0, incomingVec1, incomingVec2;
+ vector float zero, jVec;
+ vector signed int jVecInt;
+ vector signed short jVecShort;
+ vector unsigned char jVecChar, normalPerm;
+#endif
+ ent = backEnd.currentEntity;
+ ambientLightInt = ent->ambientLightInt;
+#if idppc_altivec
+ // A lot of this could be simplified if we made sure
+ // entities light info was 16-byte aligned.
+ jVecChar = vec_lvsl(0, ent->ambientLight);
+ ambientLightVec = vec_ld(0, (vector float *)ent->ambientLight);
+ jVec = vec_ld(11, (vector float *)ent->ambientLight);
+ ambientLightVec = vec_perm(ambientLightVec,jVec,jVecChar);
+
+ jVecChar = vec_lvsl(0, ent->directedLight);
+ directedLightVec = vec_ld(0,(vector float *)ent->directedLight);
+ jVec = vec_ld(11,(vector float *)ent->directedLight);
+ directedLightVec = vec_perm(directedLightVec,jVec,jVecChar);
+
+ jVecChar = vec_lvsl(0, ent->lightDir);
+ lightDirVec = vec_ld(0,(vector float *)ent->lightDir);
+ jVec = vec_ld(11,(vector float *)ent->lightDir);
+ lightDirVec = vec_perm(lightDirVec,jVec,jVecChar);
+
+ zero = (vector float)vec_splat_s8(0);
+ VectorCopy( ent->lightDir, lightDir );
+#else
+ VectorCopy( ent->ambientLight, ambientLight );
+ VectorCopy( ent->directedLight, directedLight );
+ VectorCopy( ent->lightDir, lightDir );
+#endif
+
+ v = tess.xyz[0];
+ normal = tess.normal[0];
+
+#if idppc_altivec
+ normalPerm = vec_lvsl(0,normal);
+#endif
+ numVertexes = tess.numVertexes;
+ for (i = 0 ; i < numVertexes ; i++, v += 4, normal += 4) {
+#if idppc_altivec
+ normalVec0 = vec_ld(0,(vector float *)normal);
+ normalVec1 = vec_ld(11,(vector float *)normal);
+ normalVec0 = vec_perm(normalVec0,normalVec1,normalPerm);
+ incomingVec0 = vec_madd(normalVec0, lightDirVec, zero);
+ incomingVec1 = vec_sld(incomingVec0,incomingVec0,4);
+ incomingVec2 = vec_add(incomingVec0,incomingVec1);
+ incomingVec1 = vec_sld(incomingVec1,incomingVec1,4);
+ incomingVec2 = vec_add(incomingVec2,incomingVec1);
+ incomingVec0 = vec_splat(incomingVec2,0);
+ incomingVec0 = vec_max(incomingVec0,zero);
+ normalPerm = vec_lvsl(12,normal);
+ jVec = vec_madd(incomingVec0, directedLightVec, ambientLightVec);
+ jVecInt = vec_cts(jVec,0); // RGBx
+ jVecShort = vec_pack(jVecInt,jVecInt); // RGBxRGBx
+ jVecChar = vec_packsu(jVecShort,jVecShort); // RGBxRGBxRGBxRGBx
+ jVecChar = vec_sel(jVecChar,vSel,vSel); // RGBARGBARGBARGBA replace alpha with 255
+ vec_ste((vector unsigned int)jVecChar,0,(unsigned int *)&colors[i*4]); // store color
+#else
+ incoming = DotProduct (normal, lightDir);
+ if ( incoming <= 0 ) {
+ *(int *)&colors[i*4] = ambientLightInt;
+ continue;
+ }
+ j = myftol( ambientLight[0] + incoming * directedLight[0] );
+ if ( j > 255 ) {
+ j = 255;
+ }
+ colors[i*4+0] = j;
+
+ j = myftol( ambientLight[1] + incoming * directedLight[1] );
+ if ( j > 255 ) {
+ j = 255;
+ }
+ colors[i*4+1] = j;
+
+ j = myftol( ambientLight[2] + incoming * directedLight[2] );
+ if ( j > 255 ) {
+ j = 255;
+ }
+ colors[i*4+2] = j;
+
+ colors[i*4+3] = 255;
+#endif
+ }
+}
+
diff --git a/code/renderer/tr_shader.c b/code/renderer/tr_shader.c
new file mode 100755
index 0000000..ecf3798
--- /dev/null
+++ b/code/renderer/tr_shader.c
@@ -0,0 +1,3013 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "tr_local.h"
+
+// tr_shader.c -- this file deals with the parsing and definition of shaders
+
+static char *s_shaderText;
+
+// the shader is parsed into these global variables, then copied into
+// dynamically allocated memory if it is valid.
+static shaderStage_t stages[MAX_SHADER_STAGES];
+static shader_t shader;
+static texModInfo_t texMods[MAX_SHADER_STAGES][TR_MAX_TEXMODS];
+static qboolean deferLoad;
+
+#define FILE_HASH_SIZE 1024
+static shader_t* hashTable[FILE_HASH_SIZE];
+
+#define MAX_SHADERTEXT_HASH 2048
+static char **shaderTextHashTable[MAX_SHADERTEXT_HASH];
+
+/*
+================
+return a hash value for the filename
+================
+*/
+static long generateHashValue( const char *fname, const int size ) {
+ int i;
+ long hash;
+ char letter;
+
+ hash = 0;
+ i = 0;
+ while (fname[i] != '\0') {
+ letter = tolower(fname[i]);
+ if (letter =='.') break; // don't include extension
+ if (letter =='\\') letter = '/'; // damn path names
+ if (letter == PATH_SEP) letter = '/'; // damn path names
+ hash+=(long)(letter)*(i+119);
+ i++;
+ }
+ hash = (hash ^ (hash >> 10) ^ (hash >> 20));
+ hash &= (size-1);
+ return hash;
+}
+
+void R_RemapShader(const char *shaderName, const char *newShaderName, const char *timeOffset) {
+ char strippedName[MAX_QPATH];
+ int hash;
+ shader_t *sh, *sh2;
+ qhandle_t h;
+
+ sh = R_FindShaderByName( shaderName );
+ if (sh == NULL || sh == tr.defaultShader) {
+ h = RE_RegisterShaderLightMap(shaderName, 0);
+ sh = R_GetShaderByHandle(h);
+ }
+ if (sh == NULL || sh == tr.defaultShader) {
+ ri.Printf( PRINT_WARNING, "WARNING: R_RemapShader: shader %s not found\n", shaderName );
+ return;
+ }
+
+ sh2 = R_FindShaderByName( newShaderName );
+ if (sh2 == NULL || sh2 == tr.defaultShader) {
+ h = RE_RegisterShaderLightMap(newShaderName, 0);
+ sh2 = R_GetShaderByHandle(h);
+ }
+
+ if (sh2 == NULL || sh2 == tr.defaultShader) {
+ ri.Printf( PRINT_WARNING, "WARNING: R_RemapShader: new shader %s not found\n", newShaderName );
+ return;
+ }
+
+ // remap all the shaders with the given name
+ // even tho they might have different lightmaps
+ COM_StripExtension( shaderName, strippedName );
+ hash = generateHashValue(strippedName, FILE_HASH_SIZE);
+ for (sh = hashTable[hash]; sh; sh = sh->next) {
+ if (Q_stricmp(sh->name, strippedName) == 0) {
+ if (sh != sh2) {
+ sh->remappedShader = sh2;
+ } else {
+ sh->remappedShader = NULL;
+ }
+ }
+ }
+ if (timeOffset) {
+ sh2->timeOffset = atof(timeOffset);
+ }
+}
+
+/*
+===============
+ParseVector
+===============
+*/
+static qboolean ParseVector( char **text, int count, float *v ) {
+ char *token;
+ int i;
+
+ // FIXME: spaces are currently required after parens, should change parseext...
+ token = COM_ParseExt( text, qfalse );
+ if ( strcmp( token, "(" ) ) {
+ ri.Printf( PRINT_WARNING, "WARNING: missing parenthesis in shader '%s'\n", shader.name );
+ return qfalse;
+ }
+
+ for ( i = 0 ; i < count ; i++ ) {
+ token = COM_ParseExt( text, qfalse );
+ if ( !token[0] ) {
+ ri.Printf( PRINT_WARNING, "WARNING: missing vector element in shader '%s'\n", shader.name );
+ return qfalse;
+ }
+ v[i] = atof( token );
+ }
+
+ token = COM_ParseExt( text, qfalse );
+ if ( strcmp( token, ")" ) ) {
+ ri.Printf( PRINT_WARNING, "WARNING: missing parenthesis in shader '%s'\n", shader.name );
+ return qfalse;
+ }
+
+ return qtrue;
+}
+
+
+/*
+===============
+NameToAFunc
+===============
+*/
+static unsigned NameToAFunc( const char *funcname )
+{
+ if ( !Q_stricmp( funcname, "GT0" ) )
+ {
+ return GLS_ATEST_GT_0;
+ }
+ else if ( !Q_stricmp( funcname, "LT128" ) )
+ {
+ return GLS_ATEST_LT_80;
+ }
+ else if ( !Q_stricmp( funcname, "GE128" ) )
+ {
+ return GLS_ATEST_GE_80;
+ }
+
+ ri.Printf( PRINT_WARNING, "WARNING: invalid alphaFunc name '%s' in shader '%s'\n", funcname, shader.name );
+ return 0;
+}
+
+
+/*
+===============
+NameToSrcBlendMode
+===============
+*/
+static int NameToSrcBlendMode( const char *name )
+{
+ if ( !Q_stricmp( name, "GL_ONE" ) )
+ {
+ return GLS_SRCBLEND_ONE;
+ }
+ else if ( !Q_stricmp( name, "GL_ZERO" ) )
+ {
+ return GLS_SRCBLEND_ZERO;
+ }
+ else if ( !Q_stricmp( name, "GL_DST_COLOR" ) )
+ {
+ return GLS_SRCBLEND_DST_COLOR;
+ }
+ else if ( !Q_stricmp( name, "GL_ONE_MINUS_DST_COLOR" ) )
+ {
+ return GLS_SRCBLEND_ONE_MINUS_DST_COLOR;
+ }
+ else if ( !Q_stricmp( name, "GL_SRC_ALPHA" ) )
+ {
+ return GLS_SRCBLEND_SRC_ALPHA;
+ }
+ else if ( !Q_stricmp( name, "GL_ONE_MINUS_SRC_ALPHA" ) )
+ {
+ return GLS_SRCBLEND_ONE_MINUS_SRC_ALPHA;
+ }
+ else if ( !Q_stricmp( name, "GL_DST_ALPHA" ) )
+ {
+ return GLS_SRCBLEND_DST_ALPHA;
+ }
+ else if ( !Q_stricmp( name, "GL_ONE_MINUS_DST_ALPHA" ) )
+ {
+ return GLS_SRCBLEND_ONE_MINUS_DST_ALPHA;
+ }
+ else if ( !Q_stricmp( name, "GL_SRC_ALPHA_SATURATE" ) )
+ {
+ return GLS_SRCBLEND_ALPHA_SATURATE;
+ }
+
+ ri.Printf( PRINT_WARNING, "WARNING: unknown blend mode '%s' in shader '%s', substituting GL_ONE\n", name, shader.name );
+ return GLS_SRCBLEND_ONE;
+}
+
+/*
+===============
+NameToDstBlendMode
+===============
+*/
+static int NameToDstBlendMode( const char *name )
+{
+ if ( !Q_stricmp( name, "GL_ONE" ) )
+ {
+ return GLS_DSTBLEND_ONE;
+ }
+ else if ( !Q_stricmp( name, "GL_ZERO" ) )
+ {
+ return GLS_DSTBLEND_ZERO;
+ }
+ else if ( !Q_stricmp( name, "GL_SRC_ALPHA" ) )
+ {
+ return GLS_DSTBLEND_SRC_ALPHA;
+ }
+ else if ( !Q_stricmp( name, "GL_ONE_MINUS_SRC_ALPHA" ) )
+ {
+ return GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
+ }
+ else if ( !Q_stricmp( name, "GL_DST_ALPHA" ) )
+ {
+ return GLS_DSTBLEND_DST_ALPHA;
+ }
+ else if ( !Q_stricmp( name, "GL_ONE_MINUS_DST_ALPHA" ) )
+ {
+ return GLS_DSTBLEND_ONE_MINUS_DST_ALPHA;
+ }
+ else if ( !Q_stricmp( name, "GL_SRC_COLOR" ) )
+ {
+ return GLS_DSTBLEND_SRC_COLOR;
+ }
+ else if ( !Q_stricmp( name, "GL_ONE_MINUS_SRC_COLOR" ) )
+ {
+ return GLS_DSTBLEND_ONE_MINUS_SRC_COLOR;
+ }
+
+ ri.Printf( PRINT_WARNING, "WARNING: unknown blend mode '%s' in shader '%s', substituting GL_ONE\n", name, shader.name );
+ return GLS_DSTBLEND_ONE;
+}
+
+/*
+===============
+NameToGenFunc
+===============
+*/
+static genFunc_t NameToGenFunc( const char *funcname )
+{
+ if ( !Q_stricmp( funcname, "sin" ) )
+ {
+ return GF_SIN;
+ }
+ else if ( !Q_stricmp( funcname, "square" ) )
+ {
+ return GF_SQUARE;
+ }
+ else if ( !Q_stricmp( funcname, "triangle" ) )
+ {
+ return GF_TRIANGLE;
+ }
+ else if ( !Q_stricmp( funcname, "sawtooth" ) )
+ {
+ return GF_SAWTOOTH;
+ }
+ else if ( !Q_stricmp( funcname, "inversesawtooth" ) )
+ {
+ return GF_INVERSE_SAWTOOTH;
+ }
+ else if ( !Q_stricmp( funcname, "noise" ) )
+ {
+ return GF_NOISE;
+ }
+
+ ri.Printf( PRINT_WARNING, "WARNING: invalid genfunc name '%s' in shader '%s'\n", funcname, shader.name );
+ return GF_SIN;
+}
+
+
+/*
+===================
+ParseWaveForm
+===================
+*/
+static void ParseWaveForm( char **text, waveForm_t *wave )
+{
+ char *token;
+
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name );
+ return;
+ }
+ wave->func = NameToGenFunc( token );
+
+ // BASE, AMP, PHASE, FREQ
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name );
+ return;
+ }
+ wave->base = atof( token );
+
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name );
+ return;
+ }
+ wave->amplitude = atof( token );
+
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name );
+ return;
+ }
+ wave->phase = atof( token );
+
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name );
+ return;
+ }
+ wave->frequency = atof( token );
+}
+
+
+/*
+===================
+ParseTexMod
+===================
+*/
+static void ParseTexMod( char *_text, shaderStage_t *stage )
+{
+ const char *token;
+ char **text = &_text;
+ texModInfo_t *tmi;
+
+ if ( stage->bundle[0].numTexMods == TR_MAX_TEXMODS ) {
+ ri.Error( ERR_DROP, "ERROR: too many tcMod stages in shader '%s'\n", shader.name );
+ return;
+ }
+
+ tmi = &stage->bundle[0].texMods[stage->bundle[0].numTexMods];
+ stage->bundle[0].numTexMods++;
+
+ token = COM_ParseExt( text, qfalse );
+
+ //
+ // turb
+ //
+ if ( !Q_stricmp( token, "turb" ) )
+ {
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing tcMod turb parms in shader '%s'\n", shader.name );
+ return;
+ }
+ tmi->wave.base = atof( token );
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing tcMod turb in shader '%s'\n", shader.name );
+ return;
+ }
+ tmi->wave.amplitude = atof( token );
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing tcMod turb in shader '%s'\n", shader.name );
+ return;
+ }
+ tmi->wave.phase = atof( token );
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing tcMod turb in shader '%s'\n", shader.name );
+ return;
+ }
+ tmi->wave.frequency = atof( token );
+
+ tmi->type = TMOD_TURBULENT;
+ }
+ //
+ // scale
+ //
+ else if ( !Q_stricmp( token, "scale" ) )
+ {
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing scale parms in shader '%s'\n", shader.name );
+ return;
+ }
+ tmi->scale[0] = atof( token );
+
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing scale parms in shader '%s'\n", shader.name );
+ return;
+ }
+ tmi->scale[1] = atof( token );
+ tmi->type = TMOD_SCALE;
+ }
+ //
+ // scroll
+ //
+ else if ( !Q_stricmp( token, "scroll" ) )
+ {
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing scale scroll parms in shader '%s'\n", shader.name );
+ return;
+ }
+ tmi->scroll[0] = atof( token );
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing scale scroll parms in shader '%s'\n", shader.name );
+ return;
+ }
+ tmi->scroll[1] = atof( token );
+ tmi->type = TMOD_SCROLL;
+ }
+ //
+ // stretch
+ //
+ else if ( !Q_stricmp( token, "stretch" ) )
+ {
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name );
+ return;
+ }
+ tmi->wave.func = NameToGenFunc( token );
+
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name );
+ return;
+ }
+ tmi->wave.base = atof( token );
+
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name );
+ return;
+ }
+ tmi->wave.amplitude = atof( token );
+
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name );
+ return;
+ }
+ tmi->wave.phase = atof( token );
+
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name );
+ return;
+ }
+ tmi->wave.frequency = atof( token );
+
+ tmi->type = TMOD_STRETCH;
+ }
+ //
+ // transform
+ //
+ else if ( !Q_stricmp( token, "transform" ) )
+ {
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name );
+ return;
+ }
+ tmi->matrix[0][0] = atof( token );
+
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name );
+ return;
+ }
+ tmi->matrix[0][1] = atof( token );
+
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name );
+ return;
+ }
+ tmi->matrix[1][0] = atof( token );
+
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name );
+ return;
+ }
+ tmi->matrix[1][1] = atof( token );
+
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name );
+ return;
+ }
+ tmi->translate[0] = atof( token );
+
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name );
+ return;
+ }
+ tmi->translate[1] = atof( token );
+
+ tmi->type = TMOD_TRANSFORM;
+ }
+ //
+ // rotate
+ //
+ else if ( !Q_stricmp( token, "rotate" ) )
+ {
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing tcMod rotate parms in shader '%s'\n", shader.name );
+ return;
+ }
+ tmi->rotateSpeed = atof( token );
+ tmi->type = TMOD_ROTATE;
+ }
+ //
+ // entityTranslate
+ //
+ else if ( !Q_stricmp( token, "entityTranslate" ) )
+ {
+ tmi->type = TMOD_ENTITY_TRANSLATE;
+ }
+ else
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: unknown tcMod '%s' in shader '%s'\n", token, shader.name );
+ }
+}
+
+
+/*
+===================
+ParseStage
+===================
+*/
+static qboolean ParseStage( shaderStage_t *stage, char **text )
+{
+ char *token;
+ int depthMaskBits = GLS_DEPTHMASK_TRUE, blendSrcBits = 0, blendDstBits = 0, atestBits = 0, depthFuncBits = 0;
+ qboolean depthMaskExplicit = qfalse;
+
+ stage->active = qtrue;
+
+ while ( 1 )
+ {
+ token = COM_ParseExt( text, qtrue );
+ if ( !token[0] )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: no matching '}' found\n" );
+ return qfalse;
+ }
+
+ if ( token[0] == '}' )
+ {
+ break;
+ }
+ //
+ // map <name>
+ //
+ else if ( !Q_stricmp( token, "map" ) )
+ {
+ token = COM_ParseExt( text, qfalse );
+ if ( !token[0] )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing parameter for 'map' keyword in shader '%s'\n", shader.name );
+ return qfalse;
+ }
+
+ if ( !Q_stricmp( token, "$whiteimage" ) )
+ {
+ stage->bundle[0].image[0] = tr.whiteImage;
+ continue;
+ }
+ else if ( !Q_stricmp( token, "$lightmap" ) )
+ {
+ stage->bundle[0].isLightmap = qtrue;
+ if ( shader.lightmapIndex < 0 ) {
+ stage->bundle[0].image[0] = tr.whiteImage;
+ } else {
+ stage->bundle[0].image[0] = tr.lightmaps[shader.lightmapIndex];
+ }
+ continue;
+ }
+ else
+ {
+ stage->bundle[0].image[0] = R_FindImageFile( token, !shader.noMipMaps, !shader.noPicMip, GL_REPEAT );
+ if ( !stage->bundle[0].image[0] )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name );
+ return qfalse;
+ }
+ }
+ }
+ //
+ // clampmap <name>
+ //
+ else if ( !Q_stricmp( token, "clampmap" ) )
+ {
+ token = COM_ParseExt( text, qfalse );
+ if ( !token[0] )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing parameter for 'clampmap' keyword in shader '%s'\n", shader.name );
+ return qfalse;
+ }
+
+ stage->bundle[0].image[0] = R_FindImageFile( token, !shader.noMipMaps, !shader.noPicMip, GL_CLAMP );
+ if ( !stage->bundle[0].image[0] )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name );
+ return qfalse;
+ }
+ }
+ //
+ // animMap <frequency> <image1> .... <imageN>
+ //
+ else if ( !Q_stricmp( token, "animMap" ) )
+ {
+ token = COM_ParseExt( text, qfalse );
+ if ( !token[0] )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing parameter for 'animMmap' keyword in shader '%s'\n", shader.name );
+ return qfalse;
+ }
+ stage->bundle[0].imageAnimationSpeed = atof( token );
+
+ // parse up to MAX_IMAGE_ANIMATIONS animations
+ while ( 1 ) {
+ int num;
+
+ token = COM_ParseExt( text, qfalse );
+ if ( !token[0] ) {
+ break;
+ }
+ num = stage->bundle[0].numImageAnimations;
+ if ( num < MAX_IMAGE_ANIMATIONS ) {
+ stage->bundle[0].image[num] = R_FindImageFile( token, !shader.noMipMaps, !shader.noPicMip, GL_REPEAT );
+ if ( !stage->bundle[0].image[num] )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name );
+ return qfalse;
+ }
+ stage->bundle[0].numImageAnimations++;
+ }
+ }
+ }
+ else if ( !Q_stricmp( token, "videoMap" ) )
+ {
+ token = COM_ParseExt( text, qfalse );
+ if ( !token[0] )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing parameter for 'videoMmap' keyword in shader '%s'\n", shader.name );
+ return qfalse;
+ }
+ stage->bundle[0].videoMapHandle = ri.CIN_PlayCinematic( token, 0, 0, 256, 256, (CIN_loop | CIN_silent | CIN_shader));
+ if (stage->bundle[0].videoMapHandle != -1) {
+ stage->bundle[0].isVideoMap = qtrue;
+ stage->bundle[0].image[0] = tr.scratchImage[stage->bundle[0].videoMapHandle];
+ }
+ }
+ //
+ // alphafunc <func>
+ //
+ else if ( !Q_stricmp( token, "alphaFunc" ) )
+ {
+ token = COM_ParseExt( text, qfalse );
+ if ( !token[0] )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing parameter for 'alphaFunc' keyword in shader '%s'\n", shader.name );
+ return qfalse;
+ }
+
+ atestBits = NameToAFunc( token );
+ }
+ //
+ // depthFunc <func>
+ //
+ else if ( !Q_stricmp( token, "depthfunc" ) )
+ {
+ token = COM_ParseExt( text, qfalse );
+
+ if ( !token[0] )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing parameter for 'depthfunc' keyword in shader '%s'\n", shader.name );
+ return qfalse;
+ }
+
+ if ( !Q_stricmp( token, "lequal" ) )
+ {
+ depthFuncBits = 0;
+ }
+ else if ( !Q_stricmp( token, "equal" ) )
+ {
+ depthFuncBits = GLS_DEPTHFUNC_EQUAL;
+ }
+ else
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: unknown depthfunc '%s' in shader '%s'\n", token, shader.name );
+ continue;
+ }
+ }
+ //
+ // detail
+ //
+ else if ( !Q_stricmp( token, "detail" ) )
+ {
+ stage->isDetail = qtrue;
+ }
+ //
+ // blendfunc <srcFactor> <dstFactor>
+ // or blendfunc <add|filter|blend>
+ //
+ else if ( !Q_stricmp( token, "blendfunc" ) )
+ {
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing parm for blendFunc in shader '%s'\n", shader.name );
+ continue;
+ }
+ // check for "simple" blends first
+ if ( !Q_stricmp( token, "add" ) ) {
+ blendSrcBits = GLS_SRCBLEND_ONE;
+ blendDstBits = GLS_DSTBLEND_ONE;
+ } else if ( !Q_stricmp( token, "filter" ) ) {
+ blendSrcBits = GLS_SRCBLEND_DST_COLOR;
+ blendDstBits = GLS_DSTBLEND_ZERO;
+ } else if ( !Q_stricmp( token, "blend" ) ) {
+ blendSrcBits = GLS_SRCBLEND_SRC_ALPHA;
+ blendDstBits = GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
+ } else {
+ // complex double blends
+ blendSrcBits = NameToSrcBlendMode( token );
+
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing parm for blendFunc in shader '%s'\n", shader.name );
+ continue;
+ }
+ blendDstBits = NameToDstBlendMode( token );
+ }
+
+ // clear depth mask for blended surfaces
+ if ( !depthMaskExplicit )
+ {
+ depthMaskBits = 0;
+ }
+ }
+ //
+ // rgbGen
+ //
+ else if ( !Q_stricmp( token, "rgbGen" ) )
+ {
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing parameters for rgbGen in shader '%s'\n", shader.name );
+ continue;
+ }
+
+ if ( !Q_stricmp( token, "wave" ) )
+ {
+ ParseWaveForm( text, &stage->rgbWave );
+ stage->rgbGen = CGEN_WAVEFORM;
+ }
+ else if ( !Q_stricmp( token, "const" ) )
+ {
+ vec3_t color;
+
+ ParseVector( text, 3, color );
+ stage->constantColor[0] = 255 * color[0];
+ stage->constantColor[1] = 255 * color[1];
+ stage->constantColor[2] = 255 * color[2];
+
+ stage->rgbGen = CGEN_CONST;
+ }
+ else if ( !Q_stricmp( token, "identity" ) )
+ {
+ stage->rgbGen = CGEN_IDENTITY;
+ }
+ else if ( !Q_stricmp( token, "identityLighting" ) )
+ {
+ stage->rgbGen = CGEN_IDENTITY_LIGHTING;
+ }
+ else if ( !Q_stricmp( token, "entity" ) )
+ {
+ stage->rgbGen = CGEN_ENTITY;
+ }
+ else if ( !Q_stricmp( token, "oneMinusEntity" ) )
+ {
+ stage->rgbGen = CGEN_ONE_MINUS_ENTITY;
+ }
+ else if ( !Q_stricmp( token, "vertex" ) )
+ {
+ stage->rgbGen = CGEN_VERTEX;
+ if ( stage->alphaGen == 0 ) {
+ stage->alphaGen = AGEN_VERTEX;
+ }
+ }
+ else if ( !Q_stricmp( token, "exactVertex" ) )
+ {
+ stage->rgbGen = CGEN_EXACT_VERTEX;
+ }
+ else if ( !Q_stricmp( token, "lightingDiffuse" ) )
+ {
+ stage->rgbGen = CGEN_LIGHTING_DIFFUSE;
+ }
+ else if ( !Q_stricmp( token, "oneMinusVertex" ) )
+ {
+ stage->rgbGen = CGEN_ONE_MINUS_VERTEX;
+ }
+ else
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: unknown rgbGen parameter '%s' in shader '%s'\n", token, shader.name );
+ continue;
+ }
+ }
+ //
+ // alphaGen
+ //
+ else if ( !Q_stricmp( token, "alphaGen" ) )
+ {
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing parameters for alphaGen in shader '%s'\n", shader.name );
+ continue;
+ }
+
+ if ( !Q_stricmp( token, "wave" ) )
+ {
+ ParseWaveForm( text, &stage->alphaWave );
+ stage->alphaGen = AGEN_WAVEFORM;
+ }
+ else if ( !Q_stricmp( token, "const" ) )
+ {
+ token = COM_ParseExt( text, qfalse );
+ stage->constantColor[3] = 255 * atof( token );
+ stage->alphaGen = AGEN_CONST;
+ }
+ else if ( !Q_stricmp( token, "identity" ) )
+ {
+ stage->alphaGen = AGEN_IDENTITY;
+ }
+ else if ( !Q_stricmp( token, "entity" ) )
+ {
+ stage->alphaGen = AGEN_ENTITY;
+ }
+ else if ( !Q_stricmp( token, "oneMinusEntity" ) )
+ {
+ stage->alphaGen = AGEN_ONE_MINUS_ENTITY;
+ }
+ else if ( !Q_stricmp( token, "vertex" ) )
+ {
+ stage->alphaGen = AGEN_VERTEX;
+ }
+ else if ( !Q_stricmp( token, "lightingSpecular" ) )
+ {
+ stage->alphaGen = AGEN_LIGHTING_SPECULAR;
+ }
+ else if ( !Q_stricmp( token, "oneMinusVertex" ) )
+ {
+ stage->alphaGen = AGEN_ONE_MINUS_VERTEX;
+ }
+ else if ( !Q_stricmp( token, "portal" ) )
+ {
+ stage->alphaGen = AGEN_PORTAL;
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ shader.portalRange = 256;
+ ri.Printf( PRINT_WARNING, "WARNING: missing range parameter for alphaGen portal in shader '%s', defaulting to 256\n", shader.name );
+ }
+ else
+ {
+ shader.portalRange = atof( token );
+ }
+ }
+ else
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: unknown alphaGen parameter '%s' in shader '%s'\n", token, shader.name );
+ continue;
+ }
+ }
+ //
+ // tcGen <function>
+ //
+ else if ( !Q_stricmp(token, "texgen") || !Q_stricmp( token, "tcGen" ) )
+ {
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing texgen parm in shader '%s'\n", shader.name );
+ continue;
+ }
+
+ if ( !Q_stricmp( token, "environment" ) )
+ {
+ stage->bundle[0].tcGen = TCGEN_ENVIRONMENT_MAPPED;
+ }
+ else if ( !Q_stricmp( token, "lightmap" ) )
+ {
+ stage->bundle[0].tcGen = TCGEN_LIGHTMAP;
+ }
+ else if ( !Q_stricmp( token, "texture" ) || !Q_stricmp( token, "base" ) )
+ {
+ stage->bundle[0].tcGen = TCGEN_TEXTURE;
+ }
+ else if ( !Q_stricmp( token, "vector" ) )
+ {
+ ParseVector( text, 3, stage->bundle[0].tcGenVectors[0] );
+ ParseVector( text, 3, stage->bundle[0].tcGenVectors[1] );
+
+ stage->bundle[0].tcGen = TCGEN_VECTOR;
+ }
+ else
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: unknown texgen parm in shader '%s'\n", shader.name );
+ }
+ }
+ //
+ // tcMod <type> <...>
+ //
+ else if ( !Q_stricmp( token, "tcMod" ) )
+ {
+ char buffer[1024] = "";
+
+ while ( 1 )
+ {
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ break;
+ strcat( buffer, token );
+ strcat( buffer, " " );
+ }
+
+ ParseTexMod( buffer, stage );
+
+ continue;
+ }
+ //
+ // depthmask
+ //
+ else if ( !Q_stricmp( token, "depthwrite" ) )
+ {
+ depthMaskBits = GLS_DEPTHMASK_TRUE;
+ depthMaskExplicit = qtrue;
+
+ continue;
+ }
+ else
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: unknown parameter '%s' in shader '%s'\n", token, shader.name );
+ return qfalse;
+ }
+ }
+
+ //
+ // if cgen isn't explicitly specified, use either identity or identitylighting
+ //
+ if ( stage->rgbGen == CGEN_BAD ) {
+ if ( blendSrcBits == 0 ||
+ blendSrcBits == GLS_SRCBLEND_ONE ||
+ blendSrcBits == GLS_SRCBLEND_SRC_ALPHA ) {
+ stage->rgbGen = CGEN_IDENTITY_LIGHTING;
+ } else {
+ stage->rgbGen = CGEN_IDENTITY;
+ }
+ }
+
+
+ //
+ // implicitly assume that a GL_ONE GL_ZERO blend mask disables blending
+ //
+ if ( ( blendSrcBits == GLS_SRCBLEND_ONE ) &&
+ ( blendDstBits == GLS_DSTBLEND_ZERO ) )
+ {
+ blendDstBits = blendSrcBits = 0;
+ depthMaskBits = GLS_DEPTHMASK_TRUE;
+ }
+
+ // decide which agens we can skip
+ if ( stage->alphaGen == CGEN_IDENTITY ) {
+ if ( stage->rgbGen == CGEN_IDENTITY
+ || stage->rgbGen == CGEN_LIGHTING_DIFFUSE ) {
+ stage->alphaGen = AGEN_SKIP;
+ }
+ }
+
+ //
+ // compute state bits
+ //
+ stage->stateBits = depthMaskBits |
+ blendSrcBits | blendDstBits |
+ atestBits |
+ depthFuncBits;
+
+ return qtrue;
+}
+
+/*
+===============
+ParseDeform
+
+deformVertexes wave <spread> <waveform> <base> <amplitude> <phase> <frequency>
+deformVertexes normal <frequency> <amplitude>
+deformVertexes move <vector> <waveform> <base> <amplitude> <phase> <frequency>
+deformVertexes bulge <bulgeWidth> <bulgeHeight> <bulgeSpeed>
+deformVertexes projectionShadow
+deformVertexes autoSprite
+deformVertexes autoSprite2
+deformVertexes text[0-7]
+===============
+*/
+static void ParseDeform( char **text ) {
+ char *token;
+ deformStage_t *ds;
+
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing deform parm in shader '%s'\n", shader.name );
+ return;
+ }
+
+ if ( shader.numDeforms == MAX_SHADER_DEFORMS ) {
+ ri.Printf( PRINT_WARNING, "WARNING: MAX_SHADER_DEFORMS in '%s'\n", shader.name );
+ return;
+ }
+
+ ds = &shader.deforms[ shader.numDeforms ];
+ shader.numDeforms++;
+
+ if ( !Q_stricmp( token, "projectionShadow" ) ) {
+ ds->deformation = DEFORM_PROJECTION_SHADOW;
+ return;
+ }
+
+ if ( !Q_stricmp( token, "autosprite" ) ) {
+ ds->deformation = DEFORM_AUTOSPRITE;
+ return;
+ }
+
+ if ( !Q_stricmp( token, "autosprite2" ) ) {
+ ds->deformation = DEFORM_AUTOSPRITE2;
+ return;
+ }
+
+ if ( !Q_stricmpn( token, "text", 4 ) ) {
+ int n;
+
+ n = token[4] - '0';
+ if ( n < 0 || n > 7 ) {
+ n = 0;
+ }
+ ds->deformation = DEFORM_TEXT0 + n;
+ return;
+ }
+
+ if ( !Q_stricmp( token, "bulge" ) ) {
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name );
+ return;
+ }
+ ds->bulgeWidth = atof( token );
+
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name );
+ return;
+ }
+ ds->bulgeHeight = atof( token );
+
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name );
+ return;
+ }
+ ds->bulgeSpeed = atof( token );
+
+ ds->deformation = DEFORM_BULGE;
+ return;
+ }
+
+ if ( !Q_stricmp( token, "wave" ) )
+ {
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name );
+ return;
+ }
+
+ if ( atof( token ) != 0 )
+ {
+ ds->deformationSpread = 1.0f / atof( token );
+ }
+ else
+ {
+ ds->deformationSpread = 100.0f;
+ ri.Printf( PRINT_WARNING, "WARNING: illegal div value of 0 in deformVertexes command for shader '%s'\n", shader.name );
+ }
+
+ ParseWaveForm( text, &ds->deformationWave );
+ ds->deformation = DEFORM_WAVE;
+ return;
+ }
+
+ if ( !Q_stricmp( token, "normal" ) )
+ {
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name );
+ return;
+ }
+ ds->deformationWave.amplitude = atof( token );
+
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name );
+ return;
+ }
+ ds->deformationWave.frequency = atof( token );
+
+ ds->deformation = DEFORM_NORMALS;
+ return;
+ }
+
+ if ( !Q_stricmp( token, "move" ) ) {
+ int i;
+
+ for ( i = 0 ; i < 3 ; i++ ) {
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 ) {
+ ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name );
+ return;
+ }
+ ds->moveVector[i] = atof( token );
+ }
+
+ ParseWaveForm( text, &ds->deformationWave );
+ ds->deformation = DEFORM_MOVE;
+ return;
+ }
+
+ ri.Printf( PRINT_WARNING, "WARNING: unknown deformVertexes subtype '%s' found in shader '%s'\n", token, shader.name );
+}
+
+
+/*
+===============
+ParseSkyParms
+
+skyParms <outerbox> <cloudheight> <innerbox>
+===============
+*/
+static void ParseSkyParms( char **text ) {
+ char *token;
+ static char *suf[6] = {"rt", "bk", "lf", "ft", "up", "dn"};
+ char pathname[MAX_QPATH];
+ int i;
+
+ // outerbox
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 ) {
+ ri.Printf( PRINT_WARNING, "WARNING: 'skyParms' missing parameter in shader '%s'\n", shader.name );
+ return;
+ }
+ if ( strcmp( token, "-" ) ) {
+ for (i=0 ; i<6 ; i++) {
+ Com_sprintf( pathname, sizeof(pathname), "%s_%s.tga"
+ , token, suf[i] );
+ shader.sky.outerbox[i] = R_FindImageFile( ( char * ) pathname, qtrue, qtrue, GL_CLAMP );
+ if ( !shader.sky.outerbox[i] ) {
+ shader.sky.outerbox[i] = tr.defaultImage;
+ }
+ }
+ }
+
+ // cloudheight
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 ) {
+ ri.Printf( PRINT_WARNING, "WARNING: 'skyParms' missing parameter in shader '%s'\n", shader.name );
+ return;
+ }
+ shader.sky.cloudHeight = atof( token );
+ if ( !shader.sky.cloudHeight ) {
+ shader.sky.cloudHeight = 512;
+ }
+ R_InitSkyTexCoords( shader.sky.cloudHeight );
+
+
+ // innerbox
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 ) {
+ ri.Printf( PRINT_WARNING, "WARNING: 'skyParms' missing parameter in shader '%s'\n", shader.name );
+ return;
+ }
+ if ( strcmp( token, "-" ) ) {
+ for (i=0 ; i<6 ; i++) {
+ Com_sprintf( pathname, sizeof(pathname), "%s_%s.tga"
+ , token, suf[i] );
+ shader.sky.innerbox[i] = R_FindImageFile( ( char * ) pathname, qtrue, qtrue, GL_REPEAT );
+ if ( !shader.sky.innerbox[i] ) {
+ shader.sky.innerbox[i] = tr.defaultImage;
+ }
+ }
+ }
+
+ shader.isSky = qtrue;
+}
+
+
+/*
+=================
+ParseSort
+=================
+*/
+void ParseSort( char **text ) {
+ char *token;
+
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 ) {
+ ri.Printf( PRINT_WARNING, "WARNING: missing sort parameter in shader '%s'\n", shader.name );
+ return;
+ }
+
+ if ( !Q_stricmp( token, "portal" ) ) {
+ shader.sort = SS_PORTAL;
+ } else if ( !Q_stricmp( token, "sky" ) ) {
+ shader.sort = SS_ENVIRONMENT;
+ } else if ( !Q_stricmp( token, "opaque" ) ) {
+ shader.sort = SS_OPAQUE;
+ }else if ( !Q_stricmp( token, "decal" ) ) {
+ shader.sort = SS_DECAL;
+ } else if ( !Q_stricmp( token, "seeThrough" ) ) {
+ shader.sort = SS_SEE_THROUGH;
+ } else if ( !Q_stricmp( token, "banner" ) ) {
+ shader.sort = SS_BANNER;
+ } else if ( !Q_stricmp( token, "additive" ) ) {
+ shader.sort = SS_BLEND1;
+ } else if ( !Q_stricmp( token, "nearest" ) ) {
+ shader.sort = SS_NEAREST;
+ } else if ( !Q_stricmp( token, "underwater" ) ) {
+ shader.sort = SS_UNDERWATER;
+ } else {
+ shader.sort = atof( token );
+ }
+}
+
+
+
+// this table is also present in q3map
+
+typedef struct {
+ char *name;
+ int clearSolid, surfaceFlags, contents;
+} infoParm_t;
+
+infoParm_t infoParms[] = {
+ // server relevant contents
+ {"water", 1, 0, CONTENTS_WATER },
+ {"slime", 1, 0, CONTENTS_SLIME }, // mildly damaging
+ {"lava", 1, 0, CONTENTS_LAVA }, // very damaging
+ {"playerclip", 1, 0, CONTENTS_PLAYERCLIP },
+ {"monsterclip", 1, 0, CONTENTS_MONSTERCLIP },
+ {"nodrop", 1, 0, CONTENTS_NODROP }, // don't drop items or leave bodies (death fog, lava, etc)
+ {"nonsolid", 1, SURF_NONSOLID, 0}, // clears the solid flag
+
+ // utility relevant attributes
+ {"origin", 1, 0, CONTENTS_ORIGIN }, // center of rotating brushes
+ {"trans", 0, 0, CONTENTS_TRANSLUCENT }, // don't eat contained surfaces
+ {"detail", 0, 0, CONTENTS_DETAIL }, // don't include in structural bsp
+ {"structural", 0, 0, CONTENTS_STRUCTURAL }, // force into structural bsp even if trnas
+ {"areaportal", 1, 0, CONTENTS_AREAPORTAL }, // divides areas
+ {"clusterportal", 1,0, CONTENTS_CLUSTERPORTAL }, // for bots
+ {"donotenter", 1, 0, CONTENTS_DONOTENTER }, // for bots
+
+ {"fog", 1, 0, CONTENTS_FOG}, // carves surfaces entering
+ {"sky", 0, SURF_SKY, 0 }, // emit light from an environment map
+ {"lightfilter", 0, SURF_LIGHTFILTER, 0 }, // filter light going through it
+ {"alphashadow", 0, SURF_ALPHASHADOW, 0 }, // test light on a per-pixel basis
+ {"hint", 0, SURF_HINT, 0 }, // use as a primary splitter
+
+ // server attributes
+ {"slick", 0, SURF_SLICK, 0 },
+ {"noimpact", 0, SURF_NOIMPACT, 0 }, // don't make impact explosions or marks
+ {"nomarks", 0, SURF_NOMARKS, 0 }, // don't make impact marks, but still explode
+ {"ladder", 0, SURF_LADDER, 0 },
+ {"nodamage", 0, SURF_NODAMAGE, 0 },
+ {"metalsteps", 0, SURF_METALSTEPS,0 },
+ {"flesh", 0, SURF_FLESH, 0 },
+ {"nosteps", 0, SURF_NOSTEPS, 0 },
+
+ // drawsurf attributes
+ {"nodraw", 0, SURF_NODRAW, 0 }, // don't generate a drawsurface (or a lightmap)
+ {"pointlight", 0, SURF_POINTLIGHT, 0 }, // sample lighting at vertexes
+ {"nolightmap", 0, SURF_NOLIGHTMAP,0 }, // don't generate a lightmap
+ {"nodlight", 0, SURF_NODLIGHT, 0 }, // don't ever add dynamic lights
+ {"dust", 0, SURF_DUST, 0} // leave a dust trail when walking on this surface
+};
+
+
+/*
+===============
+ParseSurfaceParm
+
+surfaceparm <name>
+===============
+*/
+static void ParseSurfaceParm( char **text ) {
+ char *token;
+ int numInfoParms = sizeof(infoParms) / sizeof(infoParms[0]);
+ int i;
+
+ token = COM_ParseExt( text, qfalse );
+ for ( i = 0 ; i < numInfoParms ; i++ ) {
+ if ( !Q_stricmp( token, infoParms[i].name ) ) {
+ shader.surfaceFlags |= infoParms[i].surfaceFlags;
+ shader.contentFlags |= infoParms[i].contents;
+#if 0
+ if ( infoParms[i].clearSolid ) {
+ si->contents &= ~CONTENTS_SOLID;
+ }
+#endif
+ break;
+ }
+ }
+}
+
+/*
+=================
+ParseShader
+
+The current text pointer is at the explicit text definition of the
+shader. Parse it into the global shader variable. Later functions
+will optimize it.
+=================
+*/
+static qboolean ParseShader( char **text )
+{
+ char *token;
+ int s;
+
+ s = 0;
+
+ token = COM_ParseExt( text, qtrue );
+ if ( token[0] != '{' )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: expecting '{', found '%s' instead in shader '%s'\n", token, shader.name );
+ return qfalse;
+ }
+
+ while ( 1 )
+ {
+ token = COM_ParseExt( text, qtrue );
+ if ( !token[0] )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: no concluding '}' in shader %s\n", shader.name );
+ return qfalse;
+ }
+
+ // end of shader definition
+ if ( token[0] == '}' )
+ {
+ break;
+ }
+ // stage definition
+ else if ( token[0] == '{' )
+ {
+ if ( !ParseStage( &stages[s], text ) )
+ {
+ return qfalse;
+ }
+ stages[s].active = qtrue;
+ s++;
+ continue;
+ }
+ // skip stuff that only the QuakeEdRadient needs
+ else if ( !Q_stricmpn( token, "qer", 3 ) ) {
+ SkipRestOfLine( text );
+ continue;
+ }
+ // sun parms
+ else if ( !Q_stricmp( token, "q3map_sun" ) ) {
+ float a, b;
+
+ token = COM_ParseExt( text, qfalse );
+ tr.sunLight[0] = atof( token );
+ token = COM_ParseExt( text, qfalse );
+ tr.sunLight[1] = atof( token );
+ token = COM_ParseExt( text, qfalse );
+ tr.sunLight[2] = atof( token );
+
+ VectorNormalize( tr.sunLight );
+
+ token = COM_ParseExt( text, qfalse );
+ a = atof( token );
+ VectorScale( tr.sunLight, a, tr.sunLight);
+
+ token = COM_ParseExt( text, qfalse );
+ a = atof( token );
+ a = a / 180 * M_PI;
+
+ token = COM_ParseExt( text, qfalse );
+ b = atof( token );
+ b = b / 180 * M_PI;
+
+ tr.sunDirection[0] = cos( a ) * cos( b );
+ tr.sunDirection[1] = sin( a ) * cos( b );
+ tr.sunDirection[2] = sin( b );
+ }
+ else if ( !Q_stricmp( token, "deformVertexes" ) ) {
+ ParseDeform( text );
+ continue;
+ }
+ else if ( !Q_stricmp( token, "tesssize" ) ) {
+ SkipRestOfLine( text );
+ continue;
+ }
+ else if ( !Q_stricmp( token, "clampTime" ) ) {
+ token = COM_ParseExt( text, qfalse );
+ if (token[0]) {
+ shader.clampTime = atof(token);
+ }
+ }
+ // skip stuff that only the q3map needs
+ else if ( !Q_stricmpn( token, "q3map", 5 ) ) {
+ SkipRestOfLine( text );
+ continue;
+ }
+ // skip stuff that only q3map or the server needs
+ else if ( !Q_stricmp( token, "surfaceParm" ) ) {
+ ParseSurfaceParm( text );
+ continue;
+ }
+ // no mip maps
+ else if ( !Q_stricmp( token, "nomipmaps" ) )
+ {
+ shader.noMipMaps = qtrue;
+ shader.noPicMip = qtrue;
+ continue;
+ }
+ // no picmip adjustment
+ else if ( !Q_stricmp( token, "nopicmip" ) )
+ {
+ shader.noPicMip = qtrue;
+ continue;
+ }
+ // polygonOffset
+ else if ( !Q_stricmp( token, "polygonOffset" ) )
+ {
+ shader.polygonOffset = qtrue;
+ continue;
+ }
+ // entityMergable, allowing sprite surfaces from multiple entities
+ // to be merged into one batch. This is a savings for smoke
+ // puffs and blood, but can't be used for anything where the
+ // shader calcs (not the surface function) reference the entity color or scroll
+ else if ( !Q_stricmp( token, "entityMergable" ) )
+ {
+ shader.entityMergable = qtrue;
+ continue;
+ }
+ // fogParms
+ else if ( !Q_stricmp( token, "fogParms" ) )
+ {
+ if ( !ParseVector( text, 3, shader.fogParms.color ) ) {
+ return qfalse;
+ }
+
+ token = COM_ParseExt( text, qfalse );
+ if ( !token[0] )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing parm for 'fogParms' keyword in shader '%s'\n", shader.name );
+ continue;
+ }
+ shader.fogParms.depthForOpaque = atof( token );
+
+ // skip any old gradient directions
+ SkipRestOfLine( text );
+ continue;
+ }
+ // portal
+ else if ( !Q_stricmp(token, "portal") )
+ {
+ shader.sort = SS_PORTAL;
+ continue;
+ }
+ // skyparms <cloudheight> <outerbox> <innerbox>
+ else if ( !Q_stricmp( token, "skyparms" ) )
+ {
+ ParseSkyParms( text );
+ continue;
+ }
+ // light <value> determines flaring in q3map, not needed here
+ else if ( !Q_stricmp(token, "light") )
+ {
+ token = COM_ParseExt( text, qfalse );
+ continue;
+ }
+ // cull <face>
+ else if ( !Q_stricmp( token, "cull") )
+ {
+ token = COM_ParseExt( text, qfalse );
+ if ( token[0] == 0 )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: missing cull parms in shader '%s'\n", shader.name );
+ continue;
+ }
+
+ if ( !Q_stricmp( token, "none" ) || !Q_stricmp( token, "twosided" ) || !Q_stricmp( token, "disable" ) )
+ {
+ shader.cullType = CT_TWO_SIDED;
+ }
+ else if ( !Q_stricmp( token, "back" ) || !Q_stricmp( token, "backside" ) || !Q_stricmp( token, "backsided" ) )
+ {
+ shader.cullType = CT_BACK_SIDED;
+ }
+ else
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: invalid cull parm '%s' in shader '%s'\n", token, shader.name );
+ }
+ continue;
+ }
+ // sort
+ else if ( !Q_stricmp( token, "sort" ) )
+ {
+ ParseSort( text );
+ continue;
+ }
+ else
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: unknown general shader parameter '%s' in '%s'\n", token, shader.name );
+ return qfalse;
+ }
+ }
+
+ //
+ // ignore shaders that don't have any stages, unless it is a sky or fog
+ //
+ if ( s == 0 && !shader.isSky && !(shader.contentFlags & CONTENTS_FOG ) ) {
+ return qfalse;
+ }
+
+ shader.explicitlyDefined = qtrue;
+
+ return qtrue;
+}
+
+/*
+========================================================================================
+
+SHADER OPTIMIZATION AND FOGGING
+
+========================================================================================
+*/
+
+/*
+===================
+ComputeStageIteratorFunc
+
+See if we can use on of the simple fastpath stage functions,
+otherwise set to the generic stage function
+===================
+*/
+static void ComputeStageIteratorFunc( void )
+{
+ shader.optimalStageIteratorFunc = RB_StageIteratorGeneric;
+
+ //
+ // see if this should go into the sky path
+ //
+ if ( shader.isSky )
+ {
+ shader.optimalStageIteratorFunc = RB_StageIteratorSky;
+ goto done;
+ }
+
+ if ( r_ignoreFastPath->integer )
+ {
+ return;
+ }
+
+ //
+ // see if this can go into the vertex lit fast path
+ //
+ if ( shader.numUnfoggedPasses == 1 )
+ {
+ if ( stages[0].rgbGen == CGEN_LIGHTING_DIFFUSE )
+ {
+ if ( stages[0].alphaGen == AGEN_IDENTITY )
+ {
+ if ( stages[0].bundle[0].tcGen == TCGEN_TEXTURE )
+ {
+ if ( !shader.polygonOffset )
+ {
+ if ( !shader.multitextureEnv )
+ {
+ if ( !shader.numDeforms )
+ {
+ shader.optimalStageIteratorFunc = RB_StageIteratorVertexLitTexture;
+ goto done;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ //
+ // see if this can go into an optimized LM, multitextured path
+ //
+ if ( shader.numUnfoggedPasses == 1 )
+ {
+ if ( ( stages[0].rgbGen == CGEN_IDENTITY ) && ( stages[0].alphaGen == AGEN_IDENTITY ) )
+ {
+ if ( stages[0].bundle[0].tcGen == TCGEN_TEXTURE &&
+ stages[0].bundle[1].tcGen == TCGEN_LIGHTMAP )
+ {
+ if ( !shader.polygonOffset )
+ {
+ if ( !shader.numDeforms )
+ {
+ if ( shader.multitextureEnv )
+ {
+ shader.optimalStageIteratorFunc = RB_StageIteratorLightmappedMultitexture;
+ goto done;
+ }
+ }
+ }
+ }
+ }
+ }
+
+done:
+ return;
+}
+
+typedef struct {
+ int blendA;
+ int blendB;
+
+ int multitextureEnv;
+ int multitextureBlend;
+} collapse_t;
+
+static collapse_t collapse[] = {
+ { 0, GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO,
+ GL_MODULATE, 0 },
+
+ { 0, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR,
+ GL_MODULATE, 0 },
+
+ { GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR,
+ GL_MODULATE, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR },
+
+ { GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR,
+ GL_MODULATE, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR },
+
+ { GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR, GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO,
+ GL_MODULATE, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR },
+
+ { GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO, GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO,
+ GL_MODULATE, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR },
+
+ { 0, GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE,
+ GL_ADD, 0 },
+
+ { GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE, GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE,
+ GL_ADD, GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE },
+#if 0
+ { 0, GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA | GLS_SRCBLEND_SRC_ALPHA,
+ GL_DECAL, 0 },
+#endif
+ { -1 }
+};
+
+/*
+================
+CollapseMultitexture
+
+Attempt to combine two stages into a single multitexture stage
+FIXME: I think modulated add + modulated add collapses incorrectly
+=================
+*/
+static qboolean CollapseMultitexture( void ) {
+ int abits, bbits;
+ int i;
+ textureBundle_t tmpBundle;
+
+ if ( !qglActiveTextureARB ) {
+ return qfalse;
+ }
+
+ // make sure both stages are active
+ if ( !stages[0].active || !stages[1].active ) {
+ return qfalse;
+ }
+
+ // on voodoo2, don't combine different tmus
+ if ( glConfig.driverType == GLDRV_VOODOO ) {
+ if ( stages[0].bundle[0].image[0]->TMU ==
+ stages[1].bundle[0].image[0]->TMU ) {
+ return qfalse;
+ }
+ }
+
+ abits = stages[0].stateBits;
+ bbits = stages[1].stateBits;
+
+ // make sure that both stages have identical state other than blend modes
+ if ( ( abits & ~( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS | GLS_DEPTHMASK_TRUE ) ) !=
+ ( bbits & ~( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS | GLS_DEPTHMASK_TRUE ) ) ) {
+ return qfalse;
+ }
+
+ abits &= ( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS );
+ bbits &= ( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS );
+
+ // search for a valid multitexture blend function
+ for ( i = 0; collapse[i].blendA != -1 ; i++ ) {
+ if ( abits == collapse[i].blendA
+ && bbits == collapse[i].blendB ) {
+ break;
+ }
+ }
+
+ // nothing found
+ if ( collapse[i].blendA == -1 ) {
+ return qfalse;
+ }
+
+ // GL_ADD is a separate extension
+ if ( collapse[i].multitextureEnv == GL_ADD && !glConfig.textureEnvAddAvailable ) {
+ return qfalse;
+ }
+
+ // make sure waveforms have identical parameters
+ if ( ( stages[0].rgbGen != stages[1].rgbGen ) ||
+ ( stages[0].alphaGen != stages[1].alphaGen ) ) {
+ return qfalse;
+ }
+
+ // an add collapse can only have identity colors
+ if ( collapse[i].multitextureEnv == GL_ADD && stages[0].rgbGen != CGEN_IDENTITY ) {
+ return qfalse;
+ }
+
+ if ( stages[0].rgbGen == CGEN_WAVEFORM )
+ {
+ if ( memcmp( &stages[0].rgbWave,
+ &stages[1].rgbWave,
+ sizeof( stages[0].rgbWave ) ) )
+ {
+ return qfalse;
+ }
+ }
+ if ( stages[0].alphaGen == CGEN_WAVEFORM )
+ {
+ if ( memcmp( &stages[0].alphaWave,
+ &stages[1].alphaWave,
+ sizeof( stages[0].alphaWave ) ) )
+ {
+ return qfalse;
+ }
+ }
+
+
+ // make sure that lightmaps are in bundle 1 for 3dfx
+ if ( stages[0].bundle[0].isLightmap )
+ {
+ tmpBundle = stages[0].bundle[0];
+ stages[0].bundle[0] = stages[1].bundle[0];
+ stages[0].bundle[1] = tmpBundle;
+ }
+ else
+ {
+ stages[0].bundle[1] = stages[1].bundle[0];
+ }
+
+ // set the new blend state bits
+ shader.multitextureEnv = collapse[i].multitextureEnv;
+ stages[0].stateBits &= ~( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS );
+ stages[0].stateBits |= collapse[i].multitextureBlend;
+
+ //
+ // move down subsequent shaders
+ //
+ memmove( &stages[1], &stages[2], sizeof( stages[0] ) * ( MAX_SHADER_STAGES - 2 ) );
+ Com_Memset( &stages[MAX_SHADER_STAGES-1], 0, sizeof( stages[0] ) );
+
+ return qtrue;
+}
+
+/*
+=============
+
+FixRenderCommandList
+https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=493
+Arnout: this is a nasty issue. Shaders can be registered after drawsurfaces are generated
+but before the frame is rendered. This will, for the duration of one frame, cause drawsurfaces
+to be rendered with bad shaders. To fix this, need to go through all render commands and fix
+sortedIndex.
+==============
+*/
+static void FixRenderCommandList( int newShader ) {
+ renderCommandList_t *cmdList = &backEndData[tr.smpFrame]->commands;
+
+ if( cmdList ) {
+ const void *curCmd = cmdList->cmds;
+
+ while ( 1 ) {
+ switch ( *(const int *)curCmd ) {
+ case RC_SET_COLOR:
+ {
+ const setColorCommand_t *sc_cmd = (const setColorCommand_t *)curCmd;
+ curCmd = (const void *)(sc_cmd + 1);
+ break;
+ }
+ case RC_STRETCH_PIC:
+ {
+ const stretchPicCommand_t *sp_cmd = (const stretchPicCommand_t *)curCmd;
+ curCmd = (const void *)(sp_cmd + 1);
+ break;
+ }
+ case RC_DRAW_SURFS:
+ {
+ int i;
+ drawSurf_t *drawSurf;
+ shader_t *shader;
+ int fogNum;
+ int entityNum;
+ int dlightMap;
+ int sortedIndex;
+ const drawSurfsCommand_t *ds_cmd = (const drawSurfsCommand_t *)curCmd;
+
+ for( i = 0, drawSurf = ds_cmd->drawSurfs; i < ds_cmd->numDrawSurfs; i++, drawSurf++ ) {
+ R_DecomposeSort( drawSurf->sort, &entityNum, &shader, &fogNum, &dlightMap );
+ sortedIndex = (( drawSurf->sort >> QSORT_SHADERNUM_SHIFT ) & (MAX_SHADERS-1));
+ if( sortedIndex >= newShader ) {
+ sortedIndex++;
+ drawSurf->sort = (sortedIndex << QSORT_SHADERNUM_SHIFT) | entityNum | ( fogNum << QSORT_FOGNUM_SHIFT ) | (int)dlightMap;
+ }
+ }
+ curCmd = (const void *)(ds_cmd + 1);
+ break;
+ }
+ case RC_DRAW_BUFFER:
+ {
+ const drawBufferCommand_t *db_cmd = (const drawBufferCommand_t *)curCmd;
+ curCmd = (const void *)(db_cmd + 1);
+ break;
+ }
+ case RC_SWAP_BUFFERS:
+ {
+ const swapBuffersCommand_t *sb_cmd = (const swapBuffersCommand_t *)curCmd;
+ curCmd = (const void *)(sb_cmd + 1);
+ break;
+ }
+ case RC_END_OF_LIST:
+ default:
+ return;
+ }
+ }
+ }
+}
+
+/*
+==============
+SortNewShader
+
+Positions the most recently created shader in the tr.sortedShaders[]
+array so that the shader->sort key is sorted reletive to the other
+shaders.
+
+Sets shader->sortedIndex
+==============
+*/
+static void SortNewShader( void ) {
+ int i;
+ float sort;
+ shader_t *newShader;
+
+ newShader = tr.shaders[ tr.numShaders - 1 ];
+ sort = newShader->sort;
+
+ for ( i = tr.numShaders - 2 ; i >= 0 ; i-- ) {
+ if ( tr.sortedShaders[ i ]->sort <= sort ) {
+ break;
+ }
+ tr.sortedShaders[i+1] = tr.sortedShaders[i];
+ tr.sortedShaders[i+1]->sortedIndex++;
+ }
+
+ // Arnout: fix rendercommandlist
+ // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=493
+ FixRenderCommandList( i+1 );
+
+ newShader->sortedIndex = i+1;
+ tr.sortedShaders[i+1] = newShader;
+}
+
+
+/*
+====================
+GeneratePermanentShader
+====================
+*/
+static shader_t *GeneratePermanentShader( void ) {
+ shader_t *newShader;
+ int i, b;
+ int size, hash;
+
+ if ( tr.numShaders == MAX_SHADERS ) {
+ ri.Printf( PRINT_WARNING, "WARNING: GeneratePermanentShader - MAX_SHADERS hit\n");
+ return tr.defaultShader;
+ }
+
+ newShader = ri.Hunk_Alloc( sizeof( shader_t ), h_low );
+
+ *newShader = shader;
+
+ if ( shader.sort <= SS_OPAQUE ) {
+ newShader->fogPass = FP_EQUAL;
+ } else if ( shader.contentFlags & CONTENTS_FOG ) {
+ newShader->fogPass = FP_LE;
+ }
+
+ tr.shaders[ tr.numShaders ] = newShader;
+ newShader->index = tr.numShaders;
+
+ tr.sortedShaders[ tr.numShaders ] = newShader;
+ newShader->sortedIndex = tr.numShaders;
+
+ tr.numShaders++;
+
+ for ( i = 0 ; i < newShader->numUnfoggedPasses ; i++ ) {
+ if ( !stages[i].active ) {
+ break;
+ }
+ newShader->stages[i] = ri.Hunk_Alloc( sizeof( stages[i] ), h_low );
+ *newShader->stages[i] = stages[i];
+
+ for ( b = 0 ; b < NUM_TEXTURE_BUNDLES ; b++ ) {
+ size = newShader->stages[i]->bundle[b].numTexMods * sizeof( texModInfo_t );
+ newShader->stages[i]->bundle[b].texMods = ri.Hunk_Alloc( size, h_low );
+ Com_Memcpy( newShader->stages[i]->bundle[b].texMods, stages[i].bundle[b].texMods, size );
+ }
+ }
+
+ SortNewShader();
+
+ hash = generateHashValue(newShader->name, FILE_HASH_SIZE);
+ newShader->next = hashTable[hash];
+ hashTable[hash] = newShader;
+
+ return newShader;
+}
+
+/*
+=================
+VertexLightingCollapse
+
+If vertex lighting is enabled, only render a single
+pass, trying to guess which is the correct one to best aproximate
+what it is supposed to look like.
+=================
+*/
+static void VertexLightingCollapse( void ) {
+ int stage;
+ shaderStage_t *bestStage;
+ int bestImageRank;
+ int rank;
+
+ // if we aren't opaque, just use the first pass
+ if ( shader.sort == SS_OPAQUE ) {
+
+ // pick the best texture for the single pass
+ bestStage = &stages[0];
+ bestImageRank = -999999;
+
+ for ( stage = 0; stage < MAX_SHADER_STAGES; stage++ ) {
+ shaderStage_t *pStage = &stages[stage];
+
+ if ( !pStage->active ) {
+ break;
+ }
+ rank = 0;
+
+ if ( pStage->bundle[0].isLightmap ) {
+ rank -= 100;
+ }
+ if ( pStage->bundle[0].tcGen != TCGEN_TEXTURE ) {
+ rank -= 5;
+ }
+ if ( pStage->bundle[0].numTexMods ) {
+ rank -= 5;
+ }
+ if ( pStage->rgbGen != CGEN_IDENTITY && pStage->rgbGen != CGEN_IDENTITY_LIGHTING ) {
+ rank -= 3;
+ }
+
+ if ( rank > bestImageRank ) {
+ bestImageRank = rank;
+ bestStage = pStage;
+ }
+ }
+
+ stages[0].bundle[0] = bestStage->bundle[0];
+ stages[0].stateBits &= ~( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS );
+ stages[0].stateBits |= GLS_DEPTHMASK_TRUE;
+ if ( shader.lightmapIndex == LIGHTMAP_NONE ) {
+ stages[0].rgbGen = CGEN_LIGHTING_DIFFUSE;
+ } else {
+ stages[0].rgbGen = CGEN_EXACT_VERTEX;
+ }
+ stages[0].alphaGen = AGEN_SKIP;
+ } else {
+ // don't use a lightmap (tesla coils)
+ if ( stages[0].bundle[0].isLightmap ) {
+ stages[0] = stages[1];
+ }
+
+ // if we were in a cross-fade cgen, hack it to normal
+ if ( stages[0].rgbGen == CGEN_ONE_MINUS_ENTITY || stages[1].rgbGen == CGEN_ONE_MINUS_ENTITY ) {
+ stages[0].rgbGen = CGEN_IDENTITY_LIGHTING;
+ }
+ if ( ( stages[0].rgbGen == CGEN_WAVEFORM && stages[0].rgbWave.func == GF_SAWTOOTH )
+ && ( stages[1].rgbGen == CGEN_WAVEFORM && stages[1].rgbWave.func == GF_INVERSE_SAWTOOTH ) ) {
+ stages[0].rgbGen = CGEN_IDENTITY_LIGHTING;
+ }
+ if ( ( stages[0].rgbGen == CGEN_WAVEFORM && stages[0].rgbWave.func == GF_INVERSE_SAWTOOTH )
+ && ( stages[1].rgbGen == CGEN_WAVEFORM && stages[1].rgbWave.func == GF_SAWTOOTH ) ) {
+ stages[0].rgbGen = CGEN_IDENTITY_LIGHTING;
+ }
+ }
+
+ for ( stage = 1; stage < MAX_SHADER_STAGES; stage++ ) {
+ shaderStage_t *pStage = &stages[stage];
+
+ if ( !pStage->active ) {
+ break;
+ }
+
+ Com_Memset( pStage, 0, sizeof( *pStage ) );
+ }
+}
+
+/*
+=========================
+FinishShader
+
+Returns a freshly allocated shader with all the needed info
+from the current global working shader
+=========================
+*/
+static shader_t *FinishShader( void ) {
+ int stage;
+ qboolean hasLightmapStage;
+ qboolean vertexLightmap;
+
+ hasLightmapStage = qfalse;
+ vertexLightmap = qfalse;
+
+ //
+ // set sky stuff appropriate
+ //
+ if ( shader.isSky ) {
+ shader.sort = SS_ENVIRONMENT;
+ }
+
+ //
+ // set polygon offset
+ //
+ if ( shader.polygonOffset && !shader.sort ) {
+ shader.sort = SS_DECAL;
+ }
+
+ //
+ // set appropriate stage information
+ //
+ for ( stage = 0; stage < MAX_SHADER_STAGES; stage++ ) {
+ shaderStage_t *pStage = &stages[stage];
+
+ if ( !pStage->active ) {
+ break;
+ }
+
+ // check for a missing texture
+ if ( !pStage->bundle[0].image[0] ) {
+ ri.Printf( PRINT_WARNING, "Shader %s has a stage with no image\n", shader.name );
+ pStage->active = qfalse;
+ continue;
+ }
+
+ //
+ // ditch this stage if it's detail and detail textures are disabled
+ //
+ if ( pStage->isDetail && !r_detailTextures->integer ) {
+ if ( stage < ( MAX_SHADER_STAGES - 1 ) ) {
+ memmove( pStage, pStage + 1, sizeof( *pStage ) * ( MAX_SHADER_STAGES - stage - 1 ) );
+ Com_Memset( pStage + 1, 0, sizeof( *pStage ) );
+ }
+ continue;
+ }
+
+ //
+ // default texture coordinate generation
+ //
+ if ( pStage->bundle[0].isLightmap ) {
+ if ( pStage->bundle[0].tcGen == TCGEN_BAD ) {
+ pStage->bundle[0].tcGen = TCGEN_LIGHTMAP;
+ }
+ hasLightmapStage = qtrue;
+ } else {
+ if ( pStage->bundle[0].tcGen == TCGEN_BAD ) {
+ pStage->bundle[0].tcGen = TCGEN_TEXTURE;
+ }
+ }
+
+
+ // not a true lightmap but we want to leave existing
+ // behaviour in place and not print out a warning
+ //if (pStage->rgbGen == CGEN_VERTEX) {
+ // vertexLightmap = qtrue;
+ //}
+
+
+
+ //
+ // determine sort order and fog color adjustment
+ //
+ if ( ( pStage->stateBits & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) &&
+ ( stages[0].stateBits & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) ) {
+ int blendSrcBits = pStage->stateBits & GLS_SRCBLEND_BITS;
+ int blendDstBits = pStage->stateBits & GLS_DSTBLEND_BITS;
+
+ // fog color adjustment only works for blend modes that have a contribution
+ // that aproaches 0 as the modulate values aproach 0 --
+ // GL_ONE, GL_ONE
+ // GL_ZERO, GL_ONE_MINUS_SRC_COLOR
+ // GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA
+
+ // modulate, additive
+ if ( ( ( blendSrcBits == GLS_SRCBLEND_ONE ) && ( blendDstBits == GLS_DSTBLEND_ONE ) ) ||
+ ( ( blendSrcBits == GLS_SRCBLEND_ZERO ) && ( blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_COLOR ) ) ) {
+ pStage->adjustColorsForFog = ACFF_MODULATE_RGB;
+ }
+ // strict blend
+ else if ( ( blendSrcBits == GLS_SRCBLEND_SRC_ALPHA ) && ( blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ) )
+ {
+ pStage->adjustColorsForFog = ACFF_MODULATE_ALPHA;
+ }
+ // premultiplied alpha
+ else if ( ( blendSrcBits == GLS_SRCBLEND_ONE ) && ( blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ) )
+ {
+ pStage->adjustColorsForFog = ACFF_MODULATE_RGBA;
+ } else {
+ // we can't adjust this one correctly, so it won't be exactly correct in fog
+ }
+
+ // don't screw with sort order if this is a portal or environment
+ if ( !shader.sort ) {
+ // see through item, like a grill or grate
+ if ( pStage->stateBits & GLS_DEPTHMASK_TRUE ) {
+ shader.sort = SS_SEE_THROUGH;
+ } else {
+ shader.sort = SS_BLEND0;
+ }
+ }
+ }
+ }
+
+ // there are times when you will need to manually apply a sort to
+ // opaque alpha tested shaders that have later blend passes
+ if ( !shader.sort ) {
+ shader.sort = SS_OPAQUE;
+ }
+
+ //
+ // if we are in r_vertexLight mode, never use a lightmap texture
+ //
+ if ( stage > 1 && ( (r_vertexLight->integer && !r_uiFullScreen->integer) || glConfig.hardwareType == GLHW_PERMEDIA2 ) ) {
+ VertexLightingCollapse();
+ stage = 1;
+ hasLightmapStage = qfalse;
+ }
+
+ //
+ // look for multitexture potential
+ //
+ if ( stage > 1 && CollapseMultitexture() ) {
+ stage--;
+ }
+
+ if ( shader.lightmapIndex >= 0 && !hasLightmapStage ) {
+ if (vertexLightmap) {
+ ri.Printf( PRINT_DEVELOPER, "WARNING: shader '%s' has VERTEX forced lightmap!\n", shader.name );
+ } else {
+ ri.Printf( PRINT_DEVELOPER, "WARNING: shader '%s' has lightmap but no lightmap stage!\n", shader.name );
+ shader.lightmapIndex = LIGHTMAP_NONE;
+ }
+ }
+
+
+ //
+ // compute number of passes
+ //
+ shader.numUnfoggedPasses = stage;
+
+ // fogonly shaders don't have any normal passes
+ if ( stage == 0 ) {
+ shader.sort = SS_FOG;
+ }
+
+ // determine which stage iterator function is appropriate
+ ComputeStageIteratorFunc();
+
+ return GeneratePermanentShader();
+}
+
+//========================================================================================
+
+/*
+====================
+FindShaderInShaderText
+
+Scans the combined text description of all the shader files for
+the given shader name.
+
+return NULL if not found
+
+If found, it will return a valid shader
+=====================
+*/
+static char *FindShaderInShaderText( const char *shadername ) {
+
+ char *token, *p;
+
+ int i, hash;
+
+ hash = generateHashValue(shadername, MAX_SHADERTEXT_HASH);
+
+ for (i = 0; shaderTextHashTable[hash][i]; i++) {
+ p = shaderTextHashTable[hash][i];
+ token = COM_ParseExt(&p, qtrue);
+ if ( !Q_stricmp( token, shadername ) ) {
+ return p;
+ }
+ }
+
+ p = s_shaderText;
+
+ if ( !p ) {
+ return NULL;
+ }
+
+ // look for label
+ while ( 1 ) {
+ token = COM_ParseExt( &p, qtrue );
+ if ( token[0] == 0 ) {
+ break;
+ }
+
+ if ( !Q_stricmp( token, shadername ) ) {
+ return p;
+ }
+ else {
+ // skip the definition
+ SkipBracedSection( &p );
+ }
+ }
+
+ return NULL;
+}
+
+
+/*
+==================
+R_FindShaderByName
+
+Will always return a valid shader, but it might be the
+default shader if the real one can't be found.
+==================
+*/
+shader_t *R_FindShaderByName( const char *name ) {
+ char strippedName[MAX_QPATH];
+ int hash;
+ shader_t *sh;
+
+ if ( (name==NULL) || (name[0] == 0) ) { // bk001205
+ return tr.defaultShader;
+ }
+
+ COM_StripExtension( name, strippedName );
+
+ hash = generateHashValue(strippedName, FILE_HASH_SIZE);
+
+ //
+ // see if the shader is already loaded
+ //
+ for (sh=hashTable[hash]; sh; sh=sh->next) {
+ // NOTE: if there was no shader or image available with the name strippedName
+ // then a default shader is created with lightmapIndex == LIGHTMAP_NONE, so we
+ // have to check all default shaders otherwise for every call to R_FindShader
+ // with that same strippedName a new default shader is created.
+ if (Q_stricmp(sh->name, strippedName) == 0) {
+ // match found
+ return sh;
+ }
+ }
+
+ return tr.defaultShader;
+}
+
+
+/*
+===============
+R_FindShader
+
+Will always return a valid shader, but it might be the
+default shader if the real one can't be found.
+
+In the interest of not requiring an explicit shader text entry to
+be defined for every single image used in the game, three default
+shader behaviors can be auto-created for any image:
+
+If lightmapIndex == LIGHTMAP_NONE, then the image will have
+dynamic diffuse lighting applied to it, as apropriate for most
+entity skin surfaces.
+
+If lightmapIndex == LIGHTMAP_2D, then the image will be used
+for 2D rendering unless an explicit shader is found
+
+If lightmapIndex == LIGHTMAP_BY_VERTEX, then the image will use
+the vertex rgba modulate values, as apropriate for misc_model
+pre-lit surfaces.
+
+Other lightmapIndex values will have a lightmap stage created
+and src*dest blending applied with the texture, as apropriate for
+most world construction surfaces.
+
+===============
+*/
+shader_t *R_FindShader( const char *name, int lightmapIndex, qboolean mipRawImage ) {
+ char strippedName[MAX_QPATH];
+ char fileName[MAX_QPATH];
+ int i, hash;
+ char *shaderText;
+ image_t *image;
+ shader_t *sh;
+
+ if ( name[0] == 0 ) {
+ return tr.defaultShader;
+ }
+
+ // use (fullbright) vertex lighting if the bsp file doesn't have
+ // lightmaps
+ if ( lightmapIndex >= 0 && lightmapIndex >= tr.numLightmaps ) {
+ lightmapIndex = LIGHTMAP_BY_VERTEX;
+ }
+
+ COM_StripExtension( name, strippedName );
+
+ hash = generateHashValue(strippedName, FILE_HASH_SIZE);
+
+ //
+ // see if the shader is already loaded
+ //
+ for (sh = hashTable[hash]; sh; sh = sh->next) {
+ // NOTE: if there was no shader or image available with the name strippedName
+ // then a default shader is created with lightmapIndex == LIGHTMAP_NONE, so we
+ // have to check all default shaders otherwise for every call to R_FindShader
+ // with that same strippedName a new default shader is created.
+ if ( (sh->lightmapIndex == lightmapIndex || sh->defaultShader) &&
+ !Q_stricmp(sh->name, strippedName)) {
+ // match found
+ return sh;
+ }
+ }
+
+ // make sure the render thread is stopped, because we are probably
+ // going to have to upload an image
+ if (r_smp->integer) {
+ R_SyncRenderThread();
+ }
+
+ // clear the global shader
+ Com_Memset( &shader, 0, sizeof( shader ) );
+ Com_Memset( &stages, 0, sizeof( stages ) );
+ Q_strncpyz(shader.name, strippedName, sizeof(shader.name));
+ shader.lightmapIndex = lightmapIndex;
+ for ( i = 0 ; i < MAX_SHADER_STAGES ; i++ ) {
+ stages[i].bundle[0].texMods = texMods[i];
+ }
+
+ // FIXME: set these "need" values apropriately
+ shader.needsNormal = qtrue;
+ shader.needsST1 = qtrue;
+ shader.needsST2 = qtrue;
+ shader.needsColor = qtrue;
+
+ //
+ // attempt to define shader from an explicit parameter file
+ //
+ shaderText = FindShaderInShaderText( strippedName );
+ if ( shaderText ) {
+ // enable this when building a pak file to get a global list
+ // of all explicit shaders
+ if ( r_printShaders->integer ) {
+ ri.Printf( PRINT_ALL, "*SHADER* %s\n", name );
+ }
+
+ if ( !ParseShader( &shaderText ) ) {
+ // had errors, so use default shader
+ shader.defaultShader = qtrue;
+ }
+ sh = FinishShader();
+ return sh;
+ }
+
+
+ //
+ // if not defined in the in-memory shader descriptions,
+ // look for a single TGA, BMP, or PCX
+ //
+ Q_strncpyz( fileName, name, sizeof( fileName ) );
+ COM_DefaultExtension( fileName, sizeof( fileName ), ".tga" );
+ image = R_FindImageFile( fileName, mipRawImage, mipRawImage, mipRawImage ? GL_REPEAT : GL_CLAMP );
+ if ( !image ) {
+ ri.Printf( PRINT_DEVELOPER, "Couldn't find image for shader %s\n", name );
+ shader.defaultShader = qtrue;
+ return FinishShader();
+ }
+
+ //
+ // create the default shading commands
+ //
+ if ( shader.lightmapIndex == LIGHTMAP_NONE ) {
+ // dynamic colors at vertexes
+ stages[0].bundle[0].image[0] = image;
+ stages[0].active = qtrue;
+ stages[0].rgbGen = CGEN_LIGHTING_DIFFUSE;
+ stages[0].stateBits = GLS_DEFAULT;
+ } else if ( shader.lightmapIndex == LIGHTMAP_BY_VERTEX ) {
+ // explicit colors at vertexes
+ stages[0].bundle[0].image[0] = image;
+ stages[0].active = qtrue;
+ stages[0].rgbGen = CGEN_EXACT_VERTEX;
+ stages[0].alphaGen = AGEN_SKIP;
+ stages[0].stateBits = GLS_DEFAULT;
+ } else if ( shader.lightmapIndex == LIGHTMAP_2D ) {
+ // GUI elements
+ stages[0].bundle[0].image[0] = image;
+ stages[0].active = qtrue;
+ stages[0].rgbGen = CGEN_VERTEX;
+ stages[0].alphaGen = AGEN_VERTEX;
+ stages[0].stateBits = GLS_DEPTHTEST_DISABLE |
+ GLS_SRCBLEND_SRC_ALPHA |
+ GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
+ } else if ( shader.lightmapIndex == LIGHTMAP_WHITEIMAGE ) {
+ // fullbright level
+ stages[0].bundle[0].image[0] = tr.whiteImage;
+ stages[0].active = qtrue;
+ stages[0].rgbGen = CGEN_IDENTITY_LIGHTING;
+ stages[0].stateBits = GLS_DEFAULT;
+
+ stages[1].bundle[0].image[0] = image;
+ stages[1].active = qtrue;
+ stages[1].rgbGen = CGEN_IDENTITY;
+ stages[1].stateBits |= GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO;
+ } else {
+ // two pass lightmap
+ stages[0].bundle[0].image[0] = tr.lightmaps[shader.lightmapIndex];
+ stages[0].bundle[0].isLightmap = qtrue;
+ stages[0].active = qtrue;
+ stages[0].rgbGen = CGEN_IDENTITY; // lightmaps are scaled on creation
+ // for identitylight
+ stages[0].stateBits = GLS_DEFAULT;
+
+ stages[1].bundle[0].image[0] = image;
+ stages[1].active = qtrue;
+ stages[1].rgbGen = CGEN_IDENTITY;
+ stages[1].stateBits |= GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO;
+ }
+
+ return FinishShader();
+}
+
+
+qhandle_t RE_RegisterShaderFromImage(const char *name, int lightmapIndex, image_t *image, qboolean mipRawImage) {
+ int i, hash;
+ shader_t *sh;
+
+ hash = generateHashValue(name, FILE_HASH_SIZE);
+
+ //
+ // see if the shader is already loaded
+ //
+ for (sh=hashTable[hash]; sh; sh=sh->next) {
+ // NOTE: if there was no shader or image available with the name strippedName
+ // then a default shader is created with lightmapIndex == LIGHTMAP_NONE, so we
+ // have to check all default shaders otherwise for every call to R_FindShader
+ // with that same strippedName a new default shader is created.
+ if ( (sh->lightmapIndex == lightmapIndex || sh->defaultShader) &&
+ // index by name
+ !Q_stricmp(sh->name, name)) {
+ // match found
+ return sh->index;
+ }
+ }
+
+ // make sure the render thread is stopped, because we are probably
+ // going to have to upload an image
+ if (r_smp->integer) {
+ R_SyncRenderThread();
+ }
+
+ // clear the global shader
+ Com_Memset( &shader, 0, sizeof( shader ) );
+ Com_Memset( &stages, 0, sizeof( stages ) );
+ Q_strncpyz(shader.name, name, sizeof(shader.name));
+ shader.lightmapIndex = lightmapIndex;
+ for ( i = 0 ; i < MAX_SHADER_STAGES ; i++ ) {
+ stages[i].bundle[0].texMods = texMods[i];
+ }
+
+ // FIXME: set these "need" values apropriately
+ shader.needsNormal = qtrue;
+ shader.needsST1 = qtrue;
+ shader.needsST2 = qtrue;
+ shader.needsColor = qtrue;
+
+ //
+ // create the default shading commands
+ //
+ if ( shader.lightmapIndex == LIGHTMAP_NONE ) {
+ // dynamic colors at vertexes
+ stages[0].bundle[0].image[0] = image;
+ stages[0].active = qtrue;
+ stages[0].rgbGen = CGEN_LIGHTING_DIFFUSE;
+ stages[0].stateBits = GLS_DEFAULT;
+ } else if ( shader.lightmapIndex == LIGHTMAP_BY_VERTEX ) {
+ // explicit colors at vertexes
+ stages[0].bundle[0].image[0] = image;
+ stages[0].active = qtrue;
+ stages[0].rgbGen = CGEN_EXACT_VERTEX;
+ stages[0].alphaGen = AGEN_SKIP;
+ stages[0].stateBits = GLS_DEFAULT;
+ } else if ( shader.lightmapIndex == LIGHTMAP_2D ) {
+ // GUI elements
+ stages[0].bundle[0].image[0] = image;
+ stages[0].active = qtrue;
+ stages[0].rgbGen = CGEN_VERTEX;
+ stages[0].alphaGen = AGEN_VERTEX;
+ stages[0].stateBits = GLS_DEPTHTEST_DISABLE |
+ GLS_SRCBLEND_SRC_ALPHA |
+ GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA;
+ } else if ( shader.lightmapIndex == LIGHTMAP_WHITEIMAGE ) {
+ // fullbright level
+ stages[0].bundle[0].image[0] = tr.whiteImage;
+ stages[0].active = qtrue;
+ stages[0].rgbGen = CGEN_IDENTITY_LIGHTING;
+ stages[0].stateBits = GLS_DEFAULT;
+
+ stages[1].bundle[0].image[0] = image;
+ stages[1].active = qtrue;
+ stages[1].rgbGen = CGEN_IDENTITY;
+ stages[1].stateBits |= GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO;
+ } else {
+ // two pass lightmap
+ stages[0].bundle[0].image[0] = tr.lightmaps[shader.lightmapIndex];
+ stages[0].bundle[0].isLightmap = qtrue;
+ stages[0].active = qtrue;
+ stages[0].rgbGen = CGEN_IDENTITY; // lightmaps are scaled on creation
+ // for identitylight
+ stages[0].stateBits = GLS_DEFAULT;
+
+ stages[1].bundle[0].image[0] = image;
+ stages[1].active = qtrue;
+ stages[1].rgbGen = CGEN_IDENTITY;
+ stages[1].stateBits |= GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO;
+ }
+
+ sh = FinishShader();
+ return sh->index;
+}
+
+
+/*
+====================
+RE_RegisterShader
+
+This is the exported shader entry point for the rest of the system
+It will always return an index that will be valid.
+
+This should really only be used for explicit shaders, because there is no
+way to ask for different implicit lighting modes (vertex, lightmap, etc)
+====================
+*/
+qhandle_t RE_RegisterShaderLightMap( const char *name, int lightmapIndex ) {
+ shader_t *sh;
+
+ if ( strlen( name ) >= MAX_QPATH ) {
+ Com_Printf( "Shader name exceeds MAX_QPATH\n" );
+ return 0;
+ }
+
+ sh = R_FindShader( name, lightmapIndex, qtrue );
+
+ // we want to return 0 if the shader failed to
+ // load for some reason, but R_FindShader should
+ // still keep a name allocated for it, so if
+ // something calls RE_RegisterShader again with
+ // the same name, we don't try looking for it again
+ if ( sh->defaultShader ) {
+ return 0;
+ }
+
+ return sh->index;
+}
+
+
+/*
+====================
+RE_RegisterShader
+
+This is the exported shader entry point for the rest of the system
+It will always return an index that will be valid.
+
+This should really only be used for explicit shaders, because there is no
+way to ask for different implicit lighting modes (vertex, lightmap, etc)
+====================
+*/
+qhandle_t RE_RegisterShader( const char *name ) {
+ shader_t *sh;
+
+ if ( strlen( name ) >= MAX_QPATH ) {
+ Com_Printf( "Shader name exceeds MAX_QPATH\n" );
+ return 0;
+ }
+
+ sh = R_FindShader( name, LIGHTMAP_2D, qtrue );
+
+ // we want to return 0 if the shader failed to
+ // load for some reason, but R_FindShader should
+ // still keep a name allocated for it, so if
+ // something calls RE_RegisterShader again with
+ // the same name, we don't try looking for it again
+ if ( sh->defaultShader ) {
+ return 0;
+ }
+
+ return sh->index;
+}
+
+
+/*
+====================
+RE_RegisterShaderNoMip
+
+For menu graphics that should never be picmiped
+====================
+*/
+qhandle_t RE_RegisterShaderNoMip( const char *name ) {
+ shader_t *sh;
+
+ if ( strlen( name ) >= MAX_QPATH ) {
+ Com_Printf( "Shader name exceeds MAX_QPATH\n" );
+ return 0;
+ }
+
+ sh = R_FindShader( name, LIGHTMAP_2D, qfalse );
+
+ // we want to return 0 if the shader failed to
+ // load for some reason, but R_FindShader should
+ // still keep a name allocated for it, so if
+ // something calls RE_RegisterShader again with
+ // the same name, we don't try looking for it again
+ if ( sh->defaultShader ) {
+ return 0;
+ }
+
+ return sh->index;
+}
+
+
+/*
+====================
+R_GetShaderByHandle
+
+When a handle is passed in by another module, this range checks
+it and returns a valid (possibly default) shader_t to be used internally.
+====================
+*/
+shader_t *R_GetShaderByHandle( qhandle_t hShader ) {
+ if ( hShader < 0 ) {
+ ri.Printf( PRINT_WARNING, "R_GetShaderByHandle: out of range hShader '%d'\n", hShader ); // bk: FIXME name
+ return tr.defaultShader;
+ }
+ if ( hShader >= tr.numShaders ) {
+ ri.Printf( PRINT_WARNING, "R_GetShaderByHandle: out of range hShader '%d'\n", hShader );
+ return tr.defaultShader;
+ }
+ return tr.shaders[hShader];
+}
+
+/*
+===============
+R_ShaderList_f
+
+Dump information on all valid shaders to the console
+A second parameter will cause it to print in sorted order
+===============
+*/
+void R_ShaderList_f (void) {
+ int i;
+ int count;
+ shader_t *shader;
+
+ ri.Printf (PRINT_ALL, "-----------------------\n");
+
+ count = 0;
+ for ( i = 0 ; i < tr.numShaders ; i++ ) {
+ if ( ri.Cmd_Argc() > 1 ) {
+ shader = tr.sortedShaders[i];
+ } else {
+ shader = tr.shaders[i];
+ }
+
+ ri.Printf( PRINT_ALL, "%i ", shader->numUnfoggedPasses );
+
+ if (shader->lightmapIndex >= 0 ) {
+ ri.Printf (PRINT_ALL, "L ");
+ } else {
+ ri.Printf (PRINT_ALL, " ");
+ }
+ if ( shader->multitextureEnv == GL_ADD ) {
+ ri.Printf( PRINT_ALL, "MT(a) " );
+ } else if ( shader->multitextureEnv == GL_MODULATE ) {
+ ri.Printf( PRINT_ALL, "MT(m) " );
+ } else if ( shader->multitextureEnv == GL_DECAL ) {
+ ri.Printf( PRINT_ALL, "MT(d) " );
+ } else {
+ ri.Printf( PRINT_ALL, " " );
+ }
+ if ( shader->explicitlyDefined ) {
+ ri.Printf( PRINT_ALL, "E " );
+ } else {
+ ri.Printf( PRINT_ALL, " " );
+ }
+
+ if ( shader->optimalStageIteratorFunc == RB_StageIteratorGeneric ) {
+ ri.Printf( PRINT_ALL, "gen " );
+ } else if ( shader->optimalStageIteratorFunc == RB_StageIteratorSky ) {
+ ri.Printf( PRINT_ALL, "sky " );
+ } else if ( shader->optimalStageIteratorFunc == RB_StageIteratorLightmappedMultitexture ) {
+ ri.Printf( PRINT_ALL, "lmmt" );
+ } else if ( shader->optimalStageIteratorFunc == RB_StageIteratorVertexLitTexture ) {
+ ri.Printf( PRINT_ALL, "vlt " );
+ } else {
+ ri.Printf( PRINT_ALL, " " );
+ }
+
+ if ( shader->defaultShader ) {
+ ri.Printf (PRINT_ALL, ": %s (DEFAULTED)\n", shader->name);
+ } else {
+ ri.Printf (PRINT_ALL, ": %s\n", shader->name);
+ }
+ count++;
+ }
+ ri.Printf (PRINT_ALL, "%i total shaders\n", count);
+ ri.Printf (PRINT_ALL, "------------------\n");
+}
+
+
+/*
+====================
+ScanAndLoadShaderFiles
+
+Finds and loads all .shader files, combining them into
+a single large text block that can be scanned for shader names
+=====================
+*/
+#define MAX_SHADER_FILES 4096
+static void ScanAndLoadShaderFiles( void )
+{
+ char **shaderFiles;
+ char *buffers[MAX_SHADER_FILES];
+ char *p;
+ int numShaders;
+ int i;
+ char *oldp, *token, *hashMem;
+ int shaderTextHashTableSizes[MAX_SHADERTEXT_HASH], hash, size;
+
+ long sum = 0;
+ // scan for shader files
+ shaderFiles = ri.FS_ListFiles( "scripts", ".shader", &numShaders );
+
+ if ( !shaderFiles || !numShaders )
+ {
+ ri.Printf( PRINT_WARNING, "WARNING: no shader files found\n" );
+ return;
+ }
+
+ if ( numShaders > MAX_SHADER_FILES ) {
+ numShaders = MAX_SHADER_FILES;
+ }
+
+ // load and parse shader files
+ for ( i = 0; i < numShaders; i++ )
+ {
+ char filename[MAX_QPATH];
+
+ Com_sprintf( filename, sizeof( filename ), "scripts/%s", shaderFiles[i] );
+ ri.Printf( PRINT_ALL, "...loading '%s'\n", filename );
+ sum += ri.FS_ReadFile( filename, (void **)&buffers[i] );
+ if ( !buffers[i] ) {
+ ri.Error( ERR_DROP, "Couldn't load %s", filename );
+ }
+ }
+
+ // build single large buffer
+ s_shaderText = ri.Hunk_Alloc( sum + numShaders*2, h_low );
+
+ // free in reverse order, so the temp files are all dumped
+ for ( i = numShaders - 1; i >= 0 ; i-- ) {
+ strcat( s_shaderText, "\n" );
+ p = &s_shaderText[strlen(s_shaderText)];
+ strcat( s_shaderText, buffers[i] );
+ ri.FS_FreeFile( buffers[i] );
+ buffers[i] = p;
+ COM_Compress(p);
+ }
+
+ // free up memory
+ ri.FS_FreeFileList( shaderFiles );
+
+ Com_Memset(shaderTextHashTableSizes, 0, sizeof(shaderTextHashTableSizes));
+ size = 0;
+ //
+ for ( i = 0; i < numShaders; i++ ) {
+ // pointer to the first shader file
+ p = buffers[i];
+ // look for label
+ while ( 1 ) {
+ token = COM_ParseExt( &p, qtrue );
+ if ( token[0] == 0 ) {
+ break;
+ }
+
+ hash = generateHashValue(token, MAX_SHADERTEXT_HASH);
+ shaderTextHashTableSizes[hash]++;
+ size++;
+ SkipBracedSection(&p);
+ // if we passed the pointer to the next shader file
+ if ( i < numShaders - 1 ) {
+ if ( p > buffers[i+1] ) {
+ break;
+ }
+ }
+ }
+ }
+
+ size += MAX_SHADERTEXT_HASH;
+
+ hashMem = ri.Hunk_Alloc( size * sizeof(char *), h_low );
+
+ for (i = 0; i < MAX_SHADERTEXT_HASH; i++) {
+ shaderTextHashTable[i] = (char **) hashMem;
+ hashMem = ((char *) hashMem) + ((shaderTextHashTableSizes[i] + 1) * sizeof(char *));
+ }
+
+ Com_Memset(shaderTextHashTableSizes, 0, sizeof(shaderTextHashTableSizes));
+ //
+ for ( i = 0; i < numShaders; i++ ) {
+ // pointer to the first shader file
+ p = buffers[i];
+ // look for label
+ while ( 1 ) {
+ oldp = p;
+ token = COM_ParseExt( &p, qtrue );
+ if ( token[0] == 0 ) {
+ break;
+ }
+
+ hash = generateHashValue(token, MAX_SHADERTEXT_HASH);
+ shaderTextHashTable[hash][shaderTextHashTableSizes[hash]++] = oldp;
+
+ SkipBracedSection(&p);
+ // if we passed the pointer to the next shader file
+ if ( i < numShaders - 1 ) {
+ if ( p > buffers[i+1] ) {
+ break;
+ }
+ }
+ }
+ }
+
+ return;
+
+}
+
+
+/*
+====================
+CreateInternalShaders
+====================
+*/
+static void CreateInternalShaders( void ) {
+ tr.numShaders = 0;
+
+ // init the default shader
+ Com_Memset( &shader, 0, sizeof( shader ) );
+ Com_Memset( &stages, 0, sizeof( stages ) );
+
+ Q_strncpyz( shader.name, "<default>", sizeof( shader.name ) );
+
+ shader.lightmapIndex = LIGHTMAP_NONE;
+ stages[0].bundle[0].image[0] = tr.defaultImage;
+ stages[0].active = qtrue;
+ stages[0].stateBits = GLS_DEFAULT;
+ tr.defaultShader = FinishShader();
+
+ // shadow shader is just a marker
+ Q_strncpyz( shader.name, "<stencil shadow>", sizeof( shader.name ) );
+ shader.sort = SS_STENCIL_SHADOW;
+ tr.shadowShader = FinishShader();
+}
+
+static void CreateExternalShaders( void ) {
+ tr.projectionShadowShader = R_FindShader( "projectionShadow", LIGHTMAP_NONE, qtrue );
+ tr.flareShader = R_FindShader( "flareShader", LIGHTMAP_NONE, qtrue );
+ tr.sunShader = R_FindShader( "sun", LIGHTMAP_NONE, qtrue );
+}
+
+/*
+==================
+R_InitShaders
+==================
+*/
+void R_InitShaders( void ) {
+ ri.Printf( PRINT_ALL, "Initializing Shaders\n" );
+
+ Com_Memset(hashTable, 0, sizeof(hashTable));
+
+ deferLoad = qfalse;
+
+ CreateInternalShaders();
+
+ ScanAndLoadShaderFiles();
+
+ CreateExternalShaders();
+}
diff --git a/code/renderer/tr_shadows.c b/code/renderer/tr_shadows.c
new file mode 100755
index 0000000..4a74292
--- /dev/null
+++ b/code/renderer/tr_shadows.c
@@ -0,0 +1,341 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "tr_local.h"
+
+
+/*
+
+ for a projection shadow:
+
+ point[x] += light vector * ( z - shadow plane )
+ point[y] +=
+ point[z] = shadow plane
+
+ 1 0 light[x] / light[z]
+
+*/
+
+typedef struct {
+ int i2;
+ int facing;
+} edgeDef_t;
+
+#define MAX_EDGE_DEFS 32
+
+static edgeDef_t edgeDefs[SHADER_MAX_VERTEXES][MAX_EDGE_DEFS];
+static int numEdgeDefs[SHADER_MAX_VERTEXES];
+static int facing[SHADER_MAX_INDEXES/3];
+
+void R_AddEdgeDef( int i1, int i2, int facing ) {
+ int c;
+
+ c = numEdgeDefs[ i1 ];
+ if ( c == MAX_EDGE_DEFS ) {
+ return; // overflow
+ }
+ edgeDefs[ i1 ][ c ].i2 = i2;
+ edgeDefs[ i1 ][ c ].facing = facing;
+
+ numEdgeDefs[ i1 ]++;
+}
+
+void R_RenderShadowEdges( void ) {
+ int i;
+
+#if 0
+ int numTris;
+
+ // dumb way -- render every triangle's edges
+ numTris = tess.numIndexes / 3;
+
+ for ( i = 0 ; i < numTris ; i++ ) {
+ int i1, i2, i3;
+
+ if ( !facing[i] ) {
+ continue;
+ }
+
+ i1 = tess.indexes[ i*3 + 0 ];
+ i2 = tess.indexes[ i*3 + 1 ];
+ i3 = tess.indexes[ i*3 + 2 ];
+
+ qglBegin( GL_TRIANGLE_STRIP );
+ qglVertex3fv( tess.xyz[ i1 ] );
+ qglVertex3fv( tess.xyz[ i1 + tess.numVertexes ] );
+ qglVertex3fv( tess.xyz[ i2 ] );
+ qglVertex3fv( tess.xyz[ i2 + tess.numVertexes ] );
+ qglVertex3fv( tess.xyz[ i3 ] );
+ qglVertex3fv( tess.xyz[ i3 + tess.numVertexes ] );
+ qglVertex3fv( tess.xyz[ i1 ] );
+ qglVertex3fv( tess.xyz[ i1 + tess.numVertexes ] );
+ qglEnd();
+ }
+#else
+ int c, c2;
+ int j, k;
+ int i2;
+ int c_edges, c_rejected;
+ int hit[2];
+
+ // an edge is NOT a silhouette edge if its face doesn't face the light,
+ // or if it has a reverse paired edge that also faces the light.
+ // A well behaved polyhedron would have exactly two faces for each edge,
+ // but lots of models have dangling edges or overfanned edges
+ c_edges = 0;
+ c_rejected = 0;
+
+ for ( i = 0 ; i < tess.numVertexes ; i++ ) {
+ c = numEdgeDefs[ i ];
+ for ( j = 0 ; j < c ; j++ ) {
+ if ( !edgeDefs[ i ][ j ].facing ) {
+ continue;
+ }
+
+ hit[0] = 0;
+ hit[1] = 0;
+
+ i2 = edgeDefs[ i ][ j ].i2;
+ c2 = numEdgeDefs[ i2 ];
+ for ( k = 0 ; k < c2 ; k++ ) {
+ if ( edgeDefs[ i2 ][ k ].i2 == i ) {
+ hit[ edgeDefs[ i2 ][ k ].facing ]++;
+ }
+ }
+
+ // if it doesn't share the edge with another front facing
+ // triangle, it is a sil edge
+ if ( hit[ 1 ] == 0 ) {
+ qglBegin( GL_TRIANGLE_STRIP );
+ qglVertex3fv( tess.xyz[ i ] );
+ qglVertex3fv( tess.xyz[ i + tess.numVertexes ] );
+ qglVertex3fv( tess.xyz[ i2 ] );
+ qglVertex3fv( tess.xyz[ i2 + tess.numVertexes ] );
+ qglEnd();
+ c_edges++;
+ } else {
+ c_rejected++;
+ }
+ }
+ }
+#endif
+}
+
+/*
+=================
+RB_ShadowTessEnd
+
+triangleFromEdge[ v1 ][ v2 ]
+
+
+ set triangle from edge( v1, v2, tri )
+ if ( facing[ triangleFromEdge[ v1 ][ v2 ] ] && !facing[ triangleFromEdge[ v2 ][ v1 ] ) {
+ }
+=================
+*/
+void RB_ShadowTessEnd( void ) {
+ int i;
+ int numTris;
+ vec3_t lightDir;
+
+ // we can only do this if we have enough space in the vertex buffers
+ if ( tess.numVertexes >= SHADER_MAX_VERTEXES / 2 ) {
+ return;
+ }
+
+ if ( glConfig.stencilBits < 4 ) {
+ return;
+ }
+
+ VectorCopy( backEnd.currentEntity->lightDir, lightDir );
+
+ // project vertexes away from light direction
+ for ( i = 0 ; i < tess.numVertexes ; i++ ) {
+ VectorMA( tess.xyz[i], -512, lightDir, tess.xyz[i+tess.numVertexes] );
+ }
+
+ // decide which triangles face the light
+ Com_Memset( numEdgeDefs, 0, 4 * tess.numVertexes );
+
+ numTris = tess.numIndexes / 3;
+ for ( i = 0 ; i < numTris ; i++ ) {
+ int i1, i2, i3;
+ vec3_t d1, d2, normal;
+ float *v1, *v2, *v3;
+ float d;
+
+ i1 = tess.indexes[ i*3 + 0 ];
+ i2 = tess.indexes[ i*3 + 1 ];
+ i3 = tess.indexes[ i*3 + 2 ];
+
+ v1 = tess.xyz[ i1 ];
+ v2 = tess.xyz[ i2 ];
+ v3 = tess.xyz[ i3 ];
+
+ VectorSubtract( v2, v1, d1 );
+ VectorSubtract( v3, v1, d2 );
+ CrossProduct( d1, d2, normal );
+
+ d = DotProduct( normal, lightDir );
+ if ( d > 0 ) {
+ facing[ i ] = 1;
+ } else {
+ facing[ i ] = 0;
+ }
+
+ // create the edges
+ R_AddEdgeDef( i1, i2, facing[ i ] );
+ R_AddEdgeDef( i2, i3, facing[ i ] );
+ R_AddEdgeDef( i3, i1, facing[ i ] );
+ }
+
+ // draw the silhouette edges
+
+ GL_Bind( tr.whiteImage );
+ qglEnable( GL_CULL_FACE );
+ GL_State( GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO );
+ qglColor3f( 0.2f, 0.2f, 0.2f );
+
+ // don't write to the color buffer
+ qglColorMask( GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE );
+
+ qglEnable( GL_STENCIL_TEST );
+ qglStencilFunc( GL_ALWAYS, 1, 255 );
+
+ // mirrors have the culling order reversed
+ if ( backEnd.viewParms.isMirror ) {
+ qglCullFace( GL_FRONT );
+ qglStencilOp( GL_KEEP, GL_KEEP, GL_INCR );
+
+ R_RenderShadowEdges();
+
+ qglCullFace( GL_BACK );
+ qglStencilOp( GL_KEEP, GL_KEEP, GL_DECR );
+
+ R_RenderShadowEdges();
+ } else {
+ qglCullFace( GL_BACK );
+ qglStencilOp( GL_KEEP, GL_KEEP, GL_INCR );
+
+ R_RenderShadowEdges();
+
+ qglCullFace( GL_FRONT );
+ qglStencilOp( GL_KEEP, GL_KEEP, GL_DECR );
+
+ R_RenderShadowEdges();
+ }
+
+
+ // reenable writing to the color buffer
+ qglColorMask( GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE );
+}
+
+
+/*
+=================
+RB_ShadowFinish
+
+Darken everything that is is a shadow volume.
+We have to delay this until everything has been shadowed,
+because otherwise shadows from different body parts would
+overlap and double darken.
+=================
+*/
+void RB_ShadowFinish( void ) {
+ if ( r_shadows->integer != 2 ) {
+ return;
+ }
+ if ( glConfig.stencilBits < 4 ) {
+ return;
+ }
+ qglEnable( GL_STENCIL_TEST );
+ qglStencilFunc( GL_NOTEQUAL, 0, 255 );
+
+ qglDisable (GL_CLIP_PLANE0);
+ qglDisable (GL_CULL_FACE);
+
+ GL_Bind( tr.whiteImage );
+
+ qglLoadIdentity ();
+
+ qglColor3f( 0.6f, 0.6f, 0.6f );
+ GL_State( GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO );
+
+// qglColor3f( 1, 0, 0 );
+// GL_State( GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO );
+
+ qglBegin( GL_QUADS );
+ qglVertex3f( -100, 100, -10 );
+ qglVertex3f( 100, 100, -10 );
+ qglVertex3f( 100, -100, -10 );
+ qglVertex3f( -100, -100, -10 );
+ qglEnd ();
+
+ qglColor4f(1,1,1,1);
+ qglDisable( GL_STENCIL_TEST );
+}
+
+
+/*
+=================
+RB_ProjectionShadowDeform
+
+=================
+*/
+void RB_ProjectionShadowDeform( void ) {
+ float *xyz;
+ int i;
+ float h;
+ vec3_t ground;
+ vec3_t light;
+ float groundDist;
+ float d;
+ vec3_t lightDir;
+
+ xyz = ( float * ) tess.xyz;
+
+ ground[0] = backEnd.or.axis[0][2];
+ ground[1] = backEnd.or.axis[1][2];
+ ground[2] = backEnd.or.axis[2][2];
+
+ groundDist = backEnd.or.origin[2] - backEnd.currentEntity->e.shadowPlane;
+
+ VectorCopy( backEnd.currentEntity->lightDir, lightDir );
+ d = DotProduct( lightDir, ground );
+ // don't let the shadows get too long or go negative
+ if ( d < 0.5 ) {
+ VectorMA( lightDir, (0.5 - d), ground, lightDir );
+ d = DotProduct( lightDir, ground );
+ }
+ d = 1.0 / d;
+
+ light[0] = lightDir[0] * d;
+ light[1] = lightDir[1] * d;
+ light[2] = lightDir[2] * d;
+
+ for ( i = 0; i < tess.numVertexes; i++, xyz += 4 ) {
+ h = DotProduct( xyz, ground ) + groundDist;
+
+ xyz[0] -= light[0] * h;
+ xyz[1] -= light[1] * h;
+ xyz[2] -= light[2] * h;
+ }
+}
diff --git a/code/renderer/tr_sky.c b/code/renderer/tr_sky.c
new file mode 100755
index 0000000..0f8aa24
--- /dev/null
+++ b/code/renderer/tr_sky.c
@@ -0,0 +1,845 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// tr_sky.c
+#include "tr_local.h"
+
+#define SKY_SUBDIVISIONS 8
+#define HALF_SKY_SUBDIVISIONS (SKY_SUBDIVISIONS/2)
+
+static float s_cloudTexCoords[6][SKY_SUBDIVISIONS+1][SKY_SUBDIVISIONS+1][2];
+static float s_cloudTexP[6][SKY_SUBDIVISIONS+1][SKY_SUBDIVISIONS+1];
+
+/*
+===================================================================================
+
+POLYGON TO BOX SIDE PROJECTION
+
+===================================================================================
+*/
+
+static vec3_t sky_clip[6] =
+{
+ {1,1,0},
+ {1,-1,0},
+ {0,-1,1},
+ {0,1,1},
+ {1,0,1},
+ {-1,0,1}
+};
+
+static float sky_mins[2][6], sky_maxs[2][6];
+static float sky_min, sky_max;
+
+/*
+================
+AddSkyPolygon
+================
+*/
+static void AddSkyPolygon (int nump, vec3_t vecs)
+{
+ int i,j;
+ vec3_t v, av;
+ float s, t, dv;
+ int axis;
+ float *vp;
+ // s = [0]/[2], t = [1]/[2]
+ static int vec_to_st[6][3] =
+ {
+ {-2,3,1},
+ {2,3,-1},
+
+ {1,3,2},
+ {-1,3,-2},
+
+ {-2,-1,3},
+ {-2,1,-3}
+
+ // {-1,2,3},
+ // {1,2,-3}
+ };
+
+ // decide which face it maps to
+ VectorCopy (vec3_origin, v);
+ for (i=0, vp=vecs ; i<nump ; i++, vp+=3)
+ {
+ VectorAdd (vp, v, v);
+ }
+ av[0] = fabs(v[0]);
+ av[1] = fabs(v[1]);
+ av[2] = fabs(v[2]);
+ if (av[0] > av[1] && av[0] > av[2])
+ {
+ if (v[0] < 0)
+ axis = 1;
+ else
+ axis = 0;
+ }
+ else if (av[1] > av[2] && av[1] > av[0])
+ {
+ if (v[1] < 0)
+ axis = 3;
+ else
+ axis = 2;
+ }
+ else
+ {
+ if (v[2] < 0)
+ axis = 5;
+ else
+ axis = 4;
+ }
+
+ // project new texture coords
+ for (i=0 ; i<nump ; i++, vecs+=3)
+ {
+ j = vec_to_st[axis][2];
+ if (j > 0)
+ dv = vecs[j - 1];
+ else
+ dv = -vecs[-j - 1];
+ if (dv < 0.001)
+ continue; // don't divide by zero
+ j = vec_to_st[axis][0];
+ if (j < 0)
+ s = -vecs[-j -1] / dv;
+ else
+ s = vecs[j-1] / dv;
+ j = vec_to_st[axis][1];
+ if (j < 0)
+ t = -vecs[-j -1] / dv;
+ else
+ t = vecs[j-1] / dv;
+
+ if (s < sky_mins[0][axis])
+ sky_mins[0][axis] = s;
+ if (t < sky_mins[1][axis])
+ sky_mins[1][axis] = t;
+ if (s > sky_maxs[0][axis])
+ sky_maxs[0][axis] = s;
+ if (t > sky_maxs[1][axis])
+ sky_maxs[1][axis] = t;
+ }
+}
+
+#define ON_EPSILON 0.1f // point on plane side epsilon
+#define MAX_CLIP_VERTS 64
+/*
+================
+ClipSkyPolygon
+================
+*/
+static void ClipSkyPolygon (int nump, vec3_t vecs, int stage)
+{
+ float *norm;
+ float *v;
+ qboolean front, back;
+ float d, e;
+ float dists[MAX_CLIP_VERTS];
+ int sides[MAX_CLIP_VERTS];
+ vec3_t newv[2][MAX_CLIP_VERTS];
+ int newc[2];
+ int i, j;
+
+ if (nump > MAX_CLIP_VERTS-2)
+ ri.Error (ERR_DROP, "ClipSkyPolygon: MAX_CLIP_VERTS");
+ if (stage == 6)
+ { // fully clipped, so draw it
+ AddSkyPolygon (nump, vecs);
+ return;
+ }
+
+ front = back = qfalse;
+ norm = sky_clip[stage];
+ for (i=0, v = vecs ; i<nump ; i++, v+=3)
+ {
+ d = DotProduct (v, norm);
+ if (d > ON_EPSILON)
+ {
+ front = qtrue;
+ sides[i] = SIDE_FRONT;
+ }
+ else if (d < -ON_EPSILON)
+ {
+ back = qtrue;
+ sides[i] = SIDE_BACK;
+ }
+ else
+ sides[i] = SIDE_ON;
+ dists[i] = d;
+ }
+
+ if (!front || !back)
+ { // not clipped
+ ClipSkyPolygon (nump, vecs, stage+1);
+ return;
+ }
+
+ // clip it
+ sides[i] = sides[0];
+ dists[i] = dists[0];
+ VectorCopy (vecs, (vecs+(i*3)) );
+ newc[0] = newc[1] = 0;
+
+ for (i=0, v = vecs ; i<nump ; i++, v+=3)
+ {
+ switch (sides[i])
+ {
+ case SIDE_FRONT:
+ VectorCopy (v, newv[0][newc[0]]);
+ newc[0]++;
+ break;
+ case SIDE_BACK:
+ VectorCopy (v, newv[1][newc[1]]);
+ newc[1]++;
+ break;
+ case SIDE_ON:
+ VectorCopy (v, newv[0][newc[0]]);
+ newc[0]++;
+ VectorCopy (v, newv[1][newc[1]]);
+ newc[1]++;
+ break;
+ }
+
+ if (sides[i] == SIDE_ON || sides[i+1] == SIDE_ON || sides[i+1] == sides[i])
+ continue;
+
+ d = dists[i] / (dists[i] - dists[i+1]);
+ for (j=0 ; j<3 ; j++)
+ {
+ e = v[j] + d*(v[j+3] - v[j]);
+ newv[0][newc[0]][j] = e;
+ newv[1][newc[1]][j] = e;
+ }
+ newc[0]++;
+ newc[1]++;
+ }
+
+ // continue
+ ClipSkyPolygon (newc[0], newv[0][0], stage+1);
+ ClipSkyPolygon (newc[1], newv[1][0], stage+1);
+}
+
+/*
+==============
+ClearSkyBox
+==============
+*/
+static void ClearSkyBox (void) {
+ int i;
+
+ for (i=0 ; i<6 ; i++) {
+ sky_mins[0][i] = sky_mins[1][i] = 9999;
+ sky_maxs[0][i] = sky_maxs[1][i] = -9999;
+ }
+}
+
+/*
+================
+RB_ClipSkyPolygons
+================
+*/
+void RB_ClipSkyPolygons( shaderCommands_t *input )
+{
+ vec3_t p[5]; // need one extra point for clipping
+ int i, j;
+
+ ClearSkyBox();
+
+ for ( i = 0; i < input->numIndexes; i += 3 )
+ {
+ for (j = 0 ; j < 3 ; j++)
+ {
+ VectorSubtract( input->xyz[input->indexes[i+j]],
+ backEnd.viewParms.or.origin,
+ p[j] );
+ }
+ ClipSkyPolygon( 3, p[0], 0 );
+ }
+}
+
+/*
+===================================================================================
+
+CLOUD VERTEX GENERATION
+
+===================================================================================
+*/
+
+/*
+** MakeSkyVec
+**
+** Parms: s, t range from -1 to 1
+*/
+static void MakeSkyVec( float s, float t, int axis, float outSt[2], vec3_t outXYZ )
+{
+ // 1 = s, 2 = t, 3 = 2048
+ static int st_to_vec[6][3] =
+ {
+ {3,-1,2},
+ {-3,1,2},
+
+ {1,3,2},
+ {-1,-3,2},
+
+ {-2,-1,3}, // 0 degrees yaw, look straight up
+ {2,-1,-3} // look straight down
+ };
+
+ vec3_t b;
+ int j, k;
+ float boxSize;
+
+ boxSize = backEnd.viewParms.zFar / 1.75; // div sqrt(3)
+ b[0] = s*boxSize;
+ b[1] = t*boxSize;
+ b[2] = boxSize;
+
+ for (j=0 ; j<3 ; j++)
+ {
+ k = st_to_vec[axis][j];
+ if (k < 0)
+ {
+ outXYZ[j] = -b[-k - 1];
+ }
+ else
+ {
+ outXYZ[j] = b[k - 1];
+ }
+ }
+
+ // avoid bilerp seam
+ s = (s+1)*0.5;
+ t = (t+1)*0.5;
+ if (s < sky_min)
+ {
+ s = sky_min;
+ }
+ else if (s > sky_max)
+ {
+ s = sky_max;
+ }
+
+ if (t < sky_min)
+ {
+ t = sky_min;
+ }
+ else if (t > sky_max)
+ {
+ t = sky_max;
+ }
+
+ t = 1.0 - t;
+
+
+ if ( outSt )
+ {
+ outSt[0] = s;
+ outSt[1] = t;
+ }
+}
+
+static int sky_texorder[6] = {0,2,1,3,4,5};
+static vec3_t s_skyPoints[SKY_SUBDIVISIONS+1][SKY_SUBDIVISIONS+1];
+static float s_skyTexCoords[SKY_SUBDIVISIONS+1][SKY_SUBDIVISIONS+1][2];
+
+static void DrawSkySide( struct image_s *image, const int mins[2], const int maxs[2] )
+{
+ int s, t;
+
+ GL_Bind( image );
+
+ for ( t = mins[1]+HALF_SKY_SUBDIVISIONS; t < maxs[1]+HALF_SKY_SUBDIVISIONS; t++ )
+ {
+ qglBegin( GL_TRIANGLE_STRIP );
+
+ for ( s = mins[0]+HALF_SKY_SUBDIVISIONS; s <= maxs[0]+HALF_SKY_SUBDIVISIONS; s++ )
+ {
+ qglTexCoord2fv( s_skyTexCoords[t][s] );
+ qglVertex3fv( s_skyPoints[t][s] );
+
+ qglTexCoord2fv( s_skyTexCoords[t+1][s] );
+ qglVertex3fv( s_skyPoints[t+1][s] );
+ }
+
+ qglEnd();
+ }
+}
+
+static void DrawSkyBox( shader_t *shader )
+{
+ int i;
+
+ sky_min = 0;
+ sky_max = 1;
+
+ Com_Memset( s_skyTexCoords, 0, sizeof( s_skyTexCoords ) );
+
+ for (i=0 ; i<6 ; i++)
+ {
+ int sky_mins_subd[2], sky_maxs_subd[2];
+ int s, t;
+
+ sky_mins[0][i] = floor( sky_mins[0][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS;
+ sky_mins[1][i] = floor( sky_mins[1][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS;
+ sky_maxs[0][i] = ceil( sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS;
+ sky_maxs[1][i] = ceil( sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS;
+
+ if ( ( sky_mins[0][i] >= sky_maxs[0][i] ) ||
+ ( sky_mins[1][i] >= sky_maxs[1][i] ) )
+ {
+ continue;
+ }
+
+ sky_mins_subd[0] = sky_mins[0][i] * HALF_SKY_SUBDIVISIONS;
+ sky_mins_subd[1] = sky_mins[1][i] * HALF_SKY_SUBDIVISIONS;
+ sky_maxs_subd[0] = sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS;
+ sky_maxs_subd[1] = sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS;
+
+ if ( sky_mins_subd[0] < -HALF_SKY_SUBDIVISIONS )
+ sky_mins_subd[0] = -HALF_SKY_SUBDIVISIONS;
+ else if ( sky_mins_subd[0] > HALF_SKY_SUBDIVISIONS )
+ sky_mins_subd[0] = HALF_SKY_SUBDIVISIONS;
+ if ( sky_mins_subd[1] < -HALF_SKY_SUBDIVISIONS )
+ sky_mins_subd[1] = -HALF_SKY_SUBDIVISIONS;
+ else if ( sky_mins_subd[1] > HALF_SKY_SUBDIVISIONS )
+ sky_mins_subd[1] = HALF_SKY_SUBDIVISIONS;
+
+ if ( sky_maxs_subd[0] < -HALF_SKY_SUBDIVISIONS )
+ sky_maxs_subd[0] = -HALF_SKY_SUBDIVISIONS;
+ else if ( sky_maxs_subd[0] > HALF_SKY_SUBDIVISIONS )
+ sky_maxs_subd[0] = HALF_SKY_SUBDIVISIONS;
+ if ( sky_maxs_subd[1] < -HALF_SKY_SUBDIVISIONS )
+ sky_maxs_subd[1] = -HALF_SKY_SUBDIVISIONS;
+ else if ( sky_maxs_subd[1] > HALF_SKY_SUBDIVISIONS )
+ sky_maxs_subd[1] = HALF_SKY_SUBDIVISIONS;
+
+ //
+ // iterate through the subdivisions
+ //
+ for ( t = sky_mins_subd[1]+HALF_SKY_SUBDIVISIONS; t <= sky_maxs_subd[1]+HALF_SKY_SUBDIVISIONS; t++ )
+ {
+ for ( s = sky_mins_subd[0]+HALF_SKY_SUBDIVISIONS; s <= sky_maxs_subd[0]+HALF_SKY_SUBDIVISIONS; s++ )
+ {
+ MakeSkyVec( ( s - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS,
+ ( t - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS,
+ i,
+ s_skyTexCoords[t][s],
+ s_skyPoints[t][s] );
+ }
+ }
+
+ DrawSkySide( shader->sky.outerbox[sky_texorder[i]],
+ sky_mins_subd,
+ sky_maxs_subd );
+ }
+
+}
+
+static void FillCloudySkySide( const int mins[2], const int maxs[2], qboolean addIndexes )
+{
+ int s, t;
+ int vertexStart = tess.numVertexes;
+ int tHeight, sWidth;
+
+ tHeight = maxs[1] - mins[1] + 1;
+ sWidth = maxs[0] - mins[0] + 1;
+
+ for ( t = mins[1]+HALF_SKY_SUBDIVISIONS; t <= maxs[1]+HALF_SKY_SUBDIVISIONS; t++ )
+ {
+ for ( s = mins[0]+HALF_SKY_SUBDIVISIONS; s <= maxs[0]+HALF_SKY_SUBDIVISIONS; s++ )
+ {
+ VectorAdd( s_skyPoints[t][s], backEnd.viewParms.or.origin, tess.xyz[tess.numVertexes] );
+ tess.texCoords[tess.numVertexes][0][0] = s_skyTexCoords[t][s][0];
+ tess.texCoords[tess.numVertexes][0][1] = s_skyTexCoords[t][s][1];
+
+ tess.numVertexes++;
+
+ if ( tess.numVertexes >= SHADER_MAX_VERTEXES )
+ {
+ ri.Error( ERR_DROP, "SHADER_MAX_VERTEXES hit in FillCloudySkySide()\n" );
+ }
+ }
+ }
+
+ // only add indexes for one pass, otherwise it would draw multiple times for each pass
+ if ( addIndexes ) {
+ for ( t = 0; t < tHeight-1; t++ )
+ {
+ for ( s = 0; s < sWidth-1; s++ )
+ {
+ tess.indexes[tess.numIndexes] = vertexStart + s + t * ( sWidth );
+ tess.numIndexes++;
+ tess.indexes[tess.numIndexes] = vertexStart + s + ( t + 1 ) * ( sWidth );
+ tess.numIndexes++;
+ tess.indexes[tess.numIndexes] = vertexStart + s + 1 + t * ( sWidth );
+ tess.numIndexes++;
+
+ tess.indexes[tess.numIndexes] = vertexStart + s + ( t + 1 ) * ( sWidth );
+ tess.numIndexes++;
+ tess.indexes[tess.numIndexes] = vertexStart + s + 1 + ( t + 1 ) * ( sWidth );
+ tess.numIndexes++;
+ tess.indexes[tess.numIndexes] = vertexStart + s + 1 + t * ( sWidth );
+ tess.numIndexes++;
+ }
+ }
+ }
+}
+
+static void FillCloudBox( const shader_t *shader, int stage )
+{
+ int i;
+
+ for ( i =0; i < 6; i++ )
+ {
+ int sky_mins_subd[2], sky_maxs_subd[2];
+ int s, t;
+ float MIN_T;
+
+ if ( 1 ) // FIXME? shader->sky.fullClouds )
+ {
+ MIN_T = -HALF_SKY_SUBDIVISIONS;
+
+ // still don't want to draw the bottom, even if fullClouds
+ if ( i == 5 )
+ continue;
+ }
+ else
+ {
+ switch( i )
+ {
+ case 0:
+ case 1:
+ case 2:
+ case 3:
+ MIN_T = -1;
+ break;
+ case 5:
+ // don't draw clouds beneath you
+ continue;
+ case 4: // top
+ default:
+ MIN_T = -HALF_SKY_SUBDIVISIONS;
+ break;
+ }
+ }
+
+ sky_mins[0][i] = floor( sky_mins[0][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS;
+ sky_mins[1][i] = floor( sky_mins[1][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS;
+ sky_maxs[0][i] = ceil( sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS;
+ sky_maxs[1][i] = ceil( sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS;
+
+ if ( ( sky_mins[0][i] >= sky_maxs[0][i] ) ||
+ ( sky_mins[1][i] >= sky_maxs[1][i] ) )
+ {
+ continue;
+ }
+
+ sky_mins_subd[0] = myftol( sky_mins[0][i] * HALF_SKY_SUBDIVISIONS );
+ sky_mins_subd[1] = myftol( sky_mins[1][i] * HALF_SKY_SUBDIVISIONS );
+ sky_maxs_subd[0] = myftol( sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS );
+ sky_maxs_subd[1] = myftol( sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS );
+
+ if ( sky_mins_subd[0] < -HALF_SKY_SUBDIVISIONS )
+ sky_mins_subd[0] = -HALF_SKY_SUBDIVISIONS;
+ else if ( sky_mins_subd[0] > HALF_SKY_SUBDIVISIONS )
+ sky_mins_subd[0] = HALF_SKY_SUBDIVISIONS;
+ if ( sky_mins_subd[1] < MIN_T )
+ sky_mins_subd[1] = MIN_T;
+ else if ( sky_mins_subd[1] > HALF_SKY_SUBDIVISIONS )
+ sky_mins_subd[1] = HALF_SKY_SUBDIVISIONS;
+
+ if ( sky_maxs_subd[0] < -HALF_SKY_SUBDIVISIONS )
+ sky_maxs_subd[0] = -HALF_SKY_SUBDIVISIONS;
+ else if ( sky_maxs_subd[0] > HALF_SKY_SUBDIVISIONS )
+ sky_maxs_subd[0] = HALF_SKY_SUBDIVISIONS;
+ if ( sky_maxs_subd[1] < MIN_T )
+ sky_maxs_subd[1] = MIN_T;
+ else if ( sky_maxs_subd[1] > HALF_SKY_SUBDIVISIONS )
+ sky_maxs_subd[1] = HALF_SKY_SUBDIVISIONS;
+
+ //
+ // iterate through the subdivisions
+ //
+ for ( t = sky_mins_subd[1]+HALF_SKY_SUBDIVISIONS; t <= sky_maxs_subd[1]+HALF_SKY_SUBDIVISIONS; t++ )
+ {
+ for ( s = sky_mins_subd[0]+HALF_SKY_SUBDIVISIONS; s <= sky_maxs_subd[0]+HALF_SKY_SUBDIVISIONS; s++ )
+ {
+ MakeSkyVec( ( s - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS,
+ ( t - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS,
+ i,
+ NULL,
+ s_skyPoints[t][s] );
+
+ s_skyTexCoords[t][s][0] = s_cloudTexCoords[i][t][s][0];
+ s_skyTexCoords[t][s][1] = s_cloudTexCoords[i][t][s][1];
+ }
+ }
+
+ // only add indexes for first stage
+ FillCloudySkySide( sky_mins_subd, sky_maxs_subd, ( stage == 0 ) );
+ }
+}
+
+/*
+** R_BuildCloudData
+*/
+void R_BuildCloudData( shaderCommands_t *input )
+{
+ int i;
+ shader_t *shader;
+
+ shader = input->shader;
+
+ assert( shader->isSky );
+
+ sky_min = 1.0 / 256.0f; // FIXME: not correct?
+ sky_max = 255.0 / 256.0f;
+
+ // set up for drawing
+ tess.numIndexes = 0;
+ tess.numVertexes = 0;
+
+ if ( input->shader->sky.cloudHeight )
+ {
+ for ( i = 0; i < MAX_SHADER_STAGES; i++ )
+ {
+ if ( !tess.xstages[i] ) {
+ break;
+ }
+ FillCloudBox( input->shader, i );
+ }
+ }
+}
+
+/*
+** R_InitSkyTexCoords
+** Called when a sky shader is parsed
+*/
+#define SQR( a ) ((a)*(a))
+void R_InitSkyTexCoords( float heightCloud )
+{
+ int i, s, t;
+ float radiusWorld = 4096;
+ float p;
+ float sRad, tRad;
+ vec3_t skyVec;
+ vec3_t v;
+
+ // init zfar so MakeSkyVec works even though
+ // a world hasn't been bounded
+ backEnd.viewParms.zFar = 1024;
+
+ for ( i = 0; i < 6; i++ )
+ {
+ for ( t = 0; t <= SKY_SUBDIVISIONS; t++ )
+ {
+ for ( s = 0; s <= SKY_SUBDIVISIONS; s++ )
+ {
+ // compute vector from view origin to sky side integral point
+ MakeSkyVec( ( s - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS,
+ ( t - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS,
+ i,
+ NULL,
+ skyVec );
+
+ // compute parametric value 'p' that intersects with cloud layer
+ p = ( 1.0f / ( 2 * DotProduct( skyVec, skyVec ) ) ) *
+ ( -2 * skyVec[2] * radiusWorld +
+ 2 * sqrt( SQR( skyVec[2] ) * SQR( radiusWorld ) +
+ 2 * SQR( skyVec[0] ) * radiusWorld * heightCloud +
+ SQR( skyVec[0] ) * SQR( heightCloud ) +
+ 2 * SQR( skyVec[1] ) * radiusWorld * heightCloud +
+ SQR( skyVec[1] ) * SQR( heightCloud ) +
+ 2 * SQR( skyVec[2] ) * radiusWorld * heightCloud +
+ SQR( skyVec[2] ) * SQR( heightCloud ) ) );
+
+ s_cloudTexP[i][t][s] = p;
+
+ // compute intersection point based on p
+ VectorScale( skyVec, p, v );
+ v[2] += radiusWorld;
+
+ // compute vector from world origin to intersection point 'v'
+ VectorNormalize( v );
+
+ sRad = Q_acos( v[0] );
+ tRad = Q_acos( v[1] );
+
+ s_cloudTexCoords[i][t][s][0] = sRad;
+ s_cloudTexCoords[i][t][s][1] = tRad;
+ }
+ }
+ }
+}
+
+//======================================================================================
+
+/*
+** RB_DrawSun
+*/
+void RB_DrawSun( void ) {
+ float size;
+ float dist;
+ vec3_t origin, vec1, vec2;
+ vec3_t temp;
+
+ if ( !backEnd.skyRenderedThisView ) {
+ return;
+ }
+ if ( !r_drawSun->integer ) {
+ return;
+ }
+ qglLoadMatrixf( backEnd.viewParms.world.modelMatrix );
+ qglTranslatef (backEnd.viewParms.or.origin[0], backEnd.viewParms.or.origin[1], backEnd.viewParms.or.origin[2]);
+
+ dist = backEnd.viewParms.zFar / 1.75; // div sqrt(3)
+ size = dist * 0.4;
+
+ VectorScale( tr.sunDirection, dist, origin );
+ PerpendicularVector( vec1, tr.sunDirection );
+ CrossProduct( tr.sunDirection, vec1, vec2 );
+
+ VectorScale( vec1, size, vec1 );
+ VectorScale( vec2, size, vec2 );
+
+ // farthest depth range
+ qglDepthRange( 1.0, 1.0 );
+
+ // FIXME: use quad stamp
+ RB_BeginSurface( tr.sunShader, tess.fogNum );
+ VectorCopy( origin, temp );
+ VectorSubtract( temp, vec1, temp );
+ VectorSubtract( temp, vec2, temp );
+ VectorCopy( temp, tess.xyz[tess.numVertexes] );
+ tess.texCoords[tess.numVertexes][0][0] = 0;
+ tess.texCoords[tess.numVertexes][0][1] = 0;
+ tess.vertexColors[tess.numVertexes][0] = 255;
+ tess.vertexColors[tess.numVertexes][1] = 255;
+ tess.vertexColors[tess.numVertexes][2] = 255;
+ tess.numVertexes++;
+
+ VectorCopy( origin, temp );
+ VectorAdd( temp, vec1, temp );
+ VectorSubtract( temp, vec2, temp );
+ VectorCopy( temp, tess.xyz[tess.numVertexes] );
+ tess.texCoords[tess.numVertexes][0][0] = 0;
+ tess.texCoords[tess.numVertexes][0][1] = 1;
+ tess.vertexColors[tess.numVertexes][0] = 255;
+ tess.vertexColors[tess.numVertexes][1] = 255;
+ tess.vertexColors[tess.numVertexes][2] = 255;
+ tess.numVertexes++;
+
+ VectorCopy( origin, temp );
+ VectorAdd( temp, vec1, temp );
+ VectorAdd( temp, vec2, temp );
+ VectorCopy( temp, tess.xyz[tess.numVertexes] );
+ tess.texCoords[tess.numVertexes][0][0] = 1;
+ tess.texCoords[tess.numVertexes][0][1] = 1;
+ tess.vertexColors[tess.numVertexes][0] = 255;
+ tess.vertexColors[tess.numVertexes][1] = 255;
+ tess.vertexColors[tess.numVertexes][2] = 255;
+ tess.numVertexes++;
+
+ VectorCopy( origin, temp );
+ VectorSubtract( temp, vec1, temp );
+ VectorAdd( temp, vec2, temp );
+ VectorCopy( temp, tess.xyz[tess.numVertexes] );
+ tess.texCoords[tess.numVertexes][0][0] = 1;
+ tess.texCoords[tess.numVertexes][0][1] = 0;
+ tess.vertexColors[tess.numVertexes][0] = 255;
+ tess.vertexColors[tess.numVertexes][1] = 255;
+ tess.vertexColors[tess.numVertexes][2] = 255;
+ tess.numVertexes++;
+
+ tess.indexes[tess.numIndexes++] = 0;
+ tess.indexes[tess.numIndexes++] = 1;
+ tess.indexes[tess.numIndexes++] = 2;
+ tess.indexes[tess.numIndexes++] = 0;
+ tess.indexes[tess.numIndexes++] = 2;
+ tess.indexes[tess.numIndexes++] = 3;
+
+ RB_EndSurface();
+
+ // back to normal depth range
+ qglDepthRange( 0.0, 1.0 );
+}
+
+
+
+
+/*
+================
+RB_StageIteratorSky
+
+All of the visible sky triangles are in tess
+
+Other things could be stuck in here, like birds in the sky, etc
+================
+*/
+void RB_StageIteratorSky( void ) {
+ if ( r_fastsky->integer ) {
+ return;
+ }
+
+ // go through all the polygons and project them onto
+ // the sky box to see which blocks on each side need
+ // to be drawn
+ RB_ClipSkyPolygons( &tess );
+
+ // r_showsky will let all the sky blocks be drawn in
+ // front of everything to allow developers to see how
+ // much sky is getting sucked in
+ if ( r_showsky->integer ) {
+ qglDepthRange( 0.0, 0.0 );
+ } else {
+ qglDepthRange( 1.0, 1.0 );
+ }
+
+ // draw the outer skybox
+ if ( tess.shader->sky.outerbox[0] && tess.shader->sky.outerbox[0] != tr.defaultImage ) {
+ qglColor3f( tr.identityLight, tr.identityLight, tr.identityLight );
+
+ qglPushMatrix ();
+ GL_State( 0 );
+ qglTranslatef (backEnd.viewParms.or.origin[0], backEnd.viewParms.or.origin[1], backEnd.viewParms.or.origin[2]);
+
+ DrawSkyBox( tess.shader );
+
+ qglPopMatrix();
+ }
+
+ // generate the vertexes for all the clouds, which will be drawn
+ // by the generic shader routine
+ R_BuildCloudData( &tess );
+
+ RB_StageIteratorGeneric();
+
+ // draw the inner skybox
+
+
+ // back to normal depth range
+ qglDepthRange( 0.0, 1.0 );
+
+ // note that sky was drawn so we will draw a sun later
+ backEnd.skyRenderedThisView = qtrue;
+}
+
diff --git a/code/renderer/tr_surface.c b/code/renderer/tr_surface.c
new file mode 100755
index 0000000..599896d
--- /dev/null
+++ b/code/renderer/tr_surface.c
@@ -0,0 +1,1215 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// tr_surf.c
+#include "tr_local.h"
+
+/*
+
+ THIS ENTIRE FILE IS BACK END
+
+backEnd.currentEntity will be valid.
+
+Tess_Begin has already been called for the surface's shader.
+
+The modelview matrix will be set.
+
+It is safe to actually issue drawing commands here if you don't want to
+use the shader system.
+*/
+
+
+//============================================================================
+
+
+/*
+==============
+RB_CheckOverflow
+==============
+*/
+void RB_CheckOverflow( int verts, int indexes ) {
+ if (tess.numVertexes + verts < SHADER_MAX_VERTEXES
+ && tess.numIndexes + indexes < SHADER_MAX_INDEXES) {
+ return;
+ }
+
+ RB_EndSurface();
+
+ if ( verts >= SHADER_MAX_VERTEXES ) {
+ ri.Error(ERR_DROP, "RB_CheckOverflow: verts > MAX (%d > %d)", verts, SHADER_MAX_VERTEXES );
+ }
+ if ( indexes >= SHADER_MAX_INDEXES ) {
+ ri.Error(ERR_DROP, "RB_CheckOverflow: indices > MAX (%d > %d)", indexes, SHADER_MAX_INDEXES );
+ }
+
+ RB_BeginSurface(tess.shader, tess.fogNum );
+}
+
+
+/*
+==============
+RB_AddQuadStampExt
+==============
+*/
+void RB_AddQuadStampExt( vec3_t origin, vec3_t left, vec3_t up, byte *color, float s1, float t1, float s2, float t2 ) {
+ vec3_t normal;
+ int ndx;
+
+ RB_CHECKOVERFLOW( 4, 6 );
+
+ ndx = tess.numVertexes;
+
+ // triangle indexes for a simple quad
+ tess.indexes[ tess.numIndexes ] = ndx;
+ tess.indexes[ tess.numIndexes + 1 ] = ndx + 1;
+ tess.indexes[ tess.numIndexes + 2 ] = ndx + 3;
+
+ tess.indexes[ tess.numIndexes + 3 ] = ndx + 3;
+ tess.indexes[ tess.numIndexes + 4 ] = ndx + 1;
+ tess.indexes[ tess.numIndexes + 5 ] = ndx + 2;
+
+ tess.xyz[ndx][0] = origin[0] + left[0] + up[0];
+ tess.xyz[ndx][1] = origin[1] + left[1] + up[1];
+ tess.xyz[ndx][2] = origin[2] + left[2] + up[2];
+
+ tess.xyz[ndx+1][0] = origin[0] - left[0] + up[0];
+ tess.xyz[ndx+1][1] = origin[1] - left[1] + up[1];
+ tess.xyz[ndx+1][2] = origin[2] - left[2] + up[2];
+
+ tess.xyz[ndx+2][0] = origin[0] - left[0] - up[0];
+ tess.xyz[ndx+2][1] = origin[1] - left[1] - up[1];
+ tess.xyz[ndx+2][2] = origin[2] - left[2] - up[2];
+
+ tess.xyz[ndx+3][0] = origin[0] + left[0] - up[0];
+ tess.xyz[ndx+3][1] = origin[1] + left[1] - up[1];
+ tess.xyz[ndx+3][2] = origin[2] + left[2] - up[2];
+
+
+ // constant normal all the way around
+ VectorSubtract( vec3_origin, backEnd.viewParms.or.axis[0], normal );
+
+ tess.normal[ndx][0] = tess.normal[ndx+1][0] = tess.normal[ndx+2][0] = tess.normal[ndx+3][0] = normal[0];
+ tess.normal[ndx][1] = tess.normal[ndx+1][1] = tess.normal[ndx+2][1] = tess.normal[ndx+3][1] = normal[1];
+ tess.normal[ndx][2] = tess.normal[ndx+1][2] = tess.normal[ndx+2][2] = tess.normal[ndx+3][2] = normal[2];
+
+ // standard square texture coordinates
+ tess.texCoords[ndx][0][0] = tess.texCoords[ndx][1][0] = s1;
+ tess.texCoords[ndx][0][1] = tess.texCoords[ndx][1][1] = t1;
+
+ tess.texCoords[ndx+1][0][0] = tess.texCoords[ndx+1][1][0] = s2;
+ tess.texCoords[ndx+1][0][1] = tess.texCoords[ndx+1][1][1] = t1;
+
+ tess.texCoords[ndx+2][0][0] = tess.texCoords[ndx+2][1][0] = s2;
+ tess.texCoords[ndx+2][0][1] = tess.texCoords[ndx+2][1][1] = t2;
+
+ tess.texCoords[ndx+3][0][0] = tess.texCoords[ndx+3][1][0] = s1;
+ tess.texCoords[ndx+3][0][1] = tess.texCoords[ndx+3][1][1] = t2;
+
+ // constant color all the way around
+ // should this be identity and let the shader specify from entity?
+ * ( unsigned int * ) &tess.vertexColors[ndx] =
+ * ( unsigned int * ) &tess.vertexColors[ndx+1] =
+ * ( unsigned int * ) &tess.vertexColors[ndx+2] =
+ * ( unsigned int * ) &tess.vertexColors[ndx+3] =
+ * ( unsigned int * )color;
+
+
+ tess.numVertexes += 4;
+ tess.numIndexes += 6;
+}
+
+/*
+==============
+RB_AddQuadStamp
+==============
+*/
+void RB_AddQuadStamp( vec3_t origin, vec3_t left, vec3_t up, byte *color ) {
+ RB_AddQuadStampExt( origin, left, up, color, 0, 0, 1, 1 );
+}
+
+/*
+==============
+RB_SurfaceSprite
+==============
+*/
+static void RB_SurfaceSprite( void ) {
+ vec3_t left, up;
+ float radius;
+
+ // calculate the xyz locations for the four corners
+ radius = backEnd.currentEntity->e.radius;
+ if ( backEnd.currentEntity->e.rotation == 0 ) {
+ VectorScale( backEnd.viewParms.or.axis[1], radius, left );
+ VectorScale( backEnd.viewParms.or.axis[2], radius, up );
+ } else {
+ float s, c;
+ float ang;
+
+ ang = M_PI * backEnd.currentEntity->e.rotation / 180;
+ s = sin( ang );
+ c = cos( ang );
+
+ VectorScale( backEnd.viewParms.or.axis[1], c * radius, left );
+ VectorMA( left, -s * radius, backEnd.viewParms.or.axis[2], left );
+
+ VectorScale( backEnd.viewParms.or.axis[2], c * radius, up );
+ VectorMA( up, s * radius, backEnd.viewParms.or.axis[1], up );
+ }
+ if ( backEnd.viewParms.isMirror ) {
+ VectorSubtract( vec3_origin, left, left );
+ }
+
+ RB_AddQuadStamp( backEnd.currentEntity->e.origin, left, up, backEnd.currentEntity->e.shaderRGBA );
+}
+
+
+/*
+=============
+RB_SurfacePolychain
+=============
+*/
+void RB_SurfacePolychain( srfPoly_t *p ) {
+ int i;
+ int numv;
+
+ RB_CHECKOVERFLOW( p->numVerts, 3*(p->numVerts - 2) );
+
+ // fan triangles into the tess array
+ numv = tess.numVertexes;
+ for ( i = 0; i < p->numVerts; i++ ) {
+ VectorCopy( p->verts[i].xyz, tess.xyz[numv] );
+ tess.texCoords[numv][0][0] = p->verts[i].st[0];
+ tess.texCoords[numv][0][1] = p->verts[i].st[1];
+ *(int *)&tess.vertexColors[numv] = *(int *)p->verts[ i ].modulate;
+
+ numv++;
+ }
+
+ // generate fan indexes into the tess array
+ for ( i = 0; i < p->numVerts-2; i++ ) {
+ tess.indexes[tess.numIndexes + 0] = tess.numVertexes;
+ tess.indexes[tess.numIndexes + 1] = tess.numVertexes + i + 1;
+ tess.indexes[tess.numIndexes + 2] = tess.numVertexes + i + 2;
+ tess.numIndexes += 3;
+ }
+
+ tess.numVertexes = numv;
+}
+
+
+/*
+=============
+RB_SurfaceTriangles
+=============
+*/
+void RB_SurfaceTriangles( srfTriangles_t *srf ) {
+ int i;
+ drawVert_t *dv;
+ float *xyz, *normal, *texCoords;
+ byte *color;
+ int dlightBits;
+ qboolean needsNormal;
+
+ dlightBits = srf->dlightBits[backEnd.smpFrame];
+ tess.dlightBits |= dlightBits;
+
+ RB_CHECKOVERFLOW( srf->numVerts, srf->numIndexes );
+
+ for ( i = 0 ; i < srf->numIndexes ; i += 3 ) {
+ tess.indexes[ tess.numIndexes + i + 0 ] = tess.numVertexes + srf->indexes[ i + 0 ];
+ tess.indexes[ tess.numIndexes + i + 1 ] = tess.numVertexes + srf->indexes[ i + 1 ];
+ tess.indexes[ tess.numIndexes + i + 2 ] = tess.numVertexes + srf->indexes[ i + 2 ];
+ }
+ tess.numIndexes += srf->numIndexes;
+
+ dv = srf->verts;
+ xyz = tess.xyz[ tess.numVertexes ];
+ normal = tess.normal[ tess.numVertexes ];
+ texCoords = tess.texCoords[ tess.numVertexes ][0];
+ color = tess.vertexColors[ tess.numVertexes ];
+ needsNormal = tess.shader->needsNormal;
+
+ for ( i = 0 ; i < srf->numVerts ; i++, dv++, xyz += 4, normal += 4, texCoords += 4, color += 4 ) {
+ xyz[0] = dv->xyz[0];
+ xyz[1] = dv->xyz[1];
+ xyz[2] = dv->xyz[2];
+
+ if ( needsNormal ) {
+ normal[0] = dv->normal[0];
+ normal[1] = dv->normal[1];
+ normal[2] = dv->normal[2];
+ }
+
+ texCoords[0] = dv->st[0];
+ texCoords[1] = dv->st[1];
+
+ texCoords[2] = dv->lightmap[0];
+ texCoords[3] = dv->lightmap[1];
+
+ *(int *)color = *(int *)dv->color;
+ }
+
+ for ( i = 0 ; i < srf->numVerts ; i++ ) {
+ tess.vertexDlightBits[ tess.numVertexes + i] = dlightBits;
+ }
+
+ tess.numVertexes += srf->numVerts;
+}
+
+
+
+/*
+==============
+RB_SurfaceBeam
+==============
+*/
+void RB_SurfaceBeam( void )
+{
+#define NUM_BEAM_SEGS 6
+ refEntity_t *e;
+ int i;
+ vec3_t perpvec;
+ vec3_t direction, normalized_direction;
+ vec3_t start_points[NUM_BEAM_SEGS], end_points[NUM_BEAM_SEGS];
+ vec3_t oldorigin, origin;
+
+ e = &backEnd.currentEntity->e;
+
+ oldorigin[0] = e->oldorigin[0];
+ oldorigin[1] = e->oldorigin[1];
+ oldorigin[2] = e->oldorigin[2];
+
+ origin[0] = e->origin[0];
+ origin[1] = e->origin[1];
+ origin[2] = e->origin[2];
+
+ normalized_direction[0] = direction[0] = oldorigin[0] - origin[0];
+ normalized_direction[1] = direction[1] = oldorigin[1] - origin[1];
+ normalized_direction[2] = direction[2] = oldorigin[2] - origin[2];
+
+ if ( VectorNormalize( normalized_direction ) == 0 )
+ return;
+
+ PerpendicularVector( perpvec, normalized_direction );
+
+ VectorScale( perpvec, 4, perpvec );
+
+ for ( i = 0; i < NUM_BEAM_SEGS ; i++ )
+ {
+ RotatePointAroundVector( start_points[i], normalized_direction, perpvec, (360.0/NUM_BEAM_SEGS)*i );
+// VectorAdd( start_points[i], origin, start_points[i] );
+ VectorAdd( start_points[i], direction, end_points[i] );
+ }
+
+ GL_Bind( tr.whiteImage );
+
+ GL_State( GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE );
+
+ qglColor3f( 1, 0, 0 );
+
+ qglBegin( GL_TRIANGLE_STRIP );
+ for ( i = 0; i <= NUM_BEAM_SEGS; i++ ) {
+ qglVertex3fv( start_points[ i % NUM_BEAM_SEGS] );
+ qglVertex3fv( end_points[ i % NUM_BEAM_SEGS] );
+ }
+ qglEnd();
+}
+
+//================================================================================
+
+static void DoRailCore( const vec3_t start, const vec3_t end, const vec3_t up, float len, float spanWidth )
+{
+ float spanWidth2;
+ int vbase;
+ float t = len / 256.0f;
+
+ vbase = tess.numVertexes;
+
+ spanWidth2 = -spanWidth;
+
+ // FIXME: use quad stamp?
+ VectorMA( start, spanWidth, up, tess.xyz[tess.numVertexes] );
+ tess.texCoords[tess.numVertexes][0][0] = 0;
+ tess.texCoords[tess.numVertexes][0][1] = 0;
+ tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0] * 0.25;
+ tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1] * 0.25;
+ tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2] * 0.25;
+ tess.numVertexes++;
+
+ VectorMA( start, spanWidth2, up, tess.xyz[tess.numVertexes] );
+ tess.texCoords[tess.numVertexes][0][0] = 0;
+ tess.texCoords[tess.numVertexes][0][1] = 1;
+ tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0];
+ tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1];
+ tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2];
+ tess.numVertexes++;
+
+ VectorMA( end, spanWidth, up, tess.xyz[tess.numVertexes] );
+
+ tess.texCoords[tess.numVertexes][0][0] = t;
+ tess.texCoords[tess.numVertexes][0][1] = 0;
+ tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0];
+ tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1];
+ tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2];
+ tess.numVertexes++;
+
+ VectorMA( end, spanWidth2, up, tess.xyz[tess.numVertexes] );
+ tess.texCoords[tess.numVertexes][0][0] = t;
+ tess.texCoords[tess.numVertexes][0][1] = 1;
+ tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0];
+ tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1];
+ tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2];
+ tess.numVertexes++;
+
+ tess.indexes[tess.numIndexes++] = vbase;
+ tess.indexes[tess.numIndexes++] = vbase + 1;
+ tess.indexes[tess.numIndexes++] = vbase + 2;
+
+ tess.indexes[tess.numIndexes++] = vbase + 2;
+ tess.indexes[tess.numIndexes++] = vbase + 1;
+ tess.indexes[tess.numIndexes++] = vbase + 3;
+}
+
+static void DoRailDiscs( int numSegs, const vec3_t start, const vec3_t dir, const vec3_t right, const vec3_t up )
+{
+ int i;
+ vec3_t pos[4];
+ vec3_t v;
+ int spanWidth = r_railWidth->integer;
+ float c, s;
+ float scale;
+
+ if ( numSegs > 1 )
+ numSegs--;
+ if ( !numSegs )
+ return;
+
+ scale = 0.25;
+
+ for ( i = 0; i < 4; i++ )
+ {
+ c = cos( DEG2RAD( 45 + i * 90 ) );
+ s = sin( DEG2RAD( 45 + i * 90 ) );
+ v[0] = ( right[0] * c + up[0] * s ) * scale * spanWidth;
+ v[1] = ( right[1] * c + up[1] * s ) * scale * spanWidth;
+ v[2] = ( right[2] * c + up[2] * s ) * scale * spanWidth;
+ VectorAdd( start, v, pos[i] );
+
+ if ( numSegs > 1 )
+ {
+ // offset by 1 segment if we're doing a long distance shot
+ VectorAdd( pos[i], dir, pos[i] );
+ }
+ }
+
+ for ( i = 0; i < numSegs; i++ )
+ {
+ int j;
+
+ RB_CHECKOVERFLOW( 4, 6 );
+
+ for ( j = 0; j < 4; j++ )
+ {
+ VectorCopy( pos[j], tess.xyz[tess.numVertexes] );
+ tess.texCoords[tess.numVertexes][0][0] = ( j < 2 );
+ tess.texCoords[tess.numVertexes][0][1] = ( j && j != 3 );
+ tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0];
+ tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1];
+ tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2];
+ tess.numVertexes++;
+
+ VectorAdd( pos[j], dir, pos[j] );
+ }
+
+ tess.indexes[tess.numIndexes++] = tess.numVertexes - 4 + 0;
+ tess.indexes[tess.numIndexes++] = tess.numVertexes - 4 + 1;
+ tess.indexes[tess.numIndexes++] = tess.numVertexes - 4 + 3;
+ tess.indexes[tess.numIndexes++] = tess.numVertexes - 4 + 3;
+ tess.indexes[tess.numIndexes++] = tess.numVertexes - 4 + 1;
+ tess.indexes[tess.numIndexes++] = tess.numVertexes - 4 + 2;
+ }
+}
+
+/*
+** RB_SurfaceRailRinges
+*/
+void RB_SurfaceRailRings( void ) {
+ refEntity_t *e;
+ int numSegs;
+ int len;
+ vec3_t vec;
+ vec3_t right, up;
+ vec3_t start, end;
+
+ e = &backEnd.currentEntity->e;
+
+ VectorCopy( e->oldorigin, start );
+ VectorCopy( e->origin, end );
+
+ // compute variables
+ VectorSubtract( end, start, vec );
+ len = VectorNormalize( vec );
+ MakeNormalVectors( vec, right, up );
+ numSegs = ( len ) / r_railSegmentLength->value;
+ if ( numSegs <= 0 ) {
+ numSegs = 1;
+ }
+
+ VectorScale( vec, r_railSegmentLength->value, vec );
+
+ DoRailDiscs( numSegs, start, vec, right, up );
+}
+
+/*
+** RB_SurfaceRailCore
+*/
+void RB_SurfaceRailCore( void ) {
+ refEntity_t *e;
+ int len;
+ vec3_t right;
+ vec3_t vec;
+ vec3_t start, end;
+ vec3_t v1, v2;
+
+ e = &backEnd.currentEntity->e;
+
+ VectorCopy( e->oldorigin, start );
+ VectorCopy( e->origin, end );
+
+ VectorSubtract( end, start, vec );
+ len = VectorNormalize( vec );
+
+ // compute side vector
+ VectorSubtract( start, backEnd.viewParms.or.origin, v1 );
+ VectorNormalize( v1 );
+ VectorSubtract( end, backEnd.viewParms.or.origin, v2 );
+ VectorNormalize( v2 );
+ CrossProduct( v1, v2, right );
+ VectorNormalize( right );
+
+ DoRailCore( start, end, right, len, r_railCoreWidth->integer );
+}
+
+/*
+** RB_SurfaceLightningBolt
+*/
+void RB_SurfaceLightningBolt( void ) {
+ refEntity_t *e;
+ int len;
+ vec3_t right;
+ vec3_t vec;
+ vec3_t start, end;
+ vec3_t v1, v2;
+ int i;
+
+ e = &backEnd.currentEntity->e;
+
+ VectorCopy( e->oldorigin, end );
+ VectorCopy( e->origin, start );
+
+ // compute variables
+ VectorSubtract( end, start, vec );
+ len = VectorNormalize( vec );
+
+ // compute side vector
+ VectorSubtract( start, backEnd.viewParms.or.origin, v1 );
+ VectorNormalize( v1 );
+ VectorSubtract( end, backEnd.viewParms.or.origin, v2 );
+ VectorNormalize( v2 );
+ CrossProduct( v1, v2, right );
+ VectorNormalize( right );
+
+ for ( i = 0 ; i < 4 ; i++ ) {
+ vec3_t temp;
+
+ DoRailCore( start, end, right, len, 8 );
+ RotatePointAroundVector( temp, vec, right, 45 );
+ VectorCopy( temp, right );
+ }
+}
+
+/*
+** VectorArrayNormalize
+*
+* The inputs to this routing seem to always be close to length = 1.0 (about 0.6 to 2.0)
+* This means that we don't have to worry about zero length or enormously long vectors.
+*/
+static void VectorArrayNormalize(vec4_t *normals, unsigned int count)
+{
+// assert(count);
+
+#if idppc
+ {
+ register float half = 0.5;
+ register float one = 1.0;
+ float *components = (float *)normals;
+
+ // Vanilla PPC code, but since PPC has a reciprocal square root estimate instruction,
+ // runs *much* faster than calling sqrt(). We'll use a single Newton-Raphson
+ // refinement step to get a little more precision. This seems to yeild results
+ // that are correct to 3 decimal places and usually correct to at least 4 (sometimes 5).
+ // (That is, for the given input range of about 0.6 to 2.0).
+ do {
+ float x, y, z;
+ float B, y0, y1;
+
+ x = components[0];
+ y = components[1];
+ z = components[2];
+ components += 4;
+ B = x*x + y*y + z*z;
+
+#ifdef __GNUC__
+ asm("frsqrte %0,%1" : "=f" (y0) : "f" (B));
+#else
+ y0 = __frsqrte(B);
+#endif
+ y1 = y0 + half*y0*(one - B*y0*y0);
+
+ x = x * y1;
+ y = y * y1;
+ components[-4] = x;
+ z = z * y1;
+ components[-3] = y;
+ components[-2] = z;
+ } while(count--);
+ }
+#else // No assembly version for this architecture, or C_ONLY defined
+ // given the input, it's safe to call VectorNormalizeFast
+ while (count--) {
+ VectorNormalizeFast(normals[0]);
+ normals++;
+ }
+#endif
+
+}
+
+
+
+/*
+** LerpMeshVertexes
+*/
+static void LerpMeshVertexes (md3Surface_t *surf, float backlerp)
+{
+ short *oldXyz, *newXyz, *oldNormals, *newNormals;
+ float *outXyz, *outNormal;
+ float oldXyzScale, newXyzScale;
+ float oldNormalScale, newNormalScale;
+ int vertNum;
+ unsigned lat, lng;
+ int numVerts;
+
+ outXyz = tess.xyz[tess.numVertexes];
+ outNormal = tess.normal[tess.numVertexes];
+
+ newXyz = (short *)((byte *)surf + surf->ofsXyzNormals)
+ + (backEnd.currentEntity->e.frame * surf->numVerts * 4);
+ newNormals = newXyz + 3;
+
+ newXyzScale = MD3_XYZ_SCALE * (1.0 - backlerp);
+ newNormalScale = 1.0 - backlerp;
+
+ numVerts = surf->numVerts;
+
+ if ( backlerp == 0 ) {
+#if idppc_altivec
+ vector signed short newNormalsVec0;
+ vector signed short newNormalsVec1;
+ vector signed int newNormalsIntVec;
+ vector float newNormalsFloatVec;
+ vector float newXyzScaleVec;
+ vector unsigned char newNormalsLoadPermute;
+ vector unsigned char newNormalsStorePermute;
+ vector float zero;
+
+ newNormalsStorePermute = vec_lvsl(0,(float *)&newXyzScaleVec);
+ newXyzScaleVec = *(vector float *)&newXyzScale;
+ newXyzScaleVec = vec_perm(newXyzScaleVec,newXyzScaleVec,newNormalsStorePermute);
+ newXyzScaleVec = vec_splat(newXyzScaleVec,0);
+ newNormalsLoadPermute = vec_lvsl(0,newXyz);
+ newNormalsStorePermute = vec_lvsr(0,outXyz);
+ zero = (vector float)vec_splat_s8(0);
+ //
+ // just copy the vertexes
+ //
+ for (vertNum=0 ; vertNum < numVerts ; vertNum++,
+ newXyz += 4, newNormals += 4,
+ outXyz += 4, outNormal += 4)
+ {
+ newNormalsLoadPermute = vec_lvsl(0,newXyz);
+ newNormalsStorePermute = vec_lvsr(0,outXyz);
+ newNormalsVec0 = vec_ld(0,newXyz);
+ newNormalsVec1 = vec_ld(16,newXyz);
+ newNormalsVec0 = vec_perm(newNormalsVec0,newNormalsVec1,newNormalsLoadPermute);
+ newNormalsIntVec = vec_unpackh(newNormalsVec0);
+ newNormalsFloatVec = vec_ctf(newNormalsIntVec,0);
+ newNormalsFloatVec = vec_madd(newNormalsFloatVec,newXyzScaleVec,zero);
+ newNormalsFloatVec = vec_perm(newNormalsFloatVec,newNormalsFloatVec,newNormalsStorePermute);
+ //outXyz[0] = newXyz[0] * newXyzScale;
+ //outXyz[1] = newXyz[1] * newXyzScale;
+ //outXyz[2] = newXyz[2] * newXyzScale;
+
+ lat = ( newNormals[0] >> 8 ) & 0xff;
+ lng = ( newNormals[0] & 0xff );
+ lat *= (FUNCTABLE_SIZE/256);
+ lng *= (FUNCTABLE_SIZE/256);
+
+ // decode X as cos( lat ) * sin( long )
+ // decode Y as sin( lat ) * sin( long )
+ // decode Z as cos( long )
+
+ outNormal[0] = tr.sinTable[(lat+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK] * tr.sinTable[lng];
+ outNormal[1] = tr.sinTable[lat] * tr.sinTable[lng];
+ outNormal[2] = tr.sinTable[(lng+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK];
+
+ vec_ste(newNormalsFloatVec,0,outXyz);
+ vec_ste(newNormalsFloatVec,4,outXyz);
+ vec_ste(newNormalsFloatVec,8,outXyz);
+ }
+
+#else
+ //
+ // just copy the vertexes
+ //
+ for (vertNum=0 ; vertNum < numVerts ; vertNum++,
+ newXyz += 4, newNormals += 4,
+ outXyz += 4, outNormal += 4)
+ {
+
+ outXyz[0] = newXyz[0] * newXyzScale;
+ outXyz[1] = newXyz[1] * newXyzScale;
+ outXyz[2] = newXyz[2] * newXyzScale;
+
+ lat = ( newNormals[0] >> 8 ) & 0xff;
+ lng = ( newNormals[0] & 0xff );
+ lat *= (FUNCTABLE_SIZE/256);
+ lng *= (FUNCTABLE_SIZE/256);
+
+ // decode X as cos( lat ) * sin( long )
+ // decode Y as sin( lat ) * sin( long )
+ // decode Z as cos( long )
+
+ outNormal[0] = tr.sinTable[(lat+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK] * tr.sinTable[lng];
+ outNormal[1] = tr.sinTable[lat] * tr.sinTable[lng];
+ outNormal[2] = tr.sinTable[(lng+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK];
+ }
+#endif
+ } else {
+ //
+ // interpolate and copy the vertex and normal
+ //
+ oldXyz = (short *)((byte *)surf + surf->ofsXyzNormals)
+ + (backEnd.currentEntity->e.oldframe * surf->numVerts * 4);
+ oldNormals = oldXyz + 3;
+
+ oldXyzScale = MD3_XYZ_SCALE * backlerp;
+ oldNormalScale = backlerp;
+
+ for (vertNum=0 ; vertNum < numVerts ; vertNum++,
+ oldXyz += 4, newXyz += 4, oldNormals += 4, newNormals += 4,
+ outXyz += 4, outNormal += 4)
+ {
+ vec3_t uncompressedOldNormal, uncompressedNewNormal;
+
+ // interpolate the xyz
+ outXyz[0] = oldXyz[0] * oldXyzScale + newXyz[0] * newXyzScale;
+ outXyz[1] = oldXyz[1] * oldXyzScale + newXyz[1] * newXyzScale;
+ outXyz[2] = oldXyz[2] * oldXyzScale + newXyz[2] * newXyzScale;
+
+ // FIXME: interpolate lat/long instead?
+ lat = ( newNormals[0] >> 8 ) & 0xff;
+ lng = ( newNormals[0] & 0xff );
+ lat *= 4;
+ lng *= 4;
+ uncompressedNewNormal[0] = tr.sinTable[(lat+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK] * tr.sinTable[lng];
+ uncompressedNewNormal[1] = tr.sinTable[lat] * tr.sinTable[lng];
+ uncompressedNewNormal[2] = tr.sinTable[(lng+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK];
+
+ lat = ( oldNormals[0] >> 8 ) & 0xff;
+ lng = ( oldNormals[0] & 0xff );
+ lat *= 4;
+ lng *= 4;
+
+ uncompressedOldNormal[0] = tr.sinTable[(lat+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK] * tr.sinTable[lng];
+ uncompressedOldNormal[1] = tr.sinTable[lat] * tr.sinTable[lng];
+ uncompressedOldNormal[2] = tr.sinTable[(lng+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK];
+
+ outNormal[0] = uncompressedOldNormal[0] * oldNormalScale + uncompressedNewNormal[0] * newNormalScale;
+ outNormal[1] = uncompressedOldNormal[1] * oldNormalScale + uncompressedNewNormal[1] * newNormalScale;
+ outNormal[2] = uncompressedOldNormal[2] * oldNormalScale + uncompressedNewNormal[2] * newNormalScale;
+
+// VectorNormalize (outNormal);
+ }
+ VectorArrayNormalize((vec4_t *)tess.normal[tess.numVertexes], numVerts);
+ }
+}
+
+/*
+=============
+RB_SurfaceMesh
+=============
+*/
+void RB_SurfaceMesh(md3Surface_t *surface) {
+ int j;
+ float backlerp;
+ int *triangles;
+ float *texCoords;
+ int indexes;
+ int Bob, Doug;
+ int numVerts;
+
+ if ( backEnd.currentEntity->e.oldframe == backEnd.currentEntity->e.frame ) {
+ backlerp = 0;
+ } else {
+ backlerp = backEnd.currentEntity->e.backlerp;
+ }
+
+ RB_CHECKOVERFLOW( surface->numVerts, surface->numTriangles*3 );
+
+ LerpMeshVertexes (surface, backlerp);
+
+ triangles = (int *) ((byte *)surface + surface->ofsTriangles);
+ indexes = surface->numTriangles * 3;
+ Bob = tess.numIndexes;
+ Doug = tess.numVertexes;
+ for (j = 0 ; j < indexes ; j++) {
+ tess.indexes[Bob + j] = Doug + triangles[j];
+ }
+ tess.numIndexes += indexes;
+
+ texCoords = (float *) ((byte *)surface + surface->ofsSt);
+
+ numVerts = surface->numVerts;
+ for ( j = 0; j < numVerts; j++ ) {
+ tess.texCoords[Doug + j][0][0] = texCoords[j*2+0];
+ tess.texCoords[Doug + j][0][1] = texCoords[j*2+1];
+ // FIXME: fill in lightmapST for completeness?
+ }
+
+ tess.numVertexes += surface->numVerts;
+
+}
+
+
+/*
+==============
+RB_SurfaceFace
+==============
+*/
+void RB_SurfaceFace( srfSurfaceFace_t *surf ) {
+ int i;
+ unsigned *indices, *tessIndexes;
+ float *v;
+ float *normal;
+ int ndx;
+ int Bob;
+ int numPoints;
+ int dlightBits;
+
+ RB_CHECKOVERFLOW( surf->numPoints, surf->numIndices );
+
+ dlightBits = surf->dlightBits[backEnd.smpFrame];
+ tess.dlightBits |= dlightBits;
+
+ indices = ( unsigned * ) ( ( ( char * ) surf ) + surf->ofsIndices );
+
+ Bob = tess.numVertexes;
+ tessIndexes = tess.indexes + tess.numIndexes;
+ for ( i = surf->numIndices-1 ; i >= 0 ; i-- ) {
+ tessIndexes[i] = indices[i] + Bob;
+ }
+
+ tess.numIndexes += surf->numIndices;
+
+ v = surf->points[0];
+
+ ndx = tess.numVertexes;
+
+ numPoints = surf->numPoints;
+
+ if ( tess.shader->needsNormal ) {
+ normal = surf->plane.normal;
+ for ( i = 0, ndx = tess.numVertexes; i < numPoints; i++, ndx++ ) {
+ VectorCopy( normal, tess.normal[ndx] );
+ }
+ }
+
+ for ( i = 0, v = surf->points[0], ndx = tess.numVertexes; i < numPoints; i++, v += VERTEXSIZE, ndx++ ) {
+ VectorCopy( v, tess.xyz[ndx]);
+ tess.texCoords[ndx][0][0] = v[3];
+ tess.texCoords[ndx][0][1] = v[4];
+ tess.texCoords[ndx][1][0] = v[5];
+ tess.texCoords[ndx][1][1] = v[6];
+ * ( unsigned int * ) &tess.vertexColors[ndx] = * ( unsigned int * ) &v[7];
+ tess.vertexDlightBits[ndx] = dlightBits;
+ }
+
+
+ tess.numVertexes += surf->numPoints;
+}
+
+
+static float LodErrorForVolume( vec3_t local, float radius ) {
+ vec3_t world;
+ float d;
+
+ // never let it go negative
+ if ( r_lodCurveError->value < 0 ) {
+ return 0;
+ }
+
+ world[0] = local[0] * backEnd.or.axis[0][0] + local[1] * backEnd.or.axis[1][0] +
+ local[2] * backEnd.or.axis[2][0] + backEnd.or.origin[0];
+ world[1] = local[0] * backEnd.or.axis[0][1] + local[1] * backEnd.or.axis[1][1] +
+ local[2] * backEnd.or.axis[2][1] + backEnd.or.origin[1];
+ world[2] = local[0] * backEnd.or.axis[0][2] + local[1] * backEnd.or.axis[1][2] +
+ local[2] * backEnd.or.axis[2][2] + backEnd.or.origin[2];
+
+ VectorSubtract( world, backEnd.viewParms.or.origin, world );
+ d = DotProduct( world, backEnd.viewParms.or.axis[0] );
+
+ if ( d < 0 ) {
+ d = -d;
+ }
+ d -= radius;
+ if ( d < 1 ) {
+ d = 1;
+ }
+
+ return r_lodCurveError->value / d;
+}
+
+/*
+=============
+RB_SurfaceGrid
+
+Just copy the grid of points and triangulate
+=============
+*/
+void RB_SurfaceGrid( srfGridMesh_t *cv ) {
+ int i, j;
+ float *xyz;
+ float *texCoords;
+ float *normal;
+ unsigned char *color;
+ drawVert_t *dv;
+ int rows, irows, vrows;
+ int used;
+ int widthTable[MAX_GRID_SIZE];
+ int heightTable[MAX_GRID_SIZE];
+ float lodError;
+ int lodWidth, lodHeight;
+ int numVertexes;
+ int dlightBits;
+ int *vDlightBits;
+ qboolean needsNormal;
+
+ dlightBits = cv->dlightBits[backEnd.smpFrame];
+ tess.dlightBits |= dlightBits;
+
+ // determine the allowable discrepance
+ lodError = LodErrorForVolume( cv->lodOrigin, cv->lodRadius );
+
+ // determine which rows and columns of the subdivision
+ // we are actually going to use
+ widthTable[0] = 0;
+ lodWidth = 1;
+ for ( i = 1 ; i < cv->width-1 ; i++ ) {
+ if ( cv->widthLodError[i] <= lodError ) {
+ widthTable[lodWidth] = i;
+ lodWidth++;
+ }
+ }
+ widthTable[lodWidth] = cv->width-1;
+ lodWidth++;
+
+ heightTable[0] = 0;
+ lodHeight = 1;
+ for ( i = 1 ; i < cv->height-1 ; i++ ) {
+ if ( cv->heightLodError[i] <= lodError ) {
+ heightTable[lodHeight] = i;
+ lodHeight++;
+ }
+ }
+ heightTable[lodHeight] = cv->height-1;
+ lodHeight++;
+
+
+ // very large grids may have more points or indexes than can be fit
+ // in the tess structure, so we may have to issue it in multiple passes
+
+ used = 0;
+ rows = 0;
+ while ( used < lodHeight - 1 ) {
+ // see how many rows of both verts and indexes we can add without overflowing
+ do {
+ vrows = ( SHADER_MAX_VERTEXES - tess.numVertexes ) / lodWidth;
+ irows = ( SHADER_MAX_INDEXES - tess.numIndexes ) / ( lodWidth * 6 );
+
+ // if we don't have enough space for at least one strip, flush the buffer
+ if ( vrows < 2 || irows < 1 ) {
+ RB_EndSurface();
+ RB_BeginSurface(tess.shader, tess.fogNum );
+ } else {
+ break;
+ }
+ } while ( 1 );
+
+ rows = irows;
+ if ( vrows < irows + 1 ) {
+ rows = vrows - 1;
+ }
+ if ( used + rows > lodHeight ) {
+ rows = lodHeight - used;
+ }
+
+ numVertexes = tess.numVertexes;
+
+ xyz = tess.xyz[numVertexes];
+ normal = tess.normal[numVertexes];
+ texCoords = tess.texCoords[numVertexes][0];
+ color = ( unsigned char * ) &tess.vertexColors[numVertexes];
+ vDlightBits = &tess.vertexDlightBits[numVertexes];
+ needsNormal = tess.shader->needsNormal;
+
+ for ( i = 0 ; i < rows ; i++ ) {
+ for ( j = 0 ; j < lodWidth ; j++ ) {
+ dv = cv->verts + heightTable[ used + i ] * cv->width
+ + widthTable[ j ];
+
+ xyz[0] = dv->xyz[0];
+ xyz[1] = dv->xyz[1];
+ xyz[2] = dv->xyz[2];
+ texCoords[0] = dv->st[0];
+ texCoords[1] = dv->st[1];
+ texCoords[2] = dv->lightmap[0];
+ texCoords[3] = dv->lightmap[1];
+ if ( needsNormal ) {
+ normal[0] = dv->normal[0];
+ normal[1] = dv->normal[1];
+ normal[2] = dv->normal[2];
+ }
+ * ( unsigned int * ) color = * ( unsigned int * ) dv->color;
+ *vDlightBits++ = dlightBits;
+ xyz += 4;
+ normal += 4;
+ texCoords += 4;
+ color += 4;
+ }
+ }
+
+
+ // add the indexes
+ {
+ int numIndexes;
+ int w, h;
+
+ h = rows - 1;
+ w = lodWidth - 1;
+ numIndexes = tess.numIndexes;
+ for (i = 0 ; i < h ; i++) {
+ for (j = 0 ; j < w ; j++) {
+ int v1, v2, v3, v4;
+
+ // vertex order to be reckognized as tristrips
+ v1 = numVertexes + i*lodWidth + j + 1;
+ v2 = v1 - 1;
+ v3 = v2 + lodWidth;
+ v4 = v3 + 1;
+
+ tess.indexes[numIndexes] = v2;
+ tess.indexes[numIndexes+1] = v3;
+ tess.indexes[numIndexes+2] = v1;
+
+ tess.indexes[numIndexes+3] = v1;
+ tess.indexes[numIndexes+4] = v3;
+ tess.indexes[numIndexes+5] = v4;
+ numIndexes += 6;
+ }
+ }
+
+ tess.numIndexes = numIndexes;
+ }
+
+ tess.numVertexes += rows * lodWidth;
+
+ used += rows - 1;
+ }
+}
+
+
+/*
+===========================================================================
+
+NULL MODEL
+
+===========================================================================
+*/
+
+/*
+===================
+RB_SurfaceAxis
+
+Draws x/y/z lines from the origin for orientation debugging
+===================
+*/
+void RB_SurfaceAxis( void ) {
+ GL_Bind( tr.whiteImage );
+ qglLineWidth( 3 );
+ qglBegin( GL_LINES );
+ qglColor3f( 1,0,0 );
+ qglVertex3f( 0,0,0 );
+ qglVertex3f( 16,0,0 );
+ qglColor3f( 0,1,0 );
+ qglVertex3f( 0,0,0 );
+ qglVertex3f( 0,16,0 );
+ qglColor3f( 0,0,1 );
+ qglVertex3f( 0,0,0 );
+ qglVertex3f( 0,0,16 );
+ qglEnd();
+ qglLineWidth( 1 );
+}
+
+//===========================================================================
+
+/*
+====================
+RB_SurfaceEntity
+
+Entities that have a single procedurally generated surface
+====================
+*/
+void RB_SurfaceEntity( surfaceType_t *surfType ) {
+ switch( backEnd.currentEntity->e.reType ) {
+ case RT_SPRITE:
+ RB_SurfaceSprite();
+ break;
+ case RT_BEAM:
+ RB_SurfaceBeam();
+ break;
+ case RT_RAIL_CORE:
+ RB_SurfaceRailCore();
+ break;
+ case RT_RAIL_RINGS:
+ RB_SurfaceRailRings();
+ break;
+ case RT_LIGHTNING:
+ RB_SurfaceLightningBolt();
+ break;
+ default:
+ RB_SurfaceAxis();
+ break;
+ }
+ return;
+}
+
+void RB_SurfaceBad( surfaceType_t *surfType ) {
+ ri.Printf( PRINT_ALL, "Bad surface tesselated.\n" );
+}
+
+#if 0
+
+void RB_SurfaceFlare( srfFlare_t *surf ) {
+ vec3_t left, up;
+ float radius;
+ byte color[4];
+ vec3_t dir;
+ vec3_t origin;
+ float d;
+
+ // calculate the xyz locations for the four corners
+ radius = 30;
+ VectorScale( backEnd.viewParms.or.axis[1], radius, left );
+ VectorScale( backEnd.viewParms.or.axis[2], radius, up );
+ if ( backEnd.viewParms.isMirror ) {
+ VectorSubtract( vec3_origin, left, left );
+ }
+
+ color[0] = color[1] = color[2] = color[3] = 255;
+
+ VectorMA( surf->origin, 3, surf->normal, origin );
+ VectorSubtract( origin, backEnd.viewParms.or.origin, dir );
+ VectorNormalize( dir );
+ VectorMA( origin, r_ignore->value, dir, origin );
+
+ d = -DotProduct( dir, surf->normal );
+ if ( d < 0 ) {
+ return;
+ }
+#if 0
+ color[0] *= d;
+ color[1] *= d;
+ color[2] *= d;
+#endif
+
+ RB_AddQuadStamp( origin, left, up, color );
+}
+
+#else
+
+void RB_SurfaceFlare( srfFlare_t *surf ) {
+#if 0
+ vec3_t left, up;
+ byte color[4];
+
+ color[0] = surf->color[0] * 255;
+ color[1] = surf->color[1] * 255;
+ color[2] = surf->color[2] * 255;
+ color[3] = 255;
+
+ VectorClear( left );
+ VectorClear( up );
+
+ left[0] = r_ignore->value;
+
+ up[1] = r_ignore->value;
+
+ RB_AddQuadStampExt( surf->origin, left, up, color, 0, 0, 1, 1 );
+#endif
+}
+
+#endif
+
+
+
+void RB_SurfaceDisplayList( srfDisplayList_t *surf ) {
+ // all apropriate state must be set in RB_BeginSurface
+ // this isn't implemented yet...
+ qglCallList( surf->listNum );
+}
+
+void RB_SurfaceSkip( void *surf ) {
+}
+
+
+void (*rb_surfaceTable[SF_NUM_SURFACE_TYPES])( void *) = {
+ (void(*)(void*))RB_SurfaceBad, // SF_BAD,
+ (void(*)(void*))RB_SurfaceSkip, // SF_SKIP,
+ (void(*)(void*))RB_SurfaceFace, // SF_FACE,
+ (void(*)(void*))RB_SurfaceGrid, // SF_GRID,
+ (void(*)(void*))RB_SurfaceTriangles, // SF_TRIANGLES,
+ (void(*)(void*))RB_SurfacePolychain, // SF_POLY,
+ (void(*)(void*))RB_SurfaceMesh, // SF_MD3,
+ (void(*)(void*))RB_SurfaceAnim, // SF_MD4,
+ (void(*)(void*))RB_SurfaceFlare, // SF_FLARE,
+ (void(*)(void*))RB_SurfaceEntity, // SF_ENTITY
+ (void(*)(void*))RB_SurfaceDisplayList // SF_DISPLAY_LIST
+};
diff --git a/code/renderer/tr_world.c b/code/renderer/tr_world.c
new file mode 100755
index 0000000..37de6af
--- /dev/null
+++ b/code/renderer/tr_world.c
@@ -0,0 +1,668 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "tr_local.h"
+
+
+
+/*
+=================
+R_CullTriSurf
+
+Returns true if the grid is completely culled away.
+Also sets the clipped hint bit in tess
+=================
+*/
+static qboolean R_CullTriSurf( srfTriangles_t *cv ) {
+ int boxCull;
+
+ boxCull = R_CullLocalBox( cv->bounds );
+
+ if ( boxCull == CULL_OUT ) {
+ return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+=================
+R_CullGrid
+
+Returns true if the grid is completely culled away.
+Also sets the clipped hint bit in tess
+=================
+*/
+static qboolean R_CullGrid( srfGridMesh_t *cv ) {
+ int boxCull;
+ int sphereCull;
+
+ if ( r_nocurves->integer ) {
+ return qtrue;
+ }
+
+ if ( tr.currentEntityNum != ENTITYNUM_WORLD ) {
+ sphereCull = R_CullLocalPointAndRadius( cv->localOrigin, cv->meshRadius );
+ } else {
+ sphereCull = R_CullPointAndRadius( cv->localOrigin, cv->meshRadius );
+ }
+ boxCull = CULL_OUT;
+
+ // check for trivial reject
+ if ( sphereCull == CULL_OUT )
+ {
+ tr.pc.c_sphere_cull_patch_out++;
+ return qtrue;
+ }
+ // check bounding box if necessary
+ else if ( sphereCull == CULL_CLIP )
+ {
+ tr.pc.c_sphere_cull_patch_clip++;
+
+ boxCull = R_CullLocalBox( cv->meshBounds );
+
+ if ( boxCull == CULL_OUT )
+ {
+ tr.pc.c_box_cull_patch_out++;
+ return qtrue;
+ }
+ else if ( boxCull == CULL_IN )
+ {
+ tr.pc.c_box_cull_patch_in++;
+ }
+ else
+ {
+ tr.pc.c_box_cull_patch_clip++;
+ }
+ }
+ else
+ {
+ tr.pc.c_sphere_cull_patch_in++;
+ }
+
+ return qfalse;
+}
+
+
+/*
+================
+R_CullSurface
+
+Tries to back face cull surfaces before they are lighted or
+added to the sorting list.
+
+This will also allow mirrors on both sides of a model without recursion.
+================
+*/
+static qboolean R_CullSurface( surfaceType_t *surface, shader_t *shader ) {
+ srfSurfaceFace_t *sface;
+ float d;
+
+ if ( r_nocull->integer ) {
+ return qfalse;
+ }
+
+ if ( *surface == SF_GRID ) {
+ return R_CullGrid( (srfGridMesh_t *)surface );
+ }
+
+ if ( *surface == SF_TRIANGLES ) {
+ return R_CullTriSurf( (srfTriangles_t *)surface );
+ }
+
+ if ( *surface != SF_FACE ) {
+ return qfalse;
+ }
+
+ if ( shader->cullType == CT_TWO_SIDED ) {
+ return qfalse;
+ }
+
+ // face culling
+ if ( !r_facePlaneCull->integer ) {
+ return qfalse;
+ }
+
+ sface = ( srfSurfaceFace_t * ) surface;
+ d = DotProduct (tr.or.viewOrigin, sface->plane.normal);
+
+ // don't cull exactly on the plane, because there are levels of rounding
+ // through the BSP, ICD, and hardware that may cause pixel gaps if an
+ // epsilon isn't allowed here
+ if ( shader->cullType == CT_FRONT_SIDED ) {
+ if ( d < sface->plane.dist - 8 ) {
+ return qtrue;
+ }
+ } else {
+ if ( d > sface->plane.dist + 8 ) {
+ return qtrue;
+ }
+ }
+
+ return qfalse;
+}
+
+
+static int R_DlightFace( srfSurfaceFace_t *face, int dlightBits ) {
+ float d;
+ int i;
+ dlight_t *dl;
+
+ for ( i = 0 ; i < tr.refdef.num_dlights ; i++ ) {
+ if ( ! ( dlightBits & ( 1 << i ) ) ) {
+ continue;
+ }
+ dl = &tr.refdef.dlights[i];
+ d = DotProduct( dl->origin, face->plane.normal ) - face->plane.dist;
+ if ( d < -dl->radius || d > dl->radius ) {
+ // dlight doesn't reach the plane
+ dlightBits &= ~( 1 << i );
+ }
+ }
+
+ if ( !dlightBits ) {
+ tr.pc.c_dlightSurfacesCulled++;
+ }
+
+ face->dlightBits[ tr.smpFrame ] = dlightBits;
+ return dlightBits;
+}
+
+static int R_DlightGrid( srfGridMesh_t *grid, int dlightBits ) {
+ int i;
+ dlight_t *dl;
+
+ for ( i = 0 ; i < tr.refdef.num_dlights ; i++ ) {
+ if ( ! ( dlightBits & ( 1 << i ) ) ) {
+ continue;
+ }
+ dl = &tr.refdef.dlights[i];
+ if ( dl->origin[0] - dl->radius > grid->meshBounds[1][0]
+ || dl->origin[0] + dl->radius < grid->meshBounds[0][0]
+ || dl->origin[1] - dl->radius > grid->meshBounds[1][1]
+ || dl->origin[1] + dl->radius < grid->meshBounds[0][1]
+ || dl->origin[2] - dl->radius > grid->meshBounds[1][2]
+ || dl->origin[2] + dl->radius < grid->meshBounds[0][2] ) {
+ // dlight doesn't reach the bounds
+ dlightBits &= ~( 1 << i );
+ }
+ }
+
+ if ( !dlightBits ) {
+ tr.pc.c_dlightSurfacesCulled++;
+ }
+
+ grid->dlightBits[ tr.smpFrame ] = dlightBits;
+ return dlightBits;
+}
+
+
+static int R_DlightTrisurf( srfTriangles_t *surf, int dlightBits ) {
+ // FIXME: more dlight culling to trisurfs...
+ surf->dlightBits[ tr.smpFrame ] = dlightBits;
+ return dlightBits;
+#if 0
+ int i;
+ dlight_t *dl;
+
+ for ( i = 0 ; i < tr.refdef.num_dlights ; i++ ) {
+ if ( ! ( dlightBits & ( 1 << i ) ) ) {
+ continue;
+ }
+ dl = &tr.refdef.dlights[i];
+ if ( dl->origin[0] - dl->radius > grid->meshBounds[1][0]
+ || dl->origin[0] + dl->radius < grid->meshBounds[0][0]
+ || dl->origin[1] - dl->radius > grid->meshBounds[1][1]
+ || dl->origin[1] + dl->radius < grid->meshBounds[0][1]
+ || dl->origin[2] - dl->radius > grid->meshBounds[1][2]
+ || dl->origin[2] + dl->radius < grid->meshBounds[0][2] ) {
+ // dlight doesn't reach the bounds
+ dlightBits &= ~( 1 << i );
+ }
+ }
+
+ if ( !dlightBits ) {
+ tr.pc.c_dlightSurfacesCulled++;
+ }
+
+ grid->dlightBits[ tr.smpFrame ] = dlightBits;
+ return dlightBits;
+#endif
+}
+
+/*
+====================
+R_DlightSurface
+
+The given surface is going to be drawn, and it touches a leaf
+that is touched by one or more dlights, so try to throw out
+more dlights if possible.
+====================
+*/
+static int R_DlightSurface( msurface_t *surf, int dlightBits ) {
+ if ( *surf->data == SF_FACE ) {
+ dlightBits = R_DlightFace( (srfSurfaceFace_t *)surf->data, dlightBits );
+ } else if ( *surf->data == SF_GRID ) {
+ dlightBits = R_DlightGrid( (srfGridMesh_t *)surf->data, dlightBits );
+ } else if ( *surf->data == SF_TRIANGLES ) {
+ dlightBits = R_DlightTrisurf( (srfTriangles_t *)surf->data, dlightBits );
+ } else {
+ dlightBits = 0;
+ }
+
+ if ( dlightBits ) {
+ tr.pc.c_dlightSurfaces++;
+ }
+
+ return dlightBits;
+}
+
+
+
+/*
+======================
+R_AddWorldSurface
+======================
+*/
+static void R_AddWorldSurface( msurface_t *surf, int dlightBits ) {
+ if ( surf->viewCount == tr.viewCount ) {
+ return; // already in this view
+ }
+
+ surf->viewCount = tr.viewCount;
+ // FIXME: bmodel fog?
+
+ // try to cull before dlighting or adding
+ if ( R_CullSurface( surf->data, surf->shader ) ) {
+ return;
+ }
+
+ // check for dlighting
+ if ( dlightBits ) {
+ dlightBits = R_DlightSurface( surf, dlightBits );
+ dlightBits = ( dlightBits != 0 );
+ }
+
+ R_AddDrawSurf( surf->data, surf->shader, surf->fogIndex, dlightBits );
+}
+
+/*
+=============================================================
+
+ BRUSH MODELS
+
+=============================================================
+*/
+
+/*
+=================
+R_AddBrushModelSurfaces
+=================
+*/
+void R_AddBrushModelSurfaces ( trRefEntity_t *ent ) {
+ bmodel_t *bmodel;
+ int clip;
+ model_t *pModel;
+ int i;
+
+ pModel = R_GetModelByHandle( ent->e.hModel );
+
+ bmodel = pModel->bmodel;
+
+ clip = R_CullLocalBox( bmodel->bounds );
+ if ( clip == CULL_OUT ) {
+ return;
+ }
+
+ R_DlightBmodel( bmodel );
+
+ for ( i = 0 ; i < bmodel->numSurfaces ; i++ ) {
+ R_AddWorldSurface( bmodel->firstSurface + i, tr.currentEntity->needDlights );
+ }
+}
+
+
+/*
+=============================================================
+
+ WORLD MODEL
+
+=============================================================
+*/
+
+
+/*
+================
+R_RecursiveWorldNode
+================
+*/
+static void R_RecursiveWorldNode( mnode_t *node, int planeBits, int dlightBits ) {
+
+ do {
+ int newDlights[2];
+
+ // if the node wasn't marked as potentially visible, exit
+ if (node->visframe != tr.visCount) {
+ return;
+ }
+
+ // if the bounding volume is outside the frustum, nothing
+ // inside can be visible OPTIMIZE: don't do this all the way to leafs?
+
+ if ( !r_nocull->integer ) {
+ int r;
+
+ if ( planeBits & 1 ) {
+ r = BoxOnPlaneSide(node->mins, node->maxs, &tr.viewParms.frustum[0]);
+ if (r == 2) {
+ return; // culled
+ }
+ if ( r == 1 ) {
+ planeBits &= ~1; // all descendants will also be in front
+ }
+ }
+
+ if ( planeBits & 2 ) {
+ r = BoxOnPlaneSide(node->mins, node->maxs, &tr.viewParms.frustum[1]);
+ if (r == 2) {
+ return; // culled
+ }
+ if ( r == 1 ) {
+ planeBits &= ~2; // all descendants will also be in front
+ }
+ }
+
+ if ( planeBits & 4 ) {
+ r = BoxOnPlaneSide(node->mins, node->maxs, &tr.viewParms.frustum[2]);
+ if (r == 2) {
+ return; // culled
+ }
+ if ( r == 1 ) {
+ planeBits &= ~4; // all descendants will also be in front
+ }
+ }
+
+ if ( planeBits & 8 ) {
+ r = BoxOnPlaneSide(node->mins, node->maxs, &tr.viewParms.frustum[3]);
+ if (r == 2) {
+ return; // culled
+ }
+ if ( r == 1 ) {
+ planeBits &= ~8; // all descendants will also be in front
+ }
+ }
+
+ }
+
+ if ( node->contents != -1 ) {
+ break;
+ }
+
+ // node is just a decision point, so go down both sides
+ // since we don't care about sort orders, just go positive to negative
+
+ // determine which dlights are needed
+ newDlights[0] = 0;
+ newDlights[1] = 0;
+ if ( dlightBits ) {
+ int i;
+
+ for ( i = 0 ; i < tr.refdef.num_dlights ; i++ ) {
+ dlight_t *dl;
+ float dist;
+
+ if ( dlightBits & ( 1 << i ) ) {
+ dl = &tr.refdef.dlights[i];
+ dist = DotProduct( dl->origin, node->plane->normal ) - node->plane->dist;
+
+ if ( dist > -dl->radius ) {
+ newDlights[0] |= ( 1 << i );
+ }
+ if ( dist < dl->radius ) {
+ newDlights[1] |= ( 1 << i );
+ }
+ }
+ }
+ }
+
+ // recurse down the children, front side first
+ R_RecursiveWorldNode (node->children[0], planeBits, newDlights[0] );
+
+ // tail recurse
+ node = node->children[1];
+ dlightBits = newDlights[1];
+ } while ( 1 );
+
+ {
+ // leaf node, so add mark surfaces
+ int c;
+ msurface_t *surf, **mark;
+
+ tr.pc.c_leafs++;
+
+ // add to z buffer bounds
+ if ( node->mins[0] < tr.viewParms.visBounds[0][0] ) {
+ tr.viewParms.visBounds[0][0] = node->mins[0];
+ }
+ if ( node->mins[1] < tr.viewParms.visBounds[0][1] ) {
+ tr.viewParms.visBounds[0][1] = node->mins[1];
+ }
+ if ( node->mins[2] < tr.viewParms.visBounds[0][2] ) {
+ tr.viewParms.visBounds[0][2] = node->mins[2];
+ }
+
+ if ( node->maxs[0] > tr.viewParms.visBounds[1][0] ) {
+ tr.viewParms.visBounds[1][0] = node->maxs[0];
+ }
+ if ( node->maxs[1] > tr.viewParms.visBounds[1][1] ) {
+ tr.viewParms.visBounds[1][1] = node->maxs[1];
+ }
+ if ( node->maxs[2] > tr.viewParms.visBounds[1][2] ) {
+ tr.viewParms.visBounds[1][2] = node->maxs[2];
+ }
+
+ // add the individual surfaces
+ mark = node->firstmarksurface;
+ c = node->nummarksurfaces;
+ while (c--) {
+ // the surface may have already been added if it
+ // spans multiple leafs
+ surf = *mark;
+ R_AddWorldSurface( surf, dlightBits );
+ mark++;
+ }
+ }
+
+}
+
+
+/*
+===============
+R_PointInLeaf
+===============
+*/
+static mnode_t *R_PointInLeaf( const vec3_t p ) {
+ mnode_t *node;
+ float d;
+ cplane_t *plane;
+
+ if ( !tr.world ) {
+ ri.Error (ERR_DROP, "R_PointInLeaf: bad model");
+ }
+
+ node = tr.world->nodes;
+ while( 1 ) {
+ if (node->contents != -1) {
+ break;
+ }
+ plane = node->plane;
+ d = DotProduct (p,plane->normal) - plane->dist;
+ if (d > 0) {
+ node = node->children[0];
+ } else {
+ node = node->children[1];
+ }
+ }
+
+ return node;
+}
+
+/*
+==============
+R_ClusterPVS
+==============
+*/
+static const byte *R_ClusterPVS (int cluster) {
+ if (!tr.world || !tr.world->vis || cluster < 0 || cluster >= tr.world->numClusters ) {
+ return tr.world->novis;
+ }
+
+ return tr.world->vis + cluster * tr.world->clusterBytes;
+}
+
+/*
+=================
+R_inPVS
+=================
+*/
+qboolean R_inPVS( const vec3_t p1, const vec3_t p2 ) {
+ mnode_t *leaf;
+ byte *vis;
+
+ leaf = R_PointInLeaf( p1 );
+ vis = CM_ClusterPVS( leaf->cluster );
+ leaf = R_PointInLeaf( p2 );
+
+ if ( !(vis[leaf->cluster>>3] & (1<<(leaf->cluster&7))) ) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+/*
+===============
+R_MarkLeaves
+
+Mark the leaves and nodes that are in the PVS for the current
+cluster
+===============
+*/
+static void R_MarkLeaves (void) {
+ const byte *vis;
+ mnode_t *leaf, *parent;
+ int i;
+ int cluster;
+
+ // lockpvs lets designers walk around to determine the
+ // extent of the current pvs
+ if ( r_lockpvs->integer ) {
+ return;
+ }
+
+ // current viewcluster
+ leaf = R_PointInLeaf( tr.viewParms.pvsOrigin );
+ cluster = leaf->cluster;
+
+ // if the cluster is the same and the area visibility matrix
+ // hasn't changed, we don't need to mark everything again
+
+ // if r_showcluster was just turned on, remark everything
+ if ( tr.viewCluster == cluster && !tr.refdef.areamaskModified
+ && !r_showcluster->modified ) {
+ return;
+ }
+
+ if ( r_showcluster->modified || r_showcluster->integer ) {
+ r_showcluster->modified = qfalse;
+ if ( r_showcluster->integer ) {
+ ri.Printf( PRINT_ALL, "cluster:%i area:%i\n", cluster, leaf->area );
+ }
+ }
+
+ tr.visCount++;
+ tr.viewCluster = cluster;
+
+ if ( r_novis->integer || tr.viewCluster == -1 ) {
+ for (i=0 ; i<tr.world->numnodes ; i++) {
+ if (tr.world->nodes[i].contents != CONTENTS_SOLID) {
+ tr.world->nodes[i].visframe = tr.visCount;
+ }
+ }
+ return;
+ }
+
+ vis = R_ClusterPVS (tr.viewCluster);
+
+ for (i=0,leaf=tr.world->nodes ; i<tr.world->numnodes ; i++, leaf++) {
+ cluster = leaf->cluster;
+ if ( cluster < 0 || cluster >= tr.world->numClusters ) {
+ continue;
+ }
+
+ // check general pvs
+ if ( !(vis[cluster>>3] & (1<<(cluster&7))) ) {
+ continue;
+ }
+
+ // check for door connection
+ if ( (tr.refdef.areamask[leaf->area>>3] & (1<<(leaf->area&7)) ) ) {
+ continue; // not visible
+ }
+
+ parent = leaf;
+ do {
+ if (parent->visframe == tr.visCount)
+ break;
+ parent->visframe = tr.visCount;
+ parent = parent->parent;
+ } while (parent);
+ }
+}
+
+
+/*
+=============
+R_AddWorldSurfaces
+=============
+*/
+void R_AddWorldSurfaces (void) {
+ if ( !r_drawworld->integer ) {
+ return;
+ }
+
+ if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) {
+ return;
+ }
+
+ tr.currentEntityNum = ENTITYNUM_WORLD;
+ tr.shiftedEntityNum = tr.currentEntityNum << QSORT_ENTITYNUM_SHIFT;
+
+ // determine which leaves are in the PVS / areamask
+ R_MarkLeaves ();
+
+ // clear out the visible min/max
+ ClearBounds( tr.viewParms.visBounds[0], tr.viewParms.visBounds[1] );
+
+ // perform frustum culling and add all the potentially visible surfaces
+ if ( tr.refdef.num_dlights > 32 ) {
+ tr.refdef.num_dlights = 32 ;
+ }
+ R_RecursiveWorldNode( tr.world->nodes, 15, ( 1 << tr.refdef.num_dlights ) - 1 );
+}
diff --git a/code/run.bat b/code/run.bat
new file mode 100755
index 0000000..60563d2
--- /dev/null
+++ b/code/run.bat
@@ -0,0 +1 @@
+debug\quake3 +set fs_basepath \quake3 +set fs_cdpath g:\quake3 + %1 %2 %3 %4 %5 %6 %7 %8 %9
diff --git a/code/runrelease.bat b/code/runrelease.bat
new file mode 100755
index 0000000..355393f
--- /dev/null
+++ b/code/runrelease.bat
@@ -0,0 +1 @@
+release\quake3 +set fs_basepath \quake3 +set fs_cdpath g:\quake3 + %1 %2 %3 %4 %5 %6 %7 %8 %9
diff --git a/code/server/server.h b/code/server/server.h
new file mode 100755
index 0000000..c32b2dc
--- /dev/null
+++ b/code/server/server.h
@@ -0,0 +1,404 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// server.h
+
+#include "../game/q_shared.h"
+#include "../qcommon/qcommon.h"
+#include "../game/g_public.h"
+#include "../game/bg_public.h"
+
+//=============================================================================
+
+#define PERS_SCORE 0 // !!! MUST NOT CHANGE, SERVER AND
+ // GAME BOTH REFERENCE !!!
+
+#define MAX_ENT_CLUSTERS 16
+
+typedef struct svEntity_s {
+ struct worldSector_s *worldSector;
+ struct svEntity_s *nextEntityInWorldSector;
+
+ entityState_t baseline; // for delta compression of initial sighting
+ int numClusters; // if -1, use headnode instead
+ int clusternums[MAX_ENT_CLUSTERS];
+ int lastCluster; // if all the clusters don't fit in clusternums
+ int areanum, areanum2;
+ int snapshotCounter; // used to prevent double adding from portal views
+} svEntity_t;
+
+typedef enum {
+ SS_DEAD, // no map loaded
+ SS_LOADING, // spawning level entities
+ SS_GAME // actively running
+} serverState_t;
+
+typedef struct {
+ serverState_t state;
+ qboolean restarting; // if true, send configstring changes during SS_LOADING
+ int serverId; // changes each server start
+ int restartedServerId; // serverId before a map_restart
+ int checksumFeed; // the feed key that we use to compute the pure checksum strings
+ // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=475
+ // the serverId associated with the current checksumFeed (always <= serverId)
+ int checksumFeedServerId;
+ int snapshotCounter; // incremented for each snapshot built
+ int timeResidual; // <= 1000 / sv_frame->value
+ int nextFrameTime; // when time > nextFrameTime, process world
+ struct cmodel_s *models[MAX_MODELS];
+ char *configstrings[MAX_CONFIGSTRINGS];
+ svEntity_t svEntities[MAX_GENTITIES];
+
+ char *entityParsePoint; // used during game VM init
+
+ // the game virtual machine will update these on init and changes
+ sharedEntity_t *gentities;
+ int gentitySize;
+ int num_entities; // current number, <= MAX_GENTITIES
+
+ playerState_t *gameClients;
+ int gameClientSize; // will be > sizeof(playerState_t) due to game private data
+
+ int restartTime;
+} server_t;
+
+
+
+
+
+typedef struct {
+ int areabytes;
+ byte areabits[MAX_MAP_AREA_BYTES]; // portalarea visibility bits
+ playerState_t ps;
+ int num_entities;
+ int first_entity; // into the circular sv_packet_entities[]
+ // the entities MUST be in increasing state number
+ // order, otherwise the delta compression will fail
+ int messageSent; // time the message was transmitted
+ int messageAcked; // time the message was acked
+ int messageSize; // used to rate drop packets
+} clientSnapshot_t;
+
+typedef enum {
+ CS_FREE, // can be reused for a new connection
+ CS_ZOMBIE, // client has been disconnected, but don't reuse
+ // connection for a couple seconds
+ CS_CONNECTED, // has been assigned to a client_t, but no gamestate yet
+ CS_PRIMED, // gamestate has been sent, but client hasn't sent a usercmd
+ CS_ACTIVE // client is fully in game
+} clientState_t;
+
+typedef struct netchan_buffer_s {
+ msg_t msg;
+ byte msgBuffer[MAX_MSGLEN];
+ struct netchan_buffer_s *next;
+} netchan_buffer_t;
+
+typedef struct client_s {
+ clientState_t state;
+ char userinfo[MAX_INFO_STRING]; // name, etc
+
+ char reliableCommands[MAX_RELIABLE_COMMANDS][MAX_STRING_CHARS];
+ int reliableSequence; // last added reliable message, not necesarily sent or acknowledged yet
+ int reliableAcknowledge; // last acknowledged reliable message
+ int reliableSent; // last sent reliable message, not necesarily acknowledged yet
+ int messageAcknowledge;
+
+ int gamestateMessageNum; // netchan->outgoingSequence of gamestate
+ int challenge;
+
+ usercmd_t lastUsercmd;
+ int lastMessageNum; // for delta compression
+ int lastClientCommand; // reliable client message sequence
+ char lastClientCommandString[MAX_STRING_CHARS];
+ sharedEntity_t *gentity; // SV_GentityNum(clientnum)
+ char name[MAX_NAME_LENGTH]; // extracted from userinfo, high bits masked
+
+ // downloading
+ char downloadName[MAX_QPATH]; // if not empty string, we are downloading
+ fileHandle_t download; // file being downloaded
+ int downloadSize; // total bytes (can't use EOF because of paks)
+ int downloadCount; // bytes sent
+ int downloadClientBlock; // last block we sent to the client, awaiting ack
+ int downloadCurrentBlock; // current block number
+ int downloadXmitBlock; // last block we xmited
+ unsigned char *downloadBlocks[MAX_DOWNLOAD_WINDOW]; // the buffers for the download blocks
+ int downloadBlockSize[MAX_DOWNLOAD_WINDOW];
+ qboolean downloadEOF; // We have sent the EOF block
+ int downloadSendTime; // time we last got an ack from the client
+
+ int deltaMessage; // frame last client usercmd message
+ int nextReliableTime; // svs.time when another reliable command will be allowed
+ int lastPacketTime; // svs.time when packet was last received
+ int lastConnectTime; // svs.time when connection started
+ int nextSnapshotTime; // send another snapshot when svs.time >= nextSnapshotTime
+ qboolean rateDelayed; // true if nextSnapshotTime was set based on rate instead of snapshotMsec
+ int timeoutCount; // must timeout a few frames in a row so debugging doesn't break
+ clientSnapshot_t frames[PACKET_BACKUP]; // updates can be delta'd from here
+ int ping;
+ int rate; // bytes / second
+ int snapshotMsec; // requests a snapshot every snapshotMsec unless rate choked
+ int pureAuthentic;
+ qboolean gotCP; // TTimo - additional flag to distinguish between a bad pure checksum, and no cp command at all
+ netchan_t netchan;
+ // TTimo
+ // queuing outgoing fragmented messages to send them properly, without udp packet bursts
+ // in case large fragmented messages are stacking up
+ // buffer them into this queue, and hand them out to netchan as needed
+ netchan_buffer_t *netchan_start_queue;
+ netchan_buffer_t **netchan_end_queue;
+} client_t;
+
+//=============================================================================
+
+
+// MAX_CHALLENGES is made large to prevent a denial
+// of service attack that could cycle all of them
+// out before legitimate users connected
+#define MAX_CHALLENGES 1024
+
+#define AUTHORIZE_TIMEOUT 5000
+
+typedef struct {
+ netadr_t adr;
+ int challenge;
+ int time; // time the last packet was sent to the autherize server
+ int pingTime; // time the challenge response was sent to client
+ int firstTime; // time the adr was first used, for authorize timeout checks
+ qboolean connected;
+} challenge_t;
+
+
+#define MAX_MASTERS 8 // max recipients for heartbeat packets
+
+
+// this structure will be cleared only when the game dll changes
+typedef struct {
+ qboolean initialized; // sv_init has completed
+
+ int time; // will be strictly increasing across level changes
+
+ int snapFlagServerBit; // ^= SNAPFLAG_SERVERCOUNT every SV_SpawnServer()
+
+ client_t *clients; // [sv_maxclients->integer];
+ int numSnapshotEntities; // sv_maxclients->integer*PACKET_BACKUP*MAX_PACKET_ENTITIES
+ int nextSnapshotEntities; // next snapshotEntities to use
+ entityState_t *snapshotEntities; // [numSnapshotEntities]
+ int nextHeartbeatTime;
+ challenge_t challenges[MAX_CHALLENGES]; // to prevent invalid IPs from connecting
+ netadr_t redirectAddress; // for rcon return messages
+
+ netadr_t authorizeAddress; // for rcon return messages
+} serverStatic_t;
+
+//=============================================================================
+
+extern serverStatic_t svs; // persistant server info across maps
+extern server_t sv; // cleared each map
+extern vm_t *gvm; // game virtual machine
+
+#define MAX_MASTER_SERVERS 5
+
+extern cvar_t *sv_fps;
+extern cvar_t *sv_timeout;
+extern cvar_t *sv_zombietime;
+extern cvar_t *sv_rconPassword;
+extern cvar_t *sv_privatePassword;
+extern cvar_t *sv_allowDownload;
+extern cvar_t *sv_maxclients;
+
+extern cvar_t *sv_privateClients;
+extern cvar_t *sv_hostname;
+extern cvar_t *sv_master[MAX_MASTER_SERVERS];
+extern cvar_t *sv_reconnectlimit;
+extern cvar_t *sv_showloss;
+extern cvar_t *sv_padPackets;
+extern cvar_t *sv_killserver;
+extern cvar_t *sv_mapname;
+extern cvar_t *sv_mapChecksum;
+extern cvar_t *sv_serverid;
+extern cvar_t *sv_maxRate;
+extern cvar_t *sv_minPing;
+extern cvar_t *sv_maxPing;
+extern cvar_t *sv_gametype;
+extern cvar_t *sv_pure;
+extern cvar_t *sv_floodProtect;
+extern cvar_t *sv_lanForceRate;
+extern cvar_t *sv_strictAuth;
+
+//===========================================================
+
+//
+// sv_main.c
+//
+void SV_FinalMessage (char *message);
+void QDECL SV_SendServerCommand( client_t *cl, const char *fmt, ...);
+
+
+void SV_AddOperatorCommands (void);
+void SV_RemoveOperatorCommands (void);
+
+
+void SV_MasterHeartbeat (void);
+void SV_MasterShutdown (void);
+
+
+
+
+//
+// sv_init.c
+//
+void SV_SetConfigstring( int index, const char *val );
+void SV_GetConfigstring( int index, char *buffer, int bufferSize );
+
+void SV_SetUserinfo( int index, const char *val );
+void SV_GetUserinfo( int index, char *buffer, int bufferSize );
+
+void SV_ChangeMaxClients( void );
+void SV_SpawnServer( char *server, qboolean killBots );
+
+
+
+//
+// sv_client.c
+//
+void SV_GetChallenge( netadr_t from );
+
+void SV_DirectConnect( netadr_t from );
+
+void SV_AuthorizeIpPacket( netadr_t from );
+
+void SV_ExecuteClientMessage( client_t *cl, msg_t *msg );
+void SV_UserinfoChanged( client_t *cl );
+
+void SV_ClientEnterWorld( client_t *client, usercmd_t *cmd );
+void SV_DropClient( client_t *drop, const char *reason );
+
+void SV_ExecuteClientCommand( client_t *cl, const char *s, qboolean clientOK );
+void SV_ClientThink (client_t *cl, usercmd_t *cmd);
+
+void SV_WriteDownloadToClient( client_t *cl , msg_t *msg );
+
+//
+// sv_ccmds.c
+//
+void SV_Heartbeat_f( void );
+
+//
+// sv_snapshot.c
+//
+void SV_AddServerCommand( client_t *client, const char *cmd );
+void SV_UpdateServerCommandsToClient( client_t *client, msg_t *msg );
+void SV_WriteFrameToClient (client_t *client, msg_t *msg);
+void SV_SendMessageToClient( msg_t *msg, client_t *client );
+void SV_SendClientMessages( void );
+void SV_SendClientSnapshot( client_t *client );
+
+//
+// sv_game.c
+//
+int SV_NumForGentity( sharedEntity_t *ent );
+sharedEntity_t *SV_GentityNum( int num );
+playerState_t *SV_GameClientNum( int num );
+svEntity_t *SV_SvEntityForGentity( sharedEntity_t *gEnt );
+sharedEntity_t *SV_GEntityForSvEntity( svEntity_t *svEnt );
+void SV_InitGameProgs ( void );
+void SV_ShutdownGameProgs ( void );
+void SV_RestartGameProgs( void );
+qboolean SV_inPVS (const vec3_t p1, const vec3_t p2);
+
+//
+// sv_bot.c
+//
+void SV_BotFrame( int time );
+int SV_BotAllocateClient(void);
+void SV_BotFreeClient( int clientNum );
+
+void SV_BotInitCvars(void);
+int SV_BotLibSetup( void );
+int SV_BotLibShutdown( void );
+int SV_BotGetSnapshotEntity( int client, int ent );
+int SV_BotGetConsoleMessage( int client, char *buf, int size );
+
+int BotImport_DebugPolygonCreate(int color, int numPoints, vec3_t *points);
+void BotImport_DebugPolygonDelete(int id);
+
+//============================================================
+//
+// high level object sorting to reduce interaction tests
+//
+
+void SV_ClearWorld (void);
+// called after the world model has been loaded, before linking any entities
+
+void SV_UnlinkEntity( sharedEntity_t *ent );
+// call before removing an entity, and before trying to move one,
+// so it doesn't clip against itself
+
+void SV_LinkEntity( sharedEntity_t *ent );
+// Needs to be called any time an entity changes origin, mins, maxs,
+// or solid. Automatically unlinks if needed.
+// sets ent->v.absmin and ent->v.absmax
+// sets ent->leafnums[] for pvs determination even if the entity
+// is not solid
+
+
+clipHandle_t SV_ClipHandleForEntity( const sharedEntity_t *ent );
+
+
+void SV_SectorList_f( void );
+
+
+int SV_AreaEntities( const vec3_t mins, const vec3_t maxs, int *entityList, int maxcount );
+// fills in a table of entity numbers with entities that have bounding boxes
+// that intersect the given area. It is possible for a non-axial bmodel
+// to be returned that doesn't actually intersect the area on an exact
+// test.
+// returns the number of pointers filled in
+// The world entity is never returned in this list.
+
+
+int SV_PointContents( const vec3_t p, int passEntityNum );
+// returns the CONTENTS_* value from the world and all entities at the given point.
+
+
+void SV_Trace( trace_t *results, const vec3_t start, vec3_t mins, vec3_t maxs, const vec3_t end, int passEntityNum, int contentmask, int capsule );
+// mins and maxs are relative
+
+// if the entire move stays in a solid volume, trace.allsolid will be set,
+// trace.startsolid will be set, and trace.fraction will be 0
+
+// if the starting point is in a solid, it will be allowed to move out
+// to an open area
+
+// passEntityNum is explicitly excluded from clipping checks (normally ENTITYNUM_NONE)
+
+
+void SV_ClipToEntity( trace_t *trace, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int entityNum, int contentmask, int capsule );
+// clip to a specific entity
+
+//
+// sv_net_chan.c
+//
+void SV_Netchan_Transmit( client_t *client, msg_t *msg);
+void SV_Netchan_TransmitNextFragment( client_t *client );
+qboolean SV_Netchan_Process( client_t *client, msg_t *msg );
+
diff --git a/code/server/sv_bot.c b/code/server/sv_bot.c
new file mode 100755
index 0000000..ddb9673
--- /dev/null
+++ b/code/server/sv_bot.c
@@ -0,0 +1,635 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// sv_bot.c
+
+#include "server.h"
+#include "../game/botlib.h"
+
+typedef struct bot_debugpoly_s
+{
+ int inuse;
+ int color;
+ int numPoints;
+ vec3_t points[128];
+} bot_debugpoly_t;
+
+static bot_debugpoly_t *debugpolygons;
+int bot_maxdebugpolys;
+
+extern botlib_export_t *botlib_export;
+int bot_enable;
+
+
+/*
+==================
+SV_BotAllocateClient
+==================
+*/
+int SV_BotAllocateClient(void) {
+ int i;
+ client_t *cl;
+
+ // find a client slot
+ for ( i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++ ) {
+ if ( cl->state == CS_FREE ) {
+ break;
+ }
+ }
+
+ if ( i == sv_maxclients->integer ) {
+ return -1;
+ }
+
+ cl->gentity = SV_GentityNum( i );
+ cl->gentity->s.number = i;
+ cl->state = CS_ACTIVE;
+ cl->lastPacketTime = svs.time;
+ cl->netchan.remoteAddress.type = NA_BOT;
+ cl->rate = 16384;
+
+ return i;
+}
+
+/*
+==================
+SV_BotFreeClient
+==================
+*/
+void SV_BotFreeClient( int clientNum ) {
+ client_t *cl;
+
+ if ( clientNum < 0 || clientNum >= sv_maxclients->integer ) {
+ Com_Error( ERR_DROP, "SV_BotFreeClient: bad clientNum: %i", clientNum );
+ }
+ cl = &svs.clients[clientNum];
+ cl->state = CS_FREE;
+ cl->name[0] = 0;
+ if ( cl->gentity ) {
+ cl->gentity->r.svFlags &= ~SVF_BOT;
+ }
+}
+
+/*
+==================
+BotDrawDebugPolygons
+==================
+*/
+void BotDrawDebugPolygons(void (*drawPoly)(int color, int numPoints, float *points), int value) {
+ static cvar_t *bot_debug, *bot_groundonly, *bot_reachability, *bot_highlightarea;
+ bot_debugpoly_t *poly;
+ int i, parm0;
+
+ if (!debugpolygons)
+ return;
+ //bot debugging
+ if (!bot_debug) bot_debug = Cvar_Get("bot_debug", "0", 0);
+ //
+ if (bot_enable && bot_debug->integer) {
+ //show reachabilities
+ if (!bot_reachability) bot_reachability = Cvar_Get("bot_reachability", "0", 0);
+ //show ground faces only
+ if (!bot_groundonly) bot_groundonly = Cvar_Get("bot_groundonly", "1", 0);
+ //get the hightlight area
+ if (!bot_highlightarea) bot_highlightarea = Cvar_Get("bot_highlightarea", "0", 0);
+ //
+ parm0 = 0;
+ if (svs.clients[0].lastUsercmd.buttons & BUTTON_ATTACK) parm0 |= 1;
+ if (bot_reachability->integer) parm0 |= 2;
+ if (bot_groundonly->integer) parm0 |= 4;
+ botlib_export->BotLibVarSet("bot_highlightarea", bot_highlightarea->string);
+ botlib_export->Test(parm0, NULL, svs.clients[0].gentity->r.currentOrigin,
+ svs.clients[0].gentity->r.currentAngles);
+ } //end if
+ //draw all debug polys
+ for (i = 0; i < bot_maxdebugpolys; i++) {
+ poly = &debugpolygons[i];
+ if (!poly->inuse) continue;
+ drawPoly(poly->color, poly->numPoints, (float *) poly->points);
+ //Com_Printf("poly %i, numpoints = %d\n", i, poly->numPoints);
+ }
+}
+
+/*
+==================
+BotImport_Print
+==================
+*/
+void QDECL BotImport_Print(int type, char *fmt, ...)
+{
+ char str[2048];
+ va_list ap;
+
+ va_start(ap, fmt);
+ vsprintf(str, fmt, ap);
+ va_end(ap);
+
+ switch(type) {
+ case PRT_MESSAGE: {
+ Com_Printf("%s", str);
+ break;
+ }
+ case PRT_WARNING: {
+ Com_Printf(S_COLOR_YELLOW "Warning: %s", str);
+ break;
+ }
+ case PRT_ERROR: {
+ Com_Printf(S_COLOR_RED "Error: %s", str);
+ break;
+ }
+ case PRT_FATAL: {
+ Com_Printf(S_COLOR_RED "Fatal: %s", str);
+ break;
+ }
+ case PRT_EXIT: {
+ Com_Error(ERR_DROP, S_COLOR_RED "Exit: %s", str);
+ break;
+ }
+ default: {
+ Com_Printf("unknown print type\n");
+ break;
+ }
+ }
+}
+
+/*
+==================
+BotImport_Trace
+==================
+*/
+void BotImport_Trace(bsp_trace_t *bsptrace, vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int passent, int contentmask) {
+ trace_t trace;
+
+ SV_Trace(&trace, start, mins, maxs, end, passent, contentmask, qfalse);
+ //copy the trace information
+ bsptrace->allsolid = trace.allsolid;
+ bsptrace->startsolid = trace.startsolid;
+ bsptrace->fraction = trace.fraction;
+ VectorCopy(trace.endpos, bsptrace->endpos);
+ bsptrace->plane.dist = trace.plane.dist;
+ VectorCopy(trace.plane.normal, bsptrace->plane.normal);
+ bsptrace->plane.signbits = trace.plane.signbits;
+ bsptrace->plane.type = trace.plane.type;
+ bsptrace->surface.value = trace.surfaceFlags;
+ bsptrace->ent = trace.entityNum;
+ bsptrace->exp_dist = 0;
+ bsptrace->sidenum = 0;
+ bsptrace->contents = 0;
+}
+
+/*
+==================
+BotImport_EntityTrace
+==================
+*/
+void BotImport_EntityTrace(bsp_trace_t *bsptrace, vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int entnum, int contentmask) {
+ trace_t trace;
+
+ SV_ClipToEntity(&trace, start, mins, maxs, end, entnum, contentmask, qfalse);
+ //copy the trace information
+ bsptrace->allsolid = trace.allsolid;
+ bsptrace->startsolid = trace.startsolid;
+ bsptrace->fraction = trace.fraction;
+ VectorCopy(trace.endpos, bsptrace->endpos);
+ bsptrace->plane.dist = trace.plane.dist;
+ VectorCopy(trace.plane.normal, bsptrace->plane.normal);
+ bsptrace->plane.signbits = trace.plane.signbits;
+ bsptrace->plane.type = trace.plane.type;
+ bsptrace->surface.value = trace.surfaceFlags;
+ bsptrace->ent = trace.entityNum;
+ bsptrace->exp_dist = 0;
+ bsptrace->sidenum = 0;
+ bsptrace->contents = 0;
+}
+
+
+/*
+==================
+BotImport_PointContents
+==================
+*/
+int BotImport_PointContents(vec3_t point) {
+ return SV_PointContents(point, -1);
+}
+
+/*
+==================
+BotImport_inPVS
+==================
+*/
+int BotImport_inPVS(vec3_t p1, vec3_t p2) {
+ return SV_inPVS (p1, p2);
+}
+
+/*
+==================
+BotImport_BSPEntityData
+==================
+*/
+char *BotImport_BSPEntityData(void) {
+ return CM_EntityString();
+}
+
+/*
+==================
+BotImport_BSPModelMinsMaxsOrigin
+==================
+*/
+void BotImport_BSPModelMinsMaxsOrigin(int modelnum, vec3_t angles, vec3_t outmins, vec3_t outmaxs, vec3_t origin) {
+ clipHandle_t h;
+ vec3_t mins, maxs;
+ float max;
+ int i;
+
+ h = CM_InlineModel(modelnum);
+ CM_ModelBounds(h, mins, maxs);
+ //if the model is rotated
+ if ((angles[0] || angles[1] || angles[2])) {
+ // expand for rotation
+
+ max = RadiusFromBounds(mins, maxs);
+ for (i = 0; i < 3; i++) {
+ mins[i] = -max;
+ maxs[i] = max;
+ }
+ }
+ if (outmins) VectorCopy(mins, outmins);
+ if (outmaxs) VectorCopy(maxs, outmaxs);
+ if (origin) VectorClear(origin);
+}
+
+/*
+==================
+BotImport_GetMemory
+==================
+*/
+void *BotImport_GetMemory(int size) {
+ void *ptr;
+
+ ptr = Z_TagMalloc( size, TAG_BOTLIB );
+ return ptr;
+}
+
+/*
+==================
+BotImport_FreeMemory
+==================
+*/
+void BotImport_FreeMemory(void *ptr) {
+ Z_Free(ptr);
+}
+
+/*
+=================
+BotImport_HunkAlloc
+=================
+*/
+void *BotImport_HunkAlloc( int size ) {
+ if( Hunk_CheckMark() ) {
+ Com_Error( ERR_DROP, "SV_Bot_HunkAlloc: Alloc with marks already set\n" );
+ }
+ return Hunk_Alloc( size, h_high );
+}
+
+/*
+==================
+BotImport_DebugPolygonCreate
+==================
+*/
+int BotImport_DebugPolygonCreate(int color, int numPoints, vec3_t *points) {
+ bot_debugpoly_t *poly;
+ int i;
+
+ if (!debugpolygons)
+ return 0;
+
+ for (i = 1; i < bot_maxdebugpolys; i++) {
+ if (!debugpolygons[i].inuse)
+ break;
+ }
+ if (i >= bot_maxdebugpolys)
+ return 0;
+ poly = &debugpolygons[i];
+ poly->inuse = qtrue;
+ poly->color = color;
+ poly->numPoints = numPoints;
+ Com_Memcpy(poly->points, points, numPoints * sizeof(vec3_t));
+ //
+ return i;
+}
+
+/*
+==================
+BotImport_DebugPolygonShow
+==================
+*/
+void BotImport_DebugPolygonShow(int id, int color, int numPoints, vec3_t *points) {
+ bot_debugpoly_t *poly;
+
+ if (!debugpolygons) return;
+ poly = &debugpolygons[id];
+ poly->inuse = qtrue;
+ poly->color = color;
+ poly->numPoints = numPoints;
+ Com_Memcpy(poly->points, points, numPoints * sizeof(vec3_t));
+}
+
+/*
+==================
+BotImport_DebugPolygonDelete
+==================
+*/
+void BotImport_DebugPolygonDelete(int id)
+{
+ if (!debugpolygons) return;
+ debugpolygons[id].inuse = qfalse;
+}
+
+/*
+==================
+BotImport_DebugLineCreate
+==================
+*/
+int BotImport_DebugLineCreate(void) {
+ vec3_t points[1];
+ return BotImport_DebugPolygonCreate(0, 0, points);
+}
+
+/*
+==================
+BotImport_DebugLineDelete
+==================
+*/
+void BotImport_DebugLineDelete(int line) {
+ BotImport_DebugPolygonDelete(line);
+}
+
+/*
+==================
+BotImport_DebugLineShow
+==================
+*/
+void BotImport_DebugLineShow(int line, vec3_t start, vec3_t end, int color) {
+ vec3_t points[4], dir, cross, up = {0, 0, 1};
+ float dot;
+
+ VectorCopy(start, points[0]);
+ VectorCopy(start, points[1]);
+ //points[1][2] -= 2;
+ VectorCopy(end, points[2]);
+ //points[2][2] -= 2;
+ VectorCopy(end, points[3]);
+
+
+ VectorSubtract(end, start, dir);
+ VectorNormalize(dir);
+ dot = DotProduct(dir, up);
+ if (dot > 0.99 || dot < -0.99) VectorSet(cross, 1, 0, 0);
+ else CrossProduct(dir, up, cross);
+
+ VectorNormalize(cross);
+
+ VectorMA(points[0], 2, cross, points[0]);
+ VectorMA(points[1], -2, cross, points[1]);
+ VectorMA(points[2], -2, cross, points[2]);
+ VectorMA(points[3], 2, cross, points[3]);
+
+ BotImport_DebugPolygonShow(line, color, 4, points);
+}
+
+/*
+==================
+SV_BotClientCommand
+==================
+*/
+void BotClientCommand( int client, char *command ) {
+ SV_ExecuteClientCommand( &svs.clients[client], command, qtrue );
+}
+
+/*
+==================
+SV_BotFrame
+==================
+*/
+void SV_BotFrame( int time ) {
+ if (!bot_enable) return;
+ //NOTE: maybe the game is already shutdown
+ if (!gvm) return;
+ VM_Call( gvm, BOTAI_START_FRAME, time );
+}
+
+/*
+===============
+SV_BotLibSetup
+===============
+*/
+int SV_BotLibSetup( void ) {
+ if (!bot_enable) {
+ return 0;
+ }
+
+ if ( !botlib_export ) {
+ Com_Printf( S_COLOR_RED "Error: SV_BotLibSetup without SV_BotInitBotLib\n" );
+ return -1;
+ }
+
+ return botlib_export->BotLibSetup();
+}
+
+/*
+===============
+SV_ShutdownBotLib
+
+Called when either the entire server is being killed, or
+it is changing to a different game directory.
+===============
+*/
+int SV_BotLibShutdown( void ) {
+
+ if ( !botlib_export ) {
+ return -1;
+ }
+
+ return botlib_export->BotLibShutdown();
+}
+
+/*
+==================
+SV_BotInitCvars
+==================
+*/
+void SV_BotInitCvars(void) {
+
+ Cvar_Get("bot_enable", "1", 0); //enable the bot
+ Cvar_Get("bot_developer", "0", CVAR_CHEAT); //bot developer mode
+ Cvar_Get("bot_debug", "0", CVAR_CHEAT); //enable bot debugging
+ Cvar_Get("bot_maxdebugpolys", "2", 0); //maximum number of debug polys
+ Cvar_Get("bot_groundonly", "1", 0); //only show ground faces of areas
+ Cvar_Get("bot_reachability", "0", 0); //show all reachabilities to other areas
+ Cvar_Get("bot_visualizejumppads", "0", CVAR_CHEAT); //show jumppads
+ Cvar_Get("bot_forceclustering", "0", 0); //force cluster calculations
+ Cvar_Get("bot_forcereachability", "0", 0); //force reachability calculations
+ Cvar_Get("bot_forcewrite", "0", 0); //force writing aas file
+ Cvar_Get("bot_aasoptimize", "0", 0); //no aas file optimisation
+ Cvar_Get("bot_saveroutingcache", "0", 0); //save routing cache
+ Cvar_Get("bot_thinktime", "100", CVAR_CHEAT); //msec the bots thinks
+ Cvar_Get("bot_reloadcharacters", "0", 0); //reload the bot characters each time
+ Cvar_Get("bot_testichat", "0", 0); //test ichats
+ Cvar_Get("bot_testrchat", "0", 0); //test rchats
+ Cvar_Get("bot_testsolid", "0", CVAR_CHEAT); //test for solid areas
+ Cvar_Get("bot_testclusters", "0", CVAR_CHEAT); //test the AAS clusters
+ Cvar_Get("bot_fastchat", "0", 0); //fast chatting bots
+ Cvar_Get("bot_nochat", "0", 0); //disable chats
+ Cvar_Get("bot_pause", "0", CVAR_CHEAT); //pause the bots thinking
+ Cvar_Get("bot_report", "0", CVAR_CHEAT); //get a full report in ctf
+ Cvar_Get("bot_grapple", "0", 0); //enable grapple
+ Cvar_Get("bot_rocketjump", "1", 0); //enable rocket jumping
+ Cvar_Get("bot_challenge", "0", 0); //challenging bot
+ Cvar_Get("bot_minplayers", "0", 0); //minimum players in a team or the game
+ Cvar_Get("bot_interbreedchar", "", CVAR_CHEAT); //bot character used for interbreeding
+ Cvar_Get("bot_interbreedbots", "10", CVAR_CHEAT); //number of bots used for interbreeding
+ Cvar_Get("bot_interbreedcycle", "20", CVAR_CHEAT); //bot interbreeding cycle
+ Cvar_Get("bot_interbreedwrite", "", CVAR_CHEAT); //write interbreeded bots to this file
+}
+
+/*
+==================
+SV_BotInitBotLib
+==================
+*/
+void SV_BotInitBotLib(void) {
+ botlib_import_t botlib_import;
+
+ if ( !Cvar_VariableValue("fs_restrict") && !Sys_CheckCD() ) {
+ Com_Error( ERR_NEED_CD, "Game CD not in drive" );
+ }
+
+ if (debugpolygons) Z_Free(debugpolygons);
+ bot_maxdebugpolys = Cvar_VariableIntegerValue("bot_maxdebugpolys");
+ debugpolygons = Z_Malloc(sizeof(bot_debugpoly_t) * bot_maxdebugpolys);
+
+ botlib_import.Print = BotImport_Print;
+ botlib_import.Trace = BotImport_Trace;
+ botlib_import.EntityTrace = BotImport_EntityTrace;
+ botlib_import.PointContents = BotImport_PointContents;
+ botlib_import.inPVS = BotImport_inPVS;
+ botlib_import.BSPEntityData = BotImport_BSPEntityData;
+ botlib_import.BSPModelMinsMaxsOrigin = BotImport_BSPModelMinsMaxsOrigin;
+ botlib_import.BotClientCommand = BotClientCommand;
+
+ //memory management
+ botlib_import.GetMemory = BotImport_GetMemory;
+ botlib_import.FreeMemory = BotImport_FreeMemory;
+ botlib_import.AvailableMemory = Z_AvailableMemory;
+ botlib_import.HunkAlloc = BotImport_HunkAlloc;
+
+ // file system access
+ botlib_import.FS_FOpenFile = FS_FOpenFileByMode;
+ botlib_import.FS_Read = FS_Read2;
+ botlib_import.FS_Write = FS_Write;
+ botlib_import.FS_FCloseFile = FS_FCloseFile;
+ botlib_import.FS_Seek = FS_Seek;
+
+ //debug lines
+ botlib_import.DebugLineCreate = BotImport_DebugLineCreate;
+ botlib_import.DebugLineDelete = BotImport_DebugLineDelete;
+ botlib_import.DebugLineShow = BotImport_DebugLineShow;
+
+ //debug polygons
+ botlib_import.DebugPolygonCreate = BotImport_DebugPolygonCreate;
+ botlib_import.DebugPolygonDelete = BotImport_DebugPolygonDelete;
+
+ botlib_export = (botlib_export_t *)GetBotLibAPI( BOTLIB_API_VERSION, &botlib_import );
+ assert(botlib_export); // bk001129 - somehow we end up with a zero import.
+}
+
+
+//
+// * * * BOT AI CODE IS BELOW THIS POINT * * *
+//
+
+/*
+==================
+SV_BotGetConsoleMessage
+==================
+*/
+int SV_BotGetConsoleMessage( int client, char *buf, int size )
+{
+ client_t *cl;
+ int index;
+
+ cl = &svs.clients[client];
+ cl->lastPacketTime = svs.time;
+
+ if ( cl->reliableAcknowledge == cl->reliableSequence ) {
+ return qfalse;
+ }
+
+ cl->reliableAcknowledge++;
+ index = cl->reliableAcknowledge & ( MAX_RELIABLE_COMMANDS - 1 );
+
+ if ( !cl->reliableCommands[index][0] ) {
+ return qfalse;
+ }
+
+ Q_strncpyz( buf, cl->reliableCommands[index], size );
+ return qtrue;
+}
+
+#if 0
+/*
+==================
+EntityInPVS
+==================
+*/
+int EntityInPVS( int client, int entityNum ) {
+ client_t *cl;
+ clientSnapshot_t *frame;
+ int i;
+
+ cl = &svs.clients[client];
+ frame = &cl->frames[cl->netchan.outgoingSequence & PACKET_MASK];
+ for ( i = 0; i < frame->num_entities; i++ ) {
+ if ( svs.snapshotEntities[(frame->first_entity + i) % svs.numSnapshotEntities].number == entityNum ) {
+ return qtrue;
+ }
+ }
+ return qfalse;
+}
+#endif
+
+/*
+==================
+SV_BotGetSnapshotEntity
+==================
+*/
+int SV_BotGetSnapshotEntity( int client, int sequence ) {
+ client_t *cl;
+ clientSnapshot_t *frame;
+
+ cl = &svs.clients[client];
+ frame = &cl->frames[cl->netchan.outgoingSequence & PACKET_MASK];
+ if (sequence < 0 || sequence >= frame->num_entities) {
+ return -1;
+ }
+ return svs.snapshotEntities[(frame->first_entity + sequence) % svs.numSnapshotEntities].number;
+}
+
diff --git a/code/server/sv_ccmds.c b/code/server/sv_ccmds.c
new file mode 100755
index 0000000..62ae179
--- /dev/null
+++ b/code/server/sv_ccmds.c
@@ -0,0 +1,762 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "server.h"
+
+/*
+===============================================================================
+
+OPERATOR CONSOLE ONLY COMMANDS
+
+These commands can only be entered from stdin or by a remote operator datagram
+===============================================================================
+*/
+
+
+/*
+==================
+SV_GetPlayerByName
+
+Returns the player with name from Cmd_Argv(1)
+==================
+*/
+static client_t *SV_GetPlayerByName( void ) {
+ client_t *cl;
+ int i;
+ char *s;
+ char cleanName[64];
+
+ // make sure server is running
+ if ( !com_sv_running->integer ) {
+ return NULL;
+ }
+
+ if ( Cmd_Argc() < 2 ) {
+ Com_Printf( "No player specified.\n" );
+ return NULL;
+ }
+
+ s = Cmd_Argv(1);
+
+ // check for a name match
+ for ( i=0, cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++ ) {
+ if ( !cl->state ) {
+ continue;
+ }
+ if ( !Q_stricmp( cl->name, s ) ) {
+ return cl;
+ }
+
+ Q_strncpyz( cleanName, cl->name, sizeof(cleanName) );
+ Q_CleanStr( cleanName );
+ if ( !Q_stricmp( cleanName, s ) ) {
+ return cl;
+ }
+ }
+
+ Com_Printf( "Player %s is not on the server\n", s );
+
+ return NULL;
+}
+
+/*
+==================
+SV_GetPlayerByNum
+
+Returns the player with idnum from Cmd_Argv(1)
+==================
+*/
+static client_t *SV_GetPlayerByNum( void ) {
+ client_t *cl;
+ int i;
+ int idnum;
+ char *s;
+
+ // make sure server is running
+ if ( !com_sv_running->integer ) {
+ return NULL;
+ }
+
+ if ( Cmd_Argc() < 2 ) {
+ Com_Printf( "No player specified.\n" );
+ return NULL;
+ }
+
+ s = Cmd_Argv(1);
+
+ for (i = 0; s[i]; i++) {
+ if (s[i] < '0' || s[i] > '9') {
+ Com_Printf( "Bad slot number: %s\n", s);
+ return NULL;
+ }
+ }
+ idnum = atoi( s );
+ if ( idnum < 0 || idnum >= sv_maxclients->integer ) {
+ Com_Printf( "Bad client slot: %i\n", idnum );
+ return NULL;
+ }
+
+ cl = &svs.clients[idnum];
+ if ( !cl->state ) {
+ Com_Printf( "Client %i is not active\n", idnum );
+ return NULL;
+ }
+ return cl;
+
+ return NULL;
+}
+
+//=========================================================
+
+
+/*
+==================
+SV_Map_f
+
+Restart the server on a different map
+==================
+*/
+static void SV_Map_f( void ) {
+ char *cmd;
+ char *map;
+ qboolean killBots, cheat;
+ char expanded[MAX_QPATH];
+ char mapname[MAX_QPATH];
+
+ map = Cmd_Argv(1);
+ if ( !map ) {
+ return;
+ }
+
+ // make sure the level exists before trying to change, so that
+ // a typo at the server console won't end the game
+ Com_sprintf (expanded, sizeof(expanded), "maps/%s.bsp", map);
+ if ( FS_ReadFile (expanded, NULL) == -1 ) {
+ Com_Printf ("Can't find map %s\n", expanded);
+ return;
+ }
+
+ // force latched values to get set
+ Cvar_Get ("g_gametype", "0", CVAR_SERVERINFO | CVAR_USERINFO | CVAR_LATCH );
+
+ cmd = Cmd_Argv(0);
+ if( Q_stricmpn( cmd, "sp", 2 ) == 0 ) {
+ Cvar_SetValue( "g_gametype", GT_SINGLE_PLAYER );
+ Cvar_SetValue( "g_doWarmup", 0 );
+ // may not set sv_maxclients directly, always set latched
+ Cvar_SetLatched( "sv_maxclients", "8" );
+ cmd += 2;
+ cheat = qfalse;
+ killBots = qtrue;
+ }
+ else {
+ if ( !Q_stricmp( cmd, "devmap" ) || !Q_stricmp( cmd, "spdevmap" ) ) {
+ cheat = qtrue;
+ killBots = qtrue;
+ } else {
+ cheat = qfalse;
+ killBots = qfalse;
+ }
+ if( sv_gametype->integer == GT_SINGLE_PLAYER ) {
+ Cvar_SetValue( "g_gametype", GT_FFA );
+ }
+ }
+
+ // save the map name here cause on a map restart we reload the q3config.cfg
+ // and thus nuke the arguments of the map command
+ Q_strncpyz(mapname, map, sizeof(mapname));
+
+ // start up the map
+ SV_SpawnServer( mapname, killBots );
+
+ // set the cheat value
+ // if the level was started with "map <levelname>", then
+ // cheats will not be allowed. If started with "devmap <levelname>"
+ // then cheats will be allowed
+ if ( cheat ) {
+ Cvar_Set( "sv_cheats", "1" );
+ } else {
+ Cvar_Set( "sv_cheats", "0" );
+ }
+}
+
+/*
+================
+SV_MapRestart_f
+
+Completely restarts a level, but doesn't send a new gamestate to the clients.
+This allows fair starts with variable load times.
+================
+*/
+static void SV_MapRestart_f( void ) {
+ int i;
+ client_t *client;
+ char *denied;
+ qboolean isBot;
+ int delay;
+
+ // make sure we aren't restarting twice in the same frame
+ if ( com_frameTime == sv.serverId ) {
+ return;
+ }
+
+ // make sure server is running
+ if ( !com_sv_running->integer ) {
+ Com_Printf( "Server is not running.\n" );
+ return;
+ }
+
+ if ( sv.restartTime ) {
+ return;
+ }
+
+ if (Cmd_Argc() > 1 ) {
+ delay = atoi( Cmd_Argv(1) );
+ }
+ else {
+ delay = 5;
+ }
+ if( delay && !Cvar_VariableValue("g_doWarmup") ) {
+ sv.restartTime = svs.time + delay * 1000;
+ SV_SetConfigstring( CS_WARMUP, va("%i", sv.restartTime) );
+ return;
+ }
+
+ // check for changes in variables that can't just be restarted
+ // check for maxclients change
+ if ( sv_maxclients->modified || sv_gametype->modified ) {
+ char mapname[MAX_QPATH];
+
+ Com_Printf( "variable change -- restarting.\n" );
+ // restart the map the slow way
+ Q_strncpyz( mapname, Cvar_VariableString( "mapname" ), sizeof( mapname ) );
+
+ SV_SpawnServer( mapname, qfalse );
+ return;
+ }
+
+ // toggle the server bit so clients can detect that a
+ // map_restart has happened
+ svs.snapFlagServerBit ^= SNAPFLAG_SERVERCOUNT;
+
+ // generate a new serverid
+ // TTimo - don't update restartedserverId there, otherwise we won't deal correctly with multiple map_restart
+ sv.serverId = com_frameTime;
+ Cvar_Set( "sv_serverid", va("%i", sv.serverId ) );
+
+ // reset all the vm data in place without changing memory allocation
+ // note that we do NOT set sv.state = SS_LOADING, so configstrings that
+ // had been changed from their default values will generate broadcast updates
+ sv.state = SS_LOADING;
+ sv.restarting = qtrue;
+
+ SV_RestartGameProgs();
+
+ // run a few frames to allow everything to settle
+ for ( i = 0 ;i < 3 ; i++ ) {
+ VM_Call( gvm, GAME_RUN_FRAME, svs.time );
+ svs.time += 100;
+ }
+
+ sv.state = SS_GAME;
+ sv.restarting = qfalse;
+
+ // connect and begin all the clients
+ for (i=0 ; i<sv_maxclients->integer ; i++) {
+ client = &svs.clients[i];
+
+ // send the new gamestate to all connected clients
+ if ( client->state < CS_CONNECTED) {
+ continue;
+ }
+
+ if ( client->netchan.remoteAddress.type == NA_BOT ) {
+ isBot = qtrue;
+ } else {
+ isBot = qfalse;
+ }
+
+ // add the map_restart command
+ SV_AddServerCommand( client, "map_restart\n" );
+
+ // connect the client again, without the firstTime flag
+ denied = VM_ExplicitArgPtr( gvm, VM_Call( gvm, GAME_CLIENT_CONNECT, i, qfalse, isBot ) );
+ if ( denied ) {
+ // this generally shouldn't happen, because the client
+ // was connected before the level change
+ SV_DropClient( client, denied );
+ Com_Printf( "SV_MapRestart_f(%d): dropped client %i - denied!\n", delay, i ); // bk010125
+ continue;
+ }
+
+ client->state = CS_ACTIVE;
+
+ SV_ClientEnterWorld( client, &client->lastUsercmd );
+ }
+
+ // run another frame to allow things to look at all the players
+ VM_Call( gvm, GAME_RUN_FRAME, svs.time );
+ svs.time += 100;
+}
+
+//===============================================================
+
+/*
+==================
+SV_Kick_f
+
+Kick a user off of the server FIXME: move to game
+==================
+*/
+static void SV_Kick_f( void ) {
+ client_t *cl;
+ int i;
+
+ // make sure server is running
+ if ( !com_sv_running->integer ) {
+ Com_Printf( "Server is not running.\n" );
+ return;
+ }
+
+ if ( Cmd_Argc() != 2 ) {
+ Com_Printf ("Usage: kick <player name>\nkick all = kick everyone\nkick allbots = kick all bots\n");
+ return;
+ }
+
+ cl = SV_GetPlayerByName();
+ if ( !cl ) {
+ if ( !Q_stricmp(Cmd_Argv(1), "all") ) {
+ for ( i=0, cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++ ) {
+ if ( !cl->state ) {
+ continue;
+ }
+ if( cl->netchan.remoteAddress.type == NA_LOOPBACK ) {
+ continue;
+ }
+ SV_DropClient( cl, "was kicked" );
+ cl->lastPacketTime = svs.time; // in case there is a funny zombie
+ }
+ }
+ else if ( !Q_stricmp(Cmd_Argv(1), "allbots") ) {
+ for ( i=0, cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++ ) {
+ if ( !cl->state ) {
+ continue;
+ }
+ if( cl->netchan.remoteAddress.type != NA_BOT ) {
+ continue;
+ }
+ SV_DropClient( cl, "was kicked" );
+ cl->lastPacketTime = svs.time; // in case there is a funny zombie
+ }
+ }
+ return;
+ }
+ if( cl->netchan.remoteAddress.type == NA_LOOPBACK ) {
+ SV_SendServerCommand(NULL, "print \"%s\"", "Cannot kick host player\n");
+ return;
+ }
+
+ SV_DropClient( cl, "was kicked" );
+ cl->lastPacketTime = svs.time; // in case there is a funny zombie
+}
+
+/*
+==================
+SV_Ban_f
+
+Ban a user from being able to play on this server through the auth
+server
+==================
+*/
+static void SV_Ban_f( void ) {
+ client_t *cl;
+
+ // make sure server is running
+ if ( !com_sv_running->integer ) {
+ Com_Printf( "Server is not running.\n" );
+ return;
+ }
+
+ if ( Cmd_Argc() != 2 ) {
+ Com_Printf ("Usage: banUser <player name>\n");
+ return;
+ }
+
+ cl = SV_GetPlayerByName();
+
+ if (!cl) {
+ return;
+ }
+
+ if( cl->netchan.remoteAddress.type == NA_LOOPBACK ) {
+ SV_SendServerCommand(NULL, "print \"%s\"", "Cannot kick host player\n");
+ return;
+ }
+
+ // look up the authorize server's IP
+ if ( !svs.authorizeAddress.ip[0] && svs.authorizeAddress.type != NA_BAD ) {
+ Com_Printf( "Resolving %s\n", AUTHORIZE_SERVER_NAME );
+ if ( !NET_StringToAdr( AUTHORIZE_SERVER_NAME, &svs.authorizeAddress ) ) {
+ Com_Printf( "Couldn't resolve address\n" );
+ return;
+ }
+ svs.authorizeAddress.port = BigShort( PORT_AUTHORIZE );
+ Com_Printf( "%s resolved to %i.%i.%i.%i:%i\n", AUTHORIZE_SERVER_NAME,
+ svs.authorizeAddress.ip[0], svs.authorizeAddress.ip[1],
+ svs.authorizeAddress.ip[2], svs.authorizeAddress.ip[3],
+ BigShort( svs.authorizeAddress.port ) );
+ }
+
+ // otherwise send their ip to the authorize server
+ if ( svs.authorizeAddress.type != NA_BAD ) {
+ NET_OutOfBandPrint( NS_SERVER, svs.authorizeAddress,
+ "banUser %i.%i.%i.%i", cl->netchan.remoteAddress.ip[0], cl->netchan.remoteAddress.ip[1],
+ cl->netchan.remoteAddress.ip[2], cl->netchan.remoteAddress.ip[3] );
+ Com_Printf("%s was banned from coming back\n", cl->name);
+ }
+}
+
+/*
+==================
+SV_BanNum_f
+
+Ban a user from being able to play on this server through the auth
+server
+==================
+*/
+static void SV_BanNum_f( void ) {
+ client_t *cl;
+
+ // make sure server is running
+ if ( !com_sv_running->integer ) {
+ Com_Printf( "Server is not running.\n" );
+ return;
+ }
+
+ if ( Cmd_Argc() != 2 ) {
+ Com_Printf ("Usage: banClient <client number>\n");
+ return;
+ }
+
+ cl = SV_GetPlayerByNum();
+ if ( !cl ) {
+ return;
+ }
+ if( cl->netchan.remoteAddress.type == NA_LOOPBACK ) {
+ SV_SendServerCommand(NULL, "print \"%s\"", "Cannot kick host player\n");
+ return;
+ }
+
+ // look up the authorize server's IP
+ if ( !svs.authorizeAddress.ip[0] && svs.authorizeAddress.type != NA_BAD ) {
+ Com_Printf( "Resolving %s\n", AUTHORIZE_SERVER_NAME );
+ if ( !NET_StringToAdr( AUTHORIZE_SERVER_NAME, &svs.authorizeAddress ) ) {
+ Com_Printf( "Couldn't resolve address\n" );
+ return;
+ }
+ svs.authorizeAddress.port = BigShort( PORT_AUTHORIZE );
+ Com_Printf( "%s resolved to %i.%i.%i.%i:%i\n", AUTHORIZE_SERVER_NAME,
+ svs.authorizeAddress.ip[0], svs.authorizeAddress.ip[1],
+ svs.authorizeAddress.ip[2], svs.authorizeAddress.ip[3],
+ BigShort( svs.authorizeAddress.port ) );
+ }
+
+ // otherwise send their ip to the authorize server
+ if ( svs.authorizeAddress.type != NA_BAD ) {
+ NET_OutOfBandPrint( NS_SERVER, svs.authorizeAddress,
+ "banUser %i.%i.%i.%i", cl->netchan.remoteAddress.ip[0], cl->netchan.remoteAddress.ip[1],
+ cl->netchan.remoteAddress.ip[2], cl->netchan.remoteAddress.ip[3] );
+ Com_Printf("%s was banned from coming back\n", cl->name);
+ }
+}
+
+/*
+==================
+SV_KickNum_f
+
+Kick a user off of the server FIXME: move to game
+==================
+*/
+static void SV_KickNum_f( void ) {
+ client_t *cl;
+
+ // make sure server is running
+ if ( !com_sv_running->integer ) {
+ Com_Printf( "Server is not running.\n" );
+ return;
+ }
+
+ if ( Cmd_Argc() != 2 ) {
+ Com_Printf ("Usage: kicknum <client number>\n");
+ return;
+ }
+
+ cl = SV_GetPlayerByNum();
+ if ( !cl ) {
+ return;
+ }
+ if( cl->netchan.remoteAddress.type == NA_LOOPBACK ) {
+ SV_SendServerCommand(NULL, "print \"%s\"", "Cannot kick host player\n");
+ return;
+ }
+
+ SV_DropClient( cl, "was kicked" );
+ cl->lastPacketTime = svs.time; // in case there is a funny zombie
+}
+
+/*
+================
+SV_Status_f
+================
+*/
+static void SV_Status_f( void ) {
+ int i, j, l;
+ client_t *cl;
+ playerState_t *ps;
+ const char *s;
+ int ping;
+
+ // make sure server is running
+ if ( !com_sv_running->integer ) {
+ Com_Printf( "Server is not running.\n" );
+ return;
+ }
+
+ Com_Printf ("map: %s\n", sv_mapname->string );
+
+ Com_Printf ("num score ping name lastmsg address qport rate\n");
+ Com_Printf ("--- ----- ---- --------------- ------- --------------------- ----- -----\n");
+ for (i=0,cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++)
+ {
+ if (!cl->state)
+ continue;
+ Com_Printf ("%3i ", i);
+ ps = SV_GameClientNum( i );
+ Com_Printf ("%5i ", ps->persistant[PERS_SCORE]);
+
+ if (cl->state == CS_CONNECTED)
+ Com_Printf ("CNCT ");
+ else if (cl->state == CS_ZOMBIE)
+ Com_Printf ("ZMBI ");
+ else
+ {
+ ping = cl->ping < 9999 ? cl->ping : 9999;
+ Com_Printf ("%4i ", ping);
+ }
+
+ Com_Printf ("%s", cl->name);
+ // TTimo adding a ^7 to reset the color
+ // NOTE: colored names in status breaks the padding (WONTFIX)
+ Com_Printf ("^7");
+ l = 16 - strlen(cl->name);
+ for (j=0 ; j<l ; j++)
+ Com_Printf (" ");
+
+ Com_Printf ("%7i ", svs.time - cl->lastPacketTime );
+
+ s = NET_AdrToString( cl->netchan.remoteAddress );
+ Com_Printf ("%s", s);
+ l = 22 - strlen(s);
+ for (j=0 ; j<l ; j++)
+ Com_Printf (" ");
+
+ Com_Printf ("%5i", cl->netchan.qport);
+
+ Com_Printf (" %5i", cl->rate);
+
+ Com_Printf ("\n");
+ }
+ Com_Printf ("\n");
+}
+
+/*
+==================
+SV_ConSay_f
+==================
+*/
+static void SV_ConSay_f(void) {
+ char *p;
+ char text[1024];
+
+ // make sure server is running
+ if ( !com_sv_running->integer ) {
+ Com_Printf( "Server is not running.\n" );
+ return;
+ }
+
+ if ( Cmd_Argc () < 2 ) {
+ return;
+ }
+
+ strcpy (text, "console: ");
+ p = Cmd_Args();
+
+ if ( *p == '"' ) {
+ p++;
+ p[strlen(p)-1] = 0;
+ }
+
+ strcat(text, p);
+
+ SV_SendServerCommand(NULL, "chat \"%s\n\"", text);
+}
+
+
+/*
+==================
+SV_Heartbeat_f
+
+Also called by SV_DropClient, SV_DirectConnect, and SV_SpawnServer
+==================
+*/
+void SV_Heartbeat_f( void ) {
+ svs.nextHeartbeatTime = -9999999;
+}
+
+
+/*
+===========
+SV_Serverinfo_f
+
+Examine the serverinfo string
+===========
+*/
+static void SV_Serverinfo_f( void ) {
+ Com_Printf ("Server info settings:\n");
+ Info_Print ( Cvar_InfoString( CVAR_SERVERINFO ) );
+}
+
+
+/*
+===========
+SV_Systeminfo_f
+
+Examine or change the serverinfo string
+===========
+*/
+static void SV_Systeminfo_f( void ) {
+ Com_Printf ("System info settings:\n");
+ Info_Print ( Cvar_InfoString( CVAR_SYSTEMINFO ) );
+}
+
+
+/*
+===========
+SV_DumpUser_f
+
+Examine all a users info strings FIXME: move to game
+===========
+*/
+static void SV_DumpUser_f( void ) {
+ client_t *cl;
+
+ // make sure server is running
+ if ( !com_sv_running->integer ) {
+ Com_Printf( "Server is not running.\n" );
+ return;
+ }
+
+ if ( Cmd_Argc() != 2 ) {
+ Com_Printf ("Usage: info <userid>\n");
+ return;
+ }
+
+ cl = SV_GetPlayerByName();
+ if ( !cl ) {
+ return;
+ }
+
+ Com_Printf( "userinfo\n" );
+ Com_Printf( "--------\n" );
+ Info_Print( cl->userinfo );
+}
+
+
+/*
+=================
+SV_KillServer
+=================
+*/
+static void SV_KillServer_f( void ) {
+ SV_Shutdown( "killserver" );
+}
+
+//===========================================================
+
+/*
+==================
+SV_AddOperatorCommands
+==================
+*/
+void SV_AddOperatorCommands( void ) {
+ static qboolean initialized;
+
+ if ( initialized ) {
+ return;
+ }
+ initialized = qtrue;
+
+ Cmd_AddCommand ("heartbeat", SV_Heartbeat_f);
+ Cmd_AddCommand ("kick", SV_Kick_f);
+ Cmd_AddCommand ("banUser", SV_Ban_f);
+ Cmd_AddCommand ("banClient", SV_BanNum_f);
+ Cmd_AddCommand ("clientkick", SV_KickNum_f);
+ Cmd_AddCommand ("status", SV_Status_f);
+ Cmd_AddCommand ("serverinfo", SV_Serverinfo_f);
+ Cmd_AddCommand ("systeminfo", SV_Systeminfo_f);
+ Cmd_AddCommand ("dumpuser", SV_DumpUser_f);
+ Cmd_AddCommand ("map_restart", SV_MapRestart_f);
+ Cmd_AddCommand ("sectorlist", SV_SectorList_f);
+ Cmd_AddCommand ("map", SV_Map_f);
+#ifndef PRE_RELEASE_DEMO
+ Cmd_AddCommand ("devmap", SV_Map_f);
+ Cmd_AddCommand ("spmap", SV_Map_f);
+ Cmd_AddCommand ("spdevmap", SV_Map_f);
+#endif
+ Cmd_AddCommand ("killserver", SV_KillServer_f);
+ if( com_dedicated->integer ) {
+ Cmd_AddCommand ("say", SV_ConSay_f);
+ }
+}
+
+/*
+==================
+SV_RemoveOperatorCommands
+==================
+*/
+void SV_RemoveOperatorCommands( void ) {
+#if 0
+ // removing these won't let the server start again
+ Cmd_RemoveCommand ("heartbeat");
+ Cmd_RemoveCommand ("kick");
+ Cmd_RemoveCommand ("banUser");
+ Cmd_RemoveCommand ("banClient");
+ Cmd_RemoveCommand ("status");
+ Cmd_RemoveCommand ("serverinfo");
+ Cmd_RemoveCommand ("systeminfo");
+ Cmd_RemoveCommand ("dumpuser");
+ Cmd_RemoveCommand ("map_restart");
+ Cmd_RemoveCommand ("sectorlist");
+ Cmd_RemoveCommand ("say");
+#endif
+}
+
diff --git a/code/server/sv_client.c b/code/server/sv_client.c
new file mode 100755
index 0000000..c3fdc92
--- /dev/null
+++ b/code/server/sv_client.c
@@ -0,0 +1,1531 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// sv_client.c -- server code for dealing with clients
+
+#include "server.h"
+
+static void SV_CloseDownload( client_t *cl );
+
+/*
+=================
+SV_GetChallenge
+
+A "getchallenge" OOB command has been received
+Returns a challenge number that can be used
+in a subsequent connectResponse command.
+We do this to prevent denial of service attacks that
+flood the server with invalid connection IPs. With a
+challenge, they must give a valid IP address.
+
+If we are authorizing, a challenge request will cause a packet
+to be sent to the authorize server.
+
+When an authorizeip is returned, a challenge response will be
+sent to that ip.
+=================
+*/
+void SV_GetChallenge( netadr_t from ) {
+ int i;
+ int oldest;
+ int oldestTime;
+ challenge_t *challenge;
+
+ // ignore if we are in single player
+ if ( Cvar_VariableValue( "g_gametype" ) == GT_SINGLE_PLAYER || Cvar_VariableValue("ui_singlePlayerActive")) {
+ return;
+ }
+
+ oldest = 0;
+ oldestTime = 0x7fffffff;
+
+ // see if we already have a challenge for this ip
+ challenge = &svs.challenges[0];
+ for (i = 0 ; i < MAX_CHALLENGES ; i++, challenge++) {
+ if ( !challenge->connected && NET_CompareAdr( from, challenge->adr ) ) {
+ break;
+ }
+ if ( challenge->time < oldestTime ) {
+ oldestTime = challenge->time;
+ oldest = i;
+ }
+ }
+
+ if (i == MAX_CHALLENGES) {
+ // this is the first time this client has asked for a challenge
+ challenge = &svs.challenges[oldest];
+
+ challenge->challenge = ( (rand() << 16) ^ rand() ) ^ svs.time;
+ challenge->adr = from;
+ challenge->firstTime = svs.time;
+ challenge->time = svs.time;
+ challenge->connected = qfalse;
+ i = oldest;
+ }
+
+ // if they are on a lan address, send the challengeResponse immediately
+ if ( Sys_IsLANAddress( from ) ) {
+ challenge->pingTime = svs.time;
+ NET_OutOfBandPrint( NS_SERVER, from, "challengeResponse %i", challenge->challenge );
+ return;
+ }
+
+ // look up the authorize server's IP
+ if ( !svs.authorizeAddress.ip[0] && svs.authorizeAddress.type != NA_BAD ) {
+ Com_Printf( "Resolving %s\n", AUTHORIZE_SERVER_NAME );
+ if ( !NET_StringToAdr( AUTHORIZE_SERVER_NAME, &svs.authorizeAddress ) ) {
+ Com_Printf( "Couldn't resolve address\n" );
+ return;
+ }
+ svs.authorizeAddress.port = BigShort( PORT_AUTHORIZE );
+ Com_Printf( "%s resolved to %i.%i.%i.%i:%i\n", AUTHORIZE_SERVER_NAME,
+ svs.authorizeAddress.ip[0], svs.authorizeAddress.ip[1],
+ svs.authorizeAddress.ip[2], svs.authorizeAddress.ip[3],
+ BigShort( svs.authorizeAddress.port ) );
+ }
+
+ // if they have been challenging for a long time and we
+ // haven't heard anything from the authorize server, go ahead and
+ // let them in, assuming the id server is down
+ if ( svs.time - challenge->firstTime > AUTHORIZE_TIMEOUT ) {
+ Com_DPrintf( "authorize server timed out\n" );
+
+ challenge->pingTime = svs.time;
+ NET_OutOfBandPrint( NS_SERVER, challenge->adr,
+ "challengeResponse %i", challenge->challenge );
+ return;
+ }
+
+ // otherwise send their ip to the authorize server
+ if ( svs.authorizeAddress.type != NA_BAD ) {
+ cvar_t *fs;
+ char game[1024];
+
+ Com_DPrintf( "sending getIpAuthorize for %s\n", NET_AdrToString( from ));
+
+ strcpy(game, BASEGAME);
+ fs = Cvar_Get ("fs_game", "", CVAR_INIT|CVAR_SYSTEMINFO );
+ if (fs && fs->string[0] != 0) {
+ strcpy(game, fs->string);
+ }
+
+ // the 0 is for backwards compatibility with obsolete sv_allowanonymous flags
+ // getIpAuthorize <challenge> <IP> <game> 0 <auth-flag>
+ NET_OutOfBandPrint( NS_SERVER, svs.authorizeAddress,
+ "getIpAuthorize %i %i.%i.%i.%i %s 0 %s", svs.challenges[i].challenge,
+ from.ip[0], from.ip[1], from.ip[2], from.ip[3], game, sv_strictAuth->string );
+ }
+}
+
+/*
+====================
+SV_AuthorizeIpPacket
+
+A packet has been returned from the authorize server.
+If we have a challenge adr for that ip, send the
+challengeResponse to it
+====================
+*/
+void SV_AuthorizeIpPacket( netadr_t from ) {
+ int challenge;
+ int i;
+ char *s;
+ char *r;
+ char ret[1024];
+
+ if ( !NET_CompareBaseAdr( from, svs.authorizeAddress ) ) {
+ Com_Printf( "SV_AuthorizeIpPacket: not from authorize server\n" );
+ return;
+ }
+
+ challenge = atoi( Cmd_Argv( 1 ) );
+
+ for (i = 0 ; i < MAX_CHALLENGES ; i++) {
+ if ( svs.challenges[i].challenge == challenge ) {
+ break;
+ }
+ }
+ if ( i == MAX_CHALLENGES ) {
+ Com_Printf( "SV_AuthorizeIpPacket: challenge not found\n" );
+ return;
+ }
+
+ // send a packet back to the original client
+ svs.challenges[i].pingTime = svs.time;
+ s = Cmd_Argv( 2 );
+ r = Cmd_Argv( 3 ); // reason
+
+ if ( !Q_stricmp( s, "demo" ) ) {
+ if ( Cvar_VariableValue( "fs_restrict" ) ) {
+ // a demo client connecting to a demo server
+ NET_OutOfBandPrint( NS_SERVER, svs.challenges[i].adr,
+ "challengeResponse %i", svs.challenges[i].challenge );
+ return;
+ }
+ // they are a demo client trying to connect to a real server
+ NET_OutOfBandPrint( NS_SERVER, svs.challenges[i].adr, "print\nServer is not a demo server\n" );
+ // clear the challenge record so it won't timeout and let them through
+ Com_Memset( &svs.challenges[i], 0, sizeof( svs.challenges[i] ) );
+ return;
+ }
+ if ( !Q_stricmp( s, "accept" ) ) {
+ NET_OutOfBandPrint( NS_SERVER, svs.challenges[i].adr,
+ "challengeResponse %i", svs.challenges[i].challenge );
+ return;
+ }
+ if ( !Q_stricmp( s, "unknown" ) ) {
+ if (!r) {
+ NET_OutOfBandPrint( NS_SERVER, svs.challenges[i].adr, "print\nAwaiting CD key authorization\n" );
+ } else {
+ sprintf(ret, "print\n%s\n", r);
+ NET_OutOfBandPrint( NS_SERVER, svs.challenges[i].adr, ret );
+ }
+ // clear the challenge record so it won't timeout and let them through
+ Com_Memset( &svs.challenges[i], 0, sizeof( svs.challenges[i] ) );
+ return;
+ }
+
+ // authorization failed
+ if (!r) {
+ NET_OutOfBandPrint( NS_SERVER, svs.challenges[i].adr, "print\nSomeone is using this CD Key\n" );
+ } else {
+ sprintf(ret, "print\n%s\n", r);
+ NET_OutOfBandPrint( NS_SERVER, svs.challenges[i].adr, ret );
+ }
+
+ // clear the challenge record so it won't timeout and let them through
+ Com_Memset( &svs.challenges[i], 0, sizeof( svs.challenges[i] ) );
+}
+
+/*
+==================
+SV_DirectConnect
+
+A "connect" OOB command has been received
+==================
+*/
+
+#define PB_MESSAGE "PunkBuster Anti-Cheat software must be installed " \
+ "and Enabled in order to join this server. An updated game patch can be downloaded from " \
+ "www.idsoftware.com"
+
+void SV_DirectConnect( netadr_t from ) {
+ char userinfo[MAX_INFO_STRING];
+ int i;
+ client_t *cl, *newcl;
+ MAC_STATIC client_t temp;
+ sharedEntity_t *ent;
+ int clientNum;
+ int version;
+ int qport;
+ int challenge;
+ char *password;
+ int startIndex;
+ char *denied;
+ int count;
+
+ Com_DPrintf ("SVC_DirectConnect ()\n");
+
+ Q_strncpyz( userinfo, Cmd_Argv(1), sizeof(userinfo) );
+
+ version = atoi( Info_ValueForKey( userinfo, "protocol" ) );
+ if ( version != PROTOCOL_VERSION ) {
+ NET_OutOfBandPrint( NS_SERVER, from, "print\nServer uses protocol version %i.\n", PROTOCOL_VERSION );
+ Com_DPrintf (" rejected connect from version %i\n", version);
+ return;
+ }
+
+ challenge = atoi( Info_ValueForKey( userinfo, "challenge" ) );
+ qport = atoi( Info_ValueForKey( userinfo, "qport" ) );
+
+ // quick reject
+ for (i=0,cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++) {
+ if ( cl->state == CS_FREE ) {
+ continue;
+ }
+ if ( NET_CompareBaseAdr( from, cl->netchan.remoteAddress )
+ && ( cl->netchan.qport == qport
+ || from.port == cl->netchan.remoteAddress.port ) ) {
+ if (( svs.time - cl->lastConnectTime)
+ < (sv_reconnectlimit->integer * 1000)) {
+ Com_DPrintf ("%s:reconnect rejected : too soon\n", NET_AdrToString (from));
+ return;
+ }
+ break;
+ }
+ }
+
+ // see if the challenge is valid (LAN clients don't need to challenge)
+ if ( !NET_IsLocalAddress (from) ) {
+ int ping;
+
+ for (i=0 ; i<MAX_CHALLENGES ; i++) {
+ if (NET_CompareAdr(from, svs.challenges[i].adr)) {
+ if ( challenge == svs.challenges[i].challenge ) {
+ break; // good
+ }
+ }
+ }
+ if (i == MAX_CHALLENGES) {
+ NET_OutOfBandPrint( NS_SERVER, from, "print\nNo or bad challenge for address.\n" );
+ return;
+ }
+ // force the IP key/value pair so the game can filter based on ip
+ Info_SetValueForKey( userinfo, "ip", NET_AdrToString( from ) );
+
+ ping = svs.time - svs.challenges[i].pingTime;
+ Com_Printf( "Client %i connecting with %i challenge ping\n", i, ping );
+ svs.challenges[i].connected = qtrue;
+
+ // never reject a LAN client based on ping
+ if ( !Sys_IsLANAddress( from ) ) {
+ if ( sv_minPing->value && ping < sv_minPing->value ) {
+ // don't let them keep trying until they get a big delay
+ NET_OutOfBandPrint( NS_SERVER, from, "print\nServer is for high pings only\n" );
+ Com_DPrintf ("Client %i rejected on a too low ping\n", i);
+ // reset the address otherwise their ping will keep increasing
+ // with each connect message and they'd eventually be able to connect
+ svs.challenges[i].adr.port = 0;
+ return;
+ }
+ if ( sv_maxPing->value && ping > sv_maxPing->value ) {
+ NET_OutOfBandPrint( NS_SERVER, from, "print\nServer is for low pings only\n" );
+ Com_DPrintf ("Client %i rejected on a too high ping\n", i);
+ return;
+ }
+ }
+ } else {
+ // force the "ip" info key to "localhost"
+ Info_SetValueForKey( userinfo, "ip", "localhost" );
+ }
+
+ newcl = &temp;
+ Com_Memset (newcl, 0, sizeof(client_t));
+
+ // if there is already a slot for this ip, reuse it
+ for (i=0,cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++) {
+ if ( cl->state == CS_FREE ) {
+ continue;
+ }
+ if ( NET_CompareBaseAdr( from, cl->netchan.remoteAddress )
+ && ( cl->netchan.qport == qport
+ || from.port == cl->netchan.remoteAddress.port ) ) {
+ Com_Printf ("%s:reconnect\n", NET_AdrToString (from));
+ newcl = cl;
+
+ // this doesn't work because it nukes the players userinfo
+
+// // disconnect the client from the game first so any flags the
+// // player might have are dropped
+// VM_Call( gvm, GAME_CLIENT_DISCONNECT, newcl - svs.clients );
+ //
+ goto gotnewcl;
+ }
+ }
+
+ // find a client slot
+ // if "sv_privateClients" is set > 0, then that number
+ // of client slots will be reserved for connections that
+ // have "password" set to the value of "sv_privatePassword"
+ // Info requests will report the maxclients as if the private
+ // slots didn't exist, to prevent people from trying to connect
+ // to a full server.
+ // This is to allow us to reserve a couple slots here on our
+ // servers so we can play without having to kick people.
+
+ // check for privateClient password
+ password = Info_ValueForKey( userinfo, "password" );
+ if ( !strcmp( password, sv_privatePassword->string ) ) {
+ startIndex = 0;
+ } else {
+ // skip past the reserved slots
+ startIndex = sv_privateClients->integer;
+ }
+
+ newcl = NULL;
+ for ( i = startIndex; i < sv_maxclients->integer ; i++ ) {
+ cl = &svs.clients[i];
+ if (cl->state == CS_FREE) {
+ newcl = cl;
+ break;
+ }
+ }
+
+ if ( !newcl ) {
+ if ( NET_IsLocalAddress( from ) ) {
+ count = 0;
+ for ( i = startIndex; i < sv_maxclients->integer ; i++ ) {
+ cl = &svs.clients[i];
+ if (cl->netchan.remoteAddress.type == NA_BOT) {
+ count++;
+ }
+ }
+ // if they're all bots
+ if (count >= sv_maxclients->integer - startIndex) {
+ SV_DropClient(&svs.clients[sv_maxclients->integer - 1], "only bots on server");
+ newcl = &svs.clients[sv_maxclients->integer - 1];
+ }
+ else {
+ Com_Error( ERR_FATAL, "server is full on local connect\n" );
+ return;
+ }
+ }
+ else {
+ NET_OutOfBandPrint( NS_SERVER, from, "print\nServer is full.\n" );
+ Com_DPrintf ("Rejected a connection.\n");
+ return;
+ }
+ }
+
+ // we got a newcl, so reset the reliableSequence and reliableAcknowledge
+ cl->reliableAcknowledge = 0;
+ cl->reliableSequence = 0;
+
+gotnewcl:
+ // build a new connection
+ // accept the new client
+ // this is the only place a client_t is ever initialized
+ *newcl = temp;
+ clientNum = newcl - svs.clients;
+ ent = SV_GentityNum( clientNum );
+ newcl->gentity = ent;
+
+ // save the challenge
+ newcl->challenge = challenge;
+
+ // save the address
+ Netchan_Setup (NS_SERVER, &newcl->netchan , from, qport);
+ // init the netchan queue
+ newcl->netchan_end_queue = &newcl->netchan_start_queue;
+
+ // save the userinfo
+ Q_strncpyz( newcl->userinfo, userinfo, sizeof(newcl->userinfo) );
+
+ // get the game a chance to reject this connection or modify the userinfo
+ denied = (char *)VM_Call( gvm, GAME_CLIENT_CONNECT, clientNum, qtrue, qfalse ); // firstTime = qtrue
+ if ( denied ) {
+ // we can't just use VM_ArgPtr, because that is only valid inside a VM_Call
+ denied = VM_ExplicitArgPtr( gvm, (int)denied );
+
+ NET_OutOfBandPrint( NS_SERVER, from, "print\n%s\n", denied );
+ Com_DPrintf ("Game rejected a connection: %s.\n", denied);
+ return;
+ }
+
+ SV_UserinfoChanged( newcl );
+
+ // send the connect packet to the client
+ NET_OutOfBandPrint( NS_SERVER, from, "connectResponse" );
+
+ Com_DPrintf( "Going from CS_FREE to CS_CONNECTED for %s\n", newcl->name );
+
+ newcl->state = CS_CONNECTED;
+ newcl->nextSnapshotTime = svs.time;
+ newcl->lastPacketTime = svs.time;
+ newcl->lastConnectTime = svs.time;
+
+ // when we receive the first packet from the client, we will
+ // notice that it is from a different serverid and that the
+ // gamestate message was not just sent, forcing a retransmit
+ newcl->gamestateMessageNum = -1;
+
+ // if this was the first client on the server, or the last client
+ // the server can hold, send a heartbeat to the master.
+ count = 0;
+ for (i=0,cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++) {
+ if ( svs.clients[i].state >= CS_CONNECTED ) {
+ count++;
+ }
+ }
+ if ( count == 1 || count == sv_maxclients->integer ) {
+ SV_Heartbeat_f();
+ }
+}
+
+
+/*
+=====================
+SV_DropClient
+
+Called when the player is totally leaving the server, either willingly
+or unwillingly. This is NOT called if the entire server is quiting
+or crashing -- SV_FinalMessage() will handle that
+=====================
+*/
+void SV_DropClient( client_t *drop, const char *reason ) {
+ int i;
+ challenge_t *challenge;
+
+ if ( drop->state == CS_ZOMBIE ) {
+ return; // already dropped
+ }
+
+ if ( !drop->gentity || !(drop->gentity->r.svFlags & SVF_BOT) ) {
+ // see if we already have a challenge for this ip
+ challenge = &svs.challenges[0];
+
+ for (i = 0 ; i < MAX_CHALLENGES ; i++, challenge++) {
+ if ( NET_CompareAdr( drop->netchan.remoteAddress, challenge->adr ) ) {
+ challenge->connected = qfalse;
+ break;
+ }
+ }
+ }
+
+ // Kill any download
+ SV_CloseDownload( drop );
+
+ // tell everyone why they got dropped
+ SV_SendServerCommand( NULL, "print \"%s" S_COLOR_WHITE " %s\n\"", drop->name, reason );
+
+ Com_DPrintf( "Going to CS_ZOMBIE for %s\n", drop->name );
+ drop->state = CS_ZOMBIE; // become free in a few seconds
+
+ if (drop->download) {
+ FS_FCloseFile( drop->download );
+ drop->download = 0;
+ }
+
+ // call the prog function for removing a client
+ // this will remove the body, among other things
+ VM_Call( gvm, GAME_CLIENT_DISCONNECT, drop - svs.clients );
+
+ // add the disconnect command
+ SV_SendServerCommand( drop, "disconnect \"%s\"", reason);
+
+ if ( drop->netchan.remoteAddress.type == NA_BOT ) {
+ SV_BotFreeClient( drop - svs.clients );
+ }
+
+ // nuke user info
+ SV_SetUserinfo( drop - svs.clients, "" );
+
+ // if this was the last client on the server, send a heartbeat
+ // to the master so it is known the server is empty
+ // send a heartbeat now so the master will get up to date info
+ // if there is already a slot for this ip, reuse it
+ for (i=0 ; i < sv_maxclients->integer ; i++ ) {
+ if ( svs.clients[i].state >= CS_CONNECTED ) {
+ break;
+ }
+ }
+ if ( i == sv_maxclients->integer ) {
+ SV_Heartbeat_f();
+ }
+}
+
+/*
+================
+SV_SendClientGameState
+
+Sends the first message from the server to a connected client.
+This will be sent on the initial connection and upon each new map load.
+
+It will be resent if the client acknowledges a later message but has
+the wrong gamestate.
+================
+*/
+void SV_SendClientGameState( client_t *client ) {
+ int start;
+ entityState_t *base, nullstate;
+ msg_t msg;
+ byte msgBuffer[MAX_MSGLEN];
+
+ Com_DPrintf ("SV_SendClientGameState() for %s\n", client->name);
+ Com_DPrintf( "Going from CS_CONNECTED to CS_PRIMED for %s\n", client->name );
+ client->state = CS_PRIMED;
+ client->pureAuthentic = 0;
+ client->gotCP = qfalse;
+
+ // when we receive the first packet from the client, we will
+ // notice that it is from a different serverid and that the
+ // gamestate message was not just sent, forcing a retransmit
+ client->gamestateMessageNum = client->netchan.outgoingSequence;
+
+ MSG_Init( &msg, msgBuffer, sizeof( msgBuffer ) );
+
+ // NOTE, MRE: all server->client messages now acknowledge
+ // let the client know which reliable clientCommands we have received
+ MSG_WriteLong( &msg, client->lastClientCommand );
+
+ // send any server commands waiting to be sent first.
+ // we have to do this cause we send the client->reliableSequence
+ // with a gamestate and it sets the clc.serverCommandSequence at
+ // the client side
+ SV_UpdateServerCommandsToClient( client, &msg );
+
+ // send the gamestate
+ MSG_WriteByte( &msg, svc_gamestate );
+ MSG_WriteLong( &msg, client->reliableSequence );
+
+ // write the configstrings
+ for ( start = 0 ; start < MAX_CONFIGSTRINGS ; start++ ) {
+ if (sv.configstrings[start][0]) {
+ MSG_WriteByte( &msg, svc_configstring );
+ MSG_WriteShort( &msg, start );
+ MSG_WriteBigString( &msg, sv.configstrings[start] );
+ }
+ }
+
+ // write the baselines
+ Com_Memset( &nullstate, 0, sizeof( nullstate ) );
+ for ( start = 0 ; start < MAX_GENTITIES; start++ ) {
+ base = &sv.svEntities[start].baseline;
+ if ( !base->number ) {
+ continue;
+ }
+ MSG_WriteByte( &msg, svc_baseline );
+ MSG_WriteDeltaEntity( &msg, &nullstate, base, qtrue );
+ }
+
+ MSG_WriteByte( &msg, svc_EOF );
+
+ MSG_WriteLong( &msg, client - svs.clients);
+
+ // write the checksum feed
+ MSG_WriteLong( &msg, sv.checksumFeed);
+
+ // deliver this to the client
+ SV_SendMessageToClient( &msg, client );
+}
+
+
+/*
+==================
+SV_ClientEnterWorld
+==================
+*/
+void SV_ClientEnterWorld( client_t *client, usercmd_t *cmd ) {
+ int clientNum;
+ sharedEntity_t *ent;
+
+ Com_DPrintf( "Going from CS_PRIMED to CS_ACTIVE for %s\n", client->name );
+ client->state = CS_ACTIVE;
+
+ // set up the entity for the client
+ clientNum = client - svs.clients;
+ ent = SV_GentityNum( clientNum );
+ ent->s.number = clientNum;
+ client->gentity = ent;
+
+ client->deltaMessage = -1;
+ client->nextSnapshotTime = svs.time; // generate a snapshot immediately
+ client->lastUsercmd = *cmd;
+
+ // call the game begin function
+ VM_Call( gvm, GAME_CLIENT_BEGIN, client - svs.clients );
+}
+
+/*
+============================================================
+
+CLIENT COMMAND EXECUTION
+
+============================================================
+*/
+
+/*
+==================
+SV_CloseDownload
+
+clear/free any download vars
+==================
+*/
+static void SV_CloseDownload( client_t *cl ) {
+ int i;
+
+ // EOF
+ if (cl->download) {
+ FS_FCloseFile( cl->download );
+ }
+ cl->download = 0;
+ *cl->downloadName = 0;
+
+ // Free the temporary buffer space
+ for (i = 0; i < MAX_DOWNLOAD_WINDOW; i++) {
+ if (cl->downloadBlocks[i]) {
+ Z_Free( cl->downloadBlocks[i] );
+ cl->downloadBlocks[i] = NULL;
+ }
+ }
+
+}
+
+/*
+==================
+SV_StopDownload_f
+
+Abort a download if in progress
+==================
+*/
+void SV_StopDownload_f( client_t *cl ) {
+ if (*cl->downloadName)
+ Com_DPrintf( "clientDownload: %d : file \"%s\" aborted\n", cl - svs.clients, cl->downloadName );
+
+ SV_CloseDownload( cl );
+}
+
+/*
+==================
+SV_DoneDownload_f
+
+Downloads are finished
+==================
+*/
+void SV_DoneDownload_f( client_t *cl ) {
+ Com_DPrintf( "clientDownload: %s Done\n", cl->name);
+ // resend the game state to update any clients that entered during the download
+ SV_SendClientGameState(cl);
+}
+
+/*
+==================
+SV_NextDownload_f
+
+The argument will be the last acknowledged block from the client, it should be
+the same as cl->downloadClientBlock
+==================
+*/
+void SV_NextDownload_f( client_t *cl )
+{
+ int block = atoi( Cmd_Argv(1) );
+
+ if (block == cl->downloadClientBlock) {
+ Com_DPrintf( "clientDownload: %d : client acknowledge of block %d\n", cl - svs.clients, block );
+
+ // Find out if we are done. A zero-length block indicates EOF
+ if (cl->downloadBlockSize[cl->downloadClientBlock % MAX_DOWNLOAD_WINDOW] == 0) {
+ Com_Printf( "clientDownload: %d : file \"%s\" completed\n", cl - svs.clients, cl->downloadName );
+ SV_CloseDownload( cl );
+ return;
+ }
+
+ cl->downloadSendTime = svs.time;
+ cl->downloadClientBlock++;
+ return;
+ }
+ // We aren't getting an acknowledge for the correct block, drop the client
+ // FIXME: this is bad... the client will never parse the disconnect message
+ // because the cgame isn't loaded yet
+ SV_DropClient( cl, "broken download" );
+}
+
+/*
+==================
+SV_BeginDownload_f
+==================
+*/
+void SV_BeginDownload_f( client_t *cl ) {
+
+ // Kill any existing download
+ SV_CloseDownload( cl );
+
+ // cl->downloadName is non-zero now, SV_WriteDownloadToClient will see this and open
+ // the file itself
+ Q_strncpyz( cl->downloadName, Cmd_Argv(1), sizeof(cl->downloadName) );
+}
+
+/*
+==================
+SV_WriteDownloadToClient
+
+Check to see if the client wants a file, open it if needed and start pumping the client
+Fill up msg with data
+==================
+*/
+void SV_WriteDownloadToClient( client_t *cl , msg_t *msg )
+{
+ int curindex;
+ int rate;
+ int blockspersnap;
+ int idPack, missionPack;
+ char errorMessage[1024];
+
+ if (!*cl->downloadName)
+ return; // Nothing being downloaded
+
+ if (!cl->download) {
+ // We open the file here
+
+ Com_Printf( "clientDownload: %d : begining \"%s\"\n", cl - svs.clients, cl->downloadName );
+
+ missionPack = FS_idPak(cl->downloadName, "missionpack");
+ idPack = missionPack || FS_idPak(cl->downloadName, "baseq3");
+
+ if ( !sv_allowDownload->integer || idPack ||
+ ( cl->downloadSize = FS_SV_FOpenFileRead( cl->downloadName, &cl->download ) ) <= 0 ) {
+ // cannot auto-download file
+ if (idPack) {
+ Com_Printf("clientDownload: %d : \"%s\" cannot download id pk3 files\n", cl - svs.clients, cl->downloadName);
+ if (missionPack) {
+ Com_sprintf(errorMessage, sizeof(errorMessage), "Cannot autodownload Team Arena file \"%s\"\n"
+ "The Team Arena mission pack can be found in your local game store.", cl->downloadName);
+ }
+ else {
+ Com_sprintf(errorMessage, sizeof(errorMessage), "Cannot autodownload id pk3 file \"%s\"", cl->downloadName);
+ }
+ } else if ( !sv_allowDownload->integer ) {
+ Com_Printf("clientDownload: %d : \"%s\" download disabled", cl - svs.clients, cl->downloadName);
+ if (sv_pure->integer) {
+ Com_sprintf(errorMessage, sizeof(errorMessage), "Could not download \"%s\" because autodownloading is disabled on the server.\n\n"
+ "You will need to get this file elsewhere before you "
+ "can connect to this pure server.\n", cl->downloadName);
+ } else {
+ Com_sprintf(errorMessage, sizeof(errorMessage), "Could not download \"%s\" because autodownloading is disabled on the server.\n\n"
+ "The server you are connecting to is not a pure server, "
+ "set autodownload to No in your settings and you might be "
+ "able to join the game anyway.\n", cl->downloadName);
+ }
+ } else {
+ // NOTE TTimo this is NOT supposed to happen unless bug in our filesystem scheme?
+ // if the pk3 is referenced, it must have been found somewhere in the filesystem
+ Com_Printf("clientDownload: %d : \"%s\" file not found on server\n", cl - svs.clients, cl->downloadName);
+ Com_sprintf(errorMessage, sizeof(errorMessage), "File \"%s\" not found on server for autodownloading.\n", cl->downloadName);
+ }
+ MSG_WriteByte( msg, svc_download );
+ MSG_WriteShort( msg, 0 ); // client is expecting block zero
+ MSG_WriteLong( msg, -1 ); // illegal file size
+ MSG_WriteString( msg, errorMessage );
+
+ *cl->downloadName = 0;
+ return;
+ }
+
+ // Init
+ cl->downloadCurrentBlock = cl->downloadClientBlock = cl->downloadXmitBlock = 0;
+ cl->downloadCount = 0;
+ cl->downloadEOF = qfalse;
+ }
+
+ // Perform any reads that we need to
+ while (cl->downloadCurrentBlock - cl->downloadClientBlock < MAX_DOWNLOAD_WINDOW &&
+ cl->downloadSize != cl->downloadCount) {
+
+ curindex = (cl->downloadCurrentBlock % MAX_DOWNLOAD_WINDOW);
+
+ if (!cl->downloadBlocks[curindex])
+ cl->downloadBlocks[curindex] = Z_Malloc( MAX_DOWNLOAD_BLKSIZE );
+
+ cl->downloadBlockSize[curindex] = FS_Read( cl->downloadBlocks[curindex], MAX_DOWNLOAD_BLKSIZE, cl->download );
+
+ if (cl->downloadBlockSize[curindex] < 0) {
+ // EOF right now
+ cl->downloadCount = cl->downloadSize;
+ break;
+ }
+
+ cl->downloadCount += cl->downloadBlockSize[curindex];
+
+ // Load in next block
+ cl->downloadCurrentBlock++;
+ }
+
+ // Check to see if we have eof condition and add the EOF block
+ if (cl->downloadCount == cl->downloadSize &&
+ !cl->downloadEOF &&
+ cl->downloadCurrentBlock - cl->downloadClientBlock < MAX_DOWNLOAD_WINDOW) {
+
+ cl->downloadBlockSize[cl->downloadCurrentBlock % MAX_DOWNLOAD_WINDOW] = 0;
+ cl->downloadCurrentBlock++;
+
+ cl->downloadEOF = qtrue; // We have added the EOF block
+ }
+
+ // Loop up to window size times based on how many blocks we can fit in the
+ // client snapMsec and rate
+
+ // based on the rate, how many bytes can we fit in the snapMsec time of the client
+ // normal rate / snapshotMsec calculation
+ rate = cl->rate;
+ if ( sv_maxRate->integer ) {
+ if ( sv_maxRate->integer < 1000 ) {
+ Cvar_Set( "sv_MaxRate", "1000" );
+ }
+ if ( sv_maxRate->integer < rate ) {
+ rate = sv_maxRate->integer;
+ }
+ }
+
+ if (!rate) {
+ blockspersnap = 1;
+ } else {
+ blockspersnap = ( (rate * cl->snapshotMsec) / 1000 + MAX_DOWNLOAD_BLKSIZE ) /
+ MAX_DOWNLOAD_BLKSIZE;
+ }
+
+ if (blockspersnap < 0)
+ blockspersnap = 1;
+
+ while (blockspersnap--) {
+
+ // Write out the next section of the file, if we have already reached our window,
+ // automatically start retransmitting
+
+ if (cl->downloadClientBlock == cl->downloadCurrentBlock)
+ return; // Nothing to transmit
+
+ if (cl->downloadXmitBlock == cl->downloadCurrentBlock) {
+ // We have transmitted the complete window, should we start resending?
+
+ //FIXME: This uses a hardcoded one second timeout for lost blocks
+ //the timeout should be based on client rate somehow
+ if (svs.time - cl->downloadSendTime > 1000)
+ cl->downloadXmitBlock = cl->downloadClientBlock;
+ else
+ return;
+ }
+
+ // Send current block
+ curindex = (cl->downloadXmitBlock % MAX_DOWNLOAD_WINDOW);
+
+ MSG_WriteByte( msg, svc_download );
+ MSG_WriteShort( msg, cl->downloadXmitBlock );
+
+ // block zero is special, contains file size
+ if ( cl->downloadXmitBlock == 0 )
+ MSG_WriteLong( msg, cl->downloadSize );
+
+ MSG_WriteShort( msg, cl->downloadBlockSize[curindex] );
+
+ // Write the block
+ if ( cl->downloadBlockSize[curindex] ) {
+ MSG_WriteData( msg, cl->downloadBlocks[curindex], cl->downloadBlockSize[curindex] );
+ }
+
+ Com_DPrintf( "clientDownload: %d : writing block %d\n", cl - svs.clients, cl->downloadXmitBlock );
+
+ // Move on to the next block
+ // It will get sent with next snap shot. The rate will keep us in line.
+ cl->downloadXmitBlock++;
+
+ cl->downloadSendTime = svs.time;
+ }
+}
+
+/*
+=================
+SV_Disconnect_f
+
+The client is going to disconnect, so remove the connection immediately FIXME: move to game?
+=================
+*/
+static void SV_Disconnect_f( client_t *cl ) {
+ SV_DropClient( cl, "disconnected" );
+}
+
+/*
+=================
+SV_VerifyPaks_f
+
+If we are pure, disconnect the client if they do no meet the following conditions:
+
+1. the first two checksums match our view of cgame and ui
+2. there are no any additional checksums that we do not have
+
+This routine would be a bit simpler with a goto but i abstained
+
+=================
+*/
+static void SV_VerifyPaks_f( client_t *cl ) {
+ int nChkSum1, nChkSum2, nClientPaks, nServerPaks, i, j, nCurArg;
+ int nClientChkSum[1024];
+ int nServerChkSum[1024];
+ const char *pPaks, *pArg;
+ qboolean bGood = qtrue;
+
+ // if we are pure, we "expect" the client to load certain things from
+ // certain pk3 files, namely we want the client to have loaded the
+ // ui and cgame that we think should be loaded based on the pure setting
+ //
+ if ( sv_pure->integer != 0 ) {
+
+ bGood = qtrue;
+ nChkSum1 = nChkSum2 = 0;
+ // we run the game, so determine which cgame and ui the client "should" be running
+ bGood = (FS_FileIsInPAK("vm/cgame.qvm", &nChkSum1) == 1);
+ if (bGood)
+ bGood = (FS_FileIsInPAK("vm/ui.qvm", &nChkSum2) == 1);
+
+ nClientPaks = Cmd_Argc();
+
+ // start at arg 2 ( skip serverId cl_paks )
+ nCurArg = 1;
+
+ pArg = Cmd_Argv(nCurArg++);
+ if(!pArg) {
+ bGood = qfalse;
+ }
+ else
+ {
+ // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=475
+ // we may get incoming cp sequences from a previous checksumFeed, which we need to ignore
+ // since serverId is a frame count, it always goes up
+ if (atoi(pArg) < sv.checksumFeedServerId)
+ {
+ Com_DPrintf("ignoring outdated cp command from client %s\n", cl->name);
+ return;
+ }
+ }
+
+ // we basically use this while loop to avoid using 'goto' :)
+ while (bGood) {
+
+ // must be at least 6: "cl_paks cgame ui @ firstref ... numChecksums"
+ // numChecksums is encoded
+ if (nClientPaks < 6) {
+ bGood = qfalse;
+ break;
+ }
+ // verify first to be the cgame checksum
+ pArg = Cmd_Argv(nCurArg++);
+ if (!pArg || *pArg == '@' || atoi(pArg) != nChkSum1 ) {
+ bGood = qfalse;
+ break;
+ }
+ // verify the second to be the ui checksum
+ pArg = Cmd_Argv(nCurArg++);
+ if (!pArg || *pArg == '@' || atoi(pArg) != nChkSum2 ) {
+ bGood = qfalse;
+ break;
+ }
+ // should be sitting at the delimeter now
+ pArg = Cmd_Argv(nCurArg++);
+ if (*pArg != '@') {
+ bGood = qfalse;
+ break;
+ }
+ // store checksums since tokenization is not re-entrant
+ for (i = 0; nCurArg < nClientPaks; i++) {
+ nClientChkSum[i] = atoi(Cmd_Argv(nCurArg++));
+ }
+
+ // store number to compare against (minus one cause the last is the number of checksums)
+ nClientPaks = i - 1;
+
+ // make sure none of the client check sums are the same
+ // so the client can't send 5 the same checksums
+ for (i = 0; i < nClientPaks; i++) {
+ for (j = 0; j < nClientPaks; j++) {
+ if (i == j)
+ continue;
+ if (nClientChkSum[i] == nClientChkSum[j]) {
+ bGood = qfalse;
+ break;
+ }
+ }
+ if (bGood == qfalse)
+ break;
+ }
+ if (bGood == qfalse)
+ break;
+
+ // get the pure checksums of the pk3 files loaded by the server
+ pPaks = FS_LoadedPakPureChecksums();
+ Cmd_TokenizeString( pPaks );
+ nServerPaks = Cmd_Argc();
+ if (nServerPaks > 1024)
+ nServerPaks = 1024;
+
+ for (i = 0; i < nServerPaks; i++) {
+ nServerChkSum[i] = atoi(Cmd_Argv(i));
+ }
+
+ // check if the client has provided any pure checksums of pk3 files not loaded by the server
+ for (i = 0; i < nClientPaks; i++) {
+ for (j = 0; j < nServerPaks; j++) {
+ if (nClientChkSum[i] == nServerChkSum[j]) {
+ break;
+ }
+ }
+ if (j >= nServerPaks) {
+ bGood = qfalse;
+ break;
+ }
+ }
+ if ( bGood == qfalse ) {
+ break;
+ }
+
+ // check if the number of checksums was correct
+ nChkSum1 = sv.checksumFeed;
+ for (i = 0; i < nClientPaks; i++) {
+ nChkSum1 ^= nClientChkSum[i];
+ }
+ nChkSum1 ^= nClientPaks;
+ if (nChkSum1 != nClientChkSum[nClientPaks]) {
+ bGood = qfalse;
+ break;
+ }
+
+ // break out
+ break;
+ }
+
+ cl->gotCP = qtrue;
+
+ if (bGood) {
+ cl->pureAuthentic = 1;
+ }
+ else {
+ cl->pureAuthentic = 0;
+ cl->nextSnapshotTime = -1;
+ cl->state = CS_ACTIVE;
+ SV_SendClientSnapshot( cl );
+ SV_DropClient( cl, "Unpure client detected. Invalid .PK3 files referenced!" );
+ }
+ }
+}
+
+/*
+=================
+SV_ResetPureClient_f
+=================
+*/
+static void SV_ResetPureClient_f( client_t *cl ) {
+ cl->pureAuthentic = 0;
+ cl->gotCP = qfalse;
+}
+
+/*
+=================
+SV_UserinfoChanged
+
+Pull specific info from a newly changed userinfo string
+into a more C friendly form.
+=================
+*/
+void SV_UserinfoChanged( client_t *cl ) {
+ char *val;
+ int i;
+
+ // name for C code
+ Q_strncpyz( cl->name, Info_ValueForKey (cl->userinfo, "name"), sizeof(cl->name) );
+
+ // rate command
+
+ // if the client is on the same subnet as the server and we aren't running an
+ // internet public server, assume they don't need a rate choke
+ if ( Sys_IsLANAddress( cl->netchan.remoteAddress ) && com_dedicated->integer != 2 && sv_lanForceRate->integer == 1) {
+ cl->rate = 99999; // lans should not rate limit
+ } else {
+ val = Info_ValueForKey (cl->userinfo, "rate");
+ if (strlen(val)) {
+ i = atoi(val);
+ cl->rate = i;
+ if (cl->rate < 1000) {
+ cl->rate = 1000;
+ } else if (cl->rate > 90000) {
+ cl->rate = 90000;
+ }
+ } else {
+ cl->rate = 3000;
+ }
+ }
+ val = Info_ValueForKey (cl->userinfo, "handicap");
+ if (strlen(val)) {
+ i = atoi(val);
+ if (i<=0 || i>100 || strlen(val) > 4) {
+ Info_SetValueForKey( cl->userinfo, "handicap", "100" );
+ }
+ }
+
+ // snaps command
+ val = Info_ValueForKey (cl->userinfo, "snaps");
+ if (strlen(val)) {
+ i = atoi(val);
+ if ( i < 1 ) {
+ i = 1;
+ } else if ( i > 30 ) {
+ i = 30;
+ }
+ cl->snapshotMsec = 1000/i;
+ } else {
+ cl->snapshotMsec = 50;
+ }
+
+ // TTimo
+ // maintain the IP information
+ // this is set in SV_DirectConnect (directly on the server, not transmitted), may be lost when client updates it's userinfo
+ // the banning code relies on this being consistently present
+ val = Info_ValueForKey (cl->userinfo, "ip");
+ if (!val[0])
+ {
+ //Com_DPrintf("Maintain IP in userinfo for '%s'\n", cl->name);
+ if ( !NET_IsLocalAddress(cl->netchan.remoteAddress) )
+ Info_SetValueForKey( cl->userinfo, "ip", NET_AdrToString( cl->netchan.remoteAddress ) );
+ else
+ // force the "ip" info key to "localhost" for local clients
+ Info_SetValueForKey( cl->userinfo, "ip", "localhost" );
+ }
+}
+
+
+/*
+==================
+SV_UpdateUserinfo_f
+==================
+*/
+static void SV_UpdateUserinfo_f( client_t *cl ) {
+ Q_strncpyz( cl->userinfo, Cmd_Argv(1), sizeof(cl->userinfo) );
+
+ SV_UserinfoChanged( cl );
+ // call prog code to allow overrides
+ VM_Call( gvm, GAME_CLIENT_USERINFO_CHANGED, cl - svs.clients );
+}
+
+typedef struct {
+ char *name;
+ void (*func)( client_t *cl );
+} ucmd_t;
+
+static ucmd_t ucmds[] = {
+ {"userinfo", SV_UpdateUserinfo_f},
+ {"disconnect", SV_Disconnect_f},
+ {"cp", SV_VerifyPaks_f},
+ {"vdr", SV_ResetPureClient_f},
+ {"download", SV_BeginDownload_f},
+ {"nextdl", SV_NextDownload_f},
+ {"stopdl", SV_StopDownload_f},
+ {"donedl", SV_DoneDownload_f},
+
+ {NULL, NULL}
+};
+
+/*
+==================
+SV_ExecuteClientCommand
+
+Also called by bot code
+==================
+*/
+void SV_ExecuteClientCommand( client_t *cl, const char *s, qboolean clientOK ) {
+ ucmd_t *u;
+ qboolean bProcessed = qfalse;
+
+ Cmd_TokenizeString( s );
+
+ // see if it is a server level command
+ for (u=ucmds ; u->name ; u++) {
+ if (!strcmp (Cmd_Argv(0), u->name) ) {
+ u->func( cl );
+ bProcessed = qtrue;
+ break;
+ }
+ }
+
+ if (clientOK) {
+ // pass unknown strings to the game
+ if (!u->name && sv.state == SS_GAME) {
+ VM_Call( gvm, GAME_CLIENT_COMMAND, cl - svs.clients );
+ }
+ }
+ else if (!bProcessed)
+ Com_DPrintf( "client text ignored for %s: %s\n", cl->name, Cmd_Argv(0) );
+}
+
+/*
+===============
+SV_ClientCommand
+===============
+*/
+static qboolean SV_ClientCommand( client_t *cl, msg_t *msg ) {
+ int seq;
+ const char *s;
+ qboolean clientOk = qtrue;
+
+ seq = MSG_ReadLong( msg );
+ s = MSG_ReadString( msg );
+
+ // see if we have already executed it
+ if ( cl->lastClientCommand >= seq ) {
+ return qtrue;
+ }
+
+ Com_DPrintf( "clientCommand: %s : %i : %s\n", cl->name, seq, s );
+
+ // drop the connection if we have somehow lost commands
+ if ( seq > cl->lastClientCommand + 1 ) {
+ Com_Printf( "Client %s lost %i clientCommands\n", cl->name,
+ seq - cl->lastClientCommand + 1 );
+ SV_DropClient( cl, "Lost reliable commands" );
+ return qfalse;
+ }
+
+ // malicious users may try using too many string commands
+ // to lag other players. If we decide that we want to stall
+ // the command, we will stop processing the rest of the packet,
+ // including the usercmd. This causes flooders to lag themselves
+ // but not other people
+ // We don't do this when the client hasn't been active yet since its
+ // normal to spam a lot of commands when downloading
+ if ( !com_cl_running->integer &&
+ cl->state >= CS_ACTIVE &&
+ sv_floodProtect->integer &&
+ svs.time < cl->nextReliableTime ) {
+ // ignore any other text messages from this client but let them keep playing
+ // TTimo - moved the ignored verbose to the actual processing in SV_ExecuteClientCommand, only printing if the core doesn't intercept
+ clientOk = qfalse;
+ }
+
+ // don't allow another command for one second
+ cl->nextReliableTime = svs.time + 1000;
+
+ SV_ExecuteClientCommand( cl, s, clientOk );
+
+ cl->lastClientCommand = seq;
+ Com_sprintf(cl->lastClientCommandString, sizeof(cl->lastClientCommandString), "%s", s);
+
+ return qtrue; // continue procesing
+}
+
+
+//==================================================================================
+
+
+/*
+==================
+SV_ClientThink
+
+Also called by bot code
+==================
+*/
+void SV_ClientThink (client_t *cl, usercmd_t *cmd) {
+ cl->lastUsercmd = *cmd;
+
+ if ( cl->state != CS_ACTIVE ) {
+ return; // may have been kicked during the last usercmd
+ }
+
+ VM_Call( gvm, GAME_CLIENT_THINK, cl - svs.clients );
+}
+
+/*
+==================
+SV_UserMove
+
+The message usually contains all the movement commands
+that were in the last three packets, so that the information
+in dropped packets can be recovered.
+
+On very fast clients, there may be multiple usercmd packed into
+each of the backup packets.
+==================
+*/
+static void SV_UserMove( client_t *cl, msg_t *msg, qboolean delta ) {
+ int i, key;
+ int cmdCount;
+ usercmd_t nullcmd;
+ usercmd_t cmds[MAX_PACKET_USERCMDS];
+ usercmd_t *cmd, *oldcmd;
+
+ if ( delta ) {
+ cl->deltaMessage = cl->messageAcknowledge;
+ } else {
+ cl->deltaMessage = -1;
+ }
+
+ cmdCount = MSG_ReadByte( msg );
+
+ if ( cmdCount < 1 ) {
+ Com_Printf( "cmdCount < 1\n" );
+ return;
+ }
+
+ if ( cmdCount > MAX_PACKET_USERCMDS ) {
+ Com_Printf( "cmdCount > MAX_PACKET_USERCMDS\n" );
+ return;
+ }
+
+ // use the checksum feed in the key
+ key = sv.checksumFeed;
+ // also use the message acknowledge
+ key ^= cl->messageAcknowledge;
+ // also use the last acknowledged server command in the key
+ key ^= Com_HashKey(cl->reliableCommands[ cl->reliableAcknowledge & (MAX_RELIABLE_COMMANDS-1) ], 32);
+
+ Com_Memset( &nullcmd, 0, sizeof(nullcmd) );
+ oldcmd = &nullcmd;
+ for ( i = 0 ; i < cmdCount ; i++ ) {
+ cmd = &cmds[i];
+ MSG_ReadDeltaUsercmdKey( msg, key, oldcmd, cmd );
+ oldcmd = cmd;
+ }
+
+ // save time for ping calculation
+ cl->frames[ cl->messageAcknowledge & PACKET_MASK ].messageAcked = svs.time;
+
+ // TTimo
+ // catch the no-cp-yet situation before SV_ClientEnterWorld
+ // if CS_ACTIVE, then it's time to trigger a new gamestate emission
+ // if not, then we are getting remaining parasite usermove commands, which we should ignore
+ if (sv_pure->integer != 0 && cl->pureAuthentic == 0 && !cl->gotCP) {
+ if (cl->state == CS_ACTIVE)
+ {
+ // we didn't get a cp yet, don't assume anything and just send the gamestate all over again
+ Com_DPrintf( "%s: didn't get cp command, resending gamestate\n", cl->name, cl->state );
+ SV_SendClientGameState( cl );
+ }
+ return;
+ }
+
+ // if this is the first usercmd we have received
+ // this gamestate, put the client into the world
+ if ( cl->state == CS_PRIMED ) {
+ SV_ClientEnterWorld( cl, &cmds[0] );
+ // the moves can be processed normaly
+ }
+
+ // a bad cp command was sent, drop the client
+ if (sv_pure->integer != 0 && cl->pureAuthentic == 0) {
+ SV_DropClient( cl, "Cannot validate pure client!");
+ return;
+ }
+
+ if ( cl->state != CS_ACTIVE ) {
+ cl->deltaMessage = -1;
+ return;
+ }
+
+ // usually, the first couple commands will be duplicates
+ // of ones we have previously received, but the servertimes
+ // in the commands will cause them to be immediately discarded
+ for ( i = 0 ; i < cmdCount ; i++ ) {
+ // if this is a cmd from before a map_restart ignore it
+ if ( cmds[i].serverTime > cmds[cmdCount-1].serverTime ) {
+ continue;
+ }
+ // extremely lagged or cmd from before a map_restart
+ //if ( cmds[i].serverTime > svs.time + 3000 ) {
+ // continue;
+ //}
+ // don't execute if this is an old cmd which is already executed
+ // these old cmds are included when cl_packetdup > 0
+ if ( cmds[i].serverTime <= cl->lastUsercmd.serverTime ) {
+ continue;
+ }
+ SV_ClientThink (cl, &cmds[ i ]);
+ }
+}
+
+
+/*
+===========================================================================
+
+USER CMD EXECUTION
+
+===========================================================================
+*/
+
+/*
+===================
+SV_ExecuteClientMessage
+
+Parse a client packet
+===================
+*/
+void SV_ExecuteClientMessage( client_t *cl, msg_t *msg ) {
+ int c;
+ int serverId;
+
+ MSG_Bitstream(msg);
+
+ serverId = MSG_ReadLong( msg );
+ cl->messageAcknowledge = MSG_ReadLong( msg );
+
+ if (cl->messageAcknowledge < 0) {
+ // usually only hackers create messages like this
+ // it is more annoying for them to let them hanging
+#ifndef NDEBUG
+ SV_DropClient( cl, "DEBUG: illegible client message" );
+#endif
+ return;
+ }
+
+ cl->reliableAcknowledge = MSG_ReadLong( msg );
+
+ // NOTE: when the client message is fux0red the acknowledgement numbers
+ // can be out of range, this could cause the server to send thousands of server
+ // commands which the server thinks are not yet acknowledged in SV_UpdateServerCommandsToClient
+ if (cl->reliableAcknowledge < cl->reliableSequence - MAX_RELIABLE_COMMANDS) {
+ // usually only hackers create messages like this
+ // it is more annoying for them to let them hanging
+#ifndef NDEBUG
+ SV_DropClient( cl, "DEBUG: illegible client message" );
+#endif
+ cl->reliableAcknowledge = cl->reliableSequence;
+ return;
+ }
+ // if this is a usercmd from a previous gamestate,
+ // ignore it or retransmit the current gamestate
+ //
+ // if the client was downloading, let it stay at whatever serverId and
+ // gamestate it was at. This allows it to keep downloading even when
+ // the gamestate changes. After the download is finished, we'll
+ // notice and send it a new game state
+ //
+ // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=536
+ // don't drop as long as previous command was a nextdl, after a dl is done, downloadName is set back to ""
+ // but we still need to read the next message to move to next download or send gamestate
+ // I don't like this hack though, it must have been working fine at some point, suspecting the fix is somewhere else
+ if ( serverId != sv.serverId && !*cl->downloadName && !strstr(cl->lastClientCommandString, "nextdl") ) {
+ if ( serverId >= sv.restartedServerId && serverId < sv.serverId ) { // TTimo - use a comparison here to catch multiple map_restart
+ // they just haven't caught the map_restart yet
+ Com_DPrintf("%s : ignoring pre map_restart / outdated client message\n", cl->name);
+ return;
+ }
+ // if we can tell that the client has dropped the last
+ // gamestate we sent them, resend it
+ if ( cl->messageAcknowledge > cl->gamestateMessageNum ) {
+ Com_DPrintf( "%s : dropped gamestate, resending\n", cl->name );
+ SV_SendClientGameState( cl );
+ }
+ return;
+ }
+
+ // read optional clientCommand strings
+ do {
+ c = MSG_ReadByte( msg );
+ if ( c == clc_EOF ) {
+ break;
+ }
+ if ( c != clc_clientCommand ) {
+ break;
+ }
+ if ( !SV_ClientCommand( cl, msg ) ) {
+ return; // we couldn't execute it because of the flood protection
+ }
+ if (cl->state == CS_ZOMBIE) {
+ return; // disconnect command
+ }
+ } while ( 1 );
+
+ // read the usercmd_t
+ if ( c == clc_move ) {
+ SV_UserMove( cl, msg, qtrue );
+ } else if ( c == clc_moveNoDelta ) {
+ SV_UserMove( cl, msg, qfalse );
+ } else if ( c != clc_EOF ) {
+ Com_Printf( "WARNING: bad command byte for client %i\n", cl - svs.clients );
+ }
+// if ( msg->readcount != msg->cursize ) {
+// Com_Printf( "WARNING: Junk at end of packet for client %i\n", cl - svs.clients );
+// }
+}
diff --git a/code/server/sv_game.c b/code/server/sv_game.c
new file mode 100755
index 0000000..202994e
--- /dev/null
+++ b/code/server/sv_game.c
@@ -0,0 +1,981 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// sv_game.c -- interface to the game dll
+
+#include "server.h"
+
+#include "../game/botlib.h"
+
+botlib_export_t *botlib_export;
+
+void SV_GameError( const char *string ) {
+ Com_Error( ERR_DROP, "%s", string );
+}
+
+void SV_GamePrint( const char *string ) {
+ Com_Printf( "%s", string );
+}
+
+// these functions must be used instead of pointer arithmetic, because
+// the game allocates gentities with private information after the server shared part
+int SV_NumForGentity( sharedEntity_t *ent ) {
+ int num;
+
+ num = ( (byte *)ent - (byte *)sv.gentities ) / sv.gentitySize;
+
+ return num;
+}
+
+sharedEntity_t *SV_GentityNum( int num ) {
+ sharedEntity_t *ent;
+
+ ent = (sharedEntity_t *)((byte *)sv.gentities + sv.gentitySize*(num));
+
+ return ent;
+}
+
+playerState_t *SV_GameClientNum( int num ) {
+ playerState_t *ps;
+
+ ps = (playerState_t *)((byte *)sv.gameClients + sv.gameClientSize*(num));
+
+ return ps;
+}
+
+svEntity_t *SV_SvEntityForGentity( sharedEntity_t *gEnt ) {
+ if ( !gEnt || gEnt->s.number < 0 || gEnt->s.number >= MAX_GENTITIES ) {
+ Com_Error( ERR_DROP, "SV_SvEntityForGentity: bad gEnt" );
+ }
+ return &sv.svEntities[ gEnt->s.number ];
+}
+
+sharedEntity_t *SV_GEntityForSvEntity( svEntity_t *svEnt ) {
+ int num;
+
+ num = svEnt - sv.svEntities;
+ return SV_GentityNum( num );
+}
+
+/*
+===============
+SV_GameSendServerCommand
+
+Sends a command string to a client
+===============
+*/
+void SV_GameSendServerCommand( int clientNum, const char *text ) {
+ if ( clientNum == -1 ) {
+ SV_SendServerCommand( NULL, "%s", text );
+ } else {
+ if ( clientNum < 0 || clientNum >= sv_maxclients->integer ) {
+ return;
+ }
+ SV_SendServerCommand( svs.clients + clientNum, "%s", text );
+ }
+}
+
+
+/*
+===============
+SV_GameDropClient
+
+Disconnects the client with a message
+===============
+*/
+void SV_GameDropClient( int clientNum, const char *reason ) {
+ if ( clientNum < 0 || clientNum >= sv_maxclients->integer ) {
+ return;
+ }
+ SV_DropClient( svs.clients + clientNum, reason );
+}
+
+
+/*
+=================
+SV_SetBrushModel
+
+sets mins and maxs for inline bmodels
+=================
+*/
+void SV_SetBrushModel( sharedEntity_t *ent, const char *name ) {
+ clipHandle_t h;
+ vec3_t mins, maxs;
+
+ if (!name) {
+ Com_Error( ERR_DROP, "SV_SetBrushModel: NULL" );
+ }
+
+ if (name[0] != '*') {
+ Com_Error( ERR_DROP, "SV_SetBrushModel: %s isn't a brush model", name );
+ }
+
+
+ ent->s.modelindex = atoi( name + 1 );
+
+ h = CM_InlineModel( ent->s.modelindex );
+ CM_ModelBounds( h, mins, maxs );
+ VectorCopy (mins, ent->r.mins);
+ VectorCopy (maxs, ent->r.maxs);
+ ent->r.bmodel = qtrue;
+
+ ent->r.contents = -1; // we don't know exactly what is in the brushes
+
+ SV_LinkEntity( ent ); // FIXME: remove
+}
+
+
+
+/*
+=================
+SV_inPVS
+
+Also checks portalareas so that doors block sight
+=================
+*/
+qboolean SV_inPVS (const vec3_t p1, const vec3_t p2)
+{
+ int leafnum;
+ int cluster;
+ int area1, area2;
+ byte *mask;
+
+ leafnum = CM_PointLeafnum (p1);
+ cluster = CM_LeafCluster (leafnum);
+ area1 = CM_LeafArea (leafnum);
+ mask = CM_ClusterPVS (cluster);
+
+ leafnum = CM_PointLeafnum (p2);
+ cluster = CM_LeafCluster (leafnum);
+ area2 = CM_LeafArea (leafnum);
+ if ( mask && (!(mask[cluster>>3] & (1<<(cluster&7)) ) ) )
+ return qfalse;
+ if (!CM_AreasConnected (area1, area2))
+ return qfalse; // a door blocks sight
+ return qtrue;
+}
+
+
+/*
+=================
+SV_inPVSIgnorePortals
+
+Does NOT check portalareas
+=================
+*/
+qboolean SV_inPVSIgnorePortals( const vec3_t p1, const vec3_t p2)
+{
+ int leafnum;
+ int cluster;
+ int area1, area2;
+ byte *mask;
+
+ leafnum = CM_PointLeafnum (p1);
+ cluster = CM_LeafCluster (leafnum);
+ area1 = CM_LeafArea (leafnum);
+ mask = CM_ClusterPVS (cluster);
+
+ leafnum = CM_PointLeafnum (p2);
+ cluster = CM_LeafCluster (leafnum);
+ area2 = CM_LeafArea (leafnum);
+
+ if ( mask && (!(mask[cluster>>3] & (1<<(cluster&7)) ) ) )
+ return qfalse;
+
+ return qtrue;
+}
+
+
+/*
+========================
+SV_AdjustAreaPortalState
+========================
+*/
+void SV_AdjustAreaPortalState( sharedEntity_t *ent, qboolean open ) {
+ svEntity_t *svEnt;
+
+ svEnt = SV_SvEntityForGentity( ent );
+ if ( svEnt->areanum2 == -1 ) {
+ return;
+ }
+ CM_AdjustAreaPortalState( svEnt->areanum, svEnt->areanum2, open );
+}
+
+
+/*
+==================
+SV_GameAreaEntities
+==================
+*/
+qboolean SV_EntityContact( vec3_t mins, vec3_t maxs, const sharedEntity_t *gEnt, int capsule ) {
+ const float *origin, *angles;
+ clipHandle_t ch;
+ trace_t trace;
+
+ // check for exact collision
+ origin = gEnt->r.currentOrigin;
+ angles = gEnt->r.currentAngles;
+
+ ch = SV_ClipHandleForEntity( gEnt );
+ CM_TransformedBoxTrace ( &trace, vec3_origin, vec3_origin, mins, maxs,
+ ch, -1, origin, angles, capsule );
+
+ return trace.startsolid;
+}
+
+
+/*
+===============
+SV_GetServerinfo
+
+===============
+*/
+void SV_GetServerinfo( char *buffer, int bufferSize ) {
+ if ( bufferSize < 1 ) {
+ Com_Error( ERR_DROP, "SV_GetServerinfo: bufferSize == %i", bufferSize );
+ }
+ Q_strncpyz( buffer, Cvar_InfoString( CVAR_SERVERINFO ), bufferSize );
+}
+
+/*
+===============
+SV_LocateGameData
+
+===============
+*/
+void SV_LocateGameData( sharedEntity_t *gEnts, int numGEntities, int sizeofGEntity_t,
+ playerState_t *clients, int sizeofGameClient ) {
+ sv.gentities = gEnts;
+ sv.gentitySize = sizeofGEntity_t;
+ sv.num_entities = numGEntities;
+
+ sv.gameClients = clients;
+ sv.gameClientSize = sizeofGameClient;
+}
+
+
+/*
+===============
+SV_GetUsercmd
+
+===============
+*/
+void SV_GetUsercmd( int clientNum, usercmd_t *cmd ) {
+ if ( clientNum < 0 || clientNum >= sv_maxclients->integer ) {
+ Com_Error( ERR_DROP, "SV_GetUsercmd: bad clientNum:%i", clientNum );
+ }
+ *cmd = svs.clients[clientNum].lastUsercmd;
+}
+
+//==============================================
+
+static int FloatAsInt( float f ) {
+ union
+ {
+ int i;
+ float f;
+ } temp;
+
+ temp.f = f;
+ return temp.i;
+}
+
+/*
+====================
+SV_GameSystemCalls
+
+The module is making a system call
+====================
+*/
+//rcg010207 - see my comments in VM_DllSyscall(), in qcommon/vm.c ...
+#if ((defined __linux__) && (defined __powerpc__))
+#define VMA(x) ((void *) args[x])
+#else
+#define VMA(x) VM_ArgPtr(args[x])
+#endif
+
+#define VMF(x) ((float *)args)[x]
+
+int SV_GameSystemCalls( int *args ) {
+ switch( args[0] ) {
+ case G_PRINT:
+ Com_Printf( "%s", VMA(1) );
+ return 0;
+ case G_ERROR:
+ Com_Error( ERR_DROP, "%s", VMA(1) );
+ return 0;
+ case G_MILLISECONDS:
+ return Sys_Milliseconds();
+ case G_CVAR_REGISTER:
+ Cvar_Register( VMA(1), VMA(2), VMA(3), args[4] );
+ return 0;
+ case G_CVAR_UPDATE:
+ Cvar_Update( VMA(1) );
+ return 0;
+ case G_CVAR_SET:
+ Cvar_Set( (const char *)VMA(1), (const char *)VMA(2) );
+ return 0;
+ case G_CVAR_VARIABLE_INTEGER_VALUE:
+ return Cvar_VariableIntegerValue( (const char *)VMA(1) );
+ case G_CVAR_VARIABLE_STRING_BUFFER:
+ Cvar_VariableStringBuffer( VMA(1), VMA(2), args[3] );
+ return 0;
+ case G_ARGC:
+ return Cmd_Argc();
+ case G_ARGV:
+ Cmd_ArgvBuffer( args[1], VMA(2), args[3] );
+ return 0;
+ case G_SEND_CONSOLE_COMMAND:
+ Cbuf_ExecuteText( args[1], VMA(2) );
+ return 0;
+
+ case G_FS_FOPEN_FILE:
+ return FS_FOpenFileByMode( VMA(1), VMA(2), args[3] );
+ case G_FS_READ:
+ FS_Read2( VMA(1), args[2], args[3] );
+ return 0;
+ case G_FS_WRITE:
+ FS_Write( VMA(1), args[2], args[3] );
+ return 0;
+ case G_FS_FCLOSE_FILE:
+ FS_FCloseFile( args[1] );
+ return 0;
+ case G_FS_GETFILELIST:
+ return FS_GetFileList( VMA(1), VMA(2), VMA(3), args[4] );
+ case G_FS_SEEK:
+ return FS_Seek( args[1], args[2], args[3] );
+
+ case G_LOCATE_GAME_DATA:
+ SV_LocateGameData( VMA(1), args[2], args[3], VMA(4), args[5] );
+ return 0;
+ case G_DROP_CLIENT:
+ SV_GameDropClient( args[1], VMA(2) );
+ return 0;
+ case G_SEND_SERVER_COMMAND:
+ SV_GameSendServerCommand( args[1], VMA(2) );
+ return 0;
+ case G_LINKENTITY:
+ SV_LinkEntity( VMA(1) );
+ return 0;
+ case G_UNLINKENTITY:
+ SV_UnlinkEntity( VMA(1) );
+ return 0;
+ case G_ENTITIES_IN_BOX:
+ return SV_AreaEntities( VMA(1), VMA(2), VMA(3), args[4] );
+ case G_ENTITY_CONTACT:
+ return SV_EntityContact( VMA(1), VMA(2), VMA(3), /*int capsule*/ qfalse );
+ case G_ENTITY_CONTACTCAPSULE:
+ return SV_EntityContact( VMA(1), VMA(2), VMA(3), /*int capsule*/ qtrue );
+ case G_TRACE:
+ SV_Trace( VMA(1), VMA(2), VMA(3), VMA(4), VMA(5), args[6], args[7], /*int capsule*/ qfalse );
+ return 0;
+ case G_TRACECAPSULE:
+ SV_Trace( VMA(1), VMA(2), VMA(3), VMA(4), VMA(5), args[6], args[7], /*int capsule*/ qtrue );
+ return 0;
+ case G_POINT_CONTENTS:
+ return SV_PointContents( VMA(1), args[2] );
+ case G_SET_BRUSH_MODEL:
+ SV_SetBrushModel( VMA(1), VMA(2) );
+ return 0;
+ case G_IN_PVS:
+ return SV_inPVS( VMA(1), VMA(2) );
+ case G_IN_PVS_IGNORE_PORTALS:
+ return SV_inPVSIgnorePortals( VMA(1), VMA(2) );
+
+ case G_SET_CONFIGSTRING:
+ SV_SetConfigstring( args[1], VMA(2) );
+ return 0;
+ case G_GET_CONFIGSTRING:
+ SV_GetConfigstring( args[1], VMA(2), args[3] );
+ return 0;
+ case G_SET_USERINFO:
+ SV_SetUserinfo( args[1], VMA(2) );
+ return 0;
+ case G_GET_USERINFO:
+ SV_GetUserinfo( args[1], VMA(2), args[3] );
+ return 0;
+ case G_GET_SERVERINFO:
+ SV_GetServerinfo( VMA(1), args[2] );
+ return 0;
+ case G_ADJUST_AREA_PORTAL_STATE:
+ SV_AdjustAreaPortalState( VMA(1), args[2] );
+ return 0;
+ case G_AREAS_CONNECTED:
+ return CM_AreasConnected( args[1], args[2] );
+
+ case G_BOT_ALLOCATE_CLIENT:
+ return SV_BotAllocateClient();
+ case G_BOT_FREE_CLIENT:
+ SV_BotFreeClient( args[1] );
+ return 0;
+
+ case G_GET_USERCMD:
+ SV_GetUsercmd( args[1], VMA(2) );
+ return 0;
+ case G_GET_ENTITY_TOKEN:
+ {
+ const char *s;
+
+ s = COM_Parse( &sv.entityParsePoint );
+ Q_strncpyz( VMA(1), s, args[2] );
+ if ( !sv.entityParsePoint && !s[0] ) {
+ return qfalse;
+ } else {
+ return qtrue;
+ }
+ }
+
+ case G_DEBUG_POLYGON_CREATE:
+ return BotImport_DebugPolygonCreate( args[1], args[2], VMA(3) );
+ case G_DEBUG_POLYGON_DELETE:
+ BotImport_DebugPolygonDelete( args[1] );
+ return 0;
+ case G_REAL_TIME:
+ return Com_RealTime( VMA(1) );
+ case G_SNAPVECTOR:
+ Sys_SnapVector( VMA(1) );
+ return 0;
+
+ //====================================
+
+ case BOTLIB_SETUP:
+ return SV_BotLibSetup();
+ case BOTLIB_SHUTDOWN:
+ return SV_BotLibShutdown();
+ case BOTLIB_LIBVAR_SET:
+ return botlib_export->BotLibVarSet( VMA(1), VMA(2) );
+ case BOTLIB_LIBVAR_GET:
+ return botlib_export->BotLibVarGet( VMA(1), VMA(2), args[3] );
+
+ case BOTLIB_PC_ADD_GLOBAL_DEFINE:
+ return botlib_export->PC_AddGlobalDefine( VMA(1) );
+ case BOTLIB_PC_LOAD_SOURCE:
+ return botlib_export->PC_LoadSourceHandle( VMA(1) );
+ case BOTLIB_PC_FREE_SOURCE:
+ return botlib_export->PC_FreeSourceHandle( args[1] );
+ case BOTLIB_PC_READ_TOKEN:
+ return botlib_export->PC_ReadTokenHandle( args[1], VMA(2) );
+ case BOTLIB_PC_SOURCE_FILE_AND_LINE:
+ return botlib_export->PC_SourceFileAndLine( args[1], VMA(2), VMA(3) );
+
+ case BOTLIB_START_FRAME:
+ return botlib_export->BotLibStartFrame( VMF(1) );
+ case BOTLIB_LOAD_MAP:
+ return botlib_export->BotLibLoadMap( VMA(1) );
+ case BOTLIB_UPDATENTITY:
+ return botlib_export->BotLibUpdateEntity( args[1], VMA(2) );
+ case BOTLIB_TEST:
+ return botlib_export->Test( args[1], VMA(2), VMA(3), VMA(4) );
+
+ case BOTLIB_GET_SNAPSHOT_ENTITY:
+ return SV_BotGetSnapshotEntity( args[1], args[2] );
+ case BOTLIB_GET_CONSOLE_MESSAGE:
+ return SV_BotGetConsoleMessage( args[1], VMA(2), args[3] );
+ case BOTLIB_USER_COMMAND:
+ SV_ClientThink( &svs.clients[args[1]], VMA(2) );
+ return 0;
+
+ case BOTLIB_AAS_BBOX_AREAS:
+ return botlib_export->aas.AAS_BBoxAreas( VMA(1), VMA(2), VMA(3), args[4] );
+ case BOTLIB_AAS_AREA_INFO:
+ return botlib_export->aas.AAS_AreaInfo( args[1], VMA(2) );
+ case BOTLIB_AAS_ALTERNATIVE_ROUTE_GOAL:
+ return botlib_export->aas.AAS_AlternativeRouteGoals( VMA(1), args[2], VMA(3), args[4], args[5], VMA(6), args[7], args[8] );
+ case BOTLIB_AAS_ENTITY_INFO:
+ botlib_export->aas.AAS_EntityInfo( args[1], VMA(2) );
+ return 0;
+
+ case BOTLIB_AAS_INITIALIZED:
+ return botlib_export->aas.AAS_Initialized();
+ case BOTLIB_AAS_PRESENCE_TYPE_BOUNDING_BOX:
+ botlib_export->aas.AAS_PresenceTypeBoundingBox( args[1], VMA(2), VMA(3) );
+ return 0;
+ case BOTLIB_AAS_TIME:
+ return FloatAsInt( botlib_export->aas.AAS_Time() );
+
+ case BOTLIB_AAS_POINT_AREA_NUM:
+ return botlib_export->aas.AAS_PointAreaNum( VMA(1) );
+ case BOTLIB_AAS_POINT_REACHABILITY_AREA_INDEX:
+ return botlib_export->aas.AAS_PointReachabilityAreaIndex( VMA(1) );
+ case BOTLIB_AAS_TRACE_AREAS:
+ return botlib_export->aas.AAS_TraceAreas( VMA(1), VMA(2), VMA(3), VMA(4), args[5] );
+
+ case BOTLIB_AAS_POINT_CONTENTS:
+ return botlib_export->aas.AAS_PointContents( VMA(1) );
+ case BOTLIB_AAS_NEXT_BSP_ENTITY:
+ return botlib_export->aas.AAS_NextBSPEntity( args[1] );
+ case BOTLIB_AAS_VALUE_FOR_BSP_EPAIR_KEY:
+ return botlib_export->aas.AAS_ValueForBSPEpairKey( args[1], VMA(2), VMA(3), args[4] );
+ case BOTLIB_AAS_VECTOR_FOR_BSP_EPAIR_KEY:
+ return botlib_export->aas.AAS_VectorForBSPEpairKey( args[1], VMA(2), VMA(3) );
+ case BOTLIB_AAS_FLOAT_FOR_BSP_EPAIR_KEY:
+ return botlib_export->aas.AAS_FloatForBSPEpairKey( args[1], VMA(2), VMA(3) );
+ case BOTLIB_AAS_INT_FOR_BSP_EPAIR_KEY:
+ return botlib_export->aas.AAS_IntForBSPEpairKey( args[1], VMA(2), VMA(3) );
+
+ case BOTLIB_AAS_AREA_REACHABILITY:
+ return botlib_export->aas.AAS_AreaReachability( args[1] );
+
+ case BOTLIB_AAS_AREA_TRAVEL_TIME_TO_GOAL_AREA:
+ return botlib_export->aas.AAS_AreaTravelTimeToGoalArea( args[1], VMA(2), args[3], args[4] );
+ case BOTLIB_AAS_ENABLE_ROUTING_AREA:
+ return botlib_export->aas.AAS_EnableRoutingArea( args[1], args[2] );
+ case BOTLIB_AAS_PREDICT_ROUTE:
+ return botlib_export->aas.AAS_PredictRoute( VMA(1), args[2], VMA(3), args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11] );
+
+ case BOTLIB_AAS_SWIMMING:
+ return botlib_export->aas.AAS_Swimming( VMA(1) );
+ case BOTLIB_AAS_PREDICT_CLIENT_MOVEMENT:
+ return botlib_export->aas.AAS_PredictClientMovement( VMA(1), args[2], VMA(3), args[4], args[5],
+ VMA(6), VMA(7), args[8], args[9], VMF(10), args[11], args[12], args[13] );
+
+ case BOTLIB_EA_SAY:
+ botlib_export->ea.EA_Say( args[1], VMA(2) );
+ return 0;
+ case BOTLIB_EA_SAY_TEAM:
+ botlib_export->ea.EA_SayTeam( args[1], VMA(2) );
+ return 0;
+ case BOTLIB_EA_COMMAND:
+ botlib_export->ea.EA_Command( args[1], VMA(2) );
+ return 0;
+
+ case BOTLIB_EA_ACTION:
+ botlib_export->ea.EA_Action( args[1], args[2] );
+ break;
+ case BOTLIB_EA_GESTURE:
+ botlib_export->ea.EA_Gesture( args[1] );
+ return 0;
+ case BOTLIB_EA_TALK:
+ botlib_export->ea.EA_Talk( args[1] );
+ return 0;
+ case BOTLIB_EA_ATTACK:
+ botlib_export->ea.EA_Attack( args[1] );
+ return 0;
+ case BOTLIB_EA_USE:
+ botlib_export->ea.EA_Use( args[1] );
+ return 0;
+ case BOTLIB_EA_RESPAWN:
+ botlib_export->ea.EA_Respawn( args[1] );
+ return 0;
+ case BOTLIB_EA_CROUCH:
+ botlib_export->ea.EA_Crouch( args[1] );
+ return 0;
+ case BOTLIB_EA_MOVE_UP:
+ botlib_export->ea.EA_MoveUp( args[1] );
+ return 0;
+ case BOTLIB_EA_MOVE_DOWN:
+ botlib_export->ea.EA_MoveDown( args[1] );
+ return 0;
+ case BOTLIB_EA_MOVE_FORWARD:
+ botlib_export->ea.EA_MoveForward( args[1] );
+ return 0;
+ case BOTLIB_EA_MOVE_BACK:
+ botlib_export->ea.EA_MoveBack( args[1] );
+ return 0;
+ case BOTLIB_EA_MOVE_LEFT:
+ botlib_export->ea.EA_MoveLeft( args[1] );
+ return 0;
+ case BOTLIB_EA_MOVE_RIGHT:
+ botlib_export->ea.EA_MoveRight( args[1] );
+ return 0;
+
+ case BOTLIB_EA_SELECT_WEAPON:
+ botlib_export->ea.EA_SelectWeapon( args[1], args[2] );
+ return 0;
+ case BOTLIB_EA_JUMP:
+ botlib_export->ea.EA_Jump( args[1] );
+ return 0;
+ case BOTLIB_EA_DELAYED_JUMP:
+ botlib_export->ea.EA_DelayedJump( args[1] );
+ return 0;
+ case BOTLIB_EA_MOVE:
+ botlib_export->ea.EA_Move( args[1], VMA(2), VMF(3) );
+ return 0;
+ case BOTLIB_EA_VIEW:
+ botlib_export->ea.EA_View( args[1], VMA(2) );
+ return 0;
+
+ case BOTLIB_EA_END_REGULAR:
+ botlib_export->ea.EA_EndRegular( args[1], VMF(2) );
+ return 0;
+ case BOTLIB_EA_GET_INPUT:
+ botlib_export->ea.EA_GetInput( args[1], VMF(2), VMA(3) );
+ return 0;
+ case BOTLIB_EA_RESET_INPUT:
+ botlib_export->ea.EA_ResetInput( args[1] );
+ return 0;
+
+ case BOTLIB_AI_LOAD_CHARACTER:
+ return botlib_export->ai.BotLoadCharacter( VMA(1), VMF(2) );
+ case BOTLIB_AI_FREE_CHARACTER:
+ botlib_export->ai.BotFreeCharacter( args[1] );
+ return 0;
+ case BOTLIB_AI_CHARACTERISTIC_FLOAT:
+ return FloatAsInt( botlib_export->ai.Characteristic_Float( args[1], args[2] ) );
+ case BOTLIB_AI_CHARACTERISTIC_BFLOAT:
+ return FloatAsInt( botlib_export->ai.Characteristic_BFloat( args[1], args[2], VMF(3), VMF(4) ) );
+ case BOTLIB_AI_CHARACTERISTIC_INTEGER:
+ return botlib_export->ai.Characteristic_Integer( args[1], args[2] );
+ case BOTLIB_AI_CHARACTERISTIC_BINTEGER:
+ return botlib_export->ai.Characteristic_BInteger( args[1], args[2], args[3], args[4] );
+ case BOTLIB_AI_CHARACTERISTIC_STRING:
+ botlib_export->ai.Characteristic_String( args[1], args[2], VMA(3), args[4] );
+ return 0;
+
+ case BOTLIB_AI_ALLOC_CHAT_STATE:
+ return botlib_export->ai.BotAllocChatState();
+ case BOTLIB_AI_FREE_CHAT_STATE:
+ botlib_export->ai.BotFreeChatState( args[1] );
+ return 0;
+ case BOTLIB_AI_QUEUE_CONSOLE_MESSAGE:
+ botlib_export->ai.BotQueueConsoleMessage( args[1], args[2], VMA(3) );
+ return 0;
+ case BOTLIB_AI_REMOVE_CONSOLE_MESSAGE:
+ botlib_export->ai.BotRemoveConsoleMessage( args[1], args[2] );
+ return 0;
+ case BOTLIB_AI_NEXT_CONSOLE_MESSAGE:
+ return botlib_export->ai.BotNextConsoleMessage( args[1], VMA(2) );
+ case BOTLIB_AI_NUM_CONSOLE_MESSAGE:
+ return botlib_export->ai.BotNumConsoleMessages( args[1] );
+ case BOTLIB_AI_INITIAL_CHAT:
+ botlib_export->ai.BotInitialChat( args[1], VMA(2), args[3], VMA(4), VMA(5), VMA(6), VMA(7), VMA(8), VMA(9), VMA(10), VMA(11) );
+ return 0;
+ case BOTLIB_AI_NUM_INITIAL_CHATS:
+ return botlib_export->ai.BotNumInitialChats( args[1], VMA(2) );
+ case BOTLIB_AI_REPLY_CHAT:
+ return botlib_export->ai.BotReplyChat( args[1], VMA(2), args[3], args[4], VMA(5), VMA(6), VMA(7), VMA(8), VMA(9), VMA(10), VMA(11), VMA(12) );
+ case BOTLIB_AI_CHAT_LENGTH:
+ return botlib_export->ai.BotChatLength( args[1] );
+ case BOTLIB_AI_ENTER_CHAT:
+ botlib_export->ai.BotEnterChat( args[1], args[2], args[3] );
+ return 0;
+ case BOTLIB_AI_GET_CHAT_MESSAGE:
+ botlib_export->ai.BotGetChatMessage( args[1], VMA(2), args[3] );
+ return 0;
+ case BOTLIB_AI_STRING_CONTAINS:
+ return botlib_export->ai.StringContains( VMA(1), VMA(2), args[3] );
+ case BOTLIB_AI_FIND_MATCH:
+ return botlib_export->ai.BotFindMatch( VMA(1), VMA(2), args[3] );
+ case BOTLIB_AI_MATCH_VARIABLE:
+ botlib_export->ai.BotMatchVariable( VMA(1), args[2], VMA(3), args[4] );
+ return 0;
+ case BOTLIB_AI_UNIFY_WHITE_SPACES:
+ botlib_export->ai.UnifyWhiteSpaces( VMA(1) );
+ return 0;
+ case BOTLIB_AI_REPLACE_SYNONYMS:
+ botlib_export->ai.BotReplaceSynonyms( VMA(1), args[2] );
+ return 0;
+ case BOTLIB_AI_LOAD_CHAT_FILE:
+ return botlib_export->ai.BotLoadChatFile( args[1], VMA(2), VMA(3) );
+ case BOTLIB_AI_SET_CHAT_GENDER:
+ botlib_export->ai.BotSetChatGender( args[1], args[2] );
+ return 0;
+ case BOTLIB_AI_SET_CHAT_NAME:
+ botlib_export->ai.BotSetChatName( args[1], VMA(2), args[3] );
+ return 0;
+
+ case BOTLIB_AI_RESET_GOAL_STATE:
+ botlib_export->ai.BotResetGoalState( args[1] );
+ return 0;
+ case BOTLIB_AI_RESET_AVOID_GOALS:
+ botlib_export->ai.BotResetAvoidGoals( args[1] );
+ return 0;
+ case BOTLIB_AI_REMOVE_FROM_AVOID_GOALS:
+ botlib_export->ai.BotRemoveFromAvoidGoals( args[1], args[2] );
+ return 0;
+ case BOTLIB_AI_PUSH_GOAL:
+ botlib_export->ai.BotPushGoal( args[1], VMA(2) );
+ return 0;
+ case BOTLIB_AI_POP_GOAL:
+ botlib_export->ai.BotPopGoal( args[1] );
+ return 0;
+ case BOTLIB_AI_EMPTY_GOAL_STACK:
+ botlib_export->ai.BotEmptyGoalStack( args[1] );
+ return 0;
+ case BOTLIB_AI_DUMP_AVOID_GOALS:
+ botlib_export->ai.BotDumpAvoidGoals( args[1] );
+ return 0;
+ case BOTLIB_AI_DUMP_GOAL_STACK:
+ botlib_export->ai.BotDumpGoalStack( args[1] );
+ return 0;
+ case BOTLIB_AI_GOAL_NAME:
+ botlib_export->ai.BotGoalName( args[1], VMA(2), args[3] );
+ return 0;
+ case BOTLIB_AI_GET_TOP_GOAL:
+ return botlib_export->ai.BotGetTopGoal( args[1], VMA(2) );
+ case BOTLIB_AI_GET_SECOND_GOAL:
+ return botlib_export->ai.BotGetSecondGoal( args[1], VMA(2) );
+ case BOTLIB_AI_CHOOSE_LTG_ITEM:
+ return botlib_export->ai.BotChooseLTGItem( args[1], VMA(2), VMA(3), args[4] );
+ case BOTLIB_AI_CHOOSE_NBG_ITEM:
+ return botlib_export->ai.BotChooseNBGItem( args[1], VMA(2), VMA(3), args[4], VMA(5), VMF(6) );
+ case BOTLIB_AI_TOUCHING_GOAL:
+ return botlib_export->ai.BotTouchingGoal( VMA(1), VMA(2) );
+ case BOTLIB_AI_ITEM_GOAL_IN_VIS_BUT_NOT_VISIBLE:
+ return botlib_export->ai.BotItemGoalInVisButNotVisible( args[1], VMA(2), VMA(3), VMA(4) );
+ case BOTLIB_AI_GET_LEVEL_ITEM_GOAL:
+ return botlib_export->ai.BotGetLevelItemGoal( args[1], VMA(2), VMA(3) );
+ case BOTLIB_AI_GET_NEXT_CAMP_SPOT_GOAL:
+ return botlib_export->ai.BotGetNextCampSpotGoal( args[1], VMA(2) );
+ case BOTLIB_AI_GET_MAP_LOCATION_GOAL:
+ return botlib_export->ai.BotGetMapLocationGoal( VMA(1), VMA(2) );
+ case BOTLIB_AI_AVOID_GOAL_TIME:
+ return FloatAsInt( botlib_export->ai.BotAvoidGoalTime( args[1], args[2] ) );
+ case BOTLIB_AI_SET_AVOID_GOAL_TIME:
+ botlib_export->ai.BotSetAvoidGoalTime( args[1], args[2], VMF(3));
+ return 0;
+ case BOTLIB_AI_INIT_LEVEL_ITEMS:
+ botlib_export->ai.BotInitLevelItems();
+ return 0;
+ case BOTLIB_AI_UPDATE_ENTITY_ITEMS:
+ botlib_export->ai.BotUpdateEntityItems();
+ return 0;
+ case BOTLIB_AI_LOAD_ITEM_WEIGHTS:
+ return botlib_export->ai.BotLoadItemWeights( args[1], VMA(2) );
+ case BOTLIB_AI_FREE_ITEM_WEIGHTS:
+ botlib_export->ai.BotFreeItemWeights( args[1] );
+ return 0;
+ case BOTLIB_AI_INTERBREED_GOAL_FUZZY_LOGIC:
+ botlib_export->ai.BotInterbreedGoalFuzzyLogic( args[1], args[2], args[3] );
+ return 0;
+ case BOTLIB_AI_SAVE_GOAL_FUZZY_LOGIC:
+ botlib_export->ai.BotSaveGoalFuzzyLogic( args[1], VMA(2) );
+ return 0;
+ case BOTLIB_AI_MUTATE_GOAL_FUZZY_LOGIC:
+ botlib_export->ai.BotMutateGoalFuzzyLogic( args[1], VMF(2) );
+ return 0;
+ case BOTLIB_AI_ALLOC_GOAL_STATE:
+ return botlib_export->ai.BotAllocGoalState( args[1] );
+ case BOTLIB_AI_FREE_GOAL_STATE:
+ botlib_export->ai.BotFreeGoalState( args[1] );
+ return 0;
+
+ case BOTLIB_AI_RESET_MOVE_STATE:
+ botlib_export->ai.BotResetMoveState( args[1] );
+ return 0;
+ case BOTLIB_AI_ADD_AVOID_SPOT:
+ botlib_export->ai.BotAddAvoidSpot( args[1], VMA(2), VMF(3), args[4] );
+ return 0;
+ case BOTLIB_AI_MOVE_TO_GOAL:
+ botlib_export->ai.BotMoveToGoal( VMA(1), args[2], VMA(3), args[4] );
+ return 0;
+ case BOTLIB_AI_MOVE_IN_DIRECTION:
+ return botlib_export->ai.BotMoveInDirection( args[1], VMA(2), VMF(3), args[4] );
+ case BOTLIB_AI_RESET_AVOID_REACH:
+ botlib_export->ai.BotResetAvoidReach( args[1] );
+ return 0;
+ case BOTLIB_AI_RESET_LAST_AVOID_REACH:
+ botlib_export->ai.BotResetLastAvoidReach( args[1] );
+ return 0;
+ case BOTLIB_AI_REACHABILITY_AREA:
+ return botlib_export->ai.BotReachabilityArea( VMA(1), args[2] );
+ case BOTLIB_AI_MOVEMENT_VIEW_TARGET:
+ return botlib_export->ai.BotMovementViewTarget( args[1], VMA(2), args[3], VMF(4), VMA(5) );
+ case BOTLIB_AI_PREDICT_VISIBLE_POSITION:
+ return botlib_export->ai.BotPredictVisiblePosition( VMA(1), args[2], VMA(3), args[4], VMA(5) );
+ case BOTLIB_AI_ALLOC_MOVE_STATE:
+ return botlib_export->ai.BotAllocMoveState();
+ case BOTLIB_AI_FREE_MOVE_STATE:
+ botlib_export->ai.BotFreeMoveState( args[1] );
+ return 0;
+ case BOTLIB_AI_INIT_MOVE_STATE:
+ botlib_export->ai.BotInitMoveState( args[1], VMA(2) );
+ return 0;
+
+ case BOTLIB_AI_CHOOSE_BEST_FIGHT_WEAPON:
+ return botlib_export->ai.BotChooseBestFightWeapon( args[1], VMA(2) );
+ case BOTLIB_AI_GET_WEAPON_INFO:
+ botlib_export->ai.BotGetWeaponInfo( args[1], args[2], VMA(3) );
+ return 0;
+ case BOTLIB_AI_LOAD_WEAPON_WEIGHTS:
+ return botlib_export->ai.BotLoadWeaponWeights( args[1], VMA(2) );
+ case BOTLIB_AI_ALLOC_WEAPON_STATE:
+ return botlib_export->ai.BotAllocWeaponState();
+ case BOTLIB_AI_FREE_WEAPON_STATE:
+ botlib_export->ai.BotFreeWeaponState( args[1] );
+ return 0;
+ case BOTLIB_AI_RESET_WEAPON_STATE:
+ botlib_export->ai.BotResetWeaponState( args[1] );
+ return 0;
+
+ case BOTLIB_AI_GENETIC_PARENTS_AND_CHILD_SELECTION:
+ return botlib_export->ai.GeneticParentsAndChildSelection(args[1], VMA(2), VMA(3), VMA(4), VMA(5));
+
+ case TRAP_MEMSET:
+ Com_Memset( VMA(1), args[2], args[3] );
+ return 0;
+
+ case TRAP_MEMCPY:
+ Com_Memcpy( VMA(1), VMA(2), args[3] );
+ return 0;
+
+ case TRAP_STRNCPY:
+ return (int)strncpy( VMA(1), VMA(2), args[3] );
+
+ case TRAP_SIN:
+ return FloatAsInt( sin( VMF(1) ) );
+
+ case TRAP_COS:
+ return FloatAsInt( cos( VMF(1) ) );
+
+ case TRAP_ATAN2:
+ return FloatAsInt( atan2( VMF(1), VMF(2) ) );
+
+ case TRAP_SQRT:
+ return FloatAsInt( sqrt( VMF(1) ) );
+
+ case TRAP_MATRIXMULTIPLY:
+ MatrixMultiply( VMA(1), VMA(2), VMA(3) );
+ return 0;
+
+ case TRAP_ANGLEVECTORS:
+ AngleVectors( VMA(1), VMA(2), VMA(3), VMA(4) );
+ return 0;
+
+ case TRAP_PERPENDICULARVECTOR:
+ PerpendicularVector( VMA(1), VMA(2) );
+ return 0;
+
+ case TRAP_FLOOR:
+ return FloatAsInt( floor( VMF(1) ) );
+
+ case TRAP_CEIL:
+ return FloatAsInt( ceil( VMF(1) ) );
+
+
+ default:
+ Com_Error( ERR_DROP, "Bad game system trap: %i", args[0] );
+ }
+ return -1;
+}
+
+/*
+===============
+SV_ShutdownGameProgs
+
+Called every time a map changes
+===============
+*/
+void SV_ShutdownGameProgs( void ) {
+ if ( !gvm ) {
+ return;
+ }
+ VM_Call( gvm, GAME_SHUTDOWN, qfalse );
+ VM_Free( gvm );
+ gvm = NULL;
+}
+
+/*
+==================
+SV_InitGameVM
+
+Called for both a full init and a restart
+==================
+*/
+static void SV_InitGameVM( qboolean restart ) {
+ int i;
+
+ // start the entity parsing at the beginning
+ sv.entityParsePoint = CM_EntityString();
+
+ // clear all gentity pointers that might still be set from
+ // a previous level
+ // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=522
+ // now done before GAME_INIT call
+ for ( i = 0 ; i < sv_maxclients->integer ; i++ ) {
+ svs.clients[i].gentity = NULL;
+ }
+
+ // use the current msec count for a random seed
+ // init for this gamestate
+ VM_Call( gvm, GAME_INIT, svs.time, Com_Milliseconds(), restart );
+}
+
+
+
+/*
+===================
+SV_RestartGameProgs
+
+Called on a map_restart, but not on a normal map change
+===================
+*/
+void SV_RestartGameProgs( void ) {
+ if ( !gvm ) {
+ return;
+ }
+ VM_Call( gvm, GAME_SHUTDOWN, qtrue );
+
+ // do a restart instead of a free
+ gvm = VM_Restart( gvm );
+ if ( !gvm ) { // bk001212 - as done below
+ Com_Error( ERR_FATAL, "VM_Restart on game failed" );
+ }
+
+ SV_InitGameVM( qtrue );
+}
+
+
+/*
+===============
+SV_InitGameProgs
+
+Called on a normal map change, not on a map_restart
+===============
+*/
+void SV_InitGameProgs( void ) {
+ cvar_t *var;
+ //FIXME these are temp while I make bots run in vm
+ extern int bot_enable;
+
+ var = Cvar_Get( "bot_enable", "1", CVAR_LATCH );
+ if ( var ) {
+ bot_enable = var->integer;
+ }
+ else {
+ bot_enable = 0;
+ }
+
+ // load the dll or bytecode
+ gvm = VM_Create( "qagame", SV_GameSystemCalls, Cvar_VariableValue( "vm_game" ) );
+ if ( !gvm ) {
+ Com_Error( ERR_FATAL, "VM_Create on game failed" );
+ }
+
+ SV_InitGameVM( qfalse );
+}
+
+
+/*
+====================
+SV_GameCommand
+
+See if the current console command is claimed by the game
+====================
+*/
+qboolean SV_GameCommand( void ) {
+ if ( sv.state != SS_GAME ) {
+ return qfalse;
+ }
+
+ return VM_Call( gvm, GAME_CONSOLE_COMMAND );
+}
+
diff --git a/code/server/sv_init.c b/code/server/sv_init.c
new file mode 100755
index 0000000..b3d0c4d
--- /dev/null
+++ b/code/server/sv_init.c
@@ -0,0 +1,695 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "server.h"
+
+/*
+===============
+SV_SetConfigstring
+
+===============
+*/
+void SV_SetConfigstring (int index, const char *val) {
+ int len, i;
+ int maxChunkSize = MAX_STRING_CHARS - 24;
+ client_t *client;
+
+ if ( index < 0 || index >= MAX_CONFIGSTRINGS ) {
+ Com_Error (ERR_DROP, "SV_SetConfigstring: bad index %i\n", index);
+ }
+
+ if ( !val ) {
+ val = "";
+ }
+
+ // don't bother broadcasting an update if no change
+ if ( !strcmp( val, sv.configstrings[ index ] ) ) {
+ return;
+ }
+
+ // change the string in sv
+ Z_Free( sv.configstrings[index] );
+ sv.configstrings[index] = CopyString( val );
+
+ // send it to all the clients if we aren't
+ // spawning a new server
+ if ( sv.state == SS_GAME || sv.restarting ) {
+
+ // send the data to all relevent clients
+ for (i = 0, client = svs.clients; i < sv_maxclients->integer ; i++, client++) {
+ if ( client->state < CS_PRIMED ) {
+ continue;
+ }
+ // do not always send server info to all clients
+ if ( index == CS_SERVERINFO && client->gentity && (client->gentity->r.svFlags & SVF_NOSERVERINFO) ) {
+ continue;
+ }
+
+ len = strlen( val );
+ if( len >= maxChunkSize ) {
+ int sent = 0;
+ int remaining = len;
+ char *cmd;
+ char buf[MAX_STRING_CHARS];
+
+ while (remaining > 0 ) {
+ if ( sent == 0 ) {
+ cmd = "bcs0";
+ }
+ else if( remaining < maxChunkSize ) {
+ cmd = "bcs2";
+ }
+ else {
+ cmd = "bcs1";
+ }
+ Q_strncpyz( buf, &val[sent], maxChunkSize );
+
+ SV_SendServerCommand( client, "%s %i \"%s\"\n", cmd, index, buf );
+
+ sent += (maxChunkSize - 1);
+ remaining -= (maxChunkSize - 1);
+ }
+ } else {
+ // standard cs, just send it
+ SV_SendServerCommand( client, "cs %i \"%s\"\n", index, val );
+ }
+ }
+ }
+}
+
+
+
+/*
+===============
+SV_GetConfigstring
+
+===============
+*/
+void SV_GetConfigstring( int index, char *buffer, int bufferSize ) {
+ if ( bufferSize < 1 ) {
+ Com_Error( ERR_DROP, "SV_GetConfigstring: bufferSize == %i", bufferSize );
+ }
+ if ( index < 0 || index >= MAX_CONFIGSTRINGS ) {
+ Com_Error (ERR_DROP, "SV_GetConfigstring: bad index %i\n", index);
+ }
+ if ( !sv.configstrings[index] ) {
+ buffer[0] = 0;
+ return;
+ }
+
+ Q_strncpyz( buffer, sv.configstrings[index], bufferSize );
+}
+
+
+/*
+===============
+SV_SetUserinfo
+
+===============
+*/
+void SV_SetUserinfo( int index, const char *val ) {
+ if ( index < 0 || index >= sv_maxclients->integer ) {
+ Com_Error (ERR_DROP, "SV_SetUserinfo: bad index %i\n", index);
+ }
+
+ if ( !val ) {
+ val = "";
+ }
+
+ Q_strncpyz( svs.clients[index].userinfo, val, sizeof( svs.clients[ index ].userinfo ) );
+ Q_strncpyz( svs.clients[index].name, Info_ValueForKey( val, "name" ), sizeof(svs.clients[index].name) );
+}
+
+
+
+/*
+===============
+SV_GetUserinfo
+
+===============
+*/
+void SV_GetUserinfo( int index, char *buffer, int bufferSize ) {
+ if ( bufferSize < 1 ) {
+ Com_Error( ERR_DROP, "SV_GetUserinfo: bufferSize == %i", bufferSize );
+ }
+ if ( index < 0 || index >= sv_maxclients->integer ) {
+ Com_Error (ERR_DROP, "SV_GetUserinfo: bad index %i\n", index);
+ }
+ Q_strncpyz( buffer, svs.clients[ index ].userinfo, bufferSize );
+}
+
+
+/*
+================
+SV_CreateBaseline
+
+Entity baselines are used to compress non-delta messages
+to the clients -- only the fields that differ from the
+baseline will be transmitted
+================
+*/
+void SV_CreateBaseline( void ) {
+ sharedEntity_t *svent;
+ int entnum;
+
+ for ( entnum = 1; entnum < sv.num_entities ; entnum++ ) {
+ svent = SV_GentityNum(entnum);
+ if (!svent->r.linked) {
+ continue;
+ }
+ svent->s.number = entnum;
+
+ //
+ // take current state as baseline
+ //
+ sv.svEntities[entnum].baseline = svent->s;
+ }
+}
+
+
+/*
+===============
+SV_BoundMaxClients
+
+===============
+*/
+void SV_BoundMaxClients( int minimum ) {
+ // get the current maxclients value
+ Cvar_Get( "sv_maxclients", "8", 0 );
+
+ sv_maxclients->modified = qfalse;
+
+ if ( sv_maxclients->integer < minimum ) {
+ Cvar_Set( "sv_maxclients", va("%i", minimum) );
+ } else if ( sv_maxclients->integer > MAX_CLIENTS ) {
+ Cvar_Set( "sv_maxclients", va("%i", MAX_CLIENTS) );
+ }
+}
+
+
+/*
+===============
+SV_Startup
+
+Called when a host starts a map when it wasn't running
+one before. Successive map or map_restart commands will
+NOT cause this to be called, unless the game is exited to
+the menu system first.
+===============
+*/
+void SV_Startup( void ) {
+ if ( svs.initialized ) {
+ Com_Error( ERR_FATAL, "SV_Startup: svs.initialized" );
+ }
+ SV_BoundMaxClients( 1 );
+
+ svs.clients = Z_Malloc (sizeof(client_t) * sv_maxclients->integer );
+ if ( com_dedicated->integer ) {
+ svs.numSnapshotEntities = sv_maxclients->integer * PACKET_BACKUP * 64;
+ } else {
+ // we don't need nearly as many when playing locally
+ svs.numSnapshotEntities = sv_maxclients->integer * 4 * 64;
+ }
+ svs.initialized = qtrue;
+
+ Cvar_Set( "sv_running", "1" );
+}
+
+
+/*
+==================
+SV_ChangeMaxClients
+==================
+*/
+void SV_ChangeMaxClients( void ) {
+ int oldMaxClients;
+ int i;
+ client_t *oldClients;
+ int count;
+
+ // get the highest client number in use
+ count = 0;
+ for ( i = 0 ; i < sv_maxclients->integer ; i++ ) {
+ if ( svs.clients[i].state >= CS_CONNECTED ) {
+ if (i > count)
+ count = i;
+ }
+ }
+ count++;
+
+ oldMaxClients = sv_maxclients->integer;
+ // never go below the highest client number in use
+ SV_BoundMaxClients( count );
+ // if still the same
+ if ( sv_maxclients->integer == oldMaxClients ) {
+ return;
+ }
+
+ oldClients = Hunk_AllocateTempMemory( count * sizeof(client_t) );
+ // copy the clients to hunk memory
+ for ( i = 0 ; i < count ; i++ ) {
+ if ( svs.clients[i].state >= CS_CONNECTED ) {
+ oldClients[i] = svs.clients[i];
+ }
+ else {
+ Com_Memset(&oldClients[i], 0, sizeof(client_t));
+ }
+ }
+
+ // free old clients arrays
+ Z_Free( svs.clients );
+
+ // allocate new clients
+ svs.clients = Z_Malloc ( sv_maxclients->integer * sizeof(client_t) );
+ Com_Memset( svs.clients, 0, sv_maxclients->integer * sizeof(client_t) );
+
+ // copy the clients over
+ for ( i = 0 ; i < count ; i++ ) {
+ if ( oldClients[i].state >= CS_CONNECTED ) {
+ svs.clients[i] = oldClients[i];
+ }
+ }
+
+ // free the old clients on the hunk
+ Hunk_FreeTempMemory( oldClients );
+
+ // allocate new snapshot entities
+ if ( com_dedicated->integer ) {
+ svs.numSnapshotEntities = sv_maxclients->integer * PACKET_BACKUP * 64;
+ } else {
+ // we don't need nearly as many when playing locally
+ svs.numSnapshotEntities = sv_maxclients->integer * 4 * 64;
+ }
+}
+
+/*
+================
+SV_ClearServer
+================
+*/
+void SV_ClearServer(void) {
+ int i;
+
+ for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) {
+ if ( sv.configstrings[i] ) {
+ Z_Free( sv.configstrings[i] );
+ }
+ }
+ Com_Memset (&sv, 0, sizeof(sv));
+}
+
+/*
+================
+SV_TouchCGame
+
+ touch the cgame.vm so that a pure client can load it if it's in a seperate pk3
+================
+*/
+void SV_TouchCGame(void) {
+ fileHandle_t f;
+ char filename[MAX_QPATH];
+
+ Com_sprintf( filename, sizeof(filename), "vm/%s.qvm", "cgame" );
+ FS_FOpenFileRead( filename, &f, qfalse );
+ if ( f ) {
+ FS_FCloseFile( f );
+ }
+}
+
+/*
+================
+SV_SpawnServer
+
+Change the server to a new map, taking all connected
+clients along with it.
+This is NOT called for map_restart
+================
+*/
+void SV_SpawnServer( char *server, qboolean killBots ) {
+ int i;
+ int checksum;
+ qboolean isBot;
+ char systemInfo[16384];
+ const char *p;
+
+ // shut down the existing game if it is running
+ SV_ShutdownGameProgs();
+
+ Com_Printf ("------ Server Initialization ------\n");
+ Com_Printf ("Server: %s\n",server);
+
+ // if not running a dedicated server CL_MapLoading will connect the client to the server
+ // also print some status stuff
+ CL_MapLoading();
+
+ // make sure all the client stuff is unloaded
+ CL_ShutdownAll();
+
+ // clear the whole hunk because we're (re)loading the server
+ Hunk_Clear();
+
+ // clear collision map data
+ CM_ClearMap();
+
+ // init client structures and svs.numSnapshotEntities
+ if ( !Cvar_VariableValue("sv_running") ) {
+ SV_Startup();
+ } else {
+ // check for maxclients change
+ if ( sv_maxclients->modified ) {
+ SV_ChangeMaxClients();
+ }
+ }
+
+ // clear pak references
+ FS_ClearPakReferences(0);
+
+ // allocate the snapshot entities on the hunk
+ svs.snapshotEntities = Hunk_Alloc( sizeof(entityState_t)*svs.numSnapshotEntities, h_high );
+ svs.nextSnapshotEntities = 0;
+
+ // toggle the server bit so clients can detect that a
+ // server has changed
+ svs.snapFlagServerBit ^= SNAPFLAG_SERVERCOUNT;
+
+ // set nextmap to the same map, but it may be overriden
+ // by the game startup or another console command
+ Cvar_Set( "nextmap", "map_restart 0");
+// Cvar_Set( "nextmap", va("map %s", server) );
+
+ // wipe the entire per-level structure
+ SV_ClearServer();
+ for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) {
+ sv.configstrings[i] = CopyString("");
+ }
+
+ // make sure we are not paused
+ Cvar_Set("cl_paused", "0");
+
+ // get a new checksum feed and restart the file system
+ srand(Com_Milliseconds());
+ sv.checksumFeed = ( ((int) rand() << 16) ^ rand() ) ^ Com_Milliseconds();
+ FS_Restart( sv.checksumFeed );
+
+ CM_LoadMap( va("maps/%s.bsp", server), qfalse, &checksum );
+
+ // set serverinfo visible name
+ Cvar_Set( "mapname", server );
+
+ Cvar_Set( "sv_mapChecksum", va("%i",checksum) );
+
+ // serverid should be different each time
+ sv.serverId = com_frameTime;
+ sv.restartedServerId = sv.serverId; // I suppose the init here is just to be safe
+ sv.checksumFeedServerId = sv.serverId;
+ Cvar_Set( "sv_serverid", va("%i", sv.serverId ) );
+
+ // clear physics interaction links
+ SV_ClearWorld ();
+
+ // media configstring setting should be done during
+ // the loading stage, so connected clients don't have
+ // to load during actual gameplay
+ sv.state = SS_LOADING;
+
+ // load and spawn all other entities
+ SV_InitGameProgs();
+
+ // don't allow a map_restart if game is modified
+ sv_gametype->modified = qfalse;
+
+ // run a few frames to allow everything to settle
+ for ( i = 0 ;i < 3 ; i++ ) {
+ VM_Call( gvm, GAME_RUN_FRAME, svs.time );
+ SV_BotFrame( svs.time );
+ svs.time += 100;
+ }
+
+ // create a baseline for more efficient communications
+ SV_CreateBaseline ();
+
+ for (i=0 ; i<sv_maxclients->integer ; i++) {
+ // send the new gamestate to all connected clients
+ if (svs.clients[i].state >= CS_CONNECTED) {
+ char *denied;
+
+ if ( svs.clients[i].netchan.remoteAddress.type == NA_BOT ) {
+ if ( killBots ) {
+ SV_DropClient( &svs.clients[i], "" );
+ continue;
+ }
+ isBot = qtrue;
+ }
+ else {
+ isBot = qfalse;
+ }
+
+ // connect the client again
+ denied = VM_ExplicitArgPtr( gvm, VM_Call( gvm, GAME_CLIENT_CONNECT, i, qfalse, isBot ) ); // firstTime = qfalse
+ if ( denied ) {
+ // this generally shouldn't happen, because the client
+ // was connected before the level change
+ SV_DropClient( &svs.clients[i], denied );
+ } else {
+ if( !isBot ) {
+ // when we get the next packet from a connected client,
+ // the new gamestate will be sent
+ svs.clients[i].state = CS_CONNECTED;
+ }
+ else {
+ client_t *client;
+ sharedEntity_t *ent;
+
+ client = &svs.clients[i];
+ client->state = CS_ACTIVE;
+ ent = SV_GentityNum( i );
+ ent->s.number = i;
+ client->gentity = ent;
+
+ client->deltaMessage = -1;
+ client->nextSnapshotTime = svs.time; // generate a snapshot immediately
+
+ VM_Call( gvm, GAME_CLIENT_BEGIN, i );
+ }
+ }
+ }
+ }
+
+ // run another frame to allow things to look at all the players
+ VM_Call( gvm, GAME_RUN_FRAME, svs.time );
+ SV_BotFrame( svs.time );
+ svs.time += 100;
+
+ if ( sv_pure->integer ) {
+ // the server sends these to the clients so they will only
+ // load pk3s also loaded at the server
+ p = FS_LoadedPakChecksums();
+ Cvar_Set( "sv_paks", p );
+ if (strlen(p) == 0) {
+ Com_Printf( "WARNING: sv_pure set but no PK3 files loaded\n" );
+ }
+ p = FS_LoadedPakNames();
+ Cvar_Set( "sv_pakNames", p );
+
+ // if a dedicated pure server we need to touch the cgame because it could be in a
+ // seperate pk3 file and the client will need to load the latest cgame.qvm
+ if ( com_dedicated->integer ) {
+ SV_TouchCGame();
+ }
+ }
+ else {
+ Cvar_Set( "sv_paks", "" );
+ Cvar_Set( "sv_pakNames", "" );
+ }
+ // the server sends these to the clients so they can figure
+ // out which pk3s should be auto-downloaded
+ p = FS_ReferencedPakChecksums();
+ Cvar_Set( "sv_referencedPaks", p );
+ p = FS_ReferencedPakNames();
+ Cvar_Set( "sv_referencedPakNames", p );
+
+ // save systeminfo and serverinfo strings
+ Q_strncpyz( systemInfo, Cvar_InfoString_Big( CVAR_SYSTEMINFO ), sizeof( systemInfo ) );
+ cvar_modifiedFlags &= ~CVAR_SYSTEMINFO;
+ SV_SetConfigstring( CS_SYSTEMINFO, systemInfo );
+
+ SV_SetConfigstring( CS_SERVERINFO, Cvar_InfoString( CVAR_SERVERINFO ) );
+ cvar_modifiedFlags &= ~CVAR_SERVERINFO;
+
+ // any media configstring setting now should issue a warning
+ // and any configstring changes should be reliably transmitted
+ // to all clients
+ sv.state = SS_GAME;
+
+ // send a heartbeat now so the master will get up to date info
+ SV_Heartbeat_f();
+
+ Hunk_SetMark();
+
+ Com_Printf ("-----------------------------------\n");
+}
+
+/*
+===============
+SV_Init
+
+Only called at main exe startup, not for each game
+===============
+*/
+void SV_BotInitBotLib(void);
+
+void SV_Init (void) {
+ SV_AddOperatorCommands ();
+
+ // serverinfo vars
+ Cvar_Get ("dmflags", "0", CVAR_SERVERINFO);
+ Cvar_Get ("fraglimit", "20", CVAR_SERVERINFO);
+ Cvar_Get ("timelimit", "0", CVAR_SERVERINFO);
+ sv_gametype = Cvar_Get ("g_gametype", "0", CVAR_SERVERINFO | CVAR_LATCH );
+ Cvar_Get ("sv_keywords", "", CVAR_SERVERINFO);
+ Cvar_Get ("protocol", va("%i", PROTOCOL_VERSION), CVAR_SERVERINFO | CVAR_ROM);
+ sv_mapname = Cvar_Get ("mapname", "nomap", CVAR_SERVERINFO | CVAR_ROM);
+ sv_privateClients = Cvar_Get ("sv_privateClients", "0", CVAR_SERVERINFO);
+ sv_hostname = Cvar_Get ("sv_hostname", "noname", CVAR_SERVERINFO | CVAR_ARCHIVE );
+ sv_maxclients = Cvar_Get ("sv_maxclients", "8", CVAR_SERVERINFO | CVAR_LATCH);
+
+ sv_maxRate = Cvar_Get ("sv_maxRate", "0", CVAR_ARCHIVE | CVAR_SERVERINFO );
+ sv_minPing = Cvar_Get ("sv_minPing", "0", CVAR_ARCHIVE | CVAR_SERVERINFO );
+ sv_maxPing = Cvar_Get ("sv_maxPing", "0", CVAR_ARCHIVE | CVAR_SERVERINFO );
+ sv_floodProtect = Cvar_Get ("sv_floodProtect", "1", CVAR_ARCHIVE | CVAR_SERVERINFO );
+
+ // systeminfo
+ Cvar_Get ("sv_cheats", "1", CVAR_SYSTEMINFO | CVAR_ROM );
+ sv_serverid = Cvar_Get ("sv_serverid", "0", CVAR_SYSTEMINFO | CVAR_ROM );
+#ifndef DLL_ONLY // bk010216 - for DLL-only servers
+ sv_pure = Cvar_Get ("sv_pure", "1", CVAR_SYSTEMINFO );
+#else
+ sv_pure = Cvar_Get ("sv_pure", "0", CVAR_SYSTEMINFO | CVAR_INIT | CVAR_ROM );
+#endif
+ Cvar_Get ("sv_paks", "", CVAR_SYSTEMINFO | CVAR_ROM );
+ Cvar_Get ("sv_pakNames", "", CVAR_SYSTEMINFO | CVAR_ROM );
+ Cvar_Get ("sv_referencedPaks", "", CVAR_SYSTEMINFO | CVAR_ROM );
+ Cvar_Get ("sv_referencedPakNames", "", CVAR_SYSTEMINFO | CVAR_ROM );
+
+ // server vars
+ sv_rconPassword = Cvar_Get ("rconPassword", "", CVAR_TEMP );
+ sv_privatePassword = Cvar_Get ("sv_privatePassword", "", CVAR_TEMP );
+ sv_fps = Cvar_Get ("sv_fps", "20", CVAR_TEMP );
+ sv_timeout = Cvar_Get ("sv_timeout", "200", CVAR_TEMP );
+ sv_zombietime = Cvar_Get ("sv_zombietime", "2", CVAR_TEMP );
+ Cvar_Get ("nextmap", "", CVAR_TEMP );
+
+ sv_allowDownload = Cvar_Get ("sv_allowDownload", "0", CVAR_SERVERINFO);
+ sv_master[0] = Cvar_Get ("sv_master1", MASTER_SERVER_NAME, 0 );
+ sv_master[1] = Cvar_Get ("sv_master2", "", CVAR_ARCHIVE );
+ sv_master[2] = Cvar_Get ("sv_master3", "", CVAR_ARCHIVE );
+ sv_master[3] = Cvar_Get ("sv_master4", "", CVAR_ARCHIVE );
+ sv_master[4] = Cvar_Get ("sv_master5", "", CVAR_ARCHIVE );
+ sv_reconnectlimit = Cvar_Get ("sv_reconnectlimit", "3", 0);
+ sv_showloss = Cvar_Get ("sv_showloss", "0", 0);
+ sv_padPackets = Cvar_Get ("sv_padPackets", "0", 0);
+ sv_killserver = Cvar_Get ("sv_killserver", "0", 0);
+ sv_mapChecksum = Cvar_Get ("sv_mapChecksum", "", CVAR_ROM);
+ sv_lanForceRate = Cvar_Get ("sv_lanForceRate", "1", CVAR_ARCHIVE );
+ sv_strictAuth = Cvar_Get ("sv_strictAuth", "1", CVAR_ARCHIVE );
+
+ // initialize bot cvars so they are listed and can be set before loading the botlib
+ SV_BotInitCvars();
+
+ // init the botlib here because we need the pre-compiler in the UI
+ SV_BotInitBotLib();
+}
+
+
+/*
+==================
+SV_FinalMessage
+
+Used by SV_Shutdown to send a final message to all
+connected clients before the server goes down. The messages are sent immediately,
+not just stuck on the outgoing message list, because the server is going
+to totally exit after returning from this function.
+==================
+*/
+void SV_FinalMessage( char *message ) {
+ int i, j;
+ client_t *cl;
+
+ // send it twice, ignoring rate
+ for ( j = 0 ; j < 2 ; j++ ) {
+ for (i=0, cl = svs.clients ; i < sv_maxclients->integer ; i++, cl++) {
+ if (cl->state >= CS_CONNECTED) {
+ // don't send a disconnect to a local client
+ if ( cl->netchan.remoteAddress.type != NA_LOOPBACK ) {
+ SV_SendServerCommand( cl, "print \"%s\"", message );
+ SV_SendServerCommand( cl, "disconnect" );
+ }
+ // force a snapshot to be sent
+ cl->nextSnapshotTime = -1;
+ SV_SendClientSnapshot( cl );
+ }
+ }
+ }
+}
+
+
+/*
+================
+SV_Shutdown
+
+Called when each game quits,
+before Sys_Quit or Sys_Error
+================
+*/
+void SV_Shutdown( char *finalmsg ) {
+ if ( !com_sv_running || !com_sv_running->integer ) {
+ return;
+ }
+
+ Com_Printf( "----- Server Shutdown -----\n" );
+
+ if ( svs.clients && !com_errorEntered ) {
+ SV_FinalMessage( finalmsg );
+ }
+
+ SV_RemoveOperatorCommands();
+ SV_MasterShutdown();
+ SV_ShutdownGameProgs();
+
+ // free current level
+ SV_ClearServer();
+
+ // free server static data
+ if ( svs.clients ) {
+ Z_Free( svs.clients );
+ }
+ Com_Memset( &svs, 0, sizeof( svs ) );
+
+ Cvar_Set( "sv_running", "0" );
+ Cvar_Set("ui_singlePlayerActive", "0");
+
+ Com_Printf( "---------------------------\n" );
+
+ // disconnect any local clients
+ CL_Disconnect( qfalse );
+}
+
diff --git a/code/server/sv_main.c b/code/server/sv_main.c
new file mode 100755
index 0000000..98c74ce
--- /dev/null
+++ b/code/server/sv_main.c
@@ -0,0 +1,855 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "server.h"
+
+serverStatic_t svs; // persistant server info
+server_t sv; // local server
+vm_t *gvm = NULL; // game virtual machine // bk001212 init
+
+cvar_t *sv_fps; // time rate for running non-clients
+cvar_t *sv_timeout; // seconds without any message
+cvar_t *sv_zombietime; // seconds to sink messages after disconnect
+cvar_t *sv_rconPassword; // password for remote server commands
+cvar_t *sv_privatePassword; // password for the privateClient slots
+cvar_t *sv_allowDownload;
+cvar_t *sv_maxclients;
+
+cvar_t *sv_privateClients; // number of clients reserved for password
+cvar_t *sv_hostname;
+cvar_t *sv_master[MAX_MASTER_SERVERS]; // master server ip address
+cvar_t *sv_reconnectlimit; // minimum seconds between connect messages
+cvar_t *sv_showloss; // report when usercmds are lost
+cvar_t *sv_padPackets; // add nop bytes to messages
+cvar_t *sv_killserver; // menu system can set to 1 to shut server down
+cvar_t *sv_mapname;
+cvar_t *sv_mapChecksum;
+cvar_t *sv_serverid;
+cvar_t *sv_maxRate;
+cvar_t *sv_minPing;
+cvar_t *sv_maxPing;
+cvar_t *sv_gametype;
+cvar_t *sv_pure;
+cvar_t *sv_floodProtect;
+cvar_t *sv_lanForceRate; // dedicated 1 (LAN) server forces local client rates to 99999 (bug #491)
+cvar_t *sv_strictAuth;
+
+/*
+=============================================================================
+
+EVENT MESSAGES
+
+=============================================================================
+*/
+
+/*
+===============
+SV_ExpandNewlines
+
+Converts newlines to "\n" so a line prints nicer
+===============
+*/
+char *SV_ExpandNewlines( char *in ) {
+ static char string[1024];
+ int l;
+
+ l = 0;
+ while ( *in && l < sizeof(string) - 3 ) {
+ if ( *in == '\n' ) {
+ string[l++] = '\\';
+ string[l++] = 'n';
+ } else {
+ string[l++] = *in;
+ }
+ in++;
+ }
+ string[l] = 0;
+
+ return string;
+}
+
+/*
+======================
+SV_ReplacePendingServerCommands
+
+ This is ugly
+======================
+*/
+int SV_ReplacePendingServerCommands( client_t *client, const char *cmd ) {
+ int i, index, csnum1, csnum2;
+
+ for ( i = client->reliableSent+1; i <= client->reliableSequence; i++ ) {
+ index = i & ( MAX_RELIABLE_COMMANDS - 1 );
+ //
+ if ( !Q_strncmp(cmd, client->reliableCommands[ index ], strlen("cs")) ) {
+ sscanf(cmd, "cs %i", &csnum1);
+ sscanf(client->reliableCommands[ index ], "cs %i", &csnum2);
+ if ( csnum1 == csnum2 ) {
+ Q_strncpyz( client->reliableCommands[ index ], cmd, sizeof( client->reliableCommands[ index ] ) );
+ /*
+ if ( client->netchan.remoteAddress.type != NA_BOT ) {
+ Com_Printf( "WARNING: client %i removed double pending config string %i: %s\n", client-svs.clients, csnum1, cmd );
+ }
+ */
+ return qtrue;
+ }
+ }
+ }
+ return qfalse;
+}
+
+/*
+======================
+SV_AddServerCommand
+
+The given command will be transmitted to the client, and is guaranteed to
+not have future snapshot_t executed before it is executed
+======================
+*/
+void SV_AddServerCommand( client_t *client, const char *cmd ) {
+ int index, i;
+
+ // this is very ugly but it's also a waste to for instance send multiple config string updates
+ // for the same config string index in one snapshot
+// if ( SV_ReplacePendingServerCommands( client, cmd ) ) {
+// return;
+// }
+
+ client->reliableSequence++;
+ // if we would be losing an old command that hasn't been acknowledged,
+ // we must drop the connection
+ // we check == instead of >= so a broadcast print added by SV_DropClient()
+ // doesn't cause a recursive drop client
+ if ( client->reliableSequence - client->reliableAcknowledge == MAX_RELIABLE_COMMANDS + 1 ) {
+ Com_Printf( "===== pending server commands =====\n" );
+ for ( i = client->reliableAcknowledge + 1 ; i <= client->reliableSequence ; i++ ) {
+ Com_Printf( "cmd %5d: %s\n", i, client->reliableCommands[ i & (MAX_RELIABLE_COMMANDS-1) ] );
+ }
+ Com_Printf( "cmd %5d: %s\n", i, cmd );
+ SV_DropClient( client, "Server command overflow" );
+ return;
+ }
+ index = client->reliableSequence & ( MAX_RELIABLE_COMMANDS - 1 );
+ Q_strncpyz( client->reliableCommands[ index ], cmd, sizeof( client->reliableCommands[ index ] ) );
+}
+
+
+/*
+=================
+SV_SendServerCommand
+
+Sends a reliable command string to be interpreted by
+the client game module: "cp", "print", "chat", etc
+A NULL client will broadcast to all clients
+=================
+*/
+void QDECL SV_SendServerCommand(client_t *cl, const char *fmt, ...) {
+ va_list argptr;
+ byte message[MAX_MSGLEN];
+ client_t *client;
+ int j;
+
+ va_start (argptr,fmt);
+ Q_vsnprintf ((char *)message, sizeof(message), fmt,argptr);
+ va_end (argptr);
+
+ if ( cl != NULL ) {
+ SV_AddServerCommand( cl, (char *)message );
+ return;
+ }
+
+ // hack to echo broadcast prints to console
+ if ( com_dedicated->integer && !strncmp( (char *)message, "print", 5) ) {
+ Com_Printf ("broadcast: %s\n", SV_ExpandNewlines((char *)message) );
+ }
+
+ // send the data to all relevent clients
+ for (j = 0, client = svs.clients; j < sv_maxclients->integer ; j++, client++) {
+ if ( client->state < CS_PRIMED ) {
+ continue;
+ }
+ SV_AddServerCommand( client, (char *)message );
+ }
+}
+
+
+/*
+==============================================================================
+
+MASTER SERVER FUNCTIONS
+
+==============================================================================
+*/
+
+/*
+================
+SV_MasterHeartbeat
+
+Send a message to the masters every few minutes to
+let it know we are alive, and log information.
+We will also have a heartbeat sent when a server
+changes from empty to non-empty, and full to non-full,
+but not on every player enter or exit.
+================
+*/
+#define HEARTBEAT_MSEC 300*1000
+#define HEARTBEAT_GAME "QuakeArena-1"
+void SV_MasterHeartbeat( void ) {
+ static netadr_t adr[MAX_MASTER_SERVERS];
+ int i;
+
+ // "dedicated 1" is for lan play, "dedicated 2" is for inet public play
+ if ( !com_dedicated || com_dedicated->integer != 2 ) {
+ return; // only dedicated servers send heartbeats
+ }
+
+ // if not time yet, don't send anything
+ if ( svs.time < svs.nextHeartbeatTime ) {
+ return;
+ }
+ svs.nextHeartbeatTime = svs.time + HEARTBEAT_MSEC;
+
+
+ // send to group masters
+ for ( i = 0 ; i < MAX_MASTER_SERVERS ; i++ ) {
+ if ( !sv_master[i]->string[0] ) {
+ continue;
+ }
+
+ // see if we haven't already resolved the name
+ // resolving usually causes hitches on win95, so only
+ // do it when needed
+ if ( sv_master[i]->modified ) {
+ sv_master[i]->modified = qfalse;
+
+ Com_Printf( "Resolving %s\n", sv_master[i]->string );
+ if ( !NET_StringToAdr( sv_master[i]->string, &adr[i] ) ) {
+ // if the address failed to resolve, clear it
+ // so we don't take repeated dns hits
+ Com_Printf( "Couldn't resolve address: %s\n", sv_master[i]->string );
+ Cvar_Set( sv_master[i]->name, "" );
+ sv_master[i]->modified = qfalse;
+ continue;
+ }
+ if ( !strstr( ":", sv_master[i]->string ) ) {
+ adr[i].port = BigShort( PORT_MASTER );
+ }
+ Com_Printf( "%s resolved to %i.%i.%i.%i:%i\n", sv_master[i]->string,
+ adr[i].ip[0], adr[i].ip[1], adr[i].ip[2], adr[i].ip[3],
+ BigShort( adr[i].port ) );
+ }
+
+
+ Com_Printf ("Sending heartbeat to %s\n", sv_master[i]->string );
+ // this command should be changed if the server info / status format
+ // ever incompatably changes
+ NET_OutOfBandPrint( NS_SERVER, adr[i], "heartbeat %s\n", HEARTBEAT_GAME );
+ }
+}
+
+/*
+=================
+SV_MasterShutdown
+
+Informs all masters that this server is going down
+=================
+*/
+void SV_MasterShutdown( void ) {
+ // send a hearbeat right now
+ svs.nextHeartbeatTime = -9999;
+ SV_MasterHeartbeat();
+
+ // send it again to minimize chance of drops
+ svs.nextHeartbeatTime = -9999;
+ SV_MasterHeartbeat();
+
+ // when the master tries to poll the server, it won't respond, so
+ // it will be removed from the list
+}
+
+
+/*
+==============================================================================
+
+CONNECTIONLESS COMMANDS
+
+==============================================================================
+*/
+
+/*
+================
+SVC_Status
+
+Responds with all the info that qplug or qspy can see about the server
+and all connected players. Used for getting detailed information after
+the simple info query.
+================
+*/
+void SVC_Status( netadr_t from ) {
+ char player[1024];
+ char status[MAX_MSGLEN];
+ int i;
+ client_t *cl;
+ playerState_t *ps;
+ int statusLength;
+ int playerLength;
+ char infostring[MAX_INFO_STRING];
+
+ // ignore if we are in single player
+ if ( Cvar_VariableValue( "g_gametype" ) == GT_SINGLE_PLAYER ) {
+ return;
+ }
+
+ strcpy( infostring, Cvar_InfoString( CVAR_SERVERINFO ) );
+
+ // echo back the parameter to status. so master servers can use it as a challenge
+ // to prevent timed spoofed reply packets that add ghost servers
+ Info_SetValueForKey( infostring, "challenge", Cmd_Argv(1) );
+
+ // add "demo" to the sv_keywords if restricted
+ if ( Cvar_VariableValue( "fs_restrict" ) ) {
+ char keywords[MAX_INFO_STRING];
+
+ Com_sprintf( keywords, sizeof( keywords ), "demo %s",
+ Info_ValueForKey( infostring, "sv_keywords" ) );
+ Info_SetValueForKey( infostring, "sv_keywords", keywords );
+ }
+
+ status[0] = 0;
+ statusLength = 0;
+
+ for (i=0 ; i < sv_maxclients->integer ; i++) {
+ cl = &svs.clients[i];
+ if ( cl->state >= CS_CONNECTED ) {
+ ps = SV_GameClientNum( i );
+ Com_sprintf (player, sizeof(player), "%i %i \"%s\"\n",
+ ps->persistant[PERS_SCORE], cl->ping, cl->name);
+ playerLength = strlen(player);
+ if (statusLength + playerLength >= sizeof(status) ) {
+ break; // can't hold any more
+ }
+ strcpy (status + statusLength, player);
+ statusLength += playerLength;
+ }
+ }
+
+ NET_OutOfBandPrint( NS_SERVER, from, "statusResponse\n%s\n%s", infostring, status );
+}
+
+/*
+================
+SVC_Info
+
+Responds with a short info message that should be enough to determine
+if a user is interested in a server to do a full status
+================
+*/
+void SVC_Info( netadr_t from ) {
+ int i, count;
+ char *gamedir;
+ char infostring[MAX_INFO_STRING];
+
+ // ignore if we are in single player
+ if ( Cvar_VariableValue( "g_gametype" ) == GT_SINGLE_PLAYER || Cvar_VariableValue("ui_singlePlayerActive")) {
+ return;
+ }
+
+ // don't count privateclients
+ count = 0;
+ for ( i = sv_privateClients->integer ; i < sv_maxclients->integer ; i++ ) {
+ if ( svs.clients[i].state >= CS_CONNECTED ) {
+ count++;
+ }
+ }
+
+ infostring[0] = 0;
+
+ // echo back the parameter to status. so servers can use it as a challenge
+ // to prevent timed spoofed reply packets that add ghost servers
+ Info_SetValueForKey( infostring, "challenge", Cmd_Argv(1) );
+
+ Info_SetValueForKey( infostring, "protocol", va("%i", PROTOCOL_VERSION) );
+ Info_SetValueForKey( infostring, "hostname", sv_hostname->string );
+ Info_SetValueForKey( infostring, "mapname", sv_mapname->string );
+ Info_SetValueForKey( infostring, "clients", va("%i", count) );
+ Info_SetValueForKey( infostring, "sv_maxclients",
+ va("%i", sv_maxclients->integer - sv_privateClients->integer ) );
+ Info_SetValueForKey( infostring, "gametype", va("%i", sv_gametype->integer ) );
+ Info_SetValueForKey( infostring, "pure", va("%i", sv_pure->integer ) );
+
+ if( sv_minPing->integer ) {
+ Info_SetValueForKey( infostring, "minPing", va("%i", sv_minPing->integer) );
+ }
+ if( sv_maxPing->integer ) {
+ Info_SetValueForKey( infostring, "maxPing", va("%i", sv_maxPing->integer) );
+ }
+ gamedir = Cvar_VariableString( "fs_game" );
+ if( *gamedir ) {
+ Info_SetValueForKey( infostring, "game", gamedir );
+ }
+
+ NET_OutOfBandPrint( NS_SERVER, from, "infoResponse\n%s", infostring );
+}
+
+/*
+================
+SVC_FlushRedirect
+
+================
+*/
+void SV_FlushRedirect( char *outputbuf ) {
+ NET_OutOfBandPrint( NS_SERVER, svs.redirectAddress, "print\n%s", outputbuf );
+}
+
+/*
+===============
+SVC_RemoteCommand
+
+An rcon packet arrived from the network.
+Shift down the remaining args
+Redirect all printfs
+===============
+*/
+void SVC_RemoteCommand( netadr_t from, msg_t *msg ) {
+ qboolean valid;
+ unsigned int time;
+ char remaining[1024];
+ // TTimo - scaled down to accumulate, but not overflow anything network wise, print wise etc.
+ // (OOB messages are the bottleneck here)
+#define SV_OUTPUTBUF_LENGTH (1024 - 16)
+ char sv_outputbuf[SV_OUTPUTBUF_LENGTH];
+ static unsigned int lasttime = 0;
+ char *cmd_aux;
+
+ // TTimo - https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=534
+ time = Com_Milliseconds();
+ if (time<(lasttime+500)) {
+ return;
+ }
+ lasttime = time;
+
+ if ( !strlen( sv_rconPassword->string ) ||
+ strcmp (Cmd_Argv(1), sv_rconPassword->string) ) {
+ valid = qfalse;
+ Com_Printf ("Bad rcon from %s:\n%s\n", NET_AdrToString (from), Cmd_Argv(2) );
+ } else {
+ valid = qtrue;
+ Com_Printf ("Rcon from %s:\n%s\n", NET_AdrToString (from), Cmd_Argv(2) );
+ }
+
+ // start redirecting all print outputs to the packet
+ svs.redirectAddress = from;
+ Com_BeginRedirect (sv_outputbuf, SV_OUTPUTBUF_LENGTH, SV_FlushRedirect);
+
+ if ( !strlen( sv_rconPassword->string ) ) {
+ Com_Printf ("No rconpassword set on the server.\n");
+ } else if ( !valid ) {
+ Com_Printf ("Bad rconpassword.\n");
+ } else {
+ remaining[0] = 0;
+
+ // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=543
+ // get the command directly, "rcon <pass> <command>" to avoid quoting issues
+ // extract the command by walking
+ // since the cmd formatting can fuckup (amount of spaces), using a dumb step by step parsing
+ cmd_aux = Cmd_Cmd();
+ cmd_aux+=4;
+ while(cmd_aux[0]==' ')
+ cmd_aux++;
+ while(cmd_aux[0] && cmd_aux[0]!=' ') // password
+ cmd_aux++;
+ while(cmd_aux[0]==' ')
+ cmd_aux++;
+
+ Q_strcat( remaining, sizeof(remaining), cmd_aux);
+
+ Cmd_ExecuteString (remaining);
+
+ }
+
+ Com_EndRedirect ();
+}
+
+/*
+=================
+SV_ConnectionlessPacket
+
+A connectionless packet has four leading 0xff
+characters to distinguish it from a game channel.
+Clients that are in the game can still send
+connectionless packets.
+=================
+*/
+void SV_ConnectionlessPacket( netadr_t from, msg_t *msg ) {
+ char *s;
+ char *c;
+
+ MSG_BeginReadingOOB( msg );
+ MSG_ReadLong( msg ); // skip the -1 marker
+
+ if (!Q_strncmp("connect", &msg->data[4], 7)) {
+ Huff_Decompress(msg, 12);
+ }
+
+ s = MSG_ReadStringLine( msg );
+ Cmd_TokenizeString( s );
+
+ c = Cmd_Argv(0);
+ Com_DPrintf ("SV packet %s : %s\n", NET_AdrToString(from), c);
+
+ if (!Q_stricmp(c, "getstatus")) {
+ SVC_Status( from );
+ } else if (!Q_stricmp(c, "getinfo")) {
+ SVC_Info( from );
+ } else if (!Q_stricmp(c, "getchallenge")) {
+ SV_GetChallenge( from );
+ } else if (!Q_stricmp(c, "connect")) {
+ SV_DirectConnect( from );
+ } else if (!Q_stricmp(c, "ipAuthorize")) {
+ SV_AuthorizeIpPacket( from );
+ } else if (!Q_stricmp(c, "rcon")) {
+ SVC_RemoteCommand( from, msg );
+ } else if (!Q_stricmp(c, "disconnect")) {
+ // if a client starts up a local server, we may see some spurious
+ // server disconnect messages when their new server sees our final
+ // sequenced messages to the old client
+ } else {
+ Com_DPrintf ("bad connectionless packet from %s:\n%s\n"
+ , NET_AdrToString (from), s);
+ }
+}
+
+//============================================================================
+
+/*
+=================
+SV_ReadPackets
+=================
+*/
+void SV_PacketEvent( netadr_t from, msg_t *msg ) {
+ int i;
+ client_t *cl;
+ int qport;
+
+ // check for connectionless packet (0xffffffff) first
+ if ( msg->cursize >= 4 && *(int *)msg->data == -1) {
+ SV_ConnectionlessPacket( from, msg );
+ return;
+ }
+
+ // read the qport out of the message so we can fix up
+ // stupid address translating routers
+ MSG_BeginReadingOOB( msg );
+ MSG_ReadLong( msg ); // sequence number
+ qport = MSG_ReadShort( msg ) & 0xffff;
+
+ // find which client the message is from
+ for (i=0, cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++) {
+ if (cl->state == CS_FREE) {
+ continue;
+ }
+ if ( !NET_CompareBaseAdr( from, cl->netchan.remoteAddress ) ) {
+ continue;
+ }
+ // it is possible to have multiple clients from a single IP
+ // address, so they are differentiated by the qport variable
+ if (cl->netchan.qport != qport) {
+ continue;
+ }
+
+ // the IP port can't be used to differentiate them, because
+ // some address translating routers periodically change UDP
+ // port assignments
+ if (cl->netchan.remoteAddress.port != from.port) {
+ Com_Printf( "SV_PacketEvent: fixing up a translated port\n" );
+ cl->netchan.remoteAddress.port = from.port;
+ }
+
+ // make sure it is a valid, in sequence packet
+ if (SV_Netchan_Process(cl, msg)) {
+ // zombie clients still need to do the Netchan_Process
+ // to make sure they don't need to retransmit the final
+ // reliable message, but they don't do any other processing
+ if (cl->state != CS_ZOMBIE) {
+ cl->lastPacketTime = svs.time; // don't timeout
+ SV_ExecuteClientMessage( cl, msg );
+ }
+ }
+ return;
+ }
+
+ // if we received a sequenced packet from an address we don't recognize,
+ // send an out of band disconnect packet to it
+ NET_OutOfBandPrint( NS_SERVER, from, "disconnect" );
+}
+
+
+/*
+===================
+SV_CalcPings
+
+Updates the cl->ping variables
+===================
+*/
+void SV_CalcPings( void ) {
+ int i, j;
+ client_t *cl;
+ int total, count;
+ int delta;
+ playerState_t *ps;
+
+ for (i=0 ; i < sv_maxclients->integer ; i++) {
+ cl = &svs.clients[i];
+ if ( cl->state != CS_ACTIVE ) {
+ cl->ping = 999;
+ continue;
+ }
+ if ( !cl->gentity ) {
+ cl->ping = 999;
+ continue;
+ }
+ if ( cl->gentity->r.svFlags & SVF_BOT ) {
+ cl->ping = 0;
+ continue;
+ }
+
+ total = 0;
+ count = 0;
+ for ( j = 0 ; j < PACKET_BACKUP ; j++ ) {
+ if ( cl->frames[j].messageAcked <= 0 ) {
+ continue;
+ }
+ delta = cl->frames[j].messageAcked - cl->frames[j].messageSent;
+ count++;
+ total += delta;
+ }
+ if (!count) {
+ cl->ping = 999;
+ } else {
+ cl->ping = total/count;
+ if ( cl->ping > 999 ) {
+ cl->ping = 999;
+ }
+ }
+
+ // let the game dll know about the ping
+ ps = SV_GameClientNum( i );
+ ps->ping = cl->ping;
+ }
+}
+
+/*
+==================
+SV_CheckTimeouts
+
+If a packet has not been received from a client for timeout->integer
+seconds, drop the conneciton. Server time is used instead of
+realtime to avoid dropping the local client while debugging.
+
+When a client is normally dropped, the client_t goes into a zombie state
+for a few seconds to make sure any final reliable message gets resent
+if necessary
+==================
+*/
+void SV_CheckTimeouts( void ) {
+ int i;
+ client_t *cl;
+ int droppoint;
+ int zombiepoint;
+
+ droppoint = svs.time - 1000 * sv_timeout->integer;
+ zombiepoint = svs.time - 1000 * sv_zombietime->integer;
+
+ for (i=0,cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++) {
+ // message times may be wrong across a changelevel
+ if (cl->lastPacketTime > svs.time) {
+ cl->lastPacketTime = svs.time;
+ }
+
+ if (cl->state == CS_ZOMBIE
+ && cl->lastPacketTime < zombiepoint) {
+ // using the client id cause the cl->name is empty at this point
+ Com_DPrintf( "Going from CS_ZOMBIE to CS_FREE for client %d\n", i );
+ cl->state = CS_FREE; // can now be reused
+ continue;
+ }
+ if ( cl->state >= CS_CONNECTED && cl->lastPacketTime < droppoint) {
+ // wait several frames so a debugger session doesn't
+ // cause a timeout
+ if ( ++cl->timeoutCount > 5 ) {
+ SV_DropClient (cl, "timed out");
+ cl->state = CS_FREE; // don't bother with zombie state
+ }
+ } else {
+ cl->timeoutCount = 0;
+ }
+ }
+}
+
+
+/*
+==================
+SV_CheckPaused
+==================
+*/
+qboolean SV_CheckPaused( void ) {
+ int count;
+ client_t *cl;
+ int i;
+
+ if ( !cl_paused->integer ) {
+ return qfalse;
+ }
+
+ // only pause if there is just a single client connected
+ count = 0;
+ for (i=0,cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++) {
+ if ( cl->state >= CS_CONNECTED && cl->netchan.remoteAddress.type != NA_BOT ) {
+ count++;
+ }
+ }
+
+ if ( count > 1 ) {
+ // don't pause
+ if (sv_paused->integer)
+ Cvar_Set("sv_paused", "0");
+ return qfalse;
+ }
+
+ if (!sv_paused->integer)
+ Cvar_Set("sv_paused", "1");
+ return qtrue;
+}
+
+/*
+==================
+SV_Frame
+
+Player movement occurs as a result of packet events, which
+happen before SV_Frame is called
+==================
+*/
+void SV_Frame( int msec ) {
+ int frameMsec;
+ int startTime;
+
+ // the menu kills the server with this cvar
+ if ( sv_killserver->integer ) {
+ SV_Shutdown ("Server was killed.\n");
+ Cvar_Set( "sv_killserver", "0" );
+ return;
+ }
+
+ if ( !com_sv_running->integer ) {
+ return;
+ }
+
+ // allow pause if only the local client is connected
+ if ( SV_CheckPaused() ) {
+ return;
+ }
+
+ // if it isn't time for the next frame, do nothing
+ if ( sv_fps->integer < 1 ) {
+ Cvar_Set( "sv_fps", "10" );
+ }
+ frameMsec = 1000 / sv_fps->integer ;
+
+ sv.timeResidual += msec;
+
+ if (!com_dedicated->integer) SV_BotFrame( svs.time + sv.timeResidual );
+
+ if ( com_dedicated->integer && sv.timeResidual < frameMsec ) {
+ // NET_Sleep will give the OS time slices until either get a packet
+ // or time enough for a server frame has gone by
+ NET_Sleep(frameMsec - sv.timeResidual);
+ return;
+ }
+
+ // if time is about to hit the 32nd bit, kick all clients
+ // and clear sv.time, rather
+ // than checking for negative time wraparound everywhere.
+ // 2giga-milliseconds = 23 days, so it won't be too often
+ if ( svs.time > 0x70000000 ) {
+ SV_Shutdown( "Restarting server due to time wrapping" );
+ Cbuf_AddText( "vstr nextmap\n" );
+ return;
+ }
+ // this can happen considerably earlier when lots of clients play and the map doesn't change
+ if ( svs.nextSnapshotEntities >= 0x7FFFFFFE - svs.numSnapshotEntities ) {
+ SV_Shutdown( "Restarting server due to numSnapshotEntities wrapping" );
+ Cbuf_AddText( "vstr nextmap\n" );
+ return;
+ }
+
+ if( sv.restartTime && svs.time >= sv.restartTime ) {
+ sv.restartTime = 0;
+ Cbuf_AddText( "map_restart 0\n" );
+ return;
+ }
+
+ // update infostrings if anything has been changed
+ if ( cvar_modifiedFlags & CVAR_SERVERINFO ) {
+ SV_SetConfigstring( CS_SERVERINFO, Cvar_InfoString( CVAR_SERVERINFO ) );
+ cvar_modifiedFlags &= ~CVAR_SERVERINFO;
+ }
+ if ( cvar_modifiedFlags & CVAR_SYSTEMINFO ) {
+ SV_SetConfigstring( CS_SYSTEMINFO, Cvar_InfoString_Big( CVAR_SYSTEMINFO ) );
+ cvar_modifiedFlags &= ~CVAR_SYSTEMINFO;
+ }
+
+ if ( com_speeds->integer ) {
+ startTime = Sys_Milliseconds ();
+ } else {
+ startTime = 0; // quite a compiler warning
+ }
+
+ // update ping based on the all received frames
+ SV_CalcPings();
+
+ if (com_dedicated->integer) SV_BotFrame( svs.time );
+
+ // run the game simulation in chunks
+ while ( sv.timeResidual >= frameMsec ) {
+ sv.timeResidual -= frameMsec;
+ svs.time += frameMsec;
+
+ // let everything in the world think and move
+ VM_Call( gvm, GAME_RUN_FRAME, svs.time );
+ }
+
+ if ( com_speeds->integer ) {
+ time_game = Sys_Milliseconds () - startTime;
+ }
+
+ // check timeouts
+ SV_CheckTimeouts();
+
+ // send messages back to the clients
+ SV_SendClientMessages();
+
+ // send a heartbeat to the master if needed
+ SV_MasterHeartbeat();
+}
+
+//============================================================================
+
diff --git a/code/server/sv_net_chan.c b/code/server/sv_net_chan.c
new file mode 100755
index 0000000..180d793
--- /dev/null
+++ b/code/server/sv_net_chan.c
@@ -0,0 +1,207 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "../game/q_shared.h"
+#include "../qcommon/qcommon.h"
+#include "server.h"
+
+/*
+==============
+SV_Netchan_Encode
+
+ // first four bytes of the data are always:
+ long reliableAcknowledge;
+
+==============
+*/
+static void SV_Netchan_Encode( client_t *client, msg_t *msg ) {
+ long reliableAcknowledge, i, index;
+ byte key, *string;
+ int srdc, sbit, soob;
+
+ if ( msg->cursize < SV_ENCODE_START ) {
+ return;
+ }
+
+ srdc = msg->readcount;
+ sbit = msg->bit;
+ soob = msg->oob;
+
+ msg->bit = 0;
+ msg->readcount = 0;
+ msg->oob = 0;
+
+ reliableAcknowledge = MSG_ReadLong(msg);
+
+ msg->oob = soob;
+ msg->bit = sbit;
+ msg->readcount = srdc;
+
+ string = (byte *)client->lastClientCommandString;
+ index = 0;
+ // xor the client challenge with the netchan sequence number
+ key = client->challenge ^ client->netchan.outgoingSequence;
+ for (i = SV_ENCODE_START; i < msg->cursize; i++) {
+ // modify the key with the last received and with this message acknowledged client command
+ if (!string[index])
+ index = 0;
+ if (string[index] > 127 || string[index] == '%') {
+ key ^= '.' << (i & 1);
+ }
+ else {
+ key ^= string[index] << (i & 1);
+ }
+ index++;
+ // encode the data with this key
+ *(msg->data + i) = *(msg->data + i) ^ key;
+ }
+}
+
+/*
+==============
+SV_Netchan_Decode
+
+ // first 12 bytes of the data are always:
+ long serverId;
+ long messageAcknowledge;
+ long reliableAcknowledge;
+
+==============
+*/
+static void SV_Netchan_Decode( client_t *client, msg_t *msg ) {
+ int serverId, messageAcknowledge, reliableAcknowledge;
+ int i, index, srdc, sbit, soob;
+ byte key, *string;
+
+ srdc = msg->readcount;
+ sbit = msg->bit;
+ soob = msg->oob;
+
+ msg->oob = 0;
+
+ serverId = MSG_ReadLong(msg);
+ messageAcknowledge = MSG_ReadLong(msg);
+ reliableAcknowledge = MSG_ReadLong(msg);
+
+ msg->oob = soob;
+ msg->bit = sbit;
+ msg->readcount = srdc;
+
+ string = (byte *)client->reliableCommands[ reliableAcknowledge & (MAX_RELIABLE_COMMANDS-1) ];
+ index = 0;
+ //
+ key = client->challenge ^ serverId ^ messageAcknowledge;
+ for (i = msg->readcount + SV_DECODE_START; i < msg->cursize; i++) {
+ // modify the key with the last sent and acknowledged server command
+ if (!string[index])
+ index = 0;
+ if (string[index] > 127 || string[index] == '%') {
+ key ^= '.' << (i & 1);
+ }
+ else {
+ key ^= string[index] << (i & 1);
+ }
+ index++;
+ // decode the data with this key
+ *(msg->data + i) = *(msg->data + i) ^ key;
+ }
+}
+
+/*
+=================
+SV_Netchan_TransmitNextFragment
+=================
+*/
+void SV_Netchan_TransmitNextFragment( client_t *client ) {
+ Netchan_TransmitNextFragment( &client->netchan );
+ if (!client->netchan.unsentFragments)
+ {
+ // make sure the netchan queue has been properly initialized (you never know)
+ if (!client->netchan_end_queue) {
+ Com_Error(ERR_DROP, "netchan queue is not properly initialized in SV_Netchan_TransmitNextFragment\n");
+ }
+ // the last fragment was transmitted, check wether we have queued messages
+ if (client->netchan_start_queue) {
+ netchan_buffer_t *netbuf;
+ Com_DPrintf("#462 Netchan_TransmitNextFragment: popping a queued message for transmit\n");
+ netbuf = client->netchan_start_queue;
+ SV_Netchan_Encode( client, &netbuf->msg );
+ Netchan_Transmit( &client->netchan, netbuf->msg.cursize, netbuf->msg.data );
+ // pop from queue
+ client->netchan_start_queue = netbuf->next;
+ if (!client->netchan_start_queue) {
+ Com_DPrintf("#462 Netchan_TransmitNextFragment: emptied queue\n");
+ client->netchan_end_queue = &client->netchan_start_queue;
+ }
+ else
+ Com_DPrintf("#462 Netchan_TransmitNextFragment: remaining queued message\n");
+ Z_Free(netbuf);
+ }
+ }
+}
+
+
+/*
+===============
+SV_Netchan_Transmit
+TTimo
+https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=462
+if there are some unsent fragments (which may happen if the snapshots
+and the gamestate are fragmenting, and collide on send for instance)
+then buffer them and make sure they get sent in correct order
+================
+*/
+
+void SV_Netchan_Transmit( client_t *client, msg_t *msg) { //int length, const byte *data ) {
+ MSG_WriteByte( msg, svc_EOF );
+ if (client->netchan.unsentFragments) {
+ netchan_buffer_t *netbuf;
+ Com_DPrintf("#462 SV_Netchan_Transmit: unsent fragments, stacked\n");
+ netbuf = (netchan_buffer_t *)Z_Malloc(sizeof(netchan_buffer_t));
+ // store the msg, we can't store it encoded, as the encoding depends on stuff we still have to finish sending
+ MSG_Copy(&netbuf->msg, netbuf->msgBuffer, sizeof( netbuf->msgBuffer ), msg);
+ netbuf->next = NULL;
+ // insert it in the queue, the message will be encoded and sent later
+ *client->netchan_end_queue = netbuf;
+ client->netchan_end_queue = &(*client->netchan_end_queue)->next;
+ // emit the next fragment of the current message for now
+ Netchan_TransmitNextFragment(&client->netchan);
+ } else {
+ SV_Netchan_Encode( client, msg );
+ Netchan_Transmit( &client->netchan, msg->cursize, msg->data );
+ }
+}
+
+/*
+=================
+Netchan_SV_Process
+=================
+*/
+qboolean SV_Netchan_Process( client_t *client, msg_t *msg ) {
+ int ret;
+ ret = Netchan_Process( &client->netchan, msg );
+ if (!ret)
+ return qfalse;
+ SV_Netchan_Decode( client, msg );
+ return qtrue;
+}
+
diff --git a/code/server/sv_rankings.c b/code/server/sv_rankings.c
new file mode 100755
index 0000000..5d8a01f
--- /dev/null
+++ b/code/server/sv_rankings.c
@@ -0,0 +1,1537 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// sv_rankings.c -- global rankings interface
+
+#include "server.h"
+#include "..\rankings\1.0\gr\grapi.h"
+#include "..\rankings\1.0\gr\grlog.h"
+
+typedef struct
+{
+ GR_CONTEXT context;
+ uint64_t game_id;
+ uint64_t match;
+ uint64_t player_id;
+ GR_PLAYER_TOKEN token;
+ grank_status_t grank_status;
+ grank_status_t final_status; // status to set after cleanup
+ uint32_t grank; // global rank
+ char name[32];
+} ranked_player_t;
+
+static int s_rankings_contexts = 0;
+static qboolean s_rankings_active = qfalse;
+static GR_CONTEXT s_server_context = 0;
+static uint64_t s_server_match = 0;
+static char* s_rankings_game_key = NULL;
+static uint64_t s_rankings_game_id = 0;
+static ranked_player_t* s_ranked_players = NULL;
+static qboolean s_server_quitting = qfalse;
+static const char s_ascii_encoding[] =
+ "0123456789abcdef"
+ "ghijklmnopqrstuv"
+ "wxyzABCDEFGHIJKL"
+ "MNOPQRSTUVWXYZ[]";
+
+// private functions
+static void SV_RankNewGameCBF( GR_NEWGAME* gr_newgame, void* cbf_arg );
+static void SV_RankUserCBF( GR_LOGIN* gr_login, void* cbf_arg );
+static void SV_RankJoinGameCBF( GR_JOINGAME* gr_joingame, void* cbf_arg );
+static void SV_RankSendReportsCBF( GR_STATUS* gr_status, void* cbf_arg );
+static void SV_RankCleanupCBF( GR_STATUS* gr_status, void* cbf_arg );
+static void SV_RankCloseContext( ranked_player_t* ranked_player );
+static int SV_RankAsciiEncode( char* dest, const unsigned char* src,
+ int src_len );
+static int SV_RankAsciiDecode( unsigned char* dest, const char* src,
+ int src_len );
+static void SV_RankEncodeGameID( uint64_t game_id, char* result,
+ int len );
+static uint64_t SV_RankDecodePlayerID( const char* string );
+static void SV_RankDecodePlayerKey( const char* string, GR_PLAYER_TOKEN key );
+static char* SV_RankStatusString( GR_STATUS status );
+static void SV_RankError( const char* fmt, ... );
+static char SV_RankGameKey[64];
+
+/*
+================
+SV_RankBegin
+================
+*/
+void SV_RankBegin( char *gamekey )
+{
+ GR_INIT init;
+ GR_STATUS status;
+
+ assert( s_rankings_contexts == 0 );
+ assert( !s_rankings_active );
+ assert( s_ranked_players == NULL );
+
+ if( sv_enableRankings->integer == 0 || Cvar_VariableValue( "g_gametype" ) == GT_SINGLE_PLAYER )
+ {
+ s_rankings_active = qfalse;
+ if( sv_rankingsActive->integer == 1 )
+ {
+ Cvar_Set( "sv_rankingsActive", "0" );
+ }
+ return;
+ }
+
+ // only allow official game key on pure servers
+ if( strcmp(gamekey, GR_GAMEKEY) == 0 )
+ {
+/*
+ if( Cvar_VariableValue("sv_pure") != 1 )
+ {
+ Cvar_Set( "sv_enableRankings", "0" );
+ return;
+ }
+*/
+
+ // substitute game-specific game key
+ switch( (int)Cvar_VariableValue("g_gametype") )
+ {
+ case GT_FFA:
+ gamekey = "Q3 Free For All";
+ break;
+ case GT_TOURNAMENT:
+ gamekey = "Q3 Tournament";
+ break;
+ case GT_TEAM:
+ gamekey = "Q3 Team Deathmatch";
+ break;
+ case GT_CTF:
+ gamekey = "Q3 Capture the Flag";
+ break;
+ case GT_1FCTF:
+ gamekey = "Q3 One Flag CTF";
+ break;
+ case GT_OBELISK:
+ gamekey = "Q3 Overload";
+ break;
+ case GT_HARVESTER:
+ gamekey = "Q3 Harvester";
+ break;
+ default:
+ break;
+ }
+ }
+ s_rankings_game_key = gamekey;
+
+ // initialize rankings
+ GRankLogLevel( GRLOG_OFF );
+ memset(SV_RankGameKey,0,sizeof(SV_RankGameKey));
+ strncpy(SV_RankGameKey,gamekey,sizeof(SV_RankGameKey)-1);
+ init = GRankInit( 1, SV_RankGameKey, GR_OPT_POLL, GR_OPT_END );
+ s_server_context = init.context;
+ s_rankings_contexts++;
+ Com_DPrintf( "SV_RankBegin(); GR_GAMEKEY is %s\n", gamekey );
+ Com_DPrintf( "SV_RankBegin(); s_rankings_contexts=%d\n",s_rankings_contexts );
+ Com_DPrintf( "SV_RankBegin(); s_server_context=%d\n",init.context );
+
+ // new game
+ if(!strlen(Cvar_VariableString( "sv_leagueName" )))
+ {
+ status = GRankNewGameAsync
+ (
+ s_server_context,
+ SV_RankNewGameCBF,
+ NULL,
+ GR_OPT_LEAGUENAME,
+ (void*)(Cvar_VariableString( "sv_leagueName" )),
+ GR_OPT_END
+ );
+ }
+ else
+ {
+ status = GRankNewGameAsync
+ (
+ s_server_context,
+ SV_RankNewGameCBF,
+ NULL,
+ GR_OPT_END
+ );
+ }
+
+ if( status != GR_STATUS_PENDING )
+ {
+ SV_RankError( "SV_RankBegin: Expected GR_STATUS_PENDING, got %s",
+ SV_RankStatusString( status ) );
+ return;
+ }
+
+ // logging
+ if( com_developer->value )
+ {
+ GRankLogLevel( GRLOG_TRACE );
+ }
+
+ // allocate rankings info for each player
+ s_ranked_players = Z_Malloc( sv_maxclients->value *
+ sizeof(ranked_player_t) );
+ memset( (void*)s_ranked_players, 0 ,sv_maxclients->value
+ * sizeof(ranked_player_t));
+}
+
+/*
+================
+SV_RankEnd
+================
+*/
+void SV_RankEnd( void )
+{
+ GR_STATUS status;
+ int i;
+
+ Com_DPrintf( "SV_RankEnd();\n" );
+
+ if( !s_rankings_active )
+ {
+ // cleanup after error during game
+ if( s_ranked_players != NULL )
+ {
+ for( i = 0; i < sv_maxclients->value; i++ )
+ {
+ if( s_ranked_players[i].context != 0 )
+ {
+ SV_RankCloseContext( &(s_ranked_players[i]) );
+ }
+ }
+ }
+ if( s_server_context != 0 )
+ {
+ SV_RankCloseContext( NULL );
+ }
+
+ return;
+ }
+
+ for( i = 0; i < sv_maxclients->value; i++ )
+ {
+ if( s_ranked_players[i].grank_status == QGR_STATUS_ACTIVE )
+ {
+ SV_RankUserLogout( i );
+ Com_DPrintf( "SV_RankEnd: SV_RankUserLogout %d\n",i );
+ }
+ }
+
+ assert( s_server_context != 0 );
+
+ // send match reports, proceed to SV_RankSendReportsCBF
+ status = GRankSendReportsAsync
+ (
+ s_server_context,
+ 0,
+ SV_RankSendReportsCBF,
+ NULL,
+ GR_OPT_END
+ );
+
+ if( status != GR_STATUS_PENDING )
+ {
+ SV_RankError( "SV_RankEnd: Expected GR_STATUS_PENDING, got %s",
+ SV_RankStatusString( status ) );
+ }
+
+ s_rankings_active = qfalse;
+ Cvar_Set( "sv_rankingsActive", "0" );
+}
+
+/*
+================
+SV_RankPoll
+================
+*/
+void SV_RankPoll( void )
+{
+ GRankPoll();
+}
+
+/*
+================
+SV_RankCheckInit
+================
+*/
+qboolean SV_RankCheckInit( void )
+{
+ return (s_rankings_contexts > 0);
+}
+
+/*
+================
+SV_RankActive
+================
+*/
+qboolean SV_RankActive( void )
+{
+ return s_rankings_active;
+}
+
+/*
+=================
+SV_RankUserStatus
+=================
+*/
+grank_status_t SV_RankUserStatus( int index )
+{
+ if( !s_rankings_active )
+ {
+ return GR_STATUS_ERROR;
+ }
+
+ assert( s_ranked_players != NULL );
+ assert( index >= 0 );
+ assert( index < sv_maxclients->value );
+
+ return s_ranked_players[index].grank_status;
+}
+
+/*
+================
+SV_RankUserGRank
+================
+*/
+int SV_RankUserGrank( int index )
+{
+ if( !s_rankings_active )
+ {
+ return 0;
+ }
+
+ assert( s_ranked_players != NULL );
+ assert( index >= 0 );
+ assert( index < sv_maxclients->value );
+
+ return s_ranked_players[index].grank;
+}
+
+/*
+================
+SV_RankUserReset
+================
+*/
+void SV_RankUserReset( int index )
+{
+ if( !s_rankings_active )
+ {
+ return;
+ }
+
+ assert( s_ranked_players != NULL );
+ assert( index >= 0 );
+ assert( index < sv_maxclients->value );
+
+ switch( s_ranked_players[index].grank_status )
+ {
+ case QGR_STATUS_SPECTATOR:
+ case QGR_STATUS_NO_USER:
+ case QGR_STATUS_BAD_PASSWORD:
+ case QGR_STATUS_USER_EXISTS:
+ case QGR_STATUS_NO_MEMBERSHIP:
+ case QGR_STATUS_TIMEOUT:
+ case QGR_STATUS_ERROR:
+ s_ranked_players[index].grank_status = QGR_STATUS_NEW;
+ break;
+ default:
+ break;
+ }
+}
+
+/*
+================
+SV_RankUserSpectate
+================
+*/
+void SV_RankUserSpectate( int index )
+{
+ if( !s_rankings_active )
+ {
+ return;
+ }
+
+ assert( s_ranked_players != NULL );
+ assert( index >= 0 );
+ assert( index < sv_maxclients->value );
+
+ // GRANK_FIXME - check current status?
+ s_ranked_players[index].grank_status = QGR_STATUS_SPECTATOR;
+}
+
+/*
+================
+SV_RankUserCreate
+================
+*/
+void SV_RankUserCreate( int index, char* username, char* password,
+ char* email )
+{
+ GR_INIT init;
+ GR_STATUS status;
+
+ assert( index >= 0 );
+ assert( index < sv_maxclients->value );
+ assert( username != NULL );
+ assert( password != NULL );
+ assert( email != NULL );
+ assert( s_ranked_players );
+ assert( s_ranked_players[index].grank_status != QGR_STATUS_ACTIVE );
+
+ Com_DPrintf( "SV_RankUserCreate( %d, %s, \"****\", %s );\n", index,
+ username, email );
+
+ if( !s_rankings_active )
+ {
+ Com_DPrintf( "SV_RankUserCreate: Not ready to create\n" );
+ s_ranked_players[index].grank_status = QGR_STATUS_ERROR;
+ return;
+ }
+
+ if( s_ranked_players[index].grank_status == QGR_STATUS_ACTIVE )
+ {
+ Com_DPrintf( "SV_RankUserCreate: Got Create from active player\n" );
+ return;
+ }
+
+ // get a separate context for the new user
+ init = GRankInit( 0, SV_RankGameKey, GR_OPT_POLL, GR_OPT_END );
+ s_ranked_players[index].context = init.context;
+ s_rankings_contexts++;
+ Com_DPrintf( "SV_RankUserCreate(); s_rankings_contexts=%d\n",s_rankings_contexts );
+ Com_DPrintf( "SV_RankUserCreate(); s_ranked_players[%d].context=%d\n",index,init.context );
+
+ // attempt to create a new account, proceed to SV_RankUserCBF
+ status = GRankUserCreateAsync
+ (
+ s_ranked_players[index].context,
+ username,
+ password,
+ email,
+ SV_RankUserCBF,
+ (void*)&s_ranked_players[index],
+ GR_OPT_END
+ );
+
+ if( status == GR_STATUS_PENDING )
+ {
+ s_ranked_players[index].grank_status = QGR_STATUS_PENDING;
+ s_ranked_players[index].final_status = QGR_STATUS_NEW;
+ }
+ else
+ {
+ SV_RankError( "SV_RankUserCreate: Expected GR_STATUS_PENDING, got %s",
+ SV_RankStatusString( status ) );
+ }
+}
+
+/*
+================
+SV_RankUserLogin
+================
+*/
+void SV_RankUserLogin( int index, char* username, char* password )
+{
+ GR_INIT init;
+ GR_STATUS status;
+
+ assert( index >= 0 );
+ assert( index < sv_maxclients->value );
+ assert( username != NULL );
+ assert( password != NULL );
+ assert( s_ranked_players );
+ assert( s_ranked_players[index].grank_status != QGR_STATUS_ACTIVE );
+
+ Com_DPrintf( "SV_RankUserLogin( %d, %s, \"****\" );\n", index, username );
+
+ if( !s_rankings_active )
+ {
+ Com_DPrintf( "SV_RankUserLogin: Not ready for login\n" );
+ s_ranked_players[index].grank_status = QGR_STATUS_ERROR;
+ return;
+ }
+
+ if( s_ranked_players[index].grank_status == QGR_STATUS_ACTIVE )
+ {
+ Com_DPrintf( "SV_RankUserLogin: Got Login from active player\n" );
+ return;
+ }
+
+ // get a separate context for the new user
+ init = GRankInit( 0, SV_RankGameKey, GR_OPT_POLL, GR_OPT_END );
+ s_ranked_players[index].context = init.context;
+ s_rankings_contexts++;
+ Com_DPrintf( "SV_RankUserLogin(); s_rankings_contexts=%d\n",s_rankings_contexts );
+ Com_DPrintf( "SV_RankUserLogin(); s_ranked_players[%d].context=%d\n",index,init.context );
+
+ // login user, proceed to SV_RankUserCBF
+ status = GRankUserLoginAsync
+ (
+ s_ranked_players[index].context,
+ username,
+ password,
+ SV_RankUserCBF,
+ (void*)&s_ranked_players[index],
+ GR_OPT_END
+ );
+
+ if( status == GR_STATUS_PENDING )
+ {
+ s_ranked_players[index].grank_status = QGR_STATUS_PENDING;
+ s_ranked_players[index].final_status = QGR_STATUS_NEW;
+ }
+ else
+ {
+ SV_RankError( "SV_RankUserLogin: Expected GR_STATUS_PENDING, got %s",
+ SV_RankStatusString( status ) );
+ }
+}
+
+/*
+===================
+SV_RankUserValidate
+===================
+*/
+qboolean SV_RankUserValidate( int index, const char* player_id, const char* key, int token_len, int rank, char* name )
+{
+ GR_INIT init;
+ GR_STATUS status;
+ qboolean rVal;
+ ranked_player_t* ranked_player;
+ int i;
+
+ assert( s_ranked_players );
+ assert( s_ranked_players[index].grank_status != QGR_STATUS_ACTIVE );
+
+ rVal = qfalse;
+
+ if( !s_rankings_active )
+ {
+ Com_DPrintf( "SV_RankUserValidate: Not ready to validate\n" );
+ s_ranked_players[index].grank_status = QGR_STATUS_ERROR;
+ return rVal;
+ }
+
+ ranked_player = &(s_ranked_players[index]);
+
+ if ( (player_id != NULL) && (key != NULL))
+ {
+ // the real player_id and key is set when SV_RankJoinGameCBF
+ // is called we do this so that SV_RankUserValidate
+ // can be shared by both server side login and client side login
+
+ // for client side logined in players
+ // server is creating GR_OPT_PLAYERCONTEXT
+ init = GRankInit( 0, SV_RankGameKey, GR_OPT_POLL, GR_OPT_END );
+ ranked_player->context = init.context;
+ s_rankings_contexts++;
+ Com_DPrintf( "SV_RankUserValidate(); s_rankings_contexts=%d\n",s_rankings_contexts );
+ Com_DPrintf( "SV_RankUserValidate(); s_ranked_players[%d].context=%d\n",index,init.context );
+
+ // uudecode player id and player token
+ ranked_player->player_id = SV_RankDecodePlayerID(player_id);
+ Com_DPrintf( "SV_RankUserValidate(); ranked_player->player_id =%u\n", (uint32_t)ranked_player->player_id );
+ SV_RankDecodePlayerKey(key, ranked_player->token);
+
+ // save name and check for duplicates
+ Q_strncpyz( ranked_player->name, name, sizeof(ranked_player->name) );
+ for( i = 0; i < sv_maxclients->value; i++ )
+ {
+ if( (i != index) && (s_ranked_players[i].grank_status == QGR_STATUS_ACTIVE) &&
+ (strcmp( s_ranked_players[i].name, name ) == 0) )
+ {
+ Com_DPrintf( "SV_RankUserValidate: Duplicate login\n" );
+ ranked_player->grank_status = QGR_STATUS_NO_USER;
+ ranked_player->final_status = QGR_STATUS_NEW;
+ ranked_player->grank = 0;
+ return qfalse;
+ }
+ }
+
+ // then validate
+ status = GRankPlayerValidate(
+ s_server_context,
+ ranked_player->player_id,
+ ranked_player->token,
+ token_len,
+ GR_OPT_PLAYERCONTEXT,
+ ranked_player->context,
+ GR_OPT_END);
+ }
+ else
+ {
+ // make server side login (bots) happy
+ status = GR_STATUS_OK;
+ }
+
+ if (status == GR_STATUS_OK)
+ {
+ ranked_player->grank_status = QGR_STATUS_ACTIVE;
+ ranked_player->final_status = QGR_STATUS_NEW;
+ ranked_player->grank = rank;
+ rVal = qtrue;
+ }
+ else if (status == GR_STATUS_INVALIDUSER)
+ {
+ ranked_player->grank_status = QGR_STATUS_INVALIDUSER;
+ ranked_player->final_status = QGR_STATUS_NEW;
+ ranked_player->grank = 0;
+ rVal = qfalse;
+ }
+ else
+ {
+ SV_RankError( "SV_RankUserValidate: Unexpected status %s",
+ SV_RankStatusString( status ) );
+ s_ranked_players[index].grank_status = QGR_STATUS_ERROR;
+ ranked_player->grank = 0;
+ }
+
+ return rVal;
+}
+
+/*
+================
+SV_RankUserLogout
+================
+*/
+void SV_RankUserLogout( int index )
+{
+ GR_STATUS status;
+ GR_STATUS cleanup_status;
+
+ if( !s_rankings_active )
+ {
+ return;
+ }
+
+ assert( index >= 0 );
+ assert( index < sv_maxclients->value );
+ assert( s_ranked_players );
+
+ if( s_ranked_players[index].context == 0 ) {
+ return;
+ }
+
+ Com_DPrintf( "SV_RankUserLogout( %d );\n", index );
+
+ // masqueraded player may not be active yet, if they fail validation,
+ // but still they have a context needs to be cleaned
+ // what matters is the s_ranked_players[index].context
+
+ // send reports, proceed to SV_RankSendReportsCBF
+ status = GRankSendReportsAsync
+ (
+ s_ranked_players[index].context,
+ 0,
+ SV_RankSendReportsCBF,
+ (void*)&s_ranked_players[index],
+ GR_OPT_END
+ );
+
+ if( status == GR_STATUS_PENDING )
+ {
+ s_ranked_players[index].grank_status = QGR_STATUS_PENDING;
+ s_ranked_players[index].final_status = QGR_STATUS_NEW;
+ }
+ else
+ {
+ SV_RankError( "SV_RankUserLogout: Expected GR_STATUS_PENDING, got %s",
+ SV_RankStatusString( status ) );
+
+ cleanup_status = GRankCleanupAsync
+ (
+ s_ranked_players[index].context,
+ 0,
+ SV_RankCleanupCBF,
+ (void*)&s_ranked_players[index],
+ GR_OPT_END
+ );
+
+ if( cleanup_status != GR_STATUS_PENDING )
+ {
+ SV_RankError( "SV_RankUserLogout: Expected "
+ "GR_STATUS_PENDING from GRankCleanupAsync, got %s",
+ SV_RankStatusString( cleanup_status ) );
+ SV_RankCloseContext( &(s_ranked_players[index]) );
+ }
+ }
+}
+
+/*
+================
+SV_RankReportInt
+================
+*/
+void SV_RankReportInt( int index1, int index2, int key, int value,
+ qboolean accum )
+{
+ GR_STATUS status;
+ GR_CONTEXT context;
+ uint64_t match;
+ uint64_t user1;
+ uint64_t user2;
+ int opt_accum;
+
+ if( !s_rankings_active )
+ {
+ return;
+ }
+
+ assert( index1 >= -1 );
+ assert( index1 < sv_maxclients->value );
+ assert( index2 >= -1 );
+ assert( index2 < sv_maxclients->value );
+ assert( s_ranked_players );
+
+// Com_DPrintf( "SV_RankReportInt( %d, %d, %d, %d, %d );\n", index1, index2,
+// key, value, accum );
+
+ // get context, match, and player_id for player index1
+ if( index1 == -1 )
+ {
+ context = s_server_context;
+ match = s_server_match;
+ user1 = 0;
+ }
+ else
+ {
+ if( s_ranked_players[index1].grank_status != QGR_STATUS_ACTIVE )
+ {
+ Com_DPrintf( "SV_RankReportInt: Expecting QGR_STATUS_ACTIVE"
+ " Got Unexpected status %d for player %d\n",
+ s_ranked_players[index1].grank_status, index1 );
+ return;
+ }
+
+ context = s_ranked_players[index1].context;
+ match = s_ranked_players[index1].match;
+ user1 = s_ranked_players[index1].player_id;
+ }
+
+ // get player_id for player index2
+ if( index2 == -1 )
+ {
+ user2 = 0;
+ }
+ else
+ {
+ if( s_ranked_players[index2].grank_status != QGR_STATUS_ACTIVE )
+ {
+ Com_DPrintf( "SV_RankReportInt: Expecting QGR_STATUS_ACTIVE"
+ " Got Unexpected status %d for player %d\n",
+ s_ranked_players[index2].grank_status, index2 );
+ return;
+ }
+
+ user2 = s_ranked_players[index2].player_id;
+ }
+
+ opt_accum = accum ? GR_OPT_ACCUM : GR_OPT_END;
+
+ status = GRankReportInt
+ (
+ context,
+ match,
+ user1,
+ user2,
+ key,
+ value,
+ opt_accum,
+ GR_OPT_END
+ );
+
+ if( status != GR_STATUS_OK )
+ {
+ SV_RankError( "SV_RankReportInt: Unexpected status %s",
+ SV_RankStatusString( status ) );
+ }
+
+ if( user2 != 0 )
+ {
+ context = s_ranked_players[index2].context;
+ match = s_ranked_players[index2].match;
+
+ status = GRankReportInt
+ (
+ context,
+ match,
+ user1,
+ user2,
+ key,
+ value,
+ opt_accum,
+ GR_OPT_END
+ );
+
+ if( status != GR_STATUS_OK )
+ {
+ SV_RankError( "SV_RankReportInt: Unexpected status %s",
+ SV_RankStatusString( status ) );
+ }
+ }
+}
+
+/*
+================
+SV_RankReportStr
+================
+*/
+void SV_RankReportStr( int index1, int index2, int key, char* value )
+{
+ GR_STATUS status;
+ GR_CONTEXT context;
+ uint64_t match;
+ uint64_t user1;
+ uint64_t user2;
+
+ if( !s_rankings_active )
+ {
+ return;
+ }
+
+ assert( index1 >= -1 );
+ assert( index1 < sv_maxclients->value );
+ assert( index2 >= -1 );
+ assert( index2 < sv_maxclients->value );
+ assert( s_ranked_players );
+
+// Com_DPrintf( "SV_RankReportStr( %d, %d, %d, \"%s\" );\n", index1, index2,
+// key, value );
+
+ // get context, match, and player_id for player index1
+ if( index1 == -1 )
+ {
+ context = s_server_context;
+ match = s_server_match;
+ user1 = 0;
+ }
+ else
+ {
+ if( s_ranked_players[index1].grank_status != QGR_STATUS_ACTIVE )
+ {
+ Com_DPrintf( "SV_RankReportStr: Unexpected status %d\n",
+ s_ranked_players[index1].grank_status );
+ return;
+ }
+
+ context = s_ranked_players[index1].context;
+ match = s_ranked_players[index1].match;
+ user1 = s_ranked_players[index1].player_id;
+ }
+
+ // get player_id for player index2
+ if( index2 == -1 )
+ {
+ user2 = 0;
+ }
+ else
+ {
+ if( s_ranked_players[index2].grank_status != QGR_STATUS_ACTIVE )
+ {
+ Com_DPrintf( "SV_RankReportStr: Unexpected status %d\n",
+ s_ranked_players[index2].grank_status );
+ return;
+ }
+
+ user2 = s_ranked_players[index2].player_id;
+ }
+
+ status = GRankReportStr
+ (
+ context,
+ match,
+ user1,
+ user2,
+ key,
+ value,
+ GR_OPT_END
+ );
+
+ if( status != GR_STATUS_OK )
+ {
+ SV_RankError( "SV_RankReportStr: Unexpected status %s",
+ SV_RankStatusString( status ) );
+ }
+
+ if( user2 != 0 )
+ {
+ context = s_ranked_players[index2].context;
+ match = s_ranked_players[index2].match;
+
+ status = GRankReportStr
+ (
+ context,
+ match,
+ user1,
+ user2,
+ key,
+ value,
+ GR_OPT_END
+ );
+
+ if( status != GR_STATUS_OK )
+ {
+ SV_RankError( "SV_RankReportInt: Unexpected status %s",
+ SV_RankStatusString( status ) );
+ }
+ }
+}
+
+/*
+================
+SV_RankQuit
+================
+*/
+void SV_RankQuit( void )
+{
+ int i;
+ int j = 0;
+ // yuck
+
+ while( s_rankings_contexts > 1 )
+ {
+ assert(s_ranked_players);
+ if( s_ranked_players != NULL )
+ {
+ for( i = 0; i < sv_maxclients->value; i++ )
+ {
+ // check for players that weren't yet active in SV_RankEnd
+ if( s_ranked_players[i].grank_status == QGR_STATUS_ACTIVE )
+ {
+ SV_RankUserLogout( i );
+ Com_DPrintf( "SV_RankQuit: SV_RankUserLogout %d\n",i );
+ }
+ else
+ {
+ if( s_ranked_players[i].context )
+ {
+ GR_STATUS cleanup_status;
+ cleanup_status = GRankCleanupAsync
+ (
+ s_ranked_players[i].context,
+ 0,
+ SV_RankCleanupCBF,
+ (void*)&(s_ranked_players[i]),
+ GR_OPT_END
+ );
+
+ if( cleanup_status != GR_STATUS_PENDING )
+ {
+ SV_RankError( "SV_RankQuit: Expected "
+ "GR_STATUS_PENDING from GRankCleanupAsync, got %s",
+ SV_RankStatusString( cleanup_status ) );
+ }
+ }
+ }
+ }
+ }
+ SV_RankPoll();
+
+ // should've finished by now
+ assert( (j++) < 68 );
+ }
+}
+
+/*
+==============================================================================
+
+Private Functions
+
+==============================================================================
+*/
+
+/*
+=================
+SV_RankNewGameCBF
+=================
+*/
+static void SV_RankNewGameCBF( GR_NEWGAME* gr_newgame, void* cbf_arg )
+{
+ GR_MATCH match;
+ int i;
+
+ assert( gr_newgame != NULL );
+ assert( cbf_arg == NULL );
+
+ Com_DPrintf( "SV_RankNewGameCBF( %08X, %08X );\n", gr_newgame, cbf_arg );
+
+ if( gr_newgame->status == GR_STATUS_OK )
+ {
+ char info[MAX_INFO_STRING];
+ char gameid[sizeof(s_ranked_players[i].game_id) * 4 / 3 + 2];
+
+ // save game id
+ s_rankings_game_id = gr_newgame->game_id;
+
+ // encode gameid
+ memset(gameid,0,sizeof(gameid));
+ SV_RankEncodeGameID(s_rankings_game_id,gameid,sizeof(gameid));
+
+ // set CS_GRANK rankingsGameID to pass to client
+ memset(info,0,sizeof(info));
+ Info_SetValueForKey( info, "rankingsGameKey", s_rankings_game_key );
+ Info_SetValueForKey( info, "rankingsGameID", gameid );
+ SV_SetConfigstring( CS_GRANK, info );
+
+ // initialize client status
+ for( i = 0; i < sv_maxclients->value; i++ )
+ s_ranked_players[i].grank_status = QGR_STATUS_NEW;
+
+ // start new match
+ match = GRankStartMatch( s_server_context );
+ s_server_match = match.match;
+
+ // ready to go
+ s_rankings_active = qtrue;
+ Cvar_Set( "sv_rankingsActive", "1" );
+
+ }
+ else if( gr_newgame->status == GR_STATUS_BADLEAGUE )
+ {
+ SV_RankError( "SV_RankNewGameCBF: Invalid League name\n" );
+ }
+ else
+ {
+ //GRank handle new game failure
+ // force SV_RankEnd() to run
+ //SV_RankEnd();
+ SV_RankError( "SV_RankNewGameCBF: Unexpected status %s",
+ SV_RankStatusString( gr_newgame->status ) );
+ }
+}
+
+/*
+================
+SV_RankUserCBF
+================
+*/
+static void SV_RankUserCBF( GR_LOGIN* gr_login, void* cbf_arg )
+{
+ ranked_player_t* ranked_player;
+ GR_STATUS join_status;
+ GR_STATUS cleanup_status;
+
+ assert( gr_login != NULL );
+ assert( cbf_arg != NULL );
+
+ Com_DPrintf( "SV_RankUserCBF( %08X, %08X );\n", gr_login, cbf_arg );
+
+ ranked_player = (ranked_player_t*)cbf_arg;
+ assert(ranked_player);
+ assert( ranked_player->context );
+
+ switch( gr_login->status )
+ {
+ case GR_STATUS_OK:
+ // attempt to join the game, proceed to SV_RankJoinGameCBF
+ join_status = GRankJoinGameAsync
+ (
+ ranked_player->context,
+ s_rankings_game_id,
+ SV_RankJoinGameCBF,
+ cbf_arg,
+ GR_OPT_END
+ );
+
+ if( join_status != GR_STATUS_PENDING )
+ {
+ SV_RankError( "SV_RankUserCBF: Expected GR_STATUS_PENDING "
+ "from GRankJoinGameAsync, got %s",
+ SV_RankStatusString( join_status ) );
+ }
+ break;
+ case GR_STATUS_NOUSER:
+ Com_DPrintf( "SV_RankUserCBF: Got status %s\n",
+ SV_RankStatusString( gr_login->status ) );
+ ranked_player->final_status = QGR_STATUS_NO_USER;
+ break;
+ case GR_STATUS_BADPASSWORD:
+ Com_DPrintf( "SV_RankUserCBF: Got status %s\n",
+ SV_RankStatusString( gr_login->status ) );
+ ranked_player->final_status = QGR_STATUS_BAD_PASSWORD;
+ break;
+ case GR_STATUS_TIMEOUT:
+ Com_DPrintf( "SV_RankUserCBF: Got status %s\n",
+ SV_RankStatusString( gr_login->status ) );
+ ranked_player->final_status = QGR_STATUS_TIMEOUT;
+ break;
+ default:
+ Com_DPrintf( "SV_RankUserCBF: Unexpected status %s\n",
+ SV_RankStatusString( gr_login->status ) );
+ ranked_player->final_status = QGR_STATUS_ERROR;
+ break;
+ }
+
+ if( ranked_player->final_status != QGR_STATUS_NEW )
+ {
+ // login or create failed, so clean up before the next attempt
+ cleanup_status = GRankCleanupAsync
+ (
+ ranked_player->context,
+ 0,
+ SV_RankCleanupCBF,
+ (void*)ranked_player,
+ GR_OPT_END
+ );
+
+ if( cleanup_status != GR_STATUS_PENDING )
+ {
+ SV_RankError( "SV_RankUserCBF: Expected GR_STATUS_PENDING "
+ "from GRankCleanupAsync, got %s",
+ SV_RankStatusString( cleanup_status ) );
+ SV_RankCloseContext( ranked_player );
+ }
+ }
+}
+
+/*
+================
+SV_RankJoinGameCBF
+================
+*/
+static void SV_RankJoinGameCBF( GR_JOINGAME* gr_joingame, void* cbf_arg )
+{
+ ranked_player_t* ranked_player;
+ GR_MATCH match;
+ GR_STATUS cleanup_status;
+
+ assert( gr_joingame != NULL );
+ assert( cbf_arg != NULL );
+
+ Com_DPrintf( "SV_RankJoinGameCBF( %08X, %08X );\n", gr_joingame, cbf_arg );
+
+ ranked_player = (ranked_player_t*)cbf_arg;
+
+ assert( ranked_player );
+ assert( ranked_player->context != 0 );
+
+ if( gr_joingame->status == GR_STATUS_OK )
+ {
+ int i;
+ // save user id
+ ranked_player->player_id = gr_joingame->player_id;
+ memcpy(ranked_player->token,gr_joingame->token,
+ sizeof(GR_PLAYER_TOKEN)) ;
+ match = GRankStartMatch( ranked_player->context );
+ ranked_player->match = match.match;
+ ranked_player->grank = gr_joingame->rank;
+
+ // find the index and call SV_RankUserValidate
+ for (i=0;i<sv_maxclients->value;i++)
+ if ( ranked_player == &s_ranked_players[i] )
+ SV_RankUserValidate(i,NULL,NULL,0, gr_joingame->rank,ranked_player->name);
+ }
+ else
+ {
+ //GRand handle join game failure
+ SV_RankError( "SV_RankJoinGameCBF: Unexpected status %s",
+ SV_RankStatusString( gr_joingame->status ) );
+
+ cleanup_status = GRankCleanupAsync
+ (
+ ranked_player->context,
+ 0,
+ SV_RankCleanupCBF,
+ cbf_arg,
+ GR_OPT_END
+ );
+
+ if( cleanup_status != GR_STATUS_PENDING )
+ {
+ SV_RankError( "SV_RankJoinGameCBF: Expected "
+ "GR_STATUS_PENDING from GRankCleanupAsync, got %s",
+ SV_RankStatusString( cleanup_status ) );
+ SV_RankCloseContext( ranked_player );
+ }
+ }
+}
+
+/*
+================
+SV_RankSendReportsCBF
+================
+*/
+static void SV_RankSendReportsCBF( GR_STATUS* status, void* cbf_arg )
+{
+ ranked_player_t* ranked_player;
+ GR_CONTEXT context;
+ GR_STATUS cleanup_status;
+
+ assert( status != NULL );
+ // NULL cbf_arg means server is sending match reports
+
+ Com_DPrintf( "SV_RankSendReportsCBF( %08X, %08X );\n", status, cbf_arg );
+
+ ranked_player = (ranked_player_t*)cbf_arg;
+ if( ranked_player == NULL )
+ {
+ Com_DPrintf( "SV_RankSendReportsCBF: server\n" );
+ context = s_server_context;
+ }
+ else
+ {
+ Com_DPrintf( "SV_RankSendReportsCBF: player\n" );
+ context = ranked_player->context;
+ }
+
+ //assert( context != 0 );
+ if( *status != GR_STATUS_OK )
+ {
+ SV_RankError( "SV_RankSendReportsCBF: Unexpected status %s",
+ SV_RankStatusString( *status ) );
+ }
+
+ if( context == 0 )
+ {
+ Com_DPrintf( "SV_RankSendReportsCBF: WARNING: context == 0" );
+ SV_RankCloseContext( ranked_player );
+ }
+ else
+ {
+ cleanup_status = GRankCleanupAsync
+ (
+ context,
+ 0,
+ SV_RankCleanupCBF,
+ cbf_arg,
+ GR_OPT_END
+ );
+
+ if( cleanup_status != GR_STATUS_PENDING )
+ {
+ SV_RankError( "SV_RankSendReportsCBF: Expected "
+ "GR_STATUS_PENDING from GRankCleanupAsync, got %s",
+ SV_RankStatusString( cleanup_status ) );
+ SV_RankCloseContext( ranked_player );
+ }
+ }
+}
+
+/*
+================
+SV_RankCleanupCBF
+================
+*/
+static void SV_RankCleanupCBF( GR_STATUS* status, void* cbf_arg )
+{
+ ranked_player_t* ranked_player;
+ ranked_player = (ranked_player_t*)cbf_arg;
+
+ assert( status != NULL );
+ // NULL cbf_arg means server is cleaning up
+
+ Com_DPrintf( "SV_RankCleanupCBF( %08X, %08X );\n", status, cbf_arg );
+
+ if( *status != GR_STATUS_OK )
+ {
+ SV_RankError( "SV_RankCleanupCBF: Unexpected status %s",
+ SV_RankStatusString( *status ) );
+ }
+
+ SV_RankCloseContext( ranked_player );
+}
+
+/*
+================
+SV_RankCloseContext
+================
+*/
+static void SV_RankCloseContext( ranked_player_t* ranked_player )
+{
+ if( ranked_player == NULL )
+ {
+ // server cleanup
+ if( s_server_context == 0 )
+ {
+ return;
+ }
+ s_server_context = 0;
+ s_server_match = 0;
+ }
+ else
+ {
+ // player cleanup
+ if( s_ranked_players == NULL )
+ {
+ return;
+ }
+ if( ranked_player->context == 0 )
+ {
+ return;
+ }
+ ranked_player->context = 0;
+ ranked_player->match = 0;
+ ranked_player->player_id = 0;
+ memset( ranked_player->token, 0, sizeof(GR_PLAYER_TOKEN) );
+ ranked_player->grank_status = ranked_player->final_status;
+ ranked_player->final_status = QGR_STATUS_NEW;
+ ranked_player->name[0] = '\0';
+ }
+
+ assert( s_rankings_contexts > 0 );
+ s_rankings_contexts--;
+ Com_DPrintf( "SV_RankCloseContext: s_rankings_contexts = %d\n",
+ s_rankings_contexts );
+
+ if( s_rankings_contexts == 0 )
+ {
+ GRankLogLevel( GRLOG_OFF );
+
+ if( s_ranked_players != NULL )
+ {
+ Z_Free( s_ranked_players );
+ s_ranked_players = NULL;
+ }
+
+ s_rankings_active = qfalse;
+ Cvar_Set( "sv_rankingsActive", "0" );
+ }
+}
+
+/*
+================
+SV_RankAsciiEncode
+
+Encodes src_len bytes of binary data from the src buffer as ASCII text,
+using 6 bits per character. The result string is null-terminated and
+stored in the dest buffer.
+
+The dest buffer must be at least (src_len * 4) / 3 + 2 bytes in length.
+
+Returns the length of the result string, not including the null.
+================
+*/
+static int SV_RankAsciiEncode( char* dest, const unsigned char* src,
+ int src_len )
+{
+ unsigned char bin[3];
+ unsigned char txt[4];
+ int dest_len = 0;
+ int i;
+ int j;
+ int num_chars;
+
+ assert( dest != NULL );
+ assert( src != NULL );
+
+ for( i = 0; i < src_len; i += 3 )
+ {
+ // read three bytes of input
+ for( j = 0; j < 3; j++ )
+ {
+ bin[j] = (i + j < src_len) ? src[i + j] : 0;
+ }
+
+ // get four 6-bit values from three bytes
+ txt[0] = bin[0] >> 2;
+ txt[1] = ((bin[0] << 4) | (bin[1] >> 4)) & 63;
+ txt[2] = ((bin[1] << 2) | (bin[2] >> 6)) & 63;
+ txt[3] = bin[2] & 63;
+
+ // store ASCII encoding of 6-bit values
+ num_chars = (i + 2 < src_len) ? 4 : ((src_len - i) * 4) / 3 + 1;
+ for( j = 0; j < num_chars; j++ )
+ {
+ dest[dest_len++] = s_ascii_encoding[txt[j]];
+ }
+ }
+
+ dest[dest_len] = '\0';
+
+ return dest_len;
+}
+
+/*
+================
+SV_RankAsciiDecode
+
+Decodes src_len characters of ASCII text from the src buffer, stores
+the binary result in the dest buffer.
+
+The dest buffer must be at least (src_len * 3) / 4 bytes in length.
+
+Returns the length of the binary result, or zero for invalid input.
+================
+*/
+static int SV_RankAsciiDecode( unsigned char* dest, const char* src,
+ int src_len )
+{
+ static unsigned char s_inverse_encoding[256];
+ static char s_init = 0;
+
+ unsigned char bin[3];
+ unsigned char txt[4];
+ int dest_len = 0;
+ int i;
+ int j;
+ int num_bytes;
+
+ assert( dest != NULL );
+ assert( src != NULL );
+
+ if( !s_init )
+ {
+ // initialize lookup table for decoding
+ memset( s_inverse_encoding, 255, sizeof(s_inverse_encoding) );
+ for( i = 0; i < 64; i++ )
+ {
+ s_inverse_encoding[s_ascii_encoding[i]] = i;
+ }
+ s_init = 1;
+ }
+
+ for( i = 0; i < src_len; i += 4 )
+ {
+ // read four characters of input, decode them to 6-bit values
+ for( j = 0; j < 4; j++ )
+ {
+ txt[j] = (i + j < src_len) ? s_inverse_encoding[src[i + j]] : 0;
+ if (txt[j] == 255)
+ {
+ return 0; // invalid input character
+ }
+ }
+
+ // get three bytes from four 6-bit values
+ bin[0] = (txt[0] << 2) | (txt[1] >> 4);
+ bin[1] = (txt[1] << 4) | (txt[2] >> 2);
+ bin[2] = (txt[2] << 6) | txt[3];
+
+ // store binary data
+ num_bytes = (i + 3 < src_len) ? 3 : ((src_len - i) * 3) / 4;
+ for( j = 0; j < num_bytes; j++ )
+ {
+ dest[dest_len++] = bin[j];
+ }
+ }
+
+ return dest_len;
+}
+
+/*
+================
+SV_RankEncodeGameID
+================
+*/
+static void SV_RankEncodeGameID( uint64_t game_id, char* result,
+ int len )
+{
+ assert( result != NULL );
+
+ if( len < ( ( sizeof(game_id) * 4) / 3 + 2) )
+ {
+ Com_DPrintf( "SV_RankEncodeGameID: result buffer too small\n" );
+ result[0] = '\0';
+ }
+ else
+ {
+ qint64 gameid = LittleLong64(*(qint64*)&game_id);
+ SV_RankAsciiEncode( result, (unsigned char*)&gameid,
+ sizeof(qint64) );
+ }
+}
+
+/*
+================
+SV_RankDecodePlayerID
+================
+*/
+static uint64_t SV_RankDecodePlayerID( const char* string )
+{
+ unsigned char buffer[9];
+ int len;
+ qint64 player_id;
+
+ assert( string != NULL );
+
+ len = strlen (string) ;
+ Com_DPrintf( "SV_RankDecodePlayerID: string length %d\n",len );
+ SV_RankAsciiDecode( buffer, string, len );
+ player_id = LittleLong64(*(qint64*)buffer);
+ return *(uint64_t*)&player_id;
+}
+
+/*
+================
+SV_RankDecodePlayerKey
+================
+*/
+static void SV_RankDecodePlayerKey( const char* string, GR_PLAYER_TOKEN key )
+{
+ unsigned char buffer[1400];
+ int len;
+ assert( string != NULL );
+
+ len = strlen (string) ;
+ Com_DPrintf( "SV_RankDecodePlayerKey: string length %d\n",len );
+
+ memset(key,0,sizeof(GR_PLAYER_TOKEN));
+ memset(buffer,0,sizeof(buffer));
+ memcpy( key, buffer, SV_RankAsciiDecode( buffer, string, len ) );
+}
+
+/*
+================
+SV_RankStatusString
+================
+*/
+static char* SV_RankStatusString( GR_STATUS status )
+{
+ switch( status )
+ {
+ case GR_STATUS_OK: return "GR_STATUS_OK";
+ case GR_STATUS_ERROR: return "GR_STATUS_ERROR";
+ case GR_STATUS_BADPARAMS: return "GR_STATUS_BADPARAMS";
+ case GR_STATUS_NETWORK: return "GR_STATUS_NETWORK";
+ case GR_STATUS_NOUSER: return "GR_STATUS_NOUSER";
+ case GR_STATUS_BADPASSWORD: return "GR_STATUS_BADPASSWORD";
+ case GR_STATUS_BADGAME: return "GR_STATUS_BADGAME";
+ case GR_STATUS_PENDING: return "GR_STATUS_PENDING";
+ case GR_STATUS_BADDOMAIN: return "GR_STATUS_BADDOMAIN";
+ case GR_STATUS_DOMAINLOCK: return "GR_STATUS_DOMAINLOCK";
+ case GR_STATUS_TIMEOUT: return "GR_STATUS_TIMEOUT";
+ case GR_STATUS_INVALIDUSER: return "GR_STATUS_INVALIDUSER";
+ case GR_STATUS_INVALIDCONTEXT: return "GR_STATUS_INVALIDCONTEXT";
+ default: return "(UNKNOWN)";
+ }
+}
+
+/*
+================
+SV_RankError
+================
+*/
+static void SV_RankError( const char* fmt, ... )
+{
+ va_list arg_ptr;
+ char text[1024];
+
+ va_start( arg_ptr, fmt );
+ vsprintf( text, fmt, arg_ptr );
+ va_end( arg_ptr );
+
+ Com_DPrintf( "****************************************\n" );
+ Com_DPrintf( "SV_RankError: %s\n", text );
+ Com_DPrintf( "****************************************\n" );
+
+ s_rankings_active = qfalse;
+ Cvar_Set( "sv_rankingsActive", "0" );
+ // FIXME - attempt clean shutdown?
+}
+
diff --git a/code/server/sv_snapshot.c b/code/server/sv_snapshot.c
new file mode 100755
index 0000000..59910c7
--- /dev/null
+++ b/code/server/sv_snapshot.c
@@ -0,0 +1,682 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "server.h"
+
+
+/*
+=============================================================================
+
+Delta encode a client frame onto the network channel
+
+A normal server packet will look like:
+
+4 sequence number (high bit set if an oversize fragment)
+<optional reliable commands>
+1 svc_snapshot
+4 last client reliable command
+4 serverTime
+1 lastframe for delta compression
+1 snapFlags
+1 areaBytes
+<areabytes>
+<playerstate>
+<packetentities>
+
+=============================================================================
+*/
+
+/*
+=============
+SV_EmitPacketEntities
+
+Writes a delta update of an entityState_t list to the message.
+=============
+*/
+static void SV_EmitPacketEntities( clientSnapshot_t *from, clientSnapshot_t *to, msg_t *msg ) {
+ entityState_t *oldent, *newent;
+ int oldindex, newindex;
+ int oldnum, newnum;
+ int from_num_entities;
+
+ // generate the delta update
+ if ( !from ) {
+ from_num_entities = 0;
+ } else {
+ from_num_entities = from->num_entities;
+ }
+
+ newent = NULL;
+ oldent = NULL;
+ newindex = 0;
+ oldindex = 0;
+ while ( newindex < to->num_entities || oldindex < from_num_entities ) {
+ if ( newindex >= to->num_entities ) {
+ newnum = 9999;
+ } else {
+ newent = &svs.snapshotEntities[(to->first_entity+newindex) % svs.numSnapshotEntities];
+ newnum = newent->number;
+ }
+
+ if ( oldindex >= from_num_entities ) {
+ oldnum = 9999;
+ } else {
+ oldent = &svs.snapshotEntities[(from->first_entity+oldindex) % svs.numSnapshotEntities];
+ oldnum = oldent->number;
+ }
+
+ if ( newnum == oldnum ) {
+ // delta update from old position
+ // because the force parm is qfalse, this will not result
+ // in any bytes being emited if the entity has not changed at all
+ MSG_WriteDeltaEntity (msg, oldent, newent, qfalse );
+ oldindex++;
+ newindex++;
+ continue;
+ }
+
+ if ( newnum < oldnum ) {
+ // this is a new entity, send it from the baseline
+ MSG_WriteDeltaEntity (msg, &sv.svEntities[newnum].baseline, newent, qtrue );
+ newindex++;
+ continue;
+ }
+
+ if ( newnum > oldnum ) {
+ // the old entity isn't present in the new message
+ MSG_WriteDeltaEntity (msg, oldent, NULL, qtrue );
+ oldindex++;
+ continue;
+ }
+ }
+
+ MSG_WriteBits( msg, (MAX_GENTITIES-1), GENTITYNUM_BITS ); // end of packetentities
+}
+
+
+
+/*
+==================
+SV_WriteSnapshotToClient
+==================
+*/
+static void SV_WriteSnapshotToClient( client_t *client, msg_t *msg ) {
+ clientSnapshot_t *frame, *oldframe;
+ int lastframe;
+ int i;
+ int snapFlags;
+
+ // this is the snapshot we are creating
+ frame = &client->frames[ client->netchan.outgoingSequence & PACKET_MASK ];
+
+ // try to use a previous frame as the source for delta compressing the snapshot
+ if ( client->deltaMessage <= 0 || client->state != CS_ACTIVE ) {
+ // client is asking for a retransmit
+ oldframe = NULL;
+ lastframe = 0;
+ } else if ( client->netchan.outgoingSequence - client->deltaMessage
+ >= (PACKET_BACKUP - 3) ) {
+ // client hasn't gotten a good message through in a long time
+ Com_DPrintf ("%s: Delta request from out of date packet.\n", client->name);
+ oldframe = NULL;
+ lastframe = 0;
+ } else {
+ // we have a valid snapshot to delta from
+ oldframe = &client->frames[ client->deltaMessage & PACKET_MASK ];
+ lastframe = client->netchan.outgoingSequence - client->deltaMessage;
+
+ // the snapshot's entities may still have rolled off the buffer, though
+ if ( oldframe->first_entity <= svs.nextSnapshotEntities - svs.numSnapshotEntities ) {
+ Com_DPrintf ("%s: Delta request from out of date entities.\n", client->name);
+ oldframe = NULL;
+ lastframe = 0;
+ }
+ }
+
+ MSG_WriteByte (msg, svc_snapshot);
+
+ // NOTE, MRE: now sent at the start of every message from server to client
+ // let the client know which reliable clientCommands we have received
+ //MSG_WriteLong( msg, client->lastClientCommand );
+
+ // send over the current server time so the client can drift
+ // its view of time to try to match
+ MSG_WriteLong (msg, svs.time);
+
+ // what we are delta'ing from
+ MSG_WriteByte (msg, lastframe);
+
+ snapFlags = svs.snapFlagServerBit;
+ if ( client->rateDelayed ) {
+ snapFlags |= SNAPFLAG_RATE_DELAYED;
+ }
+ if ( client->state != CS_ACTIVE ) {
+ snapFlags |= SNAPFLAG_NOT_ACTIVE;
+ }
+
+ MSG_WriteByte (msg, snapFlags);
+
+ // send over the areabits
+ MSG_WriteByte (msg, frame->areabytes);
+ MSG_WriteData (msg, frame->areabits, frame->areabytes);
+
+ // delta encode the playerstate
+ if ( oldframe ) {
+ MSG_WriteDeltaPlayerstate( msg, &oldframe->ps, &frame->ps );
+ } else {
+ MSG_WriteDeltaPlayerstate( msg, NULL, &frame->ps );
+ }
+
+ // delta encode the entities
+ SV_EmitPacketEntities (oldframe, frame, msg);
+
+ // padding for rate debugging
+ if ( sv_padPackets->integer ) {
+ for ( i = 0 ; i < sv_padPackets->integer ; i++ ) {
+ MSG_WriteByte (msg, svc_nop);
+ }
+ }
+}
+
+
+/*
+==================
+SV_UpdateServerCommandsToClient
+
+(re)send all server commands the client hasn't acknowledged yet
+==================
+*/
+void SV_UpdateServerCommandsToClient( client_t *client, msg_t *msg ) {
+ int i;
+
+ // write any unacknowledged serverCommands
+ for ( i = client->reliableAcknowledge + 1 ; i <= client->reliableSequence ; i++ ) {
+ MSG_WriteByte( msg, svc_serverCommand );
+ MSG_WriteLong( msg, i );
+ MSG_WriteString( msg, client->reliableCommands[ i & (MAX_RELIABLE_COMMANDS-1) ] );
+ }
+ client->reliableSent = client->reliableSequence;
+}
+
+/*
+=============================================================================
+
+Build a client snapshot structure
+
+=============================================================================
+*/
+
+#define MAX_SNAPSHOT_ENTITIES 1024
+typedef struct {
+ int numSnapshotEntities;
+ int snapshotEntities[MAX_SNAPSHOT_ENTITIES];
+} snapshotEntityNumbers_t;
+
+/*
+=======================
+SV_QsortEntityNumbers
+=======================
+*/
+static int QDECL SV_QsortEntityNumbers( const void *a, const void *b ) {
+ int *ea, *eb;
+
+ ea = (int *)a;
+ eb = (int *)b;
+
+ if ( *ea == *eb ) {
+ Com_Error( ERR_DROP, "SV_QsortEntityStates: duplicated entity" );
+ }
+
+ if ( *ea < *eb ) {
+ return -1;
+ }
+
+ return 1;
+}
+
+
+/*
+===============
+SV_AddEntToSnapshot
+===============
+*/
+static void SV_AddEntToSnapshot( svEntity_t *svEnt, sharedEntity_t *gEnt, snapshotEntityNumbers_t *eNums ) {
+ // if we have already added this entity to this snapshot, don't add again
+ if ( svEnt->snapshotCounter == sv.snapshotCounter ) {
+ return;
+ }
+ svEnt->snapshotCounter = sv.snapshotCounter;
+
+ // if we are full, silently discard entities
+ if ( eNums->numSnapshotEntities == MAX_SNAPSHOT_ENTITIES ) {
+ return;
+ }
+
+ eNums->snapshotEntities[ eNums->numSnapshotEntities ] = gEnt->s.number;
+ eNums->numSnapshotEntities++;
+}
+
+/*
+===============
+SV_AddEntitiesVisibleFromPoint
+===============
+*/
+static void SV_AddEntitiesVisibleFromPoint( vec3_t origin, clientSnapshot_t *frame,
+ snapshotEntityNumbers_t *eNums, qboolean portal ) {
+ int e, i;
+ sharedEntity_t *ent;
+ svEntity_t *svEnt;
+ int l;
+ int clientarea, clientcluster;
+ int leafnum;
+ int c_fullsend;
+ byte *clientpvs;
+ byte *bitvector;
+
+ // during an error shutdown message we may need to transmit
+ // the shutdown message after the server has shutdown, so
+ // specfically check for it
+ if ( !sv.state ) {
+ return;
+ }
+
+ leafnum = CM_PointLeafnum (origin);
+ clientarea = CM_LeafArea (leafnum);
+ clientcluster = CM_LeafCluster (leafnum);
+
+ // calculate the visible areas
+ frame->areabytes = CM_WriteAreaBits( frame->areabits, clientarea );
+
+ clientpvs = CM_ClusterPVS (clientcluster);
+
+ c_fullsend = 0;
+
+ for ( e = 0 ; e < sv.num_entities ; e++ ) {
+ ent = SV_GentityNum(e);
+
+ // never send entities that aren't linked in
+ if ( !ent->r.linked ) {
+ continue;
+ }
+
+ if (ent->s.number != e) {
+ Com_DPrintf ("FIXING ENT->S.NUMBER!!!\n");
+ ent->s.number = e;
+ }
+
+ // entities can be flagged to explicitly not be sent to the client
+ if ( ent->r.svFlags & SVF_NOCLIENT ) {
+ continue;
+ }
+
+ // entities can be flagged to be sent to only one client
+ if ( ent->r.svFlags & SVF_SINGLECLIENT ) {
+ if ( ent->r.singleClient != frame->ps.clientNum ) {
+ continue;
+ }
+ }
+ // entities can be flagged to be sent to everyone but one client
+ if ( ent->r.svFlags & SVF_NOTSINGLECLIENT ) {
+ if ( ent->r.singleClient == frame->ps.clientNum ) {
+ continue;
+ }
+ }
+ // entities can be flagged to be sent to a given mask of clients
+ if ( ent->r.svFlags & SVF_CLIENTMASK ) {
+ if (frame->ps.clientNum >= 32)
+ Com_Error( ERR_DROP, "SVF_CLIENTMASK: cientNum > 32\n" );
+ if (~ent->r.singleClient & (1 << frame->ps.clientNum))
+ continue;
+ }
+
+ svEnt = SV_SvEntityForGentity( ent );
+
+ // don't double add an entity through portals
+ if ( svEnt->snapshotCounter == sv.snapshotCounter ) {
+ continue;
+ }
+
+ // broadcast entities are always sent
+ if ( ent->r.svFlags & SVF_BROADCAST ) {
+ SV_AddEntToSnapshot( svEnt, ent, eNums );
+ continue;
+ }
+
+ // ignore if not touching a PV leaf
+ // check area
+ if ( !CM_AreasConnected( clientarea, svEnt->areanum ) ) {
+ // doors can legally straddle two areas, so
+ // we may need to check another one
+ if ( !CM_AreasConnected( clientarea, svEnt->areanum2 ) ) {
+ continue; // blocked by a door
+ }
+ }
+
+ bitvector = clientpvs;
+
+ // check individual leafs
+ if ( !svEnt->numClusters ) {
+ continue;
+ }
+ l = 0;
+ for ( i=0 ; i < svEnt->numClusters ; i++ ) {
+ l = svEnt->clusternums[i];
+ if ( bitvector[l >> 3] & (1 << (l&7) ) ) {
+ break;
+ }
+ }
+
+ // if we haven't found it to be visible,
+ // check overflow clusters that coudln't be stored
+ if ( i == svEnt->numClusters ) {
+ if ( svEnt->lastCluster ) {
+ for ( ; l <= svEnt->lastCluster ; l++ ) {
+ if ( bitvector[l >> 3] & (1 << (l&7) ) ) {
+ break;
+ }
+ }
+ if ( l == svEnt->lastCluster ) {
+ continue; // not visible
+ }
+ } else {
+ continue;
+ }
+ }
+
+ // add it
+ SV_AddEntToSnapshot( svEnt, ent, eNums );
+
+ // if its a portal entity, add everything visible from its camera position
+ if ( ent->r.svFlags & SVF_PORTAL ) {
+ if ( ent->s.generic1 ) {
+ vec3_t dir;
+ VectorSubtract(ent->s.origin, origin, dir);
+ if ( VectorLengthSquared(dir) > (float) ent->s.generic1 * ent->s.generic1 ) {
+ continue;
+ }
+ }
+ SV_AddEntitiesVisibleFromPoint( ent->s.origin2, frame, eNums, qtrue );
+ }
+
+ }
+}
+
+/*
+=============
+SV_BuildClientSnapshot
+
+Decides which entities are going to be visible to the client, and
+copies off the playerstate and areabits.
+
+This properly handles multiple recursive portals, but the render
+currently doesn't.
+
+For viewing through other player's eyes, clent can be something other than client->gentity
+=============
+*/
+static void SV_BuildClientSnapshot( client_t *client ) {
+ vec3_t org;
+ clientSnapshot_t *frame;
+ snapshotEntityNumbers_t entityNumbers;
+ int i;
+ sharedEntity_t *ent;
+ entityState_t *state;
+ svEntity_t *svEnt;
+ sharedEntity_t *clent;
+ int clientNum;
+ playerState_t *ps;
+
+ // bump the counter used to prevent double adding
+ sv.snapshotCounter++;
+
+ // this is the frame we are creating
+ frame = &client->frames[ client->netchan.outgoingSequence & PACKET_MASK ];
+
+ // clear everything in this snapshot
+ entityNumbers.numSnapshotEntities = 0;
+ Com_Memset( frame->areabits, 0, sizeof( frame->areabits ) );
+
+ // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=62
+ frame->num_entities = 0;
+
+ clent = client->gentity;
+ if ( !clent || client->state == CS_ZOMBIE ) {
+ return;
+ }
+
+ // grab the current playerState_t
+ ps = SV_GameClientNum( client - svs.clients );
+ frame->ps = *ps;
+
+ // never send client's own entity, because it can
+ // be regenerated from the playerstate
+ clientNum = frame->ps.clientNum;
+ if ( clientNum < 0 || clientNum >= MAX_GENTITIES ) {
+ Com_Error( ERR_DROP, "SV_SvEntityForGentity: bad gEnt" );
+ }
+ svEnt = &sv.svEntities[ clientNum ];
+
+ svEnt->snapshotCounter = sv.snapshotCounter;
+
+ // find the client's viewpoint
+ VectorCopy( ps->origin, org );
+ org[2] += ps->viewheight;
+
+ // add all the entities directly visible to the eye, which
+ // may include portal entities that merge other viewpoints
+ SV_AddEntitiesVisibleFromPoint( org, frame, &entityNumbers, qfalse );
+
+ // if there were portals visible, there may be out of order entities
+ // in the list which will need to be resorted for the delta compression
+ // to work correctly. This also catches the error condition
+ // of an entity being included twice.
+ qsort( entityNumbers.snapshotEntities, entityNumbers.numSnapshotEntities,
+ sizeof( entityNumbers.snapshotEntities[0] ), SV_QsortEntityNumbers );
+
+ // now that all viewpoint's areabits have been OR'd together, invert
+ // all of them to make it a mask vector, which is what the renderer wants
+ for ( i = 0 ; i < MAX_MAP_AREA_BYTES/4 ; i++ ) {
+ ((int *)frame->areabits)[i] = ((int *)frame->areabits)[i] ^ -1;
+ }
+
+ // copy the entity states out
+ frame->num_entities = 0;
+ frame->first_entity = svs.nextSnapshotEntities;
+ for ( i = 0 ; i < entityNumbers.numSnapshotEntities ; i++ ) {
+ ent = SV_GentityNum(entityNumbers.snapshotEntities[i]);
+ state = &svs.snapshotEntities[svs.nextSnapshotEntities % svs.numSnapshotEntities];
+ *state = ent->s;
+ svs.nextSnapshotEntities++;
+ // this should never hit, map should always be restarted first in SV_Frame
+ if ( svs.nextSnapshotEntities >= 0x7FFFFFFE ) {
+ Com_Error(ERR_FATAL, "svs.nextSnapshotEntities wrapped");
+ }
+ frame->num_entities++;
+ }
+}
+
+
+/*
+====================
+SV_RateMsec
+
+Return the number of msec a given size message is supposed
+to take to clear, based on the current rate
+====================
+*/
+#define HEADER_RATE_BYTES 48 // include our header, IP header, and some overhead
+static int SV_RateMsec( client_t *client, int messageSize ) {
+ int rate;
+ int rateMsec;
+
+ // individual messages will never be larger than fragment size
+ if ( messageSize > 1500 ) {
+ messageSize = 1500;
+ }
+ rate = client->rate;
+ if ( sv_maxRate->integer ) {
+ if ( sv_maxRate->integer < 1000 ) {
+ Cvar_Set( "sv_MaxRate", "1000" );
+ }
+ if ( sv_maxRate->integer < rate ) {
+ rate = sv_maxRate->integer;
+ }
+ }
+ rateMsec = ( messageSize + HEADER_RATE_BYTES ) * 1000 / rate;
+
+ return rateMsec;
+}
+
+/*
+=======================
+SV_SendMessageToClient
+
+Called by SV_SendClientSnapshot and SV_SendClientGameState
+=======================
+*/
+void SV_SendMessageToClient( msg_t *msg, client_t *client ) {
+ int rateMsec;
+
+ // record information about the message
+ client->frames[client->netchan.outgoingSequence & PACKET_MASK].messageSize = msg->cursize;
+ client->frames[client->netchan.outgoingSequence & PACKET_MASK].messageSent = svs.time;
+ client->frames[client->netchan.outgoingSequence & PACKET_MASK].messageAcked = -1;
+
+ // send the datagram
+ SV_Netchan_Transmit( client, msg ); //msg->cursize, msg->data );
+
+ // set nextSnapshotTime based on rate and requested number of updates
+
+ // local clients get snapshots every frame
+ // TTimo - https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=491
+ // added sv_lanForceRate check
+ if ( client->netchan.remoteAddress.type == NA_LOOPBACK || (sv_lanForceRate->integer && Sys_IsLANAddress (client->netchan.remoteAddress)) ) {
+ client->nextSnapshotTime = svs.time - 1;
+ return;
+ }
+
+ // normal rate / snapshotMsec calculation
+ rateMsec = SV_RateMsec( client, msg->cursize );
+
+ if ( rateMsec < client->snapshotMsec ) {
+ // never send more packets than this, no matter what the rate is at
+ rateMsec = client->snapshotMsec;
+ client->rateDelayed = qfalse;
+ } else {
+ client->rateDelayed = qtrue;
+ }
+
+ client->nextSnapshotTime = svs.time + rateMsec;
+
+ // don't pile up empty snapshots while connecting
+ if ( client->state != CS_ACTIVE ) {
+ // a gigantic connection message may have already put the nextSnapshotTime
+ // more than a second away, so don't shorten it
+ // do shorten if client is downloading
+ if ( !*client->downloadName && client->nextSnapshotTime < svs.time + 1000 ) {
+ client->nextSnapshotTime = svs.time + 1000;
+ }
+ }
+}
+
+
+/*
+=======================
+SV_SendClientSnapshot
+
+Also called by SV_FinalMessage
+
+=======================
+*/
+void SV_SendClientSnapshot( client_t *client ) {
+ byte msg_buf[MAX_MSGLEN];
+ msg_t msg;
+
+ // build the snapshot
+ SV_BuildClientSnapshot( client );
+
+ // bots need to have their snapshots build, but
+ // the query them directly without needing to be sent
+ if ( client->gentity && client->gentity->r.svFlags & SVF_BOT ) {
+ return;
+ }
+
+ MSG_Init (&msg, msg_buf, sizeof(msg_buf));
+ msg.allowoverflow = qtrue;
+
+ // NOTE, MRE: all server->client messages now acknowledge
+ // let the client know which reliable clientCommands we have received
+ MSG_WriteLong( &msg, client->lastClientCommand );
+
+ // (re)send any reliable server commands
+ SV_UpdateServerCommandsToClient( client, &msg );
+
+ // send over all the relevant entityState_t
+ // and the playerState_t
+ SV_WriteSnapshotToClient( client, &msg );
+
+ // Add any download data if the client is downloading
+ SV_WriteDownloadToClient( client, &msg );
+
+ // check for overflow
+ if ( msg.overflowed ) {
+ Com_Printf ("WARNING: msg overflowed for %s\n", client->name);
+ MSG_Clear (&msg);
+ }
+
+ SV_SendMessageToClient( &msg, client );
+}
+
+
+/*
+=======================
+SV_SendClientMessages
+=======================
+*/
+void SV_SendClientMessages( void ) {
+ int i;
+ client_t *c;
+
+ // send a message to each connected client
+ for (i=0, c = svs.clients ; i < sv_maxclients->integer ; i++, c++) {
+ if (!c->state) {
+ continue; // not connected
+ }
+
+ if ( svs.time < c->nextSnapshotTime ) {
+ continue; // not time yet
+ }
+
+ // send additional message fragments if the last message
+ // was too large to send at once
+ if ( c->netchan.unsentFragments ) {
+ c->nextSnapshotTime = svs.time +
+ SV_RateMsec( c, c->netchan.unsentLength - c->netchan.unsentFragmentStart );
+ SV_Netchan_TransmitNextFragment( c );
+ continue;
+ }
+
+ // generate and send a new message
+ SV_SendClientSnapshot( c );
+ }
+}
+
diff --git a/code/server/sv_world.c b/code/server/sv_world.c
new file mode 100755
index 0000000..acb5761
--- /dev/null
+++ b/code/server/sv_world.c
@@ -0,0 +1,691 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// world.c -- world query functions
+
+#include "server.h"
+
+/*
+================
+SV_ClipHandleForEntity
+
+Returns a headnode that can be used for testing or clipping to a
+given entity. If the entity is a bsp model, the headnode will
+be returned, otherwise a custom box tree will be constructed.
+================
+*/
+clipHandle_t SV_ClipHandleForEntity( const sharedEntity_t *ent ) {
+ if ( ent->r.bmodel ) {
+ // explicit hulls in the BSP model
+ return CM_InlineModel( ent->s.modelindex );
+ }
+ if ( ent->r.svFlags & SVF_CAPSULE ) {
+ // create a temp capsule from bounding box sizes
+ return CM_TempBoxModel( ent->r.mins, ent->r.maxs, qtrue );
+ }
+
+ // create a temp tree from bounding box sizes
+ return CM_TempBoxModel( ent->r.mins, ent->r.maxs, qfalse );
+}
+
+
+
+/*
+===============================================================================
+
+ENTITY CHECKING
+
+To avoid linearly searching through lists of entities during environment testing,
+the world is carved up with an evenly spaced, axially aligned bsp tree. Entities
+are kept in chains either at the final leafs, or at the first node that splits
+them, which prevents having to deal with multiple fragments of a single entity.
+
+===============================================================================
+*/
+
+typedef struct worldSector_s {
+ int axis; // -1 = leaf node
+ float dist;
+ struct worldSector_s *children[2];
+ svEntity_t *entities;
+} worldSector_t;
+
+#define AREA_DEPTH 4
+#define AREA_NODES 64
+
+worldSector_t sv_worldSectors[AREA_NODES];
+int sv_numworldSectors;
+
+
+/*
+===============
+SV_SectorList_f
+===============
+*/
+void SV_SectorList_f( void ) {
+ int i, c;
+ worldSector_t *sec;
+ svEntity_t *ent;
+
+ for ( i = 0 ; i < AREA_NODES ; i++ ) {
+ sec = &sv_worldSectors[i];
+
+ c = 0;
+ for ( ent = sec->entities ; ent ; ent = ent->nextEntityInWorldSector ) {
+ c++;
+ }
+ Com_Printf( "sector %i: %i entities\n", i, c );
+ }
+}
+
+/*
+===============
+SV_CreateworldSector
+
+Builds a uniformly subdivided tree for the given world size
+===============
+*/
+worldSector_t *SV_CreateworldSector( int depth, vec3_t mins, vec3_t maxs ) {
+ worldSector_t *anode;
+ vec3_t size;
+ vec3_t mins1, maxs1, mins2, maxs2;
+
+ anode = &sv_worldSectors[sv_numworldSectors];
+ sv_numworldSectors++;
+
+ if (depth == AREA_DEPTH) {
+ anode->axis = -1;
+ anode->children[0] = anode->children[1] = NULL;
+ return anode;
+ }
+
+ VectorSubtract (maxs, mins, size);
+ if (size[0] > size[1]) {
+ anode->axis = 0;
+ } else {
+ anode->axis = 1;
+ }
+
+ anode->dist = 0.5 * (maxs[anode->axis] + mins[anode->axis]);
+ VectorCopy (mins, mins1);
+ VectorCopy (mins, mins2);
+ VectorCopy (maxs, maxs1);
+ VectorCopy (maxs, maxs2);
+
+ maxs1[anode->axis] = mins2[anode->axis] = anode->dist;
+
+ anode->children[0] = SV_CreateworldSector (depth+1, mins2, maxs2);
+ anode->children[1] = SV_CreateworldSector (depth+1, mins1, maxs1);
+
+ return anode;
+}
+
+/*
+===============
+SV_ClearWorld
+
+===============
+*/
+void SV_ClearWorld( void ) {
+ clipHandle_t h;
+ vec3_t mins, maxs;
+
+ Com_Memset( sv_worldSectors, 0, sizeof(sv_worldSectors) );
+ sv_numworldSectors = 0;
+
+ // get world map bounds
+ h = CM_InlineModel( 0 );
+ CM_ModelBounds( h, mins, maxs );
+ SV_CreateworldSector( 0, mins, maxs );
+}
+
+
+/*
+===============
+SV_UnlinkEntity
+
+===============
+*/
+void SV_UnlinkEntity( sharedEntity_t *gEnt ) {
+ svEntity_t *ent;
+ svEntity_t *scan;
+ worldSector_t *ws;
+
+ ent = SV_SvEntityForGentity( gEnt );
+
+ gEnt->r.linked = qfalse;
+
+ ws = ent->worldSector;
+ if ( !ws ) {
+ return; // not linked in anywhere
+ }
+ ent->worldSector = NULL;
+
+ if ( ws->entities == ent ) {
+ ws->entities = ent->nextEntityInWorldSector;
+ return;
+ }
+
+ for ( scan = ws->entities ; scan ; scan = scan->nextEntityInWorldSector ) {
+ if ( scan->nextEntityInWorldSector == ent ) {
+ scan->nextEntityInWorldSector = ent->nextEntityInWorldSector;
+ return;
+ }
+ }
+
+ Com_Printf( "WARNING: SV_UnlinkEntity: not found in worldSector\n" );
+}
+
+
+/*
+===============
+SV_LinkEntity
+
+===============
+*/
+#define MAX_TOTAL_ENT_LEAFS 128
+void SV_LinkEntity( sharedEntity_t *gEnt ) {
+ worldSector_t *node;
+ int leafs[MAX_TOTAL_ENT_LEAFS];
+ int cluster;
+ int num_leafs;
+ int i, j, k;
+ int area;
+ int lastLeaf;
+ float *origin, *angles;
+ svEntity_t *ent;
+
+ ent = SV_SvEntityForGentity( gEnt );
+
+ if ( ent->worldSector ) {
+ SV_UnlinkEntity( gEnt ); // unlink from old position
+ }
+
+ // encode the size into the entityState_t for client prediction
+ if ( gEnt->r.bmodel ) {
+ gEnt->s.solid = SOLID_BMODEL; // a solid_box will never create this value
+ } else if ( gEnt->r.contents & ( CONTENTS_SOLID | CONTENTS_BODY ) ) {
+ // assume that x/y are equal and symetric
+ i = gEnt->r.maxs[0];
+ if (i<1)
+ i = 1;
+ if (i>255)
+ i = 255;
+
+ // z is not symetric
+ j = (-gEnt->r.mins[2]);
+ if (j<1)
+ j = 1;
+ if (j>255)
+ j = 255;
+
+ // and z maxs can be negative...
+ k = (gEnt->r.maxs[2]+32);
+ if (k<1)
+ k = 1;
+ if (k>255)
+ k = 255;
+
+ gEnt->s.solid = (k<<16) | (j<<8) | i;
+ } else {
+ gEnt->s.solid = 0;
+ }
+
+ // get the position
+ origin = gEnt->r.currentOrigin;
+ angles = gEnt->r.currentAngles;
+
+ // set the abs box
+ if ( gEnt->r.bmodel && (angles[0] || angles[1] || angles[2]) ) {
+ // expand for rotation
+ float max;
+ int i;
+
+ max = RadiusFromBounds( gEnt->r.mins, gEnt->r.maxs );
+ for (i=0 ; i<3 ; i++) {
+ gEnt->r.absmin[i] = origin[i] - max;
+ gEnt->r.absmax[i] = origin[i] + max;
+ }
+ } else {
+ // normal
+ VectorAdd (origin, gEnt->r.mins, gEnt->r.absmin);
+ VectorAdd (origin, gEnt->r.maxs, gEnt->r.absmax);
+ }
+
+ // because movement is clipped an epsilon away from an actual edge,
+ // we must fully check even when bounding boxes don't quite touch
+ gEnt->r.absmin[0] -= 1;
+ gEnt->r.absmin[1] -= 1;
+ gEnt->r.absmin[2] -= 1;
+ gEnt->r.absmax[0] += 1;
+ gEnt->r.absmax[1] += 1;
+ gEnt->r.absmax[2] += 1;
+
+ // link to PVS leafs
+ ent->numClusters = 0;
+ ent->lastCluster = 0;
+ ent->areanum = -1;
+ ent->areanum2 = -1;
+
+ //get all leafs, including solids
+ num_leafs = CM_BoxLeafnums( gEnt->r.absmin, gEnt->r.absmax,
+ leafs, MAX_TOTAL_ENT_LEAFS, &lastLeaf );
+
+ // if none of the leafs were inside the map, the
+ // entity is outside the world and can be considered unlinked
+ if ( !num_leafs ) {
+ return;
+ }
+
+ // set areas, even from clusters that don't fit in the entity array
+ for (i=0 ; i<num_leafs ; i++) {
+ area = CM_LeafArea (leafs[i]);
+ if (area != -1) {
+ // doors may legally straggle two areas,
+ // but nothing should evern need more than that
+ if (ent->areanum != -1 && ent->areanum != area) {
+ if (ent->areanum2 != -1 && ent->areanum2 != area && sv.state == SS_LOADING) {
+ Com_DPrintf ("Object %i touching 3 areas at %f %f %f\n",
+ gEnt->s.number,
+ gEnt->r.absmin[0], gEnt->r.absmin[1], gEnt->r.absmin[2]);
+ }
+ ent->areanum2 = area;
+ } else {
+ ent->areanum = area;
+ }
+ }
+ }
+
+ // store as many explicit clusters as we can
+ ent->numClusters = 0;
+ for (i=0 ; i < num_leafs ; i++) {
+ cluster = CM_LeafCluster( leafs[i] );
+ if ( cluster != -1 ) {
+ ent->clusternums[ent->numClusters++] = cluster;
+ if ( ent->numClusters == MAX_ENT_CLUSTERS ) {
+ break;
+ }
+ }
+ }
+
+ // store off a last cluster if we need to
+ if ( i != num_leafs ) {
+ ent->lastCluster = CM_LeafCluster( lastLeaf );
+ }
+
+ gEnt->r.linkcount++;
+
+ // find the first world sector node that the ent's box crosses
+ node = sv_worldSectors;
+ while (1)
+ {
+ if (node->axis == -1)
+ break;
+ if ( gEnt->r.absmin[node->axis] > node->dist)
+ node = node->children[0];
+ else if ( gEnt->r.absmax[node->axis] < node->dist)
+ node = node->children[1];
+ else
+ break; // crosses the node
+ }
+
+ // link it in
+ ent->worldSector = node;
+ ent->nextEntityInWorldSector = node->entities;
+ node->entities = ent;
+
+ gEnt->r.linked = qtrue;
+}
+
+/*
+============================================================================
+
+AREA QUERY
+
+Fills in a list of all entities who's absmin / absmax intersects the given
+bounds. This does NOT mean that they actually touch in the case of bmodels.
+============================================================================
+*/
+
+typedef struct {
+ const float *mins;
+ const float *maxs;
+ int *list;
+ int count, maxcount;
+} areaParms_t;
+
+
+/*
+====================
+SV_AreaEntities_r
+
+====================
+*/
+void SV_AreaEntities_r( worldSector_t *node, areaParms_t *ap ) {
+ svEntity_t *check, *next;
+ sharedEntity_t *gcheck;
+ int count;
+
+ count = 0;
+
+ for ( check = node->entities ; check ; check = next ) {
+ next = check->nextEntityInWorldSector;
+
+ gcheck = SV_GEntityForSvEntity( check );
+
+ if ( gcheck->r.absmin[0] > ap->maxs[0]
+ || gcheck->r.absmin[1] > ap->maxs[1]
+ || gcheck->r.absmin[2] > ap->maxs[2]
+ || gcheck->r.absmax[0] < ap->mins[0]
+ || gcheck->r.absmax[1] < ap->mins[1]
+ || gcheck->r.absmax[2] < ap->mins[2]) {
+ continue;
+ }
+
+ if ( ap->count == ap->maxcount ) {
+ Com_Printf ("SV_AreaEntities: MAXCOUNT\n");
+ return;
+ }
+
+ ap->list[ap->count] = check - sv.svEntities;
+ ap->count++;
+ }
+
+ if (node->axis == -1) {
+ return; // terminal node
+ }
+
+ // recurse down both sides
+ if ( ap->maxs[node->axis] > node->dist ) {
+ SV_AreaEntities_r ( node->children[0], ap );
+ }
+ if ( ap->mins[node->axis] < node->dist ) {
+ SV_AreaEntities_r ( node->children[1], ap );
+ }
+}
+
+/*
+================
+SV_AreaEntities
+================
+*/
+int SV_AreaEntities( const vec3_t mins, const vec3_t maxs, int *entityList, int maxcount ) {
+ areaParms_t ap;
+
+ ap.mins = mins;
+ ap.maxs = maxs;
+ ap.list = entityList;
+ ap.count = 0;
+ ap.maxcount = maxcount;
+
+ SV_AreaEntities_r( sv_worldSectors, &ap );
+
+ return ap.count;
+}
+
+
+
+//===========================================================================
+
+
+typedef struct {
+ vec3_t boxmins, boxmaxs;// enclose the test object along entire move
+ const float *mins;
+ const float *maxs; // size of the moving object
+ const float *start;
+ vec3_t end;
+ trace_t trace;
+ int passEntityNum;
+ int contentmask;
+ int capsule;
+} moveclip_t;
+
+
+/*
+====================
+SV_ClipToEntity
+
+====================
+*/
+void SV_ClipToEntity( trace_t *trace, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int entityNum, int contentmask, int capsule ) {
+ sharedEntity_t *touch;
+ clipHandle_t clipHandle;
+ float *origin, *angles;
+
+ touch = SV_GentityNum( entityNum );
+
+ Com_Memset(trace, 0, sizeof(trace_t));
+
+ // if it doesn't have any brushes of a type we
+ // are looking for, ignore it
+ if ( ! ( contentmask & touch->r.contents ) ) {
+ trace->fraction = 1.0;
+ return;
+ }
+
+ // might intersect, so do an exact clip
+ clipHandle = SV_ClipHandleForEntity (touch);
+
+ origin = touch->r.currentOrigin;
+ angles = touch->r.currentAngles;
+
+ if ( !touch->r.bmodel ) {
+ angles = vec3_origin; // boxes don't rotate
+ }
+
+ CM_TransformedBoxTrace ( trace, (float *)start, (float *)end,
+ (float *)mins, (float *)maxs, clipHandle, contentmask,
+ origin, angles, capsule);
+
+ if ( trace->fraction < 1 ) {
+ trace->entityNum = touch->s.number;
+ }
+}
+
+
+/*
+====================
+SV_ClipMoveToEntities
+
+====================
+*/
+void SV_ClipMoveToEntities( moveclip_t *clip ) {
+ int i, num;
+ int touchlist[MAX_GENTITIES];
+ sharedEntity_t *touch;
+ int passOwnerNum;
+ trace_t trace;
+ clipHandle_t clipHandle;
+ float *origin, *angles;
+
+ num = SV_AreaEntities( clip->boxmins, clip->boxmaxs, touchlist, MAX_GENTITIES);
+
+ if ( clip->passEntityNum != ENTITYNUM_NONE ) {
+ passOwnerNum = ( SV_GentityNum( clip->passEntityNum ) )->r.ownerNum;
+ if ( passOwnerNum == ENTITYNUM_NONE ) {
+ passOwnerNum = -1;
+ }
+ } else {
+ passOwnerNum = -1;
+ }
+
+ for ( i=0 ; i<num ; i++ ) {
+ if ( clip->trace.allsolid ) {
+ return;
+ }
+ touch = SV_GentityNum( touchlist[i] );
+
+ // see if we should ignore this entity
+ if ( clip->passEntityNum != ENTITYNUM_NONE ) {
+ if ( touchlist[i] == clip->passEntityNum ) {
+ continue; // don't clip against the pass entity
+ }
+ if ( touch->r.ownerNum == clip->passEntityNum ) {
+ continue; // don't clip against own missiles
+ }
+ if ( touch->r.ownerNum == passOwnerNum ) {
+ continue; // don't clip against other missiles from our owner
+ }
+ }
+
+ // if it doesn't have any brushes of a type we
+ // are looking for, ignore it
+ if ( ! ( clip->contentmask & touch->r.contents ) ) {
+ continue;
+ }
+
+ // might intersect, so do an exact clip
+ clipHandle = SV_ClipHandleForEntity (touch);
+
+ origin = touch->r.currentOrigin;
+ angles = touch->r.currentAngles;
+
+
+ if ( !touch->r.bmodel ) {
+ angles = vec3_origin; // boxes don't rotate
+ }
+
+ CM_TransformedBoxTrace ( &trace, (float *)clip->start, (float *)clip->end,
+ (float *)clip->mins, (float *)clip->maxs, clipHandle, clip->contentmask,
+ origin, angles, clip->capsule);
+
+ if ( trace.allsolid ) {
+ clip->trace.allsolid = qtrue;
+ trace.entityNum = touch->s.number;
+ } else if ( trace.startsolid ) {
+ clip->trace.startsolid = qtrue;
+ trace.entityNum = touch->s.number;
+ }
+
+ if ( trace.fraction < clip->trace.fraction ) {
+ qboolean oldStart;
+
+ // make sure we keep a startsolid from a previous trace
+ oldStart = clip->trace.startsolid;
+
+ trace.entityNum = touch->s.number;
+ clip->trace = trace;
+ clip->trace.startsolid |= oldStart;
+ }
+ }
+}
+
+
+/*
+==================
+SV_Trace
+
+Moves the given mins/maxs volume through the world from start to end.
+passEntityNum and entities owned by passEntityNum are explicitly not checked.
+==================
+*/
+void SV_Trace( trace_t *results, const vec3_t start, vec3_t mins, vec3_t maxs, const vec3_t end, int passEntityNum, int contentmask, int capsule ) {
+ moveclip_t clip;
+ int i;
+
+ if ( !mins ) {
+ mins = vec3_origin;
+ }
+ if ( !maxs ) {
+ maxs = vec3_origin;
+ }
+
+ Com_Memset ( &clip, 0, sizeof ( moveclip_t ) );
+
+ // clip to world
+ CM_BoxTrace( &clip.trace, start, end, mins, maxs, 0, contentmask, capsule );
+ clip.trace.entityNum = clip.trace.fraction != 1.0 ? ENTITYNUM_WORLD : ENTITYNUM_NONE;
+ if ( clip.trace.fraction == 0 ) {
+ *results = clip.trace;
+ return; // blocked immediately by the world
+ }
+
+ clip.contentmask = contentmask;
+ clip.start = start;
+// VectorCopy( clip.trace.endpos, clip.end );
+ VectorCopy( end, clip.end );
+ clip.mins = mins;
+ clip.maxs = maxs;
+ clip.passEntityNum = passEntityNum;
+ clip.capsule = capsule;
+
+ // create the bounding box of the entire move
+ // we can limit it to the part of the move not
+ // already clipped off by the world, which can be
+ // a significant savings for line of sight and shot traces
+ for ( i=0 ; i<3 ; i++ ) {
+ if ( end[i] > start[i] ) {
+ clip.boxmins[i] = clip.start[i] + clip.mins[i] - 1;
+ clip.boxmaxs[i] = clip.end[i] + clip.maxs[i] + 1;
+ } else {
+ clip.boxmins[i] = clip.end[i] + clip.mins[i] - 1;
+ clip.boxmaxs[i] = clip.start[i] + clip.maxs[i] + 1;
+ }
+ }
+
+ // clip to other solid entities
+ SV_ClipMoveToEntities ( &clip );
+
+ *results = clip.trace;
+}
+
+
+
+/*
+=============
+SV_PointContents
+=============
+*/
+int SV_PointContents( const vec3_t p, int passEntityNum ) {
+ int touch[MAX_GENTITIES];
+ sharedEntity_t *hit;
+ int i, num;
+ int contents, c2;
+ clipHandle_t clipHandle;
+ float *angles;
+
+ // get base contents from world
+ contents = CM_PointContents( p, 0 );
+
+ // or in contents from all the other entities
+ num = SV_AreaEntities( p, p, touch, MAX_GENTITIES );
+
+ for ( i=0 ; i<num ; i++ ) {
+ if ( touch[i] == passEntityNum ) {
+ continue;
+ }
+ hit = SV_GentityNum( touch[i] );
+ // might intersect, so do an exact clip
+ clipHandle = SV_ClipHandleForEntity( hit );
+ angles = hit->s.angles;
+ if ( !hit->r.bmodel ) {
+ angles = vec3_origin; // boxes don't rotate
+ }
+
+ c2 = CM_TransformedPointContents (p, clipHandle, hit->s.origin, hit->s.angles);
+
+ contents |= c2;
+ }
+
+ return contents;
+}
+
+
diff --git a/code/splines/Splines.vcproj b/code/splines/Splines.vcproj
new file mode 100755
index 0000000..0da2901
--- /dev/null
+++ b/code/splines/Splines.vcproj
@@ -0,0 +1,296 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+ ProjectType="Visual C++"
+ Version="7.10"
+ Name="Splines"
+ SccProjectName="&quot;$/MissionPack/code/Splines&quot;, WJNAAAAA"
+ SccLocalPath=".">
+ <Platforms>
+ <Platform
+ Name="Win32"/>
+ </Platforms>
+ <Configurations>
+ <Configuration
+ Name="Release|Win32"
+ OutputDirectory=".\Release"
+ IntermediateDirectory=".\Release"
+ ConfigurationType="4"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
+ StringPooling="TRUE"
+ RuntimeLibrary="4"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Release/Splines.pch"
+ AssemblerListingLocation=".\Release/"
+ ObjectFile=".\Release/"
+ ProgramDataBaseFileName=".\Release/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile=".\Release\Splines.lib"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCMIDLTool"/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Debug|Win32"
+ OutputDirectory=".\Debug"
+ IntermediateDirectory=".\Debug"
+ ConfigurationType="4"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
+ BasicRuntimeChecks="3"
+ RuntimeLibrary="1"
+ RuntimeTypeInfo="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Debug/Splines.pch"
+ AssemblerListingLocation=".\Debug/"
+ ObjectFile=".\Debug/"
+ ProgramDataBaseFileName=".\Debug/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile=".\Debug\Splines.lib"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCMIDLTool"/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ </Configurations>
+ <References>
+ </References>
+ <Files>
+ <Filter
+ Name="Source Files"
+ Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat">
+ <File
+ RelativePath="math_angles.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="math_matrix.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="math_quaternion.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="math_vector.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="q_parse.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="q_shared.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="splines.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="util_str.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <Filter
+ Name="Header Files"
+ Filter="h;hpp;hxx;hm;inl">
+ <File
+ RelativePath="math_angles.h">
+ </File>
+ <File
+ RelativePath="math_matrix.h">
+ </File>
+ <File
+ RelativePath="math_quaternion.h">
+ </File>
+ <File
+ RelativePath="math_vector.h">
+ </File>
+ <File
+ RelativePath="q_shared.h">
+ </File>
+ <File
+ RelativePath="splines.h">
+ </File>
+ <File
+ RelativePath="util_list.h">
+ </File>
+ <File
+ RelativePath="util_str.h">
+ </File>
+ </Filter>
+ </Files>
+ <Globals>
+ </Globals>
+</VisualStudioProject>
diff --git a/code/splines/math_angles.cpp b/code/splines/math_angles.cpp
new file mode 100755
index 0000000..4a1f5e7
--- /dev/null
+++ b/code/splines/math_angles.cpp
@@ -0,0 +1,150 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "q_shared.h"
+#include <float.h>
+
+angles_t ang_zero( 0.0f, 0.0f, 0.0f );
+
+void toAngles( mat3_t &src, angles_t &dst ) {
+ double theta;
+ double cp;
+ double sp;
+
+ sp = src[ 0 ][ 2 ];
+
+ // cap off our sin value so that we don't get any NANs
+ if ( sp > 1.0 ) {
+ sp = 1.0;
+ } else if ( sp < -1.0 ) {
+ sp = -1.0;
+ }
+
+ theta = -asin( sp );
+ cp = cos( theta );
+
+ if ( cp > 8192 * FLT_EPSILON ) {
+ dst.pitch = theta * 180 / M_PI;
+ dst.yaw = atan2( src[ 0 ][ 1 ], src[ 0 ][ 0 ] ) * 180 / M_PI;
+ dst.roll = atan2( src[ 1 ][ 2 ], src[ 2 ][ 2 ] ) * 180 / M_PI;
+ } else {
+ dst.pitch = theta * 180 / M_PI;
+ dst.yaw = -atan2( src[ 1 ][ 0 ], src[ 1 ][ 1 ] ) * 180 / M_PI;
+ dst.roll = 0;
+ }
+}
+
+void toAngles( quat_t &src, angles_t &dst ) {
+ mat3_t temp;
+
+ toMatrix( src, temp );
+ toAngles( temp, dst );
+}
+
+void toAngles( idVec3_t &src, angles_t &dst ) {
+ dst.pitch = src[ 0 ];
+ dst.yaw = src[ 1 ];
+ dst.roll = src[ 2 ];
+}
+
+void angles_t::toVectors( idVec3_t *forward, idVec3_t *right, idVec3_t *up ) {
+ float angle;
+ static float sr, sp, sy, cr, cp, cy; // static to help MS compiler fp bugs
+
+ angle = yaw * ( M_PI * 2 / 360 );
+ sy = sin( angle );
+ cy = cos( angle );
+
+ angle = pitch * ( M_PI * 2 / 360 );
+ sp = sin( angle );
+ cp = cos( angle );
+
+ angle = roll * ( M_PI * 2 / 360 );
+ sr = sin( angle );
+ cr = cos( angle );
+
+ if ( forward ) {
+ forward->set( cp * cy, cp * sy, -sp );
+ }
+
+ if ( right ) {
+ right->set( -sr * sp * cy + cr * sy, -sr * sp * sy + -cr * cy, -sr * cp );
+ }
+
+ if ( up ) {
+ up->set( cr * sp * cy + -sr * -sy, cr * sp * sy + -sr * cy, cr * cp );
+ }
+}
+
+idVec3_t angles_t::toForward( void ) {
+ float angle;
+ static float sp, sy, cp, cy; // static to help MS compiler fp bugs
+
+ angle = yaw * ( M_PI * 2 / 360 );
+ sy = sin( angle );
+ cy = cos( angle );
+
+ angle = pitch * ( M_PI * 2 / 360 );
+ sp = sin( angle );
+ cp = cos( angle );
+
+ return idVec3_t( cp * cy, cp * sy, -sp );
+}
+
+/*
+=================
+Normalize360
+
+returns angles normalized to the range [0 <= angle < 360]
+=================
+*/
+angles_t& angles_t::Normalize360( void ) {
+ pitch = (360.0 / 65536) * ( ( int )( pitch * ( 65536 / 360.0 ) ) & 65535 );
+ yaw = (360.0 / 65536) * ( ( int )( yaw * ( 65536 / 360.0 ) ) & 65535 );
+ roll = (360.0 / 65536) * ( ( int )( roll * ( 65536 / 360.0 ) ) & 65535 );
+
+ return *this;
+}
+
+
+/*
+=================
+Normalize180
+
+returns angles normalized to the range [-180 < angle <= 180]
+=================
+*/
+angles_t& angles_t::Normalize180( void ) {
+ Normalize360();
+
+ if ( pitch > 180.0 ) {
+ pitch -= 360.0;
+ }
+
+ if ( yaw > 180.0 ) {
+ yaw -= 360.0;
+ }
+
+ if ( roll > 180.0 ) {
+ roll -= 360.0;
+ }
+ return *this;
+}
diff --git a/code/splines/math_angles.h b/code/splines/math_angles.h
new file mode 100755
index 0000000..8857f90
--- /dev/null
+++ b/code/splines/math_angles.h
@@ -0,0 +1,195 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __MATH_ANGLES_H__
+#define __MATH_ANGLES_H__
+
+#include <stdlib.h>
+#include <assert.h>
+
+#include "math_vector.h"
+
+class mat3_t;
+class quat_t;
+class idVec3_t;
+typedef idVec3_t &vec3_p;
+
+class angles_t {
+public:
+ float pitch;
+ float yaw;
+ float roll;
+
+ angles_t();
+ angles_t( float pitch, float yaw, float roll );
+ angles_t( const idVec3_t &vec );
+
+ friend void toAngles( idVec3_t &src, angles_t &dst );
+ friend void toAngles( quat_t &src, angles_t &dst );
+ friend void toAngles( mat3_t &src, angles_t &dst );
+
+ operator vec3_p();
+
+ float operator[]( int index ) const;
+ float& operator[]( int index );
+
+ void set( float pitch, float yaw, float roll );
+
+ void operator=( angles_t const &a );
+ void operator=( idVec3_t const &a );
+
+ friend angles_t operator+( const angles_t &a, const angles_t &b );
+ angles_t &operator+=( angles_t const &a );
+ angles_t &operator+=( idVec3_t const &a );
+
+ friend angles_t operator-( angles_t &a, angles_t &b );
+ angles_t &operator-=( angles_t &a );
+
+ friend angles_t operator*( const angles_t &a, float b );
+ friend angles_t operator*( float a, const angles_t &b );
+ angles_t &operator*=( float a );
+
+ friend int operator==( angles_t &a, angles_t &b );
+
+ friend int operator!=( angles_t &a, angles_t &b );
+
+ void toVectors( idVec3_t *forward, idVec3_t *right = NULL, idVec3_t *up = NULL );
+ idVec3_t toForward( void );
+
+ angles_t &Zero( void );
+
+ angles_t &Normalize360( void );
+ angles_t &Normalize180( void );
+};
+
+extern angles_t ang_zero;
+
+inline angles_t::angles_t() {}
+
+inline angles_t::angles_t( float pitch, float yaw, float roll ) {
+ this->pitch = pitch;
+ this->yaw = yaw;
+ this->roll = roll;
+}
+
+inline angles_t::angles_t( const idVec3_t &vec ) {
+ this->pitch = vec.x;
+ this->yaw = vec.y;
+ this->roll = vec.z;
+}
+
+inline float angles_t::operator[]( int index ) const {
+ assert( ( index >= 0 ) && ( index < 3 ) );
+ return ( &pitch )[ index ];
+}
+
+inline float& angles_t::operator[]( int index ) {
+ assert( ( index >= 0 ) && ( index < 3 ) );
+ return ( &pitch )[ index ];
+}
+
+inline angles_t::operator vec3_p( void ) {
+ return *( idVec3_t * )&pitch;
+}
+
+inline void angles_t::set( float pitch, float yaw, float roll ) {
+ this->pitch = pitch;
+ this->yaw = yaw;
+ this->roll = roll;
+}
+
+inline void angles_t::operator=( angles_t const &a ) {
+ pitch = a.pitch;
+ yaw = a.yaw;
+ roll = a.roll;
+}
+
+inline void angles_t::operator=( idVec3_t const &a ) {
+ pitch = a[ 0 ];
+ yaw = a[ 1 ];
+ roll = a[ 2 ];
+}
+
+inline angles_t operator+( const angles_t &a, const angles_t &b ) {
+ return angles_t( a.pitch + b.pitch, a.yaw + b.yaw, a.roll + b.roll );
+}
+
+inline angles_t& angles_t::operator+=( angles_t const &a ) {
+ pitch += a.pitch;
+ yaw += a.yaw;
+ roll += a.roll;
+
+ return *this;
+}
+
+inline angles_t& angles_t::operator+=( idVec3_t const &a ) {
+ pitch += a.x;
+ yaw += a.y;
+ roll += a.z;
+
+ return *this;
+}
+
+inline angles_t operator-( angles_t &a, angles_t &b ) {
+ return angles_t( a.pitch - b.pitch, a.yaw - b.yaw, a.roll - b.roll );
+}
+
+inline angles_t& angles_t::operator-=( angles_t &a ) {
+ pitch -= a.pitch;
+ yaw -= a.yaw;
+ roll -= a.roll;
+
+ return *this;
+}
+
+inline angles_t operator*( const angles_t &a, float b ) {
+ return angles_t( a.pitch * b, a.yaw * b, a.roll * b );
+}
+
+inline angles_t operator*( float a, const angles_t &b ) {
+ return angles_t( a * b.pitch, a * b.yaw, a * b.roll );
+}
+
+inline angles_t& angles_t::operator*=( float a ) {
+ pitch *= a;
+ yaw *= a;
+ roll *= a;
+
+ return *this;
+}
+
+inline int operator==( angles_t &a, angles_t &b ) {
+ return ( ( a.pitch == b.pitch ) && ( a.yaw == b.yaw ) && ( a.roll == b.roll ) );
+}
+
+inline int operator!=( angles_t &a, angles_t &b ) {
+ return ( ( a.pitch != b.pitch ) || ( a.yaw != b.yaw ) || ( a.roll != b.roll ) );
+}
+
+inline angles_t& angles_t::Zero( void ) {
+ pitch = 0.0f;
+ yaw = 0.0f;
+ roll = 0.0f;
+
+ return *this;
+}
+
+#endif /* !__MATH_ANGLES_H__ */
diff --git a/code/splines/math_matrix.cpp b/code/splines/math_matrix.cpp
new file mode 100755
index 0000000..c7ae6db
--- /dev/null
+++ b/code/splines/math_matrix.cpp
@@ -0,0 +1,134 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "q_shared.h"
+
+mat3_t mat3_default( idVec3_t( 1, 0, 0 ), idVec3_t( 0, 1, 0 ), idVec3_t( 0, 0, 1 ) );
+
+void toMatrix( quat_t const &src, mat3_t &dst ) {
+ float wx, wy, wz;
+ float xx, yy, yz;
+ float xy, xz, zz;
+ float x2, y2, z2;
+
+ x2 = src.x + src.x;
+ y2 = src.y + src.y;
+ z2 = src.z + src.z;
+
+ xx = src.x * x2;
+ xy = src.x * y2;
+ xz = src.x * z2;
+
+ yy = src.y * y2;
+ yz = src.y * z2;
+ zz = src.z * z2;
+
+ wx = src.w * x2;
+ wy = src.w * y2;
+ wz = src.w * z2;
+
+ dst[ 0 ][ 0 ] = 1.0f - ( yy + zz );
+ dst[ 0 ][ 1 ] = xy - wz;
+ dst[ 0 ][ 2 ] = xz + wy;
+
+ dst[ 1 ][ 0 ] = xy + wz;
+ dst[ 1 ][ 1 ] = 1.0f - ( xx + zz );
+ dst[ 1 ][ 2 ] = yz - wx;
+
+ dst[ 2 ][ 0 ] = xz - wy;
+ dst[ 2 ][ 1 ] = yz + wx;
+ dst[ 2 ][ 2 ] = 1.0f - ( xx + yy );
+}
+
+void toMatrix( angles_t const &src, mat3_t &dst ) {
+ float angle;
+ static float sr, sp, sy, cr, cp, cy; // static to help MS compiler fp bugs
+
+ angle = src.yaw * ( M_PI * 2.0f / 360.0f );
+ sy = sin( angle );
+ cy = cos( angle );
+
+ angle = src.pitch * ( M_PI * 2.0f / 360.0f );
+ sp = sin( angle );
+ cp = cos( angle );
+
+ angle = src.roll * ( M_PI * 2.0f / 360.0f );
+ sr = sin( angle );
+ cr = cos( angle );
+
+ dst[ 0 ].set( cp * cy, cp * sy, -sp );
+ dst[ 1 ].set( sr * sp * cy + cr * -sy, sr * sp * sy + cr * cy, sr * cp );
+ dst[ 2 ].set( cr * sp * cy + -sr * -sy, cr * sp * sy + -sr * cy, cr * cp );
+}
+
+void toMatrix( idVec3_t const &src, mat3_t &dst ) {
+ angles_t sup = src;
+ toMatrix(sup, dst);
+}
+
+void mat3_t::ProjectVector( const idVec3_t &src, idVec3_t &dst ) const {
+ dst.x = src * mat[ 0 ];
+ dst.y = src * mat[ 1 ];
+ dst.z = src * mat[ 2 ];
+}
+
+void mat3_t::UnprojectVector( const idVec3_t &src, idVec3_t &dst ) const {
+ dst = mat[ 0 ] * src.x + mat[ 1 ] * src.y + mat[ 2 ] * src.z;
+}
+
+void mat3_t::Transpose( mat3_t &matrix ) {
+ int i;
+ int j;
+
+ for( i = 0; i < 3; i++ ) {
+ for( j = 0; j < 3; j++ ) {
+ matrix[ i ][ j ] = mat[ j ][ i ];
+ }
+ }
+}
+
+void mat3_t::Transpose( void ) {
+ float temp;
+ int i;
+ int j;
+
+ for( i = 0; i < 3; i++ ) {
+ for( j = i + 1; j < 3; j++ ) {
+ temp = mat[ i ][ j ];
+ mat[ i ][ j ] = mat[ j ][ i ];
+ mat[ j ][ i ] = temp;
+ }
+ }
+}
+
+mat3_t mat3_t::Inverse( void ) const {
+ mat3_t inv( *this );
+
+ inv.Transpose();
+
+ return inv;
+}
+
+void mat3_t::Clear( void ) {
+ mat[0].set( 1, 0, 0 );
+ mat[1].set( 0, 1, 0 );
+ mat[2].set( 0, 0, 1 );
+}
diff --git a/code/splines/math_matrix.h b/code/splines/math_matrix.h
new file mode 100755
index 0000000..e15a001
--- /dev/null
+++ b/code/splines/math_matrix.h
@@ -0,0 +1,223 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __MATH_MATRIX_H__
+#define __MATH_MATRIX_H__
+
+#include <string.h>
+#include "math_vector.h"
+
+#ifndef ID_INLINE
+#ifdef _WIN32
+#define ID_INLINE __inline
+#else
+#define ID_INLINE inline
+#endif
+#endif
+
+class quat_t;
+class angles_t;
+
+class mat3_t {
+public:
+ idVec3_t mat[ 3 ];
+
+ mat3_t();
+ mat3_t( float src[ 3 ][ 3 ] );
+ mat3_t( idVec3_t const &x, idVec3_t const &y, idVec3_t const &z );
+ mat3_t( const float xx, const float xy, const float xz, const float yx, const float yy, const float yz, const float zx, const float zy, const float zz );
+
+ friend void toMatrix( quat_t const &src, mat3_t &dst );
+ friend void toMatrix( angles_t const &src, mat3_t &dst );
+ friend void toMatrix( idVec3_t const &src, mat3_t &dst );
+
+ idVec3_t operator[]( int index ) const;
+ idVec3_t &operator[]( int index );
+
+ idVec3_t operator*( const idVec3_t &vec ) const;
+ mat3_t operator*( const mat3_t &a ) const;
+ mat3_t operator*( float a ) const;
+ mat3_t operator+( mat3_t const &a ) const;
+ mat3_t operator-( mat3_t const &a ) const;
+
+ friend idVec3_t operator*( const idVec3_t &vec, const mat3_t &mat );
+ friend mat3_t operator*( float a, mat3_t const &b );
+
+ mat3_t &operator*=( float a );
+ mat3_t &operator+=( mat3_t const &a );
+ mat3_t &operator-=( mat3_t const &a );
+
+ void Clear( void );
+
+ void ProjectVector( const idVec3_t &src, idVec3_t &dst ) const;
+ void UnprojectVector( const idVec3_t &src, idVec3_t &dst ) const;
+
+ void OrthoNormalize( void );
+ void Transpose( mat3_t &matrix );
+ void Transpose( void );
+ mat3_t Inverse( void ) const;
+ void Identity( void );
+
+ friend void InverseMultiply( const mat3_t &inv, const mat3_t &b, mat3_t &dst );
+ friend mat3_t SkewSymmetric( idVec3_t const &src );
+};
+
+ID_INLINE mat3_t::mat3_t() {
+}
+
+ID_INLINE mat3_t::mat3_t( float src[ 3 ][ 3 ] ) {
+ memcpy( mat, src, sizeof( src ) );
+}
+
+ID_INLINE mat3_t::mat3_t( idVec3_t const &x, idVec3_t const &y, idVec3_t const &z ) {
+ mat[ 0 ].x = x.x; mat[ 0 ].y = x.y; mat[ 0 ].z = x.z;
+ mat[ 1 ].x = y.x; mat[ 1 ].y = y.y; mat[ 1 ].z = y.z;
+ mat[ 2 ].x = z.x; mat[ 2 ].y = z.y; mat[ 2 ].z = z.z;
+}
+
+ID_INLINE mat3_t::mat3_t( const float xx, const float xy, const float xz, const float yx, const float yy, const float yz, const float zx, const float zy, const float zz ) {
+ mat[ 0 ].x = xx; mat[ 0 ].y = xy; mat[ 0 ].z = xz;
+ mat[ 1 ].x = yx; mat[ 1 ].y = yy; mat[ 1 ].z = yz;
+ mat[ 2 ].x = zx; mat[ 2 ].y = zy; mat[ 2 ].z = zz;
+}
+
+ID_INLINE idVec3_t mat3_t::operator[]( int index ) const {
+ assert( ( index >= 0 ) && ( index < 3 ) );
+ return mat[ index ];
+}
+
+ID_INLINE idVec3_t& mat3_t::operator[]( int index ) {
+ assert( ( index >= 0 ) && ( index < 3 ) );
+ return mat[ index ];
+}
+
+ID_INLINE idVec3_t mat3_t::operator*( const idVec3_t &vec ) const {
+ return idVec3_t(
+ mat[ 0 ].x * vec.x + mat[ 1 ].x * vec.y + mat[ 2 ].x * vec.z,
+ mat[ 0 ].y * vec.x + mat[ 1 ].y * vec.y + mat[ 2 ].y * vec.z,
+ mat[ 0 ].z * vec.x + mat[ 1 ].z * vec.y + mat[ 2 ].z * vec.z );
+}
+
+ID_INLINE mat3_t mat3_t::operator*( const mat3_t &a ) const {
+ return mat3_t(
+ mat[0].x * a[0].x + mat[0].y * a[1].x + mat[0].z * a[2].x,
+ mat[0].x * a[0].y + mat[0].y * a[1].y + mat[0].z * a[2].y,
+ mat[0].x * a[0].z + mat[0].y * a[1].z + mat[0].z * a[2].z,
+ mat[1].x * a[0].x + mat[1].y * a[1].x + mat[1].z * a[2].x,
+ mat[1].x * a[0].y + mat[1].y * a[1].y + mat[1].z * a[2].y,
+ mat[1].x * a[0].z + mat[1].y * a[1].z + mat[1].z * a[2].z,
+ mat[2].x * a[0].x + mat[2].y * a[1].x + mat[2].z * a[2].x,
+ mat[2].x * a[0].y + mat[2].y * a[1].y + mat[2].z * a[2].y,
+ mat[2].x * a[0].z + mat[2].y * a[1].z + mat[2].z * a[2].z );
+}
+
+ID_INLINE mat3_t mat3_t::operator*( float a ) const {
+ return mat3_t(
+ mat[0].x * a, mat[0].y * a, mat[0].z * a,
+ mat[1].x * a, mat[1].y * a, mat[1].z * a,
+ mat[2].x * a, mat[2].y * a, mat[2].z * a );
+}
+
+ID_INLINE mat3_t mat3_t::operator+( mat3_t const &a ) const {
+ return mat3_t(
+ mat[0].x + a[0].x, mat[0].y + a[0].y, mat[0].z + a[0].z,
+ mat[1].x + a[1].x, mat[1].y + a[1].y, mat[1].z + a[1].z,
+ mat[2].x + a[2].x, mat[2].y + a[2].y, mat[2].z + a[2].z );
+}
+
+ID_INLINE mat3_t mat3_t::operator-( mat3_t const &a ) const {
+ return mat3_t(
+ mat[0].x - a[0].x, mat[0].y - a[0].y, mat[0].z - a[0].z,
+ mat[1].x - a[1].x, mat[1].y - a[1].y, mat[1].z - a[1].z,
+ mat[2].x - a[2].x, mat[2].y - a[2].y, mat[2].z - a[2].z );
+}
+
+ID_INLINE idVec3_t operator*( const idVec3_t &vec, const mat3_t &mat ) {
+ return idVec3_t(
+ mat[ 0 ].x * vec.x + mat[ 1 ].x * vec.y + mat[ 2 ].x * vec.z,
+ mat[ 0 ].y * vec.x + mat[ 1 ].y * vec.y + mat[ 2 ].y * vec.z,
+ mat[ 0 ].z * vec.x + mat[ 1 ].z * vec.y + mat[ 2 ].z * vec.z );
+}
+
+ID_INLINE mat3_t operator*( float a, mat3_t const &b ) {
+ return mat3_t(
+ b[0].x * a, b[0].y * a, b[0].z * a,
+ b[1].x * a, b[1].y * a, b[1].z * a,
+ b[2].x * a, b[2].y * a, b[2].z * a );
+}
+
+ID_INLINE mat3_t &mat3_t::operator*=( float a ) {
+ mat[0].x *= a; mat[0].y *= a; mat[0].z *= a;
+ mat[1].x *= a; mat[1].y *= a; mat[1].z *= a;
+ mat[2].x *= a; mat[2].y *= a; mat[2].z *= a;
+
+ return *this;
+}
+
+ID_INLINE mat3_t &mat3_t::operator+=( mat3_t const &a ) {
+ mat[0].x += a[0].x; mat[0].y += a[0].y; mat[0].z += a[0].z;
+ mat[1].x += a[1].x; mat[1].y += a[1].y; mat[1].z += a[1].z;
+ mat[2].x += a[2].x; mat[2].y += a[2].y; mat[2].z += a[2].z;
+
+ return *this;
+}
+
+ID_INLINE mat3_t &mat3_t::operator-=( mat3_t const &a ) {
+ mat[0].x -= a[0].x; mat[0].y -= a[0].y; mat[0].z -= a[0].z;
+ mat[1].x -= a[1].x; mat[1].y -= a[1].y; mat[1].z -= a[1].z;
+ mat[2].x -= a[2].x; mat[2].y -= a[2].y; mat[2].z -= a[2].z;
+
+ return *this;
+}
+
+ID_INLINE void mat3_t::OrthoNormalize( void ) {
+ mat[ 0 ].Normalize();
+ mat[ 2 ].Cross( mat[ 0 ], mat[ 1 ] );
+ mat[ 2 ].Normalize();
+ mat[ 1 ].Cross( mat[ 2 ], mat[ 0 ] );
+ mat[ 1 ].Normalize();
+}
+
+ID_INLINE void mat3_t::Identity( void ) {
+ mat[ 0 ].x = 1.f; mat[ 0 ].y = 0.f; mat[ 0 ].z = 0.f;
+ mat[ 1 ].x = 0.f; mat[ 1 ].y = 1.f; mat[ 1 ].z = 0.f;
+ mat[ 2 ].x = 0.f; mat[ 2 ].y = 0.f; mat[ 2 ].z = 1.f;
+}
+
+ID_INLINE void InverseMultiply( const mat3_t &inv, const mat3_t &b, mat3_t &dst ) {
+ dst[0].x = inv[0].x * b[0].x + inv[1].x * b[1].x + inv[2].x * b[2].x;
+ dst[0].y = inv[0].x * b[0].y + inv[1].x * b[1].y + inv[2].x * b[2].y;
+ dst[0].z = inv[0].x * b[0].z + inv[1].x * b[1].z + inv[2].x * b[2].z;
+ dst[1].x = inv[0].y * b[0].x + inv[1].y * b[1].x + inv[2].y * b[2].x;
+ dst[1].y = inv[0].y * b[0].y + inv[1].y * b[1].y + inv[2].y * b[2].y;
+ dst[1].z = inv[0].y * b[0].z + inv[1].y * b[1].z + inv[2].y * b[2].z;
+ dst[2].x = inv[0].z * b[0].x + inv[1].z * b[1].x + inv[2].z * b[2].x;
+ dst[2].y = inv[0].z * b[0].y + inv[1].z * b[1].y + inv[2].z * b[2].y;
+ dst[2].z = inv[0].z * b[0].z + inv[1].z * b[1].z + inv[2].z * b[2].z;
+}
+
+ID_INLINE mat3_t SkewSymmetric( idVec3_t const &src ) {
+ return mat3_t( 0.0f, -src.z, src.y, src.z, 0.0f, -src.x, -src.y, src.x, 0.0f );
+}
+
+extern mat3_t mat3_default;
+
+#endif /* !__MATH_MATRIX_H__ */
diff --git a/code/splines/math_quaternion.cpp b/code/splines/math_quaternion.cpp
new file mode 100755
index 0000000..f37a6b6
--- /dev/null
+++ b/code/splines/math_quaternion.cpp
@@ -0,0 +1,78 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "math_quaternion.h"
+#include "math_matrix.h"
+
+void toQuat( idVec3_t &src, quat_t &dst ) {
+ dst.x = src.x;
+ dst.y = src.y;
+ dst.z = src.z;
+ dst.w = 0.0f;
+}
+
+void toQuat( angles_t &src, quat_t &dst ) {
+ mat3_t temp;
+
+ toMatrix( src, temp );
+ toQuat( temp, dst );
+}
+
+void toQuat( mat3_t &src, quat_t &dst ) {
+ float trace;
+ float s;
+ int i;
+ int j;
+ int k;
+
+ static int next[ 3 ] = { 1, 2, 0 };
+
+ trace = src[ 0 ][ 0 ] + src[ 1 ][ 1 ] + src[ 2 ][ 2 ];
+ if ( trace > 0.0f ) {
+ s = ( float )sqrt( trace + 1.0f );
+ dst.w = s * 0.5f;
+ s = 0.5f / s;
+
+ dst.x = ( src[ 2 ][ 1 ] - src[ 1 ][ 2 ] ) * s;
+ dst.y = ( src[ 0 ][ 2 ] - src[ 2 ][ 0 ] ) * s;
+ dst.z = ( src[ 1 ][ 0 ] - src[ 0 ][ 1 ] ) * s;
+ } else {
+ i = 0;
+ if ( src[ 1 ][ 1 ] > src[ 0 ][ 0 ] ) {
+ i = 1;
+ }
+ if ( src[ 2 ][ 2 ] > src[ i ][ i ] ) {
+ i = 2;
+ }
+
+ j = next[ i ];
+ k = next[ j ];
+
+ s = ( float )sqrt( ( src[ i ][ i ] - ( src[ j ][ j ] + src[ k ][ k ] ) ) + 1.0f );
+ dst[ i ] = s * 0.5f;
+
+ s = 0.5f / s;
+
+ dst.w = ( src[ k ][ j ] - src[ j ][ k ] ) * s;
+ dst[ j ] = ( src[ j ][ i ] + src[ i ][ j ] ) * s;
+ dst[ k ] = ( src[ k ][ i ] + src[ i ][ k ] ) * s;
+ }
+}
diff --git a/code/splines/math_quaternion.h b/code/splines/math_quaternion.h
new file mode 100755
index 0000000..f960aea
--- /dev/null
+++ b/code/splines/math_quaternion.h
@@ -0,0 +1,190 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __MATH_QUATERNION_H__
+#define __MATH_QUATERNION_H__
+
+#include <assert.h>
+#include <math.h>
+
+class idVec3_t;
+class angles_t;
+class mat3_t;
+
+class quat_t {
+public:
+ float x;
+ float y;
+ float z;
+ float w;
+
+ quat_t();
+ quat_t( float x, float y, float z, float w );
+
+ friend void toQuat( idVec3_t &src, quat_t &dst );
+ friend void toQuat( angles_t &src, quat_t &dst );
+ friend void toQuat( mat3_t &src, quat_t &dst );
+
+ float *vec4( void );
+
+ float operator[]( int index ) const;
+ float &operator[]( int index );
+
+ void set( float x, float y, float z, float w );
+
+ void operator=( quat_t a );
+
+ friend quat_t operator+( quat_t a, quat_t b );
+ quat_t &operator+=( quat_t a );
+
+ friend quat_t operator-( quat_t a, quat_t b );
+ quat_t &operator-=( quat_t a );
+
+ friend quat_t operator*( quat_t a, float b );
+ friend quat_t operator*( float a, quat_t b );
+ quat_t &operator*=( float a );
+
+ friend int operator==( quat_t a, quat_t b );
+ friend int operator!=( quat_t a, quat_t b );
+
+ float Length( void );
+ quat_t &Normalize( void );
+
+ quat_t operator-();
+};
+
+inline quat_t::quat_t() {
+}
+
+inline quat_t::quat_t( float x, float y, float z, float w ) {
+ this->x = x;
+ this->y = y;
+ this->z = z;
+ this->w = w;
+}
+
+inline float *quat_t::vec4( void ) {
+ return &x;
+}
+
+inline float quat_t::operator[]( int index ) const {
+ assert( ( index >= 0 ) && ( index < 4 ) );
+ return ( &x )[ index ];
+}
+
+inline float& quat_t::operator[]( int index ) {
+ assert( ( index >= 0 ) && ( index < 4 ) );
+ return ( &x )[ index ];
+}
+
+inline void quat_t::set( float x, float y, float z, float w ) {
+ this->x = x;
+ this->y = y;
+ this->z = z;
+ this->w = w;
+}
+
+inline void quat_t::operator=( quat_t a ) {
+ x = a.x;
+ y = a.y;
+ z = a.z;
+ w = a.w;
+}
+
+inline quat_t operator+( quat_t a, quat_t b ) {
+ return quat_t( a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w );
+}
+
+inline quat_t& quat_t::operator+=( quat_t a ) {
+ x += a.x;
+ y += a.y;
+ z += a.z;
+ w += a.w;
+
+ return *this;
+}
+
+inline quat_t operator-( quat_t a, quat_t b ) {
+ return quat_t( a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w );
+}
+
+inline quat_t& quat_t::operator-=( quat_t a ) {
+ x -= a.x;
+ y -= a.y;
+ z -= a.z;
+ w -= a.w;
+
+ return *this;
+}
+
+inline quat_t operator*( quat_t a, float b ) {
+ return quat_t( a.x * b, a.y * b, a.z * b, a.w * b );
+}
+
+inline quat_t operator*( float a, quat_t b ) {
+ return b * a;
+}
+
+inline quat_t& quat_t::operator*=( float a ) {
+ x *= a;
+ y *= a;
+ z *= a;
+ w *= a;
+
+ return *this;
+}
+
+inline int operator==( quat_t a, quat_t b ) {
+ return ( ( a.x == b.x ) && ( a.y == b.y ) && ( a.z == b.z ) && ( a.w == b.w ) );
+}
+
+inline int operator!=( quat_t a, quat_t b ) {
+ return ( ( a.x != b.x ) || ( a.y != b.y ) || ( a.z != b.z ) && ( a.w != b.w ) );
+}
+
+inline float quat_t::Length( void ) {
+ float length;
+
+ length = x * x + y * y + z * z + w * w;
+ return ( float )sqrt( length );
+}
+
+inline quat_t& quat_t::Normalize( void ) {
+ float length;
+ float ilength;
+
+ length = this->Length();
+ if ( length ) {
+ ilength = 1 / length;
+ x *= ilength;
+ y *= ilength;
+ z *= ilength;
+ w *= ilength;
+ }
+
+ return *this;
+}
+
+inline quat_t quat_t::operator-() {
+ return quat_t( -x, -y, -z, -w );
+}
+
+#endif /* !__MATH_QUATERNION_H__ */
diff --git a/code/splines/math_vector.cpp b/code/splines/math_vector.cpp
new file mode 100755
index 0000000..a39d859
--- /dev/null
+++ b/code/splines/math_vector.cpp
@@ -0,0 +1,144 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//#include "../game/q_shared.h"
+#include "math_vector.h"
+#include <assert.h>
+#include <math.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <string.h>
+#include <stdlib.h>
+#include <time.h>
+#include <ctype.h>
+
+#define M_PI 3.14159265358979323846 // matches value in gcc v2 math.h
+
+#define LERP_DELTA 1e-6
+
+idVec3_t vec_zero( 0.0f, 0.0f, 0.0f );
+
+Bounds boundsZero;
+
+float idVec3_t::toYaw( void ) {
+ float yaw;
+
+ if ( ( y == 0 ) && ( x == 0 ) ) {
+ yaw = 0;
+ } else {
+ yaw = atan2( y, x ) * 180 / M_PI;
+ if ( yaw < 0 ) {
+ yaw += 360;
+ }
+ }
+
+ return yaw;
+}
+
+float idVec3_t::toPitch( void ) {
+ float forward;
+ float pitch;
+
+ if ( ( x == 0 ) && ( y == 0 ) ) {
+ if ( z > 0 ) {
+ pitch = 90;
+ } else {
+ pitch = 270;
+ }
+ } else {
+ forward = ( float )idSqrt( x * x + y * y );
+ pitch = atan2( z, forward ) * 180 / M_PI;
+ if ( pitch < 0 ) {
+ pitch += 360;
+ }
+ }
+
+ return pitch;
+}
+
+/*
+angles_t idVec3_t::toAngles( void ) {
+ float forward;
+ float yaw;
+ float pitch;
+
+ if ( ( x == 0 ) && ( y == 0 ) ) {
+ yaw = 0;
+ if ( z > 0 ) {
+ pitch = 90;
+ } else {
+ pitch = 270;
+ }
+ } else {
+ yaw = atan2( y, x ) * 180 / M_PI;
+ if ( yaw < 0 ) {
+ yaw += 360;
+ }
+
+ forward = ( float )idSqrt( x * x + y * y );
+ pitch = atan2( z, forward ) * 180 / M_PI;
+ if ( pitch < 0 ) {
+ pitch += 360;
+ }
+ }
+
+ return angles_t( -pitch, yaw, 0 );
+}
+*/
+
+idVec3_t LerpVector( idVec3_t &w1, idVec3_t &w2, const float t ) {
+ float omega, cosom, sinom, scale0, scale1;
+
+ cosom = w1 * w2;
+ if ( ( 1.0 - cosom ) > LERP_DELTA ) {
+ omega = acos( cosom );
+ sinom = sin( omega );
+ scale0 = sin( ( 1.0 - t ) * omega ) / sinom;
+ scale1 = sin( t * omega ) / sinom;
+ } else {
+ scale0 = 1.0 - t;
+ scale1 = t;
+ }
+
+ return ( w1 * scale0 + w2 * scale1 );
+}
+
+/*
+=============
+idVec3_t::string
+
+This is just a convenience function
+for printing vectors
+=============
+*/
+char *idVec3_t::string( void ) {
+ static int index = 0;
+ static char str[ 8 ][ 36 ];
+ char *s;
+
+ // use an array so that multiple toString's won't collide
+ s = str[ index ];
+ index = (index + 1)&7;
+
+ sprintf( s, "%.2f %.2f %.2f", x, y, z );
+
+ return s;
+}
diff --git a/code/splines/math_vector.h b/code/splines/math_vector.h
new file mode 100755
index 0000000..be4418d
--- /dev/null
+++ b/code/splines/math_vector.h
@@ -0,0 +1,574 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __MATH_VECTOR_H__
+#define __MATH_VECTOR_H__
+
+#if defined(_WIN32)
+#pragma warning(disable : 4244)
+#endif
+
+#include <math.h>
+#include <assert.h>
+
+//#define DotProduct(a,b) ((a)[0]*(b)[0]+(a)[1]*(b)[1]+(a)[2]*(b)[2])
+//#define VectorSubtract(a,b,c) ((c)[0]=(a)[0]-(b)[0],(c)[1]=(a)[1]-(b)[1],(c)[2]=(a)[2]-(b)[2])
+//#define VectorAdd(a,b,c) ((c)[0]=(a)[0]+(b)[0],(c)[1]=(a)[1]+(b)[1],(c)[2]=(a)[2]+(b)[2])
+//#define VectorCopy(a,b) ((b)[0]=(a)[0],(b)[1]=(a)[1],(b)[2]=(a)[2])
+//#define VectorCopy(a,b) ((b).x=(a).x,(b).y=(a).y,(b).z=(a).z])
+
+//#define VectorScale(v, s, o) ((o)[0]=(v)[0]*(s),(o)[1]=(v)[1]*(s),(o)[2]=(v)[2]*(s))
+#define __VectorMA(v, s, b, o) ((o)[0]=(v)[0]+(b)[0]*(s),(o)[1]=(v)[1]+(b)[1]*(s),(o)[2]=(v)[2]+(b)[2]*(s))
+//#define CrossProduct(a,b,c) ((c)[0]=(a)[1]*(b)[2]-(a)[2]*(b)[1],(c)[1]=(a)[2]*(b)[0]-(a)[0]*(b)[2],(c)[2]=(a)[0]*(b)[1]-(a)[1]*(b)[0])
+
+#define DotProduct4(x,y) ((x)[0]*(y)[0]+(x)[1]*(y)[1]+(x)[2]*(y)[2]+(x)[3]*(y)[3])
+#define VectorSubtract4(a,b,c) ((c)[0]=(a)[0]-(b)[0],(c)[1]=(a)[1]-(b)[1],(c)[2]=(a)[2]-(b)[2],(c)[3]=(a)[3]-(b)[3])
+#define VectorAdd4(a,b,c) ((c)[0]=(a)[0]+(b)[0],(c)[1]=(a)[1]+(b)[1],(c)[2]=(a)[2]+(b)[2],(c)[3]=(a)[3]+(b)[3])
+#define VectorCopy4(a,b) ((b)[0]=(a)[0],(b)[1]=(a)[1],(b)[2]=(a)[2],(b)[3]=(a)[3])
+#define VectorScale4(v, s, o) ((o)[0]=(v)[0]*(s),(o)[1]=(v)[1]*(s),(o)[2]=(v)[2]*(s),(o)[3]=(v)[3]*(s))
+#define VectorMA4(v, s, b, o) ((o)[0]=(v)[0]+(b)[0]*(s),(o)[1]=(v)[1]+(b)[1]*(s),(o)[2]=(v)[2]+(b)[2]*(s),(o)[3]=(v)[3]+(b)[3]*(s))
+
+
+//#define VectorClear(a) ((a)[0]=(a)[1]=(a)[2]=0)
+#define VectorNegate(a,b) ((b)[0]=-(a)[0],(b)[1]=-(a)[1],(b)[2]=-(a)[2])
+//#define VectorSet(v, x, y, z) ((v)[0]=(x), (v)[1]=(y), (v)[2]=(z))
+#define Vector4Copy(a,b) ((b)[0]=(a)[0],(b)[1]=(a)[1],(b)[2]=(a)[2],(b)[3]=(a)[3])
+
+#define SnapVector(v) {v[0]=(int)v[0];v[1]=(int)v[1];v[2]=(int)v[2];}
+
+
+//#include "util_heap.h"
+
+#ifndef EQUAL_EPSILON
+#define EQUAL_EPSILON 0.001
+#endif
+
+float Q_fabs( float f );
+
+#ifndef ID_INLINE
+#ifdef _WIN32
+#define ID_INLINE __inline
+#else
+#define ID_INLINE inline
+#endif
+#endif
+
+// if this is defined, vec3 will take four elements, which may allow
+// easier SIMD optimizations
+//#define FAT_VEC3
+//#ifdef __ppc__
+//#pragma align(16)
+//#endif
+
+class angles_t;
+#ifdef __ppc__
+// Vanilla PPC code, but since PPC has a reciprocal square root estimate instruction,
+// runs *much* faster than calling sqrt(). We'll use two Newton-Raphson
+// refinement steps to get bunch more precision in the 1/sqrt() value for very little cost.
+// We'll then multiply 1/sqrt times the original value to get the sqrt.
+// This is about 12.4 times faster than sqrt() and according to my testing (not exhaustive)
+// it returns fairly accurate results (error below 1.0e-5 up to 100000.0 in 0.1 increments).
+
+static inline float idSqrt(float x) {
+ const float half = 0.5;
+ const float one = 1.0;
+ float B, y0, y1;
+
+ // This'll NaN if it hits frsqrte. Handle both +0.0 and -0.0
+ if (fabs(x) == 0.0)
+ return x;
+ B = x;
+
+#ifdef __GNUC__
+ asm("frsqrte %0,%1" : "=f" (y0) : "f" (B));
+#else
+ y0 = __frsqrte(B);
+#endif
+ /* First refinement step */
+
+ y1 = y0 + half*y0*(one - B*y0*y0);
+
+ /* Second refinement step -- copy the output of the last step to the input of this step */
+
+ y0 = y1;
+ y1 = y0 + half*y0*(one - B*y0*y0);
+
+ /* Get sqrt(x) from x * 1/sqrt(x) */
+ return x * y1;
+}
+#else
+static inline double idSqrt(double x) {
+ return sqrt(x);
+}
+#endif
+
+
+//class idVec3_t : public idHeap<idVec3_t> {
+class idVec3_t {
+public:
+#ifndef FAT_VEC3
+ float x,y,z;
+#else
+ float x,y,z,dist;
+#endif
+
+#ifndef FAT_VEC3
+ idVec3_t() {};
+#else
+ idVec3_t() {dist = 0.0f;};
+#endif
+ idVec3_t( const float x, const float y, const float z );
+
+ operator float *();
+
+ float operator[]( const int index ) const;
+ float &operator[]( const int index );
+
+ void set( const float x, const float y, const float z );
+
+ idVec3_t operator-() const;
+
+ idVec3_t &operator=( const idVec3_t &a );
+
+ float operator*( const idVec3_t &a ) const;
+ idVec3_t operator*( const float a ) const;
+ friend idVec3_t operator*( float a, idVec3_t b );
+
+ idVec3_t operator+( const idVec3_t &a ) const;
+ idVec3_t operator-( const idVec3_t &a ) const;
+
+ idVec3_t &operator+=( const idVec3_t &a );
+ idVec3_t &operator-=( const idVec3_t &a );
+ idVec3_t &operator*=( const float a );
+
+ int operator==( const idVec3_t &a ) const;
+ int operator!=( const idVec3_t &a ) const;
+
+ idVec3_t Cross( const idVec3_t &a ) const;
+ idVec3_t &Cross( const idVec3_t &a, const idVec3_t &b );
+
+ float Length( void ) const;
+ float Normalize( void );
+
+ void Zero( void );
+ void Snap( void );
+ void SnapTowards( const idVec3_t &to );
+
+ float toYaw( void );
+ float toPitch( void );
+ angles_t toAngles( void );
+ friend idVec3_t LerpVector( const idVec3_t &w1, const idVec3_t &w2, const float t );
+
+ char *string( void );
+};
+
+extern idVec3_t vec_zero;
+
+ID_INLINE idVec3_t::idVec3_t( const float x, const float y, const float z ) {
+ this->x = x;
+ this->y = y;
+ this->z = z;
+#ifdef FAT_VEC3
+ this->dist = 0.0f;
+#endif
+}
+
+ID_INLINE float idVec3_t::operator[]( const int index ) const {
+ return ( &x )[ index ];
+}
+
+ID_INLINE float &idVec3_t::operator[]( const int index ) {
+ return ( &x )[ index ];
+}
+
+ID_INLINE idVec3_t::operator float *( void ) {
+ return &x;
+}
+
+ID_INLINE idVec3_t idVec3_t::operator-() const {
+ return idVec3_t( -x, -y, -z );
+}
+
+ID_INLINE idVec3_t &idVec3_t::operator=( const idVec3_t &a ) {
+ x = a.x;
+ y = a.y;
+ z = a.z;
+
+ return *this;
+}
+
+ID_INLINE void idVec3_t::set( const float x, const float y, const float z ) {
+ this->x = x;
+ this->y = y;
+ this->z = z;
+}
+
+ID_INLINE idVec3_t idVec3_t::operator-( const idVec3_t &a ) const {
+ return idVec3_t( x - a.x, y - a.y, z - a.z );
+}
+
+ID_INLINE float idVec3_t::operator*( const idVec3_t &a ) const {
+ return x * a.x + y * a.y + z * a.z;
+}
+
+ID_INLINE idVec3_t idVec3_t::operator*( const float a ) const {
+ return idVec3_t( x * a, y * a, z * a );
+}
+
+ID_INLINE idVec3_t operator*( const float a, const idVec3_t b ) {
+ return idVec3_t( b.x * a, b.y * a, b.z * a );
+}
+
+ID_INLINE idVec3_t idVec3_t::operator+( const idVec3_t &a ) const {
+ return idVec3_t( x + a.x, y + a.y, z + a.z );
+}
+
+ID_INLINE idVec3_t &idVec3_t::operator+=( const idVec3_t &a ) {
+ x += a.x;
+ y += a.y;
+ z += a.z;
+
+ return *this;
+}
+
+ID_INLINE idVec3_t &idVec3_t::operator-=( const idVec3_t &a ) {
+ x -= a.x;
+ y -= a.y;
+ z -= a.z;
+
+ return *this;
+}
+
+ID_INLINE idVec3_t &idVec3_t::operator*=( const float a ) {
+ x *= a;
+ y *= a;
+ z *= a;
+
+ return *this;
+}
+
+ID_INLINE int idVec3_t::operator==( const idVec3_t &a ) const {
+ if ( Q_fabs( x - a.x ) > EQUAL_EPSILON ) {
+ return false;
+ }
+
+ if ( Q_fabs( y - a.y ) > EQUAL_EPSILON ) {
+ return false;
+ }
+
+ if ( Q_fabs( z - a.z ) > EQUAL_EPSILON ) {
+ return false;
+ }
+
+ return true;
+}
+
+ID_INLINE int idVec3_t::operator!=( const idVec3_t &a ) const {
+ if ( Q_fabs( x - a.x ) > EQUAL_EPSILON ) {
+ return true;
+ }
+
+ if ( Q_fabs( y - a.y ) > EQUAL_EPSILON ) {
+ return true;
+ }
+
+ if ( Q_fabs( z - a.z ) > EQUAL_EPSILON ) {
+ return true;
+ }
+
+ return false;
+}
+
+ID_INLINE idVec3_t idVec3_t::Cross( const idVec3_t &a ) const {
+ return idVec3_t( y * a.z - z * a.y, z * a.x - x * a.z, x * a.y - y * a.x );
+}
+
+ID_INLINE idVec3_t &idVec3_t::Cross( const idVec3_t &a, const idVec3_t &b ) {
+ x = a.y * b.z - a.z * b.y;
+ y = a.z * b.x - a.x * b.z;
+ z = a.x * b.y - a.y * b.x;
+
+ return *this;
+}
+
+ID_INLINE float idVec3_t::Length( void ) const {
+ float length;
+
+ length = x * x + y * y + z * z;
+ return ( float )idSqrt( length );
+}
+
+ID_INLINE float idVec3_t::Normalize( void ) {
+ float length;
+ float ilength;
+
+ length = this->Length();
+ if ( length ) {
+ ilength = 1.0f / length;
+ x *= ilength;
+ y *= ilength;
+ z *= ilength;
+ }
+
+ return length;
+}
+
+ID_INLINE void idVec3_t::Zero( void ) {
+ x = 0.0f;
+ y = 0.0f;
+ z = 0.0f;
+}
+
+ID_INLINE void idVec3_t::Snap( void ) {
+ x = float( int( x ) );
+ y = float( int( y ) );
+ z = float( int( z ) );
+}
+
+/*
+======================
+SnapTowards
+
+Round a vector to integers for more efficient network
+transmission, but make sure that it rounds towards a given point
+rather than blindly truncating. This prevents it from truncating
+into a wall.
+======================
+*/
+ID_INLINE void idVec3_t::SnapTowards( const idVec3_t &to ) {
+ if ( to.x <= x ) {
+ x = float( int( x ) );
+ } else {
+ x = float( int( x ) + 1 );
+ }
+
+ if ( to.y <= y ) {
+ y = float( int( y ) );
+ } else {
+ y = float( int( y ) + 1 );
+ }
+
+ if ( to.z <= z ) {
+ z = float( int( z ) );
+ } else {
+ z = float( int( z ) + 1 );
+ }
+}
+
+//===============================================================
+
+class Bounds {
+public:
+ idVec3_t b[2];
+
+ Bounds();
+ Bounds( const idVec3_t &mins, const idVec3_t &maxs );
+
+ void Clear();
+ void Zero();
+ float Radius(); // radius from origin, not from center
+ idVec3_t Center();
+ void AddPoint( const idVec3_t &v );
+ void AddBounds( const Bounds &bb );
+ bool IsCleared();
+ bool ContainsPoint( const idVec3_t &p );
+ bool IntersectsBounds( const Bounds &b2 ); // touching is NOT intersecting
+};
+
+extern Bounds boundsZero;
+
+ID_INLINE Bounds::Bounds(){
+}
+
+ID_INLINE bool Bounds::IsCleared() {
+ return b[0][0] > b[1][0];
+}
+
+ID_INLINE bool Bounds::ContainsPoint( const idVec3_t &p ) {
+ if ( p[0] < b[0][0] || p[1] < b[0][1] || p[2] < b[0][2]
+ || p[0] > b[1][0] || p[1] > b[1][1] || p[2] > b[1][2] ) {
+ return false;
+ }
+ return true;
+}
+
+ID_INLINE bool Bounds::IntersectsBounds( const Bounds &b2 ) {
+ if ( b2.b[1][0] < b[0][0] || b2.b[1][1] < b[0][1] || b2.b[1][2] < b[0][2]
+ || b2.b[0][0] > b[1][0] || b2.b[0][1] > b[1][1] || b2.b[0][2] > b[1][2] ) {
+ return false;
+ }
+ return true;
+}
+
+ID_INLINE Bounds::Bounds( const idVec3_t &mins, const idVec3_t &maxs ) {
+ b[0] = mins;
+ b[1] = maxs;
+}
+
+ID_INLINE idVec3_t Bounds::Center() {
+ return idVec3_t( ( b[1][0] + b[0][0] ) * 0.5f, ( b[1][1] + b[0][1] ) * 0.5f, ( b[1][2] + b[0][2] ) * 0.5f );
+}
+
+ID_INLINE void Bounds::Clear() {
+ b[0][0] = b[0][1] = b[0][2] = 99999;
+ b[1][0] = b[1][1] = b[1][2] = -99999;
+}
+
+ID_INLINE void Bounds::Zero() {
+ b[0][0] = b[0][1] = b[0][2] =
+ b[1][0] = b[1][1] = b[1][2] = 0;
+}
+
+ID_INLINE void Bounds::AddPoint( const idVec3_t &v ) {
+ if ( v[0] < b[0][0]) {
+ b[0][0] = v[0];
+ }
+ if ( v[0] > b[1][0]) {
+ b[1][0] = v[0];
+ }
+ if ( v[1] < b[0][1] ) {
+ b[0][1] = v[1];
+ }
+ if ( v[1] > b[1][1]) {
+ b[1][1] = v[1];
+ }
+ if ( v[2] < b[0][2] ) {
+ b[0][2] = v[2];
+ }
+ if ( v[2] > b[1][2]) {
+ b[1][2] = v[2];
+ }
+}
+
+
+ID_INLINE void Bounds::AddBounds( const Bounds &bb ) {
+ if ( bb.b[0][0] < b[0][0]) {
+ b[0][0] = bb.b[0][0];
+ }
+ if ( bb.b[0][1] < b[0][1]) {
+ b[0][1] = bb.b[0][1];
+ }
+ if ( bb.b[0][2] < b[0][2]) {
+ b[0][2] = bb.b[0][2];
+ }
+
+ if ( bb.b[1][0] > b[1][0]) {
+ b[1][0] = bb.b[1][0];
+ }
+ if ( bb.b[1][1] > b[1][1]) {
+ b[1][1] = bb.b[1][1];
+ }
+ if ( bb.b[1][2] > b[1][2]) {
+ b[1][2] = bb.b[1][2];
+ }
+}
+
+ID_INLINE float Bounds::Radius( ) {
+ int i;
+ float total;
+ float a, aa;
+
+ total = 0;
+ for (i=0 ; i<3 ; i++) {
+ a = (float)fabs( b[0][i] );
+ aa = (float)fabs( b[1][i] );
+ if ( aa > a ) {
+ a = aa;
+ }
+ total += a * a;
+ }
+
+ return (float)idSqrt( total );
+}
+
+//===============================================================
+
+
+class idVec2_t {
+public:
+ float x;
+ float y;
+
+ operator float *();
+ float operator[]( int index ) const;
+ float &operator[]( int index );
+};
+
+ID_INLINE float idVec2_t::operator[]( int index ) const {
+ return ( &x )[ index ];
+}
+
+ID_INLINE float& idVec2_t::operator[]( int index ) {
+ return ( &x )[ index ];
+}
+
+ID_INLINE idVec2_t::operator float *( void ) {
+ return &x;
+}
+
+class vec4_t : public idVec3_t {
+public:
+#ifndef FAT_VEC3
+ float dist;
+#endif
+ vec4_t();
+ ~vec4_t() {};
+
+ vec4_t( float x, float y, float z, float dist );
+ float operator[]( int index ) const;
+ float &operator[]( int index );
+};
+
+ID_INLINE vec4_t::vec4_t() {}
+ID_INLINE vec4_t::vec4_t( float x, float y, float z, float dist ) {
+ this->x = x;
+ this->y = y;
+ this->z = z;
+ this->dist = dist;
+}
+
+ID_INLINE float vec4_t::operator[]( int index ) const {
+ return ( &x )[ index ];
+}
+
+ID_INLINE float& vec4_t::operator[]( int index ) {
+ return ( &x )[ index ];
+}
+
+
+class idVec5_t : public idVec3_t {
+public:
+ float s;
+ float t;
+ float operator[]( int index ) const;
+ float &operator[]( int index );
+};
+
+
+ID_INLINE float idVec5_t::operator[]( int index ) const {
+ return ( &x )[ index ];
+}
+
+ID_INLINE float& idVec5_t::operator[]( int index ) {
+ return ( &x )[ index ];
+}
+
+#endif /* !__MATH_VECTOR_H__ */
diff --git a/code/splines/q_parse.cpp b/code/splines/q_parse.cpp
new file mode 100755
index 0000000..4b29ea7
--- /dev/null
+++ b/code/splines/q_parse.cpp
@@ -0,0 +1,535 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// q_parse.c -- support for parsing text files
+
+#include "q_shared.hpp"
+
+/*
+============================================================================
+
+PARSING
+
+============================================================================
+*/
+
+// multiple character punctuation tokens
+static const char *punctuation[] = {
+ "+=", "-=", "*=", "/=", "&=", "|=", "++", "--",
+ "&&", "||", "<=", ">=", "==", "!=",
+ NULL
+};
+
+typedef struct {
+ char token[MAX_TOKEN_CHARS];
+ int lines;
+ qboolean ungetToken;
+ char parseFile[MAX_QPATH];
+} parseInfo_t;
+
+#define MAX_PARSE_INFO 16
+static parseInfo_t parseInfo[MAX_PARSE_INFO];
+static int parseInfoNum;
+static parseInfo_t *pi = &parseInfo[0];
+
+/*
+===================
+Com_BeginParseSession
+===================
+*/
+void Com_BeginParseSession( const char *filename ) {
+ if ( parseInfoNum == MAX_PARSE_INFO - 1 ) {
+ Com_Error( ERR_FATAL, "Com_BeginParseSession: session overflow" );
+ }
+ parseInfoNum++;
+ pi = &parseInfo[parseInfoNum];
+
+ pi->lines = 1;
+ Q_strncpyz( pi->parseFile, filename, sizeof( pi->parseFile ) );
+}
+
+/*
+===================
+Com_EndParseSession
+===================
+*/
+void Com_EndParseSession( void ) {
+ if ( parseInfoNum == 0 ) {
+ Com_Error( ERR_FATAL, "Com_EndParseSession: session underflow" );
+ }
+ parseInfoNum--;
+ pi = &parseInfo[parseInfoNum];
+}
+
+/*
+===================
+Com_GetCurrentParseLine
+===================
+*/
+int Com_GetCurrentParseLine( void ) {
+ return pi->lines;
+}
+
+/*
+===================
+Com_ScriptError
+
+Prints the script name and line number in the message
+===================
+*/
+void Com_ScriptError( const char *msg, ... ) {
+ va_list argptr;
+ char string[32000];
+
+ va_start( argptr, msg );
+ vsprintf( string, msg,argptr );
+ va_end( argptr );
+
+ Com_Error( ERR_DROP, "File %s, line %i: %s", pi->parseFile, pi->lines, string );
+}
+
+void Com_ScriptWarning( const char *msg, ... ) {
+ va_list argptr;
+ char string[32000];
+
+ va_start( argptr, msg );
+ vsprintf( string, msg,argptr );
+ va_end( argptr );
+
+ Com_Printf( "File %s, line %i: %s", pi->parseFile, pi->lines, string );
+}
+
+
+/*
+===================
+Com_UngetToken
+
+Calling this will make the next Com_Parse return
+the current token instead of advancing the pointer
+===================
+*/
+void Com_UngetToken( void ) {
+ if ( pi->ungetToken ) {
+ Com_ScriptError( "UngetToken called twice" );
+ }
+ pi->ungetToken = qtrue;
+}
+
+
+static const char *SkipWhitespace( const char (*data), qboolean *hasNewLines ) {
+ int c;
+
+ while( (c = *data) <= ' ') {
+ if( !c ) {
+ return NULL;
+ }
+ if( c == '\n' ) {
+ pi->lines++;
+ *hasNewLines = qtrue;
+ }
+ data++;
+ }
+
+ return data;
+}
+
+/*
+==============
+Com_ParseExt
+
+Parse a token out of a string
+Will never return NULL, just empty strings.
+An empty string will only be returned at end of file.
+
+If "allowLineBreaks" is qtrue then an empty
+string will be returned if the next token is
+a newline.
+==============
+*/
+static char *Com_ParseExt( const char *(*data_p), qboolean allowLineBreaks ) {
+ int c = 0, len;
+ qboolean hasNewLines = qfalse;
+ const char *data;
+ const char **punc;
+
+ if ( !data_p ) {
+ Com_Error( ERR_FATAL, "Com_ParseExt: NULL data_p" );
+ }
+
+ data = *data_p;
+ len = 0;
+ pi->token[0] = 0;
+
+ // make sure incoming data is valid
+ if ( !data ) {
+ *data_p = NULL;
+ return pi->token;
+ }
+
+ // skip any leading whitespace
+ while ( 1 ) {
+ // skip whitespace
+ data = SkipWhitespace( data, &hasNewLines );
+ if ( !data ) {
+ *data_p = NULL;
+ return pi->token;
+ }
+ if ( hasNewLines && !allowLineBreaks ) {
+ *data_p = data;
+ return pi->token;
+ }
+
+ c = *data;
+
+ // skip double slash comments
+ if ( c == '/' && data[1] == '/' ) {
+ while (*data && *data != '\n') {
+ data++;
+ }
+ continue;
+ }
+
+ // skip /* */ comments
+ if ( c=='/' && data[1] == '*' ) {
+ while ( *data && ( *data != '*' || data[1] != '/' ) ) {
+ if( *data == '\n' ) {
+ pi->lines++;
+ }
+ data++;
+ }
+ if ( *data ) {
+ data += 2;
+ }
+ continue;
+ }
+
+ // a real token to parse
+ break;
+ }
+
+ // handle quoted strings
+ if ( c == '\"' ) {
+ data++;
+ while( 1 ) {
+ c = *data++;
+ if ( ( c=='\\' ) && ( *data == '\"' ) ) {
+ // allow quoted strings to use \" to indicate the " character
+ data++;
+ } else if ( c=='\"' || !c ) {
+ pi->token[len] = 0;
+ *data_p = ( char * ) data;
+ return pi->token;
+ } else if( *data == '\n' ) {
+ pi->lines++;
+ }
+ if ( len < MAX_TOKEN_CHARS - 1 ) {
+ pi->token[len] = c;
+ len++;
+ }
+ }
+ }
+
+ // check for a number
+ // is this parsing of negative numbers going to cause expression problems
+ if ( ( c >= '0' && c <= '9' ) || ( c == '-' && data[ 1 ] >= '0' && data[ 1 ] <= '9' ) ||
+ ( c == '.' && data[ 1 ] >= '0' && data[ 1 ] <= '9' ) ) {
+ do {
+
+ if (len < MAX_TOKEN_CHARS - 1) {
+ pi->token[len] = c;
+ len++;
+ }
+ data++;
+
+ c = *data;
+ } while ( ( c >= '0' && c <= '9' ) || c == '.' );
+
+ // parse the exponent
+ if ( c == 'e' || c == 'E' ) {
+ if (len < MAX_TOKEN_CHARS - 1) {
+ pi->token[len] = c;
+ len++;
+ }
+ data++;
+ c = *data;
+
+ if ( c == '-' || c == '+' ) {
+ if (len < MAX_TOKEN_CHARS - 1) {
+ pi->token[len] = c;
+ len++;
+ }
+ data++;
+ c = *data;
+ }
+
+ do {
+ if (len < MAX_TOKEN_CHARS - 1) {
+ pi->token[len] = c;
+ len++;
+ }
+ data++;
+
+ c = *data;
+ } while ( c >= '0' && c <= '9' );
+ }
+
+ if (len == MAX_TOKEN_CHARS) {
+ len = 0;
+ }
+ pi->token[len] = 0;
+
+ *data_p = ( char * ) data;
+ return pi->token;
+ }
+
+ // check for a regular word
+ // we still allow forward and back slashes in name tokens for pathnames
+ // and also colons for drive letters
+ if ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) || c == '_' || c == '/' || c == '\\' ) {
+ do {
+ if (len < MAX_TOKEN_CHARS - 1) {
+ pi->token[len] = c;
+ len++;
+ }
+ data++;
+
+ c = *data;
+ } while ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) || c == '_'
+ || ( c >= '0' && c <= '9' ) || c == '/' || c == '\\' || c == ':' || c == '.' );
+
+ if (len == MAX_TOKEN_CHARS) {
+ len = 0;
+ }
+ pi->token[len] = 0;
+
+ *data_p = ( char * ) data;
+ return pi->token;
+ }
+
+ // check for multi-character punctuation token
+ for ( punc = punctuation ; *punc ; punc++ ) {
+ int l;
+ int j;
+
+ l = strlen( *punc );
+ for ( j = 0 ; j < l ; j++ ) {
+ if ( data[j] != (*punc)[j] ) {
+ break;
+ }
+ }
+ if ( j == l ) {
+ // a valid multi-character punctuation
+ memcpy( pi->token, *punc, l );
+ pi->token[l] = 0;
+ data += l;
+ *data_p = (char *)data;
+ return pi->token;
+ }
+ }
+
+ // single character punctuation
+ pi->token[0] = *data;
+ pi->token[1] = 0;
+ data++;
+ *data_p = (char *)data;
+
+ return pi->token;
+}
+
+/*
+===================
+Com_Parse
+===================
+*/
+const char *Com_Parse( const char *(*data_p) ) {
+ if ( pi->ungetToken ) {
+ pi->ungetToken = qfalse;
+ return pi->token;
+ }
+ return Com_ParseExt( data_p, qtrue );
+}
+
+/*
+===================
+Com_ParseOnLine
+===================
+*/
+const char *Com_ParseOnLine( const char *(*data_p) ) {
+ if ( pi->ungetToken ) {
+ pi->ungetToken = qfalse;
+ return pi->token;
+ }
+ return Com_ParseExt( data_p, qfalse );
+}
+
+
+
+/*
+==================
+Com_MatchToken
+==================
+*/
+void Com_MatchToken( const char *(*buf_p), const char *match, qboolean warning ) {
+ const char *token;
+
+ token = Com_Parse( buf_p );
+ if ( strcmp( token, match ) ) {
+ if (warning) {
+ Com_ScriptWarning( "MatchToken: %s != %s", token, match );
+ } else {
+ Com_ScriptError( "MatchToken: %s != %s", token, match );
+ }
+ }
+}
+
+
+/*
+=================
+Com_SkipBracedSection
+
+The next token should be an open brace.
+Skips until a matching close brace is found.
+Internal brace depths are properly skipped.
+=================
+*/
+void Com_SkipBracedSection( const char *(*program) ) {
+ const char *token;
+ int depth;
+
+ depth = 0;
+ do {
+ token = Com_Parse( program );
+ if( token[1] == 0 ) {
+ if( token[0] == '{' ) {
+ depth++;
+ }
+ else if( token[0] == '}' ) {
+ depth--;
+ }
+ }
+ } while( depth && *program );
+}
+
+/*
+=================
+Com_SkipRestOfLine
+=================
+*/
+void Com_SkipRestOfLine ( const char *(*data) ) {
+ const char *p;
+ int c;
+
+ p = *data;
+ while ( (c = *p++) != 0 ) {
+ if ( c == '\n' ) {
+ pi->lines++;
+ break;
+ }
+ }
+
+ *data = p;
+}
+
+/*
+====================
+Com_ParseRestOfLine
+====================
+*/
+const char *Com_ParseRestOfLine( const char *(*data_p) ) {
+ static char line[MAX_TOKEN_CHARS];
+ const char *token;
+
+ line[0] = 0;
+ while( 1 ) {
+ token = Com_ParseOnLine( data_p );
+ if ( !token[0] ) {
+ break;
+ }
+ if ( line[0] ) {
+ Q_strcat( line, sizeof(line), " " );
+ }
+ Q_strcat( line, sizeof(line), token );
+ }
+
+ return line;
+}
+
+
+float Com_ParseFloat( const char *(*buf_p) ) {
+ const char *token;
+
+ token = Com_Parse( buf_p );
+ if ( !token[0] ) {
+ return 0;
+ }
+ return atof( token );
+}
+
+int Com_ParseInt( const char *(*buf_p) ) {
+ const char *token;
+
+ token = Com_Parse( buf_p );
+ if ( !token[0] ) {
+ return 0;
+ }
+ return atoi( token );
+}
+
+
+
+void Com_Parse1DMatrix( const char *(*buf_p), int x, float *m ) {
+ const char *token;
+ int i;
+
+ Com_MatchToken( buf_p, "(" );
+
+ for (i = 0 ; i < x ; i++) {
+ token = Com_Parse(buf_p);
+ m[i] = atof(token);
+ }
+
+ Com_MatchToken( buf_p, ")" );
+}
+
+void Com_Parse2DMatrix( const char *(*buf_p), int y, int x, float *m ) {
+ int i;
+
+ Com_MatchToken( buf_p, "(" );
+
+ for (i = 0 ; i < y ; i++) {
+ Com_Parse1DMatrix (buf_p, x, m + i * x);
+ }
+
+ Com_MatchToken( buf_p, ")" );
+}
+
+void Com_Parse3DMatrix( const char *(*buf_p), int z, int y, int x, float *m ) {
+ int i;
+
+ Com_MatchToken( buf_p, "(" );
+
+ for (i = 0 ; i < z ; i++) {
+ Com_Parse2DMatrix (buf_p, y, x, m + i * x*y);
+ }
+
+ Com_MatchToken( buf_p, ")" );
+}
+
diff --git a/code/splines/q_shared.cpp b/code/splines/q_shared.cpp
new file mode 100755
index 0000000..00934dd
--- /dev/null
+++ b/code/splines/q_shared.cpp
@@ -0,0 +1,976 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// q_shared.c -- stateless support routines that are included in each code dll
+#include "q_shared.hpp"
+
+/*
+============================================================================
+
+GROWLISTS
+
+============================================================================
+*/
+
+// malloc / free all in one place for debugging
+extern "C" void *Com_Allocate( int bytes );
+extern "C" void Com_Dealloc( void *ptr );
+
+void Com_InitGrowList( growList_t *list, int maxElements ) {
+ list->maxElements = maxElements;
+ list->currentElements = 0;
+ list->elements = (void **)Com_Allocate( list->maxElements * sizeof( void * ) );
+}
+
+int Com_AddToGrowList( growList_t *list, void *data ) {
+ void **old;
+
+ if ( list->currentElements != list->maxElements ) {
+ list->elements[list->currentElements] = data;
+ return list->currentElements++;
+ }
+
+ // grow, reallocate and move
+ old = list->elements;
+
+ if ( list->maxElements < 0 ) {
+ Com_Error( ERR_FATAL, "Com_AddToGrowList: maxElements = %i", list->maxElements );
+ }
+
+ if ( list->maxElements == 0 ) {
+ // initialize the list to hold 100 elements
+ Com_InitGrowList( list, 100 );
+ return Com_AddToGrowList( list, data );
+ }
+
+ list->maxElements *= 2;
+
+ Com_DPrintf( "Resizing growlist to %i maxElements\n", list->maxElements );
+
+ list->elements = (void **)Com_Allocate( list->maxElements * sizeof( void * ) );
+
+ if ( !list->elements ) {
+ Com_Error( ERR_DROP, "Growlist alloc failed" );
+ }
+
+ memcpy( list->elements, old, list->currentElements * sizeof( void * ) );
+
+ Com_Dealloc( old );
+
+ return Com_AddToGrowList( list, data );
+}
+
+void *Com_GrowListElement( const growList_t *list, int index ) {
+ if ( index < 0 || index >= list->currentElements ) {
+ Com_Error( ERR_DROP, "Com_GrowListElement: %i out of range of %i",
+ index, list->currentElements );
+ }
+ return list->elements[index];
+}
+
+int Com_IndexForGrowListElement( const growList_t *list, const void *element ) {
+ int i;
+
+ for ( i = 0 ; i < list->currentElements ; i++ ) {
+ if ( list->elements[i] == element ) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+//============================================================================
+
+
+float Com_Clamp( float min, float max, float value ) {
+ if ( value < min ) {
+ return min;
+ }
+ if ( value > max ) {
+ return max;
+ }
+ return value;
+}
+
+/*
+============
+Com_StringContains
+============
+*/
+const char *Com_StringContains( const char *str1, const char *str2, int casesensitive) {
+ int len, i, j;
+
+ len = strlen(str1) - strlen(str2);
+ for (i = 0; i <= len; i++, str1++) {
+ for (j = 0; str2[j]; j++) {
+ if (casesensitive) {
+ if (str1[j] != str2[j]) {
+ break;
+ }
+ }
+ else {
+ if (toupper(str1[j]) != toupper(str2[j])) {
+ break;
+ }
+ }
+ }
+ if (!str2[j]) {
+ return str1;
+ }
+ }
+ return NULL;
+}
+
+/*
+============
+Com_Filter
+============
+*/
+int Com_Filter( const char *filter, const char *name, int casesensitive)
+{
+ char buf[MAX_TOKEN_CHARS];
+ const char *ptr;
+ int i, found;
+
+ while(*filter) {
+ if (*filter == '*') {
+ filter++;
+ for (i = 0; *filter; i++) {
+ if (*filter == '*' || *filter == '?') break;
+ buf[i] = *filter;
+ filter++;
+ }
+ buf[i] = '\0';
+ if (strlen(buf)) {
+ ptr = Com_StringContains(name, buf, casesensitive);
+ if (!ptr) return qfalse;
+ name = ptr + strlen(buf);
+ }
+ }
+ else if (*filter == '?') {
+ filter++;
+ name++;
+ }
+ else if (*filter == '[' && *(filter+1) == '[') {
+ filter++;
+ }
+ else if (*filter == '[') {
+ filter++;
+ found = qfalse;
+ while(*filter && !found) {
+ if (*filter == ']' && *(filter+1) != ']') break;
+ if (*(filter+1) == '-' && *(filter+2) && (*(filter+2) != ']' || *(filter+3) == ']')) {
+ if (casesensitive) {
+ if (*name >= *filter && *name <= *(filter+2)) found = qtrue;
+ }
+ else {
+ if (toupper(*name) >= toupper(*filter) &&
+ toupper(*name) <= toupper(*(filter+2))) found = qtrue;
+ }
+ filter += 3;
+ }
+ else {
+ if (casesensitive) {
+ if (*filter == *name) found = qtrue;
+ }
+ else {
+ if (toupper(*filter) == toupper(*name)) found = qtrue;
+ }
+ filter++;
+ }
+ }
+ if (!found) return qfalse;
+ while(*filter) {
+ if (*filter == ']' && *(filter+1) != ']') break;
+ filter++;
+ }
+ filter++;
+ name++;
+ }
+ else {
+ if (casesensitive) {
+ if (*filter != *name) return qfalse;
+ }
+ else {
+ if (toupper(*filter) != toupper(*name)) return qfalse;
+ }
+ filter++;
+ name++;
+ }
+ }
+ return qtrue;
+}
+
+
+/*
+================
+Com_HashString
+
+================
+*/
+int Com_HashString( const char *fname ) {
+ int i;
+ long hash;
+ char letter;
+
+ hash = 0;
+ i = 0;
+ while (fname[i] != '\0') {
+ letter = tolower(fname[i]);
+ if (letter =='.') break; // don't include extension
+ if (letter =='\\') letter = '/'; // damn path names
+ hash+=(long)(letter)*(i+119);
+ i++;
+ }
+ hash &= (FILE_HASH_SIZE-1);
+ return hash;
+}
+
+
+/*
+============
+Com_SkipPath
+============
+*/
+char *Com_SkipPath (char *pathname)
+{
+ char *last;
+
+ last = pathname;
+ while (*pathname)
+ {
+ if (*pathname=='/')
+ last = pathname+1;
+ pathname++;
+ }
+ return last;
+}
+
+/*
+============
+Com_StripExtension
+============
+*/
+void Com_StripExtension( const char *in, char *out ) {
+ while ( *in && *in != '.' ) {
+ *out++ = *in++;
+ }
+ *out = 0;
+}
+
+
+/*
+==================
+Com_DefaultExtension
+==================
+*/
+void Com_DefaultExtension (char *path, int maxSize, const char *extension ) {
+ char oldPath[MAX_QPATH];
+ char *src;
+
+//
+// if path doesn't have a .EXT, append extension
+// (extension should include the .)
+//
+ src = path + strlen(path) - 1;
+
+ while (*src != '/' && src != path) {
+ if ( *src == '.' ) {
+ return; // it has an extension
+ }
+ src--;
+ }
+
+ Q_strncpyz( oldPath, path, sizeof( oldPath ) );
+ Com_sprintf( path, maxSize, "%s%s", oldPath, extension );
+}
+
+/*
+============================================================================
+
+ BYTE ORDER FUNCTIONS
+
+============================================================================
+*/
+
+// can't just use function pointers, or dll linkage can
+// mess up when qcommon is included in multiple places
+static short (*_BigShort) (short l);
+static short (*_LittleShort) (short l);
+static int (*_BigLong) (int l);
+static int (*_LittleLong) (int l);
+static float (*_BigFloat) (float l);
+static float (*_LittleFloat) (float l);
+
+short BigShort(short l){return _BigShort(l);}
+short LittleShort(short l) {return _LittleShort(l);}
+int BigLong (int l) {return _BigLong(l);}
+int LittleLong (int l) {return _LittleLong(l);}
+float BigFloat (float l) {return _BigFloat(l);}
+float LittleFloat (float l) {return _LittleFloat(l);}
+
+short ShortSwap (short l)
+{
+ byte b1,b2;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+
+ return (b1<<8) + b2;
+}
+
+short ShortNoSwap (short l)
+{
+ return l;
+}
+
+int LongSwap (int l)
+{
+ byte b1,b2,b3,b4;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+ b3 = (l>>16)&255;
+ b4 = (l>>24)&255;
+
+ return ((int)b1<<24) + ((int)b2<<16) + ((int)b3<<8) + b4;
+}
+
+int LongNoSwap (int l)
+{
+ return l;
+}
+
+float FloatSwap (float f)
+{
+ union
+ {
+ float f;
+ byte b[4];
+ } dat1, dat2;
+
+
+ dat1.f = f;
+ dat2.b[0] = dat1.b[3];
+ dat2.b[1] = dat1.b[2];
+ dat2.b[2] = dat1.b[1];
+ dat2.b[3] = dat1.b[0];
+ return dat2.f;
+}
+
+float FloatNoSwap (float f)
+{
+ return f;
+}
+
+/*
+================
+Swap_Init
+================
+*/
+void Swap_Init (void)
+{
+ byte swaptest[2] = {1,0};
+
+// set the byte swapping variables in a portable manner
+ if ( *(short *)swaptest == 1)
+ {
+ _BigShort = ShortSwap;
+ _LittleShort = ShortNoSwap;
+ _BigLong = LongSwap;
+ _LittleLong = LongNoSwap;
+ _BigFloat = FloatSwap;
+ _LittleFloat = FloatNoSwap;
+ }
+ else
+ {
+ _BigShort = ShortNoSwap;
+ _LittleShort = ShortSwap;
+ _BigLong = LongNoSwap;
+ _LittleLong = LongSwap;
+ _BigFloat = FloatNoSwap;
+ _LittleFloat = FloatSwap;
+ }
+
+}
+
+/*
+===============
+Com_ParseInfos
+===============
+*/
+int Com_ParseInfos( const char *buf, int max, char infos[][MAX_INFO_STRING] ) {
+ const char *token;
+ int count;
+ char key[MAX_TOKEN_CHARS];
+
+ count = 0;
+
+ while ( 1 ) {
+ token = Com_Parse( &buf );
+ if ( !token[0] ) {
+ break;
+ }
+ if ( strcmp( token, "{" ) ) {
+ Com_Printf( "Missing { in info file\n" );
+ break;
+ }
+
+ if ( count == max ) {
+ Com_Printf( "Max infos exceeded\n" );
+ break;
+ }
+
+ infos[count][0] = 0;
+ while ( 1 ) {
+ token = Com_Parse( &buf );
+ if ( !token[0] ) {
+ Com_Printf( "Unexpected end of info file\n" );
+ break;
+ }
+ if ( !strcmp( token, "}" ) ) {
+ break;
+ }
+ Q_strncpyz( key, token, sizeof( key ) );
+
+ token = Com_ParseOnLine( &buf );
+ if ( !token[0] ) {
+ token = "<NULL>";
+ }
+ Info_SetValueForKey( infos[count], key, token );
+ }
+ count++;
+ }
+
+ return count;
+}
+
+
+
+/*
+============================================================================
+
+ LIBRARY REPLACEMENT FUNCTIONS
+
+============================================================================
+*/
+
+int Q_isprint( int c )
+{
+ if ( c >= 0x20 && c <= 0x7E )
+ return ( 1 );
+ return ( 0 );
+}
+
+int Q_islower( int c )
+{
+ if (c >= 'a' && c <= 'z')
+ return ( 1 );
+ return ( 0 );
+}
+
+int Q_isupper( int c )
+{
+ if (c >= 'A' && c <= 'Z')
+ return ( 1 );
+ return ( 0 );
+}
+
+int Q_isalpha( int c )
+{
+ if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
+ return ( 1 );
+ return ( 0 );
+}
+
+char* Q_strrchr( const char* string, int c )
+{
+ char cc = c;
+ char *s;
+ char *sp=(char *)0;
+
+ s = (char*)string;
+
+ while (*s)
+ {
+ if (*s == cc)
+ sp = s;
+ s++;
+ }
+ if (cc == 0)
+ sp = s;
+
+ return sp;
+}
+
+/*
+=============
+Q_strncpyz
+
+Safe strncpy that ensures a trailing zero
+=============
+*/
+void Q_strncpyz( char *dest, const char *src, int destsize ) {
+ if ( !src ) {
+ Com_Error( ERR_FATAL, "Q_strncpyz: NULL src" );
+ }
+ if ( destsize < 1 ) {
+ Com_Error(ERR_FATAL,"Q_strncpyz: destsize < 1" );
+ }
+
+ strncpy( dest, src, destsize-1 );
+ dest[destsize-1] = 0;
+}
+
+int Q_stricmpn (const char *s1, const char *s2, int n) {
+ int c1, c2;
+
+ do {
+ c1 = *s1++;
+ c2 = *s2++;
+
+ if (!n--) {
+ return 0; // strings are equal until end point
+ }
+
+ if (c1 != c2) {
+ if (c1 >= 'a' && c1 <= 'z') {
+ c1 -= ('a' - 'A');
+ }
+ if (c2 >= 'a' && c2 <= 'z') {
+ c2 -= ('a' - 'A');
+ }
+ if (c1 != c2) {
+ return c1 < c2 ? -1 : 1;
+ }
+ }
+ } while (c1);
+
+ return 0; // strings are equal
+}
+
+int Q_strncmp (const char *s1, const char *s2, int n) {
+ int c1, c2;
+
+ do {
+ c1 = *s1++;
+ c2 = *s2++;
+
+ if (!n--) {
+ return 0; // strings are equal until end point
+ }
+
+ if (c1 != c2) {
+ return c1 < c2 ? -1 : 1;
+ }
+ } while (c1);
+
+ return 0; // strings are equal
+}
+
+int Q_stricmp (const char *s1, const char *s2) {
+ return Q_stricmpn (s1, s2, 99999);
+}
+
+
+char *Q_strlwr( char *s1 ) {
+ char *s;
+
+ s = s1;
+ while ( *s ) {
+ *s = tolower(*s);
+ s++;
+ }
+ return s1;
+}
+
+char *Q_strupr( char *s1 ) {
+ char *s;
+
+ s = s1;
+ while ( *s ) {
+ *s = toupper(*s);
+ s++;
+ }
+ return s1;
+}
+
+
+// never goes past bounds or leaves without a terminating 0
+void Q_strcat( char *dest, int size, const char *src ) {
+ int l1;
+
+ l1 = strlen( dest );
+ if ( l1 >= size ) {
+ Com_Error( ERR_FATAL, "Q_strcat: already overflowed" );
+ }
+ Q_strncpyz( dest + l1, src, size - l1 );
+}
+
+
+int Q_PrintStrlen( const char *string ) {
+ int len;
+ const char *p;
+
+ if( !string ) {
+ return 0;
+ }
+
+ len = 0;
+ p = string;
+ while( *p ) {
+ if( Q_IsColorString( p ) ) {
+ p += 2;
+ continue;
+ }
+ p++;
+ len++;
+ }
+
+ return len;
+}
+
+
+char *Q_CleanStr( char *string ) {
+ char* d;
+ char* s;
+ int c;
+
+ s = string;
+ d = string;
+ while ((c = *s) != 0 ) {
+ if ( Q_IsColorString( s ) ) {
+ s++;
+ }
+ else if ( c >= 0x20 && c <= 0x7E ) {
+ *d++ = c;
+ }
+ s++;
+ }
+ *d = '\0';
+
+ return string;
+}
+
+
+void QDECL Com_sprintf( char *dest, int size, const char *fmt, ...) {
+ int len;
+ va_list argptr;
+ char bigbuffer[32000]; // big, but small enough to fit in PPC stack
+
+ va_start (argptr,fmt);
+ len = vsprintf (bigbuffer,fmt,argptr);
+ va_end (argptr);
+ if ( len >= sizeof( bigbuffer ) ) {
+ Com_Error( ERR_FATAL, "Com_sprintf: overflowed bigbuffer" );
+ }
+ if (len >= size) {
+ Com_Printf ("Com_sprintf: overflow of %i in %i\n", len, size);
+ }
+ Q_strncpyz (dest, bigbuffer, size );
+}
+
+
+/*
+============
+va
+
+does a varargs printf into a temp buffer, so I don't need to have
+varargs versions of all text functions.
+FIXME: make this buffer size safe someday
+============
+*/
+char * QDECL va( char *format, ... ) {
+ va_list argptr;
+ static char string[2][32000]; // in case va is called by nested functions
+ static int index = 0;
+ char *buf;
+
+ buf = string[index & 1];
+ index++;
+
+ va_start (argptr, format);
+ vsprintf (buf, format,argptr);
+ va_end (argptr);
+
+ return buf;
+}
+
+
+/*
+=====================================================================
+
+ INFO STRINGS
+
+=====================================================================
+*/
+
+/*
+===============
+Info_ValueForKey
+
+Searches the string for the given
+key and returns the associated value, or an empty string.
+FIXME: overflow check?
+===============
+*/
+char *Info_ValueForKey( const char *s, const char *key ) {
+ char pkey[MAX_INFO_KEY];
+ static char value[2][MAX_INFO_VALUE]; // use two buffers so compares
+ // work without stomping on each other
+ static int valueindex = 0;
+ char *o;
+
+ if ( !s || !key ) {
+ return "";
+ }
+
+ if ( strlen( s ) >= MAX_INFO_STRING ) {
+ Com_Error( ERR_DROP, "Info_ValueForKey: oversize infostring" );
+ }
+
+ valueindex ^= 1;
+ if (*s == '\\')
+ s++;
+ while (1)
+ {
+ o = pkey;
+ while (*s != '\\')
+ {
+ if (!*s)
+ return "";
+ *o++ = *s++;
+ }
+ *o = 0;
+ s++;
+
+ o = value[valueindex];
+
+ while (*s != '\\' && *s)
+ {
+ *o++ = *s++;
+ }
+ *o = 0;
+
+ if (!Q_stricmp (key, pkey) )
+ return value[valueindex];
+
+ if (!*s)
+ break;
+ s++;
+ }
+
+ return "";
+}
+
+
+/*
+===================
+Info_NextPair
+
+Used to itterate through all the key/value pairs in an info string
+===================
+*/
+void Info_NextPair( const char *(*head), char key[MAX_INFO_KEY], char value[MAX_INFO_VALUE] ) {
+ char *o;
+ const char *s;
+
+ s = *head;
+
+ if ( *s == '\\' ) {
+ s++;
+ }
+ key[0] = 0;
+ value[0] = 0;
+
+ o = key;
+ while ( *s != '\\' ) {
+ if ( !*s ) {
+ *o = 0;
+ *head = s;
+ return;
+ }
+ *o++ = *s++;
+ }
+ *o = 0;
+ s++;
+
+ o = value;
+ while ( *s != '\\' && *s ) {
+ *o++ = *s++;
+ }
+ *o = 0;
+
+ *head = s;
+}
+
+
+/*
+===================
+Info_RemoveKey
+===================
+*/
+void Info_RemoveKey( char *s, const char *key ) {
+ char *start;
+ char pkey[MAX_INFO_KEY];
+ char value[MAX_INFO_VALUE];
+ char *o;
+
+ if ( strlen( s ) >= MAX_INFO_STRING ) {
+ Com_Error( ERR_DROP, "Info_RemoveKey: oversize infostring" );
+ }
+
+ if (strchr (key, '\\')) {
+ return;
+ }
+
+ while (1)
+ {
+ start = s;
+ if (*s == '\\')
+ s++;
+ o = pkey;
+ while (*s != '\\')
+ {
+ if (!*s)
+ return;
+ *o++ = *s++;
+ }
+ *o = 0;
+ s++;
+
+ o = value;
+ while (*s != '\\' && *s)
+ {
+ if (!*s)
+ return;
+ *o++ = *s++;
+ }
+ *o = 0;
+
+ if (!strcmp (key, pkey) )
+ {
+ strcpy (start, s); // remove this part
+ return;
+ }
+
+ if (!*s)
+ return;
+ }
+
+}
+
+
+/*
+==================
+Info_Validate
+
+Some characters are illegal in info strings because they
+can mess up the server's parsing
+==================
+*/
+qboolean Info_Validate( const char *s ) {
+ if ( strchr( s, '\"' ) ) {
+ return qfalse;
+ }
+ if ( strchr( s, ';' ) ) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+/*
+==================
+Info_SetValueForKey
+
+Changes or adds a key/value pair
+==================
+*/
+void Info_SetValueForKey( char *s, const char *key, const char *value ) {
+ char newi[MAX_INFO_STRING];
+
+ if ( strlen( s ) >= MAX_INFO_STRING ) {
+ Com_Error( ERR_DROP, "Info_SetValueForKey: oversize infostring" );
+ }
+
+ if (strchr (key, '\\') || strchr (value, '\\'))
+ {
+ Com_Printf ("Can't use keys or values with a \\\n");
+ return;
+ }
+
+ if (strchr (key, ';') || strchr (value, ';'))
+ {
+ Com_Printf ("Can't use keys or values with a semicolon\n");
+ return;
+ }
+
+ if (strchr (key, '\"') || strchr (value, '\"'))
+ {
+ Com_Printf ("Can't use keys or values with a \"\n");
+ return;
+ }
+
+ Info_RemoveKey (s, key);
+ if (!value || !strlen(value))
+ return;
+
+ Com_sprintf (newi, sizeof(newi), "\\%s\\%s", key, value);
+
+ if (strlen(newi) + strlen(s) > MAX_INFO_STRING)
+ {
+ Com_Printf ("Info string length exceeded\n");
+ return;
+ }
+
+ strcat (s, newi);
+}
+
+//====================================================================
+
+
+/*
+===============
+ParseHex
+===============
+*/
+int ParseHex( const char *text ) {
+ int value;
+ int c;
+
+ value = 0;
+ while ( ( c = *text++ ) != 0 ) {
+ if ( c >= '0' && c <= '9' ) {
+ value = value * 16 + c - '0';
+ continue;
+ }
+ if ( c >= 'a' && c <= 'f' ) {
+ value = value * 16 + 10 + c - 'a';
+ continue;
+ }
+ if ( c >= 'A' && c <= 'F' ) {
+ value = value * 16 + 10 + c - 'A';
+ continue;
+ }
+ }
+
+ return value;
+}
diff --git a/code/splines/q_shared.h b/code/splines/q_shared.h
new file mode 100755
index 0000000..bfe0925
--- /dev/null
+++ b/code/splines/q_shared.h
@@ -0,0 +1,810 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __Q_SHARED_H
+#define __Q_SHARED_H
+
+// q_shared.h -- included first by ALL program modules.
+// these are the definitions that have no dependance on
+// central system services, and can be used by any part
+// of the program without any state issues.
+
+// A user mod should never modify this file
+
+// incursion of DOOM code into the Q3A codebase
+//#define Q3_VERSION "DOOM 0.01"
+
+// alignment macros for SIMD
+#define ALIGN_ON
+#define ALIGN_OFF
+
+#ifdef _WIN32
+
+#pragma warning(disable : 4018) // signed/unsigned mismatch
+#pragma warning(disable : 4032)
+#pragma warning(disable : 4051)
+#pragma warning(disable : 4057) // slightly different base types
+#pragma warning(disable : 4100) // unreferenced formal parameter
+#pragma warning(disable : 4115)
+#pragma warning(disable : 4125) // decimal digit terminates octal escape sequence
+#pragma warning(disable : 4127) // conditional expression is constant
+#pragma warning(disable : 4136)
+#pragma warning(disable : 4201)
+#pragma warning(disable : 4214)
+#pragma warning(disable : 4244)
+#pragma warning(disable : 4305) // truncation from const double to float
+#pragma warning(disable : 4310) // cast truncates constant value
+#pragma warning(disable : 4514)
+#pragma warning(disable : 4711) // selected for automatic inline expansion
+#pragma warning(disable : 4220) // varargs matches remaining parameters
+
+#endif
+
+#include <assert.h>
+#include <math.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <string.h>
+#include <stdlib.h>
+#include <time.h>
+#include <ctype.h>
+#ifdef WIN32 // mac doesn't have malloc.h
+#include <malloc.h> // for _alloca()
+#endif
+#ifdef _WIN32
+
+//#pragma intrinsic( memset, memcpy )
+
+#endif
+
+
+// this is the define for determining if we have an asm version of a C function
+#if (defined _M_IX86 || defined __i386__) && !defined __sun__ && !defined __LCC__
+#define id386 1
+#else
+#define id386 0
+#endif
+
+// for windows fastcall option
+
+#define QDECL
+
+//======================= WIN32 DEFINES =================================
+
+#ifdef WIN32
+
+#define MAC_STATIC
+
+#undef QDECL
+#define QDECL __cdecl
+
+// buildstring will be incorporated into the version string
+#ifdef NDEBUG
+#ifdef _M_IX86
+#define CPUSTRING "win-x86"
+#elif defined _M_ALPHA
+#define CPUSTRING "win-AXP"
+#endif
+#else
+#ifdef _M_IX86
+#define CPUSTRING "win-x86-debug"
+#elif defined _M_ALPHA
+#define CPUSTRING "win-AXP-debug"
+#endif
+#endif
+
+
+#define PATH_SEP '\\'
+
+#endif
+
+//======================= MAC OS X SERVER DEFINES =====================
+
+#if defined(__MACH__) && defined(__APPLE__)
+
+#define MAC_STATIC
+
+#ifdef __ppc__
+#define CPUSTRING "MacOSXS-ppc"
+#elif defined __i386__
+#define CPUSTRING "MacOSXS-i386"
+#else
+#define CPUSTRING "MacOSXS-other"
+#endif
+
+#define PATH_SEP '/'
+
+#define GAME_HARD_LINKED
+#define CGAME_HARD_LINKED
+#define UI_HARD_LINKED
+#define _alloca alloca
+
+#undef ALIGN_ON
+#undef ALIGN_OFF
+#define ALIGN_ON #pragma align(16)
+#define ALIGN_OFF #pragma align()
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+void *osxAllocateMemory(long size);
+void osxFreeMemory(void *pointer);
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif
+
+//======================= MAC DEFINES =================================
+
+#ifdef __MACOS__
+
+#define MAC_STATIC static
+
+#define CPUSTRING "MacOS-PPC"
+
+#define PATH_SEP ':'
+
+void Sys_PumpEvents( void );
+
+#endif
+
+#ifdef __MRC__
+
+#define MAC_STATIC
+
+#define CPUSTRING "MacOS-PPC"
+
+#define PATH_SEP ':'
+
+void Sys_PumpEvents( void );
+
+#undef QDECL
+#define QDECL __cdecl
+
+#define _alloca alloca
+#endif
+
+//======================= LINUX DEFINES =================================
+
+// the mac compiler can't handle >32k of locals, so we
+// just waste space and make big arrays static...
+#ifdef __linux__
+
+// bk001205 - from Makefile
+#define stricmp strcasecmp
+
+#define MAC_STATIC // bk: FIXME
+
+#ifdef __i386__
+#define CPUSTRING "linux-i386"
+#elif defined __axp__
+#define CPUSTRING "linux-alpha"
+#else
+#define CPUSTRING "linux-other"
+#endif
+
+#define PATH_SEP '/'
+
+// bk001205 - try
+#ifdef Q3_STATIC
+#define GAME_HARD_LINKED
+#define CGAME_HARD_LINKED
+#define UI_HARD_LINKED
+#define BOTLIB_HARD_LINKED
+#endif
+
+#endif
+
+//=============================================================
+
+
+
+typedef enum {qfalse, qtrue} qboolean;
+
+typedef unsigned char byte;
+
+#define EQUAL_EPSILON 0.001
+
+typedef int qhandle_t;
+typedef int sfxHandle_t;
+typedef int fileHandle_t;
+typedef int clipHandle_t;
+
+typedef enum {
+ INVALID_JOINT = -1
+} jointHandle_t;
+
+#ifndef NULL
+#define NULL ((void *)0)
+#endif
+
+#define MAX_QINT 0x7fffffff
+#define MIN_QINT (-MAX_QINT-1)
+
+#ifndef max
+#define max( x, y ) ( ( ( x ) > ( y ) ) ? ( x ) : ( y ) )
+#define min( x, y ) ( ( ( x ) < ( y ) ) ? ( x ) : ( y ) )
+#endif
+
+#ifndef sign
+#define sign( f ) ( ( f > 0 ) ? 1 : ( ( f < 0 ) ? -1 : 0 ) )
+#endif
+
+// angle indexes
+#define PITCH 0 // up / down
+#define YAW 1 // left / right
+#define ROLL 2 // fall over
+
+// the game guarantees that no string from the network will ever
+// exceed MAX_STRING_CHARS
+#define MAX_STRING_CHARS 1024 // max length of a string passed to Cmd_TokenizeString
+#define MAX_STRING_TOKENS 256 // max tokens resulting from Cmd_TokenizeString
+#define MAX_TOKEN_CHARS 1024 // max length of an individual token
+
+#define MAX_INFO_STRING 1024
+#define MAX_INFO_KEY 1024
+#define MAX_INFO_VALUE 1024
+
+
+#define MAX_QPATH 64 // max length of a quake game pathname
+#define MAX_OSPATH 128 // max length of a filesystem pathname
+
+#define MAX_NAME_LENGTH 32 // max length of a client name
+
+// paramters for command buffer stuffing
+typedef enum {
+ EXEC_NOW, // don't return until completed, a VM should NEVER use this,
+ // because some commands might cause the VM to be unloaded...
+ EXEC_INSERT, // insert at current position, but don't run yet
+ EXEC_APPEND // add to end of the command buffer (normal case)
+} cbufExec_t;
+
+
+//
+// these aren't needed by any of the VMs. put in another header?
+//
+#define MAX_MAP_AREA_BYTES 32 // bit vector of area visibility
+
+#undef ERR_FATAL // malloc.h on unix
+
+// parameters to the main Error routine
+typedef enum {
+ ERR_NONE,
+ ERR_FATAL, // exit the entire game with a popup window
+ ERR_DROP, // print to console and disconnect from game
+ ERR_DISCONNECT, // don't kill server
+ ERR_NEED_CD // pop up the need-cd dialog
+} errorParm_t;
+
+
+// font rendering values used by ui and cgame
+
+#define PROP_GAP_WIDTH 3
+#define PROP_SPACE_WIDTH 8
+#define PROP_HEIGHT 27
+#define PROP_SMALL_SIZE_SCALE 0.75
+
+#define BLINK_DIVISOR 200
+#define PULSE_DIVISOR 75
+
+#define UI_LEFT 0x00000000 // default
+#define UI_CENTER 0x00000001
+#define UI_RIGHT 0x00000002
+#define UI_FORMATMASK 0x00000007
+#define UI_SMALLFONT 0x00000010
+#define UI_BIGFONT 0x00000020 // default
+#define UI_GIANTFONT 0x00000040
+#define UI_DROPSHADOW 0x00000800
+#define UI_BLINK 0x00001000
+#define UI_INVERSE 0x00002000
+#define UI_PULSE 0x00004000
+
+
+/*
+==============================================================
+
+MATHLIB
+
+==============================================================
+*/
+#ifdef __cplusplus // so we can include this in C code
+#define SIDE_FRONT 0
+#define SIDE_BACK 1
+#define SIDE_ON 2
+#define SIDE_CROSS 3
+
+#define Q_PI 3.14159265358979323846
+#ifndef M_PI
+#define M_PI 3.14159265358979323846 // matches value in gcc v2 math.h
+#endif
+
+#include "math_vector.h"
+#include "math_angles.h"
+#include "math_matrix.h"
+#include "math_quaternion.h"
+
+class idVec3_t; // for defining vectors
+typedef idVec3_t &vec3_p; // for passing vectors as function arguments
+typedef const idVec3_t &vec3_c; // for passing vectors as const function arguments
+
+class angles_t; // for defining angle vectors
+typedef angles_t &angles_p; // for passing angles as function arguments
+typedef const angles_t &angles_c; // for passing angles as const function arguments
+
+class mat3_t; // for defining matrices
+typedef mat3_t &mat3_p; // for passing matrices as function arguments
+typedef const mat3_t &mat3_c; // for passing matrices as const function arguments
+
+
+
+#define NUMVERTEXNORMALS 162
+extern idVec3_t bytedirs[NUMVERTEXNORMALS];
+
+// all drawing is done to a 640*480 virtual screen size
+// and will be automatically scaled to the real resolution
+#define SCREEN_WIDTH 640
+#define SCREEN_HEIGHT 480
+
+#define TINYCHAR_WIDTH (SMALLCHAR_WIDTH)
+#define TINYCHAR_HEIGHT (SMALLCHAR_HEIGHT/2)
+
+#define SMALLCHAR_WIDTH 8
+#define SMALLCHAR_HEIGHT 16
+
+#define BIGCHAR_WIDTH 16
+#define BIGCHAR_HEIGHT 16
+
+#define GIANTCHAR_WIDTH 32
+#define GIANTCHAR_HEIGHT 48
+
+extern vec4_t colorBlack;
+extern vec4_t colorRed;
+extern vec4_t colorGreen;
+extern vec4_t colorBlue;
+extern vec4_t colorYellow;
+extern vec4_t colorMagenta;
+extern vec4_t colorCyan;
+extern vec4_t colorWhite;
+extern vec4_t colorLtGrey;
+extern vec4_t colorMdGrey;
+extern vec4_t colorDkGrey;
+
+#define Q_COLOR_ESCAPE '^'
+#define Q_IsColorString(p) ( p && *(p) == Q_COLOR_ESCAPE && *((p)+1) && *((p)+1) != Q_COLOR_ESCAPE )
+
+#define COLOR_BLACK '0'
+#define COLOR_RED '1'
+#define COLOR_GREEN '2'
+#define COLOR_YELLOW '3'
+#define COLOR_BLUE '4'
+#define COLOR_CYAN '5'
+#define COLOR_MAGENTA '6'
+#define COLOR_WHITE '7'
+#define ColorIndex(c) ( ( (c) - '0' ) & 7 )
+
+#define S_COLOR_BLACK "^0"
+#define S_COLOR_RED "^1"
+#define S_COLOR_GREEN "^2"
+#define S_COLOR_YELLOW "^3"
+#define S_COLOR_BLUE "^4"
+#define S_COLOR_CYAN "^5"
+#define S_COLOR_MAGENTA "^6"
+#define S_COLOR_WHITE "^7"
+
+extern vec4_t g_color_table[8];
+
+#define MAKERGB( v, r, g, b ) v[0]=r;v[1]=g;v[2]=b
+#define MAKERGBA( v, r, g, b, a ) v[0]=r;v[1]=g;v[2]=b;v[3]=a
+
+#define DEG2RAD( a ) ( ( (a) * M_PI ) / 180.0F )
+#define RAD2DEG( a ) ( ( (a) * 180.0f ) / M_PI )
+
+struct cplane_s;
+
+extern idVec3_t vec3_origin;
+extern vec4_t vec4_origin;
+extern mat3_t axisDefault;
+
+#define nanmask (255<<23)
+
+#define IS_NAN(x) (((*(int *)&x)&nanmask)==nanmask)
+
+float Q_fabs( float f );
+float Q_rsqrt( float f ); // reciprocal square root
+
+#define SQRTFAST( x ) ( 1.0f / Q_rsqrt( x ) )
+
+signed char ClampChar( int i );
+signed short ClampShort( int i );
+
+// this isn't a real cheap function to call!
+int DirToByte( const idVec3_t &dir );
+void ByteToDir( int b, vec3_p dir );
+
+#define DotProduct(a,b) ((a)[0]*(b)[0]+(a)[1]*(b)[1]+(a)[2]*(b)[2])
+#define VectorSubtract(a,b,c) ((c)[0]=(a)[0]-(b)[0],(c)[1]=(a)[1]-(b)[1],(c)[2]=(a)[2]-(b)[2])
+#define VectorAdd(a,b,c) ((c)[0]=(a)[0]+(b)[0],(c)[1]=(a)[1]+(b)[1],(c)[2]=(a)[2]+(b)[2])
+#define VectorCopy(a,b) ((b)[0]=(a)[0],(b)[1]=(a)[1],(b)[2]=(a)[2])
+//#define VectorCopy(a,b) ((b).x=(a).x,(b).y=(a).y,(b).z=(a).z])
+
+#define VectorScale(v, s, o) ((o)[0]=(v)[0]*(s),(o)[1]=(v)[1]*(s),(o)[2]=(v)[2]*(s))
+#define VectorMA(v, s, b, o) ((o)[0]=(v)[0]+(b)[0]*(s),(o)[1]=(v)[1]+(b)[1]*(s),(o)[2]=(v)[2]+(b)[2]*(s))
+#define CrossProduct(a,b,c) ((c)[0]=(a)[1]*(b)[2]-(a)[2]*(b)[1],(c)[1]=(a)[2]*(b)[0]-(a)[0]*(b)[2],(c)[2]=(a)[0]*(b)[1]-(a)[1]*(b)[0])
+
+#define DotProduct4(x,y) ((x)[0]*(y)[0]+(x)[1]*(y)[1]+(x)[2]*(y)[2]+(x)[3]*(y)[3])
+#define VectorSubtract4(a,b,c) ((c)[0]=(a)[0]-(b)[0],(c)[1]=(a)[1]-(b)[1],(c)[2]=(a)[2]-(b)[2],(c)[3]=(a)[3]-(b)[3])
+#define VectorAdd4(a,b,c) ((c)[0]=(a)[0]+(b)[0],(c)[1]=(a)[1]+(b)[1],(c)[2]=(a)[2]+(b)[2],(c)[3]=(a)[3]+(b)[3])
+#define VectorCopy4(a,b) ((b)[0]=(a)[0],(b)[1]=(a)[1],(b)[2]=(a)[2],(b)[3]=(a)[3])
+#define VectorScale4(v, s, o) ((o)[0]=(v)[0]*(s),(o)[1]=(v)[1]*(s),(o)[2]=(v)[2]*(s),(o)[3]=(v)[3]*(s))
+#define VectorMA4(v, s, b, o) ((o)[0]=(v)[0]+(b)[0]*(s),(o)[1]=(v)[1]+(b)[1]*(s),(o)[2]=(v)[2]+(b)[2]*(s),(o)[3]=(v)[3]+(b)[3]*(s))
+
+
+#define VectorClear(a) ((a)[0]=(a)[1]=(a)[2]=0)
+#define VectorNegate(a,b) ((b)[0]=-(a)[0],(b)[1]=-(a)[1],(b)[2]=-(a)[2])
+#define VectorSet(v, x, y, z) ((v)[0]=(x), (v)[1]=(y), (v)[2]=(z))
+#define Vector4Copy(a,b) ((b)[0]=(a)[0],(b)[1]=(a)[1],(b)[2]=(a)[2],(b)[3]=(a)[3])
+
+#define SnapVector(v) {v[0]=(int)v[0];v[1]=(int)v[1];v[2]=(int)v[2];}
+
+float NormalizeColor( vec3_c in, vec3_p out );
+
+int VectorCompare( vec3_c v1, vec3_c v2 );
+float VectorLength( vec3_c v );
+float Distance( vec3_c p1, vec3_c p2 );
+float DistanceSquared( vec3_c p1, vec3_c p2 );
+float VectorNormalize (vec3_p v); // returns vector length
+void VectorNormalizeFast(vec3_p v); // does NOT return vector length, uses rsqrt approximation
+float VectorNormalize2( vec3_c v, vec3_p out );
+void VectorInverse (vec3_p v);
+void VectorRotate( vec3_c in, mat3_c matrix, vec3_p out );
+void VectorPolar(vec3_p v, float radius, float theta, float phi);
+void VectorSnap(vec3_p v);
+void Vector53Copy( const idVec5_t &in, vec3_p out);
+void Vector5Scale( const idVec5_t &v, float scale, idVec5_t &out);
+void Vector5Add( const idVec5_t &va, const idVec5_t &vb, idVec5_t &out);
+void VectorRotate3( vec3_c vIn, vec3_c vRotation, vec3_p out);
+void VectorRotate3Origin(vec3_c vIn, vec3_c vRotation, vec3_c vOrigin, vec3_p out);
+
+
+int Q_log2(int val);
+
+int Q_rand( int *seed );
+float Q_random( int *seed );
+float Q_crandom( int *seed );
+
+#define random() ((rand () & 0x7fff) / ((float)0x7fff))
+#define crandom() (2.0 * (random() - 0.5))
+
+float Q_rint( float in );
+
+void vectoangles( vec3_c value1, angles_p angles);
+void AnglesToAxis( angles_c angles, mat3_p axis );
+
+void AxisCopy( mat3_c in, mat3_p out );
+qboolean AxisRotated( mat3_c in ); // assumes a non-degenerate axis
+
+int SignbitsForNormal( vec3_c normal );
+int BoxOnPlaneSide( const Bounds &b, struct cplane_s *p );
+
+float AngleMod(float a);
+float LerpAngle (float from, float to, float frac);
+float AngleSubtract( float a1, float a2 );
+void AnglesSubtract( angles_c v1, angles_c v2, angles_p v3 );
+
+float AngleNormalize360 ( float angle );
+float AngleNormalize180 ( float angle );
+float AngleDelta ( float angle1, float angle2 );
+
+qboolean PlaneFromPoints( vec4_t &plane, vec3_c a, vec3_c b, vec3_c c );
+void ProjectPointOnPlane( vec3_p dst, vec3_c p, vec3_c normal );
+void RotatePointAroundVector( vec3_p dst, vec3_c dir, vec3_c point, float degrees );
+void RotateAroundDirection( mat3_p axis, float yaw );
+void MakeNormalVectors( vec3_c forward, vec3_p right, vec3_p up );
+// perpendicular vector could be replaced by this
+
+int PlaneTypeForNormal( vec3_c normal );
+
+void MatrixMultiply( mat3_c in1, mat3_c in2, mat3_p out );
+void MatrixInverseMultiply( mat3_c in1, mat3_c in2, mat3_p out ); // in2 is transposed during multiply
+void MatrixTransformVector( vec3_c in, mat3_c matrix, vec3_p out );
+void MatrixProjectVector( vec3_c in, mat3_c matrix, vec3_p out ); // Places the vector into a new coordinate system.
+void AngleVectors( angles_c angles, vec3_p forward, vec3_p right, vec3_p up);
+void PerpendicularVector( vec3_p dst, vec3_c src );
+
+float TriangleArea( vec3_c a, vec3_c b, vec3_c c );
+#endif // __cplusplus
+
+//=============================================
+
+float Com_Clamp( float min, float max, float value );
+
+#define FILE_HASH_SIZE 1024
+int Com_HashString( const char *fname );
+
+char *Com_SkipPath( char *pathname );
+
+// it is ok for out == in
+void Com_StripExtension( const char *in, char *out );
+
+// "extension" should include the dot: ".map"
+void Com_DefaultExtension( char *path, int maxSize, const char *extension );
+
+int Com_ParseInfos( const char *buf, int max, char infos[][MAX_INFO_STRING] );
+
+/*
+=====================================================================================
+
+SCRIPT PARSING
+
+=====================================================================================
+*/
+
+// this just controls the comment printing, it doesn't actually load a file
+void Com_BeginParseSession( const char *filename );
+void Com_EndParseSession( void );
+
+int Com_GetCurrentParseLine( void );
+
+// Will never return NULL, just empty strings.
+// An empty string will only be returned at end of file.
+// ParseOnLine will return empty if there isn't another token on this line
+
+// this funny typedef just means a moving pointer into a const char * buffer
+const char *Com_Parse( const char *(*data_p) );
+const char *Com_ParseOnLine( const char *(*data_p) );
+const char *Com_ParseRestOfLine( const char *(*data_p) );
+
+void Com_UngetToken( void );
+
+#ifdef __cplusplus
+void Com_MatchToken( const char *(*buf_p), const char *match, qboolean warning = qfalse );
+#else
+void Com_MatchToken( const char *(*buf_p), const char *match, qboolean warning );
+#endif
+
+void Com_ScriptError( const char *msg, ... );
+void Com_ScriptWarning( const char *msg, ... );
+
+void Com_SkipBracedSection( const char *(*program) );
+void Com_SkipRestOfLine( const char *(*data) );
+
+float Com_ParseFloat( const char *(*buf_p) );
+int Com_ParseInt( const char *(*buf_p) );
+
+void Com_Parse1DMatrix( const char *(*buf_p), int x, float *m );
+void Com_Parse2DMatrix( const char *(*buf_p), int y, int x, float *m );
+void Com_Parse3DMatrix( const char *(*buf_p), int z, int y, int x, float *m );
+
+//=====================================================================================
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+void QDECL Com_sprintf (char *dest, int size, const char *fmt, ...);
+
+
+// mode parm for FS_FOpenFile
+typedef enum {
+ FS_READ,
+ FS_WRITE,
+ FS_APPEND,
+ FS_APPEND_SYNC
+} fsMode_t;
+
+typedef enum {
+ FS_SEEK_CUR,
+ FS_SEEK_END,
+ FS_SEEK_SET
+} fsOrigin_t;
+
+//=============================================
+
+int Q_isprint( int c );
+int Q_islower( int c );
+int Q_isupper( int c );
+int Q_isalpha( int c );
+
+// portable case insensitive compare
+int Q_stricmp (const char *s1, const char *s2);
+int Q_strncmp (const char *s1, const char *s2, int n);
+int Q_stricmpn (const char *s1, const char *s2, int n);
+char *Q_strlwr( char *s1 );
+char *Q_strupr( char *s1 );
+char *Q_strrchr( const char* string, int c );
+
+// buffer size safe library replacements
+void Q_strncpyz( char *dest, const char *src, int destsize );
+void Q_strcat( char *dest, int size, const char *src );
+
+// strlen that discounts Quake color sequences
+int Q_PrintStrlen( const char *string );
+// removes color sequences from string
+char *Q_CleanStr( char *string );
+
+int Com_Filter( const char *filter, const char *name, int casesensitive );
+const char *Com_StringContains( const char *str1, const char *str2, int casesensitive );
+
+
+//=============================================
+
+short BigShort(short l);
+short LittleShort(short l);
+int BigLong (int l);
+int LittleLong (int l);
+float BigFloat (float l);
+float LittleFloat (float l);
+
+void Swap_Init (void);
+char * QDECL va(char *format, ...);
+
+#ifdef __cplusplus
+ }
+#endif
+
+
+//=============================================
+#ifdef __cplusplus
+//
+// mapfile parsing
+//
+typedef struct ePair_s {
+ char *key;
+ char *value;
+} ePair_t;
+
+typedef struct mapSide_s {
+ char material[MAX_QPATH];
+ vec4_t plane;
+ vec4_t textureVectors[2];
+} mapSide_t;
+
+typedef struct {
+ int numSides;
+ mapSide_t **sides;
+} mapBrush_t;
+
+typedef struct {
+ idVec3_t xyz;
+ float st[2];
+} patchVertex_t;
+
+typedef struct {
+ char material[MAX_QPATH];
+ int width, height;
+ patchVertex_t *patchVerts;
+} mapPatch_t;
+
+typedef struct {
+ char modelName[MAX_QPATH];
+ float matrix[16];
+} mapModel_t;
+
+typedef struct mapPrimitive_s {
+ int numEpairs;
+ ePair_t **ePairs;
+
+ // only one of these will be non-NULL
+ mapBrush_t *brush;
+ mapPatch_t *patch;
+ mapModel_t *model;
+} mapPrimitive_t;
+
+typedef struct mapEntity_s {
+ int numPrimitives;
+ mapPrimitive_t **primitives;
+
+ int numEpairs;
+ ePair_t **ePairs;
+} mapEntity_t;
+
+typedef struct {
+ int numEntities;
+ mapEntity_t **entities;
+} mapFile_t;
+
+
+// the order of entities, brushes, and sides will be maintained, the
+// lists won't be swapped on each load or save
+mapFile_t *ParseMapFile( const char *text );
+void FreeMapFile( mapFile_t *mapFile );
+void WriteMapFile( const mapFile_t *mapFile, FILE *f );
+
+// key names are case-insensitive
+const char *ValueForMapEntityKey( const mapEntity_t *ent, const char *key );
+float FloatForMapEntityKey( const mapEntity_t *ent, const char *key );
+qboolean GetVectorForMapEntityKey( const mapEntity_t *ent, const char *key, idVec3_t &vec );
+
+typedef struct {
+ idVec3_t xyz;
+ idVec2_t st;
+ idVec3_t normal;
+ idVec3_t tangents[2];
+ byte smoothing[4]; // colors for silhouette smoothing
+} drawVert_t;
+
+typedef struct {
+ int width, height;
+ drawVert_t *verts;
+} drawVertMesh_t;
+
+// Tesselate a map patch into smoothed, drawable vertexes
+// MaxError of around 4 is reasonable
+drawVertMesh_t *SubdivideMapPatch( const mapPatch_t *patch, float maxError );
+#endif // __cplusplus
+
+//=========================================
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+void QDECL Com_Error( int level, const char *error, ... );
+void QDECL Com_Printf( const char *msg, ... );
+void QDECL Com_DPrintf( const char *msg, ... );
+
+#ifdef __cplusplus
+ }
+#endif
+
+
+typedef struct {
+ qboolean frameMemory;
+ int currentElements;
+ int maxElements; // will reallocate and move when exceeded
+ void **elements;
+} growList_t;
+
+// you don't need to init the growlist if you don't mind it growing and moving
+// the list as it expands
+void Com_InitGrowList( growList_t *list, int maxElements );
+int Com_AddToGrowList( growList_t *list, void *data );
+void *Com_GrowListElement( const growList_t *list, int index );
+int Com_IndexForGrowListElement( const growList_t *list, const void *element );
+
+
+//
+// key / value info strings
+//
+char *Info_ValueForKey( const char *s, const char *key );
+void Info_RemoveKey( char *s, const char *key );
+void Info_SetValueForKey( char *s, const char *key, const char *value );
+qboolean Info_Validate( const char *s );
+void Info_NextPair( const char *(*s), char key[MAX_INFO_KEY], char value[MAX_INFO_VALUE] );
+
+// get cvar defs, collision defs, etc
+//#include "../shared/interface.h"
+
+// get key code numbers for events
+//#include "../shared/keycodes.h"
+
+#ifdef __cplusplus
+// get the polygon winding functions
+//#include "../shared/windings.h"
+
+// get the flags class
+//#include "../shared/idflags.h"
+#endif // __cplusplus
+
+#endif // __Q_SHARED_H
+
diff --git a/code/splines/q_shared.hpp b/code/splines/q_shared.hpp
new file mode 100755
index 0000000..bfe0925
--- /dev/null
+++ b/code/splines/q_shared.hpp
@@ -0,0 +1,810 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __Q_SHARED_H
+#define __Q_SHARED_H
+
+// q_shared.h -- included first by ALL program modules.
+// these are the definitions that have no dependance on
+// central system services, and can be used by any part
+// of the program without any state issues.
+
+// A user mod should never modify this file
+
+// incursion of DOOM code into the Q3A codebase
+//#define Q3_VERSION "DOOM 0.01"
+
+// alignment macros for SIMD
+#define ALIGN_ON
+#define ALIGN_OFF
+
+#ifdef _WIN32
+
+#pragma warning(disable : 4018) // signed/unsigned mismatch
+#pragma warning(disable : 4032)
+#pragma warning(disable : 4051)
+#pragma warning(disable : 4057) // slightly different base types
+#pragma warning(disable : 4100) // unreferenced formal parameter
+#pragma warning(disable : 4115)
+#pragma warning(disable : 4125) // decimal digit terminates octal escape sequence
+#pragma warning(disable : 4127) // conditional expression is constant
+#pragma warning(disable : 4136)
+#pragma warning(disable : 4201)
+#pragma warning(disable : 4214)
+#pragma warning(disable : 4244)
+#pragma warning(disable : 4305) // truncation from const double to float
+#pragma warning(disable : 4310) // cast truncates constant value
+#pragma warning(disable : 4514)
+#pragma warning(disable : 4711) // selected for automatic inline expansion
+#pragma warning(disable : 4220) // varargs matches remaining parameters
+
+#endif
+
+#include <assert.h>
+#include <math.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <string.h>
+#include <stdlib.h>
+#include <time.h>
+#include <ctype.h>
+#ifdef WIN32 // mac doesn't have malloc.h
+#include <malloc.h> // for _alloca()
+#endif
+#ifdef _WIN32
+
+//#pragma intrinsic( memset, memcpy )
+
+#endif
+
+
+// this is the define for determining if we have an asm version of a C function
+#if (defined _M_IX86 || defined __i386__) && !defined __sun__ && !defined __LCC__
+#define id386 1
+#else
+#define id386 0
+#endif
+
+// for windows fastcall option
+
+#define QDECL
+
+//======================= WIN32 DEFINES =================================
+
+#ifdef WIN32
+
+#define MAC_STATIC
+
+#undef QDECL
+#define QDECL __cdecl
+
+// buildstring will be incorporated into the version string
+#ifdef NDEBUG
+#ifdef _M_IX86
+#define CPUSTRING "win-x86"
+#elif defined _M_ALPHA
+#define CPUSTRING "win-AXP"
+#endif
+#else
+#ifdef _M_IX86
+#define CPUSTRING "win-x86-debug"
+#elif defined _M_ALPHA
+#define CPUSTRING "win-AXP-debug"
+#endif
+#endif
+
+
+#define PATH_SEP '\\'
+
+#endif
+
+//======================= MAC OS X SERVER DEFINES =====================
+
+#if defined(__MACH__) && defined(__APPLE__)
+
+#define MAC_STATIC
+
+#ifdef __ppc__
+#define CPUSTRING "MacOSXS-ppc"
+#elif defined __i386__
+#define CPUSTRING "MacOSXS-i386"
+#else
+#define CPUSTRING "MacOSXS-other"
+#endif
+
+#define PATH_SEP '/'
+
+#define GAME_HARD_LINKED
+#define CGAME_HARD_LINKED
+#define UI_HARD_LINKED
+#define _alloca alloca
+
+#undef ALIGN_ON
+#undef ALIGN_OFF
+#define ALIGN_ON #pragma align(16)
+#define ALIGN_OFF #pragma align()
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+void *osxAllocateMemory(long size);
+void osxFreeMemory(void *pointer);
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif
+
+//======================= MAC DEFINES =================================
+
+#ifdef __MACOS__
+
+#define MAC_STATIC static
+
+#define CPUSTRING "MacOS-PPC"
+
+#define PATH_SEP ':'
+
+void Sys_PumpEvents( void );
+
+#endif
+
+#ifdef __MRC__
+
+#define MAC_STATIC
+
+#define CPUSTRING "MacOS-PPC"
+
+#define PATH_SEP ':'
+
+void Sys_PumpEvents( void );
+
+#undef QDECL
+#define QDECL __cdecl
+
+#define _alloca alloca
+#endif
+
+//======================= LINUX DEFINES =================================
+
+// the mac compiler can't handle >32k of locals, so we
+// just waste space and make big arrays static...
+#ifdef __linux__
+
+// bk001205 - from Makefile
+#define stricmp strcasecmp
+
+#define MAC_STATIC // bk: FIXME
+
+#ifdef __i386__
+#define CPUSTRING "linux-i386"
+#elif defined __axp__
+#define CPUSTRING "linux-alpha"
+#else
+#define CPUSTRING "linux-other"
+#endif
+
+#define PATH_SEP '/'
+
+// bk001205 - try
+#ifdef Q3_STATIC
+#define GAME_HARD_LINKED
+#define CGAME_HARD_LINKED
+#define UI_HARD_LINKED
+#define BOTLIB_HARD_LINKED
+#endif
+
+#endif
+
+//=============================================================
+
+
+
+typedef enum {qfalse, qtrue} qboolean;
+
+typedef unsigned char byte;
+
+#define EQUAL_EPSILON 0.001
+
+typedef int qhandle_t;
+typedef int sfxHandle_t;
+typedef int fileHandle_t;
+typedef int clipHandle_t;
+
+typedef enum {
+ INVALID_JOINT = -1
+} jointHandle_t;
+
+#ifndef NULL
+#define NULL ((void *)0)
+#endif
+
+#define MAX_QINT 0x7fffffff
+#define MIN_QINT (-MAX_QINT-1)
+
+#ifndef max
+#define max( x, y ) ( ( ( x ) > ( y ) ) ? ( x ) : ( y ) )
+#define min( x, y ) ( ( ( x ) < ( y ) ) ? ( x ) : ( y ) )
+#endif
+
+#ifndef sign
+#define sign( f ) ( ( f > 0 ) ? 1 : ( ( f < 0 ) ? -1 : 0 ) )
+#endif
+
+// angle indexes
+#define PITCH 0 // up / down
+#define YAW 1 // left / right
+#define ROLL 2 // fall over
+
+// the game guarantees that no string from the network will ever
+// exceed MAX_STRING_CHARS
+#define MAX_STRING_CHARS 1024 // max length of a string passed to Cmd_TokenizeString
+#define MAX_STRING_TOKENS 256 // max tokens resulting from Cmd_TokenizeString
+#define MAX_TOKEN_CHARS 1024 // max length of an individual token
+
+#define MAX_INFO_STRING 1024
+#define MAX_INFO_KEY 1024
+#define MAX_INFO_VALUE 1024
+
+
+#define MAX_QPATH 64 // max length of a quake game pathname
+#define MAX_OSPATH 128 // max length of a filesystem pathname
+
+#define MAX_NAME_LENGTH 32 // max length of a client name
+
+// paramters for command buffer stuffing
+typedef enum {
+ EXEC_NOW, // don't return until completed, a VM should NEVER use this,
+ // because some commands might cause the VM to be unloaded...
+ EXEC_INSERT, // insert at current position, but don't run yet
+ EXEC_APPEND // add to end of the command buffer (normal case)
+} cbufExec_t;
+
+
+//
+// these aren't needed by any of the VMs. put in another header?
+//
+#define MAX_MAP_AREA_BYTES 32 // bit vector of area visibility
+
+#undef ERR_FATAL // malloc.h on unix
+
+// parameters to the main Error routine
+typedef enum {
+ ERR_NONE,
+ ERR_FATAL, // exit the entire game with a popup window
+ ERR_DROP, // print to console and disconnect from game
+ ERR_DISCONNECT, // don't kill server
+ ERR_NEED_CD // pop up the need-cd dialog
+} errorParm_t;
+
+
+// font rendering values used by ui and cgame
+
+#define PROP_GAP_WIDTH 3
+#define PROP_SPACE_WIDTH 8
+#define PROP_HEIGHT 27
+#define PROP_SMALL_SIZE_SCALE 0.75
+
+#define BLINK_DIVISOR 200
+#define PULSE_DIVISOR 75
+
+#define UI_LEFT 0x00000000 // default
+#define UI_CENTER 0x00000001
+#define UI_RIGHT 0x00000002
+#define UI_FORMATMASK 0x00000007
+#define UI_SMALLFONT 0x00000010
+#define UI_BIGFONT 0x00000020 // default
+#define UI_GIANTFONT 0x00000040
+#define UI_DROPSHADOW 0x00000800
+#define UI_BLINK 0x00001000
+#define UI_INVERSE 0x00002000
+#define UI_PULSE 0x00004000
+
+
+/*
+==============================================================
+
+MATHLIB
+
+==============================================================
+*/
+#ifdef __cplusplus // so we can include this in C code
+#define SIDE_FRONT 0
+#define SIDE_BACK 1
+#define SIDE_ON 2
+#define SIDE_CROSS 3
+
+#define Q_PI 3.14159265358979323846
+#ifndef M_PI
+#define M_PI 3.14159265358979323846 // matches value in gcc v2 math.h
+#endif
+
+#include "math_vector.h"
+#include "math_angles.h"
+#include "math_matrix.h"
+#include "math_quaternion.h"
+
+class idVec3_t; // for defining vectors
+typedef idVec3_t &vec3_p; // for passing vectors as function arguments
+typedef const idVec3_t &vec3_c; // for passing vectors as const function arguments
+
+class angles_t; // for defining angle vectors
+typedef angles_t &angles_p; // for passing angles as function arguments
+typedef const angles_t &angles_c; // for passing angles as const function arguments
+
+class mat3_t; // for defining matrices
+typedef mat3_t &mat3_p; // for passing matrices as function arguments
+typedef const mat3_t &mat3_c; // for passing matrices as const function arguments
+
+
+
+#define NUMVERTEXNORMALS 162
+extern idVec3_t bytedirs[NUMVERTEXNORMALS];
+
+// all drawing is done to a 640*480 virtual screen size
+// and will be automatically scaled to the real resolution
+#define SCREEN_WIDTH 640
+#define SCREEN_HEIGHT 480
+
+#define TINYCHAR_WIDTH (SMALLCHAR_WIDTH)
+#define TINYCHAR_HEIGHT (SMALLCHAR_HEIGHT/2)
+
+#define SMALLCHAR_WIDTH 8
+#define SMALLCHAR_HEIGHT 16
+
+#define BIGCHAR_WIDTH 16
+#define BIGCHAR_HEIGHT 16
+
+#define GIANTCHAR_WIDTH 32
+#define GIANTCHAR_HEIGHT 48
+
+extern vec4_t colorBlack;
+extern vec4_t colorRed;
+extern vec4_t colorGreen;
+extern vec4_t colorBlue;
+extern vec4_t colorYellow;
+extern vec4_t colorMagenta;
+extern vec4_t colorCyan;
+extern vec4_t colorWhite;
+extern vec4_t colorLtGrey;
+extern vec4_t colorMdGrey;
+extern vec4_t colorDkGrey;
+
+#define Q_COLOR_ESCAPE '^'
+#define Q_IsColorString(p) ( p && *(p) == Q_COLOR_ESCAPE && *((p)+1) && *((p)+1) != Q_COLOR_ESCAPE )
+
+#define COLOR_BLACK '0'
+#define COLOR_RED '1'
+#define COLOR_GREEN '2'
+#define COLOR_YELLOW '3'
+#define COLOR_BLUE '4'
+#define COLOR_CYAN '5'
+#define COLOR_MAGENTA '6'
+#define COLOR_WHITE '7'
+#define ColorIndex(c) ( ( (c) - '0' ) & 7 )
+
+#define S_COLOR_BLACK "^0"
+#define S_COLOR_RED "^1"
+#define S_COLOR_GREEN "^2"
+#define S_COLOR_YELLOW "^3"
+#define S_COLOR_BLUE "^4"
+#define S_COLOR_CYAN "^5"
+#define S_COLOR_MAGENTA "^6"
+#define S_COLOR_WHITE "^7"
+
+extern vec4_t g_color_table[8];
+
+#define MAKERGB( v, r, g, b ) v[0]=r;v[1]=g;v[2]=b
+#define MAKERGBA( v, r, g, b, a ) v[0]=r;v[1]=g;v[2]=b;v[3]=a
+
+#define DEG2RAD( a ) ( ( (a) * M_PI ) / 180.0F )
+#define RAD2DEG( a ) ( ( (a) * 180.0f ) / M_PI )
+
+struct cplane_s;
+
+extern idVec3_t vec3_origin;
+extern vec4_t vec4_origin;
+extern mat3_t axisDefault;
+
+#define nanmask (255<<23)
+
+#define IS_NAN(x) (((*(int *)&x)&nanmask)==nanmask)
+
+float Q_fabs( float f );
+float Q_rsqrt( float f ); // reciprocal square root
+
+#define SQRTFAST( x ) ( 1.0f / Q_rsqrt( x ) )
+
+signed char ClampChar( int i );
+signed short ClampShort( int i );
+
+// this isn't a real cheap function to call!
+int DirToByte( const idVec3_t &dir );
+void ByteToDir( int b, vec3_p dir );
+
+#define DotProduct(a,b) ((a)[0]*(b)[0]+(a)[1]*(b)[1]+(a)[2]*(b)[2])
+#define VectorSubtract(a,b,c) ((c)[0]=(a)[0]-(b)[0],(c)[1]=(a)[1]-(b)[1],(c)[2]=(a)[2]-(b)[2])
+#define VectorAdd(a,b,c) ((c)[0]=(a)[0]+(b)[0],(c)[1]=(a)[1]+(b)[1],(c)[2]=(a)[2]+(b)[2])
+#define VectorCopy(a,b) ((b)[0]=(a)[0],(b)[1]=(a)[1],(b)[2]=(a)[2])
+//#define VectorCopy(a,b) ((b).x=(a).x,(b).y=(a).y,(b).z=(a).z])
+
+#define VectorScale(v, s, o) ((o)[0]=(v)[0]*(s),(o)[1]=(v)[1]*(s),(o)[2]=(v)[2]*(s))
+#define VectorMA(v, s, b, o) ((o)[0]=(v)[0]+(b)[0]*(s),(o)[1]=(v)[1]+(b)[1]*(s),(o)[2]=(v)[2]+(b)[2]*(s))
+#define CrossProduct(a,b,c) ((c)[0]=(a)[1]*(b)[2]-(a)[2]*(b)[1],(c)[1]=(a)[2]*(b)[0]-(a)[0]*(b)[2],(c)[2]=(a)[0]*(b)[1]-(a)[1]*(b)[0])
+
+#define DotProduct4(x,y) ((x)[0]*(y)[0]+(x)[1]*(y)[1]+(x)[2]*(y)[2]+(x)[3]*(y)[3])
+#define VectorSubtract4(a,b,c) ((c)[0]=(a)[0]-(b)[0],(c)[1]=(a)[1]-(b)[1],(c)[2]=(a)[2]-(b)[2],(c)[3]=(a)[3]-(b)[3])
+#define VectorAdd4(a,b,c) ((c)[0]=(a)[0]+(b)[0],(c)[1]=(a)[1]+(b)[1],(c)[2]=(a)[2]+(b)[2],(c)[3]=(a)[3]+(b)[3])
+#define VectorCopy4(a,b) ((b)[0]=(a)[0],(b)[1]=(a)[1],(b)[2]=(a)[2],(b)[3]=(a)[3])
+#define VectorScale4(v, s, o) ((o)[0]=(v)[0]*(s),(o)[1]=(v)[1]*(s),(o)[2]=(v)[2]*(s),(o)[3]=(v)[3]*(s))
+#define VectorMA4(v, s, b, o) ((o)[0]=(v)[0]+(b)[0]*(s),(o)[1]=(v)[1]+(b)[1]*(s),(o)[2]=(v)[2]+(b)[2]*(s),(o)[3]=(v)[3]+(b)[3]*(s))
+
+
+#define VectorClear(a) ((a)[0]=(a)[1]=(a)[2]=0)
+#define VectorNegate(a,b) ((b)[0]=-(a)[0],(b)[1]=-(a)[1],(b)[2]=-(a)[2])
+#define VectorSet(v, x, y, z) ((v)[0]=(x), (v)[1]=(y), (v)[2]=(z))
+#define Vector4Copy(a,b) ((b)[0]=(a)[0],(b)[1]=(a)[1],(b)[2]=(a)[2],(b)[3]=(a)[3])
+
+#define SnapVector(v) {v[0]=(int)v[0];v[1]=(int)v[1];v[2]=(int)v[2];}
+
+float NormalizeColor( vec3_c in, vec3_p out );
+
+int VectorCompare( vec3_c v1, vec3_c v2 );
+float VectorLength( vec3_c v );
+float Distance( vec3_c p1, vec3_c p2 );
+float DistanceSquared( vec3_c p1, vec3_c p2 );
+float VectorNormalize (vec3_p v); // returns vector length
+void VectorNormalizeFast(vec3_p v); // does NOT return vector length, uses rsqrt approximation
+float VectorNormalize2( vec3_c v, vec3_p out );
+void VectorInverse (vec3_p v);
+void VectorRotate( vec3_c in, mat3_c matrix, vec3_p out );
+void VectorPolar(vec3_p v, float radius, float theta, float phi);
+void VectorSnap(vec3_p v);
+void Vector53Copy( const idVec5_t &in, vec3_p out);
+void Vector5Scale( const idVec5_t &v, float scale, idVec5_t &out);
+void Vector5Add( const idVec5_t &va, const idVec5_t &vb, idVec5_t &out);
+void VectorRotate3( vec3_c vIn, vec3_c vRotation, vec3_p out);
+void VectorRotate3Origin(vec3_c vIn, vec3_c vRotation, vec3_c vOrigin, vec3_p out);
+
+
+int Q_log2(int val);
+
+int Q_rand( int *seed );
+float Q_random( int *seed );
+float Q_crandom( int *seed );
+
+#define random() ((rand () & 0x7fff) / ((float)0x7fff))
+#define crandom() (2.0 * (random() - 0.5))
+
+float Q_rint( float in );
+
+void vectoangles( vec3_c value1, angles_p angles);
+void AnglesToAxis( angles_c angles, mat3_p axis );
+
+void AxisCopy( mat3_c in, mat3_p out );
+qboolean AxisRotated( mat3_c in ); // assumes a non-degenerate axis
+
+int SignbitsForNormal( vec3_c normal );
+int BoxOnPlaneSide( const Bounds &b, struct cplane_s *p );
+
+float AngleMod(float a);
+float LerpAngle (float from, float to, float frac);
+float AngleSubtract( float a1, float a2 );
+void AnglesSubtract( angles_c v1, angles_c v2, angles_p v3 );
+
+float AngleNormalize360 ( float angle );
+float AngleNormalize180 ( float angle );
+float AngleDelta ( float angle1, float angle2 );
+
+qboolean PlaneFromPoints( vec4_t &plane, vec3_c a, vec3_c b, vec3_c c );
+void ProjectPointOnPlane( vec3_p dst, vec3_c p, vec3_c normal );
+void RotatePointAroundVector( vec3_p dst, vec3_c dir, vec3_c point, float degrees );
+void RotateAroundDirection( mat3_p axis, float yaw );
+void MakeNormalVectors( vec3_c forward, vec3_p right, vec3_p up );
+// perpendicular vector could be replaced by this
+
+int PlaneTypeForNormal( vec3_c normal );
+
+void MatrixMultiply( mat3_c in1, mat3_c in2, mat3_p out );
+void MatrixInverseMultiply( mat3_c in1, mat3_c in2, mat3_p out ); // in2 is transposed during multiply
+void MatrixTransformVector( vec3_c in, mat3_c matrix, vec3_p out );
+void MatrixProjectVector( vec3_c in, mat3_c matrix, vec3_p out ); // Places the vector into a new coordinate system.
+void AngleVectors( angles_c angles, vec3_p forward, vec3_p right, vec3_p up);
+void PerpendicularVector( vec3_p dst, vec3_c src );
+
+float TriangleArea( vec3_c a, vec3_c b, vec3_c c );
+#endif // __cplusplus
+
+//=============================================
+
+float Com_Clamp( float min, float max, float value );
+
+#define FILE_HASH_SIZE 1024
+int Com_HashString( const char *fname );
+
+char *Com_SkipPath( char *pathname );
+
+// it is ok for out == in
+void Com_StripExtension( const char *in, char *out );
+
+// "extension" should include the dot: ".map"
+void Com_DefaultExtension( char *path, int maxSize, const char *extension );
+
+int Com_ParseInfos( const char *buf, int max, char infos[][MAX_INFO_STRING] );
+
+/*
+=====================================================================================
+
+SCRIPT PARSING
+
+=====================================================================================
+*/
+
+// this just controls the comment printing, it doesn't actually load a file
+void Com_BeginParseSession( const char *filename );
+void Com_EndParseSession( void );
+
+int Com_GetCurrentParseLine( void );
+
+// Will never return NULL, just empty strings.
+// An empty string will only be returned at end of file.
+// ParseOnLine will return empty if there isn't another token on this line
+
+// this funny typedef just means a moving pointer into a const char * buffer
+const char *Com_Parse( const char *(*data_p) );
+const char *Com_ParseOnLine( const char *(*data_p) );
+const char *Com_ParseRestOfLine( const char *(*data_p) );
+
+void Com_UngetToken( void );
+
+#ifdef __cplusplus
+void Com_MatchToken( const char *(*buf_p), const char *match, qboolean warning = qfalse );
+#else
+void Com_MatchToken( const char *(*buf_p), const char *match, qboolean warning );
+#endif
+
+void Com_ScriptError( const char *msg, ... );
+void Com_ScriptWarning( const char *msg, ... );
+
+void Com_SkipBracedSection( const char *(*program) );
+void Com_SkipRestOfLine( const char *(*data) );
+
+float Com_ParseFloat( const char *(*buf_p) );
+int Com_ParseInt( const char *(*buf_p) );
+
+void Com_Parse1DMatrix( const char *(*buf_p), int x, float *m );
+void Com_Parse2DMatrix( const char *(*buf_p), int y, int x, float *m );
+void Com_Parse3DMatrix( const char *(*buf_p), int z, int y, int x, float *m );
+
+//=====================================================================================
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+void QDECL Com_sprintf (char *dest, int size, const char *fmt, ...);
+
+
+// mode parm for FS_FOpenFile
+typedef enum {
+ FS_READ,
+ FS_WRITE,
+ FS_APPEND,
+ FS_APPEND_SYNC
+} fsMode_t;
+
+typedef enum {
+ FS_SEEK_CUR,
+ FS_SEEK_END,
+ FS_SEEK_SET
+} fsOrigin_t;
+
+//=============================================
+
+int Q_isprint( int c );
+int Q_islower( int c );
+int Q_isupper( int c );
+int Q_isalpha( int c );
+
+// portable case insensitive compare
+int Q_stricmp (const char *s1, const char *s2);
+int Q_strncmp (const char *s1, const char *s2, int n);
+int Q_stricmpn (const char *s1, const char *s2, int n);
+char *Q_strlwr( char *s1 );
+char *Q_strupr( char *s1 );
+char *Q_strrchr( const char* string, int c );
+
+// buffer size safe library replacements
+void Q_strncpyz( char *dest, const char *src, int destsize );
+void Q_strcat( char *dest, int size, const char *src );
+
+// strlen that discounts Quake color sequences
+int Q_PrintStrlen( const char *string );
+// removes color sequences from string
+char *Q_CleanStr( char *string );
+
+int Com_Filter( const char *filter, const char *name, int casesensitive );
+const char *Com_StringContains( const char *str1, const char *str2, int casesensitive );
+
+
+//=============================================
+
+short BigShort(short l);
+short LittleShort(short l);
+int BigLong (int l);
+int LittleLong (int l);
+float BigFloat (float l);
+float LittleFloat (float l);
+
+void Swap_Init (void);
+char * QDECL va(char *format, ...);
+
+#ifdef __cplusplus
+ }
+#endif
+
+
+//=============================================
+#ifdef __cplusplus
+//
+// mapfile parsing
+//
+typedef struct ePair_s {
+ char *key;
+ char *value;
+} ePair_t;
+
+typedef struct mapSide_s {
+ char material[MAX_QPATH];
+ vec4_t plane;
+ vec4_t textureVectors[2];
+} mapSide_t;
+
+typedef struct {
+ int numSides;
+ mapSide_t **sides;
+} mapBrush_t;
+
+typedef struct {
+ idVec3_t xyz;
+ float st[2];
+} patchVertex_t;
+
+typedef struct {
+ char material[MAX_QPATH];
+ int width, height;
+ patchVertex_t *patchVerts;
+} mapPatch_t;
+
+typedef struct {
+ char modelName[MAX_QPATH];
+ float matrix[16];
+} mapModel_t;
+
+typedef struct mapPrimitive_s {
+ int numEpairs;
+ ePair_t **ePairs;
+
+ // only one of these will be non-NULL
+ mapBrush_t *brush;
+ mapPatch_t *patch;
+ mapModel_t *model;
+} mapPrimitive_t;
+
+typedef struct mapEntity_s {
+ int numPrimitives;
+ mapPrimitive_t **primitives;
+
+ int numEpairs;
+ ePair_t **ePairs;
+} mapEntity_t;
+
+typedef struct {
+ int numEntities;
+ mapEntity_t **entities;
+} mapFile_t;
+
+
+// the order of entities, brushes, and sides will be maintained, the
+// lists won't be swapped on each load or save
+mapFile_t *ParseMapFile( const char *text );
+void FreeMapFile( mapFile_t *mapFile );
+void WriteMapFile( const mapFile_t *mapFile, FILE *f );
+
+// key names are case-insensitive
+const char *ValueForMapEntityKey( const mapEntity_t *ent, const char *key );
+float FloatForMapEntityKey( const mapEntity_t *ent, const char *key );
+qboolean GetVectorForMapEntityKey( const mapEntity_t *ent, const char *key, idVec3_t &vec );
+
+typedef struct {
+ idVec3_t xyz;
+ idVec2_t st;
+ idVec3_t normal;
+ idVec3_t tangents[2];
+ byte smoothing[4]; // colors for silhouette smoothing
+} drawVert_t;
+
+typedef struct {
+ int width, height;
+ drawVert_t *verts;
+} drawVertMesh_t;
+
+// Tesselate a map patch into smoothed, drawable vertexes
+// MaxError of around 4 is reasonable
+drawVertMesh_t *SubdivideMapPatch( const mapPatch_t *patch, float maxError );
+#endif // __cplusplus
+
+//=========================================
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+void QDECL Com_Error( int level, const char *error, ... );
+void QDECL Com_Printf( const char *msg, ... );
+void QDECL Com_DPrintf( const char *msg, ... );
+
+#ifdef __cplusplus
+ }
+#endif
+
+
+typedef struct {
+ qboolean frameMemory;
+ int currentElements;
+ int maxElements; // will reallocate and move when exceeded
+ void **elements;
+} growList_t;
+
+// you don't need to init the growlist if you don't mind it growing and moving
+// the list as it expands
+void Com_InitGrowList( growList_t *list, int maxElements );
+int Com_AddToGrowList( growList_t *list, void *data );
+void *Com_GrowListElement( const growList_t *list, int index );
+int Com_IndexForGrowListElement( const growList_t *list, const void *element );
+
+
+//
+// key / value info strings
+//
+char *Info_ValueForKey( const char *s, const char *key );
+void Info_RemoveKey( char *s, const char *key );
+void Info_SetValueForKey( char *s, const char *key, const char *value );
+qboolean Info_Validate( const char *s );
+void Info_NextPair( const char *(*s), char key[MAX_INFO_KEY], char value[MAX_INFO_VALUE] );
+
+// get cvar defs, collision defs, etc
+//#include "../shared/interface.h"
+
+// get key code numbers for events
+//#include "../shared/keycodes.h"
+
+#ifdef __cplusplus
+// get the polygon winding functions
+//#include "../shared/windings.h"
+
+// get the flags class
+//#include "../shared/idflags.h"
+#endif // __cplusplus
+
+#endif // __Q_SHARED_H
+
diff --git a/code/splines/splines.cpp b/code/splines/splines.cpp
new file mode 100755
index 0000000..61830fe
--- /dev/null
+++ b/code/splines/splines.cpp
@@ -0,0 +1,1250 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+//#include "stdafx.h"
+//#include "qe3.h"
+
+#include "q_shared.hpp"
+#include "splines.h"
+
+extern "C" {
+int FS_Write( const void *buffer, int len, fileHandle_t h );
+int FS_ReadFile( const char *qpath, void **buffer );
+void FS_FreeFile( void *buffer );
+fileHandle_t FS_FOpenFileWrite( const char *filename );
+void FS_FCloseFile( fileHandle_t f );
+}
+
+float Q_fabs( float f ) {
+ int tmp = * ( int * ) &f;
+ tmp &= 0x7FFFFFFF;
+ return * ( float * ) &tmp;
+}
+
+
+//#include "../shared/windings.h"
+//#include "../qcommon/qcommon.h"
+//#include "../sys/sys_public.h"
+//#include "../game/game_entity.h"
+
+idCameraDef splineList;
+idCameraDef *g_splineList = &splineList;
+
+idVec3_t idSplineList::zero(0,0,0);
+/*
+void glLabeledPoint(idVec3_t &color, idVec3_t &point, float size, const char *label) {
+ qglColor3fv(color);
+ qglPointSize(size);
+ qglBegin(GL_POINTS);
+ qglVertex3fv(point);
+ qglEnd();
+ idVec3_t v = point;
+ v.x += 1;
+ v.y += 1;
+ v.z += 1;
+ qglRasterPos3fv (v);
+ qglCallLists (strlen(label), GL_UNSIGNED_BYTE, label);
+}
+
+
+void glBox(idVec3_t &color, idVec3_t &point, float size) {
+ idVec3_t mins(point);
+ idVec3_t maxs(point);
+ mins[0] -= size;
+ mins[1] += size;
+ mins[2] -= size;
+ maxs[0] += size;
+ maxs[1] -= size;
+ maxs[2] += size;
+ qglColor3fv(color);
+ qglBegin(GL_LINE_LOOP);
+ qglVertex3f(mins[0],mins[1],mins[2]);
+ qglVertex3f(maxs[0],mins[1],mins[2]);
+ qglVertex3f(maxs[0],maxs[1],mins[2]);
+ qglVertex3f(mins[0],maxs[1],mins[2]);
+ qglEnd();
+ qglBegin(GL_LINE_LOOP);
+ qglVertex3f(mins[0],mins[1],maxs[2]);
+ qglVertex3f(maxs[0],mins[1],maxs[2]);
+ qglVertex3f(maxs[0],maxs[1],maxs[2]);
+ qglVertex3f(mins[0],maxs[1],maxs[2]);
+ qglEnd();
+
+ qglBegin(GL_LINES);
+ qglVertex3f(mins[0],mins[1],mins[2]);
+ qglVertex3f(mins[0],mins[1],maxs[2]);
+ qglVertex3f(mins[0],maxs[1],maxs[2]);
+ qglVertex3f(mins[0],maxs[1],mins[2]);
+ qglVertex3f(maxs[0],mins[1],mins[2]);
+ qglVertex3f(maxs[0],mins[1],maxs[2]);
+ qglVertex3f(maxs[0],maxs[1],maxs[2]);
+ qglVertex3f(maxs[0],maxs[1],mins[2]);
+ qglEnd();
+
+}
+
+void splineTest() {
+ //g_splineList->load("p:/doom/base/maps/test_base1.camera");
+}
+
+void splineDraw() {
+ //g_splineList->addToRenderer();
+}
+
+
+//extern void D_DebugLine( const idVec3_t &color, const idVec3_t &start, const idVec3_t &end );
+
+void debugLine(idVec3_t &color, float x, float y, float z, float x2, float y2, float z2) {
+ //idVec3_t from(x, y, z);
+ //idVec3_t to(x2, y2, z2);
+ //D_DebugLine(color, from, to);
+}
+
+
+void idSplineList::addToRenderer() {
+
+ if (controlPoints.Num() == 0) {
+ return;
+ }
+
+ idVec3_t mins, maxs;
+ idVec3_t yellow(1.0, 1.0, 0);
+ idVec3_t white(1.0, 1.0, 1.0);
+ int i;
+
+ for(i = 0; i < controlPoints.Num(); i++) {
+ VectorCopy(*controlPoints[i], mins);
+ VectorCopy(mins, maxs);
+ mins[0] -= 8;
+ mins[1] += 8;
+ mins[2] -= 8;
+ maxs[0] += 8;
+ maxs[1] -= 8;
+ maxs[2] += 8;
+ debugLine( yellow, mins[0], mins[1], mins[2], maxs[0], mins[1], mins[2]);
+ debugLine( yellow, maxs[0], mins[1], mins[2], maxs[0], maxs[1], mins[2]);
+ debugLine( yellow, maxs[0], maxs[1], mins[2], mins[0], maxs[1], mins[2]);
+ debugLine( yellow, mins[0], maxs[1], mins[2], mins[0], mins[1], mins[2]);
+
+ debugLine( yellow, mins[0], mins[1], maxs[2], maxs[0], mins[1], maxs[2]);
+ debugLine( yellow, maxs[0], mins[1], maxs[2], maxs[0], maxs[1], maxs[2]);
+ debugLine( yellow, maxs[0], maxs[1], maxs[2], mins[0], maxs[1], maxs[2]);
+ debugLine( yellow, mins[0], maxs[1], maxs[2], mins[0], mins[1], maxs[2]);
+
+ }
+
+ int step = 0;
+ idVec3_t step1;
+ for(i = 3; i < controlPoints.Num(); i++) {
+ for (float tension = 0.0f; tension < 1.001f; tension += 0.1f) {
+ float x = 0;
+ float y = 0;
+ float z = 0;
+ for (int j = 0; j < 4; j++) {
+ x += controlPoints[i - (3 - j)]->x * calcSpline(j, tension);
+ y += controlPoints[i - (3 - j)]->y * calcSpline(j, tension);
+ z += controlPoints[i - (3 - j)]->z * calcSpline(j, tension);
+ }
+ if (step == 0) {
+ step1[0] = x;
+ step1[1] = y;
+ step1[2] = z;
+ step = 1;
+ } else {
+ debugLine( white, step1[0], step1[1], step1[2], x, y, z);
+ step = 0;
+ }
+
+ }
+ }
+}
+*/
+
+void idSplineList::buildSpline() {
+ //int start = Sys_Milliseconds();
+ clearSpline();
+ for(int i = 3; i < controlPoints.Num(); i++) {
+ for (float tension = 0.0f; tension < 1.001f; tension += granularity) {
+ float x = 0;
+ float y = 0;
+ float z = 0;
+ for (int j = 0; j < 4; j++) {
+ x += controlPoints[i - (3 - j)]->x * calcSpline(j, tension);
+ y += controlPoints[i - (3 - j)]->y * calcSpline(j, tension);
+ z += controlPoints[i - (3 - j)]->z * calcSpline(j, tension);
+ }
+ splinePoints.Append(new idVec3_t(x, y, z));
+ }
+ }
+ dirty = false;
+ //Com_Printf("Spline build took %f seconds\n", (float)(Sys_Milliseconds() - start) / 1000);
+}
+
+/*
+void idSplineList::draw(bool editMode) {
+ int i;
+ vec4_t yellow(1, 1, 0, 1);
+
+ if (controlPoints.Num() == 0) {
+ return;
+ }
+
+ if (dirty) {
+ buildSpline();
+ }
+
+
+ qglColor3fv(controlColor);
+ qglPointSize(5);
+
+ qglBegin(GL_POINTS);
+ for (i = 0; i < controlPoints.Num(); i++) {
+ qglVertex3fv(*controlPoints[i]);
+ }
+ qglEnd();
+
+ if (editMode) {
+ for(i = 0; i < controlPoints.Num(); i++) {
+ glBox(activeColor, *controlPoints[i], 4);
+ }
+ }
+
+ //Draw the curve
+ qglColor3fv(pathColor);
+ qglBegin(GL_LINE_STRIP);
+ int count = splinePoints.Num();
+ for (i = 0; i < count; i++) {
+ qglVertex3fv(*splinePoints[i]);
+ }
+ qglEnd();
+
+ if (editMode) {
+ qglColor3fv(segmentColor);
+ qglPointSize(3);
+ qglBegin(GL_POINTS);
+ for (i = 0; i < count; i++) {
+ qglVertex3fv(*splinePoints[i]);
+ }
+ qglEnd();
+ }
+ if (count > 0) {
+ //assert(activeSegment >=0 && activeSegment < count);
+ if (activeSegment >=0 && activeSegment < count) {
+ glBox(activeColor, *splinePoints[activeSegment], 6);
+ glBox(yellow, *splinePoints[activeSegment], 8);
+ }
+ }
+
+}
+*/
+
+float idSplineList::totalDistance() {
+
+ if (controlPoints.Num() == 0) {
+ return 0.0;
+ }
+
+ if (dirty) {
+ buildSpline();
+ }
+
+ float dist = 0.0;
+ idVec3_t temp;
+ int count = splinePoints.Num();
+ for(int i = 1; i < count; i++) {
+ temp = *splinePoints[i-1];
+ temp -= *splinePoints[i];
+ dist += temp.Length();
+ }
+ return dist;
+}
+
+void idSplineList::initPosition(long bt, long totalTime) {
+
+ if (dirty) {
+ buildSpline();
+ }
+
+ if (splinePoints.Num() == 0) {
+ return;
+ }
+
+ baseTime = bt;
+ time = totalTime;
+
+ // calc distance to travel ( this will soon be broken into time segments )
+ splineTime.Clear();
+ splineTime.Append(bt);
+ double dist = totalDistance();
+ double distSoFar = 0.0;
+ idVec3_t temp;
+ int count = splinePoints.Num();
+ //for(int i = 2; i < count - 1; i++) {
+ for(int i = 1; i < count; i++) {
+ temp = *splinePoints[i-1];
+ temp -= *splinePoints[i];
+ distSoFar += temp.Length();
+ double percent = distSoFar / dist;
+ percent *= totalTime;
+ splineTime.Append(percent + bt);
+ }
+ assert(splineTime.Num() == splinePoints.Num());
+ activeSegment = 0;
+}
+
+
+
+float idSplineList::calcSpline(int step, float tension) {
+ switch(step) {
+ case 0: return (pow(1 - tension, 3)) / 6;
+ case 1: return (3 * pow(tension, 3) - 6 * pow(tension, 2) + 4) / 6;
+ case 2: return (-3 * pow(tension, 3) + 3 * pow(tension, 2) + 3 * tension + 1) / 6;
+ case 3: return pow(tension, 3) / 6;
+ }
+ return 0.0;
+}
+
+
+
+void idSplineList::updateSelection(const idVec3_t &move) {
+ if (selected) {
+ dirty = true;
+ VectorAdd(*selected, move, *selected);
+ }
+}
+
+
+void idSplineList::setSelectedPoint(idVec3_t *p) {
+ if (p) {
+ p->Snap();
+ for(int i = 0; i < controlPoints.Num(); i++) {
+ if (*p == *controlPoints[i]) {
+ selected = controlPoints[i];
+ }
+ }
+ } else {
+ selected = NULL;
+ }
+}
+
+const idVec3_t *idSplineList::getPosition(long t) {
+ static idVec3_t interpolatedPos;
+ //static long lastTime = -1;
+
+ int count = splineTime.Num();
+ if (count == 0) {
+ return &zero;
+ }
+
+ Com_Printf("Time: %d\n", t);
+ assert(splineTime.Num() == splinePoints.Num());
+
+ while (activeSegment < count) {
+ if (splineTime[activeSegment] >= t) {
+ if (activeSegment > 0 && activeSegment < count - 1) {
+ double timeHi = splineTime[activeSegment + 1];
+ double timeLo = splineTime[activeSegment - 1];
+ double percent = (timeHi - t) / (timeHi - timeLo);
+ // pick two bounding points
+ idVec3_t v1 = *splinePoints[activeSegment-1];
+ idVec3_t v2 = *splinePoints[activeSegment+1];
+ v2 *= (1.0 - percent);
+ v1 *= percent;
+ v2 += v1;
+ interpolatedPos = v2;
+ return &interpolatedPos;
+ }
+ return splinePoints[activeSegment];
+ } else {
+ activeSegment++;
+ }
+ }
+ return splinePoints[count-1];
+}
+
+void idSplineList::parse(const char *(*text) ) {
+ const char *token;
+ //Com_MatchToken( text, "{" );
+ do {
+ token = Com_Parse( text );
+
+ if ( !token[0] ) {
+ break;
+ }
+ if ( !Q_stricmp (token, "}") ) {
+ break;
+ }
+
+ do {
+ // if token is not a brace, it is a key for a key/value pair
+ if ( !token[0] || !Q_stricmp (token, "(") || !Q_stricmp(token, "}")) {
+ break;
+ }
+
+ Com_UngetToken();
+ idStr key = Com_ParseOnLine(text);
+ const char *token = Com_Parse(text);
+ if (Q_stricmp(key.c_str(), "granularity") == 0) {
+ granularity = atof(token);
+ } else if (Q_stricmp(key.c_str(), "name") == 0) {
+ name = token;
+ }
+ token = Com_Parse(text);
+
+ } while (1);
+
+ if ( !Q_stricmp (token, "}") ) {
+ break;
+ }
+
+ Com_UngetToken();
+ // read the control point
+ idVec3_t point;
+ Com_Parse1DMatrix( text, 3, point );
+ addPoint(point.x, point.y, point.z);
+ } while (1);
+
+ //Com_UngetToken();
+ //Com_MatchToken( text, "}" );
+ dirty = true;
+}
+
+void idSplineList::write(fileHandle_t file, const char *p) {
+ idStr s = va("\t\t%s {\n", p);
+ FS_Write(s.c_str(), s.length(), file);
+ //s = va("\t\tname %s\n", name.c_str());
+ //FS_Write(s.c_str(), s.length(), file);
+ s = va("\t\t\tgranularity %f\n", granularity);
+ FS_Write(s.c_str(), s.length(), file);
+ int count = controlPoints.Num();
+ for (int i = 0; i < count; i++) {
+ s = va("\t\t\t( %f %f %f )\n", controlPoints[i]->x, controlPoints[i]->y, controlPoints[i]->z);
+ FS_Write(s.c_str(), s.length(), file);
+ }
+ s = "\t\t}\n";
+ FS_Write(s.c_str(), s.length(), file);
+}
+
+
+void idCameraDef::getActiveSegmentInfo(int segment, idVec3_t &origin, idVec3_t &direction, float *fov) {
+#if 0
+ if (!cameraSpline.validTime()) {
+ buildCamera();
+ }
+ double d = (double)segment / numSegments();
+ getCameraInfo(d * totalTime * 1000, origin, direction, fov);
+#endif
+/*
+ if (!cameraSpline.validTime()) {
+ buildCamera();
+ }
+ origin = *cameraSpline.getSegmentPoint(segment);
+
+
+ idVec3_t temp;
+
+ int numTargets = getTargetSpline()->controlPoints.Num();
+ int count = cameraSpline.splineTime.Num();
+ if (numTargets == 0) {
+ // follow the path
+ if (cameraSpline.getActiveSegment() < count - 1) {
+ temp = *cameraSpline.splinePoints[cameraSpline.getActiveSegment()+1];
+ }
+ } else if (numTargets == 1) {
+ temp = *getTargetSpline()->controlPoints[0];
+ } else {
+ temp = *getTargetSpline()->getSegmentPoint(segment);
+ }
+
+ temp -= origin;
+ temp.Normalize();
+ direction = temp;
+*/
+}
+
+bool idCameraDef::getCameraInfo(long time, idVec3_t &origin, idVec3_t &direction, float *fv) {
+
+
+ if ((time - startTime) / 1000 > totalTime) {
+ return false;
+ }
+
+
+ for (int i = 0; i < events.Num(); i++) {
+ if (time >= startTime + events[i]->getTime() && !events[i]->getTriggered()) {
+ events[i]->setTriggered(true);
+ if (events[i]->getType() == idCameraEvent::EVENT_TARGET) {
+ setActiveTargetByName(events[i]->getParam());
+ getActiveTarget()->start(startTime + events[i]->getTime());
+ //Com_Printf("Triggered event switch to target: %s\n",events[i]->getParam());
+ } else if (events[i]->getType() == idCameraEvent::EVENT_TRIGGER) {
+ //idEntity *ent = NULL;
+ //ent = level.FindTarget( ent, events[i]->getParam());
+ //if (ent) {
+ // ent->signal( SIG_TRIGGER );
+ // ent->ProcessEvent( &EV_Activate, world );
+ //}
+ } else if (events[i]->getType() == idCameraEvent::EVENT_FOV) {
+ //*fv = fov = atof(events[i]->getParam());
+ } else if (events[i]->getType() == idCameraEvent::EVENT_STOP) {
+ return false;
+ }
+ }
+ }
+
+ origin = *cameraPosition->getPosition(time);
+
+ *fv = fov.getFOV(time);
+
+ idVec3_t temp = origin;
+
+ int numTargets = targetPositions.Num();
+ if (numTargets == 0) {
+/*
+ // follow the path
+ if (cameraSpline.getActiveSegment() < count - 1) {
+ temp = *cameraSpline.splinePoints[cameraSpline.getActiveSegment()+1];
+ if (temp == origin) {
+ int index = cameraSpline.getActiveSegment() + 2;
+ while (temp == origin && index < count - 1) {
+ temp = *cameraSpline.splinePoints[index++];
+ }
+ }
+ }
+*/
+ } else {
+ temp = *getActiveTarget()->getPosition(time);
+ }
+
+ temp -= origin;
+ temp.Normalize();
+ direction = temp;
+
+ return true;
+}
+
+bool idCameraDef::waitEvent(int index) {
+ //for (int i = 0; i < events.Num(); i++) {
+ // if (events[i]->getSegment() == index && events[i]->getType() == idCameraEvent::EVENT_WAIT) {
+ // return true;
+ // }
+ //}
+ return false;
+}
+
+
+#define NUM_CCELERATION_SEGS 10
+#define CELL_AMT 5
+
+void idCameraDef::buildCamera() {
+ int i;
+ //int lastSwitch = 0;
+ idList<float> waits;
+ idList<int> targets;
+
+ totalTime = baseTime;
+ cameraPosition->setTime(totalTime * 1000);
+ // we have a base time layout for the path and the target path
+ // now we need to layer on any wait or speed changes
+ for (i = 0; i < events.Num(); i++) {
+ //idCameraEvent *ev = events[i];
+ events[i]->setTriggered(false);
+ switch (events[i]->getType()) {
+ case idCameraEvent::EVENT_TARGET : {
+ targets.Append(i);
+ break;
+ }
+ case idCameraEvent::EVENT_WAIT : {
+ waits.Append(atof(events[i]->getParam()));
+ cameraPosition->addVelocity(events[i]->getTime(), atof(events[i]->getParam()) * 1000, 0);
+ break;
+ }
+ case idCameraEvent::EVENT_TARGETWAIT : {
+ //targetWaits.Append(i);
+ break;
+ }
+ case idCameraEvent::EVENT_SPEED : {
+/*
+ // take the average delay between up to the next five segments
+ float adjust = atof(events[i]->getParam());
+ int index = events[i]->getSegment();
+ total = 0;
+ count = 0;
+
+ // get total amount of time over the remainder of the segment
+ for (j = index; j < cameraSpline.numSegments() - 1; j++) {
+ total += cameraSpline.getSegmentTime(j + 1) - cameraSpline.getSegmentTime(j);
+ count++;
+ }
+
+ // multiply that by the adjustment
+ double newTotal = total * adjust;
+ // what is the difference..
+ newTotal -= total;
+ totalTime += newTotal / 1000;
+
+ // per segment difference
+ newTotal /= count;
+ int additive = newTotal;
+
+ // now propogate that difference out to each segment
+ for (j = index; j < cameraSpline.numSegments(); j++) {
+ cameraSpline.addSegmentTime(j, additive);
+ additive += newTotal;
+ }
+ break;
+*/
+ }
+ default: break; // FIXME: what about other idCameraEvent?
+ }
+ }
+
+
+ for (i = 0; i < waits.Num(); i++) {
+ totalTime += waits[i];
+ }
+
+ // on a new target switch, we need to take time to this point ( since last target switch )
+ // and allocate it across the active target, then reset time to this point
+ long timeSoFar = 0;
+ long total = (int)(totalTime * 1000);
+ for (i = 0; i < targets.Num(); i++) {
+ long t;
+ if (i < targets.Num() - 1) {
+ t = events[targets[i+1]]->getTime();
+ } else {
+ t = total - timeSoFar;
+ }
+ // t is how much time to use for this target
+ setActiveTargetByName(events[targets[i]]->getParam());
+ getActiveTarget()->setTime(t);
+ timeSoFar += t;
+ }
+
+
+}
+
+void idCameraDef::startCamera(long t) {
+ buildCamera();
+ cameraPosition->start(t);
+ //for (int i = 0; i < targetPositions.Num(); i++) {
+ // targetPositions[i]->
+ //}
+ startTime = t;
+ cameraRunning = true;
+}
+
+
+void idCameraDef::parse(const char *(*text) ) {
+
+ const char *token;
+ do {
+ token = Com_Parse( text );
+
+ if ( !token[0] ) {
+ break;
+ }
+ if ( !Q_stricmp (token, "}") ) {
+ break;
+ }
+
+ if (Q_stricmp(token, "time") == 0) {
+ baseTime = Com_ParseFloat(text);
+ }
+
+ if (Q_stricmp(token, "camera_fixed") == 0) {
+ cameraPosition = new idFixedPosition();
+ cameraPosition->parse(text);
+ }
+
+ if (Q_stricmp(token, "camera_interpolated") == 0) {
+ cameraPosition = new idInterpolatedPosition();
+ cameraPosition->parse(text);
+ }
+
+ if (Q_stricmp(token, "camera_spline") == 0) {
+ cameraPosition = new idSplinePosition();
+ cameraPosition->parse(text);
+ }
+
+ if (Q_stricmp(token, "target_fixed") == 0) {
+ idFixedPosition *pos = new idFixedPosition();
+ pos->parse(text);
+ targetPositions.Append(pos);
+ }
+
+ if (Q_stricmp(token, "target_interpolated") == 0) {
+ idInterpolatedPosition *pos = new idInterpolatedPosition();
+ pos->parse(text);
+ targetPositions.Append(pos);
+ }
+
+ if (Q_stricmp(token, "target_spline") == 0) {
+ idSplinePosition *pos = new idSplinePosition();
+ pos->parse(text);
+ targetPositions.Append(pos);
+ }
+
+ if (Q_stricmp(token, "fov") == 0) {
+ fov.parse(text);
+ }
+
+ if (Q_stricmp(token, "event") == 0) {
+ idCameraEvent *event = new idCameraEvent();
+ event->parse(text);
+ addEvent(event);
+ }
+
+
+ } while (1);
+
+ Com_UngetToken();
+ Com_MatchToken( text, "}" );
+
+}
+
+qboolean idCameraDef::load(const char *filename) {
+ char *buf;
+ const char *buf_p;
+ //int length =
+ FS_ReadFile( filename, (void **)&buf );
+ if ( !buf ) {
+ return qfalse;
+ }
+
+ clear();
+ Com_BeginParseSession( filename );
+ buf_p = buf;
+ parse(&buf_p);
+ Com_EndParseSession();
+ FS_FreeFile( buf );
+
+ return qtrue;
+}
+
+void idCameraDef::save(const char *filename) {
+ fileHandle_t file = FS_FOpenFileWrite(filename);
+ if (file) {
+ int i;
+ idStr s = "cameraPathDef { \n";
+ FS_Write(s.c_str(), s.length(), file);
+ s = va("\ttime %f\n", baseTime);
+ FS_Write(s.c_str(), s.length(), file);
+
+ cameraPosition->write(file, va("camera_%s",cameraPosition->typeStr()));
+
+ for (i = 0; i < numTargets(); i++) {
+ targetPositions[i]->write(file, va("target_%s", targetPositions[i]->typeStr()));
+ }
+
+ for (i = 0; i < events.Num(); i++) {
+ events[i]->write(file, "event");
+ }
+
+ fov.write(file, "fov");
+
+ s = "}\n";
+ FS_Write(s.c_str(), s.length(), file);
+ }
+ FS_FCloseFile(file);
+}
+
+int idCameraDef::sortEvents(const void *p1, const void *p2) {
+ idCameraEvent *ev1 = (idCameraEvent*)(p1);
+ idCameraEvent *ev2 = (idCameraEvent*)(p2);
+
+ if (ev1->getTime() > ev2->getTime()) {
+ return -1;
+ }
+ if (ev1->getTime() < ev2->getTime()) {
+ return 1;
+ }
+ return 0;
+}
+
+void idCameraDef::addEvent(idCameraEvent *event) {
+ events.Append(event);
+ //events.Sort(&sortEvents);
+
+}
+void idCameraDef::addEvent(idCameraEvent::eventType t, const char *param, long time) {
+ addEvent(new idCameraEvent(t, param, time));
+ buildCamera();
+}
+
+
+const char *idCameraEvent::eventStr[] = {
+ "NA",
+ "WAIT",
+ "TARGETWAIT",
+ "SPEED",
+ "TARGET",
+ "SNAPTARGET",
+ "FOV",
+ "SCRIPT",
+ "TRIGGER",
+ "STOP"
+};
+
+void idCameraEvent::parse(const char *(*text) ) {
+ const char *token;
+ Com_MatchToken( text, "{" );
+ do {
+ token = Com_Parse( text );
+
+ if ( !token[0] ) {
+ break;
+ }
+ if ( !strcmp (token, "}") ) {
+ break;
+ }
+
+ // here we may have to jump over brush epairs ( only used in editor )
+ do {
+ // if token is not a brace, it is a key for a key/value pair
+ if ( !token[0] || !strcmp (token, "(") || !strcmp(token, "}")) {
+ break;
+ }
+
+ Com_UngetToken();
+ idStr key = Com_ParseOnLine(text);
+ const char *token = Com_Parse(text);
+ if (Q_stricmp(key.c_str(), "type") == 0) {
+ type = static_cast<idCameraEvent::eventType>(atoi(token));
+ } else if (Q_stricmp(key.c_str(), "param") == 0) {
+ paramStr = token;
+ } else if (Q_stricmp(key.c_str(), "time") == 0) {
+ time = atoi(token);
+ }
+ token = Com_Parse(text);
+
+ } while (1);
+
+ if ( !strcmp (token, "}") ) {
+ break;
+ }
+
+ } while (1);
+
+ Com_UngetToken();
+ Com_MatchToken( text, "}" );
+}
+
+void idCameraEvent::write(fileHandle_t file, const char *name) {
+ idStr s = va("\t%s {\n", name);
+ FS_Write(s.c_str(), s.length(), file);
+ s = va("\t\ttype %d\n", static_cast<int>(type));
+ FS_Write(s.c_str(), s.length(), file);
+ s = va("\t\tparam %s\n", paramStr.c_str());
+ FS_Write(s.c_str(), s.length(), file);
+ s = va("\t\ttime %d\n", time);
+ FS_Write(s.c_str(), s.length(), file);
+ s = "\t}\n";
+ FS_Write(s.c_str(), s.length(), file);
+}
+
+
+const char *idCameraPosition::positionStr[] = {
+ "Fixed",
+ "Interpolated",
+ "Spline",
+};
+
+
+
+const idVec3_t *idInterpolatedPosition::getPosition(long t) {
+ static idVec3_t interpolatedPos;
+
+ float velocity = getVelocity(t);
+ float timePassed = t - lastTime;
+ lastTime = t;
+
+ // convert to seconds
+ timePassed /= 1000;
+
+ float distToTravel = timePassed *= velocity;
+
+ idVec3_t temp = startPos;
+ temp -= endPos;
+ float distance = temp.Length();
+
+ distSoFar += distToTravel;
+ float percent = (float)(distSoFar) / distance;
+
+ if (percent > 1.0) {
+ percent = 1.0;
+ } else if (percent < 0.0) {
+ percent = 0.0;
+ }
+
+ // the following line does a straigt calc on percentage of time
+ // float percent = (float)(startTime + time - t) / time;
+
+ idVec3_t v1 = startPos;
+ idVec3_t v2 = endPos;
+ v1 *= (1.0 - percent);
+ v2 *= percent;
+ v1 += v2;
+ interpolatedPos = v1;
+ return &interpolatedPos;
+}
+
+
+void idCameraFOV::parse(const char *(*text) ) {
+ const char *token;
+ Com_MatchToken( text, "{" );
+ do {
+ token = Com_Parse( text );
+
+ if ( !token[0] ) {
+ break;
+ }
+ if ( !strcmp (token, "}") ) {
+ break;
+ }
+
+ // here we may have to jump over brush epairs ( only used in editor )
+ do {
+ // if token is not a brace, it is a key for a key/value pair
+ if ( !token[0] || !strcmp (token, "(") || !strcmp(token, "}")) {
+ break;
+ }
+
+ Com_UngetToken();
+ idStr key = Com_ParseOnLine(text);
+ const char *token = Com_Parse(text);
+ if (Q_stricmp(key.c_str(), "fov") == 0) {
+ fov = atof(token);
+ } else if (Q_stricmp(key.c_str(), "startFOV") == 0) {
+ startFOV = atof(token);
+ } else if (Q_stricmp(key.c_str(), "endFOV") == 0) {
+ endFOV = atof(token);
+ } else if (Q_stricmp(key.c_str(), "time") == 0) {
+ time = atoi(token);
+ }
+ token = Com_Parse(text);
+
+ } while (1);
+
+ if ( !strcmp (token, "}") ) {
+ break;
+ }
+
+ } while (1);
+
+ Com_UngetToken();
+ Com_MatchToken( text, "}" );
+}
+
+bool idCameraPosition::parseToken(const char *key, const char *(*text)) {
+ const char *token = Com_Parse(text);
+ if (Q_stricmp(key, "time") == 0) {
+ time = atol(token);
+ return true;
+ } else if (Q_stricmp(key, "type") == 0) {
+ type = static_cast<idCameraPosition::positionType>(atoi(token));
+ return true;
+ } else if (Q_stricmp(key, "velocity") == 0) {
+ long t = atol(token);
+ token = Com_Parse(text);
+ long d = atol(token);
+ token = Com_Parse(text);
+ float s = atof(token);
+ addVelocity(t, d, s);
+ return true;
+ } else if (Q_stricmp(key, "baseVelocity") == 0) {
+ baseVelocity = atof(token);
+ return true;
+ } else if (Q_stricmp(key, "name") == 0) {
+ name = token;
+ return true;
+ } else if (Q_stricmp(key, "time") == 0) {
+ time = atoi(token);
+ return true;
+ }
+ Com_UngetToken();
+ return false;
+}
+
+
+
+void idFixedPosition::parse(const char *(*text) ) {
+ const char *token;
+ Com_MatchToken( text, "{" );
+ do {
+ token = Com_Parse( text );
+
+ if ( !token[0] ) {
+ break;
+ }
+ if ( !strcmp (token, "}") ) {
+ break;
+ }
+
+ // here we may have to jump over brush epairs ( only used in editor )
+ do {
+ // if token is not a brace, it is a key for a key/value pair
+ if ( !token[0] || !strcmp (token, "(") || !strcmp(token, "}")) {
+ break;
+ }
+
+ Com_UngetToken();
+ idStr key = Com_ParseOnLine(text);
+
+ const char *token = Com_Parse(text);
+ if (Q_stricmp(key.c_str(), "pos") == 0) {
+ Com_UngetToken();
+ Com_Parse1DMatrix( text, 3, pos );
+ } else {
+ Com_UngetToken();
+ idCameraPosition::parseToken(key.c_str(), text);
+ }
+ token = Com_Parse(text);
+
+ } while (1);
+
+ if ( !strcmp (token, "}") ) {
+ break;
+ }
+
+ } while (1);
+
+ Com_UngetToken();
+ Com_MatchToken( text, "}" );
+}
+
+void idInterpolatedPosition::parse(const char *(*text) ) {
+ const char *token;
+ Com_MatchToken( text, "{" );
+ do {
+ token = Com_Parse( text );
+
+ if ( !token[0] ) {
+ break;
+ }
+ if ( !strcmp (token, "}") ) {
+ break;
+ }
+
+ // here we may have to jump over brush epairs ( only used in editor )
+ do {
+ // if token is not a brace, it is a key for a key/value pair
+ if ( !token[0] || !strcmp (token, "(") || !strcmp(token, "}")) {
+ break;
+ }
+
+ Com_UngetToken();
+ idStr key = Com_ParseOnLine(text);
+
+ const char *token = Com_Parse(text);
+ if (Q_stricmp(key.c_str(), "startPos") == 0) {
+ Com_UngetToken();
+ Com_Parse1DMatrix( text, 3, startPos );
+ } else if (Q_stricmp(key.c_str(), "endPos") == 0) {
+ Com_UngetToken();
+ Com_Parse1DMatrix( text, 3, endPos );
+ } else {
+ Com_UngetToken();
+ idCameraPosition::parseToken(key.c_str(), text);
+ }
+ token = Com_Parse(text);
+
+ } while (1);
+
+ if ( !strcmp (token, "}") ) {
+ break;
+ }
+
+ } while (1);
+
+ Com_UngetToken();
+ Com_MatchToken( text, "}" );
+}
+
+
+void idSplinePosition::parse(const char *(*text) ) {
+ const char *token;
+ Com_MatchToken( text, "{" );
+ do {
+ token = Com_Parse( text );
+
+ if ( !token[0] ) {
+ break;
+ }
+ if ( !strcmp (token, "}") ) {
+ break;
+ }
+
+ // here we may have to jump over brush epairs ( only used in editor )
+ do {
+ // if token is not a brace, it is a key for a key/value pair
+ if ( !token[0] || !strcmp (token, "(") || !strcmp(token, "}")) {
+ break;
+ }
+
+ Com_UngetToken();
+ idStr key = Com_ParseOnLine(text);
+
+ const char *token = Com_Parse(text);
+ if (Q_stricmp(key.c_str(), "target") == 0) {
+ target.parse(text);
+ } else {
+ Com_UngetToken();
+ idCameraPosition::parseToken(key.c_str(), text);
+ }
+ token = Com_Parse(text);
+
+ } while (1);
+
+ if ( !strcmp (token, "}") ) {
+ break;
+ }
+
+ } while (1);
+
+ Com_UngetToken();
+ Com_MatchToken( text, "}" );
+}
+
+
+
+void idCameraFOV::write(fileHandle_t file, const char *p) {
+ idStr s = va("\t%s {\n", p);
+ FS_Write(s.c_str(), s.length(), file);
+
+ s = va("\t\tfov %f\n", fov);
+ FS_Write(s.c_str(), s.length(), file);
+
+ s = va("\t\tstartFOV %f\n", startFOV);
+ FS_Write(s.c_str(), s.length(), file);
+
+ s = va("\t\tendFOV %f\n", endFOV);
+ FS_Write(s.c_str(), s.length(), file);
+
+ s = va("\t\ttime %i\n", time);
+ FS_Write(s.c_str(), s.length(), file);
+
+ s = "\t}\n";
+ FS_Write(s.c_str(), s.length(), file);
+}
+
+
+void idCameraPosition::write(fileHandle_t file, const char *p) {
+
+ idStr s = va("\t\ttime %i\n", time);
+ FS_Write(s.c_str(), s.length(), file);
+
+ s = va("\t\ttype %i\n", static_cast<int>(type));
+ FS_Write(s.c_str(), s.length(), file);
+
+ s = va("\t\tname %s\n", name.c_str());
+ FS_Write(s.c_str(), s.length(), file);
+
+ s = va("\t\tbaseVelocity %f\n", baseVelocity);
+ FS_Write(s.c_str(), s.length(), file);
+
+ for (int i = 0; i < velocities.Num(); i++) {
+ s = va("\t\tvelocity %i %i %f\n", velocities[i]->startTime, velocities[i]->time, velocities[i]->speed);
+ FS_Write(s.c_str(), s.length(), file);
+ }
+
+}
+
+void idFixedPosition::write(fileHandle_t file, const char *p) {
+ idStr s = va("\t%s {\n", p);
+ FS_Write(s.c_str(), s.length(), file);
+ idCameraPosition::write(file, p);
+ s = va("\t\tpos ( %f %f %f )\n", pos.x, pos.y, pos.z);
+ FS_Write(s.c_str(), s.length(), file);
+ s = "\t}\n";
+ FS_Write(s.c_str(), s.length(), file);
+}
+
+void idInterpolatedPosition::write(fileHandle_t file, const char *p) {
+ idStr s = va("\t%s {\n", p);
+ FS_Write(s.c_str(), s.length(), file);
+ idCameraPosition::write(file, p);
+ s = va("\t\tstartPos ( %f %f %f )\n", startPos.x, startPos.y, startPos.z);
+ FS_Write(s.c_str(), s.length(), file);
+ s = va("\t\tendPos ( %f %f %f )\n", endPos.x, endPos.y, endPos.z);
+ FS_Write(s.c_str(), s.length(), file);
+ s = "\t}\n";
+ FS_Write(s.c_str(), s.length(), file);
+}
+
+void idSplinePosition::write(fileHandle_t file, const char *p) {
+ idStr s = va("\t%s {\n", p);
+ FS_Write(s.c_str(), s.length(), file);
+ idCameraPosition::write(file, p);
+ target.write(file, "target");
+ s = "\t}\n";
+ FS_Write(s.c_str(), s.length(), file);
+}
+
+void idCameraDef::addTarget(const char *name, idCameraPosition::positionType type) {
+ //const char *text = (name == NULL) ? va("target0%d", numTargets()+1) : name; // TTimo: unused
+ idCameraPosition *pos = newFromType(type);
+ if (pos) {
+ pos->setName(name);
+ targetPositions.Append(pos);
+ activeTarget = numTargets()-1;
+ if (activeTarget == 0) {
+ // first one
+ addEvent(idCameraEvent::EVENT_TARGET, name, 0);
+ }
+ }
+}
+
+
+
+idCameraDef camera;
+
+extern "C" {
+qboolean loadCamera(const char *name) {
+ camera.clear();
+ return static_cast<qboolean>(camera.load(name));
+}
+
+qboolean getCameraInfo(int time, float *origin, float*angles) {
+ idVec3_t dir, org;
+ org[0] = origin[0];
+ org[1] = origin[1];
+ org[2] = origin[2];
+ float fov = 90;
+ if (camera.getCameraInfo(time, org, dir, &fov)) {
+ origin[0] = org[0];
+ origin[1] = org[1];
+ origin[2] = org[2];
+ angles[1] = atan2 (dir[1], dir[0])*180/3.14159;
+ angles[0] = asin (dir[2])*180/3.14159;
+ return qtrue;
+ }
+ return qfalse;
+}
+
+void startCamera(int time) {
+ camera.startCamera(time);
+}
+
+}
+
+
diff --git a/code/splines/splines.h b/code/splines/splines.h
new file mode 100755
index 0000000..bb41dda
--- /dev/null
+++ b/code/splines/splines.h
@@ -0,0 +1,1075 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __SPLINES_H
+#define __SPLINES_H
+
+extern "C" {
+#ifdef Q3RADIANT
+#include "../qgl.h"
+#else
+//#include "../renderer/qgl.h"
+#endif
+}
+#include "util_list.h"
+#include "util_str.h"
+#include "math_vector.h"
+
+typedef int fileHandle_t;
+
+//extern void glBox(idVec3_t &color, idVec3_t &point, float size);
+//extern void glLabeledPoint(idVec3_t &color, idVec3_t &point, float size, const char *label);
+
+static vec4_t blue(0, 0, 1, 1);
+static vec4_t red(1, 0, 0, 1);
+
+class idPointListInterface {
+public:
+ idPointListInterface() {
+ selectedPoints.Clear();
+ }
+ virtual ~idPointListInterface() {}
+
+ virtual int numPoints() {
+ return 0;
+ }
+
+ virtual void addPoint(const float x, const float y, const float z) {}
+ virtual void addPoint(const idVec3_t &v) {}
+ virtual void removePoint(int index) {}
+ virtual idVec3_t *getPoint(int index) { return NULL; }
+
+ int selectPointByRay(float ox, float oy, float oz, float dx, float dy, float dz, bool single) {
+ idVec3_t origin(ox, oy, oz);
+ idVec3_t dir(dx, dy, dz);
+ return selectPointByRay(origin, dir, single);
+ }
+
+ int selectPointByRay(const idVec3_t origin, const idVec3_t direction, bool single) {
+ int i, besti, count;
+ float d, bestd;
+ idVec3_t temp, temp2;
+
+ // find the point closest to the ray
+ besti = -1;
+ bestd = 8;
+ count = numPoints();
+
+ for (i=0; i < count; i++) {
+ temp = *getPoint(i);
+ temp2 = temp;
+ temp -= origin;
+ d = DotProduct(temp, direction);
+ __VectorMA (origin, d, direction, temp);
+ temp2 -= temp;
+ d = temp2.Length();
+ if (d <= bestd) {
+ bestd = d;
+ besti = i;
+ }
+ }
+
+ if (besti >= 0) {
+ selectPoint(besti, single);
+ }
+
+ return besti;
+ }
+
+ int isPointSelected(int index) {
+ int count = selectedPoints.Num();
+ for (int i = 0; i < count; i++) {
+ if (selectedPoints[i] == index) {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ int selectPoint(int index, bool single) {
+ if (index >= 0 && index < numPoints()) {
+ if (single) {
+ deselectAll();
+ } else {
+ if (isPointSelected(index) >= 0) {
+ selectedPoints.Remove(index);
+ }
+ }
+ return selectedPoints.Append(index);
+ }
+ return -1;
+ }
+
+ void selectAll() {
+ selectedPoints.Clear();
+ for (int i = 0; i < numPoints(); i++) {
+ selectedPoints.Append(i);
+ }
+ }
+
+ void deselectAll() {
+ selectedPoints.Clear();
+ }
+
+ virtual void updateSelection(float x, float y, float z) {
+ idVec3_t move(x, y, z);
+ updateSelection(move);
+ }
+
+ virtual void updateSelection(const idVec3_t &move) {
+ int count = selectedPoints.Num();
+ for (int i = 0; i < count; i++) {
+ *getPoint(selectedPoints[i]) += move;
+ }
+ }
+/*
+ void drawSelection() {
+ int count = selectedPoints.Num();
+ for (int i = 0; i < count; i++) {
+ glBox(red, *getPoint(selectedPoints[i]), 4);
+ }
+ }
+*/
+protected:
+ idList<int> selectedPoints;
+
+};
+
+
+class idSplineList {
+
+public:
+
+ idSplineList() {
+ clear();
+ }
+
+ idSplineList(const char *p) {
+ clear();
+ name = p;
+ };
+
+ ~idSplineList() {
+ clear();
+ };
+
+ void clearControl() {
+ for (int i = 0; i < controlPoints.Num(); i++) {
+ delete controlPoints[i];
+ }
+ controlPoints.Clear();
+ }
+
+ void clearSpline() {
+ for (int i = 0; i < splinePoints.Num(); i++) {
+ delete splinePoints[i];
+ }
+ splinePoints.Clear();
+ }
+
+ void parse(const char *(*text));
+ void write(fileHandle_t file, const char *name);
+
+ void clear() {
+ clearControl();
+ clearSpline();
+ splineTime.Clear();
+ selected = NULL;
+ dirty = true;
+ activeSegment = 0;
+ granularity = 0.025;
+ pathColor.set(1.0, 0.5, 0.0);
+ controlColor.set(0.7, 0.0, 1.0);
+ segmentColor.set(0.0, 0.0, 1.0);
+ activeColor.set(1.0, 0.0, 0.0);
+ }
+
+ void initPosition(long startTime, long totalTime);
+ const idVec3_t *getPosition(long time);
+
+
+// void draw(bool editMode);
+ void addToRenderer();
+
+ void setSelectedPoint(idVec3_t *p);
+ idVec3_t *getSelectedPoint() {
+ return selected;
+ }
+
+ void addPoint(const idVec3_t &v) {
+ controlPoints.Append(new idVec3_t(v));
+ dirty = true;
+ }
+
+ void addPoint(float x, float y, float z) {
+ controlPoints.Append(new idVec3_t(x, y, z));
+ dirty = true;
+ }
+
+ void updateSelection(const idVec3_t &move);
+
+ void startEdit() {
+ editMode = true;
+ }
+
+ void stopEdit() {
+ editMode = false;
+ }
+
+ void buildSpline();
+
+ void setGranularity(float f) {
+ granularity = f;
+ }
+
+ float getGranularity() {
+ return granularity;
+ }
+
+ int numPoints() {
+ return controlPoints.Num();
+ }
+
+ idVec3_t *getPoint(int index) {
+ assert(index >= 0 && index < controlPoints.Num());
+ return controlPoints[index];
+ }
+
+ idVec3_t *getSegmentPoint(int index) {
+ assert(index >= 0 && index < splinePoints.Num());
+ return splinePoints[index];
+ }
+
+
+ void setSegmentTime(int index, int time) {
+ assert(index >= 0 && index < splinePoints.Num());
+ splineTime[index] = time;
+ }
+
+ double getSegmentTime(int index) {
+ assert(index >= 0 && index < splinePoints.Num());
+ return splineTime[index];
+ }
+ void addSegmentTime(int index, int time) {
+ assert(index >= 0 && index < splinePoints.Num());
+ splineTime[index] += time;
+ }
+
+ float totalDistance();
+
+ static idVec3_t zero;
+
+ int getActiveSegment() {
+ return activeSegment;
+ }
+
+ void setActiveSegment(int i) {
+ //assert(i >= 0 && (splinePoints.Num() > 0 && i < splinePoints.Num()));
+ activeSegment = i;
+ }
+
+ int numSegments() {
+ return splinePoints.Num();
+ }
+
+ void setColors(idVec3_t &path, idVec3_t &segment, idVec3_t &control, idVec3_t &active) {
+ pathColor = path;
+ segmentColor = segment;
+ controlColor = control;
+ activeColor = active;
+ }
+
+ const char *getName() {
+ return name.c_str();
+ }
+
+ void setName(const char *p) {
+ name = p;
+ }
+
+ bool validTime() {
+ if (dirty) {
+ buildSpline();
+ }
+ // gcc doesn't allow static casting away from bools
+ // why? I've no idea...
+ return (bool)(splineTime.Num() > 0 && splineTime.Num() == splinePoints.Num());
+ }
+
+ void setTime(long t) {
+ time = t;
+ }
+
+ void setBaseTime(long t) {
+ baseTime = t;
+ }
+
+protected:
+ idStr name;
+ float calcSpline(int step, float tension);
+ idList<idVec3_t*> controlPoints;
+ idList<idVec3_t*> splinePoints;
+ idList<double> splineTime;
+ idVec3_t *selected;
+ idVec3_t pathColor, segmentColor, controlColor, activeColor;
+ float granularity;
+ bool editMode;
+ bool dirty;
+ int activeSegment;
+ long baseTime;
+ long time;
+ friend class idCamera;
+};
+
+// time in milliseconds
+// velocity where 1.0 equal rough walking speed
+struct idVelocity {
+ idVelocity(long start, long duration, float s) {
+ startTime = start;
+ time = duration;
+ speed = s;
+ }
+ long startTime;
+ long time;
+ float speed;
+};
+
+// can either be a look at or origin position for a camera
+//
+class idCameraPosition : public idPointListInterface {
+public:
+
+ virtual void clear() {
+ editMode = false;
+ for (int i = 0; i < velocities.Num(); i++) {
+ delete velocities[i];
+ velocities[i] = NULL;
+ }
+ velocities.Clear();
+ }
+
+ idCameraPosition(const char *p) {
+ name = p;
+ }
+
+ idCameraPosition() {
+ time = 0;
+ name = "position";
+ }
+
+ idCameraPosition(long t) {
+ time = t;
+ }
+
+ virtual ~idCameraPosition() {
+ clear();
+ }
+
+
+ // this can be done with RTTI syntax but i like the derived classes setting a type
+ // makes serialization a bit easier to see
+ //
+ enum positionType {
+ FIXED = 0x00,
+ INTERPOLATED,
+ SPLINE,
+ POSITION_COUNT
+ };
+
+
+ virtual void start(long t) {
+ startTime = t;
+ }
+
+ long getTime() {
+ return time;
+ }
+
+ virtual void setTime(long t) {
+ time = t;
+ }
+
+ float getVelocity(long t) {
+ long check = t - startTime;
+ for (int i = 0; i < velocities.Num(); i++) {
+ if (check >= velocities[i]->startTime && check <= velocities[i]->startTime + velocities[i]->time) {
+ return velocities[i]->speed;
+ }
+ }
+ return baseVelocity;
+ }
+
+ void addVelocity(long start, long duration, float speed) {
+ velocities.Append(new idVelocity(start, duration, speed));
+ }
+
+ virtual const idVec3_t *getPosition(long t) {
+ assert(true);
+ return NULL;
+ }
+
+// virtual void draw(bool editMode) {};
+
+ virtual void parse(const char *(*text)) {};
+ virtual void write(fileHandle_t file, const char *name);
+ virtual bool parseToken(const char *key, const char *(*text));
+
+ const char *getName() {
+ return name.c_str();
+ }
+
+ void setName(const char *p) {
+ name = p;
+ }
+
+ virtual void startEdit() {
+ editMode = true;
+ }
+
+ virtual void stopEdit() {
+ editMode = false;
+ }
+
+// virtual void draw() {};
+
+ const char *typeStr() {
+ return positionStr[static_cast<int>(type)];
+ }
+
+ void calcVelocity(float distance) {
+ float secs = (float)time / 1000;
+ baseVelocity = distance / secs;
+ }
+
+protected:
+ static const char* positionStr[POSITION_COUNT];
+ long startTime;
+ long time;
+ idCameraPosition::positionType type;
+ idStr name;
+ bool editMode;
+ idList<idVelocity*> velocities;
+ float baseVelocity;
+};
+
+class idFixedPosition : public idCameraPosition {
+public:
+
+ void init() {
+ pos.Zero();
+ type = idCameraPosition::FIXED;
+ }
+
+ idFixedPosition() : idCameraPosition() {
+ init();
+ }
+
+ idFixedPosition(idVec3_t p) : idCameraPosition() {
+ init();
+ pos = p;
+ }
+
+ virtual void addPoint(const idVec3_t &v) {
+ pos = v;
+ }
+
+ virtual void addPoint(const float x, const float y, const float z) {
+ pos.set(x, y, z);
+ }
+
+
+ ~idFixedPosition() {
+ }
+
+ virtual const idVec3_t *getPosition(long t) {
+ return &pos;
+ }
+
+ void parse(const char *(*text));
+ void write(fileHandle_t file, const char *name);
+
+ virtual int numPoints() {
+ return 1;
+ }
+
+ virtual idVec3_t *getPoint(int index) {
+ if (index != 0) {
+ assert(true);
+ };
+ return &pos;
+ }
+/*
+ virtual void draw(bool editMode) {
+ glLabeledPoint(blue, pos, (editMode) ? 5 : 3, "Fixed point");
+ }
+*/
+protected:
+ idVec3_t pos;
+};
+
+class idInterpolatedPosition : public idCameraPosition {
+public:
+
+ void init() {
+ type = idCameraPosition::INTERPOLATED;
+ first = true;
+ startPos.Zero();
+ endPos.Zero();
+ }
+
+ idInterpolatedPosition() : idCameraPosition() {
+ init();
+ }
+
+ idInterpolatedPosition(idVec3_t start, idVec3_t end, long time) : idCameraPosition(time) {
+ init();
+ startPos = start;
+ endPos = end;
+ }
+
+ ~idInterpolatedPosition() {
+ }
+
+ virtual const idVec3_t *getPosition(long t);
+
+ void parse(const char *(*text));
+ void write(fileHandle_t file, const char *name);
+
+ virtual int numPoints() {
+ return 2;
+ }
+
+ virtual idVec3_t *getPoint(int index) {
+ assert(index >= 0 && index < 2);
+ if (index == 0) {
+ return &startPos;
+ }
+ return &endPos;
+ }
+
+ virtual void addPoint(const float x, const float y, const float z) {
+ if (first) {
+ startPos.set(x, y, z);
+ first = false;
+ } else {
+ endPos.set(x, y, z);
+ first = true;
+ }
+ }
+
+ virtual void addPoint(const idVec3_t &v) {
+ if (first) {
+ startPos = v;
+ first = false;
+ } else {
+ endPos = v;
+ first = true;
+ }
+ }
+/*
+ virtual void draw(bool editMode) {
+ glLabeledPoint(blue, startPos, (editMode) ? 5 : 3, "Start interpolated");
+ glLabeledPoint(blue, endPos, (editMode) ? 5 : 3, "End interpolated");
+ qglBegin(GL_LINES);
+ qglVertex3fv(startPos);
+ qglVertex3fv(endPos);
+ qglEnd();
+ }
+*/
+ virtual void start(long t) {
+ idCameraPosition::start(t);
+ lastTime = startTime;
+ distSoFar = 0.0;
+ idVec3_t temp = startPos;
+ temp -= endPos;
+ calcVelocity(temp.Length());
+ }
+
+protected:
+ bool first;
+ idVec3_t startPos;
+ idVec3_t endPos;
+ long lastTime;
+ float distSoFar;
+};
+
+class idSplinePosition : public idCameraPosition {
+public:
+
+ void init() {
+ type = idCameraPosition::SPLINE;
+ }
+
+ idSplinePosition() : idCameraPosition() {
+ init();
+ }
+
+ idSplinePosition(long time) : idCameraPosition(time) {
+ init();
+ }
+
+ ~idSplinePosition() {
+ }
+
+ virtual void start(long t) {
+ idCameraPosition::start(t);
+ target.initPosition(t, time);
+ calcVelocity(target.totalDistance());
+ }
+
+ virtual const idVec3_t *getPosition(long t) {
+ return target.getPosition(t);
+ }
+
+ //virtual const idVec3_t *getPosition(long t) const {
+
+ void addControlPoint(idVec3_t &v) {
+ target.addPoint(v);
+ }
+
+ void parse(const char *(*text));
+ void write(fileHandle_t file, const char *name);
+
+ virtual int numPoints() {
+ return target.numPoints();
+ }
+
+ virtual idVec3_t *getPoint(int index) {
+ return target.getPoint(index);
+ }
+
+ virtual void addPoint(const idVec3_t &v) {
+ target.addPoint(v);
+ }
+
+ virtual void addPoint(const float x, const float y, const float z) {
+ target.addPoint(x, y, z);
+ }
+
+/* virtual void draw(bool editMode) {
+ target.draw(editMode);
+ }
+*/
+ virtual void updateSelection(const idVec3_t &move) {
+ idCameraPosition::updateSelection(move);
+ target.buildSpline();
+ }
+
+protected:
+ idSplineList target;
+};
+
+class idCameraFOV {
+public:
+
+ idCameraFOV() {
+ time = 0;
+ fov = 90;
+ }
+
+ idCameraFOV(int v) {
+ time = 0;
+ fov = v;
+ }
+
+ idCameraFOV(int s, int e, long t) {
+ startFOV = s;
+ endFOV = e;
+ time = t;
+ }
+
+
+ ~idCameraFOV(){}
+
+ void setFOV(float f) {
+ fov = f;
+ }
+
+ float getFOV(long t) {
+ if (time) {
+ assert(startTime);
+ float percent = t / startTime;
+ float temp = startFOV - endFOV;
+ temp *= percent;
+ fov = startFOV + temp;
+ }
+ return fov;
+ }
+
+ void start(long t) {
+ startTime = t;
+ }
+
+ void parse(const char *(*text));
+ void write(fileHandle_t file, const char *name);
+
+protected:
+ float fov;
+ float startFOV;
+ float endFOV;
+ int startTime;
+ int time;
+};
+
+
+
+
+class idCameraEvent {
+public:
+ enum eventType {
+ EVENT_NA = 0x00,
+ EVENT_WAIT,
+ EVENT_TARGETWAIT,
+ EVENT_SPEED,
+ EVENT_TARGET,
+ EVENT_SNAPTARGET,
+ EVENT_FOV,
+ EVENT_SCRIPT,
+ EVENT_TRIGGER,
+ EVENT_STOP,
+ EVENT_COUNT
+ };
+
+ static const char* eventStr[EVENT_COUNT];
+
+ idCameraEvent() {
+ paramStr = "";
+ type = EVENT_NA;
+ time = 0;
+ }
+
+ idCameraEvent(eventType t, const char *param, long n) {
+ type = t;
+ paramStr = param;
+ time = n;
+ }
+
+ ~idCameraEvent() {};
+
+ eventType getType() {
+ return type;
+ }
+
+ const char *typeStr() {
+ return eventStr[static_cast<int>(type)];
+ }
+
+ const char *getParam() {
+ return paramStr.c_str();
+ }
+
+ long getTime() {
+ return time;
+ }
+
+ void setTime(long n) {
+ time = n;
+ }
+
+ void parse(const char *(*text));
+ void write(fileHandle_t file, const char *name);
+
+ void setTriggered(bool b) {
+ triggered = b;
+ }
+
+ bool getTriggered() {
+ return triggered;
+ }
+
+protected:
+ eventType type;
+ idStr paramStr;
+ long time;
+ bool triggered;
+
+};
+
+class idCameraDef {
+public:
+
+ void clear() {
+ currentCameraPosition = 0;
+ cameraRunning = false;
+ lastDirection.Zero();
+ baseTime = 30;
+ activeTarget = 0;
+ name = "camera01";
+ fov.setFOV(90);
+ int i;
+ for (i = 0; i < targetPositions.Num(); i++) {
+ delete targetPositions[i];
+ }
+ for (i = 0; i < events.Num(); i++) {
+ delete events[i];
+ }
+ delete cameraPosition;
+ cameraPosition = NULL;
+ events.Clear();
+ targetPositions.Clear();
+ }
+
+ idCameraPosition *startNewCamera(idCameraPosition::positionType type) {
+ clear();
+ if (type == idCameraPosition::SPLINE) {
+ cameraPosition = new idSplinePosition();
+ } else if (type == idCameraPosition::INTERPOLATED) {
+ cameraPosition = new idInterpolatedPosition();
+ } else {
+ cameraPosition = new idFixedPosition();
+ }
+ return cameraPosition;
+ }
+
+ idCameraDef() {
+ clear();
+ }
+
+ ~idCameraDef() {
+ clear();
+ }
+
+ void addEvent(idCameraEvent::eventType t, const char *param, long time);
+
+ void addEvent(idCameraEvent *event);
+
+ static int sortEvents(const void *p1, const void *p2);
+
+ int numEvents() {
+ return events.Num();
+ }
+
+ idCameraEvent *getEvent(int index) {
+ assert(index >= 0 && index < events.Num());
+ return events[index];
+ }
+
+ void parse(const char *(*text));
+ qboolean load(const char *filename);
+ void save(const char *filename);
+
+ void buildCamera();
+
+ //idSplineList *getcameraPosition() {
+ // return &cameraPosition;
+ //}
+
+ static idCameraPosition *newFromType(idCameraPosition::positionType t) {
+ switch (t) {
+ case idCameraPosition::FIXED : return new idFixedPosition();
+ case idCameraPosition::INTERPOLATED : return new idInterpolatedPosition();
+ case idCameraPosition::SPLINE : return new idSplinePosition();
+ default:
+ break;
+ };
+ return NULL;
+ }
+
+ void addTarget(const char *name, idCameraPosition::positionType type);
+
+ idCameraPosition *getActiveTarget() {
+ if (targetPositions.Num() == 0) {
+ addTarget(NULL, idCameraPosition::FIXED);
+ }
+ return targetPositions[activeTarget];
+ }
+
+ idCameraPosition *getActiveTarget(int index) {
+ if (targetPositions.Num() == 0) {
+ addTarget(NULL, idCameraPosition::FIXED);
+ return targetPositions[0];
+ }
+ return targetPositions[index];
+ }
+
+ int numTargets() {
+ return targetPositions.Num();
+ }
+
+
+ void setActiveTargetByName(const char *name) {
+ for (int i = 0; i < targetPositions.Num(); i++) {
+ if (Q_stricmp(name, targetPositions[i]->getName()) == 0) {
+ setActiveTarget(i);
+ return;
+ }
+ }
+ }
+
+ void setActiveTarget(int index) {
+ assert(index >= 0 && index < targetPositions.Num());
+ activeTarget = index;
+ }
+
+ void setRunning(bool b) {
+ cameraRunning = b;
+ }
+
+ void setBaseTime(float f) {
+ baseTime = f;
+ }
+
+ float getBaseTime() {
+ return baseTime;
+ }
+
+ float getTotalTime() {
+ return totalTime;
+ }
+
+ void startCamera(long t);
+ void stopCamera() {
+ cameraRunning = true;
+ }
+ void getActiveSegmentInfo(int segment, idVec3_t &origin, idVec3_t &direction, float *fv);
+
+ bool getCameraInfo(long time, idVec3_t &origin, idVec3_t &direction, float *fv);
+ bool getCameraInfo(long time, float *origin, float *direction, float *fv) {
+ idVec3_t org, dir;
+ org[0] = origin[0];
+ org[1] = origin[1];
+ org[2] = origin[2];
+ dir[0] = direction[0];
+ dir[1] = direction[1];
+ dir[2] = direction[2];
+ bool b = getCameraInfo(time, org, dir, fv);
+ origin[0] = org[0];
+ origin[1] = org[1];
+ origin[2] = org[2];
+ direction[0] = dir[0];
+ direction[1] = dir[1];
+ direction[2] = dir[2];
+ return b;
+ }
+/*
+ void draw(bool editMode) {
+ // gcc doesn't allow casting away from bools
+ // why? I've no idea...
+ if (cameraPosition) {
+ cameraPosition->draw((bool)((editMode || cameraRunning) && cameraEdit));
+ int count = targetPositions.Num();
+ for (int i = 0; i < count; i++) {
+ targetPositions[i]->draw((bool)((editMode || cameraRunning) && i == activeTarget && !cameraEdit));
+ }
+ }
+ }
+*/
+/*
+ int numSegments() {
+ if (cameraEdit) {
+ return cameraPosition.numSegments();
+ }
+ return getTargetSpline()->numSegments();
+ }
+
+ int getActiveSegment() {
+ if (cameraEdit) {
+ return cameraPosition.getActiveSegment();
+ }
+ return getTargetSpline()->getActiveSegment();
+ }
+
+ void setActiveSegment(int i) {
+ if (cameraEdit) {
+ cameraPosition.setActiveSegment(i);
+ } else {
+ getTargetSpline()->setActiveSegment(i);
+ }
+ }
+*/
+ int numPoints() {
+ if (cameraEdit) {
+ return cameraPosition->numPoints();
+ }
+ return getActiveTarget()->numPoints();
+ }
+
+ const idVec3_t *getPoint(int index) {
+ if (cameraEdit) {
+ return cameraPosition->getPoint(index);
+ }
+ return getActiveTarget()->getPoint(index);
+ }
+
+ void stopEdit() {
+ editMode = false;
+ if (cameraEdit) {
+ cameraPosition->stopEdit();
+ } else {
+ getActiveTarget()->stopEdit();
+ }
+ }
+
+ void startEdit(bool camera) {
+ cameraEdit = camera;
+ if (camera) {
+ cameraPosition->startEdit();
+ for (int i = 0; i < targetPositions.Num(); i++) {
+ targetPositions[i]->stopEdit();
+ }
+ } else {
+ getActiveTarget()->startEdit();
+ cameraPosition->stopEdit();
+ }
+ editMode = true;
+ }
+
+ bool waitEvent(int index);
+
+ const char *getName() {
+ return name.c_str();
+ }
+
+ void setName(const char *p) {
+ name = p;
+ }
+
+ idCameraPosition *getPositionObj() {
+ if (cameraPosition == NULL) {
+ cameraPosition = new idFixedPosition();
+ }
+ return cameraPosition;
+ }
+
+protected:
+ idStr name;
+ int currentCameraPosition;
+ idVec3_t lastDirection;
+ bool cameraRunning;
+ idCameraPosition *cameraPosition;
+ idList<idCameraPosition*> targetPositions;
+ idList<idCameraEvent*> events;
+ idCameraFOV fov;
+ int activeTarget;
+ float totalTime;
+ float baseTime;
+ long startTime;
+
+ bool cameraEdit;
+ bool editMode;
+};
+
+extern bool g_splineMode;
+
+extern idCameraDef *g_splineList;
+
+
+#endif
diff --git a/code/splines/util_list.h b/code/splines/util_list.h
new file mode 100755
index 0000000..6ee8f6a
--- /dev/null
+++ b/code/splines/util_list.h
@@ -0,0 +1,346 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __UTIL_LIST_H__
+#define __UTIL_LIST_H__
+
+#include <stdlib.h>
+#include <assert.h>
+
+template< class type >
+class idList {
+private:
+ int m_num;
+ int m_size;
+ int m_granularity;
+ type *m_list;
+
+public:
+ idList( int granularity = 16 );
+ ~idList<type>();
+ void Clear( void );
+ int Num( void );
+ void SetNum( int num );
+ void SetGranularity( int granularity );
+ void Condense( void );
+ int Size( void );
+ void Resize( int size );
+ type operator[]( int index ) const;
+ type &operator[]( int index );
+ int Append( type const & obj );
+ int AddUnique( type const & obj );
+ type *Find( type const & obj, int *index = NULL );
+ bool RemoveIndex( int index );
+ bool Remove( type const & obj );
+ typedef int cmp_t(const void *, const void *);
+ void Sort( cmp_t *compare );
+};
+
+/*
+================
+idList<type>::idList( int )
+================
+*/
+template< class type >
+inline idList<type>::idList( int granularity ) {
+ assert( granularity > 0 );
+
+ m_list = NULL;
+ m_granularity = granularity;
+ Clear();
+}
+
+/*
+================
+idList<type>::~idList<type>
+================
+*/
+template< class type >
+inline idList<type>::~idList() {
+ Clear();
+}
+
+/*
+================
+idList<type>::Clear
+================
+*/
+template< class type >
+inline void idList<type>::Clear( void ) {
+ if ( m_list ) {
+ delete[] m_list;
+ }
+
+ m_list = NULL;
+ m_num = 0;
+ m_size = 0;
+}
+
+/*
+================
+idList<type>::Num
+================
+*/
+template< class type >
+inline int idList<type>::Num( void ) {
+ return m_num;
+}
+
+/*
+================
+idList<type>::SetNum
+================
+*/
+template< class type >
+inline void idList<type>::SetNum( int num ) {
+ assert( num >= 0 );
+ if ( num > m_size ) {
+ // resize it up to the closest level of granularity
+ Resize( ( ( num + m_granularity - 1 ) / m_granularity ) * m_granularity );
+ }
+ m_num = num;
+}
+
+/*
+================
+idList<type>::SetGranularity
+================
+*/
+template< class type >
+inline void idList<type>::SetGranularity( int granularity ) {
+ int newsize;
+
+ assert( granularity > 0 );
+ m_granularity = granularity;
+
+ if ( m_list ) {
+ // resize it to the closest level of granularity
+ newsize = ( ( m_num + m_granularity - 1 ) / m_granularity ) * m_granularity;
+ if ( newsize != m_size ) {
+ Resize( newsize );
+ }
+ }
+}
+
+/*
+================
+idList<type>::Condense
+
+Resizes the array to exactly the number of elements it contains
+================
+*/
+template< class type >
+inline void idList<type>::Condense( void ) {
+ if ( m_list ) {
+ if ( m_num ) {
+ Resize( m_num );
+ } else {
+ Clear();
+ }
+ }
+}
+
+/*
+================
+idList<type>::Size
+================
+*/
+template< class type >
+inline int idList<type>::Size( void ) {
+ return m_size;
+}
+
+/*
+================
+idList<type>::Resize
+================
+*/
+template< class type >
+inline void idList<type>::Resize( int size ) {
+ type *temp;
+ int i;
+
+ assert( size > 0 );
+
+ if ( size <= 0 ) {
+ Clear();
+ return;
+ }
+
+ temp = m_list;
+ m_size = size;
+ if ( m_size < m_num ) {
+ m_num = m_size;
+ }
+
+ m_list = new type[ m_size ];
+ for( i = 0; i < m_num; i++ ) {
+ m_list[ i ] = temp[ i ];
+ }
+
+ if ( temp ) {
+ delete[] temp;
+ }
+}
+
+/*
+================
+idList<type>::operator[] const
+================
+*/
+template< class type >
+inline type idList<type>::operator[]( int index ) const {
+ assert( index >= 0 );
+ assert( index < m_num );
+
+ return m_list[ index ];
+}
+
+/*
+================
+idList<type>::operator[]
+================
+*/
+template< class type >
+inline type &idList<type>::operator[]( int index ) {
+ assert( index >= 0 );
+ assert( index < m_num );
+
+ return m_list[ index ];
+}
+
+/*
+================
+idList<type>::Append
+================
+*/
+template< class type >
+inline int idList<type>::Append( type const & obj ) {
+ if ( !m_list ) {
+ Resize( m_granularity );
+ }
+
+ if ( m_num == m_size ) {
+ Resize( m_size + m_granularity );
+ }
+
+ m_list[ m_num ] = obj;
+ m_num++;
+
+ return m_num - 1;
+}
+
+/*
+================
+idList<type>::AddUnique
+================
+*/
+template< class type >
+inline int idList<type>::AddUnique( type const & obj ) {
+ int index;
+
+ if ( !Find( obj, &index ) ) {
+ index = Append( obj );
+ }
+
+ return index;
+}
+
+/*
+================
+idList<type>::Find
+================
+*/
+template< class type >
+inline type *idList<type>::Find( type const & obj, int *index ) {
+ int i;
+
+ for( i = 0; i < m_num; i++ ) {
+ if ( m_list[ i ] == obj ) {
+ if ( index ) {
+ *index = i;
+ }
+ return &m_list[ i ];
+ }
+ }
+
+ return NULL;
+}
+
+/*
+================
+idList<type>::RemoveIndex
+================
+*/
+template< class type >
+inline bool idList<type>::RemoveIndex( int index ) {
+ int i;
+
+ if ( !m_list || !m_num ) {
+ return false;
+ }
+
+ assert( index >= 0 );
+ assert( index < m_num );
+
+ if ( ( index < 0 ) || ( index >= m_num ) ) {
+ return false;
+ }
+
+ m_num--;
+ for( i = index; i < m_num; i++ ) {
+ m_list[ i ] = m_list[ i + 1 ];
+ }
+
+ return true;
+}
+
+/*
+================
+idList<type>::Remove
+================
+*/
+template< class type >
+inline bool idList<type>::Remove( type const & obj ) {
+ int index;
+
+ if ( Find( obj, &index ) ) {
+ return RemoveIndex( index );
+ }
+
+ return false;
+}
+
+/*
+================
+idList<type>::Sort
+================
+*/
+template< class type >
+inline void idList<type>::Sort( cmp_t *compare ) {
+ if ( !m_list ) {
+ return;
+ }
+
+ qsort( ( void * )m_list, ( size_t )m_num, sizeof( type ), compare );
+}
+
+#endif /* !__UTIL_LIST_H__ */
diff --git a/code/splines/util_str.cpp b/code/splines/util_str.cpp
new file mode 100755
index 0000000..0ae7362
--- /dev/null
+++ b/code/splines/util_str.cpp
@@ -0,0 +1,620 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//need to rewrite this
+
+#include "util_str.h"
+#include <stdlib.h>
+#include <ctype.h>
+#include <stdio.h>
+#include <stdarg.h>
+
+#ifdef _WIN32
+#pragma warning(disable : 4244) // 'conversion' conversion from 'type1' to 'type2', possible loss of data
+#pragma warning(disable : 4710) // function 'blah' not inlined
+#endif
+
+static const int STR_ALLOC_GRAN = 20;
+
+char *idStr::toLower
+ (
+ char *s1
+ )
+
+ {
+ char *s;
+
+ s = s1;
+ while( *s )
+ {
+ *s = ::tolower( *s );
+ s++;
+ }
+
+ return s1;
+ }
+
+char *idStr::toUpper
+ (
+ char *s1
+ )
+
+ {
+ char *s;
+
+ s = s1;
+ while( *s )
+ {
+ *s = ::toupper( *s );
+ s++;
+ }
+
+ return s1;
+ }
+
+
+int idStr::icmpn
+ (
+ const char *s1,
+ const char *s2,
+ int n
+ )
+
+ {
+ int c1;
+ int c2;
+
+ do
+ {
+ c1 = *s1++;
+ c2 = *s2++;
+
+ if ( !n-- )
+ {
+ // idStrings are equal until end point
+ return 0;
+ }
+
+ if ( c1 != c2 )
+ {
+ if ( c1 >= 'a' && c1 <= 'z' )
+ {
+ c1 -= ( 'a' - 'A' );
+ }
+
+ if ( c2 >= 'a' && c2 <= 'z' )
+ {
+ c2 -= ( 'a' - 'A' );
+ }
+
+ if ( c1 < c2 )
+ {
+ // strings less than
+ return -1;
+ }
+ else if ( c1 > c2 )
+ {
+ // strings greater than
+ return 1;
+ }
+ }
+ }
+ while( c1 );
+
+ // strings are equal
+ return 0;
+ }
+
+int idStr::icmp
+ (
+ const char *s1,
+ const char *s2
+ )
+
+ {
+ int c1;
+ int c2;
+
+ do
+ {
+ c1 = *s1++;
+ c2 = *s2++;
+
+ if ( c1 != c2 )
+ {
+ if ( c1 >= 'a' && c1 <= 'z' )
+ {
+ c1 -= ( 'a' - 'A' );
+ }
+
+ if ( c2 >= 'a' && c2 <= 'z' )
+ {
+ c2 -= ( 'a' - 'A' );
+ }
+
+ if ( c1 < c2 )
+ {
+ // strings less than
+ return -1;
+ }
+ else if ( c1 > c2 )
+ {
+ // strings greater than
+ return 1;
+ }
+ }
+ }
+ while( c1 );
+
+ // strings are equal
+ return 0;
+ }
+
+int idStr::cmpn
+ (
+ const char *s1,
+ const char *s2,
+ int n
+ )
+
+ {
+ int c1;
+ int c2;
+
+ do
+ {
+ c1 = *s1++;
+ c2 = *s2++;
+
+ if ( !n-- )
+ {
+ // strings are equal until end point
+ return 0;
+ }
+
+ if ( c1 < c2 )
+ {
+ // strings less than
+ return -1;
+ }
+ else if ( c1 > c2 )
+ {
+ // strings greater than
+ return 1;
+ }
+ }
+ while( c1 );
+
+ // strings are equal
+ return 0;
+ }
+
+int idStr::cmp
+ (
+ const char *s1,
+ const char *s2
+ )
+
+ {
+ int c1;
+ int c2;
+
+ do
+ {
+ c1 = *s1++;
+ c2 = *s2++;
+
+ if ( c1 < c2 )
+ {
+ // strings less than
+ return -1;
+ }
+ else if ( c1 > c2 )
+ {
+ // strings greater than
+ return 1;
+ }
+ }
+ while( c1 );
+
+ // strings are equal
+ return 0;
+ }
+
+/*
+============
+IsNumeric
+
+Checks a string to see if it contains only numerical values.
+============
+*/
+bool idStr::isNumeric
+ (
+ const char *str
+ )
+
+ {
+ int len;
+ int i;
+ bool dot;
+
+ if ( *str == '-' )
+ {
+ str++;
+ }
+
+ dot = false;
+ len = strlen( str );
+ for( i = 0; i < len; i++ )
+ {
+ if ( !isdigit( str[ i ] ) )
+ {
+ if ( ( str[ i ] == '.' ) && !dot )
+ {
+ dot = true;
+ continue;
+ }
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+idStr operator+
+ (
+ const idStr& a,
+ const float b
+ )
+
+ {
+ char text[ 20 ];
+
+ idStr result( a );
+
+ sprintf( text, "%f", b );
+ result.append( text );
+
+ return result;
+ }
+
+idStr operator+
+ (
+ const idStr& a,
+ const int b
+ )
+
+ {
+ char text[ 20 ];
+
+ idStr result( a );
+
+ sprintf( text, "%d", b );
+ result.append( text );
+
+ return result;
+ }
+
+idStr operator+
+ (
+ const idStr& a,
+ const unsigned b
+ )
+
+ {
+ char text[ 20 ];
+
+ idStr result( a );
+
+ sprintf( text, "%u", b );
+ result.append( text );
+
+ return result;
+ }
+
+idStr& idStr::operator+=
+ (
+ const float a
+ )
+
+ {
+ char text[ 20 ];
+
+ sprintf( text, "%f", a );
+ append( text );
+
+ return *this;
+ }
+
+idStr& idStr::operator+=
+ (
+ const int a
+ )
+
+ {
+ char text[ 20 ];
+
+ sprintf( text, "%d", a );
+ append( text );
+
+ return *this;
+ }
+
+idStr& idStr::operator+=
+ (
+ const unsigned a
+ )
+
+ {
+ char text[ 20 ];
+
+ sprintf( text, "%u", a );
+ append( text );
+
+ return *this;
+ }
+
+void idStr::CapLength
+ (
+ int newlen
+ )
+
+ {
+ assert ( m_data );
+
+ if ( length() <= newlen )
+ return;
+
+ EnsureDataWritable ();
+
+ m_data->data[newlen] = 0;
+ m_data->len = newlen;
+ }
+
+void idStr::EnsureDataWritable
+ (
+ void
+ )
+
+ {
+ assert ( m_data );
+ strdata *olddata;
+ int len;
+
+ if ( !m_data->refcount )
+ return;
+
+ olddata = m_data;
+ len = length();
+
+ m_data = new strdata;
+
+ EnsureAlloced ( len + 1, false );
+ strncpy ( m_data->data, olddata->data, len+1 );
+ m_data->len = len;
+
+ olddata->DelRef ();
+ }
+
+void idStr::EnsureAlloced (int amount, bool keepold) {
+
+ if ( !m_data ) {
+ m_data = new strdata();
+ }
+
+ // Now, let's make sure it's writable
+ EnsureDataWritable ();
+
+ char *newbuffer;
+ bool wasalloced = ( m_data->alloced != 0 );
+
+ if ( amount < m_data->alloced ) {
+ return;
+ }
+
+ assert ( amount );
+ if ( amount == 1 ) {
+ m_data->alloced = 1;
+ } else {
+ int newsize, mod;
+ mod = amount % STR_ALLOC_GRAN;
+ if ( !mod ) {
+ newsize = amount;
+ } else {
+ newsize = amount + STR_ALLOC_GRAN - mod;
+ }
+ m_data->alloced = newsize;
+ }
+
+ newbuffer = new char[m_data->alloced];
+ if ( wasalloced && keepold ) {
+ strcpy ( newbuffer, m_data->data );
+ }
+
+ if ( m_data->data ) {
+ delete [] m_data->data;
+ }
+ m_data->data = newbuffer;
+}
+
+void idStr::BackSlashesToSlashes
+ (
+ void
+ )
+
+ {
+ int i;
+
+ EnsureDataWritable ();
+
+ for ( i=0; i < m_data->len; i++ )
+ {
+ if ( m_data->data[i] == '\\' )
+ m_data->data[i] = '/';
+ }
+ }
+
+void idStr::snprintf
+ (
+ char *dst,
+ int size,
+ const char *fmt,
+ ...
+ )
+
+ {
+ char buffer[0x10000];
+ int len;
+ va_list argptr;
+
+ va_start (argptr,fmt);
+ len = vsprintf (buffer,fmt,argptr);
+ va_end (argptr);
+
+ assert ( len < size );
+
+ strncpy (dst, buffer, size-1);
+ }
+
+#ifdef _WIN32
+#pragma warning(disable : 4189) // local variable is initialized but not referenced
+#endif
+
+/*
+=================
+TestStringClass
+
+This is a fairly rigorous test of the idStr class's functionality.
+Because of the fairly global and subtle ramifications of a bug occuring
+in this class, it should be run after any changes to the class.
+Add more tests as functionality is changed. Tests should include
+any possible bounds violation and NULL data tests.
+=================
+*/
+void TestStringClass
+ (
+ void
+ )
+
+ {
+ char ch; // ch == ?
+ idStr *t; // t == ?
+ idStr a; // a.len == 0, a.data == "\0"
+ idStr b; // b.len == 0, b.data == "\0"
+ idStr c( "test" ); // c.len == 4, c.data == "test\0"
+ idStr d( c ); // d.len == 4, d.data == "test\0"
+ idStr e( reinterpret_cast<const char *>(NULL) );
+ // e.len == 0, e.data == "\0" ASSERT!
+ int i; // i == ?
+
+ i = a.length(); // i == 0
+ i = c.length(); // i == 4
+
+ // TTimo: not used
+// const char *s1 = a.c_str(); // s1 == "\0"
+// const char *s2 = c.c_str(); // s2 == "test\0"
+
+ t = new idStr(); // t->len == 0, t->data == "\0"
+ delete t; // t == ?
+
+ b = "test"; // b.len == 4, b.data == "test\0"
+ t = new idStr( "test" ); // t->len == 4, t->data == "test\0"
+ delete t; // t == ?
+
+ a = c; // a.len == 4, a.data == "test\0"
+// a = "";
+ a = NULL; // a.len == 0, a.data == "\0" ASSERT!
+ a = c + d; // a.len == 8, a.data == "testtest\0"
+ a = c + "wow"; // a.len == 7, a.data == "testwow\0"
+ a = c + reinterpret_cast<const char *>(NULL);
+ // a.len == 4, a.data == "test\0" ASSERT!
+ a = "this" + d; // a.len == 8, a.data == "thistest\0"
+ a = reinterpret_cast<const char *>(NULL) + d;
+ // a.len == 4, a.data == "test\0" ASSERT!
+ a += c; // a.len == 8, a.data == "testtest\0"
+ a += "wow"; // a.len == 11, a.data == "testtestwow\0"
+ a += reinterpret_cast<const char *>(NULL);
+ // a.len == 11, a.data == "testtestwow\0" ASSERT!
+
+ a = "test"; // a.len == 4, a.data == "test\0"
+ ch = a[ 0 ]; // ch == 't'
+ ch = a[ -1 ]; // ch == 0 ASSERT!
+ ch = a[ 1000 ]; // ch == 0 ASSERT!
+ ch = a[ 0 ]; // ch == 't'
+ ch = a[ 1 ]; // ch == 'e'
+ ch = a[ 2 ]; // ch == 's'
+ ch = a[ 3 ]; // ch == 't'
+ ch = a[ 4 ]; // ch == '\0' ASSERT!
+ ch = a[ 5 ]; // ch == '\0' ASSERT!
+
+ a[ 1 ] = 'b'; // a.len == 4, a.data == "tbst\0"
+ a[ -1 ] = 'b'; // a.len == 4, a.data == "tbst\0" ASSERT!
+ a[ 0 ] = '0'; // a.len == 4, a.data == "0bst\0"
+ a[ 1 ] = '1'; // a.len == 4, a.data == "01st\0"
+ a[ 2 ] = '2'; // a.len == 4, a.data == "012t\0"
+ a[ 3 ] = '3'; // a.len == 4, a.data == "0123\0"
+ a[ 4 ] = '4'; // a.len == 4, a.data == "0123\0" ASSERT!
+ a[ 5 ] = '5'; // a.len == 4, a.data == "0123\0" ASSERT!
+ a[ 7 ] = '7'; // a.len == 4, a.data == "0123\0" ASSERT!
+
+ a = "test"; // a.len == 4, a.data == "test\0"
+ b = "no"; // b.len == 2, b.data == "no\0"
+
+ i = ( a == b ); // i == 0
+ i = ( a == c ); // i == 1
+
+ i = ( a == "blow" ); // i == 0
+ i = ( a == "test" ); // i == 1
+ i = ( a == NULL ); // i == 0 ASSERT!
+
+ i = ( "test" == b ); // i == 0
+ i = ( "test" == a ); // i == 1
+ i = ( NULL == a ); // i == 0 ASSERT!
+
+ i = ( a != b ); // i == 1
+ i = ( a != c ); // i == 0
+
+ i = ( a != "blow" ); // i == 1
+ i = ( a != "test" ); // i == 0
+ i = ( a != NULL ); // i == 1 ASSERT!
+
+ i = ( "test" != b ); // i == 1
+ i = ( "test" != a ); // i == 0
+ i = ( NULL != a ); // i == 1 ASSERT!
+
+ a = "test"; // a.data == "test"
+ b = a; // b.data == "test"
+
+ a = "not"; // a.data == "not", b.data == "test"
+
+ a = b; // a.data == b.data == "test"
+
+ a += b; // a.data == "testtest", b.data = "test"
+
+ a = b;
+
+ a[1] = '1'; // a.data = "t1st", b.data = "test"
+ }
+
+#ifdef _WIN32
+#pragma warning(default : 4189) // local variable is initialized but not referenced
+#pragma warning(disable : 4514) // unreferenced inline function has been removed
+#endif
diff --git a/code/splines/util_str.h b/code/splines/util_str.h
new file mode 100755
index 0000000..514464b
--- /dev/null
+++ b/code/splines/util_str.h
@@ -0,0 +1,817 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//need to rewrite this
+
+#ifndef __UTIL_STR_H__
+#define __UTIL_STR_H__
+
+#include <assert.h>
+#include <string.h>
+#include <stdio.h>
+
+#ifdef _WIN32
+#pragma warning(disable : 4710) // function 'blah' not inlined
+#endif
+
+void TestStringClass ();
+
+class strdata
+ {
+ public:
+ strdata () : len( 0 ), refcount ( 0 ), data ( NULL ), alloced ( 0 ) {}
+ ~strdata ()
+ {
+ if ( data )
+ delete [] data;
+ }
+
+ void AddRef () { refcount++; }
+ bool DelRef () // True if killed
+ {
+ refcount--;
+ if ( refcount < 0 )
+ {
+ delete this;
+ return true;
+ }
+
+ return false;
+ }
+
+ int len;
+ int refcount;
+ char *data;
+ int alloced;
+ };
+
+class idStr {
+protected:
+ strdata *m_data;
+ void EnsureAlloced ( int, bool keepold = true );
+ void EnsureDataWritable ();
+
+public:
+ ~idStr();
+ idStr();
+ idStr( const char *text );
+ idStr( const idStr& string );
+ idStr( const idStr string, int start, int end );
+ idStr( const char ch );
+ idStr( const int num );
+ idStr( const float num );
+ idStr( const unsigned num );
+ int length( void ) const;
+ int allocated( void ) const;
+ const char * c_str( void ) const;
+
+ void append( const char *text );
+ void append( const idStr& text );
+ char operator[]( int index ) const;
+ char& operator[]( int index );
+
+ void operator=( const idStr& text );
+ void operator=( const char *text );
+
+ friend idStr operator+( const idStr& a, const idStr& b );
+ friend idStr operator+( const idStr& a, const char *b );
+ friend idStr operator+( const char *a, const idStr& b );
+
+ friend idStr operator+( const idStr& a, const float b );
+ friend idStr operator+( const idStr& a, const int b );
+ friend idStr operator+( const idStr& a, const unsigned b );
+ friend idStr operator+( const idStr& a, const bool b );
+ friend idStr operator+( const idStr& a, const char b );
+
+ idStr& operator+=( const idStr& a );
+ idStr& operator+=( const char *a );
+ idStr& operator+=( const float a );
+ idStr& operator+=( const char a );
+ idStr& operator+=( const int a );
+ idStr& operator+=( const unsigned a );
+ idStr& operator+=( const bool a );
+
+ static char *toLower( char *s1 );
+ static char *toUpper( char *s1 );
+
+ friend bool operator==( const idStr& a, const idStr& b );
+ friend bool operator==( const idStr& a, const char *b );
+ friend bool operator==( const char *a, const idStr& b );
+
+ friend bool operator!=( const idStr& a, const idStr& b );
+ friend bool operator!=( const idStr& a, const char *b );
+ friend bool operator!=( const char *a, const idStr& b );
+
+ operator const char * () const;
+ operator const char * ();
+
+ int icmpn( const char *text, int n ) const;
+ int icmpn( const idStr& text, int n ) const;
+ int icmp( const char *text ) const;
+ int icmp( const idStr& text ) const;
+ int cmpn( const char *text, int n ) const;
+ int cmpn( const idStr& text, int n ) const;
+ int cmp( const char *text ) const;
+ int cmp( const idStr& text ) const;
+
+ void tolower( void );
+ void toupper( void );
+
+ static int icmpn( const char *s1, const char *s2, int n );
+ static int icmp( const char *s1, const char *s2 );
+ static int cmpn( const char *s1, const char *s2, int n );
+ static int cmp( const char *s1, const char *s2 );
+
+ static void snprintf ( char *dst, int size, const char *fmt, ... );
+
+ static bool isNumeric( const char *str );
+ bool isNumeric( void ) const;
+
+ void CapLength ( int );
+
+ void BackSlashesToSlashes ();
+
+};
+
+inline idStr::~idStr()
+ {
+ if ( m_data )
+ {
+ m_data->DelRef ();
+ m_data = NULL;
+ }
+ }
+
+inline idStr::idStr() : m_data ( NULL )
+ {
+ EnsureAlloced ( 1 );
+ m_data->data[ 0 ] = 0;
+ }
+
+inline idStr::idStr
+ (
+ const char *text
+ ) : m_data ( NULL )
+
+ {
+ int len;
+
+ assert( text );
+
+ if ( text )
+ {
+ len = strlen( text );
+ EnsureAlloced ( len + 1 );
+ strcpy( m_data->data, text );
+ m_data->len = len;
+ }
+ else
+ {
+ EnsureAlloced ( 1 );
+ m_data->data[ 0 ] = 0;
+ m_data->len = 0;
+ }
+ }
+
+inline idStr::idStr
+ (
+ const idStr& text
+ ) : m_data ( NULL )
+
+ {
+ m_data = text.m_data;
+ m_data->AddRef ();
+ }
+
+inline idStr::idStr
+ (
+ const idStr text,
+ int start,
+ int end
+ ) : m_data ( NULL )
+
+ {
+ int i;
+ int len;
+
+ if ( end > text.length() )
+ {
+ end = text.length();
+ }
+
+ if ( start > text.length() )
+ {
+ start = text.length();
+ }
+
+ len = end - start;
+ if ( len < 0 )
+ {
+ len = 0;
+ }
+
+ EnsureAlloced ( len + 1 );
+
+ for( i = 0; i < len; i++ )
+ {
+ m_data->data[ i ] = text[ start + i ];
+ }
+
+ m_data->data[ len ] = 0;
+ m_data->len = len;
+ }
+
+inline idStr::idStr
+ (
+ const char ch
+ ) : m_data ( NULL )
+
+ {
+ EnsureAlloced ( 2 );
+
+ m_data->data[ 0 ] = ch;
+ m_data->data[ 1 ] = 0;
+ m_data->len = 1;
+ }
+
+inline idStr::idStr
+ (
+ const float num
+ ) : m_data ( NULL )
+
+ {
+ char text[ 32 ];
+ int len;
+
+ sprintf( text, "%.3f", num );
+ len = strlen( text );
+ EnsureAlloced( len + 1 );
+ strcpy( m_data->data, text );
+ m_data->len = len;
+ }
+
+inline idStr::idStr
+ (
+ const int num
+ ) : m_data ( NULL )
+
+ {
+ char text[ 32 ];
+ int len;
+
+ sprintf( text, "%d", num );
+ len = strlen( text );
+ EnsureAlloced( len + 1 );
+ strcpy( m_data->data, text );
+ m_data->len = len;
+ }
+
+inline idStr::idStr
+ (
+ const unsigned num
+ ) : m_data ( NULL )
+
+ {
+ char text[ 32 ];
+ int len;
+
+ sprintf( text, "%u", num );
+ len = strlen( text );
+ EnsureAlloced( len + 1 );
+ strcpy( m_data->data, text );
+ m_data->len = len;
+ }
+
+inline int idStr::length( void ) const
+ {
+ return ( m_data != NULL ) ? m_data->len : 0;
+ }
+
+inline int idStr::allocated( void ) const
+ {
+ return ( m_data != NULL ) ? m_data->alloced + sizeof( *m_data ) : 0;
+ }
+
+inline const char *idStr::c_str( void ) const
+ {
+ assert( m_data );
+
+ return m_data->data;
+ }
+
+inline void idStr::append
+ (
+ const char *text
+ )
+
+ {
+ int len;
+
+ assert( text );
+
+ if ( text )
+ {
+ len = length() + strlen( text );
+ EnsureAlloced( len + 1 );
+
+ strcat( m_data->data, text );
+ m_data->len = len;
+ }
+ }
+
+inline void idStr::append
+ (
+ const idStr& text
+ )
+
+ {
+ int len;
+
+ len = length() + text.length();
+ EnsureAlloced ( len + 1 );
+
+ strcat ( m_data->data, text.c_str () );
+ m_data->len = len;
+ }
+
+inline char idStr::operator[]( int index ) const
+ {
+ assert ( m_data );
+
+ if ( !m_data )
+ return 0;
+
+ // don't include the '/0' in the test, because technically, it's out of bounds
+ assert( ( index >= 0 ) && ( index < m_data->len ) );
+
+ // In release mode, give them a null character
+ // don't include the '/0' in the test, because technically, it's out of bounds
+ if ( ( index < 0 ) || ( index >= m_data->len ) )
+ {
+ return 0;
+ }
+
+ return m_data->data[ index ];
+ }
+
+inline char& idStr::operator[]
+ (
+ int index
+ )
+
+ {
+ // Used for result for invalid indices
+ static char dummy = 0;
+ assert ( m_data );
+
+ // We don't know if they'll write to it or not
+ // if it's not a const object
+ EnsureDataWritable ();
+
+ if ( !m_data )
+ return dummy;
+
+ // don't include the '/0' in the test, because technically, it's out of bounds
+ assert( ( index >= 0 ) && ( index < m_data->len ) );
+
+ // In release mode, let them change a safe variable
+ // don't include the '/0' in the test, because technically, it's out of bounds
+ if ( ( index < 0 ) || ( index >= m_data->len ) )
+ {
+ return dummy;
+ }
+
+ return m_data->data[ index ];
+ }
+
+inline void idStr::operator=
+ (
+ const idStr& text
+ )
+
+ {
+ // adding the reference before deleting our current reference prevents
+ // us from deleting our string if we are copying from ourself
+ text.m_data->AddRef();
+ m_data->DelRef();
+ m_data = text.m_data;
+ }
+
+inline void idStr::operator=
+ (
+ const char *text
+ )
+
+ {
+ int len;
+
+ assert( text );
+
+ if ( !text )
+ {
+ // safe behaviour if NULL
+ EnsureAlloced ( 1, false );
+ m_data->data[0] = 0;
+ m_data->len = 0;
+ return;
+ }
+
+ if ( !m_data )
+ {
+ len = strlen ( text );
+ EnsureAlloced( len + 1, false );
+ strcpy ( m_data->data, text );
+ m_data->len = len;
+ return;
+ }
+
+ if ( text == m_data->data )
+ return; // Copying same thing. Punt.
+
+ // If we alias and I don't do this, I could corrupt other strings... This
+ // will get called with EnsureAlloced anyway
+ EnsureDataWritable ();
+
+ // Now we need to check if we're aliasing..
+ if ( text >= m_data->data && text <= m_data->data + m_data->len )
+ {
+ // Great, we're aliasing. We're copying from inside ourselves.
+ // This means that I don't have to ensure that anything is alloced,
+ // though I'll assert just in case.
+ int diff = text - m_data->data;
+ int i;
+
+ assert ( strlen ( text ) < (unsigned) m_data->len );
+
+ for ( i = 0; text[i]; i++ )
+ {
+ m_data->data[i] = text[i];
+ }
+
+ m_data->data[i] = 0;
+
+ m_data->len -= diff;
+
+ return;
+ }
+
+ len = strlen( text );
+ EnsureAlloced ( len + 1, false );
+ strcpy( m_data->data, text );
+ m_data->len = len;
+ }
+
+inline idStr operator+
+ (
+ const idStr& a,
+ const idStr& b
+ )
+
+ {
+ idStr result( a );
+
+ result.append( b );
+
+ return result;
+ }
+
+inline idStr operator+
+ (
+ const idStr& a,
+ const char *b
+ )
+
+ {
+ idStr result( a );
+
+ result.append( b );
+
+ return result;
+ }
+
+inline idStr operator+
+ (
+ const char *a,
+ const idStr& b
+ )
+
+ {
+ idStr result( a );
+
+ result.append( b );
+
+ return result;
+ }
+
+inline idStr operator+
+ (
+ const idStr& a,
+ const bool b
+ )
+
+ {
+ idStr result( a );
+
+ result.append( b ? "true" : "false" );
+
+ return result;
+ }
+
+inline idStr operator+
+ (
+ const idStr& a,
+ const char b
+ )
+
+ {
+ char text[ 2 ];
+
+ text[ 0 ] = b;
+ text[ 1 ] = 0;
+
+ return a + text;
+ }
+
+inline idStr& idStr::operator+=
+ (
+ const idStr& a
+ )
+
+ {
+ append( a );
+ return *this;
+ }
+
+inline idStr& idStr::operator+=
+ (
+ const char *a
+ )
+
+ {
+ append( a );
+ return *this;
+ }
+
+inline idStr& idStr::operator+=
+ (
+ const char a
+ )
+
+ {
+ char text[ 2 ];
+
+ text[ 0 ] = a;
+ text[ 1 ] = 0;
+ append( text );
+
+ return *this;
+ }
+
+inline idStr& idStr::operator+=
+ (
+ const bool a
+ )
+
+ {
+ append( a ? "true" : "false" );
+ return *this;
+ }
+
+inline bool operator==
+ (
+ const idStr& a,
+ const idStr& b
+ )
+
+ {
+ return ( !strcmp( a.c_str(), b.c_str() ) );
+ }
+
+inline bool operator==
+ (
+ const idStr& a,
+ const char *b
+ )
+
+ {
+ assert( b );
+ if ( !b )
+ {
+ return false;
+ }
+ return ( !strcmp( a.c_str(), b ) );
+ }
+
+inline bool operator==
+ (
+ const char *a,
+ const idStr& b
+ )
+
+ {
+ assert( a );
+ if ( !a )
+ {
+ return false;
+ }
+ return ( !strcmp( a, b.c_str() ) );
+ }
+
+inline bool operator!=
+ (
+ const idStr& a,
+ const idStr& b
+ )
+
+ {
+ return !( a == b );
+ }
+
+inline bool operator!=
+ (
+ const idStr& a,
+ const char *b
+ )
+
+ {
+ return !( a == b );
+ }
+
+inline bool operator!=
+ (
+ const char *a,
+ const idStr& b
+ )
+
+ {
+ return !( a == b );
+ }
+
+inline int idStr::icmpn
+ (
+ const char *text,
+ int n
+ ) const
+
+ {
+ assert( m_data );
+ assert( text );
+
+ return idStr::icmpn( m_data->data, text, n );
+ }
+
+inline int idStr::icmpn
+ (
+ const idStr& text,
+ int n
+ ) const
+
+ {
+ assert( m_data );
+ assert( text.m_data );
+
+ return idStr::icmpn( m_data->data, text.m_data->data, n );
+ }
+
+inline int idStr::icmp
+ (
+ const char *text
+ ) const
+
+ {
+ assert( m_data );
+ assert( text );
+
+ return idStr::icmp( m_data->data, text );
+ }
+
+inline int idStr::icmp
+ (
+ const idStr& text
+ ) const
+
+ {
+ assert( c_str () );
+ assert( text.c_str () );
+
+ return idStr::icmp( c_str () , text.c_str () );
+ }
+
+inline int idStr::cmp
+ (
+ const char *text
+ ) const
+
+ {
+ assert( m_data );
+ assert( text );
+
+ return idStr::cmp( m_data->data, text );
+ }
+
+inline int idStr::cmp
+ (
+ const idStr& text
+ ) const
+
+ {
+ assert( c_str () );
+ assert( text.c_str () );
+
+ return idStr::cmp( c_str () , text.c_str () );
+ }
+
+inline int idStr::cmpn
+ (
+ const char *text,
+ int n
+ ) const
+
+ {
+ assert( c_str () );
+ assert( text );
+
+ return idStr::cmpn( c_str () , text, n );
+ }
+
+inline int idStr::cmpn
+ (
+ const idStr& text,
+ int n
+ ) const
+
+ {
+ assert( c_str () );
+ assert( text.c_str () );
+
+ return idStr::cmpn( c_str () , text.c_str () , n );
+ }
+
+inline void idStr::tolower
+ (
+ void
+ )
+
+ {
+ assert( m_data );
+
+ EnsureDataWritable ();
+
+ idStr::toLower( m_data->data );
+ }
+
+inline void idStr::toupper
+ (
+ void
+ )
+
+ {
+ assert( m_data );
+
+ EnsureDataWritable ();
+
+ idStr::toUpper( m_data->data );
+ }
+
+inline bool idStr::isNumeric
+ (
+ void
+ ) const
+
+ {
+ assert( m_data );
+ return idStr::isNumeric( m_data->data );
+ }
+
+inline idStr::operator const char *() {
+ return c_str();
+}
+
+inline idStr::operator const char *
+ (
+ void
+ ) const
+
+ {
+ return c_str ();
+ }
+
+#endif
diff --git a/code/ui/Conscript b/code/ui/Conscript
new file mode 100755
index 0000000..94715d9
--- /dev/null
+++ b/code/ui/Conscript
@@ -0,0 +1,62 @@
+# TA ui building
+
+# qvm building against native:
+# only native has ui_syscalls.c
+# qvm uses a custom ui_syscalls.asm with equ stubs
+# qvm has additional bg_lib.c
+
+Import qw( BASE_CFLAGS TARGET_DIR INSTALL_DIR NO_VM NO_SO CC CXX LINK );
+
+$env = new cons(
+ # the code has the very bad habit of doing things like #include "../ui/ui_shared.h"
+ # this seems to confuse the dependency analysis, explicit toplevel includes seem to fix
+ CPPPATH => '#cgame:#game:#ui',
+ CC => $CC,
+ CXX => $CXX,
+ LINK => $LINK,
+ ENV => { PATH => $ENV{PATH}, HOME => $ENV{HOME} },
+ CFLAGS => $BASE_CFLAGS . '-DMISSIONPACK -fPIC',
+ LDFLAGS => '-shared -ldl -lm'
+);
+
+# qvm building
+# we heavily customize the cons environment
+$vm_env = new cons(
+ # the code has the very bad habit of doing things like #include "../ui/ui_shared.h"
+ # this seems to confuse the dependency analysis, explicit toplevel includes seem to fix
+ CPPPATH => '#cgame:#game:#ui',
+ CC => 'q3lcc',
+ CCCOM => '%CC %CFLAGS %_IFLAGS -c %< -o %>',
+ SUFOBJ => '.asm',
+ LINK => 'q3asm',
+ CFLAGS => '-DQ3_VM -DMISSIONPACK -S -Wf-target=bytecode -Wf-g',
+ # need to know where to find the compiler tools
+ ENV => { PATH => $ENV{PATH} . ":./qvmtools", },
+);
+
+# the file with vmMain function MUST be the first one of the list
+@FILES = qw(
+ ui_main.c
+ ui_atoms.c
+ ui_gameinfo.c
+ ui_players.c
+ ui_util.c
+ ui_shared.c
+ ../game/bg_misc.c
+ ../game/q_math.c
+ ../game/q_shared.c
+ );
+$FILESREF = \@FILES;
+
+if ($NO_SO eq 0)
+{
+ Program $env 'uii386.so', @$FILESREF, 'ui_syscalls.c';
+ Install $env $INSTALL_DIR, 'uii386.so';
+}
+if ($NO_VM eq 0)
+{
+ Depends $vm_env 'ui.qvm', '#qvmtools/q3lcc';
+ Depends $vm_env 'ui.qvm', '#qvmtools/q3asm';
+ Program $vm_env 'ui.qvm', @$FILESREF, '../game/bg_lib.c', 'ui_syscalls.asm';
+ Install $vm_env $INSTALL_DIR . '/vm', 'ui.qvm';
+}
diff --git a/code/ui/compile.bat b/code/ui/compile.bat
new file mode 100755
index 0000000..8299251
--- /dev/null
+++ b/code/ui/compile.bat
@@ -0,0 +1,2 @@
+lcc -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\ui %1
+
diff --git a/code/ui/keycodes.h b/code/ui/keycodes.h
new file mode 100755
index 0000000..a1a0f1f
--- /dev/null
+++ b/code/ui/keycodes.h
@@ -0,0 +1,163 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#ifndef __KEYCODES_H__
+#define __KEYCODES_H__
+
+//
+// these are the key numbers that should be passed to KeyEvent
+//
+
+// normal keys should be passed as lowercased ascii
+
+typedef enum {
+ K_TAB = 9,
+ K_ENTER = 13,
+ K_ESCAPE = 27,
+ K_SPACE = 32,
+
+ K_BACKSPACE = 127,
+
+ K_COMMAND = 128,
+ K_CAPSLOCK,
+ K_POWER,
+ K_PAUSE,
+
+ K_UPARROW,
+ K_DOWNARROW,
+ K_LEFTARROW,
+ K_RIGHTARROW,
+
+ K_ALT,
+ K_CTRL,
+ K_SHIFT,
+ K_INS,
+ K_DEL,
+ K_PGDN,
+ K_PGUP,
+ K_HOME,
+ K_END,
+
+ K_F1,
+ K_F2,
+ K_F3,
+ K_F4,
+ K_F5,
+ K_F6,
+ K_F7,
+ K_F8,
+ K_F9,
+ K_F10,
+ K_F11,
+ K_F12,
+ K_F13,
+ K_F14,
+ K_F15,
+
+ K_KP_HOME,
+ K_KP_UPARROW,
+ K_KP_PGUP,
+ K_KP_LEFTARROW,
+ K_KP_5,
+ K_KP_RIGHTARROW,
+ K_KP_END,
+ K_KP_DOWNARROW,
+ K_KP_PGDN,
+ K_KP_ENTER,
+ K_KP_INS,
+ K_KP_DEL,
+ K_KP_SLASH,
+ K_KP_MINUS,
+ K_KP_PLUS,
+ K_KP_NUMLOCK,
+ K_KP_STAR,
+ K_KP_EQUALS,
+
+ K_MOUSE1,
+ K_MOUSE2,
+ K_MOUSE3,
+ K_MOUSE4,
+ K_MOUSE5,
+
+ K_MWHEELDOWN,
+ K_MWHEELUP,
+
+ K_JOY1,
+ K_JOY2,
+ K_JOY3,
+ K_JOY4,
+ K_JOY5,
+ K_JOY6,
+ K_JOY7,
+ K_JOY8,
+ K_JOY9,
+ K_JOY10,
+ K_JOY11,
+ K_JOY12,
+ K_JOY13,
+ K_JOY14,
+ K_JOY15,
+ K_JOY16,
+ K_JOY17,
+ K_JOY18,
+ K_JOY19,
+ K_JOY20,
+ K_JOY21,
+ K_JOY22,
+ K_JOY23,
+ K_JOY24,
+ K_JOY25,
+ K_JOY26,
+ K_JOY27,
+ K_JOY28,
+ K_JOY29,
+ K_JOY30,
+ K_JOY31,
+ K_JOY32,
+
+ K_AUX1,
+ K_AUX2,
+ K_AUX3,
+ K_AUX4,
+ K_AUX5,
+ K_AUX6,
+ K_AUX7,
+ K_AUX8,
+ K_AUX9,
+ K_AUX10,
+ K_AUX11,
+ K_AUX12,
+ K_AUX13,
+ K_AUX14,
+ K_AUX15,
+ K_AUX16,
+
+ K_LAST_KEY // this had better be <256!
+} keyNum_t;
+
+
+// The menu code needs to get both key and char events, but
+// to avoid duplicating the paths, the char events are just
+// distinguished by or'ing in K_CHAR_FLAG (ugly)
+#define K_CHAR_FLAG 1024
+
+#endif
diff --git a/code/ui/ui.bat b/code/ui/ui.bat
new file mode 100755
index 0000000..11dbb12
--- /dev/null
+++ b/code/ui/ui.bat
@@ -0,0 +1,33 @@
+rem make sure we have a safe environement
+set LIBRARY=
+set INCLUDE=
+
+mkdir vm
+cd vm
+
+set cc=lcc -DMISSIONPACK -DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\..\cgame -I..\..\game -I..\..\ui %1
+
+%cc% ../ui_main.c
+@if errorlevel 1 goto quit
+%cc% ../../game/bg_misc.c
+@if errorlevel 1 goto quit
+%cc% ../../game/bg_lib.c
+@if errorlevel 1 goto quit
+%cc% ../../game/q_math.c
+@if errorlevel 1 goto quit
+%cc% ../../game/q_shared.c
+@if errorlevel 1 goto quit
+%cc% ../ui_atoms.c
+@if errorlevel 1 goto quit
+%cc% ../ui_players.c
+@if errorlevel 1 goto quit
+%cc% ../ui_util.c
+@if errorlevel 1 goto quit
+%cc% ../ui_shared.c
+@if errorlevel 1 goto quit
+%cc% ../ui_gameinfo.c
+@if errorlevel 1 goto quit
+
+q3asm -f ../ui
+:quit
+cd ..
diff --git a/code/ui/ui.def b/code/ui/ui.def
new file mode 100755
index 0000000..01861ba
--- /dev/null
+++ b/code/ui/ui.def
@@ -0,0 +1,3 @@
+EXPORTS
+ vmMain
+ dllEntry
diff --git a/code/ui/ui.q3asm b/code/ui/ui.q3asm
new file mode 100755
index 0000000..fbc75f1
--- /dev/null
+++ b/code/ui/ui.q3asm
@@ -0,0 +1,12 @@
+-o "\quake3\missionpack\vm\ui"
+ui_main
+..\ui_syscalls
+ui_atoms
+ui_players
+ui_util
+ui_shared
+ui_gameinfo
+bg_misc
+bg_lib
+q_math
+q_shared
diff --git a/code/ui/ui.vcproj b/code/ui/ui.vcproj
new file mode 100755
index 0000000..f32a806
--- /dev/null
+++ b/code/ui/ui.vcproj
@@ -0,0 +1,1008 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+ ProjectType="Visual C++"
+ Version="7.10"
+ Name="ui"
+ SccProjectName="&quot;$/MissionPack/code/ui&quot;, AOBAAAAA"
+ SccAuxPath=""
+ SccLocalPath="."
+ SccProvider="MSSCCI:Perforce SCM">
+ <Platforms>
+ <Platform
+ Name="Win32"/>
+ </Platforms>
+ <Configurations>
+ <Configuration
+ Name="vector|Win32"
+ OutputDirectory=".\ui___Win32_vector"
+ IntermediateDirectory=".\ui___Win32_vector"
+ ConfigurationType="2"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ OptimizeForProcessor="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;UI_EXPORTS"
+ StringPooling="TRUE"
+ RuntimeLibrary="4"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\ui___Win32_vector/ui.pch"
+ AssemblerListingLocation=".\ui___Win32_vector/"
+ ObjectFile=".\ui___Win32_vector/"
+ ProgramDataBaseFileName=".\ui___Win32_vector/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="odbc32.lib odbccp32.lib"
+ OutputFile="../Release_TA/uix86.dll"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ ModuleDefinitionFile=".\ui.def"
+ ProgramDatabaseFile=".\ui___Win32_vector/uix86.pdb"
+ GenerateMapFile="TRUE"
+ MapFileName=".\ui___Win32_vector/uix86.map"
+ BaseAddress="0x40000000"
+ ImportLibrary=".\ui___Win32_vector/uix86.lib"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="NDEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\ui___Win32_vector/ui.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Release TA|Win32"
+ OutputDirectory=".\Release_TA"
+ IntermediateDirectory=".\Release_TA"
+ ConfigurationType="2"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ OptimizeForProcessor="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;UI_EXPORTS"
+ StringPooling="TRUE"
+ RuntimeLibrary="4"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Release_TA/ui.pch"
+ AssemblerListingLocation=".\Release_TA/"
+ ObjectFile=".\Release_TA/"
+ ProgramDataBaseFileName=".\Release_TA/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="odbc32.lib odbccp32.lib"
+ OutputFile="../Release_TA/uix86.dll"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ ModuleDefinitionFile=".\ui.def"
+ ProgramDatabaseFile=".\Release_TA/uix86.pdb"
+ GenerateMapFile="TRUE"
+ MapFileName=".\Release_TA/uix86.map"
+ BaseAddress="0x40000000"
+ ImportLibrary=".\Release_TA/uix86.lib"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="NDEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\Release_TA/ui.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Debug|Win32"
+ OutputDirectory=".\Debug"
+ IntermediateDirectory=".\Debug"
+ ConfigurationType="2"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ OptimizeForProcessor="1"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;UI_EXPORTS"
+ BasicRuntimeChecks="3"
+ RuntimeLibrary="1"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Debug/ui.pch"
+ AssemblerListingLocation=".\Debug/"
+ ObjectFile=".\Debug/"
+ ProgramDataBaseFileName=".\Debug/"
+ BrowseInformation="1"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="odbc32.lib odbccp32.lib"
+ OutputFile="../Debug/uix86_new.dll"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile="../Debug/ui.pdb"
+ GenerateMapFile="TRUE"
+ MapFileName=".\Debug/uix86_new.map"
+ BaseAddress="0x40000000"
+ ImportLibrary=".\Debug/uix86_new.lib"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="_DEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\Debug/ui.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Release|Win32"
+ OutputDirectory=".\Release"
+ IntermediateDirectory=".\Release"
+ ConfigurationType="2"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ OptimizeForProcessor="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;UI_EXPORTS"
+ StringPooling="TRUE"
+ RuntimeLibrary="4"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Release/ui.pch"
+ AssemblerListingLocation=".\Release/"
+ ObjectFile=".\Release/"
+ ProgramDataBaseFileName=".\Release/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="odbc32.lib odbccp32.lib"
+ OutputFile="../Release/uix86_new.dll"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ ProgramDatabaseFile=".\Release/uix86_new.pdb"
+ GenerateMapFile="TRUE"
+ MapFileName=".\Release/uix86_new.map"
+ BaseAddress="0x40000000"
+ ImportLibrary=".\Release/uix86_new.lib"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="NDEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\Release/ui.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Debug TA|Win32"
+ OutputDirectory=".\Debug_TA"
+ IntermediateDirectory=".\Debug_TA"
+ ConfigurationType="2"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ OptimizeForProcessor="1"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;UI_EXPORTS;MISSIONPACK"
+ BasicRuntimeChecks="3"
+ RuntimeLibrary="1"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Debug_TA/ui.pch"
+ AssemblerListingLocation=".\Debug_TA/"
+ ObjectFile=".\Debug_TA/"
+ ProgramDataBaseFileName=".\Debug_TA/"
+ BrowseInformation="1"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="odbc32.lib odbccp32.lib"
+ OutputFile="../Debug_TA/uix86.dll"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ ModuleDefinitionFile=".\ui.def"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile="../Debug/ui.pdb"
+ GenerateMapFile="TRUE"
+ MapFileName=".\Debug_TA/uix86.map"
+ BaseAddress="0x40000000"
+ ImportLibrary=".\Debug_TA/uix86.lib"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="_DEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\Debug_TA/ui.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ </Configurations>
+ <References>
+ </References>
+ <Files>
+ <Filter
+ Name="Source Files"
+ Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat">
+ <File
+ RelativePath="..\game\bg_lib.c">
+ <FileConfiguration
+ Name="vector|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;MISSIONPACK;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\game\bg_misc.c">
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;MISSIONPACK;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\game\q_math.c">
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;MISSIONPACK;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\game\q_shared.c">
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;MISSIONPACK;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui.def">
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_atoms.c">
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;MISSIONPACK;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_gameinfo.c">
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;MISSIONPACK;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_main.c">
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;MISSIONPACK;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_players.c">
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;MISSIONPACK;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_shared.c">
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;MISSIONPACK;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_syscalls.c">
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;MISSIONPACK;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_util.c">
+ <FileConfiguration
+ Name="vector|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;$(NoInherit)"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug TA|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;UI_EXPORTS;MISSIONPACK;$(NoInherit)"
+ BasicRuntimeChecks="3"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <Filter
+ Name="Header Files"
+ Filter="h;hpp;hxx;hm;inl">
+ <File
+ RelativePath="..\game\bg_public.h">
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="keycodes.h">
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\..\ui\menudef.h">
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\game\q_shared.h">
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\game\surfaceflags.h">
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\cgame\tr_types.h">
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_local.h">
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_public.h">
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ui_shared.h">
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCustomBuildTool"/>
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <Filter
+ Name="Resource Files"
+ Filter="ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe">
+ </Filter>
+ </Files>
+ <Globals>
+ </Globals>
+</VisualStudioProject>
diff --git a/code/ui/ui_atoms.c b/code/ui/ui_atoms.c
new file mode 100755
index 0000000..66d3270
--- /dev/null
+++ b/code/ui/ui_atoms.c
@@ -0,0 +1,520 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/**********************************************************************
+ UI_ATOMS.C
+
+ User interface building blocks and support functions.
+**********************************************************************/
+#include "ui_local.h"
+
+qboolean m_entersound; // after a frame, so caching won't disrupt the sound
+
+// these are here so the functions in q_shared.c can link
+#ifndef UI_HARD_LINKED
+
+void QDECL Com_Error( int level, const char *error, ... ) {
+ va_list argptr;
+ char text[1024];
+
+ va_start (argptr, error);
+ vsprintf (text, error, argptr);
+ va_end (argptr);
+
+ trap_Error( va("%s", text) );
+}
+
+void QDECL Com_Printf( const char *msg, ... ) {
+ va_list argptr;
+ char text[1024];
+
+ va_start (argptr, msg);
+ vsprintf (text, msg, argptr);
+ va_end (argptr);
+
+ trap_Print( va("%s", text) );
+}
+
+#endif
+
+qboolean newUI = qfalse;
+
+
+/*
+=================
+UI_ClampCvar
+=================
+*/
+float UI_ClampCvar( float min, float max, float value )
+{
+ if ( value < min ) return min;
+ if ( value > max ) return max;
+ return value;
+}
+
+/*
+=================
+UI_StartDemoLoop
+=================
+*/
+void UI_StartDemoLoop( void ) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, "d1\n" );
+}
+
+
+#ifndef MISSIONPACK // bk001206
+static void NeedCDAction( qboolean result ) {
+ if ( !result ) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, "quit\n" );
+ }
+}
+#endif // MISSIONPACK
+
+#ifndef MISSIONPACK // bk001206
+static void NeedCDKeyAction( qboolean result ) {
+ if ( !result ) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, "quit\n" );
+ }
+}
+#endif // MISSIONPACK
+
+char *UI_Argv( int arg ) {
+ static char buffer[MAX_STRING_CHARS];
+
+ trap_Argv( arg, buffer, sizeof( buffer ) );
+
+ return buffer;
+}
+
+
+char *UI_Cvar_VariableString( const char *var_name ) {
+ static char buffer[MAX_STRING_CHARS];
+
+ trap_Cvar_VariableStringBuffer( var_name, buffer, sizeof( buffer ) );
+
+ return buffer;
+}
+
+
+
+void UI_SetBestScores(postGameInfo_t *newInfo, qboolean postGame) {
+ trap_Cvar_Set("ui_scoreAccuracy", va("%i%%", newInfo->accuracy));
+ trap_Cvar_Set("ui_scoreImpressives", va("%i", newInfo->impressives));
+ trap_Cvar_Set("ui_scoreExcellents", va("%i", newInfo->excellents));
+ trap_Cvar_Set("ui_scoreDefends", va("%i", newInfo->defends));
+ trap_Cvar_Set("ui_scoreAssists", va("%i", newInfo->assists));
+ trap_Cvar_Set("ui_scoreGauntlets", va("%i", newInfo->gauntlets));
+ trap_Cvar_Set("ui_scoreScore", va("%i", newInfo->score));
+ trap_Cvar_Set("ui_scorePerfect", va("%i", newInfo->perfects));
+ trap_Cvar_Set("ui_scoreTeam", va("%i to %i", newInfo->redScore, newInfo->blueScore));
+ trap_Cvar_Set("ui_scoreBase", va("%i", newInfo->baseScore));
+ trap_Cvar_Set("ui_scoreTimeBonus", va("%i", newInfo->timeBonus));
+ trap_Cvar_Set("ui_scoreSkillBonus", va("%i", newInfo->skillBonus));
+ trap_Cvar_Set("ui_scoreShutoutBonus", va("%i", newInfo->shutoutBonus));
+ trap_Cvar_Set("ui_scoreTime", va("%02i:%02i", newInfo->time / 60, newInfo->time % 60));
+ trap_Cvar_Set("ui_scoreCaptures", va("%i", newInfo->captures));
+ if (postGame) {
+ trap_Cvar_Set("ui_scoreAccuracy2", va("%i%%", newInfo->accuracy));
+ trap_Cvar_Set("ui_scoreImpressives2", va("%i", newInfo->impressives));
+ trap_Cvar_Set("ui_scoreExcellents2", va("%i", newInfo->excellents));
+ trap_Cvar_Set("ui_scoreDefends2", va("%i", newInfo->defends));
+ trap_Cvar_Set("ui_scoreAssists2", va("%i", newInfo->assists));
+ trap_Cvar_Set("ui_scoreGauntlets2", va("%i", newInfo->gauntlets));
+ trap_Cvar_Set("ui_scoreScore2", va("%i", newInfo->score));
+ trap_Cvar_Set("ui_scorePerfect2", va("%i", newInfo->perfects));
+ trap_Cvar_Set("ui_scoreTeam2", va("%i to %i", newInfo->redScore, newInfo->blueScore));
+ trap_Cvar_Set("ui_scoreBase2", va("%i", newInfo->baseScore));
+ trap_Cvar_Set("ui_scoreTimeBonus2", va("%i", newInfo->timeBonus));
+ trap_Cvar_Set("ui_scoreSkillBonus2", va("%i", newInfo->skillBonus));
+ trap_Cvar_Set("ui_scoreShutoutBonus2", va("%i", newInfo->shutoutBonus));
+ trap_Cvar_Set("ui_scoreTime2", va("%02i:%02i", newInfo->time / 60, newInfo->time % 60));
+ trap_Cvar_Set("ui_scoreCaptures2", va("%i", newInfo->captures));
+ }
+}
+
+void UI_LoadBestScores(const char *map, int game) {
+ char fileName[MAX_QPATH];
+ fileHandle_t f;
+ postGameInfo_t newInfo;
+ memset(&newInfo, 0, sizeof(postGameInfo_t));
+ Com_sprintf(fileName, MAX_QPATH, "games/%s_%i.game", map, game);
+ if (trap_FS_FOpenFile(fileName, &f, FS_READ) >= 0) {
+ int size = 0;
+ trap_FS_Read(&size, sizeof(int), f);
+ if (size == sizeof(postGameInfo_t)) {
+ trap_FS_Read(&newInfo, sizeof(postGameInfo_t), f);
+ }
+ trap_FS_FCloseFile(f);
+ }
+ UI_SetBestScores(&newInfo, qfalse);
+
+ Com_sprintf(fileName, MAX_QPATH, "demos/%s_%d.dm_%d", map, game, (int)trap_Cvar_VariableValue("protocol"));
+ uiInfo.demoAvailable = qfalse;
+ if (trap_FS_FOpenFile(fileName, &f, FS_READ) >= 0) {
+ uiInfo.demoAvailable = qtrue;
+ trap_FS_FCloseFile(f);
+ }
+}
+
+/*
+===============
+UI_ClearScores
+===============
+*/
+void UI_ClearScores() {
+ char gameList[4096];
+ char *gameFile;
+ int i, len, count, size;
+ fileHandle_t f;
+ postGameInfo_t newInfo;
+
+ count = trap_FS_GetFileList( "games", "game", gameList, sizeof(gameList) );
+
+ size = sizeof(postGameInfo_t);
+ memset(&newInfo, 0, size);
+
+ if (count > 0) {
+ gameFile = gameList;
+ for ( i = 0; i < count; i++ ) {
+ len = strlen(gameFile);
+ if (trap_FS_FOpenFile(va("games/%s",gameFile), &f, FS_WRITE) >= 0) {
+ trap_FS_Write(&size, sizeof(int), f);
+ trap_FS_Write(&newInfo, size, f);
+ trap_FS_FCloseFile(f);
+ }
+ gameFile += len + 1;
+ }
+ }
+
+ UI_SetBestScores(&newInfo, qfalse);
+
+}
+
+
+
+static void UI_Cache_f() {
+ Display_CacheAll();
+}
+
+/*
+=======================
+UI_CalcPostGameStats
+=======================
+*/
+static void UI_CalcPostGameStats() {
+ char map[MAX_QPATH];
+ char fileName[MAX_QPATH];
+ char info[MAX_INFO_STRING];
+ fileHandle_t f;
+ int size, game, time, adjustedTime;
+ postGameInfo_t oldInfo;
+ postGameInfo_t newInfo;
+ qboolean newHigh = qfalse;
+
+ trap_GetConfigString( CS_SERVERINFO, info, sizeof(info) );
+ Q_strncpyz( map, Info_ValueForKey( info, "mapname" ), sizeof(map) );
+ game = atoi(Info_ValueForKey(info, "g_gametype"));
+
+ // compose file name
+ Com_sprintf(fileName, MAX_QPATH, "games/%s_%i.game", map, game);
+ // see if we have one already
+ memset(&oldInfo, 0, sizeof(postGameInfo_t));
+ if (trap_FS_FOpenFile(fileName, &f, FS_READ) >= 0) {
+ // if so load it
+ size = 0;
+ trap_FS_Read(&size, sizeof(int), f);
+ if (size == sizeof(postGameInfo_t)) {
+ trap_FS_Read(&oldInfo, sizeof(postGameInfo_t), f);
+ }
+ trap_FS_FCloseFile(f);
+ }
+
+ newInfo.accuracy = atoi(UI_Argv(3));
+ newInfo.impressives = atoi(UI_Argv(4));
+ newInfo.excellents = atoi(UI_Argv(5));
+ newInfo.defends = atoi(UI_Argv(6));
+ newInfo.assists = atoi(UI_Argv(7));
+ newInfo.gauntlets = atoi(UI_Argv(8));
+ newInfo.baseScore = atoi(UI_Argv(9));
+ newInfo.perfects = atoi(UI_Argv(10));
+ newInfo.redScore = atoi(UI_Argv(11));
+ newInfo.blueScore = atoi(UI_Argv(12));
+ time = atoi(UI_Argv(13));
+ newInfo.captures = atoi(UI_Argv(14));
+
+ newInfo.time = (time - trap_Cvar_VariableValue("ui_matchStartTime")) / 1000;
+ adjustedTime = uiInfo.mapList[ui_currentMap.integer].timeToBeat[game];
+ if (newInfo.time < adjustedTime) {
+ newInfo.timeBonus = (adjustedTime - newInfo.time) * 10;
+ } else {
+ newInfo.timeBonus = 0;
+ }
+
+ if (newInfo.redScore > newInfo.blueScore && newInfo.blueScore <= 0) {
+ newInfo.shutoutBonus = 100;
+ } else {
+ newInfo.shutoutBonus = 0;
+ }
+
+ newInfo.skillBonus = trap_Cvar_VariableValue("g_spSkill");
+ if (newInfo.skillBonus <= 0) {
+ newInfo.skillBonus = 1;
+ }
+ newInfo.score = newInfo.baseScore + newInfo.shutoutBonus + newInfo.timeBonus;
+ newInfo.score *= newInfo.skillBonus;
+
+ // see if the score is higher for this one
+ newHigh = (newInfo.redScore > newInfo.blueScore && newInfo.score > oldInfo.score);
+
+ if (newHigh) {
+ // if so write out the new one
+ uiInfo.newHighScoreTime = uiInfo.uiDC.realTime + 20000;
+ if (trap_FS_FOpenFile(fileName, &f, FS_WRITE) >= 0) {
+ size = sizeof(postGameInfo_t);
+ trap_FS_Write(&size, sizeof(int), f);
+ trap_FS_Write(&newInfo, sizeof(postGameInfo_t), f);
+ trap_FS_FCloseFile(f);
+ }
+ }
+
+ if (newInfo.time < oldInfo.time) {
+ uiInfo.newBestTime = uiInfo.uiDC.realTime + 20000;
+ }
+
+ // put back all the ui overrides
+ trap_Cvar_Set("capturelimit", UI_Cvar_VariableString("ui_saveCaptureLimit"));
+ trap_Cvar_Set("fraglimit", UI_Cvar_VariableString("ui_saveFragLimit"));
+ trap_Cvar_Set("cg_drawTimer", UI_Cvar_VariableString("ui_drawTimer"));
+ trap_Cvar_Set("g_doWarmup", UI_Cvar_VariableString("ui_doWarmup"));
+ trap_Cvar_Set("g_Warmup", UI_Cvar_VariableString("ui_Warmup"));
+ trap_Cvar_Set("sv_pure", UI_Cvar_VariableString("ui_pure"));
+ trap_Cvar_Set("g_friendlyFire", UI_Cvar_VariableString("ui_friendlyFire"));
+
+ UI_SetBestScores(&newInfo, qtrue);
+ UI_ShowPostGame(newHigh);
+
+
+}
+
+
+/*
+=================
+UI_ConsoleCommand
+=================
+*/
+qboolean UI_ConsoleCommand( int realTime ) {
+ char *cmd;
+
+ uiInfo.uiDC.frameTime = realTime - uiInfo.uiDC.realTime;
+ uiInfo.uiDC.realTime = realTime;
+
+ cmd = UI_Argv( 0 );
+
+ // ensure minimum menu data is available
+ //Menu_Cache();
+
+ if ( Q_stricmp (cmd, "ui_test") == 0 ) {
+ UI_ShowPostGame(qtrue);
+ }
+
+ if ( Q_stricmp (cmd, "ui_report") == 0 ) {
+ UI_Report();
+ return qtrue;
+ }
+
+ if ( Q_stricmp (cmd, "ui_load") == 0 ) {
+ UI_Load();
+ return qtrue;
+ }
+
+ if ( Q_stricmp (cmd, "remapShader") == 0 ) {
+ if (trap_Argc() == 4) {
+ char shader1[MAX_QPATH];
+ char shader2[MAX_QPATH];
+ Q_strncpyz(shader1, UI_Argv(1), sizeof(shader1));
+ Q_strncpyz(shader2, UI_Argv(2), sizeof(shader2));
+ trap_R_RemapShader(shader1, shader2, UI_Argv(3));
+ return qtrue;
+ }
+ }
+
+ if ( Q_stricmp (cmd, "postgame") == 0 ) {
+ UI_CalcPostGameStats();
+ return qtrue;
+ }
+
+ if ( Q_stricmp (cmd, "ui_cache") == 0 ) {
+ UI_Cache_f();
+ return qtrue;
+ }
+
+ if ( Q_stricmp (cmd, "ui_teamOrders") == 0 ) {
+ //UI_TeamOrdersMenu_f();
+ return qtrue;
+ }
+
+
+ if ( Q_stricmp (cmd, "ui_cdkey") == 0 ) {
+ //UI_CDKeyMenu_f();
+ return qtrue;
+ }
+
+ return qfalse;
+}
+
+/*
+=================
+UI_Shutdown
+=================
+*/
+void UI_Shutdown( void ) {
+}
+
+/*
+================
+UI_AdjustFrom640
+
+Adjusted for resolution and screen aspect ratio
+================
+*/
+void UI_AdjustFrom640( float *x, float *y, float *w, float *h ) {
+ // expect valid pointers
+#if 0
+ *x = *x * uiInfo.uiDC.scale + uiInfo.uiDC.bias;
+ *y *= uiInfo.uiDC.scale;
+ *w *= uiInfo.uiDC.scale;
+ *h *= uiInfo.uiDC.scale;
+#endif
+
+ *x *= uiInfo.uiDC.xscale;
+ *y *= uiInfo.uiDC.yscale;
+ *w *= uiInfo.uiDC.xscale;
+ *h *= uiInfo.uiDC.yscale;
+
+}
+
+void UI_DrawNamedPic( float x, float y, float width, float height, const char *picname ) {
+ qhandle_t hShader;
+
+ hShader = trap_R_RegisterShaderNoMip( picname );
+ UI_AdjustFrom640( &x, &y, &width, &height );
+ trap_R_DrawStretchPic( x, y, width, height, 0, 0, 1, 1, hShader );
+}
+
+void UI_DrawHandlePic( float x, float y, float w, float h, qhandle_t hShader ) {
+ float s0;
+ float s1;
+ float t0;
+ float t1;
+
+ if( w < 0 ) { // flip about vertical
+ w = -w;
+ s0 = 1;
+ s1 = 0;
+ }
+ else {
+ s0 = 0;
+ s1 = 1;
+ }
+
+ if( h < 0 ) { // flip about horizontal
+ h = -h;
+ t0 = 1;
+ t1 = 0;
+ }
+ else {
+ t0 = 0;
+ t1 = 1;
+ }
+
+ UI_AdjustFrom640( &x, &y, &w, &h );
+ trap_R_DrawStretchPic( x, y, w, h, s0, t0, s1, t1, hShader );
+}
+
+/*
+================
+UI_FillRect
+
+Coordinates are 640*480 virtual values
+=================
+*/
+void UI_FillRect( float x, float y, float width, float height, const float *color ) {
+ trap_R_SetColor( color );
+
+ UI_AdjustFrom640( &x, &y, &width, &height );
+ trap_R_DrawStretchPic( x, y, width, height, 0, 0, 0, 0, uiInfo.uiDC.whiteShader );
+
+ trap_R_SetColor( NULL );
+}
+
+void UI_DrawSides(float x, float y, float w, float h) {
+ UI_AdjustFrom640( &x, &y, &w, &h );
+ trap_R_DrawStretchPic( x, y, 1, h, 0, 0, 0, 0, uiInfo.uiDC.whiteShader );
+ trap_R_DrawStretchPic( x + w - 1, y, 1, h, 0, 0, 0, 0, uiInfo.uiDC.whiteShader );
+}
+
+void UI_DrawTopBottom(float x, float y, float w, float h) {
+ UI_AdjustFrom640( &x, &y, &w, &h );
+ trap_R_DrawStretchPic( x, y, w, 1, 0, 0, 0, 0, uiInfo.uiDC.whiteShader );
+ trap_R_DrawStretchPic( x, y + h - 1, w, 1, 0, 0, 0, 0, uiInfo.uiDC.whiteShader );
+}
+/*
+================
+UI_DrawRect
+
+Coordinates are 640*480 virtual values
+=================
+*/
+void UI_DrawRect( float x, float y, float width, float height, const float *color ) {
+ trap_R_SetColor( color );
+
+ UI_DrawTopBottom(x, y, width, height);
+ UI_DrawSides(x, y, width, height);
+
+ trap_R_SetColor( NULL );
+}
+
+void UI_SetColor( const float *rgba ) {
+ trap_R_SetColor( rgba );
+}
+
+void UI_UpdateScreen( void ) {
+ trap_UpdateScreen();
+}
+
+
+void UI_DrawTextBox (int x, int y, int width, int lines)
+{
+ UI_FillRect( x + BIGCHAR_WIDTH/2, y + BIGCHAR_HEIGHT/2, ( width + 1 ) * BIGCHAR_WIDTH, ( lines + 1 ) * BIGCHAR_HEIGHT, colorBlack );
+ UI_DrawRect( x + BIGCHAR_WIDTH/2, y + BIGCHAR_HEIGHT/2, ( width + 1 ) * BIGCHAR_WIDTH, ( lines + 1 ) * BIGCHAR_HEIGHT, colorWhite );
+}
+
+qboolean UI_CursorInRect (int x, int y, int width, int height)
+{
+ if (uiInfo.uiDC.cursorx < x ||
+ uiInfo.uiDC.cursory < y ||
+ uiInfo.uiDC.cursorx > x+width ||
+ uiInfo.uiDC.cursory > y+height)
+ return qfalse;
+
+ return qtrue;
+}
diff --git a/code/ui/ui_gameinfo.c b/code/ui/ui_gameinfo.c
new file mode 100755
index 0000000..e04c8a4
--- /dev/null
+++ b/code/ui/ui_gameinfo.c
@@ -0,0 +1,324 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+//
+// gameinfo.c
+//
+
+#include "ui_local.h"
+
+
+//
+// arena and bot info
+//
+
+
+int ui_numBots;
+static char *ui_botInfos[MAX_BOTS];
+
+static int ui_numArenas;
+static char *ui_arenaInfos[MAX_ARENAS];
+
+#ifndef MISSIONPACK // bk001206
+static int ui_numSinglePlayerArenas;
+static int ui_numSpecialSinglePlayerArenas;
+#endif
+
+/*
+===============
+UI_ParseInfos
+===============
+*/
+int UI_ParseInfos( char *buf, int max, char *infos[] ) {
+ char *token;
+ int count;
+ char key[MAX_TOKEN_CHARS];
+ char info[MAX_INFO_STRING];
+
+ count = 0;
+
+ while ( 1 ) {
+ token = COM_Parse( &buf );
+ if ( !token[0] ) {
+ break;
+ }
+ if ( strcmp( token, "{" ) ) {
+ Com_Printf( "Missing { in info file\n" );
+ break;
+ }
+
+ if ( count == max ) {
+ Com_Printf( "Max infos exceeded\n" );
+ break;
+ }
+
+ info[0] = '\0';
+ while ( 1 ) {
+ token = COM_ParseExt( &buf, qtrue );
+ if ( !token[0] ) {
+ Com_Printf( "Unexpected end of info file\n" );
+ break;
+ }
+ if ( !strcmp( token, "}" ) ) {
+ break;
+ }
+ Q_strncpyz( key, token, sizeof( key ) );
+
+ token = COM_ParseExt( &buf, qfalse );
+ if ( !token[0] ) {
+ strcpy( token, "<NULL>" );
+ }
+ Info_SetValueForKey( info, key, token );
+ }
+ //NOTE: extra space for arena number
+ infos[count] = UI_Alloc(strlen(info) + strlen("\\num\\") + strlen(va("%d", MAX_ARENAS)) + 1);
+ if (infos[count]) {
+ strcpy(infos[count], info);
+ count++;
+ }
+ }
+ return count;
+}
+
+/*
+===============
+UI_LoadArenasFromFile
+===============
+*/
+static void UI_LoadArenasFromFile( char *filename ) {
+ int len;
+ fileHandle_t f;
+ char buf[MAX_ARENAS_TEXT];
+
+ len = trap_FS_FOpenFile( filename, &f, FS_READ );
+ if ( !f ) {
+ trap_Print( va( S_COLOR_RED "file not found: %s\n", filename ) );
+ return;
+ }
+ if ( len >= MAX_ARENAS_TEXT ) {
+ trap_Print( va( S_COLOR_RED "file too large: %s is %i, max allowed is %i", filename, len, MAX_ARENAS_TEXT ) );
+ trap_FS_FCloseFile( f );
+ return;
+ }
+
+ trap_FS_Read( buf, len, f );
+ buf[len] = 0;
+ trap_FS_FCloseFile( f );
+
+ ui_numArenas += UI_ParseInfos( buf, MAX_ARENAS - ui_numArenas, &ui_arenaInfos[ui_numArenas] );
+}
+
+/*
+===============
+UI_LoadArenas
+===============
+*/
+void UI_LoadArenas( void ) {
+ int numdirs;
+ vmCvar_t arenasFile;
+ char filename[128];
+ char dirlist[1024];
+ char* dirptr;
+ int i, n;
+ int dirlen;
+ char *type;
+
+ ui_numArenas = 0;
+ uiInfo.mapCount = 0;
+
+ trap_Cvar_Register( &arenasFile, "g_arenasFile", "", CVAR_INIT|CVAR_ROM );
+ if( *arenasFile.string ) {
+ UI_LoadArenasFromFile(arenasFile.string);
+ }
+ else {
+ UI_LoadArenasFromFile("scripts/arenas.txt");
+ }
+
+ // get all arenas from .arena files
+ numdirs = trap_FS_GetFileList("scripts", ".arena", dirlist, 1024 );
+ dirptr = dirlist;
+ for (i = 0; i < numdirs; i++, dirptr += dirlen+1) {
+ dirlen = strlen(dirptr);
+ strcpy(filename, "scripts/");
+ strcat(filename, dirptr);
+ UI_LoadArenasFromFile(filename);
+ }
+ trap_Print( va( "%i arenas parsed\n", ui_numArenas ) );
+ if (UI_OutOfMemory()) {
+ trap_Print(S_COLOR_YELLOW"WARNING: not anough memory in pool to load all arenas\n");
+ }
+
+ for( n = 0; n < ui_numArenas; n++ ) {
+ // determine type
+
+ uiInfo.mapList[uiInfo.mapCount].cinematic = -1;
+ uiInfo.mapList[uiInfo.mapCount].mapLoadName = String_Alloc(Info_ValueForKey(ui_arenaInfos[n], "map"));
+ uiInfo.mapList[uiInfo.mapCount].mapName = String_Alloc(Info_ValueForKey(ui_arenaInfos[n], "longname"));
+ uiInfo.mapList[uiInfo.mapCount].levelShot = -1;
+ uiInfo.mapList[uiInfo.mapCount].imageName = String_Alloc(va("levelshots/%s", uiInfo.mapList[uiInfo.mapCount].mapLoadName));
+ uiInfo.mapList[uiInfo.mapCount].typeBits = 0;
+
+ type = Info_ValueForKey( ui_arenaInfos[n], "type" );
+ // if no type specified, it will be treated as "ffa"
+ if( *type ) {
+ if( strstr( type, "ffa" ) ) {
+ uiInfo.mapList[uiInfo.mapCount].typeBits |= (1 << GT_FFA);
+ }
+ if( strstr( type, "tourney" ) ) {
+ uiInfo.mapList[uiInfo.mapCount].typeBits |= (1 << GT_TOURNAMENT);
+ }
+ if( strstr( type, "ctf" ) ) {
+ uiInfo.mapList[uiInfo.mapCount].typeBits |= (1 << GT_CTF);
+ }
+ if( strstr( type, "oneflag" ) ) {
+ uiInfo.mapList[uiInfo.mapCount].typeBits |= (1 << GT_1FCTF);
+ }
+ if( strstr( type, "overload" ) ) {
+ uiInfo.mapList[uiInfo.mapCount].typeBits |= (1 << GT_OBELISK);
+ }
+ if( strstr( type, "harvester" ) ) {
+ uiInfo.mapList[uiInfo.mapCount].typeBits |= (1 << GT_HARVESTER);
+ }
+ } else {
+ uiInfo.mapList[uiInfo.mapCount].typeBits |= (1 << GT_FFA);
+ }
+
+ uiInfo.mapCount++;
+ if (uiInfo.mapCount >= MAX_MAPS) {
+ break;
+ }
+ }
+}
+
+
+/*
+===============
+UI_LoadBotsFromFile
+===============
+*/
+static void UI_LoadBotsFromFile( char *filename ) {
+ int len;
+ fileHandle_t f;
+ char buf[MAX_BOTS_TEXT];
+
+ len = trap_FS_FOpenFile( filename, &f, FS_READ );
+ if ( !f ) {
+ trap_Print( va( S_COLOR_RED "file not found: %s\n", filename ) );
+ return;
+ }
+ if ( len >= MAX_BOTS_TEXT ) {
+ trap_Print( va( S_COLOR_RED "file too large: %s is %i, max allowed is %i", filename, len, MAX_BOTS_TEXT ) );
+ trap_FS_FCloseFile( f );
+ return;
+ }
+
+ trap_FS_Read( buf, len, f );
+ buf[len] = 0;
+ trap_FS_FCloseFile( f );
+
+ COM_Compress(buf);
+
+ ui_numBots += UI_ParseInfos( buf, MAX_BOTS - ui_numBots, &ui_botInfos[ui_numBots] );
+}
+
+/*
+===============
+UI_LoadBots
+===============
+*/
+void UI_LoadBots( void ) {
+ vmCvar_t botsFile;
+ int numdirs;
+ char filename[128];
+ char dirlist[1024];
+ char* dirptr;
+ int i;
+ int dirlen;
+
+ ui_numBots = 0;
+
+ trap_Cvar_Register( &botsFile, "g_botsFile", "", CVAR_INIT|CVAR_ROM );
+ if( *botsFile.string ) {
+ UI_LoadBotsFromFile(botsFile.string);
+ }
+ else {
+ UI_LoadBotsFromFile("scripts/bots.txt");
+ }
+
+ // get all bots from .bot files
+ numdirs = trap_FS_GetFileList("scripts", ".bot", dirlist, 1024 );
+ dirptr = dirlist;
+ for (i = 0; i < numdirs; i++, dirptr += dirlen+1) {
+ dirlen = strlen(dirptr);
+ strcpy(filename, "scripts/");
+ strcat(filename, dirptr);
+ UI_LoadBotsFromFile(filename);
+ }
+ trap_Print( va( "%i bots parsed\n", ui_numBots ) );
+}
+
+
+/*
+===============
+UI_GetBotInfoByNumber
+===============
+*/
+char *UI_GetBotInfoByNumber( int num ) {
+ if( num < 0 || num >= ui_numBots ) {
+ trap_Print( va( S_COLOR_RED "Invalid bot number: %i\n", num ) );
+ return NULL;
+ }
+ return ui_botInfos[num];
+}
+
+
+/*
+===============
+UI_GetBotInfoByName
+===============
+*/
+char *UI_GetBotInfoByName( const char *name ) {
+ int n;
+ char *value;
+
+ for ( n = 0; n < ui_numBots ; n++ ) {
+ value = Info_ValueForKey( ui_botInfos[n], "name" );
+ if ( !Q_stricmp( value, name ) ) {
+ return ui_botInfos[n];
+ }
+ }
+
+ return NULL;
+}
+
+int UI_GetNumBots() {
+ return ui_numBots;
+}
+
+
+char *UI_GetBotNameByNumber( int num ) {
+ char *info = UI_GetBotInfoByNumber(num);
+ if (info) {
+ return Info_ValueForKey( info, "name" );
+ }
+ return "Sarge";
+}
diff --git a/code/ui/ui_local.h b/code/ui/ui_local.h
new file mode 100755
index 0000000..6889598
--- /dev/null
+++ b/code/ui/ui_local.h
@@ -0,0 +1,1136 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#ifndef __UI_LOCAL_H__
+#define __UI_LOCAL_H__
+
+#include "../game/q_shared.h"
+#include "../cgame/tr_types.h"
+#include "ui_public.h"
+#include "keycodes.h"
+#include "../game/bg_public.h"
+#include "ui_shared.h"
+
+// global display context
+
+extern vmCvar_t ui_ffa_fraglimit;
+extern vmCvar_t ui_ffa_timelimit;
+
+extern vmCvar_t ui_tourney_fraglimit;
+extern vmCvar_t ui_tourney_timelimit;
+
+extern vmCvar_t ui_team_fraglimit;
+extern vmCvar_t ui_team_timelimit;
+extern vmCvar_t ui_team_friendly;
+
+extern vmCvar_t ui_ctf_capturelimit;
+extern vmCvar_t ui_ctf_timelimit;
+extern vmCvar_t ui_ctf_friendly;
+
+extern vmCvar_t ui_arenasFile;
+extern vmCvar_t ui_botsFile;
+extern vmCvar_t ui_spScores1;
+extern vmCvar_t ui_spScores2;
+extern vmCvar_t ui_spScores3;
+extern vmCvar_t ui_spScores4;
+extern vmCvar_t ui_spScores5;
+extern vmCvar_t ui_spAwards;
+extern vmCvar_t ui_spVideos;
+extern vmCvar_t ui_spSkill;
+
+extern vmCvar_t ui_spSelection;
+
+extern vmCvar_t ui_browserMaster;
+extern vmCvar_t ui_browserGameType;
+extern vmCvar_t ui_browserSortKey;
+extern vmCvar_t ui_browserShowFull;
+extern vmCvar_t ui_browserShowEmpty;
+
+extern vmCvar_t ui_brassTime;
+extern vmCvar_t ui_drawCrosshair;
+extern vmCvar_t ui_drawCrosshairNames;
+extern vmCvar_t ui_marks;
+
+extern vmCvar_t ui_server1;
+extern vmCvar_t ui_server2;
+extern vmCvar_t ui_server3;
+extern vmCvar_t ui_server4;
+extern vmCvar_t ui_server5;
+extern vmCvar_t ui_server6;
+extern vmCvar_t ui_server7;
+extern vmCvar_t ui_server8;
+extern vmCvar_t ui_server9;
+extern vmCvar_t ui_server10;
+extern vmCvar_t ui_server11;
+extern vmCvar_t ui_server12;
+extern vmCvar_t ui_server13;
+extern vmCvar_t ui_server14;
+extern vmCvar_t ui_server15;
+extern vmCvar_t ui_server16;
+
+extern vmCvar_t ui_cdkey;
+extern vmCvar_t ui_cdkeychecked;
+
+extern vmCvar_t ui_captureLimit;
+extern vmCvar_t ui_fragLimit;
+extern vmCvar_t ui_gameType;
+extern vmCvar_t ui_netGameType;
+extern vmCvar_t ui_actualNetGameType;
+extern vmCvar_t ui_joinGameType;
+extern vmCvar_t ui_netSource;
+extern vmCvar_t ui_serverFilterType;
+extern vmCvar_t ui_dedicated;
+extern vmCvar_t ui_opponentName;
+extern vmCvar_t ui_menuFiles;
+extern vmCvar_t ui_currentTier;
+extern vmCvar_t ui_currentMap;
+extern vmCvar_t ui_currentNetMap;
+extern vmCvar_t ui_mapIndex;
+extern vmCvar_t ui_currentOpponent;
+extern vmCvar_t ui_selectedPlayer;
+extern vmCvar_t ui_selectedPlayerName;
+extern vmCvar_t ui_lastServerRefresh_0;
+extern vmCvar_t ui_lastServerRefresh_1;
+extern vmCvar_t ui_lastServerRefresh_2;
+extern vmCvar_t ui_lastServerRefresh_3;
+extern vmCvar_t ui_singlePlayerActive;
+extern vmCvar_t ui_scoreAccuracy;
+extern vmCvar_t ui_scoreImpressives;
+extern vmCvar_t ui_scoreExcellents;
+extern vmCvar_t ui_scoreDefends;
+extern vmCvar_t ui_scoreAssists;
+extern vmCvar_t ui_scoreGauntlets;
+extern vmCvar_t ui_scoreScore;
+extern vmCvar_t ui_scorePerfect;
+extern vmCvar_t ui_scoreTeam;
+extern vmCvar_t ui_scoreBase;
+extern vmCvar_t ui_scoreTimeBonus;
+extern vmCvar_t ui_scoreSkillBonus;
+extern vmCvar_t ui_scoreShutoutBonus;
+extern vmCvar_t ui_scoreTime;
+extern vmCvar_t ui_smallFont;
+extern vmCvar_t ui_bigFont;
+extern vmCvar_t ui_serverStatusTimeOut;
+
+
+
+//
+// ui_qmenu.c
+//
+
+#define RCOLUMN_OFFSET ( BIGCHAR_WIDTH )
+#define LCOLUMN_OFFSET (-BIGCHAR_WIDTH )
+
+#define SLIDER_RANGE 10
+#define MAX_EDIT_LINE 256
+
+#define MAX_MENUDEPTH 8
+#define MAX_MENUITEMS 96
+
+#define MTYPE_NULL 0
+#define MTYPE_SLIDER 1
+#define MTYPE_ACTION 2
+#define MTYPE_SPINCONTROL 3
+#define MTYPE_FIELD 4
+#define MTYPE_RADIOBUTTON 5
+#define MTYPE_BITMAP 6
+#define MTYPE_TEXT 7
+#define MTYPE_SCROLLLIST 8
+#define MTYPE_PTEXT 9
+#define MTYPE_BTEXT 10
+
+#define QMF_BLINK 0x00000001
+#define QMF_SMALLFONT 0x00000002
+#define QMF_LEFT_JUSTIFY 0x00000004
+#define QMF_CENTER_JUSTIFY 0x00000008
+#define QMF_RIGHT_JUSTIFY 0x00000010
+#define QMF_NUMBERSONLY 0x00000020 // edit field is only numbers
+#define QMF_HIGHLIGHT 0x00000040
+#define QMF_HIGHLIGHT_IF_FOCUS 0x00000080 // steady focus
+#define QMF_PULSEIFFOCUS 0x00000100 // pulse if focus
+#define QMF_HASMOUSEFOCUS 0x00000200
+#define QMF_NOONOFFTEXT 0x00000400
+#define QMF_MOUSEONLY 0x00000800 // only mouse input allowed
+#define QMF_HIDDEN 0x00001000 // skips drawing
+#define QMF_GRAYED 0x00002000 // grays and disables
+#define QMF_INACTIVE 0x00004000 // disables any input
+#define QMF_NODEFAULTINIT 0x00008000 // skip default initialization
+#define QMF_OWNERDRAW 0x00010000
+#define QMF_PULSE 0x00020000
+#define QMF_LOWERCASE 0x00040000 // edit field is all lower case
+#define QMF_UPPERCASE 0x00080000 // edit field is all upper case
+#define QMF_SILENT 0x00100000
+
+// callback notifications
+#define QM_GOTFOCUS 1
+#define QM_LOSTFOCUS 2
+#define QM_ACTIVATED 3
+
+typedef struct _tag_menuframework
+{
+ int cursor;
+ int cursor_prev;
+
+ int nitems;
+ void *items[MAX_MENUITEMS];
+
+ void (*draw) (void);
+ sfxHandle_t (*key) (int key);
+
+ qboolean wrapAround;
+ qboolean fullscreen;
+ qboolean showlogo;
+} menuframework_s;
+
+typedef struct
+{
+ int type;
+ const char *name;
+ int id;
+ int x, y;
+ int left;
+ int top;
+ int right;
+ int bottom;
+ menuframework_s *parent;
+ int menuPosition;
+ unsigned flags;
+
+ void (*callback)( void *self, int event );
+ void (*statusbar)( void *self );
+ void (*ownerdraw)( void *self );
+} menucommon_s;
+
+typedef struct {
+ int cursor;
+ int scroll;
+ int widthInChars;
+ char buffer[MAX_EDIT_LINE];
+ int maxchars;
+} mfield_t;
+
+typedef struct
+{
+ menucommon_s generic;
+ mfield_t field;
+} menufield_s;
+
+typedef struct
+{
+ menucommon_s generic;
+
+ float minvalue;
+ float maxvalue;
+ float curvalue;
+
+ float range;
+} menuslider_s;
+
+typedef struct
+{
+ menucommon_s generic;
+
+ int oldvalue;
+ int curvalue;
+ int numitems;
+ int top;
+
+ const char **itemnames;
+
+ int width;
+ int height;
+ int columns;
+ int seperation;
+} menulist_s;
+
+typedef struct
+{
+ menucommon_s generic;
+} menuaction_s;
+
+typedef struct
+{
+ menucommon_s generic;
+ int curvalue;
+} menuradiobutton_s;
+
+typedef struct
+{
+ menucommon_s generic;
+ char* focuspic;
+ char* errorpic;
+ qhandle_t shader;
+ qhandle_t focusshader;
+ int width;
+ int height;
+ float* focuscolor;
+} menubitmap_s;
+
+typedef struct
+{
+ menucommon_s generic;
+ char* string;
+ int style;
+ float* color;
+} menutext_s;
+
+extern void Menu_Cache( void );
+extern void Menu_Focus( menucommon_s *m );
+extern void Menu_AddItem( menuframework_s *menu, void *item );
+extern void Menu_AdjustCursor( menuframework_s *menu, int dir );
+extern void Menu_Draw( menuframework_s *menu );
+extern void *Menu_ItemAtCursor( menuframework_s *m );
+extern sfxHandle_t Menu_ActivateItem( menuframework_s *s, menucommon_s* item );
+extern void Menu_SetCursor( menuframework_s *s, int cursor );
+extern void Menu_SetCursorToItem( menuframework_s *m, void* ptr );
+extern sfxHandle_t Menu_DefaultKey( menuframework_s *s, int key );
+extern void Bitmap_Init( menubitmap_s *b );
+extern void Bitmap_Draw( menubitmap_s *b );
+extern void ScrollList_Draw( menulist_s *l );
+extern sfxHandle_t ScrollList_Key( menulist_s *l, int key );
+extern sfxHandle_t menu_in_sound;
+extern sfxHandle_t menu_move_sound;
+extern sfxHandle_t menu_out_sound;
+extern sfxHandle_t menu_buzz_sound;
+extern sfxHandle_t menu_null_sound;
+extern sfxHandle_t weaponChangeSound;
+extern vec4_t menu_text_color;
+extern vec4_t menu_grayed_color;
+extern vec4_t menu_dark_color;
+extern vec4_t menu_highlight_color;
+extern vec4_t menu_red_color;
+extern vec4_t menu_black_color;
+extern vec4_t menu_dim_color;
+extern vec4_t color_black;
+extern vec4_t color_white;
+extern vec4_t color_yellow;
+extern vec4_t color_blue;
+extern vec4_t color_orange;
+extern vec4_t color_red;
+extern vec4_t color_dim;
+extern vec4_t name_color;
+extern vec4_t list_color;
+extern vec4_t listbar_color;
+extern vec4_t text_color_disabled;
+extern vec4_t text_color_normal;
+extern vec4_t text_color_highlight;
+
+extern char *ui_medalNames[];
+extern char *ui_medalPicNames[];
+extern char *ui_medalSounds[];
+
+//
+// ui_mfield.c
+//
+extern void MField_Clear( mfield_t *edit );
+extern void MField_KeyDownEvent( mfield_t *edit, int key );
+extern void MField_CharEvent( mfield_t *edit, int ch );
+extern void MField_Draw( mfield_t *edit, int x, int y, int style, vec4_t color );
+extern void MenuField_Init( menufield_s* m );
+extern void MenuField_Draw( menufield_s *f );
+extern sfxHandle_t MenuField_Key( menufield_s* m, int* key );
+
+//
+// ui_main.c
+//
+void UI_Report();
+void UI_Load();
+void UI_LoadMenus(const char *menuFile, qboolean reset);
+void _UI_SetActiveMenu( uiMenuCommand_t menu );
+int UI_AdjustTimeByGame(int time);
+void UI_ShowPostGame(qboolean newHigh);
+void UI_ClearScores();
+void UI_LoadArenas(void);
+
+//
+// ui_menu.c
+//
+extern void MainMenu_Cache( void );
+extern void UI_MainMenu(void);
+extern void UI_RegisterCvars( void );
+extern void UI_UpdateCvars( void );
+
+//
+// ui_credits.c
+//
+extern void UI_CreditMenu( void );
+
+//
+// ui_ingame.c
+//
+extern void InGame_Cache( void );
+extern void UI_InGameMenu(void);
+
+//
+// ui_confirm.c
+//
+extern void ConfirmMenu_Cache( void );
+extern void UI_ConfirmMenu( const char *question, void (*draw)( void ), void (*action)( qboolean result ) );
+
+//
+// ui_setup.c
+//
+extern void UI_SetupMenu_Cache( void );
+extern void UI_SetupMenu(void);
+
+//
+// ui_team.c
+//
+extern void UI_TeamMainMenu( void );
+extern void TeamMain_Cache( void );
+
+//
+// ui_connect.c
+//
+extern void UI_DrawConnectScreen( qboolean overlay );
+
+//
+// ui_controls2.c
+//
+extern void UI_ControlsMenu( void );
+extern void Controls_Cache( void );
+
+//
+// ui_demo2.c
+//
+extern void UI_DemosMenu( void );
+extern void Demos_Cache( void );
+
+//
+// ui_cinematics.c
+//
+extern void UI_CinematicsMenu( void );
+extern void UI_CinematicsMenu_f( void );
+extern void UI_CinematicsMenu_Cache( void );
+
+//
+// ui_mods.c
+//
+extern void UI_ModsMenu( void );
+extern void UI_ModsMenu_Cache( void );
+
+//
+// ui_cdkey.c
+//
+extern void UI_CDKeyMenu( void );
+extern void UI_CDKeyMenu_Cache( void );
+extern void UI_CDKeyMenu_f( void );
+
+//
+// ui_playermodel.c
+//
+extern void UI_PlayerModelMenu( void );
+extern void PlayerModel_Cache( void );
+
+//
+// ui_playersettings.c
+//
+extern void UI_PlayerSettingsMenu( void );
+extern void PlayerSettings_Cache( void );
+
+//
+// ui_preferences.c
+//
+extern void UI_PreferencesMenu( void );
+extern void Preferences_Cache( void );
+
+//
+// ui_specifyleague.c
+//
+extern void UI_SpecifyLeagueMenu( void );
+extern void SpecifyLeague_Cache( void );
+
+//
+// ui_specifyserver.c
+//
+extern void UI_SpecifyServerMenu( void );
+extern void SpecifyServer_Cache( void );
+
+//
+// ui_servers2.c
+//
+#define MAX_FAVORITESERVERS 16
+
+extern void UI_ArenaServersMenu( void );
+extern void ArenaServers_Cache( void );
+
+//
+// ui_startserver.c
+//
+extern void UI_StartServerMenu( qboolean multiplayer );
+extern void StartServer_Cache( void );
+extern void ServerOptions_Cache( void );
+extern void UI_BotSelectMenu( char *bot );
+extern void UI_BotSelectMenu_Cache( void );
+
+//
+// ui_serverinfo.c
+//
+extern void UI_ServerInfoMenu( void );
+extern void ServerInfo_Cache( void );
+
+//
+// ui_video.c
+//
+extern void UI_GraphicsOptionsMenu( void );
+extern void GraphicsOptions_Cache( void );
+extern void DriverInfo_Cache( void );
+
+//
+// ui_players.c
+//
+
+//FIXME ripped from cg_local.h
+typedef struct {
+ int oldFrame;
+ int oldFrameTime; // time when ->oldFrame was exactly on
+
+ int frame;
+ int frameTime; // time when ->frame will be exactly on
+
+ float backlerp;
+
+ float yawAngle;
+ qboolean yawing;
+ float pitchAngle;
+ qboolean pitching;
+
+ int animationNumber; // may include ANIM_TOGGLEBIT
+ animation_t *animation;
+ int animationTime; // time when the first frame of the animation will be exact
+} lerpFrame_t;
+
+typedef struct {
+ // model info
+ qhandle_t legsModel;
+ qhandle_t legsSkin;
+ lerpFrame_t legs;
+
+ qhandle_t torsoModel;
+ qhandle_t torsoSkin;
+ lerpFrame_t torso;
+
+ qhandle_t headModel;
+ qhandle_t headSkin;
+
+ animation_t animations[MAX_TOTALANIMATIONS];
+
+ qhandle_t weaponModel;
+ qhandle_t barrelModel;
+ qhandle_t flashModel;
+ vec3_t flashDlightColor;
+ int muzzleFlashTime;
+
+ // currently in use drawing parms
+ vec3_t viewAngles;
+ vec3_t moveAngles;
+ weapon_t currentWeapon;
+ int legsAnim;
+ int torsoAnim;
+
+ // animation vars
+ weapon_t weapon;
+ weapon_t lastWeapon;
+ weapon_t pendingWeapon;
+ int weaponTimer;
+ int pendingLegsAnim;
+ int torsoAnimationTimer;
+
+ int pendingTorsoAnim;
+ int legsAnimationTimer;
+
+ qboolean chat;
+ qboolean newModel;
+
+ qboolean barrelSpinning;
+ float barrelAngle;
+ int barrelTime;
+
+ int realWeapon;
+} playerInfo_t;
+
+void UI_DrawPlayer( float x, float y, float w, float h, playerInfo_t *pi, int time );
+void UI_PlayerInfo_SetModel( playerInfo_t *pi, const char *model, const char *headmodel, char *teamName );
+void UI_PlayerInfo_SetInfo( playerInfo_t *pi, int legsAnim, int torsoAnim, vec3_t viewAngles, vec3_t moveAngles, weapon_t weaponNum, qboolean chat );
+qboolean UI_RegisterClientModelname( playerInfo_t *pi, const char *modelSkinName , const char *headName, const char *teamName);
+
+//
+// ui_atoms.c
+//
+// this is only used in the old ui, the new ui has it's own version
+typedef struct {
+ int frametime;
+ int realtime;
+ int cursorx;
+ int cursory;
+ glconfig_t glconfig;
+ qboolean debug;
+ qhandle_t whiteShader;
+ qhandle_t menuBackShader;
+ qhandle_t menuBackShader2;
+ qhandle_t menuBackNoLogoShader;
+ qhandle_t charset;
+ qhandle_t charsetProp;
+ qhandle_t charsetPropGlow;
+ qhandle_t charsetPropB;
+ qhandle_t cursor;
+ qhandle_t rb_on;
+ qhandle_t rb_off;
+ float scale;
+ float bias;
+ qboolean demoversion;
+ qboolean firstdraw;
+} uiStatic_t;
+
+
+// new ui stuff
+#define UI_NUMFX 7
+#define MAX_HEADS 64
+#define MAX_ALIASES 64
+#define MAX_HEADNAME 32
+#define MAX_TEAMS 64
+#define MAX_GAMETYPES 16
+#define MAX_MAPS 128
+#define MAX_SPMAPS 16
+#define PLAYERS_PER_TEAM 5
+#define MAX_PINGREQUESTS 32
+#define MAX_ADDRESSLENGTH 64
+#define MAX_HOSTNAMELENGTH 22
+#define MAX_MAPNAMELENGTH 16
+#define MAX_STATUSLENGTH 64
+#define MAX_LISTBOXWIDTH 59
+#define UI_FONT_THRESHOLD 0.1
+#define MAX_DISPLAY_SERVERS 2048
+#define MAX_SERVERSTATUS_LINES 128
+#define MAX_SERVERSTATUS_TEXT 1024
+#define MAX_FOUNDPLAYER_SERVERS 16
+#define TEAM_MEMBERS 5
+#define GAMES_ALL 0
+#define GAMES_FFA 1
+#define GAMES_TEAMPLAY 2
+#define GAMES_TOURNEY 3
+#define GAMES_CTF 4
+#define MAPS_PER_TIER 3
+#define MAX_TIERS 16
+#define MAX_MODS 64
+#define MAX_DEMOS 256
+#define MAX_MOVIES 256
+#define MAX_PLAYERMODELS 256
+
+
+typedef struct {
+ const char *name;
+ const char *imageName;
+ qhandle_t headImage;
+ const char *base;
+ qboolean active;
+ int reference;
+} characterInfo;
+
+typedef struct {
+ const char *name;
+ const char *ai;
+ const char *action;
+} aliasInfo;
+
+typedef struct {
+ const char *teamName;
+ const char *imageName;
+ const char *teamMembers[TEAM_MEMBERS];
+ qhandle_t teamIcon;
+ qhandle_t teamIcon_Metal;
+ qhandle_t teamIcon_Name;
+ int cinematic;
+} teamInfo;
+
+typedef struct {
+ const char *gameType;
+ int gtEnum;
+} gameTypeInfo;
+
+typedef struct {
+ const char *mapName;
+ const char *mapLoadName;
+ const char *imageName;
+ const char *opponentName;
+ int teamMembers;
+ int typeBits;
+ int cinematic;
+ int timeToBeat[MAX_GAMETYPES];
+ qhandle_t levelShot;
+ qboolean active;
+} mapInfo;
+
+typedef struct {
+ const char *tierName;
+ const char *maps[MAPS_PER_TIER];
+ int gameTypes[MAPS_PER_TIER];
+ qhandle_t mapHandles[MAPS_PER_TIER];
+} tierInfo;
+
+typedef struct serverFilter_s {
+ const char *description;
+ const char *basedir;
+} serverFilter_t;
+
+typedef struct {
+ char adrstr[MAX_ADDRESSLENGTH];
+ int start;
+} pinglist_t;
+
+
+typedef struct serverStatus_s {
+ pinglist_t pingList[MAX_PINGREQUESTS];
+ int numqueriedservers;
+ int currentping;
+ int nextpingtime;
+ int maxservers;
+ int refreshtime;
+ int numServers;
+ int sortKey;
+ int sortDir;
+ int lastCount;
+ qboolean refreshActive;
+ int currentServer;
+ int displayServers[MAX_DISPLAY_SERVERS];
+ int numDisplayServers;
+ int numPlayersOnServers;
+ int nextDisplayRefresh;
+ int nextSortTime;
+ qhandle_t currentServerPreview;
+ int currentServerCinematic;
+ int motdLen;
+ int motdWidth;
+ int motdPaintX;
+ int motdPaintX2;
+ int motdOffset;
+ int motdTime;
+ char motd[MAX_STRING_CHARS];
+} serverStatus_t;
+
+
+typedef struct {
+ char adrstr[MAX_ADDRESSLENGTH];
+ char name[MAX_ADDRESSLENGTH];
+ int startTime;
+ int serverNum;
+ qboolean valid;
+} pendingServer_t;
+
+typedef struct {
+ int num;
+ pendingServer_t server[MAX_SERVERSTATUSREQUESTS];
+} pendingServerStatus_t;
+
+typedef struct {
+ char address[MAX_ADDRESSLENGTH];
+ char *lines[MAX_SERVERSTATUS_LINES][4];
+ char text[MAX_SERVERSTATUS_TEXT];
+ char pings[MAX_CLIENTS * 3];
+ int numLines;
+} serverStatusInfo_t;
+
+typedef struct {
+ const char *modName;
+ const char *modDescr;
+} modInfo_t;
+
+
+typedef struct {
+ displayContextDef_t uiDC;
+ int newHighScoreTime;
+ int newBestTime;
+ int showPostGameTime;
+ qboolean newHighScore;
+ qboolean demoAvailable;
+ qboolean soundHighScore;
+
+ int characterCount;
+ int botIndex;
+ characterInfo characterList[MAX_HEADS];
+
+ int aliasCount;
+ aliasInfo aliasList[MAX_ALIASES];
+
+ int teamCount;
+ teamInfo teamList[MAX_TEAMS];
+
+ int numGameTypes;
+ gameTypeInfo gameTypes[MAX_GAMETYPES];
+
+ int numJoinGameTypes;
+ gameTypeInfo joinGameTypes[MAX_GAMETYPES];
+
+ int redBlue;
+ int playerCount;
+ int myTeamCount;
+ int teamIndex;
+ int playerRefresh;
+ int playerIndex;
+ int playerNumber;
+ qboolean teamLeader;
+ char playerNames[MAX_CLIENTS][MAX_NAME_LENGTH];
+ char teamNames[MAX_CLIENTS][MAX_NAME_LENGTH];
+ int teamClientNums[MAX_CLIENTS];
+
+ int mapCount;
+ mapInfo mapList[MAX_MAPS];
+
+
+ int tierCount;
+ tierInfo tierList[MAX_TIERS];
+
+ int skillIndex;
+
+ modInfo_t modList[MAX_MODS];
+ int modCount;
+ int modIndex;
+
+ const char *demoList[MAX_DEMOS];
+ int demoCount;
+ int demoIndex;
+
+ const char *movieList[MAX_MOVIES];
+ int movieCount;
+ int movieIndex;
+ int previewMovie;
+
+ serverStatus_t serverStatus;
+
+ // for the showing the status of a server
+ char serverStatusAddress[MAX_ADDRESSLENGTH];
+ serverStatusInfo_t serverStatusInfo;
+ int nextServerStatusRefresh;
+
+ // to retrieve the status of server to find a player
+ pendingServerStatus_t pendingServerStatus;
+ char findPlayerName[MAX_STRING_CHARS];
+ char foundPlayerServerAddresses[MAX_FOUNDPLAYER_SERVERS][MAX_ADDRESSLENGTH];
+ char foundPlayerServerNames[MAX_FOUNDPLAYER_SERVERS][MAX_ADDRESSLENGTH];
+ int currentFoundPlayerServer;
+ int numFoundPlayerServers;
+ int nextFindPlayerRefresh;
+
+ int currentCrosshair;
+ int startPostGameTime;
+ sfxHandle_t newHighScoreSound;
+
+ int q3HeadCount;
+ char q3HeadNames[MAX_PLAYERMODELS][64];
+ qhandle_t q3HeadIcons[MAX_PLAYERMODELS];
+ int q3SelectedHead;
+
+ int effectsColor;
+
+ qboolean inGameLoad;
+
+} uiInfo_t;
+
+extern uiInfo_t uiInfo;
+
+
+extern void UI_Init( void );
+extern void UI_Shutdown( void );
+extern void UI_KeyEvent( int key );
+extern void UI_MouseEvent( int dx, int dy );
+extern void UI_Refresh( int realtime );
+extern qboolean UI_ConsoleCommand( int realTime );
+extern float UI_ClampCvar( float min, float max, float value );
+extern void UI_DrawNamedPic( float x, float y, float width, float height, const char *picname );
+extern void UI_DrawHandlePic( float x, float y, float w, float h, qhandle_t hShader );
+extern void UI_FillRect( float x, float y, float width, float height, const float *color );
+extern void UI_DrawRect( float x, float y, float width, float height, const float *color );
+extern void UI_DrawTopBottom(float x, float y, float w, float h);
+extern void UI_DrawSides(float x, float y, float w, float h);
+extern void UI_UpdateScreen( void );
+extern void UI_SetColor( const float *rgba );
+extern void UI_LerpColor(vec4_t a, vec4_t b, vec4_t c, float t);
+extern void UI_DrawBannerString( int x, int y, const char* str, int style, vec4_t color );
+extern float UI_ProportionalSizeScale( int style );
+extern void UI_DrawProportionalString( int x, int y, const char* str, int style, vec4_t color );
+extern int UI_ProportionalStringWidth( const char* str );
+extern void UI_DrawString( int x, int y, const char* str, int style, vec4_t color );
+extern void UI_DrawChar( int x, int y, int ch, int style, vec4_t color );
+extern qboolean UI_CursorInRect (int x, int y, int width, int height);
+extern void UI_AdjustFrom640( float *x, float *y, float *w, float *h );
+extern void UI_DrawTextBox (int x, int y, int width, int lines);
+extern qboolean UI_IsFullscreen( void );
+extern void UI_SetActiveMenu( uiMenuCommand_t menu );
+extern void UI_PushMenu ( menuframework_s *menu );
+extern void UI_PopMenu (void);
+extern void UI_ForceMenuOff (void);
+extern char *UI_Argv( int arg );
+extern char *UI_Cvar_VariableString( const char *var_name );
+extern void UI_Refresh( int time );
+extern void UI_KeyEvent( int key );
+extern void UI_StartDemoLoop( void );
+extern qboolean m_entersound;
+void UI_LoadBestScores(const char *map, int game);
+extern uiStatic_t uis;
+
+//
+// ui_spLevel.c
+//
+void UI_SPLevelMenu_Cache( void );
+void UI_SPLevelMenu( void );
+void UI_SPLevelMenu_f( void );
+void UI_SPLevelMenu_ReInit( void );
+
+//
+// ui_spArena.c
+//
+void UI_SPArena_Start( const char *arenaInfo );
+
+//
+// ui_spPostgame.c
+//
+void UI_SPPostgameMenu_Cache( void );
+void UI_SPPostgameMenu_f( void );
+
+//
+// ui_spSkill.c
+//
+void UI_SPSkillMenu( const char *arenaInfo );
+void UI_SPSkillMenu_Cache( void );
+
+//
+// ui_syscalls.c
+//
+void trap_Print( const char *string );
+void trap_Error( const char *string );
+int trap_Milliseconds( void );
+void trap_Cvar_Register( vmCvar_t *vmCvar, const char *varName, const char *defaultValue, int flags );
+void trap_Cvar_Update( vmCvar_t *vmCvar );
+void trap_Cvar_Set( const char *var_name, const char *value );
+float trap_Cvar_VariableValue( const char *var_name );
+void trap_Cvar_VariableStringBuffer( const char *var_name, char *buffer, int bufsize );
+void trap_Cvar_SetValue( const char *var_name, float value );
+void trap_Cvar_Reset( const char *name );
+void trap_Cvar_Create( const char *var_name, const char *var_value, int flags );
+void trap_Cvar_InfoStringBuffer( int bit, char *buffer, int bufsize );
+int trap_Argc( void );
+void trap_Argv( int n, char *buffer, int bufferLength );
+void trap_Cmd_ExecuteText( int exec_when, const char *text ); // don't use EXEC_NOW!
+int trap_FS_FOpenFile( const char *qpath, fileHandle_t *f, fsMode_t mode );
+void trap_FS_Read( void *buffer, int len, fileHandle_t f );
+void trap_FS_Write( const void *buffer, int len, fileHandle_t f );
+void trap_FS_FCloseFile( fileHandle_t f );
+int trap_FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize );
+int trap_FS_Seek( fileHandle_t f, long offset, int origin ); // fsOrigin_t
+qhandle_t trap_R_RegisterModel( const char *name );
+qhandle_t trap_R_RegisterSkin( const char *name );
+qhandle_t trap_R_RegisterShaderNoMip( const char *name );
+void trap_R_ClearScene( void );
+void trap_R_AddRefEntityToScene( const refEntity_t *re );
+void trap_R_AddPolyToScene( qhandle_t hShader , int numVerts, const polyVert_t *verts );
+void trap_R_AddLightToScene( const vec3_t org, float intensity, float r, float g, float b );
+void trap_R_RenderScene( const refdef_t *fd );
+void trap_R_SetColor( const float *rgba );
+void trap_R_DrawStretchPic( float x, float y, float w, float h, float s1, float t1, float s2, float t2, qhandle_t hShader );
+void trap_R_ModelBounds( clipHandle_t model, vec3_t mins, vec3_t maxs );
+void trap_UpdateScreen( void );
+int trap_CM_LerpTag( orientation_t *tag, clipHandle_t mod, int startFrame, int endFrame, float frac, const char *tagName );
+void trap_S_StartLocalSound( sfxHandle_t sfx, int channelNum );
+sfxHandle_t trap_S_RegisterSound( const char *sample, qboolean compressed );
+void trap_Key_KeynumToStringBuf( int keynum, char *buf, int buflen );
+void trap_Key_GetBindingBuf( int keynum, char *buf, int buflen );
+void trap_Key_SetBinding( int keynum, const char *binding );
+qboolean trap_Key_IsDown( int keynum );
+qboolean trap_Key_GetOverstrikeMode( void );
+void trap_Key_SetOverstrikeMode( qboolean state );
+void trap_Key_ClearStates( void );
+int trap_Key_GetCatcher( void );
+void trap_Key_SetCatcher( int catcher );
+void trap_GetClipboardData( char *buf, int bufsize );
+void trap_GetClientState( uiClientState_t *state );
+void trap_GetGlconfig( glconfig_t *glconfig );
+int trap_GetConfigString( int index, char* buff, int buffsize );
+int trap_LAN_GetServerCount( int source );
+void trap_LAN_GetServerAddressString( int source, int n, char *buf, int buflen );
+void trap_LAN_GetServerInfo( int source, int n, char *buf, int buflen );
+int trap_LAN_GetServerPing( int source, int n );
+int trap_LAN_GetPingQueueCount( void );
+void trap_LAN_ClearPing( int n );
+void trap_LAN_GetPing( int n, char *buf, int buflen, int *pingtime );
+void trap_LAN_GetPingInfo( int n, char *buf, int buflen );
+void trap_LAN_LoadCachedServers();
+void trap_LAN_SaveCachedServers();
+void trap_LAN_MarkServerVisible(int source, int n, qboolean visible);
+int trap_LAN_ServerIsVisible( int source, int n);
+qboolean trap_LAN_UpdateVisiblePings( int source );
+int trap_LAN_AddServer(int source, const char *name, const char *addr);
+void trap_LAN_RemoveServer(int source, const char *addr);
+void trap_LAN_ResetPings(int n);
+int trap_LAN_ServerStatus( const char *serverAddress, char *serverStatus, int maxLen );
+int trap_LAN_CompareServers( int source, int sortKey, int sortDir, int s1, int s2 );
+int trap_MemoryRemaining( void );
+void trap_GetCDKey( char *buf, int buflen );
+void trap_SetCDKey( char *buf );
+void trap_R_RegisterFont(const char *pFontname, int pointSize, fontInfo_t *font);
+void trap_S_StopBackgroundTrack( void );
+void trap_S_StartBackgroundTrack( const char *intro, const char *loop);
+int trap_CIN_PlayCinematic( const char *arg0, int xpos, int ypos, int width, int height, int bits);
+e_status trap_CIN_StopCinematic(int handle);
+e_status trap_CIN_RunCinematic (int handle);
+void trap_CIN_DrawCinematic (int handle);
+void trap_CIN_SetExtents (int handle, int x, int y, int w, int h);
+int trap_RealTime(qtime_t *qtime);
+void trap_R_RemapShader( const char *oldShader, const char *newShader, const char *timeOffset );
+qboolean trap_VerifyCDKey( const char *key, const char *chksum);
+
+void trap_SetPbClStatus( int status );
+
+//
+// ui_addbots.c
+//
+void UI_AddBots_Cache( void );
+void UI_AddBotsMenu( void );
+
+//
+// ui_removebots.c
+//
+void UI_RemoveBots_Cache( void );
+void UI_RemoveBotsMenu( void );
+
+//
+// ui_teamorders.c
+//
+extern void UI_TeamOrdersMenu( void );
+extern void UI_TeamOrdersMenu_f( void );
+extern void UI_TeamOrdersMenu_Cache( void );
+
+//
+// ui_loadconfig.c
+//
+void UI_LoadConfig_Cache( void );
+void UI_LoadConfigMenu( void );
+
+//
+// ui_saveconfig.c
+//
+void UI_SaveConfigMenu_Cache( void );
+void UI_SaveConfigMenu( void );
+
+//
+// ui_display.c
+//
+void UI_DisplayOptionsMenu_Cache( void );
+void UI_DisplayOptionsMenu( void );
+
+//
+// ui_sound.c
+//
+void UI_SoundOptionsMenu_Cache( void );
+void UI_SoundOptionsMenu( void );
+
+//
+// ui_network.c
+//
+void UI_NetworkOptionsMenu_Cache( void );
+void UI_NetworkOptionsMenu( void );
+
+//
+// ui_gameinfo.c
+//
+typedef enum {
+ AWARD_ACCURACY,
+ AWARD_IMPRESSIVE,
+ AWARD_EXCELLENT,
+ AWARD_GAUNTLET,
+ AWARD_FRAGS,
+ AWARD_PERFECT
+} awardType_t;
+
+const char *UI_GetArenaInfoByNumber( int num );
+const char *UI_GetArenaInfoByMap( const char *map );
+const char *UI_GetSpecialArenaInfo( const char *tag );
+int UI_GetNumArenas( void );
+int UI_GetNumSPArenas( void );
+int UI_GetNumSPTiers( void );
+
+char *UI_GetBotInfoByNumber( int num );
+char *UI_GetBotInfoByName( const char *name );
+int UI_GetNumBots( void );
+void UI_LoadBots( void );
+char *UI_GetBotNameByNumber( int num );
+
+void UI_GetBestScore( int level, int *score, int *skill );
+void UI_SetBestScore( int level, int score );
+int UI_TierCompleted( int levelWon );
+qboolean UI_ShowTierVideo( int tier );
+qboolean UI_CanShowTierVideo( int tier );
+int UI_GetCurrentGame( void );
+void UI_NewGame( void );
+void UI_LogAwardData( int award, int data );
+int UI_GetAwardLevel( int award );
+
+void UI_SPUnlock_f( void );
+void UI_SPUnlockMedals_f( void );
+
+void UI_InitGameinfo( void );
+
+//
+// ui_login.c
+//
+void Login_Cache( void );
+void UI_LoginMenu( void );
+
+//
+// ui_signup.c
+//
+void Signup_Cache( void );
+void UI_SignupMenu( void );
+
+//
+// ui_rankstatus.c
+//
+void RankStatus_Cache( void );
+void UI_RankStatusMenu( void );
+
+
+// new ui
+
+#define ASSET_BACKGROUND "uiBackground"
+
+// for tracking sp game info in Team Arena
+typedef struct postGameInfo_s {
+ int score;
+ int redScore;
+ int blueScore;
+ int perfects;
+ int accuracy;
+ int impressives;
+ int excellents;
+ int defends;
+ int assists;
+ int gauntlets;
+ int captures;
+ int time;
+ int timeBonus;
+ int shutoutBonus;
+ int skillBonus;
+ int baseScore;
+} postGameInfo_t;
+
+
+
+#endif
diff --git a/code/ui/ui_main.c b/code/ui/ui_main.c
new file mode 100755
index 0000000..53d73eb
--- /dev/null
+++ b/code/ui/ui_main.c
@@ -0,0 +1,5997 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+/*
+=======================================================================
+
+USER INTERFACE MAIN
+
+=======================================================================
+*/
+
+// use this to get a demo build without an explicit demo build, i.e. to get the demo ui files to build
+//#define PRE_RELEASE_TADEMO
+
+#include "ui_local.h"
+
+uiInfo_t uiInfo;
+
+static const char *MonthAbbrev[] = {
+ "Jan","Feb","Mar",
+ "Apr","May","Jun",
+ "Jul","Aug","Sep",
+ "Oct","Nov","Dec"
+};
+
+
+static const char *skillLevels[] = {
+ "I Can Win",
+ "Bring It On",
+ "Hurt Me Plenty",
+ "Hardcore",
+ "Nightmare"
+};
+
+static const int numSkillLevels = sizeof(skillLevels) / sizeof(const char*);
+
+
+static const char *netSources[] = {
+ "Local",
+ "Mplayer",
+ "Internet",
+ "Favorites"
+};
+static const int numNetSources = sizeof(netSources) / sizeof(const char*);
+
+static const serverFilter_t serverFilters[] = {
+ {"All", "" },
+ {"Quake 3 Arena", "" },
+ {"Team Arena", "missionpack" },
+ {"Rocket Arena", "arena" },
+ {"Alliance", "alliance20" },
+ {"Weapons Factory Arena", "wfa" },
+ {"OSP", "osp" },
+};
+
+static const char *teamArenaGameTypes[] = {
+ "FFA",
+ "TOURNAMENT",
+ "SP",
+ "TEAM DM",
+ "CTF",
+ "1FCTF",
+ "OVERLOAD",
+ "HARVESTER",
+ "TEAMTOURNAMENT"
+};
+
+static int const numTeamArenaGameTypes = sizeof(teamArenaGameTypes) / sizeof(const char*);
+
+
+static const char *teamArenaGameNames[] = {
+ "Free For All",
+ "Tournament",
+ "Single Player",
+ "Team Deathmatch",
+ "Capture the Flag",
+ "One Flag CTF",
+ "Overload",
+ "Harvester",
+ "Team Tournament",
+};
+
+static int const numTeamArenaGameNames = sizeof(teamArenaGameNames) / sizeof(const char*);
+
+
+static const int numServerFilters = sizeof(serverFilters) / sizeof(serverFilter_t);
+
+static const char *sortKeys[] = {
+ "Server Name",
+ "Map Name",
+ "Open Player Spots",
+ "Game Type",
+ "Ping Time"
+};
+static const int numSortKeys = sizeof(sortKeys) / sizeof(const char*);
+
+static char* netnames[] = {
+ "???",
+ "UDP",
+ "IPX",
+ NULL
+};
+
+#ifndef MISSIONPACK // bk001206
+static char quake3worldMessage[] = "Visit www.quake3world.com - News, Community, Events, Files";
+#endif
+
+static int gamecodetoui[] = {4,2,3,0,5,1,6};
+static int uitogamecode[] = {4,6,2,3,1,5,7};
+
+
+static void UI_StartServerRefresh(qboolean full);
+static void UI_StopServerRefresh( void );
+static void UI_DoServerRefresh( void );
+static void UI_FeederSelection(float feederID, int index);
+static void UI_BuildServerDisplayList(qboolean force);
+static void UI_BuildServerStatus(qboolean force);
+static void UI_BuildFindPlayerList(qboolean force);
+static int QDECL UI_ServersQsortCompare( const void *arg1, const void *arg2 );
+static int UI_MapCountByGameType(qboolean singlePlayer);
+static int UI_HeadCountByTeam( void );
+static void UI_ParseGameInfo(const char *teamFile);
+static void UI_ParseTeamInfo(const char *teamFile);
+static const char *UI_SelectedMap(int index, int *actual);
+static const char *UI_SelectedHead(int index, int *actual);
+static int UI_GetIndexFromSelection(int actual);
+
+int ProcessNewUI( int command, int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6 );
+
+/*
+================
+vmMain
+
+This is the only way control passes into the module.
+This must be the very first function compiled into the .qvm file
+================
+*/
+vmCvar_t ui_new;
+vmCvar_t ui_debug;
+vmCvar_t ui_initialized;
+vmCvar_t ui_teamArenaFirstRun;
+
+void _UI_Init( qboolean );
+void _UI_Shutdown( void );
+void _UI_KeyEvent( int key, qboolean down );
+void _UI_MouseEvent( int dx, int dy );
+void _UI_Refresh( int realtime );
+qboolean _UI_IsFullscreen( void );
+int vmMain( int command, int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11 ) {
+ switch ( command ) {
+ case UI_GETAPIVERSION:
+ return UI_API_VERSION;
+
+ case UI_INIT:
+ _UI_Init(arg0);
+ return 0;
+
+ case UI_SHUTDOWN:
+ _UI_Shutdown();
+ return 0;
+
+ case UI_KEY_EVENT:
+ _UI_KeyEvent( arg0, arg1 );
+ return 0;
+
+ case UI_MOUSE_EVENT:
+ _UI_MouseEvent( arg0, arg1 );
+ return 0;
+
+ case UI_REFRESH:
+ _UI_Refresh( arg0 );
+ return 0;
+
+ case UI_IS_FULLSCREEN:
+ return _UI_IsFullscreen();
+
+ case UI_SET_ACTIVE_MENU:
+ _UI_SetActiveMenu( arg0 );
+ return 0;
+
+ case UI_CONSOLE_COMMAND:
+ return UI_ConsoleCommand(arg0);
+
+ case UI_DRAW_CONNECT_SCREEN:
+ UI_DrawConnectScreen( arg0 );
+ return 0;
+ case UI_HASUNIQUECDKEY: // mod authors need to observe this
+ return qtrue; // bk010117 - change this to qfalse for mods!
+
+ }
+
+ return -1;
+}
+
+
+
+void AssetCache() {
+ int n;
+ //if (Assets.textFont == NULL) {
+ //}
+ //Assets.background = trap_R_RegisterShaderNoMip( ASSET_BACKGROUND );
+ //Com_Printf("Menu Size: %i bytes\n", sizeof(Menus));
+ uiInfo.uiDC.Assets.gradientBar = trap_R_RegisterShaderNoMip( ASSET_GRADIENTBAR );
+ uiInfo.uiDC.Assets.fxBasePic = trap_R_RegisterShaderNoMip( ART_FX_BASE );
+ uiInfo.uiDC.Assets.fxPic[0] = trap_R_RegisterShaderNoMip( ART_FX_RED );
+ uiInfo.uiDC.Assets.fxPic[1] = trap_R_RegisterShaderNoMip( ART_FX_YELLOW );
+ uiInfo.uiDC.Assets.fxPic[2] = trap_R_RegisterShaderNoMip( ART_FX_GREEN );
+ uiInfo.uiDC.Assets.fxPic[3] = trap_R_RegisterShaderNoMip( ART_FX_TEAL );
+ uiInfo.uiDC.Assets.fxPic[4] = trap_R_RegisterShaderNoMip( ART_FX_BLUE );
+ uiInfo.uiDC.Assets.fxPic[5] = trap_R_RegisterShaderNoMip( ART_FX_CYAN );
+ uiInfo.uiDC.Assets.fxPic[6] = trap_R_RegisterShaderNoMip( ART_FX_WHITE );
+ uiInfo.uiDC.Assets.scrollBar = trap_R_RegisterShaderNoMip( ASSET_SCROLLBAR );
+ uiInfo.uiDC.Assets.scrollBarArrowDown = trap_R_RegisterShaderNoMip( ASSET_SCROLLBAR_ARROWDOWN );
+ uiInfo.uiDC.Assets.scrollBarArrowUp = trap_R_RegisterShaderNoMip( ASSET_SCROLLBAR_ARROWUP );
+ uiInfo.uiDC.Assets.scrollBarArrowLeft = trap_R_RegisterShaderNoMip( ASSET_SCROLLBAR_ARROWLEFT );
+ uiInfo.uiDC.Assets.scrollBarArrowRight = trap_R_RegisterShaderNoMip( ASSET_SCROLLBAR_ARROWRIGHT );
+ uiInfo.uiDC.Assets.scrollBarThumb = trap_R_RegisterShaderNoMip( ASSET_SCROLL_THUMB );
+ uiInfo.uiDC.Assets.sliderBar = trap_R_RegisterShaderNoMip( ASSET_SLIDER_BAR );
+ uiInfo.uiDC.Assets.sliderThumb = trap_R_RegisterShaderNoMip( ASSET_SLIDER_THUMB );
+
+ for( n = 0; n < NUM_CROSSHAIRS; n++ ) {
+ uiInfo.uiDC.Assets.crosshairShader[n] = trap_R_RegisterShaderNoMip( va("gfx/2d/crosshair%c", 'a' + n ) );
+ }
+
+ uiInfo.newHighScoreSound = trap_S_RegisterSound("sound/feedback/voc_newhighscore.wav", qfalse);
+}
+
+void _UI_DrawSides(float x, float y, float w, float h, float size) {
+ UI_AdjustFrom640( &x, &y, &w, &h );
+ size *= uiInfo.uiDC.xscale;
+ trap_R_DrawStretchPic( x, y, size, h, 0, 0, 0, 0, uiInfo.uiDC.whiteShader );
+ trap_R_DrawStretchPic( x + w - size, y, size, h, 0, 0, 0, 0, uiInfo.uiDC.whiteShader );
+}
+
+void _UI_DrawTopBottom(float x, float y, float w, float h, float size) {
+ UI_AdjustFrom640( &x, &y, &w, &h );
+ size *= uiInfo.uiDC.yscale;
+ trap_R_DrawStretchPic( x, y, w, size, 0, 0, 0, 0, uiInfo.uiDC.whiteShader );
+ trap_R_DrawStretchPic( x, y + h - size, w, size, 0, 0, 0, 0, uiInfo.uiDC.whiteShader );
+}
+/*
+================
+UI_DrawRect
+
+Coordinates are 640*480 virtual values
+=================
+*/
+void _UI_DrawRect( float x, float y, float width, float height, float size, const float *color ) {
+ trap_R_SetColor( color );
+
+ _UI_DrawTopBottom(x, y, width, height, size);
+ _UI_DrawSides(x, y, width, height, size);
+
+ trap_R_SetColor( NULL );
+}
+
+int Text_Width(const char *text, float scale, int limit) {
+ int count,len;
+ float out;
+ glyphInfo_t *glyph;
+ float useScale;
+ const char *s = text;
+ fontInfo_t *font = &uiInfo.uiDC.Assets.textFont;
+ if (scale <= ui_smallFont.value) {
+ font = &uiInfo.uiDC.Assets.smallFont;
+ } else if (scale >= ui_bigFont.value) {
+ font = &uiInfo.uiDC.Assets.bigFont;
+ }
+ useScale = scale * font->glyphScale;
+ out = 0;
+ if (text) {
+ len = strlen(text);
+ if (limit > 0 && len > limit) {
+ len = limit;
+ }
+ count = 0;
+ while (s && *s && count < len) {
+ if ( Q_IsColorString(s) ) {
+ s += 2;
+ continue;
+ } else {
+ glyph = &font->glyphs[(int)*s];
+ out += glyph->xSkip;
+ s++;
+ count++;
+ }
+ }
+ }
+ return out * useScale;
+}
+
+int Text_Height(const char *text, float scale, int limit) {
+ int len, count;
+ float max;
+ glyphInfo_t *glyph;
+ float useScale;
+ const char *s = text; // bk001206 - unsigned
+ fontInfo_t *font = &uiInfo.uiDC.Assets.textFont;
+ if (scale <= ui_smallFont.value) {
+ font = &uiInfo.uiDC.Assets.smallFont;
+ } else if (scale >= ui_bigFont.value) {
+ font = &uiInfo.uiDC.Assets.bigFont;
+ }
+ useScale = scale * font->glyphScale;
+ max = 0;
+ if (text) {
+ len = strlen(text);
+ if (limit > 0 && len > limit) {
+ len = limit;
+ }
+ count = 0;
+ while (s && *s && count < len) {
+ if ( Q_IsColorString(s) ) {
+ s += 2;
+ continue;
+ } else {
+ glyph = &font->glyphs[(int)*s]; // TTimo: FIXME: getting nasty warnings without the cast, hopefully this doesn't break the VM build
+ if (max < glyph->height) {
+ max = glyph->height;
+ }
+ s++;
+ count++;
+ }
+ }
+ }
+ return max * useScale;
+}
+
+void Text_PaintChar(float x, float y, float width, float height, float scale, float s, float t, float s2, float t2, qhandle_t hShader) {
+ float w, h;
+ w = width * scale;
+ h = height * scale;
+ UI_AdjustFrom640( &x, &y, &w, &h );
+ trap_R_DrawStretchPic( x, y, w, h, s, t, s2, t2, hShader );
+}
+
+void Text_Paint(float x, float y, float scale, vec4_t color, const char *text, float adjust, int limit, int style) {
+ int len, count;
+ vec4_t newColor;
+ glyphInfo_t *glyph;
+ float useScale;
+ fontInfo_t *font = &uiInfo.uiDC.Assets.textFont;
+ if (scale <= ui_smallFont.value) {
+ font = &uiInfo.uiDC.Assets.smallFont;
+ } else if (scale >= ui_bigFont.value) {
+ font = &uiInfo.uiDC.Assets.bigFont;
+ }
+ useScale = scale * font->glyphScale;
+ if (text) {
+ const char *s = text; // bk001206 - unsigned
+ trap_R_SetColor( color );
+ memcpy(&newColor[0], &color[0], sizeof(vec4_t));
+ len = strlen(text);
+ if (limit > 0 && len > limit) {
+ len = limit;
+ }
+ count = 0;
+ while (s && *s && count < len) {
+ glyph = &font->glyphs[(int)*s]; // TTimo: FIXME: getting nasty warnings without the cast, hopefully this doesn't break the VM build
+ //int yadj = Assets.textFont.glyphs[text[i]].bottom + Assets.textFont.glyphs[text[i]].top;
+ //float yadj = scale * (Assets.textFont.glyphs[text[i]].imageHeight - Assets.textFont.glyphs[text[i]].height);
+ if ( Q_IsColorString( s ) ) {
+ memcpy( newColor, g_color_table[ColorIndex(*(s+1))], sizeof( newColor ) );
+ newColor[3] = color[3];
+ trap_R_SetColor( newColor );
+ s += 2;
+ continue;
+ } else {
+ float yadj = useScale * glyph->top;
+ if (style == ITEM_TEXTSTYLE_SHADOWED || style == ITEM_TEXTSTYLE_SHADOWEDMORE) {
+ int ofs = style == ITEM_TEXTSTYLE_SHADOWED ? 1 : 2;
+ colorBlack[3] = newColor[3];
+ trap_R_SetColor( colorBlack );
+ Text_PaintChar(x + ofs, y - yadj + ofs,
+ glyph->imageWidth,
+ glyph->imageHeight,
+ useScale,
+ glyph->s,
+ glyph->t,
+ glyph->s2,
+ glyph->t2,
+ glyph->glyph);
+ trap_R_SetColor( newColor );
+ colorBlack[3] = 1.0;
+ }
+ Text_PaintChar(x, y - yadj,
+ glyph->imageWidth,
+ glyph->imageHeight,
+ useScale,
+ glyph->s,
+ glyph->t,
+ glyph->s2,
+ glyph->t2,
+ glyph->glyph);
+
+ x += (glyph->xSkip * useScale) + adjust;
+ s++;
+ count++;
+ }
+ }
+ trap_R_SetColor( NULL );
+ }
+}
+
+void Text_PaintWithCursor(float x, float y, float scale, vec4_t color, const char *text, int cursorPos, char cursor, int limit, int style) {
+ int len, count;
+ vec4_t newColor;
+ glyphInfo_t *glyph, *glyph2;
+ float yadj;
+ float useScale;
+ fontInfo_t *font = &uiInfo.uiDC.Assets.textFont;
+ if (scale <= ui_smallFont.value) {
+ font = &uiInfo.uiDC.Assets.smallFont;
+ } else if (scale >= ui_bigFont.value) {
+ font = &uiInfo.uiDC.Assets.bigFont;
+ }
+ useScale = scale * font->glyphScale;
+ if (text) {
+ const char *s = text; // bk001206 - unsigned
+ trap_R_SetColor( color );
+ memcpy(&newColor[0], &color[0], sizeof(vec4_t));
+ len = strlen(text);
+ if (limit > 0 && len > limit) {
+ len = limit;
+ }
+ count = 0;
+ glyph2 = &font->glyphs[ (int) cursor]; // bk001206 - possible signed char
+ while (s && *s && count < len) {
+ glyph = &font->glyphs[(int)*s]; // TTimo: FIXME: getting nasty warnings without the cast, hopefully this doesn't break the VM build
+ //int yadj = Assets.textFont.glyphs[text[i]].bottom + Assets.textFont.glyphs[text[i]].top;
+ //float yadj = scale * (Assets.textFont.glyphs[text[i]].imageHeight - Assets.textFont.glyphs[text[i]].height);
+ if ( Q_IsColorString( s ) ) {
+ memcpy( newColor, g_color_table[ColorIndex(*(s+1))], sizeof( newColor ) );
+ newColor[3] = color[3];
+ trap_R_SetColor( newColor );
+ s += 2;
+ continue;
+ } else {
+ yadj = useScale * glyph->top;
+ if (style == ITEM_TEXTSTYLE_SHADOWED || style == ITEM_TEXTSTYLE_SHADOWEDMORE) {
+ int ofs = style == ITEM_TEXTSTYLE_SHADOWED ? 1 : 2;
+ colorBlack[3] = newColor[3];
+ trap_R_SetColor( colorBlack );
+ Text_PaintChar(x + ofs, y - yadj + ofs,
+ glyph->imageWidth,
+ glyph->imageHeight,
+ useScale,
+ glyph->s,
+ glyph->t,
+ glyph->s2,
+ glyph->t2,
+ glyph->glyph);
+ colorBlack[3] = 1.0;
+ trap_R_SetColor( newColor );
+ }
+ Text_PaintChar(x, y - yadj,
+ glyph->imageWidth,
+ glyph->imageHeight,
+ useScale,
+ glyph->s,
+ glyph->t,
+ glyph->s2,
+ glyph->t2,
+ glyph->glyph);
+
+ yadj = useScale * glyph2->top;
+ if (count == cursorPos && !((uiInfo.uiDC.realTime/BLINK_DIVISOR) & 1)) {
+ Text_PaintChar(x, y - yadj,
+ glyph2->imageWidth,
+ glyph2->imageHeight,
+ useScale,
+ glyph2->s,
+ glyph2->t,
+ glyph2->s2,
+ glyph2->t2,
+ glyph2->glyph);
+ }
+
+ x += (glyph->xSkip * useScale);
+ s++;
+ count++;
+ }
+ }
+ // need to paint cursor at end of text
+ if (cursorPos == len && !((uiInfo.uiDC.realTime/BLINK_DIVISOR) & 1)) {
+ yadj = useScale * glyph2->top;
+ Text_PaintChar(x, y - yadj,
+ glyph2->imageWidth,
+ glyph2->imageHeight,
+ useScale,
+ glyph2->s,
+ glyph2->t,
+ glyph2->s2,
+ glyph2->t2,
+ glyph2->glyph);
+
+ }
+
+ trap_R_SetColor( NULL );
+ }
+}
+
+
+static void Text_Paint_Limit(float *maxX, float x, float y, float scale, vec4_t color, const char* text, float adjust, int limit) {
+ int len, count;
+ vec4_t newColor;
+ glyphInfo_t *glyph;
+ if (text) {
+ const char *s = text; // bk001206 - unsigned
+ float max = *maxX;
+ float useScale;
+ fontInfo_t *font = &uiInfo.uiDC.Assets.textFont;
+ if (scale <= ui_smallFont.value) {
+ font = &uiInfo.uiDC.Assets.smallFont;
+ } else if (scale > ui_bigFont.value) {
+ font = &uiInfo.uiDC.Assets.bigFont;
+ }
+ useScale = scale * font->glyphScale;
+ trap_R_SetColor( color );
+ len = strlen(text);
+ if (limit > 0 && len > limit) {
+ len = limit;
+ }
+ count = 0;
+ while (s && *s && count < len) {
+ glyph = &font->glyphs[(int)*s]; // TTimo: FIXME: getting nasty warnings without the cast, hopefully this doesn't break the VM build
+ if ( Q_IsColorString( s ) ) {
+ memcpy( newColor, g_color_table[ColorIndex(*(s+1))], sizeof( newColor ) );
+ newColor[3] = color[3];
+ trap_R_SetColor( newColor );
+ s += 2;
+ continue;
+ } else {
+ float yadj = useScale * glyph->top;
+ if (Text_Width(s, useScale, 1) + x > max) {
+ *maxX = 0;
+ break;
+ }
+ Text_PaintChar(x, y - yadj,
+ glyph->imageWidth,
+ glyph->imageHeight,
+ useScale,
+ glyph->s,
+ glyph->t,
+ glyph->s2,
+ glyph->t2,
+ glyph->glyph);
+ x += (glyph->xSkip * useScale) + adjust;
+ *maxX = x;
+ count++;
+ s++;
+ }
+ }
+ trap_R_SetColor( NULL );
+ }
+
+}
+
+
+void UI_ShowPostGame(qboolean newHigh) {
+ trap_Cvar_Set ("cg_cameraOrbit", "0");
+ trap_Cvar_Set("cg_thirdPerson", "0");
+ trap_Cvar_Set( "sv_killserver", "1" );
+ uiInfo.soundHighScore = newHigh;
+ _UI_SetActiveMenu(UIMENU_POSTGAME);
+}
+/*
+=================
+_UI_Refresh
+=================
+*/
+
+void UI_DrawCenteredPic(qhandle_t image, int w, int h) {
+ int x, y;
+ x = (SCREEN_WIDTH - w) / 2;
+ y = (SCREEN_HEIGHT - h) / 2;
+ UI_DrawHandlePic(x, y, w, h, image);
+}
+
+int frameCount = 0;
+int startTime;
+
+#define UI_FPS_FRAMES 4
+void _UI_Refresh( int realtime )
+{
+ static int index;
+ static int previousTimes[UI_FPS_FRAMES];
+
+ //if ( !( trap_Key_GetCatcher() & KEYCATCH_UI ) ) {
+ // return;
+ //}
+
+ uiInfo.uiDC.frameTime = realtime - uiInfo.uiDC.realTime;
+ uiInfo.uiDC.realTime = realtime;
+
+ previousTimes[index % UI_FPS_FRAMES] = uiInfo.uiDC.frameTime;
+ index++;
+ if ( index > UI_FPS_FRAMES ) {
+ int i, total;
+ // average multiple frames together to smooth changes out a bit
+ total = 0;
+ for ( i = 0 ; i < UI_FPS_FRAMES ; i++ ) {
+ total += previousTimes[i];
+ }
+ if ( !total ) {
+ total = 1;
+ }
+ uiInfo.uiDC.FPS = 1000 * UI_FPS_FRAMES / total;
+ }
+
+
+
+ UI_UpdateCvars();
+
+ if (Menu_Count() > 0) {
+ // paint all the menus
+ Menu_PaintAll();
+ // refresh server browser list
+ UI_DoServerRefresh();
+ // refresh server status
+ UI_BuildServerStatus(qfalse);
+ // refresh find player list
+ UI_BuildFindPlayerList(qfalse);
+ }
+
+ // draw cursor
+ UI_SetColor( NULL );
+ if (Menu_Count() > 0) {
+ UI_DrawHandlePic( uiInfo.uiDC.cursorx-16, uiInfo.uiDC.cursory-16, 32, 32, uiInfo.uiDC.Assets.cursor);
+ }
+
+#ifndef NDEBUG
+ if (uiInfo.uiDC.debug)
+ {
+ // cursor coordinates
+ //FIXME
+ //UI_DrawString( 0, 0, va("(%d,%d)",uis.cursorx,uis.cursory), UI_LEFT|UI_SMALLFONT, colorRed );
+ }
+#endif
+
+}
+
+/*
+=================
+_UI_Shutdown
+=================
+*/
+void _UI_Shutdown( void ) {
+ trap_LAN_SaveCachedServers();
+}
+
+char *defaultMenu = NULL;
+
+char *GetMenuBuffer(const char *filename) {
+ int len;
+ fileHandle_t f;
+ static char buf[MAX_MENUFILE];
+
+ len = trap_FS_FOpenFile( filename, &f, FS_READ );
+ if ( !f ) {
+ trap_Print( va( S_COLOR_RED "menu file not found: %s, using default\n", filename ) );
+ return defaultMenu;
+ }
+ if ( len >= MAX_MENUFILE ) {
+ trap_Print( va( S_COLOR_RED "menu file too large: %s is %i, max allowed is %i", filename, len, MAX_MENUFILE ) );
+ trap_FS_FCloseFile( f );
+ return defaultMenu;
+ }
+
+ trap_FS_Read( buf, len, f );
+ buf[len] = 0;
+ trap_FS_FCloseFile( f );
+ //COM_Compress(buf);
+ return buf;
+
+}
+
+qboolean Asset_Parse(int handle) {
+ pc_token_t token;
+ const char *tempStr;
+
+ if (!trap_PC_ReadToken(handle, &token))
+ return qfalse;
+ if (Q_stricmp(token.string, "{") != 0) {
+ return qfalse;
+ }
+
+ while ( 1 ) {
+
+ memset(&token, 0, sizeof(pc_token_t));
+
+ if (!trap_PC_ReadToken(handle, &token))
+ return qfalse;
+
+ if (Q_stricmp(token.string, "}") == 0) {
+ return qtrue;
+ }
+
+ // font
+ if (Q_stricmp(token.string, "font") == 0) {
+ int pointSize;
+ if (!PC_String_Parse(handle, &tempStr) || !PC_Int_Parse(handle,&pointSize)) {
+ return qfalse;
+ }
+ trap_R_RegisterFont(tempStr, pointSize, &uiInfo.uiDC.Assets.textFont);
+ uiInfo.uiDC.Assets.fontRegistered = qtrue;
+ continue;
+ }
+
+ if (Q_stricmp(token.string, "smallFont") == 0) {
+ int pointSize;
+ if (!PC_String_Parse(handle, &tempStr) || !PC_Int_Parse(handle,&pointSize)) {
+ return qfalse;
+ }
+ trap_R_RegisterFont(tempStr, pointSize, &uiInfo.uiDC.Assets.smallFont);
+ continue;
+ }
+
+ if (Q_stricmp(token.string, "bigFont") == 0) {
+ int pointSize;
+ if (!PC_String_Parse(handle, &tempStr) || !PC_Int_Parse(handle,&pointSize)) {
+ return qfalse;
+ }
+ trap_R_RegisterFont(tempStr, pointSize, &uiInfo.uiDC.Assets.bigFont);
+ continue;
+ }
+
+
+ // gradientbar
+ if (Q_stricmp(token.string, "gradientbar") == 0) {
+ if (!PC_String_Parse(handle, &tempStr)) {
+ return qfalse;
+ }
+ uiInfo.uiDC.Assets.gradientBar = trap_R_RegisterShaderNoMip(tempStr);
+ continue;
+ }
+
+ // enterMenuSound
+ if (Q_stricmp(token.string, "menuEnterSound") == 0) {
+ if (!PC_String_Parse(handle, &tempStr)) {
+ return qfalse;
+ }
+ uiInfo.uiDC.Assets.menuEnterSound = trap_S_RegisterSound( tempStr, qfalse );
+ continue;
+ }
+
+ // exitMenuSound
+ if (Q_stricmp(token.string, "menuExitSound") == 0) {
+ if (!PC_String_Parse(handle, &tempStr)) {
+ return qfalse;
+ }
+ uiInfo.uiDC.Assets.menuExitSound = trap_S_RegisterSound( tempStr, qfalse );
+ continue;
+ }
+
+ // itemFocusSound
+ if (Q_stricmp(token.string, "itemFocusSound") == 0) {
+ if (!PC_String_Parse(handle, &tempStr)) {
+ return qfalse;
+ }
+ uiInfo.uiDC.Assets.itemFocusSound = trap_S_RegisterSound( tempStr, qfalse );
+ continue;
+ }
+
+ // menuBuzzSound
+ if (Q_stricmp(token.string, "menuBuzzSound") == 0) {
+ if (!PC_String_Parse(handle, &tempStr)) {
+ return qfalse;
+ }
+ uiInfo.uiDC.Assets.menuBuzzSound = trap_S_RegisterSound( tempStr, qfalse );
+ continue;
+ }
+
+ if (Q_stricmp(token.string, "cursor") == 0) {
+ if (!PC_String_Parse(handle, &uiInfo.uiDC.Assets.cursorStr)) {
+ return qfalse;
+ }
+ uiInfo.uiDC.Assets.cursor = trap_R_RegisterShaderNoMip( uiInfo.uiDC.Assets.cursorStr);
+ continue;
+ }
+
+ if (Q_stricmp(token.string, "fadeClamp") == 0) {
+ if (!PC_Float_Parse(handle, &uiInfo.uiDC.Assets.fadeClamp)) {
+ return qfalse;
+ }
+ continue;
+ }
+
+ if (Q_stricmp(token.string, "fadeCycle") == 0) {
+ if (!PC_Int_Parse(handle, &uiInfo.uiDC.Assets.fadeCycle)) {
+ return qfalse;
+ }
+ continue;
+ }
+
+ if (Q_stricmp(token.string, "fadeAmount") == 0) {
+ if (!PC_Float_Parse(handle, &uiInfo.uiDC.Assets.fadeAmount)) {
+ return qfalse;
+ }
+ continue;
+ }
+
+ if (Q_stricmp(token.string, "shadowX") == 0) {
+ if (!PC_Float_Parse(handle, &uiInfo.uiDC.Assets.shadowX)) {
+ return qfalse;
+ }
+ continue;
+ }
+
+ if (Q_stricmp(token.string, "shadowY") == 0) {
+ if (!PC_Float_Parse(handle, &uiInfo.uiDC.Assets.shadowY)) {
+ return qfalse;
+ }
+ continue;
+ }
+
+ if (Q_stricmp(token.string, "shadowColor") == 0) {
+ if (!PC_Color_Parse(handle, &uiInfo.uiDC.Assets.shadowColor)) {
+ return qfalse;
+ }
+ uiInfo.uiDC.Assets.shadowFadeClamp = uiInfo.uiDC.Assets.shadowColor[3];
+ continue;
+ }
+
+ }
+ return qfalse;
+}
+
+void Font_Report() {
+ int i;
+ Com_Printf("Font Info\n");
+ Com_Printf("=========\n");
+ for ( i = 32; i < 96; i++) {
+ Com_Printf("Glyph handle %i: %i\n", i, uiInfo.uiDC.Assets.textFont.glyphs[i].glyph);
+ }
+}
+
+void UI_Report() {
+ String_Report();
+ //Font_Report();
+
+}
+
+void UI_ParseMenu(const char *menuFile) {
+ int handle;
+ pc_token_t token;
+
+ Com_Printf("Parsing menu file:%s\n", menuFile);
+
+ handle = trap_PC_LoadSource(menuFile);
+ if (!handle) {
+ return;
+ }
+
+ while ( 1 ) {
+ memset(&token, 0, sizeof(pc_token_t));
+ if (!trap_PC_ReadToken( handle, &token )) {
+ break;
+ }
+
+ //if ( Q_stricmp( token, "{" ) ) {
+ // Com_Printf( "Missing { in menu file\n" );
+ // break;
+ //}
+
+ //if ( menuCount == MAX_MENUS ) {
+ // Com_Printf( "Too many menus!\n" );
+ // break;
+ //}
+
+ if ( token.string[0] == '}' ) {
+ break;
+ }
+
+ if (Q_stricmp(token.string, "assetGlobalDef") == 0) {
+ if (Asset_Parse(handle)) {
+ continue;
+ } else {
+ break;
+ }
+ }
+
+ if (Q_stricmp(token.string, "menudef") == 0) {
+ // start a new menu
+ Menu_New(handle);
+ }
+ }
+ trap_PC_FreeSource(handle);
+}
+
+qboolean Load_Menu(int handle) {
+ pc_token_t token;
+
+ if (!trap_PC_ReadToken(handle, &token))
+ return qfalse;
+ if (token.string[0] != '{') {
+ return qfalse;
+ }
+
+ while ( 1 ) {
+
+ if (!trap_PC_ReadToken(handle, &token))
+ return qfalse;
+
+ if ( token.string[0] == 0 ) {
+ return qfalse;
+ }
+
+ if ( token.string[0] == '}' ) {
+ return qtrue;
+ }
+
+ UI_ParseMenu(token.string);
+ }
+ return qfalse;
+}
+
+void UI_LoadMenus(const char *menuFile, qboolean reset) {
+ pc_token_t token;
+ int handle;
+ int start;
+
+ start = trap_Milliseconds();
+
+ handle = trap_PC_LoadSource( menuFile );
+ if (!handle) {
+ trap_Error( va( S_COLOR_YELLOW "menu file not found: %s, using default\n", menuFile ) );
+ handle = trap_PC_LoadSource( "ui/menus.txt" );
+ if (!handle) {
+ trap_Error( va( S_COLOR_RED "default menu file not found: ui/menus.txt, unable to continue!\n", menuFile ) );
+ }
+ }
+
+ ui_new.integer = 1;
+
+ if (reset) {
+ Menu_Reset();
+ }
+
+ while ( 1 ) {
+ if (!trap_PC_ReadToken(handle, &token))
+ break;
+ if( token.string[0] == 0 || token.string[0] == '}') {
+ break;
+ }
+
+ if ( token.string[0] == '}' ) {
+ break;
+ }
+
+ if (Q_stricmp(token.string, "loadmenu") == 0) {
+ if (Load_Menu(handle)) {
+ continue;
+ } else {
+ break;
+ }
+ }
+ }
+
+ Com_Printf("UI menu load time = %d milli seconds\n", trap_Milliseconds() - start);
+
+ trap_PC_FreeSource( handle );
+}
+
+void UI_Load() {
+ char lastName[1024];
+ menuDef_t *menu = Menu_GetFocused();
+ char *menuSet = UI_Cvar_VariableString("ui_menuFiles");
+ if (menu && menu->window.name) {
+ strcpy(lastName, menu->window.name);
+ }
+ if (menuSet == NULL || menuSet[0] == '\0') {
+ menuSet = "ui/menus.txt";
+ }
+
+ String_Init();
+
+#ifdef PRE_RELEASE_TADEMO
+ UI_ParseGameInfo("demogameinfo.txt");
+#else
+ UI_ParseGameInfo("gameinfo.txt");
+ UI_LoadArenas();
+#endif
+
+ UI_LoadMenus(menuSet, qtrue);
+ Menus_CloseAll();
+ Menus_ActivateByName(lastName);
+
+}
+
+static const char *handicapValues[] = {"None","95","90","85","80","75","70","65","60","55","50","45","40","35","30","25","20","15","10","5",NULL};
+#ifndef MISSIONPACK // bk001206
+static int numHandicaps = sizeof(handicapValues) / sizeof(const char*);
+#endif
+
+static void UI_DrawHandicap(rectDef_t *rect, float scale, vec4_t color, int textStyle) {
+ int i, h;
+
+ h = Com_Clamp( 5, 100, trap_Cvar_VariableValue("handicap") );
+ i = 20 - h / 5;
+
+ Text_Paint(rect->x, rect->y, scale, color, handicapValues[i], 0, 0, textStyle);
+}
+
+static void UI_DrawClanName(rectDef_t *rect, float scale, vec4_t color, int textStyle) {
+ Text_Paint(rect->x, rect->y, scale, color, UI_Cvar_VariableString("ui_teamName"), 0, 0, textStyle);
+}
+
+
+static void UI_SetCapFragLimits(qboolean uiVars) {
+ int cap = 5;
+ int frag = 10;
+ if (uiInfo.gameTypes[ui_gameType.integer].gtEnum == GT_OBELISK) {
+ cap = 4;
+ } else if (uiInfo.gameTypes[ui_gameType.integer].gtEnum == GT_HARVESTER) {
+ cap = 15;
+ }
+ if (uiVars) {
+ trap_Cvar_Set("ui_captureLimit", va("%d", cap));
+ trap_Cvar_Set("ui_fragLimit", va("%d", frag));
+ } else {
+ trap_Cvar_Set("capturelimit", va("%d", cap));
+ trap_Cvar_Set("fraglimit", va("%d", frag));
+ }
+}
+// ui_gameType assumes gametype 0 is -1 ALL and will not show
+static void UI_DrawGameType(rectDef_t *rect, float scale, vec4_t color, int textStyle) {
+ Text_Paint(rect->x, rect->y, scale, color, uiInfo.gameTypes[ui_gameType.integer].gameType, 0, 0, textStyle);
+}
+
+static void UI_DrawNetGameType(rectDef_t *rect, float scale, vec4_t color, int textStyle) {
+ if (ui_netGameType.integer < 0 || ui_netGameType.integer > uiInfo.numGameTypes) {
+ trap_Cvar_Set("ui_netGameType", "0");
+ trap_Cvar_Set("ui_actualNetGameType", "0");
+ }
+ Text_Paint(rect->x, rect->y, scale, color, uiInfo.gameTypes[ui_netGameType.integer].gameType , 0, 0, textStyle);
+}
+
+static void UI_DrawJoinGameType(rectDef_t *rect, float scale, vec4_t color, int textStyle) {
+ if (ui_joinGameType.integer < 0 || ui_joinGameType.integer > uiInfo.numJoinGameTypes) {
+ trap_Cvar_Set("ui_joinGameType", "0");
+ }
+ Text_Paint(rect->x, rect->y, scale, color, uiInfo.joinGameTypes[ui_joinGameType.integer].gameType , 0, 0, textStyle);
+}
+
+
+
+static int UI_TeamIndexFromName(const char *name) {
+ int i;
+
+ if (name && *name) {
+ for (i = 0; i < uiInfo.teamCount; i++) {
+ if (Q_stricmp(name, uiInfo.teamList[i].teamName) == 0) {
+ return i;
+ }
+ }
+ }
+
+ return 0;
+
+}
+
+static void UI_DrawClanLogo(rectDef_t *rect, float scale, vec4_t color) {
+ int i;
+ i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_teamName"));
+ if (i >= 0 && i < uiInfo.teamCount) {
+ trap_R_SetColor( color );
+
+ if (uiInfo.teamList[i].teamIcon == -1) {
+ uiInfo.teamList[i].teamIcon = trap_R_RegisterShaderNoMip(uiInfo.teamList[i].imageName);
+ uiInfo.teamList[i].teamIcon_Metal = trap_R_RegisterShaderNoMip(va("%s_metal",uiInfo.teamList[i].imageName));
+ uiInfo.teamList[i].teamIcon_Name = trap_R_RegisterShaderNoMip(va("%s_name", uiInfo.teamList[i].imageName));
+ }
+
+ UI_DrawHandlePic( rect->x, rect->y, rect->w, rect->h, uiInfo.teamList[i].teamIcon);
+ trap_R_SetColor(NULL);
+ }
+}
+
+static void UI_DrawClanCinematic(rectDef_t *rect, float scale, vec4_t color) {
+ int i;
+ i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_teamName"));
+ if (i >= 0 && i < uiInfo.teamCount) {
+
+ if (uiInfo.teamList[i].cinematic >= -2) {
+ if (uiInfo.teamList[i].cinematic == -1) {
+ uiInfo.teamList[i].cinematic = trap_CIN_PlayCinematic(va("%s.roq", uiInfo.teamList[i].imageName), 0, 0, 0, 0, (CIN_loop | CIN_silent) );
+ }
+ if (uiInfo.teamList[i].cinematic >= 0) {
+ trap_CIN_RunCinematic(uiInfo.teamList[i].cinematic);
+ trap_CIN_SetExtents(uiInfo.teamList[i].cinematic, rect->x, rect->y, rect->w, rect->h);
+ trap_CIN_DrawCinematic(uiInfo.teamList[i].cinematic);
+ } else {
+ trap_R_SetColor( color );
+ UI_DrawHandlePic( rect->x, rect->y, rect->w, rect->h, uiInfo.teamList[i].teamIcon_Metal);
+ trap_R_SetColor(NULL);
+ uiInfo.teamList[i].cinematic = -2;
+ }
+ } else {
+ trap_R_SetColor( color );
+ UI_DrawHandlePic( rect->x, rect->y, rect->w, rect->h, uiInfo.teamList[i].teamIcon);
+ trap_R_SetColor(NULL);
+ }
+ }
+
+}
+
+static void UI_DrawPreviewCinematic(rectDef_t *rect, float scale, vec4_t color) {
+ if (uiInfo.previewMovie > -2) {
+ uiInfo.previewMovie = trap_CIN_PlayCinematic(va("%s.roq", uiInfo.movieList[uiInfo.movieIndex]), 0, 0, 0, 0, (CIN_loop | CIN_silent) );
+ if (uiInfo.previewMovie >= 0) {
+ trap_CIN_RunCinematic(uiInfo.previewMovie);
+ trap_CIN_SetExtents(uiInfo.previewMovie, rect->x, rect->y, rect->w, rect->h);
+ trap_CIN_DrawCinematic(uiInfo.previewMovie);
+ } else {
+ uiInfo.previewMovie = -2;
+ }
+ }
+
+}
+
+
+
+static void UI_DrawSkill(rectDef_t *rect, float scale, vec4_t color, int textStyle) {
+ int i;
+ i = trap_Cvar_VariableValue( "g_spSkill" );
+ if (i < 1 || i > numSkillLevels) {
+ i = 1;
+ }
+ Text_Paint(rect->x, rect->y, scale, color, skillLevels[i-1],0, 0, textStyle);
+}
+
+
+static void UI_DrawTeamName(rectDef_t *rect, float scale, vec4_t color, qboolean blue, int textStyle) {
+ int i;
+ i = UI_TeamIndexFromName(UI_Cvar_VariableString((blue) ? "ui_blueTeam" : "ui_redTeam"));
+ if (i >= 0 && i < uiInfo.teamCount) {
+ Text_Paint(rect->x, rect->y, scale, color, va("%s: %s", (blue) ? "Blue" : "Red", uiInfo.teamList[i].teamName),0, 0, textStyle);
+ }
+}
+
+static void UI_DrawTeamMember(rectDef_t *rect, float scale, vec4_t color, qboolean blue, int num, int textStyle) {
+ // 0 - None
+ // 1 - Human
+ // 2..NumCharacters - Bot
+ int value = trap_Cvar_VariableValue(va(blue ? "ui_blueteam%i" : "ui_redteam%i", num));
+ const char *text;
+ if (value <= 0) {
+ text = "Closed";
+ } else if (value == 1) {
+ text = "Human";
+ } else {
+ value -= 2;
+
+ if (ui_actualNetGameType.integer >= GT_TEAM) {
+ if (value >= uiInfo.characterCount) {
+ value = 0;
+ }
+ text = uiInfo.characterList[value].name;
+ } else {
+ if (value >= UI_GetNumBots()) {
+ value = 0;
+ }
+ text = UI_GetBotNameByNumber(value);
+ }
+ }
+ Text_Paint(rect->x, rect->y, scale, color, text, 0, 0, textStyle);
+}
+
+static void UI_DrawEffects(rectDef_t *rect, float scale, vec4_t color) {
+ UI_DrawHandlePic( rect->x, rect->y - 14, 128, 8, uiInfo.uiDC.Assets.fxBasePic );
+ UI_DrawHandlePic( rect->x + uiInfo.effectsColor * 16 + 8, rect->y - 16, 16, 12, uiInfo.uiDC.Assets.fxPic[uiInfo.effectsColor] );
+}
+
+static void UI_DrawMapPreview(rectDef_t *rect, float scale, vec4_t color, qboolean net) {
+ int map = (net) ? ui_currentNetMap.integer : ui_currentMap.integer;
+ if (map < 0 || map > uiInfo.mapCount) {
+ if (net) {
+ ui_currentNetMap.integer = 0;
+ trap_Cvar_Set("ui_currentNetMap", "0");
+ } else {
+ ui_currentMap.integer = 0;
+ trap_Cvar_Set("ui_currentMap", "0");
+ }
+ map = 0;
+ }
+
+ if (uiInfo.mapList[map].levelShot == -1) {
+ uiInfo.mapList[map].levelShot = trap_R_RegisterShaderNoMip(uiInfo.mapList[map].imageName);
+ }
+
+ if (uiInfo.mapList[map].levelShot > 0) {
+ UI_DrawHandlePic( rect->x, rect->y, rect->w, rect->h, uiInfo.mapList[map].levelShot);
+ } else {
+ UI_DrawHandlePic( rect->x, rect->y, rect->w, rect->h, trap_R_RegisterShaderNoMip("menu/art/unknownmap"));
+ }
+}
+
+
+static void UI_DrawMapTimeToBeat(rectDef_t *rect, float scale, vec4_t color, int textStyle) {
+ int minutes, seconds, time;
+ if (ui_currentMap.integer < 0 || ui_currentMap.integer > uiInfo.mapCount) {
+ ui_currentMap.integer = 0;
+ trap_Cvar_Set("ui_currentMap", "0");
+ }
+
+ time = uiInfo.mapList[ui_currentMap.integer].timeToBeat[uiInfo.gameTypes[ui_gameType.integer].gtEnum];
+
+ minutes = time / 60;
+ seconds = time % 60;
+
+ Text_Paint(rect->x, rect->y, scale, color, va("%02i:%02i", minutes, seconds), 0, 0, textStyle);
+}
+
+
+
+static void UI_DrawMapCinematic(rectDef_t *rect, float scale, vec4_t color, qboolean net) {
+
+ int map = (net) ? ui_currentNetMap.integer : ui_currentMap.integer;
+ if (map < 0 || map > uiInfo.mapCount) {
+ if (net) {
+ ui_currentNetMap.integer = 0;
+ trap_Cvar_Set("ui_currentNetMap", "0");
+ } else {
+ ui_currentMap.integer = 0;
+ trap_Cvar_Set("ui_currentMap", "0");
+ }
+ map = 0;
+ }
+
+ if (uiInfo.mapList[map].cinematic >= -1) {
+ if (uiInfo.mapList[map].cinematic == -1) {
+ uiInfo.mapList[map].cinematic = trap_CIN_PlayCinematic(va("%s.roq", uiInfo.mapList[map].mapLoadName), 0, 0, 0, 0, (CIN_loop | CIN_silent) );
+ }
+ if (uiInfo.mapList[map].cinematic >= 0) {
+ trap_CIN_RunCinematic(uiInfo.mapList[map].cinematic);
+ trap_CIN_SetExtents(uiInfo.mapList[map].cinematic, rect->x, rect->y, rect->w, rect->h);
+ trap_CIN_DrawCinematic(uiInfo.mapList[map].cinematic);
+ } else {
+ uiInfo.mapList[map].cinematic = -2;
+ }
+ } else {
+ UI_DrawMapPreview(rect, scale, color, net);
+ }
+}
+
+
+
+static qboolean updateModel = qtrue;
+static qboolean q3Model = qfalse;
+
+static void UI_DrawPlayerModel(rectDef_t *rect) {
+ static playerInfo_t info;
+ char model[MAX_QPATH];
+ char team[256];
+ char head[256];
+ vec3_t viewangles;
+ vec3_t moveangles;
+
+ if (trap_Cvar_VariableValue("ui_Q3Model")) {
+ strcpy(model, UI_Cvar_VariableString("model"));
+ strcpy(head, UI_Cvar_VariableString("headmodel"));
+ if (!q3Model) {
+ q3Model = qtrue;
+ updateModel = qtrue;
+ }
+ team[0] = '\0';
+ } else {
+
+ strcpy(team, UI_Cvar_VariableString("ui_teamName"));
+ strcpy(model, UI_Cvar_VariableString("team_model"));
+ strcpy(head, UI_Cvar_VariableString("team_headmodel"));
+ if (q3Model) {
+ q3Model = qfalse;
+ updateModel = qtrue;
+ }
+ }
+ if (updateModel) {
+ memset( &info, 0, sizeof(playerInfo_t) );
+ viewangles[YAW] = 180 - 10;
+ viewangles[PITCH] = 0;
+ viewangles[ROLL] = 0;
+ VectorClear( moveangles );
+ UI_PlayerInfo_SetModel( &info, model, head, team);
+ UI_PlayerInfo_SetInfo( &info, LEGS_IDLE, TORSO_STAND, viewangles, vec3_origin, WP_MACHINEGUN, qfalse );
+// UI_RegisterClientModelname( &info, model, head, team);
+ updateModel = qfalse;
+ }
+
+ UI_DrawPlayer( rect->x, rect->y, rect->w, rect->h, &info, uiInfo.uiDC.realTime / 2);
+
+}
+
+static void UI_DrawNetSource(rectDef_t *rect, float scale, vec4_t color, int textStyle) {
+ if (ui_netSource.integer < 0 || ui_netSource.integer > numNetSources) {
+ ui_netSource.integer = 0;
+ }
+ Text_Paint(rect->x, rect->y, scale, color, va("Source: %s", netSources[ui_netSource.integer]), 0, 0, textStyle);
+}
+
+static void UI_DrawNetMapPreview(rectDef_t *rect, float scale, vec4_t color) {
+
+ if (uiInfo.serverStatus.currentServerPreview > 0) {
+ UI_DrawHandlePic( rect->x, rect->y, rect->w, rect->h, uiInfo.serverStatus.currentServerPreview);
+ } else {
+ UI_DrawHandlePic( rect->x, rect->y, rect->w, rect->h, trap_R_RegisterShaderNoMip("menu/art/unknownmap"));
+ }
+}
+
+static void UI_DrawNetMapCinematic(rectDef_t *rect, float scale, vec4_t color) {
+ if (ui_currentNetMap.integer < 0 || ui_currentNetMap.integer > uiInfo.mapCount) {
+ ui_currentNetMap.integer = 0;
+ trap_Cvar_Set("ui_currentNetMap", "0");
+ }
+
+ if (uiInfo.serverStatus.currentServerCinematic >= 0) {
+ trap_CIN_RunCinematic(uiInfo.serverStatus.currentServerCinematic);
+ trap_CIN_SetExtents(uiInfo.serverStatus.currentServerCinematic, rect->x, rect->y, rect->w, rect->h);
+ trap_CIN_DrawCinematic(uiInfo.serverStatus.currentServerCinematic);
+ } else {
+ UI_DrawNetMapPreview(rect, scale, color);
+ }
+}
+
+
+
+static void UI_DrawNetFilter(rectDef_t *rect, float scale, vec4_t color, int textStyle) {
+ if (ui_serverFilterType.integer < 0 || ui_serverFilterType.integer > numServerFilters) {
+ ui_serverFilterType.integer = 0;
+ }
+ Text_Paint(rect->x, rect->y, scale, color, va("Filter: %s", serverFilters[ui_serverFilterType.integer].description), 0, 0, textStyle);
+}
+
+
+static void UI_DrawTier(rectDef_t *rect, float scale, vec4_t color, int textStyle) {
+ int i;
+ i = trap_Cvar_VariableValue( "ui_currentTier" );
+ if (i < 0 || i >= uiInfo.tierCount) {
+ i = 0;
+ }
+ Text_Paint(rect->x, rect->y, scale, color, va("Tier: %s", uiInfo.tierList[i].tierName),0, 0, textStyle);
+}
+
+static void UI_DrawTierMap(rectDef_t *rect, int index) {
+ int i;
+ i = trap_Cvar_VariableValue( "ui_currentTier" );
+ if (i < 0 || i >= uiInfo.tierCount) {
+ i = 0;
+ }
+
+ if (uiInfo.tierList[i].mapHandles[index] == -1) {
+ uiInfo.tierList[i].mapHandles[index] = trap_R_RegisterShaderNoMip(va("levelshots/%s", uiInfo.tierList[i].maps[index]));
+ }
+
+ UI_DrawHandlePic( rect->x, rect->y, rect->w, rect->h, uiInfo.tierList[i].mapHandles[index]);
+}
+
+static const char *UI_EnglishMapName(const char *map) {
+ int i;
+ for (i = 0; i < uiInfo.mapCount; i++) {
+ if (Q_stricmp(map, uiInfo.mapList[i].mapLoadName) == 0) {
+ return uiInfo.mapList[i].mapName;
+ }
+ }
+ return "";
+}
+
+static void UI_DrawTierMapName(rectDef_t *rect, float scale, vec4_t color, int textStyle) {
+ int i, j;
+ i = trap_Cvar_VariableValue( "ui_currentTier" );
+ if (i < 0 || i >= uiInfo.tierCount) {
+ i = 0;
+ }
+ j = trap_Cvar_VariableValue("ui_currentMap");
+ if (j < 0 || j > MAPS_PER_TIER) {
+ j = 0;
+ }
+
+ Text_Paint(rect->x, rect->y, scale, color, UI_EnglishMapName(uiInfo.tierList[i].maps[j]), 0, 0, textStyle);
+}
+
+static void UI_DrawTierGameType(rectDef_t *rect, float scale, vec4_t color, int textStyle) {
+ int i, j;
+ i = trap_Cvar_VariableValue( "ui_currentTier" );
+ if (i < 0 || i >= uiInfo.tierCount) {
+ i = 0;
+ }
+ j = trap_Cvar_VariableValue("ui_currentMap");
+ if (j < 0 || j > MAPS_PER_TIER) {
+ j = 0;
+ }
+
+ Text_Paint(rect->x, rect->y, scale, color, uiInfo.gameTypes[uiInfo.tierList[i].gameTypes[j]].gameType , 0, 0, textStyle);
+}
+
+
+#ifndef MISSIONPACK // bk001206
+static const char *UI_OpponentLeaderName() {
+ int i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_opponentName"));
+ return uiInfo.teamList[i].teamMembers[0];
+}
+#endif
+
+static const char *UI_AIFromName(const char *name) {
+ int j;
+ for (j = 0; j < uiInfo.aliasCount; j++) {
+ if (Q_stricmp(uiInfo.aliasList[j].name, name) == 0) {
+ return uiInfo.aliasList[j].ai;
+ }
+ }
+ return "James";
+}
+
+#ifndef MISSIONPACK // bk001206
+static const int UI_AIIndex(const char *name) {
+ int j;
+ for (j = 0; j < uiInfo.characterCount; j++) {
+ if (Q_stricmp(name, uiInfo.characterList[j].name) == 0) {
+ return j;
+ }
+ }
+ return 0;
+}
+#endif
+
+#ifndef MISSIONPACK // bk001206
+static const int UI_AIIndexFromName(const char *name) {
+ int j;
+ for (j = 0; j < uiInfo.aliasCount; j++) {
+ if (Q_stricmp(uiInfo.aliasList[j].name, name) == 0) {
+ return UI_AIIndex(uiInfo.aliasList[j].ai);
+ }
+ }
+ return 0;
+}
+#endif
+
+
+#ifndef MISSIONPACK // bk001206
+static const char *UI_OpponentLeaderHead() {
+ const char *leader = UI_OpponentLeaderName();
+ return UI_AIFromName(leader);
+}
+#endif
+
+#ifndef MISSIONPACK // bk001206
+static const char *UI_OpponentLeaderModel() {
+ int i;
+ const char *head = UI_OpponentLeaderHead();
+ for (i = 0; i < uiInfo.characterCount; i++) {
+ if (Q_stricmp(head, uiInfo.characterList[i].name) == 0) {
+ return uiInfo.characterList[i].base;
+ }
+ }
+ return "James";
+}
+#endif
+
+
+static qboolean updateOpponentModel = qtrue;
+static void UI_DrawOpponent(rectDef_t *rect) {
+ static playerInfo_t info2;
+ char model[MAX_QPATH];
+ char headmodel[MAX_QPATH];
+ char team[256];
+ vec3_t viewangles;
+ vec3_t moveangles;
+
+ if (updateOpponentModel) {
+
+ strcpy(model, UI_Cvar_VariableString("ui_opponentModel"));
+ strcpy(headmodel, UI_Cvar_VariableString("ui_opponentModel"));
+ team[0] = '\0';
+
+ memset( &info2, 0, sizeof(playerInfo_t) );
+ viewangles[YAW] = 180 - 10;
+ viewangles[PITCH] = 0;
+ viewangles[ROLL] = 0;
+ VectorClear( moveangles );
+ UI_PlayerInfo_SetModel( &info2, model, headmodel, "");
+ UI_PlayerInfo_SetInfo( &info2, LEGS_IDLE, TORSO_STAND, viewangles, vec3_origin, WP_MACHINEGUN, qfalse );
+ UI_RegisterClientModelname( &info2, model, headmodel, team);
+ updateOpponentModel = qfalse;
+ }
+
+ UI_DrawPlayer( rect->x, rect->y, rect->w, rect->h, &info2, uiInfo.uiDC.realTime / 2);
+
+}
+
+static void UI_NextOpponent() {
+ int i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_opponentName"));
+ int j = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_teamName"));
+ i++;
+ if (i >= uiInfo.teamCount) {
+ i = 0;
+ }
+ if (i == j) {
+ i++;
+ if ( i >= uiInfo.teamCount) {
+ i = 0;
+ }
+ }
+ trap_Cvar_Set( "ui_opponentName", uiInfo.teamList[i].teamName );
+}
+
+static void UI_PriorOpponent() {
+ int i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_opponentName"));
+ int j = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_teamName"));
+ i--;
+ if (i < 0) {
+ i = uiInfo.teamCount - 1;
+ }
+ if (i == j) {
+ i--;
+ if ( i < 0) {
+ i = uiInfo.teamCount - 1;
+ }
+ }
+ trap_Cvar_Set( "ui_opponentName", uiInfo.teamList[i].teamName );
+}
+
+static void UI_DrawPlayerLogo(rectDef_t *rect, vec3_t color) {
+ int i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_teamName"));
+
+ if (uiInfo.teamList[i].teamIcon == -1) {
+ uiInfo.teamList[i].teamIcon = trap_R_RegisterShaderNoMip(uiInfo.teamList[i].imageName);
+ uiInfo.teamList[i].teamIcon_Metal = trap_R_RegisterShaderNoMip(va("%s_metal",uiInfo.teamList[i].imageName));
+ uiInfo.teamList[i].teamIcon_Name = trap_R_RegisterShaderNoMip(va("%s_name", uiInfo.teamList[i].imageName));
+ }
+
+ trap_R_SetColor( color );
+ UI_DrawHandlePic( rect->x, rect->y, rect->w, rect->h, uiInfo.teamList[i].teamIcon );
+ trap_R_SetColor( NULL );
+}
+
+static void UI_DrawPlayerLogoMetal(rectDef_t *rect, vec3_t color) {
+ int i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_teamName"));
+ if (uiInfo.teamList[i].teamIcon == -1) {
+ uiInfo.teamList[i].teamIcon = trap_R_RegisterShaderNoMip(uiInfo.teamList[i].imageName);
+ uiInfo.teamList[i].teamIcon_Metal = trap_R_RegisterShaderNoMip(va("%s_metal",uiInfo.teamList[i].imageName));
+ uiInfo.teamList[i].teamIcon_Name = trap_R_RegisterShaderNoMip(va("%s_name", uiInfo.teamList[i].imageName));
+ }
+
+ trap_R_SetColor( color );
+ UI_DrawHandlePic( rect->x, rect->y, rect->w, rect->h, uiInfo.teamList[i].teamIcon_Metal );
+ trap_R_SetColor( NULL );
+}
+
+static void UI_DrawPlayerLogoName(rectDef_t *rect, vec3_t color) {
+ int i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_teamName"));
+ if (uiInfo.teamList[i].teamIcon == -1) {
+ uiInfo.teamList[i].teamIcon = trap_R_RegisterShaderNoMip(uiInfo.teamList[i].imageName);
+ uiInfo.teamList[i].teamIcon_Metal = trap_R_RegisterShaderNoMip(va("%s_metal",uiInfo.teamList[i].imageName));
+ uiInfo.teamList[i].teamIcon_Name = trap_R_RegisterShaderNoMip(va("%s_name", uiInfo.teamList[i].imageName));
+ }
+
+ trap_R_SetColor( color );
+ UI_DrawHandlePic( rect->x, rect->y, rect->w, rect->h, uiInfo.teamList[i].teamIcon_Name );
+ trap_R_SetColor( NULL );
+}
+
+static void UI_DrawOpponentLogo(rectDef_t *rect, vec3_t color) {
+ int i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_opponentName"));
+ if (uiInfo.teamList[i].teamIcon == -1) {
+ uiInfo.teamList[i].teamIcon = trap_R_RegisterShaderNoMip(uiInfo.teamList[i].imageName);
+ uiInfo.teamList[i].teamIcon_Metal = trap_R_RegisterShaderNoMip(va("%s_metal",uiInfo.teamList[i].imageName));
+ uiInfo.teamList[i].teamIcon_Name = trap_R_RegisterShaderNoMip(va("%s_name", uiInfo.teamList[i].imageName));
+ }
+
+ trap_R_SetColor( color );
+ UI_DrawHandlePic( rect->x, rect->y, rect->w, rect->h, uiInfo.teamList[i].teamIcon );
+ trap_R_SetColor( NULL );
+}
+
+static void UI_DrawOpponentLogoMetal(rectDef_t *rect, vec3_t color) {
+ int i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_opponentName"));
+ if (uiInfo.teamList[i].teamIcon == -1) {
+ uiInfo.teamList[i].teamIcon = trap_R_RegisterShaderNoMip(uiInfo.teamList[i].imageName);
+ uiInfo.teamList[i].teamIcon_Metal = trap_R_RegisterShaderNoMip(va("%s_metal",uiInfo.teamList[i].imageName));
+ uiInfo.teamList[i].teamIcon_Name = trap_R_RegisterShaderNoMip(va("%s_name", uiInfo.teamList[i].imageName));
+ }
+
+ trap_R_SetColor( color );
+ UI_DrawHandlePic( rect->x, rect->y, rect->w, rect->h, uiInfo.teamList[i].teamIcon_Metal );
+ trap_R_SetColor( NULL );
+}
+
+static void UI_DrawOpponentLogoName(rectDef_t *rect, vec3_t color) {
+ int i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_opponentName"));
+ if (uiInfo.teamList[i].teamIcon == -1) {
+ uiInfo.teamList[i].teamIcon = trap_R_RegisterShaderNoMip(uiInfo.teamList[i].imageName);
+ uiInfo.teamList[i].teamIcon_Metal = trap_R_RegisterShaderNoMip(va("%s_metal",uiInfo.teamList[i].imageName));
+ uiInfo.teamList[i].teamIcon_Name = trap_R_RegisterShaderNoMip(va("%s_name", uiInfo.teamList[i].imageName));
+ }
+
+ trap_R_SetColor( color );
+ UI_DrawHandlePic( rect->x, rect->y, rect->w, rect->h, uiInfo.teamList[i].teamIcon_Name );
+ trap_R_SetColor( NULL );
+}
+
+static void UI_DrawAllMapsSelection(rectDef_t *rect, float scale, vec4_t color, int textStyle, qboolean net) {
+ int map = (net) ? ui_currentNetMap.integer : ui_currentMap.integer;
+ if (map >= 0 && map < uiInfo.mapCount) {
+ Text_Paint(rect->x, rect->y, scale, color, uiInfo.mapList[map].mapName, 0, 0, textStyle);
+ }
+}
+
+static void UI_DrawOpponentName(rectDef_t *rect, float scale, vec4_t color, int textStyle) {
+ Text_Paint(rect->x, rect->y, scale, color, UI_Cvar_VariableString("ui_opponentName"), 0, 0, textStyle);
+}
+
+
+static int UI_OwnerDrawWidth(int ownerDraw, float scale) {
+ int i, h, value;
+ const char *text;
+ const char *s = NULL;
+
+ switch (ownerDraw) {
+ case UI_HANDICAP:
+ h = Com_Clamp( 5, 100, trap_Cvar_VariableValue("handicap") );
+ i = 20 - h / 5;
+ s = handicapValues[i];
+ break;
+ case UI_CLANNAME:
+ s = UI_Cvar_VariableString("ui_teamName");
+ break;
+ case UI_GAMETYPE:
+ s = uiInfo.gameTypes[ui_gameType.integer].gameType;
+ break;
+ case UI_SKILL:
+ i = trap_Cvar_VariableValue( "g_spSkill" );
+ if (i < 1 || i > numSkillLevels) {
+ i = 1;
+ }
+ s = skillLevels[i-1];
+ break;
+ case UI_BLUETEAMNAME:
+ i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_blueTeam"));
+ if (i >= 0 && i < uiInfo.teamCount) {
+ s = va("%s: %s", "Blue", uiInfo.teamList[i].teamName);
+ }
+ break;
+ case UI_REDTEAMNAME:
+ i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_redTeam"));
+ if (i >= 0 && i < uiInfo.teamCount) {
+ s = va("%s: %s", "Red", uiInfo.teamList[i].teamName);
+ }
+ break;
+ case UI_BLUETEAM1:
+ case UI_BLUETEAM2:
+ case UI_BLUETEAM3:
+ case UI_BLUETEAM4:
+ case UI_BLUETEAM5:
+ value = trap_Cvar_VariableValue(va("ui_blueteam%i", ownerDraw-UI_BLUETEAM1 + 1));
+ if (value <= 0) {
+ text = "Closed";
+ } else if (value == 1) {
+ text = "Human";
+ } else {
+ value -= 2;
+ if (value >= uiInfo.aliasCount) {
+ value = 0;
+ }
+ text = uiInfo.aliasList[value].name;
+ }
+ s = va("%i. %s", ownerDraw-UI_BLUETEAM1 + 1, text);
+ break;
+ case UI_REDTEAM1:
+ case UI_REDTEAM2:
+ case UI_REDTEAM3:
+ case UI_REDTEAM4:
+ case UI_REDTEAM5:
+ value = trap_Cvar_VariableValue(va("ui_redteam%i", ownerDraw-UI_REDTEAM1 + 1));
+ if (value <= 0) {
+ text = "Closed";
+ } else if (value == 1) {
+ text = "Human";
+ } else {
+ value -= 2;
+ if (value >= uiInfo.aliasCount) {
+ value = 0;
+ }
+ text = uiInfo.aliasList[value].name;
+ }
+ s = va("%i. %s", ownerDraw-UI_REDTEAM1 + 1, text);
+ break;
+ case UI_NETSOURCE:
+ if (ui_netSource.integer < 0 || ui_netSource.integer > uiInfo.numJoinGameTypes) {
+ ui_netSource.integer = 0;
+ }
+ s = va("Source: %s", netSources[ui_netSource.integer]);
+ break;
+ case UI_NETFILTER:
+ if (ui_serverFilterType.integer < 0 || ui_serverFilterType.integer > numServerFilters) {
+ ui_serverFilterType.integer = 0;
+ }
+ s = va("Filter: %s", serverFilters[ui_serverFilterType.integer].description );
+ break;
+ case UI_TIER:
+ break;
+ case UI_TIER_MAPNAME:
+ break;
+ case UI_TIER_GAMETYPE:
+ break;
+ case UI_ALLMAPS_SELECTION:
+ break;
+ case UI_OPPONENT_NAME:
+ break;
+ case UI_KEYBINDSTATUS:
+ if (Display_KeyBindPending()) {
+ s = "Waiting for new key... Press ESCAPE to cancel";
+ } else {
+ s = "Press ENTER or CLICK to change, Press BACKSPACE to clear";
+ }
+ break;
+ case UI_SERVERREFRESHDATE:
+ s = UI_Cvar_VariableString(va("ui_lastServerRefresh_%i", ui_netSource.integer));
+ break;
+ default:
+ break;
+ }
+
+ if (s) {
+ return Text_Width(s, scale, 0);
+ }
+ return 0;
+}
+
+static void UI_DrawBotName(rectDef_t *rect, float scale, vec4_t color, int textStyle) {
+ int value = uiInfo.botIndex;
+ int game = trap_Cvar_VariableValue("g_gametype");
+ const char *text = "";
+ if (game >= GT_TEAM) {
+ if (value >= uiInfo.characterCount) {
+ value = 0;
+ }
+ text = uiInfo.characterList[value].name;
+ } else {
+ if (value >= UI_GetNumBots()) {
+ value = 0;
+ }
+ text = UI_GetBotNameByNumber(value);
+ }
+ Text_Paint(rect->x, rect->y, scale, color, text, 0, 0, textStyle);
+}
+
+static void UI_DrawBotSkill(rectDef_t *rect, float scale, vec4_t color, int textStyle) {
+ if (uiInfo.skillIndex >= 0 && uiInfo.skillIndex < numSkillLevels) {
+ Text_Paint(rect->x, rect->y, scale, color, skillLevels[uiInfo.skillIndex], 0, 0, textStyle);
+ }
+}
+
+static void UI_DrawRedBlue(rectDef_t *rect, float scale, vec4_t color, int textStyle) {
+ Text_Paint(rect->x, rect->y, scale, color, (uiInfo.redBlue == 0) ? "Red" : "Blue", 0, 0, textStyle);
+}
+
+static void UI_DrawCrosshair(rectDef_t *rect, float scale, vec4_t color) {
+ trap_R_SetColor( color );
+ if (uiInfo.currentCrosshair < 0 || uiInfo.currentCrosshair >= NUM_CROSSHAIRS) {
+ uiInfo.currentCrosshair = 0;
+ }
+ UI_DrawHandlePic( rect->x, rect->y - rect->h, rect->w, rect->h, uiInfo.uiDC.Assets.crosshairShader[uiInfo.currentCrosshair]);
+ trap_R_SetColor( NULL );
+}
+
+/*
+===============
+UI_BuildPlayerList
+===============
+*/
+static void UI_BuildPlayerList() {
+ uiClientState_t cs;
+ int n, count, team, team2, playerTeamNumber;
+ char info[MAX_INFO_STRING];
+
+ trap_GetClientState( &cs );
+ trap_GetConfigString( CS_PLAYERS + cs.clientNum, info, MAX_INFO_STRING );
+ uiInfo.playerNumber = cs.clientNum;
+ uiInfo.teamLeader = atoi(Info_ValueForKey(info, "tl"));
+ team = atoi(Info_ValueForKey(info, "t"));
+ trap_GetConfigString( CS_SERVERINFO, info, sizeof(info) );
+ count = atoi( Info_ValueForKey( info, "sv_maxclients" ) );
+ uiInfo.playerCount = 0;
+ uiInfo.myTeamCount = 0;
+ playerTeamNumber = 0;
+ for( n = 0; n < count; n++ ) {
+ trap_GetConfigString( CS_PLAYERS + n, info, MAX_INFO_STRING );
+
+ if (info[0]) {
+ Q_strncpyz( uiInfo.playerNames[uiInfo.playerCount], Info_ValueForKey( info, "n" ), MAX_NAME_LENGTH );
+ Q_CleanStr( uiInfo.playerNames[uiInfo.playerCount] );
+ uiInfo.playerCount++;
+ team2 = atoi(Info_ValueForKey(info, "t"));
+ if (team2 == team) {
+ Q_strncpyz( uiInfo.teamNames[uiInfo.myTeamCount], Info_ValueForKey( info, "n" ), MAX_NAME_LENGTH );
+ Q_CleanStr( uiInfo.teamNames[uiInfo.myTeamCount] );
+ uiInfo.teamClientNums[uiInfo.myTeamCount] = n;
+ if (uiInfo.playerNumber == n) {
+ playerTeamNumber = uiInfo.myTeamCount;
+ }
+ uiInfo.myTeamCount++;
+ }
+ }
+ }
+
+ if (!uiInfo.teamLeader) {
+ trap_Cvar_Set("cg_selectedPlayer", va("%d", playerTeamNumber));
+ }
+
+ n = trap_Cvar_VariableValue("cg_selectedPlayer");
+ if (n < 0 || n > uiInfo.myTeamCount) {
+ n = 0;
+ }
+ if (n < uiInfo.myTeamCount) {
+ trap_Cvar_Set("cg_selectedPlayerName", uiInfo.teamNames[n]);
+ }
+}
+
+
+static void UI_DrawSelectedPlayer(rectDef_t *rect, float scale, vec4_t color, int textStyle) {
+ if (uiInfo.uiDC.realTime > uiInfo.playerRefresh) {
+ uiInfo.playerRefresh = uiInfo.uiDC.realTime + 3000;
+ UI_BuildPlayerList();
+ }
+ Text_Paint(rect->x, rect->y, scale, color, (uiInfo.teamLeader) ? UI_Cvar_VariableString("cg_selectedPlayerName") : UI_Cvar_VariableString("name") , 0, 0, textStyle);
+}
+
+static void UI_DrawServerRefreshDate(rectDef_t *rect, float scale, vec4_t color, int textStyle) {
+ if (uiInfo.serverStatus.refreshActive) {
+ vec4_t lowLight, newColor;
+ lowLight[0] = 0.8 * color[0];
+ lowLight[1] = 0.8 * color[1];
+ lowLight[2] = 0.8 * color[2];
+ lowLight[3] = 0.8 * color[3];
+ LerpColor(color,lowLight,newColor,0.5+0.5*sin(uiInfo.uiDC.realTime / PULSE_DIVISOR));
+ Text_Paint(rect->x, rect->y, scale, newColor, va("Getting info for %d servers (ESC to cancel)", trap_LAN_GetServerCount(ui_netSource.integer)), 0, 0, textStyle);
+ } else {
+ char buff[64];
+ Q_strncpyz(buff, UI_Cvar_VariableString(va("ui_lastServerRefresh_%i", ui_netSource.integer)), 64);
+ Text_Paint(rect->x, rect->y, scale, color, va("Refresh Time: %s", buff), 0, 0, textStyle);
+ }
+}
+
+static void UI_DrawServerMOTD(rectDef_t *rect, float scale, vec4_t color) {
+ if (uiInfo.serverStatus.motdLen) {
+ float maxX;
+
+ if (uiInfo.serverStatus.motdWidth == -1) {
+ uiInfo.serverStatus.motdWidth = 0;
+ uiInfo.serverStatus.motdPaintX = rect->x + 1;
+ uiInfo.serverStatus.motdPaintX2 = -1;
+ }
+
+ if (uiInfo.serverStatus.motdOffset > uiInfo.serverStatus.motdLen) {
+ uiInfo.serverStatus.motdOffset = 0;
+ uiInfo.serverStatus.motdPaintX = rect->x + 1;
+ uiInfo.serverStatus.motdPaintX2 = -1;
+ }
+
+ if (uiInfo.uiDC.realTime > uiInfo.serverStatus.motdTime) {
+ uiInfo.serverStatus.motdTime = uiInfo.uiDC.realTime + 10;
+ if (uiInfo.serverStatus.motdPaintX <= rect->x + 2) {
+ if (uiInfo.serverStatus.motdOffset < uiInfo.serverStatus.motdLen) {
+ uiInfo.serverStatus.motdPaintX += Text_Width(&uiInfo.serverStatus.motd[uiInfo.serverStatus.motdOffset], scale, 1) - 1;
+ uiInfo.serverStatus.motdOffset++;
+ } else {
+ uiInfo.serverStatus.motdOffset = 0;
+ if (uiInfo.serverStatus.motdPaintX2 >= 0) {
+ uiInfo.serverStatus.motdPaintX = uiInfo.serverStatus.motdPaintX2;
+ } else {
+ uiInfo.serverStatus.motdPaintX = rect->x + rect->w - 2;
+ }
+ uiInfo.serverStatus.motdPaintX2 = -1;
+ }
+ } else {
+ //serverStatus.motdPaintX--;
+ uiInfo.serverStatus.motdPaintX -= 2;
+ if (uiInfo.serverStatus.motdPaintX2 >= 0) {
+ //serverStatus.motdPaintX2--;
+ uiInfo.serverStatus.motdPaintX2 -= 2;
+ }
+ }
+ }
+
+ maxX = rect->x + rect->w - 2;
+ Text_Paint_Limit(&maxX, uiInfo.serverStatus.motdPaintX, rect->y + rect->h - 3, scale, color, &uiInfo.serverStatus.motd[uiInfo.serverStatus.motdOffset], 0, 0);
+ if (uiInfo.serverStatus.motdPaintX2 >= 0) {
+ float maxX2 = rect->x + rect->w - 2;
+ Text_Paint_Limit(&maxX2, uiInfo.serverStatus.motdPaintX2, rect->y + rect->h - 3, scale, color, uiInfo.serverStatus.motd, 0, uiInfo.serverStatus.motdOffset);
+ }
+ if (uiInfo.serverStatus.motdOffset && maxX > 0) {
+ // if we have an offset ( we are skipping the first part of the string ) and we fit the string
+ if (uiInfo.serverStatus.motdPaintX2 == -1) {
+ uiInfo.serverStatus.motdPaintX2 = rect->x + rect->w - 2;
+ }
+ } else {
+ uiInfo.serverStatus.motdPaintX2 = -1;
+ }
+
+ }
+}
+
+static void UI_DrawKeyBindStatus(rectDef_t *rect, float scale, vec4_t color, int textStyle) {
+// int ofs = 0; TTimo: unused
+ if (Display_KeyBindPending()) {
+ Text_Paint(rect->x, rect->y, scale, color, "Waiting for new key... Press ESCAPE to cancel", 0, 0, textStyle);
+ } else {
+ Text_Paint(rect->x, rect->y, scale, color, "Press ENTER or CLICK to change, Press BACKSPACE to clear", 0, 0, textStyle);
+ }
+}
+
+static void UI_DrawGLInfo(rectDef_t *rect, float scale, vec4_t color, int textStyle) {
+ char * eptr;
+ char buff[1024];
+ const char *lines[64];
+ int y, numLines, i;
+
+ Text_Paint(rect->x + 2, rect->y, scale, color, va("VENDOR: %s", uiInfo.uiDC.glconfig.vendor_string), 0, 30, textStyle);
+ Text_Paint(rect->x + 2, rect->y + 15, scale, color, va("VERSION: %s: %s", uiInfo.uiDC.glconfig.version_string,uiInfo.uiDC.glconfig.renderer_string), 0, 30, textStyle);
+ Text_Paint(rect->x + 2, rect->y + 30, scale, color, va ("PIXELFORMAT: color(%d-bits) Z(%d-bits) stencil(%d-bits)", uiInfo.uiDC.glconfig.colorBits, uiInfo.uiDC.glconfig.depthBits, uiInfo.uiDC.glconfig.stencilBits), 0, 30, textStyle);
+
+ // build null terminated extension strings
+ // TTimo: https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=399
+ // in TA this was not directly crashing, but displaying a nasty broken shader right in the middle
+ // brought down the string size to 1024, there's not much that can be shown on the screen anyway
+ Q_strncpyz(buff, uiInfo.uiDC.glconfig.extensions_string, 1024);
+ eptr = buff;
+ y = rect->y + 45;
+ numLines = 0;
+ while ( y < rect->y + rect->h && *eptr )
+ {
+ while ( *eptr && *eptr == ' ' )
+ *eptr++ = '\0';
+
+ // track start of valid string
+ if (*eptr && *eptr != ' ') {
+ lines[numLines++] = eptr;
+ }
+
+ while ( *eptr && *eptr != ' ' )
+ eptr++;
+ }
+
+ i = 0;
+ while (i < numLines) {
+ Text_Paint(rect->x + 2, y, scale, color, lines[i++], 0, 20, textStyle);
+ if (i < numLines) {
+ Text_Paint(rect->x + rect->w / 2, y, scale, color, lines[i++], 0, 20, textStyle);
+ }
+ y += 10;
+ if (y > rect->y + rect->h - 11) {
+ break;
+ }
+ }
+
+
+}
+
+// FIXME: table drive
+//
+static void UI_OwnerDraw(float x, float y, float w, float h, float text_x, float text_y, int ownerDraw, int ownerDrawFlags, int align, float special, float scale, vec4_t color, qhandle_t shader, int textStyle) {
+ rectDef_t rect;
+
+ rect.x = x + text_x;
+ rect.y = y + text_y;
+ rect.w = w;
+ rect.h = h;
+
+ switch (ownerDraw) {
+ case UI_HANDICAP:
+ UI_DrawHandicap(&rect, scale, color, textStyle);
+ break;
+ case UI_EFFECTS:
+ UI_DrawEffects(&rect, scale, color);
+ break;
+ case UI_PLAYERMODEL:
+ UI_DrawPlayerModel(&rect);
+ break;
+ case UI_CLANNAME:
+ UI_DrawClanName(&rect, scale, color, textStyle);
+ break;
+ case UI_CLANLOGO:
+ UI_DrawClanLogo(&rect, scale, color);
+ break;
+ case UI_CLANCINEMATIC:
+ UI_DrawClanCinematic(&rect, scale, color);
+ break;
+ case UI_PREVIEWCINEMATIC:
+ UI_DrawPreviewCinematic(&rect, scale, color);
+ break;
+ case UI_GAMETYPE:
+ UI_DrawGameType(&rect, scale, color, textStyle);
+ break;
+ case UI_NETGAMETYPE:
+ UI_DrawNetGameType(&rect, scale, color, textStyle);
+ break;
+ case UI_JOINGAMETYPE:
+ UI_DrawJoinGameType(&rect, scale, color, textStyle);
+ break;
+ case UI_MAPPREVIEW:
+ UI_DrawMapPreview(&rect, scale, color, qtrue);
+ break;
+ case UI_MAP_TIMETOBEAT:
+ UI_DrawMapTimeToBeat(&rect, scale, color, textStyle);
+ break;
+ case UI_MAPCINEMATIC:
+ UI_DrawMapCinematic(&rect, scale, color, qfalse);
+ break;
+ case UI_STARTMAPCINEMATIC:
+ UI_DrawMapCinematic(&rect, scale, color, qtrue);
+ break;
+ case UI_SKILL:
+ UI_DrawSkill(&rect, scale, color, textStyle);
+ break;
+ case UI_BLUETEAMNAME:
+ UI_DrawTeamName(&rect, scale, color, qtrue, textStyle);
+ break;
+ case UI_REDTEAMNAME:
+ UI_DrawTeamName(&rect, scale, color, qfalse, textStyle);
+ break;
+ case UI_BLUETEAM1:
+ case UI_BLUETEAM2:
+ case UI_BLUETEAM3:
+ case UI_BLUETEAM4:
+ case UI_BLUETEAM5:
+ UI_DrawTeamMember(&rect, scale, color, qtrue, ownerDraw - UI_BLUETEAM1 + 1, textStyle);
+ break;
+ case UI_REDTEAM1:
+ case UI_REDTEAM2:
+ case UI_REDTEAM3:
+ case UI_REDTEAM4:
+ case UI_REDTEAM5:
+ UI_DrawTeamMember(&rect, scale, color, qfalse, ownerDraw - UI_REDTEAM1 + 1, textStyle);
+ break;
+ case UI_NETSOURCE:
+ UI_DrawNetSource(&rect, scale, color, textStyle);
+ break;
+ case UI_NETMAPPREVIEW:
+ UI_DrawNetMapPreview(&rect, scale, color);
+ break;
+ case UI_NETMAPCINEMATIC:
+ UI_DrawNetMapCinematic(&rect, scale, color);
+ break;
+ case UI_NETFILTER:
+ UI_DrawNetFilter(&rect, scale, color, textStyle);
+ break;
+ case UI_TIER:
+ UI_DrawTier(&rect, scale, color, textStyle);
+ break;
+ case UI_OPPONENTMODEL:
+ UI_DrawOpponent(&rect);
+ break;
+ case UI_TIERMAP1:
+ UI_DrawTierMap(&rect, 0);
+ break;
+ case UI_TIERMAP2:
+ UI_DrawTierMap(&rect, 1);
+ break;
+ case UI_TIERMAP3:
+ UI_DrawTierMap(&rect, 2);
+ break;
+ case UI_PLAYERLOGO:
+ UI_DrawPlayerLogo(&rect, color);
+ break;
+ case UI_PLAYERLOGO_METAL:
+ UI_DrawPlayerLogoMetal(&rect, color);
+ break;
+ case UI_PLAYERLOGO_NAME:
+ UI_DrawPlayerLogoName(&rect, color);
+ break;
+ case UI_OPPONENTLOGO:
+ UI_DrawOpponentLogo(&rect, color);
+ break;
+ case UI_OPPONENTLOGO_METAL:
+ UI_DrawOpponentLogoMetal(&rect, color);
+ break;
+ case UI_OPPONENTLOGO_NAME:
+ UI_DrawOpponentLogoName(&rect, color);
+ break;
+ case UI_TIER_MAPNAME:
+ UI_DrawTierMapName(&rect, scale, color, textStyle);
+ break;
+ case UI_TIER_GAMETYPE:
+ UI_DrawTierGameType(&rect, scale, color, textStyle);
+ break;
+ case UI_ALLMAPS_SELECTION:
+ UI_DrawAllMapsSelection(&rect, scale, color, textStyle, qtrue);
+ break;
+ case UI_MAPS_SELECTION:
+ UI_DrawAllMapsSelection(&rect, scale, color, textStyle, qfalse);
+ break;
+ case UI_OPPONENT_NAME:
+ UI_DrawOpponentName(&rect, scale, color, textStyle);
+ break;
+ case UI_BOTNAME:
+ UI_DrawBotName(&rect, scale, color, textStyle);
+ break;
+ case UI_BOTSKILL:
+ UI_DrawBotSkill(&rect, scale, color, textStyle);
+ break;
+ case UI_REDBLUE:
+ UI_DrawRedBlue(&rect, scale, color, textStyle);
+ break;
+ case UI_CROSSHAIR:
+ UI_DrawCrosshair(&rect, scale, color);
+ break;
+ case UI_SELECTEDPLAYER:
+ UI_DrawSelectedPlayer(&rect, scale, color, textStyle);
+ break;
+ case UI_SERVERREFRESHDATE:
+ UI_DrawServerRefreshDate(&rect, scale, color, textStyle);
+ break;
+ case UI_SERVERMOTD:
+ UI_DrawServerMOTD(&rect, scale, color);
+ break;
+ case UI_GLINFO:
+ UI_DrawGLInfo(&rect,scale, color, textStyle);
+ break;
+ case UI_KEYBINDSTATUS:
+ UI_DrawKeyBindStatus(&rect,scale, color, textStyle);
+ break;
+ default:
+ break;
+ }
+
+}
+
+static qboolean UI_OwnerDrawVisible(int flags) {
+ qboolean vis = qtrue;
+
+ while (flags) {
+
+ if (flags & UI_SHOW_FFA) {
+ if (trap_Cvar_VariableValue("g_gametype") != GT_FFA) {
+ vis = qfalse;
+ }
+ flags &= ~UI_SHOW_FFA;
+ }
+
+ if (flags & UI_SHOW_NOTFFA) {
+ if (trap_Cvar_VariableValue("g_gametype") == GT_FFA) {
+ vis = qfalse;
+ }
+ flags &= ~UI_SHOW_NOTFFA;
+ }
+
+ if (flags & UI_SHOW_LEADER) {
+ // these need to show when this client can give orders to a player or a group
+ if (!uiInfo.teamLeader) {
+ vis = qfalse;
+ } else {
+ // if showing yourself
+ if (ui_selectedPlayer.integer < uiInfo.myTeamCount && uiInfo.teamClientNums[ui_selectedPlayer.integer] == uiInfo.playerNumber) {
+ vis = qfalse;
+ }
+ }
+ flags &= ~UI_SHOW_LEADER;
+ }
+ if (flags & UI_SHOW_NOTLEADER) {
+ // these need to show when this client is assigning their own status or they are NOT the leader
+ if (uiInfo.teamLeader) {
+ // if not showing yourself
+ if (!(ui_selectedPlayer.integer < uiInfo.myTeamCount && uiInfo.teamClientNums[ui_selectedPlayer.integer] == uiInfo.playerNumber)) {
+ vis = qfalse;
+ }
+ // these need to show when this client can give orders to a player or a group
+ }
+ flags &= ~UI_SHOW_NOTLEADER;
+ }
+ if (flags & UI_SHOW_FAVORITESERVERS) {
+ // this assumes you only put this type of display flag on something showing in the proper context
+ if (ui_netSource.integer != AS_FAVORITES) {
+ vis = qfalse;
+ }
+ flags &= ~UI_SHOW_FAVORITESERVERS;
+ }
+ if (flags & UI_SHOW_NOTFAVORITESERVERS) {
+ // this assumes you only put this type of display flag on something showing in the proper context
+ if (ui_netSource.integer == AS_FAVORITES) {
+ vis = qfalse;
+ }
+ flags &= ~UI_SHOW_NOTFAVORITESERVERS;
+ }
+ if (flags & UI_SHOW_ANYTEAMGAME) {
+ if (uiInfo.gameTypes[ui_gameType.integer].gtEnum <= GT_TEAM ) {
+ vis = qfalse;
+ }
+ flags &= ~UI_SHOW_ANYTEAMGAME;
+ }
+ if (flags & UI_SHOW_ANYNONTEAMGAME) {
+ if (uiInfo.gameTypes[ui_gameType.integer].gtEnum > GT_TEAM ) {
+ vis = qfalse;
+ }
+ flags &= ~UI_SHOW_ANYNONTEAMGAME;
+ }
+ if (flags & UI_SHOW_NETANYTEAMGAME) {
+ if (uiInfo.gameTypes[ui_netGameType.integer].gtEnum <= GT_TEAM ) {
+ vis = qfalse;
+ }
+ flags &= ~UI_SHOW_NETANYTEAMGAME;
+ }
+ if (flags & UI_SHOW_NETANYNONTEAMGAME) {
+ if (uiInfo.gameTypes[ui_netGameType.integer].gtEnum > GT_TEAM ) {
+ vis = qfalse;
+ }
+ flags &= ~UI_SHOW_NETANYNONTEAMGAME;
+ }
+ if (flags & UI_SHOW_NEWHIGHSCORE) {
+ if (uiInfo.newHighScoreTime < uiInfo.uiDC.realTime) {
+ vis = qfalse;
+ } else {
+ if (uiInfo.soundHighScore) {
+ if (trap_Cvar_VariableValue("sv_killserver") == 0) {
+ // wait on server to go down before playing sound
+ trap_S_StartLocalSound(uiInfo.newHighScoreSound, CHAN_ANNOUNCER);
+ uiInfo.soundHighScore = qfalse;
+ }
+ }
+ }
+ flags &= ~UI_SHOW_NEWHIGHSCORE;
+ }
+ if (flags & UI_SHOW_NEWBESTTIME) {
+ if (uiInfo.newBestTime < uiInfo.uiDC.realTime) {
+ vis = qfalse;
+ }
+ flags &= ~UI_SHOW_NEWBESTTIME;
+ }
+ if (flags & UI_SHOW_DEMOAVAILABLE) {
+ if (!uiInfo.demoAvailable) {
+ vis = qfalse;
+ }
+ flags &= ~UI_SHOW_DEMOAVAILABLE;
+ } else {
+ flags = 0;
+ }
+ }
+ return vis;
+}
+
+static qboolean UI_Handicap_HandleKey(int flags, float *special, int key) {
+ if (key == K_MOUSE1 || key == K_MOUSE2 || key == K_ENTER || key == K_KP_ENTER) {
+ int h;
+ h = Com_Clamp( 5, 100, trap_Cvar_VariableValue("handicap") );
+ if (key == K_MOUSE2) {
+ h -= 5;
+ } else {
+ h += 5;
+ }
+ if (h > 100) {
+ h = 5;
+ } else if (h < 0) {
+ h = 100;
+ }
+ trap_Cvar_Set( "handicap", va( "%i", h) );
+ return qtrue;
+ }
+ return qfalse;
+}
+
+static qboolean UI_Effects_HandleKey(int flags, float *special, int key) {
+ if (key == K_MOUSE1 || key == K_MOUSE2 || key == K_ENTER || key == K_KP_ENTER) {
+
+ if (key == K_MOUSE2) {
+ uiInfo.effectsColor--;
+ } else {
+ uiInfo.effectsColor++;
+ }
+
+ if( uiInfo.effectsColor > 6 ) {
+ uiInfo.effectsColor = 0;
+ } else if (uiInfo.effectsColor < 0) {
+ uiInfo.effectsColor = 6;
+ }
+
+ trap_Cvar_SetValue( "color1", uitogamecode[uiInfo.effectsColor] );
+ return qtrue;
+ }
+ return qfalse;
+}
+
+static qboolean UI_ClanName_HandleKey(int flags, float *special, int key) {
+ if (key == K_MOUSE1 || key == K_MOUSE2 || key == K_ENTER || key == K_KP_ENTER) {
+ int i;
+ i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_teamName"));
+ if (uiInfo.teamList[i].cinematic >= 0) {
+ trap_CIN_StopCinematic(uiInfo.teamList[i].cinematic);
+ uiInfo.teamList[i].cinematic = -1;
+ }
+ if (key == K_MOUSE2) {
+ i--;
+ } else {
+ i++;
+ }
+ if (i >= uiInfo.teamCount) {
+ i = 0;
+ } else if (i < 0) {
+ i = uiInfo.teamCount - 1;
+ }
+ trap_Cvar_Set( "ui_teamName", uiInfo.teamList[i].teamName);
+ UI_HeadCountByTeam();
+ UI_FeederSelection(FEEDER_HEADS, 0);
+ updateModel = qtrue;
+ return qtrue;
+ }
+ return qfalse;
+}
+
+static qboolean UI_GameType_HandleKey(int flags, float *special, int key, qboolean resetMap) {
+ if (key == K_MOUSE1 || key == K_MOUSE2 || key == K_ENTER || key == K_KP_ENTER) {
+ int oldCount = UI_MapCountByGameType(qtrue);
+
+ // hard coded mess here
+ if (key == K_MOUSE2) {
+ ui_gameType.integer--;
+ if (ui_gameType.integer == 2) {
+ ui_gameType.integer = 1;
+ } else if (ui_gameType.integer < 2) {
+ ui_gameType.integer = uiInfo.numGameTypes - 1;
+ }
+ } else {
+ ui_gameType.integer++;
+ if (ui_gameType.integer >= uiInfo.numGameTypes) {
+ ui_gameType.integer = 1;
+ } else if (ui_gameType.integer == 2) {
+ ui_gameType.integer = 3;
+ }
+ }
+
+ if (uiInfo.gameTypes[ui_gameType.integer].gtEnum == GT_TOURNAMENT) {
+ trap_Cvar_Set("ui_Q3Model", "1");
+ } else {
+ trap_Cvar_Set("ui_Q3Model", "0");
+ }
+
+ trap_Cvar_Set("ui_gameType", va("%d", ui_gameType.integer));
+ UI_SetCapFragLimits(qtrue);
+ UI_LoadBestScores(uiInfo.mapList[ui_currentMap.integer].mapLoadName, uiInfo.gameTypes[ui_gameType.integer].gtEnum);
+ if (resetMap && oldCount != UI_MapCountByGameType(qtrue)) {
+ trap_Cvar_Set( "ui_currentMap", "0");
+ Menu_SetFeederSelection(NULL, FEEDER_MAPS, 0, NULL);
+ }
+ return qtrue;
+ }
+ return qfalse;
+}
+
+static qboolean UI_NetGameType_HandleKey(int flags, float *special, int key) {
+ if (key == K_MOUSE1 || key == K_MOUSE2 || key == K_ENTER || key == K_KP_ENTER) {
+
+ if (key == K_MOUSE2) {
+ ui_netGameType.integer--;
+ } else {
+ ui_netGameType.integer++;
+ }
+
+ if (ui_netGameType.integer < 0) {
+ ui_netGameType.integer = uiInfo.numGameTypes - 1;
+ } else if (ui_netGameType.integer >= uiInfo.numGameTypes) {
+ ui_netGameType.integer = 0;
+ }
+
+ trap_Cvar_Set( "ui_netGameType", va("%d", ui_netGameType.integer));
+ trap_Cvar_Set( "ui_actualnetGameType", va("%d", uiInfo.gameTypes[ui_netGameType.integer].gtEnum));
+ trap_Cvar_Set( "ui_currentNetMap", "0");
+ UI_MapCountByGameType(qfalse);
+ Menu_SetFeederSelection(NULL, FEEDER_ALLMAPS, 0, NULL);
+ return qtrue;
+ }
+ return qfalse;
+}
+
+static qboolean UI_JoinGameType_HandleKey(int flags, float *special, int key) {
+ if (key == K_MOUSE1 || key == K_MOUSE2 || key == K_ENTER || key == K_KP_ENTER) {
+
+ if (key == K_MOUSE2) {
+ ui_joinGameType.integer--;
+ } else {
+ ui_joinGameType.integer++;
+ }
+
+ if (ui_joinGameType.integer < 0) {
+ ui_joinGameType.integer = uiInfo.numJoinGameTypes - 1;
+ } else if (ui_joinGameType.integer >= uiInfo.numJoinGameTypes) {
+ ui_joinGameType.integer = 0;
+ }
+
+ trap_Cvar_Set( "ui_joinGameType", va("%d", ui_joinGameType.integer));
+ UI_BuildServerDisplayList(qtrue);
+ return qtrue;
+ }
+ return qfalse;
+}
+
+
+
+static qboolean UI_Skill_HandleKey(int flags, float *special, int key) {
+ if (key == K_MOUSE1 || key == K_MOUSE2 || key == K_ENTER || key == K_KP_ENTER) {
+ int i = trap_Cvar_VariableValue( "g_spSkill" );
+
+ if (key == K_MOUSE2) {
+ i--;
+ } else {
+ i++;
+ }
+
+ if (i < 1) {
+ i = numSkillLevels;
+ } else if (i > numSkillLevels) {
+ i = 1;
+ }
+
+ trap_Cvar_Set("g_spSkill", va("%i", i));
+ return qtrue;
+ }
+ return qfalse;
+}
+
+static qboolean UI_TeamName_HandleKey(int flags, float *special, int key, qboolean blue) {
+ if (key == K_MOUSE1 || key == K_MOUSE2 || key == K_ENTER || key == K_KP_ENTER) {
+ int i;
+ i = UI_TeamIndexFromName(UI_Cvar_VariableString((blue) ? "ui_blueTeam" : "ui_redTeam"));
+
+ if (key == K_MOUSE2) {
+ i--;
+ } else {
+ i++;
+ }
+
+ if (i >= uiInfo.teamCount) {
+ i = 0;
+ } else if (i < 0) {
+ i = uiInfo.teamCount - 1;
+ }
+
+ trap_Cvar_Set( (blue) ? "ui_blueTeam" : "ui_redTeam", uiInfo.teamList[i].teamName);
+
+ return qtrue;
+ }
+ return qfalse;
+}
+
+static qboolean UI_TeamMember_HandleKey(int flags, float *special, int key, qboolean blue, int num) {
+ if (key == K_MOUSE1 || key == K_MOUSE2 || key == K_ENTER || key == K_KP_ENTER) {
+ // 0 - None
+ // 1 - Human
+ // 2..NumCharacters - Bot
+ char *cvar = va(blue ? "ui_blueteam%i" : "ui_redteam%i", num);
+ int value = trap_Cvar_VariableValue(cvar);
+
+ if (key == K_MOUSE2) {
+ value--;
+ } else {
+ value++;
+ }
+
+ if (ui_actualNetGameType.integer >= GT_TEAM) {
+ if (value >= uiInfo.characterCount + 2) {
+ value = 0;
+ } else if (value < 0) {
+ value = uiInfo.characterCount + 2 - 1;
+ }
+ } else {
+ if (value >= UI_GetNumBots() + 2) {
+ value = 0;
+ } else if (value < 0) {
+ value = UI_GetNumBots() + 2 - 1;
+ }
+ }
+
+ trap_Cvar_Set(cvar, va("%i", value));
+ return qtrue;
+ }
+ return qfalse;
+}
+
+static qboolean UI_NetSource_HandleKey(int flags, float *special, int key) {
+ if (key == K_MOUSE1 || key == K_MOUSE2 || key == K_ENTER || key == K_KP_ENTER) {
+
+ if (key == K_MOUSE2) {
+ ui_netSource.integer--;
+ if (ui_netSource.integer == AS_MPLAYER)
+ ui_netSource.integer--;
+ } else {
+ ui_netSource.integer++;
+ if (ui_netSource.integer == AS_MPLAYER)
+ ui_netSource.integer++;
+ }
+
+ if (ui_netSource.integer >= numNetSources) {
+ ui_netSource.integer = 0;
+ } else if (ui_netSource.integer < 0) {
+ ui_netSource.integer = numNetSources - 1;
+ }
+
+ UI_BuildServerDisplayList(qtrue);
+ if (ui_netSource.integer != AS_GLOBAL) {
+ UI_StartServerRefresh(qtrue);
+ }
+ trap_Cvar_Set( "ui_netSource", va("%d", ui_netSource.integer));
+ return qtrue;
+ }
+ return qfalse;
+}
+
+static qboolean UI_NetFilter_HandleKey(int flags, float *special, int key) {
+ if (key == K_MOUSE1 || key == K_MOUSE2 || key == K_ENTER || key == K_KP_ENTER) {
+
+ if (key == K_MOUSE2) {
+ ui_serverFilterType.integer--;
+ } else {
+ ui_serverFilterType.integer++;
+ }
+
+ if (ui_serverFilterType.integer >= numServerFilters) {
+ ui_serverFilterType.integer = 0;
+ } else if (ui_serverFilterType.integer < 0) {
+ ui_serverFilterType.integer = numServerFilters - 1;
+ }
+ UI_BuildServerDisplayList(qtrue);
+ return qtrue;
+ }
+ return qfalse;
+}
+
+static qboolean UI_OpponentName_HandleKey(int flags, float *special, int key) {
+ if (key == K_MOUSE1 || key == K_MOUSE2 || key == K_ENTER || key == K_KP_ENTER) {
+ if (key == K_MOUSE2) {
+ UI_PriorOpponent();
+ } else {
+ UI_NextOpponent();
+ }
+ return qtrue;
+ }
+ return qfalse;
+}
+
+static qboolean UI_BotName_HandleKey(int flags, float *special, int key) {
+ if (key == K_MOUSE1 || key == K_MOUSE2 || key == K_ENTER || key == K_KP_ENTER) {
+ int game = trap_Cvar_VariableValue("g_gametype");
+ int value = uiInfo.botIndex;
+
+ if (key == K_MOUSE2) {
+ value--;
+ } else {
+ value++;
+ }
+
+ if (game >= GT_TEAM) {
+ if (value >= uiInfo.characterCount + 2) {
+ value = 0;
+ } else if (value < 0) {
+ value = uiInfo.characterCount + 2 - 1;
+ }
+ } else {
+ if (value >= UI_GetNumBots() + 2) {
+ value = 0;
+ } else if (value < 0) {
+ value = UI_GetNumBots() + 2 - 1;
+ }
+ }
+ uiInfo.botIndex = value;
+ return qtrue;
+ }
+ return qfalse;
+}
+
+static qboolean UI_BotSkill_HandleKey(int flags, float *special, int key) {
+ if (key == K_MOUSE1 || key == K_MOUSE2 || key == K_ENTER || key == K_KP_ENTER) {
+ if (key == K_MOUSE2) {
+ uiInfo.skillIndex--;
+ } else {
+ uiInfo.skillIndex++;
+ }
+ if (uiInfo.skillIndex >= numSkillLevels) {
+ uiInfo.skillIndex = 0;
+ } else if (uiInfo.skillIndex < 0) {
+ uiInfo.skillIndex = numSkillLevels-1;
+ }
+ return qtrue;
+ }
+ return qfalse;
+}
+
+static qboolean UI_RedBlue_HandleKey(int flags, float *special, int key) {
+ if (key == K_MOUSE1 || key == K_MOUSE2 || key == K_ENTER || key == K_KP_ENTER) {
+ uiInfo.redBlue ^= 1;
+ return qtrue;
+ }
+ return qfalse;
+}
+
+static qboolean UI_Crosshair_HandleKey(int flags, float *special, int key) {
+ if (key == K_MOUSE1 || key == K_MOUSE2 || key == K_ENTER || key == K_KP_ENTER) {
+ if (key == K_MOUSE2) {
+ uiInfo.currentCrosshair--;
+ } else {
+ uiInfo.currentCrosshair++;
+ }
+
+ if (uiInfo.currentCrosshair >= NUM_CROSSHAIRS) {
+ uiInfo.currentCrosshair = 0;
+ } else if (uiInfo.currentCrosshair < 0) {
+ uiInfo.currentCrosshair = NUM_CROSSHAIRS - 1;
+ }
+ trap_Cvar_Set("cg_drawCrosshair", va("%d", uiInfo.currentCrosshair));
+ return qtrue;
+ }
+ return qfalse;
+}
+
+
+
+static qboolean UI_SelectedPlayer_HandleKey(int flags, float *special, int key) {
+ if (key == K_MOUSE1 || key == K_MOUSE2 || key == K_ENTER || key == K_KP_ENTER) {
+ int selected;
+
+ UI_BuildPlayerList();
+ if (!uiInfo.teamLeader) {
+ return qfalse;
+ }
+ selected = trap_Cvar_VariableValue("cg_selectedPlayer");
+
+ if (key == K_MOUSE2) {
+ selected--;
+ } else {
+ selected++;
+ }
+
+ if (selected > uiInfo.myTeamCount) {
+ selected = 0;
+ } else if (selected < 0) {
+ selected = uiInfo.myTeamCount;
+ }
+
+ if (selected == uiInfo.myTeamCount) {
+ trap_Cvar_Set( "cg_selectedPlayerName", "Everyone");
+ } else {
+ trap_Cvar_Set( "cg_selectedPlayerName", uiInfo.teamNames[selected]);
+ }
+ trap_Cvar_Set( "cg_selectedPlayer", va("%d", selected));
+ }
+ return qfalse;
+}
+
+
+static qboolean UI_OwnerDrawHandleKey(int ownerDraw, int flags, float *special, int key) {
+ switch (ownerDraw) {
+ case UI_HANDICAP:
+ return UI_Handicap_HandleKey(flags, special, key);
+ break;
+ case UI_EFFECTS:
+ return UI_Effects_HandleKey(flags, special, key);
+ break;
+ case UI_CLANNAME:
+ return UI_ClanName_HandleKey(flags, special, key);
+ break;
+ case UI_GAMETYPE:
+ return UI_GameType_HandleKey(flags, special, key, qtrue);
+ break;
+ case UI_NETGAMETYPE:
+ return UI_NetGameType_HandleKey(flags, special, key);
+ break;
+ case UI_JOINGAMETYPE:
+ return UI_JoinGameType_HandleKey(flags, special, key);
+ break;
+ case UI_SKILL:
+ return UI_Skill_HandleKey(flags, special, key);
+ break;
+ case UI_BLUETEAMNAME:
+ return UI_TeamName_HandleKey(flags, special, key, qtrue);
+ break;
+ case UI_REDTEAMNAME:
+ return UI_TeamName_HandleKey(flags, special, key, qfalse);
+ break;
+ case UI_BLUETEAM1:
+ case UI_BLUETEAM2:
+ case UI_BLUETEAM3:
+ case UI_BLUETEAM4:
+ case UI_BLUETEAM5:
+ UI_TeamMember_HandleKey(flags, special, key, qtrue, ownerDraw - UI_BLUETEAM1 + 1);
+ break;
+ case UI_REDTEAM1:
+ case UI_REDTEAM2:
+ case UI_REDTEAM3:
+ case UI_REDTEAM4:
+ case UI_REDTEAM5:
+ UI_TeamMember_HandleKey(flags, special, key, qfalse, ownerDraw - UI_REDTEAM1 + 1);
+ break;
+ case UI_NETSOURCE:
+ UI_NetSource_HandleKey(flags, special, key);
+ break;
+ case UI_NETFILTER:
+ UI_NetFilter_HandleKey(flags, special, key);
+ break;
+ case UI_OPPONENT_NAME:
+ UI_OpponentName_HandleKey(flags, special, key);
+ break;
+ case UI_BOTNAME:
+ return UI_BotName_HandleKey(flags, special, key);
+ break;
+ case UI_BOTSKILL:
+ return UI_BotSkill_HandleKey(flags, special, key);
+ break;
+ case UI_REDBLUE:
+ UI_RedBlue_HandleKey(flags, special, key);
+ break;
+ case UI_CROSSHAIR:
+ UI_Crosshair_HandleKey(flags, special, key);
+ break;
+ case UI_SELECTEDPLAYER:
+ UI_SelectedPlayer_HandleKey(flags, special, key);
+ break;
+ default:
+ break;
+ }
+
+ return qfalse;
+}
+
+
+static float UI_GetValue(int ownerDraw) {
+ return 0;
+}
+
+/*
+=================
+UI_ServersQsortCompare
+=================
+*/
+static int QDECL UI_ServersQsortCompare( const void *arg1, const void *arg2 ) {
+ return trap_LAN_CompareServers( ui_netSource.integer, uiInfo.serverStatus.sortKey, uiInfo.serverStatus.sortDir, *(int*)arg1, *(int*)arg2);
+}
+
+
+/*
+=================
+UI_ServersSort
+=================
+*/
+void UI_ServersSort(int column, qboolean force) {
+
+ if ( !force ) {
+ if ( uiInfo.serverStatus.sortKey == column ) {
+ return;
+ }
+ }
+
+ uiInfo.serverStatus.sortKey = column;
+ qsort( &uiInfo.serverStatus.displayServers[0], uiInfo.serverStatus.numDisplayServers, sizeof(int), UI_ServersQsortCompare);
+}
+
+/*
+static void UI_StartSinglePlayer() {
+ int i,j, k, skill;
+ char buff[1024];
+ i = trap_Cvar_VariableValue( "ui_currentTier" );
+ if (i < 0 || i >= tierCount) {
+ i = 0;
+ }
+ j = trap_Cvar_VariableValue("ui_currentMap");
+ if (j < 0 || j > MAPS_PER_TIER) {
+ j = 0;
+ }
+
+ trap_Cvar_SetValue( "singleplayer", 1 );
+ trap_Cvar_SetValue( "g_gametype", Com_Clamp( 0, 7, tierList[i].gameTypes[j] ) );
+ trap_Cmd_ExecuteText( EXEC_APPEND, va( "wait ; wait ; map %s\n", tierList[i].maps[j] ) );
+ skill = trap_Cvar_VariableValue( "g_spSkill" );
+
+ if (j == MAPS_PER_TIER-1) {
+ k = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_opponentName"));
+ Com_sprintf( buff, sizeof(buff), "wait ; addbot %s %i %s 250 %s\n", UI_AIFromName(teamList[k].teamMembers[0]), skill, "", teamList[k].teamMembers[0]);
+ } else {
+ k = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_opponentName"));
+ for (i = 0; i < PLAYERS_PER_TEAM; i++) {
+ Com_sprintf( buff, sizeof(buff), "wait ; addbot %s %i %s 250 %s\n", UI_AIFromName(teamList[k].teamMembers[i]), skill, "Blue", teamList[k].teamMembers[i]);
+ trap_Cmd_ExecuteText( EXEC_APPEND, buff );
+ }
+
+ k = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_teamName"));
+ for (i = 1; i < PLAYERS_PER_TEAM; i++) {
+ Com_sprintf( buff, sizeof(buff), "wait ; addbot %s %i %s 250 %s\n", UI_AIFromName(teamList[k].teamMembers[i]), skill, "Red", teamList[k].teamMembers[i]);
+ trap_Cmd_ExecuteText( EXEC_APPEND, buff );
+ }
+ trap_Cmd_ExecuteText( EXEC_APPEND, "wait 5; team Red\n" );
+ }
+
+
+}
+*/
+
+/*
+===============
+UI_LoadMods
+===============
+*/
+static void UI_LoadMods() {
+ int numdirs;
+ char dirlist[2048];
+ char *dirptr;
+ char *descptr;
+ int i;
+ int dirlen;
+
+ uiInfo.modCount = 0;
+ numdirs = trap_FS_GetFileList( "$modlist", "", dirlist, sizeof(dirlist) );
+ dirptr = dirlist;
+ for( i = 0; i < numdirs; i++ ) {
+ dirlen = strlen( dirptr ) + 1;
+ descptr = dirptr + dirlen;
+ uiInfo.modList[uiInfo.modCount].modName = String_Alloc(dirptr);
+ uiInfo.modList[uiInfo.modCount].modDescr = String_Alloc(descptr);
+ dirptr += dirlen + strlen(descptr) + 1;
+ uiInfo.modCount++;
+ if (uiInfo.modCount >= MAX_MODS) {
+ break;
+ }
+ }
+
+}
+
+
+/*
+===============
+UI_LoadTeams
+===============
+*/
+static void UI_LoadTeams() {
+ char teamList[4096];
+ char *teamName;
+ int i, len, count;
+
+ count = trap_FS_GetFileList( "", "team", teamList, 4096 );
+
+ if (count) {
+ teamName = teamList;
+ for ( i = 0; i < count; i++ ) {
+ len = strlen( teamName );
+ UI_ParseTeamInfo(teamName);
+ teamName += len + 1;
+ }
+ }
+
+}
+
+
+/*
+===============
+UI_LoadMovies
+===============
+*/
+static void UI_LoadMovies() {
+ char movielist[4096];
+ char *moviename;
+ int i, len;
+
+ uiInfo.movieCount = trap_FS_GetFileList( "video", "roq", movielist, 4096 );
+
+ if (uiInfo.movieCount) {
+ if (uiInfo.movieCount > MAX_MOVIES) {
+ uiInfo.movieCount = MAX_MOVIES;
+ }
+ moviename = movielist;
+ for ( i = 0; i < uiInfo.movieCount; i++ ) {
+ len = strlen( moviename );
+ if (!Q_stricmp(moviename + len - 4,".roq")) {
+ moviename[len-4] = '\0';
+ }
+ Q_strupr(moviename);
+ uiInfo.movieList[i] = String_Alloc(moviename);
+ moviename += len + 1;
+ }
+ }
+
+}
+
+
+
+/*
+===============
+UI_LoadDemos
+===============
+*/
+static void UI_LoadDemos() {
+ char demolist[4096];
+ char demoExt[32];
+ char *demoname;
+ int i, len;
+
+ Com_sprintf(demoExt, sizeof(demoExt), "dm_%d", (int)trap_Cvar_VariableValue("protocol"));
+
+ uiInfo.demoCount = trap_FS_GetFileList( "demos", demoExt, demolist, 4096 );
+
+ Com_sprintf(demoExt, sizeof(demoExt), ".dm_%d", (int)trap_Cvar_VariableValue("protocol"));
+
+ if (uiInfo.demoCount) {
+ if (uiInfo.demoCount > MAX_DEMOS) {
+ uiInfo.demoCount = MAX_DEMOS;
+ }
+ demoname = demolist;
+ for ( i = 0; i < uiInfo.demoCount; i++ ) {
+ len = strlen( demoname );
+ if (!Q_stricmp(demoname + len - strlen(demoExt), demoExt)) {
+ demoname[len-strlen(demoExt)] = '\0';
+ }
+ Q_strupr(demoname);
+ uiInfo.demoList[i] = String_Alloc(demoname);
+ demoname += len + 1;
+ }
+ }
+
+}
+
+
+static qboolean UI_SetNextMap(int actual, int index) {
+ int i;
+ for (i = actual + 1; i < uiInfo.mapCount; i++) {
+ if (uiInfo.mapList[i].active) {
+ Menu_SetFeederSelection(NULL, FEEDER_MAPS, index + 1, "skirmish");
+ return qtrue;
+ }
+ }
+ return qfalse;
+}
+
+
+static void UI_StartSkirmish(qboolean next) {
+ int i, k, g, delay, temp;
+ float skill;
+ char buff[MAX_STRING_CHARS];
+
+ if (next) {
+ int actual;
+ int index = trap_Cvar_VariableValue("ui_mapIndex");
+ UI_MapCountByGameType(qtrue);
+ UI_SelectedMap(index, &actual);
+ if (UI_SetNextMap(actual, index)) {
+ } else {
+ UI_GameType_HandleKey(0, 0, K_MOUSE1, qfalse);
+ UI_MapCountByGameType(qtrue);
+ Menu_SetFeederSelection(NULL, FEEDER_MAPS, 0, "skirmish");
+ }
+ }
+
+ g = uiInfo.gameTypes[ui_gameType.integer].gtEnum;
+ trap_Cvar_SetValue( "g_gametype", g );
+ trap_Cmd_ExecuteText( EXEC_APPEND, va( "wait ; wait ; map %s\n", uiInfo.mapList[ui_currentMap.integer].mapLoadName) );
+ skill = trap_Cvar_VariableValue( "g_spSkill" );
+ trap_Cvar_Set("ui_scoreMap", uiInfo.mapList[ui_currentMap.integer].mapName);
+
+ k = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_opponentName"));
+
+ trap_Cvar_Set("ui_singlePlayerActive", "1");
+
+ // set up sp overrides, will be replaced on postgame
+ temp = trap_Cvar_VariableValue( "capturelimit" );
+ trap_Cvar_Set("ui_saveCaptureLimit", va("%i", temp));
+ temp = trap_Cvar_VariableValue( "fraglimit" );
+ trap_Cvar_Set("ui_saveFragLimit", va("%i", temp));
+
+ UI_SetCapFragLimits(qfalse);
+
+ temp = trap_Cvar_VariableValue( "cg_drawTimer" );
+ trap_Cvar_Set("ui_drawTimer", va("%i", temp));
+ temp = trap_Cvar_VariableValue( "g_doWarmup" );
+ trap_Cvar_Set("ui_doWarmup", va("%i", temp));
+ temp = trap_Cvar_VariableValue( "g_friendlyFire" );
+ trap_Cvar_Set("ui_friendlyFire", va("%i", temp));
+ temp = trap_Cvar_VariableValue( "sv_maxClients" );
+ trap_Cvar_Set("ui_maxClients", va("%i", temp));
+ temp = trap_Cvar_VariableValue( "g_warmup" );
+ trap_Cvar_Set("ui_Warmup", va("%i", temp));
+ temp = trap_Cvar_VariableValue( "sv_pure" );
+ trap_Cvar_Set("ui_pure", va("%i", temp));
+
+ trap_Cvar_Set("cg_cameraOrbit", "0");
+ trap_Cvar_Set("cg_thirdPerson", "0");
+ trap_Cvar_Set("cg_drawTimer", "1");
+ trap_Cvar_Set("g_doWarmup", "1");
+ trap_Cvar_Set("g_warmup", "15");
+ trap_Cvar_Set("sv_pure", "0");
+ trap_Cvar_Set("g_friendlyFire", "0");
+ trap_Cvar_Set("g_redTeam", UI_Cvar_VariableString("ui_teamName"));
+ trap_Cvar_Set("g_blueTeam", UI_Cvar_VariableString("ui_opponentName"));
+
+ if (trap_Cvar_VariableValue("ui_recordSPDemo")) {
+ Com_sprintf(buff, MAX_STRING_CHARS, "%s_%i", uiInfo.mapList[ui_currentMap.integer].mapLoadName, g);
+ trap_Cvar_Set("ui_recordSPDemoName", buff);
+ }
+
+ delay = 500;
+
+ if (g == GT_TOURNAMENT) {
+ trap_Cvar_Set("sv_maxClients", "2");
+ Com_sprintf( buff, sizeof(buff), "wait ; addbot %s %f "", %i \n", uiInfo.mapList[ui_currentMap.integer].opponentName, skill, delay);
+ trap_Cmd_ExecuteText( EXEC_APPEND, buff );
+ } else {
+ temp = uiInfo.mapList[ui_currentMap.integer].teamMembers * 2;
+ trap_Cvar_Set("sv_maxClients", va("%d", temp));
+ for (i =0; i < uiInfo.mapList[ui_currentMap.integer].teamMembers; i++) {
+ Com_sprintf( buff, sizeof(buff), "addbot %s %f %s %i %s\n", UI_AIFromName(uiInfo.teamList[k].teamMembers[i]), skill, (g == GT_FFA) ? "" : "Blue", delay, uiInfo.teamList[k].teamMembers[i]);
+ trap_Cmd_ExecuteText( EXEC_APPEND, buff );
+ delay += 500;
+ }
+ k = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_teamName"));
+ for (i =0; i < uiInfo.mapList[ui_currentMap.integer].teamMembers-1; i++) {
+ Com_sprintf( buff, sizeof(buff), "addbot %s %f %s %i %s\n", UI_AIFromName(uiInfo.teamList[k].teamMembers[i]), skill, (g == GT_FFA) ? "" : "Red", delay, uiInfo.teamList[k].teamMembers[i]);
+ trap_Cmd_ExecuteText( EXEC_APPEND, buff );
+ delay += 500;
+ }
+ }
+ if (g >= GT_TEAM ) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, "wait 5; team Red\n" );
+ }
+}
+
+static void UI_Update(const char *name) {
+ int val = trap_Cvar_VariableValue(name);
+
+ if (Q_stricmp(name, "ui_SetName") == 0) {
+ trap_Cvar_Set( "name", UI_Cvar_VariableString("ui_Name"));
+ } else if (Q_stricmp(name, "ui_setRate") == 0) {
+ float rate = trap_Cvar_VariableValue("rate");
+ if (rate >= 5000) {
+ trap_Cvar_Set("cl_maxpackets", "30");
+ trap_Cvar_Set("cl_packetdup", "1");
+ } else if (rate >= 4000) {
+ trap_Cvar_Set("cl_maxpackets", "15");
+ trap_Cvar_Set("cl_packetdup", "2"); // favor less prediction errors when there's packet loss
+ } else {
+ trap_Cvar_Set("cl_maxpackets", "15");
+ trap_Cvar_Set("cl_packetdup", "1"); // favor lower bandwidth
+ }
+ } else if (Q_stricmp(name, "ui_GetName") == 0) {
+ trap_Cvar_Set( "ui_Name", UI_Cvar_VariableString("name"));
+ } else if (Q_stricmp(name, "r_colorbits") == 0) {
+ switch (val) {
+ case 0:
+ trap_Cvar_SetValue( "r_depthbits", 0 );
+ trap_Cvar_SetValue( "r_stencilbits", 0 );
+ break;
+ case 16:
+ trap_Cvar_SetValue( "r_depthbits", 16 );
+ trap_Cvar_SetValue( "r_stencilbits", 0 );
+ break;
+ case 32:
+ trap_Cvar_SetValue( "r_depthbits", 24 );
+ break;
+ }
+ } else if (Q_stricmp(name, "r_lodbias") == 0) {
+ switch (val) {
+ case 0:
+ trap_Cvar_SetValue( "r_subdivisions", 4 );
+ break;
+ case 1:
+ trap_Cvar_SetValue( "r_subdivisions", 12 );
+ break;
+ case 2:
+ trap_Cvar_SetValue( "r_subdivisions", 20 );
+ break;
+ }
+ } else if (Q_stricmp(name, "ui_glCustom") == 0) {
+ switch (val) {
+ case 0: // high quality
+ trap_Cvar_SetValue( "r_fullScreen", 1 );
+ trap_Cvar_SetValue( "r_subdivisions", 4 );
+ trap_Cvar_SetValue( "r_vertexlight", 0 );
+ trap_Cvar_SetValue( "r_lodbias", 0 );
+ trap_Cvar_SetValue( "r_colorbits", 32 );
+ trap_Cvar_SetValue( "r_depthbits", 24 );
+ trap_Cvar_SetValue( "r_picmip", 0 );
+ trap_Cvar_SetValue( "r_mode", 4 );
+ trap_Cvar_SetValue( "r_texturebits", 32 );
+ trap_Cvar_SetValue( "r_fastSky", 0 );
+ trap_Cvar_SetValue( "r_inGameVideo", 1 );
+ trap_Cvar_SetValue( "cg_shadows", 1 );
+ trap_Cvar_SetValue( "cg_brassTime", 2500 );
+ trap_Cvar_Set( "r_texturemode", "GL_LINEAR_MIPMAP_LINEAR" );
+ break;
+ case 1: // normal
+ trap_Cvar_SetValue( "r_fullScreen", 1 );
+ trap_Cvar_SetValue( "r_subdivisions", 12 );
+ trap_Cvar_SetValue( "r_vertexlight", 0 );
+ trap_Cvar_SetValue( "r_lodbias", 0 );
+ trap_Cvar_SetValue( "r_colorbits", 0 );
+ trap_Cvar_SetValue( "r_depthbits", 24 );
+ trap_Cvar_SetValue( "r_picmip", 1 );
+ trap_Cvar_SetValue( "r_mode", 3 );
+ trap_Cvar_SetValue( "r_texturebits", 0 );
+ trap_Cvar_SetValue( "r_fastSky", 0 );
+ trap_Cvar_SetValue( "r_inGameVideo", 1 );
+ trap_Cvar_SetValue( "cg_brassTime", 2500 );
+ trap_Cvar_Set( "r_texturemode", "GL_LINEAR_MIPMAP_LINEAR" );
+ trap_Cvar_SetValue( "cg_shadows", 0 );
+ break;
+ case 2: // fast
+ trap_Cvar_SetValue( "r_fullScreen", 1 );
+ trap_Cvar_SetValue( "r_subdivisions", 8 );
+ trap_Cvar_SetValue( "r_vertexlight", 0 );
+ trap_Cvar_SetValue( "r_lodbias", 1 );
+ trap_Cvar_SetValue( "r_colorbits", 0 );
+ trap_Cvar_SetValue( "r_depthbits", 0 );
+ trap_Cvar_SetValue( "r_picmip", 1 );
+ trap_Cvar_SetValue( "r_mode", 3 );
+ trap_Cvar_SetValue( "r_texturebits", 0 );
+ trap_Cvar_SetValue( "cg_shadows", 0 );
+ trap_Cvar_SetValue( "r_fastSky", 1 );
+ trap_Cvar_SetValue( "r_inGameVideo", 0 );
+ trap_Cvar_SetValue( "cg_brassTime", 0 );
+ trap_Cvar_Set( "r_texturemode", "GL_LINEAR_MIPMAP_NEAREST" );
+ break;
+ case 3: // fastest
+ trap_Cvar_SetValue( "r_fullScreen", 1 );
+ trap_Cvar_SetValue( "r_subdivisions", 20 );
+ trap_Cvar_SetValue( "r_vertexlight", 1 );
+ trap_Cvar_SetValue( "r_lodbias", 2 );
+ trap_Cvar_SetValue( "r_colorbits", 16 );
+ trap_Cvar_SetValue( "r_depthbits", 16 );
+ trap_Cvar_SetValue( "r_mode", 3 );
+ trap_Cvar_SetValue( "r_picmip", 2 );
+ trap_Cvar_SetValue( "r_texturebits", 16 );
+ trap_Cvar_SetValue( "cg_shadows", 0 );
+ trap_Cvar_SetValue( "cg_brassTime", 0 );
+ trap_Cvar_SetValue( "r_fastSky", 1 );
+ trap_Cvar_SetValue( "r_inGameVideo", 0 );
+ trap_Cvar_Set( "r_texturemode", "GL_LINEAR_MIPMAP_NEAREST" );
+ break;
+ }
+ } else if (Q_stricmp(name, "ui_mousePitch") == 0) {
+ if (val == 0) {
+ trap_Cvar_SetValue( "m_pitch", 0.022f );
+ } else {
+ trap_Cvar_SetValue( "m_pitch", -0.022f );
+ }
+ }
+}
+
+static void UI_RunMenuScript(char **args) {
+ const char *name, *name2;
+ char buff[1024];
+
+ if (String_Parse(args, &name)) {
+ if (Q_stricmp(name, "StartServer") == 0) {
+ int i, clients, oldclients;
+ float skill;
+ trap_Cvar_Set("cg_thirdPerson", "0");
+ trap_Cvar_Set("cg_cameraOrbit", "0");
+ trap_Cvar_Set("ui_singlePlayerActive", "0");
+ trap_Cvar_SetValue( "dedicated", Com_Clamp( 0, 2, ui_dedicated.integer ) );
+ trap_Cvar_SetValue( "g_gametype", Com_Clamp( 0, 8, uiInfo.gameTypes[ui_netGameType.integer].gtEnum ) );
+ trap_Cvar_Set("g_redTeam", UI_Cvar_VariableString("ui_teamName"));
+ trap_Cvar_Set("g_blueTeam", UI_Cvar_VariableString("ui_opponentName"));
+ trap_Cmd_ExecuteText( EXEC_APPEND, va( "wait ; wait ; map %s\n", uiInfo.mapList[ui_currentNetMap.integer].mapLoadName ) );
+ skill = trap_Cvar_VariableValue( "g_spSkill" );
+ // set max clients based on spots
+ oldclients = trap_Cvar_VariableValue( "sv_maxClients" );
+ clients = 0;
+ for (i = 0; i < PLAYERS_PER_TEAM; i++) {
+ int bot = trap_Cvar_VariableValue( va("ui_blueteam%i", i+1));
+ if (bot >= 0) {
+ clients++;
+ }
+ bot = trap_Cvar_VariableValue( va("ui_redteam%i", i+1));
+ if (bot >= 0) {
+ clients++;
+ }
+ }
+ if (clients == 0) {
+ clients = 8;
+ }
+
+ if (oldclients > clients) {
+ clients = oldclients;
+ }
+
+ trap_Cvar_Set("sv_maxClients", va("%d",clients));
+
+ for (i = 0; i < PLAYERS_PER_TEAM; i++) {
+ int bot = trap_Cvar_VariableValue( va("ui_blueteam%i", i+1));
+ if (bot > 1) {
+ if (ui_actualNetGameType.integer >= GT_TEAM) {
+ Com_sprintf( buff, sizeof(buff), "addbot %s %f %s\n", uiInfo.characterList[bot-2].name, skill, "Blue");
+ } else {
+ Com_sprintf( buff, sizeof(buff), "addbot %s %f \n", UI_GetBotNameByNumber(bot-2), skill);
+ }
+ trap_Cmd_ExecuteText( EXEC_APPEND, buff );
+ }
+ bot = trap_Cvar_VariableValue( va("ui_redteam%i", i+1));
+ if (bot > 1) {
+ if (ui_actualNetGameType.integer >= GT_TEAM) {
+ Com_sprintf( buff, sizeof(buff), "addbot %s %f %s\n", uiInfo.characterList[bot-2].name, skill, "Red");
+ } else {
+ Com_sprintf( buff, sizeof(buff), "addbot %s %f \n", UI_GetBotNameByNumber(bot-2), skill);
+ }
+ trap_Cmd_ExecuteText( EXEC_APPEND, buff );
+ }
+ }
+ } else if (Q_stricmp(name, "updateSPMenu") == 0) {
+ UI_SetCapFragLimits(qtrue);
+ UI_MapCountByGameType(qtrue);
+ ui_mapIndex.integer = UI_GetIndexFromSelection(ui_currentMap.integer);
+ trap_Cvar_Set("ui_mapIndex", va("%d", ui_mapIndex.integer));
+ Menu_SetFeederSelection(NULL, FEEDER_MAPS, ui_mapIndex.integer, "skirmish");
+ UI_GameType_HandleKey(0, 0, K_MOUSE1, qfalse);
+ UI_GameType_HandleKey(0, 0, K_MOUSE2, qfalse);
+ } else if (Q_stricmp(name, "resetDefaults") == 0) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, "exec default.cfg\n");
+ trap_Cmd_ExecuteText( EXEC_APPEND, "cvar_restart\n");
+ Controls_SetDefaults();
+ trap_Cvar_Set("com_introPlayed", "1" );
+ trap_Cmd_ExecuteText( EXEC_APPEND, "vid_restart\n" );
+ } else if (Q_stricmp(name, "getCDKey") == 0) {
+ char out[17];
+ trap_GetCDKey(buff, 17);
+ trap_Cvar_Set("cdkey1", "");
+ trap_Cvar_Set("cdkey2", "");
+ trap_Cvar_Set("cdkey3", "");
+ trap_Cvar_Set("cdkey4", "");
+ if (strlen(buff) == CDKEY_LEN) {
+ Q_strncpyz(out, buff, 5);
+ trap_Cvar_Set("cdkey1", out);
+ Q_strncpyz(out, buff + 4, 5);
+ trap_Cvar_Set("cdkey2", out);
+ Q_strncpyz(out, buff + 8, 5);
+ trap_Cvar_Set("cdkey3", out);
+ Q_strncpyz(out, buff + 12, 5);
+ trap_Cvar_Set("cdkey4", out);
+ }
+
+ } else if (Q_stricmp(name, "verifyCDKey") == 0) {
+ buff[0] = '\0';
+ Q_strcat(buff, 1024, UI_Cvar_VariableString("cdkey1"));
+ Q_strcat(buff, 1024, UI_Cvar_VariableString("cdkey2"));
+ Q_strcat(buff, 1024, UI_Cvar_VariableString("cdkey3"));
+ Q_strcat(buff, 1024, UI_Cvar_VariableString("cdkey4"));
+ trap_Cvar_Set("cdkey", buff);
+ if (trap_VerifyCDKey(buff, UI_Cvar_VariableString("cdkeychecksum"))) {
+ trap_Cvar_Set("ui_cdkeyvalid", "CD Key Appears to be valid.");
+ trap_SetCDKey(buff);
+ } else {
+ trap_Cvar_Set("ui_cdkeyvalid", "CD Key does not appear to be valid.");
+ }
+ } else if (Q_stricmp(name, "loadArenas") == 0) {
+ UI_LoadArenas();
+ UI_MapCountByGameType(qfalse);
+ Menu_SetFeederSelection(NULL, FEEDER_ALLMAPS, 0, "createserver");
+ } else if (Q_stricmp(name, "saveControls") == 0) {
+ Controls_SetConfig(qtrue);
+ } else if (Q_stricmp(name, "loadControls") == 0) {
+ Controls_GetConfig();
+ } else if (Q_stricmp(name, "clearError") == 0) {
+ trap_Cvar_Set("com_errorMessage", "");
+ } else if (Q_stricmp(name, "loadGameInfo") == 0) {
+#ifdef PRE_RELEASE_TADEMO
+ UI_ParseGameInfo("demogameinfo.txt");
+#else
+ UI_ParseGameInfo("gameinfo.txt");
+#endif
+ UI_LoadBestScores(uiInfo.mapList[ui_currentMap.integer].mapLoadName, uiInfo.gameTypes[ui_gameType.integer].gtEnum);
+ } else if (Q_stricmp(name, "resetScores") == 0) {
+ UI_ClearScores();
+ } else if (Q_stricmp(name, "RefreshServers") == 0) {
+ UI_StartServerRefresh(qtrue);
+ UI_BuildServerDisplayList(qtrue);
+ } else if (Q_stricmp(name, "RefreshFilter") == 0) {
+ UI_StartServerRefresh(qfalse);
+ UI_BuildServerDisplayList(qtrue);
+ } else if (Q_stricmp(name, "RunSPDemo") == 0) {
+ if (uiInfo.demoAvailable) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, va("demo %s_%i\n", uiInfo.mapList[ui_currentMap.integer].mapLoadName, uiInfo.gameTypes[ui_gameType.integer].gtEnum));
+ }
+ } else if (Q_stricmp(name, "LoadDemos") == 0) {
+ UI_LoadDemos();
+ } else if (Q_stricmp(name, "LoadMovies") == 0) {
+ UI_LoadMovies();
+ } else if (Q_stricmp(name, "LoadMods") == 0) {
+ UI_LoadMods();
+ } else if (Q_stricmp(name, "playMovie") == 0) {
+ if (uiInfo.previewMovie >= 0) {
+ trap_CIN_StopCinematic(uiInfo.previewMovie);
+ }
+ trap_Cmd_ExecuteText( EXEC_APPEND, va("cinematic %s.roq 2\n", uiInfo.movieList[uiInfo.movieIndex]));
+ } else if (Q_stricmp(name, "RunMod") == 0) {
+ trap_Cvar_Set( "fs_game", uiInfo.modList[uiInfo.modIndex].modName);
+ trap_Cmd_ExecuteText( EXEC_APPEND, "vid_restart;" );
+ } else if (Q_stricmp(name, "RunDemo") == 0) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, va("demo %s\n", uiInfo.demoList[uiInfo.demoIndex]));
+ } else if (Q_stricmp(name, "Quake3") == 0) {
+ trap_Cvar_Set( "fs_game", "");
+ trap_Cmd_ExecuteText( EXEC_APPEND, "vid_restart;" );
+ } else if (Q_stricmp(name, "closeJoin") == 0) {
+ if (uiInfo.serverStatus.refreshActive) {
+ UI_StopServerRefresh();
+ uiInfo.serverStatus.nextDisplayRefresh = 0;
+ uiInfo.nextServerStatusRefresh = 0;
+ uiInfo.nextFindPlayerRefresh = 0;
+ UI_BuildServerDisplayList(qtrue);
+ } else {
+ Menus_CloseByName("joinserver");
+ Menus_OpenByName("main");
+ }
+ } else if (Q_stricmp(name, "StopRefresh") == 0) {
+ UI_StopServerRefresh();
+ uiInfo.serverStatus.nextDisplayRefresh = 0;
+ uiInfo.nextServerStatusRefresh = 0;
+ uiInfo.nextFindPlayerRefresh = 0;
+ } else if (Q_stricmp(name, "UpdateFilter") == 0) {
+ if (ui_netSource.integer == AS_LOCAL) {
+ UI_StartServerRefresh(qtrue);
+ }
+ UI_BuildServerDisplayList(qtrue);
+ UI_FeederSelection(FEEDER_SERVERS, 0);
+ } else if (Q_stricmp(name, "ServerStatus") == 0) {
+ trap_LAN_GetServerAddressString(ui_netSource.integer, uiInfo.serverStatus.displayServers[uiInfo.serverStatus.currentServer], uiInfo.serverStatusAddress, sizeof(uiInfo.serverStatusAddress));
+ UI_BuildServerStatus(qtrue);
+ } else if (Q_stricmp(name, "FoundPlayerServerStatus") == 0) {
+ Q_strncpyz(uiInfo.serverStatusAddress, uiInfo.foundPlayerServerAddresses[uiInfo.currentFoundPlayerServer], sizeof(uiInfo.serverStatusAddress));
+ UI_BuildServerStatus(qtrue);
+ Menu_SetFeederSelection(NULL, FEEDER_FINDPLAYER, 0, NULL);
+ } else if (Q_stricmp(name, "FindPlayer") == 0) {
+ UI_BuildFindPlayerList(qtrue);
+ // clear the displayed server status info
+ uiInfo.serverStatusInfo.numLines = 0;
+ Menu_SetFeederSelection(NULL, FEEDER_FINDPLAYER, 0, NULL);
+ } else if (Q_stricmp(name, "JoinServer") == 0) {
+ trap_Cvar_Set("cg_thirdPerson", "0");
+ trap_Cvar_Set("cg_cameraOrbit", "0");
+ trap_Cvar_Set("ui_singlePlayerActive", "0");
+ if (uiInfo.serverStatus.currentServer >= 0 && uiInfo.serverStatus.currentServer < uiInfo.serverStatus.numDisplayServers) {
+ trap_LAN_GetServerAddressString(ui_netSource.integer, uiInfo.serverStatus.displayServers[uiInfo.serverStatus.currentServer], buff, 1024);
+ trap_Cmd_ExecuteText( EXEC_APPEND, va( "connect %s\n", buff ) );
+ }
+ } else if (Q_stricmp(name, "FoundPlayerJoinServer") == 0) {
+ trap_Cvar_Set("ui_singlePlayerActive", "0");
+ if (uiInfo.currentFoundPlayerServer >= 0 && uiInfo.currentFoundPlayerServer < uiInfo.numFoundPlayerServers) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, va( "connect %s\n", uiInfo.foundPlayerServerAddresses[uiInfo.currentFoundPlayerServer] ) );
+ }
+ } else if (Q_stricmp(name, "Quit") == 0) {
+ trap_Cvar_Set("ui_singlePlayerActive", "0");
+ trap_Cmd_ExecuteText( EXEC_NOW, "quit");
+ } else if (Q_stricmp(name, "Controls") == 0) {
+ trap_Cvar_Set( "cl_paused", "1" );
+ trap_Key_SetCatcher( KEYCATCH_UI );
+ Menus_CloseAll();
+ Menus_ActivateByName("setup_menu2");
+ } else if (Q_stricmp(name, "Leave") == 0) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, "disconnect\n" );
+ trap_Key_SetCatcher( KEYCATCH_UI );
+ Menus_CloseAll();
+ Menus_ActivateByName("main");
+ } else if (Q_stricmp(name, "ServerSort") == 0) {
+ int sortColumn;
+ if (Int_Parse(args, &sortColumn)) {
+ // if same column we're already sorting on then flip the direction
+ if (sortColumn == uiInfo.serverStatus.sortKey) {
+ uiInfo.serverStatus.sortDir = !uiInfo.serverStatus.sortDir;
+ }
+ // make sure we sort again
+ UI_ServersSort(sortColumn, qtrue);
+ }
+ } else if (Q_stricmp(name, "nextSkirmish") == 0) {
+ UI_StartSkirmish(qtrue);
+ } else if (Q_stricmp(name, "SkirmishStart") == 0) {
+ UI_StartSkirmish(qfalse);
+ } else if (Q_stricmp(name, "closeingame") == 0) {
+ trap_Key_SetCatcher( trap_Key_GetCatcher() & ~KEYCATCH_UI );
+ trap_Key_ClearStates();
+ trap_Cvar_Set( "cl_paused", "0" );
+ Menus_CloseAll();
+ } else if (Q_stricmp(name, "voteMap") == 0) {
+ if (ui_currentNetMap.integer >=0 && ui_currentNetMap.integer < uiInfo.mapCount) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, va("callvote map %s\n",uiInfo.mapList[ui_currentNetMap.integer].mapLoadName) );
+ }
+ } else if (Q_stricmp(name, "voteKick") == 0) {
+ if (uiInfo.playerIndex >= 0 && uiInfo.playerIndex < uiInfo.playerCount) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, va("callvote kick %s\n",uiInfo.playerNames[uiInfo.playerIndex]) );
+ }
+ } else if (Q_stricmp(name, "voteGame") == 0) {
+ if (ui_netGameType.integer >= 0 && ui_netGameType.integer < uiInfo.numGameTypes) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, va("callvote g_gametype %i\n",uiInfo.gameTypes[ui_netGameType.integer].gtEnum) );
+ }
+ } else if (Q_stricmp(name, "voteLeader") == 0) {
+ if (uiInfo.teamIndex >= 0 && uiInfo.teamIndex < uiInfo.myTeamCount) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, va("callteamvote leader %s\n",uiInfo.teamNames[uiInfo.teamIndex]) );
+ }
+ } else if (Q_stricmp(name, "addBot") == 0) {
+ if (trap_Cvar_VariableValue("g_gametype") >= GT_TEAM) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, va("addbot %s %i %s\n", uiInfo.characterList[uiInfo.botIndex].name, uiInfo.skillIndex+1, (uiInfo.redBlue == 0) ? "Red" : "Blue") );
+ } else {
+ trap_Cmd_ExecuteText( EXEC_APPEND, va("addbot %s %i %s\n", UI_GetBotNameByNumber(uiInfo.botIndex), uiInfo.skillIndex+1, (uiInfo.redBlue == 0) ? "Red" : "Blue") );
+ }
+ } else if (Q_stricmp(name, "addFavorite") == 0) {
+ if (ui_netSource.integer != AS_FAVORITES) {
+ char name[MAX_NAME_LENGTH];
+ char addr[MAX_NAME_LENGTH];
+ int res;
+
+ trap_LAN_GetServerInfo(ui_netSource.integer, uiInfo.serverStatus.displayServers[uiInfo.serverStatus.currentServer], buff, MAX_STRING_CHARS);
+ name[0] = addr[0] = '\0';
+ Q_strncpyz(name, Info_ValueForKey(buff, "hostname"), MAX_NAME_LENGTH);
+ Q_strncpyz(addr, Info_ValueForKey(buff, "addr"), MAX_NAME_LENGTH);
+ if (strlen(name) > 0 && strlen(addr) > 0) {
+ res = trap_LAN_AddServer(AS_FAVORITES, name, addr);
+ if (res == 0) {
+ // server already in the list
+ Com_Printf("Favorite already in list\n");
+ }
+ else if (res == -1) {
+ // list full
+ Com_Printf("Favorite list full\n");
+ }
+ else {
+ // successfully added
+ Com_Printf("Added favorite server %s\n", addr);
+ }
+ }
+ }
+ } else if (Q_stricmp(name, "deleteFavorite") == 0) {
+ if (ui_netSource.integer == AS_FAVORITES) {
+ char addr[MAX_NAME_LENGTH];
+ trap_LAN_GetServerInfo(ui_netSource.integer, uiInfo.serverStatus.displayServers[uiInfo.serverStatus.currentServer], buff, MAX_STRING_CHARS);
+ addr[0] = '\0';
+ Q_strncpyz(addr, Info_ValueForKey(buff, "addr"), MAX_NAME_LENGTH);
+ if (strlen(addr) > 0) {
+ trap_LAN_RemoveServer(AS_FAVORITES, addr);
+ }
+ }
+ } else if (Q_stricmp(name, "createFavorite") == 0) {
+ if (ui_netSource.integer == AS_FAVORITES) {
+ char name[MAX_NAME_LENGTH];
+ char addr[MAX_NAME_LENGTH];
+ int res;
+
+ name[0] = addr[0] = '\0';
+ Q_strncpyz(name, UI_Cvar_VariableString("ui_favoriteName"), MAX_NAME_LENGTH);
+ Q_strncpyz(addr, UI_Cvar_VariableString("ui_favoriteAddress"), MAX_NAME_LENGTH);
+ if (strlen(name) > 0 && strlen(addr) > 0) {
+ res = trap_LAN_AddServer(AS_FAVORITES, name, addr);
+ if (res == 0) {
+ // server already in the list
+ Com_Printf("Favorite already in list\n");
+ }
+ else if (res == -1) {
+ // list full
+ Com_Printf("Favorite list full\n");
+ }
+ else {
+ // successfully added
+ Com_Printf("Added favorite server %s\n", addr);
+ }
+ }
+ }
+ } else if (Q_stricmp(name, "orders") == 0) {
+ const char *orders;
+ if (String_Parse(args, &orders)) {
+ int selectedPlayer = trap_Cvar_VariableValue("cg_selectedPlayer");
+ if (selectedPlayer < uiInfo.myTeamCount) {
+ strcpy(buff, orders);
+ trap_Cmd_ExecuteText( EXEC_APPEND, va(buff, uiInfo.teamClientNums[selectedPlayer]) );
+ trap_Cmd_ExecuteText( EXEC_APPEND, "\n" );
+ } else {
+ int i;
+ for (i = 0; i < uiInfo.myTeamCount; i++) {
+ if (Q_stricmp(UI_Cvar_VariableString("name"), uiInfo.teamNames[i]) == 0) {
+ continue;
+ }
+ strcpy(buff, orders);
+ trap_Cmd_ExecuteText( EXEC_APPEND, va(buff, uiInfo.teamNames[i]) );
+ trap_Cmd_ExecuteText( EXEC_APPEND, "\n" );
+ }
+ }
+ trap_Key_SetCatcher( trap_Key_GetCatcher() & ~KEYCATCH_UI );
+ trap_Key_ClearStates();
+ trap_Cvar_Set( "cl_paused", "0" );
+ Menus_CloseAll();
+ }
+ } else if (Q_stricmp(name, "voiceOrdersTeam") == 0) {
+ const char *orders;
+ if (String_Parse(args, &orders)) {
+ int selectedPlayer = trap_Cvar_VariableValue("cg_selectedPlayer");
+ if (selectedPlayer == uiInfo.myTeamCount) {
+ trap_Cmd_ExecuteText( EXEC_APPEND, orders );
+ trap_Cmd_ExecuteText( EXEC_APPEND, "\n" );
+ }
+ trap_Key_SetCatcher( trap_Key_GetCatcher() & ~KEYCATCH_UI );
+ trap_Key_ClearStates();
+ trap_Cvar_Set( "cl_paused", "0" );
+ Menus_CloseAll();
+ }
+ } else if (Q_stricmp(name, "voiceOrders") == 0) {
+ const char *orders;
+ if (String_Parse(args, &orders)) {
+ int selectedPlayer = trap_Cvar_VariableValue("cg_selectedPlayer");
+ if (selectedPlayer < uiInfo.myTeamCount) {
+ strcpy(buff, orders);
+ trap_Cmd_ExecuteText( EXEC_APPEND, va(buff, uiInfo.teamClientNums[selectedPlayer]) );
+ trap_Cmd_ExecuteText( EXEC_APPEND, "\n" );
+ }
+ trap_Key_SetCatcher( trap_Key_GetCatcher() & ~KEYCATCH_UI );
+ trap_Key_ClearStates();
+ trap_Cvar_Set( "cl_paused", "0" );
+ Menus_CloseAll();
+ }
+ } else if (Q_stricmp(name, "glCustom") == 0) {
+ trap_Cvar_Set("ui_glCustom", "4");
+ } else if (Q_stricmp(name, "update") == 0) {
+ if (String_Parse(args, &name2)) {
+ UI_Update(name2);
+ }
+ } else if (Q_stricmp(name, "setPbClStatus") == 0) {
+ int stat;
+ if ( Int_Parse( args, &stat ) )
+ trap_SetPbClStatus( stat );
+ }
+ else {
+ Com_Printf("unknown UI script %s\n", name);
+ }
+ }
+}
+
+static void UI_GetTeamColor(vec4_t *color) {
+}
+
+/*
+==================
+UI_MapCountByGameType
+==================
+*/
+static int UI_MapCountByGameType(qboolean singlePlayer) {
+ int i, c, game;
+ c = 0;
+ game = singlePlayer ? uiInfo.gameTypes[ui_gameType.integer].gtEnum : uiInfo.gameTypes[ui_netGameType.integer].gtEnum;
+ if (game == GT_SINGLE_PLAYER) {
+ game++;
+ }
+ if (game == GT_TEAM) {
+ game = GT_FFA;
+ }
+
+ for (i = 0; i < uiInfo.mapCount; i++) {
+ uiInfo.mapList[i].active = qfalse;
+ if ( uiInfo.mapList[i].typeBits & (1 << game)) {
+ if (singlePlayer) {
+ if (!(uiInfo.mapList[i].typeBits & (1 << GT_SINGLE_PLAYER))) {
+ continue;
+ }
+ }
+ c++;
+ uiInfo.mapList[i].active = qtrue;
+ }
+ }
+ return c;
+}
+
+qboolean UI_hasSkinForBase(const char *base, const char *team) {
+ char test[1024];
+
+ Com_sprintf( test, sizeof( test ), "models/players/%s/%s/lower_default.skin", base, team );
+
+ if (trap_FS_FOpenFile(test, 0, FS_READ)) {
+ return qtrue;
+ }
+ Com_sprintf( test, sizeof( test ), "models/players/characters/%s/%s/lower_default.skin", base, team );
+
+ if (trap_FS_FOpenFile(test, 0, FS_READ)) {
+ return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+==================
+UI_MapCountByTeam
+==================
+*/
+static int UI_HeadCountByTeam() {
+ static int init = 0;
+ int i, j, k, c, tIndex;
+
+ c = 0;
+ if (!init) {
+ for (i = 0; i < uiInfo.characterCount; i++) {
+ uiInfo.characterList[i].reference = 0;
+ for (j = 0; j < uiInfo.teamCount; j++) {
+ if (UI_hasSkinForBase(uiInfo.characterList[i].base, uiInfo.teamList[j].teamName)) {
+ uiInfo.characterList[i].reference |= (1<<j);
+ }
+ }
+ }
+ init = 1;
+ }
+
+ tIndex = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_teamName"));
+
+ // do names
+ for (i = 0; i < uiInfo.characterCount; i++) {
+ uiInfo.characterList[i].active = qfalse;
+ for(j = 0; j < TEAM_MEMBERS; j++) {
+ if (uiInfo.teamList[tIndex].teamMembers[j] != NULL) {
+ if (uiInfo.characterList[i].reference&(1<<tIndex)) {// && Q_stricmp(uiInfo.teamList[tIndex].teamMembers[j], uiInfo.characterList[i].name)==0) {
+ uiInfo.characterList[i].active = qtrue;
+ c++;
+ break;
+ }
+ }
+ }
+ }
+
+ // and then aliases
+ for(j = 0; j < TEAM_MEMBERS; j++) {
+ for(k = 0; k < uiInfo.aliasCount; k++) {
+ if (uiInfo.aliasList[k].name != NULL) {
+ if (Q_stricmp(uiInfo.teamList[tIndex].teamMembers[j], uiInfo.aliasList[k].name)==0) {
+ for (i = 0; i < uiInfo.characterCount; i++) {
+ if (uiInfo.characterList[i].headImage != -1 && uiInfo.characterList[i].reference&(1<<tIndex) && Q_stricmp(uiInfo.aliasList[k].ai, uiInfo.characterList[i].name)==0) {
+ if (uiInfo.characterList[i].active == qfalse) {
+ uiInfo.characterList[i].active = qtrue;
+ c++;
+ }
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+ return c;
+}
+
+/*
+==================
+UI_InsertServerIntoDisplayList
+==================
+*/
+static void UI_InsertServerIntoDisplayList(int num, int position) {
+ int i;
+
+ if (position < 0 || position > uiInfo.serverStatus.numDisplayServers ) {
+ return;
+ }
+ //
+ uiInfo.serverStatus.numDisplayServers++;
+ for (i = uiInfo.serverStatus.numDisplayServers; i > position; i--) {
+ uiInfo.serverStatus.displayServers[i] = uiInfo.serverStatus.displayServers[i-1];
+ }
+ uiInfo.serverStatus.displayServers[position] = num;
+}
+
+/*
+==================
+UI_RemoveServerFromDisplayList
+==================
+*/
+static void UI_RemoveServerFromDisplayList(int num) {
+ int i, j;
+
+ for (i = 0; i < uiInfo.serverStatus.numDisplayServers; i++) {
+ if (uiInfo.serverStatus.displayServers[i] == num) {
+ uiInfo.serverStatus.numDisplayServers--;
+ for (j = i; j < uiInfo.serverStatus.numDisplayServers; j++) {
+ uiInfo.serverStatus.displayServers[j] = uiInfo.serverStatus.displayServers[j+1];
+ }
+ return;
+ }
+ }
+}
+
+/*
+==================
+UI_BinaryServerInsertion
+==================
+*/
+static void UI_BinaryServerInsertion(int num) {
+ int mid, offset, res, len;
+
+ // use binary search to insert server
+ len = uiInfo.serverStatus.numDisplayServers;
+ mid = len;
+ offset = 0;
+ res = 0;
+ while(mid > 0) {
+ mid = len >> 1;
+ //
+ res = trap_LAN_CompareServers( ui_netSource.integer, uiInfo.serverStatus.sortKey,
+ uiInfo.serverStatus.sortDir, num, uiInfo.serverStatus.displayServers[offset+mid]);
+ // if equal
+ if (res == 0) {
+ UI_InsertServerIntoDisplayList(num, offset+mid);
+ return;
+ }
+ // if larger
+ else if (res == 1) {
+ offset += mid;
+ len -= mid;
+ }
+ // if smaller
+ else {
+ len -= mid;
+ }
+ }
+ if (res == 1) {
+ offset++;
+ }
+ UI_InsertServerIntoDisplayList(num, offset);
+}
+
+/*
+==================
+UI_BuildServerDisplayList
+==================
+*/
+static void UI_BuildServerDisplayList(qboolean force) {
+ int i, count, clients, maxClients, ping, game, len, visible;
+ char info[MAX_STRING_CHARS];
+// qboolean startRefresh = qtrue; TTimo: unused
+ static int numinvisible;
+
+ if (!(force || uiInfo.uiDC.realTime > uiInfo.serverStatus.nextDisplayRefresh)) {
+ return;
+ }
+ // if we shouldn't reset
+ if ( force == 2 ) {
+ force = 0;
+ }
+
+ // do motd updates here too
+ trap_Cvar_VariableStringBuffer( "cl_motdString", uiInfo.serverStatus.motd, sizeof(uiInfo.serverStatus.motd) );
+ len = strlen(uiInfo.serverStatus.motd);
+ if (len == 0) {
+ strcpy(uiInfo.serverStatus.motd, "Welcome to Team Arena!");
+ len = strlen(uiInfo.serverStatus.motd);
+ }
+ if (len != uiInfo.serverStatus.motdLen) {
+ uiInfo.serverStatus.motdLen = len;
+ uiInfo.serverStatus.motdWidth = -1;
+ }
+
+ if (force) {
+ numinvisible = 0;
+ // clear number of displayed servers
+ uiInfo.serverStatus.numDisplayServers = 0;
+ uiInfo.serverStatus.numPlayersOnServers = 0;
+ // set list box index to zero
+ Menu_SetFeederSelection(NULL, FEEDER_SERVERS, 0, NULL);
+ // mark all servers as visible so we store ping updates for them
+ trap_LAN_MarkServerVisible(ui_netSource.integer, -1, qtrue);
+ }
+
+ // get the server count (comes from the master)
+ count = trap_LAN_GetServerCount(ui_netSource.integer);
+ if (count == -1 || (ui_netSource.integer == AS_LOCAL && count == 0) ) {
+ // still waiting on a response from the master
+ uiInfo.serverStatus.numDisplayServers = 0;
+ uiInfo.serverStatus.numPlayersOnServers = 0;
+ uiInfo.serverStatus.nextDisplayRefresh = uiInfo.uiDC.realTime + 500;
+ return;
+ }
+
+ visible = qfalse;
+ for (i = 0; i < count; i++) {
+ // if we already got info for this server
+ if (!trap_LAN_ServerIsVisible(ui_netSource.integer, i)) {
+ continue;
+ }
+ visible = qtrue;
+ // get the ping for this server
+ ping = trap_LAN_GetServerPing(ui_netSource.integer, i);
+ if (ping > 0 || ui_netSource.integer == AS_FAVORITES) {
+
+ trap_LAN_GetServerInfo(ui_netSource.integer, i, info, MAX_STRING_CHARS);
+
+ clients = atoi(Info_ValueForKey(info, "clients"));
+ uiInfo.serverStatus.numPlayersOnServers += clients;
+
+ if (ui_browserShowEmpty.integer == 0) {
+ if (clients == 0) {
+ trap_LAN_MarkServerVisible(ui_netSource.integer, i, qfalse);
+ continue;
+ }
+ }
+
+ if (ui_browserShowFull.integer == 0) {
+ maxClients = atoi(Info_ValueForKey(info, "sv_maxclients"));
+ if (clients == maxClients) {
+ trap_LAN_MarkServerVisible(ui_netSource.integer, i, qfalse);
+ continue;
+ }
+ }
+
+ if (uiInfo.joinGameTypes[ui_joinGameType.integer].gtEnum != -1) {
+ game = atoi(Info_ValueForKey(info, "gametype"));
+ if (game != uiInfo.joinGameTypes[ui_joinGameType.integer].gtEnum) {
+ trap_LAN_MarkServerVisible(ui_netSource.integer, i, qfalse);
+ continue;
+ }
+ }
+
+ if (ui_serverFilterType.integer > 0) {
+ if (Q_stricmp(Info_ValueForKey(info, "game"), serverFilters[ui_serverFilterType.integer].basedir) != 0) {
+ trap_LAN_MarkServerVisible(ui_netSource.integer, i, qfalse);
+ continue;
+ }
+ }
+ // make sure we never add a favorite server twice
+ if (ui_netSource.integer == AS_FAVORITES) {
+ UI_RemoveServerFromDisplayList(i);
+ }
+ // insert the server into the list
+ UI_BinaryServerInsertion(i);
+ // done with this server
+ if (ping > 0) {
+ trap_LAN_MarkServerVisible(ui_netSource.integer, i, qfalse);
+ numinvisible++;
+ }
+ }
+ }
+
+ uiInfo.serverStatus.refreshtime = uiInfo.uiDC.realTime;
+
+ // if there were no servers visible for ping updates
+ if (!visible) {
+// UI_StopServerRefresh();
+// uiInfo.serverStatus.nextDisplayRefresh = 0;
+ }
+}
+
+typedef struct
+{
+ char *name, *altName;
+} serverStatusCvar_t;
+
+serverStatusCvar_t serverStatusCvars[] = {
+ {"sv_hostname", "Name"},
+ {"Address", ""},
+ {"gamename", "Game name"},
+ {"g_gametype", "Game type"},
+ {"mapname", "Map"},
+ {"version", ""},
+ {"protocol", ""},
+ {"timelimit", ""},
+ {"fraglimit", ""},
+ {NULL, NULL}
+};
+
+/*
+==================
+UI_SortServerStatusInfo
+==================
+*/
+static void UI_SortServerStatusInfo( serverStatusInfo_t *info ) {
+ int i, j, index;
+ char *tmp1, *tmp2;
+
+ // FIXME: if "gamename" == "baseq3" or "missionpack" then
+ // replace the gametype number by FFA, CTF etc.
+ //
+ index = 0;
+ for (i = 0; serverStatusCvars[i].name; i++) {
+ for (j = 0; j < info->numLines; j++) {
+ if ( !info->lines[j][1] || info->lines[j][1][0] ) {
+ continue;
+ }
+ if ( !Q_stricmp(serverStatusCvars[i].name, info->lines[j][0]) ) {
+ // swap lines
+ tmp1 = info->lines[index][0];
+ tmp2 = info->lines[index][3];
+ info->lines[index][0] = info->lines[j][0];
+ info->lines[index][3] = info->lines[j][3];
+ info->lines[j][0] = tmp1;
+ info->lines[j][3] = tmp2;
+ //
+ if ( strlen(serverStatusCvars[i].altName) ) {
+ info->lines[index][0] = serverStatusCvars[i].altName;
+ }
+ index++;
+ }
+ }
+ }
+}
+
+/*
+==================
+UI_GetServerStatusInfo
+==================
+*/
+static int UI_GetServerStatusInfo( const char *serverAddress, serverStatusInfo_t *info ) {
+ char *p, *score, *ping, *name;
+ int i, len;
+
+ if (!info) {
+ trap_LAN_ServerStatus( serverAddress, NULL, 0);
+ return qfalse;
+ }
+ memset(info, 0, sizeof(*info));
+ if ( trap_LAN_ServerStatus( serverAddress, info->text, sizeof(info->text)) ) {
+ Q_strncpyz(info->address, serverAddress, sizeof(info->address));
+ p = info->text;
+ info->numLines = 0;
+ info->lines[info->numLines][0] = "Address";
+ info->lines[info->numLines][1] = "";
+ info->lines[info->numLines][2] = "";
+ info->lines[info->numLines][3] = info->address;
+ info->numLines++;
+ // get the cvars
+ while (p && *p) {
+ p = strchr(p, '\\');
+ if (!p) break;
+ *p++ = '\0';
+ if (*p == '\\')
+ break;
+ info->lines[info->numLines][0] = p;
+ info->lines[info->numLines][1] = "";
+ info->lines[info->numLines][2] = "";
+ p = strchr(p, '\\');
+ if (!p) break;
+ *p++ = '\0';
+ info->lines[info->numLines][3] = p;
+
+ info->numLines++;
+ if (info->numLines >= MAX_SERVERSTATUS_LINES)
+ break;
+ }
+ // get the player list
+ if (info->numLines < MAX_SERVERSTATUS_LINES-3) {
+ // empty line
+ info->lines[info->numLines][0] = "";
+ info->lines[info->numLines][1] = "";
+ info->lines[info->numLines][2] = "";
+ info->lines[info->numLines][3] = "";
+ info->numLines++;
+ // header
+ info->lines[info->numLines][0] = "num";
+ info->lines[info->numLines][1] = "score";
+ info->lines[info->numLines][2] = "ping";
+ info->lines[info->numLines][3] = "name";
+ info->numLines++;
+ // parse players
+ i = 0;
+ len = 0;
+ while (p && *p) {
+ if (*p == '\\')
+ *p++ = '\0';
+ if (!p)
+ break;
+ score = p;
+ p = strchr(p, ' ');
+ if (!p)
+ break;
+ *p++ = '\0';
+ ping = p;
+ p = strchr(p, ' ');
+ if (!p)
+ break;
+ *p++ = '\0';
+ name = p;
+ Com_sprintf(&info->pings[len], sizeof(info->pings)-len, "%d", i);
+ info->lines[info->numLines][0] = &info->pings[len];
+ len += strlen(&info->pings[len]) + 1;
+ info->lines[info->numLines][1] = score;
+ info->lines[info->numLines][2] = ping;
+ info->lines[info->numLines][3] = name;
+ info->numLines++;
+ if (info->numLines >= MAX_SERVERSTATUS_LINES)
+ break;
+ p = strchr(p, '\\');
+ if (!p)
+ break;
+ *p++ = '\0';
+ //
+ i++;
+ }
+ }
+ UI_SortServerStatusInfo( info );
+ return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+==================
+stristr
+==================
+*/
+static char *stristr(char *str, char *charset) {
+ int i;
+
+ while(*str) {
+ for (i = 0; charset[i] && str[i]; i++) {
+ if (toupper(charset[i]) != toupper(str[i])) break;
+ }
+ if (!charset[i]) return str;
+ str++;
+ }
+ return NULL;
+}
+
+/*
+==================
+UI_BuildFindPlayerList
+==================
+*/
+static void UI_BuildFindPlayerList(qboolean force) {
+ static int numFound, numTimeOuts;
+ int i, j, resend;
+ serverStatusInfo_t info;
+ char name[MAX_NAME_LENGTH+2];
+ char infoString[MAX_STRING_CHARS];
+
+ if (!force) {
+ if (!uiInfo.nextFindPlayerRefresh || uiInfo.nextFindPlayerRefresh > uiInfo.uiDC.realTime) {
+ return;
+ }
+ }
+ else {
+ memset(&uiInfo.pendingServerStatus, 0, sizeof(uiInfo.pendingServerStatus));
+ uiInfo.numFoundPlayerServers = 0;
+ uiInfo.currentFoundPlayerServer = 0;
+ trap_Cvar_VariableStringBuffer( "ui_findPlayer", uiInfo.findPlayerName, sizeof(uiInfo.findPlayerName));
+ Q_CleanStr(uiInfo.findPlayerName);
+ // should have a string of some length
+ if (!strlen(uiInfo.findPlayerName)) {
+ uiInfo.nextFindPlayerRefresh = 0;
+ return;
+ }
+ // set resend time
+ resend = ui_serverStatusTimeOut.integer / 2 - 10;
+ if (resend < 50) {
+ resend = 50;
+ }
+ trap_Cvar_Set("cl_serverStatusResendTime", va("%d", resend));
+ // reset all server status requests
+ trap_LAN_ServerStatus( NULL, NULL, 0);
+ //
+ uiInfo.numFoundPlayerServers = 1;
+ Com_sprintf(uiInfo.foundPlayerServerNames[uiInfo.numFoundPlayerServers-1],
+ sizeof(uiInfo.foundPlayerServerNames[uiInfo.numFoundPlayerServers-1]),
+ "searching %d...", uiInfo.pendingServerStatus.num);
+ numFound = 0;
+ numTimeOuts++;
+ }
+ for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) {
+ // if this pending server is valid
+ if (uiInfo.pendingServerStatus.server[i].valid) {
+ // try to get the server status for this server
+ if (UI_GetServerStatusInfo( uiInfo.pendingServerStatus.server[i].adrstr, &info ) ) {
+ //
+ numFound++;
+ // parse through the server status lines
+ for (j = 0; j < info.numLines; j++) {
+ // should have ping info
+ if ( !info.lines[j][2] || !info.lines[j][2][0] ) {
+ continue;
+ }
+ // clean string first
+ Q_strncpyz(name, info.lines[j][3], sizeof(name));
+ Q_CleanStr(name);
+ // if the player name is a substring
+ if (stristr(name, uiInfo.findPlayerName)) {
+ // add to found server list if we have space (always leave space for a line with the number found)
+ if (uiInfo.numFoundPlayerServers < MAX_FOUNDPLAYER_SERVERS-1) {
+ //
+ Q_strncpyz(uiInfo.foundPlayerServerAddresses[uiInfo.numFoundPlayerServers-1],
+ uiInfo.pendingServerStatus.server[i].adrstr,
+ sizeof(uiInfo.foundPlayerServerAddresses[0]));
+ Q_strncpyz(uiInfo.foundPlayerServerNames[uiInfo.numFoundPlayerServers-1],
+ uiInfo.pendingServerStatus.server[i].name,
+ sizeof(uiInfo.foundPlayerServerNames[0]));
+ uiInfo.numFoundPlayerServers++;
+ }
+ else {
+ // can't add any more so we're done
+ uiInfo.pendingServerStatus.num = uiInfo.serverStatus.numDisplayServers;
+ }
+ }
+ }
+ Com_sprintf(uiInfo.foundPlayerServerNames[uiInfo.numFoundPlayerServers-1],
+ sizeof(uiInfo.foundPlayerServerNames[uiInfo.numFoundPlayerServers-1]),
+ "searching %d/%d...", uiInfo.pendingServerStatus.num, numFound);
+ // retrieved the server status so reuse this spot
+ uiInfo.pendingServerStatus.server[i].valid = qfalse;
+ }
+ }
+ // if empty pending slot or timed out
+ if (!uiInfo.pendingServerStatus.server[i].valid ||
+ uiInfo.pendingServerStatus.server[i].startTime < uiInfo.uiDC.realTime - ui_serverStatusTimeOut.integer) {
+ if (uiInfo.pendingServerStatus.server[i].valid) {
+ numTimeOuts++;
+ }
+ // reset server status request for this address
+ UI_GetServerStatusInfo( uiInfo.pendingServerStatus.server[i].adrstr, NULL );
+ // reuse pending slot
+ uiInfo.pendingServerStatus.server[i].valid = qfalse;
+ // if we didn't try to get the status of all servers in the main browser yet
+ if (uiInfo.pendingServerStatus.num < uiInfo.serverStatus.numDisplayServers) {
+ uiInfo.pendingServerStatus.server[i].startTime = uiInfo.uiDC.realTime;
+ trap_LAN_GetServerAddressString(ui_netSource.integer, uiInfo.serverStatus.displayServers[uiInfo.pendingServerStatus.num],
+ uiInfo.pendingServerStatus.server[i].adrstr, sizeof(uiInfo.pendingServerStatus.server[i].adrstr));
+ trap_LAN_GetServerInfo(ui_netSource.integer, uiInfo.serverStatus.displayServers[uiInfo.pendingServerStatus.num], infoString, sizeof(infoString));
+ Q_strncpyz(uiInfo.pendingServerStatus.server[i].name, Info_ValueForKey(infoString, "hostname"), sizeof(uiInfo.pendingServerStatus.server[0].name));
+ uiInfo.pendingServerStatus.server[i].valid = qtrue;
+ uiInfo.pendingServerStatus.num++;
+ Com_sprintf(uiInfo.foundPlayerServerNames[uiInfo.numFoundPlayerServers-1],
+ sizeof(uiInfo.foundPlayerServerNames[uiInfo.numFoundPlayerServers-1]),
+ "searching %d/%d...", uiInfo.pendingServerStatus.num, numFound);
+ }
+ }
+ }
+ for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) {
+ if (uiInfo.pendingServerStatus.server[i].valid) {
+ break;
+ }
+ }
+ // if still trying to retrieve server status info
+ if (i < MAX_SERVERSTATUSREQUESTS) {
+ uiInfo.nextFindPlayerRefresh = uiInfo.uiDC.realTime + 25;
+ }
+ else {
+ // add a line that shows the number of servers found
+ if (!uiInfo.numFoundPlayerServers) {
+ Com_sprintf(uiInfo.foundPlayerServerNames[uiInfo.numFoundPlayerServers-1], sizeof(uiInfo.foundPlayerServerAddresses[0]), "no servers found");
+ }
+ else {
+ Com_sprintf(uiInfo.foundPlayerServerNames[uiInfo.numFoundPlayerServers-1], sizeof(uiInfo.foundPlayerServerAddresses[0]),
+ "%d server%s found with player %s", uiInfo.numFoundPlayerServers-1,
+ uiInfo.numFoundPlayerServers == 2 ? "":"s", uiInfo.findPlayerName);
+ }
+ uiInfo.nextFindPlayerRefresh = 0;
+ // show the server status info for the selected server
+ UI_FeederSelection(FEEDER_FINDPLAYER, uiInfo.currentFoundPlayerServer);
+ }
+}
+
+/*
+==================
+UI_BuildServerStatus
+==================
+*/
+static void UI_BuildServerStatus(qboolean force) {
+
+ if (uiInfo.nextFindPlayerRefresh) {
+ return;
+ }
+ if (!force) {
+ if (!uiInfo.nextServerStatusRefresh || uiInfo.nextServerStatusRefresh > uiInfo.uiDC.realTime) {
+ return;
+ }
+ }
+ else {
+ Menu_SetFeederSelection(NULL, FEEDER_SERVERSTATUS, 0, NULL);
+ uiInfo.serverStatusInfo.numLines = 0;
+ // reset all server status requests
+ trap_LAN_ServerStatus( NULL, NULL, 0);
+ }
+ if (uiInfo.serverStatus.currentServer < 0 || uiInfo.serverStatus.currentServer > uiInfo.serverStatus.numDisplayServers || uiInfo.serverStatus.numDisplayServers == 0) {
+ return;
+ }
+ if (UI_GetServerStatusInfo( uiInfo.serverStatusAddress, &uiInfo.serverStatusInfo ) ) {
+ uiInfo.nextServerStatusRefresh = 0;
+ UI_GetServerStatusInfo( uiInfo.serverStatusAddress, NULL );
+ }
+ else {
+ uiInfo.nextServerStatusRefresh = uiInfo.uiDC.realTime + 500;
+ }
+}
+
+/*
+==================
+UI_FeederCount
+==================
+*/
+static int UI_FeederCount(float feederID) {
+ if (feederID == FEEDER_HEADS) {
+ return UI_HeadCountByTeam();
+ } else if (feederID == FEEDER_Q3HEADS) {
+ return uiInfo.q3HeadCount;
+ } else if (feederID == FEEDER_CINEMATICS) {
+ return uiInfo.movieCount;
+ } else if (feederID == FEEDER_MAPS || feederID == FEEDER_ALLMAPS) {
+ return UI_MapCountByGameType(feederID == FEEDER_MAPS ? qtrue : qfalse);
+ } else if (feederID == FEEDER_SERVERS) {
+ return uiInfo.serverStatus.numDisplayServers;
+ } else if (feederID == FEEDER_SERVERSTATUS) {
+ return uiInfo.serverStatusInfo.numLines;
+ } else if (feederID == FEEDER_FINDPLAYER) {
+ return uiInfo.numFoundPlayerServers;
+ } else if (feederID == FEEDER_PLAYER_LIST) {
+ if (uiInfo.uiDC.realTime > uiInfo.playerRefresh) {
+ uiInfo.playerRefresh = uiInfo.uiDC.realTime + 3000;
+ UI_BuildPlayerList();
+ }
+ return uiInfo.playerCount;
+ } else if (feederID == FEEDER_TEAM_LIST) {
+ if (uiInfo.uiDC.realTime > uiInfo.playerRefresh) {
+ uiInfo.playerRefresh = uiInfo.uiDC.realTime + 3000;
+ UI_BuildPlayerList();
+ }
+ return uiInfo.myTeamCount;
+ } else if (feederID == FEEDER_MODS) {
+ return uiInfo.modCount;
+ } else if (feederID == FEEDER_DEMOS) {
+ return uiInfo.demoCount;
+ }
+ return 0;
+}
+
+static const char *UI_SelectedMap(int index, int *actual) {
+ int i, c;
+ c = 0;
+ *actual = 0;
+ for (i = 0; i < uiInfo.mapCount; i++) {
+ if (uiInfo.mapList[i].active) {
+ if (c == index) {
+ *actual = i;
+ return uiInfo.mapList[i].mapName;
+ } else {
+ c++;
+ }
+ }
+ }
+ return "";
+}
+
+static const char *UI_SelectedHead(int index, int *actual) {
+ int i, c;
+ c = 0;
+ *actual = 0;
+ for (i = 0; i < uiInfo.characterCount; i++) {
+ if (uiInfo.characterList[i].active) {
+ if (c == index) {
+ *actual = i;
+ return uiInfo.characterList[i].name;
+ } else {
+ c++;
+ }
+ }
+ }
+ return "";
+}
+
+static int UI_GetIndexFromSelection(int actual) {
+ int i, c;
+ c = 0;
+ for (i = 0; i < uiInfo.mapCount; i++) {
+ if (uiInfo.mapList[i].active) {
+ if (i == actual) {
+ return c;
+ }
+ c++;
+ }
+ }
+ return 0;
+}
+
+static void UI_UpdatePendingPings() {
+ trap_LAN_ResetPings(ui_netSource.integer);
+ uiInfo.serverStatus.refreshActive = qtrue;
+ uiInfo.serverStatus.refreshtime = uiInfo.uiDC.realTime + 1000;
+
+}
+
+static const char *UI_FeederItemText(float feederID, int index, int column, qhandle_t *handle) {
+ static char info[MAX_STRING_CHARS];
+ static char hostname[1024];
+ static char clientBuff[32];
+ static int lastColumn = -1;
+ static int lastTime = 0;
+ *handle = -1;
+ if (feederID == FEEDER_HEADS) {
+ int actual;
+ return UI_SelectedHead(index, &actual);
+ } else if (feederID == FEEDER_Q3HEADS) {
+ if (index >= 0 && index < uiInfo.q3HeadCount) {
+ return uiInfo.q3HeadNames[index];
+ }
+ } else if (feederID == FEEDER_MAPS || feederID == FEEDER_ALLMAPS) {
+ int actual;
+ return UI_SelectedMap(index, &actual);
+ } else if (feederID == FEEDER_SERVERS) {
+ if (index >= 0 && index < uiInfo.serverStatus.numDisplayServers) {
+ int ping, game, punkbuster;
+ if (lastColumn != column || lastTime > uiInfo.uiDC.realTime + 5000) {
+ trap_LAN_GetServerInfo(ui_netSource.integer, uiInfo.serverStatus.displayServers[index], info, MAX_STRING_CHARS);
+ lastColumn = column;
+ lastTime = uiInfo.uiDC.realTime;
+ }
+ ping = atoi(Info_ValueForKey(info, "ping"));
+ if (ping == -1) {
+ // if we ever see a ping that is out of date, do a server refresh
+ // UI_UpdatePendingPings();
+ }
+ switch (column) {
+ case SORT_HOST :
+ if (ping <= 0) {
+ return Info_ValueForKey(info, "addr");
+ } else {
+ if ( ui_netSource.integer == AS_LOCAL ) {
+ Com_sprintf( hostname, sizeof(hostname), "%s [%s]",
+ Info_ValueForKey(info, "hostname"),
+ netnames[atoi(Info_ValueForKey(info, "nettype"))] );
+ return hostname;
+ }
+ else {
+ Com_sprintf( hostname, sizeof(hostname), "%s", Info_ValueForKey(info, "hostname"));
+ return hostname;
+ }
+ }
+ case SORT_MAP : return Info_ValueForKey(info, "mapname");
+ case SORT_CLIENTS :
+ Com_sprintf( clientBuff, sizeof(clientBuff), "%s (%s)", Info_ValueForKey(info, "clients"), Info_ValueForKey(info, "sv_maxclients"));
+ return clientBuff;
+ case SORT_GAME :
+ game = atoi(Info_ValueForKey(info, "gametype"));
+ if (game >= 0 && game < numTeamArenaGameTypes) {
+ return teamArenaGameTypes[game];
+ } else {
+ return "Unknown";
+ }
+ case SORT_PING :
+ if (ping <= 0) {
+ return "...";
+ } else {
+ return Info_ValueForKey(info, "ping");
+ }
+ case SORT_PUNKBUSTER:
+ punkbuster = atoi(Info_ValueForKey(info, "punkbuster"));
+ if ( punkbuster ) {
+ return "Yes";
+ } else {
+ return "No";
+ }
+ }
+ }
+ } else if (feederID == FEEDER_SERVERSTATUS) {
+ if ( index >= 0 && index < uiInfo.serverStatusInfo.numLines ) {
+ if ( column >= 0 && column < 4 ) {
+ return uiInfo.serverStatusInfo.lines[index][column];
+ }
+ }
+ } else if (feederID == FEEDER_FINDPLAYER) {
+ if ( index >= 0 && index < uiInfo.numFoundPlayerServers ) {
+ //return uiInfo.foundPlayerServerAddresses[index];
+ return uiInfo.foundPlayerServerNames[index];
+ }
+ } else if (feederID == FEEDER_PLAYER_LIST) {
+ if (index >= 0 && index < uiInfo.playerCount) {
+ return uiInfo.playerNames[index];
+ }
+ } else if (feederID == FEEDER_TEAM_LIST) {
+ if (index >= 0 && index < uiInfo.myTeamCount) {
+ return uiInfo.teamNames[index];
+ }
+ } else if (feederID == FEEDER_MODS) {
+ if (index >= 0 && index < uiInfo.modCount) {
+ if (uiInfo.modList[index].modDescr && *uiInfo.modList[index].modDescr) {
+ return uiInfo.modList[index].modDescr;
+ } else {
+ return uiInfo.modList[index].modName;
+ }
+ }
+ } else if (feederID == FEEDER_CINEMATICS) {
+ if (index >= 0 && index < uiInfo.movieCount) {
+ return uiInfo.movieList[index];
+ }
+ } else if (feederID == FEEDER_DEMOS) {
+ if (index >= 0 && index < uiInfo.demoCount) {
+ return uiInfo.demoList[index];
+ }
+ }
+ return "";
+}
+
+
+static qhandle_t UI_FeederItemImage(float feederID, int index) {
+ if (feederID == FEEDER_HEADS) {
+ int actual;
+ UI_SelectedHead(index, &actual);
+ index = actual;
+ if (index >= 0 && index < uiInfo.characterCount) {
+ if (uiInfo.characterList[index].headImage == -1) {
+ uiInfo.characterList[index].headImage = trap_R_RegisterShaderNoMip(uiInfo.characterList[index].imageName);
+ }
+ return uiInfo.characterList[index].headImage;
+ }
+ } else if (feederID == FEEDER_Q3HEADS) {
+ if (index >= 0 && index < uiInfo.q3HeadCount) {
+ return uiInfo.q3HeadIcons[index];
+ }
+ } else if (feederID == FEEDER_ALLMAPS || feederID == FEEDER_MAPS) {
+ int actual;
+ UI_SelectedMap(index, &actual);
+ index = actual;
+ if (index >= 0 && index < uiInfo.mapCount) {
+ if (uiInfo.mapList[index].levelShot == -1) {
+ uiInfo.mapList[index].levelShot = trap_R_RegisterShaderNoMip(uiInfo.mapList[index].imageName);
+ }
+ return uiInfo.mapList[index].levelShot;
+ }
+ }
+ return 0;
+}
+
+static void UI_FeederSelection(float feederID, int index) {
+ static char info[MAX_STRING_CHARS];
+ if (feederID == FEEDER_HEADS) {
+ int actual;
+ UI_SelectedHead(index, &actual);
+ index = actual;
+ if (index >= 0 && index < uiInfo.characterCount) {
+ trap_Cvar_Set( "team_model", va("%s", uiInfo.characterList[index].base));
+ trap_Cvar_Set( "team_headmodel", va("*%s", uiInfo.characterList[index].name));
+ updateModel = qtrue;
+ }
+ } else if (feederID == FEEDER_Q3HEADS) {
+ if (index >= 0 && index < uiInfo.q3HeadCount) {
+ trap_Cvar_Set( "model", uiInfo.q3HeadNames[index]);
+ trap_Cvar_Set( "headmodel", uiInfo.q3HeadNames[index]);
+ updateModel = qtrue;
+ }
+ } else if (feederID == FEEDER_MAPS || feederID == FEEDER_ALLMAPS) {
+ int actual, map;
+ map = (feederID == FEEDER_ALLMAPS) ? ui_currentNetMap.integer : ui_currentMap.integer;
+ if (uiInfo.mapList[map].cinematic >= 0) {
+ trap_CIN_StopCinematic(uiInfo.mapList[map].cinematic);
+ uiInfo.mapList[map].cinematic = -1;
+ }
+ UI_SelectedMap(index, &actual);
+ trap_Cvar_Set("ui_mapIndex", va("%d", index));
+ ui_mapIndex.integer = index;
+
+ if (feederID == FEEDER_MAPS) {
+ ui_currentMap.integer = actual;
+ trap_Cvar_Set("ui_currentMap", va("%d", actual));
+ uiInfo.mapList[ui_currentMap.integer].cinematic = trap_CIN_PlayCinematic(va("%s.roq", uiInfo.mapList[ui_currentMap.integer].mapLoadName), 0, 0, 0, 0, (CIN_loop | CIN_silent) );
+ UI_LoadBestScores(uiInfo.mapList[ui_currentMap.integer].mapLoadName, uiInfo.gameTypes[ui_gameType.integer].gtEnum);
+ trap_Cvar_Set("ui_opponentModel", uiInfo.mapList[ui_currentMap.integer].opponentName);
+ updateOpponentModel = qtrue;
+ } else {
+ ui_currentNetMap.integer = actual;
+ trap_Cvar_Set("ui_currentNetMap", va("%d", actual));
+ uiInfo.mapList[ui_currentNetMap.integer].cinematic = trap_CIN_PlayCinematic(va("%s.roq", uiInfo.mapList[ui_currentNetMap.integer].mapLoadName), 0, 0, 0, 0, (CIN_loop | CIN_silent) );
+ }
+
+ } else if (feederID == FEEDER_SERVERS) {
+ const char *mapName = NULL;
+ uiInfo.serverStatus.currentServer = index;
+ trap_LAN_GetServerInfo(ui_netSource.integer, uiInfo.serverStatus.displayServers[index], info, MAX_STRING_CHARS);
+ uiInfo.serverStatus.currentServerPreview = trap_R_RegisterShaderNoMip(va("levelshots/%s", Info_ValueForKey(info, "mapname")));
+ if (uiInfo.serverStatus.currentServerCinematic >= 0) {
+ trap_CIN_StopCinematic(uiInfo.serverStatus.currentServerCinematic);
+ uiInfo.serverStatus.currentServerCinematic = -1;
+ }
+ mapName = Info_ValueForKey(info, "mapname");
+ if (mapName && *mapName) {
+ uiInfo.serverStatus.currentServerCinematic = trap_CIN_PlayCinematic(va("%s.roq", mapName), 0, 0, 0, 0, (CIN_loop | CIN_silent) );
+ }
+ } else if (feederID == FEEDER_SERVERSTATUS) {
+ //
+ } else if (feederID == FEEDER_FINDPLAYER) {
+ uiInfo.currentFoundPlayerServer = index;
+ //
+ if ( index < uiInfo.numFoundPlayerServers-1) {
+ // build a new server status for this server
+ Q_strncpyz(uiInfo.serverStatusAddress, uiInfo.foundPlayerServerAddresses[uiInfo.currentFoundPlayerServer], sizeof(uiInfo.serverStatusAddress));
+ Menu_SetFeederSelection(NULL, FEEDER_SERVERSTATUS, 0, NULL);
+ UI_BuildServerStatus(qtrue);
+ }
+ } else if (feederID == FEEDER_PLAYER_LIST) {
+ uiInfo.playerIndex = index;
+ } else if (feederID == FEEDER_TEAM_LIST) {
+ uiInfo.teamIndex = index;
+ } else if (feederID == FEEDER_MODS) {
+ uiInfo.modIndex = index;
+ } else if (feederID == FEEDER_CINEMATICS) {
+ uiInfo.movieIndex = index;
+ if (uiInfo.previewMovie >= 0) {
+ trap_CIN_StopCinematic(uiInfo.previewMovie);
+ }
+ uiInfo.previewMovie = -1;
+ } else if (feederID == FEEDER_DEMOS) {
+ uiInfo.demoIndex = index;
+ }
+}
+
+static qboolean Team_Parse(char **p) {
+ char *token;
+ const char *tempStr;
+ int i;
+
+ token = COM_ParseExt(p, qtrue);
+
+ if (token[0] != '{') {
+ return qfalse;
+ }
+
+ while ( 1 ) {
+
+ token = COM_ParseExt(p, qtrue);
+
+ if (Q_stricmp(token, "}") == 0) {
+ return qtrue;
+ }
+
+ if ( !token || token[0] == 0 ) {
+ return qfalse;
+ }
+
+ if (token[0] == '{') {
+ // seven tokens per line, team name and icon, and 5 team member names
+ if (!String_Parse(p, &uiInfo.teamList[uiInfo.teamCount].teamName) || !String_Parse(p, &tempStr)) {
+ return qfalse;
+ }
+
+
+ uiInfo.teamList[uiInfo.teamCount].imageName = tempStr;
+ uiInfo.teamList[uiInfo.teamCount].teamIcon = trap_R_RegisterShaderNoMip(uiInfo.teamList[uiInfo.teamCount].imageName);
+ uiInfo.teamList[uiInfo.teamCount].teamIcon_Metal = trap_R_RegisterShaderNoMip(va("%s_metal",uiInfo.teamList[uiInfo.teamCount].imageName));
+ uiInfo.teamList[uiInfo.teamCount].teamIcon_Name = trap_R_RegisterShaderNoMip(va("%s_name", uiInfo.teamList[uiInfo.teamCount].imageName));
+
+ uiInfo.teamList[uiInfo.teamCount].cinematic = -1;
+
+ for (i = 0; i < TEAM_MEMBERS; i++) {
+ uiInfo.teamList[uiInfo.teamCount].teamMembers[i] = NULL;
+ if (!String_Parse(p, &uiInfo.teamList[uiInfo.teamCount].teamMembers[i])) {
+ return qfalse;
+ }
+ }
+
+ Com_Printf("Loaded team %s with team icon %s.\n", uiInfo.teamList[uiInfo.teamCount].teamName, tempStr);
+ if (uiInfo.teamCount < MAX_TEAMS) {
+ uiInfo.teamCount++;
+ } else {
+ Com_Printf("Too many teams, last team replaced!\n");
+ }
+ token = COM_ParseExt(p, qtrue);
+ if (token[0] != '}') {
+ return qfalse;
+ }
+ }
+ }
+
+ return qfalse;
+}
+
+static qboolean Character_Parse(char **p) {
+ char *token;
+ const char *tempStr;
+
+ token = COM_ParseExt(p, qtrue);
+
+ if (token[0] != '{') {
+ return qfalse;
+ }
+
+
+ while ( 1 ) {
+ token = COM_ParseExt(p, qtrue);
+
+ if (Q_stricmp(token, "}") == 0) {
+ return qtrue;
+ }
+
+ if ( !token || token[0] == 0 ) {
+ return qfalse;
+ }
+
+ if (token[0] == '{') {
+ // two tokens per line, character name and sex
+ if (!String_Parse(p, &uiInfo.characterList[uiInfo.characterCount].name) || !String_Parse(p, &tempStr)) {
+ return qfalse;
+ }
+
+ uiInfo.characterList[uiInfo.characterCount].headImage = -1;
+ uiInfo.characterList[uiInfo.characterCount].imageName = String_Alloc(va("models/players/heads/%s/icon_default.tga", uiInfo.characterList[uiInfo.characterCount].name));
+
+ if (tempStr && (!Q_stricmp(tempStr, "female"))) {
+ uiInfo.characterList[uiInfo.characterCount].base = String_Alloc(va("Janet"));
+ } else if (tempStr && (!Q_stricmp(tempStr, "male"))) {
+ uiInfo.characterList[uiInfo.characterCount].base = String_Alloc(va("James"));
+ } else {
+ uiInfo.characterList[uiInfo.characterCount].base = String_Alloc(va("%s",tempStr));
+ }
+
+ Com_Printf("Loaded %s character %s.\n", uiInfo.characterList[uiInfo.characterCount].base, uiInfo.characterList[uiInfo.characterCount].name);
+ if (uiInfo.characterCount < MAX_HEADS) {
+ uiInfo.characterCount++;
+ } else {
+ Com_Printf("Too many characters, last character replaced!\n");
+ }
+
+ token = COM_ParseExt(p, qtrue);
+ if (token[0] != '}') {
+ return qfalse;
+ }
+ }
+ }
+
+ return qfalse;
+}
+
+
+static qboolean Alias_Parse(char **p) {
+ char *token;
+
+ token = COM_ParseExt(p, qtrue);
+
+ if (token[0] != '{') {
+ return qfalse;
+ }
+
+ while ( 1 ) {
+ token = COM_ParseExt(p, qtrue);
+
+ if (Q_stricmp(token, "}") == 0) {
+ return qtrue;
+ }
+
+ if ( !token || token[0] == 0 ) {
+ return qfalse;
+ }
+
+ if (token[0] == '{') {
+ // three tokens per line, character name, bot alias, and preferred action a - all purpose, d - defense, o - offense
+ if (!String_Parse(p, &uiInfo.aliasList[uiInfo.aliasCount].name) || !String_Parse(p, &uiInfo.aliasList[uiInfo.aliasCount].ai) || !String_Parse(p, &uiInfo.aliasList[uiInfo.aliasCount].action)) {
+ return qfalse;
+ }
+
+ Com_Printf("Loaded character alias %s using character ai %s.\n", uiInfo.aliasList[uiInfo.aliasCount].name, uiInfo.aliasList[uiInfo.aliasCount].ai);
+ if (uiInfo.aliasCount < MAX_ALIASES) {
+ uiInfo.aliasCount++;
+ } else {
+ Com_Printf("Too many aliases, last alias replaced!\n");
+ }
+
+ token = COM_ParseExt(p, qtrue);
+ if (token[0] != '}') {
+ return qfalse;
+ }
+ }
+ }
+
+ return qfalse;
+}
+
+
+
+// mode
+// 0 - high level parsing
+// 1 - team parsing
+// 2 - character parsing
+static void UI_ParseTeamInfo(const char *teamFile) {
+ char *token;
+ char *p;
+ char *buff = NULL;
+ //static int mode = 0; TTimo: unused
+
+ buff = GetMenuBuffer(teamFile);
+ if (!buff) {
+ return;
+ }
+
+ p = buff;
+
+ while ( 1 ) {
+ token = COM_ParseExt( &p, qtrue );
+ if( !token || token[0] == 0 || token[0] == '}') {
+ break;
+ }
+
+ if ( Q_stricmp( token, "}" ) == 0 ) {
+ break;
+ }
+
+ if (Q_stricmp(token, "teams") == 0) {
+
+ if (Team_Parse(&p)) {
+ continue;
+ } else {
+ break;
+ }
+ }
+
+ if (Q_stricmp(token, "characters") == 0) {
+ Character_Parse(&p);
+ }
+
+ if (Q_stricmp(token, "aliases") == 0) {
+ Alias_Parse(&p);
+ }
+
+ }
+
+}
+
+
+static qboolean GameType_Parse(char **p, qboolean join) {
+ char *token;
+
+ token = COM_ParseExt(p, qtrue);
+
+ if (token[0] != '{') {
+ return qfalse;
+ }
+
+ if (join) {
+ uiInfo.numJoinGameTypes = 0;
+ } else {
+ uiInfo.numGameTypes = 0;
+ }
+
+ while ( 1 ) {
+ token = COM_ParseExt(p, qtrue);
+
+ if (Q_stricmp(token, "}") == 0) {
+ return qtrue;
+ }
+
+ if ( !token || token[0] == 0 ) {
+ return qfalse;
+ }
+
+ if (token[0] == '{') {
+ // two tokens per line, character name and sex
+ if (join) {
+ if (!String_Parse(p, &uiInfo.joinGameTypes[uiInfo.numJoinGameTypes].gameType) || !Int_Parse(p, &uiInfo.joinGameTypes[uiInfo.numJoinGameTypes].gtEnum)) {
+ return qfalse;
+ }
+ } else {
+ if (!String_Parse(p, &uiInfo.gameTypes[uiInfo.numGameTypes].gameType) || !Int_Parse(p, &uiInfo.gameTypes[uiInfo.numGameTypes].gtEnum)) {
+ return qfalse;
+ }
+ }
+
+ if (join) {
+ if (uiInfo.numJoinGameTypes < MAX_GAMETYPES) {
+ uiInfo.numJoinGameTypes++;
+ } else {
+ Com_Printf("Too many net game types, last one replace!\n");
+ }
+ } else {
+ if (uiInfo.numGameTypes < MAX_GAMETYPES) {
+ uiInfo.numGameTypes++;
+ } else {
+ Com_Printf("Too many game types, last one replace!\n");
+ }
+ }
+
+ token = COM_ParseExt(p, qtrue);
+ if (token[0] != '}') {
+ return qfalse;
+ }
+ }
+ }
+ return qfalse;
+}
+
+static qboolean MapList_Parse(char **p) {
+ char *token;
+
+ token = COM_ParseExt(p, qtrue);
+
+ if (token[0] != '{') {
+ return qfalse;
+ }
+
+ uiInfo.mapCount = 0;
+
+ while ( 1 ) {
+ token = COM_ParseExt(p, qtrue);
+
+ if (Q_stricmp(token, "}") == 0) {
+ return qtrue;
+ }
+
+ if ( !token || token[0] == 0 ) {
+ return qfalse;
+ }
+
+ if (token[0] == '{') {
+ if (!String_Parse(p, &uiInfo.mapList[uiInfo.mapCount].mapName) || !String_Parse(p, &uiInfo.mapList[uiInfo.mapCount].mapLoadName)
+ ||!Int_Parse(p, &uiInfo.mapList[uiInfo.mapCount].teamMembers) ) {
+ return qfalse;
+ }
+
+ if (!String_Parse(p, &uiInfo.mapList[uiInfo.mapCount].opponentName)) {
+ return qfalse;
+ }
+
+ uiInfo.mapList[uiInfo.mapCount].typeBits = 0;
+
+ while (1) {
+ token = COM_ParseExt(p, qtrue);
+ if (token[0] >= '0' && token[0] <= '9') {
+ uiInfo.mapList[uiInfo.mapCount].typeBits |= (1 << (token[0] - 0x030));
+ if (!Int_Parse(p, &uiInfo.mapList[uiInfo.mapCount].timeToBeat[token[0] - 0x30])) {
+ return qfalse;
+ }
+ } else {
+ break;
+ }
+ }
+
+ //mapList[mapCount].imageName = String_Alloc(va("levelshots/%s", mapList[mapCount].mapLoadName));
+ //if (uiInfo.mapCount == 0) {
+ // only load the first cinematic, selection loads the others
+ // uiInfo.mapList[uiInfo.mapCount].cinematic = trap_CIN_PlayCinematic(va("%s.roq",uiInfo.mapList[uiInfo.mapCount].mapLoadName), qfalse, qfalse, qtrue, 0, 0, 0, 0);
+ //}
+ uiInfo.mapList[uiInfo.mapCount].cinematic = -1;
+ uiInfo.mapList[uiInfo.mapCount].levelShot = trap_R_RegisterShaderNoMip(va("levelshots/%s_small", uiInfo.mapList[uiInfo.mapCount].mapLoadName));
+
+ if (uiInfo.mapCount < MAX_MAPS) {
+ uiInfo.mapCount++;
+ } else {
+ Com_Printf("Too many maps, last one replaced!\n");
+ }
+ }
+ }
+ return qfalse;
+}
+
+static void UI_ParseGameInfo(const char *teamFile) {
+ char *token;
+ char *p;
+ char *buff = NULL;
+ //int mode = 0; TTimo: unused
+
+ buff = GetMenuBuffer(teamFile);
+ if (!buff) {
+ return;
+ }
+
+ p = buff;
+
+ while ( 1 ) {
+ token = COM_ParseExt( &p, qtrue );
+ if( !token || token[0] == 0 || token[0] == '}') {
+ break;
+ }
+
+ if ( Q_stricmp( token, "}" ) == 0 ) {
+ break;
+ }
+
+ if (Q_stricmp(token, "gametypes") == 0) {
+
+ if (GameType_Parse(&p, qfalse)) {
+ continue;
+ } else {
+ break;
+ }
+ }
+
+ if (Q_stricmp(token, "joingametypes") == 0) {
+
+ if (GameType_Parse(&p, qtrue)) {
+ continue;
+ } else {
+ break;
+ }
+ }
+
+ if (Q_stricmp(token, "maps") == 0) {
+ // start a new menu
+ MapList_Parse(&p);
+ }
+
+ }
+}
+
+static void UI_Pause(qboolean b) {
+ if (b) {
+ // pause the game and set the ui keycatcher
+ trap_Cvar_Set( "cl_paused", "1" );
+ trap_Key_SetCatcher( KEYCATCH_UI );
+ } else {
+ // unpause the game and clear the ui keycatcher
+ trap_Key_SetCatcher( trap_Key_GetCatcher() & ~KEYCATCH_UI );
+ trap_Key_ClearStates();
+ trap_Cvar_Set( "cl_paused", "0" );
+ }
+}
+
+#ifndef MISSIONPACK // bk001206
+static int UI_OwnerDraw_Width(int ownerDraw) {
+ // bk001205 - LCC missing return value
+ return 0;
+}
+#endif
+
+static int UI_PlayCinematic(const char *name, float x, float y, float w, float h) {
+ return trap_CIN_PlayCinematic(name, x, y, w, h, (CIN_loop | CIN_silent));
+}
+
+static void UI_StopCinematic(int handle) {
+ if (handle >= 0) {
+ trap_CIN_StopCinematic(handle);
+ } else {
+ handle = abs(handle);
+ if (handle == UI_MAPCINEMATIC) {
+ if (uiInfo.mapList[ui_currentMap.integer].cinematic >= 0) {
+ trap_CIN_StopCinematic(uiInfo.mapList[ui_currentMap.integer].cinematic);
+ uiInfo.mapList[ui_currentMap.integer].cinematic = -1;
+ }
+ } else if (handle == UI_NETMAPCINEMATIC) {
+ if (uiInfo.serverStatus.currentServerCinematic >= 0) {
+ trap_CIN_StopCinematic(uiInfo.serverStatus.currentServerCinematic);
+ uiInfo.serverStatus.currentServerCinematic = -1;
+ }
+ } else if (handle == UI_CLANCINEMATIC) {
+ int i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_teamName"));
+ if (i >= 0 && i < uiInfo.teamCount) {
+ if (uiInfo.teamList[i].cinematic >= 0) {
+ trap_CIN_StopCinematic(uiInfo.teamList[i].cinematic);
+ uiInfo.teamList[i].cinematic = -1;
+ }
+ }
+ }
+ }
+}
+
+static void UI_DrawCinematic(int handle, float x, float y, float w, float h) {
+ trap_CIN_SetExtents(handle, x, y, w, h);
+ trap_CIN_DrawCinematic(handle);
+}
+
+static void UI_RunCinematicFrame(int handle) {
+ trap_CIN_RunCinematic(handle);
+}
+
+
+
+/*
+=================
+PlayerModel_BuildList
+=================
+*/
+static void UI_BuildQ3Model_List( void )
+{
+ int numdirs;
+ int numfiles;
+ char dirlist[2048];
+ char filelist[2048];
+ char skinname[64];
+ char scratch[256];
+ char* dirptr;
+ char* fileptr;
+ int i;
+ int j, k, dirty;
+ int dirlen;
+ int filelen;
+
+ uiInfo.q3HeadCount = 0;
+
+ // iterate directory of all player models
+ numdirs = trap_FS_GetFileList("models/players", "/", dirlist, 2048 );
+ dirptr = dirlist;
+ for (i=0; i<numdirs && uiInfo.q3HeadCount < MAX_PLAYERMODELS; i++,dirptr+=dirlen+1)
+ {
+ dirlen = strlen(dirptr);
+
+ if (dirlen && dirptr[dirlen-1]=='/') dirptr[dirlen-1]='\0';
+
+ if (!strcmp(dirptr,".") || !strcmp(dirptr,".."))
+ continue;
+
+ // iterate all skin files in directory
+ numfiles = trap_FS_GetFileList( va("models/players/%s",dirptr), "tga", filelist, 2048 );
+ fileptr = filelist;
+ for (j=0; j<numfiles && uiInfo.q3HeadCount < MAX_PLAYERMODELS;j++,fileptr+=filelen+1)
+ {
+ filelen = strlen(fileptr);
+
+ COM_StripExtension(fileptr,skinname);
+
+ // look for icon_????
+ if (Q_stricmpn(skinname, "icon_", 5) == 0 && !(Q_stricmp(skinname,"icon_blue") == 0 || Q_stricmp(skinname,"icon_red") == 0))
+ {
+ if (Q_stricmp(skinname, "icon_default") == 0) {
+ Com_sprintf( scratch, sizeof(scratch), dirptr);
+ } else {
+ Com_sprintf( scratch, sizeof(scratch), "%s/%s",dirptr, skinname + 5);
+ }
+ dirty = 0;
+ for(k=0;k<uiInfo.q3HeadCount;k++) {
+ if (!Q_stricmp(scratch, uiInfo.q3HeadNames[uiInfo.q3HeadCount])) {
+ dirty = 1;
+ break;
+ }
+ }
+ if (!dirty) {
+ Com_sprintf( uiInfo.q3HeadNames[uiInfo.q3HeadCount], sizeof(uiInfo.q3HeadNames[uiInfo.q3HeadCount]), scratch);
+ uiInfo.q3HeadIcons[uiInfo.q3HeadCount++] = trap_R_RegisterShaderNoMip(va("models/players/%s/%s",dirptr,skinname));
+ }
+ }
+
+ }
+ }
+
+}
+
+
+
+/*
+=================
+UI_Init
+=================
+*/
+void _UI_Init( qboolean inGameLoad ) {
+ const char *menuSet;
+ int start;
+
+ //uiInfo.inGameLoad = inGameLoad;
+
+ UI_RegisterCvars();
+ UI_InitMemory();
+
+ // cache redundant calulations
+ trap_GetGlconfig( &uiInfo.uiDC.glconfig );
+
+ // for 640x480 virtualized screen
+ uiInfo.uiDC.yscale = uiInfo.uiDC.glconfig.vidHeight * (1.0/480.0);
+ uiInfo.uiDC.xscale = uiInfo.uiDC.glconfig.vidWidth * (1.0/640.0);
+ if ( uiInfo.uiDC.glconfig.vidWidth * 480 > uiInfo.uiDC.glconfig.vidHeight * 640 ) {
+ // wide screen
+ uiInfo.uiDC.bias = 0.5 * ( uiInfo.uiDC.glconfig.vidWidth - ( uiInfo.uiDC.glconfig.vidHeight * (640.0/480.0) ) );
+ }
+ else {
+ // no wide screen
+ uiInfo.uiDC.bias = 0;
+ }
+
+
+ //UI_Load();
+ uiInfo.uiDC.registerShaderNoMip = &trap_R_RegisterShaderNoMip;
+ uiInfo.uiDC.setColor = &UI_SetColor;
+ uiInfo.uiDC.drawHandlePic = &UI_DrawHandlePic;
+ uiInfo.uiDC.drawStretchPic = &trap_R_DrawStretchPic;
+ uiInfo.uiDC.drawText = &Text_Paint;
+ uiInfo.uiDC.textWidth = &Text_Width;
+ uiInfo.uiDC.textHeight = &Text_Height;
+ uiInfo.uiDC.registerModel = &trap_R_RegisterModel;
+ uiInfo.uiDC.modelBounds = &trap_R_ModelBounds;
+ uiInfo.uiDC.fillRect = &UI_FillRect;
+ uiInfo.uiDC.drawRect = &_UI_DrawRect;
+ uiInfo.uiDC.drawSides = &_UI_DrawSides;
+ uiInfo.uiDC.drawTopBottom = &_UI_DrawTopBottom;
+ uiInfo.uiDC.clearScene = &trap_R_ClearScene;
+ uiInfo.uiDC.drawSides = &_UI_DrawSides;
+ uiInfo.uiDC.addRefEntityToScene = &trap_R_AddRefEntityToScene;
+ uiInfo.uiDC.renderScene = &trap_R_RenderScene;
+ uiInfo.uiDC.registerFont = &trap_R_RegisterFont;
+ uiInfo.uiDC.ownerDrawItem = &UI_OwnerDraw;
+ uiInfo.uiDC.getValue = &UI_GetValue;
+ uiInfo.uiDC.ownerDrawVisible = &UI_OwnerDrawVisible;
+ uiInfo.uiDC.runScript = &UI_RunMenuScript;
+ uiInfo.uiDC.getTeamColor = &UI_GetTeamColor;
+ uiInfo.uiDC.setCVar = trap_Cvar_Set;
+ uiInfo.uiDC.getCVarString = trap_Cvar_VariableStringBuffer;
+ uiInfo.uiDC.getCVarValue = trap_Cvar_VariableValue;
+ uiInfo.uiDC.drawTextWithCursor = &Text_PaintWithCursor;
+ uiInfo.uiDC.setOverstrikeMode = &trap_Key_SetOverstrikeMode;
+ uiInfo.uiDC.getOverstrikeMode = &trap_Key_GetOverstrikeMode;
+ uiInfo.uiDC.startLocalSound = &trap_S_StartLocalSound;
+ uiInfo.uiDC.ownerDrawHandleKey = &UI_OwnerDrawHandleKey;
+ uiInfo.uiDC.feederCount = &UI_FeederCount;
+ uiInfo.uiDC.feederItemImage = &UI_FeederItemImage;
+ uiInfo.uiDC.feederItemText = &UI_FeederItemText;
+ uiInfo.uiDC.feederSelection = &UI_FeederSelection;
+ uiInfo.uiDC.setBinding = &trap_Key_SetBinding;
+ uiInfo.uiDC.getBindingBuf = &trap_Key_GetBindingBuf;
+ uiInfo.uiDC.keynumToStringBuf = &trap_Key_KeynumToStringBuf;
+ uiInfo.uiDC.executeText = &trap_Cmd_ExecuteText;
+ uiInfo.uiDC.Error = &Com_Error;
+ uiInfo.uiDC.Print = &Com_Printf;
+ uiInfo.uiDC.Pause = &UI_Pause;
+ uiInfo.uiDC.ownerDrawWidth = &UI_OwnerDrawWidth;
+ uiInfo.uiDC.registerSound = &trap_S_RegisterSound;
+ uiInfo.uiDC.startBackgroundTrack = &trap_S_StartBackgroundTrack;
+ uiInfo.uiDC.stopBackgroundTrack = &trap_S_StopBackgroundTrack;
+ uiInfo.uiDC.playCinematic = &UI_PlayCinematic;
+ uiInfo.uiDC.stopCinematic = &UI_StopCinematic;
+ uiInfo.uiDC.drawCinematic = &UI_DrawCinematic;
+ uiInfo.uiDC.runCinematicFrame = &UI_RunCinematicFrame;
+
+ Init_Display(&uiInfo.uiDC);
+
+ String_Init();
+
+ uiInfo.uiDC.cursor = trap_R_RegisterShaderNoMip( "menu/art/3_cursor2" );
+ uiInfo.uiDC.whiteShader = trap_R_RegisterShaderNoMip( "white" );
+
+ AssetCache();
+
+ start = trap_Milliseconds();
+
+ uiInfo.teamCount = 0;
+ uiInfo.characterCount = 0;
+ uiInfo.aliasCount = 0;
+
+#ifdef PRE_RELEASE_TADEMO
+ UI_ParseTeamInfo("demoteaminfo.txt");
+ UI_ParseGameInfo("demogameinfo.txt");
+#else
+ UI_ParseTeamInfo("teaminfo.txt");
+ UI_LoadTeams();
+ UI_ParseGameInfo("gameinfo.txt");
+#endif
+
+ menuSet = UI_Cvar_VariableString("ui_menuFiles");
+ if (menuSet == NULL || menuSet[0] == '\0') {
+ menuSet = "ui/menus.txt";
+ }
+
+#if 0
+ if (uiInfo.inGameLoad) {
+ UI_LoadMenus("ui/ingame.txt", qtrue);
+ } else { // bk010222: left this: UI_LoadMenus(menuSet, qtrue);
+ }
+#else
+ UI_LoadMenus(menuSet, qtrue);
+ UI_LoadMenus("ui/ingame.txt", qfalse);
+#endif
+
+ Menus_CloseAll();
+
+ trap_LAN_LoadCachedServers();
+ UI_LoadBestScores(uiInfo.mapList[ui_currentMap.integer].mapLoadName, uiInfo.gameTypes[ui_gameType.integer].gtEnum);
+
+ UI_BuildQ3Model_List();
+ UI_LoadBots();
+
+ // sets defaults for ui temp cvars
+ uiInfo.effectsColor = gamecodetoui[(int)trap_Cvar_VariableValue("color1")-1];
+ uiInfo.currentCrosshair = (int)trap_Cvar_VariableValue("cg_drawCrosshair");
+ trap_Cvar_Set("ui_mousePitch", (trap_Cvar_VariableValue("m_pitch") >= 0) ? "0" : "1");
+
+ uiInfo.serverStatus.currentServerCinematic = -1;
+ uiInfo.previewMovie = -1;
+
+ if (trap_Cvar_VariableValue("ui_TeamArenaFirstRun") == 0) {
+ trap_Cvar_Set("s_volume", "0.8");
+ trap_Cvar_Set("s_musicvolume", "0.5");
+ trap_Cvar_Set("ui_TeamArenaFirstRun", "1");
+ }
+
+ trap_Cvar_Register(NULL, "debug_protocol", "", 0 );
+
+ trap_Cvar_Set("ui_actualNetGameType", va("%d", ui_netGameType.integer));
+}
+
+
+/*
+=================
+UI_KeyEvent
+=================
+*/
+void _UI_KeyEvent( int key, qboolean down ) {
+
+ if (Menu_Count() > 0) {
+ menuDef_t *menu = Menu_GetFocused();
+ if (menu) {
+ if (key == K_ESCAPE && down && !Menus_AnyFullScreenVisible()) {
+ Menus_CloseAll();
+ } else {
+ Menu_HandleKey(menu, key, down );
+ }
+ } else {
+ trap_Key_SetCatcher( trap_Key_GetCatcher() & ~KEYCATCH_UI );
+ trap_Key_ClearStates();
+ trap_Cvar_Set( "cl_paused", "0" );
+ }
+ }
+
+ //if ((s > 0) && (s != menu_null_sound)) {
+ // trap_S_StartLocalSound( s, CHAN_LOCAL_SOUND );
+ //}
+}
+
+/*
+=================
+UI_MouseEvent
+=================
+*/
+void _UI_MouseEvent( int dx, int dy )
+{
+ // update mouse screen position
+ uiInfo.uiDC.cursorx += dx;
+ if (uiInfo.uiDC.cursorx < 0)
+ uiInfo.uiDC.cursorx = 0;
+ else if (uiInfo.uiDC.cursorx > SCREEN_WIDTH)
+ uiInfo.uiDC.cursorx = SCREEN_WIDTH;
+
+ uiInfo.uiDC.cursory += dy;
+ if (uiInfo.uiDC.cursory < 0)
+ uiInfo.uiDC.cursory = 0;
+ else if (uiInfo.uiDC.cursory > SCREEN_HEIGHT)
+ uiInfo.uiDC.cursory = SCREEN_HEIGHT;
+
+ if (Menu_Count() > 0) {
+ //menuDef_t *menu = Menu_GetFocused();
+ //Menu_HandleMouseMove(menu, uiInfo.uiDC.cursorx, uiInfo.uiDC.cursory);
+ Display_MouseMove(NULL, uiInfo.uiDC.cursorx, uiInfo.uiDC.cursory);
+ }
+
+}
+
+void UI_LoadNonIngame() {
+ const char *menuSet = UI_Cvar_VariableString("ui_menuFiles");
+ if (menuSet == NULL || menuSet[0] == '\0') {
+ menuSet = "ui/menus.txt";
+ }
+ UI_LoadMenus(menuSet, qfalse);
+ uiInfo.inGameLoad = qfalse;
+}
+
+void _UI_SetActiveMenu( uiMenuCommand_t menu ) {
+ char buf[256];
+
+ // this should be the ONLY way the menu system is brought up
+ // enusure minumum menu data is cached
+ if (Menu_Count() > 0) {
+ vec3_t v;
+ v[0] = v[1] = v[2] = 0;
+ switch ( menu ) {
+ case UIMENU_NONE:
+ trap_Key_SetCatcher( trap_Key_GetCatcher() & ~KEYCATCH_UI );
+ trap_Key_ClearStates();
+ trap_Cvar_Set( "cl_paused", "0" );
+ Menus_CloseAll();
+
+ return;
+ case UIMENU_MAIN:
+ //trap_Cvar_Set( "sv_killserver", "1" );
+ trap_Key_SetCatcher( KEYCATCH_UI );
+ //trap_S_StartLocalSound( trap_S_RegisterSound("sound/misc/menu_background.wav", qfalse) , CHAN_LOCAL_SOUND );
+ //trap_S_StartBackgroundTrack("sound/misc/menu_background.wav", NULL);
+ if (uiInfo.inGameLoad) {
+ UI_LoadNonIngame();
+ }
+ Menus_CloseAll();
+ Menus_ActivateByName("main");
+ trap_Cvar_VariableStringBuffer("com_errorMessage", buf, sizeof(buf));
+ if (strlen(buf)) {
+ if (!ui_singlePlayerActive.integer) {
+ Menus_ActivateByName("error_popmenu");
+ } else {
+ trap_Cvar_Set("com_errorMessage", "");
+ }
+ }
+ return;
+ case UIMENU_TEAM:
+ trap_Key_SetCatcher( KEYCATCH_UI );
+ Menus_ActivateByName("team");
+ return;
+ case UIMENU_NEED_CD:
+ // no cd check in TA
+ //trap_Key_SetCatcher( KEYCATCH_UI );
+ //Menus_ActivateByName("needcd");
+ //UI_ConfirmMenu( "Insert the CD", NULL, NeedCDAction );
+ return;
+ case UIMENU_BAD_CD_KEY:
+ // no cd check in TA
+ //trap_Key_SetCatcher( KEYCATCH_UI );
+ //Menus_ActivateByName("badcd");
+ //UI_ConfirmMenu( "Bad CD Key", NULL, NeedCDKeyAction );
+ return;
+ case UIMENU_POSTGAME:
+ //trap_Cvar_Set( "sv_killserver", "1" );
+ trap_Key_SetCatcher( KEYCATCH_UI );
+ if (uiInfo.inGameLoad) {
+ UI_LoadNonIngame();
+ }
+ Menus_CloseAll();
+ Menus_ActivateByName("endofgame");
+ //UI_ConfirmMenu( "Bad CD Key", NULL, NeedCDKeyAction );
+ return;
+ case UIMENU_INGAME:
+ trap_Cvar_Set( "cl_paused", "1" );
+ trap_Key_SetCatcher( KEYCATCH_UI );
+ UI_BuildPlayerList();
+ Menus_CloseAll();
+ Menus_ActivateByName("ingame");
+ return;
+ }
+ }
+}
+
+qboolean _UI_IsFullscreen( void ) {
+ return Menus_AnyFullScreenVisible();
+}
+
+
+
+static connstate_t lastConnState;
+static char lastLoadingText[MAX_INFO_VALUE];
+
+static void UI_ReadableSize ( char *buf, int bufsize, int value )
+{
+ if (value > 1024*1024*1024 ) { // gigs
+ Com_sprintf( buf, bufsize, "%d", value / (1024*1024*1024) );
+ Com_sprintf( buf+strlen(buf), bufsize-strlen(buf), ".%02d GB",
+ (value % (1024*1024*1024))*100 / (1024*1024*1024) );
+ } else if (value > 1024*1024 ) { // megs
+ Com_sprintf( buf, bufsize, "%d", value / (1024*1024) );
+ Com_sprintf( buf+strlen(buf), bufsize-strlen(buf), ".%02d MB",
+ (value % (1024*1024))*100 / (1024*1024) );
+ } else if (value > 1024 ) { // kilos
+ Com_sprintf( buf, bufsize, "%d KB", value / 1024 );
+ } else { // bytes
+ Com_sprintf( buf, bufsize, "%d bytes", value );
+ }
+}
+
+// Assumes time is in msec
+static void UI_PrintTime ( char *buf, int bufsize, int time ) {
+ time /= 1000; // change to seconds
+
+ if (time > 3600) { // in the hours range
+ Com_sprintf( buf, bufsize, "%d hr %d min", time / 3600, (time % 3600) / 60 );
+ } else if (time > 60) { // mins
+ Com_sprintf( buf, bufsize, "%d min %d sec", time / 60, time % 60 );
+ } else { // secs
+ Com_sprintf( buf, bufsize, "%d sec", time );
+ }
+}
+
+void Text_PaintCenter(float x, float y, float scale, vec4_t color, const char *text, float adjust) {
+ int len = Text_Width(text, scale, 0);
+ Text_Paint(x - len / 2, y, scale, color, text, 0, 0, ITEM_TEXTSTYLE_SHADOWEDMORE);
+}
+
+void Text_PaintCenter_AutoWrapped(float x, float y, float xmax, float ystep, float scale, vec4_t color, const char *str, float adjust) {
+ int width;
+ char *s1,*s2,*s3;
+ char c_bcp;
+ char buf[1024];
+
+ if (!str || str[0]=='\0')
+ return;
+
+ Q_strncpyz(buf, str, sizeof(buf));
+ s1 = s2 = s3 = buf;
+
+ while (1) {
+ do {
+ s3++;
+ } while (*s3!=' ' && *s3!='\0');
+ c_bcp = *s3;
+ *s3 = '\0';
+ width = Text_Width(s1, scale, 0);
+ *s3 = c_bcp;
+ if (width > xmax) {
+ if (s1==s2)
+ {
+ // fuck, don't have a clean cut, we'll overflow
+ s2 = s3;
+ }
+ *s2 = '\0';
+ Text_PaintCenter(x, y, scale, color, s1, adjust);
+ y += ystep;
+ if (c_bcp == '\0')
+ {
+ // that was the last word
+ // we could start a new loop, but that wouldn't be much use
+ // even if the word is too long, we would overflow it (see above)
+ // so just print it now if needed
+ s2++;
+ if (*s2 != '\0') // if we are printing an overflowing line we have s2 == s3
+ Text_PaintCenter(x, y, scale, color, s2, adjust);
+ break;
+ }
+ s2++;
+ s1 = s2;
+ s3 = s2;
+ }
+ else
+ {
+ s2 = s3;
+ if (c_bcp == '\0') // we reached the end
+ {
+ Text_PaintCenter(x, y, scale, color, s1, adjust);
+ break;
+ }
+ }
+ }
+}
+
+static void UI_DisplayDownloadInfo( const char *downloadName, float centerPoint, float yStart, float scale ) {
+ static char dlText[] = "Downloading:";
+ static char etaText[] = "Estimated time left:";
+ static char xferText[] = "Transfer rate:";
+
+ int downloadSize, downloadCount, downloadTime;
+ char dlSizeBuf[64], totalSizeBuf[64], xferRateBuf[64], dlTimeBuf[64];
+ int xferRate;
+ int leftWidth;
+ const char *s;
+
+ downloadSize = trap_Cvar_VariableValue( "cl_downloadSize" );
+ downloadCount = trap_Cvar_VariableValue( "cl_downloadCount" );
+ downloadTime = trap_Cvar_VariableValue( "cl_downloadTime" );
+
+ leftWidth = 320;
+
+ UI_SetColor(colorWhite);
+ Text_PaintCenter(centerPoint, yStart + 112, scale, colorWhite, dlText, 0);
+ Text_PaintCenter(centerPoint, yStart + 192, scale, colorWhite, etaText, 0);
+ Text_PaintCenter(centerPoint, yStart + 248, scale, colorWhite, xferText, 0);
+
+ if (downloadSize > 0) {
+ s = va( "%s (%d%%)", downloadName, downloadCount * 100 / downloadSize );
+ } else {
+ s = downloadName;
+ }
+
+ Text_PaintCenter(centerPoint, yStart+136, scale, colorWhite, s, 0);
+
+ UI_ReadableSize( dlSizeBuf, sizeof dlSizeBuf, downloadCount );
+ UI_ReadableSize( totalSizeBuf, sizeof totalSizeBuf, downloadSize );
+
+ if (downloadCount < 4096 || !downloadTime) {
+ Text_PaintCenter(leftWidth, yStart+216, scale, colorWhite, "estimating", 0);
+ Text_PaintCenter(leftWidth, yStart+160, scale, colorWhite, va("(%s of %s copied)", dlSizeBuf, totalSizeBuf), 0);
+ } else {
+ if ((uiInfo.uiDC.realTime - downloadTime) / 1000) {
+ xferRate = downloadCount / ((uiInfo.uiDC.realTime - downloadTime) / 1000);
+ } else {
+ xferRate = 0;
+ }
+ UI_ReadableSize( xferRateBuf, sizeof xferRateBuf, xferRate );
+
+ // Extrapolate estimated completion time
+ if (downloadSize && xferRate) {
+ int n = downloadSize / xferRate; // estimated time for entire d/l in secs
+
+ // We do it in K (/1024) because we'd overflow around 4MB
+ UI_PrintTime ( dlTimeBuf, sizeof dlTimeBuf,
+ (n - (((downloadCount/1024) * n) / (downloadSize/1024))) * 1000);
+
+ Text_PaintCenter(leftWidth, yStart+216, scale, colorWhite, dlTimeBuf, 0);
+ Text_PaintCenter(leftWidth, yStart+160, scale, colorWhite, va("(%s of %s copied)", dlSizeBuf, totalSizeBuf), 0);
+ } else {
+ Text_PaintCenter(leftWidth, yStart+216, scale, colorWhite, "estimating", 0);
+ if (downloadSize) {
+ Text_PaintCenter(leftWidth, yStart+160, scale, colorWhite, va("(%s of %s copied)", dlSizeBuf, totalSizeBuf), 0);
+ } else {
+ Text_PaintCenter(leftWidth, yStart+160, scale, colorWhite, va("(%s copied)", dlSizeBuf), 0);
+ }
+ }
+
+ if (xferRate) {
+ Text_PaintCenter(leftWidth, yStart+272, scale, colorWhite, va("%s/Sec", xferRateBuf), 0);
+ }
+ }
+}
+
+/*
+========================
+UI_DrawConnectScreen
+
+This will also be overlaid on the cgame info screen during loading
+to prevent it from blinking away too rapidly on local or lan games.
+========================
+*/
+void UI_DrawConnectScreen( qboolean overlay ) {
+ char *s;
+ uiClientState_t cstate;
+ char info[MAX_INFO_VALUE];
+ char text[256];
+ float centerPoint, yStart, scale;
+
+ menuDef_t *menu = Menus_FindByName("Connect");
+
+
+ if ( !overlay && menu ) {
+ Menu_Paint(menu, qtrue);
+ }
+
+ if (!overlay) {
+ centerPoint = 320;
+ yStart = 130;
+ scale = 0.5f;
+ } else {
+ centerPoint = 320;
+ yStart = 32;
+ scale = 0.6f;
+ return;
+ }
+
+ // see what information we should display
+ trap_GetClientState( &cstate );
+
+ info[0] = '\0';
+ if( trap_GetConfigString( CS_SERVERINFO, info, sizeof(info) ) ) {
+ Text_PaintCenter(centerPoint, yStart, scale, colorWhite, va( "Loading %s", Info_ValueForKey( info, "mapname" )), 0);
+ }
+
+ if (!Q_stricmp(cstate.servername,"localhost")) {
+ Text_PaintCenter(centerPoint, yStart + 48, scale, colorWhite, va("Starting up..."), ITEM_TEXTSTYLE_SHADOWEDMORE);
+ } else {
+ strcpy(text, va("Connecting to %s", cstate.servername));
+ Text_PaintCenter(centerPoint, yStart + 48, scale, colorWhite,text , ITEM_TEXTSTYLE_SHADOWEDMORE);
+ }
+
+ // display global MOTD at bottom
+ Text_PaintCenter(centerPoint, 600, scale, colorWhite, Info_ValueForKey( cstate.updateInfoString, "motd" ), 0);
+ // print any server info (server full, bad version, etc)
+ if ( cstate.connState < CA_CONNECTED ) {
+ Text_PaintCenter_AutoWrapped(centerPoint, yStart + 176, 630, 20, scale, colorWhite, cstate.messageString, 0);
+ }
+
+ if ( lastConnState > cstate.connState ) {
+ lastLoadingText[0] = '\0';
+ }
+ lastConnState = cstate.connState;
+
+ switch ( cstate.connState ) {
+ case CA_CONNECTING:
+ s = va("Awaiting connection...%i", cstate.connectPacketCount);
+ break;
+ case CA_CHALLENGING:
+ s = va("Awaiting challenge...%i", cstate.connectPacketCount);
+ break;
+ case CA_CONNECTED: {
+ char downloadName[MAX_INFO_VALUE];
+
+ trap_Cvar_VariableStringBuffer( "cl_downloadName", downloadName, sizeof(downloadName) );
+ if (*downloadName) {
+ UI_DisplayDownloadInfo( downloadName, centerPoint, yStart, scale );
+ return;
+ }
+ }
+ s = "Awaiting gamestate...";
+ break;
+ case CA_LOADING:
+ return;
+ case CA_PRIMED:
+ return;
+ default:
+ return;
+ }
+
+
+ if (Q_stricmp(cstate.servername,"localhost")) {
+ Text_PaintCenter(centerPoint, yStart + 80, scale, colorWhite, s, 0);
+ }
+
+ // password required / connection rejected information goes here
+}
+
+
+/*
+================
+cvars
+================
+*/
+
+typedef struct {
+ vmCvar_t *vmCvar;
+ char *cvarName;
+ char *defaultString;
+ int cvarFlags;
+} cvarTable_t;
+
+vmCvar_t ui_ffa_fraglimit;
+vmCvar_t ui_ffa_timelimit;
+
+vmCvar_t ui_tourney_fraglimit;
+vmCvar_t ui_tourney_timelimit;
+
+vmCvar_t ui_team_fraglimit;
+vmCvar_t ui_team_timelimit;
+vmCvar_t ui_team_friendly;
+
+vmCvar_t ui_ctf_capturelimit;
+vmCvar_t ui_ctf_timelimit;
+vmCvar_t ui_ctf_friendly;
+
+vmCvar_t ui_arenasFile;
+vmCvar_t ui_botsFile;
+vmCvar_t ui_spScores1;
+vmCvar_t ui_spScores2;
+vmCvar_t ui_spScores3;
+vmCvar_t ui_spScores4;
+vmCvar_t ui_spScores5;
+vmCvar_t ui_spAwards;
+vmCvar_t ui_spVideos;
+vmCvar_t ui_spSkill;
+
+vmCvar_t ui_spSelection;
+
+vmCvar_t ui_browserMaster;
+vmCvar_t ui_browserGameType;
+vmCvar_t ui_browserSortKey;
+vmCvar_t ui_browserShowFull;
+vmCvar_t ui_browserShowEmpty;
+
+vmCvar_t ui_brassTime;
+vmCvar_t ui_drawCrosshair;
+vmCvar_t ui_drawCrosshairNames;
+vmCvar_t ui_marks;
+
+vmCvar_t ui_server1;
+vmCvar_t ui_server2;
+vmCvar_t ui_server3;
+vmCvar_t ui_server4;
+vmCvar_t ui_server5;
+vmCvar_t ui_server6;
+vmCvar_t ui_server7;
+vmCvar_t ui_server8;
+vmCvar_t ui_server9;
+vmCvar_t ui_server10;
+vmCvar_t ui_server11;
+vmCvar_t ui_server12;
+vmCvar_t ui_server13;
+vmCvar_t ui_server14;
+vmCvar_t ui_server15;
+vmCvar_t ui_server16;
+
+vmCvar_t ui_cdkeychecked;
+
+vmCvar_t ui_redteam;
+vmCvar_t ui_redteam1;
+vmCvar_t ui_redteam2;
+vmCvar_t ui_redteam3;
+vmCvar_t ui_redteam4;
+vmCvar_t ui_redteam5;
+vmCvar_t ui_blueteam;
+vmCvar_t ui_blueteam1;
+vmCvar_t ui_blueteam2;
+vmCvar_t ui_blueteam3;
+vmCvar_t ui_blueteam4;
+vmCvar_t ui_blueteam5;
+vmCvar_t ui_teamName;
+vmCvar_t ui_dedicated;
+vmCvar_t ui_gameType;
+vmCvar_t ui_netGameType;
+vmCvar_t ui_actualNetGameType;
+vmCvar_t ui_joinGameType;
+vmCvar_t ui_netSource;
+vmCvar_t ui_serverFilterType;
+vmCvar_t ui_opponentName;
+vmCvar_t ui_menuFiles;
+vmCvar_t ui_currentTier;
+vmCvar_t ui_currentMap;
+vmCvar_t ui_currentNetMap;
+vmCvar_t ui_mapIndex;
+vmCvar_t ui_currentOpponent;
+vmCvar_t ui_selectedPlayer;
+vmCvar_t ui_selectedPlayerName;
+vmCvar_t ui_lastServerRefresh_0;
+vmCvar_t ui_lastServerRefresh_1;
+vmCvar_t ui_lastServerRefresh_2;
+vmCvar_t ui_lastServerRefresh_3;
+vmCvar_t ui_singlePlayerActive;
+vmCvar_t ui_scoreAccuracy;
+vmCvar_t ui_scoreImpressives;
+vmCvar_t ui_scoreExcellents;
+vmCvar_t ui_scoreCaptures;
+vmCvar_t ui_scoreDefends;
+vmCvar_t ui_scoreAssists;
+vmCvar_t ui_scoreGauntlets;
+vmCvar_t ui_scoreScore;
+vmCvar_t ui_scorePerfect;
+vmCvar_t ui_scoreTeam;
+vmCvar_t ui_scoreBase;
+vmCvar_t ui_scoreTimeBonus;
+vmCvar_t ui_scoreSkillBonus;
+vmCvar_t ui_scoreShutoutBonus;
+vmCvar_t ui_scoreTime;
+vmCvar_t ui_captureLimit;
+vmCvar_t ui_fragLimit;
+vmCvar_t ui_smallFont;
+vmCvar_t ui_bigFont;
+vmCvar_t ui_findPlayer;
+vmCvar_t ui_Q3Model;
+vmCvar_t ui_hudFiles;
+vmCvar_t ui_recordSPDemo;
+vmCvar_t ui_realCaptureLimit;
+vmCvar_t ui_realWarmUp;
+vmCvar_t ui_serverStatusTimeOut;
+
+
+// bk001129 - made static to avoid aliasing
+static cvarTable_t cvarTable[] = {
+ { &ui_ffa_fraglimit, "ui_ffa_fraglimit", "20", CVAR_ARCHIVE },
+ { &ui_ffa_timelimit, "ui_ffa_timelimit", "0", CVAR_ARCHIVE },
+
+ { &ui_tourney_fraglimit, "ui_tourney_fraglimit", "0", CVAR_ARCHIVE },
+ { &ui_tourney_timelimit, "ui_tourney_timelimit", "15", CVAR_ARCHIVE },
+
+ { &ui_team_fraglimit, "ui_team_fraglimit", "0", CVAR_ARCHIVE },
+ { &ui_team_timelimit, "ui_team_timelimit", "20", CVAR_ARCHIVE },
+ { &ui_team_friendly, "ui_team_friendly", "1", CVAR_ARCHIVE },
+
+ { &ui_ctf_capturelimit, "ui_ctf_capturelimit", "8", CVAR_ARCHIVE },
+ { &ui_ctf_timelimit, "ui_ctf_timelimit", "30", CVAR_ARCHIVE },
+ { &ui_ctf_friendly, "ui_ctf_friendly", "0", CVAR_ARCHIVE },
+
+ { &ui_arenasFile, "g_arenasFile", "", CVAR_INIT|CVAR_ROM },
+ { &ui_botsFile, "g_botsFile", "", CVAR_INIT|CVAR_ROM },
+ { &ui_spScores1, "g_spScores1", "", CVAR_ARCHIVE | CVAR_ROM },
+ { &ui_spScores2, "g_spScores2", "", CVAR_ARCHIVE | CVAR_ROM },
+ { &ui_spScores3, "g_spScores3", "", CVAR_ARCHIVE | CVAR_ROM },
+ { &ui_spScores4, "g_spScores4", "", CVAR_ARCHIVE | CVAR_ROM },
+ { &ui_spScores5, "g_spScores5", "", CVAR_ARCHIVE | CVAR_ROM },
+ { &ui_spAwards, "g_spAwards", "", CVAR_ARCHIVE | CVAR_ROM },
+ { &ui_spVideos, "g_spVideos", "", CVAR_ARCHIVE | CVAR_ROM },
+ { &ui_spSkill, "g_spSkill", "2", CVAR_ARCHIVE },
+
+ { &ui_spSelection, "ui_spSelection", "", CVAR_ROM },
+
+ { &ui_browserMaster, "ui_browserMaster", "0", CVAR_ARCHIVE },
+ { &ui_browserGameType, "ui_browserGameType", "0", CVAR_ARCHIVE },
+ { &ui_browserSortKey, "ui_browserSortKey", "4", CVAR_ARCHIVE },
+ { &ui_browserShowFull, "ui_browserShowFull", "1", CVAR_ARCHIVE },
+ { &ui_browserShowEmpty, "ui_browserShowEmpty", "1", CVAR_ARCHIVE },
+
+ { &ui_brassTime, "cg_brassTime", "2500", CVAR_ARCHIVE },
+ { &ui_drawCrosshair, "cg_drawCrosshair", "4", CVAR_ARCHIVE },
+ { &ui_drawCrosshairNames, "cg_drawCrosshairNames", "1", CVAR_ARCHIVE },
+ { &ui_marks, "cg_marks", "1", CVAR_ARCHIVE },
+
+ { &ui_server1, "server1", "", CVAR_ARCHIVE },
+ { &ui_server2, "server2", "", CVAR_ARCHIVE },
+ { &ui_server3, "server3", "", CVAR_ARCHIVE },
+ { &ui_server4, "server4", "", CVAR_ARCHIVE },
+ { &ui_server5, "server5", "", CVAR_ARCHIVE },
+ { &ui_server6, "server6", "", CVAR_ARCHIVE },
+ { &ui_server7, "server7", "", CVAR_ARCHIVE },
+ { &ui_server8, "server8", "", CVAR_ARCHIVE },
+ { &ui_server9, "server9", "", CVAR_ARCHIVE },
+ { &ui_server10, "server10", "", CVAR_ARCHIVE },
+ { &ui_server11, "server11", "", CVAR_ARCHIVE },
+ { &ui_server12, "server12", "", CVAR_ARCHIVE },
+ { &ui_server13, "server13", "", CVAR_ARCHIVE },
+ { &ui_server14, "server14", "", CVAR_ARCHIVE },
+ { &ui_server15, "server15", "", CVAR_ARCHIVE },
+ { &ui_server16, "server16", "", CVAR_ARCHIVE },
+ { &ui_cdkeychecked, "ui_cdkeychecked", "0", CVAR_ROM },
+ { &ui_new, "ui_new", "0", CVAR_TEMP },
+ { &ui_debug, "ui_debug", "0", CVAR_TEMP },
+ { &ui_initialized, "ui_initialized", "0", CVAR_TEMP },
+ { &ui_teamName, "ui_teamName", "Pagans", CVAR_ARCHIVE },
+ { &ui_opponentName, "ui_opponentName", "Stroggs", CVAR_ARCHIVE },
+ { &ui_redteam, "ui_redteam", "Pagans", CVAR_ARCHIVE },
+ { &ui_blueteam, "ui_blueteam", "Stroggs", CVAR_ARCHIVE },
+ { &ui_dedicated, "ui_dedicated", "0", CVAR_ARCHIVE },
+ { &ui_gameType, "ui_gametype", "3", CVAR_ARCHIVE },
+ { &ui_joinGameType, "ui_joinGametype", "0", CVAR_ARCHIVE },
+ { &ui_netGameType, "ui_netGametype", "3", CVAR_ARCHIVE },
+ { &ui_actualNetGameType, "ui_actualNetGametype", "3", CVAR_ARCHIVE },
+ { &ui_redteam1, "ui_redteam1", "0", CVAR_ARCHIVE },
+ { &ui_redteam2, "ui_redteam2", "0", CVAR_ARCHIVE },
+ { &ui_redteam3, "ui_redteam3", "0", CVAR_ARCHIVE },
+ { &ui_redteam4, "ui_redteam4", "0", CVAR_ARCHIVE },
+ { &ui_redteam5, "ui_redteam5", "0", CVAR_ARCHIVE },
+ { &ui_blueteam1, "ui_blueteam1", "0", CVAR_ARCHIVE },
+ { &ui_blueteam2, "ui_blueteam2", "0", CVAR_ARCHIVE },
+ { &ui_blueteam3, "ui_blueteam3", "0", CVAR_ARCHIVE },
+ { &ui_blueteam4, "ui_blueteam4", "0", CVAR_ARCHIVE },
+ { &ui_blueteam5, "ui_blueteam5", "0", CVAR_ARCHIVE },
+ { &ui_netSource, "ui_netSource", "0", CVAR_ARCHIVE },
+ { &ui_menuFiles, "ui_menuFiles", "ui/menus.txt", CVAR_ARCHIVE },
+ { &ui_currentTier, "ui_currentTier", "0", CVAR_ARCHIVE },
+ { &ui_currentMap, "ui_currentMap", "0", CVAR_ARCHIVE },
+ { &ui_currentNetMap, "ui_currentNetMap", "0", CVAR_ARCHIVE },
+ { &ui_mapIndex, "ui_mapIndex", "0", CVAR_ARCHIVE },
+ { &ui_currentOpponent, "ui_currentOpponent", "0", CVAR_ARCHIVE },
+ { &ui_selectedPlayer, "cg_selectedPlayer", "0", CVAR_ARCHIVE},
+ { &ui_selectedPlayerName, "cg_selectedPlayerName", "", CVAR_ARCHIVE},
+ { &ui_lastServerRefresh_0, "ui_lastServerRefresh_0", "", CVAR_ARCHIVE},
+ { &ui_lastServerRefresh_1, "ui_lastServerRefresh_1", "", CVAR_ARCHIVE},
+ { &ui_lastServerRefresh_2, "ui_lastServerRefresh_2", "", CVAR_ARCHIVE},
+ { &ui_lastServerRefresh_3, "ui_lastServerRefresh_3", "", CVAR_ARCHIVE},
+ { &ui_singlePlayerActive, "ui_singlePlayerActive", "0", 0},
+ { &ui_scoreAccuracy, "ui_scoreAccuracy", "0", CVAR_ARCHIVE},
+ { &ui_scoreImpressives, "ui_scoreImpressives", "0", CVAR_ARCHIVE},
+ { &ui_scoreExcellents, "ui_scoreExcellents", "0", CVAR_ARCHIVE},
+ { &ui_scoreCaptures, "ui_scoreCaptures", "0", CVAR_ARCHIVE},
+ { &ui_scoreDefends, "ui_scoreDefends", "0", CVAR_ARCHIVE},
+ { &ui_scoreAssists, "ui_scoreAssists", "0", CVAR_ARCHIVE},
+ { &ui_scoreGauntlets, "ui_scoreGauntlets", "0",CVAR_ARCHIVE},
+ { &ui_scoreScore, "ui_scoreScore", "0", CVAR_ARCHIVE},
+ { &ui_scorePerfect, "ui_scorePerfect", "0", CVAR_ARCHIVE},
+ { &ui_scoreTeam, "ui_scoreTeam", "0 to 0", CVAR_ARCHIVE},
+ { &ui_scoreBase, "ui_scoreBase", "0", CVAR_ARCHIVE},
+ { &ui_scoreTime, "ui_scoreTime", "00:00", CVAR_ARCHIVE},
+ { &ui_scoreTimeBonus, "ui_scoreTimeBonus", "0", CVAR_ARCHIVE},
+ { &ui_scoreSkillBonus, "ui_scoreSkillBonus", "0", CVAR_ARCHIVE},
+ { &ui_scoreShutoutBonus, "ui_scoreShutoutBonus", "0", CVAR_ARCHIVE},
+ { &ui_fragLimit, "ui_fragLimit", "10", 0},
+ { &ui_captureLimit, "ui_captureLimit", "5", 0},
+ { &ui_smallFont, "ui_smallFont", "0.25", CVAR_ARCHIVE},
+ { &ui_bigFont, "ui_bigFont", "0.4", CVAR_ARCHIVE},
+ { &ui_findPlayer, "ui_findPlayer", "Sarge", CVAR_ARCHIVE},
+ { &ui_Q3Model, "ui_q3model", "0", CVAR_ARCHIVE},
+ { &ui_hudFiles, "cg_hudFiles", "ui/hud.txt", CVAR_ARCHIVE},
+ { &ui_recordSPDemo, "ui_recordSPDemo", "0", CVAR_ARCHIVE},
+ { &ui_teamArenaFirstRun, "ui_teamArenaFirstRun", "0", CVAR_ARCHIVE},
+ { &ui_realWarmUp, "g_warmup", "20", CVAR_ARCHIVE},
+ { &ui_realCaptureLimit, "capturelimit", "8", CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_NORESTART},
+ { &ui_serverStatusTimeOut, "ui_serverStatusTimeOut", "7000", CVAR_ARCHIVE},
+
+};
+
+// bk001129 - made static to avoid aliasing
+static int cvarTableSize = sizeof(cvarTable) / sizeof(cvarTable[0]);
+
+
+/*
+=================
+UI_RegisterCvars
+=================
+*/
+void UI_RegisterCvars( void ) {
+ int i;
+ cvarTable_t *cv;
+
+ for ( i = 0, cv = cvarTable ; i < cvarTableSize ; i++, cv++ ) {
+ trap_Cvar_Register( cv->vmCvar, cv->cvarName, cv->defaultString, cv->cvarFlags );
+ }
+}
+
+/*
+=================
+UI_UpdateCvars
+=================
+*/
+void UI_UpdateCvars( void ) {
+ int i;
+ cvarTable_t *cv;
+
+ for ( i = 0, cv = cvarTable ; i < cvarTableSize ; i++, cv++ ) {
+ trap_Cvar_Update( cv->vmCvar );
+ }
+}
+
+
+/*
+=================
+ArenaServers_StopRefresh
+=================
+*/
+static void UI_StopServerRefresh( void )
+{
+ int count;
+
+ if (!uiInfo.serverStatus.refreshActive) {
+ // not currently refreshing
+ return;
+ }
+ uiInfo.serverStatus.refreshActive = qfalse;
+ Com_Printf("%d servers listed in browser with %d players.\n",
+ uiInfo.serverStatus.numDisplayServers,
+ uiInfo.serverStatus.numPlayersOnServers);
+ count = trap_LAN_GetServerCount(ui_netSource.integer);
+ if (count - uiInfo.serverStatus.numDisplayServers > 0) {
+ Com_Printf("%d servers not listed due to packet loss or pings higher than %d\n",
+ count - uiInfo.serverStatus.numDisplayServers,
+ (int) trap_Cvar_VariableValue("cl_maxPing"));
+ }
+
+}
+
+/*
+=================
+ArenaServers_MaxPing
+=================
+*/
+#ifndef MISSIONPACK // bk001206
+static int ArenaServers_MaxPing( void ) {
+ int maxPing;
+
+ maxPing = (int)trap_Cvar_VariableValue( "cl_maxPing" );
+ if( maxPing < 100 ) {
+ maxPing = 100;
+ }
+ return maxPing;
+}
+#endif
+
+/*
+=================
+UI_DoServerRefresh
+=================
+*/
+static void UI_DoServerRefresh( void )
+{
+ qboolean wait = qfalse;
+
+ if (!uiInfo.serverStatus.refreshActive) {
+ return;
+ }
+ if (ui_netSource.integer != AS_FAVORITES) {
+ if (ui_netSource.integer == AS_LOCAL) {
+ if (!trap_LAN_GetServerCount(ui_netSource.integer)) {
+ wait = qtrue;
+ }
+ } else {
+ if (trap_LAN_GetServerCount(ui_netSource.integer) < 0) {
+ wait = qtrue;
+ }
+ }
+ }
+
+ if (uiInfo.uiDC.realTime < uiInfo.serverStatus.refreshtime) {
+ if (wait) {
+ return;
+ }
+ }
+
+ // if still trying to retrieve pings
+ if (trap_LAN_UpdateVisiblePings(ui_netSource.integer)) {
+ uiInfo.serverStatus.refreshtime = uiInfo.uiDC.realTime + 1000;
+ } else if (!wait) {
+ // get the last servers in the list
+ UI_BuildServerDisplayList(2);
+ // stop the refresh
+ UI_StopServerRefresh();
+ }
+ //
+ UI_BuildServerDisplayList(qfalse);
+}
+
+/*
+=================
+UI_StartServerRefresh
+=================
+*/
+static void UI_StartServerRefresh(qboolean full)
+{
+ int i;
+ char *ptr;
+
+ qtime_t q;
+ trap_RealTime(&q);
+ trap_Cvar_Set( va("ui_lastServerRefresh_%i", ui_netSource.integer), va("%s-%i, %i at %i:%i", MonthAbbrev[q.tm_mon],q.tm_mday, 1900+q.tm_year,q.tm_hour,q.tm_min));
+
+ if (!full) {
+ UI_UpdatePendingPings();
+ return;
+ }
+
+ uiInfo.serverStatus.refreshActive = qtrue;
+ uiInfo.serverStatus.nextDisplayRefresh = uiInfo.uiDC.realTime + 1000;
+ // clear number of displayed servers
+ uiInfo.serverStatus.numDisplayServers = 0;
+ uiInfo.serverStatus.numPlayersOnServers = 0;
+ // mark all servers as visible so we store ping updates for them
+ trap_LAN_MarkServerVisible(ui_netSource.integer, -1, qtrue);
+ // reset all the pings
+ trap_LAN_ResetPings(ui_netSource.integer);
+ //
+ if( ui_netSource.integer == AS_LOCAL ) {
+ trap_Cmd_ExecuteText( EXEC_NOW, "localservers\n" );
+ uiInfo.serverStatus.refreshtime = uiInfo.uiDC.realTime + 1000;
+ return;
+ }
+
+ uiInfo.serverStatus.refreshtime = uiInfo.uiDC.realTime + 5000;
+ if( ui_netSource.integer == AS_GLOBAL || ui_netSource.integer == AS_MPLAYER ) {
+ if( ui_netSource.integer == AS_GLOBAL ) {
+ i = 0;
+ }
+ else {
+ i = 1;
+ }
+
+ ptr = UI_Cvar_VariableString("debug_protocol");
+ if (strlen(ptr)) {
+ trap_Cmd_ExecuteText( EXEC_NOW, va( "globalservers %d %s full empty\n", i, ptr));
+ }
+ else {
+ trap_Cmd_ExecuteText( EXEC_NOW, va( "globalservers %d %d full empty\n", i, (int)trap_Cvar_VariableValue( "protocol" ) ) );
+ }
+ }
+}
+
diff --git a/code/ui/ui_players.c b/code/ui/ui_players.c
new file mode 100755
index 0000000..2da5397
--- /dev/null
+++ b/code/ui/ui_players.c
@@ -0,0 +1,1378 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// ui_players.c
+
+#include "ui_local.h"
+
+
+#define UI_TIMER_GESTURE 2300
+#define UI_TIMER_JUMP 1000
+#define UI_TIMER_LAND 130
+#define UI_TIMER_WEAPON_SWITCH 300
+#define UI_TIMER_ATTACK 500
+#define UI_TIMER_MUZZLE_FLASH 20
+#define UI_TIMER_WEAPON_DELAY 250
+
+#define JUMP_HEIGHT 56
+
+#define SWINGSPEED 0.3f
+
+#define SPIN_SPEED 0.9f
+#define COAST_TIME 1000
+
+
+static int dp_realtime;
+static float jumpHeight;
+sfxHandle_t weaponChangeSound;
+
+
+/*
+===============
+UI_PlayerInfo_SetWeapon
+===============
+*/
+static void UI_PlayerInfo_SetWeapon( playerInfo_t *pi, weapon_t weaponNum ) {
+ gitem_t * item;
+ char path[MAX_QPATH];
+
+ pi->currentWeapon = weaponNum;
+tryagain:
+ pi->realWeapon = weaponNum;
+ pi->weaponModel = 0;
+ pi->barrelModel = 0;
+ pi->flashModel = 0;
+
+ if ( weaponNum == WP_NONE ) {
+ return;
+ }
+
+ for ( item = bg_itemlist + 1; item->classname ; item++ ) {
+ if ( item->giType != IT_WEAPON ) {
+ continue;
+ }
+ if ( item->giTag == weaponNum ) {
+ break;
+ }
+ }
+
+ if ( item->classname ) {
+ pi->weaponModel = trap_R_RegisterModel( item->world_model[0] );
+ }
+
+ if( pi->weaponModel == 0 ) {
+ if( weaponNum == WP_MACHINEGUN ) {
+ weaponNum = WP_NONE;
+ goto tryagain;
+ }
+ weaponNum = WP_MACHINEGUN;
+ goto tryagain;
+ }
+
+ if ( weaponNum == WP_MACHINEGUN || weaponNum == WP_GAUNTLET || weaponNum == WP_BFG ) {
+ strcpy( path, item->world_model[0] );
+ COM_StripExtension( path, path );
+ strcat( path, "_barrel.md3" );
+ pi->barrelModel = trap_R_RegisterModel( path );
+ }
+
+ strcpy( path, item->world_model[0] );
+ COM_StripExtension( path, path );
+ strcat( path, "_flash.md3" );
+ pi->flashModel = trap_R_RegisterModel( path );
+
+ switch( weaponNum ) {
+ case WP_GAUNTLET:
+ MAKERGB( pi->flashDlightColor, 0.6f, 0.6f, 1 );
+ break;
+
+ case WP_MACHINEGUN:
+ MAKERGB( pi->flashDlightColor, 1, 1, 0 );
+ break;
+
+ case WP_SHOTGUN:
+ MAKERGB( pi->flashDlightColor, 1, 1, 0 );
+ break;
+
+ case WP_GRENADE_LAUNCHER:
+ MAKERGB( pi->flashDlightColor, 1, 0.7f, 0.5f );
+ break;
+
+ case WP_ROCKET_LAUNCHER:
+ MAKERGB( pi->flashDlightColor, 1, 0.75f, 0 );
+ break;
+
+ case WP_LIGHTNING:
+ MAKERGB( pi->flashDlightColor, 0.6f, 0.6f, 1 );
+ break;
+
+ case WP_RAILGUN:
+ MAKERGB( pi->flashDlightColor, 1, 0.5f, 0 );
+ break;
+
+ case WP_PLASMAGUN:
+ MAKERGB( pi->flashDlightColor, 0.6f, 0.6f, 1 );
+ break;
+
+ case WP_BFG:
+ MAKERGB( pi->flashDlightColor, 1, 0.7f, 1 );
+ break;
+
+ case WP_GRAPPLING_HOOK:
+ MAKERGB( pi->flashDlightColor, 0.6f, 0.6f, 1 );
+ break;
+
+ default:
+ MAKERGB( pi->flashDlightColor, 1, 1, 1 );
+ break;
+ }
+}
+
+
+/*
+===============
+UI_ForceLegsAnim
+===============
+*/
+static void UI_ForceLegsAnim( playerInfo_t *pi, int anim ) {
+ pi->legsAnim = ( ( pi->legsAnim & ANIM_TOGGLEBIT ) ^ ANIM_TOGGLEBIT ) | anim;
+
+ if ( anim == LEGS_JUMP ) {
+ pi->legsAnimationTimer = UI_TIMER_JUMP;
+ }
+}
+
+
+/*
+===============
+UI_SetLegsAnim
+===============
+*/
+static void UI_SetLegsAnim( playerInfo_t *pi, int anim ) {
+ if ( pi->pendingLegsAnim ) {
+ anim = pi->pendingLegsAnim;
+ pi->pendingLegsAnim = 0;
+ }
+ UI_ForceLegsAnim( pi, anim );
+}
+
+
+/*
+===============
+UI_ForceTorsoAnim
+===============
+*/
+static void UI_ForceTorsoAnim( playerInfo_t *pi, int anim ) {
+ pi->torsoAnim = ( ( pi->torsoAnim & ANIM_TOGGLEBIT ) ^ ANIM_TOGGLEBIT ) | anim;
+
+ if ( anim == TORSO_GESTURE ) {
+ pi->torsoAnimationTimer = UI_TIMER_GESTURE;
+ }
+
+ if ( anim == TORSO_ATTACK || anim == TORSO_ATTACK2 ) {
+ pi->torsoAnimationTimer = UI_TIMER_ATTACK;
+ }
+}
+
+
+/*
+===============
+UI_SetTorsoAnim
+===============
+*/
+static void UI_SetTorsoAnim( playerInfo_t *pi, int anim ) {
+ if ( pi->pendingTorsoAnim ) {
+ anim = pi->pendingTorsoAnim;
+ pi->pendingTorsoAnim = 0;
+ }
+
+ UI_ForceTorsoAnim( pi, anim );
+}
+
+
+/*
+===============
+UI_TorsoSequencing
+===============
+*/
+static void UI_TorsoSequencing( playerInfo_t *pi ) {
+ int currentAnim;
+
+ currentAnim = pi->torsoAnim & ~ANIM_TOGGLEBIT;
+
+ if ( pi->weapon != pi->currentWeapon ) {
+ if ( currentAnim != TORSO_DROP ) {
+ pi->torsoAnimationTimer = UI_TIMER_WEAPON_SWITCH;
+ UI_ForceTorsoAnim( pi, TORSO_DROP );
+ }
+ }
+
+ if ( pi->torsoAnimationTimer > 0 ) {
+ return;
+ }
+
+ if( currentAnim == TORSO_GESTURE ) {
+ UI_SetTorsoAnim( pi, TORSO_STAND );
+ return;
+ }
+
+ if( currentAnim == TORSO_ATTACK || currentAnim == TORSO_ATTACK2 ) {
+ UI_SetTorsoAnim( pi, TORSO_STAND );
+ return;
+ }
+
+ if ( currentAnim == TORSO_DROP ) {
+ UI_PlayerInfo_SetWeapon( pi, pi->weapon );
+ pi->torsoAnimationTimer = UI_TIMER_WEAPON_SWITCH;
+ UI_ForceTorsoAnim( pi, TORSO_RAISE );
+ return;
+ }
+
+ if ( currentAnim == TORSO_RAISE ) {
+ UI_SetTorsoAnim( pi, TORSO_STAND );
+ return;
+ }
+}
+
+
+/*
+===============
+UI_LegsSequencing
+===============
+*/
+static void UI_LegsSequencing( playerInfo_t *pi ) {
+ int currentAnim;
+
+ currentAnim = pi->legsAnim & ~ANIM_TOGGLEBIT;
+
+ if ( pi->legsAnimationTimer > 0 ) {
+ if ( currentAnim == LEGS_JUMP ) {
+ jumpHeight = JUMP_HEIGHT * sin( M_PI * ( UI_TIMER_JUMP - pi->legsAnimationTimer ) / UI_TIMER_JUMP );
+ }
+ return;
+ }
+
+ if ( currentAnim == LEGS_JUMP ) {
+ UI_ForceLegsAnim( pi, LEGS_LAND );
+ pi->legsAnimationTimer = UI_TIMER_LAND;
+ jumpHeight = 0;
+ return;
+ }
+
+ if ( currentAnim == LEGS_LAND ) {
+ UI_SetLegsAnim( pi, LEGS_IDLE );
+ return;
+ }
+}
+
+
+/*
+======================
+UI_PositionEntityOnTag
+======================
+*/
+static void UI_PositionEntityOnTag( refEntity_t *entity, const refEntity_t *parent,
+ clipHandle_t parentModel, char *tagName ) {
+ int i;
+ orientation_t lerped;
+
+ // lerp the tag
+ trap_CM_LerpTag( &lerped, parentModel, parent->oldframe, parent->frame,
+ 1.0 - parent->backlerp, tagName );
+
+ // FIXME: allow origin offsets along tag?
+ VectorCopy( parent->origin, entity->origin );
+ for ( i = 0 ; i < 3 ; i++ ) {
+ VectorMA( entity->origin, lerped.origin[i], parent->axis[i], entity->origin );
+ }
+
+ // cast away const because of compiler problems
+ MatrixMultiply( lerped.axis, ((refEntity_t*)parent)->axis, entity->axis );
+ entity->backlerp = parent->backlerp;
+}
+
+
+/*
+======================
+UI_PositionRotatedEntityOnTag
+======================
+*/
+static void UI_PositionRotatedEntityOnTag( refEntity_t *entity, const refEntity_t *parent,
+ clipHandle_t parentModel, char *tagName ) {
+ int i;
+ orientation_t lerped;
+ vec3_t tempAxis[3];
+
+ // lerp the tag
+ trap_CM_LerpTag( &lerped, parentModel, parent->oldframe, parent->frame,
+ 1.0 - parent->backlerp, tagName );
+
+ // FIXME: allow origin offsets along tag?
+ VectorCopy( parent->origin, entity->origin );
+ for ( i = 0 ; i < 3 ; i++ ) {
+ VectorMA( entity->origin, lerped.origin[i], parent->axis[i], entity->origin );
+ }
+
+ // cast away const because of compiler problems
+ MatrixMultiply( entity->axis, ((refEntity_t *)parent)->axis, tempAxis );
+ MatrixMultiply( lerped.axis, tempAxis, entity->axis );
+}
+
+
+/*
+===============
+UI_SetLerpFrameAnimation
+===============
+*/
+static void UI_SetLerpFrameAnimation( playerInfo_t *ci, lerpFrame_t *lf, int newAnimation ) {
+ animation_t *anim;
+
+ lf->animationNumber = newAnimation;
+ newAnimation &= ~ANIM_TOGGLEBIT;
+
+ if ( newAnimation < 0 || newAnimation >= MAX_ANIMATIONS ) {
+ trap_Error( va("Bad animation number: %i", newAnimation) );
+ }
+
+ anim = &ci->animations[ newAnimation ];
+
+ lf->animation = anim;
+ lf->animationTime = lf->frameTime + anim->initialLerp;
+}
+
+
+/*
+===============
+UI_RunLerpFrame
+===============
+*/
+static void UI_RunLerpFrame( playerInfo_t *ci, lerpFrame_t *lf, int newAnimation ) {
+ int f;
+ animation_t *anim;
+
+ // see if the animation sequence is switching
+ if ( newAnimation != lf->animationNumber || !lf->animation ) {
+ UI_SetLerpFrameAnimation( ci, lf, newAnimation );
+ }
+
+ // if we have passed the current frame, move it to
+ // oldFrame and calculate a new frame
+ if ( dp_realtime >= lf->frameTime ) {
+ lf->oldFrame = lf->frame;
+ lf->oldFrameTime = lf->frameTime;
+
+ // get the next frame based on the animation
+ anim = lf->animation;
+ if ( dp_realtime < lf->animationTime ) {
+ lf->frameTime = lf->animationTime; // initial lerp
+ } else {
+ lf->frameTime = lf->oldFrameTime + anim->frameLerp;
+ }
+ f = ( lf->frameTime - lf->animationTime ) / anim->frameLerp;
+ if ( f >= anim->numFrames ) {
+ f -= anim->numFrames;
+ if ( anim->loopFrames ) {
+ f %= anim->loopFrames;
+ f += anim->numFrames - anim->loopFrames;
+ } else {
+ f = anim->numFrames - 1;
+ // the animation is stuck at the end, so it
+ // can immediately transition to another sequence
+ lf->frameTime = dp_realtime;
+ }
+ }
+ lf->frame = anim->firstFrame + f;
+ if ( dp_realtime > lf->frameTime ) {
+ lf->frameTime = dp_realtime;
+ }
+ }
+
+ if ( lf->frameTime > dp_realtime + 200 ) {
+ lf->frameTime = dp_realtime;
+ }
+
+ if ( lf->oldFrameTime > dp_realtime ) {
+ lf->oldFrameTime = dp_realtime;
+ }
+ // calculate current lerp value
+ if ( lf->frameTime == lf->oldFrameTime ) {
+ lf->backlerp = 0;
+ } else {
+ lf->backlerp = 1.0 - (float)( dp_realtime - lf->oldFrameTime ) / ( lf->frameTime - lf->oldFrameTime );
+ }
+}
+
+
+/*
+===============
+UI_PlayerAnimation
+===============
+*/
+static void UI_PlayerAnimation( playerInfo_t *pi, int *legsOld, int *legs, float *legsBackLerp,
+ int *torsoOld, int *torso, float *torsoBackLerp ) {
+
+ // legs animation
+ pi->legsAnimationTimer -= uiInfo.uiDC.frameTime;
+ if ( pi->legsAnimationTimer < 0 ) {
+ pi->legsAnimationTimer = 0;
+ }
+
+ UI_LegsSequencing( pi );
+
+ if ( pi->legs.yawing && ( pi->legsAnim & ~ANIM_TOGGLEBIT ) == LEGS_IDLE ) {
+ UI_RunLerpFrame( pi, &pi->legs, LEGS_TURN );
+ } else {
+ UI_RunLerpFrame( pi, &pi->legs, pi->legsAnim );
+ }
+ *legsOld = pi->legs.oldFrame;
+ *legs = pi->legs.frame;
+ *legsBackLerp = pi->legs.backlerp;
+
+ // torso animation
+ pi->torsoAnimationTimer -= uiInfo.uiDC.frameTime;
+ if ( pi->torsoAnimationTimer < 0 ) {
+ pi->torsoAnimationTimer = 0;
+ }
+
+ UI_TorsoSequencing( pi );
+
+ UI_RunLerpFrame( pi, &pi->torso, pi->torsoAnim );
+ *torsoOld = pi->torso.oldFrame;
+ *torso = pi->torso.frame;
+ *torsoBackLerp = pi->torso.backlerp;
+}
+
+
+/*
+==================
+UI_SwingAngles
+==================
+*/
+static void UI_SwingAngles( float destination, float swingTolerance, float clampTolerance,
+ float speed, float *angle, qboolean *swinging ) {
+ float swing;
+ float move;
+ float scale;
+
+ if ( !*swinging ) {
+ // see if a swing should be started
+ swing = AngleSubtract( *angle, destination );
+ if ( swing > swingTolerance || swing < -swingTolerance ) {
+ *swinging = qtrue;
+ }
+ }
+
+ if ( !*swinging ) {
+ return;
+ }
+
+ // modify the speed depending on the delta
+ // so it doesn't seem so linear
+ swing = AngleSubtract( destination, *angle );
+ scale = fabs( swing );
+ if ( scale < swingTolerance * 0.5 ) {
+ scale = 0.5;
+ } else if ( scale < swingTolerance ) {
+ scale = 1.0;
+ } else {
+ scale = 2.0;
+ }
+
+ // swing towards the destination angle
+ if ( swing >= 0 ) {
+ move = uiInfo.uiDC.frameTime * scale * speed;
+ if ( move >= swing ) {
+ move = swing;
+ *swinging = qfalse;
+ }
+ *angle = AngleMod( *angle + move );
+ } else if ( swing < 0 ) {
+ move = uiInfo.uiDC.frameTime * scale * -speed;
+ if ( move <= swing ) {
+ move = swing;
+ *swinging = qfalse;
+ }
+ *angle = AngleMod( *angle + move );
+ }
+
+ // clamp to no more than tolerance
+ swing = AngleSubtract( destination, *angle );
+ if ( swing > clampTolerance ) {
+ *angle = AngleMod( destination - (clampTolerance - 1) );
+ } else if ( swing < -clampTolerance ) {
+ *angle = AngleMod( destination + (clampTolerance - 1) );
+ }
+}
+
+
+/*
+======================
+UI_MovedirAdjustment
+======================
+*/
+static float UI_MovedirAdjustment( playerInfo_t *pi ) {
+ vec3_t relativeAngles;
+ vec3_t moveVector;
+
+ VectorSubtract( pi->viewAngles, pi->moveAngles, relativeAngles );
+ AngleVectors( relativeAngles, moveVector, NULL, NULL );
+ if ( Q_fabs( moveVector[0] ) < 0.01 ) {
+ moveVector[0] = 0.0;
+ }
+ if ( Q_fabs( moveVector[1] ) < 0.01 ) {
+ moveVector[1] = 0.0;
+ }
+
+ if ( moveVector[1] == 0 && moveVector[0] > 0 ) {
+ return 0;
+ }
+ if ( moveVector[1] < 0 && moveVector[0] > 0 ) {
+ return 22;
+ }
+ if ( moveVector[1] < 0 && moveVector[0] == 0 ) {
+ return 45;
+ }
+ if ( moveVector[1] < 0 && moveVector[0] < 0 ) {
+ return -22;
+ }
+ if ( moveVector[1] == 0 && moveVector[0] < 0 ) {
+ return 0;
+ }
+ if ( moveVector[1] > 0 && moveVector[0] < 0 ) {
+ return 22;
+ }
+ if ( moveVector[1] > 0 && moveVector[0] == 0 ) {
+ return -45;
+ }
+
+ return -22;
+}
+
+
+/*
+===============
+UI_PlayerAngles
+===============
+*/
+static void UI_PlayerAngles( playerInfo_t *pi, vec3_t legs[3], vec3_t torso[3], vec3_t head[3] ) {
+ vec3_t legsAngles, torsoAngles, headAngles;
+ float dest;
+ float adjust;
+
+ VectorCopy( pi->viewAngles, headAngles );
+ headAngles[YAW] = AngleMod( headAngles[YAW] );
+ VectorClear( legsAngles );
+ VectorClear( torsoAngles );
+
+ // --------- yaw -------------
+
+ // allow yaw to drift a bit
+ if ( ( pi->legsAnim & ~ANIM_TOGGLEBIT ) != LEGS_IDLE
+ || ( pi->torsoAnim & ~ANIM_TOGGLEBIT ) != TORSO_STAND ) {
+ // if not standing still, always point all in the same direction
+ pi->torso.yawing = qtrue; // always center
+ pi->torso.pitching = qtrue; // always center
+ pi->legs.yawing = qtrue; // always center
+ }
+
+ // adjust legs for movement dir
+ adjust = UI_MovedirAdjustment( pi );
+ legsAngles[YAW] = headAngles[YAW] + adjust;
+ torsoAngles[YAW] = headAngles[YAW] + 0.25 * adjust;
+
+
+ // torso
+ UI_SwingAngles( torsoAngles[YAW], 25, 90, SWINGSPEED, &pi->torso.yawAngle, &pi->torso.yawing );
+ UI_SwingAngles( legsAngles[YAW], 40, 90, SWINGSPEED, &pi->legs.yawAngle, &pi->legs.yawing );
+
+ torsoAngles[YAW] = pi->torso.yawAngle;
+ legsAngles[YAW] = pi->legs.yawAngle;
+
+ // --------- pitch -------------
+
+ // only show a fraction of the pitch angle in the torso
+ if ( headAngles[PITCH] > 180 ) {
+ dest = (-360 + headAngles[PITCH]) * 0.75;
+ } else {
+ dest = headAngles[PITCH] * 0.75;
+ }
+ UI_SwingAngles( dest, 15, 30, 0.1f, &pi->torso.pitchAngle, &pi->torso.pitching );
+ torsoAngles[PITCH] = pi->torso.pitchAngle;
+
+ // pull the angles back out of the hierarchial chain
+ AnglesSubtract( headAngles, torsoAngles, headAngles );
+ AnglesSubtract( torsoAngles, legsAngles, torsoAngles );
+ AnglesToAxis( legsAngles, legs );
+ AnglesToAxis( torsoAngles, torso );
+ AnglesToAxis( headAngles, head );
+}
+
+
+/*
+===============
+UI_PlayerFloatSprite
+===============
+*/
+static void UI_PlayerFloatSprite( playerInfo_t *pi, vec3_t origin, qhandle_t shader ) {
+ refEntity_t ent;
+
+ memset( &ent, 0, sizeof( ent ) );
+ VectorCopy( origin, ent.origin );
+ ent.origin[2] += 48;
+ ent.reType = RT_SPRITE;
+ ent.customShader = shader;
+ ent.radius = 10;
+ ent.renderfx = 0;
+ trap_R_AddRefEntityToScene( &ent );
+}
+
+
+/*
+======================
+UI_MachinegunSpinAngle
+======================
+*/
+float UI_MachinegunSpinAngle( playerInfo_t *pi ) {
+ int delta;
+ float angle;
+ float speed;
+ int torsoAnim;
+
+ delta = dp_realtime - pi->barrelTime;
+ if ( pi->barrelSpinning ) {
+ angle = pi->barrelAngle + delta * SPIN_SPEED;
+ } else {
+ if ( delta > COAST_TIME ) {
+ delta = COAST_TIME;
+ }
+
+ speed = 0.5 * ( SPIN_SPEED + (float)( COAST_TIME - delta ) / COAST_TIME );
+ angle = pi->barrelAngle + delta * speed;
+ }
+
+ torsoAnim = pi->torsoAnim & ~ANIM_TOGGLEBIT;
+ if( torsoAnim == TORSO_ATTACK2 ) {
+ torsoAnim = TORSO_ATTACK;
+ }
+ if ( pi->barrelSpinning == !(torsoAnim == TORSO_ATTACK) ) {
+ pi->barrelTime = dp_realtime;
+ pi->barrelAngle = AngleMod( angle );
+ pi->barrelSpinning = !!(torsoAnim == TORSO_ATTACK);
+ }
+
+ return angle;
+}
+
+
+/*
+===============
+UI_DrawPlayer
+===============
+*/
+void UI_DrawPlayer( float x, float y, float w, float h, playerInfo_t *pi, int time ) {
+ refdef_t refdef;
+ refEntity_t legs;
+ refEntity_t torso;
+ refEntity_t head;
+ refEntity_t gun;
+ refEntity_t barrel;
+ refEntity_t flash;
+ vec3_t origin;
+ int renderfx;
+ vec3_t mins = {-16, -16, -24};
+ vec3_t maxs = {16, 16, 32};
+ float len;
+ float xx;
+
+ if ( !pi->legsModel || !pi->torsoModel || !pi->headModel || !pi->animations[0].numFrames ) {
+ return;
+ }
+
+ // this allows the ui to cache the player model on the main menu
+ if (w == 0 || h == 0) {
+ return;
+ }
+
+ dp_realtime = time;
+
+ if ( pi->pendingWeapon != -1 && dp_realtime > pi->weaponTimer ) {
+ pi->weapon = pi->pendingWeapon;
+ pi->lastWeapon = pi->pendingWeapon;
+ pi->pendingWeapon = -1;
+ pi->weaponTimer = 0;
+ if( pi->currentWeapon != pi->weapon ) {
+ trap_S_StartLocalSound( weaponChangeSound, CHAN_LOCAL );
+ }
+ }
+
+ UI_AdjustFrom640( &x, &y, &w, &h );
+
+ y -= jumpHeight;
+
+ memset( &refdef, 0, sizeof( refdef ) );
+ memset( &legs, 0, sizeof(legs) );
+ memset( &torso, 0, sizeof(torso) );
+ memset( &head, 0, sizeof(head) );
+
+ refdef.rdflags = RDF_NOWORLDMODEL;
+
+ AxisClear( refdef.viewaxis );
+
+ refdef.x = x;
+ refdef.y = y;
+ refdef.width = w;
+ refdef.height = h;
+
+ refdef.fov_x = (int)((float)refdef.width / 640.0f * 90.0f);
+ xx = refdef.width / tan( refdef.fov_x / 360 * M_PI );
+ refdef.fov_y = atan2( refdef.height, xx );
+ refdef.fov_y *= ( 360 / (float)M_PI );
+
+ // calculate distance so the player nearly fills the box
+ len = 0.7 * ( maxs[2] - mins[2] );
+ origin[0] = len / tan( DEG2RAD(refdef.fov_x) * 0.5 );
+ origin[1] = 0.5 * ( mins[1] + maxs[1] );
+ origin[2] = -0.5 * ( mins[2] + maxs[2] );
+
+ refdef.time = dp_realtime;
+
+ trap_R_ClearScene();
+
+ // get the rotation information
+ UI_PlayerAngles( pi, legs.axis, torso.axis, head.axis );
+
+ // get the animation state (after rotation, to allow feet shuffle)
+ UI_PlayerAnimation( pi, &legs.oldframe, &legs.frame, &legs.backlerp,
+ &torso.oldframe, &torso.frame, &torso.backlerp );
+
+ renderfx = RF_LIGHTING_ORIGIN | RF_NOSHADOW;
+
+ //
+ // add the legs
+ //
+ legs.hModel = pi->legsModel;
+ legs.customSkin = pi->legsSkin;
+
+ VectorCopy( origin, legs.origin );
+
+ VectorCopy( origin, legs.lightingOrigin );
+ legs.renderfx = renderfx;
+ VectorCopy (legs.origin, legs.oldorigin);
+
+ trap_R_AddRefEntityToScene( &legs );
+
+ if (!legs.hModel) {
+ return;
+ }
+
+ //
+ // add the torso
+ //
+ torso.hModel = pi->torsoModel;
+ if (!torso.hModel) {
+ return;
+ }
+
+ torso.customSkin = pi->torsoSkin;
+
+ VectorCopy( origin, torso.lightingOrigin );
+
+ UI_PositionRotatedEntityOnTag( &torso, &legs, pi->legsModel, "tag_torso");
+
+ torso.renderfx = renderfx;
+
+ trap_R_AddRefEntityToScene( &torso );
+
+ //
+ // add the head
+ //
+ head.hModel = pi->headModel;
+ if (!head.hModel) {
+ return;
+ }
+ head.customSkin = pi->headSkin;
+
+ VectorCopy( origin, head.lightingOrigin );
+
+ UI_PositionRotatedEntityOnTag( &head, &torso, pi->torsoModel, "tag_head");
+
+ head.renderfx = renderfx;
+
+ trap_R_AddRefEntityToScene( &head );
+
+ //
+ // add the gun
+ //
+ if ( pi->currentWeapon != WP_NONE ) {
+ memset( &gun, 0, sizeof(gun) );
+ gun.hModel = pi->weaponModel;
+ VectorCopy( origin, gun.lightingOrigin );
+ UI_PositionEntityOnTag( &gun, &torso, pi->torsoModel, "tag_weapon");
+ gun.renderfx = renderfx;
+ trap_R_AddRefEntityToScene( &gun );
+ }
+
+ //
+ // add the spinning barrel
+ //
+ if ( pi->realWeapon == WP_MACHINEGUN || pi->realWeapon == WP_GAUNTLET || pi->realWeapon == WP_BFG ) {
+ vec3_t angles;
+
+ memset( &barrel, 0, sizeof(barrel) );
+ VectorCopy( origin, barrel.lightingOrigin );
+ barrel.renderfx = renderfx;
+
+ barrel.hModel = pi->barrelModel;
+ angles[YAW] = 0;
+ angles[PITCH] = 0;
+ angles[ROLL] = UI_MachinegunSpinAngle( pi );
+ if( pi->realWeapon == WP_GAUNTLET || pi->realWeapon == WP_BFG ) {
+ angles[PITCH] = angles[ROLL];
+ angles[ROLL] = 0;
+ }
+ AnglesToAxis( angles, barrel.axis );
+
+ UI_PositionRotatedEntityOnTag( &barrel, &gun, pi->weaponModel, "tag_barrel");
+
+ trap_R_AddRefEntityToScene( &barrel );
+ }
+
+ //
+ // add muzzle flash
+ //
+ if ( dp_realtime <= pi->muzzleFlashTime ) {
+ if ( pi->flashModel ) {
+ memset( &flash, 0, sizeof(flash) );
+ flash.hModel = pi->flashModel;
+ VectorCopy( origin, flash.lightingOrigin );
+ UI_PositionEntityOnTag( &flash, &gun, pi->weaponModel, "tag_flash");
+ flash.renderfx = renderfx;
+ trap_R_AddRefEntityToScene( &flash );
+ }
+
+ // make a dlight for the flash
+ if ( pi->flashDlightColor[0] || pi->flashDlightColor[1] || pi->flashDlightColor[2] ) {
+ trap_R_AddLightToScene( flash.origin, 200 + (rand()&31), pi->flashDlightColor[0],
+ pi->flashDlightColor[1], pi->flashDlightColor[2] );
+ }
+ }
+
+ //
+ // add the chat icon
+ //
+ if ( pi->chat ) {
+ UI_PlayerFloatSprite( pi, origin, trap_R_RegisterShaderNoMip( "sprites/balloon3" ) );
+ }
+
+ //
+ // add an accent light
+ //
+ origin[0] -= 100; // + = behind, - = in front
+ origin[1] += 100; // + = left, - = right
+ origin[2] += 100; // + = above, - = below
+ trap_R_AddLightToScene( origin, 500, 1.0, 1.0, 1.0 );
+
+ origin[0] -= 100;
+ origin[1] -= 100;
+ origin[2] -= 100;
+ trap_R_AddLightToScene( origin, 500, 1.0, 0.0, 0.0 );
+
+ trap_R_RenderScene( &refdef );
+}
+
+/*
+==========================
+UI_FileExists
+==========================
+*/
+static qboolean UI_FileExists(const char *filename) {
+ int len;
+
+ len = trap_FS_FOpenFile( filename, 0, FS_READ );
+ if (len>0) {
+ return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+==========================
+UI_FindClientHeadFile
+==========================
+*/
+static qboolean UI_FindClientHeadFile( char *filename, int length, const char *teamName, const char *headModelName, const char *headSkinName, const char *base, const char *ext ) {
+ char *team, *headsFolder;
+ int i;
+
+ team = "default";
+
+ if ( headModelName[0] == '*' ) {
+ headsFolder = "heads/";
+ headModelName++;
+ }
+ else {
+ headsFolder = "";
+ }
+ while(1) {
+ for ( i = 0; i < 2; i++ ) {
+ if ( i == 0 && teamName && *teamName ) {
+ Com_sprintf( filename, length, "models/players/%s%s/%s/%s%s_%s.%s", headsFolder, headModelName, headSkinName, teamName, base, team, ext );
+ }
+ else {
+ Com_sprintf( filename, length, "models/players/%s%s/%s/%s_%s.%s", headsFolder, headModelName, headSkinName, base, team, ext );
+ }
+ if ( UI_FileExists( filename ) ) {
+ return qtrue;
+ }
+ if ( i == 0 && teamName && *teamName ) {
+ Com_sprintf( filename, length, "models/players/%s%s/%s%s_%s.%s", headsFolder, headModelName, teamName, base, headSkinName, ext );
+ }
+ else {
+ Com_sprintf( filename, length, "models/players/%s%s/%s_%s.%s", headsFolder, headModelName, base, headSkinName, ext );
+ }
+ if ( UI_FileExists( filename ) ) {
+ return qtrue;
+ }
+ if ( !teamName || !*teamName ) {
+ break;
+ }
+ }
+ // if tried the heads folder first
+ if ( headsFolder[0] ) {
+ break;
+ }
+ headsFolder = "heads/";
+ }
+
+ return qfalse;
+}
+
+/*
+==========================
+UI_RegisterClientSkin
+==========================
+*/
+static qboolean UI_RegisterClientSkin( playerInfo_t *pi, const char *modelName, const char *skinName, const char *headModelName, const char *headSkinName , const char *teamName) {
+ char filename[MAX_QPATH*2];
+
+ if (teamName && *teamName) {
+ Com_sprintf( filename, sizeof( filename ), "models/players/%s/%s/lower_%s.skin", modelName, teamName, skinName );
+ } else {
+ Com_sprintf( filename, sizeof( filename ), "models/players/%s/lower_%s.skin", modelName, skinName );
+ }
+ pi->legsSkin = trap_R_RegisterSkin( filename );
+ if (!pi->legsSkin) {
+ if (teamName && *teamName) {
+ Com_sprintf( filename, sizeof( filename ), "models/players/characters/%s/%s/lower_%s.skin", modelName, teamName, skinName );
+ } else {
+ Com_sprintf( filename, sizeof( filename ), "models/players/characters/%s/lower_%s.skin", modelName, skinName );
+ }
+ pi->legsSkin = trap_R_RegisterSkin( filename );
+ }
+
+ if (teamName && *teamName) {
+ Com_sprintf( filename, sizeof( filename ), "models/players/%s/%s/upper_%s.skin", modelName, teamName, skinName );
+ } else {
+ Com_sprintf( filename, sizeof( filename ), "models/players/%s/upper_%s.skin", modelName, skinName );
+ }
+ pi->torsoSkin = trap_R_RegisterSkin( filename );
+ if (!pi->torsoSkin) {
+ if (teamName && *teamName) {
+ Com_sprintf( filename, sizeof( filename ), "models/players/characters/%s/%s/upper_%s.skin", modelName, teamName, skinName );
+ } else {
+ Com_sprintf( filename, sizeof( filename ), "models/players/characters/%s/upper_%s.skin", modelName, skinName );
+ }
+ pi->torsoSkin = trap_R_RegisterSkin( filename );
+ }
+
+ if ( UI_FindClientHeadFile( filename, sizeof(filename), teamName, headModelName, headSkinName, "head", "skin" ) ) {
+ pi->headSkin = trap_R_RegisterSkin( filename );
+ }
+
+ if ( !pi->legsSkin || !pi->torsoSkin || !pi->headSkin ) {
+ return qfalse;
+ }
+
+ return qtrue;
+}
+
+
+/*
+======================
+UI_ParseAnimationFile
+======================
+*/
+static qboolean UI_ParseAnimationFile( const char *filename, animation_t *animations ) {
+ char *text_p, *prev;
+ int len;
+ int i;
+ char *token;
+ float fps;
+ int skip;
+ char text[20000];
+ fileHandle_t f;
+
+ memset( animations, 0, sizeof( animation_t ) * MAX_ANIMATIONS );
+
+ // load the file
+ len = trap_FS_FOpenFile( filename, &f, FS_READ );
+ if ( len <= 0 ) {
+ return qfalse;
+ }
+ if ( len >= ( sizeof( text ) - 1 ) ) {
+ Com_Printf( "File %s too long\n", filename );
+ return qfalse;
+ }
+ trap_FS_Read( text, len, f );
+ text[len] = 0;
+ trap_FS_FCloseFile( f );
+
+ COM_Compress(text);
+
+ // parse the text
+ text_p = text;
+ skip = 0; // quite the compiler warning
+
+ // read optional parameters
+ while ( 1 ) {
+ prev = text_p; // so we can unget
+ token = COM_Parse( &text_p );
+ if ( !token ) {
+ break;
+ }
+ if ( !Q_stricmp( token, "footsteps" ) ) {
+ token = COM_Parse( &text_p );
+ if ( !token ) {
+ break;
+ }
+ continue;
+ } else if ( !Q_stricmp( token, "headoffset" ) ) {
+ for ( i = 0 ; i < 3 ; i++ ) {
+ token = COM_Parse( &text_p );
+ if ( !token ) {
+ break;
+ }
+ }
+ continue;
+ } else if ( !Q_stricmp( token, "sex" ) ) {
+ token = COM_Parse( &text_p );
+ if ( !token ) {
+ break;
+ }
+ continue;
+ }
+
+ // if it is a number, start parsing animations
+ if ( token[0] >= '0' && token[0] <= '9' ) {
+ text_p = prev; // unget the token
+ break;
+ }
+
+ Com_Printf( "unknown token '%s' is %s\n", token, filename );
+ }
+
+ // read information for each frame
+ for ( i = 0 ; i < MAX_ANIMATIONS ; i++ ) {
+
+ token = COM_Parse( &text_p );
+ if ( !token ) {
+ break;
+ }
+ animations[i].firstFrame = atoi( token );
+ // leg only frames are adjusted to not count the upper body only frames
+ if ( i == LEGS_WALKCR ) {
+ skip = animations[LEGS_WALKCR].firstFrame - animations[TORSO_GESTURE].firstFrame;
+ }
+ if ( i >= LEGS_WALKCR ) {
+ animations[i].firstFrame -= skip;
+ }
+
+ token = COM_Parse( &text_p );
+ if ( !token ) {
+ break;
+ }
+ animations[i].numFrames = atoi( token );
+
+ token = COM_Parse( &text_p );
+ if ( !token ) {
+ break;
+ }
+ animations[i].loopFrames = atoi( token );
+
+ token = COM_Parse( &text_p );
+ if ( !token ) {
+ break;
+ }
+ fps = atof( token );
+ if ( fps == 0 ) {
+ fps = 1;
+ }
+ animations[i].frameLerp = 1000 / fps;
+ animations[i].initialLerp = 1000 / fps;
+ }
+
+ if ( i != MAX_ANIMATIONS ) {
+ Com_Printf( "Error parsing animation file: %s", filename );
+ return qfalse;
+ }
+
+ return qtrue;
+}
+
+/*
+==========================
+UI_RegisterClientModelname
+==========================
+*/
+qboolean UI_RegisterClientModelname( playerInfo_t *pi, const char *modelSkinName, const char *headModelSkinName, const char *teamName ) {
+ char modelName[MAX_QPATH];
+ char skinName[MAX_QPATH];
+ char headModelName[MAX_QPATH];
+ char headSkinName[MAX_QPATH];
+ char filename[MAX_QPATH];
+ char *slash;
+
+ pi->torsoModel = 0;
+ pi->headModel = 0;
+
+ if ( !modelSkinName[0] ) {
+ return qfalse;
+ }
+
+ Q_strncpyz( modelName, modelSkinName, sizeof( modelName ) );
+
+ slash = strchr( modelName, '/' );
+ if ( !slash ) {
+ // modelName did not include a skin name
+ Q_strncpyz( skinName, "default", sizeof( skinName ) );
+ } else {
+ Q_strncpyz( skinName, slash + 1, sizeof( skinName ) );
+ *slash = '\0';
+ }
+
+ Q_strncpyz( headModelName, headModelSkinName, sizeof( headModelName ) );
+ slash = strchr( headModelName, '/' );
+ if ( !slash ) {
+ // modelName did not include a skin name
+ Q_strncpyz( headSkinName, "default", sizeof( skinName ) );
+ } else {
+ Q_strncpyz( headSkinName, slash + 1, sizeof( skinName ) );
+ *slash = '\0';
+ }
+
+ // load cmodels before models so filecache works
+
+ Com_sprintf( filename, sizeof( filename ), "models/players/%s/lower.md3", modelName );
+ pi->legsModel = trap_R_RegisterModel( filename );
+ if ( !pi->legsModel ) {
+ Com_sprintf( filename, sizeof( filename ), "models/players/characters/%s/lower.md3", modelName );
+ pi->legsModel = trap_R_RegisterModel( filename );
+ if ( !pi->legsModel ) {
+ Com_Printf( "Failed to load model file %s\n", filename );
+ return qfalse;
+ }
+ }
+
+ Com_sprintf( filename, sizeof( filename ), "models/players/%s/upper.md3", modelName );
+ pi->torsoModel = trap_R_RegisterModel( filename );
+ if ( !pi->torsoModel ) {
+ Com_sprintf( filename, sizeof( filename ), "models/players/characters/%s/upper.md3", modelName );
+ pi->torsoModel = trap_R_RegisterModel( filename );
+ if ( !pi->torsoModel ) {
+ Com_Printf( "Failed to load model file %s\n", filename );
+ return qfalse;
+ }
+ }
+
+ if (headModelName && headModelName[0] == '*' ) {
+ Com_sprintf( filename, sizeof( filename ), "models/players/heads/%s/%s.md3", &headModelName[1], &headModelName[1] );
+ }
+ else {
+ Com_sprintf( filename, sizeof( filename ), "models/players/%s/head.md3", headModelName );
+ }
+ pi->headModel = trap_R_RegisterModel( filename );
+ if ( !pi->headModel && headModelName[0] != '*') {
+ Com_sprintf( filename, sizeof( filename ), "models/players/heads/%s/%s.md3", headModelName, headModelName );
+ pi->headModel = trap_R_RegisterModel( filename );
+ }
+
+ if (!pi->headModel) {
+ Com_Printf( "Failed to load model file %s\n", filename );
+ return qfalse;
+ }
+
+ // if any skins failed to load, fall back to default
+ if ( !UI_RegisterClientSkin( pi, modelName, skinName, headModelName, headSkinName, teamName) ) {
+ if ( !UI_RegisterClientSkin( pi, modelName, "default", headModelName, "default", teamName ) ) {
+ Com_Printf( "Failed to load skin file: %s : %s\n", modelName, skinName );
+ return qfalse;
+ }
+ }
+
+ // load the animations
+ Com_sprintf( filename, sizeof( filename ), "models/players/%s/animation.cfg", modelName );
+ if ( !UI_ParseAnimationFile( filename, pi->animations ) ) {
+ Com_sprintf( filename, sizeof( filename ), "models/players/characters/%s/animation.cfg", modelName );
+ if ( !UI_ParseAnimationFile( filename, pi->animations ) ) {
+ Com_Printf( "Failed to load animation file %s\n", filename );
+ return qfalse;
+ }
+ }
+
+ return qtrue;
+}
+
+
+/*
+===============
+UI_PlayerInfo_SetModel
+===============
+*/
+void UI_PlayerInfo_SetModel( playerInfo_t *pi, const char *model, const char *headmodel, char *teamName ) {
+ memset( pi, 0, sizeof(*pi) );
+ UI_RegisterClientModelname( pi, model, headmodel, teamName );
+ pi->weapon = WP_MACHINEGUN;
+ pi->currentWeapon = pi->weapon;
+ pi->lastWeapon = pi->weapon;
+ pi->pendingWeapon = -1;
+ pi->weaponTimer = 0;
+ pi->chat = qfalse;
+ pi->newModel = qtrue;
+ UI_PlayerInfo_SetWeapon( pi, pi->weapon );
+}
+
+
+/*
+===============
+UI_PlayerInfo_SetInfo
+===============
+*/
+void UI_PlayerInfo_SetInfo( playerInfo_t *pi, int legsAnim, int torsoAnim, vec3_t viewAngles, vec3_t moveAngles, weapon_t weaponNumber, qboolean chat ) {
+ int currentAnim;
+ weapon_t weaponNum;
+
+ pi->chat = chat;
+
+ // view angles
+ VectorCopy( viewAngles, pi->viewAngles );
+
+ // move angles
+ VectorCopy( moveAngles, pi->moveAngles );
+
+ if ( pi->newModel ) {
+ pi->newModel = qfalse;
+
+ jumpHeight = 0;
+ pi->pendingLegsAnim = 0;
+ UI_ForceLegsAnim( pi, legsAnim );
+ pi->legs.yawAngle = viewAngles[YAW];
+ pi->legs.yawing = qfalse;
+
+ pi->pendingTorsoAnim = 0;
+ UI_ForceTorsoAnim( pi, torsoAnim );
+ pi->torso.yawAngle = viewAngles[YAW];
+ pi->torso.yawing = qfalse;
+
+ if ( weaponNumber != -1 ) {
+ pi->weapon = weaponNumber;
+ pi->currentWeapon = weaponNumber;
+ pi->lastWeapon = weaponNumber;
+ pi->pendingWeapon = -1;
+ pi->weaponTimer = 0;
+ UI_PlayerInfo_SetWeapon( pi, pi->weapon );
+ }
+
+ return;
+ }
+
+ // weapon
+ if ( weaponNumber == -1 ) {
+ pi->pendingWeapon = -1;
+ pi->weaponTimer = 0;
+ }
+ else if ( weaponNumber != WP_NONE ) {
+ pi->pendingWeapon = weaponNumber;
+ pi->weaponTimer = dp_realtime + UI_TIMER_WEAPON_DELAY;
+ }
+ weaponNum = pi->lastWeapon;
+ pi->weapon = weaponNum;
+
+ if ( torsoAnim == BOTH_DEATH1 || legsAnim == BOTH_DEATH1 ) {
+ torsoAnim = legsAnim = BOTH_DEATH1;
+ pi->weapon = pi->currentWeapon = WP_NONE;
+ UI_PlayerInfo_SetWeapon( pi, pi->weapon );
+
+ jumpHeight = 0;
+ pi->pendingLegsAnim = 0;
+ UI_ForceLegsAnim( pi, legsAnim );
+
+ pi->pendingTorsoAnim = 0;
+ UI_ForceTorsoAnim( pi, torsoAnim );
+
+ return;
+ }
+
+ // leg animation
+ currentAnim = pi->legsAnim & ~ANIM_TOGGLEBIT;
+ if ( legsAnim != LEGS_JUMP && ( currentAnim == LEGS_JUMP || currentAnim == LEGS_LAND ) ) {
+ pi->pendingLegsAnim = legsAnim;
+ }
+ else if ( legsAnim != currentAnim ) {
+ jumpHeight = 0;
+ pi->pendingLegsAnim = 0;
+ UI_ForceLegsAnim( pi, legsAnim );
+ }
+
+ // torso animation
+ if ( torsoAnim == TORSO_STAND || torsoAnim == TORSO_STAND2 ) {
+ if ( weaponNum == WP_NONE || weaponNum == WP_GAUNTLET ) {
+ torsoAnim = TORSO_STAND2;
+ }
+ else {
+ torsoAnim = TORSO_STAND;
+ }
+ }
+
+ if ( torsoAnim == TORSO_ATTACK || torsoAnim == TORSO_ATTACK2 ) {
+ if ( weaponNum == WP_NONE || weaponNum == WP_GAUNTLET ) {
+ torsoAnim = TORSO_ATTACK2;
+ }
+ else {
+ torsoAnim = TORSO_ATTACK;
+ }
+ pi->muzzleFlashTime = dp_realtime + UI_TIMER_MUZZLE_FLASH;
+ //FIXME play firing sound here
+ }
+
+ currentAnim = pi->torsoAnim & ~ANIM_TOGGLEBIT;
+
+ if ( weaponNum != pi->currentWeapon || currentAnim == TORSO_RAISE || currentAnim == TORSO_DROP ) {
+ pi->pendingTorsoAnim = torsoAnim;
+ }
+ else if ( ( currentAnim == TORSO_GESTURE || currentAnim == TORSO_ATTACK ) && ( torsoAnim != currentAnim ) ) {
+ pi->pendingTorsoAnim = torsoAnim;
+ }
+ else if ( torsoAnim != currentAnim ) {
+ pi->pendingTorsoAnim = 0;
+ UI_ForceTorsoAnim( pi, torsoAnim );
+ }
+}
diff --git a/code/ui/ui_public.h b/code/ui/ui_public.h
new file mode 100755
index 0000000..70edee3
--- /dev/null
+++ b/code/ui/ui_public.h
@@ -0,0 +1,191 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#ifndef __UI_PUBLIC_H__
+#define __UI_PUBLIC_H__
+
+#define UI_API_VERSION 6
+
+typedef struct {
+ connstate_t connState;
+ int connectPacketCount;
+ int clientNum;
+ char servername[MAX_STRING_CHARS];
+ char updateInfoString[MAX_STRING_CHARS];
+ char messageString[MAX_STRING_CHARS];
+} uiClientState_t;
+
+typedef enum {
+ UI_ERROR,
+ UI_PRINT,
+ UI_MILLISECONDS,
+ UI_CVAR_SET,
+ UI_CVAR_VARIABLEVALUE,
+ UI_CVAR_VARIABLESTRINGBUFFER,
+ UI_CVAR_SETVALUE,
+ UI_CVAR_RESET,
+ UI_CVAR_CREATE,
+ UI_CVAR_INFOSTRINGBUFFER,
+ UI_ARGC,
+ UI_ARGV,
+ UI_CMD_EXECUTETEXT,
+ UI_FS_FOPENFILE,
+ UI_FS_READ,
+ UI_FS_WRITE,
+ UI_FS_FCLOSEFILE,
+ UI_FS_GETFILELIST,
+ UI_R_REGISTERMODEL,
+ UI_R_REGISTERSKIN,
+ UI_R_REGISTERSHADERNOMIP,
+ UI_R_CLEARSCENE,
+ UI_R_ADDREFENTITYTOSCENE,
+ UI_R_ADDPOLYTOSCENE,
+ UI_R_ADDLIGHTTOSCENE,
+ UI_R_RENDERSCENE,
+ UI_R_SETCOLOR,
+ UI_R_DRAWSTRETCHPIC,
+ UI_UPDATESCREEN,
+ UI_CM_LERPTAG,
+ UI_CM_LOADMODEL,
+ UI_S_REGISTERSOUND,
+ UI_S_STARTLOCALSOUND,
+ UI_KEY_KEYNUMTOSTRINGBUF,
+ UI_KEY_GETBINDINGBUF,
+ UI_KEY_SETBINDING,
+ UI_KEY_ISDOWN,
+ UI_KEY_GETOVERSTRIKEMODE,
+ UI_KEY_SETOVERSTRIKEMODE,
+ UI_KEY_CLEARSTATES,
+ UI_KEY_GETCATCHER,
+ UI_KEY_SETCATCHER,
+ UI_GETCLIPBOARDDATA,
+ UI_GETGLCONFIG,
+ UI_GETCLIENTSTATE,
+ UI_GETCONFIGSTRING,
+ UI_LAN_GETPINGQUEUECOUNT,
+ UI_LAN_CLEARPING,
+ UI_LAN_GETPING,
+ UI_LAN_GETPINGINFO,
+ UI_CVAR_REGISTER,
+ UI_CVAR_UPDATE,
+ UI_MEMORY_REMAINING,
+ UI_GET_CDKEY,
+ UI_SET_CDKEY,
+ UI_R_REGISTERFONT,
+ UI_R_MODELBOUNDS,
+ UI_PC_ADD_GLOBAL_DEFINE,
+ UI_PC_LOAD_SOURCE,
+ UI_PC_FREE_SOURCE,
+ UI_PC_READ_TOKEN,
+ UI_PC_SOURCE_FILE_AND_LINE,
+ UI_S_STOPBACKGROUNDTRACK,
+ UI_S_STARTBACKGROUNDTRACK,
+ UI_REAL_TIME,
+ UI_LAN_GETSERVERCOUNT,
+ UI_LAN_GETSERVERADDRESSSTRING,
+ UI_LAN_GETSERVERINFO,
+ UI_LAN_MARKSERVERVISIBLE,
+ UI_LAN_UPDATEVISIBLEPINGS,
+ UI_LAN_RESETPINGS,
+ UI_LAN_LOADCACHEDSERVERS,
+ UI_LAN_SAVECACHEDSERVERS,
+ UI_LAN_ADDSERVER,
+ UI_LAN_REMOVESERVER,
+ UI_CIN_PLAYCINEMATIC,
+ UI_CIN_STOPCINEMATIC,
+ UI_CIN_RUNCINEMATIC,
+ UI_CIN_DRAWCINEMATIC,
+ UI_CIN_SETEXTENTS,
+ UI_R_REMAP_SHADER,
+ UI_VERIFY_CDKEY,
+ UI_LAN_SERVERSTATUS,
+ UI_LAN_GETSERVERPING,
+ UI_LAN_SERVERISVISIBLE,
+ UI_LAN_COMPARESERVERS,
+ // 1.32
+ UI_FS_SEEK,
+ UI_SET_PBCLSTATUS,
+
+ UI_MEMSET = 100,
+ UI_MEMCPY,
+ UI_STRNCPY,
+ UI_SIN,
+ UI_COS,
+ UI_ATAN2,
+ UI_SQRT,
+ UI_FLOOR,
+ UI_CEIL
+} uiImport_t;
+
+typedef enum {
+ UIMENU_NONE,
+ UIMENU_MAIN,
+ UIMENU_INGAME,
+ UIMENU_NEED_CD,
+ UIMENU_BAD_CD_KEY,
+ UIMENU_TEAM,
+ UIMENU_POSTGAME
+} uiMenuCommand_t;
+
+#define SORT_HOST 0
+#define SORT_MAP 1
+#define SORT_CLIENTS 2
+#define SORT_GAME 3
+#define SORT_PING 4
+#define SORT_PUNKBUSTER 5
+
+typedef enum {
+ UI_GETAPIVERSION = 0, // system reserved
+
+ UI_INIT,
+// void UI_Init( void );
+
+ UI_SHUTDOWN,
+// void UI_Shutdown( void );
+
+ UI_KEY_EVENT,
+// void UI_KeyEvent( int key );
+
+ UI_MOUSE_EVENT,
+// void UI_MouseEvent( int dx, int dy );
+
+ UI_REFRESH,
+// void UI_Refresh( int time );
+
+ UI_IS_FULLSCREEN,
+// qboolean UI_IsFullscreen( void );
+
+ UI_SET_ACTIVE_MENU,
+// void UI_SetActiveMenu( uiMenuCommand_t menu );
+
+ UI_CONSOLE_COMMAND,
+// qboolean UI_ConsoleCommand( int realTime );
+
+ UI_DRAW_CONNECT_SCREEN,
+// void UI_DrawConnectScreen( qboolean overlay );
+ UI_HASUNIQUECDKEY
+// if !overlay, the background will be drawn, otherwise it will be
+// overlayed over whatever the cgame has drawn.
+// a GetClientState syscall will be made to get the current strings
+} uiExport_t;
+
+#endif
diff --git a/code/ui/ui_shared.c b/code/ui/ui_shared.c
new file mode 100755
index 0000000..be2f69e
--- /dev/null
+++ b/code/ui/ui_shared.c
@@ -0,0 +1,5785 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// string allocation/managment
+
+#include "ui_shared.h"
+
+#define SCROLL_TIME_START 500
+#define SCROLL_TIME_ADJUST 150
+#define SCROLL_TIME_ADJUSTOFFSET 40
+#define SCROLL_TIME_FLOOR 20
+
+typedef struct scrollInfo_s {
+ int nextScrollTime;
+ int nextAdjustTime;
+ int adjustValue;
+ int scrollKey;
+ float xStart;
+ float yStart;
+ itemDef_t *item;
+ qboolean scrollDir;
+} scrollInfo_t;
+
+static scrollInfo_t scrollInfo;
+
+static void (*captureFunc) (void *p) = NULL;
+static void *captureData = NULL;
+static itemDef_t *itemCapture = NULL; // item that has the mouse captured ( if any )
+
+displayContextDef_t *DC = NULL;
+
+static qboolean g_waitingForKey = qfalse;
+static qboolean g_editingField = qfalse;
+
+static itemDef_t *g_bindItem = NULL;
+static itemDef_t *g_editItem = NULL;
+
+menuDef_t Menus[MAX_MENUS]; // defined menus
+int menuCount = 0; // how many
+
+menuDef_t *menuStack[MAX_OPEN_MENUS];
+int openMenuCount = 0;
+
+static qboolean debugMode = qfalse;
+
+#define DOUBLE_CLICK_DELAY 300
+static int lastListBoxClickTime = 0;
+
+void Item_RunScript(itemDef_t *item, const char *s);
+void Item_SetupKeywordHash(void);
+void Menu_SetupKeywordHash(void);
+int BindingIDFromName(const char *name);
+qboolean Item_Bind_HandleKey(itemDef_t *item, int key, qboolean down);
+itemDef_t *Menu_SetPrevCursorItem(menuDef_t *menu);
+itemDef_t *Menu_SetNextCursorItem(menuDef_t *menu);
+static qboolean Menu_OverActiveItem(menuDef_t *menu, float x, float y);
+
+#ifdef CGAME
+#define MEM_POOL_SIZE 128 * 1024
+#else
+#define MEM_POOL_SIZE 1024 * 1024
+#endif
+
+static char memoryPool[MEM_POOL_SIZE];
+static int allocPoint, outOfMemory;
+
+
+/*
+===============
+UI_Alloc
+===============
+*/
+void *UI_Alloc( int size ) {
+ char *p;
+
+ if ( allocPoint + size > MEM_POOL_SIZE ) {
+ outOfMemory = qtrue;
+ if (DC->Print) {
+ DC->Print("UI_Alloc: Failure. Out of memory!\n");
+ }
+ //DC->trap_Print(S_COLOR_YELLOW"WARNING: UI Out of Memory!\n");
+ return NULL;
+ }
+
+ p = &memoryPool[allocPoint];
+
+ allocPoint += ( size + 15 ) & ~15;
+
+ return p;
+}
+
+/*
+===============
+UI_InitMemory
+===============
+*/
+void UI_InitMemory( void ) {
+ allocPoint = 0;
+ outOfMemory = qfalse;
+}
+
+qboolean UI_OutOfMemory() {
+ return outOfMemory;
+}
+
+
+
+
+
+#define HASH_TABLE_SIZE 2048
+/*
+================
+return a hash value for the string
+================
+*/
+static long hashForString(const char *str) {
+ int i;
+ long hash;
+ char letter;
+
+ hash = 0;
+ i = 0;
+ while (str[i] != '\0') {
+ letter = tolower(str[i]);
+ hash+=(long)(letter)*(i+119);
+ i++;
+ }
+ hash &= (HASH_TABLE_SIZE-1);
+ return hash;
+}
+
+typedef struct stringDef_s {
+ struct stringDef_s *next;
+ const char *str;
+} stringDef_t;
+
+static int strPoolIndex = 0;
+static char strPool[STRING_POOL_SIZE];
+
+static int strHandleCount = 0;
+static stringDef_t *strHandle[HASH_TABLE_SIZE];
+
+
+const char *String_Alloc(const char *p) {
+ int len;
+ long hash;
+ stringDef_t *str, *last;
+ static const char *staticNULL = "";
+
+ if (p == NULL) {
+ return NULL;
+ }
+
+ if (*p == 0) {
+ return staticNULL;
+ }
+
+ hash = hashForString(p);
+
+ str = strHandle[hash];
+ while (str) {
+ if (strcmp(p, str->str) == 0) {
+ return str->str;
+ }
+ str = str->next;
+ }
+
+ len = strlen(p);
+ if (len + strPoolIndex + 1 < STRING_POOL_SIZE) {
+ int ph = strPoolIndex;
+ strcpy(&strPool[strPoolIndex], p);
+ strPoolIndex += len + 1;
+
+ str = strHandle[hash];
+ last = str;
+ while (str && str->next) {
+ last = str;
+ str = str->next;
+ }
+
+ str = UI_Alloc(sizeof(stringDef_t));
+ str->next = NULL;
+ str->str = &strPool[ph];
+ if (last) {
+ last->next = str;
+ } else {
+ strHandle[hash] = str;
+ }
+ return &strPool[ph];
+ }
+ return NULL;
+}
+
+void String_Report() {
+ float f;
+ Com_Printf("Memory/String Pool Info\n");
+ Com_Printf("----------------\n");
+ f = strPoolIndex;
+ f /= STRING_POOL_SIZE;
+ f *= 100;
+ Com_Printf("String Pool is %.1f%% full, %i bytes out of %i used.\n", f, strPoolIndex, STRING_POOL_SIZE);
+ f = allocPoint;
+ f /= MEM_POOL_SIZE;
+ f *= 100;
+ Com_Printf("Memory Pool is %.1f%% full, %i bytes out of %i used.\n", f, allocPoint, MEM_POOL_SIZE);
+}
+
+/*
+=================
+String_Init
+=================
+*/
+void String_Init() {
+ int i;
+ for (i = 0; i < HASH_TABLE_SIZE; i++) {
+ strHandle[i] = 0;
+ }
+ strHandleCount = 0;
+ strPoolIndex = 0;
+ menuCount = 0;
+ openMenuCount = 0;
+ UI_InitMemory();
+ Item_SetupKeywordHash();
+ Menu_SetupKeywordHash();
+ if (DC && DC->getBindingBuf) {
+ Controls_GetConfig();
+ }
+}
+
+/*
+=================
+PC_SourceWarning
+=================
+*/
+void PC_SourceWarning(int handle, char *format, ...) {
+ int line;
+ char filename[128];
+ va_list argptr;
+ static char string[4096];
+
+ va_start (argptr, format);
+ vsprintf (string, format, argptr);
+ va_end (argptr);
+
+ filename[0] = '\0';
+ line = 0;
+ trap_PC_SourceFileAndLine(handle, filename, &line);
+
+ Com_Printf(S_COLOR_YELLOW "WARNING: %s, line %d: %s\n", filename, line, string);
+}
+
+/*
+=================
+PC_SourceError
+=================
+*/
+void PC_SourceError(int handle, char *format, ...) {
+ int line;
+ char filename[128];
+ va_list argptr;
+ static char string[4096];
+
+ va_start (argptr, format);
+ vsprintf (string, format, argptr);
+ va_end (argptr);
+
+ filename[0] = '\0';
+ line = 0;
+ trap_PC_SourceFileAndLine(handle, filename, &line);
+
+ Com_Printf(S_COLOR_RED "ERROR: %s, line %d: %s\n", filename, line, string);
+}
+
+/*
+=================
+LerpColor
+=================
+*/
+void LerpColor(vec4_t a, vec4_t b, vec4_t c, float t)
+{
+ int i;
+
+ // lerp and clamp each component
+ for (i=0; i<4; i++)
+ {
+ c[i] = a[i] + t*(b[i]-a[i]);
+ if (c[i] < 0)
+ c[i] = 0;
+ else if (c[i] > 1.0)
+ c[i] = 1.0;
+ }
+}
+
+/*
+=================
+Float_Parse
+=================
+*/
+qboolean Float_Parse(char **p, float *f) {
+ char *token;
+ token = COM_ParseExt(p, qfalse);
+ if (token && token[0] != 0) {
+ *f = atof(token);
+ return qtrue;
+ } else {
+ return qfalse;
+ }
+}
+
+/*
+=================
+PC_Float_Parse
+=================
+*/
+qboolean PC_Float_Parse(int handle, float *f) {
+ pc_token_t token;
+ int negative = qfalse;
+
+ if (!trap_PC_ReadToken(handle, &token))
+ return qfalse;
+ if (token.string[0] == '-') {
+ if (!trap_PC_ReadToken(handle, &token))
+ return qfalse;
+ negative = qtrue;
+ }
+ if (token.type != TT_NUMBER) {
+ PC_SourceError(handle, "expected float but found %s\n", token.string);
+ return qfalse;
+ }
+ if (negative)
+ *f = -token.floatvalue;
+ else
+ *f = token.floatvalue;
+ return qtrue;
+}
+
+/*
+=================
+Color_Parse
+=================
+*/
+qboolean Color_Parse(char **p, vec4_t *c) {
+ int i;
+ float f;
+
+ for (i = 0; i < 4; i++) {
+ if (!Float_Parse(p, &f)) {
+ return qfalse;
+ }
+ (*c)[i] = f;
+ }
+ return qtrue;
+}
+
+/*
+=================
+PC_Color_Parse
+=================
+*/
+qboolean PC_Color_Parse(int handle, vec4_t *c) {
+ int i;
+ float f;
+
+ for (i = 0; i < 4; i++) {
+ if (!PC_Float_Parse(handle, &f)) {
+ return qfalse;
+ }
+ (*c)[i] = f;
+ }
+ return qtrue;
+}
+
+/*
+=================
+Int_Parse
+=================
+*/
+qboolean Int_Parse(char **p, int *i) {
+ char *token;
+ token = COM_ParseExt(p, qfalse);
+
+ if (token && token[0] != 0) {
+ *i = atoi(token);
+ return qtrue;
+ } else {
+ return qfalse;
+ }
+}
+
+/*
+=================
+PC_Int_Parse
+=================
+*/
+qboolean PC_Int_Parse(int handle, int *i) {
+ pc_token_t token;
+ int negative = qfalse;
+
+ if (!trap_PC_ReadToken(handle, &token))
+ return qfalse;
+ if (token.string[0] == '-') {
+ if (!trap_PC_ReadToken(handle, &token))
+ return qfalse;
+ negative = qtrue;
+ }
+ if (token.type != TT_NUMBER) {
+ PC_SourceError(handle, "expected integer but found %s\n", token.string);
+ return qfalse;
+ }
+ *i = token.intvalue;
+ if (negative)
+ *i = - *i;
+ return qtrue;
+}
+
+/*
+=================
+Rect_Parse
+=================
+*/
+qboolean Rect_Parse(char **p, rectDef_t *r) {
+ if (Float_Parse(p, &r->x)) {
+ if (Float_Parse(p, &r->y)) {
+ if (Float_Parse(p, &r->w)) {
+ if (Float_Parse(p, &r->h)) {
+ return qtrue;
+ }
+ }
+ }
+ }
+ return qfalse;
+}
+
+/*
+=================
+PC_Rect_Parse
+=================
+*/
+qboolean PC_Rect_Parse(int handle, rectDef_t *r) {
+ if (PC_Float_Parse(handle, &r->x)) {
+ if (PC_Float_Parse(handle, &r->y)) {
+ if (PC_Float_Parse(handle, &r->w)) {
+ if (PC_Float_Parse(handle, &r->h)) {
+ return qtrue;
+ }
+ }
+ }
+ }
+ return qfalse;
+}
+
+/*
+=================
+String_Parse
+=================
+*/
+qboolean String_Parse(char **p, const char **out) {
+ char *token;
+
+ token = COM_ParseExt(p, qfalse);
+ if (token && token[0] != 0) {
+ *(out) = String_Alloc(token);
+ return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+=================
+PC_String_Parse
+=================
+*/
+qboolean PC_String_Parse(int handle, const char **out) {
+ pc_token_t token;
+
+ if (!trap_PC_ReadToken(handle, &token))
+ return qfalse;
+
+ *(out) = String_Alloc(token.string);
+ return qtrue;
+}
+
+/*
+=================
+PC_Script_Parse
+=================
+*/
+qboolean PC_Script_Parse(int handle, const char **out) {
+ char script[1024];
+ pc_token_t token;
+
+ memset(script, 0, sizeof(script));
+ // scripts start with { and have ; separated command lists.. commands are command, arg..
+ // basically we want everything between the { } as it will be interpreted at run time
+
+ if (!trap_PC_ReadToken(handle, &token))
+ return qfalse;
+ if (Q_stricmp(token.string, "{") != 0) {
+ return qfalse;
+ }
+
+ while ( 1 ) {
+ if (!trap_PC_ReadToken(handle, &token))
+ return qfalse;
+
+ if (Q_stricmp(token.string, "}") == 0) {
+ *out = String_Alloc(script);
+ return qtrue;
+ }
+
+ if (token.string[1] != '\0') {
+ Q_strcat(script, 1024, va("\"%s\"", token.string));
+ } else {
+ Q_strcat(script, 1024, token.string);
+ }
+ Q_strcat(script, 1024, " ");
+ }
+ return qfalse; // bk001105 - LCC missing return value
+}
+
+// display, window, menu, item code
+//
+
+/*
+==================
+Init_Display
+
+Initializes the display with a structure to all the drawing routines
+ ==================
+*/
+void Init_Display(displayContextDef_t *dc) {
+ DC = dc;
+}
+
+
+
+// type and style painting
+
+void GradientBar_Paint(rectDef_t *rect, vec4_t color) {
+ // gradient bar takes two paints
+ DC->setColor( color );
+ DC->drawHandlePic(rect->x, rect->y, rect->w, rect->h, DC->Assets.gradientBar);
+ DC->setColor( NULL );
+}
+
+
+/*
+==================
+Window_Init
+
+Initializes a window structure ( windowDef_t ) with defaults
+
+==================
+*/
+void Window_Init(Window *w) {
+ memset(w, 0, sizeof(windowDef_t));
+ w->borderSize = 1;
+ w->foreColor[0] = w->foreColor[1] = w->foreColor[2] = w->foreColor[3] = 1.0;
+ w->cinematic = -1;
+}
+
+void Fade(int *flags, float *f, float clamp, int *nextTime, int offsetTime, qboolean bFlags, float fadeAmount) {
+ if (*flags & (WINDOW_FADINGOUT | WINDOW_FADINGIN)) {
+ if (DC->realTime > *nextTime) {
+ *nextTime = DC->realTime + offsetTime;
+ if (*flags & WINDOW_FADINGOUT) {
+ *f -= fadeAmount;
+ if (bFlags && *f <= 0.0) {
+ *flags &= ~(WINDOW_FADINGOUT | WINDOW_VISIBLE);
+ }
+ } else {
+ *f += fadeAmount;
+ if (*f >= clamp) {
+ *f = clamp;
+ if (bFlags) {
+ *flags &= ~WINDOW_FADINGIN;
+ }
+ }
+ }
+ }
+ }
+}
+
+
+
+void Window_Paint(Window *w, float fadeAmount, float fadeClamp, float fadeCycle) {
+ //float bordersize = 0;
+ vec4_t color;
+ rectDef_t fillRect = w->rect;
+
+
+ if (debugMode) {
+ color[0] = color[1] = color[2] = color[3] = 1;
+ DC->drawRect(w->rect.x, w->rect.y, w->rect.w, w->rect.h, 1, color);
+ }
+
+ if (w == NULL || (w->style == 0 && w->border == 0)) {
+ return;
+ }
+
+ if (w->border != 0) {
+ fillRect.x += w->borderSize;
+ fillRect.y += w->borderSize;
+ fillRect.w -= w->borderSize + 1;
+ fillRect.h -= w->borderSize + 1;
+ }
+
+ if (w->style == WINDOW_STYLE_FILLED) {
+ // box, but possible a shader that needs filled
+ if (w->background) {
+ Fade(&w->flags, &w->backColor[3], fadeClamp, &w->nextTime, fadeCycle, qtrue, fadeAmount);
+ DC->setColor(w->backColor);
+ DC->drawHandlePic(fillRect.x, fillRect.y, fillRect.w, fillRect.h, w->background);
+ DC->setColor(NULL);
+ } else {
+ DC->fillRect(fillRect.x, fillRect.y, fillRect.w, fillRect.h, w->backColor);
+ }
+ } else if (w->style == WINDOW_STYLE_GRADIENT) {
+ GradientBar_Paint(&fillRect, w->backColor);
+ // gradient bar
+ } else if (w->style == WINDOW_STYLE_SHADER) {
+ if (w->flags & WINDOW_FORECOLORSET) {
+ DC->setColor(w->foreColor);
+ }
+ DC->drawHandlePic(fillRect.x, fillRect.y, fillRect.w, fillRect.h, w->background);
+ DC->setColor(NULL);
+ } else if (w->style == WINDOW_STYLE_TEAMCOLOR) {
+ if (DC->getTeamColor) {
+ DC->getTeamColor(&color);
+ DC->fillRect(fillRect.x, fillRect.y, fillRect.w, fillRect.h, color);
+ }
+ } else if (w->style == WINDOW_STYLE_CINEMATIC) {
+ if (w->cinematic == -1) {
+ w->cinematic = DC->playCinematic(w->cinematicName, fillRect.x, fillRect.y, fillRect.w, fillRect.h);
+ if (w->cinematic == -1) {
+ w->cinematic = -2;
+ }
+ }
+ if (w->cinematic >= 0) {
+ DC->runCinematicFrame(w->cinematic);
+ DC->drawCinematic(w->cinematic, fillRect.x, fillRect.y, fillRect.w, fillRect.h);
+ }
+ }
+
+ if (w->border == WINDOW_BORDER_FULL) {
+ // full
+ // HACK HACK HACK
+ if (w->style == WINDOW_STYLE_TEAMCOLOR) {
+ if (color[0] > 0) {
+ // red
+ color[0] = 1;
+ color[1] = color[2] = .5;
+
+ } else {
+ color[2] = 1;
+ color[0] = color[1] = .5;
+ }
+ color[3] = 1;
+ DC->drawRect(w->rect.x, w->rect.y, w->rect.w, w->rect.h, w->borderSize, color);
+ } else {
+ DC->drawRect(w->rect.x, w->rect.y, w->rect.w, w->rect.h, w->borderSize, w->borderColor);
+ }
+ } else if (w->border == WINDOW_BORDER_HORZ) {
+ // top/bottom
+ DC->setColor(w->borderColor);
+ DC->drawTopBottom(w->rect.x, w->rect.y, w->rect.w, w->rect.h, w->borderSize);
+ DC->setColor( NULL );
+ } else if (w->border == WINDOW_BORDER_VERT) {
+ // left right
+ DC->setColor(w->borderColor);
+ DC->drawSides(w->rect.x, w->rect.y, w->rect.w, w->rect.h, w->borderSize);
+ DC->setColor( NULL );
+ } else if (w->border == WINDOW_BORDER_KCGRADIENT) {
+ // this is just two gradient bars along each horz edge
+ rectDef_t r = w->rect;
+ r.h = w->borderSize;
+ GradientBar_Paint(&r, w->borderColor);
+ r.y = w->rect.y + w->rect.h - 1;
+ GradientBar_Paint(&r, w->borderColor);
+ }
+
+}
+
+
+void Item_SetScreenCoords(itemDef_t *item, float x, float y) {
+
+ if (item == NULL) {
+ return;
+ }
+
+ if (item->window.border != 0) {
+ x += item->window.borderSize;
+ y += item->window.borderSize;
+ }
+
+ item->window.rect.x = x + item->window.rectClient.x;
+ item->window.rect.y = y + item->window.rectClient.y;
+ item->window.rect.w = item->window.rectClient.w;
+ item->window.rect.h = item->window.rectClient.h;
+
+ // force the text rects to recompute
+ item->textRect.w = 0;
+ item->textRect.h = 0;
+}
+
+// FIXME: consolidate this with nearby stuff
+void Item_UpdatePosition(itemDef_t *item) {
+ float x, y;
+ menuDef_t *menu;
+
+ if (item == NULL || item->parent == NULL) {
+ return;
+ }
+
+ menu = item->parent;
+
+ x = menu->window.rect.x;
+ y = menu->window.rect.y;
+
+ if (menu->window.border != 0) {
+ x += menu->window.borderSize;
+ y += menu->window.borderSize;
+ }
+
+ Item_SetScreenCoords(item, x, y);
+
+}
+
+// menus
+void Menu_UpdatePosition(menuDef_t *menu) {
+ int i;
+ float x, y;
+
+ if (menu == NULL) {
+ return;
+ }
+
+ x = menu->window.rect.x;
+ y = menu->window.rect.y;
+ if (menu->window.border != 0) {
+ x += menu->window.borderSize;
+ y += menu->window.borderSize;
+ }
+
+ for (i = 0; i < menu->itemCount; i++) {
+ Item_SetScreenCoords(menu->items[i], x, y);
+ }
+}
+
+void Menu_PostParse(menuDef_t *menu) {
+ if (menu == NULL) {
+ return;
+ }
+ if (menu->fullScreen) {
+ menu->window.rect.x = 0;
+ menu->window.rect.y = 0;
+ menu->window.rect.w = 640;
+ menu->window.rect.h = 480;
+ }
+ Menu_UpdatePosition(menu);
+}
+
+itemDef_t *Menu_ClearFocus(menuDef_t *menu) {
+ int i;
+ itemDef_t *ret = NULL;
+
+ if (menu == NULL) {
+ return NULL;
+ }
+
+ for (i = 0; i < menu->itemCount; i++) {
+ if (menu->items[i]->window.flags & WINDOW_HASFOCUS) {
+ ret = menu->items[i];
+ }
+ menu->items[i]->window.flags &= ~WINDOW_HASFOCUS;
+ if (menu->items[i]->leaveFocus) {
+ Item_RunScript(menu->items[i], menu->items[i]->leaveFocus);
+ }
+ }
+
+ return ret;
+}
+
+qboolean IsVisible(int flags) {
+ return (flags & WINDOW_VISIBLE && !(flags & WINDOW_FADINGOUT));
+}
+
+qboolean Rect_ContainsPoint(rectDef_t *rect, float x, float y) {
+ if (rect) {
+ if (x > rect->x && x < rect->x + rect->w && y > rect->y && y < rect->y + rect->h) {
+ return qtrue;
+ }
+ }
+ return qfalse;
+}
+
+int Menu_ItemsMatchingGroup(menuDef_t *menu, const char *name) {
+ int i;
+ int count = 0;
+ for (i = 0; i < menu->itemCount; i++) {
+ if (Q_stricmp(menu->items[i]->window.name, name) == 0 || (menu->items[i]->window.group && Q_stricmp(menu->items[i]->window.group, name) == 0)) {
+ count++;
+ }
+ }
+ return count;
+}
+
+itemDef_t *Menu_GetMatchingItemByNumber(menuDef_t *menu, int index, const char *name) {
+ int i;
+ int count = 0;
+ for (i = 0; i < menu->itemCount; i++) {
+ if (Q_stricmp(menu->items[i]->window.name, name) == 0 || (menu->items[i]->window.group && Q_stricmp(menu->items[i]->window.group, name) == 0)) {
+ if (count == index) {
+ return menu->items[i];
+ }
+ count++;
+ }
+ }
+ return NULL;
+}
+
+
+
+void Script_SetColor(itemDef_t *item, char **args) {
+ const char *name;
+ int i;
+ float f;
+ vec4_t *out;
+ // expecting type of color to set and 4 args for the color
+ if (String_Parse(args, &name)) {
+ out = NULL;
+ if (Q_stricmp(name, "backcolor") == 0) {
+ out = &item->window.backColor;
+ item->window.flags |= WINDOW_BACKCOLORSET;
+ } else if (Q_stricmp(name, "forecolor") == 0) {
+ out = &item->window.foreColor;
+ item->window.flags |= WINDOW_FORECOLORSET;
+ } else if (Q_stricmp(name, "bordercolor") == 0) {
+ out = &item->window.borderColor;
+ }
+
+ if (out) {
+ for (i = 0; i < 4; i++) {
+ if (!Float_Parse(args, &f)) {
+ return;
+ }
+ (*out)[i] = f;
+ }
+ }
+ }
+}
+
+void Script_SetAsset(itemDef_t *item, char **args) {
+ const char *name;
+ // expecting name to set asset to
+ if (String_Parse(args, &name)) {
+ // check for a model
+ if (item->type == ITEM_TYPE_MODEL) {
+ }
+ }
+}
+
+void Script_SetBackground(itemDef_t *item, char **args) {
+ const char *name;
+ // expecting name to set asset to
+ if (String_Parse(args, &name)) {
+ item->window.background = DC->registerShaderNoMip(name);
+ }
+}
+
+
+
+
+itemDef_t *Menu_FindItemByName(menuDef_t *menu, const char *p) {
+ int i;
+ if (menu == NULL || p == NULL) {
+ return NULL;
+ }
+
+ for (i = 0; i < menu->itemCount; i++) {
+ if (Q_stricmp(p, menu->items[i]->window.name) == 0) {
+ return menu->items[i];
+ }
+ }
+
+ return NULL;
+}
+
+void Script_SetTeamColor(itemDef_t *item, char **args) {
+ if (DC->getTeamColor) {
+ int i;
+ vec4_t color;
+ DC->getTeamColor(&color);
+ for (i = 0; i < 4; i++) {
+ item->window.backColor[i] = color[i];
+ }
+ }
+}
+
+void Script_SetItemColor(itemDef_t *item, char **args) {
+ const char *itemname;
+ const char *name;
+ vec4_t color;
+ int i;
+ vec4_t *out;
+ // expecting type of color to set and 4 args for the color
+ if (String_Parse(args, &itemname) && String_Parse(args, &name)) {
+ itemDef_t *item2;
+ int j;
+ int count = Menu_ItemsMatchingGroup(item->parent, itemname);
+
+ if (!Color_Parse(args, &color)) {
+ return;
+ }
+
+ for (j = 0; j < count; j++) {
+ item2 = Menu_GetMatchingItemByNumber(item->parent, j, itemname);
+ if (item2 != NULL) {
+ out = NULL;
+ if (Q_stricmp(name, "backcolor") == 0) {
+ out = &item2->window.backColor;
+ } else if (Q_stricmp(name, "forecolor") == 0) {
+ out = &item2->window.foreColor;
+ item2->window.flags |= WINDOW_FORECOLORSET;
+ } else if (Q_stricmp(name, "bordercolor") == 0) {
+ out = &item2->window.borderColor;
+ }
+
+ if (out) {
+ for (i = 0; i < 4; i++) {
+ (*out)[i] = color[i];
+ }
+ }
+ }
+ }
+ }
+}
+
+
+void Menu_ShowItemByName(menuDef_t *menu, const char *p, qboolean bShow) {
+ itemDef_t *item;
+ int i;
+ int count = Menu_ItemsMatchingGroup(menu, p);
+ for (i = 0; i < count; i++) {
+ item = Menu_GetMatchingItemByNumber(menu, i, p);
+ if (item != NULL) {
+ if (bShow) {
+ item->window.flags |= WINDOW_VISIBLE;
+ } else {
+ item->window.flags &= ~WINDOW_VISIBLE;
+ // stop cinematics playing in the window
+ if (item->window.cinematic >= 0) {
+ DC->stopCinematic(item->window.cinematic);
+ item->window.cinematic = -1;
+ }
+ }
+ }
+ }
+}
+
+void Menu_FadeItemByName(menuDef_t *menu, const char *p, qboolean fadeOut) {
+ itemDef_t *item;
+ int i;
+ int count = Menu_ItemsMatchingGroup(menu, p);
+ for (i = 0; i < count; i++) {
+ item = Menu_GetMatchingItemByNumber(menu, i, p);
+ if (item != NULL) {
+ if (fadeOut) {
+ item->window.flags |= (WINDOW_FADINGOUT | WINDOW_VISIBLE);
+ item->window.flags &= ~WINDOW_FADINGIN;
+ } else {
+ item->window.flags |= (WINDOW_VISIBLE | WINDOW_FADINGIN);
+ item->window.flags &= ~WINDOW_FADINGOUT;
+ }
+ }
+ }
+}
+
+menuDef_t *Menus_FindByName(const char *p) {
+ int i;
+ for (i = 0; i < menuCount; i++) {
+ if (Q_stricmp(Menus[i].window.name, p) == 0) {
+ return &Menus[i];
+ }
+ }
+ return NULL;
+}
+
+void Menus_ShowByName(const char *p) {
+ menuDef_t *menu = Menus_FindByName(p);
+ if (menu) {
+ Menus_Activate(menu);
+ }
+}
+
+void Menus_OpenByName(const char *p) {
+ Menus_ActivateByName(p);
+}
+
+static void Menu_RunCloseScript(menuDef_t *menu) {
+ if (menu && menu->window.flags & WINDOW_VISIBLE && menu->onClose) {
+ itemDef_t item;
+ item.parent = menu;
+ Item_RunScript(&item, menu->onClose);
+ }
+}
+
+void Menus_CloseByName(const char *p) {
+ menuDef_t *menu = Menus_FindByName(p);
+ if (menu != NULL) {
+ Menu_RunCloseScript(menu);
+ menu->window.flags &= ~(WINDOW_VISIBLE | WINDOW_HASFOCUS);
+ }
+}
+
+void Menus_CloseAll() {
+ int i;
+ for (i = 0; i < menuCount; i++) {
+ Menu_RunCloseScript(&Menus[i]);
+ Menus[i].window.flags &= ~(WINDOW_HASFOCUS | WINDOW_VISIBLE);
+ }
+}
+
+
+void Script_Show(itemDef_t *item, char **args) {
+ const char *name;
+ if (String_Parse(args, &name)) {
+ Menu_ShowItemByName(item->parent, name, qtrue);
+ }
+}
+
+void Script_Hide(itemDef_t *item, char **args) {
+ const char *name;
+ if (String_Parse(args, &name)) {
+ Menu_ShowItemByName(item->parent, name, qfalse);
+ }
+}
+
+void Script_FadeIn(itemDef_t *item, char **args) {
+ const char *name;
+ if (String_Parse(args, &name)) {
+ Menu_FadeItemByName(item->parent, name, qfalse);
+ }
+}
+
+void Script_FadeOut(itemDef_t *item, char **args) {
+ const char *name;
+ if (String_Parse(args, &name)) {
+ Menu_FadeItemByName(item->parent, name, qtrue);
+ }
+}
+
+
+
+void Script_Open(itemDef_t *item, char **args) {
+ const char *name;
+ if (String_Parse(args, &name)) {
+ Menus_OpenByName(name);
+ }
+}
+
+void Script_ConditionalOpen(itemDef_t *item, char **args) {
+ const char *cvar;
+ const char *name1;
+ const char *name2;
+ float val;
+
+ if ( String_Parse(args, &cvar) && String_Parse(args, &name1) && String_Parse(args, &name2) ) {
+ val = DC->getCVarValue( cvar );
+ if ( val == 0.f ) {
+ Menus_OpenByName(name2);
+ } else {
+ Menus_OpenByName(name1);
+ }
+ }
+}
+
+void Script_Close(itemDef_t *item, char **args) {
+ const char *name;
+ if (String_Parse(args, &name)) {
+ Menus_CloseByName(name);
+ }
+}
+
+void Menu_TransitionItemByName(menuDef_t *menu, const char *p, rectDef_t rectFrom, rectDef_t rectTo, int time, float amt) {
+ itemDef_t *item;
+ int i;
+ int count = Menu_ItemsMatchingGroup(menu, p);
+ for (i = 0; i < count; i++) {
+ item = Menu_GetMatchingItemByNumber(menu, i, p);
+ if (item != NULL) {
+ item->window.flags |= (WINDOW_INTRANSITION | WINDOW_VISIBLE);
+ item->window.offsetTime = time;
+ memcpy(&item->window.rectClient, &rectFrom, sizeof(rectDef_t));
+ memcpy(&item->window.rectEffects, &rectTo, sizeof(rectDef_t));
+ item->window.rectEffects2.x = abs(rectTo.x - rectFrom.x) / amt;
+ item->window.rectEffects2.y = abs(rectTo.y - rectFrom.y) / amt;
+ item->window.rectEffects2.w = abs(rectTo.w - rectFrom.w) / amt;
+ item->window.rectEffects2.h = abs(rectTo.h - rectFrom.h) / amt;
+ Item_UpdatePosition(item);
+ }
+ }
+}
+
+
+void Script_Transition(itemDef_t *item, char **args) {
+ const char *name;
+ rectDef_t rectFrom, rectTo;
+ int time;
+ float amt;
+
+ if (String_Parse(args, &name)) {
+ if ( Rect_Parse(args, &rectFrom) && Rect_Parse(args, &rectTo) && Int_Parse(args, &time) && Float_Parse(args, &amt)) {
+ Menu_TransitionItemByName(item->parent, name, rectFrom, rectTo, time, amt);
+ }
+ }
+}
+
+
+void Menu_OrbitItemByName(menuDef_t *menu, const char *p, float x, float y, float cx, float cy, int time) {
+ itemDef_t *item;
+ int i;
+ int count = Menu_ItemsMatchingGroup(menu, p);
+ for (i = 0; i < count; i++) {
+ item = Menu_GetMatchingItemByNumber(menu, i, p);
+ if (item != NULL) {
+ item->window.flags |= (WINDOW_ORBITING | WINDOW_VISIBLE);
+ item->window.offsetTime = time;
+ item->window.rectEffects.x = cx;
+ item->window.rectEffects.y = cy;
+ item->window.rectClient.x = x;
+ item->window.rectClient.y = y;
+ Item_UpdatePosition(item);
+ }
+ }
+}
+
+
+void Script_Orbit(itemDef_t *item, char **args) {
+ const char *name;
+ float cx, cy, x, y;
+ int time;
+
+ if (String_Parse(args, &name)) {
+ if ( Float_Parse(args, &x) && Float_Parse(args, &y) && Float_Parse(args, &cx) && Float_Parse(args, &cy) && Int_Parse(args, &time) ) {
+ Menu_OrbitItemByName(item->parent, name, x, y, cx, cy, time);
+ }
+ }
+}
+
+
+
+void Script_SetFocus(itemDef_t *item, char **args) {
+ const char *name;
+ itemDef_t *focusItem;
+
+ if (String_Parse(args, &name)) {
+ focusItem = Menu_FindItemByName(item->parent, name);
+ if (focusItem && !(focusItem->window.flags & WINDOW_DECORATION) && !(focusItem->window.flags & WINDOW_HASFOCUS)) {
+ Menu_ClearFocus(item->parent);
+ focusItem->window.flags |= WINDOW_HASFOCUS;
+ if (focusItem->onFocus) {
+ Item_RunScript(focusItem, focusItem->onFocus);
+ }
+ if (DC->Assets.itemFocusSound) {
+ DC->startLocalSound( DC->Assets.itemFocusSound, CHAN_LOCAL_SOUND );
+ }
+ }
+ }
+}
+
+void Script_SetPlayerModel(itemDef_t *item, char **args) {
+ const char *name;
+ if (String_Parse(args, &name)) {
+ DC->setCVar("team_model", name);
+ }
+}
+
+void Script_SetPlayerHead(itemDef_t *item, char **args) {
+ const char *name;
+ if (String_Parse(args, &name)) {
+ DC->setCVar("team_headmodel", name);
+ }
+}
+
+void Script_SetCvar(itemDef_t *item, char **args) {
+ const char *cvar, *val;
+ if (String_Parse(args, &cvar) && String_Parse(args, &val)) {
+ DC->setCVar(cvar, val);
+ }
+
+}
+
+void Script_Exec(itemDef_t *item, char **args) {
+ const char *val;
+ if (String_Parse(args, &val)) {
+ DC->executeText(EXEC_APPEND, va("%s ; ", val));
+ }
+}
+
+void Script_Play(itemDef_t *item, char **args) {
+ const char *val;
+ if (String_Parse(args, &val)) {
+ DC->startLocalSound(DC->registerSound(val, qfalse), CHAN_LOCAL_SOUND);
+ }
+}
+
+void Script_playLooped(itemDef_t *item, char **args) {
+ const char *val;
+ if (String_Parse(args, &val)) {
+ DC->stopBackgroundTrack();
+ DC->startBackgroundTrack(val, val);
+ }
+}
+
+
+commandDef_t commandList[] =
+{
+ {"fadein", &Script_FadeIn}, // group/name
+ {"fadeout", &Script_FadeOut}, // group/name
+ {"show", &Script_Show}, // group/name
+ {"hide", &Script_Hide}, // group/name
+ {"setcolor", &Script_SetColor}, // works on this
+ {"open", &Script_Open}, // menu
+ {"conditionalopen", &Script_ConditionalOpen}, // menu
+ {"close", &Script_Close}, // menu
+ {"setasset", &Script_SetAsset}, // works on this
+ {"setbackground", &Script_SetBackground}, // works on this
+ {"setitemcolor", &Script_SetItemColor}, // group/name
+ {"setteamcolor", &Script_SetTeamColor}, // sets this background color to team color
+ {"setfocus", &Script_SetFocus}, // sets this background color to team color
+ {"setplayermodel", &Script_SetPlayerModel}, // sets this background color to team color
+ {"setplayerhead", &Script_SetPlayerHead}, // sets this background color to team color
+ {"transition", &Script_Transition}, // group/name
+ {"setcvar", &Script_SetCvar}, // group/name
+ {"exec", &Script_Exec}, // group/name
+ {"play", &Script_Play}, // group/name
+ {"playlooped", &Script_playLooped}, // group/name
+ {"orbit", &Script_Orbit} // group/name
+};
+
+int scriptCommandCount = sizeof(commandList) / sizeof(commandDef_t);
+
+
+void Item_RunScript(itemDef_t *item, const char *s) {
+ char script[1024], *p;
+ int i;
+ qboolean bRan;
+ memset(script, 0, sizeof(script));
+ if (item && s && s[0]) {
+ Q_strcat(script, 1024, s);
+ p = script;
+ while (1) {
+ const char *command;
+ // expect command then arguments, ; ends command, NULL ends script
+ if (!String_Parse(&p, &command)) {
+ return;
+ }
+
+ if (command[0] == ';' && command[1] == '\0') {
+ continue;
+ }
+
+ bRan = qfalse;
+ for (i = 0; i < scriptCommandCount; i++) {
+ if (Q_stricmp(command, commandList[i].name) == 0) {
+ (commandList[i].handler(item, &p));
+ bRan = qtrue;
+ break;
+ }
+ }
+ // not in our auto list, pass to handler
+ if (!bRan) {
+ DC->runScript(&p);
+ }
+ }
+ }
+}
+
+
+qboolean Item_EnableShowViaCvar(itemDef_t *item, int flag) {
+ char script[1024], *p;
+ memset(script, 0, sizeof(script));
+ if (item && item->enableCvar && *item->enableCvar && item->cvarTest && *item->cvarTest) {
+ char buff[1024];
+ DC->getCVarString(item->cvarTest, buff, sizeof(buff));
+
+ Q_strcat(script, 1024, item->enableCvar);
+ p = script;
+ while (1) {
+ const char *val;
+ // expect value then ; or NULL, NULL ends list
+ if (!String_Parse(&p, &val)) {
+ return (item->cvarFlags & flag) ? qfalse : qtrue;
+ }
+
+ if (val[0] == ';' && val[1] == '\0') {
+ continue;
+ }
+
+ // enable it if any of the values are true
+ if (item->cvarFlags & flag) {
+ if (Q_stricmp(buff, val) == 0) {
+ return qtrue;
+ }
+ } else {
+ // disable it if any of the values are true
+ if (Q_stricmp(buff, val) == 0) {
+ return qfalse;
+ }
+ }
+
+ }
+ return (item->cvarFlags & flag) ? qfalse : qtrue;
+ }
+ return qtrue;
+}
+
+
+// will optionaly set focus to this item
+qboolean Item_SetFocus(itemDef_t *item, float x, float y) {
+ int i;
+ itemDef_t *oldFocus;
+ sfxHandle_t *sfx = &DC->Assets.itemFocusSound;
+ qboolean playSound = qfalse;
+ menuDef_t *parent; // bk001206: = (menuDef_t*)item->parent;
+ // sanity check, non-null, not a decoration and does not already have the focus
+ if (item == NULL || item->window.flags & WINDOW_DECORATION || item->window.flags & WINDOW_HASFOCUS || !(item->window.flags & WINDOW_VISIBLE)) {
+ return qfalse;
+ }
+
+ // bk001206 - this can be NULL.
+ parent = (menuDef_t*)item->parent;
+
+ // items can be enabled and disabled based on cvars
+ if (item->cvarFlags & (CVAR_ENABLE | CVAR_DISABLE) && !Item_EnableShowViaCvar(item, CVAR_ENABLE)) {
+ return qfalse;
+ }
+
+ if (item->cvarFlags & (CVAR_SHOW | CVAR_HIDE) && !Item_EnableShowViaCvar(item, CVAR_SHOW)) {
+ return qfalse;
+ }
+
+ oldFocus = Menu_ClearFocus(item->parent);
+
+ if (item->type == ITEM_TYPE_TEXT) {
+ rectDef_t r;
+ r = item->textRect;
+ r.y -= r.h;
+ if (Rect_ContainsPoint(&r, x, y)) {
+ item->window.flags |= WINDOW_HASFOCUS;
+ if (item->focusSound) {
+ sfx = &item->focusSound;
+ }
+ playSound = qtrue;
+ } else {
+ if (oldFocus) {
+ oldFocus->window.flags |= WINDOW_HASFOCUS;
+ if (oldFocus->onFocus) {
+ Item_RunScript(oldFocus, oldFocus->onFocus);
+ }
+ }
+ }
+ } else {
+ item->window.flags |= WINDOW_HASFOCUS;
+ if (item->onFocus) {
+ Item_RunScript(item, item->onFocus);
+ }
+ if (item->focusSound) {
+ sfx = &item->focusSound;
+ }
+ playSound = qtrue;
+ }
+
+ if (playSound && sfx) {
+ DC->startLocalSound( *sfx, CHAN_LOCAL_SOUND );
+ }
+
+ for (i = 0; i < parent->itemCount; i++) {
+ if (parent->items[i] == item) {
+ parent->cursorItem = i;
+ break;
+ }
+ }
+
+ return qtrue;
+}
+
+int Item_ListBox_MaxScroll(itemDef_t *item) {
+ listBoxDef_t *listPtr = (listBoxDef_t*)item->typeData;
+ int count = DC->feederCount(item->special);
+ int max;
+
+ if (item->window.flags & WINDOW_HORIZONTAL) {
+ max = count - (item->window.rect.w / listPtr->elementWidth) + 1;
+ }
+ else {
+ max = count - (item->window.rect.h / listPtr->elementHeight) + 1;
+ }
+ if (max < 0) {
+ return 0;
+ }
+ return max;
+}
+
+int Item_ListBox_ThumbPosition(itemDef_t *item) {
+ float max, pos, size;
+ listBoxDef_t *listPtr = (listBoxDef_t*)item->typeData;
+
+ max = Item_ListBox_MaxScroll(item);
+ if (item->window.flags & WINDOW_HORIZONTAL) {
+ size = item->window.rect.w - (SCROLLBAR_SIZE * 2) - 2;
+ if (max > 0) {
+ pos = (size-SCROLLBAR_SIZE) / (float) max;
+ } else {
+ pos = 0;
+ }
+ pos *= listPtr->startPos;
+ return item->window.rect.x + 1 + SCROLLBAR_SIZE + pos;
+ }
+ else {
+ size = item->window.rect.h - (SCROLLBAR_SIZE * 2) - 2;
+ if (max > 0) {
+ pos = (size-SCROLLBAR_SIZE) / (float) max;
+ } else {
+ pos = 0;
+ }
+ pos *= listPtr->startPos;
+ return item->window.rect.y + 1 + SCROLLBAR_SIZE + pos;
+ }
+}
+
+int Item_ListBox_ThumbDrawPosition(itemDef_t *item) {
+ int min, max;
+
+ if (itemCapture == item) {
+ if (item->window.flags & WINDOW_HORIZONTAL) {
+ min = item->window.rect.x + SCROLLBAR_SIZE + 1;
+ max = item->window.rect.x + item->window.rect.w - 2*SCROLLBAR_SIZE - 1;
+ if (DC->cursorx >= min + SCROLLBAR_SIZE/2 && DC->cursorx <= max + SCROLLBAR_SIZE/2) {
+ return DC->cursorx - SCROLLBAR_SIZE/2;
+ }
+ else {
+ return Item_ListBox_ThumbPosition(item);
+ }
+ }
+ else {
+ min = item->window.rect.y + SCROLLBAR_SIZE + 1;
+ max = item->window.rect.y + item->window.rect.h - 2*SCROLLBAR_SIZE - 1;
+ if (DC->cursory >= min + SCROLLBAR_SIZE/2 && DC->cursory <= max + SCROLLBAR_SIZE/2) {
+ return DC->cursory - SCROLLBAR_SIZE/2;
+ }
+ else {
+ return Item_ListBox_ThumbPosition(item);
+ }
+ }
+ }
+ else {
+ return Item_ListBox_ThumbPosition(item);
+ }
+}
+
+float Item_Slider_ThumbPosition(itemDef_t *item) {
+ float value, range, x;
+ editFieldDef_t *editDef = item->typeData;
+
+ if (item->text) {
+ x = item->textRect.x + item->textRect.w + 8;
+ } else {
+ x = item->window.rect.x;
+ }
+
+ if (editDef == NULL && item->cvar) {
+ return x;
+ }
+
+ value = DC->getCVarValue(item->cvar);
+
+ if (value < editDef->minVal) {
+ value = editDef->minVal;
+ } else if (value > editDef->maxVal) {
+ value = editDef->maxVal;
+ }
+
+ range = editDef->maxVal - editDef->minVal;
+ value -= editDef->minVal;
+ value /= range;
+ //value /= (editDef->maxVal - editDef->minVal);
+ value *= SLIDER_WIDTH;
+ x += value;
+ // vm fuckage
+ //x = x + (((float)value / editDef->maxVal) * SLIDER_WIDTH);
+ return x;
+}
+
+int Item_Slider_OverSlider(itemDef_t *item, float x, float y) {
+ rectDef_t r;
+
+ r.x = Item_Slider_ThumbPosition(item) - (SLIDER_THUMB_WIDTH / 2);
+ r.y = item->window.rect.y - 2;
+ r.w = SLIDER_THUMB_WIDTH;
+ r.h = SLIDER_THUMB_HEIGHT;
+
+ if (Rect_ContainsPoint(&r, x, y)) {
+ return WINDOW_LB_THUMB;
+ }
+ return 0;
+}
+
+int Item_ListBox_OverLB(itemDef_t *item, float x, float y) {
+ rectDef_t r;
+ listBoxDef_t *listPtr;
+ int thumbstart;
+ int count;
+
+ count = DC->feederCount(item->special);
+ listPtr = (listBoxDef_t*)item->typeData;
+ if (item->window.flags & WINDOW_HORIZONTAL) {
+ // check if on left arrow
+ r.x = item->window.rect.x;
+ r.y = item->window.rect.y + item->window.rect.h - SCROLLBAR_SIZE;
+ r.h = r.w = SCROLLBAR_SIZE;
+ if (Rect_ContainsPoint(&r, x, y)) {
+ return WINDOW_LB_LEFTARROW;
+ }
+ // check if on right arrow
+ r.x = item->window.rect.x + item->window.rect.w - SCROLLBAR_SIZE;
+ if (Rect_ContainsPoint(&r, x, y)) {
+ return WINDOW_LB_RIGHTARROW;
+ }
+ // check if on thumb
+ thumbstart = Item_ListBox_ThumbPosition(item);
+ r.x = thumbstart;
+ if (Rect_ContainsPoint(&r, x, y)) {
+ return WINDOW_LB_THUMB;
+ }
+ r.x = item->window.rect.x + SCROLLBAR_SIZE;
+ r.w = thumbstart - r.x;
+ if (Rect_ContainsPoint(&r, x, y)) {
+ return WINDOW_LB_PGUP;
+ }
+ r.x = thumbstart + SCROLLBAR_SIZE;
+ r.w = item->window.rect.x + item->window.rect.w - SCROLLBAR_SIZE;
+ if (Rect_ContainsPoint(&r, x, y)) {
+ return WINDOW_LB_PGDN;
+ }
+ } else {
+ r.x = item->window.rect.x + item->window.rect.w - SCROLLBAR_SIZE;
+ r.y = item->window.rect.y;
+ r.h = r.w = SCROLLBAR_SIZE;
+ if (Rect_ContainsPoint(&r, x, y)) {
+ return WINDOW_LB_LEFTARROW;
+ }
+ r.y = item->window.rect.y + item->window.rect.h - SCROLLBAR_SIZE;
+ if (Rect_ContainsPoint(&r, x, y)) {
+ return WINDOW_LB_RIGHTARROW;
+ }
+ thumbstart = Item_ListBox_ThumbPosition(item);
+ r.y = thumbstart;
+ if (Rect_ContainsPoint(&r, x, y)) {
+ return WINDOW_LB_THUMB;
+ }
+ r.y = item->window.rect.y + SCROLLBAR_SIZE;
+ r.h = thumbstart - r.y;
+ if (Rect_ContainsPoint(&r, x, y)) {
+ return WINDOW_LB_PGUP;
+ }
+ r.y = thumbstart + SCROLLBAR_SIZE;
+ r.h = item->window.rect.y + item->window.rect.h - SCROLLBAR_SIZE;
+ if (Rect_ContainsPoint(&r, x, y)) {
+ return WINDOW_LB_PGDN;
+ }
+ }
+ return 0;
+}
+
+
+void Item_ListBox_MouseEnter(itemDef_t *item, float x, float y)
+{
+ rectDef_t r;
+ listBoxDef_t *listPtr = (listBoxDef_t*)item->typeData;
+
+ item->window.flags &= ~(WINDOW_LB_LEFTARROW | WINDOW_LB_RIGHTARROW | WINDOW_LB_THUMB | WINDOW_LB_PGUP | WINDOW_LB_PGDN);
+ item->window.flags |= Item_ListBox_OverLB(item, x, y);
+
+ if (item->window.flags & WINDOW_HORIZONTAL) {
+ if (!(item->window.flags & (WINDOW_LB_LEFTARROW | WINDOW_LB_RIGHTARROW | WINDOW_LB_THUMB | WINDOW_LB_PGUP | WINDOW_LB_PGDN))) {
+ // check for selection hit as we have exausted buttons and thumb
+ if (listPtr->elementStyle == LISTBOX_IMAGE) {
+ r.x = item->window.rect.x;
+ r.y = item->window.rect.y;
+ r.h = item->window.rect.h - SCROLLBAR_SIZE;
+ r.w = item->window.rect.w - listPtr->drawPadding;
+ if (Rect_ContainsPoint(&r, x, y)) {
+ listPtr->cursorPos = (int)((x - r.x) / listPtr->elementWidth) + listPtr->startPos;
+ if (listPtr->cursorPos >= listPtr->endPos) {
+ listPtr->cursorPos = listPtr->endPos;
+ }
+ }
+ } else {
+ // text hit..
+ }
+ }
+ } else if (!(item->window.flags & (WINDOW_LB_LEFTARROW | WINDOW_LB_RIGHTARROW | WINDOW_LB_THUMB | WINDOW_LB_PGUP | WINDOW_LB_PGDN))) {
+ r.x = item->window.rect.x;
+ r.y = item->window.rect.y;
+ r.w = item->window.rect.w - SCROLLBAR_SIZE;
+ r.h = item->window.rect.h - listPtr->drawPadding;
+ if (Rect_ContainsPoint(&r, x, y)) {
+ listPtr->cursorPos = (int)((y - 2 - r.y) / listPtr->elementHeight) + listPtr->startPos;
+ if (listPtr->cursorPos > listPtr->endPos) {
+ listPtr->cursorPos = listPtr->endPos;
+ }
+ }
+ }
+}
+
+void Item_MouseEnter(itemDef_t *item, float x, float y) {
+ rectDef_t r;
+ if (item) {
+ r = item->textRect;
+ r.y -= r.h;
+ // in the text rect?
+
+ // items can be enabled and disabled based on cvars
+ if (item->cvarFlags & (CVAR_ENABLE | CVAR_DISABLE) && !Item_EnableShowViaCvar(item, CVAR_ENABLE)) {
+ return;
+ }
+
+ if (item->cvarFlags & (CVAR_SHOW | CVAR_HIDE) && !Item_EnableShowViaCvar(item, CVAR_SHOW)) {
+ return;
+ }
+
+ if (Rect_ContainsPoint(&r, x, y)) {
+ if (!(item->window.flags & WINDOW_MOUSEOVERTEXT)) {
+ Item_RunScript(item, item->mouseEnterText);
+ item->window.flags |= WINDOW_MOUSEOVERTEXT;
+ }
+ if (!(item->window.flags & WINDOW_MOUSEOVER)) {
+ Item_RunScript(item, item->mouseEnter);
+ item->window.flags |= WINDOW_MOUSEOVER;
+ }
+
+ } else {
+ // not in the text rect
+ if (item->window.flags & WINDOW_MOUSEOVERTEXT) {
+ // if we were
+ Item_RunScript(item, item->mouseExitText);
+ item->window.flags &= ~WINDOW_MOUSEOVERTEXT;
+ }
+ if (!(item->window.flags & WINDOW_MOUSEOVER)) {
+ Item_RunScript(item, item->mouseEnter);
+ item->window.flags |= WINDOW_MOUSEOVER;
+ }
+
+ if (item->type == ITEM_TYPE_LISTBOX) {
+ Item_ListBox_MouseEnter(item, x, y);
+ }
+ }
+ }
+}
+
+void Item_MouseLeave(itemDef_t *item) {
+ if (item) {
+ if (item->window.flags & WINDOW_MOUSEOVERTEXT) {
+ Item_RunScript(item, item->mouseExitText);
+ item->window.flags &= ~WINDOW_MOUSEOVERTEXT;
+ }
+ Item_RunScript(item, item->mouseExit);
+ item->window.flags &= ~(WINDOW_LB_RIGHTARROW | WINDOW_LB_LEFTARROW);
+ }
+}
+
+itemDef_t *Menu_HitTest(menuDef_t *menu, float x, float y) {
+ int i;
+ for (i = 0; i < menu->itemCount; i++) {
+ if (Rect_ContainsPoint(&menu->items[i]->window.rect, x, y)) {
+ return menu->items[i];
+ }
+ }
+ return NULL;
+}
+
+void Item_SetMouseOver(itemDef_t *item, qboolean focus) {
+ if (item) {
+ if (focus) {
+ item->window.flags |= WINDOW_MOUSEOVER;
+ } else {
+ item->window.flags &= ~WINDOW_MOUSEOVER;
+ }
+ }
+}
+
+
+qboolean Item_OwnerDraw_HandleKey(itemDef_t *item, int key) {
+ if (item && DC->ownerDrawHandleKey) {
+ return DC->ownerDrawHandleKey(item->window.ownerDraw, item->window.ownerDrawFlags, &item->special, key);
+ }
+ return qfalse;
+}
+
+qboolean Item_ListBox_HandleKey(itemDef_t *item, int key, qboolean down, qboolean force) {
+ listBoxDef_t *listPtr = (listBoxDef_t*)item->typeData;
+ int count = DC->feederCount(item->special);
+ int max, viewmax;
+
+ if (force || (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && item->window.flags & WINDOW_HASFOCUS)) {
+ max = Item_ListBox_MaxScroll(item);
+ if (item->window.flags & WINDOW_HORIZONTAL) {
+ viewmax = (item->window.rect.w / listPtr->elementWidth);
+ if ( key == K_LEFTARROW || key == K_KP_LEFTARROW )
+ {
+ if (!listPtr->notselectable) {
+ listPtr->cursorPos--;
+ if (listPtr->cursorPos < 0) {
+ listPtr->cursorPos = 0;
+ }
+ if (listPtr->cursorPos < listPtr->startPos) {
+ listPtr->startPos = listPtr->cursorPos;
+ }
+ if (listPtr->cursorPos >= listPtr->startPos + viewmax) {
+ listPtr->startPos = listPtr->cursorPos - viewmax + 1;
+ }
+ item->cursorPos = listPtr->cursorPos;
+ DC->feederSelection(item->special, item->cursorPos);
+ }
+ else {
+ listPtr->startPos--;
+ if (listPtr->startPos < 0)
+ listPtr->startPos = 0;
+ }
+ return qtrue;
+ }
+ if ( key == K_RIGHTARROW || key == K_KP_RIGHTARROW )
+ {
+ if (!listPtr->notselectable) {
+ listPtr->cursorPos++;
+ if (listPtr->cursorPos < listPtr->startPos) {
+ listPtr->startPos = listPtr->cursorPos;
+ }
+ if (listPtr->cursorPos >= count) {
+ listPtr->cursorPos = count-1;
+ }
+ if (listPtr->cursorPos >= listPtr->startPos + viewmax) {
+ listPtr->startPos = listPtr->cursorPos - viewmax + 1;
+ }
+ item->cursorPos = listPtr->cursorPos;
+ DC->feederSelection(item->special, item->cursorPos);
+ }
+ else {
+ listPtr->startPos++;
+ if (listPtr->startPos >= count)
+ listPtr->startPos = count-1;
+ }
+ return qtrue;
+ }
+ }
+ else {
+ viewmax = (item->window.rect.h / listPtr->elementHeight);
+ if ( key == K_UPARROW || key == K_KP_UPARROW )
+ {
+ if (!listPtr->notselectable) {
+ listPtr->cursorPos--;
+ if (listPtr->cursorPos < 0) {
+ listPtr->cursorPos = 0;
+ }
+ if (listPtr->cursorPos < listPtr->startPos) {
+ listPtr->startPos = listPtr->cursorPos;
+ }
+ if (listPtr->cursorPos >= listPtr->startPos + viewmax) {
+ listPtr->startPos = listPtr->cursorPos - viewmax + 1;
+ }
+ item->cursorPos = listPtr->cursorPos;
+ DC->feederSelection(item->special, item->cursorPos);
+ }
+ else {
+ listPtr->startPos--;
+ if (listPtr->startPos < 0)
+ listPtr->startPos = 0;
+ }
+ return qtrue;
+ }
+ if ( key == K_DOWNARROW || key == K_KP_DOWNARROW )
+ {
+ if (!listPtr->notselectable) {
+ listPtr->cursorPos++;
+ if (listPtr->cursorPos < listPtr->startPos) {
+ listPtr->startPos = listPtr->cursorPos;
+ }
+ if (listPtr->cursorPos >= count) {
+ listPtr->cursorPos = count-1;
+ }
+ if (listPtr->cursorPos >= listPtr->startPos + viewmax) {
+ listPtr->startPos = listPtr->cursorPos - viewmax + 1;
+ }
+ item->cursorPos = listPtr->cursorPos;
+ DC->feederSelection(item->special, item->cursorPos);
+ }
+ else {
+ listPtr->startPos++;
+ if (listPtr->startPos > max)
+ listPtr->startPos = max;
+ }
+ return qtrue;
+ }
+ }
+ // mouse hit
+ if (key == K_MOUSE1 || key == K_MOUSE2) {
+ if (item->window.flags & WINDOW_LB_LEFTARROW) {
+ listPtr->startPos--;
+ if (listPtr->startPos < 0) {
+ listPtr->startPos = 0;
+ }
+ } else if (item->window.flags & WINDOW_LB_RIGHTARROW) {
+ // one down
+ listPtr->startPos++;
+ if (listPtr->startPos > max) {
+ listPtr->startPos = max;
+ }
+ } else if (item->window.flags & WINDOW_LB_PGUP) {
+ // page up
+ listPtr->startPos -= viewmax;
+ if (listPtr->startPos < 0) {
+ listPtr->startPos = 0;
+ }
+ } else if (item->window.flags & WINDOW_LB_PGDN) {
+ // page down
+ listPtr->startPos += viewmax;
+ if (listPtr->startPos > max) {
+ listPtr->startPos = max;
+ }
+ } else if (item->window.flags & WINDOW_LB_THUMB) {
+ // Display_SetCaptureItem(item);
+ } else {
+ // select an item
+ if (DC->realTime < lastListBoxClickTime && listPtr->doubleClick) {
+ Item_RunScript(item, listPtr->doubleClick);
+ }
+ lastListBoxClickTime = DC->realTime + DOUBLE_CLICK_DELAY;
+ if (item->cursorPos != listPtr->cursorPos) {
+ item->cursorPos = listPtr->cursorPos;
+ DC->feederSelection(item->special, item->cursorPos);
+ }
+ }
+ return qtrue;
+ }
+ if ( key == K_HOME || key == K_KP_HOME) {
+ // home
+ listPtr->startPos = 0;
+ return qtrue;
+ }
+ if ( key == K_END || key == K_KP_END) {
+ // end
+ listPtr->startPos = max;
+ return qtrue;
+ }
+ if (key == K_PGUP || key == K_KP_PGUP ) {
+ // page up
+ if (!listPtr->notselectable) {
+ listPtr->cursorPos -= viewmax;
+ if (listPtr->cursorPos < 0) {
+ listPtr->cursorPos = 0;
+ }
+ if (listPtr->cursorPos < listPtr->startPos) {
+ listPtr->startPos = listPtr->cursorPos;
+ }
+ if (listPtr->cursorPos >= listPtr->startPos + viewmax) {
+ listPtr->startPos = listPtr->cursorPos - viewmax + 1;
+ }
+ item->cursorPos = listPtr->cursorPos;
+ DC->feederSelection(item->special, item->cursorPos);
+ }
+ else {
+ listPtr->startPos -= viewmax;
+ if (listPtr->startPos < 0) {
+ listPtr->startPos = 0;
+ }
+ }
+ return qtrue;
+ }
+ if ( key == K_PGDN || key == K_KP_PGDN ) {
+ // page down
+ if (!listPtr->notselectable) {
+ listPtr->cursorPos += viewmax;
+ if (listPtr->cursorPos < listPtr->startPos) {
+ listPtr->startPos = listPtr->cursorPos;
+ }
+ if (listPtr->cursorPos >= count) {
+ listPtr->cursorPos = count-1;
+ }
+ if (listPtr->cursorPos >= listPtr->startPos + viewmax) {
+ listPtr->startPos = listPtr->cursorPos - viewmax + 1;
+ }
+ item->cursorPos = listPtr->cursorPos;
+ DC->feederSelection(item->special, item->cursorPos);
+ }
+ else {
+ listPtr->startPos += viewmax;
+ if (listPtr->startPos > max) {
+ listPtr->startPos = max;
+ }
+ }
+ return qtrue;
+ }
+ }
+ return qfalse;
+}
+
+qboolean Item_YesNo_HandleKey(itemDef_t *item, int key) {
+
+ if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && item->window.flags & WINDOW_HASFOCUS && item->cvar) {
+ if (key == K_MOUSE1 || key == K_ENTER || key == K_MOUSE2 || key == K_MOUSE3) {
+ DC->setCVar(item->cvar, va("%i", !DC->getCVarValue(item->cvar)));
+ return qtrue;
+ }
+ }
+
+ return qfalse;
+
+}
+
+int Item_Multi_CountSettings(itemDef_t *item) {
+ multiDef_t *multiPtr = (multiDef_t*)item->typeData;
+ if (multiPtr == NULL) {
+ return 0;
+ }
+ return multiPtr->count;
+}
+
+int Item_Multi_FindCvarByValue(itemDef_t *item) {
+ char buff[1024];
+ float value = 0;
+ int i;
+ multiDef_t *multiPtr = (multiDef_t*)item->typeData;
+ if (multiPtr) {
+ if (multiPtr->strDef) {
+ DC->getCVarString(item->cvar, buff, sizeof(buff));
+ } else {
+ value = DC->getCVarValue(item->cvar);
+ }
+ for (i = 0; i < multiPtr->count; i++) {
+ if (multiPtr->strDef) {
+ if (Q_stricmp(buff, multiPtr->cvarStr[i]) == 0) {
+ return i;
+ }
+ } else {
+ if (multiPtr->cvarValue[i] == value) {
+ return i;
+ }
+ }
+ }
+ }
+ return 0;
+}
+
+const char *Item_Multi_Setting(itemDef_t *item) {
+ char buff[1024];
+ float value = 0;
+ int i;
+ multiDef_t *multiPtr = (multiDef_t*)item->typeData;
+ if (multiPtr) {
+ if (multiPtr->strDef) {
+ DC->getCVarString(item->cvar, buff, sizeof(buff));
+ } else {
+ value = DC->getCVarValue(item->cvar);
+ }
+ for (i = 0; i < multiPtr->count; i++) {
+ if (multiPtr->strDef) {
+ if (Q_stricmp(buff, multiPtr->cvarStr[i]) == 0) {
+ return multiPtr->cvarList[i];
+ }
+ } else {
+ if (multiPtr->cvarValue[i] == value) {
+ return multiPtr->cvarList[i];
+ }
+ }
+ }
+ }
+ return "";
+}
+
+qboolean Item_Multi_HandleKey(itemDef_t *item, int key) {
+ multiDef_t *multiPtr = (multiDef_t*)item->typeData;
+ if (multiPtr) {
+ if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && item->window.flags & WINDOW_HASFOCUS && item->cvar) {
+ if (key == K_MOUSE1 || key == K_ENTER || key == K_MOUSE2 || key == K_MOUSE3) {
+ int current = Item_Multi_FindCvarByValue(item) + 1;
+ int max = Item_Multi_CountSettings(item);
+ if ( current < 0 || current >= max ) {
+ current = 0;
+ }
+ if (multiPtr->strDef) {
+ DC->setCVar(item->cvar, multiPtr->cvarStr[current]);
+ } else {
+ float value = multiPtr->cvarValue[current];
+ if (((float)((int) value)) == value) {
+ DC->setCVar(item->cvar, va("%i", (int) value ));
+ }
+ else {
+ DC->setCVar(item->cvar, va("%f", value ));
+ }
+ }
+ return qtrue;
+ }
+ }
+ }
+ return qfalse;
+}
+
+qboolean Item_TextField_HandleKey(itemDef_t *item, int key) {
+ char buff[1024];
+ int len;
+ itemDef_t *newItem = NULL;
+ editFieldDef_t *editPtr = (editFieldDef_t*)item->typeData;
+
+ if (item->cvar) {
+
+ memset(buff, 0, sizeof(buff));
+ DC->getCVarString(item->cvar, buff, sizeof(buff));
+ len = strlen(buff);
+ if (editPtr->maxChars && len > editPtr->maxChars) {
+ len = editPtr->maxChars;
+ }
+ if ( key & K_CHAR_FLAG ) {
+ key &= ~K_CHAR_FLAG;
+
+
+ if (key == 'h' - 'a' + 1 ) { // ctrl-h is backspace
+ if ( item->cursorPos > 0 ) {
+ memmove( &buff[item->cursorPos - 1], &buff[item->cursorPos], len + 1 - item->cursorPos);
+ item->cursorPos--;
+ if (item->cursorPos < editPtr->paintOffset) {
+ editPtr->paintOffset--;
+ }
+ }
+ DC->setCVar(item->cvar, buff);
+ return qtrue;
+ }
+
+
+ //
+ // ignore any non printable chars
+ //
+ if ( key < 32 || !item->cvar) {
+ return qtrue;
+ }
+
+ if (item->type == ITEM_TYPE_NUMERICFIELD) {
+ if (key < '0' || key > '9') {
+ return qfalse;
+ }
+ }
+
+ if (!DC->getOverstrikeMode()) {
+ if (( len == MAX_EDITFIELD - 1 ) || (editPtr->maxChars && len >= editPtr->maxChars)) {
+ return qtrue;
+ }
+ memmove( &buff[item->cursorPos + 1], &buff[item->cursorPos], len + 1 - item->cursorPos );
+ } else {
+ if (editPtr->maxChars && item->cursorPos >= editPtr->maxChars) {
+ return qtrue;
+ }
+ }
+
+ buff[item->cursorPos] = key;
+
+ DC->setCVar(item->cvar, buff);
+
+ if (item->cursorPos < len + 1) {
+ item->cursorPos++;
+ if (editPtr->maxPaintChars && item->cursorPos > editPtr->maxPaintChars) {
+ editPtr->paintOffset++;
+ }
+ }
+
+ } else {
+
+ if ( key == K_DEL || key == K_KP_DEL ) {
+ if ( item->cursorPos < len ) {
+ memmove( buff + item->cursorPos, buff + item->cursorPos + 1, len - item->cursorPos);
+ DC->setCVar(item->cvar, buff);
+ }
+ return qtrue;
+ }
+
+ if ( key == K_RIGHTARROW || key == K_KP_RIGHTARROW )
+ {
+ if (editPtr->maxPaintChars && item->cursorPos >= editPtr->maxPaintChars && item->cursorPos < len) {
+ item->cursorPos++;
+ editPtr->paintOffset++;
+ return qtrue;
+ }
+ if (item->cursorPos < len) {
+ item->cursorPos++;
+ }
+ return qtrue;
+ }
+
+ if ( key == K_LEFTARROW || key == K_KP_LEFTARROW )
+ {
+ if ( item->cursorPos > 0 ) {
+ item->cursorPos--;
+ }
+ if (item->cursorPos < editPtr->paintOffset) {
+ editPtr->paintOffset--;
+ }
+ return qtrue;
+ }
+
+ if ( key == K_HOME || key == K_KP_HOME) {// || ( tolower(key) == 'a' && trap_Key_IsDown( K_CTRL ) ) ) {
+ item->cursorPos = 0;
+ editPtr->paintOffset = 0;
+ return qtrue;
+ }
+
+ if ( key == K_END || key == K_KP_END) {// ( tolower(key) == 'e' && trap_Key_IsDown( K_CTRL ) ) ) {
+ item->cursorPos = len;
+ if(item->cursorPos > editPtr->maxPaintChars) {
+ editPtr->paintOffset = len - editPtr->maxPaintChars;
+ }
+ return qtrue;
+ }
+
+ if ( key == K_INS || key == K_KP_INS ) {
+ DC->setOverstrikeMode(!DC->getOverstrikeMode());
+ return qtrue;
+ }
+ }
+
+ if (key == K_TAB || key == K_DOWNARROW || key == K_KP_DOWNARROW) {
+ newItem = Menu_SetNextCursorItem(item->parent);
+ if (newItem && (newItem->type == ITEM_TYPE_EDITFIELD || newItem->type == ITEM_TYPE_NUMERICFIELD)) {
+ g_editItem = newItem;
+ }
+ }
+
+ if (key == K_UPARROW || key == K_KP_UPARROW) {
+ newItem = Menu_SetPrevCursorItem(item->parent);
+ if (newItem && (newItem->type == ITEM_TYPE_EDITFIELD || newItem->type == ITEM_TYPE_NUMERICFIELD)) {
+ g_editItem = newItem;
+ }
+ }
+
+ if ( key == K_ENTER || key == K_KP_ENTER || key == K_ESCAPE) {
+ return qfalse;
+ }
+
+ return qtrue;
+ }
+ return qfalse;
+
+}
+
+static void Scroll_ListBox_AutoFunc(void *p) {
+ scrollInfo_t *si = (scrollInfo_t*)p;
+ if (DC->realTime > si->nextScrollTime) {
+ // need to scroll which is done by simulating a click to the item
+ // this is done a bit sideways as the autoscroll "knows" that the item is a listbox
+ // so it calls it directly
+ Item_ListBox_HandleKey(si->item, si->scrollKey, qtrue, qfalse);
+ si->nextScrollTime = DC->realTime + si->adjustValue;
+ }
+
+ if (DC->realTime > si->nextAdjustTime) {
+ si->nextAdjustTime = DC->realTime + SCROLL_TIME_ADJUST;
+ if (si->adjustValue > SCROLL_TIME_FLOOR) {
+ si->adjustValue -= SCROLL_TIME_ADJUSTOFFSET;
+ }
+ }
+}
+
+static void Scroll_ListBox_ThumbFunc(void *p) {
+ scrollInfo_t *si = (scrollInfo_t*)p;
+ rectDef_t r;
+ int pos, max;
+
+ listBoxDef_t *listPtr = (listBoxDef_t*)si->item->typeData;
+ if (si->item->window.flags & WINDOW_HORIZONTAL) {
+ if (DC->cursorx == si->xStart) {
+ return;
+ }
+ r.x = si->item->window.rect.x + SCROLLBAR_SIZE + 1;
+ r.y = si->item->window.rect.y + si->item->window.rect.h - SCROLLBAR_SIZE - 1;
+ r.h = SCROLLBAR_SIZE;
+ r.w = si->item->window.rect.w - (SCROLLBAR_SIZE*2) - 2;
+ max = Item_ListBox_MaxScroll(si->item);
+ //
+ pos = (DC->cursorx - r.x - SCROLLBAR_SIZE/2) * max / (r.w - SCROLLBAR_SIZE);
+ if (pos < 0) {
+ pos = 0;
+ }
+ else if (pos > max) {
+ pos = max;
+ }
+ listPtr->startPos = pos;
+ si->xStart = DC->cursorx;
+ }
+ else if (DC->cursory != si->yStart) {
+
+ r.x = si->item->window.rect.x + si->item->window.rect.w - SCROLLBAR_SIZE - 1;
+ r.y = si->item->window.rect.y + SCROLLBAR_SIZE + 1;
+ r.h = si->item->window.rect.h - (SCROLLBAR_SIZE*2) - 2;
+ r.w = SCROLLBAR_SIZE;
+ max = Item_ListBox_MaxScroll(si->item);
+ //
+ pos = (DC->cursory - r.y - SCROLLBAR_SIZE/2) * max / (r.h - SCROLLBAR_SIZE);
+ if (pos < 0) {
+ pos = 0;
+ }
+ else if (pos > max) {
+ pos = max;
+ }
+ listPtr->startPos = pos;
+ si->yStart = DC->cursory;
+ }
+
+ if (DC->realTime > si->nextScrollTime) {
+ // need to scroll which is done by simulating a click to the item
+ // this is done a bit sideways as the autoscroll "knows" that the item is a listbox
+ // so it calls it directly
+ Item_ListBox_HandleKey(si->item, si->scrollKey, qtrue, qfalse);
+ si->nextScrollTime = DC->realTime + si->adjustValue;
+ }
+
+ if (DC->realTime > si->nextAdjustTime) {
+ si->nextAdjustTime = DC->realTime + SCROLL_TIME_ADJUST;
+ if (si->adjustValue > SCROLL_TIME_FLOOR) {
+ si->adjustValue -= SCROLL_TIME_ADJUSTOFFSET;
+ }
+ }
+}
+
+static void Scroll_Slider_ThumbFunc(void *p) {
+ float x, value, cursorx;
+ scrollInfo_t *si = (scrollInfo_t*)p;
+ editFieldDef_t *editDef = si->item->typeData;
+
+ if (si->item->text) {
+ x = si->item->textRect.x + si->item->textRect.w + 8;
+ } else {
+ x = si->item->window.rect.x;
+ }
+
+ cursorx = DC->cursorx;
+
+ if (cursorx < x) {
+ cursorx = x;
+ } else if (cursorx > x + SLIDER_WIDTH) {
+ cursorx = x + SLIDER_WIDTH;
+ }
+ value = cursorx - x;
+ value /= SLIDER_WIDTH;
+ value *= (editDef->maxVal - editDef->minVal);
+ value += editDef->minVal;
+ DC->setCVar(si->item->cvar, va("%f", value));
+}
+
+void Item_StartCapture(itemDef_t *item, int key) {
+ int flags;
+ switch (item->type) {
+ case ITEM_TYPE_EDITFIELD:
+ case ITEM_TYPE_NUMERICFIELD:
+
+ case ITEM_TYPE_LISTBOX:
+ {
+ flags = Item_ListBox_OverLB(item, DC->cursorx, DC->cursory);
+ if (flags & (WINDOW_LB_LEFTARROW | WINDOW_LB_RIGHTARROW)) {
+ scrollInfo.nextScrollTime = DC->realTime + SCROLL_TIME_START;
+ scrollInfo.nextAdjustTime = DC->realTime + SCROLL_TIME_ADJUST;
+ scrollInfo.adjustValue = SCROLL_TIME_START;
+ scrollInfo.scrollKey = key;
+ scrollInfo.scrollDir = (flags & WINDOW_LB_LEFTARROW) ? qtrue : qfalse;
+ scrollInfo.item = item;
+ captureData = &scrollInfo;
+ captureFunc = &Scroll_ListBox_AutoFunc;
+ itemCapture = item;
+ } else if (flags & WINDOW_LB_THUMB) {
+ scrollInfo.scrollKey = key;
+ scrollInfo.item = item;
+ scrollInfo.xStart = DC->cursorx;
+ scrollInfo.yStart = DC->cursory;
+ captureData = &scrollInfo;
+ captureFunc = &Scroll_ListBox_ThumbFunc;
+ itemCapture = item;
+ }
+ break;
+ }
+ case ITEM_TYPE_SLIDER:
+ {
+ flags = Item_Slider_OverSlider(item, DC->cursorx, DC->cursory);
+ if (flags & WINDOW_LB_THUMB) {
+ scrollInfo.scrollKey = key;
+ scrollInfo.item = item;
+ scrollInfo.xStart = DC->cursorx;
+ scrollInfo.yStart = DC->cursory;
+ captureData = &scrollInfo;
+ captureFunc = &Scroll_Slider_ThumbFunc;
+ itemCapture = item;
+ }
+ break;
+ }
+ }
+}
+
+void Item_StopCapture(itemDef_t *item) {
+
+}
+
+qboolean Item_Slider_HandleKey(itemDef_t *item, int key, qboolean down) {
+ float x, value, width, work;
+
+ //DC->Print("slider handle key\n");
+ if (item->window.flags & WINDOW_HASFOCUS && item->cvar && Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory)) {
+ if (key == K_MOUSE1 || key == K_ENTER || key == K_MOUSE2 || key == K_MOUSE3) {
+ editFieldDef_t *editDef = item->typeData;
+ if (editDef) {
+ rectDef_t testRect;
+ width = SLIDER_WIDTH;
+ if (item->text) {
+ x = item->textRect.x + item->textRect.w + 8;
+ } else {
+ x = item->window.rect.x;
+ }
+
+ testRect = item->window.rect;
+ testRect.x = x;
+ value = (float)SLIDER_THUMB_WIDTH / 2;
+ testRect.x -= value;
+ //DC->Print("slider x: %f\n", testRect.x);
+ testRect.w = (SLIDER_WIDTH + (float)SLIDER_THUMB_WIDTH / 2);
+ //DC->Print("slider w: %f\n", testRect.w);
+ if (Rect_ContainsPoint(&testRect, DC->cursorx, DC->cursory)) {
+ work = DC->cursorx - x;
+ value = work / width;
+ value *= (editDef->maxVal - editDef->minVal);
+ // vm fuckage
+ // value = (((float)(DC->cursorx - x)/ SLIDER_WIDTH) * (editDef->maxVal - editDef->minVal));
+ value += editDef->minVal;
+ DC->setCVar(item->cvar, va("%f", value));
+ return qtrue;
+ }
+ }
+ }
+ }
+ DC->Print("slider handle key exit\n");
+ return qfalse;
+}
+
+
+qboolean Item_HandleKey(itemDef_t *item, int key, qboolean down) {
+
+ if (itemCapture) {
+ Item_StopCapture(itemCapture);
+ itemCapture = NULL;
+ captureFunc = NULL;
+ captureData = NULL;
+ } else {
+ // bk001206 - parentheses
+ if ( down && ( key == K_MOUSE1 || key == K_MOUSE2 || key == K_MOUSE3 ) ) {
+ Item_StartCapture(item, key);
+ }
+ }
+
+ if (!down) {
+ return qfalse;
+ }
+
+ switch (item->type) {
+ case ITEM_TYPE_BUTTON:
+ return qfalse;
+ break;
+ case ITEM_TYPE_RADIOBUTTON:
+ return qfalse;
+ break;
+ case ITEM_TYPE_CHECKBOX:
+ return qfalse;
+ break;
+ case ITEM_TYPE_EDITFIELD:
+ case ITEM_TYPE_NUMERICFIELD:
+ //return Item_TextField_HandleKey(item, key);
+ return qfalse;
+ break;
+ case ITEM_TYPE_COMBO:
+ return qfalse;
+ break;
+ case ITEM_TYPE_LISTBOX:
+ return Item_ListBox_HandleKey(item, key, down, qfalse);
+ break;
+ case ITEM_TYPE_YESNO:
+ return Item_YesNo_HandleKey(item, key);
+ break;
+ case ITEM_TYPE_MULTI:
+ return Item_Multi_HandleKey(item, key);
+ break;
+ case ITEM_TYPE_OWNERDRAW:
+ return Item_OwnerDraw_HandleKey(item, key);
+ break;
+ case ITEM_TYPE_BIND:
+ return Item_Bind_HandleKey(item, key, down);
+ break;
+ case ITEM_TYPE_SLIDER:
+ return Item_Slider_HandleKey(item, key, down);
+ break;
+ //case ITEM_TYPE_IMAGE:
+ // Item_Image_Paint(item);
+ // break;
+ default:
+ return qfalse;
+ break;
+ }
+
+ //return qfalse;
+}
+
+void Item_Action(itemDef_t *item) {
+ if (item) {
+ Item_RunScript(item, item->action);
+ }
+}
+
+itemDef_t *Menu_SetPrevCursorItem(menuDef_t *menu) {
+ qboolean wrapped = qfalse;
+ int oldCursor = menu->cursorItem;
+
+ if (menu->cursorItem < 0) {
+ menu->cursorItem = menu->itemCount-1;
+ wrapped = qtrue;
+ }
+
+ while (menu->cursorItem > -1) {
+
+ menu->cursorItem--;
+ if (menu->cursorItem < 0 && !wrapped) {
+ wrapped = qtrue;
+ menu->cursorItem = menu->itemCount -1;
+ }
+
+ if (Item_SetFocus(menu->items[menu->cursorItem], DC->cursorx, DC->cursory)) {
+ Menu_HandleMouseMove(menu, menu->items[menu->cursorItem]->window.rect.x + 1, menu->items[menu->cursorItem]->window.rect.y + 1);
+ return menu->items[menu->cursorItem];
+ }
+ }
+ menu->cursorItem = oldCursor;
+ return NULL;
+
+}
+
+itemDef_t *Menu_SetNextCursorItem(menuDef_t *menu) {
+
+ qboolean wrapped = qfalse;
+ int oldCursor = menu->cursorItem;
+
+
+ if (menu->cursorItem == -1) {
+ menu->cursorItem = 0;
+ wrapped = qtrue;
+ }
+
+ while (menu->cursorItem < menu->itemCount) {
+
+ menu->cursorItem++;
+ if (menu->cursorItem >= menu->itemCount && !wrapped) {
+ wrapped = qtrue;
+ menu->cursorItem = 0;
+ }
+ if (Item_SetFocus(menu->items[menu->cursorItem], DC->cursorx, DC->cursory)) {
+ Menu_HandleMouseMove(menu, menu->items[menu->cursorItem]->window.rect.x + 1, menu->items[menu->cursorItem]->window.rect.y + 1);
+ return menu->items[menu->cursorItem];
+ }
+
+ }
+
+ menu->cursorItem = oldCursor;
+ return NULL;
+}
+
+static void Window_CloseCinematic(windowDef_t *window) {
+ if (window->style == WINDOW_STYLE_CINEMATIC && window->cinematic >= 0) {
+ DC->stopCinematic(window->cinematic);
+ window->cinematic = -1;
+ }
+}
+
+static void Menu_CloseCinematics(menuDef_t *menu) {
+ if (menu) {
+ int i;
+ Window_CloseCinematic(&menu->window);
+ for (i = 0; i < menu->itemCount; i++) {
+ Window_CloseCinematic(&menu->items[i]->window);
+ if (menu->items[i]->type == ITEM_TYPE_OWNERDRAW) {
+ DC->stopCinematic(0-menu->items[i]->window.ownerDraw);
+ }
+ }
+ }
+}
+
+static void Display_CloseCinematics() {
+ int i;
+ for (i = 0; i < menuCount; i++) {
+ Menu_CloseCinematics(&Menus[i]);
+ }
+}
+
+void Menus_Activate(menuDef_t *menu) {
+ menu->window.flags |= (WINDOW_HASFOCUS | WINDOW_VISIBLE);
+ if (menu->onOpen) {
+ itemDef_t item;
+ item.parent = menu;
+ Item_RunScript(&item, menu->onOpen);
+ }
+
+ if (menu->soundName && *menu->soundName) {
+// DC->stopBackgroundTrack(); // you don't want to do this since it will reset s_rawend
+ DC->startBackgroundTrack(menu->soundName, menu->soundName);
+ }
+
+ Display_CloseCinematics();
+
+}
+
+int Display_VisibleMenuCount() {
+ int i, count;
+ count = 0;
+ for (i = 0; i < menuCount; i++) {
+ if (Menus[i].window.flags & (WINDOW_FORCED | WINDOW_VISIBLE)) {
+ count++;
+ }
+ }
+ return count;
+}
+
+void Menus_HandleOOBClick(menuDef_t *menu, int key, qboolean down) {
+ if (menu) {
+ int i;
+ // basically the behaviour we are looking for is if there are windows in the stack.. see if
+ // the cursor is within any of them.. if not close them otherwise activate them and pass the
+ // key on.. force a mouse move to activate focus and script stuff
+ if (down && menu->window.flags & WINDOW_OOB_CLICK) {
+ Menu_RunCloseScript(menu);
+ menu->window.flags &= ~(WINDOW_HASFOCUS | WINDOW_VISIBLE);
+ }
+
+ for (i = 0; i < menuCount; i++) {
+ if (Menu_OverActiveItem(&Menus[i], DC->cursorx, DC->cursory)) {
+ Menu_RunCloseScript(menu);
+ menu->window.flags &= ~(WINDOW_HASFOCUS | WINDOW_VISIBLE);
+ Menus_Activate(&Menus[i]);
+ Menu_HandleMouseMove(&Menus[i], DC->cursorx, DC->cursory);
+ Menu_HandleKey(&Menus[i], key, down);
+ }
+ }
+
+ if (Display_VisibleMenuCount() == 0) {
+ if (DC->Pause) {
+ DC->Pause(qfalse);
+ }
+ }
+ Display_CloseCinematics();
+ }
+}
+
+static rectDef_t *Item_CorrectedTextRect(itemDef_t *item) {
+ static rectDef_t rect;
+ memset(&rect, 0, sizeof(rectDef_t));
+ if (item) {
+ rect = item->textRect;
+ if (rect.w) {
+ rect.y -= rect.h;
+ }
+ }
+ return &rect;
+}
+
+void Menu_HandleKey(menuDef_t *menu, int key, qboolean down) {
+ int i;
+ itemDef_t *item = NULL;
+ qboolean inHandler = qfalse;
+
+ if (inHandler) {
+ return;
+ }
+
+ inHandler = qtrue;
+ if (g_waitingForKey && down) {
+ Item_Bind_HandleKey(g_bindItem, key, down);
+ inHandler = qfalse;
+ return;
+ }
+
+ if (g_editingField && down) {
+ if (!Item_TextField_HandleKey(g_editItem, key)) {
+ g_editingField = qfalse;
+ g_editItem = NULL;
+ inHandler = qfalse;
+ return;
+ } else if (key == K_MOUSE1 || key == K_MOUSE2 || key == K_MOUSE3) {
+ g_editingField = qfalse;
+ g_editItem = NULL;
+ Display_MouseMove(NULL, DC->cursorx, DC->cursory);
+ } else if (key == K_TAB || key == K_UPARROW || key == K_DOWNARROW) {
+ return;
+ }
+ }
+
+ if (menu == NULL) {
+ inHandler = qfalse;
+ return;
+ }
+
+ // see if the mouse is within the window bounds and if so is this a mouse click
+ if (down && !(menu->window.flags & WINDOW_POPUP) && !Rect_ContainsPoint(&menu->window.rect, DC->cursorx, DC->cursory)) {
+ static qboolean inHandleKey = qfalse;
+ // bk001206 - parentheses
+ if (!inHandleKey && ( key == K_MOUSE1 || key == K_MOUSE2 || key == K_MOUSE3 ) ) {
+ inHandleKey = qtrue;
+ Menus_HandleOOBClick(menu, key, down);
+ inHandleKey = qfalse;
+ inHandler = qfalse;
+ return;
+ }
+ }
+
+ // get the item with focus
+ for (i = 0; i < menu->itemCount; i++) {
+ if (menu->items[i]->window.flags & WINDOW_HASFOCUS) {
+ item = menu->items[i];
+ }
+ }
+
+ if (item != NULL) {
+ if (Item_HandleKey(item, key, down)) {
+ Item_Action(item);
+ inHandler = qfalse;
+ return;
+ }
+ }
+
+ if (!down) {
+ inHandler = qfalse;
+ return;
+ }
+
+ // default handling
+ switch ( key ) {
+
+ case K_F11:
+ if (DC->getCVarValue("developer")) {
+ debugMode ^= 1;
+ }
+ break;
+
+ case K_F12:
+ if (DC->getCVarValue("developer")) {
+ DC->executeText(EXEC_APPEND, "screenshot\n");
+ }
+ break;
+ case K_KP_UPARROW:
+ case K_UPARROW:
+ Menu_SetPrevCursorItem(menu);
+ break;
+
+ case K_ESCAPE:
+ if (!g_waitingForKey && menu->onESC) {
+ itemDef_t it;
+ it.parent = menu;
+ Item_RunScript(&it, menu->onESC);
+ }
+ break;
+ case K_TAB:
+ case K_KP_DOWNARROW:
+ case K_DOWNARROW:
+ Menu_SetNextCursorItem(menu);
+ break;
+
+ case K_MOUSE1:
+ case K_MOUSE2:
+ if (item) {
+ if (item->type == ITEM_TYPE_TEXT) {
+ if (Rect_ContainsPoint(Item_CorrectedTextRect(item), DC->cursorx, DC->cursory)) {
+ Item_Action(item);
+ }
+ } else if (item->type == ITEM_TYPE_EDITFIELD || item->type == ITEM_TYPE_NUMERICFIELD) {
+ if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory)) {
+ item->cursorPos = 0;
+ g_editingField = qtrue;
+ g_editItem = item;
+ DC->setOverstrikeMode(qtrue);
+ }
+ } else {
+ if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory)) {
+ Item_Action(item);
+ }
+ }
+ }
+ break;
+
+ case K_JOY1:
+ case K_JOY2:
+ case K_JOY3:
+ case K_JOY4:
+ case K_AUX1:
+ case K_AUX2:
+ case K_AUX3:
+ case K_AUX4:
+ case K_AUX5:
+ case K_AUX6:
+ case K_AUX7:
+ case K_AUX8:
+ case K_AUX9:
+ case K_AUX10:
+ case K_AUX11:
+ case K_AUX12:
+ case K_AUX13:
+ case K_AUX14:
+ case K_AUX15:
+ case K_AUX16:
+ break;
+ case K_KP_ENTER:
+ case K_ENTER:
+ if (item) {
+ if (item->type == ITEM_TYPE_EDITFIELD || item->type == ITEM_TYPE_NUMERICFIELD) {
+ item->cursorPos = 0;
+ g_editingField = qtrue;
+ g_editItem = item;
+ DC->setOverstrikeMode(qtrue);
+ } else {
+ Item_Action(item);
+ }
+ }
+ break;
+ }
+ inHandler = qfalse;
+}
+
+void ToWindowCoords(float *x, float *y, windowDef_t *window) {
+ if (window->border != 0) {
+ *x += window->borderSize;
+ *y += window->borderSize;
+ }
+ *x += window->rect.x;
+ *y += window->rect.y;
+}
+
+void Rect_ToWindowCoords(rectDef_t *rect, windowDef_t *window) {
+ ToWindowCoords(&rect->x, &rect->y, window);
+}
+
+void Item_SetTextExtents(itemDef_t *item, int *width, int *height, const char *text) {
+ const char *textPtr = (text) ? text : item->text;
+
+ if (textPtr == NULL ) {
+ return;
+ }
+
+ *width = item->textRect.w;
+ *height = item->textRect.h;
+
+ // keeps us from computing the widths and heights more than once
+ if (*width == 0 || (item->type == ITEM_TYPE_OWNERDRAW && item->textalignment == ITEM_ALIGN_CENTER)) {
+ int originalWidth = DC->textWidth(item->text, item->textscale, 0);
+
+ if (item->type == ITEM_TYPE_OWNERDRAW && (item->textalignment == ITEM_ALIGN_CENTER || item->textalignment == ITEM_ALIGN_RIGHT)) {
+ originalWidth += DC->ownerDrawWidth(item->window.ownerDraw, item->textscale);
+ } else if (item->type == ITEM_TYPE_EDITFIELD && item->textalignment == ITEM_ALIGN_CENTER && item->cvar) {
+ char buff[256];
+ DC->getCVarString(item->cvar, buff, 256);
+ originalWidth += DC->textWidth(buff, item->textscale, 0);
+ }
+
+ *width = DC->textWidth(textPtr, item->textscale, 0);
+ *height = DC->textHeight(textPtr, item->textscale, 0);
+ item->textRect.w = *width;
+ item->textRect.h = *height;
+ item->textRect.x = item->textalignx;
+ item->textRect.y = item->textaligny;
+ if (item->textalignment == ITEM_ALIGN_RIGHT) {
+ item->textRect.x = item->textalignx - originalWidth;
+ } else if (item->textalignment == ITEM_ALIGN_CENTER) {
+ item->textRect.x = item->textalignx - originalWidth / 2;
+ }
+
+ ToWindowCoords(&item->textRect.x, &item->textRect.y, &item->window);
+ }
+}
+
+void Item_TextColor(itemDef_t *item, vec4_t *newColor) {
+ vec4_t lowLight;
+ menuDef_t *parent = (menuDef_t*)item->parent;
+
+ Fade(&item->window.flags, &item->window.foreColor[3], parent->fadeClamp, &item->window.nextTime, parent->fadeCycle, qtrue, parent->fadeAmount);
+
+ if (item->window.flags & WINDOW_HASFOCUS) {
+ lowLight[0] = 0.8 * parent->focusColor[0];
+ lowLight[1] = 0.8 * parent->focusColor[1];
+ lowLight[2] = 0.8 * parent->focusColor[2];
+ lowLight[3] = 0.8 * parent->focusColor[3];
+ LerpColor(parent->focusColor,lowLight,*newColor,0.5+0.5*sin(DC->realTime / PULSE_DIVISOR));
+ } else if (item->textStyle == ITEM_TEXTSTYLE_BLINK && !((DC->realTime/BLINK_DIVISOR) & 1)) {
+ lowLight[0] = 0.8 * item->window.foreColor[0];
+ lowLight[1] = 0.8 * item->window.foreColor[1];
+ lowLight[2] = 0.8 * item->window.foreColor[2];
+ lowLight[3] = 0.8 * item->window.foreColor[3];
+ LerpColor(item->window.foreColor,lowLight,*newColor,0.5+0.5*sin(DC->realTime / PULSE_DIVISOR));
+ } else {
+ memcpy(newColor, &item->window.foreColor, sizeof(vec4_t));
+ // items can be enabled and disabled based on cvars
+ }
+
+ if (item->enableCvar && *item->enableCvar && item->cvarTest && *item->cvarTest) {
+ if (item->cvarFlags & (CVAR_ENABLE | CVAR_DISABLE) && !Item_EnableShowViaCvar(item, CVAR_ENABLE)) {
+ memcpy(newColor, &parent->disableColor, sizeof(vec4_t));
+ }
+ }
+}
+
+void Item_Text_AutoWrapped_Paint(itemDef_t *item) {
+ char text[1024];
+ const char *p, *textPtr, *newLinePtr;
+ char buff[1024];
+ int width, height, len, textWidth, newLine, newLineWidth;
+ float y;
+ vec4_t color;
+
+ textWidth = 0;
+ newLinePtr = NULL;
+
+ if (item->text == NULL) {
+ if (item->cvar == NULL) {
+ return;
+ }
+ else {
+ DC->getCVarString(item->cvar, text, sizeof(text));
+ textPtr = text;
+ }
+ }
+ else {
+ textPtr = item->text;
+ }
+ if (*textPtr == '\0') {
+ return;
+ }
+ Item_TextColor(item, &color);
+ Item_SetTextExtents(item, &width, &height, textPtr);
+
+ y = item->textaligny;
+ len = 0;
+ buff[0] = '\0';
+ newLine = 0;
+ newLineWidth = 0;
+ p = textPtr;
+ while (p) {
+ if (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\0') {
+ newLine = len;
+ newLinePtr = p+1;
+ newLineWidth = textWidth;
+ }
+ textWidth = DC->textWidth(buff, item->textscale, 0);
+ if ( (newLine && textWidth > item->window.rect.w) || *p == '\n' || *p == '\0') {
+ if (len) {
+ if (item->textalignment == ITEM_ALIGN_LEFT) {
+ item->textRect.x = item->textalignx;
+ } else if (item->textalignment == ITEM_ALIGN_RIGHT) {
+ item->textRect.x = item->textalignx - newLineWidth;
+ } else if (item->textalignment == ITEM_ALIGN_CENTER) {
+ item->textRect.x = item->textalignx - newLineWidth / 2;
+ }
+ item->textRect.y = y;
+ ToWindowCoords(&item->textRect.x, &item->textRect.y, &item->window);
+ //
+ buff[newLine] = '\0';
+ DC->drawText(item->textRect.x, item->textRect.y, item->textscale, color, buff, 0, 0, item->textStyle);
+ }
+ if (*p == '\0') {
+ break;
+ }
+ //
+ y += height + 5;
+ p = newLinePtr;
+ len = 0;
+ newLine = 0;
+ newLineWidth = 0;
+ continue;
+ }
+ buff[len++] = *p++;
+ buff[len] = '\0';
+ }
+}
+
+void Item_Text_Wrapped_Paint(itemDef_t *item) {
+ char text[1024];
+ const char *p, *start, *textPtr;
+ char buff[1024];
+ int width, height;
+ float x, y;
+ vec4_t color;
+
+ // now paint the text and/or any optional images
+ // default to left
+
+ if (item->text == NULL) {
+ if (item->cvar == NULL) {
+ return;
+ }
+ else {
+ DC->getCVarString(item->cvar, text, sizeof(text));
+ textPtr = text;
+ }
+ }
+ else {
+ textPtr = item->text;
+ }
+ if (*textPtr == '\0') {
+ return;
+ }
+
+ Item_TextColor(item, &color);
+ Item_SetTextExtents(item, &width, &height, textPtr);
+
+ x = item->textRect.x;
+ y = item->textRect.y;
+ start = textPtr;
+ p = strchr(textPtr, '\r');
+ while (p && *p) {
+ strncpy(buff, start, p-start+1);
+ buff[p-start] = '\0';
+ DC->drawText(x, y, item->textscale, color, buff, 0, 0, item->textStyle);
+ y += height + 5;
+ start += p - start + 1;
+ p = strchr(p+1, '\r');
+ }
+ DC->drawText(x, y, item->textscale, color, start, 0, 0, item->textStyle);
+}
+
+void Item_Text_Paint(itemDef_t *item) {
+ char text[1024];
+ const char *textPtr;
+ int height, width;
+ vec4_t color;
+
+ if (item->window.flags & WINDOW_WRAPPED) {
+ Item_Text_Wrapped_Paint(item);
+ return;
+ }
+ if (item->window.flags & WINDOW_AUTOWRAPPED) {
+ Item_Text_AutoWrapped_Paint(item);
+ return;
+ }
+
+ if (item->text == NULL) {
+ if (item->cvar == NULL) {
+ return;
+ }
+ else {
+ DC->getCVarString(item->cvar, text, sizeof(text));
+ textPtr = text;
+ }
+ }
+ else {
+ textPtr = item->text;
+ }
+
+ // this needs to go here as it sets extents for cvar types as well
+ Item_SetTextExtents(item, &width, &height, textPtr);
+
+ if (*textPtr == '\0') {
+ return;
+ }
+
+
+ Item_TextColor(item, &color);
+
+ //FIXME: this is a fucking mess
+/*
+ adjust = 0;
+ if (item->textStyle == ITEM_TEXTSTYLE_OUTLINED || item->textStyle == ITEM_TEXTSTYLE_OUTLINESHADOWED) {
+ adjust = 0.5;
+ }
+
+ if (item->textStyle == ITEM_TEXTSTYLE_SHADOWED || item->textStyle == ITEM_TEXTSTYLE_OUTLINESHADOWED) {
+ Fade(&item->window.flags, &DC->Assets.shadowColor[3], DC->Assets.fadeClamp, &item->window.nextTime, DC->Assets.fadeCycle, qfalse);
+ DC->drawText(item->textRect.x + DC->Assets.shadowX, item->textRect.y + DC->Assets.shadowY, item->textscale, DC->Assets.shadowColor, textPtr, adjust);
+ }
+*/
+
+
+// if (item->textStyle == ITEM_TEXTSTYLE_OUTLINED || item->textStyle == ITEM_TEXTSTYLE_OUTLINESHADOWED) {
+// Fade(&item->window.flags, &item->window.outlineColor[3], DC->Assets.fadeClamp, &item->window.nextTime, DC->Assets.fadeCycle, qfalse);
+// /*
+// Text_Paint(item->textRect.x-1, item->textRect.y-1, item->textscale, item->window.foreColor, textPtr, adjust);
+// Text_Paint(item->textRect.x, item->textRect.y-1, item->textscale, item->window.foreColor, textPtr, adjust);
+// Text_Paint(item->textRect.x+1, item->textRect.y-1, item->textscale, item->window.foreColor, textPtr, adjust);
+// Text_Paint(item->textRect.x-1, item->textRect.y, item->textscale, item->window.foreColor, textPtr, adjust);
+// Text_Paint(item->textRect.x+1, item->textRect.y, item->textscale, item->window.foreColor, textPtr, adjust);
+// Text_Paint(item->textRect.x-1, item->textRect.y+1, item->textscale, item->window.foreColor, textPtr, adjust);
+// Text_Paint(item->textRect.x, item->textRect.y+1, item->textscale, item->window.foreColor, textPtr, adjust);
+// Text_Paint(item->textRect.x+1, item->textRect.y+1, item->textscale, item->window.foreColor, textPtr, adjust);
+// */
+// DC->drawText(item->textRect.x - 1, item->textRect.y + 1, item->textscale * 1.02, item->window.outlineColor, textPtr, adjust);
+// }
+
+ DC->drawText(item->textRect.x, item->textRect.y, item->textscale, color, textPtr, 0, 0, item->textStyle);
+}
+
+
+
+//float trap_Cvar_VariableValue( const char *var_name );
+//void trap_Cvar_VariableStringBuffer( const char *var_name, char *buffer, int bufsize );
+
+void Item_TextField_Paint(itemDef_t *item) {
+ char buff[1024];
+ vec4_t newColor, lowLight;
+ int offset;
+ menuDef_t *parent = (menuDef_t*)item->parent;
+ editFieldDef_t *editPtr = (editFieldDef_t*)item->typeData;
+
+ Item_Text_Paint(item);
+
+ buff[0] = '\0';
+
+ if (item->cvar) {
+ DC->getCVarString(item->cvar, buff, sizeof(buff));
+ }
+
+ parent = (menuDef_t*)item->parent;
+
+ if (item->window.flags & WINDOW_HASFOCUS) {
+ lowLight[0] = 0.8 * parent->focusColor[0];
+ lowLight[1] = 0.8 * parent->focusColor[1];
+ lowLight[2] = 0.8 * parent->focusColor[2];
+ lowLight[3] = 0.8 * parent->focusColor[3];
+ LerpColor(parent->focusColor,lowLight,newColor,0.5+0.5*sin(DC->realTime / PULSE_DIVISOR));
+ } else {
+ memcpy(&newColor, &item->window.foreColor, sizeof(vec4_t));
+ }
+
+ offset = (item->text && *item->text) ? 8 : 0;
+ if (item->window.flags & WINDOW_HASFOCUS && g_editingField) {
+ char cursor = DC->getOverstrikeMode() ? '_' : '|';
+ DC->drawTextWithCursor(item->textRect.x + item->textRect.w + offset, item->textRect.y, item->textscale, newColor, buff + editPtr->paintOffset, item->cursorPos - editPtr->paintOffset , cursor, editPtr->maxPaintChars, item->textStyle);
+ } else {
+ DC->drawText(item->textRect.x + item->textRect.w + offset, item->textRect.y, item->textscale, newColor, buff + editPtr->paintOffset, 0, editPtr->maxPaintChars, item->textStyle);
+ }
+
+}
+
+void Item_YesNo_Paint(itemDef_t *item) {
+ vec4_t newColor, lowLight;
+ float value;
+ menuDef_t *parent = (menuDef_t*)item->parent;
+
+ value = (item->cvar) ? DC->getCVarValue(item->cvar) : 0;
+
+ if (item->window.flags & WINDOW_HASFOCUS) {
+ lowLight[0] = 0.8 * parent->focusColor[0];
+ lowLight[1] = 0.8 * parent->focusColor[1];
+ lowLight[2] = 0.8 * parent->focusColor[2];
+ lowLight[3] = 0.8 * parent->focusColor[3];
+ LerpColor(parent->focusColor,lowLight,newColor,0.5+0.5*sin(DC->realTime / PULSE_DIVISOR));
+ } else {
+ memcpy(&newColor, &item->window.foreColor, sizeof(vec4_t));
+ }
+
+ if (item->text) {
+ Item_Text_Paint(item);
+ DC->drawText(item->textRect.x + item->textRect.w + 8, item->textRect.y, item->textscale, newColor, (value != 0) ? "Yes" : "No", 0, 0, item->textStyle);
+ } else {
+ DC->drawText(item->textRect.x, item->textRect.y, item->textscale, newColor, (value != 0) ? "Yes" : "No", 0, 0, item->textStyle);
+ }
+}
+
+void Item_Multi_Paint(itemDef_t *item) {
+ vec4_t newColor, lowLight;
+ const char *text = "";
+ menuDef_t *parent = (menuDef_t*)item->parent;
+
+ if (item->window.flags & WINDOW_HASFOCUS) {
+ lowLight[0] = 0.8 * parent->focusColor[0];
+ lowLight[1] = 0.8 * parent->focusColor[1];
+ lowLight[2] = 0.8 * parent->focusColor[2];
+ lowLight[3] = 0.8 * parent->focusColor[3];
+ LerpColor(parent->focusColor,lowLight,newColor,0.5+0.5*sin(DC->realTime / PULSE_DIVISOR));
+ } else {
+ memcpy(&newColor, &item->window.foreColor, sizeof(vec4_t));
+ }
+
+ text = Item_Multi_Setting(item);
+
+ if (item->text) {
+ Item_Text_Paint(item);
+ DC->drawText(item->textRect.x + item->textRect.w + 8, item->textRect.y, item->textscale, newColor, text, 0, 0, item->textStyle);
+ } else {
+ DC->drawText(item->textRect.x, item->textRect.y, item->textscale, newColor, text, 0, 0, item->textStyle);
+ }
+}
+
+
+typedef struct {
+ char *command;
+ int id;
+ int defaultbind1;
+ int defaultbind2;
+ int bind1;
+ int bind2;
+} bind_t;
+
+typedef struct
+{
+ char* name;
+ float defaultvalue;
+ float value;
+} configcvar_t;
+
+
+static bind_t g_bindings[] =
+{
+ {"+scores", K_TAB, -1, -1, -1},
+ {"+button2", K_ENTER, -1, -1, -1},
+ {"+speed", K_SHIFT, -1, -1, -1},
+ {"+forward", K_UPARROW, -1, -1, -1},
+ {"+back", K_DOWNARROW, -1, -1, -1},
+ {"+moveleft", ',', -1, -1, -1},
+ {"+moveright", '.', -1, -1, -1},
+ {"+moveup", K_SPACE, -1, -1, -1},
+ {"+movedown", 'c', -1, -1, -1},
+ {"+left", K_LEFTARROW, -1, -1, -1},
+ {"+right", K_RIGHTARROW, -1, -1, -1},
+ {"+strafe", K_ALT, -1, -1, -1},
+ {"+lookup", K_PGDN, -1, -1, -1},
+ {"+lookdown", K_DEL, -1, -1, -1},
+ {"+mlook", '/', -1, -1, -1},
+ {"centerview", K_END, -1, -1, -1},
+ {"+zoom", -1, -1, -1, -1},
+ {"weapon 1", '1', -1, -1, -1},
+ {"weapon 2", '2', -1, -1, -1},
+ {"weapon 3", '3', -1, -1, -1},
+ {"weapon 4", '4', -1, -1, -1},
+ {"weapon 5", '5', -1, -1, -1},
+ {"weapon 6", '6', -1, -1, -1},
+ {"weapon 7", '7', -1, -1, -1},
+ {"weapon 8", '8', -1, -1, -1},
+ {"weapon 9", '9', -1, -1, -1},
+ {"weapon 10", '0', -1, -1, -1},
+ {"weapon 11", -1, -1, -1, -1},
+ {"weapon 12", -1, -1, -1, -1},
+ {"weapon 13", -1, -1, -1, -1},
+ {"+attack", K_CTRL, -1, -1, -1},
+ {"weapprev", '[', -1, -1, -1},
+ {"weapnext", ']', -1, -1, -1},
+ {"+button3", K_MOUSE3, -1, -1, -1},
+ {"+button4", K_MOUSE4, -1, -1, -1},
+ {"prevTeamMember", 'w', -1, -1, -1},
+ {"nextTeamMember", 'r', -1, -1, -1},
+ {"nextOrder", 't', -1, -1, -1},
+ {"confirmOrder", 'y', -1, -1, -1},
+ {"denyOrder", 'n', -1, -1, -1},
+ {"taskOffense", 'o', -1, -1, -1},
+ {"taskDefense", 'd', -1, -1, -1},
+ {"taskPatrol", 'p', -1, -1, -1},
+ {"taskCamp", 'c', -1, -1, -1},
+ {"taskFollow", 'f', -1, -1, -1},
+ {"taskRetrieve", 'v', -1, -1, -1},
+ {"taskEscort", 'e', -1, -1, -1},
+ {"taskOwnFlag", 'i', -1, -1, -1},
+ {"taskSuicide", 'k', -1, -1, -1},
+ {"tauntKillInsult", K_F1, -1, -1, -1},
+ {"tauntPraise", K_F2, -1, -1, -1},
+ {"tauntTaunt", K_F3, -1, -1, -1},
+ {"tauntDeathInsult", K_F4, -1, -1, -1},
+ {"tauntGauntlet", K_F5, -1, -1, -1},
+ {"scoresUp", K_KP_PGUP, -1, -1, -1},
+ {"scoresDown", K_KP_PGDN, -1, -1, -1},
+ // bk001205 - this one below was: '-1'
+ {"messagemode", -1, -1, -1, -1},
+ {"messagemode2", -1, -1, -1, -1},
+ {"messagemode3", -1, -1, -1, -1},
+ {"messagemode4", -1, -1, -1, -1}
+};
+
+
+static const int g_bindCount = sizeof(g_bindings) / sizeof(bind_t);
+
+#ifndef MISSIONPACK // bk001206
+static configcvar_t g_configcvars[] =
+{
+ {"cl_run", 0, 0},
+ {"m_pitch", 0, 0},
+ {"cg_autoswitch", 0, 0},
+ {"sensitivity", 0, 0},
+ {"in_joystick", 0, 0},
+ {"joy_threshold", 0, 0},
+ {"m_filter", 0, 0},
+ {"cl_freelook", 0, 0},
+ {NULL, 0, 0}
+};
+#endif
+
+/*
+=================
+Controls_GetKeyAssignment
+=================
+*/
+static void Controls_GetKeyAssignment (char *command, int *twokeys)
+{
+ int count;
+ int j;
+ char b[256];
+
+ twokeys[0] = twokeys[1] = -1;
+ count = 0;
+
+ for ( j = 0; j < 256; j++ )
+ {
+ DC->getBindingBuf( j, b, 256 );
+ if ( *b == 0 ) {
+ continue;
+ }
+ if ( !Q_stricmp( b, command ) ) {
+ twokeys[count] = j;
+ count++;
+ if (count == 2) {
+ break;
+ }
+ }
+ }
+}
+
+/*
+=================
+Controls_GetConfig
+=================
+*/
+void Controls_GetConfig( void )
+{
+ int i;
+ int twokeys[2];
+
+ // iterate each command, get its numeric binding
+ for (i=0; i < g_bindCount; i++)
+ {
+
+ Controls_GetKeyAssignment(g_bindings[i].command, twokeys);
+
+ g_bindings[i].bind1 = twokeys[0];
+ g_bindings[i].bind2 = twokeys[1];
+ }
+
+ //s_controls.invertmouse.curvalue = DC->getCVarValue( "m_pitch" ) < 0;
+ //s_controls.smoothmouse.curvalue = UI_ClampCvar( 0, 1, Controls_GetCvarValue( "m_filter" ) );
+ //s_controls.alwaysrun.curvalue = UI_ClampCvar( 0, 1, Controls_GetCvarValue( "cl_run" ) );
+ //s_controls.autoswitch.curvalue = UI_ClampCvar( 0, 1, Controls_GetCvarValue( "cg_autoswitch" ) );
+ //s_controls.sensitivity.curvalue = UI_ClampCvar( 2, 30, Controls_GetCvarValue( "sensitivity" ) );
+ //s_controls.joyenable.curvalue = UI_ClampCvar( 0, 1, Controls_GetCvarValue( "in_joystick" ) );
+ //s_controls.joythreshold.curvalue = UI_ClampCvar( 0.05, 0.75, Controls_GetCvarValue( "joy_threshold" ) );
+ //s_controls.freelook.curvalue = UI_ClampCvar( 0, 1, Controls_GetCvarValue( "cl_freelook" ) );
+}
+
+/*
+=================
+Controls_SetConfig
+=================
+*/
+void Controls_SetConfig(qboolean restart)
+{
+ int i;
+
+ // iterate each command, get its numeric binding
+ for (i=0; i < g_bindCount; i++)
+ {
+
+ if (g_bindings[i].bind1 != -1)
+ {
+ DC->setBinding( g_bindings[i].bind1, g_bindings[i].command );
+
+ if (g_bindings[i].bind2 != -1)
+ DC->setBinding( g_bindings[i].bind2, g_bindings[i].command );
+ }
+ }
+
+ //if ( s_controls.invertmouse.curvalue )
+ // DC->setCVar("m_pitch", va("%f),-fabs( DC->getCVarValue( "m_pitch" ) ) );
+ //else
+ // trap_Cvar_SetValue( "m_pitch", fabs( trap_Cvar_VariableValue( "m_pitch" ) ) );
+
+ //trap_Cvar_SetValue( "m_filter", s_controls.smoothmouse.curvalue );
+ //trap_Cvar_SetValue( "cl_run", s_controls.alwaysrun.curvalue );
+ //trap_Cvar_SetValue( "cg_autoswitch", s_controls.autoswitch.curvalue );
+ //trap_Cvar_SetValue( "sensitivity", s_controls.sensitivity.curvalue );
+ //trap_Cvar_SetValue( "in_joystick", s_controls.joyenable.curvalue );
+ //trap_Cvar_SetValue( "joy_threshold", s_controls.joythreshold.curvalue );
+ //trap_Cvar_SetValue( "cl_freelook", s_controls.freelook.curvalue );
+ DC->executeText(EXEC_APPEND, "in_restart\n");
+ //trap_Cmd_ExecuteText( EXEC_APPEND, "in_restart\n" );
+}
+
+/*
+=================
+Controls_SetDefaults
+=================
+*/
+void Controls_SetDefaults( void )
+{
+ int i;
+
+ // iterate each command, set its default binding
+ for (i=0; i < g_bindCount; i++)
+ {
+ g_bindings[i].bind1 = g_bindings[i].defaultbind1;
+ g_bindings[i].bind2 = g_bindings[i].defaultbind2;
+ }
+
+ //s_controls.invertmouse.curvalue = Controls_GetCvarDefault( "m_pitch" ) < 0;
+ //s_controls.smoothmouse.curvalue = Controls_GetCvarDefault( "m_filter" );
+ //s_controls.alwaysrun.curvalue = Controls_GetCvarDefault( "cl_run" );
+ //s_controls.autoswitch.curvalue = Controls_GetCvarDefault( "cg_autoswitch" );
+ //s_controls.sensitivity.curvalue = Controls_GetCvarDefault( "sensitivity" );
+ //s_controls.joyenable.curvalue = Controls_GetCvarDefault( "in_joystick" );
+ //s_controls.joythreshold.curvalue = Controls_GetCvarDefault( "joy_threshold" );
+ //s_controls.freelook.curvalue = Controls_GetCvarDefault( "cl_freelook" );
+}
+
+int BindingIDFromName(const char *name) {
+ int i;
+ for (i=0; i < g_bindCount; i++)
+ {
+ if (Q_stricmp(name, g_bindings[i].command) == 0) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+char g_nameBind1[32];
+char g_nameBind2[32];
+
+void BindingFromName(const char *cvar) {
+ int i, b1, b2;
+
+ // iterate each command, set its default binding
+ for (i=0; i < g_bindCount; i++)
+ {
+ if (Q_stricmp(cvar, g_bindings[i].command) == 0) {
+ b1 = g_bindings[i].bind1;
+ if (b1 == -1) {
+ break;
+ }
+ DC->keynumToStringBuf( b1, g_nameBind1, 32 );
+ Q_strupr(g_nameBind1);
+
+ b2 = g_bindings[i].bind2;
+ if (b2 != -1)
+ {
+ DC->keynumToStringBuf( b2, g_nameBind2, 32 );
+ Q_strupr(g_nameBind2);
+ strcat( g_nameBind1, " or " );
+ strcat( g_nameBind1, g_nameBind2 );
+ }
+ return;
+ }
+ }
+ strcpy(g_nameBind1, "???");
+}
+
+void Item_Slider_Paint(itemDef_t *item) {
+ vec4_t newColor, lowLight;
+ float x, y, value;
+ menuDef_t *parent = (menuDef_t*)item->parent;
+
+ value = (item->cvar) ? DC->getCVarValue(item->cvar) : 0;
+
+ if (item->window.flags & WINDOW_HASFOCUS) {
+ lowLight[0] = 0.8 * parent->focusColor[0];
+ lowLight[1] = 0.8 * parent->focusColor[1];
+ lowLight[2] = 0.8 * parent->focusColor[2];
+ lowLight[3] = 0.8 * parent->focusColor[3];
+ LerpColor(parent->focusColor,lowLight,newColor,0.5+0.5*sin(DC->realTime / PULSE_DIVISOR));
+ } else {
+ memcpy(&newColor, &item->window.foreColor, sizeof(vec4_t));
+ }
+
+ y = item->window.rect.y;
+ if (item->text) {
+ Item_Text_Paint(item);
+ x = item->textRect.x + item->textRect.w + 8;
+ } else {
+ x = item->window.rect.x;
+ }
+ DC->setColor(newColor);
+ DC->drawHandlePic( x, y, SLIDER_WIDTH, SLIDER_HEIGHT, DC->Assets.sliderBar );
+
+ x = Item_Slider_ThumbPosition(item);
+ DC->drawHandlePic( x - (SLIDER_THUMB_WIDTH / 2), y - 2, SLIDER_THUMB_WIDTH, SLIDER_THUMB_HEIGHT, DC->Assets.sliderThumb );
+
+}
+
+void Item_Bind_Paint(itemDef_t *item) {
+ vec4_t newColor, lowLight;
+ float value;
+ int maxChars = 0;
+ menuDef_t *parent = (menuDef_t*)item->parent;
+ editFieldDef_t *editPtr = (editFieldDef_t*)item->typeData;
+ if (editPtr) {
+ maxChars = editPtr->maxPaintChars;
+ }
+
+ value = (item->cvar) ? DC->getCVarValue(item->cvar) : 0;
+
+ if (item->window.flags & WINDOW_HASFOCUS) {
+ if (g_bindItem == item) {
+ lowLight[0] = 0.8f * 1.0f;
+ lowLight[1] = 0.8f * 0.0f;
+ lowLight[2] = 0.8f * 0.0f;
+ lowLight[3] = 0.8f * 1.0f;
+ } else {
+ lowLight[0] = 0.8f * parent->focusColor[0];
+ lowLight[1] = 0.8f * parent->focusColor[1];
+ lowLight[2] = 0.8f * parent->focusColor[2];
+ lowLight[3] = 0.8f * parent->focusColor[3];
+ }
+ LerpColor(parent->focusColor,lowLight,newColor,0.5+0.5*sin(DC->realTime / PULSE_DIVISOR));
+ } else {
+ memcpy(&newColor, &item->window.foreColor, sizeof(vec4_t));
+ }
+
+ if (item->text) {
+ Item_Text_Paint(item);
+ BindingFromName(item->cvar);
+ DC->drawText(item->textRect.x + item->textRect.w + 8, item->textRect.y, item->textscale, newColor, g_nameBind1, 0, maxChars, item->textStyle);
+ } else {
+ DC->drawText(item->textRect.x, item->textRect.y, item->textscale, newColor, (value != 0) ? "FIXME" : "FIXME", 0, maxChars, item->textStyle);
+ }
+}
+
+qboolean Display_KeyBindPending() {
+ return g_waitingForKey;
+}
+
+qboolean Item_Bind_HandleKey(itemDef_t *item, int key, qboolean down) {
+ int id;
+ int i;
+
+ if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && !g_waitingForKey)
+ {
+ if (down && (key == K_MOUSE1 || key == K_ENTER)) {
+ g_waitingForKey = qtrue;
+ g_bindItem = item;
+ }
+ return qtrue;
+ }
+ else
+ {
+ if (!g_waitingForKey || g_bindItem == NULL) {
+ return qtrue;
+ }
+
+ if (key & K_CHAR_FLAG) {
+ return qtrue;
+ }
+
+ switch (key)
+ {
+ case K_ESCAPE:
+ g_waitingForKey = qfalse;
+ return qtrue;
+
+ case K_BACKSPACE:
+ id = BindingIDFromName(item->cvar);
+ if (id != -1) {
+ g_bindings[id].bind1 = -1;
+ g_bindings[id].bind2 = -1;
+ }
+ Controls_SetConfig(qtrue);
+ g_waitingForKey = qfalse;
+ g_bindItem = NULL;
+ return qtrue;
+
+ case '`':
+ return qtrue;
+ }
+ }
+
+ if (key != -1)
+ {
+
+ for (i=0; i < g_bindCount; i++)
+ {
+
+ if (g_bindings[i].bind2 == key) {
+ g_bindings[i].bind2 = -1;
+ }
+
+ if (g_bindings[i].bind1 == key)
+ {
+ g_bindings[i].bind1 = g_bindings[i].bind2;
+ g_bindings[i].bind2 = -1;
+ }
+ }
+ }
+
+
+ id = BindingIDFromName(item->cvar);
+
+ if (id != -1) {
+ if (key == -1) {
+ if( g_bindings[id].bind1 != -1 ) {
+ DC->setBinding( g_bindings[id].bind1, "" );
+ g_bindings[id].bind1 = -1;
+ }
+ if( g_bindings[id].bind2 != -1 ) {
+ DC->setBinding( g_bindings[id].bind2, "" );
+ g_bindings[id].bind2 = -1;
+ }
+ }
+ else if (g_bindings[id].bind1 == -1) {
+ g_bindings[id].bind1 = key;
+ }
+ else if (g_bindings[id].bind1 != key && g_bindings[id].bind2 == -1) {
+ g_bindings[id].bind2 = key;
+ }
+ else {
+ DC->setBinding( g_bindings[id].bind1, "" );
+ DC->setBinding( g_bindings[id].bind2, "" );
+ g_bindings[id].bind1 = key;
+ g_bindings[id].bind2 = -1;
+ }
+ }
+
+ Controls_SetConfig(qtrue);
+ g_waitingForKey = qfalse;
+
+ return qtrue;
+}
+
+
+
+void AdjustFrom640(float *x, float *y, float *w, float *h) {
+ //*x = *x * DC->scale + DC->bias;
+ *x *= DC->xscale;
+ *y *= DC->yscale;
+ *w *= DC->xscale;
+ *h *= DC->yscale;
+}
+
+void Item_Model_Paint(itemDef_t *item) {
+ float x, y, w, h;
+ refdef_t refdef;
+ refEntity_t ent;
+ vec3_t mins, maxs, origin;
+ vec3_t angles;
+ modelDef_t *modelPtr = (modelDef_t*)item->typeData;
+
+ if (modelPtr == NULL) {
+ return;
+ }
+
+ // setup the refdef
+ memset( &refdef, 0, sizeof( refdef ) );
+ refdef.rdflags = RDF_NOWORLDMODEL;
+ AxisClear( refdef.viewaxis );
+ x = item->window.rect.x+1;
+ y = item->window.rect.y+1;
+ w = item->window.rect.w-2;
+ h = item->window.rect.h-2;
+
+ AdjustFrom640( &x, &y, &w, &h );
+
+ refdef.x = x;
+ refdef.y = y;
+ refdef.width = w;
+ refdef.height = h;
+
+ DC->modelBounds( item->asset, mins, maxs );
+
+ origin[2] = -0.5 * ( mins[2] + maxs[2] );
+ origin[1] = 0.5 * ( mins[1] + maxs[1] );
+
+ // calculate distance so the model nearly fills the box
+ if (qtrue) {
+ float len = 0.5 * ( maxs[2] - mins[2] );
+ origin[0] = len / 0.268; // len / tan( fov/2 )
+ //origin[0] = len / tan(w/2);
+ } else {
+ origin[0] = item->textscale;
+ }
+ refdef.fov_x = (modelPtr->fov_x) ? modelPtr->fov_x : w;
+ refdef.fov_y = (modelPtr->fov_y) ? modelPtr->fov_y : h;
+
+ //refdef.fov_x = (int)((float)refdef.width / 640.0f * 90.0f);
+ //xx = refdef.width / tan( refdef.fov_x / 360 * M_PI );
+ //refdef.fov_y = atan2( refdef.height, xx );
+ //refdef.fov_y *= ( 360 / M_PI );
+
+ DC->clearScene();
+
+ refdef.time = DC->realTime;
+
+ // add the model
+
+ memset( &ent, 0, sizeof(ent) );
+
+ //adjust = 5.0 * sin( (float)uis.realtime / 500 );
+ //adjust = 360 % (int)((float)uis.realtime / 1000);
+ //VectorSet( angles, 0, 0, 1 );
+
+ // use item storage to track
+ if (modelPtr->rotationSpeed) {
+ if (DC->realTime > item->window.nextTime) {
+ item->window.nextTime = DC->realTime + modelPtr->rotationSpeed;
+ modelPtr->angle = (int)(modelPtr->angle + 1) % 360;
+ }
+ }
+ VectorSet( angles, 0, modelPtr->angle, 0 );
+ AnglesToAxis( angles, ent.axis );
+
+ ent.hModel = item->asset;
+ VectorCopy( origin, ent.origin );
+ VectorCopy( origin, ent.lightingOrigin );
+ ent.renderfx = RF_LIGHTING_ORIGIN | RF_NOSHADOW;
+ VectorCopy( ent.origin, ent.oldorigin );
+
+ DC->addRefEntityToScene( &ent );
+ DC->renderScene( &refdef );
+
+}
+
+
+void Item_Image_Paint(itemDef_t *item) {
+ if (item == NULL) {
+ return;
+ }
+ DC->drawHandlePic(item->window.rect.x+1, item->window.rect.y+1, item->window.rect.w-2, item->window.rect.h-2, item->asset);
+}
+
+void Item_ListBox_Paint(itemDef_t *item) {
+ float x, y, size, count, i, thumb;
+ qhandle_t image;
+ qhandle_t optionalImage;
+ listBoxDef_t *listPtr = (listBoxDef_t*)item->typeData;
+
+ // the listbox is horizontal or vertical and has a fixed size scroll bar going either direction
+ // elements are enumerated from the DC and either text or image handles are acquired from the DC as well
+ // textscale is used to size the text, textalignx and textaligny are used to size image elements
+ // there is no clipping available so only the last completely visible item is painted
+ count = DC->feederCount(item->special);
+ // default is vertical if horizontal flag is not here
+ if (item->window.flags & WINDOW_HORIZONTAL) {
+ // draw scrollbar in bottom of the window
+ // bar
+ x = item->window.rect.x + 1;
+ y = item->window.rect.y + item->window.rect.h - SCROLLBAR_SIZE - 1;
+ DC->drawHandlePic(x, y, SCROLLBAR_SIZE, SCROLLBAR_SIZE, DC->Assets.scrollBarArrowLeft);
+ x += SCROLLBAR_SIZE - 1;
+ size = item->window.rect.w - (SCROLLBAR_SIZE * 2);
+ DC->drawHandlePic(x, y, size+1, SCROLLBAR_SIZE, DC->Assets.scrollBar);
+ x += size - 1;
+ DC->drawHandlePic(x, y, SCROLLBAR_SIZE, SCROLLBAR_SIZE, DC->Assets.scrollBarArrowRight);
+ // thumb
+ thumb = Item_ListBox_ThumbDrawPosition(item);//Item_ListBox_ThumbPosition(item);
+ if (thumb > x - SCROLLBAR_SIZE - 1) {
+ thumb = x - SCROLLBAR_SIZE - 1;
+ }
+ DC->drawHandlePic(thumb, y, SCROLLBAR_SIZE, SCROLLBAR_SIZE, DC->Assets.scrollBarThumb);
+ //
+ listPtr->endPos = listPtr->startPos;
+ size = item->window.rect.w - 2;
+ // items
+ // size contains max available space
+ if (listPtr->elementStyle == LISTBOX_IMAGE) {
+ // fit = 0;
+ x = item->window.rect.x + 1;
+ y = item->window.rect.y + 1;
+ for (i = listPtr->startPos; i < count; i++) {
+ // always draw at least one
+ // which may overdraw the box if it is too small for the element
+ image = DC->feederItemImage(item->special, i);
+ if (image) {
+ DC->drawHandlePic(x+1, y+1, listPtr->elementWidth - 2, listPtr->elementHeight - 2, image);
+ }
+
+ if (i == item->cursorPos) {
+ DC->drawRect(x, y, listPtr->elementWidth-1, listPtr->elementHeight-1, item->window.borderSize, item->window.borderColor);
+ }
+
+ size -= listPtr->elementWidth;
+ if (size < listPtr->elementWidth) {
+ listPtr->drawPadding = size; //listPtr->elementWidth - size;
+ break;
+ }
+ x += listPtr->elementWidth;
+ listPtr->endPos++;
+ // fit++;
+ }
+ } else {
+ //
+ }
+ } else {
+ // draw scrollbar to right side of the window
+ x = item->window.rect.x + item->window.rect.w - SCROLLBAR_SIZE - 1;
+ y = item->window.rect.y + 1;
+ DC->drawHandlePic(x, y, SCROLLBAR_SIZE, SCROLLBAR_SIZE, DC->Assets.scrollBarArrowUp);
+ y += SCROLLBAR_SIZE - 1;
+
+ listPtr->endPos = listPtr->startPos;
+ size = item->window.rect.h - (SCROLLBAR_SIZE * 2);
+ DC->drawHandlePic(x, y, SCROLLBAR_SIZE, size+1, DC->Assets.scrollBar);
+ y += size - 1;
+ DC->drawHandlePic(x, y, SCROLLBAR_SIZE, SCROLLBAR_SIZE, DC->Assets.scrollBarArrowDown);
+ // thumb
+ thumb = Item_ListBox_ThumbDrawPosition(item);//Item_ListBox_ThumbPosition(item);
+ if (thumb > y - SCROLLBAR_SIZE - 1) {
+ thumb = y - SCROLLBAR_SIZE - 1;
+ }
+ DC->drawHandlePic(x, thumb, SCROLLBAR_SIZE, SCROLLBAR_SIZE, DC->Assets.scrollBarThumb);
+
+ // adjust size for item painting
+ size = item->window.rect.h - 2;
+ if (listPtr->elementStyle == LISTBOX_IMAGE) {
+ // fit = 0;
+ x = item->window.rect.x + 1;
+ y = item->window.rect.y + 1;
+ for (i = listPtr->startPos; i < count; i++) {
+ // always draw at least one
+ // which may overdraw the box if it is too small for the element
+ image = DC->feederItemImage(item->special, i);
+ if (image) {
+ DC->drawHandlePic(x+1, y+1, listPtr->elementWidth - 2, listPtr->elementHeight - 2, image);
+ }
+
+ if (i == item->cursorPos) {
+ DC->drawRect(x, y, listPtr->elementWidth - 1, listPtr->elementHeight - 1, item->window.borderSize, item->window.borderColor);
+ }
+
+ listPtr->endPos++;
+ size -= listPtr->elementWidth;
+ if (size < listPtr->elementHeight) {
+ listPtr->drawPadding = listPtr->elementHeight - size;
+ break;
+ }
+ y += listPtr->elementHeight;
+ // fit++;
+ }
+ } else {
+ x = item->window.rect.x + 1;
+ y = item->window.rect.y + 1;
+ for (i = listPtr->startPos; i < count; i++) {
+ const char *text;
+ // always draw at least one
+ // which may overdraw the box if it is too small for the element
+
+ if (listPtr->numColumns > 0) {
+ int j;
+ for (j = 0; j < listPtr->numColumns; j++) {
+ text = DC->feederItemText(item->special, i, j, &optionalImage);
+ if (optionalImage >= 0) {
+ DC->drawHandlePic(x + 4 + listPtr->columnInfo[j].pos, y - 1 + listPtr->elementHeight / 2, listPtr->columnInfo[j].width, listPtr->columnInfo[j].width, optionalImage);
+ } else if (text) {
+ DC->drawText(x + 4 + listPtr->columnInfo[j].pos, y + listPtr->elementHeight, item->textscale, item->window.foreColor, text, 0, listPtr->columnInfo[j].maxChars, item->textStyle);
+ }
+ }
+ } else {
+ text = DC->feederItemText(item->special, i, 0, &optionalImage);
+ if (optionalImage >= 0) {
+ //DC->drawHandlePic(x + 4 + listPtr->elementHeight, y, listPtr->columnInfo[j].width, listPtr->columnInfo[j].width, optionalImage);
+ } else if (text) {
+ DC->drawText(x + 4, y + listPtr->elementHeight, item->textscale, item->window.foreColor, text, 0, 0, item->textStyle);
+ }
+ }
+
+ if (i == item->cursorPos) {
+ DC->fillRect(x + 2, y + 2, item->window.rect.w - SCROLLBAR_SIZE - 4, listPtr->elementHeight, item->window.outlineColor);
+ }
+
+ size -= listPtr->elementHeight;
+ if (size < listPtr->elementHeight) {
+ listPtr->drawPadding = listPtr->elementHeight - size;
+ break;
+ }
+ listPtr->endPos++;
+ y += listPtr->elementHeight;
+ // fit++;
+ }
+ }
+ }
+}
+
+
+void Item_OwnerDraw_Paint(itemDef_t *item) {
+ menuDef_t *parent;
+
+ if (item == NULL) {
+ return;
+ }
+ parent = (menuDef_t*)item->parent;
+
+ if (DC->ownerDrawItem) {
+ vec4_t color, lowLight;
+ menuDef_t *parent = (menuDef_t*)item->parent;
+ Fade(&item->window.flags, &item->window.foreColor[3], parent->fadeClamp, &item->window.nextTime, parent->fadeCycle, qtrue, parent->fadeAmount);
+ memcpy(&color, &item->window.foreColor, sizeof(color));
+ if (item->numColors > 0 && DC->getValue) {
+ // if the value is within one of the ranges then set color to that, otherwise leave at default
+ int i;
+ float f = DC->getValue(item->window.ownerDraw);
+ for (i = 0; i < item->numColors; i++) {
+ if (f >= item->colorRanges[i].low && f <= item->colorRanges[i].high) {
+ memcpy(&color, &item->colorRanges[i].color, sizeof(color));
+ break;
+ }
+ }
+ }
+
+ if (item->window.flags & WINDOW_HASFOCUS) {
+ lowLight[0] = 0.8 * parent->focusColor[0];
+ lowLight[1] = 0.8 * parent->focusColor[1];
+ lowLight[2] = 0.8 * parent->focusColor[2];
+ lowLight[3] = 0.8 * parent->focusColor[3];
+ LerpColor(parent->focusColor,lowLight,color,0.5+0.5*sin(DC->realTime / PULSE_DIVISOR));
+ } else if (item->textStyle == ITEM_TEXTSTYLE_BLINK && !((DC->realTime/BLINK_DIVISOR) & 1)) {
+ lowLight[0] = 0.8 * item->window.foreColor[0];
+ lowLight[1] = 0.8 * item->window.foreColor[1];
+ lowLight[2] = 0.8 * item->window.foreColor[2];
+ lowLight[3] = 0.8 * item->window.foreColor[3];
+ LerpColor(item->window.foreColor,lowLight,color,0.5+0.5*sin(DC->realTime / PULSE_DIVISOR));
+ }
+
+ if (item->cvarFlags & (CVAR_ENABLE | CVAR_DISABLE) && !Item_EnableShowViaCvar(item, CVAR_ENABLE)) {
+ memcpy(color, parent->disableColor, sizeof(vec4_t)); // bk001207 - FIXME: Com_Memcpy
+ }
+
+ if (item->text) {
+ Item_Text_Paint(item);
+ if (item->text[0]) {
+ // +8 is an offset kludge to properly align owner draw items that have text combined with them
+ DC->ownerDrawItem(item->textRect.x + item->textRect.w + 8, item->window.rect.y, item->window.rect.w, item->window.rect.h, 0, item->textaligny, item->window.ownerDraw, item->window.ownerDrawFlags, item->alignment, item->special, item->textscale, color, item->window.background, item->textStyle );
+ } else {
+ DC->ownerDrawItem(item->textRect.x + item->textRect.w, item->window.rect.y, item->window.rect.w, item->window.rect.h, 0, item->textaligny, item->window.ownerDraw, item->window.ownerDrawFlags, item->alignment, item->special, item->textscale, color, item->window.background, item->textStyle );
+ }
+ } else {
+ DC->ownerDrawItem(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->textalignx, item->textaligny, item->window.ownerDraw, item->window.ownerDrawFlags, item->alignment, item->special, item->textscale, color, item->window.background, item->textStyle );
+ }
+ }
+}
+
+
+void Item_Paint(itemDef_t *item) {
+ vec4_t red;
+ menuDef_t *parent = (menuDef_t*)item->parent;
+ red[0] = red[3] = 1;
+ red[1] = red[2] = 0;
+
+ if (item == NULL) {
+ return;
+ }
+
+ if (item->window.flags & WINDOW_ORBITING) {
+ if (DC->realTime > item->window.nextTime) {
+ float rx, ry, a, c, s, w, h;
+
+ item->window.nextTime = DC->realTime + item->window.offsetTime;
+ // translate
+ w = item->window.rectClient.w / 2;
+ h = item->window.rectClient.h / 2;
+ rx = item->window.rectClient.x + w - item->window.rectEffects.x;
+ ry = item->window.rectClient.y + h - item->window.rectEffects.y;
+ a = 3 * M_PI / 180;
+ c = cos(a);
+ s = sin(a);
+ item->window.rectClient.x = (rx * c - ry * s) + item->window.rectEffects.x - w;
+ item->window.rectClient.y = (rx * s + ry * c) + item->window.rectEffects.y - h;
+ Item_UpdatePosition(item);
+
+ }
+ }
+
+
+ if (item->window.flags & WINDOW_INTRANSITION) {
+ if (DC->realTime > item->window.nextTime) {
+ int done = 0;
+ item->window.nextTime = DC->realTime + item->window.offsetTime;
+ // transition the x,y
+ if (item->window.rectClient.x == item->window.rectEffects.x) {
+ done++;
+ } else {
+ if (item->window.rectClient.x < item->window.rectEffects.x) {
+ item->window.rectClient.x += item->window.rectEffects2.x;
+ if (item->window.rectClient.x > item->window.rectEffects.x) {
+ item->window.rectClient.x = item->window.rectEffects.x;
+ done++;
+ }
+ } else {
+ item->window.rectClient.x -= item->window.rectEffects2.x;
+ if (item->window.rectClient.x < item->window.rectEffects.x) {
+ item->window.rectClient.x = item->window.rectEffects.x;
+ done++;
+ }
+ }
+ }
+ if (item->window.rectClient.y == item->window.rectEffects.y) {
+ done++;
+ } else {
+ if (item->window.rectClient.y < item->window.rectEffects.y) {
+ item->window.rectClient.y += item->window.rectEffects2.y;
+ if (item->window.rectClient.y > item->window.rectEffects.y) {
+ item->window.rectClient.y = item->window.rectEffects.y;
+ done++;
+ }
+ } else {
+ item->window.rectClient.y -= item->window.rectEffects2.y;
+ if (item->window.rectClient.y < item->window.rectEffects.y) {
+ item->window.rectClient.y = item->window.rectEffects.y;
+ done++;
+ }
+ }
+ }
+ if (item->window.rectClient.w == item->window.rectEffects.w) {
+ done++;
+ } else {
+ if (item->window.rectClient.w < item->window.rectEffects.w) {
+ item->window.rectClient.w += item->window.rectEffects2.w;
+ if (item->window.rectClient.w > item->window.rectEffects.w) {
+ item->window.rectClient.w = item->window.rectEffects.w;
+ done++;
+ }
+ } else {
+ item->window.rectClient.w -= item->window.rectEffects2.w;
+ if (item->window.rectClient.w < item->window.rectEffects.w) {
+ item->window.rectClient.w = item->window.rectEffects.w;
+ done++;
+ }
+ }
+ }
+ if (item->window.rectClient.h == item->window.rectEffects.h) {
+ done++;
+ } else {
+ if (item->window.rectClient.h < item->window.rectEffects.h) {
+ item->window.rectClient.h += item->window.rectEffects2.h;
+ if (item->window.rectClient.h > item->window.rectEffects.h) {
+ item->window.rectClient.h = item->window.rectEffects.h;
+ done++;
+ }
+ } else {
+ item->window.rectClient.h -= item->window.rectEffects2.h;
+ if (item->window.rectClient.h < item->window.rectEffects.h) {
+ item->window.rectClient.h = item->window.rectEffects.h;
+ done++;
+ }
+ }
+ }
+
+ Item_UpdatePosition(item);
+
+ if (done == 4) {
+ item->window.flags &= ~WINDOW_INTRANSITION;
+ }
+
+ }
+ }
+
+ if (item->window.ownerDrawFlags && DC->ownerDrawVisible) {
+ if (!DC->ownerDrawVisible(item->window.ownerDrawFlags)) {
+ item->window.flags &= ~WINDOW_VISIBLE;
+ } else {
+ item->window.flags |= WINDOW_VISIBLE;
+ }
+ }
+
+ if (item->cvarFlags & (CVAR_SHOW | CVAR_HIDE)) {
+ if (!Item_EnableShowViaCvar(item, CVAR_SHOW)) {
+ return;
+ }
+ }
+
+ if (item->window.flags & WINDOW_TIMEDVISIBLE) {
+
+ }
+
+ if (!(item->window.flags & WINDOW_VISIBLE)) {
+ return;
+ }
+
+ // paint the rect first..
+ Window_Paint(&item->window, parent->fadeAmount , parent->fadeClamp, parent->fadeCycle);
+
+ if (debugMode) {
+ vec4_t color;
+ rectDef_t *r = Item_CorrectedTextRect(item);
+ color[1] = color[3] = 1;
+ color[0] = color[2] = 0;
+ DC->drawRect(r->x, r->y, r->w, r->h, 1, color);
+ }
+
+ //DC->drawRect(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, 1, red);
+
+ switch (item->type) {
+ case ITEM_TYPE_OWNERDRAW:
+ Item_OwnerDraw_Paint(item);
+ break;
+ case ITEM_TYPE_TEXT:
+ case ITEM_TYPE_BUTTON:
+ Item_Text_Paint(item);
+ break;
+ case ITEM_TYPE_RADIOBUTTON:
+ break;
+ case ITEM_TYPE_CHECKBOX:
+ break;
+ case ITEM_TYPE_EDITFIELD:
+ case ITEM_TYPE_NUMERICFIELD:
+ Item_TextField_Paint(item);
+ break;
+ case ITEM_TYPE_COMBO:
+ break;
+ case ITEM_TYPE_LISTBOX:
+ Item_ListBox_Paint(item);
+ break;
+ //case ITEM_TYPE_IMAGE:
+ // Item_Image_Paint(item);
+ // break;
+ case ITEM_TYPE_MODEL:
+ Item_Model_Paint(item);
+ break;
+ case ITEM_TYPE_YESNO:
+ Item_YesNo_Paint(item);
+ break;
+ case ITEM_TYPE_MULTI:
+ Item_Multi_Paint(item);
+ break;
+ case ITEM_TYPE_BIND:
+ Item_Bind_Paint(item);
+ break;
+ case ITEM_TYPE_SLIDER:
+ Item_Slider_Paint(item);
+ break;
+ default:
+ break;
+ }
+
+}
+
+void Menu_Init(menuDef_t *menu) {
+ memset(menu, 0, sizeof(menuDef_t));
+ menu->cursorItem = -1;
+ menu->fadeAmount = DC->Assets.fadeAmount;
+ menu->fadeClamp = DC->Assets.fadeClamp;
+ menu->fadeCycle = DC->Assets.fadeCycle;
+ Window_Init(&menu->window);
+}
+
+itemDef_t *Menu_GetFocusedItem(menuDef_t *menu) {
+ int i;
+ if (menu) {
+ for (i = 0; i < menu->itemCount; i++) {
+ if (menu->items[i]->window.flags & WINDOW_HASFOCUS) {
+ return menu->items[i];
+ }
+ }
+ }
+ return NULL;
+}
+
+menuDef_t *Menu_GetFocused() {
+ int i;
+ for (i = 0; i < menuCount; i++) {
+ if (Menus[i].window.flags & WINDOW_HASFOCUS && Menus[i].window.flags & WINDOW_VISIBLE) {
+ return &Menus[i];
+ }
+ }
+ return NULL;
+}
+
+void Menu_ScrollFeeder(menuDef_t *menu, int feeder, qboolean down) {
+ if (menu) {
+ int i;
+ for (i = 0; i < menu->itemCount; i++) {
+ if (menu->items[i]->special == feeder) {
+ Item_ListBox_HandleKey(menu->items[i], (down) ? K_DOWNARROW : K_UPARROW, qtrue, qtrue);
+ return;
+ }
+ }
+ }
+}
+
+
+
+void Menu_SetFeederSelection(menuDef_t *menu, int feeder, int index, const char *name) {
+ if (menu == NULL) {
+ if (name == NULL) {
+ menu = Menu_GetFocused();
+ } else {
+ menu = Menus_FindByName(name);
+ }
+ }
+
+ if (menu) {
+ int i;
+ for (i = 0; i < menu->itemCount; i++) {
+ if (menu->items[i]->special == feeder) {
+ if (index == 0) {
+ listBoxDef_t *listPtr = (listBoxDef_t*)menu->items[i]->typeData;
+ listPtr->cursorPos = 0;
+ listPtr->startPos = 0;
+ }
+ menu->items[i]->cursorPos = index;
+ DC->feederSelection(menu->items[i]->special, menu->items[i]->cursorPos);
+ return;
+ }
+ }
+ }
+}
+
+qboolean Menus_AnyFullScreenVisible() {
+ int i;
+ for (i = 0; i < menuCount; i++) {
+ if (Menus[i].window.flags & WINDOW_VISIBLE && Menus[i].fullScreen) {
+ return qtrue;
+ }
+ }
+ return qfalse;
+}
+
+menuDef_t *Menus_ActivateByName(const char *p) {
+ int i;
+ menuDef_t *m = NULL;
+ menuDef_t *focus = Menu_GetFocused();
+ for (i = 0; i < menuCount; i++) {
+ if (Q_stricmp(Menus[i].window.name, p) == 0) {
+ m = &Menus[i];
+ Menus_Activate(m);
+ if (openMenuCount < MAX_OPEN_MENUS && focus != NULL) {
+ menuStack[openMenuCount++] = focus;
+ }
+ } else {
+ Menus[i].window.flags &= ~WINDOW_HASFOCUS;
+ }
+ }
+ Display_CloseCinematics();
+ return m;
+}
+
+
+void Item_Init(itemDef_t *item) {
+ memset(item, 0, sizeof(itemDef_t));
+ item->textscale = 0.55f;
+ Window_Init(&item->window);
+}
+
+void Menu_HandleMouseMove(menuDef_t *menu, float x, float y) {
+ int i, pass;
+ qboolean focusSet = qfalse;
+
+ itemDef_t *overItem;
+ if (menu == NULL) {
+ return;
+ }
+
+ if (!(menu->window.flags & (WINDOW_VISIBLE | WINDOW_FORCED))) {
+ return;
+ }
+
+ if (itemCapture) {
+ //Item_MouseMove(itemCapture, x, y);
+ return;
+ }
+
+ if (g_waitingForKey || g_editingField) {
+ return;
+ }
+
+ // FIXME: this is the whole issue of focus vs. mouse over..
+ // need a better overall solution as i don't like going through everything twice
+ for (pass = 0; pass < 2; pass++) {
+ for (i = 0; i < menu->itemCount; i++) {
+ // turn off focus each item
+ // menu->items[i].window.flags &= ~WINDOW_HASFOCUS;
+
+ if (!(menu->items[i]->window.flags & (WINDOW_VISIBLE | WINDOW_FORCED))) {
+ continue;
+ }
+
+ // items can be enabled and disabled based on cvars
+ if (menu->items[i]->cvarFlags & (CVAR_ENABLE | CVAR_DISABLE) && !Item_EnableShowViaCvar(menu->items[i], CVAR_ENABLE)) {
+ continue;
+ }
+
+ if (menu->items[i]->cvarFlags & (CVAR_SHOW | CVAR_HIDE) && !Item_EnableShowViaCvar(menu->items[i], CVAR_SHOW)) {
+ continue;
+ }
+
+
+
+ if (Rect_ContainsPoint(&menu->items[i]->window.rect, x, y)) {
+ if (pass == 1) {
+ overItem = menu->items[i];
+ if (overItem->type == ITEM_TYPE_TEXT && overItem->text) {
+ if (!Rect_ContainsPoint(Item_CorrectedTextRect(overItem), x, y)) {
+ continue;
+ }
+ }
+ // if we are over an item
+ if (IsVisible(overItem->window.flags)) {
+ // different one
+ Item_MouseEnter(overItem, x, y);
+ // Item_SetMouseOver(overItem, qtrue);
+
+ // if item is not a decoration see if it can take focus
+ if (!focusSet) {
+ focusSet = Item_SetFocus(overItem, x, y);
+ }
+ }
+ }
+ } else if (menu->items[i]->window.flags & WINDOW_MOUSEOVER) {
+ Item_MouseLeave(menu->items[i]);
+ Item_SetMouseOver(menu->items[i], qfalse);
+ }
+ }
+ }
+
+}
+
+void Menu_Paint(menuDef_t *menu, qboolean forcePaint) {
+ int i;
+
+ if (menu == NULL) {
+ return;
+ }
+
+ if (!(menu->window.flags & WINDOW_VISIBLE) && !forcePaint) {
+ return;
+ }
+
+ if (menu->window.ownerDrawFlags && DC->ownerDrawVisible && !DC->ownerDrawVisible(menu->window.ownerDrawFlags)) {
+ return;
+ }
+
+ if (forcePaint) {
+ menu->window.flags |= WINDOW_FORCED;
+ }
+
+ // draw the background if necessary
+ if (menu->fullScreen) {
+ // implies a background shader
+ // FIXME: make sure we have a default shader if fullscreen is set with no background
+ DC->drawHandlePic( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, menu->window.background );
+ } else if (menu->window.background) {
+ // this allows a background shader without being full screen
+ //UI_DrawHandlePic(menu->window.rect.x, menu->window.rect.y, menu->window.rect.w, menu->window.rect.h, menu->backgroundShader);
+ }
+
+ // paint the background and or border
+ Window_Paint(&menu->window, menu->fadeAmount, menu->fadeClamp, menu->fadeCycle );
+
+ for (i = 0; i < menu->itemCount; i++) {
+ Item_Paint(menu->items[i]);
+ }
+
+ if (debugMode) {
+ vec4_t color;
+ color[0] = color[2] = color[3] = 1;
+ color[1] = 0;
+ DC->drawRect(menu->window.rect.x, menu->window.rect.y, menu->window.rect.w, menu->window.rect.h, 1, color);
+ }
+}
+
+/*
+===============
+Item_ValidateTypeData
+===============
+*/
+void Item_ValidateTypeData(itemDef_t *item) {
+ if (item->typeData) {
+ return;
+ }
+
+ if (item->type == ITEM_TYPE_LISTBOX) {
+ item->typeData = UI_Alloc(sizeof(listBoxDef_t));
+ memset(item->typeData, 0, sizeof(listBoxDef_t));
+ } else if (item->type == ITEM_TYPE_EDITFIELD || item->type == ITEM_TYPE_NUMERICFIELD || item->type == ITEM_TYPE_YESNO || item->type == ITEM_TYPE_BIND || item->type == ITEM_TYPE_SLIDER || item->type == ITEM_TYPE_TEXT) {
+ item->typeData = UI_Alloc(sizeof(editFieldDef_t));
+ memset(item->typeData, 0, sizeof(editFieldDef_t));
+ if (item->type == ITEM_TYPE_EDITFIELD) {
+ if (!((editFieldDef_t *) item->typeData)->maxPaintChars) {
+ ((editFieldDef_t *) item->typeData)->maxPaintChars = MAX_EDITFIELD;
+ }
+ }
+ } else if (item->type == ITEM_TYPE_MULTI) {
+ item->typeData = UI_Alloc(sizeof(multiDef_t));
+ } else if (item->type == ITEM_TYPE_MODEL) {
+ item->typeData = UI_Alloc(sizeof(modelDef_t));
+ }
+}
+
+/*
+===============
+Keyword Hash
+===============
+*/
+
+#define KEYWORDHASH_SIZE 512
+
+typedef struct keywordHash_s
+{
+ char *keyword;
+ qboolean (*func)(itemDef_t *item, int handle);
+ struct keywordHash_s *next;
+} keywordHash_t;
+
+int KeywordHash_Key(char *keyword) {
+ int register hash, i;
+
+ hash = 0;
+ for (i = 0; keyword[i] != '\0'; i++) {
+ if (keyword[i] >= 'A' && keyword[i] <= 'Z')
+ hash += (keyword[i] + ('a' - 'A')) * (119 + i);
+ else
+ hash += keyword[i] * (119 + i);
+ }
+ hash = (hash ^ (hash >> 10) ^ (hash >> 20)) & (KEYWORDHASH_SIZE-1);
+ return hash;
+}
+
+void KeywordHash_Add(keywordHash_t *table[], keywordHash_t *key) {
+ int hash;
+
+ hash = KeywordHash_Key(key->keyword);
+/*
+ if (table[hash]) {
+ int collision = qtrue;
+ }
+*/
+ key->next = table[hash];
+ table[hash] = key;
+}
+
+keywordHash_t *KeywordHash_Find(keywordHash_t *table[], char *keyword)
+{
+ keywordHash_t *key;
+ int hash;
+
+ hash = KeywordHash_Key(keyword);
+ for (key = table[hash]; key; key = key->next) {
+ if (!Q_stricmp(key->keyword, keyword))
+ return key;
+ }
+ return NULL;
+}
+
+/*
+===============
+Item Keyword Parse functions
+===============
+*/
+
+// name <string>
+qboolean ItemParse_name( itemDef_t *item, int handle ) {
+ if (!PC_String_Parse(handle, &item->window.name)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+// name <string>
+qboolean ItemParse_focusSound( itemDef_t *item, int handle ) {
+ const char *temp;
+ if (!PC_String_Parse(handle, &temp)) {
+ return qfalse;
+ }
+ item->focusSound = DC->registerSound(temp, qfalse);
+ return qtrue;
+}
+
+
+// text <string>
+qboolean ItemParse_text( itemDef_t *item, int handle ) {
+ if (!PC_String_Parse(handle, &item->text)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+// group <string>
+qboolean ItemParse_group( itemDef_t *item, int handle ) {
+ if (!PC_String_Parse(handle, &item->window.group)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+// asset_model <string>
+qboolean ItemParse_asset_model( itemDef_t *item, int handle ) {
+ const char *temp;
+ modelDef_t *modelPtr;
+ Item_ValidateTypeData(item);
+ modelPtr = (modelDef_t*)item->typeData;
+
+ if (!PC_String_Parse(handle, &temp)) {
+ return qfalse;
+ }
+ item->asset = DC->registerModel(temp);
+ modelPtr->angle = rand() % 360;
+ return qtrue;
+}
+
+// asset_shader <string>
+qboolean ItemParse_asset_shader( itemDef_t *item, int handle ) {
+ const char *temp;
+
+ if (!PC_String_Parse(handle, &temp)) {
+ return qfalse;
+ }
+ item->asset = DC->registerShaderNoMip(temp);
+ return qtrue;
+}
+
+// model_origin <number> <number> <number>
+qboolean ItemParse_model_origin( itemDef_t *item, int handle ) {
+ modelDef_t *modelPtr;
+ Item_ValidateTypeData(item);
+ modelPtr = (modelDef_t*)item->typeData;
+
+ if (PC_Float_Parse(handle, &modelPtr->origin[0])) {
+ if (PC_Float_Parse(handle, &modelPtr->origin[1])) {
+ if (PC_Float_Parse(handle, &modelPtr->origin[2])) {
+ return qtrue;
+ }
+ }
+ }
+ return qfalse;
+}
+
+// model_fovx <number>
+qboolean ItemParse_model_fovx( itemDef_t *item, int handle ) {
+ modelDef_t *modelPtr;
+ Item_ValidateTypeData(item);
+ modelPtr = (modelDef_t*)item->typeData;
+
+ if (!PC_Float_Parse(handle, &modelPtr->fov_x)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+// model_fovy <number>
+qboolean ItemParse_model_fovy( itemDef_t *item, int handle ) {
+ modelDef_t *modelPtr;
+ Item_ValidateTypeData(item);
+ modelPtr = (modelDef_t*)item->typeData;
+
+ if (!PC_Float_Parse(handle, &modelPtr->fov_y)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+// model_rotation <integer>
+qboolean ItemParse_model_rotation( itemDef_t *item, int handle ) {
+ modelDef_t *modelPtr;
+ Item_ValidateTypeData(item);
+ modelPtr = (modelDef_t*)item->typeData;
+
+ if (!PC_Int_Parse(handle, &modelPtr->rotationSpeed)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+// model_angle <integer>
+qboolean ItemParse_model_angle( itemDef_t *item, int handle ) {
+ modelDef_t *modelPtr;
+ Item_ValidateTypeData(item);
+ modelPtr = (modelDef_t*)item->typeData;
+
+ if (!PC_Int_Parse(handle, &modelPtr->angle)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+// rect <rectangle>
+qboolean ItemParse_rect( itemDef_t *item, int handle ) {
+ if (!PC_Rect_Parse(handle, &item->window.rectClient)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+// style <integer>
+qboolean ItemParse_style( itemDef_t *item, int handle ) {
+ if (!PC_Int_Parse(handle, &item->window.style)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+// decoration
+qboolean ItemParse_decoration( itemDef_t *item, int handle ) {
+ item->window.flags |= WINDOW_DECORATION;
+ return qtrue;
+}
+
+// notselectable
+qboolean ItemParse_notselectable( itemDef_t *item, int handle ) {
+ listBoxDef_t *listPtr;
+ Item_ValidateTypeData(item);
+ listPtr = (listBoxDef_t*)item->typeData;
+ if (item->type == ITEM_TYPE_LISTBOX && listPtr) {
+ listPtr->notselectable = qtrue;
+ }
+ return qtrue;
+}
+
+// manually wrapped
+qboolean ItemParse_wrapped( itemDef_t *item, int handle ) {
+ item->window.flags |= WINDOW_WRAPPED;
+ return qtrue;
+}
+
+// auto wrapped
+qboolean ItemParse_autowrapped( itemDef_t *item, int handle ) {
+ item->window.flags |= WINDOW_AUTOWRAPPED;
+ return qtrue;
+}
+
+
+// horizontalscroll
+qboolean ItemParse_horizontalscroll( itemDef_t *item, int handle ) {
+ item->window.flags |= WINDOW_HORIZONTAL;
+ return qtrue;
+}
+
+// type <integer>
+qboolean ItemParse_type( itemDef_t *item, int handle ) {
+ if (!PC_Int_Parse(handle, &item->type)) {
+ return qfalse;
+ }
+ Item_ValidateTypeData(item);
+ return qtrue;
+}
+
+// elementwidth, used for listbox image elements
+// uses textalignx for storage
+qboolean ItemParse_elementwidth( itemDef_t *item, int handle ) {
+ listBoxDef_t *listPtr;
+
+ Item_ValidateTypeData(item);
+ listPtr = (listBoxDef_t*)item->typeData;
+ if (!PC_Float_Parse(handle, &listPtr->elementWidth)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+// elementheight, used for listbox image elements
+// uses textaligny for storage
+qboolean ItemParse_elementheight( itemDef_t *item, int handle ) {
+ listBoxDef_t *listPtr;
+
+ Item_ValidateTypeData(item);
+ listPtr = (listBoxDef_t*)item->typeData;
+ if (!PC_Float_Parse(handle, &listPtr->elementHeight)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+// feeder <float>
+qboolean ItemParse_feeder( itemDef_t *item, int handle ) {
+ if (!PC_Float_Parse(handle, &item->special)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+// elementtype, used to specify what type of elements a listbox contains
+// uses textstyle for storage
+qboolean ItemParse_elementtype( itemDef_t *item, int handle ) {
+ listBoxDef_t *listPtr;
+
+ Item_ValidateTypeData(item);
+ if (!item->typeData)
+ return qfalse;
+ listPtr = (listBoxDef_t*)item->typeData;
+ if (!PC_Int_Parse(handle, &listPtr->elementStyle)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+// columns sets a number of columns and an x pos and width per..
+qboolean ItemParse_columns( itemDef_t *item, int handle ) {
+ int num, i;
+ listBoxDef_t *listPtr;
+
+ Item_ValidateTypeData(item);
+ if (!item->typeData)
+ return qfalse;
+ listPtr = (listBoxDef_t*)item->typeData;
+ if (PC_Int_Parse(handle, &num)) {
+ if (num > MAX_LB_COLUMNS) {
+ num = MAX_LB_COLUMNS;
+ }
+ listPtr->numColumns = num;
+ for (i = 0; i < num; i++) {
+ int pos, width, maxChars;
+
+ if (PC_Int_Parse(handle, &pos) && PC_Int_Parse(handle, &width) && PC_Int_Parse(handle, &maxChars)) {
+ listPtr->columnInfo[i].pos = pos;
+ listPtr->columnInfo[i].width = width;
+ listPtr->columnInfo[i].maxChars = maxChars;
+ } else {
+ return qfalse;
+ }
+ }
+ } else {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_border( itemDef_t *item, int handle ) {
+ if (!PC_Int_Parse(handle, &item->window.border)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_bordersize( itemDef_t *item, int handle ) {
+ if (!PC_Float_Parse(handle, &item->window.borderSize)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_visible( itemDef_t *item, int handle ) {
+ int i;
+
+ if (!PC_Int_Parse(handle, &i)) {
+ return qfalse;
+ }
+ if (i) {
+ item->window.flags |= WINDOW_VISIBLE;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_ownerdraw( itemDef_t *item, int handle ) {
+ if (!PC_Int_Parse(handle, &item->window.ownerDraw)) {
+ return qfalse;
+ }
+ item->type = ITEM_TYPE_OWNERDRAW;
+ return qtrue;
+}
+
+qboolean ItemParse_align( itemDef_t *item, int handle ) {
+ if (!PC_Int_Parse(handle, &item->alignment)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_textalign( itemDef_t *item, int handle ) {
+ if (!PC_Int_Parse(handle, &item->textalignment)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_textalignx( itemDef_t *item, int handle ) {
+ if (!PC_Float_Parse(handle, &item->textalignx)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_textaligny( itemDef_t *item, int handle ) {
+ if (!PC_Float_Parse(handle, &item->textaligny)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_textscale( itemDef_t *item, int handle ) {
+ if (!PC_Float_Parse(handle, &item->textscale)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_textstyle( itemDef_t *item, int handle ) {
+ if (!PC_Int_Parse(handle, &item->textStyle)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_backcolor( itemDef_t *item, int handle ) {
+ int i;
+ float f;
+
+ for (i = 0; i < 4; i++) {
+ if (!PC_Float_Parse(handle, &f)) {
+ return qfalse;
+ }
+ item->window.backColor[i] = f;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_forecolor( itemDef_t *item, int handle ) {
+ int i;
+ float f;
+
+ for (i = 0; i < 4; i++) {
+ if (!PC_Float_Parse(handle, &f)) {
+ return qfalse;
+ }
+ item->window.foreColor[i] = f;
+ item->window.flags |= WINDOW_FORECOLORSET;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_bordercolor( itemDef_t *item, int handle ) {
+ int i;
+ float f;
+
+ for (i = 0; i < 4; i++) {
+ if (!PC_Float_Parse(handle, &f)) {
+ return qfalse;
+ }
+ item->window.borderColor[i] = f;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_outlinecolor( itemDef_t *item, int handle ) {
+ if (!PC_Color_Parse(handle, &item->window.outlineColor)){
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_background( itemDef_t *item, int handle ) {
+ const char *temp;
+
+ if (!PC_String_Parse(handle, &temp)) {
+ return qfalse;
+ }
+ item->window.background = DC->registerShaderNoMip(temp);
+ return qtrue;
+}
+
+qboolean ItemParse_cinematic( itemDef_t *item, int handle ) {
+ if (!PC_String_Parse(handle, &item->window.cinematicName)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_doubleClick( itemDef_t *item, int handle ) {
+ listBoxDef_t *listPtr;
+
+ Item_ValidateTypeData(item);
+ if (!item->typeData) {
+ return qfalse;
+ }
+
+ listPtr = (listBoxDef_t*)item->typeData;
+
+ if (!PC_Script_Parse(handle, &listPtr->doubleClick)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_onFocus( itemDef_t *item, int handle ) {
+ if (!PC_Script_Parse(handle, &item->onFocus)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_leaveFocus( itemDef_t *item, int handle ) {
+ if (!PC_Script_Parse(handle, &item->leaveFocus)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_mouseEnter( itemDef_t *item, int handle ) {
+ if (!PC_Script_Parse(handle, &item->mouseEnter)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_mouseExit( itemDef_t *item, int handle ) {
+ if (!PC_Script_Parse(handle, &item->mouseExit)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_mouseEnterText( itemDef_t *item, int handle ) {
+ if (!PC_Script_Parse(handle, &item->mouseEnterText)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_mouseExitText( itemDef_t *item, int handle ) {
+ if (!PC_Script_Parse(handle, &item->mouseExitText)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_action( itemDef_t *item, int handle ) {
+ if (!PC_Script_Parse(handle, &item->action)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_special( itemDef_t *item, int handle ) {
+ if (!PC_Float_Parse(handle, &item->special)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_cvarTest( itemDef_t *item, int handle ) {
+ if (!PC_String_Parse(handle, &item->cvarTest)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_cvar( itemDef_t *item, int handle ) {
+ editFieldDef_t *editPtr;
+
+ Item_ValidateTypeData(item);
+ if (!PC_String_Parse(handle, &item->cvar)) {
+ return qfalse;
+ }
+ if (item->typeData) {
+ editPtr = (editFieldDef_t*)item->typeData;
+ editPtr->minVal = -1;
+ editPtr->maxVal = -1;
+ editPtr->defVal = -1;
+ }
+ return qtrue;
+}
+
+qboolean ItemParse_maxChars( itemDef_t *item, int handle ) {
+ editFieldDef_t *editPtr;
+ int maxChars;
+
+ Item_ValidateTypeData(item);
+ if (!item->typeData)
+ return qfalse;
+
+ if (!PC_Int_Parse(handle, &maxChars)) {
+ return qfalse;
+ }
+ editPtr = (editFieldDef_t*)item->typeData;
+ editPtr->maxChars = maxChars;
+ return qtrue;
+}
+
+qboolean ItemParse_maxPaintChars( itemDef_t *item, int handle ) {
+ editFieldDef_t *editPtr;
+ int maxChars;
+
+ Item_ValidateTypeData(item);
+ if (!item->typeData)
+ return qfalse;
+
+ if (!PC_Int_Parse(handle, &maxChars)) {
+ return qfalse;
+ }
+ editPtr = (editFieldDef_t*)item->typeData;
+ editPtr->maxPaintChars = maxChars;
+ return qtrue;
+}
+
+
+
+qboolean ItemParse_cvarFloat( itemDef_t *item, int handle ) {
+ editFieldDef_t *editPtr;
+
+ Item_ValidateTypeData(item);
+ if (!item->typeData)
+ return qfalse;
+ editPtr = (editFieldDef_t*)item->typeData;
+ if (PC_String_Parse(handle, &item->cvar) &&
+ PC_Float_Parse(handle, &editPtr->defVal) &&
+ PC_Float_Parse(handle, &editPtr->minVal) &&
+ PC_Float_Parse(handle, &editPtr->maxVal)) {
+ return qtrue;
+ }
+ return qfalse;
+}
+
+qboolean ItemParse_cvarStrList( itemDef_t *item, int handle ) {
+ pc_token_t token;
+ multiDef_t *multiPtr;
+ int pass;
+
+ Item_ValidateTypeData(item);
+ if (!item->typeData)
+ return qfalse;
+ multiPtr = (multiDef_t*)item->typeData;
+ multiPtr->count = 0;
+ multiPtr->strDef = qtrue;
+
+ if (!trap_PC_ReadToken(handle, &token))
+ return qfalse;
+ if (*token.string != '{') {
+ return qfalse;
+ }
+
+ pass = 0;
+ while ( 1 ) {
+ if (!trap_PC_ReadToken(handle, &token)) {
+ PC_SourceError(handle, "end of file inside menu item\n");
+ return qfalse;
+ }
+
+ if (*token.string == '}') {
+ return qtrue;
+ }
+
+ if (*token.string == ',' || *token.string == ';') {
+ continue;
+ }
+
+ if (pass == 0) {
+ multiPtr->cvarList[multiPtr->count] = String_Alloc(token.string);
+ pass = 1;
+ } else {
+ multiPtr->cvarStr[multiPtr->count] = String_Alloc(token.string);
+ pass = 0;
+ multiPtr->count++;
+ if (multiPtr->count >= MAX_MULTI_CVARS) {
+ return qfalse;
+ }
+ }
+
+ }
+ return qfalse; // bk001205 - LCC missing return value
+}
+
+qboolean ItemParse_cvarFloatList( itemDef_t *item, int handle ) {
+ pc_token_t token;
+ multiDef_t *multiPtr;
+
+ Item_ValidateTypeData(item);
+ if (!item->typeData)
+ return qfalse;
+ multiPtr = (multiDef_t*)item->typeData;
+ multiPtr->count = 0;
+ multiPtr->strDef = qfalse;
+
+ if (!trap_PC_ReadToken(handle, &token))
+ return qfalse;
+ if (*token.string != '{') {
+ return qfalse;
+ }
+
+ while ( 1 ) {
+ if (!trap_PC_ReadToken(handle, &token)) {
+ PC_SourceError(handle, "end of file inside menu item\n");
+ return qfalse;
+ }
+
+ if (*token.string == '}') {
+ return qtrue;
+ }
+
+ if (*token.string == ',' || *token.string == ';') {
+ continue;
+ }
+
+ multiPtr->cvarList[multiPtr->count] = String_Alloc(token.string);
+ if (!PC_Float_Parse(handle, &multiPtr->cvarValue[multiPtr->count])) {
+ return qfalse;
+ }
+
+ multiPtr->count++;
+ if (multiPtr->count >= MAX_MULTI_CVARS) {
+ return qfalse;
+ }
+
+ }
+ return qfalse; // bk001205 - LCC missing return value
+}
+
+
+
+qboolean ItemParse_addColorRange( itemDef_t *item, int handle ) {
+ colorRangeDef_t color;
+
+ if (PC_Float_Parse(handle, &color.low) &&
+ PC_Float_Parse(handle, &color.high) &&
+ PC_Color_Parse(handle, &color.color) ) {
+ if (item->numColors < MAX_COLOR_RANGES) {
+ memcpy(&item->colorRanges[item->numColors], &color, sizeof(color));
+ item->numColors++;
+ }
+ return qtrue;
+ }
+ return qfalse;
+}
+
+qboolean ItemParse_ownerdrawFlag( itemDef_t *item, int handle ) {
+ int i;
+ if (!PC_Int_Parse(handle, &i)) {
+ return qfalse;
+ }
+ item->window.ownerDrawFlags |= i;
+ return qtrue;
+}
+
+qboolean ItemParse_enableCvar( itemDef_t *item, int handle ) {
+ if (PC_Script_Parse(handle, &item->enableCvar)) {
+ item->cvarFlags = CVAR_ENABLE;
+ return qtrue;
+ }
+ return qfalse;
+}
+
+qboolean ItemParse_disableCvar( itemDef_t *item, int handle ) {
+ if (PC_Script_Parse(handle, &item->enableCvar)) {
+ item->cvarFlags = CVAR_DISABLE;
+ return qtrue;
+ }
+ return qfalse;
+}
+
+qboolean ItemParse_showCvar( itemDef_t *item, int handle ) {
+ if (PC_Script_Parse(handle, &item->enableCvar)) {
+ item->cvarFlags = CVAR_SHOW;
+ return qtrue;
+ }
+ return qfalse;
+}
+
+qboolean ItemParse_hideCvar( itemDef_t *item, int handle ) {
+ if (PC_Script_Parse(handle, &item->enableCvar)) {
+ item->cvarFlags = CVAR_HIDE;
+ return qtrue;
+ }
+ return qfalse;
+}
+
+
+keywordHash_t itemParseKeywords[] = {
+ {"name", ItemParse_name, NULL},
+ {"text", ItemParse_text, NULL},
+ {"group", ItemParse_group, NULL},
+ {"asset_model", ItemParse_asset_model, NULL},
+ {"asset_shader", ItemParse_asset_shader, NULL},
+ {"model_origin", ItemParse_model_origin, NULL},
+ {"model_fovx", ItemParse_model_fovx, NULL},
+ {"model_fovy", ItemParse_model_fovy, NULL},
+ {"model_rotation", ItemParse_model_rotation, NULL},
+ {"model_angle", ItemParse_model_angle, NULL},
+ {"rect", ItemParse_rect, NULL},
+ {"style", ItemParse_style, NULL},
+ {"decoration", ItemParse_decoration, NULL},
+ {"notselectable", ItemParse_notselectable, NULL},
+ {"wrapped", ItemParse_wrapped, NULL},
+ {"autowrapped", ItemParse_autowrapped, NULL},
+ {"horizontalscroll", ItemParse_horizontalscroll, NULL},
+ {"type", ItemParse_type, NULL},
+ {"elementwidth", ItemParse_elementwidth, NULL},
+ {"elementheight", ItemParse_elementheight, NULL},
+ {"feeder", ItemParse_feeder, NULL},
+ {"elementtype", ItemParse_elementtype, NULL},
+ {"columns", ItemParse_columns, NULL},
+ {"border", ItemParse_border, NULL},
+ {"bordersize", ItemParse_bordersize, NULL},
+ {"visible", ItemParse_visible, NULL},
+ {"ownerdraw", ItemParse_ownerdraw, NULL},
+ {"align", ItemParse_align, NULL},
+ {"textalign", ItemParse_textalign, NULL},
+ {"textalignx", ItemParse_textalignx, NULL},
+ {"textaligny", ItemParse_textaligny, NULL},
+ {"textscale", ItemParse_textscale, NULL},
+ {"textstyle", ItemParse_textstyle, NULL},
+ {"backcolor", ItemParse_backcolor, NULL},
+ {"forecolor", ItemParse_forecolor, NULL},
+ {"bordercolor", ItemParse_bordercolor, NULL},
+ {"outlinecolor", ItemParse_outlinecolor, NULL},
+ {"background", ItemParse_background, NULL},
+ {"onFocus", ItemParse_onFocus, NULL},
+ {"leaveFocus", ItemParse_leaveFocus, NULL},
+ {"mouseEnter", ItemParse_mouseEnter, NULL},
+ {"mouseExit", ItemParse_mouseExit, NULL},
+ {"mouseEnterText", ItemParse_mouseEnterText, NULL},
+ {"mouseExitText", ItemParse_mouseExitText, NULL},
+ {"action", ItemParse_action, NULL},
+ {"special", ItemParse_special, NULL},
+ {"cvar", ItemParse_cvar, NULL},
+ {"maxChars", ItemParse_maxChars, NULL},
+ {"maxPaintChars", ItemParse_maxPaintChars, NULL},
+ {"focusSound", ItemParse_focusSound, NULL},
+ {"cvarFloat", ItemParse_cvarFloat, NULL},
+ {"cvarStrList", ItemParse_cvarStrList, NULL},
+ {"cvarFloatList", ItemParse_cvarFloatList, NULL},
+ {"addColorRange", ItemParse_addColorRange, NULL},
+ {"ownerdrawFlag", ItemParse_ownerdrawFlag, NULL},
+ {"enableCvar", ItemParse_enableCvar, NULL},
+ {"cvarTest", ItemParse_cvarTest, NULL},
+ {"disableCvar", ItemParse_disableCvar, NULL},
+ {"showCvar", ItemParse_showCvar, NULL},
+ {"hideCvar", ItemParse_hideCvar, NULL},
+ {"cinematic", ItemParse_cinematic, NULL},
+ {"doubleclick", ItemParse_doubleClick, NULL},
+ {NULL, NULL, NULL}
+};
+
+keywordHash_t *itemParseKeywordHash[KEYWORDHASH_SIZE];
+
+/*
+===============
+Item_SetupKeywordHash
+===============
+*/
+void Item_SetupKeywordHash(void) {
+ int i;
+
+ memset(itemParseKeywordHash, 0, sizeof(itemParseKeywordHash));
+ for (i = 0; itemParseKeywords[i].keyword; i++) {
+ KeywordHash_Add(itemParseKeywordHash, &itemParseKeywords[i]);
+ }
+}
+
+/*
+===============
+Item_Parse
+===============
+*/
+qboolean Item_Parse(int handle, itemDef_t *item) {
+ pc_token_t token;
+ keywordHash_t *key;
+
+
+ if (!trap_PC_ReadToken(handle, &token))
+ return qfalse;
+ if (*token.string != '{') {
+ return qfalse;
+ }
+ while ( 1 ) {
+ if (!trap_PC_ReadToken(handle, &token)) {
+ PC_SourceError(handle, "end of file inside menu item\n");
+ return qfalse;
+ }
+
+ if (*token.string == '}') {
+ return qtrue;
+ }
+
+ key = KeywordHash_Find(itemParseKeywordHash, token.string);
+ if (!key) {
+ PC_SourceError(handle, "unknown menu item keyword %s", token.string);
+ continue;
+ }
+ if ( !key->func(item, handle) ) {
+ PC_SourceError(handle, "couldn't parse menu item keyword %s", token.string);
+ return qfalse;
+ }
+ }
+ return qfalse; // bk001205 - LCC missing return value
+}
+
+
+// Item_InitControls
+// init's special control types
+void Item_InitControls(itemDef_t *item) {
+ if (item == NULL) {
+ return;
+ }
+ if (item->type == ITEM_TYPE_LISTBOX) {
+ listBoxDef_t *listPtr = (listBoxDef_t*)item->typeData;
+ item->cursorPos = 0;
+ if (listPtr) {
+ listPtr->cursorPos = 0;
+ listPtr->startPos = 0;
+ listPtr->endPos = 0;
+ listPtr->cursorPos = 0;
+ }
+ }
+}
+
+/*
+===============
+Menu Keyword Parse functions
+===============
+*/
+
+qboolean MenuParse_font( itemDef_t *item, int handle ) {
+ menuDef_t *menu = (menuDef_t*)item;
+ if (!PC_String_Parse(handle, &menu->font)) {
+ return qfalse;
+ }
+ if (!DC->Assets.fontRegistered) {
+ DC->registerFont(menu->font, 48, &DC->Assets.textFont);
+ DC->Assets.fontRegistered = qtrue;
+ }
+ return qtrue;
+}
+
+qboolean MenuParse_name( itemDef_t *item, int handle ) {
+ menuDef_t *menu = (menuDef_t*)item;
+ if (!PC_String_Parse(handle, &menu->window.name)) {
+ return qfalse;
+ }
+ if (Q_stricmp(menu->window.name, "main") == 0) {
+ // default main as having focus
+ //menu->window.flags |= WINDOW_HASFOCUS;
+ }
+ return qtrue;
+}
+
+qboolean MenuParse_fullscreen( itemDef_t *item, int handle ) {
+ menuDef_t *menu = (menuDef_t*)item;
+ if (!PC_Int_Parse(handle, (int*) &menu->fullScreen)) { // bk001206 - cast qboolean
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean MenuParse_rect( itemDef_t *item, int handle ) {
+ menuDef_t *menu = (menuDef_t*)item;
+ if (!PC_Rect_Parse(handle, &menu->window.rect)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean MenuParse_style( itemDef_t *item, int handle ) {
+ menuDef_t *menu = (menuDef_t*)item;
+ if (!PC_Int_Parse(handle, &menu->window.style)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean MenuParse_visible( itemDef_t *item, int handle ) {
+ int i;
+ menuDef_t *menu = (menuDef_t*)item;
+
+ if (!PC_Int_Parse(handle, &i)) {
+ return qfalse;
+ }
+ if (i) {
+ menu->window.flags |= WINDOW_VISIBLE;
+ }
+ return qtrue;
+}
+
+qboolean MenuParse_onOpen( itemDef_t *item, int handle ) {
+ menuDef_t *menu = (menuDef_t*)item;
+ if (!PC_Script_Parse(handle, &menu->onOpen)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean MenuParse_onClose( itemDef_t *item, int handle ) {
+ menuDef_t *menu = (menuDef_t*)item;
+ if (!PC_Script_Parse(handle, &menu->onClose)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean MenuParse_onESC( itemDef_t *item, int handle ) {
+ menuDef_t *menu = (menuDef_t*)item;
+ if (!PC_Script_Parse(handle, &menu->onESC)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+
+
+qboolean MenuParse_border( itemDef_t *item, int handle ) {
+ menuDef_t *menu = (menuDef_t*)item;
+ if (!PC_Int_Parse(handle, &menu->window.border)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean MenuParse_borderSize( itemDef_t *item, int handle ) {
+ menuDef_t *menu = (menuDef_t*)item;
+ if (!PC_Float_Parse(handle, &menu->window.borderSize)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean MenuParse_backcolor( itemDef_t *item, int handle ) {
+ int i;
+ float f;
+ menuDef_t *menu = (menuDef_t*)item;
+
+ for (i = 0; i < 4; i++) {
+ if (!PC_Float_Parse(handle, &f)) {
+ return qfalse;
+ }
+ menu->window.backColor[i] = f;
+ }
+ return qtrue;
+}
+
+qboolean MenuParse_forecolor( itemDef_t *item, int handle ) {
+ int i;
+ float f;
+ menuDef_t *menu = (menuDef_t*)item;
+
+ for (i = 0; i < 4; i++) {
+ if (!PC_Float_Parse(handle, &f)) {
+ return qfalse;
+ }
+ menu->window.foreColor[i] = f;
+ menu->window.flags |= WINDOW_FORECOLORSET;
+ }
+ return qtrue;
+}
+
+qboolean MenuParse_bordercolor( itemDef_t *item, int handle ) {
+ int i;
+ float f;
+ menuDef_t *menu = (menuDef_t*)item;
+
+ for (i = 0; i < 4; i++) {
+ if (!PC_Float_Parse(handle, &f)) {
+ return qfalse;
+ }
+ menu->window.borderColor[i] = f;
+ }
+ return qtrue;
+}
+
+qboolean MenuParse_focuscolor( itemDef_t *item, int handle ) {
+ int i;
+ float f;
+ menuDef_t *menu = (menuDef_t*)item;
+
+ for (i = 0; i < 4; i++) {
+ if (!PC_Float_Parse(handle, &f)) {
+ return qfalse;
+ }
+ menu->focusColor[i] = f;
+ }
+ return qtrue;
+}
+
+qboolean MenuParse_disablecolor( itemDef_t *item, int handle ) {
+ int i;
+ float f;
+ menuDef_t *menu = (menuDef_t*)item;
+ for (i = 0; i < 4; i++) {
+ if (!PC_Float_Parse(handle, &f)) {
+ return qfalse;
+ }
+ menu->disableColor[i] = f;
+ }
+ return qtrue;
+}
+
+
+qboolean MenuParse_outlinecolor( itemDef_t *item, int handle ) {
+ menuDef_t *menu = (menuDef_t*)item;
+ if (!PC_Color_Parse(handle, &menu->window.outlineColor)){
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean MenuParse_background( itemDef_t *item, int handle ) {
+ const char *buff;
+ menuDef_t *menu = (menuDef_t*)item;
+
+ if (!PC_String_Parse(handle, &buff)) {
+ return qfalse;
+ }
+ menu->window.background = DC->registerShaderNoMip(buff);
+ return qtrue;
+}
+
+qboolean MenuParse_cinematic( itemDef_t *item, int handle ) {
+ menuDef_t *menu = (menuDef_t*)item;
+
+ if (!PC_String_Parse(handle, &menu->window.cinematicName)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean MenuParse_ownerdrawFlag( itemDef_t *item, int handle ) {
+ int i;
+ menuDef_t *menu = (menuDef_t*)item;
+
+ if (!PC_Int_Parse(handle, &i)) {
+ return qfalse;
+ }
+ menu->window.ownerDrawFlags |= i;
+ return qtrue;
+}
+
+qboolean MenuParse_ownerdraw( itemDef_t *item, int handle ) {
+ menuDef_t *menu = (menuDef_t*)item;
+
+ if (!PC_Int_Parse(handle, &menu->window.ownerDraw)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+
+// decoration
+qboolean MenuParse_popup( itemDef_t *item, int handle ) {
+ menuDef_t *menu = (menuDef_t*)item;
+ menu->window.flags |= WINDOW_POPUP;
+ return qtrue;
+}
+
+
+qboolean MenuParse_outOfBounds( itemDef_t *item, int handle ) {
+ menuDef_t *menu = (menuDef_t*)item;
+
+ menu->window.flags |= WINDOW_OOB_CLICK;
+ return qtrue;
+}
+
+qboolean MenuParse_soundLoop( itemDef_t *item, int handle ) {
+ menuDef_t *menu = (menuDef_t*)item;
+
+ if (!PC_String_Parse(handle, &menu->soundName)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean MenuParse_fadeClamp( itemDef_t *item, int handle ) {
+ menuDef_t *menu = (menuDef_t*)item;
+
+ if (!PC_Float_Parse(handle, &menu->fadeClamp)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+qboolean MenuParse_fadeAmount( itemDef_t *item, int handle ) {
+ menuDef_t *menu = (menuDef_t*)item;
+
+ if (!PC_Float_Parse(handle, &menu->fadeAmount)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+
+qboolean MenuParse_fadeCycle( itemDef_t *item, int handle ) {
+ menuDef_t *menu = (menuDef_t*)item;
+
+ if (!PC_Int_Parse(handle, &menu->fadeCycle)) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+
+qboolean MenuParse_itemDef( itemDef_t *item, int handle ) {
+ menuDef_t *menu = (menuDef_t*)item;
+ if (menu->itemCount < MAX_MENUITEMS) {
+ menu->items[menu->itemCount] = UI_Alloc(sizeof(itemDef_t));
+ Item_Init(menu->items[menu->itemCount]);
+ if (!Item_Parse(handle, menu->items[menu->itemCount])) {
+ return qfalse;
+ }
+ Item_InitControls(menu->items[menu->itemCount]);
+ menu->items[menu->itemCount++]->parent = menu;
+ }
+ return qtrue;
+}
+
+keywordHash_t menuParseKeywords[] = {
+ {"font", MenuParse_font, NULL},
+ {"name", MenuParse_name, NULL},
+ {"fullscreen", MenuParse_fullscreen, NULL},
+ {"rect", MenuParse_rect, NULL},
+ {"style", MenuParse_style, NULL},
+ {"visible", MenuParse_visible, NULL},
+ {"onOpen", MenuParse_onOpen, NULL},
+ {"onClose", MenuParse_onClose, NULL},
+ {"onESC", MenuParse_onESC, NULL},
+ {"border", MenuParse_border, NULL},
+ {"borderSize", MenuParse_borderSize, NULL},
+ {"backcolor", MenuParse_backcolor, NULL},
+ {"forecolor", MenuParse_forecolor, NULL},
+ {"bordercolor", MenuParse_bordercolor, NULL},
+ {"focuscolor", MenuParse_focuscolor, NULL},
+ {"disablecolor", MenuParse_disablecolor, NULL},
+ {"outlinecolor", MenuParse_outlinecolor, NULL},
+ {"background", MenuParse_background, NULL},
+ {"ownerdraw", MenuParse_ownerdraw, NULL},
+ {"ownerdrawFlag", MenuParse_ownerdrawFlag, NULL},
+ {"outOfBoundsClick", MenuParse_outOfBounds, NULL},
+ {"soundLoop", MenuParse_soundLoop, NULL},
+ {"itemDef", MenuParse_itemDef, NULL},
+ {"cinematic", MenuParse_cinematic, NULL},
+ {"popup", MenuParse_popup, NULL},
+ {"fadeClamp", MenuParse_fadeClamp, NULL},
+ {"fadeCycle", MenuParse_fadeCycle, NULL},
+ {"fadeAmount", MenuParse_fadeAmount, NULL},
+ {NULL, NULL, NULL}
+};
+
+keywordHash_t *menuParseKeywordHash[KEYWORDHASH_SIZE];
+
+/*
+===============
+Menu_SetupKeywordHash
+===============
+*/
+void Menu_SetupKeywordHash(void) {
+ int i;
+
+ memset(menuParseKeywordHash, 0, sizeof(menuParseKeywordHash));
+ for (i = 0; menuParseKeywords[i].keyword; i++) {
+ KeywordHash_Add(menuParseKeywordHash, &menuParseKeywords[i]);
+ }
+}
+
+/*
+===============
+Menu_Parse
+===============
+*/
+qboolean Menu_Parse(int handle, menuDef_t *menu) {
+ pc_token_t token;
+ keywordHash_t *key;
+
+ if (!trap_PC_ReadToken(handle, &token))
+ return qfalse;
+ if (*token.string != '{') {
+ return qfalse;
+ }
+
+ while ( 1 ) {
+
+ memset(&token, 0, sizeof(pc_token_t));
+ if (!trap_PC_ReadToken(handle, &token)) {
+ PC_SourceError(handle, "end of file inside menu\n");
+ return qfalse;
+ }
+
+ if (*token.string == '}') {
+ return qtrue;
+ }
+
+ key = KeywordHash_Find(menuParseKeywordHash, token.string);
+ if (!key) {
+ PC_SourceError(handle, "unknown menu keyword %s", token.string);
+ continue;
+ }
+ if ( !key->func((itemDef_t*)menu, handle) ) {
+ PC_SourceError(handle, "couldn't parse menu keyword %s", token.string);
+ return qfalse;
+ }
+ }
+ return qfalse; // bk001205 - LCC missing return value
+}
+
+/*
+===============
+Menu_New
+===============
+*/
+void Menu_New(int handle) {
+ menuDef_t *menu = &Menus[menuCount];
+
+ if (menuCount < MAX_MENUS) {
+ Menu_Init(menu);
+ if (Menu_Parse(handle, menu)) {
+ Menu_PostParse(menu);
+ menuCount++;
+ }
+ }
+}
+
+int Menu_Count() {
+ return menuCount;
+}
+
+void Menu_PaintAll() {
+ int i;
+ if (captureFunc) {
+ captureFunc(captureData);
+ }
+
+ for (i = 0; i < Menu_Count(); i++) {
+ Menu_Paint(&Menus[i], qfalse);
+ }
+
+ if (debugMode) {
+ vec4_t v = {1, 1, 1, 1};
+ DC->drawText(5, 25, .5, v, va("fps: %f", DC->FPS), 0, 0, 0);
+ }
+}
+
+void Menu_Reset() {
+ menuCount = 0;
+}
+
+displayContextDef_t *Display_GetContext() {
+ return DC;
+}
+
+#ifndef MISSIONPACK // bk001206
+static float captureX;
+static float captureY;
+#endif
+
+void *Display_CaptureItem(int x, int y) {
+ int i;
+
+ for (i = 0; i < menuCount; i++) {
+ // turn off focus each item
+ // menu->items[i].window.flags &= ~WINDOW_HASFOCUS;
+ if (Rect_ContainsPoint(&Menus[i].window.rect, x, y)) {
+ return &Menus[i];
+ }
+ }
+ return NULL;
+}
+
+
+// FIXME:
+qboolean Display_MouseMove(void *p, int x, int y) {
+ int i;
+ menuDef_t *menu = p;
+
+ if (menu == NULL) {
+ menu = Menu_GetFocused();
+ if (menu) {
+ if (menu->window.flags & WINDOW_POPUP) {
+ Menu_HandleMouseMove(menu, x, y);
+ return qtrue;
+ }
+ }
+ for (i = 0; i < menuCount; i++) {
+ Menu_HandleMouseMove(&Menus[i], x, y);
+ }
+ } else {
+ menu->window.rect.x += x;
+ menu->window.rect.y += y;
+ Menu_UpdatePosition(menu);
+ }
+ return qtrue;
+
+}
+
+int Display_CursorType(int x, int y) {
+ int i;
+ for (i = 0; i < menuCount; i++) {
+ rectDef_t r2;
+ r2.x = Menus[i].window.rect.x - 3;
+ r2.y = Menus[i].window.rect.y - 3;
+ r2.w = r2.h = 7;
+ if (Rect_ContainsPoint(&r2, x, y)) {
+ return CURSOR_SIZER;
+ }
+ }
+ return CURSOR_ARROW;
+}
+
+
+void Display_HandleKey(int key, qboolean down, int x, int y) {
+ menuDef_t *menu = Display_CaptureItem(x, y);
+ if (menu == NULL) {
+ menu = Menu_GetFocused();
+ }
+ if (menu) {
+ Menu_HandleKey(menu, key, down );
+ }
+}
+
+static void Window_CacheContents(windowDef_t *window) {
+ if (window) {
+ if (window->cinematicName) {
+ int cin = DC->playCinematic(window->cinematicName, 0, 0, 0, 0);
+ DC->stopCinematic(cin);
+ }
+ }
+}
+
+
+static void Item_CacheContents(itemDef_t *item) {
+ if (item) {
+ Window_CacheContents(&item->window);
+ }
+
+}
+
+static void Menu_CacheContents(menuDef_t *menu) {
+ if (menu) {
+ int i;
+ Window_CacheContents(&menu->window);
+ for (i = 0; i < menu->itemCount; i++) {
+ Item_CacheContents(menu->items[i]);
+ }
+
+ if (menu->soundName && *menu->soundName) {
+ DC->registerSound(menu->soundName, qfalse);
+ }
+ }
+
+}
+
+void Display_CacheAll() {
+ int i;
+ for (i = 0; i < menuCount; i++) {
+ Menu_CacheContents(&Menus[i]);
+ }
+}
+
+
+static qboolean Menu_OverActiveItem(menuDef_t *menu, float x, float y) {
+ if (menu && menu->window.flags & (WINDOW_VISIBLE | WINDOW_FORCED)) {
+ if (Rect_ContainsPoint(&menu->window.rect, x, y)) {
+ int i;
+ for (i = 0; i < menu->itemCount; i++) {
+ // turn off focus each item
+ // menu->items[i].window.flags &= ~WINDOW_HASFOCUS;
+
+ if (!(menu->items[i]->window.flags & (WINDOW_VISIBLE | WINDOW_FORCED))) {
+ continue;
+ }
+
+ if (menu->items[i]->window.flags & WINDOW_DECORATION) {
+ continue;
+ }
+
+ if (Rect_ContainsPoint(&menu->items[i]->window.rect, x, y)) {
+ itemDef_t *overItem = menu->items[i];
+ if (overItem->type == ITEM_TYPE_TEXT && overItem->text) {
+ if (Rect_ContainsPoint(Item_CorrectedTextRect(overItem), x, y)) {
+ return qtrue;
+ } else {
+ continue;
+ }
+ } else {
+ return qtrue;
+ }
+ }
+ }
+
+ }
+ }
+ return qfalse;
+}
+
diff --git a/code/ui/ui_shared.h b/code/ui/ui_shared.h
new file mode 100755
index 0000000..037959e
--- /dev/null
+++ b/code/ui/ui_shared.h
@@ -0,0 +1,450 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __UI_SHARED_H
+#define __UI_SHARED_H
+
+
+#include "../game/q_shared.h"
+#include "../cgame/tr_types.h"
+#include "keycodes.h"
+
+#include "../../ui/menudef.h"
+
+#define MAX_MENUNAME 32
+#define MAX_ITEMTEXT 64
+#define MAX_ITEMACTION 64
+#define MAX_MENUDEFFILE 4096
+#define MAX_MENUFILE 32768
+#define MAX_MENUS 64
+#define MAX_MENUITEMS 96
+#define MAX_COLOR_RANGES 10
+#define MAX_OPEN_MENUS 16
+
+#define WINDOW_MOUSEOVER 0x00000001 // mouse is over it, non exclusive
+#define WINDOW_HASFOCUS 0x00000002 // has cursor focus, exclusive
+#define WINDOW_VISIBLE 0x00000004 // is visible
+#define WINDOW_GREY 0x00000008 // is visible but grey ( non-active )
+#define WINDOW_DECORATION 0x00000010 // for decoration only, no mouse, keyboard, etc..
+#define WINDOW_FADINGOUT 0x00000020 // fading out, non-active
+#define WINDOW_FADINGIN 0x00000040 // fading in
+#define WINDOW_MOUSEOVERTEXT 0x00000080 // mouse is over it, non exclusive
+#define WINDOW_INTRANSITION 0x00000100 // window is in transition
+#define WINDOW_FORECOLORSET 0x00000200 // forecolor was explicitly set ( used to color alpha images or not )
+#define WINDOW_HORIZONTAL 0x00000400 // for list boxes and sliders, vertical is default this is set of horizontal
+#define WINDOW_LB_LEFTARROW 0x00000800 // mouse is over left/up arrow
+#define WINDOW_LB_RIGHTARROW 0x00001000 // mouse is over right/down arrow
+#define WINDOW_LB_THUMB 0x00002000 // mouse is over thumb
+#define WINDOW_LB_PGUP 0x00004000 // mouse is over page up
+#define WINDOW_LB_PGDN 0x00008000 // mouse is over page down
+#define WINDOW_ORBITING 0x00010000 // item is in orbit
+#define WINDOW_OOB_CLICK 0x00020000 // close on out of bounds click
+#define WINDOW_WRAPPED 0x00040000 // manually wrap text
+#define WINDOW_AUTOWRAPPED 0x00080000 // auto wrap text
+#define WINDOW_FORCED 0x00100000 // forced open
+#define WINDOW_POPUP 0x00200000 // popup
+#define WINDOW_BACKCOLORSET 0x00400000 // backcolor was explicitly set
+#define WINDOW_TIMEDVISIBLE 0x00800000 // visibility timing ( NOT implemented )
+
+
+// CGAME cursor type bits
+#define CURSOR_NONE 0x00000001
+#define CURSOR_ARROW 0x00000002
+#define CURSOR_SIZER 0x00000004
+
+#ifdef CGAME
+#define STRING_POOL_SIZE 128*1024
+#else
+#define STRING_POOL_SIZE 384*1024
+#endif
+#define MAX_STRING_HANDLES 4096
+
+#define MAX_SCRIPT_ARGS 12
+#define MAX_EDITFIELD 256
+
+#define ART_FX_BASE "menu/art/fx_base"
+#define ART_FX_BLUE "menu/art/fx_blue"
+#define ART_FX_CYAN "menu/art/fx_cyan"
+#define ART_FX_GREEN "menu/art/fx_grn"
+#define ART_FX_RED "menu/art/fx_red"
+#define ART_FX_TEAL "menu/art/fx_teal"
+#define ART_FX_WHITE "menu/art/fx_white"
+#define ART_FX_YELLOW "menu/art/fx_yel"
+
+#define ASSET_GRADIENTBAR "ui/assets/gradientbar2.tga"
+#define ASSET_SCROLLBAR "ui/assets/scrollbar.tga"
+#define ASSET_SCROLLBAR_ARROWDOWN "ui/assets/scrollbar_arrow_dwn_a.tga"
+#define ASSET_SCROLLBAR_ARROWUP "ui/assets/scrollbar_arrow_up_a.tga"
+#define ASSET_SCROLLBAR_ARROWLEFT "ui/assets/scrollbar_arrow_left.tga"
+#define ASSET_SCROLLBAR_ARROWRIGHT "ui/assets/scrollbar_arrow_right.tga"
+#define ASSET_SCROLL_THUMB "ui/assets/scrollbar_thumb.tga"
+#define ASSET_SLIDER_BAR "ui/assets/slider2.tga"
+#define ASSET_SLIDER_THUMB "ui/assets/sliderbutt_1.tga"
+#define SCROLLBAR_SIZE 16.0
+#define SLIDER_WIDTH 96.0
+#define SLIDER_HEIGHT 16.0
+#define SLIDER_THUMB_WIDTH 12.0
+#define SLIDER_THUMB_HEIGHT 20.0
+#define NUM_CROSSHAIRS 10
+
+typedef struct {
+ const char *command;
+ const char *args[MAX_SCRIPT_ARGS];
+} scriptDef_t;
+
+
+typedef struct {
+ float x; // horiz position
+ float y; // vert position
+ float w; // width
+ float h; // height;
+} rectDef_t;
+
+typedef rectDef_t Rectangle;
+
+// FIXME: do something to separate text vs window stuff
+typedef struct {
+ Rectangle rect; // client coord rectangle
+ Rectangle rectClient; // screen coord rectangle
+ const char *name; //
+ const char *group; // if it belongs to a group
+ const char *cinematicName; // cinematic name
+ int cinematic; // cinematic handle
+ int style; //
+ int border; //
+ int ownerDraw; // ownerDraw style
+ int ownerDrawFlags; // show flags for ownerdraw items
+ float borderSize; //
+ int flags; // visible, focus, mouseover, cursor
+ Rectangle rectEffects; // for various effects
+ Rectangle rectEffects2; // for various effects
+ int offsetTime; // time based value for various effects
+ int nextTime; // time next effect should cycle
+ vec4_t foreColor; // text color
+ vec4_t backColor; // border color
+ vec4_t borderColor; // border color
+ vec4_t outlineColor; // border color
+ qhandle_t background; // background asset
+} windowDef_t;
+
+typedef windowDef_t Window;
+
+typedef struct {
+ vec4_t color;
+ float low;
+ float high;
+} colorRangeDef_t;
+
+// FIXME: combine flags into bitfields to save space
+// FIXME: consolidate all of the common stuff in one structure for menus and items
+// THINKABOUTME: is there any compelling reason not to have items contain items
+// and do away with a menu per say.. major issue is not being able to dynamically allocate
+// and destroy stuff.. Another point to consider is adding an alloc free call for vm's and have
+// the engine just allocate the pool for it based on a cvar
+// many of the vars are re-used for different item types, as such they are not always named appropriately
+// the benefits of c++ in DOOM will greatly help crap like this
+// FIXME: need to put a type ptr that points to specific type info per type
+//
+#define MAX_LB_COLUMNS 16
+
+typedef struct columnInfo_s {
+ int pos;
+ int width;
+ int maxChars;
+} columnInfo_t;
+
+typedef struct listBoxDef_s {
+ int startPos;
+ int endPos;
+ int drawPadding;
+ int cursorPos;
+ float elementWidth;
+ float elementHeight;
+ int elementStyle;
+ int numColumns;
+ columnInfo_t columnInfo[MAX_LB_COLUMNS];
+ const char *doubleClick;
+ qboolean notselectable;
+} listBoxDef_t;
+
+typedef struct editFieldDef_s {
+ float minVal; // edit field limits
+ float maxVal; //
+ float defVal; //
+ float range; //
+ int maxChars; // for edit fields
+ int maxPaintChars; // for edit fields
+ int paintOffset; //
+} editFieldDef_t;
+
+#define MAX_MULTI_CVARS 32
+
+typedef struct multiDef_s {
+ const char *cvarList[MAX_MULTI_CVARS];
+ const char *cvarStr[MAX_MULTI_CVARS];
+ float cvarValue[MAX_MULTI_CVARS];
+ int count;
+ qboolean strDef;
+} multiDef_t;
+
+typedef struct modelDef_s {
+ int angle;
+ vec3_t origin;
+ float fov_x;
+ float fov_y;
+ int rotationSpeed;
+} modelDef_t;
+
+#define CVAR_ENABLE 0x00000001
+#define CVAR_DISABLE 0x00000002
+#define CVAR_SHOW 0x00000004
+#define CVAR_HIDE 0x00000008
+
+typedef struct itemDef_s {
+ Window window; // common positional, border, style, layout info
+ Rectangle textRect; // rectangle the text ( if any ) consumes
+ int type; // text, button, radiobutton, checkbox, textfield, listbox, combo
+ int alignment; // left center right
+ int textalignment; // ( optional ) alignment for text within rect based on text width
+ float textalignx; // ( optional ) text alignment x coord
+ float textaligny; // ( optional ) text alignment x coord
+ float textscale; // scale percentage from 72pts
+ int textStyle; // ( optional ) style, normal and shadowed are it for now
+ const char *text; // display text
+ void *parent; // menu owner
+ qhandle_t asset; // handle to asset
+ const char *mouseEnterText; // mouse enter script
+ const char *mouseExitText; // mouse exit script
+ const char *mouseEnter; // mouse enter script
+ const char *mouseExit; // mouse exit script
+ const char *action; // select script
+ const char *onFocus; // select script
+ const char *leaveFocus; // select script
+ const char *cvar; // associated cvar
+ const char *cvarTest; // associated cvar for enable actions
+ const char *enableCvar; // enable, disable, show, or hide based on value, this can contain a list
+ int cvarFlags; // what type of action to take on cvarenables
+ sfxHandle_t focusSound;
+ int numColors; // number of color ranges
+ colorRangeDef_t colorRanges[MAX_COLOR_RANGES];
+ float special; // used for feeder id's etc.. diff per type
+ int cursorPos; // cursor position in characters
+ void *typeData; // type specific data ptr's
+} itemDef_t;
+
+typedef struct {
+ Window window;
+ const char *font; // font
+ qboolean fullScreen; // covers entire screen
+ int itemCount; // number of items;
+ int fontIndex; //
+ int cursorItem; // which item as the cursor
+ int fadeCycle; //
+ float fadeClamp; //
+ float fadeAmount; //
+ const char *onOpen; // run when the menu is first opened
+ const char *onClose; // run when the menu is closed
+ const char *onESC; // run when the menu is closed
+ const char *soundName; // background loop sound for menu
+
+ vec4_t focusColor; // focus color for items
+ vec4_t disableColor; // focus color for items
+ itemDef_t *items[MAX_MENUITEMS]; // items this menu contains
+} menuDef_t;
+
+typedef struct {
+ const char *fontStr;
+ const char *cursorStr;
+ const char *gradientStr;
+ fontInfo_t textFont;
+ fontInfo_t smallFont;
+ fontInfo_t bigFont;
+ qhandle_t cursor;
+ qhandle_t gradientBar;
+ qhandle_t scrollBarArrowUp;
+ qhandle_t scrollBarArrowDown;
+ qhandle_t scrollBarArrowLeft;
+ qhandle_t scrollBarArrowRight;
+ qhandle_t scrollBar;
+ qhandle_t scrollBarThumb;
+ qhandle_t buttonMiddle;
+ qhandle_t buttonInside;
+ qhandle_t solidBox;
+ qhandle_t sliderBar;
+ qhandle_t sliderThumb;
+ sfxHandle_t menuEnterSound;
+ sfxHandle_t menuExitSound;
+ sfxHandle_t menuBuzzSound;
+ sfxHandle_t itemFocusSound;
+ float fadeClamp;
+ int fadeCycle;
+ float fadeAmount;
+ float shadowX;
+ float shadowY;
+ vec4_t shadowColor;
+ float shadowFadeClamp;
+ qboolean fontRegistered;
+
+ // player settings
+ qhandle_t fxBasePic;
+ qhandle_t fxPic[7];
+ qhandle_t crosshairShader[NUM_CROSSHAIRS];
+
+} cachedAssets_t;
+
+typedef struct {
+ const char *name;
+ void (*handler) (itemDef_t *item, char** args);
+} commandDef_t;
+
+typedef struct {
+ qhandle_t (*registerShaderNoMip) (const char *p);
+ void (*setColor) (const vec4_t v);
+ void (*drawHandlePic) (float x, float y, float w, float h, qhandle_t asset);
+ void (*drawStretchPic) (float x, float y, float w, float h, float s1, float t1, float s2, float t2, qhandle_t hShader );
+ void (*drawText) (float x, float y, float scale, vec4_t color, const char *text, float adjust, int limit, int style );
+ int (*textWidth) (const char *text, float scale, int limit);
+ int (*textHeight) (const char *text, float scale, int limit);
+ qhandle_t (*registerModel) (const char *p);
+ void (*modelBounds) (qhandle_t model, vec3_t min, vec3_t max);
+ void (*fillRect) ( float x, float y, float w, float h, const vec4_t color);
+ void (*drawRect) ( float x, float y, float w, float h, float size, const vec4_t color);
+ void (*drawSides) (float x, float y, float w, float h, float size);
+ void (*drawTopBottom) (float x, float y, float w, float h, float size);
+ void (*clearScene) ();
+ void (*addRefEntityToScene) (const refEntity_t *re );
+ void (*renderScene) ( const refdef_t *fd );
+ void (*registerFont) (const char *pFontname, int pointSize, fontInfo_t *font);
+ void (*ownerDrawItem) (float x, float y, float w, float h, float text_x, float text_y, int ownerDraw, int ownerDrawFlags, int align, float special, float scale, vec4_t color, qhandle_t shader, int textStyle);
+ float (*getValue) (int ownerDraw);
+ qboolean (*ownerDrawVisible) (int flags);
+ void (*runScript)(char **p);
+ void (*getTeamColor)(vec4_t *color);
+ void (*getCVarString)(const char *cvar, char *buffer, int bufsize);
+ float (*getCVarValue)(const char *cvar);
+ void (*setCVar)(const char *cvar, const char *value);
+ void (*drawTextWithCursor)(float x, float y, float scale, vec4_t color, const char *text, int cursorPos, char cursor, int limit, int style);
+ void (*setOverstrikeMode)(qboolean b);
+ qboolean (*getOverstrikeMode)();
+ void (*startLocalSound)( sfxHandle_t sfx, int channelNum );
+ qboolean (*ownerDrawHandleKey)(int ownerDraw, int flags, float *special, int key);
+ int (*feederCount)(float feederID);
+ const char *(*feederItemText)(float feederID, int index, int column, qhandle_t *handle);
+ qhandle_t (*feederItemImage)(float feederID, int index);
+ void (*feederSelection)(float feederID, int index);
+ void (*keynumToStringBuf)( int keynum, char *buf, int buflen );
+ void (*getBindingBuf)( int keynum, char *buf, int buflen );
+ void (*setBinding)( int keynum, const char *binding );
+ void (*executeText)(int exec_when, const char *text );
+ void (*Error)(int level, const char *error, ...);
+ void (*Print)(const char *msg, ...);
+ void (*Pause)(qboolean b);
+ int (*ownerDrawWidth)(int ownerDraw, float scale);
+ sfxHandle_t (*registerSound)(const char *name, qboolean compressed);
+ void (*startBackgroundTrack)( const char *intro, const char *loop);
+ void (*stopBackgroundTrack)();
+ int (*playCinematic)(const char *name, float x, float y, float w, float h);
+ void (*stopCinematic)(int handle);
+ void (*drawCinematic)(int handle, float x, float y, float w, float h);
+ void (*runCinematicFrame)(int handle);
+
+ float yscale;
+ float xscale;
+ float bias;
+ int realTime;
+ int frameTime;
+ int cursorx;
+ int cursory;
+ qboolean debug;
+
+ cachedAssets_t Assets;
+
+ glconfig_t glconfig;
+ qhandle_t whiteShader;
+ qhandle_t gradientImage;
+ qhandle_t cursor;
+ float FPS;
+
+} displayContextDef_t;
+
+const char *String_Alloc(const char *p);
+void String_Init();
+void String_Report();
+void Init_Display(displayContextDef_t *dc);
+void Display_ExpandMacros(char * buff);
+void Menu_Init(menuDef_t *menu);
+void Item_Init(itemDef_t *item);
+void Menu_PostParse(menuDef_t *menu);
+menuDef_t *Menu_GetFocused();
+void Menu_HandleKey(menuDef_t *menu, int key, qboolean down);
+void Menu_HandleMouseMove(menuDef_t *menu, float x, float y);
+void Menu_ScrollFeeder(menuDef_t *menu, int feeder, qboolean down);
+qboolean Float_Parse(char **p, float *f);
+qboolean Color_Parse(char **p, vec4_t *c);
+qboolean Int_Parse(char **p, int *i);
+qboolean Rect_Parse(char **p, rectDef_t *r);
+qboolean String_Parse(char **p, const char **out);
+qboolean Script_Parse(char **p, const char **out);
+qboolean PC_Float_Parse(int handle, float *f);
+qboolean PC_Color_Parse(int handle, vec4_t *c);
+qboolean PC_Int_Parse(int handle, int *i);
+qboolean PC_Rect_Parse(int handle, rectDef_t *r);
+qboolean PC_String_Parse(int handle, const char **out);
+qboolean PC_Script_Parse(int handle, const char **out);
+int Menu_Count();
+void Menu_New(int handle);
+void Menu_PaintAll();
+menuDef_t *Menus_ActivateByName(const char *p);
+void Menu_Reset();
+qboolean Menus_AnyFullScreenVisible();
+void Menus_Activate(menuDef_t *menu);
+
+displayContextDef_t *Display_GetContext();
+void *Display_CaptureItem(int x, int y);
+qboolean Display_MouseMove(void *p, int x, int y);
+int Display_CursorType(int x, int y);
+qboolean Display_KeyBindPending();
+void Menus_OpenByName(const char *p);
+menuDef_t *Menus_FindByName(const char *p);
+void Menus_ShowByName(const char *p);
+void Menus_CloseByName(const char *p);
+void Display_HandleKey(int key, qboolean down, int x, int y);
+void LerpColor(vec4_t a, vec4_t b, vec4_t c, float t);
+void Menus_CloseAll();
+void Menu_Paint(menuDef_t *menu, qboolean forcePaint);
+void Menu_SetFeederSelection(menuDef_t *menu, int feeder, int index, const char *name);
+void Display_CacheAll();
+
+void *UI_Alloc( int size );
+void UI_InitMemory( void );
+qboolean UI_OutOfMemory();
+
+void Controls_GetConfig( void );
+void Controls_SetConfig(qboolean restart);
+void Controls_SetDefaults( void );
+
+int trap_PC_AddGlobalDefine( char *define );
+int trap_PC_LoadSource( const char *filename );
+int trap_PC_FreeSource( int handle );
+int trap_PC_ReadToken( int handle, pc_token_t *pc_token );
+int trap_PC_SourceFileAndLine( int handle, char *filename, int *line );
+
+#endif
diff --git a/code/ui/ui_syscalls.asm b/code/ui/ui_syscalls.asm
new file mode 100755
index 0000000..d4579ac
--- /dev/null
+++ b/code/ui/ui_syscalls.asm
@@ -0,0 +1,101 @@
+code
+
+equ trap_Error -1
+equ trap_Print -2
+equ trap_Milliseconds -3
+equ trap_Cvar_Set -4
+equ trap_Cvar_VariableValue -5
+equ trap_Cvar_VariableStringBuffer -6
+equ trap_Cvar_SetValue -7
+equ trap_Cvar_Reset -8
+equ trap_Cvar_Create -9
+equ trap_Cvar_InfoStringBuffer -10
+equ trap_Argc -11
+equ trap_Argv -12
+equ trap_Cmd_ExecuteText -13
+equ trap_FS_FOpenFile -14
+equ trap_FS_Read -15
+equ trap_FS_Write -16
+equ trap_FS_FCloseFile -17
+equ trap_FS_GetFileList -18
+equ trap_R_RegisterModel -19
+equ trap_R_RegisterSkin -20
+equ trap_R_RegisterShaderNoMip -21
+equ trap_R_ClearScene -22
+equ trap_R_AddRefEntityToScene -23
+equ trap_R_AddPolyToScene -24
+equ trap_R_AddLightToScene -25
+equ trap_R_RenderScene -26
+equ trap_R_SetColor -27
+equ trap_R_DrawStretchPic -28
+equ trap_UpdateScreen -29
+equ trap_CM_LerpTag -30
+equ trap_CM_LoadModel -31
+equ trap_S_RegisterSound -32
+equ trap_S_StartLocalSound -33
+equ trap_Key_KeynumToStringBuf -34
+equ trap_Key_GetBindingBuf -35
+equ trap_Key_SetBinding -36
+equ trap_Key_IsDown -37
+equ trap_Key_GetOverstrikeMode -38
+equ trap_Key_SetOverstrikeMode -39
+equ trap_Key_ClearStates -40
+equ trap_Key_GetCatcher -41
+equ trap_Key_SetCatcher -42
+equ trap_GetClipboardData -43
+equ trap_GetGlconfig -44
+equ trap_GetClientState -45
+equ trap_GetConfigString -46
+equ trap_LAN_GetPingQueueCount -47
+equ trap_LAN_ClearPing -48
+equ trap_LAN_GetPing -49
+equ trap_LAN_GetPingInfo -50
+equ trap_Cvar_Register -51
+equ trap_Cvar_Update -52
+equ trap_MemoryRemaining -53
+equ trap_GetCDKey -54
+equ trap_SetCDKey -55
+equ trap_R_RegisterFont -56
+equ trap_R_ModelBounds -57
+equ trap_PC_AddGlobalDefine -58
+equ trap_PC_LoadSource -59
+equ trap_PC_FreeSource -60
+equ trap_PC_ReadToken -61
+equ trap_PC_SourceFileAndLine -62
+equ trap_S_StopBackgroundTrack -63
+equ trap_S_StartBackgroundTrack -64
+equ trap_RealTime -65
+equ trap_LAN_GetServerCount -66
+equ trap_LAN_GetServerAddressString -67
+equ trap_LAN_GetServerInfo -68
+equ trap_LAN_MarkServerVisible -69
+equ trap_LAN_UpdateVisiblePings -70
+equ trap_LAN_ResetPings -71
+equ trap_LAN_LoadCachedServers -72
+equ trap_LAN_SaveCachedServers -73
+equ trap_LAN_AddServer -74
+equ trap_LAN_RemoveServer -75
+equ trap_CIN_PlayCinematic -76
+equ trap_CIN_StopCinematic -77
+equ trap_CIN_RunCinematic -78
+equ trap_CIN_DrawCinematic -79
+equ trap_CIN_SetExtents -80
+equ trap_R_RemapShader -81
+equ trap_VerifyCDKey -82
+equ trap_LAN_ServerStatus -83
+equ trap_LAN_GetServerPing -84
+equ trap_LAN_ServerIsVisible -85
+equ trap_LAN_CompareServers -86
+equ trap_FS_Seek -87
+equ trap_SetPbClStatus -88
+
+equ memset -101
+equ memcpy -102
+equ strncpy -103
+equ sin -104
+equ cos -105
+equ atan2 -106
+equ sqrt -107
+equ floor -108
+equ ceil -109
+
diff --git a/code/ui/ui_syscalls.c b/code/ui/ui_syscalls.c
new file mode 100755
index 0000000..1064a85
--- /dev/null
+++ b/code/ui/ui_syscalls.c
@@ -0,0 +1,401 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+#include "ui_local.h"
+
+// this file is only included when building a dll
+// syscalls.asm is included instead when building a qvm
+#ifdef Q3_VM
+#error "Do not use in VM build"
+#endif
+
+static int (QDECL *syscall)( int arg, ... ) = (int (QDECL *)( int, ...))-1;
+
+void dllEntry( int (QDECL *syscallptr)( int arg,... ) ) {
+ syscall = syscallptr;
+}
+
+int PASSFLOAT( float x ) {
+ float floatTemp;
+ floatTemp = x;
+ return *(int *)&floatTemp;
+}
+
+void trap_Print( const char *string ) {
+ syscall( UI_PRINT, string );
+}
+
+void trap_Error( const char *string ) {
+ syscall( UI_ERROR, string );
+}
+
+int trap_Milliseconds( void ) {
+ return syscall( UI_MILLISECONDS );
+}
+
+void trap_Cvar_Register( vmCvar_t *cvar, const char *var_name, const char *value, int flags ) {
+ syscall( UI_CVAR_REGISTER, cvar, var_name, value, flags );
+}
+
+void trap_Cvar_Update( vmCvar_t *cvar ) {
+ syscall( UI_CVAR_UPDATE, cvar );
+}
+
+void trap_Cvar_Set( const char *var_name, const char *value ) {
+ syscall( UI_CVAR_SET, var_name, value );
+}
+
+float trap_Cvar_VariableValue( const char *var_name ) {
+ int temp;
+ temp = syscall( UI_CVAR_VARIABLEVALUE, var_name );
+ return (*(float*)&temp);
+}
+
+void trap_Cvar_VariableStringBuffer( const char *var_name, char *buffer, int bufsize ) {
+ syscall( UI_CVAR_VARIABLESTRINGBUFFER, var_name, buffer, bufsize );
+}
+
+void trap_Cvar_SetValue( const char *var_name, float value ) {
+ syscall( UI_CVAR_SETVALUE, var_name, PASSFLOAT( value ) );
+}
+
+void trap_Cvar_Reset( const char *name ) {
+ syscall( UI_CVAR_RESET, name );
+}
+
+void trap_Cvar_Create( const char *var_name, const char *var_value, int flags ) {
+ syscall( UI_CVAR_CREATE, var_name, var_value, flags );
+}
+
+void trap_Cvar_InfoStringBuffer( int bit, char *buffer, int bufsize ) {
+ syscall( UI_CVAR_INFOSTRINGBUFFER, bit, buffer, bufsize );
+}
+
+int trap_Argc( void ) {
+ return syscall( UI_ARGC );
+}
+
+void trap_Argv( int n, char *buffer, int bufferLength ) {
+ syscall( UI_ARGV, n, buffer, bufferLength );
+}
+
+void trap_Cmd_ExecuteText( int exec_when, const char *text ) {
+ syscall( UI_CMD_EXECUTETEXT, exec_when, text );
+}
+
+int trap_FS_FOpenFile( const char *qpath, fileHandle_t *f, fsMode_t mode ) {
+ return syscall( UI_FS_FOPENFILE, qpath, f, mode );
+}
+
+void trap_FS_Read( void *buffer, int len, fileHandle_t f ) {
+ syscall( UI_FS_READ, buffer, len, f );
+}
+
+void trap_FS_Write( const void *buffer, int len, fileHandle_t f ) {
+ syscall( UI_FS_WRITE, buffer, len, f );
+}
+
+void trap_FS_FCloseFile( fileHandle_t f ) {
+ syscall( UI_FS_FCLOSEFILE, f );
+}
+
+int trap_FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize ) {
+ return syscall( UI_FS_GETFILELIST, path, extension, listbuf, bufsize );
+}
+
+int trap_FS_Seek( fileHandle_t f, long offset, int origin ) {
+ return syscall( UI_FS_SEEK, f, offset, origin );
+}
+
+qhandle_t trap_R_RegisterModel( const char *name ) {
+ return syscall( UI_R_REGISTERMODEL, name );
+}
+
+qhandle_t trap_R_RegisterSkin( const char *name ) {
+ return syscall( UI_R_REGISTERSKIN, name );
+}
+
+void trap_R_RegisterFont(const char *fontName, int pointSize, fontInfo_t *font) {
+ syscall( UI_R_REGISTERFONT, fontName, pointSize, font );
+}
+
+qhandle_t trap_R_RegisterShaderNoMip( const char *name ) {
+ return syscall( UI_R_REGISTERSHADERNOMIP, name );
+}
+
+void trap_R_ClearScene( void ) {
+ syscall( UI_R_CLEARSCENE );
+}
+
+void trap_R_AddRefEntityToScene( const refEntity_t *re ) {
+ syscall( UI_R_ADDREFENTITYTOSCENE, re );
+}
+
+void trap_R_AddPolyToScene( qhandle_t hShader , int numVerts, const polyVert_t *verts ) {
+ syscall( UI_R_ADDPOLYTOSCENE, hShader, numVerts, verts );
+}
+
+void trap_R_AddLightToScene( const vec3_t org, float intensity, float r, float g, float b ) {
+ syscall( UI_R_ADDLIGHTTOSCENE, org, PASSFLOAT(intensity), PASSFLOAT(r), PASSFLOAT(g), PASSFLOAT(b) );
+}
+
+void trap_R_RenderScene( const refdef_t *fd ) {
+ syscall( UI_R_RENDERSCENE, fd );
+}
+
+void trap_R_SetColor( const float *rgba ) {
+ syscall( UI_R_SETCOLOR, rgba );
+}
+
+void trap_R_DrawStretchPic( float x, float y, float w, float h, float s1, float t1, float s2, float t2, qhandle_t hShader ) {
+ syscall( UI_R_DRAWSTRETCHPIC, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), hShader );
+}
+
+void trap_R_ModelBounds( clipHandle_t model, vec3_t mins, vec3_t maxs ) {
+ syscall( UI_R_MODELBOUNDS, model, mins, maxs );
+}
+
+void trap_UpdateScreen( void ) {
+ syscall( UI_UPDATESCREEN );
+}
+
+int trap_CM_LerpTag( orientation_t *tag, clipHandle_t mod, int startFrame, int endFrame, float frac, const char *tagName ) {
+ return syscall( UI_CM_LERPTAG, tag, mod, startFrame, endFrame, PASSFLOAT(frac), tagName );
+}
+
+void trap_S_StartLocalSound( sfxHandle_t sfx, int channelNum ) {
+ syscall( UI_S_STARTLOCALSOUND, sfx, channelNum );
+}
+
+sfxHandle_t trap_S_RegisterSound( const char *sample, qboolean compressed ) {
+ return syscall( UI_S_REGISTERSOUND, sample, compressed );
+}
+
+void trap_Key_KeynumToStringBuf( int keynum, char *buf, int buflen ) {
+ syscall( UI_KEY_KEYNUMTOSTRINGBUF, keynum, buf, buflen );
+}
+
+void trap_Key_GetBindingBuf( int keynum, char *buf, int buflen ) {
+ syscall( UI_KEY_GETBINDINGBUF, keynum, buf, buflen );
+}
+
+void trap_Key_SetBinding( int keynum, const char *binding ) {
+ syscall( UI_KEY_SETBINDING, keynum, binding );
+}
+
+qboolean trap_Key_IsDown( int keynum ) {
+ return syscall( UI_KEY_ISDOWN, keynum );
+}
+
+qboolean trap_Key_GetOverstrikeMode( void ) {
+ return syscall( UI_KEY_GETOVERSTRIKEMODE );
+}
+
+void trap_Key_SetOverstrikeMode( qboolean state ) {
+ syscall( UI_KEY_SETOVERSTRIKEMODE, state );
+}
+
+void trap_Key_ClearStates( void ) {
+ syscall( UI_KEY_CLEARSTATES );
+}
+
+int trap_Key_GetCatcher( void ) {
+ return syscall( UI_KEY_GETCATCHER );
+}
+
+void trap_Key_SetCatcher( int catcher ) {
+ syscall( UI_KEY_SETCATCHER, catcher );
+}
+
+void trap_GetClipboardData( char *buf, int bufsize ) {
+ syscall( UI_GETCLIPBOARDDATA, buf, bufsize );
+}
+
+void trap_GetClientState( uiClientState_t *state ) {
+ syscall( UI_GETCLIENTSTATE, state );
+}
+
+void trap_GetGlconfig( glconfig_t *glconfig ) {
+ syscall( UI_GETGLCONFIG, glconfig );
+}
+
+int trap_GetConfigString( int index, char* buff, int buffsize ) {
+ return syscall( UI_GETCONFIGSTRING, index, buff, buffsize );
+}
+
+int trap_LAN_GetServerCount( int source ) {
+ return syscall( UI_LAN_GETSERVERCOUNT, source );
+}
+
+void trap_LAN_GetServerAddressString( int source, int n, char *buf, int buflen ) {
+ syscall( UI_LAN_GETSERVERADDRESSSTRING, source, n, buf, buflen );
+}
+
+void trap_LAN_GetServerInfo( int source, int n, char *buf, int buflen ) {
+ syscall( UI_LAN_GETSERVERINFO, source, n, buf, buflen );
+}
+
+int trap_LAN_GetServerPing( int source, int n ) {
+ return syscall( UI_LAN_GETSERVERPING, source, n );
+}
+
+int trap_LAN_GetPingQueueCount( void ) {
+ return syscall( UI_LAN_GETPINGQUEUECOUNT );
+}
+
+int trap_LAN_ServerStatus( const char *serverAddress, char *serverStatus, int maxLen ) {
+ return syscall( UI_LAN_SERVERSTATUS, serverAddress, serverStatus, maxLen );
+}
+
+void trap_LAN_SaveCachedServers() {
+ syscall( UI_LAN_SAVECACHEDSERVERS );
+}
+
+void trap_LAN_LoadCachedServers() {
+ syscall( UI_LAN_LOADCACHEDSERVERS );
+}
+
+void trap_LAN_ResetPings(int n) {
+ syscall( UI_LAN_RESETPINGS, n );
+}
+
+void trap_LAN_ClearPing( int n ) {
+ syscall( UI_LAN_CLEARPING, n );
+}
+
+void trap_LAN_GetPing( int n, char *buf, int buflen, int *pingtime ) {
+ syscall( UI_LAN_GETPING, n, buf, buflen, pingtime );
+}
+
+void trap_LAN_GetPingInfo( int n, char *buf, int buflen ) {
+ syscall( UI_LAN_GETPINGINFO, n, buf, buflen );
+}
+
+void trap_LAN_MarkServerVisible( int source, int n, qboolean visible ) {
+ syscall( UI_LAN_MARKSERVERVISIBLE, source, n, visible );
+}
+
+int trap_LAN_ServerIsVisible( int source, int n) {
+ return syscall( UI_LAN_SERVERISVISIBLE, source, n );
+}
+
+qboolean trap_LAN_UpdateVisiblePings( int source ) {
+ return syscall( UI_LAN_UPDATEVISIBLEPINGS, source );
+}
+
+int trap_LAN_AddServer(int source, const char *name, const char *addr) {
+ return syscall( UI_LAN_ADDSERVER, source, name, addr );
+}
+
+void trap_LAN_RemoveServer(int source, const char *addr) {
+ syscall( UI_LAN_REMOVESERVER, source, addr );
+}
+
+int trap_LAN_CompareServers( int source, int sortKey, int sortDir, int s1, int s2 ) {
+ return syscall( UI_LAN_COMPARESERVERS, source, sortKey, sortDir, s1, s2 );
+}
+
+int trap_MemoryRemaining( void ) {
+ return syscall( UI_MEMORY_REMAINING );
+}
+
+void trap_GetCDKey( char *buf, int buflen ) {
+ syscall( UI_GET_CDKEY, buf, buflen );
+}
+
+void trap_SetCDKey( char *buf ) {
+ syscall( UI_SET_CDKEY, buf );
+}
+
+int trap_PC_AddGlobalDefine( char *define ) {
+ return syscall( UI_PC_ADD_GLOBAL_DEFINE, define );
+}
+
+int trap_PC_LoadSource( const char *filename ) {
+ return syscall( UI_PC_LOAD_SOURCE, filename );
+}
+
+int trap_PC_FreeSource( int handle ) {
+ return syscall( UI_PC_FREE_SOURCE, handle );
+}
+
+int trap_PC_ReadToken( int handle, pc_token_t *pc_token ) {
+ return syscall( UI_PC_READ_TOKEN, handle, pc_token );
+}
+
+int trap_PC_SourceFileAndLine( int handle, char *filename, int *line ) {
+ return syscall( UI_PC_SOURCE_FILE_AND_LINE, handle, filename, line );
+}
+
+void trap_S_StopBackgroundTrack( void ) {
+ syscall( UI_S_STOPBACKGROUNDTRACK );
+}
+
+void trap_S_StartBackgroundTrack( const char *intro, const char *loop) {
+ syscall( UI_S_STARTBACKGROUNDTRACK, intro, loop );
+}
+
+int trap_RealTime(qtime_t *qtime) {
+ return syscall( UI_REAL_TIME, qtime );
+}
+
+// this returns a handle. arg0 is the name in the format "idlogo.roq", set arg1 to NULL, alteredstates to qfalse (do not alter gamestate)
+int trap_CIN_PlayCinematic( const char *arg0, int xpos, int ypos, int width, int height, int bits) {
+ return syscall(UI_CIN_PLAYCINEMATIC, arg0, xpos, ypos, width, height, bits);
+}
+
+// stops playing the cinematic and ends it. should always return FMV_EOF
+// cinematics must be stopped in reverse order of when they are started
+e_status trap_CIN_StopCinematic(int handle) {
+ return syscall(UI_CIN_STOPCINEMATIC, handle);
+}
+
+
+// will run a frame of the cinematic but will not draw it. Will return FMV_EOF if the end of the cinematic has been reached.
+e_status trap_CIN_RunCinematic (int handle) {
+ return syscall(UI_CIN_RUNCINEMATIC, handle);
+}
+
+
+// draws the current frame
+void trap_CIN_DrawCinematic (int handle) {
+ syscall(UI_CIN_DRAWCINEMATIC, handle);
+}
+
+
+// allows you to resize the animation dynamically
+void trap_CIN_SetExtents (int handle, int x, int y, int w, int h) {
+ syscall(UI_CIN_SETEXTENTS, handle, x, y, w, h);
+}
+
+
+void trap_R_RemapShader( const char *oldShader, const char *newShader, const char *timeOffset ) {
+ syscall( UI_R_REMAP_SHADER, oldShader, newShader, timeOffset );
+}
+
+qboolean trap_VerifyCDKey( const char *key, const char *chksum) {
+ return syscall( UI_VERIFY_CDKEY, key, chksum);
+}
+
+void trap_SetPbClStatus( int status ) {
+ syscall( UI_SET_PBCLSTATUS, status );
+}
diff --git a/code/ui/ui_util.c b/code/ui/ui_util.c
new file mode 100755
index 0000000..aa33507
--- /dev/null
+++ b/code/ui/ui_util.c
@@ -0,0 +1,29 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// ui_util.c
+//
+// origin: rad
+// new ui support stuff
+//
+// memory, string alloc
+
+
diff --git a/code/unix/ChangeLog b/code/unix/ChangeLog
new file mode 100755
index 0000000..2642f2d
--- /dev/null
+++ b/code/unix/ChangeLog
@@ -0,0 +1,2981 @@
+TODO: the Mac port seems stable, but outputs a bunch of warnings..
+
+2004-05-22
+- updated the xcode project from Apple's version
+ now with the latest vm_ppc code
+
+2004-05-21 Timothee Besset <ttimo@idsoftware.com>
+- fixed the Linux build to compile again on sid (glext.h and gcc3 warnings)
+- 2 weeks ago, hacked up the source to compile on panther / xcode 1.1
+ several cleanups were needed, and VM support seems broke (hangs or crashes)
+- got altivec optimisations from Apple (Kenneth Dyke)
+ merged back in
+- looks like with the new code merge the VM support is back in and working
+
+2003-09-15 Timothee Besset <ttimo@idsoftware.com>
+- import Q3 java master code, cleanups on monster
+
+2003-08-31 Timothee Besset <ttimo@idsoftware.com>
++ loki_setup hell
+ https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=626
+ http://zerowing.idsoftware.com/linux/q3a/index.html#glibc
+ text mode installer in loki_setup image built on Mandrake 7.2 crashes on some glibc 2.3 systems such as RH9 etc.
+ need to move to a different version of the installer, and update old installers to keep them still 'installing'
+ moving to build the setup binaries on Debian Woody systems (glibc 2.2, text mode installer will no longer work on 2.1 systems)
+ hacked together a new setup, using setup tree from RTCW. would need a complete revamp if a new full setup with new binaries is needed
+
+2003-07-17 Timothee Besset <ttimo@idsoftware.com>
+ + new cvsreport, testing per-module config
+
+2003-01-19 Timothee Besset <ttimo@idsoftware.com>
+ + building on both gcc 2.x and 3.x
+ added conf modules to check gcc version
+ ccache support
+
+2003-01-13 Timothee Besset <ttimo@idsoftware.com>
+ + tweaking around for gcc 3.x build
+ edit Conscript to change the compiler
+
+2002-12-16 Timothee Besset <ttimo@idsoftware.com>
+ + added pbEmit class to auth code, emit CD keys to local PB master
+
+2002-11-14 Timothee Besset <ttimo@idsoftware.com>
+ + up to latest makeself.sh
+ + add both quake3.x86 and quake3-smp.x86 to setup
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=573
+ console setup crash / glibc 2.3 (Debian Sid)
+ investigated, put together a workaround
+
+2002-11-5 Timothee Besset <ttimo@idsoftware.com>
+ + Linux building both smp and non-smp again. Will have to put both in setup
+ + added in_subframe to toggle X subframe event handling
+ + reworked the timing code to be more reliable
+ + cleaned up dgamouse/in_mouse code, removed unnecessary dgamouse var
+ + made the mouse grabbing an in_nograb cvar, no longer a compile time option
+ in_nograb 1 force in_dgamouse 0 and r_fullscreen 0 (any of those two will b0rk)
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=565
+ mouse issues on Suze 8.1 - related to subframe event timing
+ added code chunk to detect broken X timing and disable subframe
+ + tweaked the subframe/X bug workaround to be less paranoid
+
+2002-10-28 Timothee Besset <ttimo@idsoftware.com>
+ + no longer blocking demo recording if g_synchronous clients != 0
+ only sending out a warning (everyone does g_sync 1 ; record ; g_sync 0)
+
+2002-10-21 Timothee Besset <ttimo@idsoftware.com>
+ + building final mod sdk setups (added lcc bins, added link to q3asm-turbo in readme)
+
+2002-10-8 Timothee Besset <ttimo@idsoftware.com>
+ + quickfix cl_maxpackets > 125 brings back to 100
+
+1.32 release ---
+
+2002-10-7 Timothee Besset <ttimo@idsoftware.com>
+ + made the 'demo' command case-insensitive on extension match (it was confused by demo FOUR.DM_68)
+ + mouse wheel scrolling with in_mouse 1 + window mode was not working, fixed (DI didn't catch)
+ + removing on-the-fly pk3 build from Linux setup, using the finalized ones now
+ added 'pk3' option to cons for toggle of pk3 building
+
+2002-10-5 Timothee Besset <ttimo@idsoftware.com>
+ + updated win32 mod sdk (in win32/mod-sdk-setup)
+ added q3asm and lcc source
+ updated the .bat to build VMs
+
+2002-10-3 Timothee Besset <ttimo@idsoftware.com>
+ + linux mod sdk, wrote the bulk of the scripts
+
+2002-9-30 Timothee Besset <ttimo@idsoftware.com>
+ + ATVI Quake 3 1.32 Patch #9
+ rolling back to the way it was before, leaving 1v1 force vote exploit, the fix was worse than the bug
+ from comment on bug #9 in tracker:
+
+ actually the fix is worse than the original bug
+
+ after the fix, voting when you are alone on the server was no longer working
+ it was kinda intended in the fix, that you would have to be at least two to pass a vote .. but
+ it is an oversight.
+
+ calling a vote in a 1v1 game against a bot fails immediately
+ (calling a vote in any situation where there's only 1 live player fails)
+
+ Say a server's running some lame custom map that you have but a friend doesn't. You can't go
+ on the server and change it to the map you want to play, so he ends up having to auto-dl it at
+ 8K a second just so you can switch from it.
+
+ This particular 2 clients, vote / quit exploit would involve too many changes to fix properly.
+ I am reverting back to the old version, and leaving as WNF
+
+2002-9-29 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=50
+ added Wheel support to the DirectInput code IN_DIMouse (in_mouse 1)
+ tweaked the Wheel mouse reading for in_mouse -1 (old win32 input code)
+ handle correctly when zDelta is > 120
+ provide a in_logitechbug cvar to handle buggy Logitech MouseWare driver sending wheel events twice
+
+2002-9-26 Timothee Besset <ttimo@idsoftware.com>
+ + ATVI Quake 3 1.32 Patch #38
+ adding trap_SetPbClStatus, reliably checks for PB presence before enabling PB in UI
+
+2002-9-25 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=551
+ SVF_CLIENTMASK, fixed a typo
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=555
+ pushed cl_maxpackets upper limit to 125 (from 100) per CPMA Arqon's request
+
+2002-9-24 Timothee Besset <ttimo@idsoftware.com>
+ + ATVI Quake 3 1.32 Patch #33
+ PB reporting sv_paused cvar hacked, fixed SV_CheckPaused to use a Cvar_Set
+ + ATVI Quake 3 1.32 Patch #24
+ added [skipnotify] from RTCW, use to display in the console only, but not on client screen
+ (also fixes pb_msgprefix and pb_sv_msgprefix)
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=553
+ using correct error message if listen server starting as cl_punkbuster 0 sv_punkbuster 1
+ + ATVI Quake 3 1.32 Patch #35
+ text auto wrap in UI code was eating the last word if it was wrapping
+ fixed in Q3 and TA UI (this bug could have affected the server print message also)
+ + some updates to the win32 cons post-build process
+
+2002-9-21 Timothee Besset <ttimo@idsoftware.com>
+ + adding bspc cons build script
+
+2002-9-19 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=552
+ disconnect reason is transmitted in the disconnect command and processed into com_errorMessage
+ (similar to RTCW behaviour)
+ added UI for com_errorMessage cvar in baseq3/, if client is kicked/dropped/disconnected for whatever reason
+ (this is already functional in TA)
+ + ATVI Quake 3 1.32 Patch #9
+ failing vote if there's only one voting client (fixes exploit on 2-player server where one player votes then disconnects, forcing vote to pass)
+ + ATVI Quake 3 1.32 Patch #5
+ removed the userInfoChanged message (was a debugging leftover)
+ + ATVI Quake 3 1.32 Patch #18
+ rcon was not properly fixed yet, this only showed up for PB commands
+ changed the rcon parsing again to be more reliable
+
+2002-9-18 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=549
+ the demo command has a list of compatible protocols, it will loop through 66 67 68
+ you can do '/demo four' and it will try four.dm_66 four.dm_67 four.dm_68
+ or you can explicitely give a '/demo demoname.dm_??'
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=551
+ added SVF_CLIENTMASK (0x00000002), works only with <= 32 players
+ set bitmask of players to which send entity
+
+2002-9-17 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=550
+ rcon bug fix
+ + some scons updates for win32 (post build)
+ + 1.32rc2
+
+2002-9-06 Timothee Besset <ttimo@idsoftware.com>
+ + updated completely the setup system:
+ fixed cons stuff to build setup with cons -- release setup
+ working from new setup codebase with some custom patches:
+ https://bugzilla.icculus.org/show_bug.cgi?id=52
+ https://bugzilla.icculus.org/show_bug.cgi?id=53
+ checked that BSD support was still in (brandelfing and symlinks) .. will have to get tester feedback
+ bumped version to 1.32rc1
+ TODO: update the windows .VCT (standalone setup and auto-update)
+
+2002-9-04 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=543
+ backport from RTCW 1.4 code
+ rcon commands where sent after being tokenized and rebuilt
+ that was breaking any quoting, for instance 'rcon g_motd "hooka pooka"'
+ added Cmd_Cmd() to retrieve the un-tokenized command and transmit as is on both ends
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=542
+ b0rked text wrapping in connect screen
+ was a missing sizeScale in q3_ui/, and a bad param in ui/
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540
+ backport fix to pk3 reordering, happens when clearing the references, bad order from connection may break stuff
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=527
+ TA ui/, quickfix to netSource (mod stuff, doesn't affect TA)
+ + cleaned up broken old DO_WIN32 stuff in cons scripts
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=526
+ typo in models2.shader
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=443
+ Linux client: sub-frame timing of key/mouse events
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=453
+ added mousewheel support: wheel to scroll, ctrl+wheel to scroll faster, shift+wheel to scroll history
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=545
+ bumped server count to 4096
+ + keep around: __asm__ __volatile__ ("int $0x03");
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=516
+ moved screenshots to backend with a new RC_SCREENSHOT render command
+ fixes the r_smp 1 garbled screenshots
+
+2002-8-29 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=539
+ new VM code from Raven's Sof2
+ + cons / qvmtools build system fixes
+ + had to get a new qe3.ico again (resource compiler error)
+ http://vasin.hypermart.net/eei.htm
+ + updated, basic testing on win32, merging back in trunk
+ + merged bug-539 branch back into trunk, officialize the new VM code
+
+2002-8-26 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=472
+ linux client: handle ctrl+space situations (could leave space locked on + space not working with ctrl on)
+ + update the build system, build q3lcc and q3asm etc. on demand
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=62
+ fixed invisible players/entities
+
+2002-8-23 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=536
+ fixing donedl being ignored after autodl if map_restart'ed (propagate from RTCW)
+ ignoring multiple map_restart (propagated from RTCW)
+ + reworked the server 'client text ignored' message to only trigger when there's actually a message that doesn't get to the game VM
+
+2002-8-18 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=528
+ ydnar: reorg bits in the drawsurf sort index, push MAX_SHADERS to 2^12
+ + commented out some debug stuff in java auth server
+ + added FAQ item with Linux & BSD patch to handle broadcast on multiple interfaces
+
+2002-8-15 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=534
+ fixing rcon being broken on NT/XP with > 23 days uptime (or so)
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=525
+ changed the rcon buffer size to avoid overflows and dropping part of the message
+
+2002-8-14 Timothee Besset <ttimo@idsoftware.com>
+ + hacked in some experimental win32 stuff to the cons files
+ (win32 recognition and pk3 installs .. very very experimental but I needed it for win32 dev)
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=521
+ ui/ and q3_ui/ : added text auto wrapping in the connection screen drawing (server message)
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=531
+ removed the MPlayer stuff from the server browsers
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=505
+ enabled back the ignore if protocol is != (fixes Wolf servers showing in browser)
+
+2002-8-10 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=500
+ propagated IP banning fix from RTCW
+
+2002-8-08 Timothee Besset <ttimo@idsoftware.com>
+ + propagate additional sv_lanForceRate fix from RTCW
+
+2002-8-07 Timothee Besset <ttimo@idsoftware.com>
+ + added trap_FS_Seek
+
+2002-8-05 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=50
+ fixed the DI mouse init procedure
+
+2002-8-05 Timothee Besset <ttimo@idsoftware.com>
+ + removed sv_allowanonymous, was dummy and polluting the serverinfo
+ (sv_allowanonymous was designed to flag wether server was public or not, but that's replaced by g_needpass)
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=514
+ sv_strictAuth (default 1): server variable to control wether strict CDKEY auth should be performed
+ this is required if you want reliable cl_guid on the server
+ extended the getIpAuthorize (server->auth message) syntax
+ sending the fs_game at all times (default 'baseq3'), dummy sv_allowAnonymous 0, strict auth flag
+ NOTE: 1.31 server on baseq3 sends a getIpAuthorize packet like:
+ processing packet: getIpAuthorize -1230824753 217.128.77.195 0
+ the auth server will mistakenly read fs_game as '0'
+ + TAGGED the master / auth source as pre-1_32
+ will need to go back to this to comment out all my debugging crap
+
+2002-8-04 Timothee Besset <ttimo@idsoftware.com>
+ + cleaned master server stuff, client was prompting master.quake3arena.com,
+ server was sending heartbeats to master3.idsoftware.com
+ both point to 192.246.40.56, unified to master.quake3arena.com
+ the MPlayer master, master.quake3world.com doesn't exist anymore, switched it to master.quake3arena.com
+
+2002-8-02 Timothee Besset <ttimo@idsoftware.com>
+ + added auth server source, reorganized
+ + auth server name / master key optionally set on command line for master and auth servers
+ + auth and master config in build system
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=524
+ changed default GL driver from libGL.so to libGL.so.1
+ see LSB 1.2 spec: http://www.linuxbase.org/spec/refspecs/LSB_1.2.0/gLSB/libgl.html
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=480
+ applying the 'no cp command' experimental fix for beta phase
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=462
+ backported from RTCW, fix to packet fragmenting emission
+ FIXME: there is some verbose code that we have to take out in the final version (grep for #462)
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=475
+ backported from RTCW, don't get dropped if the server changes map while connecting (ignore outdated cp)
+ + PROTOCOL BUMPED TO 68
+
+2002-8-01 Timothee Besset <ttimo@idsoftware.com>
+ + Linux: dedicated build was not setting up signal handler like the full client does
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=522
+ SplashDamage bugfix, now clearing client gentity before GAME_INIT call (instead of after)
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=498
+ fixed NET_AdrToString to print the port as unsigned int (for ports > 1^^15, was showing negative)
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=501
+ maintain IP in userinfo sent to game
+ + checking in master server source
+
+2002-7-31 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=513
+ https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=506
+ porting fix from RTCW codebase. client re-orders it's pk3s to scan in the same order than the server
+ this eliminates several 'Invalid .PK3 file referenced' situations (caused by client not referencing the same thing as server)
+ + fixed border remnants in ta ui
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=517
+ ERR_DROP if PB client off / server on conflict when starting local server
+ + quickfix to q3 ui / punkbuster detect in server browser
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=458
+ code fix, no more taunt spam
+ + cons install of PB .so files
+ + correct MOD_KAMIKAZE and MOD_JUICED in TA games.log
+
+2002-7-29 Timothee Besset <ttimo@idsoftware.com>
+ + q3 ui: completed confirmation prompts and messages (added UI_ConfirmMenu_Style & UI_Message)
+ + ta ui: backported 'conditionalopen' from RTCW (conditionalopen <cvar> <menu1> <menu2>)
+ + ta ui: confirmation prompt for punkbuster enable/disable etc.
+ + added the win32 DLLs to pb/win32/
+
+2002-7-28 Timothee Besset <ttimo@idsoftware.com>
+ + ta ui: sv_punkbuster in StartServer menu
+ + ta ui: added cl_punkbuster in server browser
+ + view filters are in a modal dialog
+ + new files: filter.menu menus.txt (pak3.pk3 updated)
+ + fix broken link in Linux FAQ
+
+2002-7-27 Timothee Besset <ttimo@idsoftware.com>
+ + ta ui: PB display in the browser, in it's additional tab, with sorting
+
+2002-7-26 Timothee Besset <ttimo@idsoftware.com>
+ + PB UI: for baseq3/ AND missionpack/
+ q3_ui: Punkbuster: Enable/Disable in server broswer (cl_punkbuster)
+ q3_ui: PB logo, PB Yes/No in browser (TODO: validate this to be working)
+ q3_ui: added sv_punkbuster toggle in start server menu
+ + automated building of the new PK3s, unix/Conscript-pk3
+
+2002-7-25 Timothee Besset <ttimo@idsoftware.com>
+ + added PB build scripts on Linux, fixed the Linux build
+
+2002-7-12 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=511
+ fixing re.SetColor crash for widescreen displays (q3dm11)
+ was calling to the renderer while not registered
+
+2002-6-19 Timothee Besset <ttimo@idsoftware.com>
+ + r_roundImagesDown 0 + map q3dm16 -> tr_image.c ResampleTexture crash
+ buffer overflow because of resample to 2048x..
+ xian_q3dm12_leftwall4fin.jpg 1152x384
+ bumped one buffer byte p1[1024] -> byte p1[2048], added a safe check
+
+2002-6-14 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=493
+ propagate a renderer fix from RTCW. fixes a one-frame visual glitch when mod code
+ registers a shader after drawsurfaces are generated but before the frame is rendered
+
+2002-6-12 Timothee Besset <ttimo@idsoftware.com>
+ + added cons and pcons to unix/, updated the build script
+
+2002-5-24 Timothee Besset <ttimo@idsoftware.com>
+ towards a new Q3 release?
+ some bug fixes require protocol change, or mod code/mod interface change to be fixed properly
+ this is a biz decision, dunno yet if we are going to want a new protocol (probably not)
+ -> have to create a branch for the 1.31b, i.e. backwards compatible with 1.31 'Stable-1_31'
+ and put the 1.32 specific / protocol changes on trunk
+ no telling what will go in SOS in the end .. probably 1.32
+
+2002-5-5 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=491
+ adding a sv_lanForceRate (defaults to 1) to turn on/off server forcing rate of LAN clients
+ (only affects LAN dedicated clients - dedicated 1, default behaviour forces LAN clients to 99999 rate)
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=470
+ fixing potential overflows with cl_cdkey (propagated from RTCW)
+ + cons-based build system (imported from Wolf, was partly written for mod tools release already)
+ building with SMP on by default
+ + better #ifdef SMP handling ('disabled at compile time' message)
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=494
+ Q_vsnprintf for vsprintf calls in the core
+ not putting this in game code as we'd need a vsnprintf implementation in bg_lib.c
+
+2002-4-5 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=462
+ taking out the fix which was found broken and incomplete
+
+2002-8-4 Timothee Besset <ttimo@idsoftware.com>
+ + adding NO_MOUSEGRAB define (select in the Makefile)
+
+2002-2-4 Timothee Besset <ttimo@idsoftware.com>
+ + applying Gareth's SMP patch
+ + count number of CPUs (Sys_ProcessorCount in unix_shared.c), default r_smp appropriately
+ + bumping version to 1.32
+ + if XInitThreads fails, set r_smp to zero
+
+2002-28-2 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=462
+ send potential remaining fragmented packets before sending a gamestate
+
+2002-26-2 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=455
+ removed old libMesaVoodooGL.so loading code
+ Voodoo cards should use XF4/DRI, that load code was outdated and confusing people with broken OpenGL
+
+2002-16-1 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=441
+ adding brandelf calls to the setup building process so that our binaries run on BSD
+
+2002-1-1 Timothee Besset <ttimo@idsoftware.com>
+ + updated FAQ with BSD info (bug #441)
+ + FAQ update on CLIENT_UNKNOWN_TO_AUTH
+ + FAQ update for proper strace usage
+
+2001-12-12 Timothee Besset <ttimo@idsoftware.com>
+ + Q3 1.31 point release
+ updating build_setup.sh to new pk3 files
+ (baseq3/pak7.pk3 missionpack/pak2.pk3)
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=395
+ adding quake3.xpm icon, and modified the setup accordingly to put symlinks
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=390
+ ignoring SIGTTIN SIGTTOU
+
+2001-06-12 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=402
+ bug with full scene
+
+2001-04-12 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=398
+ cg_bobup cheat protect
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=399
+ fixed Setup > System > Driver info crash
+ + checked in code/spank.sh script, perform checksuming
+
+2001-18-09 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=371
+ propagating sound code fixes from Wolf to Q3
+
+2001-11-08 Timothee Besset <ttimo@idsoftware.com>
+ + setup script was still broken, damn shell expansion
+ the exit code for Q3 was always zero instead of $?
+ propagating the fix to Wolf
+
+2001-11-04 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=382
+ modified challenge code for motd to be truly random
+
+2001-10-31 Timothee Besset <ttimo@idsoftware.com>
+ Moved updated q3asm and lcc source at the toplevel, MissionPack/q3asm
+ and MissionPack/lcc
+
+2001-10-29 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=381
+ build system is now functional
+
+2001-10-21 Timothee Besset <ttimo@idsoftware.com>
+ + updated Sys_LoadDll code on linux to search in the following order:
+ #1 current directory
+ #2 fs_homepath
+ #3 fs_basepath
+ this was needed to make mod developement easier
+
+2001-10-09 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=51
+ the code to buffer the redirection was in there but disabled? (Com_Printf)
+ enabled it back
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=52
+ connection issues / userinfo
+ client side fix, instead of sending 'connect <userinfo>' packet
+ we now send 'connect "<userinfo>"'
+
+2001-10-08 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=371
+ added a PROT_READ to the mmap call
+ this was needed to go around a bug in glibc i586 i686, memset doing read access
+ since the audio_fd is opened O_RDWD this is harmless to Q3
+
+2001-10-07 Timothee Besset <ttimo@idsoftware.com>
+ + updating from SOS
+ S_WriteLinearBlastStereo16 C/asm is back in snd_mix.c (Graeme)
+ r_showtris r_shownormal cheat protections
+ + Sys_LoadDll changes:
+ removing -debug search when loading native dlls
+ changing the fatal aborts when not finding native from release only to debug only (was a misfeature)
+ used to search in cd_path which is bogus, now searching in pwd if basepath fails
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=275
+ fixed r_fullbright not being cheat protected / was a CVAR_LATCHED|CVAR_CHEAT issue
+
+2001-09-06 Timothee Besset <ttimo@idsoftware.com>
+ + updated from SOS, some changes to qcommon/unzip.c (statics)
+
+2001-08-27 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=3
+ Added some code in CL_InitDownloads to use FS_ComparePaks and print out information about server-referenced paks that are missing on the client. It is a first step, allows to get precise information about what can cause a connection to fail (typically when the user is sent back to the main screen).
+
+2001-08-22 Timothee Besset <ttimo@idsoftware.com>
+ + https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=86
+ fixed sound bug (with Graeme hints)
+
+2001-08-20 Timothee Besset <ttimo@idsoftware.com>
+ + made sure Sys_Printf doesn't get into an endless loop if logfile is on
+ fixed qconsole.log issues, +set logfile 1 +set fs_debug 1 was crashing (any OS)
+ fixed logfile 1 / ttycon 1 issue, didn't exit properly (same endless looping)
+ also fixes an issue reported by q3f team
+ + changed rcon commands from Com_DPrintf to Com_Printf so that they show up in the console
+ (with IP information)
+
+2001-08-19 Timothee Besset <ttimo@idsoftware.com>
+ + fixed https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=91
+ (autodownload toggle in q3 ui)
+ + fixed https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=76
+ g_password issue
+ + fixed https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=93
+ cheat protecting r_lodCurveError
+ + wontfix https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=92
+
+2001-08-18 Timothee Besset <ttimo@idsoftware.com>
+ + more fixes to the 7-button mouse code (linux only)
+ + updated faq about gamma slider
+ + added "servers don't show up in ingame browser" to faq
+ + added Alt+Enter toggle for fullscreen/windowed (linux)
+
+2001-08-16 Timothee Besset <ttimo@idsoftware.com>
+ reconfiguring CVS repository to give access to Gareth
+ + testin gareth's access
+
+2001-08-03 Timothee Besset <ttimo@idsoftware.com>
+ * https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=85
+ fixes in the setup code for older bash versions
+
+2001-08-02 Timothee Besset <ttimo@idsoftware.com>
+ * commented out assembly implementation of S_WriteLinearBlastStereo16, using modified C implementation from Zaphod
+ need to check performance: https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=88
+ * finished const declarations in CG_Trace calls, was needed in pmove_t declaration and some other functions
+ cgame/cg_local.h : CG_trace trap_CM_BoxTrace
+ game/bg_public.h : using const in pmove_t trace functions prototypes
+ (fixes gcc warnings: assignment from incompatible pointer type)
+
+2001-07-26 Timothee Besset <ttimo@idsoftware.com>
+ * https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=78
+ mapped K_MOUSE4 K_MOUSE5
+
+2001-07-23 Timothee Besset <ttimo@idsoftware.com>
+ * https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=5
+ more fixes, handling meta characters and various kinds of backspace
+
+2001-07-22 Timothee Besset <ttimo@idsoftware.com>
+ * https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=5
+ after testing feedback, fixed more stuff:
+ better backspace, works with putty and potentially more terminals
+ * https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=51
+ band aid fix to rcon status, incresed MAX_PUSHED_EVENTS from 256 to 1024
+ (adds 28kb of mem requirements)
+
+2001-07-21 Timothee Besset <ttimo@idsoftware.com>
+ * https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=2
+ using XF86 Gamma extension to set the gamma in game from the menus
+ (previous behaviour was to set /r_gamma and restart, renderer relying on s_gammatable)
+ restoring initial gamma on GLimp_ShutDown
+
+2001-07-19 Timothee Besset <ttimo@idsoftware.com>
+ * https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=5
+ first usable version of dedicated console
+ added history and completion functionality
+ ready for some testing
+ still some TODOs and FIXMEs:
+ keep the currently edited line when going back from history exploration
+ edit the current line with cursor, insert mode etc.
+
+2001-07-18 Timothee Besset <ttimo@idsoftware.com>
+ * starting TAB completion and history for the dedicated server (tty console)
+ removed Sys_ConsoleOutput (unused)
+ removing bogus nostdout variable
+ cleanup of a big chunk of code that Bernd commented out and scheduled for deletion
+ moved completion code from client/cl_keys.c stuff into qcommon/common.c, Field_CompleteCommand(field_t*)
+
+2001-07-13 Timothee Besset <ttimo@idsoftware.com>
+ * fixed https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=8
+ screenshots overwrites
+ * fixed https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=31
+ DOUBLE SIGNAL FAULT
+
+2001-07-11 Timothee Besset <ttimo@idsoftware.com>
+ * fix for french keybards / console toggle / bound to XK_twosuperior
+
+2001-07-10 Timothee Besset <ttimo@idsoftware.com>
+ * https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=19
+ cleanup of the keyboard code, adding com_developer message in case XLookupString would fail
+
+2001-07-10 Timothee Besset <ttimo@idsoftware.com>
+ * https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=33
+ using our custom handlers for X errors, should make things more robust
+ (X docs say some X errors are not fatal, but the default X handler exits the app anyway)
+
+2001-07-08 Timothee Besset <ttimo@idsoftware.com>
+ * https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=19
+ keyboard state issues, fixed the sticking with ctrl key (thks relnev)
+
+2001-07-07 Timothee Besset <ttimo@idsoftware.com>
+ * closing https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=13
+ the fixes to bug #9 solved this one too
+ * checking in to SOS
+
+2001-07-05 Timothee Besset <ttimo@idsoftware.com>
+ * work on https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=9
+ filesystem code changes:
+ updated the documentation in files.c to the current system
+ added correct fs_homepath fs_basepath fs_cdpath scanning to FS_SV_FOpenFileRead
+ (fixes description.txt not found, and probably a few other linux issues)
+
+2001-06-29 Timothee Besset <ttimo@idsoftware.com>
+ * fixed setup issues (graphical/console)
+ https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=6
+
+2001-06-26 Timothee Besset <ttimo@idsoftware.com>
+ * bug tracker is online at https://zerowing.idsoftware.com/bugzilla
+ authentication, use login: bugs password: b00gies
+ for now, using it as the linux bug tracker, possible use for more OSes and programs if anyone is interested.
+ * tweaked the graphical setup to send to bugs@idsoftware.com on errors instead of support@lokigames.com
+
+2001-06-19 Timothee Besset <ttimo@idsoftware.com>
+ * fixed generated launch script /usr/local/bin/quake3, exit $* should be exit
+
+2001-06-18 Timothee Besset <ttimo@idsoftware.com>
+ * rebuilt 1.29f setups, released as 1.29f-beta1 'Q3 1.29f linux-i386 Jun 19 2001'
+
+2001-06-10 Timothee Besset <ttimo@idsoftware.com>
+ * rebuilt against PR source, packaged 1.29b setups
+
+2001-05-25 Timothee Besset <ttimo@idsoftware.com>
+ * graphical setup, based on Loki's setup tool (GPL)
+
+2001-05-22 Timothee Besset <ttimo@idsoftware.com>
+ * changed fs_basepath to fs_homepath, according to Graeme's changes (probably missed this change?)
+ this fixes the q3key prompting at each game startup
+
+2001-05-20 Timothee Besset <ttimo@idsoftware.com>
+ * rebuilding 1.28b, various fixes on linux build:
+ - SetProgramPath was renamed to Sys_SetDefaultCDPath in unix_shared.c
+ updated unix_main.c accordingly
+ - some prototypes in qgl.h are guarded by #ifndef GL_VERSION_1_2 (ARB extentions)
+ those prototypes are needed by linux_glimp for importing functions and casting, added a #ifdef __linux__
+ (not a clean solution)
+ - game/q_shared.h
+ little endian / big endian functions have been added
+ gcc generates warnings about functions being unused .. inlined them
+ - cgame/cg_marks.c
+ // TTimo
+ // gcc warning: might be used uninitialized
+ float sInc = 0.0;
+ float s = 0.0;
+
+2001-05-15 Timothee Besset <ttimo@idsoftware.com>
+ * fixes to linux Makefile for bspc 2.1h
+ * various updates to 1.28b on linux
+
+2001-05-09 Timothee Besset <ttimo@idsoftware.com>
+
+ * R. Duffy reverted game/bg_pmove.c PM_CheckDuck, was a merging screup on my side
+ * updated setup to 1.27z, removed the .so from the setup distribution (they were in 1.27g because of issues)
+ FIXME: gotta get pk3's first
+
+2001-05-04 Timothee Besset <ttimo@idsoftware.com>
+
+ * fixes to gcc, building RC for 1.27s
+
+2001-05-01 Timothee Besset <ttimo@idsoftware.com>
+
+ * added qcommon/huffman.c to the Makefile
+ * gcc -Wall:
+ commenting out
+ CL_Netchan_Encode CL_Netchan_Decode (cl_net_chan.c)
+ Netchan_ScramblePacket Netchan_UnScramblePacket (net_chan.c)
+ SV_Netchan_Encode SV_Netchan_Decode (sv_net_chan.c)
+
+2001-04-26 Timothee Besset <ttimo@idsoftware.com>
+
+ * fixed dedicated server crash when entering the VM_COMPILED qagame on a mod (some statics lacked initialization)
+
+2001-04-25 Timothee Besset <ttimo@idsoftware.com>
+
+ * added $(Q3POBJ) to clean target (cleanup of platform-dependent objects)
+ * more make clean improvements
+
+2001-04-23 Timothee Besset <ttimo@idsoftware.com>
+
+ * cleanup the mod selection code, remove duplicates
+ * some issues with release builds, my main developement box doesn't build stable binaries with release settings
+ removing -fomit-frame-pointer seems to fix (there's probably a performance hit)
+ see OMIT-FRAME-POINTER.txt
+
+2001-04-13 Timothee Besset <ttimo@idsoftware.com>
+
+ * checked in a first set of merged files
+
+2001-04-06 Timothee Besset <ttimo@idsoftware.com>
+
+ * merged back the core linux parts to make 1.27g linux build from the Source Safe tree again
+
+2001-02-27 Bernd Kreimeier <bk@lokigames.com>
+
+ * CVS: tag with changes as of today
+ cvs tag id1-27j-loki01027
+
+ * code/qcommon/msg.c: numFields loop (SOS).
+ * code/qcommon/files.c: ue Q_stricmp (SOS uses stricmp, was strcmp).
+ * code/game/q_shared.h (Q3_VERSION): 1.27j. Also
+ MAX_STRING_TOKENS upped from 256 to 1024 (SOS).
+
+ * code/server/sv_snapshot.c (SV_AddEntitiesVisibleFromPoint): see below.
+ * code/game/g_public.h (SVF_NOTSINGLECLIENT): added (SOS).
+
+ * code/server/sv_ccmds.c: see below.
+ * code/game/g_main.c: g_gametype cvar now userinfo (SOS).
+
+ * code/game/g_active.c (SendPendingPredictableEvents): new (SOS).
+ * code/game/bg_misc.c: new SOS (sos010227)
+
+ * SOS: new update sos010227.
+
+2001-02-22 Bernd Kreimeier <bk@lokigames.com>
+
+ * CVS: now in sync with last SOS and cleanup up
+ cvs tag id1-27i-loki01022
+
+ * code/ui/ui_shared.c: below.
+ * code/ui/ui_main.c: leftover code!
+ * code/server/sv_world.c: below.
+ * code/server/sv_snapshot.c: below.
+ * code/server/sv_init.c: below.
+ * code/server/sv_game.c: below.
+ * code/server/sv_client.c: below.
+ * code/server/sv_ccmds.c: below.
+ * code/server/sv_bot.c: below.
+ * code/server/server.h: below.
+ * code/renderer/tr_surface.c: below.
+ * code/renderer/tr_shader.c: changed assert to early return.
+ * code/renderer/tr_shade_calc.c: below.
+ * code/renderer/tr_shade.c: below.
+ * code/renderer/tr_scene.c: below.
+ * code/renderer/tr_mesh.c: below.
+ * code/renderer/tr_local.h: below.
+ * code/qcommon/vm_x86.c: cleanup.
+ * code/qcommon/vm.c: below.
+ * code/qcommon/unzip.c: below.
+ * code/qcommon/qcommon.h: below.
+ * code/qcommon/files.c: below.
+ * code/qcommon/cvar.c: cleanup.
+
+2001-02-21 Bernd Kreimeier <bk@lokigames.com>
+
+ * code/qcommon/common.c: cleanup.
+ * code/qcommon/cm_trace.c: cleanup.
+ * code/qcommon/cm_patch.c: cleanup.
+ * code/qcommon/cm_public.h: cleanup.
+ * code/game/q_shared.h: cleanup.
+ * code/game/q_shared.c: cleanup.
+ * code/game/q_math.c: cleanup.
+ * code/game/g_syscalls.asm: changed (once more) floor,ceil etc.
+ * code/game/g_spawn.c: cleanup.
+ * code/game/g_session.c: cleanup.
+ * code/game/g_cmds.c: cleanup.
+ * code/game/g_client.c: cleanup.
+ * code/game/g_arenas.c: cleanup.
+ * code/game/bg_slidemove.c: cleanup.
+ * code/game/bg_pmove.c (PM_CheckDuck): old call to trace?
+ * code/game/bg_misc.c: cleanup.
+ * code/game/be_aas.h: dead code.
+ * code/game/ai_dmq3.c: cleanup. One clear/copy switched?
+ * code/game/ai_dmnet.c: more //*/. Why oh why not DEBUG....
+
+ * code/client/snd_mix.c: below.
+ * code/client/snd_dma.c: below.
+ * code/client/keys.h: cleanup.
+ TODO: #error in q3_ui/keycodes.h ?
+
+ * code/client/client.h: cleanup.
+ * code/client/cl_main.c: misplaced bracket. Cleanup.
+ * code/client/cl_keys.c: below.
+ * code/client/cl_cin.c: below.
+ * code/client/cl_cgame.c: cleanup.
+ TODO: define assert for Win32 or guard my assertions.
+
+ * code/cgame/cg_syscalls.c: below.
+ * code/cgame/cg_servercmds.c: below.
+ * code/cgame/cg_players.c: cleanup.
+
+ * code/cgame/cg_newdraw.c: remember to diff against cg_newDraw.c
+ in SOS (mixed case).
+ TODO: get id to use cg_newdraw.c, and to remove cg_newDraw.c/cpp.
+
+ * code/cgame/cg_main.c: below.
+ * code/cgame/cg_local.h: below.
+ * code/cgame/cg_event.c: below.
+ * code/cgame/cg_drawtools.c: below.
+ * code/cgame/cg_draw.c: cleanup.
+ * code/cgame/cg_consolecmds.c: dead code.
+ * code/bspc/qbsp.h: below.
+ * code/bspc/l_poly.c: below.
+ * code/bspc/l_math.c: cleanup.
+ * code/bspc/bspc.c: cleanup.
+ * code/bspc/be_aas_bspc.c: cleanup.
+ * code/bspc/aas_map.c: kept comments - merge loss at their end?
+ * code/bspc/aas_file.c: cleanup.
+
+ * code/botlib/be_interface.c: this file is plain impossible. There
+ are layers of code made dead with /* */ and the resurrected by
+ //* or // /* or variations of this. I reverted to exact mirror
+ image of SOS to be sure - short of removing it's too easy to mistake
+ live code for dead one.
+ Later: have to change 5 occurences to avoid gcc complaints about
+ nested comment tokens.
+ TODO: somebody please get rid of the cruft in here.
+
+ * code/botlib/be_ai_move.c: redundant typedef.
+ * code/botlib/be_ai_chat.c: assertions on signed string index.
+ Note: this is not in my ChangeLog - ouch.
+ TODO: use gcc -fsigned-char on all platsforms to enforce Win32
+ TODO behavior (PPC has a default unsigned char, Intel has not).
+ * code/botlib/be_aas_sample.c (AAS_TraceClientBBox): one code block
+ was placed in different location, and one FPE hack not used. I would
+ expect that divide by zero will still occur here.
+
+ * code/botlib/be_aas_reach.c: below.
+ * code/botlib/be_aas_cluster.c: cleanup.
+ * CVS: the last tag (below) marks the version with a lot of history
+ and additional comments. I am now bringing the codebase in sync with
+ SOS as of yesterday, cleaning out comments, dead code and other
+ differences to minimize a diff - in a valiant if futile attempt to
+ roll back changes into the id codebase.
+ Note: I ignore the $SOS$ - these are unfortunate but will change
+ in the same awkward way at their end.
+ Note: I stick to #if 0 instead of C comments around dead code id
+ kept (nested comments issue). The commentary is changed to sosYYMMDD
+ and includes the token DEAD.
+
+2001-02-20 Bernd Kreimeier <bk@lokigames.com>
+
+ * CVS: update, then tag current version as
+ cvs tag id1-27i-loki010219
+
+ * SOS: patched up to sos010219.
+
+ * code/qcommon/cm_trace.c (CM_Trace): fabs on sphere offsets (SOS).
+ * code/game/bg_slidemove.c (PM_StepSlideMove): stepSize vs. STEPSIZE (SOS).
+ * code/game/bg_pmove.c (PM_CheckDuck): fix in stand up check (SOS).
+ * code/bspc/bspc.c (main): -capsule (SOS).
+ * code/bspc/qbsp.h: below (SOS).
+ * code/bspc/be_aas_bspc.c (capsule_collision): added (SOS).
+ * code/bspc/aas_map.c (CapsuleOriginDistanceFromPlane): added and used (SOS).
+ * code/bspc/aas_file.c (AAS_WriteAASFile): removed diagnostics recently
+ added. No matter how long you wait, they'll always get you ;-).
+ * code/botlib/be_aas_cluster.c: enabled LogWrites, different flood (SOS).
+
+ * SOS: patching up to snapshot sos010219.
+ Note: For brevity, I use as marker sosYYMMDD now instead of bkYYMMDD, to
+ distinguish from changes not in SOS.
+
+ * CVS: tagged current version before patching up with SOS.
+ cvs tag id1-27i-loki010216-bsd
+
+2001-02-16 Bernd Kreimeier <bk@lokigames.com>
+
+ * code/server/sv_init.c: DLL_ONLY sets sv_pure to 0 and ROM.
+ TODO: determine good sv_pure policy for DLL-only servers.
+
+ * code/renderer/tr_shade_calc.c: my_ftol implementation (BSD).
+
+ * code/unix/Makefile: FreeBSD sections.
+ TODO: include target-specific Make-freebsd etc.,
+ include a Make-local not in CVS for build preferences,
+ and generally clean up this mess.
+ * code/unix/unix_glw.h: guard #error
+ * code/unix/linux_snd.c: soundcard.h location (BSD).
+ * code/unix/linux_glimp.c: guard system headers.
+ Later: added Joystick stubs.
+ Note: linux_ etc. prefixes start to loose meaning as we
+ re-use most of this on UNIXes anyway. I didn't use Raf's
+ freebsd_joystick.c but instead put generic stubs here.
+ TODO: introduce generic -DNO_JOYSTICK flag.
+ * code/renderer/tr_local.h: my_ftol guard.
+ * code/renderer/qgl.h: FreeBSD guards.
+ * code/qcommon/vm_x86.c: sys/types include on FreeBSD.
+ * code/qcommon/md4.c: Win32 pragma guard.
+ * code/qcommon/common.c: Com_Memcpy/Memset external.
+ * code/game/q_shared.h: added FreeBSD defines.
+ * code/game/q_math.c (BoxOnPlaneSide): FreeBSD conditional.
+ TODO: check whether we have/need the assembly version anyway.
+ * code/client/snd_mix.c: use C fallback on FreeBSD.
+ Note: all of the above changes from the original port by Rafael Barrero.
+
+ * CVS: tagged current version before merging FreeBSD related changes.
+ cvs tag id1-27i-loki010215-ppc
+
+2001-02-15 Bernd Kreimeier <bk@lokigames.com>
+
+ * code/unix/Makefile: BSD related changes.
+ * code/cgame/cg_draw.c: hacked phone jack rendering check for Debug.
+ TODO: finish Debug, fix CG_DrawDisconnect !!!
+
+ * code/unix/vm_x86.c: error on compile attempts. Fight redundancy!
+ * code/qcommon/vm_x86.c (VM_CallCompiled): dummy for linkage on PPC.
+ Note: DLL_ONLY is the global Makefile option for DLL-only builts.
+ Currently only executed on Linux.
+ * code/unix/unix_main.c: *ppc postfix for DLLs. Ignored the changes
+ to redundant code (have to remove the unused Un/LoadDll/API calls).
+ * code/server/sv_game.c (VMA): changed macro (see below). PPC.
+ * code/qcommon/vm.c (VM_DllSyscall): see lengthy commentary by Ryan.
+ The existing VM code makes certain assumptions about the layout of
+ varargs on the stack, which fall apart with call conventions that
+ don't even put all parameters on the stack (gcc on PPC, register-rich).
+ Using a dedicated memory area as our own stack. This should actually
+ be the default behavior.
+ Later: make vm_* cvars INIT/ROM for DLL_ONLY target.
+
+ * code/qcommon/common.c: PPC change (from Ryan Gordon).
+
+2001-02-07 Bernd Kreimeier <bk@lokigames.com>
+
+ * code/unix/unix_main.c: disabled FPE for debug for the time
+ being (that is, until I can figure out
+ Program received signal SIGFPE, Arithmetic exception.
+ RB_BeginSurface (shader=0x449572e0, fogNum=0) at ..//renderer/tr_shade.c:307
+ 307 tess.shaderTime = backEnd.refdef.floatTime - tess.shader->timeOffset;
+ without any NaN's involved.
+ TODO: unmask other FPE's selectively (see Mike's Tribes2, no getenv though).
+
+2001-02-06 Bernd Kreimeier <bk@lokigames.com>
+
+ * SOS: up to date with todays snapshot.
+ Note: got the date wrong, comment used was bk010205. Duh.
+
+ * code/server/sv_snapshot.c (SV_UpdateServerCommandsToClient): below.
+ * code/server/sv_main.c (SV_ReplacePendingServerCommands): new (SOS).
+ * code/server/server.h: reliableSent (SOS).
+
+ * code/renderer/tr_shade.c (ProjectDlightTexture): see below.
+ * code/renderer/tr_scene.c: see below.
+ * code/renderer/tr_public.h: see below (SOS).
+ * code/renderer/tr_local.h: additive light support (SOS).
+
+ * code/qcommon/cm_trace.c (CM_Trace): new tw.sphere.use branch (SOS).
+
+ * code/game/g_spawn.c: notta, notq3a entities (SOS).
+ * code/game/ai_dmq3.c: MAX_ACTIVATEAREAS search (SOS).
+
+ * code/client/cl_cgame.c: see below.
+ * code/cgame/cg_syscalls.c (trap_R_AddAdditiveLightToScene): below.
+ * code/cgame/cg_syscalls.asm: see below (trap_R_AddAdditiveLightToScene).
+ * code/cgame/cg_public.h: CG_R_ADDADDITIVELIGHTTOSCENE (SOS).
+
+ * code/bspc/l_math.c: new VectorLengthSquared, removed rotate/matrix (SOS).
+ * code/bspc/bspc.c (BSPC_VERSION): was 2.1e, now?
+ * code/bspc/be_aas_bspc.c (BotImport_Trace): CM_BoxTrace sig. (SOS).
+ * code/bspc/aas_file.c (AAS_WriteAASFile): SOS.
+ * code/botlib/be_aas_sample.c (AAS_DeAllocAASLink): SOS.
+
+ * code/unix/unix_main.c (Sys_LoadDll): do not load from installdir
+ in NDEBUG (confusing relic from old Makefile). Postfix -debug.so
+ for debug binaries to let both builds coexist.
+
+ * code/unix/Makefile: updated install targets and VERSION.
+
+ * Win32: build from SOS snapshot.
+ Note: Unix CR/LF in *.dsw/*.dsp fucks up MSVC++.
+
+2001-02-02 Bernd Kreimeier <bk@lokigames.com>
+
+ * SOS: all changes up to today.
+
+ * code/server/sv_init.c (SV_TouchCGame): added. Also memset
+ on reallocated client data (SOS).
+ * code/qcommon/qcommon.h: see below.
+ * code/qcommon/cvar.c (Cvar_SetLatched): new (SOS).
+ * code/qcommon/cm_trace.c: more sphere test fixes (SOS).
+ Note: SOS encryption key expired and updated by MrElusive.
+
+ * code/qcommon/cm_patch.c (CM_TraceThroughPatchCollide):
+ fix from MrElusive, fall through curved corner floors (q3dm17).
+ Later: also in SOS (so is shadow FPE fix).
+
+ * Win32: can't get an unadulterated SOS snapshot to build.
+ First, fix CR/LF back again (Linux client converts all).
+ find . -name '*.ds*' -print
+ alias dos2unix='recode ibmpc..lat1'
+ alias unix2dos='recode lat1..ibmpc'
+ Next, find a *.dws that works? Nope, no cigar.
+
+2001-02-01 Bernd Kreimeier <bk@lokigames.com>
+
+ * Win32: have to update dsp/dsw/etc. files in CVS, too.
+
+ * CVS: tag previous version before update
+ cvs tag id1-27h-loki010131-beta3
+
+ * code/game/q_math.c (Q_rsqrt): guard, #ifndef __linux__
+ for assert (for Win32 build).
+ TODO: assert replacement for Win32?
+ * code/q3_ui/ui_qmenu.c: see below.
+ * code/q3_ui/ui_players.c: see below.
+ * code/q3_ui/ui_controls2.c: float const with f postfix
+ Note: Win32 C4305 warning. Somebody at id has been doing
+ a lot of these recently as well...
+
+ * code/cgame/cg_players.c (CG_PlayerShadow): applied fix by
+ MrElusive, removed FPE hack (player shadows on zero mormals).
+ Prolly in this evenings' CVS.
+
+ * code/server/sv_game.c: new signatures (capsule again).
+ * code/server/server.h: new signatures (SV_Trace,ClipToEntity).
+ * code/server/sv_bot.c: new signatures (above).
+ * code/qcommon/cm_trace.c: a truckload of changes. Math
+ code added before moved upwards. Capsule traces added all
+ over the place, old box traces moved in conditional
+ branches, functions renamed and wrapped. Eliminated some
+ of the previous' versions deadcode to keep diffs smaller.
+ TODO: once a point release is out and reasonably bug
+ TODO free, remove // bkYYMMDD annotations where SOS related.
+
+ * code/qcommon/cm_public.h: new signatures in prototypes.
+ * code/qcommon/cm_patch.c: dead code re-enabled, new
+ sections (conditional branches for spheres) added to
+ several trace functions.
+ * code/qcommon/cm_local.h (CAPSULE_MODEL_HANDLE): added.
+ * code/qcommon/cm_load.c (CM_TempBoxModel): capsules.
+
+ * code/game/q_shared.h (Q3_VERSION): 1.27i now (new QVM traps).
+
+ * code/game/g_syscalls.asm: see below.
+ * code/game/g_public.h (SVF_CAPSULE): added (SOS). Also
+ G_ entry poiints for capsule traces.
+
+ * code/client/cl_cgame.c: see below.
+ * code/cgame/cg_syscalls.c: see below.
+ * code/cgame/cg_syscalls.asm: see below.
+ * code/cgame/cg_public.h: new capsule trace code (SOS).
+
+2001-01-31 Bernd Kreimeier <bk@lokigames.com>
+
+ * Win32: test compile (WinCVS, MSVC++). Have to guard isnan.
+ Note: too much shit going on....
+
+2001-01-30 Bernd Kreimeier <bk@lokigames.com>
+
+ * CVS: update for patching up (pre-1.27i).
+
+ * SOS: new changes (new collision detection primitives).
+ Now Version 1.27i.
+ TODO: start testing using DLL's (QVM code is out of sync).
+
+2001-01-25 Bernd Kreimeier <bk@lokigames.com>
+
+ * SOS: caught up till today (below).
+ * code/qcommon/cm_trace.c: new functions added: RotatePoint,
+ TransposeMatrix, CreateRotationMatrix (SOS).
+ (CM_TransformedBoxTrace): new rotation code used here.
+
+ * code/q3_ui/ui_demo2.c: sizeof(extension). SOS.
+ * code/game/g_cmds.c (G_SayTo): CON_CONNECTED.
+ * code/game/ai_main.c: HOOK added (SOS).
+ * code/botlib/be_aas_move.c (AAS_HorizontalVelocityForJump):
+ correct fix for FPE occuring (SOS).
+ * code/game/ai_dmq3.c: initmove.viewoffset (SOS).
+
+ * code/game/q_math.c: guard asser/isnan with Q3_VM (q3asm).
+ TODO: define Com_Error based assert macro? NDEBUG?
+
+2001-01-24 Bernd Kreimeier <bk@lokigames.com>
+
+ * code/server/sv_ccmds.c (SV_MapRestart_f): some debug.
+ TODO: map_restart 0 disconnects external client in 1.27h?
+
+ * code/renderer/tr_image.c (LoadTGA): added some commentary
+ and dead code based on fixes from GtkRadiant (Leonardo found
+ flipped TGA's).
+
+2001-01-23 Bernd Kreimeier <bk@lokigames.com>
+
+ * BETA3: finished testing, ready to upload to id FTP.
+ Later: neither the FreeBSD beta not the Linux Beta3
+ uloaded. Beta2 not yet released, and clients get
+ disconnected with Beta2 and Beta3 on SV_MapRestart_f.
+
+2001-01-22 Bernd Kreimeier <bk@lokigames.com>
+
+ * code/client/cl_main.c (CL_InitDownloads): undid yesterday (SOS).
+ * code/botlib/be_aas_sample.c (AAS_DeAllocAASLink): guard print (SOS).
+ * code/server/sv_client.c (SV_DirectConnect): VM_Call disconnect (SOS).
+ * code/qcommon/files.c (FS_ListFilteredFiles): trailing slashes (SOS).
+ * code/game/g_cmds.c (SetTeam): print change (SOS).
+ Note: the above plus VectorClear(v1) (below) are todays SOS changes.
+
+ * code/cgame/cg_players.c (CG_PlayerShadow): ignore bogus
+ (all zero) planes. This caused FPE in ProjectPointOnPlane.
+ TODO: why does trace return zero normal planes?
+ Note: gdb seems totally at loss with vec3_t arrays....
+
+ * code/botlib/be_aas_sample.c (AAS_TraceAreas): FPE.
+ NaN in uninitialized v1 that wasn't supposed to be referred
+ to in this branch.
+
+ * code/botlib/be_aas_move.c (AAS_HorizontalVelocityForJump):
+ FPE divide by zero (zero zvel, zero t) for jump estimates.
+
+ * code/client/cl_main.c (CL_Frame):1856. uivm==NULL on
+ client after server crashed.
+ TODO: check that uivm always non-NULL for client.
+ TODO: do setenv(FX_NO_SIGNALS) to avoid exit errors...
+
+ * code/unix/linux_glimp.c (GLW_SetMode): added "Indirect"
+ Mesa token to software rendering detection. Reworded error
+ output and added drivername.
+ TODO: measure framerate instead?
+
+2001-01-21 Bernd Kreimeier <bk@lokigames.com>
+
+ * SOS: caught up with changes up until today.
+
+ * code/server/sv_init.c (SV_SetConfigstring): gentity != NULL
+
+ * code/server/sv_client.c: connect to "{all bots" server.
+ * code/renderer/tr_init.c: JPEG extension on screenshots
+ * code/qcommon/files.c: modes based on mods, fs_basegame
+
+ * code/q3_ui/ui_demo2.c: dm3 extension (demo names, protocol).
+
+ * code/game/g_client.c: savedEvents[] removed.
+ * code/game/bg_misc.c: event sequence fixes.
+ * code/client/snd_dma.c (S_StopBackgroundTrack): different use.
+ * code/client/cl_main.c: demo file handling changed (names).
+ Also CL_InitDownloads: always next download.
+
+ * code/cgame/cg_servercmds.c: cg_thirdPerson.
+ * code/cgame/cg_weapons.c: see below.
+ Also CG_ShotgunPattern: different call (seed parameter).
+
+ * code/cgame/cg_main.c: see below.
+ * code/cgame/cg_local.h: new cg_noProjectileTrail Cvar.
+ * code/cgame/cg_effects.c (CG_BubbleTrail): early out (above).
+
+ * code/bspc/l_poly.c (BOGUS_RANGE): increased.
+ * code/bspc/bspc.c: applied patch up to "2.1e"
+
+2001-01-18 Bernd Kreimeier <bk@lokigames.com>
+
+ * code/ui/ui_main.c: below.
+ * code/q3_ui/ui_main.c: UI_HASUNIQUECDKEY comment.
+ Note: mods have to return qfalse. See Bug #2890 in Fenris.
+
+2001-01-17 Bernd Kreimeier <bk@lokigames.com>
+
+ * BETA2: finished testing, uploaded to id's FTP for release.
+
+2001-01-16 Bernd Kreimeier <bk@lokigames.com>
+
+ * CVS: checking in preparation for Beta2.
+ cvs tag id1-27h-loki010116-beta2
+
+ * SOS: new bspc "2.1e". No change on 1.27h.
+
+ * TEST: patch-up seems to work fine. No new files have been added
+ to the linkage (i.e. the ft2/ files now added), so we might not be
+ feature complete.
+
+ * code/game/g_active.c (ClientThink_real): id MISSIONPACK
+ conditional in addition to the ones I added earlier.
+ * code/qcommon/files.c: REJECT. Linux hack for userdir threw it off.
+ * code/qcommon/unzip.c: REJECT. CRC-32 section removed.
+ Later: unused tempB
+
+ * code/q3_ui/ui_syscalls.asm: REJECT. Start/StopBackgroundTrack.
+ * code/ui/ui_syscalls.asm: REJECT. syscalls ids from 1.27h
+ as of SOS (floor/ceil - will this ever get straightened out)
+ * code/win32/win_input.c: REJECT. g_pMouse edit.
+ * ui/menus.txt: REJECT. Replaced with 1.27h version.
+ Note: some more due to $SOS$.
+
+ * ui/: new scripts.
+ cinematicmenu.menu, demo_quit.menu, ingame.txt, serverinfo_old.menu
+ vid_restart.menu
+
+ * code/ft2/ttconfig.h: below.
+ * code/ft2/sfconfig.h: below.
+ * code/ft2/pstables.h: below.
+ * code/ft2/psnames.c: below.
+ * code/ft2/psdriver.h/c: below.
+ * code/ft2/keys.h: below.
+ * code/ft2/ftbbox.c: new in 1.27h
+
+ * code/cgame/cg_newdraw.c: beware: cg_newDraw.c gets lost in diff easily.
+
+ * code/cgame/cg_rankings.c: file removed from SOS.
+
+2001-01-15 Bernd Kreimeier <bk@lokigames.com>
+
+ * Patch-up: patching up from RC4 to 1.27h current.
+ No changes since 010112 snapshot.
+ ln -s sos010112/ work
+ diff -urbB sos001204-rc4/ work > work.diff
+ ln -s cvs-1.27g/ work
+ patch -p0 < work.diff > work.patch
+ find cvs1.27g/ -name '*.rej' -print
+
+ * SOS: adding the remaining SOS snapshots to CVS.
+ cvs import Quake3_sos sos001211 pr1-27g-win32-001211
+ Note: at this point id warned about repository corruption.
+ Watch out for the syscall stuff in particular.
+ cvs import Quake3_sos sos010104 pr1-27g-win32-010104
+ cvs import Quake3_sos sos010108 pr1-27h-win32-010108
+ cvs import Quake3_sos sos010110 pr1-27h-win32-010110
+ cvs import Quake3_sos sos010112 pr1-27h-win32-010112
+ Note: the first 1.27h might be the public (server only)
+ beta released, the second one was post release. Beware
+ of source files added and removed (botlib headers, FT2).
+ Note: why so late? Don't ask...
+
+2001-01-08 Bernd Kreimeier <bk@lokigames.com>
+
+ * SOS: id's working up to 1.27h (server side fix for
+ Guard exploit seems to force earlier release). Updating
+ CVS (most of the changes are debug code put in and
+ then disabled, plus some fixes as below). Next patching
+ up to current SOS.
+
+2001-01-07 Bernd Kreimeier <bk@lokigames.com>
+
+ * Makefile: need to rework this for multiple platforms.
+ We also need null/null_vm.c for platforms where we don't
+ have JIT (assembly emit).
+
+2001-01-04 Bernd Kreimeier <bk@lokigames.com>
+
+ * code/q3_ui/ui_connect.c (UI_DisplayDownloadInfo): time
+ information for current (vs. start of download) is wrong,
+ thus negative 1 "estimated time", as well as transfer
+ rate just negative downloadSize. Not fixed.
+
+ * code/unix/unix_main.c (Sys_ParseArgs): added.
+ Note: for support/us, to identify builts. This is only
+ a skeleton right now - if I ever feel the need to support
+ more than "-v" and "--version" I'll have to flesh this out.
+
+ * code/unix/linux_glimp.c (signal_handler): see below.
+ * code/unix/unix_main.c (Sys_Exit): added an abstraction
+ layer for exit/_exit/assert/raise issues.
+ Note: need both a better debug/backtrace handling, and
+ have to find a way to determine why/where the alleged
+ startup/exit errors happen...
+
+2001-01-03 Bernd Kreimeier <bk@lokigames.com>
+
+ * code/game/g_mem.c (G_Alloc): ERR_DROP initiated by
+ addbot commands for large sv_maxclients, allegedly
+ caused segfaults in 1.17. Not reproducible.
+ TODO: recover more gracefully from failure to add bot?
+
+ * code/renderer/tr_light.c (R_LightForPoint): Tim Angus
+ reports a crashbug with nolight maps. Also assertion in
+ R_SetupEntityLightingGrid, might want conditional there.
+ DONE: fixed crash on LightForPoint for nolight maps.
+
+ * code/qcommon/qcommon.h: NUM_SERVER_PORTS. A feature
+ request to increase this, or make it more flexible
+ otherwise (Fenris).
+ TODO: id decision on more flexible NUM_SERVER_PORTS.
+
+2001-01-02 Bernd Kreimeier <bk@lokigames.com>
+
+ * code/unix/snapvector.nasm: fixed FPU bit (the current
+ one had reserved bits off, behavior should not change).
+ * code/qcommon/vm_x86.c: fixed symbols (below).
+ * code/unix/ftol.nasm: FPU bits weren't correct (duh).
+ DONE: shoot-though floor (q3dm5)
+ DONE: cursor-in-rect off (TA/Player model selection)
+ Note: in gdb, "disassemble <funcname>" is your friend.
+
+ * code/cgame/cg_public.h: CG_MEMSET is set to 100. In
+ cg_syscalls.asm it's 101. If I change it I get Bad trap 100
+ from the cgame VM code, so the 1.27g "official" VM code
+ uses it.
+
+ * code/unix/linux_common.c: have to fall back to C, the
+ current assembly is buggy...
+ * code/unix/Makefile (linux_common.o): added.
+ Later: also for dedicated. Less portable this way.
+ TODO: C_ONLY for dedicated on non-i386 only?
+
+ * code/qcommon/common.c: do not use memcpy/memset under Linux.
+ * code/unix/linux_common.c: added Andrew's assembly port.
+ TODO: C_ONLY for Com_Memset/Memcpy? Conditionals are fubared.
+
+ * code/qcommon/vm.c (VM_Init): use Win32 defaults (do not
+ use DLL's by default). This exposes DLL rounding errors
+ (damage through floors), and we don't want DLL's used by
+ default anyway.
+ TODO: why vm_ui default of 1?
+
+ * code/botlib/l_precomp.c (SourceWarning): removed assert.
+
+ * code/game/bg_lib.c (acos): defined, but we don't actually
+ use it except where the cg_syscalls.asm trap is used.
+
+ * code/game/g_public.h: missing lots of trap tokens.
+ * code/game/g_syscalls.c: missing lots of traps.
+ * code/game/g_syscalls.asm: more inconsistent hooks, were:
+ equ floor -111
+ equ ceil -112
+ equ testPrintInt -113
+ equ testPrintFloat -114
+ now changed to match cg_syscalls.
+ Note: fixed this in UI earlier, how did this slip through
+ the diffs against SOS?
+
+ * code/game/g_syscalls.c: no acos hook.
+ * code/cgame/cg_syscalls.c: no acos hook.
+ * code/cgame/cg_syscalls.asm: has acos hook as -112
+ Note: report from Tim Angus. The acos function is in bg_lib.c
+ which is linked only into ui (not q3_ui). That means we are
+ using libc acos right now?
+ Note: QVM traps are negative?
+
+ * BSD/Irix: tagged current CVS (not all of the below) as
+ cvs tag id1-27g-loki010102-bsd1
+ for BSD work (Rafael Barrero). Also be used for Irix update.
+
+2001-01-01 Bernd Kreimeier <bk@lokigames.com>
+
+ * SOS: adding the remaining SOS snapshots to CVS.
+ cvs import Quake3_sos sos001201-rc3 pr1-27f-win32-001201-rc3
+ cvs import Quake3_sos sos001202 pr1-27f-win32-001202
+ cvs import Quake3_sos sos001204 pr1-27g-win32-001204-rc4
+ This is the codebase to which the Linux branch has been patched
+ up. I can't verify whether this is identical to the RC4 codebase
+ as the tag doesn't work (but can check against the ZIP file..)
+ cvs import Quake3_sos sos001211 pr1-27g-win32-001211
+ The above snapshot contains a (post-release?) fix to ui_syscalls
+ in ui/ and q3_ui/. This change has been used in Linux (Beta1 and
+ above). At this point, id discouraged further use of SOS due to
+ repository corruption on their end. No further snapshots were
+ taken since.
+
+ * Fenris: since the release of the Beta1 bugs have been
+ maintained at http://fenris.lokigames.com/. I am going to
+ list issues here as they get fixed.
+
+2000-12-21 Bernd Kreimeier <bk@lokigames.com>
+
+ * code/renderer/tr_font.c: graceful silence with old mods?
+ * code/botlib/l_precomp.c (SourceWarning): graceful exit if old mod?
+
+2000-12-20 Bernd Kreimeier <bk@lokigames.com>
+
+ * code/server/sv_ccmds.c (SV_MapRestart_f): see below.
+ * code/qcommon/vm.c: currentVM is 0x0 in VM_ArgPtr.
+ In VM_Call, oldVM was NULL - made conditional the
+ reset of currentVM to oldVM.
+
+2000-12-18 Bernd Kreimeier <bk@lokigames.com>
+
+ * BETA1: closed Linux beta release. Stripped debug
+ and release binaries, DLL's, and pak4.pk3. CVS checkin,
+ will be tagged as
+ cvs tag id1-27g-loki001218-beta1
+ Later: id added a pak5.pk3 to the Win32 point release,
+ added this to the BETA1 best.
+
+ * code/qcommon/vm_x86.c: C37F.
+ * code/unix/snapvector.nasm: C37F.
+ Note: short of any real evidence, I gamble and use max.
+ precision (as well as default Linux precision, but NOT
+ Win32 precision). It seems that precision change is not
+ really an issue (despite Graeme's claim that the cursor
+ in the menu was/is off). I also pick the roundiung behavior
+ that is seemingly used by ANSI and gcc (but possibly not
+ Win32 _ftol depending on build).
+
+2000-12-15 Bernd Kreimeier <bk@lokigames.com>
+
+ * code/unix/Makefile: added snapvector.o
+ * code/unix/unix_shared.c: #if 0'ed the old snapvector code.
+ * code/unix/snapvector.nasm (Sys_SnapVectorCW): two new
+ assembly functions from AndrewH that explicitely set the
+ FPU control word to convert vec3_t, to ensure cross-platform
+ behavior for both DLL and QVM.
+
+ * code/unix/ftol.nasm (Q_ftolC37F): for globals.
+
+ * code/unix/unix_main.c: took out global FPU manipulation.
+ For clarity this should be VM only.
+ * code/qcommon/vm_x86.c: added prototypes for the ftol
+ library. To select a specific behavior for the entire VM,
+ set ftolPtr accordingly.
+ Later: the GCC ftol function of course affect the stack
+ (there is no "declspec naked"). The problem seems to be
+ that the VM never handles the stack in a way compatible
+ to regular gcc C functions. For some odd reason _ftol seems
+ to do the right thing under Win32. All 4 control words
+ implemented at the moment work just fine with the menus.
+
+ * code/unix/ftol.nasm: added a small library of "safe" qftol
+ variations that explicitely set the control word to the
+ relevant (4) possibilities.
+
+2000-12-13 Bernd Kreimeier <bk@lokigames.com>
+
+ * code/qcommon/vm_x86.c: an entire day spent trying to nail
+ the ftol issues. It breaks down like this: id used to use
+ an unsafe (no setting FPU control word) fistp. That seemingly
+ caused subtle physics bugs which nobody cared about in 1.17.
+ They then changed the UI code, and ran into the UI bugs:
+ menu entries shifted to the right, fonts vanishing. Then
+ they switched to using _ftol. Then they had to reproduce
+ the old behavior for the physics code due to public outrage.
+ My original port used a simple (long)float cast, which gcc
+ seemingly compiles to code that does OR 0C00 on whatever
+ current control word (precision unchanged). This breaks the
+ menus. If I use the unprotected fistp instead, which should
+ (Linux 037F default) use "nearest/even", then my menus are
+ correct. That would mean Win32 _ftol in id's compile does
+ the same, only that would require /qifist or some equivalent
+ compile flag, which I can't find. Two disassemblies of _ftol
+ I got from others showed OR 0C00 as part of the default (ANSI)
+ behavior.
+
+2000-12-13 Bernd Kreimeier <bk@lokigames.com>
+
+ * code/game/bg_pmove.c (PmoveSingle): trap_SnapVector.
+ The one true and single call to snap velocity.
+ Note: bspc/map.c:void SnapVector(vec3_t normal)
+ qcommon/cm_patch.c:void CM_SnapVector(vec3_t normal)
+ game/q_shared.h: #define SnapVector(v) {v[0]=((int)(v[0]));...
+
+ * code/client/cl_cgame.c: CG_SNAPVECTOR.
+ * code/server/sv_game.c: G_SNAPVECTOR.
+ Note: these go through trap_SnapVector in syscalls.
+
+ * code/unix/unix_shared.c (Sys_SnapVector): sticking to
+ old Linux version for now...
+ * code/win32/win_shared.c (Sys_SnapVector): changed.
+ Note: Graeme points out this was changed to fix ftol
+ artifacts?
+ TODO: calculate errors for various ftol variants...
+
+ * code/qcommon/vm_x86.c: both the old fistp code (1.17)
+ and the new qftol function apparatently work. Using the
+ ftol.nasm code for now.
+
+ * code/unix/Makefile: DO_NASM and ftol.o.
+
+ * code/unix/ftol.nasm (qftol): created from Mike's SoF
+ replacements, with Andrew's help to satify the VM
+ stack/call requirements.
+ TODO: use Q_ftol herein to replace myftol elsewhere.
+
+ * code/unix/unix_main.c (Sys_ConfigureFPU): SIGFPE.
+ TODO: divide by zero in botlib. Disable this for now.
+ Note: we can't introduce calculation differences between
+ versions, so fixing these will have to wait.
+
+ * code/qcommon/vm_x86.c: two new lines in Win32 branch
+ missing from Linux assembly in AsmCall:
+ mov eax, dword ptr [edi]
+ and eax, [callMask]
+ Added, doesn't seem to affect UI etc. bugs.
+ Later: no FTOL_PTR, use fistp non-IEEE assembly as in old
+ version. This seems to work for Q3 and TA, while qftol
+ (simple cast) does not - for Win32 Graeme says the reverse
+ is true.
+
+ * code/qcommon/vm_x86_old.c: used the old cvs-1.17 version.
+ Two fixes (Hunk_Alloc, Com_Memcpy), and it works:
+ +set vm_game 2 +set vm_ui 2 +set vm_cgame 2
+ UI, cgame and game w/o apparent problems.
+
+2000-12-12 Bernd Kreimeier <bk@lokigames.com>
+
+ * code/unix/Makefile: cleanup of redundant flags.
+ Removed bogus MALLOC_CHECK (note to self: export MALLOC_CHECK_=2).
+ Also DO_SHLIB_CC on all UI DLL's.
+ Added and removed DEBUG_VM flag.
+ TODO: figure out whether Zoid did UI this way intentionally.
+ Note: this seemingly fixed the botimport problem, although
+ most of the changes were just redundant CFLAGS removed. Given
+ our wanker toolchain, should have been more paranoid. All
+ DLL's can now be used w/o apparent problems.
+
+ * code/server/sv_main.c: gvm init.
+ * code/server/sv_game.c: gvm assertions.
+ * code/unix/unix_main.c (Sys_LoadDll): print vmMain
+ Note: top no avail. There is some odd ld/gdb problem here
+ that prevents examining globals and obfuscates part of
+ the stack between VM_Call and lower level code, through
+ G_InitGame. This is not just DLL's being loaded and unloaded.
+ Wromg flags during build? The vmCvar for "bot_developer"
+ ends up overlapping global botimport in memory, which
+ thus zero-fills part of the function pointer table.
+
+ * code/server/sv_bot.c (SV_BotInitBotLib): this (by way of
+ GetBotLibAPI) is responsible for setting botimport, which,
+ if using the game DLL, is not properly set up. Called in
+ SV_Init().
+
+ * code/game/q_shared.c: Q_strncpyz does zero padding (duh).
+ Note: calls strncpy, which does a zero fill up to destsize.
+ If destsize exceeds memory size, zero padding will overwrite
+ adjacent memory. Suspicion was this happend to botimport.
+
+ * code/qcommon/cvar.c: possible problem in Q_strncpyz call.
+
+ * code/botlib/be_ai_weap.c (weaponinfo_fields): made this static.
+ Note: it seems that the "number" string got replaced by
+ p def.fields[0]
+ {name = 0x40000000 "\177ELF\001\001\001", offset = 2, type = 50, ..
+ Memory corruption?
+
+ * code/game/inv.h (WEAPONINDEX_GAUNTLET): defined here.
+ * botfiles/weapons.c (Gauntlet): the baseq3/qagamei386.so parser
+ breaks here:
+ number WEAPONINDEX_GAUNTLET
+ * code/botlib/l_precomp.c (SourceWarning): added assertion to
+ trap botlib parsing problem..
+
+ * RC1: for beta test. Using my own vm/ui.qvm files in this case.
+ TODO: Setup with nouninstall.
+ TODO: fix game DLL/ botlib setup problem (so all DLL's work)
+ TODO: SIGFPE
+ TODO: profile?
+
+ * code/unix/Makefile (ai_vcmd.o): added to game DLL linkage.
+ How the fuck did this happen?
+ DONE: "qagamei386.so: undefined symbol: BotVoiceChat_Defend"
+
+ * TEST: +set vm_ui 2 (vm_x86, not interpreter). Breaks!
+ Further: qagame had undefined, but seemingly gets reloaded
+ second try (I hate the Linux linker).
+ * TODO: never reload fail DLL, abort engine
+
+
+2000-12-11 Bernd Kreimeier <bk@lokigames.com>
+
+ * TEST: recompile QVM/DLL and executable to test new UI code.
+ The UI QVMs from the paks still do not work.
+
+ * SOS: changes in UI code!
+ * code/q3_ui/ui_public.h: this file is deprecated
+ Note: e.g. it does not contain the background track calls.
+ * code/ui/ui_public.h: the uiImport_t enum here determines
+ the values.
+ * code/ui/ui_syscalls.asm: same as q3_ui now, were:
+ equ floor -111
+ equ ceil -112
+ * code/q3_ui/ui_syscalls.asm: these are now switched, were:
+ equ trap_S_StartBackgroundTrack -63
+ equ trap_S_StopBackgroundTrack -64
+ The new values match the ui/ equivalent. Also, floor (-108)
+ and ceil (-109) are different in ui/.
+
+ * CVS: going to check in this snapshot and tag it as
+ cvs tag id1-27g-loki001209-rc4
+ Presumed equivalent to SOS tag "1.27g RC4" (master). As I can't
+ obtain the tagged code using SOS (neither Win32 nor Linux client)
+ I can only guess.
+
+ * TEST: use my own VM code, ion baseq3/vm/*.qvm and missionpack/vm/.
+ This works - in other words, the menu bug seems in the UI code, and
+ is fixed in my codebase.
+
+ * TEST: make release.
+ Note: I can postpone DLL specific problems. Bad performance is not
+ as important as outright bugs. Thus the UI QVM issue is the only
+ one that stops me from creating an RC.
+ TODO: Q3 UI QVM code from pak file does not work (neither does TA).
+ TODO: sound with video playback still awful. Threaded sound, I guess.
+ TODO: ERROR: couldn't open demos/DEMO002.dm3.dm_48 (same demo001.dm3.dm_48)
+
+ TODO: do not show Q3 demos in TA menu?
+ TODO: new demos for Q3? Or at least error message?
+
+ * code/game/bg_lib.c: itrinsics excluded by Q3_VM (another -O
+ compile). Uninitialized variable.
+ * code/unix/Makefile: -O for uninit on patched code. Also shortcuts.
+ TODO: DC_ONLY seems an obsolete flag, used in Makefiles, not source.
+
+ * TEST: +set sv_pure 0 +set vm_game 1 +set vm_cgame 1 +set vm_ui 0
+ Turns out that the pak0.pk3 UI QVM code is seemingly broken in TA
+ and Q3, but my UI DLL is not. In reverse, the QVM game/cgame for
+ Q3 seems to work quite well (including bots). The TA game/cgame
+ also works, including botlib init.
+ TODO: BotLib Init using game DLL gives:
+ TODO: Error: file weapons.c, line 38: unknown structure field number
+ TODO: Fatal: couldn't load the weapon config
+ TODO: Error: BotLoadMap: bot library used before being setup
+
+ * TEST: checked the rc4winstlr.zip CD tree against
+ my test install. baseq3/pak4.pl3 and missionpack/pak0.pk3
+ are identical, but I finally recognized that there was
+ a missionpack/pak1.pk3 not in the final install - left over
+ from an earlier update from id. Doesn't seem to affect the
+ DLL based runs at all.
+ Note: I still do not have the final CD snapshot Robert
+ promised me mid last week, they haven't even fixed the
+ FTP account they took down. Communication with id is as
+ abyssmal as ever.
+
+2000-12-08 Bernd Kreimeier <bk@lokigames.com>
+
+ * TEST: running with RC4 data files.
+ TODO: "bot library used before setup" (Q3+TA)
+ TODO: Q3 old mods wreak havoc (graceful bounce)
+ TODO: supress "FreeType code not available" in renderer
+ TODO: can't move in Q3
+ TODO: items flicker in Q3
+ TODO: no decals in Q3
+ TODO: VM UI code still broken (Q3+TA)
+ TODO: sound code is awful
+ TODO: video playback inferior to earlier builds
+
+ * code/q3_ui/ui_local.h: prototype trap_VerifyCDKey(..)
+ * code/game/g_active.c ( StuckInOtherClient): TA only.
+ * code/cgame/cg_draw.c: 4x unbalanced `#endif' - from patch?
+ * code/null/null_client.c (CL_CDKeyValidate): dummy added.
+ * code/qcommon/common.c: Q_acos missing, changed conditionals
+
+ * code/qcommon/vm_x86.c: unreacheable _asm instruction that
+ gcc doesn't quite like... #if 0'ed for now
+ TODO: understand _asm { mov eax,[ebx] }, fix it for gcc
+
+ * TEST: compile...
+
+ * code/ui/ui_main.c: full REJECT. Manual merge.
+ Note: preserved debug_protocol lines, who knows what it's good for.
+
+ * code/qcommon/files.c: REJECT. SafeMode, demo server FS_Restart.
+
+ * code/client/snd_mem.c: REJECT: $SOS$.
+ * code/client/snd_dma.c: REJECT: $SOS$.
+ * code/client/cl_cin.c: REJECT. com_timescale, $SOS$.
+
+ * code/cgame/cg_draw.c: REJECT. Lots, but virtually all either
+ float postfix (on some, not all places), or #ifndef MISSIONPACK
+ that I had already put in during -Werror (conditional unused).
+
+ * code/cgame/cg_consolecmds.c: REJECT. id commented unused code
+ that I had #if 0'ed earlier.
+
+ * code/game/: three REJECT for $SOS$.
+ * code/botlib/: lots REJECT for $SOS$.
+
+ * Patch: patching up from demo source.
+ ln -s sos001204-rc4 work
+ diff -urbB sos001122-demo/ work > work.diff
+ ln -s cvs-1.27b/ work
+ patch -p0 < work.diff > work.patch
+ find cvs1.27b/ -name '*.rej' -print
+
+ * CVS: going to check in this snapshot and tag it as
+ cvs tag id1-27b-loki001208-demo
+ Then patching up to RC4, as of sos001204-rc4 (no changes since,
+ should be equivalent to SOS tag "1.27g RC4" (raduffy), i.e. master.
+
+ * TEST: installed demota/ from Win32 distribution. Binary
+ fails claiming "Corrupted pak0.pk3". Abandoned.
+ Note: a Linux demo for Q3TA has no priority. Most important is
+ the Q3A point release in time for Q3TA hitting shelves, followed
+ by testing for Q3TA. The source is in CVS and tagged (see above)
+ in case a demo matching the released files has to be provided
+ later.
+
+
+2000-12-07 Bernd Kreimeier <bk@lokigames.com>
+
+ * TEST: compile and link - succeeds.
+
+ * code/ui/ui_main.c: UI_StopServerRefresh now uaws.
+ New unused variables.
+
+ * code/unix/unix_main.c: added Sys_LowPhysicalMemory() stub.
+ TODO: write Linux equivalent to GlobalMemoryStatus.
+
+ * code/qcommon/common.c: Com_Memset/Com_Memcpy. Neither assembly
+ nor C versions included if not on Win32 i386.
+ TODO: using/porting assembly?
+
+ * code/qcommon/files.c: unused variable.
+ TODO: fs_scrambledProductId unused if 0 for now.
+ Note: -DFS_MISSING for id's pak cleanup, not used.
+
+ * TEST: compile and link - fails.
+
+ * code/macosx/Client/Makefile.postamble: empty ORIG.
+ * code/macosx/Client/Makefile.preamble: ORIG. $(BOTLIB_OBJS) added.
+
+ * code/server/sv_client.c: ORIG. Com_Memset.
+ * code/renderer/tr_shader.c: ORIG. Com_Memset, CIN_Shader.
+ * code/qcommon/vm_x86.c: ORIG. Com_Memcpy.
+ * code/qcommon/unzip.c: REJECT. Com_Memcpy, $SOS$.
+ * code/qcommon/qcommon.h: ORIG. PROTOCOL 47, plus Sys_LowPhysicalMemory.
+ * code/qcommon/md4.c: Com_Memset,Com_Memcpy (ORIG).
+ * code/qcommon/files.c (Sys_ConcatenateFileList): REJECT.
+ Our additons threw it off, plus $SOS$.
+ * code/qcommon/common.c: they fixed same unused variables (REJECT).
+
+ * code/ui/ui_shared.c: additions (ORIG).
+ * code/ui/ui_gameinfo.c: COM_Compress added (ORIG).
+ * code/ui/ui_atoms.c: print statements removed (ORIG).
+ * code/ui/ui_main.c (UI_DoServerRefresh): REJECT on comment edit...
+
+ * code/game/g_cmds.c (Cmd_VoiceTaunt_f): logic changed heavily. ORIG.
+ * code/game/q_shared.h: Q3_VERSION "Q3 Team Arena Demo 1.27b"
+ plus Com_Memset, Com_Memcpy, CIN_shader, COM_Compress.
+ * code/game/g_main.c: Cvar change only
+ * code/game/ai_dmq3.c: $SOS$.
+
+ * code/client/snd_mix.c: Com_Memset
+ * code/client/client.h: additions (ORIG).
+ * code/client/snd_mem.c: see below.
+ * code/client/snd_dma.c: $SOS$ (CVS keyword).
+
+ * code/client/cl_cin.c: they removed unused (REJECT).
+ * code/cgame/cg_servercmds.c: ORIG. compress, noTaunt etc.
+ * code/cgame/cg_main.c: ORIG. Conditonal branch, COM_Compress.
+ * code/cgame/cg_consolecmds.c: ORIG. Cvar values changed.
+ * code/cgame/cg_draw.c (CG_DrawTeamBackground): ORIG.
+ no reject but *.orig file created. I just mark spots were
+ code changed after verifying the patch succeeded.
+
+ * code/cgame/cg_event.c: fixed reject (REJECT).
+ * code/botlib/: all *.rej here due to SOS/CVS $Keyword$.
+ TODO: preserve SOS comments/rev history somehow.
+
+ * Patch: patching up to demo source.
+ ln -s sos001122-demo work
+ diff -urbB sos001119/ work > work.diff
+ ln -s cvs-1.26/ work
+ patch -p0 < work.diff > work.patch
+ find cvs1.26/ -name '*.rej' -print
+
+ * CVS: going to check in this snapshot and tag it as
+ cvs tag id1-26w-loki001207
+ to prepare for upgrading to RC4. I have already made
+ many more changes than I wanted to w/o getting any
+ closer to pinpointing the problem, I might as well
+ patch up to id's more current sources.
+
+ * code/botlib/be_interface.c: initialize by memset. Turns
+ out that this fails in Export_BotLibSetup on BotSetupWeaponAI
+ loading "weapons.c" (from the pak, presumably) with an unknown
+ structure field number. Mismatch of datafiles vs. source again.
+
+ TODO: id replaced memsets in later source.
+ TODO: have memsets on all exports and imports.
+
+ * SOS: RC4 source should be tagged "1.27g RC4" (raduffy).
+ Unfortunately the Linux client doesn't care a bit. Show
+ History does work if from/to date differ by at least a
+ day, and it shows the tag on code/ (only that subtree),
+ but recursive get aborts halfway.
+ Manual: http://www.sourcegear.com/SOS/Doc/
+
+2000-12-06 Bernd Kreimeier <bk@lokigames.com>
+
+ * TEST: accepting missing shaders now. No bots, but I can
+ actually enter the game and play (more than can be said for
+ classic Q3 right now).
+ TODO: Error: BotStartFrame: bot library used before being setup
+
+ * code/renderer/tr_shader.c: took out assertion for now...
+ * TEST: now missiopack/cgame loads
+ TODO: tr_shader.c:2275: R_FindShaderByName: failed
+ TODO: searches ui/assets/3_cursor2.TGA, has ui/assets/3_cursor3.tga
+
+ * code/unix/Makefile (MPCGOBJ): ui_shared.o (duh).
+ DONE: /cgamei386.so: undefined symbol: PC_Float_Parse
+
+ * code/botlib/be_ai_goal.c: initialize campspots etc. This
+ might or might not fix this one (didn't get back to gdb due
+ to mouse-only navigation).
+ DONE: 0x80d1d5b in BotFreeInfoEntities () at be_ai_goal.c:447
+
+ * TEST: this time with missionpack/cgame loading... noy
+ TODO: TA menu blocked after end of intro movie
+ TODO: console in_mouse 1 doesn't grap pointer even on vid_start?
+
+ * code/cgame/cg_newdraw.c: -Werror.
+ * code/unix/Makefile (MPCGOBJ): cg_newdraw.o was missing (duh).
+ DONE: missionpack/cgamei386.so: undefined symbol: CG_OwnerDrawVisible"
+
+ * code/ui/ui_shared.c:1309 assign after bail on NULL.
+ DONE: segfault in Item_SetFocus (item=0x0, x=0, y=0)
+
+ * TEST: new set of DLL's (this time hopefully correct).
+ All baseq3/ DLL's load, as does the missionpack/ UI DLL.
+ The menus now work in both (TA seems mouse-only on everything
+ but "Quit"). Segfault on delayed TA "Quit" (stack fubared):
+ #5 0x809fc28 in VM_Call (vm=0x88408a0, callnum=3) at ..//qcommon/vm.c:617
+ #6 0x805aafc in CL_KeyEvent (key=9, down=qtrue, time=128644) cl_keys.c:1194
+ TODO: TA menu's w/o mouse?
+ TODO: Win32 goes submenus but does not unfold
+ TODO: Linux does not go submenus
+
+ * code/ui/ui_main.c: see below.
+ TODO: LCC gets fits - operands of = have illegal types
+ TODO: 'pointer to const unsigned char' and 'pointer to const char'
+ * code/ui/ui_shared.c: see below.
+ * code/ui/ui_gameinfo.c: see below.
+ * code/ui/ui_atoms.c: see below.
+ * code/game/g_bot.c: more cruft.
+ * code/cgame/cg_draw.c: loads of functions modified for
+ MISSIONPACK that aren't used at all for MISSIONPACK anymore.
+ Development relics.
+
+ * code/cgame/cg_consolecmds.c: -Werror.
+ Note: due to Makefile error never ever compiled...
+
+ * code/unix/Makefile: fixed various dependency errors
+ for game and ui library.
+ TODO: create a new Makefile with patsubst and rules.
+ TODO: why C_ONLY in the i386 dedicated server?
+
+ * code/unix/unix_main.c: use dlerror() excessively.
+ Littered more unused DLL related functions with assert(0).
+ TODO: clean up Sys_Load/UnloadDll (a real mess)
+ TODO: remove Zoid code cruft (unused per-DLL functions)
+
+ * code/game/bg_misc.c: changed G_Printf for Com_Printf.
+ This was undefined in baseq3/uii386.so preventing loading.
+
+ * TEST: +set sv_pure 0 +set vm_game 0 +set vm_cgame 0 +set vm_ui 0
+ Note: so far I used only the game DLL.. duh.
+ UI DLL fails to load: missing G_Printf.
+
+ * code/unix/Makefile: -DMALLOC_CHECK in addition to
+ the -DZONE_DEBUG I have used since switching to calloc.
+ Using MALLOC_CHECK=1 for now, might use 2 if something
+ comes up.
+
+ * code/renderer/tr_init.c (GL_SetDefaultState): it does get
+ called, but does not show up in the log.
+
+ * TEST: tried executing a script - get bounced.
+ TODO: is there any way to jump into a map?
+ TODO: cl_cinematics 0 (supress all fullscreen RoQ)
+ Next: used r_logfile 200 in Win32 (RC4) and Linux.
+ There is a buckload of setup code seemingly not done
+ at all in Linux? Either that, or logging is enabled
+ with a delay in Linux.
+
+ * code/unix/linux_glimp.c: fixed autorepeat (H2/Fakk2 way).
+
+2000-12-05 Bernd Kreimeier <bk@lokigames.com>
+
+ * code/renderer/tr_mesh.c: added assert there.
+ * TEST: menus and in-game drawing are just as they were with
+ the initial SOS001119 port. In addition:
+ R_AddMD3Surfaces: no such frame 0 to -2147483477
+ for 'models/players/xaero/upper.md3'
+ R_AddMD3Surfaces: no such frame -2147483477 to 171
+ R_AddMD3Surfaces: no such frame 171 to -2147483498
+ ad nauseam (used as my player model).
+ Triggered: haveing a trRefEntity_t *) 0x41dbbd00 with
+ frame = -2147483477. Might be a red herring (PRINT_DEVELOPER),
+ ignore for now.
+
+ * code/ui/ui_main.c: missing return.
+ * code/ui/ui_shared.c: excess byte in initializer (which gcc
+ did not caught, but LCC did). Also LCC complains about
+ missing returns, but gcc doesn't (neither says unreacheable
+ code though). If necessary (MsVC?) guard with Q3_VM.
+
+ * code/q3_ui/ui_ingame.c: see below.
+ * code/q3_ui/ui_atoms.c: voidfunc_f. LCC warns about conversion
+ from `pointer to void' to `pointer to void function(void)'
+ being compiler dependent. Casting NULL. Guess what, doesn't fix
+ it either.
+ TODO: do not use these cursed scripts to generate VM code,
+ we do not have proper rules for LCC/q3asm, thus the files never
+ get updated.
+
+ * code/unix/Makefile: for paranoia's sake recreated the 1.17
+ compile for the UI DLL (where only q_shared/math were actually
+ compiled as DO_SHLIB_CC.
+ Later: switched to different gcc.
+
+ * STATIC: remaining problems are vmMain (same entry point for all
+ DLL's), could use cgMain, uiMain and gMain here for HARD_LINKED.
+ Note: I don't think id has used this in ages.
+ Plus all the collisions in *_syscalls.c, which simply can't be
+ fixed cheaply. None is the superset of 2 others, neither seems
+ w/o overlap to others. Full stop.
+
+ * code/botlib/be_aas_move.c: see below.
+ * code/game/ai_dmq3.c: VEC_UP/DOWN, MOVEDIR_UP/DOWN now static.
+ See also game/g_utils.c for existing static duplicates.
+
+ * code/game/q_shared.h: #define stricmp strcasecmp
+ * code/unix/Makefile: no mo' -Dstricmp=strcasecmp, see q_shared.h
+ Also: no mo' -I/usr/include/glide, no FX
+ TODO: are we building against system GL headers? ../Mesa/?
+
+ * code/q3_ui/ui_atoms.c: comment on duplication
+ * code/cgame/cg_drawtools.c: use UI/CGAME_HARD_LINKED on UI duplicates
+ TODO: does this UI_ code in cg_drawtools/ui_atoms belong into ui_shared?
+
+ * code/unix/Makefile: use -DQ3_STATIC
+ * code/game/q_shared.h (*_HARD_LINKED): trigger on Q3_STATIC
+ Later: collision between UI and CGAME is still there. This fixed
+ the Com_Error, Com_Printf issues though
+
+ * code/unix/Makefile ($(B)/q3static/ai_vcmd.o): this file was
+ missing, hence undefined symbol.
+ ($(B)/baseq3/game/ai_vcmd.o): same here.
+ ($(B)/missionpack/game/ai_vcmd.o): same here.
+
+ * STATIC: cg_syscalls.c, g_syscalls.c and ui_syscalls.c alias.
+ Multiply defined symbols:
+ Com_Error, Com_Printf
+ VEC_UP, VEC_DOWN
+ MOVEDIR_UP, MOVEDIR_DOWN
+ vmMain
+ dllEntry
+ PASSFLOAT
+ trap_Error
+ trap_Milliseconds
+ trap_Argc
+ trap_Argv
+ trap_FS_FOpenFile
+ trap_FS_Read
+ trap_FS_Write
+ trap_FS_FCloseFile
+ trap_FS_GetFileList
+ trap_R_RegisterModel
+ trap_R_RegisterSkin
+ trap_R_RegisterFont
+ trap_R_RegisterShaderNoMip
+ trap_R_ClearScene
+ trap_R_AddRefEntityToScene
+ trap_R_AddPolyToScene
+ trap_R_AddLightToScene
+ trap_R_RenderScene
+ trap_R_SetColor
+ trap_R_DrawStretchPic
+ trap_R_ModelBounds
+ trap_UpdateScree
+ trap_S_StartLocalSound
+ trap_S_RegisterSound
+ trap_Key_IsDown
+ trap_Key_GetCatcher
+ trap_Key_SetCatcher
+ trap_GetGlconfig
+ trap_PC_AddGlobalDefine
+ trap_PC_LoadSource
+ trap_PC_FreeSource
+ trap_PC_FreeSource
+ trap_PC_ReadToken
+ trap_PC_SourceFileAndLine
+ trap_S_StopBackgroundTrack
+ trap_S_StartBackgroundTrack
+ trap_RealTime
+ trap_CIN_PlayCinematic
+ trap_CIN_StopCinematic
+ trap_CIN_RunCinematic
+ trap_CIN_DrawCinematic
+ trap_CIN_SetExtents
+ trap_MemoryRemaining
+ trap_SendConsoleCommand
+ trap_Cvar_Register
+ trap_Cvar_Update
+ trap_Cvar_Set
+ trap_Cvar_VariableValue
+ trap_Cvar_VariableStringBuffer
+ trap_RealTime
+ trap_SnapVector // used in game/bg_*.c, needs conditional
+ More aliasing between ui_atoms.c and cg_drawtools.c:
+ UI_DrawBannerString
+ UI_ProportionalStringWidth
+ UI_ProportionalSizeScale
+ Undefined symbol: ai_team.o: In function `FindHumanTeamLeader':
+ ai_team.c:1899: undefined reference to `BotVoiceChat_Defend'
+ Note:
+
+ * code/game/g_main.c: unused.
+ * code/game/g_arenas.c: unused.
+ * code/game/ai_team.c: init.
+ * code/game/ai_dmnet.c: /* in comment (odd).
+ Note: why do these come up now but not earlier?
+ TODO: the make dependencies might target wrong files.
+
+ * code/unix/Makefile (TARGETS): added q3static.
+ Note: this is baseq3/
+
+ * TEST: +set r_logfile 100. It seems that the addition of
+ code (add an assertion etc.) changes the behavio of the binary.
+ The intro cinematics code seems to suffer first - didn't play,
+ then played, then (another assert added) doesn't play. Watch
+ out for (missionpack):
+ UI_CIN_PlayCinematic
+ SCR_PlayCinematic( mpintro.roq )
+ trFMV::play(), playing mpintro.roq
+ Also fails to exit cleanly: break gives
+ #0 0x401919ee in __select ()
+ #1 0x400bbcb8 in __DTOR_END__ ()
+ #2 0x4004baa1 in _XSend ()
+ #3 0x452b009f in GLXRenderFlush ()
+ #4 0x804ce0c in _XRead ()
+ #5 0x40680813 in ?? ()
+ Stack is corrupted.
+ Note: ~/.q3a/gl.log
+ TODO: write per-frame files (see Heretic2)
+ TODO: add Heretic2 QGL (more detail)
+
+ * code/unix/linux_qgl.c (QGL_EnableLogging): fixed countdown
+ (i.e. propagated changes from win32/, see Fakk2).
+
+ * code/unix/linux_glimp.c: fixed QGL_EnableLogging argument
+ to avoid cast error (always qfalse).
+
+ * code/unix/Makefile (DEBUG_CFLAGS): use ZONE_DEBUG.
+
+ * code/qcommon/common.c: replaced malloc with calloc calls.
+
+ * code/q3_ui/ui_local.h: have to use ui/ui_public.h
+ * code/cgame/cg_servercmds.c: requires ../ui/menudef.h
+
+ * code/cgame/cg_consolecmds.c: ui/ui_shared.h is unique.
+ * code/q3_ui/ui_public.h: make sure this won't be compiled.
+ * code/client/client.h: we have to include ui/ui_public.h.
+ Note: id is obviously maintaing only the ui/ headers, so the
+ headers in q3_ui/ are deprecated.
+
+ * code/renderer/tr_shader.c: added assertions (see Ryan's Fakk2
+ problems with missing shaders).
+
+ * code/game/g_cmds.c: below.
+ * code/game/ai_vcmd.c: below.
+ * code/game/ai_team.c: below.
+ * code/game/ai_dmnet.c: below.
+ * code/game/ai_dmq3.c: below.
+ * code/game/ai_chat.c: below.
+ * code/game/ai_cmd.c: ../../ui/menudef.h (new Q3TA script directory).
+
+ * code/cgame/cg_newdraw.c: make sure it won't compile w/o MISSIONPACK.
+
+ * code/cgame/cg_servercmds.c: below.
+ * code/cgame/cg_event.c: below.
+ * code/cgame/cg_consolecmds.c: below.
+ * code/client/keys.h: below.
+ * code/client/client.h: below.
+ * code/q3_ui/ui_local.h: include from ../q3_ui/ not ../ui/.
+ Note: id seems to intentionally use the header from the new ui/.
+
+ * Makefile: checked -I$(UIDIR), there is no such. That means all
+ files include directly, which means all (including Q3) are using
+ the new ui/ headers.
+
+2000-12-04 Bernd Kreimeier <bk@lokigames.com>
+
+ * RC4: released as 362101115 Dec 4 11:40 TA_Q3A_RC4.zip
+
+ * TEST: the corrupted menu problem is back :-(. Looks like I am in
+ for a static link next.
+
+ * code/unix/Makefile (clean2): fixed (not all new OBJ covered).
+ * code/q3_ui/ui_teamorders.c: -Werror.
+ * code/q3_ui/ui_team.c: -Werror.
+ * code/q3_ui/ui_qmenu.c (Bitmap_Draw): -Werror.
+ * code/q3_ui/ui_mods.c (UI_Mods_LoadModsFromFile): unused. -Werror.
+ * code/q3_ui/ui_controls2.c: -Werror.
+ * code/q3_ui/ui_atoms.c: -Werror
+ * code/null/null_client.c: -Werror.
+ * code/unix/linux_joystick.c: -Werror.
+ * code/unix/linux_glimp.c: -Werror.
+ * code/unix/linux_qgl.c: -Werror.
+ * code/unix/unix_shared.c: -Werror.
+ * code/unix/unix_net.c: -Werror.
+ * code/unix/linux_local.h: added missing prototypes.
+ * code/unix/unix_main.c: -Werror. Includes linux_local.h
+ * code/jpeg-6/jdmainct.c: see below.
+ * code/jpeg-6/jcmainct.c: variables called "main" (*moan*)
+ * code/jpeg-6/jcdctmgr.c (forward_DCT): -Werror.
+ * code/botlib/l_script.c (PS_ReadLiteral): -Werror
+ * code/botlib/l_precomp.c (PC_AddBuiltinDefines): -Werror.
+ * code/botlib/be_interface.c: -Werror.
+ * code/botlib/be_aas_reach.c: -Werror
+ * code/botlib/be_aas_cluster.c: -Werror
+ * code/game/be_aas.h: -Werror.
+ Note: MrElusive accumulates a lot of code history in nested comments,
+ which gcc doesn't like at all. #if 0'ed to avoid.
+ * code/qcommon/vm_interpreted.c: -Werror.
+ * code/qcommon/unzip.c: -Werror.
+ * code/cgame/cg_servercmds.c: -Werror.
+ * code/cgame/cg_main.c: -Werror.
+ * code/cgame/cg_drawtools.c: -Werror.
+ * code/game/bg_misc.c: -Werror.
+ * code/game/be_ai_move.h (bot_avoidspot_s): added.
+ * code/botlib/be_ai_move.c: removed typedef struct bot_avoidspot_s
+ * code/client/snd_mix.c: -Werror.
+ * code/qcommon/md4.c: -Werror.
+ * code/qcommon/common.c: -Werror.
+ * code/client/cl_keys.c: -Werror.
+ * code/client/cl_cin.c: -Werror, init local variables.
+ * code/unix/Makefile: -Werror. need -O for -Wall for uninitialized
+ Note: the above is the list of files that got touched during a pass
+ with -g -O -Werror -Wall flags (in the hope of finding uninitialized
+ memory and ambiguous statements). Most of the above are simply
+ unused variables (or even code).
+
+ TEST: RC3 data files, but DLL's.
+ TODO: TA gets stuck in initial sound, doesn't play cinematics (sometimes)
+ TODO: Q3 intro movie looses sound after Sarge gets teleported
+ TODO: Q3 ingame renders world, weapon, muzzleflash, hud, can shoot,
+ TODO: but no movement, hud background is fubared.
+
+ * code/cgame/cg_main.c: cg_singlePlayerActive
+
+ * code/q3_ui/ui_login.c: doesn't seem to be used?
+ * code/game/g_rankings.c (G_RankRunFrame): doesn't seem to be used.
+ * code/q3_ui/ui.sh: disabled this.
+ * code/q3_ui/q3_ui.sh: changed include path to ../q3_ui/ (duh).
+
+ * code/game/game.sh: changed include path to ../q3_ui/ which
+ is not in the Win32 batch file.
+ * code/cgame/cg_rankings.c: this does not seem to be included.
+ * code/cgame/cgame_ta.sh: added -DCGAME. Also added cg_syscalls.c
+ to build (also missing in Win32).
+
+ * code/cgame/cgame.sh: added -DCGAME (see cgame.bat). Also
+ changed include path to ../q3_ui/ which is not in the Win32
+ batch file. Also added cg_syscalls.c to build (missing in
+ Win32).
+
+2000-12-01 Bernd Kreimeier <bk@lokigames.com>
+
+ * RC3: released as of sos001201 / Q3 1.27f
+
+ * code/unix/Makefile: more fixes with clean build. The
+ changes made fix the menu rendering for Q3 but not TA.
+ Ingame graphics still broken.
+
+ * code/game/game_ta.sh: created. Use game_ta.q3asm here.
+ * code/game/game.sh: no -DMISSIONPACK
+ * code/game/game_ta.q3asm: CR/LF, /.
+
+ * code/cgame/cgame_ta.sh: created. Use cgame_ta.q3asm here.
+ * code/cgame/cgame.sh: no -DMISSIONPACK. No cg_newdraw, ui_shared.
+ * code/cgame/cgame.q3asm: No cg_newdraw, ui_shared.
+ CR/LF, /, cg_newDraw, and the output path/name.
+
+ * code/q3_ui/q3_ui.q3asm: output to ui not q3_ui...
+
+ * code/cgame/cg_event.c: cg_singlePlayerActive used here.
+ TODO: guard by MISSIONPACK
+ * code/cgame/cg_local.h: named q3print_t enum. Cvar
+ cg_singlePlayerActive for both Q3 and TA.
+
+
+ * code/unix/Makefile: cleanly separate B/baseq3/ and
+ B/missionpack/ subtrees during build. While new and old
+ UI are in separate directories, the cgame/ and game/
+ are shared, with conditional -DMISSIONPACK compile
+ and different files includeds (cd_draw, cg_newdraw).
+ That means twice the number of targets (3 DLL's, 3 QVM's,
+ times two), and different build rules.
+ TODO: carefully check Win32 build for (other) conditionals
+ TODO: carefully check Win32 build for link lists
+
+ * CVS: ui/, code/ui, botfiles/ and subdirectories are added.
+ The code/macosx/ directory turned out to be a real pain that
+ had to be edited manually, throwing out CVS/ directories in
+ the tree that had been created by SOS as they are in id's
+ repository:
+ code/macosx/Client/CVS
+ code/macosx/Client/PBUserInfo/CVS
+ code/macosx/Client/Quake3.nib/CVS
+ code/macosx/Common/CVS
+ code/macosx/DedicatedServer/CVS
+ code/macosx/DedicatedServer/PBUserInfo/CVS
+ Now tagged
+ cvs tag id1-26y-loki001119
+ TODO: there are several new files not yet linked?
+
+ * ChangeLog: merged the Changelog from the bk00119 working
+ branch (initial Q3TA port) based on sos001119 snapshot. Also
+ merged the source tree with cvs-1.17.
+ In the ChangeLog below *** MISSIONPACK *** indicates work
+ that was done on the branch (code-sos/ prefix in files).
+ The cvs update of this will be tagged with
+ cvs tag id1-26y-loki001119
+ Use this tag to hunt for possible Linux fixes that got lost
+ (i.e. got dropped by id since id000516 and were thus not in
+ sos001119, but did not show in diff id000516 cvs1-17).
+ New directories in CVS: botfiles/, ui/.
+ Missing from SOS/Missionpack: SDK directories.
+ common, lcc, libs, q3asm, q3data, q3map, q3radiant.
+
+
+ * ssreport.txt: below.
+ Note: watch for files called "ssreport.txt", that's id ChangeLog.
+ * ui/ui_syscalls.asm: below.
+ * q3_ui/ui_syscalls.asm: below.
+ * game/g_syscalls.asm: below.
+ * cgame/cg_syscalls.asm: below.
+ * bspc/linux-i386.mak: below.
+ * bspc/lcc.mak: below.
+ * botlib/linux-i386.mak: below.
+ * botlib/lcc.mak: below.
+ * A3D/a3d_console_variables.txt: CR/LF issue (minimize diffs).
+
+ * CVS: the checked bk001119 work copy of the sos001119 initial
+ checkout (completed with everything in the SOS "Missionpack"
+ tree, i.e. botfiles/ and botfiles.* added), copied over the
+ cvs-1.17 checkout.
+ Note: in these cases, BEWARE ui -> q3_ui/ links, and different
+ ChangeLogs. Also "make clean" helps.
+
+ * unix/unix_net.c: below.
+ * unix/unix_main.c: below.
+ * unix/matha.s: below.
+ * unix/linux_qgl.c: below.
+ * unix/linux_glimp.c: see also linux_joystick.c.
+ * server/sv_client.c: below.
+ * renderer/tr_surface.c: below.
+ * renderer/qgl.h: below.
+ * qcommon/qcommon.h: below.
+ * qcommon/files.c: below.
+ * qcommon/common.c: below.
+ * q3_ui/ui_demo2.c: below.
+ * mac/mac_net.c: below.
+ * mac/mac_glimp2.c: below.
+ * game/surfaceflags.h: below.
+ * game/bg_lib.c: checked against id00516/cvs-1.17a diff.
+ * bspc/bspc.c: TH_AASToTetrahedrons call removed since id000516.
+ Note: our final compare of id000516 against cvs-1.17a, making sure
+ that all these differences are in bk001119 (initial Q3TA port).
+ If id branched the Q3TA base off before id000516 we might be screwed.
+ Note: I do not diff against bk000520, which had some minor changes
+ against id000516 (check VectorArrayNormalize, OTConfiguration), which
+ seem consistent with me taking a pre-id000516 source snapshot for that
+ working branch.
+
+2000-11-30 Bernd Kreimeier <bk@lokigames.com>
+
+ * TEST: compiled using the symbolic link ui/ -> q3_ui/.
+ Had to undo one CVS change, regarding
+ code/cgame/cg_syscalls.asm
+ code/game/g_syscalls.asm
+ code/q3_ui/ui_syscalls.asm
+ These files are neither generated by Win32 cgame.bat
+ nor cgame.sh (etc.), thus seemingly maintained by hand.
+ cvs tag pr1-17-loki001130b
+ should be used if somebody needs this 1.17 snapshot
+ (which, remember, is post-release, with additional fixes).
+ Later:
+ cvs tag pr1-17-loki001130c
+ includes the full ChangeLog (duh).
+
+ * CVS: up until cvs-1.17-001130, code/ui/ contained the
+ Q3 code for the UI QVM/DLL. In Q3TA, this code has been
+ moved to code/q3_ui/, while at the same time the new
+ (scripting driven) UI code for Q3TA was maintained in
+ code/ui/. To preserve the history of code/ui/, it has been
+ renamed to q3/ui/ in the CVSROOT.
+ Note: this will BREAK all cvs-1.17 and before checkouts.
+ To compile earlier versions, move or link q3_ui/ to ui/.
+ The code has been tagged
+ cvs tag pr1-17-loki001130
+ after the change.
+ DONE: remove code/*/vm/*.asm from CVSROOT
+ Note: this includes code/*/*.asm files (from *_syscalls.c).
+ These were originally tracked in CVS, but if we need
+ comparison of q3asm output or QVM files we can rely
+ on the Win32 and Linux SDK now. These files have been
+ physically removed from CVS now, followed by
+ cvs tag pr1-17-loki001130a
+
+2000-11-30 Bernd Kreimeier <bk@lokigames.com> *** MISSIONPACK ***
+
+ * RC2: new ZIP file (another 360M for convenience).
+
+ * SOS: new CVS module, Quake3_sos. This will be used to track
+ the unchanged SOS checkouts from id. As their repository
+ is read-only, and there is no estimate on when changes might
+ be backpropagated there, I will track their changes in a
+ separate module, and update our local Quake3 module
+ accordingly. This is effectively "tracking 3rd party"
+ w/o import and half-automated, forced mergers - in other
+ words, we now branch starting with our post-1.17 changes,
+ for the benefit of moving at all.
+ Baseline is a slightly changed PR-1.17 id000516 source dump
+ (essentially ui/ moved to q3_ui for continuity, and CR/LF etc.).
+ cvs import Quake3_sos id000516 pr1-17-win32
+ cvs import Quake3_sos sos001119 pr1-26-win32
+ cvs import Quake3_sos sos001120 pr1-26-win32-001120
+ cvs import Quake3_sos sos001121 pr1-26-win32-001121
+ cvs import Quake3_sos sos001122 pr1-26-win32-001122
+ cvs import Quake3_sos sos001122-demo pr1-26-win32-demo
+ This is about the 1.26w Team Arena Win32 demo release, give or
+ take a couple of lines. Has Q3_VERSION "Q3 Team Arena Demo 1.27b".
+ cvs import Quake3_sos sos001123 pr1-26-win32-001123
+ cvs import Quake3_sos sos001126 pr1-26-win32-001126
+ Now track id versions (see code/game/q_shared.h:Q3_VERSION)
+ cvs import Quake3_sos sos001128 pr1-27c-win32-001128
+ With 1.27d they switched from Demo to full version (RC1).
+ cvs import Quake3_sos sos001129 pr1-27d-win32-001129
+ cvs import Quake3_sos sos001130a pr1-27d-win32-001130a
+ Now switched to 1.27e. This import is done from the SOS
+ working directory.
+ cvs import Quake3_sos sos001130b pr1-27e-win32-001130b
+ Note: SoS created rwx attributes which are luckily fixed
+ automagically during import. It is also seemingly incapable
+ to compare files, and leave files that have not changed the
+ hell alone. I can't do cvs update due to the $..$ tags in
+ the original files (which CVS can't be told to ignore),
+ so I have to do import (creating a load of vendor tagged
+ branches), but at least cvsweb and cvs get the revisions
+ right.
+
+ * code-sos/unix/Makefile: added linux_joystick
+ * code-sos/unix/linux_local.h: match mac/ and win32/, for prototypes.
+
+ * code-sos/unix/linux_joystick.c: new file, code from linux_glimp.c
+ Note: decided to separate this, as (a) we might edit/extend
+ a lot, (b), it's not in the id tree, (c) it's not GL, (d)
+ there might be even more oddball devices. Anything that
+ cuts down on diffs.
+
+ * code-sos/unix/linux_glimp.c (Q_stristr): const return (cvs1.17).
+ Also (XLateKey): added more keyboard mappings (ASCII on
+ upper row digits) (cvs1.17). Added in the minimal joystick
+ hooks (cvars, function calls). Fixed joystick cvar naming
+ to match win32 (kept joystick_threshold).
+ TODO: joystick stubs for dedicated?
+
+ * CVS: I have to move up to 1.27d (data, Win32 networking).
+ With exception of linux_glimp.c (mostly joystick code),
+ all cvs1.17 changes should now be in the work snapshot
+ based on the first sos001119 we got from id. There are
+ also some additional changes in there already, thus I'll
+ move the (buggy) 1.26 snapshot into CVS before adding even
+ more differences.
+
+
+2000-11-29 Bernd Kreimeier <bk@lokigames.com> *** MISSIONPACK ***
+
+ * RC1: TeamArena_Q3A_RC1.zip. Source has moved from
+ Q3VERSION "Q3 Team Arena Demo 1.27c" to "Q3 1.27d" now.
+
+ * code-sos/qcommon/common.c: added Com_InitPushEvent(). Also
+ increased MAX_PUSHED_EVENTS to 256.
+ Note: this is another case of buffer memory not zero'ed.
+ Com_EventLoop, fixed evTime to evType in debug print.
+
+ * TEST: baseq3/
+ +set sv_pure 0 +set vm_game 0 +set in_mouse 0 +set developer 2
+ TODO: Team Arena in menu leads to RE_Shutdown(1) and locks
+ TODO: can't play game
+ TODO: shaders can't load *.tga, *.jpg files are there
+ TODO: DO_CC linking for DLL's, DO_SHLIB_CC only for export?
+ TODO: ERROR: Bad player movement angle
+ TODO: Warning: cvar "..." given initial values: "..." and "..."
+ TODO: TA demo ERROR: CL_ParseServerMessage: Illegible server message
+ TODO: WARNING: Com_PushEvent overflow
+
+ * code-sos/qcommon/files.c: add NULL filter for our Sys_ListFiles calls.
+ * unix/unix_shared.c (Sys_ListFiles): signature has changed,
+ additional Sys_ListFiles argument now.
+
+ * code-sos/unix/unix_net.c (Sys_GetPacket): see below (readcount=0).
+ * code-sos/unix/unix_main.c: see below (Mike's and my changes to DLL
+ loading, my event buffer clear fixes).
+ * code-sos/unix/linux_qgl.c (QGL_Init): see below (__FX__ guards).
+ TODO: abstract WGL/GLX and end unfortunate QGL duplication.
+ TODO: spice up QGL with Linux H2 full version.
+ * code-sos/q3_ui/ui_demo2.c: fix on demo names - no Q_strupr(demoname).
+ Note: in CVS this fix is in ui/ui_demo2.c. CVS is screwed by
+ id choosing the old name for new directory...
+ TODO: manual intervention on "ui goes q3_ui" in CVSROOT?
+ * renderer/qgl.h: see below (__FX__ guards).
+ * qcommon/files.c: migrated in the 1.17cvs changes against the
+ id000516 code dump, i.e. the (not marked - boo hiss) mkv changes.
+ Note: all the above is based on a diff of the last id code dump
+ pre-1.17 against our CVS, with those fixes now migrated into the
+ sos1.26 snapshot.
+ TODO: move in joystick code.
+ TODO: replace XAutoRepeatOn/Off with filter (focus).
+ TODO: DGA 2.0 and such.
+
+ * code-sos/game/q_shared.c: valid compare for NULL strings
+ * code-sos/unix/unix_main.c: QRTLD, and now using RTLD_NOW.
+ Note: it is a bad idea to load game DLL's that are missing symbols.
+
+ * code-sos/ui/ui_main.c: see below.
+ * code-sos/game/g_main.c: see below.
+ * code-sos/q3_ui/ui_main.c: see below.
+ * code-sos/cgame/cg_main.c: made cvarTable and cvarTableSize static. This resolved
+ a segfault related to traversing the UI table during Init.
+ Note: there is a segfault related to this variable being out of bounds.
+ Different struct size in global variables possible aliasing between the
+ DLL's.
+
+ * code-sos/unix/unix_main.c (Sys_Error): assert(0), no exit in debug.
+ * code-sos/game/q_shared.c: now aborts on NULL destination. Also DPrintf's
+ on bogus excess copies.
+ TODO: make all those string functions safe, at least assert.
+ * code-sos/server/sv_init.c: comment in SV_Init
+ // init the botlib here because we need the pre-compiler in the UI
+ Called in qcommon/common.c:Com_Init, were CL_Init is called afterwards...
+ * code-sos/server/sv_bot.c: the botlib_import is filled here.
+ * code-sos/unix/unix_main.c (Sys_GetBotLibAPI): RTLD_NOW. Which is for naught,
+ as this code is not used and has never been used. assert(0)
+
+ * code-sos/botlib/be_interface.c: botimport supposed to be set here.
+ * code-sos/botlib/l_memory.c: segfault with q3_ui/ DLL.
+ #1 0x80e23ec in GetMemory (size=35) at ..//botlib/l_memory.c:331
+ 331 ptr = botimport.GetMemory(size + sizeof(unsigned long int));
+ as botimport is completely NULL'ed.
+
+ * code-sos/q3_ui/q3_ui.sh: created from ui/ui.sh 1.17
+
+ * code-sos/q3_ui/q3_ui.q3asm: unfubared (CR/LF, / path).
+
+ * code-sos/unix/Makefile: added q3_ui/ make targets (basically
+ ui/ targets from CVS 1.17 Makefile for starters).
+
+ * code-sos/q3_ui/: this is the old UI code, which does not use
+ ../ui/menus.txt (see ui/ui_main.c). In other words,
+ the code in ui/ now has to be compiled or qvm'ed
+ for missionpack/, but to create the necessary DLL or
+ QVM modules for baseq3/ we need to use q3_ui/.
+
+
+2000-11-27 Bernd Kreimeier <bk@lokigames.com> *** MISSIONPACK ***
+
+ * code-sos/game/bg_lib.c: ld problem with a custom "tan(..)"
+ TODO: loooking forward to SIGFPE on this code base.
+
+ * code-sos/ui/ui_util.c: this file is empty.
+
+ * code-sos/ui/ui.sh: new files:
+ ui_shared.c
+ ui_util.c
+ Replaced by the /ui/*.menu files:
+ q3lcc: can't find `../ui_cdkey.c'
+ q3lcc: can't find `../ui_ingame.c'
+ etc.
+
+ * code-sos/cgame/cgame.q3asm: added cg_newdraw entry.
+ Also added ui_shared entry.
+ * cgame/cgame.sh: added cg_newdraw.c entry.
+ Also added ../ui/ui_shared.c entry.
+
+ * code-sos/cgame/cg_newdraw.c: renamed (was cg_newDraw.c mixed case).
+ Note: the infidels have taken over.
+
+ * cgame/cgame.sh: added -DMISSIONPACK.
+ Note: w/o, q3lcc complains
+ ../cg_event.c:204: undeclared identifier `cg_singlePlayerActive'
+ ../cg_event.c:204: left operand of . has incompatible type `int'
+ which indicates that this source does not compile w/o MISSIONPACK
+ anymore. The baseq3/pak4.pk3 file in the Q3TA snapshot archives
+ are dated
+ 284464 11-10-00 14:02 vm/cgame.qvm
+ 463940 11-14-00 14:47 vm/qagame.qvm
+ 271596 11-14-00 14:48 vm/ui.qvm
+ the code dump is from 11-19.
+ Note: Make does not abort on q3lcc complains
+
+ * code-sos/game/game.sh: also added ai_vcmd.c entry.
+
+ * code-sos/ui/ui.q3asm: fubared (below). In addition, this is
+ the only one to have a
+ -o "/tmp/quake3/missionpack/vm/ui"
+ line in it. Given that the other 2 QVM modules are
+ also dependend on -DMISSIONPACK, this seems a real mess.
+ For now using the same path as the other 3.
+ * code-sos/cgame/cgame.q3asm: below.
+ * code-sos/game/game.q3asm: fubared. Fixed CR/LF and \ in paths
+ again (read by q3asm called by game.sh called by make).
+ * unix/Makefile: updated fpor DLL/QVM.
+ Note: also shell scripts to use q3lcc not lcc.
+
+
+2000-11-27 Bernd Kreimeier <bk@lokigames.com>
+
+ * code/unix/Makefile: now expects a run/ directory
+ relative (between this, the Loki standards, and the
+ utility code in the same repository, it's ever so
+ slightly less dorky).
+ TODO: fix broken copyfiles target etc.pp.
+
+ * code/game/bg_lib.c: turns out the changes I
+ undid 001120 were affecting original Zoid
+ Linux port related defines, which break VM
+ compile. Mike fixed those (which I unfixed
+ when referring to the latest id code that does
+ not contain these patches). However, they
+ duplicate ANSI libc symbols, so the guards might
+ be wrong. The symbols are missing when compiling
+ for VM, so I now use the existing lcc -DQ3_VM
+ flag:
+ //#if !defined ( _MSC_VER ) && ! defined ( __linux__ )
+ #if defined ( Q3_VM )
+ This will break DLL compile on non-ANSI platforms,
+ which will have to be added to the conditional then.
+
+ * code/ui/ui.sh: below.
+ * code/game/game.sh: below.
+ * code/cgame/cgame.sh: Linux SDK installs q3lcc to
+ avoid collisions with regular lcc pre-installs. The
+ scripts fail with "lcc not found", but do not abort
+ the Makefile.
+ Note: now that VM code gets actually built, there
+ are errors:
+ g_main:648 ERROR: symbol vsprintf undefined
+ bg_pmove:1221 ERROR: symbol abs undefined
+ q_math:4309 ERROR: symbol fabs undefined
+ q_shared:2801 ERROR: symbol tolower undefined
+ q_shared:2862 ERROR: symbol toupper undefined
+ ai_dmq3:208 ERROR: symbol atoi undefined
+ ai_cmd:4951 ERROR: symbol sscanf undefined
+
+
+2000-11-20 Bernd Kreimeier <bk@lokigames.com>
+
+ * TEST: test compile of pr-1.17+cvs fixes segfaults due
+ to new baseq3/pak4.pk3
+ Note: to self ... 1.17 is not compatible with new files.
+ Checking into CVS next.
+
+ * code/: changes applied by us that are not in id's code base
+ affect q_shared.c (NULL in Q_stricmp), files.c (FIXME fs_cdpath,
+ Sys_ConcatenateFileList, ui_demo2.c (demo no tolower on linux).
+ In unix/ linux_glimp.c (joystick code), qgl.h, linux_qgl.c (__FX__),
+ unix_main.c (dlopen bug and event buffers), unix_net.c (readcount),
+ matha.s (assembly warning).
+
+ * code/server/sv_client.c (SV_WriteDownloadToClient):
+ No effective change on FS_SV_FOpenFileRead call, they reworked
+ autodownload some more seemingly.
+
+ * code/renderer/tr_surface.c: VectorArrayNormalize
+
+ * code/qcommon/qcommon.h: see below.
+ * code/qcommon/files.c: Com_ReadConfigs removed.
+ * code/qcommon/common.c: removed Com_ReadConfigs,
+ textual replacement of body in Com_Init.
+
+ * code/mac/mac_net.c: not applied (undone by id)
+ OTConfiguration *config <> OTConfigurationRef config
+
+ * code/mac/mac_glimp2.c: r_colorbits->integer > 16
+ * code/game/surfaceflags.h (CONTENTS_BOTCLIP): added.
+
+ * code/game/q_shared.h: not applied (undone by id)
+ #if defined(ppc) || defined(__ppc) || defined(__ppc__)
+ #define idppc 1
+ #else
+ #define idppc 0
+ #endif
+
+ * code/game/q_math.c: added another CPP line to guard
+ BoxOnPlaneSide, removed WIN32 guard.
+ TODO: this could be broken code guarded in all current
+ compiles...
+
+ * code/game/bg_lib.c: left Q#_VM guard for typedef cmp_t
+ Added !defined( __linux__ ) for tolower and atoi.
+ Note: the changes above relate to the very last code update
+ from id prior to the 6 month blackout, which were not in
+ CVS when Michael made his updates. Needed to establish the
+ baseline for the new patch. Source dump 1.17.00520, against
+ SOS 1.26w-001119 version.
+
+2000-11-20 Bernd Kreimeier <bk@lokigames.com> *** MISSIONPACK ***
+
+ * TEST: running against the data up to TeamArena_Q3A_001109.zip
+ Hunk_Clear: reset the hunk ok
+ Program received signal SIGBUS, Bus error.
+ "q3dm2", killBots==qtrue
+ #0 CM_ClearMap () at ..//qcommon/cm_load.c:644
+ #1 0x80884a7 in SV_Map_f () at ..//server/sv_ccmds.c:159
+ #2 0x8072579 in Cmd_ExecuteString (text=0xbffff4b0 "spmap q3dm2") at ..//qcommon/cmd.c:591
+ #3 0x8071dfe in Cbuf_Execute () at ..//qcommon/cmd.c:190
+ #4 0x80763f7 in Com_Frame () at ..//qcommon/common.c:2547
+ #5 0x8130d6b in main (argc=13, argv=0xbffff984) at ..//unix/unix_main.c:953
+ #6 0x40100cb3 in __libc_start_main (main=0x8130bc4 <main>
+ Not reproducible (screen stayed black).
+
+ * TEST: +set developer 1, same for Win32 and Linux:
+ Can't find gfx/misc/flare.tga
+ Can't find gfx/misc/sun.tga
+ Can't find gfx/misc/console02.tga
+ Can't find vm/ui.map
+ Can't find textures/sfx/logo512.tga
+ Can't find gfx/colors/black.tga
+ Can't find models/mapobjects/banner/banner5_2.md3
+ Can't find models/mapobjects/banner/banner5_1.md3
+ Can't find textures/sfx/firegorre2.tga
+ Can't find textures/sfx/bolts.tga
+ Can't find menu/art/unknownmap.tga
+
+ * Q3TA: after nearly 6 months, a code update from id. SOS access
+ even. Got it to compile, link and start, but its currently broken
+ (menu doesn't render in full, can't get into game etc.). Need
+ a baseline 1.17 to diff against. Last code dump was May 16, with
+ bspc code updated May 19. Checking working directory of bk000520
+ against CVS next (Mike's fixes never made it into id's codebase
+ or a post 1.17 release, neither did my fixes as released in the
+ point release version 1.17).
+
+2000-11-19 Bernd Kreimeier <bk@lokigames.com> *** MISSIONPACK ***
+
+ * TEST: Win32 install as tested with 1.26w. quake3.x86 (Q3A game)
+ Warning: cvar "r_uifullscreen" given initial values: "1" and "0"
+ Warning: cvar "r_inGameVideo" given initial values: "1" and "0"
+ ^3WARNING: sound/feedback/hit.wav is a 8 bit wav file
+ (on windows, sound/weapons/weapon_hover.wav is missing...)
+ Menu only partially displayed in TA and baseq3 play, menu itself
+ seems to work. Freetype?
+ WARNING: Com_PushEvent overflow
+
+ * code-sos/game/game.sh: not in SOS, moved in from CVS snapshot.
+
+ * code-sos/qcommon/common.c: conditional DEDICATED to get rid off
+ CL_ShutdownCGame/CL_ShutdownUI/CIN_CloseAllVideos.
+ Same for UI_usesUniqueCDKey: dedicated server does not
+ write CD key file.
+ TODO: check whether there is an unneeded "read CD key"
+ for dedicated server.
+
+ * code-sos/null/null_client.c (CL_ShutdownAll): added dummy.
+
+ * code-sos/unix/Makefile: server/sv_net_chan.o for dedicated server.
+
+ * code-sos/null/null_snddma.c: fixed S_RegisterSound signature.
+
+ * code-sos/client/snd_mix.c: snd_p, snd_linear_count, snd_out
+ can't be static, as used by unix/snd_mixa.s.
+
+ * code-sos/unix/Makefile: added to the executable target:
+ renderer/tr_font.c
+ client/cl_net_chan.c
+ server/sv_net_chan.c
+ Also added a lot of jc*.c files to build, to fix unresolved
+ symbol errors.
+ TODO: is there unused jpeg-6/jd*.o code linked in now?
+
+ * code-sos/ft2/smooth.c: includes ftgrays.c, ftsmooth.c
+
+ * code-sos/ft2/truetype.c: ttdriver.c, ttpload.c, ttgload.c, ttobjs.c.
+ Also (see ftoption.h) TT_CONFIG_OPTION_BYTECODE_INTERPRETER ttinterp.c
+
+ * code-sos/ft2/sfnt.c: includes ttload.c, ttcmap.c, sfobjs.c,
+ sfdriver.c. lso (see ftoption.h)
+ TT_CONFIG_OPTION_EMBEDDED_BITMAPS ttsbit.c
+ TT_CONFIG_OPTION_POSTSCRIPT_NAMES ttpost.c
+
+ * code-sos/ft2/ftbase.c: includes ftcalc.c, ftobjs.c, ftstream.c,
+ ftlist.c, ftoutln.c, ftextend.c, ftnames.c.
+
+ * code-sos/ft2/autohint.c: includes ahangles.c, ahglyph.c, ahglobal.c,
+ ahhint.c, ahmodule.c.
+
+ * code-sos/unix/Makefile: added ft2/ to client objects, took out
+ ftraster.c/ftrend1.c (see below), added -DFT_FLAT_COMPILE.
+ * ft2/ftsmooth.c: -DFT_FLAT_COMPILE required.
+ * ft2/raster1.c: -DFT_FLAT_COMPILE required.
+ Note: this includes ftraster.c/ftrend1.c.
+
+ * code-sos/qcommon/vm_x86.c: _ftol is missing, ftolPtr only defined
+ for Win32, but used in generic code. Workaround for now.
+ TODO: find good Linux ftol, or use old solution.
+
+ * SoS checkout. chown -R a+w * recode ibmpc:lat1 */*.h */*.c
+
+2000-06-30 Michael Vance <briraeos@lokigames.com>
+
+ * misc: Spoke with Leonardo about qvm mess.
+
+ * ui/ui.sh: Created to build much like the ui.bat script.
+
+ * ui/ui.q3asm: Use linux style paths.
+
+ * game/game.sh: Created to build much like the game.bat script.
+
+ * game/game.q3asm: Use linux style paths.
+
+ * cgame/cgame.sh: Created to build much like the cgame.bat script.
+
+ * cgame/cgame.q3asm: Use linux systel paths.
+
+ * unix/Makefile: Use the new .sh scripts to build the QVM files.
+
+ * lcc/etc/linux.c: Build .asm files instead of .s files.
+
+ * misc: QVMs now load properly, with minor glitches that should
+ hopefully be solvable. The new build scripts conflict with the
+ .asm files already in CVS, as the generated byte code is slightly
+ different in some cases.
+
+2000-06-29 Michael Vance <briareos@lokigames.com>
+
+ * lcc/makefile: Tweaked to automatically include the system
+ compiler's header location. Added an install directory.
+
+ * lcc/custom.mk: Added a build directory.
+
+ * lcc/etc/linux.c: Numerous small tweaks to make compiling the VM
+ code a much simpler task.
+
+ * q3asm/Makefile: Created.
+
+ * q3asm/q3asm.c: Fixed uninitialized variable in
+ HashString(). Fixed off by one in argument parsing.
+
+ * misc: Had Brian remove the Xmd.h include from glx.h so that we can
+ build Quake3 on XFree86 4.0 systems.
+
+ * wine: Attempted to build with lcc.exe and q3asm.exe using wine,
+ also did not work. This is in contrast to MikeP's .qvms, which
+ seem to work.
+
+2000-06-28 Michael Vance <briareos@lokigames.com>
+
+ * common/files.c: Fixed Mods menu behaviour.
+
+ * unix/linux_qgl.c: Guarded references to fxMesa.
+
+ * renderer/qgl.h: Guarded references to fxMesa.
+
+ * ui/ui_demo2.c: Don't convert filename to uppercase.
+
+2000-05-07 Bernd Kreimeier <bk@lokigames.com>
+
+ * common/cmdlib.c: windowism, not guarded. Added WIN32 around "ATOM a".
+
+ * q3map/Makefile: Linux Makefile.
+
+ * q3map/Makefile.irix: "makefile" in original code, Irix-only Makefile.
+ Just fixed some redundant TAB that GNU make despises about as much as I
+ despise GNU Make, and changed to a relative path.
+
+2000-05-01 Bernd Kreimeier <bk@lokigames.com>
+
+ * q3radiant/: updated with Q3Radiant198b3-src.zip.
+ Tagged (globally) as q3radiant-198b3.
+ Kept the old files
+ 3DFXCamWnd.h
+ 3DFXCamWnd.cpp
+ MainFrm2.cpp
+ New files
+ Shaders.h
+ misc/ (contributed special TGA resources, don't relly belong)
+ Removed:
+ pName
+ Changed filenames to previous case:
+ UNNAMED.MAP -> unnamed.map
+ RES/BMP0002.BMP -> RES/bmp00002.bmp
+ Changed:
+ changelog.txt -> ChangeLog
+
+2000-04-28 Bernd Kreimeier <bk@lokigames.com>
+
+ * CVS: bk000425 modified sources. This replaces the unix/ directory
+ which is not yet in id's SourceSafe. Two check-ins, due to minor
+ changes in an attempt to nail the Voodoo3 related crashes (driver
+ problems, not a Q3 issue). Undid some of the QFL changes for PI
+ and the log bug fix - put back in (TODO). Also includes:
+ * Quake3/code/botlib/be_aas_sample.c: single file update from Robert.
+
+ * CVS: id000423 code dumps (two of them). Applying Loki patches.
+ Tagged for the final version (all patches).
+
+ * CVS: id000422 code dump. This did not include the 1.16n fixes
+ used for Linux, and was the first dump for the 1.17 security fix
+ release.
+ Note: forgot to check in the ft2/ headers themselves, but they
+ are not used in the current codebase anyway. Are added in next
+ dump. Also there is use of CVS/CVS-like $Keyword$ patterns in
+ some files, and between their revisions and ours we fuck this up.
+ Also, id ZIP files create write protected sources, have to do
+ chmod -R a+w Quake3/ to work and overwrite files.
+
+ * CVS: bk000315 modified source. This version was the 1.16n release.
+ Note: the changes applied here are not in the subsequent code dumps
+ of id. If you want to compile the Linux version as released you
+ have to use bk-tagged versions until the patches are merged in by
+ Robert Duffy.
+
+ * CVS: id000314 engine code dump, same procedure as below, tag.
+ Note: this version added vm/ sudirectories with assembly files
+ for cgame, game, ui. CVS tag id000314.
+
+ * CVS: id000304 engine code dump. Now there is a problem, as CVS
+ was used in the Mac sources. Do
+ find . -name 'CVS' -exec rm -r {} \;
+ before cvs update, then tagged:
+ cvs -d /loki/cvsroot/ tag id000304 Quake3/
+
+ * CVS: checked in a source snapshot of the id00303 engine code
+ and the id0003029 tools code. The tool sources are not fully in
+ sync, and we have only partial source from earlier engine revisions.
+ The engine source marks where Loki took over from Dave Kirsch.
+ This snapshot (with all temporary and bogus files) is imported
+ and tagged using:
+ cvs -d /loki/cvsroot import Quake3 id000303 initial
+
+ Modules:
+ code: the Q3 engine code, including a jpeg-6/ copy
+ common: code shared by tools
+ libs: code shared by tools, inlcuding a jpeg6/ copy
+ q3asm: VM bytecode assembly
+ q3data: misc. Q3 data conversions
+ q3map: BSP builder
+ q3radiant: Win32 editor, as is
+ lcc: C compiler for q3asm
+
+ The sources have not been cleaned up, and binary files have not been
+ removed. The Q3Radiant code base might exhibit mixed case asmbiguities
+ in the future, and future source dumps might come from SourceForge
+ instead.
+
+2000-04-25 Bernd Kreimeier <bk@lokigames.com>
+
+ * q3code.id000425/unix/Makefile: relative path, relocatable.
+ Note: first code merge with id, finally :-).
+
+2000-04-24 Bernd Kreimeier <bk@lokigames.com>
+
+ * q3code.bk000422/unix/matha.s: in C(BoxOnPlaneSide)
+ the following line triggers assembler warning:
+ "missing prefix `*' in absolute indirect address, maybe misassembled!"
+ jmp Ljmptab(,%eax,4)
+
+
+ * q3code.bk000422/unix/Makefile (MOUNT_DIR): rember to change.
+ TODO: fix this bloody Makefile to be relocatable, damnit.
+
+ * q3code.bk000422/cgame/cg_event.c: applied JCash fix again
+ (see EV_EVENT_BITS below). Send e-mail to verify.
+
+ * q3code.bk000422/renderer/tr_image.c: "../jpeg-6/jpeglib.h" again.
+
+ * q3code.bk000422/: created from the id dump of today, lacking
+ all but one of my changes (sigh). Swapped unix/ competely, takes
+ care of 90%. Submitted all changes again to Robert...
+
+2000-04-19 Bernd Kreimeier <bk@lokigames.com>
+
+ * q3code.bk000315/unix/linux_glimp.c (GLimp_EndFrame):
+ QGL_EnableLogging( r_logFile->value ) doesn't work?
+
+ * q3code.bk000315/unix/linux_qgl.c: GLimp_LogNewFrame() is
+ obsolete. QGL_EnableLogging was out of sync with Win32 and
+ did not support the new framecounter decrement logic.
+
+2000-04-03 Bernd Kreimeier <bk@lokigames.com>
+
+ * q3code.bk000315/server/sv_snapshot.c: svs.nextSnapshotEntities
+ is a signed integer unconditionally incremented, which gets
+ negative and causes a segfaulting indexing an array. Added reset
+ to counter. Might fail if snapshot numbers are supposed to
+ monotonically increase.
+
+2000-04-02 Bernd Kreimeier <bk@lokigames.com>
+
+ * q3code.bk000315/client/cl_parse.c (CL_ParseServerMessage):
+ assert(0) on Illegible message (remember to +set in_mouse 0).
+ TODO: have to add a dump message function, it's unreadable.
+
+ * botlib/be_ai_goal.c (InitLevelItemHeap): loop counter -2
+ left -2 with uninitialized next, and -1 disconnected. Removed
+ redundant memset. There is an item alloc leak I suspect, as
+ max_levelitems 1024 merely delayed the overflow error.
+
+2000-04-01 Bernd Kreimeier <bk@lokigames.com>
+
+ * botlib/be_ai_goal.c (InitLevelItemHeap): still segfaults.
+ Not memsetting the entire item heap. As items are cleared
+ on return, that leaves only memory corruption?
+ Later: upped max_levelitems from 256 to 1024
+ Later: client dies on connect:
+ Error: CL_ParseServerMessage: Illegible server message 255
+
+
+2000-03-31 Bernd Kreimeier <bk@lokigames.com>
+
+ * botlib/be_ai_goal.c: initializing global vars.
+ Segfault in AllocLevelItem ()
+ at /home/bk/Games/Quake3/q3code/botlib/be_ai_goal.c:364
+ I suspect that the initial freelevelitems setting is at
+ the end of the list and eventually exposed.
+
+ * cgame/cg_event.c: according to Johmn Cash:
+ itemNum = (es->event & ~EV_EVENT_BITS) - EV_USE_ITEM0
+ Quote: "This causes itemNum to be invalid about half the time,
+ preventing any client side effect tied to the item from occurring."
+
+2000-03-06 Bernd Kreimeier <bk@lokigames.com>
+
+ * qcommon/common.c: set pushEvent buffer and indices
+ to zero in Com_Init().
+
+ * q3code/qcommon/qcommon.h: made SE_NONE (and for paranoia
+ also NA_BOT) explicitely set to zero.
+
+2000-02-27 Bernd Kreimeier <bk@lokigames.com>
+
+ * unix/Makefile: added dmalloc in an attempt to get on
+ the Z_Free bug. Futile. Despite stripping dmalloc debug
+ token down to essentials, I get a (seemingly bogus or
+ unrelated):
+ debug-malloc library: dumping program, fatal error
+ Error: possibly bad .c filename pointer (err 24)
+
+
+2000-02-26 Bernd Kreimeier <bk@lokigames.com>
+
+ * qcommon/common.c: various debug builts to isolate the
+ Z_Free bug. It reproducibly happens on some machines
+ with SE_PACKET, but the packets themselves look
+ thoroughly corrupted.
+
+2000-02-21 Bernd Kreimeier <bk@lokigames.com>
+
+ * qcommon/common.c (Com_EventLoop): possible problem
+ here, pointer does not get cleared.
+
+ * unix/linux_glimp.c (InitSig): no signal handler.
+ * common/common.c: dump in Com_Error for debug.
+
+2000-02-17 Bernd Kreimeier <bk@lokigames.com>
+
+ * q3code: new dump from Zoid. Repeat tr_image.c fix.
+
+ * unix/Makefile: added client/snd_adpcm.c (linkage errors).
+ Later: added entire JPDIR and rules, for tr_image.c.
+ Later: had to fix fules for game/ai_*.c files.
+ Later: removed ui/ui_quit.o (n/a)
+ Later: took out -mpentiumpro -march=pentiumpro
+
+ * renderer/tr_image.c: windowism in #include path (see below).
+ #include "..\jpeg-6\jpeglib.h"
+
+1999-12-27 Bernd Kreimeier <bk@lokigames.com>
+
+ * Alpha: tried a dedicated server compile. Segfaults in
+ ../qcommon/files.c:1682, a paksort function doing pointer
+ fiddling.
+
+ * Makefile.alpha: created.
+ Note: want to take the SDL/Setup autoconf ASAP.
+
+ * unix/unix_main.c: fixed __axp__ to __alpha__, guarded
+ _FPU_SETCW.
+
+ * qcommon/vm_alpha.c: dummy, created.
+ * qcommon/vm_null.c: dummy, created.
+
+1999-12-04 Bernd Kreimeier <bk@lokigames.com>
+
+ * renderer/tr_image.c: windowism in #include path.
+ #include "..\jpeg-6\jpeglib.h"
+
+ * Revision 1.11: from Zoid by e-mail.
+ Note: threw away my playground copy, starting with the
+ ZIP file. Zoid's using CVS now, but we can't remote
+ access it. Thus did the
+ "find . -name 'CVS' -exec rm -rf {} \;"
+ and then track it as 3rd party source by
+
+
+ * ChangeLog: created. Now starting to track Q3A source.
+
+--------- q3code log ---------------------------------------------
diff --git a/code/unix/Cons_gcc.pm b/code/unix/Cons_gcc.pm
new file mode 100755
index 0000000..1b24589
--- /dev/null
+++ b/code/unix/Cons_gcc.pm
@@ -0,0 +1,47 @@
+#
+# Some utilities to handle gcc compiler setup
+#
+
+package Cons_gcc;
+
+# pass the compiler name
+# returns an array, first element is 2 for 2.x 3 for 3.x, then full version, then machine info
+sub get_gcc_version
+{
+ my @ret;
+ my ($CC) = @_;
+ my $version=`$CC --version | head -1`;
+ chop($version);
+ my $machine=`$CC -dumpmachine`;
+ chop($machine);
+ if($version =~ '2\.[0-9]*\.[0-9]*')
+ {
+ push @ret, '2';
+ } else {
+ push @ret, '3';
+ }
+ push @ret, $version;
+ push @ret, $machine;
+ return @ret;
+}
+
+# http://ccache.samba.org/
+# check ccache existence and path
+# returns an array, first element 0 / 1, then path
+sub get_ccache
+{
+ my @ret;
+ $ccache_path=`which ccache`;
+ chop($ccache_path);
+ if(-x $ccache_path)
+ {
+ push @ret, '1';
+ push @ret, $ccache_path;
+ return @ret;
+ }
+ push @ret, '0';
+ return @ret;
+}
+
+# close package
+1;
diff --git a/code/unix/Conscript-client b/code/unix/Conscript-client
new file mode 100755
index 0000000..dc2e8b8
--- /dev/null
+++ b/code/unix/Conscript-client
@@ -0,0 +1,265 @@
+# full client build script
+
+Import qw( BASE_CFLAGS BASE_LDFLAGS INSTALL_DIR BUILD_DIR TARGETNAME CC CXX LINK );
+
+# splines
+$env_splines = new cons(
+ CC => $CC,
+ CXX => $CXX,
+ LINK => $LINK,
+ ENV => { PATH => $ENV{PATH}, HOME => $ENV{HOME} }
+ );
+
+@SPLINES_FILES = qw(
+ ../splines/math_angles.cpp
+ ../splines/math_matrix.cpp
+ ../splines/math_quaternion.cpp
+ ../splines/math_vector.cpp
+ ../splines/q_parse.cpp
+ ../splines/q_shared.cpp
+ ../splines/splines.cpp
+ ../splines/util_str.cpp
+ );
+$SPLINES_FILESREF = \@SPLINES_FILES;
+
+Library $env_splines 'splines', @$SPLINES_FILESREF;
+
+# botlib
+# FIXME TTimo
+# we already deal with botlib on dedicated target
+# the compilation options are a bit different but we could certainly rely on
+# the same Conscript and make things cleaner
+
+$env_botlib = new cons(
+ CC => $CC,
+ CXX => $CXX,
+ LINK => $LINK,
+ ENV => { PATH => $ENV{PATH}, HOME => $ENV{HOME} },
+ CFLAGS => $BASE_CFLAGS . '-DBOTLIB '
+);
+
+@BOTLIB_FILES = qw(
+ ../botlib/be_aas_bspq3.c
+ ../botlib/be_aas_cluster.c
+ ../botlib/be_aas_debug.c
+ ../botlib/be_aas_entity.c
+ ../botlib/be_aas_file.c
+ ../botlib/be_aas_main.c
+ ../botlib/be_aas_move.c
+ ../botlib/be_aas_optimize.c
+ ../botlib/be_aas_reach.c
+ ../botlib/be_aas_route.c
+ ../botlib/be_aas_routealt.c
+ ../botlib/be_aas_sample.c
+ ../botlib/be_ai_char.c
+ ../botlib/be_ai_chat.c
+ ../botlib/be_ai_gen.c
+ ../botlib/be_ai_goal.c
+ ../botlib/be_ai_move.c
+ ../botlib/be_ai_weap.c
+ ../botlib/be_ai_weight.c
+ ../botlib/be_ea.c
+ ../botlib/be_interface.c
+ ../botlib/l_crc.c
+ ../botlib/l_libvar.c
+ ../botlib/l_log.c
+ ../botlib/l_memory.c
+ ../botlib/l_precomp.c
+ ../botlib/l_script.c
+ ../botlib/l_struct.c
+);
+$BOTLIB_REF = \@BOTLIB_FILES;
+
+Library $env_botlib 'botlib', @$BOTLIB_REF;
+
+# jpeg
+# NOTE TTimo we might need this one on other targets
+$env_jpeglib = new cons(
+ CC => $CC,
+ CXX => $CXX,
+ LINK => $LINK,
+ ENV => { PATH => $ENV{PATH}, HOME => $ENV{HOME} },
+ CFLAGS => $BASE_CFLAGS
+ );
+
+@JPEGLIB_FILES = qw(
+ ../jpeg-6/jcapimin.c
+ ../jpeg-6/jchuff.c
+ ../jpeg-6/jcinit.c
+ ../jpeg-6/jccoefct.c
+ ../jpeg-6/jccolor.c
+ ../jpeg-6/jfdctflt.c
+ ../jpeg-6/jcdctmgr.c
+ ../jpeg-6/jcphuff.c
+ ../jpeg-6/jcmainct.c
+ ../jpeg-6/jcmarker.c
+ ../jpeg-6/jcmaster.c
+ ../jpeg-6/jcomapi.c
+ ../jpeg-6/jcparam.c
+ ../jpeg-6/jcprepct.c
+ ../jpeg-6/jcsample.c
+ ../jpeg-6/jdapimin.c
+ ../jpeg-6/jdapistd.c
+ ../jpeg-6/jdatasrc.c
+ ../jpeg-6/jdcoefct.c
+ ../jpeg-6/jdcolor.c
+ ../jpeg-6/jddctmgr.c
+ ../jpeg-6/jdhuff.c
+ ../jpeg-6/jdinput.c
+ ../jpeg-6/jdmainct.c
+ ../jpeg-6/jdmarker.c
+ ../jpeg-6/jdmaster.c
+ ../jpeg-6/jdpostct.c
+ ../jpeg-6/jdsample.c
+ ../jpeg-6/jdtrans.c
+ ../jpeg-6/jerror.c
+ ../jpeg-6/jidctflt.c
+ ../jpeg-6/jmemmgr.c
+ ../jpeg-6/jmemnobs.c
+ ../jpeg-6/jutils.c
+ );
+$JPEGLIB_REF = \@JPEGLIB_FILES;
+
+Library $env_jpeglib 'jpeglib', @$JPEGLIB_REF;
+
+# NOTE TTimo this requires patched cons version to work (see unix/cons)
+%nasm_hash = new cons()->copy(
+ CC => 'nasm',
+ CCCOM => '%CC -f elf -o %> %<'
+);
+$nasm_hash{SUFMAP}{'.nasm'} = 'build::command::cc';
+$nasm_env = new cons(%nasm_hash);
+
+Library $nasm_env 'asmlib', 'ftol.nasm', 'snapvector.nasm';
+
+# compiling files with inlined assembly
+$env_inlined = new cons(
+ CFLAGS => '-DELF -x assembler-with-cpp'
+ );
+
+Library $env_inlined 'inlinelib', '../unix/matha.s', '../unix/snd_mixa.s';
+
+# putting it all together
+
+$env = new cons(
+ CC => $CC,
+ CXX => $CXX,
+ LINK => $LINK,
+ ENV => { PATH => $ENV{PATH}, HOME => $ENV{HOME} },
+ CFLAGS => $BASE_CFLAGS,
+ LIBS => ' ' . $BUILD_DIR . '/unix/splines.a '
+ . $BUILD_DIR . '/unix/botlib.a '
+ . $BUILD_DIR . '/unix/jpeglib.a '
+ . $BUILD_DIR . '/unix/asmlib.a '
+ . $BUILD_DIR . '/unix/inlinelib.a '
+ . $BASE_LDFLAGS
+ . '-L/usr/X11R6/lib -lX11 -lXext -lXxf86dga -lXxf86vm -ldl -lm'
+);
+
+@RENDERER_FILES = qw(
+ ../renderer/tr_animation.c
+ ../renderer/tr_backend.c
+ ../renderer/tr_bsp.c
+ ../renderer/tr_cmds.c
+ ../renderer/tr_curve.c
+ ../renderer/tr_flares.c
+ ../renderer/tr_font.c
+ ../renderer/tr_image.c
+ ../renderer/tr_init.c
+ ../renderer/tr_light.c
+ ../renderer/tr_main.c
+ ../renderer/tr_marks.c
+ ../renderer/tr_mesh.c
+ ../renderer/tr_model.c
+ ../renderer/tr_noise.c
+ ../renderer/tr_scene.c
+ ../renderer/tr_shade.c
+ ../renderer/tr_shade_calc.c
+ ../renderer/tr_shader.c
+ ../renderer/tr_shadows.c
+ ../renderer/tr_sky.c
+ ../renderer/tr_surface.c
+ ../renderer/tr_world.c
+ );
+$RENDERER_REF = \@RENDERER_FILES;
+
+@CLIENT_FILES = qw(
+ ../client/cl_cgame.c
+ ../client/cl_cin.c
+ ../client/cl_console.c
+ ../client/cl_input.c
+ ../client/cl_keys.c
+ ../client/cl_main.c
+ ../client/cl_net_chan.c
+ ../client/cl_parse.c
+ ../client/cl_scrn.c
+ ../client/cl_ui.c
+ );
+$CLIENT_REF = \@CLIENT_FILES;
+
+@COMMON_FILES = qw(
+ ../qcommon/cm_load.c
+ ../qcommon/cm_patch.c
+ ../qcommon/cm_polylib.c
+ ../qcommon/cm_test.c
+ ../qcommon/cm_trace.c
+ ../qcommon/cmd.c
+ ../qcommon/common.c
+ ../qcommon/cvar.c
+ ../qcommon/files.c
+ ../qcommon/md4.c
+ ../qcommon/msg.c
+ ../qcommon/net_chan.c
+ ../qcommon/huffman.c
+ ../qcommon/unzip.c
+ );
+$COMMON_REF = \@COMMON_FILES;
+
+@SOUND_FILES = qw(
+ ../client/snd_adpcm.c
+ ../client/snd_dma.c
+ ../client/snd_mem.c
+ ../client/snd_mix.c
+ ../client/snd_wavelet.c
+ );
+$SOUND_REF = \@SOUND_FILES;
+
+@UNIX_FILES = qw(
+ ../unix/unix_main.c
+ ../unix/unix_net.c
+ ../unix/unix_shared.c
+ ../unix/linux_common.c
+ ../unix/linux_qgl.c
+ ../unix/linux_glimp.c
+ ../unix/linux_joystick.c
+ ../unix/linux_snd.c
+ ../unix/linux_signals.c
+ );
+$UNIX_REF = \@UNIX_FILES;
+
+@SERVER_FILES = qw(
+ ../server/sv_bot.c
+ ../server/sv_ccmds.c
+ ../server/sv_client.c
+ ../server/sv_game.c
+ ../server/sv_init.c
+ ../server/sv_main.c
+ ../server/sv_net_chan.c
+ ../server/sv_snapshot.c
+ ../server/sv_world.c
+ );
+$SERVER_REF = \@SERVER_FILES;
+
+# FIXME TTimo vm_<cpu>.c
+@VM_FILES = qw(
+ ../qcommon/vm.c
+ ../qcommon/vm_x86.c
+ ../qcommon/vm_interpreted.c
+ );
+$VM_REF = \@VM_FILES;
+
+# FIXME: import the CPU string to build the name of the target
+Program $env $TARGETNAME, '../game/q_shared.c', '../game/q_math.c',
+ @$RENDERER_REF, @$CLIENT_REF, @$COMMON_REF, @$SOUND_REF,
+ @$UNIX_REF, @$SERVER_REF, @$VM_REF;
+Install $env $INSTALL_DIR, $TARGETNAME;
diff --git a/code/unix/Conscript-dedicated b/code/unix/Conscript-dedicated
new file mode 100755
index 0000000..1401760
--- /dev/null
+++ b/code/unix/Conscript-dedicated
@@ -0,0 +1,115 @@
+# dedicated server build script
+
+Import qw( BASE_CFLAGS BUILD_DIR INSTALL_DIR CC CXX LINK );
+
+$DEDICATED_NAME = 'linuxq3ded';
+
+$env_botlib = new cons(
+ CC => $CC,
+ CXX => $CXX,
+ LINK => $LINK,
+ ENV => { PATH => $ENV{PATH}, HOME => $ENV{HOME} },
+ CFLAGS => $BASE_CFLAGS . '-DBOTLIB '
+);
+
+@BOTLIB_FILES = qw(
+ ../botlib/be_aas_bspq3.c
+ ../botlib/be_aas_cluster.c
+ ../botlib/be_aas_debug.c
+ ../botlib/be_aas_entity.c
+ ../botlib/be_aas_file.c
+ ../botlib/be_aas_main.c
+ ../botlib/be_aas_move.c
+ ../botlib/be_aas_optimize.c
+ ../botlib/be_aas_reach.c
+ ../botlib/be_aas_route.c
+ ../botlib/be_aas_routealt.c
+ ../botlib/be_aas_sample.c
+ ../botlib/be_ai_char.c
+ ../botlib/be_ai_chat.c
+ ../botlib/be_ai_gen.c
+ ../botlib/be_ai_goal.c
+ ../botlib/be_ai_move.c
+ ../botlib/be_ai_weap.c
+ ../botlib/be_ai_weight.c
+ ../botlib/be_ea.c
+ ../botlib/be_interface.c
+ ../botlib/l_crc.c
+ ../botlib/l_libvar.c
+ ../botlib/l_log.c
+ ../botlib/l_memory.c
+ ../botlib/l_precomp.c
+ ../botlib/l_script.c
+ ../botlib/l_struct.c
+);
+$BOTLIB_REF = \@BOTLIB_FILES;
+
+Library $env_botlib 'botlib', @$BOTLIB_REF;
+
+# NOTE TTimo this requires patched cons version to work (see unix/cons)
+%nasm_hash = new cons()->copy(
+ CC => 'nasm',
+ CCCOM => '%CC -f elf -o %> %<'
+);
+$nasm_hash{SUFMAP}{'.nasm'} = 'build::command::cc';
+$nasm_env = new cons(%nasm_hash);
+
+Library $nasm_env 'asmlib', 'ftol.nasm', 'snapvector.nasm';
+
+$env = new cons(
+ CC => $CC,
+ CXX => $CXX,
+ LINK => $LINK,
+ ENV => { PATH => $ENV{PATH}, HOME => $ENV{HOME} },
+ # FIXME TTimo I'm not sure about what C_ONLY is for
+ CFLAGS => $BASE_CFLAGS . '-DC_ONLY',
+ LDFLAGS => '-ldl -lm',
+ LIBS => ' '
+ . $BUILD_DIR . '/unix/botlib.a '
+ . $BUILD_DIR . '/unix/asmlib.a '
+);
+
+# list the files for the dedicated server
+@FILES = qw(
+ ../null/null_client.c
+ ../null/null_input.c
+ ../null/null_snddma.c
+ ../server/sv_bot.c
+ ../server/sv_ccmds.c
+ ../server/sv_client.c
+ ../server/sv_game.c
+ ../server/sv_init.c
+ ../server/sv_main.c
+ ../server/sv_net_chan.c
+ ../server/sv_snapshot.c
+ ../server/sv_world.c
+ ../qcommon/cm_load.c
+ ../qcommon/cm_patch.c
+ ../qcommon/cm_polylib.c
+ ../qcommon/cm_test.c
+ ../qcommon/cm_trace.c
+ ../qcommon/cmd.c
+ ../qcommon/common.c
+ ../qcommon/cvar.c
+ ../qcommon/files.c
+ ../qcommon/huffman.c
+ ../qcommon/md4.c
+ ../qcommon/msg.c
+ ../qcommon/net_chan.c
+ ../qcommon/unzip.c
+ ../qcommon/vm.c
+ ../qcommon/vm_interpreted.c
+ ../game/q_math.c
+ ../game/q_shared.c
+ ../unix/linux_common.c
+ ../unix/unix_main.c
+ ../unix/unix_net.c
+ ../unix/unix_shared.c
+ ../unix/linux_signals.c
+ );
+$FILESREF = \@FILES;
+
+# DEDICATED_NAME is imported, holds the name of the target
+# wolfded.x86 usually
+Program $env $DEDICATED_NAME, '../qcommon/vm_x86.c', @$FILESREF;
+Install $env $INSTALL_DIR, $DEDICATED_NAME;
diff --git a/code/unix/Conscript-pk3 b/code/unix/Conscript-pk3
new file mode 100755
index 0000000..9dcf691
--- /dev/null
+++ b/code/unix/Conscript-pk3
@@ -0,0 +1,135 @@
+# build pk3 on the fly
+
+Import qw( INSTALL_DIR BUILD_DIR CONFIG_DIR CC CXX LINK );
+
+use Data::Dumper;
+
+$env = new cons(); # the env on which we will be working for all pk3s (NOTE: maybe we need several ctually)
+
+$hcf_do_exec = 1;
+sub do_command($)
+{
+ printf("@_[0]\n");
+ if ($hcf_do_exec)
+ {
+ system("@_[0]");
+ }
+}
+
+sub build_pk3 {
+
+ sub launch {
+ #print "In launch\n";
+ $Data::Dumper::Indent = 2;
+ #print Dumper(@_);
+ $tmpdir = "/tmp/pk3-builder$$";
+ do_command("rm -rf $tmpdir");
+
+ ($target, $sets) = @_;
+ $base=`basename $target`; chomp($base);
+ $dirname=`dirname $target`; chomp($dirname);
+
+ foreach (@{$sets})
+ {
+ ($sourcepath, $destpath, $file) = @{$_};
+ #print "source: $sourcepath dest: $destpath file: $file\n";
+ do_command("mkdir -p $tmpdir/$destpath");
+ if ($sourcepath =~ /#.*/)
+ {
+ #print "$sourcepath is absolute\n";
+ $sourcepath =~ s/#//;
+ if (ref($file))
+ {
+ foreach(@{$file})
+ {
+ do_command("cp $sourcepath/$_ $tmpdir/$destpath/$_");
+ }
+ }
+ else
+ {
+ do_command("cp $sourcepath/$file $tmpdir/$destpath/$file");
+ }
+ }
+ else
+ {
+ #print "$sourcepath in linked dir\n";
+ if (ref($file))
+ {
+ foreach(@{$file})
+ {
+ do_command("cp $BUILD_DIR/$sourcepath/$_ $tmpdir/$destpath/$_");
+ }
+ }
+ else
+ {
+ do_command("cp $BUILD_DIR/$sourcepath/$file $tmpdir/$destpath/$file");
+ }
+ }
+ }
+
+ do_command("cd $tmpdir ; zip -r $base *");
+ do_command("mkdir -p $BUILD_DIR/$dirname");
+ do_command("cp $tmpdir/$base $BUILD_DIR/$target");
+ do_command("rm -rf $tmpdir");
+
+ return 1;
+ }
+
+ # extract the parameters
+ ($target, $sets) = @_;
+
+ $base=`basename $target`; chomp($base);
+ $dirname=`dirname $target`; chomp($dirname);
+
+ # the build command is stored and called later on by cons
+ # this makes it impossible to have several build_pk3 working together
+ # there is probably a cleaner solution than this hack, but this works
+ $target_uniquename="target_$base";
+ $target_uniquename=~s/\.//g;
+ eval("\$$target_uniquename=\$target");
+ $sets_uniquename="sets_$base";
+ $sets_uniquename=~s/\.//g;
+ eval("\$$sets_uniquename=\$sets");
+ #print "name: $target_uniquename after the hack: $target_pak8pk3";
+
+ # don't pass @{@_} .. since this will be called during the process
+ $command = "[perl] &launch( \$$target_uniquename, [ \@{\$$sets_uniquename} ] )";
+ #print "$command\n";
+
+ foreach(@{$sets})
+ {
+ ($sourcepath, $destpath, $file) = @{$_};
+ if (ref($file))
+ {
+ foreach(@{$file})
+ {
+ Depends $env $target, $sourcepath . '/' . $_;
+ }
+ }
+ else
+ {
+ Depends $env $target, $sourcepath . '/' . $file;
+ }
+ }
+ Command $env $target, $command;
+ Install $env $INSTALL_DIR . "/$dirname", $target;
+}
+
+# quick rundown on the syntax:
+# <target file>, [ <fileset1>, <fileset2>, ... ]
+# where <fileset>: [ <source directory>, <directory in zip>, <file1>, <file2>, .. ]
+
+build_pk3('baseq3/pak8.pk3',
+ [ [ '#../../../media/Q3Media-1.32/baseq3/menu/art', 'menu/art', 'pblogo.tga' ],
+ [ '../Q3/q3_ui/q3_ui', 'vm', 'ui.qvm' ],
+ [ '../Q3/cgame/cgame', 'vm', 'cgame.qvm' ],
+ [ '../Q3/game/game', 'vm', 'qagame.qvm' ] ]
+);
+
+build_pk3('missionpack/pak3.pk3',
+ [ [ '#../ui', 'ui', [ 'createserver.menu', 'joinserver.menu', 'filter.menu', 'punkbuster.menu', 'menus.txt' ] ],
+ [ '../TA/ui/ui', 'vm', 'ui.qvm' ],
+ [ '../TA/cgame/cgame', 'vm', 'cgame.qvm' ],
+ [ '../TA/game/game', 'vm', 'qagame.qvm' ],
+ [ '#../../../media/Q3Media-1.32/missionpack/scripts', 'scripts', 'models2.shader' ] ]
+);
diff --git a/code/unix/Conscript-sdk b/code/unix/Conscript-sdk
new file mode 100755
index 0000000..b2a5e23
--- /dev/null
+++ b/code/unix/Conscript-sdk
@@ -0,0 +1,122 @@
+# sdk
+
+Import qw( SDK_NAME Q3_VER CC CXX LINK );
+
+# http://www.devdaily.com/perl/edu/articles/pl010005/pl010005.shtml
+#----------------------------( promptUser )-----------------------------#
+# #
+# FUNCTION: promptUser #
+# #
+# PURPOSE: Prompt the user for some type of input, and return the #
+# input back to the calling program. #
+# #
+# ARGS: $promptString - what you want to prompt the user with #
+# $defaultValue - (optional) a default value for the prompt #
+# #
+#-------------------------------------------------------------------------#
+
+sub promptUser {
+
+ #-------------------------------------------------------------------#
+ # two possible input arguments - $promptString, and $defaultValue #
+ # make the input arguments local variables. #
+ #-------------------------------------------------------------------#
+
+ local($promptString,$defaultValue) = @_;
+
+ #-------------------------------------------------------------------#
+ # if there is a default value, use the first print statement; if #
+ # no default is provided, print the second string. #
+ #-------------------------------------------------------------------#
+
+ if ($defaultValue) {
+ print $promptString, "[", $defaultValue, "]: ";
+ } else {
+ print $promptString, ": ";
+ }
+
+ $| = 1; # force a flush after our print
+ $_ = <STDIN>; # get the input from STDIN (presumably the keyboard)
+
+
+ #------------------------------------------------------------------#
+ # remove the newline character from the end of the input the user #
+ # gave us. #
+ #------------------------------------------------------------------#
+
+ chomp;
+
+ #-----------------------------------------------------------------#
+ # if we had a $default value, and the user gave us input, then #
+ # return the input; if we had a default, and they gave us no #
+ # no input, return the $defaultValue. #
+ # #
+ # if we did not have a default value, then just return whatever #
+ # the user gave us. if they just hit the <enter> key, #
+ # the calling routine will have to deal with that. #
+ #-----------------------------------------------------------------#
+
+ if ("$defaultValue") {
+ return $_ ? $_ : $defaultValue; # return $_ if it has a value
+ } else {
+ return $_;
+ }
+}
+
+sub launch {
+
+ print("Building MOD SDK (version $Q3_VER)\n");
+ print("Before building the mod sdk, your CVS tree must be completely clean!\nIf there are some temporary files and binaries in the tree, they can get included in the distribution and cause problems.\n");
+ $ok = &promptUser("Ready to build mod sdk [y/n]? ");
+ if ($ok ne 'y')
+ {
+ print("aborting\n");
+ return 0;
+ }
+ # create the dirs:
+ $RAW_DATA = "mod-sdk-$Q3_VER";
+ system("rm -rf $RAW_DATA ; mkdir -p $RAW_DATA/code");
+ # actual code
+ system("cp -R cgame game q3_ui ui $RAW_DATA/code");
+ # UI stuff
+ system("cp -R ../ui $RAW_DATA");
+ # tools
+ system("cp -R ../lcc ../q3asm $RAW_DATA");
+ # build scripts
+ system("cp Construct $RAW_DATA/code");
+ system("mkdir $RAW_DATA/code/unix ; cp unix/cons unix/pcons-2.3.1 unix/Conscript-pk3 $RAW_DATA/code/unix");
+ system("cp unix/mod-sdk-data/Makefile $RAW_DATA/code/");
+ # cleanup some stuff
+ system("find $RAW_DATA -name CVS -exec rm -rf {} \\; 2>/dev/null");
+ # test that the build works just fine
+ $host=`hostname`; chomp($host);
+ if ($host ne 'antares')
+ {
+ system("rm -rf /tmp/$RAW_DATA ; cp -R $RAW_DATA /tmp");
+ system("cd /tmp/$RAW_DATA/code ; make");
+ if ($? ne 0)
+ {
+ printf("ERROR: test build failed\n");
+ return 0;
+ }
+ printf("build test successful\n");
+ }
+ # make a setup out of this
+ system("cp -R unix/setup/setup.sh unix/setup/setup.data $RAW_DATA");
+ # TODO: splash!
+ system("cp unix/mod-sdk-data/setup.xml unix/mod-sdk-data/config.sh unix/mod-sdk-data/postinstall.sh $RAW_DATA/setup.data");
+ # mod-sdk-data/Q3A_EULA.txt is a copy of stuff that is usually in $Q3SETUPMEDIA .. can't be arsed
+ system("cp unix/mod-sdk-data/Q3A_EULA.txt $RAW_DATA");
+ # I love those dirty hacks
+ system("cd $RAW_DATA/setup.data/bin ; ln -s Linux FreeBSD ; ln -s Linux OpenBSD ; ln -s Linux NetBSD");
+ # cleanup some stuff
+ system("find $RAW_DATA -name CVS -exec rm -rf {} \\; 2>/dev/null");
+ # weeee
+ system("unix/mod-sdk-data/makeself/makeself.sh $RAW_DATA $SDK_NAME \"Quake III Arena mod SDK\" ./setup.sh $Q3_VER");
+ return 1;
+}
+
+print("in Conscript-sdk\n");
+
+$env = new cons();
+Command $env "$SDK_NAME", "[perl] &launch()";
diff --git a/code/unix/Conscript-setup b/code/unix/Conscript-setup
new file mode 100755
index 0000000..ef70703
--- /dev/null
+++ b/code/unix/Conscript-setup
@@ -0,0 +1,33 @@
+# setup
+
+Import qw( INSTALL_BASEDIR );
+
+$env = new cons(
+ # add this path so setup script finds brandelf
+ ENV => { PATH => $ENV{PATH} . ":" . $ENV{HOME} . "./usr/bin", },
+);
+
+sub launch {
+ # need to get the correct version (i.e. from SP source)
+ $version = `cat game/q_shared.h | grep Q3_VERSION`;
+ chomp $version;
+ $version =~ s/.*Q3\ (.*)\"/$1/;
+ print("version: $version\n");
+ system("cd unix ; ./build_setup.sh $version");
+
+ return 1;
+}
+
+# no dependency to PB, we get it directly from the tree and not in install/
+Depends $env "$INSTALL_BASEDIR/foo",
+ "$INSTALL_BASEDIR/linuxq3ded",
+ "$INSTALL_BASEDIR/linuxquake3-smp",
+ "$INSTALL_BASEDIR/linuxquake3";
+ # during developement phase, we generate and copy the pk3 on the fly
+ # then those should move to the media tree
+# those have been finalized and moved to the media tree
+# "$INSTALL_BASEDIR/baseq3/pak8.pk3",
+# "$INSTALL_BASEDIR/missionpack/pak3.pk3";
+
+
+Command $env "$INSTALL_BASEDIR/foo", "[perl] &launch()";
diff --git a/code/unix/LinuxSupport/CHANGES-1.32.txt b/code/unix/LinuxSupport/CHANGES-1.32.txt
new file mode 100755
index 0000000..86577af
--- /dev/null
+++ b/code/unix/LinuxSupport/CHANGES-1.32.txt
@@ -0,0 +1,150 @@
+CHANGES 1.32
+
+11/13/2002 - 1.32b
+
+Update to the Linux client, fixing a number of issues:
+
+
+- Text mode install broken on glibc 2.3 (Debian Sid)
+http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=165358
+Current Debian Sid's glibc package break backwards compatibility
+with binaries compiled on older glibc and statically linked.
+This will cause the text mode setup to segfault.
+
+For now you can either:
+ - find a solution to run the graphical gtk-based setup
+ - roll back to glibc 2.2
+ - use an updated setup binary:
+ run the linux setup once, with the --keep option
+ (this will exand all the files to setup.tmp/)
+ get this updated setup file:
+ http://zerowing.idsoftware.com/linux/165358/setup
+ replace setup.tmp/setup.data/bin/Linux/x86/setup by the new one
+ cd to setup.tmp/ and run setup.sh
+
+
+- Current NVidia drivers don't officially support glibc 2.3 systems
+This affects Debian Sid in particular, causing crashes during vid_restart
+The issue is related to the SMP build depending upon libpthreads
+1.32b has both SMP and non-SMP binary. Use quake3-smp to launch
+the SMP version if you want to use it.
+
+
+- SMP and non-SMP builds:
+Default quake3 shortcut will spawn a non-SMP build. Use quake3-smp
+for an SMP-enabled run. From the feedback we got after the 1.32 release,
+the SMP support as designed in the Quake III Arena technology isn't so
+much relevant anymore. It was designed for much lower CPU frequencies
+and lower AGP throughputs. Modern systems won't benefit from SMP. Since
+it didn't make much sense to remove the SMP binary, we have both now.
+
+
+- Fixing broken mouse on Suse:
+Starting with XFree 4.2, the event timestamps returned by the X server
+are no longer matching gettimeofday. And there is currently no API in X
+to provide easy synchronisation. 1.32 introduced improved event timing
+by correcting event time with X server event timestamp (sub-frame timing).
+This worked fine with XFree 4.1, and no longer does. 1.32b adds a safe
+check to work again with XFree 4.2, but basically the input timing is
+back to 1.31 quality.
+
+Some new cvars related to the mouse control:
+in_dgamouse - not new, but be sure to have it set to 1 on any recent system
+in_subframe - completely disables sub-frame timing. If XFree 4.2
+ in_subframe 1 won't hurt, but it won't do anything either.
+in_nograb - for mod developers. Set to 1 and run windowed, Q3 won't be
+ grabbing your mouse pointer (useful for debug breaks)
+
+
+8/26/2002
+
+General:
+
+- new network protocol, 68
+
+- network code:
+ improved fragmented messages handling
+ map change while client loads map no longer causes an 'Invalid .PK3' error
+ map_restart while client loads map no longer causes a reload
+ fixing donedl being ignored after autodl if map_restart'ed
+- the demo command has a list of compatible protocols, it will loop through 66 67 68
+ you can do '/demo four' and it will try four.dm_66 four.dm_67 four.dm_68
+ or you can explicitely give a '/demo demoname.dm_??'
+
+- added mousewheel support in the console:
+ wheel to scroll, ctrl+wheel to scroll faster, shift+wheel to scroll history
+
+- UI in baseq3/ and missionpack/ for PunkBuster configuration
+ punkbuster server in server creation dialog (sv_punkbuster)
+ punkbuster client in server browser (cl_punkbuster)
+ added PB Yes/No to the browsers
+- removed obsolete MPlayer UI stuff
+- bumped server browser to handle up to 4096 servers
+
+- IP maintained in userinfo
+- cl_guid in userinfo (as part of PB integration)
+- printing ports as unsigned ints, no longer printing negative port numbers
+- cleaned up the legacy IP banning code
+ use * for IP pattern matching now instead of 0 (fixes some confusion)
+ ex: 192.246.12.*
+ made it safe from overflowing and crashing
+ NOTE: using PunkBuster's banning system is advised instead though
+- rcon: some fixes to the buffering to avoid overflowing and dropping parts of the message
+- rcon: now supports quoting /rcon g_motd "foo bar"
+- added SVF_CLIENTMASK (0x00000002), works only with <= 32 players
+ set bitmask of players to which send entity
+- pushed cl_maxpackets upper limit to 125
+- added [skipnotify] from RTCW, use to display in the console only, but not on client screen
+ (also fixes pb_msgprefix and pb_sv_msgprefix)
+
+- new cvar sv_lanForceRate (defaults 1):
+ forces LAN clients to the maximum rate instead of accepting client setting
+ (1 is the default behaviour, backward compatible)
+
+- new cvar sv_strictAuth (defaults 1):
+ server side variable to control wether strict CDKEY auth should be performed with the auth server
+ this is required if you want reliable cl_guid for the server (for users tracking)
+
+- filesystem:
+ client re-orders it's pk3s according to the order given by server
+ (fixes some 'Invalid .PK3 files referenced' situations
+
+- fixed invisible entities/players bug (thanks goes to Rick Johnson / Raven for this one!)
+- update x86 VM code (better and safer optimisations) (Richk Johnson / Raven too)
+- clearing client gentity before GAME_INIT call
+- failing vote if there's only one voting client (fixes exploit on 2-player server where one player votes then disconnects, forcing vote to pass)
+
+- added trap_FS_Seek
+
+- renderer fix:
+ if client game code registers a shader after drawsurfaces are generated but before frame is rendered
+ had a one-frame visual glitch (shader indexes messed up)
+- renderer fix:
+ r_roundImagesDown 0 + map q3dm1 -> crash (buffer overflow fix)
+- renderer fix:
+ fixed a crash in widescreen displays (q3dm11)
+- renderer fix:
+ MAX_SHADERS up to 2^12
+- renderer fix:
+ moved screenshot from frontend to backend, fixes broken r_smp 1 screenshots
+
+- TA fixes:
+ MOD_KAMIKAZE MOD_JUICED logging properly to games.log
+ fixed bot taunt spamming
+- fixed typo in scripts/models2.shader (shader error Ursula head)
+
+Win32 specific:
+
+- fixed the DirectInput mouse init procedure
+- rcon:
+ fixed rcon not working on NT/2000/XP workstations that have a long uptime
+
+Linux specific:
+
+- no longer trying to load libMesaVoodooGL.so
+ obsolete code, was confusing when trying to setup correct OpenGL acceleration
+- SMP support in the renderer. Detects CPU count, r_smp 1 default if available. (thanks to Gareth Hughes for contributing this)
+- changed default GL driver from libGL.so to libGL.so.1
+ see LSB 1.2 spec: http://www.linuxbase.org/spec/refspecs/LSB_1.2.0/gLSB/libgl.html
+- Handle Ctrl and Space key together correctly (Ctrl was disabling Space)
+- sub-frame timing of input events (key/mouse) (input timing quality now equivalent to win32)
diff --git a/code/unix/LinuxSupport/INSTALL b/code/unix/LinuxSupport/INSTALL
new file mode 100755
index 0000000..4ea24e7
--- /dev/null
+++ b/code/unix/LinuxSupport/INSTALL
@@ -0,0 +1,52 @@
+ Quake III Arena
+ Quake III: Team Arena
+ Installation instructions
+ ------
+
+What you need:
+
+- retail CD-ROM of Quake III Arena for Windows or linux
+- optionally, retail CD-ROM of Quake III: Team Arena
+- a computer running linux (kernel >= 2.2 glibc >= 2.1)
+- running the client requires X11 and 3D hardware acceleration with OpenGL
+
+Installation:
+
+If you have the retail CD-ROM of Quake III Arena for linux:
+- install Quake III Arena from the CD-ROM
+- run the Point Release installer
+(to buy Quake III Arena for linux online, try http://www.tuxgames.com/)
+
+If you have the retail CD-ROM of Quake III Arena for Windows:
+- run the Point Release installer first
+- now you need to copy the main pak files from the CD-ROM
+ or from your win32 partition. Namely, you need to copy baseq3/pak0.pk3
+ and for Team Arena, missionpack/pak0.pk3
+ see below for more instructions on how to copy the files:
+
+WARNING: Those instructions are provided as a reference,
+depending on your distribution the CD-ROM might not have the same
+mount point. Please refer to your linux documentation for additional
+information.
+
+- open a root shell and cd to the default installation path:
+ cd /usr/local/games/quake3
+- mount the Quake III Arena CD-ROM and install the game content
+ cp /mnt/cdrom/Quake3/baseq3/pak0.pk3 /usr/local/games/quake3/baseq3
+- optionally, mount the Quake III: Team Arena CD-ROM
+ cp /mnt/cdrom/Setup/missionpack/pak0.pk3 /usr/local/games/quake3/missionpack
+
+NOTES:
+- If you are running Quake III Arena and Quake III: Team Arena on a
+ Windows partition, you can save some space by symlinking the game
+ assets to their windows installation:
+ ln -s /win/quake3/baseq3/pak0.pk3 /usr/local/games/quake3/baseq3/pak0.pk3
+ ln -s /win/quake3/missionpack/pak0.pk3 /usr/local/games/quake3/missionpack/pak0.pk3
+ (Windows partition is mounted as /win and Quake III Arena installation is C:\quake3)
+
+Getting Help:
+
+- consult the FAQ in Help/Q3A_FAQ.html
+- head over to the Quake3World forums http://www.quake3world.com/forums
+- consult the list of known issues and tips at
+ http://zerowing.idsoftware.com/linux
diff --git a/code/unix/LinuxSupport/index.html b/code/unix/LinuxSupport/index.html
new file mode 100755
index 0000000..73cfc34
--- /dev/null
+++ b/code/unix/LinuxSupport/index.html
@@ -0,0 +1,283 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head>
+ <title>Linux Quake III Arena Known issues</title></head>
+
+<body text="#000000" bgcolor="#ffffff">
+<font size="+2"><b>Linux Quake III Arena Known issues</b></font><br>
+<i>Known issues and frequently asked questions - 1.32b</i><br>
+<br>
+<a href="mailto:ttimo@idsoftware.com">TTimo</a><br>
+<i>Changes history</i><br>
+2004.2.20 Last update<br>
+2001.6.18 Initial version
+<hr size="1"><br>
+<font size="+1">Current topics</font>
+<ul>
+ <li><a href="#install">Installation instructions</a></li>
+ <li><a href="#setupfiles">What do I do with a .x86.run file?</a></li>
+ <li><a href="#glibc">The setup crashes with <i>Segmentation fault "$setup" "$@" 2>/dev/null</i></a></li>
+ <li><a href="#bsd">Installation on BSD</a></li>
+ <li><a href="#auth">CLIENT_UNKNOWN_TO_AUTH</a></li>
+ <li><a href="#pk3">Sys_Error: Couldn't load default.cfg / Sys_Error: FS_FreeFile(
+NULL )</a></li>
+ <li><a href="#setupbug29h">I get <i>./setup.sh {: ==: binary operator expected</i>
+when running the setup?</a></li>
+ <li><a href="#hints">The game doesn't start, I have performance problems,
+etc.</a></li>
+ <li><a href="#aureal">Aureal sound drivers</a></li>
+ <li><a href="#nosound">The sound doesn't work / sound crashes</a></li>
+ <li><a href="#discuss">Where can I report bugs and discuss about linux
+Quake III Arena?</a></li>
+ <li><a href="#gameso">The *.so files are not in the setups? (<i>cgamei386.so
+qagamei386.so uii386.so</i>)</a></li>
+ <li><a href="#vm_game">I get <i>Sys_Error: Sys_LoadDll(..) failed dlopen()
+completely!</i> when running quake3?</a></li>
+ <li><a href="#3dnow">I have an AMD CPU and a kernel 2.4.*, Quake III Arena
+is slowing down to a complete stop after a while?</a></li>
+ <li><a href="#gamma">How do I set up the gamma correction?</a></li>
+ <li><a href="#browser">Servers don't show up in the ingame browser</a></li>
+ <li><a href="#libsafe">Detected an attempt to write across stack boundary</a></li>
+ <li><a href="#libmesa">libMesaVoodooGL.so</a></li>
+ <li><a href="#UDPwide">Running a LAN dedicated server with multiple network
+interfaces</a></li>
+ <li><a href="#64bits">Setup and execution on 64 bits CPUs</a></li>
+ <li><a href="#links">Links</a></li>
+</ul>
+<hr size="1"><font size="+1"><a name="install"><b>Installation instructions</b></a></font>
+<a name="install"><br>
+</a>
+<p><a name="install">Linux Quake III Arena is using a graphical installer
+(based on Loki software's </a><a href="http://www.icculus.org/loki_setup/">Setup Graphic Installer
+</a>). However, since it's a Point Release, you need a retail CD-ROM of Quake
+III Arena to perform a complete installation (and optionally your Quake III:
+Team Arena CD-ROM). This process is documented in the <a href="http://zerowing.idsoftware.com/linux/q3a/INSTALL">INSTALL</a>file
+(this file is also in the setups, it's default location is /usr/local/games/quake3/INSTALL
+.. you can run the PR setup and read it to finish the installation afterwards).</p>
+<font size="+1"><a name="setupfiles"><b>What do I do with a .x86.run file?</b></a></font>
+<a name="setupfiles"><br>
+</a>
+<p>Those are setup files, meant to be executed. They
+come with graphical installation UI or console installation, depending on
+what's available on your system. You may need to <i>chmod +x file.x86.run</i>
+to make them executable.</p>
+<font size="+1"><a name="glibc"><b>The setup crashes with <i>Segmentation fault "$setup" "$@" 2>/dev/null</i></b></a></font>
+<p>This is happening on glibc 2.3 systems such as RedHat 9 and Suze. The text mode installer will crash. If you can do a graphical installation, make sure you have Gtk1 installed and avoid the text installer altogether.
+If you are doing a remote installation (such as a dedicated server through ssh), you need to use a newer text mode installer. Run the installer with <i>--keep</i> to extract the files
+(look for a <i>setup*</i> directory in the current directory for the extracted setup).
+Then replace <i>setup.data/bin/Linux/x86/setup</i> by <a href="http://zerowing.idsoftware.com/linux/setup-RH9/setup">this newer version</a>. Run <i>setup.sh</i> at top level and things should work fine.</p>
+<p>
+<b>Update</b>: Turns out this solution is working for RTCW and ET, but not for Q3 (because the last q3 setup uses an older version of the installer). Will update a specific solution for Q3 'soon'.
+</p>
+<font size="+1"><a name="bsd"><b>Installation on
+BSD</b></a></font><a name="bsd"><br>
+</a>
+<p><a name="bsd">The linux binaries will run fine on the BSD family (FreeBSD,
+NetBSD and OpenBSD) with the linux binary compatibility software. However
+if you are getting the error message <i>ELF binary type "0" not known</i>
+while installing or trying to run the binaries, that means you need to run
+<i>brandelf</i> on the files.</a></p>
+<p><a name="bsd">If it's a setup problem, proceed with the following steps:
+</a></p>
+<pre><a name="bsd">./linuxq3apoint-1.31.x86.run --keep<br>brandelf -t Linux setup.tmp/setup.data/bin/FreeBSD/x86/setup<br>cd setup.tmp<br>sh ./setup.sh<br></a></pre>
+<p><a name="bsd">The --keep option will extract the files and leave them
+somewhere below your current directory. Depending on the game (Q3 or RTCW)
+and the setup version, your mileage may vary (setup.tmp or another directory).</a></p>
+<p><a name="bsd">The game binaries might need to be brandelf'ed too, with
+a command such as</a></p>
+<pre><a name="bsd">brandelf -t Linux /usr/local/games/quake3/quake3.x86<br></a></pre>
+<a name="bsd"></a><font size="+1"><a name="auth"><b>CLIENT_UNKNOWN_TO_AUTH</b></a></font>
+<a name="auth"><br>
+</a>
+<p><a name="auth">Graeme Devine recently updated his <i>.plan</i> with very
+complete </a><a href="http://www.webdog.org/cgi-bin/finger.plm?id=279&amp;time=20011210020942" target="_new">information about CLIENT_UNKNOWN_TO_AUTH errors</a>.</p>
+<p>
+See some additional information from the <a href="http://www.gameadmins.com/modules.php?name=Mail_List">gameadmins.com mailing list</a>:
+</p>
+<pre>If the server you are playing on and the auth server don't see you as the
+same IP (for instance you are trying to play on a public internet server
+that's on your LAN, and your internet access is using NAT), then it won't
+work.
+
+It used to work in 1.31, and it doesn't in 1.32. PunkBuster requires
+reliable auth of the players. What you can do:
+
+- run a server with sv_strictauth 0 and you'll be able to join your
+server. This will be the same behaviour as 1.31
+
+- connect to a server on the internet before you connect to your local
+server (this will trigger your IP into the cache of the auth server for
+15mn and let you in to your local server).
+
+- setup two NATs, one for your client one for your server and make sure
+your server and Id's auth see the same IP. (this one ain't for network
+setup newbies)
+</pre>
+<font size="+1"><a name="pk3"><b>Sys_Error: Couldn't load default.cfg / Sys_Error:
+FS_FreeFile( NULL )</b></a></font><br>
+<p>If you get one of these errors after installing Quake III Arena or Return
+To Castle Wolfenstein, it means that the engine didn't find all the required
+.pk3 files. Either you didn't copy them, or you copied them to the wrong
+place. Check the INSTALL instructions for the game for more details, make
+sure they are in baseq3/ for quake3 (missionpack/ for TA files) and main/
+for Return To Castle Wolfenstein.</p>
+<font size="+1"><a name="setupbug29h"><b>I get <i>./setup.sh {: ==: binary
+operator expected</i> when running the setup?</b></a></font><a name="setupbug29h"><br>
+</a>
+<p><a name="setupbug29h">This is a known issue to 1.29h setups and prior.
+It happens on systems with bash version &lt; 2.*. There are several solutions:<br>
+- Upgrade bash to something more recent and run the setup again - Run the
+setup with the --keep option. It will fail but it will leave a <i>setup-full</i>
+directory. You can then copy the files manually from that dir. - Once you
+used the --keep option above, you can edit setup.sh and replace occurences
+of == by =. Then run setup.sh and the installer will execute.</a></p>
+<a name="setupbug29h"></a><font size="+1"><a name="hints"><b>The game doesn't
+start, I have performance problems, etc.</b></a></font><br>
+<p>The first thing to do is to check on the forums and various FAQs (this
+one, but there are others. See the <a href="#links">links</a>). The Quake3World
+forums have a great search function.</p>
+<p>Before reporting the problem to <a href="mailto:ttimo@idsoftware.com">me</a>
+make sure it's an issue with the game, and not an issue with your OS/OpenGL/sound
+configuration. Common OS issues are listed in this FAQ. You should make sure
+you have OpenGL configured correctly (by checking if <i>gears</i>is running
+for instance, and how well it runs). And see if non-Id linux games are running
+fine too.</p>
+<p>When you are going to report a bug, first make sure you are using the
+latest version of the game. Include the game version in your report.</p>
+<p>Include general information about your OS:<br>
+</p>
+<ul>
+ <li>Motherboard brand, CPU type, RAM</li>
+ <li>distribution name and version</li>
+ <li>kernel / OS info (from <i>uname -a</i>)</li>
+ <li>libc version (<i>ls -l /lib/libc.so.*</i>)<br>
+ please specify if you can if the libc is your distribution's standard
+version, or if you compiled yourself, and what binary target was used (x86,
+or AMD, i686 etc.)</li>
+</ul>
+<p>If it's a problem with the client, send the output of <i>glxinfo</i>.</p>
+<p>If you have an nvidia board, send the output of <i>cat /proc/nv/card0</i>
+</p>
+<p>Send output of the run:<br>
+run the game with <i>+set developer 1</i> option, and send the output. You
+can do something like <i>quake3 +set developer 1 &amp;&gt;q3run.log</i>.</p>
+<p>If it's a crash, you can send a backtrace of the game running through
+<i>gdb</i>.</p>
+<p>You can also send a log of the game running with <i>strace</i>:</p>
+<pre>cd /usr/local/games/quake3<br>strace -o ~/strace.log ./quake3.x86<br></pre>
+<p>NOTE: please <b>avoid</b> sending me the <i>strace</i> of <i>/usr/local/games/quake3/quake3</i>,
+which is a shell script wrapper and probably no interest to your problem.
+</p>
+<font size="+1"><a name="aureal"><b>Aureal sound drivers</b></a></font><a name="aureal"><br>
+</a>
+<p><a name="aureal">It seems that some versions of the Aureal sound drivers
+don't work right with Q3. Last I heard, a kernel upgrade to 2.4.17 + Aureal
+1.1.3, and/or using the old 1.1.1 drivers from </a><a href="http://aureal.sourceforge.net/" target="_new">Aureal's website</a>fixed
+the problem.</p>
+<p>If you need to know more about this, have a look at this <a href="http://www.quake3world.com/ubb/Forum15/HTML/001348.html" target="_new">Q3W forum thread</a>.</p>
+<font size="+1"><a name="nosound"><b>The sound doesn't work / sound crashes</b></a></font><br>
+<p>The first thing to check is that it is actually a sound related. Run
+the game with <i>+set s_initsound 0</i> and see what happens. All problems
+reported so far about sound turned out to be OS/drivers. Listed below:</p>
+<p>On some Mandrake distributions:<br>
+Check if you are running the enlightenment sound daemon (esd). With <i>ps
+aux | grep esd</i>for instance. It is a multiplexer for /dev/dsp, and might
+block use of /dev/dsp by Quake III Arena. You can disable esd with <i>esdctl
+stop</i> (as root).</p>
+<p><b><a href="http://www.linux-mandrake.com/">Mandrake 8</a></b>'s default
+sound drivers seem broken, installing the <a href="http://www.alsa-project.org/" target="_new">Alsa drivers</a> or the
+ <a href="http://www.opensound.com/">http://www.opensound.com</a> drivers
+fixes the problem.</p>
+<p>Some beta <a href="http://www.alsa-project.org/" target="_new">Alsa drivers</a>
+have been reported to crash with Q3. Non-beta ones are fine.</p>
+<p>VIA chipset and AC97 driver:<br>
+This combination is known to have various issues. They have been fixed in
+recent drivers (thanks to Arne Schmitz for the heads up):<br>
+</p>
+<pre>http://sourceforge.net/projects/gkernel has got the up to date version of <br>the AC97 kernel driver. The current version can be found here:<br><br>http://prdownloads.sourceforge.net/gkernel/via82cxxx-1.1.15.tar.gz<br><br>It has working mmap sound, so Q3 shouldn't be a problem any more.<br></pre>
+(thanks to Arne Schmitz for the heads up)<p></p>
+
+<font size="+1"><a name="discuss"><b>Where can I report bugs and discuss about linux Quake III
+Arena?</b></a></font><a name="discuss"><br>
+</a>
+<p><a name="discuss">Reports bugs to </a><a href="mailto:bugs@idsoftware.com">bugs@idsoftware.com</a>. If you are pretty
+sure this is a linux-only issue, you can shorten the loop by emailing <a href="mailto:ttimo@idsoftware.com">ttimo@idsoftware.com</a> directly.</p>
+<p>You will find the discussion forums for linux Quake III Arena on <a href="http://www.quake3world.com/cgi-bin/forumdisplay.cgi?action=topics&amp;forum=*nix+Discussion&amp;number=15&amp;DaysPrune=30&amp;LastLogin=">
+Quake3World forums</a>. There is for sure a lot of other places to talk about
+linux Quake III Arena, but this is the one we read regularly to track bugs
+and common issues.</p>
+<font size="+1"><a name="gameso"><b>The *.so files are not in the setups?
+(<i>cgamei386.so qagamei386.so uii386.so</i>)</b></a></font><a name="gameso"><br>
+</a>
+<p><a name="gameso">If you still have <i>baseq3/*.so</i> and <i>missionpack/*.so</i>
+files, then those come from the earlier 1.27g beta installation and you should
+REMOVE them. They were provided in 1.27g to go around a bug in the VM code,
+which made win32 VMs incompatible with linux. This problem has been fixed
+and the two files are no longer required.</a></p>
+<p><a name="gameso">If you are upgrading from 1.27g, it is likely that your
+<i>q3config.cfg</i> files are set to use the native libraries (*.so files)
+instead of the bytecode. Run quake3 with the following options to set things
+right:<br>
+<i>quake3 +set vm_game 2 +set vm_cgame 2 +set vm_ui 2</i></a></p>
+<a name="gameso"></a><font size="+1"><a name="vm_game"><b>I get <i>Sys_Error:
+Sys_LoadDll(..) failed dlopen() completely!</i>when running quake3?</b></a></font><a name="vm_game"><br>
+</a>
+<p><a name="vm_game">Try running quake3 with the following options:<br>
+<i>quake3 +set vm_game 2 +set vm_cgame 2 +set vm_ui 2</i><br>
+You should also read the </a><a href="#gameso">above answer</a>.</p>
+<font size="+1"><a name="3dnow"><b>I have an AMD CPU and a kernel 2.4.*,
+Quake III Arena is slowing down to a complete stop after a while?</b></a></font><br>
+<p>It seems the 3DNow! copy routines have issues with the southbridge chip
+in the KT133A, this results in performances degrading while playing for a
+while. Re-compile your kernel without 3DNow! instructions to avoid the problem,
+and wait for newer kernels with better support for 3DNow! / KT133A.</p>
+<font size="+1"><a name="gamma"><b>How do I set up the gamma correction?</b></a></font><br>
+<p>Starting with 1.29h, you can set the gamma correction with the brightness
+slider in the graphical menu (under setup). On some older systems which don't
+have the appropriate XFree86 extensions, you might have to set <b>r_gamma</b>
+manually from the console, and issue a <b>vid_restart</b> command.</p>
+<font size="+1"><a name="browser"><b>Servers don't show up in the ingame
+browser</b></a></font>
+<p>The reason for this has not been clearly identified yet, seems to be related
+to upgrade from older versions. Deleting ~/.q3a/baseq3/q3config.cfg fixes
+the problem (you will have to reconfigure your bindings)</p>
+<font size="+1"><a name="libsafe"><b>Detected an attempt to write across
+stack boundary</b></a></font>
+<p>If Quake III Arena exits with the error "Detected an attempt to write
+across stack boundary", this probably means that you are running libsafe
+on this system. Quake III Arena is compiled with some options that confuse
+libsafe, you should disable it before running. See <a href="http://www.mudos.org/?faq" target="_new">this page</a> for more details.
+</p>
+<font size="+1"><a name="libmesa"><b>libMesaVoodooGL.so</b></a></font>
+<p>The GL driver for Voodoo cards (libMesaVoodoGL.so) used to be distributed
+in older Q3 setups. <b>This is no longer the case.</b> If you have this .so
+in your Quake III Arena directory (<i>/usr/local/games/quake3</i>), you should
+remove it. Any recent/decent linux distribution should support your Voodoo
+card out of the box, otherwise it is recommended that you setup XFree 4.*
+and the correct DRI infrastructure for it.</p>
+<font size="+1"><a name="UDPwide"><b>Running a LAN dedicated server with
+multiple network interfaces</b></a></font>
+<p>A LAN dedicated server will use the <i>net_ip</i> cvar to identify the
+NIC it is going to use (default is "localhost"). As it only opens one socket,
+it is not possible to have a server broadcast it's packets on all the NICs.
+This can be a problem if the server is serving games for a LAN and runs several
+NICs to access the various sub networks.<br>
+</p>
+<p>The following Linux kernel patch (2.4.19) was provided by Rogier Mulhujzen
+and John Tobin, it will force broadcasts to be emitted on all interfaces:<br>
+<a href="http://zerowing.idsoftware.com/linux/q3a/udp_wide_broadcast.patch">udp_wide_broadcast.patch</a><br>
+<a href="http://zerowing.idsoftware.com/linux/q3a/udp_wide_README.txt">udp_wide_README.txt</a><br>
+The equivalent <a href="http://www.bsdchicks.com/patches/">patch for FreeBSD</a>
+is available too.<br>
+ </p>
+<font size="+1"><a name="64bits"><b>Setup and execution on 64 bits CPUs</b></a></font><br>
+<p>If you are running Linux on a 64 bit CPU (such as AMD's Opteron), and if your system is backwards compatible so that it can execute 32 bits x86 binaries, then the regular Quake III Arena binaries should work (your mileage may vary).</p>
+<p>It's likely that the installer scripts will get confused though, and will refuse to install giving you an error: "This installation doesn't support glibc-2.1 on Linux / unknown". You will have to extract the game files manually by passing --keep on the command line when running the setup script. Once the files are unpacked, you will need to copy them manually to /usr/local/games. You probably want to have a working installation to refer to while doing this. This also applies to RTCW and ET</p>
+<font size="+1"><a name="links"><b>Links</b></a></font><br>
+<p>The <a href="http://www.icculus.org/lgfaq" target="_new">Linux Gamer's
+faq</a> is a very good resource for general Linux Gaming topics.</p>
+<p>Also at <a href="http://www.icculus.org/" target="_new">icculus.org</a>,
+the <a href="http://www.icculus.org/lgfaq/loki/q3faq.html" target="_new">old
+Q3 FAQ from Loki Software</a>.</p>
+<p><a href="http://www.quake3world.com/ubb/Forum15/HTML/000529.html">Quake3World's
+linux FAQ</a></p>
+<br>
+</body></html>
diff --git a/code/unix/LinuxSupport/udp_wide_README.txt b/code/unix/LinuxSupport/udp_wide_README.txt
new file mode 100755
index 0000000..7c0d7b6
--- /dev/null
+++ b/code/unix/LinuxSupport/udp_wide_README.txt
@@ -0,0 +1,20 @@
+UDP Wide Broadcast Patch for Kernel 2.4.19
+
+Main purpose is to allow Quake 3 servers, and all games powered by the
+engine, to be visible in the server browser when the servers are being run on
+aliased IP addresses and multiple NICs using the +set net_ip option.
+
+To apply the patch run "patch -p1 < udp_wide_broadcast.patch" from your
+source directory and recompile.
+
+Add "echo "1" > /proc/sys/net/ipv4/udp_wide_broadcast" to one of your startup
+scripts, i.e./etc/rc.d/rc.local, and run thousands of servers from your
+computer.
+
+
+Patch by:
+Rogier Mulhujzen <linux@bsdchicks.com>
+John Tobin <ogre@sirinet.net>
+
+A patch with the same functionality for FreeBSD is available from
+http://www.bsdchicks.com/patches
diff --git a/code/unix/LinuxSupport/udp_wide_broadcast.patch b/code/unix/LinuxSupport/udp_wide_broadcast.patch
new file mode 100755
index 0000000..b6f86eb
--- /dev/null
+++ b/code/unix/LinuxSupport/udp_wide_broadcast.patch
@@ -0,0 +1,57 @@
+--- linux/include/linux/sysctl.h.orig 2002-08-17 19:52:27.000000000 -0500
++++ linux/include/linux/sysctl.h 2002-08-17 19:53:00.000000000 -0500
+@@ -291,7 +291,8 @@
+ NET_IPV4_NONLOCAL_BIND=88,
+ NET_IPV4_ICMP_RATELIMIT=89,
+ NET_IPV4_ICMP_RATEMASK=90,
+- NET_TCP_TW_REUSE=91
++ NET_TCP_TW_REUSE=91,
++ NET_UDP_WIDE_BROADCAST=92
+ };
+
+ enum {
+--- linux-modified/net/ipv4/sysctl_net_ipv4.c.orig 2002-08-17 19:48:19.000000000 -0500
++++ linux-modified/net/ipv4/sysctl_net_ipv4.c 2002-08-17 19:52:03.000000000 -0500
+@@ -45,6 +45,9 @@
+ extern int inet_peer_gc_mintime;
+ extern int inet_peer_gc_maxtime;
+
++/* From udp.c */
++extern int sysctl_udp_wide_broadcast;
++
+ #ifdef CONFIG_SYSCTL
+ static int tcp_retr1_max = 255;
+ static int ip_local_port_range_min[] = { 1, 1 };
+@@ -221,6 +224,8 @@
+ &sysctl_icmp_ratemask, sizeof(int), 0644, NULL, &proc_dointvec},
+ {NET_TCP_TW_REUSE, "tcp_tw_reuse",
+ &sysctl_tcp_tw_reuse, sizeof(int), 0644, NULL, &proc_dointvec},
++ {NET_UDP_WIDE_BROADCAST, "udp_wide_broadcast",
++ &sysctl_udp_wide_broadcast, sizeof(int), 0644, NULL, &proc_dointvec},
+ {0}
+ };
+
+--- linux-modified/net/ipv4/udp.c.orig 2002-08-17 19:40:59.000000000 -0500
++++ linux-modified/net/ipv4/udp.c 2002-08-17 23:37:47.000000000 -0500
+@@ -94,6 +94,8 @@
+ #include <net/inet_common.h>
+ #include <net/checksum.h>
+
++int sysctl_udp_wide_broadcast = 0;
++
+ /*
+ * Snmp MIB for the UDP layer
+ */
+@@ -272,9 +274,10 @@
+ if ((s->num != hnum) ||
+ (s->daddr && s->daddr!=rmt_addr) ||
+ (s->dport != rmt_port && s->dport != 0) ||
+- (s->rcv_saddr && s->rcv_saddr != loc_addr) ||
+- (s->bound_dev_if && s->bound_dev_if != dif))
++ !(sysctl_udp_wide_broadcast || !(s->rcv_saddr && s->rcv_saddr != loc_addr)) ||
++ (s->bound_dev_if && s->bound_dev_if != dif)) {
+ continue;
++ }
+ break;
+ }
+ return s;
diff --git a/code/unix/Makefile b/code/unix/Makefile
new file mode 100755
index 0000000..8d9f3c1
--- /dev/null
+++ b/code/unix/Makefile
@@ -0,0 +1,2119 @@
+#
+# Quake3 Unix Makefile
+#
+# Currently build for the following:
+# Linux i386 (full client)
+# Linux Alpha (dedicated server only) (TTimo: dropped)
+# FreeBSD i386 (dedicated server only) (TTimo: maybe worth updating)
+# SGI IRIX (full client) (TTimo: who's in charge - dropped otherwise)
+# Linux PPC (full client) (TTimo: dropped)
+#
+# Nov '98 by Zoid <zoid@idsoftware.com>
+#
+# Loki Hacking by Bernd Kreimeier
+# and a little more by Ryan C. Gordon.
+# and a little more by Rafael Barrero
+#
+# GNU Make required
+#
+
+PLATFORM=$(shell uname|tr A-Z a-z)
+PLATFORM_RELEASE=$(shell uname -r)
+
+###
+### These paths are where you probably want to change things
+###
+
+# Where we are building from (where the source code should be!)
+MOUNT_DIR=../
+
+# Where we are building to, libMesaVoodooGL.so.3.3 should be here, etc.
+# the demo pk3 file should be here in demoq3/pak0.pk3 or baseq3/pak0.pk3
+BDIR=$(MOUNT_DIR)/../run
+
+
+# Build name
+# BUILD_NAME=$(BUILD_NAME)
+BUILD_NAME=quake3.x86
+
+
+
+#############################################################################
+##
+## You shouldn't have to touch anything below here
+##
+#############################################################################
+
+BASEQ3_DIR=$(BDIR)/baseq3
+
+BD=debug$(ARCH)$(GLIBC)
+BR=release$(ARCH)$(GLIBC)
+CDIR=$(MOUNT_DIR)/client
+SDIR=$(MOUNT_DIR)/server
+RDIR=$(MOUNT_DIR)/renderer
+CMDIR=$(MOUNT_DIR)/qcommon
+UDIR=$(MOUNT_DIR)/unix
+GDIR=$(MOUNT_DIR)/game
+CGDIR=$(MOUNT_DIR)/cgame
+BAIDIR=$(GDIR)
+BLIBDIR=$(MOUNT_DIR)/botlib
+NDIR=$(MOUNT_DIR)/null
+UIDIR=$(MOUNT_DIR)/ui
+Q3UIDIR=$(MOUNT_DIR)/q3_ui
+FTDIR=$(MOUNT_DIR)/ft2
+JPDIR=$(MOUNT_DIR)/jpeg-6
+SPLNDIR=$(MOUNT_DIR)/splines
+
+# extract version info
+VERSION=$(shell ./extract_ver.pl)
+RPM_RELEASE=1
+
+# NOTE: used by dcp rcp targets, not referenced
+#TESTDIR=/home/timo/Id/Quake3-loki/run
+
+#############################################################################
+# SETUP AND BUILD -- LINUX
+#############################################################################
+
+## Defaults
+DLL_ONLY=false
+# bk010215 - TODO - add all defaults / kill Ryan
+
+
+ifeq ($(PLATFORM),linux)
+
+ ifneq (,$(findstring libc6,$(shell if [ -e /lib/libc.so.6* ];then echo libc6;fi)))
+ GLIBC=-glibc
+ else
+ GLIBC=
+ endif #libc6 test
+
+ ifneq (,$(findstring alpha,$(shell uname -m)))
+ ARCH=axp
+ RPMARCH=alpha
+ VENDOR=dec
+ else
+ ifneq (,$(findstring ppc,$(shell uname -m)))
+ #used for linux builds
+ MESADIR=/usr/src/DRI-CVS/xc/xc/
+ ARCH=ppc
+ RPMARCH=ppc
+ VENDOR=unknown
+ DLL_ONLY=true
+ else #default to i386
+ MESADIR=../Mesa/
+ ARCH=i386
+ RPMARCH=i386
+ VENDOR=unknown
+ DLL_ONLY=false
+ endif
+ endif
+
+ # bk001205: no mo' -I/usr/include/glide, no FX
+ # bk001205: no mo' -Dstricmp=strcasecmp, see q_shared.h
+ BASE_CFLAGS = -pipe -fsigned-char
+ # rcg010216: DLL_ONLY for PPC
+ ifeq ($(strip $(DLL_ONLY)),true)
+ BASE_CFLAGS += -DDLL_ONLY
+ endif
+
+
+ #GL_CFLAGS = -I$(MESADIR)/include -I/usr/X11R6/include
+ GL_CFAGS = -I/usr/X11R6/include
+
+ # bk001204 - need -O for -Wall for uninitialized
+ # bk001205 - took out -O to get assertions (NDEBUG)
+ # bk001206 - MALLOC_CHECK in addition to ZONE_DEBUG
+ # TTimo 03/30/2001 temporary took out -Werror for initial merge
+ DEBUG_CFLAGS = $(BASE_CFLAGS) -g -Wall -Werror
+ DEBUG_CFLAGS += -DNO_MOUSEGRAB
+ DEBUG_CFLAGS += -O
+# DEBUG_CFLAGS=$(BASE_CFLAGS) -g -Wall -O
+ ifeq ($(ARCH),axp)
+ CC=pgcc
+ RELEASE_CFLAGS=$(BASE_CFLAGS) -DNDEBUG -O6 -ffast-math -funroll-loops -fomit-frame-pointer -fexpensive-optimizations
+ else
+ ifeq ($(ARCH),ppc)
+ NEWPGCC=/loki/global/ppc/bin/gcc
+ CC=$(NEWPGCC)
+ RELEASE_CFLAGS=$(BASE_CFLAGS) -DNDEBUG -O6 -fomit-frame-pointer -pipe -ffast-math -malign-loops=2 -malign-jumps=2 -malign-functions=2 -fno-strict-aliasing -fstrength-reduce
+ else
+ #NEWPGCC=/usr/local/gcc-2.95.2/bin/gcc # bk001205
+ #NEWPGCC=/loki/global/x86/bin/gcc
+ NEWPGCC=/usr/bin/gcc
+ CC=$(shell if [ -f $(NEWPGCC) ]; then echo $(NEWPGCC); else echo pgcc; fi )
+ CXX=/usr/bin/g++
+# TTimo: legacy RELEASE_CFLAGS
+# NOTE: the -fomit-frame-pointer option leads to an unstable binary on my test box if it was built on the main box
+# but building on the Mdk 7.2 baseline seems to work
+ RELEASE_CFLAGS=$(BASE_CFLAGS) -DNDEBUG -O6 -mcpu=pentiumpro -march=pentium -fomit-frame-pointer -pipe -ffast-math -malign-loops=2 -malign-jumps=2 -malign-functions=2 -fno-strict-aliasing -fstrength-reduce
+# TTimo: use this for building on P3 gcc 2.95.3 libc2.2 for all targets (experimental! -fomit-fram-pointer removed)
+# RELEASE_CFLAGS=$(BASE_CFLAGS) -DNDEBUG -O6 -mcpu=pentiumpro -march=pentium -pipe -ffast-math -malign-loops=2 -malign-jumps=2 -malign-functions=2 -fno-strict-aliasing -fstrength-reduce
+ endif
+ endif
+
+ LIBEXT=a
+
+ SHLIBEXT=so
+ SHLIBCFLAGS=-fPIC
+ SHLIBLDFLAGS=-shared $(LDFLAGS)
+
+ ARFLAGS=ar rv
+ RANLIB=ranlib
+
+ THREAD_LDFLAGS=-lpthread
+ LDFLAGS=-ldl -lm
+ GLLDFLAGS=-L/usr/X11R6/lib -lX11 -lXext -lXxf86dga -lXxf86vm
+
+ ifeq ($(ARCH),axp)
+ TARGETS=\
+ $(B)/$(PLATFORM)q3ded
+ else
+ TARGETS=\
+ $(B)/$(PLATFORM)quake3 \
+ $(B)/$(PLATFORM)quake3-smp \
+ $(B)/$(PLATFORM)q3ded \
+ $(B)/baseq3/cgame$(ARCH).$(SHLIBEXT) \
+ $(B)/baseq3/qagame$(ARCH).$(SHLIBEXT) \
+ $(B)/baseq3/ui$(ARCH).$(SHLIBEXT) \
+ $(B)/missionpack/cgame$(ARCH).$(SHLIBEXT) \
+ $(B)/missionpack/qagame$(ARCH).$(SHLIBEXT) \
+ $(B)/missionpack/ui$(ARCH).$(SHLIBEXT) \
+# $(B)/baseq3/vm/qagame.qvm \
+# $(B)/baseq3/vm/cgame.qvm \
+# $(B)/baseq3/vm/ui.qvm \
+# $(B)/missionpack/vm/qagame.qvm \
+# $(B)/missionpack/vm/cgame.qvm \
+# $(B)/missionpack/vm/ui.qvm
+ endif
+
+## $(B)/$(PLATFORM)q3static \
+
+else # ifeq Linux
+
+#############################################################################
+# SETUP AND BUILD -- FREEBSD
+#############################################################################
+
+ifeq ($(PLATFORM),freebsd)
+
+GLIBC= #libc is irrelevant
+
+ifneq (,$(findstring alpha,$(shell uname -m)))
+ARCH=axp
+RPMARCH=alpha
+VENDOR=dec
+else #default to i386
+ARCH=i386
+RPMARCH=i386
+VENDOR=unknown
+endif #alpha test
+
+
+BASE_CFLAGS = -pipe
+
+GL_CFLAGS = -I$(MESADIR)/include -I/usr/X11R6/include
+
+DEBUG_CFLAGS=$(BASE_CFLAGS) -g -Wall -Werror
+ifeq ($(ARCH),axp)
+CC=pgcc
+RELEASE_CFLAGS=$(BASE_CFLAGS) -DNDEBUG -O6 -ffast-math -funroll-loops -fomit-frame-pointer -fexpensive-optimizations
+else
+#NEWPGCC=/loki/global/x86/bin/gcc # raistlin012301
+#NEWPGCC=/usr/local/gcc-2.95.2/bin/gcc
+NEWPGCC=/home/raistllin/src/gcc/build/install/bin/gcc
+CC=$(shell if [ -f $(NEWPGCC) ]; then echo $(NEWPGCC); else echo pgcc; fi )
+RELEASE_CFLAGS=$(BASE_CFLAGS) -DNDEBUG -O6 -mcpu=pentiumpro -march=pentium -fomit-frame-pointer -pipe -ffast-math -malign-loops=2 -malign-jumps=2 -malign-functions=2 -fno-strict-aliasing - fstrength-reduce
+endif
+
+LIBEXT=a
+
+SHLIBEXT=so
+SHLIBCFLAGS=-fPIC
+SHLIBLDFLAGS=-shared $(LDFLAGS)
+
+ARFLAGS=ar rv
+RANLIB=ranlib
+
+THREAD_LDFLAGS=-lpthread
+# don't need -ldl (FreeBSD)
+LDFLAGS=-lm
+#GLLDFLAGS=-L/usr/X11R6/lib -L$(MESADIR)/lib -lGL -lX11 -lXext -lXxf86dga -lXxf86vm
+#GLLDFLAGS=-L/usr/X11/lib -lGL -lX11 -lXext -lm
+GLLDFLAGS=-L/usr/X11R6/lib -lGL -lX11 -lXext -lXxf86dga -lXxf86vm
+
+ifeq ($(ARCH),axp)
+TARGETS=\
+ $(B)/$(PLATFORM)q3ded
+else
+TARGETS=\
+ $(B)/$(PLATFORM)quake3 \
+ $(B)/baseq3/cgame$(ARCH).$(SHLIBEXT) \
+ $(B)/baseq3/qagame$(ARCH).$(SHLIBEXT) \
+ $(B)/baseq3/ui$(ARCH).$(SHLIBEXT) \
+ $(B)/missionpack/cgame$(ARCH).$(SHLIBEXT) \
+ $(B)/missionpack/qagame$(ARCH).$(SHLIBEXT) \
+ $(B)/missionpack/ui$(ARCH).$(SHLIBEXT)
+endif
+
+else # ifeq freebsd
+
+#############################################################################
+# SETUP AND BUILD -- IRIX
+#############################################################################
+
+ifeq ($(PLATFORM),irix)
+
+ARCH=mips #default to MIPS
+VENDOR=sgi
+GLIBC= #libc is irrelevant
+
+CC=cc
+BASE_CFLAGS=-Dstricmp=strcasecmp -Xcpluscomm -woff 1185 -mips3 \
+ -nostdinc -I. -I$(ROOT)/usr/include
+RELEASE_CFLAGS=$(BASE_CFLAGS) -O3
+DEBUG_CFLAGS=$(BASE_CFLAGS) -g
+
+LIBEXT=a
+
+SHLIBEXT=so
+SHLIBCFLAGS=
+SHLIBLDFLAGS=-shared
+
+ARFLAGS=ar rv
+RANLIB=ranlib
+
+LDFLAGS=-ldl -lm
+GLLDFLAGS=-L/usr/X11/lib -lGL -lX11 -lXext -lm
+
+TARGETS=$(B)/sgiquake3 \
+ $(B)/q3ded
+
+else # ifeq IRIX
+
+#############################################################################
+# SETUP AND BUILD -- GENERIC
+#############################################################################
+
+#CC=egcs
+#BASE_CFLAGS=-Dstricmp=strcasecmp
+#DEBUG_CFLAGS=$(BASE_CFLAGS) -g
+#RELEASE_CFLAGS=$(BASE_CFLAGS) -DNDEBUG -O3
+
+LIBEXT=a
+
+SHLIBEXT=so
+SHLIBCFLAGS=-fPIC
+SHLIBLDFLAGS=-shared
+
+ARFLAGS=ar rv
+RANLIB=ranlib
+
+ifeq ($(PLATFORM),freebsd)
+LDFLAGS=-lm
+else
+LDFLAGS=-ldl -lm
+endif # ifeq freebsd
+
+TARGETS=\
+ $(B)/$(PLATFORM)q3ded
+
+endif #Linux
+endif #FreeBSD
+endif #IRIX
+
+DO_CC=$(CC) $(CFLAGS) -o $@ -c $<
+DO_CXX=$(CXX) $(CFLAGS) -o $@ -c $<
+DO_SMP_CC=$(CC) $(CFLAGS) -DSMP -o $@ -c $<
+DO_BOT_CC=$(CC) $(CFLAGS) -DBOTLIB -o $@ -c $< # $(SHLIBCFLAGS) # bk001212
+DO_DEBUG_CC=$(CC) $(DEBUG_CFLAGS) -o $@ -c $<
+DO_SHLIB_CC=$(CC) $(CFLAGS) $(SHLIBCFLAGS) -o $@ -c $<
+DO_SHLIB_DEBUG_CC=$(CC) $(DEBUG_CFLAGS) $(SHLIBCFLAGS) -o $@ -c $<
+DO_AS=$(CC) $(CFLAGS) -DELF -x assembler-with-cpp -o $@ -c $<
+DO_NASM=nasm -f elf -o $@ $<
+DO_DED_CC=$(CC) -DDEDICATED -DC_ONLY $(CFLAGS) -o $@ -c $<
+
+#DO_LCC=$(LCC) -o $@ -S -Wf-target=bytecode -Wf-g -DQ3_VM -I$(CGDIR) -I$(GDIR) -I$(UIDIR) $<
+
+#### DEFAULT TARGET
+default:build_debug
+
+debug: build_debug
+release: build_release
+
+build_debug:
+ $(MAKE) targets B=$(BD) CFLAGS="$(DEBUG_CFLAGS)"
+
+build_release:
+ $(MAKE) targets B=$(BR) CFLAGS="$(RELEASE_CFLAGS)"
+
+#Build both debug and release builds
+all:build_debug build_release
+
+targets:makedirs $(TARGETS)
+
+makedirs:
+ @if [ ! -d $(B) ];then mkdir $(B);fi
+ @if [ ! -d $(B)/client ];then mkdir $(B)/client;fi
+ @if [ ! -d $(B)/ded ];then mkdir $(B)/ded;fi
+ @if [ ! -d $(B)/ref ];then mkdir $(B)/ref;fi
+ @if [ ! -d $(B)/ft2 ];then mkdir $(B)/ft2;fi
+ @if [ ! -d $(B)/baseq3 ];then mkdir $(B)/baseq3;fi
+ @if [ ! -d $(B)/baseq3/cgame ];then mkdir $(B)/baseq3/cgame;fi
+ @if [ ! -d $(B)/baseq3/game ];then mkdir $(B)/baseq3/game;fi
+ @if [ ! -d $(B)/baseq3/ui ];then mkdir $(B)/baseq3/ui;fi
+ @if [ ! -d $(B)/baseq3/vm ];then mkdir $(B)/baseq3/vm;fi
+ @if [ ! -d $(B)/missionpack ];then mkdir $(B)/missionpack;fi
+ @if [ ! -d $(B)/missionpack/cgame ];then mkdir $(B)/missionpack/cgame;fi
+ @if [ ! -d $(B)/missionpack/game ];then mkdir $(B)/missionpack/game;fi
+ @if [ ! -d $(B)/missionpack/ui ];then mkdir $(B)/missionpack/ui;fi
+ @if [ ! -d $(B)/missionpack/vm ];then mkdir $(B)/missionpack/vm;fi
+ @if [ ! -d $(B)/q3static ];then mkdir $(B)/q3static;fi
+
+#############################################################################
+# CLIENT/SERVER
+#############################################################################
+
+Q3OBJ = \
+ $(B)/client/cl_cgame.o \
+ $(B)/client/cl_cin.o \
+ $(B)/client/cl_console.o \
+ $(B)/client/cl_input.o \
+ $(B)/client/cl_keys.o \
+ $(B)/client/cl_main.o \
+ $(B)/client/cl_net_chan.o \
+ $(B)/client/cl_parse.o \
+ $(B)/client/cl_scrn.o \
+ $(B)/client/cl_ui.o \
+ \
+ $(B)/client/cm_load.o \
+ $(B)/client/cm_patch.o \
+ $(B)/client/cm_polylib.o \
+ $(B)/client/cm_test.o \
+ $(B)/client/cm_trace.o \
+ \
+ $(B)/client/cmd.o \
+ $(B)/client/common.o \
+ $(B)/client/cvar.o \
+ $(B)/client/files.o \
+ $(B)/client/md4.o \
+ $(B)/client/msg.o \
+ $(B)/client/net_chan.o \
+ $(B)/client/huffman.o \
+ \
+ $(B)/client/snd_adpcm.o \
+ $(B)/client/snd_dma.o \
+ $(B)/client/snd_mem.o \
+ $(B)/client/snd_mix.o \
+ $(B)/client/snd_wavelet.o \
+ \
+ $(B)/client/sv_bot.o \
+ $(B)/client/sv_ccmds.o \
+ $(B)/client/sv_client.o \
+ $(B)/client/sv_game.o \
+ $(B)/client/sv_init.o \
+ $(B)/client/sv_main.o \
+ $(B)/client/sv_net_chan.o \
+ $(B)/client/sv_snapshot.o \
+ $(B)/client/sv_world.o \
+ \
+ $(B)/client/q_math.o \
+ $(B)/client/q_shared.o \
+ \
+ $(B)/client/unzip.o \
+ $(B)/client/vm.o \
+ $(B)/client/vm_interpreted.o \
+ \
+ $(B)/client/be_aas_bspq3.o \
+ $(B)/client/be_aas_cluster.o \
+ $(B)/client/be_aas_debug.o \
+ $(B)/client/be_aas_entity.o \
+ $(B)/client/be_aas_file.o \
+ $(B)/client/be_aas_main.o \
+ $(B)/client/be_aas_move.o \
+ $(B)/client/be_aas_optimize.o \
+ $(B)/client/be_aas_reach.o \
+ $(B)/client/be_aas_route.o \
+ $(B)/client/be_aas_routealt.o \
+ $(B)/client/be_aas_sample.o \
+ $(B)/client/be_ai_char.o \
+ $(B)/client/be_ai_chat.o \
+ $(B)/client/be_ai_gen.o \
+ $(B)/client/be_ai_goal.o \
+ $(B)/client/be_ai_move.o \
+ $(B)/client/be_ai_weap.o \
+ $(B)/client/be_ai_weight.o \
+ $(B)/client/be_ea.o \
+ $(B)/client/be_interface.o \
+ $(B)/client/l_crc.o \
+ $(B)/client/l_libvar.o \
+ $(B)/client/l_log.o \
+ $(B)/client/l_memory.o \
+ $(B)/client/l_precomp.o \
+ $(B)/client/l_script.o \
+ $(B)/client/l_struct.o \
+ \
+ $(B)/client/jcapimin.o \
+ $(B)/client/jchuff.o \
+ $(B)/client/jcinit.o \
+ $(B)/client/jccoefct.o \
+ $(B)/client/jccolor.o \
+ $(B)/client/jfdctflt.o \
+ $(B)/client/jcdctmgr.o \
+ $(B)/client/jcphuff.o \
+ $(B)/client/jcmainct.o \
+ $(B)/client/jcmarker.o \
+ $(B)/client/jcmaster.o \
+ $(B)/client/jcomapi.o \
+ $(B)/client/jcparam.o \
+ $(B)/client/jcprepct.o \
+ $(B)/client/jcsample.o \
+ $(B)/client/jdapimin.o \
+ $(B)/client/jdapistd.o \
+ $(B)/client/jdatasrc.o \
+ $(B)/client/jdcoefct.o \
+ $(B)/client/jdcolor.o \
+ $(B)/client/jddctmgr.o \
+ $(B)/client/jdhuff.o \
+ $(B)/client/jdinput.o \
+ $(B)/client/jdmainct.o \
+ $(B)/client/jdmarker.o \
+ $(B)/client/jdmaster.o \
+ $(B)/client/jdpostct.o \
+ $(B)/client/jdsample.o \
+ $(B)/client/jdtrans.o \
+ $(B)/client/jerror.o \
+ $(B)/client/jidctflt.o \
+ $(B)/client/jmemmgr.o \
+ $(B)/client/jmemnobs.o \
+ $(B)/client/jutils.o \
+ \
+ $(B)/client/tr_animation.o \
+ $(B)/client/tr_backend.o \
+ $(B)/client/tr_bsp.o \
+ $(B)/client/tr_cmds.o \
+ $(B)/client/tr_curve.o \
+ $(B)/client/tr_flares.o \
+ $(B)/client/tr_font.o \
+ $(B)/client/tr_image.o \
+ $(B)/client/tr_init.o \
+ $(B)/client/tr_light.o \
+ $(B)/client/tr_main.o \
+ $(B)/client/tr_marks.o \
+ $(B)/client/tr_mesh.o \
+ $(B)/client/tr_model.o \
+ $(B)/client/tr_noise.o \
+ $(B)/client/tr_scene.o \
+ $(B)/client/tr_shade.o \
+ $(B)/client/tr_shade_calc.o \
+ $(B)/client/tr_shader.o \
+ $(B)/client/tr_shadows.o \
+ $(B)/client/tr_sky.o \
+ $(B)/client/tr_surface.o \
+ $(B)/client/tr_world.o \
+ \
+ $(B)/client/unix_main.o \
+ $(B)/client/unix_net.o \
+ $(B)/client/unix_shared.o \
+ \
+ $(B)/client/ahoptim.o \
+ $(B)/client/autohint.o \
+ $(B)/client/ftbase.o \
+ $(B)/client/ftdebug.o \
+ $(B)/client/ftglyph.o \
+ $(B)/client/ftinit.o \
+ $(B)/client/ftmm.o \
+ $(B)/client/ftsystem.o \
+ $(B)/client/raster1.o \
+ $(B)/client/sfnt.o \
+ $(B)/client/sfobjs.o \
+ $(B)/client/smooth.o \
+ $(B)/client/truetype.o
+# \
+# $(B)/client/q_parse.o \
+# $(B)/client/math_quaternion.o \
+# $(B)/client/util_str.o \
+# $(B)/client/math_angles.o \
+# $(B)/client/math_vector.o \
+# $(B)/client/splines.o \
+# $(B)/client/math_matrix.o
+
+# $(B)/client/q_shared.o \
+
+ ifeq ($(ARCH),i386)
+ Q3OBJ += $(B)/client/vm_x86.o
+ endif
+
+ ifeq ($(ARCH),ppc)
+ ifeq ($(DLL_ONLY),false)
+ Q3OBJ += $(B)/client/vm_ppc.o
+ endif
+ endif
+
+# $(B)/client/jctrans.o \
+
+#platform specific objects
+ifeq ($(PLATFORM),freebsd)
+ Q3POBJ=\
+ $(B)/client/linux_common.o \
+ $(B)/client/linux_qgl.o \
+ $(B)/client/linux_glimp.o \
+ $(B)/client/linux_snd.o \
+ $(B)/client/snd_mixa.o \
+ $(B)/client/matha.o \
+ $(B)/client/ftol.o \
+ $(B)/client/snapvector.o
+else
+ifeq ($(PLATFORM),irix)
+ Q3POBJ=\
+ $(B)/client/irix_qgl.o \
+ $(B)/client/irix_glimp.o \
+ $(B)/client/irix_snd.o
+else
+ifeq ($(PLATFORM),linux)
+ifeq ($(ARCH),axp)
+ Q3POBJ=
+else
+ Q3POBJ=\
+ $(B)/client/linux_common.o \
+ $(B)/client/linux_qgl.o \
+ $(B)/client/linux_glimp.o \
+ $(B)/client/linux_joystick.o \
+ $(B)/client/linux_snd.o \
+ $(B)/client/snd_mixa.o \
+ $(B)/client/matha.o \
+
+ Q3POBJ_SMP=\
+ $(B)/client/linux_common.o \
+ $(B)/client/linux_qgl.o \
+ $(B)/client/linux_glimp_smp.o \
+ $(B)/client/linux_joystick.o \
+ $(B)/client/linux_snd.o \
+ $(B)/client/snd_mixa.o \
+ $(B)/client/matha.o
+
+ ifeq ($(ARCH),i386)
+ Q3POBJ += $(B)/client/ftol.o $(B)/client/snapvector.o
+ Q3POBJ_SMP += $(B)/client/ftol.o $(B)/client/snapvector.o
+ endif
+
+endif
+endif #Linux
+endif #FreeBSD
+endif #IRIX
+
+$(B)/$(PLATFORM)quake3 : $(Q3OBJ) $(Q3POBJ)
+ $(CC) -o $@ $(Q3OBJ) $(Q3POBJ) $(GLLDFLAGS) $(LDFLAGS)
+# TTimo: splines code requires C++ linking, but splines have not been officially included in the codebase
+# $(CXX) -o $@ $(Q3OBJ) $(Q3POBJ) $(GLLDFLAGS) $(LDFLAGS)
+
+$(B)/$(PLATFORM)quake3-smp : $(Q3OBJ) $(Q3POBJ_SMP)
+ $(CC) -o $@ $(Q3OBJ) $(Q3POBJ_SMP) $(GLLDFLAGS) \
+ $(THREAD_LDFLAGS) $(LDFLAGS)
+
+$(B)/client/cl_cgame.o : $(CDIR)/cl_cgame.c; $(DO_CC)
+$(B)/client/cl_cin.o : $(CDIR)/cl_cin.c; $(DO_CC)
+$(B)/client/cl_console.o : $(CDIR)/cl_console.c; $(DO_CC)
+$(B)/client/cl_input.o : $(CDIR)/cl_input.c; $(DO_CC)
+$(B)/client/cl_keys.o : $(CDIR)/cl_keys.c; $(DO_CC)
+$(B)/client/cl_main.o : $(CDIR)/cl_main.c; $(DO_CC)
+$(B)/client/cl_net_chan.o : $(CDIR)/cl_net_chan.c; $(DO_CC)
+$(B)/client/cl_parse.o : $(CDIR)/cl_parse.c; $(DO_CC)
+$(B)/client/cl_scrn.o : $(CDIR)/cl_scrn.c; $(DO_CC)
+$(B)/client/cl_ui.o : $(CDIR)/cl_ui.c; $(DO_CC)
+$(B)/client/snd_adpcm.o : $(CDIR)/snd_adpcm.c; $(DO_CC)
+$(B)/client/snd_dma.o : $(CDIR)/snd_dma.c; $(DO_CC)
+$(B)/client/snd_mem.o : $(CDIR)/snd_mem.c; $(DO_CC)
+$(B)/client/snd_mix.o : $(CDIR)/snd_mix.c; $(DO_CC)
+$(B)/client/snd_wavelet.o : $(CDIR)/snd_wavelet.c; $(DO_CC)
+$(B)/client/sv_bot.o : $(SDIR)/sv_bot.c; $(DO_CC)
+$(B)/client/sv_client.o : $(SDIR)/sv_client.c; $(DO_CC)
+$(B)/client/sv_ccmds.o : $(SDIR)/sv_ccmds.c; $(DO_CC)
+$(B)/client/sv_game.o : $(SDIR)/sv_game.c; $(DO_CC)
+$(B)/client/sv_init.o : $(SDIR)/sv_init.c; $(DO_CC)
+$(B)/client/sv_main.o : $(SDIR)/sv_main.c; $(DO_CC)
+$(B)/client/sv_net_chan.o : $(SDIR)/sv_net_chan.c; $(DO_CC)
+$(B)/client/sv_snapshot.o : $(SDIR)/sv_snapshot.c; $(DO_CC)
+$(B)/client/sv_world.o : $(SDIR)/sv_world.c; $(DO_CC)
+$(B)/client/cm_trace.o : $(CMDIR)/cm_trace.c; $(DO_CC)
+$(B)/client/cm_load.o : $(CMDIR)/cm_load.c; $(DO_CC)
+$(B)/client/cm_test.o : $(CMDIR)/cm_test.c; $(DO_CC)
+$(B)/client/cm_patch.o : $(CMDIR)/cm_patch.c; $(DO_CC)
+$(B)/client/cm_polylib.o : $(CMDIR)/cm_polylib.c; $(DO_CC)
+$(B)/client/cmd.o : $(CMDIR)/cmd.c; $(DO_CC)
+$(B)/client/common.o : $(CMDIR)/common.c; $(DO_CC)
+$(B)/client/cvar.o : $(CMDIR)/cvar.c; $(DO_CC)
+$(B)/client/files.o : $(CMDIR)/files.c; $(DO_CC)
+$(B)/client/md4.o : $(CMDIR)/md4.c; $(DO_CC)
+$(B)/client/msg.o : $(CMDIR)/msg.c; $(DO_CC)
+$(B)/client/net_chan.o : $(CMDIR)/net_chan.c; $(DO_CC)
+$(B)/client/huffman.o : $(CMDIR)/huffman.c; $(DO_CC)
+$(B)/client/q_shared.o : $(GDIR)/q_shared.c; $(DO_CC)
+$(B)/client/q_math.o : $(GDIR)/q_math.c; $(DO_CC)
+
+$(B)/client/be_aas_bspq3.o : $(BLIBDIR)/be_aas_bspq3.c; $(DO_BOT_CC)
+$(B)/client/be_aas_cluster.o : $(BLIBDIR)/be_aas_cluster.c; $(DO_BOT_CC)
+$(B)/client/be_aas_debug.o : $(BLIBDIR)/be_aas_debug.c; $(DO_BOT_CC)
+$(B)/client/be_aas_entity.o : $(BLIBDIR)/be_aas_entity.c; $(DO_BOT_CC)
+$(B)/client/be_aas_file.o : $(BLIBDIR)/be_aas_file.c; $(DO_BOT_CC)
+$(B)/client/be_aas_main.o : $(BLIBDIR)/be_aas_main.c; $(DO_BOT_CC)
+$(B)/client/be_aas_move.o : $(BLIBDIR)/be_aas_move.c; $(DO_BOT_CC)
+$(B)/client/be_aas_optimize.o : $(BLIBDIR)/be_aas_optimize.c; $(DO_BOT_CC)
+$(B)/client/be_aas_reach.o : $(BLIBDIR)/be_aas_reach.c; $(DO_BOT_CC)
+$(B)/client/be_aas_route.o : $(BLIBDIR)/be_aas_route.c; $(DO_BOT_CC)
+$(B)/client/be_aas_routealt.o : $(BLIBDIR)/be_aas_routealt.c; $(DO_BOT_CC)
+$(B)/client/be_aas_sample.o : $(BLIBDIR)/be_aas_sample.c; $(DO_BOT_CC)
+$(B)/client/be_ai_char.o : $(BLIBDIR)/be_ai_char.c; $(DO_BOT_CC)
+$(B)/client/be_ai_chat.o : $(BLIBDIR)/be_ai_chat.c; $(DO_BOT_CC)
+$(B)/client/be_ai_gen.o : $(BLIBDIR)/be_ai_gen.c; $(DO_BOT_CC)
+$(B)/client/be_ai_goal.o : $(BLIBDIR)/be_ai_goal.c; $(DO_BOT_CC)
+$(B)/client/be_ai_move.o : $(BLIBDIR)/be_ai_move.c; $(DO_BOT_CC)
+$(B)/client/be_ai_weap.o : $(BLIBDIR)/be_ai_weap.c; $(DO_BOT_CC)
+$(B)/client/be_ai_weight.o : $(BLIBDIR)/be_ai_weight.c; $(DO_BOT_CC)
+$(B)/client/be_ea.o : $(BLIBDIR)/be_ea.c; $(DO_BOT_CC)
+$(B)/client/be_interface.o : $(BLIBDIR)/be_interface.c; $(DO_BOT_CC)
+$(B)/client/l_crc.o : $(BLIBDIR)/l_crc.c; $(DO_BOT_CC)
+$(B)/client/l_libvar.o : $(BLIBDIR)/l_libvar.c; $(DO_BOT_CC)
+$(B)/client/l_log.o : $(BLIBDIR)/l_log.c; $(DO_BOT_CC)
+$(B)/client/l_memory.o : $(BLIBDIR)/l_memory.c; $(DO_BOT_CC)
+$(B)/client/l_precomp.o : $(BLIBDIR)/l_precomp.c; $(DO_BOT_CC)
+$(B)/client/l_script.o : $(BLIBDIR)/l_script.c; $(DO_BOT_CC)
+$(B)/client/l_struct.o : $(BLIBDIR)/l_struct.c; $(DO_BOT_CC)
+
+$(B)/client/jcapimin.o : $(JPDIR)/jcapimin.c; $(DO_CC)
+$(B)/client/jchuff.o : $(JPDIR)/jchuff.c; $(DO_CC)
+$(B)/client/jcinit.o : $(JPDIR)/jcinit.c; $(DO_CC)
+$(B)/client/jccoefct.o : $(JPDIR)/jccoefct.c; $(DO_CC)
+$(B)/client/jccolor.o : $(JPDIR)/jccolor.c; $(DO_CC)
+$(B)/client/jfdctflt.o : $(JPDIR)/jfdctflt.c; $(DO_CC)
+$(B)/client/jcdctmgr.o : $(JPDIR)/jcdctmgr.c; $(DO_CC)
+$(B)/client/jcmainct.o : $(JPDIR)/jcmainct.c; $(DO_CC)
+$(B)/client/jcmarker.o : $(JPDIR)/jcmarker.c; $(DO_CC)
+$(B)/client/jcmaster.o : $(JPDIR)/jcmaster.c; $(DO_CC)
+$(B)/client/jcomapi.o : $(JPDIR)/jcomapi.c; $(DO_CC)
+$(B)/client/jcparam.o : $(JPDIR)/jcparam.c; $(DO_CC)
+$(B)/client/jcprepct.o : $(JPDIR)/jcprepct.c; $(DO_CC)
+$(B)/client/jcsample.o : $(JPDIR)/jcsample.c; $(DO_CC)
+
+$(B)/client/jdapimin.o : $(JPDIR)/jdapimin.c; $(DO_CC)
+$(B)/client/jdapistd.o : $(JPDIR)/jdapistd.c; $(DO_CC)
+$(B)/client/jdatasrc.o : $(JPDIR)/jdatasrc.c; $(DO_CC)
+$(B)/client/jdcoefct.o : $(JPDIR)/jdcoefct.c; $(DO_CC)
+$(B)/client/jdcolor.o : $(JPDIR)/jdcolor.c; $(DO_CC)
+$(B)/client/jcphuff.o : $(JPDIR)/jcphuff.c; $(DO_CC)
+$(B)/client/jddctmgr.o : $(JPDIR)/jddctmgr.c; $(DO_CC)
+$(B)/client/jdhuff.o : $(JPDIR)/jdhuff.c; $(DO_CC)
+$(B)/client/jdinput.o : $(JPDIR)/jdinput.c; $(DO_CC)
+$(B)/client/jdmainct.o : $(JPDIR)/jdmainct.c; $(DO_CC)
+$(B)/client/jdmarker.o : $(JPDIR)/jdmarker.c; $(DO_CC)
+$(B)/client/jdmaster.o : $(JPDIR)/jdmaster.c; $(DO_CC)
+$(B)/client/jdpostct.o : $(JPDIR)/jdpostct.c; $(DO_CC)
+$(B)/client/jdsample.o : $(JPDIR)/jdsample.c; $(DO_CC)
+$(B)/client/jdtrans.o : $(JPDIR)/jdtrans.c; $(DO_CC)
+$(B)/client/jerror.o : $(JPDIR)/jerror.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/jidctflt.o : $(JPDIR)/jidctflt.c; $(DO_CC)
+$(B)/client/jmemmgr.o : $(JPDIR)/jmemmgr.c; $(DO_CC)
+$(B)/client/jmemnobs.o : $(JPDIR)/jmemnobs.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/jutils.o : $(JPDIR)/jutils.c; $(DO_CC)
+
+$(B)/client/tr_bsp.o : $(RDIR)/tr_bsp.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_animation.o : $(RDIR)/tr_animation.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_backend.o : $(RDIR)/tr_backend.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_cmds.o : $(RDIR)/tr_cmds.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_curve.o : $(RDIR)/tr_curve.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_flares.o : $(RDIR)/tr_flares.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_font.o : $(RDIR)/tr_font.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_image.o : $(RDIR)/tr_image.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_init.o : $(RDIR)/tr_init.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_light.o : $(RDIR)/tr_light.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_main.o : $(RDIR)/tr_main.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_marks.o : $(RDIR)/tr_marks.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_mesh.o : $(RDIR)/tr_mesh.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_model.o : $(RDIR)/tr_model.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_noise.o : $(RDIR)/tr_noise.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_scene.o : $(RDIR)/tr_scene.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_shade.o : $(RDIR)/tr_shade.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_shader.o : $(RDIR)/tr_shader.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_shade_calc.o : $(RDIR)/tr_shade_calc.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_shadows.o : $(RDIR)/tr_shadows.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_sky.o : $(RDIR)/tr_sky.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_smp.o : $(RDIR)/tr_smp.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_stripify.o : $(RDIR)/tr_stripify.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_subdivide.o : $(RDIR)/tr_subdivide.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_surface.o : $(RDIR)/tr_surface.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/tr_world.o : $(RDIR)/tr_world.c; $(DO_CC) $(GL_CFLAGS)
+
+$(B)/client/unix_qgl.o : $(UDIR)/unix_qgl.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/unix_main.o : $(UDIR)/unix_main.c; $(DO_CC)
+$(B)/client/unix_net.o : $(UDIR)/unix_net.c; $(DO_CC)
+$(B)/client/unix_shared.o : $(UDIR)/unix_shared.c; $(DO_CC)
+$(B)/client/irix_glimp.o : $(UDIR)/irix_glimp.c; $(DO_CC)
+$(B)/client/irix_glimp_smp.o : $(UDIR)/irix_glimp.c; $(DO_SMP_CC)
+$(B)/client/irix_snd.o : $(UDIR)/irix_snd.c; $(DO_CC)
+$(B)/client/irix_input.o : $(UDIR)/irix_input.c; $(DO_CC)
+$(B)/client/linux_common.o : $(UDIR)/linux_common.c; $(DO_CC)
+$(B)/client/linux_glimp.o : $(UDIR)/linux_glimp.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/linux_glimp_smp.o : $(UDIR)/linux_glimp.c; $(DO_SMP_CC) $(GL_CFLAGS)
+$(B)/client/linux_joystick.o : $(UDIR)/linux_joystick.c; $(DO_CC)
+$(B)/client/linux_qgl.o : $(UDIR)/linux_qgl.c; $(DO_CC) $(GL_CFLAGS)
+$(B)/client/linux_input.o : $(UDIR)/linux_input.c; $(DO_CC)
+$(B)/client/linux_snd.o : $(UDIR)/linux_snd.c; $(DO_CC)
+$(B)/client/snd_mixa.o : $(UDIR)/snd_mixa.s; $(DO_AS)
+$(B)/client/matha.o : $(UDIR)/matha.s; $(DO_AS)
+
+ifeq ($(ARCH),i386)
+$(B)/client/ftol.o : $(UDIR)/ftol.nasm; $(DO_NASM)
+$(B)/client/snapvector.o : $(UDIR)/snapvector.nasm; $(DO_NASM)
+$(B)/client/vm_x86.o : $(CMDIR)/vm_x86.c; $(DO_CC)
+endif
+
+ifeq ($(ARCH),ppc)
+ifeq ($(DLL_ONLY),false)
+$(B)/client/vm_ppc.o : $(CMDIR)/vm_ppc.c; $(DO_CC)
+endif
+endif
+
+$(B)/client/unzip.o : $(CMDIR)/unzip.c; $(DO_CC)
+$(B)/client/vm.o : $(CMDIR)/vm.c; $(DO_CC)
+$(B)/client/vm_interpreted.o : $(CMDIR)/vm_interpreted.c; $(DO_CC)
+
+$(B)/client/ahoptim.o : $(FTDIR)/ahoptim.c; $(DO_CC)
+$(B)/client/autohint.o : $(FTDIR)/autohint.c; $(DO_CC)
+$(B)/client/ftbase.o : $(FTDIR)/ftbase.c; $(DO_CC)
+$(B)/client/ftdebug.o : $(FTDIR)/ftdebug.c; $(DO_CC)
+$(B)/client/ftglyph.o : $(FTDIR)/ftglyph.c; $(DO_CC)
+$(B)/client/ftinit.o : $(FTDIR)/ftinit.c; $(DO_CC)
+$(B)/client/ftmm.o : $(FTDIR)/ftmm.c; $(DO_CC)
+$(B)/client/ftsystem.o : $(FTDIR)/ftsystem.c; $(DO_CC)
+$(B)/client/raster1.o : $(FTDIR)/raster1.c; $(DO_CC) -DFT_FLAT_COMPILE
+$(B)/client/sfnt.o : $(FTDIR)/sfnt.c; $(DO_CC)
+$(B)/client/sfobjs.o : $(FTDIR)/sfobjs.c; $(DO_CC)
+$(B)/client/smooth.o : $(FTDIR)/smooth.c; $(DO_CC) -DFT_FLAT_COMPILE
+$(B)/client/truetype.o : $(FTDIR)/truetype.c; $(DO_CC)
+
+# TTimo: took out splines code
+#$(B)/client/q_parse.o : $(SPLNDIR)/q_parse.cpp; $(DO_CXX)
+#$(B)/client/math_quaternion.o : $(SPLNDIR)/math_quaternion.cpp; $(DO_CXX)
+# TTimo: ignored
+#$(B)/client/q_shared.o : $(SPLNDIR)/q_shared.cpp; $(DO_CXX)
+#$(B)/client/util_str.o : $(SPLNDIR)/util_str.cpp; $(DO_CXX)
+#$(B)/client/math_angles.o : $(SPLNDIR)/math_angles.cpp; $(DO_CXX)
+#$(B)/client/math_vector.o : $(SPLNDIR)/math_vector.cpp; $(DO_CXX)
+#$(B)/client/splines.o : $(SPLNDIR)/splines.cpp; $(DO_CXX)
+#$(B)/client/math_matrix.o : $(SPLNDIR)/math_matrix.cpp; $(DO_CXX)
+
+## Included by raster1.c
+# $(B)/client/ftraster.o : $(FTDIR)/ftraster.c; $(DO_CC)
+# $(B)/client/ftrend1.o : $(FTDIR)/ftrend1.c; $(DO_CC)
+
+## Included by autohint.c
+# $(B)/client/ahangles.o : $(FTDIR)/ahangles.c; $(DO_CC)
+# $(B)/client/ahglyph.o : $(FTDIR)/ahglyph.c; $(DO_CC)
+# $(B)/client/ahglobal.o : $(FTDIR)/ahglobal.c; $(DO_CC)
+# $(B)/client/ahhint.o : $(FTDIR)/ahhint.c; $(DO_CC)
+# $(B)/client/ahmodule.o : $(FTDIR)/ahmodule.c; $(DO_CC)
+
+## Included by ftcalc.c
+# $(B)/client/ftcalc.o : $(FTDIR)/ftcalc.c; $(DO_CC)
+# $(B)/client/ftobjs.o : $(FTDIR)/ftobjs.c; $(DO_CC)
+# $(B)/client/ftstream.o : $(FTDIR)/ftstream.c; $(DO_CC)
+# $(B)/client/ftlist.o : $(FTDIR)/ftlist.c; $(DO_CC)
+# $(B)/client/ftoutln.o : $(FTDIR)/ftoutln.c; $(DO_CC)
+# $(B)/client/ftextend.o : $(FTDIR)/ftextend.c; $(DO_CC)
+# $(B)/client/ftnames.o : $(FTDIR)/ftnames.c; $(DO_CC)
+
+## Included by sfnt.c
+# $(B)/client/ttload.o : $(FTDIR)/ttload.c; $(DO_CC)
+# $(B)/client/ttcmap.o : $(FTDIR)/ttcmap.c; $(DO_CC)
+# $(B)/client/sfobjs.o : $(FTDIR)/sfobjs.c; $(DO_CC)
+# $(B)/client/sfdriver.o : $(FTDIR)/sfdriver.c; $(DO_CC)
+## Unused in sfnt.c
+# $(B)/client/ttpost.o : $(FTDIR)/ttpost.c; $(DO_CC)
+# $(B)/client/ttsbit.o : $(FTDIR)/ttsbit.c; $(DO_CC)
+
+## Included by truetype.c
+# $(B)/client/ttdriver.o : $(FTDIR)/ttdriver.c; $(DO_CC)
+# $(B)/client/ttgload.o : $(FTDIR)/ttgload.c; $(DO_CC)
+# $(B)/client/ttobjs.o : $(FTDIR)/ttobjs.c; $(DO_CC)
+# $(B)/client/ttpload.o : $(FTDIR)/ttpload.c; $(DO_CC)
+## Unused in truetype.c
+# $(B)/client/ttinterp.o : $(FTDIR)/ttinterp.c; $(DO_CC)
+
+## Included by smooth.c
+# $(B)/client/ftsmooth.o : $(FTDIR)/ftsmooth.c; $(DO_CC) -DFT_FLAT_COMPILE
+# $(B)/client/ftgrays.o : $(FTDIR)/ftgrays.c; $(DO_CC)
+
+#############################################################################
+# DEDICATED SERVER
+#############################################################################
+
+Q3DOBJ = \
+ $(B)/ded/sv_bot.o \
+ $(B)/ded/sv_client.o \
+ $(B)/ded/sv_ccmds.o \
+ $(B)/ded/sv_game.o \
+ $(B)/ded/sv_init.o \
+ $(B)/ded/sv_main.o \
+ $(B)/ded/sv_net_chan.o \
+ $(B)/ded/sv_snapshot.o \
+ $(B)/ded/sv_world.o \
+ \
+ $(B)/ded/cm_load.o \
+ $(B)/ded/cm_patch.o \
+ $(B)/ded/cm_polylib.o \
+ $(B)/ded/cm_test.o \
+ $(B)/ded/cm_trace.o \
+ $(B)/ded/cmd.o \
+ $(B)/ded/common.o \
+ $(B)/ded/cvar.o \
+ $(B)/ded/files.o \
+ $(B)/ded/md4.o \
+ $(B)/ded/msg.o \
+ $(B)/ded/net_chan.o \
+ $(B)/ded/huffman.o \
+ \
+ $(B)/ded/q_math.o \
+ $(B)/ded/q_shared.o \
+ \
+ $(B)/ded/unzip.o \
+ $(B)/ded/vm.o \
+ $(B)/ded/vm_interpreted.o \
+ \
+ $(B)/ded/be_aas_bspq3.o \
+ $(B)/ded/be_aas_cluster.o \
+ $(B)/ded/be_aas_debug.o \
+ $(B)/ded/be_aas_entity.o \
+ $(B)/ded/be_aas_file.o \
+ $(B)/ded/be_aas_main.o \
+ $(B)/ded/be_aas_move.o \
+ $(B)/ded/be_aas_optimize.o \
+ $(B)/ded/be_aas_reach.o \
+ $(B)/ded/be_aas_route.o \
+ $(B)/ded/be_aas_routealt.o \
+ $(B)/ded/be_aas_sample.o \
+ $(B)/ded/be_ai_char.o \
+ $(B)/ded/be_ai_chat.o \
+ $(B)/ded/be_ai_gen.o \
+ $(B)/ded/be_ai_goal.o \
+ $(B)/ded/be_ai_move.o \
+ $(B)/ded/be_ai_weap.o \
+ $(B)/ded/be_ai_weight.o \
+ $(B)/ded/be_ea.o \
+ $(B)/ded/be_interface.o \
+ $(B)/ded/l_crc.o \
+ $(B)/ded/l_libvar.o \
+ $(B)/ded/l_log.o \
+ $(B)/ded/l_memory.o \
+ $(B)/ded/l_precomp.o \
+ $(B)/ded/l_script.o \
+ $(B)/ded/l_struct.o \
+ \
+ $(B)/ded/linux_common.o \
+ $(B)/ded/unix_main.o \
+ $(B)/ded/unix_net.o \
+ $(B)/ded/unix_shared.o \
+ \
+ $(B)/ded/null_client.o \
+ $(B)/ded/null_input.o \
+ $(B)/ded/null_snddma.o
+
+ifeq ($(ARCH),i386)
+ Q3DOBJ += $(B)/ded/vm_x86.o $(B)/ded/ftol.o $(B)/ded/snapvector.o
+endif
+
+ifeq ($(ARCH),ppc)
+ ifeq ($(DLL_ONLY),false)
+ Q3DOBJ += $(B)/ded/vm_ppc.o
+ endif
+endif
+
+$(B)/$(PLATFORM)q3ded : $(Q3DOBJ)
+ $(CC) -o $@ $(Q3DOBJ) $(LDFLAGS)
+
+$(B)/ded/sv_bot.o : $(SDIR)/sv_bot.c; $(DO_DED_CC)
+$(B)/ded/sv_client.o : $(SDIR)/sv_client.c; $(DO_DED_CC)
+$(B)/ded/sv_ccmds.o : $(SDIR)/sv_ccmds.c; $(DO_DED_CC)
+$(B)/ded/sv_game.o : $(SDIR)/sv_game.c; $(DO_DED_CC)
+$(B)/ded/sv_init.o : $(SDIR)/sv_init.c; $(DO_DED_CC)
+$(B)/ded/sv_main.o : $(SDIR)/sv_main.c; $(DO_DED_CC)
+$(B)/ded/sv_net_chan.o : $(SDIR)/sv_net_chan.c; $(DO_DED_CC)
+$(B)/ded/sv_snapshot.o : $(SDIR)/sv_snapshot.c; $(DO_DED_CC)
+$(B)/ded/sv_world.o : $(SDIR)/sv_world.c; $(DO_DED_CC)
+$(B)/ded/cm_load.o : $(CMDIR)/cm_load.c; $(DO_DED_CC)
+$(B)/ded/cm_polylib.o : $(CMDIR)/cm_polylib.c; $(DO_DED_CC)
+$(B)/ded/cm_test.o : $(CMDIR)/cm_test.c; $(DO_DED_CC)
+$(B)/ded/cm_trace.o : $(CMDIR)/cm_trace.c; $(DO_DED_CC)
+$(B)/ded/cm_patch.o : $(CMDIR)/cm_patch.c; $(DO_DED_CC)
+$(B)/ded/cmd.o : $(CMDIR)/cmd.c; $(DO_DED_CC)
+$(B)/ded/common.o : $(CMDIR)/common.c; $(DO_DED_CC)
+$(B)/ded/cvar.o : $(CMDIR)/cvar.c; $(DO_DED_CC)
+$(B)/ded/files.o : $(CMDIR)/files.c; $(DO_DED_CC)
+$(B)/ded/md4.o : $(CMDIR)/md4.c; $(DO_DED_CC)
+$(B)/ded/msg.o : $(CMDIR)/msg.c; $(DO_DED_CC)
+$(B)/ded/net_chan.o : $(CMDIR)/net_chan.c; $(DO_DED_CC)
+$(B)/ded/huffman.o : $(CMDIR)/huffman.c; $(DO_DED_CC)
+$(B)/ded/q_shared.o : $(GDIR)/q_shared.c; $(DO_DED_CC)
+$(B)/ded/q_math.o : $(GDIR)/q_math.c; $(DO_DED_CC)
+
+$(B)/ded/be_aas_bspq3.o : $(BLIBDIR)/be_aas_bspq3.c; $(DO_BOT_CC)
+$(B)/ded/be_aas_cluster.o : $(BLIBDIR)/be_aas_cluster.c; $(DO_BOT_CC)
+$(B)/ded/be_aas_debug.o : $(BLIBDIR)/be_aas_debug.c; $(DO_BOT_CC)
+$(B)/ded/be_aas_entity.o : $(BLIBDIR)/be_aas_entity.c; $(DO_BOT_CC)
+$(B)/ded/be_aas_file.o : $(BLIBDIR)/be_aas_file.c; $(DO_BOT_CC)
+$(B)/ded/be_aas_main.o : $(BLIBDIR)/be_aas_main.c; $(DO_BOT_CC)
+$(B)/ded/be_aas_move.o : $(BLIBDIR)/be_aas_move.c; $(DO_BOT_CC)
+$(B)/ded/be_aas_optimize.o : $(BLIBDIR)/be_aas_optimize.c; $(DO_BOT_CC)
+$(B)/ded/be_aas_reach.o : $(BLIBDIR)/be_aas_reach.c; $(DO_BOT_CC)
+$(B)/ded/be_aas_route.o : $(BLIBDIR)/be_aas_route.c; $(DO_BOT_CC)
+$(B)/ded/be_aas_routealt.o : $(BLIBDIR)/be_aas_routealt.c; $(DO_BOT_CC)
+$(B)/ded/be_aas_sample.o : $(BLIBDIR)/be_aas_sample.c; $(DO_BOT_CC)
+$(B)/ded/be_ai_char.o : $(BLIBDIR)/be_ai_char.c; $(DO_BOT_CC)
+$(B)/ded/be_ai_chat.o : $(BLIBDIR)/be_ai_chat.c; $(DO_BOT_CC)
+$(B)/ded/be_ai_gen.o : $(BLIBDIR)/be_ai_gen.c; $(DO_BOT_CC)
+$(B)/ded/be_ai_goal.o : $(BLIBDIR)/be_ai_goal.c; $(DO_BOT_CC)
+$(B)/ded/be_ai_move.o : $(BLIBDIR)/be_ai_move.c; $(DO_BOT_CC)
+$(B)/ded/be_ai_weap.o : $(BLIBDIR)/be_ai_weap.c; $(DO_BOT_CC)
+$(B)/ded/be_ai_weight.o : $(BLIBDIR)/be_ai_weight.c; $(DO_BOT_CC)
+$(B)/ded/be_ea.o : $(BLIBDIR)/be_ea.c; $(DO_BOT_CC)
+$(B)/ded/be_interface.o : $(BLIBDIR)/be_interface.c; $(DO_BOT_CC)
+$(B)/ded/l_crc.o : $(BLIBDIR)/l_crc.c; $(DO_BOT_CC)
+$(B)/ded/l_libvar.o : $(BLIBDIR)/l_libvar.c; $(DO_BOT_CC)
+$(B)/ded/l_log.o : $(BLIBDIR)/l_log.c; $(DO_BOT_CC)
+$(B)/ded/l_memory.o : $(BLIBDIR)/l_memory.c; $(DO_BOT_CC)
+$(B)/ded/l_precomp.o : $(BLIBDIR)/l_precomp.c; $(DO_BOT_CC)
+$(B)/ded/l_script.o : $(BLIBDIR)/l_script.c; $(DO_BOT_CC)
+$(B)/ded/l_struct.o : $(BLIBDIR)/l_struct.c; $(DO_BOT_CC)
+
+$(B)/ded/linux_common.o : $(UDIR)/linux_common.c; $(DO_CC)
+$(B)/ded/unix_main.o : $(UDIR)/unix_main.c; $(DO_DED_CC)
+$(B)/ded/unix_net.o : $(UDIR)/unix_net.c; $(DO_DED_CC)
+$(B)/ded/unix_shared.o : $(UDIR)/unix_shared.c; $(DO_DED_CC)
+$(B)/ded/null_client.o : $(NDIR)/null_client.c; $(DO_DED_CC)
+$(B)/ded/null_input.o : $(NDIR)/null_input.c; $(DO_DED_CC)
+$(B)/ded/null_snddma.o : $(NDIR)/null_snddma.c; $(DO_DED_CC)
+$(B)/ded/unzip.o : $(CMDIR)/unzip.c; $(DO_DED_CC)
+$(B)/ded/vm.o : $(CMDIR)/vm.c; $(DO_DED_CC)
+$(B)/ded/vm_interpreted.o : $(CMDIR)/vm_interpreted.c; $(DO_DED_CC)
+
+ifeq ($(ARCH),i386)
+$(B)/ded/vm_x86.o : $(CMDIR)/vm_x86.c; $(DO_DED_CC)
+$(B)/ded/ftol.o : $(UDIR)/ftol.nasm; $(DO_NASM)
+$(B)/ded/snapvector.o : $(UDIR)/snapvector.nasm; $(DO_NASM)
+endif
+
+ifeq ($(ARCH),ppc)
+ifeq ($(DLL_ONLY),false)
+$(B)/ded/vm_ppc.o : $(CMDIR)/vm_ppc.c; $(DO_DED_CC)
+endif
+endif
+
+
+#############################################################################
+## QVM
+#############################################################################
+
+$(B)/baseq3/vm/cgame.qvm:
+ cd $(CGDIR) && ./cgame.sh
+ mv /tmp/quake3/baseq3/vm/cgame.qvm $@
+
+$(B)/baseq3/vm/ui.qvm:
+ cd $(Q3UIDIR) && ./q3_ui.sh
+ mv /tmp/quake3/baseq3/vm/ui.qvm $@
+
+$(B)/baseq3/vm/qagame.qvm:
+ cd $(GDIR) && ./game.sh
+ mv /tmp/quake3/baseq3/vm/qagame.qvm $@
+
+$(B)/missionpack/vm/cgame.qvm:
+ cd $(CGDIR) && ./cgame_ta.sh
+ mv /tmp/quake3/missionpack/vm/cgame.qvm $@
+
+$(B)/missionpack/vm/qagame.qvm:
+ cd $(GDIR) && ./game_ta.sh
+ mv /tmp/quake3/missionpack/vm/qagame.qvm $@
+
+$(B)/missionpack/vm/ui.qvm:
+ cd $(UIDIR) && ./ui.sh
+ mv /tmp/quake3/missionpack/vm/ui.qvm $@
+
+
+
+#############################################################################
+## BASEQ3 CGAME
+#############################################################################
+
+Q3CGOBJ = \
+ $(B)/baseq3/cgame/bg_misc.o \
+ $(B)/baseq3/cgame/bg_pmove.o \
+ $(B)/baseq3/cgame/bg_slidemove.o \
+ $(B)/baseq3/cgame/cg_consolecmds.o \
+ $(B)/baseq3/cgame/cg_draw.o \
+ $(B)/baseq3/cgame/cg_drawtools.o \
+ $(B)/baseq3/cgame/cg_effects.o \
+ $(B)/baseq3/cgame/cg_ents.o \
+ $(B)/baseq3/cgame/cg_event.o \
+ $(B)/baseq3/cgame/cg_info.o \
+ $(B)/baseq3/cgame/cg_localents.o \
+ $(B)/baseq3/cgame/cg_main.o \
+ $(B)/baseq3/cgame/cg_marks.o \
+ $(B)/baseq3/cgame/cg_players.o \
+ $(B)/baseq3/cgame/cg_playerstate.o \
+ $(B)/baseq3/cgame/cg_predict.o \
+ $(B)/baseq3/cgame/cg_scoreboard.o \
+ $(B)/baseq3/cgame/cg_servercmds.o \
+ $(B)/baseq3/cgame/cg_snapshot.o \
+ $(B)/baseq3/cgame/cg_syscalls.o \
+ $(B)/baseq3/cgame/cg_view.o \
+ $(B)/baseq3/cgame/cg_weapons.o \
+ $(B)/baseq3/cgame/q_math.o \
+ $(B)/baseq3/cgame/q_shared.o
+
+$(B)/baseq3/cgame$(ARCH).$(SHLIBEXT) : $(Q3CGOBJ)
+ $(CC) $(SHLIBLDFLAGS) -o $@ $(Q3CGOBJ)
+
+$(B)/baseq3/cgame/bg_misc.o : $(GDIR)/bg_misc.c; $(DO_SHLIB_CC)
+$(B)/baseq3/cgame/bg_pmove.o : $(GDIR)/bg_pmove.c; $(DO_SHLIB_CC)
+$(B)/baseq3/cgame/bg_slidemove.o : $(GDIR)/bg_slidemove.c; $(DO_SHLIB_CC)
+$(B)/baseq3/cgame/cg_consolecmds.o : $(CGDIR)/cg_consolecmds.c; $(DO_SHLIB_CC)
+$(B)/baseq3/cgame/cg_draw.o : $(CGDIR)/cg_draw.c; $(DO_SHLIB_CC)
+$(B)/baseq3/cgame/cg_drawtools.o : $(CGDIR)/cg_drawtools.c; $(DO_SHLIB_CC)
+$(B)/baseq3/cgame/cg_effects.o : $(CGDIR)/cg_effects.c; $(DO_SHLIB_CC)
+$(B)/baseq3/cgame/cg_ents.o : $(CGDIR)/cg_ents.c; $(DO_SHLIB_CC)
+$(B)/baseq3/cgame/cg_event.o : $(CGDIR)/cg_event.c; $(DO_SHLIB_CC)
+$(B)/baseq3/cgame/cg_info.o : $(CGDIR)/cg_info.c; $(DO_SHLIB_CC)
+$(B)/baseq3/cgame/cg_localents.o : $(CGDIR)/cg_localents.c; $(DO_SHLIB_CC)
+$(B)/baseq3/cgame/cg_main.o : $(CGDIR)/cg_main.c; $(DO_SHLIB_CC)
+$(B)/baseq3/cgame/cg_marks.o : $(CGDIR)/cg_marks.c; $(DO_SHLIB_CC)
+$(B)/baseq3/cgame/cg_players.o : $(CGDIR)/cg_players.c; $(DO_SHLIB_CC)
+$(B)/baseq3/cgame/cg_playerstate.o : $(CGDIR)/cg_playerstate.c; $(DO_SHLIB_CC)
+$(B)/baseq3/cgame/cg_predict.o : $(CGDIR)/cg_predict.c; $(DO_SHLIB_CC)
+$(B)/baseq3/cgame/cg_scoreboard.o : $(CGDIR)/cg_scoreboard.c; $(DO_SHLIB_CC)
+$(B)/baseq3/cgame/cg_servercmds.o : $(CGDIR)/cg_servercmds.c; $(DO_SHLIB_CC)
+$(B)/baseq3/cgame/cg_snapshot.o : $(CGDIR)/cg_snapshot.c; $(DO_SHLIB_CC)
+$(B)/baseq3/cgame/cg_syscalls.o : $(CGDIR)/cg_syscalls.c; $(DO_SHLIB_CC)
+$(B)/baseq3/cgame/cg_view.o : $(CGDIR)/cg_view.c; $(DO_SHLIB_CC)
+$(B)/baseq3/cgame/cg_weapons.o : $(CGDIR)/cg_weapons.c; $(DO_SHLIB_CC)
+$(B)/baseq3/cgame/q_math.o : $(GDIR)/q_math.c; $(DO_SHLIB_CC)
+$(B)/baseq3/cgame/q_shared.o : $(GDIR)/q_shared.c; $(DO_SHLIB_CC)
+
+#############################################################################
+## MISSIONPACK CGAME
+#############################################################################
+
+MPCGOBJ = \
+ $(B)/missionpack/cgame/bg_misc.o \
+ $(B)/missionpack/cgame/bg_pmove.o \
+ $(B)/missionpack/cgame/bg_slidemove.o \
+ $(B)/missionpack/cgame/cg_consolecmds.o \
+ $(B)/missionpack/cgame/cg_newdraw.o \
+ $(B)/missionpack/cgame/cg_draw.o \
+ $(B)/missionpack/cgame/cg_drawtools.o \
+ $(B)/missionpack/cgame/cg_effects.o \
+ $(B)/missionpack/cgame/cg_ents.o \
+ $(B)/missionpack/cgame/cg_event.o \
+ $(B)/missionpack/cgame/cg_info.o \
+ $(B)/missionpack/cgame/cg_localents.o \
+ $(B)/missionpack/cgame/cg_main.o \
+ $(B)/missionpack/cgame/cg_marks.o \
+ $(B)/missionpack/cgame/cg_players.o \
+ $(B)/missionpack/cgame/cg_playerstate.o \
+ $(B)/missionpack/cgame/cg_predict.o \
+ $(B)/missionpack/cgame/cg_scoreboard.o \
+ $(B)/missionpack/cgame/cg_servercmds.o \
+ $(B)/missionpack/cgame/cg_snapshot.o \
+ $(B)/missionpack/cgame/cg_syscalls.o \
+ $(B)/missionpack/cgame/cg_view.o \
+ $(B)/missionpack/cgame/cg_weapons.o \
+ $(B)/missionpack/cgame/q_math.o \
+ $(B)/missionpack/cgame/q_shared.o \
+ $(B)/missionpack/cgame/ui_shared.o
+
+$(B)/missionpack/cgame$(ARCH).$(SHLIBEXT) : $(MPCGOBJ)
+ $(CC) $(SHLIBLDFLAGS) -o $@ $(MPCGOBJ)
+
+$(B)/missionpack/cgame/bg_misc.o : $(GDIR)/bg_misc.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/bg_pmove.o : $(GDIR)/bg_pmove.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/bg_slidemove.o : $(GDIR)/bg_slidemove.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/cg_consolecmds.o : $(CGDIR)/cg_consolecmds.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/cg_newdraw.o : $(CGDIR)/cg_newdraw.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/cg_draw.o : $(CGDIR)/cg_draw.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/cg_drawtools.o : $(CGDIR)/cg_drawtools.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/cg_effects.o : $(CGDIR)/cg_effects.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/cg_ents.o : $(CGDIR)/cg_ents.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/cg_event.o : $(CGDIR)/cg_event.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/cg_info.o : $(CGDIR)/cg_info.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/cg_localents.o : $(CGDIR)/cg_localents.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/cg_main.o : $(CGDIR)/cg_main.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/cg_marks.o : $(CGDIR)/cg_marks.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/cg_players.o : $(CGDIR)/cg_players.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/cg_playerstate.o : $(CGDIR)/cg_playerstate.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/cg_predict.o : $(CGDIR)/cg_predict.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/cg_scoreboard.o : $(CGDIR)/cg_scoreboard.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/cg_servercmds.o : $(CGDIR)/cg_servercmds.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/cg_snapshot.o : $(CGDIR)/cg_snapshot.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/cg_syscalls.o : $(CGDIR)/cg_syscalls.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/cg_view.o : $(CGDIR)/cg_view.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/cg_weapons.o : $(CGDIR)/cg_weapons.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/q_math.o : $(GDIR)/q_math.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/q_shared.o : $(GDIR)/q_shared.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/cgame/ui_shared.o : $(UIDIR)/ui_shared.c; $(DO_SHLIB_CC) -DMISSIONPACK
+
+
+
+#############################################################################
+## BASEQ3 GAME
+#############################################################################
+
+Q3GOBJ = \
+ $(B)/baseq3/game/ai_chat.o \
+ $(B)/baseq3/game/ai_cmd.o \
+ $(B)/baseq3/game/ai_dmnet.o \
+ $(B)/baseq3/game/ai_dmq3.o \
+ $(B)/baseq3/game/ai_main.o \
+ $(B)/baseq3/game/ai_team.o \
+ $(B)/baseq3/game/ai_vcmd.o \
+ $(B)/baseq3/game/bg_misc.o \
+ $(B)/baseq3/game/bg_pmove.o \
+ $(B)/baseq3/game/bg_slidemove.o \
+ $(B)/baseq3/game/g_active.o \
+ $(B)/baseq3/game/g_arenas.o \
+ $(B)/baseq3/game/g_bot.o \
+ $(B)/baseq3/game/g_client.o \
+ $(B)/baseq3/game/g_cmds.o \
+ $(B)/baseq3/game/g_combat.o \
+ $(B)/baseq3/game/g_items.o \
+ $(B)/baseq3/game/g_main.o \
+ $(B)/baseq3/game/g_mem.o \
+ $(B)/baseq3/game/g_misc.o \
+ $(B)/baseq3/game/g_missile.o \
+ $(B)/baseq3/game/g_mover.o \
+ $(B)/baseq3/game/g_session.o \
+ $(B)/baseq3/game/g_spawn.o \
+ $(B)/baseq3/game/g_svcmds.o \
+ $(B)/baseq3/game/g_syscalls.o \
+ $(B)/baseq3/game/g_target.o \
+ $(B)/baseq3/game/g_team.o \
+ $(B)/baseq3/game/g_trigger.o \
+ $(B)/baseq3/game/g_utils.o \
+ $(B)/baseq3/game/g_weapon.o \
+ \
+ $(B)/baseq3/game/q_math.o \
+ $(B)/baseq3/game/q_shared.o
+
+$(B)/baseq3/qagame$(ARCH).$(SHLIBEXT) : $(Q3GOBJ)
+ $(CC) $(SHLIBLDFLAGS) -o $@ $(Q3GOBJ)
+
+$(B)/baseq3/game/ai_chat.o : $(GDIR)/ai_chat.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/ai_cmd.o : $(GDIR)/ai_cmd.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/ai_dmnet.o : $(GDIR)/ai_dmnet.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/ai_dmq3.o : $(GDIR)/ai_dmq3.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/ai_main.o : $(GDIR)/ai_main.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/ai_team.o : $(GDIR)/ai_team.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/ai_vcmd.o : $(GDIR)/ai_vcmd.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/bg_misc.o : $(GDIR)/bg_misc.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/bg_pmove.o : $(GDIR)/bg_pmove.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/bg_slidemove.o : $(GDIR)/bg_slidemove.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/g_active.o : $(GDIR)/g_active.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/g_arenas.o : $(GDIR)/g_arenas.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/g_bot.o : $(GDIR)/g_bot.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/g_client.o : $(GDIR)/g_client.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/g_cmds.o : $(GDIR)/g_cmds.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/g_combat.o : $(GDIR)/g_combat.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/g_items.o : $(GDIR)/g_items.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/g_main.o : $(GDIR)/g_main.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/g_mem.o : $(GDIR)/g_mem.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/g_misc.o : $(GDIR)/g_misc.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/g_missile.o : $(GDIR)/g_missile.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/g_mover.o : $(GDIR)/g_mover.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/g_session.o : $(GDIR)/g_session.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/g_spawn.o : $(GDIR)/g_spawn.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/g_svcmds.o : $(GDIR)/g_svcmds.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/g_syscalls.o : $(GDIR)/g_syscalls.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/g_target.o : $(GDIR)/g_target.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/g_team.o : $(GDIR)/g_team.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/g_trigger.o : $(GDIR)/g_trigger.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/g_utils.o : $(GDIR)/g_utils.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/g_weapon.o : $(GDIR)/g_weapon.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/q_math.o : $(GDIR)/q_math.c; $(DO_SHLIB_CC)
+$(B)/baseq3/game/q_shared.o : $(GDIR)/q_shared.c; $(DO_SHLIB_CC)
+
+
+#############################################################################
+## MISSIONPACK GAME
+#############################################################################
+
+MPGOBJ = \
+ $(B)/missionpack/game/ai_chat.o \
+ $(B)/missionpack/game/ai_cmd.o \
+ $(B)/missionpack/game/ai_dmnet.o \
+ $(B)/missionpack/game/ai_dmq3.o \
+ $(B)/missionpack/game/ai_main.o \
+ $(B)/missionpack/game/ai_team.o \
+ $(B)/missionpack/game/ai_vcmd.o \
+ $(B)/missionpack/game/bg_misc.o \
+ $(B)/missionpack/game/bg_pmove.o \
+ $(B)/missionpack/game/bg_slidemove.o \
+ $(B)/missionpack/game/g_active.o \
+ $(B)/missionpack/game/g_arenas.o \
+ $(B)/missionpack/game/g_bot.o \
+ $(B)/missionpack/game/g_client.o \
+ $(B)/missionpack/game/g_cmds.o \
+ $(B)/missionpack/game/g_combat.o \
+ $(B)/missionpack/game/g_items.o \
+ $(B)/missionpack/game/g_main.o \
+ $(B)/missionpack/game/g_mem.o \
+ $(B)/missionpack/game/g_misc.o \
+ $(B)/missionpack/game/g_missile.o \
+ $(B)/missionpack/game/g_mover.o \
+ $(B)/missionpack/game/g_session.o \
+ $(B)/missionpack/game/g_spawn.o \
+ $(B)/missionpack/game/g_svcmds.o \
+ $(B)/missionpack/game/g_syscalls.o \
+ $(B)/missionpack/game/g_target.o \
+ $(B)/missionpack/game/g_team.o \
+ $(B)/missionpack/game/g_trigger.o \
+ $(B)/missionpack/game/g_utils.o \
+ $(B)/missionpack/game/g_weapon.o \
+ \
+ $(B)/missionpack/game/q_math.o \
+ $(B)/missionpack/game/q_shared.o
+
+$(B)/missionpack/qagame$(ARCH).$(SHLIBEXT) : $(MPGOBJ)
+ $(CC) $(SHLIBLDFLAGS) -o $@ $(MPGOBJ)
+
+$(B)/missionpack/game/ai_chat.o : $(GDIR)/ai_chat.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/ai_cmd.o : $(GDIR)/ai_cmd.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/ai_dmnet.o : $(GDIR)/ai_dmnet.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/ai_dmq3.o : $(GDIR)/ai_dmq3.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/ai_main.o : $(GDIR)/ai_main.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/ai_team.o : $(GDIR)/ai_team.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/ai_vcmd.o : $(GDIR)/ai_vcmd.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/bg_misc.o : $(GDIR)/bg_misc.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/bg_pmove.o : $(GDIR)/bg_pmove.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/bg_slidemove.o : $(GDIR)/bg_slidemove.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/g_active.o : $(GDIR)/g_active.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/g_arenas.o : $(GDIR)/g_arenas.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/g_bot.o : $(GDIR)/g_bot.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/g_client.o : $(GDIR)/g_client.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/g_cmds.o : $(GDIR)/g_cmds.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/g_combat.o : $(GDIR)/g_combat.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/g_items.o : $(GDIR)/g_items.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/g_main.o : $(GDIR)/g_main.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/g_mem.o : $(GDIR)/g_mem.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/g_misc.o : $(GDIR)/g_misc.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/g_missile.o : $(GDIR)/g_missile.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/g_mover.o : $(GDIR)/g_mover.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/g_session.o : $(GDIR)/g_session.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/g_spawn.o : $(GDIR)/g_spawn.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/g_svcmds.o : $(GDIR)/g_svcmds.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/g_syscalls.o : $(GDIR)/g_syscalls.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/g_target.o : $(GDIR)/g_target.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/g_team.o : $(GDIR)/g_team.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/g_trigger.o : $(GDIR)/g_trigger.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/g_utils.o : $(GDIR)/g_utils.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/g_weapon.o : $(GDIR)/g_weapon.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/q_math.o : $(GDIR)/q_math.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/game/q_shared.o : $(GDIR)/q_shared.c; $(DO_SHLIB_CC) -DMISSIONPACK
+
+
+
+#############################################################################
+## BASEQ3 UI
+#############################################################################
+
+Q3UIOBJ = \
+ $(B)/baseq3/ui/bg_misc.o \
+ $(B)/baseq3/ui/ui_addbots.o \
+ $(B)/baseq3/ui/ui_atoms.o \
+ $(B)/baseq3/ui/ui_cdkey.o \
+ $(B)/baseq3/ui/ui_cinematics.o \
+ $(B)/baseq3/ui/ui_confirm.o \
+ $(B)/baseq3/ui/ui_connect.o \
+ $(B)/baseq3/ui/ui_controls2.o \
+ $(B)/baseq3/ui/ui_credits.o \
+ $(B)/baseq3/ui/ui_demo2.o \
+ $(B)/baseq3/ui/ui_display.o \
+ $(B)/baseq3/ui/ui_gameinfo.o \
+ $(B)/baseq3/ui/ui_ingame.o \
+ $(B)/baseq3/ui/ui_loadconfig.o \
+ $(B)/baseq3/ui/ui_main.o \
+ $(B)/baseq3/ui/ui_menu.o \
+ $(B)/baseq3/ui/ui_mfield.o \
+ $(B)/baseq3/ui/ui_mods.o \
+ $(B)/baseq3/ui/ui_network.o \
+ $(B)/baseq3/ui/ui_options.o \
+ $(B)/baseq3/ui/ui_playermodel.o \
+ $(B)/baseq3/ui/ui_players.o \
+ $(B)/baseq3/ui/ui_playersettings.o \
+ $(B)/baseq3/ui/ui_preferences.o \
+ $(B)/baseq3/ui/ui_qmenu.o \
+ $(B)/baseq3/ui/ui_removebots.o \
+ $(B)/baseq3/ui/ui_saveconfig.o \
+ $(B)/baseq3/ui/ui_serverinfo.o \
+ $(B)/baseq3/ui/ui_servers2.o \
+ $(B)/baseq3/ui/ui_setup.o \
+ $(B)/baseq3/ui/ui_sound.o \
+ $(B)/baseq3/ui/ui_sparena.o \
+ $(B)/baseq3/ui/ui_specifyserver.o \
+ $(B)/baseq3/ui/ui_splevel.o \
+ $(B)/baseq3/ui/ui_sppostgame.o \
+ $(B)/baseq3/ui/ui_spskill.o \
+ $(B)/baseq3/ui/ui_startserver.o \
+ $(B)/baseq3/ui/ui_syscalls.o \
+ $(B)/baseq3/ui/ui_team.o \
+ $(B)/baseq3/ui/ui_teamorders.o \
+ $(B)/baseq3/ui/ui_video.o \
+ \
+ $(B)/baseq3/ui/q_math.o \
+ $(B)/baseq3/ui/q_shared.o
+
+$(B)/baseq3/ui$(ARCH).$(SHLIBEXT) : $(Q3UIOBJ)
+ $(CC) $(CFLAGS) $(SHLIBLDFLAGS) -o $@ $(Q3UIOBJ)
+
+$(B)/baseq3/ui/bg_misc.o : $(GDIR)/bg_misc.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_addbots.o : $(Q3UIDIR)/ui_addbots.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_atoms.o : $(Q3UIDIR)/ui_atoms.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_cinematics.o : $(Q3UIDIR)/ui_cinematics.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_cdkey.o : $(Q3UIDIR)/ui_cdkey.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_confirm.o : $(Q3UIDIR)/ui_confirm.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_connect.o : $(Q3UIDIR)/ui_connect.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_controls2.o : $(Q3UIDIR)/ui_controls2.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_credits.o : $(Q3UIDIR)/ui_credits.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_demo2.o : $(Q3UIDIR)/ui_demo2.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_display.o : $(Q3UIDIR)/ui_display.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_gameinfo.o : $(Q3UIDIR)/ui_gameinfo.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_ingame.o : $(Q3UIDIR)/ui_ingame.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_loadconfig.o : $(Q3UIDIR)/ui_loadconfig.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_main.o : $(Q3UIDIR)/ui_main.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_menu.o : $(Q3UIDIR)/ui_menu.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_mfield.o : $(Q3UIDIR)/ui_mfield.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_mods.o : $(Q3UIDIR)/ui_mods.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_network.o : $(Q3UIDIR)/ui_network.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_options.o : $(Q3UIDIR)/ui_options.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_playermodel.o : $(Q3UIDIR)/ui_playermodel.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_players.o : $(Q3UIDIR)/ui_players.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_playersettings.o : $(Q3UIDIR)/ui_playersettings.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_preferences.o : $(Q3UIDIR)/ui_preferences.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_qmenu.o : $(Q3UIDIR)/ui_qmenu.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_quit.o : $(Q3UIDIR)/ui_quit.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_removebots.o : $(Q3UIDIR)/ui_removebots.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_saveconfig.o : $(Q3UIDIR)/ui_saveconfig.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_serverinfo.o : $(Q3UIDIR)/ui_serverinfo.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_servers2.o : $(Q3UIDIR)/ui_servers2.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_setup.o : $(Q3UIDIR)/ui_setup.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_sound.o : $(Q3UIDIR)/ui_sound.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_sparena.o : $(Q3UIDIR)/ui_sparena.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_specifyserver.o : $(Q3UIDIR)/ui_specifyserver.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_splevel.o : $(Q3UIDIR)/ui_splevel.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_sppostgame.o : $(Q3UIDIR)/ui_sppostgame.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_spskill.o : $(Q3UIDIR)/ui_spskill.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_startserver.o : $(Q3UIDIR)/ui_startserver.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_team.o : $(Q3UIDIR)/ui_team.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_teamorders.o : $(Q3UIDIR)/ui_teamorders.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_syscalls.o : $(Q3UIDIR)/ui_syscalls.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/ui_video.o : $(Q3UIDIR)/ui_video.c; $(DO_SHLIB_CC)
+
+# bk001205 - these wre the only SHLIB compiles in 1.17
+$(B)/baseq3/ui/q_math.o : $(GDIR)/q_math.c; $(DO_SHLIB_CC)
+$(B)/baseq3/ui/q_shared.o : $(GDIR)/q_shared.c; $(DO_SHLIB_CC)
+
+
+
+#############################################################################
+## MISSIONPACK UI
+#############################################################################
+
+MPUIOBJ = \
+ $(B)/missionpack/ui/ui_atoms.o \
+ $(B)/missionpack/ui/ui_gameinfo.o \
+ $(B)/missionpack/ui/ui_main.o \
+ $(B)/missionpack/ui/ui_players.o \
+ $(B)/missionpack/ui/ui_syscalls.o \
+ $(B)/missionpack/ui/ui_util.o \
+ $(B)/missionpack/ui/ui_shared.o \
+ \
+ $(B)/missionpack/ui/bg_misc.o \
+ \
+ $(B)/missionpack/ui/q_math.o \
+ $(B)/missionpack/ui/q_shared.o
+# $(B)/missionpack/ui/ui_atoms.o \
+# $(B)/missionpack/ui/ui_gameinfo.o \
+# $(B)/missionpack/ui/ui_main.o \
+# $(B)/missionpack/ui/ui_players.o \
+# $(B)/missionpack/ui/ui_syscalls.o \
+# $(B)/missionpack/ui/ui_util.o \
+# $(B)/missionpack/ui/ui_shared.o \
+# \
+# $(B)/missionpack/ui/bg_misc.o \
+# $(B)/missionpack/ui/bg_lib.o \
+# \
+# $(B)/missionpack/ui/q_math.o \
+# $(B)/missionpack/ui/q_shared.o
+
+$(B)/missionpack/ui$(ARCH).$(SHLIBEXT) : $(MPUIOBJ)
+ $(CC) $(CFLAGS) $(SHLIBLDFLAGS) -o $@ $(MPUIOBJ)
+
+$(B)/missionpack/ui/ui_atoms.o : $(UIDIR)/ui_atoms.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/ui/ui_gameinfo.o : $(UIDIR)/ui_gameinfo.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/ui/ui_main.o : $(UIDIR)/ui_main.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/ui/ui_players.o : $(UIDIR)/ui_players.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/ui/ui_syscalls.o : $(UIDIR)/ui_syscalls.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/ui/ui_util.o : $(UIDIR)/ui_util.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/ui/ui_shared.o : $(UIDIR)/ui_shared.c; $(DO_SHLIB_CC) -DMISSIONPACK
+
+$(B)/missionpack/ui/bg_misc.o : $(GDIR)/bg_misc.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/ui/bg_lib.o : $(GDIR)/bg_lib.c; $(DO_SHLIB_CC) -DMISSIONPACK
+
+$(B)/missionpack/ui/q_math.o : $(GDIR)/q_math.c; $(DO_SHLIB_CC) -DMISSIONPACK
+$(B)/missionpack/ui/q_shared.o : $(GDIR)/q_shared.c; $(DO_SHLIB_CC) -DMISSIONPACK
+
+
+
+
+
+#############################################################################
+## Q3 STATIC (DEBUG) BUILD
+#############################################################################
+
+Q3SOBJ = \
+ $(B)/q3static/cl_cgame.o \
+ $(B)/q3static/cl_cin.o \
+ $(B)/q3static/cl_console.o \
+ $(B)/q3static/cl_input.o \
+ $(B)/q3static/cl_keys.o \
+ $(B)/q3static/cl_main.o \
+ $(B)/q3static/cl_net_chan.o \
+ $(B)/q3static/cl_parse.o \
+ $(B)/q3static/cl_scrn.o \
+ $(B)/q3static/cl_ui.o \
+ \
+ $(B)/q3static/cm_load.o \
+ $(B)/q3static/cm_patch.o \
+ $(B)/q3static/cm_polylib.o \
+ $(B)/q3static/cm_test.o \
+ $(B)/q3static/cm_trace.o \
+ \
+ $(B)/q3static/cmd.o \
+ $(B)/q3static/common.o \
+ $(B)/q3static/cvar.o \
+ $(B)/q3static/files.o \
+ $(B)/q3static/md4.o \
+ $(B)/q3static/msg.o \
+ $(B)/q3static/net_chan.o \
+ \
+ $(B)/q3static/snd_adpcm.o \
+ $(B)/q3static/snd_dma.o \
+ $(B)/q3static/snd_mem.o \
+ $(B)/q3static/snd_mix.o \
+ $(B)/q3static/snd_wavelet.o \
+ \
+ $(B)/q3static/sv_bot.o \
+ $(B)/q3static/sv_ccmds.o \
+ $(B)/q3static/sv_client.o \
+ $(B)/q3static/sv_game.o \
+ $(B)/q3static/sv_init.o \
+ $(B)/q3static/sv_main.o \
+ $(B)/q3static/sv_net_chan.o \
+ $(B)/q3static/sv_snapshot.o \
+ $(B)/q3static/sv_world.o \
+ \
+ $(B)/q3static/unzip.o \
+ $(B)/q3static/vm.o \
+ $(B)/q3static/vm_interpreted.o \
+ \
+ $(B)/q3static/be_aas_bspq3.o \
+ $(B)/q3static/be_aas_cluster.o \
+ $(B)/q3static/be_aas_debug.o \
+ $(B)/q3static/be_aas_entity.o \
+ $(B)/q3static/be_aas_file.o \
+ $(B)/q3static/be_aas_main.o \
+ $(B)/q3static/be_aas_move.o \
+ $(B)/q3static/be_aas_optimize.o \
+ $(B)/q3static/be_aas_reach.o \
+ $(B)/q3static/be_aas_route.o \
+ $(B)/q3static/be_aas_routealt.o \
+ $(B)/q3static/be_aas_sample.o \
+ $(B)/q3static/be_ai_char.o \
+ $(B)/q3static/be_ai_chat.o \
+ $(B)/q3static/be_ai_gen.o \
+ $(B)/q3static/be_ai_goal.o \
+ $(B)/q3static/be_ai_move.o \
+ $(B)/q3static/be_ai_weap.o \
+ $(B)/q3static/be_ai_weight.o \
+ $(B)/q3static/be_ea.o \
+ $(B)/q3static/be_interface.o \
+ $(B)/q3static/l_crc.o \
+ $(B)/q3static/l_libvar.o \
+ $(B)/q3static/l_log.o \
+ $(B)/q3static/l_memory.o \
+ $(B)/q3static/l_precomp.o \
+ $(B)/q3static/l_script.o \
+ $(B)/q3static/l_struct.o \
+ \
+ $(B)/q3static/jcapimin.o \
+ $(B)/q3static/jchuff.o \
+ $(B)/q3static/jcinit.o \
+ $(B)/q3static/jccoefct.o \
+ $(B)/q3static/jccolor.o \
+ $(B)/q3static/jfdctflt.o \
+ $(B)/q3static/jcdctmgr.o \
+ $(B)/q3static/jcphuff.o \
+ $(B)/q3static/jcmainct.o \
+ $(B)/q3static/jcmarker.o \
+ $(B)/q3static/jcmaster.o \
+ $(B)/q3static/jcomapi.o \
+ $(B)/q3static/jcparam.o \
+ $(B)/q3static/jcprepct.o \
+ $(B)/q3static/jcsample.o \
+ $(B)/q3static/jdapimin.o \
+ $(B)/q3static/jdapistd.o \
+ $(B)/q3static/jdatasrc.o \
+ $(B)/q3static/jdcoefct.o \
+ $(B)/q3static/jdcolor.o \
+ $(B)/q3static/jddctmgr.o \
+ $(B)/q3static/jdhuff.o \
+ $(B)/q3static/jdinput.o \
+ $(B)/q3static/jdmainct.o \
+ $(B)/q3static/jdmarker.o \
+ $(B)/q3static/jdmaster.o \
+ $(B)/q3static/jdpostct.o \
+ $(B)/q3static/jdsample.o \
+ $(B)/q3static/jdtrans.o \
+ $(B)/q3static/jerror.o \
+ $(B)/q3static/jidctflt.o \
+ $(B)/q3static/jmemmgr.o \
+ $(B)/q3static/jmemnobs.o \
+ $(B)/q3static/jutils.o \
+ \
+ $(B)/q3static/tr_animation.o \
+ $(B)/q3static/tr_backend.o \
+ $(B)/q3static/tr_bsp.o \
+ $(B)/q3static/tr_cmds.o \
+ $(B)/q3static/tr_curve.o \
+ $(B)/q3static/tr_flares.o \
+ $(B)/q3static/tr_font.o \
+ $(B)/q3static/tr_image.o \
+ $(B)/q3static/tr_init.o \
+ $(B)/q3static/tr_light.o \
+ $(B)/q3static/tr_main.o \
+ $(B)/q3static/tr_marks.o \
+ $(B)/q3static/tr_mesh.o \
+ $(B)/q3static/tr_model.o \
+ $(B)/q3static/tr_noise.o \
+ $(B)/q3static/tr_scene.o \
+ $(B)/q3static/tr_shade.o \
+ $(B)/q3static/tr_shade_calc.o \
+ $(B)/q3static/tr_shader.o \
+ $(B)/q3static/tr_shadows.o \
+ $(B)/q3static/tr_sky.o \
+ $(B)/q3static/tr_surface.o \
+ $(B)/q3static/tr_world.o \
+ \
+ $(B)/q3static/unix_main.o \
+ $(B)/q3static/unix_net.o \
+ $(B)/q3static/unix_shared.o \
+ \
+ $(B)/q3static/ahoptim.o \
+ $(B)/q3static/autohint.o \
+ $(B)/q3static/ftbase.o \
+ $(B)/q3static/ftdebug.o \
+ $(B)/q3static/ftglyph.o \
+ $(B)/q3static/ftinit.o \
+ $(B)/q3static/ftmm.o \
+ $(B)/q3static/ftsystem.o \
+ $(B)/q3static/raster1.o \
+ $(B)/q3static/sfnt.o \
+ $(B)/q3static/sfobjs.o \
+ $(B)/q3static/smooth.o \
+ $(B)/q3static/truetype.o \
+ \
+ $(B)/q3static/linux_qgl.o \
+ $(B)/q3static/linux_glimp.o \
+ $(B)/q3static/linux_joystick.o \
+ $(B)/q3static/linux_snd.o \
+ $(B)/q3static/snd_mixa.o \
+ $(B)/q3static/matha.o
+
+ifeq ($(ARCH),i386)
+ Q3SOBJ += $(B)/q3static/vm_x86.o
+endif
+
+ifeq ($(ARCH),ppc)
+ ifeq ($(DLL_ONLY),false)
+ Q3SOBJ += $(B)/q3static/vm_ppc.o
+ endif
+endif
+
+
+$(B)/q3static/cl_cgame.o : $(CDIR)/cl_cgame.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cl_cin.o : $(CDIR)/cl_cin.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cl_console.o : $(CDIR)/cl_console.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cl_input.o : $(CDIR)/cl_input.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cl_keys.o : $(CDIR)/cl_keys.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cl_main.o : $(CDIR)/cl_main.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cl_net_chan.o : $(CDIR)/cl_net_chan.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cl_parse.o : $(CDIR)/cl_parse.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cl_scrn.o : $(CDIR)/cl_scrn.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cl_ui.o : $(CDIR)/cl_ui.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/snd_adpcm.o : $(CDIR)/snd_adpcm.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/snd_dma.o : $(CDIR)/snd_dma.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/snd_mem.o : $(CDIR)/snd_mem.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/snd_mix.o : $(CDIR)/snd_mix.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/snd_wavelet.o : $(CDIR)/snd_wavelet.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/sv_bot.o : $(SDIR)/sv_bot.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/sv_client.o : $(SDIR)/sv_client.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/sv_ccmds.o : $(SDIR)/sv_ccmds.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/sv_game.o : $(SDIR)/sv_game.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/sv_init.o : $(SDIR)/sv_init.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/sv_main.o : $(SDIR)/sv_main.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/sv_net_chan.o : $(SDIR)/sv_net_chan.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/sv_snapshot.o : $(SDIR)/sv_snapshot.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/sv_world.o : $(SDIR)/sv_world.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cm_trace.o : $(CMDIR)/cm_trace.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cm_load.o : $(CMDIR)/cm_load.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cm_test.o : $(CMDIR)/cm_test.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cm_patch.o : $(CMDIR)/cm_patch.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cm_polylib.o : $(CMDIR)/cm_polylib.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cmd.o : $(CMDIR)/cmd.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/common.o : $(CMDIR)/common.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cvar.o : $(CMDIR)/cvar.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/files.o : $(CMDIR)/files.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/md4.o : $(CMDIR)/md4.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/msg.o : $(CMDIR)/msg.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/net_chan.o : $(CMDIR)/net_chan.c; $(DO_CC) -DQ3_STATIC
+
+$(B)/q3static/be_aas_bspq3.o : $(BLIBDIR)/be_aas_bspq3.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/be_aas_cluster.o : $(BLIBDIR)/be_aas_cluster.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/be_aas_debug.o : $(BLIBDIR)/be_aas_debug.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/be_aas_entity.o : $(BLIBDIR)/be_aas_entity.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/be_aas_file.o : $(BLIBDIR)/be_aas_file.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/be_aas_main.o : $(BLIBDIR)/be_aas_main.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/be_aas_move.o : $(BLIBDIR)/be_aas_move.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/be_aas_optimize.o : $(BLIBDIR)/be_aas_optimize.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/be_aas_reach.o : $(BLIBDIR)/be_aas_reach.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/be_aas_route.o : $(BLIBDIR)/be_aas_route.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/be_aas_routealt.o : $(BLIBDIR)/be_aas_routealt.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/be_aas_sample.o : $(BLIBDIR)/be_aas_sample.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/be_ai_char.o : $(BLIBDIR)/be_ai_char.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/be_ai_chat.o : $(BLIBDIR)/be_ai_chat.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/be_ai_gen.o : $(BLIBDIR)/be_ai_gen.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/be_ai_goal.o : $(BLIBDIR)/be_ai_goal.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/be_ai_move.o : $(BLIBDIR)/be_ai_move.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/be_ai_weap.o : $(BLIBDIR)/be_ai_weap.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/be_ai_weight.o : $(BLIBDIR)/be_ai_weight.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/be_ea.o : $(BLIBDIR)/be_ea.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/be_interface.o : $(BLIBDIR)/be_interface.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/l_crc.o : $(BLIBDIR)/l_crc.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/l_libvar.o : $(BLIBDIR)/l_libvar.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/l_log.o : $(BLIBDIR)/l_log.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/l_memory.o : $(BLIBDIR)/l_memory.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/l_precomp.o : $(BLIBDIR)/l_precomp.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/l_script.o : $(BLIBDIR)/l_script.c; $(DO_BOT_CC) -DQ3_STATIC
+$(B)/q3static/l_struct.o : $(BLIBDIR)/l_struct.c; $(DO_BOT_CC) -DQ3_STATIC
+
+$(B)/q3static/jcapimin.o : $(JPDIR)/jcapimin.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jchuff.o : $(JPDIR)/jchuff.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jcinit.o : $(JPDIR)/jcinit.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jccoefct.o : $(JPDIR)/jccoefct.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jccolor.o : $(JPDIR)/jccolor.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jfdctflt.o : $(JPDIR)/jfdctflt.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jcdctmgr.o : $(JPDIR)/jcdctmgr.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jcmainct.o : $(JPDIR)/jcmainct.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jcmarker.o : $(JPDIR)/jcmarker.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jcmaster.o : $(JPDIR)/jcmaster.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jcomapi.o : $(JPDIR)/jcomapi.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jcparam.o : $(JPDIR)/jcparam.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jcprepct.o : $(JPDIR)/jcprepct.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jcsample.o : $(JPDIR)/jcsample.c; $(DO_CC) -DQ3_STATIC
+
+$(B)/q3static/jdapimin.o : $(JPDIR)/jdapimin.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jdapistd.o : $(JPDIR)/jdapistd.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jdatasrc.o : $(JPDIR)/jdatasrc.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jdcoefct.o : $(JPDIR)/jdcoefct.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jdcolor.o : $(JPDIR)/jdcolor.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jcphuff.o : $(JPDIR)/jcphuff.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jddctmgr.o : $(JPDIR)/jddctmgr.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jdhuff.o : $(JPDIR)/jdhuff.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jdinput.o : $(JPDIR)/jdinput.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jdmainct.o : $(JPDIR)/jdmainct.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jdmarker.o : $(JPDIR)/jdmarker.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jdmaster.o : $(JPDIR)/jdmaster.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jdpostct.o : $(JPDIR)/jdpostct.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jdsample.o : $(JPDIR)/jdsample.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jdtrans.o : $(JPDIR)/jdtrans.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jerror.o : $(JPDIR)/jerror.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jidctflt.o : $(JPDIR)/jidctflt.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jmemmgr.o : $(JPDIR)/jmemmgr.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jmemnobs.o : $(JPDIR)/jmemnobs.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/jutils.o : $(JPDIR)/jutils.c; $(DO_CC) -DQ3_STATIC
+
+$(B)/q3static/tr_bsp.o : $(RDIR)/tr_bsp.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_animation.o : $(RDIR)/tr_animation.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_backend.o : $(RDIR)/tr_backend.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_cmds.o : $(RDIR)/tr_cmds.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_curve.o : $(RDIR)/tr_curve.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_flares.o : $(RDIR)/tr_flares.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_font.o : $(RDIR)/tr_font.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_image.o : $(RDIR)/tr_image.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_init.o : $(RDIR)/tr_init.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_light.o : $(RDIR)/tr_light.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_main.o : $(RDIR)/tr_main.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_marks.o : $(RDIR)/tr_marks.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_mesh.o : $(RDIR)/tr_mesh.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_model.o : $(RDIR)/tr_model.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_noise.o : $(RDIR)/tr_noise.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_scene.o : $(RDIR)/tr_scene.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_shade.o : $(RDIR)/tr_shade.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_shader.o : $(RDIR)/tr_shader.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_shade_calc.o : $(RDIR)/tr_shade_calc.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_shadows.o : $(RDIR)/tr_shadows.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_sky.o : $(RDIR)/tr_sky.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_smp.o : $(RDIR)/tr_smp.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_stripify.o : $(RDIR)/tr_stripify.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_subdivide.o : $(RDIR)/tr_subdivide.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_surface.o : $(RDIR)/tr_surface.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/tr_world.o : $(RDIR)/tr_world.c; $(DO_CC) -DQ3_STATIC
+
+$(B)/q3static/unix_qgl.o : $(UDIR)/unix_qgl.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/unix_main.o : $(UDIR)/unix_main.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/unix_net.o : $(UDIR)/unix_net.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/unix_shared.o : $(UDIR)/unix_shared.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/linux_glimp.o : $(UDIR)/linux_glimp.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/linux_joystick.o : $(UDIR)/linux_joystick.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/linux_qgl.o : $(UDIR)/linux_qgl.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/linux_input.o : $(UDIR)/linux_input.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/linux_snd.o : $(UDIR)/linux_snd.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/snd_mixa.o : $(UDIR)/snd_mixa.s; $(DO_AS)
+$(B)/q3static/matha.o : $(UDIR)/matha.s; $(DO_AS)
+$(B)/q3static/unzip.o : $(CMDIR)/unzip.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/vm.o : $(CMDIR)/vm.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/vm_interpreted.o : $(CMDIR)/vm_interpreted.c; $(DO_CC) -DQ3_STATIC
+
+ifeq ($(ARCH),i386)
+ $(B)/q3static/vm_x86.o : $(CMDIR)/vm_x86.c; $(DO_CC) -DQ3_STATIC
+endif
+
+ifeq ($(ARCH),ppc)
+ifeq ($(DLL_ONLY),false)
+$(B)/q3static/vm_ppc.o : $(CMDIR)/vm_ppc.c; $(DO_CC) -DQ3_STATIC
+endif
+endif
+
+$(B)/q3static/ahoptim.o : $(FTDIR)/ahoptim.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/autohint.o : $(FTDIR)/autohint.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ftbase.o : $(FTDIR)/ftbase.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ftdebug.o : $(FTDIR)/ftdebug.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ftglyph.o : $(FTDIR)/ftglyph.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ftinit.o : $(FTDIR)/ftinit.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ftmm.o : $(FTDIR)/ftmm.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ftsystem.o : $(FTDIR)/ftsystem.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/raster1.o : $(FTDIR)/raster1.c; $(DO_CC) -DQ3_STATIC -DFT_FLAT_COMPILE
+$(B)/q3static/sfnt.o : $(FTDIR)/sfnt.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/sfobjs.o : $(FTDIR)/sfobjs.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/smooth.o : $(FTDIR)/smooth.c; $(DO_CC) -DQ3_STATIC -DFT_FLAT_COMPILE
+$(B)/q3static/truetype.o : $(FTDIR)/truetype.c; $(DO_CC) -DQ3_STATIC
+
+## add BASEQ3 CGAME
+Q3SOBJ += \
+ $(B)/q3static/cg_consolecmds.o \
+ $(B)/q3static/cg_draw.o \
+ $(B)/q3static/cg_drawtools.o \
+ $(B)/q3static/cg_effects.o \
+ $(B)/q3static/cg_ents.o \
+ $(B)/q3static/cg_event.o \
+ $(B)/q3static/cg_info.o \
+ $(B)/q3static/cg_localents.o \
+ $(B)/q3static/cg_main.o \
+ $(B)/q3static/cg_marks.o \
+ $(B)/q3static/cg_players.o \
+ $(B)/q3static/cg_playerstate.o \
+ $(B)/q3static/cg_predict.o \
+ $(B)/q3static/cg_scoreboard.o \
+ $(B)/q3static/cg_servercmds.o \
+ $(B)/q3static/cg_snapshot.o \
+ $(B)/q3static/cg_syscalls.o \
+ $(B)/q3static/cg_view.o \
+ $(B)/q3static/cg_weapons.o
+
+$(B)/q3static/cg_consolecmds.o : $(CGDIR)/cg_consolecmds.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cg_draw.o : $(CGDIR)/cg_draw.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cg_drawtools.o : $(CGDIR)/cg_drawtools.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cg_effects.o : $(CGDIR)/cg_effects.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cg_ents.o : $(CGDIR)/cg_ents.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cg_event.o : $(CGDIR)/cg_event.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cg_info.o : $(CGDIR)/cg_info.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cg_localents.o : $(CGDIR)/cg_localents.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cg_main.o : $(CGDIR)/cg_main.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cg_marks.o : $(CGDIR)/cg_marks.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cg_players.o : $(CGDIR)/cg_players.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cg_playerstate.o : $(CGDIR)/cg_playerstate.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cg_predict.o : $(CGDIR)/cg_predict.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cg_scoreboard.o : $(CGDIR)/cg_scoreboard.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cg_servercmds.o : $(CGDIR)/cg_servercmds.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cg_snapshot.o : $(CGDIR)/cg_snapshot.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cg_syscalls.o : $(CGDIR)/cg_syscalls.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cg_view.o : $(CGDIR)/cg_view.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/cg_weapons.o : $(CGDIR)/cg_weapons.c; $(DO_CC) -DQ3_STATIC
+
+## add BASEQ3 GAME
+Q3SOBJ += \
+ $(B)/q3static/ai_chat.o \
+ $(B)/q3static/ai_cmd.o \
+ $(B)/q3static/ai_dmnet.o \
+ $(B)/q3static/ai_dmq3.o \
+ $(B)/q3static/ai_main.o \
+ $(B)/q3static/ai_team.o \
+ $(B)/q3static/ai_vcmd.o \
+ $(B)/q3static/g_active.o \
+ $(B)/q3static/g_arenas.o \
+ $(B)/q3static/g_bot.o \
+ $(B)/q3static/g_client.o \
+ $(B)/q3static/g_cmds.o \
+ $(B)/q3static/g_combat.o \
+ $(B)/q3static/g_items.o \
+ $(B)/q3static/g_main.o \
+ $(B)/q3static/g_mem.o \
+ $(B)/q3static/g_misc.o \
+ $(B)/q3static/g_missile.o \
+ $(B)/q3static/g_mover.o \
+ $(B)/q3static/g_session.o \
+ $(B)/q3static/g_spawn.o \
+ $(B)/q3static/g_svcmds.o \
+ $(B)/q3static/g_target.o \
+ $(B)/q3static/g_team.o \
+ $(B)/q3static/g_trigger.o \
+ $(B)/q3static/g_utils.o \
+ $(B)/q3static/g_weapon.o \
+ \
+ $(B)/q3static/g_syscalls.o
+
+$(B)/q3static/ai_chat.o : $(GDIR)/ai_chat.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ai_cmd.o : $(GDIR)/ai_cmd.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ai_dmnet.o : $(GDIR)/ai_dmnet.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ai_dmq3.o : $(GDIR)/ai_dmq3.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ai_main.o : $(GDIR)/ai_main.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ai_team.o : $(GDIR)/ai_team.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ai_vcmd.o : $(GDIR)/ai_vcmd.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/g_active.o : $(GDIR)/g_active.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/g_arenas.o : $(GDIR)/g_arenas.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/g_bot.o : $(GDIR)/g_bot.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/g_client.o : $(GDIR)/g_client.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/g_cmds.o : $(GDIR)/g_cmds.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/g_combat.o : $(GDIR)/g_combat.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/g_items.o : $(GDIR)/g_items.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/g_main.o : $(GDIR)/g_main.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/g_mem.o : $(GDIR)/g_mem.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/g_misc.o : $(GDIR)/g_misc.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/g_missile.o : $(GDIR)/g_missile.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/g_mover.o : $(GDIR)/g_mover.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/g_session.o : $(GDIR)/g_session.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/g_spawn.o : $(GDIR)/g_spawn.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/g_svcmds.o : $(GDIR)/g_svcmds.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/g_syscalls.o : $(GDIR)/g_syscalls.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/g_target.o : $(GDIR)/g_target.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/g_team.o : $(GDIR)/g_team.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/g_trigger.o : $(GDIR)/g_trigger.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/g_utils.o : $(GDIR)/g_utils.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/g_weapon.o : $(GDIR)/g_weapon.c; $(DO_CC) -DQ3_STATIC
+
+## add BASEQ3 UI
+Q3SOBJ += \
+ $(B)/q3static/ui_addbots.o \
+ $(B)/q3static/ui_atoms.o \
+ $(B)/q3static/ui_cdkey.o \
+ $(B)/q3static/ui_cinematics.o \
+ $(B)/q3static/ui_confirm.o \
+ $(B)/q3static/ui_connect.o \
+ $(B)/q3static/ui_controls2.o \
+ $(B)/q3static/ui_credits.o \
+ $(B)/q3static/ui_demo2.o \
+ $(B)/q3static/ui_display.o \
+ $(B)/q3static/ui_gameinfo.o \
+ $(B)/q3static/ui_ingame.o \
+ $(B)/q3static/ui_loadconfig.o \
+ $(B)/q3static/ui_main.o \
+ $(B)/q3static/ui_menu.o \
+ $(B)/q3static/ui_mfield.o \
+ $(B)/q3static/ui_mods.o \
+ $(B)/q3static/ui_network.o \
+ $(B)/q3static/ui_options.o \
+ $(B)/q3static/ui_playermodel.o \
+ $(B)/q3static/ui_players.o \
+ $(B)/q3static/ui_playersettings.o \
+ $(B)/q3static/ui_preferences.o \
+ $(B)/q3static/ui_qmenu.o \
+ $(B)/q3static/ui_removebots.o \
+ $(B)/q3static/ui_saveconfig.o \
+ $(B)/q3static/ui_serverinfo.o \
+ $(B)/q3static/ui_servers2.o \
+ $(B)/q3static/ui_setup.o \
+ $(B)/q3static/ui_sound.o \
+ $(B)/q3static/ui_sparena.o \
+ $(B)/q3static/ui_specifyserver.o \
+ $(B)/q3static/ui_splevel.o \
+ $(B)/q3static/ui_sppostgame.o \
+ $(B)/q3static/ui_spskill.o \
+ $(B)/q3static/ui_startserver.o \
+ $(B)/q3static/ui_team.o \
+ $(B)/q3static/ui_teamorders.o \
+ $(B)/q3static/ui_video.o \
+ \
+ $(B)/q3static/ui_syscalls.o
+
+$(B)/q3static/ui_addbots.o : $(Q3UIDIR)/ui_addbots.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_atoms.o : $(Q3UIDIR)/ui_atoms.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_cinematics.o : $(Q3UIDIR)/ui_cinematics.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_cdkey.o : $(Q3UIDIR)/ui_cdkey.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_confirm.o : $(Q3UIDIR)/ui_confirm.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_connect.o : $(Q3UIDIR)/ui_connect.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_controls2.o : $(Q3UIDIR)/ui_controls2.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_credits.o : $(Q3UIDIR)/ui_credits.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_demo2.o : $(Q3UIDIR)/ui_demo2.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_display.o : $(Q3UIDIR)/ui_display.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_gameinfo.o : $(Q3UIDIR)/ui_gameinfo.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_ingame.o : $(Q3UIDIR)/ui_ingame.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_loadconfig.o : $(Q3UIDIR)/ui_loadconfig.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_main.o : $(Q3UIDIR)/ui_main.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_menu.o : $(Q3UIDIR)/ui_menu.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_mfield.o : $(Q3UIDIR)/ui_mfield.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_mods.o : $(Q3UIDIR)/ui_mods.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_network.o : $(Q3UIDIR)/ui_network.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_options.o : $(Q3UIDIR)/ui_options.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_playermodel.o : $(Q3UIDIR)/ui_playermodel.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_players.o : $(Q3UIDIR)/ui_players.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_playersettings.o : $(Q3UIDIR)/ui_playersettings.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_preferences.o : $(Q3UIDIR)/ui_preferences.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_qmenu.o : $(Q3UIDIR)/ui_qmenu.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_quit.o : $(Q3UIDIR)/ui_quit.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_removebots.o : $(Q3UIDIR)/ui_removebots.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_saveconfig.o : $(Q3UIDIR)/ui_saveconfig.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_serverinfo.o : $(Q3UIDIR)/ui_serverinfo.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_servers2.o : $(Q3UIDIR)/ui_servers2.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_setup.o : $(Q3UIDIR)/ui_setup.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_sound.o : $(Q3UIDIR)/ui_sound.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_sparena.o : $(Q3UIDIR)/ui_sparena.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_specifyserver.o : $(Q3UIDIR)/ui_specifyserver.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_splevel.o : $(Q3UIDIR)/ui_splevel.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_sppostgame.o : $(Q3UIDIR)/ui_sppostgame.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_spskill.o : $(Q3UIDIR)/ui_spskill.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_startserver.o : $(Q3UIDIR)/ui_startserver.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_team.o : $(Q3UIDIR)/ui_team.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_teamorders.o : $(Q3UIDIR)/ui_teamorders.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_syscalls.o : $(Q3UIDIR)/ui_syscalls.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/ui_video.o : $(Q3UIDIR)/ui_video.c; $(DO_CC) -DQ3_STATIC
+
+
+## add shared files
+Q3SOBJ += \
+ $(B)/q3static/bg_misc.o \
+ $(B)/q3static/bg_pmove.o \
+ $(B)/q3static/bg_slidemove.o \
+ $(B)/q3static/q_math.o \
+ $(B)/q3static/q_shared.o
+
+## shared files
+$(B)/q3static/q_math.o : $(GDIR)/q_math.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/q_shared.o : $(GDIR)/q_shared.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/bg_misc.o : $(GDIR)/bg_misc.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/bg_pmove.o : $(GDIR)/bg_pmove.c; $(DO_CC) -DQ3_STATIC
+$(B)/q3static/bg_slidemove.o : $(GDIR)/bg_slidemove.c; $(DO_CC) -DQ3_STATIC
+
+
+
+$(B)/$(PLATFORM)q3static : $(Q3SOBJ)
+ $(CC) $(CFLAGS) -o $@ $(Q3SOBJ) $(GLLDFLAGS) $(LDFLAGS)
+
+
+#############################################################################
+# RPM
+#############################################################################
+
+TMPDIR=/var/tmp
+TARDIR=$(TMPDIR)/$(BUILD_NAME)
+TARFILE = $(BUILD_NAME)-$(VERSION)-$(RPM_RELEASE).$(ARCH).tar
+
+tar:
+ if [ ! -d archives ];then mkdir archives;chmod 755 archives;fi
+ $(MAKE) copyfiles COPYDIR=$(TARDIR)
+ cd $(TARDIR); tar cvf $(TARFILE) * && gzip -9 $(TARFILE)
+ mv $(TARDIR)/$(TARFILE).gz archives/.
+ rm -rf $(TARDIR)
+
+# Make RPMs. You need to be root to make this work
+RPMROOT=/usr/src/redhat
+RPM = rpm
+RPMFLAGS = -bb
+INSTALLDIR = /usr/local/games/$(BUILD_NAME)
+RPMDIR = $(TMPDIR)/$(BUILD_NAME)-$(VERSION)
+DESTDIR= $(RPMDIR)/$(INSTALLDIR)
+
+rpm: $(BUILD_NAME).spec
+ touch $(RPMROOT)/SOURCES/$(BUILD_NAME)-$(VERSION).tar.gz
+ if [ ! -d archives ];then mkdir archives;fi
+ $(MAKE) copyfiles COPYDIR=$(DESTDIR)
+ cp $(UDIR)/quake3.gif $(RPMROOT)/SOURCES/.
+ cp $(BUILD_NAME).spec $(RPMROOT)/SPECS/.
+ cd $(RPMROOT)/SPECS; $(RPM) $(RPMFLAGS) $(BUILD_NAME).spec
+ rm -rf $(RPMDIR)
+ mv $(RPMROOT)/RPMS/$(RPMARCH)/$(BUILD_NAME)-$(VERSION)-$(RPM_RELEASE).$(RPMARCH).rpm archives/$(BUILD_NAME)-$(VERSION)-$(RPM_RELEASE).$(RPMARCH).rpm
+
+copyfiles:
+ -mkdirhier $(COPYDIR)
+ cp $(BR)/linuxquake3 $(COPYDIR)/quake3.x86
+ strip $(COPYDIR)/quake3.x86
+ chmod 755 $(COPYDIR)/quake3.x86
+ cp $(BR)/linuxq3ded $(COPYDIR)/q3ded
+ strip $(COPYDIR)/q3ded
+ chmod 755 $(COPYDIR)/q3ded
+ cp $(BDIR)/libMesaVoodooGL.so.3.2 $(COPYDIR)/.
+ chmod 755 $(COPYDIR)/libMesaVoodooGL.so.3.2
+ ( cd $(COPYDIR); ln -s libMesaVoodooGL.so.3.2 libMesaVoodooGL.so )
+ cp $(BDIR)/Quake_III_Arena_FAQ.html $(COPYDIR)/.
+ chmod 644 $(COPYDIR)/Quake_III_Arena_FAQ.html
+ mkdir $(COPYDIR)/baseq3
+ cp $(BASEQ3_DIR)/pak2.pk3 $(COPYDIR)/baseq3/.
+ chmod 644 $(COPYDIR)/baseq3/pak2.pk3
+
+$(BUILD_NAME).spec : $(UDIR)/$(BUILD_NAME).spec.sh Makefile
+ sh $< $(VERSION) $(RPM_RELEASE) $(ARCH) $(INSTALLDIR) > $@
+
+#############################################################################
+# MISC
+#############################################################################
+
+# TTimo: FIXME: doesn't clean the binary and .so
+
+clean:clean-debug clean-release
+
+clean2: clean-bins
+ rm -f $(Q3OBJ) $(Q3POBJ) $(Q3POBJ_SMP) $(Q3DOBJ) $(MPGOBJ) $(Q3GOBJ) $(Q3CGOBJ) $(MPCGOBJ) $(Q3UIOBJ) $(MPUIOBJ)
+ rm -f $(CGDIR)/vm/*.asm
+ rm -f $(GDIR)/vm/*.asm
+ rm -f $(UIDIR)/vm/*.asm
+ rm -f $(Q3UIDIR)/vm/*.asm
+
+# TTimo: linuxq3ded linuxquake3 linuxquake3-smp .. hardcoded the names .. maybe not such a good thing
+# FIXME: also, removing the *.so is crappy .. I just want to avoid rm -rf debugi386-glibc to save the symlinks to pk3's for testing
+clean-bins:
+ if [ -d $(B) ];then (find $(B) -name '*.so' -exec rm {} \;)fi
+ rm -f $(B)/linuxq3ded
+ rm -f $(B)/linuxquake3
+ rm -f $(B)/linuxquake3-smp
+ rm -f $(B)/baseq3/vm/cgame.qvm
+ rm -f $(B)/baseq3/vm/ui.qvm
+ rm -f $(B)/baseq3/vm/qagame.qvm
+ rm -f $(B)/missionpack/vm/cgame.qvm
+ rm -f $(B)/missionpack/vm/qagame.qvm
+ rm -f $(B)/missionpack/vm/ui.qvm
+
+clean-debug:
+ $(MAKE) clean2 B=$(BD) CFLAGS="$(DEBUG_CFLAGS)"
+
+clean-release:
+ $(MAKE) clean2 B=$(BR) CFLAGS="$(DEBUG_CFLAGS)"
+
+# TTimo: for the setups it's easier to shell out to a script
+
+setup: release
+ ./build_setup.sh $(VERSION)
+
diff --git a/code/unix/Makefile.Game b/code/unix/Makefile.Game
new file mode 100755
index 0000000..8da0219
--- /dev/null
+++ b/code/unix/Makefile.Game
@@ -0,0 +1,285 @@
+#
+# Quake3 Unix Game Makefile
+#
+# GNU Make required
+#
+
+###
+### These paths are where you probably want to change things
+###
+
+#The main Quake3 directory
+BDIR=..
+
+#This is the game dir
+GAMEDIR=baseq3
+
+#Where the source is, assumed to be same directory as this Makefile
+SRCDIR=.
+
+#Location of binaries
+BINDIR=../bin
+LCC=$(BINDIR)/lcc # -lccdir=$(BINDIR)/
+Q3ASM=$(BINDIR)/q3asm
+
+
+#############################################################################
+##
+## You shouldn't have to touch anything below here
+##
+#############################################################################
+
+GDIR=$(SRCDIR)/game
+CGDIR=$(SRCDIR)/cgame
+UIDIR=$(SRCDIR)/ui
+
+LCCFLAGS=-DQ3_VM -S -Wf-target=bytecode -Wf-g -I..\cgame -I..\game -I..\ui
+
+DO_LCC=$(LCC) $(LCCFLAGS) -o $@ -c $<
+
+TARGETS=\
+ $(BDIR)/$(GAMEDIR)/vm/cgame.qvm \
+ $(BDIR)/$(GAMEDIR)/vm/qagame.qvm \
+ $(BDIR)/$(GAMEDIR)/vm/ui.qvm
+
+default: makedir $(TARGETS)
+
+makedir:
+ @-mkdir $(GDIR)/vm
+ @-mkdir $(CGDIR)/vm
+ @-mkdir $(UIDIR)/vm
+
+#############################################################################
+# GAME VM
+#############################################################################
+
+##NOTE: g_main must be first. Control passes to first function in the vm
+
+GVMASM = \
+ $(GDIR)/vm/g_main.asm \
+ $(GDIR)/vm/bg_misc.asm \
+ $(GDIR)/vm/bg_lib.asm \
+ $(GDIR)/vm/bg_pmove.asm \
+ $(GDIR)/vm/bg_slidemove.asm \
+ $(GDIR)/vm/q_math.asm \
+ $(GDIR)/vm/q_shared.asm \
+ $(GDIR)/vm/ai_dmnet.asm \
+ $(GDIR)/vm/ai_dmq3.asm \
+ $(GDIR)/vm/ai_team.asm \
+ $(GDIR)/vm/ai_main.asm \
+ $(GDIR)/vm/ai_chat.asm \
+ $(GDIR)/vm/ai_cmd.asm \
+ $(GDIR)/vm/g_active.asm \
+ $(GDIR)/vm/g_arenas.asm \
+ $(GDIR)/vm/g_bot.asm \
+ $(GDIR)/vm/g_client.asm \
+ $(GDIR)/vm/g_cmds.asm \
+ $(GDIR)/vm/g_combat.asm \
+ $(GDIR)/vm/g_items.asm \
+ $(GDIR)/vm/g_mem.asm \
+ $(GDIR)/vm/g_misc.asm \
+ $(GDIR)/vm/g_missile.asm \
+ $(GDIR)/vm/g_mover.asm \
+ $(GDIR)/vm/g_session.asm \
+ $(GDIR)/vm/g_spawn.asm \
+ $(GDIR)/vm/g_svcmds.asm \
+ $(GDIR)/vm/g_target.asm \
+ $(GDIR)/vm/g_team.asm \
+ $(GDIR)/vm/g_trigger.asm \
+ $(GDIR)/vm/g_utils.asm \
+ $(GDIR)/vm/g_weapon.asm
+
+$(BDIR)/$(GAMEDIR)/vm/qagame.qvm : $(GVMASM)
+ $(Q3ASM) -o $@ $(GVMASM) $(SRCDIR)/game/g_syscalls.asm
+
+$(GDIR)/vm/ai_chat.asm : $(GDIR)/ai_chat.c; $(DO_LCC)
+$(GDIR)/vm/ai_cmd.asm : $(GDIR)/ai_cmd.c; $(DO_LCC)
+$(GDIR)/vm/ai_dmnet.asm : $(GDIR)/ai_dmnet.c; $(DO_LCC)
+$(GDIR)/vm/ai_dmq3.asm : $(GDIR)/ai_dmq3.c; $(DO_LCC)
+$(GDIR)/vm/ai_main.asm : $(GDIR)/ai_main.c; $(DO_LCC)
+$(GDIR)/vm/ai_team.asm : $(GDIR)/ai_team.c; $(DO_LCC)
+$(GDIR)/vm/bg_lib.asm : $(GDIR)/bg_lib.c; $(DO_LCC)
+$(GDIR)/vm/bg_misc.asm : $(GDIR)/bg_misc.c; $(DO_LCC)
+$(GDIR)/vm/bg_pmove.asm : $(GDIR)/bg_pmove.c; $(DO_LCC)
+$(GDIR)/vm/bg_slidemove.asm : $(GDIR)/bg_slidemove.c; $(DO_LCC)
+$(GDIR)/vm/g_active.asm : $(GDIR)/g_active.c; $(DO_LCC)
+$(GDIR)/vm/g_arenas.asm : $(GDIR)/g_arenas.c; $(DO_LCC)
+$(GDIR)/vm/g_bot.asm : $(GDIR)/g_bot.c; $(DO_LCC)
+$(GDIR)/vm/g_client.asm : $(GDIR)/g_client.c; $(DO_LCC)
+$(GDIR)/vm/g_cmds.asm : $(GDIR)/g_cmds.c; $(DO_LCC)
+$(GDIR)/vm/g_combat.asm : $(GDIR)/g_combat.c; $(DO_LCC)
+$(GDIR)/vm/g_items.asm : $(GDIR)/g_items.c; $(DO_LCC)
+$(GDIR)/vm/g_main.asm : $(GDIR)/g_main.c; $(DO_LCC)
+$(GDIR)/vm/g_mem.asm : $(GDIR)/g_mem.c; $(DO_LCC)
+$(GDIR)/vm/g_misc.asm : $(GDIR)/g_misc.c; $(DO_LCC)
+$(GDIR)/vm/g_missile.asm : $(GDIR)/g_missile.c; $(DO_LCC)
+$(GDIR)/vm/g_mover.asm : $(GDIR)/g_mover.c; $(DO_LCC)
+$(GDIR)/vm/g_session.asm : $(GDIR)/g_session.c; $(DO_LCC)
+$(GDIR)/vm/g_spawn.asm : $(GDIR)/g_spawn.c; $(DO_LCC)
+$(GDIR)/vm/g_svcmds.asm : $(GDIR)/g_svcmds.c; $(DO_LCC)
+$(GDIR)/vm/g_target.asm : $(GDIR)/g_target.c; $(DO_LCC)
+$(GDIR)/vm/g_team.asm : $(GDIR)/g_team.c; $(DO_LCC)
+$(GDIR)/vm/g_trigger.asm : $(GDIR)/g_trigger.c; $(DO_LCC)
+$(GDIR)/vm/g_utils.asm : $(GDIR)/g_utils.c; $(DO_LCC)
+$(GDIR)/vm/g_weapon.asm : $(GDIR)/g_weapon.c; $(DO_LCC)
+$(GDIR)/vm/q_math.asm : $(GDIR)/q_math.c; $(DO_LCC)
+$(GDIR)/vm/q_shared.asm : $(GDIR)/q_shared.c; $(DO_LCC)
+
+$(BDIR)/$(GAMEDIR)/vm/cgame.qvm :
+ echo cgame.qvm disabled
+
+$(BDIR)/$(GAMEDIR)/vm/ui.qvm :
+ echo ui.qvm disabled
+
+#############################################################################
+# CGAME
+#############################################################################
+
+CGOBJ = \
+ $(SRCDIR)/cgame/bg_lib.o \
+ $(SRCDIR)/cgame/bg_misc.o \
+ $(SRCDIR)/cgame/bg_pmove.o \
+ $(SRCDIR)/cgame/bg_slidemove.o \
+ $(SRCDIR)/cgame/cg_consolecmds.o \
+ $(SRCDIR)/cgame/cg_draw.o \
+ $(SRCDIR)/cgame/cg_drawtools.o \
+ $(SRCDIR)/cgame/cg_effects.o \
+ $(SRCDIR)/cgame/cg_ents.o \
+ $(SRCDIR)/cgame/cg_event.o \
+ $(SRCDIR)/cgame/cg_info.o \
+ $(SRCDIR)/cgame/cg_localents.o \
+ $(SRCDIR)/cgame/cg_main.o \
+ $(SRCDIR)/cgame/cg_marks.o \
+ $(SRCDIR)/cgame/cg_players.o \
+ $(SRCDIR)/cgame/cg_playerstate.o \
+ $(SRCDIR)/cgame/cg_predict.o \
+ $(SRCDIR)/cgame/cg_scoreboard.o \
+ $(SRCDIR)/cgame/cg_servercmds.o \
+ $(SRCDIR)/cgame/cg_snapshot.o \
+ $(SRCDIR)/cgame/cg_view.o \
+ $(SRCDIR)/cgame/cg_weapons.o \
+ $(SRCDIR)/cgame/q_math.o \
+ $(SRCDIR)/cgame/q_shared.o
+
+$(SRCDIR)/cgame$(ARCH).$(SHLIBEXT) : $(CGOBJ)
+ $(CC) $(CFLAGS) $(SHLIBLDFLAGS) -o $@ $(CGOBJ)
+
+$(SRCDIR)/cgame/bg_lib.o : $(GDIR)/bg_lib.c; $(DO_SHLIB_CC)
+$(SRCDIR)/cgame/bg_misc.o : $(GDIR)/bg_misc.c; $(DO_SHLIB_CC)
+$(SRCDIR)/cgame/bg_pmove.o : $(GDIR)/bg_pmove.c; $(DO_SHLIB_CC)
+$(SRCDIR)/cgame/bg_slidemove.o : $(GDIR)/bg_slidemove.c; $(DO_SHLIB_CC)
+$(SRCDIR)/cgame/cg_consolecmds.o : $(CGDIR)/cg_consolecmds.c; $(DO_SHLIB_CC)
+$(SRCDIR)/cgame/cg_draw.o : $(CGDIR)/cg_draw.c; $(DO_SHLIB_CC)
+$(SRCDIR)/cgame/cg_drawtools.o : $(CGDIR)/cg_drawtools.c; $(DO_SHLIB_CC)
+$(SRCDIR)/cgame/cg_effects.o : $(CGDIR)/cg_effects.c; $(DO_SHLIB_CC)
+$(SRCDIR)/cgame/cg_ents.o : $(CGDIR)/cg_ents.c; $(DO_SHLIB_CC)
+$(SRCDIR)/cgame/cg_event.o : $(CGDIR)/cg_event.c; $(DO_SHLIB_CC)
+$(SRCDIR)/cgame/cg_info.o : $(CGDIR)/cg_info.c; $(DO_SHLIB_CC)
+$(SRCDIR)/cgame/cg_localents.o : $(CGDIR)/cg_localents.c; $(DO_SHLIB_CC)
+$(SRCDIR)/cgame/cg_main.o : $(CGDIR)/cg_main.c; $(DO_SHLIB_CC)
+$(SRCDIR)/cgame/cg_marks.o : $(CGDIR)/cg_marks.c; $(DO_SHLIB_CC)
+$(SRCDIR)/cgame/cg_players.o : $(CGDIR)/cg_players.c; $(DO_SHLIB_CC)
+$(SRCDIR)/cgame/cg_playerstate.o : $(CGDIR)/cg_playerstate.c; $(DO_SHLIB_CC)
+$(SRCDIR)/cgame/cg_predict.o : $(CGDIR)/cg_predict.c; $(DO_SHLIB_CC)
+$(SRCDIR)/cgame/cg_scoreboard.o : $(CGDIR)/cg_scoreboard.c; $(DO_SHLIB_CC)
+$(SRCDIR)/cgame/cg_servercmds.o : $(CGDIR)/cg_servercmds.c; $(DO_SHLIB_CC)
+$(SRCDIR)/cgame/cg_snapshot.o : $(CGDIR)/cg_snapshot.c; $(DO_SHLIB_CC)
+$(SRCDIR)/cgame/cg_view.o : $(CGDIR)/cg_view.c; $(DO_SHLIB_CC)
+$(SRCDIR)/cgame/cg_weapons.o : $(CGDIR)/cg_weapons.c; $(DO_SHLIB_CC)
+$(SRCDIR)/cgame/q_math.o : $(GDIR)/q_math.c; $(DO_SHLIB_CC)
+$(SRCDIR)/cgame/q_shared.o : $(GDIR)/q_shared.c; $(DO_SHLIB_CC)
+
+#############################################################################
+# UI
+#############################################################################
+
+UIOBJ = \
+ $(SRCDIR)/ui/bg_lib.o \
+ $(SRCDIR)/ui/bg_misc.o \
+ $(SRCDIR)/ui/ui_addbots.o \
+ $(SRCDIR)/ui/ui_atoms.o \
+ $(SRCDIR)/ui/ui_cinematics.o \
+ $(SRCDIR)/ui/ui_confirm.o \
+ $(SRCDIR)/ui/ui_connect.o \
+ $(SRCDIR)/ui/ui_controls2.o \
+ $(SRCDIR)/ui/ui_credits.o \
+ $(SRCDIR)/ui/ui_demo2.o \
+ $(SRCDIR)/ui/ui_display.o \
+ $(SRCDIR)/ui/ui_gameinfo.o \
+ $(SRCDIR)/ui/ui_ingame.o \
+ $(SRCDIR)/ui/ui_loadconfig.o \
+ $(SRCDIR)/ui/ui_main.o \
+ $(SRCDIR)/ui/ui_menu.o \
+ $(SRCDIR)/ui/ui_mfield.o \
+ $(SRCDIR)/ui/ui_network.o \
+ $(SRCDIR)/ui/ui_playermodel.o \
+ $(SRCDIR)/ui/ui_players.o \
+ $(SRCDIR)/ui/ui_playersettings.o \
+ $(SRCDIR)/ui/ui_preferences.o \
+ $(SRCDIR)/ui/ui_qmenu.o \
+ $(SRCDIR)/ui/ui_saveconfig.o \
+ $(SRCDIR)/ui/ui_serverinfo.o \
+ $(SRCDIR)/ui/ui_servers2.o \
+ $(SRCDIR)/ui/ui_setup.o \
+ $(SRCDIR)/ui/ui_sound.o \
+ $(SRCDIR)/ui/ui_sparena.o \
+ $(SRCDIR)/ui/ui_specifyserver.o \
+ $(SRCDIR)/ui/ui_splevel.o \
+ $(SRCDIR)/ui/ui_sppostgame.o \
+ $(SRCDIR)/ui/ui_spskill.o \
+ $(SRCDIR)/ui/ui_startserver.o \
+ $(SRCDIR)/ui/ui_team.o \
+ $(SRCDIR)/ui/ui_video.o \
+ \
+ $(SRCDIR)/ui/q_math.o \
+ $(SRCDIR)/ui/q_shared.o
+
+$(SRCDIR)/ui$(ARCH).$(SHLIBEXT) : $(UIOBJ)
+ $(CC) $(CFLAGS) $(SHLIBLDFLAGS) -o $@ $(UIOBJ)
+
+$(SRCDIR)/ui/bg_lib.o : $(GDIR)/bg_lib.c; $(DO_CC)
+$(SRCDIR)/ui/bg_misc.o : $(GDIR)/bg_misc.c; $(DO_CC)
+$(SRCDIR)/ui/ui_addbots.o : $(UIDIR)/ui_addbots.c; $(DO_CC)
+$(SRCDIR)/ui/ui_atoms.o : $(UIDIR)/ui_atoms.c; $(DO_CC)
+$(SRCDIR)/ui/ui_cinematics.o : $(UIDIR)/ui_cinematics.c; $(DO_CC)
+$(SRCDIR)/ui/ui_confirm.o : $(UIDIR)/ui_confirm.c; $(DO_CC)
+$(SRCDIR)/ui/ui_connect.o : $(UIDIR)/ui_connect.c; $(DO_CC)
+$(SRCDIR)/ui/ui_controls2.o : $(UIDIR)/ui_controls2.c; $(DO_CC)
+$(SRCDIR)/ui/ui_credits.o : $(UIDIR)/ui_credits.c; $(DO_CC)
+$(SRCDIR)/ui/ui_demo2.o : $(UIDIR)/ui_demo2.c; $(DO_CC)
+$(SRCDIR)/ui/ui_display.o : $(UIDIR)/ui_display.c; $(DO_CC)
+$(SRCDIR)/ui/ui_gameinfo.o : $(UIDIR)/ui_gameinfo.c; $(DO_CC)
+$(SRCDIR)/ui/ui_ingame.o : $(UIDIR)/ui_ingame.c; $(DO_CC)
+$(SRCDIR)/ui/ui_loadconfig.o : $(UIDIR)/ui_loadconfig.c; $(DO_CC)
+$(SRCDIR)/ui/ui_main.o : $(UIDIR)/ui_main.c; $(DO_CC)
+$(SRCDIR)/ui/ui_menu.o : $(UIDIR)/ui_menu.c; $(DO_CC)
+$(SRCDIR)/ui/ui_mfield.o : $(UIDIR)/ui_mfield.c; $(DO_CC)
+$(SRCDIR)/ui/ui_network.o : $(UIDIR)/ui_network.c; $(DO_CC)
+$(SRCDIR)/ui/ui_playermodel.o : $(UIDIR)/ui_playermodel.c; $(DO_CC)
+$(SRCDIR)/ui/ui_players.o : $(UIDIR)/ui_players.c; $(DO_CC)
+$(SRCDIR)/ui/ui_playersettings.o : $(UIDIR)/ui_playersettings.c; $(DO_CC)
+$(SRCDIR)/ui/ui_preferences.o : $(UIDIR)/ui_preferences.c; $(DO_CC)
+$(SRCDIR)/ui/ui_qmenu.o : $(UIDIR)/ui_qmenu.c; $(DO_CC)
+$(SRCDIR)/ui/ui_quit.o : $(UIDIR)/ui_quit.c; $(DO_CC)
+$(SRCDIR)/ui/ui_saveconfig.o : $(UIDIR)/ui_saveconfig.c; $(DO_CC)
+$(SRCDIR)/ui/ui_serverinfo.o : $(UIDIR)/ui_serverinfo.c; $(DO_CC)
+$(SRCDIR)/ui/ui_servers2.o : $(UIDIR)/ui_servers2.c; $(DO_CC)
+$(SRCDIR)/ui/ui_setup.o : $(UIDIR)/ui_setup.c; $(DO_CC)
+$(SRCDIR)/ui/ui_sound.o : $(UIDIR)/ui_sound.c; $(DO_CC)
+$(SRCDIR)/ui/ui_sparena.o : $(UIDIR)/ui_sparena.c; $(DO_CC)
+$(SRCDIR)/ui/ui_specifyserver.o : $(UIDIR)/ui_specifyserver.c; $(DO_CC)
+$(SRCDIR)/ui/ui_splevel.o : $(UIDIR)/ui_splevel.c; $(DO_CC)
+$(SRCDIR)/ui/ui_sppostgame.o : $(UIDIR)/ui_sppostgame.c; $(DO_CC)
+$(SRCDIR)/ui/ui_spskill.o : $(UIDIR)/ui_spskill.c; $(DO_CC)
+$(SRCDIR)/ui/ui_startserver.o : $(UIDIR)/ui_startserver.c; $(DO_CC)
+$(SRCDIR)/ui/ui_team.o : $(UIDIR)/ui_team.c; $(DO_CC)
+$(SRCDIR)/ui/ui_video.o : $(UIDIR)/ui_video.c; $(DO_CC)
+$(SRCDIR)/ui/q_math.o : $(GDIR)/q_math.c; $(DO_SHLIB_CC)
+$(SRCDIR)/ui/q_shared.o : $(GDIR)/q_shared.c; $(DO_SHLIB_CC)
+
+#############################################################################
+# MISC
+#############################################################################
+
+clean:
+ rm -f $(GVMASM)
diff --git a/code/unix/Quake3.kdelnk b/code/unix/Quake3.kdelnk
new file mode 100755
index 0000000..a4327ce
--- /dev/null
+++ b/code/unix/Quake3.kdelnk
@@ -0,0 +1,12 @@
+# KDE Config File
+[KDE Desktop Entry]
+Name=Quake3
+Name[C]=Quake3
+MimeType=
+Exec=/usr/local/games/quake3/linuxquake3
+Comment=Quake3: Arena by id Software
+Icon=quake3.xpm
+TerminalOptions=
+Path=
+Type=Application
+Terminal=0
diff --git a/code/unix/README.EULA b/code/unix/README.EULA
new file mode 100755
index 0000000..9b28721
--- /dev/null
+++ b/code/unix/README.EULA
@@ -0,0 +1,184 @@
+ LIMITED COMPATIBILITY TESTING AND RECREATIONAL
+ USE SOFTWARE TEST LICENSE AGREEMENT
+
+This Limited Compatibility Testing and Recreational Use Software Test
+License Agreement (the "Agreement") is a legal agreement between you, the
+end-user, and Id Software, Inc. ("ID"). BY CONTINUING THE INSTALLATION
+OF THIS TEST VERSION OF THE GAME PROGRAM ENTITLED QUAKE III: ARENA (THE
+"SOFTWARE"), BY LOADING OR RUNNING THE SOFTWARE, OR BY PLACING OR COPYING
+THE SOFTWARE ONTO YOUR COMPUTER HARD DRIVE, COMPUTER RAM OR OTHER STORAGE,
+YOU ARE AGREEING TO BE BOUND BY THE TERMS OF THIS AGREEMENT.
+
+1. Grant of License. Subject to the terms and provisions of this
+Agreement, ID grants to you the non-exclusive limited right to use this
+Software only in executable or object code form and only for the purpose
+of testing the compatibility of your computer system with the Software
+and for non-commercial, recreational purposes. The term "Software"
+includes all elements of the Software such as data files and screen
+displays. You are not receiving any ownership or proprietary right,
+title or interest in or to the Software or the copyright, trademarks, or
+other rights related thereto. For purposes of this section, "use" means
+loading the Software into RAM and/or onto computer hard drive, as well
+as installation of the Software on a hard disk or other storage device.
+You agree that the Software will not be shipped, transferred or exported
+into any country in violation of the U.S. Export Administration Act (or
+any other law governing such matters) by you or anyone at your direction
+and that you will not utilize and will not authorize anyone to utilize,
+in any other manner, the Software in violation of any applicable law.
+The Software may not be downloaded or otherwise exported or reexported
+into (or to a national or resident of) any country to which the U.S. has
+embargoed goods or to anyone or into any country who/which are prohibited,
+by applicable law, from receiving such property.
+
+2. Prohibitions. You, either directly or indirectly, shall not do
+any of the following acts:
+
+a. rent the Software;
+
+b. sell the Software;
+
+c. lease or lend the Software;
+
+d. offer the Software on a "pay-per-play" basis;
+
+e. distribute the Software (except by electronic means, as permitted
+by section 3. hereinbelow) by any means, including, but not limited to
+direct mail, retail, mail order or other means;
+
+f. in any other manner and through any medium whatsoever commercially
+exploit the Software or use the Software for any commercial purpose;
+
+g. disassemble, reverse engineer, disassemble, decompile, modify
+or alter the Software;
+
+h. translate the Software;
+
+i. reproduce or copy the Software (except as permitted by section
+3. hereinbelow);
+
+j. publicly display the Software;
+
+k. prepare or develop derivative works based upon the Software;
+
+l. remove or alter any legal notices, such as trademark and copyright
+notices, affixed on or within the Software; or
+
+m. create or develop extra or add-on levels for the Software.
+
+3. Permitted Electronic Distribution and Copying. So long as this
+Agreement accompanies the Software at all times, ID grants to you the
+limited right to distribute, free of charge, and by electronic means
+only, the Software. Anyone who receives the Software shall be limited to
+all the terms and conditions of this Agreement. You may make only the
+following copies of the Software: (i) you may download the Software
+from the Internet and onto your computer hard drive; (ii) you may copy
+the Software from your computer hard drive into your computer RAM; and
+(iii) you may make one (1) "back up" or archival copy of the Software
+on one (1) hard disk.
+
+4. Copyright. The Software and all copyrights, trademarks and all
+other conceivable intellectual property rights related to the Software
+are owned by ID and are protected by United States copyright laws,
+international treaty provisions and all applicable law, such as the
+Lanham Act. You must treat the Software like any other copyrighted
+material, as required by 17 U.S.C., ¤101 et seq. and other applicable law.
+You agree to use your best efforts to see that any user of the Software
+licensed hereunder complies with this Agreement. You agree that you
+are receiving a copy of the Software by license only and not by sale and
+that the "first sale" doctrine of 17 U.S.C. ¤109 does not apply to your
+receipt or use of the Software.
+
+5. NO WARRANTIES. ID DISCLAIMS ALL WARRANTIES, WHETHER EXPRESS
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE WITH RESPECT TO
+THE SOFTWARE. ID DOES NOT WARRANT THAT THE OPERATION OF THE SOFTWARE
+WILL BE UNINTERRUPTED OR ERROR FREE OR THAT THE SOFTWARE WILL MEET YOUR
+SPECIFIC REQUIREMENTS. ADDITIONAL STATEMENTS SUCH AS PRESENTATIONS,
+WHETHER ORAL OR WRITTEN, DO NOT CONSTITUTE WARRANTIES BY ID AND SHOULD
+NOT BE RELIED UPON.
+
+6. Governing Law, Venue and Liability Limitation. This Agreement
+shall be construed in accordance with and governed by the applicable laws
+of the State of Texas and applicable United States federal law. Copyright
+and other proprietary matters will be governed by United States laws and
+international treaties. Exclusive venue for all litigation regarding
+this Agreement shall be in Dallas County, Texas and you agree to submit to
+the jurisdiction of the courts in Dallas, Texas for any such litigation.
+IN ANY CASE, NEITHER ID NOR ID'S OFFICERS, EMPLOYEES, DIRECTORS, AGENTS,
+LICENSEES, SUBLICENSEES, SUCCESSORS OR ASSIGNS SHALL BE LIABLE FOR LOSS OF
+DATA, LOSS OF PROFITS, LOST SAVINGS, SPECIAL, INCIDENTAL, CONSEQUENTIAL,
+INDIRECT, PUNITIVE OR OTHER SIMILAR DAMAGES ARISING FROM BREACH OF
+WARRANTY, BREACH OF CONTRACT, NEGLIGENCE, STRICT PRODUCT LIABILITY,
+OR OTHER LEGAL THEORY EVEN IF ID OR ITS AGENT HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES OR EVEN IF SUCH DAMAGES ARE FORESEEABLE,
+OR LIABLE FOR ANY CLAIM BY ANY OTHER PARTY. Some jurisdictions do not
+allow the exclusion or limitation of incidental or consequential damages,
+so the above limitation or exclusion may not apply to you.
+
+7. U.S. Government Restricted Rights. To the extent applicable,
+the United States Government shall only have those rights to use the
+Software as expressly stated and expressly limited and restricted in
+this Agreement, as provided in 48 C.F.R. ¤¤ 227.7202-1 through 227.7204,
+inclusive.
+
+8. General Provisions. A copy of all notices or other correspondence
+which you send to ID shall also be sent by you to ID's counsel:
+
+D. Wade Cloud, Jr.
+HIERSCHE, MARTENS, HAYWARD, DRAKELEY & URBACH, P.C.
+15303 Dallas Parkway, Suite 700
+Dallas, TX 75248
+(972) 701-7000
+Facsimile: (972) 701-8765
+
+Neither this Agreement nor any part or portion hereof shall be assigned
+or sublicensed by you. ID may assign its rights under this Agreement
+in ID's sole discretion. Should any provision of this Agreement
+be held to be void, invalid, unenforceable or illegal by a court,
+the validity and enforceability of the other provisions shall not be
+affected thereby. If any provision is determined to be unenforceable,
+you agree to a modification of such provision to provide for enforcement
+of the provision's intent, to the extent permitted by applicable law.
+Failure of ID to enforce any provision of this Agreement shall not
+constitute or be construed as a waiver of such provision or of the right
+to enforce such provision. If you fail to comply with any term of this
+Agreement, YOUR LICENSE IS AUTOMATICALLY TERMINATED, WITHOUT NOTICE AND
+ID MAY PURSUE ALL RELIEF AND REMEDIES AGAINST YOU WHICH ARE AVAILABLE
+UNDER APPLICABLE LAW AND/OR THIS AGREEMENT. You agree that in the event
+of litigation relating to this Agreement, the prevailing litigant shall
+be entitled to recover the prevailing litigant's attorneys' fees and
+expenses and costs of court in addition to all other relief available
+under this Agreement and/or applicable law. In the event this Agreement
+is terminated, you shall have no right to use the Software, in any manner
+and you shall immediately destroy all copies of the Software in your
+possession, custody or control. You agree that your unauthorized use
+of any ID property, whether in whole or in part, would immediately and
+irreparably damage ID such that ID could not be adequately compensated
+by an award of monetary damages, and in the event of such threatened
+or actual unauthorized use ID shall be entitled to an injunctive order
+appropriately restraining and/or prohibiting such unauthorized use
+without the necessity of ID posting bond or other security.
+
+YOU ACKNOWLEDGE THAT YOU HAVE READ THIS AGREEMENT, YOU UNDERSTAND THIS
+AGREEMENT, AND UNDERSTAND THAT BY CONTINUING THE INSTALLATION OF THE
+SOFTWARE, BY LOADING OR RUNNING THE SOFTWARE, OR BY PLACING OR COPYING
+THE SOFTWARE ONTO YOUR COMPUTER HARD DRIVE OR RAM, YOU AGREE TO BE BOUND
+BY THE TERMS AND CONDITIONS OF THIS AGREEMENT. YOU FURTHER AGREE THAT,
+EXCEPT FOR WRITTEN SEPARATE AGREEMENTS BETWEEN ID AND YOU, THIS AGREEMENT
+IS A COMPLETE AND EXCLUSIVE STATEMENT OF THE RIGHTS AND LIABILITIES OF
+THE PARTIES HERETO. THIS AGREEMENT SUPERSEDES ALL PRIOR ORAL AGREEMENTS,
+PROPOSALS OR UNDERSTANDINGS, AND ANY OTHER COMMUNICATIONS BETWEEN ID
+AND YOU RELATING TO THE SUBJECT MATTER OF THIS AGREEMENT.
+
+
+
+April 23, 1999 5:11 p.m.
+
+
+
+
+
+LIMITED COMPATIBILITY TESTING AND RECREATIONAL USE SOFTWARE
+TEST LICENSE AGREEMENT Page 4
+3406.0586\C:\DWC\DOC\2082.DOC
+
diff --git a/code/unix/README.Linux b/code/unix/README.Linux
new file mode 100755
index 0000000..ef3b4c5
--- /dev/null
+++ b/code/unix/README.Linux
@@ -0,0 +1,352 @@
++----------------------------------------+
+| Q3Test |
+| The Official Quake 3: Arena TEST |
+| Linux version |
+| Revision 1.08 |
+| Released Aug 3, 1999 |
+| Copyright (C) 1999 id Software, inc. |
++----------------------------------------+
+| Documentation: Paul Jaquays |
+| Dave Kirsch |
++----------------------------------------+
+
+Outline:
+
+1. Introduction
+2. Bug Reporting
+3. Installing Q3Test
+4. Running Q3Test. Operating Instructions
+5. Known Issues
+
+==================
+== Section 1. ==
+== INTRODUCTION ==
+==================
+
+This is the Linux version of the test.
+
+Before proceeding onward, please read the README.EULA file. This is
+the End User License Agreement. It's the agreement between you and id
+regarding this test. Read it. Understand that the acts of loading or
+running the software, or placing it on your computer hard drive, RAM,
+or other storage, you are agreeing to be bound by the terms of the End
+User License Agreement. So it's best to know what you are agreeing to.
+
+The operating instructions for the test are included in the
+separate "README.Q3Test" file. For the most part, the game functions
+are the same across all platforms. Differences will be noted when necessary.
+
++----------------+
+| THIS IS A TEST |
++----------------+
+
+We want to set the record straight from the outset. This is neither a
+demo nor an ALPHA version of the final game and should not be expected
+to behave as such. Q3Test is a test of Quake3: Arena's network technology
+and graphics compatibility. While many of the game features that you will
+see in this test are in a highly polished state, do not confuse this with
+being anything other than what it is intended to be: a test. By running
+this test openly on the Internet and on a multitude of local networks,
+we hope to expose problems that could not otherwise be discovered on the
+limited number of in-house systems and computer. That's why we need your
+assistance for this test.
+
+Furthermore, it is anticipated that there may be revisions and additions
+made to the test that will make it incompatible with earlier versions.
+
++---------------------+
+| SYSTEM REQUIREMENTS |
++---------------------+
+
+There is no software-only version of the game. If your computer is not
+hardware accelerated with a game compatible graphics card, you will NOT be
+able to run Q3Test. Currently, 3DFX based cards are the only
+tested compatible cards. If your computer does not meet the
+minimum requirements, you are unlikely to be able to run a satisfactory
+game experience.
+
+A glibc compatible Linux installation is required. An easy to determine
+if you have glibc support is to type this:
+
+ ls -l /lib/libc*
+
+If you get a report of libc6 (you may also have libc5), you have a
+glibc based system.
+
+The Linux version requires a supported hardware 3D acceleration card. The
+following are currently supported:
+
+ o 3Dfx Voodoo Graphics based cards
+ o 3Dfx Voodoo2 based cards
+
+Other cards of similar make and model may work, but are not supported.
+
+Other X11 OpenGL libraries may work with a supported hardware
+accelerator, but have not been extensively tested. Performance on
+untested OpenGL configurations may not produce acceptable game
+speed.
+
+For 3Dfx based products, Linux Q3Test is distributed with a version of Mesa
+3-D specifically compiled for Voodoo support. You must have 3Dfx Linux Glide
+drivers installed however. These drivers are available from:
+
+ http://glide.xxedgexx.com/3DfxRPMS.html
+
+Make sure that you download and install the glibc versions of the drivers
+(found at the bottom of the page).
+
+Mirrors for this site are can be found at:
+
+ http://glide.mirrors.sonic.net
+ http://glide.samiam.org
+
+Please follow the installation instructions presented there for adding the
+correct drivers for your 3D-acceleration card. Note that there are two ways
+to install the 3DFX drivers-one with support for a /dev/3dfx device that
+does not require root permissions in order to use the card. If you choose to
+not use the /dev/3dfx method, you will have to run Q3Test as the root user.
+
+NOTE: Linux Q3Test will try to load "libGL.so" before using 3Dfx drivers.
+This can cause problems if you have a software or third party OpenGL driver
+installed. You can specifically target the included 3Dfx based Mesa driver
+by using the following command line:
+
+ ./linuxquake3 +set r_glDriver libMesaVoodooGL.so.3.1
+
+For 3DFX users, you may disable the vertical sync refresh. This can improve
+proformance at the cost of some visual tearing of the image. Entering the
+following command into your shell before running Q3Test will turn off
+the vertical sync:
+
+ export FX_GLIDE_SWAPINTERVAL=0
+
+Then run Linux Q3Test from the same command line normally.
+
++-----------+
+| X11 Setup |
++-----------+
+
+Linux Q3Test requires X11 to run. There is no console-based version as in
+previous id products such as GLQuake and Quake2. XFree86 version 3.2 or
+later is required.
+
+There are two ways that mouse input is handled under XFree86:
+
+ o By default, Q3Test will attempt to use DGA mouse handling. DGA
+ support features direct reading of the mouse motion and provides
+ more accurate control while playing the game. By default this
+ support is enabled, but can be disabled by adding "+set
+ in_dgamouse 0" to the command line at startup.
+ o The non-DGA method of mouse input uses pointer grabbing and warps
+ the pointer to the middle of the window on each mouse update. On
+ systems with a slow frame rate and a lot of mouse user input, the
+ motion can get "clipped" to the window boundaries. This method of
+ input is more compatible however.
+
+Q3Test uses the XFree86 VidModeExtension facilities if available to provide
+fullscreen play. This does not apply to 3Dfx passthrough based cards, since
+the passthrough cable takes over the video display upon activation anyway.
+
+When configuring your X11 server, make sure that you include lower
+resolution modes such as 640x480 and 800x600. Q3Test will auto-switch to
+these modes using the VidModeExtension if you select fullscreen from the
+graphics options menu. If the lower resolution modes are not listed in the
+XFree86 configuration file, Q3Test will be unable to switch to the desired
+resolution for fullscreen play.
+
++-------------------------+
+| Sound Support and Setup |
++-------------------------+
+
+Q3Test uses the /dev/dsp sound device for sound support under Linux. This is
+the default device provided by the sound drivers included with the Linux
+kernel. Please note that at the time of this writing, PCI based sound cards
+such as the SoundBlaster Live and Diamond Monster MX series were not
+supported. They may be supported in the future. Check
+http://www.opensound.com/ for support in the future.
+
+If you do not run Q3Test as root (recommended), you may need to make sure
+the permissions for the /dev/dsp device are read and write by the user
+running Q3Test. The cheap and easy way to make this happen is to do "chmod
+o+rw /dev/dsp" as root. For the more security conscious, a special sound
+group could be created and Q3Test could be made setgid to the sound group to
+access the device.
+
+Q3Test uses mmap() to map the sound buffers on /dev/dsp directly in order to
+provide responsive sound needs. Sound cards must be able to support this
+feature in order to work. SoundBlaster 16, AWE32 and AWE64 cards are known
+to work.
+
++----------------------+
+| WHAT'S IN THIS TEST? |
++----------------------+
+
+We have included three maps with this test version of Quake3: Arena. They
+are q3test1, q3test2, and q3tourney.
+
+q3test1 for 4-8 players on Internet or LAN play Best with 6 players
+q3test2 for 3-8 players Primarily for LAN play Best with 3 players
+q3tourney is the tournament map
+
+===================
+== Section 2. ==
+== BUG REPORTING ==
+===================
+
+What we would like from our testers are emails with descriptions of
+problems that are encountered, particularly those involving video or
+network bugs. Do NOT send reports to individual id employees. All bug
+reports should go to the following e-mail address:
+
+q3feedback@idsoftware.com
+
+In your subject line, please describe the system the game is being played
+on (Mac, Linux, Win32) and the type of problem you are reporting: video,
+network, sound or game. Example Subject Line: "Mac/video problem" or
+"Linux/network connection problem."
+
+In the body of your letter (no attached files please), briefly list and
+describe the problems. Detailed descriptions of problems are good, but
+remember that brevity is best. Please do NOT send screen shots unless
+they are the ONLY way to show a problem.
+
+While we realize that you may have comments and suggestions regarding
+specific game play features, please refrain from submitting such along
+with bug reports. Comments on game play can be made on the official
+Quake 3: Arena message board at:
+
+http://www.quake3arena.com
+
+========================
+== Section 3. ==
+== INSTALLING Q3TEST ==
+========================
+
+After you have installed the needed hardware drivers for your 3D
+acceleration and sound hardware, you need to install the Q3Test package.
+
+Q3Test is available as a Red Hat RPM file or as a tar file. To install the
+RPM file, enter the following when logged in as the root user:
+
+rpm -Uvh q3test-1.00-glibc-1.i386.rpm
+
+The rpm installs the game and data files in /usr/local/games/q3test.
+
+[ Note: If you have not installed (or do not wish to install) the Linux
+glide drivers, you may get an error message about not having libglide2x.so
+installed. This can be ignored and installation can be forced by adding
+the --nodeps option to the rpm command line as follows:
+rpm --nodeps -Uvh q3test-1.00-glibc-1.i386.rpm ]
+
+If you are going to install the tar version, make a directory for
+installation, untar the file as follows:
+
+tar xzvf q3test-1.00-glibc-i386.tar.gz
+
+This will untar the files into a q3test subdirectory under the current
+directory.
+
+====================
+== Section 4. ==
+== RUNNING Q3TEST ==
+====================
+
+It is recommended that you do not run Q3Test using the root account or with
+root privileges. There are two exceptions to this:
+
+ o If you are using a 3Dfx based accelerator card and do not install
+ the /dev/3dfx configuration option. (You will have to run as root
+ in order to access the card).
+ o If you do not have access to the /dev/dsp device and do not wish
+ to change the mode of the device so that non-root accounts can
+ access it.
+
+You will have to be running under X11 or have the DISPLAY variable pointed
+to a OpenGL glX capable X Server.
+
+By default, Q3Test tries to find the following OpenGL libraries in this
+order:
+
+ o libGL.so.1
+ o libMesaVoodooGL.so.3.1
+
+You can override the library name by entering, "+set r_glDriver <libname>"
+on the command line. This may be needed if you are using a non-standard set
+up and have a different name for the OpenGL shared library.
+
+If everything proceeds successfully, you should have a Q3Test window on your
+desktop with a menu displayed (3DFX owners will get a full screen view). If
+you want to use full screen, go to the System Configuration, Graphics
+Options, Fullscreen, change the value to Yes, and hit enter to apply it.
+
+If you intend to connect to the Internet to play Q3Test, make certain
+that your net connection is open and working first.
+
+======================
+== Section 5. ==
+== KNOWN ISSUES ==
+======================
+
+Q. My mouse is erratic. My player is constantly looking up or down and
+I can't seem to move him.
+
+A. This happens with two issues. Some versions of XFree86 have a bug in
+DGA mouse handling that confuses Q3Test. You can try turning off DGA mouse
+support by entering "+set in_dgamouse 0" on the command line when you
+start Q3Test. This problem can also occur after a restart of the video
+system (such as after a graphic setting change). This is because some
+sort of event occurred to jam up the mouse. Restarting the video system
+another time and not moving the mouse during the restart should clear it.
+
+
+Q. When I do a video restart (for example, selecting Apply in the Graphics
+Options menu), Q3Test exits with a Sig11.
+
+A. This is a driver related problem.
+On 3DFX hardware that is using the /dev/3dfx device and you are NOT running
+as root, it seems that the restart doesn't clear some sort of permission.
+Running Q3Test as root will fix this problem.
+
+
+Q. Performance is so slow I can't play! The frame rate looks like one
+frame per second!
+
+A. Most of the current drivers for Linux do not support hardware
+acceleration at any bit depth other than 15 or 16 bit color. Make sure
+that you specify 16 bit color when you run your X11 Server, such as:
+
+ startx -- -bpp 16
+
+
+Q. I have a Voodoo3. When I start the game, I send up at a low resolution
+version of my desktop.
+
+A. The current Voodoo3 X11 Servers have problems with DGA Mouse support.
+This is a known driver issue and will be fixed in newer revisions of the
+Voodoo3 X11 Server. Run the game with the following to disable it:
+ ./linuxquake3 +set in_dgamouse 0
+
+
+Q. I'm running Gnome with Englightenment and sound doesn't work.
+
+A. If you are using the Enlightenment Sound Daemon (esd), it will not release
+the sound hardware for Quake3 Test's usage. You can disable it before running
+the test as follows:
+ esdctl off # turn it off
+ start q3test the normal way
+ esdctl on # turn it back on
+
+
+Q. I try to run Q3Test, but sound doesn't work. The console says "Can't
+open /dev/dsp. /dev/dsp: Can't allocate memory."
+
+A. This can happen if the vmware kernel modules are loaded. You can unload
+them by typing when logged as root:
+ /etc/rc.d/init.d/vmware stop
+Assuming you are using a RedHat system.
+
+
+Q. I was playing Q3Test and suddenly it quit and reported a signal error.
+
+A. This is probably a bug. Please report it.
+
diff --git a/code/unix/README.Q3Test b/code/unix/README.Q3Test
new file mode 100755
index 0000000..eab97e8
--- /dev/null
+++ b/code/unix/README.Q3Test
@@ -0,0 +1,306 @@
++----------------------------------------+
+| Q3Test |
+| The Official Quake 3: Arena TEST |
+| Operating Instructions Readme |
+| Revision 2.1 |
+| Released Friday July 16th, 1999 |
+| Copyright (C) 1999 id Software, inc. |
++----------------------------------------+
+| Documentation: Paul Jaquays |
++----------------------------------------+
+
+This game is not yet rated by the ESRB. It contains animated
+violence and blood. A rating for mature audiences 17+ is
+anticipated.
+
+1. Introduction
+2. Operating Instructions
+3. Status Readouts
+4. Player Actions
+5. The Arena Environment
+6. The Game Console
+7. Problem Icons
+
+==================
+== Section 1. ==
+== INTRODUCTION ==
+==================
+
+ These instructions for game play should work with the versions of the game that are targeted at different platforms.
+
+ Before proceeding onward, click on the EULA_Readme file icon. This is the End User License Agreement. It's the agreement between you and id regarding this test. Read it. Understand that the acts of loading or running the software, or placing it on your computer hard drive, RAM, or other storage, you are agreeing to be bound by the terms of the End User License Agreement. So it's best to know what you are agreeing to.
+
+ If you agree to the conditions of the End User License Agreement, install the game on your computer's hard drive.
+ If you are using the Win32 version, open the readme file included for GLSetup. This application will load the most recent versions of the GL drivers needed to play Quake3: Arena.
+
+ The platform-specific instructions for the test are included in a separate Readme file. Refer to the appropriate Readme for your hardware.
+
++----------------+
+| THIS IS A TEST |
++----------------+
+ We want to set the record straight from the outset. This is neither a demo nor an ALPHA version of the final game and should not be expected to behave as such. Q3Test is a test of Quake3: Arena's network technology and graphics compatibility. While many of the game features that you will see in this test are in a highly polished state, do not confuse this with being anything other than what it is intended to be: a test. By running this test openly on the Internet and on a multitude of local networks, we hope to expose problems that could not otherwise be discovered on the limited number of in-house systems and computers we have available. That's why we need your assistance for this test.
+
+ Furthermore, it is anticipated that there may be ongoing revisions and additions made to the test that will make it incompatible with earlier versions.
+
+============================
+== Section 2. ==
+== OPERATING INSTRUCTIONS ==
+============================
+
+ When you start Q3Test, the game does not automatically load a map. Instead it displays the Main Menu screen. At this point (or at any time during the game) you may adjust and customize the video and audio settings on your computer, change details regarding your game character, and if desired, change the default controls to ones more to your liking.
+
+At any time during the game, press the Escape key to bring up the Main menu and superimpose it over the game screen. Use the up and down arrow keys to navigate the menu, and press the Enter key to select a function. Press Escape to return to the main level menu (and set any selected choices). Each Main menu function brings up a list of secondary menu items. If you have problems using the secondary menu selections, please refer to the message banner at the bottom of the screen for technical details.
+
+If a menu selection appears in gray, you cannot select or modify it. Choosing some options in the CONTROL CUSTOMIZATION and GRAPHICS OPTIONS menus will disallow other options. This is because they are either unnecessary (as is the case with MOUSE LOOK if you select the FREE LOOK option), or are not supported (as is the case with COLOR DEPTH if you chose the VOODOO OPENGL).
+
++-----------+
+| MAIN MENU |
++-----------+
+The first three Main Menu options, SEARCH FOR LAN GAME, CONNECT TO NETWORK GAME and START NETWORK GAME are only available if the player is not currently connected to an ongoing game.
+
+SEARCH FOR LAN GAME:
+If your computer is on a Local Area Network (LAN), this will show any currently active Q3Test servers on the network, along with the number of players currently in the game and the maximum number of players that can be in that game.
+
+Example: idserver q3test1 1/8
+
+This indicates that the server on the LAN called "idserver" is currently playing the map "q3test1" and has one player in it out of the possible 8 that can be in the game at one time.
+
+Use the up/down arrow keys to select a server and hit ENTER to command your computer to connect to that game.
+
+CONNECT TO NETWORK GAME:
+ SERVER: If your computer is connected to the Internet, you can enter the IP address of a server and hit ENTER to attempt to make a connection to that server. For server id's Q3Test server listings, go to http://www.quake3arena.com or check with your favorite 3D gaming web sites for other servers.
+ RATE: Set the type of network connection you are using. Choices are: "<=28.8K", "33.6K", "56K", "ISDN", and "LAN/cable/xDSL".
+
+START NETWORK GAME:
+To start a network game, whether on a LAN or over the Internet, select this option. The secondary menu screen has the following options:
+
+START: Launches the game using the parameters currently set on this menu.
+MAP: This gives access to the list of maps located in the Quake3/Baseq3/Maps directory/folder. For the purposes of this test, there are only two maps. Use the left and right arrow keys to toggle between the two maps.
+DEDICATED: This is either "no", "dedicated LAN," or "dedicated Internet."
+A dedicated server (set to YES) runs the game, but does not display a graphic version of the game on the screen of the computer running the game. The default value for this is no. This means that you are running the server and participating as a player at the same time.
+TIME LIMIT: entering a non-zero number here sets a time limit (in minutes) for the game duration. If the game has not ended because a frag limit has been set, then it will end when time runs out.
+FRAG LIMIT: Entering a non-zero number here sets the number of "frags" or "kills" needed to win the game. If the game has not ended because a time limit has been set, then it will end when one player in the game reaches this number of frags.
+MAX PLAYERS: This is the total number of players that may be in the game at any one time.
+HOSTNAME: This is the name of the server. In the LAN example above, the hostname is "idserver."
+
+CUSTOMIZE PLAYER:
+Allows the player to change information about his in-game persona.
+
+NAME: This is the player's name as it will appear on-screen during the game. It may be up to 33 characters long.
+
+SKIN: Visor is the only model in the test. Two skins (red and blue) are available for the model. Use the left and right arrow keys to select one.
+
+EFFECTS COLOR: You can choose an identifying color for your rail gun projectile trails. Use the left and right arrow keys to select a color.
+
+HANDICAP: Better players can choose to handicap themselves to balance a match against players of less skill by limiting the maximum amount of health and armor that they can have during the game. Use the left and right arrows to select a value from 25 to 100 points. Certain items and power ups will temporarily raise this value, but will then count down to the preset value. The default is 100.
+
+CUSTOMIZE CONTROLS:
+Allows the player to change the assignment of game controls to other keyboard and mouse buttons. When you visit this menu for the first time, the default assignments for all controls are shown. To change an assignment, use the up/down arrow keys to select a game function. Press ENTER to activate the change process. Press the keyboard key or mouse input that you want to use for that function. Up to two keys/buttons may be assigned to each game function in this manner by repeating the process. If you inadvertently use a key assigned to another function, three question marks ("???") appear next to the function that previously used that key.
+
+ALWAYS RUN: setting this to YES causes your player to move faster, but make more noise as he moves. The RUN/WALK key allows the player to switch between fast/noisy and slow/silent movement modes.
+FREELOOK: If YES, then you may look freely in all directions as if you were moving only your head by moving the mouse around. If this is Set to NO you must bind a key to mouse look.
+INVERT MOUSE: Selecting YES inverts the up and down view movement directions.
+MOUSE SPEED: This is set on the menu with a slide control. The faster your mouse speed, the greater the on-screen response to small movements of the mouse. Mouse speed can also be adjusted from the console. Bring the console down and type in "sensitivity". The game will respond by printing "sensitivity" is: "__" (the blank indicating the number value currently assigned to mouse speed) default is "5". Use the up arrow key to display sensitivity on the console again, enter a different number value and hit enter. Higher numbers are more sensitive. Lower numbers are less sensitive.
+
+SYSTEM CONFIGURATION:
+EFFECTS VOLUME: Use the slide control to adjust game sound playback volume to your liking.
+SOUND QUALITY: Select either Low (16 bit sound running at 11 megahertz) or High (32 bit sound running at 22 megahertz).
+BRIGHTNESS: First, try running the game with the brightness set to 1.0 (the default level used by the designer when making the map). If the map is too dark to see in dimly lighted areas or too light in sunny areas, use this slide control to compensate for differences in the way some monitors and video cards draw the game world. Remember that the arenas are supposed to be dark and foreboding places.
+
+GRAPHICS OPTIONS:
+This drops you down into another menu layer. The controls here are designed to help you optimize graphics and or/enhance the game's playability on your system. When you are satisfied with your selections, you must move the cursor to the bottom of the screen to the APPLY option to activate them. Pressing Escape to return to the SYSTEM CONFIGURATION MENU does not activate changes in the graphics settings. Changing anything on this menu will cause the game to restart the video.
+
+GRAPHICS MODE: This is a global setting for the display of the game's screen graphics. The settings are HIGH QUALITY, NORMAL, FAST, FASTEST, and CUSTOM. Selecting one of these choices affects most of the other settings on this page. If you make any adjustments to other settings on this page, the graphics mode changes to CUSTOM.
+DRIVER: Consult the platform specific readme for the drivers that will work with your platform.
+VIDEO MODE: This is the screen resolution size. Smaller resolutions can improve performance speed on slower machines.
+COLOR DEPTH: Determines whether you are using 16-bit textures or 32-bit textures. Default means you run with the color depth currently set for your computer's desktop.
+FULLSCREEN: A YES selection allows you to choose to run with the test filling the entire screen. A NO selection will run the game in a window. If run in a window, COLOR DEPTH is disabled because you are limited to whatever has been selected for the desktop.
+LIGHTING: Allows you to chose either a LIGHTMAP or VERTEX lighting. Using the LIGHTMAP is recommended for best appearance. VERTEX lighting may improve game performance, but at a cost to appearance.
+GEOMETRIC DETAIL: Lets you adjust the number subdivisions used to define curves in the arena on both world geometry and items, weapons and characters. HIGH is the normal setting. LOW greatly reduces curve complexity.
+SCREEN SIZE: The slide control changes the amount of screen area devoted to display of the game. Reducing screen size can improve performance.
+TEXTURE DETAIL: This sliding control allows you to adjust the level of detail displayed. Unless you have an extremely fast computer, the normal setting gives the best balance of detail vs. game speed.
+TEXTURE QUALITY: This determines whether you wish to use 32-bit textures, 16-bit textures, or compressed textures. Many of the game's special effects will appear at their best only when defined by 32-bit textures.
+OPENGL EXTENSIONS: Allows you to enable or disable OPENGL extensions.
+DRIVER INFORMATION: Brings up a display of information regarding the drivers currently operating in your machine. It is not interactive. Hit ESC to return to the previous menu.
+
+
+PREFERENCES: Hitting ENTER here will drop you into another menu that allows you to adjust other game features.
+CROSSHAIR: choose one of four options, none, cross, dot, or angle.
+MARKS ON WALLS: Enable or Disable weapons scars and blood smears. Disabling this feature may improve performance.
+DYNAMIC LIGHTS: Enable or Disable lights that move through the world (such as light generated by weapon projectile trails). Disabling this feature may improve performance.
+LIGHT FLARES: Enable or DISABLE glowing light halos around lights. Disabling this feature may improve performance.
+IDENTIFY TARGET: Enable or Disable the ability to see the name of your foe when you put your crosshair on him (does not function if target is in fog).
+SKY: Set the sky for either HIGH SPEED or HIGH QUALITY.
+
+RESET DEFAULTS: Restore all game settings and controls to their default value by reloading the default configuration.
+
+APPLY: You must select this and hit ENTER to lock in your choices. Doing so will restart the game video.
+
+SCREENSHOT:
+Makes a targa file screen shot of what is currently in view on the screen. Look for it in the Screenshot folder within your Quake 3/Baseq3/screenshots folder.
+
+LEAVE ARENA:
+This disconnects you from the arena you are currently playing, but does not quit you out of the game. From here you can connect to other servers or start your own. You can also leave an arena by typing "disconnect" on the command line of the console.
+
+QUIT GAME:
+Returns you to the desktop.
+
+
+======================
+== Section 6. ==
+== STATUS READOUTS ==
+======================
+
+ Your player status is shown as numbers and icons floating in your view at the bottom of the screen. There is an indicator for your ammo (far left) including the type of ammo currently in use, current health (left-center), your character portrait (center), armor (center-right), and Frag Count (far right). The digital timer in the upper right shows the amount of time you have been in this arena. When you have a one-use item in your inventory (such as the personal teleporter), its icon will appear on the right side of your display. When you are fragged, the character portrait and name of the foe who killed you appears in the upper right corner of the display. When you change weapons, icons representing the ammo of the weapons in your inventory will appear above your character portrait. If you have a weapon, but no ammunition for it, a negation symbol will be superimposed over the ammo icon.
+
++----------------------------+
+| INTERPRETING THE LAGOMETER |
++----------------------------+
+ The Lagometer is the graph in the lower right corner of the status display. It is a test function and not a part of regular game play. The upper graph (blue/yellow) slides one pixel for every rendered frame. Blue lines below the baseline mean that the frame is interpolating between two valid snapshots. Yellow lines above the baseline mean the frame is extrapolating beyond the latest valid time. The length of the line is proportional to the time.
+The lower graph (green/yellow/red) slides one pixel for every received snapshot. By default, snapshots come 20 times a second, so if you are running >20 fps, the top graph will move faster, and vice versa. A red bar means the snapshot was dropped by the network. Green and yellow bars are properly received snapshots, with the height of the bar proportional to the ping. A yellow bar indicates that the previous snapshot was intentionally suppressed to stay under the rate limit.
+The upper graph indicates the consistency of your connection. Ideally, you should always have blue bars of only a pixel or two in height. If you are commonly getting big triangles of yellow on the graph, your connection is inconsistent.
+ In a heavy firefight, it is normal for modem players to see yellow bars in the bottom graph, which should return to green when the action quiets down. If you are getting several red bars visible, you may want to look for a server that drops less packets.
+ There are a few tuning variables for people trying to optimize their connection: The most important one is "rate", which is what the connection speed option in the menu sets. We are fairly conservative with the values we set for the given modem speeds: 2500 for 28.8, 3000 for 33, and 3500 for 56k. You may actually be connecting faster than that, and modem compression may be buying you something, so you might get a better play experience by increasing the values slightly. If you connect at 50000 bps, try a rate of 5000, etc. Quake 3 errs on the conservative side, because too low of a rate will only make the movement of other things in the world choppy, while too high of a rate can cause huge amounts of lag.
+ Note that the optimal rate will be somewhat lower than a rate for QW or Q2, because Quake 3 now includes the UDP packet header length in the bandwidth estimate. You can ask for a different number of snapshots by changing the "snaps" variable, but there isn't a lot of benefit to that. Dedicated servers run at 40hz, so stick to divisors of that: 40, 20 (default), 10. A "snaps" of 40 will usually just cause you to hit your rate limit a lot faster. It may be useful for tuning rate, if nothing else.
+ You can adjust the local timing point with "cg_timenudge ", which effectively adds local lag to try to make sure you interpolate instead of extrapolate. If you really want to play on a server that is dropping a ton of packets, a timenudge of 100 or so might make the game smoother.
+
+=====================
+== Section 7. ==
+== PLAYER ACTIONS ==
+=====================
+
+ The descriptions below are based on the preset default configurations for the game controls. If you have played first person shooting games previously (such as Quake or Quake 2), you may want to reconfigure the controls to match your preferences.
+
++----------+
+| ACTIONS |
++----------+
+WALKING: Use the four arrow keys or the mouse to walk around. To walk steadily forward, hold down the "forward" key (the up arrow or center button on a 3-button mouse). Turn left or right with the left or right arrow keys, or by sliding your mouse in the desired direction.
+
+RUNNING: To run, simply hold down the left Shift key to increase your
+Speed (unless you have selected "Always Run", in which case it reverts you to a walk. If you prefer to always run during the game, open the Main menu, then the Customize Controls menu, and select Always Run.
+
+SHOOTING: Tap the Ctrl key or the left mouse button to fire. Hold the
+fire key down to keep firing.
+
+LOOKING UP AND DOWN: The letters A and Z allow you to look up and down,
+respectively. Start walking forward and your line of vision will
+automatically readjust to the center position. You may also choose to
+select Free Look under the Controls menu which will allow you to move the
+mouse around as if it was your head movement.
+
+SWIMMING: While underwater, aim yourself in the direction you wish to go
+and press the forward key to go in that direction. Unfortunately, as in
+real life, you may lose your bearings while underwater. Use the jump key,
+(default is the Space Bar), to kick straight up towards the surface. Once on
+the surface, tread water by holding down the jump key. To get out of the
+drink, swim toward the shore and you can either jump up onto the land or
+walk straight out if it is shallow enough. There is always a way out of
+water, but you may have to submerge even deeper in order to find it.
+
+CROUCHING: Press and hold down the C key to duck and move forward to "duck walk." When you release the C key, you will return to an upright position. It is also possible to avoid rockets in this manner.
+
+JUMPING: Tap the space bar to jump. You jump farther if you're moving
+forward at the time.
+
+STRAFING: Hold down the ALT key and the left or right arrow key and you will side-step in that particular direction. This is perfect for avoiding incoming weapon attacks.
+
+PICKING UP OBJECTS: To pick up items, weapons, and power-ups, simply walk
+over them. The weapon cross-hair will pulse larger briefly to indicate you have acquired a new weapon or supply. If you are unable to pick something up, it means you already have the maximum amount possible for that object.
+
+TALKING: To communicate with other players, press the T key
+and type in your message. Press Enter when finished and your words will
+appear at the top of the screen. You can also enter communications on the command line of the console.
+
+ATTACKING: Point your weapon at an opponent and press the fire button. Default fire keys are the left mouse and the control key). If a weapon runs out of ammo, it switches to the next available weapon with ammo the next time you fire it. If you have no ammo at all, you fight with the gauntlet.
+
++--------+
+| DYING: |
++--------+
+ When you die, the weapon you were using (except for the gauntlet and the machine gun), and any active power ups drop where you died. Armor, ammo and one-use items like the teleporter are lost. To respawn into the game, press the fire key. When you re-enter the game you are once again armed with only your starting equipment.
+
+===========================
+== Section 8. ==
+== THE ARENA ENVIRONMENT ==
+===========================
+
++-----------------------+
+| RAPID TRANSIT DEVICES |
++-----------------------+
+TELEPORTERS: These devices instantaneously move you to a pre-selected destination.
+
+PORTALS: These are devices that generate holes in space through which you can see your ultimate destination and move to it like walking through a doorway.
+
+JUMP PADS: Jump pads throw you upwards to land on higher portions of the arena. You have some "air" control over your final landing point.
+
+ACCELERATION PADS: Acceleration pads turn you into a human cannon ball, launching you to distant locations in the arena. As with the jump pads, you have some "air" control over your final landing point.
+
++-----------------------+
+| ENVIRONMENTAL HAZARDS |
++-----------------------+
+LAVA: Walking on lava is not instantly fatal, but even with good armor protection, it can be a relatively quick (and noisy) doom.
+
+THE VOID: Falling off into the infinite blackness of the void is a near inescapable death.
+
++--------------+
+| TEST ARSENAL |
++--------------+
+MACHINE GUN: This is your default weapon. It's an instant hit attack and reasonably accurate even at long range. It uses bullets.
+
+GAUNTLET: This is either your weapon of last resort when you're out of ammo or a cool tool to humiliate other players. When it hits, it does damage and knocks a foe back. It does not require ammunition, but you have to be in direct contact with a foe and activating (firing) it to cause injury and knockback.
+
+SHOTGUN: This uses shells for ammunition. The spread of the shotgun blast makes it deadly in close combat, but not the best choice for long-range attacks.
+
+ROCKET LAUNCHER: The rocket launcher delivers heavy fire power to your target, but travels slower compared to other attacks. Be careful when you use this weapon in close combat.
+
+PLASMA GUN: Powered by Energy cells, this rapid-fire weapon delivers deadly gouts of glowing energy quickly and accurately.
+
+RAIL GUN: The Rail Gun fires depleted uranium slugs at super high velocities. It hits instantly and can pass through the bodies of multiple opponents. But be warned, it recharges slowly and can be a liability in close combat. Take note of the distinctive trail of atmospheric disturbance
+caused by the projectile. The color of the rail gun's trail can be changed under the CUSTOMIZE PLAYER menu on the EFFECTS COLOR line.
+
+LIGHTNING GUN: Zap them!
+
++------------------+
+| COMBAT SUPPLIES: |
++------------------+
+Pick up these helpful items whenever possible. Some items take effect when
+picked up, others you must activate during play.
+
+AMMO: With the exception of the gauntlet, each weapon has a corresponding ammo type. The color of the ammo boxes corresponds with the color of the graphic weapon icons displayed briefly in your heads up display. Each ammo type has a maximum you can carry.
+
+ARMOR: There are three armor types: Green armor shards, yellow combat armor and red body armor. Collecting them increases your armor protection. The red armor and the green armor shards can increase your total armor protection above the maximum for short duration. The points "decay" back to the normal maximum value.
+
+HEALTH: There are three types of standard health kits: small (green), medium (yellow) and large (red) encased in crystalline shells. The green health can increase your total health value above the maximum. Like armor, it "decays" back to your maximum possible health value.
+
+QUAD DAMAGE: The quad temporarily multiplies all your weapon's strengths.
+
+MEGA HEALTH: This blue health power up provides a temporary but significant boost to your health, taking it above your maximum level. Like armor, it "decays" back to your maximum possible health value.
+
+PERSONAL TELEPORTER: Grab this single-use power up and use it to escape from dangerous situations. Activating it immediately teleports you to one of the arena's spawn spots.
+
+=======================
+== Section 9. ==
+== THE GAME CONSOLE ==
+=======================
+
+ The game console (or just the console) is a pull down window shade that shows recent game information, including the text of conversations and recently executed game commands. The bottom line of the console is the command line. While playing Q3test, you can enter into console mode by pressing the tilde (~) key and exit by pressing it again. The console is where you enter all the commands to change the game state.
+
+ For example, one console command is "map <name>" which will load a map
+and start it up. Starting up a map actually starts a local Server and a Client. For the purposes of this test, most of the console commands will be executed to optimize graphics. Pressing the up and down arrows in the console will change to the last command entered. You can backspace over the command and enter new values if you'd like. There is also a command-completion function. Type in the first few letters of a command. By pressing the TAB key, you can have the console automatically finish the name of the command for you.
+
+ When you are in console mode (or when you have selected to "talk" by typing in words to appear on the screen), a blue "voice balloon" will appear over your head. Common game courtesy is to NOT shoot players who are in this mode.
+
+=======================
+== Section 10. ==
+== PROBLEM ICONS ==
+=======================
+
+Q3Test has a Problem Icon that you may see on your screen from time to time. When you are disconnected from a Quake Server or the network packet flow is disturbed, you will see a Network Disconnect icon above the spot where your frag count is displayed. Other players will see it displayed over your character's head (similar to the way the talk balloon is displayed). If you are not immediately reconnected to the server, you will need to disconnect (leave arena) and attempt to reconnect with the server by either using the menu commands or by typing "connect" <server IP address> in the console command line.
+ NOTE: Courteous players will refrain from getting cheap points by fragging lagged out opponents.
+
+=======================
+== Section 11. ==
+== MESSAGE OF THE DAY ==
+=======================
+
+When Quake 3 Arena starts a map up, it sends the GL_RENDERER string to the Message Of The Day server at id. This responds back with a message of the day to the client. If you wish to switch this option off, set CL_MOTD to 0 (+set CL_MOTD 0 from the command line).
+
diff --git a/code/unix/build_setup.sh b/code/unix/build_setup.sh
new file mode 100755
index 0000000..c1a5f6d
--- /dev/null
+++ b/code/unix/build_setup.sh
@@ -0,0 +1,125 @@
+#!/bin/bash
+# Build various setups..
+
+# inputs:
+# directory with the common media
+Q3SETUPMEDIA=/home/timo/Id/Q3SetupMedia/quake3
+# directory with binaries tree
+Q3BINARIES=../install
+# version: $1
+VERSION=$1
+# temporary directory used to prepare the files
+# NOTE: this dir is erased before a new setup is built
+TMPDIR=setup.tmp
+
+# location of the setup dir (for graphical installer and makeself)
+SETUPDIR=setup
+
+# cp setup phase
+# we need to copy the symlinked files, and not the symlinks themselves
+# on antares this is forced with a cp -L
+# on spoutnik, -L is not recognized, and dereference is the default behaviour
+# we need a robust way of checking
+TESTFILE=/tmp/foo$$
+touch $TESTFILE
+# see if option is supported
+cp -L $TESTFILE $TESTFILE.cp 2>/dev/null
+if [ $? -eq 1 ]
+then
+ # option not supported, should be on by default
+ echo "cp doesn't have -L option"
+ unset CPOPT
+else
+ # option supported, use it
+ echo "cp supports -L option"
+ CPOPT="-L"
+fi
+rm $TESTFILE
+
+
+# graphical installer (based on Loki Software's Setup tool)
+build_installer ()
+{
+TMPDIR=setup.tmp
+
+rm -rf $TMPDIR
+mkdir $TMPDIR
+
+# copy base setup files
+cp $CPOPT -R $SETUPDIR/setup.sh $SETUPDIR/setup.data $TMPDIR
+
+# copy media files
+cp $CPOPT -R $Q3SETUPMEDIA/* $TMPDIR
+
+# remove CVS entries
+find $TMPDIR -name CVS | xargs rm -rf
+
+# copy binaries
+mkdir -p $TMPDIR/bin/x86
+# smp
+cp $CPOPT $Q3BINARIES/linuxquake3-smp $TMPDIR/bin/x86/quake3-smp.x86
+strip $TMPDIR/bin/x86/quake3-smp.x86
+brandelf -t Linux $TMPDIR/bin/x86/quake3-smp.x86
+# old school
+cp $CPOPT $Q3BINARIES/linuxquake3 $TMPDIR/bin/x86/quake3.x86
+strip $TMPDIR/bin/x86/quake3.x86
+brandelf -t Linux $TMPDIR/bin/x86/quake3.x86
+# ded
+cp $CPOPT $Q3BINARIES/linuxq3ded $TMPDIR/bin/x86/q3ded
+strip $TMPDIR/bin/x86/q3ded
+brandelf -t Linux $TMPDIR/bin/x86/q3ded
+
+# PB files
+mkdir -p $TMPDIR/pb/htm
+cp $CPOPT ../pb/linux/*.so $TMPDIR/pb
+cp $CPOPT ../pb/htm/*.htm $TMPDIR/pb/htm
+
+# Linux FAQ
+mkdir -p $TMPDIR/Docs/LinuxFAQ
+cp $CPOPT LinuxSupport/* $TMPDIR/Docs/LinuxFAQ
+
+# generated .qvm pk3 files
+mkdir -p $TMPDIR/baseq3
+mkdir -p $TMPDIR/missionpack
+# not needed now
+#cp $CPOPT $Q3BINARIES/baseq3/pak8.pk3 $TMPDIR/baseq3/
+#cp $CPOPT $Q3BINARIES/missionpack/pak3.pk3 $TMPDIR/missionpack/
+
+# menu shortcut to the game
+# FIXME current setup doesn't have a way to set symlinks on arbitrary things
+# so we use a dummy quake3 script (which will be overwritten by postinstall.sh)
+echo -e "#!/bin/sh\necho \"If you read this, then the setup script failed miserably.\nPlease report to ttimo@idsoftware.com\n\"" > $TMPDIR/bin/x86/quake3
+echo -e "#!/bin/sh\necho \"If you read this, then the setup script failed miserably.\nPlease report to ttimo@idsoftware.com\n\"" > $TMPDIR/bin/x86/quake3-smp
+# create the auto-extractible archive
+# first step: on FreeBSD we would default to Linux binaries .. use a symlink
+(
+cd $TMPDIR/setup.data/bin
+ln -s Linux FreeBSD
+ln -s Linux NetBSD
+ln -s Linux OpenBSD
+)
+# NOTE: we used to pass the $VERSION, but it doesn't seem very usefull
+./$SETUPDIR/makeself/makeself.sh $TMPDIR linuxq3apoint-$VERSION.x86.run "Quake III Arena Point Release $VERSION " ./setup.sh
+
+chmod a+rx linuxq3apoint-$VERSION.x86.run
+
+#rm -rf $TMPDIR
+}
+
+check_brandelf()
+{
+ # make sure brandelf is installed to avoid any problem when building the setups
+ BRAND=`which brandelf`;
+ if [ -n "$BRAND" ] && [ -x "$BRAND" ]
+ then
+ echo "brandelf is present: $BRAND"
+ else
+ echo "brandelf not found"
+ exit
+ fi
+}
+
+# safe checks
+check_brandelf
+
+build_installer
diff --git a/code/unix/cons b/code/unix/cons
new file mode 100755
index 0000000..450488e
--- /dev/null
+++ b/code/unix/cons
@@ -0,0 +1,6828 @@
+#!/usr/bin/env perl
+
+# NOTE: Cons intentionally does not use the "perl -w" option or
+# "use strict." Because Cons "configuration files" are actually
+# Perl scripts, enabling those restrictions here would force them
+# on every user's config files, wanted or not. Would users write
+# "better" Construct and Conscript files if we forced "use strict"
+# on them? Probably. But we want people to use Cons to get work
+# done, not force everyone to become a Perl guru to use it, so we
+# don't insist.
+#
+# That said, Cons' code is both "perl -w" and "use strict" clean.
+# Regression tests keep the code honest by checking for warnings
+# and "use strict" failures.
+
+use vars qw( $CVS_id $CVS_ver $ver_num $ver_rev $version );
+
+$CVS_id = 'Id';
+$CVS_ver = (split(/\s+/, $CVS_id))[2];
+
+$ver_num = "2.3";
+$ver_rev = ".1";
+
+$version = "This is Cons $ver_num$ver_rev ($CVS_id)\n";
+
+# Cons: A Software Construction Tool.
+# Copyright (c) 1996-2001 Free Software Foundation, Inc.
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; see the file COPYING. If not, write to
+# the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+# Boston, MA 02111-1307, USA.
+
+require 5.003;
+# See the NOTE above about why Cons doesn't "use strict".
+use integer;
+use Cwd;
+use File::Copy;
+
+use vars qw( $_WIN32 $_a $_exe $_o $_so );
+
+#------------------------------------------------------------------
+# Determine if running on win32 platform - either Windows NT or 95
+#------------------------------------------------------------------
+
+use vars qw( $PATH_SEPARATOR $iswin32 $_WIN32 $usage $indent @targets );
+
+BEGIN {
+ use Config;
+
+ # if the version is 5.003, we can check $^O
+ if ($] < 5.003) {
+ eval("require Win32");
+ $_WIN32 = (!$@);
+ } else {
+ $_WIN32 = ($^O eq "MSWin32") ? 1 : 0;
+ }
+
+ # Fetch the PATH separator from Config;
+ # provide our old defaults in case it's not set.
+ $PATH_SEPARATOR = $Config{path_sep};
+ $PATH_SEPARATOR = $_WIN32 ? ';' : ':' if ! defined $PATH_SEPARATOR;
+
+ # Fetch file suffixes from Config,
+ # accomodating differences in the Config variables
+ # used by different Perl versions.
+ $_exe = $Config{_exe};
+ $_exe = $Config{exe_ext} if ! defined $_exe;
+ $_exe = $_WIN32 ? '.exe' : '' if ! defined $_exe;
+ $_o = $Config{_o};
+ $_o = $Config{obj_ext} if ! defined $_o;
+ $_o = $_WIN32 ? '.obj' : '.o' if ! defined $_o;
+ $_a = $Config{_a};
+ $_a = $Config{lib_ext} if ! defined $_a;
+ $_a = $_WIN32 ? '.lib' : '.a' if ! defined $_a;
+ $_so = ".$Config{so}";
+ $_so = $_WIN32 ? '.dll' : '.so' if ! defined $_so;
+}
+
+# Flush stdout each time.
+$| = 1;
+
+# Seed random number generator.
+srand(time . $$); # this works better than time ^ $$ in perlfunc manpage.
+
+$usage = q(
+Usage: cons <arguments> -- <construct-args>
+
+Arguments can be any of the following, in any order:
+
+ <targets> Build the specified targets. If <target> is a directory
+ recursively build everything within that directory.
+
+ +<pattern> Limit the cons scripts considered to just those that
+ match <pattern>. Multiple + arguments are accepted.
+
+ <name>=<val> Sets <name> to value <val> in the ARG hash passed to the
+ top-level Construct file.
+
+ -cc Show command that would have been executed, when
+ retrieving from cache. No indication that the file
+ has been retrieved is given; this is useful for
+ generating build logs that can be compared with
+ real build logs.
+
+ -cd Disable all caching. Do not retrieve from cache nor
+ flush to cache.
+
+ -cr Build dependencies in random order. This is useful when
+ building multiple similar trees with caching enabled.
+
+ -cs Synchronize existing build targets that are found to be
+ up-to-date with cache. This is useful if caching has
+ been disabled with -cc or just recently enabled with
+ UseCache.
+
+ -d Enable dependency debugging.
+
+ -f <file> Use the specified file instead of "Construct" (but first
+ change to containing directory of <file>).
+
+ -h Show a help message local to the current build if
+ one such is defined, and exit.
+
+ -k Keep going as far as possible after errors.
+
+ -o <file> Read override file <file>.
+
+ -p Show construction products in specified trees.
+ -pa Show construction products and associated actions.
+ -pw Show products and where they are defined.
+
+ -q Be quiet; multiple -q flags increase quietness level:
+ 1: quiet about Installing and Removing targets
+ 2: quiet about build commands, up-to-date targets
+
+ -r Remove construction products associated with <targets>
+
+ -R <repos> Search for files in <repos>. Multiple -R <repos>
+ directories are searched in the order specified.
+
+ -S <pkg> Use package sig::<pkg> to calculate file signatures.
+ Currently supported values are "md5" for MD5
+ signatures (the default) and "md5::debug" for MD5
+ signature debug information.
+
+ -t Traverse up the directory hierarchy looking for a
+ Construct file, if none exists in the current directory.
+ (Targets will be modified to be relative to the
+ Construct file.)
+
+ -v Show cons version and continue processing.
+ -V Show cons version and exit.
+
+ -wf <file> Write all filenames considered into <file>.
+
+ -x Show this message and exit.
+
+
+ Please report any suggestions through the cons-discuss@gnu.org mailing
+ list.
+
+ To subscribe, send mail to cons-discuss-request@gnu.org with body
+ 'subscribe'.
+
+ If you find a bug, please report it through the bug-cons@gnu.org
+ mailing list.
+
+ Information about CONS can be obtained from the official cons web site
+ http://www.dsmit.com/cons/ or its mirrors (listed there).
+
+ The cons maintainers can be contacted by email at cons-maintainers@gnu.org
+
+ User documentation of cons is contained in cons and can be obtained
+ by doing 'perldoc /path/to/cons'.
+
+);
+
+# Simplify program name, if it is a path.
+{
+ my ($vol, $dir, $file) = File::Spec->splitpath(File::Spec->canonpath($0));
+ $0 = $file;
+}
+
+# Default parameters.
+$param::topfile = 'Construct'; # Top-level construction file.
+$param::install = 1; # Show installations
+$param::build = 1; # Build targets
+### $param::show = 1; # Show building of targets.
+$param::sigpro = 'md5'; # Signature protocol.
+$param::depfile = ''; # Write all deps out to this file
+$param::salt = ''; # Salt derived file signatures with this.
+$param::sourcesig = ['*' => 'content'];# Source file signature calculation
+$param::rep_sig_times_ok = 1; # Repository .consign times are in sync
+ # w/files.
+$param::conscript_chdir = 0; # Change dir to Conscript directory
+$param::quiet = 0; # should we show the command being executed.
+
+@param::defaults = ();
+
+#
+$indent = '';
+
+# Display a command while executing or otherwise. This
+# should be called by command builder action methods.
+sub showcom {
+ print($indent . $_[0] . "\n") if ($param::quiet < 2);
+}
+
+# Default environment.
+# This contains only the completely platform-independent information
+# we can figure out. Platform-specific information (UNIX, Win32)
+# gets added below.
+@param::base = (
+ 'SIGNATURE' => [ '*' => 'build' ],
+ 'SUFEXE' => $_exe, # '' on UNIX systems
+ 'SUFLIB' => $_a, # '.a' on UNIX systems
+ 'SUFLIBS' => "$_so:$_a", # '.so:.a' on UNIX
+ 'SUFOBJ' => $_o, # '.o' on UNIX systems
+ 'SUFMAP' => {
+ '.c' => 'build::command::cc',
+ '.s' => 'build::command::cc',
+ '.S' => 'build::command::cc',
+ '.C' => 'build::command::cxx',
+ '.cc' => 'build::command::cxx',
+ '.cxx'=> 'build::command::cxx',
+ '.cpp'=> 'build::command::cxx',
+ '.c++'=> 'build::command::cxx',
+ '.C++'=> 'build::command::cxx',
+ },
+ 'PERL' => $^X,
+);
+
+%param::rulesets =
+ (
+ # Defaults for Win32.
+ # Defined for VC++ 6.0 by Greg Spencer <greg_spencer@acm.org>
+ # Your mileage may vary.
+ 'msvc' => [
+ 'CC' => 'cl',
+ 'CFLAGS' => '/nologo',
+ 'CCCOM' => '%CC %CFLAGS %_IFLAGS /c %< /Fo%>',
+ 'CXX' => '%CC',
+ 'CXXFLAGS' => '%CFLAGS',
+ 'CXXCOM' => '%CXX %CXXFLAGS %_IFLAGS /c %< /Fo%>',
+ 'INCDIRPREFIX' => '/I',
+ 'INCDIRSUFFIX' => '',
+ 'LINK' => 'link',
+ 'LINKCOM' => '%LINK %LDFLAGS /out:%> %< %_LDIRS %LIBS',
+ 'LINKMODULECOM' => '%LD /r /o %> %<',
+ 'LIBDIRPREFIX' => '/LIBPATH:',
+ 'LIBDIRSUFFIX' => '',
+ 'AR' => 'lib',
+ 'ARFLAGS' => '/nologo ',
+ 'ARCOM' => "%AR %ARFLAGS /out:%> %<",
+ 'RANLIB' => '',
+ 'LD' => 'link',
+ 'LDFLAGS' => '/nologo ',
+ 'PREFLIB' => '',
+ ],
+ # Defaults for a typical (?) UNIX platform.
+ # Your mileage may vary.
+ 'unix' => [
+ 'CC' => 'cc',
+ 'CFLAGS' => '',
+ 'CCCOM' => '%CC %CFLAGS %_IFLAGS -c %< -o %>',
+ 'CXX' => '%CC',
+ 'CXXFLAGS' => '%CFLAGS',
+ 'CXXCOM' => '%CXX %CXXFLAGS %_IFLAGS -c %< -o %>',
+ 'INCDIRPREFIX' => '-I',
+ 'INCDIRSUFFIX' => '',
+ 'LINK' => '%CXX',
+ 'LINKCOM' => '%LINK %LDFLAGS -o %> %< %_LDIRS %LIBS',
+ 'LINKMODULECOM' => '%LD -r -o %> %<',
+ 'LIBDIRPREFIX' => '-L',
+ 'LIBDIRSUFFIX' => '',
+ 'AR' => 'ar',
+ 'ARFLAGS' => 'r', # rs?
+ 'ARCOM' => ['%AR %ARFLAGS %> %<', '%RANLIB %>'],
+ 'RANLIB' => 'ranlib',
+ 'AS' => 'as',
+ 'ASFLAGS' => '',
+ 'ASCOM' => '%AS %ASFLAGS %< -o %>',
+ 'LD' => 'ld',
+ 'LDFLAGS' => '',
+ 'PREFLIB' => 'lib',
+ 'ENV' => { 'PATH' => '/bin:/usr/bin' },
+ ],
+ );
+
+# Set the rules based on the platform.
+script::DefaultRules(script::RuleSet($_WIN32 ? 'msvc' : 'unix'));
+
+# Handle command line arguments.
+while (@ARGV) {
+ $_ = shift @ARGV;
+ last if /^--$/; # Argument passing to Construct.
+ &option, next if s/^-//;
+ push (@param::include, $_), next if s/^\+//;
+ &equate, next if /=/;
+ push (@targets, $_), next;
+}
+
+sub option {
+ my %opt = (
+ 'cc' => sub { $param::cachecom = 1; },
+ 'cd' => sub { $param::cachedisable = 1; },
+ 'cr' => sub { $param::random = 1; },
+ 'cs' => sub { $param::cachesync = 1; },
+ 'd' => sub { $param::depends = 1; },
+ 'h' => sub { $param::localhelp = 1; },
+ 'k' => sub { $param::kflag = 1; },
+ 'p' => sub { $param::pflag = 1;
+ $param::build = 0; },
+ 'pa' => sub { $param::pflag = 1;
+ $param::aflag = 1;
+ $indent = "... ";
+ $param::build = 0; },
+ 'pw' => sub { $param::pflag = 1;
+ $param::wflag = 1;
+ $param::build = 0; },
+ 'q' => sub { $param::quiet++; },
+ 'r' => sub { $param::rflag = 1;
+ $param::build = 0; },
+ 't' => sub { $param::traverse = 1; },
+ 'v' => sub { print($version); },
+ 'V' => sub { print($version), exit(0); },
+ 'x' => sub { print($usage), exit 0; },
+ );
+
+ my %opt_arg = (
+ 'f' => sub { $param::topfile = $_[0]; },
+ 'o' => sub { $param::overfile = $_[0]; },
+ 'R' => sub { script::Repository($_[0]); },
+ 'S' => sub { $param::sigpro = $_[0]; },
+ 'wf' => sub { $param::depfile = $_[0]; },
+ );
+
+ if (defined $opt{$_}) {
+ &{$opt{$_}}();
+ return;
+ }
+ while ($_) {
+ $_ =~ m/(.)(.*)/;
+ if (defined $opt{$1}) {
+ &{$opt{$1}}();
+ $_ = $2;
+ next;
+ }
+ if (defined $opt_arg{$1}) {
+ if (! $2) {
+ $_ = shift @ARGV;
+ die("$0: -$1 option requires an argument.\n") if ! $_;
+ }
+ &{$opt_arg{$1}}($2 || $_);
+ return;
+ }
+ $_ =~ m/(..)(.*)/;
+ if (defined $opt_arg{$1}) {
+ if (! $2) {
+ $_ = shift @ARGV;
+ die("$0: -$1 option requires an argument.\n") if ! $_;
+ }
+ &{$opt_arg{$1}}($2 || $_);
+ return;
+ }
+ if ($_) {
+ die qq($0: unrecognized option "-$_". Use -x for a usage message.\n);
+ }
+ }
+}
+
+# Process an equate argument (var=val).
+sub equate {
+ my($var, $val) = /([^=]*)=(.*)/;
+ $script::ARG{$var} = $val;
+}
+
+# Define file signature protocol.
+'sig'->select($param::sigpro);
+
+# Cleanup after an interrupt.
+$SIG{INT} = $SIG{QUIT} = $SIG{TERM} = sub {
+ $SIG{PIPE} = $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = 'IGNORE';
+ $SIG{HUP} = $SIG{INT} if ! $main::_WIN32;
+ warn("\n$0: killed\n");
+ # Call this first, to make sure that this processing
+ # occurs even if a child process does not die (and we
+ # hang on the wait).
+ sig::hash::END();
+ wait();
+ exit(1);
+};
+$SIG{HUP} = $SIG{INT} if ! $main::_WIN32;
+
+# Cleanup after a broken pipe (someone piped our stdout?)
+$SIG{PIPE} = sub {
+ $SIG{PIPE} = $SIG{HUP} = $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = 'IGNORE';
+ warn("\n$0: broken pipe\n");
+ sig::hash::END();
+ wait();
+ exit(1);
+};
+
+if ($param::depfile) {
+ open (main::DEPFILE, ">".$param::depfile) ||
+ die ("$0: couldn't open $param::depfile ($!)\n");
+}
+
+# If the supplied top-level Conscript file is not in the
+# current directory, then change to that directory.
+{
+ my ($vol, $dir, $file) =
+ File::Spec->splitpath(File::Spec->canonpath($param::topfile));
+ if ($vol || $dir) {
+ my($cd) = File::Spec->catpath($vol, $dir, undef);
+ chdir($cd) || die("$0: couldn't change to directory $cd ($!)\n");
+ $param::topfile = $file;
+ }
+}
+
+# Walk up the directory hierarchy looking for a Conscript file (if -t set).
+my($target_top);
+my(@targetdir) = ();
+if ($param::traverse && ! -f $param::topfile) {
+ my($vol, $dirs, $file) = File::Spec->splitpath(cwd());
+ my(@dirs) = (File::Spec->splitdir($dirs), $file);
+ while (! -f File::Spec->catpath($vol, File::Spec->catdir(@dirs),
+ $param::topfile)) {
+ die("$0: unable to find $param::topfile.\n") if ! @dirs;
+ unshift(@targetdir, pop(@dirs));
+ }
+ my($cwd) = File::Spec->catpath($vol, File::Spec->catdir(@dirs), '');
+ print "$0: Entering directory `$cwd'\n";
+ chdir($cwd);
+ @targets = map {File::Spec->catdir(@targetdir, $_)} @targets;
+}
+
+# Set up $dir::top and $dir::cwd, now that we are in the right directory.
+dir::init();
+
+#
+if (@targetdir) {
+ $target_top = $dir::top->lookupdir(File::Spec->catdir(@targetdir));
+}
+
+# Now handle override file.
+package override;
+if ($param::overfile) {
+ my($ov) = $param::overfile;
+ die qq($0: can\'t read override file "$ov" ($!)\n) if ! -f $ov; #'
+ do $ov;
+ if ($@) {
+ chop($@);
+ die qq($0: errors in override file "$ov" ($@)\n);
+ }
+}
+
+# Provide this to user to setup override patterns.
+sub Override {
+ my($re, @env) = @_;
+ return if $param::overrides{$re}; # if identical, first will win.
+ $param::overrides = 1;
+ $param::overrides{$re} = \@env;
+ push(@param::overrides, $re);
+}
+
+package main;
+
+use vars qw( %priority $errors );
+
+# Check script inclusion regexps
+my $re;
+for $re (@param::include) {
+ if (! defined eval {"" =~ /$re/}) {
+ my($err) = $@;
+ $err =~ s/in regexp at .*$//;
+ die("$0: error in regexp $err");
+ }
+}
+
+# Read the top-level construct file and its included scripts.
+doscripts($param::topfile);
+
+# Status priorities. This lets us aggregate status for directories
+# and print an appropriate message (at the top-level).
+%priority =
+ ('none' => 1, 'handled' => 2, 'built' => 3, 'unknown' => 4, 'errors' => 5);
+
+# If no targets were specified, supply default targets (if any).
+@targets = @param::default_targets if ! @targets;
+
+$errors = 0;
+
+# Build the supplied target patterns.
+my $tgt;
+for $tgt (map($dir::top->lookup($_), @targets)) {
+ if ($target_top && ! $tgt->is_under($target_top)) {
+ # A -t option was used, and this target is not underneath
+ # the directory where we were invoked via -t.
+ # If the target is a directory and the -t directory
+ # is underneath it, then build the -t directory.
+ if (ref $tgt ne "dir" || ! $target_top->is_under($tgt)) {
+ next;
+ }
+ $tgt = $target_top;
+ }
+ buildtoptarget($tgt);
+}
+
+exit 0 + ($errors != 0);
+
+sub buildtoptarget {
+ my($tgt) = @_;
+ return if ! $tgt;
+ my($status) = buildtarget($tgt);
+ if ($status ne 'built') {
+ my($path) = $tgt->path;
+ if ($status eq "errors") {
+ print qq($0: "$path" not remade because of errors.\n);
+ $errors++;
+ } elsif ($status eq "handled") {
+ print qq($0: "$path" is up-to-date.\n) if ($param::quiet < 2);
+ } elsif ($status eq "unknown") {
+ # cons error already reported.
+ $errors++;
+ } elsif ($status eq "none") {
+ # search for targets that may be linked to the given path.
+ my @linked = dir::linked_targets($tgt) if $target_top;
+ if (@linked) {
+ my @names = map($_->path, @linked);
+ print "Linked targets: @names\n" if ($param::quiet < 1);
+ map(buildtoptarget($_), @linked);
+ } else {
+ print qq($0: nothing to be built in "$path".\n)
+ if $param::build && ($param::quiet < 2);
+ }
+ } else {
+ print qq($0: don\'t know how to construct "$path".\n); #'
+ $errors++;
+ }
+ }
+}
+
+# Build the supplied target directory or files. Return aggregated status.
+sub buildtarget {
+ my($tgt) = @_;
+ if (ref($tgt) eq "dir") {
+ my($result) = "none";
+ my($priority) = $priority{$result};
+ if (exists $tgt->{member}) {
+ my($members) = $tgt->{member};
+ my $entry;
+ for $entry (sort keys %$members) {
+ next if $entry eq $dir::CURDIR || $entry eq $dir::UPDIR;
+ my($tgt) = $members->{$entry};
+ next if ref($tgt) ne "dir" && !exists($tgt->{builder});
+ my($stat) = buildtarget($members->{$entry});
+ my($pri) = $priority{$stat};
+ if ($pri > $priority) {
+ $priority = $pri;
+ $result = $stat;
+ }
+ }
+ }
+ return $result;
+ }
+ if ($param::depends) {
+ my($path) = $tgt->path;
+ if ($tgt->{builder}) {
+ my(@dep) = (@{$tgt->{dep}}, @{$tgt->{sources}});
+ my($dep) = join(' ',map($_->path, @dep));
+ print("Target $path: $dep\n");
+ } else {
+ print("Target $path: not a derived file\n");
+ }
+ }
+ if ($param::build) {
+ return build $tgt;
+ } elsif ($param::pflag || $param::wflag || $param::aflag) {
+ if ($tgt->{builder}) {
+ if ($param::wflag) {
+ print qq(${\$tgt->path}: $tgt->{script}\n);
+ } elsif ($param::pflag) {
+ print qq(${\$tgt->path}:\n) if $param::aflag;
+ print qq(${\$tgt->path}\n) if !$param::aflag;
+ }
+ if ($param::aflag) {
+ $tgt->{builder}->action($tgt);
+ }
+ }
+ } elsif ($param::rflag && $tgt->{builder}) {
+ my($path) = $tgt->path;
+ if (-f $path) {
+ if (unlink($path)) {
+ print("Removed $path\n") if ($param::quiet < 1);
+ } else {
+ warn("$0: couldn't remove $path\n");
+ }
+ }
+ }
+
+ return "none";
+}
+
+package NameSpace;
+
+# Return a hash that maps the name of symbols in a namespace to an
+# array of refs for all types for which the name has a defined value.
+# A list of symbols may be specified; default is all symbols in the
+# name space.
+sub save {
+ my $package = shift;
+ my(%namerefs, $var, $type);
+ no strict 'refs';
+ @_ = keys %{$package."::"} if ! @_;
+ foreach $var (@_) {
+ $namerefs{$var} = [];
+ my $fqvar = $package."::".$var;
+ # If the scalar for this variable name doesn't already
+ # exist, *foo{SCALAR} will autovivify the reference
+ # instead of returning undef, so unlike the other types,
+ # we have to dereference to find out if it exists.
+ push(@{$namerefs{$var}}, *{$fqvar}{SCALAR})
+ if defined ${*{$fqvar}{SCALAR}};
+ foreach $type (qw(ARRAY HASH CODE IO)) {
+ push(@{$namerefs{$var}}, *{$fqvar}{$type})
+ if defined *{$fqvar}{$type};
+ }
+ }
+ return \%namerefs;
+}
+
+# Remove the specified symbols from the namespace.
+# Default is to remove all.
+sub remove {
+ my $package = shift;
+ my(%namerefs, $var);
+ no strict 'refs';
+ @_ = keys %{$package."::"} if ! @_;
+ foreach $var (@_) {
+ delete ${$package."::"}{$var};
+ }
+}
+
+# Restore values to symbols specified in a hash as returned
+# by NameSpace::save.
+sub restore {
+ my($package, $namerefs) = @_;
+ my($var, $ref);
+ no strict 'refs';
+ foreach $var (keys %$namerefs) {
+ my $fqvar = $package."::".$var;
+ foreach $ref (@{$namerefs->{$var}}) {
+ *{$fqvar} = $ref;
+ }
+ }
+}
+
+# Support for "building" scripts, importing and exporting variables.
+# With the exception of the top-level routine here (invoked from the
+# main package by cons), these are all invoked by user scripts.
+package script;
+
+use vars qw( $ARG $caller_dir_path %special_var );
+
+BEGIN {
+ # We can't Export or Import the following variables because Perl always
+ # treats them as part of the "main::" package (see perlvar(1)).
+ %special_var = map {$_ => 1} qw(ENV INC ARGV ARGVOUT SIG
+ STDIN STDOUT STDERR);
+}
+
+# This is called from main to interpret/run the top-level Construct
+# file, passed in as the single argument.
+sub main::doscripts {
+ my($script) = @_;
+ Build($script);
+ # Now set up the includes/excludes (after the Construct file is read).
+ $param::include = join('|', @param::include);
+
+ # Save the original variable names from the script package.
+ # These will stay intact, but any other "script::" variables
+ # defined in a Conscript file will get saved, deleted,
+ # and (when necessary) restored.
+ my(%orig_script_var) = map {$_ => 1} keys %script::;
+ $caller_dir_path = undef;
+ my $cwd = Cwd::cwd();
+ my(@scripts) = pop(@priv::scripts);
+ while ($priv::self = shift(@scripts)) {
+ my($path) = $priv::self->{script}->rsrcpath;
+ if (-f $path) {
+ $dir::cwd = $priv::self->{script}->{dir};
+ # Handle chdir to the Conscript file directory, if necessary.
+ my ($vol, $dir, $file);
+ if ($param::conscript_chdir) {
+ ($vol, $dir, $file) =
+ File::Spec->splitpath(File::Spec->canonpath($path));
+ if ($vol ne '' || $dir ne '') {
+ $caller_dir_path = File::Spec->catpath($vol, $dir, undef);
+ chdir($caller_dir_path) ||
+ die "Could not chdir to $caller_dir_path: $!\n";
+ }
+ } else {
+ $file = $path;
+ }
+ # Actually process the Conscript file.
+ do $file;
+ # Save any variables defined by the Conscript file
+ # so we can restore them later, if needed;
+ # then delete them from the script:: namespace.
+ my(@del) = grep(! $orig_script_var{$_}, keys %script::);
+ if (@del) {
+ $priv::self->{script}->{pkgvars} = NameSpace::save('script',
+ @del);
+ NameSpace::remove('script', @del);
+ }
+ if ($caller_dir_path) {
+ chdir($cwd);
+ $caller_dir_path = undef;
+ }
+ if ($@) {
+ chomp($@);
+ my $err = ($@ =~ /\n/ms) ? ":\n$@" : " ($@)";
+ print qq($0: error in file "$path"$err\n);
+ $run::errors++;
+ } else {
+ # Only process subsidiary scripts if no errors in parent.
+ unshift(@scripts, @priv::scripts);
+ }
+ undef @priv::scripts;
+ } else {
+ my $where = '';
+ my $cref = $priv::self->{script}->creator;
+ if (defined $cref) {
+ my($_foo, $script, $line, $sub) = @$cref;
+ $where = " ($sub in $script, line $line)";
+ }
+ warn qq(Ignoring missing script "$path"$where);
+ }
+ }
+ die("$0: script errors encountered: construction aborted\n")
+ if $run::errors;
+}
+
+# Return caller info about the method being invoked.
+# This is everything from the Perl "caller" builtin function,
+# including which Construct/Conscript file, line number,
+# subroutine name, etc.
+sub caller_info {
+ my($lev) = 1;
+ my(@frame);
+ do {
+ @frame = caller ++$lev;
+ if (defined($frame[3]) && $frame[3] eq '(eval)') {
+ @frame = caller --$lev;
+ if ($caller_dir_path) {
+ $frame[1] = File::Spec->catfile($caller_dir_path, $frame[1]);
+ }
+ return @frame;
+ }
+ } while ($frame[3]);
+ return;
+}
+
+# Link a directory to another. This simply means set up the *source*
+# for the directory to be the other directory.
+sub Link {
+ dir::link(@_);
+}
+
+# Add directories to the repository search path for files.
+# Strip our current directory from the list so Repository
+# (or -R options) can be used from within the repository.
+sub Repository {
+ my($my_dir) = Cwd::cwd();
+ my $dir;
+ foreach $dir (@_) {
+ # The following more direct call isn't available in
+ # Cwd.pm until some time after 5.003...
+ # my($d) = Cwd::abs_path($dir);
+ chdir($dir);
+ my($d) = Cwd::cwd();
+ chdir($my_dir);
+ #
+ next if ! $d || ! -d $d || $d eq $my_dir;
+ # We know we can get away with passing undef to lookupdir
+ # as the directory because $dir is an absolute path.
+ push(@param::rpath, dir::lookupdir(undef, $dir));
+ push @INC, $d;
+ }
+}
+
+# Return the list of Repository directories specified.
+sub Repository_List {
+ map($_->path, @param::rpath);
+}
+
+# Specify whether the .consign signature times in repository files are,
+# in fact, consistent with the times on the files themselves.
+sub Repository_Sig_Times_OK {
+ $param::rep_sig_times_ok = shift;
+}
+
+sub SourceSignature {
+ $param::sourcesig = [@_];
+}
+
+# Specify whether we should chdir to the containing directories
+# of Conscript files.
+sub Conscript_chdir {
+ $param::conscript_chdir = shift;
+}
+
+# Specify files/targets that must be present and built locally,
+# even if they exist already-built in a Repository.
+sub Local {
+ my(@files) = map($dir::cwd->lookupfile($_), @_);
+ map($_->local(1), @files);
+}
+
+# Export variables to any scripts invoked from this one.
+sub Export {
+ my(@illegal) = grep($special_var{$_}, @_);
+ if (@illegal) {
+ die qq($0: cannot Export special Perl variables: @illegal\n);
+ }
+ @{$priv::self->{exports}} = grep(! defined $special_var{$_}, @_);
+}
+
+# Import variables from the export list of the caller
+# of the current script.
+sub Import {
+ my(@illegal) = grep($special_var{$_}, @_);
+ if (@illegal) {
+ die qq($0: cannot Import special Perl variables: @illegal\n);
+ }
+ my($parent) = $priv::self->{parent};
+ my($imports) = $priv::self->{imports};
+ @{$priv::self->{exports}} = keys %$imports;
+ my($var);
+ foreach $var (grep(! defined $special_var{$_}, @_)) {
+ if (!exists $imports->{$var}) {
+ my($path) = $parent->{script}->path;
+ die qq($0: variable "$var" not exported by file "$path"\n);
+ }
+ if (!defined $imports->{$var}) {
+ my $path = $parent->{script}->path;
+ my $err = "$0: variable \"$var\" exported but not " .
+ "defined by file \"$path\"\n";
+ die $err;
+ }
+ ${"script::$var"} = $imports->{$var};
+ }
+}
+
+# Build an inferior script. That is, arrange to read and execute
+# the specified script, passing to it any exported variables from
+# the current script.
+sub Build {
+ my(@files) = map($dir::cwd->lookupfile($_), @_);
+ my(%imports) = map {$_ => ${"script::$_"}} @{$priv::self->{exports}};
+ my $file;
+ for $file (@files) {
+ next if $param::include && $file->path !~ /$param::include/o;
+ my($self) = {'script' => $file,
+ 'parent' => $priv::self,
+ 'imports' => \%imports};
+ bless $self; # may want to bless into class of parent in future
+ push(@priv::scripts, $self);
+ }
+}
+
+# Set up regexps dependencies to ignore. Should only be called once.
+sub Ignore {
+ die("Ignore called more than once\n") if $param::ignore;
+ $param::ignore = join("|", map("($_)", @_)) if @_;
+}
+
+# Specification of default targets.
+sub Default {
+ push(@param::default_targets, map($dir::cwd->lookup($_)->path, @_));
+}
+
+# Local Help. Should only be called once.
+sub Help {
+ if ($param::localhelp) {
+ print "@_\n";
+ exit 2;
+ }
+}
+
+# For windows platforms which use unix tool sets, the msvc defaults may
+# not be useful. Also, in the future, other platforms (Mac?) may have the
+# same problem.
+sub RuleSet {
+ my $style = shift;
+ my @rulesets = sort keys %param::rulesets;
+ die "Unknown style for rules: $style.\n" .
+ "Supported rules are: (" . join(" ", @rulesets) . ")"
+ unless eval(join("||", map("\$style eq '$_'", @rulesets)));
+ return @param::base, @{$param::rulesets{$style}};
+}
+
+sub DefaultRules {
+ @param::defaults = ();
+ push @param::defaults, @_;
+}
+
+# Return the build name(s) of a file or file list.
+sub FilePath {
+ wantarray
+ ? map($dir::cwd->lookupfile($_)->path, @_)
+ : $dir::cwd->lookupfile($_[0])->path;
+}
+
+# Return the build name(s) of a directory or directory list.
+sub DirPath {
+ wantarray
+ ? map($dir::cwd->lookupdir($_)->path, @_)
+ : $dir::cwd->lookupdir($_[0])->path;
+}
+
+# Split the search path provided into components. Look each up
+# relative to the current directory.
+# The usual path separator problems abound; for now we'll use :
+sub SplitPath {
+ my($dirs) = @_;
+ if (ref($dirs) ne "ARRAY") {
+ $dirs = [ split(/$main::PATH_SEPARATOR/o, $dirs) ];
+ }
+ map { DirPath($_) } @$dirs;
+}
+
+# Return true if the supplied path is available as a source file
+# or is buildable (by rules seen to-date in the build).
+sub ConsPath {
+ my($path) = @_;
+ my($file) = $dir::cwd->lookup($path);
+ return $file->accessible;
+}
+
+# Return the source path of the supplied path.
+sub SourcePath {
+ wantarray
+ ? map($dir::cwd->lookupfile($_)->rsrcpath, @_)
+ : $dir::cwd->lookupfile($_[0])->rsrcpath;
+}
+
+# Search up the tree for the specified cache directory, starting with
+# the current directory. Returns undef if not found, 1 otherwise.
+# If the directory is found, then caching is enabled. The directory
+# must be readable and writable. If the argument "mixtargets" is provided,
+# then targets may be mixed in the cache (two targets may share the same
+# cache file--not recommended).
+sub UseCache($@) {
+ my($dir, @args) = @_;
+ # NOTE: it's important to process arguments here regardless of whether
+ # the cache is disabled temporarily, since the mixtargets option affects
+ # the salt for derived signatures.
+ for (@args) {
+ if ($_ eq "mixtargets") {
+ # When mixtargets is enabled, we salt the target signatures.
+ # This is done purely to avoid a scenario whereby if
+ # mixtargets is turned on or off after doing builds, and
+ # if cache synchronization with -cs is used, then
+ # cache files may be shared in the cache itself (linked
+ # under more than one name in the cache). This is not bad,
+ # per se, but simply would mean that a cache cleaning algorithm
+ # that looked for a link count of 1 would never find those
+ # particular files; they would always appear to be in use.
+ $param::salt = 'M' . $param::salt;
+ $param::mixtargets = 1;
+ } else {
+ die qq($0: UseCache unrecognized option "$_"\n);
+ }
+ }
+ if ($param::cachedisable) {
+ warn("Note: caching disabled by -cd flag\n");
+ return 1;
+ }
+ my($depth) = 15;
+ while ($depth-- && ! -d $dir) {
+ $dir = File::Spec->catdir($dir::UPDIR, $dir);
+ }
+ if (-d $dir) {
+ $param::cache = $dir;
+ return 1;
+ }
+ return undef;
+}
+
+# Salt the signature generator. The salt (a number of string) is added
+# into the signature of each derived file. Changing the salt will
+# force recompilation of all derived files.
+sub Salt($) {
+ # We append the value, so that UseCache and Salt may be used
+ # in either order without changing the signature calculation.
+ $param::salt .= $_[0];
+}
+
+# Mark files (or directories) to not be removed before building.
+sub Precious {
+ map($_->{precious} = 1, map($dir::cwd->lookup($_), @_));
+}
+
+
+# These methods are callable from Conscript files, via a cons
+# object. Procs beginning with _ are intended for internal use.
+package cons;
+
+use vars qw( %envcache );
+
+# This is passed the name of the base environment to instantiate.
+# Overrides to the base environment may also be passed in
+# as key/value pairs.
+sub new {
+ my($package) = shift;
+ my ($env) = {@param::defaults, @_};
+ @{$env->{_envcopy}} = %$env; # Note: we never change PATH
+ $env->{_cwd} = $dir::cwd; # Save directory of environment for
+ bless $env, $package; # any deferred name interpretation.
+}
+
+# Clone an environment.
+# Note that the working directory will be the initial directory
+# of the original environment.
+sub clone {
+ my($env) = shift;
+ my $clone = {@{$env->{_envcopy}}, @_};
+ @{$clone->{_envcopy}} = %$clone; # Note: we never change PATH
+ $clone->{_cwd} = $env->{_cwd};
+ bless $clone, ref $env;
+}
+
+# Create a flattened hash representing the environment.
+# It also contains a copy of the PATH, so that the path
+# may be modified if it is converted back to a hash.
+sub copy {
+ my($env) = shift;
+ (@{$env->{_envcopy}}, 'ENV' => {%{$env->{ENV}}}, @_)
+}
+
+# Resolve which environment to actually use for a given
+# target. This is just used for simple overrides.
+sub _resolve {
+ return $_[0] if !$param::overrides;
+ my($env, $tgt) = @_;
+ my($path) = $tgt->path;
+ my $re;
+ for $re (@param::overrides) {
+ next if $path !~ /$re/;
+ # Found one. Return a combination of the original environment
+ # and the override.
+ my($ovr) = $param::overrides{$re};
+ return $envcache{$env,$re} if $envcache{$env,$re};
+ my($newenv) = {@{$env->{_envcopy}}, @$ovr};
+ @{$newenv->{_envcopy}} = %$env;
+ $newenv->{_cwd} = $env->{_cwd};
+ return $envcache{$env,$re} = bless $newenv, ref $env;
+ }
+ return $env;
+}
+
+# Substitute construction environment variables into a string.
+# Internal function/method.
+sub _subst {
+ my($env, $str) = @_;
+ if (! defined $str) {
+ return undef;
+ } elsif (ref($str) eq "ARRAY") {
+ return [ map($env->_subst($_), @$str) ];
+ } else {
+ # % expansion. %% gets converted to % later, so expand any
+ # %keyword construction that doesn't have a % in front of it,
+ # modulo multiple %% pairs in between.
+ # In Perl 5.005 and later, we could actually do this in one regex
+ # using a conditional expression as follows,
+ # while ($str =~ s/($pre)\%(\{)?([_a-zA-Z]\w*)(?(2)\})/"$1".
+ # $env->{$3}/ge) {}
+ # The following two-step approach is backwards-compatible
+ # to (at least) Perl5.003.
+ my $pre = '^|[^\%](?:\%\%)*';
+ while (($str =~ s/($pre)\%([_a-zA-Z]\w*)/$1.($env->{$2}||'')/ge) ||
+ ($str =~ s/($pre)\%\{([_a-zA-Z]\w*)\}/$1.($env->{$2}||'')/ge)) {
+ }
+ return $str;
+ }
+}
+
+sub AfterBuild {
+ my($env) = shift;
+ my($perl_eval_str) = pop(@_);
+ my $file;
+ for $file (map($dir::cwd->lookup($_), @_)) {
+ $file->{after_build_func} = $perl_eval_str;
+ }
+}
+
+sub Install {
+ my($env) = shift;
+ my($tgtdir) = $dir::cwd->lookupdir($env->_subst(shift));
+ my $file;
+ for $file (map($dir::cwd->lookupfile($env->_subst($_)), @_)) {
+ my($tgt) = $tgtdir->lookupfile($file->{entry});
+ $tgt->bind(find build::install($env), $file);
+ }
+}
+
+sub InstallAs {
+ my $env = shift;
+ my $tgt = shift;
+ my $src = shift;
+ my @sources = ();
+ my @targets = ();
+
+ if (ref $tgt) {
+ die "InstallAs: Source is a file and target is a list!\n"
+ if (!ref($src));
+ @sources = @$src;
+ @targets = @$tgt;
+ } elsif (ref $src) {
+ die "InstallAs: Target is a file and source is a list!\n";
+ } else {
+ push @sources, $src;
+ push @targets, $tgt;
+ }
+
+ if ($#sources != $#targets) {
+ my $tn = $#targets+1;
+ my $sn = $#sources+1;
+ die "InstallAs: Source file list ($sn) and target file list ($tn) " .
+ "are inconsistent in length!\n";
+ } else {
+ foreach (0..$#sources) {
+ my $tfile = $dir::cwd->lookupfile($env->_subst($targets[$_]));
+ my $sfile = $dir::cwd->lookupfile($env->_subst($sources[$_]));
+ $tfile->bind(find build::install($env), $sfile);
+ }
+ }
+}
+
+# Installation in a local build directory,
+# copying from the repository if it's already built there.
+# Functionally equivalent to:
+# Install $env $dir, $file;
+# Local "$dir/$file";
+sub Install_Local {
+ my($env) = shift;
+ my($tgtdir) = $dir::cwd->lookupdir($env->_subst(shift));
+ my $file;
+ for $file (map($dir::cwd->lookupfile($env->_subst($_)), @_)) {
+ my($tgt) = $tgtdir->lookupfile($file->{entry});
+ $tgt->bind(find build::install($env), $file);
+ $tgt->local(1);
+ }
+}
+
+sub Objects {
+ my($env) = shift;
+ map($dir::cwd->relpath($_), $env->_Objects(@_));
+}
+
+# Called with multiple source file references (or object files).
+# Returns corresponding object files references.
+sub _Objects {
+ my($env) = shift;
+ my($suffix) = $env->{SUFOBJ};
+ map($env->_Object($_, $_->{dir}->lookupfile($_->base_suf($suffix))),
+ map { ref $_ ? $_ : $dir::cwd->lookupfile($env->_subst($_)) }
+ grep(defined $_, @_));
+}
+
+# Called with an object and source reference. If no object reference
+# is supplied, then the object file is determined implicitly from the
+# source file's extension. Sets up the appropriate rules for creating
+# the object from the source. Returns the object reference.
+sub _Object {
+ my($env, $src, $obj) = @_;
+ return $obj if $src eq $obj; # don't need to build self from self.
+ my($objenv) = $env->_resolve($obj);
+ my($suffix) = $src->suffix;
+
+ my($builder) = $env->{SUFMAP}{$suffix};
+
+ if ($builder) {
+ $obj->bind((find $builder($objenv)), $src);
+ } else {
+ die("don't know how to construct ${\$obj->path} from " .
+ "${\$src->path}.\n");
+ }
+ $obj
+}
+
+sub Program {
+ my($env) = shift;
+ my($tgt) = $dir::cwd->lookupfile(file::addsuffix($env->_subst(shift),
+ $env->{SUFEXE}));
+ my($progenv) = $env->_resolve($tgt);
+ $tgt->bind(find build::command::link($progenv, $progenv->{LINKCOM}),
+ $env->_Objects(@_));
+}
+
+sub Module {
+ my($env) = shift;
+ my($tgt) = $dir::cwd->lookupfile($env->_subst(shift));
+ my($modenv) = $env->_resolve($tgt);
+ my($com) = pop(@_);
+ $tgt->bind(find build::command::link($modenv, $com), $env->_Objects(@_));
+}
+
+sub LinkedModule {
+ my($env) = shift;
+ my($tgt) = $dir::cwd->lookupfile($env->_subst(shift));
+ my($progenv) = $env->_resolve($tgt);
+ $tgt->bind(find build::command::linkedmodule
+ ($progenv, $progenv->{LINKMODULECOM}),
+ $env->_Objects(@_));
+}
+
+sub Library {
+ my($env) = shift;
+ my($lib) = $dir::cwd->lookupfile(file::addsuffix($env->_subst(shift),
+ $env->{SUFLIB}));
+ my($libenv) = $env->_resolve($lib);
+ $lib->bind(find build::command::library($libenv), $env->_Objects(@_));
+}
+
+# Simple derivation: you provide target, source(s), command.
+# Special variables substitute into the rule.
+# Target may be a reference, in which case it is taken
+# to be a multiple target (all targets built at once).
+sub Command {
+ my($env) = shift;
+ my($tgt) = $env->_subst(shift);
+ my($builder) = find build::command::user($env, pop(@_), 'script');
+ my(@sources) = map($dir::cwd->lookupfile($env->_subst($_)), @_);
+ if (ref($tgt)) {
+ # A multi-target command.
+ my(@tgts) = map($dir::cwd->lookupfile($_), @$tgt);
+ die("empty target list in multi-target command\n") if !@tgts;
+ $env = $env->_resolve($tgts[0]);
+ my($multi) = build::multiple->new($builder, \@tgts);
+ for $tgt (@tgts) {
+ $tgt->bind($multi, @sources);
+ }
+ } else {
+ $tgt = $dir::cwd->lookupfile($tgt);
+ $env = $env->_resolve($tgt);
+ $tgt->bind($builder, @sources);
+ }
+}
+
+sub Depends {
+ my($env) = shift;
+ my($tgt) = $env->_subst(shift);
+ my(@deps) = map($dir::cwd->lookup($env->_subst($_)), @_);
+ if (! ref($tgt)) {
+ $tgt = [ $tgt ];
+ }
+ my($t);
+ foreach $t (map($dir::cwd->lookupfile($_), @$tgt)) {
+ push(@{$t->{dep}}, @deps);
+ }
+}
+
+# Setup a quick scanner for the specified input file, for the
+# associated environment. Any use of the input file will cause the
+# scanner to be invoked, once only. The scanner sees just one line at
+# a time of the file, and is expected to return a list of
+# dependencies.
+sub QuickScan {
+ my($env, $code, $file, $path) = @_;
+ $dir::cwd->lookup($env->_subst($file))->{'srcscan',$env} =
+ find scan::quickscan($code, $env, $env->_subst($path));
+}
+
+# Generic builder module. Just a few default methods. Every derivable
+# file must have a builder object of some sort attached. Usually
+# builder objects are shared.
+package build;
+
+use vars qw( %builder );
+
+# Every builder must now have at least an associated environment,
+# so we can find its sigarray and calculate the proper signature.
+sub find {
+ my($class, $env) = @_;
+ $builder{$env} || do {
+ my $self = { env => $env };
+ $builder{$env} = bless $self, $class;
+ }
+}
+
+# Null signature for dynamic includes.
+sub includes { () }
+
+# Null signature for build script.
+sub scriptsig { () }
+
+# Not compatible with any other builder, by default.
+sub compatible { 0 }
+
+
+# Builder module for the Install command.
+package build::install;
+
+use vars qw( @ISA );
+
+BEGIN { @ISA = qw(build) }
+
+# Caching not supported for Install: generally install is trivial anyway,
+# and we don't want to clutter the cache.
+sub cachin { undef }
+sub cachout { }
+
+# Do the installation.
+sub action {
+ my($self, $tgt) = @_;
+ my($src) = $tgt->{sources}[0];
+ main::showcom("Install ${\$src->rpath} as ${\$tgt->path}")
+ if ($param::install && $param::quiet < 1);
+ return unless $param::build;
+ futil::install($src->rpath, $tgt);
+ return 1;
+}
+
+
+# Builder module for generic UNIX commands.
+package build::command;
+
+use vars qw( @ISA %com );
+
+BEGIN { @ISA = qw(build) }
+
+sub find {
+ my($class, $env, $cmd, $package) = @_;
+ my($act) = action::new($env, $cmd);
+ $package ||= '';
+ $com{$env,$act,$package} || do {
+ my $self = { env => $env, act => $act, 'package' => $package };
+ $com{$env,$act,$package} = bless $self, $class;
+ }
+}
+
+# Default cache in function.
+sub cachin {
+ my($self, $tgt, $sig) = @_;
+ if (cache::in($tgt, $sig)) {
+ if ($param::cachecom) {
+ $self->{act}->show($self->{env}, $tgt);
+ } else {
+ printf("Retrieved %s from cache\n", $tgt->path)
+ if ($param::quiet < 1);
+ }
+ return 1;
+ }
+ return undef;
+}
+
+# Default cache out function.
+sub cachout {
+ my($self, $tgt, $sig) = @_;
+ cache::out($tgt, $sig);
+}
+
+# Build the target using the previously specified commands.
+sub action {
+ my($self, $tgt) = @_;
+ $self->{act}->execute($self->{env}, $tgt, $self->{'package'});
+}
+
+# Return script signature.
+sub scriptsig {
+ $_[0]->{act}->scriptsig
+}
+
+
+# Create a linked module.
+package build::command::link;
+
+use vars qw( @ISA );
+
+BEGIN { @ISA = qw(build::command) }
+
+# Find an appropriate linker.
+sub find {
+ my($class, $env, $command) = @_;
+ if (!exists $env->{_LDIRS}) {
+ my($ldirs) = '';
+ my($wd) = $env->{_cwd};
+ my($pdirs) = $env->{LIBPATH};
+ if (! defined $pdirs) {
+ $pdirs = [ ];
+ } elsif (ref($pdirs) ne 'ARRAY') {
+ $pdirs = [ split(/$main::PATH_SEPARATOR/o, $pdirs) ];
+ }
+ my($dir, $dpath);
+ for $dir (map($wd->lookupdir($env->_subst($_)), @$pdirs)) {
+ $dpath = $dir->path;
+ # Add the (presumably local) directory to the -L flags
+ # if we're not using repositories, the directory exists,
+ # or it's Linked to a source directory (that is, it *will*
+ # exist by the time the link occurs).
+ $ldirs .= " ".$env->{LIBDIRPREFIX}.$dpath.$env->{LIBDIRSUFFIX}
+ if ! @param::rpath || -d $dpath || $dir->is_linked;
+ next if File::Spec->file_name_is_absolute($dpath);
+ if (@param::rpath) {
+ my $d;
+ if ($dpath eq $dir::CURDIR) {
+ foreach $d (map($_->path, @param::rpath)) {
+ $ldirs .= " " . $env->{LIBDIRPREFIX} .
+ $d . $env->{LIBDIRSUFFIX};
+ }
+ } else {
+ my($rpath);
+ foreach $d (map($_->path, @param::rpath)) {
+ $rpath = File::Spec->catfile($d, $dpath);
+ $ldirs .= " ". $env->{LIBDIRPREFIX} .
+ $rpath . $env->{LIBDIRSUFFIX} if -d $rpath;
+ }
+ }
+ }
+ }
+ $env->{_LDIRS} = "%($ldirs%)";
+ }
+
+ # Introduce a new magic _LIBS symbol which allows to use the
+ # Unix-style -lNAME syntax for Win32 only. -lNAME will be replaced
+ # with %{PREFLIB}NAME%{SUFLIB}. <schwarze@isa.de> 1998-06-18
+
+ if ($main::_WIN32 && !exists $env->{_LIBS}) {
+ my $libs;
+ my $name;
+ for $name (split(' ', $env->_subst($env->{LIBS} || ''))) {
+ if ($name =~ /^-l(.*)/) {
+ $name = "$env->{PREFLIB}$1$env->{SUFLIB}";
+ }
+ $libs .= ' ' . $name;
+ }
+ $env->{_LIBS} = $libs ? "%($libs%)" : '';
+ }
+ bless find build::command($env, $command);
+}
+
+# Called from file::build. Make sure any libraries needed by the
+# environment are built, and return the collected signatures
+# of the libraries in the path.
+sub includes {
+ return $_[0]->{'bsig'} if exists $_[0]->{'bsig'};
+ my($self, $tgt) = @_;
+ my($env) = $self->{env};
+ my($ewd) = $env->{_cwd};
+ my $ldirs = $env->{LIBPATH};
+ if (! defined $ldirs) {
+ $ldirs = [ ];
+ } elsif (ref($ldirs) ne 'ARRAY') {
+ $ldirs = [ split(/$main::PATH_SEPARATOR/o, $ldirs) ];
+ }
+ my @lpath = map($ewd->lookupdir($_), @$ldirs);
+ my(@sigs);
+ my(@names);
+
+ # Pass %LIBS symbol through %-substituition
+ # <schwarze@isa.de> 1998-06-18
+ @names = split(' ', $env->_subst($env->{LIBS} || ''));
+ my $name;
+ for $name (@names) {
+ my ($lpath, @allnames);
+ if ($name =~ /^-l(.*)/) {
+ # -l style names are looked up on LIBPATH, using all
+ # possible lib suffixes in the same search order the
+ # linker uses (according to SUFLIBS).
+ # Recognize new PREFLIB symbol, which should be 'lib' on
+ # Unix, and empty on Win32. TODO: What about shared
+ # library suffixes? <schwarze@isa.de> 1998-05-13
+ @allnames = map("$env->{PREFLIB}$1$_",
+ split(/:/, $env->{SUFLIBS}));
+ $lpath = \@lpath;
+ } else {
+ @allnames = ($name);
+ # On Win32, all library names are looked up in LIBPATH
+ # <schwarze@isa.de> 1998-05-13
+ if ($main::_WIN32) {
+ $lpath = [$dir::top, @lpath];
+ }
+ else {
+ $lpath = [$dir::top];
+ }
+ }
+ my $dir;
+ DIR: for $dir (@$lpath) {
+ my $n;
+ for $n (@allnames) {
+ my($lib) = $dir->lookup_accessible($n);
+ if ($lib) {
+ last DIR if $lib->ignore;
+ if ((build $lib) eq 'errors') {
+ $tgt->{status} = 'errors';
+ return undef;
+ }
+ push(@sigs, 'sig'->signature($lib));
+ last DIR;
+ }
+ }
+ }
+ }
+ $self->{'bsig'} = 'sig'->collect(@sigs);
+}
+
+# Always compatible with other such builders, so the user
+# can define a single program or module from multiple places.
+sub compatible {
+ my($self, $other) = @_;
+ ref($other) eq "build::command::link";
+}
+
+# Link a program.
+package build::command::linkedmodule;
+
+use vars qw( @ISA );
+
+BEGIN { @ISA = qw(build::command) }
+
+# Always compatible with other such builders, so the user
+# can define a single linked module from multiple places.
+sub compatible {
+ my($self, $other) = @_;
+ ref($other) eq "build::command::linkedmodule";
+}
+
+# Builder for a C module
+package build::command::cc;
+
+use vars qw( @ISA );
+
+BEGIN { @ISA = qw(build::command) }
+
+sub find {
+ $_[1]->{_cc} || do {
+ my($class, $env) = @_;
+ my($cpppath) = $env->_subst($env->{CPPPATH});
+ my($cscanner) = find scan::cpp($env->{_cwd}, $cpppath);
+ $env->{_IFLAGS} = "%(" . $cscanner->iflags($env) . "%)";
+ my($self) = find build::command($env, $env->{CCCOM});
+ $self->{scanner} = $cscanner;
+ bless $env->{_cc} = $self;
+ }
+}
+
+# Invoke the associated C scanner to get signature of included files.
+sub includes {
+ my($self, $tgt) = @_;
+ $self->{scanner}->includes($tgt, $tgt->{sources}[0]);
+}
+
+# Builder for a C++ module
+package build::command::cxx;
+
+use vars qw( @ISA );
+
+BEGIN { @ISA = qw(build::command) }
+
+sub find {
+ $_[1]->{_cxx} || do {
+ my($class, $env) = @_;
+ my($cpppath) = $env->_subst($env->{CPPPATH});
+ my($cscanner) = find scan::cpp($env->{_cwd}, $cpppath);
+ $env->{_IFLAGS} = "%(" . $cscanner->iflags($env) . "%)";
+ my($self) = find build::command($env, $env->{CXXCOM});
+ $self->{scanner} = $cscanner;
+ bless $env->{_cxx} = $self;
+ }
+}
+
+# Invoke the associated C scanner to get signature of included files.
+sub includes {
+ my($self, $tgt) = @_;
+ $self->{scanner}->includes($tgt, $tgt->{sources}[0]);
+}
+
+# Builder for a user command (cons::Command). We assume that a user
+# command might be built and implement the appropriate dependencies on
+# the command itself (actually, just on the first word of the command
+# line).
+package build::command::user;
+
+use vars qw( @ISA );
+
+BEGIN { @ISA = qw(build::command) }
+
+sub includes {
+ my($self, $tgt) = @_;
+ my($sig) = '';
+
+ # Check for any quick scanners attached to source files.
+ my $dep;
+ for $dep (@{$tgt->{dep}}, @{$tgt->{sources}}) {
+ my($scanner) = $dep->{'srcscan',$self->{env}};
+ if ($scanner) {
+ $sig .= $scanner->includes($tgt, $dep);
+ }
+ }
+
+ # XXX Optimize this to not use ignored paths.
+ if (! exists $self->{_comsig}) {
+ my($env) = $self->{env};
+ $self->{_comsig} = '';
+ my($com, $dir);
+ com:
+ for $com ($self->{act}->commands) {
+ my($pdirs) = $env->{ENV}->{PATH};
+ if (! defined $pdirs) {
+ $pdirs = [ ];
+ } elsif (ref($pdirs) ne 'ARRAY') {
+ $pdirs = [ split(/$main::PATH_SEPARATOR/o, $pdirs) ];
+ }
+ for $dir (map($dir::top->lookupdir($_), @$pdirs)) {
+ my($prog) = $dir->lookup_accessible($com);
+ if ($prog) { # XXX Not checking execute permission.
+ if ((build $prog) eq 'errors') {
+ $tgt->{status} = 'errors';
+ return $sig;
+ }
+ next com if $prog->ignore;
+ $self->{_comsig} .= 'sig'->signature($prog);
+ next com;
+ }
+ }
+ }
+ }
+
+ return $self->{_comsig} . $sig
+}
+
+
+# Builder for a library module (archive).
+# We assume that a user command might be built and implement the
+# appropriate dependencies on the command itself.
+package build::command::library;
+
+use vars qw( @ISA );
+
+BEGIN { @ISA = qw(build::command) }
+
+sub find {
+ my($class, $env) = @_;
+ bless find build::command($env, $env->{ARCOM})
+}
+
+# Always compatible with other library builders, so the user
+# can define a single library from multiple places.
+sub compatible {
+ my($self, $other) = @_;
+ ref($other) eq "build::command::library";
+}
+
+# A multi-target builder.
+# This allows multiple targets to be associated with a single build
+# script, without forcing all the code to be aware of multiple targets.
+package build::multiple;
+
+sub new {
+ my($class, $builder, $tgts) = @_;
+ bless { 'builder' => $builder, 'env' => $builder->{env}, 'tgts' => $tgts };
+}
+
+sub scriptsig {
+ my($self, $tgt) = @_;
+ $self->{builder}->scriptsig($tgt);
+}
+
+sub includes {
+ my($self, $tgt) = @_;
+ $self->{builder}->includes($tgt);
+}
+
+sub compatible {
+ my($self, $tgt) = @_;
+ $self->{builder}->compatible($tgt);
+}
+
+sub cachin {
+ my($self, $tgt, $sig) = @_;
+ $self->{builder}->cachin($tgt, $sig);
+}
+
+sub cachout {
+ my($self, $tgt, $sig) = @_;
+ $self->{builder}->cachout($tgt, $sig);
+}
+
+sub action {
+ my($self, $invoked_tgt) = @_;
+ return $self->{built} if exists $self->{built};
+
+ # Make sure all targets in the group are unlinked before building any.
+ my($tgts) = $self->{tgts};
+ my $tgt;
+ for $tgt (@$tgts) {
+ futil::mkdir($tgt->{dir});
+ unlink($tgt->path) if ! $tgt->precious;
+ }
+
+ # Now do the action to build all the targets. For consistency
+ # we always call the action on the first target, just so that
+ # $> is deterministic.
+ $self->{built} = $self->{builder}->action($tgts->[0]);
+
+ # Now "build" all the other targets (except for the one
+ # we were called with). This guarantees that the signature
+ # of each target is updated appropriately. We force the
+ # targets to be built even if they have been previously
+ # considered and found to be OK; the only effect this
+ # has is to make sure that signature files are updated
+ # correctly.
+ for $tgt (@$tgts) {
+ if ($tgt ne $invoked_tgt) {
+ delete $tgt->{status};
+ 'sig'->invalidate($tgt);
+ build $tgt;
+ }
+ }
+
+ # Status of action.
+ $self->{built};
+}
+
+package action;
+
+sub new {
+ my($env, $act) = @_;
+ if (ref($act) eq 'CODE') {
+ return action::perl->new($act);
+ } else {
+ return action::command->new($env, $act);
+ }
+}
+
+package action::command;
+
+use vars qw( @ISA %cmd %_varopts $_varletters );
+
+BEGIN {
+ @ISA = $main::_WIN32 ? 'action::command::win32' : 'action::command::unix';
+
+ # Internal hash for processing variable options.
+ # f: return file part
+ # d: return directory part
+ # F: return file part, but strip any suffix
+ # b: return full path, but strip any suffix (a.k.a. return basename)
+ # s: return only the suffix (or an empty string, if no suffix is there)
+ # a: return the absolute path to the file
+ # S: return the absolute path to a Linked source file
+ %_varopts = (
+ 'f' => sub { return $_[0]->{entry}; },
+ 'd' => sub { return $_[0]->{dir}->path; },
+ 'F' => sub { my $subst = $_[0]->{entry};
+ $subst =~ s/\.[^\.]+$//;
+ return $subst; },
+ 'b' => sub { my $subst = $_[0]->path;
+ $subst =~ s/\.[^\.]+$//;
+ return $subst; },
+ 's' => sub { my $subst = $_[0]->{entry};
+ $subst =~ m/(\.[^\.]+)$/;
+ return $1; },
+ 'a' => sub { my $path = $_[0]->path;
+ if (! File::Spec->file_name_is_absolute($path)) {
+ $path = File::Spec->catfile(Cwd::cwd(), $path);
+ }
+ return $path; },
+ 'S' => sub { my $path = $_[0]->srcpath;
+ if (! File::Spec->file_name_is_absolute($path)) {
+ my $cwd = File::Spec->canonpath(Cwd::cwd());
+ $path = File::Spec->catfile($cwd, $path);
+ }
+ return $path; },
+ );
+
+ $_varletters = join('', keys %_varopts);
+}
+
+# Internal routine for processing variable options.
+# Options are specified in hash in the BEGIN block above.
+# no option: return path to file (relative to top,
+# or absolute if it's outside)
+sub _variant {
+ my($opt, $file) = @_;
+ $opt = '' if ! defined $opt;
+ if (defined $_varopts{$opt}) {
+ return &{$_varopts{$opt}}($file);
+ }
+ return $file->path;
+}
+
+sub new {
+ my($class, $env, $cmd) = @_;
+ $cmd = $env->_subst($cmd);
+ $cmd{$env,$cmd} || do {
+ # Remove unwanted bits from signature -- those bracketed by %( ... %)
+ my $sigs = $cmd;
+ my $sig = '';
+ if (ref($sigs) eq 'ARRAY') {
+ # This is an array of commands..
+ my $f;
+ foreach $f (@$sigs) {
+ $sig .= _strip($f);
+ }
+ } else {
+ $sig = _strip($sigs);
+ }
+ my $self = { cmd => $cmd, cmdsig => 'sig'->cmdsig($sig) };
+ $cmd{$env,$cmd} = bless $self, $class;
+ }
+}
+
+sub _strip {
+ my $sig = shift;
+ $sig =~ s/^\@\s*//mg;
+ while ($sig =~ s/%\(([^%]|%[^\(])*?%\)//g) { }
+ $sig;
+}
+
+sub scriptsig {
+ $_[0]->{cmdsig};
+}
+
+# Return an array of all the commands (first word on each line).
+sub commands {
+ my($self) = @_;
+ my(@cmds) = ();
+ my $com;
+ my $cmd = $self->{'cmd'};
+ my @allcoms;
+
+ push @allcoms, ref $cmd ? @{$cmd} : split(/\n/, $cmd);
+
+ for $com (@allcoms) {
+ $com =~ s/^\s*//;
+ $com =~ s/\s.*//;
+ next if ! $com; # blank line
+ push @cmds, $com;
+ }
+ @cmds;
+}
+
+# For the signature of a basic command, we don't bother
+# including the command itself. This is not strictly correct,
+# and if we wanted to be rigorous, we might want to insist
+# that the command was checked for all the basic commands
+# like gcc, etc. For this reason we don't have an includes
+# method.
+
+# Call this to get the command line script: an array of
+# fully substituted commands.
+sub getcoms {
+ my($self, $env, $tgt) = @_;
+ my(@coms);
+ my $com;
+ my @allcoms = ();
+ my $cmd = $self->{'cmd'};
+
+ push @allcoms, ref $cmd ? @{$cmd} : split(/\n/, $cmd);
+
+ for $com (@allcoms) {
+ my(@src) = (undef, @{$tgt->{sources}});
+ my(@src1) = @src;
+
+ next if $com =~ /^\s*$/;
+
+ # NOTE: we used to have a more elegant s//.../e solution
+ # for the items below, but this caused a bus error...
+
+ # Remove %( and %) -- those are only used to bracket parts
+ # of the command that we don't depend on.
+ $com =~ s/%[()]//g;
+
+ # Deal with %n, n=1,9 and variants.
+ while ($com =~ /%([1-9])(:([$_varletters]?))?/o) {
+ my($match) = $&;
+ my($src) = $src1[$1];
+ my($subst) = _variant($3, $src1[$1]->rfile);
+ undef $src[$1];
+ $com =~ s/$match/$subst/;
+ }
+
+ # Deal with %0 aka %> and variants.
+ while ($com =~ /%[0>](:([$_varletters]?))?/o) {
+ my($match) = $&;
+ my($subst) = _variant($2, $tgt);
+ $com =~ s/$match/$subst/;
+ }
+
+ # Deal with %< (all sources except %n's already used)
+ while ($com =~ /%<(:([$_varletters]?))?/o) {
+ my($match) = $&;
+ my @list = ();
+ foreach (@src) {
+ push(@list, _variant($2, $_->rfile)) if $_;
+ }
+ my($subst) = join(' ', @list);
+ $com =~ s/$match/$subst/;
+ }
+
+ # Deal with %[ %].
+ $com =~ s{%\[(.*?)%\]}{
+ my($func, @args) = grep { $_ ne '' } split(/\s+/, $1);
+ die("$0: \"$func\" is not defined.\n")
+ unless ($env->{$func});
+ &{$env->{$func}}(@args);
+ }gex;
+
+ # Convert left-over %% into %.
+ $com =~ s/%%/%/g;
+
+ # White space cleanup. XXX NO WAY FOR USER TO HAVE QUOTED SPACES
+ $com = join(' ', split(' ', $com));
+ next if $com =~ /^:/ && $com !~ /^:\S/;
+ push(@coms, $com);
+ }
+ @coms
+}
+
+# Build the target using the previously specified commands.
+sub execute {
+ my($self, $env, $tgt, $package) = @_;
+
+ if ($param::build) {
+ futil::mkdir($tgt->{dir});
+ unlink($tgt->path) if ! $tgt->precious;
+ }
+
+ # Set environment.
+ map(delete $ENV{$_}, keys %ENV);
+ %ENV = %{$env->{ENV}};
+
+ # Handle multi-line commands.
+ my $com;
+ for $com ($self->getcoms($env, $tgt)) {
+ if ($com !~ s/^\@\s*//) {
+ main::showcom($com);
+ }
+ next if ! $param::build;
+
+ if ($com =~ /^\[perl\]\s*/) {
+ my $perlcmd = $';
+ my $status;
+ {
+ # Restore the script package variables that were defined
+ # in the Conscript file that defined this [perl] build,
+ # so the code executes with the expected variables.
+ # Then actually execute (eval) the [perl] command to build
+ # the target, followed by cleaning up the name space
+ # by deleting the package variables we just restored.
+ my($pkgvars) = $tgt->{conscript}->{pkgvars};
+ NameSpace::restore($package, $pkgvars) if $pkgvars;
+ $status = eval "package $package; $perlcmd";
+ NameSpace::remove($package, keys %$pkgvars) if $pkgvars;
+ }
+ if (!defined($status)) {
+ warn "$0: *** Error during perl command eval: $@.\n";
+ return undef;
+ } elsif ($status == 0) {
+ warn "$0: *** Perl command returned $status "
+ . "(this indicates an error).\n";
+ return undef;
+ }
+ next;
+ }
+ if (! $self->do_command($com, $tgt->path)) {
+ return undef;
+ }
+ }
+
+ # success.
+ return 1;
+}
+
+sub show {
+ my($self, $env, $tgt) = @_;
+ my $com;
+ for $com ($self->getcoms($env, $tgt)) {
+ if ($com !~ /^\@\s*/) {
+ main::showcom($com);
+ }
+ }
+}
+
+package action::command::unix;
+
+sub do_command {
+ my($class, $com, $path) = @_;
+ my($pid) = fork();
+ die("$0: unable to fork child process ($!)\n") if !defined $pid;
+ if (!$pid) {
+ # This is the child. We eval the command to suppress -w
+ # warnings about not reaching the statements afterwards.
+ eval 'exec($com)';
+ $com =~ s/\s.*//;
+ die qq($0: failed to execute "$com" ($!). )
+ . qq(Is this an executable on path "$ENV{PATH}"?\n);
+ }
+ for (;;) {
+ do {} until wait() == $pid;
+ my ($b0, $b1) = ($? & 0xFF, $? >> 8);
+ # Don't actually see 0177 on stopped process; is this necessary?
+ next if $b0 == 0177; # process stopped; we can wait.
+ if ($b0) {
+ my($core, $sig) = ($b0 & 0200, $b0 & 0177);
+ my($coremsg) = $core ? "; core dumped" : "";
+ $com =~ s/\s.*//;
+ my $err = "$0: *** \[$path\] $com terminated by signal " .
+ "$sig$coremsg\n";
+ warn $err;
+ return undef;
+ }
+ if ($b1) {
+ warn qq($0: *** [$path] Error $b1\n); # trying to be like make.
+ return undef;
+ }
+ last;
+ }
+ return 1;
+}
+
+package action::command::win32;
+
+sub do_command {
+ my($class, $com, $path) = @_;
+ system($com);
+ if ($?) {
+ my ($b0, $b1) = ($? & 0xFF, $? >> 8);
+ my $err = $b1 || $?;
+ my $warn = qq($0: *** [$path] Error $err);
+ $warn .= " (executable not found in path?)" if $b1 == 0xFF;
+ warn "$warn\n";
+ return undef;
+ }
+ return 1;
+}
+
+package action::perl;
+
+# THIS IS AN EXPERIMENTAL PACKAGE. It's entirely possible that the
+# interface may change as this gets completed, so use at your own risk.
+#
+# There are (at least) two issues that need to be solved before blessing
+# this as a real, fully-supported feature:
+#
+# -- We need to calculate a signature value for a Perl code ref, in
+# order to rebuild the target if there's a change to the Perl code
+# used to generate it.
+#
+# This is not straightforward. A B::Deparse package exists that
+# decompiles a coderef into text. It's reportedly not completely
+# reliable for closures; it misses which variables are global, and
+# the values of private lexicals. Nevertheless, it'd probably
+# be perfect for our purposes, except that it wasn't added until
+# some time between Perl 5.00502 and 5.00554, and doesn't seem to
+# really work until Perl 5.6.0, so by relying on it, we'd lose
+# support for Perl versions back to 5.003*.
+#
+# -- Ideally, a code ref should be able to use something like
+# $env->_subst to fetch values from the construction environment
+# to modify its behavior without having to cut-and-paste code.
+# (Actually, since we pass the environment to the executed code
+# ref, there's no reason you can't do this with the code as it
+# stands today.) But this REALLY complicates the signature
+# calculation, because now the actual signature would depend not
+# just on the code contents, but on the construction variables (or
+# maybe just the environment).
+#
+# A potentially valid workaround would be to use the contents of the
+# Conscript file in which the code reference is defined as the code
+# ref's signature. This has the drawback of causing a recompilation of
+# the target file even in response to unrelated changes in the Conscript
+# file, but it would ensure correct builds without having to solve the
+# messy issues of generating a signature directly from a code ref.
+#
+# Nevertheless, this seemed a useful enough skeleton of a feature that
+# it made sense to release it in hopes that some practical experience
+# will encourage someone to figure out how to solve the signature
+# issues. Or maybe we'll discover these aren't big issues in practice
+# and end up blessing it as is.
+
+use vars qw( %code );
+
+sub new {
+ my($class, $cref) = @_;
+ $code{$cref} || do {
+ my $sig = '';
+ # Generating a code signature using B::Deparse doesn't really
+ # work for us until Perl 5.6.0. Here's the code in case
+ # someone wants to use it.
+ #use B::Deparse;
+ #my $deparse = B::Deparse->new();
+ #my $body = $deparse->coderef2text($cref);
+ #$sig = $body; # should be an MD5 sig
+ my($self) = { cref => $cref, crefsig => $sig };
+ $code{$cref} = bless $self, $class;
+ }
+}
+
+sub scriptsig {
+ $_[0]->{crefsig}
+}
+
+sub execute {
+ my($self, $env, $tgt) = @_;
+ if ($param::build) {
+ futil::mkdir($tgt->{dir});
+ unlink($tgt->path) if ! $tgt->precious;
+ my($cref) = $self->{cref};
+ &$cref($env, $tgt->path, map($_->rpath, @{$tgt->{sources}}));
+ }
+}
+
+sub commands {
+ return ();
+}
+
+
+# Generic scanning module.
+package scan;
+
+# Returns the signature of files included by the specified files on
+# behalf of the associated target. Any errors in handling the included
+# files are propagated to the target on whose behalf this processing
+# is being done. Signatures are cached for each unique file/scanner
+# pair.
+sub includes {
+ my($self, $tgt, @files) = @_;
+ my(%files, $file);
+ my($inc) = $self->{includes} || ($self->{includes} = {});
+ while ($file = pop @files) {
+ next if exists $files{$file};
+ if ($inc->{$file}) {
+ push(@files, @{$inc->{$file}});
+ $files{$file} = 'sig'->signature($file->rfile);
+ } else {
+ if ((build $file) eq 'errors') {
+ $tgt->{status} = 'errors'; # tgt inherits build status
+ return ();
+ }
+ $files{$file} = 'sig'->signature($file->rfile);
+ my(@includes) = $self->scan($file);
+ $inc->{$file} = \@includes;
+ push(@files, @includes);
+ }
+ }
+ 'sig'->collect(sort values %files)
+}
+
+
+# A simple scanner. This is used by the QuickScanfunction, to setup
+# one-time target and environment-independent scanning for a source
+# file. Only used for commands run by the Command method.
+package scan::quickscan;
+
+use vars qw( @ISA %scanner );
+
+BEGIN { @ISA = qw(scan) }
+
+sub find {
+ my($class, $code, $env, $pdirs) = @_;
+ if (! defined $pdirs) {
+ $pdirs = [ ] ;
+ } elsif (ref($pdirs) ne 'ARRAY') {
+ $pdirs = [ split(/$main::PATH_SEPARATOR/o, $pdirs) ];
+ }
+ my(@path) = map { $dir::cwd->lookupdir($_) } @$pdirs;
+ my($spath) = "@path";
+ $scanner{$code,$env,$spath} || do {
+ my($self) = { code => $code, env => $env, path => \@path };
+ $scanner{$code,$env,$spath} = bless $self;
+ }
+}
+
+# Scan the specified file for included file names.
+sub scan {
+ my($self, $file) = @_;
+ my($code) = $self->{code};
+ my(@includes);
+ # File should have been built by now. If not, we'll ignore it.
+ return () unless open(SCAN, $file->rpath);
+ while(<SCAN>) {
+ push(@includes, grep($_ ne '', &$code));
+ }
+ close(SCAN);
+ my($wd) = $file->{dir};
+ my(@files);
+ my $name;
+ for $name (@includes) {
+ my $dir;
+ for $dir ($file->{dir}, @{$self->{path}}) {
+ my($include) = $dir->lookup_accessible($name);
+ if ($include) {
+ push(@files, $include) unless $include->ignore;
+ last;
+ }
+ }
+ }
+ @files
+}
+
+
+# CPP (C preprocessor) scanning module
+package scan::cpp;
+
+use vars qw( @ISA %scanner );
+
+BEGIN { @ISA = qw(scan) }
+
+# For this constructor, provide the include path argument (colon
+# separated). Each path is taken relative to the provided directory.
+
+# Note: a particular scanning object is assumed to always return the
+# same result for the same input. This is why the search path is a
+# parameter to the constructor for a CPP scanning object. We go to
+# some pains to make sure that we return the same scanner object
+# for the same path: otherwise we will unecessarily scan files.
+sub find {
+ my($class, $dir, $pdirs) = @_;
+ if (! defined $pdirs) {
+ $pdirs = [ ];
+ } elsif (ref($pdirs) ne 'ARRAY') {
+ $pdirs = [ split(/$main::PATH_SEPARATOR/o, $pdirs) ];
+ }
+ my @path = map($dir->lookupdir($_), @$pdirs);
+ my($spath) = "@path";
+ $scanner{$spath} || do {
+ my($self) = {'path' => \@path};
+ $scanner{$spath} = bless $self;
+ }
+}
+
+# Scan the specified file for include lines.
+sub scan {
+ my($self, $file) = @_;
+ my($angles, $quotes);
+
+ if (exists $file->{angles}) {
+ $angles = $file->{angles};
+ $quotes = $file->{quotes};
+ } else {
+ my(@anglenames, @quotenames);
+ return () unless open(SCAN, $file->rpath);
+ while (<SCAN>) {
+ next unless /^\s*#/;
+ if (/^\s*#\s*include\s*([<"])(.*?)[>"]/) {
+ if ($1 eq "<") {
+ push(@anglenames, $2);
+ } else {
+ push(@quotenames, $2);
+ }
+ }
+ }
+ close(SCAN);
+ $angles = $file->{angles} = \@anglenames;
+ $quotes = $file->{quotes} = \@quotenames;
+ }
+
+
+ my(@shortpath) = @{$self->{path}}; # path for <> style includes
+ my(@longpath) = ($file->{dir}, @shortpath); # path for "" style includes
+
+ my(@includes);
+
+ my $name;
+ for $name (@$angles) {
+ my $dir;
+ for $dir (@shortpath) {
+ my($include) = $dir->lookup_accessible($name);
+ if ($include) {
+ push(@includes, $include) unless $include->ignore;
+ last;
+ }
+ }
+ }
+
+ for $name (@$quotes) {
+ my $dir;
+ for $dir(@longpath) {
+ my($include) = $dir->lookup_accessible($name);
+ if ($include) {
+ push(@includes, $include) unless $include->ignore;
+ last;
+ }
+ }
+ }
+
+ return @includes
+}
+
+# Return the include flags that would be used for a C Compile.
+sub iflags {
+ my($self, $env) = @_;
+ my($iflags) = '';
+ my($dir, $dpath);
+ for $dir (@{$self->{path}}) {
+ $dpath = $dir->path;
+ # Add the (presumably local) directory to the -I flags
+ # if we're not using repositories, the directory exists,
+ # or it's Linked to a source directory (that is, it *will*
+ # exist by the time the compilation occurs).
+ $iflags .= " ".$env->{INCDIRPREFIX}.$dpath.$env->{INCDIRSUFFIX}
+ if ! @param::rpath || -d $dpath || $dir->is_linked;
+ next if File::Spec->file_name_is_absolute($dpath);
+ if (@param::rpath) {
+ my $d;
+ if ($dpath eq $dir::CURDIR) {
+ foreach $d (map($_->path, @param::rpath)) {
+ $iflags .= " ".$env->{INCDIRPREFIX}.$d.$env->{INCDIRSUFFIX};
+ }
+ } else {
+ my($rpath);
+ foreach $d (map($_->path, @param::rpath)) {
+ $rpath = File::Spec->catfile($d, $dpath);
+ $iflags .= " ".$env->{INCDIRPREFIX}.$rpath.$env->{INCDIRSUFFIX}
+ if -d $rpath;
+ }
+ }
+ }
+ }
+ $iflags
+}
+
+package File::Spec;
+
+use vars qw( $_SEP $_MATCH_SEP $_MATCH_VOL );
+
+# Cons is migrating to using File::Spec for portable path name
+# manipulation. This is the right long-term direction, but there are
+# some problems with making the transition:
+#
+# For multi-volume support, we need to use newer interfaces
+# (splitpath, catpath, splitdir) that are only available in
+# File::Spec 0.8.
+#
+# File::Spec 0.8 doesn't work with Perl 5.00[34] due to
+# regular expression incompatibilities (use of \z).
+#
+# Forcing people to use a new version of a module is painful
+# because (in the workplace) their administrators aren't
+# always going to agree to install it everywhere.
+#
+# As a middle ground, we provide our own versions of all the File::Spec
+# methods we use, supporting both UNIX and Win32. Some of these methods
+# are home brew, some are cut-and-pasted from the real File::Spec methods.
+# This way, we're not reinventing the whole wheel, at least.
+#
+# We can (and should) get rid of this class whenever 5.00[34] and
+# versions of File::Spec prior to 0.9 (?) have faded sufficiently.
+# We also may need to revisit whenever someone first wants to use
+# Cons on some platform other than UNIX or Win32.
+
+BEGIN {
+ if ($main::_WIN32) {
+ $_SEP = '\\';
+ $_MATCH_SEP = "[\Q/$_SEP\E]";
+ $_MATCH_VOL = "([a-z]:)?$_MATCH_SEP";
+ } else {
+ $_SEP = '/';
+ $_MATCH_SEP = "\Q$_SEP\E";
+ $_MATCH_VOL = $_MATCH_SEP;
+ }
+}
+
+sub canonpath {
+ my ($self, $path) = @_;
+ if ($main::_WIN32) {
+ $path =~ s/^([a-z]:)/\u$1/s;
+ $path =~ s|/|\\|g;
+ $path =~ s|([^\\])\\+|$1\\|g; # xx////xx -> xx/xx
+ $path =~ s|(\\\.)+\\|\\|g; # xx/././xx -> xx/xx
+ $path =~ s|^(\.\\)+||s unless $path eq ".\\"; # ./xx -> xx
+ $path =~ s|\\$||
+ unless $path =~ m#^([A-Z]:)?\\$#s; # xx/ -> xx
+ } else {
+ $path =~ s|/+|/|g unless($^O eq 'cygwin'); # xx////xx -> xx/xx
+ $path =~ s|(/\.)+/|/|g; # xx/././xx -> xx/xx
+ $path =~ s|^(\./)+||s unless $path eq "./"; # ./xx -> xx
+ $path =~ s|^/(\.\./)+|/|s; # /../../xx -> xx
+ $path =~ s|/$|| unless $path eq "/"; # xx/ -> xx
+ }
+ return $path;
+}
+
+sub catdir {
+ my $self = shift;
+ my @args = @_;
+ foreach (@args) {
+ # append a slash to each argument unless it has one there
+ $_ .= $_SEP if $_ eq '' || substr($_,-1) ne $_SEP;
+ }
+ return $self->canonpath(join('', @args));
+}
+
+sub catfile {
+ my $self = shift;
+ my $file = pop @_;
+ return $file unless @_;
+ my $dir = $self->catdir(@_);
+ $dir .= $_SEP unless substr($dir,-1) eq $_SEP;
+ $file = '' if ! defined($file);
+ return $dir.$file;
+}
+
+sub catpath {
+ my $path = $_[1] . $_[0]->catfile(@_[2..$#_]);
+ $path =~ s/(.)$_MATCH_SEP*$/$1/;
+ $path;
+}
+
+sub curdir {
+ '.'
+}
+
+sub file_name_is_absolute {
+ my ($self, $file) = @_;
+ return scalar($file =~ m{^$_MATCH_VOL}is);
+}
+
+sub splitdir {
+ my @dirs = split(/$_MATCH_SEP/, $_[1], -1);
+ push(@dirs, '') if $dirs[$#dirs];
+ @dirs;
+}
+
+sub splitpath {
+ my ($self, $path) = @_;
+ my $vol = '';
+ my $sep = $_SEP;
+ if ($main::_WIN32) {
+ if ($path =~ s#^([A-Za-z]:|(?:\\\\|//)[^\\/]+[\\/][^\\/]+)([\\/])#$2#) {
+ $vol = $1;
+ $sep = $2;
+ }
+ }
+ my(@path) = split(/$_MATCH_SEP/, $path, -1);
+ my $file = pop @path;
+ my $dirs = join($sep, @path, '');
+ return ($vol, $dirs, $file);
+}
+
+sub updir {
+ '..'
+}
+
+sub case_tolerant {
+ return $main::_WIN32;
+}
+
+# Directory and file handling. Files/dirs are represented by objects.
+# Other packages are welcome to add component-specific attributes.
+package dir;
+
+use vars qw( $SEPARATOR $MATCH_SEPARATOR $CURDIR $UPDIR
+ $cwd_vol %root $top $cwd );
+
+BEGIN {
+ # A portable way of determing our directory separator.
+ $SEPARATOR = File::Spec->catdir('', '');
+ # A fast-path regular expression to match a directory separator
+ # anywhere in a path name.
+ if ($SEPARATOR eq '/') {
+ $MATCH_SEPARATOR = "\Q$SEPARATOR\E";
+ } else {
+ $MATCH_SEPARATOR = "[\Q/$SEPARATOR\E]";
+ }
+ # Cache these values so we don't have to make a method call
+ # every time we need them.
+ $CURDIR = File::Spec->curdir; # '.' on UNIX
+ $UPDIR = File::Spec->updir; # '..' on UNIX
+ #
+ $cwd_vol = '';
+}
+
+# Annotate a node (file or directory) with info about the
+# method that created it.
+sub creator {
+ my($self, @frame) = @_;
+ $self->{'creator'} = \@frame if @frame;
+ $self->{'creator'};
+}
+
+# Handle a file|dir type exception. We only die if we find we were
+# invoked by something in a Conscript/Construct file, because
+# dependencies created directly by Cons' analysis shouldn't cause
+# an error.
+sub _type_exception {
+ my($e) = @_;
+ my($line, $sub);
+ (undef, undef, $line, $sub) = script::caller_info;
+ if (defined $line) {
+ my $err = "\"${\$e->path}\" already in use as a " . ref($e) . " before $sub on line $line";
+ if ($e->{'creator'}) {
+ my $script;
+ (undef, $script, $line, $sub) = @{$e->{'creator'}};
+ $err = "\t" . $err . ",\n\t\tdefined by $sub in $script, line $line";
+ }
+ $err .= "\n";
+ die $err;
+ }
+}
+
+# This wraps up all the common File::Spec logic that we use for parsing
+# directory separators in a path and turning it into individual
+# subdirectories that we must create, as well as creation of root
+# nodes for any new file system volumes we find. File::Spec doesn't have
+# intuitively obvious interfaces, so this is heavily commented.
+#
+# Note: This is NOT an object or class method;
+# it's just a utility subroutine.
+sub _parse_path {
+ my($dir, $path) = @_;
+
+ # Convert all slashes to the native directory separator.
+ # This allows Construct files to always be written with good
+ # old POSIX path names, regardless of what we're running on.
+ $path = File::Spec->canonpath($path);
+
+ # File::Spec doesn't understand the Cons convention of
+ # an initial '#' for top-relative files. Strip it.
+ my($toprel) = $path =~ s/^#//;
+
+ # Let File::Spec do the heavy lifting of parsing the path name.
+ my($vol, $directories, $entry) = File::Spec->splitpath($path);
+ my @dirs = File::Spec->splitdir($directories);
+
+ # If there was a file entry on the end of the path, then the
+ # last @dirs element is '' and we don't need it. If there
+ # wasn't a file entry on the end (File::Spec->splitpath() knew
+ # the last component was a directory), then the last @dirs
+ # element becomes the entry we want to look up.
+ my($e) = pop @dirs;
+ $entry = $e if $entry eq '';
+
+ if (File::Spec->file_name_is_absolute($path)) {
+ # An absolute path name. If no volume was supplied,
+ # use the volume of our current directory.
+ $vol = $cwd_vol if $vol eq '';
+ $vol = uc($vol) if File::Spec->case_tolerant;
+ if (! defined $root{$vol}) {
+ # This is our first time looking up a path name
+ # on this volume, so create a root node for it.
+ # (On UNIX systems, $vol is always '', so '/'
+ # always maps to the $root{''} node.)
+ $root{$vol} = {path => $vol.$SEPARATOR,
+ prefix => $vol.$SEPARATOR,
+ srcpath => $vol.$SEPARATOR,
+ 'exists' => 1 };
+ $root{$vol}->{'srcdir'} = $root{$vol};
+ bless $root{$vol};
+ }
+ # We're at the top, so strip the blank entry from the front of
+ # the @dirs array since the initial '/' it represents will now
+ # be supplied by the root node we return.
+ shift @dirs;
+ $dir = $root{$vol};
+ } elsif ($toprel) {
+ $dir = $dir::top;
+ }
+ ($dir, \@dirs, $entry);
+}
+
+# Common subroutine for creating directory nodes.
+sub _create_dirs {
+ my ($dir, @dirs) = @_;
+ my $e;
+ foreach $e (@dirs) {
+ my $d = $dir->{member}->{$e};
+ if (! defined $d) {
+ bless $d = { 'entry' => $e, 'dir' => $dir, }, 'dir';
+ $d->creator(script::caller_info);
+ $d->{member}->{$dir::CURDIR} = $d;
+ $d->{member}->{$dir::UPDIR} = $dir;
+ $dir->{member}->{$e} = $d;
+ } elsif (ref $d eq 'entry') {
+ bless $d, 'dir';
+ $d->{member}->{$dir::CURDIR} = $d;
+ $d->{member}->{$dir::UPDIR} = $dir;
+ } elsif (ref $d eq 'file') {
+ # This clause is to supply backwards compatibility,
+ # with a warning, for anyone that's used FilePath
+ # to refer to a directory. After people have using
+ # 1.8 have had time to adjust (sometime in version
+ # 1.9 or later), we should remove this entire clause.
+ my($script, $line, $sub);
+ (undef, $script, $line, $sub) = @{$d->{'creator'}};
+ if ($sub eq 'script::FilePath') {
+ print STDERR "$0: Warning: $sub used to refer to a directory\n"
+ . "\tat line $line of $script. Use DirPath instead.\n";
+ bless $d, 'dir';
+ } else {
+ _type_exception($d);
+ }
+ } elsif (ref $d ne 'dir') {
+ _type_exception($d);
+ }
+ $dir = $d;
+ }
+ $dir;
+}
+
+# Look up an entry in a directory. This method is for when we don't
+# care whether a file or directory is returned, so if the entry already
+# exists, it will simply be returned. If not, we create it as a
+# generic "entry" which can be later turned into a file or directory
+# by a more-specific lookup.
+#
+# The file entry may be specified as relative, absolute (starts with /),
+# or top-relative (starts with #).
+sub lookup {
+ my($dir, $entry) = @_;
+
+ if ($entry !~ m#$MATCH_SEPARATOR#o) {
+ # Fast path: simple entry name in a known directory.
+ if ($entry =~ s/^#//) {
+ # Top-relative names begin with #.
+ $dir = $dir::top;
+ } elsif ($entry =~ s/^!//) {
+ $dir = $dir::cwd->srcdir;
+ }
+ } else {
+ my $dirsref;
+ ($dir, $dirsref, $entry) = _parse_path($dir, $entry);
+ $dir = _create_dirs($dir, @$dirsref) if @$dirsref;
+ return if ! defined $dir;
+ return $dir if $entry eq '';
+ }
+
+ my $e = $dir->{member}->{$entry};
+ if (! defined $e) {
+ bless $e = { 'entry' => $entry, 'dir' => $dir, }, 'entry';
+ $e->creator(script::caller_info);
+ $dir->{member}->{$entry} = $e;
+ }
+
+ $e;
+}
+
+# Look up a file entry in a directory.
+#
+# The file entry may be specified as relative, absolute (starts with /),
+# or top-relative (starts with #).
+sub lookupfile {
+ my($dir, $entry) = @_;
+
+ if ($entry !~ m#$MATCH_SEPARATOR#o) {
+ # Fast path: simple entry name in a known directory.
+ if ($entry =~ s/^#//) {
+ # Top-relative names begin with #.
+ $dir = $dir::top;
+ } elsif ($entry =~ s/^!//) {
+ $dir = $dir::cwd->srcdir;
+ }
+ } else {
+ my $dirsref;
+ ($dir, $dirsref, $entry) = _parse_path($dir, $entry);
+ $dir = _create_dirs($dir, @$dirsref) if @$dirsref;
+ return undef if $entry eq '';
+ }
+
+ my $f = $dir->{member}->{$entry};
+ if (! defined $f) {
+ bless $f = { 'entry' => $entry, 'dir' => $dir, }, 'file';
+ $f->creator(script::caller_info);
+ $dir->{member}->{$entry} = $f;
+ } elsif (ref $f eq 'entry') {
+ bless $f, 'file';
+ } elsif (ref $f ne 'file') {
+ _type_exception($f);
+ }
+
+ $f;
+}
+
+# Look up a (sub-)directory entry in a directory.
+#
+# The (sub-)directory entry may be specified as relative, absolute
+# (starts with /), or top-relative (starts with #).
+sub lookupdir {
+ my($dir, $entry) = @_;
+
+ my $dirsref;
+ if ($entry !~ m#$MATCH_SEPARATOR#o) {
+ # Fast path: simple entry name in a known directory.
+ if ($entry =~ s/^#//) {
+ # Top-relative names begin with #.
+ $dir = $dir::top;
+ } elsif ($entry =~ s/^!//) {
+ $dir = $dir::cwd->srcdir;
+ }
+ } else {
+ ($dir, $dirsref, $entry) = _parse_path($dir, $entry);
+ }
+ push(@$dirsref, $entry) if $entry ne '';
+ _create_dirs($dir, @$dirsref);
+}
+
+# Look up a file entry and return it if it's accessible.
+sub lookup_accessible {
+ my $file = $_[0]->lookupfile($_[1]);
+ return ($file && $file->accessible) ? $file : undef;
+}
+
+# Return the parent directory without doing a lookupdir,
+# which would create a parent if it doesn't already exist.
+# A return value of undef (! $dir->up) indicates a root directory.
+sub up {
+ $_[0]->{member}->{$dir::UPDIR};
+}
+
+# Return whether this is an entry somewhere underneath the
+# specified directory.
+sub is_under {
+ my $dir = $_[0];
+ while ($dir) {
+ return 1 if $_[1] == $dir;
+ $dir = $dir->up;
+ }
+ return undef;
+}
+
+# Return the relative path from the calling directory ($_[1])
+# to the object. If the object is not under the directory, then
+# we return it as a top-relative or absolute path name.
+sub relpath {
+ my ($dir, $obj) = @_;
+ my @dirs;
+ my $o = $obj;
+ while ($o) {
+ if ($dir == $o) {
+ if (@dirs < 2) {
+ return $dirs[0] || '';
+ } else {
+ return File::Spec->catdir(@dirs);
+ }
+ }
+ unshift(@dirs, $o->{entry});
+ $o = $o->up;
+ }
+ # The object was not underneath the specified directory.
+ # Use the node's cached path, which is either top-relative
+ # (in which case we append '#' to the beginning) or
+ # absolute.
+ my $p = $obj->path;
+ $p = '#' . $p if ! File::Spec->file_name_is_absolute($p);
+ return $p;
+}
+
+# Return the path of the directory (file paths implemented
+# separately, below).
+sub path {
+ $_[0]->{path} ||
+ ($_[0]->{path} = $_[0]->{dir}->prefix . $_[0]->{entry});
+}
+
+# Return the pathname as a prefix to be concatenated with an entry.
+sub prefix {
+ return $_[0]->{prefix} if exists $_[0]->{prefix};
+ $_[0]->{prefix} = $_[0]->path . $SEPARATOR;
+}
+
+# Return the related source path prefix.
+sub srcprefix {
+ return $_[0]->{srcprefix} if exists $_[0]->{srcprefix};
+ my($srcdir) = $_[0]->srcdir;
+ $srcdir->{srcprefix} = $srcdir eq $_[0] ? $srcdir->prefix
+ : $srcdir->srcprefix;
+}
+
+# Return the related source directory.
+sub srcdir {
+ $_[0]->{'srcdir'} ||
+ ($_[0]->{'srcdir'} = $_[0]->{dir}->srcdir->lookupdir($_[0]->{entry}))
+}
+
+# Return if the directory is linked to a separate source directory.
+sub is_linked {
+ return $_[0]->{is_linked} if defined $_[0]->{is_linked};
+ $_[0]->{is_linked} = $_[0]->path ne $_[0]->srcdir->path;
+}
+
+sub link {
+ my(@paths) = @_;
+ my($srcdir) = $dir::cwd->lookupdir(pop @paths)->srcdir;
+ map($dir::cwd->lookupdir($_)->{'srcdir'} = $srcdir, @paths);
+
+ # make a reverse lookup for the link.
+ $srcdir->{links} = [] if ! $srcdir->{links};
+ push @{$srcdir->{links}}, @paths;
+}
+
+use vars qw( @tail ); # TODO: Why global ????
+
+sub linked_targets {
+ my $tgt = shift;
+ my @targets = ();
+ my $dir;
+ if (ref $tgt eq 'dir') {
+ $dir = $tgt;
+ } else {
+ push @tail, $tgt;
+ $dir = $tgt->{dir};
+ }
+ while ($dir) {
+ if (defined $dir->{links} && @{$dir->{links}}) {
+ push @targets,
+ map(File::Spec->catdir($_, @tail), @{$dir->{links}});
+ #print STDERR "Found Link: ${\$dir->path} -> @{\$dir->{links}}\n";
+ }
+ unshift @tail, $dir->{entry};
+ $dir = $dir->up;
+ }
+
+ return map($dir::top->lookupdir($_), @targets);
+}
+
+sub accessible {
+ my $path = $_[0]->path;
+ my $err = "$0: you have attempted to use path \"$path\" both as a file " .
+ "and as a directory!\n";
+ die $err;
+}
+
+sub init {
+ my $path = Cwd::cwd();
+
+ # We know we can get away with passing undef to lookupdir
+ # as the directory because $dir is an absolute path.
+ $top = lookupdir(undef, $path);
+ $top->{'path'} = $top->{srcpath} = $dir::CURDIR;
+ $top->{'prefix'} = '';
+ $top->{'srcdir'} = $top;
+
+ $cwd = $top;
+
+ ($cwd_vol, undef, undef) = File::Spec->splitpath($path);
+ $cwd_vol = '' if ! defined $cwd_vol;
+ $cwd_vol = uc($cwd_vol) if File::Spec->case_tolerant;
+}
+
+package file;
+
+use vars qw( @ISA $level );
+
+BEGIN { @ISA = qw(dir); $level = 0 }
+
+# Return the pathname of the file.
+# Define this separately from dir::path because we don't want to
+# cache all file pathnames (just directory pathnames).
+sub path {
+ $_[0]->{dir}->prefix . $_[0]->{entry}
+}
+
+# Return the related source file path.
+sub srcpath {
+ $_[0]->{dir}->srcprefix . $_[0]->{entry}
+}
+
+# Return if the file is (should be) linked to a separate source file.
+sub is_linked {
+ $_[0]->{dir}->is_linked
+}
+
+# Repository file search. If the local file exists, that wins.
+# Otherwise, return the first existing same-named file under a
+# Repository directory. If there isn't anything with the same name
+# under a Repository directory, return the local file name anyway
+# so that some higher layer can try to construct it.
+sub rfile {
+ return $_[0]->{rfile} if exists $_[0]->{rfile};
+ my($self) = @_;
+ my($rfile) = $self;
+ if (@param::rpath) {
+ my($path) = $self->path;
+ if (! File::Spec->file_name_is_absolute($path) && ! -f $path) {
+ my($dir);
+ foreach $dir (@param::rpath) {
+ my($t) = $dir->prefix . $path;
+ if (-f $t) {
+ $rfile = $_[0]->lookupfile($t);
+ $rfile->{'lfile'} = $self;
+ last;
+ }
+ }
+ }
+ }
+ $self->{rfile} = $rfile;
+}
+
+# Returns the local file for a repository file;
+# returns self if it's already a local file.
+sub lfile {
+ $_[0]->{'lfile'} || $_[0]
+}
+
+# returns the "precious" status of this file.
+sub precious {
+ return $_[0]->{precious};
+}
+
+# "Erase" reference to a Repository file,
+# making this a completely local file object
+# by pointing it back to itself.
+sub no_rfile {
+ $_[0]->{'rfile'} = $_[0];
+}
+
+# Return a path to the first existing file under a Repository directory,
+# implicitly returning the current file's path if there isn't a
+# same-named file under a Repository directory.
+sub rpath {
+ $_[0]->{rpath} ||
+ ($_[0]->{rpath} = $_[0]->rfile->path)
+}
+
+# Return a path to the first linked srcpath file under a Repositoy
+# directory, implicitly returning the current file's srcpath if there
+# isn't a same-named file under a Repository directory.
+sub rsrcpath {
+ return $_[0]->{rsrcpath} if exists $_[0]->{rsrcpath};
+ my($self) = @_;
+ my($path) = $self->{rsrcpath} = $self->srcpath;
+ if (@param::rpath && ! File::Spec->file_name_is_absolute($path) && ! -f $path) {
+ my($dir);
+ foreach $dir (@param::rpath) {
+ my($t) = $dir->prefix . $path;
+ if (-f $t) {
+ $self->{rsrcpath} = $t;
+ last;
+ }
+ }
+ }
+ $self->{rsrcpath};
+}
+
+# Return if a same-named file source file exists.
+# This handles the interaction of Link and Repository logic.
+# As a side effect, it will link a source file from its Linked
+# directory (preferably local, but maybe in a repository)
+# into a build directory from its proper Linked directory.
+sub source_exists {
+ return $_[0]->{source_exists} if defined $_[0]->{source_exists};
+ my($self) = @_;
+ my($path) = $self->path;
+ my($mtime, $ctime) = (stat($path))[9,10];
+ if ($self->is_linked) {
+ # Linked directory, local logic.
+ my($srcpath) = $self->srcpath;
+ my($src_mtime, $src_ctime) = (stat($srcpath))[9,10];
+ if ($src_mtime) {
+ if (! $mtime || $src_mtime != $mtime || $src_ctime != $ctime) {
+ futil::install($srcpath, $self);
+ }
+ return $self->{source_exists} = 1;
+ }
+ # Linked directory, repository logic.
+ if (@param::rpath) {
+ if ($self != $self->rfile) {
+ return $self->{source_exists} = 1;
+ }
+ my($rsrcpath) = $self->rsrcpath;
+ if ($path ne $rsrcpath) {
+ my($rsrc_mtime, $rsrc_ctime) = (stat($rsrcpath))[9,10];
+ if ($rsrc_mtime) {
+ if (! $mtime || $rsrc_mtime != $mtime
+ || $rsrc_ctime != $ctime) {
+ futil::install($rsrcpath, $self);
+ }
+ return $self->{source_exists} = 1;
+ }
+ }
+ }
+ # There was no source file in any Linked directory
+ # under any Repository. If there's one in the local
+ # build directory, it no longer belongs there.
+ if ($mtime) {
+ unlink($path) || die("$0: couldn't unlink $path ($!)\n");
+ }
+ return $self->{source_exists} = '';
+ } else {
+ if ($mtime) {
+ return $self->{source_exists} = 1;
+ }
+ if (@param::rpath && $self != $self->rfile) {
+ return $self->{source_exists} = 1;
+ }
+ return $self->{source_exists} = '';
+ }
+}
+
+# Return if a same-named derived file exists under a Repository directory.
+sub derived_exists {
+ $_[0]->{derived_exists} ||
+ ($_[0]->{derived_exists} = ($_[0] != $_[0]->rfile));
+}
+
+# Return if this file is somewhere under a Repository directory.
+sub is_on_rpath {
+ defined $_[0]->{'lfile'};
+}
+
+sub local {
+ my($self, $arg) = @_;
+ if (defined $arg) {
+ $self->{'local'} = $arg;
+ }
+ $self->{'local'};
+}
+
+# Return the entry name of the specified file with the specified
+# suffix appended. Leave it untouched if the suffix is already there.
+# Differs from the addsuffix function, below, in that this strips
+# the existing suffix (if any) before appending the desired one.
+sub base_suf {
+ my($entry) = $_[0]->{entry};
+ if ($entry !~ m/$_[1]$/) {
+ $entry =~ s/\.[^\.]*$//;
+ $entry .= $_[1];
+ }
+ $entry;
+}
+
+# Return the suffix of the file; everything including and to the
+# right of the last dot.
+sub suffix {
+ my @pieces = split(/\./, $_[0]->{entry});
+ my $suffix = pop(@pieces);
+ return ".$suffix";
+}
+
+# Called as a simple function file::addsuffix(name, suffix)
+sub addsuffix {
+ my($name, $suffix) = @_;
+
+ if ($suffix && substr($name, -length($suffix)) ne $suffix) {
+ return $name .= $suffix;
+ }
+ $name;
+}
+
+# Return true if the file is (or will be) accessible.
+# That is, if we can build it, or if it is already present.
+sub accessible {
+ (exists $_[0]->{builder}) || ($_[0]->source_exists);
+}
+
+# Return true if the file should be ignored for the purpose
+# of computing dependency information (should not be considered
+# as a dependency and, further, should not be scanned for
+# dependencies).
+sub ignore {
+ return 0 if !$param::ignore;
+ return $_[0]->{ignore} if exists $_[0]->{ignore};
+ $_[0]->{ignore} = $_[0]->path =~ /$param::ignore/o;
+}
+
+# Build the file, if necessary.
+sub build {
+ return $_[0]->{status} if $_[0]->{status};
+ my($status) = &file::_build;
+ if ($_[0]->{after_build_func}) {
+ my($pkgvars) = $_[0]->{conscript}->{pkgvars};
+ NameSpace::restore('script', $pkgvars) if $pkgvars;
+ eval("package script; " . $_[0]->{after_build_func});
+ print "Error running AfterBuild for ${\$_[0]->path}: $@\n" if ($@);
+ NameSpace::remove('script', keys %$pkgvars) if $pkgvars;
+ }
+ return $status;
+}
+
+sub _build {
+ my($self) = @_;
+ print main::DEPFILE $self->path, "\n" if $param::depfile;
+ print((' ' x $level), "Checking ", $self->path, "\n") if $param::depends;
+ if (!exists $self->{builder}) {
+ # We don't know how to build the file. This is OK, if
+ # the file is present as a source file, under either the
+ # local tree or a Repository.
+ if ($self->source_exists) {
+ return $self->{status} = 'handled';
+ } else {
+ my($name) = $self->path;
+ print("$0: don't know how to construct \"$name\"\n");
+ exit(1) unless $param::kflag;
+ return $self->{status} = 'errors'; # xxx used to be 'unknown'
+ }
+ }
+
+ # An associated build object exists, so we know how to build
+ # the file. We first compute the signature of the file, based
+ # on its dependendencies, then only rebuild the file if the
+ # signature has changed.
+ my($builder) = $self->{builder};
+ $level += 2;
+
+ my(@deps) = (@{$self->{dep}}, @{$self->{sources}});
+ my($rdeps) = \@deps;
+
+ if ($param::random) {
+ # If requested, build in a random order, instead of the
+ # order that the dependencies were listed.
+ my(%rdeps);
+ map { $rdeps{$_,'*' x int(rand 10)} = $_ } @deps;
+ $rdeps = [values(%rdeps)];
+ }
+
+ $self->{status} = '';
+
+ my $dep;
+ for $dep (@$rdeps) {
+ if ((build $dep) eq 'errors') {
+ # Propagate dependent errors to target.
+ # but try to build all dependents regardless of errors.
+ $self->{status} = 'errors';
+ }
+ }
+
+ # If any dependents had errors, then we abort.
+ if ($self->{status} eq 'errors') {
+ $level -= 2;
+ return 'errors';
+ }
+
+ # Compute the final signature of the file, based on
+ # the static dependencies (in order), dynamic dependencies,
+ # output path name, and (non-substituted) build script.
+ my($sig) = 'sig'->collect(map('sig'->signature($_->rfile), @deps),
+ $builder->includes($self),
+ $builder->scriptsig);
+
+ # May have gotten errors during computation of dynamic
+ # dependency signature, above.
+ $level -= 2;
+ return 'errors' if $self->{status} eq 'errors';
+
+ if (@param::rpath && $self->derived_exists) {
+ # There is no local file of this name, but there is one
+ # under a Repository directory.
+
+ if ('sig'->current($self->rfile, $sig)) {
+ # The Repository copy is current (its signature matches
+ # our calculated signature).
+ if ($self->local) {
+ # ...but they want a local copy, so provide it.
+ main::showcom("Local copy of ${\$self->path} from " .
+ "${\$self->rpath}");
+ futil::install($self->rpath, $self);
+ 'sig'->bsig($self, $sig);
+ }
+ return $self->{status} = 'handled';
+ }
+
+ # The signatures don't match, implicitly because something
+ # on which we depend exists locally. Get rid of the reference
+ # to the Repository file; we'll build this (and anything that
+ # depends on it) locally.
+ $self->no_rfile;
+ }
+
+ # Then check for currency.
+ if (! 'sig'->current($self, $sig)) {
+ # We have to build/derive the file.
+ print((' ' x $level), "Rebuilding ", $self->path, ": out of date.\n")
+ if $param::depends;
+ # First check to see if the built file is cached.
+ if ($builder->cachin($self, $sig)) {
+ 'sig'->bsig($self, $sig);
+ return $self->{status} = 'built';
+ } elsif ($builder->action($self)) {
+ $builder->cachout($self, $sig);
+ 'sig'->bsig($self, $sig);
+ return $self->{status} = 'built';
+ } else {
+ die("$0: errors constructing ${\$self->path}\n")
+ unless $param::kflag;
+ return $self->{status} = 'errors';
+ }
+ } else {
+ # Push this out to the cache if we've been asked to (-C option).
+ # Don't normally do this because it slows us down.
+ # In a fully built system, no accesses to the cache directory
+ # are required to check any files. This is a win if cache is
+ # heavily shared. Enabling this option puts the directory in the
+ # loop. Useful only when you wish to recreate a cache from a build.
+ if ($param::cachesync) {
+ $builder->cachout($self, $sig);
+ 'sig'->bsig($self, $sig);
+ }
+ return $self->{status} = 'handled';
+ }
+}
+
+# Bind an action to a file, with the specified sources. No return value.
+sub bind {
+ my($self, $builder, @sources) = @_;
+ if ($self->{builder} && !$self->{builder}->compatible($builder)) {
+ # Even if not "compatible", we can still check to see if the
+ # derivation is identical. It should be identical if the builder is
+ # the same and the sources are the same.
+ if ("$self->{builder} @{$self->{sources}}" ne "$builder @sources") {
+ $main::errors++;
+ my($_foo1, $script1, $line1, $sub1) = @{$self->creator};
+ my($_foo2, $script2, $line2, $sub2) = script::caller_info;
+ my $err = "\t${\$self->path}\n" .
+ "\tbuilt (at least) two different ways:\n" .
+ "\t\t$script1, line $line1: $sub1\n" .
+ "\t\t$script2, line $line2: $sub2\n";
+ die $err;
+ }
+ return;
+ }
+ if ($param::wflag) {
+ my($script, $line, $sub);
+ (undef, $script, $line, $sub) = script::caller_info;
+ $self->{script} = '' if ! defined $self->{script};
+ $self->{script} .= "; " if $self->{script};
+ $self->{script} .= qq($sub in "$script", line $line);
+ }
+ $self->{builder} = $builder;
+ push(@{$self->{sources}}, @sources);
+ @{$self->{dep}} = () if ! defined $self->{dep};
+ $self->{conscript} = $priv::self->{script};
+}
+
+sub is_under {
+ $_[0]->{dir}->is_under($_[1]);
+}
+
+sub relpath {
+ my $dirpath = $_[0]->relpath($_[1]->{dir});
+ if (! $dirpath) {
+ return $_[1]->{entry};
+ } else {
+ File::Spec->catfile($dirpath, $_[1]->{entry});
+ }
+}
+
+# Return the signature array for this file.
+# This probably belongs in its own "sigarray" package,
+# which would make it easier to optimize performance.
+sub sigarray {
+ if ($_[0]->{sigaref}) {
+ return @{$_[0]->{sigaref}};
+ }
+ my $self = shift;
+ # glob2pat based on The Perl Cookbook, p. 180.
+ sub glob2pat {
+ my $globstr = shift;
+ my %patmap = (
+ '*' => '.*',
+ '?' => '.',
+ '[' => '[',
+ ']' => ']',
+ '/' => "\Q$dir::SEPARATOR", # Cons-specific modification
+ );
+ $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
+ return '^' . $globstr . '$';
+ }
+ my @sigarray;
+ my $default;
+ my $builder = $self->lfile->{builder};
+ if (! $builder) {
+ @sigarray = @$param::sourcesig;
+ $default = [qw(content)];
+ } else {
+ if ($builder->{env} && $builder->{env}->{SIGNATURE}) {
+ @sigarray = @{$builder->{env}->{SIGNATURE}};
+ } else {
+ my $class = ref $builder;
+ my $path = $self->path;
+ warn qq($0: Warning: Builder package $class did not record\n) .
+ qq(\tthe calling environment for '$path'.\n) .
+ qq(\tUnable to use any %SIGNATURE construction variable\n) .
+ qq(\tfor signature configuration.\n);
+ }
+ $default = [qw(build)];
+ }
+ my $path = $self->path;
+ while (@sigarray) {
+ my($glob, $aref) = splice(@sigarray, 0, 2);
+ my $re = glob2pat($glob);
+ if ($path =~ /$re/) {
+ $aref = [split(/\s+/, $aref)] if ! ref $aref;
+ $self->{sigaref} = $aref;
+ return @$aref;
+ }
+ }
+ $self->{sigaref} = $default;
+ return @{$self->{sigaref}}
+}
+
+# Decide if this file's signature should be the content or build signature.
+sub sigtype {
+ if ($_[0]->{sigtype}) {
+ return $_[0]->{sigtype};
+ }
+ my $self = shift;
+ my @sigarray = $self->sigarray;
+ my $sigtype;
+ if (grep($_ eq "build", @sigarray)) {
+ $sigtype = 'bsig';
+ } elsif (grep($_ =~ /content$/, @sigarray)) {
+ $sigtype = 'csig';
+ }
+ return $self->{sigtype} = $sigtype;
+}
+
+# Return whether this file is configured to use stored
+# signature values from the .consign file.
+sub stored {
+ if (! defined $_[0]->{stored}) {
+ $_[0]->{stored} = grep($_ eq "stored-content", $_[0]->sigarray);
+ }
+ return $_[0]->{stored};
+}
+
+# Generic entry (file or directory) handling.
+# This is an empty subclass for nodes that haven't
+# quite decided whether they're files or dirs.
+# Use file methods until someone blesses them one way or the other.
+package entry;
+
+use vars qw( @ISA );
+
+BEGIN { @ISA = qw(file) }
+
+# File utilities
+package futil;
+
+# Install one file as another.
+# Links them if possible (hard link), otherwise copies.
+# Don't ask why, but the source is a path, the tgt is a file obj.
+sub install {
+ my($sp, $tgt) = @_;
+ my($tp) = $tgt->path;
+ return 1 if $tp eq $sp;
+ return 1 if eval { link($sp, $tp) };
+ unlink($tp);
+ if (! futil::mkdir($tgt->{dir})) {
+ return undef;
+ }
+ return 1 if eval { link($sp, $tp) };
+ futil::copy($sp, $tp);
+}
+
+# Copy one file to another. Arguments are actual file names.
+# Returns undef on failure. Preserves mtime and mode.
+sub copy {
+ my ($sp, $tp) = @_;
+ my ($mode, $length, $atime, $mtime) = (stat($sp))[2,7,8,9];
+
+ # Use Perl standard library module for file copying, which handles
+ # binary copies. <schwarze@isa.de> 1998-06-18
+ if (! File::Copy::copy($sp, $tp)) {
+ warn qq($0: can\'t install "$sp" to "$tp" ($!)\n); #'
+ return undef;
+ }
+ # The file has been created, so try both the chmod and utime,
+ # first making sure the copy is writable (because permissions
+ # affect the ability to modify file times on some operating
+ # systems), and then changing permissions back if necessary.
+ my $ret = 1;
+ my $wmode = $mode | 0700;
+ if (! chmod $wmode, $tp) {
+ warn qq($0: can\'t set mode $wmode on file "$tp" ($!)\n); #'
+ $ret = undef;
+ }
+ if (! utime $atime, $mtime, $tp) {
+ warn qq($0: can\'t set modification time for file "$tp" ($!)\n); #'
+ $ret = undef;
+ }
+ if ($mode != $wmode && ! chmod $mode, $tp) {
+ warn qq($0: can\'t set mode $mode on file "$tp" ($!)\n); #'
+ $ret = undef;
+ }
+ return $ret;
+}
+
+# Ensure that the specified directory exists.
+# Aborts on failure.
+sub mkdir {
+ return 1 if $_[0]->{'exists'};
+ if (! futil::mkdir($_[0]->{dir})) { # Recursively make parent.
+ return undef;
+ }
+ my($path) = $_[0]->path;
+ if (!-d $path && !mkdir($path, 0777)) {
+ warn qq($0: can't create directory $path ($!).\n); #'
+ return undef;
+ }
+ $_[0]->{'exists'} = 1;
+}
+
+
+# Signature package.
+package sig::hash;
+
+use vars qw( $called );
+
+sub init {
+ my($dir) = @_;
+ my($consign) = $dir->prefix . ".consign";
+ my($dhash) = $dir->{consign} = {};
+ if (-f $consign) {
+ open(CONSIGN, $consign) || die("$0: can't open $consign ($!)\n");
+ while(<CONSIGN>) {
+ chop;
+ my ($file, $sig) = split(/:/,$_);
+ $dhash->{$file} = $sig;
+ }
+ close(CONSIGN);
+ }
+ $dhash
+}
+
+# Read the hash entry for a particular file.
+sub in {
+ my($dir) = $_[0]->{dir};
+ ($dir->{consign} || init($dir))->{$_[0]->{entry}}
+}
+
+# Write the hash entry for a particular file.
+sub out {
+ my($file, $sig) = @_;
+ my($dir) = $file->{dir};
+ ($dir->{consign} || init($dir))->{$file->{entry}} = $sig;
+ $sig::hash::dirty{$dir} = $dir;
+}
+
+# Eliminate the hash entry for a particular file.
+sub clear {
+ my($file) = @_;
+ my($dir) = $file->{dir};
+ delete $dir->{consign}->{$file->{entry}} if $dir->{consign};
+ $sig::hash::dirty{$dir} = $dir;
+}
+
+# Flush hash entries. Called at end or via ^C interrupt.
+sub END {
+ return if $called++; # May be called twice.
+ close(CONSIGN); # in case this came in via ^C.
+ my $dir;
+ for $dir (values %sig::hash::dirty) {
+ my($consign) = $dir->prefix . ".consign";
+ my($constemp) = $consign . ".$$";
+ if (! open(CONSIGN, ">$constemp")) {
+ die("$0: can't create $constemp ($!)\n");
+ }
+ my($entry, $sig);
+ while (($entry, $sig) = each %{$dir->{consign}}) {
+ if (! print CONSIGN "$entry:$sig\n") {
+ die("$0: error writing to $constemp ($!)\n");
+ }
+ }
+ close(CONSIGN);
+ if (! rename($constemp, $consign)) {
+ if (futil::copy($constemp, $consign)) {
+ unlink($constemp);
+ } else {
+ die("$0: couldn't rename or copy $constemp to $consign " .
+ "($!)\n");
+ }
+ }
+ }
+}
+
+
+# Derived file caching.
+package cache;
+
+# Find a file in the cache. Return non-null if the file is in the cache.
+sub in {
+ return undef unless $param::cache;
+ my($file, $sig) = @_;
+ # Add the path to the signature, to make it unique.
+ $sig = 'sig'->collect($sig, $file->path) unless $param::mixtargets;
+ my($dir) = substr($sig, 0, 1);
+ my($cp) = File::Spec->catfile($param::cache, $dir, $sig);
+ return -f $cp && futil::install($cp, $file);
+}
+
+# Try to flush a file to the cache, if not already there.
+# If it doesn't make it out, due to an error, then that doesn't
+# really matter.
+sub out {
+ return unless $param::cache;
+ my($file, $sig) = @_;
+ # Add the path to the signature, to make it unique.
+ $sig = 'sig'->collect($sig, $file->path) unless $param::mixtargets;
+ my($dir) = substr($sig, 0, 1);
+ my($sp) = $file->path;
+ my($cp) = File::Spec->catfile($param::cache, $dir, $sig);
+ my($cdir) = File::Spec->catfile($param::cache, $dir);
+ if (! -d $cdir) {
+ mkdir($cdir, 0777) ||
+ die("$0: can't create cache directory $cdir ($!).\n");
+ } elsif (-f $cp) {
+ # Already cached: try to use that instead, to save space.
+ # This can happen if the -cs option is used on a previously
+ # uncached build, or if two builds occur simultaneously.
+ my($lp) = ".$sig";
+ unlink($lp);
+ return if ! eval { link($cp, $lp) };
+ rename($lp, $sp);
+ # Unix98 says, "If the old argument and the new argument both
+ # [refer] to the same existing file, the rename() function
+ # returns successfully and performs no other action." So, if
+ # $lp and $sp are links (i.e., $cp and $sp are links), $lp is
+ # left, and we must unlink it ourselves. If the rename failed
+ # for any reason, it is also good form to unlink the temporary
+ # $lp. Otherwise $lp no longer exists and, barring some race,
+ # the unlink fails silently.
+ unlink($lp);
+ return;
+ }
+
+ return if eval { link($sp, $cp) };
+ return if ! -f $sp; # if nothing to cache.
+ if (futil::copy($sp, "$cp.new")) {
+ rename("$cp.new", $cp);
+ }
+}
+
+
+# Generic signature handling package.
+# This handles the higher-layer distinction between content and build
+# signatures, relying on an underlying calculation package like
+# "sig::md5"" to provide the signature values themselves.
+package sig;
+
+use vars qw( @ISA );
+
+# Select the underlying package to be used for signature calculation.
+# We play a few namespace games here. Specifically, we append
+# "sig::" to the beginning of the subclass we're passed. Then,
+# if the package ends in "::debug", we actually subclass the
+# "sig::debug" package and as a wrapper around the underlying
+# (e.g.) "sig::md5" package that's doing the real calculation.
+sub select {
+ my($package, $subclass) = @_;
+ my $p = $package . "::" . $subclass;
+ my $sigpkg = $p;
+ if ($p =~ /(.*)::debug$/) {
+ $sigpkg = $1;
+ $p = 'sig::debug';
+ }
+ @ISA = ($p);
+ $p->init($sigpkg);
+};
+
+# Set or return the build signature of a file.
+# This is computed elsewhere and passed in to us.
+sub bsig {
+ my($self, $file, $sig) = @_;
+ if (defined $sig) {
+ $file->{'bsig'} = $sig;
+ $self->set($file);
+ } elsif (! defined $file->{'bsig'}) {
+ $file->{'bsig'} = '';
+ }
+ $file->{'bsig'}
+}
+
+# Determine the content signature of a file.
+# This also sets the .consign entry unless the file is in a
+# repository; we don't write into repositories, only read from them.
+sub csig {
+ my($self, $file) = @_;
+ if (! $file->{'csig'}) {
+ $file->{'csig'} = $self->srcsig($file->path);
+ $self->set($file) if ! $file->is_on_rpath;
+ }
+ $_[1]->{'csig'}
+}
+
+# Determine the current signature of an already-existing or
+# non-existant file. Unless a specific signature type (bsig
+# or csig) is requested, this consults the file's signature
+# array to decide whether to return content or build signature,
+# and whether to use a cached value from a .consign file.
+sub signature {
+ my($self, $file, $sigtype) = @_;
+ $sigtype = $file->sigtype if ! $sigtype;
+ #open(TTY, ">/dev/tty");
+ #print TTY $file->path, ": $sigtype\n";
+ #close(TTY);
+ my($path) = $file->path;
+ my($time) = (stat($path))[9];
+ if ($time) {
+ if ($file->{$sigtype}) {
+ return $file->{$sigtype};
+ }
+ if ($file->is_on_rpath || $file->stored) {
+ if ('sig'->fetch($file) && $file->{$sigtype}) {
+ if ($file->{'sigtime'} == $time ||
+ ! $param::rep_sig_times_ok
+ && $file->is_on_rpath) {
+ return $file->{$sigtype};
+ }
+ }
+ $file->{$sigtype} = undef;
+ }
+ if ($file->is_on_rpath || ! File::Spec->file_name_is_absolute($path)) {
+ my $sig = '';
+ if ($sigtype eq 'bsig') { $sig = $self->bsig($file); }
+ elsif ($sigtype eq 'csig') { $sig = $self->csig($file); }
+ return $sig;
+ }
+ # This file is not in a repository or under the local directory
+ # structure. In the canonical case, it's a utility that will be
+ # executed by a command. Historically, Cons has returned the
+ # name of the command concatenated with the modification time.
+ # Note that this is *not* the path ("cc" not "/bin/cc"), so it
+ # would lose in the unlikely event that a different copy of the
+ # utility was used that happened to have the same modification
+ # time (due to living in a different directory on the PATH, for
+ # example). The obvious "fix" of using the path like so, however:
+ # return $path . $time;
+ # is wrong. In a multi-machine build environment, different
+ # systems may have the same utility in different locations (due
+ # to different NFS mount points, for example), which would
+ # cause a lot of unnecessary builds if we used the full path.
+ # A better solution to strengthen this signature would be to
+ # also concatenate the size of the file, but that would cause
+ # unnecessary rebuilds when coming from .consign files that used
+ # the old scheme. All of which is to merely explain why we're
+ # leaving this as it has been, but documenting it here in case
+ # there's reason to change it in the future.
+ return $file->{entry} . $time;
+ }
+ return $file->{$sigtype} = '';
+}
+
+sub bsignature {
+ my($self, $file) = @_;
+ my($path) = $file->path;
+ my($time) = (stat($path))[9];
+ if ($time) {
+ if ($file->{'bsig'}) {
+ return $file->{'bsig'};
+ }
+ if ('sig'->fetch($file, 'bsig') && $file->{'bsig'}) {
+ if ($file->{'sigtime'} == $time ||
+ ! $param::rep_sig_times_ok
+ && $file->is_on_rpath) {
+ return $file->{'bsig'};
+ }
+ }
+ if ($file->is_on_rpath || ! File::Spec->file_name_is_absolute($path)) {
+ return $self->bsig($file);
+ }
+ return $path . $time;
+ }
+ return $file->{'bsig'} = '';
+}
+
+# Invalidate a file's signature, also clearing its .consign entry.
+sub invalidate {
+ my($self, $file) = @_;
+ delete $file->{'sigtime'};
+ delete $file->{'bsig'};
+ delete $file->{'csig'};
+ sig::hash::clear($file);
+}
+
+# Store the signature for a file.
+sub set {
+ my($self, $file) = @_;
+ my $sig = (stat($file->path))[9];
+ $sig .= " " . ($file->{'bsig'} || '-');
+ $sig .= " " . $file->{'csig'} if $file->{'csig'};
+ sig::hash::out($file, $sig);
+}
+
+# Fetch the signature(s) for a file.
+# Returns whether there was a signature to fetch.
+sub fetch {
+ my($self, $file, @kw) = @_;
+ @kw = ('bsig', 'csig') if ! @kw;
+ my $sig = sig::hash::in($file) || '';
+ my($sigtime, $bsig, $csig) = split(/ /, $sig);
+ $file->{'sigtime'} = $sigtime;
+ $file->{'bsig'} = $bsig || '' if grep($_ eq 'bsig', @kw);
+ $file->{'csig'} = $csig || '' if grep($_ eq 'csig', @kw);
+ $file->{'bsig'} = '' if $file->{'bsig'} eq '-';
+ return $sig ne '';
+}
+
+# MD5-based signature package.
+package sig::md5;
+
+use vars qw( $md5 );
+
+# Initialize MD5 signature calculation by finding an appropriate
+# module and creating the proper object.
+sub init {
+ my $self = shift;
+ my @md5_modules = qw(Digest::MD5 MD5 Digest::Perl::MD5);
+ # We used to find the right module more simply, using $_ as the
+ # loop iterator and just doing:
+ #
+ # eval "use $_";
+ # $module = $_, $last if ! $@;
+ #
+ # in the loop. Empirically, though, this doesn't pass back the
+ # right value in $module on some ActiveState versions. (Maybe
+ # it's something to do with the eval in a for loop, I dunno.)
+ # Work around it by using $_ to pass the value out of the loop,
+ # which seems to work everywhere.
+ my $module;
+ for $module (@md5_modules) {
+ eval "use $module";
+ $_ = $module, last if ! $@;
+ }
+ $module = $_;
+ die "Cannot find any MD5 module from: @md5_modules" if $@;
+
+ $md5 = new $module;
+}
+
+# Is the provided signature equal to the signature of the current
+# instantiation of the target (and does the target exist)?
+sub current {
+ my($self, $file, $sig, $sigtype) = @_;
+ $self->bsignature($file) eq $sig;
+}
+
+# Return an aggregate signature for a list of signature values.
+sub collect {
+ my($self, @sigs) = @_;
+ # The following sequence is faster than calling the hex interface.
+ $md5->reset();
+ $md5->add(join('', $param::salt, @sigs));
+ unpack("H*", $md5->digest());
+}
+
+# Directly compute a file signature as the MD5 checksum of the
+# bytes in the file.
+sub srcsig {
+ my($self, $path) = @_;
+ $md5->reset();
+ open(FILE, $path) || return '';
+ binmode(FILE);
+ $md5->addfile(\*FILE);
+ close(FILE);
+ unpack("H*", $md5->digest());
+}
+
+# Compute the signature of a command string.
+# For MD5, this is just the string itself, since MD5 will condense
+# the string contents into the ultimate signature. Other signature
+# schemes may need to figure this out differently.
+sub cmdsig {
+ my($self, $sig) = @_;
+ return $sig
+}
+
+# Generic debug package for signature calculation.
+# Because of the way we're called by sig::select() and then use
+# the specified value to set up @ISA, this package is essentially a
+# factory that creates packages like sig::md5::debug, etc., on the fly.
+package sig::debug;
+
+use vars qw( @ISA $sigpkg $outfh );
+
+local *FH;
+
+sub init {
+ my $self = shift;
+ $sigpkg = shift;
+ @ISA = ($sigpkg);
+ $sigpkg->init();
+ my $file = $ENV{CONS_SIG_DEBUG};
+ if ($file) {
+ if (! open(FH, ">$file")) {
+ die "Cannot open $file: $!";
+ }
+ $outfh = \*FH;
+ } else {
+ $outfh = \*STDOUT;
+ }
+}
+
+sub current {
+ my($self, $file, $sig, $sigtype) = @_;
+ my $fsig = $self->bsignature($file);
+ my $sub = "${sigpkg}::current";
+ my $sep = "\n" . ' ' x (length($sub) + 1 - 3);
+ print $outfh "$sub(|$fsig|${sep}eq |$sig|)\n";
+ return $fsig eq $sig;
+}
+
+sub collect {
+ my($self, @sigs) = @_;
+ my $sig = $sigpkg->collect(@sigs);
+ my $sub = "${sigpkg}::collect";
+ my $sep = ",\n" . ' ' x (length($sub) + 1);
+ my $buf = join($sep, @sigs);
+ $buf = $param::salt . $sep . $buf if $param::salt;
+ print $outfh "$sub($buf)\n\t=> |$sig|\n";
+ return $sig;
+}
+
+sub srcsig {
+ my($self, $path) = @_;
+ my $sig = $sigpkg->srcsig($path);
+ print $outfh "${sigpkg}::srcsig($path)\n\t=> |$sig|\n";
+ return $sig;
+}
+
+__END__;
+
+=head1 NAME
+
+Cons - A Software Construction System
+
+=head1 DESCRIPTION
+
+A guide and reference for version 2.3.1
+
+Copyright (c) 1996-2001 Free Software Foundation, Inc.
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; see the file COPYING. If not, write to
+the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+Boston, MA 02111-1307, USA.
+
+=head1 Introduction
+
+B<Cons> is a system for constructing, primarily, software, but is quite
+different from previous software construction systems. Cons was designed
+from the ground up to deal easily with the construction of software spread
+over multiple source directories. Cons makes it easy to create build scripts
+that are simple, understandable and maintainable. Cons ensures that complex
+software is easily and accurately reproducible.
+
+Cons uses a number of techniques to accomplish all of this. Construction
+scripts are just Perl scripts, making them both easy to comprehend and very
+flexible. Global scoping of variables is replaced with an import/export
+mechanism for sharing information between scripts, significantly improving
+the readability and maintainability of each script. B<Construction
+environments> are introduced: these are Perl objects that capture the
+information required for controlling the build process. Multiple
+environments are used when different semantics are required for generating
+products in the build tree. Cons implements automatic dependency analysis
+and uses this to globally sequence the entire build. Variant builds are
+easily produced from a single source tree. Intelligent build subsetting is
+possible, when working on localized changes. Overrides can be setup to
+easily override build instructions without modifying any scripts. MD5
+cryptographic B<signatures> are associated with derived files, and are used
+to accurately determine whether a given file needs to be rebuilt.
+
+While offering all of the above, and more, Cons remains simple and easy to
+use. This will, hopefully, become clear as you read the remainder of this
+document.
+
+
+=head1 Why Cons? Why not Make?
+
+Cons is a B<make> replacement. In the following paragraphs, we look at a few
+of the undesirable characteristics of make--and typical build environments
+based on make--that motivated the development of Cons.
+
+=head2 Build complexity
+
+Traditional make-based systems of any size tend to become quite complex. The
+original make utility and its derivatives have contributed to this tendency
+in a number of ways. Make is not good at dealing with systems that are
+spread over multiple directories. Various work-arounds are used to overcome
+this difficulty; the usual choice is for make to invoke itself recursively
+for each sub-directory of a build. This leads to complicated code, in which
+it is often unclear how a variable is set, or what effect the setting of a
+variable will have on the build as a whole. The make scripting language has
+gradually been extended to provide more possibilities, but these have
+largely served to clutter an already overextended language. Often, builds
+are done in multiple passes in order to provide appropriate products from
+one directory to another directory. This represents a further increase in
+build complexity.
+
+
+=head2 Build reproducibility
+
+The bane of all makes has always been the correct handling of
+dependencies. Most often, an attempt is made to do a reasonable job of
+dependencies within a single directory, but no serious attempt is made to do
+the job between directories. Even when dependencies are working correctly,
+make's reliance on a simple time stamp comparison to determine whether a
+file is out of date with respect to its dependents is not, in general,
+adequate for determining when a file should be rederived. If an external
+library, for example, is rebuilt and then ``snapped'' into place, the
+timestamps on its newly created files may well be earlier than the last
+local build, since it was built before it became visible.
+
+
+=head2 Variant builds
+
+Make provides only limited facilities for handling variant builds. With the
+proliferation of hardware platforms and the need for debuggable
+vs. optimized code, the ability to easily create these variants is
+essential. More importantly, if variants are created, it is important to
+either be able to separate the variants or to be able to reproduce the
+original or variant at will. With make it is very difficult to separate the
+builds into multiple build directories, separate from the source. And if
+this technique isn't used, it's also virtually impossible to guarantee at
+any given time which variant is present in the tree, without resorting to a
+complete rebuild.
+
+
+=head2 Repositories
+
+Make provides only limited support for building software from code that
+exists in a central repository directory structure. The VPATH feature of
+GNU make (and some other make implementations) is intended to provide this,
+but doesn't work as expected: it changes the path of target file to the
+VPATH name too early in its analysis, and therefore searches for all
+dependencies in the VPATH directory. To ensure correct development builds,
+it is important to be able to create a file in a local build directory and
+have any files in a code repository (a VPATH directory, in make terms) that
+depend on the local file get rebuilt properly. This isn't possible with
+VPATH, without coding a lot of complex repository knowledge directly into
+the makefiles.
+
+
+=head1 Keeping it simple
+
+A few of the difficulties with make have been cited above. In this and
+subsequent sections, we shall introduce Cons and show how these issues are
+addressed.
+
+=head2 Perl scripts
+
+Cons is Perl-based. That is, Cons scripts--F<Conscript> and F<Construct>
+files, the equivalent to F<Makefile> or F<makefile>--are all written in
+Perl. This provides an immediate benefit: the language for writing scripts
+is a familiar one. Even if you don't happen to be a Perl programmer, it
+helps to know that Perl is basically just a simple declarative language,
+with a well-defined flow of control, and familiar semantics. It has
+variables that behave basically the way you would expect them to,
+subroutines, flow of control, and so on. There is no special syntax
+introduced for Cons. The use of Perl as a scripting language simplifies
+the task of expressing the appropriate solution to the often complex
+requirements of a build.
+
+
+=head2 Hello, World!
+
+To ground the following discussion, here's how you could build the B<Hello,
+World!> C application with Cons:
+
+
+
+ $env = new cons();
+ Program $env 'hello', 'hello.c';
+
+If you install this script in a directory, naming the script F<Construct>,
+and create the F<hello.c> source file in the same directory, then you can
+type C<cons hello> to build the application:
+
+
+
+ % cons hello
+ cc -c hello.c -o hello.o
+ cc -o hello hello.o
+
+
+=head2 Construction environments
+
+A key simplification of Cons is the idea of a B<construction environment>. A
+construction environment is an B<object> characterized by a set of key/value
+pairs and a set of B<methods>. In order to tell Cons how to build something,
+you invoke the appropriate method via an appropriate construction
+environment. Consider the following example:
+
+
+
+ $env = new cons(
+ CC => 'gcc',
+ LIBS => 'libworld.a'
+ );
+
+ Program $env 'hello', 'hello.c';
+
+In this case, rather than using the default construction environment, as is,
+we have overridden the value of C<CC> so that the GNU C Compiler equivalent
+is used, instead. Since this version of B<Hello, World!> requires a library,
+F<libworld.a>, we have specified that any program linked in this environment
+should be linked with that library. If the library exists already, well and
+good, but if not, then we'll also have to include the statement:
+
+
+
+ Library $env 'libworld', 'world.c';
+
+Now if you type C<cons hello>, the library will be built before the program
+is linked, and, of course, C<gcc> will be used to compile both modules:
+
+
+
+ % cons hello
+ gcc -c hello.c -o hello.o
+ gcc -c world.c -o world.o
+ ar r libworld.a world.o
+ ar: creating libworld.a
+ ranlib libworld.a
+ gcc -o hello hello.o libworld.a
+
+
+=head2 Automatic and complete dependency analysis
+
+With Cons, dependencies are handled automatically. Continuing the previous
+example, note that when we modify F<world.c>, F<world.o> is recompiled,
+F<libworld.a> recreated, and F<hello> relinked:
+
+
+
+ % vi world.c
+ [EDIT]
+ % cons hello
+ gcc -c world.c -o world.o
+ ar r libworld.a world.o
+ ar: creating libworld.a
+ ranlib libworld.a
+ gcc -o hello hello.o libworld.a
+
+This is a relatively simple example: Cons ``knows'' F<world.o> depends upon
+F<world.c>, because the dependency is explicitly set up by the C<Library>
+method. It also knows that F<libworld.a> depends upon F<world.o> and that
+F<hello> depends upon F<libworld.a>, all for similar reasons.
+
+Now it turns out that F<hello.c> also includes the interface definition
+file, F<world.h>:
+
+
+
+ % emacs world.h
+ [EDIT]
+ % cons hello
+ gcc -c hello.c -o hello.o
+ gcc -o hello hello.o libworld.a
+
+How does Cons know that F<hello.c> includes F<world.h>, and that F<hello.o>
+must therefore be recompiled? For now, suffice it to say that when
+considering whether or not F<hello.o> is up-to-date, Cons invokes a scanner
+for its dependency, F<hello.c>. This scanner enumerates the files included
+by F<hello.c> to come up with a list of further dependencies, beyond those
+made explicit by the Cons script. This process is recursive: any files
+included by included files will also be scanned.
+
+Isn't this expensive? The answer is--it depends. If you do a full build of a
+large system, the scanning time is insignificant. If you do a rebuild of a
+large system, then Cons will spend a fair amount of time thinking about it
+before it decides that nothing has to be done (although not necessarily more
+time than make!). The good news is that Cons makes it very easy to
+intelligently subset your build, when you are working on localized changes.
+
+
+=head2 Automatic global build sequencing
+
+Because Cons does full and accurate dependency analysis, and does this
+globally, for the entire build, Cons is able to use this information to take
+full control of the B<sequencing> of the build. This sequencing is evident
+in the above examples, and is equivalent to what you would expect for make,
+given a full set of dependencies. With Cons, this extends trivially to
+larger, multi-directory builds. As a result, all of the complexity involved
+in making sure that a build is organized correctly--including multi-pass
+hierarchical builds--is eliminated. We'll discuss this further in the next
+sections.
+
+=head1 Building large trees--still just as simple
+
+
+=head2 A hierarchy of build scripts
+
+A larger build, in Cons, is organized by creating a hierarchy of B<build
+scripts>. At the top of the tree is a script called F<Construct>. The rest
+of the scripts, by convention, are each called F<Conscript>. These scripts
+are connected together, very simply, by the C<Build>, C<Export>, and
+C<Import> commands.
+
+
+=head2 The Build command
+
+The C<Build> command takes a list of F<Conscript> file names, and arranges
+for them to be included in the build. For example:
+
+ Build qw(
+ drivers/display/Conscript
+ drivers/mouse/Conscript
+ parser/Conscript
+ utilities/Conscript
+ );
+
+This is a simple two-level hierarchy of build scripts: all the subsidiary
+F<Conscript> files are mentioned in the top-level F<Construct> file. Notice
+that not all directories in the tree necessarily have build scripts
+associated with them.
+
+This could also be written as a multi-level script. For example, the
+F<Construct> file might contain this command:
+
+ Build qw(
+ parser/Conscript
+ drivers/Conscript
+ utilities/Conscript
+ );
+
+and the F<Conscript> file in the F<drivers> directory might contain this:
+
+ Build qw(
+ display/Conscript
+ mouse/Conscript
+ );
+
+Experience has shown that the former model is a little easier to understand,
+since the whole construction tree is laid out in front of you, at the
+top-level. Hybrid schemes are also possible. A separately maintained
+component that needs to be incorporated into a build tree, for example,
+might hook into the build tree in one place, but define its own construction
+hierarchy.
+
+By default, Cons does not change its working directory to the directory
+containing a subsidiary F<Conscript> file it is including. This behavior
+can be enabled for a build by specifying, in the top-level F<Construct>
+file:
+
+ Conscript_chdir 1;
+
+When enabled, Cons will change to the subsidiary F<Conscript> file's
+containing directory while reading in that file, and then change back
+to the top-level directory once the file has been processed.
+
+It is expected that this behavior will become the default in some future
+version of Cons. To prepare for this transition, builds that expect
+Cons to remain at the top of the build while it reads in a subsidiary
+F<Conscript> file should explicitly disable this feature as follows:
+
+ Conscript_chdir 0;
+
+
+=head2 Relative, top-relative, and absolute file names
+
+You may have noticed that the file names specified to the Build command are
+relative to the location of the script it is invoked from. This is generally
+true for other filename arguments to other commands, too, although we might
+as well mention here that if you begin a file name with a hash mark, ``#'',
+then that file is interpreted relative to the top-level directory (where the
+F<Construct> file resides). And, not surprisingly, if you begin it with ``/'',
+then it is considered to be an absolute pathname. This is true even on
+systems which use a back slash rather than a forward slash to name absolute
+paths.
+
+(There is another file prefix, ``!'', that is interpreted specially by
+Cons. See discussion of the C<Link> command, below, for details.)
+
+
+=head2 Using modules in build scripts
+
+You may pull modules into each F<Conscript> file using the normal Perl
+C<use> or C<require> statements:
+
+ use English;
+ require My::Module;
+
+Each C<use> or C<require> only affects the one F<Conscript> file in which
+it appears. To use a module in multiple F<Conscript> files, you must
+put a C<use> or C<require> statement in each one that needs the module.
+
+
+=head2 Scope of variables
+
+The top-level F<Construct> file and all F<Conscript> files begin life in
+a common, separate Perl package. B<Cons> controls the symbol table for
+the package so that, the symbol table for each script is empty, except
+for the F<Construct> file, which gets some of the command line arguments.
+All of the variables that are set or used, therefore, are set by the
+script itself--not by some external script.
+
+Variables can be explicitly B<imported> by a script from its parent
+script. To import a variable, it must have been B<exported> by the parent
+and initialized (otherwise an error will occur).
+
+
+=head2 The Export command
+
+The C<Export> command is used as in the following example:
+
+ $env = new cons();
+ $INCLUDE = "#export/include";
+ $LIB = "#export/lib";
+ Export qw( env INCLUDE LIB );
+ Build qw( util/Conscript );
+
+The values of the simple variables mentioned in the C<Export> list will be
+squirreled away by any subsequent C<Build> commands. The C<Export> command
+will only export Perl B<scalar> variables, that is, variables whose name
+begins with C<$>. Other variables, objects, etc. can be exported by
+reference--but all scripts will refer to the same object, and this object
+should be considered to be read-only by the subsidiary scripts and by the
+original exporting script. It's acceptable, however, to assign a new value
+to the exported scalar variable--that won't change the underlying variable
+referenced. This sequence, for example, is OK:
+
+ $env = new cons();
+ Export qw( env INCLUDE LIB );
+ Build qw( util/Conscript );
+ $env = new cons(CFLAGS => '-O');
+ Build qw( other/Conscript );
+
+It doesn't matter whether the variable is set before or after the C<Export>
+command. The important thing is the value of the variable at the time the
+C<Build> command is executed. This is what gets squirreled away. Any
+subsequent C<Export> commands, by the way, invalidate the first: you must
+mention all the variables you wish to export on each C<Export> command.
+
+
+=head2 The Import command
+
+Variables exported by the C<Export> command can be imported into subsidiary
+scripts by the C<Import> command. The subsidiary script always imports
+variables directly from the superior script. Consider this example:
+
+ Import qw( env INCLUDE );
+
+This is only legal if the parent script exported both C<$env> and
+C<$INCLUDE>. It also must have given each of these variables values. It is
+OK for the subsidiary script to only import a subset of the exported
+variables (in this example, C<$LIB>, which was exported by the previous
+example, is not imported).
+
+All the imported variables are automatically re-exported, so the sequence:
+
+ Import qw ( env INCLUDE );
+ Build qw ( beneath-me/Conscript );
+
+will supply both C<$env> and C<$INCLUDE> to the subsidiary file. If only
+C<$env> is to be exported, then the following will suffice:
+
+ Import qw ( env INCLUDE );
+ Export qw ( env );
+ Build qw ( beneath-me/Conscript );
+
+Needless to say, the variables may be modified locally before invoking
+C<Build> on the subsidiary script.
+
+
+=head2 Build script evaluation order
+
+The only constraint on the ordering of build scripts is that superior
+scripts are evaluated before their inferior scripts. The top-level
+F<Construct> file, for instance, is evaluated first, followed by any
+inferior scripts. This is all you really need to know about the evaluation
+order, since order is generally irrelevant. Consider the following C<Build>
+command:
+
+ Build qw(
+ drivers/display/Conscript
+ drivers/mouse/Conscript
+ parser/Conscript
+ utilities/Conscript
+ );
+
+We've chosen to put the script names in alphabetical order, simply because
+that's the most convenient for maintenance purposes. Changing the order will
+make no difference to the build.
+
+
+=head1 A Model for sharing files
+
+
+=head2 Some simple conventions
+
+In any complex software system, a method for sharing build products needs to
+be established. We propose a simple set of conventions which are trivial to
+implement with Cons, but very effective.
+
+The basic rule is to require that all build products which need to be shared
+between directories are shared via an intermediate directory. We have
+typically called this F<export>, and, in a C environment, provided
+conventional sub-directories of this directory, such as F<include>, F<lib>,
+F<bin>, etc.
+
+These directories are defined by the top-level F<Construct> file. A simple
+F<Construct> file for a B<Hello, World!> application, organized using
+multiple directories, might look like this:
+
+ # Construct file for Hello, World!
+
+ # Where to put all our shared products.
+ $EXPORT = '#export';
+
+ Export qw( CONS INCLUDE LIB BIN );
+
+ # Standard directories for sharing products.
+ $INCLUDE = "$EXPORT/include";
+ $LIB = "$EXPORT/lib";
+ $BIN = "$EXPORT/bin";
+
+ # A standard construction environment.
+ $CONS = new cons (
+ CPPPATH => $INCLUDE, # Include path for C Compilations
+ LIBPATH => $LIB, # Library path for linking programs
+ LIBS => '-lworld', # List of standard libraries
+ );
+
+ Build qw(
+ hello/Conscript
+ world/Conscript
+ );
+
+The F<world> directory's F<Conscript> file looks like this:
+
+ # Conscript file for directory world
+ Import qw( CONS INCLUDE LIB );
+
+ # Install the products of this directory
+ Install $CONS $LIB, 'libworld.a';
+ Install $CONS $INCLUDE, 'world.h';
+
+ # Internal products
+ Library $CONS 'libworld.a', 'world.c';
+
+and the F<hello> directory's F<Conscript> file looks like this:
+
+ # Conscript file for directory hello
+ Import qw( CONS BIN );
+
+ # Exported products
+ Install $CONS $BIN, 'hello';
+
+ # Internal products
+ Program $CONS 'hello', 'hello.c';
+
+To construct a B<Hello, World!> program with this directory structure, go to
+the top-level directory, and invoke C<cons> with the appropriate
+arguments. In the following example, we tell Cons to build the directory
+F<export>. To build a directory, Cons recursively builds all known products
+within that directory (only if they need rebuilding, of course). If any of
+those products depend upon other products in other directories, then those
+will be built, too.
+
+ % cons export
+ Install world/world.h as export/include/world.h
+ cc -Iexport/include -c hello/hello.c -o hello/hello.o
+ cc -Iexport/include -c world/world.c -o world/world.o
+ ar r world/libworld.a world/world.o
+ ar: creating world/libworld.a
+ ranlib world/libworld.a
+ Install world/libworld.a as export/lib/libworld.a
+ cc -o hello/hello hello/hello.o -Lexport/lib -lworld
+ Install hello/hello as export/bin/hello
+
+
+=head2 Clean, understandable, location-independent scripts
+
+You'll note that the two F<Conscript> files are very clean and
+to-the-point. They simply specify products of the directory and how to build
+those products. The build instructions are minimal: they specify which
+construction environment to use, the name of the product, and the name of
+the inputs. Note also that the scripts are location-independent: if you wish
+to reorganize your source tree, you are free to do so: you only have to
+change the F<Construct> file (in this example), to specify the new locations
+of the F<Conscript> files. The use of an export tree makes this goal easy.
+
+Note, too, how Cons takes care of little details for you. All the F<export>
+directories, for example, were made automatically. And the installed files
+were really hard-linked into the respective export directories, to save
+space and time. This attention to detail saves considerable work, and makes
+it even easier to produce simple, maintainable scripts.
+
+
+=head1 Separating source and build trees
+
+It's often desirable to keep any derived files from the build completely
+separate from the source files. This makes it much easier to keep track of
+just what is a source file, and also makes it simpler to handle B<variant>
+builds, especially if you want the variant builds to co-exist.
+
+
+=head2 Separating build and source directories using the Link command
+
+Cons provides a simple mechanism that handles all of these requirements. The
+C<Link> command is invoked as in this example:
+
+ Link 'build' => 'src';
+
+The specified directories are ``linked'' to the specified source
+directory. Let's suppose that you setup a source directory, F<src>, with the
+sub-directories F<world> and F<hello> below it, as in the previous
+example. You could then substitute for the original build lines the
+following:
+
+ Build qw(
+ build/world/Conscript
+ build/hello/Conscript
+ );
+
+Notice that you treat the F<Conscript> file as if it existed in the build
+directory. Now if you type the same command as before, you will get the
+following results:
+
+ % cons export
+ Install build/world/world.h as export/include/world.h
+ cc -Iexport/include -c build/hello/hello.c -o build/hello/hello.o
+ cc -Iexport/include -c build/world/world.c -o build/world/world.o
+ ar r build/world/libworld.a build/world/world.o
+ ar: creating build/world/libworld.a
+ ranlib build/world/libworld.a
+ Install build/world/libworld.a as export/lib/libworld.a
+ cc -o build/hello/hello build/hello/hello.o -Lexport/lib -lworld
+ Install build/hello/hello as export/bin/hello
+
+Again, Cons has taken care of the details for you. In particular, you will
+notice that all the builds are done using source files and object files from
+the build directory. For example, F<build/world/world.o> is compiled from
+F<build/world/world.c>, and F<export/include/world.h> is installed from
+F<build/world/world.h>. This is accomplished on most systems by the simple
+expedient of ``hard'' linking the required files from each source directory
+into the appropriate build directory.
+
+The links are maintained correctly by Cons, no matter what you do to the
+source directory. If you modify a source file, your editor may do this ``in
+place'' or it may rename it first and create a new file. In the latter case,
+any hard link will be lost. Cons will detect this condition the next time
+the source file is needed, and will relink it appropriately.
+
+You'll also notice, by the way, that B<no> changes were required to the
+underlying F<Conscript> files. And we can go further, as we shall see in the
+next section.
+
+=head2 Explicit references to the source directory
+
+When using the C<Link> command on some operating systems or with some
+tool chains, it's sometimes useful to have a command actually use
+the path name to the source directory, not the build directory. For
+example, on systems that must copy, not "hard link," the F<src/> and
+F<build/> copies of C<Linked> files, using the F<src/> path of a file
+name might make an editor aware that a syntax error must be fixed in the
+source directory, not the build directory.
+
+You can tell Cons that you want to use the "source path" for a file by
+preceding the file name with a ``!'' (exclamation point). For example,
+if we add a ``!'' to the beginning of a source file:
+
+ Program $env "foo", "!foo.c"; # Notice initial ! on foo.c
+
+Cons will compile the target as follows:
+
+ cc -c src/foo.c -o build/foo.o
+ cc -o build/foo build/foo.o
+
+Notice that Cons has compiled the program from the the F<src/foo.c>
+source file. Without the initial ``!'', Cons would have compiled the
+program using the F<build/foo.c> path name.
+
+
+
+=head1 Variant builds
+
+
+=head2 Hello, World! for baNaNa and peAcH OS's
+
+Variant builds require just another simple extension. Let's take as an
+example a requirement to allow builds for both the baNaNa and peAcH
+operating systems. In this case, we are using a distributed file system,
+such as NFS to access the particular system, and only one or the other of
+the systems has to be compiled for any given invocation of C<cons>. Here's
+one way we could set up the F<Construct> file for our B<Hello, World!>
+application:
+
+ # Construct file for Hello, World!
+
+ die qq(OS must be specified) unless $OS = $ARG{OS};
+ die qq(OS must be "peach" or "banana")
+ if $OS ne "peach" && $OS ne "banana";
+
+ # Where to put all our shared products.
+ $EXPORT = "#export/$OS";
+
+ Export qw( CONS INCLUDE LIB BIN );
+
+ # Standard directories for sharing products.
+ $INCLUDE = "$EXPORT/include";
+ $LIB = "$EXPORT/lib";
+ $BIN = "$EXPORT/bin";
+
+ # A standard construction environment.
+ $CONS = new cons (
+ CPPPATH => $INCLUDE, # Include path for C Compilations
+ LIBPATH => $LIB, # Library path for linking programs
+ LIBS => '-lworld', # List of standard libraries
+ );
+
+ # $BUILD is where we will derive everything.
+ $BUILD = "#build/$OS";
+
+ # Tell cons where the source files for $BUILD are.
+ Link $BUILD => 'src';
+
+ Build (
+ "$BUILD/hello/Conscript",
+ "$BUILD/world/Conscript",
+ );
+
+Now if we login to a peAcH system, we can build our B<Hello, World!>
+application for that platform:
+
+ % cons export OS=peach
+ Install build/peach/world/world.h as export/peach/include/world.h
+ cc -Iexport/peach/include -c build/peach/hello/hello.c -o build/peach/hello/hello.o
+ cc -Iexport/peach/include -c build/peach/world/world.c -o build/peach/world/world.o
+ ar r build/peach/world/libworld.a build/peach/world/world.o
+ ar: creating build/peach/world/libworld.a
+ ranlib build/peach/world/libworld.a
+ Install build/peach/world/libworld.a as export/peach/lib/libworld.a
+ cc -o build/peach/hello/hello build/peach/hello/hello.o -Lexport/peach/lib -lworld
+ Install build/peach/hello/hello as export/peach/bin/hello
+
+
+=head2 Variations on a theme
+
+Other variations of this model are possible. For example, you might decide
+that you want to separate out your include files into platform dependent and
+platform independent files. In this case, you'd have to define an
+alternative to C<$INCLUDE> for platform-dependent files. Most F<Conscript>
+files, generating purely platform-independent include files, would not have
+to change.
+
+You might also want to be able to compile your whole system with debugging
+or profiling, for example, enabled. You could do this with appropriate
+command line options, such as C<DEBUG=on>. This would then be translated
+into the appropriate platform-specific requirements to enable debugging
+(this might include turning off optimization, for example). You could
+optionally vary the name space for these different types of systems, but, as
+we'll see in the next section, it's not B<essential> to do this, since Cons
+is pretty smart about rebuilding things when you change options.
+
+
+=head1 Signatures
+
+Cons uses file B<signatures> to decide if a derived file is out-of-date
+and needs rebuilding. In essence, if the contents of a file change,
+or the manner in which the file is built changes, the file's signature
+changes as well. This allows Cons to decide with certainty when a file
+needs rebuilding, because Cons can detect, quickly and reliably, whether
+any of its dependency files have been changed.
+
+
+=head2 MD5 content and build signatures
+
+Cons uses the B<MD5> (B<Message Digest 5>) algorithm to compute file
+signatures. The MD5 algorithm computes a strong cryptographic checksum
+for any given input string. Cons can, based on configuration, use two
+different MD5 signatures for a given file:
+
+The B<content signature> of a file is an MD5 checksum of the file's
+contents. Consequently, when the contents of a file change, its content
+signature changes as well.
+
+The B<build signature> of a file is a combined MD5 checksum of:
+
+=over 4
+
+the signatures of all the input files used to build the file
+
+the signatures of all dependency files discovered by source scanners
+(for example, C<.h> files)
+
+the signatures of all dependency files specified explicitly via the
+C<Depends> method)
+
+the command-line string used to build the file
+
+=back
+
+The build signature is, in effect, a digest of all the dependency
+information for the specified file. Consequently, a file's build
+signature changes whenever any part of its dependency information
+changes: a new file is added, the contents of a file on which it depends
+change, there's a change to the command line used to build the file (or
+any of its dependency files), etc.
+
+For example, in the previous section, the build signature of the
+F<world.o> file will include:
+
+=over 4
+
+the signature of the F<world.c> file
+
+the signatures of any header files that Cons detects are included,
+directly or indirectly, by F<world.c>
+
+the text of the actual command line was used to generate F<world.o>
+
+=back
+
+Similarly, the build signature of the F<libworld.a> file will include
+all the signatures of its constituents (and hence, transitively, the
+signatures of B<their> constituents), as well as the command line that
+created the file.
+
+Note that there is no need for a derived file to depend upon any
+particular F<Construct> or F<Conscript> file. If changes to these files
+affect a file, then this will be automatically reflected in its build
+signature, since relevant parts of the command line are included in the
+signature. Unrelated F<Construct> or F<Conscript> changes will have no
+effect.
+
+
+=head2 Storing signatures in .consign files
+
+Before Cons exits, it stores the calculated signatures for all of the
+files it built or examined in F<.consign> files, one per directory.
+Cons uses this stored information on later invocations to decide if
+derived files need to be rebuilt.
+
+After the previous example was compiled, the F<.consign> file in the
+F<build/peach/world> directory looked like this:
+
+ world.h:985533370 - d181712f2fdc07c1f05d97b16bfad904
+ world.o:985533372 2a0f71e0766927c0532977b0d2158981
+ world.c:985533370 - c712f77189307907f4189b5a7ab62ff3
+ libworld.a:985533374 69e568fc5241d7d25be86d581e1fb6aa
+
+After the file name and colon, the first number is a timestamp of the
+file's modification time (on UNIX systems, this is typically the number
+of seconds since January 1st, 1970). The second value is the build
+signature of the file (or ``-'' in the case of files with no build
+signature--that is, source files). The third value, if any, is the
+content signature of the file.
+
+
+=head2 Using build signatures to decide when to rebuild files
+
+When Cons is deciding whether to build or rebuild a derived file, it
+first computes the file's current build signature. If the file doesn't
+exist, it must obviously be built.
+
+If, however, the file already exists, Cons next compares the
+modification timestamp of the file against the timestamp value in
+the F<.consign> file. If the timestamps match, Cons compares the
+newly-computed build signature against the build signature in the
+F<.consign> file. If the timestamps do not match or the build
+signatures do not match, the derived file is rebuilt.
+
+After the file is built or rebuilt, Cons arranges to store the
+newly-computed build signature in the F<.consign> file when it exits.
+
+
+=head2 Signature example
+
+The use of these signatures is an extremely simple, efficient, and
+effective method of improving--dramatically--the reproducibility of a
+system.
+
+We'll demonstrate this with a simple example:
+
+ # Simple "Hello, World!" Construct file
+ $CFLAGS = '-g' if $ARG{DEBUG} eq 'on';
+ $CONS = new cons(CFLAGS => $CFLAGS);
+ Program $CONS 'hello', 'hello.c';
+
+Notice how Cons recompiles at the appropriate times:
+
+ % cons hello
+ cc -c hello.c -o hello.o
+ cc -o hello hello.o
+ % cons hello
+ cons: "hello" is up-to-date.
+ % cons DEBUG=on hello
+ cc -g -c hello.c -o hello.o
+ cc -o hello hello.o
+ % cons DEBUG=on hello
+ cons: "hello" is up-to-date.
+ % cons hello
+ cc -c hello.c -o hello.o
+ cc -o hello hello.o
+
+
+=head2 Source-file signature configuration
+
+Cons provides a C<SourceSignature> method that allows you to configure
+how the signature should be calculated for any source file when its
+signature is being used to decide if a dependent file is up-to-date.
+The arguments to the C<SourceSignature> method consist of one or more
+pairs of strings:
+
+ SourceSignature 'auto/*.c' => 'content',
+ '*' => 'stored-content';
+
+The first string in each pair is a pattern to match against derived file
+path names. The pattern is a file-globbing pattern, not a Perl regular
+expression; the pattern <*.l> will match all Lex source files. The C<*>
+wildcard will match across directory separators; the pattern C<foo/*.c>
+would match all C source files in any subdirectory underneath the C<foo>
+subdirectory.
+
+The second string in each pair contains one of the following keywords to
+specify how signatures should be calculated for source files that match
+the pattern. The available keywords are:
+
+=over 4
+
+=item content
+
+Use the content signature of the source file when calculating signatures
+of files that depend on it. This guarantees correct calculation of the
+file's signature for all builds, by telling Cons to read the contents of
+a source file to calculate its content signature each time it is run.
+
+=item stored-content
+
+Use the source file's content signature as stored in the F<.consign>
+file, provided the file's timestamp matches the cached timestamp value
+in the F<.consign> file. This optimizes performance, with the slight
+risk of an incorrect build if a source file's contents have been changed
+so quickly after its previous update that the timestamp still matches
+the stored timestamp in the F<.consign> file even though the contents
+have changed.
+
+=back
+
+The Cons default behavior of always calculating a source file's
+signature from the file's contents is equivalent to specifying:
+
+ SourceSignature '*' => 'content';
+
+The C<*> will match all source files. The C<content> keyword
+specifies that Cons will read the contents of a source file to calculate
+its signature each time it is run.
+
+A useful global performance optimization is:
+
+ SourceSignature '*' => 'stored-content';
+
+This specifies that Cons will use pre-computed content signatures
+from F<.consign> files, when available, rather than re-calculating a
+signature from the the source file's contents each time Cons is run. In
+practice, this is safe for most build situations, and only a problem
+when source files are changed automatically (by scripts, for example).
+The Cons default, however, errs on the side of guaranteeing a correct
+build in all situations.
+
+Cons tries to match source file path names against the patterns in the
+order they are specified in the C<SourceSignature> arguments:
+
+ SourceSignature '/usr/repository/objects/*' => 'stored-content',
+ '/usr/repository/*' => 'content',
+ '*.y' => 'content',
+ '*' => 'stored-content';
+
+In this example, all source files under the F</usr/repository/objects>
+directory will use F<.consign> file content signatures, source files
+anywhere else underneath F</usr/repository> will not use F<.consign>
+signature values, all Yacc source files (C<*.y>) anywhere else will not
+use F<.consign> signature values, and any other source file will use
+F<.consign> signature values.
+
+
+=head2 Derived-file signature configuration
+
+Cons provides a C<SIGNATURE> construction variable that allows you to
+configure how signatures are calculated for any derived file when its
+signature is being used to decide if a dependent file is up-to-date.
+The value of the C<SIGNATURE> construction variable is a Perl array
+reference that holds one or more pairs of strings, like the arguments to
+the C<SourceSignature> method.
+
+The first string in each pair is a pattern to match against derived file
+path names. The pattern is a file-globbing pattern, not a Perl regular
+expression; the pattern `*.obj' will match all (Win32) object files.
+The C<*> wildcard will match across directory separators; the pattern
+`foo/*.a' would match all (UNIX) library archives in any subdirectory
+underneath the foo subdirectory.
+
+The second string in each pair contains one of the following keywords
+to specify how signatures should be calculated for derived files that
+match the pattern. The available keywords are the same as for the
+C<SourceSignature> method, with an additional keyword:
+
+=over 4
+
+=item build
+
+Use the build signature of the derived file when calculating signatures
+of files that depend on it. This guarantees correct builds by forcing
+Cons to rebuild any and all files that depend on the derived file.
+
+=item content
+
+Use the content signature of the derived file when calculating signatures
+of files that depend on it. This guarantees correct calculation of the
+file's signature for all builds, by telling Cons to read the contents of
+a derived file to calculate its content signature each time it is run.
+
+=item stored-content
+
+Use the derived file's content signature as stored in the F<.consign>
+file, provided the file's timestamp matches the cached timestamp value
+in the F<.consign> file. This optimizes performance, with the slight
+risk of an incorrect build if a derived file's contents have been
+changed so quickly after a Cons build that the file's timestamp still
+matches the stored timestamp in the F<.consign> file.
+
+=back
+
+The Cons default behavior (as previously described) for using
+derived-file signatures is equivalent to:
+
+ $env = new cons(SIGNATURE => ['*' => 'build']);
+
+The C<*> will match all derived files. The C<build> keyword specifies
+that all derived files' build signatures will be used when calculating
+whether a dependent file is up-to-date.
+
+A useful alternative default C<SIGNATURE> configuration for many sites:
+
+ $env = new cons(SIGNATURE => ['*' => 'content']);
+
+In this configuration, derived files have their signatures calculated
+from the file contents. This adds slightly to Cons' workload, but has
+the useful effect of "stopping" further rebuilds if a derived file is
+rebuilt to exactly the same file contents as before, which usually
+outweighs the additional computation Cons must perform.
+
+For example, changing a comment in a C file and recompiling should
+generate the exact same object file (assuming the compiler doesn't
+insert a timestamp in the object file's header). In that case,
+specifying C<content> or C<stored-content> for the signature calculation
+will cause Cons to recognize that the object file did not actually
+change as a result of being rebuilt, and libraries or programs that
+include the object file will not be rebuilt. When C<build> is
+specified, however, Cons will only "know" that the object file was
+rebuilt, and proceed to rebuild any additional files that include the
+object file.
+
+Note that Cons tries to match derived file path names against the
+patterns in the order they are specified in the C<SIGNATURE> array
+reference:
+
+ $env = new cons(SIGNATURE => ['foo/*.o' => 'build',
+ '*.o' => 'content',
+ '*.a' => 'stored-content',
+ '*' => 'content']);
+
+In this example, all object files underneath the F<foo> subdirectory
+will use build signatures, all other object files (including object
+files underneath other subdirectories!) will use F<.consign> file
+content signatures, libraries will use F<.consign> file build
+signatures, and all other derived files will use content signatures.
+
+
+=head2 Debugging signature calculation
+
+Cons provides a C<-S> option that can be used to specify what internal
+Perl package Cons should use to calculate signatures. The default Cons
+behavior is equivalent to specifying C<-S md5> on the command line.
+
+The only other package (currently) available is an C<md5::debug>
+package that prints out detailed information about the MD5 signature
+calculations performed by Cons:
+
+ % cons -S md5::debug hello
+ sig::md5::srcsig(hello.c)
+ => |52d891204c62fe93ecb95281e1571938|
+ sig::md5::collect(52d891204c62fe93ecb95281e1571938)
+ => |fb0660af4002c40461a2f01fbb5ffd03|
+ sig::md5::collect(52d891204c62fe93ecb95281e1571938,
+ fb0660af4002c40461a2f01fbb5ffd03,
+ cc -c %< -o %>)
+ => |f7128da6c3fe3c377dc22ade70647b39|
+ sig::md5::current(||
+ eq |f7128da6c3fe3c377dc22ade70647b39|)
+ cc -c hello.c -o hello.o
+ sig::md5::collect()
+ => |d41d8cd98f00b204e9800998ecf8427e|
+ sig::md5::collect(f7128da6c3fe3c377dc22ade70647b39,
+ d41d8cd98f00b204e9800998ecf8427e,
+ cc -o %> %< )
+ => |a0bdce7fd09e0350e7efbbdb043a00b0|
+ sig::md5::current(||
+ eq |a0bdce7fd09e0350e7efbbdb043a00b0|)
+ cc -o hello, hello.o
+
+
+=head1 Code Repositories
+
+Many software development organizations will have one or more central
+repository directory trees containing the current source code for one or
+more projects, as well as the derived object files, libraries, and
+executables. In order to reduce unnecessary recompilation, it is useful to
+use files from the repository to build development software--assuming, of
+course, that no newer dependency file exists in the local build tree.
+
+
+=head2 Repository
+
+Cons provides a mechanism to specify a list of code repositories that will
+be searched, in-order, for source files and derived files not found in the
+local build directory tree.
+
+The following lines in a F<Construct> file will instruct Cons to look first
+under the F</usr/experiment/repository> directory and then under the
+F</usr/product/repository> directory:
+
+ Repository qw (
+ /usr/experiment/repository
+ /usr/product/repository
+ );
+
+The repository directories specified may contain source files, derived files
+(objects, libraries and executables), or both. If there is no local file
+(source or derived) under the directory in which Cons is executed, then the
+first copy of a same-named file found under a repository directory will be
+used to build any local derived files.
+
+Cons maintains one global list of repositories directories. Cons will
+eliminate the current directory, and any non-existent directories, from the
+list.
+
+
+=head2 Finding the Construct file in a Repository
+
+Cons will also search for F<Construct> and F<Conscript> files in the
+repository tree or trees. This leads to a chicken-and-egg situation,
+though: how do you look in a repository tree for a F<Construct> file if the
+F<Construct> file tells you where the repository is? To get around this,
+repositories may be specified via C<-R> options on the command line:
+
+ % cons -R /usr/experiment/repository -R /usr/product/repository .
+
+Any repository directories specified in the F<Construct> or F<Conscript>
+files will be appended to the repository directories specified by
+command-line C<-R> options.
+
+=head2 Repository source files
+
+If the source code (include the F<Conscript> file) for the library version
+of the I<Hello, World!> C application is in a repository (with no derived
+files), Cons will use the repository source files to create the local object
+files and executable file:
+
+ % cons -R /usr/src_only/repository hello
+ gcc -c /usr/src_only/repository/hello.c -o hello.o
+ gcc -c /usr/src_only/repository/world.c -o world.o
+ ar r libworld.a world.o
+ ar: creating libworld.a
+ ranlib libworld.a
+ gcc -o hello hello.o libworld.a
+
+Creating a local source file will cause Cons to rebuild the appropriate
+derived file or files:
+
+ % pico world.c
+ [EDIT]
+ % cons -R /usr/src_only/repository hello
+ gcc -c world.c -o world.o
+ ar r libworld.a world.o
+ ar: creating libworld.a
+ ranlib libworld.a
+ gcc -o hello hello.o libworld.a
+
+And removing the local source file will cause Cons to revert back to
+building the derived files from the repository source:
+
+ % rm world.c
+ % cons -R /usr/src_only/repository hello
+ gcc -c /usr/src_only/repository/world.c -o world.o
+ ar r libworld.a world.o
+ ar: creating libworld.a
+ ranlib libworld.a
+ gcc -o hello hello.o libworld.a
+
+
+=head2 Repository derived files
+
+If a repository tree contains derived files (usually object files,
+libraries, or executables), Cons will perform its normal signature
+calculation to decide whether the repository file is up-to-date or a derived
+file must be built locally. This means that, in order to ensure correct
+signature calculation, a repository tree must also contain the F<.consign>
+files that were created by Cons when generating the derived files.
+
+This would usually be accomplished by building the software in the
+repository (or, alternatively, in a build directory, and then copying the
+result to the repository):
+
+ % cd /usr/all/repository
+ % cons hello
+ gcc -c hello.c -o hello.o
+ gcc -c world.c -o world.o
+ ar r libworld.a world.o
+ ar: creating libworld.a
+ ranlib libworld.a
+ gcc -o hello hello.o libworld.a
+
+(This is safe even if the F<Construct> file lists the F</usr/all/repository>
+directory in a C<Repository> command because Cons will remove the current
+directory from the repository list.)
+
+Now if we want to build a copy of the application with our own F<hello.c>
+file, we only need to create the one necessary source file, and use the
+C<-R> option to have Cons use other files from the repository:
+
+ % mkdir $HOME/build1
+ % cd $HOME/build1
+ % ed hello.c
+ [EDIT]
+ % cons -R /usr/all/repository hello
+ gcc -c hello.c -o hello.o
+ gcc -o hello hello.o /usr/all/repository/libworld.a
+
+Notice that Cons has not bothered to recreate a local F<libworld.a> library
+(or recompile the F<world.o> module), but instead uses the already-compiled
+version from the repository.
+
+Because the MD5 signatures that Cons puts in the F<.consign> file contain
+timestamps for the derived files, the signature timestamps must match the
+file timestamps for a signature to be considered valid.
+
+Some software systems may alter the timestamps on repository files (by
+copying them, e.g.), in which case Cons will, by default, assume the
+repository signatures are invalid and rebuild files unnecessarily. This
+behavior may be altered by specifying:
+
+ Repository_Sig_Times_OK 0;
+
+This tells Cons to ignore timestamps when deciding whether a signature is
+valid. (Note that avoiding this sanity check means there must be proper
+control over the repository tree to ensure that the derived files cannot be
+modified without updating the F<.consign> signature.)
+
+
+=head2 Local copies of files
+
+If the repository tree contains the complete results of a build, and we try
+to build from the repository without any files in our local tree, something
+moderately surprising happens:
+
+ % mkdir $HOME/build2
+ % cd $HOME/build2
+ % cons -R /usr/all/repository hello
+ cons: "hello" is up-to-date.
+
+Why does Cons say that the F<hello> program is up-to-date when there is no
+F<hello> program in the local build directory? Because the repository (not
+the local directory) contains the up-to-date F<hello> program, and Cons
+correctly determines that nothing needs to be done to rebuild this
+up-to-date copy of the file.
+
+There are, however, many times in which it is appropriate to ensure that a
+local copy of a file always exists. A packaging or testing script, for
+example, may assume that certain generated files exist locally. Instead of
+making these subsidiary scripts aware of the repository directory, the
+C<Local> command may be added to a F<Construct> or F<Conscript> file to
+specify that a certain file or files must appear in the local build
+directory:
+
+ Local qw(
+ hello
+ );
+
+Then, if we re-run the same command, Cons will make a local copy of the
+program from the repository copy (telling you that it is doing so):
+
+ % cons -R /usr/all/repository hello
+ Local copy of hello from /usr/all/repository/hello
+ cons: "hello" is up-to-date.
+
+Notice that, because the act of making the local copy is not considered a
+"build" of the F<hello> file, Cons still reports that it is up-to-date.
+
+Creating local copies is most useful for files that are being installed into
+an intermediate directory (for sharing with other directories) via the
+C<Install> command. Accompanying the C<Install> command for a file with a
+companion C<Local> command is so common that Cons provides a
+C<Install_Local> command as a convenient way to do both:
+
+ Install_Local $env, '#export', 'hello';
+
+is exactly equivalent to:
+
+ Install $env '#export', 'hello';
+ Local '#export/hello';
+
+Both the C<Local> and C<Install_Local> commands update the local F<.consign>
+file with the appropriate file signatures, so that future builds are
+performed correctly.
+
+
+=head2 Repository dependency analysis
+
+Due to its built-in scanning, Cons will search the specified repository
+trees for included F<.h> files. Unless the compiler also knows about the
+repository trees, though, it will be unable to find F<.h> files that only
+exist in a repository. If, for example, the F<hello.c> file includes the
+F<hello.h> file in its current directory:
+
+ % cons -R /usr/all/repository hello
+ gcc -c /usr/all/repository/hello.c -o hello.o
+ /usr/all/repository/hello.c:1: hello.h: No such file or directory
+
+Solving this problem forces some requirements onto the way construction
+environments are defined and onto the way the C C<#include> preprocessor
+directive is used to include files.
+
+In order to inform the compiler about the repository trees, Cons will add
+appropriate C<-I> flags to the compilation commands. This means that the
+C<CPPPATH> variable in the construction environment must explicitly specify
+all subdirectories which are to be searched for included files, including the
+current directory. Consequently, we can fix the above example by changing
+the environment creation in the F<Construct> file as follows:
+
+ $env = new cons(
+ CC => 'gcc',
+ CPPPATH => '.',
+ LIBS => 'libworld.a',
+ );
+
+Due to the definition of the C<CPPPATH> variable, this yields, when we
+re-execute the command:
+
+ % cons -R /usr/all/repository hello
+ gcc -c -I. -I/usr/all/repository /usr/all/repository/hello.c -o hello.o
+ gcc -o hello hello.o /usr/all/repository/libworld.a
+
+The order of the C<-I> flags replicates, for the C preprocessor, the same
+repository-directory search path that Cons uses for its own dependency
+analysis. If there are multiple repositories and multiple C<CPPPATH>
+directories, Cons will append the repository directories to the beginning of
+each C<CPPPATH> directory, rapidly multiplying the number of C<-I> flags.
+As an extreme example, a F<Construct> file containing:
+
+ Repository qw(
+ /u1
+ /u2
+ );
+
+ $env = new cons(
+ CPPPATH => 'a:b:c',
+ );
+
+Would yield a compilation command of:
+
+ cc -Ia -I/u1/a -I/u2/a -Ib -I/u1/b -I/u2/b -Ic -I/u1/c -I/u2/c -c hello.c -o hello.o
+
+In order to shorten the command lines as much as possible, Cons will
+remove C<-I> flags for any directories, locally or in the repositories,
+which do not actually exist. (Note that the C<-I> flags are not included
+in the MD5 signature calculation for the target file, so the target will
+not be recompiled if the compilation command changes due to a directory
+coming into existence.)
+
+Because Cons relies on the compiler's C<-I> flags to communicate the
+order in which repository directories must be searched, Cons' handling
+of repository directories is fundamentally incompatible with using
+double-quotes on the C<#include> directives in any C source code that
+you plan to modify:
+
+ #include "file.h" /* DON'T USE DOUBLE-QUOTES LIKE THIS */
+
+This is because most C preprocessors, when faced with such a directive, will
+always first search the directory containing the source file. This
+undermines the elaborate C<-I> options that Cons constructs to make the
+preprocessor conform to its preferred search path.
+
+Consequently, when using repository trees in Cons, B<always> use
+angle-brackets for included files in any C source (.c or .h) files that
+you plan to modify locally:
+
+ #include <file.h> /* USE ANGLE-BRACKETS INSTEAD */
+
+Code that will not change can still safely use double quotes on #include
+lines.
+
+
+=head2 Repository_List
+
+Cons provides a C<Repository_List> command to return a list of all
+repository directories in their current search order. This can be used for
+debugging, or to do more complex Perl stuff:
+
+ @list = Repository_List;
+ print join(' ', @list), "\n";
+
+
+=head2 Repository interaction with other Cons features
+
+Cons' handling of repository trees interacts correctly with other Cons
+features--which is to say, it generally does what you would expect.
+
+Most notably, repository trees interact correctly, and rather powerfully,
+with the 'Link' command. A repository tree may contain one or more
+subdirectories for version builds established via C<Link> to a source
+subdirectory. Cons will search for derived files in the appropriate build
+subdirectories under the repository tree.
+
+
+=head1 Default targets
+
+Until now, we've demonstrated invoking Cons with an explicit target
+to build:
+
+ % cons hello
+
+Normally, Cons does not build anything unless a target is specified,
+but specifying '.' (the current directory) will build everything:
+
+ % cons # does not build anything
+
+ % cons . # builds everything under the top-level directory
+
+Adding the C<Default> method to any F<Construct> or F<Conscript> file will add
+the specified targets to a list of default targets. Cons will build
+these defaults if there are no targets specified on the command line.
+So adding the following line to the top-level F<Construct> file will mimic
+Make's typical behavior of building everything by default:
+
+ Default '.';
+
+The following would add the F<hello> and F<goodbye> commands (in the
+same directory as the F<Construct> or F<Conscript> file) to the default list:
+
+ Default qw(
+ hello
+ goodbye
+ );
+
+The C<Default> method may be used more than once to add targets to the
+default list.
+
+=head1 Selective builds
+
+Cons provides two methods for reducing the size of given build. The first is
+by specifying targets on the command line, and the second is a method for
+pruning the build tree. We'll consider target specification first.
+
+
+=head2 Selective targeting
+
+Like make, Cons allows the specification of ``targets'' on the command
+line. Cons targets may be either files or directories. When a directory is
+specified, this is simply a short-hand notation for every derivable
+product--that Cons knows about--in the specified directory and below. For
+example:
+
+ % cons build/hello/hello.o
+
+means build F<hello.o> and everything that F<hello.o> might need. This is
+from a previous version of the B<Hello, World!> program in which F<hello.o>
+depended upon F<export/include/world.h>. If that file is not up-to-date
+(because someone modified F<src/world/world.h)>, then it will be rebuilt,
+even though it is in a directory remote from F<build/hello>.
+
+In this example:
+
+ % cons build
+
+Everything in the F<build> directory is built, if necessary. Again, this may
+cause more files to be built. In particular, both F<export/include/world.h>
+and F<export/lib/libworld.a> are required by the F<build/hello> directory,
+and so they will be built if they are out-of-date.
+
+If we do, instead:
+
+ % cons export
+
+then only the files that should be installed in the export directory will be
+rebuilt, if necessary, and then installed there. Note that C<cons build>
+might build files that C<cons export> doesn't build, and vice-versa.
+
+
+=head2 No ``special'' targets
+
+With Cons, make-style ``special'' targets are not required. The simplest
+analog with Cons is to use special F<export> directories, instead. Let's
+suppose, for example, that you have a whole series of unit tests that are
+associated with your code. The tests live in the source directory near the
+code. Normally, however, you don't want to build these tests. One solution
+is to provide all the build instructions for creating the tests, and then to
+install the tests into a separate part of the tree. If we install the tests
+in a top-level directory called F<tests>, then:
+
+ % cons tests
+
+will build all the tests.
+
+ % cons export
+
+will build the production version of the system (but not the tests), and:
+
+ % cons build
+
+should probably be avoided (since it will compile tests unnecessarily).
+
+If you want to build just a single test, then you could explicitly name the
+test (in either the F<tests> directory or the F<build> directory). You could
+also aggregate the tests into a convenient hierarchy within the tests
+directory. This hierarchy need not necessarily match the source hierarchy,
+in much the same manner that the include hierarchy probably doesn't match
+the source hierarchy (the include hierarchy is unlikely to be more than two
+levels deep, for C programs).
+
+If you want to build absolutely everything in the tree (subject to whatever
+options you select), you can use:
+
+ % cons .
+
+This is not particularly efficient, since it will redundantly walk all the
+trees, including the source tree. The source tree, of course, may have
+buildable objects in it--nothing stops you from doing this, even if you
+normally build in a separate build tree.
+
+
+=head1 Build Pruning
+
+In conjunction with target selection, B<build pruning> can be used to reduce
+the scope of the build. In the previous peAcH and baNaNa example, we have
+already seen how script-driven build pruning can be used to make only half
+of the potential build available for any given invocation of C<cons>. Cons
+also provides, as a convenience, a command line convention that allows you
+to specify which F<Conscript> files actually get ``built''--that is,
+incorporated into the build tree. For example:
+
+ % cons build +world
+
+The C<+> argument introduces a Perl regular expression. This must, of
+course, be quoted at the shell level if there are any shell meta-characters
+within the expression. The expression is matched against each F<Conscript>
+file which has been mentioned in a C<Build> statement, and only those
+scripts with matching names are actually incorporated into the build
+tree. Multiple such arguments are allowed, in which case a match against any
+of them is sufficient to cause a script to be included.
+
+In the example, above, the F<hello> program will not be built, since Cons
+will have no knowledge of the script F<hello/Conscript>. The F<libworld.a>
+archive will be built, however, if need be.
+
+There are a couple of uses for build pruning via the command line. Perhaps
+the most useful is the ability to make local changes, and then, with
+sufficient knowledge of the consequences of those changes, restrict the size
+of the build tree in order to speed up the rebuild time. A second use for
+build pruning is to actively prevent the recompilation of certain files that
+you know will recompile due to, for example, a modified header file. You may
+know that either the changes to the header file are immaterial, or that the
+changes may be safely ignored for most of the tree, for testing
+purposes.With Cons, the view is that it is pragmatic to admit this type of
+behavior, with the understanding that on the next full build everything that
+needs to be rebuilt will be. There is no equivalent to a ``make touch''
+command, to mark files as permanently up-to-date. So any risk that is
+incurred by build pruning is mitigated. For release quality work, obviously,
+we recommend that you do not use build pruning (it's perfectly OK to use
+during integration, however, for checking compilation, etc. Just be sure to
+do an unconstrained build before committing the integration).
+
+
+=head1 Temporary overrides
+
+Cons provides a very simple mechanism for overriding aspects of a build. The
+essence is that you write an override file containing one or more
+C<Override> commands, and you specify this on the command line, when you run
+C<cons>:
+
+ % cons -o over export
+
+will build the F<export> directory, with all derived files subject to the
+overrides present in the F<over> file. If you leave out the C<-o> option,
+then everything necessary to remove all overrides will be rebuilt.
+
+
+=head2 Overriding environment variables
+
+The override file can contain two types of overrides. The first is incoming
+environment variables. These are normally accessible by the F<Construct>
+file from the C<%ENV> hash variable. These can trivially be overridden in
+the override file by setting the appropriate elements of C<%ENV> (these
+could also be overridden in the user's environment, of course).
+
+
+=head2 The Override command
+
+The second type of override is accomplished with the C<Override> command,
+which looks like this:
+
+ Override <regexp>, <var1> => <value1>, <var2> => <value2>, ...;
+
+The regular expression I<regexp> is matched against every derived file that
+is a candidate for the build. If the derived file matches, then the
+variable/value pairs are used to override the values in the construction
+environment associated with the derived file.
+
+Let's suppose that we have a construction environment like this:
+
+ $CONS = new cons(
+ COPT => '',
+ CDBG => '-g',
+ CFLAGS => '%COPT %CDBG',
+ );
+
+Then if we have an override file F<over> containing this command:
+
+ Override '\.o$', COPT => '-O', CDBG => '';
+
+then any C<cons> invocation with C<-o over> that creates F<.o> files via
+this environment will cause them to be compiled with C<-O >and no C<-g>. The
+override could, of course, be restricted to a single directory by the
+appropriate selection of a regular expression.
+
+Here's the original version of the Hello, World! program, built with this
+environment. Note that Cons rebuilds the appropriate pieces when the
+override is applied or removed:
+
+ % cons hello
+ cc -g -c hello.c -o hello.o
+ cc -o hello hello.o
+ % cons -o over hello
+ cc -O -c hello.c -o hello.o
+ cc -o hello hello.o
+ % cons -o over hello
+ cons: "hello" is up-to-date.
+ % cons hello
+ cc -g -c hello.c -o hello.o
+ cc -o hello hello.o
+
+It's important that the C<Override> command only be used for temporary,
+on-the-fly overrides necessary for development because the overrides are not
+platform independent and because they rely too much on intimate knowledge of
+the workings of the scripts. For temporary use, however, they are exactly
+what you want.
+
+Note that it is still useful to provide, say, the ability to create a fully
+optimized version of a system for production use--from the F<Construct> and
+F<Conscript> files. This way you can tailor the optimized system to the
+platform. Where optimizer trade-offs need to be made (particular files may
+not be compiled with full optimization, for example), then these can be
+recorded for posterity (and reproducibility) directly in the scripts.
+
+
+=head1 More on construction environments
+
+As previously mentioned, a B<construction environment> is an object that
+has a set of keyword/value pairs and a set of methods, and which is used
+to tell Cons how target files should be built. This section describes
+how Cons uses and expands construction environment values to control its
+build behavior.
+
+=head2 Construction variable expansion
+
+Construction variables from a construction environment are expanded
+by preceding the keyword with a C<%> (percent sign):
+
+ Construction variables:
+ XYZZY => 'abracadabra',
+
+ The string: "The magic word is: %XYZZY!"
+ expands to: "The magic word is: abracadabra!"
+
+A construction variable name may be surrounded by C<{> and C<}> (curly
+braces), which are stripped as part of the expansion. This can
+sometimes be necessary to separate a variable expansion from trailing
+alphanumeric characters:
+
+ Construction variables:
+ OPT => 'value1',
+ OPTION => 'value2',
+
+ The string: "%OPT %{OPT}ION %OPTION %{OPTION}"
+ expands to: "value1 value1ION value2 value2"
+
+Construction variable expansion is recursive--that is, a string
+containing C<%->expansions after substitution will be re-expanded until
+no further substitutions can be made:
+
+ Construction variables:
+ STRING => 'The result is: %FOO',
+ FOO => '%BAR',
+ BAR => 'final value',
+
+ The string: "The string says: %STRING"
+ expands to: "The string says: The result is: final value"
+
+If a construction variable is not defined in an environment, then the
+null string is substituted:
+
+ Construction variables:
+ FOO => 'value1',
+ BAR => 'value2',
+
+ The string: "%FOO <%NO_VARIABLE> %BAR"
+ expands to: "value1 <> value2"
+
+A doubled C<%%> will be replaced by a single C<%>:
+
+ The string: "Here is a percent sign: %%"
+ expands to: "Here is a percent sign: %"
+
+=head2 Default construction variables
+
+When you specify no arguments when creating a new construction
+environment:
+
+ $env = new cons();
+
+Cons creates a reference to a new, default construction
+environment. This contains a number of construction variables and some
+methods. At the present writing, the default construction variables on a
+UNIX system are:
+
+ CC => 'cc',
+ CFLAGS => '',
+ CCCOM => '%CC %CFLAGS %_IFLAGS -c %< -o %>',
+ CXX => '%CC',
+ CXXFLAGS => '%CFLAGS',
+ CXXCOM => '%CXX %CXXFLAGS %_IFLAGS -c %< -o %>',
+ INCDIRPREFIX => '-I',
+ INCDIRSUFFIX => '',
+ LINK => '%CXX',
+ LINKCOM => '%LINK %LDFLAGS -o %> %< %_LDIRS %LIBS',
+ LINKMODULECOM => '%LD -r -o %> %<',
+ LIBDIRPREFIX => '-L',
+ LIBDIRSUFFIX => '',
+ AR => 'ar',
+ ARFLAGS => 'r',
+ ARCOM => ['%AR %ARFLAGS %> %<', '%RANLIB %>'],
+ RANLIB => 'ranlib',
+ AS => 'as',
+ ASFLAGS => '',
+ ASCOM => '%AS %ASFLAGS %< -o %>',
+ LD => 'ld',
+ LDFLAGS => '',
+ PREFLIB => 'lib',
+ SUFLIB => '.a',
+ SUFLIBS => '.so:.a',
+ SUFOBJ => '.o',
+ SIGNATURE => [ '*' => 'build' ],
+ ENV => { 'PATH' => '/bin:/usr/bin' },
+
+
+And on a Win32 system (Windows NT), the default construction variables
+are (unless the default rule style is set using the B<DefaultRules>
+method):
+
+ CC => 'cl',
+ CFLAGS => '/nologo',
+ CCCOM => '%CC %CFLAGS %_IFLAGS /c %< /Fo%>',
+ CXXCOM => '%CXX %CXXFLAGS %_IFLAGS /c %< /Fo%>',
+ INCDIRPREFIX => '/I',
+ INCDIRSUFFIX => '',
+ LINK => 'link',
+ LINKCOM => '%LINK %LDFLAGS /out:%> %< %_LDIRS %LIBS',
+ LINKMODULECOM => '%LD /r /o %> %<',
+ LIBDIRPREFIX => '/LIBPATH:',
+ LIBDIRSUFFIX => '',
+ AR => 'lib',
+ ARFLAGS => '/nologo ',
+ ARCOM => "%AR %ARFLAGS /out:%> %<",
+ RANLIB => '',
+ LD => 'link',
+ LDFLAGS => '/nologo ',
+ PREFLIB => '',
+ SUFEXE => '.exe',
+ SUFLIB => '.lib',
+ SUFLIBS => '.dll:.lib',
+ SUFOBJ => '.obj',
+ SIGNATURE => [ '*' => 'build' ],
+
+These variables are used by the various methods associated with the
+environment. In particular, any method that ultimately invokes an external
+command will substitute these variables into the final command, as
+appropriate. For example, the C<Objects> method takes a number of source
+files and arranges to derive, if necessary, the corresponding object
+files:
+
+ Objects $env 'foo.c', 'bar.c';
+
+This will arrange to produce, if necessary, F<foo.o> and F<bar.o>. The
+command invoked is simply C<%CCCOM>, which expands, through substitution,
+to the appropriate external command required to build each object. The
+substitution rules will be discussed in detail in the next section.
+
+The construction variables are also used for other purposes. For example,
+C<CPPPATH> is used to specify a colon-separated path of include
+directories. These are intended to be passed to the C preprocessor and are
+also used by the C-file scanning machinery to determine the dependencies
+involved in a C Compilation.
+
+Variables beginning with underscore are created by various methods,
+and should normally be considered ``internal'' variables. For example,
+when a method is called which calls for the creation of an object from
+a C source, the variable C<_IFLAGS> is created: this corresponds to the
+C<-I> switches required by the C compiler to represent the directories
+specified by C<CPPPATH>.
+
+Note that, for any particular environment, the value of a variable is set
+once, and then never reset (to change a variable, you must create a new
+environment. Methods are provided for copying existing environments for this
+purpose). Some internal variables, such as C<_IFLAGS> are created on demand,
+but once set, they remain fixed for the life of the environment.
+
+The C<CFLAGS>, C<LDFLAGS>, and C<ARFLAGS> variables all supply a place
+for passing options to the compiler, loader, and archiver, respectively.
+
+The C<INCDIRPREFIX> and C<INCDIRSUFFIX> variables specify option
+strings to be appended to the beginning and end, respectively, of each
+include directory so that the compiler knows where to find F<.h> files.
+Similarly, the C<LIBDIRPREFIX> and C<LIBDIRSUFFIX> variables specify the
+option string to be appended to the beginning of and end, respectively,
+of each directory that the linker should search for libraries.
+
+Another variable, C<ENV>, is used to determine the system environment during
+the execution of an external command. By default, the only environment
+variable that is set is C<PATH>, which is the execution path for a UNIX
+command. For the utmost reproducibility, you should really arrange to set
+your own execution path, in your top-level F<Construct> file (or perhaps by
+importing an appropriate construction package with the Perl C<use>
+command). The default variables are intended to get you off the ground.
+
+=head2 Expanding variables in construction commands
+
+Within a construction command, construction variables will be expanded
+according to the rules described above. In addition to normal variable
+expansion from the construction environment, construction commands also
+expand the following pseudo-variables to insert the specific input and
+output files in the command line that will be executed:
+
+=over 10
+
+=item %>
+
+The target file name. In a multi-target command, this expands to the
+first target mentioned.)
+
+=item %0
+
+Same as C<%E<gt>>.
+
+=item %1, %2, ..., %9
+
+These refer to the first through ninth input file, respectively.
+
+=item %E<lt>
+
+The full set of input file names. If any of these have been used
+anywhere else in the current command line (via C<%1>, C<%2>, etc.), then
+those will be deleted from the list provided by C<%E<lt>>. Consider the
+following command found in a F<Conscript> file in the F<test> directory:
+
+ Command $env 'tgt', qw(foo bar baz), qq(
+ echo %< -i %1 > %>
+ echo %< -i %2 >> %>
+ echo %< -i %3 >> %>
+ );
+
+If F<tgt> needed to be updated, then this would result in the execution of
+the following commands, assuming that no remapping has been established for
+the F<test> directory:
+
+ echo test/bar test/baz -i test/foo > test/tgt
+ echo test/foo test/baz -i test/bar >> test/tgt
+ echo test/foo test/bar -i test/baz >> test/tgt
+
+=back
+
+Any of the above pseudo-variables may be followed immediately by one of
+the following suffixes to select a portion of the expanded path name:
+
+ :a the absolute path to the file name
+ :b the directory plus the file name stripped of any suffix
+ :d the directory
+ :f the file name
+ :s the file name suffix
+ :F the file name stripped of any suffix
+ :S the absolute path path to a Linked source file
+
+Continuing with the above example, C<%E<lt>:f> would expand to C<foo bar baz>,
+and C<%E<gt>:d> would expand to C<test>.
+
+There are additional C<%> elements which affect the command line(s):
+
+=over 10
+
+=item %[ %]
+
+It is possible to programmatically rewrite part of the command by
+enclosing part of it between C<%[> and C<%]>. This will call the
+construction variable named as the first word enclosed in the brackets
+as a Perl code reference; the results of this call will be used to
+replace the contents of the brackets in the command line. For example,
+given an existing input file named F<tgt.in>:
+
+ @keywords = qw(foo bar baz);
+ $env = new cons(X_COMMA => sub { join(",", @_) });
+ Command $env 'tgt', 'tgt.in', qq(
+ echo '# Keywords: %[X_COMMA @keywords %]' > %>
+ cat %< >> %>
+ );
+
+This will execute:
+
+ echo '# Keywords: foo,bar,baz' > tgt
+ cat tgt.in >> tgt
+
+=item %( %)
+
+Cons includes the text of the command line in the MD5 signature for a
+build, so that targets get rebuilt if you change the command line (to
+add or remove an option, for example). Command-line text in between
+C<%(> and C<%)>, however, will be ignored for MD5 signature calculation.
+
+Internally, Cons uses C<%(> and C<%)> around include and library
+directory options (C<-I> and C<-L> on UNIX systems, C</I> and
+C</LIBPATH> on Windows NT) to avoid rebuilds just because the directory
+list changes. Rebuilds occur only if the changed directory list causes
+any included I<files> to change, and a changed include file is detected
+by the MD5 signature calculation on the actual file contents.
+
+=back
+
+=head2 Expanding construction variables in file names
+
+Cons expands construction variables in the source and target file names
+passed to the various construction methods according to the expansion
+rules described above:
+
+ $env = new cons(
+ DESTDIR => 'programs',
+ SRCDIR => 'src',
+ );
+ Program $env '%DESTDIR/hello', '%SRCDIR/hello.c';
+
+This allows for flexible configuration, through the construction
+environment, of directory names, suffixes, etc.
+
+
+=head1 Build actions
+
+Cons supports several types of B<build actions> that can be performed
+to construct one or more target files. Usually, a build action is
+a construction command--that is, a command-line string that invokes
+an external command. Cons can also execute Perl code embedded in a
+command-line string, and even supports an experimental ability to build
+a target file by executing a Perl code reference directly.
+
+A build action is usually specified as the value of a construction
+variable:
+
+ $env = new cons(
+ CCCOM => '%CC %CFLAGS %_IFLAGS -c %< -o %>',
+ LINKCOM => '[perl] &link_executable("%>", "%<")',
+ ARCOM => sub { my($env, $target, @sources) = @_;
+ # code to create an archive
+ }
+ );
+
+A build action may be associated directly with one or more target files
+via the C<Command> method; see below.
+
+=head2 Construction commands
+
+A construction command goes through expansion of construction variables
+and C<%-> pseudo-variables, as described above, to create the actual
+command line that Cons will execute to generate the target file or
+files.
+
+After substitution occurs, strings of white space are converted into
+single blanks, and leading and trailing white space is eliminated. It
+is therefore currently not possible to introduce variable length white
+space in strings passed into a command.
+
+If a multi-line command string is provided, the commands are executed
+sequentially. If any of the commands fails, then none of the rest are
+executed, and the target is not marked as updated, i.e. a new signature is
+not stored for the target.
+
+Normally, if all the commands succeed, and return a zero status (or whatever
+platform-specific indication of success is required), then a new signature
+is stored for the target. If a command erroneously reports success even
+after a failure, then Cons will assume that the target file created by that
+command is accurate and up-to-date.
+
+The first word of each command string, after expansion, is assumed to be an
+executable command looked up on the C<PATH> environment variable (which is,
+in turn, specified by the C<ENV> construction variable). If this command is
+found on the path, then the target will depend upon it: the command will
+therefore be automatically built, as necessary. It's possible to write
+multi-part commands to some shells, separated by semi-colons. Only the first
+command word will be depended upon, however, so if you write your command
+strings this way, you must either explicitly set up a dependency (with the
+C<Depends> method), or be sure that the command you are using is a system
+command which is expected to be available. If it isn't available, you will,
+of course, get an error.
+
+Cons normally prints a command before executing it. This behavior is
+suppressed if the first character of the command is C<@>. Note that
+you may need to separate the C<@> from the command name or escape it to
+prevent C<@cmd> from looking like an array to Perl quote operators that
+perform interpolation:
+
+ # The first command line is incorrect,
+ # because "@cp" looks like an array
+ # to the Perl qq// function.
+ # Use the second form instead.
+ Command $env 'foo', 'foo.in', qq(
+ @cp %< tempfile
+ @ cp tempfile %>
+ );
+
+If there are shell meta characters anywhere in the expanded command line,
+such as C<E<lt>>, C<E<gt>>, quotes, or semi-colon, then the command
+will actually be executed by invoking a shell. This means that a command
+such as:
+
+ cd foo
+
+alone will typically fail, since there is no command C<cd> on the path. But
+the command string:
+
+ cd $<:d; tar cf $>:f $<:f
+
+when expanded will still contain the shell meta character semi-colon, and a
+shell will be invoked to interpret the command. Since C<cd> is interpreted
+by this sub-shell, the command will execute as expected.
+
+=head2 Perl expressions
+
+If any command (even one within a multi-line command) begins with
+C<[perl]>, the remainder of that command line will be evaluated by the
+running Perl instead of being forked by the shell. If an error occurs
+in parsing the Perl code, or if the Perl expression returns 0 or undef,
+the command will be considered to have failed. For example, here is a
+simple command which creates a file C<foo> directly from Perl:
+
+ $env = new cons();
+ Command $env 'foo',
+ qq([perl] open(FOO,'>foo');print FOO "hi\\n"; close(FOO); 1);
+
+Note that when the command is executed, you are in the same package as
+when the F<Construct> or F<Conscript> file was read, so you can call
+Perl functions you've defined in the same F<Construct> or F<Conscript>
+file in which the C<Command> appears:
+
+ $env = new cons();
+ sub create_file {
+ my $file = shift;
+ open(FILE, ">$file");
+ print FILE "hi\n";
+ close(FILE);
+ return 1;
+ }
+ Command $env 'foo', "[perl] &create_file('%>')";
+
+The Perl string will be used to generate the signature for the derived
+file, so if you change the string, the file will be rebuilt. The contents
+of any subroutines you call, however, are not part of the signature,
+so if you modify a called subroutine such as C<create_file> above,
+the target will I<not> be rebuilt. Caveat user.
+
+=head2 Perl code references [EXPERIMENTAL]
+
+Cons supports the ability to create a derived file by directly executing
+a Perl code reference. This feature is considered EXPERIMENTAL and
+subject to change in the future.
+
+A code reference may either be a named subroutine referenced by the
+usual C<\&> syntax:
+
+ sub build_output {
+ my($env, $target, @sources) = @_;
+ print "build_output building $target\n";
+ open(OUT, ">$target");
+ foreach $src (@sources) {
+ if (! open(IN, "<$src")) {
+ print STDERR "cannot open '$src': $!\n";
+ return undef;
+ }
+ print OUT, <IN>;
+ }
+ close(OUT);
+ return 1;
+ }
+ Command $env 'output', \&build_output;
+
+or the code reference may be an anonymous subroutine:
+
+ Command $env 'output', sub {
+ my($env, $target, @sources) = @_;
+ print "building $target\n";
+ open(FILE, ">$target");
+ print FILE "hello\n";
+ close(FILE);
+ return 1;
+ };
+
+To build the target file, the referenced subroutine is passed, in order:
+the construction environment used to generate the target; the path
+name of the target itself; and the path names of all the source files
+necessary to build the target file.
+
+The code reference is expected to generate the target file, of course,
+but may manipulate the source and target files in any way it chooses.
+The code reference must return a false value (C<undef> or C<0>) if
+the build of the file failed. Any true value indicates a successful
+build of the target.
+
+Building target files using code references is considered EXPERIMENTAL
+due to the following current limitations:
+
+=over 4
+
+Cons does I<not> print anything to indicate the code reference is being
+called to build the file. The only way to give the user any indication
+is to have the code reference explicitly print some sort of "building"
+message, as in the above examples.
+
+Cons does not generate any signatures for code references, so if the
+code in the reference changes, the target will I<not> be rebuilt.
+
+Cons has no public method to allow a code reference to extract
+construction variables. This would be good to allow generalization of
+code references based on the current construction environment, but would
+also complicate the problem of generating meaningful signatures for code
+references.
+
+=back
+
+Support for building targets via code references has been released in
+this version to encourage experimentation and the seeking of possible
+solutions to the above limitations.
+
+
+=head1 Default construction methods
+
+The list of default construction methods includes the following:
+
+
+=head2 The C<new> constructor
+
+The C<new> method is a Perl object constructor. That is, it is not invoked
+via a reference to an existing construction environment B<reference>, but,
+rather statically, using the name of the Perl B<package> where the
+constructor is defined. The method is invoked like this:
+
+ $env = new cons(<overrides>);
+
+The environment you get back is blessed into the package C<cons>, which
+means that it will have associated with it the default methods described
+below. Individual construction variables can be overridden by providing
+name/value pairs in an override list. Note that to override any command
+environment variable (i.e. anything under C<ENV>), you will have to override
+all of them. You can get around this difficulty by using the C<copy> method
+on an existing construction environment.
+
+
+=head2 The C<clone> method
+
+The C<clone> method creates a clone of an existing construction environment,
+and can be called as in the following example:
+
+ $env2 = $env1->clone(<overrides>);
+
+You can provide overrides in the usual manner to create a different
+environment from the original. If you just want a new name for the same
+environment (which may be helpful when exporting environments to existing
+components), you can just use simple assignment.
+
+
+=head2 The C<copy> method
+
+The C<copy> method extracts the externally defined construction variables
+from an environment and returns them as a list of name/value
+pairs. Overrides can also be provided, in which case, the overridden values
+will be returned, as appropriate. The returned list can be assigned to a
+hash, as shown in the prototype, below, but it can also be manipulated in
+other ways:
+
+ %env = $env1->copy(<overrides>);
+
+The value of C<ENV>, which is itself a hash, is also copied to a new hash,
+so this may be changed without fear of affecting the original
+environment. So, for example, if you really want to override just the
+C<PATH> variable in the default environment, you could do the following:
+
+ %cons = new cons()->copy();
+ $cons{ENV}{PATH} = "<your path here>";
+ $cons = new cons(%cons);
+
+This will leave anything else that might be in the default execution
+environment undisturbed.
+
+
+=head2 The C<Install> method
+
+The C<Install> method arranges for the specified files to be installed in
+the specified directory. The installation is optimized: the file is not
+copied if it can be linked. If this is not the desired behavior, you will
+need to use a different method to install the file. It is called as follows:
+
+ Install $env <directory>, <names>;
+
+Note that, while the files to be installed may be arbitrarily named,
+only the last component of each name is used for the installed target
+name. So, for example, if you arrange to install F<foo/bar> in F<baz>,
+this will create a F<bar> file in the F<baz> directory (not F<foo/bar>).
+
+
+=head2 The C<InstallAs> method
+
+The C<InstallAs> method arranges for the specified source file(s) to be
+installed as the specified target file(s). Multiple files should be
+specified as a file list. The installation is optimized: the file is not
+copied if it can be linked. If this is not the desired behavior, you will
+need to use a different method to install the file. It is called as follows:
+
+C<InstallAs> works in two ways:
+
+Single file install:
+
+ InstallAs $env TgtFile, SrcFile;
+
+Multiple file install:
+
+ InstallAs $env ['tgt1', 'tgt2'], ['src1', 'src2'];
+
+Or, even as:
+
+ @srcs = qw(src1 src2 src3);
+ @tgts = qw(tgt1 tgt2 tgt3);
+ InstallAs $env [@tgts], [@srcs];
+
+Both the target and the sources lists should be of the same length.
+
+=head2 The C<Precious> method
+
+The C<Precious> method asks cons not to delete the specified file or
+list of files before building them again. It is invoked as:
+
+ Precious <files>;
+
+This is especially useful for allowing incremental updates to libraries
+or debug information files which are updated rather than rebuilt anew each
+time. Cons will still delete the files when the C<-r> flag is specified.
+
+=head2 The C<AfterBuild> method
+
+The C<AfterBuild> method evaluates the specified perl string after
+building the given file or files (or finding that they are up to date).
+The eval will happen once per specified file. C<AfterBuild> is called
+as follows:
+
+ AfterBuild $env 'foo.o', qq(print "foo.o is up to date!\n");
+
+The perl string is evaluated in the C<script> package, and has access
+to all variables and subroutines defined in the F<Conscript> file in
+which the C<AfterBuild> method is called.
+
+=head2 The C<Command> method
+
+The C<Command> method is a catchall method which can be used to arrange for
+any build action to be executed to update the target. For this command, a
+target file and list of inputs is provided. In addition, a build action
+is specified as the last argument. The build action is typically a
+command line or lines, but may also contain Perl code to be executed;
+see the section above on build actions for details.
+
+The C<Command> method is called as follows:
+
+ Command $env <target>, <inputs>, <build action>;
+
+The target is made dependent upon the list of input files specified, and the
+inputs must be built successfully or Cons will not attempt to build the
+target.
+
+To specify a command with multiple targets, you can specify a reference to a
+list of targets. In Perl, a list reference can be created by enclosing a
+list in square brackets. Hence the following command:
+
+ Command $env ['foo.h', 'foo.c'], 'foo.template', q(
+ gen %1
+ );
+
+could be used in a case where the command C<gen> creates two files, both
+F<foo.h> and F<foo.c>.
+
+
+=head2 The C<Objects> method
+
+The C<Objects> method arranges to create the object files that correspond to
+the specified source files. It is invoked as shown below:
+
+ @files = Objects $env <source or object files>;
+
+Under Unix, source files ending in F<.s> and F<.c> are currently
+supported, and will be compiled into a name of the same file ending
+in F<.o>. By default, all files are created by invoking the external
+command which results from expanding the C<CCCOM> construction variable,
+with C<%E<lt>> and C<%E<gt>> set to the source and object files,
+respectively. (See the section above on construction variable expansion
+for details). The variable C<CPPPATH> is also used when scanning source
+files for dependencies. This is a colon separated list of pathnames, and
+is also used to create the construction variable C<_IFLAGS,> which will
+contain the appropriate list of -C<I> options for the compilation. Any
+relative pathnames in C<CPPPATH> is interpreted relative to the
+directory in which the associated construction environment was created
+(absolute and top-relative names may also be used). This variable is
+used by C<CCCOM>. The behavior of this command can be modified by
+changing any of the variables which are interpolated into C<CCCOM>, such
+as C<CC>, C<CFLAGS>, and, indirectly, C<CPPPATH>. It's also possible
+to replace the value of C<CCCOM>, itself. As a convenience, this file
+returns the list of object filenames.
+
+
+=head2 The C<Program> method
+
+The C<Program> method arranges to link the specified program with the
+specified object files. It is invoked in the following manner:
+
+ Program $env <program name>, <source or object files>;
+
+The program name will have the value of the C<SUFEXE> construction
+variable appended (by default, C<.exe> on Win32 systems, nothing on Unix
+systems) if the suffix is not already present.
+
+Source files may be specified in place of objects files--the C<Objects>
+method will be invoked to arrange the conversion of all the files into
+object files, and hence all the observations about the C<Objects> method,
+above, apply to this method also.
+
+The actual linking of the program will be handled by an external command
+which results from expanding the C<LINKCOM> construction variable, with
+C<%E<lt>> set to the object files to be linked (in the order presented),
+and C<%E<gt>> set to the target. (See the section above on construction
+variable expansion for details.) The user may set additional variables
+in the construction environment, including C<LINK>, to define which
+program to use for linking, C<LIBPATH>, a colon-separated list of
+library search paths, for use with library specifications of the form
+I<-llib>, and C<LIBS>, specifying the list of libraries to link against
+(in either I<-llib> form or just as pathnames. Relative pathnames in
+both C<LIBPATH> and C<LIBS> are interpreted relative to the directory
+in which the associated construction environment is created (absolute
+and top-relative names may also be used). Cons automatically sets up
+dependencies on any libraries mentioned in C<LIBS>: those libraries will
+be built before the command is linked.
+
+
+=head2 The C<Library> method
+
+The C<Library> method arranges to create the specified library from the
+specified object files. It is invoked as follows:
+
+ Library $env <library name>, <source or object files>;
+
+The library name will have the value of the C<SUFLIB> construction
+variable appended (by default, C<.lib> on Win32 systems, C<.a> on Unix
+systems) if the suffix is not already present.
+
+Source files may be specified in place of objects files--the C<Objects>
+method will be invoked to arrange the conversion of all the files into
+object files, and hence all the observations about the C<Objects> method,
+above, apply to this method also.
+
+The actual creation of the library will be handled by an external
+command which results from expanding the C<ARCOM> construction variable,
+with C<%E<lt>> set to the library members (in the order presented),
+and C<%E<gt>> to the library to be created. (See the section above
+on construction variable expansion for details.) The user may set
+variables in the construction environment which will affect the
+operation of the command. These include C<AR>, the archive program
+to use, C<ARFLAGS>, which can be used to modify the flags given to
+the program specified by C<AR>, and C<RANLIB>, the name of a archive
+index generation program, if needed (if the particular need does not
+require the latter functionality, then C<ARCOM> must be redefined to not
+reference C<RANLIB>).
+
+The C<Library> method allows the same library to be specified in multiple
+method invocations. All of the contributing objects from all the invocations
+(which may be from different directories) are combined and generated by a
+single archive command. Note, however, that if you prune a build so that
+only part of a library is specified, then only that part of the library will
+be generated (the rest will disappear!).
+
+
+=head2 The C<Module> method
+
+The C<Module> method is a combination of the C<Program> and C<Command>
+methods. Rather than generating an executable program directly, this command
+allows you to specify your own command to actually generate a module. The
+method is invoked as follows:
+
+ Module $env <module name>, <source or object files>, <construction command>;
+
+This command is useful in instances where you wish to create, for example,
+dynamically loaded modules, or statically linked code libraries.
+
+
+=head2 The C<Depends> method
+
+The C<Depends> method allows you to specify additional dependencies for a
+target. It is invoked as follows:
+
+ Depends $env <target>, <dependencies>;
+
+This may be occasionally useful, especially in cases where no scanner exists
+(or is writable) for particular types of files. Normally, dependencies are
+calculated automatically from a combination of the explicit dependencies set
+up by the method invocation or by scanning source files.
+
+A set of identical dependencies for multiple targets may be specified
+using a reference to a list of targets. In Perl, a list reference can
+be created by enclosing a list in square brackets. Hence the following
+command:
+
+ Depends $env ['foo', 'bar'], 'input_file_1', 'input_file_2';
+
+specifies that both the F<foo> and F<bar> files depend on the listed
+input files.
+
+
+=head2 The C<RuleSet> method
+
+The C<RuleSet> method returns the construction variables for building
+various components with one of the rule sets supported by Cons. The
+currently supported rule sets are:
+
+=over 4
+
+=item msvc
+
+Rules for the Microsoft Visual C++ compiler suite.
+
+=item unix
+
+Generic rules for most UNIX-like compiler suites.
+
+=back
+
+On systems with more than one available compiler suite, this allows you
+to easily create side-by-side environments for building software with
+multiple tools:
+
+ $msvcenv = new cons(RuleSet("msvc"));
+ $cygnusenv = new cons(RuleSet("unix"));
+
+In the future, this could also be extended to other platforms that
+have different default rule sets.
+
+
+=head2 The C<DefaultRules> method
+
+The C<DefaultRules> method sets the default construction variables that
+will be returned by the C<new> method to the specified arguments:
+
+ DefaultRules(CC => 'gcc',
+ CFLAGS => '',
+ CCCOM => '%CC %CFLAGS %_IFLAGS -c %< -o %>');
+ $env = new cons();
+ # $env now contains *only* the CC, CFLAGS,
+ # and CCCOM construction variables
+
+Combined with the C<RuleSet> method, this also provides an easy way
+to set explicitly the default build environment to use some supported
+toolset other than the Cons defaults:
+
+ # use a UNIX-like tool suite (like cygwin) on Win32
+ DefaultRules(RuleSet('unix'));
+ $env = new cons();
+
+Note that the C<DefaultRules> method completely replaces the default
+construction environment with the specified arguments, it does not
+simply override the existing defaults. To override one or more
+variables in a supported C<RuleSet>, append the variables and values:
+
+ DefaultRules(RuleSet('unix'), CFLAGS => '-O3');
+ $env1 = new cons();
+ $env2 = new cons();
+ # both $env1 and $env2 have 'unix' defaults
+ # with CFLAGS set to '-O3'
+
+
+=head2 The C<Ignore> method
+
+The C<Ignore> method allows you to ignore explicitly dependencies that
+Cons infers on its own. It is invoked as follows:
+
+ Ignore <patterns>;
+
+This can be used to avoid recompilations due to changes in system header
+files or utilities that are known to not affect the generated targets.
+
+If, for example, a program is built in an NFS-mounted directory on
+multiple systems that have different copies of F<stdio.h>, the differences
+will affect the signatures of all derived targets built from source files
+that C<#include E<lt>stdio.hE<gt>>. This will cause all those targets to
+be rebuilt when changing systems. If this is not desirable behavior, then
+the following line will remove the dependencies on the F<stdio.h> file:
+
+ Ignore '^/usr/include/stdio\.h$';
+
+Note that the arguments to the C<Ignore> method are regular expressions,
+so special characters must be escaped and you may wish to anchor the
+beginning or end of the expression with C<^> or C<$> characters.
+
+
+=head2 The C<Salt> method
+
+The C<Salt> method adds a constant value to the signature calculation
+for every derived file. It is invoked as follows:
+
+ Salt $string;
+
+Changing the Salt value will force a complete rebuild of every derived
+file. This can be used to force rebuilds in certain desired
+circumstances. For example,
+
+ Salt `uname -s`;
+
+Would force a complete rebuild of every derived file whenever the
+operating system on which the build is performed (as reported by C<uname
+-s>) changes.
+
+
+=head2 The C<UseCache> method
+
+The C<UseCache> method instructs Cons to maintain a cache of derived
+files, to be shared among separate build trees of the same project.
+
+ UseCache("cache/<buildname>") || warn("cache directory not found");
+
+
+=head2 The C<SourcePath> method
+
+The C<SourcePath> mathod returns the real source path name of a file,
+as opposed to the path name within a build directory. It is invoked
+as follows:
+
+ $path = SourcePath <buildpath>;
+
+
+=head2 The C<ConsPath> method
+
+The C<ConsPath> method returns true if the supplied path is a derivable
+file, and returns undef (false) otherwise.
+It is invoked as follows:
+
+ $result = ConsPath <path>;
+
+
+=head2 The C<SplitPath> method
+
+The C<SplitPath> method looks up multiple path names in a string separated
+by the default path separator for the operating system (':' on UNIX
+systems, ';' on Windows NT), and returns the fully-qualified names.
+It is invoked as follows:
+
+ @paths = SplitPath <pathlist>;
+
+The C<SplitPath> method will convert names prefixed '#' to the
+appropriate top-level build name (without the '#') and will convert
+relative names to top-level names.
+
+
+=head2 The C<DirPath> method
+
+The C<DirPath> method returns the build path name(s) of a directory or
+list of directories. It is invoked as follows:
+
+ $cwd = DirPath <paths>;
+
+The most common use for the C<DirPath> method is:
+
+ $cwd = DirPath '.';
+
+to fetch the path to the current directory of a subsidiary F<Conscript>
+file.
+
+
+=head2 The C<FilePath> method
+
+The C<FilePath> method returns the build path name(s) of a file or
+list of files. It is invoked as follows:
+
+ $file = FilePath <path>;
+
+
+=head2 The C<Help> method
+
+The C<Help> method specifies help text that will be displayed when the
+user invokes C<cons -h>. This can be used to provide documentation
+of specific targets, values, build options, etc. for the build tree.
+It is invoked as follows:
+
+ Help <helptext>;
+
+The C<Help> method may only be called once, and should typically be
+specified in the top-level F<Construct> file.
+
+
+=head1 Extending Cons
+
+
+=head2 Overriding construction variables
+
+There are several ways of extending Cons, which vary in degree of
+difficulty. The simplest method is to define your own construction
+environment, based on the default environment, but modified to reflect your
+particular needs. This will often suffice for C-based applications. You can
+use the C<new> constructor, and the C<clone> and C<copy> methods to create
+hybrid environments. These changes can be entirely transparent to the
+underlying F<Conscript> files.
+
+
+=head2 Adding new methods
+
+For slightly more demanding changes, you may wish to add new methods to the
+C<cons> package. Here's an example of a very simple extension,
+C<InstallScript>, which installs a tcl script in a requested location, but
+edits the script first to reflect a platform-dependent path that needs to be
+installed in the script:
+
+ # cons::InstallScript - Create a platform dependent version of a shell
+ # script by replacing string ``#!your-path-here'' with platform specific
+ # path $BIN_DIR.
+
+ sub cons::InstallScript {
+ my ($env, $dst, $src) = @_;
+ Command $env $dst, $src, qq(
+ sed s+your-path-here+$BIN_DIR+ %< > %>
+ chmod oug+x %>
+ );
+ }
+
+Notice that this method is defined directly in the C<cons> package (by
+prefixing the name with C<cons::>). A change made in this manner will be
+globally visible to all environments, and could be called as in the
+following example:
+
+ InstallScript $env "$BIN/foo", "foo.tcl";
+
+For a small improvement in generality, the C<BINDIR> variable could be
+passed in as an argument or taken from the construction environment--as
+C<%BINDIR>.
+
+
+=head2 Overriding methods
+
+Instead of adding the method to the C<cons> name space, you could define a
+new package which inherits existing methods from the C<cons> package and
+overrides or adds others. This can be done using Perl's inheritance
+mechanisms.
+
+The following example defines a new package C<cons::switch> which
+overrides the standard C<Library> method. The overridden method builds
+linked library modules, rather than library archives. A new
+constructor is provided. Environments created with this constructor
+will have the new library method; others won't.
+
+ package cons::switch;
+ BEGIN {@ISA = 'cons'}
+
+ sub new {
+ shift;
+ bless new cons(@_);
+ }
+
+ sub Library {
+ my($env) = shift;
+ my($lib) = shift;
+ my(@objs) = Objects $env @_;
+ Command $env $lib, @objs, q(
+ %LD -r %LDFLAGS %< -o %>
+ );
+ }
+
+This functionality could be invoked as in the following example:
+
+ $env = new cons::switch(@overrides);
+ ...
+ Library $env 'lib.o', 'foo.c', 'bar.c';
+
+
+=head1 Invoking Cons
+
+The C<cons> command is usually invoked from the root of the build tree. A
+F<Construct> file must exist in that directory. If the C<-f> argument is
+used, then an alternate F<Construct> file may be used (and, possibly, an
+alternate root, since C<cons> will cd to F<Construct> file's containing
+directory).
+
+If C<cons> is invoked from a child of the root of the build tree with
+the C<-t> argument, it will walk up the directory hierarchy looking for a
+F<Construct> file. (An alternate name may still be specified with C<-f>.)
+The targets supplied on the command line will be modified to be relative
+to the discovered F<Construct> file. For example, from a directory
+containing a top-level F<Construct> file, the following invocation:
+
+ % cd libfoo/subdir
+ % cons -t target
+
+is exactly equivalent to:
+
+ % cons libfoo/subdir/target
+
+If there are any C<Default> targets specified in the directory hierarchy's
+F<Construct> or F<Conscript> files, only the default targets at or below
+the directory from which C<cons -t> was invoked will be built.
+
+The command is invoked as follows:
+
+ cons <arguments> -- <construct-args>
+
+where I<arguments> can be any of the following, in any order:
+
+=over 10
+
+=item I<target>
+
+Build the specified target. If I<target> is a directory, then recursively
+build everything within that directory.
+
+=item I<+pattern>
+
+Limit the F<Conscript> files considered to just those that match I<pattern>,
+which is a Perl regular expression. Multiple C<+> arguments are accepted.
+
+=item I<name>=<val>
+
+Sets I<name> to value I<val> in the C<ARG> hash passed to the top-level
+F<Construct> file.
+
+=item C<-cc>
+
+Show command that would have been executed, when retrieving from cache. No
+indication that the file has been retrieved is given; this is useful for
+generating build logs that can be compared with real build logs.
+
+=item C<-cd>
+
+Disable all caching. Do not retrieve from cache nor flush to cache.
+
+=item C<-cr>
+
+Build dependencies in random order. This is useful when building multiple
+similar trees with caching enabled.
+
+=item C<-cs>
+
+Synchronize existing build targets that are found to be up-to-date with
+cache. This is useful if caching has been disabled with -cc or just recently
+enabled with UseCache.
+
+=item C<-d>
+
+Enable dependency debugging.
+
+=item C<-f> <file>
+
+Use the specified file instead of F<Construct> (but first change to
+containing directory of I<file>).
+
+=item C<-h>
+
+Show a help message local to the current build if one such is defined, and
+exit.
+
+=item C<-k>
+
+Keep going as far as possible after errors.
+
+=item C<-o> <file>
+
+Read override file I<file>.
+
+=item C<-p>
+
+Show construction products in specified trees. No build is attempted.
+
+=item C<-pa>
+
+Show construction products and associated actions. No build is attempted.
+
+=item C<-pw>
+
+Show products and where they are defined. No build is attempted.
+
+=item C<-q>
+
+Make the build quiet. Multiple C<-q> options may be specified.
+
+A single C<-q> options suppress messages about Installing and Removing
+targets.
+
+Two C<-q> options suppress build command lines and target up-to-date
+messages.
+
+=item C<-r>
+
+Remove construction products associated with <targets>. No build is
+attempted.
+
+=item C<-R> <repos>
+
+Search for files in I<repos>. Multiple B<-R> I<repos> directories are
+searched in the order specified.
+
+=item C<-S> <pkg>
+
+Use the sig::<pkg> package to calculate. Supported <pkg> values
+include "md5" for MD5 signature calculation and "md5::debug" for debug
+information about MD5 signature calculation.
+
+If the specified package ends in <::debug>, signature debug information
+will be printed to the file name specified in the C<CONS_SIG_DEBUG>
+environment variable, or to standard output if the environment variable
+is not set.
+
+=item C<-t>
+
+Traverse up the directory hierarchy looking for a F<Construct> file,
+if none exists in the current directory. Targets will be modified to
+be relative to the F<Construct> file.
+
+Internally, C<cons> will change its working directory to the directory
+which contains the top-level F<Construct> file and report:
+
+ cons: Entering directory `top-level-directory'
+
+This message indicates to an invoking editor (such as emacs) or build
+environment that Cons will now report all file names relative to the
+top-level directory. This message can not be suppressed with the C<-q>
+option.
+
+=item C<-v>
+
+Show C<cons> version and continue processing.
+
+=item C<-V>
+
+Show C<cons> version and exit.
+
+=item C<-wf> <file>
+
+Write all filenames considered into I<file>.
+
+=item C<-x>
+
+Show a help message similar to this one, and exit.
+
+=back
+
+And I<construct-args> can be any arguments that you wish to process in the
+F<Construct> file. Note that there should be a B<--> separating the arguments
+to cons and the arguments that you wish to process in the F<Construct> file.
+
+Processing of I<construct-args> can be done by any standard package like
+B<Getopt> or its variants, or any user defined package. B<cons> will pass in
+the I<construct-args> as B<@ARGV> and will not attempt to interpret anything
+after the B<-->.
+
+ % cons -R /usr/local/repository -d os=solaris +driver -- -c test -f DEBUG
+
+would pass the following to cons
+
+ -R /usr/local/repository -d os=solaris +driver
+
+and the following, to the top level F<Construct> file as B<@ARGV>
+
+ -c test -f DEBUG
+
+Note that C<cons -r .> is equivalent to a full recursive C<make clean>,
+but requires no support in the F<Construct> file or any F<Conscript>
+files. This is most useful if you are compiling files into source
+directories (if you separate the F<build> and F<export> directories,
+then you can just remove the directories).
+
+The options C<-p>, C<-pa>, and C<-pw> are extremely useful for use as an aid
+in reading scripts or debugging them. If you want to know what script
+installs F<export/include/foo.h>, for example, just type:
+
+ % cons -pw export/include/foo.h
+
+
+=head1 Using and writing dependency scanners
+
+QuickScan allows simple target-independent scanners to be set up for
+source files. Only one QuickScan scanner may be associated with any given
+source file and environment, although the same scanner may (and should)
+be used for multiple files of a given type.
+
+A QuickScan scanner is only ever invoked once for a given source file,
+and it is only invoked if the file is used by some target in the tree
+(i.e., there is a dependency on the source file).
+
+QuickScan is invoked as follows:
+
+ QuickScan CONSENV CODEREF, FILENAME [, PATH]
+
+The subroutine referenced by CODEREF is expected to return a list of
+filenames included directly by FILE. These filenames will, in turn, be
+scanned. The optional PATH argument supplies a lookup path for finding
+FILENAME and/or files returned by the user-supplied subroutine. The PATH
+may be a reference to an array of lookup-directory names, or a string of
+names separated by the system's separator character (':' on UNIX systems,
+';' on Windows NT).
+
+The subroutine is called once for each line in the file, with $_ set to the
+current line. If the subroutine needs to look at additional lines, or, for
+that matter, the entire file, then it may read them itself, from the
+filehandle SCAN. It may also terminate the loop, if it knows that no further
+include information is available, by closing the filehandle.
+
+Whether or not a lookup path is provided, QuickScan first tries to lookup
+the file relative to the current directory (for the top-level file
+supplied directly to QuickScan), or from the directory containing the
+file which referenced the file. This is not very general, but seems good
+enough--especially if you have the luxury of writing your own utilities
+and can control the use of the search path in a standard way.
+
+Here's a real example, taken from a F<Construct> file here:
+
+ sub cons::SMFgen {
+ my($env, @tables) = @_;
+ foreach $t (@tables) {
+ $env->QuickScan(sub { /\b\S*?\.smf\b/g }, "$t.smf",
+ $env->{SMF_INCLUDE_PATH});
+ $env->Command(["$t.smdb.cc","$t.smdb.h","$t.snmp.cc",
+ "$t.ami.cc", "$t.http.cc"], "$t.smf",
+ q(smfgen %( %SMF_INCLUDE_OPT %) %<));
+ }
+ }
+
+The subroutine above finds all names of the form <name>.smf in the
+file. It will return the names even if they're found within comments,
+but that's OK (the mechanism is forgiving of extra files; they're just
+ignored on the assumption that the missing file will be noticed when
+the program, in this example, smfgen, is actually invoked).
+
+[NOTE that the form C<$env-E<gt>QuickScan ...> and C<$env-E<gt>Command
+...> should not be necessary, but, for some reason, is required
+for this particular invocation. This appears to be a bug in Perl or
+a misunderstanding on my part; this invocation style does not always
+appear to be necessary.]
+
+Here is another way to build the same scanner. This one uses an
+explicit code reference, and also (unnecessarily, in this case) reads
+the whole file itself:
+
+ sub myscan {
+ my(@includes);
+ do {
+ push(@includes, /\b\S*?\.smf\b/g);
+ } while <SCAN>;
+ @includes
+ }
+
+Note that the order of the loop is reversed, with the loop test at the
+end. This is because the first line is already read for you. This scanner
+can be attached to a source file by:
+
+ QuickScan $env \&myscan, "$_.smf";
+
+This final example, which scans a different type of input file, takes
+over the file scanning rather than being called for each input line:
+
+ $env->QuickScan(
+ sub { my(@includes) = ();
+ do {
+ push(@includes, $3)
+ if /^(#include|import)\s+(\")(.+)(\")/ && $3
+ } while <SCAN>;
+ @includes
+ },
+ "$idlFileName",
+ "$env->{CPPPATH};$BUILD/ActiveContext/ACSCLientInterfaces"
+ );
+
+=head1 SUPPORT AND SUGGESTIONS
+
+Cons is maintained by the user community. To subscribe, send mail to
+B<cons-discuss-request@gnu.org> with body B<subscribe>.
+
+Please report any suggestions through the B<cons-discuss@gnu.org> mailing
+list.
+
+=head1 BUGS
+
+Sure to be some. Please report any bugs through the B<bug-cons@gnu.org>
+mailing list.
+
+=head1 INFORMATION ABOUT CONS
+
+Information about CONS can be obtained from the official cons web site
+B<http://www.dsmit.com/cons/> or its mirrors listed there.
+
+The cons maintainers can be contacted by email at
+B<cons-maintainers@gnu.org>
+
+=head1 AUTHORS
+
+Originally by Bob Sidebotham. Then significantly enriched by the members
+of the Cons community B<cons-discuss@gnu.org>.
+
+The Cons community would like to thank Ulrich Pfeifer for the original pod
+documentation derived from the F<cons.html> file. Cons documentation is now
+a part of the program itself.
+
+=cut
diff --git a/code/unix/extract_ver.pl b/code/unix/extract_ver.pl
new file mode 100755
index 0000000..4193d68
--- /dev/null
+++ b/code/unix/extract_ver.pl
@@ -0,0 +1,9 @@
+#!/usr/bin/env perl
+# extracting version string from game/q_shared.h
+# hacked from Wolf build process
+
+# extract the wolf version from q_shared.h
+$line = `cat ../game/q_shared.h | grep Q3_VERSION`;
+chomp $line;
+$line =~ s/.*Q3\ (.*)\"/$1/;
+print "$line\n";
diff --git a/code/unix/ftol.nasm b/code/unix/ftol.nasm
new file mode 100755
index 0000000..772e6a0
--- /dev/null
+++ b/code/unix/ftol.nasm
@@ -0,0 +1,151 @@
+;===========================================================================
+;Copyright (C) 1999-2005 Id Software, Inc.
+;
+;This file is part of Quake III Arena source code.
+;
+;Quake III Arena source code is free software; you can redistribute it
+;and/or modify it under the terms of the GNU General Public License as
+;published by the Free Software Foundation; either version 2 of the License,
+;or (at your option) any later version.
+;
+;Quake III Arena source code is distributed in the hope that it will be
+;useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+;MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;GNU General Public License for more details.
+;
+;You should have received a copy of the GNU General Public License
+;along with Foobar; if not, write to the Free Software
+;Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+;===========================================================================
+
+;
+; qftol -- fast floating point to long conversion.
+;
+
+segment .data
+
+temp dd 0.0
+fpucw dd 0
+
+; Precision Control Field , 2 bits / 0x0300
+; PC24 0x0000 Single precision (24 bits).
+; PC53 0x0200 Double precision (53 bits).
+; PC64 0x0300 Extended precision (64 bits).
+
+; Rounding Control Field, 2 bits / 0x0C00
+; RCN 0x0000 Rounding to nearest (even).
+; RCD 0x0400 Rounding down (directed, minus).
+; RCU 0x0800 Rounding up (directed plus).
+; RC0 0x0C00 Rounding towards zero (chop mode).
+
+
+; rounding towards nearest (even)
+cw027F dd 0x027F ; double precision
+cw037F dd 0x037F ; extended precision
+
+; rounding towards zero (chop mode)
+cw0E7F dd 0x0E7F ; double precision
+cw0F7F dd 0x0F7F ; extended precision
+
+
+segment .text
+
+;
+; int qftol( void ) - default control word
+;
+
+global qftol
+
+qftol:
+ fistp dword [temp]
+ mov eax, [temp]
+ ret
+
+
+;
+; int qftol027F( void ) - DirectX FPU
+;
+
+global qftol027F
+
+qftol027F:
+ fnstcw [fpucw]
+ fldcw [cw027F]
+ fistp dword [temp]
+ fldcw [fpucw]
+ mov eax, [temp]
+ ret
+
+;
+; int qftol037F( void ) - Linux FPU
+;
+
+global qftol037F
+
+qftol037F:
+ fnstcw [fpucw]
+ fldcw [cw037F]
+ fistp dword [temp]
+ fldcw [fpucw]
+ mov eax, [temp]
+ ret
+
+
+;
+; int qftol0F7F( void ) - ANSI
+;
+
+global qftol0F7F
+
+qftol0F7F:
+ fnstcw [fpucw]
+ fldcw [cw0F7F]
+ fistp dword [temp]
+ fldcw [fpucw]
+ mov eax, [temp]
+ ret
+
+;
+; int qftol0E7F( void )
+;
+
+global qftol0E7F
+
+qftol0E7F:
+ fnstcw [fpucw]
+ fldcw [cw0E7F]
+ fistp dword [temp]
+ fldcw [fpucw]
+ mov eax, [temp]
+ ret
+
+
+
+;
+; long Q_ftol( float q )
+;
+
+global Q_ftol
+
+Q_ftol:
+ fld dword [esp+4]
+ fistp dword [temp]
+ mov eax, [temp]
+ ret
+
+
+;
+; long qftol0F7F( float q ) - Linux FPU
+;
+
+global Q_ftol0F7F
+
+Q_ftol0F7F:
+ fnstcw [fpucw]
+ fld dword [esp+4]
+ fldcw [cw0F7F]
+ fistp dword [temp]
+ fldcw [fpucw]
+ mov eax, [temp]
+ ret
+
diff --git a/code/unix/linux_common.c b/code/unix/linux_common.c
new file mode 100755
index 0000000..512d425
--- /dev/null
+++ b/code/unix/linux_common.c
@@ -0,0 +1,344 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+/**
+ * GAS syntax equivalents of the MSVC asm memory calls in common.c
+ *
+ * The following changes have been made to the asm:
+ * 1. Registers are loaded by the inline asm arguments when possible
+ * 2. Labels have been changed to local label format (0,1,etc.) to allow inlining
+ *
+ * HISTORY:
+ * AH - Created on 08 Dec 2000
+ */
+
+#include <unistd.h> // AH - for size_t
+#include <string.h>
+
+// bk001207 - we need something under Linux, too. Mac?
+#if 1 // defined(C_ONLY) // bk010102 - dedicated?
+void Com_Memcpy (void* dest, const void* src, const size_t count) {
+ memcpy(dest, src, count);
+}
+
+void Com_Memset (void* dest, const int val, const size_t count) {
+ memset(dest, val, count);
+}
+
+#else
+
+typedef enum {
+ PRE_READ, // prefetch assuming that buffer is used for reading only
+ PRE_WRITE, // prefetch assuming that buffer is used for writing only
+ PRE_READ_WRITE // prefetch assuming that buffer is used for both reading and writing
+} e_prefetch;
+
+void Com_Prefetch (const void *s, const unsigned int bytes, e_prefetch type);
+
+void _copyDWord (unsigned int* dest, const unsigned int constant, const unsigned int count) {
+ // MMX version not used on standard Pentium MMX
+ // because the dword version is faster (with
+ // proper destination prefetching)
+ __asm__ __volatile__ (" \
+ //mov eax,constant // eax = val \
+ //mov edx,dest // dest \
+ //mov ecx,count \
+ movd %%eax, %%mm0 \
+ punpckldq %%mm0, %%mm0 \
+\
+ // ensure that destination is qword aligned \
+\
+ testl $7, %%edx // qword padding?\
+ jz 0f \
+ movl %%eax, (%%edx) \
+ decl %%ecx \
+ addl $4, %%edx \
+\
+0: movl %%ecx, %%ebx \
+ andl $0xfffffff0, %%ecx \
+ jz 2f \
+ jmp 1f \
+ .align 16 \
+\
+ // funny ordering here to avoid commands \
+ // that cross 32-byte boundaries (the \
+ // [edx+0] version has a special 3-byte opcode... \
+1: movq %%mm0, 8(%%edx) \
+ movq %%mm0, 16(%%edx) \
+ movq %%mm0, 24(%%edx) \
+ movq %%mm0, 32(%%edx) \
+ movq %%mm0, 40(%%edx) \
+ movq %%mm0, 48(%%edx) \
+ movq %%mm0, 56(%%edx) \
+ movq %%mm0, (%%edx)\
+ addl $64, %%edx \
+ subl $16, %%ecx \
+ jnz 1b \
+2: \
+ movl %%ebx, %%ecx // ebx = cnt \
+ andl $0xfffffff0, %%ecx // ecx = cnt&~15 \
+ subl %%ecx, %%ebx \
+ jz 6f \
+ cmpl $8, %%ebx \
+ jl 3f \
+\
+ movq %%mm0, (%%edx) \
+ movq %%mm0, 8(%%edx) \
+ movq %%mm0, 16(%%edx) \
+ movq %%mm0, 24(%%edx) \
+ addl $32, %%edx \
+ subl $8, %%ebx \
+ jz 6f \
+\
+3: cmpl $4, %%ebx \
+ jl 4f \
+ \
+ movq %%mm0, (%%edx) \
+ movq %%mm0, 8(%%edx) \
+ addl $16, %%edx \
+ subl $4, %%ebx \
+\
+4: cmpl $2, %%ebx \
+ jl 5f \
+ movq %%mm0, (%%edx) \
+ addl $8, %%edx \
+ subl $2, %%ebx \
+\
+5: cmpl $1, %%ebx \
+ jl 6f \
+ movl %%eax, (%%edx) \
+6: \
+ emms \
+ "
+ : : "a" (constant), "c" (count), "d" (dest)
+ : "%ebx", "%edi", "%esi", "cc", "memory");
+}
+
+// optimized memory copy routine that handles all alignment
+// cases and block sizes efficiently
+void Com_Memcpy (void* dest, const void* src, const size_t count) {
+ Com_Prefetch (src, count, PRE_READ);
+ __asm__ __volatile__ (" \
+ pushl %%edi \
+ pushl %%esi \
+ //mov ecx,count \
+ cmpl $0, %%ecx // count = 0 check (just to be on the safe side) \
+ je 6f \
+ //mov edx,dest \
+ movl %0, %%ebx \
+ cmpl $32, %%ecx // padding only? \
+ jl 1f \
+\
+ movl %%ecx, %%edi \
+ andl $0xfffffe00, %%edi // edi = count&~31 \
+ subl $32, %%edi \
+\
+ .align 16 \
+0: \
+ movl (%%ebx, %%edi, 1), %%eax \
+ movl 4(%%ebx, %%edi, 1), %%esi \
+ movl %%eax, (%%edx, %%edi, 1) \
+ movl %%esi, 4(%%edx, %%edi, 1) \
+ movl 8(%%ebx, %%edi, 1), %%eax \
+ movl 12(%%ebx, %%edi, 1), %%esi \
+ movl %%eax, 8(%%edx, %%edi, 1) \
+ movl %%esi, 12(%%edx, %%edi, 1) \
+ movl 16(%%ebx, %%edi, 1), %%eax \
+ movl 20(%%ebx, %%edi, 1), %%esi \
+ movl %%eax, 16(%%edx, %%edi, 1) \
+ movl %%esi, 20(%%edx, %%edi, 1) \
+ movl 24(%%ebx, %%edi, 1), %%eax \
+ movl 28(%%ebx, %%edi, 1), %%esi \
+ movl %%eax, 24(%%edx, %%edi, 1) \
+ movl %%esi, 28(%%edx, %%edi, 1) \
+ subl $32, %%edi \
+ jge 0b \
+ \
+ movl %%ecx, %%edi \
+ andl $0xfffffe00, %%edi \
+ addl %%edi, %%ebx // increase src pointer \
+ addl %%edi, %%edx // increase dst pointer \
+ andl $31, %%ecx // new count \
+ jz 6f // if count = 0, get outta here \
+\
+1: \
+ cmpl $16, %%ecx \
+ jl 2f \
+ movl (%%ebx), %%eax \
+ movl %%eax, (%%edx) \
+ movl 4(%%ebx), %%eax \
+ movl %%eax, 4(%%edx) \
+ movl 8(%%ebx), %%eax \
+ movl %%eax, 8(%%edx) \
+ movl 12(%%ebx), %%eax \
+ movl %%eax, 12(%%edx) \
+ subl $16, %%ecx \
+ addl $16, %%ebx \
+ addl $16, %%edx \
+2: \
+ cmpl $8, %%ecx \
+ jl 3f \
+ movl (%%ebx), %%eax \
+ movl %%eax, (%%edx) \
+ movl 4(%%ebx), %%eax \
+ subl $8, %%ecx \
+ movl %%eax, 4(%%edx) \
+ addl $8, %%ebx \
+ addl $8, %%edx \
+3: \
+ cmpl $4, %%ecx \
+ jl 4f \
+ movl (%%ebx), %%eax // here 4-7 bytes \
+ addl $4, %%ebx \
+ subl $4, %%ecx \
+ movl %%eax, (%%edx) \
+ addl $4, %%edx \
+4: // 0-3 remaining bytes \
+ cmpl $2, %%ecx \
+ jl 5f \
+ movw (%%ebx), %%ax // two bytes \
+ cmpl $3, %%ecx // less than 3? \
+ movw %%ax, (%%edx) \
+ jl 6f \
+ movb 2(%%ebx), %%al // last byte \
+ movb %%al, 2(%%edx) \
+ jmp 6f \
+5: \
+ cmpl $1, %%ecx \
+ jl 6f \
+ movb (%%ebx), %%al \
+ movb %%al, (%%edx) \
+6: \
+ popl %%esi \
+ popl %%edi \
+ "
+ : : "m" (src), "d" (dest), "c" (count)
+ : "%eax", "%ebx", "%edi", "%esi", "cc", "memory");
+}
+
+void Com_Memset (void* dest, const int val, const size_t count)
+{
+ unsigned int fillval;
+
+ if (count < 8)
+ {
+ __asm__ __volatile__ (" \
+ //mov edx,dest \
+ //mov eax, val \
+ movb %%al, %%ah \
+ movl %%eax, %%ebx \
+ andl $0xffff, %%ebx \
+ shll $16, %%eax \
+ addl %%ebx, %%eax // eax now contains pattern \
+ //mov ecx,count \
+ cmpl $4, %%ecx \
+ jl 0f \
+ movl %%eax, (%%edx) // copy first dword \
+ addl $4, %%edx \
+ subl $4, %%ecx \
+ 0: cmpl $2, %%ecx \
+ jl 1f \
+ movw %%ax, (%%edx) // copy 2 bytes \
+ addl $2, %%edx \
+ subl $2, %%ecx \
+ 1: cmpl $0, %%ecx \
+ je 2f \
+ movb %%al, (%%edx) // copy single byte \
+ 2: \
+ "
+ : : "d" (dest), "a" (val), "c" (count)
+ : "%ebx", "%edi", "%esi", "cc", "memory");
+
+ return;
+ }
+
+ fillval = val;
+
+ fillval = fillval|(fillval<<8);
+ fillval = fillval|(fillval<<16); // fill dword with 8-bit pattern
+
+ _copyDWord ((unsigned int*)(dest),fillval, count/4);
+
+ __asm__ __volatile__ (" // padding of 0-3 bytes \
+ //mov ecx,count \
+ movl %%ecx, %%eax \
+ andl $3, %%ecx \
+ jz 1f \
+ andl $0xffffff00, %%eax \
+ //mov ebx,dest \
+ addl %%eax, %%edx \
+ movl %0, %%eax \
+ cmpl $2, %%ecx \
+ jl 0f \
+ movw %%ax, (%%edx) \
+ cmpl $2, %%ecx \
+ je 1f \
+ movb %%al, 2(%%edx) \
+ jmp 1f \
+0: \
+ cmpl $0, %%ecx\
+ je 1f\
+ movb %%al, (%%edx)\
+1: \
+ "
+ : : "m" (fillval), "c" (count), "d" (dest)
+ : "%eax", "%ebx", "%edi", "%esi", "cc", "memory");
+}
+
+void Com_Prefetch (const void *s, const unsigned int bytes, e_prefetch type)
+{
+ // write buffer prefetching is performed only if
+ // the processor benefits from it. Read and read/write
+ // prefetching is always performed.
+
+ switch (type)
+ {
+ case PRE_WRITE : break;
+ case PRE_READ:
+ case PRE_READ_WRITE:
+
+ __asm__ __volatile__ ("\
+ //mov ebx,s\
+ //mov ecx,bytes\
+ cmpl $4096, %%ecx // clamp to 4kB\
+ jle 0f\
+ movl $4096, %%ecx\
+ 0:\
+ addl $0x1f, %%ecx\
+ shrl $5, %%ecx // number of cache lines\
+ jz 2f\
+ jmp 1f\
+\
+ .align 16\
+ 1: testb %%al, (%%edx)\
+ addl $32, %%edx\
+ decl %%ecx\
+ jnz 1b\
+ 2:\
+ "
+ : : "d" (s), "c" (bytes)
+ : "%eax", "%ebx", "%edi", "%esi", "memory", "cc");
+
+ break;
+ }
+}
+
+#endif
diff --git a/code/unix/linux_glimp.c b/code/unix/linux_glimp.c
new file mode 100755
index 0000000..fa92501
--- /dev/null
+++ b/code/unix/linux_glimp.c
@@ -0,0 +1,1780 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+/*
+** GLW_IMP.C
+**
+** This file contains ALL Linux specific stuff having to do with the
+** OpenGL refresh. When a port is being made the following functions
+** must be implemented by the port:
+**
+** GLimp_EndFrame
+** GLimp_Init
+** GLimp_Shutdown
+** GLimp_SwitchFullscreen
+** GLimp_SetGamma
+**
+*/
+
+#include <termios.h>
+#include <sys/ioctl.h>
+#ifdef __linux__
+ #include <sys/stat.h>
+ #include <sys/vt.h>
+#endif
+#include <stdarg.h>
+#include <stdio.h>
+#include <signal.h>
+#include <pthread.h>
+#include <semaphore.h>
+
+// bk001204
+#include <dlfcn.h>
+
+// bk001206 - from my Heretic2 by way of Ryan's Fakk2
+// Needed for the new X11_PendingInput() function.
+#include <sys/time.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include "../renderer/tr_local.h"
+#include "../client/client.h"
+#include "linux_local.h" // bk001130
+
+#include "unix_glw.h"
+
+#include <GL/glx.h>
+
+#include <X11/keysym.h>
+#include <X11/cursorfont.h>
+
+#include <X11/extensions/xf86dga.h>
+#include <X11/extensions/xf86vmode.h>
+
+#define WINDOW_CLASS_NAME "Quake III: Arena"
+
+typedef enum
+{
+ RSERR_OK,
+
+ RSERR_INVALID_FULLSCREEN,
+ RSERR_INVALID_MODE,
+
+ RSERR_UNKNOWN
+} rserr_t;
+
+glwstate_t glw_state;
+
+static Display *dpy = NULL;
+static int scrnum;
+static Window win = 0;
+static GLXContext ctx = NULL;
+
+// bk001206 - not needed anymore
+// static qboolean autorepeaton = qtrue;
+
+#define KEY_MASK (KeyPressMask | KeyReleaseMask)
+#define MOUSE_MASK (ButtonPressMask | ButtonReleaseMask | \
+ PointerMotionMask | ButtonMotionMask )
+#define X_MASK (KEY_MASK | MOUSE_MASK | VisibilityChangeMask | StructureNotifyMask )
+
+static qboolean mouse_avail;
+static qboolean mouse_active = qfalse;
+static int mwx, mwy;
+static int mx = 0, my = 0;
+
+// Time mouse was reset, we ignore the first 50ms of the mouse to allow settling of events
+static int mouseResetTime = 0;
+#define MOUSE_RESET_DELAY 50
+
+static cvar_t *in_mouse;
+static cvar_t *in_dgamouse; // user pref for dga mouse
+cvar_t *in_subframe;
+cvar_t *in_nograb; // this is strictly for developers
+
+// bk001130 - from cvs1.17 (mkv), but not static
+cvar_t *in_joystick = NULL;
+cvar_t *in_joystickDebug = NULL;
+cvar_t *joy_threshold = NULL;
+
+cvar_t *r_allowSoftwareGL; // don't abort out if the pixelformat claims software
+cvar_t *r_previousglDriver;
+
+qboolean vidmode_ext = qfalse;
+static int vidmode_MajorVersion = 0, vidmode_MinorVersion = 0; // major and minor of XF86VidExtensions
+
+// gamma value of the X display before we start playing with it
+static XF86VidModeGamma vidmode_InitialGamma;
+
+static int win_x, win_y;
+
+static XF86VidModeModeInfo **vidmodes;
+//static int default_dotclock_vidmode; // bk001204 - unused
+static int num_vidmodes;
+static qboolean vidmode_active = qfalse;
+
+static int mouse_accel_numerator;
+static int mouse_accel_denominator;
+static int mouse_threshold;
+
+/*
+* Find the first occurrence of find in s.
+*/
+// bk001130 - from cvs1.17 (mkv), const
+// bk001130 - made first argument const
+static const char *Q_stristr( const char *s, const char *find)
+{
+ register char c, sc;
+ register size_t len;
+
+ if ((c = *find++) != 0)
+ {
+ if (c >= 'a' && c <= 'z')
+ {
+ c -= ('a' - 'A');
+ }
+ len = strlen(find);
+ do
+ {
+ do
+ {
+ if ((sc = *s++) == 0)
+ return NULL;
+ if (sc >= 'a' && sc <= 'z')
+ {
+ sc -= ('a' - 'A');
+ }
+ } while (sc != c);
+ } while (Q_stricmpn(s, find, len) != 0);
+ s--;
+ }
+ return s;
+}
+
+/*****************************************************************************
+** KEYBOARD
+** NOTE TTimo the keyboard handling is done with KeySyms
+** that means relying on the keyboard mapping provided by X
+** in-game it would probably be better to use KeyCode (i.e. hardware key codes)
+** you would still need the KeySyms in some cases, such as for the console and all entry textboxes
+** (cause there's nothing worse than a qwerty mapping on a french keyboard)
+**
+** you can turn on some debugging and verbose of the keyboard code with #define KBD_DBG
+******************************************************************************/
+
+//#define KBD_DBG
+
+static char *XLateKey(XKeyEvent *ev, int *key)
+{
+ static char buf[64];
+ KeySym keysym;
+ int XLookupRet;
+
+ *key = 0;
+
+ XLookupRet = XLookupString(ev, buf, sizeof buf, &keysym, 0);
+#ifdef KBD_DBG
+ ri.Printf(PRINT_ALL, "XLookupString ret: %d buf: %s keysym: %x\n", XLookupRet, buf, keysym);
+#endif
+
+ switch (keysym)
+ {
+ case XK_KP_Page_Up:
+ case XK_KP_9: *key = K_KP_PGUP; break;
+ case XK_Page_Up: *key = K_PGUP; break;
+
+ case XK_KP_Page_Down:
+ case XK_KP_3: *key = K_KP_PGDN; break;
+ case XK_Page_Down: *key = K_PGDN; break;
+
+ case XK_KP_Home: *key = K_KP_HOME; break;
+ case XK_KP_7: *key = K_KP_HOME; break;
+ case XK_Home: *key = K_HOME; break;
+
+ case XK_KP_End:
+ case XK_KP_1: *key = K_KP_END; break;
+ case XK_End: *key = K_END; break;
+
+ case XK_KP_Left: *key = K_KP_LEFTARROW; break;
+ case XK_KP_4: *key = K_KP_LEFTARROW; break;
+ case XK_Left: *key = K_LEFTARROW; break;
+
+ case XK_KP_Right: *key = K_KP_RIGHTARROW; break;
+ case XK_KP_6: *key = K_KP_RIGHTARROW; break;
+ case XK_Right: *key = K_RIGHTARROW; break;
+
+ case XK_KP_Down:
+ case XK_KP_2: *key = K_KP_DOWNARROW; break;
+ case XK_Down: *key = K_DOWNARROW; break;
+
+ case XK_KP_Up:
+ case XK_KP_8: *key = K_KP_UPARROW; break;
+ case XK_Up: *key = K_UPARROW; break;
+
+ case XK_Escape: *key = K_ESCAPE; break;
+
+ case XK_KP_Enter: *key = K_KP_ENTER; break;
+ case XK_Return: *key = K_ENTER; break;
+
+ case XK_Tab: *key = K_TAB; break;
+
+ case XK_F1: *key = K_F1; break;
+
+ case XK_F2: *key = K_F2; break;
+
+ case XK_F3: *key = K_F3; break;
+
+ case XK_F4: *key = K_F4; break;
+
+ case XK_F5: *key = K_F5; break;
+
+ case XK_F6: *key = K_F6; break;
+
+ case XK_F7: *key = K_F7; break;
+
+ case XK_F8: *key = K_F8; break;
+
+ case XK_F9: *key = K_F9; break;
+
+ case XK_F10: *key = K_F10; break;
+
+ case XK_F11: *key = K_F11; break;
+
+ case XK_F12: *key = K_F12; break;
+
+ // bk001206 - from Ryan's Fakk2
+ //case XK_BackSpace: *key = 8; break; // ctrl-h
+ case XK_BackSpace: *key = K_BACKSPACE; break; // ctrl-h
+
+ case XK_KP_Delete:
+ case XK_KP_Decimal: *key = K_KP_DEL; break;
+ case XK_Delete: *key = K_DEL; break;
+
+ case XK_Pause: *key = K_PAUSE; break;
+
+ case XK_Shift_L:
+ case XK_Shift_R: *key = K_SHIFT; break;
+
+ case XK_Execute:
+ case XK_Control_L:
+ case XK_Control_R: *key = K_CTRL; break;
+
+ case XK_Alt_L:
+ case XK_Meta_L:
+ case XK_Alt_R:
+ case XK_Meta_R: *key = K_ALT; break;
+
+ case XK_KP_Begin: *key = K_KP_5; break;
+
+ case XK_Insert: *key = K_INS; break;
+ case XK_KP_Insert:
+ case XK_KP_0: *key = K_KP_INS; break;
+
+ case XK_KP_Multiply: *key = '*'; break;
+ case XK_KP_Add: *key = K_KP_PLUS; break;
+ case XK_KP_Subtract: *key = K_KP_MINUS; break;
+ case XK_KP_Divide: *key = K_KP_SLASH; break;
+
+ // bk001130 - from cvs1.17 (mkv)
+ case XK_exclam: *key = '1'; break;
+ case XK_at: *key = '2'; break;
+ case XK_numbersign: *key = '3'; break;
+ case XK_dollar: *key = '4'; break;
+ case XK_percent: *key = '5'; break;
+ case XK_asciicircum: *key = '6'; break;
+ case XK_ampersand: *key = '7'; break;
+ case XK_asterisk: *key = '8'; break;
+ case XK_parenleft: *key = '9'; break;
+ case XK_parenright: *key = '0'; break;
+
+ // weird french keyboards ..
+ // NOTE: console toggle is hardcoded in cl_keys.c, can't be unbound
+ // cleaner would be .. using hardware key codes instead of the key syms
+ // could also add a new K_KP_CONSOLE
+ case XK_twosuperior: *key = '~'; break;
+
+ // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=472
+ case XK_space:
+ case XK_KP_Space: *key = K_SPACE; break;
+
+ default:
+ if (XLookupRet == 0)
+ {
+ if (com_developer->value)
+ {
+ ri.Printf(PRINT_ALL, "Warning: XLookupString failed on KeySym %d\n", keysym);
+ }
+ return NULL;
+ }
+ else
+ {
+ // XK_* tests failed, but XLookupString got a buffer, so let's try it
+ *key = *(unsigned char *)buf;
+ if (*key >= 'A' && *key <= 'Z')
+ *key = *key - 'A' + 'a';
+ // if ctrl is pressed, the keys are not between 'A' and 'Z', for instance ctrl-z == 26 ^Z ^C etc.
+ // see https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=19
+ else if (*key >= 1 && *key <= 26)
+ *key = *key + 'a' - 1;
+ }
+ break;
+ }
+
+ return buf;
+}
+
+// ========================================================================
+// makes a null cursor
+// ========================================================================
+
+static Cursor CreateNullCursor(Display *display, Window root)
+{
+ Pixmap cursormask;
+ XGCValues xgc;
+ GC gc;
+ XColor dummycolour;
+ Cursor cursor;
+
+ cursormask = XCreatePixmap(display, root, 1, 1, 1/*depth*/);
+ xgc.function = GXclear;
+ gc = XCreateGC(display, cursormask, GCFunction, &xgc);
+ XFillRectangle(display, cursormask, gc, 0, 0, 1, 1);
+ dummycolour.pixel = 0;
+ dummycolour.red = 0;
+ dummycolour.flags = 04;
+ cursor = XCreatePixmapCursor(display, cursormask, cursormask,
+ &dummycolour,&dummycolour, 0,0);
+ XFreePixmap(display,cursormask);
+ XFreeGC(display,gc);
+ return cursor;
+}
+
+static void install_grabs(void)
+{
+ // inviso cursor
+ XWarpPointer(dpy, None, win,
+ 0, 0, 0, 0,
+ glConfig.vidWidth / 2, glConfig.vidHeight / 2);
+ XSync(dpy, False);
+
+ XDefineCursor(dpy, win, CreateNullCursor(dpy, win));
+
+ XGrabPointer(dpy, win, // bk010108 - do this earlier?
+ False,
+ MOUSE_MASK,
+ GrabModeAsync, GrabModeAsync,
+ win,
+ None,
+ CurrentTime);
+
+ XGetPointerControl(dpy, &mouse_accel_numerator, &mouse_accel_denominator,
+ &mouse_threshold);
+
+ XChangePointerControl(dpy, True, True, 1, 1, 0);
+
+ XSync(dpy, False);
+
+ mouseResetTime = Sys_Milliseconds ();
+
+ if (in_dgamouse->value)
+ {
+ int MajorVersion, MinorVersion;
+
+ if (!XF86DGAQueryVersion(dpy, &MajorVersion, &MinorVersion))
+ {
+ // unable to query, probalby not supported, force the setting to 0
+ ri.Printf( PRINT_ALL, "Failed to detect XF86DGA Mouse\n" );
+ ri.Cvar_Set( "in_dgamouse", "0" );
+ } else
+ {
+ XF86DGADirectVideo(dpy, DefaultScreen(dpy), XF86DGADirectMouse);
+ XWarpPointer(dpy, None, win, 0, 0, 0, 0, 0, 0);
+ }
+ } else
+ {
+ mwx = glConfig.vidWidth / 2;
+ mwy = glConfig.vidHeight / 2;
+ mx = my = 0;
+ }
+
+ XGrabKeyboard(dpy, win,
+ False,
+ GrabModeAsync, GrabModeAsync,
+ CurrentTime);
+
+ XSync(dpy, False);
+}
+
+static void uninstall_grabs(void)
+{
+ if (in_dgamouse->value)
+ {
+ if (com_developer->value)
+ ri.Printf( PRINT_ALL, "DGA Mouse - Disabling DGA DirectVideo\n" );
+ XF86DGADirectVideo(dpy, DefaultScreen(dpy), 0);
+ }
+
+ XChangePointerControl(dpy, qtrue, qtrue, mouse_accel_numerator,
+ mouse_accel_denominator, mouse_threshold);
+
+ XUngrabPointer(dpy, CurrentTime);
+ XUngrabKeyboard(dpy, CurrentTime);
+
+ XWarpPointer(dpy, None, win,
+ 0, 0, 0, 0,
+ glConfig.vidWidth / 2, glConfig.vidHeight / 2);
+
+ // inviso cursor
+ XUndefineCursor(dpy, win);
+}
+
+// bk001206 - from Ryan's Fakk2
+/**
+ * XPending() actually performs a blocking read
+ * if no events available. From Fakk2, by way of
+ * Heretic2, by way of SDL, original idea GGI project.
+ * The benefit of this approach over the quite
+ * badly behaved XAutoRepeatOn/Off is that you get
+ * focus handling for free, which is a major win
+ * with debug and windowed mode. It rests on the
+ * assumption that the X server will use the
+ * same timestamp on press/release event pairs
+ * for key repeats.
+ */
+static qboolean X11_PendingInput(void) {
+
+ assert(dpy != NULL);
+
+ // Flush the display connection
+ // and look to see if events are queued
+ XFlush( dpy );
+ if ( XEventsQueued( dpy, QueuedAlready) )
+ {
+ return qtrue;
+ }
+
+ // More drastic measures are required -- see if X is ready to talk
+ {
+ static struct timeval zero_time;
+ int x11_fd;
+ fd_set fdset;
+
+ x11_fd = ConnectionNumber( dpy );
+ FD_ZERO(&fdset);
+ FD_SET(x11_fd, &fdset);
+ if ( select(x11_fd+1, &fdset, NULL, NULL, &zero_time) == 1 )
+ {
+ return(XPending(dpy));
+ }
+ }
+
+ // Oh well, nothing is ready ..
+ return qfalse;
+}
+
+// bk001206 - from Ryan's Fakk2. See above.
+static qboolean repeated_press(XEvent *event)
+{
+ XEvent peekevent;
+ qboolean repeated = qfalse;
+
+ assert(dpy != NULL);
+
+ if (X11_PendingInput())
+ {
+ XPeekEvent(dpy, &peekevent);
+
+ if ((peekevent.type == KeyPress) &&
+ (peekevent.xkey.keycode == event->xkey.keycode) &&
+ (peekevent.xkey.time == event->xkey.time))
+ {
+ repeated = qtrue;
+ XNextEvent(dpy, &peekevent); // skip event.
+ } // if
+ } // if
+
+ return(repeated);
+} // repeated_press
+
+int Sys_XTimeToSysTime (Time xtime);
+static void HandleEvents(void)
+{
+ int b;
+ int key;
+ XEvent event;
+ qboolean dowarp = qfalse;
+ char *p;
+ int dx, dy;
+ int t = 0; // default to 0 in case we don't set
+
+ if (!dpy)
+ return;
+
+ while (XPending(dpy))
+ {
+ XNextEvent(dpy, &event);
+ switch (event.type)
+ {
+ case KeyPress:
+ t = Sys_XTimeToSysTime(event.xkey.time);
+ p = XLateKey(&event.xkey, &key);
+ if (key)
+ {
+ Sys_QueEvent( t, SE_KEY, key, qtrue, 0, NULL );
+ }
+ if (p)
+ {
+ while (*p)
+ {
+ Sys_QueEvent( t, SE_CHAR, *p++, 0, 0, NULL );
+ }
+ }
+ break;
+
+ case KeyRelease:
+ t = Sys_XTimeToSysTime(event.xkey.time);
+ // bk001206 - handle key repeat w/o XAutRepatOn/Off
+ // also: not done if console/menu is active.
+ // From Ryan's Fakk2.
+ // see game/q_shared.h, KEYCATCH_* . 0 == in 3d game.
+ if (cls.keyCatchers == 0)
+ { // FIXME: KEYCATCH_NONE
+ if (repeated_press(&event) == qtrue)
+ continue;
+ } // if
+ XLateKey(&event.xkey, &key);
+
+ Sys_QueEvent( t, SE_KEY, key, qfalse, 0, NULL );
+ break;
+
+ case MotionNotify:
+ t = Sys_XTimeToSysTime(event.xkey.time);
+ if (mouse_active)
+ {
+ if (in_dgamouse->value)
+ {
+ if (abs(event.xmotion.x_root) > 1)
+ mx += event.xmotion.x_root * 2;
+ else
+ mx += event.xmotion.x_root;
+ if (abs(event.xmotion.y_root) > 1)
+ my += event.xmotion.y_root * 2;
+ else
+ my += event.xmotion.y_root;
+ if (t - mouseResetTime > MOUSE_RESET_DELAY )
+ {
+ Sys_QueEvent( t, SE_MOUSE, mx, my, 0, NULL );
+ }
+ mx = my = 0;
+ } else
+ {
+ // If it's a center motion, we've just returned from our warp
+ if (event.xmotion.x == glConfig.vidWidth/2 &&
+ event.xmotion.y == glConfig.vidHeight/2)
+ {
+ mwx = glConfig.vidWidth/2;
+ mwy = glConfig.vidHeight/2;
+ if (t - mouseResetTime > MOUSE_RESET_DELAY )
+ {
+ Sys_QueEvent( t, SE_MOUSE, mx, my, 0, NULL );
+ }
+ mx = my = 0;
+ break;
+ }
+
+ dx = ((int)event.xmotion.x - mwx);
+ dy = ((int)event.xmotion.y - mwy);
+ if (abs(dx) > 1)
+ mx += dx * 2;
+ else
+ mx += dx;
+ if (abs(dy) > 1)
+ my += dy * 2;
+ else
+ my += dy;
+
+ mwx = event.xmotion.x;
+ mwy = event.xmotion.y;
+ dowarp = qtrue;
+ }
+ }
+ break;
+
+ case ButtonPress:
+ t = Sys_XTimeToSysTime(event.xkey.time);
+ if (event.xbutton.button == 4)
+ {
+ Sys_QueEvent( t, SE_KEY, K_MWHEELUP, qtrue, 0, NULL );
+ } else if (event.xbutton.button == 5)
+ {
+ Sys_QueEvent( t, SE_KEY, K_MWHEELDOWN, qtrue, 0, NULL );
+ } else
+ {
+ // NOTE TTimo there seems to be a weird mapping for K_MOUSE1 K_MOUSE2 K_MOUSE3 ..
+ b=-1;
+ if (event.xbutton.button == 1)
+ {
+ b = 0; // K_MOUSE1
+ } else if (event.xbutton.button == 2)
+ {
+ b = 2; // K_MOUSE3
+ } else if (event.xbutton.button == 3)
+ {
+ b = 1; // K_MOUSE2
+ } else if (event.xbutton.button == 6)
+ {
+ b = 3; // K_MOUSE4
+ } else if (event.xbutton.button == 7)
+ {
+ b = 4; // K_MOUSE5
+ };
+
+ Sys_QueEvent( t, SE_KEY, K_MOUSE1 + b, qtrue, 0, NULL );
+ }
+ break;
+
+ case ButtonRelease:
+ t = Sys_XTimeToSysTime(event.xkey.time);
+ if (event.xbutton.button == 4)
+ {
+ Sys_QueEvent( t, SE_KEY, K_MWHEELUP, qfalse, 0, NULL );
+ } else if (event.xbutton.button == 5)
+ {
+ Sys_QueEvent( t, SE_KEY, K_MWHEELDOWN, qfalse, 0, NULL );
+ } else
+ {
+ b=-1;
+ if (event.xbutton.button == 1)
+ {
+ b = 0;
+ } else if (event.xbutton.button == 2)
+ {
+ b = 2;
+ } else if (event.xbutton.button == 3)
+ {
+ b = 1;
+ } else if (event.xbutton.button == 6)
+ {
+ b = 3; // K_MOUSE4
+ } else if (event.xbutton.button == 7)
+ {
+ b = 4; // K_MOUSE5
+ };
+ Sys_QueEvent( t, SE_KEY, K_MOUSE1 + b, qfalse, 0, NULL );
+ }
+ break;
+
+ case CreateNotify :
+ win_x = event.xcreatewindow.x;
+ win_y = event.xcreatewindow.y;
+ break;
+
+ case ConfigureNotify :
+ win_x = event.xconfigure.x;
+ win_y = event.xconfigure.y;
+ break;
+ }
+ }
+
+ if (dowarp)
+ {
+ XWarpPointer(dpy,None,win,0,0,0,0,
+ (glConfig.vidWidth/2),(glConfig.vidHeight/2));
+ }
+}
+
+// NOTE TTimo for the tty console input, we didn't rely on those ..
+// it's not very surprising actually cause they are not used otherwise
+void KBD_Init(void)
+{
+}
+
+void KBD_Close(void)
+{
+}
+
+void IN_ActivateMouse( void )
+{
+ if (!mouse_avail || !dpy || !win)
+ return;
+
+ if (!mouse_active)
+ {
+ if (!in_nograb->value)
+ install_grabs();
+ else if (in_dgamouse->value) // force dga mouse to 0 if using nograb
+ ri.Cvar_Set("in_dgamouse", "0");
+ mouse_active = qtrue;
+ }
+}
+
+void IN_DeactivateMouse( void )
+{
+ if (!mouse_avail || !dpy || !win)
+ return;
+
+ if (mouse_active)
+ {
+ if (!in_nograb->value)
+ uninstall_grabs();
+ else if (in_dgamouse->value) // force dga mouse to 0 if using nograb
+ ri.Cvar_Set("in_dgamouse", "0");
+ mouse_active = qfalse;
+ }
+}
+/*****************************************************************************/
+
+/*
+** GLimp_SetGamma
+**
+** This routine should only be called if glConfig.deviceSupportsGamma is TRUE
+*/
+void GLimp_SetGamma( unsigned char red[256], unsigned char green[256], unsigned char blue[256] )
+{
+ // NOTE TTimo we get the gamma value from cvar, because we can't work with the s_gammatable
+ // the API wasn't changed to avoid breaking other OSes
+ float g = Cvar_Get("r_gamma", "1.0", 0)->value;
+ XF86VidModeGamma gamma;
+ assert(glConfig.deviceSupportsGamma);
+ gamma.red = g;
+ gamma.green = g;
+ gamma.blue = g;
+ XF86VidModeSetGamma(dpy, scrnum, &gamma);
+}
+
+/*
+** GLimp_Shutdown
+**
+** This routine does all OS specific shutdown procedures for the OpenGL
+** subsystem. Under OpenGL this means NULLing out the current DC and
+** HGLRC, deleting the rendering context, and releasing the DC acquired
+** for the window. The state structure is also nulled out.
+**
+*/
+void GLimp_Shutdown( void )
+{
+ if (!ctx || !dpy)
+ return;
+ IN_DeactivateMouse();
+ // bk001206 - replaced with H2/Fakk2 solution
+ // XAutoRepeatOn(dpy);
+ // autorepeaton = qfalse; // bk001130 - from cvs1.17 (mkv)
+ if (dpy)
+ {
+ if (ctx)
+ qglXDestroyContext(dpy, ctx);
+ if (win)
+ XDestroyWindow(dpy, win);
+ if (vidmode_active)
+ XF86VidModeSwitchToMode(dpy, scrnum, vidmodes[0]);
+ if (glConfig.deviceSupportsGamma)
+ {
+ XF86VidModeSetGamma(dpy, scrnum, &vidmode_InitialGamma);
+ }
+ // NOTE TTimo opening/closing the display should be necessary only once per run
+ // but it seems QGL_Shutdown gets called in a lot of occasion
+ // in some cases, this XCloseDisplay is known to raise some X errors
+ // ( https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=33 )
+ XCloseDisplay(dpy);
+ }
+ vidmode_active = qfalse;
+ dpy = NULL;
+ win = 0;
+ ctx = NULL;
+
+ memset( &glConfig, 0, sizeof( glConfig ) );
+ memset( &glState, 0, sizeof( glState ) );
+
+ QGL_Shutdown();
+}
+
+/*
+** GLimp_LogComment
+*/
+void GLimp_LogComment( char *comment )
+{
+ if ( glw_state.log_fp )
+ {
+ fprintf( glw_state.log_fp, "%s", comment );
+ }
+}
+
+/*
+** GLW_StartDriverAndSetMode
+*/
+// bk001204 - prototype needed
+int GLW_SetMode( const char *drivername, int mode, qboolean fullscreen );
+static qboolean GLW_StartDriverAndSetMode( const char *drivername,
+ int mode,
+ qboolean fullscreen )
+{
+ rserr_t err;
+
+ // don't ever bother going into fullscreen with a voodoo card
+#if 1 // JDC: I reenabled this
+ if ( Q_stristr( drivername, "Voodoo" ) )
+ {
+ ri.Cvar_Set( "r_fullscreen", "0" );
+ r_fullscreen->modified = qfalse;
+ fullscreen = qfalse;
+ }
+#endif
+
+ if (fullscreen && in_nograb->value)
+ {
+ ri.Printf( PRINT_ALL, "Fullscreen not allowed with in_nograb 1\n");
+ ri.Cvar_Set( "r_fullscreen", "0" );
+ r_fullscreen->modified = qfalse;
+ fullscreen = qfalse;
+ }
+
+ err = GLW_SetMode( drivername, mode, fullscreen );
+
+ switch ( err )
+ {
+ case RSERR_INVALID_FULLSCREEN:
+ ri.Printf( PRINT_ALL, "...WARNING: fullscreen unavailable in this mode\n" );
+ return qfalse;
+ case RSERR_INVALID_MODE:
+ ri.Printf( PRINT_ALL, "...WARNING: could not set the given mode (%d)\n", mode );
+ return qfalse;
+ default:
+ break;
+ }
+ return qtrue;
+}
+
+/*
+** GLW_SetMode
+*/
+int GLW_SetMode( const char *drivername, int mode, qboolean fullscreen )
+{
+ int attrib[] = {
+ GLX_RGBA, // 0
+ GLX_RED_SIZE, 4, // 1, 2
+ GLX_GREEN_SIZE, 4, // 3, 4
+ GLX_BLUE_SIZE, 4, // 5, 6
+ GLX_DOUBLEBUFFER, // 7
+ GLX_DEPTH_SIZE, 1, // 8, 9
+ GLX_STENCIL_SIZE, 1, // 10, 11
+ None
+ };
+ // these match in the array
+#define ATTR_RED_IDX 2
+#define ATTR_GREEN_IDX 4
+#define ATTR_BLUE_IDX 6
+#define ATTR_DEPTH_IDX 9
+#define ATTR_STENCIL_IDX 11
+ Window root;
+ XVisualInfo *visinfo;
+ XSetWindowAttributes attr;
+ XSizeHints sizehints;
+ unsigned long mask;
+ int colorbits, depthbits, stencilbits;
+ int tcolorbits, tdepthbits, tstencilbits;
+ int dga_MajorVersion, dga_MinorVersion;
+ int actualWidth, actualHeight;
+ int i;
+ const char* glstring; // bk001130 - from cvs1.17 (mkv)
+
+ ri.Printf( PRINT_ALL, "Initializing OpenGL display\n");
+
+ ri.Printf (PRINT_ALL, "...setting mode %d:", mode );
+
+ if ( !R_GetModeInfo( &glConfig.vidWidth, &glConfig.vidHeight, &glConfig.windowAspect, mode ) )
+ {
+ ri.Printf( PRINT_ALL, " invalid mode\n" );
+ return RSERR_INVALID_MODE;
+ }
+ ri.Printf( PRINT_ALL, " %d %d\n", glConfig.vidWidth, glConfig.vidHeight);
+
+ if (!(dpy = XOpenDisplay(NULL)))
+ {
+ fprintf(stderr, "Error couldn't open the X display\n");
+ return RSERR_INVALID_MODE;
+ }
+
+ scrnum = DefaultScreen(dpy);
+ root = RootWindow(dpy, scrnum);
+
+ actualWidth = glConfig.vidWidth;
+ actualHeight = glConfig.vidHeight;
+
+ // Get video mode list
+ if (!XF86VidModeQueryVersion(dpy, &vidmode_MajorVersion, &vidmode_MinorVersion))
+ {
+ vidmode_ext = qfalse;
+ } else
+ {
+ ri.Printf(PRINT_ALL, "Using XFree86-VidModeExtension Version %d.%d\n",
+ vidmode_MajorVersion, vidmode_MinorVersion);
+ vidmode_ext = qtrue;
+ }
+
+ // Check for DGA
+ dga_MajorVersion = 0, dga_MinorVersion = 0;
+ if (in_dgamouse->value)
+ {
+ if (!XF86DGAQueryVersion(dpy, &dga_MajorVersion, &dga_MinorVersion))
+ {
+ // unable to query, probalby not supported
+ ri.Printf( PRINT_ALL, "Failed to detect XF86DGA Mouse\n" );
+ ri.Cvar_Set( "in_dgamouse", "0" );
+ } else
+ {
+ ri.Printf( PRINT_ALL, "XF86DGA Mouse (Version %d.%d) initialized\n",
+ dga_MajorVersion, dga_MinorVersion);
+ }
+ }
+
+ if (vidmode_ext)
+ {
+ int best_fit, best_dist, dist, x, y;
+
+ XF86VidModeGetAllModeLines(dpy, scrnum, &num_vidmodes, &vidmodes);
+
+ // Are we going fullscreen? If so, let's change video mode
+ if (fullscreen)
+ {
+ best_dist = 9999999;
+ best_fit = -1;
+
+ for (i = 0; i < num_vidmodes; i++)
+ {
+ if (glConfig.vidWidth > vidmodes[i]->hdisplay ||
+ glConfig.vidHeight > vidmodes[i]->vdisplay)
+ continue;
+
+ x = glConfig.vidWidth - vidmodes[i]->hdisplay;
+ y = glConfig.vidHeight - vidmodes[i]->vdisplay;
+ dist = (x * x) + (y * y);
+ if (dist < best_dist)
+ {
+ best_dist = dist;
+ best_fit = i;
+ }
+ }
+
+ if (best_fit != -1)
+ {
+ actualWidth = vidmodes[best_fit]->hdisplay;
+ actualHeight = vidmodes[best_fit]->vdisplay;
+
+ // change to the mode
+ XF86VidModeSwitchToMode(dpy, scrnum, vidmodes[best_fit]);
+ vidmode_active = qtrue;
+
+ // Move the viewport to top left
+ XF86VidModeSetViewPort(dpy, scrnum, 0, 0);
+
+ ri.Printf(PRINT_ALL, "XFree86-VidModeExtension Activated at %dx%d\n",
+ actualWidth, actualHeight);
+
+ } else
+ {
+ fullscreen = 0;
+ ri.Printf(PRINT_ALL, "XFree86-VidModeExtension: No acceptable modes found\n");
+ }
+ } else
+ {
+ ri.Printf(PRINT_ALL, "XFree86-VidModeExtension: Ignored on non-fullscreen/Voodoo\n");
+ }
+ }
+
+
+ if (!r_colorbits->value)
+ colorbits = 24;
+ else
+ colorbits = r_colorbits->value;
+
+ if ( !Q_stricmp( r_glDriver->string, _3DFX_DRIVER_NAME ) )
+ colorbits = 16;
+
+ if (!r_depthbits->value)
+ depthbits = 24;
+ else
+ depthbits = r_depthbits->value;
+ stencilbits = r_stencilbits->value;
+
+ for (i = 0; i < 16; i++)
+ {
+ // 0 - default
+ // 1 - minus colorbits
+ // 2 - minus depthbits
+ // 3 - minus stencil
+ if ((i % 4) == 0 && i)
+ {
+ // one pass, reduce
+ switch (i / 4)
+ {
+ case 2 :
+ if (colorbits == 24)
+ colorbits = 16;
+ break;
+ case 1 :
+ if (depthbits == 24)
+ depthbits = 16;
+ else if (depthbits == 16)
+ depthbits = 8;
+ case 3 :
+ if (stencilbits == 24)
+ stencilbits = 16;
+ else if (stencilbits == 16)
+ stencilbits = 8;
+ }
+ }
+
+ tcolorbits = colorbits;
+ tdepthbits = depthbits;
+ tstencilbits = stencilbits;
+
+ if ((i % 4) == 3)
+ { // reduce colorbits
+ if (tcolorbits == 24)
+ tcolorbits = 16;
+ }
+
+ if ((i % 4) == 2)
+ { // reduce depthbits
+ if (tdepthbits == 24)
+ tdepthbits = 16;
+ else if (tdepthbits == 16)
+ tdepthbits = 8;
+ }
+
+ if ((i % 4) == 1)
+ { // reduce stencilbits
+ if (tstencilbits == 24)
+ tstencilbits = 16;
+ else if (tstencilbits == 16)
+ tstencilbits = 8;
+ else
+ tstencilbits = 0;
+ }
+
+ if (tcolorbits == 24)
+ {
+ attrib[ATTR_RED_IDX] = 8;
+ attrib[ATTR_GREEN_IDX] = 8;
+ attrib[ATTR_BLUE_IDX] = 8;
+ } else
+ {
+ // must be 16 bit
+ attrib[ATTR_RED_IDX] = 4;
+ attrib[ATTR_GREEN_IDX] = 4;
+ attrib[ATTR_BLUE_IDX] = 4;
+ }
+
+ attrib[ATTR_DEPTH_IDX] = tdepthbits; // default to 24 depth
+ attrib[ATTR_STENCIL_IDX] = tstencilbits;
+
+ visinfo = qglXChooseVisual(dpy, scrnum, attrib);
+ if (!visinfo)
+ {
+ continue;
+ }
+
+ ri.Printf( PRINT_ALL, "Using %d/%d/%d Color bits, %d depth, %d stencil display.\n",
+ attrib[ATTR_RED_IDX], attrib[ATTR_GREEN_IDX], attrib[ATTR_BLUE_IDX],
+ attrib[ATTR_DEPTH_IDX], attrib[ATTR_STENCIL_IDX]);
+
+ glConfig.colorBits = tcolorbits;
+ glConfig.depthBits = tdepthbits;
+ glConfig.stencilBits = tstencilbits;
+ break;
+ }
+
+ if (!visinfo)
+ {
+ ri.Printf( PRINT_ALL, "Couldn't get a visual\n" );
+ return RSERR_INVALID_MODE;
+ }
+
+ /* window attributes */
+ attr.background_pixel = BlackPixel(dpy, scrnum);
+ attr.border_pixel = 0;
+ attr.colormap = XCreateColormap(dpy, root, visinfo->visual, AllocNone);
+ attr.event_mask = X_MASK;
+ if (vidmode_active)
+ {
+ mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore |
+ CWEventMask | CWOverrideRedirect;
+ attr.override_redirect = True;
+ attr.backing_store = NotUseful;
+ attr.save_under = False;
+ } else
+ mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
+
+ win = XCreateWindow(dpy, root, 0, 0,
+ actualWidth, actualHeight,
+ 0, visinfo->depth, InputOutput,
+ visinfo->visual, mask, &attr);
+
+ XStoreName( dpy, win, WINDOW_CLASS_NAME );
+
+ /* GH: Don't let the window be resized */
+ sizehints.flags = PMinSize | PMaxSize;
+ sizehints.min_width = sizehints.max_width = actualWidth;
+ sizehints.min_height = sizehints.max_height = actualHeight;
+
+ XSetWMNormalHints( dpy, win, &sizehints );
+
+ XMapWindow( dpy, win );
+
+ if (vidmode_active)
+ XMoveWindow(dpy, win, 0, 0);
+
+ XFlush(dpy);
+ XSync(dpy,False); // bk001130 - from cvs1.17 (mkv)
+ ctx = qglXCreateContext(dpy, visinfo, NULL, True);
+ XSync(dpy,False); // bk001130 - from cvs1.17 (mkv)
+
+ /* GH: Free the visinfo after we're done with it */
+ XFree( visinfo );
+
+ qglXMakeCurrent(dpy, win, ctx);
+
+ // bk001130 - from cvs1.17 (mkv)
+ glstring = qglGetString (GL_RENDERER);
+ ri.Printf( PRINT_ALL, "GL_RENDERER: %s\n", glstring );
+
+ // bk010122 - new software token (Indirect)
+ if ( !Q_stricmp( glstring, "Mesa X11")
+ || !Q_stricmp( glstring, "Mesa GLX Indirect") )
+ {
+ if ( !r_allowSoftwareGL->integer )
+ {
+ ri.Printf( PRINT_ALL, "\n\n***********************************************************\n" );
+ ri.Printf( PRINT_ALL, " You are using software Mesa (no hardware acceleration)! \n" );
+ ri.Printf( PRINT_ALL, " Driver DLL used: %s\n", drivername );
+ ri.Printf( PRINT_ALL, " If this is intentional, add\n" );
+ ri.Printf( PRINT_ALL, " \"+set r_allowSoftwareGL 1\"\n" );
+ ri.Printf( PRINT_ALL, " to the command line when starting the game.\n" );
+ ri.Printf( PRINT_ALL, "***********************************************************\n");
+ GLimp_Shutdown( );
+ return RSERR_INVALID_MODE;
+ } else
+ {
+ ri.Printf( PRINT_ALL, "...using software Mesa (r_allowSoftwareGL==1).\n" );
+ }
+ }
+
+ return RSERR_OK;
+}
+
+/*
+** GLW_InitExtensions
+*/
+static void GLW_InitExtensions( void )
+{
+ if ( !r_allowExtensions->integer )
+ {
+ ri.Printf( PRINT_ALL, "*** IGNORING OPENGL EXTENSIONS ***\n" );
+ return;
+ }
+
+ ri.Printf( PRINT_ALL, "Initializing OpenGL extensions\n" );
+
+ // GL_S3_s3tc
+ if ( Q_stristr( glConfig.extensions_string, "GL_S3_s3tc" ) )
+ {
+ if ( r_ext_compressed_textures->value )
+ {
+ glConfig.textureCompression = TC_S3TC;
+ ri.Printf( PRINT_ALL, "...using GL_S3_s3tc\n" );
+ } else
+ {
+ glConfig.textureCompression = TC_NONE;
+ ri.Printf( PRINT_ALL, "...ignoring GL_S3_s3tc\n" );
+ }
+ } else
+ {
+ glConfig.textureCompression = TC_NONE;
+ ri.Printf( PRINT_ALL, "...GL_S3_s3tc not found\n" );
+ }
+
+ // GL_EXT_texture_env_add
+ glConfig.textureEnvAddAvailable = qfalse;
+ if ( Q_stristr( glConfig.extensions_string, "EXT_texture_env_add" ) )
+ {
+ if ( r_ext_texture_env_add->integer )
+ {
+ glConfig.textureEnvAddAvailable = qtrue;
+ ri.Printf( PRINT_ALL, "...using GL_EXT_texture_env_add\n" );
+ } else
+ {
+ glConfig.textureEnvAddAvailable = qfalse;
+ ri.Printf( PRINT_ALL, "...ignoring GL_EXT_texture_env_add\n" );
+ }
+ } else
+ {
+ ri.Printf( PRINT_ALL, "...GL_EXT_texture_env_add not found\n" );
+ }
+
+ // GL_ARB_multitexture
+ qglMultiTexCoord2fARB = NULL;
+ qglActiveTextureARB = NULL;
+ qglClientActiveTextureARB = NULL;
+ if ( Q_stristr( glConfig.extensions_string, "GL_ARB_multitexture" ) )
+ {
+ if ( r_ext_multitexture->value )
+ {
+ qglMultiTexCoord2fARB = ( PFNGLMULTITEXCOORD2FARBPROC ) dlsym( glw_state.OpenGLLib, "glMultiTexCoord2fARB" );
+ qglActiveTextureARB = ( PFNGLACTIVETEXTUREARBPROC ) dlsym( glw_state.OpenGLLib, "glActiveTextureARB" );
+ qglClientActiveTextureARB = ( PFNGLCLIENTACTIVETEXTUREARBPROC ) dlsym( glw_state.OpenGLLib, "glClientActiveTextureARB" );
+
+ if ( qglActiveTextureARB )
+ {
+ qglGetIntegerv( GL_MAX_ACTIVE_TEXTURES_ARB, &glConfig.maxActiveTextures );
+
+ if ( glConfig.maxActiveTextures > 1 )
+ {
+ ri.Printf( PRINT_ALL, "...using GL_ARB_multitexture\n" );
+ } else
+ {
+ qglMultiTexCoord2fARB = NULL;
+ qglActiveTextureARB = NULL;
+ qglClientActiveTextureARB = NULL;
+ ri.Printf( PRINT_ALL, "...not using GL_ARB_multitexture, < 2 texture units\n" );
+ }
+ }
+ } else
+ {
+ ri.Printf( PRINT_ALL, "...ignoring GL_ARB_multitexture\n" );
+ }
+ } else
+ {
+ ri.Printf( PRINT_ALL, "...GL_ARB_multitexture not found\n" );
+ }
+
+ // GL_EXT_compiled_vertex_array
+ if ( Q_stristr( glConfig.extensions_string, "GL_EXT_compiled_vertex_array" ) )
+ {
+ if ( r_ext_compiled_vertex_array->value )
+ {
+ ri.Printf( PRINT_ALL, "...using GL_EXT_compiled_vertex_array\n" );
+ qglLockArraysEXT = ( void ( APIENTRY * )( int, int ) ) dlsym( glw_state.OpenGLLib, "glLockArraysEXT" );
+ qglUnlockArraysEXT = ( void ( APIENTRY * )( void ) ) dlsym( glw_state.OpenGLLib, "glUnlockArraysEXT" );
+ if (!qglLockArraysEXT || !qglUnlockArraysEXT)
+ {
+ ri.Error (ERR_FATAL, "bad getprocaddress");
+ }
+ } else
+ {
+ ri.Printf( PRINT_ALL, "...ignoring GL_EXT_compiled_vertex_array\n" );
+ }
+ } else
+ {
+ ri.Printf( PRINT_ALL, "...GL_EXT_compiled_vertex_array not found\n" );
+ }
+
+}
+
+static void GLW_InitGamma()
+{
+ /* Minimum extension version required */
+ #define GAMMA_MINMAJOR 2
+ #define GAMMA_MINMINOR 0
+
+ glConfig.deviceSupportsGamma = qfalse;
+
+ if (vidmode_ext)
+ {
+ if (vidmode_MajorVersion < GAMMA_MINMAJOR ||
+ (vidmode_MajorVersion == GAMMA_MINMAJOR && vidmode_MinorVersion < GAMMA_MINMINOR)) {
+ ri.Printf( PRINT_ALL, "XF86 Gamma extension not supported in this version\n");
+ return;
+ }
+ XF86VidModeGetGamma(dpy, scrnum, &vidmode_InitialGamma);
+ ri.Printf( PRINT_ALL, "XF86 Gamma extension initialized\n");
+ glConfig.deviceSupportsGamma = qtrue;
+ }
+}
+
+/*
+** GLW_LoadOpenGL
+**
+** GLimp_win.c internal function that that attempts to load and use
+** a specific OpenGL DLL.
+*/
+static qboolean GLW_LoadOpenGL( const char *name )
+{
+ qboolean fullscreen;
+
+ ri.Printf( PRINT_ALL, "...loading %s: ", name );
+
+ // disable the 3Dfx splash screen and set gamma
+ // we do this all the time, but it shouldn't hurt anything
+ // on non-3Dfx stuff
+ putenv("FX_GLIDE_NO_SPLASH=0");
+
+ // Mesa VooDoo hacks
+ putenv("MESA_GLX_FX=fullscreen\n");
+
+ // load the QGL layer
+ if ( QGL_Init( name ) )
+ {
+ fullscreen = r_fullscreen->integer;
+
+ // create the window and set up the context
+ if ( !GLW_StartDriverAndSetMode( name, r_mode->integer, fullscreen ) )
+ {
+ if (r_mode->integer != 3)
+ {
+ if ( !GLW_StartDriverAndSetMode( name, 3, fullscreen ) )
+ {
+ goto fail;
+ }
+ } else
+ goto fail;
+ }
+
+ return qtrue;
+ } else
+ {
+ ri.Printf( PRINT_ALL, "failed\n" );
+ }
+ fail:
+
+ QGL_Shutdown();
+
+ return qfalse;
+}
+
+/*
+** XErrorHandler
+** the default X error handler exits the application
+** I found out that on some hosts some operations would raise X errors (GLXUnsupportedPrivateRequest)
+** but those don't seem to be fatal .. so the default would be to just ignore them
+** our implementation mimics the default handler behaviour (not completely cause I'm lazy)
+*/
+int qXErrorHandler(Display *dpy, XErrorEvent *ev)
+{
+ static char buf[1024];
+ XGetErrorText(dpy, ev->error_code, buf, 1024);
+ ri.Printf( PRINT_ALL, "X Error of failed request: %s\n", buf);
+ ri.Printf( PRINT_ALL, " Major opcode of failed request: %d\n", ev->request_code, buf);
+ ri.Printf( PRINT_ALL, " Minor opcode of failed request: %d\n", ev->minor_code);
+ ri.Printf( PRINT_ALL, " Serial number of failed request: %d\n", ev->serial);
+ return 0;
+}
+
+/*
+** GLimp_Init
+**
+** This routine is responsible for initializing the OS specific portions
+** of OpenGL.
+*/
+void GLimp_Init( void )
+{
+ qboolean attemptedlibGL = qfalse;
+ qboolean attempted3Dfx = qfalse;
+ qboolean success = qfalse;
+ char buf[1024];
+ cvar_t *lastValidRenderer = ri.Cvar_Get( "r_lastValidRenderer", "(uninitialized)", CVAR_ARCHIVE );
+
+ // guarded, as this is only relevant to SMP renderer thread
+#ifdef SMP
+ if (!XInitThreads())
+ {
+ Com_Printf("GLimp_Init() - XInitThreads() failed, disabling r_smp\n");
+ ri.Cvar_Set( "r_smp", "0" );
+ }
+#endif
+
+ r_allowSoftwareGL = ri.Cvar_Get( "r_allowSoftwareGL", "0", CVAR_LATCH );
+
+ r_previousglDriver = ri.Cvar_Get( "r_previousglDriver", "", CVAR_ROM );
+
+ InitSig();
+
+ // Hack here so that if the UI
+ if ( *r_previousglDriver->string )
+ {
+ // The UI changed it on us, hack it back
+ // This means the renderer can't be changed on the fly
+ ri.Cvar_Set( "r_glDriver", r_previousglDriver->string );
+ }
+
+ // set up our custom error handler for X failures
+ XSetErrorHandler(&qXErrorHandler);
+
+ //
+ // load and initialize the specific OpenGL driver
+ //
+ if ( !GLW_LoadOpenGL( r_glDriver->string ) )
+ {
+ if ( !Q_stricmp( r_glDriver->string, OPENGL_DRIVER_NAME ) )
+ {
+ attemptedlibGL = qtrue;
+ } else if ( !Q_stricmp( r_glDriver->string, _3DFX_DRIVER_NAME ) )
+ {
+ attempted3Dfx = qtrue;
+ }
+
+ #if 0
+ // TTimo
+ // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=455
+ // old legacy load code, was confusing people who had a bad OpenGL setup
+ if ( !attempted3Dfx && !success )
+ {
+ attempted3Dfx = qtrue;
+ if ( GLW_LoadOpenGL( _3DFX_DRIVER_NAME ) )
+ {
+ ri.Cvar_Set( "r_glDriver", _3DFX_DRIVER_NAME );
+ r_glDriver->modified = qfalse;
+ success = qtrue;
+ }
+ }
+ #endif
+
+ // try ICD before trying 3Dfx standalone driver
+ if ( !attemptedlibGL && !success )
+ {
+ attemptedlibGL = qtrue;
+ if ( GLW_LoadOpenGL( OPENGL_DRIVER_NAME ) )
+ {
+ ri.Cvar_Set( "r_glDriver", OPENGL_DRIVER_NAME );
+ r_glDriver->modified = qfalse;
+ success = qtrue;
+ }
+ }
+
+ if (!success)
+ ri.Error( ERR_FATAL, "GLimp_Init() - could not load OpenGL subsystem\n" );
+
+ }
+
+ // Save it in case the UI stomps it
+ ri.Cvar_Set( "r_previousglDriver", r_glDriver->string );
+
+ // This values force the UI to disable driver selection
+ glConfig.driverType = GLDRV_ICD;
+ glConfig.hardwareType = GLHW_GENERIC;
+
+ // get our config strings
+ Q_strncpyz( glConfig.vendor_string, qglGetString (GL_VENDOR), sizeof( glConfig.vendor_string ) );
+ Q_strncpyz( glConfig.renderer_string, qglGetString (GL_RENDERER), sizeof( glConfig.renderer_string ) );
+ if (*glConfig.renderer_string && glConfig.renderer_string[strlen(glConfig.renderer_string) - 1] == '\n')
+ glConfig.renderer_string[strlen(glConfig.renderer_string) - 1] = 0;
+ Q_strncpyz( glConfig.version_string, qglGetString (GL_VERSION), sizeof( glConfig.version_string ) );
+ Q_strncpyz( glConfig.extensions_string, qglGetString (GL_EXTENSIONS), sizeof( glConfig.extensions_string ) );
+
+ //
+ // chipset specific configuration
+ //
+ strcpy( buf, glConfig.renderer_string );
+ strlwr( buf );
+
+ //
+ // NOTE: if changing cvars, do it within this block. This allows them
+ // to be overridden when testing driver fixes, etc. but only sets
+ // them to their default state when the hardware is first installed/run.
+ //
+ if ( Q_stricmp( lastValidRenderer->string, glConfig.renderer_string ) )
+ {
+ glConfig.hardwareType = GLHW_GENERIC;
+
+ ri.Cvar_Set( "r_textureMode", "GL_LINEAR_MIPMAP_NEAREST" );
+
+ // VOODOO GRAPHICS w/ 2MB
+ if ( Q_stristr( buf, "voodoo graphics/1 tmu/2 mb" ) )
+ {
+ ri.Cvar_Set( "r_picmip", "2" );
+ ri.Cvar_Get( "r_picmip", "1", CVAR_ARCHIVE | CVAR_LATCH );
+ } else
+ {
+ ri.Cvar_Set( "r_picmip", "1" );
+
+ if ( Q_stristr( buf, "rage 128" ) || Q_stristr( buf, "rage128" ) )
+ {
+ ri.Cvar_Set( "r_finish", "0" );
+ }
+ // Savage3D and Savage4 should always have trilinear enabled
+ else if ( Q_stristr( buf, "savage3d" ) || Q_stristr( buf, "s3 savage4" ) )
+ {
+ ri.Cvar_Set( "r_texturemode", "GL_LINEAR_MIPMAP_LINEAR" );
+ }
+ }
+ }
+
+ //
+ // this is where hardware specific workarounds that should be
+ // detected/initialized every startup should go.
+ //
+ if ( Q_stristr( buf, "banshee" ) || Q_stristr( buf, "Voodoo_Graphics" ) )
+ {
+ glConfig.hardwareType = GLHW_3DFX_2D3D;
+ } else if ( Q_stristr( buf, "rage pro" ) || Q_stristr( buf, "RagePro" ) )
+ {
+ glConfig.hardwareType = GLHW_RAGEPRO;
+ } else if ( Q_stristr( buf, "permedia2" ) )
+ {
+ glConfig.hardwareType = GLHW_PERMEDIA2;
+ } else if ( Q_stristr( buf, "riva 128" ) )
+ {
+ glConfig.hardwareType = GLHW_RIVA128;
+ } else if ( Q_stristr( buf, "riva tnt " ) )
+ {
+ }
+
+ ri.Cvar_Set( "r_lastValidRenderer", glConfig.renderer_string );
+
+ // initialize extensions
+ GLW_InitExtensions();
+ GLW_InitGamma();
+
+ InitSig(); // not clear why this is at begin & end of function
+
+ return;
+}
+
+
+/*
+** GLimp_EndFrame
+**
+** Responsible for doing a swapbuffers and possibly for other stuff
+** as yet to be determined. Probably better not to make this a GLimp
+** function and instead do a call to GLimp_SwapBuffers.
+*/
+void GLimp_EndFrame (void)
+{
+ // don't flip if drawing to front buffer
+ if ( stricmp( r_drawBuffer->string, "GL_FRONT" ) != 0 )
+ {
+ qglXSwapBuffers(dpy, win);
+ }
+
+ // check logging
+ QGL_EnableLogging( (qboolean)r_logFile->integer ); // bk001205 - was ->value
+}
+
+#ifdef SMP
+/*
+===========================================================
+
+SMP acceleration
+
+===========================================================
+*/
+
+static pthread_mutex_t smpMutex = PTHREAD_MUTEX_INITIALIZER;
+
+static pthread_cond_t renderCommandsEvent = PTHREAD_COND_INITIALIZER;
+static pthread_cond_t renderCompletedEvent = PTHREAD_COND_INITIALIZER;
+
+static void (*glimpRenderThread)( void );
+
+static void *GLimp_RenderThreadWrapper( void *arg )
+{
+ Com_Printf( "Render thread starting\n" );
+
+ glimpRenderThread();
+
+ qglXMakeCurrent( dpy, None, NULL );
+
+ Com_Printf( "Render thread terminating\n" );
+
+ return arg;
+}
+
+qboolean GLimp_SpawnRenderThread( void (*function)( void ) )
+{
+ pthread_t renderThread;
+ int ret;
+
+ pthread_mutex_init( &smpMutex, NULL );
+
+ pthread_cond_init( &renderCommandsEvent, NULL );
+ pthread_cond_init( &renderCompletedEvent, NULL );
+
+ glimpRenderThread = function;
+
+ ret = pthread_create( &renderThread,
+ NULL, // attributes
+ GLimp_RenderThreadWrapper,
+ NULL ); // argument
+ if ( ret ) {
+ ri.Printf( PRINT_ALL, "pthread_create returned %d: %s", ret, strerror( ret ) );
+ return qfalse;
+ } else {
+ ret = pthread_detach( renderThread );
+ if ( ret ) {
+ ri.Printf( PRINT_ALL, "pthread_detach returned %d: %s", ret, strerror( ret ) );
+ }
+ }
+
+ return qtrue;
+}
+
+static volatile void *smpData = NULL;
+static volatile qboolean smpDataReady;
+
+void *GLimp_RendererSleep( void )
+{
+ void *data;
+
+ qglXMakeCurrent( dpy, None, NULL );
+
+ pthread_mutex_lock( &smpMutex );
+ {
+ smpData = NULL;
+ smpDataReady = qfalse;
+
+ // after this, the front end can exit GLimp_FrontEndSleep
+ pthread_cond_signal( &renderCompletedEvent );
+
+ while ( !smpDataReady ) {
+ pthread_cond_wait( &renderCommandsEvent, &smpMutex );
+ }
+
+ data = (void *)smpData;
+ }
+ pthread_mutex_unlock( &smpMutex );
+
+ qglXMakeCurrent( dpy, win, ctx );
+
+ return data;
+}
+
+void GLimp_FrontEndSleep( void )
+{
+ pthread_mutex_lock( &smpMutex );
+ {
+ while ( smpData ) {
+ pthread_cond_wait( &renderCompletedEvent, &smpMutex );
+ }
+ }
+ pthread_mutex_unlock( &smpMutex );
+
+ qglXMakeCurrent( dpy, win, ctx );
+}
+
+void GLimp_WakeRenderer( void *data )
+{
+ qglXMakeCurrent( dpy, None, NULL );
+
+ pthread_mutex_lock( &smpMutex );
+ {
+ assert( smpData == NULL );
+ smpData = data;
+ smpDataReady = qtrue;
+
+ // after this, the renderer can continue through GLimp_RendererSleep
+ pthread_cond_signal( &renderCommandsEvent );
+ }
+ pthread_mutex_unlock( &smpMutex );
+}
+
+#else
+
+void GLimp_RenderThreadWrapper( void *stub ) {}
+qboolean GLimp_SpawnRenderThread( void (*function)( void ) ) {
+ ri.Printf( PRINT_WARNING, "ERROR: SMP support was disabled at compile time\n");
+ return qfalse;
+}
+void *GLimp_RendererSleep( void ) {
+ return NULL;
+}
+void GLimp_FrontEndSleep( void ) {}
+void GLimp_WakeRenderer( void *data ) {}
+
+#endif
+
+/*****************************************************************************/
+/* MOUSE */
+/*****************************************************************************/
+
+void IN_Init(void) {
+ Com_Printf ("\n------- Input Initialization -------\n");
+ // mouse variables
+ in_mouse = Cvar_Get ("in_mouse", "1", CVAR_ARCHIVE);
+ in_dgamouse = Cvar_Get ("in_dgamouse", "1", CVAR_ARCHIVE);
+
+ // turn on-off sub-frame timing of X events
+ in_subframe = Cvar_Get ("in_subframe", "1", CVAR_ARCHIVE);
+
+ // developer feature, allows to break without loosing mouse pointer
+ in_nograb = Cvar_Get ("in_nograb", "0", 0);
+
+ // bk001130 - from cvs.17 (mkv), joystick variables
+ in_joystick = Cvar_Get ("in_joystick", "0", CVAR_ARCHIVE|CVAR_LATCH);
+ // bk001130 - changed this to match win32
+ in_joystickDebug = Cvar_Get ("in_debugjoystick", "0", CVAR_TEMP);
+ joy_threshold = Cvar_Get ("joy_threshold", "0.15", CVAR_ARCHIVE); // FIXME: in_joythreshold
+
+ if (in_mouse->value)
+ mouse_avail = qtrue;
+ else
+ mouse_avail = qfalse;
+
+ IN_StartupJoystick( ); // bk001130 - from cvs1.17 (mkv)
+ Com_Printf ("------------------------------------\n");
+}
+
+void IN_Shutdown(void)
+{
+ mouse_avail = qfalse;
+}
+
+void IN_Frame (void) {
+
+ // bk001130 - from cvs 1.17 (mkv)
+ IN_JoyMove(); // FIXME: disable if on desktop?
+
+ if ( cls.keyCatchers & KEYCATCH_CONSOLE )
+ {
+ // temporarily deactivate if not in the game and
+ // running on the desktop
+ // voodoo always counts as full screen
+ if (Cvar_VariableValue ("r_fullscreen") == 0
+ && strcmp( Cvar_VariableString("r_glDriver"), _3DFX_DRIVER_NAME ) )
+ {
+ IN_DeactivateMouse ();
+ return;
+ }
+ }
+
+ IN_ActivateMouse();
+}
+
+void IN_Activate(void)
+{
+}
+
+// bk001130 - cvs1.17 joystick code (mkv) was here, no linux_joystick.c
+
+void Sys_SendKeyEvents (void) {
+ // XEvent event; // bk001204 - unused
+
+ if (!dpy)
+ return;
+ HandleEvents();
+}
+
+
+// bk010216 - added stubs for non-Linux UNIXes here
+// FIXME - use NO_JOYSTICK or something else generic
+
+#if defined( __FreeBSD__ ) // rb010123
+void IN_StartupJoystick( void ) {}
+void IN_JoyMove( void ) {}
+#endif
diff --git a/code/unix/linux_joystick.c b/code/unix/linux_joystick.c
new file mode 100755
index 0000000..f287e8b
--- /dev/null
+++ b/code/unix/linux_joystick.c
@@ -0,0 +1,207 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+/*
+** linux_joystick.c
+**
+** This file contains ALL Linux specific stuff having to do with the
+** Joystick input. When a port is being made the following functions
+** must be implemented by the port:
+**
+** Authors: mkv, bk
+**
+*/
+
+#include <linux/joystick.h>
+#include <sys/types.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
+#include <unistd.h> // bk001204
+
+
+#include "../client/client.h"
+#include "linux_local.h"
+
+/* We translate axes movement into keypresses. */
+int joy_keys[16] = {
+ K_LEFTARROW, K_RIGHTARROW,
+ K_UPARROW, K_DOWNARROW,
+ K_JOY16, K_JOY17,
+ K_JOY18, K_JOY19,
+ K_JOY20, K_JOY21,
+ K_JOY22, K_JOY23,
+
+ K_JOY24, K_JOY25,
+ K_JOY26, K_JOY27
+};
+
+/* Our file descriptor for the joystick device. */
+static int joy_fd = -1;
+
+
+// bk001130 - from linux_glimp.c
+extern cvar_t * in_joystick;
+extern cvar_t * in_joystickDebug;
+extern cvar_t * joy_threshold;
+
+
+/**********************************************/
+/* Joystick routines. */
+/**********************************************/
+// bk001130 - from cvs1.17 (mkv), removed from linux_glimp.c
+void IN_StartupJoystick( void )
+{
+ int i = 0;
+
+ joy_fd = -1;
+
+ if( !in_joystick->integer ) {
+ Com_Printf( "Joystick is not active.\n" );
+ return;
+ }
+
+ for( i = 0; i < 4; i++ ) {
+ char filename[PATH_MAX];
+
+ snprintf( filename, PATH_MAX, "/dev/js%d", i );
+
+ joy_fd = open( filename, O_RDONLY | O_NONBLOCK );
+
+ if( joy_fd != -1 ) {
+ struct js_event event;
+ char axes = 0;
+ char buttons = 0;
+ char name[128];
+ int n = -1;
+
+ Com_Printf( "Joystick %s found\n", filename );
+
+ /* Get rid of initialization messages. */
+ do {
+ n = read( joy_fd, &event, sizeof( event ) );
+
+ if( n == -1 ) {
+ break;
+ }
+
+ } while( ( event.type & JS_EVENT_INIT ) );
+
+ /* Get joystick statistics. */
+ ioctl( joy_fd, JSIOCGAXES, &axes );
+ ioctl( joy_fd, JSIOCGBUTTONS, &buttons );
+
+ if( ioctl( joy_fd, JSIOCGNAME( sizeof( name ) ), name ) < 0 ) {
+ strncpy( name, "Unknown", sizeof( name ) );
+ }
+
+ Com_Printf( "Name: %s\n", name );
+ Com_Printf( "Axes: %d\n", axes );
+ Com_Printf( "Buttons: %d\n", buttons );
+
+ /* Our work here is done. */
+ return;
+ }
+
+ }
+
+ /* No soup for you. */
+ if( joy_fd == -1 ) {
+ Com_Printf( "No joystick found.\n" );
+ return;
+ }
+
+}
+
+void IN_JoyMove( void )
+{
+ /* Store instantaneous joystick state. Hack to get around
+ * event model used in Linux joystick driver.
+ */
+ static int axes_state[16];
+ /* Old bits for Quake-style input compares. */
+ static unsigned int old_axes = 0;
+ /* Our current goodies. */
+ unsigned int axes = 0;
+ int i = 0;
+
+ if( joy_fd == -1 ) {
+ return;
+ }
+
+ /* Empty the queue, dispatching button presses immediately
+ * and updating the instantaneous state for the axes.
+ */
+ do {
+ int n = -1;
+ struct js_event event;
+
+ n = read( joy_fd, &event, sizeof( event ) );
+
+ if( n == -1 ) {
+ /* No error, we're non-blocking. */
+ break;
+ }
+
+ if( event.type & JS_EVENT_BUTTON ) {
+ Sys_QueEvent( 0, SE_KEY, K_JOY1 + event.number, event.value, 0, NULL );
+ } else if( event.type & JS_EVENT_AXIS ) {
+
+ if( event.number >= 16 ) {
+ continue;
+ }
+
+ axes_state[event.number] = event.value;
+ } else {
+ Com_Printf( "Unknown joystick event type\n" );
+ }
+
+ } while( 1 );
+
+
+ /* Translate our instantaneous state to bits. */
+ for( i = 0; i < 16; i++ ) {
+ float f = ( (float) axes_state[i] ) / 32767.0f;
+
+ if( f < -joy_threshold->value ) {
+ axes |= ( 1 << ( i * 2 ) );
+ } else if( f > joy_threshold->value ) {
+ axes |= ( 1 << ( ( i * 2 ) + 1 ) );
+ }
+
+ }
+
+ /* Time to update axes state based on old vs. new. */
+ for( i = 0; i < 16; i++ ) {
+
+ if( ( axes & ( 1 << i ) ) && !( old_axes & ( 1 << i ) ) ) {
+ Sys_QueEvent( 0, SE_KEY, joy_keys[i], qtrue, 0, NULL );
+ }
+
+ if( !( axes & ( 1 << i ) ) && ( old_axes & ( 1 << i ) ) ) {
+ Sys_QueEvent( 0, SE_KEY, joy_keys[i], qfalse, 0, NULL );
+ }
+ }
+
+ /* Save for future generations. */
+ old_axes = axes;
+}
+
+
diff --git a/code/unix/linux_local.h b/code/unix/linux_local.h
new file mode 100755
index 0000000..6d2d619
--- /dev/null
+++ b/code/unix/linux_local.h
@@ -0,0 +1,49 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// linux_local.h: Linux-specific Quake3 header file
+
+void Sys_QueEvent( int time, sysEventType_t type, int value, int value2, int ptrLength, void *ptr );
+qboolean Sys_GetPacket ( netadr_t *net_from, msg_t *net_message );
+void Sys_SendKeyEvents (void);
+
+// Input subsystem
+
+void IN_Init (void);
+void IN_Frame (void);
+void IN_Shutdown (void);
+
+
+void IN_JoyMove( void );
+void IN_StartupJoystick( void );
+
+// GL subsystem
+qboolean QGL_Init( const char *dllname );
+void QGL_EnableLogging( qboolean enable );
+void QGL_Shutdown( void );
+
+// bk001130 - win32
+// void IN_JoystickCommands (void);
+
+char *strlwr (char *s);
+
+// signals.c
+void InitSig(void);
diff --git a/code/unix/linux_qgl.c b/code/unix/linux_qgl.c
new file mode 100755
index 0000000..aa49f80
--- /dev/null
+++ b/code/unix/linux_qgl.c
@@ -0,0 +1,4153 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+/*
+** LINUX_QGL.C
+**
+** This file implements the operating system binding of GL to QGL function
+** pointers. When doing a port of Quake2 you must implement the following
+** two functions:
+**
+** QGL_Init() - loads libraries, assigns function pointers, etc.
+** QGL_Shutdown() - unloads libraries, NULLs function pointers
+*/
+
+// bk001204
+#include <unistd.h>
+#include <sys/types.h>
+
+
+#include <float.h>
+#include "../renderer/tr_local.h"
+#include "unix_glw.h"
+
+// bk001129 - from cvs1.17 (mkv)
+//#if defined(__FX__)
+//#include <GL/fxmesa.h>
+//#endif
+//#include <GL/glx.h> // bk010216 - FIXME: all of the above redundant? renderer/qgl.h
+
+#include <dlfcn.h>
+
+
+// bk001129 - from cvs1.17 (mkv)
+#if defined(__FX__)
+//FX Mesa Functions
+fxMesaContext (*qfxMesaCreateContext)(GLuint win, GrScreenResolution_t, GrScreenRefresh_t, const GLint attribList[]);
+fxMesaContext (*qfxMesaCreateBestContext)(GLuint win, GLint width, GLint height, const GLint attribList[]);
+void (*qfxMesaDestroyContext)(fxMesaContext ctx);
+void (*qfxMesaMakeCurrent)(fxMesaContext ctx);
+fxMesaContext (*qfxMesaGetCurrentContext)(void);
+void (*qfxMesaSwapBuffers)(void);
+#endif
+
+//GLX Functions
+XVisualInfo * (*qglXChooseVisual)( Display *dpy, int screen, int *attribList );
+GLXContext (*qglXCreateContext)( Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct );
+void (*qglXDestroyContext)( Display *dpy, GLXContext ctx );
+Bool (*qglXMakeCurrent)( Display *dpy, GLXDrawable drawable, GLXContext ctx);
+void (*qglXCopyContext)( Display *dpy, GLXContext src, GLXContext dst, GLuint mask );
+void (*qglXSwapBuffers)( Display *dpy, GLXDrawable drawable );
+
+void ( APIENTRY * qglAccum )(GLenum op, GLfloat value);
+void ( APIENTRY * qglAlphaFunc )(GLenum func, GLclampf ref);
+GLboolean ( APIENTRY * qglAreTexturesResident )(GLsizei n, const GLuint *textures, GLboolean *residences);
+void ( APIENTRY * qglArrayElement )(GLint i);
+void ( APIENTRY * qglBegin )(GLenum mode);
+void ( APIENTRY * qglBindTexture )(GLenum target, GLuint texture);
+void ( APIENTRY * qglBitmap )(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap);
+void ( APIENTRY * qglBlendFunc )(GLenum sfactor, GLenum dfactor);
+void ( APIENTRY * qglCallList )(GLuint list);
+void ( APIENTRY * qglCallLists )(GLsizei n, GLenum type, const GLvoid *lists);
+void ( APIENTRY * qglClear )(GLbitfield mask);
+void ( APIENTRY * qglClearAccum )(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+void ( APIENTRY * qglClearColor )(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+void ( APIENTRY * qglClearDepth )(GLclampd depth);
+void ( APIENTRY * qglClearIndex )(GLfloat c);
+void ( APIENTRY * qglClearStencil )(GLint s);
+void ( APIENTRY * qglClipPlane )(GLenum plane, const GLdouble *equation);
+void ( APIENTRY * qglColor3b )(GLbyte red, GLbyte green, GLbyte blue);
+void ( APIENTRY * qglColor3bv )(const GLbyte *v);
+void ( APIENTRY * qglColor3d )(GLdouble red, GLdouble green, GLdouble blue);
+void ( APIENTRY * qglColor3dv )(const GLdouble *v);
+void ( APIENTRY * qglColor3f )(GLfloat red, GLfloat green, GLfloat blue);
+void ( APIENTRY * qglColor3fv )(const GLfloat *v);
+void ( APIENTRY * qglColor3i )(GLint red, GLint green, GLint blue);
+void ( APIENTRY * qglColor3iv )(const GLint *v);
+void ( APIENTRY * qglColor3s )(GLshort red, GLshort green, GLshort blue);
+void ( APIENTRY * qglColor3sv )(const GLshort *v);
+void ( APIENTRY * qglColor3ub )(GLubyte red, GLubyte green, GLubyte blue);
+void ( APIENTRY * qglColor3ubv )(const GLubyte *v);
+void ( APIENTRY * qglColor3ui )(GLuint red, GLuint green, GLuint blue);
+void ( APIENTRY * qglColor3uiv )(const GLuint *v);
+void ( APIENTRY * qglColor3us )(GLushort red, GLushort green, GLushort blue);
+void ( APIENTRY * qglColor3usv )(const GLushort *v);
+void ( APIENTRY * qglColor4b )(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha);
+void ( APIENTRY * qglColor4bv )(const GLbyte *v);
+void ( APIENTRY * qglColor4d )(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha);
+void ( APIENTRY * qglColor4dv )(const GLdouble *v);
+void ( APIENTRY * qglColor4f )(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+void ( APIENTRY * qglColor4fv )(const GLfloat *v);
+void ( APIENTRY * qglColor4i )(GLint red, GLint green, GLint blue, GLint alpha);
+void ( APIENTRY * qglColor4iv )(const GLint *v);
+void ( APIENTRY * qglColor4s )(GLshort red, GLshort green, GLshort blue, GLshort alpha);
+void ( APIENTRY * qglColor4sv )(const GLshort *v);
+void ( APIENTRY * qglColor4ub )(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha);
+void ( APIENTRY * qglColor4ubv )(const GLubyte *v);
+void ( APIENTRY * qglColor4ui )(GLuint red, GLuint green, GLuint blue, GLuint alpha);
+void ( APIENTRY * qglColor4uiv )(const GLuint *v);
+void ( APIENTRY * qglColor4us )(GLushort red, GLushort green, GLushort blue, GLushort alpha);
+void ( APIENTRY * qglColor4usv )(const GLushort *v);
+void ( APIENTRY * qglColorMask )(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
+void ( APIENTRY * qglColorMaterial )(GLenum face, GLenum mode);
+void ( APIENTRY * qglColorPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+void ( APIENTRY * qglCopyPixels )(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type);
+void ( APIENTRY * qglCopyTexImage1D )(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLint border);
+void ( APIENTRY * qglCopyTexImage2D )(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+void ( APIENTRY * qglCopyTexSubImage1D )(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
+void ( APIENTRY * qglCopyTexSubImage2D )(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+void ( APIENTRY * qglCullFace )(GLenum mode);
+void ( APIENTRY * qglDeleteLists )(GLuint list, GLsizei range);
+void ( APIENTRY * qglDeleteTextures )(GLsizei n, const GLuint *textures);
+void ( APIENTRY * qglDepthFunc )(GLenum func);
+void ( APIENTRY * qglDepthMask )(GLboolean flag);
+void ( APIENTRY * qglDepthRange )(GLclampd zNear, GLclampd zFar);
+void ( APIENTRY * qglDisable )(GLenum cap);
+void ( APIENTRY * qglDisableClientState )(GLenum array);
+void ( APIENTRY * qglDrawArrays )(GLenum mode, GLint first, GLsizei count);
+void ( APIENTRY * qglDrawBuffer )(GLenum mode);
+void ( APIENTRY * qglDrawElements )(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices);
+void ( APIENTRY * qglDrawPixels )(GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+void ( APIENTRY * qglEdgeFlag )(GLboolean flag);
+void ( APIENTRY * qglEdgeFlagPointer )(GLsizei stride, const GLvoid *pointer);
+void ( APIENTRY * qglEdgeFlagv )(const GLboolean *flag);
+void ( APIENTRY * qglEnable )(GLenum cap);
+void ( APIENTRY * qglEnableClientState )(GLenum array);
+void ( APIENTRY * qglEnd )(void);
+void ( APIENTRY * qglEndList )(void);
+void ( APIENTRY * qglEvalCoord1d )(GLdouble u);
+void ( APIENTRY * qglEvalCoord1dv )(const GLdouble *u);
+void ( APIENTRY * qglEvalCoord1f )(GLfloat u);
+void ( APIENTRY * qglEvalCoord1fv )(const GLfloat *u);
+void ( APIENTRY * qglEvalCoord2d )(GLdouble u, GLdouble v);
+void ( APIENTRY * qglEvalCoord2dv )(const GLdouble *u);
+void ( APIENTRY * qglEvalCoord2f )(GLfloat u, GLfloat v);
+void ( APIENTRY * qglEvalCoord2fv )(const GLfloat *u);
+void ( APIENTRY * qglEvalMesh1 )(GLenum mode, GLint i1, GLint i2);
+void ( APIENTRY * qglEvalMesh2 )(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2);
+void ( APIENTRY * qglEvalPoint1 )(GLint i);
+void ( APIENTRY * qglEvalPoint2 )(GLint i, GLint j);
+void ( APIENTRY * qglFeedbackBuffer )(GLsizei size, GLenum type, GLfloat *buffer);
+void ( APIENTRY * qglFinish )(void);
+void ( APIENTRY * qglFlush )(void);
+void ( APIENTRY * qglFogf )(GLenum pname, GLfloat param);
+void ( APIENTRY * qglFogfv )(GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglFogi )(GLenum pname, GLint param);
+void ( APIENTRY * qglFogiv )(GLenum pname, const GLint *params);
+void ( APIENTRY * qglFrontFace )(GLenum mode);
+void ( APIENTRY * qglFrustum )(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+GLuint ( APIENTRY * qglGenLists )(GLsizei range);
+void ( APIENTRY * qglGenTextures )(GLsizei n, GLuint *textures);
+void ( APIENTRY * qglGetBooleanv )(GLenum pname, GLboolean *params);
+void ( APIENTRY * qglGetClipPlane )(GLenum plane, GLdouble *equation);
+void ( APIENTRY * qglGetDoublev )(GLenum pname, GLdouble *params);
+GLenum ( APIENTRY * qglGetError )(void);
+void ( APIENTRY * qglGetFloatv )(GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetIntegerv )(GLenum pname, GLint *params);
+void ( APIENTRY * qglGetLightfv )(GLenum light, GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetLightiv )(GLenum light, GLenum pname, GLint *params);
+void ( APIENTRY * qglGetMapdv )(GLenum target, GLenum query, GLdouble *v);
+void ( APIENTRY * qglGetMapfv )(GLenum target, GLenum query, GLfloat *v);
+void ( APIENTRY * qglGetMapiv )(GLenum target, GLenum query, GLint *v);
+void ( APIENTRY * qglGetMaterialfv )(GLenum face, GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetMaterialiv )(GLenum face, GLenum pname, GLint *params);
+void ( APIENTRY * qglGetPixelMapfv )(GLenum map, GLfloat *values);
+void ( APIENTRY * qglGetPixelMapuiv )(GLenum map, GLuint *values);
+void ( APIENTRY * qglGetPixelMapusv )(GLenum map, GLushort *values);
+void ( APIENTRY * qglGetPointerv )(GLenum pname, GLvoid* *params);
+void ( APIENTRY * qglGetPolygonStipple )(GLubyte *mask);
+const GLubyte * ( APIENTRY * qglGetString )(GLenum name);
+void ( APIENTRY * qglGetTexEnvfv )(GLenum target, GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetTexEnviv )(GLenum target, GLenum pname, GLint *params);
+void ( APIENTRY * qglGetTexGendv )(GLenum coord, GLenum pname, GLdouble *params);
+void ( APIENTRY * qglGetTexGenfv )(GLenum coord, GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetTexGeniv )(GLenum coord, GLenum pname, GLint *params);
+void ( APIENTRY * qglGetTexImage )(GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels);
+void ( APIENTRY * qglGetTexLevelParameterfv )(GLenum target, GLint level, GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetTexLevelParameteriv )(GLenum target, GLint level, GLenum pname, GLint *params);
+void ( APIENTRY * qglGetTexParameterfv )(GLenum target, GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetTexParameteriv )(GLenum target, GLenum pname, GLint *params);
+void ( APIENTRY * qglHint )(GLenum target, GLenum mode);
+void ( APIENTRY * qglIndexMask )(GLuint mask);
+void ( APIENTRY * qglIndexPointer )(GLenum type, GLsizei stride, const GLvoid *pointer);
+void ( APIENTRY * qglIndexd )(GLdouble c);
+void ( APIENTRY * qglIndexdv )(const GLdouble *c);
+void ( APIENTRY * qglIndexf )(GLfloat c);
+void ( APIENTRY * qglIndexfv )(const GLfloat *c);
+void ( APIENTRY * qglIndexi )(GLint c);
+void ( APIENTRY * qglIndexiv )(const GLint *c);
+void ( APIENTRY * qglIndexs )(GLshort c);
+void ( APIENTRY * qglIndexsv )(const GLshort *c);
+void ( APIENTRY * qglIndexub )(GLubyte c);
+void ( APIENTRY * qglIndexubv )(const GLubyte *c);
+void ( APIENTRY * qglInitNames )(void);
+void ( APIENTRY * qglInterleavedArrays )(GLenum format, GLsizei stride, const GLvoid *pointer);
+GLboolean ( APIENTRY * qglIsEnabled )(GLenum cap);
+GLboolean ( APIENTRY * qglIsList )(GLuint list);
+GLboolean ( APIENTRY * qglIsTexture )(GLuint texture);
+void ( APIENTRY * qglLightModelf )(GLenum pname, GLfloat param);
+void ( APIENTRY * qglLightModelfv )(GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglLightModeli )(GLenum pname, GLint param);
+void ( APIENTRY * qglLightModeliv )(GLenum pname, const GLint *params);
+void ( APIENTRY * qglLightf )(GLenum light, GLenum pname, GLfloat param);
+void ( APIENTRY * qglLightfv )(GLenum light, GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglLighti )(GLenum light, GLenum pname, GLint param);
+void ( APIENTRY * qglLightiv )(GLenum light, GLenum pname, const GLint *params);
+void ( APIENTRY * qglLineStipple )(GLint factor, GLushort pattern);
+void ( APIENTRY * qglLineWidth )(GLfloat width);
+void ( APIENTRY * qglListBase )(GLuint base);
+void ( APIENTRY * qglLoadIdentity )(void);
+void ( APIENTRY * qglLoadMatrixd )(const GLdouble *m);
+void ( APIENTRY * qglLoadMatrixf )(const GLfloat *m);
+void ( APIENTRY * qglLoadName )(GLuint name);
+void ( APIENTRY * qglLogicOp )(GLenum opcode);
+void ( APIENTRY * qglMap1d )(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points);
+void ( APIENTRY * qglMap1f )(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points);
+void ( APIENTRY * qglMap2d )(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points);
+void ( APIENTRY * qglMap2f )(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points);
+void ( APIENTRY * qglMapGrid1d )(GLint un, GLdouble u1, GLdouble u2);
+void ( APIENTRY * qglMapGrid1f )(GLint un, GLfloat u1, GLfloat u2);
+void ( APIENTRY * qglMapGrid2d )(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2);
+void ( APIENTRY * qglMapGrid2f )(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2);
+void ( APIENTRY * qglMaterialf )(GLenum face, GLenum pname, GLfloat param);
+void ( APIENTRY * qglMaterialfv )(GLenum face, GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglMateriali )(GLenum face, GLenum pname, GLint param);
+void ( APIENTRY * qglMaterialiv )(GLenum face, GLenum pname, const GLint *params);
+void ( APIENTRY * qglMatrixMode )(GLenum mode);
+void ( APIENTRY * qglMultMatrixd )(const GLdouble *m);
+void ( APIENTRY * qglMultMatrixf )(const GLfloat *m);
+void ( APIENTRY * qglNewList )(GLuint list, GLenum mode);
+void ( APIENTRY * qglNormal3b )(GLbyte nx, GLbyte ny, GLbyte nz);
+void ( APIENTRY * qglNormal3bv )(const GLbyte *v);
+void ( APIENTRY * qglNormal3d )(GLdouble nx, GLdouble ny, GLdouble nz);
+void ( APIENTRY * qglNormal3dv )(const GLdouble *v);
+void ( APIENTRY * qglNormal3f )(GLfloat nx, GLfloat ny, GLfloat nz);
+void ( APIENTRY * qglNormal3fv )(const GLfloat *v);
+void ( APIENTRY * qglNormal3i )(GLint nx, GLint ny, GLint nz);
+void ( APIENTRY * qglNormal3iv )(const GLint *v);
+void ( APIENTRY * qglNormal3s )(GLshort nx, GLshort ny, GLshort nz);
+void ( APIENTRY * qglNormal3sv )(const GLshort *v);
+void ( APIENTRY * qglNormalPointer )(GLenum type, GLsizei stride, const GLvoid *pointer);
+void ( APIENTRY * qglOrtho )(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+void ( APIENTRY * qglPassThrough )(GLfloat token);
+void ( APIENTRY * qglPixelMapfv )(GLenum map, GLsizei mapsize, const GLfloat *values);
+void ( APIENTRY * qglPixelMapuiv )(GLenum map, GLsizei mapsize, const GLuint *values);
+void ( APIENTRY * qglPixelMapusv )(GLenum map, GLsizei mapsize, const GLushort *values);
+void ( APIENTRY * qglPixelStoref )(GLenum pname, GLfloat param);
+void ( APIENTRY * qglPixelStorei )(GLenum pname, GLint param);
+void ( APIENTRY * qglPixelTransferf )(GLenum pname, GLfloat param);
+void ( APIENTRY * qglPixelTransferi )(GLenum pname, GLint param);
+void ( APIENTRY * qglPixelZoom )(GLfloat xfactor, GLfloat yfactor);
+void ( APIENTRY * qglPointSize )(GLfloat size);
+void ( APIENTRY * qglPolygonMode )(GLenum face, GLenum mode);
+void ( APIENTRY * qglPolygonOffset )(GLfloat factor, GLfloat units);
+void ( APIENTRY * qglPolygonStipple )(const GLubyte *mask);
+void ( APIENTRY * qglPopAttrib )(void);
+void ( APIENTRY * qglPopClientAttrib )(void);
+void ( APIENTRY * qglPopMatrix )(void);
+void ( APIENTRY * qglPopName )(void);
+void ( APIENTRY * qglPrioritizeTextures )(GLsizei n, const GLuint *textures, const GLclampf *priorities);
+void ( APIENTRY * qglPushAttrib )(GLbitfield mask);
+void ( APIENTRY * qglPushClientAttrib )(GLbitfield mask);
+void ( APIENTRY * qglPushMatrix )(void);
+void ( APIENTRY * qglPushName )(GLuint name);
+void ( APIENTRY * qglRasterPos2d )(GLdouble x, GLdouble y);
+void ( APIENTRY * qglRasterPos2dv )(const GLdouble *v);
+void ( APIENTRY * qglRasterPos2f )(GLfloat x, GLfloat y);
+void ( APIENTRY * qglRasterPos2fv )(const GLfloat *v);
+void ( APIENTRY * qglRasterPos2i )(GLint x, GLint y);
+void ( APIENTRY * qglRasterPos2iv )(const GLint *v);
+void ( APIENTRY * qglRasterPos2s )(GLshort x, GLshort y);
+void ( APIENTRY * qglRasterPos2sv )(const GLshort *v);
+void ( APIENTRY * qglRasterPos3d )(GLdouble x, GLdouble y, GLdouble z);
+void ( APIENTRY * qglRasterPos3dv )(const GLdouble *v);
+void ( APIENTRY * qglRasterPos3f )(GLfloat x, GLfloat y, GLfloat z);
+void ( APIENTRY * qglRasterPos3fv )(const GLfloat *v);
+void ( APIENTRY * qglRasterPos3i )(GLint x, GLint y, GLint z);
+void ( APIENTRY * qglRasterPos3iv )(const GLint *v);
+void ( APIENTRY * qglRasterPos3s )(GLshort x, GLshort y, GLshort z);
+void ( APIENTRY * qglRasterPos3sv )(const GLshort *v);
+void ( APIENTRY * qglRasterPos4d )(GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+void ( APIENTRY * qglRasterPos4dv )(const GLdouble *v);
+void ( APIENTRY * qglRasterPos4f )(GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+void ( APIENTRY * qglRasterPos4fv )(const GLfloat *v);
+void ( APIENTRY * qglRasterPos4i )(GLint x, GLint y, GLint z, GLint w);
+void ( APIENTRY * qglRasterPos4iv )(const GLint *v);
+void ( APIENTRY * qglRasterPos4s )(GLshort x, GLshort y, GLshort z, GLshort w);
+void ( APIENTRY * qglRasterPos4sv )(const GLshort *v);
+void ( APIENTRY * qglReadBuffer )(GLenum mode);
+void ( APIENTRY * qglReadPixels )(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels);
+void ( APIENTRY * qglRectd )(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2);
+void ( APIENTRY * qglRectdv )(const GLdouble *v1, const GLdouble *v2);
+void ( APIENTRY * qglRectf )(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2);
+void ( APIENTRY * qglRectfv )(const GLfloat *v1, const GLfloat *v2);
+void ( APIENTRY * qglRecti )(GLint x1, GLint y1, GLint x2, GLint y2);
+void ( APIENTRY * qglRectiv )(const GLint *v1, const GLint *v2);
+void ( APIENTRY * qglRects )(GLshort x1, GLshort y1, GLshort x2, GLshort y2);
+void ( APIENTRY * qglRectsv )(const GLshort *v1, const GLshort *v2);
+GLint ( APIENTRY * qglRenderMode )(GLenum mode);
+void ( APIENTRY * qglRotated )(GLdouble angle, GLdouble x, GLdouble y, GLdouble z);
+void ( APIENTRY * qglRotatef )(GLfloat angle, GLfloat x, GLfloat y, GLfloat z);
+void ( APIENTRY * qglScaled )(GLdouble x, GLdouble y, GLdouble z);
+void ( APIENTRY * qglScalef )(GLfloat x, GLfloat y, GLfloat z);
+void ( APIENTRY * qglScissor )(GLint x, GLint y, GLsizei width, GLsizei height);
+void ( APIENTRY * qglSelectBuffer )(GLsizei size, GLuint *buffer);
+void ( APIENTRY * qglShadeModel )(GLenum mode);
+void ( APIENTRY * qglStencilFunc )(GLenum func, GLint ref, GLuint mask);
+void ( APIENTRY * qglStencilMask )(GLuint mask);
+void ( APIENTRY * qglStencilOp )(GLenum fail, GLenum zfail, GLenum zpass);
+void ( APIENTRY * qglTexCoord1d )(GLdouble s);
+void ( APIENTRY * qglTexCoord1dv )(const GLdouble *v);
+void ( APIENTRY * qglTexCoord1f )(GLfloat s);
+void ( APIENTRY * qglTexCoord1fv )(const GLfloat *v);
+void ( APIENTRY * qglTexCoord1i )(GLint s);
+void ( APIENTRY * qglTexCoord1iv )(const GLint *v);
+void ( APIENTRY * qglTexCoord1s )(GLshort s);
+void ( APIENTRY * qglTexCoord1sv )(const GLshort *v);
+void ( APIENTRY * qglTexCoord2d )(GLdouble s, GLdouble t);
+void ( APIENTRY * qglTexCoord2dv )(const GLdouble *v);
+void ( APIENTRY * qglTexCoord2f )(GLfloat s, GLfloat t);
+void ( APIENTRY * qglTexCoord2fv )(const GLfloat *v);
+void ( APIENTRY * qglTexCoord2i )(GLint s, GLint t);
+void ( APIENTRY * qglTexCoord2iv )(const GLint *v);
+void ( APIENTRY * qglTexCoord2s )(GLshort s, GLshort t);
+void ( APIENTRY * qglTexCoord2sv )(const GLshort *v);
+void ( APIENTRY * qglTexCoord3d )(GLdouble s, GLdouble t, GLdouble r);
+void ( APIENTRY * qglTexCoord3dv )(const GLdouble *v);
+void ( APIENTRY * qglTexCoord3f )(GLfloat s, GLfloat t, GLfloat r);
+void ( APIENTRY * qglTexCoord3fv )(const GLfloat *v);
+void ( APIENTRY * qglTexCoord3i )(GLint s, GLint t, GLint r);
+void ( APIENTRY * qglTexCoord3iv )(const GLint *v);
+void ( APIENTRY * qglTexCoord3s )(GLshort s, GLshort t, GLshort r);
+void ( APIENTRY * qglTexCoord3sv )(const GLshort *v);
+void ( APIENTRY * qglTexCoord4d )(GLdouble s, GLdouble t, GLdouble r, GLdouble q);
+void ( APIENTRY * qglTexCoord4dv )(const GLdouble *v);
+void ( APIENTRY * qglTexCoord4f )(GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+void ( APIENTRY * qglTexCoord4fv )(const GLfloat *v);
+void ( APIENTRY * qglTexCoord4i )(GLint s, GLint t, GLint r, GLint q);
+void ( APIENTRY * qglTexCoord4iv )(const GLint *v);
+void ( APIENTRY * qglTexCoord4s )(GLshort s, GLshort t, GLshort r, GLshort q);
+void ( APIENTRY * qglTexCoord4sv )(const GLshort *v);
+void ( APIENTRY * qglTexCoordPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+void ( APIENTRY * qglTexEnvf )(GLenum target, GLenum pname, GLfloat param);
+void ( APIENTRY * qglTexEnvfv )(GLenum target, GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglTexEnvi )(GLenum target, GLenum pname, GLint param);
+void ( APIENTRY * qglTexEnviv )(GLenum target, GLenum pname, const GLint *params);
+void ( APIENTRY * qglTexGend )(GLenum coord, GLenum pname, GLdouble param);
+void ( APIENTRY * qglTexGendv )(GLenum coord, GLenum pname, const GLdouble *params);
+void ( APIENTRY * qglTexGenf )(GLenum coord, GLenum pname, GLfloat param);
+void ( APIENTRY * qglTexGenfv )(GLenum coord, GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglTexGeni )(GLenum coord, GLenum pname, GLint param);
+void ( APIENTRY * qglTexGeniv )(GLenum coord, GLenum pname, const GLint *params);
+void ( APIENTRY * qglTexImage1D )(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+void ( APIENTRY * qglTexImage2D )(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+void ( APIENTRY * qglTexParameterf )(GLenum target, GLenum pname, GLfloat param);
+void ( APIENTRY * qglTexParameterfv )(GLenum target, GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglTexParameteri )(GLenum target, GLenum pname, GLint param);
+void ( APIENTRY * qglTexParameteriv )(GLenum target, GLenum pname, const GLint *params);
+void ( APIENTRY * qglTexSubImage1D )(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels);
+void ( APIENTRY * qglTexSubImage2D )(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+void ( APIENTRY * qglTranslated )(GLdouble x, GLdouble y, GLdouble z);
+void ( APIENTRY * qglTranslatef )(GLfloat x, GLfloat y, GLfloat z);
+void ( APIENTRY * qglVertex2d )(GLdouble x, GLdouble y);
+void ( APIENTRY * qglVertex2dv )(const GLdouble *v);
+void ( APIENTRY * qglVertex2f )(GLfloat x, GLfloat y);
+void ( APIENTRY * qglVertex2fv )(const GLfloat *v);
+void ( APIENTRY * qglVertex2i )(GLint x, GLint y);
+void ( APIENTRY * qglVertex2iv )(const GLint *v);
+void ( APIENTRY * qglVertex2s )(GLshort x, GLshort y);
+void ( APIENTRY * qglVertex2sv )(const GLshort *v);
+void ( APIENTRY * qglVertex3d )(GLdouble x, GLdouble y, GLdouble z);
+void ( APIENTRY * qglVertex3dv )(const GLdouble *v);
+void ( APIENTRY * qglVertex3f )(GLfloat x, GLfloat y, GLfloat z);
+void ( APIENTRY * qglVertex3fv )(const GLfloat *v);
+void ( APIENTRY * qglVertex3i )(GLint x, GLint y, GLint z);
+void ( APIENTRY * qglVertex3iv )(const GLint *v);
+void ( APIENTRY * qglVertex3s )(GLshort x, GLshort y, GLshort z);
+void ( APIENTRY * qglVertex3sv )(const GLshort *v);
+void ( APIENTRY * qglVertex4d )(GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+void ( APIENTRY * qglVertex4dv )(const GLdouble *v);
+void ( APIENTRY * qglVertex4f )(GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+void ( APIENTRY * qglVertex4fv )(const GLfloat *v);
+void ( APIENTRY * qglVertex4i )(GLint x, GLint y, GLint z, GLint w);
+void ( APIENTRY * qglVertex4iv )(const GLint *v);
+void ( APIENTRY * qglVertex4s )(GLshort x, GLshort y, GLshort z, GLshort w);
+void ( APIENTRY * qglVertex4sv )(const GLshort *v);
+void ( APIENTRY * qglVertexPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+void ( APIENTRY * qglViewport )(GLint x, GLint y, GLsizei width, GLsizei height);
+
+void ( APIENTRY * qglMultiTexCoord2fARB )( GLenum texture, GLfloat s, GLfloat t );
+void ( APIENTRY * qglActiveTextureARB )( GLenum texture );
+void ( APIENTRY * qglClientActiveTextureARB )( GLenum texture );
+
+void ( APIENTRY * qglLockArraysEXT)( int, int);
+void ( APIENTRY * qglUnlockArraysEXT) ( void );
+
+void ( APIENTRY * qglPointParameterfEXT)( GLenum param, GLfloat value );
+void ( APIENTRY * qglPointParameterfvEXT)( GLenum param, const GLfloat *value );
+void ( APIENTRY * qglColorTableEXT)( int, int, int, int, int, const void * );
+void ( APIENTRY * qgl3DfxSetPaletteEXT)( GLuint * );
+void ( APIENTRY * qglSelectTextureSGIS)( GLenum );
+void ( APIENTRY * qglMTexCoord2fSGIS)( GLenum, GLfloat, GLfloat );
+
+static void ( APIENTRY * dllAccum )(GLenum op, GLfloat value);
+static void ( APIENTRY * dllAlphaFunc )(GLenum func, GLclampf ref);
+GLboolean ( APIENTRY * dllAreTexturesResident )(GLsizei n, const GLuint *textures, GLboolean *residences);
+static void ( APIENTRY * dllArrayElement )(GLint i);
+static void ( APIENTRY * dllBegin )(GLenum mode);
+static void ( APIENTRY * dllBindTexture )(GLenum target, GLuint texture);
+static void ( APIENTRY * dllBitmap )(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap);
+static void ( APIENTRY * dllBlendFunc )(GLenum sfactor, GLenum dfactor);
+static void ( APIENTRY * dllCallList )(GLuint list);
+static void ( APIENTRY * dllCallLists )(GLsizei n, GLenum type, const GLvoid *lists);
+static void ( APIENTRY * dllClear )(GLbitfield mask);
+static void ( APIENTRY * dllClearAccum )(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+static void ( APIENTRY * dllClearColor )(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+static void ( APIENTRY * dllClearDepth )(GLclampd depth);
+static void ( APIENTRY * dllClearIndex )(GLfloat c);
+static void ( APIENTRY * dllClearStencil )(GLint s);
+static void ( APIENTRY * dllClipPlane )(GLenum plane, const GLdouble *equation);
+static void ( APIENTRY * dllColor3b )(GLbyte red, GLbyte green, GLbyte blue);
+static void ( APIENTRY * dllColor3bv )(const GLbyte *v);
+static void ( APIENTRY * dllColor3d )(GLdouble red, GLdouble green, GLdouble blue);
+static void ( APIENTRY * dllColor3dv )(const GLdouble *v);
+static void ( APIENTRY * dllColor3f )(GLfloat red, GLfloat green, GLfloat blue);
+static void ( APIENTRY * dllColor3fv )(const GLfloat *v);
+static void ( APIENTRY * dllColor3i )(GLint red, GLint green, GLint blue);
+static void ( APIENTRY * dllColor3iv )(const GLint *v);
+static void ( APIENTRY * dllColor3s )(GLshort red, GLshort green, GLshort blue);
+static void ( APIENTRY * dllColor3sv )(const GLshort *v);
+static void ( APIENTRY * dllColor3ub )(GLubyte red, GLubyte green, GLubyte blue);
+static void ( APIENTRY * dllColor3ubv )(const GLubyte *v);
+static void ( APIENTRY * dllColor3ui )(GLuint red, GLuint green, GLuint blue);
+static void ( APIENTRY * dllColor3uiv )(const GLuint *v);
+static void ( APIENTRY * dllColor3us )(GLushort red, GLushort green, GLushort blue);
+static void ( APIENTRY * dllColor3usv )(const GLushort *v);
+static void ( APIENTRY * dllColor4b )(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha);
+static void ( APIENTRY * dllColor4bv )(const GLbyte *v);
+static void ( APIENTRY * dllColor4d )(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha);
+static void ( APIENTRY * dllColor4dv )(const GLdouble *v);
+static void ( APIENTRY * dllColor4f )(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+static void ( APIENTRY * dllColor4fv )(const GLfloat *v);
+static void ( APIENTRY * dllColor4i )(GLint red, GLint green, GLint blue, GLint alpha);
+static void ( APIENTRY * dllColor4iv )(const GLint *v);
+static void ( APIENTRY * dllColor4s )(GLshort red, GLshort green, GLshort blue, GLshort alpha);
+static void ( APIENTRY * dllColor4sv )(const GLshort *v);
+static void ( APIENTRY * dllColor4ub )(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha);
+static void ( APIENTRY * dllColor4ubv )(const GLubyte *v);
+static void ( APIENTRY * dllColor4ui )(GLuint red, GLuint green, GLuint blue, GLuint alpha);
+static void ( APIENTRY * dllColor4uiv )(const GLuint *v);
+static void ( APIENTRY * dllColor4us )(GLushort red, GLushort green, GLushort blue, GLushort alpha);
+static void ( APIENTRY * dllColor4usv )(const GLushort *v);
+static void ( APIENTRY * dllColorMask )(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
+static void ( APIENTRY * dllColorMaterial )(GLenum face, GLenum mode);
+static void ( APIENTRY * dllColorPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+static void ( APIENTRY * dllCopyPixels )(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type);
+static void ( APIENTRY * dllCopyTexImage1D )(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLint border);
+static void ( APIENTRY * dllCopyTexImage2D )(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+static void ( APIENTRY * dllCopyTexSubImage1D )(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
+static void ( APIENTRY * dllCopyTexSubImage2D )(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+static void ( APIENTRY * dllCullFace )(GLenum mode);
+static void ( APIENTRY * dllDeleteLists )(GLuint list, GLsizei range);
+static void ( APIENTRY * dllDeleteTextures )(GLsizei n, const GLuint *textures);
+static void ( APIENTRY * dllDepthFunc )(GLenum func);
+static void ( APIENTRY * dllDepthMask )(GLboolean flag);
+static void ( APIENTRY * dllDepthRange )(GLclampd zNear, GLclampd zFar);
+static void ( APIENTRY * dllDisable )(GLenum cap);
+static void ( APIENTRY * dllDisableClientState )(GLenum array);
+static void ( APIENTRY * dllDrawArrays )(GLenum mode, GLint first, GLsizei count);
+static void ( APIENTRY * dllDrawBuffer )(GLenum mode);
+static void ( APIENTRY * dllDrawElements )(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices);
+static void ( APIENTRY * dllDrawPixels )(GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+static void ( APIENTRY * dllEdgeFlag )(GLboolean flag);
+static void ( APIENTRY * dllEdgeFlagPointer )(GLsizei stride, const GLvoid *pointer);
+static void ( APIENTRY * dllEdgeFlagv )(const GLboolean *flag);
+static void ( APIENTRY * dllEnable )(GLenum cap);
+static void ( APIENTRY * dllEnableClientState )(GLenum array);
+static void ( APIENTRY * dllEnd )(void);
+static void ( APIENTRY * dllEndList )(void);
+static void ( APIENTRY * dllEvalCoord1d )(GLdouble u);
+static void ( APIENTRY * dllEvalCoord1dv )(const GLdouble *u);
+static void ( APIENTRY * dllEvalCoord1f )(GLfloat u);
+static void ( APIENTRY * dllEvalCoord1fv )(const GLfloat *u);
+static void ( APIENTRY * dllEvalCoord2d )(GLdouble u, GLdouble v);
+static void ( APIENTRY * dllEvalCoord2dv )(const GLdouble *u);
+static void ( APIENTRY * dllEvalCoord2f )(GLfloat u, GLfloat v);
+static void ( APIENTRY * dllEvalCoord2fv )(const GLfloat *u);
+static void ( APIENTRY * dllEvalMesh1 )(GLenum mode, GLint i1, GLint i2);
+static void ( APIENTRY * dllEvalMesh2 )(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2);
+static void ( APIENTRY * dllEvalPoint1 )(GLint i);
+static void ( APIENTRY * dllEvalPoint2 )(GLint i, GLint j);
+static void ( APIENTRY * dllFeedbackBuffer )(GLsizei size, GLenum type, GLfloat *buffer);
+static void ( APIENTRY * dllFinish )(void);
+static void ( APIENTRY * dllFlush )(void);
+static void ( APIENTRY * dllFogf )(GLenum pname, GLfloat param);
+static void ( APIENTRY * dllFogfv )(GLenum pname, const GLfloat *params);
+static void ( APIENTRY * dllFogi )(GLenum pname, GLint param);
+static void ( APIENTRY * dllFogiv )(GLenum pname, const GLint *params);
+static void ( APIENTRY * dllFrontFace )(GLenum mode);
+static void ( APIENTRY * dllFrustum )(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+GLuint ( APIENTRY * dllGenLists )(GLsizei range);
+static void ( APIENTRY * dllGenTextures )(GLsizei n, GLuint *textures);
+static void ( APIENTRY * dllGetBooleanv )(GLenum pname, GLboolean *params);
+static void ( APIENTRY * dllGetClipPlane )(GLenum plane, GLdouble *equation);
+static void ( APIENTRY * dllGetDoublev )(GLenum pname, GLdouble *params);
+GLenum ( APIENTRY * dllGetError )(void);
+static void ( APIENTRY * dllGetFloatv )(GLenum pname, GLfloat *params);
+static void ( APIENTRY * dllGetIntegerv )(GLenum pname, GLint *params);
+static void ( APIENTRY * dllGetLightfv )(GLenum light, GLenum pname, GLfloat *params);
+static void ( APIENTRY * dllGetLightiv )(GLenum light, GLenum pname, GLint *params);
+static void ( APIENTRY * dllGetMapdv )(GLenum target, GLenum query, GLdouble *v);
+static void ( APIENTRY * dllGetMapfv )(GLenum target, GLenum query, GLfloat *v);
+static void ( APIENTRY * dllGetMapiv )(GLenum target, GLenum query, GLint *v);
+static void ( APIENTRY * dllGetMaterialfv )(GLenum face, GLenum pname, GLfloat *params);
+static void ( APIENTRY * dllGetMaterialiv )(GLenum face, GLenum pname, GLint *params);
+static void ( APIENTRY * dllGetPixelMapfv )(GLenum map, GLfloat *values);
+static void ( APIENTRY * dllGetPixelMapuiv )(GLenum map, GLuint *values);
+static void ( APIENTRY * dllGetPixelMapusv )(GLenum map, GLushort *values);
+static void ( APIENTRY * dllGetPointerv )(GLenum pname, GLvoid* *params);
+static void ( APIENTRY * dllGetPolygonStipple )(GLubyte *mask);
+const GLubyte * ( APIENTRY * dllGetString )(GLenum name);
+static void ( APIENTRY * dllGetTexEnvfv )(GLenum target, GLenum pname, GLfloat *params);
+static void ( APIENTRY * dllGetTexEnviv )(GLenum target, GLenum pname, GLint *params);
+static void ( APIENTRY * dllGetTexGendv )(GLenum coord, GLenum pname, GLdouble *params);
+static void ( APIENTRY * dllGetTexGenfv )(GLenum coord, GLenum pname, GLfloat *params);
+static void ( APIENTRY * dllGetTexGeniv )(GLenum coord, GLenum pname, GLint *params);
+static void ( APIENTRY * dllGetTexImage )(GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels);
+static void ( APIENTRY * dllGetTexLevelParameterfv )(GLenum target, GLint level, GLenum pname, GLfloat *params);
+static void ( APIENTRY * dllGetTexLevelParameteriv )(GLenum target, GLint level, GLenum pname, GLint *params);
+static void ( APIENTRY * dllGetTexParameterfv )(GLenum target, GLenum pname, GLfloat *params);
+static void ( APIENTRY * dllGetTexParameteriv )(GLenum target, GLenum pname, GLint *params);
+static void ( APIENTRY * dllHint )(GLenum target, GLenum mode);
+static void ( APIENTRY * dllIndexMask )(GLuint mask);
+static void ( APIENTRY * dllIndexPointer )(GLenum type, GLsizei stride, const GLvoid *pointer);
+static void ( APIENTRY * dllIndexd )(GLdouble c);
+static void ( APIENTRY * dllIndexdv )(const GLdouble *c);
+static void ( APIENTRY * dllIndexf )(GLfloat c);
+static void ( APIENTRY * dllIndexfv )(const GLfloat *c);
+static void ( APIENTRY * dllIndexi )(GLint c);
+static void ( APIENTRY * dllIndexiv )(const GLint *c);
+static void ( APIENTRY * dllIndexs )(GLshort c);
+static void ( APIENTRY * dllIndexsv )(const GLshort *c);
+static void ( APIENTRY * dllIndexub )(GLubyte c);
+static void ( APIENTRY * dllIndexubv )(const GLubyte *c);
+static void ( APIENTRY * dllInitNames )(void);
+static void ( APIENTRY * dllInterleavedArrays )(GLenum format, GLsizei stride, const GLvoid *pointer);
+GLboolean ( APIENTRY * dllIsEnabled )(GLenum cap);
+GLboolean ( APIENTRY * dllIsList )(GLuint list);
+GLboolean ( APIENTRY * dllIsTexture )(GLuint texture);
+static void ( APIENTRY * dllLightModelf )(GLenum pname, GLfloat param);
+static void ( APIENTRY * dllLightModelfv )(GLenum pname, const GLfloat *params);
+static void ( APIENTRY * dllLightModeli )(GLenum pname, GLint param);
+static void ( APIENTRY * dllLightModeliv )(GLenum pname, const GLint *params);
+static void ( APIENTRY * dllLightf )(GLenum light, GLenum pname, GLfloat param);
+static void ( APIENTRY * dllLightfv )(GLenum light, GLenum pname, const GLfloat *params);
+static void ( APIENTRY * dllLighti )(GLenum light, GLenum pname, GLint param);
+static void ( APIENTRY * dllLightiv )(GLenum light, GLenum pname, const GLint *params);
+static void ( APIENTRY * dllLineStipple )(GLint factor, GLushort pattern);
+static void ( APIENTRY * dllLineWidth )(GLfloat width);
+static void ( APIENTRY * dllListBase )(GLuint base);
+static void ( APIENTRY * dllLoadIdentity )(void);
+static void ( APIENTRY * dllLoadMatrixd )(const GLdouble *m);
+static void ( APIENTRY * dllLoadMatrixf )(const GLfloat *m);
+static void ( APIENTRY * dllLoadName )(GLuint name);
+static void ( APIENTRY * dllLogicOp )(GLenum opcode);
+static void ( APIENTRY * dllMap1d )(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points);
+static void ( APIENTRY * dllMap1f )(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points);
+static void ( APIENTRY * dllMap2d )(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points);
+static void ( APIENTRY * dllMap2f )(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points);
+static void ( APIENTRY * dllMapGrid1d )(GLint un, GLdouble u1, GLdouble u2);
+static void ( APIENTRY * dllMapGrid1f )(GLint un, GLfloat u1, GLfloat u2);
+static void ( APIENTRY * dllMapGrid2d )(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2);
+static void ( APIENTRY * dllMapGrid2f )(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2);
+static void ( APIENTRY * dllMaterialf )(GLenum face, GLenum pname, GLfloat param);
+static void ( APIENTRY * dllMaterialfv )(GLenum face, GLenum pname, const GLfloat *params);
+static void ( APIENTRY * dllMateriali )(GLenum face, GLenum pname, GLint param);
+static void ( APIENTRY * dllMaterialiv )(GLenum face, GLenum pname, const GLint *params);
+static void ( APIENTRY * dllMatrixMode )(GLenum mode);
+static void ( APIENTRY * dllMultMatrixd )(const GLdouble *m);
+static void ( APIENTRY * dllMultMatrixf )(const GLfloat *m);
+static void ( APIENTRY * dllNewList )(GLuint list, GLenum mode);
+static void ( APIENTRY * dllNormal3b )(GLbyte nx, GLbyte ny, GLbyte nz);
+static void ( APIENTRY * dllNormal3bv )(const GLbyte *v);
+static void ( APIENTRY * dllNormal3d )(GLdouble nx, GLdouble ny, GLdouble nz);
+static void ( APIENTRY * dllNormal3dv )(const GLdouble *v);
+static void ( APIENTRY * dllNormal3f )(GLfloat nx, GLfloat ny, GLfloat nz);
+static void ( APIENTRY * dllNormal3fv )(const GLfloat *v);
+static void ( APIENTRY * dllNormal3i )(GLint nx, GLint ny, GLint nz);
+static void ( APIENTRY * dllNormal3iv )(const GLint *v);
+static void ( APIENTRY * dllNormal3s )(GLshort nx, GLshort ny, GLshort nz);
+static void ( APIENTRY * dllNormal3sv )(const GLshort *v);
+static void ( APIENTRY * dllNormalPointer )(GLenum type, GLsizei stride, const GLvoid *pointer);
+static void ( APIENTRY * dllOrtho )(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+static void ( APIENTRY * dllPassThrough )(GLfloat token);
+static void ( APIENTRY * dllPixelMapfv )(GLenum map, GLsizei mapsize, const GLfloat *values);
+static void ( APIENTRY * dllPixelMapuiv )(GLenum map, GLsizei mapsize, const GLuint *values);
+static void ( APIENTRY * dllPixelMapusv )(GLenum map, GLsizei mapsize, const GLushort *values);
+static void ( APIENTRY * dllPixelStoref )(GLenum pname, GLfloat param);
+static void ( APIENTRY * dllPixelStorei )(GLenum pname, GLint param);
+static void ( APIENTRY * dllPixelTransferf )(GLenum pname, GLfloat param);
+static void ( APIENTRY * dllPixelTransferi )(GLenum pname, GLint param);
+static void ( APIENTRY * dllPixelZoom )(GLfloat xfactor, GLfloat yfactor);
+static void ( APIENTRY * dllPointSize )(GLfloat size);
+static void ( APIENTRY * dllPolygonMode )(GLenum face, GLenum mode);
+static void ( APIENTRY * dllPolygonOffset )(GLfloat factor, GLfloat units);
+static void ( APIENTRY * dllPolygonStipple )(const GLubyte *mask);
+static void ( APIENTRY * dllPopAttrib )(void);
+static void ( APIENTRY * dllPopClientAttrib )(void);
+static void ( APIENTRY * dllPopMatrix )(void);
+static void ( APIENTRY * dllPopName )(void);
+static void ( APIENTRY * dllPrioritizeTextures )(GLsizei n, const GLuint *textures, const GLclampf *priorities);
+static void ( APIENTRY * dllPushAttrib )(GLbitfield mask);
+static void ( APIENTRY * dllPushClientAttrib )(GLbitfield mask);
+static void ( APIENTRY * dllPushMatrix )(void);
+static void ( APIENTRY * dllPushName )(GLuint name);
+static void ( APIENTRY * dllRasterPos2d )(GLdouble x, GLdouble y);
+static void ( APIENTRY * dllRasterPos2dv )(const GLdouble *v);
+static void ( APIENTRY * dllRasterPos2f )(GLfloat x, GLfloat y);
+static void ( APIENTRY * dllRasterPos2fv )(const GLfloat *v);
+static void ( APIENTRY * dllRasterPos2i )(GLint x, GLint y);
+static void ( APIENTRY * dllRasterPos2iv )(const GLint *v);
+static void ( APIENTRY * dllRasterPos2s )(GLshort x, GLshort y);
+static void ( APIENTRY * dllRasterPos2sv )(const GLshort *v);
+static void ( APIENTRY * dllRasterPos3d )(GLdouble x, GLdouble y, GLdouble z);
+static void ( APIENTRY * dllRasterPos3dv )(const GLdouble *v);
+static void ( APIENTRY * dllRasterPos3f )(GLfloat x, GLfloat y, GLfloat z);
+static void ( APIENTRY * dllRasterPos3fv )(const GLfloat *v);
+static void ( APIENTRY * dllRasterPos3i )(GLint x, GLint y, GLint z);
+static void ( APIENTRY * dllRasterPos3iv )(const GLint *v);
+static void ( APIENTRY * dllRasterPos3s )(GLshort x, GLshort y, GLshort z);
+static void ( APIENTRY * dllRasterPos3sv )(const GLshort *v);
+static void ( APIENTRY * dllRasterPos4d )(GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+static void ( APIENTRY * dllRasterPos4dv )(const GLdouble *v);
+static void ( APIENTRY * dllRasterPos4f )(GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+static void ( APIENTRY * dllRasterPos4fv )(const GLfloat *v);
+static void ( APIENTRY * dllRasterPos4i )(GLint x, GLint y, GLint z, GLint w);
+static void ( APIENTRY * dllRasterPos4iv )(const GLint *v);
+static void ( APIENTRY * dllRasterPos4s )(GLshort x, GLshort y, GLshort z, GLshort w);
+static void ( APIENTRY * dllRasterPos4sv )(const GLshort *v);
+static void ( APIENTRY * dllReadBuffer )(GLenum mode);
+static void ( APIENTRY * dllReadPixels )(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels);
+static void ( APIENTRY * dllRectd )(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2);
+static void ( APIENTRY * dllRectdv )(const GLdouble *v1, const GLdouble *v2);
+static void ( APIENTRY * dllRectf )(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2);
+static void ( APIENTRY * dllRectfv )(const GLfloat *v1, const GLfloat *v2);
+static void ( APIENTRY * dllRecti )(GLint x1, GLint y1, GLint x2, GLint y2);
+static void ( APIENTRY * dllRectiv )(const GLint *v1, const GLint *v2);
+static void ( APIENTRY * dllRects )(GLshort x1, GLshort y1, GLshort x2, GLshort y2);
+static void ( APIENTRY * dllRectsv )(const GLshort *v1, const GLshort *v2);
+GLint ( APIENTRY * dllRenderMode )(GLenum mode);
+static void ( APIENTRY * dllRotated )(GLdouble angle, GLdouble x, GLdouble y, GLdouble z);
+static void ( APIENTRY * dllRotatef )(GLfloat angle, GLfloat x, GLfloat y, GLfloat z);
+static void ( APIENTRY * dllScaled )(GLdouble x, GLdouble y, GLdouble z);
+static void ( APIENTRY * dllScalef )(GLfloat x, GLfloat y, GLfloat z);
+static void ( APIENTRY * dllScissor )(GLint x, GLint y, GLsizei width, GLsizei height);
+static void ( APIENTRY * dllSelectBuffer )(GLsizei size, GLuint *buffer);
+static void ( APIENTRY * dllShadeModel )(GLenum mode);
+static void ( APIENTRY * dllStencilFunc )(GLenum func, GLint ref, GLuint mask);
+static void ( APIENTRY * dllStencilMask )(GLuint mask);
+static void ( APIENTRY * dllStencilOp )(GLenum fail, GLenum zfail, GLenum zpass);
+static void ( APIENTRY * dllTexCoord1d )(GLdouble s);
+static void ( APIENTRY * dllTexCoord1dv )(const GLdouble *v);
+static void ( APIENTRY * dllTexCoord1f )(GLfloat s);
+static void ( APIENTRY * dllTexCoord1fv )(const GLfloat *v);
+static void ( APIENTRY * dllTexCoord1i )(GLint s);
+static void ( APIENTRY * dllTexCoord1iv )(const GLint *v);
+static void ( APIENTRY * dllTexCoord1s )(GLshort s);
+static void ( APIENTRY * dllTexCoord1sv )(const GLshort *v);
+static void ( APIENTRY * dllTexCoord2d )(GLdouble s, GLdouble t);
+static void ( APIENTRY * dllTexCoord2dv )(const GLdouble *v);
+static void ( APIENTRY * dllTexCoord2f )(GLfloat s, GLfloat t);
+static void ( APIENTRY * dllTexCoord2fv )(const GLfloat *v);
+static void ( APIENTRY * dllTexCoord2i )(GLint s, GLint t);
+static void ( APIENTRY * dllTexCoord2iv )(const GLint *v);
+static void ( APIENTRY * dllTexCoord2s )(GLshort s, GLshort t);
+static void ( APIENTRY * dllTexCoord2sv )(const GLshort *v);
+static void ( APIENTRY * dllTexCoord3d )(GLdouble s, GLdouble t, GLdouble r);
+static void ( APIENTRY * dllTexCoord3dv )(const GLdouble *v);
+static void ( APIENTRY * dllTexCoord3f )(GLfloat s, GLfloat t, GLfloat r);
+static void ( APIENTRY * dllTexCoord3fv )(const GLfloat *v);
+static void ( APIENTRY * dllTexCoord3i )(GLint s, GLint t, GLint r);
+static void ( APIENTRY * dllTexCoord3iv )(const GLint *v);
+static void ( APIENTRY * dllTexCoord3s )(GLshort s, GLshort t, GLshort r);
+static void ( APIENTRY * dllTexCoord3sv )(const GLshort *v);
+static void ( APIENTRY * dllTexCoord4d )(GLdouble s, GLdouble t, GLdouble r, GLdouble q);
+static void ( APIENTRY * dllTexCoord4dv )(const GLdouble *v);
+static void ( APIENTRY * dllTexCoord4f )(GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+static void ( APIENTRY * dllTexCoord4fv )(const GLfloat *v);
+static void ( APIENTRY * dllTexCoord4i )(GLint s, GLint t, GLint r, GLint q);
+static void ( APIENTRY * dllTexCoord4iv )(const GLint *v);
+static void ( APIENTRY * dllTexCoord4s )(GLshort s, GLshort t, GLshort r, GLshort q);
+static void ( APIENTRY * dllTexCoord4sv )(const GLshort *v);
+static void ( APIENTRY * dllTexCoordPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+static void ( APIENTRY * dllTexEnvf )(GLenum target, GLenum pname, GLfloat param);
+static void ( APIENTRY * dllTexEnvfv )(GLenum target, GLenum pname, const GLfloat *params);
+static void ( APIENTRY * dllTexEnvi )(GLenum target, GLenum pname, GLint param);
+static void ( APIENTRY * dllTexEnviv )(GLenum target, GLenum pname, const GLint *params);
+static void ( APIENTRY * dllTexGend )(GLenum coord, GLenum pname, GLdouble param);
+static void ( APIENTRY * dllTexGendv )(GLenum coord, GLenum pname, const GLdouble *params);
+static void ( APIENTRY * dllTexGenf )(GLenum coord, GLenum pname, GLfloat param);
+static void ( APIENTRY * dllTexGenfv )(GLenum coord, GLenum pname, const GLfloat *params);
+static void ( APIENTRY * dllTexGeni )(GLenum coord, GLenum pname, GLint param);
+static void ( APIENTRY * dllTexGeniv )(GLenum coord, GLenum pname, const GLint *params);
+static void ( APIENTRY * dllTexImage1D )(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+static void ( APIENTRY * dllTexImage2D )(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+static void ( APIENTRY * dllTexParameterf )(GLenum target, GLenum pname, GLfloat param);
+static void ( APIENTRY * dllTexParameterfv )(GLenum target, GLenum pname, const GLfloat *params);
+static void ( APIENTRY * dllTexParameteri )(GLenum target, GLenum pname, GLint param);
+static void ( APIENTRY * dllTexParameteriv )(GLenum target, GLenum pname, const GLint *params);
+static void ( APIENTRY * dllTexSubImage1D )(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels);
+static void ( APIENTRY * dllTexSubImage2D )(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+static void ( APIENTRY * dllTranslated )(GLdouble x, GLdouble y, GLdouble z);
+static void ( APIENTRY * dllTranslatef )(GLfloat x, GLfloat y, GLfloat z);
+static void ( APIENTRY * dllVertex2d )(GLdouble x, GLdouble y);
+static void ( APIENTRY * dllVertex2dv )(const GLdouble *v);
+static void ( APIENTRY * dllVertex2f )(GLfloat x, GLfloat y);
+static void ( APIENTRY * dllVertex2fv )(const GLfloat *v);
+static void ( APIENTRY * dllVertex2i )(GLint x, GLint y);
+static void ( APIENTRY * dllVertex2iv )(const GLint *v);
+static void ( APIENTRY * dllVertex2s )(GLshort x, GLshort y);
+static void ( APIENTRY * dllVertex2sv )(const GLshort *v);
+static void ( APIENTRY * dllVertex3d )(GLdouble x, GLdouble y, GLdouble z);
+static void ( APIENTRY * dllVertex3dv )(const GLdouble *v);
+static void ( APIENTRY * dllVertex3f )(GLfloat x, GLfloat y, GLfloat z);
+static void ( APIENTRY * dllVertex3fv )(const GLfloat *v);
+static void ( APIENTRY * dllVertex3i )(GLint x, GLint y, GLint z);
+static void ( APIENTRY * dllVertex3iv )(const GLint *v);
+static void ( APIENTRY * dllVertex3s )(GLshort x, GLshort y, GLshort z);
+static void ( APIENTRY * dllVertex3sv )(const GLshort *v);
+static void ( APIENTRY * dllVertex4d )(GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+static void ( APIENTRY * dllVertex4dv )(const GLdouble *v);
+static void ( APIENTRY * dllVertex4f )(GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+static void ( APIENTRY * dllVertex4fv )(const GLfloat *v);
+static void ( APIENTRY * dllVertex4i )(GLint x, GLint y, GLint z, GLint w);
+static void ( APIENTRY * dllVertex4iv )(const GLint *v);
+static void ( APIENTRY * dllVertex4s )(GLshort x, GLshort y, GLshort z, GLshort w);
+static void ( APIENTRY * dllVertex4sv )(const GLshort *v);
+static void ( APIENTRY * dllVertexPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+static void ( APIENTRY * dllViewport )(GLint x, GLint y, GLsizei width, GLsizei height);
+
+static void APIENTRY logAccum(GLenum op, GLfloat value)
+{
+ fprintf( glw_state.log_fp, "glAccum\n" );
+ dllAccum( op, value );
+}
+
+static void APIENTRY logAlphaFunc(GLenum func, GLclampf ref)
+{
+ fprintf( glw_state.log_fp, "glAlphaFunc( 0x%x, %f )\n", func, ref );
+ dllAlphaFunc( func, ref );
+}
+
+static GLboolean APIENTRY logAreTexturesResident(GLsizei n, const GLuint *textures, GLboolean *residences)
+{
+ fprintf( glw_state.log_fp, "glAreTexturesResident\n" );
+ return dllAreTexturesResident( n, textures, residences );
+}
+
+static void APIENTRY logArrayElement(GLint i)
+{
+ fprintf( glw_state.log_fp, "glArrayElement\n" );
+ dllArrayElement( i );
+}
+
+static void APIENTRY logBegin(GLenum mode)
+{
+ fprintf( glw_state.log_fp, "glBegin( 0x%x )\n", mode );
+ dllBegin( mode );
+}
+
+static void APIENTRY logBindTexture(GLenum target, GLuint texture)
+{
+ fprintf( glw_state.log_fp, "glBindTexture( 0x%x, %u )\n", target, texture );
+ dllBindTexture( target, texture );
+}
+
+static void APIENTRY logBitmap(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap)
+{
+ fprintf( glw_state.log_fp, "glBitmap\n" );
+ dllBitmap( width, height, xorig, yorig, xmove, ymove, bitmap );
+}
+
+static void APIENTRY logBlendFunc(GLenum sfactor, GLenum dfactor)
+{
+ fprintf( glw_state.log_fp, "glBlendFunc( 0x%x, 0x%x )\n", sfactor, dfactor );
+ dllBlendFunc( sfactor, dfactor );
+}
+
+static void APIENTRY logCallList(GLuint list)
+{
+ fprintf( glw_state.log_fp, "glCallList( %u )\n", list );
+ dllCallList( list );
+}
+
+static void APIENTRY logCallLists(GLsizei n, GLenum type, const void *lists)
+{
+ fprintf( glw_state.log_fp, "glCallLists\n" );
+ dllCallLists( n, type, lists );
+}
+
+static void APIENTRY logClear(GLbitfield mask)
+{
+ fprintf( glw_state.log_fp, "glClear\n" );
+ dllClear( mask );
+}
+
+static void APIENTRY logClearAccum(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha)
+{
+ fprintf( glw_state.log_fp, "glClearAccum\n" );
+ dllClearAccum( red, green, blue, alpha );
+}
+
+static void APIENTRY logClearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
+{
+ fprintf( glw_state.log_fp, "glClearColor\n" );
+ dllClearColor( red, green, blue, alpha );
+}
+
+static void APIENTRY logClearDepth(GLclampd depth)
+{
+ fprintf( glw_state.log_fp, "glClearDepth\n" );
+ dllClearDepth( depth );
+}
+
+static void APIENTRY logClearIndex(GLfloat c)
+{
+ fprintf( glw_state.log_fp, "glClearIndex\n" );
+ dllClearIndex( c );
+}
+
+static void APIENTRY logClearStencil(GLint s)
+{
+ fprintf( glw_state.log_fp, "glClearStencil\n" );
+ dllClearStencil( s );
+}
+
+static void APIENTRY logClipPlane(GLenum plane, const GLdouble *equation)
+{
+ fprintf( glw_state.log_fp, "glClipPlane\n" );
+ dllClipPlane( plane, equation );
+}
+
+static void APIENTRY logColor3b(GLbyte red, GLbyte green, GLbyte blue)
+{
+ fprintf( glw_state.log_fp, "glColor3b\n" );
+ dllColor3b( red, green, blue );
+}
+
+static void APIENTRY logColor3bv(const GLbyte *v)
+{
+ fprintf( glw_state.log_fp, "glColor3bv\n" );
+ dllColor3bv( v );
+}
+
+static void APIENTRY logColor3d(GLdouble red, GLdouble green, GLdouble blue)
+{
+ fprintf( glw_state.log_fp, "glColor3d\n" );
+ dllColor3d( red, green, blue );
+}
+
+static void APIENTRY logColor3dv(const GLdouble *v)
+{
+ fprintf( glw_state.log_fp, "glColor3dv\n" );
+ dllColor3dv( v );
+}
+
+static void APIENTRY logColor3f(GLfloat red, GLfloat green, GLfloat blue)
+{
+ fprintf( glw_state.log_fp, "glColor3f\n" );
+ dllColor3f( red, green, blue );
+}
+
+static void APIENTRY logColor3fv(const GLfloat *v)
+{
+ fprintf( glw_state.log_fp, "glColor3fv\n" );
+ dllColor3fv( v );
+}
+
+static void APIENTRY logColor3i(GLint red, GLint green, GLint blue)
+{
+ fprintf( glw_state.log_fp, "glColor3i\n" );
+ dllColor3i( red, green, blue );
+}
+
+static void APIENTRY logColor3iv(const GLint *v)
+{
+ fprintf( glw_state.log_fp, "glColor3iv\n" );
+ dllColor3iv( v );
+}
+
+static void APIENTRY logColor3s(GLshort red, GLshort green, GLshort blue)
+{
+ fprintf( glw_state.log_fp, "glColor3s\n" );
+ dllColor3s( red, green, blue );
+}
+
+static void APIENTRY logColor3sv(const GLshort *v)
+{
+ fprintf( glw_state.log_fp, "glColor3sv\n" );
+ dllColor3sv( v );
+}
+
+static void APIENTRY logColor3ub(GLubyte red, GLubyte green, GLubyte blue)
+{
+ fprintf( glw_state.log_fp, "glColor3ub\n" );
+ dllColor3ub( red, green, blue );
+}
+
+static void APIENTRY logColor3ubv(const GLubyte *v)
+{
+ fprintf( glw_state.log_fp, "glColor3ubv\n" );
+ dllColor3ubv( v );
+}
+
+#define SIG( x ) fprintf( glw_state.log_fp, x "\n" )
+
+static void APIENTRY logColor3ui(GLuint red, GLuint green, GLuint blue)
+{
+ SIG( "glColor3ui" );
+ dllColor3ui( red, green, blue );
+}
+
+static void APIENTRY logColor3uiv(const GLuint *v)
+{
+ SIG( "glColor3uiv" );
+ dllColor3uiv( v );
+}
+
+static void APIENTRY logColor3us(GLushort red, GLushort green, GLushort blue)
+{
+ SIG( "glColor3us" );
+ dllColor3us( red, green, blue );
+}
+
+static void APIENTRY logColor3usv(const GLushort *v)
+{
+ SIG( "glColor3usv" );
+ dllColor3usv( v );
+}
+
+static void APIENTRY logColor4b(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha)
+{
+ SIG( "glColor4b" );
+ dllColor4b( red, green, blue, alpha );
+}
+
+static void APIENTRY logColor4bv(const GLbyte *v)
+{
+ SIG( "glColor4bv" );
+ dllColor4bv( v );
+}
+
+static void APIENTRY logColor4d(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha)
+{
+ SIG( "glColor4d" );
+ dllColor4d( red, green, blue, alpha );
+}
+static void APIENTRY logColor4dv(const GLdouble *v)
+{
+ SIG( "glColor4dv" );
+ dllColor4dv( v );
+}
+static void APIENTRY logColor4f(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha)
+{
+ fprintf( glw_state.log_fp, "glColor4f( %f,%f,%f,%f )\n", red, green, blue, alpha );
+ dllColor4f( red, green, blue, alpha );
+}
+static void APIENTRY logColor4fv(const GLfloat *v)
+{
+ fprintf( glw_state.log_fp, "glColor4fv( %f,%f,%f,%f )\n", v[0], v[1], v[2], v[3] );
+ dllColor4fv( v );
+}
+static void APIENTRY logColor4i(GLint red, GLint green, GLint blue, GLint alpha)
+{
+ SIG( "glColor4i" );
+ dllColor4i( red, green, blue, alpha );
+}
+static void APIENTRY logColor4iv(const GLint *v)
+{
+ SIG( "glColor4iv" );
+ dllColor4iv( v );
+}
+static void APIENTRY logColor4s(GLshort red, GLshort green, GLshort blue, GLshort alpha)
+{
+ SIG( "glColor4s" );
+ dllColor4s( red, green, blue, alpha );
+}
+static void APIENTRY logColor4sv(const GLshort *v)
+{
+ SIG( "glColor4sv" );
+ dllColor4sv( v );
+}
+static void APIENTRY logColor4ub(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha)
+{
+ SIG( "glColor4b" );
+ dllColor4b( red, green, blue, alpha );
+}
+static void APIENTRY logColor4ubv(const GLubyte *v)
+{
+ SIG( "glColor4ubv" );
+ dllColor4ubv( v );
+}
+static void APIENTRY logColor4ui(GLuint red, GLuint green, GLuint blue, GLuint alpha)
+{
+ SIG( "glColor4ui" );
+ dllColor4ui( red, green, blue, alpha );
+}
+static void APIENTRY logColor4uiv(const GLuint *v)
+{
+ SIG( "glColor4uiv" );
+ dllColor4uiv( v );
+}
+static void APIENTRY logColor4us(GLushort red, GLushort green, GLushort blue, GLushort alpha)
+{
+ SIG( "glColor4us" );
+ dllColor4us( red, green, blue, alpha );
+}
+static void APIENTRY logColor4usv(const GLushort *v)
+{
+ SIG( "glColor4usv" );
+ dllColor4usv( v );
+}
+static void APIENTRY logColorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)
+{
+ SIG( "glColorMask" );
+ dllColorMask( red, green, blue, alpha );
+}
+static void APIENTRY logColorMaterial(GLenum face, GLenum mode)
+{
+ SIG( "glColorMaterial" );
+ dllColorMaterial( face, mode );
+}
+
+static void APIENTRY logColorPointer(GLint size, GLenum type, GLsizei stride, const void *pointer)
+{
+ SIG( "glColorPointer" );
+ dllColorPointer( size, type, stride, pointer );
+}
+
+static void APIENTRY logCopyPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type)
+{
+ SIG( "glCopyPixels" );
+ dllCopyPixels( x, y, width, height, type );
+}
+
+static void APIENTRY logCopyTexImage1D(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLint border)
+{
+ SIG( "glCopyTexImage1D" );
+ dllCopyTexImage1D( target, level, internalFormat, x, y, width, border );
+}
+
+static void APIENTRY logCopyTexImage2D(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border)
+{
+ SIG( "glCopyTexImage2D" );
+ dllCopyTexImage2D( target, level, internalFormat, x, y, width, height, border );
+}
+
+static void APIENTRY logCopyTexSubImage1D(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width)
+{
+ SIG( "glCopyTexSubImage1D" );
+ dllCopyTexSubImage1D( target, level, xoffset, x, y, width );
+}
+
+static void APIENTRY logCopyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height)
+{
+ SIG( "glCopyTexSubImage2D" );
+ dllCopyTexSubImage2D( target, level, xoffset, yoffset, x, y, width, height );
+}
+
+static void APIENTRY logCullFace(GLenum mode)
+{
+ SIG( "glCullFace" );
+ dllCullFace( mode );
+}
+
+static void APIENTRY logDeleteLists(GLuint list, GLsizei range)
+{
+ SIG( "glDeleteLists" );
+ dllDeleteLists( list, range );
+}
+
+static void APIENTRY logDeleteTextures(GLsizei n, const GLuint *textures)
+{
+ SIG( "glDeleteTextures" );
+ dllDeleteTextures( n, textures );
+}
+
+static void APIENTRY logDepthFunc(GLenum func)
+{
+ SIG( "glDepthFunc" );
+ dllDepthFunc( func );
+}
+
+static void APIENTRY logDepthMask(GLboolean flag)
+{
+ SIG( "glDepthMask" );
+ dllDepthMask( flag );
+}
+
+static void APIENTRY logDepthRange(GLclampd zNear, GLclampd zFar)
+{
+ SIG( "glDepthRange" );
+ dllDepthRange( zNear, zFar );
+}
+
+static void APIENTRY logDisable(GLenum cap)
+{
+ fprintf( glw_state.log_fp, "glDisable( 0x%x )\n", cap );
+ dllDisable( cap );
+}
+
+static void APIENTRY logDisableClientState(GLenum array)
+{
+ SIG( "glDisableClientState" );
+ dllDisableClientState( array );
+}
+
+static void APIENTRY logDrawArrays(GLenum mode, GLint first, GLsizei count)
+{
+ SIG( "glDrawArrays" );
+ dllDrawArrays( mode, first, count );
+}
+
+static void APIENTRY logDrawBuffer(GLenum mode)
+{
+ SIG( "glDrawBuffer" );
+ dllDrawBuffer( mode );
+}
+
+static void APIENTRY logDrawElements(GLenum mode, GLsizei count, GLenum type, const void *indices)
+{
+ SIG( "glDrawElements" );
+ dllDrawElements( mode, count, type, indices );
+}
+
+static void APIENTRY logDrawPixels(GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels)
+{
+ SIG( "glDrawPixels" );
+ dllDrawPixels( width, height, format, type, pixels );
+}
+
+static void APIENTRY logEdgeFlag(GLboolean flag)
+{
+ SIG( "glEdgeFlag" );
+ dllEdgeFlag( flag );
+}
+
+static void APIENTRY logEdgeFlagPointer(GLsizei stride, const void *pointer)
+{
+ SIG( "glEdgeFlagPointer" );
+ dllEdgeFlagPointer( stride, pointer );
+}
+
+static void APIENTRY logEdgeFlagv(const GLboolean *flag)
+{
+ SIG( "glEdgeFlagv" );
+ dllEdgeFlagv( flag );
+}
+
+static void APIENTRY logEnable(GLenum cap)
+{
+ fprintf( glw_state.log_fp, "glEnable( 0x%x )\n", cap );
+ dllEnable( cap );
+}
+
+static void APIENTRY logEnableClientState(GLenum array)
+{
+ SIG( "glEnableClientState" );
+ dllEnableClientState( array );
+}
+
+static void APIENTRY logEnd(void)
+{
+ SIG( "glEnd" );
+ dllEnd();
+}
+
+static void APIENTRY logEndList(void)
+{
+ SIG( "glEndList" );
+ dllEndList();
+}
+
+static void APIENTRY logEvalCoord1d(GLdouble u)
+{
+ SIG( "glEvalCoord1d" );
+ dllEvalCoord1d( u );
+}
+
+static void APIENTRY logEvalCoord1dv(const GLdouble *u)
+{
+ SIG( "glEvalCoord1dv" );
+ dllEvalCoord1dv( u );
+}
+
+static void APIENTRY logEvalCoord1f(GLfloat u)
+{
+ SIG( "glEvalCoord1f" );
+ dllEvalCoord1f( u );
+}
+
+static void APIENTRY logEvalCoord1fv(const GLfloat *u)
+{
+ SIG( "glEvalCoord1fv" );
+ dllEvalCoord1fv( u );
+}
+static void APIENTRY logEvalCoord2d(GLdouble u, GLdouble v)
+{
+ SIG( "glEvalCoord2d" );
+ dllEvalCoord2d( u, v );
+}
+static void APIENTRY logEvalCoord2dv(const GLdouble *u)
+{
+ SIG( "glEvalCoord2dv" );
+ dllEvalCoord2dv( u );
+}
+static void APIENTRY logEvalCoord2f(GLfloat u, GLfloat v)
+{
+ SIG( "glEvalCoord2f" );
+ dllEvalCoord2f( u, v );
+}
+static void APIENTRY logEvalCoord2fv(const GLfloat *u)
+{
+ SIG( "glEvalCoord2fv" );
+ dllEvalCoord2fv( u );
+}
+
+static void APIENTRY logEvalMesh1(GLenum mode, GLint i1, GLint i2)
+{
+ SIG( "glEvalMesh1" );
+ dllEvalMesh1( mode, i1, i2 );
+}
+static void APIENTRY logEvalMesh2(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2)
+{
+ SIG( "glEvalMesh2" );
+ dllEvalMesh2( mode, i1, i2, j1, j2 );
+}
+static void APIENTRY logEvalPoint1(GLint i)
+{
+ SIG( "glEvalPoint1" );
+ dllEvalPoint1( i );
+}
+static void APIENTRY logEvalPoint2(GLint i, GLint j)
+{
+ SIG( "glEvalPoint2" );
+ dllEvalPoint2( i, j );
+}
+
+static void APIENTRY logFeedbackBuffer(GLsizei size, GLenum type, GLfloat *buffer)
+{
+ SIG( "glFeedbackBuffer" );
+ dllFeedbackBuffer( size, type, buffer );
+}
+
+static void APIENTRY logFinish(void)
+{
+ SIG( "glFinish" );
+ dllFinish();
+}
+
+static void APIENTRY logFlush(void)
+{
+ SIG( "glFlush" );
+ dllFlush();
+}
+
+static void APIENTRY logFogf(GLenum pname, GLfloat param)
+{
+ SIG( "glFogf" );
+ dllFogf( pname, param );
+}
+
+static void APIENTRY logFogfv(GLenum pname, const GLfloat *params)
+{
+ SIG( "glFogfv" );
+ dllFogfv( pname, params );
+}
+
+static void APIENTRY logFogi(GLenum pname, GLint param)
+{
+ SIG( "glFogi" );
+ dllFogi( pname, param );
+}
+
+static void APIENTRY logFogiv(GLenum pname, const GLint *params)
+{
+ SIG( "glFogiv" );
+ dllFogiv( pname, params );
+}
+
+static void APIENTRY logFrontFace(GLenum mode)
+{
+ SIG( "glFrontFace" );
+ dllFrontFace( mode );
+}
+
+static void APIENTRY logFrustum(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar)
+{
+ SIG( "glFrustum" );
+ dllFrustum( left, right, bottom, top, zNear, zFar );
+}
+
+static GLuint APIENTRY logGenLists(GLsizei range)
+{
+ SIG( "glGenLists" );
+ return dllGenLists( range );
+}
+
+static void APIENTRY logGenTextures(GLsizei n, GLuint *textures)
+{
+ SIG( "glGenTextures" );
+ dllGenTextures( n, textures );
+}
+
+static void APIENTRY logGetBooleanv(GLenum pname, GLboolean *params)
+{
+ SIG( "glGetBooleanv" );
+ dllGetBooleanv( pname, params );
+}
+
+static void APIENTRY logGetClipPlane(GLenum plane, GLdouble *equation)
+{
+ SIG( "glGetClipPlane" );
+ dllGetClipPlane( plane, equation );
+}
+
+static void APIENTRY logGetDoublev(GLenum pname, GLdouble *params)
+{
+ SIG( "glGetDoublev" );
+ dllGetDoublev( pname, params );
+}
+
+static GLenum APIENTRY logGetError(void)
+{
+ SIG( "glGetError" );
+ return dllGetError();
+}
+
+static void APIENTRY logGetFloatv(GLenum pname, GLfloat *params)
+{
+ SIG( "glGetFloatv" );
+ dllGetFloatv( pname, params );
+}
+
+static void APIENTRY logGetIntegerv(GLenum pname, GLint *params)
+{
+ SIG( "glGetIntegerv" );
+ dllGetIntegerv( pname, params );
+}
+
+static void APIENTRY logGetLightfv(GLenum light, GLenum pname, GLfloat *params)
+{
+ SIG( "glGetLightfv" );
+ dllGetLightfv( light, pname, params );
+}
+
+static void APIENTRY logGetLightiv(GLenum light, GLenum pname, GLint *params)
+{
+ SIG( "glGetLightiv" );
+ dllGetLightiv( light, pname, params );
+}
+
+static void APIENTRY logGetMapdv(GLenum target, GLenum query, GLdouble *v)
+{
+ SIG( "glGetMapdv" );
+ dllGetMapdv( target, query, v );
+}
+
+static void APIENTRY logGetMapfv(GLenum target, GLenum query, GLfloat *v)
+{
+ SIG( "glGetMapfv" );
+ dllGetMapfv( target, query, v );
+}
+
+static void APIENTRY logGetMapiv(GLenum target, GLenum query, GLint *v)
+{
+ SIG( "glGetMapiv" );
+ dllGetMapiv( target, query, v );
+}
+
+static void APIENTRY logGetMaterialfv(GLenum face, GLenum pname, GLfloat *params)
+{
+ SIG( "glGetMaterialfv" );
+ dllGetMaterialfv( face, pname, params );
+}
+
+static void APIENTRY logGetMaterialiv(GLenum face, GLenum pname, GLint *params)
+{
+ SIG( "glGetMaterialiv" );
+ dllGetMaterialiv( face, pname, params );
+}
+
+static void APIENTRY logGetPixelMapfv(GLenum map, GLfloat *values)
+{
+ SIG( "glGetPixelMapfv" );
+ dllGetPixelMapfv( map, values );
+}
+
+static void APIENTRY logGetPixelMapuiv(GLenum map, GLuint *values)
+{
+ SIG( "glGetPixelMapuiv" );
+ dllGetPixelMapuiv( map, values );
+}
+
+static void APIENTRY logGetPixelMapusv(GLenum map, GLushort *values)
+{
+ SIG( "glGetPixelMapusv" );
+ dllGetPixelMapusv( map, values );
+}
+
+static void APIENTRY logGetPointerv(GLenum pname, GLvoid* *params)
+{
+ SIG( "glGetPointerv" );
+ dllGetPointerv( pname, params );
+}
+
+static void APIENTRY logGetPolygonStipple(GLubyte *mask)
+{
+ SIG( "glGetPolygonStipple" );
+ dllGetPolygonStipple( mask );
+}
+
+static const GLubyte * APIENTRY logGetString(GLenum name)
+{
+ SIG( "glGetString" );
+ return dllGetString( name );
+}
+
+static void APIENTRY logGetTexEnvfv(GLenum target, GLenum pname, GLfloat *params)
+{
+ SIG( "glGetTexEnvfv" );
+ dllGetTexEnvfv( target, pname, params );
+}
+
+static void APIENTRY logGetTexEnviv(GLenum target, GLenum pname, GLint *params)
+{
+ SIG( "glGetTexEnviv" );
+ dllGetTexEnviv( target, pname, params );
+}
+
+static void APIENTRY logGetTexGendv(GLenum coord, GLenum pname, GLdouble *params)
+{
+ SIG( "glGetTexGendv" );
+ dllGetTexGendv( coord, pname, params );
+}
+
+static void APIENTRY logGetTexGenfv(GLenum coord, GLenum pname, GLfloat *params)
+{
+ SIG( "glGetTexGenfv" );
+ dllGetTexGenfv( coord, pname, params );
+}
+
+static void APIENTRY logGetTexGeniv(GLenum coord, GLenum pname, GLint *params)
+{
+ SIG( "glGetTexGeniv" );
+ dllGetTexGeniv( coord, pname, params );
+}
+
+static void APIENTRY logGetTexImage(GLenum target, GLint level, GLenum format, GLenum type, void *pixels)
+{
+ SIG( "glGetTexImage" );
+ dllGetTexImage( target, level, format, type, pixels );
+}
+static void APIENTRY logGetTexLevelParameterfv(GLenum target, GLint level, GLenum pname, GLfloat *params )
+{
+ SIG( "glGetTexLevelParameterfv" );
+ dllGetTexLevelParameterfv( target, level, pname, params );
+}
+
+static void APIENTRY logGetTexLevelParameteriv(GLenum target, GLint level, GLenum pname, GLint *params)
+{
+ SIG( "glGetTexLevelParameteriv" );
+ dllGetTexLevelParameteriv( target, level, pname, params );
+}
+
+static void APIENTRY logGetTexParameterfv(GLenum target, GLenum pname, GLfloat *params)
+{
+ SIG( "glGetTexParameterfv" );
+ dllGetTexParameterfv( target, pname, params );
+}
+
+static void APIENTRY logGetTexParameteriv(GLenum target, GLenum pname, GLint *params)
+{
+ SIG( "glGetTexParameteriv" );
+ dllGetTexParameteriv( target, pname, params );
+}
+
+static void APIENTRY logHint(GLenum target, GLenum mode)
+{
+ fprintf( glw_state.log_fp, "glHint( 0x%x, 0x%x )\n", target, mode );
+ dllHint( target, mode );
+}
+
+static void APIENTRY logIndexMask(GLuint mask)
+{
+ SIG( "glIndexMask" );
+ dllIndexMask( mask );
+}
+
+static void APIENTRY logIndexPointer(GLenum type, GLsizei stride, const void *pointer)
+{
+ SIG( "glIndexPointer" );
+ dllIndexPointer( type, stride, pointer );
+}
+
+static void APIENTRY logIndexd(GLdouble c)
+{
+ SIG( "glIndexd" );
+ dllIndexd( c );
+}
+
+static void APIENTRY logIndexdv(const GLdouble *c)
+{
+ SIG( "glIndexdv" );
+ dllIndexdv( c );
+}
+
+static void APIENTRY logIndexf(GLfloat c)
+{
+ SIG( "glIndexf" );
+ dllIndexf( c );
+}
+
+static void APIENTRY logIndexfv(const GLfloat *c)
+{
+ SIG( "glIndexfv" );
+ dllIndexfv( c );
+}
+
+static void APIENTRY logIndexi(GLint c)
+{
+ SIG( "glIndexi" );
+ dllIndexi( c );
+}
+
+static void APIENTRY logIndexiv(const GLint *c)
+{
+ SIG( "glIndexiv" );
+ dllIndexiv( c );
+}
+
+static void APIENTRY logIndexs(GLshort c)
+{
+ SIG( "glIndexs" );
+ dllIndexs( c );
+}
+
+static void APIENTRY logIndexsv(const GLshort *c)
+{
+ SIG( "glIndexsv" );
+ dllIndexsv( c );
+}
+
+static void APIENTRY logIndexub(GLubyte c)
+{
+ SIG( "glIndexub" );
+ dllIndexub( c );
+}
+
+static void APIENTRY logIndexubv(const GLubyte *c)
+{
+ SIG( "glIndexubv" );
+ dllIndexubv( c );
+}
+
+static void APIENTRY logInitNames(void)
+{
+ SIG( "glInitNames" );
+ dllInitNames();
+}
+
+static void APIENTRY logInterleavedArrays(GLenum format, GLsizei stride, const void *pointer)
+{
+ SIG( "glInterleavedArrays" );
+ dllInterleavedArrays( format, stride, pointer );
+}
+
+static GLboolean APIENTRY logIsEnabled(GLenum cap)
+{
+ SIG( "glIsEnabled" );
+ return dllIsEnabled( cap );
+}
+static GLboolean APIENTRY logIsList(GLuint list)
+{
+ SIG( "glIsList" );
+ return dllIsList( list );
+}
+static GLboolean APIENTRY logIsTexture(GLuint texture)
+{
+ SIG( "glIsTexture" );
+ return dllIsTexture( texture );
+}
+
+static void APIENTRY logLightModelf(GLenum pname, GLfloat param)
+{
+ SIG( "glLightModelf" );
+ dllLightModelf( pname, param );
+}
+
+static void APIENTRY logLightModelfv(GLenum pname, const GLfloat *params)
+{
+ SIG( "glLightModelfv" );
+ dllLightModelfv( pname, params );
+}
+
+static void APIENTRY logLightModeli(GLenum pname, GLint param)
+{
+ SIG( "glLightModeli" );
+ dllLightModeli( pname, param );
+
+}
+
+static void APIENTRY logLightModeliv(GLenum pname, const GLint *params)
+{
+ SIG( "glLightModeliv" );
+ dllLightModeliv( pname, params );
+}
+
+static void APIENTRY logLightf(GLenum light, GLenum pname, GLfloat param)
+{
+ SIG( "glLightf" );
+ dllLightf( light, pname, param );
+}
+
+static void APIENTRY logLightfv(GLenum light, GLenum pname, const GLfloat *params)
+{
+ SIG( "glLightfv" );
+ dllLightfv( light, pname, params );
+}
+
+static void APIENTRY logLighti(GLenum light, GLenum pname, GLint param)
+{
+ SIG( "glLighti" );
+ dllLighti( light, pname, param );
+}
+
+static void APIENTRY logLightiv(GLenum light, GLenum pname, const GLint *params)
+{
+ SIG( "glLightiv" );
+ dllLightiv( light, pname, params );
+}
+
+static void APIENTRY logLineStipple(GLint factor, GLushort pattern)
+{
+ SIG( "glLineStipple" );
+ dllLineStipple( factor, pattern );
+}
+
+static void APIENTRY logLineWidth(GLfloat width)
+{
+ SIG( "glLineWidth" );
+ dllLineWidth( width );
+}
+
+static void APIENTRY logListBase(GLuint base)
+{
+ SIG( "glListBase" );
+ dllListBase( base );
+}
+
+static void APIENTRY logLoadIdentity(void)
+{
+ SIG( "glLoadIdentity" );
+ dllLoadIdentity();
+}
+
+static void APIENTRY logLoadMatrixd(const GLdouble *m)
+{
+ SIG( "glLoadMatrixd" );
+ dllLoadMatrixd( m );
+}
+
+static void APIENTRY logLoadMatrixf(const GLfloat *m)
+{
+ SIG( "glLoadMatrixf" );
+ dllLoadMatrixf( m );
+}
+
+static void APIENTRY logLoadName(GLuint name)
+{
+ SIG( "glLoadName" );
+ dllLoadName( name );
+}
+
+static void APIENTRY logLogicOp(GLenum opcode)
+{
+ SIG( "glLogicOp" );
+ dllLogicOp( opcode );
+}
+
+static void APIENTRY logMap1d(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points)
+{
+ SIG( "glMap1d" );
+ dllMap1d( target, u1, u2, stride, order, points );
+}
+
+static void APIENTRY logMap1f(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points)
+{
+ SIG( "glMap1f" );
+ dllMap1f( target, u1, u2, stride, order, points );
+}
+
+static void APIENTRY logMap2d(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points)
+{
+ SIG( "glMap2d" );
+ dllMap2d( target, u1, u2, ustride, uorder, v1, v2, vstride, vorder, points );
+}
+
+static void APIENTRY logMap2f(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points)
+{
+ SIG( "glMap2f" );
+ dllMap2f( target, u1, u2, ustride, uorder, v1, v2, vstride, vorder, points );
+}
+
+static void APIENTRY logMapGrid1d(GLint un, GLdouble u1, GLdouble u2)
+{
+ SIG( "glMapGrid1d" );
+ dllMapGrid1d( un, u1, u2 );
+}
+
+static void APIENTRY logMapGrid1f(GLint un, GLfloat u1, GLfloat u2)
+{
+ SIG( "glMapGrid1f" );
+ dllMapGrid1f( un, u1, u2 );
+}
+
+static void APIENTRY logMapGrid2d(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2)
+{
+ SIG( "glMapGrid2d" );
+ dllMapGrid2d( un, u1, u2, vn, v1, v2 );
+}
+static void APIENTRY logMapGrid2f(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2)
+{
+ SIG( "glMapGrid2f" );
+ dllMapGrid2f( un, u1, u2, vn, v1, v2 );
+}
+static void APIENTRY logMaterialf(GLenum face, GLenum pname, GLfloat param)
+{
+ SIG( "glMaterialf" );
+ dllMaterialf( face, pname, param );
+}
+static void APIENTRY logMaterialfv(GLenum face, GLenum pname, const GLfloat *params)
+{
+ SIG( "glMaterialfv" );
+ dllMaterialfv( face, pname, params );
+}
+
+static void APIENTRY logMateriali(GLenum face, GLenum pname, GLint param)
+{
+ SIG( "glMateriali" );
+ dllMateriali( face, pname, param );
+}
+
+static void APIENTRY logMaterialiv(GLenum face, GLenum pname, const GLint *params)
+{
+ SIG( "glMaterialiv" );
+ dllMaterialiv( face, pname, params );
+}
+
+static void APIENTRY logMatrixMode(GLenum mode)
+{
+ SIG( "glMatrixMode" );
+ dllMatrixMode( mode );
+}
+
+static void APIENTRY logMultMatrixd(const GLdouble *m)
+{
+ SIG( "glMultMatrixd" );
+ dllMultMatrixd( m );
+}
+
+static void APIENTRY logMultMatrixf(const GLfloat *m)
+{
+ SIG( "glMultMatrixf" );
+ dllMultMatrixf( m );
+}
+
+static void APIENTRY logNewList(GLuint list, GLenum mode)
+{
+ SIG( "glNewList" );
+ dllNewList( list, mode );
+}
+
+static void APIENTRY logNormal3b(GLbyte nx, GLbyte ny, GLbyte nz)
+{
+ SIG ("glNormal3b" );
+ dllNormal3b( nx, ny, nz );
+}
+
+static void APIENTRY logNormal3bv(const GLbyte *v)
+{
+ SIG( "glNormal3bv" );
+ dllNormal3bv( v );
+}
+
+static void APIENTRY logNormal3d(GLdouble nx, GLdouble ny, GLdouble nz)
+{
+ SIG( "glNormal3d" );
+ dllNormal3d( nx, ny, nz );
+}
+
+static void APIENTRY logNormal3dv(const GLdouble *v)
+{
+ SIG( "glNormal3dv" );
+ dllNormal3dv( v );
+}
+
+static void APIENTRY logNormal3f(GLfloat nx, GLfloat ny, GLfloat nz)
+{
+ SIG( "glNormal3f" );
+ dllNormal3f( nx, ny, nz );
+}
+
+static void APIENTRY logNormal3fv(const GLfloat *v)
+{
+ SIG( "glNormal3fv" );
+ dllNormal3fv( v );
+}
+static void APIENTRY logNormal3i(GLint nx, GLint ny, GLint nz)
+{
+ SIG( "glNormal3i" );
+ dllNormal3i( nx, ny, nz );
+}
+static void APIENTRY logNormal3iv(const GLint *v)
+{
+ SIG( "glNormal3iv" );
+ dllNormal3iv( v );
+}
+static void APIENTRY logNormal3s(GLshort nx, GLshort ny, GLshort nz)
+{
+ SIG( "glNormal3s" );
+ dllNormal3s( nx, ny, nz );
+}
+static void APIENTRY logNormal3sv(const GLshort *v)
+{
+ SIG( "glNormal3sv" );
+ dllNormal3sv( v );
+}
+static void APIENTRY logNormalPointer(GLenum type, GLsizei stride, const void *pointer)
+{
+ SIG( "glNormalPointer" );
+ dllNormalPointer( type, stride, pointer );
+}
+static void APIENTRY logOrtho(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar)
+{
+ SIG( "glOrtho" );
+ dllOrtho( left, right, bottom, top, zNear, zFar );
+}
+
+static void APIENTRY logPassThrough(GLfloat token)
+{
+ SIG( "glPassThrough" );
+ dllPassThrough( token );
+}
+
+static void APIENTRY logPixelMapfv(GLenum map, GLsizei mapsize, const GLfloat *values)
+{
+ SIG( "glPixelMapfv" );
+ dllPixelMapfv( map, mapsize, values );
+}
+
+static void APIENTRY logPixelMapuiv(GLenum map, GLsizei mapsize, const GLuint *values)
+{
+ SIG( "glPixelMapuiv" );
+ dllPixelMapuiv( map, mapsize, values );
+}
+
+static void APIENTRY logPixelMapusv(GLenum map, GLsizei mapsize, const GLushort *values)
+{
+ SIG( "glPixelMapusv" );
+ dllPixelMapusv( map, mapsize, values );
+}
+static void APIENTRY logPixelStoref(GLenum pname, GLfloat param)
+{
+ SIG( "glPixelStoref" );
+ dllPixelStoref( pname, param );
+}
+static void APIENTRY logPixelStorei(GLenum pname, GLint param)
+{
+ SIG( "glPixelStorei" );
+ dllPixelStorei( pname, param );
+}
+static void APIENTRY logPixelTransferf(GLenum pname, GLfloat param)
+{
+ SIG( "glPixelTransferf" );
+ dllPixelTransferf( pname, param );
+}
+
+static void APIENTRY logPixelTransferi(GLenum pname, GLint param)
+{
+ SIG( "glPixelTransferi" );
+ dllPixelTransferi( pname, param );
+}
+
+static void APIENTRY logPixelZoom(GLfloat xfactor, GLfloat yfactor)
+{
+ SIG( "glPixelZoom" );
+ dllPixelZoom( xfactor, yfactor );
+}
+
+static void APIENTRY logPointSize(GLfloat size)
+{
+ SIG( "glPointSize" );
+ dllPointSize( size );
+}
+
+static void APIENTRY logPolygonMode(GLenum face, GLenum mode)
+{
+ fprintf( glw_state.log_fp, "glPolygonMode( 0x%x, 0x%x )\n", face, mode );
+ dllPolygonMode( face, mode );
+}
+
+static void APIENTRY logPolygonOffset(GLfloat factor, GLfloat units)
+{
+ SIG( "glPolygonOffset" );
+ dllPolygonOffset( factor, units );
+}
+static void APIENTRY logPolygonStipple(const GLubyte *mask )
+{
+ SIG( "glPolygonStipple" );
+ dllPolygonStipple( mask );
+}
+static void APIENTRY logPopAttrib(void)
+{
+ SIG( "glPopAttrib" );
+ dllPopAttrib();
+}
+
+static void APIENTRY logPopClientAttrib(void)
+{
+ SIG( "glPopClientAttrib" );
+ dllPopClientAttrib();
+}
+
+static void APIENTRY logPopMatrix(void)
+{
+ SIG( "glPopMatrix" );
+ dllPopMatrix();
+}
+
+static void APIENTRY logPopName(void)
+{
+ SIG( "glPopName" );
+ dllPopName();
+}
+
+static void APIENTRY logPrioritizeTextures(GLsizei n, const GLuint *textures, const GLclampf *priorities)
+{
+ SIG( "glPrioritizeTextures" );
+ dllPrioritizeTextures( n, textures, priorities );
+}
+
+static void APIENTRY logPushAttrib(GLbitfield mask)
+{
+ SIG( "glPushAttrib" );
+ dllPushAttrib( mask );
+}
+
+static void APIENTRY logPushClientAttrib(GLbitfield mask)
+{
+ SIG( "glPushClientAttrib" );
+ dllPushClientAttrib( mask );
+}
+
+static void APIENTRY logPushMatrix(void)
+{
+ SIG( "glPushMatrix" );
+ dllPushMatrix();
+}
+
+static void APIENTRY logPushName(GLuint name)
+{
+ SIG( "glPushName" );
+ dllPushName( name );
+}
+
+static void APIENTRY logRasterPos2d(GLdouble x, GLdouble y)
+{
+ SIG ("glRasterPot2d" );
+ dllRasterPos2d( x, y );
+}
+
+static void APIENTRY logRasterPos2dv(const GLdouble *v)
+{
+ SIG( "glRasterPos2dv" );
+ dllRasterPos2dv( v );
+}
+
+static void APIENTRY logRasterPos2f(GLfloat x, GLfloat y)
+{
+ SIG( "glRasterPos2f" );
+ dllRasterPos2f( x, y );
+}
+static void APIENTRY logRasterPos2fv(const GLfloat *v)
+{
+ SIG( "glRasterPos2dv" );
+ dllRasterPos2fv( v );
+}
+static void APIENTRY logRasterPos2i(GLint x, GLint y)
+{
+ SIG( "glRasterPos2if" );
+ dllRasterPos2i( x, y );
+}
+static void APIENTRY logRasterPos2iv(const GLint *v)
+{
+ SIG( "glRasterPos2iv" );
+ dllRasterPos2iv( v );
+}
+static void APIENTRY logRasterPos2s(GLshort x, GLshort y)
+{
+ SIG( "glRasterPos2s" );
+ dllRasterPos2s( x, y );
+}
+static void APIENTRY logRasterPos2sv(const GLshort *v)
+{
+ SIG( "glRasterPos2sv" );
+ dllRasterPos2sv( v );
+}
+static void APIENTRY logRasterPos3d(GLdouble x, GLdouble y, GLdouble z)
+{
+ SIG( "glRasterPos3d" );
+ dllRasterPos3d( x, y, z );
+}
+static void APIENTRY logRasterPos3dv(const GLdouble *v)
+{
+ SIG( "glRasterPos3dv" );
+ dllRasterPos3dv( v );
+}
+static void APIENTRY logRasterPos3f(GLfloat x, GLfloat y, GLfloat z)
+{
+ SIG( "glRasterPos3f" );
+ dllRasterPos3f( x, y, z );
+}
+static void APIENTRY logRasterPos3fv(const GLfloat *v)
+{
+ SIG( "glRasterPos3fv" );
+ dllRasterPos3fv( v );
+}
+static void APIENTRY logRasterPos3i(GLint x, GLint y, GLint z)
+{
+ SIG( "glRasterPos3i" );
+ dllRasterPos3i( x, y, z );
+}
+static void APIENTRY logRasterPos3iv(const GLint *v)
+{
+ SIG( "glRasterPos3iv" );
+ dllRasterPos3iv( v );
+}
+static void APIENTRY logRasterPos3s(GLshort x, GLshort y, GLshort z)
+{
+ SIG( "glRasterPos3s" );
+ dllRasterPos3s( x, y, z );
+}
+static void APIENTRY logRasterPos3sv(const GLshort *v)
+{
+ SIG( "glRasterPos3sv" );
+ dllRasterPos3sv( v );
+}
+static void APIENTRY logRasterPos4d(GLdouble x, GLdouble y, GLdouble z, GLdouble w)
+{
+ SIG( "glRasterPos4d" );
+ dllRasterPos4d( x, y, z, w );
+}
+static void APIENTRY logRasterPos4dv(const GLdouble *v)
+{
+ SIG( "glRasterPos4dv" );
+ dllRasterPos4dv( v );
+}
+static void APIENTRY logRasterPos4f(GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+ SIG( "glRasterPos4f" );
+ dllRasterPos4f( x, y, z, w );
+}
+static void APIENTRY logRasterPos4fv(const GLfloat *v)
+{
+ SIG( "glRasterPos4fv" );
+ dllRasterPos4fv( v );
+}
+static void APIENTRY logRasterPos4i(GLint x, GLint y, GLint z, GLint w)
+{
+ SIG( "glRasterPos4i" );
+ dllRasterPos4i( x, y, z, w );
+}
+static void APIENTRY logRasterPos4iv(const GLint *v)
+{
+ SIG( "glRasterPos4iv" );
+ dllRasterPos4iv( v );
+}
+static void APIENTRY logRasterPos4s(GLshort x, GLshort y, GLshort z, GLshort w)
+{
+ SIG( "glRasterPos4s" );
+ dllRasterPos4s( x, y, z, w );
+}
+static void APIENTRY logRasterPos4sv(const GLshort *v)
+{
+ SIG( "glRasterPos4sv" );
+ dllRasterPos4sv( v );
+}
+static void APIENTRY logReadBuffer(GLenum mode)
+{
+ SIG( "glReadBuffer" );
+ dllReadBuffer( mode );
+}
+static void APIENTRY logReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels)
+{
+ SIG( "glReadPixels" );
+ dllReadPixels( x, y, width, height, format, type, pixels );
+}
+
+static void APIENTRY logRectd(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2)
+{
+ SIG( "glRectd" );
+ dllRectd( x1, y1, x2, y2 );
+}
+
+static void APIENTRY logRectdv(const GLdouble *v1, const GLdouble *v2)
+{
+ SIG( "glRectdv" );
+ dllRectdv( v1, v2 );
+}
+
+static void APIENTRY logRectf(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2)
+{
+ SIG( "glRectf" );
+ dllRectf( x1, y1, x2, y2 );
+}
+
+static void APIENTRY logRectfv(const GLfloat *v1, const GLfloat *v2)
+{
+ SIG( "glRectfv" );
+ dllRectfv( v1, v2 );
+}
+static void APIENTRY logRecti(GLint x1, GLint y1, GLint x2, GLint y2)
+{
+ SIG( "glRecti" );
+ dllRecti( x1, y1, x2, y2 );
+}
+static void APIENTRY logRectiv(const GLint *v1, const GLint *v2)
+{
+ SIG( "glRectiv" );
+ dllRectiv( v1, v2 );
+}
+static void APIENTRY logRects(GLshort x1, GLshort y1, GLshort x2, GLshort y2)
+{
+ SIG( "glRects" );
+ dllRects( x1, y1, x2, y2 );
+}
+static void APIENTRY logRectsv(const GLshort *v1, const GLshort *v2)
+{
+ SIG( "glRectsv" );
+ dllRectsv( v1, v2 );
+}
+static GLint APIENTRY logRenderMode(GLenum mode)
+{
+ SIG( "glRenderMode" );
+ return dllRenderMode( mode );
+}
+static void APIENTRY logRotated(GLdouble angle, GLdouble x, GLdouble y, GLdouble z)
+{
+ SIG( "glRotated" );
+ dllRotated( angle, x, y, z );
+}
+
+static void APIENTRY logRotatef(GLfloat angle, GLfloat x, GLfloat y, GLfloat z)
+{
+ SIG( "glRotatef" );
+ dllRotatef( angle, x, y, z );
+}
+
+static void APIENTRY logScaled(GLdouble x, GLdouble y, GLdouble z)
+{
+ SIG( "glScaled" );
+ dllScaled( x, y, z );
+}
+
+static void APIENTRY logScalef(GLfloat x, GLfloat y, GLfloat z)
+{
+ SIG( "glScalef" );
+ dllScalef( x, y, z );
+}
+
+static void APIENTRY logScissor(GLint x, GLint y, GLsizei width, GLsizei height)
+{
+ SIG( "glScissor" );
+ dllScissor( x, y, width, height );
+}
+
+static void APIENTRY logSelectBuffer(GLsizei size, GLuint *buffer)
+{
+ SIG( "glSelectBuffer" );
+ dllSelectBuffer( size, buffer );
+}
+
+static void APIENTRY logShadeModel(GLenum mode)
+{
+ SIG( "glShadeModel" );
+ dllShadeModel( mode );
+}
+
+static void APIENTRY logStencilFunc(GLenum func, GLint ref, GLuint mask)
+{
+ SIG( "glStencilFunc" );
+ dllStencilFunc( func, ref, mask );
+}
+
+static void APIENTRY logStencilMask(GLuint mask)
+{
+ SIG( "glStencilMask" );
+ dllStencilMask( mask );
+}
+
+static void APIENTRY logStencilOp(GLenum fail, GLenum zfail, GLenum zpass)
+{
+ SIG( "glStencilOp" );
+ dllStencilOp( fail, zfail, zpass );
+}
+
+static void APIENTRY logTexCoord1d(GLdouble s)
+{
+ SIG( "glTexCoord1d" );
+ dllTexCoord1d( s );
+}
+
+static void APIENTRY logTexCoord1dv(const GLdouble *v)
+{
+ SIG( "glTexCoord1dv" );
+ dllTexCoord1dv( v );
+}
+
+static void APIENTRY logTexCoord1f(GLfloat s)
+{
+ SIG( "glTexCoord1f" );
+ dllTexCoord1f( s );
+}
+static void APIENTRY logTexCoord1fv(const GLfloat *v)
+{
+ SIG( "glTexCoord1fv" );
+ dllTexCoord1fv( v );
+}
+static void APIENTRY logTexCoord1i(GLint s)
+{
+ SIG( "glTexCoord1i" );
+ dllTexCoord1i( s );
+}
+static void APIENTRY logTexCoord1iv(const GLint *v)
+{
+ SIG( "glTexCoord1iv" );
+ dllTexCoord1iv( v );
+}
+static void APIENTRY logTexCoord1s(GLshort s)
+{
+ SIG( "glTexCoord1s" );
+ dllTexCoord1s( s );
+}
+static void APIENTRY logTexCoord1sv(const GLshort *v)
+{
+ SIG( "glTexCoord1sv" );
+ dllTexCoord1sv( v );
+}
+static void APIENTRY logTexCoord2d(GLdouble s, GLdouble t)
+{
+ SIG( "glTexCoord2d" );
+ dllTexCoord2d( s, t );
+}
+
+static void APIENTRY logTexCoord2dv(const GLdouble *v)
+{
+ SIG( "glTexCoord2dv" );
+ dllTexCoord2dv( v );
+}
+static void APIENTRY logTexCoord2f(GLfloat s, GLfloat t)
+{
+ SIG( "glTexCoord2f" );
+ dllTexCoord2f( s, t );
+}
+static void APIENTRY logTexCoord2fv(const GLfloat *v)
+{
+ SIG( "glTexCoord2fv" );
+ dllTexCoord2fv( v );
+}
+static void APIENTRY logTexCoord2i(GLint s, GLint t)
+{
+ SIG( "glTexCoord2i" );
+ dllTexCoord2i( s, t );
+}
+static void APIENTRY logTexCoord2iv(const GLint *v)
+{
+ SIG( "glTexCoord2iv" );
+ dllTexCoord2iv( v );
+}
+static void APIENTRY logTexCoord2s(GLshort s, GLshort t)
+{
+ SIG( "glTexCoord2s" );
+ dllTexCoord2s( s, t );
+}
+static void APIENTRY logTexCoord2sv(const GLshort *v)
+{
+ SIG( "glTexCoord2sv" );
+ dllTexCoord2sv( v );
+}
+static void APIENTRY logTexCoord3d(GLdouble s, GLdouble t, GLdouble r)
+{
+ SIG( "glTexCoord3d" );
+ dllTexCoord3d( s, t, r );
+}
+static void APIENTRY logTexCoord3dv(const GLdouble *v)
+{
+ SIG( "glTexCoord3dv" );
+ dllTexCoord3dv( v );
+}
+static void APIENTRY logTexCoord3f(GLfloat s, GLfloat t, GLfloat r)
+{
+ SIG( "glTexCoord3f" );
+ dllTexCoord3f( s, t, r );
+}
+static void APIENTRY logTexCoord3fv(const GLfloat *v)
+{
+ SIG( "glTexCoord3fv" );
+ dllTexCoord3fv( v );
+}
+static void APIENTRY logTexCoord3i(GLint s, GLint t, GLint r)
+{
+ SIG( "glTexCoord3i" );
+ dllTexCoord3i( s, t, r );
+}
+static void APIENTRY logTexCoord3iv(const GLint *v)
+{
+ SIG( "glTexCoord3iv" );
+ dllTexCoord3iv( v );
+}
+static void APIENTRY logTexCoord3s(GLshort s, GLshort t, GLshort r)
+{
+ SIG( "glTexCoord3s" );
+ dllTexCoord3s( s, t, r );
+}
+static void APIENTRY logTexCoord3sv(const GLshort *v)
+{
+ SIG( "glTexCoord3sv" );
+ dllTexCoord3sv( v );
+}
+static void APIENTRY logTexCoord4d(GLdouble s, GLdouble t, GLdouble r, GLdouble q)
+{
+ SIG( "glTexCoord4d" );
+ dllTexCoord4d( s, t, r, q );
+}
+static void APIENTRY logTexCoord4dv(const GLdouble *v)
+{
+ SIG( "glTexCoord4dv" );
+ dllTexCoord4dv( v );
+}
+static void APIENTRY logTexCoord4f(GLfloat s, GLfloat t, GLfloat r, GLfloat q)
+{
+ SIG( "glTexCoord4f" );
+ dllTexCoord4f( s, t, r, q );
+}
+static void APIENTRY logTexCoord4fv(const GLfloat *v)
+{
+ SIG( "glTexCoord4fv" );
+ dllTexCoord4fv( v );
+}
+static void APIENTRY logTexCoord4i(GLint s, GLint t, GLint r, GLint q)
+{
+ SIG( "glTexCoord4i" );
+ dllTexCoord4i( s, t, r, q );
+}
+static void APIENTRY logTexCoord4iv(const GLint *v)
+{
+ SIG( "glTexCoord4iv" );
+ dllTexCoord4iv( v );
+}
+static void APIENTRY logTexCoord4s(GLshort s, GLshort t, GLshort r, GLshort q)
+{
+ SIG( "glTexCoord4s" );
+ dllTexCoord4s( s, t, r, q );
+}
+static void APIENTRY logTexCoord4sv(const GLshort *v)
+{
+ SIG( "glTexCoord4sv" );
+ dllTexCoord4sv( v );
+}
+static void APIENTRY logTexCoordPointer(GLint size, GLenum type, GLsizei stride, const void *pointer)
+{
+ SIG( "glTexCoordPointer" );
+ dllTexCoordPointer( size, type, stride, pointer );
+}
+
+static void APIENTRY logTexEnvf(GLenum target, GLenum pname, GLfloat param)
+{
+ fprintf( glw_state.log_fp, "glTexEnvf( 0x%x, 0x%x, %f )\n", target, pname, param );
+ dllTexEnvf( target, pname, param );
+}
+
+static void APIENTRY logTexEnvfv(GLenum target, GLenum pname, const GLfloat *params)
+{
+ SIG( "glTexEnvfv" );
+ dllTexEnvfv( target, pname, params );
+}
+
+static void APIENTRY logTexEnvi(GLenum target, GLenum pname, GLint param)
+{
+ fprintf( glw_state.log_fp, "glTexEnvi( 0x%x, 0x%x, 0x%x )\n", target, pname, param );
+ dllTexEnvi( target, pname, param );
+}
+static void APIENTRY logTexEnviv(GLenum target, GLenum pname, const GLint *params)
+{
+ SIG( "glTexEnviv" );
+ dllTexEnviv( target, pname, params );
+}
+
+static void APIENTRY logTexGend(GLenum coord, GLenum pname, GLdouble param)
+{
+ SIG( "glTexGend" );
+ dllTexGend( coord, pname, param );
+}
+
+static void APIENTRY logTexGendv(GLenum coord, GLenum pname, const GLdouble *params)
+{
+ SIG( "glTexGendv" );
+ dllTexGendv( coord, pname, params );
+}
+
+static void APIENTRY logTexGenf(GLenum coord, GLenum pname, GLfloat param)
+{
+ SIG( "glTexGenf" );
+ dllTexGenf( coord, pname, param );
+}
+static void APIENTRY logTexGenfv(GLenum coord, GLenum pname, const GLfloat *params)
+{
+ SIG( "glTexGenfv" );
+ dllTexGenfv( coord, pname, params );
+}
+static void APIENTRY logTexGeni(GLenum coord, GLenum pname, GLint param)
+{
+ SIG( "glTexGeni" );
+ dllTexGeni( coord, pname, param );
+}
+static void APIENTRY logTexGeniv(GLenum coord, GLenum pname, const GLint *params)
+{
+ SIG( "glTexGeniv" );
+ dllTexGeniv( coord, pname, params );
+}
+static void APIENTRY logTexImage1D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels)
+{
+ SIG( "glTexImage1D" );
+ dllTexImage1D( target, level, internalformat, width, border, format, type, pixels );
+}
+static void APIENTRY logTexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels)
+{
+ SIG( "glTexImage2D" );
+ dllTexImage2D( target, level, internalformat, width, height, border, format, type, pixels );
+}
+
+static void APIENTRY logTexParameterf(GLenum target, GLenum pname, GLfloat param)
+{
+ fprintf( glw_state.log_fp, "glTexParameterf( 0x%x, 0x%x, %f )\n", target, pname, param );
+ dllTexParameterf( target, pname, param );
+}
+
+static void APIENTRY logTexParameterfv(GLenum target, GLenum pname, const GLfloat *params)
+{
+ SIG( "glTexParameterfv" );
+ dllTexParameterfv( target, pname, params );
+}
+static void APIENTRY logTexParameteri(GLenum target, GLenum pname, GLint param)
+{
+ fprintf( glw_state.log_fp, "glTexParameteri( 0x%x, 0x%x, 0x%x )\n", target, pname, param );
+ dllTexParameteri( target, pname, param );
+}
+static void APIENTRY logTexParameteriv(GLenum target, GLenum pname, const GLint *params)
+{
+ SIG( "glTexParameteriv" );
+ dllTexParameteriv( target, pname, params );
+}
+static void APIENTRY logTexSubImage1D(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels)
+{
+ SIG( "glTexSubImage1D" );
+ dllTexSubImage1D( target, level, xoffset, width, format, type, pixels );
+}
+static void APIENTRY logTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels)
+{
+ SIG( "glTexSubImage2D" );
+ dllTexSubImage2D( target, level, xoffset, yoffset, width, height, format, type, pixels );
+}
+static void APIENTRY logTranslated(GLdouble x, GLdouble y, GLdouble z)
+{
+ SIG( "glTranslated" );
+ dllTranslated( x, y, z );
+}
+
+static void APIENTRY logTranslatef(GLfloat x, GLfloat y, GLfloat z)
+{
+ SIG( "glTranslatef" );
+ dllTranslatef( x, y, z );
+}
+
+static void APIENTRY logVertex2d(GLdouble x, GLdouble y)
+{
+ SIG( "glVertex2d" );
+ dllVertex2d( x, y );
+}
+
+static void APIENTRY logVertex2dv(const GLdouble *v)
+{
+ SIG( "glVertex2dv" );
+ dllVertex2dv( v );
+}
+static void APIENTRY logVertex2f(GLfloat x, GLfloat y)
+{
+ SIG( "glVertex2f" );
+ dllVertex2f( x, y );
+}
+static void APIENTRY logVertex2fv(const GLfloat *v)
+{
+ SIG( "glVertex2fv" );
+ dllVertex2fv( v );
+}
+static void APIENTRY logVertex2i(GLint x, GLint y)
+{
+ SIG( "glVertex2i" );
+ dllVertex2i( x, y );
+}
+static void APIENTRY logVertex2iv(const GLint *v)
+{
+ SIG( "glVertex2iv" );
+ dllVertex2iv( v );
+}
+static void APIENTRY logVertex2s(GLshort x, GLshort y)
+{
+ SIG( "glVertex2s" );
+ dllVertex2s( x, y );
+}
+static void APIENTRY logVertex2sv(const GLshort *v)
+{
+ SIG( "glVertex2sv" );
+ dllVertex2sv( v );
+}
+static void APIENTRY logVertex3d(GLdouble x, GLdouble y, GLdouble z)
+{
+ SIG( "glVertex3d" );
+ dllVertex3d( x, y, z );
+}
+static void APIENTRY logVertex3dv(const GLdouble *v)
+{
+ SIG( "glVertex3dv" );
+ dllVertex3dv( v );
+}
+static void APIENTRY logVertex3f(GLfloat x, GLfloat y, GLfloat z)
+{
+ SIG( "glVertex3f" );
+ dllVertex3f( x, y, z );
+}
+static void APIENTRY logVertex3fv(const GLfloat *v)
+{
+ SIG( "glVertex3fv" );
+ dllVertex3fv( v );
+}
+static void APIENTRY logVertex3i(GLint x, GLint y, GLint z)
+{
+ SIG( "glVertex3i" );
+ dllVertex3i( x, y, z );
+}
+static void APIENTRY logVertex3iv(const GLint *v)
+{
+ SIG( "glVertex3iv" );
+ dllVertex3iv( v );
+}
+static void APIENTRY logVertex3s(GLshort x, GLshort y, GLshort z)
+{
+ SIG( "glVertex3s" );
+ dllVertex3s( x, y, z );
+}
+static void APIENTRY logVertex3sv(const GLshort *v)
+{
+ SIG( "glVertex3sv" );
+ dllVertex3sv( v );
+}
+static void APIENTRY logVertex4d(GLdouble x, GLdouble y, GLdouble z, GLdouble w)
+{
+ SIG( "glVertex4d" );
+ dllVertex4d( x, y, z, w );
+}
+static void APIENTRY logVertex4dv(const GLdouble *v)
+{
+ SIG( "glVertex4dv" );
+ dllVertex4dv( v );
+}
+static void APIENTRY logVertex4f(GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+ SIG( "glVertex4f" );
+ dllVertex4f( x, y, z, w );
+}
+static void APIENTRY logVertex4fv(const GLfloat *v)
+{
+ SIG( "glVertex4fv" );
+ dllVertex4fv( v );
+}
+static void APIENTRY logVertex4i(GLint x, GLint y, GLint z, GLint w)
+{
+ SIG( "glVertex4i" );
+ dllVertex4i( x, y, z, w );
+}
+static void APIENTRY logVertex4iv(const GLint *v)
+{
+ SIG( "glVertex4iv" );
+ dllVertex4iv( v );
+}
+static void APIENTRY logVertex4s(GLshort x, GLshort y, GLshort z, GLshort w)
+{
+ SIG( "glVertex4s" );
+ dllVertex4s( x, y, z, w );
+}
+static void APIENTRY logVertex4sv(const GLshort *v)
+{
+ SIG( "glVertex4sv" );
+ dllVertex4sv( v );
+}
+static void APIENTRY logVertexPointer(GLint size, GLenum type, GLsizei stride, const void *pointer)
+{
+ SIG( "glVertexPointer" );
+ dllVertexPointer( size, type, stride, pointer );
+}
+static void APIENTRY logViewport(GLint x, GLint y, GLsizei width, GLsizei height)
+{
+ SIG( "glViewport" );
+ dllViewport( x, y, width, height );
+}
+
+/*
+** QGL_Shutdown
+**
+** Unloads the specified DLL then nulls out all the proc pointers.
+*/
+void QGL_Shutdown( void )
+{
+ if ( glw_state.OpenGLLib )
+ {
+ dlclose ( glw_state.OpenGLLib );
+ glw_state.OpenGLLib = NULL;
+ }
+
+ glw_state.OpenGLLib = NULL;
+
+ qglAccum = NULL;
+ qglAlphaFunc = NULL;
+ qglAreTexturesResident = NULL;
+ qglArrayElement = NULL;
+ qglBegin = NULL;
+ qglBindTexture = NULL;
+ qglBitmap = NULL;
+ qglBlendFunc = NULL;
+ qglCallList = NULL;
+ qglCallLists = NULL;
+ qglClear = NULL;
+ qglClearAccum = NULL;
+ qglClearColor = NULL;
+ qglClearDepth = NULL;
+ qglClearIndex = NULL;
+ qglClearStencil = NULL;
+ qglClipPlane = NULL;
+ qglColor3b = NULL;
+ qglColor3bv = NULL;
+ qglColor3d = NULL;
+ qglColor3dv = NULL;
+ qglColor3f = NULL;
+ qglColor3fv = NULL;
+ qglColor3i = NULL;
+ qglColor3iv = NULL;
+ qglColor3s = NULL;
+ qglColor3sv = NULL;
+ qglColor3ub = NULL;
+ qglColor3ubv = NULL;
+ qglColor3ui = NULL;
+ qglColor3uiv = NULL;
+ qglColor3us = NULL;
+ qglColor3usv = NULL;
+ qglColor4b = NULL;
+ qglColor4bv = NULL;
+ qglColor4d = NULL;
+ qglColor4dv = NULL;
+ qglColor4f = NULL;
+ qglColor4fv = NULL;
+ qglColor4i = NULL;
+ qglColor4iv = NULL;
+ qglColor4s = NULL;
+ qglColor4sv = NULL;
+ qglColor4ub = NULL;
+ qglColor4ubv = NULL;
+ qglColor4ui = NULL;
+ qglColor4uiv = NULL;
+ qglColor4us = NULL;
+ qglColor4usv = NULL;
+ qglColorMask = NULL;
+ qglColorMaterial = NULL;
+ qglColorPointer = NULL;
+ qglCopyPixels = NULL;
+ qglCopyTexImage1D = NULL;
+ qglCopyTexImage2D = NULL;
+ qglCopyTexSubImage1D = NULL;
+ qglCopyTexSubImage2D = NULL;
+ qglCullFace = NULL;
+ qglDeleteLists = NULL;
+ qglDeleteTextures = NULL;
+ qglDepthFunc = NULL;
+ qglDepthMask = NULL;
+ qglDepthRange = NULL;
+ qglDisable = NULL;
+ qglDisableClientState = NULL;
+ qglDrawArrays = NULL;
+ qglDrawBuffer = NULL;
+ qglDrawElements = NULL;
+ qglDrawPixels = NULL;
+ qglEdgeFlag = NULL;
+ qglEdgeFlagPointer = NULL;
+ qglEdgeFlagv = NULL;
+ qglEnable = NULL;
+ qglEnableClientState = NULL;
+ qglEnd = NULL;
+ qglEndList = NULL;
+ qglEvalCoord1d = NULL;
+ qglEvalCoord1dv = NULL;
+ qglEvalCoord1f = NULL;
+ qglEvalCoord1fv = NULL;
+ qglEvalCoord2d = NULL;
+ qglEvalCoord2dv = NULL;
+ qglEvalCoord2f = NULL;
+ qglEvalCoord2fv = NULL;
+ qglEvalMesh1 = NULL;
+ qglEvalMesh2 = NULL;
+ qglEvalPoint1 = NULL;
+ qglEvalPoint2 = NULL;
+ qglFeedbackBuffer = NULL;
+ qglFinish = NULL;
+ qglFlush = NULL;
+ qglFogf = NULL;
+ qglFogfv = NULL;
+ qglFogi = NULL;
+ qglFogiv = NULL;
+ qglFrontFace = NULL;
+ qglFrustum = NULL;
+ qglGenLists = NULL;
+ qglGenTextures = NULL;
+ qglGetBooleanv = NULL;
+ qglGetClipPlane = NULL;
+ qglGetDoublev = NULL;
+ qglGetError = NULL;
+ qglGetFloatv = NULL;
+ qglGetIntegerv = NULL;
+ qglGetLightfv = NULL;
+ qglGetLightiv = NULL;
+ qglGetMapdv = NULL;
+ qglGetMapfv = NULL;
+ qglGetMapiv = NULL;
+ qglGetMaterialfv = NULL;
+ qglGetMaterialiv = NULL;
+ qglGetPixelMapfv = NULL;
+ qglGetPixelMapuiv = NULL;
+ qglGetPixelMapusv = NULL;
+ qglGetPointerv = NULL;
+ qglGetPolygonStipple = NULL;
+ qglGetString = NULL;
+ qglGetTexEnvfv = NULL;
+ qglGetTexEnviv = NULL;
+ qglGetTexGendv = NULL;
+ qglGetTexGenfv = NULL;
+ qglGetTexGeniv = NULL;
+ qglGetTexImage = NULL;
+ qglGetTexLevelParameterfv = NULL;
+ qglGetTexLevelParameteriv = NULL;
+ qglGetTexParameterfv = NULL;
+ qglGetTexParameteriv = NULL;
+ qglHint = NULL;
+ qglIndexMask = NULL;
+ qglIndexPointer = NULL;
+ qglIndexd = NULL;
+ qglIndexdv = NULL;
+ qglIndexf = NULL;
+ qglIndexfv = NULL;
+ qglIndexi = NULL;
+ qglIndexiv = NULL;
+ qglIndexs = NULL;
+ qglIndexsv = NULL;
+ qglIndexub = NULL;
+ qglIndexubv = NULL;
+ qglInitNames = NULL;
+ qglInterleavedArrays = NULL;
+ qglIsEnabled = NULL;
+ qglIsList = NULL;
+ qglIsTexture = NULL;
+ qglLightModelf = NULL;
+ qglLightModelfv = NULL;
+ qglLightModeli = NULL;
+ qglLightModeliv = NULL;
+ qglLightf = NULL;
+ qglLightfv = NULL;
+ qglLighti = NULL;
+ qglLightiv = NULL;
+ qglLineStipple = NULL;
+ qglLineWidth = NULL;
+ qglListBase = NULL;
+ qglLoadIdentity = NULL;
+ qglLoadMatrixd = NULL;
+ qglLoadMatrixf = NULL;
+ qglLoadName = NULL;
+ qglLogicOp = NULL;
+ qglMap1d = NULL;
+ qglMap1f = NULL;
+ qglMap2d = NULL;
+ qglMap2f = NULL;
+ qglMapGrid1d = NULL;
+ qglMapGrid1f = NULL;
+ qglMapGrid2d = NULL;
+ qglMapGrid2f = NULL;
+ qglMaterialf = NULL;
+ qglMaterialfv = NULL;
+ qglMateriali = NULL;
+ qglMaterialiv = NULL;
+ qglMatrixMode = NULL;
+ qglMultMatrixd = NULL;
+ qglMultMatrixf = NULL;
+ qglNewList = NULL;
+ qglNormal3b = NULL;
+ qglNormal3bv = NULL;
+ qglNormal3d = NULL;
+ qglNormal3dv = NULL;
+ qglNormal3f = NULL;
+ qglNormal3fv = NULL;
+ qglNormal3i = NULL;
+ qglNormal3iv = NULL;
+ qglNormal3s = NULL;
+ qglNormal3sv = NULL;
+ qglNormalPointer = NULL;
+ qglOrtho = NULL;
+ qglPassThrough = NULL;
+ qglPixelMapfv = NULL;
+ qglPixelMapuiv = NULL;
+ qglPixelMapusv = NULL;
+ qglPixelStoref = NULL;
+ qglPixelStorei = NULL;
+ qglPixelTransferf = NULL;
+ qglPixelTransferi = NULL;
+ qglPixelZoom = NULL;
+ qglPointSize = NULL;
+ qglPolygonMode = NULL;
+ qglPolygonOffset = NULL;
+ qglPolygonStipple = NULL;
+ qglPopAttrib = NULL;
+ qglPopClientAttrib = NULL;
+ qglPopMatrix = NULL;
+ qglPopName = NULL;
+ qglPrioritizeTextures = NULL;
+ qglPushAttrib = NULL;
+ qglPushClientAttrib = NULL;
+ qglPushMatrix = NULL;
+ qglPushName = NULL;
+ qglRasterPos2d = NULL;
+ qglRasterPos2dv = NULL;
+ qglRasterPos2f = NULL;
+ qglRasterPos2fv = NULL;
+ qglRasterPos2i = NULL;
+ qglRasterPos2iv = NULL;
+ qglRasterPos2s = NULL;
+ qglRasterPos2sv = NULL;
+ qglRasterPos3d = NULL;
+ qglRasterPos3dv = NULL;
+ qglRasterPos3f = NULL;
+ qglRasterPos3fv = NULL;
+ qglRasterPos3i = NULL;
+ qglRasterPos3iv = NULL;
+ qglRasterPos3s = NULL;
+ qglRasterPos3sv = NULL;
+ qglRasterPos4d = NULL;
+ qglRasterPos4dv = NULL;
+ qglRasterPos4f = NULL;
+ qglRasterPos4fv = NULL;
+ qglRasterPos4i = NULL;
+ qglRasterPos4iv = NULL;
+ qglRasterPos4s = NULL;
+ qglRasterPos4sv = NULL;
+ qglReadBuffer = NULL;
+ qglReadPixels = NULL;
+ qglRectd = NULL;
+ qglRectdv = NULL;
+ qglRectf = NULL;
+ qglRectfv = NULL;
+ qglRecti = NULL;
+ qglRectiv = NULL;
+ qglRects = NULL;
+ qglRectsv = NULL;
+ qglRenderMode = NULL;
+ qglRotated = NULL;
+ qglRotatef = NULL;
+ qglScaled = NULL;
+ qglScalef = NULL;
+ qglScissor = NULL;
+ qglSelectBuffer = NULL;
+ qglShadeModel = NULL;
+ qglStencilFunc = NULL;
+ qglStencilMask = NULL;
+ qglStencilOp = NULL;
+ qglTexCoord1d = NULL;
+ qglTexCoord1dv = NULL;
+ qglTexCoord1f = NULL;
+ qglTexCoord1fv = NULL;
+ qglTexCoord1i = NULL;
+ qglTexCoord1iv = NULL;
+ qglTexCoord1s = NULL;
+ qglTexCoord1sv = NULL;
+ qglTexCoord2d = NULL;
+ qglTexCoord2dv = NULL;
+ qglTexCoord2f = NULL;
+ qglTexCoord2fv = NULL;
+ qglTexCoord2i = NULL;
+ qglTexCoord2iv = NULL;
+ qglTexCoord2s = NULL;
+ qglTexCoord2sv = NULL;
+ qglTexCoord3d = NULL;
+ qglTexCoord3dv = NULL;
+ qglTexCoord3f = NULL;
+ qglTexCoord3fv = NULL;
+ qglTexCoord3i = NULL;
+ qglTexCoord3iv = NULL;
+ qglTexCoord3s = NULL;
+ qglTexCoord3sv = NULL;
+ qglTexCoord4d = NULL;
+ qglTexCoord4dv = NULL;
+ qglTexCoord4f = NULL;
+ qglTexCoord4fv = NULL;
+ qglTexCoord4i = NULL;
+ qglTexCoord4iv = NULL;
+ qglTexCoord4s = NULL;
+ qglTexCoord4sv = NULL;
+ qglTexCoordPointer = NULL;
+ qglTexEnvf = NULL;
+ qglTexEnvfv = NULL;
+ qglTexEnvi = NULL;
+ qglTexEnviv = NULL;
+ qglTexGend = NULL;
+ qglTexGendv = NULL;
+ qglTexGenf = NULL;
+ qglTexGenfv = NULL;
+ qglTexGeni = NULL;
+ qglTexGeniv = NULL;
+ qglTexImage1D = NULL;
+ qglTexImage2D = NULL;
+ qglTexParameterf = NULL;
+ qglTexParameterfv = NULL;
+ qglTexParameteri = NULL;
+ qglTexParameteriv = NULL;
+ qglTexSubImage1D = NULL;
+ qglTexSubImage2D = NULL;
+ qglTranslated = NULL;
+ qglTranslatef = NULL;
+ qglVertex2d = NULL;
+ qglVertex2dv = NULL;
+ qglVertex2f = NULL;
+ qglVertex2fv = NULL;
+ qglVertex2i = NULL;
+ qglVertex2iv = NULL;
+ qglVertex2s = NULL;
+ qglVertex2sv = NULL;
+ qglVertex3d = NULL;
+ qglVertex3dv = NULL;
+ qglVertex3f = NULL;
+ qglVertex3fv = NULL;
+ qglVertex3i = NULL;
+ qglVertex3iv = NULL;
+ qglVertex3s = NULL;
+ qglVertex3sv = NULL;
+ qglVertex4d = NULL;
+ qglVertex4dv = NULL;
+ qglVertex4f = NULL;
+ qglVertex4fv = NULL;
+ qglVertex4i = NULL;
+ qglVertex4iv = NULL;
+ qglVertex4s = NULL;
+ qglVertex4sv = NULL;
+ qglVertexPointer = NULL;
+ qglViewport = NULL;
+
+// bk001129 - from cvs1.17 (mkv)
+#if defined(__FX__)
+ qfxMesaCreateContext = NULL;
+ qfxMesaCreateBestContext = NULL;
+ qfxMesaDestroyContext = NULL;
+ qfxMesaMakeCurrent = NULL;
+ qfxMesaGetCurrentContext = NULL;
+ qfxMesaSwapBuffers = NULL;
+#endif
+
+ qglXChooseVisual = NULL;
+ qglXCreateContext = NULL;
+ qglXDestroyContext = NULL;
+ qglXMakeCurrent = NULL;
+ qglXCopyContext = NULL;
+ qglXSwapBuffers = NULL;
+}
+
+#define GPA( a ) dlsym( glw_state.OpenGLLib, a )
+
+void *qwglGetProcAddress(char *symbol)
+{
+ if (glw_state.OpenGLLib)
+ return GPA ( symbol );
+ return NULL;
+}
+
+/*
+** QGL_Init
+**
+** This is responsible for binding our qgl function pointers to
+** the appropriate GL stuff. In Windows this means doing a
+** LoadLibrary and a bunch of calls to GetProcAddress. On other
+** operating systems we need to do the right thing, whatever that
+** might be.
+**
+*/
+
+qboolean QGL_Init( const char *dllname )
+{
+ if ( ( glw_state.OpenGLLib = dlopen( dllname, RTLD_LAZY|RTLD_GLOBAL ) ) == 0 )
+ {
+ char fn[1024];
+ // FILE *fp; // bk001204 - unused
+ extern uid_t saved_euid; // unix_main.c
+
+ // if we are not setuid, try current directory
+ if (getuid() == saved_euid) {
+ getcwd(fn, sizeof(fn));
+ Q_strcat(fn, sizeof(fn), "/");
+ Q_strcat(fn, sizeof(fn), dllname);
+
+ if ( ( glw_state.OpenGLLib = dlopen( fn, RTLD_LAZY ) ) == 0 ) {
+ ri.Printf(PRINT_ALL, "QGL_Init: Can't load %s from /etc/ld.so.conf or current dir: %s\n", dllname, dlerror());
+ return qfalse;
+ }
+ } else {
+ ri.Printf(PRINT_ALL, "QGL_Init: Can't load %s from /etc/ld.so.conf: %s\n", dllname, dlerror());
+ return qfalse;
+ }
+ }
+
+ qglAccum = dllAccum = GPA( "glAccum" );
+ qglAlphaFunc = dllAlphaFunc = GPA( "glAlphaFunc" );
+ qglAreTexturesResident = dllAreTexturesResident = GPA( "glAreTexturesResident" );
+ qglArrayElement = dllArrayElement = GPA( "glArrayElement" );
+ qglBegin = dllBegin = GPA( "glBegin" );
+ qglBindTexture = dllBindTexture = GPA( "glBindTexture" );
+ qglBitmap = dllBitmap = GPA( "glBitmap" );
+ qglBlendFunc = dllBlendFunc = GPA( "glBlendFunc" );
+ qglCallList = dllCallList = GPA( "glCallList" );
+ qglCallLists = dllCallLists = GPA( "glCallLists" );
+ qglClear = dllClear = GPA( "glClear" );
+ qglClearAccum = dllClearAccum = GPA( "glClearAccum" );
+ qglClearColor = dllClearColor = GPA( "glClearColor" );
+ qglClearDepth = dllClearDepth = GPA( "glClearDepth" );
+ qglClearIndex = dllClearIndex = GPA( "glClearIndex" );
+ qglClearStencil = dllClearStencil = GPA( "glClearStencil" );
+ qglClipPlane = dllClipPlane = GPA( "glClipPlane" );
+ qglColor3b = dllColor3b = GPA( "glColor3b" );
+ qglColor3bv = dllColor3bv = GPA( "glColor3bv" );
+ qglColor3d = dllColor3d = GPA( "glColor3d" );
+ qglColor3dv = dllColor3dv = GPA( "glColor3dv" );
+ qglColor3f = dllColor3f = GPA( "glColor3f" );
+ qglColor3fv = dllColor3fv = GPA( "glColor3fv" );
+ qglColor3i = dllColor3i = GPA( "glColor3i" );
+ qglColor3iv = dllColor3iv = GPA( "glColor3iv" );
+ qglColor3s = dllColor3s = GPA( "glColor3s" );
+ qglColor3sv = dllColor3sv = GPA( "glColor3sv" );
+ qglColor3ub = dllColor3ub = GPA( "glColor3ub" );
+ qglColor3ubv = dllColor3ubv = GPA( "glColor3ubv" );
+ qglColor3ui = dllColor3ui = GPA( "glColor3ui" );
+ qglColor3uiv = dllColor3uiv = GPA( "glColor3uiv" );
+ qglColor3us = dllColor3us = GPA( "glColor3us" );
+ qglColor3usv = dllColor3usv = GPA( "glColor3usv" );
+ qglColor4b = dllColor4b = GPA( "glColor4b" );
+ qglColor4bv = dllColor4bv = GPA( "glColor4bv" );
+ qglColor4d = dllColor4d = GPA( "glColor4d" );
+ qglColor4dv = dllColor4dv = GPA( "glColor4dv" );
+ qglColor4f = dllColor4f = GPA( "glColor4f" );
+ qglColor4fv = dllColor4fv = GPA( "glColor4fv" );
+ qglColor4i = dllColor4i = GPA( "glColor4i" );
+ qglColor4iv = dllColor4iv = GPA( "glColor4iv" );
+ qglColor4s = dllColor4s = GPA( "glColor4s" );
+ qglColor4sv = dllColor4sv = GPA( "glColor4sv" );
+ qglColor4ub = dllColor4ub = GPA( "glColor4ub" );
+ qglColor4ubv = dllColor4ubv = GPA( "glColor4ubv" );
+ qglColor4ui = dllColor4ui = GPA( "glColor4ui" );
+ qglColor4uiv = dllColor4uiv = GPA( "glColor4uiv" );
+ qglColor4us = dllColor4us = GPA( "glColor4us" );
+ qglColor4usv = dllColor4usv = GPA( "glColor4usv" );
+ qglColorMask = dllColorMask = GPA( "glColorMask" );
+ qglColorMaterial = dllColorMaterial = GPA( "glColorMaterial" );
+ qglColorPointer = dllColorPointer = GPA( "glColorPointer" );
+ qglCopyPixels = dllCopyPixels = GPA( "glCopyPixels" );
+ qglCopyTexImage1D = dllCopyTexImage1D = GPA( "glCopyTexImage1D" );
+ qglCopyTexImage2D = dllCopyTexImage2D = GPA( "glCopyTexImage2D" );
+ qglCopyTexSubImage1D = dllCopyTexSubImage1D = GPA( "glCopyTexSubImage1D" );
+ qglCopyTexSubImage2D = dllCopyTexSubImage2D = GPA( "glCopyTexSubImage2D" );
+ qglCullFace = dllCullFace = GPA( "glCullFace" );
+ qglDeleteLists = dllDeleteLists = GPA( "glDeleteLists" );
+ qglDeleteTextures = dllDeleteTextures = GPA( "glDeleteTextures" );
+ qglDepthFunc = dllDepthFunc = GPA( "glDepthFunc" );
+ qglDepthMask = dllDepthMask = GPA( "glDepthMask" );
+ qglDepthRange = dllDepthRange = GPA( "glDepthRange" );
+ qglDisable = dllDisable = GPA( "glDisable" );
+ qglDisableClientState = dllDisableClientState = GPA( "glDisableClientState" );
+ qglDrawArrays = dllDrawArrays = GPA( "glDrawArrays" );
+ qglDrawBuffer = dllDrawBuffer = GPA( "glDrawBuffer" );
+ qglDrawElements = dllDrawElements = GPA( "glDrawElements" );
+ qglDrawPixels = dllDrawPixels = GPA( "glDrawPixels" );
+ qglEdgeFlag = dllEdgeFlag = GPA( "glEdgeFlag" );
+ qglEdgeFlagPointer = dllEdgeFlagPointer = GPA( "glEdgeFlagPointer" );
+ qglEdgeFlagv = dllEdgeFlagv = GPA( "glEdgeFlagv" );
+ qglEnable = dllEnable = GPA( "glEnable" );
+ qglEnableClientState = dllEnableClientState = GPA( "glEnableClientState" );
+ qglEnd = dllEnd = GPA( "glEnd" );
+ qglEndList = dllEndList = GPA( "glEndList" );
+ qglEvalCoord1d = dllEvalCoord1d = GPA( "glEvalCoord1d" );
+ qglEvalCoord1dv = dllEvalCoord1dv = GPA( "glEvalCoord1dv" );
+ qglEvalCoord1f = dllEvalCoord1f = GPA( "glEvalCoord1f" );
+ qglEvalCoord1fv = dllEvalCoord1fv = GPA( "glEvalCoord1fv" );
+ qglEvalCoord2d = dllEvalCoord2d = GPA( "glEvalCoord2d" );
+ qglEvalCoord2dv = dllEvalCoord2dv = GPA( "glEvalCoord2dv" );
+ qglEvalCoord2f = dllEvalCoord2f = GPA( "glEvalCoord2f" );
+ qglEvalCoord2fv = dllEvalCoord2fv = GPA( "glEvalCoord2fv" );
+ qglEvalMesh1 = dllEvalMesh1 = GPA( "glEvalMesh1" );
+ qglEvalMesh2 = dllEvalMesh2 = GPA( "glEvalMesh2" );
+ qglEvalPoint1 = dllEvalPoint1 = GPA( "glEvalPoint1" );
+ qglEvalPoint2 = dllEvalPoint2 = GPA( "glEvalPoint2" );
+ qglFeedbackBuffer = dllFeedbackBuffer = GPA( "glFeedbackBuffer" );
+ qglFinish = dllFinish = GPA( "glFinish" );
+ qglFlush = dllFlush = GPA( "glFlush" );
+ qglFogf = dllFogf = GPA( "glFogf" );
+ qglFogfv = dllFogfv = GPA( "glFogfv" );
+ qglFogi = dllFogi = GPA( "glFogi" );
+ qglFogiv = dllFogiv = GPA( "glFogiv" );
+ qglFrontFace = dllFrontFace = GPA( "glFrontFace" );
+ qglFrustum = dllFrustum = GPA( "glFrustum" );
+ qglGenLists = dllGenLists = GPA( "glGenLists" );
+ qglGenTextures = dllGenTextures = GPA( "glGenTextures" );
+ qglGetBooleanv = dllGetBooleanv = GPA( "glGetBooleanv" );
+ qglGetClipPlane = dllGetClipPlane = GPA( "glGetClipPlane" );
+ qglGetDoublev = dllGetDoublev = GPA( "glGetDoublev" );
+ qglGetError = dllGetError = GPA( "glGetError" );
+ qglGetFloatv = dllGetFloatv = GPA( "glGetFloatv" );
+ qglGetIntegerv = dllGetIntegerv = GPA( "glGetIntegerv" );
+ qglGetLightfv = dllGetLightfv = GPA( "glGetLightfv" );
+ qglGetLightiv = dllGetLightiv = GPA( "glGetLightiv" );
+ qglGetMapdv = dllGetMapdv = GPA( "glGetMapdv" );
+ qglGetMapfv = dllGetMapfv = GPA( "glGetMapfv" );
+ qglGetMapiv = dllGetMapiv = GPA( "glGetMapiv" );
+ qglGetMaterialfv = dllGetMaterialfv = GPA( "glGetMaterialfv" );
+ qglGetMaterialiv = dllGetMaterialiv = GPA( "glGetMaterialiv" );
+ qglGetPixelMapfv = dllGetPixelMapfv = GPA( "glGetPixelMapfv" );
+ qglGetPixelMapuiv = dllGetPixelMapuiv = GPA( "glGetPixelMapuiv" );
+ qglGetPixelMapusv = dllGetPixelMapusv = GPA( "glGetPixelMapusv" );
+ qglGetPointerv = dllGetPointerv = GPA( "glGetPointerv" );
+ qglGetPolygonStipple = dllGetPolygonStipple = GPA( "glGetPolygonStipple" );
+ qglGetString = dllGetString = GPA( "glGetString" );
+ qglGetTexEnvfv = dllGetTexEnvfv = GPA( "glGetTexEnvfv" );
+ qglGetTexEnviv = dllGetTexEnviv = GPA( "glGetTexEnviv" );
+ qglGetTexGendv = dllGetTexGendv = GPA( "glGetTexGendv" );
+ qglGetTexGenfv = dllGetTexGenfv = GPA( "glGetTexGenfv" );
+ qglGetTexGeniv = dllGetTexGeniv = GPA( "glGetTexGeniv" );
+ qglGetTexImage = dllGetTexImage = GPA( "glGetTexImage" );
+ qglGetTexParameterfv = dllGetTexParameterfv = GPA( "glGetTexParameterfv" );
+ qglGetTexParameteriv = dllGetTexParameteriv = GPA( "glGetTexParameteriv" );
+ qglHint = dllHint = GPA( "glHint" );
+ qglIndexMask = dllIndexMask = GPA( "glIndexMask" );
+ qglIndexPointer = dllIndexPointer = GPA( "glIndexPointer" );
+ qglIndexd = dllIndexd = GPA( "glIndexd" );
+ qglIndexdv = dllIndexdv = GPA( "glIndexdv" );
+ qglIndexf = dllIndexf = GPA( "glIndexf" );
+ qglIndexfv = dllIndexfv = GPA( "glIndexfv" );
+ qglIndexi = dllIndexi = GPA( "glIndexi" );
+ qglIndexiv = dllIndexiv = GPA( "glIndexiv" );
+ qglIndexs = dllIndexs = GPA( "glIndexs" );
+ qglIndexsv = dllIndexsv = GPA( "glIndexsv" );
+ qglIndexub = dllIndexub = GPA( "glIndexub" );
+ qglIndexubv = dllIndexubv = GPA( "glIndexubv" );
+ qglInitNames = dllInitNames = GPA( "glInitNames" );
+ qglInterleavedArrays = dllInterleavedArrays = GPA( "glInterleavedArrays" );
+ qglIsEnabled = dllIsEnabled = GPA( "glIsEnabled" );
+ qglIsList = dllIsList = GPA( "glIsList" );
+ qglIsTexture = dllIsTexture = GPA( "glIsTexture" );
+ qglLightModelf = dllLightModelf = GPA( "glLightModelf" );
+ qglLightModelfv = dllLightModelfv = GPA( "glLightModelfv" );
+ qglLightModeli = dllLightModeli = GPA( "glLightModeli" );
+ qglLightModeliv = dllLightModeliv = GPA( "glLightModeliv" );
+ qglLightf = dllLightf = GPA( "glLightf" );
+ qglLightfv = dllLightfv = GPA( "glLightfv" );
+ qglLighti = dllLighti = GPA( "glLighti" );
+ qglLightiv = dllLightiv = GPA( "glLightiv" );
+ qglLineStipple = dllLineStipple = GPA( "glLineStipple" );
+ qglLineWidth = dllLineWidth = GPA( "glLineWidth" );
+ qglListBase = dllListBase = GPA( "glListBase" );
+ qglLoadIdentity = dllLoadIdentity = GPA( "glLoadIdentity" );
+ qglLoadMatrixd = dllLoadMatrixd = GPA( "glLoadMatrixd" );
+ qglLoadMatrixf = dllLoadMatrixf = GPA( "glLoadMatrixf" );
+ qglLoadName = dllLoadName = GPA( "glLoadName" );
+ qglLogicOp = dllLogicOp = GPA( "glLogicOp" );
+ qglMap1d = dllMap1d = GPA( "glMap1d" );
+ qglMap1f = dllMap1f = GPA( "glMap1f" );
+ qglMap2d = dllMap2d = GPA( "glMap2d" );
+ qglMap2f = dllMap2f = GPA( "glMap2f" );
+ qglMapGrid1d = dllMapGrid1d = GPA( "glMapGrid1d" );
+ qglMapGrid1f = dllMapGrid1f = GPA( "glMapGrid1f" );
+ qglMapGrid2d = dllMapGrid2d = GPA( "glMapGrid2d" );
+ qglMapGrid2f = dllMapGrid2f = GPA( "glMapGrid2f" );
+ qglMaterialf = dllMaterialf = GPA( "glMaterialf" );
+ qglMaterialfv = dllMaterialfv = GPA( "glMaterialfv" );
+ qglMateriali = dllMateriali = GPA( "glMateriali" );
+ qglMaterialiv = dllMaterialiv = GPA( "glMaterialiv" );
+ qglMatrixMode = dllMatrixMode = GPA( "glMatrixMode" );
+ qglMultMatrixd = dllMultMatrixd = GPA( "glMultMatrixd" );
+ qglMultMatrixf = dllMultMatrixf = GPA( "glMultMatrixf" );
+ qglNewList = dllNewList = GPA( "glNewList" );
+ qglNormal3b = dllNormal3b = GPA( "glNormal3b" );
+ qglNormal3bv = dllNormal3bv = GPA( "glNormal3bv" );
+ qglNormal3d = dllNormal3d = GPA( "glNormal3d" );
+ qglNormal3dv = dllNormal3dv = GPA( "glNormal3dv" );
+ qglNormal3f = dllNormal3f = GPA( "glNormal3f" );
+ qglNormal3fv = dllNormal3fv = GPA( "glNormal3fv" );
+ qglNormal3i = dllNormal3i = GPA( "glNormal3i" );
+ qglNormal3iv = dllNormal3iv = GPA( "glNormal3iv" );
+ qglNormal3s = dllNormal3s = GPA( "glNormal3s" );
+ qglNormal3sv = dllNormal3sv = GPA( "glNormal3sv" );
+ qglNormalPointer = dllNormalPointer = GPA( "glNormalPointer" );
+ qglOrtho = dllOrtho = GPA( "glOrtho" );
+ qglPassThrough = dllPassThrough = GPA( "glPassThrough" );
+ qglPixelMapfv = dllPixelMapfv = GPA( "glPixelMapfv" );
+ qglPixelMapuiv = dllPixelMapuiv = GPA( "glPixelMapuiv" );
+ qglPixelMapusv = dllPixelMapusv = GPA( "glPixelMapusv" );
+ qglPixelStoref = dllPixelStoref = GPA( "glPixelStoref" );
+ qglPixelStorei = dllPixelStorei = GPA( "glPixelStorei" );
+ qglPixelTransferf = dllPixelTransferf = GPA( "glPixelTransferf" );
+ qglPixelTransferi = dllPixelTransferi = GPA( "glPixelTransferi" );
+ qglPixelZoom = dllPixelZoom = GPA( "glPixelZoom" );
+ qglPointSize = dllPointSize = GPA( "glPointSize" );
+ qglPolygonMode = dllPolygonMode = GPA( "glPolygonMode" );
+ qglPolygonOffset = dllPolygonOffset = GPA( "glPolygonOffset" );
+ qglPolygonStipple = dllPolygonStipple = GPA( "glPolygonStipple" );
+ qglPopAttrib = dllPopAttrib = GPA( "glPopAttrib" );
+ qglPopClientAttrib = dllPopClientAttrib = GPA( "glPopClientAttrib" );
+ qglPopMatrix = dllPopMatrix = GPA( "glPopMatrix" );
+ qglPopName = dllPopName = GPA( "glPopName" );
+ qglPrioritizeTextures = dllPrioritizeTextures = GPA( "glPrioritizeTextures" );
+ qglPushAttrib = dllPushAttrib = GPA( "glPushAttrib" );
+ qglPushClientAttrib = dllPushClientAttrib = GPA( "glPushClientAttrib" );
+ qglPushMatrix = dllPushMatrix = GPA( "glPushMatrix" );
+ qglPushName = dllPushName = GPA( "glPushName" );
+ qglRasterPos2d = dllRasterPos2d = GPA( "glRasterPos2d" );
+ qglRasterPos2dv = dllRasterPos2dv = GPA( "glRasterPos2dv" );
+ qglRasterPos2f = dllRasterPos2f = GPA( "glRasterPos2f" );
+ qglRasterPos2fv = dllRasterPos2fv = GPA( "glRasterPos2fv" );
+ qglRasterPos2i = dllRasterPos2i = GPA( "glRasterPos2i" );
+ qglRasterPos2iv = dllRasterPos2iv = GPA( "glRasterPos2iv" );
+ qglRasterPos2s = dllRasterPos2s = GPA( "glRasterPos2s" );
+ qglRasterPos2sv = dllRasterPos2sv = GPA( "glRasterPos2sv" );
+ qglRasterPos3d = dllRasterPos3d = GPA( "glRasterPos3d" );
+ qglRasterPos3dv = dllRasterPos3dv = GPA( "glRasterPos3dv" );
+ qglRasterPos3f = dllRasterPos3f = GPA( "glRasterPos3f" );
+ qglRasterPos3fv = dllRasterPos3fv = GPA( "glRasterPos3fv" );
+ qglRasterPos3i = dllRasterPos3i = GPA( "glRasterPos3i" );
+ qglRasterPos3iv = dllRasterPos3iv = GPA( "glRasterPos3iv" );
+ qglRasterPos3s = dllRasterPos3s = GPA( "glRasterPos3s" );
+ qglRasterPos3sv = dllRasterPos3sv = GPA( "glRasterPos3sv" );
+ qglRasterPos4d = dllRasterPos4d = GPA( "glRasterPos4d" );
+ qglRasterPos4dv = dllRasterPos4dv = GPA( "glRasterPos4dv" );
+ qglRasterPos4f = dllRasterPos4f = GPA( "glRasterPos4f" );
+ qglRasterPos4fv = dllRasterPos4fv = GPA( "glRasterPos4fv" );
+ qglRasterPos4i = dllRasterPos4i = GPA( "glRasterPos4i" );
+ qglRasterPos4iv = dllRasterPos4iv = GPA( "glRasterPos4iv" );
+ qglRasterPos4s = dllRasterPos4s = GPA( "glRasterPos4s" );
+ qglRasterPos4sv = dllRasterPos4sv = GPA( "glRasterPos4sv" );
+ qglReadBuffer = dllReadBuffer = GPA( "glReadBuffer" );
+ qglReadPixels = dllReadPixels = GPA( "glReadPixels" );
+ qglRectd = dllRectd = GPA( "glRectd" );
+ qglRectdv = dllRectdv = GPA( "glRectdv" );
+ qglRectf = dllRectf = GPA( "glRectf" );
+ qglRectfv = dllRectfv = GPA( "glRectfv" );
+ qglRecti = dllRecti = GPA( "glRecti" );
+ qglRectiv = dllRectiv = GPA( "glRectiv" );
+ qglRects = dllRects = GPA( "glRects" );
+ qglRectsv = dllRectsv = GPA( "glRectsv" );
+ qglRenderMode = dllRenderMode = GPA( "glRenderMode" );
+ qglRotated = dllRotated = GPA( "glRotated" );
+ qglRotatef = dllRotatef = GPA( "glRotatef" );
+ qglScaled = dllScaled = GPA( "glScaled" );
+ qglScalef = dllScalef = GPA( "glScalef" );
+ qglScissor = dllScissor = GPA( "glScissor" );
+ qglSelectBuffer = dllSelectBuffer = GPA( "glSelectBuffer" );
+ qglShadeModel = dllShadeModel = GPA( "glShadeModel" );
+ qglStencilFunc = dllStencilFunc = GPA( "glStencilFunc" );
+ qglStencilMask = dllStencilMask = GPA( "glStencilMask" );
+ qglStencilOp = dllStencilOp = GPA( "glStencilOp" );
+ qglTexCoord1d = dllTexCoord1d = GPA( "glTexCoord1d" );
+ qglTexCoord1dv = dllTexCoord1dv = GPA( "glTexCoord1dv" );
+ qglTexCoord1f = dllTexCoord1f = GPA( "glTexCoord1f" );
+ qglTexCoord1fv = dllTexCoord1fv = GPA( "glTexCoord1fv" );
+ qglTexCoord1i = dllTexCoord1i = GPA( "glTexCoord1i" );
+ qglTexCoord1iv = dllTexCoord1iv = GPA( "glTexCoord1iv" );
+ qglTexCoord1s = dllTexCoord1s = GPA( "glTexCoord1s" );
+ qglTexCoord1sv = dllTexCoord1sv = GPA( "glTexCoord1sv" );
+ qglTexCoord2d = dllTexCoord2d = GPA( "glTexCoord2d" );
+ qglTexCoord2dv = dllTexCoord2dv = GPA( "glTexCoord2dv" );
+ qglTexCoord2f = dllTexCoord2f = GPA( "glTexCoord2f" );
+ qglTexCoord2fv = dllTexCoord2fv = GPA( "glTexCoord2fv" );
+ qglTexCoord2i = dllTexCoord2i = GPA( "glTexCoord2i" );
+ qglTexCoord2iv = dllTexCoord2iv = GPA( "glTexCoord2iv" );
+ qglTexCoord2s = dllTexCoord2s = GPA( "glTexCoord2s" );
+ qglTexCoord2sv = dllTexCoord2sv = GPA( "glTexCoord2sv" );
+ qglTexCoord3d = dllTexCoord3d = GPA( "glTexCoord3d" );
+ qglTexCoord3dv = dllTexCoord3dv = GPA( "glTexCoord3dv" );
+ qglTexCoord3f = dllTexCoord3f = GPA( "glTexCoord3f" );
+ qglTexCoord3fv = dllTexCoord3fv = GPA( "glTexCoord3fv" );
+ qglTexCoord3i = dllTexCoord3i = GPA( "glTexCoord3i" );
+ qglTexCoord3iv = dllTexCoord3iv = GPA( "glTexCoord3iv" );
+ qglTexCoord3s = dllTexCoord3s = GPA( "glTexCoord3s" );
+ qglTexCoord3sv = dllTexCoord3sv = GPA( "glTexCoord3sv" );
+ qglTexCoord4d = dllTexCoord4d = GPA( "glTexCoord4d" );
+ qglTexCoord4dv = dllTexCoord4dv = GPA( "glTexCoord4dv" );
+ qglTexCoord4f = dllTexCoord4f = GPA( "glTexCoord4f" );
+ qglTexCoord4fv = dllTexCoord4fv = GPA( "glTexCoord4fv" );
+ qglTexCoord4i = dllTexCoord4i = GPA( "glTexCoord4i" );
+ qglTexCoord4iv = dllTexCoord4iv = GPA( "glTexCoord4iv" );
+ qglTexCoord4s = dllTexCoord4s = GPA( "glTexCoord4s" );
+ qglTexCoord4sv = dllTexCoord4sv = GPA( "glTexCoord4sv" );
+ qglTexCoordPointer = dllTexCoordPointer = GPA( "glTexCoordPointer" );
+ qglTexEnvf = dllTexEnvf = GPA( "glTexEnvf" );
+ qglTexEnvfv = dllTexEnvfv = GPA( "glTexEnvfv" );
+ qglTexEnvi = dllTexEnvi = GPA( "glTexEnvi" );
+ qglTexEnviv = dllTexEnviv = GPA( "glTexEnviv" );
+ qglTexGend = dllTexGend = GPA( "glTexGend" );
+ qglTexGendv = dllTexGendv = GPA( "glTexGendv" );
+ qglTexGenf = dllTexGenf = GPA( "glTexGenf" );
+ qglTexGenfv = dllTexGenfv = GPA( "glTexGenfv" );
+ qglTexGeni = dllTexGeni = GPA( "glTexGeni" );
+ qglTexGeniv = dllTexGeniv = GPA( "glTexGeniv" );
+ qglTexImage1D = dllTexImage1D = GPA( "glTexImage1D" );
+ qglTexImage2D = dllTexImage2D = GPA( "glTexImage2D" );
+ qglTexParameterf = dllTexParameterf = GPA( "glTexParameterf" );
+ qglTexParameterfv = dllTexParameterfv = GPA( "glTexParameterfv" );
+ qglTexParameteri = dllTexParameteri = GPA( "glTexParameteri" );
+ qglTexParameteriv = dllTexParameteriv = GPA( "glTexParameteriv" );
+ qglTexSubImage1D = dllTexSubImage1D = GPA( "glTexSubImage1D" );
+ qglTexSubImage2D = dllTexSubImage2D = GPA( "glTexSubImage2D" );
+ qglTranslated = dllTranslated = GPA( "glTranslated" );
+ qglTranslatef = dllTranslatef = GPA( "glTranslatef" );
+ qglVertex2d = dllVertex2d = GPA( "glVertex2d" );
+ qglVertex2dv = dllVertex2dv = GPA( "glVertex2dv" );
+ qglVertex2f = dllVertex2f = GPA( "glVertex2f" );
+ qglVertex2fv = dllVertex2fv = GPA( "glVertex2fv" );
+ qglVertex2i = dllVertex2i = GPA( "glVertex2i" );
+ qglVertex2iv = dllVertex2iv = GPA( "glVertex2iv" );
+ qglVertex2s = dllVertex2s = GPA( "glVertex2s" );
+ qglVertex2sv = dllVertex2sv = GPA( "glVertex2sv" );
+ qglVertex3d = dllVertex3d = GPA( "glVertex3d" );
+ qglVertex3dv = dllVertex3dv = GPA( "glVertex3dv" );
+ qglVertex3f = dllVertex3f = GPA( "glVertex3f" );
+ qglVertex3fv = dllVertex3fv = GPA( "glVertex3fv" );
+ qglVertex3i = dllVertex3i = GPA( "glVertex3i" );
+ qglVertex3iv = dllVertex3iv = GPA( "glVertex3iv" );
+ qglVertex3s = dllVertex3s = GPA( "glVertex3s" );
+ qglVertex3sv = dllVertex3sv = GPA( "glVertex3sv" );
+ qglVertex4d = dllVertex4d = GPA( "glVertex4d" );
+ qglVertex4dv = dllVertex4dv = GPA( "glVertex4dv" );
+ qglVertex4f = dllVertex4f = GPA( "glVertex4f" );
+ qglVertex4fv = dllVertex4fv = GPA( "glVertex4fv" );
+ qglVertex4i = dllVertex4i = GPA( "glVertex4i" );
+ qglVertex4iv = dllVertex4iv = GPA( "glVertex4iv" );
+ qglVertex4s = dllVertex4s = GPA( "glVertex4s" );
+ qglVertex4sv = dllVertex4sv = GPA( "glVertex4sv" );
+ qglVertexPointer = dllVertexPointer = GPA( "glVertexPointer" );
+ qglViewport = dllViewport = GPA( "glViewport" );
+
+// bk001129 - from cvs1.17 (mkv)
+#if defined(__FX__)
+ qfxMesaCreateContext = GPA("fxMesaCreateContext");
+ qfxMesaCreateBestContext = GPA("fxMesaCreateBestContext");
+ qfxMesaDestroyContext = GPA("fxMesaDestroyContext");
+ qfxMesaMakeCurrent = GPA("fxMesaMakeCurrent");
+ qfxMesaGetCurrentContext = GPA("fxMesaGetCurrentContext");
+ qfxMesaSwapBuffers = GPA("fxMesaSwapBuffers");
+#endif
+
+ qglXChooseVisual = GPA("glXChooseVisual");
+ qglXCreateContext = GPA("glXCreateContext");
+ qglXDestroyContext = GPA("glXDestroyContext");
+ qglXMakeCurrent = GPA("glXMakeCurrent");
+ qglXCopyContext = GPA("glXCopyContext");
+ qglXSwapBuffers = GPA("glXSwapBuffers");
+
+ qglLockArraysEXT = 0;
+ qglUnlockArraysEXT = 0;
+ qglPointParameterfEXT = 0;
+ qglPointParameterfvEXT = 0;
+ qglColorTableEXT = 0;
+ qgl3DfxSetPaletteEXT = 0;
+ qglSelectTextureSGIS = 0;
+ qglMTexCoord2fSGIS = 0;
+ qglActiveTextureARB = 0;
+ qglClientActiveTextureARB = 0;
+ qglMultiTexCoord2fARB = 0;
+
+ return qtrue;
+}
+
+void QGL_EnableLogging( qboolean enable ) {
+ // bk001205 - fixed for new countdown
+ static qboolean isEnabled = qfalse; // init
+
+ // return if we're already active
+ if ( isEnabled && enable ) {
+ // decrement log counter and stop if it has reached 0
+ ri.Cvar_Set( "r_logFile", va("%d", r_logFile->integer - 1 ) );
+ if ( r_logFile->integer ) {
+ return;
+ }
+ enable = qfalse;
+ }
+
+ // return if we're already disabled
+ if ( !enable && !isEnabled )
+ return;
+
+ isEnabled = enable;
+
+ // bk001205 - old code starts here
+ if ( enable ) {
+ if ( !glw_state.log_fp ) {
+ struct tm *newtime;
+ time_t aclock;
+ char buffer[1024];
+ cvar_t *basedir;
+
+ time( &aclock );
+ newtime = localtime( &aclock );
+
+ asctime( newtime );
+
+ basedir = ri.Cvar_Get( "fs_basepath", "", 0 ); // FIXME: userdir?
+ assert(basedir);
+ Com_sprintf( buffer, sizeof(buffer), "%s/gl.log", basedir->string );
+ glw_state.log_fp = fopen( buffer, "wt" );
+ assert(glw_state.log_fp);
+ ri.Printf(PRINT_ALL, "QGL_EnableLogging(%d): writing %s\n", r_logFile->integer, buffer );
+
+ fprintf( glw_state.log_fp, "%s\n", asctime( newtime ) );
+ }
+
+ qglAccum = logAccum;
+ qglAlphaFunc = logAlphaFunc;
+ qglAreTexturesResident = logAreTexturesResident;
+ qglArrayElement = logArrayElement;
+ qglBegin = logBegin;
+ qglBindTexture = logBindTexture;
+ qglBitmap = logBitmap;
+ qglBlendFunc = logBlendFunc;
+ qglCallList = logCallList;
+ qglCallLists = logCallLists;
+ qglClear = logClear;
+ qglClearAccum = logClearAccum;
+ qglClearColor = logClearColor;
+ qglClearDepth = logClearDepth;
+ qglClearIndex = logClearIndex;
+ qglClearStencil = logClearStencil;
+ qglClipPlane = logClipPlane;
+ qglColor3b = logColor3b;
+ qglColor3bv = logColor3bv;
+ qglColor3d = logColor3d;
+ qglColor3dv = logColor3dv;
+ qglColor3f = logColor3f;
+ qglColor3fv = logColor3fv;
+ qglColor3i = logColor3i;
+ qglColor3iv = logColor3iv;
+ qglColor3s = logColor3s;
+ qglColor3sv = logColor3sv;
+ qglColor3ub = logColor3ub;
+ qglColor3ubv = logColor3ubv;
+ qglColor3ui = logColor3ui;
+ qglColor3uiv = logColor3uiv;
+ qglColor3us = logColor3us;
+ qglColor3usv = logColor3usv;
+ qglColor4b = logColor4b;
+ qglColor4bv = logColor4bv;
+ qglColor4d = logColor4d;
+ qglColor4dv = logColor4dv;
+ qglColor4f = logColor4f;
+ qglColor4fv = logColor4fv;
+ qglColor4i = logColor4i;
+ qglColor4iv = logColor4iv;
+ qglColor4s = logColor4s;
+ qglColor4sv = logColor4sv;
+ qglColor4ub = logColor4ub;
+ qglColor4ubv = logColor4ubv;
+ qglColor4ui = logColor4ui;
+ qglColor4uiv = logColor4uiv;
+ qglColor4us = logColor4us;
+ qglColor4usv = logColor4usv;
+ qglColorMask = logColorMask;
+ qglColorMaterial = logColorMaterial;
+ qglColorPointer = logColorPointer;
+ qglCopyPixels = logCopyPixels;
+ qglCopyTexImage1D = logCopyTexImage1D;
+ qglCopyTexImage2D = logCopyTexImage2D;
+ qglCopyTexSubImage1D = logCopyTexSubImage1D;
+ qglCopyTexSubImage2D = logCopyTexSubImage2D;
+ qglCullFace = logCullFace;
+ qglDeleteLists = logDeleteLists ;
+ qglDeleteTextures = logDeleteTextures ;
+ qglDepthFunc = logDepthFunc ;
+ qglDepthMask = logDepthMask ;
+ qglDepthRange = logDepthRange ;
+ qglDisable = logDisable ;
+ qglDisableClientState = logDisableClientState ;
+ qglDrawArrays = logDrawArrays ;
+ qglDrawBuffer = logDrawBuffer ;
+ qglDrawElements = logDrawElements ;
+ qglDrawPixels = logDrawPixels ;
+ qglEdgeFlag = logEdgeFlag ;
+ qglEdgeFlagPointer = logEdgeFlagPointer ;
+ qglEdgeFlagv = logEdgeFlagv ;
+ qglEnable = logEnable ;
+ qglEnableClientState = logEnableClientState ;
+ qglEnd = logEnd ;
+ qglEndList = logEndList ;
+ qglEvalCoord1d = logEvalCoord1d ;
+ qglEvalCoord1dv = logEvalCoord1dv ;
+ qglEvalCoord1f = logEvalCoord1f ;
+ qglEvalCoord1fv = logEvalCoord1fv ;
+ qglEvalCoord2d = logEvalCoord2d ;
+ qglEvalCoord2dv = logEvalCoord2dv ;
+ qglEvalCoord2f = logEvalCoord2f ;
+ qglEvalCoord2fv = logEvalCoord2fv ;
+ qglEvalMesh1 = logEvalMesh1 ;
+ qglEvalMesh2 = logEvalMesh2 ;
+ qglEvalPoint1 = logEvalPoint1 ;
+ qglEvalPoint2 = logEvalPoint2 ;
+ qglFeedbackBuffer = logFeedbackBuffer ;
+ qglFinish = logFinish ;
+ qglFlush = logFlush ;
+ qglFogf = logFogf ;
+ qglFogfv = logFogfv ;
+ qglFogi = logFogi ;
+ qglFogiv = logFogiv ;
+ qglFrontFace = logFrontFace ;
+ qglFrustum = logFrustum ;
+ qglGenLists = logGenLists ;
+ qglGenTextures = logGenTextures ;
+ qglGetBooleanv = logGetBooleanv ;
+ qglGetClipPlane = logGetClipPlane ;
+ qglGetDoublev = logGetDoublev ;
+ qglGetError = logGetError ;
+ qglGetFloatv = logGetFloatv ;
+ qglGetIntegerv = logGetIntegerv ;
+ qglGetLightfv = logGetLightfv ;
+ qglGetLightiv = logGetLightiv ;
+ qglGetMapdv = logGetMapdv ;
+ qglGetMapfv = logGetMapfv ;
+ qglGetMapiv = logGetMapiv ;
+ qglGetMaterialfv = logGetMaterialfv ;
+ qglGetMaterialiv = logGetMaterialiv ;
+ qglGetPixelMapfv = logGetPixelMapfv ;
+ qglGetPixelMapuiv = logGetPixelMapuiv ;
+ qglGetPixelMapusv = logGetPixelMapusv ;
+ qglGetPointerv = logGetPointerv ;
+ qglGetPolygonStipple = logGetPolygonStipple ;
+ qglGetString = logGetString ;
+ qglGetTexEnvfv = logGetTexEnvfv ;
+ qglGetTexEnviv = logGetTexEnviv ;
+ qglGetTexGendv = logGetTexGendv ;
+ qglGetTexGenfv = logGetTexGenfv ;
+ qglGetTexGeniv = logGetTexGeniv ;
+ qglGetTexImage = logGetTexImage ;
+ qglGetTexLevelParameterfv = logGetTexLevelParameterfv ;
+ qglGetTexLevelParameteriv = logGetTexLevelParameteriv ;
+ qglGetTexParameterfv = logGetTexParameterfv ;
+ qglGetTexParameteriv = logGetTexParameteriv ;
+ qglHint = logHint ;
+ qglIndexMask = logIndexMask ;
+ qglIndexPointer = logIndexPointer ;
+ qglIndexd = logIndexd ;
+ qglIndexdv = logIndexdv ;
+ qglIndexf = logIndexf ;
+ qglIndexfv = logIndexfv ;
+ qglIndexi = logIndexi ;
+ qglIndexiv = logIndexiv ;
+ qglIndexs = logIndexs ;
+ qglIndexsv = logIndexsv ;
+ qglIndexub = logIndexub ;
+ qglIndexubv = logIndexubv ;
+ qglInitNames = logInitNames ;
+ qglInterleavedArrays = logInterleavedArrays ;
+ qglIsEnabled = logIsEnabled ;
+ qglIsList = logIsList ;
+ qglIsTexture = logIsTexture ;
+ qglLightModelf = logLightModelf ;
+ qglLightModelfv = logLightModelfv ;
+ qglLightModeli = logLightModeli ;
+ qglLightModeliv = logLightModeliv ;
+ qglLightf = logLightf ;
+ qglLightfv = logLightfv ;
+ qglLighti = logLighti ;
+ qglLightiv = logLightiv ;
+ qglLineStipple = logLineStipple ;
+ qglLineWidth = logLineWidth ;
+ qglListBase = logListBase ;
+ qglLoadIdentity = logLoadIdentity ;
+ qglLoadMatrixd = logLoadMatrixd ;
+ qglLoadMatrixf = logLoadMatrixf ;
+ qglLoadName = logLoadName ;
+ qglLogicOp = logLogicOp ;
+ qglMap1d = logMap1d ;
+ qglMap1f = logMap1f ;
+ qglMap2d = logMap2d ;
+ qglMap2f = logMap2f ;
+ qglMapGrid1d = logMapGrid1d ;
+ qglMapGrid1f = logMapGrid1f ;
+ qglMapGrid2d = logMapGrid2d ;
+ qglMapGrid2f = logMapGrid2f ;
+ qglMaterialf = logMaterialf ;
+ qglMaterialfv = logMaterialfv ;
+ qglMateriali = logMateriali ;
+ qglMaterialiv = logMaterialiv ;
+ qglMatrixMode = logMatrixMode ;
+ qglMultMatrixd = logMultMatrixd ;
+ qglMultMatrixf = logMultMatrixf ;
+ qglNewList = logNewList ;
+ qglNormal3b = logNormal3b ;
+ qglNormal3bv = logNormal3bv ;
+ qglNormal3d = logNormal3d ;
+ qglNormal3dv = logNormal3dv ;
+ qglNormal3f = logNormal3f ;
+ qglNormal3fv = logNormal3fv ;
+ qglNormal3i = logNormal3i ;
+ qglNormal3iv = logNormal3iv ;
+ qglNormal3s = logNormal3s ;
+ qglNormal3sv = logNormal3sv ;
+ qglNormalPointer = logNormalPointer ;
+ qglOrtho = logOrtho ;
+ qglPassThrough = logPassThrough ;
+ qglPixelMapfv = logPixelMapfv ;
+ qglPixelMapuiv = logPixelMapuiv ;
+ qglPixelMapusv = logPixelMapusv ;
+ qglPixelStoref = logPixelStoref ;
+ qglPixelStorei = logPixelStorei ;
+ qglPixelTransferf = logPixelTransferf ;
+ qglPixelTransferi = logPixelTransferi ;
+ qglPixelZoom = logPixelZoom ;
+ qglPointSize = logPointSize ;
+ qglPolygonMode = logPolygonMode ;
+ qglPolygonOffset = logPolygonOffset ;
+ qglPolygonStipple = logPolygonStipple ;
+ qglPopAttrib = logPopAttrib ;
+ qglPopClientAttrib = logPopClientAttrib ;
+ qglPopMatrix = logPopMatrix ;
+ qglPopName = logPopName ;
+ qglPrioritizeTextures = logPrioritizeTextures ;
+ qglPushAttrib = logPushAttrib ;
+ qglPushClientAttrib = logPushClientAttrib ;
+ qglPushMatrix = logPushMatrix ;
+ qglPushName = logPushName ;
+ qglRasterPos2d = logRasterPos2d ;
+ qglRasterPos2dv = logRasterPos2dv ;
+ qglRasterPos2f = logRasterPos2f ;
+ qglRasterPos2fv = logRasterPos2fv ;
+ qglRasterPos2i = logRasterPos2i ;
+ qglRasterPos2iv = logRasterPos2iv ;
+ qglRasterPos2s = logRasterPos2s ;
+ qglRasterPos2sv = logRasterPos2sv ;
+ qglRasterPos3d = logRasterPos3d ;
+ qglRasterPos3dv = logRasterPos3dv ;
+ qglRasterPos3f = logRasterPos3f ;
+ qglRasterPos3fv = logRasterPos3fv ;
+ qglRasterPos3i = logRasterPos3i ;
+ qglRasterPos3iv = logRasterPos3iv ;
+ qglRasterPos3s = logRasterPos3s ;
+ qglRasterPos3sv = logRasterPos3sv ;
+ qglRasterPos4d = logRasterPos4d ;
+ qglRasterPos4dv = logRasterPos4dv ;
+ qglRasterPos4f = logRasterPos4f ;
+ qglRasterPos4fv = logRasterPos4fv ;
+ qglRasterPos4i = logRasterPos4i ;
+ qglRasterPos4iv = logRasterPos4iv ;
+ qglRasterPos4s = logRasterPos4s ;
+ qglRasterPos4sv = logRasterPos4sv ;
+ qglReadBuffer = logReadBuffer ;
+ qglReadPixels = logReadPixels ;
+ qglRectd = logRectd ;
+ qglRectdv = logRectdv ;
+ qglRectf = logRectf ;
+ qglRectfv = logRectfv ;
+ qglRecti = logRecti ;
+ qglRectiv = logRectiv ;
+ qglRects = logRects ;
+ qglRectsv = logRectsv ;
+ qglRenderMode = logRenderMode ;
+ qglRotated = logRotated ;
+ qglRotatef = logRotatef ;
+ qglScaled = logScaled ;
+ qglScalef = logScalef ;
+ qglScissor = logScissor ;
+ qglSelectBuffer = logSelectBuffer ;
+ qglShadeModel = logShadeModel ;
+ qglStencilFunc = logStencilFunc ;
+ qglStencilMask = logStencilMask ;
+ qglStencilOp = logStencilOp ;
+ qglTexCoord1d = logTexCoord1d ;
+ qglTexCoord1dv = logTexCoord1dv ;
+ qglTexCoord1f = logTexCoord1f ;
+ qglTexCoord1fv = logTexCoord1fv ;
+ qglTexCoord1i = logTexCoord1i ;
+ qglTexCoord1iv = logTexCoord1iv ;
+ qglTexCoord1s = logTexCoord1s ;
+ qglTexCoord1sv = logTexCoord1sv ;
+ qglTexCoord2d = logTexCoord2d ;
+ qglTexCoord2dv = logTexCoord2dv ;
+ qglTexCoord2f = logTexCoord2f ;
+ qglTexCoord2fv = logTexCoord2fv ;
+ qglTexCoord2i = logTexCoord2i ;
+ qglTexCoord2iv = logTexCoord2iv ;
+ qglTexCoord2s = logTexCoord2s ;
+ qglTexCoord2sv = logTexCoord2sv ;
+ qglTexCoord3d = logTexCoord3d ;
+ qglTexCoord3dv = logTexCoord3dv ;
+ qglTexCoord3f = logTexCoord3f ;
+ qglTexCoord3fv = logTexCoord3fv ;
+ qglTexCoord3i = logTexCoord3i ;
+ qglTexCoord3iv = logTexCoord3iv ;
+ qglTexCoord3s = logTexCoord3s ;
+ qglTexCoord3sv = logTexCoord3sv ;
+ qglTexCoord4d = logTexCoord4d ;
+ qglTexCoord4dv = logTexCoord4dv ;
+ qglTexCoord4f = logTexCoord4f ;
+ qglTexCoord4fv = logTexCoord4fv ;
+ qglTexCoord4i = logTexCoord4i ;
+ qglTexCoord4iv = logTexCoord4iv ;
+ qglTexCoord4s = logTexCoord4s ;
+ qglTexCoord4sv = logTexCoord4sv ;
+ qglTexCoordPointer = logTexCoordPointer ;
+ qglTexEnvf = logTexEnvf ;
+ qglTexEnvfv = logTexEnvfv ;
+ qglTexEnvi = logTexEnvi ;
+ qglTexEnviv = logTexEnviv ;
+ qglTexGend = logTexGend ;
+ qglTexGendv = logTexGendv ;
+ qglTexGenf = logTexGenf ;
+ qglTexGenfv = logTexGenfv ;
+ qglTexGeni = logTexGeni ;
+ qglTexGeniv = logTexGeniv ;
+ qglTexImage1D = logTexImage1D ;
+ qglTexImage2D = logTexImage2D ;
+ qglTexParameterf = logTexParameterf ;
+ qglTexParameterfv = logTexParameterfv ;
+ qglTexParameteri = logTexParameteri ;
+ qglTexParameteriv = logTexParameteriv ;
+ qglTexSubImage1D = logTexSubImage1D ;
+ qglTexSubImage2D = logTexSubImage2D ;
+ qglTranslated = logTranslated ;
+ qglTranslatef = logTranslatef ;
+ qglVertex2d = logVertex2d ;
+ qglVertex2dv = logVertex2dv ;
+ qglVertex2f = logVertex2f ;
+ qglVertex2fv = logVertex2fv ;
+ qglVertex2i = logVertex2i ;
+ qglVertex2iv = logVertex2iv ;
+ qglVertex2s = logVertex2s ;
+ qglVertex2sv = logVertex2sv ;
+ qglVertex3d = logVertex3d ;
+ qglVertex3dv = logVertex3dv ;
+ qglVertex3f = logVertex3f ;
+ qglVertex3fv = logVertex3fv ;
+ qglVertex3i = logVertex3i ;
+ qglVertex3iv = logVertex3iv ;
+ qglVertex3s = logVertex3s ;
+ qglVertex3sv = logVertex3sv ;
+ qglVertex4d = logVertex4d ;
+ qglVertex4dv = logVertex4dv ;
+ qglVertex4f = logVertex4f ;
+ qglVertex4fv = logVertex4fv ;
+ qglVertex4i = logVertex4i ;
+ qglVertex4iv = logVertex4iv ;
+ qglVertex4s = logVertex4s ;
+ qglVertex4sv = logVertex4sv ;
+ qglVertexPointer = logVertexPointer ;
+ qglViewport = logViewport ;
+ }
+ else
+ {
+ qglAccum = dllAccum;
+ qglAlphaFunc = dllAlphaFunc;
+ qglAreTexturesResident = dllAreTexturesResident;
+ qglArrayElement = dllArrayElement;
+ qglBegin = dllBegin;
+ qglBindTexture = dllBindTexture;
+ qglBitmap = dllBitmap;
+ qglBlendFunc = dllBlendFunc;
+ qglCallList = dllCallList;
+ qglCallLists = dllCallLists;
+ qglClear = dllClear;
+ qglClearAccum = dllClearAccum;
+ qglClearColor = dllClearColor;
+ qglClearDepth = dllClearDepth;
+ qglClearIndex = dllClearIndex;
+ qglClearStencil = dllClearStencil;
+ qglClipPlane = dllClipPlane;
+ qglColor3b = dllColor3b;
+ qglColor3bv = dllColor3bv;
+ qglColor3d = dllColor3d;
+ qglColor3dv = dllColor3dv;
+ qglColor3f = dllColor3f;
+ qglColor3fv = dllColor3fv;
+ qglColor3i = dllColor3i;
+ qglColor3iv = dllColor3iv;
+ qglColor3s = dllColor3s;
+ qglColor3sv = dllColor3sv;
+ qglColor3ub = dllColor3ub;
+ qglColor3ubv = dllColor3ubv;
+ qglColor3ui = dllColor3ui;
+ qglColor3uiv = dllColor3uiv;
+ qglColor3us = dllColor3us;
+ qglColor3usv = dllColor3usv;
+ qglColor4b = dllColor4b;
+ qglColor4bv = dllColor4bv;
+ qglColor4d = dllColor4d;
+ qglColor4dv = dllColor4dv;
+ qglColor4f = dllColor4f;
+ qglColor4fv = dllColor4fv;
+ qglColor4i = dllColor4i;
+ qglColor4iv = dllColor4iv;
+ qglColor4s = dllColor4s;
+ qglColor4sv = dllColor4sv;
+ qglColor4ub = dllColor4ub;
+ qglColor4ubv = dllColor4ubv;
+ qglColor4ui = dllColor4ui;
+ qglColor4uiv = dllColor4uiv;
+ qglColor4us = dllColor4us;
+ qglColor4usv = dllColor4usv;
+ qglColorMask = dllColorMask;
+ qglColorMaterial = dllColorMaterial;
+ qglColorPointer = dllColorPointer;
+ qglCopyPixels = dllCopyPixels;
+ qglCopyTexImage1D = dllCopyTexImage1D;
+ qglCopyTexImage2D = dllCopyTexImage2D;
+ qglCopyTexSubImage1D = dllCopyTexSubImage1D;
+ qglCopyTexSubImage2D = dllCopyTexSubImage2D;
+ qglCullFace = dllCullFace;
+ qglDeleteLists = dllDeleteLists ;
+ qglDeleteTextures = dllDeleteTextures ;
+ qglDepthFunc = dllDepthFunc ;
+ qglDepthMask = dllDepthMask ;
+ qglDepthRange = dllDepthRange ;
+ qglDisable = dllDisable ;
+ qglDisableClientState = dllDisableClientState ;
+ qglDrawArrays = dllDrawArrays ;
+ qglDrawBuffer = dllDrawBuffer ;
+ qglDrawElements = dllDrawElements ;
+ qglDrawPixels = dllDrawPixels ;
+ qglEdgeFlag = dllEdgeFlag ;
+ qglEdgeFlagPointer = dllEdgeFlagPointer ;
+ qglEdgeFlagv = dllEdgeFlagv ;
+ qglEnable = dllEnable ;
+ qglEnableClientState = dllEnableClientState ;
+ qglEnd = dllEnd ;
+ qglEndList = dllEndList ;
+ qglEvalCoord1d = dllEvalCoord1d ;
+ qglEvalCoord1dv = dllEvalCoord1dv ;
+ qglEvalCoord1f = dllEvalCoord1f ;
+ qglEvalCoord1fv = dllEvalCoord1fv ;
+ qglEvalCoord2d = dllEvalCoord2d ;
+ qglEvalCoord2dv = dllEvalCoord2dv ;
+ qglEvalCoord2f = dllEvalCoord2f ;
+ qglEvalCoord2fv = dllEvalCoord2fv ;
+ qglEvalMesh1 = dllEvalMesh1 ;
+ qglEvalMesh2 = dllEvalMesh2 ;
+ qglEvalPoint1 = dllEvalPoint1 ;
+ qglEvalPoint2 = dllEvalPoint2 ;
+ qglFeedbackBuffer = dllFeedbackBuffer ;
+ qglFinish = dllFinish ;
+ qglFlush = dllFlush ;
+ qglFogf = dllFogf ;
+ qglFogfv = dllFogfv ;
+ qglFogi = dllFogi ;
+ qglFogiv = dllFogiv ;
+ qglFrontFace = dllFrontFace ;
+ qglFrustum = dllFrustum ;
+ qglGenLists = dllGenLists ;
+ qglGenTextures = dllGenTextures ;
+ qglGetBooleanv = dllGetBooleanv ;
+ qglGetClipPlane = dllGetClipPlane ;
+ qglGetDoublev = dllGetDoublev ;
+ qglGetError = dllGetError ;
+ qglGetFloatv = dllGetFloatv ;
+ qglGetIntegerv = dllGetIntegerv ;
+ qglGetLightfv = dllGetLightfv ;
+ qglGetLightiv = dllGetLightiv ;
+ qglGetMapdv = dllGetMapdv ;
+ qglGetMapfv = dllGetMapfv ;
+ qglGetMapiv = dllGetMapiv ;
+ qglGetMaterialfv = dllGetMaterialfv ;
+ qglGetMaterialiv = dllGetMaterialiv ;
+ qglGetPixelMapfv = dllGetPixelMapfv ;
+ qglGetPixelMapuiv = dllGetPixelMapuiv ;
+ qglGetPixelMapusv = dllGetPixelMapusv ;
+ qglGetPointerv = dllGetPointerv ;
+ qglGetPolygonStipple = dllGetPolygonStipple ;
+ qglGetString = dllGetString ;
+ qglGetTexEnvfv = dllGetTexEnvfv ;
+ qglGetTexEnviv = dllGetTexEnviv ;
+ qglGetTexGendv = dllGetTexGendv ;
+ qglGetTexGenfv = dllGetTexGenfv ;
+ qglGetTexGeniv = dllGetTexGeniv ;
+ qglGetTexImage = dllGetTexImage ;
+ qglGetTexLevelParameterfv = dllGetTexLevelParameterfv ;
+ qglGetTexLevelParameteriv = dllGetTexLevelParameteriv ;
+ qglGetTexParameterfv = dllGetTexParameterfv ;
+ qglGetTexParameteriv = dllGetTexParameteriv ;
+ qglHint = dllHint ;
+ qglIndexMask = dllIndexMask ;
+ qglIndexPointer = dllIndexPointer ;
+ qglIndexd = dllIndexd ;
+ qglIndexdv = dllIndexdv ;
+ qglIndexf = dllIndexf ;
+ qglIndexfv = dllIndexfv ;
+ qglIndexi = dllIndexi ;
+ qglIndexiv = dllIndexiv ;
+ qglIndexs = dllIndexs ;
+ qglIndexsv = dllIndexsv ;
+ qglIndexub = dllIndexub ;
+ qglIndexubv = dllIndexubv ;
+ qglInitNames = dllInitNames ;
+ qglInterleavedArrays = dllInterleavedArrays ;
+ qglIsEnabled = dllIsEnabled ;
+ qglIsList = dllIsList ;
+ qglIsTexture = dllIsTexture ;
+ qglLightModelf = dllLightModelf ;
+ qglLightModelfv = dllLightModelfv ;
+ qglLightModeli = dllLightModeli ;
+ qglLightModeliv = dllLightModeliv ;
+ qglLightf = dllLightf ;
+ qglLightfv = dllLightfv ;
+ qglLighti = dllLighti ;
+ qglLightiv = dllLightiv ;
+ qglLineStipple = dllLineStipple ;
+ qglLineWidth = dllLineWidth ;
+ qglListBase = dllListBase ;
+ qglLoadIdentity = dllLoadIdentity ;
+ qglLoadMatrixd = dllLoadMatrixd ;
+ qglLoadMatrixf = dllLoadMatrixf ;
+ qglLoadName = dllLoadName ;
+ qglLogicOp = dllLogicOp ;
+ qglMap1d = dllMap1d ;
+ qglMap1f = dllMap1f ;
+ qglMap2d = dllMap2d ;
+ qglMap2f = dllMap2f ;
+ qglMapGrid1d = dllMapGrid1d ;
+ qglMapGrid1f = dllMapGrid1f ;
+ qglMapGrid2d = dllMapGrid2d ;
+ qglMapGrid2f = dllMapGrid2f ;
+ qglMaterialf = dllMaterialf ;
+ qglMaterialfv = dllMaterialfv ;
+ qglMateriali = dllMateriali ;
+ qglMaterialiv = dllMaterialiv ;
+ qglMatrixMode = dllMatrixMode ;
+ qglMultMatrixd = dllMultMatrixd ;
+ qglMultMatrixf = dllMultMatrixf ;
+ qglNewList = dllNewList ;
+ qglNormal3b = dllNormal3b ;
+ qglNormal3bv = dllNormal3bv ;
+ qglNormal3d = dllNormal3d ;
+ qglNormal3dv = dllNormal3dv ;
+ qglNormal3f = dllNormal3f ;
+ qglNormal3fv = dllNormal3fv ;
+ qglNormal3i = dllNormal3i ;
+ qglNormal3iv = dllNormal3iv ;
+ qglNormal3s = dllNormal3s ;
+ qglNormal3sv = dllNormal3sv ;
+ qglNormalPointer = dllNormalPointer ;
+ qglOrtho = dllOrtho ;
+ qglPassThrough = dllPassThrough ;
+ qglPixelMapfv = dllPixelMapfv ;
+ qglPixelMapuiv = dllPixelMapuiv ;
+ qglPixelMapusv = dllPixelMapusv ;
+ qglPixelStoref = dllPixelStoref ;
+ qglPixelStorei = dllPixelStorei ;
+ qglPixelTransferf = dllPixelTransferf ;
+ qglPixelTransferi = dllPixelTransferi ;
+ qglPixelZoom = dllPixelZoom ;
+ qglPointSize = dllPointSize ;
+ qglPolygonMode = dllPolygonMode ;
+ qglPolygonOffset = dllPolygonOffset ;
+ qglPolygonStipple = dllPolygonStipple ;
+ qglPopAttrib = dllPopAttrib ;
+ qglPopClientAttrib = dllPopClientAttrib ;
+ qglPopMatrix = dllPopMatrix ;
+ qglPopName = dllPopName ;
+ qglPrioritizeTextures = dllPrioritizeTextures ;
+ qglPushAttrib = dllPushAttrib ;
+ qglPushClientAttrib = dllPushClientAttrib ;
+ qglPushMatrix = dllPushMatrix ;
+ qglPushName = dllPushName ;
+ qglRasterPos2d = dllRasterPos2d ;
+ qglRasterPos2dv = dllRasterPos2dv ;
+ qglRasterPos2f = dllRasterPos2f ;
+ qglRasterPos2fv = dllRasterPos2fv ;
+ qglRasterPos2i = dllRasterPos2i ;
+ qglRasterPos2iv = dllRasterPos2iv ;
+ qglRasterPos2s = dllRasterPos2s ;
+ qglRasterPos2sv = dllRasterPos2sv ;
+ qglRasterPos3d = dllRasterPos3d ;
+ qglRasterPos3dv = dllRasterPos3dv ;
+ qglRasterPos3f = dllRasterPos3f ;
+ qglRasterPos3fv = dllRasterPos3fv ;
+ qglRasterPos3i = dllRasterPos3i ;
+ qglRasterPos3iv = dllRasterPos3iv ;
+ qglRasterPos3s = dllRasterPos3s ;
+ qglRasterPos3sv = dllRasterPos3sv ;
+ qglRasterPos4d = dllRasterPos4d ;
+ qglRasterPos4dv = dllRasterPos4dv ;
+ qglRasterPos4f = dllRasterPos4f ;
+ qglRasterPos4fv = dllRasterPos4fv ;
+ qglRasterPos4i = dllRasterPos4i ;
+ qglRasterPos4iv = dllRasterPos4iv ;
+ qglRasterPos4s = dllRasterPos4s ;
+ qglRasterPos4sv = dllRasterPos4sv ;
+ qglReadBuffer = dllReadBuffer ;
+ qglReadPixels = dllReadPixels ;
+ qglRectd = dllRectd ;
+ qglRectdv = dllRectdv ;
+ qglRectf = dllRectf ;
+ qglRectfv = dllRectfv ;
+ qglRecti = dllRecti ;
+ qglRectiv = dllRectiv ;
+ qglRects = dllRects ;
+ qglRectsv = dllRectsv ;
+ qglRenderMode = dllRenderMode ;
+ qglRotated = dllRotated ;
+ qglRotatef = dllRotatef ;
+ qglScaled = dllScaled ;
+ qglScalef = dllScalef ;
+ qglScissor = dllScissor ;
+ qglSelectBuffer = dllSelectBuffer ;
+ qglShadeModel = dllShadeModel ;
+ qglStencilFunc = dllStencilFunc ;
+ qglStencilMask = dllStencilMask ;
+ qglStencilOp = dllStencilOp ;
+ qglTexCoord1d = dllTexCoord1d ;
+ qglTexCoord1dv = dllTexCoord1dv ;
+ qglTexCoord1f = dllTexCoord1f ;
+ qglTexCoord1fv = dllTexCoord1fv ;
+ qglTexCoord1i = dllTexCoord1i ;
+ qglTexCoord1iv = dllTexCoord1iv ;
+ qglTexCoord1s = dllTexCoord1s ;
+ qglTexCoord1sv = dllTexCoord1sv ;
+ qglTexCoord2d = dllTexCoord2d ;
+ qglTexCoord2dv = dllTexCoord2dv ;
+ qglTexCoord2f = dllTexCoord2f ;
+ qglTexCoord2fv = dllTexCoord2fv ;
+ qglTexCoord2i = dllTexCoord2i ;
+ qglTexCoord2iv = dllTexCoord2iv ;
+ qglTexCoord2s = dllTexCoord2s ;
+ qglTexCoord2sv = dllTexCoord2sv ;
+ qglTexCoord3d = dllTexCoord3d ;
+ qglTexCoord3dv = dllTexCoord3dv ;
+ qglTexCoord3f = dllTexCoord3f ;
+ qglTexCoord3fv = dllTexCoord3fv ;
+ qglTexCoord3i = dllTexCoord3i ;
+ qglTexCoord3iv = dllTexCoord3iv ;
+ qglTexCoord3s = dllTexCoord3s ;
+ qglTexCoord3sv = dllTexCoord3sv ;
+ qglTexCoord4d = dllTexCoord4d ;
+ qglTexCoord4dv = dllTexCoord4dv ;
+ qglTexCoord4f = dllTexCoord4f ;
+ qglTexCoord4fv = dllTexCoord4fv ;
+ qglTexCoord4i = dllTexCoord4i ;
+ qglTexCoord4iv = dllTexCoord4iv ;
+ qglTexCoord4s = dllTexCoord4s ;
+ qglTexCoord4sv = dllTexCoord4sv ;
+ qglTexCoordPointer = dllTexCoordPointer ;
+ qglTexEnvf = dllTexEnvf ;
+ qglTexEnvfv = dllTexEnvfv ;
+ qglTexEnvi = dllTexEnvi ;
+ qglTexEnviv = dllTexEnviv ;
+ qglTexGend = dllTexGend ;
+ qglTexGendv = dllTexGendv ;
+ qglTexGenf = dllTexGenf ;
+ qglTexGenfv = dllTexGenfv ;
+ qglTexGeni = dllTexGeni ;
+ qglTexGeniv = dllTexGeniv ;
+ qglTexImage1D = dllTexImage1D ;
+ qglTexImage2D = dllTexImage2D ;
+ qglTexParameterf = dllTexParameterf ;
+ qglTexParameterfv = dllTexParameterfv ;
+ qglTexParameteri = dllTexParameteri ;
+ qglTexParameteriv = dllTexParameteriv ;
+ qglTexSubImage1D = dllTexSubImage1D ;
+ qglTexSubImage2D = dllTexSubImage2D ;
+ qglTranslated = dllTranslated ;
+ qglTranslatef = dllTranslatef ;
+ qglVertex2d = dllVertex2d ;
+ qglVertex2dv = dllVertex2dv ;
+ qglVertex2f = dllVertex2f ;
+ qglVertex2fv = dllVertex2fv ;
+ qglVertex2i = dllVertex2i ;
+ qglVertex2iv = dllVertex2iv ;
+ qglVertex2s = dllVertex2s ;
+ qglVertex2sv = dllVertex2sv ;
+ qglVertex3d = dllVertex3d ;
+ qglVertex3dv = dllVertex3dv ;
+ qglVertex3f = dllVertex3f ;
+ qglVertex3fv = dllVertex3fv ;
+ qglVertex3i = dllVertex3i ;
+ qglVertex3iv = dllVertex3iv ;
+ qglVertex3s = dllVertex3s ;
+ qglVertex3sv = dllVertex3sv ;
+ qglVertex4d = dllVertex4d ;
+ qglVertex4dv = dllVertex4dv ;
+ qglVertex4f = dllVertex4f ;
+ qglVertex4fv = dllVertex4fv ;
+ qglVertex4i = dllVertex4i ;
+ qglVertex4iv = dllVertex4iv ;
+ qglVertex4s = dllVertex4s ;
+ qglVertex4sv = dllVertex4sv ;
+ qglVertexPointer = dllVertexPointer ;
+ qglViewport = dllViewport ;
+ }
+}
+
+
+void GLimp_LogNewFrame( void )
+{
+ fprintf( glw_state.log_fp, "*** R_BeginFrame ***\n" );
+}
+
+
diff --git a/code/unix/linux_signals.c b/code/unix/linux_signals.c
new file mode 100755
index 0000000..279fbad
--- /dev/null
+++ b/code/unix/linux_signals.c
@@ -0,0 +1,61 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include <signal.h>
+
+#include "../game/q_shared.h"
+#include "../qcommon/qcommon.h"
+#ifndef DEDICATED
+#include "../renderer/tr_local.h"
+#endif
+
+static qboolean signalcaught = qfalse;;
+
+void Sys_Exit(int); // bk010104 - abstraction
+
+static void signal_handler(int sig) // bk010104 - replace this... (NOTE TTimo huh?)
+{
+ if (signalcaught)
+ {
+ printf("DOUBLE SIGNAL FAULT: Received signal %d, exiting...\n", sig);
+ Sys_Exit(1); // bk010104 - abstraction
+ }
+
+ signalcaught = qtrue;
+ printf("Received signal %d, exiting...\n", sig);
+#ifndef DEDICATED
+ GLimp_Shutdown(); // bk010104 - shouldn't this be CL_Shutdown
+#endif
+ Sys_Exit(0); // bk010104 - abstraction NOTE TTimo send a 0 to avoid DOUBLE SIGNAL FAULT
+}
+
+void InitSig(void)
+{
+ signal(SIGHUP, signal_handler);
+ signal(SIGQUIT, signal_handler);
+ signal(SIGILL, signal_handler);
+ signal(SIGTRAP, signal_handler);
+ signal(SIGIOT, signal_handler);
+ signal(SIGBUS, signal_handler);
+ signal(SIGFPE, signal_handler);
+ signal(SIGSEGV, signal_handler);
+ signal(SIGTERM, signal_handler);
+}
diff --git a/code/unix/linux_snd.c b/code/unix/linux_snd.c
new file mode 100755
index 0000000..8c3b6b8
--- /dev/null
+++ b/code/unix/linux_snd.c
@@ -0,0 +1,293 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include <unistd.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <sys/types.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <sys/shm.h>
+#include <sys/wait.h>
+#ifdef __linux__ // rb0101023 - guard this
+#include <linux/soundcard.h>
+#endif
+#ifdef __FreeBSD__ // rb0101023 - added
+#include <sys/soundcard.h>
+#endif
+#include <stdio.h>
+
+#include "../game/q_shared.h"
+#include "../client/snd_local.h"
+
+int audio_fd;
+int snd_inited=0;
+
+cvar_t *sndbits;
+cvar_t *sndspeed;
+cvar_t *sndchannels;
+
+cvar_t *snddevice;
+
+/* Some devices may work only with 48000 */
+static int tryrates[] = { 22050, 11025, 44100, 48000, 8000 };
+
+static qboolean use_custom_memset = qfalse;
+// https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=371
+void Snd_Memset (void* dest, const int val, const size_t count)
+{
+ int *pDest;
+ int i, iterate;
+
+ if (!use_custom_memset)
+ {
+ Com_Memset(dest,val,count);
+ return;
+ }
+ iterate = count / sizeof(int);
+ pDest = (int*)dest;
+ for(i=0; i<iterate; i++)
+ {
+ pDest[i] = val;
+ }
+}
+
+qboolean SNDDMA_Init(void)
+{
+ int rc;
+ int fmt;
+ int tmp;
+ int i;
+ // char *s; // bk001204 - unused
+ struct audio_buf_info info;
+ int caps;
+ extern uid_t saved_euid;
+
+ if (snd_inited)
+ return 1;
+
+ if (!snddevice) {
+ sndbits = Cvar_Get("sndbits", "16", CVAR_ARCHIVE);
+ sndspeed = Cvar_Get("sndspeed", "0", CVAR_ARCHIVE);
+ sndchannels = Cvar_Get("sndchannels", "2", CVAR_ARCHIVE);
+ snddevice = Cvar_Get("snddevice", "/dev/dsp", CVAR_ARCHIVE);
+ }
+
+ // open /dev/dsp, confirm capability to mmap, and get size of dma buffer
+ if (!audio_fd) {
+ seteuid(saved_euid);
+
+ audio_fd = open(snddevice->string, O_RDWR);
+
+ seteuid(getuid());
+
+ if (audio_fd < 0) {
+ perror(snddevice->string);
+ Com_Printf("Could not open %s\n", snddevice->string);
+ return 0;
+ }
+ }
+
+ if (ioctl(audio_fd, SNDCTL_DSP_GETCAPS, &caps) == -1) {
+ perror(snddevice->string);
+ Com_Printf("Sound driver too old\n");
+ close(audio_fd);
+ return 0;
+ }
+
+ if (!(caps & DSP_CAP_TRIGGER) || !(caps & DSP_CAP_MMAP)) {
+ Com_Printf("Sorry but your soundcard can't do this\n");
+ close(audio_fd);
+ return 0;
+ }
+
+
+ /* SNDCTL_DSP_GETOSPACE moved to be called later */
+
+ // set sample bits & speed
+ dma.samplebits = (int)sndbits->value;
+ if (dma.samplebits != 16 && dma.samplebits != 8) {
+ ioctl(audio_fd, SNDCTL_DSP_GETFMTS, &fmt);
+ if (fmt & AFMT_S16_LE)
+ dma.samplebits = 16;
+ else if (fmt & AFMT_U8)
+ dma.samplebits = 8;
+ }
+
+ dma.speed = (int)sndspeed->value;
+ if (!dma.speed) {
+ for (i=0 ; i<sizeof(tryrates)/4 ; i++)
+ if (!ioctl(audio_fd, SNDCTL_DSP_SPEED, &tryrates[i]))
+ break;
+ dma.speed = tryrates[i];
+ }
+
+ dma.channels = (int)sndchannels->value;
+ if (dma.channels < 1 || dma.channels > 2)
+ dma.channels = 2;
+
+/* mmap() call moved forward */
+
+ tmp = 0;
+ if (dma.channels == 2)
+ tmp = 1;
+ rc = ioctl(audio_fd, SNDCTL_DSP_STEREO, &tmp);
+ if (rc < 0) {
+ perror(snddevice->string);
+ Com_Printf("Could not set %s to stereo=%d", snddevice->string, dma.channels);
+ close(audio_fd);
+ return 0;
+ }
+
+ if (tmp)
+ dma.channels = 2;
+ else
+ dma.channels = 1;
+
+ rc = ioctl(audio_fd, SNDCTL_DSP_SPEED, &dma.speed);
+ if (rc < 0) {
+ perror(snddevice->string);
+ Com_Printf("Could not set %s speed to %d", snddevice->string, dma.speed);
+ close(audio_fd);
+ return 0;
+ }
+
+ if (dma.samplebits == 16) {
+ rc = AFMT_S16_LE;
+ rc = ioctl(audio_fd, SNDCTL_DSP_SETFMT, &rc);
+ if (rc < 0) {
+ perror(snddevice->string);
+ Com_Printf("Could not support 16-bit data. Try 8-bit.\n");
+ close(audio_fd);
+ return 0;
+ }
+ } else if (dma.samplebits == 8) {
+ rc = AFMT_U8;
+ rc = ioctl(audio_fd, SNDCTL_DSP_SETFMT, &rc);
+ if (rc < 0) {
+ perror(snddevice->string);
+ Com_Printf("Could not support 8-bit data.\n");
+ close(audio_fd);
+ return 0;
+ }
+ } else {
+ perror(snddevice->string);
+ Com_Printf("%d-bit sound not supported.", dma.samplebits);
+ close(audio_fd);
+ return 0;
+ }
+
+ if (ioctl(audio_fd, SNDCTL_DSP_GETOSPACE, &info)==-1) {
+ perror("GETOSPACE");
+ Com_Printf("Um, can't do GETOSPACE?\n");
+ close(audio_fd);
+ return 0;
+ }
+
+ dma.samples = info.fragstotal * info.fragsize / (dma.samplebits/8);
+ dma.submission_chunk = 1;
+
+ // memory map the dma buffer
+
+ // TTimo 2001/10/08 added PROT_READ to the mmap
+ // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=371
+ // checking Alsa bug, doesn't allow dma alloc with PROT_READ?
+
+ if (!dma.buffer)
+ dma.buffer = (unsigned char *) mmap(NULL, info.fragstotal
+ * info.fragsize, PROT_WRITE|PROT_READ, MAP_FILE|MAP_SHARED, audio_fd, 0);
+
+ if (dma.buffer == MAP_FAILED)
+ {
+ Com_Printf("Could not mmap dma buffer PROT_WRITE|PROT_READ\n");
+ Com_Printf("trying mmap PROT_WRITE (with associated better compatibility / less performance code)\n");
+ dma.buffer = (unsigned char *) mmap(NULL, info.fragstotal
+ * info.fragsize, PROT_WRITE, MAP_FILE|MAP_SHARED, audio_fd, 0);
+ // NOTE TTimo could add a variable to force using regular memset on systems that are known to be safe
+ use_custom_memset = qtrue;
+ }
+
+ if (dma.buffer == MAP_FAILED) {
+ perror(snddevice->string);
+ Com_Printf("Could not mmap %s\n", snddevice->string);
+ close(audio_fd);
+ return 0;
+ }
+
+ // toggle the trigger & start her up
+
+ tmp = 0;
+ rc = ioctl(audio_fd, SNDCTL_DSP_SETTRIGGER, &tmp);
+ if (rc < 0) {
+ perror(snddevice->string);
+ Com_Printf("Could not toggle.\n");
+ close(audio_fd);
+ return 0;
+ }
+
+ tmp = PCM_ENABLE_OUTPUT;
+ rc = ioctl(audio_fd, SNDCTL_DSP_SETTRIGGER, &tmp);
+ if (rc < 0) {
+ perror(snddevice->string);
+ Com_Printf("Could not toggle.\n");
+ close(audio_fd);
+
+ return 0;
+ }
+
+ snd_inited = 1;
+ return 1;
+}
+
+int SNDDMA_GetDMAPos(void)
+{
+ struct count_info count;
+
+ if (!snd_inited) return 0;
+
+ if (ioctl(audio_fd, SNDCTL_DSP_GETOPTR, &count) == -1) {
+ perror(snddevice->string);
+ Com_Printf("Uh, sound dead.\n");
+ close(audio_fd);
+ snd_inited = 0;
+ return 0;
+ }
+ return count.ptr / (dma.samplebits / 8);
+}
+
+void SNDDMA_Shutdown(void)
+{
+}
+
+/*
+==============
+SNDDMA_Submit
+
+Send sound to device if buffer isn't really the dma buffer
+===============
+*/
+void SNDDMA_Submit(void)
+{
+}
+
+void SNDDMA_BeginPainting (void)
+{
+}
diff --git a/code/unix/matha.s b/code/unix/matha.s
new file mode 100755
index 0000000..b193661
--- /dev/null
+++ b/code/unix/matha.s
@@ -0,0 +1,425 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// math.s
+// x86 assembly-language math routines.
+
+#define GLQUAKE 1 // don't include unneeded defs
+#include "qasm.h"
+
+
+#if id386
+
+ .data
+
+ .align 4
+Ljmptab: .long Lcase0, Lcase1, Lcase2, Lcase3
+ .long Lcase4, Lcase5, Lcase6, Lcase7
+
+ .text
+
+// TODO: rounding needed?
+// stack parameter offset
+#define val 4
+
+.globl C(Invert24To16)
+C(Invert24To16):
+
+ movl val(%esp),%ecx
+ movl $0x100,%edx // 0x10000000000 as dividend
+ cmpl %edx,%ecx
+ jle LOutOfRange
+
+ subl %eax,%eax
+ divl %ecx
+
+ ret
+
+LOutOfRange:
+ movl $0xFFFFFFFF,%eax
+ ret
+
+#if 0
+
+#define in 4
+#define out 8
+
+ .align 2
+.globl C(TransformVector)
+C(TransformVector):
+ movl in(%esp),%eax
+ movl out(%esp),%edx
+
+ flds (%eax) // in[0]
+ fmuls C(vright) // in[0]*vright[0]
+ flds (%eax) // in[0] | in[0]*vright[0]
+ fmuls C(vup) // in[0]*vup[0] | in[0]*vright[0]
+ flds (%eax) // in[0] | in[0]*vup[0] | in[0]*vright[0]
+ fmuls C(vpn) // in[0]*vpn[0] | in[0]*vup[0] | in[0]*vright[0]
+
+ flds 4(%eax) // in[1] | ...
+ fmuls C(vright)+4 // in[1]*vright[1] | ...
+ flds 4(%eax) // in[1] | in[1]*vright[1] | ...
+ fmuls C(vup)+4 // in[1]*vup[1] | in[1]*vright[1] | ...
+ flds 4(%eax) // in[1] | in[1]*vup[1] | in[1]*vright[1] | ...
+ fmuls C(vpn)+4 // in[1]*vpn[1] | in[1]*vup[1] | in[1]*vright[1] | ...
+ fxch %st(2) // in[1]*vright[1] | in[1]*vup[1] | in[1]*vpn[1] | ...
+
+ faddp %st(0),%st(5) // in[1]*vup[1] | in[1]*vpn[1] | ...
+ faddp %st(0),%st(3) // in[1]*vpn[1] | ...
+ faddp %st(0),%st(1) // vpn_accum | vup_accum | vright_accum
+
+ flds 8(%eax) // in[2] | ...
+ fmuls C(vright)+8 // in[2]*vright[2] | ...
+ flds 8(%eax) // in[2] | in[2]*vright[2] | ...
+ fmuls C(vup)+8 // in[2]*vup[2] | in[2]*vright[2] | ...
+ flds 8(%eax) // in[2] | in[2]*vup[2] | in[2]*vright[2] | ...
+ fmuls C(vpn)+8 // in[2]*vpn[2] | in[2]*vup[2] | in[2]*vright[2] | ...
+ fxch %st(2) // in[2]*vright[2] | in[2]*vup[2] | in[2]*vpn[2] | ...
+
+ faddp %st(0),%st(5) // in[2]*vup[2] | in[2]*vpn[2] | ...
+ faddp %st(0),%st(3) // in[2]*vpn[2] | ...
+ faddp %st(0),%st(1) // vpn_accum | vup_accum | vright_accum
+
+ fstps 8(%edx) // out[2]
+ fstps 4(%edx) // out[1]
+ fstps (%edx) // out[0]
+
+ ret
+
+#endif
+
+#define EMINS 4+4
+#define EMAXS 4+8
+#define P 4+12
+
+ .align 2
+.globl C(BoxOnPlaneSide)
+C(BoxOnPlaneSide):
+ pushl %ebx
+
+ movl P(%esp),%edx
+ movl EMINS(%esp),%ecx
+ xorl %eax,%eax
+ movl EMAXS(%esp),%ebx
+ movb pl_signbits(%edx),%al
+ cmpb $8,%al
+ jge Lerror
+ flds pl_normal(%edx) // p->normal[0]
+ fld %st(0) // p->normal[0] | p->normal[0]
+ // bk000422 - warning: missing prefix `*' in absolute indirect address, maybe misassembled!
+ // bk001129 - fix from Andrew Henderson, was: Ljmptab(,%eax,4)
+ jmp *Ljmptab(,%eax,4)
+
+
+//dist1= p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2];
+//dist2= p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2];
+Lcase0:
+ fmuls (%ebx) // p->normal[0]*emaxs[0] | p->normal[0]
+ flds pl_normal+4(%edx) // p->normal[1] | p->normal[0]*emaxs[0] |
+ // p->normal[0]
+ fxch %st(2) // p->normal[0] | p->normal[0]*emaxs[0] |
+ // p->normal[1]
+ fmuls (%ecx) // p->normal[0]*emins[0] |
+ // p->normal[0]*emaxs[0] | p->normal[1]
+ fxch %st(2) // p->normal[1] | p->normal[0]*emaxs[0] |
+ // p->normal[0]*emins[0]
+ fld %st(0) // p->normal[1] | p->normal[1] |
+ // p->normal[0]*emaxs[0] |
+ // p->normal[0]*emins[0]
+ fmuls 4(%ebx) // p->normal[1]*emaxs[1] | p->normal[1] |
+ // p->normal[0]*emaxs[0] |
+ // p->normal[0]*emins[0]
+ flds pl_normal+8(%edx) // p->normal[2] | p->normal[1]*emaxs[1] |
+ // p->normal[1] | p->normal[0]*emaxs[0] |
+ // p->normal[0]*emins[0]
+ fxch %st(2) // p->normal[1] | p->normal[1]*emaxs[1] |
+ // p->normal[2] | p->normal[0]*emaxs[0] |
+ // p->normal[0]*emins[0]
+ fmuls 4(%ecx) // p->normal[1]*emins[1] |
+ // p->normal[1]*emaxs[1] |
+ // p->normal[2] | p->normal[0]*emaxs[0] |
+ // p->normal[0]*emins[0]
+ fxch %st(2) // p->normal[2] | p->normal[1]*emaxs[1] |
+ // p->normal[1]*emins[1] |
+ // p->normal[0]*emaxs[0] |
+ // p->normal[0]*emins[0]
+ fld %st(0) // p->normal[2] | p->normal[2] |
+ // p->normal[1]*emaxs[1] |
+ // p->normal[1]*emins[1] |
+ // p->normal[0]*emaxs[0] |
+ // p->normal[0]*emins[0]
+ fmuls 8(%ebx) // p->normal[2]*emaxs[2] |
+ // p->normal[2] |
+ // p->normal[1]*emaxs[1] |
+ // p->normal[1]*emins[1] |
+ // p->normal[0]*emaxs[0] |
+ // p->normal[0]*emins[0]
+ fxch %st(5) // p->normal[0]*emins[0] |
+ // p->normal[2] |
+ // p->normal[1]*emaxs[1] |
+ // p->normal[1]*emins[1] |
+ // p->normal[0]*emaxs[0] |
+ // p->normal[2]*emaxs[2]
+ faddp %st(0),%st(3) //p->normal[2] |
+ // p->normal[1]*emaxs[1] |
+ // p->normal[1]*emins[1]+p->normal[0]*emins[0]|
+ // p->normal[0]*emaxs[0] |
+ // p->normal[2]*emaxs[2]
+ fmuls 8(%ecx) //p->normal[2]*emins[2] |
+ // p->normal[1]*emaxs[1] |
+ // p->normal[1]*emins[1]+p->normal[0]*emins[0]|
+ // p->normal[0]*emaxs[0] |
+ // p->normal[2]*emaxs[2]
+ fxch %st(1) //p->normal[1]*emaxs[1] |
+ // p->normal[2]*emins[2] |
+ // p->normal[1]*emins[1]+p->normal[0]*emins[0]|
+ // p->normal[0]*emaxs[0] |
+ // p->normal[2]*emaxs[2]
+ faddp %st(0),%st(3) //p->normal[2]*emins[2] |
+ // p->normal[1]*emins[1]+p->normal[0]*emins[0]|
+ // p->normal[0]*emaxs[0]+p->normal[1]*emaxs[1]|
+ // p->normal[2]*emaxs[2]
+ fxch %st(3) //p->normal[2]*emaxs[2] +
+ // p->normal[1]*emins[1]+p->normal[0]*emins[0]|
+ // p->normal[0]*emaxs[0]+p->normal[1]*emaxs[1]|
+ // p->normal[2]*emins[2]
+ faddp %st(0),%st(2) //p->normal[1]*emins[1]+p->normal[0]*emins[0]|
+ // dist1 | p->normal[2]*emins[2]
+
+ jmp LSetSides
+
+//dist1= p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2];
+//dist2= p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2];
+Lcase1:
+ fmuls (%ecx) // emins[0]
+ flds pl_normal+4(%edx)
+ fxch %st(2)
+ fmuls (%ebx) // emaxs[0]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 4(%ebx) // emaxs[1]
+ flds pl_normal+8(%edx)
+ fxch %st(2)
+ fmuls 4(%ecx) // emins[1]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 8(%ebx) // emaxs[2]
+ fxch %st(5)
+ faddp %st(0),%st(3)
+ fmuls 8(%ecx) // emins[2]
+ fxch %st(1)
+ faddp %st(0),%st(3)
+ fxch %st(3)
+ faddp %st(0),%st(2)
+
+ jmp LSetSides
+
+//dist1= p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2];
+//dist2= p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2];
+Lcase2:
+ fmuls (%ebx) // emaxs[0]
+ flds pl_normal+4(%edx)
+ fxch %st(2)
+ fmuls (%ecx) // emins[0]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 4(%ecx) // emins[1]
+ flds pl_normal+8(%edx)
+ fxch %st(2)
+ fmuls 4(%ebx) // emaxs[1]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 8(%ebx) // emaxs[2]
+ fxch %st(5)
+ faddp %st(0),%st(3)
+ fmuls 8(%ecx) // emins[2]
+ fxch %st(1)
+ faddp %st(0),%st(3)
+ fxch %st(3)
+ faddp %st(0),%st(2)
+
+ jmp LSetSides
+
+//dist1= p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2];
+//dist2= p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2];
+Lcase3:
+ fmuls (%ecx) // emins[0]
+ flds pl_normal+4(%edx)
+ fxch %st(2)
+ fmuls (%ebx) // emaxs[0]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 4(%ecx) // emins[1]
+ flds pl_normal+8(%edx)
+ fxch %st(2)
+ fmuls 4(%ebx) // emaxs[1]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 8(%ebx) // emaxs[2]
+ fxch %st(5)
+ faddp %st(0),%st(3)
+ fmuls 8(%ecx) // emins[2]
+ fxch %st(1)
+ faddp %st(0),%st(3)
+ fxch %st(3)
+ faddp %st(0),%st(2)
+
+ jmp LSetSides
+
+//dist1= p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2];
+//dist2= p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2];
+Lcase4:
+ fmuls (%ebx) // emaxs[0]
+ flds pl_normal+4(%edx)
+ fxch %st(2)
+ fmuls (%ecx) // emins[0]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 4(%ebx) // emaxs[1]
+ flds pl_normal+8(%edx)
+ fxch %st(2)
+ fmuls 4(%ecx) // emins[1]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 8(%ecx) // emins[2]
+ fxch %st(5)
+ faddp %st(0),%st(3)
+ fmuls 8(%ebx) // emaxs[2]
+ fxch %st(1)
+ faddp %st(0),%st(3)
+ fxch %st(3)
+ faddp %st(0),%st(2)
+
+ jmp LSetSides
+
+//dist1= p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2];
+//dist2= p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2];
+Lcase5:
+ fmuls (%ecx) // emins[0]
+ flds pl_normal+4(%edx)
+ fxch %st(2)
+ fmuls (%ebx) // emaxs[0]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 4(%ebx) // emaxs[1]
+ flds pl_normal+8(%edx)
+ fxch %st(2)
+ fmuls 4(%ecx) // emins[1]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 8(%ecx) // emins[2]
+ fxch %st(5)
+ faddp %st(0),%st(3)
+ fmuls 8(%ebx) // emaxs[2]
+ fxch %st(1)
+ faddp %st(0),%st(3)
+ fxch %st(3)
+ faddp %st(0),%st(2)
+
+ jmp LSetSides
+
+//dist1= p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2];
+//dist2= p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2];
+Lcase6:
+ fmuls (%ebx) // emaxs[0]
+ flds pl_normal+4(%edx)
+ fxch %st(2)
+ fmuls (%ecx) // emins[0]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 4(%ecx) // emins[1]
+ flds pl_normal+8(%edx)
+ fxch %st(2)
+ fmuls 4(%ebx) // emaxs[1]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 8(%ecx) // emins[2]
+ fxch %st(5)
+ faddp %st(0),%st(3)
+ fmuls 8(%ebx) // emaxs[2]
+ fxch %st(1)
+ faddp %st(0),%st(3)
+ fxch %st(3)
+ faddp %st(0),%st(2)
+
+ jmp LSetSides
+
+//dist1= p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2];
+//dist2= p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2];
+Lcase7:
+ fmuls (%ecx) // emins[0]
+ flds pl_normal+4(%edx)
+ fxch %st(2)
+ fmuls (%ebx) // emaxs[0]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 4(%ecx) // emins[1]
+ flds pl_normal+8(%edx)
+ fxch %st(2)
+ fmuls 4(%ebx) // emaxs[1]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 8(%ecx) // emins[2]
+ fxch %st(5)
+ faddp %st(0),%st(3)
+ fmuls 8(%ebx) // emaxs[2]
+ fxch %st(1)
+ faddp %st(0),%st(3)
+ fxch %st(3)
+ faddp %st(0),%st(2)
+
+LSetSides:
+
+// sides = 0;
+// if (dist1 >= p->dist)
+// sides = 1;
+// if (dist2 < p->dist)
+// sides |= 2;
+
+ faddp %st(0),%st(2) // dist1 | dist2
+ fcomps pl_dist(%edx)
+ xorl %ecx,%ecx
+ fnstsw %ax
+ fcomps pl_dist(%edx)
+ andb $1,%ah
+ xorb $1,%ah
+ addb %ah,%cl
+
+ fnstsw %ax
+ andb $1,%ah
+ addb %ah,%ah
+ addb %ah,%cl
+
+// return sides;
+
+ popl %ebx
+ movl %ecx,%eax // return status
+
+ ret
+
+
+Lerror:
+ movl 1, %eax
+ ret
+
+#endif // id386
diff --git a/code/unix/pcons-2.3.1 b/code/unix/pcons-2.3.1
new file mode 100755
index 0000000..db9452c
--- /dev/null
+++ b/code/unix/pcons-2.3.1
@@ -0,0 +1,7911 @@
+#!/usr/bin/env perl
+
+#
+# Revision history:
+# -----------------
+# July 2001, Thomas Gleerup <tgl@oticon.dk>
+# 1) pcons-1.6 (John Erickson, August 1999) merged into cons-2.3.0.
+# 2) Added automatic insertion of && for multi-line commands.
+#
+# September 2001, Thomas Gleerup <tgl@oticon.dk>
+# 1) Updated with Kevin Nolish's multi-line improvement.
+# 2) Improved this so that single [perl] commands can still be used.
+#
+
+# NOTE: Cons intentionally does not use the "perl -w" option or
+# "use strict." Because Cons "configuration files" are actually
+# Perl scripts, enabling those restrictions here would force them
+# on every user's config files, wanted or not. Would users write
+# "better" Construct and Conscript files if we forced "use strict"
+# on them? Probably. But we want people to use Cons to get work
+# done, not force everyone to become a Perl guru to use it, so we
+# don't insist.
+#
+# That said, Cons' code is both "perl -w" and "use strict" clean.
+# Regression tests keep the code honest by checking for warnings
+# and "use strict" failures.
+
+use vars qw( $CVS_id $CVS_ver $ver_num $ver_rev $version );
+
+# I hate those CVS tags
+$CVS_id = 'pcons-2.3.1';
+$CVS_ver = (split (/\s+/, $CVS_id))[2];
+
+$ver_num = "__VERSION__";
+$ver_rev = "__REVISION__";
+
+#$version = "This is Cons $ver_num$ver_rev ($CVS_id)\n";
+$version = "This is parallel Cons (pcons) $ver_num$ver_rev ($CVS_id)\n";
+
+# Cons: A Software Construction Tool.
+# Copyright (c) 1996-2001 Free Software Foundation, Inc.
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; see the file COPYING. If not, write to
+# the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+# Boston, MA 02111-1307, USA.
+
+require 5.003;
+
+# See the NOTE above about why Cons doesn't "use strict".
+use integer;
+use Cwd;
+use File::Copy;
+
+use vars qw( $_WIN32 $_a $_exe $_o $_so );
+
+#------------------------------------------------------------------
+# Determine if running on win32 platform - either Windows NT or 95
+#------------------------------------------------------------------
+
+use vars qw( $PATH_SEPARATOR $iswin32 $_WIN32 $usage $indent @targets );
+
+BEGIN
+{
+ use Config;
+
+ # if the version is 5.003, we can check $^O
+ if ($] < 5.003)
+ {
+ eval("require Win32");
+ $_WIN32 = (!$@);
+ }
+ else
+ {
+ $_WIN32 = ($^O eq "MSWin32") ? 1 : 0;
+ }
+
+ # Fetch the PATH separator from Config;
+ # provide our old defaults in case it's not set.
+ $PATH_SEPARATOR = $Config{path_sep};
+ $PATH_SEPARATOR = $_WIN32 ? ';' : ':' if !defined $PATH_SEPARATOR;
+
+ # Fetch file suffixes from Config,
+ # accomodating differences in the Config variables
+ # used by different Perl versions.
+ $_exe = $Config{_exe};
+ $_exe = $Config{exe_ext} if !defined $_exe;
+ $_exe = $_WIN32 ? '.exe' : '' if !defined $_exe;
+ $_o = $Config{_o};
+ $_o = $Config{obj_ext} if !defined $_o;
+ $_o = $_WIN32 ? '.obj' : '.o' if !defined $_o;
+ $_a = $Config{_a};
+ $_a = $Config{lib_ext} if !defined $_a;
+ $_a = $_WIN32 ? '.lib' : '.a' if !defined $_a;
+ $_so = ".$Config{so}";
+ $_so = $_WIN32 ? '.dll' : '.so' if !defined $_so;
+}
+
+# Flush stdout each time.
+$| = 1;
+
+# Seed random number generator.
+srand(time . $$); # this works better than time ^ $$ in perlfunc manpage.
+
+$usage = q(
+Usage: cons <arguments> -- <construct-args>
+
+Arguments can be any of the following, in any order:
+
+ <targets> Build the specified targets. If <target> is a directory
+ recursively build everything within that directory.
+
+ +<pattern> Limit the cons scripts considered to just those that
+ match <pattern>. Multiple + arguments are accepted.
+
+ <name>=<val> Sets <name> to value <val> in the ARG hash passed to the
+ top-level Construct file.
+
+ -cc Show command that would have been executed, when
+ retrieving from cache. No indication that the file
+ has been retrieved is given; this is useful for
+ generating build logs that can be compared with
+ real build logs.
+
+ -cd Disable all caching. Do not retrieve from cache nor
+ flush to cache.
+
+ -cr Build dependencies in random order. This is useful when
+ building multiple similar trees with caching enabled.
+
+ -cs Synchronize existing build targets that are found to be
+ up-to-date with cache. This is useful if caching has
+ been disabled with -cc or just recently enabled with
+ UseCache.
+
+ -d Enable dependency debugging.
+
+ -f <file> Use the specified file instead of "Construct" (but first
+ change to containing directory of <file>).
+
+ -h Show a help message local to the current build if
+ one such is defined, and exit.
+
+ -k Keep going as far as possible after errors.
+
+ -o <file> Read override file <file>.
+
+ -p Show construction products in specified trees.
+ -pa Show construction products and associated actions.
+ -pw Show products and where they are defined.
+
+ -q Be quiet; multiple -q flags increase quietness level:
+ 1: quiet about Installing and Removing targets
+ 2: quiet about build commands, up-to-date targets
+
+ -r Remove construction products associated with <targets>
+
+ -R <repos> Search for files in <repos>. Multiple -R <repos>
+ directories are searched in the order specified.
+
+ -S <pkg> Use package sig::<pkg> to calculate file signatures.
+ Currently supported values are "md5" for MD5
+ signatures (the default) and "md5::debug" for MD5
+ signature debug information.
+
+ -t Traverse up the directory hierarchy looking for a
+ Construct file, if none exists in the current directory.
+ (Targets will be modified to be relative to the
+ Construct file.)
+
+ -v Show cons version and continue processing.
+ -V Show cons version and exit.
+
+ -wf <file> Write all filenames considered into <file>.
+
+ -x Show this message and exit.
+
+
+ Please report any suggestions through the cons-discuss@gnu.org mailing
+ list.
+
+ To subscribe, send mail to cons-discuss-request@gnu.org with body
+ 'subscribe'.
+
+ If you find a bug, please report it through the bug-cons@gnu.org
+ mailing list.
+
+ Information about CONS can be obtained from the official cons web site
+ http://www.dsmit.com/cons/ or its mirrors (listed there).
+
+ The cons maintainers can be contacted by email at cons-maintainers@gnu.org
+
+ User documentation of cons is contained in cons and can be obtained
+ by doing 'perldoc /path/to/cons'.
+
+);
+my $pcons = 1;
+
+# Simplify program name, if it is a path.
+{
+ my ($vol, $dir, $file) = File::Spec->splitpath(File::Spec->canonpath($0));
+ $0 = $file;
+}
+
+# Default parameters.
+$param::topfile = 'Construct'; # Top-level construction file.
+$param::install = 1; # Show installations
+$param::build = 1; # Build targets
+ ### $param::show = 1; # Show building of targets.
+$param::sigpro = 'md5'; # Signature protocol.
+$param::depfile = ''; # Write all deps out to this file
+$param::salt = ''; # Salt derived file signatures with this.
+$param::sourcesig = ['*' => 'content']; # Source file signature calculation
+$param::rep_sig_times_ok = 1; # Repository .consign times are in sync
+ # w/files.
+$param::conscript_chdir = 0; # Change dir to Conscript directory
+$param::quiet = 0; # should we show the command being executed.
+$param::max_jobs = 1; # pcons
+
+@param::defaults = ();
+
+#
+$indent = '';
+
+# Display a command while executing or otherwise. This
+# should be called by command builder action methods.
+sub showcom
+{
+ print($indent . $_[0] . "\n") if ($param::quiet < 2);
+}
+
+# Default environment.
+# This contains only the completely platform-independent information
+# we can figure out. Platform-specific information (UNIX, Win32)
+# gets added below.
+@param::base = (
+ 'SIGNATURE' => ['*' => 'build'],
+ 'SUFEXE' => $_exe, # '' on UNIX systems
+ 'SUFLIB' => $_a, # '.a' on UNIX systems
+ 'SUFLIBS' => "$_so:$_a", # '.so:.a' on UNIX
+ 'SUFOBJ' => $_o, # '.o' on UNIX systems
+ 'SUFMAP' => {
+ '.c' => 'build::command::cc',
+ '.s' => 'build::command::cc',
+ '.S' => 'build::command::cc',
+ '.C' => 'build::command::cxx',
+ '.cc' => 'build::command::cxx',
+ '.cxx' => 'build::command::cxx',
+ '.cpp' => 'build::command::cxx',
+ '.c++' => 'build::command::cxx',
+ '.C++' => 'build::command::cxx',
+ },
+ 'PERL' => $^X,
+ );
+
+# pcons does not allow multi-line commands
+my $ar_command = ($param::max_jobs <= 1)
+ ? # pcons
+ ['%AR %ARFLAGS %> %<', '%RANLIB %>']
+ : # cons
+ '%AR %ARFLAGS %> %< && %RANLIB %>'; # pcons
+
+%param::rulesets = (
+
+ # Defaults for Win32.
+ # Defined for VC++ 6.0 by Greg Spencer <greg_spencer@acm.org>
+ # Your mileage may vary.
+ 'msvc' => [
+ 'CC' => 'cl',
+ 'CFLAGS' => '/nologo',
+ 'CCCOM' => '%CC %CFLAGS %_IFLAGS /c %< /Fo%>',
+ 'CXX' => '%CC',
+ 'CXXFLAGS' => '%CFLAGS',
+ 'CXXCOM' => '%CXX %CXXFLAGS %_IFLAGS /c %< /Fo%>',
+ 'INCDIRPREFIX' => '/I',
+ 'INCDIRSUFFIX' => '',
+ 'LINK' => 'link',
+ 'LINKCOM' => '%LINK %LDFLAGS /out:%> %< %_LDIRS %LIBS',
+ 'LINKMODULECOM' => '%LD /r /o %> %<',
+ 'LIBDIRPREFIX' => '/LIBPATH:',
+ 'LIBDIRSUFFIX' => '',
+ 'AR' => 'lib',
+ 'ARFLAGS' => '/nologo ',
+ 'ARCOM' => "%AR %ARFLAGS /out:%> %<",
+ 'RANLIB' => '',
+ 'LD' => 'link',
+ 'LDFLAGS' => '/nologo ',
+ 'PREFLIB' => '',
+ ],
+
+ # Defaults for a typical (?) UNIX platform.
+ # Your mileage may vary.
+ 'unix' => [
+ 'CC' => 'cc',
+ 'CFLAGS' => '',
+ 'CCCOM' => '%CC %CFLAGS %_IFLAGS -c %< -o %>',
+ 'CXX' => '%CC',
+ 'CXXFLAGS' => '%CFLAGS',
+ 'CXXCOM' => '%CXX %CXXFLAGS %_IFLAGS -c %< -o %>',
+ 'INCDIRPREFIX' => '-I',
+ 'INCDIRSUFFIX' => '',
+ 'LINK' => '%CXX',
+ 'LINKCOM' => '%LINK %LDFLAGS -o %> %< %_LDIRS %LIBS',
+ 'LINKMODULECOM' => '%LD -r -o %> %<',
+ 'LIBDIRPREFIX' => '-L',
+ 'LIBDIRSUFFIX' => '',
+ 'AR' => 'ar',
+ 'ARFLAGS' => 'r', # rs?
+ 'ARCOM' => $ar_command, # pcons
+ 'RANLIB' => 'ranlib',
+ 'AS' => 'as',
+ 'ASFLAGS' => '',
+ 'ASCOM' => '%AS %ASFLAGS %< -o %>',
+ 'LD' => 'ld',
+ 'LDFLAGS' => '',
+ 'PREFLIB' => 'lib',
+ 'ENV' => {'PATH' => '/bin:/usr/bin'},
+ ],
+ );
+
+# Set the rules based on the platform.
+script::DefaultRules(script::RuleSet($_WIN32 ? 'msvc' : 'unix'));
+
+# Handle command line arguments.
+while (@ARGV)
+{
+ $_ = shift @ARGV;
+ last if /^--$/; # Argument passing to Construct.
+ &option, next if s/^-//;
+ push (@param::include, $_), next if s/^\+//;
+ &equate, next if /=/;
+ push (@targets, $_), next;
+}
+
+sub option
+{
+ my %opt = (
+ 'cc' => sub { $param::cachecom = 1; },
+ 'cd' => sub { $param::cachedisable = 1; },
+ 'cr' => sub { $param::random = 1; },
+ 'cs' => sub { $param::cachesync = 1; },
+ 'd' => sub { $param::depends = 1; },
+ 'h' => sub { $param::localhelp = 1; },
+ 'k' => sub { $param::kflag = 1; },
+ 'p' => sub {
+ $param::pflag = 1;
+ $param::build = 0;
+ },
+ 'pa' => sub {
+ $param::pflag = 1;
+ $param::aflag = 1;
+ $indent = "... ";
+ $param::build = 0;
+ },
+ 'pw' => sub {
+ $param::pflag = 1;
+ $param::wflag = 1;
+ $param::build = 0;
+ },
+ 'q' => sub { $param::quiet++; },
+ 'r' => sub {
+ $param::rflag = 1;
+ $param::build = 0;
+ },
+ 't' => sub { $param::traverse = 1; },
+ 'v' => sub { print($version); },
+ 'V' => sub { print($version), exit(0); },
+ 'x' => sub { print($usage), exit 0; },
+ );
+
+ my %opt_arg = (
+ 'f' => sub { $param::topfile = $_[0]; },
+ 'o' => sub { $param::overfile = $_[0]; },
+ 'R' => sub { script::Repository($_[0]); },
+ 'S' => sub { $param::sigpro = $_[0]; },
+ 'wf' => sub { $param::depfile = $_[0]; },
+ 'j' => sub { $param::max_jobs = $_[0]; }, # pcons
+ );
+
+ if (defined $opt{$_})
+ {
+ &{$opt{$_}} ();
+ return;
+ }
+ while ($_)
+ {
+ $_ =~ m/(.)(.*)/;
+ if (defined $opt{$1})
+ {
+ &{$opt{$1}} ();
+ $_ = $2;
+ next;
+ }
+ if (defined $opt_arg{$1})
+ {
+ if (!$2)
+ {
+ $_ = shift @ARGV;
+ die ("$0: -$1 option requires an argument.\n") if !$_;
+ }
+ &{$opt_arg{$1}} ($2 || $_);
+ return;
+ }
+ $_ =~ m/(..)(.*)/;
+ if (defined $opt_arg{$1})
+ {
+ if (!$2)
+ {
+ $_ = shift @ARGV;
+ die ("$0: -$1 option requires an argument.\n") if !$_;
+ }
+ &{$opt_arg{$1}} ($2 || $_);
+ return;
+ }
+ if ($_)
+ {
+ die
+ qq($0: unrecognized option "-$_". Use -x for a usage message.\n);
+ }
+ }
+}
+
+# Process an equate argument (var=val).
+sub equate
+{
+ my ($var, $val) = /([^=]*)=(.*)/;
+ $script::ARG{$var} = $val;
+}
+
+# Define file signature protocol.
+'sig'->select($param::sigpro);
+
+# Cleanup after an interrupt.
+$SIG{INT} = $SIG{QUIT} = $SIG{TERM} = sub {
+ $SIG{PIPE} = $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = 'IGNORE';
+ $SIG{HUP} = $SIG{INT} if !$main::_WIN32;
+ warn("\n$0: killed\n");
+
+ # Call this first, to make sure that this processing
+ # occurs even if a child process does not die (and we
+ # hang on the wait).
+ sig::hash::END();
+ wait();
+ exit(1);
+};
+$SIG{HUP} = $SIG{INT} if !$main::_WIN32;
+
+# Cleanup after a broken pipe (someone piped our stdout?)
+$SIG{PIPE} = sub {
+ $SIG{PIPE} = $SIG{HUP} = $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = 'IGNORE';
+ warn("\n$0: broken pipe\n");
+ sig::hash::END();
+ wait();
+ exit(1);
+};
+
+if ($param::depfile)
+{
+ open(main::DEPFILE, ">" . $param::depfile)
+ || die ("$0: couldn't open $param::depfile ($!)\n");
+}
+
+# If the supplied top-level Conscript file is not in the
+# current directory, then change to that directory.
+{
+ my ($vol, $dir, $file) =
+ File::Spec->splitpath(File::Spec->canonpath($param::topfile));
+ if ($vol || $dir)
+ {
+ my ($cd) = File::Spec->catpath($vol, $dir, undef);
+ chdir($cd) || die ("$0: couldn't change to directory $cd ($!)\n");
+ $param::topfile = $file;
+ }
+}
+
+# Walk up the directory hierarchy looking for a Conscript file (if -t set).
+my ($target_top);
+my (@targetdir) = ();
+if ($param::traverse && !-f $param::topfile)
+{
+ my ($vol, $dirs, $file) = File::Spec->splitpath(cwd());
+ my (@dirs) = (File::Spec->splitdir($dirs), $file);
+ while (
+ !-f File::Spec->catpath($vol, File::Spec->catdir(@dirs),
+ $param::topfile))
+ {
+ die ("$0: unable to find $param::topfile.\n") if !@dirs;
+ unshift (@targetdir, pop (@dirs));
+ }
+ my ($cwd) = File::Spec->catpath($vol, File::Spec->catdir(@dirs), '');
+ print "$0: Entering directory `$cwd'\n";
+ chdir($cwd);
+ @targets = map { File::Spec->catdir(@targetdir, $_) } @targets;
+}
+
+# Set up $dir::top and $dir::cwd, now that we are in the right directory.
+dir::init();
+
+#
+if (@targetdir)
+{
+ $target_top = $dir::top->lookupdir(File::Spec->catdir(@targetdir));
+}
+
+# Now handle override file.
+package override;
+if ($param::overfile)
+{
+ my ($ov) = $param::overfile;
+ die qq($0: can\'t read override file "$ov" ($!)\n) if !-f $ov; #'
+ do $ov;
+ if ($@)
+ {
+ chop($@);
+ die qq($0: errors in override file "$ov" ($@)\n);
+ }
+}
+
+# Provide this to user to setup override patterns.
+sub Override
+{
+ my ($re, @env) = @_;
+ return if $param::overrides{$re}; # if identical, first will win.
+ $param::overrides = 1;
+ $param::overrides{$re} = \@env;
+ push (@param::overrides, $re);
+}
+
+package main;
+
+use vars qw( %priority $errors );
+
+# Check script inclusion regexps
+my $re;
+for $re (@param::include)
+{
+ if (!defined eval { "" =~ /$re/ })
+ {
+ my ($err) = $@;
+ $err =~ s/in regexp at .*$//;
+ die ("$0: error in regexp $err");
+ }
+}
+
+# Read the top-level construct file and its included scripts.
+doscripts($param::topfile);
+
+# Status priorities. This lets us aggregate status for directories
+# and print an appropriate message (at the top-level).
+%priority =
+ ('none' => 1, 'handled' => 2, 'built' => 3, 'unknown' => 4, 'errors' => 5);
+
+# If no targets were specified, supply default targets (if any).
+@targets = @param::default_targets if !@targets;
+
+$errors = 0;
+
+# Build the supplied target patterns.
+my $tgt;
+for $tgt (map($dir::top->lookup($_), @targets))
+{
+ if ($target_top && !$tgt->is_under($target_top))
+ {
+
+ # A -t option was used, and this target is not underneath
+ # the directory where we were invoked via -t.
+ # If the target is a directory and the -t directory
+ # is underneath it, then build the -t directory.
+ if (ref $tgt ne "dir" || !$target_top->is_under($tgt))
+ {
+ next;
+ }
+ $tgt = $target_top;
+ }
+ buildtoptarget($tgt);
+}
+
+exit 0 + ($errors != 0);
+
+sub buildtoptarget
+{
+ my ($tgt) = @_;
+ return if !$tgt;
+ my ($status) = buildtarget($tgt);
+ if ($status ne 'built')
+ {
+ my ($path) = $tgt->path;
+ if ($status eq "errors")
+ {
+ print qq($0: "$path" not remade because of errors.\n);
+ $errors++;
+ }
+ elsif ($status eq "handled")
+ {
+ print qq($0: "$path" is up-to-date.\n) if ($param::quiet < 2);
+ }
+ elsif ($status eq "unknown")
+ {
+
+ # cons error already reported.
+ $errors++;
+ }
+ elsif ($status eq "none")
+ {
+
+ # search for targets that may be linked to the given path.
+ my @linked = dir::linked_targets($tgt) if $target_top;
+ if (@linked)
+ {
+ my @names = map($_->path, @linked);
+ print "Linked targets: @names\n" if ($param::quiet < 1);
+ map(buildtoptarget($_), @linked);
+ }
+ else
+ {
+ print qq($0: nothing to be built in "$path".\n)
+ if $param::build && ($param::quiet < 2);
+ }
+ }
+ else
+ {
+ print qq($0: don\'t know how to construct "$path".\n); #'
+ $errors++;
+ }
+ }
+}
+
+# Build the supplied target directory or files. Return aggregated status.
+sub buildtarget
+{
+ my ($tgt) = @_;
+ if (ref($tgt) eq "dir")
+ {
+ my ($result) = "none";
+ my ($priority) = $priority{$result};
+ if (exists $tgt->{member})
+ {
+ my ($members) = $tgt->{member};
+ my $entry;
+ for $entry (sort keys %$members)
+ {
+ next if $entry eq $dir::CURDIR || $entry eq $dir::UPDIR;
+ my ($tgt) = $members->{$entry};
+ next if ref($tgt) ne "dir" && !exists($tgt->{builder});
+ my ($stat) = buildtarget($members->{$entry});
+ my ($pri) = $priority{$stat};
+ if ($pri > $priority)
+ {
+ $priority = $pri;
+ $result = $stat;
+ }
+ }
+ }
+ return $result;
+ }
+ if ($param::depends)
+ {
+ my ($path) = $tgt->path;
+ if ($tgt->{builder})
+ {
+ my (@dep) = (@{$tgt->{dep}}, @{$tgt->{sources}});
+ my ($dep) = join (' ', map($_->path, @dep));
+ print("Target $path: $dep\n");
+ }
+ else
+ {
+ print("Target $path: not a derived file\n");
+ }
+ }
+ if ($param::build)
+ {
+ return build $tgt;
+ }
+ elsif ($param::pflag || $param::wflag || $param::aflag)
+ {
+ if ($tgt->{builder})
+ {
+ if ($param::wflag)
+ {
+ print qq(${\$tgt->path}: $tgt->{script}\n);
+ }
+ elsif ($param::pflag)
+ {
+ print qq(${\$tgt->path}:\n) if $param::aflag;
+ print qq(${\$tgt->path}\n) if !$param::aflag;
+ }
+ if ($param::aflag)
+ {
+ $tgt->{builder}->action($tgt);
+ }
+ }
+ }
+ elsif ($param::rflag && $tgt->{builder})
+ {
+ my ($path) = $tgt->path;
+ if (-f $path)
+ {
+ if (unlink($path))
+ {
+ print("Removed $path\n") if ($param::quiet < 1);
+ }
+ else
+ {
+ warn("$0: couldn't remove $path\n");
+ }
+ }
+ }
+
+ return "none";
+}
+
+package NameSpace;
+
+# Return a hash that maps the name of symbols in a namespace to an
+# array of refs for all types for which the name has a defined value.
+# A list of symbols may be specified; default is all symbols in the
+# name space.
+sub save
+{
+ my $package = shift;
+ my (%namerefs, $var, $type);
+ no strict 'refs';
+ @_ = keys %{$package . "::"} if !@_;
+ foreach $var (@_)
+ {
+ $namerefs{$var} = [];
+ my $fqvar = $package . "::" . $var;
+
+ # If the scalar for this variable name doesn't already
+ # exist, *foo{SCALAR} will autovivify the reference
+ # instead of returning undef, so unlike the other types,
+ # we have to dereference to find out if it exists.
+ push (@{$namerefs{$var}}, *{$fqvar}{SCALAR})
+ if defined ${*{$fqvar}{SCALAR}};
+ foreach $type (qw(ARRAY HASH CODE IO))
+ {
+ push (@{$namerefs{$var}}, *{$fqvar}{$type})
+ if defined *{$fqvar}{$type};
+ }
+ }
+ return \%namerefs;
+}
+
+# Remove the specified symbols from the namespace.
+# Default is to remove all.
+sub remove
+{
+ my $package = shift;
+ my (%namerefs, $var);
+ no strict 'refs';
+ @_ = keys %{$package . "::"} if !@_;
+ foreach $var (@_)
+ {
+ delete ${$package . "::"}{$var};
+ }
+}
+
+# Restore values to symbols specified in a hash as returned
+# by NameSpace::save.
+sub restore
+{
+ my ($package, $namerefs) = @_;
+ my ($var, $ref);
+ no strict 'refs';
+ foreach $var (keys %$namerefs)
+ {
+ my $fqvar = $package . "::" . $var;
+ foreach $ref (@{$namerefs->{$var}})
+ {
+ *{$fqvar} = $ref;
+ }
+ }
+}
+
+# Support for "building" scripts, importing and exporting variables.
+# With the exception of the top-level routine here (invoked from the
+# main package by cons), these are all invoked by user scripts.
+package script;
+
+use vars qw( $ARG $caller_dir_path %special_var );
+
+BEGIN
+{
+
+ # We can't Export or Import the following variables because Perl always
+ # treats them as part of the "main::" package (see perlvar(1)).
+ %special_var = map { $_ => 1 } qw(ENV INC ARGV ARGVOUT SIG
+ STDIN STDOUT STDERR);
+}
+
+# This is called from main to interpret/run the top-level Construct
+# file, passed in as the single argument.
+sub main::doscripts
+{
+ my ($script) = @_;
+ Build($script);
+
+ # Now set up the includes/excludes (after the Construct file is read).
+ $param::include = join ('|', @param::include);
+
+ # Save the original variable names from the script package.
+ # These will stay intact, but any other "script::" variables
+ # defined in a Conscript file will get saved, deleted,
+ # and (when necessary) restored.
+ my (%orig_script_var) = map { $_ => 1 } keys %script::;
+ $caller_dir_path = undef;
+ my $cwd = Cwd::cwd();
+ my (@scripts) = pop (@priv::scripts);
+ while ($priv::self = shift (@scripts))
+ {
+ my ($path) = $priv::self->{script}->rsrcpath;
+ if (-f $path)
+ {
+ $dir::cwd = $priv::self->{script}->{dir};
+
+ # Handle chdir to the Conscript file directory, if necessary.
+ my ($vol, $dir, $file);
+ if ($param::conscript_chdir)
+ {
+ ($vol, $dir, $file) =
+ File::Spec->splitpath(File::Spec->canonpath($path));
+ if ($vol ne '' || $dir ne '')
+ {
+ $caller_dir_path = File::Spec->catpath($vol, $dir, undef);
+ chdir($caller_dir_path)
+ || die "Could not chdir to $caller_dir_path: $!\n";
+ }
+ }
+ else
+ {
+ $file = $path;
+ }
+
+ # Actually process the Conscript file.
+ do $file;
+
+ # Save any variables defined by the Conscript file
+ # so we can restore them later, if needed;
+ # then delete them from the script:: namespace.
+ my (@del) = grep(!$orig_script_var{$_}, keys %script::);
+ if (@del)
+ {
+ $priv::self->{script}->{pkgvars} =
+ NameSpace::save('script', @del);
+ NameSpace::remove('script', @del);
+ }
+ if ($caller_dir_path)
+ {
+ chdir($cwd);
+ $caller_dir_path = undef;
+ }
+ if ($@)
+ {
+ chomp($@);
+ my $err = ($@ =~ /\n/ms) ? ":\n$@" : " ($@)";
+ print qq($0: error in file "$path"$err\n);
+ $run::errors++;
+ }
+ else
+ {
+
+ # Only process subsidiary scripts if no errors in parent.
+ unshift (@scripts, @priv::scripts);
+ }
+ undef @priv::scripts;
+ }
+ else
+ {
+ my $where = '';
+ my $cref = $priv::self->{script}->creator;
+ if (defined $cref)
+ {
+ my ($_foo, $script, $line, $sub) = @$cref;
+ $where = " ($sub in $script, line $line)";
+ }
+ warn qq(Ignoring missing script "$path"$where);
+ }
+ }
+ die ("$0: script errors encountered: construction aborted\n")
+ if $run::errors;
+}
+
+# Return caller info about the method being invoked.
+# This is everything from the Perl "caller" builtin function,
+# including which Construct/Conscript file, line number,
+# subroutine name, etc.
+sub caller_info
+{
+ my ($lev) = 1;
+ my (@frame);
+ do
+ {
+ @frame = caller ++$lev;
+ if (defined($frame[3]) && $frame[3] eq '(eval)')
+ {
+ @frame = caller --$lev;
+ if ($caller_dir_path)
+ {
+ $frame[1] = File::Spec->catfile($caller_dir_path, $frame[1]);
+ }
+ return @frame;
+ }
+ } while ($frame[3]);
+ return;
+}
+
+# Link a directory to another. This simply means set up the *source*
+# for the directory to be the other directory.
+sub Link
+{
+ dir::link(@_);
+}
+
+# Add directories to the repository search path for files.
+# Strip our current directory from the list so Repository
+# (or -R options) can be used from within the repository.
+sub Repository
+{
+ my ($my_dir) = Cwd::cwd();
+ my $dir;
+ foreach $dir (@_)
+ {
+
+ # The following more direct call isn't available in
+ # Cwd.pm until some time after 5.003...
+ # my($d) = Cwd::abs_path($dir);
+ chdir($dir);
+ my ($d) = Cwd::cwd();
+ chdir($my_dir);
+
+ #
+ next if !$d || !-d $d || $d eq $my_dir;
+
+ # We know we can get away with passing undef to lookupdir
+ # as the directory because $dir is an absolute path.
+ push (@param::rpath, dir::lookupdir(undef, $dir));
+ push @INC, $d;
+ }
+}
+
+# Return the list of Repository directories specified.
+sub Repository_List
+{
+ map($_->path, @param::rpath);
+}
+
+# Specify whether the .consign signature times in repository files are,
+# in fact, consistent with the times on the files themselves.
+sub Repository_Sig_Times_OK
+{
+ $param::rep_sig_times_ok = shift;
+}
+
+sub SourceSignature
+{
+ $param::sourcesig = [@_];
+}
+
+# Specify whether we should chdir to the containing directories
+# of Conscript files.
+sub Conscript_chdir
+{
+ $param::conscript_chdir = shift;
+}
+
+# Specify files/targets that must be present and built locally,
+# even if they exist already-built in a Repository.
+sub Local
+{
+ my (@files) = map($dir::cwd->lookupfile($_), @_);
+ map($_->local(1), @files);
+}
+
+# Export variables to any scripts invoked from this one.
+sub Export
+{
+ my (@illegal) = grep($special_var{$_}, @_);
+ if (@illegal)
+ {
+ die qq($0: cannot Export special Perl variables: @illegal\n);
+ }
+ @{$priv::self->{exports}} = grep(!defined $special_var{$_}, @_);
+}
+
+# Import variables from the export list of the caller
+# of the current script.
+sub Import
+{
+ my (@illegal) = grep($special_var{$_}, @_);
+ if (@illegal)
+ {
+ die qq($0: cannot Import special Perl variables: @illegal\n);
+ }
+ my ($parent) = $priv::self->{parent};
+ my ($imports) = $priv::self->{imports};
+ @{$priv::self->{exports}} = keys %$imports;
+ my ($var);
+ foreach $var (grep(!defined $special_var{$_}, @_))
+ {
+ if (!exists $imports->{$var})
+ {
+ my ($path) = $parent->{script}->path;
+ die qq($0: variable "$var" not exported by file "$path"\n);
+ }
+ if (!defined $imports->{$var})
+ {
+ my $path = $parent->{script}->path;
+ my $err =
+ "$0: variable \"$var\" exported but not "
+ . "defined by file \"$path\"\n";
+ die $err;
+ }
+ ${"script::$var"} = $imports->{$var};
+ }
+}
+
+# Build an inferior script. That is, arrange to read and execute
+# the specified script, passing to it any exported variables from
+# the current script.
+sub Build
+{
+ my (@files) = map($dir::cwd->lookupfile($_), @_);
+ my (%imports) = map { $_ => ${"script::$_"} } @{$priv::self->{exports}};
+ my $file;
+ for $file (@files)
+ {
+ next if $param::include && $file->path !~ /$param::include/o;
+ my ($self) = {
+ 'script' => $file,
+ 'parent' => $priv::self,
+ 'imports' => \%imports
+ };
+ bless $self; # may want to bless into class of parent in future
+ push (@priv::scripts, $self);
+ }
+}
+
+# Set up regexps dependencies to ignore. Should only be called once.
+sub Ignore
+{
+ die ("Ignore called more than once\n") if $param::ignore;
+ $param::ignore = join ("|", map("($_)", @_)) if @_;
+}
+
+# Specification of default targets.
+sub Default
+{
+ push (@param::default_targets, map($dir::cwd->lookup($_)->path, @_));
+}
+
+# Local Help. Should only be called once.
+sub Help
+{
+ if ($param::localhelp)
+ {
+ print "@_\n";
+ exit 2;
+ }
+}
+
+# For windows platforms which use unix tool sets, the msvc defaults may
+# not be useful. Also, in the future, other platforms (Mac?) may have the
+# same problem.
+sub RuleSet
+{
+ my $style = shift;
+ my @rulesets = sort keys %param::rulesets;
+ die "Unknown style for rules: $style.\n"
+ . "Supported rules are: ("
+ . join (" ", @rulesets) . ")"
+ unless eval(join ("||", map("\$style eq '$_'", @rulesets)));
+ return @param::base, @{$param::rulesets{$style}};
+}
+
+sub DefaultRules
+{
+ @param::defaults = ();
+ push @param::defaults, @_;
+}
+
+# Return the build name(s) of a file or file list.
+sub FilePath
+{
+ wantarray
+ ? map($dir::cwd->lookupfile($_)->path, @_)
+ : $dir::cwd->lookupfile($_[0])->path;
+}
+
+# Return the build name(s) of a directory or directory list.
+sub DirPath
+{
+ wantarray
+ ? map($dir::cwd->lookupdir($_)->path, @_)
+ : $dir::cwd->lookupdir($_[0])->path;
+}
+
+# Split the search path provided into components. Look each up
+# relative to the current directory.
+# The usual path separator problems abound; for now we'll use :
+sub SplitPath
+{
+ my ($dirs) = @_;
+ if (ref($dirs) ne "ARRAY")
+ {
+ $dirs = [split (/$main::PATH_SEPARATOR/o, $dirs)];
+ }
+ map { DirPath($_) } @$dirs;
+}
+
+# Return true if the supplied path is available as a source file
+# or is buildable (by rules seen to-date in the build).
+sub ConsPath
+{
+ my ($path) = @_;
+ my ($file) = $dir::cwd->lookup($path);
+ return $file->accessible;
+}
+
+# Return the source path of the supplied path.
+sub SourcePath
+{
+ wantarray
+ ? map($dir::cwd->lookupfile($_)->rsrcpath, @_)
+ : $dir::cwd->lookupfile($_[0])->rsrcpath;
+}
+
+# Search up the tree for the specified cache directory, starting with
+# the current directory. Returns undef if not found, 1 otherwise.
+# If the directory is found, then caching is enabled. The directory
+# must be readable and writable. If the argument "mixtargets" is provided,
+# then targets may be mixed in the cache (two targets may share the same
+# cache file--not recommended).
+sub UseCache($@)
+{
+ my ($dir, @args) = @_;
+
+ # NOTE: it's important to process arguments here regardless of whether
+ # the cache is disabled temporarily, since the mixtargets option affects
+ # the salt for derived signatures.
+ for (@args)
+ {
+ if ($_ eq "mixtargets")
+ {
+
+ # When mixtargets is enabled, we salt the target signatures.
+ # This is done purely to avoid a scenario whereby if
+ # mixtargets is turned on or off after doing builds, and
+ # if cache synchronization with -cs is used, then
+ # cache files may be shared in the cache itself (linked
+ # under more than one name in the cache). This is not bad,
+ # per se, but simply would mean that a cache cleaning algorithm
+ # that looked for a link count of 1 would never find those
+ # particular files; they would always appear to be in use.
+ $param::salt = 'M' . $param::salt;
+ $param::mixtargets = 1;
+ }
+ else
+ {
+ die qq($0: UseCache unrecognized option "$_"\n);
+ }
+ }
+ if ($param::cachedisable)
+ {
+ warn("Note: caching disabled by -cd flag\n");
+ return 1;
+ }
+ my ($depth) = 15;
+ while ($depth-- && !-d $dir)
+ {
+ $dir = File::Spec->catdir($dir::UPDIR, $dir);
+ }
+ if (-d $dir)
+ {
+ $param::cache = $dir;
+ return 1;
+ }
+ return undef;
+}
+
+# Salt the signature generator. The salt (a number of string) is added
+# into the signature of each derived file. Changing the salt will
+# force recompilation of all derived files.
+sub Salt($)
+{
+
+ # We append the value, so that UseCache and Salt may be used
+ # in either order without changing the signature calculation.
+ $param::salt .= $_[0];
+}
+
+# Mark files (or directories) to not be removed before building.
+sub Precious
+{
+ map($_->{precious} = 1, map($dir::cwd->lookup($_), @_));
+}
+
+# These methods are callable from Conscript files, via a cons
+# object. Procs beginning with _ are intended for internal use.
+package cons;
+
+use vars qw( %envcache );
+
+# This is passed the name of the base environment to instantiate.
+# Overrides to the base environment may also be passed in
+# as key/value pairs.
+sub new
+{
+ my ($package) = shift;
+ my ($env) = {@param::defaults, @_};
+ @{$env->{_envcopy}} = %$env; # Note: we never change PATH
+ $env->{_cwd} = $dir::cwd; # Save directory of environment for
+ bless $env, $package; # any deferred name interpretation.
+}
+
+# Clone an environment.
+# Note that the working directory will be the initial directory
+# of the original environment.
+sub clone
+{
+ my ($env) = shift;
+ my $clone = {@{$env->{_envcopy}}, @_};
+ @{$clone->{_envcopy}} = %$clone; # Note: we never change PATH
+ $clone->{_cwd} = $env->{_cwd};
+ bless $clone, ref $env;
+}
+
+# Create a flattened hash representing the environment.
+# It also contains a copy of the PATH, so that the path
+# may be modified if it is converted back to a hash.
+sub copy
+{
+ my ($env) = shift;
+ (@{$env->{_envcopy}}, 'ENV' => {%{$env->{ENV}}}, @_);
+}
+
+# Resolve which environment to actually use for a given
+# target. This is just used for simple overrides.
+sub _resolve
+{
+ return $_[0] if !$param::overrides;
+ my ($env, $tgt) = @_;
+ my ($path) = $tgt->path;
+ my $re;
+ for $re (@param::overrides)
+ {
+ next if $path !~ /$re/;
+
+ # Found one. Return a combination of the original environment
+ # and the override.
+ my ($ovr) = $param::overrides{$re};
+ return $envcache{$env, $re} if $envcache{$env, $re};
+ my ($newenv) = {@{$env->{_envcopy}}, @$ovr};
+ @{$newenv->{_envcopy}} = %$env;
+ $newenv->{_cwd} = $env->{_cwd};
+ return $envcache{$env, $re} = bless $newenv, ref $env;
+ }
+ return $env;
+}
+
+# Substitute construction environment variables into a string.
+# Internal function/method.
+sub _subst
+{
+ my ($env, $str) = @_;
+ if (!defined $str)
+ {
+ return undef;
+ }
+ elsif (ref($str) eq "ARRAY")
+ {
+ return [map($env->_subst($_), @$str)];
+ }
+ else
+ {
+
+ # % expansion. %% gets converted to % later, so expand any
+ # %keyword construction that doesn't have a % in front of it,
+ # modulo multiple %% pairs in between.
+ # In Perl 5.005 and later, we could actually do this in one regex
+ # using a conditional expression as follows,
+ # while ($str =~ s/($pre)\%(\{)?([_a-zA-Z]\w*)(?(2)\})/"$1".
+ # $env->{$3}/ge) {}
+ # The following two-step approach is backwards-compatible
+ # to (at least) Perl5.003.
+ my $pre = '^|[^\%](?:\%\%)*';
+ while (($str =~ s/($pre)\%([_a-zA-Z]\w*)/$1.($env->{$2}||'')/ge)
+ || ($str =~ s/($pre)\%\{([_a-zA-Z]\w*)\}/$1.($env->{$2}||'')/ge))
+ {
+ }
+ return $str;
+ }
+}
+
+sub AfterBuild
+{
+ my ($env) = shift;
+ my ($perl_eval_str) = pop (@_);
+ my $file;
+ for $file (map($dir::cwd->lookup($_), @_))
+ {
+ $file->{after_build_func} = $perl_eval_str;
+
+ }
+}
+
+sub Install
+{
+ my ($env) = shift;
+ my ($tgtdir) = $dir::cwd->lookupdir($env->_subst(shift));
+ my $file;
+ for $file (map($dir::cwd->lookupfile($env->_subst($_)), @_))
+ {
+ my ($tgt) = $tgtdir->lookupfile($file->{entry});
+ $tgt->bind(find build::install($env), $file);
+ }
+}
+
+sub InstallAs
+{
+ my $env = shift;
+ my $tgt = shift;
+ my $src = shift;
+ my @sources = ();
+ my @targets = ();
+
+ if (ref $tgt)
+ {
+ die "InstallAs: Source is a file and target is a list!\n"
+ if (!ref($src));
+ @sources = @$src;
+ @targets = @$tgt;
+ }
+ elsif (ref $src)
+ {
+ die "InstallAs: Target is a file and source is a list!\n";
+ }
+ else
+ {
+ push @sources, $src;
+ push @targets, $tgt;
+ }
+
+ if ($#sources != $#targets)
+ {
+ my $tn = $#targets + 1;
+ my $sn = $#sources + 1;
+ die "InstallAs: Source file list ($sn) and target file list ($tn) "
+ . "are inconsistent in length!\n";
+ }
+ else
+ {
+ foreach (0 .. $#sources)
+ {
+ my $tfile = $dir::cwd->lookupfile($env->_subst($targets[$_]));
+ my $sfile = $dir::cwd->lookupfile($env->_subst($sources[$_]));
+ $tfile->bind(find build::install($env), $sfile);
+ }
+ }
+}
+
+# Installation in a local build directory,
+# copying from the repository if it's already built there.
+# Functionally equivalent to:
+# Install $env $dir, $file;
+# Local "$dir/$file";
+sub Install_Local
+{
+ my ($env) = shift;
+ my ($tgtdir) = $dir::cwd->lookupdir($env->_subst(shift));
+ my $file;
+ for $file (map($dir::cwd->lookupfile($env->_subst($_)), @_))
+ {
+ my ($tgt) = $tgtdir->lookupfile($file->{entry});
+ $tgt->bind(find build::install($env), $file);
+ $tgt->local(1);
+ }
+}
+
+sub Objects
+{
+ my ($env) = shift;
+ map($dir::cwd->relpath($_), $env->_Objects(@_));
+}
+
+# Called with multiple source file references (or object files).
+# Returns corresponding object files references.
+sub _Objects
+{
+ my ($env) = shift;
+ my ($suffix) = $env->{SUFOBJ};
+ map($env->_Object($_, $_->{dir}->lookupfile($_->base_suf($suffix))),
+ map { ref $_ ? $_ : $dir::cwd->lookupfile($env->_subst($_)) }
+ grep(defined $_, @_));
+}
+
+# Called with an object and source reference. If no object reference
+# is supplied, then the object file is determined implicitly from the
+# source file's extension. Sets up the appropriate rules for creating
+# the object from the source. Returns the object reference.
+sub _Object
+{
+ my ($env, $src, $obj) = @_;
+ return $obj if $src eq $obj; # don't need to build self from self.
+ my ($objenv) = $env->_resolve($obj);
+ my ($suffix) = $src->suffix;
+
+ my ($builder) = $env->{SUFMAP}{$suffix};
+
+ if ($builder)
+ {
+ $obj->bind((find $builder($objenv)), $src);
+ }
+ else
+ {
+ die ("don't know how to construct ${\$obj->path} from "
+ . "${\$src->path}.\n");
+ }
+ $obj;
+}
+
+sub Program
+{
+ my ($env) = shift;
+ my ($tgt) =
+ $dir::cwd->lookupfile(
+ file::addsuffix($env->_subst(shift), $env->{SUFEXE}));
+ my ($progenv) = $env->_resolve($tgt);
+ $tgt->bind(find build::command::link($progenv, $progenv->{LINKCOM}),
+ $env->_Objects(@_));
+}
+
+sub Module
+{
+ my ($env) = shift;
+ my ($tgt) = $dir::cwd->lookupfile($env->_subst(shift));
+ my ($modenv) = $env->_resolve($tgt);
+ my ($com) = pop (@_);
+ $tgt->bind(find build::command::link($modenv, $com), $env->_Objects(@_));
+}
+
+sub LinkedModule
+{
+ my ($env) = shift;
+ my ($tgt) = $dir::cwd->lookupfile($env->_subst(shift));
+ my ($progenv) = $env->_resolve($tgt);
+ $tgt->bind(
+ find build::command::linkedmodule($progenv,
+ $progenv->{LINKMODULECOM}),
+ $env->_Objects(@_));
+}
+
+sub Library
+{
+ my ($env) = shift;
+ my ($lib) =
+ $dir::cwd->lookupfile(
+ file::addsuffix($env->_subst(shift), $env->{SUFLIB}));
+ my ($libenv) = $env->_resolve($lib);
+ $lib->bind(find build::command::library($libenv), $env->_Objects(@_));
+}
+
+# Simple derivation: you provide target, source(s), command.
+# Special variables substitute into the rule.
+# Target may be a reference, in which case it is taken
+# to be a multiple target (all targets built at once).
+sub Command
+{
+ my ($env) = shift;
+ my ($tgt) = $env->_subst(shift);
+ my ($builder) = find build::command::user($env, pop (@_), 'script');
+ my (@sources) = map($dir::cwd->lookupfile($env->_subst($_)), @_);
+ if (ref($tgt))
+ {
+
+ # A multi-target command.
+ my (@tgts) = map($dir::cwd->lookupfile($_), @$tgt);
+ die ("empty target list in multi-target command\n") if !@tgts;
+ $env = $env->_resolve($tgts[0]);
+ my ($multi) = build::multiple->new($builder, \@tgts);
+ for $tgt (@tgts)
+ {
+ $tgt->bind($multi, @sources);
+ }
+ }
+ else
+ {
+ $tgt = $dir::cwd->lookupfile($tgt);
+ $env = $env->_resolve($tgt);
+ $tgt->bind($builder, @sources);
+ }
+}
+
+sub Depends
+{
+ my ($env) = shift;
+ my ($tgt) = $env->_subst(shift);
+ my (@deps) = map($dir::cwd->lookup($env->_subst($_)), @_);
+ if (!ref($tgt))
+ {
+ $tgt = [$tgt];
+ }
+ my ($t);
+ foreach $t (map($dir::cwd->lookupfile($_), @$tgt))
+ {
+ push (@{$t->{dep}}, @deps);
+ }
+}
+
+# Setup a quick scanner for the specified input file, for the
+# associated environment. Any use of the input file will cause the
+# scanner to be invoked, once only. The scanner sees just one line at
+# a time of the file, and is expected to return a list of
+# dependencies.
+sub QuickScan
+{
+ my ($env, $code, $file, $path) = @_;
+ $dir::cwd->lookup($env->_subst($file))->{'srcscan', $env} =
+ find scan::quickscan($code, $env, $env->_subst($path));
+}
+
+# Generic builder module. Just a few default methods. Every derivable
+# file must have a builder object of some sort attached. Usually
+# builder objects are shared.
+package build;
+
+use vars qw( %builder );
+
+# Every builder must now have at least an associated environment,
+# so we can find its sigarray and calculate the proper signature.
+sub find
+{
+ my ($class, $env) = @_;
+ $builder{$env} || do
+ {
+ my $self = {env => $env};
+ $builder{$env} = bless $self, $class;
+ }
+}
+
+# Null signature for dynamic includes.
+sub includes { () }
+
+# Null signature for build script.
+sub scriptsig { () }
+
+# Not compatible with any other builder, by default.
+sub compatible { 0 }
+
+# Builder module for the Install command.
+package build::install;
+
+use vars qw( @ISA );
+
+BEGIN { @ISA = qw(build) }
+
+# Caching not supported for Install: generally install is trivial anyway,
+# and we don't want to clutter the cache.
+sub cachin { undef }
+sub cachout { }
+
+# Do the installation.
+sub action
+{
+ my ($self, $tgt) = @_;
+ my ($src) = $tgt->{sources}[0];
+ main::showcom("Install ${\$src->rpath} as ${\$tgt->path}")
+ if ($param::install && $param::quiet < 1);
+ return unless $param::build;
+ futil::install($src->rpath, $tgt);
+ return 1;
+}
+
+# Builder module for generic UNIX commands.
+package build::command;
+
+use vars qw( @ISA %com );
+
+BEGIN { @ISA = qw(build) }
+
+sub find
+{
+ my ($class, $env, $cmd, $package) = @_;
+ my ($act) = action::new($env, $cmd);
+ $package ||= '';
+ $com{$env, $act, $package} || do
+ {
+ my $self = {env => $env, act => $act, 'package' => $package};
+ $com{$env, $act, $package} = bless $self, $class;
+ }
+}
+
+# Default cache in function.
+sub cachin
+{
+ my ($self, $tgt, $sig) = @_;
+ if (cache::in($tgt, $sig))
+ {
+ if ($param::cachecom)
+ {
+ $self->{act}->show($self->{env}, $tgt);
+ }
+ else
+ {
+ printf("Retrieved %s from cache\n", $tgt->path)
+ if ($param::quiet < 1);
+ }
+ return 1;
+ }
+ return undef;
+}
+
+# Default cache out function.
+sub cachout
+{
+ my ($self, $tgt, $sig) = @_;
+ cache::out($tgt, $sig);
+}
+
+# Build the target using the previously specified commands.
+sub action
+{
+ my ($self, $tgt) = @_;
+ $self->{act}->execute($self->{env}, $tgt, $self->{'package'});
+}
+
+# Return script signature.
+sub scriptsig
+{
+ $_[0]->{act}->scriptsig;
+}
+
+# Create a linked module.
+package build::command::link;
+
+use vars qw( @ISA );
+
+BEGIN { @ISA = qw(build::command) }
+
+# Find an appropriate linker.
+sub find
+{
+ my ($class, $env, $command) = @_;
+ if (!exists $env->{_LDIRS})
+ {
+ my ($ldirs) = '';
+ my ($wd) = $env->{_cwd};
+ my ($pdirs) = $env->{LIBPATH};
+ if (!defined $pdirs)
+ {
+ $pdirs = [];
+ }
+ elsif (ref($pdirs) ne 'ARRAY')
+ {
+ $pdirs = [split (/$main::PATH_SEPARATOR/o, $pdirs)];
+ }
+ my ($dir, $dpath);
+ for $dir (map($wd->lookupdir($env->_subst($_)), @$pdirs))
+ {
+ $dpath = $dir->path;
+
+ # Add the (presumably local) directory to the -L flags
+ # if we're not using repositories, the directory exists,
+ # or it's Linked to a source directory (that is, it *will*
+ # exist by the time the link occurs).
+ $ldirs .= " " . $env->{LIBDIRPREFIX} . $dpath . $env->{LIBDIRSUFFIX}
+ if !@param::rpath || -d $dpath || $dir->is_linked;
+ next if File::Spec->file_name_is_absolute($dpath);
+ if (@param::rpath)
+ {
+ my $d;
+ if ($dpath eq $dir::CURDIR)
+ {
+ foreach $d (map($_->path, @param::rpath))
+ {
+ $ldirs .= " "
+ . $env->{LIBDIRPREFIX} . $d
+ . $env->{LIBDIRSUFFIX};
+ }
+ }
+ else
+ {
+ my ($rpath);
+ foreach $d (map($_->path, @param::rpath))
+ {
+ $rpath = File::Spec->catfile($d, $dpath);
+ $ldirs .= " "
+ . $env->{LIBDIRPREFIX} . $rpath
+ . $env->{LIBDIRSUFFIX}
+ if -d $rpath;
+ }
+ }
+ }
+ }
+ $env->{_LDIRS} = "%($ldirs%)";
+ }
+
+ # Introduce a new magic _LIBS symbol which allows to use the
+ # Unix-style -lNAME syntax for Win32 only. -lNAME will be replaced
+ # with %{PREFLIB}NAME%{SUFLIB}. <schwarze@isa.de> 1998-06-18
+
+ if ($main::_WIN32 && !exists $env->{_LIBS})
+ {
+ my $libs;
+ my $name;
+ for $name (split (' ', $env->_subst($env->{LIBS} || '')))
+ {
+ if ($name =~ /^-l(.*)/)
+ {
+ $name = "$env->{PREFLIB}$1$env->{SUFLIB}";
+ }
+ $libs .= ' ' . $name;
+ }
+ $env->{_LIBS} = $libs ? "%($libs%)" : '';
+ }
+ bless find build::command($env, $command);
+}
+
+# Called from file::build. Make sure any libraries needed by the
+# environment are built, and return the collected signatures
+# of the libraries in the path.
+sub includes
+{
+ return $_[0]->{'bsig'} if exists $_[0]->{'bsig'};
+ my ($self, $tgt) = @_;
+ my ($env) = $self->{env};
+ my ($ewd) = $env->{_cwd};
+ my $ldirs = $env->{LIBPATH};
+ if (!defined $ldirs)
+ {
+ $ldirs = [];
+ }
+ elsif (ref($ldirs) ne 'ARRAY')
+ {
+ $ldirs = [split (/$main::PATH_SEPARATOR/o, $ldirs)];
+ }
+ my @lpath = map($ewd->lookupdir($_), @$ldirs);
+ my (@sigs);
+ my (@names);
+
+ # Pass %LIBS symbol through %-substituition
+ # <schwarze@isa.de> 1998-06-18
+ @names = split (' ', $env->_subst($env->{LIBS} || ''));
+ my $name;
+ for $name (@names)
+ {
+ my ($lpath, @allnames);
+ if ($name =~ /^-l(.*)/)
+ {
+
+ # -l style names are looked up on LIBPATH, using all
+ # possible lib suffixes in the same search order the
+ # linker uses (according to SUFLIBS).
+ # Recognize new PREFLIB symbol, which should be 'lib' on
+ # Unix, and empty on Win32. TODO: What about shared
+ # library suffixes? <schwarze@isa.de> 1998-05-13
+ @allnames =
+ map("$env->{PREFLIB}$1$_", split (/:/, $env->{SUFLIBS}));
+ $lpath = \@lpath;
+ }
+ else
+ {
+ @allnames = ($name);
+
+ # On Win32, all library names are looked up in LIBPATH
+ # <schwarze@isa.de> 1998-05-13
+ if ($main::_WIN32)
+ {
+ $lpath = [$dir::top, @lpath];
+ }
+ else
+ {
+ $lpath = [$dir::top];
+ }
+ }
+ my $dir;
+ DIR: for $dir (@$lpath)
+ {
+ my $n;
+ for $n (@allnames)
+ {
+ my ($lib) = $dir->lookup_accessible($n);
+ if ($lib)
+ {
+ last DIR if $lib->ignore;
+ if ((build $lib) eq 'errors')
+ {
+ $tgt->{status} = 'errors';
+ return undef;
+ }
+ push (@sigs, 'sig'->signature($lib));
+ last DIR;
+ }
+ }
+ }
+ }
+ $self->{'bsig'} = 'sig'->collect(@sigs);
+}
+
+# Always compatible with other such builders, so the user
+# can define a single program or module from multiple places.
+sub compatible
+{
+ my ($self, $other) = @_;
+ ref($other) eq "build::command::link";
+}
+
+# Link a program.
+package build::command::linkedmodule;
+
+use vars qw( @ISA );
+
+BEGIN { @ISA = qw(build::command) }
+
+# Always compatible with other such builders, so the user
+# can define a single linked module from multiple places.
+sub compatible
+{
+ my ($self, $other) = @_;
+ ref($other) eq "build::command::linkedmodule";
+}
+
+# Builder for a C module
+package build::command::cc;
+
+use vars qw( @ISA );
+
+BEGIN { @ISA = qw(build::command) }
+
+sub find
+{
+ $_[1]->{_cc} || do
+ {
+ my ($class, $env) = @_;
+ my ($cpppath) = $env->_subst($env->{CPPPATH});
+ my ($cscanner) = find scan::cpp($env->{_cwd}, $cpppath);
+ $env->{_IFLAGS} = "%(" . $cscanner->iflags($env) . "%)";
+ my ($self) = find build::command($env, $env->{CCCOM});
+ $self->{scanner} = $cscanner;
+ bless $env->{_cc} = $self;
+ }
+}
+
+# Invoke the associated C scanner to get signature of included files.
+sub includes
+{
+ my ($self, $tgt) = @_;
+ $self->{scanner}->includes($tgt, $tgt->{sources}[0]);
+}
+
+# Builder for a C++ module
+package build::command::cxx;
+
+use vars qw( @ISA );
+
+BEGIN { @ISA = qw(build::command) }
+
+sub find
+{
+ $_[1]->{_cxx} || do
+ {
+ my ($class, $env) = @_;
+ my ($cpppath) = $env->_subst($env->{CPPPATH});
+ my ($cscanner) = find scan::cpp($env->{_cwd}, $cpppath);
+ $env->{_IFLAGS} = "%(" . $cscanner->iflags($env) . "%)";
+ my ($self) = find build::command($env, $env->{CXXCOM});
+ $self->{scanner} = $cscanner;
+ bless $env->{_cxx} = $self;
+ }
+}
+
+# Invoke the associated C scanner to get signature of included files.
+sub includes
+{
+ my ($self, $tgt) = @_;
+ $self->{scanner}->includes($tgt, $tgt->{sources}[0]);
+}
+
+# Builder for a user command (cons::Command). We assume that a user
+# command might be built and implement the appropriate dependencies on
+# the command itself (actually, just on the first word of the command
+# line).
+package build::command::user;
+
+use vars qw( @ISA );
+
+BEGIN { @ISA = qw(build::command) }
+
+sub includes
+{
+ my ($self, $tgt) = @_;
+ my ($sig) = '';
+
+ # Check for any quick scanners attached to source files.
+ my $dep;
+ for $dep (@{$tgt->{dep}}, @{$tgt->{sources}})
+ {
+ my ($scanner) = $dep->{'srcscan', $self->{env}};
+ if ($scanner)
+ {
+ $sig .= $scanner->includes($tgt, $dep);
+ }
+ }
+
+ # XXX Optimize this to not use ignored paths.
+ if (!exists $self->{_comsig})
+ {
+ my ($env) = $self->{env};
+ $self->{_comsig} = '';
+ my ($com, $dir);
+ com:
+ for $com ($self->{act}->commands)
+ {
+ my ($pdirs) = $env->{ENV}->{PATH};
+ if (!defined $pdirs)
+ {
+ $pdirs = [];
+ }
+ elsif (ref($pdirs) ne 'ARRAY')
+ {
+ $pdirs = [split (/$main::PATH_SEPARATOR/o, $pdirs)];
+ }
+ for $dir (map($dir::top->lookupdir($_), @$pdirs))
+ {
+ my ($prog) = $dir->lookup_accessible($com);
+ if ($prog)
+ { # XXX Not checking execute permission.
+ if ((build $prog) eq 'errors')
+ {
+ $tgt->{status} = 'errors';
+ return $sig;
+ }
+ next com if $prog->ignore;
+ $self->{_comsig} .= 'sig'->signature($prog);
+ next com;
+ }
+ }
+ }
+ }
+
+ return $self->{_comsig} . $sig;
+}
+
+# Builder for a library module (archive).
+# We assume that a user command might be built and implement the
+# appropriate dependencies on the command itself.
+package build::command::library;
+
+use vars qw( @ISA );
+
+BEGIN { @ISA = qw(build::command) }
+
+sub find
+{
+ my ($class, $env) = @_;
+ bless find build::command($env, $env->{ARCOM});
+}
+
+# Always compatible with other library builders, so the user
+# can define a single library from multiple places.
+sub compatible
+{
+ my ($self, $other) = @_;
+ ref($other) eq "build::command::library";
+}
+
+# A multi-target builder.
+# This allows multiple targets to be associated with a single build
+# script, without forcing all the code to be aware of multiple targets.
+package build::multiple;
+
+sub new
+{
+ my ($class, $builder, $tgts) = @_;
+ bless {'builder' => $builder, 'env' => $builder->{env}, 'tgts' => $tgts};
+}
+
+sub scriptsig
+{
+ my ($self, $tgt) = @_;
+ $self->{builder}->scriptsig($tgt);
+}
+
+sub includes
+{
+ my ($self, $tgt) = @_;
+ $self->{builder}->includes($tgt);
+}
+
+sub compatible
+{
+ my ($self, $tgt) = @_;
+ $self->{builder}->compatible($tgt);
+}
+
+sub cachin
+{
+ my ($self, $tgt, $sig) = @_;
+ $self->{builder}->cachin($tgt, $sig);
+}
+
+sub cachout
+{
+ my ($self, $tgt, $sig) = @_;
+ $self->{builder}->cachout($tgt, $sig);
+}
+
+sub action
+{
+ my ($self, $invoked_tgt) = @_;
+ return $self->{built} if exists $self->{built};
+
+ # Make sure all targets in the group are unlinked before building any.
+ my ($tgts) = $self->{tgts};
+ my $tgt;
+ for $tgt (@$tgts)
+ {
+ futil::mkdir($tgt->{dir});
+ unlink($tgt->path) if !$tgt->precious;
+ }
+
+ # Now do the action to build all the targets. For consistency
+ # we always call the action on the first target, just so that
+ # $> is deterministic.
+ if ($param::max_jobs <= 1)
+ { # pcons
+ $self->{built} = $self->{builder}->action($tgts->[0]);
+ }
+ else
+ {
+ {
+
+ # action now is non-blocking, so we must kludge blocking for this
+ # explicit call
+ local ($file::child_queue) = {parent => $tgts->[0]}; # pcons
+ $self->{built} = $self->{builder}->action($tgts->[0]); # pcons
+ &file::wait_on_all_children(); # pcons
+ }
+ }
+
+ # Now "build" all the other targets (except for the one
+ # we were called with). This guarantees that the signature
+ # of each target is updated appropriately. We force the
+ # targets to be built even if they have been previously
+ # considered and found to be OK; the only effect this
+ # has is to make sure that signature files are updated
+ # correctly.
+ for $tgt (@$tgts)
+ {
+ if ($tgt ne $invoked_tgt)
+ {
+ delete $tgt->{status};
+ 'sig'->invalidate($tgt);
+ build $tgt;
+ }
+ }
+
+ # Status of action.
+ $self->{built};
+}
+
+package action;
+
+sub new
+{
+ my ($env, $act) = @_;
+ if (ref($act) eq 'CODE')
+ {
+ return action::perl->new($act);
+ }
+ else
+ {
+ return action::command->new($env, $act);
+ }
+}
+
+package action::command;
+
+use vars qw( @ISA %cmd %_varopts $_varletters );
+
+BEGIN
+{
+ @ISA = $main::_WIN32 ? 'action::command::win32' : 'action::command::unix';
+
+ # Internal hash for processing variable options.
+ # f: return file part
+ # d: return directory part
+ # F: return file part, but strip any suffix
+ # b: return full path, but strip any suffix (a.k.a. return basename)
+ # s: return only the suffix (or an empty string, if no suffix is there)
+ # a: return the absolute path to the file
+ # S: return the absolute path to a Linked source file
+ %_varopts = (
+ 'f' => sub { return $_[0]->{entry}; },
+ 'd' => sub { return $_[0]->{dir}->path; },
+ 'F' => sub {
+ my $subst = $_[0]->{entry};
+ $subst =~ s/\.[^\.]+$//;
+ return $subst;
+ },
+ 'b' => sub {
+ my $subst = $_[0]->path;
+ $subst =~ s/\.[^\.]+$//;
+ return $subst;
+ },
+ 's' => sub {
+ my $subst = $_[0]->{entry};
+ $subst =~ m/(\.[^\.]+)$/;
+ return $1;
+ },
+ 'a' => sub {
+ my $path = $_[0]->path;
+ if (!File::Spec->file_name_is_absolute($path))
+ {
+ $path = File::Spec->catfile(Cwd::cwd(), $path);
+ }
+ return $path;
+ },
+ 'S' => sub {
+ my $path = $_[0]->srcpath;
+ if (!File::Spec->file_name_is_absolute($path))
+ {
+ my $cwd = File::Spec->canonpath(Cwd::cwd());
+ $path = File::Spec->catfile($cwd, $path);
+ }
+ return $path;
+ },
+ );
+
+ $_varletters = join ('', keys %_varopts);
+}
+
+# Internal routine for processing variable options.
+# Options are specified in hash in the BEGIN block above.
+# no option: return path to file (relative to top,
+# or absolute if it's outside)
+sub _variant
+{
+ my ($opt, $file) = @_;
+ $opt = '' if !defined $opt;
+ if (defined $_varopts{$opt})
+ {
+ return &{$_varopts{$opt}} ($file);
+ }
+ return $file->path;
+}
+
+sub new
+{
+ my ($class, $env, $cmd) = @_;
+ $cmd = $env->_subst($cmd);
+ $cmd{$env, $cmd} || do
+ {
+
+ # Remove unwanted bits from signature -- those bracketed by %( ... %)
+ my $sigs = $cmd;
+ my $sig = '';
+ if (ref($sigs) eq 'ARRAY')
+ {
+
+ # This is an array of commands..
+ my $f;
+ foreach $f (@$sigs)
+ {
+ $sig .= _strip($f);
+ }
+ }
+ else
+ {
+ $sig = _strip($sigs);
+ }
+ my $self = {cmd => $cmd, cmdsig => 'sig'->cmdsig($sig)};
+ $cmd{$env, $cmd} = bless $self, $class;
+ };
+}
+
+sub _strip
+{
+ my $sig = shift;
+ $sig =~ s/^\@\s*//mg;
+ while ($sig =~ s/%\(([^%]|%[^\(])*?%\)//g) { }
+ $sig;
+}
+
+sub scriptsig
+{
+ $_[0]->{cmdsig};
+}
+
+# Return an array of all the commands (first word on each line).
+sub commands
+{
+ my ($self) = @_;
+ my (@cmds) = ();
+ my $com;
+ my $cmd = $self->{'cmd'};
+ my @allcoms;
+
+ push @allcoms, ref $cmd ? @{$cmd} : split (/\n/, $cmd);
+
+ for $com (@allcoms)
+ {
+ $com =~ s/^\s*//;
+ $com =~ s/\s.*//;
+ next if !$com; # blank line
+ push @cmds, $com;
+ }
+ @cmds;
+}
+
+# For the signature of a basic command, we don't bother
+# including the command itself. This is not strictly correct,
+# and if we wanted to be rigorous, we might want to insist
+# that the command was checked for all the basic commands
+# like gcc, etc. For this reason we don't have an includes
+# method.
+
+# Call this to get the command line script: an array of
+# fully substituted commands.
+sub getcoms
+{
+ my ($self, $env, $tgt) = @_;
+ my (@coms);
+ my $com;
+ my @allcoms = ();
+ my $cmd = $self->{'cmd'};
+
+ push @allcoms, ref $cmd ? @{$cmd} : split (/\n/, $cmd);
+
+ for $com (@allcoms)
+ {
+ my (@src) = (undef, @{$tgt->{sources}});
+ my (@src1) = @src;
+
+ next if $com =~ /^\s*$/;
+
+ # NOTE: we used to have a more elegant s//.../e solution
+ # for the items below, but this caused a bus error...
+
+ # Remove %( and %) -- those are only used to bracket parts
+ # of the command that we don't depend on.
+ $com =~ s/%[()]//g;
+
+ # Deal with %n, n=1,9 and variants.
+ while ($com =~ /%([1-9])(:([$_varletters]?))?/o)
+ {
+ my ($match) = $&;
+ my ($src) = $src1[$1];
+ my ($subst) = _variant($3, $src1[$1]->rfile);
+ undef $src[$1];
+ $com =~ s/$match/$subst/;
+ }
+
+ # Deal with %0 aka %> and variants.
+ while ($com =~ /%[0>](:([$_varletters]?))?/o)
+ {
+ my ($match) = $&;
+ my ($subst) = _variant($2, $tgt);
+ $com =~ s/$match/$subst/;
+ }
+
+ # Deal with %< (all sources except %n's already used)
+ while ($com =~ /%<(:([$_varletters]?))?/o)
+ {
+ my ($match) = $&;
+ my @list = ();
+ foreach (@src)
+ {
+ push (@list, _variant($2, $_->rfile)) if $_;
+ }
+ my ($subst) = join (' ', @list);
+ $com =~ s/$match/$subst/;
+ }
+
+ # Deal with %[ %].
+ $com =~ s{%\[(.*?)%\]}{
+ my($func, @args) = grep { $_ ne '' } split(/\s+/, $1);
+ die("$0: \"$func\" is not defined.\n")
+ unless ($env->{$func});
+ &{$env->{$func}}(@args);
+ }gex;
+
+ # Convert left-over %% into %.
+ $com =~ s/%%/%/g;
+
+ # White space cleanup. XXX NO WAY FOR USER TO HAVE QUOTED SPACES
+ $com = join (' ', split (' ', $com));
+ next if $com =~ /^:/ && $com !~ /^:\S/;
+ push (@coms, $com);
+ }
+ @coms;
+}
+
+# Build the target using the previously specified commands.
+sub execute
+{
+ my ($self, $env, $tgt, $package) = @_;
+
+ if ($param::build)
+ {
+ futil::mkdir($tgt->{dir});
+ unlink($tgt->path) if !$tgt->precious;
+ }
+
+ # Set environment.
+ map(delete $ENV{$_}, keys %ENV);
+ %ENV = %{$env->{ENV}};
+
+ # Handle multi-line commands.
+
+ my @cmds = $self->getcoms($env, $tgt); # pcons
+ if ($param::max_jobs > 1)
+ { # pcons
+ if ($#cmds > 0)
+ {
+ for ($i = 0 ; $i < @cmds ; $i++)
+ { #pcons -kn
+ $cmds[$i] = "( " . $cmds[$i] . " )"; #pcons -kn
+ } #pcons -kn
+ @cmds = join (" && ", @cmds); # pcons
+ } # pcons
+ } # pcons
+
+ my $com; # pcons
+ for $com (@cmds)
+ { # pcons
+ if ($com !~ s/^\@\s*//)
+ {
+ main::showcom($com);
+ }
+ next if !$param::build;
+
+ if ($com =~ /^\[perl\]\s*/)
+ {
+ my $perlcmd = $';
+ my $status;
+ {
+
+ # Restore the script package variables that were defined
+ # in the Conscript file that defined this [perl] build,
+ # so the code executes with the expected variables.
+ # Then actually execute (eval) the [perl] command to build
+ # the target, followed by cleaning up the name space
+ # by deleting the package variables we just restored.
+ my ($pkgvars) = $tgt->{conscript}->{pkgvars};
+ NameSpace::restore($package, $pkgvars) if $pkgvars;
+ $status = eval "package $package; $perlcmd";
+ NameSpace::remove($package, keys %$pkgvars) if $pkgvars;
+ }
+ if (!defined($status))
+ {
+ warn "$0: *** Error during perl command eval: $@.\n";
+ return undef;
+ }
+ elsif ($status == 0)
+ {
+ warn "$0: *** Perl command returned $status "
+ . "(this indicates an error).\n";
+ return undef;
+ }
+ next;
+ }
+ if (!$self->do_command($com, $tgt->path, $tgt))
+ {
+ return undef;
+ }
+ }
+
+ # success.
+ return 1;
+}
+
+sub show
+{
+ my ($self, $env, $tgt) = @_;
+ my $com;
+ for $com ($self->getcoms($env, $tgt))
+ {
+ if ($com !~ /^\@\s*/)
+ {
+ main::showcom($com);
+ }
+ }
+}
+
+package action::command::unix;
+
+sub do_command
+{
+ my ($class, $com, $path) = @_; # cons
+ my ($class, $com, $path, $tgt) = @_; # pcons
+
+ if ($param::max_jobs > 1)
+ { # pcons
+ &file::wait_on_max_jobs(); # pcons
+ } # pcons
+ my ($pid) = fork();
+ die ("$0: unable to fork child process ($!)\n") if !defined $pid;
+ if (!$pid)
+ {
+
+ # This is the child. We eval the command to suppress -w
+ # warnings about not reaching the statements afterwards.
+ eval 'exec($com)';
+ $com =~ s/\s.*//;
+ die qq($0: failed to execute "$com" ($!). )
+ . qq(Is this an executable on path "$ENV{PATH}"?\n);
+ }
+ if ($param::max_jobs <= 1)
+ { # pcons
+ for (; ;)
+ {
+ do { } until wait() == $pid;
+ my ($b0, $b1) = ($? & 0xFF, $? >> 8);
+
+ # Don't actually see 0177 on stopped process; is this necessary?
+ next if $b0 == 0177; # process stopped; we can wait.
+ if ($b0)
+ {
+ my ($core, $sig) = ($b0 & 0200, $b0 & 0177);
+ my ($coremsg) = $core ? "; core dumped" : "";
+ $com =~ s/\s.*//;
+ my $err =
+ "$0: *** \[$path\] $com terminated by signal "
+ . "$sig$coremsg\n";
+ warn $err;
+ return undef;
+ }
+ if ($b1)
+ {
+ warn qq($0: *** [$path] Error $b1\n); # trying to be like make.
+ return undef;
+ }
+ last;
+ }
+ }
+ else
+ { # pcons
+ $file::child_queue->{$pid}->{com} = $com; # pcons
+ $file::child_queue->{$pid}->{tgt} = $tgt; # pcons
+
+ } # pcons
+
+ return 1;
+}
+
+package action::command::win32;
+
+sub do_command
+{
+ my ($class, $com, $path, $tgt) = @_;
+ system($com);
+ if ($?)
+ {
+ my ($b0, $b1) = ($? & 0xFF, $? >> 8);
+ my $err = $b1 || $?;
+ my $warn = qq($0: *** [$path] Error $err);
+ $warn .= " (executable not found in path?)" if $b1 == 0xFF;
+ warn "$warn\n";
+ return undef;
+ }
+ return 1;
+}
+
+package action::perl;
+
+# THIS IS AN EXPERIMENTAL PACKAGE. It's entirely possible that the
+# interface may change as this gets completed, so use at your own risk.
+#
+# There are (at least) two issues that need to be solved before blessing
+# this as a real, fully-supported feature:
+#
+# -- We need to calculate a signature value for a Perl code ref, in
+# order to rebuild the target if there's a change to the Perl code
+# used to generate it.
+#
+# This is not straightforward. A B::Deparse package exists that
+# decompiles a coderef into text. It's reportedly not completely
+# reliable for closures; it misses which variables are global, and
+# the values of private lexicals. Nevertheless, it'd probably
+# be perfect for our purposes, except that it wasn't added until
+# some time between Perl 5.00502 and 5.00554, and doesn't seem to
+# really work until Perl 5.6.0, so by relying on it, we'd lose
+# support for Perl versions back to 5.003*.
+#
+# -- Ideally, a code ref should be able to use something like
+# $env->_subst to fetch values from the construction environment
+# to modify its behavior without having to cut-and-paste code.
+# (Actually, since we pass the environment to the executed code
+# ref, there's no reason you can't do this with the code as it
+# stands today.) But this REALLY complicates the signature
+# calculation, because now the actual signature would depend not
+# just on the code contents, but on the construction variables (or
+# maybe just the environment).
+#
+# A potentially valid workaround would be to use the contents of the
+# Conscript file in which the code reference is defined as the code
+# ref's signature. This has the drawback of causing a recompilation of
+# the target file even in response to unrelated changes in the Conscript
+# file, but it would ensure correct builds without having to solve the
+# messy issues of generating a signature directly from a code ref.
+#
+# Nevertheless, this seemed a useful enough skeleton of a feature that
+# it made sense to release it in hopes that some practical experience
+# will encourage someone to figure out how to solve the signature
+# issues. Or maybe we'll discover these aren't big issues in practice
+# and end up blessing it as is.
+
+use vars qw( %code );
+
+sub new
+{
+ my ($class, $cref) = @_;
+ $code{$cref} || do
+ {
+ my $sig = '';
+
+ # Generating a code signature using B::Deparse doesn't really
+ # work for us until Perl 5.6.0. Here's the code in case
+ # someone wants to use it.
+ #use B::Deparse;
+ #my $deparse = B::Deparse->new();
+ #my $body = $deparse->coderef2text($cref);
+ #$sig = $body; # should be an MD5 sig
+ my ($self) = {cref => $cref, crefsig => $sig};
+ $code{$cref} = bless $self, $class;
+ }
+}
+
+sub scriptsig
+{
+ $_[0]->{crefsig};
+}
+
+sub execute
+{
+ my ($self, $env, $tgt) = @_;
+ if ($param::build)
+ {
+ futil::mkdir($tgt->{dir});
+ unlink($tgt->path) if !$tgt->precious;
+ my ($cref) = $self->{cref};
+ &$cref($env, $tgt->path, map($_->rpath, @{$tgt->{sources}}));
+ }
+}
+
+sub commands
+{
+ return ();
+}
+
+# Generic scanning module.
+package scan;
+
+# Returns the signature of files included by the specified files on
+# behalf of the associated target. Any errors in handling the included
+# files are propagated to the target on whose behalf this processing
+# is being done. Signatures are cached for each unique file/scanner
+# pair.
+sub includes
+{
+ my ($self, $tgt, @files) = @_;
+ my (%files, $file);
+ my ($inc) = $self->{includes} || ($self->{includes} = {});
+ while ($file = pop @files)
+ {
+ next if exists $files{$file};
+ if ($inc->{$file})
+ {
+ push (@files, @{$inc->{$file}});
+ $files{$file} = 'sig'->signature($file->rfile);
+ }
+ else
+ {
+ if ((build $file) eq 'errors')
+ {
+ $tgt->{status} = 'errors'; # tgt inherits build status
+ return ();
+ }
+ $files{$file} = 'sig'->signature($file->rfile);
+ my (@includes) = $self->scan($file);
+ $inc->{$file} = \@includes;
+ push (@files, @includes);
+ }
+ }
+ 'sig'->collect(sort values %files);
+}
+
+# A simple scanner. This is used by the QuickScanfunction, to setup
+# one-time target and environment-independent scanning for a source
+# file. Only used for commands run by the Command method.
+package scan::quickscan;
+
+use vars qw( @ISA %scanner );
+
+BEGIN { @ISA = qw(scan) }
+
+sub find
+{
+ my ($class, $code, $env, $pdirs) = @_;
+ if (!defined $pdirs)
+ {
+ $pdirs = [];
+ }
+ elsif (ref($pdirs) ne 'ARRAY')
+ {
+ $pdirs = [split (/$main::PATH_SEPARATOR/o, $pdirs)];
+ }
+ my (@path) = map { $dir::cwd->lookupdir($_) } @$pdirs;
+ my ($spath) = "@path";
+ $scanner{$code, $env, $spath} || do
+ {
+ my ($self) = {code => $code, env => $env, path => \@path};
+ $scanner{$code, $env, $spath} = bless $self;
+ }
+}
+
+# Scan the specified file for included file names.
+sub scan
+{
+ my ($self, $file) = @_;
+ my ($code) = $self->{code};
+ my (@includes);
+
+ # File should have been built by now. If not, we'll ignore it.
+ return () unless open(SCAN, $file->rpath);
+ while (<SCAN>)
+ {
+ push (@includes, grep($_ ne '', &$code));
+ }
+ close(SCAN);
+ my ($wd) = $file->{dir};
+ my (@files);
+ my $name;
+ for $name (@includes)
+ {
+ my $dir;
+ for $dir ($file->{dir}, @{$self->{path}})
+ {
+ my ($include) = $dir->lookup_accessible($name);
+ if ($include)
+ {
+ push (@files, $include) unless $include->ignore;
+ last;
+ }
+ }
+ }
+ @files;
+}
+
+# CPP (C preprocessor) scanning module
+package scan::cpp;
+
+use vars qw( @ISA %scanner );
+
+BEGIN { @ISA = qw(scan) }
+
+# For this constructor, provide the include path argument (colon
+# separated). Each path is taken relative to the provided directory.
+
+# Note: a particular scanning object is assumed to always return the
+# same result for the same input. This is why the search path is a
+# parameter to the constructor for a CPP scanning object. We go to
+# some pains to make sure that we return the same scanner object
+# for the same path: otherwise we will unecessarily scan files.
+sub find
+{
+ my ($class, $dir, $pdirs) = @_;
+ if (!defined $pdirs)
+ {
+ $pdirs = [];
+ }
+ elsif (ref($pdirs) ne 'ARRAY')
+ {
+ $pdirs = [split (/$main::PATH_SEPARATOR/o, $pdirs)];
+ }
+ my @path = map($dir->lookupdir($_), @$pdirs);
+ my ($spath) = "@path";
+ $scanner{$spath} || do
+ {
+ my ($self) = {'path' => \@path};
+ $scanner{$spath} = bless $self;
+ }
+}
+
+# Scan the specified file for include lines.
+sub scan
+{
+ my ($self, $file) = @_;
+ my ($angles, $quotes);
+
+ if (exists $file->{angles})
+ {
+ $angles = $file->{angles};
+ $quotes = $file->{quotes};
+ }
+ else
+ {
+ my (@anglenames, @quotenames);
+ return () unless open(SCAN, $file->rpath);
+ while (<SCAN>)
+ {
+ next unless /^\s*#/;
+ if (/^\s*#\s*include\s*([<"])(.*?)[>"]/)
+ {
+ if ($1 eq "<")
+ {
+ push (@anglenames, $2);
+ }
+ else
+ {
+ push (@quotenames, $2);
+ }
+ }
+ }
+ close(SCAN);
+ $angles = $file->{angles} = \@anglenames;
+ $quotes = $file->{quotes} = \@quotenames;
+ }
+
+ my (@shortpath) = @{$self->{path}}; # path for <> style includes
+ my (@longpath) = ($file->{dir}, @shortpath); # path for "" style includes
+
+ my (@includes);
+
+ my $name;
+ for $name (@$angles)
+ {
+ my $dir;
+ for $dir (@shortpath)
+ {
+ my ($include) = $dir->lookup_accessible($name);
+ if ($include)
+ {
+ push (@includes, $include) unless $include->ignore;
+ last;
+ }
+ }
+ }
+
+ for $name (@$quotes)
+ {
+ my $dir;
+ for $dir (@longpath)
+ {
+ my ($include) = $dir->lookup_accessible($name);
+ if ($include)
+ {
+ push (@includes, $include) unless $include->ignore;
+ last;
+ }
+ }
+ }
+
+ return @includes;
+}
+
+# Return the include flags that would be used for a C Compile.
+sub iflags
+{
+ my ($self, $env) = @_;
+ my ($iflags) = '';
+ my ($dir, $dpath);
+ for $dir (@{$self->{path}})
+ {
+ $dpath = $dir->path;
+
+ # Add the (presumably local) directory to the -I flags
+ # if we're not using repositories, the directory exists,
+ # or it's Linked to a source directory (that is, it *will*
+ # exist by the time the compilation occurs).
+ $iflags .= " " . $env->{INCDIRPREFIX} . $dpath . $env->{INCDIRSUFFIX}
+ if !@param::rpath || -d $dpath || $dir->is_linked;
+ next if File::Spec->file_name_is_absolute($dpath);
+ if (@param::rpath)
+ {
+ my $d;
+ if ($dpath eq $dir::CURDIR)
+ {
+ foreach $d (map($_->path, @param::rpath))
+ {
+ $iflags .=
+ " " . $env->{INCDIRPREFIX} . $d . $env->{INCDIRSUFFIX};
+ }
+ }
+ else
+ {
+ my ($rpath);
+ foreach $d (map($_->path, @param::rpath))
+ {
+ $rpath = File::Spec->catfile($d, $dpath);
+ $iflags .=
+ " " . $env->{INCDIRPREFIX} . $rpath . $env->{INCDIRSUFFIX}
+ if -d $rpath;
+ }
+ }
+ }
+ }
+ $iflags;
+}
+
+package File::Spec;
+
+use vars qw( $_SEP $_MATCH_SEP $_MATCH_VOL );
+
+# Cons is migrating to using File::Spec for portable path name
+# manipulation. This is the right long-term direction, but there are
+# some problems with making the transition:
+#
+# For multi-volume support, we need to use newer interfaces
+# (splitpath, catpath, splitdir) that are only available in
+# File::Spec 0.8.
+#
+# File::Spec 0.8 doesn't work with Perl 5.00[34] due to
+# regular expression incompatibilities (use of \z).
+#
+# Forcing people to use a new version of a module is painful
+# because (in the workplace) their administrators aren't
+# always going to agree to install it everywhere.
+#
+# As a middle ground, we provide our own versions of all the File::Spec
+# methods we use, supporting both UNIX and Win32. Some of these methods
+# are home brew, some are cut-and-pasted from the real File::Spec methods.
+# This way, we're not reinventing the whole wheel, at least.
+#
+# We can (and should) get rid of this class whenever 5.00[34] and
+# versions of File::Spec prior to 0.9 (?) have faded sufficiently.
+# We also may need to revisit whenever someone first wants to use
+# Cons on some platform other than UNIX or Win32.
+
+BEGIN
+{
+ if ($main::_WIN32)
+ {
+ $_SEP = '\\';
+ $_MATCH_SEP = "[\Q/$_SEP\E]";
+ $_MATCH_VOL = "([a-z]:)?$_MATCH_SEP";
+ }
+ else
+ {
+ $_SEP = '/';
+ $_MATCH_SEP = "\Q$_SEP\E";
+ $_MATCH_VOL = $_MATCH_SEP;
+ }
+}
+
+sub canonpath
+{
+ my ($self, $path) = @_;
+ if ($main::_WIN32)
+ {
+ $path =~ s/^([a-z]:)/\u$1/s;
+ $path =~ s|/|\\|g;
+ $path =~ s|([^\\])\\+|$1\\|g; # xx////xx -> xx/xx
+ $path =~ s|(\\\.)+\\|\\|g; # xx/././xx -> xx/xx
+ $path =~ s|^(\.\\)+||s unless $path eq ".\\"; # ./xx -> xx
+ $path =~ s|\\$|| unless $path =~ m#^([A-Z]:)?\\$#s; # xx/ -> xx
+ }
+ else
+ {
+ $path =~ s|/+|/|g unless ($^O eq 'cygwin'); # xx////xx -> xx/xx
+ $path =~ s|(/\.)+/|/|g; # xx/././xx -> xx/xx
+ $path =~ s|^(\./)+||s unless $path eq "./"; # ./xx -> xx
+ $path =~ s|^/(\.\./)+|/|s; # /../../xx -> xx
+ $path =~ s|/$|| unless $path eq "/"; # xx/ -> xx
+ }
+ return $path;
+}
+
+sub catdir
+{
+ my $self = shift;
+ my @args = @_;
+ foreach (@args)
+ {
+
+ # append a slash to each argument unless it has one there
+ $_ .= $_SEP if $_ eq '' || substr($_, -1) ne $_SEP;
+ }
+ return $self->canonpath(join ('', @args));
+}
+
+sub catfile
+{
+ my $self = shift;
+ my $file = pop @_;
+ return $file unless @_;
+ my $dir = $self->catdir(@_);
+ $dir .= $_SEP unless substr($dir, -1) eq $_SEP;
+ $file = '' if !defined($file);
+ return $dir . $file;
+}
+
+sub catpath
+{
+ my $path = $_[1] . $_[0]->catfile(@_[2 .. $#_]);
+ $path =~ s/(.)$_MATCH_SEP*$/$1/;
+ $path;
+}
+
+sub curdir
+{
+ '.';
+}
+
+sub file_name_is_absolute
+{
+ my ($self, $file) = @_;
+ return scalar($file =~ m{^$_MATCH_VOL}is);
+}
+
+sub splitdir
+{
+ my @dirs = split (/$_MATCH_SEP/, $_[1], -1);
+ push (@dirs, '') if $dirs[$#dirs];
+ @dirs;
+}
+
+sub splitpath
+{
+ my ($self, $path) = @_;
+ my $vol = '';
+ my $sep = $_SEP;
+ if ($main::_WIN32)
+ {
+ if ($path =~ s#^([A-Za-z]:|(?:\\\\|//)[^\\/]+[\\/][^\\/]+)([\\/])#$2#)
+ {
+ $vol = $1;
+ $sep = $2;
+ }
+ }
+ my (@path) = split (/$_MATCH_SEP/, $path, -1);
+ my $file = pop @path;
+ my $dirs = join ($sep, @path, '');
+ return ($vol, $dirs, $file);
+}
+
+sub updir
+{
+ '..';
+}
+
+sub case_tolerant
+{
+ return $main::_WIN32;
+}
+
+# Directory and file handling. Files/dirs are represented by objects.
+# Other packages are welcome to add component-specific attributes.
+package dir;
+
+use vars qw( $SEPARATOR $MATCH_SEPARATOR $CURDIR $UPDIR
+ $cwd_vol %root $top $cwd );
+
+BEGIN
+{
+
+ # A portable way of determing our directory separator.
+ $SEPARATOR = File::Spec->catdir('', '');
+
+ # A fast-path regular expression to match a directory separator
+ # anywhere in a path name.
+ if ($SEPARATOR eq '/')
+ {
+ $MATCH_SEPARATOR = "\Q$SEPARATOR\E";
+ }
+ else
+ {
+ $MATCH_SEPARATOR = "[\Q/$SEPARATOR\E]";
+ }
+
+ # Cache these values so we don't have to make a method call
+ # every time we need them.
+ $CURDIR = File::Spec->curdir; # '.' on UNIX
+ $UPDIR = File::Spec->updir; # '..' on UNIX
+ #
+ $cwd_vol = '';
+}
+
+# Annotate a node (file or directory) with info about the
+# method that created it.
+sub creator
+{
+ my ($self, @frame) = @_;
+ $self->{'creator'} = \@frame if @frame;
+ $self->{'creator'};
+}
+
+# Handle a file|dir type exception. We only die if we find we were
+# invoked by something in a Conscript/Construct file, because
+# dependencies created directly by Cons' analysis shouldn't cause
+# an error.
+sub _type_exception
+{
+ my ($e) = @_;
+ my ($line, $sub);
+ (undef, undef, $line, $sub) = script::caller_info;
+ if (defined $line)
+ {
+ my $err =
+ "\"${\$e->path}\" already in use as a "
+ . ref($e)
+ . " before $sub on line $line";
+ if ($e->{'creator'})
+ {
+ my $script;
+ (undef, $script, $line, $sub) = @{$e->{'creator'}};
+ $err =
+ "\t" . $err . ",\n\t\tdefined by $sub in $script, line $line";
+ }
+ $err .= "\n";
+ die $err;
+ }
+}
+
+# This wraps up all the common File::Spec logic that we use for parsing
+# directory separators in a path and turning it into individual
+# subdirectories that we must create, as well as creation of root
+# nodes for any new file system volumes we find. File::Spec doesn't have
+# intuitively obvious interfaces, so this is heavily commented.
+#
+# Note: This is NOT an object or class method;
+# it's just a utility subroutine.
+sub _parse_path
+{
+ my ($dir, $path) = @_;
+
+ # Convert all slashes to the native directory separator.
+ # This allows Construct files to always be written with good
+ # old POSIX path names, regardless of what we're running on.
+ $path = File::Spec->canonpath($path);
+
+ # File::Spec doesn't understand the Cons convention of
+ # an initial '#' for top-relative files. Strip it.
+ my ($toprel) = $path =~ s/^#//;
+
+ # Let File::Spec do the heavy lifting of parsing the path name.
+ my ($vol, $directories, $entry) = File::Spec->splitpath($path);
+ my @dirs = File::Spec->splitdir($directories);
+
+ # If there was a file entry on the end of the path, then the
+ # last @dirs element is '' and we don't need it. If there
+ # wasn't a file entry on the end (File::Spec->splitpath() knew
+ # the last component was a directory), then the last @dirs
+ # element becomes the entry we want to look up.
+ my ($e) = pop @dirs;
+ $entry = $e if $entry eq '';
+
+ if (File::Spec->file_name_is_absolute($path))
+ {
+
+ # An absolute path name. If no volume was supplied,
+ # use the volume of our current directory.
+ $vol = $cwd_vol if $vol eq '';
+ $vol = uc($vol) if File::Spec->case_tolerant;
+ if (!defined $root{$vol})
+ {
+
+ # This is our first time looking up a path name
+ # on this volume, so create a root node for it.
+ # (On UNIX systems, $vol is always '', so '/'
+ # always maps to the $root{''} node.)
+ $root{$vol} = {
+ path => $vol . $SEPARATOR,
+ prefix => $vol . $SEPARATOR,
+ srcpath => $vol . $SEPARATOR,
+ 'exists' => 1
+ };
+ $root{$vol}->{'srcdir'} = $root{$vol};
+ bless $root{$vol};
+ }
+
+ # We're at the top, so strip the blank entry from the front of
+ # the @dirs array since the initial '/' it represents will now
+ # be supplied by the root node we return.
+ shift @dirs;
+ $dir = $root{$vol};
+ }
+ elsif ($toprel)
+ {
+ $dir = $dir::top;
+ }
+ ($dir, \@dirs, $entry);
+}
+
+# Common subroutine for creating directory nodes.
+sub _create_dirs
+{
+ my ($dir, @dirs) = @_;
+ my $e;
+ foreach $e (@dirs)
+ {
+ my $d = $dir->{member}->{$e};
+ if (!defined $d)
+ {
+ bless $d = {'entry' => $e, 'dir' => $dir,}, 'dir';
+ $d->creator(script::caller_info);
+ $d->{member}->{$dir::CURDIR} = $d;
+ $d->{member}->{$dir::UPDIR} = $dir;
+ $dir->{member}->{$e} = $d;
+ }
+ elsif (ref $d eq 'entry')
+ {
+ bless $d, 'dir';
+ $d->{member}->{$dir::CURDIR} = $d;
+ $d->{member}->{$dir::UPDIR} = $dir;
+ }
+ elsif (ref $d eq 'file')
+ {
+
+ # This clause is to supply backwards compatibility,
+ # with a warning, for anyone that's used FilePath
+ # to refer to a directory. After people have using
+ # 1.8 have had time to adjust (sometime in version
+ # 1.9 or later), we should remove this entire clause.
+ my ($script, $line, $sub);
+ (undef, $script, $line, $sub) = @{$d->{'creator'}};
+ if ($sub eq 'script::FilePath')
+ {
+ print STDERR
+ "$0: Warning: $sub used to refer to a directory\n"
+ . "\tat line $line of $script. Use DirPath instead.\n";
+ bless $d, 'dir';
+ }
+ else
+ {
+ _type_exception($d);
+ }
+ }
+ elsif (ref $d ne 'dir')
+ {
+ _type_exception($d);
+ }
+ $dir = $d;
+ }
+ $dir;
+}
+
+# Look up an entry in a directory. This method is for when we don't
+# care whether a file or directory is returned, so if the entry already
+# exists, it will simply be returned. If not, we create it as a
+# generic "entry" which can be later turned into a file or directory
+# by a more-specific lookup.
+#
+# The file entry may be specified as relative, absolute (starts with /),
+# or top-relative (starts with #).
+sub lookup
+{
+ my ($dir, $entry) = @_;
+
+ if ($entry !~ m#$MATCH_SEPARATOR#o)
+ {
+
+ # Fast path: simple entry name in a known directory.
+ if ($entry =~ s/^#//)
+ {
+
+ # Top-relative names begin with #.
+ $dir = $dir::top;
+ }
+ elsif ($entry =~ s/^!//)
+ {
+ $dir = $dir::cwd->srcdir;
+ }
+ }
+ else
+ {
+ my $dirsref;
+ ($dir, $dirsref, $entry) = _parse_path($dir, $entry);
+ $dir = _create_dirs($dir, @$dirsref) if @$dirsref;
+ return if !defined $dir;
+ return $dir if $entry eq '';
+ }
+
+ my $e = $dir->{member}->{$entry};
+ if (!defined $e)
+ {
+ bless $e = {'entry' => $entry, 'dir' => $dir,}, 'entry';
+ $e->creator(script::caller_info);
+ $dir->{member}->{$entry} = $e;
+ }
+
+ $e;
+}
+
+# Look up a file entry in a directory.
+#
+# The file entry may be specified as relative, absolute (starts with /),
+# or top-relative (starts with #).
+sub lookupfile
+{
+ my ($dir, $entry) = @_;
+
+ if ($entry !~ m#$MATCH_SEPARATOR#o)
+ {
+
+ # Fast path: simple entry name in a known directory.
+ if ($entry =~ s/^#//)
+ {
+
+ # Top-relative names begin with #.
+ $dir = $dir::top;
+ }
+ elsif ($entry =~ s/^!//)
+ {
+ $dir = $dir::cwd->srcdir;
+ }
+ }
+ else
+ {
+ my $dirsref;
+ ($dir, $dirsref, $entry) = _parse_path($dir, $entry);
+ $dir = _create_dirs($dir, @$dirsref) if @$dirsref;
+ return undef if $entry eq '';
+ }
+
+ my $f = $dir->{member}->{$entry};
+ if (!defined $f)
+ {
+ bless $f = {'entry' => $entry, 'dir' => $dir,}, 'file';
+ $f->creator(script::caller_info);
+ $dir->{member}->{$entry} = $f;
+ }
+ elsif (ref $f eq 'entry')
+ {
+ bless $f, 'file';
+ }
+ elsif (ref $f ne 'file')
+ {
+ _type_exception($f);
+ }
+
+ $f;
+}
+
+# Look up a (sub-)directory entry in a directory.
+#
+# The (sub-)directory entry may be specified as relative, absolute
+# (starts with /), or top-relative (starts with #).
+sub lookupdir
+{
+ my ($dir, $entry) = @_;
+
+ my $dirsref;
+ if ($entry !~ m#$MATCH_SEPARATOR#o)
+ {
+
+ # Fast path: simple entry name in a known directory.
+ if ($entry =~ s/^#//)
+ {
+
+ # Top-relative names begin with #.
+ $dir = $dir::top;
+ }
+ elsif ($entry =~ s/^!//)
+ {
+ $dir = $dir::cwd->srcdir;
+ }
+ }
+ else
+ {
+ ($dir, $dirsref, $entry) = _parse_path($dir, $entry);
+ }
+ push (@$dirsref, $entry) if $entry ne '';
+ _create_dirs($dir, @$dirsref);
+}
+
+# Look up a file entry and return it if it's accessible.
+sub lookup_accessible
+{
+ my $file = $_[0]->lookupfile($_[1]);
+ return ($file && $file->accessible) ? $file : undef;
+}
+
+# Return the parent directory without doing a lookupdir,
+# which would create a parent if it doesn't already exist.
+# A return value of undef (! $dir->up) indicates a root directory.
+sub up
+{
+ $_[0]->{member}->{$dir::UPDIR};
+}
+
+# Return whether this is an entry somewhere underneath the
+# specified directory.
+sub is_under
+{
+ my $dir = $_[0];
+ while ($dir)
+ {
+ return 1 if $_[1] == $dir;
+ $dir = $dir->up;
+ }
+ return undef;
+}
+
+# Return the relative path from the calling directory ($_[1])
+# to the object. If the object is not under the directory, then
+# we return it as a top-relative or absolute path name.
+sub relpath
+{
+ my ($dir, $obj) = @_;
+ my @dirs;
+ my $o = $obj;
+ while ($o)
+ {
+ if ($dir == $o)
+ {
+ if (@dirs < 2)
+ {
+ return $dirs[0] || '';
+ }
+ else
+ {
+ return File::Spec->catdir(@dirs);
+ }
+ }
+ unshift (@dirs, $o->{entry});
+ $o = $o->up;
+ }
+
+ # The object was not underneath the specified directory.
+ # Use the node's cached path, which is either top-relative
+ # (in which case we append '#' to the beginning) or
+ # absolute.
+ my $p = $obj->path;
+ $p = '#' . $p if !File::Spec->file_name_is_absolute($p);
+ return $p;
+}
+
+# Return the path of the directory (file paths implemented
+# separately, below).
+sub path
+{
+ $_[0]->{path} || ($_[0]->{path} = $_[0]->{dir}->prefix . $_[0]->{entry});
+}
+
+# Return the pathname as a prefix to be concatenated with an entry.
+sub prefix
+{
+ return $_[0]->{prefix} if exists $_[0]->{prefix};
+ $_[0]->{prefix} = $_[0]->path . $SEPARATOR;
+}
+
+# Return the related source path prefix.
+sub srcprefix
+{
+ return $_[0]->{srcprefix} if exists $_[0]->{srcprefix};
+ my ($srcdir) = $_[0]->srcdir;
+ $srcdir->{srcprefix} =
+ $srcdir eq $_[0] ? $srcdir->prefix : $srcdir->srcprefix;
+}
+
+# Return the related source directory.
+sub srcdir
+{
+ $_[0]->{'srcdir'}
+ || ($_[0]->{'srcdir'} = $_[0]->{dir}->srcdir->lookupdir($_[0]->{entry}));
+}
+
+# Return if the directory is linked to a separate source directory.
+sub is_linked
+{
+ return $_[0]->{is_linked} if defined $_[0]->{is_linked};
+ $_[0]->{is_linked} = $_[0]->path ne $_[0]->srcdir->path;
+}
+
+sub link
+{
+ my (@paths) = @_;
+ my ($srcdir) = $dir::cwd->lookupdir(pop @paths)->srcdir;
+ map($dir::cwd->lookupdir($_)->{'srcdir'} = $srcdir, @paths);
+
+ # make a reverse lookup for the link.
+ $srcdir->{links} = [] if !$srcdir->{links};
+ push @{$srcdir->{links}}, @paths;
+}
+
+use vars qw( @tail ); # TODO: Why global ????
+
+sub linked_targets
+{
+ my $tgt = shift;
+ my @targets = ();
+ my $dir;
+ if (ref $tgt eq 'dir')
+ {
+ $dir = $tgt;
+ }
+ else
+ {
+ push @tail, $tgt;
+ $dir = $tgt->{dir};
+ }
+ while ($dir)
+ {
+ if (defined $dir->{links} && @{$dir->{links}})
+ {
+ push @targets, map(File::Spec->catdir($_, @tail), @{$dir->{links}});
+
+ #print STDERR "Found Link: ${\$dir->path} -> @{\$dir->{links}}\n";
+ }
+ unshift @tail, $dir->{entry};
+ $dir = $dir->up;
+ }
+
+ return map($dir::top->lookupdir($_), @targets);
+}
+
+sub accessible
+{
+ my $path = $_[0]->path;
+ my $err =
+ "$0: you have attempted to use path \"$path\" both as a file "
+ . "and as a directory!\n";
+ die $err;
+}
+
+sub init
+{
+ my $path = Cwd::cwd();
+
+ # We know we can get away with passing undef to lookupdir
+ # as the directory because $dir is an absolute path.
+ $top = lookupdir(undef, $path);
+ $top->{'path'} = $top->{srcpath} = $dir::CURDIR;
+ $top->{'prefix'} = '';
+ $top->{'srcdir'} = $top;
+
+ $cwd = $top;
+
+ ($cwd_vol, undef, undef) = File::Spec->splitpath($path);
+ $cwd_vol = '' if !defined $cwd_vol;
+ $cwd_vol = uc($cwd_vol) if File::Spec->case_tolerant;
+}
+
+package file;
+
+use vars qw( @ISA $level );
+
+BEGIN { @ISA = qw(dir); $level = 0 }
+
+# Return the pathname of the file.
+# Define this separately from dir::path because we don't want to
+# cache all file pathnames (just directory pathnames).
+sub path
+{
+ $_[0]->{dir}->prefix . $_[0]->{entry};
+}
+
+# Return the related source file path.
+sub srcpath
+{
+ $_[0]->{dir}->srcprefix . $_[0]->{entry};
+}
+
+# Return if the file is (should be) linked to a separate source file.
+sub is_linked
+{
+ $_[0]->{dir}->is_linked;
+}
+
+# Repository file search. If the local file exists, that wins.
+# Otherwise, return the first existing same-named file under a
+# Repository directory. If there isn't anything with the same name
+# under a Repository directory, return the local file name anyway
+# so that some higher layer can try to construct it.
+sub rfile
+{
+ return $_[0]->{rfile} if exists $_[0]->{rfile};
+ my ($self) = @_;
+ my ($rfile) = $self;
+ if (@param::rpath)
+ {
+ my ($path) = $self->path;
+ if (!File::Spec->file_name_is_absolute($path) && !-f $path)
+ {
+ my ($dir);
+ foreach $dir (@param::rpath)
+ {
+ my ($t) = $dir->prefix . $path;
+ if (-f $t)
+ {
+ $rfile = $_[0]->lookupfile($t);
+ $rfile->{'lfile'} = $self;
+ last;
+ }
+ }
+ }
+ }
+ $self->{rfile} = $rfile;
+}
+
+# Returns the local file for a repository file;
+# returns self if it's already a local file.
+sub lfile
+{
+ $_[0]->{'lfile'} || $_[0];
+}
+
+# returns the "precious" status of this file.
+sub precious
+{
+ return $_[0]->{precious};
+}
+
+# "Erase" reference to a Repository file,
+# making this a completely local file object
+# by pointing it back to itself.
+sub no_rfile
+{
+ $_[0]->{'rfile'} = $_[0];
+}
+
+# Return a path to the first existing file under a Repository directory,
+# implicitly returning the current file's path if there isn't a
+# same-named file under a Repository directory.
+sub rpath
+{
+ $_[0]->{rpath} || ($_[0]->{rpath} = $_[0]->rfile->path);
+}
+
+# Return a path to the first linked srcpath file under a Repositoy
+# directory, implicitly returning the current file's srcpath if there
+# isn't a same-named file under a Repository directory.
+sub rsrcpath
+{
+ return $_[0]->{rsrcpath} if exists $_[0]->{rsrcpath};
+ my ($self) = @_;
+ my ($path) = $self->{rsrcpath} = $self->srcpath;
+ if (@param::rpath && !File::Spec->file_name_is_absolute($path) && !-f $path)
+ {
+ my ($dir);
+ foreach $dir (@param::rpath)
+ {
+ my ($t) = $dir->prefix . $path;
+ if (-f $t)
+ {
+ $self->{rsrcpath} = $t;
+ last;
+ }
+ }
+ }
+ $self->{rsrcpath};
+}
+
+# Return if a same-named file source file exists.
+# This handles the interaction of Link and Repository logic.
+# As a side effect, it will link a source file from its Linked
+# directory (preferably local, but maybe in a repository)
+# into a build directory from its proper Linked directory.
+sub source_exists
+{
+ return $_[0]->{source_exists} if defined $_[0]->{source_exists};
+ my ($self) = @_;
+ my ($path) = $self->path;
+ my ($mtime, $ctime) = (stat($path))[9, 10];
+ if ($self->is_linked)
+ {
+
+ # Linked directory, local logic.
+ my ($srcpath) = $self->srcpath;
+ my ($src_mtime, $src_ctime) = (stat($srcpath))[9, 10];
+ if ($src_mtime)
+ {
+ if (!$mtime || $src_mtime != $mtime || $src_ctime != $ctime)
+ {
+ futil::install($srcpath, $self);
+ }
+ return $self->{source_exists} = 1;
+ }
+
+ # Linked directory, repository logic.
+ if (@param::rpath)
+ {
+ if ($self != $self->rfile)
+ {
+ return $self->{source_exists} = 1;
+ }
+ my ($rsrcpath) = $self->rsrcpath;
+ if ($path ne $rsrcpath)
+ {
+ my ($rsrc_mtime, $rsrc_ctime) = (stat($rsrcpath))[9, 10];
+ if ($rsrc_mtime)
+ {
+ if (!$mtime
+ || $rsrc_mtime != $mtime
+ || $rsrc_ctime != $ctime)
+ {
+ futil::install($rsrcpath, $self);
+ }
+ return $self->{source_exists} = 1;
+ }
+ }
+ }
+
+ # There was no source file in any Linked directory
+ # under any Repository. If there's one in the local
+ # build directory, it no longer belongs there.
+ if ($mtime)
+ {
+ unlink($path) || die ("$0: couldn't unlink $path ($!)\n");
+ }
+ return $self->{source_exists} = '';
+ }
+ else
+ {
+ if ($mtime)
+ {
+ return $self->{source_exists} = 1;
+ }
+ if (@param::rpath && $self != $self->rfile)
+ {
+ return $self->{source_exists} = 1;
+ }
+ return $self->{source_exists} = '';
+ }
+}
+
+# Return if a same-named derived file exists under a Repository directory.
+sub derived_exists
+{
+ $_[0]->{derived_exists}
+ || ($_[0]->{derived_exists} = ($_[0] != $_[0]->rfile));
+}
+
+# Return if this file is somewhere under a Repository directory.
+sub is_on_rpath
+{
+ defined $_[0]->{'lfile'};
+}
+
+sub local
+{
+ my ($self, $arg) = @_;
+ if (defined $arg)
+ {
+ $self->{'local'} = $arg;
+ }
+ $self->{'local'};
+}
+
+# Return the entry name of the specified file with the specified
+# suffix appended. Leave it untouched if the suffix is already there.
+# Differs from the addsuffix function, below, in that this strips
+# the existing suffix (if any) before appending the desired one.
+sub base_suf
+{
+ my ($entry) = $_[0]->{entry};
+ if ($entry !~ m/$_[1]$/)
+ {
+ $entry =~ s/\.[^\.]*$//;
+ $entry .= $_[1];
+ }
+ $entry;
+}
+
+# Return the suffix of the file; everything including and to the
+# right of the last dot.
+sub suffix
+{
+ my @pieces = split (/\./, $_[0]->{entry});
+ my $suffix = pop (@pieces);
+ return ".$suffix";
+}
+
+# Called as a simple function file::addsuffix(name, suffix)
+sub addsuffix
+{
+ my ($name, $suffix) = @_;
+
+ if ($suffix && substr($name, -length($suffix)) ne $suffix)
+ {
+ return $name .= $suffix;
+ }
+ $name;
+}
+
+# Return true if the file is (or will be) accessible.
+# That is, if we can build it, or if it is already present.
+sub accessible
+{
+ (exists $_[0]->{builder}) || ($_[0]->source_exists);
+}
+
+# Return true if the file should be ignored for the purpose
+# of computing dependency information (should not be considered
+# as a dependency and, further, should not be scanned for
+# dependencies).
+sub ignore
+{
+ return 0 if !$param::ignore;
+ return $_[0]->{ignore} if exists $_[0]->{ignore};
+ $_[0]->{ignore} = $_[0]->path =~ /$param::ignore/o;
+}
+
+# Build the file, if necessary.
+sub build
+{
+ return $_[0]->{status} if $_[0]->{status};
+ my ($status) = &file::_build;
+ if ($_[0]->{after_build_func})
+ {
+
+ #print STDERR "DEBUG: after_build_func=$_[0]->{after_build_func}\n";
+ my ($pkgvars) = $_[0]->{conscript}->{pkgvars};
+ NameSpace::restore('script', $pkgvars) if $pkgvars;
+ eval("package script; " . $_[0]->{after_build_func});
+ print "Error running AfterBuild for ${\$_[0]->path}: $@\n" if ($@);
+ NameSpace::remove('script', keys %$pkgvars) if $pkgvars;
+ }
+ return $status;
+}
+
+sub _build
+{
+ my @args = @_;
+
+ if ($param::max_jobs <= 1)
+ { # pcons
+ my ($self) = @args;
+ print main::DEPFILE $self->path, "\n" if $param::depfile;
+ print((' ' x $level), "Checking ", $self->path, "\n")
+ if $param::depends;
+ if (!exists $self->{builder})
+ {
+
+ # We don't know how to build the file. This is OK, if
+ # the file is present as a source file, under either the
+ # local tree or a Repository.
+ if ($self->source_exists)
+ {
+ return $self->{status} = 'handled';
+ }
+ else
+ {
+ my ($name) = $self->path;
+ print("$0: don't know how to construct \"$name\"\n");
+ exit(1) unless $param::kflag;
+ return $self->{status} = 'errors'; # xxx used to be 'unknown'
+ }
+ }
+
+ # An associated build object exists, so we know how to build
+ # the file. We first compute the signature of the file, based
+ # on its dependendencies, then only rebuild the file if the
+ # signature has changed.
+ my ($builder) = $self->{builder};
+ $level += 2;
+
+ my (@deps) = (@{$self->{dep}}, @{$self->{sources}});
+ my ($rdeps) = \@deps;
+
+ if ($param::random)
+ {
+
+ # If requested, build in a random order, instead of the
+ # order that the dependencies were listed.
+ my (%rdeps);
+ map { $rdeps{$_, '*' x int(rand 10)} = $_ } @deps;
+ $rdeps = [values(%rdeps)];
+ }
+
+ $self->{status} = '';
+
+ my $dep;
+ for $dep (@$rdeps)
+ {
+ if ((build $dep) eq 'errors')
+ {
+
+ # Propagate dependent errors to target.
+ # but try to build all dependents regardless of errors.
+ $self->{status} = 'errors';
+ }
+ }
+
+ # If any dependents had errors, then we abort.
+ if ($self->{status} eq 'errors')
+ {
+ $level -= 2;
+ return 'errors';
+ }
+
+ # Compute the final signature of the file, based on
+ # the static dependencies (in order), dynamic dependencies,
+ # output path name, and (non-substituted) build script.
+ my ($sig) =
+ 'sig'->collect(map('sig'->signature($_->rfile), @deps),
+ $builder->includes($self), $builder->scriptsig);
+
+ # May have gotten errors during computation of dynamic
+ # dependency signature, above.
+ $level -= 2;
+ return 'errors' if $self->{status} eq 'errors';
+
+ if (@param::rpath && $self->derived_exists)
+ {
+
+ # There is no local file of this name, but there is one
+ # under a Repository directory.
+
+ if ('sig'->current($self->rfile, $sig))
+ {
+
+ # The Repository copy is current (its signature matches
+ # our calculated signature).
+ if ($self->local)
+ {
+
+ # ...but they want a local copy, so provide it.
+ main::showcom("Local copy of ${\$self->path} from "
+ . "${\$self->rpath}");
+ futil::install($self->rpath, $self);
+ 'sig'->bsig($self, $sig);
+ }
+ return $self->{status} = 'handled';
+ }
+
+ # The signatures don't match, implicitly because something
+ # on which we depend exists locally. Get rid of the reference
+ # to the Repository file; we'll build this (and anything that
+ # depends on it) locally.
+ $self->no_rfile;
+ }
+
+ # Then check for currency.
+ if (!'sig'->current($self, $sig))
+ {
+
+ # We have to build/derive the file.
+ print((' ' x $level), "Rebuilding ", $self->path,
+ ": out of date.\n")
+ if $param::depends;
+
+ # First check to see if the built file is cached.
+ if ($builder->cachin($self, $sig))
+ {
+ 'sig'->bsig($self, $sig);
+ return $self->{status} = 'built';
+ }
+ elsif ($builder->action($self))
+ {
+ $builder->cachout($self, $sig);
+ 'sig'->bsig($self, $sig);
+ return $self->{status} = 'built';
+ }
+ else
+ {
+ die ("$0: errors constructing ${\$self->path}\n")
+ unless $param::kflag;
+ return $self->{status} = 'errors';
+ }
+ }
+ else
+ {
+
+ # Push this out to the cache if we've been asked to (-C option).
+ # Don't normally do this because it slows us down.
+ # In a fully built system, no accesses to the cache directory
+ # are required to check any files. This is a win if cache is
+ # heavily shared. Enabling this option puts the directory in the
+ # loop. Useful only when you wish to recreate a cache from a build.
+ if ($param::cachesync)
+ {
+ $builder->cachout($self, $sig);
+ 'sig'->bsig($self, $sig);
+ }
+ return $self->{status} = 'handled';
+ }
+ }
+ else
+ { # pcons
+ my ($tgt) = @args; # pcons
+ local ($file::child_queue) = {parent => $tgt}; # pcons
+ _pbuild($tgt); # pcons
+ wait_on_all_children(); # pcons
+ return $tgt->{status}; # pcons
+ }
+}
+
+########################################
+# pcons only BEGIN
+#
+
+sub pbuild
+{
+ $_[0]->{status} || &file::_pbuild;
+}
+
+sub _pbuild
+{
+ my ($self) = @_;
+ $self->{status} = ''; # tgl
+ print main::DEPFILE $self->path, "\n" if param::depfile;
+ print((' ' x $level), $self->path, "\n") if $param::depends;
+ if (!exists $self->{builder})
+ {
+
+ # We don't know how to build the file. This is OK, if
+ # the file is present as a source file, under either the
+ # local tree or a Repository.
+ if ($self->source_exists)
+ {
+ return $self->{status} = 'handled';
+ }
+ else
+ {
+ my ($name) = $self->path;
+ print("$0: don't know how to construct \"$name\"\n");
+ exit(1) unless $param::kflag;
+ return $self->{status} = 'errors'; # xxx used to be 'unknown'
+ }
+ }
+
+ # An associated build object exists, so we know how to build
+ # the file. We first compute the signature of the file, based
+ # on its dependendencies, then only rebuild the file if the
+ # signature has changed.
+ my ($builder) = $self->{'builder'};
+ $level += 2;
+
+ my (@deps) = (@{$self->{dep}}, @{$self->{sources}});
+ my ($rdeps) = \@deps;
+
+ if ($param::random)
+ {
+
+ # If requested, build in a random order, instead of the
+ # order that the dependencies were listed.
+ my (%rdeps);
+
+ # FIX map { $rdeps{$_,'*' x int(rand(0,10))} = $_ } @deps;
+ map { $rdeps{$_, '*' x int(rand(10))} = $_ } @deps;
+ $rdeps = [values(%rdeps)];
+ }
+
+ $self->{status} = '';
+
+ my $sig;
+ {
+
+ # print "in ", $self->path, "\n";
+ local ($file::child_queue) = {parent => $self};
+ for my $dep (@$rdeps)
+ {
+ if ((pbuild $dep) eq 'errors')
+ {
+
+ # Propagate dependent errors to target.
+ # but try to build all dependents regardless of errors.
+ $self->{status} = 'errors';
+ }
+ }
+ wait_on_all_children();
+
+ }
+
+ # If any dependents had errors, then we abort.
+ if ($self->{'status'} eq 'errors')
+ {
+ $level -= 2;
+ return 'errors';
+ }
+
+ # Compute the final signature of the file, based on
+ # the static dependencies (in order), dynamic dependencies,
+ # output path name, and (non-substituted) build script.
+
+ # my($sig) = $self->{'sign'} = sig->collect(map(sig->signature($_->rfile), @deps),
+ # $builder->includes($self),
+ ## FIX $builder->script);
+ # $builder->scriptsig);
+
+ my ($sig) = 'sig'->collect(
+ map('sig'->signature($_->rfile), @deps), # from cons-2.3.0
+ $builder->includes($self), # from cons-2.3.0
+ $builder->scriptsig
+ ); # from cons-2.3.0
+ $self->{sign} = $sig;
+
+ # May have gotten errors during computation of dynamic
+ # dependency signature, above.
+ $level -= 2;
+ return 'errors' if $self->{status} eq 'errors';
+
+ if (@param::rpath && $self->derived_exists)
+ {
+
+ # There is no local file of this name, but there is one
+ # under a Repository directory.
+
+ if ('sig'->current($self->rfile, $sig))
+ {
+
+ # The Repository copy is current (its signature matches
+ # our calculated signature).
+ if ($self->local)
+ {
+
+ # ...but they want a local copy, so provide it.
+ main::showcom(
+ "Local copy of ${\$self->path} from ${\$self->rpath}");
+ futil::install($self->rpath, $self);
+
+ #'sig'->set($self, $sig);
+ 'sig'->bsig($self, $sig); # pcons
+ }
+ return $self->{status} = 'handled';
+ }
+
+ # The signatures don't match, implicitly because something
+ # on which we depend exists locally. Get rid of the reference
+ # to the Repository file; we'll build this (and anything that
+ # depends on it) locally.
+ $self->no_rfile;
+ }
+
+ # Then check for currency.
+ if (!'sig'->current($self, $sig))
+ {
+
+ # We have to build/derive the file.
+ # First check to see if the built file is cached.
+ if ($builder->cachin($self, $sig))
+ {
+
+ #'sig'->set($self, $sig);
+ 'sig'->bsig($self, $sig); # pcons
+ return $self->{status} = 'built';
+
+ # action no longer blocks (for most actions), so this returns
+ # immediately, before any commands are actually run. The
+ # signature and return status should be overridden later in
+ # wait_on_child if a process was forked, but they are still set
+ # here in case a non-spawning action was called
+ }
+ elsif ($builder->action($self))
+ {
+ $builder->cachout($self, $sig);
+
+ #'sig'->set($self, $sig);
+ 'sig'->bsig($self, $sig); # pcons
+ return $self->{status} = 'built';
+ }
+ else
+ {
+ die ("$0: errors constructing ${\$self->path}\n")
+ unless $param::kflag;
+ return $self->{status} = 'errors';
+ }
+ }
+ else
+ {
+
+ # Push this out to the cache if we've been asked to (-C option).
+ # Don't normally do this because it slows us down.
+ # In a fully built system, no accesses to the cache directory
+ # are required to check any files. This is a win if cache is
+ # heavily shared. Enabling this option puts the directory in the
+ # loop. Useful only when you wish to recreate a cache from a build.
+ if ($param::cachesync)
+ {
+ $builder->cachout($self, $sig);
+
+ #'sig'->set($self, $sig);
+ 'sig'->bsig($self, $sig);
+ }
+ return $self->{status} = 'handled';
+ }
+}
+
+my @finished; # pcons //fix -Mstrict
+
+sub wait_on_max_jobs
+{
+ while (grep(/\d+/, keys %{$file::child_queue}) >= $param::max_jobs)
+ {
+ wait_on_child();
+ }
+}
+
+sub wait_on_all_children
+{
+
+ while (grep(/\d+/, keys %{$file::child_queue}) != 0)
+ {
+ wait_on_child();
+ }
+}
+
+sub wait_on_child
+{
+ my ($queue) = $file::child_queue;
+ my ($parent) = $queue->{parent};
+
+ my $n = grep(/\d+/, keys %{$file::child_queue});
+
+ # printf "Waiting to build (%s): %s\n", $n, $parent->path if ref($parent) eq 'file';
+ my $pid = undef;
+
+ # first check for jobs that have already been collected from child
+ # targets
+ for my $p (@finished)
+ {
+ if ($queue->{$p})
+ {
+ $pid = $p;
+ last;
+ }
+ }
+
+ while (!$queue->{$pid})
+ {
+ $pid = wait();
+ if ($pid < 1)
+ {
+ die "wait returned invalid pid $pid";
+ }
+ else
+ {
+
+ # this job was meant for a parent, save it so that it can be
+ # found later
+ if (!$queue->{$pid})
+ {
+ push @finished, $pid;
+ }
+ }
+ }
+
+ my $child = $queue->{$pid};
+ my $tgt = $queue->{$pid}->{'tgt'};
+ my $com = $child->{'com'};
+ $tgt->{status} = 'built';
+
+ #print "waited: ", $tgt->path;
+ #print "on: ", keys %{$queue}, "\n";
+
+ my ($b0, $b1) = ($? & 0xFF, $? >> 8);
+
+ # Don't actually see 0177 on stopped process; is this necessary?
+ # next if $b0 == 0177; # process stopped; we can wait.
+ if ($b0)
+ {
+ my ($core, $sig) = ($b0 & 0200, $b0 & 0177);
+ my ($coremsg) = $core ? "; core dumped" : "";
+ $com =~ s/\s.*//;
+ my ($path) = $tgt->path;
+ warn qq($0: *** [$path] $com terminated by signal $sig$coremsg\n);
+ $parent->{status} = $tgt->{status} = 'errors';
+ }
+ if ($b1)
+ {
+ my ($path) = $tgt->path;
+ warn qq($0: *** [$path] Error $b1\n); # trying to be like make.
+ $parent->{status} = $tgt->{status} = 'errors';
+ }
+ if ($tgt->{status} eq 'built')
+ {
+ $tgt->{builder}->cachout($tgt, $tgt->{sign});
+
+ #'sig'->set($tgt, $tgt->{sign});
+ 'sig'->bsig($tgt, $tgt->{sign});
+ }
+ else
+ {
+ die ("$0: errors constructing ${\$tgt->path}\n") unless $param::kflag;
+ }
+ delete $queue->{$pid};
+
+}
+
+#
+# pcons END
+########################################
+
+# Bind an action to a file, with the specified sources. No return value.
+sub bind
+{
+ my ($self, $builder, @sources) = @_;
+ if ($self->{builder} && !$self->{builder}->compatible($builder))
+ {
+
+ # Even if not "compatible", we can still check to see if the
+ # derivation is identical. It should be identical if the builder is
+ # the same and the sources are the same.
+ if ("$self->{builder} @{$self->{sources}}" ne "$builder @sources")
+ {
+ $main::errors++;
+ my ($_foo1, $script1, $line1, $sub1) = @{$self->creator};
+ my ($_foo2, $script2, $line2, $sub2) = script::caller_info;
+ my $err =
+ "\t${\$self->path}\n"
+ . "\tbuilt (at least) two different ways:\n"
+ . "\t\t$script1, line $line1: $sub1\n"
+ . "\t\t$script2, line $line2: $sub2\n";
+ die $err;
+ }
+ return;
+ }
+ if ($param::wflag)
+ {
+ my ($script, $line, $sub);
+ (undef, $script, $line, $sub) = script::caller_info;
+ $self->{script} = '' if !defined $self->{script};
+ $self->{script} .= "; " if $self->{script};
+ $self->{script} .= qq($sub in "$script", line $line);
+ }
+ $self->{builder} = $builder;
+ push (@{$self->{sources}}, @sources);
+ @{$self->{dep}} = () if !defined $self->{dep};
+ $self->{conscript} = $priv::self->{script};
+}
+
+sub is_under
+{
+ $_[0]->{dir}->is_under($_[1]);
+}
+
+sub relpath
+{
+ my $dirpath = $_[0]->relpath($_[1]->{dir});
+ if (!$dirpath)
+ {
+ return $_[1]->{entry};
+ }
+ else
+ {
+ File::Spec->catfile($dirpath, $_[1]->{entry});
+ }
+}
+
+# Return the signature array for this file.
+# This probably belongs in its own "sigarray" package,
+# which would make it easier to optimize performance.
+sub sigarray
+{
+ if ($_[0]->{sigaref})
+ {
+ return @{$_[0]->{sigaref}};
+ }
+ my $self = shift;
+
+ # glob2pat based on The Perl Cookbook, p. 180.
+ sub glob2pat
+ {
+ my $globstr = shift;
+ my %patmap = (
+ '*' => '.*',
+ '?' => '.',
+ '[' => '[',
+ ']' => ']',
+ '/' => "\Q$dir::SEPARATOR", # Cons-specific modification
+ );
+ $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
+ return '^' . $globstr . '$';
+ }
+ my @sigarray;
+ my $default;
+ my $builder = $self->lfile->{builder};
+ if (!$builder)
+ {
+ @sigarray = @$param::sourcesig;
+ $default = [qw(content)];
+ }
+ else
+ {
+ if ($builder->{env} && $builder->{env}->{SIGNATURE})
+ {
+ @sigarray = @{$builder->{env}->{SIGNATURE}};
+ }
+ else
+ {
+ my $class = ref $builder;
+ my $path = $self->path;
+ warn qq($0: Warning: Builder package $class did not record\n)
+ . qq(\tthe calling environment for '$path'.\n)
+ . qq(\tUnable to use any %SIGNATURE construction variable\n)
+ . qq(\tfor signature configuration.\n);
+ }
+ $default = [qw(build)];
+ }
+ my $path = $self->path;
+ while (@sigarray)
+ {
+ my ($glob, $aref) = splice(@sigarray, 0, 2);
+ my $re = glob2pat($glob);
+ if ($path =~ /$re/)
+ {
+ $aref = [split (/\s+/, $aref)] if !ref $aref;
+ $self->{sigaref} = $aref;
+ return @$aref;
+ }
+ }
+ $self->{sigaref} = $default;
+ return @{$self->{sigaref}};
+}
+
+# Decide if this file's signature should be the content or build signature.
+sub sigtype
+{
+ if ($_[0]->{sigtype})
+ {
+ return $_[0]->{sigtype};
+ }
+ my $self = shift;
+ my @sigarray = $self->sigarray;
+ my $sigtype;
+ if (grep($_ eq "build", @sigarray))
+ {
+ $sigtype = 'bsig';
+ }
+ elsif (grep($_ =~ /content$/, @sigarray))
+ {
+ $sigtype = 'csig';
+ }
+ return $self->{sigtype} = $sigtype;
+}
+
+# Return whether this file is configured to use stored
+# signature values from the .consign file.
+sub stored
+{
+ if (!defined $_[0]->{stored})
+ {
+ $_[0]->{stored} = grep($_ eq "stored-content", $_[0]->sigarray);
+ }
+ return $_[0]->{stored};
+}
+
+# Generic entry (file or directory) handling.
+# This is an empty subclass for nodes that haven't
+# quite decided whether they're files or dirs.
+# Use file methods until someone blesses them one way or the other.
+package entry;
+
+use vars qw( @ISA );
+
+BEGIN { @ISA = qw(file) }
+
+# File utilities
+package futil;
+
+# Install one file as another.
+# Links them if possible (hard link), otherwise copies.
+# Don't ask why, but the source is a path, the tgt is a file obj.
+sub install
+{
+ my ($sp, $tgt) = @_;
+ my ($tp) = $tgt->path;
+ return 1 if $tp eq $sp;
+ return 1 if eval { link($sp, $tp) };
+ unlink($tp);
+ if (!futil::mkdir($tgt->{dir}))
+ {
+ return undef;
+ }
+ return 1 if eval { link($sp, $tp) };
+ futil::copy($sp, $tp);
+}
+
+# Copy one file to another. Arguments are actual file names.
+# Returns undef on failure. Preserves mtime and mode.
+sub copy
+{
+ my ($sp, $tp) = @_;
+ my ($mode, $length, $atime, $mtime) = (stat($sp))[2, 7, 8, 9];
+
+ # Use Perl standard library module for file copying, which handles
+ # binary copies. <schwarze@isa.de> 1998-06-18
+ if (!File::Copy::copy($sp, $tp))
+ {
+ warn qq($0: can\'t install "$sp" to "$tp" ($!)\n); #'
+ return undef;
+ }
+
+ # The file has been created, so try both the chmod and utime,
+ # first making sure the copy is writable (because permissions
+ # affect the ability to modify file times on some operating
+ # systems), and then changing permissions back if necessary.
+ my $ret = 1;
+ my $wmode = $mode | 0700;
+ if (!chmod $wmode, $tp)
+ {
+ warn qq($0: can\'t set mode $wmode on file "$tp" ($!)\n); #'
+ $ret = undef;
+ }
+ if (!utime $atime, $mtime, $tp)
+ {
+ warn qq($0: can\'t set modification time for file "$tp" ($!)\n); #'
+ $ret = undef;
+ }
+ if ($mode != $wmode && !chmod $mode, $tp)
+ {
+ warn qq($0: can\'t set mode $mode on file "$tp" ($!)\n); #'
+ $ret = undef;
+ }
+ return $ret;
+}
+
+# Ensure that the specified directory exists.
+# Aborts on failure.
+sub mkdir
+{
+ return 1 if $_[0]->{'exists'};
+ if (!futil::mkdir($_[0]->{dir}))
+ { # Recursively make parent.
+ return undef;
+ }
+ my ($path) = $_[0]->path;
+ if (!-d $path && !mkdir($path, 0777))
+ {
+ warn qq($0: can't create directory $path ($!).\n); #'
+ return undef;
+ }
+ $_[0]->{'exists'} = 1;
+}
+
+# Signature package.
+package sig::hash;
+
+use vars qw( $called );
+
+sub init
+{
+ my ($dir) = @_;
+ my ($consign) = $dir->prefix . ".consign";
+ my ($dhash) = $dir->{consign} = {};
+ if (-f $consign)
+ {
+ open(CONSIGN, $consign) || die ("$0: can't open $consign ($!)\n");
+ while (<CONSIGN>)
+ {
+ chop;
+ my ($file, $sig) = split (/:/, $_);
+ $dhash->{$file} = $sig;
+ }
+ close(CONSIGN);
+ }
+ $dhash;
+}
+
+# Read the hash entry for a particular file.
+sub in
+{
+ my ($dir) = $_[0]->{dir};
+ ($dir->{consign} || init($dir))->{$_[0]->{entry}};
+}
+
+# Write the hash entry for a particular file.
+sub out
+{
+ my ($file, $sig) = @_;
+ my ($dir) = $file->{dir};
+ ($dir->{consign} || init($dir))->{$file->{entry}} = $sig;
+ $sig::hash::dirty{$dir} = $dir;
+}
+
+# Eliminate the hash entry for a particular file.
+sub clear
+{
+ my ($file) = @_;
+ my ($dir) = $file->{dir};
+ delete $dir->{consign}->{$file->{entry}} if $dir->{consign};
+ $sig::hash::dirty{$dir} = $dir;
+}
+
+# Flush hash entries. Called at end or via ^C interrupt.
+sub END
+{
+ return if $called++; # May be called twice.
+ close(CONSIGN); # in case this came in via ^C.
+ my $dir;
+ for $dir (values %sig::hash::dirty)
+ {
+ my ($consign) = $dir->prefix . ".consign";
+ my ($constemp) = $consign . ".$$";
+ if (!open(CONSIGN, ">$constemp"))
+ {
+ die ("$0: can't create $constemp ($!)\n");
+ }
+ my ($entry, $sig);
+ while (($entry, $sig) = each %{$dir->{consign}})
+ {
+ if (!print CONSIGN "$entry:$sig\n")
+ {
+ die ("$0: error writing to $constemp ($!)\n");
+ }
+ }
+ close(CONSIGN);
+ if (!rename($constemp, $consign))
+ {
+ if (futil::copy($constemp, $consign))
+ {
+ unlink($constemp);
+ }
+ else
+ {
+ die ("$0: couldn't rename or copy $constemp to $consign "
+ . "($!)\n");
+ }
+ }
+ }
+}
+
+# Derived file caching.
+package cache;
+
+# Find a file in the cache. Return non-null if the file is in the cache.
+sub in
+{
+ return undef unless $param::cache;
+ my ($file, $sig) = @_;
+
+ # Add the path to the signature, to make it unique.
+ $sig = 'sig'->collect($sig, $file->path) unless $param::mixtargets;
+ my ($dir) = substr($sig, 0, 1);
+ my ($cp) = File::Spec->catfile($param::cache, $dir, $sig);
+ return -f $cp && futil::install($cp, $file);
+}
+
+# Try to flush a file to the cache, if not already there.
+# If it doesn't make it out, due to an error, then that doesn't
+# really matter.
+sub out
+{
+ return unless $param::cache;
+ my ($file, $sig) = @_;
+
+ # Add the path to the signature, to make it unique.
+ $sig = 'sig'->collect($sig, $file->path) unless $param::mixtargets;
+ my ($dir) = substr($sig, 0, 1);
+ my ($sp) = $file->path;
+ my ($cp) = File::Spec->catfile($param::cache, $dir, $sig);
+ my ($cdir) = File::Spec->catfile($param::cache, $dir);
+ if (!-d $cdir)
+ {
+ mkdir($cdir, 0777)
+ || die ("$0: can't create cache directory $cdir ($!).\n");
+ }
+ elsif (-f $cp)
+ {
+
+ # Already cached: try to use that instead, to save space.
+ # This can happen if the -cs option is used on a previously
+ # uncached build, or if two builds occur simultaneously.
+ my ($lp) = ".$sig";
+ unlink($lp);
+ return if !eval { link($cp, $lp) };
+ rename($lp, $sp);
+
+ # Unix98 says, "If the old argument and the new argument both
+ # [refer] to the same existing file, the rename() function
+ # returns successfully and performs no other action." So, if
+ # $lp and $sp are links (i.e., $cp and $sp are links), $lp is
+ # left, and we must unlink it ourselves. If the rename failed
+ # for any reason, it is also good form to unlink the temporary
+ # $lp. Otherwise $lp no longer exists and, barring some race,
+ # the unlink fails silently.
+ unlink($lp);
+ return;
+ }
+
+ return if eval { link($sp, $cp) };
+ return if !-f $sp; # if nothing to cache.
+ if (futil::copy($sp, "$cp.new"))
+ {
+ rename("$cp.new", $cp);
+ }
+}
+
+# Generic signature handling package.
+# This handles the higher-layer distinction between content and build
+# signatures, relying on an underlying calculation package like
+# "sig::md5"" to provide the signature values themselves.
+package sig;
+
+use vars qw( @ISA );
+
+# Select the underlying package to be used for signature calculation.
+# We play a few namespace games here. Specifically, we append
+# "sig::" to the beginning of the subclass we're passed. Then,
+# if the package ends in "::debug", we actually subclass the
+# "sig::debug" package and as a wrapper around the underlying
+# (e.g.) "sig::md5" package that's doing the real calculation.
+sub select
+{
+ my ($package, $subclass) = @_;
+ my $p = $package . "::" . $subclass;
+ my $sigpkg = $p;
+ if ($p =~ /(.*)::debug$/)
+ {
+ $sigpkg = $1;
+ $p = 'sig::debug';
+ }
+ @ISA = ($p);
+ $p->init($sigpkg);
+};
+
+# Set or return the build signature of a file.
+# This is computed elsewhere and passed in to us.
+sub bsig
+{
+ my ($self, $file, $sig) = @_;
+ if (defined $sig)
+ {
+ $file->{'bsig'} = $sig;
+ $self->set($file);
+ }
+ elsif (!defined $file->{'bsig'})
+ {
+ $file->{'bsig'} = '';
+ }
+ $file->{'bsig'};
+}
+
+# Determine the content signature of a file.
+# This also sets the .consign entry unless the file is in a
+# repository; we don't write into repositories, only read from them.
+sub csig
+{
+ my ($self, $file) = @_;
+ if (!$file->{'csig'})
+ {
+ $file->{'csig'} = $self->srcsig($file->path);
+ $self->set($file) if !$file->is_on_rpath;
+ }
+ $_[1]->{'csig'};
+}
+
+# Determine the current signature of an already-existing or
+# non-existant file. Unless a specific signature type (bsig
+# or csig) is requested, this consults the file's signature
+# array to decide whether to return content or build signature,
+# and whether to use a cached value from a .consign file.
+sub signature
+{
+ my ($self, $file, $sigtype) = @_;
+ $sigtype = $file->sigtype if !$sigtype;
+
+ #open(TTY, ">/dev/tty");
+ #print TTY $file->path, ": $sigtype\n";
+ #close(TTY);
+ my ($path) = $file->path;
+ my ($time) = (stat($path))[9];
+ if ($time)
+ {
+ if ($file->{$sigtype})
+ {
+ return $file->{$sigtype};
+ }
+ if ($file->is_on_rpath || $file->stored)
+ {
+ if ('sig'->fetch($file) && $file->{$sigtype})
+ {
+ if ($file->{'sigtime'} == $time
+ || !$param::rep_sig_times_ok && $file->is_on_rpath)
+ {
+ return $file->{$sigtype};
+ }
+ }
+ $file->{$sigtype} = undef;
+ }
+ if ($file->is_on_rpath || !File::Spec->file_name_is_absolute($path))
+ {
+ my $sig = '';
+ if ($sigtype eq 'bsig') { $sig = $self->bsig($file); }
+ elsif ($sigtype eq 'csig') { $sig = $self->csig($file); }
+ return $sig;
+ }
+
+ # This file is not in a repository or under the local directory
+ # structure. In the canonical case, it's a utility that will be
+ # executed by a command. Historically, Cons has returned the
+ # name of the command concatenated with the modification time.
+ # Note that this is *not* the path ("cc" not "/bin/cc"), so it
+ # would lose in the unlikely event that a different copy of the
+ # utility was used that happened to have the same modification
+ # time (due to living in a different directory on the PATH, for
+ # example). The obvious "fix" of using the path like so, however:
+ # return $path . $time;
+ # is wrong. In a multi-machine build environment, different
+ # systems may have the same utility in different locations (due
+ # to different NFS mount points, for example), which would
+ # cause a lot of unnecessary builds if we used the full path.
+ # A better solution to strengthen this signature would be to
+ # also concatenate the size of the file, but that would cause
+ # unnecessary rebuilds when coming from .consign files that used
+ # the old scheme. All of which is to merely explain why we're
+ # leaving this as it has been, but documenting it here in case
+ # there's reason to change it in the future.
+ return $file->{entry} . $time;
+ }
+ return $file->{$sigtype} = '';
+}
+
+sub bsignature
+{
+ my ($self, $file) = @_;
+ my ($path) = $file->path;
+ my ($time) = (stat($path))[9];
+ if ($time)
+ {
+ if ($file->{'bsig'})
+ {
+ return $file->{'bsig'};
+ }
+ if ('sig'->fetch($file, 'bsig') && $file->{'bsig'})
+ {
+ if ($file->{'sigtime'} == $time
+ || !$param::rep_sig_times_ok && $file->is_on_rpath)
+ {
+ return $file->{'bsig'};
+ }
+ }
+ if ($file->is_on_rpath || !File::Spec->file_name_is_absolute($path))
+ {
+ return $self->bsig($file);
+ }
+ return $path . $time;
+ }
+ return $file->{'bsig'} = '';
+}
+
+# Invalidate a file's signature, also clearing its .consign entry.
+sub invalidate
+{
+ my ($self, $file) = @_;
+ delete $file->{'sigtime'};
+ delete $file->{'bsig'};
+ delete $file->{'csig'};
+ sig::hash::clear($file);
+}
+
+# Store the signature for a file.
+sub set
+{
+ my ($self, $file) = @_;
+ my $sig = (stat($file->path))[9];
+ $sig .= " " . ($file->{'bsig'} || '-');
+ $sig .= " " . $file->{'csig'} if $file->{'csig'};
+ sig::hash::out($file, $sig);
+}
+
+# Fetch the signature(s) for a file.
+# Returns whether there was a signature to fetch.
+sub fetch
+{
+ my ($self, $file, @kw) = @_;
+ @kw = ('bsig', 'csig') if !@kw;
+ my $sig = sig::hash::in($file) || '';
+ my ($sigtime, $bsig, $csig) = split (/ /, $sig);
+ $file->{'sigtime'} = $sigtime;
+ $file->{'bsig'} = $bsig || '' if grep($_ eq 'bsig', @kw);
+ $file->{'csig'} = $csig || '' if grep($_ eq 'csig', @kw);
+ $file->{'bsig'} = '' if $file->{'bsig'} eq '-';
+ return $sig ne '';
+}
+
+# MD5-based signature package.
+package sig::md5;
+
+use vars qw( $md5 );
+
+# Initialize MD5 signature calculation by finding an appropriate
+# module and creating the proper object.
+sub init
+{
+ my $self = shift;
+ my @md5_modules = qw(Digest::MD5 MD5 Digest::Perl::MD5);
+
+ # We used to find the right module more simply, using $_ as the
+ # loop iterator and just doing:
+ #
+ # eval "use $_";
+ # $module = $_, $last if ! $@;
+ #
+ # in the loop. Empirically, though, this doesn't pass back the
+ # right value in $module on some ActiveState versions. (Maybe
+ # it's something to do with the eval in a for loop, I dunno.)
+ # Work around it by using $_ to pass the value out of the loop,
+ # which seems to work everywhere.
+ my $module;
+ for $module (@md5_modules)
+ {
+ eval "use $module";
+ $_ = $module, last if !$@;
+ }
+ $module = $_;
+ die "Cannot find any MD5 module from: @md5_modules" if $@;
+
+ $md5 = new $module;
+}
+
+# Is the provided signature equal to the signature of the current
+# instantiation of the target (and does the target exist)?
+sub current
+{
+ my ($self, $file, $sig, $sigtype) = @_;
+ $self->bsignature($file) eq $sig;
+}
+
+# Return an aggregate signature for a list of signature values.
+sub collect
+{
+ my ($self, @sigs) = @_;
+
+ # The following sequence is faster than calling the hex interface.
+ $md5->reset();
+ $md5->add(join ('', $param::salt, @sigs));
+ unpack("H*", $md5->digest());
+}
+
+# Directly compute a file signature as the MD5 checksum of the
+# bytes in the file.
+sub srcsig
+{
+ my ($self, $path) = @_;
+ $md5->reset();
+ open(FILE, $path) || return '';
+ binmode(FILE);
+ $md5->addfile(\*FILE);
+ close(FILE);
+ unpack("H*", $md5->digest());
+}
+
+# Compute the signature of a command string.
+# For MD5, this is just the string itself, since MD5 will condense
+# the string contents into the ultimate signature. Other signature
+# schemes may need to figure this out differently.
+sub cmdsig
+{
+ my ($self, $sig) = @_;
+ return $sig;
+}
+
+# Generic debug package for signature calculation.
+# Because of the way we're called by sig::select() and then use
+# the specified value to set up @ISA, this package is essentially a
+# factory that creates packages like sig::md5::debug, etc., on the fly.
+package sig::debug;
+
+use vars qw( @ISA $sigpkg $outfh );
+
+local *FH;
+
+sub init
+{
+ my $self = shift;
+ $sigpkg = shift;
+ @ISA = ($sigpkg);
+ $sigpkg->init();
+ my $file = $ENV{CONS_SIG_DEBUG};
+ if ($file)
+ {
+ if (!open(FH, ">$file"))
+ {
+ die "Cannot open $file: $!";
+ }
+ $outfh = \*FH;
+ }
+ else
+ {
+ $outfh = \*STDOUT;
+ }
+}
+
+sub current
+{
+ my ($self, $file, $sig, $sigtype) = @_;
+ my $fsig = $self->bsignature($file);
+ my $sub = "${sigpkg}::current";
+ my $sep = "\n" . ' ' x (length($sub) + 1 - 3);
+ print $outfh "$sub(|$fsig|${sep}eq |$sig|)\n";
+ return $fsig eq $sig;
+}
+
+sub collect
+{
+ my ($self, @sigs) = @_;
+ my $sig = $sigpkg->collect(@sigs);
+ my $sub = "${sigpkg}::collect";
+ my $sep = ",\n" . ' ' x (length($sub) + 1);
+ my $buf = join ($sep, @sigs);
+ $buf = $param::salt . $sep . $buf if $param::salt;
+ print $outfh "$sub($buf)\n\t=> |$sig|\n";
+ return $sig;
+}
+
+sub srcsig
+{
+ my ($self, $path) = @_;
+ my $sig = $sigpkg->srcsig($path);
+ print $outfh "${sigpkg}::srcsig($path)\n\t=> |$sig|\n";
+ return $sig;
+}
+
+__END__;
+
+=head1 NAME
+
+Cons - A Software Construction System
+
+=head1 DESCRIPTION
+
+A guide and reference for version __VERSION____REVISION__
+
+Copyright (c) 1996-2001 Free Software Foundation, Inc.
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; see the file COPYING. If not, write to
+the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+Boston, MA 02111-1307, USA.
+
+=head1 Introduction
+
+B<Cons> is a system for constructing, primarily, software, but is quite
+different from previous software construction systems. Cons was designed
+from the ground up to deal easily with the construction of software spread
+over multiple source directories. Cons makes it easy to create build scripts
+that are simple, understandable and maintainable. Cons ensures that complex
+software is easily and accurately reproducible.
+
+Cons uses a number of techniques to accomplish all of this. Construction
+scripts are just Perl scripts, making them both easy to comprehend and very
+flexible. Global scoping of variables is replaced with an import/export
+mechanism for sharing information between scripts, significantly improving
+the readability and maintainability of each script. B<Construction
+environments> are introduced: these are Perl objects that capture the
+information required for controlling the build process. Multiple
+environments are used when different semantics are required for generating
+products in the build tree. Cons implements automatic dependency analysis
+and uses this to globally sequence the entire build. Variant builds are
+easily produced from a single source tree. Intelligent build subsetting is
+possible, when working on localized changes. Overrides can be setup to
+easily override build instructions without modifying any scripts. MD5
+cryptographic B<signatures> are associated with derived files, and are used
+to accurately determine whether a given file needs to be rebuilt.
+
+While offering all of the above, and more, Cons remains simple and easy to
+use. This will, hopefully, become clear as you read the remainder of this
+document.
+
+
+=head1 Why Cons? Why not Make?
+
+Cons is a B<make> replacement. In the following paragraphs, we look at a few
+of the undesirable characteristics of make--and typical build environments
+based on make--that motivated the development of Cons.
+
+=head2 Build complexity
+
+Traditional make-based systems of any size tend to become quite complex. The
+original make utility and its derivatives have contributed to this tendency
+in a number of ways. Make is not good at dealing with systems that are
+spread over multiple directories. Various work-arounds are used to overcome
+this difficulty; the usual choice is for make to invoke itself recursively
+for each sub-directory of a build. This leads to complicated code, in which
+it is often unclear how a variable is set, or what effect the setting of a
+variable will have on the build as a whole. The make scripting language has
+gradually been extended to provide more possibilities, but these have
+largely served to clutter an already overextended language. Often, builds
+are done in multiple passes in order to provide appropriate products from
+one directory to another directory. This represents a further increase in
+build complexity.
+
+
+=head2 Build reproducibility
+
+The bane of all makes has always been the correct handling of
+dependencies. Most often, an attempt is made to do a reasonable job of
+dependencies within a single directory, but no serious attempt is made to do
+the job between directories. Even when dependencies are working correctly,
+make's reliance on a simple time stamp comparison to determine whether a
+file is out of date with respect to its dependents is not, in general,
+adequate for determining when a file should be rederived. If an external
+library, for example, is rebuilt and then ``snapped'' into place, the
+timestamps on its newly created files may well be earlier than the last
+local build, since it was built before it became visible.
+
+
+=head2 Variant builds
+
+Make provides only limited facilities for handling variant builds. With the
+proliferation of hardware platforms and the need for debuggable
+vs. optimized code, the ability to easily create these variants is
+essential. More importantly, if variants are created, it is important to
+either be able to separate the variants or to be able to reproduce the
+original or variant at will. With make it is very difficult to separate the
+builds into multiple build directories, separate from the source. And if
+this technique isn't used, it's also virtually impossible to guarantee at
+any given time which variant is present in the tree, without resorting to a
+complete rebuild.
+
+
+=head2 Repositories
+
+Make provides only limited support for building software from code that
+exists in a central repository directory structure. The VPATH feature of
+GNU make (and some other make implementations) is intended to provide this,
+but doesn't work as expected: it changes the path of target file to the
+VPATH name too early in its analysis, and therefore searches for all
+dependencies in the VPATH directory. To ensure correct development builds,
+it is important to be able to create a file in a local build directory and
+have any files in a code repository (a VPATH directory, in make terms) that
+depend on the local file get rebuilt properly. This isn't possible with
+VPATH, without coding a lot of complex repository knowledge directly into
+the makefiles.
+
+
+=head1 Keeping it simple
+
+A few of the difficulties with make have been cited above. In this and
+subsequent sections, we shall introduce Cons and show how these issues are
+addressed.
+
+=head2 Perl scripts
+
+Cons is Perl-based. That is, Cons scripts--F<Conscript> and F<Construct>
+files, the equivalent to F<Makefile> or F<makefile>--are all written in
+Perl. This provides an immediate benefit: the language for writing scripts
+is a familiar one. Even if you don't happen to be a Perl programmer, it
+helps to know that Perl is basically just a simple declarative language,
+with a well-defined flow of control, and familiar semantics. It has
+variables that behave basically the way you would expect them to,
+subroutines, flow of control, and so on. There is no special syntax
+introduced for Cons. The use of Perl as a scripting language simplifies
+the task of expressing the appropriate solution to the often complex
+requirements of a build.
+
+
+=head2 Hello, World!
+
+To ground the following discussion, here's how you could build the B<Hello,
+World!> C application with Cons:
+
+
+
+ $env = new cons();
+ Program $env 'hello', 'hello.c';
+
+If you install this script in a directory, naming the script F<Construct>,
+and create the F<hello.c> source file in the same directory, then you can
+type C<cons hello> to build the application:
+
+
+
+ % cons hello
+ cc -c hello.c -o hello.o
+ cc -o hello hello.o
+
+
+=head2 Construction environments
+
+A key simplification of Cons is the idea of a B<construction environment>. A
+construction environment is an B<object> characterized by a set of key/value
+pairs and a set of B<methods>. In order to tell Cons how to build something,
+you invoke the appropriate method via an appropriate construction
+environment. Consider the following example:
+
+
+
+ $env = new cons(
+ CC => 'gcc',
+ LIBS => 'libworld.a'
+ );
+
+ Program $env 'hello', 'hello.c';
+
+In this case, rather than using the default construction environment, as is,
+we have overridden the value of C<CC> so that the GNU C Compiler equivalent
+is used, instead. Since this version of B<Hello, World!> requires a library,
+F<libworld.a>, we have specified that any program linked in this environment
+should be linked with that library. If the library exists already, well and
+good, but if not, then we'll also have to include the statement:
+
+
+
+ Library $env 'libworld', 'world.c';
+
+Now if you type C<cons hello>, the library will be built before the program
+is linked, and, of course, C<gcc> will be used to compile both modules:
+
+
+
+ % cons hello
+ gcc -c hello.c -o hello.o
+ gcc -c world.c -o world.o
+ ar r libworld.a world.o
+ ar: creating libworld.a
+ ranlib libworld.a
+ gcc -o hello hello.o libworld.a
+
+
+=head2 Automatic and complete dependency analysis
+
+With Cons, dependencies are handled automatically. Continuing the previous
+example, note that when we modify F<world.c>, F<world.o> is recompiled,
+F<libworld.a> recreated, and F<hello> relinked:
+
+
+
+ % vi world.c
+ [EDIT]
+ % cons hello
+ gcc -c world.c -o world.o
+ ar r libworld.a world.o
+ ar: creating libworld.a
+ ranlib libworld.a
+ gcc -o hello hello.o libworld.a
+
+This is a relatively simple example: Cons ``knows'' F<world.o> depends upon
+F<world.c>, because the dependency is explicitly set up by the C<Library>
+method. It also knows that F<libworld.a> depends upon F<world.o> and that
+F<hello> depends upon F<libworld.a>, all for similar reasons.
+
+Now it turns out that F<hello.c> also includes the interface definition
+file, F<world.h>:
+
+
+
+ % emacs world.h
+ [EDIT]
+ % cons hello
+ gcc -c hello.c -o hello.o
+ gcc -o hello hello.o libworld.a
+
+How does Cons know that F<hello.c> includes F<world.h>, and that F<hello.o>
+must therefore be recompiled? For now, suffice it to say that when
+considering whether or not F<hello.o> is up-to-date, Cons invokes a scanner
+for its dependency, F<hello.c>. This scanner enumerates the files included
+by F<hello.c> to come up with a list of further dependencies, beyond those
+made explicit by the Cons script. This process is recursive: any files
+included by included files will also be scanned.
+
+Isn't this expensive? The answer is--it depends. If you do a full build of a
+large system, the scanning time is insignificant. If you do a rebuild of a
+large system, then Cons will spend a fair amount of time thinking about it
+before it decides that nothing has to be done (although not necessarily more
+time than make!). The good news is that Cons makes it very easy to
+intelligently subset your build, when you are working on localized changes.
+
+
+=head2 Automatic global build sequencing
+
+Because Cons does full and accurate dependency analysis, and does this
+globally, for the entire build, Cons is able to use this information to take
+full control of the B<sequencing> of the build. This sequencing is evident
+in the above examples, and is equivalent to what you would expect for make,
+given a full set of dependencies. With Cons, this extends trivially to
+larger, multi-directory builds. As a result, all of the complexity involved
+in making sure that a build is organized correctly--including multi-pass
+hierarchical builds--is eliminated. We'll discuss this further in the next
+sections.
+
+=head1 Building large trees--still just as simple
+
+
+=head2 A hierarchy of build scripts
+
+A larger build, in Cons, is organized by creating a hierarchy of B<build
+scripts>. At the top of the tree is a script called F<Construct>. The rest
+of the scripts, by convention, are each called F<Conscript>. These scripts
+are connected together, very simply, by the C<Build>, C<Export>, and
+C<Import> commands.
+
+
+=head2 The Build command
+
+The C<Build> command takes a list of F<Conscript> file names, and arranges
+for them to be included in the build. For example:
+
+ Build qw(
+ drivers/display/Conscript
+ drivers/mouse/Conscript
+ parser/Conscript
+ utilities/Conscript
+ );
+
+This is a simple two-level hierarchy of build scripts: all the subsidiary
+F<Conscript> files are mentioned in the top-level F<Construct> file. Notice
+that not all directories in the tree necessarily have build scripts
+associated with them.
+
+This could also be written as a multi-level script. For example, the
+F<Construct> file might contain this command:
+
+ Build qw(
+ parser/Conscript
+ drivers/Conscript
+ utilities/Conscript
+ );
+
+and the F<Conscript> file in the F<drivers> directory might contain this:
+
+ Build qw(
+ display/Conscript
+ mouse/Conscript
+ );
+
+Experience has shown that the former model is a little easier to understand,
+since the whole construction tree is laid out in front of you, at the
+top-level. Hybrid schemes are also possible. A separately maintained
+component that needs to be incorporated into a build tree, for example,
+might hook into the build tree in one place, but define its own construction
+hierarchy.
+
+By default, Cons does not change its working directory to the directory
+containing a subsidiary F<Conscript> file it is including. This behavior
+can be enabled for a build by specifying, in the top-level F<Construct>
+file:
+
+ Conscript_chdir 1;
+
+When enabled, Cons will change to the subsidiary F<Conscript> file's
+containing directory while reading in that file, and then change back
+to the top-level directory once the file has been processed.
+
+It is expected that this behavior will become the default in some future
+version of Cons. To prepare for this transition, builds that expect
+Cons to remain at the top of the build while it reads in a subsidiary
+F<Conscript> file should explicitly disable this feature as follows:
+
+ Conscript_chdir 0;
+
+
+=head2 Relative, top-relative, and absolute file names
+
+You may have noticed that the file names specified to the Build command are
+relative to the location of the script it is invoked from. This is generally
+true for other filename arguments to other commands, too, although we might
+as well mention here that if you begin a file name with a hash mark, ``#'',
+then that file is interpreted relative to the top-level directory (where the
+F<Construct> file resides). And, not surprisingly, if you begin it with ``/'',
+then it is considered to be an absolute pathname. This is true even on
+systems which use a back slash rather than a forward slash to name absolute
+paths.
+
+(There is another file prefix, ``!'', that is interpreted specially by
+Cons. See discussion of the C<Link> command, below, for details.)
+
+
+=head2 Using modules in build scripts
+
+You may pull modules into each F<Conscript> file using the normal Perl
+C<use> or C<require> statements:
+
+ use English;
+ require My::Module;
+
+Each C<use> or C<require> only affects the one F<Conscript> file in which
+it appears. To use a module in multiple F<Conscript> files, you must
+put a C<use> or C<require> statement in each one that needs the module.
+
+
+=head2 Scope of variables
+
+The top-level F<Construct> file and all F<Conscript> files begin life in
+a common, separate Perl package. B<Cons> controls the symbol table for
+the package so that, the symbol table for each script is empty, except
+for the F<Construct> file, which gets some of the command line arguments.
+All of the variables that are set or used, therefore, are set by the
+script itself--not by some external script.
+
+Variables can be explicitly B<imported> by a script from its parent
+script. To import a variable, it must have been B<exported> by the parent
+and initialized (otherwise an error will occur).
+
+
+=head2 The Export command
+
+The C<Export> command is used as in the following example:
+
+ $env = new cons();
+ $INCLUDE = "#export/include";
+ $LIB = "#export/lib";
+ Export qw( env INCLUDE LIB );
+ Build qw( util/Conscript );
+
+The values of the simple variables mentioned in the C<Export> list will be
+squirreled away by any subsequent C<Build> commands. The C<Export> command
+will only export Perl B<scalar> variables, that is, variables whose name
+begins with C<$>. Other variables, objects, etc. can be exported by
+reference--but all scripts will refer to the same object, and this object
+should be considered to be read-only by the subsidiary scripts and by the
+original exporting script. It's acceptable, however, to assign a new value
+to the exported scalar variable--that won't change the underlying variable
+referenced. This sequence, for example, is OK:
+
+ $env = new cons();
+ Export qw( env INCLUDE LIB );
+ Build qw( util/Conscript );
+ $env = new cons(CFLAGS => '-O');
+ Build qw( other/Conscript );
+
+It doesn't matter whether the variable is set before or after the C<Export>
+command. The important thing is the value of the variable at the time the
+C<Build> command is executed. This is what gets squirreled away. Any
+subsequent C<Export> commands, by the way, invalidate the first: you must
+mention all the variables you wish to export on each C<Export> command.
+
+
+=head2 The Import command
+
+Variables exported by the C<Export> command can be imported into subsidiary
+scripts by the C<Import> command. The subsidiary script always imports
+variables directly from the superior script. Consider this example:
+
+ Import qw( env INCLUDE );
+
+This is only legal if the parent script exported both C<$env> and
+C<$INCLUDE>. It also must have given each of these variables values. It is
+OK for the subsidiary script to only import a subset of the exported
+variables (in this example, C<$LIB>, which was exported by the previous
+example, is not imported).
+
+All the imported variables are automatically re-exported, so the sequence:
+
+ Import qw ( env INCLUDE );
+ Build qw ( beneath-me/Conscript );
+
+will supply both C<$env> and C<$INCLUDE> to the subsidiary file. If only
+C<$env> is to be exported, then the following will suffice:
+
+ Import qw ( env INCLUDE );
+ Export qw ( env );
+ Build qw ( beneath-me/Conscript );
+
+Needless to say, the variables may be modified locally before invoking
+C<Build> on the subsidiary script.
+
+
+=head2 Build script evaluation order
+
+The only constraint on the ordering of build scripts is that superior
+scripts are evaluated before their inferior scripts. The top-level
+F<Construct> file, for instance, is evaluated first, followed by any
+inferior scripts. This is all you really need to know about the evaluation
+order, since order is generally irrelevant. Consider the following C<Build>
+command:
+
+ Build qw(
+ drivers/display/Conscript
+ drivers/mouse/Conscript
+ parser/Conscript
+ utilities/Conscript
+ );
+
+We've chosen to put the script names in alphabetical order, simply because
+that's the most convenient for maintenance purposes. Changing the order will
+make no difference to the build.
+
+
+=head1 A Model for sharing files
+
+
+=head2 Some simple conventions
+
+In any complex software system, a method for sharing build products needs to
+be established. We propose a simple set of conventions which are trivial to
+implement with Cons, but very effective.
+
+The basic rule is to require that all build products which need to be shared
+between directories are shared via an intermediate directory. We have
+typically called this F<export>, and, in a C environment, provided
+conventional sub-directories of this directory, such as F<include>, F<lib>,
+F<bin>, etc.
+
+These directories are defined by the top-level F<Construct> file. A simple
+F<Construct> file for a B<Hello, World!> application, organized using
+multiple directories, might look like this:
+
+ # Construct file for Hello, World!
+
+ # Where to put all our shared products.
+ $EXPORT = '#export';
+
+ Export qw( CONS INCLUDE LIB BIN );
+
+ # Standard directories for sharing products.
+ $INCLUDE = "$EXPORT/include";
+ $LIB = "$EXPORT/lib";
+ $BIN = "$EXPORT/bin";
+
+ # A standard construction environment.
+ $CONS = new cons (
+ CPPPATH => $INCLUDE, # Include path for C Compilations
+ LIBPATH => $LIB, # Library path for linking programs
+ LIBS => '-lworld', # List of standard libraries
+ );
+
+ Build qw(
+ hello/Conscript
+ world/Conscript
+ );
+
+The F<world> directory's F<Conscript> file looks like this:
+
+ # Conscript file for directory world
+ Import qw( CONS INCLUDE LIB );
+
+ # Install the products of this directory
+ Install $CONS $LIB, 'libworld.a';
+ Install $CONS $INCLUDE, 'world.h';
+
+ # Internal products
+ Library $CONS 'libworld.a', 'world.c';
+
+and the F<hello> directory's F<Conscript> file looks like this:
+
+ # Conscript file for directory hello
+ Import qw( CONS BIN );
+
+ # Exported products
+ Install $CONS $BIN, 'hello';
+
+ # Internal products
+ Program $CONS 'hello', 'hello.c';
+
+To construct a B<Hello, World!> program with this directory structure, go to
+the top-level directory, and invoke C<cons> with the appropriate
+arguments. In the following example, we tell Cons to build the directory
+F<export>. To build a directory, Cons recursively builds all known products
+within that directory (only if they need rebuilding, of course). If any of
+those products depend upon other products in other directories, then those
+will be built, too.
+
+ % cons export
+ Install world/world.h as export/include/world.h
+ cc -Iexport/include -c hello/hello.c -o hello/hello.o
+ cc -Iexport/include -c world/world.c -o world/world.o
+ ar r world/libworld.a world/world.o
+ ar: creating world/libworld.a
+ ranlib world/libworld.a
+ Install world/libworld.a as export/lib/libworld.a
+ cc -o hello/hello hello/hello.o -Lexport/lib -lworld
+ Install hello/hello as export/bin/hello
+
+
+=head2 Clean, understandable, location-independent scripts
+
+You'll note that the two F<Conscript> files are very clean and
+to-the-point. They simply specify products of the directory and how to build
+those products. The build instructions are minimal: they specify which
+construction environment to use, the name of the product, and the name of
+the inputs. Note also that the scripts are location-independent: if you wish
+to reorganize your source tree, you are free to do so: you only have to
+change the F<Construct> file (in this example), to specify the new locations
+of the F<Conscript> files. The use of an export tree makes this goal easy.
+
+Note, too, how Cons takes care of little details for you. All the F<export>
+directories, for example, were made automatically. And the installed files
+were really hard-linked into the respective export directories, to save
+space and time. This attention to detail saves considerable work, and makes
+it even easier to produce simple, maintainable scripts.
+
+
+=head1 Separating source and build trees
+
+It's often desirable to keep any derived files from the build completely
+separate from the source files. This makes it much easier to keep track of
+just what is a source file, and also makes it simpler to handle B<variant>
+builds, especially if you want the variant builds to co-exist.
+
+
+=head2 Separating build and source directories using the Link command
+
+Cons provides a simple mechanism that handles all of these requirements. The
+C<Link> command is invoked as in this example:
+
+ Link 'build' => 'src';
+
+The specified directories are ``linked'' to the specified source
+directory. Let's suppose that you setup a source directory, F<src>, with the
+sub-directories F<world> and F<hello> below it, as in the previous
+example. You could then substitute for the original build lines the
+following:
+
+ Build qw(
+ build/world/Conscript
+ build/hello/Conscript
+ );
+
+Notice that you treat the F<Conscript> file as if it existed in the build
+directory. Now if you type the same command as before, you will get the
+following results:
+
+ % cons export
+ Install build/world/world.h as export/include/world.h
+ cc -Iexport/include -c build/hello/hello.c -o build/hello/hello.o
+ cc -Iexport/include -c build/world/world.c -o build/world/world.o
+ ar r build/world/libworld.a build/world/world.o
+ ar: creating build/world/libworld.a
+ ranlib build/world/libworld.a
+ Install build/world/libworld.a as export/lib/libworld.a
+ cc -o build/hello/hello build/hello/hello.o -Lexport/lib -lworld
+ Install build/hello/hello as export/bin/hello
+
+Again, Cons has taken care of the details for you. In particular, you will
+notice that all the builds are done using source files and object files from
+the build directory. For example, F<build/world/world.o> is compiled from
+F<build/world/world.c>, and F<export/include/world.h> is installed from
+F<build/world/world.h>. This is accomplished on most systems by the simple
+expedient of ``hard'' linking the required files from each source directory
+into the appropriate build directory.
+
+The links are maintained correctly by Cons, no matter what you do to the
+source directory. If you modify a source file, your editor may do this ``in
+place'' or it may rename it first and create a new file. In the latter case,
+any hard link will be lost. Cons will detect this condition the next time
+the source file is needed, and will relink it appropriately.
+
+You'll also notice, by the way, that B<no> changes were required to the
+underlying F<Conscript> files. And we can go further, as we shall see in the
+next section.
+
+=head2 Explicit references to the source directory
+
+When using the C<Link> command on some operating systems or with some
+tool chains, it's sometimes useful to have a command actually use
+the path name to the source directory, not the build directory. For
+example, on systems that must copy, not "hard link," the F<src/> and
+F<build/> copies of C<Linked> files, using the F<src/> path of a file
+name might make an editor aware that a syntax error must be fixed in the
+source directory, not the build directory.
+
+You can tell Cons that you want to use the "source path" for a file by
+preceding the file name with a ``!'' (exclamation point). For example,
+if we add a ``!'' to the beginning of a source file:
+
+ Program $env "foo", "!foo.c"; # Notice initial ! on foo.c
+
+Cons will compile the target as follows:
+
+ cc -c src/foo.c -o build/foo.o
+ cc -o build/foo build/foo.o
+
+Notice that Cons has compiled the program from the the F<src/foo.c>
+source file. Without the initial ``!'', Cons would have compiled the
+program using the F<build/foo.c> path name.
+
+
+
+=head1 Variant builds
+
+
+=head2 Hello, World! for baNaNa and peAcH OS's
+
+Variant builds require just another simple extension. Let's take as an
+example a requirement to allow builds for both the baNaNa and peAcH
+operating systems. In this case, we are using a distributed file system,
+such as NFS to access the particular system, and only one or the other of
+the systems has to be compiled for any given invocation of C<cons>. Here's
+one way we could set up the F<Construct> file for our B<Hello, World!>
+application:
+
+ # Construct file for Hello, World!
+
+ die qq(OS must be specified) unless $OS = $ARG{OS};
+ die qq(OS must be "peach" or "banana")
+ if $OS ne "peach" && $OS ne "banana";
+
+ # Where to put all our shared products.
+ $EXPORT = "#export/$OS";
+
+ Export qw( CONS INCLUDE LIB BIN );
+
+ # Standard directories for sharing products.
+ $INCLUDE = "$EXPORT/include";
+ $LIB = "$EXPORT/lib";
+ $BIN = "$EXPORT/bin";
+
+ # A standard construction environment.
+ $CONS = new cons (
+ CPPPATH => $INCLUDE, # Include path for C Compilations
+ LIBPATH => $LIB, # Library path for linking programs
+ LIBS => '-lworld', # List of standard libraries
+ );
+
+ # $BUILD is where we will derive everything.
+ $BUILD = "#build/$OS";
+
+ # Tell cons where the source files for $BUILD are.
+ Link $BUILD => 'src';
+
+ Build (
+ "$BUILD/hello/Conscript",
+ "$BUILD/world/Conscript",
+ );
+
+Now if we login to a peAcH system, we can build our B<Hello, World!>
+application for that platform:
+
+ % cons export OS=peach
+ Install build/peach/world/world.h as export/peach/include/world.h
+ cc -Iexport/peach/include -c build/peach/hello/hello.c -o build/peach/hello/hello.o
+ cc -Iexport/peach/include -c build/peach/world/world.c -o build/peach/world/world.o
+ ar r build/peach/world/libworld.a build/peach/world/world.o
+ ar: creating build/peach/world/libworld.a
+ ranlib build/peach/world/libworld.a
+ Install build/peach/world/libworld.a as export/peach/lib/libworld.a
+ cc -o build/peach/hello/hello build/peach/hello/hello.o -Lexport/peach/lib -lworld
+ Install build/peach/hello/hello as export/peach/bin/hello
+
+
+=head2 Variations on a theme
+
+Other variations of this model are possible. For example, you might decide
+that you want to separate out your include files into platform dependent and
+platform independent files. In this case, you'd have to define an
+alternative to C<$INCLUDE> for platform-dependent files. Most F<Conscript>
+files, generating purely platform-independent include files, would not have
+to change.
+
+You might also want to be able to compile your whole system with debugging
+or profiling, for example, enabled. You could do this with appropriate
+command line options, such as C<DEBUG=on>. This would then be translated
+into the appropriate platform-specific requirements to enable debugging
+(this might include turning off optimization, for example). You could
+optionally vary the name space for these different types of systems, but, as
+we'll see in the next section, it's not B<essential> to do this, since Cons
+is pretty smart about rebuilding things when you change options.
+
+
+=head1 Signatures
+
+Cons uses file B<signatures> to decide if a derived file is out-of-date
+and needs rebuilding. In essence, if the contents of a file change,
+or the manner in which the file is built changes, the file's signature
+changes as well. This allows Cons to decide with certainty when a file
+needs rebuilding, because Cons can detect, quickly and reliably, whether
+any of its dependency files have been changed.
+
+
+=head2 MD5 content and build signatures
+
+Cons uses the B<MD5> (B<Message Digest 5>) algorithm to compute file
+signatures. The MD5 algorithm computes a strong cryptographic checksum
+for any given input string. Cons can, based on configuration, use two
+different MD5 signatures for a given file:
+
+The B<content signature> of a file is an MD5 checksum of the file's
+contents. Consequently, when the contents of a file change, its content
+signature changes as well.
+
+The B<build signature> of a file is a combined MD5 checksum of:
+
+=over 4
+
+the signatures of all the input files used to build the file
+
+the signatures of all dependency files discovered by source scanners
+(for example, C<.h> files)
+
+the signatures of all dependency files specified explicitly via the
+C<Depends> method)
+
+the command-line string used to build the file
+
+=back
+
+The build signature is, in effect, a digest of all the dependency
+information for the specified file. Consequently, a file's build
+signature changes whenever any part of its dependency information
+changes: a new file is added, the contents of a file on which it depends
+change, there's a change to the command line used to build the file (or
+any of its dependency files), etc.
+
+For example, in the previous section, the build signature of the
+F<world.o> file will include:
+
+=over 4
+
+the signature of the F<world.c> file
+
+the signatures of any header files that Cons detects are included,
+directly or indirectly, by F<world.c>
+
+the text of the actual command line was used to generate F<world.o>
+
+=back
+
+Similarly, the build signature of the F<libworld.a> file will include
+all the signatures of its constituents (and hence, transitively, the
+signatures of B<their> constituents), as well as the command line that
+created the file.
+
+Note that there is no need for a derived file to depend upon any
+particular F<Construct> or F<Conscript> file. If changes to these files
+affect a file, then this will be automatically reflected in its build
+signature, since relevant parts of the command line are included in the
+signature. Unrelated F<Construct> or F<Conscript> changes will have no
+effect.
+
+
+=head2 Storing signatures in .consign files
+
+Before Cons exits, it stores the calculated signatures for all of the
+files it built or examined in F<.consign> files, one per directory.
+Cons uses this stored information on later invocations to decide if
+derived files need to be rebuilt.
+
+After the previous example was compiled, the F<.consign> file in the
+F<build/peach/world> directory looked like this:
+
+ world.h:985533370 - d181712f2fdc07c1f05d97b16bfad904
+ world.o:985533372 2a0f71e0766927c0532977b0d2158981
+ world.c:985533370 - c712f77189307907f4189b5a7ab62ff3
+ libworld.a:985533374 69e568fc5241d7d25be86d581e1fb6aa
+
+After the file name and colon, the first number is a timestamp of the
+file's modification time (on UNIX systems, this is typically the number
+of seconds since January 1st, 1970). The second value is the build
+signature of the file (or ``-'' in the case of files with no build
+signature--that is, source files). The third value, if any, is the
+content signature of the file.
+
+
+=head2 Using build signatures to decide when to rebuild files
+
+When Cons is deciding whether to build or rebuild a derived file, it
+first computes the file's current build signature. If the file doesn't
+exist, it must obviously be built.
+
+If, however, the file already exists, Cons next compares the
+modification timestamp of the file against the timestamp value in
+the F<.consign> file. If the timestamps match, Cons compares the
+newly-computed build signature against the build signature in the
+F<.consign> file. If the timestamps do not match or the build
+signatures do not match, the derived file is rebuilt.
+
+After the file is built or rebuilt, Cons arranges to store the
+newly-computed build signature in the F<.consign> file when it exits.
+
+
+=head2 Signature example
+
+The use of these signatures is an extremely simple, efficient, and
+effective method of improving--dramatically--the reproducibility of a
+system.
+
+We'll demonstrate this with a simple example:
+
+ # Simple "Hello, World!" Construct file
+ $CFLAGS = '-g' if $ARG{DEBUG} eq 'on';
+ $CONS = new cons(CFLAGS => $CFLAGS);
+ Program $CONS 'hello', 'hello.c';
+
+Notice how Cons recompiles at the appropriate times:
+
+ % cons hello
+ cc -c hello.c -o hello.o
+ cc -o hello hello.o
+ % cons hello
+ cons: "hello" is up-to-date.
+ % cons DEBUG=on hello
+ cc -g -c hello.c -o hello.o
+ cc -o hello hello.o
+ % cons DEBUG=on hello
+ cons: "hello" is up-to-date.
+ % cons hello
+ cc -c hello.c -o hello.o
+ cc -o hello hello.o
+
+
+=head2 Source-file signature configuration
+
+Cons provides a C<SourceSignature> method that allows you to configure
+how the signature should be calculated for any source file when its
+signature is being used to decide if a dependent file is up-to-date.
+The arguments to the C<SourceSignature> method consist of one or more
+pairs of strings:
+
+ SourceSignature 'auto/*.c' => 'content',
+ '*' => 'stored-content';
+
+The first string in each pair is a pattern to match against derived file
+path names. The pattern is a file-globbing pattern, not a Perl regular
+expression; the pattern <*.l> will match all Lex source files. The C<*>
+wildcard will match across directory separators; the pattern C<foo/*.c>
+would match all C source files in any subdirectory underneath the C<foo>
+subdirectory.
+
+The second string in each pair contains one of the following keywords to
+specify how signatures should be calculated for source files that match
+the pattern. The available keywords are:
+
+=over 4
+
+=item content
+
+Use the content signature of the source file when calculating signatures
+of files that depend on it. This guarantees correct calculation of the
+file's signature for all builds, by telling Cons to read the contents of
+a source file to calculate its content signature each time it is run.
+
+=item stored-content
+
+Use the source file's content signature as stored in the F<.consign>
+file, provided the file's timestamp matches the cached timestamp value
+in the F<.consign> file. This optimizes performance, with the slight
+risk of an incorrect build if a source file's contents have been changed
+so quickly after its previous update that the timestamp still matches
+the stored timestamp in the F<.consign> file even though the contents
+have changed.
+
+=back
+
+The Cons default behavior of always calculating a source file's
+signature from the file's contents is equivalent to specifying:
+
+ SourceSignature '*' => 'content';
+
+The C<*> will match all source files. The C<content> keyword
+specifies that Cons will read the contents of a source file to calculate
+its signature each time it is run.
+
+A useful global performance optimization is:
+
+ SourceSignature '*' => 'stored-content';
+
+This specifies that Cons will use pre-computed content signatures
+from F<.consign> files, when available, rather than re-calculating a
+signature from the the source file's contents each time Cons is run. In
+practice, this is safe for most build situations, and only a problem
+when source files are changed automatically (by scripts, for example).
+The Cons default, however, errs on the side of guaranteeing a correct
+build in all situations.
+
+Cons tries to match source file path names against the patterns in the
+order they are specified in the C<SourceSignature> arguments:
+
+ SourceSignature '/usr/repository/objects/*' => 'stored-content',
+ '/usr/repository/*' => 'content',
+ '*.y' => 'content',
+ '*' => 'stored-content';
+
+In this example, all source files under the F</usr/repository/objects>
+directory will use F<.consign> file content signatures, source files
+anywhere else underneath F</usr/repository> will not use F<.consign>
+signature values, all Yacc source files (C<*.y>) anywhere else will not
+use F<.consign> signature values, and any other source file will use
+F<.consign> signature values.
+
+
+=head2 Derived-file signature configuration
+
+Cons provides a C<SIGNATURE> construction variable that allows you to
+configure how signatures are calculated for any derived file when its
+signature is being used to decide if a dependent file is up-to-date.
+The value of the C<SIGNATURE> construction variable is a Perl array
+reference that holds one or more pairs of strings, like the arguments to
+the C<SourceSignature> method.
+
+The first string in each pair is a pattern to match against derived file
+path names. The pattern is a file-globbing pattern, not a Perl regular
+expression; the pattern `*.obj' will match all (Win32) object files.
+The C<*> wildcard will match across directory separators; the pattern
+`foo/*.a' would match all (UNIX) library archives in any subdirectory
+underneath the foo subdirectory.
+
+The second string in each pair contains one of the following keywords
+to specify how signatures should be calculated for derived files that
+match the pattern. The available keywords are the same as for the
+C<SourceSignature> method, with an additional keyword:
+
+=over 4
+
+=item build
+
+Use the build signature of the derived file when calculating signatures
+of files that depend on it. This guarantees correct builds by forcing
+Cons to rebuild any and all files that depend on the derived file.
+
+=item content
+
+Use the content signature of the derived file when calculating signatures
+of files that depend on it. This guarantees correct calculation of the
+file's signature for all builds, by telling Cons to read the contents of
+a derived file to calculate its content signature each time it is run.
+
+=item stored-content
+
+Use the derived file's content signature as stored in the F<.consign>
+file, provided the file's timestamp matches the cached timestamp value
+in the F<.consign> file. This optimizes performance, with the slight
+risk of an incorrect build if a derived file's contents have been
+changed so quickly after a Cons build that the file's timestamp still
+matches the stored timestamp in the F<.consign> file.
+
+=back
+
+The Cons default behavior (as previously described) for using
+derived-file signatures is equivalent to:
+
+ $env = new cons(SIGNATURE => ['*' => 'build']);
+
+The C<*> will match all derived files. The C<build> keyword specifies
+that all derived files' build signatures will be used when calculating
+whether a dependent file is up-to-date.
+
+A useful alternative default C<SIGNATURE> configuration for many sites:
+
+ $env = new cons(SIGNATURE => ['*' => 'content']);
+
+In this configuration, derived files have their signatures calculated
+from the file contents. This adds slightly to Cons' workload, but has
+the useful effect of "stopping" further rebuilds if a derived file is
+rebuilt to exactly the same file contents as before, which usually
+outweighs the additional computation Cons must perform.
+
+For example, changing a comment in a C file and recompiling should
+generate the exact same object file (assuming the compiler doesn't
+insert a timestamp in the object file's header). In that case,
+specifying C<content> or C<stored-content> for the signature calculation
+will cause Cons to recognize that the object file did not actually
+change as a result of being rebuilt, and libraries or programs that
+include the object file will not be rebuilt. When C<build> is
+specified, however, Cons will only "know" that the object file was
+rebuilt, and proceed to rebuild any additional files that include the
+object file.
+
+Note that Cons tries to match derived file path names against the
+patterns in the order they are specified in the C<SIGNATURE> array
+reference:
+
+ $env = new cons(SIGNATURE => ['foo/*.o' => 'build',
+ '*.o' => 'content',
+ '*.a' => 'stored-content',
+ '*' => 'content']);
+
+In this example, all object files underneath the F<foo> subdirectory
+will use build signatures, all other object files (including object
+files underneath other subdirectories!) will use F<.consign> file
+content signatures, libraries will use F<.consign> file build
+signatures, and all other derived files will use content signatures.
+
+
+=head2 Debugging signature calculation
+
+Cons provides a C<-S> option that can be used to specify what internal
+Perl package Cons should use to calculate signatures. The default Cons
+behavior is equivalent to specifying C<-S md5> on the command line.
+
+The only other package (currently) available is an C<md5::debug>
+package that prints out detailed information about the MD5 signature
+calculations performed by Cons:
+
+ % cons -S md5::debug hello
+ sig::md5::srcsig(hello.c)
+ => |52d891204c62fe93ecb95281e1571938|
+ sig::md5::collect(52d891204c62fe93ecb95281e1571938)
+ => |fb0660af4002c40461a2f01fbb5ffd03|
+ sig::md5::collect(52d891204c62fe93ecb95281e1571938,
+ fb0660af4002c40461a2f01fbb5ffd03,
+ cc -c %< -o %>)
+ => |f7128da6c3fe3c377dc22ade70647b39|
+ sig::md5::current(||
+ eq |f7128da6c3fe3c377dc22ade70647b39|)
+ cc -c hello.c -o hello.o
+ sig::md5::collect()
+ => |d41d8cd98f00b204e9800998ecf8427e|
+ sig::md5::collect(f7128da6c3fe3c377dc22ade70647b39,
+ d41d8cd98f00b204e9800998ecf8427e,
+ cc -o %> %< )
+ => |a0bdce7fd09e0350e7efbbdb043a00b0|
+ sig::md5::current(||
+ eq |a0bdce7fd09e0350e7efbbdb043a00b0|)
+ cc -o hello, hello.o
+
+
+=head1 Code Repositories
+
+Many software development organizations will have one or more central
+repository directory trees containing the current source code for one or
+more projects, as well as the derived object files, libraries, and
+executables. In order to reduce unnecessary recompilation, it is useful to
+use files from the repository to build development software--assuming, of
+course, that no newer dependency file exists in the local build tree.
+
+
+=head2 Repository
+
+Cons provides a mechanism to specify a list of code repositories that will
+be searched, in-order, for source files and derived files not found in the
+local build directory tree.
+
+The following lines in a F<Construct> file will instruct Cons to look first
+under the F</usr/experiment/repository> directory and then under the
+F</usr/product/repository> directory:
+
+ Repository qw (
+ /usr/experiment/repository
+ /usr/product/repository
+ );
+
+The repository directories specified may contain source files, derived files
+(objects, libraries and executables), or both. If there is no local file
+(source or derived) under the directory in which Cons is executed, then the
+first copy of a same-named file found under a repository directory will be
+used to build any local derived files.
+
+Cons maintains one global list of repositories directories. Cons will
+eliminate the current directory, and any non-existent directories, from the
+list.
+
+
+=head2 Finding the Construct file in a Repository
+
+Cons will also search for F<Construct> and F<Conscript> files in the
+repository tree or trees. This leads to a chicken-and-egg situation,
+though: how do you look in a repository tree for a F<Construct> file if the
+F<Construct> file tells you where the repository is? To get around this,
+repositories may be specified via C<-R> options on the command line:
+
+ % cons -R /usr/experiment/repository -R /usr/product/repository .
+
+Any repository directories specified in the F<Construct> or F<Conscript>
+files will be appended to the repository directories specified by
+command-line C<-R> options.
+
+=head2 Repository source files
+
+If the source code (include the F<Conscript> file) for the library version
+of the I<Hello, World!> C application is in a repository (with no derived
+files), Cons will use the repository source files to create the local object
+files and executable file:
+
+ % cons -R /usr/src_only/repository hello
+ gcc -c /usr/src_only/repository/hello.c -o hello.o
+ gcc -c /usr/src_only/repository/world.c -o world.o
+ ar r libworld.a world.o
+ ar: creating libworld.a
+ ranlib libworld.a
+ gcc -o hello hello.o libworld.a
+
+Creating a local source file will cause Cons to rebuild the appropriate
+derived file or files:
+
+ % pico world.c
+ [EDIT]
+ % cons -R /usr/src_only/repository hello
+ gcc -c world.c -o world.o
+ ar r libworld.a world.o
+ ar: creating libworld.a
+ ranlib libworld.a
+ gcc -o hello hello.o libworld.a
+
+And removing the local source file will cause Cons to revert back to
+building the derived files from the repository source:
+
+ % rm world.c
+ % cons -R /usr/src_only/repository hello
+ gcc -c /usr/src_only/repository/world.c -o world.o
+ ar r libworld.a world.o
+ ar: creating libworld.a
+ ranlib libworld.a
+ gcc -o hello hello.o libworld.a
+
+
+=head2 Repository derived files
+
+If a repository tree contains derived files (usually object files,
+libraries, or executables), Cons will perform its normal signature
+calculation to decide whether the repository file is up-to-date or a derived
+file must be built locally. This means that, in order to ensure correct
+signature calculation, a repository tree must also contain the F<.consign>
+files that were created by Cons when generating the derived files.
+
+This would usually be accomplished by building the software in the
+repository (or, alternatively, in a build directory, and then copying the
+result to the repository):
+
+ % cd /usr/all/repository
+ % cons hello
+ gcc -c hello.c -o hello.o
+ gcc -c world.c -o world.o
+ ar r libworld.a world.o
+ ar: creating libworld.a
+ ranlib libworld.a
+ gcc -o hello hello.o libworld.a
+
+(This is safe even if the F<Construct> file lists the F</usr/all/repository>
+directory in a C<Repository> command because Cons will remove the current
+directory from the repository list.)
+
+Now if we want to build a copy of the application with our own F<hello.c>
+file, we only need to create the one necessary source file, and use the
+C<-R> option to have Cons use other files from the repository:
+
+ % mkdir $HOME/build1
+ % cd $HOME/build1
+ % ed hello.c
+ [EDIT]
+ % cons -R /usr/all/repository hello
+ gcc -c hello.c -o hello.o
+ gcc -o hello hello.o /usr/all/repository/libworld.a
+
+Notice that Cons has not bothered to recreate a local F<libworld.a> library
+(or recompile the F<world.o> module), but instead uses the already-compiled
+version from the repository.
+
+Because the MD5 signatures that Cons puts in the F<.consign> file contain
+timestamps for the derived files, the signature timestamps must match the
+file timestamps for a signature to be considered valid.
+
+Some software systems may alter the timestamps on repository files (by
+copying them, e.g.), in which case Cons will, by default, assume the
+repository signatures are invalid and rebuild files unnecessarily. This
+behavior may be altered by specifying:
+
+ Repository_Sig_Times_OK 0;
+
+This tells Cons to ignore timestamps when deciding whether a signature is
+valid. (Note that avoiding this sanity check means there must be proper
+control over the repository tree to ensure that the derived files cannot be
+modified without updating the F<.consign> signature.)
+
+
+=head2 Local copies of files
+
+If the repository tree contains the complete results of a build, and we try
+to build from the repository without any files in our local tree, something
+moderately surprising happens:
+
+ % mkdir $HOME/build2
+ % cd $HOME/build2
+ % cons -R /usr/all/repository hello
+ cons: "hello" is up-to-date.
+
+Why does Cons say that the F<hello> program is up-to-date when there is no
+F<hello> program in the local build directory? Because the repository (not
+the local directory) contains the up-to-date F<hello> program, and Cons
+correctly determines that nothing needs to be done to rebuild this
+up-to-date copy of the file.
+
+There are, however, many times in which it is appropriate to ensure that a
+local copy of a file always exists. A packaging or testing script, for
+example, may assume that certain generated files exist locally. Instead of
+making these subsidiary scripts aware of the repository directory, the
+C<Local> command may be added to a F<Construct> or F<Conscript> file to
+specify that a certain file or files must appear in the local build
+directory:
+
+ Local qw(
+ hello
+ );
+
+Then, if we re-run the same command, Cons will make a local copy of the
+program from the repository copy (telling you that it is doing so):
+
+ % cons -R /usr/all/repository hello
+ Local copy of hello from /usr/all/repository/hello
+ cons: "hello" is up-to-date.
+
+Notice that, because the act of making the local copy is not considered a
+"build" of the F<hello> file, Cons still reports that it is up-to-date.
+
+Creating local copies is most useful for files that are being installed into
+an intermediate directory (for sharing with other directories) via the
+C<Install> command. Accompanying the C<Install> command for a file with a
+companion C<Local> command is so common that Cons provides a
+C<Install_Local> command as a convenient way to do both:
+
+ Install_Local $env, '#export', 'hello';
+
+is exactly equivalent to:
+
+ Install $env '#export', 'hello';
+ Local '#export/hello';
+
+Both the C<Local> and C<Install_Local> commands update the local F<.consign>
+file with the appropriate file signatures, so that future builds are
+performed correctly.
+
+
+=head2 Repository dependency analysis
+
+Due to its built-in scanning, Cons will search the specified repository
+trees for included F<.h> files. Unless the compiler also knows about the
+repository trees, though, it will be unable to find F<.h> files that only
+exist in a repository. If, for example, the F<hello.c> file includes the
+F<hello.h> file in its current directory:
+
+ % cons -R /usr/all/repository hello
+ gcc -c /usr/all/repository/hello.c -o hello.o
+ /usr/all/repository/hello.c:1: hello.h: No such file or directory
+
+Solving this problem forces some requirements onto the way construction
+environments are defined and onto the way the C C<#include> preprocessor
+directive is used to include files.
+
+In order to inform the compiler about the repository trees, Cons will add
+appropriate C<-I> flags to the compilation commands. This means that the
+C<CPPPATH> variable in the construction environment must explicitly specify
+all subdirectories which are to be searched for included files, including the
+current directory. Consequently, we can fix the above example by changing
+the environment creation in the F<Construct> file as follows:
+
+ $env = new cons(
+ CC => 'gcc',
+ CPPPATH => '.',
+ LIBS => 'libworld.a',
+ );
+
+Due to the definition of the C<CPPPATH> variable, this yields, when we
+re-execute the command:
+
+ % cons -R /usr/all/repository hello
+ gcc -c -I. -I/usr/all/repository /usr/all/repository/hello.c -o hello.o
+ gcc -o hello hello.o /usr/all/repository/libworld.a
+
+The order of the C<-I> flags replicates, for the C preprocessor, the same
+repository-directory search path that Cons uses for its own dependency
+analysis. If there are multiple repositories and multiple C<CPPPATH>
+directories, Cons will append the repository directories to the beginning of
+each C<CPPPATH> directory, rapidly multiplying the number of C<-I> flags.
+As an extreme example, a F<Construct> file containing:
+
+ Repository qw(
+ /u1
+ /u2
+ );
+
+ $env = new cons(
+ CPPPATH => 'a:b:c',
+ );
+
+Would yield a compilation command of:
+
+ cc -Ia -I/u1/a -I/u2/a -Ib -I/u1/b -I/u2/b -Ic -I/u1/c -I/u2/c -c hello.c -o hello.o
+
+In order to shorten the command lines as much as possible, Cons will
+remove C<-I> flags for any directories, locally or in the repositories,
+which do not actually exist. (Note that the C<-I> flags are not included
+in the MD5 signature calculation for the target file, so the target will
+not be recompiled if the compilation command changes due to a directory
+coming into existence.)
+
+Because Cons relies on the compiler's C<-I> flags to communicate the
+order in which repository directories must be searched, Cons' handling
+of repository directories is fundamentally incompatible with using
+double-quotes on the C<#include> directives in any C source code that
+you plan to modify:
+
+ #include "file.h" /* DON'T USE DOUBLE-QUOTES LIKE THIS */
+
+This is because most C preprocessors, when faced with such a directive, will
+always first search the directory containing the source file. This
+undermines the elaborate C<-I> options that Cons constructs to make the
+preprocessor conform to its preferred search path.
+
+Consequently, when using repository trees in Cons, B<always> use
+angle-brackets for included files in any C source (.c or .h) files that
+you plan to modify locally:
+
+ #include <file.h> /* USE ANGLE-BRACKETS INSTEAD */
+
+Code that will not change can still safely use double quotes on #include
+lines.
+
+
+=head2 Repository_List
+
+Cons provides a C<Repository_List> command to return a list of all
+repository directories in their current search order. This can be used for
+debugging, or to do more complex Perl stuff:
+
+ @list = Repository_List;
+ print join(' ', @list), "\n";
+
+
+=head2 Repository interaction with other Cons features
+
+Cons' handling of repository trees interacts correctly with other Cons
+features--which is to say, it generally does what you would expect.
+
+Most notably, repository trees interact correctly, and rather powerfully,
+with the 'Link' command. A repository tree may contain one or more
+subdirectories for version builds established via C<Link> to a source
+subdirectory. Cons will search for derived files in the appropriate build
+subdirectories under the repository tree.
+
+
+=head1 Default targets
+
+Until now, we've demonstrated invoking Cons with an explicit target
+to build:
+
+ % cons hello
+
+Normally, Cons does not build anything unless a target is specified,
+but specifying '.' (the current directory) will build everything:
+
+ % cons # does not build anything
+
+ % cons . # builds everything under the top-level directory
+
+Adding the C<Default> method to any F<Construct> or F<Conscript> file will add
+the specified targets to a list of default targets. Cons will build
+these defaults if there are no targets specified on the command line.
+So adding the following line to the top-level F<Construct> file will mimic
+Make's typical behavior of building everything by default:
+
+ Default '.';
+
+The following would add the F<hello> and F<goodbye> commands (in the
+same directory as the F<Construct> or F<Conscript> file) to the default list:
+
+ Default qw(
+ hello
+ goodbye
+ );
+
+The C<Default> method may be used more than once to add targets to the
+default list.
+
+=head1 Selective builds
+
+Cons provides two methods for reducing the size of given build. The first is
+by specifying targets on the command line, and the second is a method for
+pruning the build tree. We'll consider target specification first.
+
+
+=head2 Selective targeting
+
+Like make, Cons allows the specification of ``targets'' on the command
+line. Cons targets may be either files or directories. When a directory is
+specified, this is simply a short-hand notation for every derivable
+product--that Cons knows about--in the specified directory and below. For
+example:
+
+ % cons build/hello/hello.o
+
+means build F<hello.o> and everything that F<hello.o> might need. This is
+from a previous version of the B<Hello, World!> program in which F<hello.o>
+depended upon F<export/include/world.h>. If that file is not up-to-date
+(because someone modified F<src/world/world.h)>, then it will be rebuilt,
+even though it is in a directory remote from F<build/hello>.
+
+In this example:
+
+ % cons build
+
+Everything in the F<build> directory is built, if necessary. Again, this may
+cause more files to be built. In particular, both F<export/include/world.h>
+and F<export/lib/libworld.a> are required by the F<build/hello> directory,
+and so they will be built if they are out-of-date.
+
+If we do, instead:
+
+ % cons export
+
+then only the files that should be installed in the export directory will be
+rebuilt, if necessary, and then installed there. Note that C<cons build>
+might build files that C<cons export> doesn't build, and vice-versa.
+
+
+=head2 No ``special'' targets
+
+With Cons, make-style ``special'' targets are not required. The simplest
+analog with Cons is to use special F<export> directories, instead. Let's
+suppose, for example, that you have a whole series of unit tests that are
+associated with your code. The tests live in the source directory near the
+code. Normally, however, you don't want to build these tests. One solution
+is to provide all the build instructions for creating the tests, and then to
+install the tests into a separate part of the tree. If we install the tests
+in a top-level directory called F<tests>, then:
+
+ % cons tests
+
+will build all the tests.
+
+ % cons export
+
+will build the production version of the system (but not the tests), and:
+
+ % cons build
+
+should probably be avoided (since it will compile tests unnecessarily).
+
+If you want to build just a single test, then you could explicitly name the
+test (in either the F<tests> directory or the F<build> directory). You could
+also aggregate the tests into a convenient hierarchy within the tests
+directory. This hierarchy need not necessarily match the source hierarchy,
+in much the same manner that the include hierarchy probably doesn't match
+the source hierarchy (the include hierarchy is unlikely to be more than two
+levels deep, for C programs).
+
+If you want to build absolutely everything in the tree (subject to whatever
+options you select), you can use:
+
+ % cons .
+
+This is not particularly efficient, since it will redundantly walk all the
+trees, including the source tree. The source tree, of course, may have
+buildable objects in it--nothing stops you from doing this, even if you
+normally build in a separate build tree.
+
+
+=head1 Build Pruning
+
+In conjunction with target selection, B<build pruning> can be used to reduce
+the scope of the build. In the previous peAcH and baNaNa example, we have
+already seen how script-driven build pruning can be used to make only half
+of the potential build available for any given invocation of C<cons>. Cons
+also provides, as a convenience, a command line convention that allows you
+to specify which F<Conscript> files actually get ``built''--that is,
+incorporated into the build tree. For example:
+
+ % cons build +world
+
+The C<+> argument introduces a Perl regular expression. This must, of
+course, be quoted at the shell level if there are any shell meta-characters
+within the expression. The expression is matched against each F<Conscript>
+file which has been mentioned in a C<Build> statement, and only those
+scripts with matching names are actually incorporated into the build
+tree. Multiple such arguments are allowed, in which case a match against any
+of them is sufficient to cause a script to be included.
+
+In the example, above, the F<hello> program will not be built, since Cons
+will have no knowledge of the script F<hello/Conscript>. The F<libworld.a>
+archive will be built, however, if need be.
+
+There are a couple of uses for build pruning via the command line. Perhaps
+the most useful is the ability to make local changes, and then, with
+sufficient knowledge of the consequences of those changes, restrict the size
+of the build tree in order to speed up the rebuild time. A second use for
+build pruning is to actively prevent the recompilation of certain files that
+you know will recompile due to, for example, a modified header file. You may
+know that either the changes to the header file are immaterial, or that the
+changes may be safely ignored for most of the tree, for testing
+purposes.With Cons, the view is that it is pragmatic to admit this type of
+behavior, with the understanding that on the next full build everything that
+needs to be rebuilt will be. There is no equivalent to a ``make touch''
+command, to mark files as permanently up-to-date. So any risk that is
+incurred by build pruning is mitigated. For release quality work, obviously,
+we recommend that you do not use build pruning (it's perfectly OK to use
+during integration, however, for checking compilation, etc. Just be sure to
+do an unconstrained build before committing the integration).
+
+
+=head1 Temporary overrides
+
+Cons provides a very simple mechanism for overriding aspects of a build. The
+essence is that you write an override file containing one or more
+C<Override> commands, and you specify this on the command line, when you run
+C<cons>:
+
+ % cons -o over export
+
+will build the F<export> directory, with all derived files subject to the
+overrides present in the F<over> file. If you leave out the C<-o> option,
+then everything necessary to remove all overrides will be rebuilt.
+
+
+=head2 Overriding environment variables
+
+The override file can contain two types of overrides. The first is incoming
+environment variables. These are normally accessible by the F<Construct>
+file from the C<%ENV> hash variable. These can trivially be overridden in
+the override file by setting the appropriate elements of C<%ENV> (these
+could also be overridden in the user's environment, of course).
+
+
+=head2 The Override command
+
+The second type of override is accomplished with the C<Override> command,
+which looks like this:
+
+ Override <regexp>, <var1> => <value1>, <var2> => <value2>, ...;
+
+The regular expression I<regexp> is matched against every derived file that
+is a candidate for the build. If the derived file matches, then the
+variable/value pairs are used to override the values in the construction
+environment associated with the derived file.
+
+Let's suppose that we have a construction environment like this:
+
+ $CONS = new cons(
+ COPT => '',
+ CDBG => '-g',
+ CFLAGS => '%COPT %CDBG',
+ );
+
+Then if we have an override file F<over> containing this command:
+
+ Override '\.o$', COPT => '-O', CDBG => '';
+
+then any C<cons> invocation with C<-o over> that creates F<.o> files via
+this environment will cause them to be compiled with C<-O >and no C<-g>. The
+override could, of course, be restricted to a single directory by the
+appropriate selection of a regular expression.
+
+Here's the original version of the Hello, World! program, built with this
+environment. Note that Cons rebuilds the appropriate pieces when the
+override is applied or removed:
+
+ % cons hello
+ cc -g -c hello.c -o hello.o
+ cc -o hello hello.o
+ % cons -o over hello
+ cc -O -c hello.c -o hello.o
+ cc -o hello hello.o
+ % cons -o over hello
+ cons: "hello" is up-to-date.
+ % cons hello
+ cc -g -c hello.c -o hello.o
+ cc -o hello hello.o
+
+It's important that the C<Override> command only be used for temporary,
+on-the-fly overrides necessary for development because the overrides are not
+platform independent and because they rely too much on intimate knowledge of
+the workings of the scripts. For temporary use, however, they are exactly
+what you want.
+
+Note that it is still useful to provide, say, the ability to create a fully
+optimized version of a system for production use--from the F<Construct> and
+F<Conscript> files. This way you can tailor the optimized system to the
+platform. Where optimizer trade-offs need to be made (particular files may
+not be compiled with full optimization, for example), then these can be
+recorded for posterity (and reproducibility) directly in the scripts.
+
+
+=head1 More on construction environments
+
+As previously mentioned, a B<construction environment> is an object that
+has a set of keyword/value pairs and a set of methods, and which is used
+to tell Cons how target files should be built. This section describes
+how Cons uses and expands construction environment values to control its
+build behavior.
+
+=head2 Construction variable expansion
+
+Construction variables from a construction environment are expanded
+by preceding the keyword with a C<%> (percent sign):
+
+ Construction variables:
+ XYZZY => 'abracadabra',
+
+ The string: "The magic word is: %XYZZY!"
+ expands to: "The magic word is: abracadabra!"
+
+A construction variable name may be surrounded by C<{> and C<}> (curly
+braces), which are stripped as part of the expansion. This can
+sometimes be necessary to separate a variable expansion from trailing
+alphanumeric characters:
+
+ Construction variables:
+ OPT => 'value1',
+ OPTION => 'value2',
+
+ The string: "%OPT %{OPT}ION %OPTION %{OPTION}"
+ expands to: "value1 value1ION value2 value2"
+
+Construction variable expansion is recursive--that is, a string
+containing C<%->expansions after substitution will be re-expanded until
+no further substitutions can be made:
+
+ Construction variables:
+ STRING => 'The result is: %FOO',
+ FOO => '%BAR',
+ BAR => 'final value',
+
+ The string: "The string says: %STRING"
+ expands to: "The string says: The result is: final value"
+
+If a construction variable is not defined in an environment, then the
+null string is substituted:
+
+ Construction variables:
+ FOO => 'value1',
+ BAR => 'value2',
+
+ The string: "%FOO <%NO_VARIABLE> %BAR"
+ expands to: "value1 <> value2"
+
+A doubled C<%%> will be replaced by a single C<%>:
+
+ The string: "Here is a percent sign: %%"
+ expands to: "Here is a percent sign: %"
+
+=head2 Default construction variables
+
+When you specify no arguments when creating a new construction
+environment:
+
+ $env = new cons();
+
+Cons creates a reference to a new, default construction
+environment. This contains a number of construction variables and some
+methods. At the present writing, the default construction variables on a
+UNIX system are:
+
+ CC => 'cc',
+ CFLAGS => '',
+ CCCOM => '%CC %CFLAGS %_IFLAGS -c %< -o %>',
+ CXX => '%CC',
+ CXXFLAGS => '%CFLAGS',
+ CXXCOM => '%CXX %CXXFLAGS %_IFLAGS -c %< -o %>',
+ INCDIRPREFIX => '-I',
+ INCDIRSUFFIX => '',
+ LINK => '%CXX',
+ LINKCOM => '%LINK %LDFLAGS -o %> %< %_LDIRS %LIBS',
+ LINKMODULECOM => '%LD -r -o %> %<',
+ LIBDIRPREFIX => '-L',
+ LIBDIRSUFFIX => '',
+ AR => 'ar',
+ ARFLAGS => 'r',
+ ARCOM => ['%AR %ARFLAGS %> %<', '%RANLIB %>'],
+ RANLIB => 'ranlib',
+ AS => 'as',
+ ASFLAGS => '',
+ ASCOM => '%AS %ASFLAGS %< -o %>',
+ LD => 'ld',
+ LDFLAGS => '',
+ PREFLIB => 'lib',
+ SUFLIB => '.a',
+ SUFLIBS => '.so:.a',
+ SUFOBJ => '.o',
+ SIGNATURE => [ '*' => 'build' ],
+ ENV => { 'PATH' => '/bin:/usr/bin' },
+
+
+And on a Win32 system (Windows NT), the default construction variables
+are (unless the default rule style is set using the B<DefaultRules>
+method):
+
+ CC => 'cl',
+ CFLAGS => '/nologo',
+ CCCOM => '%CC %CFLAGS %_IFLAGS /c %< /Fo%>',
+ CXXCOM => '%CXX %CXXFLAGS %_IFLAGS /c %< /Fo%>',
+ INCDIRPREFIX => '/I',
+ INCDIRSUFFIX => '',
+ LINK => 'link',
+ LINKCOM => '%LINK %LDFLAGS /out:%> %< %_LDIRS %LIBS',
+ LINKMODULECOM => '%LD /r /o %> %<',
+ LIBDIRPREFIX => '/LIBPATH:',
+ LIBDIRSUFFIX => '',
+ AR => 'lib',
+ ARFLAGS => '/nologo ',
+ ARCOM => "%AR %ARFLAGS /out:%> %<",
+ RANLIB => '',
+ LD => 'link',
+ LDFLAGS => '/nologo ',
+ PREFLIB => '',
+ SUFEXE => '.exe',
+ SUFLIB => '.lib',
+ SUFLIBS => '.dll:.lib',
+ SUFOBJ => '.obj',
+ SIGNATURE => [ '*' => 'build' ],
+
+These variables are used by the various methods associated with the
+environment. In particular, any method that ultimately invokes an external
+command will substitute these variables into the final command, as
+appropriate. For example, the C<Objects> method takes a number of source
+files and arranges to derive, if necessary, the corresponding object
+files:
+
+ Objects $env 'foo.c', 'bar.c';
+
+This will arrange to produce, if necessary, F<foo.o> and F<bar.o>. The
+command invoked is simply C<%CCCOM>, which expands, through substitution,
+to the appropriate external command required to build each object. The
+substitution rules will be discussed in detail in the next section.
+
+The construction variables are also used for other purposes. For example,
+C<CPPPATH> is used to specify a colon-separated path of include
+directories. These are intended to be passed to the C preprocessor and are
+also used by the C-file scanning machinery to determine the dependencies
+involved in a C Compilation.
+
+Variables beginning with underscore are created by various methods,
+and should normally be considered ``internal'' variables. For example,
+when a method is called which calls for the creation of an object from
+a C source, the variable C<_IFLAGS> is created: this corresponds to the
+C<-I> switches required by the C compiler to represent the directories
+specified by C<CPPPATH>.
+
+Note that, for any particular environment, the value of a variable is set
+once, and then never reset (to change a variable, you must create a new
+environment. Methods are provided for copying existing environments for this
+purpose). Some internal variables, such as C<_IFLAGS> are created on demand,
+but once set, they remain fixed for the life of the environment.
+
+The C<CFLAGS>, C<LDFLAGS>, and C<ARFLAGS> variables all supply a place
+for passing options to the compiler, loader, and archiver, respectively.
+
+The C<INCDIRPREFIX> and C<INCDIRSUFFIX> variables specify option
+strings to be appended to the beginning and end, respectively, of each
+include directory so that the compiler knows where to find F<.h> files.
+Similarly, the C<LIBDIRPREFIX> and C<LIBDIRSUFFIX> variables specify the
+option string to be appended to the beginning of and end, respectively,
+of each directory that the linker should search for libraries.
+
+Another variable, C<ENV>, is used to determine the system environment during
+the execution of an external command. By default, the only environment
+variable that is set is C<PATH>, which is the execution path for a UNIX
+command. For the utmost reproducibility, you should really arrange to set
+your own execution path, in your top-level F<Construct> file (or perhaps by
+importing an appropriate construction package with the Perl C<use>
+command). The default variables are intended to get you off the ground.
+
+=head2 Expanding variables in construction commands
+
+Within a construction command, construction variables will be expanded
+according to the rules described above. In addition to normal variable
+expansion from the construction environment, construction commands also
+expand the following pseudo-variables to insert the specific input and
+output files in the command line that will be executed:
+
+=over 10
+
+=item %>
+
+The target file name. In a multi-target command, this expands to the
+first target mentioned.)
+
+=item %0
+
+Same as C<%E<gt>>.
+
+=item %1, %2, ..., %9
+
+These refer to the first through ninth input file, respectively.
+
+=item %E<lt>
+
+The full set of input file names. If any of these have been used
+anywhere else in the current command line (via C<%1>, C<%2>, etc.), then
+those will be deleted from the list provided by C<%E<lt>>. Consider the
+following command found in a F<Conscript> file in the F<test> directory:
+
+ Command $env 'tgt', qw(foo bar baz), qq(
+ echo %< -i %1 > %>
+ echo %< -i %2 >> %>
+ echo %< -i %3 >> %>
+ );
+
+If F<tgt> needed to be updated, then this would result in the execution of
+the following commands, assuming that no remapping has been established for
+the F<test> directory:
+
+ echo test/bar test/baz -i test/foo > test/tgt
+ echo test/foo test/baz -i test/bar >> test/tgt
+ echo test/foo test/bar -i test/baz >> test/tgt
+
+=back
+
+Any of the above pseudo-variables may be followed immediately by one of
+the following suffixes to select a portion of the expanded path name:
+
+ :a the absolute path to the file name
+ :b the directory plus the file name stripped of any suffix
+ :d the directory
+ :f the file name
+ :s the file name suffix
+ :F the file name stripped of any suffix
+ :S the absolute path path to a Linked source file
+
+Continuing with the above example, C<%E<lt>:f> would expand to C<foo bar baz>,
+and C<%E<gt>:d> would expand to C<test>.
+
+There are additional C<%> elements which affect the command line(s):
+
+=over 10
+
+=item %[ %]
+
+It is possible to programmatically rewrite part of the command by
+enclosing part of it between C<%[> and C<%]>. This will call the
+construction variable named as the first word enclosed in the brackets
+as a Perl code reference; the results of this call will be used to
+replace the contents of the brackets in the command line. For example,
+given an existing input file named F<tgt.in>:
+
+ @keywords = qw(foo bar baz);
+ $env = new cons(X_COMMA => sub { join(",", @_) });
+ Command $env 'tgt', 'tgt.in', qq(
+ echo '# Keywords: %[X_COMMA @keywords %]' > %>
+ cat %< >> %>
+ );
+
+This will execute:
+
+ echo '# Keywords: foo,bar,baz' > tgt
+ cat tgt.in >> tgt
+
+=item %( %)
+
+Cons includes the text of the command line in the MD5 signature for a
+build, so that targets get rebuilt if you change the command line (to
+add or remove an option, for example). Command-line text in between
+C<%(> and C<%)>, however, will be ignored for MD5 signature calculation.
+
+Internally, Cons uses C<%(> and C<%)> around include and library
+directory options (C<-I> and C<-L> on UNIX systems, C</I> and
+C</LIBPATH> on Windows NT) to avoid rebuilds just because the directory
+list changes. Rebuilds occur only if the changed directory list causes
+any included I<files> to change, and a changed include file is detected
+by the MD5 signature calculation on the actual file contents.
+
+=back
+
+=head2 Expanding construction variables in file names
+
+Cons expands construction variables in the source and target file names
+passed to the various construction methods according to the expansion
+rules described above:
+
+ $env = new cons(
+ DESTDIR => 'programs',
+ SRCDIR => 'src',
+ );
+ Program $env '%DESTDIR/hello', '%SRCDIR/hello.c';
+
+This allows for flexible configuration, through the construction
+environment, of directory names, suffixes, etc.
+
+
+=head1 Build actions
+
+Cons supports several types of B<build actions> that can be performed
+to construct one or more target files. Usually, a build action is
+a construction command--that is, a command-line string that invokes
+an external command. Cons can also execute Perl code embedded in a
+command-line string, and even supports an experimental ability to build
+a target file by executing a Perl code reference directly.
+
+A build action is usually specified as the value of a construction
+variable:
+
+ $env = new cons(
+ CCCOM => '%CC %CFLAGS %_IFLAGS -c %< -o %>',
+ LINKCOM => '[perl] &link_executable("%>", "%<")',
+ ARCOM => sub { my($env, $target, @sources) = @_;
+ # code to create an archive
+ }
+ );
+
+A build action may be associated directly with one or more target files
+via the C<Command> method; see below.
+
+=head2 Construction commands
+
+A construction command goes through expansion of construction variables
+and C<%-> pseudo-variables, as described above, to create the actual
+command line that Cons will execute to generate the target file or
+files.
+
+After substitution occurs, strings of white space are converted into
+single blanks, and leading and trailing white space is eliminated. It
+is therefore currently not possible to introduce variable length white
+space in strings passed into a command.
+
+If a multi-line command string is provided, the commands are executed
+sequentially. If any of the commands fails, then none of the rest are
+executed, and the target is not marked as updated, i.e. a new signature is
+not stored for the target.
+
+Normally, if all the commands succeed, and return a zero status (or whatever
+platform-specific indication of success is required), then a new signature
+is stored for the target. If a command erroneously reports success even
+after a failure, then Cons will assume that the target file created by that
+command is accurate and up-to-date.
+
+The first word of each command string, after expansion, is assumed to be an
+executable command looked up on the C<PATH> environment variable (which is,
+in turn, specified by the C<ENV> construction variable). If this command is
+found on the path, then the target will depend upon it: the command will
+therefore be automatically built, as necessary. It's possible to write
+multi-part commands to some shells, separated by semi-colons. Only the first
+command word will be depended upon, however, so if you write your command
+strings this way, you must either explicitly set up a dependency (with the
+C<Depends> method), or be sure that the command you are using is a system
+command which is expected to be available. If it isn't available, you will,
+of course, get an error.
+
+Cons normally prints a command before executing it. This behavior is
+suppressed if the first character of the command is C<@>. Note that
+you may need to separate the C<@> from the command name or escape it to
+prevent C<@cmd> from looking like an array to Perl quote operators that
+perform interpolation:
+
+ # The first command line is incorrect,
+ # because "@cp" looks like an array
+ # to the Perl qq// function.
+ # Use the second form instead.
+ Command $env 'foo', 'foo.in', qq(
+ @cp %< tempfile
+ @ cp tempfile %>
+ );
+
+If there are shell meta characters anywhere in the expanded command line,
+such as C<E<lt>>, C<E<gt>>, quotes, or semi-colon, then the command
+will actually be executed by invoking a shell. This means that a command
+such as:
+
+ cd foo
+
+alone will typically fail, since there is no command C<cd> on the path. But
+the command string:
+
+ cd $<:d; tar cf $>:f $<:f
+
+when expanded will still contain the shell meta character semi-colon, and a
+shell will be invoked to interpret the command. Since C<cd> is interpreted
+by this sub-shell, the command will execute as expected.
+
+=head2 Perl expressions
+
+If any command (even one within a multi-line command) begins with
+C<[perl]>, the remainder of that command line will be evaluated by the
+running Perl instead of being forked by the shell. If an error occurs
+in parsing the Perl code, or if the Perl expression returns 0 or undef,
+the command will be considered to have failed. For example, here is a
+simple command which creates a file C<foo> directly from Perl:
+
+ $env = new cons();
+ Command $env 'foo',
+ qq([perl] open(FOO,'>foo');print FOO "hi\\n"; close(FOO); 1);
+
+Note that when the command is executed, you are in the same package as
+when the F<Construct> or F<Conscript> file was read, so you can call
+Perl functions you've defined in the same F<Construct> or F<Conscript>
+file in which the C<Command> appears:
+
+ $env = new cons();
+ sub create_file {
+ my $file = shift;
+ open(FILE, ">$file");
+ print FILE "hi\n";
+ close(FILE);
+ return 1;
+ }
+ Command $env 'foo', "[perl] &create_file('%>')";
+
+The Perl string will be used to generate the signature for the derived
+file, so if you change the string, the file will be rebuilt. The contents
+of any subroutines you call, however, are not part of the signature,
+so if you modify a called subroutine such as C<create_file> above,
+the target will I<not> be rebuilt. Caveat user.
+
+=head2 Perl code references [EXPERIMENTAL]
+
+Cons supports the ability to create a derived file by directly executing
+a Perl code reference. This feature is considered EXPERIMENTAL and
+subject to change in the future.
+
+A code reference may either be a named subroutine referenced by the
+usual C<\&> syntax:
+
+ sub build_output {
+ my($env, $target, @sources) = @_;
+ print "build_output building $target\n";
+ open(OUT, ">$target");
+ foreach $src (@sources) {
+ if (! open(IN, "<$src")) {
+ print STDERR "cannot open '$src': $!\n";
+ return undef;
+ }
+ print OUT, <IN>;
+ }
+ close(OUT);
+ return 1;
+ }
+ Command $env 'output', \&build_output;
+
+or the code reference may be an anonymous subroutine:
+
+ Command $env 'output', sub {
+ my($env, $target, @sources) = @_;
+ print "building $target\n";
+ open(FILE, ">$target");
+ print FILE "hello\n";
+ close(FILE);
+ return 1;
+ };
+
+To build the target file, the referenced subroutine is passed, in order:
+the construction environment used to generate the target; the path
+name of the target itself; and the path names of all the source files
+necessary to build the target file.
+
+The code reference is expected to generate the target file, of course,
+but may manipulate the source and target files in any way it chooses.
+The code reference must return a false value (C<undef> or C<0>) if
+the build of the file failed. Any true value indicates a successful
+build of the target.
+
+Building target files using code references is considered EXPERIMENTAL
+due to the following current limitations:
+
+=over 4
+
+Cons does I<not> print anything to indicate the code reference is being
+called to build the file. The only way to give the user any indication
+is to have the code reference explicitly print some sort of "building"
+message, as in the above examples.
+
+Cons does not generate any signatures for code references, so if the
+code in the reference changes, the target will I<not> be rebuilt.
+
+Cons has no public method to allow a code reference to extract
+construction variables. This would be good to allow generalization of
+code references based on the current construction environment, but would
+also complicate the problem of generating meaningful signatures for code
+references.
+
+=back
+
+Support for building targets via code references has been released in
+this version to encourage experimentation and the seeking of possible
+solutions to the above limitations.
+
+
+=head1 Default construction methods
+
+The list of default construction methods includes the following:
+
+
+=head2 The C<new> constructor
+
+The C<new> method is a Perl object constructor. That is, it is not invoked
+via a reference to an existing construction environment B<reference>, but,
+rather statically, using the name of the Perl B<package> where the
+constructor is defined. The method is invoked like this:
+
+ $env = new cons(<overrides>);
+
+The environment you get back is blessed into the package C<cons>, which
+means that it will have associated with it the default methods described
+below. Individual construction variables can be overridden by providing
+name/value pairs in an override list. Note that to override any command
+environment variable (i.e. anything under C<ENV>), you will have to override
+all of them. You can get around this difficulty by using the C<copy> method
+on an existing construction environment.
+
+
+=head2 The C<clone> method
+
+The C<clone> method creates a clone of an existing construction environment,
+and can be called as in the following example:
+
+ $env2 = $env1->clone(<overrides>);
+
+You can provide overrides in the usual manner to create a different
+environment from the original. If you just want a new name for the same
+environment (which may be helpful when exporting environments to existing
+components), you can just use simple assignment.
+
+
+=head2 The C<copy> method
+
+The C<copy> method extracts the externally defined construction variables
+from an environment and returns them as a list of name/value
+pairs. Overrides can also be provided, in which case, the overridden values
+will be returned, as appropriate. The returned list can be assigned to a
+hash, as shown in the prototype, below, but it can also be manipulated in
+other ways:
+
+ %env = $env1->copy(<overrides>);
+
+The value of C<ENV>, which is itself a hash, is also copied to a new hash,
+so this may be changed without fear of affecting the original
+environment. So, for example, if you really want to override just the
+C<PATH> variable in the default environment, you could do the following:
+
+ %cons = new cons()->copy();
+ $cons{ENV}{PATH} = "<your path here>";
+ $cons = new cons(%cons);
+
+This will leave anything else that might be in the default execution
+environment undisturbed.
+
+
+=head2 The C<Install> method
+
+The C<Install> method arranges for the specified files to be installed in
+the specified directory. The installation is optimized: the file is not
+copied if it can be linked. If this is not the desired behavior, you will
+need to use a different method to install the file. It is called as follows:
+
+ Install $env <directory>, <names>;
+
+Note that, while the files to be installed may be arbitrarily named,
+only the last component of each name is used for the installed target
+name. So, for example, if you arrange to install F<foo/bar> in F<baz>,
+this will create a F<bar> file in the F<baz> directory (not F<foo/bar>).
+
+
+=head2 The C<InstallAs> method
+
+The C<InstallAs> method arranges for the specified source file(s) to be
+installed as the specified target file(s). Multiple files should be
+specified as a file list. The installation is optimized: the file is not
+copied if it can be linked. If this is not the desired behavior, you will
+need to use a different method to install the file. It is called as follows:
+
+C<InstallAs> works in two ways:
+
+Single file install:
+
+ InstallAs $env TgtFile, SrcFile;
+
+Multiple file install:
+
+ InstallAs $env ['tgt1', 'tgt2'], ['src1', 'src2'];
+
+Or, even as:
+
+ @srcs = qw(src1 src2 src3);
+ @tgts = qw(tgt1 tgt2 tgt3);
+ InstallAs $env [@tgts], [@srcs];
+
+Both the target and the sources lists should be of the same length.
+
+=head2 The C<Precious> method
+
+The C<Precious> method asks cons not to delete the specified file or
+list of files before building them again. It is invoked as:
+
+ Precious <files>;
+
+This is especially useful for allowing incremental updates to libraries
+or debug information files which are updated rather than rebuilt anew each
+time. Cons will still delete the files when the C<-r> flag is specified.
+
+=head2 The C<AfterBuild> method
+
+The C<AfterBuild> method evaluates the specified perl string after
+building the given file or files (or finding that they are up to date).
+The eval will happen once per specified file. C<AfterBuild> is called
+as follows:
+
+ AfterBuild $env 'foo.o', qq(print "foo.o is up to date!\n");
+
+The perl string is evaluated in the C<script> package, and has access
+to all variables and subroutines defined in the F<Conscript> file in
+which the C<AfterBuild> method is called.
+
+=head2 The C<Command> method
+
+The C<Command> method is a catchall method which can be used to arrange for
+any build action to be executed to update the target. For this command, a
+target file and list of inputs is provided. In addition, a build action
+is specified as the last argument. The build action is typically a
+command line or lines, but may also contain Perl code to be executed;
+see the section above on build actions for details.
+
+The C<Command> method is called as follows:
+
+ Command $env <target>, <inputs>, <build action>;
+
+The target is made dependent upon the list of input files specified, and the
+inputs must be built successfully or Cons will not attempt to build the
+target.
+
+To specify a command with multiple targets, you can specify a reference to a
+list of targets. In Perl, a list reference can be created by enclosing a
+list in square brackets. Hence the following command:
+
+ Command $env ['foo.h', 'foo.c'], 'foo.template', q(
+ gen %1
+ );
+
+could be used in a case where the command C<gen> creates two files, both
+F<foo.h> and F<foo.c>.
+
+
+=head2 The C<Objects> method
+
+The C<Objects> method arranges to create the object files that correspond to
+the specified source files. It is invoked as shown below:
+
+ @files = Objects $env <source or object files>;
+
+Under Unix, source files ending in F<.s> and F<.c> are currently
+supported, and will be compiled into a name of the same file ending
+in F<.o>. By default, all files are created by invoking the external
+command which results from expanding the C<CCCOM> construction variable,
+with C<%E<lt>> and C<%E<gt>> set to the source and object files,
+respectively. (See the section above on construction variable expansion
+for details). The variable C<CPPPATH> is also used when scanning source
+files for dependencies. This is a colon separated list of pathnames, and
+is also used to create the construction variable C<_IFLAGS,> which will
+contain the appropriate list of -C<I> options for the compilation. Any
+relative pathnames in C<CPPPATH> is interpreted relative to the
+directory in which the associated construction environment was created
+(absolute and top-relative names may also be used). This variable is
+used by C<CCCOM>. The behavior of this command can be modified by
+changing any of the variables which are interpolated into C<CCCOM>, such
+as C<CC>, C<CFLAGS>, and, indirectly, C<CPPPATH>. It's also possible
+to replace the value of C<CCCOM>, itself. As a convenience, this file
+returns the list of object filenames.
+
+
+=head2 The C<Program> method
+
+The C<Program> method arranges to link the specified program with the
+specified object files. It is invoked in the following manner:
+
+ Program $env <program name>, <source or object files>;
+
+The program name will have the value of the C<SUFEXE> construction
+variable appended (by default, C<.exe> on Win32 systems, nothing on Unix
+systems) if the suffix is not already present.
+
+Source files may be specified in place of objects files--the C<Objects>
+method will be invoked to arrange the conversion of all the files into
+object files, and hence all the observations about the C<Objects> method,
+above, apply to this method also.
+
+The actual linking of the program will be handled by an external command
+which results from expanding the C<LINKCOM> construction variable, with
+C<%E<lt>> set to the object files to be linked (in the order presented),
+and C<%E<gt>> set to the target. (See the section above on construction
+variable expansion for details.) The user may set additional variables
+in the construction environment, including C<LINK>, to define which
+program to use for linking, C<LIBPATH>, a colon-separated list of
+library search paths, for use with library specifications of the form
+I<-llib>, and C<LIBS>, specifying the list of libraries to link against
+(in either I<-llib> form or just as pathnames. Relative pathnames in
+both C<LIBPATH> and C<LIBS> are interpreted relative to the directory
+in which the associated construction environment is created (absolute
+and top-relative names may also be used). Cons automatically sets up
+dependencies on any libraries mentioned in C<LIBS>: those libraries will
+be built before the command is linked.
+
+
+=head2 The C<Library> method
+
+The C<Library> method arranges to create the specified library from the
+specified object files. It is invoked as follows:
+
+ Library $env <library name>, <source or object files>;
+
+The library name will have the value of the C<SUFLIB> construction
+variable appended (by default, C<.lib> on Win32 systems, C<.a> on Unix
+systems) if the suffix is not already present.
+
+Source files may be specified in place of objects files--the C<Objects>
+method will be invoked to arrange the conversion of all the files into
+object files, and hence all the observations about the C<Objects> method,
+above, apply to this method also.
+
+The actual creation of the library will be handled by an external
+command which results from expanding the C<ARCOM> construction variable,
+with C<%E<lt>> set to the library members (in the order presented),
+and C<%E<gt>> to the library to be created. (See the section above
+on construction variable expansion for details.) The user may set
+variables in the construction environment which will affect the
+operation of the command. These include C<AR>, the archive program
+to use, C<ARFLAGS>, which can be used to modify the flags given to
+the program specified by C<AR>, and C<RANLIB>, the name of a archive
+index generation program, if needed (if the particular need does not
+require the latter functionality, then C<ARCOM> must be redefined to not
+reference C<RANLIB>).
+
+The C<Library> method allows the same library to be specified in multiple
+method invocations. All of the contributing objects from all the invocations
+(which may be from different directories) are combined and generated by a
+single archive command. Note, however, that if you prune a build so that
+only part of a library is specified, then only that part of the library will
+be generated (the rest will disappear!).
+
+
+=head2 The C<Module> method
+
+The C<Module> method is a combination of the C<Program> and C<Command>
+methods. Rather than generating an executable program directly, this command
+allows you to specify your own command to actually generate a module. The
+method is invoked as follows:
+
+ Module $env <module name>, <source or object files>, <construction command>;
+
+This command is useful in instances where you wish to create, for example,
+dynamically loaded modules, or statically linked code libraries.
+
+
+=head2 The C<Depends> method
+
+The C<Depends> method allows you to specify additional dependencies for a
+target. It is invoked as follows:
+
+ Depends $env <target>, <dependencies>;
+
+This may be occasionally useful, especially in cases where no scanner exists
+(or is writable) for particular types of files. Normally, dependencies are
+calculated automatically from a combination of the explicit dependencies set
+up by the method invocation or by scanning source files.
+
+A set of identical dependencies for multiple targets may be specified
+using a reference to a list of targets. In Perl, a list reference can
+be created by enclosing a list in square brackets. Hence the following
+command:
+
+ Depends $env ['foo', 'bar'], 'input_file_1', 'input_file_2';
+
+specifies that both the F<foo> and F<bar> files depend on the listed
+input files.
+
+
+=head2 The C<RuleSet> method
+
+The C<RuleSet> method returns the construction variables for building
+various components with one of the rule sets supported by Cons. The
+currently supported rule sets are:
+
+=over 4
+
+=item msvc
+
+Rules for the Microsoft Visual C++ compiler suite.
+
+=item unix
+
+Generic rules for most UNIX-like compiler suites.
+
+=back
+
+On systems with more than one available compiler suite, this allows you
+to easily create side-by-side environments for building software with
+multiple tools:
+
+ $msvcenv = new cons(RuleSet("msvc"));
+ $cygnusenv = new cons(RuleSet("unix"));
+
+In the future, this could also be extended to other platforms that
+have different default rule sets.
+
+
+=head2 The C<DefaultRules> method
+
+The C<DefaultRules> method sets the default construction variables that
+will be returned by the C<new> method to the specified arguments:
+
+ DefaultRules(CC => 'gcc',
+ CFLAGS => '',
+ CCCOM => '%CC %CFLAGS %_IFLAGS -c %< -o %>');
+ $env = new cons();
+ # $env now contains *only* the CC, CFLAGS,
+ # and CCCOM construction variables
+
+Combined with the C<RuleSet> method, this also provides an easy way
+to set explicitly the default build environment to use some supported
+toolset other than the Cons defaults:
+
+ # use a UNIX-like tool suite (like cygwin) on Win32
+ DefaultRules(RuleSet('unix'));
+ $env = new cons();
+
+Note that the C<DefaultRules> method completely replaces the default
+construction environment with the specified arguments, it does not
+simply override the existing defaults. To override one or more
+variables in a supported C<RuleSet>, append the variables and values:
+
+ DefaultRules(RuleSet('unix'), CFLAGS => '-O3');
+ $env1 = new cons();
+ $env2 = new cons();
+ # both $env1 and $env2 have 'unix' defaults
+ # with CFLAGS set to '-O3'
+
+
+=head2 The C<Ignore> method
+
+The C<Ignore> method allows you to ignore explicitly dependencies that
+Cons infers on its own. It is invoked as follows:
+
+ Ignore <patterns>;
+
+This can be used to avoid recompilations due to changes in system header
+files or utilities that are known to not affect the generated targets.
+
+If, for example, a program is built in an NFS-mounted directory on
+multiple systems that have different copies of F<stdio.h>, the differences
+will affect the signatures of all derived targets built from source files
+that C<#include E<lt>stdio.hE<gt>>. This will cause all those targets to
+be rebuilt when changing systems. If this is not desirable behavior, then
+the following line will remove the dependencies on the F<stdio.h> file:
+
+ Ignore '^/usr/include/stdio\.h$';
+
+Note that the arguments to the C<Ignore> method are regular expressions,
+so special characters must be escaped and you may wish to anchor the
+beginning or end of the expression with C<^> or C<$> characters.
+
+
+=head2 The C<Salt> method
+
+The C<Salt> method adds a constant value to the signature calculation
+for every derived file. It is invoked as follows:
+
+ Salt $string;
+
+Changing the Salt value will force a complete rebuild of every derived
+file. This can be used to force rebuilds in certain desired
+circumstances. For example,
+
+ Salt `uname -s`;
+
+Would force a complete rebuild of every derived file whenever the
+operating system on which the build is performed (as reported by C<uname
+-s>) changes.
+
+
+=head2 The C<UseCache> method
+
+The C<UseCache> method instructs Cons to maintain a cache of derived
+files, to be shared among separate build trees of the same project.
+
+ UseCache("cache/<buildname>") || warn("cache directory not found");
+
+
+=head2 The C<SourcePath> method
+
+The C<SourcePath> mathod returns the real source path name of a file,
+as opposed to the path name within a build directory. It is invoked
+as follows:
+
+ $path = SourcePath <buildpath>;
+
+
+=head2 The C<ConsPath> method
+
+The C<ConsPath> method returns true if the supplied path is a derivable
+file, and returns undef (false) otherwise.
+It is invoked as follows:
+
+ $result = ConsPath <path>;
+
+
+=head2 The C<SplitPath> method
+
+The C<SplitPath> method looks up multiple path names in a string separated
+by the default path separator for the operating system (':' on UNIX
+systems, ';' on Windows NT), and returns the fully-qualified names.
+It is invoked as follows:
+
+ @paths = SplitPath <pathlist>;
+
+The C<SplitPath> method will convert names prefixed '#' to the
+appropriate top-level build name (without the '#') and will convert
+relative names to top-level names.
+
+
+=head2 The C<DirPath> method
+
+The C<DirPath> method returns the build path name(s) of a directory or
+list of directories. It is invoked as follows:
+
+ $cwd = DirPath <paths>;
+
+The most common use for the C<DirPath> method is:
+
+ $cwd = DirPath '.';
+
+to fetch the path to the current directory of a subsidiary F<Conscript>
+file.
+
+
+=head2 The C<FilePath> method
+
+The C<FilePath> method returns the build path name(s) of a file or
+list of files. It is invoked as follows:
+
+ $file = FilePath <path>;
+
+
+=head2 The C<Help> method
+
+The C<Help> method specifies help text that will be displayed when the
+user invokes C<cons -h>. This can be used to provide documentation
+of specific targets, values, build options, etc. for the build tree.
+It is invoked as follows:
+
+ Help <helptext>;
+
+The C<Help> method may only be called once, and should typically be
+specified in the top-level F<Construct> file.
+
+
+=head1 Extending Cons
+
+
+=head2 Overriding construction variables
+
+There are several ways of extending Cons, which vary in degree of
+difficulty. The simplest method is to define your own construction
+environment, based on the default environment, but modified to reflect your
+particular needs. This will often suffice for C-based applications. You can
+use the C<new> constructor, and the C<clone> and C<copy> methods to create
+hybrid environments. These changes can be entirely transparent to the
+underlying F<Conscript> files.
+
+
+=head2 Adding new methods
+
+For slightly more demanding changes, you may wish to add new methods to the
+C<cons> package. Here's an example of a very simple extension,
+C<InstallScript>, which installs a tcl script in a requested location, but
+edits the script first to reflect a platform-dependent path that needs to be
+installed in the script:
+
+ # cons::InstallScript - Create a platform dependent version of a shell
+ # script by replacing string ``#!your-path-here'' with platform specific
+ # path $BIN_DIR.
+
+ sub cons::InstallScript {
+ my ($env, $dst, $src) = @_;
+ Command $env $dst, $src, qq(
+ sed s+your-path-here+$BIN_DIR+ %< > %>
+ chmod oug+x %>
+ );
+ }
+
+Notice that this method is defined directly in the C<cons> package (by
+prefixing the name with C<cons::>). A change made in this manner will be
+globally visible to all environments, and could be called as in the
+following example:
+
+ InstallScript $env "$BIN/foo", "foo.tcl";
+
+For a small improvement in generality, the C<BINDIR> variable could be
+passed in as an argument or taken from the construction environment--as
+C<%BINDIR>.
+
+
+=head2 Overriding methods
+
+Instead of adding the method to the C<cons> name space, you could define a
+new package which inherits existing methods from the C<cons> package and
+overrides or adds others. This can be done using Perl's inheritance
+mechanisms.
+
+The following example defines a new package C<cons::switch> which
+overrides the standard C<Library> method. The overridden method builds
+linked library modules, rather than library archives. A new
+constructor is provided. Environments created with this constructor
+will have the new library method; others won't.
+
+ package cons::switch;
+ BEGIN {@ISA = 'cons'}
+
+ sub new {
+ shift;
+ bless new cons(@_);
+ }
+
+ sub Library {
+ my($env) = shift;
+ my($lib) = shift;
+ my(@objs) = Objects $env @_;
+ Command $env $lib, @objs, q(
+ %LD -r %LDFLAGS %< -o %>
+ );
+ }
+
+This functionality could be invoked as in the following example:
+
+ $env = new cons::switch(@overrides);
+ ...
+ Library $env 'lib.o', 'foo.c', 'bar.c';
+
+
+=head1 Invoking Cons
+
+The C<cons> command is usually invoked from the root of the build tree. A
+F<Construct> file must exist in that directory. If the C<-f> argument is
+used, then an alternate F<Construct> file may be used (and, possibly, an
+alternate root, since C<cons> will cd to F<Construct> file's containing
+directory).
+
+If C<cons> is invoked from a child of the root of the build tree with
+the C<-t> argument, it will walk up the directory hierarchy looking for a
+F<Construct> file. (An alternate name may still be specified with C<-f>.)
+The targets supplied on the command line will be modified to be relative
+to the discovered F<Construct> file. For example, from a directory
+containing a top-level F<Construct> file, the following invocation:
+
+ % cd libfoo/subdir
+ % cons -t target
+
+is exactly equivalent to:
+
+ % cons libfoo/subdir/target
+
+If there are any C<Default> targets specified in the directory hierarchy's
+F<Construct> or F<Conscript> files, only the default targets at or below
+the directory from which C<cons -t> was invoked will be built.
+
+The command is invoked as follows:
+
+ cons <arguments> -- <construct-args>
+
+where I<arguments> can be any of the following, in any order:
+
+=over 10
+
+=item I<target>
+
+Build the specified target. If I<target> is a directory, then recursively
+build everything within that directory.
+
+=item I<+pattern>
+
+Limit the F<Conscript> files considered to just those that match I<pattern>,
+which is a Perl regular expression. Multiple C<+> arguments are accepted.
+
+=item I<name>=<val>
+
+Sets I<name> to value I<val> in the C<ARG> hash passed to the top-level
+F<Construct> file.
+
+=item C<-cc>
+
+Show command that would have been executed, when retrieving from cache. No
+indication that the file has been retrieved is given; this is useful for
+generating build logs that can be compared with real build logs.
+
+=item C<-cd>
+
+Disable all caching. Do not retrieve from cache nor flush to cache.
+
+=item C<-cr>
+
+Build dependencies in random order. This is useful when building multiple
+similar trees with caching enabled.
+
+=item C<-cs>
+
+Synchronize existing build targets that are found to be up-to-date with
+cache. This is useful if caching has been disabled with -cc or just recently
+enabled with UseCache.
+
+=item C<-d>
+
+Enable dependency debugging.
+
+=item C<-f> <file>
+
+Use the specified file instead of F<Construct> (but first change to
+containing directory of I<file>).
+
+=item C<-h>
+
+Show a help message local to the current build if one such is defined, and
+exit.
+
+=item C<-k>
+
+Keep going as far as possible after errors.
+
+=item C<-o> <file>
+
+Read override file I<file>.
+
+=item C<-p>
+
+Show construction products in specified trees. No build is attempted.
+
+=item C<-pa>
+
+Show construction products and associated actions. No build is attempted.
+
+=item C<-pw>
+
+Show products and where they are defined. No build is attempted.
+
+=item C<-q>
+
+Make the build quiet. Multiple C<-q> options may be specified.
+
+A single C<-q> options suppress messages about Installing and Removing
+targets.
+
+Two C<-q> options suppress build command lines and target up-to-date
+messages.
+
+=item C<-r>
+
+Remove construction products associated with <targets>. No build is
+attempted.
+
+=item C<-R> <repos>
+
+Search for files in I<repos>. Multiple B<-R> I<repos> directories are
+searched in the order specified.
+
+=item C<-S> <pkg>
+
+Use the sig::<pkg> package to calculate. Supported <pkg> values
+include "md5" for MD5 signature calculation and "md5::debug" for debug
+information about MD5 signature calculation.
+
+If the specified package ends in <::debug>, signature debug information
+will be printed to the file name specified in the C<CONS_SIG_DEBUG>
+environment variable, or to standard output if the environment variable
+is not set.
+
+=item C<-t>
+
+Traverse up the directory hierarchy looking for a F<Construct> file,
+if none exists in the current directory. Targets will be modified to
+be relative to the F<Construct> file.
+
+Internally, C<cons> will change its working directory to the directory
+which contains the top-level F<Construct> file and report:
+
+ cons: Entering directory `top-level-directory'
+
+This message indicates to an invoking editor (such as emacs) or build
+environment that Cons will now report all file names relative to the
+top-level directory. This message can not be suppressed with the C<-q>
+option.
+
+=item C<-v>
+
+Show C<cons> version and continue processing.
+
+=item C<-V>
+
+Show C<cons> version and exit.
+
+=item C<-wf> <file>
+
+Write all filenames considered into I<file>.
+
+=item C<-x>
+
+Show a help message similar to this one, and exit.
+
+=back
+
+And I<construct-args> can be any arguments that you wish to process in the
+F<Construct> file. Note that there should be a B<--> separating the arguments
+to cons and the arguments that you wish to process in the F<Construct> file.
+
+Processing of I<construct-args> can be done by any standard package like
+B<Getopt> or its variants, or any user defined package. B<cons> will pass in
+the I<construct-args> as B<@ARGV> and will not attempt to interpret anything
+after the B<-->.
+
+ % cons -R /usr/local/repository -d os=solaris +driver -- -c test -f DEBUG
+
+would pass the following to cons
+
+ -R /usr/local/repository -d os=solaris +driver
+
+and the following, to the top level F<Construct> file as B<@ARGV>
+
+ -c test -f DEBUG
+
+Note that C<cons -r .> is equivalent to a full recursive C<make clean>,
+but requires no support in the F<Construct> file or any F<Conscript>
+files. This is most useful if you are compiling files into source
+directories (if you separate the F<build> and F<export> directories,
+then you can just remove the directories).
+
+The options C<-p>, C<-pa>, and C<-pw> are extremely useful for use as an aid
+in reading scripts or debugging them. If you want to know what script
+installs F<export/include/foo.h>, for example, just type:
+
+ % cons -pw export/include/foo.h
+
+
+=head1 Using and writing dependency scanners
+
+QuickScan allows simple target-independent scanners to be set up for
+source files. Only one QuickScan scanner may be associated with any given
+source file and environment, although the same scanner may (and should)
+be used for multiple files of a given type.
+
+A QuickScan scanner is only ever invoked once for a given source file,
+and it is only invoked if the file is used by some target in the tree
+(i.e., there is a dependency on the source file).
+
+QuickScan is invoked as follows:
+
+ QuickScan CONSENV CODEREF, FILENAME [, PATH]
+
+The subroutine referenced by CODEREF is expected to return a list of
+filenames included directly by FILE. These filenames will, in turn, be
+scanned. The optional PATH argument supplies a lookup path for finding
+FILENAME and/or files returned by the user-supplied subroutine. The PATH
+may be a reference to an array of lookup-directory names, or a string of
+names separated by the system's separator character (':' on UNIX systems,
+';' on Windows NT).
+
+The subroutine is called once for each line in the file, with $_ set to the
+current line. If the subroutine needs to look at additional lines, or, for
+that matter, the entire file, then it may read them itself, from the
+filehandle SCAN. It may also terminate the loop, if it knows that no further
+include information is available, by closing the filehandle.
+
+Whether or not a lookup path is provided, QuickScan first tries to lookup
+the file relative to the current directory (for the top-level file
+supplied directly to QuickScan), or from the directory containing the
+file which referenced the file. This is not very general, but seems good
+enough--especially if you have the luxury of writing your own utilities
+and can control the use of the search path in a standard way.
+
+Here's a real example, taken from a F<Construct> file here:
+
+ sub cons::SMFgen {
+ my($env, @tables) = @_;
+ foreach $t (@tables) {
+ $env->QuickScan(sub { /\b\S*?\.smf\b/g }, "$t.smf",
+ $env->{SMF_INCLUDE_PATH});
+ $env->Command(["$t.smdb.cc","$t.smdb.h","$t.snmp.cc",
+ "$t.ami.cc", "$t.http.cc"], "$t.smf",
+ q(smfgen %( %SMF_INCLUDE_OPT %) %<));
+ }
+ }
+
+The subroutine above finds all names of the form <name>.smf in the
+file. It will return the names even if they're found within comments,
+but that's OK (the mechanism is forgiving of extra files; they're just
+ignored on the assumption that the missing file will be noticed when
+the program, in this example, smfgen, is actually invoked).
+
+[NOTE that the form C<$env-E<gt>QuickScan ...> and C<$env-E<gt>Command
+...> should not be necessary, but, for some reason, is required
+for this particular invocation. This appears to be a bug in Perl or
+a misunderstanding on my part; this invocation style does not always
+appear to be necessary.]
+
+Here is another way to build the same scanner. This one uses an
+explicit code reference, and also (unnecessarily, in this case) reads
+the whole file itself:
+
+ sub myscan {
+ my(@includes);
+ do {
+ push(@includes, /\b\S*?\.smf\b/g);
+ } while <SCAN>;
+ @includes
+ }
+
+Note that the order of the loop is reversed, with the loop test at the
+end. This is because the first line is already read for you. This scanner
+can be attached to a source file by:
+
+ QuickScan $env \&myscan, "$_.smf";
+
+This final example, which scans a different type of input file, takes
+over the file scanning rather than being called for each input line:
+
+ $env->QuickScan(
+ sub { my(@includes) = ();
+ do {
+ push(@includes, $3)
+ if /^(#include|import)\s+(\")(.+)(\")/ && $3
+ } while <SCAN>;
+ @includes
+ },
+ "$idlFileName",
+ "$env->{CPPPATH};$BUILD/ActiveContext/ACSCLientInterfaces"
+ );
+
+=head1 SUPPORT AND SUGGESTIONS
+
+Cons is maintained by the user community. To subscribe, send mail to
+B<cons-discuss-request@gnu.org> with body B<subscribe>.
+
+Please report any suggestions through the B<cons-discuss@gnu.org> mailing
+list.
+
+=head1 BUGS
+
+Sure to be some. Please report any bugs through the B<bug-cons@gnu.org>
+mailing list.
+
+=head1 INFORMATION ABOUT CONS
+
+Information about CONS can be obtained from the official cons web site
+B<http://www.dsmit.com/cons/> or its mirrors listed there.
+
+The cons maintainers can be contacted by email at
+B<cons-maintainers@gnu.org>
+
+=head1 AUTHORS
+
+Originally by Bob Sidebotham. Then significantly enriched by the members
+of the Cons community B<cons-discuss@gnu.org>.
+
+The Cons community would like to thank Ulrich Pfeifer for the original pod
+documentation derived from the F<cons.html> file. Cons documentation is now
+a part of the program itself.
+
+=cut
+
diff --git a/code/unix/q3test.spec.sh b/code/unix/q3test.spec.sh
new file mode 100755
index 0000000..93f3714
--- /dev/null
+++ b/code/unix/q3test.spec.sh
@@ -0,0 +1,52 @@
+#!/bin/sh
+# Generate Quake3 test
+# $1 is version
+# $2 is release
+# $3 is arch
+# $4 is install dir (assumed to be in /var/tmp)
+cat <<EOF
+%define name q3test
+%define version ${1}
+%define release ${2}
+%define arch ${3}
+%define builddir \$RPM_BUILD_DIR/%{name}-%{version}
+Name: %{name}
+Version: %{version}
+Release: %{release}
+Vendor: id Software
+Packager: Dave "Zoid" Kirsch <zoid@idsoftware.com>
+URL: http://www.idsoftware.com/
+Source: q3test-%{version}.tar.gz
+Group: Games
+Copyright: Restricted
+Icon: quake3.gif
+BuildRoot: /var/tmp/%{name}-%{version}
+Summary: Q3Test for Linux
+
+%description
+
+%install
+
+%files
+
+%attr(644,root,root) $4/README.EULA
+%attr(644,root,root) $4/README.Q3Test
+%attr(644,root,root) $4/README.Linux
+%attr(644,root,root) $4/Quake3.kdelnk
+%attr(644,root,root) $4/quake3.xpm
+%attr(755,root,root) $4/linuxquake3
+%attr(755,root,root) $4/cgamei386.so
+%attr(755,root,root) $4/qagamei386.so
+%attr(755,root,root) $4/uii386.so
+%attr(755,root,root) $4/libMesaVoodooGL.so.3.1
+%attr(644,root,root) $4/demoq3/pak0.pk3
+
+%post
+
+if [ -n "\$KDEDIR" ]; then
+ ln -sf $4/Quake3.kdelnk \$KDEDIR/share/applnk/Games/Quake3.kdelnk
+ ln -sf $4/quake3.xpm \$KDEDIR/share/icons/quake3.xpm
+fi
+
+EOF
+
diff --git a/code/unix/qasm.h b/code/unix/qasm.h
new file mode 100755
index 0000000..365346f
--- /dev/null
+++ b/code/unix/qasm.h
@@ -0,0 +1,480 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __ASM_I386__
+#define __ASM_I386__
+
+#ifdef ELF
+#define C(label) label
+#else
+#define C(label) _##label
+#endif
+
+
+//#define GLQUAKE 1
+
+#if defined(_WIN32) && !defined(WINDED)
+
+#if defined(_M_IX86)
+#define __i386__ 1
+#endif
+
+#endif
+
+#ifdef __i386__
+#define id386 1
+#else
+#define id386 0
+#endif
+
+// !!! must be kept the same as in d_iface.h !!!
+#define TRANSPARENT_COLOR 255
+
+#ifndef GLQUAKE
+ .extern C(d_zistepu)
+ .extern C(d_pzbuffer)
+ .extern C(d_zistepv)
+ .extern C(d_zrowbytes)
+ .extern C(d_ziorigin)
+ .extern C(r_turb_s)
+ .extern C(r_turb_t)
+ .extern C(r_turb_pdest)
+ .extern C(r_turb_spancount)
+ .extern C(r_turb_turb)
+ .extern C(r_turb_pbase)
+ .extern C(r_turb_sstep)
+ .extern C(r_turb_tstep)
+ .extern C(r_bmodelactive)
+ .extern C(d_sdivzstepu)
+ .extern C(d_tdivzstepu)
+ .extern C(d_sdivzstepv)
+ .extern C(d_tdivzstepv)
+ .extern C(d_sdivzorigin)
+ .extern C(d_tdivzorigin)
+ .extern C(sadjust)
+ .extern C(tadjust)
+ .extern C(bbextents)
+ .extern C(bbextentt)
+ .extern C(cacheblock)
+ .extern C(d_viewbuffer)
+ .extern C(cachewidth)
+ .extern C(d_pzbuffer)
+ .extern C(d_zrowbytes)
+ .extern C(d_zwidth)
+ .extern C(d_scantable)
+ .extern C(r_lightptr)
+ .extern C(r_numvblocks)
+ .extern C(prowdestbase)
+ .extern C(pbasesource)
+ .extern C(r_lightwidth)
+ .extern C(lightright)
+ .extern C(lightrightstep)
+ .extern C(lightdeltastep)
+ .extern C(lightdelta)
+ .extern C(lightright)
+ .extern C(lightdelta)
+ .extern C(sourcetstep)
+ .extern C(surfrowbytes)
+ .extern C(lightrightstep)
+ .extern C(lightdeltastep)
+ .extern C(r_sourcemax)
+ .extern C(r_stepback)
+ .extern C(colormap)
+ .extern C(blocksize)
+ .extern C(sourcesstep)
+ .extern C(lightleft)
+ .extern C(blockdivshift)
+ .extern C(blockdivmask)
+ .extern C(lightleftstep)
+ .extern C(r_origin)
+ .extern C(r_ppn)
+ .extern C(r_pup)
+ .extern C(r_pright)
+ .extern C(ycenter)
+ .extern C(xcenter)
+ .extern C(d_vrectbottom_particle)
+ .extern C(d_vrectright_particle)
+ .extern C(d_vrecty)
+ .extern C(d_vrectx)
+ .extern C(d_pix_shift)
+ .extern C(d_pix_min)
+ .extern C(d_pix_max)
+ .extern C(d_y_aspect_shift)
+ .extern C(screenwidth)
+ .extern C(r_leftclipped)
+ .extern C(r_leftenter)
+ .extern C(r_rightclipped)
+ .extern C(r_rightenter)
+ .extern C(modelorg)
+ .extern C(xscale)
+ .extern C(r_refdef)
+ .extern C(yscale)
+ .extern C(r_leftexit)
+ .extern C(r_rightexit)
+ .extern C(r_lastvertvalid)
+ .extern C(cacheoffset)
+ .extern C(newedges)
+ .extern C(removeedges)
+ .extern C(r_pedge)
+ .extern C(r_framecount)
+ .extern C(r_u1)
+ .extern C(r_emitted)
+ .extern C(edge_p)
+ .extern C(surface_p)
+ .extern C(surfaces)
+ .extern C(r_lzi1)
+ .extern C(r_v1)
+ .extern C(r_ceilv1)
+ .extern C(r_nearzi)
+ .extern C(r_nearzionly)
+ .extern C(edge_aftertail)
+ .extern C(edge_tail)
+ .extern C(current_iv)
+ .extern C(edge_head_u_shift20)
+ .extern C(span_p)
+ .extern C(edge_head)
+ .extern C(fv)
+ .extern C(edge_tail_u_shift20)
+ .extern C(r_apverts)
+ .extern C(r_anumverts)
+ .extern C(aliastransform)
+ .extern C(r_avertexnormals)
+ .extern C(r_plightvec)
+ .extern C(r_ambientlight)
+ .extern C(r_shadelight)
+ .extern C(aliasxcenter)
+ .extern C(aliasycenter)
+ .extern C(a_sstepxfrac)
+ .extern C(r_affinetridesc)
+ .extern C(acolormap)
+ .extern C(d_pcolormap)
+ .extern C(r_affinetridesc)
+ .extern C(d_sfrac)
+ .extern C(d_ptex)
+ .extern C(d_pedgespanpackage)
+ .extern C(d_tfrac)
+ .extern C(d_light)
+ .extern C(d_zi)
+ .extern C(d_pdest)
+ .extern C(d_pz)
+ .extern C(d_aspancount)
+ .extern C(erroradjustup)
+ .extern C(errorterm)
+ .extern C(d_xdenom)
+ .extern C(r_p0)
+ .extern C(r_p1)
+ .extern C(r_p2)
+ .extern C(a_tstepxfrac)
+ .extern C(r_sstepx)
+ .extern C(r_tstepx)
+ .extern C(a_ststepxwhole)
+ .extern C(zspantable)
+ .extern C(skintable)
+ .extern C(r_zistepx)
+ .extern C(erroradjustdown)
+ .extern C(d_countextrastep)
+ .extern C(ubasestep)
+ .extern C(a_ststepxwhole)
+ .extern C(a_tstepxfrac)
+ .extern C(r_lstepx)
+ .extern C(a_spans)
+ .extern C(erroradjustdown)
+ .extern C(d_pdestextrastep)
+ .extern C(d_pzextrastep)
+ .extern C(d_sfracextrastep)
+ .extern C(d_ptexextrastep)
+ .extern C(d_countextrastep)
+ .extern C(d_tfracextrastep)
+ .extern C(d_lightextrastep)
+ .extern C(d_ziextrastep)
+ .extern C(d_pdestbasestep)
+ .extern C(d_pzbasestep)
+ .extern C(d_sfracbasestep)
+ .extern C(d_ptexbasestep)
+ .extern C(ubasestep)
+ .extern C(d_tfracbasestep)
+ .extern C(d_lightbasestep)
+ .extern C(d_zibasestep)
+ .extern C(zspantable)
+ .extern C(r_lstepy)
+ .extern C(r_sstepy)
+ .extern C(r_tstepy)
+ .extern C(r_zistepy)
+ .extern C(D_PolysetSetEdgeTable)
+ .extern C(D_RasterizeAliasPolySmooth)
+
+ .extern float_point5
+ .extern Float2ToThe31nd
+ .extern izistep
+ .extern izi
+ .extern FloatMinus2ToThe31nd
+ .extern float_1
+ .extern float_particle_z_clip
+ .extern float_minus_1
+ .extern float_0
+ .extern fp_16
+ .extern fp_64k
+ .extern fp_1m
+ .extern fp_1m_minus_1
+ .extern fp_8
+ .extern entryvec_table
+ .extern advancetable
+ .extern sstep
+ .extern tstep
+ .extern pspantemp
+ .extern counttemp
+ .extern jumptemp
+ .extern reciprocal_table
+ .extern DP_Count
+ .extern DP_u
+ .extern DP_v
+ .extern DP_32768
+ .extern DP_Color
+ .extern DP_Pix
+ .extern DP_EntryTable
+ .extern pbase
+ .extern s
+ .extern t
+ .extern sfracf
+ .extern tfracf
+ .extern snext
+ .extern tnext
+ .extern spancountminus1
+ .extern zi16stepu
+ .extern sdivz16stepu
+ .extern tdivz16stepu
+ .extern zi8stepu
+ .extern sdivz8stepu
+ .extern tdivz8stepu
+ .extern reciprocal_table_16
+ .extern entryvec_table_16
+ .extern ceil_cw
+ .extern single_cw
+ .extern fp_64kx64k
+ .extern pz
+ .extern spr8entryvec_table
+#endif
+
+ .extern C(snd_scaletable)
+ .extern C(paintbuffer)
+ .extern C(snd_linear_count)
+ .extern C(snd_p)
+ .extern C(snd_vol)
+ .extern C(snd_out)
+ .extern C(vright)
+ .extern C(vup)
+ .extern C(vpn)
+ .extern C(BOPS_Error)
+
+//
+// !!! note that this file must match the corresponding C structures at all
+// times !!!
+//
+
+// plane_t structure
+// !!! if this is changed, it must be changed in model.h too !!!
+// !!! if the size of this is changed, the array lookup in SV_HullPointContents
+// must be changed too !!!
+#define pl_normal 0
+#define pl_dist 12
+#define pl_type 16
+#define pl_signbits 17
+#define pl_pad 18
+#define pl_size 20
+
+// hull_t structure
+// !!! if this is changed, it must be changed in model.h too !!!
+#define hu_clipnodes 0
+#define hu_planes 4
+#define hu_firstclipnode 8
+#define hu_lastclipnode 12
+#define hu_clip_mins 16
+#define hu_clip_maxs 28
+#define hu_size 40
+
+// dnode_t structure
+// !!! if this is changed, it must be changed in bspfile.h too !!!
+#define nd_planenum 0
+#define nd_children 4
+#define nd_mins 8
+#define nd_maxs 20
+#define nd_firstface 32
+#define nd_numfaces 36
+#define nd_size 40
+
+// sfxcache_t structure
+// !!! if this is changed, it much be changed in sound.h too !!!
+#define sfxc_length 0
+#define sfxc_loopstart 4
+#define sfxc_speed 8
+#define sfxc_width 12
+#define sfxc_stereo 16
+#define sfxc_data 20
+
+// channel_t structure
+// !!! if this is changed, it much be changed in sound.h too !!!
+#define ch_sfx 0
+#define ch_leftvol 4
+#define ch_rightvol 8
+#define ch_end 12
+#define ch_pos 16
+#define ch_looping 20
+#define ch_entnum 24
+#define ch_entchannel 28
+#define ch_origin 32
+#define ch_dist_mult 44
+#define ch_master_vol 48
+#define ch_size 52
+
+// portable_samplepair_t structure
+// !!! if this is changed, it much be changed in sound.h too !!!
+#define psp_left 0
+#define psp_right 4
+#define psp_size 8
+
+
+//
+// !!! note that this file must match the corresponding C structures at all
+// times !!!
+//
+
+// !!! if this is changed, it must be changed in r_local.h too !!!
+#define NEAR_CLIP 0.01
+
+// !!! if this is changed, it must be changed in r_local.h too !!!
+#define CYCLE 128
+
+// espan_t structure
+// !!! if this is changed, it must be changed in r_shared.h too !!!
+#define espan_t_u 0
+#define espan_t_v 4
+#define espan_t_count 8
+#define espan_t_pnext 12
+#define espan_t_size 16
+
+// sspan_t structure
+// !!! if this is changed, it must be changed in d_local.h too !!!
+#define sspan_t_u 0
+#define sspan_t_v 4
+#define sspan_t_count 8
+#define sspan_t_size 12
+
+// spanpackage_t structure
+// !!! if this is changed, it must be changed in d_polyset.c too !!!
+#define spanpackage_t_pdest 0
+#define spanpackage_t_pz 4
+#define spanpackage_t_count 8
+#define spanpackage_t_ptex 12
+#define spanpackage_t_sfrac 16
+#define spanpackage_t_tfrac 20
+#define spanpackage_t_light 24
+#define spanpackage_t_zi 28
+#define spanpackage_t_size 32
+
+// edge_t structure
+// !!! if this is changed, it must be changed in r_shared.h too !!!
+#define et_u 0
+#define et_u_step 4
+#define et_prev 8
+#define et_next 12
+#define et_surfs 16
+#define et_nextremove 20
+#define et_nearzi 24
+#define et_owner 28
+#define et_size 32
+
+// surf_t structure
+// !!! if this is changed, it must be changed in r_shared.h too !!!
+#define SURF_T_SHIFT 6
+#define st_next 0
+#define st_prev 4
+#define st_spans 8
+#define st_key 12
+#define st_last_u 16
+#define st_spanstate 20
+#define st_flags 24
+#define st_data 28
+#define st_entity 32
+#define st_nearzi 36
+#define st_insubmodel 40
+#define st_d_ziorigin 44
+#define st_d_zistepu 48
+#define st_d_zistepv 52
+#define st_pad 56
+#define st_size 64
+
+// clipplane_t structure
+// !!! if this is changed, it must be changed in r_local.h too !!!
+#define cp_normal 0
+#define cp_dist 12
+#define cp_next 16
+#define cp_leftedge 20
+#define cp_rightedge 21
+#define cp_reserved 22
+#define cp_size 24
+
+// medge_t structure
+// !!! if this is changed, it must be changed in model.h too !!!
+#define me_v 0
+#define me_cachededgeoffset 4
+#define me_size 8
+
+// mvertex_t structure
+// !!! if this is changed, it must be changed in model.h too !!!
+#define mv_position 0
+#define mv_size 12
+
+// refdef_t structure
+// !!! if this is changed, it must be changed in render.h too !!!
+#define rd_vrect 0
+#define rd_aliasvrect 20
+#define rd_vrectright 40
+#define rd_vrectbottom 44
+#define rd_aliasvrectright 48
+#define rd_aliasvrectbottom 52
+#define rd_vrectrightedge 56
+#define rd_fvrectx 60
+#define rd_fvrecty 64
+#define rd_fvrectx_adj 68
+#define rd_fvrecty_adj 72
+#define rd_vrect_x_adj_shift20 76
+#define rd_vrectright_adj_shift20 80
+#define rd_fvrectright_adj 84
+#define rd_fvrectbottom_adj 88
+#define rd_fvrectright 92
+#define rd_fvrectbottom 96
+#define rd_horizontalFieldOfView 100
+#define rd_xOrigin 104
+#define rd_yOrigin 108
+#define rd_vieworg 112
+#define rd_viewangles 124
+#define rd_ambientlight 136
+#define rd_size 140
+
+// mtriangle_t structure
+// !!! if this is changed, it must be changed in model.h too !!!
+#define mtri_facesfront 0
+#define mtri_vertindex 4
+#define mtri_size 16 // !!! if this changes, array indexing in !!!
+ // !!! d_polysa.s must be changed to match !!!
+#define mtri_shift 4
+
+#endif
diff --git a/code/unix/quake3.gif b/code/unix/quake3.gif
new file mode 100755
index 0000000..0e7a01c
--- /dev/null
+++ b/code/unix/quake3.gif
Binary files differ
diff --git a/code/unix/quake3.xpm b/code/unix/quake3.xpm
new file mode 100755
index 0000000..c9b736d
--- /dev/null
+++ b/code/unix/quake3.xpm
@@ -0,0 +1,161 @@
+/* XPM */
+static char *quake3[] = {
+/* width height num_colors chars_per_pixel */
+" 32 32 122 2",
+/* colors */
+".. c #6b1008",
+".# c #6b1810",
+".a c #6b2118",
+".b c #6b2921",
+".c c #6b3129",
+".d c #731810",
+".e c #732118",
+".f c #732921",
+".g c #733129",
+".h c #733931",
+".i c #733939",
+".j c #734239",
+".k c #734a4a",
+".l c #7b1810",
+".m c #7b2118",
+".n c #7b2921",
+".o c #7b4239",
+".p c #7b4a4a",
+".q c #7b524a",
+".r c #7b5252",
+".s c #7b5a5a",
+".t c #7b6363",
+".u c #7b6b6b",
+".v c #7b7373",
+".w c #842110",
+".x c #842118",
+".y c #842921",
+".z c #843129",
+".A c #843931",
+".B c #844239",
+".C c #844a42",
+".D c #84524a",
+".E c #845252",
+".F c #845a5a",
+".G c #846b63",
+".H c #846b6b",
+".I c #847373",
+".J c #847b7b",
+".K c #848484",
+".L c #8c2118",
+".M c #8c2921",
+".N c #8c4239",
+".O c #8c4a42",
+".P c #8c5a52",
+".Q c #8c635a",
+".R c #8c6363",
+".S c #8c6b6b",
+".T c #8c7b7b",
+".U c #8c8484",
+".V c #8c848c",
+".W c #8c8c8c",
+".X c #942921",
+".Y c #944a42",
+".Z c #946363",
+".0 c #946b63",
+".1 c #947373",
+".2 c #947b7b",
+".3 c #948484",
+".4 c #949494",
+".5 c #9c5a5a",
+".6 c #9c6363",
+".7 c #9c6b63",
+".8 c #9c736b",
+".9 c #9c7b73",
+"#. c #9c7b7b",
+"## c #9c8c8c",
+"#a c #9c9494",
+"#b c #9c949c",
+"#c c #9c9c9c",
+"#d c #a55a52",
+"#e c #a5736b",
+"#f c #a57b73",
+"#g c #a57b7b",
+"#h c #a58484",
+"#i c #a58c8c",
+"#j c #a59c9c",
+"#k c #a5a5a5",
+"#l c #ad8c84",
+"#m c #ad8c8c",
+"#n c #ad9494",
+"#o c #ada5a5",
+"#p c #adadad",
+"#q c #b59c9c",
+"#r c #b5a5a5",
+"#s c #b5adad",
+"#t c #b5b5b5",
+"#u c #bda5a5",
+"#v c #bdadad",
+"#w c #bdb5b5",
+"#x c #bdbdbd",
+"#y c #c69c9c",
+"#z c #c6a59c",
+"#A c #c6adad",
+"#B c #c6b5ad",
+"#C c #c6b5b5",
+"#D c #c6bdbd",
+"#E c #c6c6c6",
+"#F c #ceb5b5",
+"#G c #cec6c6",
+"#H c #cecece",
+"#I c #d6b5b5",
+"#J c #d6bdbd",
+"#K c #d6c6bd",
+"#L c #d6cece",
+"#M c #d6d6d6",
+"#N c #decec6",
+"#O c #decece",
+"#P c #ded6ce",
+"#Q c #ded6d6",
+"#R c #dedede",
+"#S c #e7d6d6",
+"#T c #e7dede",
+"#U c #e7e7e7",
+"#V c #efe7e7",
+"#W c #efefe7",
+"#X c #efefef",
+"#Y c #f7efef",
+"#Z c #f7f7ef",
+"#0 c #f7f7f7",
+"#1 c #fff7f7",
+"#2 c #fffff7",
+"#3 c #ffffff",
+/* pixels */
+"#3#2#3#0#3#2#3#2#3#0#3#2#3#2#3#0#3#2#3#2#3#0#3#2#3#2#3#0#3#2#3#2",
+"#3#2#3#2#3#0#3#2#3#2#3#0#3#2#Z#A#3#2#3#0#3#2#3#2#3#0#3#2#3#2#3#0",
+"#3#2#3#0#3#3#2#3#0#3#3#2#3#3#X#l#U#0#3#2#3#3#0#3#2#3#3#2#3#0#3#3",
+"#3#2#3#2#3#0#3#3#2#3#2#3#0#3#Y#e#G#0#3#2#3#2#3#3#0#3#2#3#2#3#0#3",
+"#3#2#3#0#3#3#2#3#0#3#3#2#3#2#U.6#D#X#3#2#3#3#0#3#2#3#3#0#3#2#3#2",
+"#3#2#3#2#3#0#3#2#3#2#3#3#0#3#Q#d#t#X#3#2#3#2#3#0#3#2#3#3#2#3#0#3",
+"#3#2#3#0#3#3#2#3#0#3#2#3#3#2#H.Y#t#X#2#3#1#3#3#2#3#2#3#0#3#3#2#3",
+"#3#2#3#2#3#0#3#3#2#3#2#3#0#3#G.N#s#X#3#2#3#2#3#3#0#3#2#3#2#3#3#0",
+"#3#2#3#0#3#3#2#3#0#3#3#2#3#2#A.A#o#W#3#0#3#3#2#3#2#3#3#0#3#2#3#2",
+"#3#Z#O#s#R#2#3#2#3#2#3#3#0#3#r.z#k#U#2#3#0#3#2#3#2#T#F#L#X#2#3#0",
+"#O.2#B#V#X#X#3#2#3#3#0#3#2#3#n.m#a#U#2#3#3#0#3#2#3#3#X#C#.#u#2#3",
+".D#Q#M#H#M#Z#3#3#0#3#2#3#2#3#h.x.W#R#3#2#3#2#3#3#0#3#Z#R#D.C#M#0",
+".7.D#n#R#1#3#2#3#2#3#0#3#3#1#f.x.W#R#2#3#1#3#2#3#2#0#X#F.5.o#s#U",
+"#V.R.b.f.C.7#i#y#F#K#N#O#P#X.8.w.K#D#O#N#J#I#z#h.7.C.f.f.P#v#k#R",
+"#3#R#a.s.h.a.#...d.d.m.y.n#A.Z.x.I.D.y.m.e.#...#.a.i.t###a#c#x#Y",
+"#3#1#W#E#k.T.H.k.j.j.h.y.m.1.C.L.v.o.l.a.b.h.k.u.v.J.W#c#t#M#0#3",
+"#3#2#3#0#Z#R#E#t#b#a.W.H.y.t.p.X.J.o.g.v.J.V.W.4#o#x#M#V#0#3#2#3",
+"#3#2#3#2#3#3#1#0#X#U#R#r.n.I.q.M.J.p.g.U#t#M#R#V#0#0#2#3#2#3#2#3",
+"#3#2#3#0#3#2#3#2#3#2#3#N.z.J.E.x.K.D.h.4#T#3#2#3#2#3#2#3#0#3#3#2",
+"#3#2#3#2#3#3#0#3#2#3#2#O.A.K.Q.m.K.F.o#a#U#3#2#3#0#3#3#2#3#2#3#0",
+"#3#2#3#0#3#2#3#3#2#3#0#S.B.U.T.d.4.0.p#c#X#3#2#3#2#3#0#3#3#2#3#2",
+"#3#2#3#2#3#3#0#3#2#3#3#S.O.4.3.e.4#g.r#p#X#3#2#3#0#3#3#2#3#0#3#3",
+"#3#2#3#0#3#2#3#2#3#0#3#T.C#a.4.b.4#h.G#s#Z#3#3#2#3#0#3#2#3#2#3#2",
+"#3#2#3#2#3#3#0#3#2#3#2#U.F#j#o.c.4#m.T#w#0#3#0#3#2#3#3#2#3#0#3#3",
+"#3#2#3#0#3#2#3#3#2#3#0#Y.S#o#t.j#j#q###x#0#3#2#3#3#0#3#2#3#3#2#3",
+"#3#2#3#2#3#3#0#3#2#3#3#0.9#w#G.p#k#r#o#E#0#3#2#3#2#3#0#3#2#3#2#3",
+"#3#2#3#0#3#2#3#2#3#0#3#2#n#E#Q.Q#p#w#x#G#0#3#2#3#3#2#3#0#3#3#2#3",
+"#3#2#3#2#3#3#0#3#2#3#3#2#R#H#T.3#t#R#T#R#2#3#2#3#0#3#3#2#3#2#3#0",
+"#3#2#3#0#3#2#3#3#2#3#0#3#2#U#U#s#D#0#0#W#3#3#0#3#2#3#2#3#3#0#3#2",
+"#3#2#3#2#3#3#0#3#2#3#3#2#3#2#3#X#E#0#3#2#3#0#3#3#2#3#0#3#2#3#3#0",
+"#3#2#3#0#3#2#3#2#3#0#3#2#3#3#0#3#W#2#3#0#3#3#2#3#0#3#3#2#3#0#3#2",
+"#3#2#3#2#3#3#0#3#2#3#3#2#3#0#3#2#3#3#0#3#2#3#2#3#2#3#0#3#3#2#3#2"
+};
diff --git a/code/unix/run-target.sh b/code/unix/run-target.sh
new file mode 100755
index 0000000..7a5830c
--- /dev/null
+++ b/code/unix/run-target.sh
@@ -0,0 +1,12 @@
+#!/bin/sh
+# for easy use with Anjuta
+cd `dirname $0`/debugi386-glibc
+echo "in $PWD"
+
+# now execute whatever you want
+#./linuxquake3-smp +set fs_basepath /usr/local/games/quake3 +set developer 1 +set r_smp 1 +set r_showsmp 1 +devmap mythology
+
+#gvd ./linuxquake3-smp --pargs +set logfile 2 +set fs_basepath /usr/local/games/quake3 +set developer 1 +set r_smp 0 +set r_showsmp 1 +devmap mythology
+
+./linuxquake3-smp +set logfile 2 +set fs_basepath /usr/local/games/quake3 +set developer 1 +set r_smp 1 +set r_fullscreen 0 +set r_showsmp 1 +devmap mythology &
+gvd ./linuxquake3-smp
diff --git a/code/unix/snapvector.nasm b/code/unix/snapvector.nasm
new file mode 100755
index 0000000..3232fde
--- /dev/null
+++ b/code/unix/snapvector.nasm
@@ -0,0 +1,95 @@
+;===========================================================================
+;Copyright (C) 1999-2005 Id Software, Inc.
+;
+;This file is part of Quake III Arena source code.
+;
+;Quake III Arena source code is free software; you can redistribute it
+;and/or modify it under the terms of the GNU General Public License as
+;published by the Free Software Foundation; either version 2 of the License,
+;or (at your option) any later version.
+;
+;Quake III Arena source code is distributed in the hope that it will be
+;useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+;MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;GNU General Public License for more details.
+;
+;You should have received a copy of the GNU General Public License
+;along with Foobar; if not, write to the Free Software
+;Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+;===========================================================================
+
+;
+; Sys_SnapVector NASM code (Andrew Henderson)
+; See win32/win_shared.c for the Win32 equivalent
+; This code is provided to ensure that the
+; rounding behavior (and, if necessary, the
+; precision) of DLL and QVM code are identical
+; e.g. for network-visible operations.
+; See ftol.nasm for operations on a single float,
+; as used in compiled VM and DLL code that does
+; not use this system trap.
+;
+
+
+segment .data
+
+fpucw dd 0
+cw037F dd 0x037F ; Rounding to nearest (even).
+
+segment .text
+
+; void Sys_SnapVector( float *v )
+global Sys_SnapVector
+Sys_SnapVector:
+ push eax
+ push ebp
+ mov ebp, esp
+
+ fnstcw [fpucw]
+ mov eax, dword [ebp + 12]
+ fldcw [cw037F]
+ fld dword [eax]
+ fistp dword [eax]
+ fild dword [eax]
+ fstp dword [eax]
+ fld dword [eax + 4]
+ fistp dword [eax + 4]
+ fild dword [eax + 4]
+ fstp dword [eax + 4]
+ fld dword [eax + 8]
+ fistp dword [eax + 8]
+ fild dword [eax + 8]
+ fstp dword [eax + 8]
+ fldcw [fpucw]
+
+ pop ebp
+ pop eax
+ ret
+
+; void Sys_SnapVectorCW( float *v, unsigned short int cw )
+global Sys_SnapVectorCW
+Sys_SnapVector_cw:
+ push eax
+ push ebp
+ mov ebp, esp
+
+ fnstcw [fpucw]
+ mov eax, dword [ebp + 12]
+ fldcw [ebp + 16]
+ fld dword [eax]
+ fistp dword [eax]
+ fild dword [eax]
+ fstp dword [eax]
+ fld dword [eax + 4]
+ fistp dword [eax + 4]
+ fild dword [eax + 4]
+ fstp dword [eax + 4]
+ fld dword [eax + 8]
+ fistp dword [eax + 8]
+ fild dword [eax + 8]
+ fstp dword [eax + 8]
+ fldcw [fpucw]
+
+ pop ebp
+ pop eax
+ ret \ No newline at end of file
diff --git a/code/unix/snd_mixa.s b/code/unix/snd_mixa.s
new file mode 100755
index 0000000..3fc35a8
--- /dev/null
+++ b/code/unix/snd_mixa.s
@@ -0,0 +1,217 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// snd_mixa.s
+// x86 assembly-language sound code
+//
+
+#include "qasm.h"
+
+#if id386
+
+ .text
+
+#if 0
+//----------------------------------------------------------------------
+// 8-bit sound-mixing code
+//----------------------------------------------------------------------
+
+#define ch 4+16
+#define sc 8+16
+#define count 12+16
+
+.globl C(S_PaintChannelFrom8)
+C(S_PaintChannelFrom8):
+ pushl %esi // preserve register variables
+ pushl %edi
+ pushl %ebx
+ pushl %ebp
+
+// int data;
+// short *lscale, *rscale;
+// unsigned char *sfx;
+// int i;
+
+ movl ch(%esp),%ebx
+ movl sc(%esp),%esi
+
+// if (ch->leftvol > 255)
+// ch->leftvol = 255;
+// if (ch->rightvol > 255)
+// ch->rightvol = 255;
+ movl ch_leftvol(%ebx),%eax
+ movl ch_rightvol(%ebx),%edx
+ cmpl $255,%eax
+ jna LLeftSet
+ movl $255,%eax
+LLeftSet:
+ cmpl $255,%edx
+ jna LRightSet
+ movl $255,%edx
+LRightSet:
+
+// lscale = snd_scaletable[ch->leftvol >> 3];
+// rscale = snd_scaletable[ch->rightvol >> 3];
+// sfx = (signed char *)sc->data + ch->pos;
+// ch->pos += count;
+ andl $0xF8,%eax
+ addl $20,%esi
+ movl (%esi),%esi
+ andl $0xF8,%edx
+ movl ch_pos(%ebx),%edi
+ movl count(%esp),%ecx
+ addl %edi,%esi
+ shll $7,%eax
+ addl %ecx,%edi
+ shll $7,%edx
+ movl %edi,ch_pos(%ebx)
+ addl $(C(snd_scaletable)),%eax
+ addl $(C(snd_scaletable)),%edx
+ subl %ebx,%ebx
+ movb -1(%esi,%ecx,1),%bl
+
+ testl $1,%ecx
+ jz LMix8Loop
+
+ movl (%eax,%ebx,4),%edi
+ movl (%edx,%ebx,4),%ebp
+ addl C(paintbuffer)+psp_left-psp_size(,%ecx,psp_size),%edi
+ addl C(paintbuffer)+psp_right-psp_size(,%ecx,psp_size),%ebp
+ movl %edi,C(paintbuffer)+psp_left-psp_size(,%ecx,psp_size)
+ movl %ebp,C(paintbuffer)+psp_right-psp_size(,%ecx,psp_size)
+ movb -2(%esi,%ecx,1),%bl
+
+ decl %ecx
+ jz LDone
+
+// for (i=0 ; i<count ; i++)
+// {
+LMix8Loop:
+
+// data = sfx[i];
+// paintbuffer[i].left += lscale[data];
+// paintbuffer[i].right += rscale[data];
+ movl (%eax,%ebx,4),%edi
+ movl (%edx,%ebx,4),%ebp
+ addl C(paintbuffer)+psp_left-psp_size(,%ecx,psp_size),%edi
+ addl C(paintbuffer)+psp_right-psp_size(,%ecx,psp_size),%ebp
+ movb -2(%esi,%ecx,1),%bl
+ movl %edi,C(paintbuffer)+psp_left-psp_size(,%ecx,psp_size)
+ movl %ebp,C(paintbuffer)+psp_right-psp_size(,%ecx,psp_size)
+
+ movl (%eax,%ebx,4),%edi
+ movl (%edx,%ebx,4),%ebp
+ movb -3(%esi,%ecx,1),%bl
+ addl C(paintbuffer)+psp_left-psp_size*2(,%ecx,psp_size),%edi
+ addl C(paintbuffer)+psp_right-psp_size*2(,%ecx,psp_size),%ebp
+ movl %edi,C(paintbuffer)+psp_left-psp_size*2(,%ecx,psp_size)
+ movl %ebp,C(paintbuffer)+psp_right-psp_size*2(,%ecx,psp_size)
+
+// }
+ subl $2,%ecx
+ jnz LMix8Loop
+
+LDone:
+ popl %ebp
+ popl %ebx
+ popl %edi
+ popl %esi
+
+ ret
+
+
+#endif
+
+//----------------------------------------------------------------------
+// Transfer of stereo buffer to 16-bit DMA buffer code
+//----------------------------------------------------------------------
+
+.globl C(S_WriteLinearBlastStereo16)
+C(S_WriteLinearBlastStereo16):
+ pushl %edi
+ pushl %ebx
+
+// int i;
+// int val;
+ movl C(snd_linear_count),%ecx
+ movl C(snd_p),%ebx
+ movl C(snd_out),%edi
+
+// for (i=0 ; i<snd_linear_count ; i+=2)
+// {
+LWLBLoopTop:
+
+// val = (snd_p[i]*snd_vol)>>8;
+// if (val > 0x7fff)
+// snd_out[i] = 0x7fff;
+// else if (val < (short)0x8000)
+// snd_out[i] = (short)0x8000;
+// else
+// snd_out[i] = val;
+ movl -8(%ebx,%ecx,4),%eax
+ sarl $8,%eax
+ cmpl $0x7FFF,%eax
+ jg LClampHigh
+ cmpl $0xFFFF8000,%eax
+ jnl LClampDone
+ movl $0xFFFF8000,%eax
+ jmp LClampDone
+LClampHigh:
+ movl $0x7FFF,%eax
+LClampDone:
+
+// val = (snd_p[i+1]*snd_vol)>>8;
+// if (val > 0x7fff)
+// snd_out[i+1] = 0x7fff;
+// else if (val < (short)0x8000)
+// snd_out[i+1] = (short)0x8000;
+// else
+// snd_out[i+1] = val;
+ movl -4(%ebx,%ecx,4),%edx
+ sarl $8,%edx
+ cmpl $0x7FFF,%edx
+ jg LClampHigh2
+ cmpl $0xFFFF8000,%edx
+ jnl LClampDone2
+ movl $0xFFFF8000,%edx
+ jmp LClampDone2
+LClampHigh2:
+ movl $0x7FFF,%edx
+LClampDone2:
+ shll $16,%edx
+ andl $0xFFFF,%eax
+ orl %eax,%edx
+ movl %edx,-4(%edi,%ecx,2)
+
+// }
+ subl $2,%ecx
+ jnz LWLBLoopTop
+
+// snd_p += snd_linear_count;
+
+ popl %ebx
+ popl %edi
+
+ ret
+
+#endif // id386
+
diff --git a/code/unix/sys_dosa.s b/code/unix/sys_dosa.s
new file mode 100755
index 0000000..4b1aca5
--- /dev/null
+++ b/code/unix/sys_dosa.s
@@ -0,0 +1,115 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// sys_dosa.s
+// x86 assembly-language DOS-dependent routines.
+
+#include "qasm.h"
+
+
+ .data
+
+ .align 4
+fpenv:
+ .long 0, 0, 0, 0, 0, 0, 0, 0
+
+ .text
+
+.globl C(MaskExceptions)
+C(MaskExceptions):
+ fnstenv fpenv
+ orl $0x3F,fpenv
+ fldenv fpenv
+
+ ret
+
+#if 0
+.globl C(unmaskexceptions)
+C(unmaskexceptions):
+ fnstenv fpenv
+ andl $0xFFFFFFE0,fpenv
+ fldenv fpenv
+
+ ret
+#endif
+
+ .data
+
+ .align 4
+.globl ceil_cw, single_cw, full_cw, cw, pushed_cw
+ceil_cw: .long 0
+single_cw: .long 0
+full_cw: .long 0
+cw: .long 0
+pushed_cw: .long 0
+
+ .text
+
+.globl C(Sys_LowFPPrecision)
+C(Sys_LowFPPrecision):
+ fldcw single_cw
+
+ ret
+
+.globl C(Sys_HighFPPrecision)
+C(Sys_HighFPPrecision):
+ fldcw full_cw
+
+ ret
+
+.globl C(Sys_PushFPCW_SetHigh)
+C(Sys_PushFPCW_SetHigh):
+ fnstcw pushed_cw
+ fldcw full_cw
+
+ ret
+
+.globl C(Sys_PopFPCW)
+C(Sys_PopFPCW):
+ fldcw pushed_cw
+
+ ret
+
+.globl C(Sys_SetFPCW)
+C(Sys_SetFPCW):
+ fnstcw cw
+ movl cw,%eax
+#if id386
+ andb $0xF0,%ah
+ orb $0x03,%ah // round mode, 64-bit precision
+#endif
+ movl %eax,full_cw
+
+#if id386
+ andb $0xF0,%ah
+ orb $0x0C,%ah // chop mode, single precision
+#endif
+ movl %eax,single_cw
+
+#if id386
+ andb $0xF0,%ah
+ orb $0x08,%ah // ceil mode, single precision
+#endif
+ movl %eax,ceil_cw
+
+ ret
+
diff --git a/code/unix/unix_glw.h b/code/unix/unix_glw.h
new file mode 100755
index 0000000..9a84f0c
--- /dev/null
+++ b/code/unix/unix_glw.h
@@ -0,0 +1,38 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !( defined __linux__ || defined __FreeBSD__ )
+#error You should include this file only on Linux/FreeBSD platforms
+#endif
+
+#ifndef __GLW_LINUX_H__
+#define __GLW_LINUX_H__
+
+typedef struct
+{
+ void *OpenGLLib; // instance of OpenGL library
+
+ FILE *log_fp;
+} glwstate_t;
+
+extern glwstate_t glw_state;
+
+#endif
diff --git a/code/unix/unix_main.c b/code/unix/unix_main.c
new file mode 100755
index 0000000..e439568
--- /dev/null
+++ b/code/unix/unix_main.c
@@ -0,0 +1,1273 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include <unistd.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <limits.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <sys/ipc.h>
+#include <sys/shm.h>
+#include <sys/stat.h>
+#include <string.h>
+#include <ctype.h>
+#include <sys/wait.h>
+#include <sys/mman.h>
+#include <errno.h>
+#ifdef __linux__ // rb010123
+ #include <mntent.h>
+#endif
+#include <dlfcn.h>
+
+#ifdef __linux__
+ #include <fpu_control.h> // bk001213 - force dumps on divide by zero
+#endif
+
+// FIXME TTimo should we gard this? most *nix system should comply?
+#include <termios.h>
+
+#include "../game/q_shared.h"
+#include "../qcommon/qcommon.h"
+#include "../renderer/tr_public.h"
+
+#include "linux_local.h" // bk001204
+
+// Structure containing functions exported from refresh DLL
+refexport_t re;
+
+unsigned sys_frame_time;
+
+uid_t saved_euid;
+qboolean stdin_active = qtrue;
+
+// =============================================================
+// tty console variables
+// =============================================================
+
+// enable/disabled tty input mode
+// NOTE TTimo this is used during startup, cannot be changed during run
+static cvar_t *ttycon = NULL;
+// general flag to tell about tty console mode
+static qboolean ttycon_on = qfalse;
+// when printing general stuff to stdout stderr (Sys_Printf)
+// we need to disable the tty console stuff
+// this increments so we can recursively disable
+static int ttycon_hide = 0;
+// some key codes that the terminal may be using
+// TTimo NOTE: I'm not sure how relevant this is
+static int tty_erase;
+static int tty_eof;
+
+static struct termios tty_tc;
+
+static field_t tty_con;
+
+// history
+// NOTE TTimo this is a bit duplicate of the graphical console history
+// but it's safer and faster to write our own here
+#define TTY_HISTORY 32
+static field_t ttyEditLines[TTY_HISTORY];
+static int hist_current = -1, hist_count = 0;
+
+// =======================================================================
+// General routines
+// =======================================================================
+
+// bk001207
+#define MEM_THRESHOLD 96*1024*1024
+
+/*
+==================
+Sys_LowPhysicalMemory()
+==================
+*/
+qboolean Sys_LowPhysicalMemory() {
+ //MEMORYSTATUS stat;
+ //GlobalMemoryStatus (&stat);
+ //return (stat.dwTotalPhys <= MEM_THRESHOLD) ? qtrue : qfalse;
+ return qfalse; // bk001207 - FIXME
+}
+
+/*
+==================
+Sys_FunctionCmp
+==================
+*/
+int Sys_FunctionCmp(void *f1, void *f2) {
+ return qtrue;
+}
+
+/*
+==================
+Sys_FunctionCheckSum
+==================
+*/
+int Sys_FunctionCheckSum(void *f1) {
+ return 0;
+}
+
+/*
+==================
+Sys_MonkeyShouldBeSpanked
+==================
+*/
+int Sys_MonkeyShouldBeSpanked( void ) {
+ return 0;
+}
+
+void Sys_BeginProfiling( void ) {
+}
+
+/*
+=================
+Sys_In_Restart_f
+
+Restart the input subsystem
+=================
+*/
+void Sys_In_Restart_f( void )
+{
+ IN_Shutdown();
+ IN_Init();
+}
+
+// =============================================================
+// tty console routines
+// NOTE: if the user is editing a line when something gets printed to the early console then it won't look good
+// so we provide tty_Clear and tty_Show to be called before and after a stdout or stderr output
+// =============================================================
+
+// flush stdin, I suspect some terminals are sending a LOT of shit
+// FIXME TTimo relevant?
+void tty_FlushIn()
+{
+ char key;
+ while (read(0, &key, 1)!=-1);
+}
+
+// do a backspace
+// TTimo NOTE: it seems on some terminals just sending '\b' is not enough
+// so for now, in any case we send "\b \b" .. yeah well ..
+// (there may be a way to find out if '\b' alone would work though)
+void tty_Back()
+{
+ char key;
+ key = '\b';
+ write(1, &key, 1);
+ key = ' ';
+ write(1, &key, 1);
+ key = '\b';
+ write(1, &key, 1);
+}
+
+// clear the display of the line currently edited
+// bring cursor back to beginning of line
+void tty_Hide()
+{
+ int i;
+ assert(ttycon_on);
+ if (ttycon_hide)
+ {
+ ttycon_hide++;
+ return;
+ }
+ if (tty_con.cursor>0)
+ {
+ for (i=0; i<tty_con.cursor; i++)
+ {
+ tty_Back();
+ }
+ }
+ ttycon_hide++;
+}
+
+// show the current line
+// FIXME TTimo need to position the cursor if needed??
+void tty_Show()
+{
+ int i;
+ assert(ttycon_on);
+ assert(ttycon_hide>0);
+ ttycon_hide--;
+ if (ttycon_hide == 0)
+ {
+ if (tty_con.cursor)
+ {
+ for (i=0; i<tty_con.cursor; i++)
+ {
+ write(1, tty_con.buffer+i, 1);
+ }
+ }
+ }
+}
+
+// never exit without calling this, or your terminal will be left in a pretty bad state
+void Sys_ConsoleInputShutdown()
+{
+ if (ttycon_on)
+ {
+ Com_Printf("Shutdown tty console\n");
+ tcsetattr (0, TCSADRAIN, &tty_tc);
+ }
+}
+
+void Hist_Add(field_t *field)
+{
+ int i;
+ assert(hist_count <= TTY_HISTORY);
+ assert(hist_count >= 0);
+ assert(hist_current >= -1);
+ assert(hist_current <= hist_count);
+ // make some room
+ for (i=TTY_HISTORY-1; i>0; i--)
+ {
+ ttyEditLines[i] = ttyEditLines[i-1];
+ }
+ ttyEditLines[0] = *field;
+ if (hist_count<TTY_HISTORY)
+ {
+ hist_count++;
+ }
+ hist_current = -1; // re-init
+}
+
+field_t *Hist_Prev()
+{
+ int hist_prev;
+ assert(hist_count <= TTY_HISTORY);
+ assert(hist_count >= 0);
+ assert(hist_current >= -1);
+ assert(hist_current <= hist_count);
+ hist_prev = hist_current + 1;
+ if (hist_prev >= hist_count)
+ {
+ return NULL;
+ }
+ hist_current++;
+ return &(ttyEditLines[hist_current]);
+}
+
+field_t *Hist_Next()
+{
+ assert(hist_count <= TTY_HISTORY);
+ assert(hist_count >= 0);
+ assert(hist_current >= -1);
+ assert(hist_current <= hist_count);
+ if (hist_current >= 0)
+ {
+ hist_current--;
+ }
+ if (hist_current == -1)
+ {
+ return NULL;
+ }
+ return &(ttyEditLines[hist_current]);
+}
+
+// =============================================================
+// general sys routines
+// =============================================================
+
+#if 0
+// NOTE TTimo this is not used .. looks interesting though? protection against buffer overflow kind of stuff?
+void Sys_Printf (char *fmt, ...)
+{
+ va_list argptr;
+ char text[1024];
+ unsigned char *p;
+
+ va_start (argptr,fmt);
+ vsprintf (text,fmt,argptr);
+ va_end (argptr);
+
+ if (strlen(text) > sizeof(text))
+ Sys_Error("memory overwrite in Sys_Printf");
+
+ for (p = (unsigned char *)text; *p; p++)
+ {
+ *p &= 0x7f;
+ if ((*p > 128 || *p < 32) && *p != 10 && *p != 13 && *p != 9)
+ printf("[%02x]", *p);
+ else
+ putc(*p, stdout);
+ }
+}
+#endif
+
+// single exit point (regular exit or in case of signal fault)
+void Sys_Exit( int ex ) {
+ Sys_ConsoleInputShutdown();
+
+#ifdef NDEBUG // regular behavior
+
+ // We can't do this
+ // as long as GL DLL's keep installing with atexit...
+ //exit(ex);
+ _exit(ex);
+#else
+
+ // Give me a backtrace on error exits.
+ assert( ex == 0 );
+ exit(ex);
+#endif
+}
+
+
+void Sys_Quit (void) {
+ CL_Shutdown ();
+ fcntl (0, F_SETFL, fcntl (0, F_GETFL, 0) & ~FNDELAY);
+ Sys_Exit(0);
+}
+
+void Sys_Init(void)
+{
+ Cmd_AddCommand ("in_restart", Sys_In_Restart_f);
+
+#if defined __linux__
+#if defined __i386__
+ Cvar_Set( "arch", "linux i386" );
+#elif defined __alpha__
+ Cvar_Set( "arch", "linux alpha" );
+#elif defined __sparc__
+ Cvar_Set( "arch", "linux sparc" );
+#elif defined __FreeBSD__
+
+#if defined __i386__ // FreeBSD
+ Cvar_Set( "arch", "freebsd i386" );
+#elif defined __alpha__
+ Cvar_Set( "arch", "freebsd alpha" );
+#else
+ Cvar_Set( "arch", "freebsd unknown" );
+#endif // FreeBSD
+
+#else
+ Cvar_Set( "arch", "linux unknown" );
+#endif
+#elif defined __sun__
+#if defined __i386__
+ Cvar_Set( "arch", "solaris x86" );
+#elif defined __sparc__
+ Cvar_Set( "arch", "solaris sparc" );
+#else
+ Cvar_Set( "arch", "solaris unknown" );
+#endif
+#elif defined __sgi__
+#if defined __mips__
+ Cvar_Set( "arch", "sgi mips" );
+#else
+ Cvar_Set( "arch", "sgi unknown" );
+#endif
+#else
+ Cvar_Set( "arch", "unknown" );
+#endif
+
+ Cvar_Set( "username", Sys_GetCurrentUser() );
+
+ IN_Init();
+
+}
+
+void Sys_Error( const char *error, ...)
+{
+ va_list argptr;
+ char string[1024];
+
+ // change stdin to non blocking
+ // NOTE TTimo not sure how well that goes with tty console mode
+ fcntl (0, F_SETFL, fcntl (0, F_GETFL, 0) & ~FNDELAY);
+
+ // don't bother do a show on this one heh
+ if (ttycon_on)
+ {
+ tty_Hide();
+ }
+
+ CL_Shutdown ();
+
+ va_start (argptr,error);
+ vsprintf (string,error,argptr);
+ va_end (argptr);
+ fprintf(stderr, "Sys_Error: %s\n", string);
+
+ Sys_Exit( 1 ); // bk010104 - use single exit point.
+}
+
+void Sys_Warn (char *warning, ...)
+{
+ va_list argptr;
+ char string[1024];
+
+ va_start (argptr,warning);
+ vsprintf (string,warning,argptr);
+ va_end (argptr);
+
+ if (ttycon_on)
+ {
+ tty_Hide();
+ }
+
+ fprintf(stderr, "Warning: %s", string);
+
+ if (ttycon_on)
+ {
+ tty_Show();
+ }
+}
+
+/*
+============
+Sys_FileTime
+
+returns -1 if not present
+============
+*/
+int Sys_FileTime (char *path)
+{
+ struct stat buf;
+
+ if (stat (path,&buf) == -1)
+ return -1;
+
+ return buf.st_mtime;
+}
+
+void floating_point_exception_handler(int whatever)
+{
+ signal(SIGFPE, floating_point_exception_handler);
+}
+
+// initialize the console input (tty mode if wanted and possible)
+void Sys_ConsoleInputInit()
+{
+ struct termios tc;
+
+ // TTimo
+ // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=390
+ // ttycon 0 or 1, if the process is backgrounded (running non interactively)
+ // then SIGTTIN or SIGTOU is emitted, if not catched, turns into a SIGSTP
+ signal(SIGTTIN, SIG_IGN);
+ signal(SIGTTOU, SIG_IGN);
+
+ // FIXME TTimo initialize this in Sys_Init or something?
+ ttycon = Cvar_Get("ttycon", "1", 0);
+ if (ttycon && ttycon->value)
+ {
+ if (isatty(STDIN_FILENO)!=1)
+ {
+ Com_Printf("stdin is not a tty, tty console mode failed\n");
+ Cvar_Set("ttycon", "0");
+ ttycon_on = qfalse;
+ return;
+ }
+ Com_Printf("Started tty console (use +set ttycon 0 to disable)\n");
+ Field_Clear(&tty_con);
+ tcgetattr (0, &tty_tc);
+ tty_erase = tty_tc.c_cc[VERASE];
+ tty_eof = tty_tc.c_cc[VEOF];
+ tc = tty_tc;
+ /*
+ ECHO: don't echo input characters
+ ICANON: enable canonical mode. This enables the special
+ characters EOF, EOL, EOL2, ERASE, KILL, REPRINT,
+ STATUS, and WERASE, and buffers by lines.
+ ISIG: when any of the characters INTR, QUIT, SUSP, or
+ DSUSP are received, generate the corresponding sig­
+ nal
+ */
+ tc.c_lflag &= ~(ECHO | ICANON);
+ /*
+ ISTRIP strip off bit 8
+ INPCK enable input parity checking
+ */
+ tc.c_iflag &= ~(ISTRIP | INPCK);
+ tc.c_cc[VMIN] = 1;
+ tc.c_cc[VTIME] = 0;
+ tcsetattr (0, TCSADRAIN, &tc);
+ ttycon_on = qtrue;
+ } else
+ ttycon_on = qfalse;
+}
+
+char *Sys_ConsoleInput(void)
+{
+ // we use this when sending back commands
+ static char text[256];
+ int i;
+ int avail;
+ char key;
+ field_t *history;
+
+ if (ttycon && ttycon->value)
+ {
+ avail = read(0, &key, 1);
+ if (avail != -1)
+ {
+ // we have something
+ // backspace?
+ // NOTE TTimo testing a lot of values .. seems it's the only way to get it to work everywhere
+ if ((key == tty_erase) || (key == 127) || (key == 8))
+ {
+ if (tty_con.cursor > 0)
+ {
+ tty_con.cursor--;
+ tty_con.buffer[tty_con.cursor] = '\0';
+ tty_Back();
+ }
+ return NULL;
+ }
+ // check if this is a control char
+ if ((key) && (key) < ' ')
+ {
+ if (key == '\n')
+ {
+ // push it in history
+ Hist_Add(&tty_con);
+ strcpy(text, tty_con.buffer);
+ Field_Clear(&tty_con);
+ key = '\n';
+ write(1, &key, 1);
+ return text;
+ }
+ if (key == '\t')
+ {
+ tty_Hide();
+ Field_CompleteCommand( &tty_con );
+ // Field_CompleteCommand does weird things to the string, do a cleanup
+ // it adds a '\' at the beginning of the string
+ // cursor doesn't reflect actual length of the string that's sent back
+ tty_con.cursor = strlen(tty_con.buffer);
+ if (tty_con.cursor>0)
+ {
+ if (tty_con.buffer[0] == '\\')
+ {
+ for (i=0; i<=tty_con.cursor; i++)
+ {
+ tty_con.buffer[i] = tty_con.buffer[i+1];
+ }
+ tty_con.cursor--;
+ }
+ }
+ tty_Show();
+ return NULL;
+ }
+ avail = read(0, &key, 1);
+ if (avail != -1)
+ {
+ // VT 100 keys
+ if (key == '[' || key == 'O')
+ {
+ avail = read(0, &key, 1);
+ if (avail != -1)
+ {
+ switch (key)
+ {
+ case 'A':
+ history = Hist_Prev();
+ if (history)
+ {
+ tty_Hide();
+ tty_con = *history;
+ tty_Show();
+ }
+ tty_FlushIn();
+ return NULL;
+ break;
+ case 'B':
+ history = Hist_Next();
+ tty_Hide();
+ if (history)
+ {
+ tty_con = *history;
+ } else
+ {
+ Field_Clear(&tty_con);
+ }
+ tty_Show();
+ tty_FlushIn();
+ return NULL;
+ break;
+ case 'C':
+ return NULL;
+ case 'D':
+ return NULL;
+ }
+ }
+ }
+ }
+ Com_DPrintf("droping ISCTL sequence: %d, tty_erase: %d\n", key, tty_erase);
+ tty_FlushIn();
+ return NULL;
+ }
+ // push regular character
+ tty_con.buffer[tty_con.cursor] = key;
+ tty_con.cursor++;
+ // print the current line (this is differential)
+ write(1, &key, 1);
+ }
+ return NULL;
+ } else
+ {
+ int len;
+ fd_set fdset;
+ struct timeval timeout;
+
+ if (!com_dedicated || !com_dedicated->value)
+ return NULL;
+
+ if (!stdin_active)
+ return NULL;
+
+ FD_ZERO(&fdset);
+ FD_SET(0, &fdset); // stdin
+ timeout.tv_sec = 0;
+ timeout.tv_usec = 0;
+ if (select (1, &fdset, NULL, NULL, &timeout) == -1 || !FD_ISSET(0, &fdset))
+ {
+ return NULL;
+ }
+
+ len = read (0, text, sizeof(text));
+ if (len == 0)
+ { // eof!
+ stdin_active = qfalse;
+ return NULL;
+ }
+
+ if (len < 1)
+ return NULL;
+ text[len-1] = 0; // rip off the /n and terminate
+
+ return text;
+ }
+}
+
+/*****************************************************************************/
+
+/*
+=================
+Sys_UnloadDll
+
+=================
+*/
+void Sys_UnloadDll( void *dllHandle ) {
+ // bk001206 - verbose error reporting
+ const char* err; // rb010123 - now const
+ if ( !dllHandle )
+ {
+ Com_Printf("Sys_UnloadDll(NULL)\n");
+ return;
+ }
+ dlclose( dllHandle );
+ err = dlerror();
+ if ( err != NULL )
+ Com_Printf ( "Sys_UnloadGame failed on dlclose: \"%s\"!\n", err );
+}
+
+
+/*
+=================
+Sys_LoadDll
+
+Used to load a development dll instead of a virtual machine
+TTimo:
+changed the load procedure to match VFS logic, and allow developer use
+#1 look down current path
+#2 look in fs_homepath
+#3 look in fs_basepath
+=================
+*/
+extern char *FS_BuildOSPath( const char *base, const char *game, const char *qpath );
+
+void *Sys_LoadDll( const char *name, char *fqpath ,
+ int (**entryPoint)(int, ...),
+ int (*systemcalls)(int, ...) )
+{
+ void *libHandle;
+ void (*dllEntry)( int (*syscallptr)(int, ...) );
+ char curpath[MAX_OSPATH];
+ char fname[MAX_OSPATH];
+ char *basepath;
+ char *homepath;
+ char *pwdpath;
+ char *gamedir;
+ char *fn;
+ const char* err = NULL;
+
+ *fqpath = 0;
+
+ // bk001206 - let's have some paranoia
+ assert( name );
+
+ getcwd(curpath, sizeof(curpath));
+#if defined __i386__
+ snprintf (fname, sizeof(fname), "%si386.so", name);
+#elif defined __powerpc__ //rcg010207 - PPC support.
+ snprintf (fname, sizeof(fname), "%sppc.so", name);
+#elif defined __axp__
+ snprintf (fname, sizeof(fname), "%saxp.so", name);
+#elif defined __mips__
+ snprintf (fname, sizeof(fname), "%smips.so", name);
+#else
+#error Unknown arch
+#endif
+
+// bk001129 - was RTLD_LAZY
+#define Q_RTLD RTLD_NOW
+
+ pwdpath = Sys_Cwd();
+ basepath = Cvar_VariableString( "fs_basepath" );
+ homepath = Cvar_VariableString( "fs_homepath" );
+ gamedir = Cvar_VariableString( "fs_game" );
+
+ // pwdpath
+ fn = FS_BuildOSPath( pwdpath, gamedir, fname );
+ Com_Printf( "Sys_LoadDll(%s)... \n", fn );
+ libHandle = dlopen( fn, Q_RTLD );
+
+ if ( !libHandle )
+ {
+ Com_Printf( "Sys_LoadDll(%s) failed:\n\"%s\"\n", fn, dlerror() );
+ // fs_homepath
+ fn = FS_BuildOSPath( homepath, gamedir, fname );
+ Com_Printf( "Sys_LoadDll(%s)... \n", fn );
+ libHandle = dlopen( fn, Q_RTLD );
+
+ if ( !libHandle )
+ {
+ Com_Printf( "Sys_LoadDll(%s) failed:\n\"%s\"\n", fn, dlerror() );
+ // fs_basepath
+ fn = FS_BuildOSPath( basepath, gamedir, fname );
+ Com_Printf( "Sys_LoadDll(%s)... \n", fn );
+ libHandle = dlopen( fn, Q_RTLD );
+
+ if ( !libHandle )
+ {
+#ifndef NDEBUG // bk001206 - in debug abort on failure
+ Com_Error ( ERR_FATAL, "Sys_LoadDll(%s) failed dlopen() completely!\n", name );
+#else
+ Com_Printf ( "Sys_LoadDll(%s) failed dlopen() completely!\n", name );
+#endif
+ return NULL;
+ } else
+ Com_Printf ( "Sys_LoadDll(%s): succeeded ...\n", fn );
+ } else
+ Com_Printf ( "Sys_LoadDll(%s): succeeded ...\n", fn );
+ } else
+ Com_Printf ( "Sys_LoadDll(%s): succeeded ...\n", fn );
+
+ dllEntry = dlsym( libHandle, "dllEntry" );
+ *entryPoint = dlsym( libHandle, "vmMain" );
+ if ( !*entryPoint || !dllEntry )
+ {
+ err = dlerror();
+#ifndef NDEBUG // bk001206 - in debug abort on failure
+ Com_Error ( ERR_FATAL, "Sys_LoadDll(%s) failed dlsym(vmMain):\n\"%s\" !\n", name, err );
+#else
+ Com_Printf ( "Sys_LoadDll(%s) failed dlsym(vmMain):\n\"%s\" !\n", name, err );
+#endif
+ dlclose( libHandle );
+ err = dlerror();
+ if ( err != NULL )
+ Com_Printf ( "Sys_LoadDll(%s) failed dlcose:\n\"%s\"\n", name, err );
+ return NULL;
+ }
+ Com_Printf ( "Sys_LoadDll(%s) found **vmMain** at %p \n", name, *entryPoint ); // bk001212
+ dllEntry( systemcalls );
+ Com_Printf ( "Sys_LoadDll(%s) succeeded!\n", name );
+ if ( libHandle ) Q_strncpyz ( fqpath , fn , MAX_QPATH ) ; // added 7/20/02 by T.Ray
+ return libHandle;
+}
+
+/*
+========================================================================
+
+BACKGROUND FILE STREAMING
+
+========================================================================
+*/
+
+#if 1
+
+void Sys_InitStreamThread( void ) {
+}
+
+void Sys_ShutdownStreamThread( void ) {
+}
+
+void Sys_BeginStreamedFile( fileHandle_t f, int readAhead ) {
+}
+
+void Sys_EndStreamedFile( fileHandle_t f ) {
+}
+
+int Sys_StreamedRead( void *buffer, int size, int count, fileHandle_t f ) {
+ return FS_Read( buffer, size * count, f );
+}
+
+void Sys_StreamSeek( fileHandle_t f, int offset, int origin ) {
+ FS_Seek( f, offset, origin );
+}
+
+#else
+
+typedef struct
+{
+ fileHandle_t file;
+ byte *buffer;
+ qboolean eof;
+ int bufferSize;
+ int streamPosition; // next byte to be returned by Sys_StreamRead
+ int threadPosition; // next byte to be read from file
+} streamState_t;
+
+streamState_t stream;
+
+/*
+===============
+Sys_StreamThread
+
+A thread will be sitting in this loop forever
+================
+*/
+void Sys_StreamThread( void )
+{
+ int buffer;
+ int count;
+ int readCount;
+ int bufferPoint;
+ int r;
+
+ // if there is any space left in the buffer, fill it up
+ if ( !stream.eof )
+ {
+ count = stream.bufferSize - (stream.threadPosition - stream.streamPosition);
+ if ( count )
+ {
+ bufferPoint = stream.threadPosition % stream.bufferSize;
+ buffer = stream.bufferSize - bufferPoint;
+ readCount = buffer < count ? buffer : count;
+ r = FS_Read ( stream.buffer + bufferPoint, readCount, stream.file );
+ stream.threadPosition += r;
+
+ if ( r != readCount )
+ stream.eof = qtrue;
+ }
+ }
+}
+
+/*
+===============
+Sys_InitStreamThread
+
+================
+*/
+void Sys_InitStreamThread( void )
+{
+}
+
+/*
+===============
+Sys_ShutdownStreamThread
+
+================
+*/
+void Sys_ShutdownStreamThread( void )
+{
+}
+
+
+/*
+===============
+Sys_BeginStreamedFile
+
+================
+*/
+void Sys_BeginStreamedFile( fileHandle_t f, int readAhead )
+{
+ if ( stream.file )
+ {
+ Com_Error( ERR_FATAL, "Sys_BeginStreamedFile: unclosed stream");
+ }
+
+ stream.file = f;
+ stream.buffer = Z_Malloc( readAhead );
+ stream.bufferSize = readAhead;
+ stream.streamPosition = 0;
+ stream.threadPosition = 0;
+ stream.eof = qfalse;
+}
+
+/*
+===============
+Sys_EndStreamedFile
+
+================
+*/
+void Sys_EndStreamedFile( fileHandle_t f )
+{
+ if ( f != stream.file )
+ {
+ Com_Error( ERR_FATAL, "Sys_EndStreamedFile: wrong file");
+ }
+
+ stream.file = 0;
+ Z_Free( stream.buffer );
+}
+
+
+/*
+===============
+Sys_StreamedRead
+
+================
+*/
+int Sys_StreamedRead( void *buffer, int size, int count, fileHandle_t f )
+{
+ int available;
+ int remaining;
+ int sleepCount;
+ int copy;
+ int bufferCount;
+ int bufferPoint;
+ byte *dest;
+
+ dest = (byte *)buffer;
+ remaining = size * count;
+
+ if ( remaining <= 0 )
+ {
+ Com_Error( ERR_FATAL, "Streamed read with non-positive size" );
+ }
+
+ sleepCount = 0;
+ while ( remaining > 0 )
+ {
+ available = stream.threadPosition - stream.streamPosition;
+ if ( !available )
+ {
+ if (stream.eof)
+ break;
+ Sys_StreamThread();
+ continue;
+ }
+
+ bufferPoint = stream.streamPosition % stream.bufferSize;
+ bufferCount = stream.bufferSize - bufferPoint;
+
+ copy = available < bufferCount ? available : bufferCount;
+ if ( copy > remaining )
+ {
+ copy = remaining;
+ }
+ memcpy( dest, stream.buffer + bufferPoint, copy );
+ stream.streamPosition += copy;
+ dest += copy;
+ remaining -= copy;
+ }
+
+ return(count * size - remaining) / size;
+}
+
+/*
+===============
+Sys_StreamSeek
+
+================
+*/
+void Sys_StreamSeek( fileHandle_t f, int offset, int origin ) {
+ // clear to that point
+ FS_Seek( f, offset, origin );
+ stream.streamPosition = 0;
+ stream.threadPosition = 0;
+ stream.eof = qfalse;
+}
+
+#endif
+
+/*
+========================================================================
+
+EVENT LOOP
+
+========================================================================
+*/
+
+// bk000306: upped this from 64
+#define MAX_QUED_EVENTS 256
+#define MASK_QUED_EVENTS ( MAX_QUED_EVENTS - 1 )
+
+sysEvent_t eventQue[MAX_QUED_EVENTS];
+// bk000306: initialize
+int eventHead = 0;
+int eventTail = 0;
+byte sys_packetReceived[MAX_MSGLEN];
+
+/*
+================
+Sys_QueEvent
+
+A time of 0 will get the current time
+Ptr should either be null, or point to a block of data that can
+be freed by the game later.
+================
+*/
+void Sys_QueEvent( int time, sysEventType_t type, int value, int value2, int ptrLength, void *ptr ) {
+ sysEvent_t *ev;
+
+ ev = &eventQue[ eventHead & MASK_QUED_EVENTS ];
+
+ // bk000305 - was missing
+ if ( eventHead - eventTail >= MAX_QUED_EVENTS )
+ {
+ Com_Printf("Sys_QueEvent: overflow\n");
+ // we are discarding an event, but don't leak memory
+ if ( ev->evPtr )
+ {
+ Z_Free( ev->evPtr );
+ }
+ eventTail++;
+ }
+
+ eventHead++;
+
+ if ( time == 0 )
+ {
+ time = Sys_Milliseconds();
+ }
+
+ ev->evTime = time;
+ ev->evType = type;
+ ev->evValue = value;
+ ev->evValue2 = value2;
+ ev->evPtrLength = ptrLength;
+ ev->evPtr = ptr;
+}
+
+/*
+================
+Sys_GetEvent
+
+================
+*/
+sysEvent_t Sys_GetEvent( void ) {
+ sysEvent_t ev;
+ char *s;
+ msg_t netmsg;
+ netadr_t adr;
+
+ // return if we have data
+ if ( eventHead > eventTail )
+ {
+ eventTail++;
+ return eventQue[ ( eventTail - 1 ) & MASK_QUED_EVENTS ];
+ }
+
+ // pump the message loop
+ // in vga this calls KBD_Update, under X, it calls GetEvent
+ Sys_SendKeyEvents ();
+
+ // check for console commands
+ s = Sys_ConsoleInput();
+ if ( s )
+ {
+ char *b;
+ int len;
+
+ len = strlen( s ) + 1;
+ b = Z_Malloc( len );
+ strcpy( b, s );
+ Sys_QueEvent( 0, SE_CONSOLE, 0, 0, len, b );
+ }
+
+ // check for other input devices
+ IN_Frame();
+
+ // check for network packets
+ MSG_Init( &netmsg, sys_packetReceived, sizeof( sys_packetReceived ) );
+ if ( Sys_GetPacket ( &adr, &netmsg ) )
+ {
+ netadr_t *buf;
+ int len;
+
+ // copy out to a seperate buffer for qeueing
+ len = sizeof( netadr_t ) + netmsg.cursize;
+ buf = Z_Malloc( len );
+ *buf = adr;
+ memcpy( buf+1, netmsg.data, netmsg.cursize );
+ Sys_QueEvent( 0, SE_PACKET, 0, 0, len, buf );
+ }
+
+ // return if we have data
+ if ( eventHead > eventTail )
+ {
+ eventTail++;
+ return eventQue[ ( eventTail - 1 ) & MASK_QUED_EVENTS ];
+ }
+
+ // create an empty event to return
+
+ memset( &ev, 0, sizeof( ev ) );
+ ev.evTime = Sys_Milliseconds();
+
+ return ev;
+}
+
+/*****************************************************************************/
+
+qboolean Sys_CheckCD( void ) {
+ return qtrue;
+}
+
+void Sys_AppActivate (void)
+{
+}
+
+char *Sys_GetClipboardData(void)
+{
+ return NULL;
+}
+
+void Sys_Print( const char *msg )
+{
+ if (ttycon_on)
+ {
+ tty_Hide();
+ }
+ fputs(msg, stderr);
+ if (ttycon_on)
+ {
+ tty_Show();
+ }
+}
+
+
+void Sys_ConfigureFPU() { // bk001213 - divide by zero
+#ifdef __linux__
+#ifdef __i386
+#ifndef NDEBUG
+
+ // bk0101022 - enable FPE's in debug mode
+ static int fpu_word = _FPU_DEFAULT & ~(_FPU_MASK_ZM | _FPU_MASK_IM);
+ int current = 0;
+ _FPU_GETCW(current);
+ if ( current!=fpu_word)
+ {
+#if 0
+ Com_Printf("FPU Control 0x%x (was 0x%x)\n", fpu_word, current );
+ _FPU_SETCW( fpu_word );
+ _FPU_GETCW( current );
+ assert(fpu_word==current);
+#endif
+ }
+#else // NDEBUG
+ static int fpu_word = _FPU_DEFAULT;
+ _FPU_SETCW( fpu_word );
+#endif // NDEBUG
+#endif // __i386
+#endif // __linux
+}
+
+void Sys_PrintBinVersion( const char* name ) {
+ char* date = __DATE__;
+ char* time = __TIME__;
+ char* sep = "==============================================================";
+ fprintf( stdout, "\n\n%s\n", sep );
+#ifdef DEDICATED
+ fprintf( stdout, "Linux Quake3 Dedicated Server [%s %s]\n", date, time );
+#else
+ fprintf( stdout, "Linux Quake3 Full Executable [%s %s]\n", date, time );
+#endif
+ fprintf( stdout, " local install: %s\n", name );
+ fprintf( stdout, "%s\n\n", sep );
+}
+
+void Sys_ParseArgs( int argc, char* argv[] ) {
+
+ if ( argc==2 )
+ {
+ if ( (!strcmp( argv[1], "--version" ))
+ || ( !strcmp( argv[1], "-v" )) )
+ {
+ Sys_PrintBinVersion( argv[0] );
+ Sys_Exit(0);
+ }
+ }
+}
+
+#include "../client/client.h"
+extern clientStatic_t cls;
+
+int main ( int argc, char* argv[] )
+{
+ // int oldtime, newtime; // bk001204 - unused
+ int len, i;
+ char *cmdline;
+ void Sys_SetDefaultCDPath(const char *path);
+
+ // go back to real user for config loads
+ saved_euid = geteuid();
+ seteuid(getuid());
+
+ Sys_ParseArgs( argc, argv ); // bk010104 - added this for support
+
+ Sys_SetDefaultCDPath(argv[0]);
+
+ // merge the command line, this is kinda silly
+ for (len = 1, i = 1; i < argc; i++)
+ len += strlen(argv[i]) + 1;
+ cmdline = malloc(len);
+ *cmdline = 0;
+ for (i = 1; i < argc; i++)
+ {
+ if (i > 1)
+ strcat(cmdline, " ");
+ strcat(cmdline, argv[i]);
+ }
+
+ // bk000306 - clear queues
+ memset( &eventQue[0], 0, MAX_QUED_EVENTS*sizeof(sysEvent_t) );
+ memset( &sys_packetReceived[0], 0, MAX_MSGLEN*sizeof(byte) );
+
+ Com_Init(cmdline);
+ NET_Init();
+
+ Sys_ConsoleInputInit();
+
+ fcntl(0, F_SETFL, fcntl (0, F_GETFL, 0) | FNDELAY);
+
+#ifdef DEDICATED
+ // init here for dedicated, as we don't have GLimp_Init
+ InitSig();
+#endif
+
+ while (1)
+ {
+#ifdef __linux__
+ Sys_ConfigureFPU();
+#endif
+ Com_Frame ();
+ }
+}
diff --git a/code/unix/unix_net.c b/code/unix/unix_net.c
new file mode 100755
index 0000000..299881f
--- /dev/null
+++ b/code/unix/unix_net.c
@@ -0,0 +1,616 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// unix_net.c
+
+#include "../game/q_shared.h"
+#include "../qcommon/qcommon.h"
+
+#include <unistd.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+#include <netinet/in.h>
+#include <netdb.h>
+#include <arpa/inet.h> // bk001204
+
+#include <sys/param.h>
+#include <sys/ioctl.h>
+#include <sys/uio.h>
+#include <errno.h>
+
+#ifdef MACOS_X
+#import <sys/sockio.h>
+#import <net/if.h>
+#import <net/if_types.h>
+
+#import <arpa/inet.h> // for inet_ntoa()
+#import <net/if_dl.h> // for 'struct sockaddr_dl'
+#endif
+
+static cvar_t *noudp;
+
+netadr_t net_local_adr;
+
+int ip_socket;
+int ipx_socket;
+
+#define MAX_IPS 16
+static int numIP;
+static byte localIP[MAX_IPS][4];
+
+int NET_Socket (char *net_interface, int port);
+char *NET_ErrorString (void);
+
+//=============================================================================
+
+void NetadrToSockadr (netadr_t *a, struct sockaddr_in *s)
+{
+ memset (s, 0, sizeof(*s));
+
+ if (a->type == NA_BROADCAST)
+ {
+ s->sin_family = AF_INET;
+
+ s->sin_port = a->port;
+ *(int *)&s->sin_addr = -1;
+ }
+ else if (a->type == NA_IP)
+ {
+ s->sin_family = AF_INET;
+
+ *(int *)&s->sin_addr = *(int *)&a->ip;
+ s->sin_port = a->port;
+ }
+}
+
+void SockadrToNetadr (struct sockaddr_in *s, netadr_t *a)
+{
+ *(int *)&a->ip = *(int *)&s->sin_addr;
+ a->port = s->sin_port;
+ a->type = NA_IP;
+}
+
+char *NET_BaseAdrToString (netadr_t a)
+{
+ static char s[64];
+
+ Com_sprintf (s, sizeof(s), "%i.%i.%i.%i", a.ip[0], a.ip[1], a.ip[2], a.ip[3]);
+
+ return s;
+}
+
+/*
+=============
+Sys_StringToAdr
+
+idnewt
+192.246.40.70
+=============
+*/
+qboolean Sys_StringToSockaddr (const char *s, struct sockaddr *sadr)
+{
+ struct hostent *h;
+ //char *colon; // bk001204 - unused
+
+ memset (sadr, 0, sizeof(*sadr));
+ ((struct sockaddr_in *)sadr)->sin_family = AF_INET;
+
+ ((struct sockaddr_in *)sadr)->sin_port = 0;
+
+ if ( s[0] >= '0' && s[0] <= '9')
+ {
+ *(int *)&((struct sockaddr_in *)sadr)->sin_addr = inet_addr(s);
+ }
+ else
+ {
+ if (! (h = gethostbyname(s)) )
+ return qfalse;
+ *(int *)&((struct sockaddr_in *)sadr)->sin_addr = *(int *)h->h_addr_list[0];
+ }
+
+ return qtrue;
+}
+
+/*
+=============
+Sys_StringToAdr
+
+localhost
+idnewt
+idnewt:28000
+192.246.40.70
+192.246.40.70:28000
+=============
+*/
+qboolean Sys_StringToAdr (const char *s, netadr_t *a)
+{
+ struct sockaddr_in sadr;
+
+ if (!Sys_StringToSockaddr (s, (struct sockaddr *)&sadr))
+ return qfalse;
+
+ SockadrToNetadr (&sadr, a);
+
+ return qtrue;
+}
+
+
+//=============================================================================
+
+qboolean Sys_GetPacket (netadr_t *net_from, msg_t *net_message)
+{
+ int ret;
+ struct sockaddr_in from;
+ int fromlen;
+ int net_socket;
+ int protocol;
+ int err;
+
+ for (protocol = 0 ; protocol < 2 ; protocol++)
+ {
+ if (protocol == 0)
+ net_socket = ip_socket;
+ else
+ net_socket = ipx_socket;
+
+ if (!net_socket)
+ continue;
+
+ fromlen = sizeof(from);
+ ret = recvfrom (net_socket, net_message->data, net_message->maxsize
+ , 0, (struct sockaddr *)&from, &fromlen);
+
+ SockadrToNetadr (&from, net_from);
+ // bk000305: was missing
+ net_message->readcount = 0;
+
+ if (ret == -1)
+ {
+ err = errno;
+
+ if (err == EWOULDBLOCK || err == ECONNREFUSED)
+ continue;
+ Com_Printf ("NET_GetPacket: %s from %s\n", NET_ErrorString(),
+ NET_AdrToString(*net_from));
+ continue;
+ }
+
+ if (ret == net_message->maxsize)
+ {
+ Com_Printf ("Oversize packet from %s\n", NET_AdrToString (*net_from));
+ continue;
+ }
+
+ net_message->cursize = ret;
+ return qtrue;
+ }
+
+ return qfalse;
+}
+
+//=============================================================================
+
+void Sys_SendPacket( int length, const void *data, netadr_t to )
+{
+ int ret;
+ struct sockaddr_in addr;
+ int net_socket;
+
+ if (to.type == NA_BROADCAST)
+ {
+ net_socket = ip_socket;
+ }
+ else if (to.type == NA_IP)
+ {
+ net_socket = ip_socket;
+ }
+ else if (to.type == NA_IPX)
+ {
+ net_socket = ipx_socket;
+ }
+ else if (to.type == NA_BROADCAST_IPX)
+ {
+ net_socket = ipx_socket;
+ }
+ else {
+ Com_Error (ERR_FATAL, "NET_SendPacket: bad address type");
+ return;
+ }
+
+ if (!net_socket)
+ return;
+
+ NetadrToSockadr (&to, &addr);
+
+ ret = sendto (net_socket, data, length, 0, (struct sockaddr *)&addr, sizeof(addr) );
+ if (ret == -1)
+ {
+ Com_Printf ("NET_SendPacket ERROR: %s to %s\n", NET_ErrorString(),
+ NET_AdrToString (to));
+ }
+}
+
+
+//=============================================================================
+
+/*
+==================
+Sys_IsLANAddress
+
+LAN clients will have their rate var ignored
+==================
+*/
+qboolean Sys_IsLANAddress (netadr_t adr) {
+ int i;
+
+ if( adr.type == NA_LOOPBACK ) {
+ return qtrue;
+ }
+
+ if( adr.type == NA_IPX ) {
+ return qtrue;
+ }
+
+ if( adr.type != NA_IP ) {
+ return qfalse;
+ }
+
+ // choose which comparison to use based on the class of the address being tested
+ // any local adresses of a different class than the address being tested will fail based on the first byte
+
+ // Class A
+ if( (adr.ip[0] & 0x80) == 0x00 ) {
+ for ( i = 0 ; i < numIP ; i++ ) {
+ if( adr.ip[0] == localIP[i][0] ) {
+ return qtrue;
+ }
+ }
+ // the RFC1918 class a block will pass the above test
+ return qfalse;
+ }
+
+ // Class B
+ if( (adr.ip[0] & 0xc0) == 0x80 ) {
+ for ( i = 0 ; i < numIP ; i++ ) {
+ if( adr.ip[0] == localIP[i][0] && adr.ip[1] == localIP[i][1] ) {
+ return qtrue;
+ }
+ // also check against the RFC1918 class b blocks
+ if( adr.ip[0] == 172 && localIP[i][0] == 172 && (adr.ip[1] & 0xf0) == 16 && (localIP[i][1] & 0xf0) == 16 ) {
+ return qtrue;
+ }
+ }
+ return qfalse;
+ }
+
+ // Class C
+ for ( i = 0 ; i < numIP ; i++ ) {
+ if( adr.ip[0] == localIP[i][0] && adr.ip[1] == localIP[i][1] && adr.ip[2] == localIP[i][2] ) {
+ return qtrue;
+ }
+ // also check against the RFC1918 class c blocks
+ if( adr.ip[0] == 192 && localIP[i][0] == 192 && adr.ip[1] == 168 && localIP[i][1] == 168 ) {
+ return qtrue;
+ }
+ }
+ return qfalse;
+}
+
+/*
+==================
+Sys_ShowIP
+==================
+*/
+void Sys_ShowIP(void) {
+ int i;
+
+ for (i = 0; i < numIP; i++) {
+ Com_Printf( "IP: %i.%i.%i.%i\n", localIP[i][0], localIP[i][1], localIP[i][2], localIP[i][3] );
+ }
+}
+
+/*
+=====================
+NET_GetLocalAddress
+=====================
+*/
+#ifdef MACOS_X
+// Don't do a forward mapping from the hostname of the machine to the IP. The reason is that we might have obtained an IP address from DHCP and there might not be any name registered for the machine. On Mac OS X, the machine name defaults to 'localhost' and NetInfo has 127.0.0.1 listed for this name. Instead, we want to get a list of all the IP network interfaces on the machine.
+// This code adapted from OmniNetworking.
+
+#define IFR_NEXT(ifr) \
+ ((struct ifreq *) ((char *) (ifr) + sizeof(*(ifr)) + \
+ MAX(0, (int) (ifr)->ifr_addr.sa_len - (int) sizeof((ifr)->ifr_addr))))
+
+void NET_GetLocalAddress( void ) {
+ struct ifreq requestBuffer[MAX_IPS], *linkInterface, *inetInterface;
+ struct ifconf ifc;
+ struct ifreq ifr;
+ struct sockaddr_dl *sdl;
+ int interfaceSocket;
+ int family;
+
+ //Com_Printf("NET_GetLocalAddress: Querying for network interfaces\n");
+
+ // Set this early so we can just return if there is an error
+ numIP = 0;
+
+ ifc.ifc_len = sizeof(requestBuffer);
+ ifc.ifc_buf = (caddr_t)requestBuffer;
+
+ // Since we get at this info via an ioctl, we need a temporary little socket. This will only get AF_INET interfaces, but we probably don't care about anything else. If we do end up caring later, we should add a ONAddressFamily and at a -interfaces method to it.
+ family = AF_INET;
+ if ((interfaceSocket = socket(family, SOCK_DGRAM, 0)) < 0) {
+ Com_Printf("NET_GetLocalAddress: Unable to create temporary socket, errno = %d\n", errno);
+ return;
+ }
+
+ if (ioctl(interfaceSocket, SIOCGIFCONF, &ifc) != 0) {
+ Com_Printf("NET_GetLocalAddress: Unable to get list of network interfaces, errno = %d\n", errno);
+ return;
+ }
+
+
+ linkInterface = (struct ifreq *) ifc.ifc_buf;
+ while ((char *) linkInterface < &ifc.ifc_buf[ifc.ifc_len]) {
+ unsigned int nameLength;
+
+ // The ioctl returns both the entries having the address (AF_INET) and the link layer entries (AF_LINK). The AF_LINK entry has the link layer address which contains the interface type. This is the only way I can see to get this information. We cannot assume that we will get bot an AF_LINK and AF_INET entry since the interface may not be configured. For example, if you have a 10Mb port on the motherboard and a 100Mb card, you may not configure the motherboard port.
+
+ // For each AF_LINK entry...
+ if (linkInterface->ifr_addr.sa_family == AF_LINK) {
+ // if there is a matching AF_INET entry
+ inetInterface = (struct ifreq *) ifc.ifc_buf;
+ while ((char *) inetInterface < &ifc.ifc_buf[ifc.ifc_len]) {
+ if (inetInterface->ifr_addr.sa_family == AF_INET &&
+ !strncmp(inetInterface->ifr_name, linkInterface->ifr_name, sizeof(linkInterface->ifr_name))) {
+
+ for (nameLength = 0; nameLength < IFNAMSIZ; nameLength++)
+ if (!linkInterface->ifr_name[nameLength])
+ break;
+
+ sdl = (struct sockaddr_dl *)&linkInterface->ifr_addr;
+ // Skip loopback interfaces
+ if (sdl->sdl_type != IFT_LOOP) {
+ // Get the local interface address
+ strncpy(ifr.ifr_name, inetInterface->ifr_name, sizeof(ifr.ifr_name));
+ if (ioctl(interfaceSocket, OSIOCGIFADDR, (caddr_t)&ifr) < 0) {
+ Com_Printf("NET_GetLocalAddress: Unable to get local address for interface '%s', errno = %d\n", inetInterface->ifr_name, errno);
+ } else {
+ struct sockaddr_in *sin;
+ int ip;
+
+ sin = (struct sockaddr_in *)&ifr.ifr_addr;
+
+ ip = ntohl(sin->sin_addr.s_addr);
+ localIP[ numIP ][0] = (ip >> 24) & 0xff;
+ localIP[ numIP ][1] = (ip >> 16) & 0xff;
+ localIP[ numIP ][2] = (ip >> 8) & 0xff;
+ localIP[ numIP ][3] = (ip >> 0) & 0xff;
+ Com_Printf( "IP: %i.%i.%i.%i (%s)\n", localIP[ numIP ][0], localIP[ numIP ][1], localIP[ numIP ][2], localIP[ numIP ][3], inetInterface->ifr_name);
+ numIP++;
+ }
+ }
+
+ // We will assume that there is only one AF_INET entry per AF_LINK entry.
+ // What happens when we have an interface that has multiple IP addresses, or
+ // can that even happen?
+ // break;
+ }
+ inetInterface = IFR_NEXT(inetInterface);
+ }
+ }
+ linkInterface = IFR_NEXT(linkInterface);
+ }
+
+ close(interfaceSocket);
+}
+
+#else
+void NET_GetLocalAddress( void ) {
+ char hostname[256];
+ struct hostent *hostInfo;
+ // int error; // bk001204 - unused
+ char *p;
+ int ip;
+ int n;
+
+ if ( gethostname( hostname, 256 ) == -1 ) {
+ return;
+ }
+
+ hostInfo = gethostbyname( hostname );
+ if ( !hostInfo ) {
+ return;
+ }
+
+ Com_Printf( "Hostname: %s\n", hostInfo->h_name );
+ n = 0;
+ while( ( p = hostInfo->h_aliases[n++] ) != NULL ) {
+ Com_Printf( "Alias: %s\n", p );
+ }
+
+ if ( hostInfo->h_addrtype != AF_INET ) {
+ return;
+ }
+
+ numIP = 0;
+ while( ( p = hostInfo->h_addr_list[numIP++] ) != NULL && numIP < MAX_IPS ) {
+ ip = ntohl( *(int *)p );
+ localIP[ numIP ][0] = p[0];
+ localIP[ numIP ][1] = p[1];
+ localIP[ numIP ][2] = p[2];
+ localIP[ numIP ][3] = p[3];
+ Com_Printf( "IP: %i.%i.%i.%i\n", ( ip >> 24 ) & 0xff, ( ip >> 16 ) & 0xff, ( ip >> 8 ) & 0xff, ip & 0xff );
+ }
+}
+#endif
+
+/*
+====================
+NET_OpenIP
+====================
+*/
+// bk001204 - prototype needed
+int NET_IPSocket (char *net_interface, int port);
+void NET_OpenIP (void)
+{
+ cvar_t *ip;
+ int port;
+ int i;
+
+ ip = Cvar_Get ("net_ip", "localhost", 0);
+
+ port = Cvar_Get("net_port", va("%i", PORT_SERVER), 0)->value;
+
+ for ( i = 0 ; i < 10 ; i++ ) {
+ ip_socket = NET_IPSocket (ip->string, port + i);
+ if ( ip_socket ) {
+ Cvar_SetValue( "net_port", port + i );
+ NET_GetLocalAddress();
+ return;
+ }
+ }
+ Com_Error (ERR_FATAL, "Couldn't allocate IP port");
+}
+
+
+/*
+====================
+NET_Init
+====================
+*/
+void NET_Init (void)
+{
+ noudp = Cvar_Get ("net_noudp", "0", 0);
+ // open sockets
+ if (! noudp->value) {
+ NET_OpenIP ();
+ }
+}
+
+
+/*
+====================
+NET_IPSocket
+====================
+*/
+int NET_IPSocket (char *net_interface, int port)
+{
+ int newsocket;
+ struct sockaddr_in address;
+ qboolean _qtrue = qtrue;
+ int i = 1;
+
+ if ( net_interface ) {
+ Com_Printf("Opening IP socket: %s:%i\n", net_interface, port );
+ } else {
+ Com_Printf("Opening IP socket: localhost:%i\n", port );
+ }
+
+ if ((newsocket = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
+ {
+ Com_Printf ("ERROR: UDP_OpenSocket: socket: %s", NET_ErrorString());
+ return 0;
+ }
+
+ // make it non-blocking
+ if (ioctl (newsocket, FIONBIO, &_qtrue) == -1)
+ {
+ Com_Printf ("ERROR: UDP_OpenSocket: ioctl FIONBIO:%s\n", NET_ErrorString());
+ return 0;
+ }
+
+ // make it broadcast capable
+ if (setsockopt(newsocket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i)) == -1)
+ {
+ Com_Printf ("ERROR: UDP_OpenSocket: setsockopt SO_BROADCAST:%s\n", NET_ErrorString());
+ return 0;
+ }
+
+ if (!net_interface || !net_interface[0] || !Q_stricmp(net_interface, "localhost"))
+ address.sin_addr.s_addr = INADDR_ANY;
+ else
+ Sys_StringToSockaddr (net_interface, (struct sockaddr *)&address);
+
+ if (port == PORT_ANY)
+ address.sin_port = 0;
+ else
+ address.sin_port = htons((short)port);
+
+ address.sin_family = AF_INET;
+
+ if( bind (newsocket, (void *)&address, sizeof(address)) == -1)
+ {
+ Com_Printf ("ERROR: UDP_OpenSocket: bind: %s\n", NET_ErrorString());
+ close (newsocket);
+ return 0;
+ }
+
+ return newsocket;
+}
+
+/*
+====================
+NET_Shutdown
+====================
+*/
+void NET_Shutdown (void)
+{
+ if (ip_socket) {
+ close(ip_socket);
+ ip_socket = 0;
+ }
+}
+
+
+/*
+====================
+NET_ErrorString
+====================
+*/
+char *NET_ErrorString (void)
+{
+ int code;
+
+ code = errno;
+ return strerror (code);
+}
+
+// sleeps msec or until net socket is ready
+void NET_Sleep(int msec)
+{
+ struct timeval timeout;
+ fd_set fdset;
+ extern qboolean stdin_active;
+
+ if (!ip_socket || !com_dedicated->integer)
+ return; // we're not a server, just run full speed
+
+ FD_ZERO(&fdset);
+ if (stdin_active)
+ FD_SET(0, &fdset); // stdin is processed too
+ FD_SET(ip_socket, &fdset); // network socket
+ timeout.tv_sec = msec/1000;
+ timeout.tv_usec = (msec%1000)*1000;
+ select(ip_socket+1, &fdset, NULL, NULL, &timeout);
+}
+
diff --git a/code/unix/unix_shared.c b/code/unix/unix_shared.c
new file mode 100755
index 0000000..af67760
--- /dev/null
+++ b/code/unix/unix_shared.c
@@ -0,0 +1,435 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <errno.h>
+#include <stdio.h>
+#include <dirent.h>
+#include <unistd.h>
+#include <sys/mman.h>
+#include <sys/time.h>
+#include <pwd.h>
+
+#include "../game/q_shared.h"
+#include "../qcommon/qcommon.h"
+
+//=============================================================================
+
+// Used to determine CD Path
+static char cdPath[MAX_OSPATH];
+
+// Used to determine local installation path
+static char installPath[MAX_OSPATH];
+
+// Used to determine where to store user-specific files
+static char homePath[MAX_OSPATH];
+
+/*
+================
+Sys_Milliseconds
+================
+*/
+/* base time in seconds, that's our origin
+ timeval:tv_sec is an int:
+ assuming this wraps every 0x7fffffff - ~68 years since the Epoch (1970) - we're safe till 2038
+ using unsigned long data type to work right with Sys_XTimeToSysTime */
+unsigned long sys_timeBase = 0;
+/* current time in ms, using sys_timeBase as origin
+ NOTE: sys_timeBase*1000 + curtime -> ms since the Epoch
+ 0x7fffffff ms - ~24 days
+ although timeval:tv_usec is an int, I'm not sure wether it is actually used as an unsigned int
+ (which would affect the wrap period) */
+int curtime;
+int Sys_Milliseconds (void)
+{
+ struct timeval tp;
+
+ gettimeofday(&tp, NULL);
+
+ if (!sys_timeBase)
+ {
+ sys_timeBase = tp.tv_sec;
+ return tp.tv_usec/1000;
+ }
+
+ curtime = (tp.tv_sec - sys_timeBase)*1000 + tp.tv_usec/1000;
+
+ return curtime;
+}
+
+#if defined(__linux__) && !defined(DEDICATED)
+/*
+================
+Sys_XTimeToSysTime
+sub-frame timing of events returned by X
+X uses the Time typedef - unsigned long
+disable with in_subframe 0
+
+ sys_timeBase*1000 is the number of ms since the Epoch of our origin
+ xtime is in ms and uses the Epoch as origin
+ Time data type is an unsigned long: 0xffffffff ms - ~49 days period
+ I didn't find much info in the XWindow documentation about the wrapping
+ we clamp sys_timeBase*1000 to unsigned long, that gives us the current origin for xtime
+ the computation will still work if xtime wraps (at ~49 days period since the Epoch) after we set sys_timeBase
+
+================
+*/
+extern cvar_t *in_subframe;
+int Sys_XTimeToSysTime (unsigned long xtime)
+{
+ int ret, time, test;
+
+ if (!in_subframe->value)
+ {
+ // if you don't want to do any event times corrections
+ return Sys_Milliseconds();
+ }
+
+ // test the wrap issue
+#if 0
+ // reference values for test: sys_timeBase 0x3dc7b5e9 xtime 0x541ea451 (read these from a test run)
+ // xtime will wrap in 0xabe15bae ms >~ 0x2c0056 s (33 days from Nov 5 2002 -> 8 Dec)
+ // NOTE: date -d '1970-01-01 UTC 1039384002 seconds' +%c
+ // use sys_timeBase 0x3dc7b5e9+0x2c0056 = 0x3df3b63f
+ // after around 5s, xtime would have wrapped around
+ // we get 7132, the formula handles the wrap safely
+ unsigned long xtime_aux,base_aux;
+ int test;
+// Com_Printf("sys_timeBase: %p\n", sys_timeBase);
+// Com_Printf("xtime: %p\n", xtime);
+ xtime_aux = 500; // 500 ms after wrap
+ base_aux = 0x3df3b63f; // the base a few seconds before wrap
+ test = xtime_aux - (unsigned long)(base_aux*1000);
+ Com_Printf("xtime wrap test: %d\n", test);
+#endif
+
+ // some X servers (like suse 8.1's) report weird event times
+ // if the game is loading, resolving DNS, etc. we are also getting old events
+ // so we only deal with subframe corrections that look 'normal'
+ ret = xtime - (unsigned long)(sys_timeBase*1000);
+ time = Sys_Milliseconds();
+ test = time - ret;
+ //printf("delta: %d\n", test);
+ if (test < 0 || test > 30) // in normal conditions I've never seen this go above
+ {
+ return time;
+ }
+
+ return ret;
+}
+#endif
+
+//#if 0 // bk001215 - see snapvector.nasm for replacement
+#if (defined __APPLE__) // rcg010206 - using this for PPC builds...
+long fastftol( float f ) { // bk001213 - from win32/win_shared.c
+ //static int tmp;
+ // __asm fld f
+ //__asm fistp tmp
+ //__asm mov eax, tmp
+ return (long)f;
+}
+
+void Sys_SnapVector( float *v ) { // bk001213 - see win32/win_shared.c
+ // bk001213 - old linux
+ v[0] = rint(v[0]);
+ v[1] = rint(v[1]);
+ v[2] = rint(v[2]);
+}
+#endif
+
+
+void Sys_Mkdir( const char *path )
+{
+ mkdir (path, 0777);
+}
+
+char *strlwr (char *s) {
+ if ( s==NULL ) { // bk001204 - paranoia
+ assert(0);
+ return s;
+ }
+ while (*s) {
+ *s = tolower(*s);
+ s++;
+ }
+ return s; // bk001204 - duh
+}
+
+//============================================
+
+#define MAX_FOUND_FILES 0x1000
+
+// bk001129 - new in 1.26
+void Sys_ListFilteredFiles( const char *basedir, char *subdirs, char *filter, char **list, int *numfiles ) {
+ char search[MAX_OSPATH], newsubdirs[MAX_OSPATH];
+ char filename[MAX_OSPATH];
+ DIR *fdir;
+ struct dirent *d;
+ struct stat st;
+
+ if ( *numfiles >= MAX_FOUND_FILES - 1 ) {
+ return;
+ }
+
+ if (strlen(subdirs)) {
+ Com_sprintf( search, sizeof(search), "%s/%s", basedir, subdirs );
+ }
+ else {
+ Com_sprintf( search, sizeof(search), "%s", basedir );
+ }
+
+ if ((fdir = opendir(search)) == NULL) {
+ return;
+ }
+
+ while ((d = readdir(fdir)) != NULL) {
+ Com_sprintf(filename, sizeof(filename), "%s/%s", search, d->d_name);
+ if (stat(filename, &st) == -1)
+ continue;
+
+ if (st.st_mode & S_IFDIR) {
+ if (Q_stricmp(d->d_name, ".") && Q_stricmp(d->d_name, "..")) {
+ if (strlen(subdirs)) {
+ Com_sprintf( newsubdirs, sizeof(newsubdirs), "%s/%s", subdirs, d->d_name);
+ }
+ else {
+ Com_sprintf( newsubdirs, sizeof(newsubdirs), "%s", d->d_name);
+ }
+ Sys_ListFilteredFiles( basedir, newsubdirs, filter, list, numfiles );
+ }
+ }
+ if ( *numfiles >= MAX_FOUND_FILES - 1 ) {
+ break;
+ }
+ Com_sprintf( filename, sizeof(filename), "%s/%s", subdirs, d->d_name );
+ if (!Com_FilterPath( filter, filename, qfalse ))
+ continue;
+ list[ *numfiles ] = CopyString( filename );
+ (*numfiles)++;
+ }
+
+ closedir(fdir);
+}
+
+// bk001129 - in 1.17 this used to be
+// char **Sys_ListFiles( const char *directory, const char *extension, int *numfiles, qboolean wantsubs )
+char **Sys_ListFiles( const char *directory, const char *extension, char *filter, int *numfiles, qboolean wantsubs )
+{
+ struct dirent *d;
+ // char *p; // bk001204 - unused
+ DIR *fdir;
+ qboolean dironly = wantsubs;
+ char search[MAX_OSPATH];
+ int nfiles;
+ char **listCopy;
+ char *list[MAX_FOUND_FILES];
+ //int flag; // bk001204 - unused
+ int i;
+ struct stat st;
+
+ int extLen;
+
+ if (filter) {
+
+ nfiles = 0;
+ Sys_ListFilteredFiles( directory, "", filter, list, &nfiles );
+
+ list[ nfiles ] = 0;
+ *numfiles = nfiles;
+
+ if (!nfiles)
+ return NULL;
+
+ listCopy = Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ) );
+ for ( i = 0 ; i < nfiles ; i++ ) {
+ listCopy[i] = list[i];
+ }
+ listCopy[i] = NULL;
+
+ return listCopy;
+ }
+
+ if ( !extension)
+ extension = "";
+
+ if ( extension[0] == '/' && extension[1] == 0 ) {
+ extension = "";
+ dironly = qtrue;
+ }
+
+ extLen = strlen( extension );
+
+ // search
+ nfiles = 0;
+
+ if ((fdir = opendir(directory)) == NULL) {
+ *numfiles = 0;
+ return NULL;
+ }
+
+ while ((d = readdir(fdir)) != NULL) {
+ Com_sprintf(search, sizeof(search), "%s/%s", directory, d->d_name);
+ if (stat(search, &st) == -1)
+ continue;
+ if ((dironly && !(st.st_mode & S_IFDIR)) ||
+ (!dironly && (st.st_mode & S_IFDIR)))
+ continue;
+
+ if (*extension) {
+ if ( strlen( d->d_name ) < strlen( extension ) ||
+ Q_stricmp(
+ d->d_name + strlen( d->d_name ) - strlen( extension ),
+ extension ) ) {
+ continue; // didn't match
+ }
+ }
+
+ if ( nfiles == MAX_FOUND_FILES - 1 )
+ break;
+ list[ nfiles ] = CopyString( d->d_name );
+ nfiles++;
+ }
+
+ list[ nfiles ] = 0;
+
+ closedir(fdir);
+
+ // return a copy of the list
+ *numfiles = nfiles;
+
+ if ( !nfiles ) {
+ return NULL;
+ }
+
+ listCopy = Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ) );
+ for ( i = 0 ; i < nfiles ; i++ ) {
+ listCopy[i] = list[i];
+ }
+ listCopy[i] = NULL;
+
+ return listCopy;
+}
+
+void Sys_FreeFileList( char **list ) {
+ int i;
+
+ if ( !list ) {
+ return;
+ }
+
+ for ( i = 0 ; list[i] ; i++ ) {
+ Z_Free( list[i] );
+ }
+
+ Z_Free( list );
+}
+
+char *Sys_Cwd( void )
+{
+ static char cwd[MAX_OSPATH];
+
+ getcwd( cwd, sizeof( cwd ) - 1 );
+ cwd[MAX_OSPATH-1] = 0;
+
+ return cwd;
+}
+
+void Sys_SetDefaultCDPath(const char *path)
+{
+ Q_strncpyz(cdPath, path, sizeof(cdPath));
+}
+
+char *Sys_DefaultCDPath(void)
+{
+ return cdPath;
+}
+
+void Sys_SetDefaultInstallPath(const char *path)
+{
+ Q_strncpyz(installPath, path, sizeof(installPath));
+}
+
+char *Sys_DefaultInstallPath(void)
+{
+ if (*installPath)
+ return installPath;
+ else
+ return Sys_Cwd();
+}
+
+void Sys_SetDefaultHomePath(const char *path)
+{
+ Q_strncpyz(homePath, path, sizeof(homePath));
+}
+
+char *Sys_DefaultHomePath(void)
+{
+ char *p;
+
+ if (*homePath)
+ return homePath;
+
+ if ((p = getenv("HOME")) != NULL) {
+ Q_strncpyz(homePath, p, sizeof(homePath));
+#ifdef MACOS_X
+ Q_strcat(homePath, sizeof(homePath), "/Library/Application Support/Quake3");
+#else
+ Q_strcat(homePath, sizeof(homePath), "/.q3a");
+#endif
+ if (mkdir(homePath, 0777)) {
+ if (errno != EEXIST)
+ Sys_Error("Unable to create directory \"%s\", error is %s(%d)\n", homePath, strerror(errno), errno);
+ }
+ return homePath;
+ }
+ return ""; // assume current dir
+}
+
+//============================================
+
+int Sys_GetProcessorId( void )
+{
+ return CPUID_GENERIC;
+}
+
+void Sys_ShowConsole( int visLevel, qboolean quitOnClose )
+{
+}
+
+char *Sys_GetCurrentUser( void )
+{
+ struct passwd *p;
+
+ if ( (p = getpwuid( getuid() )) == NULL ) {
+ return "player";
+ }
+ return p->pw_name;
+}
+
+#if defined(__linux__)
+// TTimo
+// sysconf() in libc, POSIX.1 compliant
+unsigned int Sys_ProcessorCount()
+{
+ return sysconf(_SC_NPROCESSORS_ONLN);
+}
+#endif
diff --git a/code/unix/vm_x86.c b/code/unix/vm_x86.c
new file mode 100755
index 0000000..de79d36
--- /dev/null
+++ b/code/unix/vm_x86.c
@@ -0,0 +1,29 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "../qcommon/vm_local.h"
+
+void VM_Compile( vm_t *vm, vmHeader_t *header ) {}
+int VM_CallCompiled( vm_t *vm, int *args ) {}
+
+
+
diff --git a/code/unix/vm_x86a.s b/code/unix/vm_x86a.s
new file mode 100755
index 0000000..a85e452
--- /dev/null
+++ b/code/unix/vm_x86a.s
@@ -0,0 +1,462 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// vm_x86a.s
+// linux x86 vm support
+
+#include "qasm.h"
+
+.extern C(instructionPointers)
+
+ .data
+
+ .align 4
+
+programStack .long 0
+opStack .long 0
+syscallNum .long 0
+
+ .text
+
+.globl C(AsmCAll)
+C(AsmCall):
+ movl (%edi),%eax
+ subl 4,%edi
+ orl %eax,%eax
+ jl systemCall
+ // calling another vm function
+ shll 2,%eax
+ addl C(instructionPointers),%eax
+ call (%eax)
+ ret
+systemCall:
+
+ // convert negative num to system call number
+ // and store right before the first arg
+ negl %eax
+ decl %eax
+
+ movl %eax,syscallNum
+///---- UNFINISHED FROM HERE
+ mov dword ptr syscallNum, eax // so C code can get at it
+ mov dword ptr programStack, esi // so C code can get at it
+ mov dword ptr opStack, edi
+
+ push ecx
+ push esi // we may call recursively, so the
+ push edi // statics aren't guaranteed to be around
+}
+ // save the stack to allow recursive VM entry
+ currentVM->programStack = programStack - 4;
+ *(int *)((byte *)currentVM->dataBase + programStack + 4) = syscallNum;
+//VM_LogSyscalls( (int *)((byte *)currentVM->dataBase + programStack + 4) );
+ *(opStack+1) = currentVM->systemCall( (int *)((byte *)currentVM->dataBase + programStack + 4) );
+
+_asm {
+ pop edi
+ pop esi
+ pop ecx
+ add edi, 4 // we added the return value
+
+ ret
+}
+
+}
+
+//--------------------------------------------
+ movl val(%esp),%ecx
+ movl $0x100,%edx // 0x10000000000 as dividend
+ cmpl %edx,%ecx
+ jle LOutOfRange
+
+ subl %eax,%eax
+ divl %ecx
+
+ ret
+
+LOutOfRange:
+ movl $0xFFFFFFFF,%eax
+ ret
+
+#if 0
+
+#define in 4
+#define out 8
+
+ .align 2
+.globl C(TransformVector)
+C(TransformVector):
+ movl in(%esp),%eax
+ movl out(%esp),%edx
+
+ flds (%eax) // in[0]
+ fmuls C(vright) // in[0]*vright[0]
+ flds (%eax) // in[0] | in[0]*vright[0]
+ fmuls C(vup) // in[0]*vup[0] | in[0]*vright[0]
+ flds (%eax) // in[0] | in[0]*vup[0] | in[0]*vright[0]
+ fmuls C(vpn) // in[0]*vpn[0] | in[0]*vup[0] | in[0]*vright[0]
+
+ flds 4(%eax) // in[1] | ...
+ fmuls C(vright)+4 // in[1]*vright[1] | ...
+ flds 4(%eax) // in[1] | in[1]*vright[1] | ...
+ fmuls C(vup)+4 // in[1]*vup[1] | in[1]*vright[1] | ...
+ flds 4(%eax) // in[1] | in[1]*vup[1] | in[1]*vright[1] | ...
+ fmuls C(vpn)+4 // in[1]*vpn[1] | in[1]*vup[1] | in[1]*vright[1] | ...
+ fxch %st(2) // in[1]*vright[1] | in[1]*vup[1] | in[1]*vpn[1] | ...
+
+ faddp %st(0),%st(5) // in[1]*vup[1] | in[1]*vpn[1] | ...
+ faddp %st(0),%st(3) // in[1]*vpn[1] | ...
+ faddp %st(0),%st(1) // vpn_accum | vup_accum | vright_accum
+
+ flds 8(%eax) // in[2] | ...
+ fmuls C(vright)+8 // in[2]*vright[2] | ...
+ flds 8(%eax) // in[2] | in[2]*vright[2] | ...
+ fmuls C(vup)+8 // in[2]*vup[2] | in[2]*vright[2] | ...
+ flds 8(%eax) // in[2] | in[2]*vup[2] | in[2]*vright[2] | ...
+ fmuls C(vpn)+8 // in[2]*vpn[2] | in[2]*vup[2] | in[2]*vright[2] | ...
+ fxch %st(2) // in[2]*vright[2] | in[2]*vup[2] | in[2]*vpn[2] | ...
+
+ faddp %st(0),%st(5) // in[2]*vup[2] | in[2]*vpn[2] | ...
+ faddp %st(0),%st(3) // in[2]*vpn[2] | ...
+ faddp %st(0),%st(1) // vpn_accum | vup_accum | vright_accum
+
+ fstps 8(%edx) // out[2]
+ fstps 4(%edx) // out[1]
+ fstps (%edx) // out[0]
+
+ ret
+
+#endif
+
+#define EMINS 4+4
+#define EMAXS 4+8
+#define P 4+12
+
+ .align 2
+.globl C(BoxOnPlaneSide)
+C(BoxOnPlaneSide):
+ pushl %ebx
+
+ movl P(%esp),%edx
+ movl EMINS(%esp),%ecx
+ xorl %eax,%eax
+ movl EMAXS(%esp),%ebx
+ movb pl_signbits(%edx),%al
+ cmpb $8,%al
+ jge Lerror
+ flds pl_normal(%edx) // p->normal[0]
+ fld %st(0) // p->normal[0] | p->normal[0]
+ jmp Ljmptab(,%eax,4)
+
+
+//dist1= p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2];
+//dist2= p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2];
+Lcase0:
+ fmuls (%ebx) // p->normal[0]*emaxs[0] | p->normal[0]
+ flds pl_normal+4(%edx) // p->normal[1] | p->normal[0]*emaxs[0] |
+ // p->normal[0]
+ fxch %st(2) // p->normal[0] | p->normal[0]*emaxs[0] |
+ // p->normal[1]
+ fmuls (%ecx) // p->normal[0]*emins[0] |
+ // p->normal[0]*emaxs[0] | p->normal[1]
+ fxch %st(2) // p->normal[1] | p->normal[0]*emaxs[0] |
+ // p->normal[0]*emins[0]
+ fld %st(0) // p->normal[1] | p->normal[1] |
+ // p->normal[0]*emaxs[0] |
+ // p->normal[0]*emins[0]
+ fmuls 4(%ebx) // p->normal[1]*emaxs[1] | p->normal[1] |
+ // p->normal[0]*emaxs[0] |
+ // p->normal[0]*emins[0]
+ flds pl_normal+8(%edx) // p->normal[2] | p->normal[1]*emaxs[1] |
+ // p->normal[1] | p->normal[0]*emaxs[0] |
+ // p->normal[0]*emins[0]
+ fxch %st(2) // p->normal[1] | p->normal[1]*emaxs[1] |
+ // p->normal[2] | p->normal[0]*emaxs[0] |
+ // p->normal[0]*emins[0]
+ fmuls 4(%ecx) // p->normal[1]*emins[1] |
+ // p->normal[1]*emaxs[1] |
+ // p->normal[2] | p->normal[0]*emaxs[0] |
+ // p->normal[0]*emins[0]
+ fxch %st(2) // p->normal[2] | p->normal[1]*emaxs[1] |
+ // p->normal[1]*emins[1] |
+ // p->normal[0]*emaxs[0] |
+ // p->normal[0]*emins[0]
+ fld %st(0) // p->normal[2] | p->normal[2] |
+ // p->normal[1]*emaxs[1] |
+ // p->normal[1]*emins[1] |
+ // p->normal[0]*emaxs[0] |
+ // p->normal[0]*emins[0]
+ fmuls 8(%ebx) // p->normal[2]*emaxs[2] |
+ // p->normal[2] |
+ // p->normal[1]*emaxs[1] |
+ // p->normal[1]*emins[1] |
+ // p->normal[0]*emaxs[0] |
+ // p->normal[0]*emins[0]
+ fxch %st(5) // p->normal[0]*emins[0] |
+ // p->normal[2] |
+ // p->normal[1]*emaxs[1] |
+ // p->normal[1]*emins[1] |
+ // p->normal[0]*emaxs[0] |
+ // p->normal[2]*emaxs[2]
+ faddp %st(0),%st(3) //p->normal[2] |
+ // p->normal[1]*emaxs[1] |
+ // p->normal[1]*emins[1]+p->normal[0]*emins[0]|
+ // p->normal[0]*emaxs[0] |
+ // p->normal[2]*emaxs[2]
+ fmuls 8(%ecx) //p->normal[2]*emins[2] |
+ // p->normal[1]*emaxs[1] |
+ // p->normal[1]*emins[1]+p->normal[0]*emins[0]|
+ // p->normal[0]*emaxs[0] |
+ // p->normal[2]*emaxs[2]
+ fxch %st(1) //p->normal[1]*emaxs[1] |
+ // p->normal[2]*emins[2] |
+ // p->normal[1]*emins[1]+p->normal[0]*emins[0]|
+ // p->normal[0]*emaxs[0] |
+ // p->normal[2]*emaxs[2]
+ faddp %st(0),%st(3) //p->normal[2]*emins[2] |
+ // p->normal[1]*emins[1]+p->normal[0]*emins[0]|
+ // p->normal[0]*emaxs[0]+p->normal[1]*emaxs[1]|
+ // p->normal[2]*emaxs[2]
+ fxch %st(3) //p->normal[2]*emaxs[2] +
+ // p->normal[1]*emins[1]+p->normal[0]*emins[0]|
+ // p->normal[0]*emaxs[0]+p->normal[1]*emaxs[1]|
+ // p->normal[2]*emins[2]
+ faddp %st(0),%st(2) //p->normal[1]*emins[1]+p->normal[0]*emins[0]|
+ // dist1 | p->normal[2]*emins[2]
+
+ jmp LSetSides
+
+//dist1= p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2];
+//dist2= p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2];
+Lcase1:
+ fmuls (%ecx) // emins[0]
+ flds pl_normal+4(%edx)
+ fxch %st(2)
+ fmuls (%ebx) // emaxs[0]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 4(%ebx) // emaxs[1]
+ flds pl_normal+8(%edx)
+ fxch %st(2)
+ fmuls 4(%ecx) // emins[1]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 8(%ebx) // emaxs[2]
+ fxch %st(5)
+ faddp %st(0),%st(3)
+ fmuls 8(%ecx) // emins[2]
+ fxch %st(1)
+ faddp %st(0),%st(3)
+ fxch %st(3)
+ faddp %st(0),%st(2)
+
+ jmp LSetSides
+
+//dist1= p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2];
+//dist2= p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2];
+Lcase2:
+ fmuls (%ebx) // emaxs[0]
+ flds pl_normal+4(%edx)
+ fxch %st(2)
+ fmuls (%ecx) // emins[0]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 4(%ecx) // emins[1]
+ flds pl_normal+8(%edx)
+ fxch %st(2)
+ fmuls 4(%ebx) // emaxs[1]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 8(%ebx) // emaxs[2]
+ fxch %st(5)
+ faddp %st(0),%st(3)
+ fmuls 8(%ecx) // emins[2]
+ fxch %st(1)
+ faddp %st(0),%st(3)
+ fxch %st(3)
+ faddp %st(0),%st(2)
+
+ jmp LSetSides
+
+//dist1= p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2];
+//dist2= p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2];
+Lcase3:
+ fmuls (%ecx) // emins[0]
+ flds pl_normal+4(%edx)
+ fxch %st(2)
+ fmuls (%ebx) // emaxs[0]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 4(%ecx) // emins[1]
+ flds pl_normal+8(%edx)
+ fxch %st(2)
+ fmuls 4(%ebx) // emaxs[1]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 8(%ebx) // emaxs[2]
+ fxch %st(5)
+ faddp %st(0),%st(3)
+ fmuls 8(%ecx) // emins[2]
+ fxch %st(1)
+ faddp %st(0),%st(3)
+ fxch %st(3)
+ faddp %st(0),%st(2)
+
+ jmp LSetSides
+
+//dist1= p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2];
+//dist2= p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2];
+Lcase4:
+ fmuls (%ebx) // emaxs[0]
+ flds pl_normal+4(%edx)
+ fxch %st(2)
+ fmuls (%ecx) // emins[0]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 4(%ebx) // emaxs[1]
+ flds pl_normal+8(%edx)
+ fxch %st(2)
+ fmuls 4(%ecx) // emins[1]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 8(%ecx) // emins[2]
+ fxch %st(5)
+ faddp %st(0),%st(3)
+ fmuls 8(%ebx) // emaxs[2]
+ fxch %st(1)
+ faddp %st(0),%st(3)
+ fxch %st(3)
+ faddp %st(0),%st(2)
+
+ jmp LSetSides
+
+//dist1= p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2];
+//dist2= p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2];
+Lcase5:
+ fmuls (%ecx) // emins[0]
+ flds pl_normal+4(%edx)
+ fxch %st(2)
+ fmuls (%ebx) // emaxs[0]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 4(%ebx) // emaxs[1]
+ flds pl_normal+8(%edx)
+ fxch %st(2)
+ fmuls 4(%ecx) // emins[1]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 8(%ecx) // emins[2]
+ fxch %st(5)
+ faddp %st(0),%st(3)
+ fmuls 8(%ebx) // emaxs[2]
+ fxch %st(1)
+ faddp %st(0),%st(3)
+ fxch %st(3)
+ faddp %st(0),%st(2)
+
+ jmp LSetSides
+
+//dist1= p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2];
+//dist2= p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2];
+Lcase6:
+ fmuls (%ebx) // emaxs[0]
+ flds pl_normal+4(%edx)
+ fxch %st(2)
+ fmuls (%ecx) // emins[0]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 4(%ecx) // emins[1]
+ flds pl_normal+8(%edx)
+ fxch %st(2)
+ fmuls 4(%ebx) // emaxs[1]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 8(%ecx) // emins[2]
+ fxch %st(5)
+ faddp %st(0),%st(3)
+ fmuls 8(%ebx) // emaxs[2]
+ fxch %st(1)
+ faddp %st(0),%st(3)
+ fxch %st(3)
+ faddp %st(0),%st(2)
+
+ jmp LSetSides
+
+//dist1= p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2];
+//dist2= p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2];
+Lcase7:
+ fmuls (%ecx) // emins[0]
+ flds pl_normal+4(%edx)
+ fxch %st(2)
+ fmuls (%ebx) // emaxs[0]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 4(%ecx) // emins[1]
+ flds pl_normal+8(%edx)
+ fxch %st(2)
+ fmuls 4(%ebx) // emaxs[1]
+ fxch %st(2)
+ fld %st(0)
+ fmuls 8(%ecx) // emins[2]
+ fxch %st(5)
+ faddp %st(0),%st(3)
+ fmuls 8(%ebx) // emaxs[2]
+ fxch %st(1)
+ faddp %st(0),%st(3)
+ fxch %st(3)
+ faddp %st(0),%st(2)
+
+LSetSides:
+
+// sides = 0;
+// if (dist1 >= p->dist)
+// sides = 1;
+// if (dist2 < p->dist)
+// sides |= 2;
+
+ faddp %st(0),%st(2) // dist1 | dist2
+ fcomps pl_dist(%edx)
+ xorl %ecx,%ecx
+ fnstsw %ax
+ fcomps pl_dist(%edx)
+ andb $1,%ah
+ xorb $1,%ah
+ addb %ah,%cl
+
+ fnstsw %ax
+ andb $1,%ah
+ addb %ah,%ah
+ addb %ah,%cl
+
+// return sides;
+
+ popl %ebx
+ movl %ecx,%eax // return status
+
+ ret
+
+
+Lerror:
+ movl 1, %eax
+ ret
+
+#endif // id386
diff --git a/code/win32/background.bmp b/code/win32/background.bmp
new file mode 100755
index 0000000..88b3dab
--- /dev/null
+++ b/code/win32/background.bmp
Binary files differ
diff --git a/code/win32/clear.bmp b/code/win32/clear.bmp
new file mode 100755
index 0000000..1451638
--- /dev/null
+++ b/code/win32/clear.bmp
Binary files differ
diff --git a/code/win32/glw_win.h b/code/win32/glw_win.h
new file mode 100755
index 0000000..9367650
--- /dev/null
+++ b/code/win32/glw_win.h
@@ -0,0 +1,51 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef _WIN32
+# error You should not be including this file on this platform
+#endif
+
+#ifndef __GLW_WIN_H__
+#define __GLW_WIN_H__
+
+typedef struct
+{
+ WNDPROC wndproc;
+
+ HDC hDC; // handle to device context
+ HGLRC hGLRC; // handle to GL rendering context
+
+ HINSTANCE hinstOpenGL; // HINSTANCE for the OpenGL library
+
+ qboolean allowdisplaydepthchange;
+ qboolean pixelFormatSet;
+
+ int desktopBitsPixel;
+ int desktopWidth, desktopHeight;
+
+ qboolean cdsFullscreen;
+
+ FILE *log_fp;
+} glwstate_t;
+
+extern glwstate_t glw_state;
+
+#endif
diff --git a/code/win32/icon2.ico b/code/win32/icon2.ico
new file mode 100755
index 0000000..8ba9328
--- /dev/null
+++ b/code/win32/icon2.ico
Binary files differ
diff --git a/code/win32/mod-sdk-setup/GameSource.VCT b/code/win32/mod-sdk-setup/GameSource.VCT
new file mode 100755
index 0000000..b9dda61
--- /dev/null
+++ b/code/win32/mod-sdk-setup/GameSource.VCT
Binary files differ
diff --git a/code/win32/mod-sdk-setup/QIIIA Game Source License.doc b/code/win32/mod-sdk-setup/QIIIA Game Source License.doc
new file mode 100755
index 0000000..790e7fe
--- /dev/null
+++ b/code/win32/mod-sdk-setup/QIIIA Game Source License.doc
Binary files differ
diff --git a/code/win32/mod-sdk-setup/bin/lcc.exe b/code/win32/mod-sdk-setup/bin/lcc.exe
new file mode 100755
index 0000000..ff0b286
--- /dev/null
+++ b/code/win32/mod-sdk-setup/bin/lcc.exe
Binary files differ
diff --git a/code/win32/mod-sdk-setup/bin/q3asm.exe b/code/win32/mod-sdk-setup/bin/q3asm.exe
new file mode 100755
index 0000000..ba9fd3d
--- /dev/null
+++ b/code/win32/mod-sdk-setup/bin/q3asm.exe
Binary files differ
diff --git a/code/win32/mod-sdk-setup/bin/q3cpp.exe b/code/win32/mod-sdk-setup/bin/q3cpp.exe
new file mode 100755
index 0000000..55e68a1
--- /dev/null
+++ b/code/win32/mod-sdk-setup/bin/q3cpp.exe
Binary files differ
diff --git a/code/win32/mod-sdk-setup/bin/q3rcc.exe b/code/win32/mod-sdk-setup/bin/q3rcc.exe
new file mode 100755
index 0000000..8f09cab
--- /dev/null
+++ b/code/win32/mod-sdk-setup/bin/q3rcc.exe
Binary files differ
diff --git a/code/win32/qe3.ico b/code/win32/qe3.ico
new file mode 100755
index 0000000..a7f4f0a
--- /dev/null
+++ b/code/win32/qe3.ico
Binary files differ
diff --git a/code/win32/resource.h b/code/win32/resource.h
new file mode 100755
index 0000000..65260b9
--- /dev/null
+++ b/code/win32/resource.h
@@ -0,0 +1,44 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//{{NO_DEPENDENCIES}}
+// Microsoft Developer Studio generated include file.
+// Used by winquake.rc
+//
+#define IDS_STRING1 1
+#define IDI_ICON1 1
+#define IDB_BITMAP1 1
+#define IDB_BITMAP2 128
+#define IDC_CURSOR1 129
+#define IDC_CURSOR2 130
+#define IDC_CURSOR3 131
+
+// Next default values for new objects
+//
+#ifdef APSTUDIO_INVOKED
+#ifndef APSTUDIO_READONLY_SYMBOLS
+#define _APS_NO_MFC 1
+#define _APS_NEXT_RESOURCE_VALUE 132
+#define _APS_NEXT_COMMAND_VALUE 40001
+#define _APS_NEXT_CONTROL_VALUE 1005
+#define _APS_NEXT_SYMED_VALUE 101
+#endif
+#endif
diff --git a/code/win32/win_gamma.c b/code/win32/win_gamma.c
new file mode 100755
index 0000000..9b51209
--- /dev/null
+++ b/code/win32/win_gamma.c
@@ -0,0 +1,214 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+/*
+** WIN_GAMMA.C
+*/
+#include <assert.h>
+#include "../renderer/tr_local.h"
+#include "../qcommon/qcommon.h"
+#include "glw_win.h"
+#include "win_local.h"
+
+static unsigned short s_oldHardwareGamma[3][256];
+
+/*
+** WG_CheckHardwareGamma
+**
+** Determines if the underlying hardware supports the Win32 gamma correction API.
+*/
+void WG_CheckHardwareGamma( void )
+{
+ HDC hDC;
+
+ glConfig.deviceSupportsGamma = qfalse;
+
+ if ( qwglSetDeviceGammaRamp3DFX )
+ {
+ glConfig.deviceSupportsGamma = qtrue;
+
+ hDC = GetDC( GetDesktopWindow() );
+ glConfig.deviceSupportsGamma = qwglGetDeviceGammaRamp3DFX( hDC, s_oldHardwareGamma );
+ ReleaseDC( GetDesktopWindow(), hDC );
+
+ return;
+ }
+
+ // non-3Dfx standalone drivers don't support gamma changes, period
+ if ( glConfig.driverType == GLDRV_STANDALONE )
+ {
+ return;
+ }
+
+ if ( !r_ignorehwgamma->integer )
+ {
+ hDC = GetDC( GetDesktopWindow() );
+ glConfig.deviceSupportsGamma = GetDeviceGammaRamp( hDC, s_oldHardwareGamma );
+ ReleaseDC( GetDesktopWindow(), hDC );
+
+ if ( glConfig.deviceSupportsGamma )
+ {
+ //
+ // do a sanity check on the gamma values
+ //
+ if ( ( HIBYTE( s_oldHardwareGamma[0][255] ) <= HIBYTE( s_oldHardwareGamma[0][0] ) ) ||
+ ( HIBYTE( s_oldHardwareGamma[1][255] ) <= HIBYTE( s_oldHardwareGamma[1][0] ) ) ||
+ ( HIBYTE( s_oldHardwareGamma[2][255] ) <= HIBYTE( s_oldHardwareGamma[2][0] ) ) )
+ {
+ glConfig.deviceSupportsGamma = qfalse;
+ ri.Printf( PRINT_WARNING, "WARNING: device has broken gamma support, generated gamma.dat\n" );
+ }
+
+ //
+ // make sure that we didn't have a prior crash in the game, and if so we need to
+ // restore the gamma values to at least a linear value
+ //
+ if ( ( HIBYTE( s_oldHardwareGamma[0][181] ) == 255 ) )
+ {
+ int g;
+
+ ri.Printf( PRINT_WARNING, "WARNING: suspicious gamma tables, using linear ramp for restoration\n" );
+
+ for ( g = 0; g < 255; g++ )
+ {
+ s_oldHardwareGamma[0][g] = g << 8;
+ s_oldHardwareGamma[1][g] = g << 8;
+ s_oldHardwareGamma[2][g] = g << 8;
+ }
+ }
+ }
+ }
+}
+
+/*
+void mapGammaMax( void ) {
+ int i, j;
+ unsigned short table[3][256];
+
+ // try to figure out what win2k will let us get away with setting
+ for ( i = 0 ; i < 256 ; i++ ) {
+ if ( i >= 128 ) {
+ table[0][i] = table[1][i] = table[2][i] = 0xffff;
+ } else {
+ table[0][i] = table[1][i] = table[2][i] = i<<9;
+ }
+ }
+
+ for ( i = 0 ; i < 128 ; i++ ) {
+ for ( j = i*2 ; j < 255 ; j++ ) {
+ table[0][i] = table[1][i] = table[2][i] = j<<8;
+ if ( !SetDeviceGammaRamp( glw_state.hDC, table ) ) {
+ break;
+ }
+ }
+ table[0][i] = table[1][i] = table[2][i] = i<<9;
+ Com_Printf( "index %i max: %i\n", i, j-1 );
+ }
+}
+*/
+
+/*
+** GLimp_SetGamma
+**
+** This routine should only be called if glConfig.deviceSupportsGamma is TRUE
+*/
+void GLimp_SetGamma( unsigned char red[256], unsigned char green[256], unsigned char blue[256] ) {
+ unsigned short table[3][256];
+ int i, j;
+ int ret;
+ OSVERSIONINFO vinfo;
+
+ if ( !glConfig.deviceSupportsGamma || r_ignorehwgamma->integer || !glw_state.hDC ) {
+ return;
+ }
+
+//mapGammaMax();
+
+ for ( i = 0; i < 256; i++ ) {
+ table[0][i] = ( ( ( unsigned short ) red[i] ) << 8 ) | red[i];
+ table[1][i] = ( ( ( unsigned short ) green[i] ) << 8 ) | green[i];
+ table[2][i] = ( ( ( unsigned short ) blue[i] ) << 8 ) | blue[i];
+ }
+
+ // Win2K puts this odd restriction on gamma ramps...
+ vinfo.dwOSVersionInfoSize = sizeof(vinfo);
+ GetVersionEx( &vinfo );
+ if ( vinfo.dwMajorVersion == 5 && vinfo.dwPlatformId == VER_PLATFORM_WIN32_NT ) {
+ Com_DPrintf( "performing W2K gamma clamp.\n" );
+ for ( j = 0 ; j < 3 ; j++ ) {
+ for ( i = 0 ; i < 128 ; i++ ) {
+ if ( table[j][i] > ( (128+i) << 8 ) ) {
+ table[j][i] = (128+i) << 8;
+ }
+ }
+ if ( table[j][127] > 254<<8 ) {
+ table[j][127] = 254<<8;
+ }
+ }
+ } else {
+ Com_DPrintf( "skipping W2K gamma clamp.\n" );
+ }
+
+ // enforce constantly increasing
+ for ( j = 0 ; j < 3 ; j++ ) {
+ for ( i = 1 ; i < 256 ; i++ ) {
+ if ( table[j][i] < table[j][i-1] ) {
+ table[j][i] = table[j][i-1];
+ }
+ }
+ }
+
+
+ if ( qwglSetDeviceGammaRamp3DFX )
+ {
+ qwglSetDeviceGammaRamp3DFX( glw_state.hDC, table );
+ }
+ else
+ {
+ ret = SetDeviceGammaRamp( glw_state.hDC, table );
+ if ( !ret ) {
+ Com_Printf( "SetDeviceGammaRamp failed.\n" );
+ }
+ }
+}
+
+/*
+** WG_RestoreGamma
+*/
+void WG_RestoreGamma( void )
+{
+ if ( glConfig.deviceSupportsGamma )
+ {
+ if ( qwglSetDeviceGammaRamp3DFX )
+ {
+ qwglSetDeviceGammaRamp3DFX( glw_state.hDC, s_oldHardwareGamma );
+ }
+ else
+ {
+ HDC hDC;
+
+ hDC = GetDC( GetDesktopWindow() );
+ SetDeviceGammaRamp( hDC, s_oldHardwareGamma );
+ ReleaseDC( GetDesktopWindow(), hDC );
+ }
+ }
+}
+
diff --git a/code/win32/win_glimp.c b/code/win32/win_glimp.c
new file mode 100755
index 0000000..88fe180
--- /dev/null
+++ b/code/win32/win_glimp.c
@@ -0,0 +1,1658 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+/*
+** WIN_GLIMP.C
+**
+** This file contains ALL Win32 specific stuff having to do with the
+** OpenGL refresh. When a port is being made the following functions
+** must be implemented by the port:
+**
+** GLimp_EndFrame
+** GLimp_Init
+** GLimp_LogComment
+** GLimp_Shutdown
+**
+** Note that the GLW_xxx functions are Windows specific GL-subsystem
+** related functions that are relevant ONLY to win_glimp.c
+*/
+#include <assert.h>
+#include "../renderer/tr_local.h"
+#include "../qcommon/qcommon.h"
+#include "resource.h"
+#include "glw_win.h"
+#include "win_local.h"
+
+extern void WG_CheckHardwareGamma( void );
+extern void WG_RestoreGamma( void );
+
+typedef enum {
+ RSERR_OK,
+
+ RSERR_INVALID_FULLSCREEN,
+ RSERR_INVALID_MODE,
+
+ RSERR_UNKNOWN
+} rserr_t;
+
+#define TRY_PFD_SUCCESS 0
+#define TRY_PFD_FAIL_SOFT 1
+#define TRY_PFD_FAIL_HARD 2
+
+#define WINDOW_CLASS_NAME "Quake 3: Arena"
+
+static void GLW_InitExtensions( void );
+static rserr_t GLW_SetMode( const char *drivername,
+ int mode,
+ int colorbits,
+ qboolean cdsFullscreen );
+
+static qboolean s_classRegistered = qfalse;
+
+//
+// function declaration
+//
+void QGL_EnableLogging( qboolean enable );
+qboolean QGL_Init( const char *dllname );
+void QGL_Shutdown( void );
+
+//
+// variable declarations
+//
+glwstate_t glw_state;
+
+cvar_t *r_allowSoftwareGL; // don't abort out if the pixelformat claims software
+cvar_t *r_maskMinidriver; // allow a different dll name to be treated as if it were opengl32.dll
+
+
+
+/*
+** GLW_StartDriverAndSetMode
+*/
+static qboolean GLW_StartDriverAndSetMode( const char *drivername,
+ int mode,
+ int colorbits,
+ qboolean cdsFullscreen )
+{
+ rserr_t err;
+
+ err = GLW_SetMode( drivername, r_mode->integer, colorbits, cdsFullscreen );
+
+ switch ( err )
+ {
+ case RSERR_INVALID_FULLSCREEN:
+ ri.Printf( PRINT_ALL, "...WARNING: fullscreen unavailable in this mode\n" );
+ return qfalse;
+ case RSERR_INVALID_MODE:
+ ri.Printf( PRINT_ALL, "...WARNING: could not set the given mode (%d)\n", mode );
+ return qfalse;
+ default:
+ break;
+ }
+ return qtrue;
+}
+
+/*
+** ChoosePFD
+**
+** Helper function that replaces ChoosePixelFormat.
+*/
+#define MAX_PFDS 256
+
+static int GLW_ChoosePFD( HDC hDC, PIXELFORMATDESCRIPTOR *pPFD )
+{
+ PIXELFORMATDESCRIPTOR pfds[MAX_PFDS+1];
+ int maxPFD = 0;
+ int i;
+ int bestMatch = 0;
+
+ ri.Printf( PRINT_ALL, "...GLW_ChoosePFD( %d, %d, %d )\n", ( int ) pPFD->cColorBits, ( int ) pPFD->cDepthBits, ( int ) pPFD->cStencilBits );
+
+ // count number of PFDs
+ if ( glConfig.driverType > GLDRV_ICD )
+ {
+ maxPFD = qwglDescribePixelFormat( hDC, 1, sizeof( PIXELFORMATDESCRIPTOR ), &pfds[0] );
+ }
+ else
+ {
+ maxPFD = DescribePixelFormat( hDC, 1, sizeof( PIXELFORMATDESCRIPTOR ), &pfds[0] );
+ }
+ if ( maxPFD > MAX_PFDS )
+ {
+ ri.Printf( PRINT_WARNING, "...numPFDs > MAX_PFDS (%d > %d)\n", maxPFD, MAX_PFDS );
+ maxPFD = MAX_PFDS;
+ }
+
+ ri.Printf( PRINT_ALL, "...%d PFDs found\n", maxPFD - 1 );
+
+ // grab information
+ for ( i = 1; i <= maxPFD; i++ )
+ {
+ if ( glConfig.driverType > GLDRV_ICD )
+ {
+ qwglDescribePixelFormat( hDC, i, sizeof( PIXELFORMATDESCRIPTOR ), &pfds[i] );
+ }
+ else
+ {
+ DescribePixelFormat( hDC, i, sizeof( PIXELFORMATDESCRIPTOR ), &pfds[i] );
+ }
+ }
+
+ // look for a best match
+ for ( i = 1; i <= maxPFD; i++ )
+ {
+ //
+ // make sure this has hardware acceleration
+ //
+ if ( ( pfds[i].dwFlags & PFD_GENERIC_FORMAT ) != 0 )
+ {
+ if ( !r_allowSoftwareGL->integer )
+ {
+ if ( r_verbose->integer )
+ {
+ ri.Printf( PRINT_ALL, "...PFD %d rejected, software acceleration\n", i );
+ }
+ continue;
+ }
+ }
+
+ // verify pixel type
+ if ( pfds[i].iPixelType != PFD_TYPE_RGBA )
+ {
+ if ( r_verbose->integer )
+ {
+ ri.Printf( PRINT_ALL, "...PFD %d rejected, not RGBA\n", i );
+ }
+ continue;
+ }
+
+ // verify proper flags
+ if ( ( ( pfds[i].dwFlags & pPFD->dwFlags ) & pPFD->dwFlags ) != pPFD->dwFlags )
+ {
+ if ( r_verbose->integer )
+ {
+ ri.Printf( PRINT_ALL, "...PFD %d rejected, improper flags (%x instead of %x)\n", i, pfds[i].dwFlags, pPFD->dwFlags );
+ }
+ continue;
+ }
+
+ // verify enough bits
+ if ( pfds[i].cDepthBits < 15 )
+ {
+ continue;
+ }
+ if ( ( pfds[i].cStencilBits < 4 ) && ( pPFD->cStencilBits > 0 ) )
+ {
+ continue;
+ }
+
+ //
+ // selection criteria (in order of priority):
+ //
+ // PFD_STEREO
+ // colorBits
+ // depthBits
+ // stencilBits
+ //
+ if ( bestMatch )
+ {
+ // check stereo
+ if ( ( pfds[i].dwFlags & PFD_STEREO ) && ( !( pfds[bestMatch].dwFlags & PFD_STEREO ) ) && ( pPFD->dwFlags & PFD_STEREO ) )
+ {
+ bestMatch = i;
+ continue;
+ }
+
+ if ( !( pfds[i].dwFlags & PFD_STEREO ) && ( pfds[bestMatch].dwFlags & PFD_STEREO ) && ( pPFD->dwFlags & PFD_STEREO ) )
+ {
+ bestMatch = i;
+ continue;
+ }
+
+ // check color
+ if ( pfds[bestMatch].cColorBits != pPFD->cColorBits )
+ {
+ // prefer perfect match
+ if ( pfds[i].cColorBits == pPFD->cColorBits )
+ {
+ bestMatch = i;
+ continue;
+ }
+ // otherwise if this PFD has more bits than our best, use it
+ else if ( pfds[i].cColorBits > pfds[bestMatch].cColorBits )
+ {
+ bestMatch = i;
+ continue;
+ }
+ }
+
+ // check depth
+ if ( pfds[bestMatch].cDepthBits != pPFD->cDepthBits )
+ {
+ // prefer perfect match
+ if ( pfds[i].cDepthBits == pPFD->cDepthBits )
+ {
+ bestMatch = i;
+ continue;
+ }
+ // otherwise if this PFD has more bits than our best, use it
+ else if ( pfds[i].cDepthBits > pfds[bestMatch].cDepthBits )
+ {
+ bestMatch = i;
+ continue;
+ }
+ }
+
+ // check stencil
+ if ( pfds[bestMatch].cStencilBits != pPFD->cStencilBits )
+ {
+ // prefer perfect match
+ if ( pfds[i].cStencilBits == pPFD->cStencilBits )
+ {
+ bestMatch = i;
+ continue;
+ }
+ // otherwise if this PFD has more bits than our best, use it
+ else if ( ( pfds[i].cStencilBits > pfds[bestMatch].cStencilBits ) &&
+ ( pPFD->cStencilBits > 0 ) )
+ {
+ bestMatch = i;
+ continue;
+ }
+ }
+ }
+ else
+ {
+ bestMatch = i;
+ }
+ }
+
+ if ( !bestMatch )
+ return 0;
+
+ if ( ( pfds[bestMatch].dwFlags & PFD_GENERIC_FORMAT ) != 0 )
+ {
+ if ( !r_allowSoftwareGL->integer )
+ {
+ ri.Printf( PRINT_ALL, "...no hardware acceleration found\n" );
+ return 0;
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "...using software emulation\n" );
+ }
+ }
+ else if ( pfds[bestMatch].dwFlags & PFD_GENERIC_ACCELERATED )
+ {
+ ri.Printf( PRINT_ALL, "...MCD acceleration found\n" );
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "...hardware acceleration found\n" );
+ }
+
+ *pPFD = pfds[bestMatch];
+
+ return bestMatch;
+}
+
+/*
+** void GLW_CreatePFD
+**
+** Helper function zeros out then fills in a PFD
+*/
+static void GLW_CreatePFD( PIXELFORMATDESCRIPTOR *pPFD, int colorbits, int depthbits, int stencilbits, qboolean stereo )
+{
+ PIXELFORMATDESCRIPTOR src =
+ {
+ sizeof(PIXELFORMATDESCRIPTOR), // size of this pfd
+ 1, // version number
+ PFD_DRAW_TO_WINDOW | // support window
+ PFD_SUPPORT_OPENGL | // support OpenGL
+ PFD_DOUBLEBUFFER, // double buffered
+ PFD_TYPE_RGBA, // RGBA type
+ 24, // 24-bit color depth
+ 0, 0, 0, 0, 0, 0, // color bits ignored
+ 0, // no alpha buffer
+ 0, // shift bit ignored
+ 0, // no accumulation buffer
+ 0, 0, 0, 0, // accum bits ignored
+ 24, // 24-bit z-buffer
+ 8, // 8-bit stencil buffer
+ 0, // no auxiliary buffer
+ PFD_MAIN_PLANE, // main layer
+ 0, // reserved
+ 0, 0, 0 // layer masks ignored
+ };
+
+ src.cColorBits = colorbits;
+ src.cDepthBits = depthbits;
+ src.cStencilBits = stencilbits;
+
+ if ( stereo )
+ {
+ ri.Printf( PRINT_ALL, "...attempting to use stereo\n" );
+ src.dwFlags |= PFD_STEREO;
+ glConfig.stereoEnabled = qtrue;
+ }
+ else
+ {
+ glConfig.stereoEnabled = qfalse;
+ }
+
+ *pPFD = src;
+}
+
+/*
+** GLW_MakeContext
+*/
+static int GLW_MakeContext( PIXELFORMATDESCRIPTOR *pPFD )
+{
+ int pixelformat;
+
+ //
+ // don't putz around with pixelformat if it's already set (e.g. this is a soft
+ // reset of the graphics system)
+ //
+ if ( !glw_state.pixelFormatSet )
+ {
+ //
+ // choose, set, and describe our desired pixel format. If we're
+ // using a minidriver then we need to bypass the GDI functions,
+ // otherwise use the GDI functions.
+ //
+ if ( ( pixelformat = GLW_ChoosePFD( glw_state.hDC, pPFD ) ) == 0 )
+ {
+ ri.Printf( PRINT_ALL, "...GLW_ChoosePFD failed\n");
+ return TRY_PFD_FAIL_SOFT;
+ }
+ ri.Printf( PRINT_ALL, "...PIXELFORMAT %d selected\n", pixelformat );
+
+ if ( glConfig.driverType > GLDRV_ICD )
+ {
+ qwglDescribePixelFormat( glw_state.hDC, pixelformat, sizeof( *pPFD ), pPFD );
+ if ( qwglSetPixelFormat( glw_state.hDC, pixelformat, pPFD ) == FALSE )
+ {
+ ri.Printf ( PRINT_ALL, "...qwglSetPixelFormat failed\n");
+ return TRY_PFD_FAIL_SOFT;
+ }
+ }
+ else
+ {
+ DescribePixelFormat( glw_state.hDC, pixelformat, sizeof( *pPFD ), pPFD );
+
+ if ( SetPixelFormat( glw_state.hDC, pixelformat, pPFD ) == FALSE )
+ {
+ ri.Printf (PRINT_ALL, "...SetPixelFormat failed\n", glw_state.hDC );
+ return TRY_PFD_FAIL_SOFT;
+ }
+ }
+
+ glw_state.pixelFormatSet = qtrue;
+ }
+
+ //
+ // startup the OpenGL subsystem by creating a context and making it current
+ //
+ if ( !glw_state.hGLRC )
+ {
+ ri.Printf( PRINT_ALL, "...creating GL context: " );
+ if ( ( glw_state.hGLRC = qwglCreateContext( glw_state.hDC ) ) == 0 )
+ {
+ ri.Printf (PRINT_ALL, "failed\n");
+
+ return TRY_PFD_FAIL_HARD;
+ }
+ ri.Printf( PRINT_ALL, "succeeded\n" );
+
+ ri.Printf( PRINT_ALL, "...making context current: " );
+ if ( !qwglMakeCurrent( glw_state.hDC, glw_state.hGLRC ) )
+ {
+ qwglDeleteContext( glw_state.hGLRC );
+ glw_state.hGLRC = NULL;
+ ri.Printf (PRINT_ALL, "failed\n");
+ return TRY_PFD_FAIL_HARD;
+ }
+ ri.Printf( PRINT_ALL, "succeeded\n" );
+ }
+
+ return TRY_PFD_SUCCESS;
+}
+
+
+/*
+** GLW_InitDriver
+**
+** - get a DC if one doesn't exist
+** - create an HGLRC if one doesn't exist
+*/
+static qboolean GLW_InitDriver( const char *drivername, int colorbits )
+{
+ int tpfd;
+ int depthbits, stencilbits;
+ static PIXELFORMATDESCRIPTOR pfd; // save between frames since 'tr' gets cleared
+
+ ri.Printf( PRINT_ALL, "Initializing OpenGL driver\n" );
+
+ //
+ // get a DC for our window if we don't already have one allocated
+ //
+ if ( glw_state.hDC == NULL )
+ {
+ ri.Printf( PRINT_ALL, "...getting DC: " );
+
+ if ( ( glw_state.hDC = GetDC( g_wv.hWnd ) ) == NULL )
+ {
+ ri.Printf( PRINT_ALL, "failed\n" );
+ return qfalse;
+ }
+ ri.Printf( PRINT_ALL, "succeeded\n" );
+ }
+
+ if ( colorbits == 0 )
+ {
+ colorbits = glw_state.desktopBitsPixel;
+ }
+
+ //
+ // implicitly assume Z-buffer depth == desktop color depth
+ //
+ if ( r_depthbits->integer == 0 ) {
+ if ( colorbits > 16 ) {
+ depthbits = 24;
+ } else {
+ depthbits = 16;
+ }
+ } else {
+ depthbits = r_depthbits->integer;
+ }
+
+ //
+ // do not allow stencil if Z-buffer depth likely won't contain it
+ //
+ stencilbits = r_stencilbits->integer;
+ if ( depthbits < 24 )
+ {
+ stencilbits = 0;
+ }
+
+ //
+ // make two attempts to set the PIXELFORMAT
+ //
+
+ //
+ // first attempt: r_colorbits, depthbits, and r_stencilbits
+ //
+ if ( !glw_state.pixelFormatSet )
+ {
+ GLW_CreatePFD( &pfd, colorbits, depthbits, stencilbits, r_stereo->integer );
+ if ( ( tpfd = GLW_MakeContext( &pfd ) ) != TRY_PFD_SUCCESS )
+ {
+ if ( tpfd == TRY_PFD_FAIL_HARD )
+ {
+ ri.Printf( PRINT_WARNING, "...failed hard\n" );
+ return qfalse;
+ }
+
+ //
+ // punt if we've already tried the desktop bit depth and no stencil bits
+ //
+ if ( ( r_colorbits->integer == glw_state.desktopBitsPixel ) &&
+ ( stencilbits == 0 ) )
+ {
+ ReleaseDC( g_wv.hWnd, glw_state.hDC );
+ glw_state.hDC = NULL;
+
+ ri.Printf( PRINT_ALL, "...failed to find an appropriate PIXELFORMAT\n" );
+
+ return qfalse;
+ }
+
+ //
+ // second attempt: desktop's color bits and no stencil
+ //
+ if ( colorbits > glw_state.desktopBitsPixel )
+ {
+ colorbits = glw_state.desktopBitsPixel;
+ }
+ GLW_CreatePFD( &pfd, colorbits, depthbits, 0, r_stereo->integer );
+ if ( GLW_MakeContext( &pfd ) != TRY_PFD_SUCCESS )
+ {
+ if ( glw_state.hDC )
+ {
+ ReleaseDC( g_wv.hWnd, glw_state.hDC );
+ glw_state.hDC = NULL;
+ }
+
+ ri.Printf( PRINT_ALL, "...failed to find an appropriate PIXELFORMAT\n" );
+
+ return qfalse;
+ }
+ }
+
+ /*
+ ** report if stereo is desired but unavailable
+ */
+ if ( !( pfd.dwFlags & PFD_STEREO ) && ( r_stereo->integer != 0 ) )
+ {
+ ri.Printf( PRINT_ALL, "...failed to select stereo pixel format\n" );
+ glConfig.stereoEnabled = qfalse;
+ }
+ }
+
+ /*
+ ** store PFD specifics
+ */
+ glConfig.colorBits = ( int ) pfd.cColorBits;
+ glConfig.depthBits = ( int ) pfd.cDepthBits;
+ glConfig.stencilBits = ( int ) pfd.cStencilBits;
+
+ return qtrue;
+}
+
+/*
+** GLW_CreateWindow
+**
+** Responsible for creating the Win32 window and initializing the OpenGL driver.
+*/
+#define WINDOW_STYLE (WS_OVERLAPPED|WS_BORDER|WS_CAPTION|WS_VISIBLE)
+static qboolean GLW_CreateWindow( const char *drivername, int width, int height, int colorbits, qboolean cdsFullscreen )
+{
+ RECT r;
+ cvar_t *vid_xpos, *vid_ypos;
+ int stylebits;
+ int x, y, w, h;
+ int exstyle;
+
+ //
+ // register the window class if necessary
+ //
+ if ( !s_classRegistered )
+ {
+ WNDCLASS wc;
+
+ memset( &wc, 0, sizeof( wc ) );
+
+ wc.style = 0;
+ wc.lpfnWndProc = (WNDPROC) glw_state.wndproc;
+ wc.cbClsExtra = 0;
+ wc.cbWndExtra = 0;
+ wc.hInstance = g_wv.hInstance;
+ wc.hIcon = LoadIcon( g_wv.hInstance, MAKEINTRESOURCE(IDI_ICON1));
+ wc.hCursor = LoadCursor (NULL,IDC_ARROW);
+ wc.hbrBackground = (void *)COLOR_GRAYTEXT;
+ wc.lpszMenuName = 0;
+ wc.lpszClassName = WINDOW_CLASS_NAME;
+
+ if ( !RegisterClass( &wc ) )
+ {
+ ri.Error( ERR_FATAL, "GLW_CreateWindow: could not register window class" );
+ }
+ s_classRegistered = qtrue;
+ ri.Printf( PRINT_ALL, "...registered window class\n" );
+ }
+
+ //
+ // create the HWND if one does not already exist
+ //
+ if ( !g_wv.hWnd )
+ {
+ //
+ // compute width and height
+ //
+ r.left = 0;
+ r.top = 0;
+ r.right = width;
+ r.bottom = height;
+
+ if ( cdsFullscreen || !Q_stricmp( _3DFX_DRIVER_NAME, drivername ) )
+ {
+ exstyle = WS_EX_TOPMOST;
+ stylebits = WS_POPUP|WS_VISIBLE|WS_SYSMENU;
+ }
+ else
+ {
+ exstyle = 0;
+ stylebits = WINDOW_STYLE|WS_SYSMENU;
+ AdjustWindowRect (&r, stylebits, FALSE);
+ }
+
+ w = r.right - r.left;
+ h = r.bottom - r.top;
+
+ if ( cdsFullscreen || !Q_stricmp( _3DFX_DRIVER_NAME, drivername ) )
+ {
+ x = 0;
+ y = 0;
+ }
+ else
+ {
+ vid_xpos = ri.Cvar_Get ("vid_xpos", "", 0);
+ vid_ypos = ri.Cvar_Get ("vid_ypos", "", 0);
+ x = vid_xpos->integer;
+ y = vid_ypos->integer;
+
+ // adjust window coordinates if necessary
+ // so that the window is completely on screen
+ if ( x < 0 )
+ x = 0;
+ if ( y < 0 )
+ y = 0;
+
+ if ( w < glw_state.desktopWidth &&
+ h < glw_state.desktopHeight )
+ {
+ if ( x + w > glw_state.desktopWidth )
+ x = ( glw_state.desktopWidth - w );
+ if ( y + h > glw_state.desktopHeight )
+ y = ( glw_state.desktopHeight - h );
+ }
+ }
+
+ g_wv.hWnd = CreateWindowEx (
+ exstyle,
+ WINDOW_CLASS_NAME,
+ "Quake 3: Arena",
+ stylebits,
+ x, y, w, h,
+ NULL,
+ NULL,
+ g_wv.hInstance,
+ NULL);
+
+ if ( !g_wv.hWnd )
+ {
+ ri.Error (ERR_FATAL, "GLW_CreateWindow() - Couldn't create window");
+ }
+
+ ShowWindow( g_wv.hWnd, SW_SHOW );
+ UpdateWindow( g_wv.hWnd );
+ ri.Printf( PRINT_ALL, "...created window@%d,%d (%dx%d)\n", x, y, w, h );
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "...window already present, CreateWindowEx skipped\n" );
+ }
+
+ if ( !GLW_InitDriver( drivername, colorbits ) )
+ {
+ ShowWindow( g_wv.hWnd, SW_HIDE );
+ DestroyWindow( g_wv.hWnd );
+ g_wv.hWnd = NULL;
+
+ return qfalse;
+ }
+
+ SetForegroundWindow( g_wv.hWnd );
+ SetFocus( g_wv.hWnd );
+
+ return qtrue;
+}
+
+static void PrintCDSError( int value )
+{
+ switch ( value )
+ {
+ case DISP_CHANGE_RESTART:
+ ri.Printf( PRINT_ALL, "restart required\n" );
+ break;
+ case DISP_CHANGE_BADPARAM:
+ ri.Printf( PRINT_ALL, "bad param\n" );
+ break;
+ case DISP_CHANGE_BADFLAGS:
+ ri.Printf( PRINT_ALL, "bad flags\n" );
+ break;
+ case DISP_CHANGE_FAILED:
+ ri.Printf( PRINT_ALL, "DISP_CHANGE_FAILED\n" );
+ break;
+ case DISP_CHANGE_BADMODE:
+ ri.Printf( PRINT_ALL, "bad mode\n" );
+ break;
+ case DISP_CHANGE_NOTUPDATED:
+ ri.Printf( PRINT_ALL, "not updated\n" );
+ break;
+ default:
+ ri.Printf( PRINT_ALL, "unknown error %d\n", value );
+ break;
+ }
+}
+
+/*
+** GLW_SetMode
+*/
+static rserr_t GLW_SetMode( const char *drivername,
+ int mode,
+ int colorbits,
+ qboolean cdsFullscreen )
+{
+ HDC hDC;
+ const char *win_fs[] = { "W", "FS" };
+ int cdsRet;
+ DEVMODE dm;
+
+ //
+ // print out informational messages
+ //
+ ri.Printf( PRINT_ALL, "...setting mode %d:", mode );
+ if ( !R_GetModeInfo( &glConfig.vidWidth, &glConfig.vidHeight, &glConfig.windowAspect, mode ) )
+ {
+ ri.Printf( PRINT_ALL, " invalid mode\n" );
+ return RSERR_INVALID_MODE;
+ }
+ ri.Printf( PRINT_ALL, " %d %d %s\n", glConfig.vidWidth, glConfig.vidHeight, win_fs[cdsFullscreen] );
+
+ //
+ // check our desktop attributes
+ //
+ hDC = GetDC( GetDesktopWindow() );
+ glw_state.desktopBitsPixel = GetDeviceCaps( hDC, BITSPIXEL );
+ glw_state.desktopWidth = GetDeviceCaps( hDC, HORZRES );
+ glw_state.desktopHeight = GetDeviceCaps( hDC, VERTRES );
+ ReleaseDC( GetDesktopWindow(), hDC );
+
+ //
+ // verify desktop bit depth
+ //
+ if ( glConfig.driverType != GLDRV_VOODOO )
+ {
+ if ( glw_state.desktopBitsPixel < 15 || glw_state.desktopBitsPixel == 24 )
+ {
+ if ( colorbits == 0 || ( !cdsFullscreen && colorbits >= 15 ) )
+ {
+ if ( MessageBox( NULL,
+ "It is highly unlikely that a correct\n"
+ "windowed display can be initialized with\n"
+ "the current desktop display depth. Select\n"
+ "'OK' to try anyway. Press 'Cancel' if you\n"
+ "have a 3Dfx Voodoo, Voodoo-2, or Voodoo Rush\n"
+ "3D accelerator installed, or if you otherwise\n"
+ "wish to quit.",
+ "Low Desktop Color Depth",
+ MB_OKCANCEL | MB_ICONEXCLAMATION ) != IDOK )
+ {
+ return RSERR_INVALID_MODE;
+ }
+ }
+ }
+ }
+
+ // do a CDS if needed
+ if ( cdsFullscreen )
+ {
+ memset( &dm, 0, sizeof( dm ) );
+
+ dm.dmSize = sizeof( dm );
+
+ dm.dmPelsWidth = glConfig.vidWidth;
+ dm.dmPelsHeight = glConfig.vidHeight;
+ dm.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT;
+
+ if ( r_displayRefresh->integer != 0 )
+ {
+ dm.dmDisplayFrequency = r_displayRefresh->integer;
+ dm.dmFields |= DM_DISPLAYFREQUENCY;
+ }
+
+ // try to change color depth if possible
+ if ( colorbits != 0 )
+ {
+ if ( glw_state.allowdisplaydepthchange )
+ {
+ dm.dmBitsPerPel = colorbits;
+ dm.dmFields |= DM_BITSPERPEL;
+ ri.Printf( PRINT_ALL, "...using colorsbits of %d\n", colorbits );
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "WARNING:...changing depth not supported on Win95 < pre-OSR 2.x\n" );
+ }
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "...using desktop display depth of %d\n", glw_state.desktopBitsPixel );
+ }
+
+ //
+ // if we're already in fullscreen then just create the window
+ //
+ if ( glw_state.cdsFullscreen )
+ {
+ ri.Printf( PRINT_ALL, "...already fullscreen, avoiding redundant CDS\n" );
+
+ if ( !GLW_CreateWindow ( drivername, glConfig.vidWidth, glConfig.vidHeight, colorbits, qtrue ) )
+ {
+ ri.Printf( PRINT_ALL, "...restoring display settings\n" );
+ ChangeDisplaySettings( 0, 0 );
+ return RSERR_INVALID_MODE;
+ }
+ }
+ //
+ // need to call CDS
+ //
+ else
+ {
+ ri.Printf( PRINT_ALL, "...calling CDS: " );
+
+ // try setting the exact mode requested, because some drivers don't report
+ // the low res modes in EnumDisplaySettings, but still work
+ if ( ( cdsRet = ChangeDisplaySettings( &dm, CDS_FULLSCREEN ) ) == DISP_CHANGE_SUCCESSFUL )
+ {
+ ri.Printf( PRINT_ALL, "ok\n" );
+
+ if ( !GLW_CreateWindow ( drivername, glConfig.vidWidth, glConfig.vidHeight, colorbits, qtrue) )
+ {
+ ri.Printf( PRINT_ALL, "...restoring display settings\n" );
+ ChangeDisplaySettings( 0, 0 );
+ return RSERR_INVALID_MODE;
+ }
+
+ glw_state.cdsFullscreen = qtrue;
+ }
+ else
+ {
+ //
+ // the exact mode failed, so scan EnumDisplaySettings for the next largest mode
+ //
+ DEVMODE devmode;
+ int modeNum;
+
+ ri.Printf( PRINT_ALL, "failed, " );
+
+ PrintCDSError( cdsRet );
+
+ ri.Printf( PRINT_ALL, "...trying next higher resolution:" );
+
+ // we could do a better matching job here...
+ for ( modeNum = 0 ; ; modeNum++ ) {
+ if ( !EnumDisplaySettings( NULL, modeNum, &devmode ) ) {
+ modeNum = -1;
+ break;
+ }
+ if ( devmode.dmPelsWidth >= glConfig.vidWidth
+ && devmode.dmPelsHeight >= glConfig.vidHeight
+ && devmode.dmBitsPerPel >= 15 ) {
+ break;
+ }
+ }
+
+ if ( modeNum != -1 && ( cdsRet = ChangeDisplaySettings( &devmode, CDS_FULLSCREEN ) ) == DISP_CHANGE_SUCCESSFUL )
+ {
+ ri.Printf( PRINT_ALL, " ok\n" );
+ if ( !GLW_CreateWindow( drivername, glConfig.vidWidth, glConfig.vidHeight, colorbits, qtrue) )
+ {
+ ri.Printf( PRINT_ALL, "...restoring display settings\n" );
+ ChangeDisplaySettings( 0, 0 );
+ return RSERR_INVALID_MODE;
+ }
+
+ glw_state.cdsFullscreen = qtrue;
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, " failed, " );
+
+ PrintCDSError( cdsRet );
+
+ ri.Printf( PRINT_ALL, "...restoring display settings\n" );
+ ChangeDisplaySettings( 0, 0 );
+
+ glw_state.cdsFullscreen = qfalse;
+ glConfig.isFullscreen = qfalse;
+ if ( !GLW_CreateWindow( drivername, glConfig.vidWidth, glConfig.vidHeight, colorbits, qfalse) )
+ {
+ return RSERR_INVALID_MODE;
+ }
+ return RSERR_INVALID_FULLSCREEN;
+ }
+ }
+ }
+ }
+ else
+ {
+ if ( glw_state.cdsFullscreen )
+ {
+ ChangeDisplaySettings( 0, 0 );
+ }
+
+ glw_state.cdsFullscreen = qfalse;
+ if ( !GLW_CreateWindow( drivername, glConfig.vidWidth, glConfig.vidHeight, colorbits, qfalse ) )
+ {
+ return RSERR_INVALID_MODE;
+ }
+ }
+
+ //
+ // success, now check display frequency, although this won't be valid on Voodoo(2)
+ //
+ memset( &dm, 0, sizeof( dm ) );
+ dm.dmSize = sizeof( dm );
+ if ( EnumDisplaySettings( NULL, ENUM_CURRENT_SETTINGS, &dm ) )
+ {
+ glConfig.displayFrequency = dm.dmDisplayFrequency;
+ }
+
+ // NOTE: this is overridden later on standalone 3Dfx drivers
+ glConfig.isFullscreen = cdsFullscreen;
+
+ return RSERR_OK;
+}
+
+/*
+** GLW_InitExtensions
+*/
+static void GLW_InitExtensions( void )
+{
+ if ( !r_allowExtensions->integer )
+ {
+ ri.Printf( PRINT_ALL, "*** IGNORING OPENGL EXTENSIONS ***\n" );
+ return;
+ }
+
+ ri.Printf( PRINT_ALL, "Initializing OpenGL extensions\n" );
+
+ // GL_S3_s3tc
+ glConfig.textureCompression = TC_NONE;
+ if ( strstr( glConfig.extensions_string, "GL_S3_s3tc" ) )
+ {
+ if ( r_ext_compressed_textures->integer )
+ {
+ glConfig.textureCompression = TC_S3TC;
+ ri.Printf( PRINT_ALL, "...using GL_S3_s3tc\n" );
+ }
+ else
+ {
+ glConfig.textureCompression = TC_NONE;
+ ri.Printf( PRINT_ALL, "...ignoring GL_S3_s3tc\n" );
+ }
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "...GL_S3_s3tc not found\n" );
+ }
+
+ // GL_EXT_texture_env_add
+ glConfig.textureEnvAddAvailable = qfalse;
+ if ( strstr( glConfig.extensions_string, "EXT_texture_env_add" ) )
+ {
+ if ( r_ext_texture_env_add->integer )
+ {
+ glConfig.textureEnvAddAvailable = qtrue;
+ ri.Printf( PRINT_ALL, "...using GL_EXT_texture_env_add\n" );
+ }
+ else
+ {
+ glConfig.textureEnvAddAvailable = qfalse;
+ ri.Printf( PRINT_ALL, "...ignoring GL_EXT_texture_env_add\n" );
+ }
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "...GL_EXT_texture_env_add not found\n" );
+ }
+
+ // WGL_EXT_swap_control
+ qwglSwapIntervalEXT = ( BOOL (WINAPI *)(int)) qwglGetProcAddress( "wglSwapIntervalEXT" );
+ if ( qwglSwapIntervalEXT )
+ {
+ ri.Printf( PRINT_ALL, "...using WGL_EXT_swap_control\n" );
+ r_swapInterval->modified = qtrue; // force a set next frame
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "...WGL_EXT_swap_control not found\n" );
+ }
+
+ // GL_ARB_multitexture
+ qglMultiTexCoord2fARB = NULL;
+ qglActiveTextureARB = NULL;
+ qglClientActiveTextureARB = NULL;
+ if ( strstr( glConfig.extensions_string, "GL_ARB_multitexture" ) )
+ {
+ if ( r_ext_multitexture->integer )
+ {
+ qglMultiTexCoord2fARB = ( PFNGLMULTITEXCOORD2FARBPROC ) qwglGetProcAddress( "glMultiTexCoord2fARB" );
+ qglActiveTextureARB = ( PFNGLACTIVETEXTUREARBPROC ) qwglGetProcAddress( "glActiveTextureARB" );
+ qglClientActiveTextureARB = ( PFNGLCLIENTACTIVETEXTUREARBPROC ) qwglGetProcAddress( "glClientActiveTextureARB" );
+
+ if ( qglActiveTextureARB )
+ {
+ qglGetIntegerv( GL_MAX_ACTIVE_TEXTURES_ARB, &glConfig.maxActiveTextures );
+
+ if ( glConfig.maxActiveTextures > 1 )
+ {
+ ri.Printf( PRINT_ALL, "...using GL_ARB_multitexture\n" );
+ }
+ else
+ {
+ qglMultiTexCoord2fARB = NULL;
+ qglActiveTextureARB = NULL;
+ qglClientActiveTextureARB = NULL;
+ ri.Printf( PRINT_ALL, "...not using GL_ARB_multitexture, < 2 texture units\n" );
+ }
+ }
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "...ignoring GL_ARB_multitexture\n" );
+ }
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "...GL_ARB_multitexture not found\n" );
+ }
+
+ // GL_EXT_compiled_vertex_array
+ qglLockArraysEXT = NULL;
+ qglUnlockArraysEXT = NULL;
+ if ( strstr( glConfig.extensions_string, "GL_EXT_compiled_vertex_array" ) && ( glConfig.hardwareType != GLHW_RIVA128 ) )
+ {
+ if ( r_ext_compiled_vertex_array->integer )
+ {
+ ri.Printf( PRINT_ALL, "...using GL_EXT_compiled_vertex_array\n" );
+ qglLockArraysEXT = ( void ( APIENTRY * )( int, int ) ) qwglGetProcAddress( "glLockArraysEXT" );
+ qglUnlockArraysEXT = ( void ( APIENTRY * )( void ) ) qwglGetProcAddress( "glUnlockArraysEXT" );
+ if (!qglLockArraysEXT || !qglUnlockArraysEXT) {
+ ri.Error (ERR_FATAL, "bad getprocaddress");
+ }
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "...ignoring GL_EXT_compiled_vertex_array\n" );
+ }
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "...GL_EXT_compiled_vertex_array not found\n" );
+ }
+
+ // WGL_3DFX_gamma_control
+ qwglGetDeviceGammaRamp3DFX = NULL;
+ qwglSetDeviceGammaRamp3DFX = NULL;
+
+ if ( strstr( glConfig.extensions_string, "WGL_3DFX_gamma_control" ) )
+ {
+ if ( !r_ignorehwgamma->integer && r_ext_gamma_control->integer )
+ {
+ qwglGetDeviceGammaRamp3DFX = ( BOOL ( WINAPI * )( HDC, LPVOID ) ) qwglGetProcAddress( "wglGetDeviceGammaRamp3DFX" );
+ qwglSetDeviceGammaRamp3DFX = ( BOOL ( WINAPI * )( HDC, LPVOID ) ) qwglGetProcAddress( "wglSetDeviceGammaRamp3DFX" );
+
+ if ( qwglGetDeviceGammaRamp3DFX && qwglSetDeviceGammaRamp3DFX )
+ {
+ ri.Printf( PRINT_ALL, "...using WGL_3DFX_gamma_control\n" );
+ }
+ else
+ {
+ qwglGetDeviceGammaRamp3DFX = NULL;
+ qwglSetDeviceGammaRamp3DFX = NULL;
+ }
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "...ignoring WGL_3DFX_gamma_control\n" );
+ }
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "...WGL_3DFX_gamma_control not found\n" );
+ }
+}
+
+/*
+** GLW_CheckOSVersion
+*/
+static qboolean GLW_CheckOSVersion( void )
+{
+#define OSR2_BUILD_NUMBER 1111
+
+ OSVERSIONINFO vinfo;
+
+ vinfo.dwOSVersionInfoSize = sizeof(vinfo);
+
+ glw_state.allowdisplaydepthchange = qfalse;
+
+ if ( GetVersionEx( &vinfo) )
+ {
+ if ( vinfo.dwMajorVersion > 4 )
+ {
+ glw_state.allowdisplaydepthchange = qtrue;
+ }
+ else if ( vinfo.dwMajorVersion == 4 )
+ {
+ if ( vinfo.dwPlatformId == VER_PLATFORM_WIN32_NT )
+ {
+ glw_state.allowdisplaydepthchange = qtrue;
+ }
+ else if ( vinfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS )
+ {
+ if ( LOWORD( vinfo.dwBuildNumber ) >= OSR2_BUILD_NUMBER )
+ {
+ glw_state.allowdisplaydepthchange = qtrue;
+ }
+ }
+ }
+ }
+ else
+ {
+ ri.Printf( PRINT_ALL, "GLW_CheckOSVersion() - GetVersionEx failed\n" );
+ return qfalse;
+ }
+
+ return qtrue;
+}
+
+/*
+** GLW_LoadOpenGL
+**
+** GLimp_win.c internal function that attempts to load and use
+** a specific OpenGL DLL.
+*/
+static qboolean GLW_LoadOpenGL( const char *drivername )
+{
+ char buffer[1024];
+ qboolean cdsFullscreen;
+
+ Q_strncpyz( buffer, drivername, sizeof(buffer) );
+ Q_strlwr(buffer);
+
+ //
+ // determine if we're on a standalone driver
+ //
+ if ( strstr( buffer, "opengl32" ) != 0 || r_maskMinidriver->integer )
+ {
+ glConfig.driverType = GLDRV_ICD;
+ }
+ else
+ {
+ glConfig.driverType = GLDRV_STANDALONE;
+
+ ri.Printf( PRINT_ALL, "...assuming '%s' is a standalone driver\n", drivername );
+
+ if ( strstr( buffer, _3DFX_DRIVER_NAME ) )
+ {
+ glConfig.driverType = GLDRV_VOODOO;
+ }
+ }
+
+ // disable the 3Dfx splash screen
+ _putenv("FX_GLIDE_NO_SPLASH=0");
+
+ //
+ // load the driver and bind our function pointers to it
+ //
+ if ( QGL_Init( buffer ) )
+ {
+ cdsFullscreen = r_fullscreen->integer;
+
+ // create the window and set up the context
+ if ( !GLW_StartDriverAndSetMode( drivername, r_mode->integer, r_colorbits->integer, cdsFullscreen ) )
+ {
+ // if we're on a 24/32-bit desktop and we're going fullscreen on an ICD,
+ // try it again but with a 16-bit desktop
+ if ( glConfig.driverType == GLDRV_ICD )
+ {
+ if ( r_colorbits->integer != 16 ||
+ cdsFullscreen != qtrue ||
+ r_mode->integer != 3 )
+ {
+ if ( !GLW_StartDriverAndSetMode( drivername, 3, 16, qtrue ) )
+ {
+ goto fail;
+ }
+ }
+ }
+ else
+ {
+ goto fail;
+ }
+ }
+
+ if ( glConfig.driverType == GLDRV_VOODOO )
+ {
+ glConfig.isFullscreen = qtrue;
+ }
+
+ return qtrue;
+ }
+fail:
+
+ QGL_Shutdown();
+
+ return qfalse;
+}
+
+/*
+** GLimp_EndFrame
+*/
+void GLimp_EndFrame (void)
+{
+ //
+ // swapinterval stuff
+ //
+ if ( r_swapInterval->modified ) {
+ r_swapInterval->modified = qfalse;
+
+ if ( !glConfig.stereoEnabled ) { // why?
+ if ( qwglSwapIntervalEXT ) {
+ qwglSwapIntervalEXT( r_swapInterval->integer );
+ }
+ }
+ }
+
+
+ // don't flip if drawing to front buffer
+ if ( Q_stricmp( r_drawBuffer->string, "GL_FRONT" ) != 0 )
+ {
+ if ( glConfig.driverType > GLDRV_ICD )
+ {
+ if ( !qwglSwapBuffers( glw_state.hDC ) )
+ {
+ ri.Error( ERR_FATAL, "GLimp_EndFrame() - SwapBuffers() failed!\n" );
+ }
+ }
+ else
+ {
+ SwapBuffers( glw_state.hDC );
+ }
+ }
+
+ // check logging
+ QGL_EnableLogging( r_logFile->integer );
+}
+
+static void GLW_StartOpenGL( void )
+{
+ qboolean attemptedOpenGL32 = qfalse;
+ qboolean attempted3Dfx = qfalse;
+
+ //
+ // load and initialize the specific OpenGL driver
+ //
+ if ( !GLW_LoadOpenGL( r_glDriver->string ) )
+ {
+ if ( !Q_stricmp( r_glDriver->string, OPENGL_DRIVER_NAME ) )
+ {
+ attemptedOpenGL32 = qtrue;
+ }
+ else if ( !Q_stricmp( r_glDriver->string, _3DFX_DRIVER_NAME ) )
+ {
+ attempted3Dfx = qtrue;
+ }
+
+ if ( !attempted3Dfx )
+ {
+ attempted3Dfx = qtrue;
+ if ( GLW_LoadOpenGL( _3DFX_DRIVER_NAME ) )
+ {
+ ri.Cvar_Set( "r_glDriver", _3DFX_DRIVER_NAME );
+ r_glDriver->modified = qfalse;
+ }
+ else
+ {
+ if ( !attemptedOpenGL32 )
+ {
+ if ( !GLW_LoadOpenGL( OPENGL_DRIVER_NAME ) )
+ {
+ ri.Error( ERR_FATAL, "GLW_StartOpenGL() - could not load OpenGL subsystem\n" );
+ }
+ ri.Cvar_Set( "r_glDriver", OPENGL_DRIVER_NAME );
+ r_glDriver->modified = qfalse;
+ }
+ else
+ {
+ ri.Error( ERR_FATAL, "GLW_StartOpenGL() - could not load OpenGL subsystem\n" );
+ }
+ }
+ }
+ else if ( !attemptedOpenGL32 )
+ {
+ attemptedOpenGL32 = qtrue;
+ if ( GLW_LoadOpenGL( OPENGL_DRIVER_NAME ) )
+ {
+ ri.Cvar_Set( "r_glDriver", OPENGL_DRIVER_NAME );
+ r_glDriver->modified = qfalse;
+ }
+ else
+ {
+ ri.Error( ERR_FATAL, "GLW_StartOpenGL() - could not load OpenGL subsystem\n" );
+ }
+ }
+ }
+}
+
+/*
+** GLimp_Init
+**
+** This is the platform specific OpenGL initialization function. It
+** is responsible for loading OpenGL, initializing it, setting
+** extensions, creating a window of the appropriate size, doing
+** fullscreen manipulations, etc. Its overall responsibility is
+** to make sure that a functional OpenGL subsystem is operating
+** when it returns to the ref.
+*/
+void GLimp_Init( void )
+{
+ char buf[1024];
+ cvar_t *lastValidRenderer = ri.Cvar_Get( "r_lastValidRenderer", "(uninitialized)", CVAR_ARCHIVE );
+ cvar_t *cv;
+
+ ri.Printf( PRINT_ALL, "Initializing OpenGL subsystem\n" );
+
+ //
+ // check OS version to see if we can do fullscreen display changes
+ //
+ if ( !GLW_CheckOSVersion() )
+ {
+ ri.Error( ERR_FATAL, "GLimp_Init() - incorrect operating system\n" );
+ }
+
+ // save off hInstance and wndproc
+ cv = ri.Cvar_Get( "win_hinstance", "", 0 );
+ sscanf( cv->string, "%i", (int *)&g_wv.hInstance );
+
+ cv = ri.Cvar_Get( "win_wndproc", "", 0 );
+ sscanf( cv->string, "%i", (int *)&glw_state.wndproc );
+
+ r_allowSoftwareGL = ri.Cvar_Get( "r_allowSoftwareGL", "0", CVAR_LATCH );
+ r_maskMinidriver = ri.Cvar_Get( "r_maskMinidriver", "0", CVAR_LATCH );
+
+ // load appropriate DLL and initialize subsystem
+ GLW_StartOpenGL();
+
+ // get our config strings
+ Q_strncpyz( glConfig.vendor_string, qglGetString (GL_VENDOR), sizeof( glConfig.vendor_string ) );
+ Q_strncpyz( glConfig.renderer_string, qglGetString (GL_RENDERER), sizeof( glConfig.renderer_string ) );
+ Q_strncpyz( glConfig.version_string, qglGetString (GL_VERSION), sizeof( glConfig.version_string ) );
+ Q_strncpyz( glConfig.extensions_string, qglGetString (GL_EXTENSIONS), sizeof( glConfig.extensions_string ) );
+
+ //
+ // chipset specific configuration
+ //
+ Q_strncpyz( buf, glConfig.renderer_string, sizeof(buf) );
+ Q_strlwr( buf );
+
+ //
+ // NOTE: if changing cvars, do it within this block. This allows them
+ // to be overridden when testing driver fixes, etc. but only sets
+ // them to their default state when the hardware is first installed/run.
+ //
+ if ( Q_stricmp( lastValidRenderer->string, glConfig.renderer_string ) )
+ {
+ glConfig.hardwareType = GLHW_GENERIC;
+
+ ri.Cvar_Set( "r_textureMode", "GL_LINEAR_MIPMAP_NEAREST" );
+
+ // VOODOO GRAPHICS w/ 2MB
+ if ( strstr( buf, "voodoo graphics/1 tmu/2 mb" ) )
+ {
+ ri.Cvar_Set( "r_picmip", "2" );
+ ri.Cvar_Get( "r_picmip", "1", CVAR_ARCHIVE | CVAR_LATCH );
+ }
+ else
+ {
+ ri.Cvar_Set( "r_picmip", "1" );
+
+ if ( strstr( buf, "rage 128" ) || strstr( buf, "rage128" ) )
+ {
+ ri.Cvar_Set( "r_finish", "0" );
+ }
+ // Savage3D and Savage4 should always have trilinear enabled
+ else if ( strstr( buf, "savage3d" ) || strstr( buf, "s3 savage4" ) )
+ {
+ ri.Cvar_Set( "r_texturemode", "GL_LINEAR_MIPMAP_LINEAR" );
+ }
+ }
+ }
+
+ //
+ // this is where hardware specific workarounds that should be
+ // detected/initialized every startup should go.
+ //
+ if ( strstr( buf, "banshee" ) || strstr( buf, "voodoo3" ) )
+ {
+ glConfig.hardwareType = GLHW_3DFX_2D3D;
+ }
+ // VOODOO GRAPHICS w/ 2MB
+ else if ( strstr( buf, "voodoo graphics/1 tmu/2 mb" ) )
+ {
+ }
+ else if ( strstr( buf, "glzicd" ) )
+ {
+ }
+ else if ( strstr( buf, "rage pro" ) || strstr( buf, "Rage Pro" ) || strstr( buf, "ragepro" ) )
+ {
+ glConfig.hardwareType = GLHW_RAGEPRO;
+ }
+ else if ( strstr( buf, "rage 128" ) )
+ {
+ }
+ else if ( strstr( buf, "permedia2" ) )
+ {
+ glConfig.hardwareType = GLHW_PERMEDIA2;
+ }
+ else if ( strstr( buf, "riva 128" ) )
+ {
+ glConfig.hardwareType = GLHW_RIVA128;
+ }
+ else if ( strstr( buf, "riva tnt " ) )
+ {
+ }
+
+ ri.Cvar_Set( "r_lastValidRenderer", glConfig.renderer_string );
+
+ GLW_InitExtensions();
+ WG_CheckHardwareGamma();
+}
+
+/*
+** GLimp_Shutdown
+**
+** This routine does all OS specific shutdown procedures for the OpenGL
+** subsystem.
+*/
+void GLimp_Shutdown( void )
+{
+// const char *strings[] = { "soft", "hard" };
+ const char *success[] = { "failed", "success" };
+ int retVal;
+
+ // FIXME: Brian, we need better fallbacks from partially initialized failures
+ if ( !qwglMakeCurrent ) {
+ return;
+ }
+
+ ri.Printf( PRINT_ALL, "Shutting down OpenGL subsystem\n" );
+
+ // restore gamma. We do this first because 3Dfx's extension needs a valid OGL subsystem
+ WG_RestoreGamma();
+
+ // set current context to NULL
+ if ( qwglMakeCurrent )
+ {
+ retVal = qwglMakeCurrent( NULL, NULL ) != 0;
+
+ ri.Printf( PRINT_ALL, "...wglMakeCurrent( NULL, NULL ): %s\n", success[retVal] );
+ }
+
+ // delete HGLRC
+ if ( glw_state.hGLRC )
+ {
+ retVal = qwglDeleteContext( glw_state.hGLRC ) != 0;
+ ri.Printf( PRINT_ALL, "...deleting GL context: %s\n", success[retVal] );
+ glw_state.hGLRC = NULL;
+ }
+
+ // release DC
+ if ( glw_state.hDC )
+ {
+ retVal = ReleaseDC( g_wv.hWnd, glw_state.hDC ) != 0;
+ ri.Printf( PRINT_ALL, "...releasing DC: %s\n", success[retVal] );
+ glw_state.hDC = NULL;
+ }
+
+ // destroy window
+ if ( g_wv.hWnd )
+ {
+ ri.Printf( PRINT_ALL, "...destroying window\n" );
+ ShowWindow( g_wv.hWnd, SW_HIDE );
+ DestroyWindow( g_wv.hWnd );
+ g_wv.hWnd = NULL;
+ glw_state.pixelFormatSet = qfalse;
+ }
+
+ // close the r_logFile
+ if ( glw_state.log_fp )
+ {
+ fclose( glw_state.log_fp );
+ glw_state.log_fp = 0;
+ }
+
+ // reset display settings
+ if ( glw_state.cdsFullscreen )
+ {
+ ri.Printf( PRINT_ALL, "...resetting display\n" );
+ ChangeDisplaySettings( 0, 0 );
+ glw_state.cdsFullscreen = qfalse;
+ }
+
+ // shutdown QGL subsystem
+ QGL_Shutdown();
+
+ memset( &glConfig, 0, sizeof( glConfig ) );
+ memset( &glState, 0, sizeof( glState ) );
+}
+
+/*
+** GLimp_LogComment
+*/
+void GLimp_LogComment( char *comment )
+{
+ if ( glw_state.log_fp ) {
+ fprintf( glw_state.log_fp, "%s", comment );
+ }
+}
+
+
+/*
+===========================================================
+
+SMP acceleration
+
+===========================================================
+*/
+
+HANDLE renderCommandsEvent;
+HANDLE renderCompletedEvent;
+HANDLE renderActiveEvent;
+
+void (*glimpRenderThread)( void );
+
+void GLimp_RenderThreadWrapper( void ) {
+ glimpRenderThread();
+
+ // unbind the context before we die
+ qwglMakeCurrent( glw_state.hDC, NULL );
+}
+
+/*
+=======================
+GLimp_SpawnRenderThread
+=======================
+*/
+HANDLE renderThreadHandle;
+int renderThreadId;
+qboolean GLimp_SpawnRenderThread( void (*function)( void ) ) {
+
+ renderCommandsEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
+ renderCompletedEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
+ renderActiveEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
+
+ glimpRenderThread = function;
+
+ renderThreadHandle = CreateThread(
+ NULL, // LPSECURITY_ATTRIBUTES lpsa,
+ 0, // DWORD cbStack,
+ (LPTHREAD_START_ROUTINE)GLimp_RenderThreadWrapper, // LPTHREAD_START_ROUTINE lpStartAddr,
+ 0, // LPVOID lpvThreadParm,
+ 0, // DWORD fdwCreate,
+ &renderThreadId );
+
+ if ( !renderThreadHandle ) {
+ return qfalse;
+ }
+
+ return qtrue;
+}
+
+static void *smpData;
+static int wglErrors;
+
+void *GLimp_RendererSleep( void ) {
+ void *data;
+
+ if ( !qwglMakeCurrent( glw_state.hDC, NULL ) ) {
+ wglErrors++;
+ }
+
+ ResetEvent( renderActiveEvent );
+
+ // after this, the front end can exit GLimp_FrontEndSleep
+ SetEvent( renderCompletedEvent );
+
+ WaitForSingleObject( renderCommandsEvent, INFINITE );
+
+ if ( !qwglMakeCurrent( glw_state.hDC, glw_state.hGLRC ) ) {
+ wglErrors++;
+ }
+
+ ResetEvent( renderCompletedEvent );
+ ResetEvent( renderCommandsEvent );
+
+ data = smpData;
+
+ // after this, the main thread can exit GLimp_WakeRenderer
+ SetEvent( renderActiveEvent );
+
+ return data;
+}
+
+
+void GLimp_FrontEndSleep( void ) {
+ WaitForSingleObject( renderCompletedEvent, INFINITE );
+
+ if ( !qwglMakeCurrent( glw_state.hDC, glw_state.hGLRC ) ) {
+ wglErrors++;
+ }
+}
+
+
+void GLimp_WakeRenderer( void *data ) {
+ smpData = data;
+
+ if ( !qwglMakeCurrent( glw_state.hDC, NULL ) ) {
+ wglErrors++;
+ }
+
+ // after this, the renderer can continue through GLimp_RendererSleep
+ SetEvent( renderCommandsEvent );
+
+ WaitForSingleObject( renderActiveEvent, INFINITE );
+}
+
diff --git a/code/win32/win_input.c b/code/win32/win_input.c
new file mode 100755
index 0000000..7012558
--- /dev/null
+++ b/code/win32/win_input.c
@@ -0,0 +1,1149 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// win_input.c -- win32 mouse and joystick code
+// 02/21/97 JCB Added extended DirectInput code to support external controllers.
+
+#include "../client/client.h"
+#include "win_local.h"
+
+
+typedef struct {
+ int oldButtonState;
+
+ qboolean mouseActive;
+ qboolean mouseInitialized;
+ qboolean mouseStartupDelayed; // delay mouse init to try DI again when we have a window
+} WinMouseVars_t;
+
+static WinMouseVars_t s_wmv;
+
+static int window_center_x, window_center_y;
+
+//
+// MIDI definitions
+//
+static void IN_StartupMIDI( void );
+static void IN_ShutdownMIDI( void );
+
+#define MAX_MIDIIN_DEVICES 8
+
+typedef struct {
+ int numDevices;
+ MIDIINCAPS caps[MAX_MIDIIN_DEVICES];
+
+ HMIDIIN hMidiIn;
+} MidiInfo_t;
+
+static MidiInfo_t s_midiInfo;
+
+//
+// Joystick definitions
+//
+#define JOY_MAX_AXES 6 // X, Y, Z, R, U, V
+
+typedef struct {
+ qboolean avail;
+ int id; // joystick number
+ JOYCAPS jc;
+
+ int oldbuttonstate;
+ int oldpovstate;
+
+ JOYINFOEX ji;
+} joystickInfo_t;
+
+static joystickInfo_t joy;
+
+
+
+cvar_t *in_midi;
+cvar_t *in_midiport;
+cvar_t *in_midichannel;
+cvar_t *in_mididevice;
+
+cvar_t *in_mouse;
+cvar_t *in_logitechbug;
+cvar_t *in_joystick;
+cvar_t *in_joyBallScale;
+cvar_t *in_debugJoystick;
+cvar_t *joy_threshold;
+
+qboolean in_appactive;
+
+// forward-referenced functions
+void IN_StartupJoystick (void);
+void IN_JoyMove(void);
+
+static void MidiInfo_f( void );
+
+/*
+============================================================
+
+WIN32 MOUSE CONTROL
+
+============================================================
+*/
+
+/*
+================
+IN_InitWin32Mouse
+================
+*/
+void IN_InitWin32Mouse( void )
+{
+}
+
+/*
+================
+IN_ShutdownWin32Mouse
+================
+*/
+void IN_ShutdownWin32Mouse( void ) {
+}
+
+/*
+================
+IN_ActivateWin32Mouse
+================
+*/
+void IN_ActivateWin32Mouse( void ) {
+ int width, height;
+ RECT window_rect;
+
+ width = GetSystemMetrics (SM_CXSCREEN);
+ height = GetSystemMetrics (SM_CYSCREEN);
+
+ GetWindowRect ( g_wv.hWnd, &window_rect);
+ if (window_rect.left < 0)
+ window_rect.left = 0;
+ if (window_rect.top < 0)
+ window_rect.top = 0;
+ if (window_rect.right >= width)
+ window_rect.right = width-1;
+ if (window_rect.bottom >= height-1)
+ window_rect.bottom = height-1;
+ window_center_x = (window_rect.right + window_rect.left)/2;
+ window_center_y = (window_rect.top + window_rect.bottom)/2;
+
+ SetCursorPos (window_center_x, window_center_y);
+
+ SetCapture ( g_wv.hWnd );
+ ClipCursor (&window_rect);
+ while (ShowCursor (FALSE) >= 0)
+ ;
+}
+
+/*
+================
+IN_DeactivateWin32Mouse
+================
+*/
+void IN_DeactivateWin32Mouse( void )
+{
+ ClipCursor (NULL);
+ ReleaseCapture ();
+ while (ShowCursor (TRUE) < 0)
+ ;
+}
+
+/*
+================
+IN_Win32Mouse
+================
+*/
+void IN_Win32Mouse( int *mx, int *my ) {
+ POINT current_pos;
+
+ // find mouse movement
+ GetCursorPos (&current_pos);
+
+ // force the mouse to the center, so there's room to move
+ SetCursorPos (window_center_x, window_center_y);
+
+ *mx = current_pos.x - window_center_x;
+ *my = current_pos.y - window_center_y;
+}
+
+
+/*
+============================================================
+
+DIRECT INPUT MOUSE CONTROL
+
+============================================================
+*/
+
+#undef DEFINE_GUID
+
+#define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
+ EXTERN_C const GUID name \
+ = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }
+
+DEFINE_GUID(GUID_SysMouse, 0x6F1D2B60,0xD5A0,0x11CF,0xBF,0xC7,0x44,0x45,0x53,0x54,0x00,0x00);
+DEFINE_GUID(GUID_XAxis, 0xA36D02E0,0xC9F3,0x11CF,0xBF,0xC7,0x44,0x45,0x53,0x54,0x00,0x00);
+DEFINE_GUID(GUID_YAxis, 0xA36D02E1,0xC9F3,0x11CF,0xBF,0xC7,0x44,0x45,0x53,0x54,0x00,0x00);
+DEFINE_GUID(GUID_ZAxis, 0xA36D02E2,0xC9F3,0x11CF,0xBF,0xC7,0x44,0x45,0x53,0x54,0x00,0x00);
+
+
+#define DINPUT_BUFFERSIZE 16
+#define iDirectInputCreate(a,b,c,d) pDirectInputCreate(a,b,c,d)
+
+HRESULT (WINAPI *pDirectInputCreate)(HINSTANCE hinst, DWORD dwVersion,
+ LPDIRECTINPUT * lplpDirectInput, LPUNKNOWN punkOuter);
+
+static HINSTANCE hInstDI;
+
+typedef struct MYDATA {
+ LONG lX; // X axis goes here
+ LONG lY; // Y axis goes here
+ LONG lZ; // Z axis goes here
+ BYTE bButtonA; // One button goes here
+ BYTE bButtonB; // Another button goes here
+ BYTE bButtonC; // Another button goes here
+ BYTE bButtonD; // Another button goes here
+} MYDATA;
+
+static DIOBJECTDATAFORMAT rgodf[] = {
+ { &GUID_XAxis, FIELD_OFFSET(MYDATA, lX), DIDFT_AXIS | DIDFT_ANYINSTANCE, 0,},
+ { &GUID_YAxis, FIELD_OFFSET(MYDATA, lY), DIDFT_AXIS | DIDFT_ANYINSTANCE, 0,},
+ { &GUID_ZAxis, FIELD_OFFSET(MYDATA, lZ), 0x80000000 | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0,},
+ { 0, FIELD_OFFSET(MYDATA, bButtonA), DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,},
+ { 0, FIELD_OFFSET(MYDATA, bButtonB), DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,},
+ { 0, FIELD_OFFSET(MYDATA, bButtonC), 0x80000000 | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,},
+ { 0, FIELD_OFFSET(MYDATA, bButtonD), 0x80000000 | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,},
+};
+
+#define NUM_OBJECTS (sizeof(rgodf) / sizeof(rgodf[0]))
+
+// NOTE TTimo: would be easier using c_dfDIMouse or c_dfDIMouse2
+static DIDATAFORMAT df = {
+ sizeof(DIDATAFORMAT), // this structure
+ sizeof(DIOBJECTDATAFORMAT), // size of object data format
+ DIDF_RELAXIS, // absolute axis coordinates
+ sizeof(MYDATA), // device data size
+ NUM_OBJECTS, // number of objects
+ rgodf, // and here they are
+};
+
+static LPDIRECTINPUT g_pdi;
+static LPDIRECTINPUTDEVICE g_pMouse;
+
+void IN_DIMouse( int *mx, int *my );
+
+/*
+========================
+IN_InitDIMouse
+========================
+*/
+qboolean IN_InitDIMouse( void ) {
+ HRESULT hr;
+ int x, y;
+ DIPROPDWORD dipdw = {
+ {
+ sizeof(DIPROPDWORD), // diph.dwSize
+ sizeof(DIPROPHEADER), // diph.dwHeaderSize
+ 0, // diph.dwObj
+ DIPH_DEVICE, // diph.dwHow
+ },
+ DINPUT_BUFFERSIZE, // dwData
+ };
+
+ Com_Printf( "Initializing DirectInput...\n");
+
+ if (!hInstDI) {
+ hInstDI = LoadLibrary("dinput.dll");
+
+ if (hInstDI == NULL) {
+ Com_Printf ("Couldn't load dinput.dll\n");
+ return qfalse;
+ }
+ }
+
+ if (!pDirectInputCreate) {
+ pDirectInputCreate = (long (__stdcall *)(void *,unsigned long ,struct IDirectInputA ** ,struct IUnknown *))
+ GetProcAddress(hInstDI,"DirectInputCreateA");
+
+ if (!pDirectInputCreate) {
+ Com_Printf ("Couldn't get DI proc addr\n");
+ return qfalse;
+ }
+ }
+
+ // register with DirectInput and get an IDirectInput to play with.
+ hr = iDirectInputCreate( g_wv.hInstance, DIRECTINPUT_VERSION, &g_pdi, NULL);
+
+ if (FAILED(hr)) {
+ Com_Printf ("iDirectInputCreate failed\n");
+ return qfalse;
+ }
+
+ // obtain an interface to the system mouse device.
+ hr = IDirectInput_CreateDevice(g_pdi, &GUID_SysMouse, &g_pMouse, NULL);
+
+ if (FAILED(hr)) {
+ Com_Printf ("Couldn't open DI mouse device\n");
+ return qfalse;
+ }
+
+ // set the data format to "mouse format".
+ hr = IDirectInputDevice_SetDataFormat(g_pMouse, &df);
+
+ if (FAILED(hr)) {
+ Com_Printf ("Couldn't set DI mouse format\n");
+ return qfalse;
+ }
+
+ // set the cooperativity level.
+ hr = IDirectInputDevice_SetCooperativeLevel(g_pMouse, g_wv.hWnd,
+ DISCL_EXCLUSIVE | DISCL_FOREGROUND);
+
+ // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=50
+ if (FAILED(hr)) {
+ Com_Printf ("Couldn't set DI coop level\n");
+ return qfalse;
+ }
+
+
+ // set the buffer size to DINPUT_BUFFERSIZE elements.
+ // the buffer size is a DWORD property associated with the device
+ hr = IDirectInputDevice_SetProperty(g_pMouse, DIPROP_BUFFERSIZE, &dipdw.diph);
+
+ if (FAILED(hr)) {
+ Com_Printf ("Couldn't set DI buffersize\n");
+ return qfalse;
+ }
+
+ // clear any pending samples
+ IN_DIMouse( &x, &y );
+ IN_DIMouse( &x, &y );
+
+ Com_Printf( "DirectInput initialized.\n");
+ return qtrue;
+}
+
+/*
+==========================
+IN_ShutdownDIMouse
+==========================
+*/
+void IN_ShutdownDIMouse( void ) {
+ if (g_pMouse) {
+ IDirectInputDevice_Release(g_pMouse);
+ g_pMouse = NULL;
+ }
+
+ if (g_pdi) {
+ IDirectInput_Release(g_pdi);
+ g_pdi = NULL;
+ }
+}
+
+/*
+==========================
+IN_ActivateDIMouse
+==========================
+*/
+void IN_ActivateDIMouse( void ) {
+ HRESULT hr;
+
+ if (!g_pMouse) {
+ return;
+ }
+
+ // we may fail to reacquire if the window has been recreated
+ hr = IDirectInputDevice_Acquire( g_pMouse );
+ if (FAILED(hr)) {
+ if ( !IN_InitDIMouse() ) {
+ Com_Printf ("Falling back to Win32 mouse support...\n");
+ Cvar_Set( "in_mouse", "-1" );
+ }
+ }
+}
+
+/*
+==========================
+IN_DeactivateDIMouse
+==========================
+*/
+void IN_DeactivateDIMouse( void ) {
+ if (!g_pMouse) {
+ return;
+ }
+ IDirectInputDevice_Unacquire( g_pMouse );
+}
+
+
+/*
+===================
+IN_DIMouse
+===================
+*/
+void IN_DIMouse( int *mx, int *my ) {
+ DIDEVICEOBJECTDATA od;
+ DIMOUSESTATE state;
+ DWORD dwElements;
+ HRESULT hr;
+ int value;
+ static float oldSysTime;
+
+ if ( !g_pMouse ) {
+ return;
+ }
+
+ // fetch new events
+ for (;;)
+ {
+ dwElements = 1;
+
+ hr = IDirectInputDevice_GetDeviceData(g_pMouse,
+ sizeof(DIDEVICEOBJECTDATA), &od, &dwElements, 0);
+ if ((hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED)) {
+ IDirectInputDevice_Acquire(g_pMouse);
+ return;
+ }
+
+ /* Unable to read data or no data available */
+ if ( FAILED(hr) ) {
+ break;
+ }
+
+ if ( dwElements == 0 ) {
+ break;
+ }
+
+ switch (od.dwOfs) {
+ case DIMOFS_BUTTON0:
+ if (od.dwData & 0x80)
+ Sys_QueEvent( od.dwTimeStamp, SE_KEY, K_MOUSE1, qtrue, 0, NULL );
+ else
+ Sys_QueEvent( od.dwTimeStamp, SE_KEY, K_MOUSE1, qfalse, 0, NULL );
+ break;
+
+ case DIMOFS_BUTTON1:
+ if (od.dwData & 0x80)
+ Sys_QueEvent( od.dwTimeStamp, SE_KEY, K_MOUSE2, qtrue, 0, NULL );
+ else
+ Sys_QueEvent( od.dwTimeStamp, SE_KEY, K_MOUSE2, qfalse, 0, NULL );
+ break;
+
+ case DIMOFS_BUTTON2:
+ if (od.dwData & 0x80)
+ Sys_QueEvent( od.dwTimeStamp, SE_KEY, K_MOUSE3, qtrue, 0, NULL );
+ else
+ Sys_QueEvent( od.dwTimeStamp, SE_KEY, K_MOUSE3, qfalse, 0, NULL );
+ break;
+
+ case DIMOFS_BUTTON3:
+ if (od.dwData & 0x80)
+ Sys_QueEvent( od.dwTimeStamp, SE_KEY, K_MOUSE4, qtrue, 0, NULL );
+ else
+ Sys_QueEvent( od.dwTimeStamp, SE_KEY, K_MOUSE4, qfalse, 0, NULL );
+ break;
+ // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=50
+ case DIMOFS_Z:
+ value = od.dwData;
+ if (value == 0) {
+
+ } else if (value < 0) {
+ Sys_QueEvent( od.dwTimeStamp, SE_KEY, K_MWHEELDOWN, qtrue, 0, NULL );
+ Sys_QueEvent( od.dwTimeStamp, SE_KEY, K_MWHEELDOWN, qfalse, 0, NULL );
+ } else {
+ Sys_QueEvent( od.dwTimeStamp, SE_KEY, K_MWHEELUP, qtrue, 0, NULL );
+ Sys_QueEvent( od.dwTimeStamp, SE_KEY, K_MWHEELUP, qfalse, 0, NULL );
+ }
+ break;
+ }
+ }
+
+ // read the raw delta counter and ignore
+ // the individual sample time / values
+ hr = IDirectInputDevice_GetDeviceState(g_pMouse,
+ sizeof(DIDEVICEOBJECTDATA), &state);
+ if ( FAILED(hr) ) {
+ *mx = *my = 0;
+ return;
+ }
+ *mx = state.lX;
+ *my = state.lY;
+}
+
+/*
+============================================================
+
+ MOUSE CONTROL
+
+============================================================
+*/
+
+/*
+===========
+IN_ActivateMouse
+
+Called when the window gains focus or changes in some way
+===========
+*/
+void IN_ActivateMouse( void )
+{
+ if (!s_wmv.mouseInitialized ) {
+ return;
+ }
+ if ( !in_mouse->integer )
+ {
+ s_wmv.mouseActive = qfalse;
+ return;
+ }
+ if ( s_wmv.mouseActive )
+ {
+ return;
+ }
+
+ s_wmv.mouseActive = qtrue;
+
+ if ( in_mouse->integer != -1 ) {
+ IN_ActivateDIMouse();
+ }
+ IN_ActivateWin32Mouse();
+}
+
+
+/*
+===========
+IN_DeactivateMouse
+
+Called when the window loses focus
+===========
+*/
+void IN_DeactivateMouse( void ) {
+ if (!s_wmv.mouseInitialized ) {
+ return;
+ }
+ if (!s_wmv.mouseActive ) {
+ return;
+ }
+ s_wmv.mouseActive = qfalse;
+
+ IN_DeactivateDIMouse();
+ IN_DeactivateWin32Mouse();
+}
+
+
+
+/*
+===========
+IN_StartupMouse
+===========
+*/
+void IN_StartupMouse( void )
+{
+ s_wmv.mouseInitialized = qfalse;
+ s_wmv.mouseStartupDelayed = qfalse;
+
+ if ( in_mouse->integer == 0 ) {
+ Com_Printf ("Mouse control not active.\n");
+ return;
+ }
+
+ // nt4.0 direct input is screwed up
+ if ( ( g_wv.osversion.dwPlatformId == VER_PLATFORM_WIN32_NT ) &&
+ ( g_wv.osversion.dwMajorVersion == 4 ) )
+ {
+ Com_Printf ("Disallowing DirectInput on NT 4.0\n");
+ Cvar_Set( "in_mouse", "-1" );
+ }
+
+ if ( in_mouse->integer == -1 ) {
+ Com_Printf ("Skipping check for DirectInput\n");
+ } else {
+ if (!g_wv.hWnd)
+ {
+ Com_Printf ("No window for DirectInput mouse init, delaying\n");
+ s_wmv.mouseStartupDelayed = qtrue;
+ return;
+ }
+ if ( IN_InitDIMouse() ) {
+ s_wmv.mouseInitialized = qtrue;
+ return;
+ }
+ Com_Printf ("Falling back to Win32 mouse support...\n");
+ }
+ s_wmv.mouseInitialized = qtrue;
+ IN_InitWin32Mouse();
+}
+
+/*
+===========
+IN_MouseEvent
+===========
+*/
+void IN_MouseEvent (int mstate)
+{
+ int i;
+
+ if ( !s_wmv.mouseInitialized )
+ return;
+
+// perform button actions
+ for (i = 0 ; i < 3 ; i++ )
+ {
+ if ( (mstate & (1<<i)) &&
+ !(s_wmv.oldButtonState & (1<<i)) )
+ {
+ Sys_QueEvent( g_wv.sysMsgTime, SE_KEY, K_MOUSE1 + i, qtrue, 0, NULL );
+ }
+
+ if ( !(mstate & (1<<i)) &&
+ (s_wmv.oldButtonState & (1<<i)) )
+ {
+ Sys_QueEvent( g_wv.sysMsgTime, SE_KEY, K_MOUSE1 + i, qfalse, 0, NULL );
+ }
+ }
+
+ s_wmv.oldButtonState = mstate;
+}
+
+
+/*
+===========
+IN_MouseMove
+===========
+*/
+void IN_MouseMove ( void ) {
+ int mx, my;
+
+ if ( g_pMouse ) {
+ IN_DIMouse( &mx, &my );
+ } else {
+ IN_Win32Mouse( &mx, &my );
+ }
+
+ if ( !mx && !my ) {
+ return;
+ }
+
+ Sys_QueEvent( 0, SE_MOUSE, mx, my, 0, NULL );
+}
+
+
+/*
+=========================================================================
+
+=========================================================================
+*/
+
+/*
+===========
+IN_Startup
+===========
+*/
+void IN_Startup( void ) {
+ Com_Printf ("\n------- Input Initialization -------\n");
+ IN_StartupMouse ();
+ IN_StartupJoystick ();
+ IN_StartupMIDI();
+ Com_Printf ("------------------------------------\n");
+
+ in_mouse->modified = qfalse;
+ in_joystick->modified = qfalse;
+}
+
+/*
+===========
+IN_Shutdown
+===========
+*/
+void IN_Shutdown( void ) {
+ IN_DeactivateMouse();
+ IN_ShutdownDIMouse();
+ IN_ShutdownMIDI();
+ Cmd_RemoveCommand("midiinfo" );
+}
+
+
+/*
+===========
+IN_Init
+===========
+*/
+void IN_Init( void ) {
+ // MIDI input controler variables
+ in_midi = Cvar_Get ("in_midi", "0", CVAR_ARCHIVE);
+ in_midiport = Cvar_Get ("in_midiport", "1", CVAR_ARCHIVE);
+ in_midichannel = Cvar_Get ("in_midichannel", "1", CVAR_ARCHIVE);
+ in_mididevice = Cvar_Get ("in_mididevice", "0", CVAR_ARCHIVE);
+
+ Cmd_AddCommand( "midiinfo", MidiInfo_f );
+
+ // mouse variables
+ in_mouse = Cvar_Get ("in_mouse", "1", CVAR_ARCHIVE|CVAR_LATCH);
+ in_logitechbug = Cvar_Get ("in_logitechbug", "0", CVAR_ARCHIVE);
+
+ // joystick variables
+ in_joystick = Cvar_Get ("in_joystick", "0", CVAR_ARCHIVE|CVAR_LATCH);
+ in_joyBallScale = Cvar_Get ("in_joyBallScale", "0.02", CVAR_ARCHIVE);
+ in_debugJoystick = Cvar_Get ("in_debugjoystick", "0", CVAR_TEMP);
+
+ joy_threshold = Cvar_Get ("joy_threshold", "0.15", CVAR_ARCHIVE);
+
+ IN_Startup();
+}
+
+
+/*
+===========
+IN_Activate
+
+Called when the main window gains or loses focus.
+The window may have been destroyed and recreated
+between a deactivate and an activate.
+===========
+*/
+void IN_Activate (qboolean active) {
+ in_appactive = active;
+
+ if ( !active )
+ {
+ IN_DeactivateMouse();
+ }
+}
+
+
+/*
+==================
+IN_Frame
+
+Called every frame, even if not generating commands
+==================
+*/
+void IN_Frame (void) {
+ // post joystick events
+ IN_JoyMove();
+
+ if ( !s_wmv.mouseInitialized ) {
+ if (s_wmv.mouseStartupDelayed && g_wv.hWnd)
+ {
+ Com_Printf("Proceeding with delayed mouse init\n");
+ IN_StartupMouse();
+ s_wmv.mouseStartupDelayed = qfalse;
+ }
+ return;
+ }
+
+ if ( cls.keyCatchers & KEYCATCH_CONSOLE ) {
+ // temporarily deactivate if not in the game and
+ // running on the desktop
+ // voodoo always counts as full screen
+ if (Cvar_VariableValue ("r_fullscreen") == 0
+ && strcmp( Cvar_VariableString("r_glDriver"), _3DFX_DRIVER_NAME) ) {
+ IN_DeactivateMouse ();
+ return;
+ }
+ }
+
+ if ( !in_appactive ) {
+ IN_DeactivateMouse ();
+ return;
+ }
+
+ IN_ActivateMouse();
+
+ // post events to the system que
+ IN_MouseMove();
+
+}
+
+
+/*
+===================
+IN_ClearStates
+===================
+*/
+void IN_ClearStates (void)
+{
+ s_wmv.oldButtonState = 0;
+}
+
+
+/*
+=========================================================================
+
+JOYSTICK
+
+=========================================================================
+*/
+
+/*
+===============
+IN_StartupJoystick
+===============
+*/
+void IN_StartupJoystick (void) {
+ int numdevs;
+ MMRESULT mmr;
+
+ // assume no joystick
+ joy.avail = qfalse;
+
+ if (! in_joystick->integer ) {
+ Com_Printf ("Joystick is not active.\n");
+ return;
+ }
+
+ // verify joystick driver is present
+ if ((numdevs = joyGetNumDevs ()) == 0)
+ {
+ Com_Printf ("joystick not found -- driver not present\n");
+ return;
+ }
+
+ // cycle through the joystick ids for the first valid one
+ mmr = 0;
+ for (joy.id=0 ; joy.id<numdevs ; joy.id++)
+ {
+ Com_Memset (&joy.ji, 0, sizeof(joy.ji));
+ joy.ji.dwSize = sizeof(joy.ji);
+ joy.ji.dwFlags = JOY_RETURNCENTERED;
+
+ if ((mmr = joyGetPosEx (joy.id, &joy.ji)) == JOYERR_NOERROR)
+ break;
+ }
+
+ // abort startup if we didn't find a valid joystick
+ if (mmr != JOYERR_NOERROR)
+ {
+ Com_Printf ("joystick not found -- no valid joysticks (%x)\n", mmr);
+ return;
+ }
+
+ // get the capabilities of the selected joystick
+ // abort startup if command fails
+ Com_Memset (&joy.jc, 0, sizeof(joy.jc));
+ if ((mmr = joyGetDevCaps (joy.id, &joy.jc, sizeof(joy.jc))) != JOYERR_NOERROR)
+ {
+ Com_Printf ("joystick not found -- invalid joystick capabilities (%x)\n", mmr);
+ return;
+ }
+
+ Com_Printf( "Joystick found.\n" );
+ Com_Printf( "Pname: %s\n", joy.jc.szPname );
+ Com_Printf( "OemVxD: %s\n", joy.jc.szOEMVxD );
+ Com_Printf( "RegKey: %s\n", joy.jc.szRegKey );
+
+ Com_Printf( "Numbuttons: %i / %i\n", joy.jc.wNumButtons, joy.jc.wMaxButtons );
+ Com_Printf( "Axis: %i / %i\n", joy.jc.wNumAxes, joy.jc.wMaxAxes );
+ Com_Printf( "Caps: 0x%x\n", joy.jc.wCaps );
+ if ( joy.jc.wCaps & JOYCAPS_HASPOV ) {
+ Com_Printf( "HASPOV\n" );
+ } else {
+ Com_Printf( "no POV\n" );
+ }
+
+ // old button and POV states default to no buttons pressed
+ joy.oldbuttonstate = 0;
+ joy.oldpovstate = 0;
+
+ // mark the joystick as available
+ joy.avail = qtrue;
+}
+
+/*
+===========
+JoyToF
+===========
+*/
+float JoyToF( int value ) {
+ float fValue;
+
+ // move centerpoint to zero
+ value -= 32768;
+
+ // convert range from -32768..32767 to -1..1
+ fValue = (float)value / 32768.0;
+
+ if ( fValue < -1 ) {
+ fValue = -1;
+ }
+ if ( fValue > 1 ) {
+ fValue = 1;
+ }
+ return fValue;
+}
+
+int JoyToI( int value ) {
+ // move centerpoint to zero
+ value -= 32768;
+
+ return value;
+}
+
+int joyDirectionKeys[16] = {
+ K_LEFTARROW, K_RIGHTARROW,
+ K_UPARROW, K_DOWNARROW,
+ K_JOY16, K_JOY17,
+ K_JOY18, K_JOY19,
+ K_JOY20, K_JOY21,
+ K_JOY22, K_JOY23,
+
+ K_JOY24, K_JOY25,
+ K_JOY26, K_JOY27
+};
+
+/*
+===========
+IN_JoyMove
+===========
+*/
+void IN_JoyMove( void ) {
+ float fAxisValue;
+ int i;
+ DWORD buttonstate, povstate;
+ int x, y;
+
+ // verify joystick is available and that the user wants to use it
+ if ( !joy.avail ) {
+ return;
+ }
+
+ // collect the joystick data, if possible
+ Com_Memset (&joy.ji, 0, sizeof(joy.ji));
+ joy.ji.dwSize = sizeof(joy.ji);
+ joy.ji.dwFlags = JOY_RETURNALL;
+
+ if ( joyGetPosEx (joy.id, &joy.ji) != JOYERR_NOERROR ) {
+ // read error occurred
+ // turning off the joystick seems too harsh for 1 read error,\
+ // but what should be done?
+ // Com_Printf ("IN_ReadJoystick: no response\n");
+ // joy.avail = false;
+ return;
+ }
+
+ if ( in_debugJoystick->integer ) {
+ Com_Printf( "%8x %5i %5.2f %5.2f %5.2f %5.2f %6i %6i\n",
+ joy.ji.dwButtons,
+ joy.ji.dwPOV,
+ JoyToF( joy.ji.dwXpos ), JoyToF( joy.ji.dwYpos ),
+ JoyToF( joy.ji.dwZpos ), JoyToF( joy.ji.dwRpos ),
+ JoyToI( joy.ji.dwUpos ), JoyToI( joy.ji.dwVpos ) );
+ }
+
+ // loop through the joystick buttons
+ // key a joystick event or auxillary event for higher number buttons for each state change
+ buttonstate = joy.ji.dwButtons;
+ for ( i=0 ; i < joy.jc.wNumButtons ; i++ ) {
+ if ( (buttonstate & (1<<i)) && !(joy.oldbuttonstate & (1<<i)) ) {
+ Sys_QueEvent( g_wv.sysMsgTime, SE_KEY, K_JOY1 + i, qtrue, 0, NULL );
+ }
+ if ( !(buttonstate & (1<<i)) && (joy.oldbuttonstate & (1<<i)) ) {
+ Sys_QueEvent( g_wv.sysMsgTime, SE_KEY, K_JOY1 + i, qfalse, 0, NULL );
+ }
+ }
+ joy.oldbuttonstate = buttonstate;
+
+ povstate = 0;
+
+ // convert main joystick motion into 6 direction button bits
+ for (i = 0; i < joy.jc.wNumAxes && i < 4 ; i++) {
+ // get the floating point zero-centered, potentially-inverted data for the current axis
+ fAxisValue = JoyToF( (&joy.ji.dwXpos)[i] );
+
+ if ( fAxisValue < -joy_threshold->value ) {
+ povstate |= (1<<(i*2));
+ } else if ( fAxisValue > joy_threshold->value ) {
+ povstate |= (1<<(i*2+1));
+ }
+ }
+
+ // convert POV information from a direction into 4 button bits
+ if ( joy.jc.wCaps & JOYCAPS_HASPOV ) {
+ if ( joy.ji.dwPOV != JOY_POVCENTERED ) {
+ if (joy.ji.dwPOV == JOY_POVFORWARD)
+ povstate |= 1<<12;
+ if (joy.ji.dwPOV == JOY_POVBACKWARD)
+ povstate |= 1<<13;
+ if (joy.ji.dwPOV == JOY_POVRIGHT)
+ povstate |= 1<<14;
+ if (joy.ji.dwPOV == JOY_POVLEFT)
+ povstate |= 1<<15;
+ }
+ }
+
+ // determine which bits have changed and key an auxillary event for each change
+ for (i=0 ; i < 16 ; i++) {
+ if ( (povstate & (1<<i)) && !(joy.oldpovstate & (1<<i)) ) {
+ Sys_QueEvent( g_wv.sysMsgTime, SE_KEY, joyDirectionKeys[i], qtrue, 0, NULL );
+ }
+
+ if ( !(povstate & (1<<i)) && (joy.oldpovstate & (1<<i)) ) {
+ Sys_QueEvent( g_wv.sysMsgTime, SE_KEY, joyDirectionKeys[i], qfalse, 0, NULL );
+ }
+ }
+ joy.oldpovstate = povstate;
+
+ // if there is a trackball like interface, simulate mouse moves
+ if ( joy.jc.wNumAxes >= 6 ) {
+ x = JoyToI( joy.ji.dwUpos ) * in_joyBallScale->value;
+ y = JoyToI( joy.ji.dwVpos ) * in_joyBallScale->value;
+ if ( x || y ) {
+ Sys_QueEvent( g_wv.sysMsgTime, SE_MOUSE, x, y, 0, NULL );
+ }
+ }
+}
+
+/*
+=========================================================================
+
+MIDI
+
+=========================================================================
+*/
+
+static void MIDI_NoteOff( int note )
+{
+ int qkey;
+
+ qkey = note - 60 + K_AUX1;
+
+ if ( qkey > 255 || qkey < K_AUX1 )
+ return;
+
+ Sys_QueEvent( g_wv.sysMsgTime, SE_KEY, qkey, qfalse, 0, NULL );
+}
+
+static void MIDI_NoteOn( int note, int velocity )
+{
+ int qkey;
+
+ if ( velocity == 0 )
+ MIDI_NoteOff( note );
+
+ qkey = note - 60 + K_AUX1;
+
+ if ( qkey > 255 || qkey < K_AUX1 )
+ return;
+
+ Sys_QueEvent( g_wv.sysMsgTime, SE_KEY, qkey, qtrue, 0, NULL );
+}
+
+static void CALLBACK MidiInProc( HMIDIIN hMidiIn, UINT uMsg, DWORD dwInstance,
+ DWORD dwParam1, DWORD dwParam2 )
+{
+ int message;
+
+ switch ( uMsg )
+ {
+ case MIM_OPEN:
+ break;
+ case MIM_CLOSE:
+ break;
+ case MIM_DATA:
+ message = dwParam1 & 0xff;
+
+ // note on
+ if ( ( message & 0xf0 ) == 0x90 )
+ {
+ if ( ( ( message & 0x0f ) + 1 ) == in_midichannel->integer )
+ MIDI_NoteOn( ( dwParam1 & 0xff00 ) >> 8, ( dwParam1 & 0xff0000 ) >> 16 );
+ }
+ else if ( ( message & 0xf0 ) == 0x80 )
+ {
+ if ( ( ( message & 0x0f ) + 1 ) == in_midichannel->integer )
+ MIDI_NoteOff( ( dwParam1 & 0xff00 ) >> 8 );
+ }
+ break;
+ case MIM_LONGDATA:
+ break;
+ case MIM_ERROR:
+ break;
+ case MIM_LONGERROR:
+ break;
+ }
+
+// Sys_QueEvent( sys_msg_time, SE_KEY, wMsg, qtrue, 0, NULL );
+}
+
+static void MidiInfo_f( void )
+{
+ int i;
+
+ const char *enableStrings[] = { "disabled", "enabled" };
+
+ Com_Printf( "\nMIDI control: %s\n", enableStrings[in_midi->integer != 0] );
+ Com_Printf( "port: %d\n", in_midiport->integer );
+ Com_Printf( "channel: %d\n", in_midichannel->integer );
+ Com_Printf( "current device: %d\n", in_mididevice->integer );
+ Com_Printf( "number of devices: %d\n", s_midiInfo.numDevices );
+ for ( i = 0; i < s_midiInfo.numDevices; i++ )
+ {
+ if ( i == Cvar_VariableValue( "in_mididevice" ) )
+ Com_Printf( "***" );
+ else
+ Com_Printf( "..." );
+ Com_Printf( "device %2d: %s\n", i, s_midiInfo.caps[i].szPname );
+ Com_Printf( "...manufacturer ID: 0x%hx\n", s_midiInfo.caps[i].wMid );
+ Com_Printf( "...product ID: 0x%hx\n", s_midiInfo.caps[i].wPid );
+
+ Com_Printf( "\n" );
+ }
+}
+
+static void IN_StartupMIDI( void )
+{
+ int i;
+
+ if ( !Cvar_VariableValue( "in_midi" ) )
+ return;
+
+ //
+ // enumerate MIDI IN devices
+ //
+ s_midiInfo.numDevices = midiInGetNumDevs();
+
+ for ( i = 0; i < s_midiInfo.numDevices; i++ )
+ {
+ midiInGetDevCaps( i, &s_midiInfo.caps[i], sizeof( s_midiInfo.caps[i] ) );
+ }
+
+ //
+ // open the MIDI IN port
+ //
+ if ( midiInOpen( &s_midiInfo.hMidiIn,
+ in_mididevice->integer,
+ ( unsigned long ) MidiInProc,
+ ( unsigned long ) NULL,
+ CALLBACK_FUNCTION ) != MMSYSERR_NOERROR )
+ {
+ Com_Printf( "WARNING: could not open MIDI device %d: '%s'\n", in_mididevice->integer , s_midiInfo.caps[( int ) in_mididevice->value] );
+ return;
+ }
+
+ midiInStart( s_midiInfo.hMidiIn );
+}
+
+static void IN_ShutdownMIDI( void )
+{
+ if ( s_midiInfo.hMidiIn )
+ {
+ midiInClose( s_midiInfo.hMidiIn );
+ }
+ Com_Memset( &s_midiInfo, 0, sizeof( s_midiInfo ) );
+}
+
diff --git a/code/win32/win_local.h b/code/win32/win_local.h
new file mode 100755
index 0000000..0ac78cf
--- /dev/null
+++ b/code/win32/win_local.h
@@ -0,0 +1,95 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// win_local.h: Win32-specific Quake3 header file
+
+#if defined (_MSC_VER) && (_MSC_VER >= 1200)
+#pragma warning(disable : 4201)
+#pragma warning( push )
+#endif
+#include <windows.h>
+#if defined (_MSC_VER) && (_MSC_VER >= 1200)
+#pragma warning( pop )
+#endif
+
+#define DIRECTSOUND_VERSION 0x0300
+#define DIRECTINPUT_VERSION 0x0300
+
+#include <dinput.h>
+#include <dsound.h>
+#include <winsock.h>
+#include <wsipx.h>
+
+void IN_MouseEvent (int mstate);
+
+void Sys_QueEvent( int time, sysEventType_t type, int value, int value2, int ptrLength, void *ptr );
+
+void Sys_CreateConsole( void );
+void Sys_DestroyConsole( void );
+
+char *Sys_ConsoleInput (void);
+
+qboolean Sys_GetPacket ( netadr_t *net_from, msg_t *net_message );
+
+// Input subsystem
+
+void IN_Init (void);
+void IN_Shutdown (void);
+void IN_JoystickCommands (void);
+
+void IN_Move (usercmd_t *cmd);
+// add additional non keyboard / non mouse movement on top of the keyboard move cmd
+
+void IN_DeactivateWin32Mouse( void);
+
+void IN_Activate (qboolean active);
+void IN_Frame (void);
+
+// window procedure
+LONG WINAPI MainWndProc (
+ HWND hWnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam);
+
+void Conbuf_AppendText( const char *msg );
+
+void SNDDMA_Activate( void );
+int SNDDMA_InitDS ();
+
+typedef struct
+{
+
+ HINSTANCE reflib_library; // Handle to refresh DLL
+ qboolean reflib_active;
+
+ HWND hWnd;
+ HINSTANCE hInstance;
+ qboolean activeApp;
+ qboolean isMinimized;
+ OSVERSIONINFO osversion;
+
+ // when we get a windows message, we store the time off so keyboard processing
+ // can know the exact time of an event
+ unsigned sysMsgTime;
+} WinVars_t;
+
+extern WinVars_t g_wv;
diff --git a/code/win32/win_main.c b/code/win32/win_main.c
new file mode 100755
index 0000000..55c0cea
--- /dev/null
+++ b/code/win32/win_main.c
@@ -0,0 +1,1253 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// win_main.c
+
+#include "../client/client.h"
+#include "../qcommon/qcommon.h"
+#include "win_local.h"
+#include "resource.h"
+#include <errno.h>
+#include <float.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <direct.h>
+#include <io.h>
+#include <conio.h>
+
+#define CD_BASEDIR "quake3"
+#define CD_EXE "quake3.exe"
+#define CD_BASEDIR_LINUX "bin\\x86\\glibc-2.1"
+#define CD_EXE_LINUX "quake3"
+#define MEM_THRESHOLD 96*1024*1024
+
+static char sys_cmdline[MAX_STRING_CHARS];
+
+// define this to use alternate spanking method
+// I found out that the regular way doesn't work on my box for some reason
+// see the associated spank.sh script
+#define ALT_SPANK
+#ifdef ALT_SPANK
+#include <stdio.h>
+#include <sys\stat.h>
+
+int fh = 0;
+
+void Spk_Open(char *name)
+{
+ fh = open( name, O_TRUNC | O_CREAT | O_WRONLY, S_IREAD | S_IWRITE );
+};
+
+void Spk_Close()
+{
+ if (!fh)
+ return;
+
+ close( fh );
+ fh = 0;
+}
+
+void Spk_Printf (const char *text, ...)
+{
+ va_list argptr;
+ char buf[32768];
+
+ if (!fh)
+ return;
+
+ va_start (argptr,text);
+ vsprintf (buf, text, argptr);
+ write(fh, buf, strlen(buf));
+ _commit(fh);
+ va_end (argptr);
+
+};
+#endif
+
+/*
+==================
+Sys_LowPhysicalMemory()
+==================
+*/
+
+qboolean Sys_LowPhysicalMemory() {
+ MEMORYSTATUS stat;
+ GlobalMemoryStatus (&stat);
+ return (stat.dwTotalPhys <= MEM_THRESHOLD) ? qtrue : qfalse;
+}
+
+/*
+==================
+Sys_BeginProfiling
+==================
+*/
+void Sys_BeginProfiling( void ) {
+ // this is just used on the mac build
+}
+
+/*
+=============
+Sys_Error
+
+Show the early console as an error dialog
+=============
+*/
+void QDECL Sys_Error( const char *error, ... ) {
+ va_list argptr;
+ char text[4096];
+ MSG msg;
+
+ va_start (argptr, error);
+ vsprintf (text, error, argptr);
+ va_end (argptr);
+
+ Conbuf_AppendText( text );
+ Conbuf_AppendText( "\n" );
+
+ Sys_SetErrorText( text );
+ Sys_ShowConsole( 1, qtrue );
+
+ timeEndPeriod( 1 );
+
+ IN_Shutdown();
+
+ // wait for the user to quit
+ while ( 1 ) {
+ if (!GetMessage (&msg, NULL, 0, 0))
+ Com_Quit_f ();
+ TranslateMessage (&msg);
+ DispatchMessage (&msg);
+ }
+
+ Sys_DestroyConsole();
+
+ exit (1);
+}
+
+/*
+==============
+Sys_Quit
+==============
+*/
+void Sys_Quit( void ) {
+ timeEndPeriod( 1 );
+ IN_Shutdown();
+ Sys_DestroyConsole();
+
+ exit (0);
+}
+
+/*
+==============
+Sys_Print
+==============
+*/
+void Sys_Print( const char *msg ) {
+ Conbuf_AppendText( msg );
+}
+
+
+/*
+==============
+Sys_Mkdir
+==============
+*/
+void Sys_Mkdir( const char *path ) {
+ _mkdir (path);
+}
+
+/*
+==============
+Sys_Cwd
+==============
+*/
+char *Sys_Cwd( void ) {
+ static char cwd[MAX_OSPATH];
+
+ _getcwd( cwd, sizeof( cwd ) - 1 );
+ cwd[MAX_OSPATH-1] = 0;
+
+ return cwd;
+}
+
+/*
+==============
+Sys_DefaultCDPath
+==============
+*/
+char *Sys_DefaultCDPath( void ) {
+ return "";
+}
+
+/*
+==============
+Sys_DefaultBasePath
+==============
+*/
+char *Sys_DefaultBasePath( void ) {
+ return Sys_Cwd();
+}
+
+/*
+==============================================================
+
+DIRECTORY SCANNING
+
+==============================================================
+*/
+
+#define MAX_FOUND_FILES 0x1000
+
+void Sys_ListFilteredFiles( const char *basedir, char *subdirs, char *filter, char **list, int *numfiles ) {
+ char search[MAX_OSPATH], newsubdirs[MAX_OSPATH];
+ char filename[MAX_OSPATH];
+ int findhandle;
+ struct _finddata_t findinfo;
+
+ if ( *numfiles >= MAX_FOUND_FILES - 1 ) {
+ return;
+ }
+
+ if (strlen(subdirs)) {
+ Com_sprintf( search, sizeof(search), "%s\\%s\\*", basedir, subdirs );
+ }
+ else {
+ Com_sprintf( search, sizeof(search), "%s\\*", basedir );
+ }
+
+ findhandle = _findfirst (search, &findinfo);
+ if (findhandle == -1) {
+ return;
+ }
+
+ do {
+ if (findinfo.attrib & _A_SUBDIR) {
+ if (Q_stricmp(findinfo.name, ".") && Q_stricmp(findinfo.name, "..")) {
+ if (strlen(subdirs)) {
+ Com_sprintf( newsubdirs, sizeof(newsubdirs), "%s\\%s", subdirs, findinfo.name);
+ }
+ else {
+ Com_sprintf( newsubdirs, sizeof(newsubdirs), "%s", findinfo.name);
+ }
+ Sys_ListFilteredFiles( basedir, newsubdirs, filter, list, numfiles );
+ }
+ }
+ if ( *numfiles >= MAX_FOUND_FILES - 1 ) {
+ break;
+ }
+ Com_sprintf( filename, sizeof(filename), "%s\\%s", subdirs, findinfo.name );
+ if (!Com_FilterPath( filter, filename, qfalse ))
+ continue;
+ list[ *numfiles ] = CopyString( filename );
+ (*numfiles)++;
+ } while ( _findnext (findhandle, &findinfo) != -1 );
+
+ _findclose (findhandle);
+}
+
+static qboolean strgtr(const char *s0, const char *s1) {
+ int l0, l1, i;
+
+ l0 = strlen(s0);
+ l1 = strlen(s1);
+
+ if (l1<l0) {
+ l0 = l1;
+ }
+
+ for(i=0;i<l0;i++) {
+ if (s1[i] > s0[i]) {
+ return qtrue;
+ }
+ if (s1[i] < s0[i]) {
+ return qfalse;
+ }
+ }
+ return qfalse;
+}
+
+char **Sys_ListFiles( const char *directory, const char *extension, char *filter, int *numfiles, qboolean wantsubs ) {
+ char search[MAX_OSPATH];
+ int nfiles;
+ char **listCopy;
+ char *list[MAX_FOUND_FILES];
+ struct _finddata_t findinfo;
+ int findhandle;
+ int flag;
+ int i;
+
+ if (filter) {
+
+ nfiles = 0;
+ Sys_ListFilteredFiles( directory, "", filter, list, &nfiles );
+
+ list[ nfiles ] = 0;
+ *numfiles = nfiles;
+
+ if (!nfiles)
+ return NULL;
+
+ listCopy = Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ) );
+ for ( i = 0 ; i < nfiles ; i++ ) {
+ listCopy[i] = list[i];
+ }
+ listCopy[i] = NULL;
+
+ return listCopy;
+ }
+
+ if ( !extension) {
+ extension = "";
+ }
+
+ // passing a slash as extension will find directories
+ if ( extension[0] == '/' && extension[1] == 0 ) {
+ extension = "";
+ flag = 0;
+ } else {
+ flag = _A_SUBDIR;
+ }
+
+ Com_sprintf( search, sizeof(search), "%s\\*%s", directory, extension );
+
+ // search
+ nfiles = 0;
+
+ findhandle = _findfirst (search, &findinfo);
+ if (findhandle == -1) {
+ *numfiles = 0;
+ return NULL;
+ }
+
+ do {
+ if ( (!wantsubs && flag ^ ( findinfo.attrib & _A_SUBDIR )) || (wantsubs && findinfo.attrib & _A_SUBDIR) ) {
+ if ( nfiles == MAX_FOUND_FILES - 1 ) {
+ break;
+ }
+ list[ nfiles ] = CopyString( findinfo.name );
+ nfiles++;
+ }
+ } while ( _findnext (findhandle, &findinfo) != -1 );
+
+ list[ nfiles ] = 0;
+
+ _findclose (findhandle);
+
+ // return a copy of the list
+ *numfiles = nfiles;
+
+ if ( !nfiles ) {
+ return NULL;
+ }
+
+ listCopy = Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ) );
+ for ( i = 0 ; i < nfiles ; i++ ) {
+ listCopy[i] = list[i];
+ }
+ listCopy[i] = NULL;
+
+ do {
+ flag = 0;
+ for(i=1; i<nfiles; i++) {
+ if (strgtr(listCopy[i-1], listCopy[i])) {
+ char *temp = listCopy[i];
+ listCopy[i] = listCopy[i-1];
+ listCopy[i-1] = temp;
+ flag = 1;
+ }
+ }
+ } while(flag);
+
+ return listCopy;
+}
+
+void Sys_FreeFileList( char **list ) {
+ int i;
+
+ if ( !list ) {
+ return;
+ }
+
+ for ( i = 0 ; list[i] ; i++ ) {
+ Z_Free( list[i] );
+ }
+
+ Z_Free( list );
+}
+
+//========================================================
+
+
+/*
+================
+Sys_ScanForCD
+
+Search all the drives to see if there is a valid CD to grab
+the cddir from
+================
+*/
+qboolean Sys_ScanForCD( void ) {
+ static char cddir[MAX_OSPATH];
+ char drive[4];
+ FILE *f;
+ char test[MAX_OSPATH];
+#if 0
+ // don't override a cdpath on the command line
+ if ( strstr( sys_cmdline, "cdpath" ) ) {
+ return;
+ }
+#endif
+
+ drive[0] = 'c';
+ drive[1] = ':';
+ drive[2] = '\\';
+ drive[3] = 0;
+
+ // scan the drives
+ for ( drive[0] = 'c' ; drive[0] <= 'z' ; drive[0]++ ) {
+ if ( GetDriveType (drive) != DRIVE_CDROM ) {
+ continue;
+ }
+
+ sprintf (cddir, "%s%s", drive, CD_BASEDIR);
+ sprintf (test, "%s\\%s", cddir, CD_EXE);
+ f = fopen( test, "r" );
+ if ( f ) {
+ fclose (f);
+ return qtrue;
+ } else {
+ sprintf(cddir, "%s%s", drive, CD_BASEDIR_LINUX);
+ sprintf(test, "%s\\%s", cddir, CD_EXE_LINUX);
+ f = fopen( test, "r" );
+ if ( f ) {
+ fclose (f);
+ return qtrue;
+ }
+ }
+ }
+
+ return qfalse;
+}
+
+/*
+================
+Sys_CheckCD
+
+Return true if the proper CD is in the drive
+================
+*/
+qboolean Sys_CheckCD( void ) {
+ // FIXME: mission pack
+ return qtrue;
+ //return Sys_ScanForCD();
+}
+
+
+/*
+================
+Sys_GetClipboardData
+
+================
+*/
+char *Sys_GetClipboardData( void ) {
+ char *data = NULL;
+ char *cliptext;
+
+ if ( OpenClipboard( NULL ) != 0 ) {
+ HANDLE hClipboardData;
+
+ if ( ( hClipboardData = GetClipboardData( CF_TEXT ) ) != 0 ) {
+ if ( ( cliptext = GlobalLock( hClipboardData ) ) != 0 ) {
+ data = Z_Malloc( GlobalSize( hClipboardData ) + 1 );
+ Q_strncpyz( data, cliptext, GlobalSize( hClipboardData ) );
+ GlobalUnlock( hClipboardData );
+
+ strtok( data, "\n\r\b" );
+ }
+ }
+ CloseClipboard();
+ }
+ return data;
+}
+
+
+/*
+========================================================================
+
+LOAD/UNLOAD DLL
+
+========================================================================
+*/
+
+/*
+=================
+Sys_UnloadDll
+
+=================
+*/
+void Sys_UnloadDll( void *dllHandle ) {
+ if ( !dllHandle ) {
+ return;
+ }
+ if ( !FreeLibrary( dllHandle ) ) {
+ Com_Error (ERR_FATAL, "Sys_UnloadDll FreeLibrary failed");
+ }
+}
+
+/*
+=================
+Sys_LoadDll
+
+Used to load a development dll instead of a virtual machine
+
+TTimo: added some verbosity in debug
+=================
+*/
+extern char *FS_BuildOSPath( const char *base, const char *game, const char *qpath );
+
+// fqpath param added 7/20/02 by T.Ray - Sys_LoadDll is only called in vm.c at this time
+// fqpath will be empty if dll not loaded, otherwise will hold fully qualified path of dll module loaded
+// fqpath buffersize must be at least MAX_QPATH+1 bytes long
+void * QDECL Sys_LoadDll( const char *name, char *fqpath , int (QDECL **entryPoint)(int, ...),
+ int (QDECL *systemcalls)(int, ...) ) {
+ static int lastWarning = 0;
+ HINSTANCE libHandle;
+ void (QDECL *dllEntry)( int (QDECL *syscallptr)(int, ...) );
+ char *basepath;
+ char *cdpath;
+ char *gamedir;
+ char *fn;
+#ifdef NDEBUG
+ int timestamp;
+ int ret;
+#endif
+ char filename[MAX_QPATH];
+
+ *fqpath = 0 ; // added 7/20/02 by T.Ray
+
+ Com_sprintf( filename, sizeof( filename ), "%sx86.dll", name );
+
+#ifdef NDEBUG
+ timestamp = Sys_Milliseconds();
+ if( ((timestamp - lastWarning) > (5 * 60000)) && !Cvar_VariableIntegerValue( "dedicated" )
+ && !Cvar_VariableIntegerValue( "com_blindlyLoadDLLs" ) ) {
+ if (FS_FileExists(filename)) {
+ lastWarning = timestamp;
+ ret = MessageBoxEx( NULL, "You are about to load a .DLL executable that\n"
+ "has not been verified for use with Quake III Arena.\n"
+ "This type of file can compromise the security of\n"
+ "your computer.\n\n"
+ "Select 'OK' if you choose to load it anyway.",
+ "Security Warning", MB_OKCANCEL | MB_ICONEXCLAMATION | MB_DEFBUTTON2 | MB_TOPMOST | MB_SETFOREGROUND,
+ MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ) );
+ if( ret != IDOK ) {
+ return NULL;
+ }
+ }
+ }
+#endif
+
+#ifndef NDEBUG
+ libHandle = LoadLibrary( filename );
+ if (libHandle)
+ Com_Printf("LoadLibrary '%s' ok\n", filename);
+ else
+ Com_Printf("LoadLibrary '%s' failed\n", filename);
+ if ( !libHandle ) {
+#endif
+ basepath = Cvar_VariableString( "fs_basepath" );
+ cdpath = Cvar_VariableString( "fs_cdpath" );
+ gamedir = Cvar_VariableString( "fs_game" );
+
+ fn = FS_BuildOSPath( basepath, gamedir, filename );
+ libHandle = LoadLibrary( fn );
+#ifndef NDEBUG
+ if (libHandle)
+ Com_Printf("LoadLibrary '%s' ok\n", fn);
+ else
+ Com_Printf("LoadLibrary '%s' failed\n", fn);
+#endif
+
+ if ( !libHandle ) {
+ if( cdpath[0] ) {
+ fn = FS_BuildOSPath( cdpath, gamedir, filename );
+ libHandle = LoadLibrary( fn );
+#ifndef NDEBUG
+ if (libHandle)
+ Com_Printf("LoadLibrary '%s' ok\n", fn);
+ else
+ Com_Printf("LoadLibrary '%s' failed\n", fn);
+#endif
+ }
+
+ if ( !libHandle ) {
+ return NULL;
+ }
+ }
+#ifndef NDEBUG
+ }
+#endif
+
+ dllEntry = ( void (QDECL *)( int (QDECL *)( int, ... ) ) )GetProcAddress( libHandle, "dllEntry" );
+ *entryPoint = (int (QDECL *)(int,...))GetProcAddress( libHandle, "vmMain" );
+ if ( !*entryPoint || !dllEntry ) {
+ FreeLibrary( libHandle );
+ return NULL;
+ }
+ dllEntry( systemcalls );
+
+ if ( libHandle ) Q_strncpyz ( fqpath , filename , MAX_QPATH ) ; // added 7/20/02 by T.Ray
+ return libHandle;
+}
+
+
+/*
+========================================================================
+
+BACKGROUND FILE STREAMING
+
+========================================================================
+*/
+
+#if 1
+
+void Sys_InitStreamThread( void ) {
+}
+
+void Sys_ShutdownStreamThread( void ) {
+}
+
+void Sys_BeginStreamedFile( fileHandle_t f, int readAhead ) {
+}
+
+void Sys_EndStreamedFile( fileHandle_t f ) {
+}
+
+int Sys_StreamedRead( void *buffer, int size, int count, fileHandle_t f ) {
+ return FS_Read( buffer, size * count, f );
+}
+
+void Sys_StreamSeek( fileHandle_t f, int offset, int origin ) {
+ FS_Seek( f, offset, origin );
+}
+
+
+#else
+
+typedef struct {
+ fileHandle_t file;
+ byte *buffer;
+ qboolean eof;
+ qboolean active;
+ int bufferSize;
+ int streamPosition; // next byte to be returned by Sys_StreamRead
+ int threadPosition; // next byte to be read from file
+} streamsIO_t;
+
+typedef struct {
+ HANDLE threadHandle;
+ int threadId;
+ CRITICAL_SECTION crit;
+ streamsIO_t sIO[MAX_FILE_HANDLES];
+} streamState_t;
+
+streamState_t stream;
+
+/*
+===============
+Sys_StreamThread
+
+A thread will be sitting in this loop forever
+================
+*/
+void Sys_StreamThread( void ) {
+ int buffer;
+ int count;
+ int readCount;
+ int bufferPoint;
+ int r, i;
+
+ while (1) {
+ Sleep( 10 );
+// EnterCriticalSection (&stream.crit);
+
+ for (i=1;i<MAX_FILE_HANDLES;i++) {
+ // if there is any space left in the buffer, fill it up
+ if ( stream.sIO[i].active && !stream.sIO[i].eof ) {
+ count = stream.sIO[i].bufferSize - (stream.sIO[i].threadPosition - stream.sIO[i].streamPosition);
+ if ( !count ) {
+ continue;
+ }
+
+ bufferPoint = stream.sIO[i].threadPosition % stream.sIO[i].bufferSize;
+ buffer = stream.sIO[i].bufferSize - bufferPoint;
+ readCount = buffer < count ? buffer : count;
+
+ r = FS_Read( stream.sIO[i].buffer + bufferPoint, readCount, stream.sIO[i].file );
+ stream.sIO[i].threadPosition += r;
+
+ if ( r != readCount ) {
+ stream.sIO[i].eof = qtrue;
+ }
+ }
+ }
+// LeaveCriticalSection (&stream.crit);
+ }
+}
+
+/*
+===============
+Sys_InitStreamThread
+
+================
+*/
+void Sys_InitStreamThread( void ) {
+ int i;
+
+ InitializeCriticalSection ( &stream.crit );
+
+ // don't leave the critical section until there is a
+ // valid file to stream, which will cause the StreamThread
+ // to sleep without any overhead
+// EnterCriticalSection( &stream.crit );
+
+ stream.threadHandle = CreateThread(
+ NULL, // LPSECURITY_ATTRIBUTES lpsa,
+ 0, // DWORD cbStack,
+ (LPTHREAD_START_ROUTINE)Sys_StreamThread, // LPTHREAD_START_ROUTINE lpStartAddr,
+ 0, // LPVOID lpvThreadParm,
+ 0, // DWORD fdwCreate,
+ &stream.threadId);
+ for(i=0;i<MAX_FILE_HANDLES;i++) {
+ stream.sIO[i].active = qfalse;
+ }
+}
+
+/*
+===============
+Sys_ShutdownStreamThread
+
+================
+*/
+void Sys_ShutdownStreamThread( void ) {
+}
+
+
+/*
+===============
+Sys_BeginStreamedFile
+
+================
+*/
+void Sys_BeginStreamedFile( fileHandle_t f, int readAhead ) {
+ if ( stream.sIO[f].file ) {
+ Sys_EndStreamedFile( stream.sIO[f].file );
+ }
+
+ stream.sIO[f].file = f;
+ stream.sIO[f].buffer = Z_Malloc( readAhead );
+ stream.sIO[f].bufferSize = readAhead;
+ stream.sIO[f].streamPosition = 0;
+ stream.sIO[f].threadPosition = 0;
+ stream.sIO[f].eof = qfalse;
+ stream.sIO[f].active = qtrue;
+
+ // let the thread start running
+// LeaveCriticalSection( &stream.crit );
+}
+
+/*
+===============
+Sys_EndStreamedFile
+
+================
+*/
+void Sys_EndStreamedFile( fileHandle_t f ) {
+ if ( f != stream.sIO[f].file ) {
+ Com_Error( ERR_FATAL, "Sys_EndStreamedFile: wrong file");
+ }
+ // don't leave critical section until another stream is started
+ EnterCriticalSection( &stream.crit );
+
+ stream.sIO[f].file = 0;
+ stream.sIO[f].active = qfalse;
+
+ Z_Free( stream.sIO[f].buffer );
+
+ LeaveCriticalSection( &stream.crit );
+}
+
+
+/*
+===============
+Sys_StreamedRead
+
+================
+*/
+int Sys_StreamedRead( void *buffer, int size, int count, fileHandle_t f ) {
+ int available;
+ int remaining;
+ int sleepCount;
+ int copy;
+ int bufferCount;
+ int bufferPoint;
+ byte *dest;
+
+ if (stream.sIO[f].active == qfalse) {
+ Com_Error( ERR_FATAL, "Streamed read with non-streaming file" );
+ }
+
+ dest = (byte *)buffer;
+ remaining = size * count;
+
+ if ( remaining <= 0 ) {
+ Com_Error( ERR_FATAL, "Streamed read with non-positive size" );
+ }
+
+ sleepCount = 0;
+ while ( remaining > 0 ) {
+ available = stream.sIO[f].threadPosition - stream.sIO[f].streamPosition;
+ if ( !available ) {
+ if ( stream.sIO[f].eof ) {
+ break;
+ }
+ if ( sleepCount == 1 ) {
+ Com_DPrintf( "Sys_StreamedRead: waiting\n" );
+ }
+ if ( ++sleepCount > 100 ) {
+ Com_Error( ERR_FATAL, "Sys_StreamedRead: thread has died");
+ }
+ Sleep( 10 );
+ continue;
+ }
+
+ EnterCriticalSection( &stream.crit );
+
+ bufferPoint = stream.sIO[f].streamPosition % stream.sIO[f].bufferSize;
+ bufferCount = stream.sIO[f].bufferSize - bufferPoint;
+
+ copy = available < bufferCount ? available : bufferCount;
+ if ( copy > remaining ) {
+ copy = remaining;
+ }
+ memcpy( dest, stream.sIO[f].buffer + bufferPoint, copy );
+ stream.sIO[f].streamPosition += copy;
+ dest += copy;
+ remaining -= copy;
+
+ LeaveCriticalSection( &stream.crit );
+ }
+
+ return (count * size - remaining) / size;
+}
+
+/*
+===============
+Sys_StreamSeek
+
+================
+*/
+void Sys_StreamSeek( fileHandle_t f, int offset, int origin ) {
+
+ // halt the thread
+ EnterCriticalSection( &stream.crit );
+
+ // clear to that point
+ FS_Seek( f, offset, origin );
+ stream.sIO[f].streamPosition = 0;
+ stream.sIO[f].threadPosition = 0;
+ stream.sIO[f].eof = qfalse;
+
+ // let the thread start running at the new position
+ LeaveCriticalSection( &stream.crit );
+}
+
+#endif
+
+/*
+========================================================================
+
+EVENT LOOP
+
+========================================================================
+*/
+
+#define MAX_QUED_EVENTS 256
+#define MASK_QUED_EVENTS ( MAX_QUED_EVENTS - 1 )
+
+sysEvent_t eventQue[MAX_QUED_EVENTS];
+int eventHead, eventTail;
+byte sys_packetReceived[MAX_MSGLEN];
+
+/*
+================
+Sys_QueEvent
+
+A time of 0 will get the current time
+Ptr should either be null, or point to a block of data that can
+be freed by the game later.
+================
+*/
+void Sys_QueEvent( int time, sysEventType_t type, int value, int value2, int ptrLength, void *ptr ) {
+ sysEvent_t *ev;
+
+ ev = &eventQue[ eventHead & MASK_QUED_EVENTS ];
+ if ( eventHead - eventTail >= MAX_QUED_EVENTS ) {
+ Com_Printf("Sys_QueEvent: overflow\n");
+ // we are discarding an event, but don't leak memory
+ if ( ev->evPtr ) {
+ Z_Free( ev->evPtr );
+ }
+ eventTail++;
+ }
+
+ eventHead++;
+
+ if ( time == 0 ) {
+ time = Sys_Milliseconds();
+ }
+
+ ev->evTime = time;
+ ev->evType = type;
+ ev->evValue = value;
+ ev->evValue2 = value2;
+ ev->evPtrLength = ptrLength;
+ ev->evPtr = ptr;
+}
+
+/*
+================
+Sys_GetEvent
+
+================
+*/
+sysEvent_t Sys_GetEvent( void ) {
+ MSG msg;
+ sysEvent_t ev;
+ char *s;
+ msg_t netmsg;
+ netadr_t adr;
+
+ // return if we have data
+ if ( eventHead > eventTail ) {
+ eventTail++;
+ return eventQue[ ( eventTail - 1 ) & MASK_QUED_EVENTS ];
+ }
+
+ // pump the message loop
+ while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)) {
+ if ( !GetMessage (&msg, NULL, 0, 0) ) {
+ Com_Quit_f();
+ }
+
+ // save the msg time, because wndprocs don't have access to the timestamp
+ g_wv.sysMsgTime = msg.time;
+
+ TranslateMessage (&msg);
+ DispatchMessage (&msg);
+ }
+
+ // check for console commands
+ s = Sys_ConsoleInput();
+ if ( s ) {
+ char *b;
+ int len;
+
+ len = strlen( s ) + 1;
+ b = Z_Malloc( len );
+ Q_strncpyz( b, s, len-1 );
+ Sys_QueEvent( 0, SE_CONSOLE, 0, 0, len, b );
+ }
+
+ // check for network packets
+ MSG_Init( &netmsg, sys_packetReceived, sizeof( sys_packetReceived ) );
+ if ( Sys_GetPacket ( &adr, &netmsg ) ) {
+ netadr_t *buf;
+ int len;
+
+ // copy out to a seperate buffer for qeueing
+ // the readcount stepahead is for SOCKS support
+ len = sizeof( netadr_t ) + netmsg.cursize - netmsg.readcount;
+ buf = Z_Malloc( len );
+ *buf = adr;
+ memcpy( buf+1, &netmsg.data[netmsg.readcount], netmsg.cursize - netmsg.readcount );
+ Sys_QueEvent( 0, SE_PACKET, 0, 0, len, buf );
+ }
+
+ // return if we have data
+ if ( eventHead > eventTail ) {
+ eventTail++;
+ return eventQue[ ( eventTail - 1 ) & MASK_QUED_EVENTS ];
+ }
+
+ // create an empty event to return
+
+ memset( &ev, 0, sizeof( ev ) );
+ ev.evTime = timeGetTime();
+
+ return ev;
+}
+
+//================================================================
+
+/*
+=================
+Sys_In_Restart_f
+
+Restart the input subsystem
+=================
+*/
+void Sys_In_Restart_f( void ) {
+ IN_Shutdown();
+ IN_Init();
+}
+
+
+/*
+=================
+Sys_Net_Restart_f
+
+Restart the network subsystem
+=================
+*/
+void Sys_Net_Restart_f( void ) {
+ NET_Restart();
+}
+
+
+/*
+================
+Sys_Init
+
+Called after the common systems (cvars, files, etc)
+are initialized
+================
+*/
+#define OSR2_BUILD_NUMBER 1111
+#define WIN98_BUILD_NUMBER 1998
+
+void Sys_Init( void ) {
+ int cpuid;
+
+ // make sure the timer is high precision, otherwise
+ // NT gets 18ms resolution
+ timeBeginPeriod( 1 );
+
+ Cmd_AddCommand ("in_restart", Sys_In_Restart_f);
+ Cmd_AddCommand ("net_restart", Sys_Net_Restart_f);
+
+ g_wv.osversion.dwOSVersionInfoSize = sizeof( g_wv.osversion );
+
+ if (!GetVersionEx (&g_wv.osversion))
+ Sys_Error ("Couldn't get OS info");
+
+ if (g_wv.osversion.dwMajorVersion < 4)
+ Sys_Error ("Quake3 requires Windows version 4 or greater");
+ if (g_wv.osversion.dwPlatformId == VER_PLATFORM_WIN32s)
+ Sys_Error ("Quake3 doesn't run on Win32s");
+
+ if ( g_wv.osversion.dwPlatformId == VER_PLATFORM_WIN32_NT )
+ {
+ Cvar_Set( "arch", "winnt" );
+ }
+ else if ( g_wv.osversion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS )
+ {
+ if ( LOWORD( g_wv.osversion.dwBuildNumber ) >= WIN98_BUILD_NUMBER )
+ {
+ Cvar_Set( "arch", "win98" );
+ }
+ else if ( LOWORD( g_wv.osversion.dwBuildNumber ) >= OSR2_BUILD_NUMBER )
+ {
+ Cvar_Set( "arch", "win95 osr2.x" );
+ }
+ else
+ {
+ Cvar_Set( "arch", "win95" );
+ }
+ }
+ else
+ {
+ Cvar_Set( "arch", "unknown Windows variant" );
+ }
+
+ // save out a couple things in rom cvars for the renderer to access
+ Cvar_Get( "win_hinstance", va("%i", (int)g_wv.hInstance), CVAR_ROM );
+ Cvar_Get( "win_wndproc", va("%i", (int)MainWndProc), CVAR_ROM );
+
+ //
+ // figure out our CPU
+ //
+ Cvar_Get( "sys_cpustring", "detect", 0 );
+ if ( !Q_stricmp( Cvar_VariableString( "sys_cpustring"), "detect" ) )
+ {
+ Com_Printf( "...detecting CPU, found " );
+
+ cpuid = Sys_GetProcessorId();
+
+ switch ( cpuid )
+ {
+ case CPUID_GENERIC:
+ Cvar_Set( "sys_cpustring", "generic" );
+ break;
+ case CPUID_INTEL_UNSUPPORTED:
+ Cvar_Set( "sys_cpustring", "x86 (pre-Pentium)" );
+ break;
+ case CPUID_INTEL_PENTIUM:
+ Cvar_Set( "sys_cpustring", "x86 (P5/PPro, non-MMX)" );
+ break;
+ case CPUID_INTEL_MMX:
+ Cvar_Set( "sys_cpustring", "x86 (P5/Pentium2, MMX)" );
+ break;
+ case CPUID_INTEL_KATMAI:
+ Cvar_Set( "sys_cpustring", "Intel Pentium III" );
+ break;
+ case CPUID_AMD_3DNOW:
+ Cvar_Set( "sys_cpustring", "AMD w/ 3DNow!" );
+ break;
+ case CPUID_AXP:
+ Cvar_Set( "sys_cpustring", "Alpha AXP" );
+ break;
+ default:
+ Com_Error( ERR_FATAL, "Unknown cpu type %d\n", cpuid );
+ break;
+ }
+ }
+ else
+ {
+ Com_Printf( "...forcing CPU type to " );
+ if ( !Q_stricmp( Cvar_VariableString( "sys_cpustring" ), "generic" ) )
+ {
+ cpuid = CPUID_GENERIC;
+ }
+ else if ( !Q_stricmp( Cvar_VariableString( "sys_cpustring" ), "x87" ) )
+ {
+ cpuid = CPUID_INTEL_PENTIUM;
+ }
+ else if ( !Q_stricmp( Cvar_VariableString( "sys_cpustring" ), "mmx" ) )
+ {
+ cpuid = CPUID_INTEL_MMX;
+ }
+ else if ( !Q_stricmp( Cvar_VariableString( "sys_cpustring" ), "3dnow" ) )
+ {
+ cpuid = CPUID_AMD_3DNOW;
+ }
+ else if ( !Q_stricmp( Cvar_VariableString( "sys_cpustring" ), "PentiumIII" ) )
+ {
+ cpuid = CPUID_INTEL_KATMAI;
+ }
+ else if ( !Q_stricmp( Cvar_VariableString( "sys_cpustring" ), "axp" ) )
+ {
+ cpuid = CPUID_AXP;
+ }
+ else
+ {
+ Com_Printf( "WARNING: unknown sys_cpustring '%s'\n", Cvar_VariableString( "sys_cpustring" ) );
+ cpuid = CPUID_GENERIC;
+ }
+ }
+ Cvar_SetValue( "sys_cpuid", cpuid );
+ Com_Printf( "%s\n", Cvar_VariableString( "sys_cpustring" ) );
+
+ Cvar_Set( "username", Sys_GetCurrentUser() );
+
+ IN_Init(); // FIXME: not in dedicated?
+}
+
+
+//=======================================================================
+
+int totalMsec, countMsec;
+
+/*
+==================
+WinMain
+
+==================
+*/
+int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
+ char cwd[MAX_OSPATH];
+ int startTime, endTime;
+
+ // should never get a previous instance in Win32
+ if ( hPrevInstance ) {
+ return 0;
+ }
+
+ g_wv.hInstance = hInstance;
+ Q_strncpyz( sys_cmdline, lpCmdLine, sizeof( sys_cmdline ) );
+
+ // done before Com/Sys_Init since we need this for error output
+ Sys_CreateConsole();
+
+ // no abort/retry/fail errors
+ SetErrorMode( SEM_FAILCRITICALERRORS );
+
+ // get the initial time base
+ Sys_Milliseconds();
+#if 0
+ // if we find the CD, add a +set cddir xxx command line
+ Sys_ScanForCD();
+#endif
+
+ Sys_InitStreamThread();
+
+ Com_Init( sys_cmdline );
+ NET_Init();
+
+ _getcwd (cwd, sizeof(cwd));
+ Com_Printf("Working directory: %s\n", cwd);
+
+ // hide the early console since we've reached the point where we
+ // have a working graphics subsystems
+ if ( !com_dedicated->integer && !com_viewlog->integer ) {
+ Sys_ShowConsole( 0, qfalse );
+ }
+
+ // main game loop
+ while( 1 ) {
+ // if not running as a game client, sleep a bit
+ if ( g_wv.isMinimized || ( com_dedicated && com_dedicated->integer ) ) {
+ Sleep( 5 );
+ }
+
+ // set low precision every frame, because some system calls
+ // reset it arbitrarily
+// _controlfp( _PC_24, _MCW_PC );
+// _controlfp( -1, _MCW_EM ); // no exceptions, even if some crappy
+ // syscall turns them back on!
+
+ startTime = Sys_Milliseconds();
+
+ // make sure mouse and joystick are only called once a frame
+ IN_Frame();
+
+ // run the game
+ Com_Frame();
+
+ endTime = Sys_Milliseconds();
+ totalMsec += endTime - startTime;
+ countMsec++;
+ }
+
+ // never gets here
+}
+
+
diff --git a/code/win32/win_net.c b/code/win32/win_net.c
new file mode 100755
index 0000000..c58ea21
--- /dev/null
+++ b/code/win32/win_net.c
@@ -0,0 +1,1031 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// net_wins.c
+
+#include "../game/q_shared.h"
+#include "../qcommon/qcommon.h"
+#include "win_local.h"
+
+static WSADATA winsockdata;
+static qboolean winsockInitialized = qfalse;
+static qboolean usingSocks = qfalse;
+static qboolean networkingEnabled = qfalse;
+
+static cvar_t *net_noudp;
+static cvar_t *net_noipx;
+
+static cvar_t *net_socksEnabled;
+static cvar_t *net_socksServer;
+static cvar_t *net_socksPort;
+static cvar_t *net_socksUsername;
+static cvar_t *net_socksPassword;
+static struct sockaddr socksRelayAddr;
+
+static SOCKET ip_socket;
+static SOCKET socks_socket;
+static SOCKET ipx_socket;
+
+#define MAX_IPS 16
+static int numIP;
+static byte localIP[MAX_IPS][4];
+
+//=============================================================================
+
+
+/*
+====================
+NET_ErrorString
+====================
+*/
+char *NET_ErrorString( void ) {
+ int code;
+
+ code = WSAGetLastError();
+ switch( code ) {
+ case WSAEINTR: return "WSAEINTR";
+ case WSAEBADF: return "WSAEBADF";
+ case WSAEACCES: return "WSAEACCES";
+ case WSAEDISCON: return "WSAEDISCON";
+ case WSAEFAULT: return "WSAEFAULT";
+ case WSAEINVAL: return "WSAEINVAL";
+ case WSAEMFILE: return "WSAEMFILE";
+ case WSAEWOULDBLOCK: return "WSAEWOULDBLOCK";
+ case WSAEINPROGRESS: return "WSAEINPROGRESS";
+ case WSAEALREADY: return "WSAEALREADY";
+ case WSAENOTSOCK: return "WSAENOTSOCK";
+ case WSAEDESTADDRREQ: return "WSAEDESTADDRREQ";
+ case WSAEMSGSIZE: return "WSAEMSGSIZE";
+ case WSAEPROTOTYPE: return "WSAEPROTOTYPE";
+ case WSAENOPROTOOPT: return "WSAENOPROTOOPT";
+ case WSAEPROTONOSUPPORT: return "WSAEPROTONOSUPPORT";
+ case WSAESOCKTNOSUPPORT: return "WSAESOCKTNOSUPPORT";
+ case WSAEOPNOTSUPP: return "WSAEOPNOTSUPP";
+ case WSAEPFNOSUPPORT: return "WSAEPFNOSUPPORT";
+ case WSAEAFNOSUPPORT: return "WSAEAFNOSUPPORT";
+ case WSAEADDRINUSE: return "WSAEADDRINUSE";
+ case WSAEADDRNOTAVAIL: return "WSAEADDRNOTAVAIL";
+ case WSAENETDOWN: return "WSAENETDOWN";
+ case WSAENETUNREACH: return "WSAENETUNREACH";
+ case WSAENETRESET: return "WSAENETRESET";
+ case WSAECONNABORTED: return "WSWSAECONNABORTEDAEINTR";
+ case WSAECONNRESET: return "WSAECONNRESET";
+ case WSAENOBUFS: return "WSAENOBUFS";
+ case WSAEISCONN: return "WSAEISCONN";
+ case WSAENOTCONN: return "WSAENOTCONN";
+ case WSAESHUTDOWN: return "WSAESHUTDOWN";
+ case WSAETOOMANYREFS: return "WSAETOOMANYREFS";
+ case WSAETIMEDOUT: return "WSAETIMEDOUT";
+ case WSAECONNREFUSED: return "WSAECONNREFUSED";
+ case WSAELOOP: return "WSAELOOP";
+ case WSAENAMETOOLONG: return "WSAENAMETOOLONG";
+ case WSAEHOSTDOWN: return "WSAEHOSTDOWN";
+ case WSASYSNOTREADY: return "WSASYSNOTREADY";
+ case WSAVERNOTSUPPORTED: return "WSAVERNOTSUPPORTED";
+ case WSANOTINITIALISED: return "WSANOTINITIALISED";
+ case WSAHOST_NOT_FOUND: return "WSAHOST_NOT_FOUND";
+ case WSATRY_AGAIN: return "WSATRY_AGAIN";
+ case WSANO_RECOVERY: return "WSANO_RECOVERY";
+ case WSANO_DATA: return "WSANO_DATA";
+ default: return "NO ERROR";
+ }
+}
+
+void NetadrToSockadr( netadr_t *a, struct sockaddr *s ) {
+ memset( s, 0, sizeof(*s) );
+
+ if( a->type == NA_BROADCAST ) {
+ ((struct sockaddr_in *)s)->sin_family = AF_INET;
+ ((struct sockaddr_in *)s)->sin_port = a->port;
+ ((struct sockaddr_in *)s)->sin_addr.s_addr = INADDR_BROADCAST;
+ }
+ else if( a->type == NA_IP ) {
+ ((struct sockaddr_in *)s)->sin_family = AF_INET;
+ ((struct sockaddr_in *)s)->sin_addr.s_addr = *(int *)&a->ip;
+ ((struct sockaddr_in *)s)->sin_port = a->port;
+ }
+ else if( a->type == NA_IPX ) {
+ ((struct sockaddr_ipx *)s)->sa_family = AF_IPX;
+ memcpy( ((struct sockaddr_ipx *)s)->sa_netnum, &a->ipx[0], 4 );
+ memcpy( ((struct sockaddr_ipx *)s)->sa_nodenum, &a->ipx[4], 6 );
+ ((struct sockaddr_ipx *)s)->sa_socket = a->port;
+ }
+ else if( a->type == NA_BROADCAST_IPX ) {
+ ((struct sockaddr_ipx *)s)->sa_family = AF_IPX;
+ memset( ((struct sockaddr_ipx *)s)->sa_netnum, 0, 4 );
+ memset( ((struct sockaddr_ipx *)s)->sa_nodenum, 0xff, 6 );
+ ((struct sockaddr_ipx *)s)->sa_socket = a->port;
+ }
+}
+
+
+void SockadrToNetadr( struct sockaddr *s, netadr_t *a ) {
+ if (s->sa_family == AF_INET) {
+ a->type = NA_IP;
+ *(int *)&a->ip = ((struct sockaddr_in *)s)->sin_addr.s_addr;
+ a->port = ((struct sockaddr_in *)s)->sin_port;
+ }
+ else if( s->sa_family == AF_IPX ) {
+ a->type = NA_IPX;
+ memcpy( &a->ipx[0], ((struct sockaddr_ipx *)s)->sa_netnum, 4 );
+ memcpy( &a->ipx[4], ((struct sockaddr_ipx *)s)->sa_nodenum, 6 );
+ a->port = ((struct sockaddr_ipx *)s)->sa_socket;
+ }
+}
+
+
+/*
+=============
+Sys_StringToAdr
+
+idnewt
+192.246.40.70
+12121212.121212121212
+=============
+*/
+#define DO(src,dest) \
+ copy[0] = s[src]; \
+ copy[1] = s[src + 1]; \
+ sscanf (copy, "%x", &val); \
+ ((struct sockaddr_ipx *)sadr)->dest = val
+
+qboolean Sys_StringToSockaddr( const char *s, struct sockaddr *sadr ) {
+ struct hostent *h;
+ int val;
+ char copy[MAX_STRING_CHARS];
+
+ memset( sadr, 0, sizeof( *sadr ) );
+
+ // check for an IPX address
+ if( ( strlen( s ) == 21 ) && ( s[8] == '.' ) ) {
+ ((struct sockaddr_ipx *)sadr)->sa_family = AF_IPX;
+ ((struct sockaddr_ipx *)sadr)->sa_socket = 0;
+ copy[2] = 0;
+ DO(0, sa_netnum[0]);
+ DO(2, sa_netnum[1]);
+ DO(4, sa_netnum[2]);
+ DO(6, sa_netnum[3]);
+ DO(9, sa_nodenum[0]);
+ DO(11, sa_nodenum[1]);
+ DO(13, sa_nodenum[2]);
+ DO(15, sa_nodenum[3]);
+ DO(17, sa_nodenum[4]);
+ DO(19, sa_nodenum[5]);
+ }
+ else {
+ ((struct sockaddr_in *)sadr)->sin_family = AF_INET;
+ ((struct sockaddr_in *)sadr)->sin_port = 0;
+
+ if( s[0] >= '0' && s[0] <= '9' ) {
+ *(int *)&((struct sockaddr_in *)sadr)->sin_addr = inet_addr(s);
+ } else {
+ if( ( h = gethostbyname( s ) ) == 0 ) {
+ return 0;
+ }
+ *(int *)&((struct sockaddr_in *)sadr)->sin_addr = *(int *)h->h_addr_list[0];
+ }
+ }
+
+ return qtrue;
+}
+
+#undef DO
+
+/*
+=============
+Sys_StringToAdr
+
+idnewt
+192.246.40.70
+=============
+*/
+qboolean Sys_StringToAdr( const char *s, netadr_t *a ) {
+ struct sockaddr sadr;
+
+ if ( !Sys_StringToSockaddr( s, &sadr ) ) {
+ return qfalse;
+ }
+
+ SockadrToNetadr( &sadr, a );
+ return qtrue;
+}
+
+//=============================================================================
+
+/*
+==================
+Sys_GetPacket
+
+Never called by the game logic, just the system event queing
+==================
+*/
+int recvfromCount;
+
+qboolean Sys_GetPacket( netadr_t *net_from, msg_t *net_message ) {
+ int ret;
+ struct sockaddr from;
+ int fromlen;
+ int net_socket;
+ int protocol;
+ int err;
+
+ for( protocol = 0 ; protocol < 2 ; protocol++ ) {
+ if( protocol == 0 ) {
+ net_socket = ip_socket;
+ }
+ else {
+ net_socket = ipx_socket;
+ }
+
+ if( !net_socket ) {
+ continue;
+ }
+
+ fromlen = sizeof(from);
+ recvfromCount++; // performance check
+ ret = recvfrom( net_socket, net_message->data, net_message->maxsize, 0, (struct sockaddr *)&from, &fromlen );
+ if (ret == SOCKET_ERROR)
+ {
+ err = WSAGetLastError();
+
+ if( err == WSAEWOULDBLOCK || err == WSAECONNRESET ) {
+ continue;
+ }
+ Com_Printf( "NET_GetPacket: %s\n", NET_ErrorString() );
+ continue;
+ }
+
+ if ( net_socket == ip_socket ) {
+ memset( ((struct sockaddr_in *)&from)->sin_zero, 0, 8 );
+ }
+
+ if ( usingSocks && net_socket == ip_socket && memcmp( &from, &socksRelayAddr, fromlen ) == 0 ) {
+ if ( ret < 10 || net_message->data[0] != 0 || net_message->data[1] != 0 || net_message->data[2] != 0 || net_message->data[3] != 1 ) {
+ continue;
+ }
+ net_from->type = NA_IP;
+ net_from->ip[0] = net_message->data[4];
+ net_from->ip[1] = net_message->data[5];
+ net_from->ip[2] = net_message->data[6];
+ net_from->ip[3] = net_message->data[7];
+ net_from->port = *(short *)&net_message->data[8];
+ net_message->readcount = 10;
+ }
+ else {
+ SockadrToNetadr( &from, net_from );
+ net_message->readcount = 0;
+ }
+
+ if( ret == net_message->maxsize ) {
+ Com_Printf( "Oversize packet from %s\n", NET_AdrToString (*net_from) );
+ continue;
+ }
+
+ net_message->cursize = ret;
+ return qtrue;
+ }
+
+ return qfalse;
+}
+
+//=============================================================================
+
+static char socksBuf[4096];
+
+/*
+==================
+Sys_SendPacket
+==================
+*/
+void Sys_SendPacket( int length, const void *data, netadr_t to ) {
+ int ret;
+ struct sockaddr addr;
+ SOCKET net_socket;
+
+ if( to.type == NA_BROADCAST ) {
+ net_socket = ip_socket;
+ }
+ else if( to.type == NA_IP ) {
+ net_socket = ip_socket;
+ }
+ else if( to.type == NA_IPX ) {
+ net_socket = ipx_socket;
+ }
+ else if( to.type == NA_BROADCAST_IPX ) {
+ net_socket = ipx_socket;
+ }
+ else {
+ Com_Error( ERR_FATAL, "Sys_SendPacket: bad address type" );
+ return;
+ }
+
+ if( !net_socket ) {
+ return;
+ }
+
+ NetadrToSockadr( &to, &addr );
+
+ if( usingSocks && to.type == NA_IP ) {
+ socksBuf[0] = 0; // reserved
+ socksBuf[1] = 0;
+ socksBuf[2] = 0; // fragment (not fragmented)
+ socksBuf[3] = 1; // address type: IPV4
+ *(int *)&socksBuf[4] = ((struct sockaddr_in *)&addr)->sin_addr.s_addr;
+ *(short *)&socksBuf[8] = ((struct sockaddr_in *)&addr)->sin_port;
+ memcpy( &socksBuf[10], data, length );
+ ret = sendto( net_socket, socksBuf, length+10, 0, &socksRelayAddr, sizeof(socksRelayAddr) );
+ }
+ else {
+ ret = sendto( net_socket, data, length, 0, &addr, sizeof(addr) );
+ }
+ if( ret == SOCKET_ERROR ) {
+ int err = WSAGetLastError();
+
+ // wouldblock is silent
+ if( err == WSAEWOULDBLOCK ) {
+ return;
+ }
+
+ // some PPP links do not allow broadcasts and return an error
+ if( ( err == WSAEADDRNOTAVAIL ) && ( ( to.type == NA_BROADCAST ) || ( to.type == NA_BROADCAST_IPX ) ) ) {
+ return;
+ }
+
+ Com_Printf( "NET_SendPacket: %s\n", NET_ErrorString() );
+ }
+}
+
+
+//=============================================================================
+
+/*
+==================
+Sys_IsLANAddress
+
+LAN clients will have their rate var ignored
+==================
+*/
+qboolean Sys_IsLANAddress( netadr_t adr ) {
+ int i;
+
+ if( adr.type == NA_LOOPBACK ) {
+ return qtrue;
+ }
+
+ if( adr.type == NA_IPX ) {
+ return qtrue;
+ }
+
+ if( adr.type != NA_IP ) {
+ return qfalse;
+ }
+
+ // choose which comparison to use based on the class of the address being tested
+ // any local adresses of a different class than the address being tested will fail based on the first byte
+
+ if( adr.ip[0] == 127 && adr.ip[1] == 0 && adr.ip[2] == 0 && adr.ip[3] == 1 ) {
+ return qtrue;
+ }
+
+ // Class A
+ if( (adr.ip[0] & 0x80) == 0x00 ) {
+ for ( i = 0 ; i < numIP ; i++ ) {
+ if( adr.ip[0] == localIP[i][0] ) {
+ return qtrue;
+ }
+ }
+ // the RFC1918 class a block will pass the above test
+ return qfalse;
+ }
+
+ // Class B
+ if( (adr.ip[0] & 0xc0) == 0x80 ) {
+ for ( i = 0 ; i < numIP ; i++ ) {
+ if( adr.ip[0] == localIP[i][0] && adr.ip[1] == localIP[i][1] ) {
+ return qtrue;
+ }
+ // also check against the RFC1918 class b blocks
+ if( adr.ip[0] == 172 && localIP[i][0] == 172 && (adr.ip[1] & 0xf0) == 16 && (localIP[i][1] & 0xf0) == 16 ) {
+ return qtrue;
+ }
+ }
+ return qfalse;
+ }
+
+ // Class C
+ for ( i = 0 ; i < numIP ; i++ ) {
+ if( adr.ip[0] == localIP[i][0] && adr.ip[1] == localIP[i][1] && adr.ip[2] == localIP[i][2] ) {
+ return qtrue;
+ }
+ // also check against the RFC1918 class c blocks
+ if( adr.ip[0] == 192 && localIP[i][0] == 192 && adr.ip[1] == 168 && localIP[i][1] == 168 ) {
+ return qtrue;
+ }
+ }
+ return qfalse;
+}
+
+/*
+==================
+Sys_ShowIP
+==================
+*/
+void Sys_ShowIP(void) {
+ int i;
+
+ for (i = 0; i < numIP; i++) {
+ Com_Printf( "IP: %i.%i.%i.%i\n", localIP[i][0], localIP[i][1], localIP[i][2], localIP[i][3] );
+ }
+}
+
+
+//=============================================================================
+
+
+/*
+====================
+NET_IPSocket
+====================
+*/
+int NET_IPSocket( char *net_interface, int port ) {
+ SOCKET newsocket;
+ struct sockaddr_in address;
+ qboolean _true = qtrue;
+ int i = 1;
+ int err;
+
+ if( net_interface ) {
+ Com_Printf( "Opening IP socket: %s:%i\n", net_interface, port );
+ }
+ else {
+ Com_Printf( "Opening IP socket: localhost:%i\n", port );
+ }
+
+ if( ( newsocket = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP ) ) == INVALID_SOCKET ) {
+ err = WSAGetLastError();
+ if( err != WSAEAFNOSUPPORT ) {
+ Com_Printf( "WARNING: UDP_OpenSocket: socket: %s\n", NET_ErrorString() );
+ }
+ return 0;
+ }
+
+ // make it non-blocking
+ if( ioctlsocket( newsocket, FIONBIO, &_true ) == SOCKET_ERROR ) {
+ Com_Printf( "WARNING: UDP_OpenSocket: ioctl FIONBIO: %s\n", NET_ErrorString() );
+ return 0;
+ }
+
+ // make it broadcast capable
+ if( setsockopt( newsocket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i) ) == SOCKET_ERROR ) {
+ Com_Printf( "WARNING: UDP_OpenSocket: setsockopt SO_BROADCAST: %s\n", NET_ErrorString() );
+ return 0;
+ }
+
+ if( !net_interface || !net_interface[0] || !Q_stricmp(net_interface, "localhost") ) {
+ address.sin_addr.s_addr = INADDR_ANY;
+ }
+ else {
+ Sys_StringToSockaddr( net_interface, (struct sockaddr *)&address );
+ }
+
+ if( port == PORT_ANY ) {
+ address.sin_port = 0;
+ }
+ else {
+ address.sin_port = htons( (short)port );
+ }
+
+ address.sin_family = AF_INET;
+
+ if( bind( newsocket, (void *)&address, sizeof(address) ) == SOCKET_ERROR ) {
+ Com_Printf( "WARNING: UDP_OpenSocket: bind: %s\n", NET_ErrorString() );
+ closesocket( newsocket );
+ return 0;
+ }
+
+ return newsocket;
+}
+
+
+/*
+====================
+NET_OpenSocks
+====================
+*/
+void NET_OpenSocks( int port ) {
+ struct sockaddr_in address;
+ int err;
+ struct hostent *h;
+ int len;
+ qboolean rfc1929;
+ unsigned char buf[64];
+
+ usingSocks = qfalse;
+
+ Com_Printf( "Opening connection to SOCKS server.\n" );
+
+ if ( ( socks_socket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP ) ) == INVALID_SOCKET ) {
+ err = WSAGetLastError();
+ Com_Printf( "WARNING: NET_OpenSocks: socket: %s\n", NET_ErrorString() );
+ return;
+ }
+
+ h = gethostbyname( net_socksServer->string );
+ if ( h == NULL ) {
+ err = WSAGetLastError();
+ Com_Printf( "WARNING: NET_OpenSocks: gethostbyname: %s\n", NET_ErrorString() );
+ return;
+ }
+ if ( h->h_addrtype != AF_INET ) {
+ Com_Printf( "WARNING: NET_OpenSocks: gethostbyname: address type was not AF_INET\n" );
+ return;
+ }
+ address.sin_family = AF_INET;
+ address.sin_addr.s_addr = *(int *)h->h_addr_list[0];
+ address.sin_port = htons( (short)net_socksPort->integer );
+
+ if ( connect( socks_socket, (struct sockaddr *)&address, sizeof( address ) ) == SOCKET_ERROR ) {
+ err = WSAGetLastError();
+ Com_Printf( "NET_OpenSocks: connect: %s\n", NET_ErrorString() );
+ return;
+ }
+
+ // send socks authentication handshake
+ if ( *net_socksUsername->string || *net_socksPassword->string ) {
+ rfc1929 = qtrue;
+ }
+ else {
+ rfc1929 = qfalse;
+ }
+
+ buf[0] = 5; // SOCKS version
+ // method count
+ if ( rfc1929 ) {
+ buf[1] = 2;
+ len = 4;
+ }
+ else {
+ buf[1] = 1;
+ len = 3;
+ }
+ buf[2] = 0; // method #1 - method id #00: no authentication
+ if ( rfc1929 ) {
+ buf[2] = 2; // method #2 - method id #02: username/password
+ }
+ if ( send( socks_socket, buf, len, 0 ) == SOCKET_ERROR ) {
+ err = WSAGetLastError();
+ Com_Printf( "NET_OpenSocks: send: %s\n", NET_ErrorString() );
+ return;
+ }
+
+ // get the response
+ len = recv( socks_socket, buf, 64, 0 );
+ if ( len == SOCKET_ERROR ) {
+ err = WSAGetLastError();
+ Com_Printf( "NET_OpenSocks: recv: %s\n", NET_ErrorString() );
+ return;
+ }
+ if ( len != 2 || buf[0] != 5 ) {
+ Com_Printf( "NET_OpenSocks: bad response\n" );
+ return;
+ }
+ switch( buf[1] ) {
+ case 0: // no authentication
+ break;
+ case 2: // username/password authentication
+ break;
+ default:
+ Com_Printf( "NET_OpenSocks: request denied\n" );
+ return;
+ }
+
+ // do username/password authentication if needed
+ if ( buf[1] == 2 ) {
+ int ulen;
+ int plen;
+
+ // build the request
+ ulen = strlen( net_socksUsername->string );
+ plen = strlen( net_socksPassword->string );
+
+ buf[0] = 1; // username/password authentication version
+ buf[1] = ulen;
+ if ( ulen ) {
+ memcpy( &buf[2], net_socksUsername->string, ulen );
+ }
+ buf[2 + ulen] = plen;
+ if ( plen ) {
+ memcpy( &buf[3 + ulen], net_socksPassword->string, plen );
+ }
+
+ // send it
+ if ( send( socks_socket, buf, 3 + ulen + plen, 0 ) == SOCKET_ERROR ) {
+ err = WSAGetLastError();
+ Com_Printf( "NET_OpenSocks: send: %s\n", NET_ErrorString() );
+ return;
+ }
+
+ // get the response
+ len = recv( socks_socket, buf, 64, 0 );
+ if ( len == SOCKET_ERROR ) {
+ err = WSAGetLastError();
+ Com_Printf( "NET_OpenSocks: recv: %s\n", NET_ErrorString() );
+ return;
+ }
+ if ( len != 2 || buf[0] != 1 ) {
+ Com_Printf( "NET_OpenSocks: bad response\n" );
+ return;
+ }
+ if ( buf[1] != 0 ) {
+ Com_Printf( "NET_OpenSocks: authentication failed\n" );
+ return;
+ }
+ }
+
+ // send the UDP associate request
+ buf[0] = 5; // SOCKS version
+ buf[1] = 3; // command: UDP associate
+ buf[2] = 0; // reserved
+ buf[3] = 1; // address type: IPV4
+ *(int *)&buf[4] = INADDR_ANY;
+ *(short *)&buf[8] = htons( (short)port ); // port
+ if ( send( socks_socket, buf, 10, 0 ) == SOCKET_ERROR ) {
+ err = WSAGetLastError();
+ Com_Printf( "NET_OpenSocks: send: %s\n", NET_ErrorString() );
+ return;
+ }
+
+ // get the response
+ len = recv( socks_socket, buf, 64, 0 );
+ if( len == SOCKET_ERROR ) {
+ err = WSAGetLastError();
+ Com_Printf( "NET_OpenSocks: recv: %s\n", NET_ErrorString() );
+ return;
+ }
+ if( len < 2 || buf[0] != 5 ) {
+ Com_Printf( "NET_OpenSocks: bad response\n" );
+ return;
+ }
+ // check completion code
+ if( buf[1] != 0 ) {
+ Com_Printf( "NET_OpenSocks: request denied: %i\n", buf[1] );
+ return;
+ }
+ if( buf[3] != 1 ) {
+ Com_Printf( "NET_OpenSocks: relay address is not IPV4: %i\n", buf[3] );
+ return;
+ }
+ ((struct sockaddr_in *)&socksRelayAddr)->sin_family = AF_INET;
+ ((struct sockaddr_in *)&socksRelayAddr)->sin_addr.s_addr = *(int *)&buf[4];
+ ((struct sockaddr_in *)&socksRelayAddr)->sin_port = *(short *)&buf[8];
+ memset( ((struct sockaddr_in *)&socksRelayAddr)->sin_zero, 0, 8 );
+
+ usingSocks = qtrue;
+}
+
+
+/*
+=====================
+NET_GetLocalAddress
+=====================
+*/
+void NET_GetLocalAddress( void ) {
+ char hostname[256];
+ struct hostent *hostInfo;
+ int error;
+ char *p;
+ int ip;
+ int n;
+
+ if( gethostname( hostname, 256 ) == SOCKET_ERROR ) {
+ error = WSAGetLastError();
+ return;
+ }
+
+ hostInfo = gethostbyname( hostname );
+ if( !hostInfo ) {
+ error = WSAGetLastError();
+ return;
+ }
+
+ Com_Printf( "Hostname: %s\n", hostInfo->h_name );
+ n = 0;
+ while( ( p = hostInfo->h_aliases[n++] ) != NULL ) {
+ Com_Printf( "Alias: %s\n", p );
+ }
+
+ if ( hostInfo->h_addrtype != AF_INET ) {
+ return;
+ }
+
+ numIP = 0;
+ while( ( p = hostInfo->h_addr_list[numIP] ) != NULL && numIP < MAX_IPS ) {
+ ip = ntohl( *(int *)p );
+ localIP[ numIP ][0] = p[0];
+ localIP[ numIP ][1] = p[1];
+ localIP[ numIP ][2] = p[2];
+ localIP[ numIP ][3] = p[3];
+ Com_Printf( "IP: %i.%i.%i.%i\n", ( ip >> 24 ) & 0xff, ( ip >> 16 ) & 0xff, ( ip >> 8 ) & 0xff, ip & 0xff );
+ numIP++;
+ }
+}
+
+/*
+====================
+NET_OpenIP
+====================
+*/
+void NET_OpenIP( void ) {
+ cvar_t *ip;
+ int port;
+ int i;
+
+ ip = Cvar_Get( "net_ip", "localhost", CVAR_LATCH );
+ port = Cvar_Get( "net_port", va( "%i", PORT_SERVER ), CVAR_LATCH )->integer;
+
+ // automatically scan for a valid port, so multiple
+ // dedicated servers can be started without requiring
+ // a different net_port for each one
+ for( i = 0 ; i < 10 ; i++ ) {
+ ip_socket = NET_IPSocket( ip->string, port + i );
+ if ( ip_socket ) {
+ Cvar_SetValue( "net_port", port + i );
+ if ( net_socksEnabled->integer ) {
+ NET_OpenSocks( port + i );
+ }
+ NET_GetLocalAddress();
+ return;
+ }
+ }
+ Com_Printf( "WARNING: Couldn't allocate IP port\n");
+}
+
+
+/*
+====================
+NET_IPXSocket
+====================
+*/
+int NET_IPXSocket( int port ) {
+ SOCKET newsocket;
+ struct sockaddr_ipx address;
+ int _true = 1;
+ int err;
+
+ if( ( newsocket = socket( AF_IPX, SOCK_DGRAM, NSPROTO_IPX ) ) == INVALID_SOCKET ) {
+ err = WSAGetLastError();
+ if (err != WSAEAFNOSUPPORT) {
+ Com_Printf( "WARNING: IPX_Socket: socket: %s\n", NET_ErrorString() );
+ }
+ return 0;
+ }
+
+ // make it non-blocking
+ if( ioctlsocket( newsocket, FIONBIO, &_true ) == SOCKET_ERROR ) {
+ Com_Printf( "WARNING: IPX_Socket: ioctl FIONBIO: %s\n", NET_ErrorString() );
+ return 0;
+ }
+
+ // make it broadcast capable
+ if( setsockopt( newsocket, SOL_SOCKET, SO_BROADCAST, (char *)&_true, sizeof( _true ) ) == SOCKET_ERROR ) {
+ Com_Printf( "WARNING: IPX_Socket: setsockopt SO_BROADCAST: %s\n", NET_ErrorString() );
+ return 0;
+ }
+
+ address.sa_family = AF_IPX;
+ memset( address.sa_netnum, 0, 4 );
+ memset( address.sa_nodenum, 0, 6 );
+ if( port == PORT_ANY ) {
+ address.sa_socket = 0;
+ }
+ else {
+ address.sa_socket = htons( (short)port );
+ }
+
+ if( bind( newsocket, (void *)&address, sizeof(address) ) == SOCKET_ERROR ) {
+ Com_Printf( "WARNING: IPX_Socket: bind: %s\n", NET_ErrorString() );
+ closesocket( newsocket );
+ return 0;
+ }
+
+ return newsocket;
+}
+
+
+/*
+====================
+NET_OpenIPX
+====================
+*/
+void NET_OpenIPX( void ) {
+ int port;
+
+ port = Cvar_Get( "net_port", va( "%i", PORT_SERVER ), CVAR_LATCH )->integer;
+ ipx_socket = NET_IPXSocket( port );
+}
+
+
+
+//===================================================================
+
+
+/*
+====================
+NET_GetCvars
+====================
+*/
+static qboolean NET_GetCvars( void ) {
+ qboolean modified;
+
+ modified = qfalse;
+
+ if( net_noudp && net_noudp->modified ) {
+ modified = qtrue;
+ }
+ net_noudp = Cvar_Get( "net_noudp", "0", CVAR_LATCH | CVAR_ARCHIVE );
+
+ if( net_noipx && net_noipx->modified ) {
+ modified = qtrue;
+ }
+ net_noipx = Cvar_Get( "net_noipx", "0", CVAR_LATCH | CVAR_ARCHIVE );
+
+
+ if( net_socksEnabled && net_socksEnabled->modified ) {
+ modified = qtrue;
+ }
+ net_socksEnabled = Cvar_Get( "net_socksEnabled", "0", CVAR_LATCH | CVAR_ARCHIVE );
+
+ if( net_socksServer && net_socksServer->modified ) {
+ modified = qtrue;
+ }
+ net_socksServer = Cvar_Get( "net_socksServer", "", CVAR_LATCH | CVAR_ARCHIVE );
+
+ if( net_socksPort && net_socksPort->modified ) {
+ modified = qtrue;
+ }
+ net_socksPort = Cvar_Get( "net_socksPort", "1080", CVAR_LATCH | CVAR_ARCHIVE );
+
+ if( net_socksUsername && net_socksUsername->modified ) {
+ modified = qtrue;
+ }
+ net_socksUsername = Cvar_Get( "net_socksUsername", "", CVAR_LATCH | CVAR_ARCHIVE );
+
+ if( net_socksPassword && net_socksPassword->modified ) {
+ modified = qtrue;
+ }
+ net_socksPassword = Cvar_Get( "net_socksPassword", "", CVAR_LATCH | CVAR_ARCHIVE );
+
+
+ return modified;
+}
+
+
+/*
+====================
+NET_Config
+====================
+*/
+void NET_Config( qboolean enableNetworking ) {
+ qboolean modified;
+ qboolean stop;
+ qboolean start;
+
+ // get any latched changes to cvars
+ modified = NET_GetCvars();
+
+ if( net_noudp->integer && net_noipx->integer ) {
+ enableNetworking = qfalse;
+ }
+
+ // if enable state is the same and no cvars were modified, we have nothing to do
+ if( enableNetworking == networkingEnabled && !modified ) {
+ return;
+ }
+
+ if( enableNetworking == networkingEnabled ) {
+ if( enableNetworking ) {
+ stop = qtrue;
+ start = qtrue;
+ }
+ else {
+ stop = qfalse;
+ start = qfalse;
+ }
+ }
+ else {
+ if( enableNetworking ) {
+ stop = qfalse;
+ start = qtrue;
+ }
+ else {
+ stop = qtrue;
+ start = qfalse;
+ }
+ networkingEnabled = enableNetworking;
+ }
+
+ if( stop ) {
+ if ( ip_socket && ip_socket != INVALID_SOCKET ) {
+ closesocket( ip_socket );
+ ip_socket = 0;
+ }
+
+ if ( socks_socket && socks_socket != INVALID_SOCKET ) {
+ closesocket( socks_socket );
+ socks_socket = 0;
+ }
+
+ if ( ipx_socket && ipx_socket != INVALID_SOCKET ) {
+ closesocket( ipx_socket );
+ ipx_socket = 0;
+ }
+ }
+
+ if( start ) {
+ if (! net_noudp->integer ) {
+ NET_OpenIP();
+ }
+ if (! net_noipx->integer ) {
+ NET_OpenIPX();
+ }
+ }
+}
+
+
+/*
+====================
+NET_Init
+====================
+*/
+void NET_Init( void ) {
+ int r;
+
+ r = WSAStartup( MAKEWORD( 1, 1 ), &winsockdata );
+ if( r ) {
+ Com_Printf( "WARNING: Winsock initialization failed, returned %d\n", r );
+ return;
+ }
+
+ winsockInitialized = qtrue;
+ Com_Printf( "Winsock Initialized\n" );
+
+ // this is really just to get the cvars registered
+ NET_GetCvars();
+
+ //FIXME testing!
+ NET_Config( qtrue );
+}
+
+
+/*
+====================
+NET_Shutdown
+====================
+*/
+void NET_Shutdown( void ) {
+ if ( !winsockInitialized ) {
+ return;
+ }
+ NET_Config( qfalse );
+ WSACleanup();
+ winsockInitialized = qfalse;
+}
+
+
+/*
+====================
+NET_Sleep
+
+sleeps msec or until net socket is ready
+====================
+*/
+void NET_Sleep( int msec ) {
+}
+
+
+/*
+====================
+NET_Restart_f
+====================
+*/
+void NET_Restart( void ) {
+ NET_Config( networkingEnabled );
+}
diff --git a/code/win32/win_qgl.c b/code/win32/win_qgl.c
new file mode 100755
index 0000000..65d0c25
--- /dev/null
+++ b/code/win32/win_qgl.c
@@ -0,0 +1,4374 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+/*
+** QGL_WIN.C
+**
+** This file implements the operating system binding of GL to QGL function
+** pointers. When doing a port of Quake3 you must implement the following
+** two functions:
+**
+** QGL_Init() - loads libraries, assigns function pointers, etc.
+** QGL_Shutdown() - unloads libraries, NULLs function pointers
+*/
+#include <float.h>
+#include "../renderer/tr_local.h"
+#include "glw_win.h"
+
+void QGL_EnableLogging( qboolean enable );
+
+int ( WINAPI * qwglSwapIntervalEXT)( int interval );
+BOOL ( WINAPI * qwglGetDeviceGammaRamp3DFX)( HDC, LPVOID );
+BOOL ( WINAPI * qwglSetDeviceGammaRamp3DFX)( HDC, LPVOID );
+
+int ( WINAPI * qwglChoosePixelFormat )(HDC, CONST PIXELFORMATDESCRIPTOR *);
+int ( WINAPI * qwglDescribePixelFormat) (HDC, int, UINT, LPPIXELFORMATDESCRIPTOR);
+int ( WINAPI * qwglGetPixelFormat)(HDC);
+BOOL ( WINAPI * qwglSetPixelFormat)(HDC, int, CONST PIXELFORMATDESCRIPTOR *);
+BOOL ( WINAPI * qwglSwapBuffers)(HDC);
+
+BOOL ( WINAPI * qwglCopyContext)(HGLRC, HGLRC, UINT);
+HGLRC ( WINAPI * qwglCreateContext)(HDC);
+HGLRC ( WINAPI * qwglCreateLayerContext)(HDC, int);
+BOOL ( WINAPI * qwglDeleteContext)(HGLRC);
+HGLRC ( WINAPI * qwglGetCurrentContext)(VOID);
+HDC ( WINAPI * qwglGetCurrentDC)(VOID);
+PROC ( WINAPI * qwglGetProcAddress)(LPCSTR);
+BOOL ( WINAPI * qwglMakeCurrent)(HDC, HGLRC);
+BOOL ( WINAPI * qwglShareLists)(HGLRC, HGLRC);
+BOOL ( WINAPI * qwglUseFontBitmaps)(HDC, DWORD, DWORD, DWORD);
+
+BOOL ( WINAPI * qwglUseFontOutlines)(HDC, DWORD, DWORD, DWORD, FLOAT,
+ FLOAT, int, LPGLYPHMETRICSFLOAT);
+
+BOOL ( WINAPI * qwglDescribeLayerPlane)(HDC, int, int, UINT,
+ LPLAYERPLANEDESCRIPTOR);
+int ( WINAPI * qwglSetLayerPaletteEntries)(HDC, int, int, int,
+ CONST COLORREF *);
+int ( WINAPI * qwglGetLayerPaletteEntries)(HDC, int, int, int,
+ COLORREF *);
+BOOL ( WINAPI * qwglRealizeLayerPalette)(HDC, int, BOOL);
+BOOL ( WINAPI * qwglSwapLayerBuffers)(HDC, UINT);
+
+void ( APIENTRY * qglAccum )(GLenum op, GLfloat value);
+void ( APIENTRY * qglAlphaFunc )(GLenum func, GLclampf ref);
+GLboolean ( APIENTRY * qglAreTexturesResident )(GLsizei n, const GLuint *textures, GLboolean *residences);
+void ( APIENTRY * qglArrayElement )(GLint i);
+void ( APIENTRY * qglBegin )(GLenum mode);
+void ( APIENTRY * qglBindTexture )(GLenum target, GLuint texture);
+void ( APIENTRY * qglBitmap )(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap);
+void ( APIENTRY * qglBlendFunc )(GLenum sfactor, GLenum dfactor);
+void ( APIENTRY * qglCallList )(GLuint list);
+void ( APIENTRY * qglCallLists )(GLsizei n, GLenum type, const GLvoid *lists);
+void ( APIENTRY * qglClear )(GLbitfield mask);
+void ( APIENTRY * qglClearAccum )(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+void ( APIENTRY * qglClearColor )(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+void ( APIENTRY * qglClearDepth )(GLclampd depth);
+void ( APIENTRY * qglClearIndex )(GLfloat c);
+void ( APIENTRY * qglClearStencil )(GLint s);
+void ( APIENTRY * qglClipPlane )(GLenum plane, const GLdouble *equation);
+void ( APIENTRY * qglColor3b )(GLbyte red, GLbyte green, GLbyte blue);
+void ( APIENTRY * qglColor3bv )(const GLbyte *v);
+void ( APIENTRY * qglColor3d )(GLdouble red, GLdouble green, GLdouble blue);
+void ( APIENTRY * qglColor3dv )(const GLdouble *v);
+void ( APIENTRY * qglColor3f )(GLfloat red, GLfloat green, GLfloat blue);
+void ( APIENTRY * qglColor3fv )(const GLfloat *v);
+void ( APIENTRY * qglColor3i )(GLint red, GLint green, GLint blue);
+void ( APIENTRY * qglColor3iv )(const GLint *v);
+void ( APIENTRY * qglColor3s )(GLshort red, GLshort green, GLshort blue);
+void ( APIENTRY * qglColor3sv )(const GLshort *v);
+void ( APIENTRY * qglColor3ub )(GLubyte red, GLubyte green, GLubyte blue);
+void ( APIENTRY * qglColor3ubv )(const GLubyte *v);
+void ( APIENTRY * qglColor3ui )(GLuint red, GLuint green, GLuint blue);
+void ( APIENTRY * qglColor3uiv )(const GLuint *v);
+void ( APIENTRY * qglColor3us )(GLushort red, GLushort green, GLushort blue);
+void ( APIENTRY * qglColor3usv )(const GLushort *v);
+void ( APIENTRY * qglColor4b )(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha);
+void ( APIENTRY * qglColor4bv )(const GLbyte *v);
+void ( APIENTRY * qglColor4d )(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha);
+void ( APIENTRY * qglColor4dv )(const GLdouble *v);
+void ( APIENTRY * qglColor4f )(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+void ( APIENTRY * qglColor4fv )(const GLfloat *v);
+void ( APIENTRY * qglColor4i )(GLint red, GLint green, GLint blue, GLint alpha);
+void ( APIENTRY * qglColor4iv )(const GLint *v);
+void ( APIENTRY * qglColor4s )(GLshort red, GLshort green, GLshort blue, GLshort alpha);
+void ( APIENTRY * qglColor4sv )(const GLshort *v);
+void ( APIENTRY * qglColor4ub )(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha);
+void ( APIENTRY * qglColor4ubv )(const GLubyte *v);
+void ( APIENTRY * qglColor4ui )(GLuint red, GLuint green, GLuint blue, GLuint alpha);
+void ( APIENTRY * qglColor4uiv )(const GLuint *v);
+void ( APIENTRY * qglColor4us )(GLushort red, GLushort green, GLushort blue, GLushort alpha);
+void ( APIENTRY * qglColor4usv )(const GLushort *v);
+void ( APIENTRY * qglColorMask )(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
+void ( APIENTRY * qglColorMaterial )(GLenum face, GLenum mode);
+void ( APIENTRY * qglColorPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+void ( APIENTRY * qglCopyPixels )(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type);
+void ( APIENTRY * qglCopyTexImage1D )(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLint border);
+void ( APIENTRY * qglCopyTexImage2D )(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+void ( APIENTRY * qglCopyTexSubImage1D )(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
+void ( APIENTRY * qglCopyTexSubImage2D )(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+void ( APIENTRY * qglCullFace )(GLenum mode);
+void ( APIENTRY * qglDeleteLists )(GLuint list, GLsizei range);
+void ( APIENTRY * qglDeleteTextures )(GLsizei n, const GLuint *textures);
+void ( APIENTRY * qglDepthFunc )(GLenum func);
+void ( APIENTRY * qglDepthMask )(GLboolean flag);
+void ( APIENTRY * qglDepthRange )(GLclampd zNear, GLclampd zFar);
+void ( APIENTRY * qglDisable )(GLenum cap);
+void ( APIENTRY * qglDisableClientState )(GLenum array);
+void ( APIENTRY * qglDrawArrays )(GLenum mode, GLint first, GLsizei count);
+void ( APIENTRY * qglDrawBuffer )(GLenum mode);
+void ( APIENTRY * qglDrawElements )(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices);
+void ( APIENTRY * qglDrawPixels )(GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+void ( APIENTRY * qglEdgeFlag )(GLboolean flag);
+void ( APIENTRY * qglEdgeFlagPointer )(GLsizei stride, const GLvoid *pointer);
+void ( APIENTRY * qglEdgeFlagv )(const GLboolean *flag);
+void ( APIENTRY * qglEnable )(GLenum cap);
+void ( APIENTRY * qglEnableClientState )(GLenum array);
+void ( APIENTRY * qglEnd )(void);
+void ( APIENTRY * qglEndList )(void);
+void ( APIENTRY * qglEvalCoord1d )(GLdouble u);
+void ( APIENTRY * qglEvalCoord1dv )(const GLdouble *u);
+void ( APIENTRY * qglEvalCoord1f )(GLfloat u);
+void ( APIENTRY * qglEvalCoord1fv )(const GLfloat *u);
+void ( APIENTRY * qglEvalCoord2d )(GLdouble u, GLdouble v);
+void ( APIENTRY * qglEvalCoord2dv )(const GLdouble *u);
+void ( APIENTRY * qglEvalCoord2f )(GLfloat u, GLfloat v);
+void ( APIENTRY * qglEvalCoord2fv )(const GLfloat *u);
+void ( APIENTRY * qglEvalMesh1 )(GLenum mode, GLint i1, GLint i2);
+void ( APIENTRY * qglEvalMesh2 )(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2);
+void ( APIENTRY * qglEvalPoint1 )(GLint i);
+void ( APIENTRY * qglEvalPoint2 )(GLint i, GLint j);
+void ( APIENTRY * qglFeedbackBuffer )(GLsizei size, GLenum type, GLfloat *buffer);
+void ( APIENTRY * qglFinish )(void);
+void ( APIENTRY * qglFlush )(void);
+void ( APIENTRY * qglFogf )(GLenum pname, GLfloat param);
+void ( APIENTRY * qglFogfv )(GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglFogi )(GLenum pname, GLint param);
+void ( APIENTRY * qglFogiv )(GLenum pname, const GLint *params);
+void ( APIENTRY * qglFrontFace )(GLenum mode);
+void ( APIENTRY * qglFrustum )(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+GLuint ( APIENTRY * qglGenLists )(GLsizei range);
+void ( APIENTRY * qglGenTextures )(GLsizei n, GLuint *textures);
+void ( APIENTRY * qglGetBooleanv )(GLenum pname, GLboolean *params);
+void ( APIENTRY * qglGetClipPlane )(GLenum plane, GLdouble *equation);
+void ( APIENTRY * qglGetDoublev )(GLenum pname, GLdouble *params);
+GLenum ( APIENTRY * qglGetError )(void);
+void ( APIENTRY * qglGetFloatv )(GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetIntegerv )(GLenum pname, GLint *params);
+void ( APIENTRY * qglGetLightfv )(GLenum light, GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetLightiv )(GLenum light, GLenum pname, GLint *params);
+void ( APIENTRY * qglGetMapdv )(GLenum target, GLenum query, GLdouble *v);
+void ( APIENTRY * qglGetMapfv )(GLenum target, GLenum query, GLfloat *v);
+void ( APIENTRY * qglGetMapiv )(GLenum target, GLenum query, GLint *v);
+void ( APIENTRY * qglGetMaterialfv )(GLenum face, GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetMaterialiv )(GLenum face, GLenum pname, GLint *params);
+void ( APIENTRY * qglGetPixelMapfv )(GLenum map, GLfloat *values);
+void ( APIENTRY * qglGetPixelMapuiv )(GLenum map, GLuint *values);
+void ( APIENTRY * qglGetPixelMapusv )(GLenum map, GLushort *values);
+void ( APIENTRY * qglGetPointerv )(GLenum pname, GLvoid* *params);
+void ( APIENTRY * qglGetPolygonStipple )(GLubyte *mask);
+const GLubyte * ( APIENTRY * qglGetString )(GLenum name);
+void ( APIENTRY * qglGetTexEnvfv )(GLenum target, GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetTexEnviv )(GLenum target, GLenum pname, GLint *params);
+void ( APIENTRY * qglGetTexGendv )(GLenum coord, GLenum pname, GLdouble *params);
+void ( APIENTRY * qglGetTexGenfv )(GLenum coord, GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetTexGeniv )(GLenum coord, GLenum pname, GLint *params);
+void ( APIENTRY * qglGetTexImage )(GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels);
+void ( APIENTRY * qglGetTexLevelParameterfv )(GLenum target, GLint level, GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetTexLevelParameteriv )(GLenum target, GLint level, GLenum pname, GLint *params);
+void ( APIENTRY * qglGetTexParameterfv )(GLenum target, GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetTexParameteriv )(GLenum target, GLenum pname, GLint *params);
+void ( APIENTRY * qglHint )(GLenum target, GLenum mode);
+void ( APIENTRY * qglIndexMask )(GLuint mask);
+void ( APIENTRY * qglIndexPointer )(GLenum type, GLsizei stride, const GLvoid *pointer);
+void ( APIENTRY * qglIndexd )(GLdouble c);
+void ( APIENTRY * qglIndexdv )(const GLdouble *c);
+void ( APIENTRY * qglIndexf )(GLfloat c);
+void ( APIENTRY * qglIndexfv )(const GLfloat *c);
+void ( APIENTRY * qglIndexi )(GLint c);
+void ( APIENTRY * qglIndexiv )(const GLint *c);
+void ( APIENTRY * qglIndexs )(GLshort c);
+void ( APIENTRY * qglIndexsv )(const GLshort *c);
+void ( APIENTRY * qglIndexub )(GLubyte c);
+void ( APIENTRY * qglIndexubv )(const GLubyte *c);
+void ( APIENTRY * qglInitNames )(void);
+void ( APIENTRY * qglInterleavedArrays )(GLenum format, GLsizei stride, const GLvoid *pointer);
+GLboolean ( APIENTRY * qglIsEnabled )(GLenum cap);
+GLboolean ( APIENTRY * qglIsList )(GLuint list);
+GLboolean ( APIENTRY * qglIsTexture )(GLuint texture);
+void ( APIENTRY * qglLightModelf )(GLenum pname, GLfloat param);
+void ( APIENTRY * qglLightModelfv )(GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglLightModeli )(GLenum pname, GLint param);
+void ( APIENTRY * qglLightModeliv )(GLenum pname, const GLint *params);
+void ( APIENTRY * qglLightf )(GLenum light, GLenum pname, GLfloat param);
+void ( APIENTRY * qglLightfv )(GLenum light, GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglLighti )(GLenum light, GLenum pname, GLint param);
+void ( APIENTRY * qglLightiv )(GLenum light, GLenum pname, const GLint *params);
+void ( APIENTRY * qglLineStipple )(GLint factor, GLushort pattern);
+void ( APIENTRY * qglLineWidth )(GLfloat width);
+void ( APIENTRY * qglListBase )(GLuint base);
+void ( APIENTRY * qglLoadIdentity )(void);
+void ( APIENTRY * qglLoadMatrixd )(const GLdouble *m);
+void ( APIENTRY * qglLoadMatrixf )(const GLfloat *m);
+void ( APIENTRY * qglLoadName )(GLuint name);
+void ( APIENTRY * qglLogicOp )(GLenum opcode);
+void ( APIENTRY * qglMap1d )(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points);
+void ( APIENTRY * qglMap1f )(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points);
+void ( APIENTRY * qglMap2d )(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points);
+void ( APIENTRY * qglMap2f )(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points);
+void ( APIENTRY * qglMapGrid1d )(GLint un, GLdouble u1, GLdouble u2);
+void ( APIENTRY * qglMapGrid1f )(GLint un, GLfloat u1, GLfloat u2);
+void ( APIENTRY * qglMapGrid2d )(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2);
+void ( APIENTRY * qglMapGrid2f )(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2);
+void ( APIENTRY * qglMaterialf )(GLenum face, GLenum pname, GLfloat param);
+void ( APIENTRY * qglMaterialfv )(GLenum face, GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglMateriali )(GLenum face, GLenum pname, GLint param);
+void ( APIENTRY * qglMaterialiv )(GLenum face, GLenum pname, const GLint *params);
+void ( APIENTRY * qglMatrixMode )(GLenum mode);
+void ( APIENTRY * qglMultMatrixd )(const GLdouble *m);
+void ( APIENTRY * qglMultMatrixf )(const GLfloat *m);
+void ( APIENTRY * qglNewList )(GLuint list, GLenum mode);
+void ( APIENTRY * qglNormal3b )(GLbyte nx, GLbyte ny, GLbyte nz);
+void ( APIENTRY * qglNormal3bv )(const GLbyte *v);
+void ( APIENTRY * qglNormal3d )(GLdouble nx, GLdouble ny, GLdouble nz);
+void ( APIENTRY * qglNormal3dv )(const GLdouble *v);
+void ( APIENTRY * qglNormal3f )(GLfloat nx, GLfloat ny, GLfloat nz);
+void ( APIENTRY * qglNormal3fv )(const GLfloat *v);
+void ( APIENTRY * qglNormal3i )(GLint nx, GLint ny, GLint nz);
+void ( APIENTRY * qglNormal3iv )(const GLint *v);
+void ( APIENTRY * qglNormal3s )(GLshort nx, GLshort ny, GLshort nz);
+void ( APIENTRY * qglNormal3sv )(const GLshort *v);
+void ( APIENTRY * qglNormalPointer )(GLenum type, GLsizei stride, const GLvoid *pointer);
+void ( APIENTRY * qglOrtho )(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+void ( APIENTRY * qglPassThrough )(GLfloat token);
+void ( APIENTRY * qglPixelMapfv )(GLenum map, GLsizei mapsize, const GLfloat *values);
+void ( APIENTRY * qglPixelMapuiv )(GLenum map, GLsizei mapsize, const GLuint *values);
+void ( APIENTRY * qglPixelMapusv )(GLenum map, GLsizei mapsize, const GLushort *values);
+void ( APIENTRY * qglPixelStoref )(GLenum pname, GLfloat param);
+void ( APIENTRY * qglPixelStorei )(GLenum pname, GLint param);
+void ( APIENTRY * qglPixelTransferf )(GLenum pname, GLfloat param);
+void ( APIENTRY * qglPixelTransferi )(GLenum pname, GLint param);
+void ( APIENTRY * qglPixelZoom )(GLfloat xfactor, GLfloat yfactor);
+void ( APIENTRY * qglPointSize )(GLfloat size);
+void ( APIENTRY * qglPolygonMode )(GLenum face, GLenum mode);
+void ( APIENTRY * qglPolygonOffset )(GLfloat factor, GLfloat units);
+void ( APIENTRY * qglPolygonStipple )(const GLubyte *mask);
+void ( APIENTRY * qglPopAttrib )(void);
+void ( APIENTRY * qglPopClientAttrib )(void);
+void ( APIENTRY * qglPopMatrix )(void);
+void ( APIENTRY * qglPopName )(void);
+void ( APIENTRY * qglPrioritizeTextures )(GLsizei n, const GLuint *textures, const GLclampf *priorities);
+void ( APIENTRY * qglPushAttrib )(GLbitfield mask);
+void ( APIENTRY * qglPushClientAttrib )(GLbitfield mask);
+void ( APIENTRY * qglPushMatrix )(void);
+void ( APIENTRY * qglPushName )(GLuint name);
+void ( APIENTRY * qglRasterPos2d )(GLdouble x, GLdouble y);
+void ( APIENTRY * qglRasterPos2dv )(const GLdouble *v);
+void ( APIENTRY * qglRasterPos2f )(GLfloat x, GLfloat y);
+void ( APIENTRY * qglRasterPos2fv )(const GLfloat *v);
+void ( APIENTRY * qglRasterPos2i )(GLint x, GLint y);
+void ( APIENTRY * qglRasterPos2iv )(const GLint *v);
+void ( APIENTRY * qglRasterPos2s )(GLshort x, GLshort y);
+void ( APIENTRY * qglRasterPos2sv )(const GLshort *v);
+void ( APIENTRY * qglRasterPos3d )(GLdouble x, GLdouble y, GLdouble z);
+void ( APIENTRY * qglRasterPos3dv )(const GLdouble *v);
+void ( APIENTRY * qglRasterPos3f )(GLfloat x, GLfloat y, GLfloat z);
+void ( APIENTRY * qglRasterPos3fv )(const GLfloat *v);
+void ( APIENTRY * qglRasterPos3i )(GLint x, GLint y, GLint z);
+void ( APIENTRY * qglRasterPos3iv )(const GLint *v);
+void ( APIENTRY * qglRasterPos3s )(GLshort x, GLshort y, GLshort z);
+void ( APIENTRY * qglRasterPos3sv )(const GLshort *v);
+void ( APIENTRY * qglRasterPos4d )(GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+void ( APIENTRY * qglRasterPos4dv )(const GLdouble *v);
+void ( APIENTRY * qglRasterPos4f )(GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+void ( APIENTRY * qglRasterPos4fv )(const GLfloat *v);
+void ( APIENTRY * qglRasterPos4i )(GLint x, GLint y, GLint z, GLint w);
+void ( APIENTRY * qglRasterPos4iv )(const GLint *v);
+void ( APIENTRY * qglRasterPos4s )(GLshort x, GLshort y, GLshort z, GLshort w);
+void ( APIENTRY * qglRasterPos4sv )(const GLshort *v);
+void ( APIENTRY * qglReadBuffer )(GLenum mode);
+void ( APIENTRY * qglReadPixels )(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels);
+void ( APIENTRY * qglRectd )(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2);
+void ( APIENTRY * qglRectdv )(const GLdouble *v1, const GLdouble *v2);
+void ( APIENTRY * qglRectf )(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2);
+void ( APIENTRY * qglRectfv )(const GLfloat *v1, const GLfloat *v2);
+void ( APIENTRY * qglRecti )(GLint x1, GLint y1, GLint x2, GLint y2);
+void ( APIENTRY * qglRectiv )(const GLint *v1, const GLint *v2);
+void ( APIENTRY * qglRects )(GLshort x1, GLshort y1, GLshort x2, GLshort y2);
+void ( APIENTRY * qglRectsv )(const GLshort *v1, const GLshort *v2);
+GLint ( APIENTRY * qglRenderMode )(GLenum mode);
+void ( APIENTRY * qglRotated )(GLdouble angle, GLdouble x, GLdouble y, GLdouble z);
+void ( APIENTRY * qglRotatef )(GLfloat angle, GLfloat x, GLfloat y, GLfloat z);
+void ( APIENTRY * qglScaled )(GLdouble x, GLdouble y, GLdouble z);
+void ( APIENTRY * qglScalef )(GLfloat x, GLfloat y, GLfloat z);
+void ( APIENTRY * qglScissor )(GLint x, GLint y, GLsizei width, GLsizei height);
+void ( APIENTRY * qglSelectBuffer )(GLsizei size, GLuint *buffer);
+void ( APIENTRY * qglShadeModel )(GLenum mode);
+void ( APIENTRY * qglStencilFunc )(GLenum func, GLint ref, GLuint mask);
+void ( APIENTRY * qglStencilMask )(GLuint mask);
+void ( APIENTRY * qglStencilOp )(GLenum fail, GLenum zfail, GLenum zpass);
+void ( APIENTRY * qglTexCoord1d )(GLdouble s);
+void ( APIENTRY * qglTexCoord1dv )(const GLdouble *v);
+void ( APIENTRY * qglTexCoord1f )(GLfloat s);
+void ( APIENTRY * qglTexCoord1fv )(const GLfloat *v);
+void ( APIENTRY * qglTexCoord1i )(GLint s);
+void ( APIENTRY * qglTexCoord1iv )(const GLint *v);
+void ( APIENTRY * qglTexCoord1s )(GLshort s);
+void ( APIENTRY * qglTexCoord1sv )(const GLshort *v);
+void ( APIENTRY * qglTexCoord2d )(GLdouble s, GLdouble t);
+void ( APIENTRY * qglTexCoord2dv )(const GLdouble *v);
+void ( APIENTRY * qglTexCoord2f )(GLfloat s, GLfloat t);
+void ( APIENTRY * qglTexCoord2fv )(const GLfloat *v);
+void ( APIENTRY * qglTexCoord2i )(GLint s, GLint t);
+void ( APIENTRY * qglTexCoord2iv )(const GLint *v);
+void ( APIENTRY * qglTexCoord2s )(GLshort s, GLshort t);
+void ( APIENTRY * qglTexCoord2sv )(const GLshort *v);
+void ( APIENTRY * qglTexCoord3d )(GLdouble s, GLdouble t, GLdouble r);
+void ( APIENTRY * qglTexCoord3dv )(const GLdouble *v);
+void ( APIENTRY * qglTexCoord3f )(GLfloat s, GLfloat t, GLfloat r);
+void ( APIENTRY * qglTexCoord3fv )(const GLfloat *v);
+void ( APIENTRY * qglTexCoord3i )(GLint s, GLint t, GLint r);
+void ( APIENTRY * qglTexCoord3iv )(const GLint *v);
+void ( APIENTRY * qglTexCoord3s )(GLshort s, GLshort t, GLshort r);
+void ( APIENTRY * qglTexCoord3sv )(const GLshort *v);
+void ( APIENTRY * qglTexCoord4d )(GLdouble s, GLdouble t, GLdouble r, GLdouble q);
+void ( APIENTRY * qglTexCoord4dv )(const GLdouble *v);
+void ( APIENTRY * qglTexCoord4f )(GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+void ( APIENTRY * qglTexCoord4fv )(const GLfloat *v);
+void ( APIENTRY * qglTexCoord4i )(GLint s, GLint t, GLint r, GLint q);
+void ( APIENTRY * qglTexCoord4iv )(const GLint *v);
+void ( APIENTRY * qglTexCoord4s )(GLshort s, GLshort t, GLshort r, GLshort q);
+void ( APIENTRY * qglTexCoord4sv )(const GLshort *v);
+void ( APIENTRY * qglTexCoordPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+void ( APIENTRY * qglTexEnvf )(GLenum target, GLenum pname, GLfloat param);
+void ( APIENTRY * qglTexEnvfv )(GLenum target, GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglTexEnvi )(GLenum target, GLenum pname, GLint param);
+void ( APIENTRY * qglTexEnviv )(GLenum target, GLenum pname, const GLint *params);
+void ( APIENTRY * qglTexGend )(GLenum coord, GLenum pname, GLdouble param);
+void ( APIENTRY * qglTexGendv )(GLenum coord, GLenum pname, const GLdouble *params);
+void ( APIENTRY * qglTexGenf )(GLenum coord, GLenum pname, GLfloat param);
+void ( APIENTRY * qglTexGenfv )(GLenum coord, GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglTexGeni )(GLenum coord, GLenum pname, GLint param);
+void ( APIENTRY * qglTexGeniv )(GLenum coord, GLenum pname, const GLint *params);
+void ( APIENTRY * qglTexImage1D )(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+void ( APIENTRY * qglTexImage2D )(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+void ( APIENTRY * qglTexParameterf )(GLenum target, GLenum pname, GLfloat param);
+void ( APIENTRY * qglTexParameterfv )(GLenum target, GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglTexParameteri )(GLenum target, GLenum pname, GLint param);
+void ( APIENTRY * qglTexParameteriv )(GLenum target, GLenum pname, const GLint *params);
+void ( APIENTRY * qglTexSubImage1D )(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels);
+void ( APIENTRY * qglTexSubImage2D )(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+void ( APIENTRY * qglTranslated )(GLdouble x, GLdouble y, GLdouble z);
+void ( APIENTRY * qglTranslatef )(GLfloat x, GLfloat y, GLfloat z);
+void ( APIENTRY * qglVertex2d )(GLdouble x, GLdouble y);
+void ( APIENTRY * qglVertex2dv )(const GLdouble *v);
+void ( APIENTRY * qglVertex2f )(GLfloat x, GLfloat y);
+void ( APIENTRY * qglVertex2fv )(const GLfloat *v);
+void ( APIENTRY * qglVertex2i )(GLint x, GLint y);
+void ( APIENTRY * qglVertex2iv )(const GLint *v);
+void ( APIENTRY * qglVertex2s )(GLshort x, GLshort y);
+void ( APIENTRY * qglVertex2sv )(const GLshort *v);
+void ( APIENTRY * qglVertex3d )(GLdouble x, GLdouble y, GLdouble z);
+void ( APIENTRY * qglVertex3dv )(const GLdouble *v);
+void ( APIENTRY * qglVertex3f )(GLfloat x, GLfloat y, GLfloat z);
+void ( APIENTRY * qglVertex3fv )(const GLfloat *v);
+void ( APIENTRY * qglVertex3i )(GLint x, GLint y, GLint z);
+void ( APIENTRY * qglVertex3iv )(const GLint *v);
+void ( APIENTRY * qglVertex3s )(GLshort x, GLshort y, GLshort z);
+void ( APIENTRY * qglVertex3sv )(const GLshort *v);
+void ( APIENTRY * qglVertex4d )(GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+void ( APIENTRY * qglVertex4dv )(const GLdouble *v);
+void ( APIENTRY * qglVertex4f )(GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+void ( APIENTRY * qglVertex4fv )(const GLfloat *v);
+void ( APIENTRY * qglVertex4i )(GLint x, GLint y, GLint z, GLint w);
+void ( APIENTRY * qglVertex4iv )(const GLint *v);
+void ( APIENTRY * qglVertex4s )(GLshort x, GLshort y, GLshort z, GLshort w);
+void ( APIENTRY * qglVertex4sv )(const GLshort *v);
+void ( APIENTRY * qglVertexPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+void ( APIENTRY * qglViewport )(GLint x, GLint y, GLsizei width, GLsizei height);
+
+
+
+static void ( APIENTRY * dllAccum )(GLenum op, GLfloat value);
+static void ( APIENTRY * dllAlphaFunc )(GLenum func, GLclampf ref);
+GLboolean ( APIENTRY * dllAreTexturesResident )(GLsizei n, const GLuint *textures, GLboolean *residences);
+static void ( APIENTRY * dllArrayElement )(GLint i);
+static void ( APIENTRY * dllBegin )(GLenum mode);
+static void ( APIENTRY * dllBindTexture )(GLenum target, GLuint texture);
+static void ( APIENTRY * dllBitmap )(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap);
+static void ( APIENTRY * dllBlendFunc )(GLenum sfactor, GLenum dfactor);
+static void ( APIENTRY * dllCallList )(GLuint list);
+static void ( APIENTRY * dllCallLists )(GLsizei n, GLenum type, const GLvoid *lists);
+static void ( APIENTRY * dllClear )(GLbitfield mask);
+static void ( APIENTRY * dllClearAccum )(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+static void ( APIENTRY * dllClearColor )(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+static void ( APIENTRY * dllClearDepth )(GLclampd depth);
+static void ( APIENTRY * dllClearIndex )(GLfloat c);
+static void ( APIENTRY * dllClearStencil )(GLint s);
+static void ( APIENTRY * dllClipPlane )(GLenum plane, const GLdouble *equation);
+static void ( APIENTRY * dllColor3b )(GLbyte red, GLbyte green, GLbyte blue);
+static void ( APIENTRY * dllColor3bv )(const GLbyte *v);
+static void ( APIENTRY * dllColor3d )(GLdouble red, GLdouble green, GLdouble blue);
+static void ( APIENTRY * dllColor3dv )(const GLdouble *v);
+static void ( APIENTRY * dllColor3f )(GLfloat red, GLfloat green, GLfloat blue);
+static void ( APIENTRY * dllColor3fv )(const GLfloat *v);
+static void ( APIENTRY * dllColor3i )(GLint red, GLint green, GLint blue);
+static void ( APIENTRY * dllColor3iv )(const GLint *v);
+static void ( APIENTRY * dllColor3s )(GLshort red, GLshort green, GLshort blue);
+static void ( APIENTRY * dllColor3sv )(const GLshort *v);
+static void ( APIENTRY * dllColor3ub )(GLubyte red, GLubyte green, GLubyte blue);
+static void ( APIENTRY * dllColor3ubv )(const GLubyte *v);
+static void ( APIENTRY * dllColor3ui )(GLuint red, GLuint green, GLuint blue);
+static void ( APIENTRY * dllColor3uiv )(const GLuint *v);
+static void ( APIENTRY * dllColor3us )(GLushort red, GLushort green, GLushort blue);
+static void ( APIENTRY * dllColor3usv )(const GLushort *v);
+static void ( APIENTRY * dllColor4b )(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha);
+static void ( APIENTRY * dllColor4bv )(const GLbyte *v);
+static void ( APIENTRY * dllColor4d )(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha);
+static void ( APIENTRY * dllColor4dv )(const GLdouble *v);
+static void ( APIENTRY * dllColor4f )(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+static void ( APIENTRY * dllColor4fv )(const GLfloat *v);
+static void ( APIENTRY * dllColor4i )(GLint red, GLint green, GLint blue, GLint alpha);
+static void ( APIENTRY * dllColor4iv )(const GLint *v);
+static void ( APIENTRY * dllColor4s )(GLshort red, GLshort green, GLshort blue, GLshort alpha);
+static void ( APIENTRY * dllColor4sv )(const GLshort *v);
+static void ( APIENTRY * dllColor4ub )(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha);
+static void ( APIENTRY * dllColor4ubv )(const GLubyte *v);
+static void ( APIENTRY * dllColor4ui )(GLuint red, GLuint green, GLuint blue, GLuint alpha);
+static void ( APIENTRY * dllColor4uiv )(const GLuint *v);
+static void ( APIENTRY * dllColor4us )(GLushort red, GLushort green, GLushort blue, GLushort alpha);
+static void ( APIENTRY * dllColor4usv )(const GLushort *v);
+static void ( APIENTRY * dllColorMask )(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
+static void ( APIENTRY * dllColorMaterial )(GLenum face, GLenum mode);
+static void ( APIENTRY * dllColorPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+static void ( APIENTRY * dllCopyPixels )(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type);
+static void ( APIENTRY * dllCopyTexImage1D )(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLint border);
+static void ( APIENTRY * dllCopyTexImage2D )(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+static void ( APIENTRY * dllCopyTexSubImage1D )(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
+static void ( APIENTRY * dllCopyTexSubImage2D )(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+static void ( APIENTRY * dllCullFace )(GLenum mode);
+static void ( APIENTRY * dllDeleteLists )(GLuint list, GLsizei range);
+static void ( APIENTRY * dllDeleteTextures )(GLsizei n, const GLuint *textures);
+static void ( APIENTRY * dllDepthFunc )(GLenum func);
+static void ( APIENTRY * dllDepthMask )(GLboolean flag);
+static void ( APIENTRY * dllDepthRange )(GLclampd zNear, GLclampd zFar);
+static void ( APIENTRY * dllDisable )(GLenum cap);
+static void ( APIENTRY * dllDisableClientState )(GLenum array);
+static void ( APIENTRY * dllDrawArrays )(GLenum mode, GLint first, GLsizei count);
+static void ( APIENTRY * dllDrawBuffer )(GLenum mode);
+static void ( APIENTRY * dllDrawElements )(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices);
+static void ( APIENTRY * dllDrawPixels )(GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+static void ( APIENTRY * dllEdgeFlag )(GLboolean flag);
+static void ( APIENTRY * dllEdgeFlagPointer )(GLsizei stride, const GLvoid *pointer);
+static void ( APIENTRY * dllEdgeFlagv )(const GLboolean *flag);
+static void ( APIENTRY * dllEnable )(GLenum cap);
+static void ( APIENTRY * dllEnableClientState )(GLenum array);
+static void ( APIENTRY * dllEnd )(void);
+static void ( APIENTRY * dllEndList )(void);
+static void ( APIENTRY * dllEvalCoord1d )(GLdouble u);
+static void ( APIENTRY * dllEvalCoord1dv )(const GLdouble *u);
+static void ( APIENTRY * dllEvalCoord1f )(GLfloat u);
+static void ( APIENTRY * dllEvalCoord1fv )(const GLfloat *u);
+static void ( APIENTRY * dllEvalCoord2d )(GLdouble u, GLdouble v);
+static void ( APIENTRY * dllEvalCoord2dv )(const GLdouble *u);
+static void ( APIENTRY * dllEvalCoord2f )(GLfloat u, GLfloat v);
+static void ( APIENTRY * dllEvalCoord2fv )(const GLfloat *u);
+static void ( APIENTRY * dllEvalMesh1 )(GLenum mode, GLint i1, GLint i2);
+static void ( APIENTRY * dllEvalMesh2 )(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2);
+static void ( APIENTRY * dllEvalPoint1 )(GLint i);
+static void ( APIENTRY * dllEvalPoint2 )(GLint i, GLint j);
+static void ( APIENTRY * dllFeedbackBuffer )(GLsizei size, GLenum type, GLfloat *buffer);
+static void ( APIENTRY * dllFinish )(void);
+static void ( APIENTRY * dllFlush )(void);
+static void ( APIENTRY * dllFogf )(GLenum pname, GLfloat param);
+static void ( APIENTRY * dllFogfv )(GLenum pname, const GLfloat *params);
+static void ( APIENTRY * dllFogi )(GLenum pname, GLint param);
+static void ( APIENTRY * dllFogiv )(GLenum pname, const GLint *params);
+static void ( APIENTRY * dllFrontFace )(GLenum mode);
+static void ( APIENTRY * dllFrustum )(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+GLuint ( APIENTRY * dllGenLists )(GLsizei range);
+static void ( APIENTRY * dllGenTextures )(GLsizei n, GLuint *textures);
+static void ( APIENTRY * dllGetBooleanv )(GLenum pname, GLboolean *params);
+static void ( APIENTRY * dllGetClipPlane )(GLenum plane, GLdouble *equation);
+static void ( APIENTRY * dllGetDoublev )(GLenum pname, GLdouble *params);
+GLenum ( APIENTRY * dllGetError )(void);
+static void ( APIENTRY * dllGetFloatv )(GLenum pname, GLfloat *params);
+static void ( APIENTRY * dllGetIntegerv )(GLenum pname, GLint *params);
+static void ( APIENTRY * dllGetLightfv )(GLenum light, GLenum pname, GLfloat *params);
+static void ( APIENTRY * dllGetLightiv )(GLenum light, GLenum pname, GLint *params);
+static void ( APIENTRY * dllGetMapdv )(GLenum target, GLenum query, GLdouble *v);
+static void ( APIENTRY * dllGetMapfv )(GLenum target, GLenum query, GLfloat *v);
+static void ( APIENTRY * dllGetMapiv )(GLenum target, GLenum query, GLint *v);
+static void ( APIENTRY * dllGetMaterialfv )(GLenum face, GLenum pname, GLfloat *params);
+static void ( APIENTRY * dllGetMaterialiv )(GLenum face, GLenum pname, GLint *params);
+static void ( APIENTRY * dllGetPixelMapfv )(GLenum map, GLfloat *values);
+static void ( APIENTRY * dllGetPixelMapuiv )(GLenum map, GLuint *values);
+static void ( APIENTRY * dllGetPixelMapusv )(GLenum map, GLushort *values);
+static void ( APIENTRY * dllGetPointerv )(GLenum pname, GLvoid* *params);
+static void ( APIENTRY * dllGetPolygonStipple )(GLubyte *mask);
+const GLubyte * ( APIENTRY * dllGetString )(GLenum name);
+static void ( APIENTRY * dllGetTexEnvfv )(GLenum target, GLenum pname, GLfloat *params);
+static void ( APIENTRY * dllGetTexEnviv )(GLenum target, GLenum pname, GLint *params);
+static void ( APIENTRY * dllGetTexGendv )(GLenum coord, GLenum pname, GLdouble *params);
+static void ( APIENTRY * dllGetTexGenfv )(GLenum coord, GLenum pname, GLfloat *params);
+static void ( APIENTRY * dllGetTexGeniv )(GLenum coord, GLenum pname, GLint *params);
+static void ( APIENTRY * dllGetTexImage )(GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels);
+static void ( APIENTRY * dllGetTexLevelParameterfv )(GLenum target, GLint level, GLenum pname, GLfloat *params);
+static void ( APIENTRY * dllGetTexLevelParameteriv )(GLenum target, GLint level, GLenum pname, GLint *params);
+static void ( APIENTRY * dllGetTexParameterfv )(GLenum target, GLenum pname, GLfloat *params);
+static void ( APIENTRY * dllGetTexParameteriv )(GLenum target, GLenum pname, GLint *params);
+static void ( APIENTRY * dllHint )(GLenum target, GLenum mode);
+static void ( APIENTRY * dllIndexMask )(GLuint mask);
+static void ( APIENTRY * dllIndexPointer )(GLenum type, GLsizei stride, const GLvoid *pointer);
+static void ( APIENTRY * dllIndexd )(GLdouble c);
+static void ( APIENTRY * dllIndexdv )(const GLdouble *c);
+static void ( APIENTRY * dllIndexf )(GLfloat c);
+static void ( APIENTRY * dllIndexfv )(const GLfloat *c);
+static void ( APIENTRY * dllIndexi )(GLint c);
+static void ( APIENTRY * dllIndexiv )(const GLint *c);
+static void ( APIENTRY * dllIndexs )(GLshort c);
+static void ( APIENTRY * dllIndexsv )(const GLshort *c);
+static void ( APIENTRY * dllIndexub )(GLubyte c);
+static void ( APIENTRY * dllIndexubv )(const GLubyte *c);
+static void ( APIENTRY * dllInitNames )(void);
+static void ( APIENTRY * dllInterleavedArrays )(GLenum format, GLsizei stride, const GLvoid *pointer);
+GLboolean ( APIENTRY * dllIsEnabled )(GLenum cap);
+GLboolean ( APIENTRY * dllIsList )(GLuint list);
+GLboolean ( APIENTRY * dllIsTexture )(GLuint texture);
+static void ( APIENTRY * dllLightModelf )(GLenum pname, GLfloat param);
+static void ( APIENTRY * dllLightModelfv )(GLenum pname, const GLfloat *params);
+static void ( APIENTRY * dllLightModeli )(GLenum pname, GLint param);
+static void ( APIENTRY * dllLightModeliv )(GLenum pname, const GLint *params);
+static void ( APIENTRY * dllLightf )(GLenum light, GLenum pname, GLfloat param);
+static void ( APIENTRY * dllLightfv )(GLenum light, GLenum pname, const GLfloat *params);
+static void ( APIENTRY * dllLighti )(GLenum light, GLenum pname, GLint param);
+static void ( APIENTRY * dllLightiv )(GLenum light, GLenum pname, const GLint *params);
+static void ( APIENTRY * dllLineStipple )(GLint factor, GLushort pattern);
+static void ( APIENTRY * dllLineWidth )(GLfloat width);
+static void ( APIENTRY * dllListBase )(GLuint base);
+static void ( APIENTRY * dllLoadIdentity )(void);
+static void ( APIENTRY * dllLoadMatrixd )(const GLdouble *m);
+static void ( APIENTRY * dllLoadMatrixf )(const GLfloat *m);
+static void ( APIENTRY * dllLoadName )(GLuint name);
+static void ( APIENTRY * dllLogicOp )(GLenum opcode);
+static void ( APIENTRY * dllMap1d )(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points);
+static void ( APIENTRY * dllMap1f )(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points);
+static void ( APIENTRY * dllMap2d )(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points);
+static void ( APIENTRY * dllMap2f )(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points);
+static void ( APIENTRY * dllMapGrid1d )(GLint un, GLdouble u1, GLdouble u2);
+static void ( APIENTRY * dllMapGrid1f )(GLint un, GLfloat u1, GLfloat u2);
+static void ( APIENTRY * dllMapGrid2d )(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2);
+static void ( APIENTRY * dllMapGrid2f )(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2);
+static void ( APIENTRY * dllMaterialf )(GLenum face, GLenum pname, GLfloat param);
+static void ( APIENTRY * dllMaterialfv )(GLenum face, GLenum pname, const GLfloat *params);
+static void ( APIENTRY * dllMateriali )(GLenum face, GLenum pname, GLint param);
+static void ( APIENTRY * dllMaterialiv )(GLenum face, GLenum pname, const GLint *params);
+static void ( APIENTRY * dllMatrixMode )(GLenum mode);
+static void ( APIENTRY * dllMultMatrixd )(const GLdouble *m);
+static void ( APIENTRY * dllMultMatrixf )(const GLfloat *m);
+static void ( APIENTRY * dllNewList )(GLuint list, GLenum mode);
+static void ( APIENTRY * dllNormal3b )(GLbyte nx, GLbyte ny, GLbyte nz);
+static void ( APIENTRY * dllNormal3bv )(const GLbyte *v);
+static void ( APIENTRY * dllNormal3d )(GLdouble nx, GLdouble ny, GLdouble nz);
+static void ( APIENTRY * dllNormal3dv )(const GLdouble *v);
+static void ( APIENTRY * dllNormal3f )(GLfloat nx, GLfloat ny, GLfloat nz);
+static void ( APIENTRY * dllNormal3fv )(const GLfloat *v);
+static void ( APIENTRY * dllNormal3i )(GLint nx, GLint ny, GLint nz);
+static void ( APIENTRY * dllNormal3iv )(const GLint *v);
+static void ( APIENTRY * dllNormal3s )(GLshort nx, GLshort ny, GLshort nz);
+static void ( APIENTRY * dllNormal3sv )(const GLshort *v);
+static void ( APIENTRY * dllNormalPointer )(GLenum type, GLsizei stride, const GLvoid *pointer);
+static void ( APIENTRY * dllOrtho )(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+static void ( APIENTRY * dllPassThrough )(GLfloat token);
+static void ( APIENTRY * dllPixelMapfv )(GLenum map, GLsizei mapsize, const GLfloat *values);
+static void ( APIENTRY * dllPixelMapuiv )(GLenum map, GLsizei mapsize, const GLuint *values);
+static void ( APIENTRY * dllPixelMapusv )(GLenum map, GLsizei mapsize, const GLushort *values);
+static void ( APIENTRY * dllPixelStoref )(GLenum pname, GLfloat param);
+static void ( APIENTRY * dllPixelStorei )(GLenum pname, GLint param);
+static void ( APIENTRY * dllPixelTransferf )(GLenum pname, GLfloat param);
+static void ( APIENTRY * dllPixelTransferi )(GLenum pname, GLint param);
+static void ( APIENTRY * dllPixelZoom )(GLfloat xfactor, GLfloat yfactor);
+static void ( APIENTRY * dllPointSize )(GLfloat size);
+static void ( APIENTRY * dllPolygonMode )(GLenum face, GLenum mode);
+static void ( APIENTRY * dllPolygonOffset )(GLfloat factor, GLfloat units);
+static void ( APIENTRY * dllPolygonStipple )(const GLubyte *mask);
+static void ( APIENTRY * dllPopAttrib )(void);
+static void ( APIENTRY * dllPopClientAttrib )(void);
+static void ( APIENTRY * dllPopMatrix )(void);
+static void ( APIENTRY * dllPopName )(void);
+static void ( APIENTRY * dllPrioritizeTextures )(GLsizei n, const GLuint *textures, const GLclampf *priorities);
+static void ( APIENTRY * dllPushAttrib )(GLbitfield mask);
+static void ( APIENTRY * dllPushClientAttrib )(GLbitfield mask);
+static void ( APIENTRY * dllPushMatrix )(void);
+static void ( APIENTRY * dllPushName )(GLuint name);
+static void ( APIENTRY * dllRasterPos2d )(GLdouble x, GLdouble y);
+static void ( APIENTRY * dllRasterPos2dv )(const GLdouble *v);
+static void ( APIENTRY * dllRasterPos2f )(GLfloat x, GLfloat y);
+static void ( APIENTRY * dllRasterPos2fv )(const GLfloat *v);
+static void ( APIENTRY * dllRasterPos2i )(GLint x, GLint y);
+static void ( APIENTRY * dllRasterPos2iv )(const GLint *v);
+static void ( APIENTRY * dllRasterPos2s )(GLshort x, GLshort y);
+static void ( APIENTRY * dllRasterPos2sv )(const GLshort *v);
+static void ( APIENTRY * dllRasterPos3d )(GLdouble x, GLdouble y, GLdouble z);
+static void ( APIENTRY * dllRasterPos3dv )(const GLdouble *v);
+static void ( APIENTRY * dllRasterPos3f )(GLfloat x, GLfloat y, GLfloat z);
+static void ( APIENTRY * dllRasterPos3fv )(const GLfloat *v);
+static void ( APIENTRY * dllRasterPos3i )(GLint x, GLint y, GLint z);
+static void ( APIENTRY * dllRasterPos3iv )(const GLint *v);
+static void ( APIENTRY * dllRasterPos3s )(GLshort x, GLshort y, GLshort z);
+static void ( APIENTRY * dllRasterPos3sv )(const GLshort *v);
+static void ( APIENTRY * dllRasterPos4d )(GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+static void ( APIENTRY * dllRasterPos4dv )(const GLdouble *v);
+static void ( APIENTRY * dllRasterPos4f )(GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+static void ( APIENTRY * dllRasterPos4fv )(const GLfloat *v);
+static void ( APIENTRY * dllRasterPos4i )(GLint x, GLint y, GLint z, GLint w);
+static void ( APIENTRY * dllRasterPos4iv )(const GLint *v);
+static void ( APIENTRY * dllRasterPos4s )(GLshort x, GLshort y, GLshort z, GLshort w);
+static void ( APIENTRY * dllRasterPos4sv )(const GLshort *v);
+static void ( APIENTRY * dllReadBuffer )(GLenum mode);
+static void ( APIENTRY * dllReadPixels )(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels);
+static void ( APIENTRY * dllRectd )(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2);
+static void ( APIENTRY * dllRectdv )(const GLdouble *v1, const GLdouble *v2);
+static void ( APIENTRY * dllRectf )(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2);
+static void ( APIENTRY * dllRectfv )(const GLfloat *v1, const GLfloat *v2);
+static void ( APIENTRY * dllRecti )(GLint x1, GLint y1, GLint x2, GLint y2);
+static void ( APIENTRY * dllRectiv )(const GLint *v1, const GLint *v2);
+static void ( APIENTRY * dllRects )(GLshort x1, GLshort y1, GLshort x2, GLshort y2);
+static void ( APIENTRY * dllRectsv )(const GLshort *v1, const GLshort *v2);
+GLint ( APIENTRY * dllRenderMode )(GLenum mode);
+static void ( APIENTRY * dllRotated )(GLdouble angle, GLdouble x, GLdouble y, GLdouble z);
+static void ( APIENTRY * dllRotatef )(GLfloat angle, GLfloat x, GLfloat y, GLfloat z);
+static void ( APIENTRY * dllScaled )(GLdouble x, GLdouble y, GLdouble z);
+static void ( APIENTRY * dllScalef )(GLfloat x, GLfloat y, GLfloat z);
+static void ( APIENTRY * dllScissor )(GLint x, GLint y, GLsizei width, GLsizei height);
+static void ( APIENTRY * dllSelectBuffer )(GLsizei size, GLuint *buffer);
+static void ( APIENTRY * dllShadeModel )(GLenum mode);
+static void ( APIENTRY * dllStencilFunc )(GLenum func, GLint ref, GLuint mask);
+static void ( APIENTRY * dllStencilMask )(GLuint mask);
+static void ( APIENTRY * dllStencilOp )(GLenum fail, GLenum zfail, GLenum zpass);
+static void ( APIENTRY * dllTexCoord1d )(GLdouble s);
+static void ( APIENTRY * dllTexCoord1dv )(const GLdouble *v);
+static void ( APIENTRY * dllTexCoord1f )(GLfloat s);
+static void ( APIENTRY * dllTexCoord1fv )(const GLfloat *v);
+static void ( APIENTRY * dllTexCoord1i )(GLint s);
+static void ( APIENTRY * dllTexCoord1iv )(const GLint *v);
+static void ( APIENTRY * dllTexCoord1s )(GLshort s);
+static void ( APIENTRY * dllTexCoord1sv )(const GLshort *v);
+static void ( APIENTRY * dllTexCoord2d )(GLdouble s, GLdouble t);
+static void ( APIENTRY * dllTexCoord2dv )(const GLdouble *v);
+static void ( APIENTRY * dllTexCoord2f )(GLfloat s, GLfloat t);
+static void ( APIENTRY * dllTexCoord2fv )(const GLfloat *v);
+static void ( APIENTRY * dllTexCoord2i )(GLint s, GLint t);
+static void ( APIENTRY * dllTexCoord2iv )(const GLint *v);
+static void ( APIENTRY * dllTexCoord2s )(GLshort s, GLshort t);
+static void ( APIENTRY * dllTexCoord2sv )(const GLshort *v);
+static void ( APIENTRY * dllTexCoord3d )(GLdouble s, GLdouble t, GLdouble r);
+static void ( APIENTRY * dllTexCoord3dv )(const GLdouble *v);
+static void ( APIENTRY * dllTexCoord3f )(GLfloat s, GLfloat t, GLfloat r);
+static void ( APIENTRY * dllTexCoord3fv )(const GLfloat *v);
+static void ( APIENTRY * dllTexCoord3i )(GLint s, GLint t, GLint r);
+static void ( APIENTRY * dllTexCoord3iv )(const GLint *v);
+static void ( APIENTRY * dllTexCoord3s )(GLshort s, GLshort t, GLshort r);
+static void ( APIENTRY * dllTexCoord3sv )(const GLshort *v);
+static void ( APIENTRY * dllTexCoord4d )(GLdouble s, GLdouble t, GLdouble r, GLdouble q);
+static void ( APIENTRY * dllTexCoord4dv )(const GLdouble *v);
+static void ( APIENTRY * dllTexCoord4f )(GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+static void ( APIENTRY * dllTexCoord4fv )(const GLfloat *v);
+static void ( APIENTRY * dllTexCoord4i )(GLint s, GLint t, GLint r, GLint q);
+static void ( APIENTRY * dllTexCoord4iv )(const GLint *v);
+static void ( APIENTRY * dllTexCoord4s )(GLshort s, GLshort t, GLshort r, GLshort q);
+static void ( APIENTRY * dllTexCoord4sv )(const GLshort *v);
+static void ( APIENTRY * dllTexCoordPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+static void ( APIENTRY * dllTexEnvf )(GLenum target, GLenum pname, GLfloat param);
+static void ( APIENTRY * dllTexEnvfv )(GLenum target, GLenum pname, const GLfloat *params);
+static void ( APIENTRY * dllTexEnvi )(GLenum target, GLenum pname, GLint param);
+static void ( APIENTRY * dllTexEnviv )(GLenum target, GLenum pname, const GLint *params);
+static void ( APIENTRY * dllTexGend )(GLenum coord, GLenum pname, GLdouble param);
+static void ( APIENTRY * dllTexGendv )(GLenum coord, GLenum pname, const GLdouble *params);
+static void ( APIENTRY * dllTexGenf )(GLenum coord, GLenum pname, GLfloat param);
+static void ( APIENTRY * dllTexGenfv )(GLenum coord, GLenum pname, const GLfloat *params);
+static void ( APIENTRY * dllTexGeni )(GLenum coord, GLenum pname, GLint param);
+static void ( APIENTRY * dllTexGeniv )(GLenum coord, GLenum pname, const GLint *params);
+static void ( APIENTRY * dllTexImage1D )(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+static void ( APIENTRY * dllTexImage2D )(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+static void ( APIENTRY * dllTexParameterf )(GLenum target, GLenum pname, GLfloat param);
+static void ( APIENTRY * dllTexParameterfv )(GLenum target, GLenum pname, const GLfloat *params);
+static void ( APIENTRY * dllTexParameteri )(GLenum target, GLenum pname, GLint param);
+static void ( APIENTRY * dllTexParameteriv )(GLenum target, GLenum pname, const GLint *params);
+static void ( APIENTRY * dllTexSubImage1D )(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels);
+static void ( APIENTRY * dllTexSubImage2D )(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+static void ( APIENTRY * dllTranslated )(GLdouble x, GLdouble y, GLdouble z);
+static void ( APIENTRY * dllTranslatef )(GLfloat x, GLfloat y, GLfloat z);
+static void ( APIENTRY * dllVertex2d )(GLdouble x, GLdouble y);
+static void ( APIENTRY * dllVertex2dv )(const GLdouble *v);
+static void ( APIENTRY * dllVertex2f )(GLfloat x, GLfloat y);
+static void ( APIENTRY * dllVertex2fv )(const GLfloat *v);
+static void ( APIENTRY * dllVertex2i )(GLint x, GLint y);
+static void ( APIENTRY * dllVertex2iv )(const GLint *v);
+static void ( APIENTRY * dllVertex2s )(GLshort x, GLshort y);
+static void ( APIENTRY * dllVertex2sv )(const GLshort *v);
+static void ( APIENTRY * dllVertex3d )(GLdouble x, GLdouble y, GLdouble z);
+static void ( APIENTRY * dllVertex3dv )(const GLdouble *v);
+static void ( APIENTRY * dllVertex3f )(GLfloat x, GLfloat y, GLfloat z);
+static void ( APIENTRY * dllVertex3fv )(const GLfloat *v);
+static void ( APIENTRY * dllVertex3i )(GLint x, GLint y, GLint z);
+static void ( APIENTRY * dllVertex3iv )(const GLint *v);
+static void ( APIENTRY * dllVertex3s )(GLshort x, GLshort y, GLshort z);
+static void ( APIENTRY * dllVertex3sv )(const GLshort *v);
+static void ( APIENTRY * dllVertex4d )(GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+static void ( APIENTRY * dllVertex4dv )(const GLdouble *v);
+static void ( APIENTRY * dllVertex4f )(GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+static void ( APIENTRY * dllVertex4fv )(const GLfloat *v);
+static void ( APIENTRY * dllVertex4i )(GLint x, GLint y, GLint z, GLint w);
+static void ( APIENTRY * dllVertex4iv )(const GLint *v);
+static void ( APIENTRY * dllVertex4s )(GLshort x, GLshort y, GLshort z, GLshort w);
+static void ( APIENTRY * dllVertex4sv )(const GLshort *v);
+static void ( APIENTRY * dllVertexPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+static void ( APIENTRY * dllViewport )(GLint x, GLint y, GLsizei width, GLsizei height);
+
+static const char * BooleanToString( GLboolean b )
+{
+ if ( b == GL_FALSE )
+ return "GL_FALSE";
+ else if ( b == GL_TRUE )
+ return "GL_TRUE";
+ else
+ return "OUT OF RANGE FOR BOOLEAN";
+}
+
+static const char * FuncToString( GLenum f )
+{
+ switch ( f )
+ {
+ case GL_ALWAYS:
+ return "GL_ALWAYS";
+ case GL_NEVER:
+ return "GL_NEVER";
+ case GL_LEQUAL:
+ return "GL_LEQUAL";
+ case GL_LESS:
+ return "GL_LESS";
+ case GL_EQUAL:
+ return "GL_EQUAL";
+ case GL_GREATER:
+ return "GL_GREATER";
+ case GL_GEQUAL:
+ return "GL_GEQUAL";
+ case GL_NOTEQUAL:
+ return "GL_NOTEQUAL";
+ default:
+ return "!!! UNKNOWN !!!";
+ }
+}
+
+static const char * PrimToString( GLenum mode )
+{
+ static char prim[1024];
+
+ if ( mode == GL_TRIANGLES )
+ strcpy( prim, "GL_TRIANGLES" );
+ else if ( mode == GL_TRIANGLE_STRIP )
+ strcpy( prim, "GL_TRIANGLE_STRIP" );
+ else if ( mode == GL_TRIANGLE_FAN )
+ strcpy( prim, "GL_TRIANGLE_FAN" );
+ else if ( mode == GL_QUADS )
+ strcpy( prim, "GL_QUADS" );
+ else if ( mode == GL_QUAD_STRIP )
+ strcpy( prim, "GL_QUAD_STRIP" );
+ else if ( mode == GL_POLYGON )
+ strcpy( prim, "GL_POLYGON" );
+ else if ( mode == GL_POINTS )
+ strcpy( prim, "GL_POINTS" );
+ else if ( mode == GL_LINES )
+ strcpy( prim, "GL_LINES" );
+ else if ( mode == GL_LINE_STRIP )
+ strcpy( prim, "GL_LINE_STRIP" );
+ else if ( mode == GL_LINE_LOOP )
+ strcpy( prim, "GL_LINE_LOOP" );
+ else
+ sprintf( prim, "0x%x", mode );
+
+ return prim;
+}
+
+static const char * CapToString( GLenum cap )
+{
+ static char buffer[1024];
+
+ switch ( cap )
+ {
+ case GL_TEXTURE_2D:
+ return "GL_TEXTURE_2D";
+ case GL_BLEND:
+ return "GL_BLEND";
+ case GL_DEPTH_TEST:
+ return "GL_DEPTH_TEST";
+ case GL_CULL_FACE:
+ return "GL_CULL_FACE";
+ case GL_CLIP_PLANE0:
+ return "GL_CLIP_PLANE0";
+ case GL_COLOR_ARRAY:
+ return "GL_COLOR_ARRAY";
+ case GL_TEXTURE_COORD_ARRAY:
+ return "GL_TEXTURE_COORD_ARRAY";
+ case GL_VERTEX_ARRAY:
+ return "GL_VERTEX_ARRAY";
+ case GL_ALPHA_TEST:
+ return "GL_ALPHA_TEST";
+ case GL_STENCIL_TEST:
+ return "GL_STENCIL_TEST";
+ default:
+ sprintf( buffer, "0x%x", cap );
+ }
+
+ return buffer;
+}
+
+static const char * TypeToString( GLenum t )
+{
+ switch ( t )
+ {
+ case GL_BYTE:
+ return "GL_BYTE";
+ case GL_UNSIGNED_BYTE:
+ return "GL_UNSIGNED_BYTE";
+ case GL_SHORT:
+ return "GL_SHORT";
+ case GL_UNSIGNED_SHORT:
+ return "GL_UNSIGNED_SHORT";
+ case GL_INT:
+ return "GL_INT";
+ case GL_UNSIGNED_INT:
+ return "GL_UNSIGNED_INT";
+ case GL_FLOAT:
+ return "GL_FLOAT";
+ case GL_DOUBLE:
+ return "GL_DOUBLE";
+ default:
+ return "!!! UNKNOWN !!!";
+ }
+}
+
+static void APIENTRY logAccum(GLenum op, GLfloat value)
+{
+ fprintf( glw_state.log_fp, "glAccum\n" );
+ dllAccum( op, value );
+}
+
+static void APIENTRY logAlphaFunc(GLenum func, GLclampf ref)
+{
+ fprintf( glw_state.log_fp, "glAlphaFunc( 0x%x, %f )\n", func, ref );
+ dllAlphaFunc( func, ref );
+}
+
+static GLboolean APIENTRY logAreTexturesResident(GLsizei n, const GLuint *textures, GLboolean *residences)
+{
+ fprintf( glw_state.log_fp, "glAreTexturesResident\n" );
+ return dllAreTexturesResident( n, textures, residences );
+}
+
+static void APIENTRY logArrayElement(GLint i)
+{
+ fprintf( glw_state.log_fp, "glArrayElement\n" );
+ dllArrayElement( i );
+}
+
+static void APIENTRY logBegin(GLenum mode)
+{
+ fprintf( glw_state.log_fp, "glBegin( %s )\n", PrimToString( mode ));
+ dllBegin( mode );
+}
+
+static void APIENTRY logBindTexture(GLenum target, GLuint texture)
+{
+ fprintf( glw_state.log_fp, "glBindTexture( 0x%x, %u )\n", target, texture );
+ dllBindTexture( target, texture );
+}
+
+static void APIENTRY logBitmap(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap)
+{
+ fprintf( glw_state.log_fp, "glBitmap\n" );
+ dllBitmap( width, height, xorig, yorig, xmove, ymove, bitmap );
+}
+
+static void BlendToName( char *n, GLenum f )
+{
+ switch ( f )
+ {
+ case GL_ONE:
+ strcpy( n, "GL_ONE" );
+ break;
+ case GL_ZERO:
+ strcpy( n, "GL_ZERO" );
+ break;
+ case GL_SRC_ALPHA:
+ strcpy( n, "GL_SRC_ALPHA" );
+ break;
+ case GL_ONE_MINUS_SRC_ALPHA:
+ strcpy( n, "GL_ONE_MINUS_SRC_ALPHA" );
+ break;
+ case GL_DST_COLOR:
+ strcpy( n, "GL_DST_COLOR" );
+ break;
+ case GL_ONE_MINUS_DST_COLOR:
+ strcpy( n, "GL_ONE_MINUS_DST_COLOR" );
+ break;
+ case GL_DST_ALPHA:
+ strcpy( n, "GL_DST_ALPHA" );
+ break;
+ default:
+ sprintf( n, "0x%x", f );
+ }
+}
+static void APIENTRY logBlendFunc(GLenum sfactor, GLenum dfactor)
+{
+ char sf[128], df[128];
+
+ BlendToName( sf, sfactor );
+ BlendToName( df, dfactor );
+
+ fprintf( glw_state.log_fp, "glBlendFunc( %s, %s )\n", sf, df );
+ dllBlendFunc( sfactor, dfactor );
+}
+
+static void APIENTRY logCallList(GLuint list)
+{
+ fprintf( glw_state.log_fp, "glCallList( %u )\n", list );
+ dllCallList( list );
+}
+
+static void APIENTRY logCallLists(GLsizei n, GLenum type, const void *lists)
+{
+ fprintf( glw_state.log_fp, "glCallLists\n" );
+ dllCallLists( n, type, lists );
+}
+
+static void APIENTRY logClear(GLbitfield mask)
+{
+ fprintf( glw_state.log_fp, "glClear( 0x%x = ", mask );
+
+ if ( mask & GL_COLOR_BUFFER_BIT )
+ fprintf( glw_state.log_fp, "GL_COLOR_BUFFER_BIT " );
+ if ( mask & GL_DEPTH_BUFFER_BIT )
+ fprintf( glw_state.log_fp, "GL_DEPTH_BUFFER_BIT " );
+ if ( mask & GL_STENCIL_BUFFER_BIT )
+ fprintf( glw_state.log_fp, "GL_STENCIL_BUFFER_BIT " );
+ if ( mask & GL_ACCUM_BUFFER_BIT )
+ fprintf( glw_state.log_fp, "GL_ACCUM_BUFFER_BIT " );
+
+ fprintf( glw_state.log_fp, ")\n" );
+ dllClear( mask );
+}
+
+static void APIENTRY logClearAccum(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha)
+{
+ fprintf( glw_state.log_fp, "glClearAccum\n" );
+ dllClearAccum( red, green, blue, alpha );
+}
+
+static void APIENTRY logClearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
+{
+ fprintf( glw_state.log_fp, "glClearColor\n" );
+ dllClearColor( red, green, blue, alpha );
+}
+
+static void APIENTRY logClearDepth(GLclampd depth)
+{
+ fprintf( glw_state.log_fp, "glClearDepth( %f )\n", ( float ) depth );
+ dllClearDepth( depth );
+}
+
+static void APIENTRY logClearIndex(GLfloat c)
+{
+ fprintf( glw_state.log_fp, "glClearIndex\n" );
+ dllClearIndex( c );
+}
+
+static void APIENTRY logClearStencil(GLint s)
+{
+ fprintf( glw_state.log_fp, "glClearStencil( %d )\n", s );
+ dllClearStencil( s );
+}
+
+static void APIENTRY logClipPlane(GLenum plane, const GLdouble *equation)
+{
+ fprintf( glw_state.log_fp, "glClipPlane\n" );
+ dllClipPlane( plane, equation );
+}
+
+static void APIENTRY logColor3b(GLbyte red, GLbyte green, GLbyte blue)
+{
+ fprintf( glw_state.log_fp, "glColor3b\n" );
+ dllColor3b( red, green, blue );
+}
+
+static void APIENTRY logColor3bv(const GLbyte *v)
+{
+ fprintf( glw_state.log_fp, "glColor3bv\n" );
+ dllColor3bv( v );
+}
+
+static void APIENTRY logColor3d(GLdouble red, GLdouble green, GLdouble blue)
+{
+ fprintf( glw_state.log_fp, "glColor3d\n" );
+ dllColor3d( red, green, blue );
+}
+
+static void APIENTRY logColor3dv(const GLdouble *v)
+{
+ fprintf( glw_state.log_fp, "glColor3dv\n" );
+ dllColor3dv( v );
+}
+
+static void APIENTRY logColor3f(GLfloat red, GLfloat green, GLfloat blue)
+{
+ fprintf( glw_state.log_fp, "glColor3f\n" );
+ dllColor3f( red, green, blue );
+}
+
+static void APIENTRY logColor3fv(const GLfloat *v)
+{
+ fprintf( glw_state.log_fp, "glColor3fv\n" );
+ dllColor3fv( v );
+}
+
+static void APIENTRY logColor3i(GLint red, GLint green, GLint blue)
+{
+ fprintf( glw_state.log_fp, "glColor3i\n" );
+ dllColor3i( red, green, blue );
+}
+
+static void APIENTRY logColor3iv(const GLint *v)
+{
+ fprintf( glw_state.log_fp, "glColor3iv\n" );
+ dllColor3iv( v );
+}
+
+static void APIENTRY logColor3s(GLshort red, GLshort green, GLshort blue)
+{
+ fprintf( glw_state.log_fp, "glColor3s\n" );
+ dllColor3s( red, green, blue );
+}
+
+static void APIENTRY logColor3sv(const GLshort *v)
+{
+ fprintf( glw_state.log_fp, "glColor3sv\n" );
+ dllColor3sv( v );
+}
+
+static void APIENTRY logColor3ub(GLubyte red, GLubyte green, GLubyte blue)
+{
+ fprintf( glw_state.log_fp, "glColor3ub\n" );
+ dllColor3ub( red, green, blue );
+}
+
+static void APIENTRY logColor3ubv(const GLubyte *v)
+{
+ fprintf( glw_state.log_fp, "glColor3ubv\n" );
+ dllColor3ubv( v );
+}
+
+#define SIG( x ) fprintf( glw_state.log_fp, x "\n" )
+
+static void APIENTRY logColor3ui(GLuint red, GLuint green, GLuint blue)
+{
+ SIG( "glColor3ui" );
+ dllColor3ui( red, green, blue );
+}
+
+static void APIENTRY logColor3uiv(const GLuint *v)
+{
+ SIG( "glColor3uiv" );
+ dllColor3uiv( v );
+}
+
+static void APIENTRY logColor3us(GLushort red, GLushort green, GLushort blue)
+{
+ SIG( "glColor3us" );
+ dllColor3us( red, green, blue );
+}
+
+static void APIENTRY logColor3usv(const GLushort *v)
+{
+ SIG( "glColor3usv" );
+ dllColor3usv( v );
+}
+
+static void APIENTRY logColor4b(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha)
+{
+ SIG( "glColor4b" );
+ dllColor4b( red, green, blue, alpha );
+}
+
+static void APIENTRY logColor4bv(const GLbyte *v)
+{
+ SIG( "glColor4bv" );
+ dllColor4bv( v );
+}
+
+static void APIENTRY logColor4d(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha)
+{
+ SIG( "glColor4d" );
+ dllColor4d( red, green, blue, alpha );
+}
+static void APIENTRY logColor4dv(const GLdouble *v)
+{
+ SIG( "glColor4dv" );
+ dllColor4dv( v );
+}
+static void APIENTRY logColor4f(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha)
+{
+ fprintf( glw_state.log_fp, "glColor4f( %f,%f,%f,%f )\n", red, green, blue, alpha );
+ dllColor4f( red, green, blue, alpha );
+}
+static void APIENTRY logColor4fv(const GLfloat *v)
+{
+ fprintf( glw_state.log_fp, "glColor4fv( %f,%f,%f,%f )\n", v[0], v[1], v[2], v[3] );
+ dllColor4fv( v );
+}
+static void APIENTRY logColor4i(GLint red, GLint green, GLint blue, GLint alpha)
+{
+ SIG( "glColor4i" );
+ dllColor4i( red, green, blue, alpha );
+}
+static void APIENTRY logColor4iv(const GLint *v)
+{
+ SIG( "glColor4iv" );
+ dllColor4iv( v );
+}
+static void APIENTRY logColor4s(GLshort red, GLshort green, GLshort blue, GLshort alpha)
+{
+ SIG( "glColor4s" );
+ dllColor4s( red, green, blue, alpha );
+}
+static void APIENTRY logColor4sv(const GLshort *v)
+{
+ SIG( "glColor4sv" );
+ dllColor4sv( v );
+}
+static void APIENTRY logColor4ub(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha)
+{
+ SIG( "glColor4b" );
+ dllColor4b( red, green, blue, alpha );
+}
+static void APIENTRY logColor4ubv(const GLubyte *v)
+{
+ SIG( "glColor4ubv" );
+ dllColor4ubv( v );
+}
+static void APIENTRY logColor4ui(GLuint red, GLuint green, GLuint blue, GLuint alpha)
+{
+ SIG( "glColor4ui" );
+ dllColor4ui( red, green, blue, alpha );
+}
+static void APIENTRY logColor4uiv(const GLuint *v)
+{
+ SIG( "glColor4uiv" );
+ dllColor4uiv( v );
+}
+static void APIENTRY logColor4us(GLushort red, GLushort green, GLushort blue, GLushort alpha)
+{
+ SIG( "glColor4us" );
+ dllColor4us( red, green, blue, alpha );
+}
+static void APIENTRY logColor4usv(const GLushort *v)
+{
+ SIG( "glColor4usv" );
+ dllColor4usv( v );
+}
+static void APIENTRY logColorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)
+{
+ SIG( "glColorMask" );
+ dllColorMask( red, green, blue, alpha );
+}
+static void APIENTRY logColorMaterial(GLenum face, GLenum mode)
+{
+ SIG( "glColorMaterial" );
+ dllColorMaterial( face, mode );
+}
+
+static void APIENTRY logColorPointer(GLint size, GLenum type, GLsizei stride, const void *pointer)
+{
+ fprintf( glw_state.log_fp, "glColorPointer( %d, %s, %d, MEM )\n", size, TypeToString( type ), stride );
+ dllColorPointer( size, type, stride, pointer );
+}
+
+static void APIENTRY logCopyPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type)
+{
+ SIG( "glCopyPixels" );
+ dllCopyPixels( x, y, width, height, type );
+}
+
+static void APIENTRY logCopyTexImage1D(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLint border)
+{
+ SIG( "glCopyTexImage1D" );
+ dllCopyTexImage1D( target, level, internalFormat, x, y, width, border );
+}
+
+static void APIENTRY logCopyTexImage2D(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border)
+{
+ SIG( "glCopyTexImage2D" );
+ dllCopyTexImage2D( target, level, internalFormat, x, y, width, height, border );
+}
+
+static void APIENTRY logCopyTexSubImage1D(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width)
+{
+ SIG( "glCopyTexSubImage1D" );
+ dllCopyTexSubImage1D( target, level, xoffset, x, y, width );
+}
+
+static void APIENTRY logCopyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height)
+{
+ SIG( "glCopyTexSubImage2D" );
+ dllCopyTexSubImage2D( target, level, xoffset, yoffset, x, y, width, height );
+}
+
+static void APIENTRY logCullFace(GLenum mode)
+{
+ fprintf( glw_state.log_fp, "glCullFace( %s )\n", ( mode == GL_FRONT ) ? "GL_FRONT" : "GL_BACK" );
+ dllCullFace( mode );
+}
+
+static void APIENTRY logDeleteLists(GLuint list, GLsizei range)
+{
+ SIG( "glDeleteLists" );
+ dllDeleteLists( list, range );
+}
+
+static void APIENTRY logDeleteTextures(GLsizei n, const GLuint *textures)
+{
+ SIG( "glDeleteTextures" );
+ dllDeleteTextures( n, textures );
+}
+
+static void APIENTRY logDepthFunc(GLenum func)
+{
+ fprintf( glw_state.log_fp, "glDepthFunc( %s )\n", FuncToString( func ) );
+ dllDepthFunc( func );
+}
+
+static void APIENTRY logDepthMask(GLboolean flag)
+{
+ fprintf( glw_state.log_fp, "glDepthMask( %s )\n", BooleanToString( flag ) );
+ dllDepthMask( flag );
+}
+
+static void APIENTRY logDepthRange(GLclampd zNear, GLclampd zFar)
+{
+ fprintf( glw_state.log_fp, "glDepthRange( %f, %f )\n", ( float ) zNear, ( float ) zFar );
+ dllDepthRange( zNear, zFar );
+}
+
+static void APIENTRY logDisable(GLenum cap)
+{
+ fprintf( glw_state.log_fp, "glDisable( %s )\n", CapToString( cap ) );
+ dllDisable( cap );
+}
+
+static void APIENTRY logDisableClientState(GLenum array)
+{
+ fprintf( glw_state.log_fp, "glDisableClientState( %s )\n", CapToString( array ) );
+ dllDisableClientState( array );
+}
+
+static void APIENTRY logDrawArrays(GLenum mode, GLint first, GLsizei count)
+{
+ SIG( "glDrawArrays" );
+ dllDrawArrays( mode, first, count );
+}
+
+static void APIENTRY logDrawBuffer(GLenum mode)
+{
+ SIG( "glDrawBuffer" );
+ dllDrawBuffer( mode );
+}
+
+static void APIENTRY logDrawElements(GLenum mode, GLsizei count, GLenum type, const void *indices)
+{
+ fprintf( glw_state.log_fp, "glDrawElements( %s, %d, %s, MEM )\n", PrimToString( mode ), count, TypeToString( type ) );
+ dllDrawElements( mode, count, type, indices );
+}
+
+static void APIENTRY logDrawPixels(GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels)
+{
+ SIG( "glDrawPixels" );
+ dllDrawPixels( width, height, format, type, pixels );
+}
+
+static void APIENTRY logEdgeFlag(GLboolean flag)
+{
+ SIG( "glEdgeFlag" );
+ dllEdgeFlag( flag );
+}
+
+static void APIENTRY logEdgeFlagPointer(GLsizei stride, const void *pointer)
+{
+ SIG( "glEdgeFlagPointer" );
+ dllEdgeFlagPointer( stride, pointer );
+}
+
+static void APIENTRY logEdgeFlagv(const GLboolean *flag)
+{
+ SIG( "glEdgeFlagv" );
+ dllEdgeFlagv( flag );
+}
+
+static void APIENTRY logEnable(GLenum cap)
+{
+ fprintf( glw_state.log_fp, "glEnable( %s )\n", CapToString( cap ) );
+ dllEnable( cap );
+}
+
+static void APIENTRY logEnableClientState(GLenum array)
+{
+ fprintf( glw_state.log_fp, "glEnableClientState( %s )\n", CapToString( array ) );
+ dllEnableClientState( array );
+}
+
+static void APIENTRY logEnd(void)
+{
+ SIG( "glEnd" );
+ dllEnd();
+}
+
+static void APIENTRY logEndList(void)
+{
+ SIG( "glEndList" );
+ dllEndList();
+}
+
+static void APIENTRY logEvalCoord1d(GLdouble u)
+{
+ SIG( "glEvalCoord1d" );
+ dllEvalCoord1d( u );
+}
+
+static void APIENTRY logEvalCoord1dv(const GLdouble *u)
+{
+ SIG( "glEvalCoord1dv" );
+ dllEvalCoord1dv( u );
+}
+
+static void APIENTRY logEvalCoord1f(GLfloat u)
+{
+ SIG( "glEvalCoord1f" );
+ dllEvalCoord1f( u );
+}
+
+static void APIENTRY logEvalCoord1fv(const GLfloat *u)
+{
+ SIG( "glEvalCoord1fv" );
+ dllEvalCoord1fv( u );
+}
+static void APIENTRY logEvalCoord2d(GLdouble u, GLdouble v)
+{
+ SIG( "glEvalCoord2d" );
+ dllEvalCoord2d( u, v );
+}
+static void APIENTRY logEvalCoord2dv(const GLdouble *u)
+{
+ SIG( "glEvalCoord2dv" );
+ dllEvalCoord2dv( u );
+}
+static void APIENTRY logEvalCoord2f(GLfloat u, GLfloat v)
+{
+ SIG( "glEvalCoord2f" );
+ dllEvalCoord2f( u, v );
+}
+static void APIENTRY logEvalCoord2fv(const GLfloat *u)
+{
+ SIG( "glEvalCoord2fv" );
+ dllEvalCoord2fv( u );
+}
+
+static void APIENTRY logEvalMesh1(GLenum mode, GLint i1, GLint i2)
+{
+ SIG( "glEvalMesh1" );
+ dllEvalMesh1( mode, i1, i2 );
+}
+static void APIENTRY logEvalMesh2(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2)
+{
+ SIG( "glEvalMesh2" );
+ dllEvalMesh2( mode, i1, i2, j1, j2 );
+}
+static void APIENTRY logEvalPoint1(GLint i)
+{
+ SIG( "glEvalPoint1" );
+ dllEvalPoint1( i );
+}
+static void APIENTRY logEvalPoint2(GLint i, GLint j)
+{
+ SIG( "glEvalPoint2" );
+ dllEvalPoint2( i, j );
+}
+
+static void APIENTRY logFeedbackBuffer(GLsizei size, GLenum type, GLfloat *buffer)
+{
+ SIG( "glFeedbackBuffer" );
+ dllFeedbackBuffer( size, type, buffer );
+}
+
+static void APIENTRY logFinish(void)
+{
+ SIG( "glFinish" );
+ dllFinish();
+}
+
+static void APIENTRY logFlush(void)
+{
+ SIG( "glFlush" );
+ dllFlush();
+}
+
+static void APIENTRY logFogf(GLenum pname, GLfloat param)
+{
+ SIG( "glFogf" );
+ dllFogf( pname, param );
+}
+
+static void APIENTRY logFogfv(GLenum pname, const GLfloat *params)
+{
+ SIG( "glFogfv" );
+ dllFogfv( pname, params );
+}
+
+static void APIENTRY logFogi(GLenum pname, GLint param)
+{
+ SIG( "glFogi" );
+ dllFogi( pname, param );
+}
+
+static void APIENTRY logFogiv(GLenum pname, const GLint *params)
+{
+ SIG( "glFogiv" );
+ dllFogiv( pname, params );
+}
+
+static void APIENTRY logFrontFace(GLenum mode)
+{
+ SIG( "glFrontFace" );
+ dllFrontFace( mode );
+}
+
+static void APIENTRY logFrustum(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar)
+{
+ SIG( "glFrustum" );
+ dllFrustum( left, right, bottom, top, zNear, zFar );
+}
+
+static GLuint APIENTRY logGenLists(GLsizei range)
+{
+ SIG( "glGenLists" );
+ return dllGenLists( range );
+}
+
+static void APIENTRY logGenTextures(GLsizei n, GLuint *textures)
+{
+ SIG( "glGenTextures" );
+ dllGenTextures( n, textures );
+}
+
+static void APIENTRY logGetBooleanv(GLenum pname, GLboolean *params)
+{
+ SIG( "glGetBooleanv" );
+ dllGetBooleanv( pname, params );
+}
+
+static void APIENTRY logGetClipPlane(GLenum plane, GLdouble *equation)
+{
+ SIG( "glGetClipPlane" );
+ dllGetClipPlane( plane, equation );
+}
+
+static void APIENTRY logGetDoublev(GLenum pname, GLdouble *params)
+{
+ SIG( "glGetDoublev" );
+ dllGetDoublev( pname, params );
+}
+
+static GLenum APIENTRY logGetError(void)
+{
+ SIG( "glGetError" );
+ return dllGetError();
+}
+
+static void APIENTRY logGetFloatv(GLenum pname, GLfloat *params)
+{
+ SIG( "glGetFloatv" );
+ dllGetFloatv( pname, params );
+}
+
+static void APIENTRY logGetIntegerv(GLenum pname, GLint *params)
+{
+ SIG( "glGetIntegerv" );
+ dllGetIntegerv( pname, params );
+}
+
+static void APIENTRY logGetLightfv(GLenum light, GLenum pname, GLfloat *params)
+{
+ SIG( "glGetLightfv" );
+ dllGetLightfv( light, pname, params );
+}
+
+static void APIENTRY logGetLightiv(GLenum light, GLenum pname, GLint *params)
+{
+ SIG( "glGetLightiv" );
+ dllGetLightiv( light, pname, params );
+}
+
+static void APIENTRY logGetMapdv(GLenum target, GLenum query, GLdouble *v)
+{
+ SIG( "glGetMapdv" );
+ dllGetMapdv( target, query, v );
+}
+
+static void APIENTRY logGetMapfv(GLenum target, GLenum query, GLfloat *v)
+{
+ SIG( "glGetMapfv" );
+ dllGetMapfv( target, query, v );
+}
+
+static void APIENTRY logGetMapiv(GLenum target, GLenum query, GLint *v)
+{
+ SIG( "glGetMapiv" );
+ dllGetMapiv( target, query, v );
+}
+
+static void APIENTRY logGetMaterialfv(GLenum face, GLenum pname, GLfloat *params)
+{
+ SIG( "glGetMaterialfv" );
+ dllGetMaterialfv( face, pname, params );
+}
+
+static void APIENTRY logGetMaterialiv(GLenum face, GLenum pname, GLint *params)
+{
+ SIG( "glGetMaterialiv" );
+ dllGetMaterialiv( face, pname, params );
+}
+
+static void APIENTRY logGetPixelMapfv(GLenum map, GLfloat *values)
+{
+ SIG( "glGetPixelMapfv" );
+ dllGetPixelMapfv( map, values );
+}
+
+static void APIENTRY logGetPixelMapuiv(GLenum map, GLuint *values)
+{
+ SIG( "glGetPixelMapuiv" );
+ dllGetPixelMapuiv( map, values );
+}
+
+static void APIENTRY logGetPixelMapusv(GLenum map, GLushort *values)
+{
+ SIG( "glGetPixelMapusv" );
+ dllGetPixelMapusv( map, values );
+}
+
+static void APIENTRY logGetPointerv(GLenum pname, GLvoid* *params)
+{
+ SIG( "glGetPointerv" );
+ dllGetPointerv( pname, params );
+}
+
+static void APIENTRY logGetPolygonStipple(GLubyte *mask)
+{
+ SIG( "glGetPolygonStipple" );
+ dllGetPolygonStipple( mask );
+}
+
+static const GLubyte * APIENTRY logGetString(GLenum name)
+{
+ SIG( "glGetString" );
+ return dllGetString( name );
+}
+
+static void APIENTRY logGetTexEnvfv(GLenum target, GLenum pname, GLfloat *params)
+{
+ SIG( "glGetTexEnvfv" );
+ dllGetTexEnvfv( target, pname, params );
+}
+
+static void APIENTRY logGetTexEnviv(GLenum target, GLenum pname, GLint *params)
+{
+ SIG( "glGetTexEnviv" );
+ dllGetTexEnviv( target, pname, params );
+}
+
+static void APIENTRY logGetTexGendv(GLenum coord, GLenum pname, GLdouble *params)
+{
+ SIG( "glGetTexGendv" );
+ dllGetTexGendv( coord, pname, params );
+}
+
+static void APIENTRY logGetTexGenfv(GLenum coord, GLenum pname, GLfloat *params)
+{
+ SIG( "glGetTexGenfv" );
+ dllGetTexGenfv( coord, pname, params );
+}
+
+static void APIENTRY logGetTexGeniv(GLenum coord, GLenum pname, GLint *params)
+{
+ SIG( "glGetTexGeniv" );
+ dllGetTexGeniv( coord, pname, params );
+}
+
+static void APIENTRY logGetTexImage(GLenum target, GLint level, GLenum format, GLenum type, void *pixels)
+{
+ SIG( "glGetTexImage" );
+ dllGetTexImage( target, level, format, type, pixels );
+}
+static void APIENTRY logGetTexLevelParameterfv(GLenum target, GLint level, GLenum pname, GLfloat *params )
+{
+ SIG( "glGetTexLevelParameterfv" );
+ dllGetTexLevelParameterfv( target, level, pname, params );
+}
+
+static void APIENTRY logGetTexLevelParameteriv(GLenum target, GLint level, GLenum pname, GLint *params)
+{
+ SIG( "glGetTexLevelParameteriv" );
+ dllGetTexLevelParameteriv( target, level, pname, params );
+}
+
+static void APIENTRY logGetTexParameterfv(GLenum target, GLenum pname, GLfloat *params)
+{
+ SIG( "glGetTexParameterfv" );
+ dllGetTexParameterfv( target, pname, params );
+}
+
+static void APIENTRY logGetTexParameteriv(GLenum target, GLenum pname, GLint *params)
+{
+ SIG( "glGetTexParameteriv" );
+ dllGetTexParameteriv( target, pname, params );
+}
+
+static void APIENTRY logHint(GLenum target, GLenum mode)
+{
+ fprintf( glw_state.log_fp, "glHint( 0x%x, 0x%x )\n", target, mode );
+ dllHint( target, mode );
+}
+
+static void APIENTRY logIndexMask(GLuint mask)
+{
+ SIG( "glIndexMask" );
+ dllIndexMask( mask );
+}
+
+static void APIENTRY logIndexPointer(GLenum type, GLsizei stride, const void *pointer)
+{
+ SIG( "glIndexPointer" );
+ dllIndexPointer( type, stride, pointer );
+}
+
+static void APIENTRY logIndexd(GLdouble c)
+{
+ SIG( "glIndexd" );
+ dllIndexd( c );
+}
+
+static void APIENTRY logIndexdv(const GLdouble *c)
+{
+ SIG( "glIndexdv" );
+ dllIndexdv( c );
+}
+
+static void APIENTRY logIndexf(GLfloat c)
+{
+ SIG( "glIndexf" );
+ dllIndexf( c );
+}
+
+static void APIENTRY logIndexfv(const GLfloat *c)
+{
+ SIG( "glIndexfv" );
+ dllIndexfv( c );
+}
+
+static void APIENTRY logIndexi(GLint c)
+{
+ SIG( "glIndexi" );
+ dllIndexi( c );
+}
+
+static void APIENTRY logIndexiv(const GLint *c)
+{
+ SIG( "glIndexiv" );
+ dllIndexiv( c );
+}
+
+static void APIENTRY logIndexs(GLshort c)
+{
+ SIG( "glIndexs" );
+ dllIndexs( c );
+}
+
+static void APIENTRY logIndexsv(const GLshort *c)
+{
+ SIG( "glIndexsv" );
+ dllIndexsv( c );
+}
+
+static void APIENTRY logIndexub(GLubyte c)
+{
+ SIG( "glIndexub" );
+ dllIndexub( c );
+}
+
+static void APIENTRY logIndexubv(const GLubyte *c)
+{
+ SIG( "glIndexubv" );
+ dllIndexubv( c );
+}
+
+static void APIENTRY logInitNames(void)
+{
+ SIG( "glInitNames" );
+ dllInitNames();
+}
+
+static void APIENTRY logInterleavedArrays(GLenum format, GLsizei stride, const void *pointer)
+{
+ SIG( "glInterleavedArrays" );
+ dllInterleavedArrays( format, stride, pointer );
+}
+
+static GLboolean APIENTRY logIsEnabled(GLenum cap)
+{
+ SIG( "glIsEnabled" );
+ return dllIsEnabled( cap );
+}
+static GLboolean APIENTRY logIsList(GLuint list)
+{
+ SIG( "glIsList" );
+ return dllIsList( list );
+}
+static GLboolean APIENTRY logIsTexture(GLuint texture)
+{
+ SIG( "glIsTexture" );
+ return dllIsTexture( texture );
+}
+
+static void APIENTRY logLightModelf(GLenum pname, GLfloat param)
+{
+ SIG( "glLightModelf" );
+ dllLightModelf( pname, param );
+}
+
+static void APIENTRY logLightModelfv(GLenum pname, const GLfloat *params)
+{
+ SIG( "glLightModelfv" );
+ dllLightModelfv( pname, params );
+}
+
+static void APIENTRY logLightModeli(GLenum pname, GLint param)
+{
+ SIG( "glLightModeli" );
+ dllLightModeli( pname, param );
+
+}
+
+static void APIENTRY logLightModeliv(GLenum pname, const GLint *params)
+{
+ SIG( "glLightModeliv" );
+ dllLightModeliv( pname, params );
+}
+
+static void APIENTRY logLightf(GLenum light, GLenum pname, GLfloat param)
+{
+ SIG( "glLightf" );
+ dllLightf( light, pname, param );
+}
+
+static void APIENTRY logLightfv(GLenum light, GLenum pname, const GLfloat *params)
+{
+ SIG( "glLightfv" );
+ dllLightfv( light, pname, params );
+}
+
+static void APIENTRY logLighti(GLenum light, GLenum pname, GLint param)
+{
+ SIG( "glLighti" );
+ dllLighti( light, pname, param );
+}
+
+static void APIENTRY logLightiv(GLenum light, GLenum pname, const GLint *params)
+{
+ SIG( "glLightiv" );
+ dllLightiv( light, pname, params );
+}
+
+static void APIENTRY logLineStipple(GLint factor, GLushort pattern)
+{
+ SIG( "glLineStipple" );
+ dllLineStipple( factor, pattern );
+}
+
+static void APIENTRY logLineWidth(GLfloat width)
+{
+ SIG( "glLineWidth" );
+ dllLineWidth( width );
+}
+
+static void APIENTRY logListBase(GLuint base)
+{
+ SIG( "glListBase" );
+ dllListBase( base );
+}
+
+static void APIENTRY logLoadIdentity(void)
+{
+ SIG( "glLoadIdentity" );
+ dllLoadIdentity();
+}
+
+static void APIENTRY logLoadMatrixd(const GLdouble *m)
+{
+ SIG( "glLoadMatrixd" );
+ dllLoadMatrixd( m );
+}
+
+static void APIENTRY logLoadMatrixf(const GLfloat *m)
+{
+ SIG( "glLoadMatrixf" );
+ dllLoadMatrixf( m );
+}
+
+static void APIENTRY logLoadName(GLuint name)
+{
+ SIG( "glLoadName" );
+ dllLoadName( name );
+}
+
+static void APIENTRY logLogicOp(GLenum opcode)
+{
+ SIG( "glLogicOp" );
+ dllLogicOp( opcode );
+}
+
+static void APIENTRY logMap1d(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points)
+{
+ SIG( "glMap1d" );
+ dllMap1d( target, u1, u2, stride, order, points );
+}
+
+static void APIENTRY logMap1f(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points)
+{
+ SIG( "glMap1f" );
+ dllMap1f( target, u1, u2, stride, order, points );
+}
+
+static void APIENTRY logMap2d(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points)
+{
+ SIG( "glMap2d" );
+ dllMap2d( target, u1, u2, ustride, uorder, v1, v2, vstride, vorder, points );
+}
+
+static void APIENTRY logMap2f(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points)
+{
+ SIG( "glMap2f" );
+ dllMap2f( target, u1, u2, ustride, uorder, v1, v2, vstride, vorder, points );
+}
+
+static void APIENTRY logMapGrid1d(GLint un, GLdouble u1, GLdouble u2)
+{
+ SIG( "glMapGrid1d" );
+ dllMapGrid1d( un, u1, u2 );
+}
+
+static void APIENTRY logMapGrid1f(GLint un, GLfloat u1, GLfloat u2)
+{
+ SIG( "glMapGrid1f" );
+ dllMapGrid1f( un, u1, u2 );
+}
+
+static void APIENTRY logMapGrid2d(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2)
+{
+ SIG( "glMapGrid2d" );
+ dllMapGrid2d( un, u1, u2, vn, v1, v2 );
+}
+static void APIENTRY logMapGrid2f(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2)
+{
+ SIG( "glMapGrid2f" );
+ dllMapGrid2f( un, u1, u2, vn, v1, v2 );
+}
+static void APIENTRY logMaterialf(GLenum face, GLenum pname, GLfloat param)
+{
+ SIG( "glMaterialf" );
+ dllMaterialf( face, pname, param );
+}
+static void APIENTRY logMaterialfv(GLenum face, GLenum pname, const GLfloat *params)
+{
+ SIG( "glMaterialfv" );
+ dllMaterialfv( face, pname, params );
+}
+
+static void APIENTRY logMateriali(GLenum face, GLenum pname, GLint param)
+{
+ SIG( "glMateriali" );
+ dllMateriali( face, pname, param );
+}
+
+static void APIENTRY logMaterialiv(GLenum face, GLenum pname, const GLint *params)
+{
+ SIG( "glMaterialiv" );
+ dllMaterialiv( face, pname, params );
+}
+
+static void APIENTRY logMatrixMode(GLenum mode)
+{
+ SIG( "glMatrixMode" );
+ dllMatrixMode( mode );
+}
+
+static void APIENTRY logMultMatrixd(const GLdouble *m)
+{
+ SIG( "glMultMatrixd" );
+ dllMultMatrixd( m );
+}
+
+static void APIENTRY logMultMatrixf(const GLfloat *m)
+{
+ SIG( "glMultMatrixf" );
+ dllMultMatrixf( m );
+}
+
+static void APIENTRY logNewList(GLuint list, GLenum mode)
+{
+ SIG( "glNewList" );
+ dllNewList( list, mode );
+}
+
+static void APIENTRY logNormal3b(GLbyte nx, GLbyte ny, GLbyte nz)
+{
+ SIG ("glNormal3b" );
+ dllNormal3b( nx, ny, nz );
+}
+
+static void APIENTRY logNormal3bv(const GLbyte *v)
+{
+ SIG( "glNormal3bv" );
+ dllNormal3bv( v );
+}
+
+static void APIENTRY logNormal3d(GLdouble nx, GLdouble ny, GLdouble nz)
+{
+ SIG( "glNormal3d" );
+ dllNormal3d( nx, ny, nz );
+}
+
+static void APIENTRY logNormal3dv(const GLdouble *v)
+{
+ SIG( "glNormal3dv" );
+ dllNormal3dv( v );
+}
+
+static void APIENTRY logNormal3f(GLfloat nx, GLfloat ny, GLfloat nz)
+{
+ SIG( "glNormal3f" );
+ dllNormal3f( nx, ny, nz );
+}
+
+static void APIENTRY logNormal3fv(const GLfloat *v)
+{
+ SIG( "glNormal3fv" );
+ dllNormal3fv( v );
+}
+static void APIENTRY logNormal3i(GLint nx, GLint ny, GLint nz)
+{
+ SIG( "glNormal3i" );
+ dllNormal3i( nx, ny, nz );
+}
+static void APIENTRY logNormal3iv(const GLint *v)
+{
+ SIG( "glNormal3iv" );
+ dllNormal3iv( v );
+}
+static void APIENTRY logNormal3s(GLshort nx, GLshort ny, GLshort nz)
+{
+ SIG( "glNormal3s" );
+ dllNormal3s( nx, ny, nz );
+}
+static void APIENTRY logNormal3sv(const GLshort *v)
+{
+ SIG( "glNormal3sv" );
+ dllNormal3sv( v );
+}
+static void APIENTRY logNormalPointer(GLenum type, GLsizei stride, const void *pointer)
+{
+ SIG( "glNormalPointer" );
+ dllNormalPointer( type, stride, pointer );
+}
+static void APIENTRY logOrtho(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar)
+{
+ SIG( "glOrtho" );
+ dllOrtho( left, right, bottom, top, zNear, zFar );
+}
+
+static void APIENTRY logPassThrough(GLfloat token)
+{
+ SIG( "glPassThrough" );
+ dllPassThrough( token );
+}
+
+static void APIENTRY logPixelMapfv(GLenum map, GLsizei mapsize, const GLfloat *values)
+{
+ SIG( "glPixelMapfv" );
+ dllPixelMapfv( map, mapsize, values );
+}
+
+static void APIENTRY logPixelMapuiv(GLenum map, GLsizei mapsize, const GLuint *values)
+{
+ SIG( "glPixelMapuiv" );
+ dllPixelMapuiv( map, mapsize, values );
+}
+
+static void APIENTRY logPixelMapusv(GLenum map, GLsizei mapsize, const GLushort *values)
+{
+ SIG( "glPixelMapusv" );
+ dllPixelMapusv( map, mapsize, values );
+}
+static void APIENTRY logPixelStoref(GLenum pname, GLfloat param)
+{
+ SIG( "glPixelStoref" );
+ dllPixelStoref( pname, param );
+}
+static void APIENTRY logPixelStorei(GLenum pname, GLint param)
+{
+ SIG( "glPixelStorei" );
+ dllPixelStorei( pname, param );
+}
+static void APIENTRY logPixelTransferf(GLenum pname, GLfloat param)
+{
+ SIG( "glPixelTransferf" );
+ dllPixelTransferf( pname, param );
+}
+
+static void APIENTRY logPixelTransferi(GLenum pname, GLint param)
+{
+ SIG( "glPixelTransferi" );
+ dllPixelTransferi( pname, param );
+}
+
+static void APIENTRY logPixelZoom(GLfloat xfactor, GLfloat yfactor)
+{
+ SIG( "glPixelZoom" );
+ dllPixelZoom( xfactor, yfactor );
+}
+
+static void APIENTRY logPointSize(GLfloat size)
+{
+ SIG( "glPointSize" );
+ dllPointSize( size );
+}
+
+static void APIENTRY logPolygonMode(GLenum face, GLenum mode)
+{
+ fprintf( glw_state.log_fp, "glPolygonMode( 0x%x, 0x%x )\n", face, mode );
+ dllPolygonMode( face, mode );
+}
+
+static void APIENTRY logPolygonOffset(GLfloat factor, GLfloat units)
+{
+ SIG( "glPolygonOffset" );
+ dllPolygonOffset( factor, units );
+}
+static void APIENTRY logPolygonStipple(const GLubyte *mask )
+{
+ SIG( "glPolygonStipple" );
+ dllPolygonStipple( mask );
+}
+static void APIENTRY logPopAttrib(void)
+{
+ SIG( "glPopAttrib" );
+ dllPopAttrib();
+}
+
+static void APIENTRY logPopClientAttrib(void)
+{
+ SIG( "glPopClientAttrib" );
+ dllPopClientAttrib();
+}
+
+static void APIENTRY logPopMatrix(void)
+{
+ SIG( "glPopMatrix" );
+ dllPopMatrix();
+}
+
+static void APIENTRY logPopName(void)
+{
+ SIG( "glPopName" );
+ dllPopName();
+}
+
+static void APIENTRY logPrioritizeTextures(GLsizei n, const GLuint *textures, const GLclampf *priorities)
+{
+ SIG( "glPrioritizeTextures" );
+ dllPrioritizeTextures( n, textures, priorities );
+}
+
+static void APIENTRY logPushAttrib(GLbitfield mask)
+{
+ SIG( "glPushAttrib" );
+ dllPushAttrib( mask );
+}
+
+static void APIENTRY logPushClientAttrib(GLbitfield mask)
+{
+ SIG( "glPushClientAttrib" );
+ dllPushClientAttrib( mask );
+}
+
+static void APIENTRY logPushMatrix(void)
+{
+ SIG( "glPushMatrix" );
+ dllPushMatrix();
+}
+
+static void APIENTRY logPushName(GLuint name)
+{
+ SIG( "glPushName" );
+ dllPushName( name );
+}
+
+static void APIENTRY logRasterPos2d(GLdouble x, GLdouble y)
+{
+ SIG ("glRasterPot2d" );
+ dllRasterPos2d( x, y );
+}
+
+static void APIENTRY logRasterPos2dv(const GLdouble *v)
+{
+ SIG( "glRasterPos2dv" );
+ dllRasterPos2dv( v );
+}
+
+static void APIENTRY logRasterPos2f(GLfloat x, GLfloat y)
+{
+ SIG( "glRasterPos2f" );
+ dllRasterPos2f( x, y );
+}
+static void APIENTRY logRasterPos2fv(const GLfloat *v)
+{
+ SIG( "glRasterPos2dv" );
+ dllRasterPos2fv( v );
+}
+static void APIENTRY logRasterPos2i(GLint x, GLint y)
+{
+ SIG( "glRasterPos2if" );
+ dllRasterPos2i( x, y );
+}
+static void APIENTRY logRasterPos2iv(const GLint *v)
+{
+ SIG( "glRasterPos2iv" );
+ dllRasterPos2iv( v );
+}
+static void APIENTRY logRasterPos2s(GLshort x, GLshort y)
+{
+ SIG( "glRasterPos2s" );
+ dllRasterPos2s( x, y );
+}
+static void APIENTRY logRasterPos2sv(const GLshort *v)
+{
+ SIG( "glRasterPos2sv" );
+ dllRasterPos2sv( v );
+}
+static void APIENTRY logRasterPos3d(GLdouble x, GLdouble y, GLdouble z)
+{
+ SIG( "glRasterPos3d" );
+ dllRasterPos3d( x, y, z );
+}
+static void APIENTRY logRasterPos3dv(const GLdouble *v)
+{
+ SIG( "glRasterPos3dv" );
+ dllRasterPos3dv( v );
+}
+static void APIENTRY logRasterPos3f(GLfloat x, GLfloat y, GLfloat z)
+{
+ SIG( "glRasterPos3f" );
+ dllRasterPos3f( x, y, z );
+}
+static void APIENTRY logRasterPos3fv(const GLfloat *v)
+{
+ SIG( "glRasterPos3fv" );
+ dllRasterPos3fv( v );
+}
+static void APIENTRY logRasterPos3i(GLint x, GLint y, GLint z)
+{
+ SIG( "glRasterPos3i" );
+ dllRasterPos3i( x, y, z );
+}
+static void APIENTRY logRasterPos3iv(const GLint *v)
+{
+ SIG( "glRasterPos3iv" );
+ dllRasterPos3iv( v );
+}
+static void APIENTRY logRasterPos3s(GLshort x, GLshort y, GLshort z)
+{
+ SIG( "glRasterPos3s" );
+ dllRasterPos3s( x, y, z );
+}
+static void APIENTRY logRasterPos3sv(const GLshort *v)
+{
+ SIG( "glRasterPos3sv" );
+ dllRasterPos3sv( v );
+}
+static void APIENTRY logRasterPos4d(GLdouble x, GLdouble y, GLdouble z, GLdouble w)
+{
+ SIG( "glRasterPos4d" );
+ dllRasterPos4d( x, y, z, w );
+}
+static void APIENTRY logRasterPos4dv(const GLdouble *v)
+{
+ SIG( "glRasterPos4dv" );
+ dllRasterPos4dv( v );
+}
+static void APIENTRY logRasterPos4f(GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+ SIG( "glRasterPos4f" );
+ dllRasterPos4f( x, y, z, w );
+}
+static void APIENTRY logRasterPos4fv(const GLfloat *v)
+{
+ SIG( "glRasterPos4fv" );
+ dllRasterPos4fv( v );
+}
+static void APIENTRY logRasterPos4i(GLint x, GLint y, GLint z, GLint w)
+{
+ SIG( "glRasterPos4i" );
+ dllRasterPos4i( x, y, z, w );
+}
+static void APIENTRY logRasterPos4iv(const GLint *v)
+{
+ SIG( "glRasterPos4iv" );
+ dllRasterPos4iv( v );
+}
+static void APIENTRY logRasterPos4s(GLshort x, GLshort y, GLshort z, GLshort w)
+{
+ SIG( "glRasterPos4s" );
+ dllRasterPos4s( x, y, z, w );
+}
+static void APIENTRY logRasterPos4sv(const GLshort *v)
+{
+ SIG( "glRasterPos4sv" );
+ dllRasterPos4sv( v );
+}
+static void APIENTRY logReadBuffer(GLenum mode)
+{
+ SIG( "glReadBuffer" );
+ dllReadBuffer( mode );
+}
+static void APIENTRY logReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels)
+{
+ SIG( "glReadPixels" );
+ dllReadPixels( x, y, width, height, format, type, pixels );
+}
+
+static void APIENTRY logRectd(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2)
+{
+ SIG( "glRectd" );
+ dllRectd( x1, y1, x2, y2 );
+}
+
+static void APIENTRY logRectdv(const GLdouble *v1, const GLdouble *v2)
+{
+ SIG( "glRectdv" );
+ dllRectdv( v1, v2 );
+}
+
+static void APIENTRY logRectf(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2)
+{
+ SIG( "glRectf" );
+ dllRectf( x1, y1, x2, y2 );
+}
+
+static void APIENTRY logRectfv(const GLfloat *v1, const GLfloat *v2)
+{
+ SIG( "glRectfv" );
+ dllRectfv( v1, v2 );
+}
+static void APIENTRY logRecti(GLint x1, GLint y1, GLint x2, GLint y2)
+{
+ SIG( "glRecti" );
+ dllRecti( x1, y1, x2, y2 );
+}
+static void APIENTRY logRectiv(const GLint *v1, const GLint *v2)
+{
+ SIG( "glRectiv" );
+ dllRectiv( v1, v2 );
+}
+static void APIENTRY logRects(GLshort x1, GLshort y1, GLshort x2, GLshort y2)
+{
+ SIG( "glRects" );
+ dllRects( x1, y1, x2, y2 );
+}
+static void APIENTRY logRectsv(const GLshort *v1, const GLshort *v2)
+{
+ SIG( "glRectsv" );
+ dllRectsv( v1, v2 );
+}
+static GLint APIENTRY logRenderMode(GLenum mode)
+{
+ SIG( "glRenderMode" );
+ return dllRenderMode( mode );
+}
+static void APIENTRY logRotated(GLdouble angle, GLdouble x, GLdouble y, GLdouble z)
+{
+ SIG( "glRotated" );
+ dllRotated( angle, x, y, z );
+}
+
+static void APIENTRY logRotatef(GLfloat angle, GLfloat x, GLfloat y, GLfloat z)
+{
+ SIG( "glRotatef" );
+ dllRotatef( angle, x, y, z );
+}
+
+static void APIENTRY logScaled(GLdouble x, GLdouble y, GLdouble z)
+{
+ SIG( "glScaled" );
+ dllScaled( x, y, z );
+}
+
+static void APIENTRY logScalef(GLfloat x, GLfloat y, GLfloat z)
+{
+ SIG( "glScalef" );
+ dllScalef( x, y, z );
+}
+
+static void APIENTRY logScissor(GLint x, GLint y, GLsizei width, GLsizei height)
+{
+ fprintf( glw_state.log_fp, "glScissor( %d, %d, %d, %d )\n", x, y, width, height );
+ dllScissor( x, y, width, height );
+}
+
+static void APIENTRY logSelectBuffer(GLsizei size, GLuint *buffer)
+{
+ SIG( "glSelectBuffer" );
+ dllSelectBuffer( size, buffer );
+}
+
+static void APIENTRY logShadeModel(GLenum mode)
+{
+ SIG( "glShadeModel" );
+ dllShadeModel( mode );
+}
+
+static void APIENTRY logStencilFunc(GLenum func, GLint ref, GLuint mask)
+{
+ SIG( "glStencilFunc" );
+ dllStencilFunc( func, ref, mask );
+}
+
+static void APIENTRY logStencilMask(GLuint mask)
+{
+ SIG( "glStencilMask" );
+ dllStencilMask( mask );
+}
+
+static void APIENTRY logStencilOp(GLenum fail, GLenum zfail, GLenum zpass)
+{
+ SIG( "glStencilOp" );
+ dllStencilOp( fail, zfail, zpass );
+}
+
+static void APIENTRY logTexCoord1d(GLdouble s)
+{
+ SIG( "glTexCoord1d" );
+ dllTexCoord1d( s );
+}
+
+static void APIENTRY logTexCoord1dv(const GLdouble *v)
+{
+ SIG( "glTexCoord1dv" );
+ dllTexCoord1dv( v );
+}
+
+static void APIENTRY logTexCoord1f(GLfloat s)
+{
+ SIG( "glTexCoord1f" );
+ dllTexCoord1f( s );
+}
+static void APIENTRY logTexCoord1fv(const GLfloat *v)
+{
+ SIG( "glTexCoord1fv" );
+ dllTexCoord1fv( v );
+}
+static void APIENTRY logTexCoord1i(GLint s)
+{
+ SIG( "glTexCoord1i" );
+ dllTexCoord1i( s );
+}
+static void APIENTRY logTexCoord1iv(const GLint *v)
+{
+ SIG( "glTexCoord1iv" );
+ dllTexCoord1iv( v );
+}
+static void APIENTRY logTexCoord1s(GLshort s)
+{
+ SIG( "glTexCoord1s" );
+ dllTexCoord1s( s );
+}
+static void APIENTRY logTexCoord1sv(const GLshort *v)
+{
+ SIG( "glTexCoord1sv" );
+ dllTexCoord1sv( v );
+}
+static void APIENTRY logTexCoord2d(GLdouble s, GLdouble t)
+{
+ SIG( "glTexCoord2d" );
+ dllTexCoord2d( s, t );
+}
+
+static void APIENTRY logTexCoord2dv(const GLdouble *v)
+{
+ SIG( "glTexCoord2dv" );
+ dllTexCoord2dv( v );
+}
+static void APIENTRY logTexCoord2f(GLfloat s, GLfloat t)
+{
+ SIG( "glTexCoord2f" );
+ dllTexCoord2f( s, t );
+}
+static void APIENTRY logTexCoord2fv(const GLfloat *v)
+{
+ SIG( "glTexCoord2fv" );
+ dllTexCoord2fv( v );
+}
+static void APIENTRY logTexCoord2i(GLint s, GLint t)
+{
+ SIG( "glTexCoord2i" );
+ dllTexCoord2i( s, t );
+}
+static void APIENTRY logTexCoord2iv(const GLint *v)
+{
+ SIG( "glTexCoord2iv" );
+ dllTexCoord2iv( v );
+}
+static void APIENTRY logTexCoord2s(GLshort s, GLshort t)
+{
+ SIG( "glTexCoord2s" );
+ dllTexCoord2s( s, t );
+}
+static void APIENTRY logTexCoord2sv(const GLshort *v)
+{
+ SIG( "glTexCoord2sv" );
+ dllTexCoord2sv( v );
+}
+static void APIENTRY logTexCoord3d(GLdouble s, GLdouble t, GLdouble r)
+{
+ SIG( "glTexCoord3d" );
+ dllTexCoord3d( s, t, r );
+}
+static void APIENTRY logTexCoord3dv(const GLdouble *v)
+{
+ SIG( "glTexCoord3dv" );
+ dllTexCoord3dv( v );
+}
+static void APIENTRY logTexCoord3f(GLfloat s, GLfloat t, GLfloat r)
+{
+ SIG( "glTexCoord3f" );
+ dllTexCoord3f( s, t, r );
+}
+static void APIENTRY logTexCoord3fv(const GLfloat *v)
+{
+ SIG( "glTexCoord3fv" );
+ dllTexCoord3fv( v );
+}
+static void APIENTRY logTexCoord3i(GLint s, GLint t, GLint r)
+{
+ SIG( "glTexCoord3i" );
+ dllTexCoord3i( s, t, r );
+}
+static void APIENTRY logTexCoord3iv(const GLint *v)
+{
+ SIG( "glTexCoord3iv" );
+ dllTexCoord3iv( v );
+}
+static void APIENTRY logTexCoord3s(GLshort s, GLshort t, GLshort r)
+{
+ SIG( "glTexCoord3s" );
+ dllTexCoord3s( s, t, r );
+}
+static void APIENTRY logTexCoord3sv(const GLshort *v)
+{
+ SIG( "glTexCoord3sv" );
+ dllTexCoord3sv( v );
+}
+static void APIENTRY logTexCoord4d(GLdouble s, GLdouble t, GLdouble r, GLdouble q)
+{
+ SIG( "glTexCoord4d" );
+ dllTexCoord4d( s, t, r, q );
+}
+static void APIENTRY logTexCoord4dv(const GLdouble *v)
+{
+ SIG( "glTexCoord4dv" );
+ dllTexCoord4dv( v );
+}
+static void APIENTRY logTexCoord4f(GLfloat s, GLfloat t, GLfloat r, GLfloat q)
+{
+ SIG( "glTexCoord4f" );
+ dllTexCoord4f( s, t, r, q );
+}
+static void APIENTRY logTexCoord4fv(const GLfloat *v)
+{
+ SIG( "glTexCoord4fv" );
+ dllTexCoord4fv( v );
+}
+static void APIENTRY logTexCoord4i(GLint s, GLint t, GLint r, GLint q)
+{
+ SIG( "glTexCoord4i" );
+ dllTexCoord4i( s, t, r, q );
+}
+static void APIENTRY logTexCoord4iv(const GLint *v)
+{
+ SIG( "glTexCoord4iv" );
+ dllTexCoord4iv( v );
+}
+static void APIENTRY logTexCoord4s(GLshort s, GLshort t, GLshort r, GLshort q)
+{
+ SIG( "glTexCoord4s" );
+ dllTexCoord4s( s, t, r, q );
+}
+static void APIENTRY logTexCoord4sv(const GLshort *v)
+{
+ SIG( "glTexCoord4sv" );
+ dllTexCoord4sv( v );
+}
+static void APIENTRY logTexCoordPointer(GLint size, GLenum type, GLsizei stride, const void *pointer)
+{
+ fprintf( glw_state.log_fp, "glTexCoordPointer( %d, %s, %d, MEM )\n", size, TypeToString( type ), stride );
+ dllTexCoordPointer( size, type, stride, pointer );
+}
+
+static void APIENTRY logTexEnvf(GLenum target, GLenum pname, GLfloat param)
+{
+ fprintf( glw_state.log_fp, "glTexEnvf( 0x%x, 0x%x, %f )\n", target, pname, param );
+ dllTexEnvf( target, pname, param );
+}
+
+static void APIENTRY logTexEnvfv(GLenum target, GLenum pname, const GLfloat *params)
+{
+ SIG( "glTexEnvfv" );
+ dllTexEnvfv( target, pname, params );
+}
+
+static void APIENTRY logTexEnvi(GLenum target, GLenum pname, GLint param)
+{
+ fprintf( glw_state.log_fp, "glTexEnvi( 0x%x, 0x%x, 0x%x )\n", target, pname, param );
+ dllTexEnvi( target, pname, param );
+}
+static void APIENTRY logTexEnviv(GLenum target, GLenum pname, const GLint *params)
+{
+ SIG( "glTexEnviv" );
+ dllTexEnviv( target, pname, params );
+}
+
+static void APIENTRY logTexGend(GLenum coord, GLenum pname, GLdouble param)
+{
+ SIG( "glTexGend" );
+ dllTexGend( coord, pname, param );
+}
+
+static void APIENTRY logTexGendv(GLenum coord, GLenum pname, const GLdouble *params)
+{
+ SIG( "glTexGendv" );
+ dllTexGendv( coord, pname, params );
+}
+
+static void APIENTRY logTexGenf(GLenum coord, GLenum pname, GLfloat param)
+{
+ SIG( "glTexGenf" );
+ dllTexGenf( coord, pname, param );
+}
+static void APIENTRY logTexGenfv(GLenum coord, GLenum pname, const GLfloat *params)
+{
+ SIG( "glTexGenfv" );
+ dllTexGenfv( coord, pname, params );
+}
+static void APIENTRY logTexGeni(GLenum coord, GLenum pname, GLint param)
+{
+ SIG( "glTexGeni" );
+ dllTexGeni( coord, pname, param );
+}
+static void APIENTRY logTexGeniv(GLenum coord, GLenum pname, const GLint *params)
+{
+ SIG( "glTexGeniv" );
+ dllTexGeniv( coord, pname, params );
+}
+static void APIENTRY logTexImage1D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels)
+{
+ SIG( "glTexImage1D" );
+ dllTexImage1D( target, level, internalformat, width, border, format, type, pixels );
+}
+static void APIENTRY logTexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels)
+{
+ SIG( "glTexImage2D" );
+ dllTexImage2D( target, level, internalformat, width, height, border, format, type, pixels );
+}
+
+static void APIENTRY logTexParameterf(GLenum target, GLenum pname, GLfloat param)
+{
+ fprintf( glw_state.log_fp, "glTexParameterf( 0x%x, 0x%x, %f )\n", target, pname, param );
+ dllTexParameterf( target, pname, param );
+}
+
+static void APIENTRY logTexParameterfv(GLenum target, GLenum pname, const GLfloat *params)
+{
+ SIG( "glTexParameterfv" );
+ dllTexParameterfv( target, pname, params );
+}
+static void APIENTRY logTexParameteri(GLenum target, GLenum pname, GLint param)
+{
+ fprintf( glw_state.log_fp, "glTexParameteri( 0x%x, 0x%x, 0x%x )\n", target, pname, param );
+ dllTexParameteri( target, pname, param );
+}
+static void APIENTRY logTexParameteriv(GLenum target, GLenum pname, const GLint *params)
+{
+ SIG( "glTexParameteriv" );
+ dllTexParameteriv( target, pname, params );
+}
+static void APIENTRY logTexSubImage1D(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels)
+{
+ SIG( "glTexSubImage1D" );
+ dllTexSubImage1D( target, level, xoffset, width, format, type, pixels );
+}
+static void APIENTRY logTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels)
+{
+ SIG( "glTexSubImage2D" );
+ dllTexSubImage2D( target, level, xoffset, yoffset, width, height, format, type, pixels );
+}
+static void APIENTRY logTranslated(GLdouble x, GLdouble y, GLdouble z)
+{
+ SIG( "glTranslated" );
+ dllTranslated( x, y, z );
+}
+
+static void APIENTRY logTranslatef(GLfloat x, GLfloat y, GLfloat z)
+{
+ SIG( "glTranslatef" );
+ dllTranslatef( x, y, z );
+}
+
+static void APIENTRY logVertex2d(GLdouble x, GLdouble y)
+{
+ SIG( "glVertex2d" );
+ dllVertex2d( x, y );
+}
+
+static void APIENTRY logVertex2dv(const GLdouble *v)
+{
+ SIG( "glVertex2dv" );
+ dllVertex2dv( v );
+}
+static void APIENTRY logVertex2f(GLfloat x, GLfloat y)
+{
+ SIG( "glVertex2f" );
+ dllVertex2f( x, y );
+}
+static void APIENTRY logVertex2fv(const GLfloat *v)
+{
+ SIG( "glVertex2fv" );
+ dllVertex2fv( v );
+}
+static void APIENTRY logVertex2i(GLint x, GLint y)
+{
+ SIG( "glVertex2i" );
+ dllVertex2i( x, y );
+}
+static void APIENTRY logVertex2iv(const GLint *v)
+{
+ SIG( "glVertex2iv" );
+ dllVertex2iv( v );
+}
+static void APIENTRY logVertex2s(GLshort x, GLshort y)
+{
+ SIG( "glVertex2s" );
+ dllVertex2s( x, y );
+}
+static void APIENTRY logVertex2sv(const GLshort *v)
+{
+ SIG( "glVertex2sv" );
+ dllVertex2sv( v );
+}
+static void APIENTRY logVertex3d(GLdouble x, GLdouble y, GLdouble z)
+{
+ SIG( "glVertex3d" );
+ dllVertex3d( x, y, z );
+}
+static void APIENTRY logVertex3dv(const GLdouble *v)
+{
+ SIG( "glVertex3dv" );
+ dllVertex3dv( v );
+}
+static void APIENTRY logVertex3f(GLfloat x, GLfloat y, GLfloat z)
+{
+ SIG( "glVertex3f" );
+ dllVertex3f( x, y, z );
+}
+static void APIENTRY logVertex3fv(const GLfloat *v)
+{
+ SIG( "glVertex3fv" );
+ dllVertex3fv( v );
+}
+static void APIENTRY logVertex3i(GLint x, GLint y, GLint z)
+{
+ SIG( "glVertex3i" );
+ dllVertex3i( x, y, z );
+}
+static void APIENTRY logVertex3iv(const GLint *v)
+{
+ SIG( "glVertex3iv" );
+ dllVertex3iv( v );
+}
+static void APIENTRY logVertex3s(GLshort x, GLshort y, GLshort z)
+{
+ SIG( "glVertex3s" );
+ dllVertex3s( x, y, z );
+}
+static void APIENTRY logVertex3sv(const GLshort *v)
+{
+ SIG( "glVertex3sv" );
+ dllVertex3sv( v );
+}
+static void APIENTRY logVertex4d(GLdouble x, GLdouble y, GLdouble z, GLdouble w)
+{
+ SIG( "glVertex4d" );
+ dllVertex4d( x, y, z, w );
+}
+static void APIENTRY logVertex4dv(const GLdouble *v)
+{
+ SIG( "glVertex4dv" );
+ dllVertex4dv( v );
+}
+static void APIENTRY logVertex4f(GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+ SIG( "glVertex4f" );
+ dllVertex4f( x, y, z, w );
+}
+static void APIENTRY logVertex4fv(const GLfloat *v)
+{
+ SIG( "glVertex4fv" );
+ dllVertex4fv( v );
+}
+static void APIENTRY logVertex4i(GLint x, GLint y, GLint z, GLint w)
+{
+ SIG( "glVertex4i" );
+ dllVertex4i( x, y, z, w );
+}
+static void APIENTRY logVertex4iv(const GLint *v)
+{
+ SIG( "glVertex4iv" );
+ dllVertex4iv( v );
+}
+static void APIENTRY logVertex4s(GLshort x, GLshort y, GLshort z, GLshort w)
+{
+ SIG( "glVertex4s" );
+ dllVertex4s( x, y, z, w );
+}
+static void APIENTRY logVertex4sv(const GLshort *v)
+{
+ SIG( "glVertex4sv" );
+ dllVertex4sv( v );
+}
+static void APIENTRY logVertexPointer(GLint size, GLenum type, GLsizei stride, const void *pointer)
+{
+ fprintf( glw_state.log_fp, "glVertexPointer( %d, %s, %d, MEM )\n", size, TypeToString( type ), stride );
+ dllVertexPointer( size, type, stride, pointer );
+}
+static void APIENTRY logViewport(GLint x, GLint y, GLsizei width, GLsizei height)
+{
+ fprintf( glw_state.log_fp, "glViewport( %d, %d, %d, %d )\n", x, y, width, height );
+ dllViewport( x, y, width, height );
+}
+
+/*
+** QGL_Shutdown
+**
+** Unloads the specified DLL then nulls out all the proc pointers. This
+** is only called during a hard shutdown of the OGL subsystem (e.g. vid_restart).
+*/
+void QGL_Shutdown( void )
+{
+ ri.Printf( PRINT_ALL, "...shutting down QGL\n" );
+
+ if ( glw_state.hinstOpenGL )
+ {
+ ri.Printf( PRINT_ALL, "...unloading OpenGL DLL\n" );
+ FreeLibrary( glw_state.hinstOpenGL );
+ }
+
+ glw_state.hinstOpenGL = NULL;
+
+ qglAccum = NULL;
+ qglAlphaFunc = NULL;
+ qglAreTexturesResident = NULL;
+ qglArrayElement = NULL;
+ qglBegin = NULL;
+ qglBindTexture = NULL;
+ qglBitmap = NULL;
+ qglBlendFunc = NULL;
+ qglCallList = NULL;
+ qglCallLists = NULL;
+ qglClear = NULL;
+ qglClearAccum = NULL;
+ qglClearColor = NULL;
+ qglClearDepth = NULL;
+ qglClearIndex = NULL;
+ qglClearStencil = NULL;
+ qglClipPlane = NULL;
+ qglColor3b = NULL;
+ qglColor3bv = NULL;
+ qglColor3d = NULL;
+ qglColor3dv = NULL;
+ qglColor3f = NULL;
+ qglColor3fv = NULL;
+ qglColor3i = NULL;
+ qglColor3iv = NULL;
+ qglColor3s = NULL;
+ qglColor3sv = NULL;
+ qglColor3ub = NULL;
+ qglColor3ubv = NULL;
+ qglColor3ui = NULL;
+ qglColor3uiv = NULL;
+ qglColor3us = NULL;
+ qglColor3usv = NULL;
+ qglColor4b = NULL;
+ qglColor4bv = NULL;
+ qglColor4d = NULL;
+ qglColor4dv = NULL;
+ qglColor4f = NULL;
+ qglColor4fv = NULL;
+ qglColor4i = NULL;
+ qglColor4iv = NULL;
+ qglColor4s = NULL;
+ qglColor4sv = NULL;
+ qglColor4ub = NULL;
+ qglColor4ubv = NULL;
+ qglColor4ui = NULL;
+ qglColor4uiv = NULL;
+ qglColor4us = NULL;
+ qglColor4usv = NULL;
+ qglColorMask = NULL;
+ qglColorMaterial = NULL;
+ qglColorPointer = NULL;
+ qglCopyPixels = NULL;
+ qglCopyTexImage1D = NULL;
+ qglCopyTexImage2D = NULL;
+ qglCopyTexSubImage1D = NULL;
+ qglCopyTexSubImage2D = NULL;
+ qglCullFace = NULL;
+ qglDeleteLists = NULL;
+ qglDeleteTextures = NULL;
+ qglDepthFunc = NULL;
+ qglDepthMask = NULL;
+ qglDepthRange = NULL;
+ qglDisable = NULL;
+ qglDisableClientState = NULL;
+ qglDrawArrays = NULL;
+ qglDrawBuffer = NULL;
+ qglDrawElements = NULL;
+ qglDrawPixels = NULL;
+ qglEdgeFlag = NULL;
+ qglEdgeFlagPointer = NULL;
+ qglEdgeFlagv = NULL;
+ qglEnable = NULL;
+ qglEnableClientState = NULL;
+ qglEnd = NULL;
+ qglEndList = NULL;
+ qglEvalCoord1d = NULL;
+ qglEvalCoord1dv = NULL;
+ qglEvalCoord1f = NULL;
+ qglEvalCoord1fv = NULL;
+ qglEvalCoord2d = NULL;
+ qglEvalCoord2dv = NULL;
+ qglEvalCoord2f = NULL;
+ qglEvalCoord2fv = NULL;
+ qglEvalMesh1 = NULL;
+ qglEvalMesh2 = NULL;
+ qglEvalPoint1 = NULL;
+ qglEvalPoint2 = NULL;
+ qglFeedbackBuffer = NULL;
+ qglFinish = NULL;
+ qglFlush = NULL;
+ qglFogf = NULL;
+ qglFogfv = NULL;
+ qglFogi = NULL;
+ qglFogiv = NULL;
+ qglFrontFace = NULL;
+ qglFrustum = NULL;
+ qglGenLists = NULL;
+ qglGenTextures = NULL;
+ qglGetBooleanv = NULL;
+ qglGetClipPlane = NULL;
+ qglGetDoublev = NULL;
+ qglGetError = NULL;
+ qglGetFloatv = NULL;
+ qglGetIntegerv = NULL;
+ qglGetLightfv = NULL;
+ qglGetLightiv = NULL;
+ qglGetMapdv = NULL;
+ qglGetMapfv = NULL;
+ qglGetMapiv = NULL;
+ qglGetMaterialfv = NULL;
+ qglGetMaterialiv = NULL;
+ qglGetPixelMapfv = NULL;
+ qglGetPixelMapuiv = NULL;
+ qglGetPixelMapusv = NULL;
+ qglGetPointerv = NULL;
+ qglGetPolygonStipple = NULL;
+ qglGetString = NULL;
+ qglGetTexEnvfv = NULL;
+ qglGetTexEnviv = NULL;
+ qglGetTexGendv = NULL;
+ qglGetTexGenfv = NULL;
+ qglGetTexGeniv = NULL;
+ qglGetTexImage = NULL;
+ qglGetTexLevelParameterfv = NULL;
+ qglGetTexLevelParameteriv = NULL;
+ qglGetTexParameterfv = NULL;
+ qglGetTexParameteriv = NULL;
+ qglHint = NULL;
+ qglIndexMask = NULL;
+ qglIndexPointer = NULL;
+ qglIndexd = NULL;
+ qglIndexdv = NULL;
+ qglIndexf = NULL;
+ qglIndexfv = NULL;
+ qglIndexi = NULL;
+ qglIndexiv = NULL;
+ qglIndexs = NULL;
+ qglIndexsv = NULL;
+ qglIndexub = NULL;
+ qglIndexubv = NULL;
+ qglInitNames = NULL;
+ qglInterleavedArrays = NULL;
+ qglIsEnabled = NULL;
+ qglIsList = NULL;
+ qglIsTexture = NULL;
+ qglLightModelf = NULL;
+ qglLightModelfv = NULL;
+ qglLightModeli = NULL;
+ qglLightModeliv = NULL;
+ qglLightf = NULL;
+ qglLightfv = NULL;
+ qglLighti = NULL;
+ qglLightiv = NULL;
+ qglLineStipple = NULL;
+ qglLineWidth = NULL;
+ qglListBase = NULL;
+ qglLoadIdentity = NULL;
+ qglLoadMatrixd = NULL;
+ qglLoadMatrixf = NULL;
+ qglLoadName = NULL;
+ qglLogicOp = NULL;
+ qglMap1d = NULL;
+ qglMap1f = NULL;
+ qglMap2d = NULL;
+ qglMap2f = NULL;
+ qglMapGrid1d = NULL;
+ qglMapGrid1f = NULL;
+ qglMapGrid2d = NULL;
+ qglMapGrid2f = NULL;
+ qglMaterialf = NULL;
+ qglMaterialfv = NULL;
+ qglMateriali = NULL;
+ qglMaterialiv = NULL;
+ qglMatrixMode = NULL;
+ qglMultMatrixd = NULL;
+ qglMultMatrixf = NULL;
+ qglNewList = NULL;
+ qglNormal3b = NULL;
+ qglNormal3bv = NULL;
+ qglNormal3d = NULL;
+ qglNormal3dv = NULL;
+ qglNormal3f = NULL;
+ qglNormal3fv = NULL;
+ qglNormal3i = NULL;
+ qglNormal3iv = NULL;
+ qglNormal3s = NULL;
+ qglNormal3sv = NULL;
+ qglNormalPointer = NULL;
+ qglOrtho = NULL;
+ qglPassThrough = NULL;
+ qglPixelMapfv = NULL;
+ qglPixelMapuiv = NULL;
+ qglPixelMapusv = NULL;
+ qglPixelStoref = NULL;
+ qglPixelStorei = NULL;
+ qglPixelTransferf = NULL;
+ qglPixelTransferi = NULL;
+ qglPixelZoom = NULL;
+ qglPointSize = NULL;
+ qglPolygonMode = NULL;
+ qglPolygonOffset = NULL;
+ qglPolygonStipple = NULL;
+ qglPopAttrib = NULL;
+ qglPopClientAttrib = NULL;
+ qglPopMatrix = NULL;
+ qglPopName = NULL;
+ qglPrioritizeTextures = NULL;
+ qglPushAttrib = NULL;
+ qglPushClientAttrib = NULL;
+ qglPushMatrix = NULL;
+ qglPushName = NULL;
+ qglRasterPos2d = NULL;
+ qglRasterPos2dv = NULL;
+ qglRasterPos2f = NULL;
+ qglRasterPos2fv = NULL;
+ qglRasterPos2i = NULL;
+ qglRasterPos2iv = NULL;
+ qglRasterPos2s = NULL;
+ qglRasterPos2sv = NULL;
+ qglRasterPos3d = NULL;
+ qglRasterPos3dv = NULL;
+ qglRasterPos3f = NULL;
+ qglRasterPos3fv = NULL;
+ qglRasterPos3i = NULL;
+ qglRasterPos3iv = NULL;
+ qglRasterPos3s = NULL;
+ qglRasterPos3sv = NULL;
+ qglRasterPos4d = NULL;
+ qglRasterPos4dv = NULL;
+ qglRasterPos4f = NULL;
+ qglRasterPos4fv = NULL;
+ qglRasterPos4i = NULL;
+ qglRasterPos4iv = NULL;
+ qglRasterPos4s = NULL;
+ qglRasterPos4sv = NULL;
+ qglReadBuffer = NULL;
+ qglReadPixels = NULL;
+ qglRectd = NULL;
+ qglRectdv = NULL;
+ qglRectf = NULL;
+ qglRectfv = NULL;
+ qglRecti = NULL;
+ qglRectiv = NULL;
+ qglRects = NULL;
+ qglRectsv = NULL;
+ qglRenderMode = NULL;
+ qglRotated = NULL;
+ qglRotatef = NULL;
+ qglScaled = NULL;
+ qglScalef = NULL;
+ qglScissor = NULL;
+ qglSelectBuffer = NULL;
+ qglShadeModel = NULL;
+ qglStencilFunc = NULL;
+ qglStencilMask = NULL;
+ qglStencilOp = NULL;
+ qglTexCoord1d = NULL;
+ qglTexCoord1dv = NULL;
+ qglTexCoord1f = NULL;
+ qglTexCoord1fv = NULL;
+ qglTexCoord1i = NULL;
+ qglTexCoord1iv = NULL;
+ qglTexCoord1s = NULL;
+ qglTexCoord1sv = NULL;
+ qglTexCoord2d = NULL;
+ qglTexCoord2dv = NULL;
+ qglTexCoord2f = NULL;
+ qglTexCoord2fv = NULL;
+ qglTexCoord2i = NULL;
+ qglTexCoord2iv = NULL;
+ qglTexCoord2s = NULL;
+ qglTexCoord2sv = NULL;
+ qglTexCoord3d = NULL;
+ qglTexCoord3dv = NULL;
+ qglTexCoord3f = NULL;
+ qglTexCoord3fv = NULL;
+ qglTexCoord3i = NULL;
+ qglTexCoord3iv = NULL;
+ qglTexCoord3s = NULL;
+ qglTexCoord3sv = NULL;
+ qglTexCoord4d = NULL;
+ qglTexCoord4dv = NULL;
+ qglTexCoord4f = NULL;
+ qglTexCoord4fv = NULL;
+ qglTexCoord4i = NULL;
+ qglTexCoord4iv = NULL;
+ qglTexCoord4s = NULL;
+ qglTexCoord4sv = NULL;
+ qglTexCoordPointer = NULL;
+ qglTexEnvf = NULL;
+ qglTexEnvfv = NULL;
+ qglTexEnvi = NULL;
+ qglTexEnviv = NULL;
+ qglTexGend = NULL;
+ qglTexGendv = NULL;
+ qglTexGenf = NULL;
+ qglTexGenfv = NULL;
+ qglTexGeni = NULL;
+ qglTexGeniv = NULL;
+ qglTexImage1D = NULL;
+ qglTexImage2D = NULL;
+ qglTexParameterf = NULL;
+ qglTexParameterfv = NULL;
+ qglTexParameteri = NULL;
+ qglTexParameteriv = NULL;
+ qglTexSubImage1D = NULL;
+ qglTexSubImage2D = NULL;
+ qglTranslated = NULL;
+ qglTranslatef = NULL;
+ qglVertex2d = NULL;
+ qglVertex2dv = NULL;
+ qglVertex2f = NULL;
+ qglVertex2fv = NULL;
+ qglVertex2i = NULL;
+ qglVertex2iv = NULL;
+ qglVertex2s = NULL;
+ qglVertex2sv = NULL;
+ qglVertex3d = NULL;
+ qglVertex3dv = NULL;
+ qglVertex3f = NULL;
+ qglVertex3fv = NULL;
+ qglVertex3i = NULL;
+ qglVertex3iv = NULL;
+ qglVertex3s = NULL;
+ qglVertex3sv = NULL;
+ qglVertex4d = NULL;
+ qglVertex4dv = NULL;
+ qglVertex4f = NULL;
+ qglVertex4fv = NULL;
+ qglVertex4i = NULL;
+ qglVertex4iv = NULL;
+ qglVertex4s = NULL;
+ qglVertex4sv = NULL;
+ qglVertexPointer = NULL;
+ qglViewport = NULL;
+
+ qwglCopyContext = NULL;
+ qwglCreateContext = NULL;
+ qwglCreateLayerContext = NULL;
+ qwglDeleteContext = NULL;
+ qwglDescribeLayerPlane = NULL;
+ qwglGetCurrentContext = NULL;
+ qwglGetCurrentDC = NULL;
+ qwglGetLayerPaletteEntries = NULL;
+ qwglGetProcAddress = NULL;
+ qwglMakeCurrent = NULL;
+ qwglRealizeLayerPalette = NULL;
+ qwglSetLayerPaletteEntries = NULL;
+ qwglShareLists = NULL;
+ qwglSwapLayerBuffers = NULL;
+ qwglUseFontBitmaps = NULL;
+ qwglUseFontOutlines = NULL;
+
+ qwglChoosePixelFormat = NULL;
+ qwglDescribePixelFormat = NULL;
+ qwglGetPixelFormat = NULL;
+ qwglSetPixelFormat = NULL;
+ qwglSwapBuffers = NULL;
+}
+
+#define GR_NUM_BOARDS 0x0f
+
+static qboolean GlideIsValid( void )
+{
+ HMODULE hGlide;
+// int numBoards;
+// void (__stdcall *grGet)(unsigned int, unsigned int, int*);
+
+ if ( ( hGlide = LoadLibrary("Glide3X") ) != 0 )
+ {
+ // FIXME: 3Dfx needs to fix this shit
+ return qtrue;
+
+#if 0
+ grGet = (void *)GetProcAddress( hGlide, "_grGet@12");
+
+ if ( grGet )
+ {
+ grGet( GR_NUM_BOARDS, sizeof(int), &numBoards);
+ }
+ else
+ {
+ // if we've reached this point, something is seriously wrong
+ ri.Printf( PRINT_WARNING, "WARNING: could not find grGet in GLIDE3X.DLL\n" );
+ numBoards = 0;
+ }
+
+ FreeLibrary( hGlide );
+ hGlide = NULL;
+
+ if ( numBoards > 0 )
+ {
+ return qtrue;
+ }
+
+ ri.Printf( PRINT_WARNING, "WARNING: invalid Glide installation!\n" );
+#endif
+ }
+
+ return qfalse;
+}
+
+# pragma warning (disable : 4113 4133 4047 )
+# define GPA( a ) GetProcAddress( glw_state.hinstOpenGL, a )
+
+/*
+** QGL_Init
+**
+** This is responsible for binding our qgl function pointers to
+** the appropriate GL stuff. In Windows this means doing a
+** LoadLibrary and a bunch of calls to GetProcAddress. On other
+** operating systems we need to do the right thing, whatever that
+** might be.
+*/
+qboolean QGL_Init( const char *dllname )
+{
+ char systemDir[1024];
+ char libName[1024];
+
+ GetSystemDirectory( systemDir, sizeof( systemDir ) );
+
+ assert( glw_state.hinstOpenGL == 0 );
+
+ ri.Printf( PRINT_ALL, "...initializing QGL\n" );
+
+ // NOTE: this assumes that 'dllname' is lower case (and it should be)!
+ if ( strstr( dllname, _3DFX_DRIVER_NAME ) )
+ {
+ if ( !GlideIsValid() )
+ {
+ ri.Printf( PRINT_ALL, "...WARNING: missing Glide installation, assuming no 3Dfx available\n" );
+ return qfalse;
+ }
+ }
+
+ if ( dllname[0] != '!' )
+ {
+ Com_sprintf( libName, sizeof( libName ), "%s\\%s", systemDir, dllname );
+ }
+ else
+ {
+ Q_strncpyz( libName, dllname, sizeof( libName ) );
+ }
+
+ ri.Printf( PRINT_ALL, "...calling LoadLibrary( '%s.dll' ): ", libName );
+
+ if ( ( glw_state.hinstOpenGL = LoadLibrary( dllname ) ) == 0 )
+ {
+ ri.Printf( PRINT_ALL, "failed\n" );
+ return qfalse;
+ }
+ ri.Printf( PRINT_ALL, "succeeded\n" );
+
+ qglAccum = dllAccum = GPA( "glAccum" );
+ qglAlphaFunc = dllAlphaFunc = GPA( "glAlphaFunc" );
+ qglAreTexturesResident = dllAreTexturesResident = GPA( "glAreTexturesResident" );
+ qglArrayElement = dllArrayElement = GPA( "glArrayElement" );
+ qglBegin = dllBegin = GPA( "glBegin" );
+ qglBindTexture = dllBindTexture = GPA( "glBindTexture" );
+ qglBitmap = dllBitmap = GPA( "glBitmap" );
+ qglBlendFunc = dllBlendFunc = GPA( "glBlendFunc" );
+ qglCallList = dllCallList = GPA( "glCallList" );
+ qglCallLists = dllCallLists = GPA( "glCallLists" );
+ qglClear = dllClear = GPA( "glClear" );
+ qglClearAccum = dllClearAccum = GPA( "glClearAccum" );
+ qglClearColor = dllClearColor = GPA( "glClearColor" );
+ qglClearDepth = dllClearDepth = GPA( "glClearDepth" );
+ qglClearIndex = dllClearIndex = GPA( "glClearIndex" );
+ qglClearStencil = dllClearStencil = GPA( "glClearStencil" );
+ qglClipPlane = dllClipPlane = GPA( "glClipPlane" );
+ qglColor3b = dllColor3b = GPA( "glColor3b" );
+ qglColor3bv = dllColor3bv = GPA( "glColor3bv" );
+ qglColor3d = dllColor3d = GPA( "glColor3d" );
+ qglColor3dv = dllColor3dv = GPA( "glColor3dv" );
+ qglColor3f = dllColor3f = GPA( "glColor3f" );
+ qglColor3fv = dllColor3fv = GPA( "glColor3fv" );
+ qglColor3i = dllColor3i = GPA( "glColor3i" );
+ qglColor3iv = dllColor3iv = GPA( "glColor3iv" );
+ qglColor3s = dllColor3s = GPA( "glColor3s" );
+ qglColor3sv = dllColor3sv = GPA( "glColor3sv" );
+ qglColor3ub = dllColor3ub = GPA( "glColor3ub" );
+ qglColor3ubv = dllColor3ubv = GPA( "glColor3ubv" );
+ qglColor3ui = dllColor3ui = GPA( "glColor3ui" );
+ qglColor3uiv = dllColor3uiv = GPA( "glColor3uiv" );
+ qglColor3us = dllColor3us = GPA( "glColor3us" );
+ qglColor3usv = dllColor3usv = GPA( "glColor3usv" );
+ qglColor4b = dllColor4b = GPA( "glColor4b" );
+ qglColor4bv = dllColor4bv = GPA( "glColor4bv" );
+ qglColor4d = dllColor4d = GPA( "glColor4d" );
+ qglColor4dv = dllColor4dv = GPA( "glColor4dv" );
+ qglColor4f = dllColor4f = GPA( "glColor4f" );
+ qglColor4fv = dllColor4fv = GPA( "glColor4fv" );
+ qglColor4i = dllColor4i = GPA( "glColor4i" );
+ qglColor4iv = dllColor4iv = GPA( "glColor4iv" );
+ qglColor4s = dllColor4s = GPA( "glColor4s" );
+ qglColor4sv = dllColor4sv = GPA( "glColor4sv" );
+ qglColor4ub = dllColor4ub = GPA( "glColor4ub" );
+ qglColor4ubv = dllColor4ubv = GPA( "glColor4ubv" );
+ qglColor4ui = dllColor4ui = GPA( "glColor4ui" );
+ qglColor4uiv = dllColor4uiv = GPA( "glColor4uiv" );
+ qglColor4us = dllColor4us = GPA( "glColor4us" );
+ qglColor4usv = dllColor4usv = GPA( "glColor4usv" );
+ qglColorMask = dllColorMask = GPA( "glColorMask" );
+ qglColorMaterial = dllColorMaterial = GPA( "glColorMaterial" );
+ qglColorPointer = dllColorPointer = GPA( "glColorPointer" );
+ qglCopyPixels = dllCopyPixels = GPA( "glCopyPixels" );
+ qglCopyTexImage1D = dllCopyTexImage1D = GPA( "glCopyTexImage1D" );
+ qglCopyTexImage2D = dllCopyTexImage2D = GPA( "glCopyTexImage2D" );
+ qglCopyTexSubImage1D = dllCopyTexSubImage1D = GPA( "glCopyTexSubImage1D" );
+ qglCopyTexSubImage2D = dllCopyTexSubImage2D = GPA( "glCopyTexSubImage2D" );
+ qglCullFace = dllCullFace = GPA( "glCullFace" );
+ qglDeleteLists = dllDeleteLists = GPA( "glDeleteLists" );
+ qglDeleteTextures = dllDeleteTextures = GPA( "glDeleteTextures" );
+ qglDepthFunc = dllDepthFunc = GPA( "glDepthFunc" );
+ qglDepthMask = dllDepthMask = GPA( "glDepthMask" );
+ qglDepthRange = dllDepthRange = GPA( "glDepthRange" );
+ qglDisable = dllDisable = GPA( "glDisable" );
+ qglDisableClientState = dllDisableClientState = GPA( "glDisableClientState" );
+ qglDrawArrays = dllDrawArrays = GPA( "glDrawArrays" );
+ qglDrawBuffer = dllDrawBuffer = GPA( "glDrawBuffer" );
+ qglDrawElements = dllDrawElements = GPA( "glDrawElements" );
+ qglDrawPixels = dllDrawPixels = GPA( "glDrawPixels" );
+ qglEdgeFlag = dllEdgeFlag = GPA( "glEdgeFlag" );
+ qglEdgeFlagPointer = dllEdgeFlagPointer = GPA( "glEdgeFlagPointer" );
+ qglEdgeFlagv = dllEdgeFlagv = GPA( "glEdgeFlagv" );
+ qglEnable = dllEnable = GPA( "glEnable" );
+ qglEnableClientState = dllEnableClientState = GPA( "glEnableClientState" );
+ qglEnd = dllEnd = GPA( "glEnd" );
+ qglEndList = dllEndList = GPA( "glEndList" );
+ qglEvalCoord1d = dllEvalCoord1d = GPA( "glEvalCoord1d" );
+ qglEvalCoord1dv = dllEvalCoord1dv = GPA( "glEvalCoord1dv" );
+ qglEvalCoord1f = dllEvalCoord1f = GPA( "glEvalCoord1f" );
+ qglEvalCoord1fv = dllEvalCoord1fv = GPA( "glEvalCoord1fv" );
+ qglEvalCoord2d = dllEvalCoord2d = GPA( "glEvalCoord2d" );
+ qglEvalCoord2dv = dllEvalCoord2dv = GPA( "glEvalCoord2dv" );
+ qglEvalCoord2f = dllEvalCoord2f = GPA( "glEvalCoord2f" );
+ qglEvalCoord2fv = dllEvalCoord2fv = GPA( "glEvalCoord2fv" );
+ qglEvalMesh1 = dllEvalMesh1 = GPA( "glEvalMesh1" );
+ qglEvalMesh2 = dllEvalMesh2 = GPA( "glEvalMesh2" );
+ qglEvalPoint1 = dllEvalPoint1 = GPA( "glEvalPoint1" );
+ qglEvalPoint2 = dllEvalPoint2 = GPA( "glEvalPoint2" );
+ qglFeedbackBuffer = dllFeedbackBuffer = GPA( "glFeedbackBuffer" );
+ qglFinish = dllFinish = GPA( "glFinish" );
+ qglFlush = dllFlush = GPA( "glFlush" );
+ qglFogf = dllFogf = GPA( "glFogf" );
+ qglFogfv = dllFogfv = GPA( "glFogfv" );
+ qglFogi = dllFogi = GPA( "glFogi" );
+ qglFogiv = dllFogiv = GPA( "glFogiv" );
+ qglFrontFace = dllFrontFace = GPA( "glFrontFace" );
+ qglFrustum = dllFrustum = GPA( "glFrustum" );
+ qglGenLists = dllGenLists = ( GLuint (__stdcall * )(int) ) GPA( "glGenLists" );
+ qglGenTextures = dllGenTextures = GPA( "glGenTextures" );
+ qglGetBooleanv = dllGetBooleanv = GPA( "glGetBooleanv" );
+ qglGetClipPlane = dllGetClipPlane = GPA( "glGetClipPlane" );
+ qglGetDoublev = dllGetDoublev = GPA( "glGetDoublev" );
+ qglGetError = dllGetError = ( GLenum (__stdcall * )(void) ) GPA( "glGetError" );
+ qglGetFloatv = dllGetFloatv = GPA( "glGetFloatv" );
+ qglGetIntegerv = dllGetIntegerv = GPA( "glGetIntegerv" );
+ qglGetLightfv = dllGetLightfv = GPA( "glGetLightfv" );
+ qglGetLightiv = dllGetLightiv = GPA( "glGetLightiv" );
+ qglGetMapdv = dllGetMapdv = GPA( "glGetMapdv" );
+ qglGetMapfv = dllGetMapfv = GPA( "glGetMapfv" );
+ qglGetMapiv = dllGetMapiv = GPA( "glGetMapiv" );
+ qglGetMaterialfv = dllGetMaterialfv = GPA( "glGetMaterialfv" );
+ qglGetMaterialiv = dllGetMaterialiv = GPA( "glGetMaterialiv" );
+ qglGetPixelMapfv = dllGetPixelMapfv = GPA( "glGetPixelMapfv" );
+ qglGetPixelMapuiv = dllGetPixelMapuiv = GPA( "glGetPixelMapuiv" );
+ qglGetPixelMapusv = dllGetPixelMapusv = GPA( "glGetPixelMapusv" );
+ qglGetPointerv = dllGetPointerv = GPA( "glGetPointerv" );
+ qglGetPolygonStipple = dllGetPolygonStipple = GPA( "glGetPolygonStipple" );
+ qglGetString = dllGetString = GPA( "glGetString" );
+ qglGetTexEnvfv = dllGetTexEnvfv = GPA( "glGetTexEnvfv" );
+ qglGetTexEnviv = dllGetTexEnviv = GPA( "glGetTexEnviv" );
+ qglGetTexGendv = dllGetTexGendv = GPA( "glGetTexGendv" );
+ qglGetTexGenfv = dllGetTexGenfv = GPA( "glGetTexGenfv" );
+ qglGetTexGeniv = dllGetTexGeniv = GPA( "glGetTexGeniv" );
+ qglGetTexImage = dllGetTexImage = GPA( "glGetTexImage" );
+ qglGetTexParameterfv = dllGetTexParameterfv = GPA( "glGetTexParameterfv" );
+ qglGetTexParameteriv = dllGetTexParameteriv = GPA( "glGetTexParameteriv" );
+ qglHint = dllHint = GPA( "glHint" );
+ qglIndexMask = dllIndexMask = GPA( "glIndexMask" );
+ qglIndexPointer = dllIndexPointer = GPA( "glIndexPointer" );
+ qglIndexd = dllIndexd = GPA( "glIndexd" );
+ qglIndexdv = dllIndexdv = GPA( "glIndexdv" );
+ qglIndexf = dllIndexf = GPA( "glIndexf" );
+ qglIndexfv = dllIndexfv = GPA( "glIndexfv" );
+ qglIndexi = dllIndexi = GPA( "glIndexi" );
+ qglIndexiv = dllIndexiv = GPA( "glIndexiv" );
+ qglIndexs = dllIndexs = GPA( "glIndexs" );
+ qglIndexsv = dllIndexsv = GPA( "glIndexsv" );
+ qglIndexub = dllIndexub = GPA( "glIndexub" );
+ qglIndexubv = dllIndexubv = GPA( "glIndexubv" );
+ qglInitNames = dllInitNames = GPA( "glInitNames" );
+ qglInterleavedArrays = dllInterleavedArrays = GPA( "glInterleavedArrays" );
+ qglIsEnabled = dllIsEnabled = GPA( "glIsEnabled" );
+ qglIsList = dllIsList = GPA( "glIsList" );
+ qglIsTexture = dllIsTexture = GPA( "glIsTexture" );
+ qglLightModelf = dllLightModelf = GPA( "glLightModelf" );
+ qglLightModelfv = dllLightModelfv = GPA( "glLightModelfv" );
+ qglLightModeli = dllLightModeli = GPA( "glLightModeli" );
+ qglLightModeliv = dllLightModeliv = GPA( "glLightModeliv" );
+ qglLightf = dllLightf = GPA( "glLightf" );
+ qglLightfv = dllLightfv = GPA( "glLightfv" );
+ qglLighti = dllLighti = GPA( "glLighti" );
+ qglLightiv = dllLightiv = GPA( "glLightiv" );
+ qglLineStipple = dllLineStipple = GPA( "glLineStipple" );
+ qglLineWidth = dllLineWidth = GPA( "glLineWidth" );
+ qglListBase = dllListBase = GPA( "glListBase" );
+ qglLoadIdentity = dllLoadIdentity = GPA( "glLoadIdentity" );
+ qglLoadMatrixd = dllLoadMatrixd = GPA( "glLoadMatrixd" );
+ qglLoadMatrixf = dllLoadMatrixf = GPA( "glLoadMatrixf" );
+ qglLoadName = dllLoadName = GPA( "glLoadName" );
+ qglLogicOp = dllLogicOp = GPA( "glLogicOp" );
+ qglMap1d = dllMap1d = GPA( "glMap1d" );
+ qglMap1f = dllMap1f = GPA( "glMap1f" );
+ qglMap2d = dllMap2d = GPA( "glMap2d" );
+ qglMap2f = dllMap2f = GPA( "glMap2f" );
+ qglMapGrid1d = dllMapGrid1d = GPA( "glMapGrid1d" );
+ qglMapGrid1f = dllMapGrid1f = GPA( "glMapGrid1f" );
+ qglMapGrid2d = dllMapGrid2d = GPA( "glMapGrid2d" );
+ qglMapGrid2f = dllMapGrid2f = GPA( "glMapGrid2f" );
+ qglMaterialf = dllMaterialf = GPA( "glMaterialf" );
+ qglMaterialfv = dllMaterialfv = GPA( "glMaterialfv" );
+ qglMateriali = dllMateriali = GPA( "glMateriali" );
+ qglMaterialiv = dllMaterialiv = GPA( "glMaterialiv" );
+ qglMatrixMode = dllMatrixMode = GPA( "glMatrixMode" );
+ qglMultMatrixd = dllMultMatrixd = GPA( "glMultMatrixd" );
+ qglMultMatrixf = dllMultMatrixf = GPA( "glMultMatrixf" );
+ qglNewList = dllNewList = GPA( "glNewList" );
+ qglNormal3b = dllNormal3b = GPA( "glNormal3b" );
+ qglNormal3bv = dllNormal3bv = GPA( "glNormal3bv" );
+ qglNormal3d = dllNormal3d = GPA( "glNormal3d" );
+ qglNormal3dv = dllNormal3dv = GPA( "glNormal3dv" );
+ qglNormal3f = dllNormal3f = GPA( "glNormal3f" );
+ qglNormal3fv = dllNormal3fv = GPA( "glNormal3fv" );
+ qglNormal3i = dllNormal3i = GPA( "glNormal3i" );
+ qglNormal3iv = dllNormal3iv = GPA( "glNormal3iv" );
+ qglNormal3s = dllNormal3s = GPA( "glNormal3s" );
+ qglNormal3sv = dllNormal3sv = GPA( "glNormal3sv" );
+ qglNormalPointer = dllNormalPointer = GPA( "glNormalPointer" );
+ qglOrtho = dllOrtho = GPA( "glOrtho" );
+ qglPassThrough = dllPassThrough = GPA( "glPassThrough" );
+ qglPixelMapfv = dllPixelMapfv = GPA( "glPixelMapfv" );
+ qglPixelMapuiv = dllPixelMapuiv = GPA( "glPixelMapuiv" );
+ qglPixelMapusv = dllPixelMapusv = GPA( "glPixelMapusv" );
+ qglPixelStoref = dllPixelStoref = GPA( "glPixelStoref" );
+ qglPixelStorei = dllPixelStorei = GPA( "glPixelStorei" );
+ qglPixelTransferf = dllPixelTransferf = GPA( "glPixelTransferf" );
+ qglPixelTransferi = dllPixelTransferi = GPA( "glPixelTransferi" );
+ qglPixelZoom = dllPixelZoom = GPA( "glPixelZoom" );
+ qglPointSize = dllPointSize = GPA( "glPointSize" );
+ qglPolygonMode = dllPolygonMode = GPA( "glPolygonMode" );
+ qglPolygonOffset = dllPolygonOffset = GPA( "glPolygonOffset" );
+ qglPolygonStipple = dllPolygonStipple = GPA( "glPolygonStipple" );
+ qglPopAttrib = dllPopAttrib = GPA( "glPopAttrib" );
+ qglPopClientAttrib = dllPopClientAttrib = GPA( "glPopClientAttrib" );
+ qglPopMatrix = dllPopMatrix = GPA( "glPopMatrix" );
+ qglPopName = dllPopName = GPA( "glPopName" );
+ qglPrioritizeTextures = dllPrioritizeTextures = GPA( "glPrioritizeTextures" );
+ qglPushAttrib = dllPushAttrib = GPA( "glPushAttrib" );
+ qglPushClientAttrib = dllPushClientAttrib = GPA( "glPushClientAttrib" );
+ qglPushMatrix = dllPushMatrix = GPA( "glPushMatrix" );
+ qglPushName = dllPushName = GPA( "glPushName" );
+ qglRasterPos2d = dllRasterPos2d = GPA( "glRasterPos2d" );
+ qglRasterPos2dv = dllRasterPos2dv = GPA( "glRasterPos2dv" );
+ qglRasterPos2f = dllRasterPos2f = GPA( "glRasterPos2f" );
+ qglRasterPos2fv = dllRasterPos2fv = GPA( "glRasterPos2fv" );
+ qglRasterPos2i = dllRasterPos2i = GPA( "glRasterPos2i" );
+ qglRasterPos2iv = dllRasterPos2iv = GPA( "glRasterPos2iv" );
+ qglRasterPos2s = dllRasterPos2s = GPA( "glRasterPos2s" );
+ qglRasterPos2sv = dllRasterPos2sv = GPA( "glRasterPos2sv" );
+ qglRasterPos3d = dllRasterPos3d = GPA( "glRasterPos3d" );
+ qglRasterPos3dv = dllRasterPos3dv = GPA( "glRasterPos3dv" );
+ qglRasterPos3f = dllRasterPos3f = GPA( "glRasterPos3f" );
+ qglRasterPos3fv = dllRasterPos3fv = GPA( "glRasterPos3fv" );
+ qglRasterPos3i = dllRasterPos3i = GPA( "glRasterPos3i" );
+ qglRasterPos3iv = dllRasterPos3iv = GPA( "glRasterPos3iv" );
+ qglRasterPos3s = dllRasterPos3s = GPA( "glRasterPos3s" );
+ qglRasterPos3sv = dllRasterPos3sv = GPA( "glRasterPos3sv" );
+ qglRasterPos4d = dllRasterPos4d = GPA( "glRasterPos4d" );
+ qglRasterPos4dv = dllRasterPos4dv = GPA( "glRasterPos4dv" );
+ qglRasterPos4f = dllRasterPos4f = GPA( "glRasterPos4f" );
+ qglRasterPos4fv = dllRasterPos4fv = GPA( "glRasterPos4fv" );
+ qglRasterPos4i = dllRasterPos4i = GPA( "glRasterPos4i" );
+ qglRasterPos4iv = dllRasterPos4iv = GPA( "glRasterPos4iv" );
+ qglRasterPos4s = dllRasterPos4s = GPA( "glRasterPos4s" );
+ qglRasterPos4sv = dllRasterPos4sv = GPA( "glRasterPos4sv" );
+ qglReadBuffer = dllReadBuffer = GPA( "glReadBuffer" );
+ qglReadPixels = dllReadPixels = GPA( "glReadPixels" );
+ qglRectd = dllRectd = GPA( "glRectd" );
+ qglRectdv = dllRectdv = GPA( "glRectdv" );
+ qglRectf = dllRectf = GPA( "glRectf" );
+ qglRectfv = dllRectfv = GPA( "glRectfv" );
+ qglRecti = dllRecti = GPA( "glRecti" );
+ qglRectiv = dllRectiv = GPA( "glRectiv" );
+ qglRects = dllRects = GPA( "glRects" );
+ qglRectsv = dllRectsv = GPA( "glRectsv" );
+ qglRenderMode = dllRenderMode = GPA( "glRenderMode" );
+ qglRotated = dllRotated = GPA( "glRotated" );
+ qglRotatef = dllRotatef = GPA( "glRotatef" );
+ qglScaled = dllScaled = GPA( "glScaled" );
+ qglScalef = dllScalef = GPA( "glScalef" );
+ qglScissor = dllScissor = GPA( "glScissor" );
+ qglSelectBuffer = dllSelectBuffer = GPA( "glSelectBuffer" );
+ qglShadeModel = dllShadeModel = GPA( "glShadeModel" );
+ qglStencilFunc = dllStencilFunc = GPA( "glStencilFunc" );
+ qglStencilMask = dllStencilMask = GPA( "glStencilMask" );
+ qglStencilOp = dllStencilOp = GPA( "glStencilOp" );
+ qglTexCoord1d = dllTexCoord1d = GPA( "glTexCoord1d" );
+ qglTexCoord1dv = dllTexCoord1dv = GPA( "glTexCoord1dv" );
+ qglTexCoord1f = dllTexCoord1f = GPA( "glTexCoord1f" );
+ qglTexCoord1fv = dllTexCoord1fv = GPA( "glTexCoord1fv" );
+ qglTexCoord1i = dllTexCoord1i = GPA( "glTexCoord1i" );
+ qglTexCoord1iv = dllTexCoord1iv = GPA( "glTexCoord1iv" );
+ qglTexCoord1s = dllTexCoord1s = GPA( "glTexCoord1s" );
+ qglTexCoord1sv = dllTexCoord1sv = GPA( "glTexCoord1sv" );
+ qglTexCoord2d = dllTexCoord2d = GPA( "glTexCoord2d" );
+ qglTexCoord2dv = dllTexCoord2dv = GPA( "glTexCoord2dv" );
+ qglTexCoord2f = dllTexCoord2f = GPA( "glTexCoord2f" );
+ qglTexCoord2fv = dllTexCoord2fv = GPA( "glTexCoord2fv" );
+ qglTexCoord2i = dllTexCoord2i = GPA( "glTexCoord2i" );
+ qglTexCoord2iv = dllTexCoord2iv = GPA( "glTexCoord2iv" );
+ qglTexCoord2s = dllTexCoord2s = GPA( "glTexCoord2s" );
+ qglTexCoord2sv = dllTexCoord2sv = GPA( "glTexCoord2sv" );
+ qglTexCoord3d = dllTexCoord3d = GPA( "glTexCoord3d" );
+ qglTexCoord3dv = dllTexCoord3dv = GPA( "glTexCoord3dv" );
+ qglTexCoord3f = dllTexCoord3f = GPA( "glTexCoord3f" );
+ qglTexCoord3fv = dllTexCoord3fv = GPA( "glTexCoord3fv" );
+ qglTexCoord3i = dllTexCoord3i = GPA( "glTexCoord3i" );
+ qglTexCoord3iv = dllTexCoord3iv = GPA( "glTexCoord3iv" );
+ qglTexCoord3s = dllTexCoord3s = GPA( "glTexCoord3s" );
+ qglTexCoord3sv = dllTexCoord3sv = GPA( "glTexCoord3sv" );
+ qglTexCoord4d = dllTexCoord4d = GPA( "glTexCoord4d" );
+ qglTexCoord4dv = dllTexCoord4dv = GPA( "glTexCoord4dv" );
+ qglTexCoord4f = dllTexCoord4f = GPA( "glTexCoord4f" );
+ qglTexCoord4fv = dllTexCoord4fv = GPA( "glTexCoord4fv" );
+ qglTexCoord4i = dllTexCoord4i = GPA( "glTexCoord4i" );
+ qglTexCoord4iv = dllTexCoord4iv = GPA( "glTexCoord4iv" );
+ qglTexCoord4s = dllTexCoord4s = GPA( "glTexCoord4s" );
+ qglTexCoord4sv = dllTexCoord4sv = GPA( "glTexCoord4sv" );
+ qglTexCoordPointer = dllTexCoordPointer = GPA( "glTexCoordPointer" );
+ qglTexEnvf = dllTexEnvf = GPA( "glTexEnvf" );
+ qglTexEnvfv = dllTexEnvfv = GPA( "glTexEnvfv" );
+ qglTexEnvi = dllTexEnvi = GPA( "glTexEnvi" );
+ qglTexEnviv = dllTexEnviv = GPA( "glTexEnviv" );
+ qglTexGend = dllTexGend = GPA( "glTexGend" );
+ qglTexGendv = dllTexGendv = GPA( "glTexGendv" );
+ qglTexGenf = dllTexGenf = GPA( "glTexGenf" );
+ qglTexGenfv = dllTexGenfv = GPA( "glTexGenfv" );
+ qglTexGeni = dllTexGeni = GPA( "glTexGeni" );
+ qglTexGeniv = dllTexGeniv = GPA( "glTexGeniv" );
+ qglTexImage1D = dllTexImage1D = GPA( "glTexImage1D" );
+ qglTexImage2D = dllTexImage2D = GPA( "glTexImage2D" );
+ qglTexParameterf = dllTexParameterf = GPA( "glTexParameterf" );
+ qglTexParameterfv = dllTexParameterfv = GPA( "glTexParameterfv" );
+ qglTexParameteri = dllTexParameteri = GPA( "glTexParameteri" );
+ qglTexParameteriv = dllTexParameteriv = GPA( "glTexParameteriv" );
+ qglTexSubImage1D = dllTexSubImage1D = GPA( "glTexSubImage1D" );
+ qglTexSubImage2D = dllTexSubImage2D = GPA( "glTexSubImage2D" );
+ qglTranslated = dllTranslated = GPA( "glTranslated" );
+ qglTranslatef = dllTranslatef = GPA( "glTranslatef" );
+ qglVertex2d = dllVertex2d = GPA( "glVertex2d" );
+ qglVertex2dv = dllVertex2dv = GPA( "glVertex2dv" );
+ qglVertex2f = dllVertex2f = GPA( "glVertex2f" );
+ qglVertex2fv = dllVertex2fv = GPA( "glVertex2fv" );
+ qglVertex2i = dllVertex2i = GPA( "glVertex2i" );
+ qglVertex2iv = dllVertex2iv = GPA( "glVertex2iv" );
+ qglVertex2s = dllVertex2s = GPA( "glVertex2s" );
+ qglVertex2sv = dllVertex2sv = GPA( "glVertex2sv" );
+ qglVertex3d = dllVertex3d = GPA( "glVertex3d" );
+ qglVertex3dv = dllVertex3dv = GPA( "glVertex3dv" );
+ qglVertex3f = dllVertex3f = GPA( "glVertex3f" );
+ qglVertex3fv = dllVertex3fv = GPA( "glVertex3fv" );
+ qglVertex3i = dllVertex3i = GPA( "glVertex3i" );
+ qglVertex3iv = dllVertex3iv = GPA( "glVertex3iv" );
+ qglVertex3s = dllVertex3s = GPA( "glVertex3s" );
+ qglVertex3sv = dllVertex3sv = GPA( "glVertex3sv" );
+ qglVertex4d = dllVertex4d = GPA( "glVertex4d" );
+ qglVertex4dv = dllVertex4dv = GPA( "glVertex4dv" );
+ qglVertex4f = dllVertex4f = GPA( "glVertex4f" );
+ qglVertex4fv = dllVertex4fv = GPA( "glVertex4fv" );
+ qglVertex4i = dllVertex4i = GPA( "glVertex4i" );
+ qglVertex4iv = dllVertex4iv = GPA( "glVertex4iv" );
+ qglVertex4s = dllVertex4s = GPA( "glVertex4s" );
+ qglVertex4sv = dllVertex4sv = GPA( "glVertex4sv" );
+ qglVertexPointer = dllVertexPointer = GPA( "glVertexPointer" );
+ qglViewport = dllViewport = GPA( "glViewport" );
+
+ qwglCopyContext = GPA( "wglCopyContext" );
+ qwglCreateContext = GPA( "wglCreateContext" );
+ qwglCreateLayerContext = GPA( "wglCreateLayerContext" );
+ qwglDeleteContext = GPA( "wglDeleteContext" );
+ qwglDescribeLayerPlane = GPA( "wglDescribeLayerPlane" );
+ qwglGetCurrentContext = GPA( "wglGetCurrentContext" );
+ qwglGetCurrentDC = GPA( "wglGetCurrentDC" );
+ qwglGetLayerPaletteEntries = GPA( "wglGetLayerPaletteEntries" );
+ qwglGetProcAddress = GPA( "wglGetProcAddress" );
+ qwglMakeCurrent = GPA( "wglMakeCurrent" );
+ qwglRealizeLayerPalette = GPA( "wglRealizeLayerPalette" );
+ qwglSetLayerPaletteEntries = GPA( "wglSetLayerPaletteEntries" );
+ qwglShareLists = GPA( "wglShareLists" );
+ qwglSwapLayerBuffers = GPA( "wglSwapLayerBuffers" );
+ qwglUseFontBitmaps = GPA( "wglUseFontBitmapsA" );
+ qwglUseFontOutlines = GPA( "wglUseFontOutlinesA" );
+
+ qwglChoosePixelFormat = GPA( "wglChoosePixelFormat" );
+ qwglDescribePixelFormat = GPA( "wglDescribePixelFormat" );
+ qwglGetPixelFormat = GPA( "wglGetPixelFormat" );
+ qwglSetPixelFormat = GPA( "wglSetPixelFormat" );
+ qwglSwapBuffers = GPA( "wglSwapBuffers" );
+
+ qwglSwapIntervalEXT = 0;
+ qglActiveTextureARB = 0;
+ qglClientActiveTextureARB = 0;
+ qglMultiTexCoord2fARB = 0;
+ qglLockArraysEXT = 0;
+ qglUnlockArraysEXT = 0;
+ qwglGetDeviceGammaRamp3DFX = NULL;
+ qwglSetDeviceGammaRamp3DFX = NULL;
+
+ // check logging
+ QGL_EnableLogging( r_logFile->integer );
+
+ return qtrue;
+}
+
+void QGL_EnableLogging( qboolean enable )
+{
+ static qboolean isEnabled;
+
+ // return if we're already active
+ if ( isEnabled && enable ) {
+ // decrement log counter and stop if it has reached 0
+ ri.Cvar_Set( "r_logFile", va("%d", r_logFile->integer - 1 ) );
+ if ( r_logFile->integer ) {
+ return;
+ }
+ enable = qfalse;
+ }
+
+ // return if we're already disabled
+ if ( !enable && !isEnabled )
+ return;
+
+ isEnabled = enable;
+
+ if ( enable )
+ {
+ if ( !glw_state.log_fp )
+ {
+ struct tm *newtime;
+ time_t aclock;
+ char buffer[1024];
+ cvar_t *basedir;
+
+ time( &aclock );
+ newtime = localtime( &aclock );
+
+ asctime( newtime );
+
+ basedir = ri.Cvar_Get( "fs_basepath", "", 0 );
+ Com_sprintf( buffer, sizeof(buffer), "%s/gl.log", basedir->string );
+ glw_state.log_fp = fopen( buffer, "wt" );
+
+ fprintf( glw_state.log_fp, "%s\n", asctime( newtime ) );
+ }
+
+ qglAccum = logAccum;
+ qglAlphaFunc = logAlphaFunc;
+ qglAreTexturesResident = logAreTexturesResident;
+ qglArrayElement = logArrayElement;
+ qglBegin = logBegin;
+ qglBindTexture = logBindTexture;
+ qglBitmap = logBitmap;
+ qglBlendFunc = logBlendFunc;
+ qglCallList = logCallList;
+ qglCallLists = logCallLists;
+ qglClear = logClear;
+ qglClearAccum = logClearAccum;
+ qglClearColor = logClearColor;
+ qglClearDepth = logClearDepth;
+ qglClearIndex = logClearIndex;
+ qglClearStencil = logClearStencil;
+ qglClipPlane = logClipPlane;
+ qglColor3b = logColor3b;
+ qglColor3bv = logColor3bv;
+ qglColor3d = logColor3d;
+ qglColor3dv = logColor3dv;
+ qglColor3f = logColor3f;
+ qglColor3fv = logColor3fv;
+ qglColor3i = logColor3i;
+ qglColor3iv = logColor3iv;
+ qglColor3s = logColor3s;
+ qglColor3sv = logColor3sv;
+ qglColor3ub = logColor3ub;
+ qglColor3ubv = logColor3ubv;
+ qglColor3ui = logColor3ui;
+ qglColor3uiv = logColor3uiv;
+ qglColor3us = logColor3us;
+ qglColor3usv = logColor3usv;
+ qglColor4b = logColor4b;
+ qglColor4bv = logColor4bv;
+ qglColor4d = logColor4d;
+ qglColor4dv = logColor4dv;
+ qglColor4f = logColor4f;
+ qglColor4fv = logColor4fv;
+ qglColor4i = logColor4i;
+ qglColor4iv = logColor4iv;
+ qglColor4s = logColor4s;
+ qglColor4sv = logColor4sv;
+ qglColor4ub = logColor4ub;
+ qglColor4ubv = logColor4ubv;
+ qglColor4ui = logColor4ui;
+ qglColor4uiv = logColor4uiv;
+ qglColor4us = logColor4us;
+ qglColor4usv = logColor4usv;
+ qglColorMask = logColorMask;
+ qglColorMaterial = logColorMaterial;
+ qglColorPointer = logColorPointer;
+ qglCopyPixels = logCopyPixels;
+ qglCopyTexImage1D = logCopyTexImage1D;
+ qglCopyTexImage2D = logCopyTexImage2D;
+ qglCopyTexSubImage1D = logCopyTexSubImage1D;
+ qglCopyTexSubImage2D = logCopyTexSubImage2D;
+ qglCullFace = logCullFace;
+ qglDeleteLists = logDeleteLists ;
+ qglDeleteTextures = logDeleteTextures ;
+ qglDepthFunc = logDepthFunc ;
+ qglDepthMask = logDepthMask ;
+ qglDepthRange = logDepthRange ;
+ qglDisable = logDisable ;
+ qglDisableClientState = logDisableClientState ;
+ qglDrawArrays = logDrawArrays ;
+ qglDrawBuffer = logDrawBuffer ;
+ qglDrawElements = logDrawElements ;
+ qglDrawPixels = logDrawPixels ;
+ qglEdgeFlag = logEdgeFlag ;
+ qglEdgeFlagPointer = logEdgeFlagPointer ;
+ qglEdgeFlagv = logEdgeFlagv ;
+ qglEnable = logEnable ;
+ qglEnableClientState = logEnableClientState ;
+ qglEnd = logEnd ;
+ qglEndList = logEndList ;
+ qglEvalCoord1d = logEvalCoord1d ;
+ qglEvalCoord1dv = logEvalCoord1dv ;
+ qglEvalCoord1f = logEvalCoord1f ;
+ qglEvalCoord1fv = logEvalCoord1fv ;
+ qglEvalCoord2d = logEvalCoord2d ;
+ qglEvalCoord2dv = logEvalCoord2dv ;
+ qglEvalCoord2f = logEvalCoord2f ;
+ qglEvalCoord2fv = logEvalCoord2fv ;
+ qglEvalMesh1 = logEvalMesh1 ;
+ qglEvalMesh2 = logEvalMesh2 ;
+ qglEvalPoint1 = logEvalPoint1 ;
+ qglEvalPoint2 = logEvalPoint2 ;
+ qglFeedbackBuffer = logFeedbackBuffer ;
+ qglFinish = logFinish ;
+ qglFlush = logFlush ;
+ qglFogf = logFogf ;
+ qglFogfv = logFogfv ;
+ qglFogi = logFogi ;
+ qglFogiv = logFogiv ;
+ qglFrontFace = logFrontFace ;
+ qglFrustum = logFrustum ;
+ qglGenLists = logGenLists ;
+ qglGenTextures = logGenTextures ;
+ qglGetBooleanv = logGetBooleanv ;
+ qglGetClipPlane = logGetClipPlane ;
+ qglGetDoublev = logGetDoublev ;
+ qglGetError = logGetError ;
+ qglGetFloatv = logGetFloatv ;
+ qglGetIntegerv = logGetIntegerv ;
+ qglGetLightfv = logGetLightfv ;
+ qglGetLightiv = logGetLightiv ;
+ qglGetMapdv = logGetMapdv ;
+ qglGetMapfv = logGetMapfv ;
+ qglGetMapiv = logGetMapiv ;
+ qglGetMaterialfv = logGetMaterialfv ;
+ qglGetMaterialiv = logGetMaterialiv ;
+ qglGetPixelMapfv = logGetPixelMapfv ;
+ qglGetPixelMapuiv = logGetPixelMapuiv ;
+ qglGetPixelMapusv = logGetPixelMapusv ;
+ qglGetPointerv = logGetPointerv ;
+ qglGetPolygonStipple = logGetPolygonStipple ;
+ qglGetString = logGetString ;
+ qglGetTexEnvfv = logGetTexEnvfv ;
+ qglGetTexEnviv = logGetTexEnviv ;
+ qglGetTexGendv = logGetTexGendv ;
+ qglGetTexGenfv = logGetTexGenfv ;
+ qglGetTexGeniv = logGetTexGeniv ;
+ qglGetTexImage = logGetTexImage ;
+ qglGetTexLevelParameterfv = logGetTexLevelParameterfv ;
+ qglGetTexLevelParameteriv = logGetTexLevelParameteriv ;
+ qglGetTexParameterfv = logGetTexParameterfv ;
+ qglGetTexParameteriv = logGetTexParameteriv ;
+ qglHint = logHint ;
+ qglIndexMask = logIndexMask ;
+ qglIndexPointer = logIndexPointer ;
+ qglIndexd = logIndexd ;
+ qglIndexdv = logIndexdv ;
+ qglIndexf = logIndexf ;
+ qglIndexfv = logIndexfv ;
+ qglIndexi = logIndexi ;
+ qglIndexiv = logIndexiv ;
+ qglIndexs = logIndexs ;
+ qglIndexsv = logIndexsv ;
+ qglIndexub = logIndexub ;
+ qglIndexubv = logIndexubv ;
+ qglInitNames = logInitNames ;
+ qglInterleavedArrays = logInterleavedArrays ;
+ qglIsEnabled = logIsEnabled ;
+ qglIsList = logIsList ;
+ qglIsTexture = logIsTexture ;
+ qglLightModelf = logLightModelf ;
+ qglLightModelfv = logLightModelfv ;
+ qglLightModeli = logLightModeli ;
+ qglLightModeliv = logLightModeliv ;
+ qglLightf = logLightf ;
+ qglLightfv = logLightfv ;
+ qglLighti = logLighti ;
+ qglLightiv = logLightiv ;
+ qglLineStipple = logLineStipple ;
+ qglLineWidth = logLineWidth ;
+ qglListBase = logListBase ;
+ qglLoadIdentity = logLoadIdentity ;
+ qglLoadMatrixd = logLoadMatrixd ;
+ qglLoadMatrixf = logLoadMatrixf ;
+ qglLoadName = logLoadName ;
+ qglLogicOp = logLogicOp ;
+ qglMap1d = logMap1d ;
+ qglMap1f = logMap1f ;
+ qglMap2d = logMap2d ;
+ qglMap2f = logMap2f ;
+ qglMapGrid1d = logMapGrid1d ;
+ qglMapGrid1f = logMapGrid1f ;
+ qglMapGrid2d = logMapGrid2d ;
+ qglMapGrid2f = logMapGrid2f ;
+ qglMaterialf = logMaterialf ;
+ qglMaterialfv = logMaterialfv ;
+ qglMateriali = logMateriali ;
+ qglMaterialiv = logMaterialiv ;
+ qglMatrixMode = logMatrixMode ;
+ qglMultMatrixd = logMultMatrixd ;
+ qglMultMatrixf = logMultMatrixf ;
+ qglNewList = logNewList ;
+ qglNormal3b = logNormal3b ;
+ qglNormal3bv = logNormal3bv ;
+ qglNormal3d = logNormal3d ;
+ qglNormal3dv = logNormal3dv ;
+ qglNormal3f = logNormal3f ;
+ qglNormal3fv = logNormal3fv ;
+ qglNormal3i = logNormal3i ;
+ qglNormal3iv = logNormal3iv ;
+ qglNormal3s = logNormal3s ;
+ qglNormal3sv = logNormal3sv ;
+ qglNormalPointer = logNormalPointer ;
+ qglOrtho = logOrtho ;
+ qglPassThrough = logPassThrough ;
+ qglPixelMapfv = logPixelMapfv ;
+ qglPixelMapuiv = logPixelMapuiv ;
+ qglPixelMapusv = logPixelMapusv ;
+ qglPixelStoref = logPixelStoref ;
+ qglPixelStorei = logPixelStorei ;
+ qglPixelTransferf = logPixelTransferf ;
+ qglPixelTransferi = logPixelTransferi ;
+ qglPixelZoom = logPixelZoom ;
+ qglPointSize = logPointSize ;
+ qglPolygonMode = logPolygonMode ;
+ qglPolygonOffset = logPolygonOffset ;
+ qglPolygonStipple = logPolygonStipple ;
+ qglPopAttrib = logPopAttrib ;
+ qglPopClientAttrib = logPopClientAttrib ;
+ qglPopMatrix = logPopMatrix ;
+ qglPopName = logPopName ;
+ qglPrioritizeTextures = logPrioritizeTextures ;
+ qglPushAttrib = logPushAttrib ;
+ qglPushClientAttrib = logPushClientAttrib ;
+ qglPushMatrix = logPushMatrix ;
+ qglPushName = logPushName ;
+ qglRasterPos2d = logRasterPos2d ;
+ qglRasterPos2dv = logRasterPos2dv ;
+ qglRasterPos2f = logRasterPos2f ;
+ qglRasterPos2fv = logRasterPos2fv ;
+ qglRasterPos2i = logRasterPos2i ;
+ qglRasterPos2iv = logRasterPos2iv ;
+ qglRasterPos2s = logRasterPos2s ;
+ qglRasterPos2sv = logRasterPos2sv ;
+ qglRasterPos3d = logRasterPos3d ;
+ qglRasterPos3dv = logRasterPos3dv ;
+ qglRasterPos3f = logRasterPos3f ;
+ qglRasterPos3fv = logRasterPos3fv ;
+ qglRasterPos3i = logRasterPos3i ;
+ qglRasterPos3iv = logRasterPos3iv ;
+ qglRasterPos3s = logRasterPos3s ;
+ qglRasterPos3sv = logRasterPos3sv ;
+ qglRasterPos4d = logRasterPos4d ;
+ qglRasterPos4dv = logRasterPos4dv ;
+ qglRasterPos4f = logRasterPos4f ;
+ qglRasterPos4fv = logRasterPos4fv ;
+ qglRasterPos4i = logRasterPos4i ;
+ qglRasterPos4iv = logRasterPos4iv ;
+ qglRasterPos4s = logRasterPos4s ;
+ qglRasterPos4sv = logRasterPos4sv ;
+ qglReadBuffer = logReadBuffer ;
+ qglReadPixels = logReadPixels ;
+ qglRectd = logRectd ;
+ qglRectdv = logRectdv ;
+ qglRectf = logRectf ;
+ qglRectfv = logRectfv ;
+ qglRecti = logRecti ;
+ qglRectiv = logRectiv ;
+ qglRects = logRects ;
+ qglRectsv = logRectsv ;
+ qglRenderMode = logRenderMode ;
+ qglRotated = logRotated ;
+ qglRotatef = logRotatef ;
+ qglScaled = logScaled ;
+ qglScalef = logScalef ;
+ qglScissor = logScissor ;
+ qglSelectBuffer = logSelectBuffer ;
+ qglShadeModel = logShadeModel ;
+ qglStencilFunc = logStencilFunc ;
+ qglStencilMask = logStencilMask ;
+ qglStencilOp = logStencilOp ;
+ qglTexCoord1d = logTexCoord1d ;
+ qglTexCoord1dv = logTexCoord1dv ;
+ qglTexCoord1f = logTexCoord1f ;
+ qglTexCoord1fv = logTexCoord1fv ;
+ qglTexCoord1i = logTexCoord1i ;
+ qglTexCoord1iv = logTexCoord1iv ;
+ qglTexCoord1s = logTexCoord1s ;
+ qglTexCoord1sv = logTexCoord1sv ;
+ qglTexCoord2d = logTexCoord2d ;
+ qglTexCoord2dv = logTexCoord2dv ;
+ qglTexCoord2f = logTexCoord2f ;
+ qglTexCoord2fv = logTexCoord2fv ;
+ qglTexCoord2i = logTexCoord2i ;
+ qglTexCoord2iv = logTexCoord2iv ;
+ qglTexCoord2s = logTexCoord2s ;
+ qglTexCoord2sv = logTexCoord2sv ;
+ qglTexCoord3d = logTexCoord3d ;
+ qglTexCoord3dv = logTexCoord3dv ;
+ qglTexCoord3f = logTexCoord3f ;
+ qglTexCoord3fv = logTexCoord3fv ;
+ qglTexCoord3i = logTexCoord3i ;
+ qglTexCoord3iv = logTexCoord3iv ;
+ qglTexCoord3s = logTexCoord3s ;
+ qglTexCoord3sv = logTexCoord3sv ;
+ qglTexCoord4d = logTexCoord4d ;
+ qglTexCoord4dv = logTexCoord4dv ;
+ qglTexCoord4f = logTexCoord4f ;
+ qglTexCoord4fv = logTexCoord4fv ;
+ qglTexCoord4i = logTexCoord4i ;
+ qglTexCoord4iv = logTexCoord4iv ;
+ qglTexCoord4s = logTexCoord4s ;
+ qglTexCoord4sv = logTexCoord4sv ;
+ qglTexCoordPointer = logTexCoordPointer ;
+ qglTexEnvf = logTexEnvf ;
+ qglTexEnvfv = logTexEnvfv ;
+ qglTexEnvi = logTexEnvi ;
+ qglTexEnviv = logTexEnviv ;
+ qglTexGend = logTexGend ;
+ qglTexGendv = logTexGendv ;
+ qglTexGenf = logTexGenf ;
+ qglTexGenfv = logTexGenfv ;
+ qglTexGeni = logTexGeni ;
+ qglTexGeniv = logTexGeniv ;
+ qglTexImage1D = logTexImage1D ;
+ qglTexImage2D = logTexImage2D ;
+ qglTexParameterf = logTexParameterf ;
+ qglTexParameterfv = logTexParameterfv ;
+ qglTexParameteri = logTexParameteri ;
+ qglTexParameteriv = logTexParameteriv ;
+ qglTexSubImage1D = logTexSubImage1D ;
+ qglTexSubImage2D = logTexSubImage2D ;
+ qglTranslated = logTranslated ;
+ qglTranslatef = logTranslatef ;
+ qglVertex2d = logVertex2d ;
+ qglVertex2dv = logVertex2dv ;
+ qglVertex2f = logVertex2f ;
+ qglVertex2fv = logVertex2fv ;
+ qglVertex2i = logVertex2i ;
+ qglVertex2iv = logVertex2iv ;
+ qglVertex2s = logVertex2s ;
+ qglVertex2sv = logVertex2sv ;
+ qglVertex3d = logVertex3d ;
+ qglVertex3dv = logVertex3dv ;
+ qglVertex3f = logVertex3f ;
+ qglVertex3fv = logVertex3fv ;
+ qglVertex3i = logVertex3i ;
+ qglVertex3iv = logVertex3iv ;
+ qglVertex3s = logVertex3s ;
+ qglVertex3sv = logVertex3sv ;
+ qglVertex4d = logVertex4d ;
+ qglVertex4dv = logVertex4dv ;
+ qglVertex4f = logVertex4f ;
+ qglVertex4fv = logVertex4fv ;
+ qglVertex4i = logVertex4i ;
+ qglVertex4iv = logVertex4iv ;
+ qglVertex4s = logVertex4s ;
+ qglVertex4sv = logVertex4sv ;
+ qglVertexPointer = logVertexPointer ;
+ qglViewport = logViewport ;
+ }
+ else
+ {
+ if ( glw_state.log_fp ) {
+ fprintf( glw_state.log_fp, "*** CLOSING LOG ***\n" );
+ fclose( glw_state.log_fp );
+ glw_state.log_fp = NULL;
+ }
+ qglAccum = dllAccum;
+ qglAlphaFunc = dllAlphaFunc;
+ qglAreTexturesResident = dllAreTexturesResident;
+ qglArrayElement = dllArrayElement;
+ qglBegin = dllBegin;
+ qglBindTexture = dllBindTexture;
+ qglBitmap = dllBitmap;
+ qglBlendFunc = dllBlendFunc;
+ qglCallList = dllCallList;
+ qglCallLists = dllCallLists;
+ qglClear = dllClear;
+ qglClearAccum = dllClearAccum;
+ qglClearColor = dllClearColor;
+ qglClearDepth = dllClearDepth;
+ qglClearIndex = dllClearIndex;
+ qglClearStencil = dllClearStencil;
+ qglClipPlane = dllClipPlane;
+ qglColor3b = dllColor3b;
+ qglColor3bv = dllColor3bv;
+ qglColor3d = dllColor3d;
+ qglColor3dv = dllColor3dv;
+ qglColor3f = dllColor3f;
+ qglColor3fv = dllColor3fv;
+ qglColor3i = dllColor3i;
+ qglColor3iv = dllColor3iv;
+ qglColor3s = dllColor3s;
+ qglColor3sv = dllColor3sv;
+ qglColor3ub = dllColor3ub;
+ qglColor3ubv = dllColor3ubv;
+ qglColor3ui = dllColor3ui;
+ qglColor3uiv = dllColor3uiv;
+ qglColor3us = dllColor3us;
+ qglColor3usv = dllColor3usv;
+ qglColor4b = dllColor4b;
+ qglColor4bv = dllColor4bv;
+ qglColor4d = dllColor4d;
+ qglColor4dv = dllColor4dv;
+ qglColor4f = dllColor4f;
+ qglColor4fv = dllColor4fv;
+ qglColor4i = dllColor4i;
+ qglColor4iv = dllColor4iv;
+ qglColor4s = dllColor4s;
+ qglColor4sv = dllColor4sv;
+ qglColor4ub = dllColor4ub;
+ qglColor4ubv = dllColor4ubv;
+ qglColor4ui = dllColor4ui;
+ qglColor4uiv = dllColor4uiv;
+ qglColor4us = dllColor4us;
+ qglColor4usv = dllColor4usv;
+ qglColorMask = dllColorMask;
+ qglColorMaterial = dllColorMaterial;
+ qglColorPointer = dllColorPointer;
+ qglCopyPixels = dllCopyPixels;
+ qglCopyTexImage1D = dllCopyTexImage1D;
+ qglCopyTexImage2D = dllCopyTexImage2D;
+ qglCopyTexSubImage1D = dllCopyTexSubImage1D;
+ qglCopyTexSubImage2D = dllCopyTexSubImage2D;
+ qglCullFace = dllCullFace;
+ qglDeleteLists = dllDeleteLists ;
+ qglDeleteTextures = dllDeleteTextures ;
+ qglDepthFunc = dllDepthFunc ;
+ qglDepthMask = dllDepthMask ;
+ qglDepthRange = dllDepthRange ;
+ qglDisable = dllDisable ;
+ qglDisableClientState = dllDisableClientState ;
+ qglDrawArrays = dllDrawArrays ;
+ qglDrawBuffer = dllDrawBuffer ;
+ qglDrawElements = dllDrawElements ;
+ qglDrawPixels = dllDrawPixels ;
+ qglEdgeFlag = dllEdgeFlag ;
+ qglEdgeFlagPointer = dllEdgeFlagPointer ;
+ qglEdgeFlagv = dllEdgeFlagv ;
+ qglEnable = dllEnable ;
+ qglEnableClientState = dllEnableClientState ;
+ qglEnd = dllEnd ;
+ qglEndList = dllEndList ;
+ qglEvalCoord1d = dllEvalCoord1d ;
+ qglEvalCoord1dv = dllEvalCoord1dv ;
+ qglEvalCoord1f = dllEvalCoord1f ;
+ qglEvalCoord1fv = dllEvalCoord1fv ;
+ qglEvalCoord2d = dllEvalCoord2d ;
+ qglEvalCoord2dv = dllEvalCoord2dv ;
+ qglEvalCoord2f = dllEvalCoord2f ;
+ qglEvalCoord2fv = dllEvalCoord2fv ;
+ qglEvalMesh1 = dllEvalMesh1 ;
+ qglEvalMesh2 = dllEvalMesh2 ;
+ qglEvalPoint1 = dllEvalPoint1 ;
+ qglEvalPoint2 = dllEvalPoint2 ;
+ qglFeedbackBuffer = dllFeedbackBuffer ;
+ qglFinish = dllFinish ;
+ qglFlush = dllFlush ;
+ qglFogf = dllFogf ;
+ qglFogfv = dllFogfv ;
+ qglFogi = dllFogi ;
+ qglFogiv = dllFogiv ;
+ qglFrontFace = dllFrontFace ;
+ qglFrustum = dllFrustum ;
+ qglGenLists = dllGenLists ;
+ qglGenTextures = dllGenTextures ;
+ qglGetBooleanv = dllGetBooleanv ;
+ qglGetClipPlane = dllGetClipPlane ;
+ qglGetDoublev = dllGetDoublev ;
+ qglGetError = dllGetError ;
+ qglGetFloatv = dllGetFloatv ;
+ qglGetIntegerv = dllGetIntegerv ;
+ qglGetLightfv = dllGetLightfv ;
+ qglGetLightiv = dllGetLightiv ;
+ qglGetMapdv = dllGetMapdv ;
+ qglGetMapfv = dllGetMapfv ;
+ qglGetMapiv = dllGetMapiv ;
+ qglGetMaterialfv = dllGetMaterialfv ;
+ qglGetMaterialiv = dllGetMaterialiv ;
+ qglGetPixelMapfv = dllGetPixelMapfv ;
+ qglGetPixelMapuiv = dllGetPixelMapuiv ;
+ qglGetPixelMapusv = dllGetPixelMapusv ;
+ qglGetPointerv = dllGetPointerv ;
+ qglGetPolygonStipple = dllGetPolygonStipple ;
+ qglGetString = dllGetString ;
+ qglGetTexEnvfv = dllGetTexEnvfv ;
+ qglGetTexEnviv = dllGetTexEnviv ;
+ qglGetTexGendv = dllGetTexGendv ;
+ qglGetTexGenfv = dllGetTexGenfv ;
+ qglGetTexGeniv = dllGetTexGeniv ;
+ qglGetTexImage = dllGetTexImage ;
+ qglGetTexLevelParameterfv = dllGetTexLevelParameterfv ;
+ qglGetTexLevelParameteriv = dllGetTexLevelParameteriv ;
+ qglGetTexParameterfv = dllGetTexParameterfv ;
+ qglGetTexParameteriv = dllGetTexParameteriv ;
+ qglHint = dllHint ;
+ qglIndexMask = dllIndexMask ;
+ qglIndexPointer = dllIndexPointer ;
+ qglIndexd = dllIndexd ;
+ qglIndexdv = dllIndexdv ;
+ qglIndexf = dllIndexf ;
+ qglIndexfv = dllIndexfv ;
+ qglIndexi = dllIndexi ;
+ qglIndexiv = dllIndexiv ;
+ qglIndexs = dllIndexs ;
+ qglIndexsv = dllIndexsv ;
+ qglIndexub = dllIndexub ;
+ qglIndexubv = dllIndexubv ;
+ qglInitNames = dllInitNames ;
+ qglInterleavedArrays = dllInterleavedArrays ;
+ qglIsEnabled = dllIsEnabled ;
+ qglIsList = dllIsList ;
+ qglIsTexture = dllIsTexture ;
+ qglLightModelf = dllLightModelf ;
+ qglLightModelfv = dllLightModelfv ;
+ qglLightModeli = dllLightModeli ;
+ qglLightModeliv = dllLightModeliv ;
+ qglLightf = dllLightf ;
+ qglLightfv = dllLightfv ;
+ qglLighti = dllLighti ;
+ qglLightiv = dllLightiv ;
+ qglLineStipple = dllLineStipple ;
+ qglLineWidth = dllLineWidth ;
+ qglListBase = dllListBase ;
+ qglLoadIdentity = dllLoadIdentity ;
+ qglLoadMatrixd = dllLoadMatrixd ;
+ qglLoadMatrixf = dllLoadMatrixf ;
+ qglLoadName = dllLoadName ;
+ qglLogicOp = dllLogicOp ;
+ qglMap1d = dllMap1d ;
+ qglMap1f = dllMap1f ;
+ qglMap2d = dllMap2d ;
+ qglMap2f = dllMap2f ;
+ qglMapGrid1d = dllMapGrid1d ;
+ qglMapGrid1f = dllMapGrid1f ;
+ qglMapGrid2d = dllMapGrid2d ;
+ qglMapGrid2f = dllMapGrid2f ;
+ qglMaterialf = dllMaterialf ;
+ qglMaterialfv = dllMaterialfv ;
+ qglMateriali = dllMateriali ;
+ qglMaterialiv = dllMaterialiv ;
+ qglMatrixMode = dllMatrixMode ;
+ qglMultMatrixd = dllMultMatrixd ;
+ qglMultMatrixf = dllMultMatrixf ;
+ qglNewList = dllNewList ;
+ qglNormal3b = dllNormal3b ;
+ qglNormal3bv = dllNormal3bv ;
+ qglNormal3d = dllNormal3d ;
+ qglNormal3dv = dllNormal3dv ;
+ qglNormal3f = dllNormal3f ;
+ qglNormal3fv = dllNormal3fv ;
+ qglNormal3i = dllNormal3i ;
+ qglNormal3iv = dllNormal3iv ;
+ qglNormal3s = dllNormal3s ;
+ qglNormal3sv = dllNormal3sv ;
+ qglNormalPointer = dllNormalPointer ;
+ qglOrtho = dllOrtho ;
+ qglPassThrough = dllPassThrough ;
+ qglPixelMapfv = dllPixelMapfv ;
+ qglPixelMapuiv = dllPixelMapuiv ;
+ qglPixelMapusv = dllPixelMapusv ;
+ qglPixelStoref = dllPixelStoref ;
+ qglPixelStorei = dllPixelStorei ;
+ qglPixelTransferf = dllPixelTransferf ;
+ qglPixelTransferi = dllPixelTransferi ;
+ qglPixelZoom = dllPixelZoom ;
+ qglPointSize = dllPointSize ;
+ qglPolygonMode = dllPolygonMode ;
+ qglPolygonOffset = dllPolygonOffset ;
+ qglPolygonStipple = dllPolygonStipple ;
+ qglPopAttrib = dllPopAttrib ;
+ qglPopClientAttrib = dllPopClientAttrib ;
+ qglPopMatrix = dllPopMatrix ;
+ qglPopName = dllPopName ;
+ qglPrioritizeTextures = dllPrioritizeTextures ;
+ qglPushAttrib = dllPushAttrib ;
+ qglPushClientAttrib = dllPushClientAttrib ;
+ qglPushMatrix = dllPushMatrix ;
+ qglPushName = dllPushName ;
+ qglRasterPos2d = dllRasterPos2d ;
+ qglRasterPos2dv = dllRasterPos2dv ;
+ qglRasterPos2f = dllRasterPos2f ;
+ qglRasterPos2fv = dllRasterPos2fv ;
+ qglRasterPos2i = dllRasterPos2i ;
+ qglRasterPos2iv = dllRasterPos2iv ;
+ qglRasterPos2s = dllRasterPos2s ;
+ qglRasterPos2sv = dllRasterPos2sv ;
+ qglRasterPos3d = dllRasterPos3d ;
+ qglRasterPos3dv = dllRasterPos3dv ;
+ qglRasterPos3f = dllRasterPos3f ;
+ qglRasterPos3fv = dllRasterPos3fv ;
+ qglRasterPos3i = dllRasterPos3i ;
+ qglRasterPos3iv = dllRasterPos3iv ;
+ qglRasterPos3s = dllRasterPos3s ;
+ qglRasterPos3sv = dllRasterPos3sv ;
+ qglRasterPos4d = dllRasterPos4d ;
+ qglRasterPos4dv = dllRasterPos4dv ;
+ qglRasterPos4f = dllRasterPos4f ;
+ qglRasterPos4fv = dllRasterPos4fv ;
+ qglRasterPos4i = dllRasterPos4i ;
+ qglRasterPos4iv = dllRasterPos4iv ;
+ qglRasterPos4s = dllRasterPos4s ;
+ qglRasterPos4sv = dllRasterPos4sv ;
+ qglReadBuffer = dllReadBuffer ;
+ qglReadPixels = dllReadPixels ;
+ qglRectd = dllRectd ;
+ qglRectdv = dllRectdv ;
+ qglRectf = dllRectf ;
+ qglRectfv = dllRectfv ;
+ qglRecti = dllRecti ;
+ qglRectiv = dllRectiv ;
+ qglRects = dllRects ;
+ qglRectsv = dllRectsv ;
+ qglRenderMode = dllRenderMode ;
+ qglRotated = dllRotated ;
+ qglRotatef = dllRotatef ;
+ qglScaled = dllScaled ;
+ qglScalef = dllScalef ;
+ qglScissor = dllScissor ;
+ qglSelectBuffer = dllSelectBuffer ;
+ qglShadeModel = dllShadeModel ;
+ qglStencilFunc = dllStencilFunc ;
+ qglStencilMask = dllStencilMask ;
+ qglStencilOp = dllStencilOp ;
+ qglTexCoord1d = dllTexCoord1d ;
+ qglTexCoord1dv = dllTexCoord1dv ;
+ qglTexCoord1f = dllTexCoord1f ;
+ qglTexCoord1fv = dllTexCoord1fv ;
+ qglTexCoord1i = dllTexCoord1i ;
+ qglTexCoord1iv = dllTexCoord1iv ;
+ qglTexCoord1s = dllTexCoord1s ;
+ qglTexCoord1sv = dllTexCoord1sv ;
+ qglTexCoord2d = dllTexCoord2d ;
+ qglTexCoord2dv = dllTexCoord2dv ;
+ qglTexCoord2f = dllTexCoord2f ;
+ qglTexCoord2fv = dllTexCoord2fv ;
+ qglTexCoord2i = dllTexCoord2i ;
+ qglTexCoord2iv = dllTexCoord2iv ;
+ qglTexCoord2s = dllTexCoord2s ;
+ qglTexCoord2sv = dllTexCoord2sv ;
+ qglTexCoord3d = dllTexCoord3d ;
+ qglTexCoord3dv = dllTexCoord3dv ;
+ qglTexCoord3f = dllTexCoord3f ;
+ qglTexCoord3fv = dllTexCoord3fv ;
+ qglTexCoord3i = dllTexCoord3i ;
+ qglTexCoord3iv = dllTexCoord3iv ;
+ qglTexCoord3s = dllTexCoord3s ;
+ qglTexCoord3sv = dllTexCoord3sv ;
+ qglTexCoord4d = dllTexCoord4d ;
+ qglTexCoord4dv = dllTexCoord4dv ;
+ qglTexCoord4f = dllTexCoord4f ;
+ qglTexCoord4fv = dllTexCoord4fv ;
+ qglTexCoord4i = dllTexCoord4i ;
+ qglTexCoord4iv = dllTexCoord4iv ;
+ qglTexCoord4s = dllTexCoord4s ;
+ qglTexCoord4sv = dllTexCoord4sv ;
+ qglTexCoordPointer = dllTexCoordPointer ;
+ qglTexEnvf = dllTexEnvf ;
+ qglTexEnvfv = dllTexEnvfv ;
+ qglTexEnvi = dllTexEnvi ;
+ qglTexEnviv = dllTexEnviv ;
+ qglTexGend = dllTexGend ;
+ qglTexGendv = dllTexGendv ;
+ qglTexGenf = dllTexGenf ;
+ qglTexGenfv = dllTexGenfv ;
+ qglTexGeni = dllTexGeni ;
+ qglTexGeniv = dllTexGeniv ;
+ qglTexImage1D = dllTexImage1D ;
+ qglTexImage2D = dllTexImage2D ;
+ qglTexParameterf = dllTexParameterf ;
+ qglTexParameterfv = dllTexParameterfv ;
+ qglTexParameteri = dllTexParameteri ;
+ qglTexParameteriv = dllTexParameteriv ;
+ qglTexSubImage1D = dllTexSubImage1D ;
+ qglTexSubImage2D = dllTexSubImage2D ;
+ qglTranslated = dllTranslated ;
+ qglTranslatef = dllTranslatef ;
+ qglVertex2d = dllVertex2d ;
+ qglVertex2dv = dllVertex2dv ;
+ qglVertex2f = dllVertex2f ;
+ qglVertex2fv = dllVertex2fv ;
+ qglVertex2i = dllVertex2i ;
+ qglVertex2iv = dllVertex2iv ;
+ qglVertex2s = dllVertex2s ;
+ qglVertex2sv = dllVertex2sv ;
+ qglVertex3d = dllVertex3d ;
+ qglVertex3dv = dllVertex3dv ;
+ qglVertex3f = dllVertex3f ;
+ qglVertex3fv = dllVertex3fv ;
+ qglVertex3i = dllVertex3i ;
+ qglVertex3iv = dllVertex3iv ;
+ qglVertex3s = dllVertex3s ;
+ qglVertex3sv = dllVertex3sv ;
+ qglVertex4d = dllVertex4d ;
+ qglVertex4dv = dllVertex4dv ;
+ qglVertex4f = dllVertex4f ;
+ qglVertex4fv = dllVertex4fv ;
+ qglVertex4i = dllVertex4i ;
+ qglVertex4iv = dllVertex4iv ;
+ qglVertex4s = dllVertex4s ;
+ qglVertex4sv = dllVertex4sv ;
+ qglVertexPointer = dllVertexPointer ;
+ qglViewport = dllViewport ;
+ }
+}
+
+#pragma warning (default : 4113 4133 4047 )
+
+
+
diff --git a/code/win32/win_shared.c b/code/win32/win_shared.c
new file mode 100755
index 0000000..996d6d3
--- /dev/null
+++ b/code/win32/win_shared.c
@@ -0,0 +1,306 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "../game/q_shared.h"
+#include "../qcommon/qcommon.h"
+#include "win_local.h"
+#include <lmerr.h>
+#include <lmcons.h>
+#include <lmwksta.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <direct.h>
+#include <io.h>
+#include <conio.h>
+
+/*
+================
+Sys_Milliseconds
+================
+*/
+int sys_timeBase;
+int Sys_Milliseconds (void)
+{
+ int sys_curtime;
+ static qboolean initialized = qfalse;
+
+ if (!initialized) {
+ sys_timeBase = timeGetTime();
+ initialized = qtrue;
+ }
+ sys_curtime = timeGetTime() - sys_timeBase;
+
+ return sys_curtime;
+}
+
+/*
+================
+Sys_SnapVector
+================
+*/
+long fastftol( float f ) {
+ static int tmp;
+ __asm fld f
+ __asm fistp tmp
+ __asm mov eax, tmp
+}
+
+void Sys_SnapVector( float *v )
+{
+ int i;
+ float f;
+
+ f = *v;
+ __asm fld f;
+ __asm fistp i;
+ *v = i;
+ v++;
+ f = *v;
+ __asm fld f;
+ __asm fistp i;
+ *v = i;
+ v++;
+ f = *v;
+ __asm fld f;
+ __asm fistp i;
+ *v = i;
+ /*
+ *v = fastftol(*v);
+ v++;
+ *v = fastftol(*v);
+ v++;
+ *v = fastftol(*v);
+ */
+}
+
+
+/*
+**
+** Disable all optimizations temporarily so this code works correctly!
+**
+*/
+#pragma optimize( "", off )
+
+/*
+** --------------------------------------------------------------------------------
+**
+** PROCESSOR STUFF
+**
+** --------------------------------------------------------------------------------
+*/
+static void CPUID( int func, unsigned regs[4] )
+{
+ unsigned regEAX, regEBX, regECX, regEDX;
+
+#ifndef __VECTORC
+ __asm mov eax, func
+ __asm __emit 00fh
+ __asm __emit 0a2h
+ __asm mov regEAX, eax
+ __asm mov regEBX, ebx
+ __asm mov regECX, ecx
+ __asm mov regEDX, edx
+
+ regs[0] = regEAX;
+ regs[1] = regEBX;
+ regs[2] = regECX;
+ regs[3] = regEDX;
+#else
+ regs[0] = 0;
+ regs[1] = 0;
+ regs[2] = 0;
+ regs[3] = 0;
+#endif
+}
+
+static int IsPentium( void )
+{
+ __asm
+ {
+ pushfd // save eflags
+ pop eax
+ test eax, 0x00200000 // check ID bit
+ jz set21 // bit 21 is not set, so jump to set_21
+ and eax, 0xffdfffff // clear bit 21
+ push eax // save new value in register
+ popfd // store new value in flags
+ pushfd
+ pop eax
+ test eax, 0x00200000 // check ID bit
+ jz good
+ jmp err // cpuid not supported
+set21:
+ or eax, 0x00200000 // set ID bit
+ push eax // store new value
+ popfd // store new value in EFLAGS
+ pushfd
+ pop eax
+ test eax, 0x00200000 // if bit 21 is on
+ jnz good
+ jmp err
+ }
+
+err:
+ return qfalse;
+good:
+ return qtrue;
+}
+
+static int Is3DNOW( void )
+{
+ unsigned regs[4];
+ char pstring[16];
+ char processorString[13];
+
+ // get name of processor
+ CPUID( 0, ( unsigned int * ) pstring );
+ processorString[0] = pstring[4];
+ processorString[1] = pstring[5];
+ processorString[2] = pstring[6];
+ processorString[3] = pstring[7];
+ processorString[4] = pstring[12];
+ processorString[5] = pstring[13];
+ processorString[6] = pstring[14];
+ processorString[7] = pstring[15];
+ processorString[8] = pstring[8];
+ processorString[9] = pstring[9];
+ processorString[10] = pstring[10];
+ processorString[11] = pstring[11];
+ processorString[12] = 0;
+
+// REMOVED because you can have 3DNow! on non-AMD systems
+// if ( strcmp( processorString, "AuthenticAMD" ) )
+// return qfalse;
+
+ // check AMD-specific functions
+ CPUID( 0x80000000, regs );
+ if ( regs[0] < 0x80000000 )
+ return qfalse;
+
+ // bit 31 of EDX denotes 3DNOW! support
+ CPUID( 0x80000001, regs );
+ if ( regs[3] & ( 1 << 31 ) )
+ return qtrue;
+
+ return qfalse;
+}
+
+static int IsKNI( void )
+{
+ unsigned regs[4];
+
+ // get CPU feature bits
+ CPUID( 1, regs );
+
+ // bit 25 of EDX denotes KNI existence
+ if ( regs[3] & ( 1 << 25 ) )
+ return qtrue;
+
+ return qfalse;
+}
+
+static int IsMMX( void )
+{
+ unsigned regs[4];
+
+ // get CPU feature bits
+ CPUID( 1, regs );
+
+ // bit 23 of EDX denotes MMX existence
+ if ( regs[3] & ( 1 << 23 ) )
+ return qtrue;
+ return qfalse;
+}
+
+int Sys_GetProcessorId( void )
+{
+#if defined _M_ALPHA
+ return CPUID_AXP;
+#elif !defined _M_IX86
+ return CPUID_GENERIC;
+#else
+
+ // verify we're at least a Pentium or 486 w/ CPUID support
+ if ( !IsPentium() )
+ return CPUID_INTEL_UNSUPPORTED;
+
+ // check for MMX
+ if ( !IsMMX() )
+ {
+ // Pentium or PPro
+ return CPUID_INTEL_PENTIUM;
+ }
+
+ // see if we're an AMD 3DNOW! processor
+ if ( Is3DNOW() )
+ {
+ return CPUID_AMD_3DNOW;
+ }
+
+ // see if we're an Intel Katmai
+ if ( IsKNI() )
+ {
+ return CPUID_INTEL_KATMAI;
+ }
+
+ // by default we're functionally a vanilla Pentium/MMX or P2/MMX
+ return CPUID_INTEL_MMX;
+
+#endif
+}
+
+/*
+**
+** Re-enable optimizations back to what they were
+**
+*/
+#pragma optimize( "", on )
+
+//============================================
+
+char *Sys_GetCurrentUser( void )
+{
+ static char s_userName[1024];
+ unsigned long size = sizeof( s_userName );
+
+
+ if ( !GetUserName( s_userName, &size ) )
+ strcpy( s_userName, "player" );
+
+ if ( !s_userName[0] )
+ {
+ strcpy( s_userName, "player" );
+ }
+
+ return s_userName;
+}
+
+char *Sys_DefaultHomePath(void) {
+ return NULL;
+}
+
+char *Sys_DefaultInstallPath(void)
+{
+ return Sys_Cwd();
+}
+
diff --git a/code/win32/win_snd.c b/code/win32/win_snd.c
new file mode 100755
index 0000000..224d06d
--- /dev/null
+++ b/code/win32/win_snd.c
@@ -0,0 +1,388 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include <float.h>
+
+#include "../client/snd_local.h"
+#include "win_local.h"
+
+HRESULT (WINAPI *pDirectSoundCreate)(GUID FAR *lpGUID, LPDIRECTSOUND FAR *lplpDS, IUnknown FAR *pUnkOuter);
+#define iDirectSoundCreate(a,b,c) pDirectSoundCreate(a,b,c)
+
+#define SECONDARY_BUFFER_SIZE 0x10000
+
+
+static qboolean dsound_init;
+static int sample16;
+static DWORD gSndBufSize;
+static DWORD locksize;
+static LPDIRECTSOUND pDS;
+static LPDIRECTSOUNDBUFFER pDSBuf, pDSPBuf;
+static HINSTANCE hInstDS;
+
+
+static const char *DSoundError( int error ) {
+ switch ( error ) {
+ case DSERR_BUFFERLOST:
+ return "DSERR_BUFFERLOST";
+ case DSERR_INVALIDCALL:
+ return "DSERR_INVALIDCALLS";
+ case DSERR_INVALIDPARAM:
+ return "DSERR_INVALIDPARAM";
+ case DSERR_PRIOLEVELNEEDED:
+ return "DSERR_PRIOLEVELNEEDED";
+ }
+
+ return "unknown";
+}
+
+/*
+==================
+SNDDMA_Shutdown
+==================
+*/
+void SNDDMA_Shutdown( void ) {
+ Com_DPrintf( "Shutting down sound system\n" );
+
+ if ( pDS ) {
+ Com_DPrintf( "Destroying DS buffers\n" );
+ if ( pDS )
+ {
+ Com_DPrintf( "...setting NORMAL coop level\n" );
+ pDS->lpVtbl->SetCooperativeLevel( pDS, g_wv.hWnd, DSSCL_PRIORITY );
+ }
+
+ if ( pDSBuf )
+ {
+ Com_DPrintf( "...stopping and releasing sound buffer\n" );
+ pDSBuf->lpVtbl->Stop( pDSBuf );
+ pDSBuf->lpVtbl->Release( pDSBuf );
+ }
+
+ // only release primary buffer if it's not also the mixing buffer we just released
+ if ( pDSPBuf && ( pDSBuf != pDSPBuf ) )
+ {
+ Com_DPrintf( "...releasing primary buffer\n" );
+ pDSPBuf->lpVtbl->Release( pDSPBuf );
+ }
+ pDSBuf = NULL;
+ pDSPBuf = NULL;
+
+ dma.buffer = NULL;
+
+ Com_DPrintf( "...releasing DS object\n" );
+ pDS->lpVtbl->Release( pDS );
+ }
+
+ if ( hInstDS ) {
+ Com_DPrintf( "...freeing DSOUND.DLL\n" );
+ FreeLibrary( hInstDS );
+ hInstDS = NULL;
+ }
+
+ pDS = NULL;
+ pDSBuf = NULL;
+ pDSPBuf = NULL;
+ dsound_init = qfalse;
+ memset ((void *)&dma, 0, sizeof (dma));
+ CoUninitialize( );
+}
+
+/*
+==================
+SNDDMA_Init
+
+Initialize direct sound
+Returns false if failed
+==================
+*/
+qboolean SNDDMA_Init(void) {
+
+ memset ((void *)&dma, 0, sizeof (dma));
+ dsound_init = 0;
+
+ CoInitialize(NULL);
+
+ if ( !SNDDMA_InitDS () ) {
+ return qfalse;
+ }
+
+ dsound_init = qtrue;
+
+ Com_DPrintf("Completed successfully\n" );
+
+ return qtrue;
+}
+
+#undef DEFINE_GUID
+
+#define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
+ EXTERN_C const GUID name \
+ = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }
+
+// DirectSound Component GUID {47D4D946-62E8-11CF-93BC-444553540000}
+DEFINE_GUID(CLSID_DirectSound, 0x47d4d946, 0x62e8, 0x11cf, 0x93, 0xbc, 0x44, 0x45, 0x53, 0x54, 0x0, 0x0);
+
+// DirectSound 8.0 Component GUID {3901CC3F-84B5-4FA4-BA35-AA8172B8A09B}
+DEFINE_GUID(CLSID_DirectSound8, 0x3901cc3f, 0x84b5, 0x4fa4, 0xba, 0x35, 0xaa, 0x81, 0x72, 0xb8, 0xa0, 0x9b);
+
+DEFINE_GUID(IID_IDirectSound8, 0xC50A7E93, 0xF395, 0x4834, 0x9E, 0xF6, 0x7F, 0xA9, 0x9D, 0xE5, 0x09, 0x66);
+DEFINE_GUID(IID_IDirectSound, 0x279AFA83, 0x4981, 0x11CE, 0xA5, 0x21, 0x00, 0x20, 0xAF, 0x0B, 0xE5, 0x60);
+
+
+int SNDDMA_InitDS ()
+{
+ HRESULT hresult;
+ DSBUFFERDESC dsbuf;
+ DSBCAPS dsbcaps;
+ WAVEFORMATEX format;
+ int use8;
+
+ Com_Printf( "Initializing DirectSound\n");
+
+ use8 = 1;
+ // Create IDirectSound using the primary sound device
+ if( FAILED( hresult = CoCreateInstance(&CLSID_DirectSound8, NULL, CLSCTX_INPROC_SERVER, &IID_IDirectSound8, (void **)&pDS))) {
+ use8 = 0;
+ if( FAILED( hresult = CoCreateInstance(&CLSID_DirectSound, NULL, CLSCTX_INPROC_SERVER, &IID_IDirectSound, (void **)&pDS))) {
+ Com_Printf ("failed\n");
+ SNDDMA_Shutdown ();
+ return qfalse;
+ }
+ }
+
+ hresult = pDS->lpVtbl->Initialize( pDS, NULL);
+
+ Com_DPrintf( "ok\n" );
+
+ Com_DPrintf("...setting DSSCL_PRIORITY coop level: " );
+
+ if ( DS_OK != pDS->lpVtbl->SetCooperativeLevel( pDS, g_wv.hWnd, DSSCL_PRIORITY ) ) {
+ Com_Printf ("failed\n");
+ SNDDMA_Shutdown ();
+ return qfalse;
+ }
+ Com_DPrintf("ok\n" );
+
+
+ // create the secondary buffer we'll actually work with
+ dma.channels = 2;
+ dma.samplebits = 16;
+
+// if (s_khz->integer == 44)
+// dma.speed = 44100;
+// else if (s_khz->integer == 22)
+// dma.speed = 22050;
+// else
+// dma.speed = 11025;
+
+ dma.speed = 22050;
+ memset (&format, 0, sizeof(format));
+ format.wFormatTag = WAVE_FORMAT_PCM;
+ format.nChannels = dma.channels;
+ format.wBitsPerSample = dma.samplebits;
+ format.nSamplesPerSec = dma.speed;
+ format.nBlockAlign = format.nChannels * format.wBitsPerSample / 8;
+ format.cbSize = 0;
+ format.nAvgBytesPerSec = format.nSamplesPerSec*format.nBlockAlign;
+
+ memset (&dsbuf, 0, sizeof(dsbuf));
+ dsbuf.dwSize = sizeof(DSBUFFERDESC);
+
+ // Micah: take advantage of 2D hardware.if available.
+ dsbuf.dwFlags = DSBCAPS_LOCHARDWARE;
+ if (use8) {
+ dsbuf.dwFlags |= DSBCAPS_GETCURRENTPOSITION2;
+ }
+ dsbuf.dwBufferBytes = SECONDARY_BUFFER_SIZE;
+ dsbuf.lpwfxFormat = &format;
+
+ memset(&dsbcaps, 0, sizeof(dsbcaps));
+ dsbcaps.dwSize = sizeof(dsbcaps);
+
+ Com_DPrintf( "...creating secondary buffer: " );
+ if (DS_OK == pDS->lpVtbl->CreateSoundBuffer(pDS, &dsbuf, &pDSBuf, NULL)) {
+ Com_Printf( "locked hardware. ok\n" );
+ }
+ else {
+ // Couldn't get hardware, fallback to software.
+ dsbuf.dwFlags = DSBCAPS_LOCSOFTWARE;
+ if (use8) {
+ dsbuf.dwFlags |= DSBCAPS_GETCURRENTPOSITION2;
+ }
+ if (DS_OK != pDS->lpVtbl->CreateSoundBuffer(pDS, &dsbuf, &pDSBuf, NULL)) {
+ Com_Printf( "failed\n" );
+ SNDDMA_Shutdown ();
+ return qfalse;
+ }
+ Com_DPrintf( "forced to software. ok\n" );
+ }
+
+ // Make sure mixer is active
+ if ( DS_OK != pDSBuf->lpVtbl->Play(pDSBuf, 0, 0, DSBPLAY_LOOPING) ) {
+ Com_Printf ("*** Looped sound play failed ***\n");
+ SNDDMA_Shutdown ();
+ return qfalse;
+ }
+
+ // get the returned buffer size
+ if ( DS_OK != pDSBuf->lpVtbl->GetCaps (pDSBuf, &dsbcaps) ) {
+ Com_Printf ("*** GetCaps failed ***\n");
+ SNDDMA_Shutdown ();
+ return qfalse;
+ }
+
+ gSndBufSize = dsbcaps.dwBufferBytes;
+
+ dma.channels = format.nChannels;
+ dma.samplebits = format.wBitsPerSample;
+ dma.speed = format.nSamplesPerSec;
+ dma.samples = gSndBufSize/(dma.samplebits/8);
+ dma.submission_chunk = 1;
+ dma.buffer = NULL; // must be locked first
+
+ sample16 = (dma.samplebits/8) - 1;
+
+ SNDDMA_BeginPainting ();
+ if (dma.buffer)
+ memset(dma.buffer, 0, dma.samples * dma.samplebits/8);
+ SNDDMA_Submit ();
+ return 1;
+}
+/*
+==============
+SNDDMA_GetDMAPos
+
+return the current sample position (in mono samples read)
+inside the recirculating dma buffer, so the mixing code will know
+how many sample are required to fill it up.
+===============
+*/
+int SNDDMA_GetDMAPos( void ) {
+ MMTIME mmtime;
+ int s;
+ DWORD dwWrite;
+
+ if ( !dsound_init ) {
+ return 0;
+ }
+
+ mmtime.wType = TIME_SAMPLES;
+ pDSBuf->lpVtbl->GetCurrentPosition(pDSBuf, &mmtime.u.sample, &dwWrite);
+
+ s = mmtime.u.sample;
+
+ s >>= sample16;
+
+ s &= (dma.samples-1);
+
+ return s;
+}
+
+/*
+==============
+SNDDMA_BeginPainting
+
+Makes sure dma.buffer is valid
+===============
+*/
+void SNDDMA_BeginPainting( void ) {
+ int reps;
+ DWORD dwSize2;
+ DWORD *pbuf, *pbuf2;
+ HRESULT hresult;
+ DWORD dwStatus;
+
+ if ( !pDSBuf ) {
+ return;
+ }
+
+ // if the buffer was lost or stopped, restore it and/or restart it
+ if ( pDSBuf->lpVtbl->GetStatus (pDSBuf, &dwStatus) != DS_OK ) {
+ Com_Printf ("Couldn't get sound buffer status\n");
+ }
+
+ if (dwStatus & DSBSTATUS_BUFFERLOST)
+ pDSBuf->lpVtbl->Restore (pDSBuf);
+
+ if (!(dwStatus & DSBSTATUS_PLAYING))
+ pDSBuf->lpVtbl->Play(pDSBuf, 0, 0, DSBPLAY_LOOPING);
+
+ // lock the dsound buffer
+
+ reps = 0;
+ dma.buffer = NULL;
+
+ while ((hresult = pDSBuf->lpVtbl->Lock(pDSBuf, 0, gSndBufSize, &pbuf, &locksize,
+ &pbuf2, &dwSize2, 0)) != DS_OK)
+ {
+ if (hresult != DSERR_BUFFERLOST)
+ {
+ Com_Printf( "SNDDMA_BeginPainting: Lock failed with error '%s'\n", DSoundError( hresult ) );
+ S_Shutdown ();
+ return;
+ }
+ else
+ {
+ pDSBuf->lpVtbl->Restore( pDSBuf );
+ }
+
+ if (++reps > 2)
+ return;
+ }
+ dma.buffer = (unsigned char *)pbuf;
+}
+
+/*
+==============
+SNDDMA_Submit
+
+Send sound to device if buffer isn't really the dma buffer
+Also unlocks the dsound buffer
+===============
+*/
+void SNDDMA_Submit( void ) {
+ // unlock the dsound buffer
+ if ( pDSBuf ) {
+ pDSBuf->lpVtbl->Unlock(pDSBuf, dma.buffer, locksize, NULL, 0);
+ }
+}
+
+
+/*
+=================
+SNDDMA_Activate
+
+When we change windows we need to do this
+=================
+*/
+void SNDDMA_Activate( void ) {
+ if ( !pDS ) {
+ return;
+ }
+
+ if ( DS_OK != pDS->lpVtbl->SetCooperativeLevel( pDS, g_wv.hWnd, DSSCL_PRIORITY ) ) {
+ Com_Printf ("sound SetCooperativeLevel failed\n");
+ SNDDMA_Shutdown ();
+ }
+}
+
+
diff --git a/code/win32/win_syscon.c b/code/win32/win_syscon.c
new file mode 100755
index 0000000..9d1e425
--- /dev/null
+++ b/code/win32/win_syscon.c
@@ -0,0 +1,596 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// win_syscon.h
+#include "../client/client.h"
+#include "win_local.h"
+#include "resource.h"
+#include <errno.h>
+#include <float.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <direct.h>
+#include <io.h>
+#include <conio.h>
+
+#define COPY_ID 1
+#define QUIT_ID 2
+#define CLEAR_ID 3
+
+#define ERRORBOX_ID 10
+#define ERRORTEXT_ID 11
+
+#define EDIT_ID 100
+#define INPUT_ID 101
+
+typedef struct
+{
+ HWND hWnd;
+ HWND hwndBuffer;
+
+ HWND hwndButtonClear;
+ HWND hwndButtonCopy;
+ HWND hwndButtonQuit;
+
+ HWND hwndErrorBox;
+ HWND hwndErrorText;
+
+ HBITMAP hbmLogo;
+ HBITMAP hbmClearBitmap;
+
+ HBRUSH hbrEditBackground;
+ HBRUSH hbrErrorBackground;
+
+ HFONT hfBufferFont;
+ HFONT hfButtonFont;
+
+ HWND hwndInputLine;
+
+ char errorString[80];
+
+ char consoleText[512], returnedText[512];
+ int visLevel;
+ qboolean quitOnClose;
+ int windowWidth, windowHeight;
+
+ WNDPROC SysInputLineWndProc;
+
+} WinConData;
+
+static WinConData s_wcd;
+
+static LONG WINAPI ConWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
+{
+ char *cmdString;
+ static qboolean s_timePolarity;
+
+ switch (uMsg)
+ {
+ case WM_ACTIVATE:
+ if ( LOWORD( wParam ) != WA_INACTIVE )
+ {
+ SetFocus( s_wcd.hwndInputLine );
+ }
+
+ if ( com_viewlog && ( com_dedicated && !com_dedicated->integer ) )
+ {
+ // if the viewlog is open, check to see if it's being minimized
+ if ( com_viewlog->integer == 1 )
+ {
+ if ( HIWORD( wParam ) ) // minimized flag
+ {
+ Cvar_Set( "viewlog", "2" );
+ }
+ }
+ else if ( com_viewlog->integer == 2 )
+ {
+ if ( !HIWORD( wParam ) ) // minimized flag
+ {
+ Cvar_Set( "viewlog", "1" );
+ }
+ }
+ }
+ break;
+
+ case WM_CLOSE:
+ if ( ( com_dedicated && com_dedicated->integer ) )
+ {
+ cmdString = CopyString( "quit" );
+ Sys_QueEvent( 0, SE_CONSOLE, 0, 0, strlen( cmdString ) + 1, cmdString );
+ }
+ else if ( s_wcd.quitOnClose )
+ {
+ PostQuitMessage( 0 );
+ }
+ else
+ {
+ Sys_ShowConsole( 0, qfalse );
+ Cvar_Set( "viewlog", "0" );
+ }
+ return 0;
+ case WM_CTLCOLORSTATIC:
+ if ( ( HWND ) lParam == s_wcd.hwndBuffer )
+ {
+ SetBkColor( ( HDC ) wParam, RGB( 0x00, 0x00, 0xB0 ) );
+ SetTextColor( ( HDC ) wParam, RGB( 0xff, 0xff, 0x00 ) );
+
+#if 0 // this draws a background in the edit box, but there are issues with this
+ if ( ( hdcScaled = CreateCompatibleDC( ( HDC ) wParam ) ) != 0 )
+ {
+ if ( SelectObject( ( HDC ) hdcScaled, s_wcd.hbmLogo ) )
+ {
+ StretchBlt( ( HDC ) wParam, 0, 0, 512, 384,
+ hdcScaled, 0, 0, 512, 384,
+ SRCCOPY );
+ }
+ DeleteDC( hdcScaled );
+ }
+#endif
+ return ( long ) s_wcd.hbrEditBackground;
+ }
+ else if ( ( HWND ) lParam == s_wcd.hwndErrorBox )
+ {
+ if ( s_timePolarity & 1 )
+ {
+ SetBkColor( ( HDC ) wParam, RGB( 0x80, 0x80, 0x80 ) );
+ SetTextColor( ( HDC ) wParam, RGB( 0xff, 0x0, 0x00 ) );
+ }
+ else
+ {
+ SetBkColor( ( HDC ) wParam, RGB( 0x80, 0x80, 0x80 ) );
+ SetTextColor( ( HDC ) wParam, RGB( 0x00, 0x0, 0x00 ) );
+ }
+ return ( long ) s_wcd.hbrErrorBackground;
+ }
+ break;
+
+ case WM_COMMAND:
+ if ( wParam == COPY_ID )
+ {
+ SendMessage( s_wcd.hwndBuffer, EM_SETSEL, 0, -1 );
+ SendMessage( s_wcd.hwndBuffer, WM_COPY, 0, 0 );
+ }
+ else if ( wParam == QUIT_ID )
+ {
+ if ( s_wcd.quitOnClose )
+ {
+ PostQuitMessage( 0 );
+ }
+ else
+ {
+ cmdString = CopyString( "quit" );
+ Sys_QueEvent( 0, SE_CONSOLE, 0, 0, strlen( cmdString ) + 1, cmdString );
+ }
+ }
+ else if ( wParam == CLEAR_ID )
+ {
+ SendMessage( s_wcd.hwndBuffer, EM_SETSEL, 0, -1 );
+ SendMessage( s_wcd.hwndBuffer, EM_REPLACESEL, FALSE, ( LPARAM ) "" );
+ UpdateWindow( s_wcd.hwndBuffer );
+ }
+ break;
+ case WM_CREATE:
+// s_wcd.hbmLogo = LoadBitmap( g_wv.hInstance, MAKEINTRESOURCE( IDB_BITMAP1 ) );
+// s_wcd.hbmClearBitmap = LoadBitmap( g_wv.hInstance, MAKEINTRESOURCE( IDB_BITMAP2 ) );
+ s_wcd.hbrEditBackground = CreateSolidBrush( RGB( 0x00, 0x00, 0xB0 ) );
+ s_wcd.hbrErrorBackground = CreateSolidBrush( RGB( 0x80, 0x80, 0x80 ) );
+ SetTimer( hWnd, 1, 1000, NULL );
+ break;
+ case WM_ERASEBKGND:
+#if 0
+ HDC hdcScaled;
+ HGDIOBJ oldObject;
+
+#if 1 // a single, large image
+ hdcScaled = CreateCompatibleDC( ( HDC ) wParam );
+ assert( hdcScaled != 0 );
+
+ if ( hdcScaled )
+ {
+ oldObject = SelectObject( ( HDC ) hdcScaled, s_wcd.hbmLogo );
+ assert( oldObject != 0 );
+ if ( oldObject )
+ {
+ StretchBlt( ( HDC ) wParam, 0, 0, s_wcd.windowWidth, s_wcd.windowHeight,
+ hdcScaled, 0, 0, 512, 384,
+ SRCCOPY );
+ }
+ DeleteDC( hdcScaled );
+ hdcScaled = 0;
+ }
+#else // a repeating brush
+ {
+ HBRUSH hbrClearBrush;
+ RECT r;
+
+ GetWindowRect( hWnd, &r );
+
+ r.bottom = r.bottom - r.top + 1;
+ r.right = r.right - r.left + 1;
+ r.top = 0;
+ r.left = 0;
+
+ hbrClearBrush = CreatePatternBrush( s_wcd.hbmClearBitmap );
+
+ assert( hbrClearBrush != 0 );
+
+ if ( hbrClearBrush )
+ {
+ FillRect( ( HDC ) wParam, &r, hbrClearBrush );
+ DeleteObject( hbrClearBrush );
+ }
+ }
+#endif
+ return 1;
+#endif
+ return DefWindowProc( hWnd, uMsg, wParam, lParam );
+ case WM_TIMER:
+ if ( wParam == 1 )
+ {
+ s_timePolarity = !s_timePolarity;
+ if ( s_wcd.hwndErrorBox )
+ {
+ InvalidateRect( s_wcd.hwndErrorBox, NULL, FALSE );
+ }
+ }
+ break;
+ }
+
+ return DefWindowProc( hWnd, uMsg, wParam, lParam );
+}
+
+LONG WINAPI InputLineWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
+{
+ char inputBuffer[1024];
+
+ switch ( uMsg )
+ {
+ case WM_KILLFOCUS:
+ if ( ( HWND ) wParam == s_wcd.hWnd ||
+ ( HWND ) wParam == s_wcd.hwndErrorBox )
+ {
+ SetFocus( hWnd );
+ return 0;
+ }
+ break;
+
+ case WM_CHAR:
+ if ( wParam == 13 )
+ {
+ GetWindowText( s_wcd.hwndInputLine, inputBuffer, sizeof( inputBuffer ) );
+ strncat( s_wcd.consoleText, inputBuffer, sizeof( s_wcd.consoleText ) - strlen( s_wcd.consoleText ) - 5 );
+ strcat( s_wcd.consoleText, "\n" );
+ SetWindowText( s_wcd.hwndInputLine, "" );
+
+ Sys_Print( va( "]%s\n", inputBuffer ) );
+
+ return 0;
+ }
+ }
+
+ return CallWindowProc( s_wcd.SysInputLineWndProc, hWnd, uMsg, wParam, lParam );
+}
+
+/*
+** Sys_CreateConsole
+*/
+void Sys_CreateConsole( void )
+{
+ HDC hDC;
+ WNDCLASS wc;
+ RECT rect;
+ const char *DEDCLASS = "Q3 WinConsole";
+ int nHeight;
+ int swidth, sheight;
+ int DEDSTYLE = WS_POPUPWINDOW | WS_CAPTION | WS_MINIMIZEBOX;
+
+ memset( &wc, 0, sizeof( wc ) );
+
+ wc.style = 0;
+ wc.lpfnWndProc = (WNDPROC) ConWndProc;
+ wc.cbClsExtra = 0;
+ wc.cbWndExtra = 0;
+ wc.hInstance = g_wv.hInstance;
+ wc.hIcon = LoadIcon( g_wv.hInstance, MAKEINTRESOURCE(IDI_ICON1));
+ wc.hCursor = LoadCursor (NULL,IDC_ARROW);
+ wc.hbrBackground = (void *)COLOR_WINDOW;
+ wc.lpszMenuName = 0;
+ wc.lpszClassName = DEDCLASS;
+
+ if ( !RegisterClass (&wc) )
+ return;
+
+ rect.left = 0;
+ rect.right = 540;
+ rect.top = 0;
+ rect.bottom = 450;
+ AdjustWindowRect( &rect, DEDSTYLE, FALSE );
+
+ hDC = GetDC( GetDesktopWindow() );
+ swidth = GetDeviceCaps( hDC, HORZRES );
+ sheight = GetDeviceCaps( hDC, VERTRES );
+ ReleaseDC( GetDesktopWindow(), hDC );
+
+ s_wcd.windowWidth = rect.right - rect.left + 1;
+ s_wcd.windowHeight = rect.bottom - rect.top + 1;
+
+ s_wcd.hWnd = CreateWindowEx( 0,
+ DEDCLASS,
+ "Quake 3 Console",
+ DEDSTYLE,
+ ( swidth - 600 ) / 2, ( sheight - 450 ) / 2 , rect.right - rect.left + 1, rect.bottom - rect.top + 1,
+ NULL,
+ NULL,
+ g_wv.hInstance,
+ NULL );
+
+ if ( s_wcd.hWnd == NULL )
+ {
+ return;
+ }
+
+ //
+ // create fonts
+ //
+ hDC = GetDC( s_wcd.hWnd );
+ nHeight = -MulDiv( 8, GetDeviceCaps( hDC, LOGPIXELSY), 72);
+
+ s_wcd.hfBufferFont = CreateFont( nHeight,
+ 0,
+ 0,
+ 0,
+ FW_LIGHT,
+ 0,
+ 0,
+ 0,
+ DEFAULT_CHARSET,
+ OUT_DEFAULT_PRECIS,
+ CLIP_DEFAULT_PRECIS,
+ DEFAULT_QUALITY,
+ FF_MODERN | FIXED_PITCH,
+ "Courier New" );
+
+ ReleaseDC( s_wcd.hWnd, hDC );
+
+ //
+ // create the input line
+ //
+ s_wcd.hwndInputLine = CreateWindow( "edit", NULL, WS_CHILD | WS_VISIBLE | WS_BORDER |
+ ES_LEFT | ES_AUTOHSCROLL,
+ 6, 400, 528, 20,
+ s_wcd.hWnd,
+ ( HMENU ) INPUT_ID, // child window ID
+ g_wv.hInstance, NULL );
+
+ //
+ // create the buttons
+ //
+ s_wcd.hwndButtonCopy = CreateWindow( "button", NULL, BS_PUSHBUTTON | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
+ 5, 425, 72, 24,
+ s_wcd.hWnd,
+ ( HMENU ) COPY_ID, // child window ID
+ g_wv.hInstance, NULL );
+ SendMessage( s_wcd.hwndButtonCopy, WM_SETTEXT, 0, ( LPARAM ) "copy" );
+
+ s_wcd.hwndButtonClear = CreateWindow( "button", NULL, BS_PUSHBUTTON | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
+ 82, 425, 72, 24,
+ s_wcd.hWnd,
+ ( HMENU ) CLEAR_ID, // child window ID
+ g_wv.hInstance, NULL );
+ SendMessage( s_wcd.hwndButtonClear, WM_SETTEXT, 0, ( LPARAM ) "clear" );
+
+ s_wcd.hwndButtonQuit = CreateWindow( "button", NULL, BS_PUSHBUTTON | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
+ 462, 425, 72, 24,
+ s_wcd.hWnd,
+ ( HMENU ) QUIT_ID, // child window ID
+ g_wv.hInstance, NULL );
+ SendMessage( s_wcd.hwndButtonQuit, WM_SETTEXT, 0, ( LPARAM ) "quit" );
+
+
+ //
+ // create the scrollbuffer
+ //
+ s_wcd.hwndBuffer = CreateWindow( "edit", NULL, WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_BORDER |
+ ES_LEFT | ES_MULTILINE | ES_AUTOVSCROLL | ES_READONLY,
+ 6, 40, 526, 354,
+ s_wcd.hWnd,
+ ( HMENU ) EDIT_ID, // child window ID
+ g_wv.hInstance, NULL );
+ SendMessage( s_wcd.hwndBuffer, WM_SETFONT, ( WPARAM ) s_wcd.hfBufferFont, 0 );
+
+ s_wcd.SysInputLineWndProc = ( WNDPROC ) SetWindowLong( s_wcd.hwndInputLine, GWL_WNDPROC, ( long ) InputLineWndProc );
+ SendMessage( s_wcd.hwndInputLine, WM_SETFONT, ( WPARAM ) s_wcd.hfBufferFont, 0 );
+
+ ShowWindow( s_wcd.hWnd, SW_SHOWDEFAULT);
+ UpdateWindow( s_wcd.hWnd );
+ SetForegroundWindow( s_wcd.hWnd );
+ SetFocus( s_wcd.hwndInputLine );
+
+ s_wcd.visLevel = 1;
+}
+
+/*
+** Sys_DestroyConsole
+*/
+void Sys_DestroyConsole( void ) {
+ if ( s_wcd.hWnd ) {
+ ShowWindow( s_wcd.hWnd, SW_HIDE );
+ CloseWindow( s_wcd.hWnd );
+ DestroyWindow( s_wcd.hWnd );
+ s_wcd.hWnd = 0;
+ }
+}
+
+/*
+** Sys_ShowConsole
+*/
+void Sys_ShowConsole( int visLevel, qboolean quitOnClose )
+{
+ s_wcd.quitOnClose = quitOnClose;
+
+ if ( visLevel == s_wcd.visLevel )
+ {
+ return;
+ }
+
+ s_wcd.visLevel = visLevel;
+
+ if ( !s_wcd.hWnd )
+ return;
+
+ switch ( visLevel )
+ {
+ case 0:
+ ShowWindow( s_wcd.hWnd, SW_HIDE );
+ break;
+ case 1:
+ ShowWindow( s_wcd.hWnd, SW_SHOWNORMAL );
+ SendMessage( s_wcd.hwndBuffer, EM_LINESCROLL, 0, 0xffff );
+ break;
+ case 2:
+ ShowWindow( s_wcd.hWnd, SW_MINIMIZE );
+ break;
+ default:
+ Sys_Error( "Invalid visLevel %d sent to Sys_ShowConsole\n", visLevel );
+ break;
+ }
+}
+
+/*
+** Sys_ConsoleInput
+*/
+char *Sys_ConsoleInput( void )
+{
+ if ( s_wcd.consoleText[0] == 0 )
+ {
+ return NULL;
+ }
+
+ strcpy( s_wcd.returnedText, s_wcd.consoleText );
+ s_wcd.consoleText[0] = 0;
+
+ return s_wcd.returnedText;
+}
+
+/*
+** Conbuf_AppendText
+*/
+void Conbuf_AppendText( const char *pMsg )
+{
+#define CONSOLE_BUFFER_SIZE 16384
+
+ char buffer[CONSOLE_BUFFER_SIZE*2];
+ char *b = buffer;
+ const char *msg;
+ int bufLen;
+ int i = 0;
+ static unsigned long s_totalChars;
+
+ //
+ // if the message is REALLY long, use just the last portion of it
+ //
+ if ( strlen( pMsg ) > CONSOLE_BUFFER_SIZE - 1 )
+ {
+ msg = pMsg + strlen( pMsg ) - CONSOLE_BUFFER_SIZE + 1;
+ }
+ else
+ {
+ msg = pMsg;
+ }
+
+ //
+ // copy into an intermediate buffer
+ //
+ while ( msg[i] && ( ( b - buffer ) < sizeof( buffer ) - 1 ) )
+ {
+ if ( msg[i] == '\n' && msg[i+1] == '\r' )
+ {
+ b[0] = '\r';
+ b[1] = '\n';
+ b += 2;
+ i++;
+ }
+ else if ( msg[i] == '\r' )
+ {
+ b[0] = '\r';
+ b[1] = '\n';
+ b += 2;
+ }
+ else if ( msg[i] == '\n' )
+ {
+ b[0] = '\r';
+ b[1] = '\n';
+ b += 2;
+ }
+ else if ( Q_IsColorString( &msg[i] ) )
+ {
+ i++;
+ }
+ else
+ {
+ *b= msg[i];
+ b++;
+ }
+ i++;
+ }
+ *b = 0;
+ bufLen = b - buffer;
+
+ s_totalChars += bufLen;
+
+ //
+ // replace selection instead of appending if we're overflowing
+ //
+ if ( s_totalChars > 0x7fff )
+ {
+ SendMessage( s_wcd.hwndBuffer, EM_SETSEL, 0, -1 );
+ s_totalChars = bufLen;
+ }
+
+ //
+ // put this text into the windows console
+ //
+ SendMessage( s_wcd.hwndBuffer, EM_LINESCROLL, 0, 0xffff );
+ SendMessage( s_wcd.hwndBuffer, EM_SCROLLCARET, 0, 0 );
+ SendMessage( s_wcd.hwndBuffer, EM_REPLACESEL, 0, (LPARAM) buffer );
+}
+
+/*
+** Sys_SetErrorText
+*/
+void Sys_SetErrorText( const char *buf )
+{
+ Q_strncpyz( s_wcd.errorString, buf, sizeof( s_wcd.errorString ) );
+
+ if ( !s_wcd.hwndErrorBox )
+ {
+ s_wcd.hwndErrorBox = CreateWindow( "static", NULL, WS_CHILD | WS_VISIBLE | SS_SUNKEN,
+ 6, 5, 526, 30,
+ s_wcd.hWnd,
+ ( HMENU ) ERRORBOX_ID, // child window ID
+ g_wv.hInstance, NULL );
+ SendMessage( s_wcd.hwndErrorBox, WM_SETFONT, ( WPARAM ) s_wcd.hfBufferFont, 0 );
+ SetWindowText( s_wcd.hwndErrorBox, s_wcd.errorString );
+
+ DestroyWindow( s_wcd.hwndInputLine );
+ s_wcd.hwndInputLine = NULL;
+ }
+}
diff --git a/code/win32/win_wndproc.c b/code/win32/win_wndproc.c
new file mode 100755
index 0000000..fd537ca
--- /dev/null
+++ b/code/win32/win_wndproc.c
@@ -0,0 +1,456 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "../client/client.h"
+#include "win_local.h"
+
+WinVars_t g_wv;
+
+#ifndef WM_MOUSEWHEEL
+#define WM_MOUSEWHEEL (WM_MOUSELAST+1) // message that will be supported by the OS
+#endif
+
+static UINT MSH_MOUSEWHEEL;
+
+// Console variables that we need to access from this module
+cvar_t *vid_xpos; // X coordinate of window position
+cvar_t *vid_ypos; // Y coordinate of window position
+cvar_t *r_fullscreen;
+
+#define VID_NUM_MODES ( sizeof( vid_modes ) / sizeof( vid_modes[0] ) )
+
+LONG WINAPI MainWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );
+
+static qboolean s_alttab_disabled;
+
+static void WIN_DisableAltTab( void )
+{
+ if ( s_alttab_disabled )
+ return;
+
+ if ( !Q_stricmp( Cvar_VariableString( "arch" ), "winnt" ) )
+ {
+ RegisterHotKey( 0, 0, MOD_ALT, VK_TAB );
+ }
+ else
+ {
+ BOOL old;
+
+ SystemParametersInfo( SPI_SCREENSAVERRUNNING, 1, &old, 0 );
+ }
+ s_alttab_disabled = qtrue;
+}
+
+static void WIN_EnableAltTab( void )
+{
+ if ( s_alttab_disabled )
+ {
+ if ( !Q_stricmp( Cvar_VariableString( "arch" ), "winnt" ) )
+ {
+ UnregisterHotKey( 0, 0 );
+ }
+ else
+ {
+ BOOL old;
+
+ SystemParametersInfo( SPI_SCREENSAVERRUNNING, 0, &old, 0 );
+ }
+
+ s_alttab_disabled = qfalse;
+ }
+}
+
+/*
+==================
+VID_AppActivate
+==================
+*/
+static void VID_AppActivate(BOOL fActive, BOOL minimize)
+{
+ g_wv.isMinimized = minimize;
+
+ Com_DPrintf("VID_AppActivate: %i\n", fActive );
+
+ Key_ClearStates(); // FIXME!!!
+
+ // we don't want to act like we're active if we're minimized
+ if (fActive && !g_wv.isMinimized )
+ {
+ g_wv.activeApp = qtrue;
+ }
+ else
+ {
+ g_wv.activeApp = qfalse;
+ }
+
+ // minimize/restore mouse-capture on demand
+ if (!g_wv.activeApp )
+ {
+ IN_Activate (qfalse);
+ }
+ else
+ {
+ IN_Activate (qtrue);
+ }
+}
+
+//==========================================================================
+
+static byte s_scantokey[128] =
+ {
+// 0 1 2 3 4 5 6 7
+// 8 9 A B C D E F
+ 0 , 27, '1', '2', '3', '4', '5', '6',
+ '7', '8', '9', '0', '-', '=', K_BACKSPACE, 9, // 0
+ 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i',
+ 'o', 'p', '[', ']', 13 , K_CTRL,'a', 's', // 1
+ 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';',
+ '\'' , '`', K_SHIFT,'\\', 'z', 'x', 'c', 'v', // 2
+ 'b', 'n', 'm', ',', '.', '/', K_SHIFT,'*',
+ K_ALT,' ', K_CAPSLOCK , K_F1, K_F2, K_F3, K_F4, K_F5, // 3
+ K_F6, K_F7, K_F8, K_F9, K_F10, K_PAUSE, 0 , K_HOME,
+ K_UPARROW,K_PGUP,K_KP_MINUS,K_LEFTARROW,K_KP_5,K_RIGHTARROW, K_KP_PLUS,K_END, //4
+ K_DOWNARROW,K_PGDN,K_INS,K_DEL,0,0, 0, K_F11,
+ K_F12,0 , 0 , 0 , 0 , 0 , 0 , 0, // 5
+ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0,
+ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0, // 6
+ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0,
+ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 // 7
+};
+
+/*
+=======
+MapKey
+
+Map from windows to quake keynums
+=======
+*/
+static int MapKey (int key)
+{
+ int result;
+ int modified;
+ qboolean is_extended;
+
+// Com_Printf( "0x%x\n", key);
+
+ modified = ( key >> 16 ) & 255;
+
+ if ( modified > 127 )
+ return 0;
+
+ if ( key & ( 1 << 24 ) )
+ {
+ is_extended = qtrue;
+ }
+ else
+ {
+ is_extended = qfalse;
+ }
+
+ result = s_scantokey[modified];
+
+ if ( !is_extended )
+ {
+ switch ( result )
+ {
+ case K_HOME:
+ return K_KP_HOME;
+ case K_UPARROW:
+ return K_KP_UPARROW;
+ case K_PGUP:
+ return K_KP_PGUP;
+ case K_LEFTARROW:
+ return K_KP_LEFTARROW;
+ case K_RIGHTARROW:
+ return K_KP_RIGHTARROW;
+ case K_END:
+ return K_KP_END;
+ case K_DOWNARROW:
+ return K_KP_DOWNARROW;
+ case K_PGDN:
+ return K_KP_PGDN;
+ case K_INS:
+ return K_KP_INS;
+ case K_DEL:
+ return K_KP_DEL;
+ default:
+ return result;
+ }
+ }
+ else
+ {
+ switch ( result )
+ {
+ case K_PAUSE:
+ return K_KP_NUMLOCK;
+ case 0x0D:
+ return K_KP_ENTER;
+ case 0x2F:
+ return K_KP_SLASH;
+ case 0xAF:
+ return K_KP_PLUS;
+ }
+ return result;
+ }
+}
+
+
+/*
+====================
+MainWndProc
+
+main window procedure
+====================
+*/
+extern cvar_t *in_mouse;
+extern cvar_t *in_logitechbug;
+LONG WINAPI MainWndProc (
+ HWND hWnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam)
+{
+ static qboolean flip = qtrue;
+ int zDelta, i;
+
+ // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/mouseinput/aboutmouseinput.asp
+ // Windows 95, Windows NT 3.51 - uses MSH_MOUSEWHEEL
+ // only relevant for non-DI input
+ //
+ // NOTE: not sure how reliable this is anymore, might trigger double wheel events
+ if (in_mouse->integer != 1)
+ {
+ if ( uMsg == MSH_MOUSEWHEEL )
+ {
+ if ( ( ( int ) wParam ) > 0 )
+ {
+ Sys_QueEvent( g_wv.sysMsgTime, SE_KEY, K_MWHEELUP, qtrue, 0, NULL );
+ Sys_QueEvent( g_wv.sysMsgTime, SE_KEY, K_MWHEELUP, qfalse, 0, NULL );
+ }
+ else
+ {
+ Sys_QueEvent( g_wv.sysMsgTime, SE_KEY, K_MWHEELDOWN, qtrue, 0, NULL );
+ Sys_QueEvent( g_wv.sysMsgTime, SE_KEY, K_MWHEELDOWN, qfalse, 0, NULL );
+ }
+ return DefWindowProc (hWnd, uMsg, wParam, lParam);
+ }
+ }
+
+ switch (uMsg)
+ {
+ case WM_MOUSEWHEEL:
+ // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/mouseinput/aboutmouseinput.asp
+ // Windows 98/Me, Windows NT 4.0 and later - uses WM_MOUSEWHEEL
+ // only relevant for non-DI input and when console is toggled in window mode
+ // if console is toggled in window mode (KEYCATCH_CONSOLE) then mouse is released and DI doesn't see any mouse wheel
+ if (in_mouse->integer != 1 || (!r_fullscreen->integer && (cls.keyCatchers & KEYCATCH_CONSOLE)))
+ {
+ // 120 increments, might be 240 and multiples if wheel goes too fast
+ // NOTE Logitech: logitech drivers are screwed and send the message twice?
+ // could add a cvar to interpret the message as successive press/release events
+ zDelta = ( short ) HIWORD( wParam ) / 120;
+ if ( zDelta > 0 )
+ {
+ for(i=0; i<zDelta; i++)
+ {
+ if (!in_logitechbug->integer)
+ {
+ Sys_QueEvent( g_wv.sysMsgTime, SE_KEY, K_MWHEELUP, qtrue, 0, NULL );
+ Sys_QueEvent( g_wv.sysMsgTime, SE_KEY, K_MWHEELUP, qfalse, 0, NULL );
+ }
+ else
+ {
+ Sys_QueEvent( g_wv.sysMsgTime, SE_KEY, K_MWHEELUP, flip, 0, NULL );
+ flip = !flip;
+ }
+ }
+ }
+ else
+ {
+ for(i=0; i<-zDelta; i++)
+ {
+ if (!in_logitechbug->integer)
+ {
+ Sys_QueEvent( g_wv.sysMsgTime, SE_KEY, K_MWHEELDOWN, qtrue, 0, NULL );
+ Sys_QueEvent( g_wv.sysMsgTime, SE_KEY, K_MWHEELDOWN, qfalse, 0, NULL );
+ }
+ else
+ {
+ Sys_QueEvent( g_wv.sysMsgTime, SE_KEY, K_MWHEELDOWN, flip, 0, NULL );
+ flip = !flip;
+ }
+ }
+ }
+ // when an application processes the WM_MOUSEWHEEL message, it must return zero
+ return 0;
+ }
+ break;
+
+ case WM_CREATE:
+
+ g_wv.hWnd = hWnd;
+
+ vid_xpos = Cvar_Get ("vid_xpos", "3", CVAR_ARCHIVE);
+ vid_ypos = Cvar_Get ("vid_ypos", "22", CVAR_ARCHIVE);
+ r_fullscreen = Cvar_Get ("r_fullscreen", "1", CVAR_ARCHIVE | CVAR_LATCH );
+
+ MSH_MOUSEWHEEL = RegisterWindowMessage("MSWHEEL_ROLLMSG");
+ if ( r_fullscreen->integer )
+ {
+ WIN_DisableAltTab();
+ }
+ else
+ {
+ WIN_EnableAltTab();
+ }
+
+ break;
+#if 0
+ case WM_DISPLAYCHANGE:
+ Com_DPrintf( "WM_DISPLAYCHANGE\n" );
+ // we need to force a vid_restart if the user has changed
+ // their desktop resolution while the game is running,
+ // but don't do anything if the message is a result of
+ // our own calling of ChangeDisplaySettings
+ if ( com_insideVidInit ) {
+ break; // we did this on purpose
+ }
+ // something else forced a mode change, so restart all our gl stuff
+ Cbuf_AddText( "vid_restart\n" );
+ break;
+#endif
+ case WM_DESTROY:
+ // let sound and input know about this?
+ g_wv.hWnd = NULL;
+ if ( r_fullscreen->integer )
+ {
+ WIN_EnableAltTab();
+ }
+ break;
+
+ case WM_CLOSE:
+ Cbuf_ExecuteText( EXEC_APPEND, "quit" );
+ break;
+
+ case WM_ACTIVATE:
+ {
+ int fActive, fMinimized;
+
+ fActive = LOWORD(wParam);
+ fMinimized = (BOOL) HIWORD(wParam);
+
+ VID_AppActivate( fActive != WA_INACTIVE, fMinimized);
+ SNDDMA_Activate();
+ }
+ break;
+
+ case WM_MOVE:
+ {
+ int xPos, yPos;
+ RECT r;
+ int style;
+
+ if (!r_fullscreen->integer )
+ {
+ xPos = (short) LOWORD(lParam); // horizontal position
+ yPos = (short) HIWORD(lParam); // vertical position
+
+ r.left = 0;
+ r.top = 0;
+ r.right = 1;
+ r.bottom = 1;
+
+ style = GetWindowLong( hWnd, GWL_STYLE );
+ AdjustWindowRect( &r, style, FALSE );
+
+ Cvar_SetValue( "vid_xpos", xPos + r.left);
+ Cvar_SetValue( "vid_ypos", yPos + r.top);
+ vid_xpos->modified = qfalse;
+ vid_ypos->modified = qfalse;
+ if ( g_wv.activeApp )
+ {
+ IN_Activate (qtrue);
+ }
+ }
+ }
+ break;
+
+// this is complicated because Win32 seems to pack multiple mouse events into
+// one update sometimes, so we always check all states and look for events
+ case WM_LBUTTONDOWN:
+ case WM_LBUTTONUP:
+ case WM_RBUTTONDOWN:
+ case WM_RBUTTONUP:
+ case WM_MBUTTONDOWN:
+ case WM_MBUTTONUP:
+ case WM_MOUSEMOVE:
+ {
+ int temp;
+
+ temp = 0;
+
+ if (wParam & MK_LBUTTON)
+ temp |= 1;
+
+ if (wParam & MK_RBUTTON)
+ temp |= 2;
+
+ if (wParam & MK_MBUTTON)
+ temp |= 4;
+
+ IN_MouseEvent (temp);
+ }
+ break;
+
+ case WM_SYSCOMMAND:
+ if ( wParam == SC_SCREENSAVE )
+ return 0;
+ break;
+
+ case WM_SYSKEYDOWN:
+ if ( wParam == 13 )
+ {
+ if ( r_fullscreen )
+ {
+ Cvar_SetValue( "r_fullscreen", !r_fullscreen->integer );
+ Cbuf_AddText( "vid_restart\n" );
+ }
+ return 0;
+ }
+ // fall through
+ case WM_KEYDOWN:
+ Sys_QueEvent( g_wv.sysMsgTime, SE_KEY, MapKey( lParam ), qtrue, 0, NULL );
+ break;
+
+ case WM_SYSKEYUP:
+ case WM_KEYUP:
+ Sys_QueEvent( g_wv.sysMsgTime, SE_KEY, MapKey( lParam ), qfalse, 0, NULL );
+ break;
+
+ case WM_CHAR:
+ Sys_QueEvent( g_wv.sysMsgTime, SE_CHAR, wParam, 0, 0, NULL );
+ break;
+ }
+
+ return DefWindowProc( hWnd, uMsg, wParam, lParam );
+}
+
diff --git a/code/win32/winquake.rc b/code/win32/winquake.rc
new file mode 100755
index 0000000..c50d6f2
--- /dev/null
+++ b/code/win32/winquake.rc
@@ -0,0 +1,71 @@
+//Microsoft Developer Studio generated resource script.
+//
+#include "resource.h"
+
+#define APSTUDIO_READONLY_SYMBOLS
+/////////////////////////////////////////////////////////////////////////////
+//
+// Generated from the TEXTINCLUDE 2 resource.
+//
+#include "winres.h"
+
+/////////////////////////////////////////////////////////////////////////////
+#undef APSTUDIO_READONLY_SYMBOLS
+
+/////////////////////////////////////////////////////////////////////////////
+// English (U.S.) resources
+
+#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
+#ifdef _WIN32
+LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
+#pragma code_page(1252)
+#endif //_WIN32
+
+#ifdef APSTUDIO_INVOKED
+/////////////////////////////////////////////////////////////////////////////
+//
+// TEXTINCLUDE
+//
+
+1 TEXTINCLUDE DISCARDABLE
+BEGIN
+ "resource.h\0"
+END
+
+2 TEXTINCLUDE DISCARDABLE
+BEGIN
+ "#include ""winres.h""\r\n"
+ "\0"
+END
+
+3 TEXTINCLUDE DISCARDABLE
+BEGIN
+ "\0"
+END
+
+#endif // APSTUDIO_INVOKED
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Icon
+//
+
+// Icon with lowest ID value placed first to ensure application icon
+// remains consistent on all systems.
+IDI_ICON1 ICON DISCARDABLE "qe3.ico"
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// String Table
+//
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ IDS_STRING1 "Quake3"
+END
+
+#endif // English (U.S.) resources
+/////////////////////////////////////////////////////////////////////////////
+
+
diff --git a/common/aselib.c b/common/aselib.c
new file mode 100755
index 0000000..5706c9e
--- /dev/null
+++ b/common/aselib.c
@@ -0,0 +1,933 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "aselib.h"
+
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#define MAX_ASE_MATERIALS 32
+#define MAX_ASE_OBJECTS 64
+#define MAX_ASE_ANIMATIONS 32
+#define MAX_ASE_ANIMATION_FRAMES 512
+
+#define VERBOSE( x ) { if ( ase.verbose ) { printf x ; } }
+
+typedef struct
+{
+ float x, y, z;
+ float nx, ny, nz;
+ float s, t;
+} aseVertex_t;
+
+typedef struct
+{
+ float s, t;
+} aseTVertex_t;
+
+typedef int aseFace_t[3];
+
+typedef struct
+{
+ int numFaces;
+ int numVertexes;
+ int numTVertexes;
+
+ int timeValue;
+
+ aseVertex_t *vertexes;
+ aseTVertex_t *tvertexes;
+ aseFace_t *faces, *tfaces;
+
+ int currentFace, currentVertex;
+} aseMesh_t;
+
+typedef struct
+{
+ int numFrames;
+ aseMesh_t frames[MAX_ASE_ANIMATION_FRAMES];
+
+ int currentFrame;
+} aseMeshAnimation_t;
+
+typedef struct
+{
+ char name[128];
+} aseMaterial_t;
+
+/*
+** contains the animate sequence of a single surface
+** using a single material
+*/
+typedef struct
+{
+ char name[128];
+
+ int materialRef;
+ int numAnimations;
+
+ aseMeshAnimation_t anim;
+
+} aseGeomObject_t;
+
+typedef struct
+{
+ int numMaterials;
+ aseMaterial_t materials[MAX_ASE_MATERIALS];
+ aseGeomObject_t objects[MAX_ASE_OBJECTS];
+
+ char *buffer;
+ char *curpos;
+ int len;
+
+ int currentObject;
+ qboolean verbose;
+ qboolean grabAnims;
+
+} ase_t;
+
+static char s_token[1024];
+static ase_t ase;
+
+static void ASE_Process( void );
+static void ASE_FreeGeomObject( int ndx );
+
+/*
+** ASE_Load
+*/
+void ASE_Load( const char *filename, qboolean verbose, qboolean grabAnims )
+{
+ FILE *fp = fopen( filename, "rb" );
+
+ if ( !fp )
+ Error( "File not found '%s'", filename );
+
+ memset( &ase, 0, sizeof( ase ) );
+
+ ase.verbose = verbose;
+ ase.grabAnims = grabAnims;
+ ase.len = Q_filelength( fp );
+
+ ase.curpos = ase.buffer = malloc( ase.len );
+
+ printf( "Processing '%s'\n", filename );
+
+ if ( fread( ase.buffer, ase.len, 1, fp ) != 1 )
+ {
+ fclose( fp );
+ Error( "fread() != -1 for '%s'", filename );
+ }
+
+ fclose( fp );
+
+ ASE_Process();
+}
+
+/*
+** ASE_Free
+*/
+void ASE_Free( void )
+{
+ int i;
+
+ for ( i = 0; i < ase.currentObject; i++ )
+ {
+ ASE_FreeGeomObject( i );
+ }
+}
+
+/*
+** ASE_GetNumSurfaces
+*/
+int ASE_GetNumSurfaces( void )
+{
+ return ase.currentObject;
+}
+
+/*
+** ASE_GetSurfaceName
+*/
+const char *ASE_GetSurfaceName( int which )
+{
+ aseGeomObject_t *pObject = &ase.objects[which];
+
+ if ( !pObject->anim.numFrames )
+ return 0;
+
+ return pObject->name;
+}
+
+/*
+** ASE_GetSurfaceAnimation
+**
+** Returns an animation (sequence of polysets)
+*/
+polyset_t *ASE_GetSurfaceAnimation( int which, int *pNumFrames, int skipFrameStart, int skipFrameEnd, int maxFrames )
+{
+ aseGeomObject_t *pObject = &ase.objects[which];
+ polyset_t *psets;
+ int numFramesInAnimation;
+ int numFramesToKeep;
+ int i, f;
+
+ if ( !pObject->anim.numFrames )
+ return 0;
+
+ if ( pObject->anim.numFrames > maxFrames && maxFrames != -1 )
+ {
+ numFramesInAnimation = maxFrames;
+ }
+ else
+ {
+ numFramesInAnimation = pObject->anim.numFrames;
+ if ( maxFrames != -1 )
+ printf( "WARNING: ASE_GetSurfaceAnimation maxFrames > numFramesInAnimation\n" );
+ }
+
+ if ( skipFrameEnd != -1 )
+ numFramesToKeep = numFramesInAnimation - ( skipFrameEnd - skipFrameStart + 1 );
+ else
+ numFramesToKeep = numFramesInAnimation;
+
+ *pNumFrames = numFramesToKeep;
+
+ psets = calloc( sizeof( polyset_t ) * numFramesToKeep, 1 );
+
+ for ( f = 0, i = 0; i < numFramesInAnimation; i++ )
+ {
+ int t;
+ aseMesh_t *pMesh = &pObject->anim.frames[i];
+
+ if ( skipFrameStart != -1 )
+ {
+ if ( i >= skipFrameStart && i <= skipFrameEnd )
+ continue;
+ }
+
+ strcpy( psets[f].name, pObject->name );
+ strcpy( psets[f].materialname, ase.materials[pObject->materialRef].name );
+
+ psets[f].triangles = calloc( sizeof( triangle_t ) * pObject->anim.frames[i].numFaces, 1 );
+ psets[f].numtriangles = pObject->anim.frames[i].numFaces;
+
+ for ( t = 0; t < pObject->anim.frames[i].numFaces; t++ )
+ {
+ int k;
+
+ for ( k = 0; k < 3; k++ )
+ {
+ psets[f].triangles[t].verts[k][0] = pMesh->vertexes[pMesh->faces[t][k]].x;
+ psets[f].triangles[t].verts[k][1] = pMesh->vertexes[pMesh->faces[t][k]].y;
+ psets[f].triangles[t].verts[k][2] = pMesh->vertexes[pMesh->faces[t][k]].z;
+
+ if ( pMesh->tvertexes && pMesh->tfaces )
+ {
+ psets[f].triangles[t].texcoords[k][0] = pMesh->tvertexes[pMesh->tfaces[t][k]].s;
+ psets[f].triangles[t].texcoords[k][1] = pMesh->tvertexes[pMesh->tfaces[t][k]].t;
+ }
+
+ }
+ }
+
+ f++;
+ }
+
+ return psets;
+}
+
+static void ASE_FreeGeomObject( int ndx )
+{
+ aseGeomObject_t *pObject;
+ int i;
+
+ pObject = &ase.objects[ndx];
+
+ for ( i = 0; i < pObject->anim.numFrames; i++ )
+ {
+ if ( pObject->anim.frames[i].vertexes )
+ {
+ free( pObject->anim.frames[i].vertexes );
+ }
+ if ( pObject->anim.frames[i].tvertexes )
+ {
+ free( pObject->anim.frames[i].tvertexes );
+ }
+ if ( pObject->anim.frames[i].faces )
+ {
+ free( pObject->anim.frames[i].faces );
+ }
+ if ( pObject->anim.frames[i].tfaces )
+ {
+ free( pObject->anim.frames[i].tfaces );
+ }
+ }
+
+ memset( pObject, 0, sizeof( *pObject ) );
+}
+
+static aseMesh_t *ASE_GetCurrentMesh( void )
+{
+ aseGeomObject_t *pObject;
+
+ if ( ase.currentObject >= MAX_ASE_OBJECTS )
+ {
+ Error( "Too many GEOMOBJECTs" );
+ return 0; // never called
+ }
+
+ pObject = &ase.objects[ase.currentObject];
+
+ if ( pObject->anim.currentFrame >= MAX_ASE_ANIMATION_FRAMES )
+ {
+ Error( "Too many MESHes" );
+ return 0;
+ }
+
+ return &pObject->anim.frames[pObject->anim.currentFrame];
+}
+
+static int CharIsTokenDelimiter( int ch )
+{
+ if ( ch <= 32 )
+ return 1;
+ return 0;
+}
+
+static int ASE_GetToken( qboolean restOfLine )
+{
+ int i = 0;
+
+ if ( ase.buffer == 0 )
+ return 0;
+
+ if ( ( ase.curpos - ase.buffer ) == ase.len )
+ return 0;
+
+ // skip over crap
+ while ( ( ( ase.curpos - ase.buffer ) < ase.len ) &&
+ ( *ase.curpos <= 32 ) )
+ {
+ ase.curpos++;
+ }
+
+ while ( ( ase.curpos - ase.buffer ) < ase.len )
+ {
+ s_token[i] = *ase.curpos;
+
+ ase.curpos++;
+ i++;
+
+ if ( ( CharIsTokenDelimiter( s_token[i-1] ) && !restOfLine ) ||
+ ( ( s_token[i-1] == '\n' ) || ( s_token[i-1] == '\r' ) ) )
+ {
+ s_token[i-1] = 0;
+ break;
+ }
+ }
+
+ s_token[i] = 0;
+
+ return 1;
+}
+
+static void ASE_ParseBracedBlock( void (*parser)( const char *token ) )
+{
+ int indent = 0;
+
+ while ( ASE_GetToken( qfalse ) )
+ {
+ if ( !strcmp( s_token, "{" ) )
+ {
+ indent++;
+ }
+ else if ( !strcmp( s_token, "}" ) )
+ {
+ --indent;
+ if ( indent == 0 )
+ break;
+ else if ( indent < 0 )
+ Error( "Unexpected '}'" );
+ }
+ else
+ {
+ if ( parser )
+ parser( s_token );
+ }
+ }
+}
+
+static void ASE_SkipEnclosingBraces( void )
+{
+ int indent = 0;
+
+ while ( ASE_GetToken( qfalse ) )
+ {
+ if ( !strcmp( s_token, "{" ) )
+ {
+ indent++;
+ }
+ else if ( !strcmp( s_token, "}" ) )
+ {
+ indent--;
+ if ( indent == 0 )
+ break;
+ else if ( indent < 0 )
+ Error( "Unexpected '}'" );
+ }
+ }
+}
+
+static void ASE_SkipRestOfLine( void )
+{
+ ASE_GetToken( qtrue );
+}
+
+static void ASE_KeyMAP_DIFFUSE( const char *token )
+{
+ char buffer[1024], buff1[1024], buff2[1024];
+ char *buf1, *buf2;
+ int i = 0, count;
+
+ if ( !strcmp( token, "*BITMAP" ) )
+ {
+ ASE_GetToken( qfalse );
+
+ strcpy( buffer, s_token + 1 );
+ if ( strchr( buffer, '"' ) )
+ *strchr( buffer, '"' ) = 0;
+
+ while ( buffer[i] )
+ {
+ if ( buffer[i] == '\\' )
+ buffer[i] = '/';
+ i++;
+ }
+
+ buf1 = buffer;
+ buf2 = gamedir;
+ // need to compare win32 volumes to potential unix junk
+ //
+ if ( (gamedir[1] == ':' && (buffer[0] == '/' && buffer[1] == '/')) ||
+ (buffer[1] == ':' && (gamedir[0] == '/' && gamedir[1] == '/')) ) {
+ if (buffer[1] == ':') {
+ buf1 = buffer + 2;
+ buf2 = gamedir + 2;
+ } else {
+ buf1 = gamedir + 2;
+ buf2 = buffer +2;
+ }
+ count = 0;
+ while (*buf2 && count < 2) {
+ if (*buf2 == '/') {
+ count++;
+ }
+ buf2++;
+ }
+ }
+ strcpy(buff1, buf1);
+ strlwr(buff1);
+ strcpy(buff2, buf2);
+ strlwr(buff2);
+ if ( strstr( buff2, buff1 + 2 ) )
+ {
+ strcpy( ase.materials[ase.numMaterials].name, strstr( buff2, buff1 + 2 ) + strlen( buff1 ) - 2 );
+ }
+ else
+ {
+ sprintf( ase.materials[ase.numMaterials].name, "(not converted: '%s')", buffer );
+ printf( "WARNING: illegal material name '%s'\n", buffer );
+ }
+ }
+ else
+ {
+ }
+}
+
+static void ASE_KeyMATERIAL( const char *token )
+{
+ if ( !strcmp( token, "*MAP_DIFFUSE" ) )
+ {
+ ASE_ParseBracedBlock( ASE_KeyMAP_DIFFUSE );
+ }
+ else
+ {
+ }
+}
+
+static void ASE_KeyMATERIAL_LIST( const char *token )
+{
+ if ( !strcmp( token, "*MATERIAL_COUNT" ) )
+ {
+ ASE_GetToken( qfalse );
+ VERBOSE( ( "..num materials: %s\n", s_token ) );
+ if ( atoi( s_token ) > MAX_ASE_MATERIALS )
+ {
+ Error( "Too many materials!" );
+ }
+ ase.numMaterials = 0;
+ }
+ else if ( !strcmp( token, "*MATERIAL" ) )
+ {
+ VERBOSE( ( "..material %d ", ase.numMaterials ) );
+ ASE_ParseBracedBlock( ASE_KeyMATERIAL );
+ ase.numMaterials++;
+ }
+}
+
+static void ASE_KeyMESH_VERTEX_LIST( const char *token )
+{
+ aseMesh_t *pMesh = ASE_GetCurrentMesh();
+
+ if ( !strcmp( token, "*MESH_VERTEX" ) )
+ {
+ ASE_GetToken( qfalse ); // skip number
+
+ ASE_GetToken( qfalse );
+ pMesh->vertexes[pMesh->currentVertex].y = atof( s_token );
+
+ ASE_GetToken( qfalse );
+ pMesh->vertexes[pMesh->currentVertex].x = -atof( s_token );
+
+ ASE_GetToken( qfalse );
+ pMesh->vertexes[pMesh->currentVertex].z = atof( s_token );
+
+ pMesh->currentVertex++;
+
+ if ( pMesh->currentVertex > pMesh->numVertexes )
+ {
+ Error( "pMesh->currentVertex >= pMesh->numVertexes" );
+ }
+ }
+ else
+ {
+ Error( "Unknown token '%s' while parsing MESH_VERTEX_LIST", token );
+ }
+}
+
+static void ASE_KeyMESH_FACE_LIST( const char *token )
+{
+ aseMesh_t *pMesh = ASE_GetCurrentMesh();
+
+ if ( !strcmp( token, "*MESH_FACE" ) )
+ {
+ ASE_GetToken( qfalse ); // skip face number
+
+ ASE_GetToken( qfalse ); // skip label
+ ASE_GetToken( qfalse ); // first vertex
+ pMesh->faces[pMesh->currentFace][0] = atoi( s_token );
+
+ ASE_GetToken( qfalse ); // skip label
+ ASE_GetToken( qfalse ); // second vertex
+ pMesh->faces[pMesh->currentFace][2] = atoi( s_token );
+
+ ASE_GetToken( qfalse ); // skip label
+ ASE_GetToken( qfalse ); // third vertex
+ pMesh->faces[pMesh->currentFace][1] = atoi( s_token );
+
+ ASE_GetToken( qtrue );
+
+/*
+ if ( ( p = strstr( s_token, "*MESH_MTLID" ) ) != 0 )
+ {
+ p += strlen( "*MESH_MTLID" ) + 1;
+ mtlID = atoi( p );
+ }
+ else
+ {
+ Error( "No *MESH_MTLID found for face!" );
+ }
+*/
+
+ pMesh->currentFace++;
+ }
+ else
+ {
+ Error( "Unknown token '%s' while parsing MESH_FACE_LIST", token );
+ }
+}
+
+static void ASE_KeyTFACE_LIST( const char *token )
+{
+ aseMesh_t *pMesh = ASE_GetCurrentMesh();
+
+ if ( !strcmp( token, "*MESH_TFACE" ) )
+ {
+ int a, b, c;
+
+ ASE_GetToken( qfalse );
+
+ ASE_GetToken( qfalse );
+ a = atoi( s_token );
+ ASE_GetToken( qfalse );
+ c = atoi( s_token );
+ ASE_GetToken( qfalse );
+ b = atoi( s_token );
+
+ pMesh->tfaces[pMesh->currentFace][0] = a;
+ pMesh->tfaces[pMesh->currentFace][1] = b;
+ pMesh->tfaces[pMesh->currentFace][2] = c;
+
+ pMesh->currentFace++;
+ }
+ else
+ {
+ Error( "Unknown token '%s' in MESH_TFACE", token );
+ }
+}
+
+static void ASE_KeyMESH_TVERTLIST( const char *token )
+{
+ aseMesh_t *pMesh = ASE_GetCurrentMesh();
+
+ if ( !strcmp( token, "*MESH_TVERT" ) )
+ {
+ char u[80], v[80], w[80];
+
+ ASE_GetToken( qfalse );
+
+ ASE_GetToken( qfalse );
+ strcpy( u, s_token );
+
+ ASE_GetToken( qfalse );
+ strcpy( v, s_token );
+
+ ASE_GetToken( qfalse );
+ strcpy( w, s_token );
+
+ pMesh->tvertexes[pMesh->currentVertex].s = atof( u );
+ pMesh->tvertexes[pMesh->currentVertex].t = 1.0f - atof( v );
+
+ pMesh->currentVertex++;
+
+ if ( pMesh->currentVertex > pMesh->numTVertexes )
+ {
+ Error( "pMesh->currentVertex > pMesh->numTVertexes" );
+ }
+ }
+ else
+ {
+ Error( "Unknown token '%s' while parsing MESH_TVERTLIST" );
+ }
+}
+
+static void ASE_KeyMESH( const char *token )
+{
+ aseMesh_t *pMesh = ASE_GetCurrentMesh();
+
+ if ( !strcmp( token, "*TIMEVALUE" ) )
+ {
+ ASE_GetToken( qfalse );
+
+ pMesh->timeValue = atoi( s_token );
+ VERBOSE( ( ".....timevalue: %d\n", pMesh->timeValue ) );
+ }
+ else if ( !strcmp( token, "*MESH_NUMVERTEX" ) )
+ {
+ ASE_GetToken( qfalse );
+
+ pMesh->numVertexes = atoi( s_token );
+ VERBOSE( ( ".....TIMEVALUE: %d\n", pMesh->timeValue ) );
+ VERBOSE( ( ".....num vertexes: %d\n", pMesh->numVertexes ) );
+ }
+ else if ( !strcmp( token, "*MESH_NUMFACES" ) )
+ {
+ ASE_GetToken( qfalse );
+
+ pMesh->numFaces = atoi( s_token );
+ VERBOSE( ( ".....num faces: %d\n", pMesh->numFaces ) );
+ }
+ else if ( !strcmp( token, "*MESH_NUMTVFACES" ) )
+ {
+ ASE_GetToken( qfalse );
+
+ if ( atoi( s_token ) != pMesh->numFaces )
+ {
+ Error( "MESH_NUMTVFACES != MESH_NUMFACES" );
+ }
+ }
+ else if ( !strcmp( token, "*MESH_NUMTVERTEX" ) )
+ {
+ ASE_GetToken( qfalse );
+
+ pMesh->numTVertexes = atoi( s_token );
+ VERBOSE( ( ".....num tvertexes: %d\n", pMesh->numTVertexes ) );
+ }
+ else if ( !strcmp( token, "*MESH_VERTEX_LIST" ) )
+ {
+ pMesh->vertexes = calloc( sizeof( aseVertex_t ) * pMesh->numVertexes, 1 );
+ pMesh->currentVertex = 0;
+ VERBOSE( ( ".....parsing MESH_VERTEX_LIST\n" ) );
+ ASE_ParseBracedBlock( ASE_KeyMESH_VERTEX_LIST );
+ }
+ else if ( !strcmp( token, "*MESH_TVERTLIST" ) )
+ {
+ pMesh->currentVertex = 0;
+ pMesh->tvertexes = calloc( sizeof( aseTVertex_t ) * pMesh->numTVertexes, 1 );
+ VERBOSE( ( ".....parsing MESH_TVERTLIST\n" ) );
+ ASE_ParseBracedBlock( ASE_KeyMESH_TVERTLIST );
+ }
+ else if ( !strcmp( token, "*MESH_FACE_LIST" ) )
+ {
+ pMesh->faces = calloc( sizeof( aseFace_t ) * pMesh->numFaces, 1 );
+ pMesh->currentFace = 0;
+ VERBOSE( ( ".....parsing MESH_FACE_LIST\n" ) );
+ ASE_ParseBracedBlock( ASE_KeyMESH_FACE_LIST );
+ }
+ else if ( !strcmp( token, "*MESH_TFACELIST" ) )
+ {
+ pMesh->tfaces = calloc( sizeof( aseFace_t ) * pMesh->numFaces, 1 );
+ pMesh->currentFace = 0;
+ VERBOSE( ( ".....parsing MESH_TFACE_LIST\n" ) );
+ ASE_ParseBracedBlock( ASE_KeyTFACE_LIST );
+ }
+ else if ( !strcmp( token, "*MESH_NORMALS" ) )
+ {
+ ASE_ParseBracedBlock( 0 );
+ }
+}
+
+static void ASE_KeyMESH_ANIMATION( const char *token )
+{
+ aseMesh_t *pMesh = ASE_GetCurrentMesh();
+
+ // loads a single animation frame
+ if ( !strcmp( token, "*MESH" ) )
+ {
+ VERBOSE( ( "...found MESH\n" ) );
+ assert( pMesh->faces == 0 );
+ assert( pMesh->vertexes == 0 );
+ assert( pMesh->tvertexes == 0 );
+ memset( pMesh, 0, sizeof( *pMesh ) );
+
+ ASE_ParseBracedBlock( ASE_KeyMESH );
+
+ if ( ++ase.objects[ase.currentObject].anim.currentFrame == MAX_ASE_ANIMATION_FRAMES )
+ {
+ Error( "Too many animation frames" );
+ }
+ }
+ else
+ {
+ Error( "Unknown token '%s' while parsing MESH_ANIMATION", token );
+ }
+}
+
+static void ASE_KeyGEOMOBJECT( const char *token )
+{
+ if ( !strcmp( token, "*NODE_NAME" ) )
+ {
+ char *name = ase.objects[ase.currentObject].name;
+
+ ASE_GetToken( qtrue );
+ VERBOSE( ( " %s\n", s_token ) );
+ strcpy( ase.objects[ase.currentObject].name, s_token + 1 );
+ if ( strchr( ase.objects[ase.currentObject].name, '"' ) )
+ *strchr( ase.objects[ase.currentObject].name, '"' ) = 0;
+
+ if ( strstr( name, "tag" ) == name )
+ {
+ while ( strchr( name, '_' ) != strrchr( name, '_' ) )
+ {
+ *strrchr( name, '_' ) = 0;
+ }
+ while ( strrchr( name, ' ' ) )
+ {
+ *strrchr( name, ' ' ) = 0;
+ }
+ }
+ }
+ else if ( !strcmp( token, "*NODE_PARENT" ) )
+ {
+ ASE_SkipRestOfLine();
+ }
+ // ignore unused data blocks
+ else if ( !strcmp( token, "*NODE_TM" ) ||
+ !strcmp( token, "*TM_ANIMATION" ) )
+ {
+ ASE_ParseBracedBlock( 0 );
+ }
+ // ignore regular meshes that aren't part of animation
+ else if ( !strcmp( token, "*MESH" ) && !ase.grabAnims )
+ {
+/*
+ if ( strstr( ase.objects[ase.currentObject].name, "tag_" ) == ase.objects[ase.currentObject].name )
+ {
+ s_forceStaticMesh = true;
+ ASE_ParseBracedBlock( ASE_KeyMESH );
+ s_forceStaticMesh = false;
+ }
+*/
+ ASE_ParseBracedBlock( ASE_KeyMESH );
+ if ( ++ase.objects[ase.currentObject].anim.currentFrame == MAX_ASE_ANIMATION_FRAMES )
+ {
+ Error( "Too many animation frames" );
+ }
+ ase.objects[ase.currentObject].anim.numFrames = ase.objects[ase.currentObject].anim.currentFrame;
+ ase.objects[ase.currentObject].numAnimations++;
+/*
+ // ignore meshes that aren't part of animations if this object isn't a
+ // a tag
+ else
+ {
+ ASE_ParseBracedBlock( 0 );
+ }
+*/
+ }
+ // according to spec these are obsolete
+ else if ( !strcmp( token, "*MATERIAL_REF" ) )
+ {
+ ASE_GetToken( qfalse );
+
+ ase.objects[ase.currentObject].materialRef = atoi( s_token );
+ }
+ // loads a sequence of animation frames
+ else if ( !strcmp( token, "*MESH_ANIMATION" ) )
+ {
+ if ( ase.grabAnims )
+ {
+ VERBOSE( ( "..found MESH_ANIMATION\n" ) );
+
+ if ( ase.objects[ase.currentObject].numAnimations )
+ {
+ Error( "Multiple MESH_ANIMATIONS within a single GEOM_OBJECT" );
+ }
+ ASE_ParseBracedBlock( ASE_KeyMESH_ANIMATION );
+ ase.objects[ase.currentObject].anim.numFrames = ase.objects[ase.currentObject].anim.currentFrame;
+ ase.objects[ase.currentObject].numAnimations++;
+ }
+ else
+ {
+ ASE_SkipEnclosingBraces();
+ }
+ }
+ // skip unused info
+ else if ( !strcmp( token, "*PROP_MOTIONBLUR" ) ||
+ !strcmp( token, "*PROP_CASTSHADOW" ) ||
+ !strcmp( token, "*PROP_RECVSHADOW" ) )
+ {
+ ASE_SkipRestOfLine();
+ }
+}
+
+static void ConcatenateObjects( aseGeomObject_t *pObjA, aseGeomObject_t *pObjB )
+{
+}
+
+static void CollapseObjects( void )
+{
+ int i;
+ int numObjects = ase.currentObject;
+
+ for ( i = 0; i < numObjects; i++ )
+ {
+ int j;
+
+ // skip tags
+ if ( strstr( ase.objects[i].name, "tag" ) == ase.objects[i].name )
+ {
+ continue;
+ }
+
+ if ( !ase.objects[i].numAnimations )
+ {
+ continue;
+ }
+
+ for ( j = i + 1; j < numObjects; j++ )
+ {
+ if ( strstr( ase.objects[j].name, "tag" ) == ase.objects[j].name )
+ {
+ continue;
+ }
+ if ( ase.objects[i].materialRef == ase.objects[j].materialRef )
+ {
+ if ( ase.objects[j].numAnimations )
+ {
+ ConcatenateObjects( &ase.objects[i], &ase.objects[j] );
+ }
+ }
+ }
+ }
+}
+
+/*
+** ASE_Process
+*/
+static void ASE_Process( void )
+{
+ while ( ASE_GetToken( qfalse ) )
+ {
+ if ( !strcmp( s_token, "*3DSMAX_ASCIIEXPORT" ) ||
+ !strcmp( s_token, "*COMMENT" ) )
+ {
+ ASE_SkipRestOfLine();
+ }
+ else if ( !strcmp( s_token, "*SCENE" ) )
+ ASE_SkipEnclosingBraces();
+ else if ( !strcmp( s_token, "*MATERIAL_LIST" ) )
+ {
+ VERBOSE( ("MATERIAL_LIST\n") );
+
+ ASE_ParseBracedBlock( ASE_KeyMATERIAL_LIST );
+ }
+ else if ( !strcmp( s_token, "*GEOMOBJECT" ) )
+ {
+ VERBOSE( ("GEOMOBJECT" ) );
+
+ ASE_ParseBracedBlock( ASE_KeyGEOMOBJECT );
+
+ if ( strstr( ase.objects[ase.currentObject].name, "Bip" ) ||
+ strstr( ase.objects[ase.currentObject].name, "ignore_" ) )
+ {
+ ASE_FreeGeomObject( ase.currentObject );
+ VERBOSE( ( "(discarding BIP/ignore object)\n" ) );
+ }
+ else if ( ( strstr( ase.objects[ase.currentObject].name, "h_" ) != ase.objects[ase.currentObject].name ) &&
+ ( strstr( ase.objects[ase.currentObject].name, "l_" ) != ase.objects[ase.currentObject].name ) &&
+ ( strstr( ase.objects[ase.currentObject].name, "u_" ) != ase.objects[ase.currentObject].name ) &&
+ ( strstr( ase.objects[ase.currentObject].name, "tag" ) != ase.objects[ase.currentObject].name ) &&
+ ase.grabAnims )
+ {
+ VERBOSE( ( "(ignoring improperly labeled object '%s')\n", ase.objects[ase.currentObject].name ) );
+ ASE_FreeGeomObject( ase.currentObject );
+ }
+ else
+ {
+ if ( ++ase.currentObject == MAX_ASE_OBJECTS )
+ {
+ Error( "Too many GEOMOBJECTs" );
+ }
+ }
+ }
+ else if ( s_token[0] )
+ {
+ printf( "Unknown token '%s'\n", s_token );
+ }
+ }
+
+ if ( !ase.currentObject )
+ Error( "No animation data!" );
+
+ CollapseObjects();
+}
+
diff --git a/common/aselib.h b/common/aselib.h
new file mode 100755
index 0000000..31bc0e6
--- /dev/null
+++ b/common/aselib.h
@@ -0,0 +1,31 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "cmdlib.h"
+#include "mathlib.h"
+#include "polyset.h"
+
+void ASE_Load( const char *filename, qboolean verbose, qboolean meshanims );
+int ASE_GetNumSurfaces( void );
+polyset_t *ASE_GetSurfaceAnimation( int ndx, int *numFrames, int skipFrameStart, int skipFrameEnd, int maxFrames );
+const char *ASE_GetSurfaceName( int ndx );
+void ASE_Free( void );
diff --git a/common/bspfile.c b/common/bspfile.c
new file mode 100755
index 0000000..d9d4e04
--- /dev/null
+++ b/common/bspfile.c
@@ -0,0 +1,564 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "cmdlib.h"
+#include "mathlib.h"
+#include "bspfile.h"
+#include "scriplib.h"
+
+void GetLeafNums (void);
+
+//=============================================================================
+
+int nummodels;
+dmodel_t dmodels[MAX_MAP_MODELS];
+
+int numShaders;
+dshader_t dshaders[MAX_MAP_SHADERS];
+
+int entdatasize;
+char dentdata[MAX_MAP_ENTSTRING];
+
+int numleafs;
+dleaf_t dleafs[MAX_MAP_LEAFS];
+
+int numplanes;
+dplane_t dplanes[MAX_MAP_PLANES];
+
+int numnodes;
+dnode_t dnodes[MAX_MAP_NODES];
+
+int numleafsurfaces;
+int dleafsurfaces[MAX_MAP_LEAFFACES];
+
+int numleafbrushes;
+int dleafbrushes[MAX_MAP_LEAFBRUSHES];
+
+int numbrushes;
+dbrush_t dbrushes[MAX_MAP_BRUSHES];
+
+int numbrushsides;
+dbrushside_t dbrushsides[MAX_MAP_BRUSHSIDES];
+
+int numLightBytes;
+byte lightBytes[MAX_MAP_LIGHTING];
+
+int numGridPoints;
+byte gridData[MAX_MAP_LIGHTGRID];
+
+int numVisBytes;
+byte visBytes[MAX_MAP_VISIBILITY];
+
+int numDrawVerts;
+drawVert_t drawVerts[MAX_MAP_DRAW_VERTS];
+
+int numDrawIndexes;
+int drawIndexes[MAX_MAP_DRAW_INDEXES];
+
+int numDrawSurfaces;
+dsurface_t drawSurfaces[MAX_MAP_DRAW_SURFS];
+
+int numFogs;
+dfog_t dfogs[MAX_MAP_FOGS];
+
+//=============================================================================
+
+/*
+=============
+SwapBlock
+
+If all values are 32 bits, this can be used to swap everything
+=============
+*/
+void SwapBlock( int *block, int sizeOfBlock ) {
+ int i;
+
+ sizeOfBlock >>= 2;
+ for ( i = 0 ; i < sizeOfBlock ; i++ ) {
+ block[i] = LittleLong( block[i] );
+ }
+}
+
+/*
+=============
+SwapBSPFile
+
+Byte swaps all data in a bsp file.
+=============
+*/
+void SwapBSPFile( void ) {
+ int i;
+
+ // models
+ SwapBlock( (int *)dmodels, nummodels * sizeof( dmodels[0] ) );
+
+ // shaders (don't swap the name)
+ for ( i = 0 ; i < numShaders ; i++ ) {
+ dshaders[i].contentFlags = LittleLong( dshaders[i].contentFlags );
+ dshaders[i].surfaceFlags = LittleLong( dshaders[i].surfaceFlags );
+ }
+
+ // planes
+ SwapBlock( (int *)dplanes, numplanes * sizeof( dplanes[0] ) );
+
+ // nodes
+ SwapBlock( (int *)dnodes, numnodes * sizeof( dnodes[0] ) );
+
+ // leafs
+ SwapBlock( (int *)dleafs, numleafs * sizeof( dleafs[0] ) );
+
+ // leaffaces
+ SwapBlock( (int *)dleafsurfaces, numleafsurfaces * sizeof( dleafsurfaces[0] ) );
+
+ // leafbrushes
+ SwapBlock( (int *)dleafbrushes, numleafbrushes * sizeof( dleafbrushes[0] ) );
+
+ // brushes
+ SwapBlock( (int *)dbrushes, numbrushes * sizeof( dbrushes[0] ) );
+
+ // brushsides
+ SwapBlock( (int *)dbrushsides, numbrushsides * sizeof( dbrushsides[0] ) );
+
+ // vis
+ ((int *)&visBytes)[0] = LittleLong( ((int *)&visBytes)[0] );
+ ((int *)&visBytes)[1] = LittleLong( ((int *)&visBytes)[1] );
+
+ // drawverts (don't swap colors )
+ for ( i = 0 ; i < numDrawVerts ; i++ ) {
+ drawVerts[i].lightmap[0] = LittleFloat( drawVerts[i].lightmap[0] );
+ drawVerts[i].lightmap[1] = LittleFloat( drawVerts[i].lightmap[1] );
+ drawVerts[i].st[0] = LittleFloat( drawVerts[i].st[0] );
+ drawVerts[i].st[1] = LittleFloat( drawVerts[i].st[1] );
+ drawVerts[i].xyz[0] = LittleFloat( drawVerts[i].xyz[0] );
+ drawVerts[i].xyz[1] = LittleFloat( drawVerts[i].xyz[1] );
+ drawVerts[i].xyz[2] = LittleFloat( drawVerts[i].xyz[2] );
+ drawVerts[i].normal[0] = LittleFloat( drawVerts[i].normal[0] );
+ drawVerts[i].normal[1] = LittleFloat( drawVerts[i].normal[1] );
+ drawVerts[i].normal[2] = LittleFloat( drawVerts[i].normal[2] );
+ }
+
+ // drawindexes
+ SwapBlock( (int *)drawIndexes, numDrawIndexes * sizeof( drawIndexes[0] ) );
+
+ // drawsurfs
+ SwapBlock( (int *)drawSurfaces, numDrawSurfaces * sizeof( drawSurfaces[0] ) );
+
+ // fogs
+ for ( i = 0 ; i < numFogs ; i++ ) {
+ dfogs[i].brushNum = LittleLong( dfogs[i].brushNum );
+ dfogs[i].visibleSide = LittleLong( dfogs[i].visibleSide );
+ }
+}
+
+
+
+/*
+=============
+CopyLump
+=============
+*/
+int CopyLump( dheader_t *header, int lump, void *dest, int size ) {
+ int length, ofs;
+
+ length = header->lumps[lump].filelen;
+ ofs = header->lumps[lump].fileofs;
+
+ if ( length % size ) {
+ Error ("LoadBSPFile: odd lump size");
+ }
+
+ memcpy( dest, (byte *)header + ofs, length );
+
+ return length / size;
+}
+
+/*
+=============
+LoadBSPFile
+=============
+*/
+void LoadBSPFile( const char *filename ) {
+ dheader_t *header;
+
+ // load the file header
+ LoadFile (filename, (void **)&header);
+
+ // swap the header
+ SwapBlock( (int *)header, sizeof(*header) );
+
+ if ( header->ident != BSP_IDENT ) {
+ Error( "%s is not a IBSP file", filename );
+ }
+ if ( header->version != BSP_VERSION ) {
+ Error( "%s is version %i, not %i", filename, header->version, BSP_VERSION );
+ }
+
+ numShaders = CopyLump( header, LUMP_SHADERS, dshaders, sizeof(dshader_t) );
+ nummodels = CopyLump( header, LUMP_MODELS, dmodels, sizeof(dmodel_t) );
+ numplanes = CopyLump( header, LUMP_PLANES, dplanes, sizeof(dplane_t) );
+ numleafs = CopyLump( header, LUMP_LEAFS, dleafs, sizeof(dleaf_t) );
+ numnodes = CopyLump( header, LUMP_NODES, dnodes, sizeof(dnode_t) );
+ numleafsurfaces = CopyLump( header, LUMP_LEAFSURFACES, dleafsurfaces, sizeof(dleafsurfaces[0]) );
+ numleafbrushes = CopyLump( header, LUMP_LEAFBRUSHES, dleafbrushes, sizeof(dleafbrushes[0]) );
+ numbrushes = CopyLump( header, LUMP_BRUSHES, dbrushes, sizeof(dbrush_t) );
+ numbrushsides = CopyLump( header, LUMP_BRUSHSIDES, dbrushsides, sizeof(dbrushside_t) );
+ numDrawVerts = CopyLump( header, LUMP_DRAWVERTS, drawVerts, sizeof(drawVert_t) );
+ numDrawSurfaces = CopyLump( header, LUMP_SURFACES, drawSurfaces, sizeof(dsurface_t) );
+ numFogs = CopyLump( header, LUMP_FOGS, dfogs, sizeof(dfog_t) );
+ numDrawIndexes = CopyLump( header, LUMP_DRAWINDEXES, drawIndexes, sizeof(drawIndexes[0]) );
+
+ numVisBytes = CopyLump( header, LUMP_VISIBILITY, visBytes, 1 );
+ numLightBytes = CopyLump( header, LUMP_LIGHTMAPS, lightBytes, 1 );
+ entdatasize = CopyLump( header, LUMP_ENTITIES, dentdata, 1);
+
+ numGridPoints = CopyLump( header, LUMP_LIGHTGRID, gridData, 8 );
+
+
+ free( header ); // everything has been copied out
+
+ // swap everything
+ SwapBSPFile();
+}
+
+
+//============================================================================
+
+/*
+=============
+AddLump
+=============
+*/
+void AddLump( FILE *bspfile, dheader_t *header, int lumpnum, const void *data, int len ) {
+ lump_t *lump;
+
+ lump = &header->lumps[lumpnum];
+
+ lump->fileofs = LittleLong( ftell(bspfile) );
+ lump->filelen = LittleLong( len );
+ SafeWrite( bspfile, data, (len+3)&~3 );
+}
+
+/*
+=============
+WriteBSPFile
+
+Swaps the bsp file in place, so it should not be referenced again
+=============
+*/
+void WriteBSPFile( const char *filename ) {
+ dheader_t outheader, *header;
+ FILE *bspfile;
+
+ header = &outheader;
+ memset( header, 0, sizeof(dheader_t) );
+
+ SwapBSPFile();
+
+ header->ident = LittleLong( BSP_IDENT );
+ header->version = LittleLong( BSP_VERSION );
+
+ bspfile = SafeOpenWrite( filename );
+ SafeWrite( bspfile, header, sizeof(dheader_t) ); // overwritten later
+
+ AddLump( bspfile, header, LUMP_SHADERS, dshaders, numShaders*sizeof(dshader_t) );
+ AddLump( bspfile, header, LUMP_PLANES, dplanes, numplanes*sizeof(dplane_t) );
+ AddLump( bspfile, header, LUMP_LEAFS, dleafs, numleafs*sizeof(dleaf_t) );
+ AddLump( bspfile, header, LUMP_NODES, dnodes, numnodes*sizeof(dnode_t) );
+ AddLump( bspfile, header, LUMP_BRUSHES, dbrushes, numbrushes*sizeof(dbrush_t) );
+ AddLump( bspfile, header, LUMP_BRUSHSIDES, dbrushsides, numbrushsides*sizeof(dbrushside_t) );
+ AddLump( bspfile, header, LUMP_LEAFSURFACES, dleafsurfaces, numleafsurfaces*sizeof(dleafsurfaces[0]) );
+ AddLump( bspfile, header, LUMP_LEAFBRUSHES, dleafbrushes, numleafbrushes*sizeof(dleafbrushes[0]) );
+ AddLump( bspfile, header, LUMP_MODELS, dmodels, nummodels*sizeof(dmodel_t) );
+ AddLump( bspfile, header, LUMP_DRAWVERTS, drawVerts, numDrawVerts*sizeof(drawVert_t) );
+ AddLump( bspfile, header, LUMP_SURFACES, drawSurfaces, numDrawSurfaces*sizeof(dsurface_t) );
+ AddLump( bspfile, header, LUMP_VISIBILITY, visBytes, numVisBytes );
+ AddLump( bspfile, header, LUMP_LIGHTMAPS, lightBytes, numLightBytes );
+ AddLump( bspfile, header, LUMP_LIGHTGRID, gridData, 8 * numGridPoints );
+ AddLump( bspfile, header, LUMP_ENTITIES, dentdata, entdatasize );
+ AddLump( bspfile, header, LUMP_FOGS, dfogs, numFogs * sizeof(dfog_t) );
+ AddLump( bspfile, header, LUMP_DRAWINDEXES, drawIndexes, numDrawIndexes * sizeof(drawIndexes[0]) );
+
+ fseek (bspfile, 0, SEEK_SET);
+ SafeWrite (bspfile, header, sizeof(dheader_t));
+ fclose (bspfile);
+}
+
+//============================================================================
+
+/*
+=============
+PrintBSPFileSizes
+
+Dumps info about current file
+=============
+*/
+void PrintBSPFileSizes( void ) {
+ if ( !num_entities ) {
+ ParseEntities();
+ }
+
+ printf ("%6i models %7i\n"
+ ,nummodels, (int)(nummodels*sizeof(dmodel_t)));
+ printf ("%6i shaders %7i\n"
+ ,numShaders, (int)(numShaders*sizeof(dshader_t)));
+ printf ("%6i brushes %7i\n"
+ ,numbrushes, (int)(numbrushes*sizeof(dbrush_t)));
+ printf ("%6i brushsides %7i\n"
+ ,numbrushsides, (int)(numbrushsides*sizeof(dbrushside_t)));
+ printf ("%6i fogs %7i\n"
+ ,numFogs, (int)(numFogs*sizeof(dfog_t)));
+ printf ("%6i planes %7i\n"
+ ,numplanes, (int)(numplanes*sizeof(dplane_t)));
+ printf ("%6i entdata %7i\n", num_entities, entdatasize);
+
+ printf ("\n");
+
+ printf ("%6i nodes %7i\n"
+ ,numnodes, (int)(numnodes*sizeof(dnode_t)));
+ printf ("%6i leafs %7i\n"
+ ,numleafs, (int)(numleafs*sizeof(dleaf_t)));
+ printf ("%6i leafsurfaces %7i\n"
+ ,numleafsurfaces, (int)(numleafsurfaces*sizeof(dleafsurfaces[0])));
+ printf ("%6i leafbrushes %7i\n"
+ ,numleafbrushes, (int)(numleafbrushes*sizeof(dleafbrushes[0])));
+ printf ("%6i drawverts %7i\n"
+ ,numDrawVerts, (int)(numDrawVerts*sizeof(drawVerts[0])));
+ printf ("%6i drawindexes %7i\n"
+ ,numDrawIndexes, (int)(numDrawIndexes*sizeof(drawIndexes[0])));
+ printf ("%6i drawsurfaces %7i\n"
+ ,numDrawSurfaces, (int)(numDrawSurfaces*sizeof(drawSurfaces[0])));
+
+ printf ("%6i lightmaps %7i\n"
+ ,numLightBytes / (LIGHTMAP_WIDTH*LIGHTMAP_HEIGHT*3), numLightBytes );
+ printf (" visibility %7i\n"
+ , numVisBytes );
+}
+
+
+//============================================
+
+int num_entities;
+entity_t entities[MAX_MAP_ENTITIES];
+
+void StripTrailing( char *e ) {
+ char *s;
+
+ s = e + strlen(e)-1;
+ while (s >= e && *s <= 32)
+ {
+ *s = 0;
+ s--;
+ }
+}
+
+/*
+=================
+ParseEpair
+=================
+*/
+epair_t *ParseEpair( void ) {
+ epair_t *e;
+
+ e = malloc( sizeof(epair_t) );
+ memset( e, 0, sizeof(epair_t) );
+
+ if ( strlen(token) >= MAX_KEY-1 ) {
+ Error ("ParseEpar: token too long");
+ }
+ e->key = copystring( token );
+ GetToken( qfalse );
+ if ( strlen(token) >= MAX_VALUE-1 ) {
+ Error ("ParseEpar: token too long");
+ }
+ e->value = copystring( token );
+
+ // strip trailing spaces that sometimes get accidentally
+ // added in the editor
+ StripTrailing( e->key );
+ StripTrailing( e->value );
+
+ return e;
+}
+
+
+/*
+================
+ParseEntity
+================
+*/
+qboolean ParseEntity( void ) {
+ epair_t *e;
+ entity_t *mapent;
+
+ if ( !GetToken (qtrue) ) {
+ return qfalse;
+ }
+
+ if ( strcmp (token, "{") ) {
+ Error ("ParseEntity: { not found");
+ }
+ if ( num_entities == MAX_MAP_ENTITIES ) {
+ Error ("num_entities == MAX_MAP_ENTITIES");
+ }
+ mapent = &entities[num_entities];
+ num_entities++;
+
+ do {
+ if ( !GetToken (qtrue) ) {
+ Error ("ParseEntity: EOF without closing brace");
+ }
+ if ( !strcmp (token, "}") ) {
+ break;
+ }
+ e = ParseEpair ();
+ e->next = mapent->epairs;
+ mapent->epairs = e;
+ } while (1);
+
+ return qtrue;
+}
+
+/*
+================
+ParseEntities
+
+Parses the dentdata string into entities
+================
+*/
+void ParseEntities( void ) {
+ num_entities = 0;
+ ParseFromMemory( dentdata, entdatasize );
+
+ while ( ParseEntity () ) {
+ }
+}
+
+
+/*
+================
+UnparseEntities
+
+Generates the dentdata string from all the entities
+This allows the utilities to add or remove key/value pairs
+to the data created by the map editor.
+================
+*/
+void UnparseEntities( void ) {
+ char *buf, *end;
+ epair_t *ep;
+ char line[2048];
+ int i;
+ char key[1024], value[1024];
+
+ buf = dentdata;
+ end = buf;
+ *end = 0;
+
+ for (i=0 ; i<num_entities ; i++) {
+ ep = entities[i].epairs;
+ if ( !ep ) {
+ continue; // ent got removed
+ }
+
+ strcat (end,"{\n");
+ end += 2;
+
+ for ( ep = entities[i].epairs ; ep ; ep=ep->next ) {
+ strcpy (key, ep->key);
+ StripTrailing (key);
+ strcpy (value, ep->value);
+ StripTrailing (value);
+
+ sprintf (line, "\"%s\" \"%s\"\n", key, value);
+ strcat (end, line);
+ end += strlen(line);
+ }
+ strcat (end,"}\n");
+ end += 2;
+
+ if (end > buf + MAX_MAP_ENTSTRING) {
+ Error ("Entity text too long");
+ }
+ }
+ entdatasize = end - buf + 1;
+}
+
+void PrintEntity( const entity_t *ent ) {
+ epair_t *ep;
+
+ printf ("------- entity %p -------\n", ent);
+ for (ep=ent->epairs ; ep ; ep=ep->next) {
+ printf( "%s = %s\n", ep->key, ep->value );
+ }
+
+}
+
+void SetKeyValue( entity_t *ent, const char *key, const char *value ) {
+ epair_t *ep;
+
+ for ( ep=ent->epairs ; ep ; ep=ep->next ) {
+ if ( !strcmp (ep->key, key) ) {
+ free (ep->value);
+ ep->value = copystring(value);
+ return;
+ }
+ }
+ ep = malloc (sizeof(*ep));
+ ep->next = ent->epairs;
+ ent->epairs = ep;
+ ep->key = copystring(key);
+ ep->value = copystring(value);
+}
+
+const char *ValueForKey( const entity_t *ent, const char *key ) {
+ epair_t *ep;
+
+ for (ep=ent->epairs ; ep ; ep=ep->next) {
+ if (!strcmp (ep->key, key) ) {
+ return ep->value;
+ }
+ }
+ return "";
+}
+
+vec_t FloatForKey( const entity_t *ent, const char *key ) {
+ const char *k;
+
+ k = ValueForKey( ent, key );
+ return atof(k);
+}
+
+void GetVectorForKey( const entity_t *ent, const char *key, vec3_t vec ) {
+ const char *k;
+ double v1, v2, v3;
+
+ k = ValueForKey (ent, key);
+
+ // scanf into doubles, then assign, so it is vec_t size independent
+ v1 = v2 = v3 = 0;
+ sscanf (k, "%lf %lf %lf", &v1, &v2, &v3);
+ vec[0] = v1;
+ vec[1] = v2;
+ vec[2] = v3;
+}
+
+
diff --git a/common/bspfile.h b/common/bspfile.h
new file mode 100755
index 0000000..fa136dd
--- /dev/null
+++ b/common/bspfile.h
@@ -0,0 +1,118 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifdef _TTIMOBUILD
+#include "qfiles.h"
+#include "surfaceflags.h"
+#else
+#include "../code/qcommon/qfiles.h"
+#include "../code/game/surfaceflags.h"
+#endif
+
+extern int nummodels;
+extern dmodel_t dmodels[MAX_MAP_MODELS];
+
+extern int numShaders;
+extern dshader_t dshaders[MAX_MAP_MODELS];
+
+extern int entdatasize;
+extern char dentdata[MAX_MAP_ENTSTRING];
+
+extern int numleafs;
+extern dleaf_t dleafs[MAX_MAP_LEAFS];
+
+extern int numplanes;
+extern dplane_t dplanes[MAX_MAP_PLANES];
+
+extern int numnodes;
+extern dnode_t dnodes[MAX_MAP_NODES];
+
+extern int numleafsurfaces;
+extern int dleafsurfaces[MAX_MAP_LEAFFACES];
+
+extern int numleafbrushes;
+extern int dleafbrushes[MAX_MAP_LEAFBRUSHES];
+
+extern int numbrushes;
+extern dbrush_t dbrushes[MAX_MAP_BRUSHES];
+
+extern int numbrushsides;
+extern dbrushside_t dbrushsides[MAX_MAP_BRUSHSIDES];
+
+extern int numLightBytes;
+extern byte lightBytes[MAX_MAP_LIGHTING];
+
+extern int numGridPoints;
+extern byte gridData[MAX_MAP_LIGHTGRID];
+
+extern int numVisBytes;
+extern byte visBytes[MAX_MAP_VISIBILITY];
+
+extern int numDrawVerts;
+extern drawVert_t drawVerts[MAX_MAP_DRAW_VERTS];
+
+extern int numDrawIndexes;
+extern int drawIndexes[MAX_MAP_DRAW_INDEXES];
+
+extern int numDrawSurfaces;
+extern dsurface_t drawSurfaces[MAX_MAP_DRAW_SURFS];
+
+extern int numFogs;
+extern dfog_t dfogs[MAX_MAP_FOGS];
+
+void LoadBSPFile( const char *filename );
+void WriteBSPFile( const char *filename );
+void PrintBSPFileSizes( void );
+
+//===============
+
+
+typedef struct epair_s {
+ struct epair_s *next;
+ char *key;
+ char *value;
+} epair_t;
+
+typedef struct {
+ vec3_t origin;
+ struct bspbrush_s *brushes;
+ struct parseMesh_s *patches;
+ int firstDrawSurf;
+ epair_t *epairs;
+} entity_t;
+
+extern int num_entities;
+extern entity_t entities[MAX_MAP_ENTITIES];
+
+void ParseEntities( void );
+void UnparseEntities( void );
+
+void SetKeyValue( entity_t *ent, const char *key, const char *value );
+const char *ValueForKey( const entity_t *ent, const char *key );
+// will return "" if not present
+
+vec_t FloatForKey( const entity_t *ent, const char *key );
+void GetVectorForKey( const entity_t *ent, const char *key, vec3_t vec );
+
+epair_t *ParseEpair( void );
+
+void PrintEntity( const entity_t *ent );
+
diff --git a/common/cmdlib.c b/common/cmdlib.c
new file mode 100755
index 0000000..794d4c0
--- /dev/null
+++ b/common/cmdlib.c
@@ -0,0 +1,1201 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// cmdlib.c
+
+#include "cmdlib.h"
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#ifdef WIN32
+#include <direct.h>
+#include <windows.h>
+#endif
+
+#ifdef NeXT
+#include <libc.h>
+#endif
+
+#define BASEDIRNAME "quake" // assumed to have a 2 or 3 following
+#define PATHSEPERATOR '/'
+
+// set these before calling CheckParm
+int myargc;
+char **myargv;
+
+char com_token[1024];
+qboolean com_eof;
+
+qboolean archive;
+char archivedir[1024];
+
+
+/*
+===================
+ExpandWildcards
+
+Mimic unix command line expansion
+===================
+*/
+#define MAX_EX_ARGC 1024
+int ex_argc;
+char *ex_argv[MAX_EX_ARGC];
+#ifdef _WIN32
+#include "io.h"
+void ExpandWildcards( int *argc, char ***argv )
+{
+ struct _finddata_t fileinfo;
+ int handle;
+ int i;
+ char filename[1024];
+ char filebase[1024];
+ char *path;
+
+ ex_argc = 0;
+ for (i=0 ; i<*argc ; i++)
+ {
+ path = (*argv)[i];
+ if ( path[0] == '-'
+ || ( !strstr(path, "*") && !strstr(path, "?") ) )
+ {
+ ex_argv[ex_argc++] = path;
+ continue;
+ }
+
+ handle = _findfirst (path, &fileinfo);
+ if (handle == -1)
+ return;
+
+ ExtractFilePath (path, filebase);
+
+ do
+ {
+ sprintf (filename, "%s%s", filebase, fileinfo.name);
+ ex_argv[ex_argc++] = copystring (filename);
+ } while (_findnext( handle, &fileinfo ) != -1);
+
+ _findclose (handle);
+ }
+
+ *argc = ex_argc;
+ *argv = ex_argv;
+}
+#else
+void ExpandWildcards (int *argc, char ***argv)
+{
+}
+#endif
+
+#ifdef WIN_ERROR
+#include <windows.h>
+/*
+=================
+Error
+
+For abnormal program terminations in windowed apps
+=================
+*/
+void Error( const char *error, ... )
+{
+ va_list argptr;
+ char text[1024];
+ char text2[1024];
+ int err;
+
+ err = GetLastError ();
+
+ va_start (argptr,error);
+ vsprintf (text, error,argptr);
+ va_end (argptr);
+
+ sprintf (text2, "%s\nGetLastError() = %i", text, err);
+ MessageBox(NULL, text2, "Error", 0 /* MB_OK */ );
+
+ exit (1);
+}
+
+#else
+/*
+=================
+Error
+
+For abnormal program terminations in console apps
+=================
+*/
+void Error( const char *error, ...)
+{
+ va_list argptr;
+
+ _printf ("\n************ ERROR ************\n");
+
+ va_start (argptr,error);
+ vprintf (error,argptr);
+ va_end (argptr);
+ _printf ("\r\n");
+
+ exit (1);
+}
+#endif
+
+// only printf if in verbose mode
+qboolean verbose = qfalse;
+void qprintf( const char *format, ... ) {
+ va_list argptr;
+
+ if (!verbose)
+ return;
+
+ va_start (argptr,format);
+ vprintf (format,argptr);
+ va_end (argptr);
+
+}
+
+#ifdef WIN32
+HWND hwndOut = NULL;
+qboolean lookedForServer = qfalse;
+UINT wm_BroadcastCommand = -1;
+#endif
+
+void _printf( const char *format, ... ) {
+ va_list argptr;
+ char text[4096];
+ ATOM a;
+
+ va_start (argptr,format);
+ vsprintf (text, format, argptr);
+ va_end (argptr);
+
+ printf(text);
+
+#ifdef WIN32
+ if (!lookedForServer) {
+ lookedForServer = qtrue;
+ hwndOut = FindWindow(NULL, "Q3Map Process Server");
+ if (hwndOut) {
+ wm_BroadcastCommand = RegisterWindowMessage( "Q3MPS_BroadcastCommand" );
+ }
+ }
+ if (hwndOut) {
+ a = GlobalAddAtom(text);
+ PostMessage(hwndOut, wm_BroadcastCommand, 0, (LPARAM)a);
+ }
+#endif
+}
+
+
+/*
+
+qdir will hold the path up to the quake directory, including the slash
+
+ f:\quake\
+ /raid/quake/
+
+gamedir will hold qdir + the game directory (id1, id2, etc)
+
+ */
+
+char qdir[1024];
+char gamedir[1024];
+char writedir[1024];
+
+void SetQdirFromPath( const char *path )
+{
+ char temp[1024];
+ const char *c;
+ const char *sep;
+ int len, count;
+
+ if (!(path[0] == '/' || path[0] == '\\' || path[1] == ':'))
+ { // path is partial
+ Q_getwd (temp);
+ strcat (temp, path);
+ path = temp;
+ }
+
+ // search for "quake2" in path
+
+ len = strlen(BASEDIRNAME);
+ for (c=path+strlen(path)-1 ; c != path ; c--)
+ {
+ int i;
+
+ if (!Q_strncasecmp (c, BASEDIRNAME, len))
+ {
+ //
+ //strncpy (qdir, path, c+len+2-path);
+ // the +2 assumes a 2 or 3 following quake which is not the
+ // case with a retail install
+ // so we need to add up how much to the next separator
+ sep = c + len;
+ count = 1;
+ while (*sep && *sep != '/' && *sep != '\\')
+ {
+ sep++;
+ count++;
+ }
+ strncpy (qdir, path, c+len+count-path);
+ qprintf ("qdir: %s\n", qdir);
+ for ( i = 0; i < strlen( qdir ); i++ )
+ {
+ if ( qdir[i] == '\\' )
+ qdir[i] = '/';
+ }
+
+ c += len+count;
+ while (*c)
+ {
+ if (*c == '/' || *c == '\\')
+ {
+ strncpy (gamedir, path, c+1-path);
+
+ for ( i = 0; i < strlen( gamedir ); i++ )
+ {
+ if ( gamedir[i] == '\\' )
+ gamedir[i] = '/';
+ }
+
+ qprintf ("gamedir: %s\n", gamedir);
+
+ if ( !writedir[0] )
+ strcpy( writedir, gamedir );
+ else if ( writedir[strlen( writedir )-1] != '/' )
+ {
+ writedir[strlen( writedir )] = '/';
+ writedir[strlen( writedir )+1] = 0;
+ }
+
+ return;
+ }
+ c++;
+ }
+ Error ("No gamedir in %s", path);
+ return;
+ }
+ }
+ Error ("SetQdirFromPath: no '%s' in %s", BASEDIRNAME, path);
+}
+
+char *ExpandArg (const char *path)
+{
+ static char full[1024];
+
+ if (path[0] != '/' && path[0] != '\\' && path[1] != ':')
+ {
+ Q_getwd (full);
+ strcat (full, path);
+ }
+ else
+ strcpy (full, path);
+ return full;
+}
+
+char *ExpandPath (const char *path)
+{
+ static char full[1024];
+ if (!qdir)
+ Error ("ExpandPath called without qdir set");
+ if (path[0] == '/' || path[0] == '\\' || path[1] == ':') {
+ strcpy( full, path );
+ return full;
+ }
+ sprintf (full, "%s%s", qdir, path);
+ return full;
+}
+
+char *ExpandGamePath (const char *path)
+{
+ static char full[1024];
+ if (!qdir)
+ Error ("ExpandGamePath called without qdir set");
+ if (path[0] == '/' || path[0] == '\\' || path[1] == ':') {
+ strcpy( full, path );
+ return full;
+ }
+ sprintf (full, "%s%s", gamedir, path);
+ return full;
+}
+
+char *ExpandPathAndArchive (const char *path)
+{
+ char *expanded;
+ char archivename[1024];
+
+ expanded = ExpandPath (path);
+
+ if (archive)
+ {
+ sprintf (archivename, "%s/%s", archivedir, path);
+ QCopyFile (expanded, archivename);
+ }
+ return expanded;
+}
+
+
+char *copystring(const char *s)
+{
+ char *b;
+ b = malloc(strlen(s)+1);
+ strcpy (b, s);
+ return b;
+}
+
+
+
+/*
+================
+I_FloatTime
+================
+*/
+double I_FloatTime (void)
+{
+ time_t t;
+
+ time (&t);
+
+ return t;
+#if 0
+// more precise, less portable
+ struct timeval tp;
+ struct timezone tzp;
+ static int secbase;
+
+ gettimeofday(&tp, &tzp);
+
+ if (!secbase)
+ {
+ secbase = tp.tv_sec;
+ return tp.tv_usec/1000000.0;
+ }
+
+ return (tp.tv_sec - secbase) + tp.tv_usec/1000000.0;
+#endif
+}
+
+void Q_getwd (char *out)
+{
+ int i = 0;
+
+#ifdef WIN32
+ _getcwd (out, 256);
+ strcat (out, "\\");
+#else
+ getwd (out);
+ strcat (out, "/");
+#endif
+
+ while ( out[i] != 0 )
+ {
+ if ( out[i] == '\\' )
+ out[i] = '/';
+ i++;
+ }
+}
+
+
+void Q_mkdir (const char *path)
+{
+#ifdef WIN32
+ if (_mkdir (path) != -1)
+ return;
+#else
+ if (mkdir (path, 0777) != -1)
+ return;
+#endif
+ if (errno != EEXIST)
+ Error ("mkdir %s: %s",path, strerror(errno));
+}
+
+/*
+============
+FileTime
+
+returns -1 if not present
+============
+*/
+int FileTime (const char *path)
+{
+ struct stat buf;
+
+ if (stat (path,&buf) == -1)
+ return -1;
+
+ return buf.st_mtime;
+}
+
+
+
+/*
+==============
+COM_Parse
+
+Parse a token out of a string
+==============
+*/
+char *COM_Parse (char *data)
+{
+ int c;
+ int len;
+
+ len = 0;
+ com_token[0] = 0;
+
+ if (!data)
+ return NULL;
+
+// skip whitespace
+skipwhite:
+ while ( (c = *data) <= ' ')
+ {
+ if (c == 0)
+ {
+ com_eof = qtrue;
+ return NULL; // end of file;
+ }
+ data++;
+ }
+
+// skip // comments
+ if (c=='/' && data[1] == '/')
+ {
+ while (*data && *data != '\n')
+ data++;
+ goto skipwhite;
+ }
+
+
+// handle quoted strings specially
+ if (c == '\"')
+ {
+ data++;
+ do
+ {
+ c = *data++;
+ if (c=='\"')
+ {
+ com_token[len] = 0;
+ return data;
+ }
+ com_token[len] = c;
+ len++;
+ } while (1);
+ }
+
+// parse single characters
+ if (c=='{' || c=='}'|| c==')'|| c=='(' || c=='\'' || c==':')
+ {
+ com_token[len] = c;
+ len++;
+ com_token[len] = 0;
+ return data+1;
+ }
+
+// parse a regular word
+ do
+ {
+ com_token[len] = c;
+ data++;
+ len++;
+ c = *data;
+ if (c=='{' || c=='}'|| c==')'|| c=='(' || c=='\'' || c==':')
+ break;
+ } while (c>32);
+
+ com_token[len] = 0;
+ return data;
+}
+
+
+int Q_strncasecmp (const char *s1, const char *s2, int n)
+{
+ int c1, c2;
+
+ do
+ {
+ c1 = *s1++;
+ c2 = *s2++;
+
+ if (!n--)
+ return 0; // strings are equal until end point
+
+ if (c1 != c2)
+ {
+ if (c1 >= 'a' && c1 <= 'z')
+ c1 -= ('a' - 'A');
+ if (c2 >= 'a' && c2 <= 'z')
+ c2 -= ('a' - 'A');
+ if (c1 != c2)
+ return -1; // strings not equal
+ }
+ } while (c1);
+
+ return 0; // strings are equal
+}
+
+int Q_stricmp (const char *s1, const char *s2)
+{
+ return Q_strncasecmp (s1, s2, 99999);
+}
+
+
+char *strupr (char *start)
+{
+ char *in;
+ in = start;
+ while (*in)
+ {
+ *in = toupper(*in);
+ in++;
+ }
+ return start;
+}
+
+char *strlower (char *start)
+{
+ char *in;
+ in = start;
+ while (*in)
+ {
+ *in = tolower(*in);
+ in++;
+ }
+ return start;
+}
+
+
+/*
+=============================================================================
+
+ MISC FUNCTIONS
+
+=============================================================================
+*/
+
+
+/*
+=================
+CheckParm
+
+Checks for the given parameter in the program's command line arguments
+Returns the argument number (1 to argc-1) or 0 if not present
+=================
+*/
+int CheckParm (const char *check)
+{
+ int i;
+
+ for (i = 1;i<myargc;i++)
+ {
+ if ( !Q_stricmp(check, myargv[i]) )
+ return i;
+ }
+
+ return 0;
+}
+
+
+
+/*
+================
+Q_filelength
+================
+*/
+int Q_filelength (FILE *f)
+{
+ int pos;
+ int end;
+
+ pos = ftell (f);
+ fseek (f, 0, SEEK_END);
+ end = ftell (f);
+ fseek (f, pos, SEEK_SET);
+
+ return end;
+}
+
+
+FILE *SafeOpenWrite (const char *filename)
+{
+ FILE *f;
+
+ f = fopen(filename, "wb");
+
+ if (!f)
+ Error ("Error opening %s: %s",filename,strerror(errno));
+
+ return f;
+}
+
+FILE *SafeOpenRead (const char *filename)
+{
+ FILE *f;
+
+ f = fopen(filename, "rb");
+
+ if (!f)
+ Error ("Error opening %s: %s",filename,strerror(errno));
+
+ return f;
+}
+
+
+void SafeRead (FILE *f, void *buffer, int count)
+{
+ if ( fread (buffer, 1, count, f) != (size_t)count)
+ Error ("File read failure");
+}
+
+
+void SafeWrite (FILE *f, const void *buffer, int count)
+{
+ if (fwrite (buffer, 1, count, f) != (size_t)count)
+ Error ("File write failure");
+}
+
+
+/*
+==============
+FileExists
+==============
+*/
+qboolean FileExists (const char *filename)
+{
+ FILE *f;
+
+ f = fopen (filename, "r");
+ if (!f)
+ return qfalse;
+ fclose (f);
+ return qtrue;
+}
+
+/*
+==============
+LoadFile
+==============
+*/
+int LoadFile( const char *filename, void **bufferptr )
+{
+ FILE *f;
+ int length;
+ void *buffer;
+
+ f = SafeOpenRead (filename);
+ length = Q_filelength (f);
+ buffer = malloc (length+1);
+ ((char *)buffer)[length] = 0;
+ SafeRead (f, buffer, length);
+ fclose (f);
+
+ *bufferptr = buffer;
+ return length;
+}
+
+
+/*
+==============
+LoadFileBlock
+-
+rounds up memory allocation to 4K boundry
+-
+==============
+*/
+int LoadFileBlock( const char *filename, void **bufferptr )
+{
+ FILE *f;
+ int length, nBlock, nAllocSize;
+ void *buffer;
+
+ f = SafeOpenRead (filename);
+ length = Q_filelength (f);
+ nAllocSize = length;
+ nBlock = nAllocSize % MEM_BLOCKSIZE;
+ if ( nBlock > 0) {
+ nAllocSize += MEM_BLOCKSIZE - nBlock;
+ }
+ buffer = malloc (nAllocSize+1);
+ memset(buffer, 0, nAllocSize+1);
+ SafeRead (f, buffer, length);
+ fclose (f);
+
+ *bufferptr = buffer;
+ return length;
+}
+
+
+/*
+==============
+TryLoadFile
+
+Allows failure
+==============
+*/
+int TryLoadFile (const char *filename, void **bufferptr)
+{
+ FILE *f;
+ int length;
+ void *buffer;
+
+ *bufferptr = NULL;
+
+ f = fopen (filename, "rb");
+ if (!f)
+ return -1;
+ length = Q_filelength (f);
+ buffer = malloc (length+1);
+ ((char *)buffer)[length] = 0;
+ SafeRead (f, buffer, length);
+ fclose (f);
+
+ *bufferptr = buffer;
+ return length;
+}
+
+
+/*
+==============
+SaveFile
+==============
+*/
+void SaveFile (const char *filename, const void *buffer, int count)
+{
+ FILE *f;
+
+ f = SafeOpenWrite (filename);
+ SafeWrite (f, buffer, count);
+ fclose (f);
+}
+
+
+
+void DefaultExtension (char *path, const char *extension)
+{
+ char *src;
+//
+// if path doesnt have a .EXT, append extension
+// (extension should include the .)
+//
+ src = path + strlen(path) - 1;
+
+ while (*src != '/' && *src != '\\' && src != path)
+ {
+ if (*src == '.')
+ return; // it has an extension
+ src--;
+ }
+
+ strcat (path, extension);
+}
+
+
+void DefaultPath (char *path, const char *basepath)
+{
+ char temp[128];
+
+ if (path[0] == PATHSEPERATOR)
+ return; // absolute path location
+ strcpy (temp,path);
+ strcpy (path,basepath);
+ strcat (path,temp);
+}
+
+
+void StripFilename (char *path)
+{
+ int length;
+
+ length = strlen(path)-1;
+ while (length > 0 && path[length] != PATHSEPERATOR)
+ length--;
+ path[length] = 0;
+}
+
+void StripExtension (char *path)
+{
+ int length;
+
+ length = strlen(path)-1;
+ while (length > 0 && path[length] != '.')
+ {
+ length--;
+ if (path[length] == '/')
+ return; // no extension
+ }
+ if (length)
+ path[length] = 0;
+}
+
+
+/*
+====================
+Extract file parts
+====================
+*/
+// FIXME: should include the slash, otherwise
+// backing to an empty path will be wrong when appending a slash
+void ExtractFilePath (const char *path, char *dest)
+{
+ const char *src;
+
+ src = path + strlen(path) - 1;
+
+//
+// back up until a \ or the start
+//
+ while (src != path && *(src-1) != '\\' && *(src-1) != '/')
+ src--;
+
+ memcpy (dest, path, src-path);
+ dest[src-path] = 0;
+}
+
+void ExtractFileBase (const char *path, char *dest)
+{
+ const char *src;
+
+ src = path + strlen(path) - 1;
+
+//
+// back up until a \ or the start
+//
+ while (src != path && *(src-1) != PATHSEPERATOR)
+ src--;
+
+ while (*src && *src != '.')
+ {
+ *dest++ = *src++;
+ }
+ *dest = 0;
+}
+
+void ExtractFileExtension (const char *path, char *dest)
+{
+ const char *src;
+
+ src = path + strlen(path) - 1;
+
+//
+// back up until a . or the start
+//
+ while (src != path && *(src-1) != '.')
+ src--;
+ if (src == path)
+ {
+ *dest = 0; // no extension
+ return;
+ }
+
+ strcpy (dest,src);
+}
+
+
+/*
+==============
+ParseNum / ParseHex
+==============
+*/
+int ParseHex (const char *hex)
+{
+ const char *str;
+ int num;
+
+ num = 0;
+ str = hex;
+
+ while (*str)
+ {
+ num <<= 4;
+ if (*str >= '0' && *str <= '9')
+ num += *str-'0';
+ else if (*str >= 'a' && *str <= 'f')
+ num += 10 + *str-'a';
+ else if (*str >= 'A' && *str <= 'F')
+ num += 10 + *str-'A';
+ else
+ Error ("Bad hex number: %s",hex);
+ str++;
+ }
+
+ return num;
+}
+
+
+int ParseNum (const char *str)
+{
+ if (str[0] == '$')
+ return ParseHex (str+1);
+ if (str[0] == '0' && str[1] == 'x')
+ return ParseHex (str+2);
+ return atol (str);
+}
+
+
+
+/*
+============================================================================
+
+ BYTE ORDER FUNCTIONS
+
+============================================================================
+*/
+
+#ifdef _SGI_SOURCE
+#define __BIG_ENDIAN__
+#endif
+
+#ifdef __BIG_ENDIAN__
+
+short LittleShort (short l)
+{
+ byte b1,b2;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+
+ return (b1<<8) + b2;
+}
+
+short BigShort (short l)
+{
+ return l;
+}
+
+
+int LittleLong (int l)
+{
+ byte b1,b2,b3,b4;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+ b3 = (l>>16)&255;
+ b4 = (l>>24)&255;
+
+ return ((int)b1<<24) + ((int)b2<<16) + ((int)b3<<8) + b4;
+}
+
+int BigLong (int l)
+{
+ return l;
+}
+
+
+float LittleFloat (float l)
+{
+ union {byte b[4]; float f;} in, out;
+
+ in.f = l;
+ out.b[0] = in.b[3];
+ out.b[1] = in.b[2];
+ out.b[2] = in.b[1];
+ out.b[3] = in.b[0];
+
+ return out.f;
+}
+
+float BigFloat (float l)
+{
+ return l;
+}
+
+
+#else
+
+
+short BigShort (short l)
+{
+ byte b1,b2;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+
+ return (b1<<8) + b2;
+}
+
+short LittleShort (short l)
+{
+ return l;
+}
+
+
+int BigLong (int l)
+{
+ byte b1,b2,b3,b4;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+ b3 = (l>>16)&255;
+ b4 = (l>>24)&255;
+
+ return ((int)b1<<24) + ((int)b2<<16) + ((int)b3<<8) + b4;
+}
+
+int LittleLong (int l)
+{
+ return l;
+}
+
+float BigFloat (float l)
+{
+ union {byte b[4]; float f;} in, out;
+
+ in.f = l;
+ out.b[0] = in.b[3];
+ out.b[1] = in.b[2];
+ out.b[2] = in.b[1];
+ out.b[3] = in.b[0];
+
+ return out.f;
+}
+
+float LittleFloat (float l)
+{
+ return l;
+}
+
+
+#endif
+
+
+//=======================================================
+
+
+// FIXME: byte swap?
+
+// this is a 16 bit, non-reflected CRC using the polynomial 0x1021
+// and the initial and final xor values shown below... in other words, the
+// CCITT standard CRC used by XMODEM
+
+#define CRC_INIT_VALUE 0xffff
+#define CRC_XOR_VALUE 0x0000
+
+static unsigned short crctable[256] =
+{
+ 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
+ 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
+ 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
+ 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
+ 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
+ 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
+ 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
+ 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
+ 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
+ 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
+ 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
+ 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
+ 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
+ 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
+ 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
+ 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
+ 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
+ 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
+ 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
+ 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
+ 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
+ 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
+ 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
+ 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
+ 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
+ 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
+ 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
+ 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
+ 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
+ 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
+ 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
+ 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0
+};
+
+void CRC_Init(unsigned short *crcvalue)
+{
+ *crcvalue = CRC_INIT_VALUE;
+}
+
+void CRC_ProcessByte(unsigned short *crcvalue, byte data)
+{
+ *crcvalue = (*crcvalue << 8) ^ crctable[(*crcvalue >> 8) ^ data];
+}
+
+unsigned short CRC_Value(unsigned short crcvalue)
+{
+ return crcvalue ^ CRC_XOR_VALUE;
+}
+//=============================================================================
+
+/*
+============
+CreatePath
+============
+*/
+void CreatePath (const char *path)
+{
+ const char *ofs;
+ char c;
+ char dir[1024];
+
+#ifdef _WIN32
+ int olddrive = -1;
+
+ if ( path[1] == ':' )
+ {
+ olddrive = _getdrive();
+ _chdrive( toupper( path[0] ) - 'A' + 1 );
+ }
+#endif
+
+ if (path[1] == ':')
+ path += 2;
+
+ for (ofs = path+1 ; *ofs ; ofs++)
+ {
+ c = *ofs;
+ if (c == '/' || c == '\\')
+ { // create the directory
+ memcpy( dir, path, ofs - path );
+ dir[ ofs - path ] = 0;
+ Q_mkdir( dir );
+ }
+ }
+
+#ifdef _WIN32
+ if ( olddrive != -1 )
+ {
+ _chdrive( olddrive );
+ }
+#endif
+}
+
+
+/*
+============
+QCopyFile
+
+ Used to archive source files
+============
+*/
+void QCopyFile (const char *from, const char *to)
+{
+ void *buffer;
+ int length;
+
+ length = LoadFile (from, &buffer);
+ CreatePath (to);
+ SaveFile (to, buffer, length);
+ free (buffer);
+}
diff --git a/common/cmdlib.h b/common/cmdlib.h
new file mode 100755
index 0000000..68d211d
--- /dev/null
+++ b/common/cmdlib.h
@@ -0,0 +1,160 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// cmdlib.h
+
+#ifndef __CMDLIB__
+#define __CMDLIB__
+
+#ifdef _WIN32
+#pragma warning(disable : 4244) // MIPS
+#pragma warning(disable : 4136) // X86
+#pragma warning(disable : 4051) // ALPHA
+
+#pragma warning(disable : 4018) // signed/unsigned mismatch
+#pragma warning(disable : 4305) // truncate from double to float
+
+#pragma check_stack(off)
+
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <ctype.h>
+#include <time.h>
+#include <stdarg.h>
+
+#ifdef _WIN32
+
+#pragma intrinsic( memset, memcpy )
+
+#endif
+
+#ifndef __BYTEBOOL__
+#define __BYTEBOOL__
+typedef enum { qfalse, qtrue } qboolean;
+typedef unsigned char byte;
+#endif
+
+#define MAX_OS_PATH 1024
+#define MEM_BLOCKSIZE 4096
+
+// the dec offsetof macro doesnt work very well...
+#define myoffsetof(type,identifier) ((size_t)&((type *)0)->identifier)
+
+
+// set these before calling CheckParm
+extern int myargc;
+extern char **myargv;
+
+char *strupr (char *in);
+char *strlower (char *in);
+int Q_strncasecmp( const char *s1, const char *s2, int n );
+int Q_stricmp( const char *s1, const char *s2 );
+void Q_getwd( char *out );
+
+int Q_filelength (FILE *f);
+int FileTime( const char *path );
+
+void Q_mkdir( const char *path );
+
+extern char qdir[1024];
+extern char gamedir[1024];
+extern char writedir[1024];
+void SetQdirFromPath( const char *path );
+char *ExpandArg( const char *path ); // from cmd line
+char *ExpandPath( const char *path ); // from scripts
+char *ExpandGamePath (const char *path);
+char *ExpandPathAndArchive( const char *path );
+
+
+double I_FloatTime( void );
+
+void Error( const char *error, ... );
+int CheckParm( const char *check );
+
+FILE *SafeOpenWrite( const char *filename );
+FILE *SafeOpenRead( const char *filename );
+void SafeRead (FILE *f, void *buffer, int count);
+void SafeWrite (FILE *f, const void *buffer, int count);
+
+int LoadFile( const char *filename, void **bufferptr );
+int LoadFileBlock( const char *filename, void **bufferptr );
+int TryLoadFile( const char *filename, void **bufferptr );
+void SaveFile( const char *filename, const void *buffer, int count );
+qboolean FileExists( const char *filename );
+
+void DefaultExtension( char *path, const char *extension );
+void DefaultPath( char *path, const char *basepath );
+void StripFilename( char *path );
+void StripExtension( char *path );
+
+void ExtractFilePath( const char *path, char *dest );
+void ExtractFileBase( const char *path, char *dest );
+void ExtractFileExtension( const char *path, char *dest );
+
+int ParseNum (const char *str);
+
+short BigShort (short l);
+short LittleShort (short l);
+int BigLong (int l);
+int LittleLong (int l);
+float BigFloat (float l);
+float LittleFloat (float l);
+
+
+char *COM_Parse (char *data);
+
+extern char com_token[1024];
+extern qboolean com_eof;
+
+char *copystring(const char *s);
+
+
+void CRC_Init(unsigned short *crcvalue);
+void CRC_ProcessByte(unsigned short *crcvalue, byte data);
+unsigned short CRC_Value(unsigned short crcvalue);
+
+void CreatePath( const char *path );
+void QCopyFile( const char *from, const char *to );
+
+extern qboolean archive;
+extern char archivedir[1024];
+
+
+extern qboolean verbose;
+void qprintf( const char *format, ... );
+void _printf( const char *format, ... );
+
+void ExpandWildcards( int *argc, char ***argv );
+
+
+// for compression routines
+typedef struct
+{
+ void *data;
+ int count, width, height;
+} cblock_t;
+
+
+#endif
diff --git a/common/imagelib.c b/common/imagelib.c
new file mode 100755
index 0000000..d59c2d0
--- /dev/null
+++ b/common/imagelib.c
@@ -0,0 +1,1164 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// imagelib.c
+
+#include "cmdlib.h"
+#include "imagelib.h"
+
+
+int fgetLittleShort (FILE *f)
+{
+ byte b1, b2;
+
+ b1 = fgetc(f);
+ b2 = fgetc(f);
+
+ return (short)(b1 + b2*256);
+}
+
+int fgetLittleLong (FILE *f)
+{
+ byte b1, b2, b3, b4;
+
+ b1 = fgetc(f);
+ b2 = fgetc(f);
+ b3 = fgetc(f);
+ b4 = fgetc(f);
+
+ return b1 + (b2<<8) + (b3<<16) + (b4<<24);
+}
+
+
+
+/*
+============================================================================
+
+ LBM STUFF
+
+============================================================================
+*/
+
+
+typedef unsigned char UBYTE;
+//conflicts with windows typedef short WORD;
+typedef unsigned short UWORD;
+typedef long LONG;
+
+typedef enum
+{
+ ms_none,
+ ms_mask,
+ ms_transcolor,
+ ms_lasso
+} mask_t;
+
+typedef enum
+{
+ cm_none,
+ cm_rle1
+} compress_t;
+
+typedef struct
+{
+ UWORD w,h;
+ short x,y;
+ UBYTE nPlanes;
+ UBYTE masking;
+ UBYTE compression;
+ UBYTE pad1;
+ UWORD transparentColor;
+ UBYTE xAspect,yAspect;
+ short pageWidth,pageHeight;
+} bmhd_t;
+
+extern bmhd_t bmhd; // will be in native byte order
+
+
+
+#define FORMID ('F'+('O'<<8)+((int)'R'<<16)+((int)'M'<<24))
+#define ILBMID ('I'+('L'<<8)+((int)'B'<<16)+((int)'M'<<24))
+#define PBMID ('P'+('B'<<8)+((int)'M'<<16)+((int)' '<<24))
+#define BMHDID ('B'+('M'<<8)+((int)'H'<<16)+((int)'D'<<24))
+#define BODYID ('B'+('O'<<8)+((int)'D'<<16)+((int)'Y'<<24))
+#define CMAPID ('C'+('M'<<8)+((int)'A'<<16)+((int)'P'<<24))
+
+
+bmhd_t bmhd;
+
+int Align (int l)
+{
+ if (l&1)
+ return l+1;
+ return l;
+}
+
+
+
+/*
+================
+LBMRLEdecompress
+
+Source must be evenly aligned!
+================
+*/
+byte *LBMRLEDecompress (byte *source,byte *unpacked, int bpwidth)
+{
+ int count;
+ byte b,rept;
+
+ count = 0;
+
+ do
+ {
+ rept = *source++;
+
+ if (rept > 0x80)
+ {
+ rept = (rept^0xff)+2;
+ b = *source++;
+ memset(unpacked,b,rept);
+ unpacked += rept;
+ }
+ else if (rept < 0x80)
+ {
+ rept++;
+ memcpy(unpacked,source,rept);
+ unpacked += rept;
+ source += rept;
+ }
+ else
+ rept = 0; // rept of 0x80 is NOP
+
+ count += rept;
+
+ } while (count<bpwidth);
+
+ if (count>bpwidth)
+ Error ("Decompression exceeded width!\n");
+
+
+ return source;
+}
+
+
+/*
+=================
+LoadLBM
+=================
+*/
+void LoadLBM (const char *filename, byte **picture, byte **palette)
+{
+ byte *LBMbuffer, *picbuffer, *cmapbuffer;
+ int y;
+ byte *LBM_P, *LBMEND_P;
+ byte *pic_p;
+ byte *body_p;
+
+ int formtype,formlength;
+ int chunktype,chunklength;
+
+// qiet compiler warnings
+ picbuffer = NULL;
+ cmapbuffer = NULL;
+
+//
+// load the LBM
+//
+ LoadFile (filename, (void **)&LBMbuffer);
+
+//
+// parse the LBM header
+//
+ LBM_P = LBMbuffer;
+ if ( *(int *)LBMbuffer != LittleLong(FORMID) )
+ Error ("No FORM ID at start of file!\n");
+
+ LBM_P += 4;
+ formlength = BigLong( *(int *)LBM_P );
+ LBM_P += 4;
+ LBMEND_P = LBM_P + Align(formlength);
+
+ formtype = LittleLong(*(int *)LBM_P);
+
+ if (formtype != ILBMID && formtype != PBMID)
+ Error ("Unrecognized form type: %c%c%c%c\n", formtype&0xff
+ ,(formtype>>8)&0xff,(formtype>>16)&0xff,(formtype>>24)&0xff);
+
+ LBM_P += 4;
+
+//
+// parse chunks
+//
+
+ while (LBM_P < LBMEND_P)
+ {
+ chunktype = LBM_P[0] + (LBM_P[1]<<8) + (LBM_P[2]<<16) + (LBM_P[3]<<24);
+ LBM_P += 4;
+ chunklength = LBM_P[3] + (LBM_P[2]<<8) + (LBM_P[1]<<16) + (LBM_P[0]<<24);
+ LBM_P += 4;
+
+ switch ( chunktype )
+ {
+ case BMHDID:
+ memcpy (&bmhd,LBM_P,sizeof(bmhd));
+ bmhd.w = BigShort(bmhd.w);
+ bmhd.h = BigShort(bmhd.h);
+ bmhd.x = BigShort(bmhd.x);
+ bmhd.y = BigShort(bmhd.y);
+ bmhd.pageWidth = BigShort(bmhd.pageWidth);
+ bmhd.pageHeight = BigShort(bmhd.pageHeight);
+ break;
+
+ case CMAPID:
+ cmapbuffer = malloc (768);
+ memset (cmapbuffer, 0, 768);
+ memcpy (cmapbuffer, LBM_P, chunklength);
+ break;
+
+ case BODYID:
+ body_p = LBM_P;
+
+ pic_p = picbuffer = malloc (bmhd.w*bmhd.h);
+ if (formtype == PBMID)
+ {
+ //
+ // unpack PBM
+ //
+ for (y=0 ; y<bmhd.h ; y++, pic_p += bmhd.w)
+ {
+ if (bmhd.compression == cm_rle1)
+ body_p = LBMRLEDecompress ((byte *)body_p
+ , pic_p , bmhd.w);
+ else if (bmhd.compression == cm_none)
+ {
+ memcpy (pic_p,body_p,bmhd.w);
+ body_p += Align(bmhd.w);
+ }
+ }
+
+ }
+ else
+ {
+ //
+ // unpack ILBM
+ //
+ Error ("%s is an interlaced LBM, not packed", filename);
+ }
+ break;
+ }
+
+ LBM_P += Align(chunklength);
+ }
+
+ free (LBMbuffer);
+
+ *picture = picbuffer;
+
+ if (palette)
+ *palette = cmapbuffer;
+}
+
+
+/*
+============================================================================
+
+ WRITE LBM
+
+============================================================================
+*/
+
+/*
+==============
+WriteLBMfile
+==============
+*/
+void WriteLBMfile (const char *filename, byte *data,
+ int width, int height, byte *palette)
+{
+ byte *lbm, *lbmptr;
+ int *formlength, *bmhdlength, *cmaplength, *bodylength;
+ int length;
+ bmhd_t basebmhd;
+
+ lbm = lbmptr = malloc (width*height+1000);
+
+//
+// start FORM
+//
+ *lbmptr++ = 'F';
+ *lbmptr++ = 'O';
+ *lbmptr++ = 'R';
+ *lbmptr++ = 'M';
+
+ formlength = (int*)lbmptr;
+ lbmptr+=4; // leave space for length
+
+ *lbmptr++ = 'P';
+ *lbmptr++ = 'B';
+ *lbmptr++ = 'M';
+ *lbmptr++ = ' ';
+
+//
+// write BMHD
+//
+ *lbmptr++ = 'B';
+ *lbmptr++ = 'M';
+ *lbmptr++ = 'H';
+ *lbmptr++ = 'D';
+
+ bmhdlength = (int *)lbmptr;
+ lbmptr+=4; // leave space for length
+
+ memset (&basebmhd,0,sizeof(basebmhd));
+ basebmhd.w = BigShort((short)width);
+ basebmhd.h = BigShort((short)height);
+ basebmhd.nPlanes = BigShort(8);
+ basebmhd.xAspect = BigShort(5);
+ basebmhd.yAspect = BigShort(6);
+ basebmhd.pageWidth = BigShort((short)width);
+ basebmhd.pageHeight = BigShort((short)height);
+
+ memcpy (lbmptr,&basebmhd,sizeof(basebmhd));
+ lbmptr += sizeof(basebmhd);
+
+ length = lbmptr-(byte *)bmhdlength-4;
+ *bmhdlength = BigLong(length);
+ if (length&1)
+ *lbmptr++ = 0; // pad chunk to even offset
+
+//
+// write CMAP
+//
+ *lbmptr++ = 'C';
+ *lbmptr++ = 'M';
+ *lbmptr++ = 'A';
+ *lbmptr++ = 'P';
+
+ cmaplength = (int *)lbmptr;
+ lbmptr+=4; // leave space for length
+
+ memcpy (lbmptr,palette,768);
+ lbmptr += 768;
+
+ length = lbmptr-(byte *)cmaplength-4;
+ *cmaplength = BigLong(length);
+ if (length&1)
+ *lbmptr++ = 0; // pad chunk to even offset
+
+//
+// write BODY
+//
+ *lbmptr++ = 'B';
+ *lbmptr++ = 'O';
+ *lbmptr++ = 'D';
+ *lbmptr++ = 'Y';
+
+ bodylength = (int *)lbmptr;
+ lbmptr+=4; // leave space for length
+
+ memcpy (lbmptr,data,width*height);
+ lbmptr += width*height;
+
+ length = lbmptr-(byte *)bodylength-4;
+ *bodylength = BigLong(length);
+ if (length&1)
+ *lbmptr++ = 0; // pad chunk to even offset
+
+//
+// done
+//
+ length = lbmptr-(byte *)formlength-4;
+ *formlength = BigLong(length);
+ if (length&1)
+ *lbmptr++ = 0; // pad chunk to even offset
+
+//
+// write output file
+//
+ SaveFile (filename, lbm, lbmptr-lbm);
+ free (lbm);
+}
+
+
+/*
+============================================================================
+
+LOAD PCX
+
+============================================================================
+*/
+
+typedef struct
+{
+ char manufacturer;
+ char version;
+ char encoding;
+ char bits_per_pixel;
+ unsigned short xmin,ymin,xmax,ymax;
+ unsigned short hres,vres;
+ unsigned char palette[48];
+ char reserved;
+ char color_planes;
+ unsigned short bytes_per_line;
+ unsigned short palette_type;
+ char filler[58];
+ unsigned char data; // unbounded
+} pcx_t;
+
+
+/*
+==============
+LoadPCX
+==============
+*/
+void LoadPCX (const char *filename, byte **pic, byte **palette, int *width, int *height)
+{
+ byte *raw;
+ pcx_t *pcx;
+ int x, y;
+ int len;
+ int dataByte, runLength;
+ byte *out, *pix;
+
+ //
+ // load the file
+ //
+ len = LoadFile (filename, (void **)&raw);
+
+ //
+ // parse the PCX file
+ //
+ pcx = (pcx_t *)raw;
+ raw = &pcx->data;
+
+ pcx->xmin = LittleShort(pcx->xmin);
+ pcx->ymin = LittleShort(pcx->ymin);
+ pcx->xmax = LittleShort(pcx->xmax);
+ pcx->ymax = LittleShort(pcx->ymax);
+ pcx->hres = LittleShort(pcx->hres);
+ pcx->vres = LittleShort(pcx->vres);
+ pcx->bytes_per_line = LittleShort(pcx->bytes_per_line);
+ pcx->palette_type = LittleShort(pcx->palette_type);
+
+ if (pcx->manufacturer != 0x0a
+ || pcx->version != 5
+ || pcx->encoding != 1
+ || pcx->bits_per_pixel != 8
+ || pcx->xmax >= 640
+ || pcx->ymax >= 480)
+ Error ("Bad pcx file %s", filename);
+
+ if (palette)
+ {
+ *palette = malloc(768);
+ memcpy (*palette, (byte *)pcx + len - 768, 768);
+ }
+
+ if (width)
+ *width = pcx->xmax+1;
+ if (height)
+ *height = pcx->ymax+1;
+
+ if (!pic)
+ return;
+
+ out = malloc ( (pcx->ymax+1) * (pcx->xmax+1) );
+ if (!out)
+ Error ("Skin_Cache: couldn't allocate");
+
+ *pic = out;
+
+ pix = out;
+
+ for (y=0 ; y<=pcx->ymax ; y++, pix += pcx->xmax+1)
+ {
+ for (x=0 ; x<=pcx->xmax ; )
+ {
+ dataByte = *raw++;
+
+ if((dataByte & 0xC0) == 0xC0)
+ {
+ runLength = dataByte & 0x3F;
+ dataByte = *raw++;
+ }
+ else
+ runLength = 1;
+
+ // FIXME: this shouldn't happen, but it does. Are we decoding the file wrong?
+ // Truncate runLength so we don't overrun the end of the buffer
+ if ( ( y == pcx->ymax ) && ( x + runLength > pcx->xmax + 1 ) ) {
+ runLength = pcx->xmax - x + 1;
+ }
+
+ while(runLength-- > 0)
+ pix[x++] = dataByte;
+ }
+
+ }
+
+ if ( raw - (byte *)pcx > len)
+ Error ("PCX file %s was malformed", filename);
+
+ free (pcx);
+}
+
+/*
+==============
+WritePCXfile
+==============
+*/
+void WritePCXfile (const char *filename, byte *data,
+ int width, int height, byte *palette)
+{
+ int i, j, length;
+ pcx_t *pcx;
+ byte *pack;
+
+ pcx = malloc (width*height*2+1000);
+ memset (pcx, 0, sizeof(*pcx));
+
+ pcx->manufacturer = 0x0a; // PCX id
+ pcx->version = 5; // 256 color
+ pcx->encoding = 1; // uncompressed
+ pcx->bits_per_pixel = 8; // 256 color
+ pcx->xmin = 0;
+ pcx->ymin = 0;
+ pcx->xmax = LittleShort((short)(width-1));
+ pcx->ymax = LittleShort((short)(height-1));
+ pcx->hres = LittleShort((short)width);
+ pcx->vres = LittleShort((short)height);
+ pcx->color_planes = 1; // chunky image
+ pcx->bytes_per_line = LittleShort((short)width);
+ pcx->palette_type = LittleShort(1); // not a grey scale
+
+ // pack the image
+ pack = &pcx->data;
+
+ for (i=0 ; i<height ; i++)
+ {
+ for (j=0 ; j<width ; j++)
+ {
+ if ( (*data & 0xc0) != 0xc0)
+ *pack++ = *data++;
+ else
+ {
+ *pack++ = 0xc1;
+ *pack++ = *data++;
+ }
+ }
+ }
+
+ // write the palette
+ *pack++ = 0x0c; // palette ID byte
+ for (i=0 ; i<768 ; i++)
+ *pack++ = *palette++;
+
+// write output file
+ length = pack - (byte *)pcx;
+ SaveFile (filename, pcx, length);
+
+ free (pcx);
+}
+
+/*
+============================================================================
+
+LOAD BMP
+
+============================================================================
+*/
+
+
+/*
+
+// we can't just use these structures, because
+// compiler structure alignment will not be portable
+// on this unaligned stuff
+
+typedef struct tagBITMAPFILEHEADER { // bmfh
+ WORD bfType; // BM
+ DWORD bfSize;
+ WORD bfReserved1;
+ WORD bfReserved2;
+ DWORD bfOffBits;
+} BITMAPFILEHEADER;
+
+typedef struct tagBITMAPINFOHEADER{ // bmih
+ DWORD biSize;
+ LONG biWidth;
+ LONG biHeight;
+ WORD biPlanes;
+ WORD biBitCount
+ DWORD biCompression;
+ DWORD biSizeImage;
+ LONG biXPelsPerMeter;
+ LONG biYPelsPerMeter;
+ DWORD biClrUsed;
+ DWORD biClrImportant;
+} BITMAPINFOHEADER;
+
+typedef struct tagBITMAPINFO { // bmi
+ BITMAPINFOHEADER bmiHeader;
+ RGBQUAD bmiColors[1];
+} BITMAPINFO;
+
+typedef struct tagBITMAPCOREHEADER { // bmch
+ DWORD bcSize;
+ WORD bcWidth;
+ WORD bcHeight;
+ WORD bcPlanes;
+ WORD bcBitCount;
+} BITMAPCOREHEADER;
+
+typedef struct _BITMAPCOREINFO { // bmci
+ BITMAPCOREHEADER bmciHeader;
+ RGBTRIPLE bmciColors[1];
+} BITMAPCOREINFO;
+
+*/
+
+/*
+==============
+LoadBMP
+==============
+*/
+void LoadBMP (const char *filename, byte **pic, byte **palette, int *width, int *height)
+{
+ byte *out;
+ FILE *fin;
+ int i;
+ int bfSize;
+ int bfOffBits;
+ int structSize;
+ int bcWidth;
+ int bcHeight;
+ int bcPlanes;
+ int bcBitCount;
+ byte bcPalette[1024];
+ qboolean flipped;
+
+ fin = fopen (filename, "rb");
+ if (!fin) {
+ Error ("Couldn't read %s", filename);
+ }
+
+ i = fgetLittleShort (fin);
+ if (i != 'B' + ('M'<<8) ) {
+ Error ("%s is not a bmp file", filename);
+ }
+
+ bfSize = fgetLittleLong (fin);
+ fgetLittleShort(fin);
+ fgetLittleShort(fin);
+ bfOffBits = fgetLittleLong (fin);
+
+ // the size will tell us if it is a
+ // bitmapinfo or a bitmapcore
+ structSize = fgetLittleLong (fin);
+ if (structSize == 40) {
+ // bitmapinfo
+ bcWidth = fgetLittleLong(fin);
+ bcHeight= fgetLittleLong(fin);
+ bcPlanes = fgetLittleShort(fin);
+ bcBitCount = fgetLittleShort(fin);
+
+ fseek (fin, 24, SEEK_CUR);
+
+ if (palette) {
+ fread (bcPalette, 1, 1024, fin);
+ *palette = malloc(768);
+
+ for (i = 0 ; i < 256 ; i++) {
+ (*palette)[i * 3 + 0] = bcPalette[i * 4 + 2];
+ (*palette)[i * 3 + 1] = bcPalette[i * 4 + 1];
+ (*palette)[i * 3 + 2] = bcPalette[i * 4 + 0];
+ }
+ }
+ } else if (structSize == 12) {
+ // bitmapcore
+ bcWidth = fgetLittleShort(fin);
+ bcHeight= fgetLittleShort(fin);
+ bcPlanes = fgetLittleShort(fin);
+ bcBitCount = fgetLittleShort(fin);
+
+ if (palette) {
+ fread (bcPalette, 1, 768, fin);
+ *palette = malloc(768);
+
+ for (i = 0 ; i < 256 ; i++) {
+ (*palette)[i * 3 + 0] = bcPalette[i * 3 + 2];
+ (*palette)[i * 3 + 1] = bcPalette[i * 3 + 1];
+ (*palette)[i * 3 + 2] = bcPalette[i * 3 + 0];
+ }
+ }
+ } else {
+ Error ("%s had strange struct size", filename);
+ }
+
+ if (bcPlanes != 1) {
+ Error ("%s was not a single plane image", filename);
+ }
+
+ if (bcBitCount != 8) {
+ Error ("%s was not an 8 bit image", filename);
+ }
+
+ if (bcHeight < 0) {
+ bcHeight = -bcHeight;
+ flipped = qtrue;
+ } else {
+ flipped = qfalse;
+ }
+
+ if (width)
+ *width = bcWidth;
+ if (height)
+ *height = bcHeight;
+
+ if (!pic) {
+ fclose (fin);
+ return;
+ }
+
+ out = malloc ( bcWidth * bcHeight );
+ *pic = out;
+ fseek (fin, bfOffBits, SEEK_SET);
+
+ if (flipped) {
+ for (i = 0 ; i < bcHeight ; i++) {
+ fread (out + bcWidth * (bcHeight - 1 - i), 1, bcWidth, fin);
+ }
+ } else {
+ fread (out, 1, bcWidth*bcHeight, fin);
+ }
+
+ fclose (fin);
+}
+
+
+/*
+============================================================================
+
+LOAD IMAGE
+
+============================================================================
+*/
+
+/*
+==============
+Load256Image
+
+Will load either an lbm or pcx, depending on extension.
+Any of the return pointers can be NULL if you don't want them.
+==============
+*/
+void Load256Image (const char *name, byte **pixels, byte **palette,
+ int *width, int *height)
+{
+ char ext[128];
+
+ ExtractFileExtension (name, ext);
+ if (!Q_stricmp (ext, "lbm"))
+ {
+ LoadLBM (name, pixels, palette);
+ if (width)
+ *width = bmhd.w;
+ if (height)
+ *height = bmhd.h;
+ }
+ else if (!Q_stricmp (ext, "pcx"))
+ {
+ LoadPCX (name, pixels, palette, width, height);
+ }
+ else if (!Q_stricmp (ext, "bmp"))
+ {
+ LoadBMP (name, pixels, palette, width, height);
+ }
+ else
+ Error ("%s doesn't have a known image extension", name);
+}
+
+
+/*
+==============
+Save256Image
+
+Will save either an lbm or pcx, depending on extension.
+==============
+*/
+void Save256Image (const char *name, byte *pixels, byte *palette,
+ int width, int height)
+{
+ char ext[128];
+
+ ExtractFileExtension (name, ext);
+ if (!Q_stricmp (ext, "lbm"))
+ {
+ WriteLBMfile (name, pixels, width, height, palette);
+ }
+ else if (!Q_stricmp (ext, "pcx"))
+ {
+ WritePCXfile (name, pixels, width, height, palette);
+ }
+ else
+ Error ("%s doesn't have a known image extension", name);
+}
+
+
+
+
+/*
+============================================================================
+
+TARGA IMAGE
+
+============================================================================
+*/
+
+typedef struct _TargaHeader {
+ unsigned char id_length, colormap_type, image_type;
+ unsigned short colormap_index, colormap_length;
+ unsigned char colormap_size;
+ unsigned short x_origin, y_origin, width, height;
+ unsigned char pixel_size, attributes;
+} TargaHeader;
+
+/*
+=============
+LoadTGABuffer
+=============
+*/
+void LoadTGABuffer ( byte *buffer, byte **pic, int *width, int *height)
+{
+ int columns, rows, numPixels;
+ byte *pixbuf;
+ int row, column;
+ byte *buf_p;
+ TargaHeader targa_header;
+ byte *targa_rgba;
+
+ *pic = NULL;
+
+ buf_p = buffer;
+
+ targa_header.id_length = *buf_p++;
+ targa_header.colormap_type = *buf_p++;
+ targa_header.image_type = *buf_p++;
+
+ targa_header.colormap_index = LittleShort ( *(short *)buf_p );
+ buf_p += 2;
+ targa_header.colormap_length = LittleShort ( *(short *)buf_p );
+ buf_p += 2;
+ targa_header.colormap_size = *buf_p++;
+ targa_header.x_origin = LittleShort ( *(short *)buf_p );
+ buf_p += 2;
+ targa_header.y_origin = LittleShort ( *(short *)buf_p );
+ buf_p += 2;
+ targa_header.width = LittleShort ( *(short *)buf_p );
+ buf_p += 2;
+ targa_header.height = LittleShort ( *(short *)buf_p );
+ buf_p += 2;
+ targa_header.pixel_size = *buf_p++;
+ targa_header.attributes = *buf_p++;
+
+ if (targa_header.image_type!=2
+ && targa_header.image_type!=10
+ && targa_header.image_type != 3 )
+ {
+ Error("LoadTGA: Only type 2 (RGB), 3 (gray), and 10 (RGB) TGA images supported\n");
+ }
+
+ if ( targa_header.colormap_type != 0 )
+ {
+ Error("LoadTGA: colormaps not supported\n" );
+ }
+
+ if ( ( targa_header.pixel_size != 32 && targa_header.pixel_size != 24 ) && targa_header.image_type != 3 )
+ {
+ Error("LoadTGA: Only 32 or 24 bit images supported (no colormaps)\n");
+ }
+
+ columns = targa_header.width;
+ rows = targa_header.height;
+ numPixels = columns * rows;
+
+ if (width)
+ *width = columns;
+ if (height)
+ *height = rows;
+
+ targa_rgba = malloc (numPixels*4);
+ *pic = targa_rgba;
+
+ if (targa_header.id_length != 0)
+ buf_p += targa_header.id_length; // skip TARGA image comment
+
+ if ( targa_header.image_type==2 || targa_header.image_type == 3 )
+ {
+ // Uncompressed RGB or gray scale image
+ for(row=rows-1; row>=0; row--)
+ {
+ pixbuf = targa_rgba + row*columns*4;
+ for(column=0; column<columns; column++)
+ {
+ unsigned char red,green,blue,alphabyte;
+ switch (targa_header.pixel_size)
+ {
+
+ case 8:
+ blue = *buf_p++;
+ green = blue;
+ red = blue;
+ *pixbuf++ = red;
+ *pixbuf++ = green;
+ *pixbuf++ = blue;
+ *pixbuf++ = 255;
+ break;
+
+ case 24:
+ blue = *buf_p++;
+ green = *buf_p++;
+ red = *buf_p++;
+ *pixbuf++ = red;
+ *pixbuf++ = green;
+ *pixbuf++ = blue;
+ *pixbuf++ = 255;
+ break;
+ case 32:
+ blue = *buf_p++;
+ green = *buf_p++;
+ red = *buf_p++;
+ alphabyte = *buf_p++;
+ *pixbuf++ = red;
+ *pixbuf++ = green;
+ *pixbuf++ = blue;
+ *pixbuf++ = alphabyte;
+ break;
+ default:
+ //Error("LoadTGA: illegal pixel_size '%d' in file '%s'\n", targa_header.pixel_size, name );
+ break;
+ }
+ }
+ }
+ }
+ else if (targa_header.image_type==10) { // Runlength encoded RGB images
+ unsigned char red,green,blue,alphabyte,packetHeader,packetSize,j;
+
+ red = 0;
+ green = 0;
+ blue = 0;
+ alphabyte = 0xff;
+
+ for(row=rows-1; row>=0; row--) {
+ pixbuf = targa_rgba + row*columns*4;
+ for(column=0; column<columns; ) {
+ packetHeader= *buf_p++;
+ packetSize = 1 + (packetHeader & 0x7f);
+ if (packetHeader & 0x80) { // run-length packet
+ switch (targa_header.pixel_size) {
+ case 24:
+ blue = *buf_p++;
+ green = *buf_p++;
+ red = *buf_p++;
+ alphabyte = 255;
+ break;
+ case 32:
+ blue = *buf_p++;
+ green = *buf_p++;
+ red = *buf_p++;
+ alphabyte = *buf_p++;
+ break;
+ default:
+ //Error("LoadTGA: illegal pixel_size '%d' in file '%s'\n", targa_header.pixel_size, name );
+ break;
+ }
+
+ for(j=0;j<packetSize;j++) {
+ *pixbuf++=red;
+ *pixbuf++=green;
+ *pixbuf++=blue;
+ *pixbuf++=alphabyte;
+ column++;
+ if (column==columns) { // run spans across rows
+ column=0;
+ if (row>0)
+ row--;
+ else
+ goto breakOut;
+ pixbuf = targa_rgba + row*columns*4;
+ }
+ }
+ }
+ else { // non run-length packet
+ for(j=0;j<packetSize;j++) {
+ switch (targa_header.pixel_size) {
+ case 24:
+ blue = *buf_p++;
+ green = *buf_p++;
+ red = *buf_p++;
+ *pixbuf++ = red;
+ *pixbuf++ = green;
+ *pixbuf++ = blue;
+ *pixbuf++ = 255;
+ break;
+ case 32:
+ blue = *buf_p++;
+ green = *buf_p++;
+ red = *buf_p++;
+ alphabyte = *buf_p++;
+ *pixbuf++ = red;
+ *pixbuf++ = green;
+ *pixbuf++ = blue;
+ *pixbuf++ = alphabyte;
+ break;
+ default:
+ //Sys_Printf("LoadTGA: illegal pixel_size '%d' in file '%s'\n", targa_header.pixel_size, name );
+ break;
+ }
+ column++;
+ if (column==columns) { // pixel packet run spans across rows
+ column=0;
+ if (row>0)
+ row--;
+ else
+ goto breakOut;
+ pixbuf = targa_rgba + row*columns*4;
+ }
+ }
+ }
+ }
+ breakOut:;
+ }
+ }
+
+ //free(buffer);
+}
+
+
+
+/*
+=============
+LoadTGA
+=============
+*/
+void LoadTGA (const char *name, byte **pixels, int *width, int *height)
+{
+ byte *buffer;
+ int nLen;
+ //
+ // load the file
+ //
+ nLen = LoadFile ( ( char * ) name, (void **)&buffer);
+ if (nLen == -1)
+ {
+ Error ("Couldn't read %s", name);
+ }
+
+ LoadTGABuffer(buffer, pixels, width, height);
+
+}
+
+
+/*
+================
+WriteTGA
+================
+*/
+void WriteTGA (const char *filename, byte *data, int width, int height) {
+ byte *buffer;
+ int i;
+ int c;
+ FILE *f;
+
+ buffer = malloc(width*height*4 + 18);
+ memset (buffer, 0, 18);
+ buffer[2] = 2; // uncompressed type
+ buffer[12] = width&255;
+ buffer[13] = width>>8;
+ buffer[14] = height&255;
+ buffer[15] = height>>8;
+ buffer[16] = 32; // pixel size
+
+ // swap rgb to bgr
+ c = 18 + width * height * 4;
+ for (i=18 ; i<c ; i+=4)
+ {
+ buffer[i] = data[i-18+2]; // blue
+ buffer[i+1] = data[i-18+1]; // green
+ buffer[i+2] = data[i-18+0]; // red
+ buffer[i+3] = data[i-18+3]; // alpha
+ }
+
+ f = fopen (filename, "wb");
+ fwrite (buffer, 1, c, f);
+ fclose (f);
+
+ free (buffer);
+}
+
+/*
+============================================================================
+
+LOAD32BITIMAGE
+
+============================================================================
+*/
+
+/*
+==============
+Load32BitImage
+
+Any of the return pointers can be NULL if you don't want them.
+==============
+*/
+void Load32BitImage (const char *name, unsigned **pixels, int *width, int *height)
+{
+ char ext[128];
+ byte *palette;
+ byte *pixels8;
+ byte *pixels32;
+ int size;
+ int i;
+ int v;
+
+ ExtractFileExtension (name, ext);
+ if (!Q_stricmp (ext, "tga")) {
+ LoadTGA (name, (byte **)pixels, width, height);
+ } else {
+ Load256Image (name, &pixels8, &palette, width, height);
+ if (!pixels) {
+ return;
+ }
+ size = *width * *height;
+ pixels32 = malloc(size * 4);
+ *pixels = (unsigned *)pixels32;
+ for (i = 0 ; i < size ; i++) {
+ v = pixels8[i];
+ pixels32[i*4 + 0] = palette[ v * 3 + 0 ];
+ pixels32[i*4 + 1] = palette[ v * 3 + 1 ];
+ pixels32[i*4 + 2] = palette[ v * 3 + 2 ];
+ pixels32[i*4 + 3] = 0xff;
+ }
+ }
+}
+
+
diff --git a/common/imagelib.h b/common/imagelib.h
new file mode 100755
index 0000000..57287ec
--- /dev/null
+++ b/common/imagelib.h
@@ -0,0 +1,44 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// piclib.h
+
+
+void LoadLBM (const char *filename, byte **picture, byte **palette);
+void WriteLBMfile (const char *filename, byte *data, int width, int height
+ , byte *palette);
+void LoadPCX (const char *filename, byte **picture, byte **palette, int *width, int *height);
+void WritePCXfile (const char *filename, byte *data, int width, int height
+ , byte *palette);
+
+// loads / saves either lbm or pcx, depending on extension
+void Load256Image (const char *name, byte **pixels, byte **palette,
+ int *width, int *height);
+void Save256Image (const char *name, byte *pixels, byte *palette,
+ int width, int height);
+
+
+void LoadTGA (const char *filename, byte **pixels, int *width, int *height);
+void LoadTGABuffer ( byte *buffer, byte **pic, int *width, int *height);
+void WriteTGA (const char *filename, byte *data, int width, int height);
+
+void Load32BitImage (const char *name, unsigned **pixels, int *width, int *height);
+
diff --git a/common/l3dslib.c b/common/l3dslib.c
new file mode 100755
index 0000000..0faed60
--- /dev/null
+++ b/common/l3dslib.c
@@ -0,0 +1,300 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// l3dslib.c: library for loading triangles from an Alias triangle file
+//
+
+#include <stdio.h>
+#include "cmdlib.h"
+#include "mathlib.h"
+#include "trilib.h"
+#include "l3dslib.h"
+
+#define MAIN3DS 0x4D4D
+#define EDIT3DS 0x3D3D // this is the start of the editor config
+#define EDIT_OBJECT 0x4000
+#define OBJ_TRIMESH 0x4100
+#define TRI_VERTEXL 0x4110
+#define TRI_FACEL1 0x4120
+
+#define MAXVERTS 2000
+
+typedef struct {
+ int v[4];
+} tri;
+
+float fverts[MAXVERTS][3];
+tri tris[MAXTRIANGLES];
+
+int bytesread, level, numtris, totaltris;
+int vertsfound, trisfound;
+
+triangle_t *ptri;
+
+
+// Alias stores triangles as 3 explicit vertices in .tri files, so even though we
+// start out with a vertex pool and vertex indices for triangles, we have to convert
+// to raw, explicit triangles
+void StoreAliasTriangles (void)
+{
+ int i, j, k;
+
+ if ((totaltris + numtris) > MAXTRIANGLES)
+ Error ("Error: Too many triangles");
+
+ for (i=0; i<numtris ; i++)
+ {
+ for (j=0 ; j<3 ; j++)
+ {
+ for (k=0 ; k<3 ; k++)
+ {
+ ptri[i+totaltris].verts[j][k] = fverts[tris[i].v[j]][k];
+ }
+ }
+ }
+
+ totaltris += numtris;
+ numtris = 0;
+ vertsfound = 0;
+ trisfound = 0;
+}
+
+
+int ParseVertexL (FILE *input)
+{
+ int i, j, startbytesread, numverts;
+ unsigned short tshort;
+
+ if (vertsfound)
+ Error ("Error: Multiple vertex chunks");
+
+ vertsfound = 1;
+ startbytesread = bytesread;
+
+ if (feof(input))
+ Error ("Error: unexpected end of file");
+
+ fread(&tshort, sizeof(tshort), 1, input);
+ bytesread += sizeof(tshort);
+ numverts = (int)tshort;
+
+ if (numverts > MAXVERTS)
+ Error ("Error: Too many vertices");
+
+ for (i=0 ; i<numverts ; i++)
+ {
+ for (j=0 ; j<3 ; j++)
+ {
+ if (feof(input))
+ Error ("Error: unexpected end of file");
+
+ fread(&fverts[i][j], sizeof(float), 1, input);
+ bytesread += sizeof(float);
+ }
+ }
+
+ if (vertsfound && trisfound)
+ StoreAliasTriangles ();
+
+ return bytesread - startbytesread;
+}
+
+
+int ParseFaceL1 (FILE *input)
+{
+
+ int i, j, startbytesread;
+ unsigned short tshort;
+
+ if (trisfound)
+ Error ("Error: Multiple face chunks");
+
+ trisfound = 1;
+ startbytesread = bytesread;
+
+ if (feof(input))
+ Error ("Error: unexpected end of file");
+
+ fread(&tshort, sizeof(tshort), 1, input);
+ bytesread += sizeof(tshort);
+ numtris = (int)tshort;
+
+ if (numtris > MAXTRIANGLES)
+ Error ("Error: Too many triangles");
+
+ for (i=0 ; i<numtris ; i++)
+ {
+ for (j=0 ; j<4 ; j++)
+ {
+ if (feof(input))
+ Error ("Error: unexpected end of file");
+
+ fread(&tshort, sizeof(tshort), 1, input);
+ bytesread += sizeof(tshort);
+ tris[i].v[j] = (int)tshort;
+ }
+ }
+
+ if (vertsfound && trisfound)
+ StoreAliasTriangles ();
+
+ return bytesread - startbytesread;
+}
+
+
+int ParseChunk (FILE *input)
+{
+#define BLOCK_SIZE 4096
+ char temp[BLOCK_SIZE];
+ unsigned short type;
+ int i, length, w, t, retval;
+
+ level++;
+ retval = 0;
+
+// chunk type
+ if (feof(input))
+ Error ("Error: unexpected end of file");
+
+ fread(&type, sizeof(type), 1, input);
+ bytesread += sizeof(type);
+
+// chunk length
+ if (feof(input))
+ Error ("Error: unexpected end of file");
+
+ fread (&length, sizeof(length), 1, input);
+ bytesread += sizeof(length);
+ w = length - 6;
+
+// process chunk if we care about it, otherwise skip it
+ switch (type)
+ {
+ case TRI_VERTEXL:
+ w -= ParseVertexL (input);
+ goto ParseSubchunk;
+
+ case TRI_FACEL1:
+ w -= ParseFaceL1 (input);
+ goto ParseSubchunk;
+
+ case EDIT_OBJECT:
+ // read the name
+ i = 0;
+
+ do
+ {
+ if (feof(input))
+ Error ("Error: unexpected end of file");
+
+ fread (&temp[i], 1, 1, input);
+ i++;
+ w--;
+ bytesread++;
+ } while (temp[i-1]);
+
+ case MAIN3DS:
+ case OBJ_TRIMESH:
+ case EDIT3DS:
+ // parse through subchunks
+ParseSubchunk:
+ while (w > 0)
+ {
+ w -= ParseChunk (input);
+ }
+
+ retval = length;
+ goto Done;
+
+ default:
+ // skip other chunks
+ while (w > 0)
+ {
+ t = w;
+
+ if (t > BLOCK_SIZE)
+ t = BLOCK_SIZE;
+
+ if (feof(input))
+ Error ("Error: unexpected end of file");
+
+ fread (&temp, t, 1, input);
+ bytesread += t;
+
+ w -= t;
+ }
+
+ retval = length;
+ goto Done;
+ }
+
+Done:
+ level--;
+ return retval;
+}
+
+
+void Load3DSTriangleList (char *filename, triangle_t **pptri, int *numtriangles)
+{
+ FILE *input;
+ short int tshort;
+
+ bytesread = 0;
+ level = 0;
+ numtris = 0;
+ totaltris = 0;
+ vertsfound = 0;
+ trisfound = 0;
+
+ if ((input = fopen(filename, "rb")) == 0) {
+ fprintf(stderr,"reader: could not open file '%s'\n", filename);
+ exit(0);
+ }
+
+ fread(&tshort, sizeof(tshort), 1, input);
+
+// should only be MAIN3DS, but some files seem to start with EDIT3DS, with
+// no MAIN3DS
+ if ((tshort != MAIN3DS) && (tshort != EDIT3DS)) {
+ fprintf(stderr,"File is not a 3DS file.\n");
+ exit(0);
+ }
+
+// back to top of file so we can parse the first chunk descriptor
+ fseek(input, 0, SEEK_SET);
+
+ ptri = malloc (MAXTRIANGLES * sizeof(triangle_t));
+
+ *pptri = ptri;
+
+// parse through looking for the relevant chunk tree (MAIN3DS | EDIT3DS | EDIT_OBJECT |
+// OBJ_TRIMESH | {TRI_VERTEXL, TRI_FACEL1}) and skipping other chunks
+ ParseChunk (input);
+
+ if (vertsfound || trisfound)
+ Error ("Incomplete triangle set");
+
+ *numtriangles = totaltris;
+
+ fclose (input);
+}
+
diff --git a/common/l3dslib.h b/common/l3dslib.h
new file mode 100755
index 0000000..c98524c
--- /dev/null
+++ b/common/l3dslib.h
@@ -0,0 +1,26 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// l3dslib.h: header file for loading triangles from a 3DS triangle file
+//
+void Load3DSTriangleList (char *filename, triangle_t **pptri, int *numtriangles);
+
diff --git a/common/mathlib.c b/common/mathlib.c
new file mode 100755
index 0000000..1435024
--- /dev/null
+++ b/common/mathlib.c
@@ -0,0 +1,434 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// mathlib.c -- math primitives
+
+#include "cmdlib.h"
+#include "mathlib.h"
+
+#ifdef _WIN32
+//Improve floating-point consistency.
+//without this option weird floating point issues occur
+#pragma optimize( "p", on )
+#endif
+
+
+vec3_t vec3_origin = {0,0,0};
+
+/*
+** NormalToLatLong
+**
+** We use two byte encoded normals in some space critical applications.
+** Lat = 0 at (1,0,0) to 360 (-1,0,0), encoded in 8-bit sine table format
+** Lng = 0 at (0,0,1) to 180 (0,0,-1), encoded in 8-bit sine table format
+**
+*/
+void NormalToLatLong( const vec3_t normal, byte bytes[2] ) {
+ // check for singularities
+ if ( normal[0] == 0 && normal[1] == 0 ) {
+ if ( normal[2] > 0 ) {
+ bytes[0] = 0;
+ bytes[1] = 0; // lat = 0, long = 0
+ } else {
+ bytes[0] = 128;
+ bytes[1] = 0; // lat = 0, long = 128
+ }
+ } else {
+ int a, b;
+
+ a = RAD2DEG( atan2( normal[1], normal[0] ) ) * (255.0f / 360.0f );
+ a &= 0xff;
+
+ b = RAD2DEG( acos( normal[2] ) ) * ( 255.0f / 360.0f );
+ b &= 0xff;
+
+ bytes[0] = b; // longitude
+ bytes[1] = a; // lattitude
+ }
+}
+
+/*
+=====================
+PlaneFromPoints
+
+Returns false if the triangle is degenrate.
+The normal will point out of the clock for clockwise ordered points
+=====================
+*/
+qboolean PlaneFromPoints( vec4_t plane, const vec3_t a, const vec3_t b, const vec3_t c ) {
+ vec3_t d1, d2;
+
+ VectorSubtract( b, a, d1 );
+ VectorSubtract( c, a, d2 );
+ CrossProduct( d2, d1, plane );
+ if ( VectorNormalize( plane, plane ) == 0 ) {
+ return qfalse;
+ }
+
+ plane[3] = DotProduct( a, plane );
+ return qtrue;
+}
+
+/*
+================
+MakeNormalVectors
+
+Given a normalized forward vector, create two
+other perpendicular vectors
+================
+*/
+void MakeNormalVectors (vec3_t forward, vec3_t right, vec3_t up)
+{
+ float d;
+
+ // this rotate and negate guarantees a vector
+ // not colinear with the original
+ right[1] = -forward[0];
+ right[2] = forward[1];
+ right[0] = forward[2];
+
+ d = DotProduct (right, forward);
+ VectorMA (right, -d, forward, right);
+ VectorNormalize (right, right);
+ CrossProduct (right, forward, up);
+}
+
+
+void Vec10Copy( vec_t *in, vec_t *out ) {
+ out[0] = in[0];
+ out[1] = in[1];
+ out[2] = in[2];
+ out[3] = in[3];
+ out[4] = in[4];
+ out[5] = in[5];
+ out[6] = in[6];
+ out[7] = in[7];
+ out[8] = in[8];
+ out[9] = in[9];
+}
+
+
+void VectorRotate3x3( vec3_t v, float r[3][3], vec3_t d )
+{
+ d[0] = v[0] * r[0][0] + v[1] * r[1][0] + v[2] * r[2][0];
+ d[1] = v[0] * r[0][1] + v[1] * r[1][1] + v[2] * r[2][1];
+ d[2] = v[0] * r[0][2] + v[1] * r[1][2] + v[2] * r[2][2];
+}
+
+double VectorLength( const vec3_t v ) {
+ int i;
+ double length;
+
+ length = 0;
+ for (i=0 ; i< 3 ; i++)
+ length += v[i]*v[i];
+ length = sqrt (length); // FIXME
+
+ return length;
+}
+
+qboolean VectorCompare( const vec3_t v1, const vec3_t v2 ) {
+ int i;
+
+ for (i=0 ; i<3 ; i++)
+ if (fabs(v1[i]-v2[i]) > EQUAL_EPSILON)
+ return qfalse;
+
+ return qtrue;
+}
+
+vec_t Q_rint (vec_t in)
+{
+ return floor (in + 0.5);
+}
+
+void VectorMA( const vec3_t va, double scale, const vec3_t vb, vec3_t vc ) {
+ vc[0] = va[0] + scale*vb[0];
+ vc[1] = va[1] + scale*vb[1];
+ vc[2] = va[2] + scale*vb[2];
+}
+
+void CrossProduct( const vec3_t v1, const vec3_t v2, vec3_t cross ) {
+ cross[0] = v1[1]*v2[2] - v1[2]*v2[1];
+ cross[1] = v1[2]*v2[0] - v1[0]*v2[2];
+ cross[2] = v1[0]*v2[1] - v1[1]*v2[0];
+}
+
+vec_t _DotProduct (vec3_t v1, vec3_t v2)
+{
+ return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2];
+}
+
+void _VectorSubtract (vec3_t va, vec3_t vb, vec3_t out)
+{
+ out[0] = va[0]-vb[0];
+ out[1] = va[1]-vb[1];
+ out[2] = va[2]-vb[2];
+}
+
+void _VectorAdd (vec3_t va, vec3_t vb, vec3_t out)
+{
+ out[0] = va[0]+vb[0];
+ out[1] = va[1]+vb[1];
+ out[2] = va[2]+vb[2];
+}
+
+void _VectorCopy (vec3_t in, vec3_t out)
+{
+ out[0] = in[0];
+ out[1] = in[1];
+ out[2] = in[2];
+}
+
+void _VectorScale (vec3_t v, vec_t scale, vec3_t out)
+{
+ out[0] = v[0] * scale;
+ out[1] = v[1] * scale;
+ out[2] = v[2] * scale;
+}
+
+vec_t VectorNormalize( const vec3_t in, vec3_t out ) {
+ vec_t length, ilength;
+
+ length = sqrt (in[0]*in[0] + in[1]*in[1] + in[2]*in[2]);
+ if (length == 0)
+ {
+ VectorClear (out);
+ return 0;
+ }
+
+ ilength = 1.0/length;
+ out[0] = in[0]*ilength;
+ out[1] = in[1]*ilength;
+ out[2] = in[2]*ilength;
+
+ return length;
+}
+
+vec_t ColorNormalize( const vec3_t in, vec3_t out ) {
+ float max, scale;
+
+ max = in[0];
+ if (in[1] > max)
+ max = in[1];
+ if (in[2] > max)
+ max = in[2];
+
+ if (max == 0) {
+ out[0] = out[1] = out[2] = 1.0;
+ return 0;
+ }
+
+ scale = 1.0 / max;
+
+ VectorScale (in, scale, out);
+
+ return max;
+}
+
+
+
+void VectorInverse (vec3_t v)
+{
+ v[0] = -v[0];
+ v[1] = -v[1];
+ v[2] = -v[2];
+}
+
+void ClearBounds (vec3_t mins, vec3_t maxs)
+{
+ mins[0] = mins[1] = mins[2] = 99999;
+ maxs[0] = maxs[1] = maxs[2] = -99999;
+}
+
+void AddPointToBounds( const vec3_t v, vec3_t mins, vec3_t maxs ) {
+ int i;
+ vec_t val;
+
+ for (i=0 ; i<3 ; i++)
+ {
+ val = v[i];
+ if (val < mins[i])
+ mins[i] = val;
+ if (val > maxs[i])
+ maxs[i] = val;
+ }
+}
+
+
+/*
+=================
+PlaneTypeForNormal
+=================
+*/
+int PlaneTypeForNormal (vec3_t normal) {
+ if (normal[0] == 1.0 || normal[0] == -1.0)
+ return PLANE_X;
+ if (normal[1] == 1.0 || normal[1] == -1.0)
+ return PLANE_Y;
+ if (normal[2] == 1.0 || normal[2] == -1.0)
+ return PLANE_Z;
+
+ return PLANE_NON_AXIAL;
+}
+
+/*
+================
+MatrixMultiply
+================
+*/
+void MatrixMultiply(float in1[3][3], float in2[3][3], float out[3][3]) {
+ out[0][0] = in1[0][0] * in2[0][0] + in1[0][1] * in2[1][0] +
+ in1[0][2] * in2[2][0];
+ out[0][1] = in1[0][0] * in2[0][1] + in1[0][1] * in2[1][1] +
+ in1[0][2] * in2[2][1];
+ out[0][2] = in1[0][0] * in2[0][2] + in1[0][1] * in2[1][2] +
+ in1[0][2] * in2[2][2];
+ out[1][0] = in1[1][0] * in2[0][0] + in1[1][1] * in2[1][0] +
+ in1[1][2] * in2[2][0];
+ out[1][1] = in1[1][0] * in2[0][1] + in1[1][1] * in2[1][1] +
+ in1[1][2] * in2[2][1];
+ out[1][2] = in1[1][0] * in2[0][2] + in1[1][1] * in2[1][2] +
+ in1[1][2] * in2[2][2];
+ out[2][0] = in1[2][0] * in2[0][0] + in1[2][1] * in2[1][0] +
+ in1[2][2] * in2[2][0];
+ out[2][1] = in1[2][0] * in2[0][1] + in1[2][1] * in2[1][1] +
+ in1[2][2] * in2[2][1];
+ out[2][2] = in1[2][0] * in2[0][2] + in1[2][1] * in2[1][2] +
+ in1[2][2] * in2[2][2];
+}
+
+void ProjectPointOnPlane( vec3_t dst, const vec3_t p, const vec3_t normal )
+{
+ float d;
+ vec3_t n;
+ float inv_denom;
+
+ inv_denom = 1.0F / DotProduct( normal, normal );
+
+ d = DotProduct( normal, p ) * inv_denom;
+
+ n[0] = normal[0] * inv_denom;
+ n[1] = normal[1] * inv_denom;
+ n[2] = normal[2] * inv_denom;
+
+ dst[0] = p[0] - d * n[0];
+ dst[1] = p[1] - d * n[1];
+ dst[2] = p[2] - d * n[2];
+}
+
+/*
+** assumes "src" is normalized
+*/
+void PerpendicularVector( vec3_t dst, const vec3_t src )
+{
+ int pos;
+ int i;
+ float minelem = 1.0F;
+ vec3_t tempvec;
+
+ /*
+ ** find the smallest magnitude axially aligned vector
+ */
+ for ( pos = 0, i = 0; i < 3; i++ )
+ {
+ if ( fabs( src[i] ) < minelem )
+ {
+ pos = i;
+ minelem = fabs( src[i] );
+ }
+ }
+ tempvec[0] = tempvec[1] = tempvec[2] = 0.0F;
+ tempvec[pos] = 1.0F;
+
+ /*
+ ** project the point onto the plane defined by src
+ */
+ ProjectPointOnPlane( dst, tempvec, src );
+
+ /*
+ ** normalize the result
+ */
+ VectorNormalize( dst, dst );
+}
+
+/*
+===============
+RotatePointAroundVector
+
+This is not implemented very well...
+===============
+*/
+void RotatePointAroundVector( vec3_t dst, const vec3_t dir, const vec3_t point,
+ float degrees ) {
+ float m[3][3];
+ float im[3][3];
+ float zrot[3][3];
+ float tmpmat[3][3];
+ float rot[3][3];
+ int i;
+ vec3_t vr, vup, vf;
+ float rad;
+
+ vf[0] = dir[0];
+ vf[1] = dir[1];
+ vf[2] = dir[2];
+
+ PerpendicularVector( vr, dir );
+ CrossProduct( vr, vf, vup );
+
+ m[0][0] = vr[0];
+ m[1][0] = vr[1];
+ m[2][0] = vr[2];
+
+ m[0][1] = vup[0];
+ m[1][1] = vup[1];
+ m[2][1] = vup[2];
+
+ m[0][2] = vf[0];
+ m[1][2] = vf[1];
+ m[2][2] = vf[2];
+
+ memcpy( im, m, sizeof( im ) );
+
+ im[0][1] = m[1][0];
+ im[0][2] = m[2][0];
+ im[1][0] = m[0][1];
+ im[1][2] = m[2][1];
+ im[2][0] = m[0][2];
+ im[2][1] = m[1][2];
+
+ memset( zrot, 0, sizeof( zrot ) );
+ zrot[0][0] = zrot[1][1] = zrot[2][2] = 1.0F;
+
+ rad = DEG2RAD( degrees );
+ zrot[0][0] = cos( rad );
+ zrot[0][1] = sin( rad );
+ zrot[1][0] = -sin( rad );
+ zrot[1][1] = cos( rad );
+
+ MatrixMultiply( m, zrot, tmpmat );
+ MatrixMultiply( tmpmat, im, rot );
+
+ for ( i = 0; i < 3; i++ ) {
+ dst[i] = rot[i][0] * point[0] + rot[i][1] * point[1] + rot[i][2] * point[2];
+ }
+}
diff --git a/common/mathlib.h b/common/mathlib.h
new file mode 100755
index 0000000..7bd7158
--- /dev/null
+++ b/common/mathlib.h
@@ -0,0 +1,96 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __MATHLIB__
+#define __MATHLIB__
+
+// mathlib.h
+
+#include <math.h>
+
+#ifdef DOUBLEVEC_T
+typedef double vec_t;
+#else
+typedef float vec_t;
+#endif
+typedef vec_t vec2_t[3];
+typedef vec_t vec3_t[3];
+typedef vec_t vec4_t[4];
+
+#define SIDE_FRONT 0
+#define SIDE_ON 2
+#define SIDE_BACK 1
+#define SIDE_CROSS -2
+
+#define Q_PI 3.14159265358979323846
+#define DEG2RAD( a ) ( ( (a) * Q_PI ) / 180.0F )
+#define RAD2DEG( a ) ( ( (a) * 180.0f ) / Q_PI )
+
+extern vec3_t vec3_origin;
+
+#define EQUAL_EPSILON 0.001
+
+// plane types are used to speed some tests
+// 0-2 are axial planes
+#define PLANE_X 0
+#define PLANE_Y 1
+#define PLANE_Z 2
+#define PLANE_NON_AXIAL 3
+
+qboolean VectorCompare( const vec3_t v1, const vec3_t v2 );
+
+#define DotProduct(x,y) (x[0]*y[0]+x[1]*y[1]+x[2]*y[2])
+#define VectorSubtract(a,b,c) {c[0]=a[0]-b[0];c[1]=a[1]-b[1];c[2]=a[2]-b[2];}
+#define VectorAdd(a,b,c) {c[0]=a[0]+b[0];c[1]=a[1]+b[1];c[2]=a[2]+b[2];}
+#define VectorCopy(a,b) {b[0]=a[0];b[1]=a[1];b[2]=a[2];}
+#define VectorScale(a,b,c) {c[0]=b*a[0];c[1]=b*a[1];c[2]=b*a[2];}
+#define VectorClear(x) {x[0] = x[1] = x[2] = 0;}
+#define VectorNegate(x) {x[0]=-x[0];x[1]=-x[1];x[2]=-x[2];}
+void Vec10Copy( vec_t *in, vec_t *out );
+
+vec_t Q_rint (vec_t in);
+vec_t _DotProduct (vec3_t v1, vec3_t v2);
+void _VectorSubtract (vec3_t va, vec3_t vb, vec3_t out);
+void _VectorAdd (vec3_t va, vec3_t vb, vec3_t out);
+void _VectorCopy (vec3_t in, vec3_t out);
+void _VectorScale (vec3_t v, vec_t scale, vec3_t out);
+
+double VectorLength( const vec3_t v );
+
+void VectorMA( const vec3_t va, double scale, const vec3_t vb, vec3_t vc );
+
+void CrossProduct( const vec3_t v1, const vec3_t v2, vec3_t cross );
+vec_t VectorNormalize( const vec3_t in, vec3_t out );
+vec_t ColorNormalize( const vec3_t in, vec3_t out );
+void VectorInverse (vec3_t v);
+
+void ClearBounds (vec3_t mins, vec3_t maxs);
+void AddPointToBounds( const vec3_t v, vec3_t mins, vec3_t maxs );
+
+qboolean PlaneFromPoints( vec4_t plane, const vec3_t a, const vec3_t b, const vec3_t c );
+
+void NormalToLatLong( const vec3_t normal, byte bytes[2] );
+
+int PlaneTypeForNormal (vec3_t normal);
+
+void RotatePointAroundVector( vec3_t dst, const vec3_t dir, const vec3_t point,
+ float degrees );
+#endif
diff --git a/common/md4.c b/common/md4.c
new file mode 100755
index 0000000..37de7f7
--- /dev/null
+++ b/common/md4.c
@@ -0,0 +1,277 @@
+/* GLOBAL.H - RSAREF types and constants */
+
+#include <string.h>
+
+/* POINTER defines a generic pointer type */
+typedef unsigned char *POINTER;
+
+/* UINT2 defines a two byte word */
+typedef unsigned short int UINT2;
+
+/* UINT4 defines a four byte word */
+typedef unsigned long int UINT4;
+
+
+/* MD4.H - header file for MD4C.C */
+
+/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991.
+
+All rights reserved.
+
+License to copy and use this software is granted provided that it is identified as the “RSA Data Security, Inc. MD4 Message-Digest Algorithm” in all material mentioning or referencing this software or this function.
+License is also granted to make and use derivative works provided that such works are identified as “derived from the RSA Data Security, Inc. MD4 Message-Digest Algorithm” in all material mentioning or referencing the derived work.
+RSA Data Security, Inc. makes no representations concerning either the merchantability of this software or the suitability of this software for any particular purpose. It is provided “as is” without express or implied warranty of any kind.
+
+These notices must be retained in any copies of any part of this documentation and/or software. */
+
+/* MD4 context. */
+typedef struct {
+ UINT4 state[4]; /* state (ABCD) */
+ UINT4 count[2]; /* number of bits, modulo 2^64 (lsb first) */
+ unsigned char buffer[64]; /* input buffer */
+} MD4_CTX;
+
+void MD4Init (MD4_CTX *);
+void MD4Update (MD4_CTX *, unsigned char *, unsigned int);
+void MD4Final (unsigned char [16], MD4_CTX *);
+
+
+
+/* MD4C.C - RSA Data Security, Inc., MD4 message-digest algorithm */
+/* Copyright (C) 1990-2, RSA Data Security, Inc. All rights reserved.
+
+License to copy and use this software is granted provided that it is identified as the
+RSA Data Security, Inc. MD4 Message-Digest Algorithm
+ in all material mentioning or referencing this software or this function.
+License is also granted to make and use derivative works provided that such works are identified as
+derived from the RSA Data Security, Inc. MD4 Message-Digest Algorithm
+in all material mentioning or referencing the derived work.
+RSA Data Security, Inc. makes no representations concerning either the merchantability of this software or the suitability of this software for any particular purpose. It is provided
+as is without express or implied warranty of any kind.
+
+These notices must be retained in any copies of any part of this documentation and/or software. */
+
+/* Constants for MD4Transform routine. */
+#define S11 3
+#define S12 7
+#define S13 11
+#define S14 19
+#define S21 3
+#define S22 5
+#define S23 9
+#define S24 13
+#define S31 3
+#define S32 9
+#define S33 11
+#define S34 15
+
+static void MD4Transform (UINT4 [4], unsigned char [64]);
+static void Encode (unsigned char *, UINT4 *, unsigned int);
+static void Decode (UINT4 *, unsigned char *, unsigned int);
+static void MD4_memcpy (POINTER, POINTER, unsigned int);
+static void MD4_memset (POINTER, int, unsigned int);
+
+static unsigned char PADDING[64] = {
+0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+};
+
+/* F, G and H are basic MD4 functions. */
+#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
+#define G(x, y, z) (((x) & (y)) | ((x) & (z)) | ((y) & (z)))
+#define H(x, y, z) ((x) ^ (y) ^ (z))
+
+/* ROTATE_LEFT rotates x left n bits. */
+#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
+
+/* FF, GG and HH are transformations for rounds 1, 2 and 3 */
+/* Rotation is separate from addition to prevent recomputation */
+#define FF(a, b, c, d, x, s) {(a) += F ((b), (c), (d)) + (x); (a) = ROTATE_LEFT ((a), (s));}
+
+#define GG(a, b, c, d, x, s) {(a) += G ((b), (c), (d)) + (x) + (UINT4)0x5a827999; (a) = ROTATE_LEFT ((a), (s));}
+
+#define HH(a, b, c, d, x, s) {(a) += H ((b), (c), (d)) + (x) + (UINT4)0x6ed9eba1; (a) = \
+ROTATE_LEFT ((a), (s)); }
+
+
+/* MD4 initialization. Begins an MD4 operation, writing a new context. */
+void MD4Init (MD4_CTX *context)
+{
+ context->count[0] = context->count[1] = 0;
+
+/* Load magic initialization constants.*/
+context->state[0] = 0x67452301;
+context->state[1] = 0xefcdab89;
+context->state[2] = 0x98badcfe;
+context->state[3] = 0x10325476;
+}
+
+/* MD4 block update operation. Continues an MD4 message-digest operation, processing another message block, and updating the context. */
+void MD4Update (MD4_CTX *context, unsigned char *input, unsigned int inputLen)
+{
+ unsigned int i, index, partLen;
+
+ /* Compute number of bytes mod 64 */
+ index = (unsigned int)((context->count[0] >> 3) & 0x3F);
+
+ /* Update number of bits */
+ if ((context->count[0] += ((UINT4)inputLen << 3))< ((UINT4)inputLen << 3))
+ context->count[1]++;
+
+ context->count[1] += ((UINT4)inputLen >> 29);
+
+ partLen = 64 - index;
+
+ /* Transform as many times as possible.*/
+ if (inputLen >= partLen)
+ {
+ memcpy((POINTER)&context->buffer[index], (POINTER)input, partLen);
+ MD4Transform (context->state, context->buffer);
+
+ for (i = partLen; i + 63 < inputLen; i += 64)
+ MD4Transform (context->state, &input[i]);
+
+ index = 0;
+ }
+ else
+ i = 0;
+
+ /* Buffer remaining input */
+ memcpy ((POINTER)&context->buffer[index], (POINTER)&input[i], inputLen-i);
+}
+
+
+/* MD4 finalization. Ends an MD4 message-digest operation, writing the the message digest and zeroizing the context. */
+void MD4Final (unsigned char digest[16], MD4_CTX *context)
+{
+ unsigned char bits[8];
+ unsigned int index, padLen;
+
+ /* Save number of bits */
+ Encode (bits, context->count, 8);
+
+ /* Pad out to 56 mod 64.*/
+ index = (unsigned int)((context->count[0] >> 3) & 0x3f);
+ padLen = (index < 56) ? (56 - index) : (120 - index);
+ MD4Update (context, PADDING, padLen);
+
+ /* Append length (before padding) */
+ MD4Update (context, bits, 8);
+
+ /* Store state in digest */
+ Encode (digest, context->state, 16);
+
+ /* Zeroize sensitive information.*/
+ memset ((POINTER)context, 0, sizeof (*context));
+}
+
+
+/* MD4 basic transformation. Transforms state based on block. */
+static void MD4Transform (UINT4 state[4], unsigned char block[64])
+{
+ UINT4 a = state[0], b = state[1], c = state[2], d = state[3], x[16];
+
+ Decode (x, block, 64);
+
+/* Round 1 */
+FF (a, b, c, d, x[ 0], S11); /* 1 */
+FF (d, a, b, c, x[ 1], S12); /* 2 */
+FF (c, d, a, b, x[ 2], S13); /* 3 */
+FF (b, c, d, a, x[ 3], S14); /* 4 */
+FF (a, b, c, d, x[ 4], S11); /* 5 */
+FF (d, a, b, c, x[ 5], S12); /* 6 */
+FF (c, d, a, b, x[ 6], S13); /* 7 */
+FF (b, c, d, a, x[ 7], S14); /* 8 */
+FF (a, b, c, d, x[ 8], S11); /* 9 */
+FF (d, a, b, c, x[ 9], S12); /* 10 */
+FF (c, d, a, b, x[10], S13); /* 11 */
+FF (b, c, d, a, x[11], S14); /* 12 */
+FF (a, b, c, d, x[12], S11); /* 13 */
+FF (d, a, b, c, x[13], S12); /* 14 */
+FF (c, d, a, b, x[14], S13); /* 15 */
+FF (b, c, d, a, x[15], S14); /* 16 */
+
+/* Round 2 */
+GG (a, b, c, d, x[ 0], S21); /* 17 */
+GG (d, a, b, c, x[ 4], S22); /* 18 */
+GG (c, d, a, b, x[ 8], S23); /* 19 */
+GG (b, c, d, a, x[12], S24); /* 20 */
+GG (a, b, c, d, x[ 1], S21); /* 21 */
+GG (d, a, b, c, x[ 5], S22); /* 22 */
+GG (c, d, a, b, x[ 9], S23); /* 23 */
+GG (b, c, d, a, x[13], S24); /* 24 */
+GG (a, b, c, d, x[ 2], S21); /* 25 */
+GG (d, a, b, c, x[ 6], S22); /* 26 */
+GG (c, d, a, b, x[10], S23); /* 27 */
+GG (b, c, d, a, x[14], S24); /* 28 */
+GG (a, b, c, d, x[ 3], S21); /* 29 */
+GG (d, a, b, c, x[ 7], S22); /* 30 */
+GG (c, d, a, b, x[11], S23); /* 31 */
+GG (b, c, d, a, x[15], S24); /* 32 */
+
+/* Round 3 */
+HH (a, b, c, d, x[ 0], S31); /* 33 */
+HH (d, a, b, c, x[ 8], S32); /* 34 */
+HH (c, d, a, b, x[ 4], S33); /* 35 */
+HH (b, c, d, a, x[12], S34); /* 36 */
+HH (a, b, c, d, x[ 2], S31); /* 37 */
+HH (d, a, b, c, x[10], S32); /* 38 */
+HH (c, d, a, b, x[ 6], S33); /* 39 */
+HH (b, c, d, a, x[14], S34); /* 40 */
+HH (a, b, c, d, x[ 1], S31); /* 41 */
+HH (d, a, b, c, x[ 9], S32); /* 42 */
+HH (c, d, a, b, x[ 5], S33); /* 43 */
+HH (b, c, d, a, x[13], S34); /* 44 */
+HH (a, b, c, d, x[ 3], S31); /* 45 */
+HH (d, a, b, c, x[11], S32); /* 46 */
+HH (c, d, a, b, x[ 7], S33); /* 47 */
+HH (b, c, d, a, x[15], S34); /* 48 */
+
+state[0] += a;
+state[1] += b;
+state[2] += c;
+state[3] += d;
+
+ /* Zeroize sensitive information.*/
+ memset ((POINTER)x, 0, sizeof (x));
+}
+
+
+/* Encodes input (UINT4) into output (unsigned char). Assumes len is a multiple of 4. */
+static void Encode (unsigned char *output, UINT4 *input, unsigned int len)
+{
+ unsigned int i, j;
+
+ for (i = 0, j = 0; j < len; i++, j += 4) {
+ output[j] = (unsigned char)(input[i] & 0xff);
+ output[j+1] = (unsigned char)((input[i] >> 8) & 0xff);
+ output[j+2] = (unsigned char)((input[i] >> 16) & 0xff);
+ output[j+3] = (unsigned char)((input[i] >> 24) & 0xff);
+ }
+}
+
+
+/* Decodes input (unsigned char) into output (UINT4). Assumes len is a multiple of 4. */
+static void Decode (UINT4 *output, unsigned char *input, unsigned int len)
+{
+unsigned int i, j;
+
+for (i = 0, j = 0; j < len; i++, j += 4)
+ output[i] = ((UINT4)input[j]) | (((UINT4)input[j+1]) << 8) | (((UINT4)input[j+2]) << 16) | (((UINT4)input[j+3]) << 24);
+}
+
+//===================================================================
+
+unsigned Com_BlockChecksum (void *buffer, int length)
+{
+ int digest[4];
+ unsigned val;
+ MD4_CTX ctx;
+
+ MD4Init (&ctx);
+ MD4Update (&ctx, (unsigned char *)buffer, length);
+ MD4Final ( (unsigned char *)digest, &ctx);
+
+ val = digest[0] ^ digest[1] ^ digest[2] ^ digest[3];
+
+ return val;
+}
diff --git a/common/mutex.c b/common/mutex.c
new file mode 100755
index 0000000..ee16031
--- /dev/null
+++ b/common/mutex.c
@@ -0,0 +1,197 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "cmdlib.h"
+#include "threads.h"
+#include "mutex.h"
+
+/*
+===================================================================
+
+WIN32
+
+===================================================================
+*/
+#ifdef WIN32
+
+#define USED
+
+#include <windows.h>
+
+void MutexLock (mutex_t *m)
+{
+ CRITICAL_SECTION *crit;
+
+ if (!m)
+ return;
+ crit = (CRITICAL_SECTION *) m;
+ EnterCriticalSection (crit);
+}
+
+void MutexUnlock (mutex_t *m)
+{
+ CRITICAL_SECTION *crit;
+
+ if (!m)
+ return;
+ crit = (CRITICAL_SECTION *) m;
+ LeaveCriticalSection (crit);
+}
+
+mutex_t *MutexAlloc(void)
+{
+ CRITICAL_SECTION *crit;
+
+ if (numthreads == 1)
+ return NULL;
+ crit = (CRITICAL_SECTION *) malloc(sizeof(CRITICAL_SECTION));
+ InitializeCriticalSection (crit);
+ return (void *) crit;
+}
+
+#endif
+
+/*
+===================================================================
+
+OSF1
+
+===================================================================
+*/
+
+#ifdef __osf__
+#define USED
+
+#include <pthread.h>
+
+void MutexLock (mutex_t *m)
+{
+ pthread_mutex_t *my_mutex;
+
+ if (!m)
+ return;
+ my_mutex = (pthread_mutex_t *) m;
+ pthread_mutex_lock (my_mutex);
+}
+
+void MutexUnlock (mutex_t *m)
+{
+ pthread_mutex_t *my_mutex;
+
+ if (!m)
+ return;
+ my_mutex = (pthread_mutex_t *) m;
+ pthread_mutex_unlock (my_mutex);
+}
+
+mutex_t *MutexAlloc(void)
+{
+ pthread_mutex_t *my_mutex;
+ pthread_mutexattr_t mattrib;
+
+ if (numthreads == 1)
+ return NULL;
+ my_mutex = malloc (sizeof(*my_mutex));
+ if (pthread_mutexattr_create (&mattrib) == -1)
+ Error ("pthread_mutex_attr_create failed");
+ if (pthread_mutexattr_setkind_np (&mattrib, MUTEX_FAST_NP) == -1)
+ Error ("pthread_mutexattr_setkind_np failed");
+ if (pthread_mutex_init (my_mutex, mattrib) == -1)
+ Error ("pthread_mutex_init failed");
+ return (void *) my_mutex;
+}
+
+#endif
+
+/*
+===================================================================
+
+IRIX
+
+===================================================================
+*/
+
+#ifdef _MIPS_ISA
+#define USED
+
+#include <task.h>
+#include <abi_mutex.h>
+#include <sys/types.h>
+#include <sys/prctl.h>
+
+void MutexLock (mutex_t *m)
+{
+ abilock_t *lck;
+
+ if (!m)
+ return;
+ lck = (abilock_t *) m;
+ spin_lock (lck);
+}
+
+void MutexUnlock (mutex_t *m)
+{
+ abilock_t *lck;
+
+ if (!m)
+ return;
+ lck = (abilock_t *) m;
+ release_lock (lck);
+}
+
+mutex_t *MutexAlloc(void)
+{
+ abilock_t *lck;
+
+ if (numthreads == 1)
+ return NULL;
+ lck = (abilock_t *) malloc(sizeof(abilock_t));
+ init_lock (lck);
+ return (void *) lck;
+}
+
+#endif
+
+/*
+=======================================================================
+
+ SINGLE THREAD
+
+=======================================================================
+*/
+
+#ifndef USED
+
+void MutexLock (mutex_t *m)
+{
+}
+
+void MutexUnlock (mutex_t *m)
+{
+}
+
+mutex_t *MutexAlloc(void)
+{
+ return NULL;
+}
+
+#endif
diff --git a/common/mutex.h b/common/mutex.h
new file mode 100755
index 0000000..923f6bf
--- /dev/null
+++ b/common/mutex.h
@@ -0,0 +1,28 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+
+typedef void *mutex_t;
+
+void MutexLock (mutex_t *m);
+void MutexUnlock (mutex_t *m);
+mutex_t *MutexAlloc(void);
diff --git a/common/polylib.c b/common/polylib.c
new file mode 100755
index 0000000..c0e89a7
--- /dev/null
+++ b/common/polylib.c
@@ -0,0 +1,740 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "cmdlib.h"
+#include "mathlib.h"
+#include "polylib.h"
+#include "qfiles.h"
+
+
+extern int numthreads;
+
+// counters are only bumped when running single threaded,
+// because they are an awefull coherence problem
+int c_active_windings;
+int c_peak_windings;
+int c_winding_allocs;
+int c_winding_points;
+
+#define BOGUS_RANGE WORLD_SIZE
+
+void pw(winding_t *w)
+{
+ int i;
+ for (i=0 ; i<w->numpoints ; i++)
+ printf ("(%5.1f, %5.1f, %5.1f)\n",w->p[i][0], w->p[i][1],w->p[i][2]);
+}
+
+
+/*
+=============
+AllocWinding
+=============
+*/
+winding_t *AllocWinding (int points)
+{
+ winding_t *w;
+ int s;
+
+ if (numthreads == 1)
+ {
+ c_winding_allocs++;
+ c_winding_points += points;
+ c_active_windings++;
+ if (c_active_windings > c_peak_windings)
+ c_peak_windings = c_active_windings;
+ }
+ s = sizeof(vec_t)*3*points + sizeof(int);
+ w = malloc (s);
+ memset (w, 0, s);
+ return w;
+}
+
+void FreeWinding (winding_t *w)
+{
+ if (*(unsigned *)w == 0xdeaddead)
+ Error ("FreeWinding: freed a freed winding");
+ *(unsigned *)w = 0xdeaddead;
+
+ if (numthreads == 1)
+ c_active_windings--;
+ free (w);
+}
+
+/*
+============
+RemoveColinearPoints
+============
+*/
+int c_removed;
+
+void RemoveColinearPoints (winding_t *w)
+{
+ int i, j, k;
+ vec3_t v1, v2;
+ int nump;
+ vec3_t p[MAX_POINTS_ON_WINDING];
+
+ nump = 0;
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ j = (i+1)%w->numpoints;
+ k = (i+w->numpoints-1)%w->numpoints;
+ VectorSubtract (w->p[j], w->p[i], v1);
+ VectorSubtract (w->p[i], w->p[k], v2);
+ VectorNormalize(v1,v1);
+ VectorNormalize(v2,v2);
+ if (DotProduct(v1, v2) < 0.999)
+ {
+ VectorCopy (w->p[i], p[nump]);
+ nump++;
+ }
+ }
+
+ if (nump == w->numpoints)
+ return;
+
+ if (numthreads == 1)
+ c_removed += w->numpoints - nump;
+ w->numpoints = nump;
+ memcpy (w->p, p, nump*sizeof(p[0]));
+}
+
+/*
+============
+WindingPlane
+============
+*/
+void WindingPlane (winding_t *w, vec3_t normal, vec_t *dist)
+{
+ vec3_t v1, v2;
+
+ VectorSubtract (w->p[1], w->p[0], v1);
+ VectorSubtract (w->p[2], w->p[0], v2);
+ CrossProduct (v2, v1, normal);
+ VectorNormalize (normal, normal);
+ *dist = DotProduct (w->p[0], normal);
+
+}
+
+/*
+=============
+WindingArea
+=============
+*/
+vec_t WindingArea (winding_t *w)
+{
+ int i;
+ vec3_t d1, d2, cross;
+ vec_t total;
+
+ total = 0;
+ for (i=2 ; i<w->numpoints ; i++)
+ {
+ VectorSubtract (w->p[i-1], w->p[0], d1);
+ VectorSubtract (w->p[i], w->p[0], d2);
+ CrossProduct (d1, d2, cross);
+ total += 0.5 * VectorLength ( cross );
+ }
+ return total;
+}
+
+void WindingBounds (winding_t *w, vec3_t mins, vec3_t maxs)
+{
+ vec_t v;
+ int i,j;
+
+ mins[0] = mins[1] = mins[2] = 99999;
+ maxs[0] = maxs[1] = maxs[2] = -99999;
+
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ for (j=0 ; j<3 ; j++)
+ {
+ v = w->p[i][j];
+ if (v < mins[j])
+ mins[j] = v;
+ if (v > maxs[j])
+ maxs[j] = v;
+ }
+ }
+}
+
+/*
+=============
+WindingCenter
+=============
+*/
+void WindingCenter (winding_t *w, vec3_t center)
+{
+ int i;
+ float scale;
+
+ VectorCopy (vec3_origin, center);
+ for (i=0 ; i<w->numpoints ; i++)
+ VectorAdd (w->p[i], center, center);
+
+ scale = 1.0/w->numpoints;
+ VectorScale (center, scale, center);
+}
+
+/*
+=================
+BaseWindingForPlane
+=================
+*/
+winding_t *BaseWindingForPlane (vec3_t normal, vec_t dist)
+{
+ int i, x;
+ vec_t max, v;
+ vec3_t org, vright, vup;
+ winding_t *w;
+
+// find the major axis
+
+ max = -BOGUS_RANGE;
+ x = -1;
+ for (i=0 ; i<3; i++)
+ {
+ v = fabs(normal[i]);
+ if (v > max)
+ {
+ x = i;
+ max = v;
+ }
+ }
+ if (x==-1)
+ Error ("BaseWindingForPlane: no axis found");
+
+ VectorCopy (vec3_origin, vup);
+ switch (x)
+ {
+ case 0:
+ case 1:
+ vup[2] = 1;
+ break;
+ case 2:
+ vup[0] = 1;
+ break;
+ }
+
+ v = DotProduct (vup, normal);
+ VectorMA (vup, -v, normal, vup);
+ VectorNormalize (vup, vup);
+
+ VectorScale (normal, dist, org);
+
+ CrossProduct (vup, normal, vright);
+
+ VectorScale (vup, MAX_WORLD_COORD, vup);
+ VectorScale (vright, MAX_WORLD_COORD, vright);
+
+// project a really big axis aligned box onto the plane
+ w = AllocWinding (4);
+
+ VectorSubtract (org, vright, w->p[0]);
+ VectorAdd (w->p[0], vup, w->p[0]);
+
+ VectorAdd (org, vright, w->p[1]);
+ VectorAdd (w->p[1], vup, w->p[1]);
+
+ VectorAdd (org, vright, w->p[2]);
+ VectorSubtract (w->p[2], vup, w->p[2]);
+
+ VectorSubtract (org, vright, w->p[3]);
+ VectorSubtract (w->p[3], vup, w->p[3]);
+
+ w->numpoints = 4;
+
+ return w;
+}
+
+/*
+==================
+CopyWinding
+==================
+*/
+winding_t *CopyWinding (winding_t *w)
+{
+ int size;
+ winding_t *c;
+
+ c = AllocWinding (w->numpoints);
+ size = (int)((winding_t *)0)->p[w->numpoints];
+ memcpy (c, w, size);
+ return c;
+}
+
+/*
+==================
+ReverseWinding
+==================
+*/
+winding_t *ReverseWinding (winding_t *w)
+{
+ int i;
+ winding_t *c;
+
+ c = AllocWinding (w->numpoints);
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ VectorCopy (w->p[w->numpoints-1-i], c->p[i]);
+ }
+ c->numpoints = w->numpoints;
+ return c;
+}
+
+
+/*
+=============
+ClipWindingEpsilon
+=============
+*/
+void ClipWindingEpsilon (winding_t *in, vec3_t normal, vec_t dist,
+ vec_t epsilon, winding_t **front, winding_t **back)
+{
+ vec_t dists[MAX_POINTS_ON_WINDING+4];
+ int sides[MAX_POINTS_ON_WINDING+4];
+ int counts[3];
+ static vec_t dot; // VC 4.2 optimizer bug if not static
+ int i, j;
+ vec_t *p1, *p2;
+ vec3_t mid;
+ winding_t *f, *b;
+ int maxpts;
+
+ counts[0] = counts[1] = counts[2] = 0;
+
+// determine sides for each point
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ dot = DotProduct (in->p[i], normal);
+ dot -= dist;
+ dists[i] = dot;
+ if (dot > epsilon)
+ sides[i] = SIDE_FRONT;
+ else if (dot < -epsilon)
+ sides[i] = SIDE_BACK;
+ else
+ {
+ sides[i] = SIDE_ON;
+ }
+ counts[sides[i]]++;
+ }
+ sides[i] = sides[0];
+ dists[i] = dists[0];
+
+ *front = *back = NULL;
+
+ if (!counts[0])
+ {
+ *back = CopyWinding (in);
+ return;
+ }
+ if (!counts[1])
+ {
+ *front = CopyWinding (in);
+ return;
+ }
+
+ maxpts = in->numpoints+4; // cant use counts[0]+2 because
+ // of fp grouping errors
+
+ *front = f = AllocWinding (maxpts);
+ *back = b = AllocWinding (maxpts);
+
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ p1 = in->p[i];
+
+ if (sides[i] == SIDE_ON)
+ {
+ VectorCopy (p1, f->p[f->numpoints]);
+ f->numpoints++;
+ VectorCopy (p1, b->p[b->numpoints]);
+ b->numpoints++;
+ continue;
+ }
+
+ if (sides[i] == SIDE_FRONT)
+ {
+ VectorCopy (p1, f->p[f->numpoints]);
+ f->numpoints++;
+ }
+ if (sides[i] == SIDE_BACK)
+ {
+ VectorCopy (p1, b->p[b->numpoints]);
+ b->numpoints++;
+ }
+
+ if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i])
+ continue;
+
+ // generate a split point
+ p2 = in->p[(i+1)%in->numpoints];
+
+ dot = dists[i] / (dists[i]-dists[i+1]);
+ for (j=0 ; j<3 ; j++)
+ { // avoid round off error when possible
+ if (normal[j] == 1)
+ mid[j] = dist;
+ else if (normal[j] == -1)
+ mid[j] = -dist;
+ else
+ mid[j] = p1[j] + dot*(p2[j]-p1[j]);
+ }
+
+ VectorCopy (mid, f->p[f->numpoints]);
+ f->numpoints++;
+ VectorCopy (mid, b->p[b->numpoints]);
+ b->numpoints++;
+ }
+
+ if (f->numpoints > maxpts || b->numpoints > maxpts)
+ Error ("ClipWinding: points exceeded estimate");
+ if (f->numpoints > MAX_POINTS_ON_WINDING || b->numpoints > MAX_POINTS_ON_WINDING)
+ Error ("ClipWinding: MAX_POINTS_ON_WINDING");
+}
+
+
+/*
+=============
+ChopWindingInPlace
+=============
+*/
+void ChopWindingInPlace (winding_t **inout, vec3_t normal, vec_t dist, vec_t epsilon)
+{
+ winding_t *in;
+ vec_t dists[MAX_POINTS_ON_WINDING+4];
+ int sides[MAX_POINTS_ON_WINDING+4];
+ int counts[3];
+ static vec_t dot; // VC 4.2 optimizer bug if not static
+ int i, j;
+ vec_t *p1, *p2;
+ vec3_t mid;
+ winding_t *f;
+ int maxpts;
+
+ in = *inout;
+ counts[0] = counts[1] = counts[2] = 0;
+
+// determine sides for each point
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ dot = DotProduct (in->p[i], normal);
+ dot -= dist;
+ dists[i] = dot;
+ if (dot > epsilon)
+ sides[i] = SIDE_FRONT;
+ else if (dot < -epsilon)
+ sides[i] = SIDE_BACK;
+ else
+ {
+ sides[i] = SIDE_ON;
+ }
+ counts[sides[i]]++;
+ }
+ sides[i] = sides[0];
+ dists[i] = dists[0];
+
+ if (!counts[0])
+ {
+ FreeWinding (in);
+ *inout = NULL;
+ return;
+ }
+ if (!counts[1])
+ return; // inout stays the same
+
+ maxpts = in->numpoints+4; // cant use counts[0]+2 because
+ // of fp grouping errors
+
+ f = AllocWinding (maxpts);
+
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ p1 = in->p[i];
+
+ if (sides[i] == SIDE_ON)
+ {
+ VectorCopy (p1, f->p[f->numpoints]);
+ f->numpoints++;
+ continue;
+ }
+
+ if (sides[i] == SIDE_FRONT)
+ {
+ VectorCopy (p1, f->p[f->numpoints]);
+ f->numpoints++;
+ }
+
+ if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i])
+ continue;
+
+ // generate a split point
+ p2 = in->p[(i+1)%in->numpoints];
+
+ dot = dists[i] / (dists[i]-dists[i+1]);
+ for (j=0 ; j<3 ; j++)
+ { // avoid round off error when possible
+ if (normal[j] == 1)
+ mid[j] = dist;
+ else if (normal[j] == -1)
+ mid[j] = -dist;
+ else
+ mid[j] = p1[j] + dot*(p2[j]-p1[j]);
+ }
+
+ VectorCopy (mid, f->p[f->numpoints]);
+ f->numpoints++;
+ }
+
+ if (f->numpoints > maxpts)
+ Error ("ClipWinding: points exceeded estimate");
+ if (f->numpoints > MAX_POINTS_ON_WINDING)
+ Error ("ClipWinding: MAX_POINTS_ON_WINDING");
+
+ FreeWinding (in);
+ *inout = f;
+}
+
+
+/*
+=================
+ChopWinding
+
+Returns the fragment of in that is on the front side
+of the cliping plane. The original is freed.
+=================
+*/
+winding_t *ChopWinding (winding_t *in, vec3_t normal, vec_t dist)
+{
+ winding_t *f, *b;
+
+ ClipWindingEpsilon (in, normal, dist, ON_EPSILON, &f, &b);
+ FreeWinding (in);
+ if (b)
+ FreeWinding (b);
+ return f;
+}
+
+
+/*
+=================
+CheckWinding
+
+=================
+*/
+void CheckWinding (winding_t *w)
+{
+ int i, j;
+ vec_t *p1, *p2;
+ vec_t d, edgedist;
+ vec3_t dir, edgenormal, facenormal;
+ vec_t area;
+ vec_t facedist;
+
+ if (w->numpoints < 3)
+ Error ("CheckWinding: %i points",w->numpoints);
+
+ area = WindingArea(w);
+ if (area < 1)
+ Error ("CheckWinding: %f area", area);
+
+ WindingPlane (w, facenormal, &facedist);
+
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ p1 = w->p[i];
+
+ for (j=0 ; j<3 ; j++)
+ if (p1[j] > MAX_WORLD_COORD || p1[j] < MIN_WORLD_COORD)
+ Error ("CheckFace: BUGUS_RANGE: %f",p1[j]);
+
+ j = i+1 == w->numpoints ? 0 : i+1;
+
+ // check the point is on the face plane
+ d = DotProduct (p1, facenormal) - facedist;
+ if (d < -ON_EPSILON || d > ON_EPSILON)
+ Error ("CheckWinding: point off plane");
+
+ // check the edge isnt degenerate
+ p2 = w->p[j];
+ VectorSubtract (p2, p1, dir);
+
+ if (VectorLength (dir) < ON_EPSILON)
+ Error ("CheckWinding: degenerate edge");
+
+ CrossProduct (facenormal, dir, edgenormal);
+ VectorNormalize (edgenormal, edgenormal);
+ edgedist = DotProduct (p1, edgenormal);
+ edgedist += ON_EPSILON;
+
+ // all other points must be on front side
+ for (j=0 ; j<w->numpoints ; j++)
+ {
+ if (j == i)
+ continue;
+ d = DotProduct (w->p[j], edgenormal);
+ if (d > edgedist)
+ Error ("CheckWinding: non-convex");
+ }
+ }
+}
+
+
+/*
+============
+WindingOnPlaneSide
+============
+*/
+int WindingOnPlaneSide (winding_t *w, vec3_t normal, vec_t dist)
+{
+ qboolean front, back;
+ int i;
+ vec_t d;
+
+ front = qfalse;
+ back = qfalse;
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ d = DotProduct (w->p[i], normal) - dist;
+ if (d < -ON_EPSILON)
+ {
+ if (front)
+ return SIDE_CROSS;
+ back = qtrue;
+ continue;
+ }
+ if (d > ON_EPSILON)
+ {
+ if (back)
+ return SIDE_CROSS;
+ front = qtrue;
+ continue;
+ }
+ }
+
+ if (back)
+ return SIDE_BACK;
+ if (front)
+ return SIDE_FRONT;
+ return SIDE_ON;
+}
+
+
+/*
+=================
+AddWindingToConvexHull
+
+Both w and *hull are on the same plane
+=================
+*/
+#define MAX_HULL_POINTS 128
+void AddWindingToConvexHull( winding_t *w, winding_t **hull, vec3_t normal ) {
+ int i, j, k;
+ float *p, *copy;
+ vec3_t dir;
+ float d;
+ int numHullPoints, numNew;
+ vec3_t hullPoints[MAX_HULL_POINTS];
+ vec3_t newHullPoints[MAX_HULL_POINTS];
+ vec3_t hullDirs[MAX_HULL_POINTS];
+ qboolean hullSide[MAX_HULL_POINTS];
+ qboolean outside;
+
+ if ( !*hull ) {
+ *hull = CopyWinding( w );
+ return;
+ }
+
+ numHullPoints = (*hull)->numpoints;
+ memcpy( hullPoints, (*hull)->p, numHullPoints * sizeof(vec3_t) );
+
+ for ( i = 0 ; i < w->numpoints ; i++ ) {
+ p = w->p[i];
+
+ // calculate hull side vectors
+ for ( j = 0 ; j < numHullPoints ; j++ ) {
+ k = ( j + 1 ) % numHullPoints;
+
+ VectorSubtract( hullPoints[k], hullPoints[j], dir );
+ VectorNormalize( dir, dir );
+ CrossProduct( normal, dir, hullDirs[j] );
+ }
+
+ outside = qfalse;
+ for ( j = 0 ; j < numHullPoints ; j++ ) {
+ VectorSubtract( p, hullPoints[j], dir );
+ d = DotProduct( dir, hullDirs[j] );
+ if ( d >= ON_EPSILON ) {
+ outside = qtrue;
+ }
+ if ( d >= -ON_EPSILON ) {
+ hullSide[j] = qtrue;
+ } else {
+ hullSide[j] = qfalse;
+ }
+ }
+
+ // if the point is effectively inside, do nothing
+ if ( !outside ) {
+ continue;
+ }
+
+ // find the back side to front side transition
+ for ( j = 0 ; j < numHullPoints ; j++ ) {
+ if ( !hullSide[ j % numHullPoints ] && hullSide[ (j + 1) % numHullPoints ] ) {
+ break;
+ }
+ }
+ if ( j == numHullPoints ) {
+ continue;
+ }
+
+ // insert the point here
+ VectorCopy( p, newHullPoints[0] );
+ numNew = 1;
+
+ // copy over all points that aren't double fronts
+ j = (j+1)%numHullPoints;
+ for ( k = 0 ; k < numHullPoints ; k++ ) {
+ if ( hullSide[ (j+k) % numHullPoints ] && hullSide[ (j+k+1) % numHullPoints ] ) {
+ continue;
+ }
+ copy = hullPoints[ (j+k+1) % numHullPoints ];
+ VectorCopy( copy, newHullPoints[numNew] );
+ numNew++;
+ }
+
+ numHullPoints = numNew;
+ memcpy( hullPoints, newHullPoints, numHullPoints * sizeof(vec3_t) );
+ }
+
+ FreeWinding( *hull );
+ w = AllocWinding( numHullPoints );
+ w->numpoints = numHullPoints;
+ *hull = w;
+ memcpy( w->p, hullPoints, numHullPoints * sizeof(vec3_t) );
+}
+
+
diff --git a/common/polylib.h b/common/polylib.h
new file mode 100755
index 0000000..9f25a89
--- /dev/null
+++ b/common/polylib.h
@@ -0,0 +1,57 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+typedef struct
+{
+ int numpoints;
+ vec3_t p[4]; // variable sized
+} winding_t;
+
+#define MAX_POINTS_ON_WINDING 64
+
+// you can define on_epsilon in the makefile as tighter
+#ifndef ON_EPSILON
+#define ON_EPSILON 0.1
+#endif
+
+winding_t *AllocWinding (int points);
+vec_t WindingArea (winding_t *w);
+void WindingCenter (winding_t *w, vec3_t center);
+void ClipWindingEpsilon (winding_t *in, vec3_t normal, vec_t dist,
+ vec_t epsilon, winding_t **front, winding_t **back);
+winding_t *ChopWinding (winding_t *in, vec3_t normal, vec_t dist);
+winding_t *CopyWinding (winding_t *w);
+winding_t *ReverseWinding (winding_t *w);
+winding_t *BaseWindingForPlane (vec3_t normal, vec_t dist);
+void CheckWinding (winding_t *w);
+void WindingPlane (winding_t *w, vec3_t normal, vec_t *dist);
+void RemoveColinearPoints (winding_t *w);
+int WindingOnPlaneSide (winding_t *w, vec3_t normal, vec_t dist);
+void FreeWinding (winding_t *w);
+void WindingBounds (winding_t *w, vec3_t mins, vec3_t maxs);
+
+void AddWindingToConvexHull( winding_t *w, winding_t **hull, vec3_t normal );
+
+void ChopWindingInPlace (winding_t **w, vec3_t normal, vec_t dist, vec_t epsilon);
+// frees the original if clipped
+
+void pw(winding_t *w);
diff --git a/common/polyset.h b/common/polyset.h
new file mode 100755
index 0000000..3ee8858
--- /dev/null
+++ b/common/polyset.h
@@ -0,0 +1,51 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __POLYSET_H__
+#define __POLYSET_H__
+
+#define POLYSET_MAXTRIANGLES 4096
+#define POLYSET_MAXPOLYSETS 64
+
+typedef float st_t[2];
+typedef float rgb_t[3];
+
+typedef struct {
+ vec3_t verts[3];
+ vec3_t normals[3];
+ st_t texcoords[3];
+} triangle_t;
+
+typedef struct
+{
+ char name[100];
+ char materialname[100];
+ triangle_t *triangles;
+ int numtriangles;
+} polyset_t;
+
+polyset_t *Polyset_LoadSets( const char *file, int *numpolysets, int maxTrisPerSet );
+polyset_t *Polyset_CollapseSets( polyset_t *psets, int numpolysets );
+polyset_t *Polyset_SplitSets( polyset_t *psets, int numpolysets, int *pNumNewPolysets, int maxTris );
+void Polyset_SnapSets( polyset_t *psets, int numpolysets );
+void Polyset_ComputeNormals( polyset_t *psets, int numpolysets );
+
+#endif
diff --git a/common/qfiles.h b/common/qfiles.h
new file mode 100755
index 0000000..095de25
--- /dev/null
+++ b/common/qfiles.h
@@ -0,0 +1,489 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __QFILES_H__
+#define __QFILES_H__
+
+//
+// qfiles.h: quake file formats
+// This file must be identical in the quake and utils directories
+//
+
+// surface geometry should not exceed these limits
+#define SHADER_MAX_VERTEXES 1000
+#define SHADER_MAX_INDEXES (6*SHADER_MAX_VERTEXES)
+
+
+// the maximum size of game reletive pathnames
+#define MAX_QPATH 64
+
+
+/*
+========================================================================
+
+QVM files
+
+========================================================================
+*/
+
+#define VM_MAGIC 0x12721444
+typedef struct {
+ int vmMagic;
+
+ int instructionCount;
+
+ int codeOffset;
+ int codeLength;
+
+ int dataOffset;
+ int dataLength;
+ int litLength; // ( dataLength - litLength ) should be byteswapped on load
+ int bssLength; // zero filled memory appended to datalength
+} vmHeader_t;
+
+/*
+========================================================================
+
+PCX files are used for 8 bit images
+
+========================================================================
+*/
+
+typedef struct {
+ char manufacturer;
+ char version;
+ char encoding;
+ char bits_per_pixel;
+ unsigned short xmin,ymin,xmax,ymax;
+ unsigned short hres,vres;
+ unsigned char palette[48];
+ char reserved;
+ char color_planes;
+ unsigned short bytes_per_line;
+ unsigned short palette_type;
+ char filler[58];
+ unsigned char data; // unbounded
+} pcx_t;
+
+
+/*
+========================================================================
+
+TGA files are used for 24/32 bit images
+
+========================================================================
+*/
+
+typedef struct _TargaHeader {
+ unsigned char id_length, colormap_type, image_type;
+ unsigned short colormap_index, colormap_length;
+ unsigned char colormap_size;
+ unsigned short x_origin, y_origin, width, height;
+ unsigned char pixel_size, attributes;
+} TargaHeader;
+
+
+
+/*
+========================================================================
+
+.MD3 triangle model file format
+
+========================================================================
+*/
+
+#define MD3_IDENT (('3'<<24)+('P'<<16)+('D'<<8)+'I')
+#define MD3_VERSION 15
+
+// limits
+#define MD3_MAX_LODS 4
+#define MD3_MAX_TRIANGLES 8192 // per surface
+#define MD3_MAX_VERTS 4096 // per surface
+#define MD3_MAX_SHADERS 256 // per surface
+#define MD3_MAX_FRAMES 1024 // per model
+#define MD3_MAX_SURFACES 32 // per model
+#define MD3_MAX_TAGS 16 // per frame
+
+// vertex scales
+#define MD3_XYZ_SCALE (1.0/64)
+
+typedef struct md3Frame_s {
+ vec3_t bounds[2];
+ vec3_t localOrigin;
+ float radius;
+ char name[16];
+} md3Frame_t;
+
+typedef struct md3Tag_s {
+ char name[MAX_QPATH]; // tag name
+ vec3_t origin;
+ vec3_t axis[3];
+} md3Tag_t;
+
+/*
+** md3Surface_t
+**
+** CHUNK SIZE
+** header sizeof( md3Surface_t )
+** shaders sizeof( md3Shader_t ) * numShaders
+** triangles[0] sizeof( md3Triangle_t ) * numTriangles
+** st sizeof( md3St_t ) * numVerts
+** XyzNormals sizeof( md3XyzNormal_t ) * numVerts * numFrames
+*/
+typedef struct {
+ int ident; //
+
+ char name[MAX_QPATH]; // polyset name
+
+ int flags;
+ int numFrames; // all surfaces in a model should have the same
+
+ int numShaders; // all surfaces in a model should have the same
+ int numVerts;
+
+ int numTriangles;
+ int ofsTriangles;
+
+ int ofsShaders; // offset from start of md3Surface_t
+ int ofsSt; // texture coords are common for all frames
+ int ofsXyzNormals; // numVerts * numFrames
+
+ int ofsEnd; // next surface follows
+} md3Surface_t;
+
+typedef struct {
+ char name[MAX_QPATH];
+ int shaderIndex; // for in-game use
+} md3Shader_t;
+
+typedef struct {
+ int indexes[3];
+} md3Triangle_t;
+
+typedef struct {
+ float st[2];
+} md3St_t;
+
+typedef struct {
+ short xyz[3];
+ short normal;
+} md3XyzNormal_t;
+
+typedef struct {
+ int ident;
+ int version;
+
+ char name[MAX_QPATH]; // model name
+
+ int flags;
+
+ int numFrames;
+ int numTags;
+ int numSurfaces;
+
+ int numSkins;
+
+ int ofsFrames; // offset for first frame
+ int ofsTags; // numFrames * numTags
+ int ofsSurfaces; // first surface, others follow
+
+ int ofsEnd; // end of file
+} md3Header_t;
+
+
+/*
+==============================================================================
+
+MD4 file format
+
+==============================================================================
+*/
+
+#define MD4_IDENT (('4'<<24)+('P'<<16)+('D'<<8)+'I')
+#define MD4_VERSION 1
+#define MD4_MAX_BONES 128
+
+typedef struct {
+ int boneIndex; // these are indexes into the boneReferences,
+ float boneWeight; // not the global per-frame bone list
+} md4Weight_t;
+
+typedef struct {
+ vec3_t vertex;
+ vec3_t normal;
+ float texCoords[2];
+ int numWeights;
+ md4Weight_t weights[1]; // variable sized
+} md4Vertex_t;
+
+typedef struct {
+ int indexes[3];
+} md4Triangle_t;
+
+typedef struct {
+ int ident;
+
+ char name[MAX_QPATH]; // polyset name
+ char shader[MAX_QPATH];
+ int shaderIndex; // for in-game use
+
+ int ofsHeader; // this will be a negative number
+
+ int numVerts;
+ int ofsVerts;
+
+ int numTriangles;
+ int ofsTriangles;
+
+ // Bone references are a set of ints representing all the bones
+ // present in any vertex weights for this surface. This is
+ // needed because a model may have surfaces that need to be
+ // drawn at different sort times, and we don't want to have
+ // to re-interpolate all the bones for each surface.
+ int numBoneReferences;
+ int ofsBoneReferences;
+
+ int ofsEnd; // next surface follows
+} md4Surface_t;
+
+typedef struct {
+ float matrix[3][4];
+} md4Bone_t;
+
+typedef struct {
+ vec3_t bounds[2]; // bounds of all surfaces of all LOD's for this frame
+ vec3_t localOrigin; // midpoint of bounds, used for sphere cull
+ float radius; // dist from localOrigin to corner
+ char name[16];
+ md4Bone_t bones[1]; // [numBones]
+} md4Frame_t;
+
+typedef struct {
+ int numSurfaces;
+ int ofsSurfaces; // first surface, others follow
+ int ofsEnd; // next lod follows
+} md4LOD_t;
+
+typedef struct {
+ int ident;
+ int version;
+
+ char name[MAX_QPATH]; // model name
+
+ // frames and bones are shared by all levels of detail
+ int numFrames;
+ int numBones;
+ int ofsFrames; // md4Frame_t[numFrames]
+
+ // each level of detail has completely separate sets of surfaces
+ int numLODs;
+ int ofsLODs;
+
+ int ofsEnd; // end of file
+} md4Header_t;
+
+
+/*
+==============================================================================
+
+ .BSP file format
+
+==============================================================================
+*/
+
+
+#define BSP_IDENT (('P'<<24)+('S'<<16)+('B'<<8)+'I')
+ // little-endian "IBSP"
+
+#define BSP_VERSION 46
+
+
+// there shouldn't be any problem with increasing these values at the
+// expense of more memory allocation in the utilities
+#define MAX_MAP_MODELS 0x400
+#define MAX_MAP_BRUSHES 0x8000
+#define MAX_MAP_ENTITIES 0x800
+#define MAX_MAP_ENTSTRING 0x40000
+#define MAX_MAP_SHADERS 0x400
+
+#define MAX_MAP_AREAS 0x100 // MAX_MAP_AREA_BYTES in q_shared must match!
+#define MAX_MAP_FOGS 0x100
+#define MAX_MAP_PLANES 0x20000
+#define MAX_MAP_NODES 0x20000
+#define MAX_MAP_BRUSHSIDES 0x20000
+#define MAX_MAP_LEAFS 0x20000
+#define MAX_MAP_LEAFFACES 0x20000
+#define MAX_MAP_LEAFBRUSHES 0x40000
+#define MAX_MAP_PORTALS 0x20000
+#define MAX_MAP_LIGHTING 0x800000
+#define MAX_MAP_LIGHTGRID 0x800000
+#define MAX_MAP_VISIBILITY 0x200000
+
+#define MAX_MAP_DRAW_SURFS 0x20000
+#define MAX_MAP_DRAW_VERTS 0x80000
+#define MAX_MAP_DRAW_INDEXES 0x80000
+
+
+// key / value pair sizes in the entities lump
+#define MAX_KEY 32
+#define MAX_VALUE 1024
+
+// the editor uses these predefined yaw angles to orient entities up or down
+#define ANGLE_UP -1
+#define ANGLE_DOWN -2
+
+#define LIGHTMAP_WIDTH 128
+#define LIGHTMAP_HEIGHT 128
+
+#define MAX_WORLD_COORD ( 128*1024 )
+#define MIN_WORLD_COORD ( -128*1024 )
+#define WORLD_SIZE ( MAX_WORLD_COORD - MIN_WORLD_COORD )
+
+//=============================================================================
+
+
+typedef struct {
+ int fileofs, filelen;
+} lump_t;
+
+#define LUMP_ENTITIES 0
+#define LUMP_SHADERS 1
+#define LUMP_PLANES 2
+#define LUMP_NODES 3
+#define LUMP_LEAFS 4
+#define LUMP_LEAFSURFACES 5
+#define LUMP_LEAFBRUSHES 6
+#define LUMP_MODELS 7
+#define LUMP_BRUSHES 8
+#define LUMP_BRUSHSIDES 9
+#define LUMP_DRAWVERTS 10
+#define LUMP_DRAWINDEXES 11
+#define LUMP_FOGS 12
+#define LUMP_SURFACES 13
+#define LUMP_LIGHTMAPS 14
+#define LUMP_LIGHTGRID 15
+#define LUMP_VISIBILITY 16
+#define HEADER_LUMPS 17
+
+typedef struct {
+ int ident;
+ int version;
+
+ lump_t lumps[HEADER_LUMPS];
+} dheader_t;
+
+typedef struct {
+ float mins[3], maxs[3];
+ int firstSurface, numSurfaces;
+ int firstBrush, numBrushes;
+} dmodel_t;
+
+typedef struct {
+ char shader[MAX_QPATH];
+ int surfaceFlags;
+ int contentFlags;
+} dshader_t;
+
+// planes x^1 is allways the opposite of plane x
+
+typedef struct {
+ float normal[3];
+ float dist;
+} dplane_t;
+
+typedef struct {
+ int planeNum;
+ int children[2]; // negative numbers are -(leafs+1), not nodes
+ int mins[3]; // for frustom culling
+ int maxs[3];
+} dnode_t;
+
+typedef struct {
+ int cluster; // -1 = opaque cluster (do I still store these?)
+ int area;
+
+ int mins[3]; // for frustum culling
+ int maxs[3];
+
+ int firstLeafSurface;
+ int numLeafSurfaces;
+
+ int firstLeafBrush;
+ int numLeafBrushes;
+} dleaf_t;
+
+typedef struct {
+ int planeNum; // positive plane side faces out of the leaf
+ int shaderNum;
+} dbrushside_t;
+
+typedef struct {
+ int firstSide;
+ int numSides;
+ int shaderNum; // the shader that determines the contents flags
+} dbrush_t;
+
+typedef struct {
+ char shader[MAX_QPATH];
+ int brushNum;
+ int visibleSide; // the brush side that ray tests need to clip against (-1 == none)
+} dfog_t;
+
+typedef struct {
+ vec3_t xyz;
+ float st[2];
+ float lightmap[2];
+ vec3_t normal;
+ byte color[4];
+} drawVert_t;
+
+typedef enum {
+ MST_BAD,
+ MST_PLANAR,
+ MST_PATCH,
+ MST_TRIANGLE_SOUP,
+ MST_FLARE
+} mapSurfaceType_t;
+
+typedef struct {
+ int shaderNum;
+ int fogNum;
+ int surfaceType;
+
+ int firstVert;
+ int numVerts;
+
+ int firstIndex;
+ int numIndexes;
+
+ int lightmapNum;
+ int lightmapX, lightmapY;
+ int lightmapWidth, lightmapHeight;
+
+ vec3_t lightmapOrigin;
+ vec3_t lightmapVecs[3]; // for patches, [0] and [1] are lodbounds
+
+ int patchWidth;
+ int patchHeight;
+} dsurface_t;
+
+
+#endif
diff --git a/common/scriplib.c b/common/scriplib.c
new file mode 100755
index 0000000..782a538
--- /dev/null
+++ b/common/scriplib.c
@@ -0,0 +1,375 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// scriplib.c
+
+#include "cmdlib.h"
+#include "scriplib.h"
+
+/*
+=============================================================================
+
+ PARSING STUFF
+
+=============================================================================
+*/
+
+typedef struct
+{
+ char filename[1024];
+ char *buffer,*script_p,*end_p;
+ int line;
+} script_t;
+
+#define MAX_INCLUDES 8
+script_t scriptstack[MAX_INCLUDES];
+script_t *script;
+int scriptline;
+
+char token[MAXTOKEN];
+qboolean endofscript;
+qboolean tokenready; // only qtrue if UnGetToken was just called
+
+/*
+==============
+AddScriptToStack
+==============
+*/
+void AddScriptToStack( const char *filename ) {
+ int size;
+
+ script++;
+ if (script == &scriptstack[MAX_INCLUDES])
+ Error ("script file exceeded MAX_INCLUDES");
+ strcpy (script->filename, ExpandPath (filename) );
+
+ size = LoadFile (script->filename, (void **)&script->buffer);
+
+ printf ("entering %s\n", script->filename);
+
+ script->line = 1;
+
+ script->script_p = script->buffer;
+ script->end_p = script->buffer + size;
+}
+
+
+/*
+==============
+LoadScriptFile
+==============
+*/
+void LoadScriptFile( const char *filename ) {
+ script = scriptstack;
+ AddScriptToStack (filename);
+
+ endofscript = qfalse;
+ tokenready = qfalse;
+}
+
+
+/*
+==============
+ParseFromMemory
+==============
+*/
+void ParseFromMemory (char *buffer, int size)
+{
+ script = scriptstack;
+ script++;
+ if (script == &scriptstack[MAX_INCLUDES])
+ Error ("script file exceeded MAX_INCLUDES");
+ strcpy (script->filename, "memory buffer" );
+
+ script->buffer = buffer;
+ script->line = 1;
+ script->script_p = script->buffer;
+ script->end_p = script->buffer + size;
+
+ endofscript = qfalse;
+ tokenready = qfalse;
+}
+
+
+/*
+==============
+UnGetToken
+
+Signals that the current token was not used, and should be reported
+for the next GetToken. Note that
+
+GetToken (qtrue);
+UnGetToken ();
+GetToken (qfalse);
+
+could cross a line boundary.
+==============
+*/
+void UnGetToken (void)
+{
+ tokenready = qtrue;
+}
+
+
+qboolean EndOfScript (qboolean crossline)
+{
+ if (!crossline)
+ Error ("Line %i is incomplete\n",scriptline);
+
+ if (!strcmp (script->filename, "memory buffer"))
+ {
+ endofscript = qtrue;
+ return qfalse;
+ }
+
+ free (script->buffer);
+ if (script == scriptstack+1)
+ {
+ endofscript = qtrue;
+ return qfalse;
+ }
+ script--;
+ scriptline = script->line;
+ printf ("returning to %s\n", script->filename);
+ return GetToken (crossline);
+}
+
+/*
+==============
+GetToken
+==============
+*/
+qboolean GetToken (qboolean crossline)
+{
+ char *token_p;
+
+ if (tokenready) // is a token allready waiting?
+ {
+ tokenready = qfalse;
+ return qtrue;
+ }
+
+ if (script->script_p >= script->end_p)
+ return EndOfScript (crossline);
+
+//
+// skip space
+//
+skipspace:
+ while (*script->script_p <= 32)
+ {
+ if (script->script_p >= script->end_p)
+ return EndOfScript (crossline);
+ if (*script->script_p++ == '\n')
+ {
+ if (!crossline)
+ Error ("Line %i is incomplete\n",scriptline);
+ scriptline = script->line++;
+ }
+ }
+
+ if (script->script_p >= script->end_p)
+ return EndOfScript (crossline);
+
+ // ; # // comments
+ if (*script->script_p == ';' || *script->script_p == '#'
+ || ( script->script_p[0] == '/' && script->script_p[1] == '/') )
+ {
+ if (!crossline)
+ Error ("Line %i is incomplete\n",scriptline);
+ while (*script->script_p++ != '\n')
+ if (script->script_p >= script->end_p)
+ return EndOfScript (crossline);
+ scriptline = script->line++;
+ goto skipspace;
+ }
+
+ // /* */ comments
+ if (script->script_p[0] == '/' && script->script_p[1] == '*')
+ {
+ if (!crossline)
+ Error ("Line %i is incomplete\n",scriptline);
+ script->script_p+=2;
+ while (script->script_p[0] != '*' && script->script_p[1] != '/')
+ {
+ if ( *script->script_p == '\n' ) {
+ scriptline = script->line++;
+ }
+ script->script_p++;
+ if (script->script_p >= script->end_p)
+ return EndOfScript (crossline);
+ }
+ script->script_p += 2;
+ goto skipspace;
+ }
+
+//
+// copy token
+//
+ token_p = token;
+
+ if (*script->script_p == '"')
+ {
+ // quoted token
+ script->script_p++;
+ while (*script->script_p != '"')
+ {
+ *token_p++ = *script->script_p++;
+ if (script->script_p == script->end_p)
+ break;
+ if (token_p == &token[MAXTOKEN])
+ Error ("Token too large on line %i\n",scriptline);
+ }
+ script->script_p++;
+ }
+ else // regular token
+ while ( *script->script_p > 32 && *script->script_p != ';')
+ {
+ *token_p++ = *script->script_p++;
+ if (script->script_p == script->end_p)
+ break;
+ if (token_p == &token[MAXTOKEN])
+ Error ("Token too large on line %i\n",scriptline);
+ }
+
+ *token_p = 0;
+
+ if (!strcmp (token, "$include"))
+ {
+ GetToken (qfalse);
+ AddScriptToStack (token);
+ return GetToken (crossline);
+ }
+
+ return qtrue;
+}
+
+
+/*
+==============
+TokenAvailable
+
+Returns qtrue if there is another token on the line
+==============
+*/
+qboolean TokenAvailable (void) {
+ int oldLine;
+ qboolean r;
+
+ oldLine = script->line;
+ r = GetToken( qtrue );
+ if ( !r ) {
+ return qfalse;
+ }
+ UnGetToken();
+ if ( oldLine == script->line ) {
+ return qtrue;
+ }
+ return qfalse;
+}
+
+
+//=====================================================================
+
+
+void MatchToken( char *match ) {
+ GetToken( qtrue );
+
+ if ( strcmp( token, match ) ) {
+ Error( "MatchToken( \"%s\" ) failed at line %i", match, scriptline );
+ }
+}
+
+
+void Parse1DMatrix (int x, vec_t *m) {
+ int i;
+
+ MatchToken( "(" );
+
+ for (i = 0 ; i < x ; i++) {
+ GetToken( qfalse );
+ m[i] = atof(token);
+ }
+
+ MatchToken( ")" );
+}
+
+void Parse2DMatrix (int y, int x, vec_t *m) {
+ int i;
+
+ MatchToken( "(" );
+
+ for (i = 0 ; i < y ; i++) {
+ Parse1DMatrix (x, m + i * x);
+ }
+
+ MatchToken( ")" );
+}
+
+void Parse3DMatrix (int z, int y, int x, vec_t *m) {
+ int i;
+
+ MatchToken( "(" );
+
+ for (i = 0 ; i < z ; i++) {
+ Parse2DMatrix (y, x, m + i * x*y);
+ }
+
+ MatchToken( ")" );
+}
+
+
+void Write1DMatrix (FILE *f, int x, vec_t *m) {
+ int i;
+
+ fprintf (f, "( ");
+ for (i = 0 ; i < x ; i++) {
+ if (m[i] == (int)m[i] ) {
+ fprintf (f, "%i ", (int)m[i]);
+ } else {
+ fprintf (f, "%f ", m[i]);
+ }
+ }
+ fprintf (f, ")");
+}
+
+void Write2DMatrix (FILE *f, int y, int x, vec_t *m) {
+ int i;
+
+ fprintf (f, "( ");
+ for (i = 0 ; i < y ; i++) {
+ Write1DMatrix (f, x, m + i*x);
+ fprintf (f, " ");
+ }
+ fprintf (f, ")\n");
+}
+
+
+void Write3DMatrix (FILE *f, int z, int y, int x, vec_t *m) {
+ int i;
+
+ fprintf (f, "(\n");
+ for (i = 0 ; i < z ; i++) {
+ Write2DMatrix (f, y, x, m + i*(x*y) );
+ }
+ fprintf (f, ")\n");
+}
+
diff --git a/common/scriplib.h b/common/scriplib.h
new file mode 100755
index 0000000..88274cb
--- /dev/null
+++ b/common/scriplib.h
@@ -0,0 +1,55 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// scriplib.h
+
+#ifndef __CMDLIB__
+#include "cmdlib.h"
+#endif
+#ifndef __MATHLIB__
+#include "mathlib.h"
+#endif
+
+#define MAXTOKEN 1024
+
+extern char token[MAXTOKEN];
+extern char *scriptbuffer,*script_p,*scriptend_p;
+extern int grabbed;
+extern int scriptline;
+extern qboolean endofscript;
+
+
+void LoadScriptFile( const char *filename );
+void ParseFromMemory (char *buffer, int size);
+
+qboolean GetToken (qboolean crossline);
+void UnGetToken (void);
+qboolean TokenAvailable (void);
+
+void MatchToken( char *match );
+
+void Parse1DMatrix (int x, vec_t *m);
+void Parse2DMatrix (int y, int x, vec_t *m);
+void Parse3DMatrix (int z, int y, int x, vec_t *m);
+
+void Write1DMatrix (FILE *f, int x, vec_t *m);
+void Write2DMatrix (FILE *f, int y, int x, vec_t *m);
+void Write3DMatrix (FILE *f, int z, int y, int x, vec_t *m);
diff --git a/common/surfaceflags.h b/common/surfaceflags.h
new file mode 100755
index 0000000..b99cfda
--- /dev/null
+++ b/common/surfaceflags.h
@@ -0,0 +1,72 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// This file must be identical in the quake and utils directories
+
+// contents flags are seperate bits
+// a given brush can contribute multiple content bits
+
+// these definitions also need to be in q_shared.h!
+
+#define CONTENTS_SOLID 1 // an eye is never valid in a solid
+#define CONTENTS_LAVA 8
+#define CONTENTS_SLIME 16
+#define CONTENTS_WATER 32
+#define CONTENTS_FOG 64
+
+#define CONTENTS_AREAPORTAL 0x8000
+
+#define CONTENTS_PLAYERCLIP 0x10000
+#define CONTENTS_MONSTERCLIP 0x20000
+//bot specific contents types
+#define CONTENTS_TELEPORTER 0x40000
+#define CONTENTS_JUMPPAD 0x80000
+#define CONTENTS_CLUSTERPORTAL 0x100000
+#define CONTENTS_DONOTENTER 0x200000
+
+#define CONTENTS_ORIGIN 0x1000000 // removed before bsping an entity
+
+#define CONTENTS_BODY 0x2000000 // should never be on a brush, only in game
+#define CONTENTS_CORPSE 0x4000000
+#define CONTENTS_DETAIL 0x8000000 // brushes not used for the bsp
+#define CONTENTS_STRUCTURAL 0x10000000 // brushes used for the bsp
+#define CONTENTS_TRANSLUCENT 0x20000000 // don't consume surface fragments inside
+#define CONTENTS_TRIGGER 0x40000000
+#define CONTENTS_NODROP 0x80000000 // don't leave bodies or items (death fog, lava)
+
+#define SURF_NODAMAGE 0x1 // never give falling damage
+#define SURF_SLICK 0x2 // effects game physics
+#define SURF_SKY 0x4 // lighting from environment map
+#define SURF_LADDER 0x8
+#define SURF_NOIMPACT 0x10 // don't make missile explosions
+#define SURF_NOMARKS 0x20 // don't leave missile marks
+#define SURF_FLESH 0x40 // make flesh sounds and effects
+#define SURF_NODRAW 0x80 // don't generate a drawsurface at all
+#define SURF_HINT 0x100 // make a primary bsp splitter
+#define SURF_SKIP 0x200 // completely ignore, allowing non-closed brushes
+#define SURF_NOLIGHTMAP 0x400 // surface doesn't need a lightmap
+#define SURF_POINTLIGHT 0x800 // generate lighting info at vertexes
+#define SURF_METALSTEPS 0x1000 // clanking footsteps
+#define SURF_NOSTEPS 0x2000 // no footstep sounds
+#define SURF_NONSOLID 0x4000 // don't collide against curves with this set
+#define SURF_LIGHTFILTER 0x8000 // act as a light filter during q3map -light
+#define SURF_ALPHASHADOW 0x10000 // do per-pixel light shadow casting in q3map
+#define SURF_NODLIGHT 0x20000 // never add dynamic lights
diff --git a/common/threads.c b/common/threads.c
new file mode 100755
index 0000000..e700dbb
--- /dev/null
+++ b/common/threads.c
@@ -0,0 +1,441 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "cmdlib.h"
+#include "threads.h"
+
+#define MAX_THREADS 64
+
+int dispatch;
+int workcount;
+int oldf;
+qboolean pacifier;
+
+qboolean threaded;
+
+/*
+=============
+GetThreadWork
+
+=============
+*/
+int GetThreadWork (void)
+{
+ int r;
+ int f;
+
+ ThreadLock ();
+
+ if (dispatch == workcount)
+ {
+ ThreadUnlock ();
+ return -1;
+ }
+
+ f = 10*dispatch / workcount;
+ if (f != oldf)
+ {
+ oldf = f;
+ if (pacifier)
+ _printf ("%i...", f);
+ }
+
+ r = dispatch;
+ dispatch++;
+ ThreadUnlock ();
+
+ return r;
+}
+
+
+void (*workfunction) (int);
+
+void ThreadWorkerFunction (int threadnum)
+{
+ int work;
+
+ while (1)
+ {
+ work = GetThreadWork ();
+ if (work == -1)
+ break;
+//_printf ("thread %i, work %i\n", threadnum, work);
+ workfunction(work);
+ }
+}
+
+void RunThreadsOnIndividual (int workcnt, qboolean showpacifier, void(*func)(int))
+{
+ if (numthreads == -1)
+ ThreadSetDefault ();
+ workfunction = func;
+ RunThreadsOn (workcnt, showpacifier, ThreadWorkerFunction);
+}
+
+
+/*
+===================================================================
+
+WIN32
+
+===================================================================
+*/
+#ifdef WIN32
+
+#define USED
+
+#include <windows.h>
+
+int numthreads = -1;
+CRITICAL_SECTION crit;
+static int enter;
+
+void ThreadSetDefault (void)
+{
+ SYSTEM_INFO info;
+
+ if (numthreads == -1) // not set manually
+ {
+ GetSystemInfo (&info);
+ numthreads = info.dwNumberOfProcessors;
+ if (numthreads < 1 || numthreads > 32)
+ numthreads = 1;
+ }
+
+ qprintf ("%i threads\n", numthreads);
+}
+
+
+void ThreadLock (void)
+{
+ if (!threaded)
+ return;
+ EnterCriticalSection (&crit);
+ if (enter)
+ Error ("Recursive ThreadLock\n");
+ enter = 1;
+}
+
+void ThreadUnlock (void)
+{
+ if (!threaded)
+ return;
+ if (!enter)
+ Error ("ThreadUnlock without lock\n");
+ enter = 0;
+ LeaveCriticalSection (&crit);
+}
+
+/*
+=============
+RunThreadsOn
+=============
+*/
+void RunThreadsOn (int workcnt, qboolean showpacifier, void(*func)(int))
+{
+ int threadid[MAX_THREADS];
+ HANDLE threadhandle[MAX_THREADS];
+ int i;
+ int start, end;
+
+ start = I_FloatTime ();
+ dispatch = 0;
+ workcount = workcnt;
+ oldf = -1;
+ pacifier = showpacifier;
+ threaded = qtrue;
+
+ //
+ // run threads in parallel
+ //
+ InitializeCriticalSection (&crit);
+
+ if (numthreads == 1)
+ { // use same thread
+ func (0);
+ }
+ else
+ {
+ for (i=0 ; i<numthreads ; i++)
+ {
+ threadhandle[i] = CreateThread(
+ NULL, // LPSECURITY_ATTRIBUTES lpsa,
+ 0, // DWORD cbStack,
+ (LPTHREAD_START_ROUTINE)func, // LPTHREAD_START_ROUTINE lpStartAddr,
+ (LPVOID)i, // LPVOID lpvThreadParm,
+ 0, // DWORD fdwCreate,
+ &threadid[i]);
+ }
+
+ for (i=0 ; i<numthreads ; i++)
+ WaitForSingleObject (threadhandle[i], INFINITE);
+ }
+ DeleteCriticalSection (&crit);
+
+ threaded = qfalse;
+ end = I_FloatTime ();
+ if (pacifier)
+ _printf (" (%i)\n", end-start);
+}
+
+
+#endif
+
+/*
+===================================================================
+
+OSF1
+
+===================================================================
+*/
+
+#ifdef __osf__
+#define USED
+
+int numthreads = 4;
+
+void ThreadSetDefault (void)
+{
+ if (numthreads == -1) // not set manually
+ {
+ numthreads = 4;
+ }
+}
+
+
+#include <pthread.h>
+
+pthread_mutex_t *my_mutex;
+
+void ThreadLock (void)
+{
+ if (my_mutex)
+ pthread_mutex_lock (my_mutex);
+}
+
+void ThreadUnlock (void)
+{
+ if (my_mutex)
+ pthread_mutex_unlock (my_mutex);
+}
+
+
+/*
+=============
+RunThreadsOn
+=============
+*/
+void RunThreadsOn (int workcnt, qboolean showpacifier, void(*func)(int))
+{
+ int i;
+ pthread_t work_threads[MAX_THREADS];
+ pthread_addr_t status;
+ pthread_attr_t attrib;
+ pthread_mutexattr_t mattrib;
+ int start, end;
+
+ start = I_FloatTime ();
+ dispatch = 0;
+ workcount = workcnt;
+ oldf = -1;
+ pacifier = showpacifier;
+ threaded = qtrue;
+
+ if (pacifier)
+ setbuf (stdout, NULL);
+
+ if (!my_mutex)
+ {
+ my_mutex = malloc (sizeof(*my_mutex));
+ if (pthread_mutexattr_create (&mattrib) == -1)
+ Error ("pthread_mutex_attr_create failed");
+ if (pthread_mutexattr_setkind_np (&mattrib, MUTEX_FAST_NP) == -1)
+ Error ("pthread_mutexattr_setkind_np failed");
+ if (pthread_mutex_init (my_mutex, mattrib) == -1)
+ Error ("pthread_mutex_init failed");
+ }
+
+ if (pthread_attr_create (&attrib) == -1)
+ Error ("pthread_attr_create failed");
+ if (pthread_attr_setstacksize (&attrib, 0x100000) == -1)
+ Error ("pthread_attr_setstacksize failed");
+
+ for (i=0 ; i<numthreads ; i++)
+ {
+ if (pthread_create(&work_threads[i], attrib
+ , (pthread_startroutine_t)func, (pthread_addr_t)i) == -1)
+ Error ("pthread_create failed");
+ }
+
+ for (i=0 ; i<numthreads ; i++)
+ {
+ if (pthread_join (work_threads[i], &status) == -1)
+ Error ("pthread_join failed");
+ }
+
+ threaded = qfalse;
+
+ end = I_FloatTime ();
+ if (pacifier)
+ _printf (" (%i)\n", end-start);
+}
+
+
+#endif
+
+/*
+===================================================================
+
+IRIX
+
+===================================================================
+*/
+
+#ifdef _MIPS_ISA
+#define USED
+
+#include <task.h>
+#include <abi_mutex.h>
+#include <sys/types.h>
+#include <sys/prctl.h>
+
+
+int numthreads = -1;
+abilock_t lck;
+
+void ThreadSetDefault (void)
+{
+ if (numthreads == -1)
+ numthreads = prctl(PR_MAXPPROCS);
+ _printf ("%i threads\n", numthreads);
+ usconfig (CONF_INITUSERS, numthreads);
+}
+
+
+void ThreadLock (void)
+{
+ spin_lock (&lck);
+}
+
+void ThreadUnlock (void)
+{
+ release_lock (&lck);
+}
+
+
+/*
+=============
+RunThreadsOn
+=============
+*/
+void RunThreadsOn (int workcnt, qboolean showpacifier, void(*func)(int))
+{
+ int i;
+ int pid[MAX_THREADS];
+ int start, end;
+
+ start = I_FloatTime ();
+ dispatch = 0;
+ workcount = workcnt;
+ oldf = -1;
+ pacifier = showpacifier;
+ threaded = qtrue;
+
+ if (pacifier)
+ setbuf (stdout, NULL);
+
+ init_lock (&lck);
+
+ for (i=0 ; i<numthreads-1 ; i++)
+ {
+ pid[i] = sprocsp ( (void (*)(void *, size_t))func, PR_SALL, (void *)i
+ , NULL, 0x200000); // 2 meg stacks
+ if (pid[i] == -1)
+ {
+ perror ("sproc");
+ Error ("sproc failed");
+ }
+ }
+
+ func(i);
+
+ for (i=0 ; i<numthreads-1 ; i++)
+ wait (NULL);
+
+ threaded = qfalse;
+
+ end = I_FloatTime ();
+ if (pacifier)
+ _printf (" (%i)\n", end-start);
+}
+
+
+#endif
+
+/*
+=======================================================================
+
+ SINGLE THREAD
+
+=======================================================================
+*/
+
+#ifndef USED
+
+int numthreads = 1;
+
+void ThreadSetDefault (void)
+{
+ numthreads = 1;
+}
+
+void ThreadLock (void)
+{
+}
+
+void ThreadUnlock (void)
+{
+}
+
+/*
+=============
+RunThreadsOn
+=============
+*/
+void RunThreadsOn (int workcnt, qboolean showpacifier, void(*func)(int))
+{
+ int i;
+ int start, end;
+
+ dispatch = 0;
+ workcount = workcnt;
+ oldf = -1;
+ pacifier = showpacifier;
+ start = I_FloatTime ();
+ func(0);
+
+ end = I_FloatTime ();
+ if (pacifier)
+ _printf (" (%i)\n", end-start);
+}
+
+#endif
diff --git a/common/threads.h b/common/threads.h
new file mode 100755
index 0000000..ba76dfb
--- /dev/null
+++ b/common/threads.h
@@ -0,0 +1,31 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+extern int numthreads;
+
+void ThreadSetDefault (void);
+int GetThreadWork (void);
+void RunThreadsOnIndividual (int workcnt, qboolean showpacifier, void(*func)(int));
+void RunThreadsOn (int workcnt, qboolean showpacifier, void(*func)(int));
+void ThreadLock (void);
+void ThreadUnlock (void);
+
diff --git a/common/trilib.c b/common/trilib.c
new file mode 100755
index 0000000..34f9e2e
--- /dev/null
+++ b/common/trilib.c
@@ -0,0 +1,231 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// trilib.c: library for loading triangles from an Alias triangle file
+//
+
+#include <stdio.h>
+#include "cmdlib.h"
+#include "mathlib.h"
+#include "polyset.h"
+#include "trilib.h"
+
+// on disk representation of a face
+
+
+#define FLOAT_START 99999.0
+#define FLOAT_END -FLOAT_START
+#define MAGIC 123322
+
+//#define NOISY 1
+
+typedef struct {
+ float v[3];
+} vector;
+
+typedef struct
+{
+ vector n; /* normal */
+ vector p; /* point */
+ vector c; /* color */
+ float u; /* u */
+ float v; /* v */
+} aliaspoint_t;
+
+typedef struct {
+ aliaspoint_t pt[3];
+} tf_triangle;
+
+
+static void ByteSwapTri (tf_triangle *tri)
+{
+ int i;
+
+ for (i=0 ; i<sizeof(tf_triangle)/4 ; i++)
+ {
+ ((int *)tri)[i] = BigLong (((int *)tri)[i]);
+ }
+}
+
+static void ReadPolysetGeometry( triangle_t *tripool, FILE *input, int count, triangle_t *ptri )
+{
+ tf_triangle tri;
+ int i;
+
+ for (i = 0; i < count; ++i) {
+ int j;
+
+ fread( &tri, sizeof(tf_triangle), 1, input );
+ ByteSwapTri (&tri);
+ for (j=0 ; j<3 ; j++)
+ {
+ int k;
+
+ for (k=0 ; k<3 ; k++)
+ {
+ ptri->verts[j][k] = tri.pt[j].p.v[k];
+ ptri->normals[j][k] = tri.pt[j].n.v[k];
+// ptri->colors[j][k] = tri.pt[j].c.v[k];
+ }
+
+ ptri->texcoords[j][0] = tri.pt[j].u;
+ ptri->texcoords[j][1] = tri.pt[j].v;
+ }
+
+ ptri++;
+ if ((ptri - tripool ) >= POLYSET_MAXTRIANGLES)
+ Error ("Error: too many triangles; increase POLYSET_MAXTRIANGLES\n");
+ }
+}
+
+void TRI_LoadPolysets( const char *filename, polyset_t **ppPSET, int *numpsets )
+{
+ FILE *input;
+ float start;
+ char name[256], tex[256];
+ int i, count, magic, pset = 0;
+ triangle_t *ptri;
+ polyset_t *pPSET;
+ int iLevel;
+ int exitpattern;
+ float t;
+
+ t = -FLOAT_START;
+ *((unsigned char *)&exitpattern + 0) = *((unsigned char *)&t + 3);
+ *((unsigned char *)&exitpattern + 1) = *((unsigned char *)&t + 2);
+ *((unsigned char *)&exitpattern + 2) = *((unsigned char *)&t + 1);
+ *((unsigned char *)&exitpattern + 3) = *((unsigned char *)&t + 0);
+
+ if ((input = fopen(filename, "rb")) == 0)
+ Error ("reader: could not open file '%s'", filename);
+
+ iLevel = 0;
+
+ fread(&magic, sizeof(int), 1, input);
+ if (BigLong(magic) != MAGIC)
+ Error ("%s is not a Alias object separated triangle file, magic number is wrong.", filename);
+
+ pPSET = calloc( 1, POLYSET_MAXPOLYSETS * sizeof( polyset_t ) );
+ ptri = calloc( 1, POLYSET_MAXTRIANGLES * sizeof( triangle_t ) );
+
+ *ppPSET = pPSET;
+
+ while (feof(input) == 0) {
+ if (fread(&start, sizeof(float), 1, input) < 1)
+ break;
+ *(int *)&start = BigLong(*(int *)&start);
+ if (*(int *)&start != exitpattern)
+ {
+ if (start == FLOAT_START) {
+ /* Start of an object or group of objects. */
+ i = -1;
+ do {
+ /* There are probably better ways to read a string from */
+ /* a file, but this does allow you to do error checking */
+ /* (which I'm not doing) on a per character basis. */
+ ++i;
+ fread( &(name[i]), sizeof( char ), 1, input);
+ } while( name[i] != '\0' );
+
+ if ( i != 0 )
+ strncpy( pPSET[pset].name, name, sizeof( pPSET[pset].name ) - 1 );
+ else
+ strcpy( pPSET[pset].name , "(unnamed)" );
+ strlwr( pPSET[pset].name );
+
+// indent();
+// fprintf(stdout,"OBJECT START: %s\n",name);
+ fread( &count, sizeof(int), 1, input);
+ count = BigLong(count);
+ ++iLevel;
+ if (count != 0) {
+// indent();
+// fprintf(stdout,"NUMBER OF TRIANGLES: %d\n",count);
+
+ i = -1;
+ do {
+ ++i;
+ fread( &(tex[i]), sizeof( char ), 1, input);
+ } while( tex[i] != '\0' );
+
+/*
+ if ( i != 0 )
+ strncpy( pPSET[pset].texname, tex, sizeof( pPSET[pset].texname ) - 1 );
+ else
+ strcpy( pPSET[pset].texname, "(unnamed)" );
+ strlwr( pPSET[pset].texname );
+*/
+
+// indent();
+// fprintf(stdout," Object texture name: '%s'\n",tex);
+ }
+
+ /* Else (count == 0) this is the start of a group, and */
+ /* no texture name is present. */
+ }
+ else if (start == FLOAT_END) {
+ /* End of an object or group. Yes, the name should be */
+ /* obvious from context, but it is in here just to be */
+ /* safe and to provide a little extra information for */
+ /* those who do not wish to write a recursive reader. */
+ /* Mea culpa. */
+ --iLevel;
+ i = -1;
+ do {
+ ++i;
+ fread( &(name[i]), sizeof( char ), 1, input);
+ } while( name[i] != '\0' );
+
+ if ( i != 0 )
+ strncpy( pPSET[pset].name, name, sizeof( pPSET[pset].name ) - 1 );
+ else
+ strcpy( pPSET[pset].name , "(unnamed)" );
+
+ strlwr( pPSET[pset].name );
+
+// indent();
+// fprintf(stdout,"OBJECT END: %s\n",name);
+ continue;
+ }
+ }
+
+//
+// read the triangles
+//
+ if ( count > 0 )
+ {
+ pPSET[pset].triangles = ptri;
+ ReadPolysetGeometry( pPSET[0].triangles, input, count, ptri );
+ ptri += count;
+ pPSET[pset].numtriangles = count;
+ if ( ++pset >= POLYSET_MAXPOLYSETS )
+ {
+ Error ("Error: too many polysets; increase POLYSET_MAXPOLYSETS\n");
+ }
+ }
+ }
+
+ *numpsets = pset;
+
+ fclose (input);
+}
+
diff --git a/common/trilib.h b/common/trilib.h
new file mode 100755
index 0000000..a823411
--- /dev/null
+++ b/common/trilib.h
@@ -0,0 +1,26 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// trilib.h: header file for loading triangles from an Alias triangle file
+//
+void TRI_LoadPolysets( const char *filename, polyset_t **ppPSET, int *numpsets );
+
diff --git a/lcc/COPYRIGHT b/lcc/COPYRIGHT
new file mode 100755
index 0000000..f98a895
--- /dev/null
+++ b/lcc/COPYRIGHT
@@ -0,0 +1,61 @@
+The authors of this software are Christopher W. Fraser and
+David R. Hanson.
+
+Copyright (c) 1991,1992,1993,1994,1995,1996,1997,1998 by AT&T,
+Christopher W. Fraser, and David R. Hanson. All Rights Reserved.
+
+Permission to use, copy, modify, and distribute this software for any
+purpose, subject to the provisions described below, without fee is
+hereby granted, provided that this entire notice is included in all
+copies of any software that is or includes a copy or modification of
+this software and in all copies of the supporting documentation for
+such software.
+
+THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
+WARRANTY. IN PARTICULAR, NEITHER THE AUTHORS NOR AT&T MAKE ANY
+REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
+OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
+
+
+lcc is not public-domain software, shareware, and it is not protected
+by a `copyleft' agreement, like the code from the Free Software
+Foundation.
+
+lcc is available free for your personal research and instructional use
+under the `fair use' provisions of the copyright law. You may, however,
+redistribute lcc in whole or in part provided you acknowledge its
+source and include this CPYRIGHT file. You may, for example, include
+the distribution in a CDROM of free software, provided you charge only
+for the media, or mirror the distribution files at your site.
+
+You may not sell lcc or any product derived from it in which it is a
+significant part of the value of the product. Using the lcc front end
+to build a C syntax checker is an example of this kind of product.
+
+You may use parts of lcc in products as long as you charge for only
+those components that are entirely your own and you acknowledge the use
+of lcc clearly in all product documentation and distribution media. You
+must state clearly that your product uses or is based on parts of lcc
+and that lcc is available free of charge. You must also request that
+bug reports on your product be reported to you. Using the lcc front
+end to build a C compiler for the Motorola 88000 chip and charging for
+and distributing only the 88000 code generator is an example of this
+kind of product.
+
+Using parts of lcc in other products is more problematic. For example,
+using parts of lcc in a C++ compiler could save substantial time and
+effort and therefore contribute significantly to the profitability of
+the product. This kind of use, or any use where others stand to make a
+profit from what is primarily our work, requires a license agreement
+with Addison-Wesley. Per-copy and unlimited use licenses are
+available; for more information, contact
+
+ J. Carter Shanklin
+ Addison Wesley Longman, Inc.
+ 2725 Sand Hill Rd.
+ Menlo Park, CA 94025
+ 650/854-0300 x2478 FAX: 650/614-2930 jcs@awl.com
+-----
+Chris Fraser / cwfraser@microsoft.com
+David Hanson / drh@microsoft.com
+$Revision: 145 $ $Date: 2001-10-17 16:53:10 -0500 (Wed, 17 Oct 2001) $
diff --git a/lcc/LOG b/lcc/LOG
new file mode 100755
index 0000000..3d83da3
--- /dev/null
+++ b/lcc/LOG
@@ -0,0 +1,91 @@
+From lcc 4.0 to 4.1:
+
+Changes:
+
+See doc/4.html for changes in the code-generation interface.
+
+Warns about constants that are too large, eg, short x = 70000;
+
+Warns about expressions that have no effect.
+
+Unsigned shorts are now used for wide-character constants, and
+wchar_t is a typedef for unsigned short.
+
+More assertions in gen.c to confirm that the register allocator is
+configured correctly; ie, that the various masks, wildcards,
+clobbers, and targets are internally consistent. Full checking
+appears impractical, but there's still more than than there was
+before.
+
+On the SPARC, lcc now emits .type and .size directives
+unconditionally.
+
+On the x86, constants are now emitted into the text segment.
+
+If the environment variable "LCCDIR" is defined, it gives the directory
+that contains the preprocessor, the compiler proper, and the
+lcc-specific libraries.
+
+Under Windows, lcc searches the directories named in the environment
+variable "include" for header files.
+
+Errors fixed:
+
+Erroneously complained about unknown sizes for some const fields, eg,
+typedef struct foo ref; struct foo { const ref *q; int a; };
+f(ref *p, int i) { return p->q[i].a; }
+
+-A -A erroneously complained about static main's that didn't conform
+to the ANSI-mandated "int main(void)" or "int main(int, char **)".
+
+Silently generated incorrect code for a structure copy with a
+post-incremented target, eg,
+struct { int x; } data = {1}, copy[2], *q = copy;
+main() { *q++ = data; }
+
+Generated incorrect values in some expressions with constant pointers.
+
+Silently truncated string literals longer than 4095 characters.
+
+Failed to emit debugging information for uninitialized globals.
+
+Failed to diagnose missing sizes in some multi-dimensioned array
+declarators, eg, extern int x[][10]; int x[5][];
+
+Silently emitted incorrect sizes and initalizations for some
+incomplete multi-dimensioned arrays involving pointers and whose size
+is determined by the number of initializers.
+
+Set only the x.name field for some back-end symbols (eg, wildcards),
+and the uninitialized name field crashed some debugging output.
+
+uses() failed to check the register *set* as well as the register
+mask. There's no known bug demo, but a wildcard set might be
+contrived that would need the test.
+
+Crashed with -b on some conditional expressions involving calls, eg,
+int p; void g(void) { p ? f() : 1; }
+
+On the MIPS, sometimes generated an incorrect frame size and thus a
+crash when floating-point registers were saved.
+
+On the SPARC, erroneously reused a register variable as a temporary
+when the variable is compiler-generated.
+
+On the SPARC with -b, emitted incorrect code for returning structs.
+
+On the x86, conversion from float to int rounded instead of truncated
+with the default floating-point mode.
+
+On the x86, eliminate rtargets for kids after the first (see p. 419).
+
+On the x86, substitute reg for freg, in order to use the common reg
+rules. Needed only for debugging output, since we're not using any
+float regs as regs at this time.
+
+On the x86, "double f(); main(){f();}" wasn't popping the FP register stack.
+
+On the x86, ECX was saved by the callee, when it should have been
+saved by the caller.
+
+$Id: LOG 145 2001-10-17 21:53:10Z timo $
diff --git a/lcc/README b/lcc/README
new file mode 100755
index 0000000..4f64dee
--- /dev/null
+++ b/lcc/README
@@ -0,0 +1,21 @@
+This hierarchy is the distribution for lcc version 4.1.
+
+lcc version 3.x is described in the book "A Retargetable C Compiler:
+Design and Implementation" (Addison-Wesley, 1995, ISBN 0-8053-1670-1).
+There are significant differences between 3.x and 4.x, most notably in
+the intermediate code. doc/4.html summarizes the differences.
+
+VERSION 4.1 IS INCOMPATIBLE WITH EARLIER VERSIONS OF LCC. DO NOT
+UNLOAD THIS DISTRIBUTION ON TOP OF A 3.X DISTRIBUTION.
+
+LOG describes the changes since the last release.
+
+CPYRIGHT describes the conditions under you can use, copy, modify, and
+distribute lcc or works derived from lcc.
+
+doc/install.html is an HTML file that gives a complete description of
+the distribution and installation instructions.
+
+Chris Fraser / cwfraser@microsoft.com
+David Hanson / drh@microsoft.com
+$Revision: 145 $ $Date: 2001-10-17 16:53:10 -0500 (Wed, 17 Oct 2001) $
diff --git a/lcc/README.id b/lcc/README.id
new file mode 100755
index 0000000..2277953
--- /dev/null
+++ b/lcc/README.id
@@ -0,0 +1,3 @@
+2001-10-31 Timothee Besset <ttimo@idsoftware.com>
+updated from the $/source/lcc code
+modified for portability and use with >= 1.31 mod source release
diff --git a/lcc/alpha/osf/tst/8q.1bk b/lcc/alpha/osf/tst/8q.1bk
new file mode 100755
index 0000000..c66df8e
--- /dev/null
+++ b/lcc/alpha/osf/tst/8q.1bk
@@ -0,0 +1,92 @@
+1 5 8 6 3 7 2 4
+1 6 8 3 7 4 2 5
+1 7 4 6 8 2 5 3
+1 7 5 8 2 4 6 3
+2 4 6 8 3 1 7 5
+2 5 7 1 3 8 6 4
+2 5 7 4 1 8 6 3
+2 6 1 7 4 8 3 5
+2 6 8 3 1 4 7 5
+2 7 3 6 8 5 1 4
+2 7 5 8 1 4 6 3
+2 8 6 1 3 5 7 4
+3 1 7 5 8 2 4 6
+3 5 2 8 1 7 4 6
+3 5 2 8 6 4 7 1
+3 5 7 1 4 2 8 6
+3 5 8 4 1 7 2 6
+3 6 2 5 8 1 7 4
+3 6 2 7 1 4 8 5
+3 6 2 7 5 1 8 4
+3 6 4 1 8 5 7 2
+3 6 4 2 8 5 7 1
+3 6 8 1 4 7 5 2
+3 6 8 1 5 7 2 4
+3 6 8 2 4 1 7 5
+3 7 2 8 5 1 4 6
+3 7 2 8 6 4 1 5
+3 8 4 7 1 6 2 5
+4 1 5 8 2 7 3 6
+4 1 5 8 6 3 7 2
+4 2 5 8 6 1 3 7
+4 2 7 3 6 8 1 5
+4 2 7 3 6 8 5 1
+4 2 7 5 1 8 6 3
+4 2 8 5 7 1 3 6
+4 2 8 6 1 3 5 7
+4 6 1 5 2 8 3 7
+4 6 8 2 7 1 3 5
+4 6 8 3 1 7 5 2
+4 7 1 8 5 2 6 3
+4 7 3 8 2 5 1 6
+4 7 5 2 6 1 3 8
+4 7 5 3 1 6 8 2
+4 8 1 3 6 2 7 5
+4 8 1 5 7 2 6 3
+4 8 5 3 1 7 2 6
+5 1 4 6 8 2 7 3
+5 1 8 4 2 7 3 6
+5 1 8 6 3 7 2 4
+5 2 4 6 8 3 1 7
+5 2 4 7 3 8 6 1
+5 2 6 1 7 4 8 3
+5 2 8 1 4 7 3 6
+5 3 1 6 8 2 4 7
+5 3 1 7 2 8 6 4
+5 3 8 4 7 1 6 2
+5 7 1 3 8 6 4 2
+5 7 1 4 2 8 6 3
+5 7 2 4 8 1 3 6
+5 7 2 6 3 1 4 8
+5 7 2 6 3 1 8 4
+5 7 4 1 3 8 6 2
+5 8 4 1 3 6 2 7
+5 8 4 1 7 2 6 3
+6 1 5 2 8 3 7 4
+6 2 7 1 3 5 8 4
+6 2 7 1 4 8 5 3
+6 3 1 7 5 8 2 4
+6 3 1 8 4 2 7 5
+6 3 1 8 5 2 4 7
+6 3 5 7 1 4 2 8
+6 3 5 8 1 4 2 7
+6 3 7 2 4 8 1 5
+6 3 7 2 8 5 1 4
+6 3 7 4 1 8 2 5
+6 4 1 5 8 2 7 3
+6 4 2 8 5 7 1 3
+6 4 7 1 3 5 2 8
+6 4 7 1 8 2 5 3
+6 8 2 4 1 7 5 3
+7 1 3 8 6 4 2 5
+7 2 4 1 8 5 3 6
+7 2 6 3 1 4 8 5
+7 3 1 6 8 5 2 4
+7 3 8 2 5 1 6 4
+7 4 2 5 8 1 3 6
+7 4 2 8 6 1 3 5
+7 5 3 1 6 8 2 4
+8 2 4 1 7 5 3 6
+8 2 5 3 1 7 4 6
+8 3 1 6 2 5 7 4
+8 4 1 3 6 2 7 5
diff --git a/lcc/alpha/osf/tst/8q.2bk b/lcc/alpha/osf/tst/8q.2bk
new file mode 100755
index 0000000..fb28350
--- /dev/null
+++ b/lcc/alpha/osf/tst/8q.2bk
@@ -0,0 +1,2 @@
+tst/8q.c:30: warning: missing return value
+tst/8q.c:39: warning: missing return value
diff --git a/lcc/alpha/osf/tst/8q.sbk b/lcc/alpha/osf/tst/8q.sbk
new file mode 100755
index 0000000..df86e78
--- /dev/null
+++ b/lcc/alpha/osf/tst/8q.sbk
@@ -0,0 +1,193 @@
+.globl main
+.text
+.text
+.ent main
+main:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4004000,-72
+.frame $sp,80,$26,48
+stq $14,0($sp)
+stq $26,8($sp)
+.prologue 1
+mov $31,$14
+L.2:
+sll $14,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+lda $25,1
+stl $25,down($27)
+stl $25,up($27)
+L.3:
+lda $14,1($14)
+cmplt $14,15,$23
+bne $23,L.2
+mov $31,$14
+L.6:
+sll $14,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+lda $25,1
+stl $25,rows($27)
+L.7:
+lda $14,1($14)
+cmplt $14,8,$23
+bne $23,L.6
+mov $31,$16
+jsr $26,queens
+ldgp $gp,0($26)
+mov $31,$0
+L.1:
+ldq $14,0($sp)
+ldq $26,8($sp)
+lda $sp,80($sp)
+ret
+.end main
+.globl queens
+.text
+.ent queens
+queens:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4006000,-64
+.frame $sp,80,$26,48
+stq $13,0($sp)
+stq $14,8($sp)
+stq $26,16($sp)
+mov $16,$14
+.prologue 1
+mov $31,$13
+L.11:
+sll $13,8*(8-4),$25
+sra $25,8*(8-4),$25
+sll $25,2,$25
+ldl $25,rows($25)
+cmpeq $25,$31,$23
+bne $23,L.15
+subl $13,$14,$25
+lda $25,7($25)
+sll $25,8*(8-4),$25
+sra $25,8*(8-4),$25
+sll $25,2,$25
+ldl $25,up($25)
+cmpeq $25,$31,$23
+bne $23,L.15
+addl $13,$14,$25
+sll $25,8*(8-4),$25
+sra $25,8*(8-4),$25
+sll $25,2,$25
+ldl $25,down($25)
+cmpeq $25,$31,$23
+bne $23,L.15
+addl $13,$14,$25
+sll $25,8*(8-4),$25
+sra $25,8*(8-4),$25
+sll $25,2,$25
+stl $31,down($25)
+subl $13,$14,$25
+lda $25,7($25)
+sll $25,8*(8-4),$25
+sra $25,8*(8-4),$25
+sll $25,2,$25
+stl $31,up($25)
+sll $13,8*(8-4),$25
+sra $25,8*(8-4),$25
+sll $25,2,$25
+stl $31,rows($25)
+sll $14,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+stl $13,x($27)
+cmpeq $14,7,$23
+beq $23,L.17
+jsr $26,print
+ldgp $gp,0($26)
+br L.18
+L.17:
+lda $16,1($14)
+jsr $26,queens
+ldgp $gp,0($26)
+L.18:
+lda $27,1
+addl $13,$14,$25
+sll $25,8*(8-4),$25
+sra $25,8*(8-4),$25
+sll $25,2,$25
+stl $27,down($25)
+subl $13,$14,$25
+lda $25,7($25)
+sll $25,8*(8-4),$25
+sra $25,8*(8-4),$25
+sll $25,2,$25
+stl $27,up($25)
+sll $13,8*(8-4),$25
+sra $25,8*(8-4),$25
+sll $25,2,$25
+stl $27,rows($25)
+L.15:
+L.12:
+lda $13,1($13)
+cmplt $13,8,$23
+bne $23,L.11
+mov $31,$0
+L.10:
+ldq $13,0($sp)
+ldq $14,8($sp)
+ldq $26,16($sp)
+lda $sp,80($sp)
+ret
+.end queens
+.globl print
+.text
+.ent print
+print:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4004000,-72
+.frame $sp,80,$26,48
+stq $14,0($sp)
+stq $26,8($sp)
+.prologue 1
+mov $31,$14
+L.20:
+lda $16,L.24
+sll $14,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+ldl $27,x($27)
+lda $17,49($27)
+jsr $26,printf
+ldgp $gp,0($26)
+L.21:
+lda $14,1($14)
+cmplt $14,8,$23
+bne $23,L.20
+lda $16,L.25
+jsr $26,printf
+ldgp $gp,0($26)
+mov $31,$0
+L.19:
+ldq $14,0($sp)
+ldq $26,8($sp)
+lda $sp,80($sp)
+ret
+.end print
+.globl x
+.comm x,32
+.globl rows
+.comm rows,32
+.globl down
+.comm down,60
+.globl up
+.comm up,60
+.rdata
+.align 0
+L.25:
+.byte 10
+.byte 0
+.align 0
+L.24:
+.byte 37
+.byte 99
+.byte 32
+.byte 0
diff --git a/lcc/alpha/osf/tst/array.1bk b/lcc/alpha/osf/tst/array.1bk
new file mode 100755
index 0000000..e188568
--- /dev/null
+++ b/lcc/alpha/osf/tst/array.1bk
@@ -0,0 +1,4 @@
+ 0 1 2 3 1000 1001 1002 1003 2000 2001 2002 2003
+ 0 1 2 3 1000 1001 1002 1003 2000 2001 2002 2003
+ 0 1 2 3 1000 1001 1002 1003 2000 2001 2002 2003
+ 0 1 2 3 1000 1001 1002 1003 2000 2001 2002 2003
diff --git a/lcc/alpha/osf/tst/array.2bk b/lcc/alpha/osf/tst/array.2bk
new file mode 100755
index 0000000..0a9b206
--- /dev/null
+++ b/lcc/alpha/osf/tst/array.2bk
@@ -0,0 +1,2 @@
+tst/array.c:33: warning: missing return value
+tst/array.c:48: warning: missing return value
diff --git a/lcc/alpha/osf/tst/array.sbk b/lcc/alpha/osf/tst/array.sbk
new file mode 100755
index 0000000..f47573a
--- /dev/null
+++ b/lcc/alpha/osf/tst/array.sbk
@@ -0,0 +1,260 @@
+.globl main
+.text
+.text
+.ent main
+main:
+ldgp $gp,0($27)
+lda $sp,-144($sp)
+.mask 0x4007000,-120
+.frame $sp,144,$26,48
+stq $12,0($sp)
+stq $13,8($sp)
+stq $14,16($sp)
+stq $26,24($sp)
+.prologue 1
+mov $31,$13
+L.2:
+mov $31,$14
+L.6:
+sll $14,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+sll $13,8*(8-4),$25
+sra $25,8*(8-4),$25
+sll $25,4,$25
+lda $25,x($25)
+addq $27,$25,$27
+lda $25,1000
+mull $25,$13,$25
+addl $25,$14,$25
+stl $25,($27)
+L.7:
+lda $14,1($14)
+cmplt $14,4,$23
+bne $23,L.6
+sll $13,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,3,$25
+sll $27,4,$27
+lda $27,x($27)
+stq $27,y($25)
+L.3:
+lda $13,1($13)
+cmplt $13,3,$23
+bne $23,L.2
+jsr $26,f
+ldgp $gp,0($26)
+mov $31,$13
+L.10:
+sll $13,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,4,$25
+lda $22,-104+144($sp)
+addq $25,$22,$25
+mov $25,$12
+sll $27,3,$27
+stq $25,y($27)
+mov $31,$14
+L.14:
+sll $14,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+addq $27,$12,$25
+sll $13,8*(8-4),$22
+sra $22,8*(8-4),$22
+sll $22,4,$22
+lda $22,x($22)
+addq $27,$22,$27
+ldl $27,($27)
+stl $27,($25)
+L.15:
+lda $14,1($14)
+cmplt $14,4,$23
+bne $23,L.14
+L.11:
+lda $13,1($13)
+cmplt $13,3,$23
+bne $23,L.10
+lda $16,-104+144($sp)
+lda $17,y
+jsr $26,g
+ldgp $gp,0($26)
+mov $31,$0
+L.1:
+ldq $12,0($sp)
+ldq $13,8($sp)
+ldq $14,16($sp)
+ldq $26,24($sp)
+lda $sp,144($sp)
+ret
+.end main
+.globl f
+.text
+.ent f
+f:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4006000,-64
+.frame $sp,80,$26,48
+stq $13,0($sp)
+stq $14,8($sp)
+stq $26,16($sp)
+.prologue 1
+mov $31,$13
+L.19:
+mov $31,$14
+L.23:
+lda $16,L.27
+sll $14,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+sll $13,8*(8-4),$25
+sra $25,8*(8-4),$25
+sll $25,4,$25
+lda $25,x($25)
+addq $27,$25,$27
+ldl $17,($27)
+jsr $26,printf
+ldgp $gp,0($26)
+L.24:
+lda $14,1($14)
+cmplt $14,4,$23
+bne $23,L.23
+L.20:
+lda $13,1($13)
+cmplt $13,3,$23
+bne $23,L.19
+lda $16,L.28
+jsr $26,printf
+ldgp $gp,0($26)
+mov $31,$13
+L.29:
+mov $31,$14
+L.33:
+lda $16,L.27
+sll $14,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+sll $13,8*(8-4),$25
+sra $25,8*(8-4),$25
+sll $25,3,$25
+ldq $25,y($25)
+addq $27,$25,$27
+ldl $17,($27)
+jsr $26,printf
+ldgp $gp,0($26)
+L.34:
+lda $14,1($14)
+cmplt $14,4,$23
+bne $23,L.33
+L.30:
+lda $13,1($13)
+cmplt $13,3,$23
+bne $23,L.29
+lda $16,L.28
+jsr $26,printf
+ldgp $gp,0($26)
+mov $31,$0
+L.18:
+ldq $13,0($sp)
+ldq $14,8($sp)
+ldq $26,16($sp)
+lda $sp,80($sp)
+ret
+.end f
+.globl g
+.text
+.ent g
+g:
+ldgp $gp,0($27)
+lda $sp,-96($sp)
+.mask 0x4007800,-64
+.frame $sp,96,$26,48
+stq $11,0($sp)
+stq $12,8($sp)
+stq $13,16($sp)
+stq $14,24($sp)
+stq $26,32($sp)
+mov $16,$14
+mov $17,$13
+.prologue 1
+mov $31,$11
+L.38:
+mov $31,$12
+L.42:
+lda $16,L.27
+sll $12,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+sll $11,8*(8-4),$25
+sra $25,8*(8-4),$25
+sll $25,4,$25
+addq $25,$14,$25
+addq $27,$25,$27
+ldl $17,($27)
+jsr $26,printf
+ldgp $gp,0($26)
+L.43:
+lda $12,1($12)
+cmplt $12,4,$23
+bne $23,L.42
+L.39:
+lda $11,1($11)
+cmplt $11,3,$23
+bne $23,L.38
+lda $16,L.28
+jsr $26,printf
+ldgp $gp,0($26)
+mov $31,$11
+L.46:
+mov $31,$12
+L.50:
+lda $16,L.27
+sll $12,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+sll $11,8*(8-4),$25
+sra $25,8*(8-4),$25
+sll $25,3,$25
+addq $25,$13,$25
+ldq $25,($25)
+addq $27,$25,$27
+ldl $17,($27)
+jsr $26,printf
+ldgp $gp,0($26)
+L.51:
+lda $12,1($12)
+cmplt $12,4,$23
+bne $23,L.50
+L.47:
+lda $11,1($11)
+cmplt $11,3,$23
+bne $23,L.46
+lda $16,L.28
+jsr $26,printf
+ldgp $gp,0($26)
+mov $31,$0
+L.37:
+ldq $11,0($sp)
+ldq $12,8($sp)
+ldq $13,16($sp)
+ldq $14,24($sp)
+ldq $26,32($sp)
+lda $sp,96($sp)
+ret
+.end g
+.globl y
+.comm y,24
+.globl x
+.comm x,48
+.rdata
+.align 0
+L.28:
+.byte 10
+.byte 0
+.align 0
+L.27:
+.byte 32
+.byte 37
+.byte 100
+.byte 0
diff --git a/lcc/alpha/osf/tst/cf.1bk b/lcc/alpha/osf/tst/cf.1bk
new file mode 100755
index 0000000..24e21ba
--- /dev/null
+++ b/lcc/alpha/osf/tst/cf.1bk
@@ -0,0 +1,51 @@
+char freq
+011 8.1
+012 6.1
+040 11.9
+! 0.2
+" 1.5
+% 0.6
+& 0.4
+' 0.4
+( 2.9
+) 2.9
+* 0.8
++ 1.3
+, 1.3
+- 0.4
+. 0.6
+/ 1.0
+0 2.5
+1 1.9
+2 0.6
+3 0.2
+7 0.4
+8 0.2
+; 3.8
+< 0.8
+= 2.7
+> 0.2
+[ 1.5
+\ 0.8
+] 1.5
+a 3.1
+c 4.4
+e 2.3
+f 6.0
+g 1.3
+h 1.0
+i 5.0
+l 1.0
+m 0.2
+n 3.3
+o 2.1
+p 1.0
+q 0.4
+r 4.2
+s 0.6
+t 3.8
+u 1.2
+v 0.6
+w 0.2
+{ 0.6
+} 0.6
diff --git a/lcc/alpha/osf/tst/cf.2bk b/lcc/alpha/osf/tst/cf.2bk
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/alpha/osf/tst/cf.2bk
diff --git a/lcc/alpha/osf/tst/cf.sbk b/lcc/alpha/osf/tst/cf.sbk
new file mode 100755
index 0000000..16683fa
--- /dev/null
+++ b/lcc/alpha/osf/tst/cf.sbk
@@ -0,0 +1,170 @@
+.globl main
+.text
+.text
+.ent main
+main:
+ldgp $gp,0($27)
+lda $sp,-96($sp)
+.fmask 0x200,-96
+.mask 0x4007000,-64
+.frame $sp,96,$26,48
+stt $f9,0($sp)
+stq $12,8($sp)
+stq $13,16($sp)
+stq $14,24($sp)
+stq $26,32($sp)
+stq $16,48($sp)
+stq $17,56($sp)
+.prologue 1
+ldl $27,-48+96($sp)
+cmple $27,1,$23
+beq $23,L.2
+lds $f9,L.4
+br L.3
+L.2:
+ldq $27,-40+96($sp)
+ldq $16,8($27)
+jsr $26,atof
+ldgp $gp,0($26)
+lds $f29,L.5
+divs $f0,$f29,$f9
+L.3:
+mov $31,$14
+L.6:
+mov $14,$27
+lda $14,1($27)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+lds $f30,L.4
+sts $f30,f($27)
+L.7:
+lda $27,127
+cmple $14,$27,$23
+bne $23,L.6
+mov $31,$13
+br L.11
+L.10:
+sll $12,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+lda $27,f($27)
+lds $f30,($27)
+lds $f29,L.13
+adds $f30,$f29,$f30
+sts $f30,($27)
+lda $13,1($13)
+L.11:
+jsr $26,getchar
+ldgp $gp,0($26)
+mov $0,$12
+lda $25,-1
+cmpeq $0,$25,$23
+beq $23,L.10
+lda $16,L.14
+jsr $26,printf
+ldgp $gp,0($26)
+mov $31,$14
+L.15:
+sll $14,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+lds $f30,f($27)
+lds $f29,L.4
+cmpteq $f30,$f29,$f1
+fbne $f1,L.19
+stq $13,-56+96($sp)
+ldt $f29,-56+96($sp)
+cvtqs $f29,$f29
+divs $f30,$f29,$f30
+cmptlt $f30,$f9,$f1
+fbne $f1,L.19
+cmple $14,32,$23
+beq $23,L.21
+lda $16,L.23
+mov $14,$17
+jsr $26,printf
+ldgp $gp,0($26)
+br L.22
+L.21:
+lda $16,L.24
+mov $14,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.22:
+lda $16,L.25
+lds $f30,L.5
+sll $14,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+lds $f29,f($27)
+muls $f30,$f29,$f30
+stq $13,-56+96($sp)
+ldt $f29,-56+96($sp)
+cvtqs $f29,$f29
+divs $f30,$f29,$f30
+cvtst $f30,$f17
+jsr $26,printf
+ldgp $gp,0($26)
+L.19:
+L.16:
+lda $14,1($14)
+lda $27,127
+cmple $14,$27,$23
+bne $23,L.15
+mov $31,$0
+L.1:
+ldt $f9,0($sp)
+ldq $12,8($sp)
+ldq $13,16($sp)
+ldq $14,24($sp)
+ldq $26,32($sp)
+lda $sp,96($sp)
+ret
+.end main
+.globl f
+.comm f,512
+.rdata
+.align 0
+L.25:
+.byte 9
+.byte 37
+.byte 46
+.byte 49
+.byte 102
+.byte 10
+.byte 0
+.align 0
+L.24:
+.byte 37
+.byte 99
+.byte 0
+.align 0
+L.23:
+.byte 37
+.byte 48
+.byte 51
+.byte 111
+.byte 0
+.align 0
+L.14:
+.byte 99
+.byte 104
+.byte 97
+.byte 114
+.byte 9
+.byte 102
+.byte 114
+.byte 101
+.byte 113
+.byte 10
+.byte 0
+.align 2
+L.13:
+.long 0x3f800000
+.align 2
+L.5:
+.long 0x42c80000
+.align 2
+L.4:
+.long 0x0
diff --git a/lcc/alpha/osf/tst/cq.1bk b/lcc/alpha/osf/tst/cq.1bk
new file mode 100755
index 0000000..d040603
--- /dev/null
+++ b/lcc/alpha/osf/tst/cq.1bk
@@ -0,0 +1,45 @@
+Section s22 returned 0.
+s241,er4
+Section s241 returned 4.
+Section s243 returned 0.
+Section s244 returned 0.
+Section s25 returned 0.
+ 8 bits in chars.
+ 32 bits in ints.
+ 16 bits in shorts.
+ 64 bits in longs.
+ 32 bits in unsigneds.
+ 32 bits in floats.
+ 64 bits in doubles.
+1.192093e-07 is the least number that can be added to 1. (float).
+2.220446e-16 is the least number that can be added to 1. (double).
+Section s26 returned 0.
+Section s4 returned 0.
+Section s61 returned 0.
+Section s626 returned 0.
+Section s71 returned 0.
+Section s72 returned 0.
+Section s757 returned 0.
+Section s7813 returned 0.
+Section s714 returned 0.
+Section s715 returned 0.
+Register count for char is unreliable.
+Register count for pointer is unreliable.
+Register count for int is unreliable.
+Section s81 returned 0.
+Section s84 returned 0.
+char alignment: 1
+short alignment: 2
+int alignment: 4
+long alignment: 8
+unsigned alignment: 4
+float alignment: 4
+double alignment: 8
+Sign extension in fields
+Be especially careful with 1-bit fields!
+Section s85 returned 0.
+Section s86 returned 0.
+Section s88 returned 0.
+Section s9 returned 0.
+
+Failed.
diff --git a/lcc/alpha/osf/tst/cq.2bk b/lcc/alpha/osf/tst/cq.2bk
new file mode 100755
index 0000000..f4e4562
--- /dev/null
+++ b/lcc/alpha/osf/tst/cq.2bk
@@ -0,0 +1,4 @@
+tst/cq.c:533: warning: missing return value
+tst/cq.c:1169: warning: missing return value
+tst/cq.c:5294: warning: unreachable code
+tst/cq.c:5303: warning: missing return value
diff --git a/lcc/alpha/osf/tst/cq.sbk b/lcc/alpha/osf/tst/cq.sbk
new file mode 100755
index 0000000..2971313
--- /dev/null
+++ b/lcc/alpha/osf/tst/cq.sbk
@@ -0,0 +1,16904 @@
+.sdata
+.align 3
+L.2:
+.quad s22
+.quad s241
+.quad s243
+.quad s244
+.quad s25
+.quad s26
+.quad s4
+.quad s61
+.quad s626
+.quad s71
+.quad s72
+.quad s757
+.quad s7813
+.quad s714
+.quad s715
+.quad s81
+.quad s84
+.quad s85
+.quad s86
+.quad s88
+.quad s9
+.lcomm L.3,68
+.lcomm L.4,8
+.globl main
+.text
+.text
+.ent main
+main:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4004000,-72
+.frame $sp,80,$26,48
+stq $14,0($sp)
+stq $26,8($sp)
+stq $16,32($sp)
+stq $17,40($sp)
+.prologue 1
+lda $27,1
+stl $27,L.3+36
+lda $27,1
+stl $27,L.3+40
+lda $27,1
+stl $27,L.3+44
+lda $27,1
+stl $27,L.3+48
+lda $27,L.3
+stq $27,L.4
+mov $31,$14
+br L.12
+L.9:
+ldq $16,L.4
+sll $14,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,3,$27
+ldq $27,L.2($27)
+jsr $26,($27)
+ldgp $gp,0($26)
+stl $0,L.3+52
+ldl $27,L.3+56
+ldl $25,L.3+52
+addl $27,$25,$27
+stl $27,L.3+56
+ldl $27,L.3+36
+cmpeq $27,$31,$23
+bne $23,L.17
+lda $16,L.20
+lda $17,L.3+60
+ldl $18,L.3+52
+jsr $26,printf
+ldgp $gp,0($26)
+L.17:
+L.10:
+lda $14,1($14)
+L.12:
+mov $14,$27
+lda $25,21
+cmpult $27,$25,$23
+bne $23,L.9
+ldl $27,L.3+56
+cmpeq $27,$31,$23
+beq $23,L.23
+lda $16,L.26
+jsr $26,printf
+ldgp $gp,0($26)
+br L.24
+L.23:
+lda $16,L.27
+jsr $26,printf
+ldgp $gp,0($26)
+L.24:
+mov $31,$0
+L.1:
+ldq $14,0($sp)
+ldq $26,8($sp)
+lda $sp,80($sp)
+ret
+.end main
+.sdata
+.align 0
+L.29:
+.byte 115
+.byte 50
+.byte 50
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.30:
+.byte 115
+.byte 50
+.byte 50
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s22
+.text
+.text
+.ent s22
+s22:
+ldgp $gp,0($27)
+lda $sp,-128($sp)
+.mask 0x5007800,-88
+.frame $sp,128,$26,48
+stq $11,0($sp)
+stq $12,8($sp)
+stq $13,16($sp)
+stq $14,24($sp)
+stq $24,32($sp)
+stq $26,40($sp)
+stq $16,80($sp)
+.prologue 1
+mov $31,$12
+lda $14,L.30
+ldq $27,-48+128($sp)
+lda $13,60($27)
+L.31:
+L.32:
+mov $13,$27
+lda $13,1($27)
+mov $14,$25
+lda $14,1($25)
+ldb $25,($25)
+stb $25,($27)
+sll $25,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,$31,$23
+beq $23,L.31
+lda $11,1
+lda $27,2
+stl $27,-64+128($sp)
+lda $27,3
+stl $27,-68+128($sp)
+lda $27,4
+stl $27,-60+128($sp)
+ldl $27,-64+128($sp)
+addl $11,$27,$27
+ldl $25,-68+128($sp)
+addl $27,$25,$27
+ldl $25,-60+128($sp)
+addl $27,$25,$27
+cmpeq $27,10,$23
+bne $23,L.34
+lda $12,1($12)
+ldq $27,-48+128($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.36
+lda $16,L.29
+lda $17,1
+jsr $26,printf
+ldgp $gp,0($26)
+L.36:
+L.34:
+lda $27,2
+stl $27,-72+128($sp)
+ldl $27,-72+128($sp)
+cmpeq $27,$11,$23
+beq $23,L.38
+lda $12,4($12)
+ldq $27,-48+128($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.40
+lda $16,L.29
+lda $17,4
+jsr $26,printf
+ldgp $gp,0($26)
+L.40:
+L.38:
+mov $12,$0
+L.28:
+ldq $11,0($sp)
+ldq $12,8($sp)
+ldq $13,16($sp)
+ldq $14,24($sp)
+ldq $24,32($sp)
+ldq $26,40($sp)
+lda $sp,128($sp)
+ret
+.end s22
+.sdata
+.align 0
+L.43:
+.byte 115
+.byte 50
+.byte 52
+.byte 49
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.44:
+.byte 115
+.byte 50
+.byte 52
+.byte 49
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.align 3
+L.45:
+.quad 0x0
+.quad 0x0
+.quad 0x0
+.quad 0x0
+.quad 0x0
+.quad 0x0
+.quad 0x0
+.quad 0x0
+.quad 0x0
+.quad 0x0
+.quad 0x0
+.quad 0x0
+.quad 0x0
+.quad 0x0
+.quad 0x0
+.quad 0x0
+.quad 0x0
+.quad 0x0
+.quad 0x6
+.quad 0x0
+.quad 0x8
+.quad 0x0
+.quad 0xc
+.quad 0x0
+.quad 0x10
+.quad 0x0
+.quad 0x12
+.quad 0x0
+.quad 0x14
+.quad 0x0
+.quad 0x18
+.quad 0x0
+.quad 0x1c
+.quad 0x0
+.quad 0x1e
+.quad 0x0
+.quad 0x20
+.quad 0x0
+.quad 0x24
+.globl s241
+.text
+.text
+.ent s241
+s241:
+ldgp $gp,0($27)
+lda $sp,-1072($sp)
+.mask 0x5007c00,-1024
+.frame $sp,1072,$26,48
+stq $10,0($sp)
+stq $11,8($sp)
+stq $12,16($sp)
+stq $13,24($sp)
+stq $14,32($sp)
+stq $24,40($sp)
+stq $26,48($sp)
+mov $16,$14
+.prologue 1
+mov $31,$10
+stl $31,-996+1072($sp)
+lda $12,L.44
+lda $11,60($14)
+L.46:
+L.47:
+mov $11,$27
+lda $11,1($27)
+mov $12,$25
+lda $12,1($25)
+ldb $25,($25)
+stb $25,($27)
+sll $25,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,$31,$23
+beq $23,L.46
+br L.49
+lda $10,1($10)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.51
+lda $16,L.43
+lda $17,1
+jsr $26,printf
+ldgp $gp,0($26)
+L.51:
+L.49:
+br L.53
+lda $10,2($10)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.55
+lda $16,L.43
+lda $17,2
+jsr $26,printf
+ldgp $gp,0($26)
+L.55:
+L.53:
+lda $10,4($10)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.59
+lda $16,L.43
+lda $17,4
+jsr $26,printf
+ldgp $gp,0($26)
+L.59:
+L.57:
+br L.61
+lda $10,8($10)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.63
+lda $16,L.43
+lda $17,8
+jsr $26,printf
+ldgp $gp,0($26)
+L.63:
+L.61:
+mov $31,$13
+L.65:
+sll $13,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,3,$25
+stq $27,L.45($25)
+L.66:
+lda $13,1($13)
+cmplt $13,17,$23
+bne $23,L.65
+lda $13,18
+L.69:
+sll $13,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,3,$27
+lda $27,L.45($27)
+stq $27,-1008+1072($sp)
+ldq $16,($27)
+jsr $26,pow2
+ldgp $gp,0($26)
+ldq $25,-1008+1072($sp)
+stq $0,($25)
+subl $13,1,$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,3,$27
+sll $13,8*(8-4),$25
+sra $25,8*(8-4),$25
+sll $25,3,$25
+ldq $25,L.45($25)
+subq $25,1,$25
+stq $25,L.45($27)
+lda $13,2($13)
+L.70:
+cmplt $13,39,$23
+bne $23,L.69
+stq $31,-368+1072($sp)
+stq $31,-680+1072($sp)
+stq $31,-992+1072($sp)
+lda $27,1
+stq $27,-360+1072($sp)
+lda $27,1
+stq $27,-672+1072($sp)
+lda $27,1
+stq $27,-984+1072($sp)
+lda $27,2
+stq $27,-352+1072($sp)
+lda $27,2
+stq $27,-664+1072($sp)
+lda $27,2
+stq $27,-976+1072($sp)
+lda $27,3
+stq $27,-344+1072($sp)
+lda $27,3
+stq $27,-656+1072($sp)
+lda $27,3
+stq $27,-968+1072($sp)
+lda $27,4
+stq $27,-336+1072($sp)
+lda $27,4
+stq $27,-648+1072($sp)
+lda $27,4
+stq $27,-960+1072($sp)
+lda $27,5
+stq $27,-328+1072($sp)
+lda $27,5
+stq $27,-640+1072($sp)
+lda $27,5
+stq $27,-952+1072($sp)
+lda $27,6
+stq $27,-320+1072($sp)
+lda $27,6
+stq $27,-632+1072($sp)
+lda $27,6
+stq $27,-944+1072($sp)
+lda $27,7
+stq $27,-312+1072($sp)
+lda $27,7
+stq $27,-624+1072($sp)
+lda $27,7
+stq $27,-936+1072($sp)
+lda $27,8
+stq $27,-304+1072($sp)
+lda $27,8
+stq $27,-616+1072($sp)
+lda $27,8
+stq $27,-928+1072($sp)
+lda $27,9
+stq $27,-296+1072($sp)
+lda $27,9
+stq $27,-608+1072($sp)
+lda $27,9
+stq $27,-920+1072($sp)
+lda $27,10
+stq $27,-288+1072($sp)
+lda $27,10
+stq $27,-600+1072($sp)
+lda $27,10
+stq $27,-912+1072($sp)
+lda $27,11
+stq $27,-280+1072($sp)
+lda $27,11
+stq $27,-592+1072($sp)
+lda $27,11
+stq $27,-904+1072($sp)
+lda $27,12
+stq $27,-272+1072($sp)
+lda $27,12
+stq $27,-584+1072($sp)
+lda $27,12
+stq $27,-896+1072($sp)
+lda $27,13
+stq $27,-264+1072($sp)
+lda $27,13
+stq $27,-576+1072($sp)
+lda $27,13
+stq $27,-888+1072($sp)
+lda $27,14
+stq $27,-256+1072($sp)
+lda $27,14
+stq $27,-568+1072($sp)
+lda $27,14
+stq $27,-880+1072($sp)
+lda $27,15
+stq $27,-248+1072($sp)
+lda $27,15
+stq $27,-560+1072($sp)
+lda $27,15
+stq $27,-872+1072($sp)
+lda $27,16
+stq $27,-240+1072($sp)
+lda $27,16
+stq $27,-552+1072($sp)
+lda $27,16
+stq $27,-864+1072($sp)
+lda $27,63
+stq $27,-232+1072($sp)
+lda $27,63
+stq $27,-544+1072($sp)
+lda $27,63
+stq $27,-856+1072($sp)
+lda $27,64
+stq $27,-224+1072($sp)
+lda $27,64
+stq $27,-536+1072($sp)
+lda $27,64
+stq $27,-848+1072($sp)
+lda $27,255
+stq $27,-216+1072($sp)
+lda $27,255
+stq $27,-528+1072($sp)
+lda $27,255
+stq $27,-840+1072($sp)
+lda $27,256
+stq $27,-208+1072($sp)
+lda $27,256
+stq $27,-520+1072($sp)
+lda $27,256
+stq $27,-832+1072($sp)
+lda $27,4095
+stq $27,-200+1072($sp)
+lda $27,4095
+stq $27,-512+1072($sp)
+lda $27,4095
+stq $27,-824+1072($sp)
+lda $27,4096
+stq $27,-192+1072($sp)
+lda $27,4096
+stq $27,-504+1072($sp)
+lda $27,4096
+stq $27,-816+1072($sp)
+lda $27,65535
+stq $27,-184+1072($sp)
+lda $27,65535
+stq $27,-496+1072($sp)
+lda $27,65535
+stq $27,-808+1072($sp)
+lda $27,65536
+stq $27,-176+1072($sp)
+lda $27,65536
+stq $27,-488+1072($sp)
+lda $27,65536
+stq $27,-800+1072($sp)
+lda $27,262143
+stq $27,-168+1072($sp)
+lda $27,262143
+stq $27,-480+1072($sp)
+lda $27,262143
+stq $27,-792+1072($sp)
+lda $27,262144
+stq $27,-160+1072($sp)
+lda $27,262144
+stq $27,-472+1072($sp)
+lda $27,262144
+stq $27,-784+1072($sp)
+lda $27,1048575
+stq $27,-152+1072($sp)
+lda $27,1048575
+stq $27,-464+1072($sp)
+lda $27,1048575
+stq $27,-776+1072($sp)
+lda $27,1048576
+stq $27,-144+1072($sp)
+lda $27,1048576
+stq $27,-456+1072($sp)
+lda $27,1048576
+stq $27,-768+1072($sp)
+lda $27,16777215
+stq $27,-136+1072($sp)
+lda $27,16777215
+stq $27,-448+1072($sp)
+lda $27,16777215
+stq $27,-760+1072($sp)
+lda $27,16777216
+stq $27,-128+1072($sp)
+lda $27,16777216
+stq $27,-440+1072($sp)
+lda $27,16777216
+stq $27,-752+1072($sp)
+lda $27,268435455
+stq $27,-120+1072($sp)
+lda $27,268435455
+stq $27,-432+1072($sp)
+lda $27,268435455
+stq $27,-744+1072($sp)
+lda $27,268435456
+stq $27,-112+1072($sp)
+lda $27,268435456
+stq $27,-424+1072($sp)
+lda $27,268435456
+stq $27,-736+1072($sp)
+lda $27,1073741823
+stq $27,-104+1072($sp)
+lda $27,1073741823
+stq $27,-416+1072($sp)
+lda $27,1073741823
+stq $27,-728+1072($sp)
+lda $27,1073741824
+stq $27,-96+1072($sp)
+lda $27,1073741824
+stq $27,-408+1072($sp)
+lda $27,1073741824
+stq $27,-720+1072($sp)
+lda $27,4294967295
+stq $27,-88+1072($sp)
+lda $27,4294967295
+stq $27,-400+1072($sp)
+lda $27,4294967295
+stq $27,-712+1072($sp)
+lda $27,4294967296
+stq $27,-80+1072($sp)
+lda $27,4294967296
+stq $27,-392+1072($sp)
+lda $27,4294967296
+stq $27,-704+1072($sp)
+lda $27,68719476735
+stq $27,-72+1072($sp)
+lda $27,68719476735
+stq $27,-384+1072($sp)
+lda $27,68719476735
+stq $27,-696+1072($sp)
+lda $27,68719476736
+stq $27,-64+1072($sp)
+lda $27,68719476736
+stq $27,-376+1072($sp)
+lda $27,68719476736
+stq $27,-688+1072($sp)
+mov $31,$13
+L.187:
+sll $13,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,3,$27
+lda $25,-368+1072($sp)
+addq $27,$25,$25
+ldq $25,($25)
+ldq $22,L.45($27)
+cmpeq $22,$25,$23
+beq $23,L.194
+lda $22,-680+1072($sp)
+addq $27,$22,$22
+ldq $22,($22)
+cmpeq $25,$22,$23
+beq $23,L.194
+lda $25,-992+1072($sp)
+addq $27,$25,$27
+ldq $27,($27)
+cmpeq $22,$27,$23
+bne $23,L.191
+L.194:
+ldl $27,40($14)
+cmpeq $27,$31,$23
+bne $23,L.195
+lda $16,L.197
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.198
+jsr $26,printf
+ldgp $gp,0($26)
+L.195:
+L.191:
+L.188:
+lda $13,1($13)
+cmplt $13,39,$23
+bne $23,L.187
+ldl $27,-996+1072($sp)
+cmpeq $27,$31,$23
+bne $23,L.199
+lda $10,16
+L.199:
+mov $10,$0
+L.42:
+ldq $10,0($sp)
+ldq $11,8($sp)
+ldq $12,16($sp)
+ldq $13,24($sp)
+ldq $14,32($sp)
+ldq $24,40($sp)
+ldq $26,48($sp)
+lda $sp,1072($sp)
+ret
+.end s241
+.globl pow2
+.text
+.ent pow2
+pow2:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4004000,-72
+.frame $sp,80,$26,48
+stq $14,0($sp)
+stq $26,8($sp)
+.prologue 1
+lda $14,1
+br L.203
+L.202:
+sll $14,1,$14
+L.203:
+mov $16,$27
+subq $27,1,$16
+cmpeq $27,$31,$23
+beq $23,L.202
+mov $14,$0
+L.201:
+ldq $14,0($sp)
+ldq $26,8($sp)
+lda $sp,80($sp)
+ret
+.end pow2
+.sdata
+.align 0
+L.206:
+.byte 115
+.byte 50
+.byte 52
+.byte 51
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.207:
+.byte 115
+.byte 50
+.byte 52
+.byte 51
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s243
+.text
+.text
+.ent s243
+s243:
+ldgp $gp,0($27)
+lda $sp,-352($sp)
+.mask 0x5007000,-320
+.frame $sp,352,$26,48
+stq $12,0($sp)
+stq $13,8($sp)
+stq $14,16($sp)
+stq $24,24($sp)
+stq $26,32($sp)
+stq $16,304($sp)
+.prologue 1
+mov $31,$12
+lda $14,L.207
+ldq $27,-48+352($sp)
+lda $13,60($27)
+L.208:
+L.209:
+mov $13,$27
+lda $13,1($27)
+mov $14,$25
+lda $14,1($25)
+ldb $25,($25)
+stb $25,($27)
+sll $25,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,$31,$23
+beq $23,L.208
+lda $16,-312+352($sp)
+jsr $26,zerofill
+ldgp $gp,0($26)
+lda $27,1
+stb $27,-215+352($sp)
+lda $27,1
+stb $27,-247+352($sp)
+lda $27,1
+stb $27,-186+352($sp)
+lda $27,1
+stb $27,-264+352($sp)
+lda $27,1
+stb $27,-214+352($sp)
+lda $27,1
+stb $27,-246+352($sp)
+lda $27,1
+stb $27,-279+352($sp)
+lda $27,1
+stb $27,-263+352($sp)
+lda $27,1
+stb $27,-213+352($sp)
+lda $27,1
+stb $27,-245+352($sp)
+lda $27,1
+stb $27,-278+352($sp)
+lda $27,1
+stb $27,-262+352($sp)
+lda $27,1
+stb $27,-212+352($sp)
+lda $27,1
+stb $27,-244+352($sp)
+lda $27,1
+stb $27,-277+352($sp)
+lda $27,1
+stb $27,-261+352($sp)
+lda $27,1
+stb $27,-211+352($sp)
+lda $27,1
+stb $27,-243+352($sp)
+lda $27,1
+stb $27,-275+352($sp)
+lda $27,1
+stb $27,-260+352($sp)
+lda $27,1
+stb $27,-210+352($sp)
+lda $27,1
+stb $27,-242+352($sp)
+lda $27,1
+stb $27,-274+352($sp)
+lda $27,1
+stb $27,-259+352($sp)
+lda $27,1
+stb $27,-209+352($sp)
+lda $27,1
+stb $27,-241+352($sp)
+lda $27,1
+stb $27,-272+352($sp)
+lda $27,1
+stb $27,-258+352($sp)
+lda $27,1
+stb $27,-208+352($sp)
+lda $27,1
+stb $27,-240+352($sp)
+lda $27,1
+stb $27,-271+352($sp)
+lda $27,1
+stb $27,-257+352($sp)
+lda $27,1
+stb $27,-207+352($sp)
+lda $27,1
+stb $27,-239+352($sp)
+lda $27,1
+stb $27,-217+352($sp)
+lda $27,1
+stb $27,-256+352($sp)
+lda $27,1
+stb $27,-206+352($sp)
+lda $27,1
+stb $27,-238+352($sp)
+lda $27,1
+stb $27,-251+352($sp)
+lda $27,1
+stb $27,-255+352($sp)
+lda $27,1
+stb $27,-205+352($sp)
+lda $27,1
+stb $27,-237+352($sp)
+lda $27,1
+stb $27,-267+352($sp)
+lda $27,1
+stb $27,-204+352($sp)
+lda $27,1
+stb $27,-236+352($sp)
+lda $27,1
+stb $27,-218+352($sp)
+lda $27,1
+stb $27,-203+352($sp)
+lda $27,1
+stb $27,-235+352($sp)
+lda $27,1
+stb $27,-188+352($sp)
+lda $27,1
+stb $27,-302+352($sp)
+lda $27,1
+stb $27,-202+352($sp)
+lda $27,1
+stb $27,-234+352($sp)
+lda $27,1
+stb $27,-303+352($sp)
+lda $27,1
+stb $27,-201+352($sp)
+lda $27,1
+stb $27,-233+352($sp)
+lda $27,1
+stb $27,-189+352($sp)
+lda $27,1
+stb $27,-304+352($sp)
+lda $27,1
+stb $27,-200+352($sp)
+lda $27,1
+stb $27,-232+352($sp)
+lda $27,1
+stb $27,-187+352($sp)
+lda $27,1
+stb $27,-299+352($sp)
+lda $27,1
+stb $27,-199+352($sp)
+lda $27,1
+stb $27,-231+352($sp)
+lda $27,1
+stb $27,-221+352($sp)
+lda $27,1
+stb $27,-300+352($sp)
+lda $27,1
+stb $27,-198+352($sp)
+lda $27,1
+stb $27,-230+352($sp)
+lda $27,1
+stb $27,-219+352($sp)
+lda $27,1
+stb $27,-197+352($sp)
+lda $27,1
+stb $27,-229+352($sp)
+lda $27,1
+stb $27,-269+352($sp)
+lda $27,1
+stb $27,-220+352($sp)
+lda $27,1
+stb $27,-196+352($sp)
+lda $27,1
+stb $27,-228+352($sp)
+lda $27,1
+stb $27,-253+352($sp)
+lda $27,1
+stb $27,-273+352($sp)
+lda $27,1
+stb $27,-195+352($sp)
+lda $27,1
+stb $27,-227+352($sp)
+lda $27,1
+stb $27,-270+352($sp)
+lda $27,1
+stb $27,-194+352($sp)
+lda $27,1
+stb $27,-226+352($sp)
+lda $27,1
+stb $27,-254+352($sp)
+lda $27,1
+stb $27,-312+352($sp)
+stb $27,-193+352($sp)
+lda $27,1
+stb $27,-225+352($sp)
+lda $27,1
+stb $27,-252+352($sp)
+lda $27,1
+stb $27,-280+352($sp)
+lda $27,1
+stb $27,-192+352($sp)
+lda $27,1
+stb $27,-224+352($sp)
+lda $27,1
+stb $27,-250+352($sp)
+lda $27,1
+stb $27,-191+352($sp)
+lda $27,1
+stb $27,-223+352($sp)
+lda $27,1
+stb $27,-268+352($sp)
+lda $27,1
+stb $27,-190+352($sp)
+lda $27,1
+stb $27,-222+352($sp)
+lda $27,1
+stb $27,-266+352($sp)
+lda $27,1
+stb $27,-249+352($sp)
+lda $27,1
+stb $27,-265+352($sp)
+lda $16,-312+352($sp)
+jsr $26,sumof
+ldgp $gp,0($26)
+lda $25,98
+cmpeq $0,$25,$23
+bne $23,L.308
+lda $12,1($12)
+ldq $27,-48+352($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.310
+lda $16,L.206
+lda $17,1
+jsr $26,printf
+ldgp $gp,0($26)
+L.310:
+L.308:
+br L.312
+lda $12,8($12)
+ldq $27,-48+352($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.314
+lda $16,L.206
+lda $17,8
+jsr $26,printf
+ldgp $gp,0($26)
+L.314:
+L.312:
+mov $12,$0
+L.205:
+ldq $12,0($sp)
+ldq $13,8($sp)
+ldq $14,16($sp)
+ldq $24,24($sp)
+ldq $26,32($sp)
+lda $sp,352($sp)
+ret
+.end s243
+.globl zerofill
+.text
+.ent zerofill
+zerofill:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x5004000,-64
+.frame $sp,80,$26,48
+stq $14,0($sp)
+stq $24,8($sp)
+stq $26,16($sp)
+.prologue 1
+mov $31,$14
+L.317:
+mov $16,$27
+lda $16,1($27)
+stb $31,($27)
+L.318:
+lda $14,1($14)
+lda $27,256
+cmplt $14,$27,$23
+bne $23,L.317
+mov $31,$0
+L.316:
+ldq $14,0($sp)
+ldq $24,8($sp)
+ldq $26,16($sp)
+lda $sp,80($sp)
+ret
+.end zerofill
+.globl sumof
+.text
+.ent sumof
+sumof:
+ldgp $gp,0($27)
+lda $sp,-96($sp)
+.mask 0x4007000,-72
+.frame $sp,96,$26,48
+stq $12,0($sp)
+stq $13,8($sp)
+stq $14,16($sp)
+stq $26,24($sp)
+.prologue 1
+mov $16,$12
+mov $31,$14
+mov $31,$13
+L.322:
+mov $12,$27
+lda $12,1($27)
+ldb $27,($27)
+addl $14,$27,$14
+L.323:
+lda $13,1($13)
+lda $27,256
+cmplt $13,$27,$23
+bne $23,L.322
+mov $14,$0
+L.321:
+ldq $12,0($sp)
+ldq $13,8($sp)
+ldq $14,16($sp)
+ldq $26,24($sp)
+lda $sp,96($sp)
+ret
+.end sumof
+.sdata
+.align 0
+L.327:
+.byte 115
+.byte 50
+.byte 52
+.byte 52
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.328:
+.byte 115
+.byte 50
+.byte 52
+.byte 52
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s244
+.text
+.text
+.ent s244
+s244:
+ldgp $gp,0($27)
+lda $sp,-176($sp)
+.mask 0x5007c00,-128
+.frame $sp,176,$26,48
+stq $10,0($sp)
+stq $11,8($sp)
+stq $12,16($sp)
+stq $13,24($sp)
+stq $14,32($sp)
+stq $24,40($sp)
+stq $26,48($sp)
+stq $16,128($sp)
+.prologue 1
+lda $13,L.328
+ldq $27,-48+176($sp)
+lda $12,60($27)
+L.329:
+L.330:
+mov $12,$27
+lda $12,1($27)
+mov $13,$25
+lda $13,1($25)
+ldb $25,($25)
+stb $25,($27)
+sll $25,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,$31,$23
+beq $23,L.329
+mov $31,$10
+mov $31,$11
+ldt $f30,L.332
+stt $f30,-120+176($sp)
+stt $f30,-112+176($sp)
+ldt $f30,L.332
+stt $f30,-104+176($sp)
+ldt $f30,L.332
+stt $f30,-96+176($sp)
+ldt $f30,L.332
+stt $f30,-88+176($sp)
+ldt $f30,L.332
+stt $f30,-80+176($sp)
+ldt $f30,L.332
+stt $f30,-72+176($sp)
+ldt $f30,L.332
+stt $f30,-64+176($sp)
+mov $31,$11
+mov $31,$14
+L.340:
+sll $14,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,3,$27
+lda $25,-120+176($sp)
+addq $27,$25,$27
+ldt $f30,($27)
+lda $27,1($14)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,3,$27
+lda $25,-120+176($sp)
+addq $27,$25,$27
+ldt $f29,($27)
+cmpteq $f30,$f29,$f1
+fbne $f1,L.344
+lda $11,1
+L.344:
+L.341:
+lda $14,1($14)
+cmplt $14,7,$23
+bne $23,L.340
+cmpeq $11,$31,$23
+bne $23,L.346
+ldq $27,-48+176($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.348
+lda $16,L.327
+lda $17,1
+jsr $26,printf
+ldgp $gp,0($26)
+L.348:
+lda $10,1($10)
+L.346:
+br L.350
+ldq $27,-48+176($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.352
+lda $16,L.327
+lda $17,2
+jsr $26,printf
+ldgp $gp,0($26)
+L.352:
+lda $10,2($10)
+L.350:
+mov $10,$0
+L.326:
+ldq $10,0($sp)
+ldq $11,8($sp)
+ldq $12,16($sp)
+ldq $13,24($sp)
+ldq $14,32($sp)
+ldq $24,40($sp)
+ldq $26,48($sp)
+lda $sp,176($sp)
+ret
+.end s244
+.sdata
+.align 0
+L.355:
+.byte 115
+.byte 50
+.byte 53
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.356:
+.byte 115
+.byte 50
+.byte 53
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s25
+.text
+.text
+.ent s25
+s25:
+ldgp $gp,0($27)
+lda $sp,-128($sp)
+.mask 0x5007e00,-72
+.frame $sp,128,$26,48
+stq $9,0($sp)
+stq $10,8($sp)
+stq $11,16($sp)
+stq $12,24($sp)
+stq $13,32($sp)
+stq $14,40($sp)
+stq $24,48($sp)
+stq $26,56($sp)
+mov $16,$14
+.prologue 1
+lda $10,L.356
+lda $9,60($14)
+L.357:
+L.358:
+mov $9,$27
+lda $9,1($27)
+mov $10,$25
+lda $10,1($25)
+ldb $25,($25)
+stb $25,($27)
+sll $25,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,$31,$23
+beq $23,L.357
+stl $31,-60+128($sp)
+lda $12,L.360
+lda $27,1($12)
+ldb $27,($27)
+ldb $25,($12)
+cmpeq $25,$27,$23
+beq $23,L.364
+lda $25,2($12)
+ldb $25,($25)
+cmpeq $27,$25,$23
+beq $23,L.364
+cmpeq $25,46,$23
+bne $23,L.361
+L.364:
+ldl $27,-60+128($sp)
+lda $27,1($27)
+stl $27,-60+128($sp)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.365
+lda $16,L.355
+lda $17,1
+jsr $26,printf
+ldgp $gp,0($26)
+L.365:
+L.361:
+lda $27,3($12)
+ldb $27,($27)
+cmpeq $27,$31,$23
+bne $23,L.367
+ldl $27,-60+128($sp)
+lda $27,4($27)
+stl $27,-60+128($sp)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.369
+lda $16,L.355
+lda $17,4
+jsr $26,printf
+ldgp $gp,0($26)
+L.369:
+L.367:
+lda $27,L.373+1
+ldb $27,($27)
+cmpeq $27,34,$23
+bne $23,L.371
+ldl $27,-60+128($sp)
+lda $27,8($27)
+stl $27,-60+128($sp)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.375
+lda $16,L.355
+lda $17,8
+jsr $26,printf
+ldgp $gp,0($26)
+L.375:
+L.371:
+lda $12,L.377
+ldb $27,($12)
+cmpeq $27,10,$23
+beq $23,L.385
+lda $27,1($12)
+ldb $27,($27)
+cmpeq $27,9,$23
+beq $23,L.385
+lda $27,2($12)
+ldb $27,($27)
+cmpeq $27,8,$23
+beq $23,L.385
+lda $27,3($12)
+ldb $27,($27)
+cmpeq $27,13,$23
+beq $23,L.385
+lda $27,4($12)
+ldb $27,($27)
+cmpeq $27,12,$23
+beq $23,L.385
+lda $27,5($12)
+ldb $27,($27)
+lda $25,92
+cmpeq $27,$25,$23
+beq $23,L.385
+lda $27,6($12)
+ldb $27,($27)
+cmpeq $27,39,$23
+bne $23,L.378
+L.385:
+ldl $27,-60+128($sp)
+lda $27,16($27)
+stl $27,-60+128($sp)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.386
+lda $16,L.355
+lda $17,16
+jsr $26,printf
+ldgp $gp,0($26)
+L.386:
+L.378:
+lda $27,L.388
+mov $27,$11
+mov $27,$12
+stl $31,-64+128($sp)
+mov $31,$13
+br L.392
+L.389:
+addq $13,$12,$27
+ldb $27,($27)
+addq $13,$11,$25
+ldb $25,($25)
+cmpeq $27,$25,$23
+bne $23,L.393
+lda $27,1
+stl $27,-64+128($sp)
+L.393:
+L.390:
+lda $13,1($13)
+L.392:
+mov $13,$27
+lda $25,7
+cmpult $27,$25,$23
+bne $23,L.389
+ldl $27,-64+128($sp)
+cmpeq $27,$31,$23
+bne $23,L.395
+ldl $27,-60+128($sp)
+lda $27,32($27)
+stl $27,-60+128($sp)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.397
+lda $16,L.355
+lda $17,32
+jsr $26,printf
+ldgp $gp,0($26)
+L.397:
+L.395:
+ldl $0,-60+128($sp)
+L.354:
+ldq $9,0($sp)
+ldq $10,8($sp)
+ldq $11,16($sp)
+ldq $12,24($sp)
+ldq $13,32($sp)
+ldq $14,40($sp)
+ldq $24,48($sp)
+ldq $26,56($sp)
+lda $sp,128($sp)
+ret
+.end s25
+.sdata
+.align 0
+L.400:
+.byte 115
+.byte 50
+.byte 54
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.align 0
+L.401:
+.byte 37
+.byte 51
+.byte 100
+.byte 32
+.byte 98
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 37
+.byte 115
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.402:
+.byte 37
+.byte 101
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 108
+.byte 101
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 97
+.byte 100
+.byte 100
+.byte 101
+.byte 100
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 49
+.byte 46
+.byte 32
+.byte 40
+.byte 37
+.byte 115
+.byte 41
+.byte 46
+.byte 10
+.byte 0
+.globl s26
+.text
+.text
+.ent s26
+s26:
+ldgp $gp,0($27)
+lda $sp,-160($sp)
+.fmask 0x3e0,-128
+.mask 0x5007c00,-72
+.frame $sp,160,$26,48
+stt $f5,0($sp)
+stt $f6,8($sp)
+stt $f7,16($sp)
+stt $f8,24($sp)
+stt $f9,32($sp)
+stq $10,40($sp)
+stq $11,48($sp)
+stq $12,56($sp)
+stq $13,64($sp)
+stq $14,72($sp)
+stq $24,80($sp)
+stq $26,88($sp)
+mov $16,$14
+.prologue 1
+lda $12,L.400
+lda $11,60($14)
+L.403:
+L.404:
+mov $11,$27
+lda $11,1($27)
+mov $12,$25
+lda $12,1($25)
+ldb $25,($25)
+stb $25,($27)
+sll $25,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,$31,$23
+beq $23,L.403
+stl $31,($14)
+mov $31,$10
+lda $13,1
+br L.407
+L.406:
+sll $13,8*(8-1),$27
+sra $27,8*(8-1),$27
+sll $27,1,$27
+addl $27,0,$27
+mov $27,$13
+ldl $27,($14)
+lda $27,1($27)
+stl $27,($14)
+L.407:
+sll $10,8*(8-1),$27
+sra $27,8*(8-1),$27
+sll $13,8*(8-1),$25
+sra $25,8*(8-1),$25
+cmpeq $27,$25,$23
+beq $23,L.406
+ldl $27,($14)
+sll $27,2,$27
+stl $27,4($14)
+ldl $27,($14)
+sll $27,1,$27
+stl $27,8($14)
+ldl $27,($14)
+sll $27,3,$27
+stl $27,12($14)
+ldl $27,($14)
+sll $27,2,$27
+stl $27,16($14)
+ldl $27,($14)
+sll $27,2,$27
+stl $27,20($14)
+ldl $27,($14)
+sll $27,3,$27
+stl $27,24($14)
+lds $f30,L.409
+fmov $f30,$f7
+fmov $f30,$f9
+lds $f8,L.410
+br L.412
+L.411:
+adds $f7,$f9,$f8
+cvtst $f9,$f30
+ldt $f29,L.414
+divt $f30,$f29,$f30
+cvtts $f30,$f9
+L.412:
+cmpteq $f8,$f7,$f1
+fbeq $f1,L.411
+ldt $f30,L.415
+cvtst $f9,$f29
+mult $f30,$f29,$f30
+cvtts $f30,$f30
+sts $f30,28($14)
+ldt $f5,L.416
+lds $f9,L.409
+ldt $f6,L.417
+br L.419
+L.418:
+cvtst $f9,$f30
+addt $f5,$f30,$f6
+ldt $f29,L.414
+divt $f30,$f29,$f30
+cvtts $f30,$f9
+L.419:
+cmpteq $f6,$f5,$f1
+fbeq $f1,L.418
+ldt $f30,L.415
+cvtst $f9,$f29
+mult $f30,$f29,$f30
+cvtts $f30,$f30
+sts $f30,32($14)
+ldl $27,40($14)
+cmpeq $27,$31,$23
+bne $23,L.421
+lda $16,L.401
+ldl $17,($14)
+lda $18,L.423
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.401
+ldl $17,4($14)
+lda $18,L.424
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.401
+ldl $17,8($14)
+lda $18,L.425
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.401
+ldl $17,12($14)
+lda $18,L.426
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.401
+ldl $17,16($14)
+lda $18,L.427
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.401
+ldl $17,20($14)
+lda $18,L.428
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.401
+ldl $17,24($14)
+lda $18,L.429
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.402
+lds $f30,28($14)
+cvtst $f30,$f17
+lda $18,L.428
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.402
+lds $f30,32($14)
+cvtst $f30,$f17
+lda $18,L.429
+jsr $26,printf
+ldgp $gp,0($26)
+L.421:
+mov $31,$0
+L.399:
+ldt $f5,0($sp)
+ldt $f6,8($sp)
+ldt $f7,16($sp)
+ldt $f8,24($sp)
+ldt $f9,32($sp)
+ldq $10,40($sp)
+ldq $11,48($sp)
+ldq $12,56($sp)
+ldq $13,64($sp)
+ldq $14,72($sp)
+ldq $24,80($sp)
+ldq $26,88($sp)
+lda $sp,160($sp)
+ret
+.end s26
+.sdata
+.align 0
+L.431:
+.byte 115
+.byte 52
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.432:
+.byte 115
+.byte 52
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s4
+.text
+.text
+.ent s4
+s4:
+ldgp $gp,0($27)
+lda $sp,-160($sp)
+.mask 0x5007e00,-104
+.frame $sp,160,$26,48
+stq $9,0($sp)
+stq $10,8($sp)
+stq $11,16($sp)
+stq $12,24($sp)
+stq $13,32($sp)
+stq $14,40($sp)
+stq $24,48($sp)
+stq $26,56($sp)
+mov $16,$14
+.prologue 1
+stl $31,-60+160($sp)
+lda $10,L.432
+lda $9,60($14)
+L.433:
+L.434:
+mov $9,$27
+lda $9,1($27)
+mov $10,$25
+lda $10,1($25)
+ldb $25,($25)
+stb $25,($27)
+sll $25,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,$31,$23
+beq $23,L.433
+mov $31,$13
+L.436:
+mov $13,$16
+jsr $26,svtest
+ldgp $gp,0($26)
+mov $0,$27
+stl $27,-84+160($sp)
+jsr $26,zero
+ldgp $gp,0($26)
+ldl $25,-84+160($sp)
+cmpeq $25,$0,$23
+bne $23,L.440
+lda $27,1
+stl $27,-60+160($sp)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.442
+lda $16,L.431
+lda $17,1
+jsr $26,printf
+ldgp $gp,0($26)
+L.442:
+L.440:
+L.437:
+lda $13,1($13)
+cmplt $13,3,$23
+bne $23,L.436
+jsr $26,setev
+ldgp $gp,0($26)
+jsr $26,testev
+ldgp $gp,0($26)
+cmpeq $0,$31,$23
+bne $23,L.444
+ldl $27,-60+160($sp)
+lda $27,2($27)
+stl $27,-60+160($sp)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.446
+lda $16,L.431
+lda $17,2
+jsr $26,printf
+ldgp $gp,0($26)
+L.446:
+L.444:
+br L.448
+ldl $27,-60+160($sp)
+lda $27,4($27)
+stl $27,-60+160($sp)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.450
+lda $16,L.431
+lda $17,4
+jsr $26,printf
+ldgp $gp,0($26)
+L.450:
+L.448:
+lda $12,0xffffffff
+lda $11,1
+mov $31,$13
+br L.455
+L.452:
+and $11,$12,$11
+srl $12,1,$12
+L.453:
+lda $13,1($13)
+L.455:
+mov $13,$27
+ldl $25,($14)
+sll $25,2,$25
+cmpult $27,$25,$23
+bne $23,L.452
+lda $27,1
+cmpeq $11,$27,$23
+beq $23,L.458
+cmpeq $12,$31,$23
+bne $23,L.456
+L.458:
+ldl $27,-60+160($sp)
+lda $27,8($27)
+stl $27,-60+160($sp)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.459
+lda $16,L.431
+lda $17,8
+jsr $26,printf
+ldgp $gp,0($26)
+L.459:
+L.456:
+ldl $0,-60+160($sp)
+L.430:
+ldq $9,0($sp)
+ldq $10,8($sp)
+ldq $11,16($sp)
+ldq $12,24($sp)
+ldq $13,32($sp)
+ldq $14,40($sp)
+ldq $24,48($sp)
+ldq $26,56($sp)
+lda $sp,160($sp)
+ret
+.end s4
+.lcomm L.462,4
+.globl svtest
+.text
+.text
+.ent svtest
+svtest:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.frame $sp,64,$26,48
+.prologue 1
+cmpeq $16,$31,$23
+bne $23,L.465
+cmpeq $16,1,$23
+bne $23,L.466
+cmpeq $16,2,$23
+bne $23,L.469
+br L.463
+L.465:
+lda $27,1978
+stl $27,L.462
+stl $31,-60+64($sp)
+br L.464
+L.466:
+ldl $27,L.462
+lda $25,1978
+cmpeq $27,$25,$23
+bne $23,L.467
+lda $27,1
+stl $27,-60+64($sp)
+br L.464
+L.467:
+lda $27,1929
+stl $27,L.462
+stl $31,-60+64($sp)
+br L.464
+L.469:
+ldl $27,L.462
+lda $25,1929
+cmpeq $27,$25,$23
+bne $23,L.470
+lda $27,1
+stl $27,-60+64($sp)
+br L.464
+L.470:
+stl $31,-60+64($sp)
+L.463:
+L.464:
+ldl $0,-60+64($sp)
+L.461:
+lda $sp,64($sp)
+ret
+.end svtest
+.lcomm L.473,4
+.globl zero
+.text
+.text
+.ent zero
+zero:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.frame $sp,64,$26,48
+.prologue 1
+lda $27,2
+stl $27,L.473
+stl $31,-60+64($sp)
+ldl $0,-60+64($sp)
+L.472:
+lda $sp,64($sp)
+ret
+.end zero
+.globl testev
+.text
+.ent testev
+testev:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.frame $sp,64,$26,48
+.prologue 1
+ldl $27,extvar
+lda $25,1066
+cmpeq $27,$25,$23
+bne $23,L.475
+lda $0,1
+br L.474
+L.475:
+mov $31,$0
+L.474:
+lda $sp,64($sp)
+ret
+.end testev
+.sdata
+.align 0
+L.478:
+.byte 115
+.byte 54
+.byte 49
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.479:
+.byte 115
+.byte 54
+.byte 49
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.align 0
+L.480:
+.byte 65
+.byte 66
+.byte 67
+.byte 68
+.byte 69
+.byte 70
+.byte 71
+.byte 72
+.byte 73
+.byte 74
+.byte 75
+.byte 76
+.byte 77
+.byte 78
+.byte 79
+.byte 80
+.byte 81
+.byte 82
+.byte 83
+.byte 84
+.byte 85
+.byte 86
+.byte 87
+.byte 88
+.byte 89
+.byte 90
+.byte 0
+.align 0
+L.481:
+.byte 97
+.byte 98
+.byte 99
+.byte 100
+.byte 101
+.byte 102
+.byte 103
+.byte 104
+.byte 105
+.byte 106
+.byte 107
+.byte 108
+.byte 109
+.byte 110
+.byte 111
+.byte 112
+.byte 113
+.byte 114
+.byte 115
+.byte 116
+.byte 117
+.byte 118
+.byte 119
+.byte 120
+.byte 121
+.byte 122
+.byte 0
+.align 0
+L.482:
+.byte 48
+.byte 49
+.byte 50
+.byte 51
+.byte 52
+.byte 53
+.byte 54
+.byte 55
+.byte 56
+.byte 57
+.byte 0
+.align 0
+L.483:
+.byte 126
+.byte 33
+.byte 34
+.byte 35
+.byte 37
+.byte 38
+.byte 40
+.byte 41
+.byte 95
+.byte 61
+.byte 45
+.byte 94
+.byte 124
+.byte 123
+.byte 125
+.byte 91
+.byte 93
+.byte 43
+.byte 59
+.byte 42
+.byte 58
+.byte 60
+.byte 62
+.byte 44
+.byte 46
+.byte 63
+.byte 47
+.byte 0
+.align 0
+L.484:
+.byte 10
+.byte 9
+.byte 8
+.byte 13
+.byte 12
+.byte 92
+.byte 39
+.byte 0
+.align 0
+L.485:
+.byte 32
+.byte 0
+.byte 0
+.globl s61
+.text
+.text
+.ent s61
+s61:
+ldgp $gp,0($27)
+lda $sp,-192($sp)
+.mask 0x5007e00,-136
+.frame $sp,192,$26,48
+stq $9,0($sp)
+stq $10,8($sp)
+stq $11,16($sp)
+stq $12,24($sp)
+stq $13,32($sp)
+stq $14,40($sp)
+stq $24,48($sp)
+stq $26,56($sp)
+stq $16,144($sp)
+.prologue 1
+lda $12,L.479
+ldq $27,-48+192($sp)
+lda $11,60($27)
+mov $31,$9
+L.486:
+L.487:
+mov $11,$27
+lda $11,1($27)
+mov $12,$25
+lda $12,1($25)
+ldb $25,($25)
+stb $25,($27)
+sll $25,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,$31,$23
+beq $23,L.486
+lda $27,-19
+stw $27,-110+192($sp)
+lda $27,-110+192($sp)
+ldw $27,($27)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+stq $27,-120+192($sp)
+ldq $27,-120+192($sp)
+lda $25,-19
+cmpeq $27,$25,$23
+bne $23,L.489
+lda $9,1($9)
+ldq $27,-48+192($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.491
+lda $16,L.478
+lda $17,1
+jsr $26,printf
+ldgp $gp,0($26)
+L.491:
+L.489:
+lda $27,L.480
+stq $27,-104+192($sp)
+lda $27,L.481
+stq $27,-96+192($sp)
+lda $27,L.482
+stq $27,-88+192($sp)
+lda $27,L.483
+stq $27,-80+192($sp)
+lda $27,L.484
+stq $27,-72+192($sp)
+lda $27,L.485
+stq $27,-64+192($sp)
+mov $31,$13
+mov $31,$14
+br L.503
+L.502:
+sll $14,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,3,$27
+lda $25,-104+192($sp)
+addq $27,$25,$27
+ldq $25,($27)
+lda $22,1($25)
+stq $22,($27)
+ldb $27,($25)
+cmplt $27,$31,$23
+beq $23,L.505
+lda $13,1
+L.505:
+L.503:
+sll $14,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,3,$27
+lda $25,-104+192($sp)
+addq $27,$25,$27
+ldq $27,($27)
+ldb $27,($27)
+cmpeq $27,$31,$23
+beq $23,L.502
+L.499:
+lda $14,1($14)
+cmplt $14,6,$23
+bne $23,L.503
+cmpeq $13,$31,$23
+bne $23,L.507
+lda $9,2($9)
+ldq $27,-48+192($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.509
+lda $16,L.478
+lda $17,2
+jsr $26,printf
+ldgp $gp,0($26)
+L.509:
+L.507:
+lda $10,1048579
+mov $10,$27
+stw $27,-106+192($sp)
+mov $10,$27
+stb $27,-107+192($sp)
+lda $27,-106+192($sp)
+ldw $27,($27)
+sll $27,8*(8-4),$25
+sra $25,8*(8-4),$25
+cmpeq $25,$10,$23
+bne $23,L.514
+cmpeq $27,3,$23
+beq $23,L.513
+L.514:
+lda $27,-107+192($sp)
+ldb $27,($27)
+sll $27,8*(8-4),$25
+sra $25,8*(8-4),$25
+cmpeq $25,$10,$23
+bne $23,L.511
+cmpeq $27,3,$23
+bne $23,L.511
+L.513:
+lda $9,8($9)
+ldq $27,-48+192($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.515
+lda $16,L.478
+lda $17,8
+jsr $26,printf
+ldgp $gp,0($26)
+L.515:
+L.511:
+mov $9,$0
+L.477:
+ldq $9,0($sp)
+ldq $10,8($sp)
+ldq $11,16($sp)
+ldq $12,24($sp)
+ldq $13,32($sp)
+ldq $14,40($sp)
+ldq $24,48($sp)
+ldq $26,56($sp)
+lda $sp,192($sp)
+ret
+.end s61
+.sdata
+.align 0
+L.518:
+.byte 115
+.byte 54
+.byte 50
+.byte 54
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.519:
+.byte 115
+.byte 54
+.byte 50
+.byte 54
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s626
+.text
+.text
+.ent s626
+s626:
+ldgp $gp,0($27)
+lda $sp,-240($sp)
+.fmask 0x3c0,-216
+.mask 0x5007e00,-152
+.frame $sp,240,$26,48
+stt $f6,0($sp)
+stt $f7,8($sp)
+stt $f8,16($sp)
+stt $f9,24($sp)
+stq $9,32($sp)
+stq $10,40($sp)
+stq $11,48($sp)
+stq $12,56($sp)
+stq $13,64($sp)
+stq $14,72($sp)
+stq $24,80($sp)
+stq $26,88($sp)
+mov $16,$14
+.prologue 1
+lda $10,L.519
+lda $9,60($14)
+stl $31,-128+240($sp)
+L.520:
+L.521:
+mov $9,$27
+lda $9,1($27)
+mov $10,$25
+lda $10,1($25)
+ldb $25,($25)
+stb $25,($27)
+sll $25,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,$31,$23
+beq $23,L.520
+lds $f9,L.409
+lda $27,1
+stq $27,-96+240($sp)
+mov $27,$12
+mov $31,$13
+br L.526
+L.523:
+lds $f30,L.527
+muls $f30,$f9,$f9
+sll $12,1,$27
+ldq $25,-96+240($sp)
+or $27,$25,$12
+L.524:
+lda $13,1($13)
+L.526:
+ldl $27,12($14)
+subl $27,2,$27
+cmplt $13,$27,$23
+bne $23,L.523
+stq $12,-56+240($sp)
+ldt $f30,-56+240($sp)
+cvtqs $f30,$f30
+sts $f30,-140+240($sp)
+lds $f30,-140+240($sp)
+subs $f9,$f30,$f30
+divs $f30,$f9,$f9
+cvtst $f9,$f30
+ldt $f29,L.414
+lds $f28,28($14)
+cvtst $f28,$f28
+mult $f29,$f28,$f29
+cmptle $f30,$f29,$f1
+fbne $f1,L.528
+ldl $27,-128+240($sp)
+lda $27,2($27)
+stl $27,-128+240($sp)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.530
+lda $16,L.518
+lda $17,2
+jsr $26,printf
+ldgp $gp,0($26)
+L.530:
+L.528:
+lda $27,125
+stb $27,-105+240($sp)
+lda $27,125
+stw $27,-108+240($sp)
+lda $27,125
+stl $27,-112+240($sp)
+lda $27,15625
+stl $27,-120+240($sp)
+lda $27,125
+stl $27,-116+240($sp)
+lda $27,15625
+stl $27,-124+240($sp)
+lda $27,125
+stq $27,-104+240($sp)
+lda $27,15625
+stq $27,-136+240($sp)
+lds $f7,L.532
+ldt $f6,L.533
+ldt $f8,L.534
+mov $31,$13
+L.535:
+lda $27,-84+240($sp)
+addq $13,$27,$27
+stb $31,($27)
+L.536:
+lda $13,1($13)
+cmplt $13,28,$23
+bne $23,L.535
+lda $27,-105+240($sp)
+ldb $27,($27)
+mull $27,$27,$27
+ldl $25,-120+240($sp)
+cmpeq $27,$25,$23
+bne $23,L.539
+lda $27,1
+stb $27,-84+240($sp)
+L.539:
+lda $27,-108+240($sp)
+ldw $27,($27)
+lda $25,-105+240($sp)
+ldb $25,($25)
+mull $27,$25,$27
+ldl $25,-120+240($sp)
+cmpeq $27,$25,$23
+bne $23,L.541
+lda $27,1
+stb $27,-83+240($sp)
+L.541:
+lda $27,-108+240($sp)
+ldw $27,($27)
+mull $27,$27,$27
+ldl $25,-120+240($sp)
+cmpeq $27,$25,$23
+bne $23,L.544
+lda $27,1
+stb $27,-82+240($sp)
+L.544:
+ldl $27,-112+240($sp)
+lda $25,-105+240($sp)
+ldb $25,($25)
+mull $27,$25,$27
+ldl $25,-120+240($sp)
+cmpeq $27,$25,$23
+bne $23,L.547
+lda $27,1
+stb $27,-81+240($sp)
+L.547:
+ldl $27,-112+240($sp)
+lda $25,-108+240($sp)
+ldw $25,($25)
+mull $27,$25,$27
+ldl $25,-120+240($sp)
+cmpeq $27,$25,$23
+bne $23,L.550
+lda $27,1
+stb $27,-80+240($sp)
+L.550:
+ldl $27,-112+240($sp)
+mull $27,$27,$27
+ldl $25,-120+240($sp)
+cmpeq $27,$25,$23
+bne $23,L.553
+lda $27,1
+stb $27,-79+240($sp)
+L.553:
+ldl $27,-116+240($sp)
+zap $27,240,$27
+lda $25,-105+240($sp)
+ldb $25,($25)
+mull $27,$25,$27
+zap $27,240,$27
+ldl $25,-124+240($sp)
+zap $25,240,$25
+cmpeq $27,$25,$23
+bne $23,L.556
+lda $27,1
+stb $27,-78+240($sp)
+L.556:
+ldl $27,-116+240($sp)
+zap $27,240,$27
+lda $25,-108+240($sp)
+ldw $25,($25)
+mull $27,$25,$27
+zap $27,240,$27
+ldl $25,-124+240($sp)
+zap $25,240,$25
+cmpeq $27,$25,$23
+bne $23,L.559
+lda $27,1
+stb $27,-77+240($sp)
+L.559:
+ldl $27,-116+240($sp)
+zap $27,240,$27
+ldl $25,-112+240($sp)
+mull $27,$25,$27
+zap $27,240,$27
+ldl $25,-124+240($sp)
+zap $25,240,$25
+cmpeq $27,$25,$23
+bne $23,L.562
+lda $27,1
+stb $27,-76+240($sp)
+L.562:
+ldl $27,-116+240($sp)
+zap $27,240,$27
+mull $27,$27,$27
+zap $27,240,$27
+ldl $25,-124+240($sp)
+zap $25,240,$25
+cmpeq $27,$25,$23
+bne $23,L.565
+lda $27,1
+stb $27,-75+240($sp)
+L.565:
+ldq $27,-104+240($sp)
+lda $25,-105+240($sp)
+ldb $25,($25)
+sll $25,8*(8-4),$25
+sra $25,8*(8-4),$25
+mulq $27,$25,$27
+ldq $25,-136+240($sp)
+cmpeq $27,$25,$23
+bne $23,L.568
+lda $27,1
+stb $27,-74+240($sp)
+L.568:
+ldq $27,-104+240($sp)
+lda $25,-108+240($sp)
+ldw $25,($25)
+sll $25,8*(8-4),$25
+sra $25,8*(8-4),$25
+mulq $27,$25,$27
+ldq $25,-136+240($sp)
+cmpeq $27,$25,$23
+bne $23,L.571
+lda $27,1
+stb $27,-73+240($sp)
+L.571:
+ldq $27,-104+240($sp)
+ldl $25,-112+240($sp)
+mulq $27,$25,$27
+ldq $25,-136+240($sp)
+cmpeq $27,$25,$23
+bne $23,L.574
+lda $27,1
+stb $27,-72+240($sp)
+L.574:
+ldq $27,-104+240($sp)
+ldl $25,-116+240($sp)
+zap $25,240,$25
+mulq $27,$25,$27
+ldl $25,-124+240($sp)
+zap $25,240,$25
+cmpeq $27,$25,$23
+bne $23,L.577
+lda $27,1
+stb $27,-71+240($sp)
+L.577:
+ldq $27,-104+240($sp)
+mulq $27,$27,$27
+ldq $25,-136+240($sp)
+cmpeq $27,$25,$23
+bne $23,L.580
+lda $27,1
+stb $27,-70+240($sp)
+L.580:
+lda $27,-105+240($sp)
+ldb $27,($27)
+stq $27,-56+240($sp)
+ldt $f30,-56+240($sp)
+cvtqs $f30,$f30
+muls $f7,$f30,$f30
+cvtst $f30,$f30
+cmpteq $f30,$f8,$f1
+fbne $f1,L.583
+lda $27,1
+stb $27,-69+240($sp)
+L.583:
+lda $27,-108+240($sp)
+ldw $27,($27)
+stq $27,-56+240($sp)
+ldt $f30,-56+240($sp)
+cvtqs $f30,$f30
+muls $f7,$f30,$f30
+cvtst $f30,$f30
+cmpteq $f30,$f8,$f1
+fbne $f1,L.586
+lda $27,1
+stb $27,-68+240($sp)
+L.586:
+lds $f30,-112+240($sp)
+cvtlq $f30,$f30
+cvtqs $f30,$f30
+muls $f7,$f30,$f30
+cvtst $f30,$f30
+cmpteq $f30,$f8,$f1
+fbne $f1,L.589
+lda $27,1
+stb $27,-67+240($sp)
+L.589:
+ldl $27,-116+240($sp)
+zap $27,240,$27
+ldt $f30,L.594
+srl $27,1,$25
+stq $25,-56+240($sp)
+ldt $f29,-56+240($sp)
+cvtqt $f29,$f29
+mult $f30,$f29,$f30
+and $27,1,$27
+stq $27,-56+240($sp)
+ldt $f29,-56+240($sp)
+cvtqt $f29,$f29
+addt $f30,$f29,$f30
+cvtts $f30,$f30
+muls $f7,$f30,$f30
+cvtst $f30,$f30
+cmpteq $f30,$f8,$f1
+fbne $f1,L.592
+lda $27,1
+stb $27,-66+240($sp)
+L.592:
+ldt $f30,-104+240($sp)
+cvtqs $f30,$f30
+muls $f7,$f30,$f30
+cvtst $f30,$f30
+cmpteq $f30,$f8,$f1
+fbne $f1,L.596
+lda $27,1
+stb $27,-65+240($sp)
+L.596:
+muls $f7,$f7,$f30
+cvtst $f30,$f30
+cmpteq $f30,$f8,$f1
+fbne $f1,L.599
+lda $27,1
+stb $27,-64+240($sp)
+L.599:
+lda $27,-105+240($sp)
+ldb $27,($27)
+stq $27,-56+240($sp)
+ldt $f30,-56+240($sp)
+cvtqt $f30,$f30
+mult $f6,$f30,$f30
+cmpteq $f30,$f8,$f1
+fbne $f1,L.602
+lda $27,1
+stb $27,-63+240($sp)
+L.602:
+lda $27,-108+240($sp)
+ldw $27,($27)
+stq $27,-56+240($sp)
+ldt $f30,-56+240($sp)
+cvtqt $f30,$f30
+mult $f6,$f30,$f30
+cmpteq $f30,$f8,$f1
+fbne $f1,L.605
+lda $27,1
+stb $27,-62+240($sp)
+L.605:
+lds $f30,-112+240($sp)
+cvtlq $f30,$f30
+cvtqt $f30,$f30
+mult $f6,$f30,$f30
+cmpteq $f30,$f8,$f1
+fbne $f1,L.608
+lda $27,1
+stb $27,-61+240($sp)
+L.608:
+ldl $27,-116+240($sp)
+zap $27,240,$27
+ldt $f30,L.594
+srl $27,1,$25
+stq $25,-56+240($sp)
+ldt $f29,-56+240($sp)
+cvtqt $f29,$f29
+mult $f30,$f29,$f30
+and $27,1,$27
+stq $27,-56+240($sp)
+ldt $f29,-56+240($sp)
+cvtqt $f29,$f29
+addt $f30,$f29,$f30
+mult $f6,$f30,$f30
+cmpteq $f30,$f8,$f1
+fbne $f1,L.611
+lda $27,1
+stb $27,-60+240($sp)
+L.611:
+ldt $f30,-104+240($sp)
+cvtqt $f30,$f30
+mult $f6,$f30,$f30
+cmpteq $f30,$f8,$f1
+fbne $f1,L.614
+lda $27,1
+stb $27,-59+240($sp)
+L.614:
+cvtst $f7,$f30
+mult $f6,$f30,$f30
+cmpteq $f30,$f8,$f1
+fbne $f1,L.617
+lda $27,1
+stb $27,-58+240($sp)
+L.617:
+mult $f6,$f6,$f30
+cmpteq $f30,$f8,$f1
+fbne $f1,L.620
+lda $27,1
+stb $27,-57+240($sp)
+L.620:
+mov $31,$11
+mov $31,$13
+L.623:
+sll $11,8*(8-1),$27
+sra $27,8*(8-1),$27
+lda $25,-84+240($sp)
+addq $13,$25,$25
+ldb $25,($25)
+addl $27,$25,$27
+mov $27,$11
+L.624:
+lda $13,1($13)
+cmplt $13,28,$23
+bne $23,L.623
+sll $11,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,$31,$23
+bne $23,L.627
+ldl $27,-128+240($sp)
+lda $27,4($27)
+stl $27,-128+240($sp)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.629
+lda $16,L.518
+lda $17,4
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.631
+jsr $26,printf
+ldgp $gp,0($26)
+mov $31,$13
+L.632:
+lda $16,L.636
+lda $27,-84+240($sp)
+addq $13,$27,$27
+ldb $17,($27)
+jsr $26,printf
+ldgp $gp,0($26)
+L.633:
+lda $13,1($13)
+cmplt $13,28,$23
+bne $23,L.632
+lda $16,L.637
+jsr $26,printf
+ldgp $gp,0($26)
+L.629:
+L.627:
+lda $27,32768
+stq $27,-104+240($sp)
+ldq $25,-104+240($sp)
+cmple $25,$27,$23
+bne $23,L.638
+ldl $27,-128+240($sp)
+lda $27,8($27)
+stl $27,-128+240($sp)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.640
+lda $16,L.518
+lda $17,8
+jsr $26,printf
+ldgp $gp,0($26)
+L.640:
+L.638:
+ldl $0,-128+240($sp)
+L.517:
+ldt $f6,0($sp)
+ldt $f7,8($sp)
+ldt $f8,16($sp)
+ldt $f9,24($sp)
+ldq $9,32($sp)
+ldq $10,40($sp)
+ldq $11,48($sp)
+ldq $12,56($sp)
+ldq $13,64($sp)
+ldq $14,72($sp)
+ldq $24,80($sp)
+ldq $26,88($sp)
+lda $sp,240($sp)
+ret
+.end s626
+.sdata
+.align 0
+L.643:
+.byte 115
+.byte 55
+.byte 49
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.644:
+.byte 115
+.byte 55
+.byte 49
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.align 0
+L.645:
+.byte 0x71
+.globl s71
+.text
+.text
+.ent s71
+s71:
+ldgp $gp,0($27)
+lda $sp,-176($sp)
+.mask 0x5007c00,-128
+.frame $sp,176,$26,48
+stq $10,0($sp)
+stq $11,8($sp)
+stq $12,16($sp)
+stq $13,24($sp)
+stq $14,32($sp)
+stq $24,40($sp)
+stq $26,48($sp)
+mov $16,$14
+.prologue 1
+lda $13,L.644
+lda $12,60($14)
+mov $31,$11
+L.646:
+L.647:
+mov $12,$27
+lda $12,1($27)
+mov $13,$25
+lda $13,1($25)
+ldb $25,($25)
+stb $25,($27)
+sll $25,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,$31,$23
+beq $23,L.646
+lda $27,L.651
+ldb $27,($27)
+lda $25,L.645
+ldb $25,($25)
+cmpeq $27,$25,$23
+bne $23,L.649
+lda $11,1($11)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.652
+lda $16,L.643
+lda $17,1
+jsr $26,printf
+ldgp $gp,0($26)
+L.652:
+L.649:
+br L.654
+lda $11,2($11)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.656
+lda $16,L.643
+lda $17,2
+jsr $26,printf
+ldgp $gp,0($26)
+L.656:
+L.654:
+lda $27,1942
+stl $27,-76+176($sp)
+ldl $27,-76+176($sp)
+lda $25,1942
+cmpeq $27,$25,$23
+beq $23,L.664
+ldl $27,-76+176($sp)
+ldl $25,-76+176($sp)
+cmpeq $27,$25,$23
+bne $23,L.659
+L.664:
+lda $11,4($11)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.665
+lda $16,L.643
+lda $17,4
+jsr $26,printf
+ldgp $gp,0($26)
+L.665:
+L.659:
+lda $16,-5
+jsr $26,McCarthy
+ldgp $gp,0($26)
+lda $25,91
+cmpeq $0,$25,$23
+bne $23,L.667
+lda $11,8($11)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.669
+lda $16,L.643
+lda $17,8
+jsr $26,printf
+ldgp $gp,0($26)
+L.669:
+L.667:
+lda $10,2
+lda $27,3
+stl $27,-100+176($sp)
+lda $27,-100+176($sp)
+stq $27,-112+176($sp)
+mov $10,$16
+ldq $17,-112+176($sp)
+jsr $26,clobber
+ldgp $gp,0($26)
+cmpeq $10,2,$23
+beq $23,L.673
+ldl $27,-100+176($sp)
+cmpeq $27,2,$23
+bne $23,L.671
+L.673:
+lda $11,16($11)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.674
+lda $16,L.643
+lda $17,16
+jsr $26,printf
+ldgp $gp,0($26)
+L.674:
+L.671:
+lds $f30,32($14)
+cmpteq $f30,$f30,$f1
+fbne $f1,L.676
+lda $11,32($11)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.678
+lda $16,L.643
+lda $17,32
+jsr $26,printf
+ldgp $gp,0($26)
+L.678:
+L.676:
+mov $11,$0
+L.642:
+ldq $10,0($sp)
+ldq $11,8($sp)
+ldq $12,16($sp)
+ldq $13,24($sp)
+ldq $14,32($sp)
+ldq $24,40($sp)
+ldq $26,48($sp)
+lda $sp,176($sp)
+ret
+.end s71
+.globl McCarthy
+.text
+.ent McCarthy
+McCarthy:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+stq $16,16($sp)
+.prologue 1
+ldl $27,-48+64($sp)
+lda $25,100
+cmple $27,$25,$23
+bne $23,L.681
+ldl $27,-48+64($sp)
+subl $27,10,$0
+br L.680
+L.681:
+ldl $27,-48+64($sp)
+lda $16,11($27)
+jsr $26,McCarthy
+ldgp $gp,0($26)
+mov $0,$27
+mov $27,$16
+jsr $26,McCarthy
+ldgp $gp,0($26)
+mov $0,$27
+L.680:
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end McCarthy
+.globl clobber
+.text
+.ent clobber
+clobber:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.frame $sp,64,$26,48
+.prologue 1
+lda $16,3
+lda $27,2
+stl $27,($17)
+mov $31,$0
+L.683:
+lda $sp,64($sp)
+ret
+.end clobber
+.sdata
+.align 0
+L.685:
+.byte 76
+.byte 111
+.byte 99
+.byte 97
+.byte 108
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 37
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.686:
+.byte 115
+.byte 55
+.byte 49
+.byte 52
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.687:
+.byte 115
+.byte 55
+.byte 49
+.byte 52
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s714
+.text
+.text
+.ent s714
+s714:
+ldgp $gp,0($27)
+lda $sp,-256($sp)
+.fmask 0x3c0,-232
+.mask 0x5007e00,-168
+.frame $sp,256,$26,48
+stt $f6,0($sp)
+stt $f7,8($sp)
+stt $f8,16($sp)
+stt $f9,24($sp)
+stq $9,32($sp)
+stq $10,40($sp)
+stq $11,48($sp)
+stq $12,56($sp)
+stq $13,64($sp)
+stq $14,72($sp)
+stq $24,80($sp)
+stq $26,88($sp)
+stq $16,208($sp)
+.prologue 1
+lda $27,L.687
+stq $27,-96+256($sp)
+ldq $27,-48+256($sp)
+lda $25,60($27)
+stq $25,-104+256($sp)
+stl $31,-108+256($sp)
+mov $31,$13
+ldl $14,48($27)
+L.688:
+L.689:
+ldq $27,-104+256($sp)
+lda $25,1($27)
+stq $25,-104+256($sp)
+ldq $25,-96+256($sp)
+lda $22,1($25)
+stq $22,-96+256($sp)
+ldb $25,($25)
+stb $25,($27)
+sll $25,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,$31,$23
+beq $23,L.688
+lda $12,5
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $12,($27)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,2,$23
+bne $23,L.691
+lda $13,1
+cmpeq $14,$31,$23
+bne $23,L.693
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.693:
+L.691:
+lda $12,5
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,2,$23
+bne $23,L.695
+lda $13,2
+cmpeq $14,$31,$23
+bne $23,L.697
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.697:
+L.695:
+lda $12,5
+lda $27,2
+stl $27,-68+256($sp)
+ldl $27,-68+256($sp)
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,2,$23
+bne $23,L.699
+lda $13,3
+cmpeq $14,$31,$23
+bne $23,L.701
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.701:
+L.699:
+lda $12,5
+lda $27,2
+stq $27,-80+256($sp)
+ldq $27,-80+256($sp)
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,2,$23
+bne $23,L.703
+lda $13,4
+cmpeq $14,$31,$23
+bne $23,L.705
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.705:
+L.703:
+lda $12,5
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,2,$23
+bne $23,L.707
+lda $13,5
+cmpeq $14,$31,$23
+bne $23,L.709
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.709:
+L.707:
+lda $12,5
+lds $f7,L.527
+cvttqc $f7,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,2,$23
+bne $23,L.711
+lda $13,6
+cmpeq $14,$31,$23
+bne $23,L.713
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.713:
+L.711:
+lda $12,5
+ldt $f6,L.414
+cvttqc $f6,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,2,$23
+bne $23,L.715
+lda $13,7
+cmpeq $14,$31,$23
+bne $23,L.717
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.717:
+L.715:
+lda $11,5
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,2,$23
+bne $23,L.719
+lda $13,8
+cmpeq $14,$31,$23
+bne $23,L.721
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.721:
+L.719:
+lda $11,5
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $11,($27)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,2,$23
+bne $23,L.723
+lda $13,9
+cmpeq $14,$31,$23
+bne $23,L.725
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.725:
+L.723:
+lda $11,5
+lda $27,2
+stl $27,-68+256($sp)
+ldl $27,-68+256($sp)
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,2,$23
+bne $23,L.727
+lda $13,10
+cmpeq $14,$31,$23
+bne $23,L.729
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.729:
+L.727:
+lda $11,5
+lda $27,2
+stq $27,-80+256($sp)
+ldq $27,-80+256($sp)
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,2,$23
+bne $23,L.731
+lda $13,11
+cmpeq $14,$31,$23
+bne $23,L.733
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.733:
+L.731:
+lda $11,5
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,2,$23
+bne $23,L.735
+lda $13,12
+cmpeq $14,$31,$23
+bne $23,L.737
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.737:
+L.735:
+lda $11,5
+lds $f7,L.527
+cvttqc $f7,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,2,$23
+bne $23,L.739
+lda $13,13
+cmpeq $14,$31,$23
+bne $23,L.741
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.741:
+L.739:
+lda $11,5
+ldt $f6,L.414
+cvttqc $f6,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,2,$23
+bne $23,L.743
+lda $13,14
+cmpeq $14,$31,$23
+bne $23,L.745
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.745:
+L.743:
+lda $10,5
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $10,($27)
+cmpeq $10,2,$23
+bne $23,L.747
+lda $13,15
+cmpeq $14,$31,$23
+bne $23,L.749
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.749:
+L.747:
+lda $10,5
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $10,($27)
+cmpeq $10,2,$23
+bne $23,L.751
+lda $13,16
+cmpeq $14,$31,$23
+bne $23,L.753
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.753:
+L.751:
+lda $10,5
+lda $27,2
+stl $27,-68+256($sp)
+ldl $10,-68+256($sp)
+cmpeq $10,2,$23
+bne $23,L.755
+lda $13,17
+cmpeq $14,$31,$23
+bne $23,L.757
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.757:
+L.755:
+lda $10,5
+lda $27,2
+stq $27,-80+256($sp)
+ldq $27,-80+256($sp)
+mov $27,$10
+cmpeq $10,2,$23
+bne $23,L.759
+lda $13,18
+cmpeq $14,$31,$23
+bne $23,L.761
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.761:
+L.759:
+lda $10,5
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+mov $27,$10
+cmpeq $10,2,$23
+bne $23,L.763
+lda $13,19
+cmpeq $14,$31,$23
+bne $23,L.765
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.765:
+L.763:
+lda $10,5
+lds $f7,L.527
+cvttqc $f7,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $10,-56+256($sp)
+cmpeq $10,2,$23
+bne $23,L.767
+lda $13,20
+cmpeq $14,$31,$23
+bne $23,L.769
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.769:
+L.767:
+lda $10,5
+ldt $f6,L.414
+cvttqc $f6,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $10,-56+256($sp)
+cmpeq $10,2,$23
+bne $23,L.771
+lda $13,21
+cmpeq $14,$31,$23
+bne $23,L.773
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.773:
+L.771:
+lda $9,5
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+sll $27,8*(8-4),$9
+sra $9,8*(8-4),$9
+cmpeq $9,2,$23
+bne $23,L.775
+lda $13,22
+cmpeq $14,$31,$23
+bne $23,L.777
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.777:
+L.775:
+lda $9,5
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+sll $27,8*(8-4),$9
+sra $9,8*(8-4),$9
+cmpeq $9,2,$23
+bne $23,L.779
+lda $13,23
+cmpeq $14,$31,$23
+bne $23,L.781
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.781:
+L.779:
+lda $9,5
+lda $27,2
+stl $27,-68+256($sp)
+ldl $9,-68+256($sp)
+cmpeq $9,2,$23
+bne $23,L.783
+lda $13,24
+cmpeq $14,$31,$23
+bne $23,L.785
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.785:
+L.783:
+lda $9,5
+lda $27,2
+stq $27,-80+256($sp)
+ldq $9,-80+256($sp)
+cmpeq $9,2,$23
+bne $23,L.787
+lda $13,25
+cmpeq $14,$31,$23
+bne $23,L.789
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.789:
+L.787:
+lda $9,5
+lda $27,2
+stl $27,-84+256($sp)
+ldl $9,-84+256($sp)
+zap $9,240,$9
+cmpeq $9,2,$23
+bne $23,L.791
+lda $13,26
+cmpeq $14,$31,$23
+bne $23,L.793
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.793:
+L.791:
+lda $9,5
+lds $f7,L.527
+cvttqc $f7,$f1
+stt $f1,-56+256($sp)
+ldq $9,-56+256($sp)
+cmpeq $9,2,$23
+bne $23,L.795
+lda $13,27
+cmpeq $14,$31,$23
+bne $23,L.797
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.797:
+L.795:
+lda $9,5
+ldt $f6,L.414
+cvttqc $f6,$f1
+stt $f1,-56+256($sp)
+ldq $9,-56+256($sp)
+cmpeq $9,2,$23
+bne $23,L.799
+lda $13,28
+cmpeq $14,$31,$23
+bne $23,L.801
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.801:
+L.799:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,2
+cmpeq $27,$25,$23
+bne $23,L.803
+lda $13,29
+cmpeq $14,$31,$23
+bne $23,L.805
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.805:
+L.803:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,2
+cmpeq $27,$25,$23
+bne $23,L.807
+lda $13,30
+cmpeq $14,$31,$23
+bne $23,L.809
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.809:
+L.807:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stl $27,-68+256($sp)
+ldl $27,-68+256($sp)
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,2
+cmpeq $27,$25,$23
+bne $23,L.811
+lda $13,31
+cmpeq $14,$31,$23
+bne $23,L.813
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.813:
+L.811:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stq $27,-80+256($sp)
+ldq $27,-80+256($sp)
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,2
+cmpeq $27,$25,$23
+bne $23,L.815
+lda $13,32
+cmpeq $14,$31,$23
+bne $23,L.817
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.817:
+L.815:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stl $27,-84+256($sp)
+ldl $25,-84+256($sp)
+zap $25,240,$25
+stl $25,-60+256($sp)
+ldl $25,-60+256($sp)
+zap $25,240,$25
+cmpeq $25,$27,$23
+bne $23,L.819
+lda $13,33
+cmpeq $14,$31,$23
+bne $23,L.821
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.821:
+L.819:
+lda $27,5
+stl $27,-60+256($sp)
+lds $f7,L.527
+lds $f30,L.826
+cmptlt $f7,$f30,$f1
+fbne $f1,L.824
+subs $f7,$f30,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+addl $27,0x80000000,$27
+zap $27,240,$27
+stl $27,-112+256($sp)
+br L.825
+L.824:
+cvttqc $f7,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+stl $27,-112+256($sp)
+L.825:
+ldl $27,-112+256($sp)
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,2
+cmpeq $27,$25,$23
+bne $23,L.827
+lda $13,34
+cmpeq $14,$31,$23
+bne $23,L.829
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.829:
+L.827:
+lda $27,5
+stl $27,-60+256($sp)
+ldt $f6,L.414
+ldt $f30,L.834
+cmptlt $f6,$f30,$f1
+fbne $f1,L.832
+subt $f6,$f30,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+addl $27,0x80000000,$27
+zap $27,240,$27
+stl $27,-116+256($sp)
+br L.833
+L.832:
+cvttqc $f6,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+stl $27,-116+256($sp)
+L.833:
+ldl $27,-116+256($sp)
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,2
+cmpeq $27,$25,$23
+bne $23,L.835
+lda $13,35
+cmpeq $14,$31,$23
+bne $23,L.837
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.837:
+L.835:
+lds $f9,L.839
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+stq $27,-56+256($sp)
+ldt $f9,-56+256($sp)
+cvtqs $f9,$f9
+lds $f30,L.527
+cmpteq $f9,$f30,$f1
+fbne $f1,L.840
+lda $13,36
+cmpeq $14,$31,$23
+bne $23,L.842
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.842:
+L.840:
+lds $f9,L.839
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+stq $27,-56+256($sp)
+ldt $f9,-56+256($sp)
+cvtqs $f9,$f9
+lds $f30,L.527
+cmpteq $f9,$f30,$f1
+fbne $f1,L.844
+lda $13,37
+cmpeq $14,$31,$23
+bne $23,L.846
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.846:
+L.844:
+lds $f9,L.839
+lda $27,2
+stl $27,-68+256($sp)
+lds $f9,-68+256($sp)
+cvtlq $f9,$f9
+cvtqs $f9,$f9
+lds $f30,L.527
+cmpteq $f9,$f30,$f1
+fbne $f1,L.848
+lda $13,38
+cmpeq $14,$31,$23
+bne $23,L.850
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.850:
+L.848:
+lds $f9,L.839
+lda $27,2
+stq $27,-80+256($sp)
+ldt $f9,-80+256($sp)
+cvtqs $f9,$f9
+lds $f30,L.527
+cmpteq $f9,$f30,$f1
+fbne $f1,L.852
+lda $13,39
+cmpeq $14,$31,$23
+bne $23,L.854
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.854:
+L.852:
+lds $f9,L.839
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+ldt $f30,L.594
+srl $27,1,$25
+stq $25,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+mult $f30,$f29,$f30
+and $27,1,$27
+stq $27,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+addt $f30,$f29,$f30
+cvtts $f30,$f9
+lds $f30,L.527
+cmpteq $f9,$f30,$f1
+fbne $f1,L.856
+lda $13,40
+cmpeq $14,$31,$23
+bne $23,L.858
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.858:
+L.856:
+lds $f9,L.839
+lds $f30,L.527
+fmov $f30,$f7
+fmov $f7,$f9
+cmpteq $f9,$f30,$f1
+fbne $f1,L.860
+lda $13,41
+cmpeq $14,$31,$23
+bne $23,L.862
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.862:
+L.860:
+lds $f9,L.839
+ldt $f6,L.414
+cvtts $f6,$f9
+lds $f30,L.527
+cmpteq $f9,$f30,$f1
+fbne $f1,L.864
+lda $13,42
+cmpeq $14,$31,$23
+bne $23,L.866
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.866:
+L.864:
+ldt $f8,L.868
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+stq $27,-56+256($sp)
+ldt $f8,-56+256($sp)
+cvtqt $f8,$f8
+ldt $f30,L.414
+cmpteq $f8,$f30,$f1
+fbne $f1,L.869
+lda $13,43
+cmpeq $14,$31,$23
+bne $23,L.871
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.871:
+L.869:
+ldt $f8,L.868
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+stq $27,-56+256($sp)
+ldt $f8,-56+256($sp)
+cvtqt $f8,$f8
+ldt $f30,L.414
+cmpteq $f8,$f30,$f1
+fbne $f1,L.873
+lda $13,44
+cmpeq $14,$31,$23
+bne $23,L.875
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.875:
+L.873:
+ldt $f8,L.868
+lda $27,2
+stl $27,-68+256($sp)
+lds $f8,-68+256($sp)
+cvtlq $f8,$f8
+cvtqt $f8,$f8
+ldt $f30,L.414
+cmpteq $f8,$f30,$f1
+fbne $f1,L.877
+lda $13,45
+cmpeq $14,$31,$23
+bne $23,L.879
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.879:
+L.877:
+ldt $f8,L.868
+lda $27,2
+stq $27,-80+256($sp)
+ldt $f8,-80+256($sp)
+cvtqt $f8,$f8
+ldt $f30,L.414
+cmpteq $f8,$f30,$f1
+fbne $f1,L.881
+lda $13,46
+cmpeq $14,$31,$23
+bne $23,L.883
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.883:
+L.881:
+ldt $f8,L.868
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+ldt $f30,L.594
+srl $27,1,$25
+stq $25,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+mult $f30,$f29,$f30
+and $27,1,$27
+stq $27,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+addt $f30,$f29,$f8
+ldt $f30,L.414
+cmpteq $f8,$f30,$f1
+fbne $f1,L.885
+lda $13,47
+cmpeq $14,$31,$23
+bne $23,L.887
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.887:
+L.885:
+ldt $f8,L.868
+lds $f7,L.527
+cvtst $f7,$f8
+ldt $f30,L.414
+cmpteq $f8,$f30,$f1
+fbne $f1,L.889
+lda $13,48
+cmpeq $14,$31,$23
+bne $23,L.891
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.891:
+L.889:
+ldt $f8,L.868
+ldt $f30,L.414
+fmov $f30,$f6
+fmov $f6,$f8
+cmpteq $f8,$f30,$f1
+fbne $f1,L.893
+lda $13,49
+cmpeq $14,$31,$23
+bne $23,L.895
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.895:
+L.893:
+lda $12,5
+lda $27,2
+stb $27,-61+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+addl $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,7,$23
+bne $23,L.897
+lda $13,50
+cmpeq $14,$31,$23
+bne $23,L.899
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.899:
+L.897:
+lda $12,5
+lda $27,2
+stw $27,-64+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+addl $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,7,$23
+bne $23,L.901
+lda $13,51
+cmpeq $14,$31,$23
+bne $23,L.903
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.903:
+L.901:
+lda $12,5
+lda $27,2
+stl $27,-68+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+ldl $25,-68+256($sp)
+addl $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,7,$23
+bne $23,L.905
+lda $13,52
+cmpeq $14,$31,$23
+bne $23,L.907
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.907:
+L.905:
+lda $12,5
+lda $27,2
+stq $27,-80+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+ldq $25,-80+256($sp)
+addq $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,7,$23
+bne $23,L.909
+lda $13,53
+cmpeq $14,$31,$23
+bne $23,L.911
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.911:
+L.909:
+lda $12,5
+lda $27,2
+stl $27,-84+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+addl $27,$25,$27
+zap $27,240,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,7,$23
+bne $23,L.913
+lda $13,54
+cmpeq $14,$31,$23
+bne $23,L.915
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.915:
+L.913:
+lda $12,5
+lds $f7,L.527
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqs $f30,$f30
+adds $f30,$f7,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,7,$23
+bne $23,L.917
+lda $13,55
+cmpeq $14,$31,$23
+bne $23,L.919
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.919:
+L.917:
+lda $12,5
+ldt $f6,L.414
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqt $f30,$f30
+addt $f30,$f6,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,7,$23
+bne $23,L.921
+lda $13,56
+cmpeq $14,$31,$23
+bne $23,L.923
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.923:
+L.921:
+lda $11,5
+lda $27,2
+stb $27,-61+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+addl $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,7,$23
+bne $23,L.925
+lda $13,57
+cmpeq $14,$31,$23
+bne $23,L.927
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.927:
+L.925:
+lda $11,5
+lda $27,2
+stw $27,-64+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+addl $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,7,$23
+bne $23,L.929
+lda $13,58
+cmpeq $14,$31,$23
+bne $23,L.931
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.931:
+L.929:
+lda $11,5
+lda $27,2
+stl $27,-68+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+ldl $25,-68+256($sp)
+addl $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,7,$23
+bne $23,L.933
+lda $13,59
+cmpeq $14,$31,$23
+bne $23,L.935
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.935:
+L.933:
+lda $11,5
+lda $27,2
+stq $27,-80+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+ldq $25,-80+256($sp)
+addq $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,7,$23
+bne $23,L.937
+lda $13,60
+cmpeq $14,$31,$23
+bne $23,L.939
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.939:
+L.937:
+lda $11,5
+lda $27,2
+stl $27,-84+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+addl $27,$25,$27
+zap $27,240,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,7,$23
+bne $23,L.941
+lda $13,61
+cmpeq $14,$31,$23
+bne $23,L.943
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.943:
+L.941:
+lda $11,5
+lds $f7,L.527
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqs $f30,$f30
+adds $f30,$f7,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,7,$23
+bne $23,L.945
+lda $13,62
+cmpeq $14,$31,$23
+bne $23,L.947
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.947:
+L.945:
+lda $11,5
+ldt $f6,L.414
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqt $f30,$f30
+addt $f30,$f6,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,7,$23
+bne $23,L.949
+lda $13,63
+cmpeq $14,$31,$23
+bne $23,L.951
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.951:
+L.949:
+lda $10,5
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+addl $10,$27,$10
+cmpeq $10,7,$23
+bne $23,L.953
+lda $13,64
+cmpeq $14,$31,$23
+bne $23,L.955
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.955:
+L.953:
+lda $10,5
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+addl $10,$27,$10
+cmpeq $10,7,$23
+bne $23,L.957
+lda $13,65
+cmpeq $14,$31,$23
+bne $23,L.959
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.959:
+L.957:
+lda $10,5
+lda $27,2
+stl $27,-68+256($sp)
+ldl $27,-68+256($sp)
+addl $10,$27,$10
+cmpeq $10,7,$23
+bne $23,L.961
+lda $13,66
+cmpeq $14,$31,$23
+bne $23,L.963
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.963:
+L.961:
+lda $10,5
+lda $27,2
+stq $27,-80+256($sp)
+sll $10,8*(8-4),$27
+sra $27,8*(8-4),$27
+ldq $25,-80+256($sp)
+addq $27,$25,$27
+mov $27,$10
+cmpeq $10,7,$23
+bne $23,L.965
+lda $13,67
+cmpeq $14,$31,$23
+bne $23,L.967
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.967:
+L.965:
+lda $10,5
+lda $27,2
+stl $27,-84+256($sp)
+mov $10,$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+addl $27,$25,$27
+zap $27,240,$27
+mov $27,$10
+cmpeq $10,7,$23
+bne $23,L.969
+lda $13,68
+cmpeq $14,$31,$23
+bne $23,L.971
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.971:
+L.969:
+lda $10,5
+lds $f7,L.527
+stq $10,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqs $f30,$f30
+adds $f30,$f7,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $10,-56+256($sp)
+cmpeq $10,7,$23
+bne $23,L.973
+lda $13,69
+cmpeq $14,$31,$23
+bne $23,L.975
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.975:
+L.973:
+lda $10,5
+ldt $f6,L.414
+stq $10,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqt $f30,$f30
+addt $f30,$f6,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $10,-56+256($sp)
+cmpeq $10,7,$23
+bne $23,L.977
+lda $13,70
+cmpeq $14,$31,$23
+bne $23,L.979
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.979:
+L.977:
+lda $9,5
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+addq $9,$27,$9
+cmpeq $9,7,$23
+bne $23,L.981
+lda $13,71
+cmpeq $14,$31,$23
+bne $23,L.983
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.983:
+L.981:
+lda $9,5
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+addq $9,$27,$9
+cmpeq $9,7,$23
+bne $23,L.985
+lda $13,72
+cmpeq $14,$31,$23
+bne $23,L.987
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.987:
+L.985:
+lda $9,5
+lda $27,2
+stl $27,-68+256($sp)
+ldl $27,-68+256($sp)
+addq $9,$27,$9
+cmpeq $9,7,$23
+bne $23,L.989
+lda $13,73
+cmpeq $14,$31,$23
+bne $23,L.991
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.991:
+L.989:
+lda $9,5
+lda $27,2
+stq $27,-80+256($sp)
+ldq $27,-80+256($sp)
+addq $9,$27,$9
+cmpeq $9,7,$23
+bne $23,L.993
+lda $13,74
+cmpeq $14,$31,$23
+bne $23,L.995
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.995:
+L.993:
+lda $9,5
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+addq $9,$27,$9
+cmpeq $9,7,$23
+bne $23,L.997
+lda $13,75
+cmpeq $14,$31,$23
+bne $23,L.999
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.999:
+L.997:
+lda $9,5
+lds $f7,L.527
+stq $9,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqs $f30,$f30
+adds $f30,$f7,$f30
+cvttqc $f30,$f1
+stt $f1,-56+256($sp)
+ldq $9,-56+256($sp)
+cmpeq $9,7,$23
+bne $23,L.1001
+lda $13,76
+cmpeq $14,$31,$23
+bne $23,L.1003
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1003:
+L.1001:
+lda $9,5
+ldt $f6,L.414
+stq $9,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqt $f30,$f30
+addt $f30,$f6,$f30
+cvttqc $f30,$f1
+stt $f1,-56+256($sp)
+ldq $9,-56+256($sp)
+cmpeq $9,7,$23
+bne $23,L.1005
+lda $13,77
+cmpeq $14,$31,$23
+bne $23,L.1007
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1007:
+L.1005:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stb $27,-61+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+addl $27,$25,$27
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,7
+cmpeq $27,$25,$23
+bne $23,L.1009
+lda $13,78
+cmpeq $14,$31,$23
+bne $23,L.1011
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1011:
+L.1009:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stw $27,-64+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+addl $27,$25,$27
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,7
+cmpeq $27,$25,$23
+bne $23,L.1013
+lda $13,79
+cmpeq $14,$31,$23
+bne $23,L.1015
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1015:
+L.1013:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stl $27,-68+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldl $25,-68+256($sp)
+addl $27,$25,$27
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,7
+cmpeq $27,$25,$23
+bne $23,L.1017
+lda $13,80
+cmpeq $14,$31,$23
+bne $23,L.1019
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1019:
+L.1017:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stq $27,-80+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldq $25,-80+256($sp)
+addq $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,7
+cmpeq $27,$25,$23
+bne $23,L.1021
+lda $13,81
+cmpeq $14,$31,$23
+bne $23,L.1023
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1023:
+L.1021:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+addl $27,$25,$27
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,7
+cmpeq $27,$25,$23
+bne $23,L.1025
+lda $13,82
+cmpeq $14,$31,$23
+bne $23,L.1027
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1027:
+L.1025:
+lda $27,5
+stl $27,-60+256($sp)
+lds $f7,L.527
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldt $f30,L.594
+srl $27,1,$25
+stq $25,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+mult $f30,$f29,$f30
+and $27,1,$27
+stq $27,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+addt $f30,$f29,$f30
+cvtts $f30,$f30
+adds $f30,$f7,$f30
+lds $f29,L.826
+cmptlt $f30,$f29,$f1
+fbne $f1,L.1030
+subs $f30,$f29,$f29
+cvttqc $f29,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+addl $27,0x80000000,$27
+zap $27,240,$27
+stl $27,-120+256($sp)
+br L.1031
+L.1030:
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+stl $27,-120+256($sp)
+L.1031:
+ldl $27,-120+256($sp)
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,7
+cmpeq $27,$25,$23
+bne $23,L.1032
+lda $13,83
+cmpeq $14,$31,$23
+bne $23,L.1034
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1034:
+L.1032:
+lda $27,5
+stl $27,-60+256($sp)
+ldt $f6,L.414
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldt $f30,L.594
+srl $27,1,$25
+stq $25,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+mult $f30,$f29,$f30
+and $27,1,$27
+stq $27,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+addt $f30,$f29,$f30
+addt $f30,$f6,$f30
+ldt $f29,L.834
+cmptlt $f30,$f29,$f1
+fbne $f1,L.1037
+subt $f30,$f29,$f29
+cvttqc $f29,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+addl $27,0x80000000,$27
+zap $27,240,$27
+stl $27,-124+256($sp)
+br L.1038
+L.1037:
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+stl $27,-124+256($sp)
+L.1038:
+ldl $27,-124+256($sp)
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,7
+cmpeq $27,$25,$23
+bne $23,L.1039
+lda $13,84
+cmpeq $14,$31,$23
+bne $23,L.1041
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1041:
+L.1039:
+lds $f9,L.839
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqs $f30,$f30
+adds $f9,$f30,$f9
+lds $f30,L.1045
+cmpteq $f9,$f30,$f1
+fbne $f1,L.1043
+lda $13,85
+cmpeq $14,$31,$23
+bne $23,L.1046
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1046:
+L.1043:
+lds $f9,L.839
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqs $f30,$f30
+adds $f9,$f30,$f9
+lds $f30,L.1045
+cmpteq $f9,$f30,$f1
+fbne $f1,L.1048
+lda $13,86
+cmpeq $14,$31,$23
+bne $23,L.1050
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1050:
+L.1048:
+lds $f9,L.839
+lda $27,2
+stl $27,-68+256($sp)
+lds $f30,-68+256($sp)
+cvtlq $f30,$f30
+cvtqs $f30,$f30
+adds $f9,$f30,$f9
+lds $f30,L.1045
+cmpteq $f9,$f30,$f1
+fbne $f1,L.1052
+lda $13,87
+cmpeq $14,$31,$23
+bne $23,L.1054
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1054:
+L.1052:
+lds $f9,L.839
+lda $27,2
+stq $27,-80+256($sp)
+ldt $f30,-80+256($sp)
+cvtqs $f30,$f30
+adds $f9,$f30,$f9
+lds $f30,L.1045
+cmpteq $f9,$f30,$f1
+fbne $f1,L.1056
+lda $13,88
+cmpeq $14,$31,$23
+bne $23,L.1058
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1058:
+L.1056:
+lds $f9,L.839
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+ldt $f30,L.594
+srl $27,1,$25
+stq $25,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+mult $f30,$f29,$f30
+and $27,1,$27
+stq $27,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+addt $f30,$f29,$f30
+cvtts $f30,$f30
+adds $f9,$f30,$f9
+lds $f30,L.1045
+cmpteq $f9,$f30,$f1
+fbne $f1,L.1060
+lda $13,89
+cmpeq $14,$31,$23
+bne $23,L.1062
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1062:
+L.1060:
+lds $f9,L.839
+lds $f7,L.527
+adds $f9,$f7,$f9
+lds $f30,L.1045
+cmpteq $f9,$f30,$f1
+fbne $f1,L.1064
+lda $13,90
+cmpeq $14,$31,$23
+bne $23,L.1066
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1066:
+L.1064:
+lds $f9,L.839
+ldt $f6,L.414
+cvtst $f9,$f30
+addt $f30,$f6,$f30
+cvtts $f30,$f9
+lds $f30,L.1045
+cmpteq $f9,$f30,$f1
+fbne $f1,L.1068
+lda $13,91
+cmpeq $14,$31,$23
+bne $23,L.1070
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1070:
+L.1068:
+ldt $f8,L.868
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqt $f30,$f30
+addt $f8,$f30,$f8
+ldt $f30,L.1074
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1072
+lda $13,92
+cmpeq $14,$31,$23
+bne $23,L.1075
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1075:
+L.1072:
+ldt $f8,L.868
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqt $f30,$f30
+addt $f8,$f30,$f8
+ldt $f30,L.1074
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1077
+lda $13,93
+cmpeq $14,$31,$23
+bne $23,L.1079
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1079:
+L.1077:
+ldt $f8,L.868
+lda $27,2
+stl $27,-68+256($sp)
+lds $f30,-68+256($sp)
+cvtlq $f30,$f30
+cvtqt $f30,$f30
+addt $f8,$f30,$f8
+ldt $f30,L.1074
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1081
+lda $13,94
+cmpeq $14,$31,$23
+bne $23,L.1083
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1083:
+L.1081:
+ldt $f8,L.868
+lda $27,2
+stq $27,-80+256($sp)
+ldt $f30,-80+256($sp)
+cvtqt $f30,$f30
+addt $f8,$f30,$f8
+ldt $f30,L.1074
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1085
+lda $13,95
+cmpeq $14,$31,$23
+bne $23,L.1087
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1087:
+L.1085:
+ldt $f8,L.868
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+ldt $f30,L.594
+srl $27,1,$25
+stq $25,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+mult $f30,$f29,$f30
+and $27,1,$27
+stq $27,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+addt $f30,$f29,$f30
+addt $f8,$f30,$f8
+ldt $f30,L.1074
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1089
+lda $13,96
+cmpeq $14,$31,$23
+bne $23,L.1091
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1091:
+L.1089:
+ldt $f8,L.868
+lds $f7,L.527
+cvtst $f7,$f30
+addt $f8,$f30,$f8
+ldt $f30,L.1074
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1093
+lda $13,97
+cmpeq $14,$31,$23
+bne $23,L.1095
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1095:
+L.1093:
+ldt $f8,L.868
+ldt $f6,L.414
+addt $f8,$f6,$f8
+ldt $f30,L.1074
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1097
+lda $13,98
+cmpeq $14,$31,$23
+bne $23,L.1099
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1099:
+L.1097:
+lda $12,5
+lda $27,2
+stb $27,-61+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+subl $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,3,$23
+bne $23,L.1101
+lda $13,99
+cmpeq $14,$31,$23
+bne $23,L.1103
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1103:
+L.1101:
+lda $12,5
+lda $27,2
+stw $27,-64+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+subl $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,3,$23
+bne $23,L.1105
+lda $13,100
+cmpeq $14,$31,$23
+bne $23,L.1107
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1107:
+L.1105:
+lda $12,5
+lda $27,2
+stl $27,-68+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+ldl $25,-68+256($sp)
+subl $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,3,$23
+bne $23,L.1109
+lda $13,101
+cmpeq $14,$31,$23
+bne $23,L.1111
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1111:
+L.1109:
+lda $12,5
+lda $27,2
+stq $27,-80+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+ldq $25,-80+256($sp)
+subq $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,3,$23
+bne $23,L.1113
+lda $13,102
+cmpeq $14,$31,$23
+bne $23,L.1115
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1115:
+L.1113:
+lda $12,5
+lda $27,2
+stl $27,-84+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+subl $27,$25,$27
+zap $27,240,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,3,$23
+bne $23,L.1117
+lda $13,103
+cmpeq $14,$31,$23
+bne $23,L.1119
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1119:
+L.1117:
+lda $12,5
+lds $f7,L.527
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqs $f30,$f30
+subs $f30,$f7,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,3,$23
+bne $23,L.1121
+lda $13,104
+cmpeq $14,$31,$23
+bne $23,L.1123
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1123:
+L.1121:
+lda $12,5
+ldt $f6,L.414
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqt $f30,$f30
+subt $f30,$f6,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,3,$23
+bne $23,L.1125
+lda $13,105
+cmpeq $14,$31,$23
+bne $23,L.1127
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1127:
+L.1125:
+lda $11,5
+lda $27,2
+stb $27,-61+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+subl $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,3,$23
+bne $23,L.1129
+lda $13,106
+cmpeq $14,$31,$23
+bne $23,L.1131
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1131:
+L.1129:
+lda $11,5
+lda $27,2
+stw $27,-64+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+subl $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,3,$23
+bne $23,L.1133
+lda $13,107
+cmpeq $14,$31,$23
+bne $23,L.1135
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1135:
+L.1133:
+lda $11,5
+lda $27,2
+stl $27,-68+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+ldl $25,-68+256($sp)
+subl $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,3,$23
+bne $23,L.1137
+lda $13,108
+cmpeq $14,$31,$23
+bne $23,L.1139
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1139:
+L.1137:
+lda $11,5
+lda $27,2
+stq $27,-80+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+ldq $25,-80+256($sp)
+subq $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,3,$23
+bne $23,L.1141
+lda $13,109
+cmpeq $14,$31,$23
+bne $23,L.1143
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1143:
+L.1141:
+lda $11,5
+lda $27,2
+stl $27,-84+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+subl $27,$25,$27
+zap $27,240,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,3,$23
+bne $23,L.1145
+lda $13,110
+cmpeq $14,$31,$23
+bne $23,L.1147
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1147:
+L.1145:
+lda $11,5
+lds $f7,L.527
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqs $f30,$f30
+subs $f30,$f7,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,3,$23
+bne $23,L.1149
+lda $13,111
+cmpeq $14,$31,$23
+bne $23,L.1151
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1151:
+L.1149:
+lda $11,5
+ldt $f6,L.414
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqt $f30,$f30
+subt $f30,$f6,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,3,$23
+bne $23,L.1153
+lda $13,112
+cmpeq $14,$31,$23
+bne $23,L.1155
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1155:
+L.1153:
+lda $10,5
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+subl $10,$27,$10
+cmpeq $10,3,$23
+bne $23,L.1157
+lda $13,113
+cmpeq $14,$31,$23
+bne $23,L.1159
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1159:
+L.1157:
+lda $10,5
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+subl $10,$27,$10
+cmpeq $10,3,$23
+bne $23,L.1161
+lda $13,114
+cmpeq $14,$31,$23
+bne $23,L.1163
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1163:
+L.1161:
+lda $10,5
+lda $27,2
+stl $27,-68+256($sp)
+ldl $27,-68+256($sp)
+subl $10,$27,$10
+cmpeq $10,3,$23
+bne $23,L.1165
+lda $13,115
+cmpeq $14,$31,$23
+bne $23,L.1167
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1167:
+L.1165:
+lda $10,5
+lda $27,2
+stq $27,-80+256($sp)
+sll $10,8*(8-4),$27
+sra $27,8*(8-4),$27
+ldq $25,-80+256($sp)
+subq $27,$25,$27
+mov $27,$10
+cmpeq $10,3,$23
+bne $23,L.1169
+lda $13,116
+cmpeq $14,$31,$23
+bne $23,L.1171
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1171:
+L.1169:
+lda $10,5
+lda $27,2
+stl $27,-84+256($sp)
+mov $10,$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+subl $27,$25,$27
+zap $27,240,$27
+mov $27,$10
+cmpeq $10,3,$23
+bne $23,L.1173
+lda $13,117
+cmpeq $14,$31,$23
+bne $23,L.1175
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1175:
+L.1173:
+lda $10,5
+lds $f7,L.527
+stq $10,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqs $f30,$f30
+subs $f30,$f7,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $10,-56+256($sp)
+cmpeq $10,3,$23
+bne $23,L.1177
+lda $13,118
+cmpeq $14,$31,$23
+bne $23,L.1179
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1179:
+L.1177:
+lda $10,5
+ldt $f6,L.414
+stq $10,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqt $f30,$f30
+subt $f30,$f6,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $10,-56+256($sp)
+cmpeq $10,3,$23
+bne $23,L.1181
+lda $13,119
+cmpeq $14,$31,$23
+bne $23,L.1183
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1183:
+L.1181:
+lda $9,5
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+subq $9,$27,$9
+cmpeq $9,3,$23
+bne $23,L.1185
+lda $13,120
+cmpeq $14,$31,$23
+bne $23,L.1187
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1187:
+L.1185:
+lda $9,5
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+subq $9,$27,$9
+cmpeq $9,3,$23
+bne $23,L.1189
+lda $13,121
+cmpeq $14,$31,$23
+bne $23,L.1191
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1191:
+L.1189:
+lda $9,5
+lda $27,2
+stl $27,-68+256($sp)
+ldl $27,-68+256($sp)
+subq $9,$27,$9
+cmpeq $9,3,$23
+bne $23,L.1193
+lda $13,122
+cmpeq $14,$31,$23
+bne $23,L.1195
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1195:
+L.1193:
+lda $9,5
+lda $27,2
+stq $27,-80+256($sp)
+ldq $27,-80+256($sp)
+subq $9,$27,$9
+cmpeq $9,3,$23
+bne $23,L.1197
+lda $13,123
+cmpeq $14,$31,$23
+bne $23,L.1199
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1199:
+L.1197:
+lda $9,5
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+subq $9,$27,$9
+cmpeq $9,3,$23
+bne $23,L.1201
+lda $13,124
+cmpeq $14,$31,$23
+bne $23,L.1203
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1203:
+L.1201:
+lda $9,5
+lds $f7,L.527
+stq $9,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqs $f30,$f30
+subs $f30,$f7,$f30
+cvttqc $f30,$f1
+stt $f1,-56+256($sp)
+ldq $9,-56+256($sp)
+cmpeq $9,3,$23
+bne $23,L.1205
+lda $13,125
+cmpeq $14,$31,$23
+bne $23,L.1207
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1207:
+L.1205:
+lda $9,5
+ldt $f6,L.414
+stq $9,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqt $f30,$f30
+subt $f30,$f6,$f30
+cvttqc $f30,$f1
+stt $f1,-56+256($sp)
+ldq $9,-56+256($sp)
+cmpeq $9,3,$23
+bne $23,L.1209
+lda $13,126
+cmpeq $14,$31,$23
+bne $23,L.1211
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1211:
+L.1209:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stb $27,-61+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+subl $27,$25,$27
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,3
+cmpeq $27,$25,$23
+bne $23,L.1213
+lda $13,127
+cmpeq $14,$31,$23
+bne $23,L.1215
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1215:
+L.1213:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stw $27,-64+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+subl $27,$25,$27
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,3
+cmpeq $27,$25,$23
+bne $23,L.1217
+lda $13,128
+cmpeq $14,$31,$23
+bne $23,L.1219
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1219:
+L.1217:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stl $27,-68+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldl $25,-68+256($sp)
+subl $27,$25,$27
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,3
+cmpeq $27,$25,$23
+bne $23,L.1221
+lda $13,129
+cmpeq $14,$31,$23
+bne $23,L.1223
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1223:
+L.1221:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stq $27,-80+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldq $25,-80+256($sp)
+subq $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,3
+cmpeq $27,$25,$23
+bne $23,L.1225
+lda $13,130
+cmpeq $14,$31,$23
+bne $23,L.1227
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1227:
+L.1225:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+subl $27,$25,$27
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,3
+cmpeq $27,$25,$23
+bne $23,L.1229
+lda $13,131
+cmpeq $14,$31,$23
+bne $23,L.1231
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1231:
+L.1229:
+lda $27,5
+stl $27,-60+256($sp)
+lds $f7,L.527
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldt $f30,L.594
+srl $27,1,$25
+stq $25,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+mult $f30,$f29,$f30
+and $27,1,$27
+stq $27,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+addt $f30,$f29,$f30
+cvtts $f30,$f30
+subs $f30,$f7,$f30
+lds $f29,L.826
+cmptlt $f30,$f29,$f1
+fbne $f1,L.1234
+subs $f30,$f29,$f29
+cvttqc $f29,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+addl $27,0x80000000,$27
+zap $27,240,$27
+stl $27,-128+256($sp)
+br L.1235
+L.1234:
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+stl $27,-128+256($sp)
+L.1235:
+ldl $27,-128+256($sp)
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,3
+cmpeq $27,$25,$23
+bne $23,L.1236
+lda $13,132
+cmpeq $14,$31,$23
+bne $23,L.1238
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1238:
+L.1236:
+lda $27,5
+stl $27,-60+256($sp)
+ldt $f6,L.414
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldt $f30,L.594
+srl $27,1,$25
+stq $25,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+mult $f30,$f29,$f30
+and $27,1,$27
+stq $27,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+addt $f30,$f29,$f30
+subt $f30,$f6,$f30
+ldt $f29,L.834
+cmptlt $f30,$f29,$f1
+fbne $f1,L.1241
+subt $f30,$f29,$f29
+cvttqc $f29,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+addl $27,0x80000000,$27
+zap $27,240,$27
+stl $27,-132+256($sp)
+br L.1242
+L.1241:
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+stl $27,-132+256($sp)
+L.1242:
+ldl $27,-132+256($sp)
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,3
+cmpeq $27,$25,$23
+bne $23,L.1243
+lda $13,133
+cmpeq $14,$31,$23
+bne $23,L.1245
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1245:
+L.1243:
+lds $f9,L.839
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqs $f30,$f30
+subs $f9,$f30,$f9
+lds $f30,L.1249
+cmpteq $f9,$f30,$f1
+fbne $f1,L.1247
+lda $13,134
+cmpeq $14,$31,$23
+bne $23,L.1250
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1250:
+L.1247:
+lds $f9,L.839
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqs $f30,$f30
+subs $f9,$f30,$f9
+lds $f30,L.1249
+cmpteq $f9,$f30,$f1
+fbne $f1,L.1252
+lda $13,135
+cmpeq $14,$31,$23
+bne $23,L.1254
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1254:
+L.1252:
+lds $f9,L.839
+lda $27,2
+stl $27,-68+256($sp)
+lds $f30,-68+256($sp)
+cvtlq $f30,$f30
+cvtqs $f30,$f30
+subs $f9,$f30,$f9
+lds $f30,L.1249
+cmpteq $f9,$f30,$f1
+fbne $f1,L.1256
+lda $13,136
+cmpeq $14,$31,$23
+bne $23,L.1258
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1258:
+L.1256:
+lds $f9,L.839
+lda $27,2
+stq $27,-80+256($sp)
+ldt $f30,-80+256($sp)
+cvtqs $f30,$f30
+subs $f9,$f30,$f9
+lds $f30,L.1249
+cmpteq $f9,$f30,$f1
+fbne $f1,L.1260
+lda $13,137
+cmpeq $14,$31,$23
+bne $23,L.1262
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1262:
+L.1260:
+lds $f9,L.839
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+ldt $f30,L.594
+srl $27,1,$25
+stq $25,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+mult $f30,$f29,$f30
+and $27,1,$27
+stq $27,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+addt $f30,$f29,$f30
+cvtts $f30,$f30
+subs $f9,$f30,$f9
+lds $f30,L.1249
+cmpteq $f9,$f30,$f1
+fbne $f1,L.1264
+lda $13,138
+cmpeq $14,$31,$23
+bne $23,L.1266
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1266:
+L.1264:
+lds $f9,L.839
+lds $f7,L.527
+subs $f9,$f7,$f9
+lds $f30,L.1249
+cmpteq $f9,$f30,$f1
+fbne $f1,L.1268
+lda $13,139
+cmpeq $14,$31,$23
+bne $23,L.1270
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1270:
+L.1268:
+lds $f9,L.839
+ldt $f6,L.414
+cvtst $f9,$f30
+subt $f30,$f6,$f30
+cvtts $f30,$f9
+lds $f30,L.1249
+cmpteq $f9,$f30,$f1
+fbne $f1,L.1272
+lda $13,140
+cmpeq $14,$31,$23
+bne $23,L.1274
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1274:
+L.1272:
+ldt $f8,L.868
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqt $f30,$f30
+subt $f8,$f30,$f8
+ldt $f30,L.1278
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1276
+lda $13,141
+cmpeq $14,$31,$23
+bne $23,L.1279
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1279:
+L.1276:
+ldt $f8,L.868
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqt $f30,$f30
+subt $f8,$f30,$f8
+ldt $f30,L.1278
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1281
+lda $13,142
+cmpeq $14,$31,$23
+bne $23,L.1283
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1283:
+L.1281:
+ldt $f8,L.868
+lda $27,2
+stl $27,-68+256($sp)
+lds $f30,-68+256($sp)
+cvtlq $f30,$f30
+cvtqt $f30,$f30
+subt $f8,$f30,$f8
+ldt $f30,L.1278
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1285
+lda $13,143
+cmpeq $14,$31,$23
+bne $23,L.1287
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1287:
+L.1285:
+ldt $f8,L.868
+lda $27,2
+stq $27,-80+256($sp)
+ldt $f30,-80+256($sp)
+cvtqt $f30,$f30
+subt $f8,$f30,$f8
+ldt $f30,L.1278
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1289
+lda $13,144
+cmpeq $14,$31,$23
+bne $23,L.1291
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1291:
+L.1289:
+ldt $f8,L.868
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+ldt $f30,L.594
+srl $27,1,$25
+stq $25,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+mult $f30,$f29,$f30
+and $27,1,$27
+stq $27,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+addt $f30,$f29,$f30
+subt $f8,$f30,$f8
+ldt $f30,L.1278
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1293
+lda $13,145
+cmpeq $14,$31,$23
+bne $23,L.1295
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1295:
+L.1293:
+ldt $f8,L.868
+lds $f7,L.527
+cvtst $f7,$f30
+subt $f8,$f30,$f8
+ldt $f30,L.1278
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1297
+lda $13,146
+cmpeq $14,$31,$23
+bne $23,L.1299
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1299:
+L.1297:
+ldt $f8,L.868
+ldt $f6,L.414
+subt $f8,$f6,$f8
+ldt $f30,L.1278
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1301
+lda $13,147
+cmpeq $14,$31,$23
+bne $23,L.1303
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1303:
+L.1301:
+lda $12,5
+lda $27,2
+stb $27,-61+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+mull $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,10,$23
+bne $23,L.1305
+lda $13,148
+cmpeq $14,$31,$23
+bne $23,L.1307
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1307:
+L.1305:
+lda $12,5
+lda $27,2
+stw $27,-64+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+mull $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,10,$23
+bne $23,L.1309
+lda $13,149
+cmpeq $14,$31,$23
+bne $23,L.1311
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1311:
+L.1309:
+lda $12,5
+lda $27,2
+stl $27,-68+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+ldl $25,-68+256($sp)
+mull $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,10,$23
+bne $23,L.1313
+lda $13,150
+cmpeq $14,$31,$23
+bne $23,L.1315
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1315:
+L.1313:
+lda $12,5
+lda $27,2
+stq $27,-80+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+ldq $25,-80+256($sp)
+mulq $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,10,$23
+bne $23,L.1317
+lda $13,151
+cmpeq $14,$31,$23
+bne $23,L.1319
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1319:
+L.1317:
+lda $12,5
+lda $27,2
+stl $27,-84+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+mull $27,$25,$27
+zap $27,240,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,10,$23
+bne $23,L.1321
+lda $13,152
+cmpeq $14,$31,$23
+bne $23,L.1323
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1323:
+L.1321:
+lda $12,5
+lds $f7,L.527
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqs $f30,$f30
+muls $f30,$f7,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,10,$23
+bne $23,L.1325
+lda $13,153
+cmpeq $14,$31,$23
+bne $23,L.1327
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1327:
+L.1325:
+lda $12,5
+ldt $f6,L.414
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqt $f30,$f30
+mult $f30,$f6,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,10,$23
+bne $23,L.1329
+lda $13,154
+cmpeq $14,$31,$23
+bne $23,L.1331
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1331:
+L.1329:
+lda $11,5
+lda $27,2
+stb $27,-61+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+mull $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,10,$23
+bne $23,L.1333
+lda $13,155
+cmpeq $14,$31,$23
+bne $23,L.1335
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1335:
+L.1333:
+lda $11,5
+lda $27,2
+stw $27,-64+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+mull $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,10,$23
+bne $23,L.1337
+lda $13,156
+cmpeq $14,$31,$23
+bne $23,L.1339
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1339:
+L.1337:
+lda $11,5
+lda $27,2
+stl $27,-68+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+ldl $25,-68+256($sp)
+mull $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,10,$23
+bne $23,L.1341
+lda $13,157
+cmpeq $14,$31,$23
+bne $23,L.1343
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1343:
+L.1341:
+lda $11,5
+lda $27,2
+stq $27,-80+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+ldq $25,-80+256($sp)
+mulq $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,10,$23
+bne $23,L.1345
+lda $13,158
+cmpeq $14,$31,$23
+bne $23,L.1347
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1347:
+L.1345:
+lda $11,5
+lda $27,2
+stl $27,-84+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+mull $27,$25,$27
+zap $27,240,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,10,$23
+bne $23,L.1349
+lda $13,159
+cmpeq $14,$31,$23
+bne $23,L.1351
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1351:
+L.1349:
+lda $11,5
+lds $f7,L.527
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqs $f30,$f30
+muls $f30,$f7,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,10,$23
+bne $23,L.1353
+lda $13,160
+cmpeq $14,$31,$23
+bne $23,L.1355
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1355:
+L.1353:
+lda $11,5
+ldt $f6,L.414
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqt $f30,$f30
+mult $f30,$f6,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,10,$23
+bne $23,L.1357
+lda $13,161
+cmpeq $14,$31,$23
+bne $23,L.1359
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1359:
+L.1357:
+lda $10,5
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+mull $10,$27,$10
+cmpeq $10,10,$23
+bne $23,L.1361
+lda $13,162
+cmpeq $14,$31,$23
+bne $23,L.1363
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1363:
+L.1361:
+lda $10,5
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+mull $10,$27,$10
+cmpeq $10,10,$23
+bne $23,L.1365
+lda $13,163
+cmpeq $14,$31,$23
+bne $23,L.1367
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1367:
+L.1365:
+lda $10,5
+lda $27,2
+stl $27,-68+256($sp)
+ldl $27,-68+256($sp)
+mull $10,$27,$10
+cmpeq $10,10,$23
+bne $23,L.1369
+lda $13,164
+cmpeq $14,$31,$23
+bne $23,L.1371
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1371:
+L.1369:
+lda $10,5
+lda $27,2
+stq $27,-80+256($sp)
+sll $10,8*(8-4),$27
+sra $27,8*(8-4),$27
+ldq $25,-80+256($sp)
+mulq $27,$25,$27
+mov $27,$10
+cmpeq $10,10,$23
+bne $23,L.1373
+lda $13,165
+cmpeq $14,$31,$23
+bne $23,L.1375
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1375:
+L.1373:
+lda $10,5
+lda $27,2
+stl $27,-84+256($sp)
+mov $10,$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+mull $27,$25,$27
+zap $27,240,$27
+mov $27,$10
+cmpeq $10,10,$23
+bne $23,L.1377
+lda $13,166
+cmpeq $14,$31,$23
+bne $23,L.1379
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1379:
+L.1377:
+lda $10,5
+lds $f7,L.527
+stq $10,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqs $f30,$f30
+muls $f30,$f7,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $10,-56+256($sp)
+cmpeq $10,10,$23
+bne $23,L.1381
+lda $13,167
+cmpeq $14,$31,$23
+bne $23,L.1383
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1383:
+L.1381:
+lda $10,5
+ldt $f6,L.414
+stq $10,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqt $f30,$f30
+mult $f30,$f6,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $10,-56+256($sp)
+cmpeq $10,10,$23
+bne $23,L.1385
+lda $13,168
+cmpeq $14,$31,$23
+bne $23,L.1387
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1387:
+L.1385:
+lda $9,5
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+mulq $9,$27,$9
+cmpeq $9,10,$23
+bne $23,L.1389
+lda $13,169
+cmpeq $14,$31,$23
+bne $23,L.1391
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1391:
+L.1389:
+lda $9,5
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+mulq $9,$27,$9
+cmpeq $9,10,$23
+bne $23,L.1393
+lda $13,170
+cmpeq $14,$31,$23
+bne $23,L.1395
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1395:
+L.1393:
+lda $9,5
+lda $27,2
+stl $27,-68+256($sp)
+ldl $27,-68+256($sp)
+mulq $9,$27,$9
+cmpeq $9,10,$23
+bne $23,L.1397
+lda $13,171
+cmpeq $14,$31,$23
+bne $23,L.1399
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1399:
+L.1397:
+lda $9,5
+lda $27,2
+stq $27,-80+256($sp)
+ldq $27,-80+256($sp)
+mulq $9,$27,$9
+cmpeq $9,10,$23
+bne $23,L.1401
+lda $13,172
+cmpeq $14,$31,$23
+bne $23,L.1403
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1403:
+L.1401:
+lda $9,5
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+mulq $9,$27,$9
+cmpeq $9,10,$23
+bne $23,L.1405
+lda $13,173
+cmpeq $14,$31,$23
+bne $23,L.1407
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1407:
+L.1405:
+lda $9,5
+lds $f7,L.527
+stq $9,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqs $f30,$f30
+muls $f30,$f7,$f30
+cvttqc $f30,$f1
+stt $f1,-56+256($sp)
+ldq $9,-56+256($sp)
+cmpeq $9,10,$23
+bne $23,L.1409
+lda $13,174
+cmpeq $14,$31,$23
+bne $23,L.1411
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1411:
+L.1409:
+lda $9,5
+ldt $f6,L.414
+stq $9,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqt $f30,$f30
+mult $f30,$f6,$f30
+cvttqc $f30,$f1
+stt $f1,-56+256($sp)
+ldq $9,-56+256($sp)
+cmpeq $9,10,$23
+bne $23,L.1413
+lda $13,175
+cmpeq $14,$31,$23
+bne $23,L.1415
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1415:
+L.1413:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stb $27,-61+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+mull $27,$25,$27
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,10
+cmpeq $27,$25,$23
+bne $23,L.1417
+lda $13,176
+cmpeq $14,$31,$23
+bne $23,L.1419
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1419:
+L.1417:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stw $27,-64+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+mull $27,$25,$27
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,10
+cmpeq $27,$25,$23
+bne $23,L.1421
+lda $13,177
+cmpeq $14,$31,$23
+bne $23,L.1423
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1423:
+L.1421:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stl $27,-68+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldl $25,-68+256($sp)
+mull $27,$25,$27
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,10
+cmpeq $27,$25,$23
+bne $23,L.1425
+lda $13,178
+cmpeq $14,$31,$23
+bne $23,L.1427
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1427:
+L.1425:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stq $27,-80+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldq $25,-80+256($sp)
+mulq $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,10
+cmpeq $27,$25,$23
+bne $23,L.1429
+lda $13,179
+cmpeq $14,$31,$23
+bne $23,L.1431
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1431:
+L.1429:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+mull $27,$25,$27
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,10
+cmpeq $27,$25,$23
+bne $23,L.1433
+lda $13,180
+cmpeq $14,$31,$23
+bne $23,L.1435
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1435:
+L.1433:
+lda $27,5
+stl $27,-60+256($sp)
+lds $f7,L.527
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldt $f30,L.594
+srl $27,1,$25
+stq $25,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+mult $f30,$f29,$f30
+and $27,1,$27
+stq $27,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+addt $f30,$f29,$f30
+cvtts $f30,$f30
+muls $f30,$f7,$f30
+lds $f29,L.826
+cmptlt $f30,$f29,$f1
+fbne $f1,L.1438
+subs $f30,$f29,$f29
+cvttqc $f29,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+addl $27,0x80000000,$27
+zap $27,240,$27
+stl $27,-136+256($sp)
+br L.1439
+L.1438:
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+stl $27,-136+256($sp)
+L.1439:
+ldl $27,-136+256($sp)
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,10
+cmpeq $27,$25,$23
+bne $23,L.1440
+lda $13,181
+cmpeq $14,$31,$23
+bne $23,L.1442
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1442:
+L.1440:
+lda $27,5
+stl $27,-60+256($sp)
+ldt $f6,L.414
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldt $f30,L.594
+srl $27,1,$25
+stq $25,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+mult $f30,$f29,$f30
+and $27,1,$27
+stq $27,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+addt $f30,$f29,$f30
+mult $f30,$f6,$f30
+ldt $f29,L.834
+cmptlt $f30,$f29,$f1
+fbne $f1,L.1445
+subt $f30,$f29,$f29
+cvttqc $f29,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+addl $27,0x80000000,$27
+zap $27,240,$27
+stl $27,-140+256($sp)
+br L.1446
+L.1445:
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+stl $27,-140+256($sp)
+L.1446:
+ldl $27,-140+256($sp)
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,10
+cmpeq $27,$25,$23
+bne $23,L.1447
+lda $13,182
+cmpeq $14,$31,$23
+bne $23,L.1449
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1449:
+L.1447:
+lds $f9,L.839
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqs $f30,$f30
+muls $f9,$f30,$f9
+lds $f30,L.1453
+cmpteq $f9,$f30,$f1
+fbne $f1,L.1451
+lda $13,183
+cmpeq $14,$31,$23
+bne $23,L.1454
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1454:
+L.1451:
+lds $f9,L.839
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqs $f30,$f30
+muls $f9,$f30,$f9
+lds $f30,L.1453
+cmpteq $f9,$f30,$f1
+fbne $f1,L.1456
+lda $13,184
+cmpeq $14,$31,$23
+bne $23,L.1458
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1458:
+L.1456:
+lds $f9,L.839
+lda $27,2
+stl $27,-68+256($sp)
+lds $f30,-68+256($sp)
+cvtlq $f30,$f30
+cvtqs $f30,$f30
+muls $f9,$f30,$f9
+lds $f30,L.1453
+cmpteq $f9,$f30,$f1
+fbne $f1,L.1460
+lda $13,185
+cmpeq $14,$31,$23
+bne $23,L.1462
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1462:
+L.1460:
+lds $f9,L.839
+lda $27,2
+stq $27,-80+256($sp)
+ldt $f30,-80+256($sp)
+cvtqs $f30,$f30
+muls $f9,$f30,$f9
+lds $f30,L.1453
+cmpteq $f9,$f30,$f1
+fbne $f1,L.1464
+lda $13,186
+cmpeq $14,$31,$23
+bne $23,L.1466
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1466:
+L.1464:
+lds $f9,L.839
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+ldt $f30,L.594
+srl $27,1,$25
+stq $25,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+mult $f30,$f29,$f30
+and $27,1,$27
+stq $27,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+addt $f30,$f29,$f30
+cvtts $f30,$f30
+muls $f9,$f30,$f9
+lds $f30,L.1453
+cmpteq $f9,$f30,$f1
+fbne $f1,L.1468
+lda $13,187
+cmpeq $14,$31,$23
+bne $23,L.1470
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1470:
+L.1468:
+lds $f9,L.839
+lds $f7,L.527
+muls $f9,$f7,$f9
+lds $f30,L.1453
+cmpteq $f9,$f30,$f1
+fbne $f1,L.1472
+lda $13,188
+cmpeq $14,$31,$23
+bne $23,L.1474
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1474:
+L.1472:
+lds $f9,L.839
+ldt $f6,L.414
+cvtst $f9,$f30
+mult $f30,$f6,$f30
+cvtts $f30,$f9
+lds $f30,L.1453
+cmpteq $f9,$f30,$f1
+fbne $f1,L.1476
+lda $13,189
+cmpeq $14,$31,$23
+bne $23,L.1478
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1478:
+L.1476:
+ldt $f8,L.868
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqt $f30,$f30
+mult $f8,$f30,$f8
+ldt $f30,L.1482
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1480
+lda $13,190
+cmpeq $14,$31,$23
+bne $23,L.1483
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1483:
+L.1480:
+ldt $f8,L.868
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqt $f30,$f30
+mult $f8,$f30,$f8
+ldt $f30,L.1482
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1485
+lda $13,191
+cmpeq $14,$31,$23
+bne $23,L.1487
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1487:
+L.1485:
+ldt $f8,L.868
+lda $27,2
+stl $27,-68+256($sp)
+lds $f30,-68+256($sp)
+cvtlq $f30,$f30
+cvtqt $f30,$f30
+mult $f8,$f30,$f8
+ldt $f30,L.1482
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1489
+lda $13,192
+cmpeq $14,$31,$23
+bne $23,L.1491
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1491:
+L.1489:
+ldt $f8,L.868
+lda $27,2
+stq $27,-80+256($sp)
+ldt $f30,-80+256($sp)
+cvtqt $f30,$f30
+mult $f8,$f30,$f8
+ldt $f30,L.1482
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1493
+lda $13,193
+cmpeq $14,$31,$23
+bne $23,L.1495
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1495:
+L.1493:
+ldt $f8,L.868
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+ldt $f30,L.594
+srl $27,1,$25
+stq $25,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+mult $f30,$f29,$f30
+and $27,1,$27
+stq $27,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+addt $f30,$f29,$f30
+mult $f8,$f30,$f8
+ldt $f30,L.1482
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1497
+lda $13,194
+cmpeq $14,$31,$23
+bne $23,L.1499
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1499:
+L.1497:
+ldt $f8,L.868
+lds $f7,L.527
+cvtst $f7,$f30
+mult $f8,$f30,$f8
+ldt $f30,L.1482
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1501
+lda $13,195
+cmpeq $14,$31,$23
+bne $23,L.1503
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1503:
+L.1501:
+ldt $f8,L.868
+ldt $f6,L.414
+mult $f8,$f6,$f8
+ldt $f30,L.1482
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1505
+lda $13,196
+cmpeq $14,$31,$23
+bne $23,L.1507
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1507:
+L.1505:
+lda $12,5
+lda $27,2
+stb $27,-61+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+divl $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,2,$23
+bne $23,L.1509
+lda $13,197
+cmpeq $14,$31,$23
+bne $23,L.1511
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1511:
+L.1509:
+lda $12,5
+lda $27,2
+stw $27,-64+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+divl $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,2,$23
+bne $23,L.1513
+lda $13,198
+cmpeq $14,$31,$23
+bne $23,L.1515
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1515:
+L.1513:
+lda $12,5
+lda $27,2
+stl $27,-68+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+ldl $25,-68+256($sp)
+divl $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,2,$23
+bne $23,L.1517
+lda $13,199
+cmpeq $14,$31,$23
+bne $23,L.1519
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1519:
+L.1517:
+lda $12,5
+lda $27,2
+stq $27,-80+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+ldq $25,-80+256($sp)
+divq $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,2,$23
+bne $23,L.1521
+lda $13,200
+cmpeq $14,$31,$23
+bne $23,L.1523
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1523:
+L.1521:
+lda $12,5
+lda $27,2
+stl $27,-84+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+divlu $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,2,$23
+bne $23,L.1525
+lda $13,201
+cmpeq $14,$31,$23
+bne $23,L.1527
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1527:
+L.1525:
+lda $12,5
+lds $f7,L.527
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqs $f30,$f30
+divs $f30,$f7,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,2,$23
+bne $23,L.1529
+lda $13,202
+cmpeq $14,$31,$23
+bne $23,L.1531
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1531:
+L.1529:
+lda $12,5
+ldt $f6,L.414
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqt $f30,$f30
+divt $f30,$f6,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,2,$23
+bne $23,L.1533
+lda $13,203
+cmpeq $14,$31,$23
+bne $23,L.1535
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1535:
+L.1533:
+lda $11,5
+lda $27,2
+stb $27,-61+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+divl $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,2,$23
+bne $23,L.1537
+lda $13,204
+cmpeq $14,$31,$23
+bne $23,L.1539
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1539:
+L.1537:
+lda $11,5
+lda $27,2
+stw $27,-64+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+divl $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,2,$23
+bne $23,L.1541
+lda $13,205
+cmpeq $14,$31,$23
+bne $23,L.1543
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1543:
+L.1541:
+lda $11,5
+lda $27,2
+stl $27,-68+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+ldl $25,-68+256($sp)
+divl $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,2,$23
+bne $23,L.1545
+lda $13,206
+cmpeq $14,$31,$23
+bne $23,L.1547
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1547:
+L.1545:
+lda $11,5
+lda $27,2
+stq $27,-80+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+ldq $25,-80+256($sp)
+divq $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,2,$23
+bne $23,L.1549
+lda $13,207
+cmpeq $14,$31,$23
+bne $23,L.1551
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1551:
+L.1549:
+lda $11,5
+lda $27,2
+stl $27,-84+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+divlu $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,2,$23
+bne $23,L.1553
+lda $13,208
+cmpeq $14,$31,$23
+bne $23,L.1555
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1555:
+L.1553:
+lda $11,5
+lds $f7,L.527
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqs $f30,$f30
+divs $f30,$f7,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,2,$23
+bne $23,L.1557
+lda $13,209
+cmpeq $14,$31,$23
+bne $23,L.1559
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1559:
+L.1557:
+lda $11,5
+ldt $f6,L.414
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqt $f30,$f30
+divt $f30,$f6,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,2,$23
+bne $23,L.1561
+lda $13,210
+cmpeq $14,$31,$23
+bne $23,L.1563
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1563:
+L.1561:
+lda $10,5
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+divl $10,$27,$10
+cmpeq $10,2,$23
+bne $23,L.1565
+lda $13,211
+cmpeq $14,$31,$23
+bne $23,L.1567
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1567:
+L.1565:
+lda $10,5
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+divl $10,$27,$10
+cmpeq $10,2,$23
+bne $23,L.1569
+lda $13,212
+cmpeq $14,$31,$23
+bne $23,L.1571
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1571:
+L.1569:
+lda $10,5
+lda $27,2
+stl $27,-68+256($sp)
+ldl $27,-68+256($sp)
+divl $10,$27,$10
+cmpeq $10,2,$23
+bne $23,L.1573
+lda $13,213
+cmpeq $14,$31,$23
+bne $23,L.1575
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1575:
+L.1573:
+lda $10,5
+lda $27,2
+stq $27,-80+256($sp)
+sll $10,8*(8-4),$27
+sra $27,8*(8-4),$27
+ldq $25,-80+256($sp)
+divq $27,$25,$27
+mov $27,$10
+cmpeq $10,2,$23
+bne $23,L.1577
+lda $13,214
+cmpeq $14,$31,$23
+bne $23,L.1579
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1579:
+L.1577:
+lda $10,5
+lda $27,2
+stl $27,-84+256($sp)
+mov $10,$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+divlu $27,$25,$27
+mov $27,$10
+cmpeq $10,2,$23
+bne $23,L.1581
+lda $13,215
+cmpeq $14,$31,$23
+bne $23,L.1583
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1583:
+L.1581:
+lda $10,5
+lds $f7,L.527
+stq $10,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqs $f30,$f30
+divs $f30,$f7,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $10,-56+256($sp)
+cmpeq $10,2,$23
+bne $23,L.1585
+lda $13,216
+cmpeq $14,$31,$23
+bne $23,L.1587
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1587:
+L.1585:
+lda $10,5
+ldt $f6,L.414
+stq $10,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqt $f30,$f30
+divt $f30,$f6,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $10,-56+256($sp)
+cmpeq $10,2,$23
+bne $23,L.1589
+lda $13,217
+cmpeq $14,$31,$23
+bne $23,L.1591
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1591:
+L.1589:
+lda $9,5
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+divq $9,$27,$9
+cmpeq $9,2,$23
+bne $23,L.1593
+lda $13,218
+cmpeq $14,$31,$23
+bne $23,L.1595
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1595:
+L.1593:
+lda $9,5
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+divq $9,$27,$9
+cmpeq $9,2,$23
+bne $23,L.1597
+lda $13,219
+cmpeq $14,$31,$23
+bne $23,L.1599
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1599:
+L.1597:
+lda $9,5
+lda $27,2
+stl $27,-68+256($sp)
+ldl $27,-68+256($sp)
+divq $9,$27,$9
+cmpeq $9,2,$23
+bne $23,L.1601
+lda $13,220
+cmpeq $14,$31,$23
+bne $23,L.1603
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1603:
+L.1601:
+lda $9,5
+lda $27,2
+stq $27,-80+256($sp)
+ldq $27,-80+256($sp)
+divq $9,$27,$9
+cmpeq $9,2,$23
+bne $23,L.1605
+lda $13,221
+cmpeq $14,$31,$23
+bne $23,L.1607
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1607:
+L.1605:
+lda $9,5
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+divq $9,$27,$9
+cmpeq $9,2,$23
+bne $23,L.1609
+lda $13,222
+cmpeq $14,$31,$23
+bne $23,L.1611
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1611:
+L.1609:
+lda $9,5
+lds $f7,L.527
+stq $9,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqs $f30,$f30
+divs $f30,$f7,$f30
+cvttqc $f30,$f1
+stt $f1,-56+256($sp)
+ldq $9,-56+256($sp)
+cmpeq $9,2,$23
+bne $23,L.1613
+lda $13,223
+cmpeq $14,$31,$23
+bne $23,L.1615
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1615:
+L.1613:
+lda $9,5
+ldt $f6,L.414
+stq $9,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqt $f30,$f30
+divt $f30,$f6,$f30
+cvttqc $f30,$f1
+stt $f1,-56+256($sp)
+ldq $9,-56+256($sp)
+cmpeq $9,2,$23
+bne $23,L.1617
+lda $13,224
+cmpeq $14,$31,$23
+bne $23,L.1619
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1619:
+L.1617:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stb $27,-61+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+divlu $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,2
+cmpeq $27,$25,$23
+bne $23,L.1621
+lda $13,225
+cmpeq $14,$31,$23
+bne $23,L.1623
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1623:
+L.1621:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stw $27,-64+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+divlu $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,2
+cmpeq $27,$25,$23
+bne $23,L.1625
+lda $13,226
+cmpeq $14,$31,$23
+bne $23,L.1627
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1627:
+L.1625:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stl $27,-68+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldl $25,-68+256($sp)
+divlu $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,2
+cmpeq $27,$25,$23
+bne $23,L.1629
+lda $13,227
+cmpeq $14,$31,$23
+bne $23,L.1631
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1631:
+L.1629:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stq $27,-80+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldq $25,-80+256($sp)
+divq $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,2
+cmpeq $27,$25,$23
+bne $23,L.1633
+lda $13,228
+cmpeq $14,$31,$23
+bne $23,L.1635
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1635:
+L.1633:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stl $27,-144+256($sp)
+stl $27,-84+256($sp)
+ldl $25,-60+256($sp)
+zap $25,240,$25
+ldl $22,-84+256($sp)
+zap $22,240,$22
+divlu $25,$22,$25
+stl $25,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldl $25,-144+256($sp)
+zap $25,240,$25
+cmpeq $27,$25,$23
+bne $23,L.1637
+lda $13,229
+cmpeq $14,$31,$23
+bne $23,L.1639
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1639:
+L.1637:
+lda $27,5
+stl $27,-60+256($sp)
+lds $f7,L.527
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldt $f30,L.594
+srl $27,1,$25
+stq $25,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+mult $f30,$f29,$f30
+and $27,1,$27
+stq $27,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+addt $f30,$f29,$f30
+cvtts $f30,$f30
+divs $f30,$f7,$f30
+lds $f29,L.826
+cmptlt $f30,$f29,$f1
+fbne $f1,L.1642
+subs $f30,$f29,$f29
+cvttqc $f29,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+addl $27,0x80000000,$27
+zap $27,240,$27
+stl $27,-148+256($sp)
+br L.1643
+L.1642:
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+stl $27,-148+256($sp)
+L.1643:
+ldl $27,-148+256($sp)
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,2
+cmpeq $27,$25,$23
+bne $23,L.1644
+lda $13,230
+cmpeq $14,$31,$23
+bne $23,L.1646
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1646:
+L.1644:
+lda $27,5
+stl $27,-60+256($sp)
+ldt $f6,L.414
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldt $f30,L.594
+srl $27,1,$25
+stq $25,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+mult $f30,$f29,$f30
+and $27,1,$27
+stq $27,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+addt $f30,$f29,$f30
+divt $f30,$f6,$f30
+ldt $f29,L.834
+cmptlt $f30,$f29,$f1
+fbne $f1,L.1649
+subt $f30,$f29,$f29
+cvttqc $f29,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+addl $27,0x80000000,$27
+zap $27,240,$27
+stl $27,-152+256($sp)
+br L.1650
+L.1649:
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+stl $27,-152+256($sp)
+L.1650:
+ldl $27,-152+256($sp)
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,2
+cmpeq $27,$25,$23
+bne $23,L.1651
+lda $13,231
+cmpeq $14,$31,$23
+bne $23,L.1653
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1653:
+L.1651:
+lds $f9,L.839
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqs $f30,$f30
+divs $f9,$f30,$f9
+cvtst $f9,$f30
+ldt $f29,L.1657
+cmpteq $f30,$f29,$f1
+fbne $f1,L.1655
+lda $13,232
+cmpeq $14,$31,$23
+bne $23,L.1658
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1658:
+L.1655:
+lds $f9,L.839
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqs $f30,$f30
+divs $f9,$f30,$f9
+cvtst $f9,$f30
+ldt $f29,L.1657
+cmpteq $f30,$f29,$f1
+fbne $f1,L.1660
+lda $13,233
+cmpeq $14,$31,$23
+bne $23,L.1662
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1662:
+L.1660:
+lds $f9,L.839
+lda $27,2
+stl $27,-68+256($sp)
+lds $f30,-68+256($sp)
+cvtlq $f30,$f30
+cvtqs $f30,$f30
+divs $f9,$f30,$f9
+cvtst $f9,$f30
+ldt $f29,L.1657
+cmpteq $f30,$f29,$f1
+fbne $f1,L.1664
+lda $13,234
+cmpeq $14,$31,$23
+bne $23,L.1666
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1666:
+L.1664:
+lds $f9,L.839
+lda $27,2
+stq $27,-80+256($sp)
+ldt $f30,-80+256($sp)
+cvtqs $f30,$f30
+divs $f9,$f30,$f9
+cvtst $f9,$f30
+ldt $f29,L.1657
+cmpteq $f30,$f29,$f1
+fbne $f1,L.1668
+lda $13,235
+cmpeq $14,$31,$23
+bne $23,L.1670
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1670:
+L.1668:
+lds $f9,L.839
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+ldt $f30,L.594
+srl $27,1,$25
+stq $25,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+mult $f30,$f29,$f30
+and $27,1,$27
+stq $27,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+addt $f30,$f29,$f30
+cvtts $f30,$f30
+divs $f9,$f30,$f9
+cvtst $f9,$f30
+ldt $f29,L.1657
+cmpteq $f30,$f29,$f1
+fbne $f1,L.1672
+lda $13,236
+cmpeq $14,$31,$23
+bne $23,L.1674
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1674:
+L.1672:
+lds $f9,L.839
+lds $f7,L.527
+divs $f9,$f7,$f9
+cvtst $f9,$f30
+ldt $f29,L.1657
+cmpteq $f30,$f29,$f1
+fbne $f1,L.1676
+lda $13,237
+cmpeq $14,$31,$23
+bne $23,L.1678
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1678:
+L.1676:
+lds $f9,L.839
+ldt $f6,L.414
+cvtst $f9,$f30
+divt $f30,$f6,$f30
+cvtts $f30,$f9
+cvtst $f9,$f30
+ldt $f29,L.1657
+cmpteq $f30,$f29,$f1
+fbne $f1,L.1680
+lda $13,238
+cmpeq $14,$31,$23
+bne $23,L.1682
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1682:
+L.1680:
+ldt $f8,L.868
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqt $f30,$f30
+divt $f8,$f30,$f8
+ldt $f30,L.1657
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1684
+lda $13,239
+cmpeq $14,$31,$23
+bne $23,L.1686
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1686:
+L.1684:
+ldt $f8,L.868
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+stq $27,-56+256($sp)
+ldt $f30,-56+256($sp)
+cvtqt $f30,$f30
+divt $f8,$f30,$f8
+ldt $f30,L.1657
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1688
+lda $13,240
+cmpeq $14,$31,$23
+bne $23,L.1690
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1690:
+L.1688:
+ldt $f8,L.868
+lda $27,2
+stl $27,-68+256($sp)
+lds $f30,-68+256($sp)
+cvtlq $f30,$f30
+cvtqt $f30,$f30
+divt $f8,$f30,$f8
+ldt $f30,L.1657
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1692
+lda $13,241
+cmpeq $14,$31,$23
+bne $23,L.1694
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1694:
+L.1692:
+ldt $f8,L.868
+lda $27,2
+stq $27,-80+256($sp)
+ldt $f30,-80+256($sp)
+cvtqt $f30,$f30
+divt $f8,$f30,$f8
+ldt $f30,L.1657
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1696
+lda $13,242
+cmpeq $14,$31,$23
+bne $23,L.1698
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1698:
+L.1696:
+ldt $f8,L.868
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+ldt $f30,L.594
+srl $27,1,$25
+stq $25,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+mult $f30,$f29,$f30
+and $27,1,$27
+stq $27,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+addt $f30,$f29,$f30
+divt $f8,$f30,$f8
+ldt $f30,L.1657
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1700
+lda $13,243
+cmpeq $14,$31,$23
+bne $23,L.1702
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1702:
+L.1700:
+ldt $f8,L.868
+lds $f7,L.527
+cvtst $f7,$f30
+divt $f8,$f30,$f8
+ldt $f30,L.1657
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1704
+lda $13,244
+cmpeq $14,$31,$23
+bne $23,L.1706
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1706:
+L.1704:
+ldt $f8,L.868
+ldt $f6,L.414
+divt $f8,$f6,$f8
+ldt $f30,L.1657
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1708
+lda $13,245
+cmpeq $14,$31,$23
+bne $23,L.1710
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1710:
+L.1708:
+lda $12,5
+lda $27,2
+stb $27,-61+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+reml $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,1,$23
+bne $23,L.1712
+lda $13,246
+cmpeq $14,$31,$23
+bne $23,L.1714
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1714:
+L.1712:
+lda $12,5
+lda $27,2
+stw $27,-64+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+reml $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,1,$23
+bne $23,L.1716
+lda $13,247
+cmpeq $14,$31,$23
+bne $23,L.1718
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1718:
+L.1716:
+lda $12,5
+lda $27,2
+stl $27,-68+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+ldl $25,-68+256($sp)
+reml $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,1,$23
+bne $23,L.1720
+lda $13,248
+cmpeq $14,$31,$23
+bne $23,L.1722
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1722:
+L.1720:
+lda $12,5
+lda $27,2
+stq $27,-80+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+ldq $25,-80+256($sp)
+remq $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,1,$23
+bne $23,L.1724
+lda $13,249
+cmpeq $14,$31,$23
+bne $23,L.1726
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1726:
+L.1724:
+lda $12,5
+lda $27,2
+stl $27,-84+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+remlu $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,1,$23
+bne $23,L.1728
+lda $13,250
+cmpeq $14,$31,$23
+bne $23,L.1730
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1730:
+L.1728:
+lda $11,5
+lda $27,2
+stb $27,-61+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+reml $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,1,$23
+bne $23,L.1732
+lda $13,251
+cmpeq $14,$31,$23
+bne $23,L.1734
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1734:
+L.1732:
+lda $11,5
+lda $27,2
+stw $27,-64+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+reml $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,1,$23
+bne $23,L.1736
+lda $13,252
+cmpeq $14,$31,$23
+bne $23,L.1738
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1738:
+L.1736:
+lda $11,5
+lda $27,2
+stl $27,-68+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+ldl $25,-68+256($sp)
+reml $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,1,$23
+bne $23,L.1740
+lda $13,253
+cmpeq $14,$31,$23
+bne $23,L.1742
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1742:
+L.1740:
+lda $11,5
+lda $27,2
+stq $27,-80+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+ldq $25,-80+256($sp)
+remq $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,1,$23
+bne $23,L.1744
+lda $13,254
+cmpeq $14,$31,$23
+bne $23,L.1746
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1746:
+L.1744:
+lda $11,5
+lda $27,2
+stl $27,-84+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+remlu $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,1,$23
+bne $23,L.1748
+lda $13,255
+cmpeq $14,$31,$23
+bne $23,L.1750
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1750:
+L.1748:
+lda $10,5
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+reml $10,$27,$10
+cmpeq $10,1,$23
+bne $23,L.1752
+lda $13,256
+cmpeq $14,$31,$23
+bne $23,L.1754
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1754:
+L.1752:
+lda $10,5
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+reml $10,$27,$10
+cmpeq $10,1,$23
+bne $23,L.1756
+lda $13,257
+cmpeq $14,$31,$23
+bne $23,L.1758
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1758:
+L.1756:
+lda $10,5
+lda $27,2
+stl $27,-68+256($sp)
+ldl $27,-68+256($sp)
+reml $10,$27,$10
+cmpeq $10,1,$23
+bne $23,L.1760
+lda $13,258
+cmpeq $14,$31,$23
+bne $23,L.1762
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1762:
+L.1760:
+lda $10,5
+lda $27,2
+stq $27,-80+256($sp)
+sll $10,8*(8-4),$27
+sra $27,8*(8-4),$27
+ldq $25,-80+256($sp)
+remq $27,$25,$27
+mov $27,$10
+cmpeq $10,1,$23
+bne $23,L.1764
+lda $13,259
+cmpeq $14,$31,$23
+bne $23,L.1766
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1766:
+L.1764:
+lda $10,5
+lda $27,2
+stl $27,-84+256($sp)
+mov $10,$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+remlu $27,$25,$27
+mov $27,$10
+cmpeq $10,1,$23
+bne $23,L.1768
+lda $13,260
+cmpeq $14,$31,$23
+bne $23,L.1770
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1770:
+L.1768:
+lda $9,5
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+remq $9,$27,$9
+cmpeq $9,1,$23
+bne $23,L.1772
+lda $13,261
+cmpeq $14,$31,$23
+bne $23,L.1774
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1774:
+L.1772:
+lda $9,5
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+remq $9,$27,$9
+cmpeq $9,1,$23
+bne $23,L.1776
+lda $13,262
+cmpeq $14,$31,$23
+bne $23,L.1778
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1778:
+L.1776:
+lda $9,5
+lda $27,2
+stl $27,-68+256($sp)
+ldl $27,-68+256($sp)
+remq $9,$27,$9
+cmpeq $9,1,$23
+bne $23,L.1780
+lda $13,263
+cmpeq $14,$31,$23
+bne $23,L.1782
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1782:
+L.1780:
+lda $9,5
+lda $27,2
+stq $27,-80+256($sp)
+ldq $27,-80+256($sp)
+remq $9,$27,$9
+cmpeq $9,1,$23
+bne $23,L.1784
+lda $13,264
+cmpeq $14,$31,$23
+bne $23,L.1786
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1786:
+L.1784:
+lda $9,5
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+remq $9,$27,$9
+cmpeq $9,1,$23
+bne $23,L.1788
+lda $13,265
+cmpeq $14,$31,$23
+bne $23,L.1790
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1790:
+L.1788:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stb $27,-61+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+remlu $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,1
+cmpeq $27,$25,$23
+bne $23,L.1792
+lda $13,266
+cmpeq $14,$31,$23
+bne $23,L.1794
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1794:
+L.1792:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stw $27,-64+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+remlu $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,1
+cmpeq $27,$25,$23
+bne $23,L.1796
+lda $13,267
+cmpeq $14,$31,$23
+bne $23,L.1798
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1798:
+L.1796:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stl $27,-68+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldl $25,-68+256($sp)
+remlu $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,1
+cmpeq $27,$25,$23
+bne $23,L.1800
+lda $13,268
+cmpeq $14,$31,$23
+bne $23,L.1802
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1802:
+L.1800:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stq $27,-80+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldq $25,-80+256($sp)
+remq $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,1
+cmpeq $27,$25,$23
+bne $23,L.1804
+lda $13,269
+cmpeq $14,$31,$23
+bne $23,L.1806
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1806:
+L.1804:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+remlu $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,1
+cmpeq $27,$25,$23
+bne $23,L.1808
+lda $13,270
+cmpeq $14,$31,$23
+bne $23,L.1810
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1810:
+L.1808:
+lda $12,5
+lda $27,2
+stb $27,-61+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+sra $27,$25,$27
+addl $27,0,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,1,$23
+bne $23,L.1812
+lda $13,271
+cmpeq $14,$31,$23
+bne $23,L.1814
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1814:
+L.1812:
+lda $12,5
+lda $27,2
+stw $27,-64+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+sra $27,$25,$27
+addl $27,0,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,1,$23
+bne $23,L.1816
+lda $13,272
+cmpeq $14,$31,$23
+bne $23,L.1818
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1818:
+L.1816:
+lda $12,5
+lda $27,2
+stl $27,-68+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+ldl $25,-68+256($sp)
+sra $27,$25,$27
+addl $27,0,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,1,$23
+bne $23,L.1820
+lda $13,273
+cmpeq $14,$31,$23
+bne $23,L.1822
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1822:
+L.1820:
+lda $12,5
+lda $27,2
+stq $27,-80+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+ldq $25,-80+256($sp)
+sra $27,$25,$27
+addl $27,0,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,1,$23
+bne $23,L.1824
+lda $13,274
+cmpeq $14,$31,$23
+bne $23,L.1826
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1826:
+L.1824:
+lda $12,5
+lda $27,2
+stl $27,-84+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+sra $27,$25,$27
+addl $27,0,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,1,$23
+bne $23,L.1828
+lda $13,275
+cmpeq $14,$31,$23
+bne $23,L.1830
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1830:
+L.1828:
+lda $11,5
+lda $27,2
+stb $27,-61+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+sra $27,$25,$27
+addl $27,0,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,1,$23
+bne $23,L.1832
+lda $13,276
+cmpeq $14,$31,$23
+bne $23,L.1834
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1834:
+L.1832:
+lda $11,5
+lda $27,2
+stw $27,-64+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+sra $27,$25,$27
+addl $27,0,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,1,$23
+bne $23,L.1836
+lda $13,277
+cmpeq $14,$31,$23
+bne $23,L.1838
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1838:
+L.1836:
+lda $11,5
+lda $27,2
+stl $27,-68+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+ldl $25,-68+256($sp)
+sra $27,$25,$27
+addl $27,0,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,1,$23
+bne $23,L.1840
+lda $13,278
+cmpeq $14,$31,$23
+bne $23,L.1842
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1842:
+L.1840:
+lda $11,5
+lda $27,2
+stq $27,-80+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+ldq $25,-80+256($sp)
+sra $27,$25,$27
+addl $27,0,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,1,$23
+bne $23,L.1844
+lda $13,279
+cmpeq $14,$31,$23
+bne $23,L.1846
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1846:
+L.1844:
+lda $11,5
+lda $27,2
+stl $27,-84+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+sra $27,$25,$27
+addl $27,0,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,1,$23
+bne $23,L.1848
+lda $13,280
+cmpeq $14,$31,$23
+bne $23,L.1850
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1850:
+L.1848:
+lda $10,5
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+sra $10,$27,$10
+addl $10,0,$10
+cmpeq $10,1,$23
+bne $23,L.1852
+lda $13,281
+cmpeq $14,$31,$23
+bne $23,L.1854
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1854:
+L.1852:
+lda $10,5
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+sra $10,$27,$10
+addl $10,0,$10
+cmpeq $10,1,$23
+bne $23,L.1856
+lda $13,282
+cmpeq $14,$31,$23
+bne $23,L.1858
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1858:
+L.1856:
+lda $10,5
+lda $27,2
+stl $27,-68+256($sp)
+ldl $27,-68+256($sp)
+sra $10,$27,$10
+addl $10,0,$10
+cmpeq $10,1,$23
+bne $23,L.1860
+lda $13,283
+cmpeq $14,$31,$23
+bne $23,L.1862
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1862:
+L.1860:
+lda $10,5
+lda $27,2
+stq $27,-80+256($sp)
+ldq $27,-80+256($sp)
+sra $10,$27,$10
+addl $10,0,$10
+cmpeq $10,1,$23
+bne $23,L.1864
+lda $13,284
+cmpeq $14,$31,$23
+bne $23,L.1866
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1866:
+L.1864:
+lda $10,5
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+sra $10,$27,$10
+addl $10,0,$10
+cmpeq $10,1,$23
+bne $23,L.1868
+lda $13,285
+cmpeq $14,$31,$23
+bne $23,L.1870
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1870:
+L.1868:
+lda $9,5
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+sra $9,$27,$9
+cmpeq $9,1,$23
+bne $23,L.1872
+lda $13,286
+cmpeq $14,$31,$23
+bne $23,L.1874
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1874:
+L.1872:
+lda $9,5
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+sra $9,$27,$9
+cmpeq $9,1,$23
+bne $23,L.1876
+lda $13,287
+cmpeq $14,$31,$23
+bne $23,L.1878
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1878:
+L.1876:
+lda $9,5
+lda $27,2
+stl $27,-68+256($sp)
+ldl $27,-68+256($sp)
+sra $9,$27,$9
+cmpeq $9,1,$23
+bne $23,L.1880
+lda $13,288
+cmpeq $14,$31,$23
+bne $23,L.1882
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1882:
+L.1880:
+lda $9,5
+lda $27,2
+stq $27,-80+256($sp)
+ldq $27,-80+256($sp)
+sra $9,$27,$9
+cmpeq $9,1,$23
+bne $23,L.1884
+lda $13,289
+cmpeq $14,$31,$23
+bne $23,L.1886
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1886:
+L.1884:
+lda $9,5
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+sra $9,$27,$9
+cmpeq $9,1,$23
+bne $23,L.1888
+lda $13,290
+cmpeq $14,$31,$23
+bne $23,L.1890
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1890:
+L.1888:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stb $27,-61+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+srl $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,1
+cmpeq $27,$25,$23
+bne $23,L.1892
+lda $13,291
+cmpeq $14,$31,$23
+bne $23,L.1894
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1894:
+L.1892:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stw $27,-64+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+srl $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,1
+cmpeq $27,$25,$23
+bne $23,L.1896
+lda $13,292
+cmpeq $14,$31,$23
+bne $23,L.1898
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1898:
+L.1896:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stl $27,-68+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldl $25,-68+256($sp)
+srl $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,1
+cmpeq $27,$25,$23
+bne $23,L.1900
+lda $13,293
+cmpeq $14,$31,$23
+bne $23,L.1902
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1902:
+L.1900:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stq $27,-80+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldq $25,-80+256($sp)
+srl $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,1
+cmpeq $27,$25,$23
+bne $23,L.1904
+lda $13,294
+cmpeq $14,$31,$23
+bne $23,L.1906
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1906:
+L.1904:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+srl $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,1
+cmpeq $27,$25,$23
+bne $23,L.1908
+lda $13,295
+cmpeq $14,$31,$23
+bne $23,L.1910
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1910:
+L.1908:
+lda $12,5
+lda $27,2
+stb $27,-61+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+sll $27,$25,$27
+addl $27,0,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,20,$23
+bne $23,L.1912
+lda $13,296
+cmpeq $14,$31,$23
+bne $23,L.1914
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1914:
+L.1912:
+lda $12,5
+lda $27,2
+stw $27,-64+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+sll $27,$25,$27
+addl $27,0,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,20,$23
+bne $23,L.1916
+lda $13,297
+cmpeq $14,$31,$23
+bne $23,L.1918
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1918:
+L.1916:
+lda $12,5
+lda $27,2
+stl $27,-68+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+ldl $25,-68+256($sp)
+sll $27,$25,$27
+addl $27,0,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,20,$23
+bne $23,L.1920
+lda $13,298
+cmpeq $14,$31,$23
+bne $23,L.1922
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1922:
+L.1920:
+lda $12,5
+lda $27,2
+stq $27,-80+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+ldq $25,-80+256($sp)
+sll $27,$25,$27
+addl $27,0,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,20,$23
+bne $23,L.1924
+lda $13,299
+cmpeq $14,$31,$23
+bne $23,L.1926
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1926:
+L.1924:
+lda $12,5
+lda $27,2
+stl $27,-84+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+sll $27,$25,$27
+addl $27,0,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,20,$23
+bne $23,L.1928
+lda $13,300
+cmpeq $14,$31,$23
+bne $23,L.1930
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1930:
+L.1928:
+lda $11,5
+lda $27,2
+stb $27,-61+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+sll $27,$25,$27
+addl $27,0,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,20,$23
+bne $23,L.1932
+lda $13,301
+cmpeq $14,$31,$23
+bne $23,L.1934
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1934:
+L.1932:
+lda $11,5
+lda $27,2
+stw $27,-64+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+sll $27,$25,$27
+addl $27,0,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,20,$23
+bne $23,L.1936
+lda $13,302
+cmpeq $14,$31,$23
+bne $23,L.1938
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1938:
+L.1936:
+lda $11,5
+lda $27,2
+stl $27,-68+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+ldl $25,-68+256($sp)
+sll $27,$25,$27
+addl $27,0,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,20,$23
+bne $23,L.1940
+lda $13,303
+cmpeq $14,$31,$23
+bne $23,L.1942
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1942:
+L.1940:
+lda $11,5
+lda $27,2
+stq $27,-80+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+ldq $25,-80+256($sp)
+sll $27,$25,$27
+addl $27,0,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,20,$23
+bne $23,L.1944
+lda $13,304
+cmpeq $14,$31,$23
+bne $23,L.1946
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1946:
+L.1944:
+lda $11,5
+lda $27,2
+stl $27,-84+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+sll $27,$25,$27
+addl $27,0,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,20,$23
+bne $23,L.1948
+lda $13,305
+cmpeq $14,$31,$23
+bne $23,L.1950
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1950:
+L.1948:
+lda $10,5
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+sll $10,$27,$10
+addl $10,0,$10
+cmpeq $10,20,$23
+bne $23,L.1952
+lda $13,306
+cmpeq $14,$31,$23
+bne $23,L.1954
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1954:
+L.1952:
+lda $10,5
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+sll $10,$27,$10
+addl $10,0,$10
+cmpeq $10,20,$23
+bne $23,L.1956
+lda $13,307
+cmpeq $14,$31,$23
+bne $23,L.1958
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1958:
+L.1956:
+lda $10,5
+lda $27,2
+stl $27,-68+256($sp)
+ldl $27,-68+256($sp)
+sll $10,$27,$10
+addl $10,0,$10
+cmpeq $10,20,$23
+bne $23,L.1960
+lda $13,308
+cmpeq $14,$31,$23
+bne $23,L.1962
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1962:
+L.1960:
+lda $10,5
+lda $27,2
+stq $27,-80+256($sp)
+ldq $27,-80+256($sp)
+sll $10,$27,$10
+addl $10,0,$10
+cmpeq $10,20,$23
+bne $23,L.1964
+lda $13,309
+cmpeq $14,$31,$23
+bne $23,L.1966
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1966:
+L.1964:
+lda $10,5
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+sll $10,$27,$10
+addl $10,0,$10
+cmpeq $10,20,$23
+bne $23,L.1968
+lda $13,310
+cmpeq $14,$31,$23
+bne $23,L.1970
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1970:
+L.1968:
+lda $9,5
+lda $27,2
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+sll $9,$27,$9
+cmpeq $9,20,$23
+bne $23,L.1972
+lda $13,311
+cmpeq $14,$31,$23
+bne $23,L.1974
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1974:
+L.1972:
+lda $9,5
+lda $27,2
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+sll $9,$27,$9
+cmpeq $9,20,$23
+bne $23,L.1976
+lda $13,312
+cmpeq $14,$31,$23
+bne $23,L.1978
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1978:
+L.1976:
+lda $9,5
+lda $27,2
+stl $27,-68+256($sp)
+ldl $27,-68+256($sp)
+sll $9,$27,$9
+cmpeq $9,20,$23
+bne $23,L.1980
+lda $13,313
+cmpeq $14,$31,$23
+bne $23,L.1982
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1982:
+L.1980:
+lda $9,5
+lda $27,2
+stq $27,-80+256($sp)
+ldq $27,-80+256($sp)
+sll $9,$27,$9
+cmpeq $9,20,$23
+bne $23,L.1984
+lda $13,314
+cmpeq $14,$31,$23
+bne $23,L.1986
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1986:
+L.1984:
+lda $9,5
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+sll $9,$27,$9
+cmpeq $9,20,$23
+bne $23,L.1988
+lda $13,315
+cmpeq $14,$31,$23
+bne $23,L.1990
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1990:
+L.1988:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stb $27,-61+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+sll $27,$25,$27
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,20
+cmpeq $27,$25,$23
+bne $23,L.1992
+lda $13,316
+cmpeq $14,$31,$23
+bne $23,L.1994
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1994:
+L.1992:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stw $27,-64+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+sll $27,$25,$27
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,20
+cmpeq $27,$25,$23
+bne $23,L.1996
+lda $13,317
+cmpeq $14,$31,$23
+bne $23,L.1998
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.1998:
+L.1996:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stl $27,-68+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldl $25,-68+256($sp)
+sll $27,$25,$27
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,20
+cmpeq $27,$25,$23
+bne $23,L.2000
+lda $13,318
+cmpeq $14,$31,$23
+bne $23,L.2002
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2002:
+L.2000:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stq $27,-80+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldq $25,-80+256($sp)
+sll $27,$25,$27
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,20
+cmpeq $27,$25,$23
+bne $23,L.2004
+lda $13,319
+cmpeq $14,$31,$23
+bne $23,L.2006
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2006:
+L.2004:
+lda $27,5
+stl $27,-60+256($sp)
+lda $27,2
+stl $27,-84+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+sll $27,$25,$27
+zap $27,240,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,20
+cmpeq $27,$25,$23
+bne $23,L.2008
+lda $13,320
+cmpeq $14,$31,$23
+bne $23,L.2010
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2010:
+L.2008:
+lda $12,12
+lda $27,10
+stb $27,-61+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+and $27,$25,$27
+addl $27,0,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,8,$23
+bne $23,L.2012
+lda $13,321
+cmpeq $14,$31,$23
+bne $23,L.2014
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2014:
+L.2012:
+lda $12,12
+lda $27,10
+stw $27,-64+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+and $27,$25,$27
+addl $27,0,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,8,$23
+bne $23,L.2016
+lda $13,322
+cmpeq $14,$31,$23
+bne $23,L.2018
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2018:
+L.2016:
+lda $12,12
+lda $27,10
+stl $27,-68+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+ldl $25,-68+256($sp)
+and $27,$25,$27
+addl $27,0,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,8,$23
+bne $23,L.2020
+lda $13,323
+cmpeq $14,$31,$23
+bne $23,L.2022
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2022:
+L.2020:
+lda $12,12
+lda $27,10
+stq $27,-80+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+ldq $25,-80+256($sp)
+and $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,8,$23
+bne $23,L.2024
+lda $13,324
+cmpeq $14,$31,$23
+bne $23,L.2026
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2026:
+L.2024:
+lda $12,12
+lda $27,10
+stl $27,-84+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+and $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,8,$23
+bne $23,L.2028
+lda $13,325
+cmpeq $14,$31,$23
+bne $23,L.2030
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2030:
+L.2028:
+lda $11,12
+lda $27,10
+stb $27,-61+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+and $27,$25,$27
+addl $27,0,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,8,$23
+bne $23,L.2032
+lda $13,326
+cmpeq $14,$31,$23
+bne $23,L.2034
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2034:
+L.2032:
+lda $11,12
+lda $27,10
+stw $27,-64+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+and $27,$25,$27
+addl $27,0,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,8,$23
+bne $23,L.2036
+lda $13,327
+cmpeq $14,$31,$23
+bne $23,L.2038
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2038:
+L.2036:
+lda $11,12
+lda $27,10
+stl $27,-68+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+ldl $25,-68+256($sp)
+and $27,$25,$27
+addl $27,0,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,8,$23
+bne $23,L.2040
+lda $13,328
+cmpeq $14,$31,$23
+bne $23,L.2042
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2042:
+L.2040:
+lda $11,12
+lda $27,10
+stq $27,-80+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+ldq $25,-80+256($sp)
+and $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,8,$23
+bne $23,L.2044
+lda $13,329
+cmpeq $14,$31,$23
+bne $23,L.2046
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2046:
+L.2044:
+lda $11,12
+lda $27,10
+stl $27,-84+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+and $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,8,$23
+bne $23,L.2048
+lda $13,330
+cmpeq $14,$31,$23
+bne $23,L.2050
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2050:
+L.2048:
+lda $10,12
+lda $27,10
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+and $10,$27,$10
+addl $10,0,$10
+cmpeq $10,8,$23
+bne $23,L.2052
+lda $13,331
+cmpeq $14,$31,$23
+bne $23,L.2054
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2054:
+L.2052:
+lda $10,12
+lda $27,10
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+and $10,$27,$10
+addl $10,0,$10
+cmpeq $10,8,$23
+bne $23,L.2056
+lda $13,332
+cmpeq $14,$31,$23
+bne $23,L.2058
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2058:
+L.2056:
+lda $10,12
+lda $27,10
+stl $27,-68+256($sp)
+ldl $27,-68+256($sp)
+and $10,$27,$10
+addl $10,0,$10
+cmpeq $10,8,$23
+bne $23,L.2060
+lda $13,333
+cmpeq $14,$31,$23
+bne $23,L.2062
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2062:
+L.2060:
+lda $10,12
+lda $27,10
+stq $27,-80+256($sp)
+sll $10,8*(8-4),$27
+sra $27,8*(8-4),$27
+ldq $25,-80+256($sp)
+and $27,$25,$27
+mov $27,$10
+cmpeq $10,8,$23
+bne $23,L.2064
+lda $13,334
+cmpeq $14,$31,$23
+bne $23,L.2066
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2066:
+L.2064:
+lda $10,12
+lda $27,10
+stl $27,-84+256($sp)
+mov $10,$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+and $27,$25,$27
+mov $27,$10
+cmpeq $10,8,$23
+bne $23,L.2068
+lda $13,335
+cmpeq $14,$31,$23
+bne $23,L.2070
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2070:
+L.2068:
+lda $9,12
+lda $27,10
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+and $9,$27,$9
+cmpeq $9,8,$23
+bne $23,L.2072
+lda $13,336
+cmpeq $14,$31,$23
+bne $23,L.2074
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2074:
+L.2072:
+lda $9,12
+lda $27,10
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+and $9,$27,$9
+cmpeq $9,8,$23
+bne $23,L.2076
+lda $13,337
+cmpeq $14,$31,$23
+bne $23,L.2078
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2078:
+L.2076:
+lda $9,12
+lda $27,10
+stl $27,-68+256($sp)
+ldl $27,-68+256($sp)
+and $9,$27,$9
+cmpeq $9,8,$23
+bne $23,L.2080
+lda $13,338
+cmpeq $14,$31,$23
+bne $23,L.2082
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2082:
+L.2080:
+lda $9,12
+lda $27,10
+stq $27,-80+256($sp)
+ldq $27,-80+256($sp)
+and $9,$27,$9
+cmpeq $9,8,$23
+bne $23,L.2084
+lda $13,339
+cmpeq $14,$31,$23
+bne $23,L.2086
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2086:
+L.2084:
+lda $9,12
+lda $27,10
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+and $9,$27,$9
+cmpeq $9,8,$23
+bne $23,L.2088
+lda $13,340
+cmpeq $14,$31,$23
+bne $23,L.2090
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2090:
+L.2088:
+lda $27,12
+stl $27,-60+256($sp)
+lda $27,10
+stb $27,-61+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+and $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,8
+cmpeq $27,$25,$23
+bne $23,L.2092
+lda $13,341
+cmpeq $14,$31,$23
+bne $23,L.2094
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2094:
+L.2092:
+lda $27,12
+stl $27,-60+256($sp)
+lda $27,10
+stw $27,-64+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+and $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,8
+cmpeq $27,$25,$23
+bne $23,L.2096
+lda $13,342
+cmpeq $14,$31,$23
+bne $23,L.2098
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2098:
+L.2096:
+lda $27,12
+stl $27,-60+256($sp)
+lda $27,10
+stl $27,-68+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldl $25,-68+256($sp)
+and $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,8
+cmpeq $27,$25,$23
+bne $23,L.2100
+lda $13,343
+cmpeq $14,$31,$23
+bne $23,L.2102
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2102:
+L.2100:
+lda $27,12
+stl $27,-60+256($sp)
+lda $27,10
+stq $27,-80+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldq $25,-80+256($sp)
+and $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,8
+cmpeq $27,$25,$23
+bne $23,L.2104
+lda $13,344
+cmpeq $14,$31,$23
+bne $23,L.2106
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2106:
+L.2104:
+lda $27,12
+stl $27,-60+256($sp)
+lda $27,10
+stl $27,-84+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+and $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,8
+cmpeq $27,$25,$23
+bne $23,L.2108
+lda $13,345
+cmpeq $14,$31,$23
+bne $23,L.2110
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2110:
+L.2108:
+lda $12,12
+lda $27,10
+stb $27,-61+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+xor $27,$25,$27
+addl $27,0,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,6,$23
+bne $23,L.2112
+lda $13,346
+cmpeq $14,$31,$23
+bne $23,L.2114
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2114:
+L.2112:
+lda $12,12
+lda $27,10
+stw $27,-64+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+xor $27,$25,$27
+addl $27,0,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,6,$23
+bne $23,L.2116
+lda $13,347
+cmpeq $14,$31,$23
+bne $23,L.2118
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2118:
+L.2116:
+lda $12,12
+lda $27,10
+stl $27,-68+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+ldl $25,-68+256($sp)
+xor $27,$25,$27
+addl $27,0,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,6,$23
+bne $23,L.2120
+lda $13,348
+cmpeq $14,$31,$23
+bne $23,L.2122
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2122:
+L.2120:
+lda $12,12
+lda $27,10
+stq $27,-80+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+ldq $25,-80+256($sp)
+xor $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,6,$23
+bne $23,L.2124
+lda $13,349
+cmpeq $14,$31,$23
+bne $23,L.2126
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2126:
+L.2124:
+lda $12,12
+lda $27,10
+stl $27,-84+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+xor $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,6,$23
+bne $23,L.2128
+lda $13,350
+cmpeq $14,$31,$23
+bne $23,L.2130
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2130:
+L.2128:
+lda $11,12
+lda $27,10
+stb $27,-61+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+xor $27,$25,$27
+addl $27,0,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,6,$23
+bne $23,L.2132
+lda $13,351
+cmpeq $14,$31,$23
+bne $23,L.2134
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2134:
+L.2132:
+lda $11,12
+lda $27,10
+stw $27,-64+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+xor $27,$25,$27
+addl $27,0,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,6,$23
+bne $23,L.2136
+lda $13,352
+cmpeq $14,$31,$23
+bne $23,L.2138
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2138:
+L.2136:
+lda $11,12
+lda $27,10
+stl $27,-68+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+ldl $25,-68+256($sp)
+xor $27,$25,$27
+addl $27,0,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,6,$23
+bne $23,L.2140
+lda $13,353
+cmpeq $14,$31,$23
+bne $23,L.2142
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2142:
+L.2140:
+lda $11,12
+lda $27,10
+stq $27,-80+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+ldq $25,-80+256($sp)
+xor $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,6,$23
+bne $23,L.2144
+lda $13,354
+cmpeq $14,$31,$23
+bne $23,L.2146
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2146:
+L.2144:
+lda $11,12
+lda $27,10
+stl $27,-84+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+xor $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,6,$23
+bne $23,L.2148
+lda $13,355
+cmpeq $14,$31,$23
+bne $23,L.2150
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2150:
+L.2148:
+lda $10,12
+lda $27,10
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+xor $10,$27,$10
+addl $10,0,$10
+cmpeq $10,6,$23
+bne $23,L.2152
+lda $13,356
+cmpeq $14,$31,$23
+bne $23,L.2154
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2154:
+L.2152:
+lda $10,12
+lda $27,10
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+xor $10,$27,$10
+addl $10,0,$10
+cmpeq $10,6,$23
+bne $23,L.2156
+lda $13,357
+cmpeq $14,$31,$23
+bne $23,L.2158
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2158:
+L.2156:
+lda $10,12
+lda $27,10
+stl $27,-68+256($sp)
+ldl $27,-68+256($sp)
+xor $10,$27,$10
+addl $10,0,$10
+cmpeq $10,6,$23
+bne $23,L.2160
+lda $13,358
+cmpeq $14,$31,$23
+bne $23,L.2162
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2162:
+L.2160:
+lda $10,12
+lda $27,10
+stq $27,-80+256($sp)
+sll $10,8*(8-4),$27
+sra $27,8*(8-4),$27
+ldq $25,-80+256($sp)
+xor $27,$25,$27
+mov $27,$10
+cmpeq $10,6,$23
+bne $23,L.2164
+lda $13,359
+cmpeq $14,$31,$23
+bne $23,L.2166
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2166:
+L.2164:
+lda $10,12
+lda $27,10
+stl $27,-84+256($sp)
+mov $10,$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+xor $27,$25,$27
+mov $27,$10
+cmpeq $10,6,$23
+bne $23,L.2168
+lda $13,360
+cmpeq $14,$31,$23
+bne $23,L.2170
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2170:
+L.2168:
+lda $9,12
+lda $27,10
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+xor $9,$27,$9
+cmpeq $9,6,$23
+bne $23,L.2172
+lda $13,361
+cmpeq $14,$31,$23
+bne $23,L.2174
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2174:
+L.2172:
+lda $9,12
+lda $27,10
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+xor $9,$27,$9
+cmpeq $9,6,$23
+bne $23,L.2176
+lda $13,362
+cmpeq $14,$31,$23
+bne $23,L.2178
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2178:
+L.2176:
+lda $9,12
+lda $27,10
+stl $27,-68+256($sp)
+ldl $27,-68+256($sp)
+xor $9,$27,$9
+cmpeq $9,6,$23
+bne $23,L.2180
+lda $13,363
+cmpeq $14,$31,$23
+bne $23,L.2182
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2182:
+L.2180:
+lda $9,12
+lda $27,10
+stq $27,-80+256($sp)
+ldq $27,-80+256($sp)
+xor $9,$27,$9
+cmpeq $9,6,$23
+bne $23,L.2184
+lda $13,364
+cmpeq $14,$31,$23
+bne $23,L.2186
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2186:
+L.2184:
+lda $9,12
+lda $27,10
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+xor $9,$27,$9
+cmpeq $9,6,$23
+bne $23,L.2188
+lda $13,365
+cmpeq $14,$31,$23
+bne $23,L.2190
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2190:
+L.2188:
+lda $27,12
+stl $27,-60+256($sp)
+lda $27,10
+stb $27,-61+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+xor $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,6
+cmpeq $27,$25,$23
+bne $23,L.2192
+lda $13,366
+cmpeq $14,$31,$23
+bne $23,L.2194
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2194:
+L.2192:
+lda $27,12
+stl $27,-60+256($sp)
+lda $27,10
+stw $27,-64+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+xor $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,6
+cmpeq $27,$25,$23
+bne $23,L.2196
+lda $13,367
+cmpeq $14,$31,$23
+bne $23,L.2198
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2198:
+L.2196:
+lda $27,12
+stl $27,-60+256($sp)
+lda $27,10
+stl $27,-68+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldl $25,-68+256($sp)
+xor $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,6
+cmpeq $27,$25,$23
+bne $23,L.2200
+lda $13,368
+cmpeq $14,$31,$23
+bne $23,L.2202
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2202:
+L.2200:
+lda $27,12
+stl $27,-60+256($sp)
+lda $27,10
+stq $27,-80+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldq $25,-80+256($sp)
+xor $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,6
+cmpeq $27,$25,$23
+bne $23,L.2204
+lda $13,369
+cmpeq $14,$31,$23
+bne $23,L.2206
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2206:
+L.2204:
+lda $27,12
+stl $27,-60+256($sp)
+lda $27,10
+stl $27,-84+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+xor $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,6
+cmpeq $27,$25,$23
+bne $23,L.2208
+lda $13,370
+cmpeq $14,$31,$23
+bne $23,L.2210
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2210:
+L.2208:
+lda $12,12
+lda $27,10
+stb $27,-61+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+or $27,$25,$27
+addl $27,0,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,14,$23
+bne $23,L.2212
+lda $13,371
+cmpeq $14,$31,$23
+bne $23,L.2214
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2214:
+L.2212:
+lda $12,12
+lda $27,10
+stw $27,-64+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+or $27,$25,$27
+addl $27,0,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,14,$23
+bne $23,L.2216
+lda $13,372
+cmpeq $14,$31,$23
+bne $23,L.2218
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2218:
+L.2216:
+lda $12,12
+lda $27,10
+stl $27,-68+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+ldl $25,-68+256($sp)
+or $27,$25,$27
+addl $27,0,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,14,$23
+bne $23,L.2220
+lda $13,373
+cmpeq $14,$31,$23
+bne $23,L.2222
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2222:
+L.2220:
+lda $12,12
+lda $27,10
+stq $27,-80+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+ldq $25,-80+256($sp)
+or $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,14,$23
+bne $23,L.2224
+lda $13,374
+cmpeq $14,$31,$23
+bne $23,L.2226
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2226:
+L.2224:
+lda $12,12
+lda $27,10
+stl $27,-84+256($sp)
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+or $27,$25,$27
+mov $27,$12
+sll $12,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,14,$23
+bne $23,L.2228
+lda $13,375
+cmpeq $14,$31,$23
+bne $23,L.2230
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2230:
+L.2228:
+lda $11,12
+lda $27,10
+stb $27,-61+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+or $27,$25,$27
+addl $27,0,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,14,$23
+bne $23,L.2232
+lda $13,376
+cmpeq $14,$31,$23
+bne $23,L.2234
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2234:
+L.2232:
+lda $11,12
+lda $27,10
+stw $27,-64+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+or $27,$25,$27
+addl $27,0,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,14,$23
+bne $23,L.2236
+lda $13,377
+cmpeq $14,$31,$23
+bne $23,L.2238
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2238:
+L.2236:
+lda $11,12
+lda $27,10
+stl $27,-68+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+ldl $25,-68+256($sp)
+or $27,$25,$27
+addl $27,0,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,14,$23
+bne $23,L.2240
+lda $13,378
+cmpeq $14,$31,$23
+bne $23,L.2242
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2242:
+L.2240:
+lda $11,12
+lda $27,10
+stq $27,-80+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+ldq $25,-80+256($sp)
+or $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,14,$23
+bne $23,L.2244
+lda $13,379
+cmpeq $14,$31,$23
+bne $23,L.2246
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2246:
+L.2244:
+lda $11,12
+lda $27,10
+stl $27,-84+256($sp)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+or $27,$25,$27
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,14,$23
+bne $23,L.2248
+lda $13,380
+cmpeq $14,$31,$23
+bne $23,L.2250
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2250:
+L.2248:
+lda $10,12
+lda $27,10
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+or $10,$27,$10
+addl $10,0,$10
+cmpeq $10,14,$23
+bne $23,L.2252
+lda $13,381
+cmpeq $14,$31,$23
+bne $23,L.2254
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2254:
+L.2252:
+lda $10,12
+lda $27,10
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+or $10,$27,$10
+addl $10,0,$10
+cmpeq $10,14,$23
+bne $23,L.2256
+lda $13,382
+cmpeq $14,$31,$23
+bne $23,L.2258
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2258:
+L.2256:
+lda $10,12
+lda $27,10
+stl $27,-68+256($sp)
+ldl $27,-68+256($sp)
+or $10,$27,$10
+addl $10,0,$10
+cmpeq $10,14,$23
+bne $23,L.2260
+lda $13,383
+cmpeq $14,$31,$23
+bne $23,L.2262
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2262:
+L.2260:
+lda $10,12
+lda $27,10
+stq $27,-80+256($sp)
+sll $10,8*(8-4),$27
+sra $27,8*(8-4),$27
+ldq $25,-80+256($sp)
+or $27,$25,$27
+mov $27,$10
+cmpeq $10,14,$23
+bne $23,L.2264
+lda $13,384
+cmpeq $14,$31,$23
+bne $23,L.2266
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2266:
+L.2264:
+lda $10,12
+lda $27,10
+stl $27,-84+256($sp)
+mov $10,$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+or $27,$25,$27
+mov $27,$10
+cmpeq $10,14,$23
+bne $23,L.2268
+lda $13,385
+cmpeq $14,$31,$23
+bne $23,L.2270
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2270:
+L.2268:
+lda $9,12
+lda $27,10
+stb $27,-61+256($sp)
+lda $27,-61+256($sp)
+ldb $27,($27)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+or $9,$27,$9
+cmpeq $9,14,$23
+bne $23,L.2272
+lda $13,386
+cmpeq $14,$31,$23
+bne $23,L.2274
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2274:
+L.2272:
+lda $9,12
+lda $27,10
+stw $27,-64+256($sp)
+lda $27,-64+256($sp)
+ldw $27,($27)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+or $9,$27,$9
+cmpeq $9,14,$23
+bne $23,L.2276
+lda $13,387
+cmpeq $14,$31,$23
+bne $23,L.2278
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2278:
+L.2276:
+lda $9,12
+lda $27,10
+stl $27,-68+256($sp)
+ldl $27,-68+256($sp)
+or $9,$27,$9
+cmpeq $9,14,$23
+bne $23,L.2280
+lda $13,388
+cmpeq $14,$31,$23
+bne $23,L.2282
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2282:
+L.2280:
+lda $9,12
+lda $27,10
+stq $27,-80+256($sp)
+ldq $27,-80+256($sp)
+or $9,$27,$9
+cmpeq $9,14,$23
+bne $23,L.2284
+lda $13,389
+cmpeq $14,$31,$23
+bne $23,L.2286
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2286:
+L.2284:
+lda $9,12
+lda $27,10
+stl $27,-84+256($sp)
+ldl $27,-84+256($sp)
+zap $27,240,$27
+or $9,$27,$9
+cmpeq $9,14,$23
+bne $23,L.2288
+lda $13,390
+cmpeq $14,$31,$23
+bne $23,L.2290
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2290:
+L.2288:
+lda $27,12
+stl $27,-60+256($sp)
+lda $27,10
+stb $27,-61+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,-61+256($sp)
+ldb $25,($25)
+or $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,14
+cmpeq $27,$25,$23
+bne $23,L.2292
+lda $13,391
+cmpeq $14,$31,$23
+bne $23,L.2294
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2294:
+L.2292:
+lda $27,12
+stl $27,-60+256($sp)
+lda $27,10
+stw $27,-64+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,-64+256($sp)
+ldw $25,($25)
+or $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,14
+cmpeq $27,$25,$23
+bne $23,L.2296
+lda $13,392
+cmpeq $14,$31,$23
+bne $23,L.2298
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2298:
+L.2296:
+lda $27,12
+stl $27,-60+256($sp)
+lda $27,10
+stl $27,-68+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldl $25,-68+256($sp)
+or $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,14
+cmpeq $27,$25,$23
+bne $23,L.2300
+lda $13,393
+cmpeq $14,$31,$23
+bne $23,L.2302
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2302:
+L.2300:
+lda $27,12
+stl $27,-60+256($sp)
+lda $27,10
+stq $27,-80+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldq $25,-80+256($sp)
+or $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,14
+cmpeq $27,$25,$23
+bne $23,L.2304
+lda $13,394
+cmpeq $14,$31,$23
+bne $23,L.2306
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2306:
+L.2304:
+lda $27,12
+stl $27,-60+256($sp)
+lda $27,10
+stl $27,-84+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+ldl $25,-84+256($sp)
+zap $25,240,$25
+or $27,$25,$27
+stl $27,-60+256($sp)
+ldl $27,-60+256($sp)
+zap $27,240,$27
+lda $25,14
+cmpeq $27,$25,$23
+bne $23,L.2308
+lda $13,395
+cmpeq $14,$31,$23
+bne $23,L.2310
+lda $16,L.685
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2310:
+L.2308:
+cmpeq $13,$31,$23
+bne $23,L.2312
+lda $27,1
+stl $27,-108+256($sp)
+ldq $27,-48+256($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.2314
+lda $16,L.686
+lda $17,1
+jsr $26,printf
+ldgp $gp,0($26)
+L.2314:
+L.2312:
+ldl $0,-108+256($sp)
+L.684:
+ldt $f6,0($sp)
+ldt $f7,8($sp)
+ldt $f8,16($sp)
+ldt $f9,24($sp)
+ldq $9,32($sp)
+ldq $10,40($sp)
+ldq $11,48($sp)
+ldq $12,56($sp)
+ldq $13,64($sp)
+ldq $14,72($sp)
+ldq $24,80($sp)
+ldq $26,88($sp)
+lda $sp,256($sp)
+ret
+.end s714
+.sdata
+.align 0
+L.2317:
+.byte 115
+.byte 55
+.byte 49
+.byte 53
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.2318:
+.byte 115
+.byte 55
+.byte 49
+.byte 53
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s715
+.text
+.text
+.ent s715
+s715:
+ldgp $gp,0($27)
+lda $sp,-128($sp)
+.mask 0x5007800,-88
+.frame $sp,128,$26,48
+stq $11,0($sp)
+stq $12,8($sp)
+stq $13,16($sp)
+stq $14,24($sp)
+stq $24,32($sp)
+stq $26,40($sp)
+stq $16,80($sp)
+.prologue 1
+stl $31,-68+128($sp)
+stl $31,-60+128($sp)
+lda $14,L.2318
+ldq $25,-48+128($sp)
+lda $13,60($25)
+mov $31,$11
+L.2319:
+L.2320:
+mov $13,$27
+lda $13,1($27)
+mov $14,$25
+lda $14,1($25)
+ldb $25,($25)
+stb $25,($27)
+sll $25,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,$31,$23
+beq $23,L.2319
+lda $27,1
+mov $27,$12
+lda $12,1($12)
+lda $12,1($12)
+lda $12,1($12)
+lda $12,1($12)
+lda $27,1($12)
+mov $27,$12
+cmpeq $27,6,$23
+bne $23,L.2322
+ldq $27,-48+128($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.2324
+lda $16,L.2317
+lda $17,1
+jsr $26,printf
+ldgp $gp,0($26)
+L.2324:
+lda $11,1($11)
+L.2322:
+ldl $16,-60+128($sp)
+lda $27,3
+stl $27,-64+128($sp)
+ldl $27,-64+128($sp)
+lda $17,2($27)
+ldl $18,-68+128($sp)
+jsr $26,s715f
+ldgp $gp,0($26)
+cmpeq $0,5,$23
+bne $23,L.2326
+ldq $27,-48+128($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.2328
+lda $16,L.2317
+lda $17,2
+jsr $26,printf
+ldgp $gp,0($26)
+L.2328:
+lda $11,2($11)
+L.2326:
+mov $11,$0
+L.2316:
+ldq $11,0($sp)
+ldq $12,8($sp)
+ldq $13,16($sp)
+ldq $14,24($sp)
+ldq $24,32($sp)
+ldq $26,40($sp)
+lda $sp,128($sp)
+ret
+.end s715
+.globl s715f
+.text
+.ent s715f
+s715f:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.frame $sp,64,$26,48
+.prologue 1
+mov $17,$0
+L.2330:
+lda $sp,64($sp)
+ret
+.end s715f
+.sdata
+.align 0
+L.2332:
+.byte 115
+.byte 55
+.byte 50
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.2333:
+.byte 115
+.byte 55
+.byte 50
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s72
+.text
+.text
+.ent s72
+s72:
+ldgp $gp,0($27)
+lda $sp,-176($sp)
+.fmask 0x300,-168
+.mask 0x5007e00,-104
+.frame $sp,176,$26,48
+stt $f8,0($sp)
+stt $f9,8($sp)
+stq $9,16($sp)
+stq $10,24($sp)
+stq $11,32($sp)
+stq $12,40($sp)
+stq $13,48($sp)
+stq $14,56($sp)
+stq $24,64($sp)
+stq $26,72($sp)
+mov $16,$14
+.prologue 1
+lda $12,L.2333
+lda $11,60($14)
+mov $31,$9
+L.2334:
+L.2335:
+mov $11,$27
+lda $11,1($27)
+mov $12,$25
+lda $12,1($25)
+ldb $25,($25)
+stb $25,($27)
+sll $25,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,$31,$23
+beq $23,L.2334
+lda $27,2
+stl $27,-60+176($sp)
+ldl $27,-60+176($sp)
+cmpeq $27,2,$23
+bne $23,L.2337
+lda $27,1
+lda $9,1($9)
+lda $16,L.2332
+mov $27,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2337:
+ldl $27,-60+176($sp)
+negl $27,$25
+addl $27,$25,$27
+cmpeq $27,$31,$23
+bne $23,L.2339
+lda $27,2
+lda $9,2($9)
+lda $16,L.2332
+mov $27,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2339:
+stl $31,-60+176($sp)
+mov $31,$13
+br L.2344
+L.2341:
+ldl $27,-60+176($sp)
+sll $27,1,$27
+addl $27,0,$27
+or $27,1,$27
+addl $27,0,$27
+stl $27,-60+176($sp)
+L.2342:
+lda $13,1($13)
+L.2344:
+ldl $27,4($14)
+cmplt $13,$27,$23
+bne $23,L.2341
+ldl $27,-60+176($sp)
+not $27,$27
+addl $27,0,$27
+cmpeq $27,$31,$23
+bne $23,L.2345
+lda $27,4
+lda $9,4($9)
+lda $16,L.2332
+mov $27,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2345:
+lda $27,5
+stl $27,-60+176($sp)
+ldl $27,-60+176($sp)
+lda $27,1($27)
+stl $27,-60+176($sp)
+cmpeq $27,6,$23
+beq $23,L.2352
+ldl $27,-60+176($sp)
+subl $27,1,$27
+stl $27,-60+176($sp)
+cmpeq $27,5,$23
+beq $23,L.2352
+ldl $27,-60+176($sp)
+lda $25,1($27)
+stl $25,-60+176($sp)
+cmpeq $27,5,$23
+beq $23,L.2352
+ldl $27,-60+176($sp)
+subl $27,1,$25
+stl $25,-60+176($sp)
+cmpeq $27,6,$23
+beq $23,L.2352
+ldl $27,-60+176($sp)
+cmpeq $27,5,$23
+bne $23,L.2347
+L.2352:
+lda $27,8
+lda $9,8($9)
+lda $16,L.2332
+mov $27,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2347:
+lda $27,26
+stb $27,-65+176($sp)
+lda $27,26
+stq $27,-80+176($sp)
+ldt $f9,L.2353
+lda $27,26
+stw $27,-68+176($sp)
+lda $27,26
+stl $27,-84+176($sp)
+lda $27,26
+stl $27,-64+176($sp)
+lds $f8,L.2354
+mov $31,$10
+lda $27,-68+176($sp)
+ldw $27,($27)
+sll $27,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,26,$23
+beq $23,L.2361
+ldl $27,-64+176($sp)
+sll $27,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,26,$23
+beq $23,L.2361
+ldq $27,-80+176($sp)
+sll $27,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,26,$23
+beq $23,L.2361
+ldl $27,-84+176($sp)
+zap $27,240,$27
+sll $27,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,26,$23
+beq $23,L.2361
+cvttqc $f8,$f1
+cvtql $f1,$f1
+sts $f1,-56+176($sp)
+ldl $27,-56+176($sp)
+sll $27,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,26,$23
+beq $23,L.2361
+cvttqc $f9,$f1
+cvtql $f1,$f1
+sts $f1,-56+176($sp)
+ldl $27,-56+176($sp)
+sll $27,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,26,$23
+bne $23,L.2355
+L.2361:
+lda $10,1($10)
+L.2355:
+lda $27,-65+176($sp)
+ldb $27,($27)
+sll $27,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,26,$23
+beq $23,L.2368
+ldl $27,-64+176($sp)
+sll $27,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,26,$23
+beq $23,L.2368
+ldq $27,-80+176($sp)
+sll $27,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,26,$23
+beq $23,L.2368
+ldl $27,-84+176($sp)
+zap $27,240,$27
+sll $27,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,26,$23
+beq $23,L.2368
+cvttqc $f8,$f1
+cvtql $f1,$f1
+sts $f1,-56+176($sp)
+ldl $27,-56+176($sp)
+sll $27,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,26,$23
+beq $23,L.2368
+cvttqc $f9,$f1
+cvtql $f1,$f1
+sts $f1,-56+176($sp)
+ldl $27,-56+176($sp)
+sll $27,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,26,$23
+bne $23,L.2362
+L.2368:
+lda $10,2($10)
+L.2362:
+lda $27,-65+176($sp)
+ldb $27,($27)
+cmpeq $27,26,$23
+beq $23,L.2375
+lda $27,-68+176($sp)
+ldw $27,($27)
+cmpeq $27,26,$23
+beq $23,L.2375
+ldq $27,-80+176($sp)
+cmpeq $27,26,$23
+beq $23,L.2375
+ldl $27,-84+176($sp)
+zap $27,240,$27
+cmpeq $27,26,$23
+beq $23,L.2375
+cvttqc $f8,$f1
+cvtql $f1,$f1
+sts $f1,-56+176($sp)
+ldl $27,-56+176($sp)
+cmpeq $27,26,$23
+beq $23,L.2375
+cvttqc $f9,$f1
+cvtql $f1,$f1
+sts $f1,-56+176($sp)
+ldl $27,-56+176($sp)
+cmpeq $27,26,$23
+bne $23,L.2369
+L.2375:
+lda $10,4($10)
+L.2369:
+lda $27,-65+176($sp)
+ldb $27,($27)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+cmpeq $27,26,$23
+beq $23,L.2382
+lda $27,-68+176($sp)
+ldw $27,($27)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+cmpeq $27,26,$23
+beq $23,L.2382
+ldl $27,-64+176($sp)
+cmpeq $27,26,$23
+beq $23,L.2382
+ldl $27,-84+176($sp)
+zap $27,240,$27
+cmpeq $27,26,$23
+beq $23,L.2382
+cvttqc $f8,$f1
+stt $f1,-56+176($sp)
+ldq $27,-56+176($sp)
+cmpeq $27,26,$23
+beq $23,L.2382
+cvttqc $f9,$f1
+stt $f1,-56+176($sp)
+ldq $27,-56+176($sp)
+cmpeq $27,26,$23
+bne $23,L.2376
+L.2382:
+lda $10,8($10)
+L.2376:
+lda $27,26
+lda $25,-65+176($sp)
+ldb $25,($25)
+cmpeq $25,$27,$23
+beq $23,L.2391
+lda $25,-68+176($sp)
+ldw $25,($25)
+cmpeq $25,$27,$23
+beq $23,L.2391
+ldl $25,-64+176($sp)
+cmpeq $25,$27,$23
+beq $23,L.2391
+ldq $25,-80+176($sp)
+cmpeq $25,$27,$23
+beq $23,L.2391
+lds $f30,L.826
+cmptlt $f8,$f30,$f1
+fbne $f1,L.2392
+subs $f8,$f30,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+176($sp)
+ldl $27,-56+176($sp)
+addl $27,0x80000000,$27
+zap $27,240,$27
+stl $27,-88+176($sp)
+br L.2393
+L.2392:
+cvttqc $f8,$f1
+cvtql $f1,$f1
+sts $f1,-56+176($sp)
+ldl $27,-56+176($sp)
+stl $27,-88+176($sp)
+L.2393:
+ldl $27,-88+176($sp)
+zap $27,240,$27
+lda $25,26
+cmpeq $27,$25,$23
+beq $23,L.2391
+ldt $f30,L.834
+cmptlt $f9,$f30,$f1
+fbne $f1,L.2394
+subt $f9,$f30,$f30
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+176($sp)
+ldl $27,-56+176($sp)
+addl $27,0x80000000,$27
+zap $27,240,$27
+stl $27,-92+176($sp)
+br L.2395
+L.2394:
+cvttqc $f9,$f1
+cvtql $f1,$f1
+sts $f1,-56+176($sp)
+ldl $27,-56+176($sp)
+stl $27,-92+176($sp)
+L.2395:
+ldl $27,-92+176($sp)
+zap $27,240,$27
+lda $25,26
+cmpeq $27,$25,$23
+bne $23,L.2383
+L.2391:
+lda $10,16($10)
+L.2383:
+ldt $f30,L.2353
+lda $27,-65+176($sp)
+ldb $27,($27)
+stq $27,-56+176($sp)
+ldt $f29,-56+176($sp)
+cvtqs $f29,$f29
+cvtst $f29,$f29
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.2402
+lda $27,-68+176($sp)
+ldw $27,($27)
+stq $27,-56+176($sp)
+ldt $f29,-56+176($sp)
+cvtqs $f29,$f29
+cvtst $f29,$f29
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.2402
+lds $f29,-64+176($sp)
+cvtlq $f29,$f29
+cvtqs $f29,$f29
+cvtst $f29,$f29
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.2402
+ldt $f29,-80+176($sp)
+cvtqs $f29,$f29
+cvtst $f29,$f29
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.2402
+ldl $27,-84+176($sp)
+zap $27,240,$27
+ldt $f29,L.594
+srl $27,1,$25
+stq $25,-56+176($sp)
+ldt $f28,-56+176($sp)
+cvtqt $f28,$f28
+mult $f29,$f28,$f29
+and $27,1,$27
+stq $27,-56+176($sp)
+ldt $f28,-56+176($sp)
+cvtqt $f28,$f28
+addt $f29,$f28,$f29
+cvtts $f29,$f29
+cvtst $f29,$f29
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.2402
+cvtts $f9,$f29
+cvtst $f29,$f29
+cmpteq $f29,$f30,$f1
+fbne $f1,L.2396
+L.2402:
+lda $10,32($10)
+L.2396:
+ldt $f30,L.2353
+lda $27,-65+176($sp)
+ldb $27,($27)
+stq $27,-56+176($sp)
+ldt $f29,-56+176($sp)
+cvtqt $f29,$f29
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.2409
+lda $27,-68+176($sp)
+ldw $27,($27)
+stq $27,-56+176($sp)
+ldt $f29,-56+176($sp)
+cvtqt $f29,$f29
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.2409
+lds $f29,-64+176($sp)
+cvtlq $f29,$f29
+cvtqt $f29,$f29
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.2409
+ldt $f29,-80+176($sp)
+cvtqt $f29,$f29
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.2409
+ldl $27,-84+176($sp)
+zap $27,240,$27
+ldt $f29,L.594
+srl $27,1,$25
+stq $25,-56+176($sp)
+ldt $f28,-56+176($sp)
+cvtqt $f28,$f28
+mult $f29,$f28,$f29
+and $27,1,$27
+stq $27,-56+176($sp)
+ldt $f28,-56+176($sp)
+cvtqt $f28,$f28
+addt $f29,$f28,$f29
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.2409
+cvtst $f8,$f29
+cmpteq $f29,$f30,$f1
+fbne $f1,L.2403
+L.2409:
+lda $10,64($10)
+L.2403:
+cmpeq $10,$31,$23
+bne $23,L.2410
+lda $27,16
+lda $9,16($9)
+lda $16,L.2332
+mov $27,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2410:
+mov $9,$0
+L.2331:
+ldt $f8,0($sp)
+ldt $f9,8($sp)
+ldq $9,16($sp)
+ldq $10,24($sp)
+ldq $11,32($sp)
+ldq $12,40($sp)
+ldq $13,48($sp)
+ldq $14,56($sp)
+ldq $24,64($sp)
+ldq $26,72($sp)
+lda $sp,176($sp)
+ret
+.end s72
+.sdata
+.align 0
+L.2413:
+.byte 115
+.byte 55
+.byte 53
+.byte 55
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.2414:
+.byte 115
+.byte 55
+.byte 53
+.byte 55
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s757
+.text
+.text
+.ent s757
+s757:
+ldgp $gp,0($27)
+lda $sp,-272($sp)
+.mask 0x5007e00,-216
+.frame $sp,272,$26,48
+stq $9,0($sp)
+stq $10,8($sp)
+stq $11,16($sp)
+stq $12,24($sp)
+stq $13,32($sp)
+stq $14,40($sp)
+stq $24,48($sp)
+stq $26,56($sp)
+mov $16,$14
+.prologue 1
+lda $27,L.2414
+stq $27,-152+272($sp)
+lda $27,60($14)
+stq $27,-160+272($sp)
+stl $31,-164+272($sp)
+L.2415:
+L.2416:
+ldq $27,-160+272($sp)
+lda $25,1($27)
+stq $25,-160+272($sp)
+ldq $25,-152+272($sp)
+lda $22,1($25)
+stq $22,-152+272($sp)
+ldb $25,($25)
+stb $25,($27)
+sll $25,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,$31,$23
+beq $23,L.2415
+lda $27,40
+stl $27,-168+272($sp)
+ldl $27,-168+272($sp)
+sll $27,3,$25
+addl $25,0,$25
+sll $25,2,$25
+addl $25,0,$25
+lda $22,1280
+cmpeq $25,$22,$23
+beq $23,L.2420
+sra $27,3,$27
+addl $27,0,$27
+sra $27,2,$27
+addl $27,0,$27
+cmpeq $27,1,$23
+bne $23,L.2418
+L.2420:
+ldl $27,-164+272($sp)
+lda $27,1($27)
+stl $27,-164+272($sp)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.2421
+lda $16,L.2413
+lda $17,1
+jsr $26,printf
+ldgp $gp,0($26)
+L.2421:
+L.2418:
+mov $31,$9
+stl $31,-136+272($sp)
+br L.2426
+L.2423:
+lda $27,1
+stl $27,-128+272($sp)
+ldl $27,-128+272($sp)
+zap $27,240,$27
+ldl $25,16($14)
+subl $25,1,$25
+sll $27,$25,$27
+zap $27,240,$27
+stl $27,-132+272($sp)
+stl $31,-140+272($sp)
+ldl $27,-140+272($sp)
+zap $27,240,$27
+not $27,$27
+zap $27,240,$27
+ldl $25,-136+272($sp)
+srl $27,$25,$22
+stl $22,-144+272($sp)
+sll $27,$25,$27
+zap $27,240,$27
+stl $27,-140+272($sp)
+stl $31,-124+272($sp)
+br L.2430
+L.2427:
+ldl $27,-124+272($sp)
+ldl $25,-136+272($sp)
+cmplt $27,$25,$23
+beq $23,L.2438
+lda $27,1
+stl $27,-180+272($sp)
+br L.2439
+L.2438:
+stl $31,-180+272($sp)
+L.2439:
+ldl $27,-128+272($sp)
+zap $27,240,$27
+ldl $25,-140+272($sp)
+zap $25,240,$25
+and $27,$25,$27
+cmpeq $27,$31,$23
+beq $23,L.2440
+lda $27,1
+stl $27,-184+272($sp)
+br L.2441
+L.2440:
+stl $31,-184+272($sp)
+L.2441:
+ldl $27,-180+272($sp)
+ldl $25,-184+272($sp)
+cmpeq $27,$25,$23
+beq $23,L.2437
+ldl $27,-124+272($sp)
+ldl $25,-136+272($sp)
+cmplt $27,$25,$23
+beq $23,L.2442
+lda $27,1
+stl $27,-188+272($sp)
+br L.2443
+L.2442:
+stl $31,-188+272($sp)
+L.2443:
+ldl $27,-132+272($sp)
+zap $27,240,$27
+ldl $25,-144+272($sp)
+zap $25,240,$25
+and $27,$25,$27
+cmpeq $27,$31,$23
+beq $23,L.2444
+lda $27,1
+stl $27,-192+272($sp)
+br L.2445
+L.2444:
+stl $31,-192+272($sp)
+L.2445:
+ldl $27,-188+272($sp)
+ldl $25,-192+272($sp)
+cmpeq $27,$25,$23
+bne $23,L.2431
+L.2437:
+lda $9,1
+L.2431:
+ldl $27,-128+272($sp)
+zap $27,240,$27
+sll $27,1,$27
+zap $27,240,$27
+stl $27,-128+272($sp)
+ldl $27,-132+272($sp)
+zap $27,240,$27
+srl $27,1,$27
+stl $27,-132+272($sp)
+L.2428:
+ldl $27,-124+272($sp)
+lda $27,1($27)
+stl $27,-124+272($sp)
+L.2430:
+ldl $27,-124+272($sp)
+ldl $25,16($14)
+cmplt $27,$25,$23
+bne $23,L.2427
+L.2424:
+ldl $27,-136+272($sp)
+lda $27,1($27)
+stl $27,-136+272($sp)
+L.2426:
+ldl $27,-136+272($sp)
+ldl $25,16($14)
+cmplt $27,$25,$23
+bne $23,L.2423
+cmpeq $9,$31,$23
+bne $23,L.2446
+ldl $27,-164+272($sp)
+lda $27,2($27)
+stl $27,-164+272($sp)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.2448
+lda $16,L.2413
+lda $17,2
+jsr $26,printf
+ldgp $gp,0($26)
+L.2448:
+L.2446:
+lda $10,3
+lda $11,2
+lda $12,1
+cmplt $10,$11,$23
+beq $23,L.2456
+lda $27,1
+stl $27,-184+272($sp)
+br L.2457
+L.2456:
+stl $31,-184+272($sp)
+L.2457:
+ldl $27,-184+272($sp)
+cmplt $27,$12,$23
+beq $23,L.2454
+lda $27,1
+stl $27,-180+272($sp)
+br L.2455
+L.2454:
+stl $31,-180+272($sp)
+L.2455:
+ldl $27,-180+272($sp)
+cmpeq $27,1,$23
+bne $23,L.2450
+ldl $27,-164+272($sp)
+lda $27,4($27)
+stl $27,-164+272($sp)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.2458
+lda $16,L.2413
+lda $17,4
+jsr $26,printf
+ldgp $gp,0($26)
+L.2458:
+L.2450:
+lda $27,-116+272($sp)
+lda $25,-120+272($sp)
+cmpeq $27,$25,$23
+beq $23,L.2460
+ldl $27,-164+272($sp)
+lda $27,8($27)
+stl $27,-164+272($sp)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.2463
+lda $16,L.2413
+lda $17,8
+jsr $26,printf
+ldgp $gp,0($26)
+L.2463:
+L.2460:
+lda $27,-116+272($sp)
+lda $25,-120+272($sp)
+cmpult $27,$25,$23
+beq $23,L.2465
+ldl $27,40($14)
+cmpeq $27,$31,$23
+bne $23,L.2468
+lda $16,L.2470
+jsr $26,printf
+ldgp $gp,0($26)
+L.2468:
+L.2465:
+mov $31,$9
+stl $31,-124+272($sp)
+L.2471:
+ldl $27,-124+272($sp)
+sll $27,2,$27
+lda $25,-120+272($sp)
+addq $27,$25,$27
+lda $25,1
+stl $25,($27)
+L.2472:
+ldl $27,-124+272($sp)
+lda $27,1($27)
+stl $27,-124+272($sp)
+ldl $27,-124+272($sp)
+cmplt $27,16,$23
+bne $23,L.2471
+stl $31,-116+272($sp)
+stl $31,-104+272($sp)
+stl $31,-96+272($sp)
+stl $31,-92+272($sp)
+stl $31,-84+272($sp)
+stl $31,-68+272($sp)
+mov $31,$10
+L.2481:
+mov $31,$11
+L.2485:
+mov $31,$12
+L.2489:
+mov $31,$13
+L.2493:
+cmplt $10,$11,$23
+beq $23,L.2504
+lda $27,1
+stl $27,-192+272($sp)
+br L.2505
+L.2504:
+stl $31,-192+272($sp)
+L.2505:
+cmplt $12,$13,$23
+beq $23,L.2506
+lda $27,1
+stl $27,-196+272($sp)
+br L.2507
+L.2506:
+stl $31,-196+272($sp)
+L.2507:
+ldl $27,-192+272($sp)
+ldl $25,-196+272($sp)
+cmpeq $27,$25,$23
+beq $23,L.2502
+lda $27,1
+stl $27,-188+272($sp)
+br L.2503
+L.2502:
+stl $31,-188+272($sp)
+L.2503:
+ldl $27,-188+272($sp)
+sll $10,3,$25
+addl $25,0,$25
+sll $11,2,$22
+addl $22,0,$22
+addl $25,$22,$25
+sll $12,1,$22
+addl $22,0,$22
+addl $25,$22,$25
+addl $25,$13,$25
+sll $25,8*(8-4),$25
+sra $25,8*(8-4),$25
+sll $25,2,$25
+lda $22,-120+272($sp)
+addq $25,$22,$25
+ldl $25,($25)
+cmpeq $27,$25,$23
+bne $23,L.2497
+lda $9,1
+L.2497:
+L.2494:
+lda $13,1($13)
+cmplt $13,2,$23
+bne $23,L.2493
+L.2490:
+lda $12,1($12)
+cmplt $12,2,$23
+bne $23,L.2489
+L.2486:
+lda $11,1($11)
+cmplt $11,2,$23
+bne $23,L.2485
+L.2482:
+lda $10,1($10)
+cmplt $10,2,$23
+bne $23,L.2481
+cmpeq $9,$31,$23
+bne $23,L.2508
+ldl $27,-164+272($sp)
+lda $27,16($27)
+stl $27,-164+272($sp)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.2510
+lda $16,L.2413
+lda $17,16
+jsr $26,printf
+ldgp $gp,0($26)
+L.2510:
+L.2508:
+stq $31,-176+272($sp)
+ldq $27,-176+272($sp)
+cmpeq $27,$31,$23
+bne $23,L.2512
+ldl $27,-164+272($sp)
+lda $27,32($27)
+stl $27,-164+272($sp)
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.2514
+lda $16,L.2413
+lda $17,32
+jsr $26,printf
+ldgp $gp,0($26)
+L.2514:
+L.2512:
+ldl $0,-164+272($sp)
+L.2412:
+ldq $9,0($sp)
+ldq $10,8($sp)
+ldq $11,16($sp)
+ldq $12,24($sp)
+ldq $13,32($sp)
+ldq $14,40($sp)
+ldq $24,48($sp)
+ldq $26,56($sp)
+lda $sp,272($sp)
+ret
+.end s757
+.sdata
+.align 0
+L.2517:
+.byte 76
+.byte 111
+.byte 99
+.byte 97
+.byte 108
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 37
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.2518:
+.byte 115
+.byte 55
+.byte 56
+.byte 49
+.byte 51
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.2519:
+.byte 115
+.byte 55
+.byte 56
+.byte 49
+.byte 51
+.byte 32
+.byte 32
+.byte 0
+.globl s7813
+.text
+.text
+.ent s7813
+s7813:
+ldgp $gp,0($27)
+lda $sp,-192($sp)
+.mask 0x5007e00,-136
+.frame $sp,192,$26,48
+stq $9,0($sp)
+stq $10,8($sp)
+stq $11,16($sp)
+stq $12,24($sp)
+stq $13,32($sp)
+stq $14,40($sp)
+stq $24,48($sp)
+stq $26,56($sp)
+stq $16,144($sp)
+.prologue 1
+lda $9,L.2519
+ldq $27,-48+192($sp)
+lda $25,60($27)
+stq $25,-64+192($sp)
+mov $31,$13
+stl $31,-68+192($sp)
+ldl $14,48($27)
+L.2520:
+L.2521:
+ldq $27,-64+192($sp)
+lda $25,1($27)
+stq $25,-64+192($sp)
+mov $9,$25
+lda $9,1($25)
+ldb $25,($25)
+stb $25,($27)
+sll $25,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,$31,$23
+beq $23,L.2520
+br L.2523
+lda $13,1
+cmpeq $14,$31,$23
+bne $23,L.2525
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2525:
+L.2523:
+br L.2527
+lda $13,2
+cmpeq $14,$31,$23
+bne $23,L.2529
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2529:
+L.2527:
+br L.2531
+lda $13,3
+cmpeq $14,$31,$23
+bne $23,L.2533
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2533:
+L.2531:
+br L.2535
+lda $13,4
+cmpeq $14,$31,$23
+bne $23,L.2537
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2537:
+L.2535:
+br L.2539
+lda $13,5
+cmpeq $14,$31,$23
+bne $23,L.2541
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2541:
+L.2539:
+br L.2543
+lda $13,6
+cmpeq $14,$31,$23
+bne $23,L.2545
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2545:
+L.2543:
+br L.2547
+lda $13,7
+cmpeq $14,$31,$23
+bne $23,L.2549
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2549:
+L.2547:
+br L.2551
+lda $13,8
+cmpeq $14,$31,$23
+bne $23,L.2553
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2553:
+L.2551:
+br L.2555
+lda $13,9
+cmpeq $14,$31,$23
+bne $23,L.2557
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2557:
+L.2555:
+br L.2559
+lda $13,10
+cmpeq $14,$31,$23
+bne $23,L.2561
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2561:
+L.2559:
+br L.2563
+lda $13,11
+cmpeq $14,$31,$23
+bne $23,L.2565
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2565:
+L.2563:
+br L.2567
+lda $13,12
+cmpeq $14,$31,$23
+bne $23,L.2569
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2569:
+L.2567:
+br L.2571
+lda $13,13
+cmpeq $14,$31,$23
+bne $23,L.2573
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2573:
+L.2571:
+br L.2575
+lda $13,14
+cmpeq $14,$31,$23
+bne $23,L.2577
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2577:
+L.2575:
+br L.2579
+lda $13,15
+cmpeq $14,$31,$23
+bne $23,L.2581
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2581:
+L.2579:
+br L.2583
+lda $13,16
+cmpeq $14,$31,$23
+bne $23,L.2585
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2585:
+L.2583:
+br L.2587
+lda $13,17
+cmpeq $14,$31,$23
+bne $23,L.2589
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2589:
+L.2587:
+br L.2591
+lda $13,18
+cmpeq $14,$31,$23
+bne $23,L.2593
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2593:
+L.2591:
+br L.2595
+lda $13,16
+cmpeq $14,$31,$23
+bne $23,L.2597
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2597:
+L.2595:
+br L.2599
+lda $13,20
+cmpeq $14,$31,$23
+bne $23,L.2601
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2601:
+L.2599:
+br L.2603
+lda $13,21
+cmpeq $14,$31,$23
+bne $23,L.2605
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2605:
+L.2603:
+br L.2607
+lda $13,22
+cmpeq $14,$31,$23
+bne $23,L.2609
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2609:
+L.2607:
+br L.2611
+lda $13,23
+cmpeq $14,$31,$23
+bne $23,L.2613
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2613:
+L.2611:
+br L.2615
+lda $13,24
+cmpeq $14,$31,$23
+bne $23,L.2617
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2617:
+L.2615:
+br L.2619
+lda $13,25
+cmpeq $14,$31,$23
+bne $23,L.2621
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2621:
+L.2619:
+br L.2623
+lda $13,26
+cmpeq $14,$31,$23
+bne $23,L.2625
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2625:
+L.2623:
+br L.2627
+lda $13,27
+cmpeq $14,$31,$23
+bne $23,L.2629
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2629:
+L.2627:
+br L.2631
+lda $13,28
+cmpeq $14,$31,$23
+bne $23,L.2633
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2633:
+L.2631:
+br L.2635
+lda $13,26
+cmpeq $14,$31,$23
+bne $23,L.2637
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2637:
+L.2635:
+br L.2639
+lda $13,30
+cmpeq $14,$31,$23
+bne $23,L.2641
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2641:
+L.2639:
+br L.2643
+lda $13,31
+cmpeq $14,$31,$23
+bne $23,L.2645
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2645:
+L.2643:
+br L.2647
+lda $13,32
+cmpeq $14,$31,$23
+bne $23,L.2649
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2649:
+L.2647:
+br L.2651
+lda $13,33
+cmpeq $14,$31,$23
+bne $23,L.2653
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2653:
+L.2651:
+br L.2655
+lda $13,34
+cmpeq $14,$31,$23
+bne $23,L.2657
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2657:
+L.2655:
+br L.2659
+lda $13,35
+cmpeq $14,$31,$23
+bne $23,L.2661
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2661:
+L.2659:
+br L.2663
+lda $13,36
+cmpeq $14,$31,$23
+bne $23,L.2665
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2665:
+L.2663:
+br L.2667
+lda $13,37
+cmpeq $14,$31,$23
+bne $23,L.2669
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2669:
+L.2667:
+br L.2671
+lda $13,38
+cmpeq $14,$31,$23
+bne $23,L.2673
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2673:
+L.2671:
+br L.2675
+lda $13,39
+cmpeq $14,$31,$23
+bne $23,L.2677
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2677:
+L.2675:
+br L.2679
+lda $13,40
+cmpeq $14,$31,$23
+bne $23,L.2681
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2681:
+L.2679:
+br L.2683
+lda $13,41
+cmpeq $14,$31,$23
+bne $23,L.2685
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2685:
+L.2683:
+br L.2687
+lda $13,42
+cmpeq $14,$31,$23
+bne $23,L.2689
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2689:
+L.2687:
+br L.2691
+lda $13,43
+cmpeq $14,$31,$23
+bne $23,L.2693
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2693:
+L.2691:
+br L.2695
+lda $13,44
+cmpeq $14,$31,$23
+bne $23,L.2697
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2697:
+L.2695:
+br L.2699
+lda $13,45
+cmpeq $14,$31,$23
+bne $23,L.2701
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2701:
+L.2699:
+br L.2703
+lda $13,46
+cmpeq $14,$31,$23
+bne $23,L.2705
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2705:
+L.2703:
+br L.2707
+lda $13,47
+cmpeq $14,$31,$23
+bne $23,L.2709
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2709:
+L.2707:
+br L.2711
+lda $13,48
+cmpeq $14,$31,$23
+bne $23,L.2713
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2713:
+L.2711:
+br L.2715
+lda $13,49
+cmpeq $14,$31,$23
+bne $23,L.2717
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2717:
+L.2715:
+br L.2719
+lda $13,50
+cmpeq $14,$31,$23
+bne $23,L.2721
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2721:
+L.2719:
+br L.2723
+lda $13,51
+cmpeq $14,$31,$23
+bne $23,L.2725
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2725:
+L.2723:
+br L.2727
+lda $13,52
+cmpeq $14,$31,$23
+bne $23,L.2729
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2729:
+L.2727:
+br L.2731
+lda $13,53
+cmpeq $14,$31,$23
+bne $23,L.2733
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2733:
+L.2731:
+br L.2735
+lda $13,54
+cmpeq $14,$31,$23
+bne $23,L.2737
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2737:
+L.2735:
+br L.2739
+lda $13,55
+cmpeq $14,$31,$23
+bne $23,L.2741
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2741:
+L.2739:
+br L.2743
+lda $13,56
+cmpeq $14,$31,$23
+bne $23,L.2745
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2745:
+L.2743:
+br L.2747
+lda $13,57
+cmpeq $14,$31,$23
+bne $23,L.2749
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2749:
+L.2747:
+br L.2751
+lda $13,58
+cmpeq $14,$31,$23
+bne $23,L.2753
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2753:
+L.2751:
+br L.2755
+lda $13,56
+cmpeq $14,$31,$23
+bne $23,L.2757
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2757:
+L.2755:
+br L.2759
+lda $13,60
+cmpeq $14,$31,$23
+bne $23,L.2761
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2761:
+L.2759:
+br L.2763
+lda $13,61
+cmpeq $14,$31,$23
+bne $23,L.2765
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2765:
+L.2763:
+br L.2767
+lda $13,62
+cmpeq $14,$31,$23
+bne $23,L.2769
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2769:
+L.2767:
+br L.2771
+lda $13,63
+cmpeq $14,$31,$23
+bne $23,L.2773
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2773:
+L.2771:
+br L.2775
+lda $13,64
+cmpeq $14,$31,$23
+bne $23,L.2777
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2777:
+L.2775:
+br L.2779
+lda $13,65
+cmpeq $14,$31,$23
+bne $23,L.2781
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2781:
+L.2779:
+br L.2783
+lda $13,66
+cmpeq $14,$31,$23
+bne $23,L.2785
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2785:
+L.2783:
+br L.2787
+lda $13,67
+cmpeq $14,$31,$23
+bne $23,L.2789
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2789:
+L.2787:
+br L.2791
+lda $13,68
+cmpeq $14,$31,$23
+bne $23,L.2793
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2793:
+L.2791:
+br L.2795
+lda $13,69
+cmpeq $14,$31,$23
+bne $23,L.2797
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2797:
+L.2795:
+br L.2799
+lda $13,70
+cmpeq $14,$31,$23
+bne $23,L.2801
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2801:
+L.2799:
+br L.2803
+lda $13,71
+cmpeq $14,$31,$23
+bne $23,L.2805
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2805:
+L.2803:
+br L.2807
+lda $13,72
+cmpeq $14,$31,$23
+bne $23,L.2809
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2809:
+L.2807:
+br L.2811
+lda $13,73
+cmpeq $14,$31,$23
+bne $23,L.2813
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2813:
+L.2811:
+br L.2815
+lda $13,74
+cmpeq $14,$31,$23
+bne $23,L.2817
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2817:
+L.2815:
+br L.2819
+lda $13,75
+cmpeq $14,$31,$23
+bne $23,L.2821
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2821:
+L.2819:
+cmpeq $13,$31,$23
+bne $23,L.2823
+ldq $27,-48+192($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.2825
+lda $16,L.2518
+lda $17,1
+jsr $26,printf
+ldgp $gp,0($26)
+L.2825:
+ldl $27,-68+192($sp)
+lda $27,1($27)
+stl $27,-68+192($sp)
+L.2823:
+mov $31,$13
+mov $31,$11
+mov $31,$12
+mov $12,$27
+lda $12,1($27)
+mov $31,$25
+cmpeq $27,$25,$23
+bne $23,L.2828
+mov $11,$27
+lda $11,1($27)
+cmpeq $27,$25,$23
+bne $23,L.2828
+lda $27,1
+stl $27,-80+192($sp)
+br L.2829
+L.2828:
+stl $31,-80+192($sp)
+L.2829:
+ldl $10,-80+192($sp)
+cmpeq $12,1,$23
+bne $23,L.2830
+lda $13,1
+cmpeq $14,$31,$23
+bne $23,L.2832
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2832:
+L.2830:
+cmpeq $11,$31,$23
+bne $23,L.2834
+lda $13,2
+cmpeq $14,$31,$23
+bne $23,L.2836
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2836:
+L.2834:
+cmpeq $10,$31,$23
+bne $23,L.2838
+lda $13,3
+cmpeq $14,$31,$23
+bne $23,L.2840
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2840:
+L.2838:
+cmpeq $12,$31,$23
+bne $23,L.2843
+mov $11,$25
+lda $11,1($25)
+cmpeq $25,$31,$23
+bne $23,L.2843
+lda $27,1
+stl $27,-84+192($sp)
+br L.2844
+L.2843:
+stl $31,-84+192($sp)
+L.2844:
+ldl $10,-84+192($sp)
+cmpeq $12,1,$23
+bne $23,L.2845
+lda $13,4
+cmpeq $14,$31,$23
+bne $23,L.2847
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2847:
+L.2845:
+cmpeq $11,1,$23
+bne $23,L.2849
+lda $13,5
+cmpeq $14,$31,$23
+bne $23,L.2851
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2851:
+L.2849:
+cmpeq $10,$31,$23
+bne $23,L.2853
+lda $13,6
+cmpeq $14,$31,$23
+bne $23,L.2855
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2855:
+L.2853:
+mov $12,$27
+subl $27,1,$12
+mov $31,$25
+cmpeq $27,$25,$23
+bne $23,L.2858
+cmpeq $11,$25,$23
+bne $23,L.2858
+lda $27,1
+stl $27,-88+192($sp)
+br L.2859
+L.2858:
+stl $31,-88+192($sp)
+L.2859:
+ldl $10,-88+192($sp)
+cmpeq $12,$31,$23
+bne $23,L.2860
+lda $13,7
+cmpeq $14,$31,$23
+bne $23,L.2862
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2862:
+L.2860:
+cmpeq $11,1,$23
+bne $23,L.2864
+lda $13,8
+cmpeq $14,$31,$23
+bne $23,L.2866
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2866:
+L.2864:
+cmpeq $10,1,$23
+bne $23,L.2868
+lda $13,9
+cmpeq $14,$31,$23
+bne $23,L.2870
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2870:
+L.2868:
+cmpeq $12,$31,$23
+bne $23,L.2873
+mov $11,$25
+subl $25,1,$11
+cmpeq $25,$31,$23
+bne $23,L.2873
+lda $27,1
+stl $27,-92+192($sp)
+br L.2874
+L.2873:
+stl $31,-92+192($sp)
+L.2874:
+ldl $10,-92+192($sp)
+cmpeq $12,$31,$23
+bne $23,L.2875
+lda $13,10
+cmpeq $14,$31,$23
+bne $23,L.2877
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2877:
+L.2875:
+cmpeq $11,1,$23
+bne $23,L.2879
+lda $13,11
+cmpeq $14,$31,$23
+bne $23,L.2881
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2881:
+L.2879:
+cmpeq $10,$31,$23
+bne $23,L.2883
+lda $13,12
+cmpeq $14,$31,$23
+bne $23,L.2885
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2885:
+L.2883:
+cmpeq $13,$31,$23
+bne $23,L.2887
+ldq $27,-48+192($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.2889
+lda $16,L.2518
+lda $17,2
+jsr $26,printf
+ldgp $gp,0($26)
+L.2889:
+ldl $27,-68+192($sp)
+lda $27,2($27)
+stl $27,-68+192($sp)
+L.2887:
+mov $31,$13
+mov $31,$11
+mov $31,$12
+mov $12,$27
+lda $12,1($27)
+mov $31,$25
+cmpeq $27,$25,$23
+beq $23,L.2894
+cmpeq $11,$25,$23
+bne $23,L.2892
+L.2894:
+lda $27,1
+stl $27,-96+192($sp)
+br L.2893
+L.2892:
+stl $31,-96+192($sp)
+L.2893:
+ldl $10,-96+192($sp)
+cmpeq $12,1,$23
+bne $23,L.2895
+lda $13,1
+cmpeq $14,$31,$23
+bne $23,L.2897
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2897:
+L.2895:
+cmpeq $11,$31,$23
+bne $23,L.2899
+lda $13,2
+cmpeq $14,$31,$23
+bne $23,L.2901
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2901:
+L.2899:
+cmpeq $10,$31,$23
+bne $23,L.2903
+lda $13,3
+cmpeq $14,$31,$23
+bne $23,L.2905
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2905:
+L.2903:
+mov $11,$27
+lda $11,1($27)
+mov $31,$25
+cmpeq $27,$25,$23
+beq $23,L.2910
+cmpeq $12,$25,$23
+bne $23,L.2908
+L.2910:
+lda $27,1
+stl $27,-100+192($sp)
+br L.2909
+L.2908:
+stl $31,-100+192($sp)
+L.2909:
+ldl $10,-100+192($sp)
+cmpeq $12,1,$23
+bne $23,L.2911
+lda $13,4
+cmpeq $14,$31,$23
+bne $23,L.2913
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2913:
+L.2911:
+cmpeq $11,1,$23
+bne $23,L.2915
+lda $13,5
+cmpeq $14,$31,$23
+bne $23,L.2917
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2917:
+L.2915:
+cmpeq $10,1,$23
+bne $23,L.2919
+lda $13,6
+cmpeq $14,$31,$23
+bne $23,L.2921
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2921:
+L.2919:
+mov $12,$27
+subl $27,1,$12
+mov $31,$25
+cmpeq $27,$25,$23
+beq $23,L.2926
+mov $11,$27
+subl $27,1,$11
+cmpeq $27,$25,$23
+bne $23,L.2924
+L.2926:
+lda $27,1
+stl $27,-104+192($sp)
+br L.2925
+L.2924:
+stl $31,-104+192($sp)
+L.2925:
+ldl $10,-104+192($sp)
+cmpeq $12,$31,$23
+bne $23,L.2927
+lda $13,7
+cmpeq $14,$31,$23
+bne $23,L.2929
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2929:
+L.2927:
+cmpeq $11,1,$23
+bne $23,L.2931
+lda $13,8
+cmpeq $14,$31,$23
+bne $23,L.2933
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2933:
+L.2931:
+cmpeq $10,1,$23
+bne $23,L.2935
+lda $13,9
+cmpeq $14,$31,$23
+bne $23,L.2937
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2937:
+L.2935:
+mov $31,$27
+cmpeq $12,$27,$23
+beq $23,L.2942
+mov $11,$25
+subl $25,1,$11
+cmpeq $25,$27,$23
+bne $23,L.2940
+L.2942:
+lda $27,1
+stl $27,-108+192($sp)
+br L.2941
+L.2940:
+stl $31,-108+192($sp)
+L.2941:
+ldl $10,-108+192($sp)
+cmpeq $12,$31,$23
+bne $23,L.2943
+lda $13,10
+cmpeq $14,$31,$23
+bne $23,L.2945
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2945:
+L.2943:
+cmpeq $11,$31,$23
+bne $23,L.2947
+lda $13,11
+cmpeq $14,$31,$23
+bne $23,L.2949
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2949:
+L.2947:
+cmpeq $10,1,$23
+bne $23,L.2951
+lda $13,12
+cmpeq $14,$31,$23
+bne $23,L.2953
+lda $16,L.2517
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.2953:
+L.2951:
+cmpeq $13,$31,$23
+bne $23,L.2955
+ldq $27,-48+192($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.2957
+lda $16,L.2518
+lda $17,4
+jsr $26,printf
+ldgp $gp,0($26)
+L.2957:
+ldl $27,-68+192($sp)
+lda $27,4($27)
+stl $27,-68+192($sp)
+L.2955:
+mov $31,$11
+mov $31,$12
+stl $31,-72+192($sp)
+lda $25,1
+stl $25,-76+192($sp)
+ldl $25,-76+192($sp)
+cmpeq $25,$31,$23
+bne $23,L.2961
+ldl $27,-72+192($sp)
+stl $27,-112+192($sp)
+br L.2962
+L.2961:
+ldl $27,-76+192($sp)
+cmpeq $27,$31,$23
+bne $23,L.2963
+mov $12,$27
+lda $12,1($27)
+stl $27,-116+192($sp)
+br L.2964
+L.2963:
+mov $11,$27
+lda $11,1($27)
+stl $27,-116+192($sp)
+L.2964:
+ldl $27,-116+192($sp)
+stl $27,-112+192($sp)
+L.2962:
+ldl $10,-112+192($sp)
+cmpeq $10,$31,$23
+beq $23,L.2968
+cmpeq $12,$31,$23
+beq $23,L.2968
+cmpeq $11,$31,$23
+bne $23,L.2965
+L.2968:
+ldq $27,-48+192($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.2969
+lda $16,L.2518
+lda $17,8
+jsr $26,printf
+ldgp $gp,0($26)
+L.2969:
+ldl $27,-68+192($sp)
+lda $27,8($27)
+stl $27,-68+192($sp)
+L.2965:
+ldl $27,-76+192($sp)
+cmpeq $27,$31,$23
+bne $23,L.2976
+ldl $27,-72+192($sp)
+stl $27,-120+192($sp)
+br L.2977
+L.2976:
+lda $27,1
+stl $27,-120+192($sp)
+L.2977:
+ldl $25,-120+192($sp)
+cmpeq $25,$31,$23
+beq $23,L.2975
+ldl $25,-72+192($sp)
+cmpeq $25,$31,$23
+bne $23,L.2978
+lda $27,1
+stl $27,-124+192($sp)
+br L.2979
+L.2978:
+ldl $27,-72+192($sp)
+stl $27,-124+192($sp)
+L.2979:
+ldl $27,-124+192($sp)
+cmpeq $27,$31,$23
+bne $23,L.2971
+L.2975:
+ldq $27,-48+192($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.2980
+lda $16,L.2518
+lda $17,16
+jsr $26,printf
+ldgp $gp,0($26)
+L.2980:
+ldl $27,-68+192($sp)
+lda $27,16($27)
+stl $27,-68+192($sp)
+L.2971:
+ldl $0,-68+192($sp)
+L.2516:
+ldq $9,0($sp)
+ldq $10,8($sp)
+ldq $11,16($sp)
+ldq $12,24($sp)
+ldq $13,32($sp)
+ldq $14,40($sp)
+ldq $24,48($sp)
+ldq $26,56($sp)
+lda $sp,192($sp)
+ret
+.end s7813
+.sdata
+.align 0
+L.2983:
+.byte 115
+.byte 56
+.byte 49
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.2984:
+.byte 115
+.byte 56
+.byte 49
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.align 0
+L.2985:
+.byte 82
+.byte 101
+.byte 103
+.byte 105
+.byte 115
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 99
+.byte 111
+.byte 117
+.byte 110
+.byte 116
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 37
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 117
+.byte 110
+.byte 114
+.byte 101
+.byte 108
+.byte 105
+.byte 97
+.byte 98
+.byte 108
+.byte 101
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.2986:
+.byte 37
+.byte 100
+.byte 32
+.byte 114
+.byte 101
+.byte 103
+.byte 105
+.byte 115
+.byte 116
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 97
+.byte 115
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 101
+.byte 100
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 37
+.byte 115
+.byte 32
+.byte 118
+.byte 97
+.byte 114
+.byte 105
+.byte 97
+.byte 98
+.byte 108
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.globl s81
+.text
+.text
+.ent s81
+s81:
+ldgp $gp,0($27)
+lda $sp,-160($sp)
+.mask 0x5007e00,-104
+.frame $sp,160,$26,48
+stq $9,0($sp)
+stq $10,8($sp)
+stq $11,16($sp)
+stq $12,24($sp)
+stq $13,32($sp)
+stq $14,40($sp)
+stq $24,48($sp)
+stq $26,56($sp)
+stq $16,112($sp)
+.prologue 1
+stl $31,-96+160($sp)
+stl $31,-84+160($sp)
+stl $31,-88+160($sp)
+stl $31,-92+160($sp)
+lda $27,L.2984
+stq $27,-72+160($sp)
+ldq $27,-48+160($sp)
+lda $27,60($27)
+stq $27,-80+160($sp)
+L.2987:
+L.2988:
+ldq $27,-80+160($sp)
+lda $25,1($27)
+stq $25,-80+160($sp)
+ldq $25,-72+160($sp)
+lda $22,1($25)
+stq $22,-72+160($sp)
+ldb $25,($25)
+stb $25,($27)
+sll $25,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,$31,$23
+beq $23,L.2987
+lda $27,1
+stl $27,-60+160($sp)
+mov $31,$11
+L.2990:
+ldl $27,-60+160($sp)
+mov $27,$25
+mov $25,$14
+mov $25,$10
+lda $13,-60+160($sp)
+lda $9,-60+160($sp)
+mov $27,$12
+stl $27,-64+160($sp)
+sll $14,8*(8-1),$27
+sra $27,8*(8-1),$27
+sll $10,8*(8-1),$25
+sra $25,8*(8-1),$25
+cmpeq $27,$25,$23
+bne $23,L.2994
+lda $27,1
+stl $27,-84+160($sp)
+L.2994:
+mov $13,$27
+mov $9,$25
+cmpeq $27,$25,$23
+bne $23,L.2996
+lda $27,1
+stl $27,-88+160($sp)
+L.2996:
+ldl $27,-64+160($sp)
+cmpeq $12,$27,$23
+bne $23,L.2998
+lda $27,1
+stl $27,-92+160($sp)
+L.2998:
+ldl $27,-60+160($sp)
+sll $27,1,$27
+addl $27,0,$27
+stl $27,-60+160($sp)
+L.2991:
+lda $11,1($11)
+cmplt $11,50,$23
+bne $23,L.2990
+ldl $27,-84+160($sp)
+cmpeq $27,$31,$23
+bne $23,L.3000
+ldl $27,-96+160($sp)
+lda $27,1($27)
+stl $27,-96+160($sp)
+ldq $27,-48+160($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.3002
+lda $16,L.2983
+lda $17,1
+jsr $26,printf
+ldgp $gp,0($26)
+L.3002:
+L.3000:
+ldl $27,-88+160($sp)
+cmpeq $27,$31,$23
+bne $23,L.3004
+ldl $27,-96+160($sp)
+lda $27,2($27)
+stl $27,-96+160($sp)
+ldq $27,-48+160($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.3006
+lda $16,L.2983
+lda $17,2
+jsr $26,printf
+ldgp $gp,0($26)
+L.3006:
+L.3004:
+ldl $27,-92+160($sp)
+cmpeq $27,$31,$23
+bne $23,L.3008
+ldl $27,-96+160($sp)
+lda $27,4($27)
+stl $27,-96+160($sp)
+ldq $27,-48+160($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.3010
+lda $16,L.2983
+lda $17,4
+jsr $26,printf
+ldgp $gp,0($26)
+L.3010:
+L.3008:
+jsr $26,regc
+ldgp $gp,0($26)
+stl $0,-60+160($sp)
+ldq $27,-48+160($sp)
+ldl $27,40($27)
+cmpeq $27,$31,$23
+bne $23,L.3012
+ldl $27,-60+160($sp)
+cmplt $27,$31,$23
+beq $23,L.3014
+lda $16,L.2985
+lda $17,L.423
+jsr $26,printf
+ldgp $gp,0($26)
+br L.3015
+L.3014:
+lda $16,L.2986
+ldl $17,-60+160($sp)
+lda $18,L.423
+jsr $26,printf
+ldgp $gp,0($26)
+L.3015:
+L.3012:
+jsr $26,regp
+ldgp $gp,0($26)
+stl $0,-60+160($sp)
+ldq $27,-48+160($sp)
+ldl $27,40($27)
+cmpeq $27,$31,$23
+bne $23,L.3016
+ldl $27,-60+160($sp)
+cmplt $27,$31,$23
+beq $23,L.3018
+lda $16,L.2985
+lda $17,L.3020
+jsr $26,printf
+ldgp $gp,0($26)
+br L.3019
+L.3018:
+lda $16,L.2986
+ldl $17,-60+160($sp)
+lda $18,L.3020
+jsr $26,printf
+ldgp $gp,0($26)
+L.3019:
+L.3016:
+jsr $26,regi
+ldgp $gp,0($26)
+stl $0,-60+160($sp)
+ldq $27,-48+160($sp)
+ldl $27,40($27)
+cmpeq $27,$31,$23
+bne $23,L.3021
+ldl $27,-60+160($sp)
+cmplt $27,$31,$23
+beq $23,L.3023
+lda $16,L.2985
+lda $17,L.424
+jsr $26,printf
+ldgp $gp,0($26)
+br L.3024
+L.3023:
+lda $16,L.2986
+ldl $17,-60+160($sp)
+lda $18,L.424
+jsr $26,printf
+ldgp $gp,0($26)
+L.3024:
+L.3021:
+ldl $0,-96+160($sp)
+L.2982:
+ldq $9,0($sp)
+ldq $10,8($sp)
+ldq $11,16($sp)
+ldq $12,24($sp)
+ldq $13,32($sp)
+ldq $14,40($sp)
+ldq $24,48($sp)
+ldq $26,56($sp)
+lda $sp,160($sp)
+ret
+.end s81
+.globl regc
+.text
+.ent regc
+regc:
+ldgp $gp,0($27)
+lda $sp,-272($sp)
+.mask 0x5007e00,-216
+.frame $sp,272,$26,48
+stq $9,0($sp)
+stq $10,8($sp)
+stq $11,16($sp)
+stq $12,24($sp)
+stq $13,32($sp)
+stq $14,40($sp)
+stq $24,48($sp)
+stq $26,56($sp)
+.prologue 1
+stb $31,-190+272($sp)
+lda $27,1
+stb $27,-169+272($sp)
+lda $27,2
+stb $27,-170+272($sp)
+lda $27,3
+stb $27,-171+272($sp)
+lda $14,4
+lda $27,5
+stb $27,-172+272($sp)
+lda $13,6
+lda $27,7
+stb $27,-173+272($sp)
+lda $12,8
+lda $27,9
+stb $27,-174+272($sp)
+lda $11,10
+lda $27,11
+stb $27,-175+272($sp)
+lda $10,12
+lda $27,13
+stb $27,-176+272($sp)
+lda $9,14
+lda $27,15
+stb $27,-177+272($sp)
+lda $27,16
+stb $27,-57+272($sp)
+lda $27,17
+stb $27,-178+272($sp)
+lda $27,18
+stb $27,-58+272($sp)
+lda $27,19
+stb $27,-179+272($sp)
+lda $27,20
+stb $27,-59+272($sp)
+lda $27,21
+stb $27,-180+272($sp)
+lda $27,22
+stb $27,-60+272($sp)
+lda $27,23
+stb $27,-181+272($sp)
+lda $27,24
+stb $27,-61+272($sp)
+lda $27,25
+stb $27,-182+272($sp)
+lda $27,26
+stb $27,-62+272($sp)
+lda $27,27
+stb $27,-183+272($sp)
+lda $27,28
+stb $27,-63+272($sp)
+lda $27,29
+stb $27,-184+272($sp)
+lda $27,30
+stb $27,-64+272($sp)
+lda $27,31
+stb $27,-185+272($sp)
+lda $27,32
+stb $27,-65+272($sp)
+lda $27,33
+stb $27,-186+272($sp)
+lda $27,34
+stb $27,-66+272($sp)
+lda $27,35
+stb $27,-187+272($sp)
+lda $27,36
+stb $27,-188+272($sp)
+lda $27,37
+stb $27,-189+272($sp)
+lda $27,38
+stb $27,-191+272($sp)
+lda $27,-169+272($sp)
+lda $25,-190+272($sp)
+subq $27,$25,$25
+stl $25,-156+272($sp)
+lda $25,-170+272($sp)
+subq $25,$27,$27
+stl $27,-152+272($sp)
+lda $27,-171+272($sp)
+lda $25,-170+272($sp)
+subq $27,$25,$27
+stl $27,-148+272($sp)
+lda $27,-172+272($sp)
+lda $25,-171+272($sp)
+subq $27,$25,$27
+stl $27,-144+272($sp)
+lda $27,-173+272($sp)
+lda $25,-172+272($sp)
+subq $27,$25,$27
+stl $27,-140+272($sp)
+lda $27,-174+272($sp)
+lda $25,-173+272($sp)
+subq $27,$25,$27
+stl $27,-136+272($sp)
+lda $27,-175+272($sp)
+lda $25,-174+272($sp)
+subq $27,$25,$27
+stl $27,-132+272($sp)
+lda $27,-176+272($sp)
+lda $25,-175+272($sp)
+subq $27,$25,$27
+stl $27,-128+272($sp)
+lda $27,-177+272($sp)
+lda $25,-176+272($sp)
+subq $27,$25,$27
+stl $27,-124+272($sp)
+lda $27,-178+272($sp)
+lda $25,-177+272($sp)
+subq $27,$25,$27
+stl $27,-120+272($sp)
+lda $27,-179+272($sp)
+lda $25,-178+272($sp)
+subq $27,$25,$27
+stl $27,-116+272($sp)
+lda $27,-180+272($sp)
+lda $25,-179+272($sp)
+subq $27,$25,$27
+stl $27,-112+272($sp)
+lda $27,-181+272($sp)
+lda $25,-180+272($sp)
+subq $27,$25,$27
+stl $27,-108+272($sp)
+lda $27,-182+272($sp)
+lda $25,-181+272($sp)
+subq $27,$25,$27
+stl $27,-104+272($sp)
+lda $27,-183+272($sp)
+lda $25,-182+272($sp)
+subq $27,$25,$27
+stl $27,-100+272($sp)
+lda $27,-184+272($sp)
+lda $25,-183+272($sp)
+subq $27,$25,$27
+stl $27,-96+272($sp)
+lda $27,-185+272($sp)
+lda $25,-184+272($sp)
+subq $27,$25,$27
+stl $27,-92+272($sp)
+lda $27,-186+272($sp)
+lda $25,-185+272($sp)
+subq $27,$25,$27
+stl $27,-88+272($sp)
+lda $27,-187+272($sp)
+lda $25,-186+272($sp)
+subq $27,$25,$27
+stl $27,-84+272($sp)
+lda $27,-188+272($sp)
+lda $25,-187+272($sp)
+subq $27,$25,$27
+stl $27,-80+272($sp)
+lda $27,-189+272($sp)
+lda $25,-188+272($sp)
+subq $27,$25,$27
+stl $27,-76+272($sp)
+lda $27,-191+272($sp)
+lda $25,-189+272($sp)
+subq $27,$25,$27
+stl $27,-72+272($sp)
+ldl $27,-156+272($sp)
+stl $27,-168+272($sp)
+lda $27,1
+stl $27,-164+272($sp)
+stl $31,-160+272($sp)
+L.3047:
+ldl $27,-164+272($sp)
+cmpeq $27,1,$23
+bne $23,L.3053
+cmpeq $27,2,$23
+bne $23,L.3056
+cmpeq $27,3,$23
+bne $23,L.3061
+br L.3051
+L.3053:
+ldl $27,-160+272($sp)
+sll $27,2,$27
+lda $25,-156+272($sp)
+addq $27,$25,$27
+ldl $27,($27)
+ldl $25,-168+272($sp)
+cmpeq $27,$25,$23
+bne $23,L.3052
+lda $27,2
+ldl $25,-160+272($sp)
+sll $25,2,$25
+lda $22,-156+272($sp)
+addq $25,$22,$25
+ldl $25,($25)
+stl $25,-200+272($sp)
+stl $27,-164+272($sp)
+lda $27,1
+stl $27,-196+272($sp)
+br L.3052
+L.3056:
+ldl $27,-160+272($sp)
+sll $27,2,$27
+lda $25,-156+272($sp)
+addq $27,$25,$27
+ldl $27,($27)
+ldl $25,-168+272($sp)
+cmpeq $27,$25,$23
+beq $23,L.3057
+lda $27,3
+stl $27,-164+272($sp)
+br L.3052
+L.3057:
+ldl $27,-160+272($sp)
+sll $27,2,$27
+lda $25,-156+272($sp)
+addq $27,$25,$27
+ldl $27,($27)
+ldl $25,-200+272($sp)
+cmpeq $27,$25,$23
+beq $23,L.3059
+ldl $27,-196+272($sp)
+lda $27,1($27)
+stl $27,-196+272($sp)
+br L.3052
+L.3059:
+lda $27,4
+stl $27,-164+272($sp)
+br L.3052
+L.3061:
+ldl $27,-160+272($sp)
+sll $27,2,$27
+lda $25,-156+272($sp)
+addq $27,$25,$27
+ldl $27,($27)
+ldl $25,-168+272($sp)
+cmpeq $27,$25,$23
+bne $23,L.3052
+lda $27,4
+stl $27,-164+272($sp)
+L.3051:
+L.3052:
+L.3048:
+ldl $27,-160+272($sp)
+lda $27,1($27)
+stl $27,-160+272($sp)
+ldl $27,-160+272($sp)
+cmplt $27,22,$23
+bne $23,L.3047
+ldl $27,-164+272($sp)
+cmpeq $27,3,$23
+beq $23,L.3064
+lda $27,16
+ldl $25,-196+272($sp)
+subl $27,$25,$0
+br L.3025
+L.3064:
+lda $0,-1
+L.3025:
+ldq $9,0($sp)
+ldq $10,8($sp)
+ldq $11,16($sp)
+ldq $12,24($sp)
+ldq $13,32($sp)
+ldq $14,40($sp)
+ldq $24,48($sp)
+ldq $26,56($sp)
+lda $sp,272($sp)
+ret
+.end regc
+.globl regi
+.text
+.ent regi
+regi:
+ldgp $gp,0($27)
+lda $sp,-368($sp)
+.mask 0x5007e00,-312
+.frame $sp,368,$26,48
+stq $9,0($sp)
+stq $10,8($sp)
+stq $11,16($sp)
+stq $12,24($sp)
+stq $13,32($sp)
+stq $14,40($sp)
+stq $24,48($sp)
+stq $26,56($sp)
+.prologue 1
+stl $31,-284+368($sp)
+lda $27,1
+stl $27,-200+368($sp)
+lda $27,2
+stl $27,-204+368($sp)
+lda $27,3
+stl $27,-208+368($sp)
+lda $14,4
+lda $27,5
+stl $27,-212+368($sp)
+lda $13,6
+lda $27,7
+stl $27,-216+368($sp)
+lda $12,8
+lda $27,9
+stl $27,-220+368($sp)
+lda $11,10
+lda $27,11
+stl $27,-224+368($sp)
+lda $10,12
+lda $27,13
+stl $27,-228+368($sp)
+lda $9,14
+lda $27,15
+stl $27,-232+368($sp)
+lda $27,16
+stl $27,-60+368($sp)
+lda $27,17
+stl $27,-236+368($sp)
+lda $27,18
+stl $27,-64+368($sp)
+lda $27,19
+stl $27,-240+368($sp)
+lda $27,20
+stl $27,-68+368($sp)
+lda $27,21
+stl $27,-244+368($sp)
+lda $27,22
+stl $27,-72+368($sp)
+lda $27,23
+stl $27,-248+368($sp)
+lda $27,24
+stl $27,-76+368($sp)
+lda $27,25
+stl $27,-252+368($sp)
+lda $27,26
+stl $27,-80+368($sp)
+lda $27,27
+stl $27,-256+368($sp)
+lda $27,28
+stl $27,-84+368($sp)
+lda $27,29
+stl $27,-260+368($sp)
+lda $27,30
+stl $27,-88+368($sp)
+lda $27,31
+stl $27,-264+368($sp)
+lda $27,32
+stl $27,-92+368($sp)
+lda $27,33
+stl $27,-268+368($sp)
+lda $27,34
+stl $27,-96+368($sp)
+lda $27,35
+stl $27,-272+368($sp)
+lda $27,36
+stl $27,-276+368($sp)
+lda $27,37
+stl $27,-280+368($sp)
+lda $27,38
+stl $27,-288+368($sp)
+lda $27,-200+368($sp)
+stq $27,-304+368($sp)
+lda $25,-284+368($sp)
+subq $27,$25,$25
+divq $25,4,$25
+mov $25,$27
+stl $27,-184+368($sp)
+lda $27,-204+368($sp)
+ldq $25,-304+368($sp)
+subq $27,$25,$27
+divq $27,4,$27
+stl $27,-180+368($sp)
+lda $27,-208+368($sp)
+lda $25,-204+368($sp)
+subq $27,$25,$27
+divq $27,4,$27
+stl $27,-176+368($sp)
+lda $27,-212+368($sp)
+lda $25,-208+368($sp)
+subq $27,$25,$27
+divq $27,4,$27
+stl $27,-172+368($sp)
+lda $27,-216+368($sp)
+lda $25,-212+368($sp)
+subq $27,$25,$27
+divq $27,4,$27
+stl $27,-168+368($sp)
+lda $27,-220+368($sp)
+lda $25,-216+368($sp)
+subq $27,$25,$27
+divq $27,4,$27
+stl $27,-164+368($sp)
+lda $27,-224+368($sp)
+lda $25,-220+368($sp)
+subq $27,$25,$27
+divq $27,4,$27
+stl $27,-160+368($sp)
+lda $27,-228+368($sp)
+lda $25,-224+368($sp)
+subq $27,$25,$27
+divq $27,4,$27
+stl $27,-156+368($sp)
+lda $27,-232+368($sp)
+lda $25,-228+368($sp)
+subq $27,$25,$27
+divq $27,4,$27
+stl $27,-152+368($sp)
+lda $27,-236+368($sp)
+lda $25,-232+368($sp)
+subq $27,$25,$27
+divq $27,4,$27
+stl $27,-148+368($sp)
+lda $27,-240+368($sp)
+lda $25,-236+368($sp)
+subq $27,$25,$27
+divq $27,4,$27
+stl $27,-144+368($sp)
+lda $27,-244+368($sp)
+lda $25,-240+368($sp)
+subq $27,$25,$27
+divq $27,4,$27
+stl $27,-140+368($sp)
+lda $27,-248+368($sp)
+lda $25,-244+368($sp)
+subq $27,$25,$27
+divq $27,4,$27
+stl $27,-136+368($sp)
+lda $27,-252+368($sp)
+lda $25,-248+368($sp)
+subq $27,$25,$27
+divq $27,4,$27
+stl $27,-132+368($sp)
+lda $27,-256+368($sp)
+lda $25,-252+368($sp)
+subq $27,$25,$27
+divq $27,4,$27
+stl $27,-128+368($sp)
+lda $27,-260+368($sp)
+lda $25,-256+368($sp)
+subq $27,$25,$27
+divq $27,4,$27
+stl $27,-124+368($sp)
+lda $27,-264+368($sp)
+lda $25,-260+368($sp)
+subq $27,$25,$27
+divq $27,4,$27
+stl $27,-120+368($sp)
+lda $27,-268+368($sp)
+lda $25,-264+368($sp)
+subq $27,$25,$27
+divq $27,4,$27
+stl $27,-116+368($sp)
+lda $27,-272+368($sp)
+lda $25,-268+368($sp)
+subq $27,$25,$27
+divq $27,4,$27
+stl $27,-112+368($sp)
+lda $27,-276+368($sp)
+lda $25,-272+368($sp)
+subq $27,$25,$27
+divq $27,4,$27
+stl $27,-108+368($sp)
+lda $27,-280+368($sp)
+lda $25,-276+368($sp)
+subq $27,$25,$27
+divq $27,4,$27
+stl $27,-104+368($sp)
+lda $27,-288+368($sp)
+lda $25,-280+368($sp)
+subq $27,$25,$27
+divq $27,4,$27
+stl $27,-100+368($sp)
+ldl $27,-184+368($sp)
+stl $27,-196+368($sp)
+lda $27,1
+stl $27,-192+368($sp)
+stl $31,-188+368($sp)
+L.3088:
+ldl $27,-192+368($sp)
+cmpeq $27,1,$23
+bne $23,L.3094
+cmpeq $27,2,$23
+bne $23,L.3097
+cmpeq $27,3,$23
+bne $23,L.3102
+br L.3092
+L.3094:
+ldl $27,-188+368($sp)
+sll $27,2,$27
+lda $25,-184+368($sp)
+addq $27,$25,$27
+ldl $27,($27)
+ldl $25,-196+368($sp)
+cmpeq $27,$25,$23
+bne $23,L.3093
+lda $27,2
+ldl $25,-188+368($sp)
+sll $25,2,$25
+lda $22,-184+368($sp)
+addq $25,$22,$25
+ldl $25,($25)
+stl $25,-296+368($sp)
+stl $27,-192+368($sp)
+lda $27,1
+stl $27,-292+368($sp)
+br L.3093
+L.3097:
+ldl $27,-188+368($sp)
+sll $27,2,$27
+lda $25,-184+368($sp)
+addq $27,$25,$27
+ldl $27,($27)
+ldl $25,-196+368($sp)
+cmpeq $27,$25,$23
+beq $23,L.3098
+lda $27,3
+stl $27,-192+368($sp)
+br L.3093
+L.3098:
+ldl $27,-188+368($sp)
+sll $27,2,$27
+lda $25,-184+368($sp)
+addq $27,$25,$27
+ldl $27,($27)
+ldl $25,-296+368($sp)
+cmpeq $27,$25,$23
+beq $23,L.3100
+ldl $27,-292+368($sp)
+lda $27,1($27)
+stl $27,-292+368($sp)
+br L.3093
+L.3100:
+lda $27,4
+stl $27,-192+368($sp)
+br L.3093
+L.3102:
+ldl $27,-188+368($sp)
+sll $27,2,$27
+lda $25,-184+368($sp)
+addq $27,$25,$27
+ldl $27,($27)
+ldl $25,-196+368($sp)
+cmpeq $27,$25,$23
+bne $23,L.3093
+lda $27,4
+stl $27,-192+368($sp)
+L.3092:
+L.3093:
+L.3089:
+ldl $27,-188+368($sp)
+lda $27,1($27)
+stl $27,-188+368($sp)
+ldl $27,-188+368($sp)
+cmplt $27,22,$23
+bne $23,L.3088
+ldl $27,-192+368($sp)
+cmpeq $27,3,$23
+beq $23,L.3105
+lda $27,16
+ldl $25,-292+368($sp)
+subl $27,$25,$0
+br L.3066
+L.3105:
+lda $0,-1
+L.3066:
+ldq $9,0($sp)
+ldq $10,8($sp)
+ldq $11,16($sp)
+ldq $12,24($sp)
+ldq $13,32($sp)
+ldq $14,40($sp)
+ldq $24,48($sp)
+ldq $26,56($sp)
+lda $sp,368($sp)
+ret
+.end regi
+.globl regp
+.text
+.ent regp
+regp:
+ldgp $gp,0($27)
+lda $sp,-512($sp)
+.mask 0x5007e00,-456
+.frame $sp,512,$26,48
+stq $9,0($sp)
+stq $10,8($sp)
+stq $11,16($sp)
+stq $12,24($sp)
+stq $13,32($sp)
+stq $14,40($sp)
+stq $24,48($sp)
+stq $26,56($sp)
+.prologue 1
+lda $27,-416+512($sp)
+stq $27,-416+512($sp)
+lda $27,-368+512($sp)
+stq $27,-368+512($sp)
+lda $27,-376+512($sp)
+stq $27,-376+512($sp)
+lda $27,-384+512($sp)
+stq $27,-384+512($sp)
+lda $14,-240+512($sp)
+lda $27,-240+512($sp)
+stq $27,-240+512($sp)
+lda $13,-248+512($sp)
+lda $27,-248+512($sp)
+stq $27,-248+512($sp)
+lda $12,-256+512($sp)
+lda $27,-256+512($sp)
+stq $27,-256+512($sp)
+lda $11,-264+512($sp)
+lda $27,-264+512($sp)
+stq $27,-264+512($sp)
+lda $10,-272+512($sp)
+lda $27,-272+512($sp)
+stq $27,-272+512($sp)
+lda $9,-280+512($sp)
+lda $27,-280+512($sp)
+stq $27,-280+512($sp)
+lda $27,-288+512($sp)
+stq $27,-64+512($sp)
+lda $27,-288+512($sp)
+stq $27,-288+512($sp)
+lda $27,-296+512($sp)
+stq $27,-72+512($sp)
+lda $27,-296+512($sp)
+stq $27,-296+512($sp)
+lda $27,-304+512($sp)
+stq $27,-80+512($sp)
+lda $27,-304+512($sp)
+stq $27,-304+512($sp)
+lda $27,-312+512($sp)
+stq $27,-88+512($sp)
+lda $27,-312+512($sp)
+stq $27,-312+512($sp)
+lda $27,-320+512($sp)
+stq $27,-96+512($sp)
+lda $27,-320+512($sp)
+stq $27,-320+512($sp)
+lda $27,-328+512($sp)
+stq $27,-104+512($sp)
+lda $27,-328+512($sp)
+stq $27,-328+512($sp)
+lda $27,-336+512($sp)
+stq $27,-112+512($sp)
+lda $27,-336+512($sp)
+stq $27,-336+512($sp)
+lda $27,-344+512($sp)
+stq $27,-120+512($sp)
+lda $27,-344+512($sp)
+stq $27,-344+512($sp)
+lda $27,-352+512($sp)
+stq $27,-128+512($sp)
+lda $27,-352+512($sp)
+stq $27,-352+512($sp)
+lda $27,-360+512($sp)
+stq $27,-136+512($sp)
+lda $27,-360+512($sp)
+stq $27,-360+512($sp)
+lda $27,-392+512($sp)
+stq $27,-392+512($sp)
+lda $27,-400+512($sp)
+stq $27,-400+512($sp)
+lda $27,-424+512($sp)
+stq $27,-424+512($sp)
+lda $27,-368+512($sp)
+stq $27,-440+512($sp)
+lda $25,-416+512($sp)
+subq $27,$25,$25
+divq $25,8,$25
+mov $25,$27
+stl $27,-224+512($sp)
+lda $27,-376+512($sp)
+ldq $25,-440+512($sp)
+subq $27,$25,$27
+divq $27,8,$27
+stl $27,-220+512($sp)
+lda $27,-384+512($sp)
+lda $25,-376+512($sp)
+subq $27,$25,$27
+divq $27,8,$27
+stl $27,-216+512($sp)
+lda $27,-240+512($sp)
+lda $25,-384+512($sp)
+subq $27,$25,$27
+divq $27,8,$27
+stl $27,-212+512($sp)
+lda $27,-248+512($sp)
+lda $25,-240+512($sp)
+subq $27,$25,$27
+divq $27,8,$27
+stl $27,-208+512($sp)
+lda $27,-256+512($sp)
+lda $25,-248+512($sp)
+subq $27,$25,$27
+divq $27,8,$27
+stl $27,-204+512($sp)
+lda $27,-264+512($sp)
+lda $25,-256+512($sp)
+subq $27,$25,$27
+divq $27,8,$27
+stl $27,-200+512($sp)
+lda $27,-272+512($sp)
+lda $25,-264+512($sp)
+subq $27,$25,$27
+divq $27,8,$27
+stl $27,-196+512($sp)
+lda $27,-280+512($sp)
+lda $25,-272+512($sp)
+subq $27,$25,$27
+divq $27,8,$27
+stl $27,-192+512($sp)
+lda $27,-288+512($sp)
+lda $25,-280+512($sp)
+subq $27,$25,$27
+divq $27,8,$27
+stl $27,-188+512($sp)
+lda $27,-296+512($sp)
+lda $25,-288+512($sp)
+subq $27,$25,$27
+divq $27,8,$27
+stl $27,-184+512($sp)
+lda $27,-304+512($sp)
+lda $25,-296+512($sp)
+subq $27,$25,$27
+divq $27,8,$27
+stl $27,-180+512($sp)
+lda $27,-312+512($sp)
+lda $25,-304+512($sp)
+subq $27,$25,$27
+divq $27,8,$27
+stl $27,-176+512($sp)
+lda $27,-320+512($sp)
+lda $25,-312+512($sp)
+subq $27,$25,$27
+divq $27,8,$27
+stl $27,-172+512($sp)
+lda $27,-328+512($sp)
+lda $25,-320+512($sp)
+subq $27,$25,$27
+divq $27,8,$27
+stl $27,-168+512($sp)
+lda $27,-336+512($sp)
+lda $25,-328+512($sp)
+subq $27,$25,$27
+divq $27,8,$27
+stl $27,-164+512($sp)
+lda $27,-344+512($sp)
+lda $25,-336+512($sp)
+subq $27,$25,$27
+divq $27,8,$27
+stl $27,-160+512($sp)
+lda $27,-352+512($sp)
+lda $25,-344+512($sp)
+subq $27,$25,$27
+divq $27,8,$27
+stl $27,-156+512($sp)
+lda $27,-360+512($sp)
+lda $25,-352+512($sp)
+subq $27,$25,$27
+divq $27,8,$27
+stl $27,-152+512($sp)
+lda $27,-392+512($sp)
+lda $25,-360+512($sp)
+subq $27,$25,$27
+divq $27,8,$27
+stl $27,-148+512($sp)
+lda $27,-400+512($sp)
+lda $25,-392+512($sp)
+subq $27,$25,$27
+divq $27,8,$27
+stl $27,-144+512($sp)
+lda $27,-424+512($sp)
+lda $25,-400+512($sp)
+subq $27,$25,$27
+divq $27,8,$27
+stl $27,-140+512($sp)
+ldl $27,-224+512($sp)
+stl $27,-404+512($sp)
+lda $27,1
+stl $27,-232+512($sp)
+stl $31,-228+512($sp)
+L.3129:
+ldl $27,-232+512($sp)
+cmpeq $27,1,$23
+bne $23,L.3135
+cmpeq $27,2,$23
+bne $23,L.3138
+cmpeq $27,3,$23
+bne $23,L.3143
+br L.3133
+L.3135:
+ldl $27,-228+512($sp)
+sll $27,2,$27
+lda $25,-224+512($sp)
+addq $27,$25,$27
+ldl $27,($27)
+ldl $25,-404+512($sp)
+cmpeq $27,$25,$23
+bne $23,L.3134
+lda $27,2
+ldl $25,-228+512($sp)
+sll $25,2,$25
+lda $22,-224+512($sp)
+addq $25,$22,$25
+ldl $25,($25)
+stl $25,-432+512($sp)
+stl $27,-232+512($sp)
+lda $27,1
+stl $27,-428+512($sp)
+br L.3134
+L.3138:
+ldl $27,-228+512($sp)
+sll $27,2,$27
+lda $25,-224+512($sp)
+addq $27,$25,$27
+ldl $27,($27)
+ldl $25,-404+512($sp)
+cmpeq $27,$25,$23
+beq $23,L.3139
+lda $27,3
+stl $27,-232+512($sp)
+br L.3134
+L.3139:
+ldl $27,-228+512($sp)
+sll $27,2,$27
+lda $25,-224+512($sp)
+addq $27,$25,$27
+ldl $27,($27)
+ldl $25,-432+512($sp)
+cmpeq $27,$25,$23
+beq $23,L.3141
+ldl $27,-428+512($sp)
+lda $27,1($27)
+stl $27,-428+512($sp)
+br L.3134
+L.3141:
+lda $27,4
+stl $27,-232+512($sp)
+br L.3134
+L.3143:
+ldl $27,-228+512($sp)
+sll $27,2,$27
+lda $25,-224+512($sp)
+addq $27,$25,$27
+ldl $27,($27)
+ldl $25,-404+512($sp)
+cmpeq $27,$25,$23
+bne $23,L.3134
+lda $27,4
+stl $27,-232+512($sp)
+L.3133:
+L.3134:
+L.3130:
+ldl $27,-228+512($sp)
+lda $27,1($27)
+stl $27,-228+512($sp)
+ldl $27,-228+512($sp)
+cmplt $27,22,$23
+bne $23,L.3129
+ldl $27,-232+512($sp)
+cmpeq $27,3,$23
+beq $23,L.3146
+lda $27,16
+ldl $25,-428+512($sp)
+subl $27,$25,$0
+br L.3107
+L.3146:
+lda $0,-1
+L.3107:
+ldq $9,0($sp)
+ldq $10,8($sp)
+ldq $11,16($sp)
+ldq $12,24($sp)
+ldq $13,32($sp)
+ldq $14,40($sp)
+ldq $24,48($sp)
+ldq $26,56($sp)
+lda $sp,512($sp)
+ret
+.end regp
+.lcomm L.3149,420
+.sdata
+.align 0
+L.3150:
+.byte 115
+.byte 56
+.byte 52
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.3151:
+.byte 115
+.byte 56
+.byte 52
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s84
+.text
+.text
+.ent s84
+s84:
+ldgp $gp,0($27)
+lda $sp,-368($sp)
+.fmask 0x200,-368
+.mask 0x5007e00,-304
+.frame $sp,368,$26,48
+stt $f9,0($sp)
+stq $9,8($sp)
+stq $10,16($sp)
+stq $11,24($sp)
+stq $12,32($sp)
+stq $13,40($sp)
+stq $14,48($sp)
+stq $24,56($sp)
+stq $26,64($sp)
+mov $16,$14
+.prologue 1
+lda $10,L.3151
+lda $9,60($14)
+stl $31,-268+368($sp)
+L.3152:
+L.3153:
+mov $9,$27
+lda $9,1($27)
+mov $10,$25
+lda $10,1($25)
+ldb $25,($25)
+stb $25,($27)
+sll $25,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,$31,$23
+beq $23,L.3152
+lda $16,3
+jsr $26,fip
+ldgp $gp,0($26)
+stq $0,-280+368($sp)
+ldq $27,-280+368($sp)
+ldl $27,($27)
+cmpeq $27,3,$23
+bne $23,L.3155
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.3157
+lda $16,L.3150
+lda $17,1
+jsr $26,printf
+ldgp $gp,0($26)
+L.3157:
+ldl $27,-268+368($sp)
+lda $27,1($27)
+stl $27,-268+368($sp)
+L.3155:
+lda $27,glork
+stq $27,-288+368($sp)
+lda $16,4
+ldq $27,-288+368($sp)
+jsr $26,($27)
+ldgp $gp,0($26)
+cmpeq $0,4,$23
+bne $23,L.3159
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.3161
+lda $16,L.3150
+lda $17,2
+jsr $26,printf
+ldgp $gp,0($26)
+L.3161:
+ldl $27,-268+368($sp)
+lda $27,2($27)
+stl $27,-268+368($sp)
+L.3159:
+mov $31,$12
+L.3163:
+sll $12,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+lda $25,-124+368($sp)
+addq $27,$25,$27
+stq $12,-56+368($sp)
+ldt $f30,-56+368($sp)
+cvtqs $f30,$f30
+sts $f30,($27)
+sll $12,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,3,$25
+lda $22,-264+368($sp)
+addq $25,$22,$25
+sll $27,2,$27
+lda $22,-124+368($sp)
+addq $27,$22,$27
+stq $27,($25)
+L.3164:
+lda $12,1($12)
+cmplt $12,17,$23
+bne $23,L.3163
+lds $f9,L.410
+mov $31,$12
+L.3167:
+sll $12,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,3,$27
+lda $25,-264+368($sp)
+addq $27,$25,$27
+ldq $27,($27)
+lds $f30,($27)
+adds $f9,$f30,$f9
+L.3168:
+lda $12,1($12)
+cmplt $12,17,$23
+bne $23,L.3167
+lds $f30,L.3173
+cmpteq $f9,$f30,$f1
+fbne $f1,L.3171
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.3174
+lda $16,L.3150
+lda $17,4
+jsr $26,printf
+ldgp $gp,0($26)
+L.3174:
+ldl $27,-268+368($sp)
+lda $27,4($27)
+stl $27,-268+368($sp)
+L.3171:
+mov $31,$11
+L.3176:
+mov $31,$12
+L.3180:
+mov $31,$13
+L.3184:
+sll $13,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+lda $25,28
+sll $12,8*(8-4),$22
+sra $22,8*(8-4),$22
+mulq $25,$22,$25
+lda $22,140
+sll $11,8*(8-4),$8
+sra $8,8*(8-4),$8
+mulq $22,$8,$22
+lda $22,L.3149($22)
+addq $25,$22,$25
+addq $27,$25,$27
+lda $25,35
+mull $25,$11,$25
+lda $22,7
+mull $22,$12,$22
+addl $25,$22,$25
+addl $25,$13,$25
+stl $25,($27)
+L.3185:
+lda $13,1($13)
+cmplt $13,7,$23
+bne $23,L.3184
+L.3181:
+lda $12,1($12)
+cmplt $12,5,$23
+bne $23,L.3180
+L.3177:
+lda $11,1($11)
+cmplt $11,3,$23
+bne $23,L.3176
+lda $11,1
+lda $12,2
+lda $13,3
+lda $16,L.3149
+lda $17,105
+mov $31,$18
+jsr $26,array
+ldgp $gp,0($26)
+mov $0,$27
+stl $27,-292+368($sp)
+lda $25,140
+sll $11,8*(8-4),$22
+sra $22,8*(8-4),$22
+mulq $25,$22,$25
+lda $16,L.3149($25)
+lda $25,35
+mov $25,$17
+mov $25,$18
+jsr $26,array
+ldgp $gp,0($26)
+mov $0,$27
+stl $27,-296+368($sp)
+lda $25,28
+sll $12,8*(8-4),$22
+sra $22,8*(8-4),$22
+mulq $25,$22,$25
+lda $22,140
+sll $11,8*(8-4),$8
+sra $8,8*(8-4),$8
+mulq $22,$8,$22
+lda $22,L.3149($22)
+addq $25,$22,$16
+lda $17,7
+lda $18,49
+jsr $26,array
+ldgp $gp,0($26)
+ldl $25,-292+368($sp)
+ldl $22,-296+368($sp)
+addl $25,$22,$25
+addl $25,$0,$27
+sll $13,8*(8-4),$25
+sra $25,8*(8-4),$25
+sll $25,2,$25
+lda $22,28
+sll $12,8*(8-4),$8
+sra $8,8*(8-4),$8
+mulq $22,$8,$22
+lda $8,140
+sll $11,8*(8-4),$7
+sra $7,8*(8-4),$7
+mulq $8,$7,$8
+lda $8,L.3149($8)
+addq $22,$8,$22
+addq $25,$22,$25
+ldl $25,($25)
+addl $27,$25,$27
+subl $27,52,$27
+cmpeq $27,$31,$23
+bne $23,L.3188
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.3190
+lda $16,L.3150
+lda $17,8
+jsr $26,printf
+ldgp $gp,0($26)
+L.3190:
+ldl $27,-268+368($sp)
+lda $27,8($27)
+stl $27,-268+368($sp)
+L.3188:
+ldl $0,-268+368($sp)
+L.3148:
+ldt $f9,0($sp)
+ldq $9,8($sp)
+ldq $10,16($sp)
+ldq $11,24($sp)
+ldq $12,32($sp)
+ldq $13,40($sp)
+ldq $14,48($sp)
+ldq $24,56($sp)
+ldq $26,64($sp)
+lda $sp,368($sp)
+ret
+.end s84
+.globl array
+.text
+.ent array
+array:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4004000,-72
+.frame $sp,80,$26,48
+stq $14,0($sp)
+stq $26,8($sp)
+.prologue 1
+mov $31,$14
+br L.3196
+L.3193:
+sll $14,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+addq $27,$16,$27
+ldl $27,($27)
+addl $14,$18,$25
+cmpeq $27,$25,$23
+bne $23,L.3197
+lda $0,1
+br L.3192
+L.3197:
+L.3194:
+lda $14,1($14)
+L.3196:
+cmplt $14,$17,$23
+bne $23,L.3193
+mov $31,$0
+L.3192:
+ldq $14,0($sp)
+ldq $26,8($sp)
+lda $sp,80($sp)
+ret
+.end array
+.lcomm L.3200,4
+.globl fip
+.text
+.text
+.ent fip
+fip:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.frame $sp,64,$26,48
+.prologue 1
+lda $27,L.3200
+stl $16,L.3200
+mov $27,$0
+L.3199:
+lda $sp,64($sp)
+ret
+.end fip
+.globl glork
+.text
+.ent glork
+glork:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.frame $sp,64,$26,48
+.prologue 1
+mov $16,$0
+L.3201:
+lda $sp,64($sp)
+ret
+.end glork
+.sdata
+.align 0
+L.3203:
+.byte 115
+.byte 56
+.byte 53
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.3204:
+.byte 115
+.byte 56
+.byte 53
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.align 3
+L.3212:
+.quad L.423
+.quad L.425
+.quad L.424
+.quad L.426
+.quad L.427
+.quad L.428
+.quad L.429
+.align 0
+L.3213:
+.byte 32
+.byte 97
+.byte 108
+.byte 105
+.byte 103
+.byte 110
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 58
+.byte 32
+.byte 0
+.globl s85
+.text
+.text
+.ent s85
+s85:
+ldgp $gp,0($27)
+lda $sp,-528($sp)
+.mask 0x5007c00,-480
+.frame $sp,528,$26,48
+stq $10,0($sp)
+stq $11,8($sp)
+stq $12,16($sp)
+stq $13,24($sp)
+stq $14,32($sp)
+stq $24,40($sp)
+stq $26,48($sp)
+mov $16,$14
+.prologue 1
+lda $12,L.3204
+lda $11,60($14)
+mov $31,$10
+L.3217:
+L.3218:
+mov $11,$27
+lda $11,1($27)
+mov $12,$25
+lda $12,1($25)
+ldb $25,($25)
+stb $25,($27)
+sll $25,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,$31,$23
+beq $23,L.3217
+lda $25,-348+528($sp)
+lda $22,-368+528($sp)
+subq $25,$22,$25
+cmple $25,$31,$23
+bne $23,L.3228
+lda $25,-344+528($sp)
+lda $22,-348+528($sp)
+subq $25,$22,$25
+cmple $25,$31,$23
+bne $23,L.3228
+lda $25,-336+528($sp)
+lda $22,-344+528($sp)
+subq $25,$22,$25
+cmple $25,$31,$23
+beq $23,L.3220
+L.3228:
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.3229
+lda $16,L.3203
+lda $17,1
+jsr $26,printf
+ldgp $gp,0($26)
+L.3229:
+lda $10,1($10)
+L.3220:
+lda $27,-409+528($sp)
+lda $25,-410+528($sp)
+subq $27,$25,$27
+stl $27,-324+528($sp)
+lda $27,-412+528($sp)
+lda $25,-414+528($sp)
+subq $27,$25,$27
+stl $27,-320+528($sp)
+lda $27,-420+528($sp)
+lda $25,-424+528($sp)
+subq $27,$25,$27
+stl $27,-316+528($sp)
+lda $27,-432+528($sp)
+lda $25,-440+528($sp)
+subq $27,$25,$27
+stl $27,-312+528($sp)
+lda $27,-444+528($sp)
+lda $25,-448+528($sp)
+subq $27,$25,$27
+stl $27,-308+528($sp)
+lda $27,-452+528($sp)
+lda $25,-456+528($sp)
+subq $27,$25,$27
+stl $27,-304+528($sp)
+lda $27,-464+528($sp)
+lda $25,-472+528($sp)
+subq $27,$25,$27
+stl $27,-300+528($sp)
+ldl $27,40($14)
+cmpeq $27,$31,$23
+bne $23,L.3244
+mov $31,$13
+L.3246:
+lda $16,L.3250
+sll $13,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,3,$25
+ldq $17,L.3212($25)
+lda $18,L.3213
+sll $27,2,$27
+lda $25,-324+528($sp)
+addq $27,$25,$27
+ldl $19,($27)
+jsr $26,printf
+ldgp $gp,0($26)
+L.3247:
+lda $13,1($13)
+cmplt $13,7,$23
+bne $23,L.3246
+L.3244:
+ldl $27,-328+528($sp)
+or $27,56,$27
+stl $27,-328+528($sp)
+ldl $27,-328+528($sp)
+mov $27,$25
+and $25,0xfffffffc,$25
+sll $27,26,$27
+addl $27,0,$27
+sra $27,29,$27
+addl $27,0,$27
+sll $27,30,$27
+addl $27,0,$27
+sra $27,30,$27
+addl $27,0,$27
+and $27,3,$27
+or $25,$27,$27
+stl $27,-328+528($sp)
+ldl $27,-328+528($sp)
+mov $27,$25
+and $25,0xffffffc7,$25
+sll $27,30,$27
+addl $27,0,$27
+sra $27,30,$27
+addl $27,0,$27
+sll $27,29,$27
+addl $27,0,$27
+sra $27,29,$27
+addl $27,0,$27
+sll $27,3,$27
+zap $27,240,$27
+and $27,56,$27
+or $25,$27,$27
+stl $27,-328+528($sp)
+ldl $27,-328+528($sp)
+sll $27,26,$27
+addl $27,0,$27
+sra $27,29,$27
+addl $27,0,$27
+cmpeq $27,3,$23
+bne $23,L.3251
+ldl $27,-328+528($sp)
+sll $27,26,$27
+addl $27,0,$27
+sra $27,29,$27
+addl $27,0,$27
+lda $25,-1
+cmpeq $27,$25,$23
+beq $23,L.3253
+ldl $27,40($14)
+cmpeq $27,$31,$23
+bne $23,L.3254
+lda $16,L.3257
+jsr $26,printf
+ldgp $gp,0($26)
+br L.3254
+L.3253:
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.3258
+lda $16,L.3203
+lda $17,2
+jsr $26,printf
+ldgp $gp,0($26)
+L.3258:
+lda $10,2($10)
+L.3254:
+L.3251:
+ldl $27,-328+528($sp)
+or $27,64,$27
+stl $27,-328+528($sp)
+ldl $27,-328+528($sp)
+sll $27,25,$27
+addl $27,0,$27
+sra $27,31,$27
+addl $27,0,$27
+cmpeq $27,1,$23
+bne $23,L.3260
+ldl $27,40($14)
+cmpeq $27,$31,$23
+bne $23,L.3262
+lda $16,L.3264
+jsr $26,printf
+ldgp $gp,0($26)
+L.3262:
+L.3260:
+lda $27,-296+528($sp)
+subq $27,$27,$27
+cmpeq $27,$31,$23
+beq $23,L.3272
+cmpeq $27,$31,$23
+beq $23,L.3272
+cmpeq $27,$31,$23
+beq $23,L.3272
+cmpeq $27,$31,$23
+beq $23,L.3272
+cmpeq $27,$31,$23
+beq $23,L.3272
+cmpeq $27,$31,$23
+beq $23,L.3272
+cmpeq $27,$31,$23
+bne $23,L.3265
+L.3272:
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.3273
+lda $16,L.3203
+lda $17,4
+jsr $26,printf
+ldgp $gp,0($26)
+L.3273:
+lda $10,4($10)
+L.3265:
+br L.3275
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.3277
+lda $16,L.3203
+lda $17,8
+jsr $26,printf
+ldgp $gp,0($26)
+L.3277:
+lda $10,8($10)
+L.3275:
+lda $27,-408+528($sp)
+stq $27,-336+528($sp)
+lda $27,2
+stb $27,-408+528($sp)
+ldq $27,-336+528($sp)
+ldb $25,($27)
+lda $25,1($25)
+stb $25,($27)
+lda $27,-408+528($sp)
+ldb $27,($27)
+cmpeq $27,3,$23
+bne $23,L.3281
+ldl $27,44($14)
+cmpeq $27,$31,$23
+bne $23,L.3283
+lda $16,L.3203
+lda $17,16
+jsr $26,printf
+ldgp $gp,0($26)
+L.3283:
+lda $10,16($10)
+L.3281:
+mov $10,$0
+L.3202:
+ldq $10,0($sp)
+ldq $11,8($sp)
+ldq $12,16($sp)
+ldq $13,24($sp)
+ldq $14,32($sp)
+ldq $24,40($sp)
+ldq $26,48($sp)
+lda $sp,528($sp)
+ret
+.end s85
+.sdata
+.align 0
+L.3286:
+.byte 115
+.byte 56
+.byte 54
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.3287:
+.byte 115
+.byte 56
+.byte 54
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.align 2
+L.3288:
+.long 0x1
+.long 0x3
+.long 0x5
+.align 3
+L.3289:
+.quad L.3288+8
+.lcomm L.3291,40
+.sdata
+.align 2
+L.3292:
+.long 0x3f800000
+.long 0x40400000
+.long 0x40a00000
+.long 0x40000000
+.long 0x40800000
+.long 0x40c00000
+.long 0x40400000
+.long 0x40a00000
+.long 0x40e00000
+.long 0x0
+.long 0x0
+.long 0x0
+.align 2
+L.3293:
+.long 0x3f800000
+.long 0x40400000
+.long 0x40a00000
+.long 0x40000000
+.long 0x40800000
+.long 0x40c00000
+.long 0x40400000
+.long 0x40a00000
+.long 0x40e00000
+.space 12
+.align 2
+L.3294:
+.long 0x3f800000
+.long 0x40400000
+.long 0x40a00000
+.long 0x40000000
+.long 0x40800000
+.long 0x40c00000
+.long 0x40400000
+.long 0x40a00000
+.long 0x40e00000
+.space 12
+.align 2
+L.3295:
+.long 0x3f800000
+.space 8
+.long 0x40000000
+.space 8
+.long 0x40400000
+.space 8
+.long 0x40800000
+.space 8
+.globl s86
+.text
+.text
+.ent s86
+s86:
+ldgp $gp,0($27)
+lda $sp,-144($sp)
+.mask 0x5007e00,-88
+.frame $sp,144,$26,48
+stq $9,0($sp)
+stq $10,8($sp)
+stq $11,16($sp)
+stq $12,24($sp)
+stq $13,32($sp)
+stq $14,40($sp)
+stq $24,48($sp)
+stq $26,56($sp)
+stq $16,96($sp)
+.prologue 1
+ldq $27,L.3289
+lda $27,-4($27)
+stq $27,-80+144($sp)
+jsr $26,one
+ldgp $gp,0($26)
+sll $0,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+ldq $25,-80+144($sp)
+addq $27,$25,$14
+lda $9,L.3287
+ldq $27,-48+144($sp)
+lda $27,60($27)
+stq $27,-64+144($sp)
+stl $31,-68+144($sp)
+L.3296:
+L.3297:
+ldq $27,-64+144($sp)
+lda $25,1($27)
+stq $25,-64+144($sp)
+mov $9,$25
+lda $9,1($25)
+ldb $25,($25)
+stb $25,($27)
+sll $25,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,$31,$23
+beq $23,L.3296
+ldq $27,L.3289
+ldl $27,($27)
+cmpeq $27,5,$23
+bne $23,L.3299
+ldq $27,-48+144($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.3301
+lda $16,L.3286
+lda $17,1
+jsr $26,printf
+ldgp $gp,0($26)
+L.3301:
+ldl $27,-68+144($sp)
+lda $27,1($27)
+stl $27,-68+144($sp)
+L.3299:
+ldq $27,-80+144($sp)
+ldl $27,($27)
+cmpeq $27,3,$23
+bne $23,L.3303
+ldq $27,-48+144($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.3305
+lda $16,L.3286
+lda $17,2
+jsr $26,printf
+ldgp $gp,0($26)
+L.3305:
+ldl $27,-68+144($sp)
+lda $27,2($27)
+stl $27,-68+144($sp)
+L.3303:
+ldl $27,($14)
+cmpeq $27,5,$23
+bne $23,L.3307
+ldq $27,-48+144($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.3309
+lda $16,L.3286
+lda $17,4
+jsr $26,printf
+ldgp $gp,0($26)
+L.3309:
+ldl $27,-68+144($sp)
+lda $27,4($27)
+stl $27,-68+144($sp)
+L.3307:
+mov $31,$10
+mov $31,$13
+L.3311:
+sll $13,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+ldl $27,L.3291($27)
+cmpeq $27,$31,$23
+bne $23,L.3315
+lda $10,1
+L.3315:
+L.3312:
+lda $13,1($13)
+cmplt $13,10,$23
+bne $23,L.3311
+cmpeq $10,$31,$23
+bne $23,L.3317
+ldq $27,-48+144($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.3319
+lda $16,L.3286
+lda $17,8
+jsr $26,printf
+ldgp $gp,0($26)
+L.3319:
+ldl $27,-68+144($sp)
+lda $27,8($27)
+stl $27,-68+144($sp)
+L.3317:
+mov $31,$10
+mov $31,$12
+L.3321:
+mov $31,$13
+L.3325:
+lda $27,3
+mull $27,$12,$27
+addl $27,$13,$11
+sll $13,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+lda $25,12
+sll $12,8*(8-4),$22
+sra $22,8*(8-4),$22
+mulq $25,$22,$25
+lda $22,L.3293($25)
+addq $27,$22,$22
+lds $f30,($22)
+lda $25,L.3294($25)
+addq $27,$25,$27
+lds $f29,($27)
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.3331
+sll $11,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+lds $f29,L.3292($27)
+cmpteq $f30,$f29,$f1
+fbne $f1,L.3329
+L.3331:
+lda $10,1
+L.3329:
+L.3326:
+lda $13,1($13)
+cmplt $13,3,$23
+bne $23,L.3325
+L.3322:
+lda $12,1($12)
+cmplt $12,4,$23
+bne $23,L.3321
+cmpeq $10,$31,$23
+bne $23,L.3332
+ldq $27,-48+144($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.3334
+lda $16,L.3286
+lda $17,16
+jsr $26,printf
+ldgp $gp,0($26)
+L.3334:
+ldl $27,-68+144($sp)
+lda $27,16($27)
+stl $27,-68+144($sp)
+L.3332:
+mov $31,$10
+mov $31,$13
+L.3336:
+lda $27,12
+sll $13,8*(8-4),$25
+sra $25,8*(8-4),$25
+mulq $27,$25,$27
+lds $f30,L.3295($27)
+lda $27,1($13)
+stq $27,-56+144($sp)
+ldt $f29,-56+144($sp)
+cvtqs $f29,$f29
+cmpteq $f30,$f29,$f1
+fbne $f1,L.3340
+lda $10,1
+L.3340:
+L.3337:
+lda $13,1($13)
+cmplt $13,4,$23
+bne $23,L.3336
+cmpeq $10,$31,$23
+bne $23,L.3342
+ldq $27,-48+144($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.3344
+lda $16,L.3286
+lda $17,32
+jsr $26,printf
+ldgp $gp,0($26)
+L.3344:
+ldl $27,-68+144($sp)
+lda $27,32($27)
+stl $27,-68+144($sp)
+L.3342:
+ldl $0,-68+144($sp)
+L.3285:
+ldq $9,0($sp)
+ldq $10,8($sp)
+ldq $11,16($sp)
+ldq $12,24($sp)
+ldq $13,32($sp)
+ldq $14,40($sp)
+ldq $24,48($sp)
+ldq $26,56($sp)
+lda $sp,144($sp)
+ret
+.end s86
+.globl one
+.text
+.ent one
+one:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.frame $sp,64,$26,48
+.prologue 1
+lda $0,1
+L.3346:
+lda $sp,64($sp)
+ret
+.end one
+.sdata
+.align 0
+L.3348:
+.byte 115
+.byte 56
+.byte 56
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.3349:
+.byte 115
+.byte 56
+.byte 56
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s88
+.text
+.text
+.ent s88
+s88:
+ldgp $gp,0($27)
+lda $sp,-128($sp)
+.mask 0x5007800,-88
+.frame $sp,128,$26,48
+stq $11,0($sp)
+stq $12,8($sp)
+stq $13,16($sp)
+stq $14,24($sp)
+stq $24,32($sp)
+stq $26,40($sp)
+stq $16,80($sp)
+.prologue 1
+lda $14,L.3349
+ldq $27,-48+128($sp)
+lda $13,60($27)
+mov $31,$12
+L.3351:
+L.3352:
+mov $13,$27
+lda $13,1($27)
+mov $14,$25
+lda $14,1($25)
+ldb $25,($25)
+stb $25,($27)
+sll $25,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,$31,$23
+beq $23,L.3351
+br L.3354
+ldq $27,-48+128($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.3356
+lda $16,L.3348
+lda $17,1
+jsr $26,printf
+ldgp $gp,0($26)
+L.3356:
+lda $12,1($12)
+L.3354:
+lda $27,-76+128($sp)
+stq $27,metricp
+lda $27,2
+stl $27,-76+128($sp)
+ldq $27,metricp
+lda $25,3
+stl $25,($27)
+ldl $27,-76+128($sp)
+cmpeq $27,3,$23
+bne $23,L.3358
+ldq $27,-48+128($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.3360
+lda $16,L.3348
+lda $17,2
+jsr $26,printf
+ldgp $gp,0($26)
+L.3360:
+lda $12,2($12)
+L.3358:
+ldt $f30,L.417
+stt $f30,-72+128($sp)
+stt $f30,-64+128($sp)
+lda $11,-72+128($sp)
+ldt $f30,L.416
+stt $f30,($11)
+ldt $f30,L.416
+stt $f30,8($11)
+ldt $f30,-72+128($sp)
+ldt $f29,-64+128($sp)
+addt $f30,$f29,$f30
+ldt $f29,L.414
+cmpteq $f30,$f29,$f1
+fbne $f1,L.3363
+ldq $27,-48+128($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.3366
+lda $16,L.3348
+lda $17,4
+jsr $26,printf
+ldgp $gp,0($26)
+L.3366:
+lda $12,4($12)
+L.3363:
+mov $12,$0
+L.3347:
+ldq $11,0($sp)
+ldq $12,8($sp)
+ldq $13,16($sp)
+ldq $14,24($sp)
+ldq $24,32($sp)
+ldq $26,40($sp)
+lda $sp,128($sp)
+ret
+.end s88
+.sdata
+.align 0
+L.3369:
+.byte 115
+.byte 57
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.3370:
+.byte 115
+.byte 57
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s9
+.text
+.text
+.ent s9
+s9:
+ldgp $gp,0($27)
+lda $sp,-144($sp)
+.mask 0x5007e00,-88
+.frame $sp,144,$26,48
+stq $9,0($sp)
+stq $10,8($sp)
+stq $11,16($sp)
+stq $12,24($sp)
+stq $13,32($sp)
+stq $14,40($sp)
+stq $24,48($sp)
+stq $26,56($sp)
+stq $16,96($sp)
+.prologue 1
+lda $12,L.3370
+ldq $27,-48+144($sp)
+lda $11,60($27)
+mov $31,$10
+L.3371:
+L.3372:
+mov $11,$27
+lda $11,1($27)
+mov $12,$25
+lda $12,1($25)
+ldb $25,($25)
+stb $25,($27)
+sll $25,8*(8-1),$27
+sra $27,8*(8-1),$27
+cmpeq $27,$31,$23
+beq $23,L.3371
+mov $31,$13
+mov $31,$14
+L.3374:
+lda $27,2
+mov $27,$9
+stl $27,-60+144($sp)
+lda $27,3
+stl $27,-64+144($sp)
+stl $27,-68+144($sp)
+ldl $27,-68+144($sp)
+cmpeq $27,3,$23
+beq $23,L.3380
+ldl $27,-64+144($sp)
+cmpeq $27,3,$23
+bne $23,L.3378
+L.3380:
+lda $13,1
+L.3378:
+ldl $27,-60+144($sp)
+cmpeq $27,2,$23
+beq $23,L.3383
+cmpeq $9,2,$23
+bne $23,L.3381
+L.3383:
+lda $13,1
+L.3381:
+L.3375:
+lda $14,1($14)
+cmplt $14,2,$23
+bne $23,L.3374
+cmpeq $13,$31,$23
+bne $23,L.3388
+ldq $27,-48+144($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.3386
+lda $16,L.3369
+lda $17,1
+jsr $26,printf
+ldgp $gp,0($26)
+L.3386:
+lda $10,1($10)
+br L.3388
+ldq $27,-48+144($sp)
+ldl $27,44($27)
+cmpeq $27,$31,$23
+bne $23,L.3389
+lda $16,L.3369
+lda $17,2
+jsr $26,printf
+ldgp $gp,0($26)
+L.3389:
+lda $10,2($10)
+L.3388:
+mov $10,$0
+L.3368:
+ldq $9,0($sp)
+ldq $10,8($sp)
+ldq $11,16($sp)
+ldq $12,24($sp)
+ldq $13,32($sp)
+ldq $14,40($sp)
+ldq $24,48($sp)
+ldq $26,56($sp)
+lda $sp,144($sp)
+ret
+.end s9
+.globl setev
+.text
+.ent setev
+setev:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.frame $sp,64,$26,48
+.prologue 1
+lda $27,1066
+stl $27,extvar
+mov $31,$0
+L.3391:
+lda $sp,64($sp)
+ret
+.end setev
+.globl rfs
+.comm rfs,8
+.globl crc
+.comm crc,4
+.globl rrc
+.comm rrc,4
+.globl flgl
+.comm flgl,4
+.globl flgd
+.comm flgd,4
+.globl flgm
+.comm flgm,4
+.globl flgs
+.comm flgs,4
+.globl dprec
+.comm dprec,4
+.globl fprec
+.comm fprec,4
+.globl dbits
+.comm dbits,4
+.globl fbits
+.comm fbits,4
+.globl ubits
+.comm ubits,4
+.globl lbits
+.comm lbits,4
+.globl metricp
+.comm metricp,8
+.globl extvar
+.comm extvar,4
+.rdata
+.align 0
+L.3264:
+.byte 66
+.byte 101
+.byte 32
+.byte 101
+.byte 115
+.byte 112
+.byte 101
+.byte 99
+.byte 105
+.byte 97
+.byte 108
+.byte 108
+.byte 121
+.byte 32
+.byte 99
+.byte 97
+.byte 114
+.byte 101
+.byte 102
+.byte 117
+.byte 108
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 49
+.byte 45
+.byte 98
+.byte 105
+.byte 116
+.byte 32
+.byte 102
+.byte 105
+.byte 101
+.byte 108
+.byte 100
+.byte 115
+.byte 33
+.byte 10
+.byte 0
+.align 0
+L.3257:
+.byte 83
+.byte 105
+.byte 103
+.byte 110
+.byte 32
+.byte 101
+.byte 120
+.byte 116
+.byte 101
+.byte 110
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 102
+.byte 105
+.byte 101
+.byte 108
+.byte 100
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.3250:
+.byte 37
+.byte 115
+.byte 37
+.byte 115
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 2
+L.3173:
+.long 0x43080000
+.align 0
+L.3020:
+.byte 112
+.byte 111
+.byte 105
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 0
+.align 0
+L.2470:
+.byte 73
+.byte 110
+.byte 99
+.byte 114
+.byte 101
+.byte 97
+.byte 115
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 97
+.byte 114
+.byte 114
+.byte 97
+.byte 121
+.byte 32
+.byte 101
+.byte 108
+.byte 101
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 97
+.byte 115
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 101
+.byte 100
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 100
+.byte 101
+.byte 99
+.byte 114
+.byte 101
+.byte 97
+.byte 115
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 108
+.byte 111
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 10
+.byte 0
+.align 2
+L.2354:
+.long 0x41d00000
+.align 3
+L.2353:
+.long 0x0
+.long 0x403a0000
+.align 3
+L.1657:
+.long 0x0
+.long 0x40040000
+.align 3
+L.1482:
+.long 0x0
+.long 0x40240000
+.align 2
+L.1453:
+.long 0x41200000
+.align 3
+L.1278:
+.long 0x0
+.long 0x40080000
+.align 2
+L.1249:
+.long 0x40400000
+.align 3
+L.1074:
+.long 0x0
+.long 0x401c0000
+.align 2
+L.1045:
+.long 0x40e00000
+.align 3
+L.868:
+.long 0x0
+.long 0x40140000
+.align 2
+L.839:
+.long 0x40a00000
+.align 3
+L.834:
+.long 0x0
+.long 0x41e00000
+.align 2
+L.826:
+.long 0x4f000000
+.align 0
+L.651:
+.byte 113
+.byte 117
+.byte 101
+.byte 101
+.byte 112
+.byte 0
+.align 0
+L.637:
+.byte 10
+.byte 0
+.align 0
+L.636:
+.byte 37
+.byte 100
+.byte 0
+.align 0
+L.631:
+.byte 32
+.byte 32
+.byte 32
+.byte 107
+.byte 101
+.byte 121
+.byte 61
+.byte 0
+.align 3
+L.594:
+.long 0x0
+.long 0x40000000
+.align 3
+L.534:
+.long 0x0
+.long 0x40ce8480
+.align 3
+L.533:
+.long 0x0
+.long 0x405f4000
+.align 2
+L.532:
+.long 0x42fa0000
+.align 2
+L.527:
+.long 0x40000000
+.align 0
+L.429:
+.byte 100
+.byte 111
+.byte 117
+.byte 98
+.byte 108
+.byte 101
+.byte 0
+.align 0
+L.428:
+.byte 102
+.byte 108
+.byte 111
+.byte 97
+.byte 116
+.byte 0
+.align 0
+L.427:
+.byte 117
+.byte 110
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 101
+.byte 100
+.byte 0
+.align 0
+L.426:
+.byte 108
+.byte 111
+.byte 110
+.byte 103
+.byte 0
+.align 0
+L.425:
+.byte 115
+.byte 104
+.byte 111
+.byte 114
+.byte 116
+.byte 0
+.align 0
+L.424:
+.byte 105
+.byte 110
+.byte 116
+.byte 0
+.align 0
+L.423:
+.byte 99
+.byte 104
+.byte 97
+.byte 114
+.byte 0
+.align 3
+L.417:
+.long 0x0
+.long 0x0
+.align 3
+L.416:
+.long 0x0
+.long 0x3ff00000
+.align 3
+L.415:
+.long 0x0
+.long 0x40100000
+.align 3
+L.414:
+.long 0x0
+.long 0x40000000
+.align 2
+L.410:
+.long 0x0
+.align 2
+L.409:
+.long 0x3f800000
+.align 0
+L.388:
+.byte 113
+.byte 117
+.byte 101
+.byte 101
+.byte 112
+.byte 33
+.byte 0
+.align 0
+L.377:
+.byte 10
+.byte 9
+.byte 8
+.byte 13
+.byte 12
+.byte 92
+.byte 39
+.byte 0
+.align 0
+L.373:
+.byte 46
+.byte 34
+.byte 46
+.byte 0
+.align 0
+L.360:
+.byte 46
+.byte 46
+.byte 46
+.byte 0
+.align 3
+L.332:
+.long 0x0
+.long 0x40938800
+.align 0
+L.198:
+.byte 32
+.byte 32
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 114
+.byte 101
+.byte 115
+.byte 117
+.byte 108
+.byte 116
+.byte 115
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 110
+.byte 32
+.byte 97
+.byte 115
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 101
+.byte 100
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 108
+.byte 111
+.byte 110
+.byte 103
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.197:
+.byte 68
+.byte 101
+.byte 99
+.byte 105
+.byte 109
+.byte 97
+.byte 108
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 111
+.byte 99
+.byte 116
+.byte 97
+.byte 108
+.byte 47
+.byte 104
+.byte 101
+.byte 120
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 115
+.byte 116
+.byte 97
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 115
+.byte 111
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 109
+.byte 101
+.byte 115
+.byte 32
+.byte 103
+.byte 105
+.byte 118
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.27:
+.byte 10
+.byte 70
+.byte 97
+.byte 105
+.byte 108
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.26:
+.byte 10
+.byte 78
+.byte 111
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 115
+.byte 32
+.byte 100
+.byte 101
+.byte 116
+.byte 101
+.byte 99
+.byte 116
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.20:
+.byte 83
+.byte 101
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 37
+.byte 115
+.byte 32
+.byte 114
+.byte 101
+.byte 116
+.byte 117
+.byte 114
+.byte 110
+.byte 101
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 46
+.byte 10
+.byte 0
diff --git a/lcc/alpha/osf/tst/cvt.1bk b/lcc/alpha/osf/tst/cvt.1bk
new file mode 100755
index 0000000..74c79f1
--- /dev/null
+++ b/lcc/alpha/osf/tst/cvt.1bk
@@ -0,0 +1,11 @@
+1 1 1 1 1 1 1 1 1.000000 1.000000 1.000000
+2 2 2 2 2 2 2 2 2.000000 2.000000 2.000000
+3 3 3 3 3 3 3 3 3.000000 3.000000 3.000000
+4 4 4 4 4 4 4 4 4.000000 4.000000 4.000000
+5 5 5 5 5 5 5 5 5.000000 5.000000 5.000000
+6 6 6 6 6 6 6 6 6.000000 6.000000 6.000000
+7 7 7 7 7 7 7 7 7.000000 7.000000 7.000000
+8 8 8 8 8 8 8 8 8.000000 8.000000 8.000000
+9 9 9 9 9 9 9 9 9.000000 9.000000 9.000000
+10 10 10 10 10 10 10 10 10.000000 10.000000 10.000000
+11 11 11 11 11 11 11 11 11.000000 11.000000 11.000000
diff --git a/lcc/alpha/osf/tst/cvt.2bk b/lcc/alpha/osf/tst/cvt.2bk
new file mode 100755
index 0000000..b3ab360
--- /dev/null
+++ b/lcc/alpha/osf/tst/cvt.2bk
@@ -0,0 +1,2 @@
+tst/cvt.c:32: warning: conversion from `pointer to void function(void)' to `pointer to void' is compiler dependent
+tst/cvt.c:33: warning: conversion from `pointer to void' to `pointer to void function(void)' is compiler dependent
diff --git a/lcc/alpha/osf/tst/cvt.sbk b/lcc/alpha/osf/tst/cvt.sbk
new file mode 100755
index 0000000..d81c370
--- /dev/null
+++ b/lcc/alpha/osf/tst/cvt.sbk
@@ -0,0 +1,744 @@
+.globl print
+.text
+.text
+.ent print
+print:
+ldgp $gp,0($27)
+lda $sp,-112($sp)
+.mask 0x4000000,-64
+.frame $sp,112,$26,48
+stq $26,48($sp)
+.prologue 1
+lda $16,L.2
+lda $27,c
+ldb $17,($27)
+lda $27,s
+ldw $18,($27)
+ldl $19,i
+ldq $20,l
+lda $27,C
+ldbu $21,($27)
+lda $27,S
+ldwu $27,($27)
+stq $27,0($sp)
+ldl $27,I
+zap $27,240,$27
+stq $27,8($sp)
+ldq $27,L
+stq $27,16($sp)
+lds $f30,f
+cvtst $f30,$f30
+stt $f30,24($sp)
+ldt $f30,d
+stt $f30,32($sp)
+ldt $f30,D
+stt $f30,40($sp)
+jsr $26,printf
+ldgp $gp,0($26)
+L.1:
+ldq $26,48($sp)
+lda $sp,112($sp)
+ret
+.end print
+.globl main
+.text
+.ent main
+main:
+ldgp $gp,0($27)
+lda $sp,-160($sp)
+.mask 0x5007e00,-104
+.frame $sp,160,$26,48
+stq $9,0($sp)
+stq $10,8($sp)
+stq $11,16($sp)
+stq $12,24($sp)
+stq $13,32($sp)
+stq $14,40($sp)
+stq $24,48($sp)
+stq $26,56($sp)
+.prologue 1
+lda $27,c
+lda $25,1
+stb $25,c
+ldb $27,($27)
+mov $27,$25
+stw $25,s
+stl $27,i
+sll $27,8*(8-4),$25
+sra $25,8*(8-4),$25
+stq $25,l
+mov $27,$25
+mov $25,$22
+stb $22,C
+mov $25,$22
+stw $22,S
+stl $25,I
+mov $27,$25
+stq $25,L
+stq $27,-56+160($sp)
+ldt $f30,-56+160($sp)
+cvtqs $f30,$f30
+sts $f30,f
+stq $27,-56+160($sp)
+ldt $f30,-56+160($sp)
+cvtqt $f30,$f30
+stt $f30,d
+stt $f30,D
+jsr $26,print
+ldgp $gp,0($26)
+lda $27,s
+lda $25,2
+stw $25,s
+ldw $27,($27)
+mov $27,$25
+stb $25,c
+stl $27,i
+sll $27,8*(8-4),$25
+sra $25,8*(8-4),$25
+stq $25,l
+mov $27,$25
+mov $25,$22
+stb $22,C
+mov $25,$22
+stw $22,S
+stl $25,I
+mov $27,$25
+stq $25,L
+stq $27,-56+160($sp)
+ldt $f30,-56+160($sp)
+cvtqs $f30,$f30
+sts $f30,f
+stq $27,-56+160($sp)
+ldt $f30,-56+160($sp)
+cvtqt $f30,$f30
+stt $f30,d
+stt $f30,D
+jsr $26,print
+ldgp $gp,0($26)
+lda $27,3
+stl $27,i
+ldl $27,i
+mov $27,$25
+stb $25,c
+mov $27,$25
+stw $25,s
+sll $27,8*(8-4),$25
+sra $25,8*(8-4),$25
+stq $25,l
+mov $27,$25
+mov $25,$22
+stb $22,C
+mov $25,$22
+stw $22,S
+stl $25,I
+mov $27,$25
+stq $25,L
+stq $27,-56+160($sp)
+ldt $f30,-56+160($sp)
+cvtqs $f30,$f30
+sts $f30,f
+stq $27,-56+160($sp)
+ldt $f30,-56+160($sp)
+cvtqt $f30,$f30
+stt $f30,d
+stt $f30,D
+jsr $26,print
+ldgp $gp,0($26)
+lda $27,4
+stq $27,l
+ldq $27,l
+mov $27,$25
+stb $25,c
+mov $27,$25
+stw $25,s
+mov $27,$25
+stl $25,i
+mov $27,$25
+mov $25,$22
+stb $22,C
+mov $25,$22
+stw $22,S
+stl $25,I
+mov $27,$25
+stq $25,L
+stq $27,-56+160($sp)
+ldt $f30,-56+160($sp)
+cvtqs $f30,$f30
+sts $f30,f
+stq $27,-56+160($sp)
+ldt $f30,-56+160($sp)
+cvtqt $f30,$f30
+stt $f30,d
+stt $f30,D
+jsr $26,print
+ldgp $gp,0($26)
+lda $27,C
+lda $25,5
+stb $25,C
+ldbu $27,($27)
+mov $27,$25
+stb $25,c
+mov $27,$25
+stw $25,s
+stl $27,i
+sll $27,8*(8-4),$25
+sra $25,8*(8-4),$25
+stq $25,l
+mov $27,$25
+mov $25,$22
+stw $22,S
+stl $25,I
+mov $27,$25
+stq $25,L
+stq $27,-56+160($sp)
+ldt $f30,-56+160($sp)
+cvtqs $f30,$f30
+sts $f30,f
+stq $27,-56+160($sp)
+ldt $f30,-56+160($sp)
+cvtqt $f30,$f30
+stt $f30,d
+stt $f30,D
+jsr $26,print
+ldgp $gp,0($26)
+lda $27,S
+lda $25,6
+stw $25,S
+ldwu $27,($27)
+mov $27,$25
+stb $25,c
+mov $27,$25
+stw $25,s
+stl $27,i
+sll $27,8*(8-4),$25
+sra $25,8*(8-4),$25
+stq $25,l
+mov $27,$25
+mov $25,$22
+stb $22,C
+stl $25,I
+mov $27,$25
+stq $25,L
+stq $27,-56+160($sp)
+ldt $f30,-56+160($sp)
+cvtqs $f30,$f30
+sts $f30,f
+stq $27,-56+160($sp)
+ldt $f30,-56+160($sp)
+cvtqt $f30,$f30
+stt $f30,d
+stt $f30,D
+jsr $26,print
+ldgp $gp,0($26)
+lda $27,7
+stl $27,I
+ldl $27,I
+zap $27,240,$27
+mov $27,$25
+mov $25,$22
+stb $22,c
+mov $25,$22
+stw $22,s
+stl $25,i
+and $27,(1<<(8*4))-1,$25
+stq $25,l
+mov $27,$25
+stb $25,C
+mov $27,$25
+stw $25,S
+and $27,(1<<(8*4))-1,$25
+stq $25,L
+ldt $f30,L.4
+srl $27,1,$25
+stq $25,-56+160($sp)
+ldt $f29,-56+160($sp)
+cvtqt $f29,$f29
+mult $f30,$f29,$f30
+and $27,1,$27
+stq $27,-56+160($sp)
+ldt $f29,-56+160($sp)
+cvtqt $f29,$f29
+addt $f30,$f29,$f30
+cvtts $f30,$f29
+sts $f29,f
+stt $f30,d
+stt $f30,D
+jsr $26,print
+ldgp $gp,0($26)
+lda $27,8
+stq $27,L
+ldq $27,L
+mov $27,$25
+mov $25,$22
+stb $22,c
+mov $25,$22
+stw $22,s
+stl $25,i
+mov $27,$25
+stq $25,l
+mov $27,$25
+stb $25,C
+lda $25,S
+mov $27,$22
+stw $22,S
+ldwu $25,($25)
+stl $25,I
+ldt $f30,L.4
+srl $27,1,$25
+stq $25,-56+160($sp)
+ldt $f29,-56+160($sp)
+cvtqt $f29,$f29
+mult $f30,$f29,$f30
+and $27,1,$27
+stq $27,-56+160($sp)
+ldt $f29,-56+160($sp)
+cvtqt $f29,$f29
+addt $f30,$f29,$f30
+cvtts $f30,$f29
+sts $f29,f
+stt $f30,d
+stt $f30,D
+jsr $26,print
+ldgp $gp,0($26)
+lds $f30,L.5
+sts $f30,f
+lds $f30,f
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+160($sp)
+ldl $27,-56+160($sp)
+mov $27,$25
+stb $25,c
+mov $27,$25
+stw $25,s
+stl $27,i
+cvttqc $f30,$f1
+stt $f1,-56+160($sp)
+ldq $27,-56+160($sp)
+stq $27,l
+lds $f29,L.9
+cmptlt $f30,$f29,$f1
+fbne $f1,L.7
+subs $f30,$f29,$f29
+cvttqc $f29,$f1
+cvtql $f1,$f1
+sts $f1,-56+160($sp)
+ldl $27,-56+160($sp)
+addl $27,0x80000000,$14
+zap $14,240,$14
+br L.8
+L.7:
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+160($sp)
+ldl $27,-56+160($sp)
+mov $27,$14
+L.8:
+mov $14,$27
+stb $27,C
+lds $f30,f
+lds $f29,L.9
+cmptlt $f30,$f29,$f1
+fbne $f1,L.11
+subs $f30,$f29,$f29
+cvttqc $f29,$f1
+cvtql $f1,$f1
+sts $f1,-56+160($sp)
+ldl $27,-56+160($sp)
+addl $27,0x80000000,$13
+zap $13,240,$13
+br L.12
+L.11:
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+160($sp)
+ldl $27,-56+160($sp)
+mov $27,$13
+L.12:
+mov $13,$27
+stw $27,S
+lds $f30,f
+lds $f29,L.9
+cmptlt $f30,$f29,$f1
+fbne $f1,L.14
+subs $f30,$f29,$f29
+cvttqc $f29,$f1
+cvtql $f1,$f1
+sts $f1,-56+160($sp)
+ldl $27,-56+160($sp)
+addl $27,0x80000000,$12
+zap $12,240,$12
+br L.15
+L.14:
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+160($sp)
+ldl $27,-56+160($sp)
+mov $27,$12
+L.15:
+stl $12,I
+lds $f30,f
+lds $f29,L.19
+cmptlt $f30,$f29,$f1
+fbne $f1,L.17
+subs $f30,$f29,$f29
+cvttqc $f29,$f1
+stt $f1,-56+160($sp)
+ldq $27,-56+160($sp)
+lda $11,0x8000000000000000($27)
+br L.18
+L.17:
+cvttqc $f30,$f1
+stt $f1,-56+160($sp)
+ldq $27,-56+160($sp)
+mov $27,$11
+L.18:
+stq $11,L
+lds $f30,f
+cvtst $f30,$f30
+stt $f30,d
+stt $f30,D
+jsr $26,print
+ldgp $gp,0($26)
+ldt $f30,L.20
+stt $f30,d
+ldt $f30,d
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+160($sp)
+ldl $27,-56+160($sp)
+mov $27,$25
+stb $25,c
+mov $27,$25
+stw $25,s
+stl $27,i
+cvttqc $f30,$f1
+stt $f1,-56+160($sp)
+ldq $27,-56+160($sp)
+stq $27,l
+ldt $f29,L.24
+cmptlt $f30,$f29,$f1
+fbne $f1,L.22
+subt $f30,$f29,$f29
+cvttqc $f29,$f1
+cvtql $f1,$f1
+sts $f1,-56+160($sp)
+ldl $27,-56+160($sp)
+addl $27,0x80000000,$10
+zap $10,240,$10
+br L.23
+L.22:
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+160($sp)
+ldl $27,-56+160($sp)
+mov $27,$10
+L.23:
+mov $10,$27
+stb $27,C
+ldt $f30,d
+ldt $f29,L.24
+cmptlt $f30,$f29,$f1
+fbne $f1,L.26
+subt $f30,$f29,$f29
+cvttqc $f29,$f1
+cvtql $f1,$f1
+sts $f1,-56+160($sp)
+ldl $27,-56+160($sp)
+addl $27,0x80000000,$9
+zap $9,240,$9
+br L.27
+L.26:
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+160($sp)
+ldl $27,-56+160($sp)
+mov $27,$9
+L.27:
+mov $9,$27
+stw $27,S
+ldt $f30,d
+ldt $f29,L.24
+cmptlt $f30,$f29,$f1
+fbne $f1,L.29
+subt $f30,$f29,$f29
+cvttqc $f29,$f1
+cvtql $f1,$f1
+sts $f1,-56+160($sp)
+ldl $27,-56+160($sp)
+addl $27,0x80000000,$27
+zap $27,240,$27
+stl $27,-60+160($sp)
+br L.30
+L.29:
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+160($sp)
+ldl $27,-56+160($sp)
+stl $27,-60+160($sp)
+L.30:
+ldl $27,-60+160($sp)
+zap $27,240,$27
+stl $27,I
+ldt $f30,d
+ldt $f29,L.34
+cmptlt $f30,$f29,$f1
+fbne $f1,L.32
+subt $f30,$f29,$f29
+cvttqc $f29,$f1
+stt $f1,-56+160($sp)
+ldq $27,-56+160($sp)
+lda $27,0x8000000000000000($27)
+stq $27,-72+160($sp)
+br L.33
+L.32:
+cvttqc $f30,$f1
+stt $f1,-56+160($sp)
+ldq $27,-56+160($sp)
+stq $27,-72+160($sp)
+L.33:
+ldq $27,-72+160($sp)
+stq $27,L
+ldt $f30,d
+cvtts $f30,$f29
+sts $f29,f
+stt $f30,D
+jsr $26,print
+ldgp $gp,0($26)
+ldt $f30,L.35
+stt $f30,D
+ldt $f30,D
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+160($sp)
+ldl $27,-56+160($sp)
+mov $27,$25
+stb $25,c
+mov $27,$25
+stw $25,s
+stl $27,i
+cvttqc $f30,$f1
+stt $f1,-56+160($sp)
+ldq $27,-56+160($sp)
+stq $27,l
+ldt $f29,L.39
+cmptlt $f30,$f29,$f1
+fbne $f1,L.37
+subt $f30,$f29,$f29
+cvttqc $f29,$f1
+cvtql $f1,$f1
+sts $f1,-56+160($sp)
+ldl $27,-56+160($sp)
+addl $27,0x80000000,$27
+zap $27,240,$27
+stl $27,-76+160($sp)
+br L.38
+L.37:
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+160($sp)
+ldl $27,-56+160($sp)
+stl $27,-76+160($sp)
+L.38:
+ldl $27,-76+160($sp)
+zap $27,240,$27
+stb $27,C
+ldt $f30,D
+ldt $f29,L.39
+cmptlt $f30,$f29,$f1
+fbne $f1,L.41
+subt $f30,$f29,$f29
+cvttqc $f29,$f1
+cvtql $f1,$f1
+sts $f1,-56+160($sp)
+ldl $27,-56+160($sp)
+addl $27,0x80000000,$27
+zap $27,240,$27
+stl $27,-80+160($sp)
+br L.42
+L.41:
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+160($sp)
+ldl $27,-56+160($sp)
+stl $27,-80+160($sp)
+L.42:
+ldl $27,-80+160($sp)
+zap $27,240,$27
+stw $27,S
+ldt $f30,D
+ldt $f29,L.39
+cmptlt $f30,$f29,$f1
+fbne $f1,L.44
+subt $f30,$f29,$f29
+cvttqc $f29,$f1
+cvtql $f1,$f1
+sts $f1,-56+160($sp)
+ldl $27,-56+160($sp)
+addl $27,0x80000000,$27
+zap $27,240,$27
+stl $27,-84+160($sp)
+br L.45
+L.44:
+cvttqc $f30,$f1
+cvtql $f1,$f1
+sts $f1,-56+160($sp)
+ldl $27,-56+160($sp)
+stl $27,-84+160($sp)
+L.45:
+ldl $27,-84+160($sp)
+zap $27,240,$27
+stl $27,I
+ldt $f30,D
+ldt $f29,L.49
+cmptlt $f30,$f29,$f1
+fbne $f1,L.47
+subt $f30,$f29,$f29
+cvttqc $f29,$f1
+stt $f1,-56+160($sp)
+ldq $27,-56+160($sp)
+lda $27,0x8000000000000000($27)
+stq $27,-96+160($sp)
+br L.48
+L.47:
+cvttqc $f30,$f1
+stt $f1,-56+160($sp)
+ldq $27,-56+160($sp)
+stq $27,-96+160($sp)
+L.48:
+ldq $27,-96+160($sp)
+stq $27,L
+ldt $f30,D
+cvtts $f30,$f29
+sts $f29,f
+stt $f30,d
+jsr $26,print
+ldgp $gp,0($26)
+stq $31,p
+stq $31,p
+stq $31,p
+stq $31,p
+ldq $27,P
+stq $27,p
+stq $31,P
+stq $31,P
+stq $31,P
+stq $31,P
+ldq $27,p
+stq $27,P
+mov $31,$0
+L.3:
+ldq $9,0($sp)
+ldq $10,8($sp)
+ldq $11,16($sp)
+ldq $12,24($sp)
+ldq $13,32($sp)
+ldq $14,40($sp)
+ldq $24,48($sp)
+ldq $26,56($sp)
+lda $sp,160($sp)
+ret
+.end main
+.globl P
+.comm P,8
+.globl p
+.comm p,8
+.globl D
+.comm D,8
+.globl d
+.comm d,8
+.globl f
+.comm f,4
+.globl L
+.comm L,8
+.globl I
+.comm I,4
+.globl S
+.comm S,2
+.globl C
+.comm C,1
+.globl l
+.comm l,8
+.globl i
+.comm i,4
+.globl s
+.comm s,2
+.globl c
+.comm c,1
+.rdata
+.align 3
+L.49:
+.long 0x0
+.long 0x43e00000
+.align 3
+L.39:
+.long 0x0
+.long 0x41e00000
+.align 3
+L.35:
+.long 0x0
+.long 0x40260000
+.align 3
+L.34:
+.long 0x0
+.long 0x43e00000
+.align 3
+L.24:
+.long 0x0
+.long 0x41e00000
+.align 3
+L.20:
+.long 0x0
+.long 0x40240000
+.align 2
+L.19:
+.long 0x5f000000
+.align 2
+L.9:
+.long 0x4f000000
+.align 2
+L.5:
+.long 0x41100000
+.align 3
+L.4:
+.long 0x0
+.long 0x40000000
+.align 0
+L.2:
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 108
+.byte 100
+.byte 32
+.byte 37
+.byte 117
+.byte 32
+.byte 37
+.byte 117
+.byte 32
+.byte 37
+.byte 117
+.byte 32
+.byte 37
+.byte 108
+.byte 117
+.byte 32
+.byte 37
+.byte 102
+.byte 32
+.byte 37
+.byte 102
+.byte 32
+.byte 37
+.byte 108
+.byte 102
+.byte 10
+.byte 0
diff --git a/lcc/alpha/osf/tst/fields.1bk b/lcc/alpha/osf/tst/fields.1bk
new file mode 100755
index 0000000..f30b13f
--- /dev/null
+++ b/lcc/alpha/osf/tst/fields.1bk
@@ -0,0 +1,5 @@
+x = 1 2 3 4 -3 6
+y = 3 8 9
+x = 1 2 3 0 0 6
+y = 2 8 16
+p->a = 0x3, p->b = 0xf
diff --git a/lcc/alpha/osf/tst/fields.2bk b/lcc/alpha/osf/tst/fields.2bk
new file mode 100755
index 0000000..e689d78
--- /dev/null
+++ b/lcc/alpha/osf/tst/fields.2bk
@@ -0,0 +1,4 @@
+tst/fields.c:6: warning: initializer exceeds bit-field width
+tst/fields.c:8: warning: initializer exceeds bit-field width
+tst/fields.c:30: warning: missing return value
+tst/fields.c:34: warning: missing return value
diff --git a/lcc/alpha/osf/tst/fields.sbk b/lcc/alpha/osf/tst/fields.sbk
new file mode 100755
index 0000000..0c8f38c
--- /dev/null
+++ b/lcc/alpha/osf/tst/fields.sbk
@@ -0,0 +1,325 @@
+.sdata
+.globl x
+.align 2
+x:
+.long 0x1
+.byte 0x2
+.space 3
+.byte 0x3
+.byte 0x40
+.space 2
+.byte 0x50
+.byte 0x6
+.space 2
+.globl i
+.align 2
+i:
+.long 0x10
+.globl y
+.align 2
+y:
+.byte 0x23
+.space 3
+.byte 0x9
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.globl main
+.text
+.text
+.ent main
+main:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4000000,-72
+.frame $sp,80,$26,48
+stq $26,8($sp)
+.prologue 1
+lda $16,L.4
+ldl $17,x
+lda $27,x+4
+ldb $18,($27)
+ldl $27,x+8
+sll $27,20,$27
+addl $27,0,$27
+sra $27,20,$19
+addl $19,0,$19
+ldl $27,x+8
+sll $27,16,$27
+addl $27,0,$27
+sra $27,28,$20
+addl $20,0,$20
+ldl $27,x+12
+sll $27,25,$27
+addl $27,0,$27
+sra $27,29,$21
+addl $21,0,$21
+lda $27,x+13
+ldb $27,($27)
+stq $27,0($sp)
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.10
+ldl $27,y
+zap $27,240,$27
+and $27,3,$17
+srl $27,2,$27
+and $27,15,$18
+ldl $19,y+4
+zap $19,240,$19
+jsr $26,printf
+ldgp $gp,0($26)
+ldl $27,x+8
+and $27,0xffff0fff,$27
+ldl $25,i
+sll $25,28,$25
+addl $25,0,$25
+sra $25,28,$25
+addl $25,0,$25
+sll $25,12,$25
+zap $25,240,$25
+and $25,0xf000,$25
+or $27,$25,$27
+stl $27,x+8
+ldl $27,x+12
+and $27,0xffffff8f,$27
+stl $27,x+12
+lda $16,L.4
+ldl $17,x
+lda $27,x+4
+ldb $18,($27)
+ldl $27,x+8
+sll $27,20,$27
+addl $27,0,$27
+sra $27,20,$19
+addl $19,0,$19
+ldl $27,x+8
+sll $27,16,$27
+addl $27,0,$27
+sra $27,28,$20
+addl $20,0,$20
+ldl $27,x+12
+sll $27,25,$27
+addl $27,0,$27
+sra $27,29,$21
+addl $21,0,$21
+lda $27,x+13
+ldb $27,($27)
+stq $27,0($sp)
+jsr $26,printf
+ldgp $gp,0($26)
+ldl $27,y
+zap $27,240,$27
+and $27,0xfffffffc,$27
+or $27,2,$27
+stl $27,y
+ldl $27,i
+stl $27,y+4
+lda $16,L.10
+ldl $27,y
+zap $27,240,$27
+and $27,3,$17
+srl $27,2,$27
+and $27,15,$18
+ldl $19,y+4
+zap $19,240,$19
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,x
+jsr $26,f2
+ldgp $gp,0($26)
+mov $31,$0
+L.3:
+ldq $26,8($sp)
+lda $sp,80($sp)
+ret
+.end main
+.globl f1
+.text
+.ent f1
+f1:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4004000,-72
+.frame $sp,80,$26,48
+stq $14,0($sp)
+stq $26,8($sp)
+mov $16,$14
+.prologue 1
+ldl $27,($14)
+zap $27,240,$27
+and $27,0xffffffc3,$27
+stl $27,($14)
+ldl $27,($14)
+zap $27,240,$27
+and $27,0xfffffffc,$27
+and $31,3,$25
+and $25,3,$25
+or $27,$25,$27
+stl $27,($14)
+ldl $27,($14)
+zap $27,240,$27
+and $27,60,$27
+cmpeq $27,$31,$23
+bne $23,L.22
+lda $16,L.24
+jsr $26,printf
+ldgp $gp,0($26)
+L.22:
+ldl $27,($14)
+zap $27,240,$27
+or $27,3,$27
+stl $27,($14)
+ldl $27,($14)
+zap $27,240,$27
+or $27,60,$27
+stl $27,($14)
+lda $16,L.25
+ldl $27,($14)
+zap $27,240,$27
+and $27,3,$17
+srl $27,2,$27
+and $27,15,$18
+jsr $26,printf
+ldgp $gp,0($26)
+mov $31,$0
+L.21:
+ldq $14,0($sp)
+ldq $26,8($sp)
+lda $sp,80($sp)
+ret
+.end f1
+.globl f2
+.text
+.ent f2
+f2:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4006000,-64
+.frame $sp,80,$26,48
+stq $13,0($sp)
+stq $14,8($sp)
+stq $26,16($sp)
+mov $16,$14
+.prologue 1
+ldl $27,i
+cmpeq $27,$31,$23
+beq $23,L.28
+lda $13,1
+br L.29
+L.28:
+mov $31,$13
+L.29:
+ldl $27,($14)
+zap $27,240,$27
+and $27,0xfffffffc,$27
+mov $13,$25
+and $25,3,$25
+and $25,3,$25
+or $27,$25,$27
+stl $27,($14)
+mov $14,$16
+jsr $26,f1
+ldgp $gp,0($26)
+ldl $27,($14)
+zap $27,240,$27
+and $27,0xffffffc3,$27
+mov $31,$25
+and $25,15,$25
+sll $25,2,$25
+zap $25,240,$25
+and $25,60,$25
+or $27,$25,$27
+stl $27,($14)
+mov $31,$0
+L.26:
+ldq $13,0($sp)
+ldq $14,8($sp)
+ldq $26,16($sp)
+lda $sp,80($sp)
+ret
+.end f2
+.rdata
+.align 0
+L.25:
+.byte 112
+.byte 45
+.byte 62
+.byte 97
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 120
+.byte 37
+.byte 120
+.byte 44
+.byte 32
+.byte 112
+.byte 45
+.byte 62
+.byte 98
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 120
+.byte 37
+.byte 120
+.byte 10
+.byte 0
+.align 0
+L.24:
+.byte 112
+.byte 45
+.byte 62
+.byte 98
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 33
+.byte 10
+.byte 0
+.align 0
+L.10:
+.byte 121
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.4:
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
diff --git a/lcc/alpha/osf/tst/front.2bk b/lcc/alpha/osf/tst/front.2bk
new file mode 100755
index 0000000..841e6a5
--- /dev/null
+++ b/lcc/alpha/osf/tst/front.2bk
@@ -0,0 +1,29 @@
+tst/front.c:3: warning: missing return value
+tst/front.c:10: warning: missing return value
+tst/front.c:20: type error in argument 1 to `s'; found `pointer to struct D' expected `pointer to incomplete struct D defined at tst/front.c:14'
+tst/front.c:21: warning: missing return value
+tst/front.c:32: warning: missing return value
+tst/front.c:36: operands of = have illegal types `pointer to int' and `pointer to const int'
+tst/front.c:38: warning: missing return value
+tst/front.c:62: operands of = have illegal types `pointer to char' and `pointer to const void'
+tst/front.c:63: warning: missing return value
+tst/front.c:68: warning: missing return value
+tst/front.c:69: warning: inconsistent linkage for `yy' previously declared at tst/front.c:68
+tst/front.c:69: warning: missing return value
+tst/front.c:71: invalid storage class `static' for `int function goo'
+tst/front.c:71: warning: declaration of `goo' does not match previous declaration at tst/front.c:70
+tst/front.c:71: warning: missing return value
+tst/front.c:74: warning: declaration of `xr' does not match previous declaration at tst/front.c:72
+tst/front.c:74: warning: missing return value
+tst/front.c:81: warning: missing return value
+tst/front.c:82: warning: declaration of `ss2' does not match previous declaration at tst/front.c:81
+tst/front.c:84: warning: inconsistent linkage for `ss5' previously declared at tst/front.c:80
+tst/front.c:92: type error in argument 1 to `gx1'; found `pointer to double' expected `double'
+tst/front.c:92: warning: missing return value
+tst/front.c:95: redeclaration of `hx1' previously declared at tst/front.c:94
+tst/front.c:98: warning: missing return value
+tst/front.c:101: conflicting argument declarations for function `gg1'
+tst/front.c:101: warning: missing return value
+tst/front.c:112: type error in argument 4 to `qsort'; found `pointer to int function(pointer to pointer to char,pointer to pointer to char)' expected `pointer to int function(pointer to const void,pointer to const void)'
+tst/front.c:113: warning: missing return value
+tst/front.c:120: warning: missing return value
diff --git a/lcc/alpha/osf/tst/front.sbk b/lcc/alpha/osf/tst/front.sbk
new file mode 100755
index 0000000..366aab1
--- /dev/null
+++ b/lcc/alpha/osf/tst/front.sbk
@@ -0,0 +1,380 @@
+.globl main
+.text
+.text
+.ent main
+main:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+.prologue 1
+mov $31,$16
+jsr $26,exit
+ldgp $gp,0($26)
+mov $31,$0
+L.1:
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end main
+.globl nested
+.text
+.ent nested
+nested:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.frame $sp,64,$26,48
+.prologue 1
+cmplt $16,4,$23
+beq $23,L.6
+lda $27,114
+cmpeq $17,$27,$23
+bne $23,L.9
+L.6:
+cmpeq $16,1,$23
+beq $23,L.8
+lda $27,104
+cmpeq $17,$27,$23
+bne $23,L.9
+lda $27,105
+cmpeq $17,$27,$23
+bne $23,L.9
+L.8:
+cmpeq $16,2,$23
+beq $23,L.3
+lda $27,111
+cmpeq $17,$27,$23
+bne $23,L.9
+lda $27,121
+cmpeq $17,$27,$23
+beq $23,L.3
+L.9:
+mov $17,$16
+L.3:
+mov $31,$0
+L.2:
+lda $sp,64($sp)
+ret
+.end nested
+.globl s
+.text
+.ent s
+s:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.frame $sp,64,$26,48
+.prologue 1
+L.10:
+lda $sp,64($sp)
+ret
+.end s
+.sdata
+.globl Dy
+.align 2
+Dy:
+.long 0x0
+.space 4
+.globl Dz
+.align 2
+Dz:
+.long 0x1
+.space 4
+.globl Dfunc
+.text
+.text
+.ent Dfunc
+Dfunc:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+.prologue 1
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end Dfunc
+.globl f
+.text
+.ent f
+f:
+ldgp $gp,0($27)
+lda $sp,-48($sp)
+.frame $sp,48,$26,48
+.prologue 1
+lda $sp,48($sp)
+ret
+.end f
+.globl f1
+.text
+.ent f1
+f1:
+ldgp $gp,0($27)
+lda $sp,-48($sp)
+.frame $sp,48,$26,48
+.prologue 1
+lda $sp,48($sp)
+ret
+.end f1
+.globl f2
+.text
+.ent f2
+f2:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+stq $16,16($sp)
+stq $17,24($sp)
+.prologue 1
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end f2
+.globl g
+.text
+.ent g
+g:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+stq $16,16($sp)
+.prologue 1
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end g
+.globl h
+.text
+.ent h
+h:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+stq $16,16($sp)
+.prologue 1
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end h
+.globl h1
+.text
+.ent h1
+h1:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+stq $16,16($sp)
+stq $17,24($sp)
+.prologue 1
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end h1
+.globl h2
+.text
+.ent h2
+h2:
+ldgp $gp,0($27)
+lda $sp,-48($sp)
+.frame $sp,48,$26,48
+.prologue 1
+lda $sp,48($sp)
+ret
+.end h2
+.sdata
+.align 2
+L.21:
+.long 0x1
+.globl set1
+.text
+.text
+.ent set1
+set1:
+ldgp $gp,0($27)
+lda $sp,-48($sp)
+.frame $sp,48,$26,48
+.prologue 1
+lda $sp,48($sp)
+ret
+.end set1
+.sdata
+.align 2
+L.23:
+.long 0x2
+.globl set2
+.text
+.text
+.ent set2
+set2:
+ldgp $gp,0($27)
+lda $sp,-48($sp)
+.frame $sp,48,$26,48
+.prologue 1
+lda $sp,48($sp)
+ret
+.end set2
+.text
+.ent goo
+goo:
+ldgp $gp,0($27)
+lda $sp,-48($sp)
+.frame $sp,48,$26,48
+.prologue 1
+lda $sp,48($sp)
+ret
+.end goo
+.globl sss
+.text
+.ent sss
+sss:
+ldgp $gp,0($27)
+lda $sp,-48($sp)
+.frame $sp,48,$26,48
+.prologue 1
+lda $sp,48($sp)
+ret
+.end sss
+.lcomm L.27,4
+.globl rrr
+.text
+.text
+.ent rrr
+rrr:
+ldgp $gp,0($27)
+lda $sp,-48($sp)
+.frame $sp,48,$26,48
+.prologue 1
+lda $sp,48($sp)
+ret
+.end rrr
+.globl setstatic
+.text
+.ent setstatic
+setstatic:
+ldgp $gp,0($27)
+lda $sp,-48($sp)
+.frame $sp,48,$26,48
+.prologue 1
+lda $sp,48($sp)
+ret
+.end setstatic
+.globl gx1
+.text
+.ent gx1
+gx1:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+stt $f16,16($sp)
+.prologue 1
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end gx1
+.globl ff1
+.text
+.ent ff1
+ff1:
+ldgp $gp,0($27)
+lda $sp,-48($sp)
+.frame $sp,48,$26,48
+.prologue 1
+lda $sp,48($sp)
+ret
+.end ff1
+.globl gg1
+.text
+.ent gg1
+gg1:
+ldgp $gp,0($27)
+lda $sp,-48($sp)
+.frame $sp,48,$26,48
+.prologue 1
+lda $sp,48($sp)
+ret
+.end gg1
+.globl hh1
+.text
+.ent hh1
+hh1:
+ldgp $gp,0($27)
+lda $sp,-48($sp)
+.frame $sp,48,$26,48
+.prologue 1
+lda $sp,48($sp)
+ret
+.end hh1
+.globl cmp
+.text
+.ent cmp
+cmp:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+stq $16,16($sp)
+stq $17,24($sp)
+.prologue 1
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end cmp
+.globl sort
+.text
+.ent sort
+sort:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+.prologue 1
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end sort
+.globl onearg
+.text
+.ent onearg
+onearg:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+.prologue 1
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end onearg
+.extern xr 4
+.globl ss4
+.comm ss4,4
+.lcomm ss2,4
+.lcomm ss5,4
+.globl ss3
+.comm ss3,4
+.lcomm ss1,4
+.lcomm yy,4
+.globl z
+.comm z,4
+.globl y
+.comm y,8
+.globl x
+.comm x,8
+.globl b
+.comm b,4
+.globl a
+.comm a,4
diff --git a/lcc/alpha/osf/tst/incr.1bk b/lcc/alpha/osf/tst/incr.1bk
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/alpha/osf/tst/incr.1bk
diff --git a/lcc/alpha/osf/tst/incr.2bk b/lcc/alpha/osf/tst/incr.2bk
new file mode 100755
index 0000000..b86c400
--- /dev/null
+++ b/lcc/alpha/osf/tst/incr.2bk
@@ -0,0 +1,9 @@
+tst/incr.c:1: warning: missing return value
+tst/incr.c:6: warning: expression with no effect elided
+tst/incr.c:6: warning: expression with no effect elided
+tst/incr.c:11: warning: missing return value
+tst/incr.c:16: warning: expression with no effect elided
+tst/incr.c:16: warning: expression with no effect elided
+tst/incr.c:21: warning: missing return value
+tst/incr.c:30: warning: missing return value
+tst/incr.c:39: warning: missing return value
diff --git a/lcc/alpha/osf/tst/incr.sbk b/lcc/alpha/osf/tst/incr.sbk
new file mode 100755
index 0000000..5a9555a
--- /dev/null
+++ b/lcc/alpha/osf/tst/incr.sbk
@@ -0,0 +1,151 @@
+.globl main
+.text
+.text
+.ent main
+main:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.frame $sp,64,$26,48
+.prologue 1
+mov $31,$0
+L.1:
+lda $sp,64($sp)
+ret
+.end main
+.globl memchar
+.text
+.ent memchar
+memchar:
+ldgp $gp,0($27)
+lda $sp,-96($sp)
+.mask 0x5000000,-88
+.frame $sp,96,$26,48
+stq $24,0($sp)
+stq $26,8($sp)
+.prologue 1
+ldq $27,-72+96($sp)
+lda $25,1($27)
+stq $25,-72+96($sp)
+ldb $27,($27)
+stb $27,-57+96($sp)
+ldq $27,-72+96($sp)
+lda $27,1($27)
+stq $27,-72+96($sp)
+ldb $27,($27)
+stb $27,-57+96($sp)
+ldq $27,-72+96($sp)
+lda $25,-1($27)
+stq $25,-72+96($sp)
+ldb $27,($27)
+stb $27,-57+96($sp)
+ldq $27,-72+96($sp)
+lda $27,-1($27)
+stq $27,-72+96($sp)
+ldb $27,($27)
+stb $27,-57+96($sp)
+mov $31,$0
+L.2:
+ldq $24,0($sp)
+ldq $26,8($sp)
+lda $sp,96($sp)
+ret
+.end memchar
+.globl memint
+.text
+.ent memint
+memint:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.frame $sp,80,$26,48
+.prologue 1
+ldq $27,-72+80($sp)
+lda $25,4($27)
+stq $25,-72+80($sp)
+ldl $27,($27)
+stl $27,-60+80($sp)
+ldq $27,-72+80($sp)
+lda $27,4($27)
+stq $27,-72+80($sp)
+ldl $27,($27)
+stl $27,-60+80($sp)
+ldq $27,-72+80($sp)
+lda $25,-4($27)
+stq $25,-72+80($sp)
+ldl $27,($27)
+stl $27,-60+80($sp)
+ldq $27,-72+80($sp)
+lda $27,-4($27)
+stq $27,-72+80($sp)
+ldl $27,($27)
+stl $27,-60+80($sp)
+mov $31,$0
+L.3:
+lda $sp,80($sp)
+ret
+.end memint
+.globl regchar
+.text
+.ent regchar
+regchar:
+ldgp $gp,0($27)
+lda $sp,-96($sp)
+.mask 0x5006000,-72
+.frame $sp,96,$26,48
+stq $13,0($sp)
+stq $14,8($sp)
+stq $24,16($sp)
+stq $26,24($sp)
+.prologue 1
+mov $13,$27
+lda $13,1($27)
+ldb $14,($27)
+lda $27,1($13)
+mov $27,$13
+ldb $14,($27)
+mov $13,$27
+lda $13,-1($27)
+ldb $14,($27)
+lda $27,-1($13)
+mov $27,$13
+ldb $14,($27)
+mov $31,$0
+L.4:
+ldq $13,0($sp)
+ldq $14,8($sp)
+ldq $24,16($sp)
+ldq $26,24($sp)
+lda $sp,96($sp)
+ret
+.end regchar
+.globl regint
+.text
+.ent regint
+regint:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4006000,-64
+.frame $sp,80,$26,48
+stq $13,0($sp)
+stq $14,8($sp)
+stq $26,16($sp)
+.prologue 1
+mov $13,$27
+lda $13,4($27)
+ldl $14,($27)
+lda $27,4($13)
+mov $27,$13
+ldl $14,($27)
+mov $13,$27
+lda $13,-4($27)
+ldl $14,($27)
+lda $27,-4($13)
+mov $27,$13
+ldl $14,($27)
+mov $31,$0
+L.5:
+ldq $13,0($sp)
+ldq $14,8($sp)
+ldq $26,16($sp)
+lda $sp,80($sp)
+ret
+.end regint
diff --git a/lcc/alpha/osf/tst/init.1bk b/lcc/alpha/osf/tst/init.1bk
new file mode 100755
index 0000000..042f3bb
--- /dev/null
+++ b/lcc/alpha/osf/tst/init.1bk
@@ -0,0 +1,16 @@
+ 1 2 3 4
+ 5 6
+ 7
+if
+for
+else
+while
+1 2 3 if
+4 5 0 for
+6 7 8 else
+9 10 11 while
+1 2 3 if
+4 5 0 for
+6 7 8 else
+9 10 11 while
+0 0 0
diff --git a/lcc/alpha/osf/tst/init.2bk b/lcc/alpha/osf/tst/init.2bk
new file mode 100755
index 0000000..da08062
--- /dev/null
+++ b/lcc/alpha/osf/tst/init.2bk
@@ -0,0 +1,3 @@
+tst/init.c:36: warning: missing return value
+tst/init.c:49: warning: missing return value
+tst/init.c:59: warning: missing return value
diff --git a/lcc/alpha/osf/tst/init.sbk b/lcc/alpha/osf/tst/init.sbk
new file mode 100755
index 0000000..3ecc4a0
--- /dev/null
+++ b/lcc/alpha/osf/tst/init.sbk
@@ -0,0 +1,333 @@
+.sdata
+.globl words
+.align 2
+words:
+.long 0x1
+.long 0x2
+.long 0x3
+.byte 105
+.byte 102
+.byte 0
+.space 3
+.space 2
+.long 0x4
+.long 0x5
+.space 4
+.byte 102
+.byte 111
+.byte 114
+.space 3
+.space 2
+.long 0x6
+.long 0x7
+.long 0x8
+.byte 101
+.byte 108
+.byte 115
+.byte 101
+.byte 0
+.space 1
+.space 2
+.long 0x9
+.long 0xa
+.long 0xb
+.byte 119
+.byte 104
+.byte 105
+.byte 108
+.byte 101
+.space 1
+.space 2
+.long 0x0
+.space 8
+.space 8
+.globl wordlist
+.align 3
+wordlist:
+.quad words
+.globl x
+.align 2
+x:
+.long 0x1
+.long 0x2
+.long 0x3
+.long 0x4
+.long 0x0
+.long 0x5
+.long 0x6
+.space 12
+.long 0x7
+.space 16
+.globl y
+.align 3
+y:
+.quad x
+.quad x+20
+.quad x+40
+.quad 0x0
+.globl main
+.text
+.text
+.ent main
+main:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4006000,-64
+.frame $sp,80,$26,48
+stq $13,0($sp)
+stq $14,8($sp)
+stq $26,16($sp)
+.prologue 1
+mov $31,$13
+br L.8
+L.5:
+mov $31,$14
+br L.12
+L.9:
+lda $16,L.13
+sll $14,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+sll $13,8*(8-4),$25
+sra $25,8*(8-4),$25
+sll $25,3,$25
+ldq $25,y($25)
+addq $27,$25,$27
+ldl $17,($27)
+jsr $26,printf
+ldgp $gp,0($26)
+L.10:
+lda $14,1($14)
+L.12:
+sll $14,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+sll $13,8*(8-4),$25
+sra $25,8*(8-4),$25
+sll $25,3,$25
+ldq $25,y($25)
+addq $27,$25,$27
+ldl $27,($27)
+cmpeq $27,$31,$23
+beq $23,L.9
+lda $16,L.14
+jsr $26,printf
+ldgp $gp,0($26)
+L.6:
+lda $13,1($13)
+L.8:
+sll $13,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,3,$27
+ldq $27,y($27)
+cmpeq $27,$31,$23
+beq $23,L.5
+jsr $26,f
+ldgp $gp,0($26)
+ldq $16,wordlist
+jsr $26,g
+ldgp $gp,0($26)
+mov $31,$0
+L.4:
+ldq $13,0($sp)
+ldq $14,8($sp)
+ldq $26,16($sp)
+lda $sp,80($sp)
+ret
+.end main
+.sdata
+.align 3
+L.16:
+.quad L.17
+.quad L.18
+.quad L.19
+.quad L.20
+.quad 0x0
+.globl f
+.text
+.text
+.ent f
+f:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4004000,-72
+.frame $sp,80,$26,48
+stq $14,0($sp)
+stq $26,8($sp)
+.prologue 1
+lda $14,L.16
+br L.24
+L.21:
+lda $16,L.25
+ldq $17,($14)
+jsr $26,printf
+ldgp $gp,0($26)
+L.22:
+lda $14,8($14)
+L.24:
+ldq $27,($14)
+cmpeq $27,$31,$23
+beq $23,L.21
+mov $31,$0
+L.15:
+ldq $14,0($sp)
+ldq $26,8($sp)
+lda $sp,80($sp)
+ret
+.end f
+.globl g
+.text
+.ent g
+g:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4006000,-64
+.frame $sp,80,$26,48
+stq $13,0($sp)
+stq $14,8($sp)
+stq $26,16($sp)
+mov $16,$14
+.prologue 1
+br L.30
+L.27:
+mov $31,$13
+br L.34
+L.31:
+lda $16,L.35
+sll $13,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+addq $27,$14,$27
+ldl $17,($27)
+jsr $26,printf
+ldgp $gp,0($26)
+L.32:
+lda $13,1($13)
+L.34:
+mov $13,$27
+lda $25,3
+cmpult $27,$25,$23
+bne $23,L.31
+lda $16,L.25
+lda $17,12($14)
+jsr $26,printf
+ldgp $gp,0($26)
+L.28:
+lda $14,20($14)
+L.30:
+ldl $27,($14)
+cmpeq $27,$31,$23
+beq $23,L.27
+jsr $26,h
+ldgp $gp,0($26)
+mov $31,$0
+L.26:
+ldq $13,0($sp)
+ldq $14,8($sp)
+ldq $26,16($sp)
+lda $sp,80($sp)
+ret
+.end g
+.globl h
+.text
+.ent h
+h:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4004000,-72
+.frame $sp,80,$26,48
+stq $14,0($sp)
+stq $26,8($sp)
+.prologue 1
+mov $31,$14
+br L.40
+L.37:
+lda $16,L.41
+lda $27,20
+sll $14,8*(8-4),$25
+sra $25,8*(8-4),$25
+mulq $27,$25,$27
+ldl $17,words($27)
+ldl $18,words+4($27)
+ldl $19,words+8($27)
+lda $20,words+12($27)
+jsr $26,printf
+ldgp $gp,0($26)
+L.38:
+lda $14,1($14)
+L.40:
+mov $14,$27
+lda $25,5
+cmpult $27,$25,$23
+bne $23,L.37
+mov $31,$0
+L.36:
+ldq $14,0($sp)
+ldq $26,8($sp)
+lda $sp,80($sp)
+ret
+.end h
+.rdata
+.align 0
+L.41:
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.35:
+.byte 37
+.byte 100
+.byte 32
+.byte 0
+.align 0
+L.25:
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.20:
+.byte 119
+.byte 104
+.byte 105
+.byte 108
+.byte 101
+.byte 0
+.align 0
+L.19:
+.byte 101
+.byte 108
+.byte 115
+.byte 101
+.byte 0
+.align 0
+L.18:
+.byte 102
+.byte 111
+.byte 114
+.byte 0
+.align 0
+L.17:
+.byte 105
+.byte 102
+.byte 0
+.align 0
+L.14:
+.byte 10
+.byte 0
+.align 0
+L.13:
+.byte 32
+.byte 37
+.byte 100
+.byte 0
diff --git a/lcc/alpha/osf/tst/limits.1bk b/lcc/alpha/osf/tst/limits.1bk
new file mode 100755
index 0000000..2bc818a
--- /dev/null
+++ b/lcc/alpha/osf/tst/limits.1bk
@@ -0,0 +1,14 @@
+UCHAR_MAX: 000000ff=255
+USHRT_MAX: 0000ffff=65535
+UINT_MAX: ffffffff=-1
+ULONG_MAX: ffffffffffffffff=-1
+CHAR_MAX: 0000007f=127
+SCHAR_MAX: 0000007f=127
+SHRT_MAX: 00007fff=32767
+INT_MAX: 7fffffff=2147483647
+LONG_MAX: 7fffffffffffffff=9223372036854775807
+CHAR_MIN: ffffff80=-128
+SCHAR_MIN: ffffff80=-128
+SHRT_MIN: ffff8000=-32768
+INT_MIN: 80000000=-2147483648
+LONG_MIN: 8000000000000000=-9223372036854775808
diff --git a/lcc/alpha/osf/tst/limits.2bk b/lcc/alpha/osf/tst/limits.2bk
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/alpha/osf/tst/limits.2bk
diff --git a/lcc/alpha/osf/tst/limits.sbk b/lcc/alpha/osf/tst/limits.sbk
new file mode 100755
index 0000000..811ce42
--- /dev/null
+++ b/lcc/alpha/osf/tst/limits.sbk
@@ -0,0 +1,405 @@
+.globl main
+.text
+.text
+.ent main
+main:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+.prologue 1
+lda $16,L.2
+lda $27,255
+mov $27,$17
+mov $27,$18
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.3
+lda $27,65535
+mov $27,$17
+mov $27,$18
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.4
+lda $27,0xffffffff
+mov $27,$17
+mov $27,$18
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.5
+lda $27,0xffffffffffffffff
+mov $27,$17
+mov $27,$18
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.6
+lda $27,127
+mov $27,$17
+mov $27,$18
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.7
+lda $27,127
+mov $27,$17
+mov $27,$18
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.8
+lda $27,32767
+mov $27,$17
+mov $27,$18
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.9
+lda $27,2147483647
+mov $27,$17
+mov $27,$18
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.10
+lda $27,9223372036854775807
+mov $27,$17
+mov $27,$18
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.11
+lda $27,-128
+mov $27,$17
+mov $27,$18
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.12
+lda $27,-128
+mov $27,$17
+mov $27,$18
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.13
+lda $27,-32768
+mov $27,$17
+mov $27,$18
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.14
+lda $27,-2147483648
+mov $27,$17
+mov $27,$18
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.15
+lda $27,-9223372036854775808
+mov $27,$17
+mov $27,$18
+jsr $26,printf
+ldgp $gp,0($26)
+mov $31,$0
+L.1:
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end main
+.rdata
+.align 0
+L.15:
+.byte 76
+.byte 79
+.byte 78
+.byte 71
+.byte 95
+.byte 77
+.byte 73
+.byte 78
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 108
+.byte 120
+.byte 61
+.byte 37
+.byte 108
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.14:
+.byte 73
+.byte 78
+.byte 84
+.byte 95
+.byte 77
+.byte 73
+.byte 78
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.13:
+.byte 83
+.byte 72
+.byte 82
+.byte 84
+.byte 95
+.byte 77
+.byte 73
+.byte 78
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.12:
+.byte 83
+.byte 67
+.byte 72
+.byte 65
+.byte 82
+.byte 95
+.byte 77
+.byte 73
+.byte 78
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.11:
+.byte 67
+.byte 72
+.byte 65
+.byte 82
+.byte 95
+.byte 77
+.byte 73
+.byte 78
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.10:
+.byte 76
+.byte 79
+.byte 78
+.byte 71
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 108
+.byte 120
+.byte 61
+.byte 37
+.byte 108
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.9:
+.byte 73
+.byte 78
+.byte 84
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.8:
+.byte 83
+.byte 72
+.byte 82
+.byte 84
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.7:
+.byte 83
+.byte 67
+.byte 72
+.byte 65
+.byte 82
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.6:
+.byte 67
+.byte 72
+.byte 65
+.byte 82
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.5:
+.byte 85
+.byte 76
+.byte 79
+.byte 78
+.byte 71
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 108
+.byte 120
+.byte 61
+.byte 37
+.byte 108
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.4:
+.byte 85
+.byte 73
+.byte 78
+.byte 84
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.3:
+.byte 85
+.byte 83
+.byte 72
+.byte 82
+.byte 84
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.2:
+.byte 85
+.byte 67
+.byte 72
+.byte 65
+.byte 82
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
diff --git a/lcc/alpha/osf/tst/paranoia.1bk b/lcc/alpha/osf/tst/paranoia.1bk
new file mode 100755
index 0000000..c74a883
--- /dev/null
+++ b/lcc/alpha/osf/tst/paranoia.1bk
@@ -0,0 +1,195 @@
+Lest this program stop prematurely, i.e. before displaying
+
+ `END OF TEST',
+
+try to persuade the computer NOT to terminate execution when an
+error like Over/Underflow or Division by Zero occurs, but rather
+to persevere with a surrogate value after, perhaps, displaying some
+warning. If persuasion avails naught, don't despair but run this
+program anyway to see how many milestones it passes, and then
+amend it to make further progress.
+
+Answer questions with Y, y, N or n (unless otherwise indicated).
+
+
+Diagnosis resumes after milestone Number 0 Page: 1
+
+Users are invited to help debug and augment this program so it will
+cope with unanticipated and newly uncovered arithmetic pathologies.
+
+Please send suggestions and interesting results to
+ Richard Karpinski
+ Computer Center U-76
+ University of California
+ San Francisco, CA 94143-0704, USA
+
+In doing so, please include the following information:
+ Precision: double;
+ Version: 10 February 1989;
+ Computer:
+
+ Compiler:
+
+ Optimization level:
+
+ Other relevant compiler options:
+
+Diagnosis resumes after milestone Number 1 Page: 2
+
+Running this program should reveal these characteristics:
+ Radix = 1, 2, 4, 8, 10, 16, 100, 256 ...
+ Precision = number of significant digits carried.
+ U2 = Radix/Radix^Precision = One Ulp
+ (OneUlpnit in the Last Place) of 1.000xxx .
+ U1 = 1/Radix^Precision = One Ulp of numbers a little less than 1.0 .
+ Adequacy of guard digits for Mult., Div. and Subt.
+ Whether arithmetic is chopped, correctly rounded, or something else
+ for Mult., Div., Add/Subt. and Sqrt.
+ Whether a Sticky Bit used correctly for rounding.
+ UnderflowThreshold = an underflow threshold.
+ E0 and PseudoZero tell whether underflow is abrupt, gradual, or fuzzy.
+ V = an overflow threshold, roughly.
+ V0 tells, roughly, whether Infinity is represented.
+ Comparisions are checked for consistency with subtraction
+ and for contamination with pseudo-zeros.
+ Sqrt is tested. Y^X is not tested.
+ Extra-precise subexpressions are revealed but NOT YET tested.
+ Decimal-Binary conversion is NOT YET tested for accuracy.
+
+Diagnosis resumes after milestone Number 2 Page: 3
+
+The program attempts to discriminate among
+ FLAWs, like lack of a sticky bit,
+ Serious DEFECTs, like lack of a guard digit, and
+ FAILUREs, like 2+2 == 5 .
+Failures may confound subsequent diagnoses.
+
+The diagnostic capabilities of this program go beyond an earlier
+program called `MACHAR', which can be found at the end of the
+book `Software Manual for the Elementary Functions' (1980) by
+W. J. Cody and W. Waite. Although both programs try to discover
+the Radix, Precision and range (over/underflow thresholds)
+of the arithmetic, this program tries to cope with a wider variety
+of pathologies, and to say how well the arithmetic is implemented.
+
+The program is based upon a conventional radix representation for
+floating-point numbers, but also allows logarithmic encoding
+as used by certain early WANG machines.
+
+BASIC version of this program (C) 1983 by Prof. W. M. Kahan;
+see source comments for more history.
+
+Diagnosis resumes after milestone Number 3 Page: 4
+
+Program is now RUNNING tests on small integers:
+-1, 0, 1/2, 1, 2, 3, 4, 5, 9, 27, 32 & 240 are O.K.
+
+Searching for Radix and Precision.
+Radix = 2.000000 .
+Closest relative separation found is U1 = 1.1102230e-16 .
+
+Recalculating radix and precision
+ confirms closest relative separation U1 .
+Radix confirmed.
+The number of significant digits of the Radix is 53.000000 .
+
+Diagnosis resumes after milestone Number 30 Page: 5
+
+Subtraction appears to be normalized, as it should be.
+Checking for guard digit in *, /, and -.
+ *, /, and - appear to have guard digits, as they should.
+
+Diagnosis resumes after milestone Number 40 Page: 6
+
+Checking rounding on multiply, divide and add/subtract.
+Multiplication appears to round correctly.
+Division appears to round correctly.
+Addition/Subtraction appears to round correctly.
+Checking for sticky bit.
+Sticky bit apparently used correctly.
+
+Does Multiplication commute? Testing on 20 random pairs.
+ No failures found in 20 integer pairs.
+
+Running test of square root(x).
+Testing if sqrt(X * X) == X for 20 Integers X.
+Test for sqrt monotonicity.
+sqrt has passed a test for Monotonicity.
+Testing whether sqrt is rounded or chopped.
+Square root appears to be correctly rounded.
+
+Diagnosis resumes after milestone Number 90 Page: 7
+
+Testing powers Z^i for small Integers Z and i.
+... no discrepancis found.
+
+Seeking Underflow thresholds UfThold and E0.
+Smallest strictly positive number found is E0 = 2.22507e-308 .
+Since comparison denies Z = 0, evaluating (Z + Z) / Z should be safe.
+What the machine gets for (Z + Z) / Z is 2.00000000000000000e+00 .
+This is O.K., provided Over/Underflow has NOT just been signaled.
+
+Diagnosis resumes after milestone Number 120 Page: 8
+
+
+FLAW: X = 3.05947655544740190e-308
+ is not equal to Z = 2.22507385850720140e-308 .
+yet X - Z yields 0.00000000000000000e+00 .
+ Should this NOT signal Underflow, this is a SERIOUS DEFECT
+that causes confusion when innocent statements like
+ if (X == Z) ... else ... (f(X) - f(Z)) / (X - Z) ...
+encounter Division by Zero although actually
+X / Z = 1 + 0.375 .
+The Underflow threshold is 2.22507385850720140e-308, below which
+calculation may suffer larger Relative error than merely roundoff.
+Since underflow occurs below the threshold
+UfThold = (2.00000000000000000e+00) ^ (-1.02200000000000000e+03)
+only underflow should afflict the expression
+ (2.00000000000000000e+00) ^ (-1.02200000000000000e+03);
+actually calculating yields: 0.00000000000000000e+00 .
+This computed value is O.K.
+
+Testing X^((X + 1) / (X - 1)) vs. exp(2) = 7.38905609893065220e+00 as X -> 1.
+Accuracy seems adequate.
+Testing powers Z^Q at four nearly extreme values.
+ ... no discrepancies found.
+
+
+Diagnosis resumes after milestone Number 160 Page: 9
+
+Searching for Overflow threshold:
+This may generate an error.
+
+* * * FLOATING-POINT ERROR * * *
+Can `Z = -Y' overflow?
+Trying it on Y = -8.98846567431157950e+307 .
+Seems O.K.
+Overflow threshold is V = 1.79769313486231570e+308 .
+There is no saturation value because the system traps on overflow.
+No Overflow should be signaled for V * 1 = 1.79769313486231570e+308
+ nor for V / 1 = 1.79769313486231570e+308 .
+Any overflow signal separating this * from the one
+above is a DEFECT.
+
+
+Diagnosis resumes after milestone Number 190 Page: 10
+
+
+What message and/or values does Division by Zero produce?
+ Trying to compute 1 / 0 produces ...
+* * * FLOATING-POINT ERROR * * *
+
+ Trying to compute 0 / 0 produces ...
+* * * FLOATING-POINT ERROR * * *
+
+Diagnosis resumes after milestone Number 220 Page: 11
+
+
+
+No failures, defects nor flaws have been discovered.
+Rounding appears to conform to the proposed IEEE standard P754,
+except for possibly Double Rounding during Gradual Underflow.
+The arithmetic diagnosed appears to be Excellent!
+
+A total of 3 floating point exceptions were registered.
+END OF TEST.
diff --git a/lcc/alpha/osf/tst/paranoia.2bk b/lcc/alpha/osf/tst/paranoia.2bk
new file mode 100755
index 0000000..f6ddf16
--- /dev/null
+++ b/lcc/alpha/osf/tst/paranoia.2bk
@@ -0,0 +1,16 @@
+tst/paranoia.c:1867: warning: missing return value
+tst/paranoia.c:1874: warning: missing return value
+tst/paranoia.c:1884: warning: missing return value
+tst/paranoia.c:1924: warning: missing return value
+tst/paranoia.c:1939: warning: missing return value
+tst/paranoia.c:1956: warning: missing return value
+tst/paranoia.c:1975: warning: missing return value
+tst/paranoia.c:1988: warning: missing return value
+tst/paranoia.c:1995: warning: missing return value
+tst/paranoia.c:2055: warning: missing return value
+tst/paranoia.c:2062: warning: missing return value
+tst/paranoia.c:2070: warning: missing return value
+tst/paranoia.c:2087: warning: missing return value
+tst/paranoia.c:2115: warning: missing return value
+tst/paranoia.c:2144: warning: missing return value
+tst/paranoia.c:2173: warning: missing return value
diff --git a/lcc/alpha/osf/tst/paranoia.sbk b/lcc/alpha/osf/tst/paranoia.sbk
new file mode 100755
index 0000000..da869df
--- /dev/null
+++ b/lcc/alpha/osf/tst/paranoia.sbk
@@ -0,0 +1,19291 @@
+.sdata
+.globl Zero
+.align 3
+Zero:
+.long 0x0
+.long 0x0
+.globl Half
+.align 3
+Half:
+.long 0x0
+.long 0x3fe00000
+.globl One
+.align 3
+One:
+.long 0x0
+.long 0x3ff00000
+.globl Two
+.align 3
+Two:
+.long 0x0
+.long 0x40000000
+.globl Three
+.align 3
+Three:
+.long 0x0
+.long 0x40080000
+.globl Four
+.align 3
+Four:
+.long 0x0
+.long 0x40100000
+.globl Five
+.align 3
+Five:
+.long 0x0
+.long 0x40140000
+.globl Eight
+.align 3
+Eight:
+.long 0x0
+.long 0x40200000
+.globl Nine
+.align 3
+Nine:
+.long 0x0
+.long 0x40220000
+.globl TwentySeven
+.align 3
+TwentySeven:
+.long 0x0
+.long 0x403b0000
+.globl ThirtyTwo
+.align 3
+ThirtyTwo:
+.long 0x0
+.long 0x40400000
+.globl TwoForty
+.align 3
+TwoForty:
+.long 0x0
+.long 0x406e0000
+.globl MinusOne
+.align 3
+MinusOne:
+.long 0x0
+.long 0xbff00000
+.globl OneAndHalf
+.align 3
+OneAndHalf:
+.long 0x0
+.long 0x3ff80000
+.globl NoTrials
+.align 2
+NoTrials:
+.long 0x14
+.globl sigfpe
+.text
+.text
+.ent sigfpe
+sigfpe:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+stq $16,16($sp)
+.prologue 1
+ldl $27,fpecount
+lda $27,1($27)
+stl $27,fpecount
+lda $16,L.3
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,_iob+56
+jsr $26,fflush
+ldgp $gp,0($26)
+ldq $27,sigsave
+cmpeq $27,$31,$23
+bne $23,L.5
+lda $16,8
+ldq $17,sigsave
+jsr $26,signal
+ldgp $gp,0($26)
+stq $31,sigsave
+lda $16,ovfl_buf
+lda $17,1
+jsr $26,longjmp
+ldgp $gp,0($26)
+L.5:
+jsr $26,abort
+ldgp $gp,0($26)
+L.2:
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end sigfpe
+.sdata
+.align 3
+L.756:
+.quad L.757
+.quad L.758
+.quad L.759
+.quad L.760
+.globl main
+.text
+.text
+.ent main
+main:
+ldgp $gp,0($27)
+lda $sp,-256($sp)
+.mask 0x4007e00,-208
+.frame $sp,256,$26,48
+stq $9,0($sp)
+stq $10,8($sp)
+stq $11,16($sp)
+stq $12,24($sp)
+stq $13,32($sp)
+stq $14,40($sp)
+stq $26,48($sp)
+.prologue 1
+ldt $f30,L.8
+stt $f30,Zero
+ldt $f30,L.9
+stt $f30,One
+ldt $f30,One
+addt $f30,$f30,$f29
+stt $f29,Two
+ldt $f29,Two
+addt $f29,$f30,$f28
+stt $f28,Three
+ldt $f28,Three
+addt $f28,$f30,$f27
+stt $f27,Four
+ldt $f27,Four
+addt $f27,$f30,$f26
+stt $f26,Five
+addt $f27,$f27,$f26
+stt $f26,Eight
+mult $f28,$f28,$f26
+stt $f26,Nine
+ldt $f26,Nine
+mult $f26,$f28,$f26
+stt $f26,TwentySeven
+ldt $f26,Eight
+mult $f27,$f26,$f26
+stt $f26,ThirtyTwo
+ldt $f26,Five
+mult $f27,$f26,$f26
+mult $f26,$f28,$f28
+mult $f28,$f27,$f28
+stt $f28,TwoForty
+negt $f30,$f28
+stt $f28,MinusOne
+divt $f30,$f29,$f29
+stt $f29,Half
+ldt $f29,Half
+addt $f30,$f29,$f30
+stt $f30,OneAndHalf
+stl $31,ErrCnt
+stl $31,ErrCnt+4
+stl $31,ErrCnt+8
+stl $31,ErrCnt+12
+lda $27,1
+stl $27,PageNo
+stl $31,Milestone
+lda $16,8
+lda $17,sigfpe
+jsr $26,signal
+ldgp $gp,0($26)
+jsr $26,Instructions
+ldgp $gp,0($26)
+jsr $26,Pause
+ldgp $gp,0($26)
+jsr $26,Heading
+ldgp $gp,0($26)
+jsr $26,Pause
+ldgp $gp,0($26)
+jsr $26,Characteristics
+ldgp $gp,0($26)
+jsr $26,Pause
+ldgp $gp,0($26)
+jsr $26,History
+ldgp $gp,0($26)
+jsr $26,Pause
+ldgp $gp,0($26)
+lda $27,7
+stl $27,Milestone
+lda $16,L.13
+jsr $26,printf
+ldgp $gp,0($26)
+mov $31,$16
+ldt $f30,Zero
+addt $f30,$f30,$f29
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.16
+ldt $f29,One
+subt $f29,$f29,$f28
+cmpteq $f28,$f30,$f1
+fbeq $f1,L.16
+cmptle $f29,$f30,$f1
+fbne $f1,L.16
+addt $f29,$f29,$f30
+ldt $f29,Two
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.16
+lda $14,1
+br L.17
+L.16:
+mov $31,$14
+L.17:
+mov $14,$17
+lda $18,L.15
+jsr $26,TstCond
+ldgp $gp,0($26)
+ldt $f30,Zero
+negt $f30,$f30
+stt $f30,Z
+ldt $f30,Z
+ldt $f29,L.8
+cmpteq $f30,$f29,$f1
+fbne $f1,L.18
+ldl $27,ErrCnt
+lda $27,1($27)
+stl $27,ErrCnt
+lda $16,L.20
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,L.21
+stt $f30,U1
+ldt $f30,L.9
+stt $f30,Radix
+jsr $26,TstPtUf
+ldgp $gp,0($26)
+L.18:
+mov $31,$16
+ldt $f30,Three
+ldt $f29,Two
+ldt $f28,One
+addt $f29,$f28,$f27
+cmpteq $f30,$f27,$f1
+fbeq $f1,L.24
+ldt $f27,Four
+addt $f30,$f28,$f26
+cmpteq $f27,$f26,$f1
+fbeq $f1,L.24
+ldt $f26,Zero
+negt $f29,$f25
+mult $f29,$f25,$f29
+addt $f27,$f29,$f29
+cmpteq $f29,$f26,$f1
+fbeq $f1,L.24
+subt $f27,$f30,$f30
+subt $f30,$f28,$f30
+cmpteq $f30,$f26,$f1
+fbeq $f1,L.24
+lda $13,1
+br L.25
+L.24:
+mov $31,$13
+L.25:
+mov $13,$17
+lda $18,L.23
+jsr $26,TstCond
+ldgp $gp,0($26)
+ldt $f30,MinusOne
+stt $f30,-64+256($sp)
+ldt $f29,One
+ldt $f28,L.8
+subt $f28,$f29,$f28
+cmpteq $f30,$f28,$f1
+fbeq $f1,L.28
+ldt $f28,Zero
+addt $f30,$f29,$f27
+cmpteq $f27,$f28,$f1
+fbeq $f1,L.28
+addt $f29,$f30,$f27
+cmpteq $f27,$f28,$f1
+fbeq $f1,L.28
+fmov $f29,$f16
+jsr $26,fabs
+ldgp $gp,0($26)
+ldt $f29,Zero
+ldt $f28,-64+256($sp)
+addt $f28,$f0,$f30
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.28
+ldt $f30,MinusOne
+mult $f30,$f30,$f28
+addt $f30,$f28,$f30
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.28
+lda $12,1
+br L.29
+L.28:
+mov $31,$12
+L.29:
+mov $31,$16
+mov $12,$17
+lda $18,L.27
+jsr $26,TstCond
+ldgp $gp,0($26)
+mov $31,$16
+ldt $f30,Half
+ldt $f29,MinusOne
+addt $f30,$f29,$f29
+addt $f29,$f30,$f30
+ldt $f29,Zero
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.32
+lda $11,1
+br L.33
+L.32:
+mov $31,$11
+L.33:
+mov $11,$17
+lda $18,L.31
+jsr $26,TstCond
+ldgp $gp,0($26)
+lda $27,10
+stl $27,Milestone
+mov $31,$16
+ldt $f30,Nine
+ldt $f29,Three
+mult $f29,$f29,$f28
+cmpteq $f30,$f28,$f1
+fbeq $f1,L.36
+ldt $f28,TwentySeven
+mult $f30,$f29,$f30
+cmpteq $f28,$f30,$f1
+fbeq $f1,L.36
+ldt $f30,Eight
+ldt $f29,Four
+addt $f29,$f29,$f27
+cmpteq $f30,$f27,$f1
+fbeq $f1,L.36
+ldt $f27,ThirtyTwo
+mult $f30,$f29,$f30
+cmpteq $f27,$f30,$f1
+fbeq $f1,L.36
+subt $f27,$f28,$f30
+subt $f30,$f29,$f30
+ldt $f29,One
+subt $f30,$f29,$f30
+ldt $f29,Zero
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.36
+lda $10,1
+br L.37
+L.36:
+mov $31,$10
+L.37:
+mov $10,$17
+lda $18,L.35
+jsr $26,TstCond
+ldgp $gp,0($26)
+mov $31,$16
+ldt $f30,Five
+ldt $f29,Four
+ldt $f28,One
+addt $f29,$f28,$f28
+cmpteq $f30,$f28,$f1
+fbeq $f1,L.40
+ldt $f28,TwoForty
+ldt $f27,Three
+mult $f29,$f30,$f26
+mult $f26,$f27,$f26
+mult $f26,$f29,$f26
+cmpteq $f28,$f26,$f1
+fbeq $f1,L.40
+ldt $f26,Zero
+divt $f28,$f27,$f25
+mult $f29,$f29,$f24
+mult $f24,$f30,$f24
+subt $f25,$f24,$f25
+cmpteq $f25,$f26,$f1
+fbeq $f1,L.40
+divt $f28,$f29,$f25
+mult $f30,$f27,$f24
+mult $f24,$f29,$f24
+subt $f25,$f24,$f25
+cmpteq $f25,$f26,$f1
+fbeq $f1,L.40
+divt $f28,$f30,$f30
+mult $f29,$f27,$f28
+mult $f28,$f29,$f29
+subt $f30,$f29,$f30
+cmpteq $f30,$f26,$f1
+fbeq $f1,L.40
+lda $9,1
+br L.41
+L.40:
+mov $31,$9
+L.41:
+mov $9,$17
+lda $18,L.39
+jsr $26,TstCond
+ldgp $gp,0($26)
+ldl $27,ErrCnt
+cmpeq $27,$31,$23
+beq $23,L.42
+lda $16,L.44
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.45
+jsr $26,printf
+ldgp $gp,0($26)
+L.42:
+lda $16,L.46
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,One
+stt $f30,W
+L.47:
+ldt $f30,W
+addt $f30,$f30,$f30
+stt $f30,W
+ldt $f30,W
+ldt $f29,One
+addt $f30,$f29,$f28
+stt $f28,Y
+ldt $f28,Y
+subt $f28,$f30,$f30
+stt $f30,Z
+ldt $f30,Z
+subt $f30,$f29,$f30
+stt $f30,Y
+L.48:
+ldt $f16,Y
+jsr $26,fabs
+ldgp $gp,0($26)
+ldt $f29,MinusOne
+addt $f29,$f0,$f30
+ldt $f29,Zero
+cmptlt $f30,$f29,$f1
+fbne $f1,L.47
+ldt $f30,Zero
+stt $f30,Precision
+ldt $f30,One
+stt $f30,Y
+L.50:
+ldt $f30,W
+ldt $f29,Y
+addt $f30,$f29,$f28
+stt $f28,Radix
+addt $f29,$f29,$f29
+stt $f29,Y
+ldt $f29,Radix
+subt $f29,$f30,$f30
+stt $f30,Radix
+L.51:
+ldt $f30,Radix
+ldt $f29,Zero
+cmpteq $f30,$f29,$f1
+fbne $f1,L.50
+ldt $f30,Radix
+ldt $f29,Two
+cmptlt $f30,$f29,$f1
+fbeq $f1,L.53
+ldt $f30,One
+stt $f30,Radix
+L.53:
+lda $16,L.55
+ldt $f17,Radix
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,Radix
+ldt $f29,L.9
+cmpteq $f30,$f29,$f1
+fbne $f1,L.56
+ldt $f30,One
+stt $f30,W
+L.58:
+ldt $f30,One
+ldt $f29,Precision
+addt $f29,$f30,$f29
+stt $f29,Precision
+ldt $f29,W
+ldt $f28,Radix
+mult $f29,$f28,$f29
+stt $f29,W
+ldt $f29,W
+addt $f29,$f30,$f30
+stt $f30,Y
+L.59:
+ldt $f30,Y
+ldt $f29,W
+subt $f30,$f29,$f30
+ldt $f29,One
+cmpteq $f30,$f29,$f1
+fbne $f1,L.58
+L.56:
+ldt $f30,One
+ldt $f29,W
+divt $f30,$f29,$f30
+stt $f30,U1
+ldt $f30,U1
+ldt $f29,Radix
+mult $f29,$f30,$f29
+stt $f29,U2
+lda $16,L.61
+fmov $f30,$f17
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.62
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,Radix
+stt $f30,E0
+ldt $f30,U1
+stt $f30,E1
+ldt $f30,U2
+stt $f30,E9
+ldt $f30,Precision
+stt $f30,E3
+ldt $f30,Four
+ldt $f29,Three
+divt $f30,$f29,$f30
+stt $f30,X
+ldt $f30,X
+ldt $f29,One
+subt $f30,$f29,$f30
+stt $f30,Third
+ldt $f30,Third
+ldt $f29,Half
+subt $f29,$f30,$f29
+stt $f29,F6
+ldt $f29,F6
+addt $f29,$f29,$f29
+stt $f29,X
+ldt $f29,X
+subt $f29,$f30,$f16
+jsr $26,fabs
+ldgp $gp,0($26)
+stt $f0,X
+ldt $f30,X
+ldt $f29,U2
+cmptlt $f30,$f29,$f1
+fbeq $f1,L.63
+ldt $f30,U2
+stt $f30,X
+L.63:
+L.65:
+ldt $f30,X
+stt $f30,U2
+ldt $f30,U2
+ldt $f29,Half
+mult $f29,$f30,$f29
+ldt $f28,ThirtyTwo
+mult $f28,$f30,$f28
+mult $f28,$f30,$f30
+addt $f29,$f30,$f30
+stt $f30,Y
+ldt $f30,One
+ldt $f29,Y
+addt $f30,$f29,$f29
+stt $f29,Y
+ldt $f29,Y
+subt $f29,$f30,$f30
+stt $f30,X
+L.66:
+ldt $f30,X
+ldt $f29,U2
+cmptle $f29,$f30,$f1
+fbne $f1,L.68
+ldt $f29,Zero
+cmptle $f30,$f29,$f1
+fbeq $f1,L.65
+L.68:
+ldt $f30,Two
+ldt $f29,Three
+divt $f30,$f29,$f30
+stt $f30,X
+ldt $f30,Half
+ldt $f29,X
+subt $f29,$f30,$f29
+stt $f29,F6
+ldt $f29,F6
+addt $f29,$f29,$f28
+stt $f28,Third
+ldt $f28,Third
+subt $f28,$f30,$f30
+stt $f30,X
+ldt $f30,X
+addt $f30,$f29,$f16
+jsr $26,fabs
+ldgp $gp,0($26)
+stt $f0,X
+ldt $f30,X
+ldt $f29,U1
+cmptlt $f30,$f29,$f1
+fbeq $f1,L.69
+ldt $f30,U1
+stt $f30,X
+L.69:
+L.71:
+ldt $f30,X
+stt $f30,U1
+ldt $f30,Half
+ldt $f29,U1
+mult $f30,$f29,$f28
+ldt $f27,ThirtyTwo
+mult $f27,$f29,$f27
+mult $f27,$f29,$f29
+addt $f28,$f29,$f29
+stt $f29,Y
+ldt $f29,Y
+subt $f30,$f29,$f29
+stt $f29,Y
+ldt $f29,Y
+addt $f30,$f29,$f29
+stt $f29,X
+ldt $f29,X
+subt $f30,$f29,$f29
+stt $f29,Y
+ldt $f29,Y
+addt $f30,$f29,$f30
+stt $f30,X
+L.72:
+ldt $f30,X
+ldt $f29,U1
+cmptle $f29,$f30,$f1
+fbne $f1,L.74
+ldt $f29,Zero
+cmptle $f30,$f29,$f1
+fbeq $f1,L.71
+L.74:
+ldt $f30,U1
+ldt $f29,E1
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.75
+lda $16,L.77
+jsr $26,printf
+ldgp $gp,0($26)
+br L.76
+L.75:
+lda $16,L.78
+ldt $f17,U1
+jsr $26,printf
+ldgp $gp,0($26)
+L.76:
+ldt $f30,U1
+ldt $f29,One
+divt $f29,$f30,$f29
+stt $f29,W
+ldt $f29,Half
+subt $f29,$f30,$f28
+addt $f28,$f29,$f29
+stt $f29,F9
+ldt $f29,U2
+divt $f29,$f30,$f30
+ldt $f29,L.79
+addt $f30,$f29,$f16
+jsr $26,floor
+ldgp $gp,0($26)
+stt $f0,Radix
+ldt $f30,Radix
+ldt $f29,E0
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.80
+lda $16,L.82
+jsr $26,printf
+ldgp $gp,0($26)
+br L.81
+L.80:
+lda $16,L.83
+ldt $f17,Radix
+jsr $26,printf
+ldgp $gp,0($26)
+L.81:
+lda $16,2
+ldt $f30,Eight
+ldt $f29,Radix
+addt $f30,$f30,$f30
+cmptle $f29,$f30,$f1
+fbeq $f1,L.86
+lda $27,1
+stl $27,-68+256($sp)
+br L.87
+L.86:
+stl $31,-68+256($sp)
+L.87:
+ldl $17,-68+256($sp)
+lda $18,L.85
+jsr $26,TstCond
+ldgp $gp,0($26)
+lda $16,3
+ldt $f30,Radix
+ldt $f29,Two
+cmpteq $f30,$f29,$f1
+fbne $f1,L.93
+ldt $f29,L.94
+cmpteq $f30,$f29,$f1
+fbne $f1,L.93
+ldt $f29,One
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.90
+L.93:
+lda $27,1
+stl $27,-72+256($sp)
+br L.91
+L.90:
+stl $31,-72+256($sp)
+L.91:
+ldl $17,-72+256($sp)
+lda $18,L.89
+jsr $26,TstCond
+ldgp $gp,0($26)
+lda $27,20
+stl $27,Milestone
+mov $31,$16
+ldt $f30,Half
+ldt $f29,F9
+subt $f29,$f30,$f29
+cmptlt $f29,$f30,$f1
+fbeq $f1,L.97
+lda $27,1
+stl $27,-76+256($sp)
+br L.98
+L.97:
+stl $31,-76+256($sp)
+L.98:
+ldl $17,-76+256($sp)
+lda $18,L.96
+jsr $26,TstCond
+ldgp $gp,0($26)
+ldt $f30,F9
+stt $f30,X
+lda $27,1
+stl $27,I
+ldt $f30,Half
+ldt $f29,X
+subt $f29,$f30,$f29
+stt $f29,Y
+ldt $f29,Y
+subt $f29,$f30,$f30
+stt $f30,Z
+mov $31,$16
+ldt $f30,X
+ldt $f29,One
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.103
+ldt $f30,Z
+ldt $f29,Zero
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.101
+L.103:
+lda $27,1
+stl $27,-80+256($sp)
+br L.102
+L.101:
+stl $31,-80+256($sp)
+L.102:
+ldl $17,-80+256($sp)
+lda $18,L.100
+jsr $26,TstCond
+ldgp $gp,0($26)
+ldt $f30,One
+ldt $f29,U2
+addt $f30,$f29,$f28
+stt $f28,X
+stl $31,I
+lda $27,25
+stl $27,Milestone
+ldt $f28,Radix
+subt $f28,$f30,$f27
+stt $f27,BMinusU2
+ldt $f27,BMinusU2
+subt $f27,$f29,$f29
+addt $f29,$f30,$f29
+stt $f29,BMinusU2
+cmpteq $f28,$f30,$f1
+fbne $f1,L.104
+ldt $f16,U1
+jsr $26,log
+ldgp $gp,0($26)
+fmov $f0,$f30
+stt $f30,-88+256($sp)
+ldt $f16,Radix
+jsr $26,log
+ldgp $gp,0($26)
+ldt $f29,TwoForty
+negt $f29,$f29
+ldt $f28,-88+256($sp)
+mult $f29,$f28,$f29
+divt $f29,$f0,$f30
+stt $f30,X
+ldt $f30,Half
+ldt $f29,X
+addt $f30,$f29,$f16
+jsr $26,floor
+ldgp $gp,0($26)
+stt $f0,Y
+ldt $f30,X
+ldt $f29,Y
+subt $f30,$f29,$f16
+jsr $26,fabs
+ldgp $gp,0($26)
+ldt $f29,Four
+mult $f0,$f29,$f30
+ldt $f29,One
+cmptlt $f30,$f29,$f1
+fbeq $f1,L.106
+ldt $f30,Y
+stt $f30,X
+L.106:
+ldt $f30,X
+ldt $f29,TwoForty
+divt $f30,$f29,$f30
+stt $f30,Precision
+ldt $f30,Half
+ldt $f29,Precision
+addt $f30,$f29,$f16
+jsr $26,floor
+ldgp $gp,0($26)
+stt $f0,Y
+ldt $f30,Precision
+ldt $f29,Y
+subt $f30,$f29,$f16
+jsr $26,fabs
+ldgp $gp,0($26)
+ldt $f29,TwoForty
+mult $f0,$f29,$f30
+ldt $f29,Half
+cmptlt $f30,$f29,$f1
+fbeq $f1,L.108
+ldt $f30,Y
+stt $f30,Precision
+L.108:
+L.104:
+ldt $f30,Precision
+stt $f30,-88+256($sp)
+fmov $f30,$f16
+jsr $26,floor
+ldgp $gp,0($26)
+ldt $f29,-88+256($sp)
+cmpteq $f29,$f0,$f1
+fbeq $f1,L.112
+ldt $f30,Radix
+ldt $f29,One
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.110
+L.112:
+lda $16,L.113
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.114
+jsr $26,printf
+ldgp $gp,0($26)
+L.110:
+ldt $f30,Radix
+ldt $f29,One
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.115
+lda $16,L.117
+jsr $26,printf
+ldgp $gp,0($26)
+br L.116
+L.115:
+lda $16,L.118
+ldt $f17,Precision
+jsr $26,printf
+ldgp $gp,0($26)
+L.116:
+lda $16,1
+ldt $f30,Nine
+ldt $f29,U2
+mult $f29,$f30,$f29
+mult $f29,$f30,$f30
+ldt $f29,TwoForty
+mult $f30,$f29,$f30
+ldt $f29,One
+cmptlt $f30,$f29,$f1
+fbeq $f1,L.121
+lda $27,1
+stl $27,-92+256($sp)
+br L.122
+L.121:
+stl $31,-92+256($sp)
+L.122:
+ldl $17,-92+256($sp)
+lda $18,L.120
+jsr $26,TstCond
+ldgp $gp,0($26)
+lda $27,30
+stl $27,Milestone
+ldt $f30,Four
+ldt $f29,Three
+ldt $f28,One
+divt $f28,$f30,$f27
+divt $f30,$f29,$f30
+subt $f30,$f28,$f30
+subt $f30,$f27,$f30
+mult $f30,$f29,$f30
+subt $f30,$f27,$f16
+jsr $26,fabs
+ldgp $gp,0($26)
+stt $f0,X
+L.123:
+ldt $f30,X
+stt $f30,Z2
+ldt $f30,One
+ldt $f29,Z2
+ldt $f28,Half
+mult $f28,$f29,$f28
+ldt $f27,ThirtyTwo
+mult $f27,$f29,$f27
+mult $f27,$f29,$f29
+addt $f28,$f29,$f29
+addt $f30,$f29,$f29
+subt $f29,$f30,$f30
+stt $f30,X
+L.124:
+ldt $f30,X
+ldt $f29,Z2
+cmptle $f29,$f30,$f1
+fbne $f1,L.126
+ldt $f29,Zero
+cmptle $f30,$f29,$f1
+fbeq $f1,L.123
+L.126:
+ldt $f30,Three
+ldt $f29,Four
+divt $f30,$f29,$f28
+ldt $f27,Two
+divt $f27,$f30,$f27
+subt $f28,$f27,$f28
+mult $f28,$f30,$f30
+ldt $f28,One
+divt $f28,$f29,$f29
+subt $f30,$f29,$f16
+jsr $26,fabs
+ldgp $gp,0($26)
+stt $f0,Z
+stt $f0,Y
+stt $f0,X
+L.127:
+ldt $f30,Z
+stt $f30,Z1
+ldt $f30,One
+ldt $f29,Two
+divt $f30,$f29,$f30
+ldt $f29,Z1
+ldt $f28,Half
+mult $f28,$f29,$f28
+ldt $f27,ThirtyTwo
+mult $f27,$f29,$f27
+mult $f27,$f29,$f29
+addt $f28,$f29,$f29
+subt $f30,$f29,$f29
+addt $f29,$f30,$f29
+subt $f30,$f29,$f29
+addt $f29,$f30,$f30
+stt $f30,Z
+L.128:
+ldt $f30,Z
+ldt $f29,Z1
+cmptle $f29,$f30,$f1
+fbne $f1,L.130
+ldt $f29,Zero
+cmptle $f30,$f29,$f1
+fbeq $f1,L.127
+L.130:
+L.131:
+L.134:
+ldt $f30,Y
+stt $f30,Y1
+ldt $f30,Half
+ldt $f29,Y1
+mult $f30,$f29,$f28
+ldt $f27,ThirtyTwo
+mult $f27,$f29,$f27
+mult $f27,$f29,$f29
+addt $f28,$f29,$f29
+subt $f30,$f29,$f29
+addt $f29,$f30,$f29
+subt $f30,$f29,$f29
+addt $f29,$f30,$f30
+stt $f30,Y
+L.135:
+ldt $f30,Y
+ldt $f29,Y1
+cmptle $f29,$f30,$f1
+fbne $f1,L.137
+ldt $f29,Zero
+cmptle $f30,$f29,$f1
+fbeq $f1,L.134
+L.137:
+ldt $f30,X
+stt $f30,X1
+ldt $f30,X1
+ldt $f29,F9
+ldt $f28,Half
+mult $f28,$f30,$f28
+ldt $f27,ThirtyTwo
+mult $f27,$f30,$f27
+mult $f27,$f30,$f30
+addt $f28,$f30,$f30
+subt $f30,$f29,$f30
+addt $f30,$f29,$f30
+stt $f30,X
+L.132:
+ldt $f30,X
+ldt $f29,X1
+cmptle $f29,$f30,$f1
+fbne $f1,L.138
+ldt $f29,Zero
+cmptle $f30,$f29,$f1
+fbeq $f1,L.131
+L.138:
+ldt $f30,X1
+ldt $f29,Y1
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.141
+ldt $f29,Z1
+cmpteq $f30,$f29,$f1
+fbne $f1,L.139
+L.141:
+lda $16,1
+lda $17,L.142
+jsr $26,BadCond
+ldgp $gp,0($26)
+lda $16,L.143
+ldt $f17,X1
+ldt $f18,Y1
+ldt $f19,Z1
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.144
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.145
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.146
+jsr $26,notify
+ldgp $gp,0($26)
+ldt $f30,U1
+ldt $f29,X1
+cmpteq $f29,$f30,$f1
+fbne $f1,L.150
+ldt $f29,Y1
+cmpteq $f29,$f30,$f1
+fbne $f1,L.150
+ldt $f29,Z1
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.140
+L.150:
+lda $16,L.151
+jsr $26,printf
+ldgp $gp,0($26)
+br L.140
+L.139:
+ldt $f30,Z1
+ldt $f29,U1
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.154
+ldt $f30,Z2
+ldt $f29,U2
+cmpteq $f30,$f29,$f1
+fbne $f1,L.152
+L.154:
+ldt $f30,Z1
+ldt $f29,U1
+cmptlt $f30,$f29,$f1
+fbeq $f1,L.157
+ldt $f30,Z2
+ldt $f29,U2
+cmptlt $f30,$f29,$f1
+fbne $f1,L.155
+L.157:
+mov $31,$16
+lda $17,L.158
+jsr $26,BadCond
+ldgp $gp,0($26)
+lda $16,L.159
+jsr $26,notify
+ldgp $gp,0($26)
+lda $16,L.160
+ldt $f30,U1
+fmov $f30,$f17
+ldt $f29,Z1
+subt $f29,$f30,$f18
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.161
+ldt $f30,U2
+fmov $f30,$f17
+ldt $f29,Z2
+subt $f29,$f30,$f18
+jsr $26,printf
+ldgp $gp,0($26)
+br L.156
+L.155:
+ldt $f30,Zero
+ldt $f29,Z1
+cmptle $f29,$f30,$f1
+fbne $f1,L.164
+ldt $f29,Z2
+cmptle $f29,$f30,$f1
+fbeq $f1,L.162
+L.164:
+lda $16,L.165
+ldt $f17,Radix
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.166
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.167
+ldt $f17,Z1
+ldt $f18,Z2
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.168
+jsr $26,notify
+ldgp $gp,0($26)
+L.162:
+ldt $f30,Z1
+ldt $f29,Z2
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.171
+ldt $f29,Zero
+cmptle $f30,$f29,$f1
+fbne $f1,L.169
+L.171:
+ldt $f30,Z1
+ldt $f29,U1
+divt $f30,$f29,$f30
+stt $f30,X
+ldt $f30,Z2
+ldt $f29,U2
+divt $f30,$f29,$f30
+stt $f30,Y
+ldt $f30,Y
+ldt $f29,X
+cmptle $f30,$f29,$f1
+fbne $f1,L.172
+ldt $f30,Y
+stt $f30,X
+L.172:
+ldt $f16,X
+jsr $26,log
+ldgp $gp,0($26)
+negt $f0,$f30
+stt $f30,Q
+lda $16,L.174
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f16,Radix
+jsr $26,log
+ldgp $gp,0($26)
+fmov $f0,$f30
+lda $16,L.175
+ldt $f29,Q
+divt $f29,$f30,$f17
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f16,L.94
+jsr $26,log
+ldgp $gp,0($26)
+fmov $f0,$f30
+lda $16,L.176
+ldt $f29,Q
+divt $f29,$f30,$f17
+jsr $26,printf
+ldgp $gp,0($26)
+L.169:
+lda $16,L.151
+jsr $26,printf
+ldgp $gp,0($26)
+L.156:
+L.152:
+L.140:
+jsr $26,Pause
+ldgp $gp,0($26)
+lda $27,35
+stl $27,Milestone
+ldt $f30,Radix
+ldt $f29,Two
+cmptlt $f30,$f29,$f1
+fbne $f1,L.177
+ldt $f30,Radix
+ldt $f29,W
+mult $f30,$f30,$f30
+divt $f29,$f30,$f30
+stt $f30,X
+ldt $f30,X
+ldt $f29,One
+addt $f30,$f29,$f29
+stt $f29,Y
+ldt $f29,Y
+subt $f29,$f30,$f30
+stt $f30,Z
+ldt $f30,Z
+ldt $f29,U2
+addt $f30,$f29,$f28
+stt $f28,T
+ldt $f28,T
+subt $f28,$f30,$f30
+stt $f30,X
+mov $31,$16
+ldt $f30,X
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.181
+lda $27,1
+stl $27,-96+256($sp)
+br L.182
+L.181:
+stl $31,-96+256($sp)
+L.182:
+ldl $17,-96+256($sp)
+lda $18,L.180
+jsr $26,TstCond
+ldgp $gp,0($26)
+ldt $f30,X
+ldt $f29,U2
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.183
+lda $16,L.185
+jsr $26,printf
+ldgp $gp,0($26)
+L.183:
+L.177:
+lda $16,L.186
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,F9
+ldt $f29,One
+mult $f30,$f29,$f28
+stt $f28,Y
+mult $f29,$f30,$f28
+stt $f28,Z
+ldt $f28,Half
+subt $f30,$f28,$f30
+stt $f30,X
+ldt $f30,X
+ldt $f27,Y
+subt $f27,$f28,$f27
+subt $f27,$f30,$f27
+stt $f27,Y
+ldt $f27,Z
+subt $f27,$f28,$f28
+subt $f28,$f30,$f30
+stt $f30,Z
+ldt $f30,U2
+addt $f29,$f30,$f28
+stt $f28,X
+ldt $f28,X
+ldt $f27,Radix
+mult $f28,$f27,$f26
+stt $f26,T
+mult $f27,$f28,$f28
+stt $f28,R
+ldt $f28,T
+subt $f28,$f27,$f28
+stt $f28,X
+mult $f27,$f30,$f30
+ldt $f28,X
+subt $f28,$f30,$f28
+stt $f28,X
+ldt $f28,R
+subt $f28,$f27,$f28
+stt $f28,T
+ldt $f28,T
+subt $f28,$f30,$f30
+stt $f30,T
+subt $f27,$f29,$f30
+ldt $f29,X
+mult $f29,$f30,$f29
+stt $f29,X
+ldt $f29,T
+mult $f29,$f30,$f30
+stt $f30,T
+ldt $f30,Zero
+ldt $f29,X
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.187
+ldt $f29,Y
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.187
+ldt $f29,Z
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.187
+ldt $f29,T
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.187
+lda $27,1
+stl $27,GMult
+br L.188
+L.187:
+mov $31,$27
+stl $27,GMult
+lda $16,1
+mov $27,$17
+lda $18,L.189
+jsr $26,TstCond
+ldgp $gp,0($26)
+L.188:
+ldt $f30,Radix
+ldt $f29,U2
+mult $f30,$f29,$f30
+stt $f30,Z
+ldt $f30,Z
+ldt $f29,One
+addt $f29,$f30,$f29
+stt $f29,X
+ldt $f29,X
+addt $f29,$f30,$f30
+mult $f29,$f29,$f29
+subt $f30,$f29,$f16
+jsr $26,fabs
+ldgp $gp,0($26)
+ldt $f29,U2
+subt $f0,$f29,$f30
+stt $f30,Y
+ldt $f30,One
+subt $f30,$f29,$f30
+stt $f30,X
+ldt $f30,X
+subt $f30,$f29,$f29
+mult $f30,$f30,$f30
+subt $f29,$f30,$f16
+jsr $26,fabs
+ldgp $gp,0($26)
+ldt $f29,U1
+subt $f0,$f29,$f30
+stt $f30,Z
+mov $31,$16
+ldt $f30,Zero
+ldt $f29,Y
+cmptle $f29,$f30,$f1
+fbeq $f1,L.192
+ldt $f29,Z
+cmptle $f29,$f30,$f1
+fbeq $f1,L.192
+lda $27,1
+stl $27,-96+256($sp)
+br L.193
+L.192:
+stl $31,-96+256($sp)
+L.193:
+ldl $17,-96+256($sp)
+lda $18,L.191
+jsr $26,TstCond
+ldgp $gp,0($26)
+ldt $f30,One
+ldt $f29,U2
+subt $f30,$f29,$f28
+stt $f28,Y
+addt $f30,$f29,$f29
+stt $f29,X
+ldt $f29,Y
+divt $f30,$f29,$f29
+stt $f29,Z
+ldt $f29,Z
+ldt $f28,X
+subt $f29,$f28,$f29
+stt $f29,Y
+ldt $f29,Three
+divt $f30,$f29,$f30
+stt $f30,X
+ldt $f30,Nine
+divt $f29,$f30,$f29
+stt $f29,Z
+ldt $f29,Z
+ldt $f28,X
+subt $f28,$f29,$f28
+stt $f28,X
+ldt $f28,TwentySeven
+divt $f30,$f28,$f30
+stt $f30,T
+ldt $f30,T
+subt $f29,$f30,$f30
+stt $f30,Z
+lda $16,2
+ldt $f30,Zero
+ldt $f29,X
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.196
+ldt $f29,Y
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.196
+ldt $f29,Z
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.196
+lda $27,1
+stl $27,-100+256($sp)
+br L.197
+L.196:
+stl $31,-100+256($sp)
+L.197:
+ldl $17,-100+256($sp)
+lda $18,L.195
+jsr $26,TstCond
+ldgp $gp,0($26)
+ldt $f30,F9
+ldt $f29,One
+divt $f30,$f29,$f28
+stt $f28,Y
+ldt $f28,Half
+subt $f30,$f28,$f30
+stt $f30,X
+ldt $f30,Y
+subt $f30,$f28,$f30
+ldt $f28,X
+subt $f30,$f28,$f30
+stt $f30,Y
+ldt $f30,U2
+addt $f29,$f30,$f30
+stt $f30,X
+ldt $f30,X
+divt $f30,$f29,$f29
+stt $f29,T
+ldt $f29,T
+subt $f29,$f30,$f30
+stt $f30,X
+ldt $f30,Zero
+ldt $f29,X
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.198
+ldt $f29,Y
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.198
+ldt $f29,Z
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.198
+lda $27,1
+stl $27,GDiv
+br L.199
+L.198:
+mov $31,$27
+stl $27,GDiv
+lda $16,1
+mov $27,$17
+lda $18,L.200
+jsr $26,TstCond
+ldgp $gp,0($26)
+L.199:
+ldt $f30,One
+ldt $f29,U2
+addt $f30,$f29,$f29
+divt $f30,$f29,$f30
+stt $f30,X
+ldt $f30,Half
+ldt $f29,X
+subt $f29,$f30,$f29
+subt $f29,$f30,$f30
+stt $f30,Y
+lda $16,1
+ldt $f30,Y
+ldt $f29,Zero
+cmptlt $f30,$f29,$f1
+fbeq $f1,L.203
+lda $27,1
+stl $27,-104+256($sp)
+br L.204
+L.203:
+stl $31,-104+256($sp)
+L.204:
+ldl $17,-104+256($sp)
+lda $18,L.202
+jsr $26,TstCond
+ldgp $gp,0($26)
+ldt $f30,One
+ldt $f29,U2
+subt $f30,$f29,$f28
+stt $f28,X
+ldt $f28,Radix
+mult $f28,$f29,$f29
+addt $f30,$f29,$f30
+stt $f30,Y
+ldt $f30,X
+mult $f30,$f28,$f29
+stt $f29,Z
+ldt $f29,Y
+mult $f29,$f28,$f27
+stt $f27,T
+ldt $f27,Z
+divt $f27,$f28,$f27
+stt $f27,R
+ldt $f27,T
+divt $f27,$f28,$f28
+stt $f28,StickyBit
+ldt $f28,R
+subt $f28,$f30,$f30
+stt $f30,X
+ldt $f30,StickyBit
+subt $f30,$f29,$f30
+stt $f30,Y
+mov $31,$16
+ldt $f30,Zero
+ldt $f29,X
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.207
+ldt $f29,Y
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.207
+lda $27,1
+stl $27,-108+256($sp)
+br L.208
+L.207:
+stl $31,-108+256($sp)
+L.208:
+ldl $17,-108+256($sp)
+lda $18,L.206
+jsr $26,TstCond
+ldgp $gp,0($26)
+ldt $f30,One
+ldt $f29,U1
+subt $f30,$f29,$f29
+stt $f29,Y
+ldt $f29,F9
+subt $f30,$f29,$f29
+stt $f29,X
+ldt $f29,Y
+subt $f30,$f29,$f30
+stt $f30,Y
+ldt $f30,Radix
+ldt $f29,U2
+subt $f30,$f29,$f29
+stt $f29,T
+ldt $f29,BMinusU2
+subt $f30,$f29,$f29
+stt $f29,Z
+ldt $f29,T
+subt $f30,$f29,$f30
+stt $f30,T
+ldt $f30,U1
+ldt $f29,X
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.209
+ldt $f29,Y
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.209
+ldt $f30,U2
+ldt $f29,Z
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.209
+ldt $f29,T
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.209
+lda $27,1
+stl $27,GAddSub
+br L.210
+L.209:
+mov $31,$27
+stl $27,GAddSub
+lda $16,1
+mov $27,$17
+lda $18,L.211
+jsr $26,TstCond
+ldgp $gp,0($26)
+L.210:
+ldt $f30,F9
+ldt $f29,One
+cmpteq $f30,$f29,$f1
+fbne $f1,L.212
+subt $f30,$f29,$f30
+ldt $f29,Zero
+cmptlt $f30,$f29,$f1
+fbne $f1,L.212
+lda $16,1
+lda $17,L.214
+jsr $26,BadCond
+ldgp $gp,0($26)
+lda $16,L.215
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.216
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.217
+jsr $26,printf
+ldgp $gp,0($26)
+L.212:
+ldl $27,GMult
+cmpeq $27,1,$23
+beq $23,L.218
+ldl $27,GDiv
+cmpeq $27,1,$23
+beq $23,L.218
+ldl $27,GAddSub
+cmpeq $27,1,$23
+beq $23,L.218
+lda $16,L.220
+jsr $26,printf
+ldgp $gp,0($26)
+L.218:
+lda $27,40
+stl $27,Milestone
+jsr $26,Pause
+ldgp $gp,0($26)
+lda $16,L.221
+jsr $26,printf
+ldgp $gp,0($26)
+stl $31,RMult
+stl $31,RDiv
+stl $31,RAddSub
+ldt $f30,Two
+ldt $f29,Radix
+divt $f29,$f30,$f29
+stt $f29,RadixD2
+stt $f30,A1
+stl $31,Done
+L.222:
+ldt $f30,Radix
+stt $f30,AInvrse
+L.225:
+ldt $f30,AInvrse
+stt $f30,X
+ldt $f29,A1
+divt $f30,$f29,$f30
+stt $f30,AInvrse
+L.226:
+ldt $f16,AInvrse
+jsr $26,floor
+ldgp $gp,0($26)
+ldt $f29,AInvrse
+cmpteq $f0,$f29,$f1
+fbne $f1,L.225
+ldt $f30,X
+ldt $f29,One
+cmpteq $f30,$f29,$f1
+fbne $f1,L.231
+ldt $f30,A1
+ldt $f29,Three
+cmptle $f30,$f29,$f1
+fbne $f1,L.229
+L.231:
+lda $27,1
+stl $27,-112+256($sp)
+br L.230
+L.229:
+stl $31,-112+256($sp)
+L.230:
+ldl $27,-112+256($sp)
+stl $27,Done
+ldl $27,Done
+cmpeq $27,$31,$23
+beq $23,L.232
+ldt $f30,Nine
+ldt $f29,One
+addt $f30,$f29,$f30
+stt $f30,A1
+L.232:
+L.223:
+ldl $27,Done
+cmpeq $27,$31,$23
+bne $23,L.222
+ldt $f30,X
+ldt $f29,One
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.234
+ldt $f30,Radix
+stt $f30,A1
+L.234:
+ldt $f30,A1
+ldt $f29,One
+divt $f29,$f30,$f29
+stt $f29,AInvrse
+stt $f30,X
+ldt $f30,AInvrse
+stt $f30,Y
+stl $31,Done
+L.236:
+ldt $f30,Half
+ldt $f29,X
+ldt $f28,Y
+mult $f29,$f28,$f29
+subt $f29,$f30,$f29
+stt $f29,Z
+mov $31,$16
+ldt $f29,Z
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.241
+lda $27,1
+stl $27,-112+256($sp)
+br L.242
+L.241:
+stl $31,-112+256($sp)
+L.242:
+ldl $17,-112+256($sp)
+lda $18,L.240
+jsr $26,TstCond
+ldgp $gp,0($26)
+ldt $f30,X
+ldt $f29,Radix
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.244
+lda $27,1
+stl $27,-116+256($sp)
+br L.245
+L.244:
+stl $31,-116+256($sp)
+L.245:
+ldl $27,-116+256($sp)
+stl $27,Done
+ldt $f30,Radix
+stt $f30,X
+ldt $f30,One
+ldt $f29,X
+divt $f30,$f29,$f30
+stt $f30,Y
+L.237:
+ldl $27,Done
+cmpeq $27,$31,$23
+bne $23,L.236
+ldt $f30,One
+ldt $f29,U2
+addt $f30,$f29,$f28
+stt $f28,Y2
+subt $f30,$f29,$f30
+stt $f30,Y1
+ldt $f30,OneAndHalf
+subt $f30,$f29,$f28
+stt $f28,X
+addt $f30,$f29,$f28
+stt $f28,Y
+ldt $f28,X
+ldt $f27,Y2
+subt $f28,$f29,$f26
+mult $f26,$f27,$f26
+stt $f26,Z
+ldt $f26,Y
+ldt $f25,Y1
+mult $f26,$f25,$f24
+stt $f24,T
+ldt $f24,Z
+subt $f24,$f28,$f24
+stt $f24,Z
+ldt $f24,T
+subt $f24,$f28,$f24
+stt $f24,T
+mult $f28,$f27,$f28
+stt $f28,X
+addt $f26,$f29,$f29
+mult $f29,$f25,$f29
+stt $f29,Y
+ldt $f29,X
+subt $f29,$f30,$f29
+stt $f29,X
+ldt $f29,Y
+subt $f29,$f30,$f30
+stt $f30,Y
+ldt $f30,Zero
+ldt $f29,X
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.246
+ldt $f29,Y
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.246
+ldt $f29,Z
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.246
+ldt $f29,T
+cmptle $f29,$f30,$f1
+fbeq $f1,L.246
+ldt $f30,OneAndHalf
+ldt $f29,U2
+addt $f30,$f29,$f28
+ldt $f27,Y2
+mult $f28,$f27,$f26
+stt $f26,X
+subt $f30,$f29,$f30
+subt $f30,$f29,$f26
+stt $f26,Y
+addt $f28,$f29,$f28
+stt $f28,Z
+ldt $f28,Y1
+mult $f30,$f28,$f30
+stt $f30,T
+ldt $f30,Z
+addt $f30,$f29,$f26
+ldt $f25,X
+subt $f25,$f26,$f25
+stt $f25,X
+ldt $f25,Y
+mult $f25,$f28,$f24
+stt $f24,StickyBit
+mult $f30,$f27,$f30
+stt $f30,S
+ldt $f30,T
+subt $f30,$f25,$f30
+stt $f30,T
+subt $f29,$f25,$f30
+ldt $f25,StickyBit
+addt $f30,$f25,$f30
+stt $f30,Y
+ldt $f30,S
+addt $f26,$f29,$f26
+subt $f30,$f26,$f30
+stt $f30,Z
+addt $f27,$f29,$f30
+mult $f30,$f28,$f30
+stt $f30,StickyBit
+mult $f27,$f28,$f30
+stt $f30,Y1
+ldt $f30,StickyBit
+subt $f30,$f27,$f30
+stt $f30,StickyBit
+ldt $f30,Y1
+ldt $f29,Half
+subt $f30,$f29,$f30
+stt $f30,Y1
+ldt $f30,Zero
+ldt $f29,X
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.248
+ldt $f29,Y
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.248
+ldt $f29,Z
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.248
+ldt $f29,T
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.248
+ldt $f29,StickyBit
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.248
+ldt $f30,Y1
+ldt $f29,Half
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.248
+lda $27,1
+stl $27,RMult
+lda $16,L.250
+jsr $26,printf
+ldgp $gp,0($26)
+br L.249
+L.248:
+ldt $f30,U2
+ldt $f29,Zero
+ldt $f28,X
+addt $f28,$f30,$f28
+cmpteq $f28,$f29,$f1
+fbeq $f1,L.251
+ldt $f28,Y
+cmptlt $f28,$f29,$f1
+fbeq $f1,L.251
+ldt $f28,Z
+addt $f28,$f30,$f28
+cmpteq $f28,$f29,$f1
+fbeq $f1,L.251
+ldt $f28,T
+cmptlt $f28,$f29,$f1
+fbeq $f1,L.251
+ldt $f28,StickyBit
+addt $f28,$f30,$f30
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.251
+ldt $f30,Y1
+ldt $f29,Half
+cmptlt $f30,$f29,$f1
+fbeq $f1,L.251
+lda $27,2
+stl $27,RMult
+lda $16,L.253
+jsr $26,printf
+ldgp $gp,0($26)
+br L.252
+L.251:
+lda $16,L.254
+jsr $26,printf
+ldgp $gp,0($26)
+L.252:
+L.249:
+ldl $27,RMult
+cmpeq $27,1,$23
+beq $23,L.247
+ldl $27,GMult
+cmpeq $27,$31,$23
+beq $23,L.247
+lda $16,L.257
+jsr $26,notify
+ldgp $gp,0($26)
+br L.247
+L.246:
+lda $16,L.254
+jsr $26,printf
+ldgp $gp,0($26)
+L.247:
+lda $27,45
+stl $27,Milestone
+ldt $f30,One
+ldt $f29,U2
+addt $f30,$f29,$f28
+stt $f28,Y2
+subt $f30,$f29,$f30
+stt $f30,Y1
+ldt $f30,OneAndHalf
+addt $f30,$f29,$f28
+addt $f28,$f29,$f27
+stt $f27,Z
+ldt $f27,Z
+ldt $f26,Y2
+divt $f27,$f26,$f25
+stt $f25,X
+subt $f30,$f29,$f25
+subt $f25,$f29,$f25
+stt $f25,T
+ldt $f25,T
+ldt $f24,Y1
+subt $f25,$f29,$f23
+divt $f23,$f24,$f23
+stt $f23,Y
+addt $f27,$f29,$f27
+divt $f27,$f26,$f27
+stt $f27,Z
+ldt $f27,X
+subt $f27,$f30,$f27
+stt $f27,X
+ldt $f27,Y
+subt $f27,$f25,$f27
+stt $f27,Y
+divt $f25,$f24,$f27
+stt $f27,T
+ldt $f27,Z
+subt $f27,$f28,$f28
+stt $f28,Z
+subt $f29,$f30,$f30
+ldt $f29,T
+addt $f30,$f29,$f30
+stt $f30,T
+ldt $f30,Zero
+ldt $f29,X
+cmptle $f29,$f30,$f1
+fbeq $f1,L.258
+ldt $f29,Y
+cmptle $f29,$f30,$f1
+fbeq $f1,L.258
+ldt $f29,Z
+cmptle $f29,$f30,$f1
+fbeq $f1,L.258
+ldt $f29,T
+cmptle $f29,$f30,$f1
+fbeq $f1,L.258
+ldt $f30,OneAndHalf
+ldt $f29,Y2
+divt $f30,$f29,$f28
+stt $f28,X
+ldt $f28,U2
+subt $f30,$f28,$f27
+stt $f27,Y
+addt $f30,$f28,$f27
+stt $f27,Z
+ldt $f27,Y
+ldt $f26,X
+subt $f26,$f27,$f26
+stt $f26,X
+ldt $f26,Y1
+divt $f30,$f26,$f25
+stt $f25,T
+divt $f27,$f26,$f27
+stt $f27,Y
+ldt $f27,Z
+ldt $f26,T
+addt $f27,$f28,$f25
+subt $f26,$f25,$f26
+stt $f26,T
+ldt $f26,Y
+subt $f26,$f27,$f26
+stt $f26,Y
+divt $f27,$f29,$f27
+stt $f27,Z
+addt $f29,$f28,$f28
+divt $f28,$f29,$f28
+stt $f28,Y1
+ldt $f28,Z
+subt $f28,$f30,$f30
+stt $f30,Z
+ldt $f30,Y1
+subt $f30,$f29,$f30
+stt $f30,Y2
+ldt $f30,F9
+ldt $f29,U1
+subt $f30,$f29,$f29
+divt $f29,$f30,$f30
+stt $f30,Y1
+ldt $f30,Zero
+ldt $f29,X
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.260
+ldt $f29,Y
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.260
+ldt $f29,Z
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.260
+ldt $f29,T
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.260
+ldt $f29,Y2
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.260
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.260
+ldt $f30,Half
+ldt $f29,Y1
+subt $f29,$f30,$f29
+ldt $f28,F9
+subt $f28,$f30,$f30
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.260
+lda $27,1
+stl $27,RDiv
+lda $16,L.262
+jsr $26,printf
+ldgp $gp,0($26)
+ldl $27,GDiv
+cmpeq $27,$31,$23
+beq $23,L.261
+lda $16,L.265
+jsr $26,notify
+ldgp $gp,0($26)
+br L.261
+L.260:
+ldt $f30,Zero
+ldt $f29,X
+cmptlt $f29,$f30,$f1
+fbeq $f1,L.266
+ldt $f29,Y
+cmptlt $f29,$f30,$f1
+fbeq $f1,L.266
+ldt $f29,Z
+cmptlt $f29,$f30,$f1
+fbeq $f1,L.266
+ldt $f29,T
+cmptlt $f29,$f30,$f1
+fbeq $f1,L.266
+ldt $f29,Y2
+cmptlt $f29,$f30,$f1
+fbeq $f1,L.266
+ldt $f30,Half
+ldt $f29,Y1
+subt $f29,$f30,$f29
+ldt $f28,F9
+subt $f28,$f30,$f30
+cmptlt $f29,$f30,$f1
+fbeq $f1,L.266
+lda $27,2
+stl $27,RDiv
+lda $16,L.268
+jsr $26,printf
+ldgp $gp,0($26)
+L.266:
+L.261:
+L.258:
+ldl $27,RDiv
+cmpeq $27,$31,$23
+beq $23,L.269
+lda $16,L.271
+jsr $26,printf
+ldgp $gp,0($26)
+L.269:
+ldt $f30,Radix
+ldt $f29,One
+divt $f29,$f30,$f29
+stt $f29,BInvrse
+mov $31,$16
+ldt $f29,Half
+ldt $f28,BInvrse
+mult $f28,$f30,$f30
+subt $f30,$f29,$f30
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.274
+lda $27,1
+stl $27,-112+256($sp)
+br L.275
+L.274:
+stl $31,-112+256($sp)
+L.275:
+ldl $17,-112+256($sp)
+lda $18,L.273
+jsr $26,TstCond
+ldgp $gp,0($26)
+lda $27,50
+stl $27,Milestone
+mov $31,$16
+ldt $f30,Half
+ldt $f29,F9
+ldt $f28,U1
+addt $f29,$f28,$f29
+subt $f29,$f30,$f29
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.278
+ldt $f30,One
+ldt $f29,BMinusU2
+ldt $f28,U2
+addt $f29,$f28,$f29
+subt $f29,$f30,$f29
+ldt $f28,Radix
+subt $f28,$f30,$f30
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.278
+lda $27,1
+stl $27,-116+256($sp)
+br L.279
+L.278:
+stl $31,-116+256($sp)
+L.279:
+ldl $17,-116+256($sp)
+lda $18,L.277
+jsr $26,TstCond
+ldgp $gp,0($26)
+ldt $f30,One
+ldt $f29,U1
+mult $f29,$f29,$f29
+subt $f30,$f29,$f29
+stt $f29,X
+ldt $f29,U2
+subt $f30,$f29,$f28
+mult $f29,$f28,$f29
+addt $f30,$f29,$f29
+stt $f29,Y
+ldt $f29,Half
+ldt $f28,F9
+subt $f28,$f29,$f28
+stt $f28,Z
+ldt $f28,X
+subt $f28,$f29,$f29
+ldt $f28,Z
+subt $f29,$f28,$f29
+stt $f29,X
+ldt $f29,Y
+subt $f29,$f30,$f30
+stt $f30,Y
+ldt $f30,Zero
+ldt $f29,X
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.280
+ldt $f29,Y
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.280
+lda $27,2
+stl $27,RAddSub
+lda $16,L.282
+jsr $26,printf
+ldgp $gp,0($26)
+L.280:
+ldl $27,GAddSub
+cmpeq $27,1,$23
+beq $23,L.283
+ldt $f30,Half
+ldt $f29,U2
+addt $f30,$f29,$f28
+mult $f28,$f29,$f28
+stt $f28,X
+subt $f30,$f29,$f30
+mult $f30,$f29,$f30
+stt $f30,Y
+ldt $f30,One
+ldt $f28,X
+addt $f30,$f28,$f28
+stt $f28,X
+ldt $f28,Y
+addt $f30,$f28,$f28
+stt $f28,Y
+addt $f30,$f29,$f29
+ldt $f28,X
+subt $f29,$f28,$f29
+stt $f29,X
+ldt $f29,Y
+subt $f30,$f29,$f30
+stt $f30,Y
+ldt $f30,Zero
+ldt $f29,X
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.285
+ldt $f29,Y
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.285
+ldt $f30,Half
+ldt $f29,U2
+ldt $f28,U1
+addt $f30,$f29,$f27
+mult $f27,$f28,$f27
+stt $f27,X
+subt $f30,$f29,$f30
+mult $f30,$f28,$f30
+stt $f30,Y
+ldt $f30,One
+ldt $f29,X
+subt $f30,$f29,$f29
+stt $f29,X
+ldt $f29,Y
+subt $f30,$f29,$f29
+stt $f29,Y
+ldt $f29,F9
+ldt $f28,X
+subt $f29,$f28,$f29
+stt $f29,X
+ldt $f29,Y
+subt $f30,$f29,$f30
+stt $f30,Y
+ldt $f30,Zero
+ldt $f29,X
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.287
+ldt $f29,Y
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.287
+lda $27,1
+stl $27,RAddSub
+lda $16,L.289
+jsr $26,printf
+ldgp $gp,0($26)
+ldl $27,GAddSub
+cmpeq $27,$31,$23
+beq $23,L.284
+lda $16,L.292
+jsr $26,notify
+ldgp $gp,0($26)
+br L.284
+L.287:
+lda $16,L.293
+jsr $26,printf
+ldgp $gp,0($26)
+br L.284
+L.285:
+lda $16,L.293
+jsr $26,printf
+ldgp $gp,0($26)
+br L.284
+L.283:
+lda $16,L.293
+jsr $26,printf
+ldgp $gp,0($26)
+L.284:
+ldt $f30,One
+stt $f30,S
+ldt $f29,Half
+addt $f30,$f29,$f28
+mult $f29,$f28,$f28
+addt $f30,$f28,$f28
+stt $f28,X
+ldt $f28,U2
+addt $f30,$f28,$f30
+mult $f30,$f29,$f30
+stt $f30,Y
+ldt $f30,X
+ldt $f29,Y
+subt $f30,$f29,$f28
+stt $f28,Z
+subt $f29,$f30,$f30
+stt $f30,T
+ldt $f30,Z
+ldt $f29,T
+addt $f30,$f29,$f30
+stt $f30,StickyBit
+ldt $f30,StickyBit
+ldt $f29,Zero
+cmpteq $f30,$f29,$f1
+fbne $f1,L.294
+ldt $f30,Zero
+stt $f30,S
+lda $16,3
+lda $17,L.296
+jsr $26,BadCond
+ldgp $gp,0($26)
+L.294:
+ldt $f30,Zero
+stt $f30,StickyBit
+ldl $27,GMult
+cmpeq $27,1,$23
+beq $23,L.297
+ldl $27,GDiv
+cmpeq $27,1,$23
+beq $23,L.297
+ldl $27,GAddSub
+cmpeq $27,1,$23
+beq $23,L.297
+ldl $27,RMult
+cmpeq $27,1,$23
+beq $23,L.297
+ldl $27,RDiv
+cmpeq $27,1,$23
+beq $23,L.297
+ldl $27,RAddSub
+cmpeq $27,1,$23
+beq $23,L.297
+ldt $f16,RadixD2
+jsr $26,floor
+ldgp $gp,0($26)
+ldt $f29,RadixD2
+cmpteq $f0,$f29,$f1
+fbeq $f1,L.297
+lda $16,L.299
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,Half
+ldt $f29,U2
+ldt $f28,U1
+addt $f30,$f28,$f28
+mult $f28,$f29,$f28
+stt $f28,X
+mult $f30,$f29,$f30
+stt $f30,Y
+ldt $f30,One
+ldt $f29,Y
+addt $f30,$f29,$f29
+stt $f29,Z
+ldt $f29,X
+addt $f30,$f29,$f30
+stt $f30,T
+ldt $f30,One
+ldt $f29,Z
+subt $f29,$f30,$f29
+ldt $f28,Zero
+cmptle $f29,$f28,$f1
+fbeq $f1,L.300
+ldt $f29,T
+subt $f29,$f30,$f30
+ldt $f29,U2
+cmptlt $f30,$f29,$f1
+fbne $f1,L.300
+ldt $f30,T
+ldt $f29,Y
+addt $f30,$f29,$f30
+stt $f30,Z
+ldt $f30,Z
+ldt $f29,X
+subt $f30,$f29,$f30
+stt $f30,Y
+ldt $f30,T
+ldt $f29,Z
+subt $f29,$f30,$f29
+ldt $f28,U2
+cmptlt $f29,$f28,$f1
+fbne $f1,L.302
+ldt $f29,Y
+subt $f29,$f30,$f30
+ldt $f29,Zero
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.302
+ldt $f30,Half
+ldt $f29,U1
+addt $f30,$f29,$f28
+mult $f28,$f29,$f28
+stt $f28,X
+mult $f30,$f29,$f30
+stt $f30,Y
+ldt $f30,One
+ldt $f29,Y
+subt $f30,$f29,$f29
+stt $f29,Z
+ldt $f29,X
+subt $f30,$f29,$f30
+stt $f30,T
+ldt $f30,Zero
+ldt $f29,Z
+ldt $f28,One
+subt $f29,$f28,$f29
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.304
+ldt $f29,T
+ldt $f28,F9
+subt $f29,$f28,$f29
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.304
+ldt $f30,U1
+ldt $f29,Half
+subt $f29,$f30,$f29
+mult $f29,$f30,$f30
+stt $f30,Z
+ldt $f30,F9
+ldt $f29,Z
+subt $f30,$f29,$f29
+stt $f29,T
+ldt $f29,Y
+subt $f30,$f29,$f30
+stt $f30,Q
+ldt $f30,F9
+ldt $f29,Zero
+ldt $f28,T
+subt $f28,$f30,$f28
+cmpteq $f28,$f29,$f1
+fbeq $f1,L.306
+ldt $f28,U1
+subt $f30,$f28,$f30
+ldt $f28,Q
+subt $f30,$f28,$f30
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.306
+ldt $f30,One
+ldt $f29,U2
+ldt $f28,OneAndHalf
+addt $f30,$f29,$f27
+mult $f27,$f28,$f27
+stt $f27,Z
+addt $f28,$f29,$f28
+ldt $f27,Z
+subt $f28,$f27,$f28
+addt $f28,$f29,$f28
+stt $f28,T
+ldt $f28,Radix
+ldt $f27,Half
+divt $f27,$f28,$f27
+addt $f30,$f27,$f27
+stt $f27,X
+mult $f28,$f29,$f29
+addt $f30,$f29,$f30
+stt $f30,Y
+ldt $f30,X
+ldt $f29,Y
+mult $f30,$f29,$f30
+stt $f30,Z
+ldt $f30,Zero
+ldt $f29,T
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.308
+ldt $f29,X
+ldt $f28,Radix
+ldt $f27,U2
+mult $f28,$f27,$f28
+addt $f29,$f28,$f29
+ldt $f28,Z
+subt $f29,$f28,$f29
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.308
+ldt $f30,Radix
+ldt $f29,Two
+cmpteq $f30,$f29,$f1
+fbne $f1,L.310
+ldt $f30,Two
+ldt $f29,U2
+addt $f30,$f29,$f29
+stt $f29,X
+ldt $f29,X
+divt $f29,$f30,$f30
+stt $f30,Y
+ldt $f30,Y
+ldt $f29,One
+subt $f30,$f29,$f30
+ldt $f29,Zero
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.311
+ldt $f30,S
+stt $f30,StickyBit
+br L.311
+L.310:
+ldt $f30,S
+stt $f30,StickyBit
+L.311:
+L.308:
+L.306:
+L.304:
+L.302:
+L.300:
+L.297:
+ldt $f30,StickyBit
+ldt $f29,One
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.314
+lda $16,L.316
+jsr $26,printf
+ldgp $gp,0($26)
+br L.315
+L.314:
+lda $16,L.317
+jsr $26,printf
+ldgp $gp,0($26)
+L.315:
+lda $16,3
+ldl $25,GMult
+cmpeq $25,$31,$23
+bne $23,L.320
+ldl $25,GDiv
+cmpeq $25,$31,$23
+bne $23,L.320
+ldl $25,GAddSub
+cmpeq $25,$31,$23
+bne $23,L.320
+ldl $25,RMult
+cmpeq $25,$31,$23
+bne $23,L.320
+ldl $25,RDiv
+cmpeq $25,$31,$23
+bne $23,L.320
+ldl $25,RAddSub
+cmpeq $25,$31,$23
+bne $23,L.320
+lda $27,1
+stl $27,-120+256($sp)
+br L.321
+L.320:
+stl $31,-120+256($sp)
+L.321:
+ldl $17,-120+256($sp)
+lda $18,L.319
+jsr $26,TstCond
+ldgp $gp,0($26)
+lda $27,60
+stl $27,Milestone
+lda $16,L.45
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.322
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.323
+ldl $17,NoTrials
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f16,L.324
+jsr $26,sqrt
+ldgp $gp,0($26)
+stt $f0,Random9
+ldt $f30,Third
+stt $f30,Random1
+lda $27,1
+stl $27,I
+L.325:
+jsr $26,Random
+ldgp $gp,0($26)
+stt $f0,X
+jsr $26,Random
+ldgp $gp,0($26)
+stt $f0,Y
+ldt $f30,Y
+ldt $f29,X
+mult $f30,$f29,$f28
+stt $f28,Z9
+mult $f29,$f30,$f30
+stt $f30,Z
+ldt $f30,Z
+ldt $f29,Z9
+subt $f30,$f29,$f30
+stt $f30,Z9
+ldl $27,I
+lda $27,1($27)
+stl $27,I
+L.326:
+ldl $27,I
+ldl $25,NoTrials
+cmple $27,$25,$23
+beq $23,L.328
+ldt $f30,Z9
+ldt $f29,Zero
+cmpteq $f30,$f29,$f1
+fbne $f1,L.325
+L.328:
+ldl $27,I
+ldl $25,NoTrials
+cmpeq $27,$25,$23
+beq $23,L.329
+ldt $f30,One
+ldt $f29,Half
+ldt $f28,Three
+divt $f29,$f28,$f29
+addt $f30,$f29,$f29
+stt $f29,Random1
+ldt $f28,U2
+ldt $f27,U1
+addt $f28,$f27,$f28
+addt $f28,$f30,$f30
+stt $f30,Random2
+ldt $f28,Random1
+ldt $f27,Random2
+mult $f28,$f27,$f26
+stt $f26,Z
+mult $f27,$f28,$f28
+stt $f28,Y
+mult $f29,$f30,$f30
+subt $f30,$f30,$f30
+stt $f30,Z9
+L.329:
+ldl $27,I
+ldl $25,NoTrials
+cmpeq $27,$25,$23
+bne $23,L.331
+ldt $f30,Z9
+ldt $f29,Zero
+cmpteq $f30,$f29,$f1
+fbne $f1,L.331
+lda $16,2
+lda $17,L.333
+jsr $26,BadCond
+ldgp $gp,0($26)
+br L.332
+L.331:
+lda $16,L.334
+ldl $17,NoTrials
+jsr $26,printf
+ldgp $gp,0($26)
+L.332:
+lda $27,70
+stl $27,Milestone
+lda $16,L.335
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,Zero
+stt $f30,-136+256($sp)
+fmov $f30,$f16
+jsr $26,sqrt
+ldgp $gp,0($26)
+ldt $f29,-136+256($sp)
+cmpteq $f29,$f0,$f1
+fbeq $f1,L.338
+ldt $f30,Zero
+negt $f30,$f30
+stt $f30,-144+256($sp)
+fmov $f30,$f16
+jsr $26,sqrt
+ldgp $gp,0($26)
+ldt $f29,-144+256($sp)
+cmpteq $f29,$f0,$f1
+fbeq $f1,L.338
+ldt $f30,One
+stt $f30,-152+256($sp)
+fmov $f30,$f16
+jsr $26,sqrt
+ldgp $gp,0($26)
+fmov $f0,$f30
+ldt $f29,-152+256($sp)
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.338
+lda $27,1
+stl $27,-124+256($sp)
+br L.339
+L.338:
+stl $31,-124+256($sp)
+L.339:
+mov $31,$16
+ldl $17,-124+256($sp)
+lda $18,L.337
+jsr $26,TstCond
+ldgp $gp,0($26)
+ldt $f30,Zero
+stt $f30,MinSqEr
+stt $f30,MaxSqEr
+stt $f30,J
+ldt $f30,Radix
+stt $f30,X
+ldt $f30,U2
+stt $f30,OneUlp
+lda $16,1
+jsr $26,SqXMinX
+ldgp $gp,0($26)
+ldt $f30,BInvrse
+stt $f30,X
+ldt $f29,U1
+mult $f30,$f29,$f30
+stt $f30,OneUlp
+lda $16,1
+jsr $26,SqXMinX
+ldgp $gp,0($26)
+ldt $f30,U1
+stt $f30,X
+mult $f30,$f30,$f30
+stt $f30,OneUlp
+lda $16,1
+jsr $26,SqXMinX
+ldgp $gp,0($26)
+ldt $f30,J
+ldt $f29,Zero
+cmpteq $f30,$f29,$f1
+fbne $f1,L.340
+jsr $26,Pause
+ldgp $gp,0($26)
+L.340:
+lda $16,L.342
+ldl $17,NoTrials
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,Zero
+stt $f30,J
+ldt $f30,Two
+stt $f30,X
+ldt $f30,Radix
+stt $f30,Y
+ldt $f29,One
+cmpteq $f30,$f29,$f1
+fbne $f1,L.343
+L.345:
+ldt $f30,Y
+stt $f30,X
+ldt $f29,Radix
+mult $f29,$f30,$f30
+stt $f30,Y
+L.346:
+ldt $f30,Y
+ldt $f29,X
+subt $f30,$f29,$f30
+lds $f29,NoTrials
+cvtlq $f29,$f29
+cvtqt $f29,$f29
+cmptlt $f30,$f29,$f1
+fbne $f1,L.345
+L.343:
+ldt $f30,X
+ldt $f29,U2
+mult $f30,$f29,$f30
+stt $f30,OneUlp
+lda $27,1
+stl $27,I
+br L.349
+L.348:
+ldt $f30,X
+ldt $f29,One
+addt $f30,$f29,$f30
+stt $f30,X
+lda $16,2
+jsr $26,SqXMinX
+ldgp $gp,0($26)
+ldt $f30,J
+ldt $f29,Zero
+cmptle $f30,$f29,$f1
+fbne $f1,L.351
+br L.350
+L.351:
+ldl $27,I
+lda $27,1($27)
+stl $27,I
+L.349:
+ldl $27,I
+ldl $25,NoTrials
+cmple $27,$25,$23
+bne $23,L.348
+L.350:
+lda $16,L.353
+jsr $26,printf
+ldgp $gp,0($26)
+lda $27,-1
+stl $27,I
+ldt $f30,BMinusU2
+stt $f30,X
+ldt $f30,Radix
+stt $f30,Y
+ldt $f29,U2
+mult $f30,$f29,$f29
+addt $f30,$f29,$f30
+stt $f30,Z
+stl $31,NotMonot
+stl $31,Monot
+br L.355
+L.354:
+ldl $27,I
+lda $27,1($27)
+stl $27,I
+ldt $f16,X
+jsr $26,sqrt
+ldgp $gp,0($26)
+stt $f0,X
+ldt $f16,Y
+jsr $26,sqrt
+ldgp $gp,0($26)
+stt $f0,Q
+ldt $f16,Z
+jsr $26,sqrt
+ldgp $gp,0($26)
+stt $f0,Z
+ldt $f30,Q
+ldt $f29,X
+cmptle $f29,$f30,$f1
+fbeq $f1,L.359
+ldt $f29,Z
+cmptle $f30,$f29,$f1
+fbne $f1,L.357
+L.359:
+lda $27,1
+stl $27,NotMonot
+br L.358
+L.357:
+ldt $f30,Q
+ldt $f29,Half
+addt $f30,$f29,$f16
+jsr $26,floor
+ldgp $gp,0($26)
+stt $f0,Q
+ldl $27,I
+cmple $27,$31,$23
+beq $23,L.362
+ldt $f30,Q
+ldt $f29,Radix
+mult $f30,$f30,$f30
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.360
+L.362:
+lda $27,1
+stl $27,Monot
+br L.361
+L.360:
+ldl $27,I
+cmple $27,$31,$23
+bne $23,L.363
+ldl $27,I
+cmple $27,1,$23
+bne $23,L.365
+lda $27,1
+stl $27,Monot
+br L.364
+L.365:
+ldt $f30,Y
+ldt $f29,BInvrse
+mult $f30,$f29,$f30
+stt $f30,Y
+ldt $f30,Y
+ldt $f29,U1
+subt $f30,$f29,$f28
+stt $f28,X
+addt $f30,$f29,$f30
+stt $f30,Z
+br L.364
+L.363:
+ldt $f30,Q
+stt $f30,Y
+ldt $f30,Y
+ldt $f29,U2
+subt $f30,$f29,$f28
+stt $f28,X
+addt $f30,$f29,$f30
+stt $f30,Z
+L.364:
+L.361:
+L.358:
+L.355:
+ldl $25,NotMonot
+cmpeq $25,$31,$23
+beq $23,L.367
+ldl $25,Monot
+cmpeq $25,$31,$23
+bne $23,L.354
+L.367:
+ldl $27,Monot
+cmpeq $27,$31,$23
+bne $23,L.368
+lda $16,L.370
+jsr $26,printf
+ldgp $gp,0($26)
+br L.369
+L.368:
+lda $16,2
+lda $17,L.158
+jsr $26,BadCond
+ldgp $gp,0($26)
+lda $16,L.371
+ldt $f17,Y
+jsr $26,printf
+ldgp $gp,0($26)
+L.369:
+lda $27,80
+stl $27,Milestone
+ldt $f30,Half
+ldt $f29,MinSqEr
+addt $f29,$f30,$f29
+stt $f29,MinSqEr
+ldt $f29,MaxSqEr
+subt $f29,$f30,$f30
+stt $f30,MaxSqEr
+ldt $f30,One
+ldt $f29,U2
+addt $f30,$f29,$f16
+jsr $26,sqrt
+ldgp $gp,0($26)
+ldt $f29,One
+ldt $f28,U2
+subt $f0,$f29,$f30
+divt $f30,$f28,$f30
+stt $f30,Y
+ldt $f30,Y
+subt $f30,$f29,$f30
+ldt $f29,Eight
+divt $f28,$f29,$f29
+addt $f30,$f29,$f30
+stt $f30,SqEr
+ldt $f30,SqEr
+ldt $f29,MaxSqEr
+cmptle $f30,$f29,$f1
+fbne $f1,L.372
+ldt $f30,SqEr
+stt $f30,MaxSqEr
+L.372:
+ldt $f30,Y
+ldt $f29,U2
+ldt $f28,Eight
+divt $f29,$f28,$f29
+addt $f30,$f29,$f30
+stt $f30,SqEr
+ldt $f30,SqEr
+ldt $f29,MinSqEr
+cmptlt $f30,$f29,$f1
+fbeq $f1,L.374
+ldt $f30,SqEr
+stt $f30,MinSqEr
+L.374:
+ldt $f16,F9
+jsr $26,sqrt
+ldgp $gp,0($26)
+ldt $f29,U2
+ldt $f28,U1
+subt $f0,$f29,$f30
+ldt $f27,One
+subt $f27,$f29,$f29
+subt $f30,$f29,$f30
+divt $f30,$f28,$f30
+stt $f30,Y
+ldt $f30,Y
+ldt $f29,Eight
+divt $f28,$f29,$f29
+addt $f30,$f29,$f30
+stt $f30,SqEr
+ldt $f30,SqEr
+ldt $f29,MaxSqEr
+cmptle $f30,$f29,$f1
+fbne $f1,L.376
+ldt $f30,SqEr
+stt $f30,MaxSqEr
+L.376:
+ldt $f30,Y
+ldt $f29,One
+addt $f30,$f29,$f30
+ldt $f29,U1
+ldt $f28,Eight
+divt $f29,$f28,$f29
+addt $f30,$f29,$f30
+stt $f30,SqEr
+ldt $f30,SqEr
+ldt $f29,MinSqEr
+cmptlt $f30,$f29,$f1
+fbeq $f1,L.378
+ldt $f30,SqEr
+stt $f30,MinSqEr
+L.378:
+ldt $f30,U2
+stt $f30,OneUlp
+ldt $f30,OneUlp
+stt $f30,X
+lda $27,1
+stl $27,Indx
+L.380:
+ldt $f30,X
+ldt $f29,U1
+addt $f30,$f29,$f29
+addt $f29,$f30,$f30
+ldt $f29,F9
+addt $f30,$f29,$f16
+jsr $26,sqrt
+ldgp $gp,0($26)
+stt $f0,Y
+ldt $f30,U2
+ldt $f29,X
+ldt $f28,OneUlp
+ldt $f27,Y
+subt $f27,$f30,$f27
+ldt $f26,One
+subt $f26,$f30,$f30
+addt $f30,$f29,$f30
+subt $f27,$f30,$f30
+divt $f30,$f28,$f30
+stt $f30,Y
+ldt $f30,Half
+ldt $f27,U1
+subt $f27,$f29,$f27
+ldt $f26,F9
+addt $f27,$f26,$f27
+mult $f27,$f30,$f27
+mult $f27,$f29,$f27
+mult $f27,$f29,$f29
+divt $f29,$f28,$f29
+stt $f29,Z
+ldt $f29,Y
+addt $f29,$f30,$f30
+ldt $f29,Z
+addt $f30,$f29,$f30
+stt $f30,SqEr
+ldt $f30,SqEr
+ldt $f29,MinSqEr
+cmptlt $f30,$f29,$f1
+fbeq $f1,L.384
+ldt $f30,SqEr
+stt $f30,MinSqEr
+L.384:
+ldt $f30,Y
+ldt $f29,Half
+subt $f30,$f29,$f30
+ldt $f29,Z
+addt $f30,$f29,$f30
+stt $f30,SqEr
+ldt $f30,SqEr
+ldt $f29,MaxSqEr
+cmptle $f30,$f29,$f1
+fbne $f1,L.386
+ldt $f30,SqEr
+stt $f30,MaxSqEr
+L.386:
+ldl $27,Indx
+cmpeq $27,1,$23
+bne $23,L.390
+cmpeq $27,3,$23
+beq $23,L.388
+L.390:
+ldt $f16,X
+jsr $26,Sign
+ldgp $gp,0($26)
+fmov $f0,$f30
+stt $f30,-160+256($sp)
+ldt $f16,OneUlp
+jsr $26,sqrt
+ldgp $gp,0($26)
+ldt $f29,Eight
+ldt $f28,Nine
+mult $f28,$f0,$f30
+divt $f29,$f30,$f16
+jsr $26,floor
+ldgp $gp,0($26)
+ldt $f29,OneUlp
+ldt $f28,-160+256($sp)
+mult $f29,$f28,$f29
+mult $f29,$f0,$f30
+stt $f30,X
+br L.389
+L.388:
+ldt $f30,U1
+stt $f30,OneUlp
+ldt $f30,OneUlp
+negt $f30,$f30
+stt $f30,X
+L.389:
+L.381:
+ldl $27,Indx
+lda $27,1($27)
+stl $27,Indx
+ldl $27,Indx
+cmple $27,3,$23
+bne $23,L.380
+lda $27,85
+stl $27,Milestone
+stl $31,SqRWrng
+stl $31,Anomaly
+stl $31,RSqrt
+ldt $f30,Radix
+ldt $f29,One
+cmpteq $f30,$f29,$f1
+fbne $f1,L.391
+lda $16,L.393
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,Precision
+stt $f30,-160+256($sp)
+fmov $f30,$f16
+jsr $26,floor
+ldgp $gp,0($26)
+fmov $f0,$f30
+ldt $f16,Radix
+ldt $f29,One
+ldt $f28,-160+256($sp)
+addt $f29,$f28,$f29
+subt $f29,$f30,$f17
+jsr $26,pow
+ldgp $gp,0($26)
+fmov $f0,$f30
+ldt $f29,Half
+addt $f29,$f30,$f16
+jsr $26,floor
+ldgp $gp,0($26)
+stt $f0,D
+ldt $f30,D
+ldt $f29,Radix
+divt $f30,$f29,$f29
+stt $f29,X
+ldt $f29,A1
+divt $f30,$f29,$f30
+stt $f30,Y
+ldt $f30,X
+stt $f30,-168+256($sp)
+fmov $f30,$f16
+jsr $26,floor
+ldgp $gp,0($26)
+ldt $f29,-168+256($sp)
+cmpteq $f29,$f0,$f1
+fbeq $f1,L.396
+ldt $f30,Y
+stt $f30,-176+256($sp)
+fmov $f30,$f16
+jsr $26,floor
+ldgp $gp,0($26)
+ldt $f29,-176+256($sp)
+cmpteq $f29,$f0,$f1
+fbne $f1,L.394
+L.396:
+lda $27,1
+stl $27,Anomaly
+br L.395
+L.394:
+ldt $f30,Zero
+stt $f30,X
+ldt $f30,X
+stt $f30,Z2
+ldt $f30,One
+stt $f30,Y
+ldt $f29,Y
+stt $f29,Y2
+ldt $f29,Radix
+subt $f29,$f30,$f30
+stt $f30,Z1
+ldt $f30,Four
+ldt $f29,D
+mult $f30,$f29,$f30
+stt $f30,FourD
+L.397:
+ldt $f30,Y2
+ldt $f29,Z2
+cmptle $f30,$f29,$f1
+fbne $f1,L.400
+ldt $f30,Radix
+stt $f30,Q
+ldt $f30,Y
+stt $f30,Y1
+L.402:
+ldt $f30,Q
+stt $f30,-184+256($sp)
+ldt $f29,Half
+ldt $f28,Y1
+divt $f30,$f28,$f28
+subt $f29,$f28,$f16
+jsr $26,floor
+ldgp $gp,0($26)
+ldt $f29,Y1
+mult $f0,$f29,$f30
+ldt $f29,-184+256($sp)
+addt $f29,$f30,$f16
+jsr $26,fabs
+ldgp $gp,0($26)
+stt $f0,X1
+ldt $f30,Y1
+stt $f30,Q
+ldt $f30,X1
+stt $f30,Y1
+L.403:
+ldt $f30,X1
+ldt $f29,Zero
+cmptle $f30,$f29,$f1
+fbeq $f1,L.402
+ldt $f30,Q
+ldt $f29,One
+cmptle $f30,$f29,$f1
+fbeq $f1,L.405
+ldt $f30,Y2
+stt $f30,Z2
+ldt $f30,Y
+stt $f30,Z
+L.405:
+L.400:
+ldt $f30,Y
+ldt $f29,Two
+addt $f30,$f29,$f30
+stt $f30,Y
+ldt $f30,X
+ldt $f29,Eight
+addt $f30,$f29,$f30
+stt $f30,X
+ldt $f30,Y2
+ldt $f29,X
+addt $f30,$f29,$f30
+stt $f30,Y2
+ldt $f30,Y2
+ldt $f29,FourD
+cmptlt $f30,$f29,$f1
+fbne $f1,L.407
+ldt $f30,Y2
+ldt $f29,FourD
+subt $f30,$f29,$f30
+stt $f30,Y2
+L.407:
+L.398:
+ldt $f30,Y
+ldt $f29,D
+cmptlt $f30,$f29,$f1
+fbne $f1,L.397
+ldt $f30,FourD
+ldt $f29,Z2
+subt $f30,$f29,$f29
+stt $f29,X8
+ldt $f29,X8
+ldt $f28,Z
+mult $f28,$f28,$f28
+addt $f29,$f28,$f28
+divt $f28,$f30,$f30
+stt $f30,Q
+ldt $f30,Eight
+divt $f29,$f30,$f30
+stt $f30,X8
+ldt $f30,Q
+stt $f30,-184+256($sp)
+fmov $f30,$f16
+jsr $26,floor
+ldgp $gp,0($26)
+ldt $f29,-184+256($sp)
+cmpteq $f29,$f0,$f1
+fbne $f1,L.409
+lda $27,1
+stl $27,Anomaly
+br L.410
+L.409:
+stl $31,Break
+L.411:
+ldt $f30,Z1
+ldt $f29,Z
+mult $f30,$f29,$f30
+stt $f30,X
+ldt $f30,X
+stt $f30,-192+256($sp)
+ldt $f29,Radix
+divt $f30,$f29,$f16
+jsr $26,floor
+ldgp $gp,0($26)
+ldt $f29,Radix
+mult $f0,$f29,$f30
+ldt $f29,-192+256($sp)
+subt $f29,$f30,$f30
+stt $f30,X
+ldt $f30,X
+ldt $f29,One
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.414
+lda $27,1
+stl $27,Break
+br L.415
+L.414:
+ldt $f30,Z1
+ldt $f29,One
+subt $f30,$f29,$f30
+stt $f30,Z1
+L.415:
+L.412:
+ldl $27,Break
+cmpeq $27,$31,$23
+beq $23,L.416
+ldt $f30,Z1
+ldt $f29,Zero
+cmptle $f30,$f29,$f1
+fbeq $f1,L.411
+L.416:
+ldt $f30,Z1
+ldt $f29,Zero
+cmptle $f30,$f29,$f1
+fbeq $f1,L.417
+ldl $27,Break
+cmpeq $27,$31,$23
+beq $23,L.417
+lda $27,1
+stl $27,Anomaly
+br L.418
+L.417:
+ldt $f30,Z1
+ldt $f29,RadixD2
+cmptle $f30,$f29,$f1
+fbne $f1,L.419
+ldt $f30,Z1
+ldt $f29,Radix
+subt $f30,$f29,$f30
+stt $f30,Z1
+L.419:
+L.421:
+jsr $26,NewD
+ldgp $gp,0($26)
+L.422:
+ldt $f30,U2
+ldt $f29,D
+mult $f30,$f29,$f30
+ldt $f29,F9
+cmptlt $f30,$f29,$f1
+fbne $f1,L.421
+ldt $f30,D
+ldt $f29,Radix
+mult $f30,$f29,$f29
+subt $f29,$f30,$f29
+ldt $f28,W
+subt $f28,$f30,$f30
+cmpteq $f29,$f30,$f1
+fbne $f1,L.424
+lda $27,1
+stl $27,Anomaly
+br L.425
+L.424:
+ldt $f30,D
+stt $f30,Z2
+stl $31,I
+ldt $f29,Z
+ldt $f28,One
+addt $f28,$f29,$f28
+ldt $f27,Half
+mult $f28,$f27,$f28
+addt $f30,$f28,$f28
+stt $f28,Y
+addt $f30,$f29,$f30
+ldt $f29,Q
+addt $f30,$f29,$f30
+stt $f30,X
+jsr $26,SR3750
+ldgp $gp,0($26)
+ldt $f30,D
+ldt $f29,Z
+ldt $f28,One
+subt $f28,$f29,$f28
+ldt $f27,Half
+mult $f28,$f27,$f28
+addt $f30,$f28,$f28
+addt $f28,$f30,$f28
+stt $f28,Y
+subt $f30,$f29,$f29
+addt $f29,$f30,$f30
+stt $f30,X
+ldt $f30,X
+ldt $f29,Q
+addt $f30,$f29,$f29
+addt $f29,$f30,$f30
+stt $f30,X
+jsr $26,SR3750
+ldgp $gp,0($26)
+jsr $26,NewD
+ldgp $gp,0($26)
+ldt $f30,Z2
+ldt $f29,D
+subt $f29,$f30,$f29
+ldt $f28,W
+subt $f28,$f30,$f30
+cmpteq $f29,$f30,$f1
+fbne $f1,L.426
+lda $27,1
+stl $27,Anomaly
+br L.427
+L.426:
+ldt $f30,Z2
+ldt $f29,D
+subt $f29,$f30,$f29
+ldt $f28,Z
+ldt $f27,One
+subt $f27,$f28,$f27
+ldt $f26,Half
+mult $f27,$f26,$f27
+addt $f30,$f27,$f27
+addt $f29,$f27,$f27
+stt $f27,Y
+subt $f30,$f28,$f30
+ldt $f28,Q
+addt $f30,$f28,$f30
+addt $f29,$f30,$f30
+stt $f30,X
+jsr $26,SR3750
+ldgp $gp,0($26)
+ldt $f30,One
+ldt $f29,Z
+addt $f30,$f29,$f30
+ldt $f29,Half
+mult $f30,$f29,$f30
+stt $f30,Y
+ldt $f30,Q
+stt $f30,X
+jsr $26,SR3750
+ldgp $gp,0($26)
+ldl $27,I
+cmpeq $27,$31,$23
+beq $23,L.428
+lda $27,1
+stl $27,Anomaly
+L.428:
+L.427:
+L.425:
+L.418:
+L.410:
+L.395:
+ldl $25,I
+cmpeq $25,$31,$23
+bne $23,L.432
+ldl $25,Anomaly
+cmpeq $25,$31,$23
+bne $23,L.430
+L.432:
+mov $31,$16
+lda $17,L.433
+jsr $26,BadCond
+ldgp $gp,0($26)
+lda $16,L.434
+ldt $f17,W
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.435
+jsr $26,printf
+ldgp $gp,0($26)
+lda $27,1
+stl $27,SqRWrng
+L.430:
+L.391:
+ldl $27,Anomaly
+cmpeq $27,$31,$23
+beq $23,L.436
+ldt $f30,Zero
+ldt $f29,MinSqEr
+cmptlt $f29,$f30,$f1
+fbne $f1,L.438
+ldt $f29,MaxSqEr
+cmptle $f29,$f30,$f1
+fbeq $f1,L.438
+lda $27,1
+stl $27,RSqrt
+lda $16,L.440
+jsr $26,printf
+ldgp $gp,0($26)
+br L.439
+L.438:
+ldt $f30,U2
+ldt $f29,Half
+ldt $f28,MaxSqEr
+addt $f28,$f30,$f28
+subt $f30,$f29,$f30
+cmptle $f28,$f30,$f1
+fbeq $f1,L.444
+ldt $f30,MinSqEr
+cmptle $f30,$f29,$f1
+fbeq $f1,L.444
+ldt $f28,Radix
+addt $f30,$f28,$f30
+cmptlt $f30,$f29,$f1
+fbeq $f1,L.441
+L.444:
+lda $27,1
+stl $27,SqRWrng
+br L.442
+L.441:
+lda $27,2
+stl $27,RSqrt
+lda $16,L.445
+jsr $26,printf
+ldgp $gp,0($26)
+L.442:
+L.439:
+L.436:
+ldl $27,SqRWrng
+cmpeq $27,$31,$23
+bne $23,L.446
+lda $16,L.448
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.449
+ldt $f30,MinSqEr
+ldt $f29,Half
+subt $f30,$f29,$f17
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.450
+ldt $f30,Half
+ldt $f29,MaxSqEr
+addt $f30,$f29,$f17
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,1
+ldt $f30,Radix
+ldt $f29,MaxSqEr
+ldt $f28,MinSqEr
+subt $f29,$f28,$f29
+mult $f30,$f30,$f30
+cmptlt $f29,$f30,$f1
+fbeq $f1,L.453
+lda $27,1
+stl $27,-156+256($sp)
+br L.454
+L.453:
+stl $31,-156+256($sp)
+L.454:
+ldl $17,-156+256($sp)
+lda $18,L.452
+jsr $26,TstCond
+ldgp $gp,0($26)
+L.446:
+lda $27,90
+stl $27,Milestone
+jsr $26,Pause
+ldgp $gp,0($26)
+lda $16,L.455
+jsr $26,printf
+ldgp $gp,0($26)
+stl $31,N
+stl $31,I
+ldt $f30,Zero
+negt $f30,$f30
+stt $f30,Z
+lda $25,3
+stl $25,M
+stl $31,Break
+L.456:
+ldt $f30,One
+stt $f30,X
+jsr $26,SR3980
+ldgp $gp,0($26)
+ldl $27,I
+cmple $27,10,$23
+beq $23,L.459
+lda $27,1023
+stl $27,I
+jsr $26,SR3980
+ldgp $gp,0($26)
+L.459:
+ldt $f30,Z
+ldt $f29,MinusOne
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.461
+lda $27,1
+stl $27,Break
+br L.462
+L.461:
+ldt $f30,MinusOne
+stt $f30,Z
+jsr $26,PrintIfNPositive
+ldgp $gp,0($26)
+stl $31,N
+lda $27,-4
+stl $27,I
+L.462:
+L.457:
+ldl $27,Break
+cmpeq $27,$31,$23
+bne $23,L.456
+jsr $26,PrintIfNPositive
+ldgp $gp,0($26)
+ldl $27,N
+stl $27,N1
+stl $31,N
+ldt $f30,A1
+stt $f30,Z
+ldt $f16,W
+jsr $26,log
+ldgp $gp,0($26)
+fmov $f0,$f30
+stt $f30,-160+256($sp)
+ldt $f16,A1
+jsr $26,log
+ldgp $gp,0($26)
+fmov $f0,$f30
+ldt $f29,Two
+ldt $f28,-160+256($sp)
+mult $f29,$f28,$f29
+divt $f29,$f30,$f16
+jsr $26,floor
+ldgp $gp,0($26)
+cvttqc $f0,$f1
+cvtql $f1,$f1
+sts $f1,-56+256($sp)
+ldl $27,-56+256($sp)
+stl $27,M
+stl $31,Break
+L.463:
+ldt $f30,Z
+stt $f30,X
+lda $27,1
+stl $27,I
+jsr $26,SR3980
+ldgp $gp,0($26)
+ldt $f30,Z
+ldt $f29,AInvrse
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.466
+lda $27,1
+stl $27,Break
+br L.467
+L.466:
+ldt $f30,AInvrse
+stt $f30,Z
+L.467:
+L.464:
+ldl $27,Break
+cmpeq $27,$31,$23
+bne $23,L.463
+lda $27,100
+stl $27,Milestone
+ldl $27,NoTrials
+stl $27,M
+ldt $f30,Three
+stt $f30,Z
+L.468:
+ldt $f30,Z
+stt $f30,X
+lda $27,1
+stl $27,I
+jsr $26,SR3980
+ldgp $gp,0($26)
+L.471:
+ldt $f30,Z
+ldt $f29,Two
+addt $f30,$f29,$f30
+stt $f30,Z
+L.472:
+ldt $f30,Three
+stt $f30,-168+256($sp)
+ldt $f29,Z
+divt $f29,$f30,$f16
+jsr $26,floor
+ldgp $gp,0($26)
+ldt $f29,-168+256($sp)
+mult $f29,$f0,$f30
+ldt $f29,Z
+cmpteq $f30,$f29,$f1
+fbne $f1,L.471
+L.469:
+ldt $f30,Z
+ldt $f29,Eight
+ldt $f28,Three
+mult $f29,$f28,$f29
+cmptlt $f30,$f29,$f1
+fbne $f1,L.468
+ldl $27,N
+cmple $27,$31,$23
+bne $23,L.474
+lda $16,L.476
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.477
+jsr $26,printf
+ldgp $gp,0($26)
+L.474:
+jsr $26,PrintIfNPositive
+ldgp $gp,0($26)
+ldl $27,N
+ldl $25,N1
+addl $27,$25,$27
+stl $27,N
+ldl $27,N
+cmpeq $27,$31,$23
+beq $23,L.478
+lda $16,L.480
+jsr $26,printf
+ldgp $gp,0($26)
+L.478:
+ldl $27,N
+cmple $27,$31,$23
+bne $23,L.481
+jsr $26,Pause
+ldgp $gp,0($26)
+br L.482
+L.481:
+lda $16,L.45
+jsr $26,printf
+ldgp $gp,0($26)
+L.482:
+lda $27,110
+stl $27,Milestone
+lda $16,L.483
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,U1
+stt $f30,D
+ldt $f30,Precision
+stt $f30,-168+256($sp)
+fmov $f30,$f16
+jsr $26,floor
+ldgp $gp,0($26)
+ldt $f29,-168+256($sp)
+cmpteq $f29,$f0,$f1
+fbne $f1,L.484
+ldt $f30,BInvrse
+stt $f30,D
+ldt $f30,Precision
+stt $f30,X
+L.486:
+ldt $f30,D
+ldt $f29,BInvrse
+mult $f30,$f29,$f30
+stt $f30,D
+ldt $f30,X
+ldt $f29,One
+subt $f30,$f29,$f30
+stt $f30,X
+L.487:
+ldt $f30,X
+ldt $f29,Zero
+cmptle $f30,$f29,$f1
+fbeq $f1,L.486
+L.484:
+ldt $f30,One
+stt $f30,Y
+ldt $f30,D
+stt $f30,Z
+L.489:
+ldt $f30,Y
+stt $f30,C
+ldt $f30,Z
+stt $f30,Y
+ldt $f30,Y
+mult $f30,$f30,$f30
+stt $f30,Z
+L.490:
+ldt $f30,Z
+ldt $f29,Y
+cmptle $f29,$f30,$f1
+fbne $f1,L.492
+addt $f30,$f30,$f29
+cmptle $f29,$f30,$f1
+fbeq $f1,L.489
+L.492:
+ldt $f30,C
+stt $f30,Y
+ldt $f30,Y
+ldt $f29,D
+mult $f30,$f29,$f30
+stt $f30,Z
+L.493:
+ldt $f30,Y
+stt $f30,C
+ldt $f30,Z
+stt $f30,Y
+ldt $f30,Y
+ldt $f29,D
+mult $f30,$f29,$f30
+stt $f30,Z
+L.494:
+ldt $f30,Z
+ldt $f29,Y
+cmptle $f29,$f30,$f1
+fbne $f1,L.496
+addt $f30,$f30,$f29
+cmptle $f29,$f30,$f1
+fbeq $f1,L.493
+L.496:
+ldt $f30,Radix
+ldt $f29,Two
+cmptlt $f30,$f29,$f1
+fbeq $f1,L.497
+ldt $f30,Two
+stt $f30,HInvrse
+br L.498
+L.497:
+ldt $f30,Radix
+stt $f30,HInvrse
+L.498:
+ldt $f30,One
+ldt $f29,HInvrse
+divt $f30,$f29,$f29
+stt $f29,H
+ldt $f29,C
+divt $f30,$f29,$f30
+stt $f30,CInvrse
+stt $f29,E0
+ldt $f30,E0
+ldt $f29,H
+mult $f30,$f29,$f30
+stt $f30,Z
+L.499:
+ldt $f30,E0
+stt $f30,Y
+ldt $f30,Z
+stt $f30,E0
+ldt $f30,E0
+ldt $f29,H
+mult $f30,$f29,$f30
+stt $f30,Z
+L.500:
+ldt $f30,Z
+ldt $f29,E0
+cmptle $f29,$f30,$f1
+fbne $f1,L.502
+addt $f30,$f30,$f29
+cmptle $f29,$f30,$f1
+fbeq $f1,L.499
+L.502:
+ldt $f30,E0
+stt $f30,UfThold
+ldt $f30,Zero
+stt $f30,E1
+stt $f30,Q
+ldt $f30,U2
+stt $f30,E9
+ldt $f30,One
+ldt $f29,E9
+addt $f30,$f29,$f30
+stt $f30,S
+ldt $f30,C
+ldt $f29,S
+mult $f30,$f29,$f29
+stt $f29,D
+ldt $f29,D
+cmptle $f29,$f30,$f1
+fbeq $f1,L.503
+ldt $f30,Radix
+ldt $f29,U2
+mult $f30,$f29,$f30
+stt $f30,E9
+ldt $f30,One
+ldt $f29,E9
+addt $f30,$f29,$f30
+stt $f30,S
+ldt $f30,C
+ldt $f29,S
+mult $f30,$f29,$f29
+stt $f29,D
+ldt $f29,D
+cmptle $f29,$f30,$f1
+fbeq $f1,L.504
+mov $31,$16
+lda $17,L.507
+jsr $26,BadCond
+ldgp $gp,0($26)
+ldt $f30,E0
+stt $f30,Underflow
+ldt $f30,Zero
+stt $f30,Y1
+ldt $f30,Z
+stt $f30,PseudoZero
+jsr $26,Pause
+ldgp $gp,0($26)
+br L.504
+L.503:
+ldt $f30,D
+stt $f30,Underflow
+ldt $f30,Underflow
+ldt $f29,H
+mult $f30,$f29,$f30
+stt $f30,PseudoZero
+ldt $f30,Zero
+stt $f30,UfThold
+L.508:
+ldt $f30,Underflow
+stt $f30,Y1
+ldt $f30,PseudoZero
+stt $f30,Underflow
+ldt $f30,E1
+addt $f30,$f30,$f29
+cmptle $f29,$f30,$f1
+fbeq $f1,L.511
+ldt $f30,Underflow
+ldt $f29,HInvrse
+mult $f30,$f29,$f30
+stt $f30,Y2
+ldt $f30,Y1
+ldt $f29,Y2
+subt $f30,$f29,$f16
+jsr $26,fabs
+ldgp $gp,0($26)
+stt $f0,E1
+ldt $f30,Y1
+stt $f30,Q
+ldt $f30,UfThold
+ldt $f29,Zero
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.513
+ldt $f30,Y1
+ldt $f29,Y2
+cmpteq $f30,$f29,$f1
+fbne $f1,L.513
+ldt $f30,Y1
+stt $f30,UfThold
+L.513:
+L.511:
+ldt $f30,PseudoZero
+ldt $f29,H
+mult $f30,$f29,$f30
+stt $f30,PseudoZero
+L.509:
+ldt $f30,PseudoZero
+ldt $f29,Underflow
+cmptle $f29,$f30,$f1
+fbne $f1,L.515
+addt $f30,$f30,$f29
+cmptle $f29,$f30,$f1
+fbeq $f1,L.508
+L.515:
+L.504:
+ldt $f30,PseudoZero
+ldt $f29,Zero
+cmpteq $f30,$f29,$f1
+fbne $f1,L.516
+lda $16,L.45
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,PseudoZero
+stt $f30,Z
+ldt $f29,Zero
+cmptle $f30,$f29,$f1
+fbeq $f1,L.518
+mov $31,$16
+lda $17,L.520
+jsr $26,BadCond
+ldgp $gp,0($26)
+lda $16,L.521
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.522
+ldt $f17,PseudoZero
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,PseudoZero
+negt $f30,$f30
+stt $f30,X
+ldt $f30,X
+ldt $f29,Zero
+cmptle $f30,$f29,$f1
+fbeq $f1,L.519
+lda $16,L.525
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.526
+ldt $f17,X
+jsr $26,printf
+ldgp $gp,0($26)
+br L.519
+L.518:
+lda $16,3
+lda $17,L.527
+jsr $26,BadCond
+ldgp $gp,0($26)
+lda $16,L.528
+ldt $f17,PseudoZero
+jsr $26,printf
+ldgp $gp,0($26)
+L.519:
+jsr $26,TstPtUf
+ldgp $gp,0($26)
+L.516:
+lda $27,120
+stl $27,Milestone
+ldt $f30,CInvrse
+ldt $f29,Y
+mult $f30,$f29,$f29
+ldt $f28,Y1
+mult $f30,$f28,$f30
+cmptle $f29,$f30,$f1
+fbne $f1,L.529
+ldt $f30,H
+ldt $f29,S
+mult $f30,$f29,$f30
+stt $f30,S
+ldt $f30,Underflow
+stt $f30,E0
+L.529:
+ldt $f30,E1
+ldt $f29,Zero
+cmpteq $f30,$f29,$f1
+fbne $f1,L.531
+ldt $f29,E0
+cmpteq $f30,$f29,$f1
+fbne $f1,L.531
+lda $16,2
+lda $17,L.158
+jsr $26,BadCond
+ldgp $gp,0($26)
+ldt $f30,E1
+ldt $f29,E0
+cmptlt $f30,$f29,$f1
+fbeq $f1,L.533
+lda $16,L.535
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.536
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,PseudoZero
+ldt $f29,Zero
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.534
+ldt $f30,E1
+stt $f30,E0
+br L.534
+L.533:
+lda $16,L.539
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.540
+jsr $26,printf
+ldgp $gp,0($26)
+L.534:
+L.531:
+lda $16,L.541
+ldt $f17,E0
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,E0
+stt $f30,Z
+jsr $26,TstPtUf
+ldgp $gp,0($26)
+ldt $f30,E0
+stt $f30,Underflow
+ldl $27,N
+cmpeq $27,1,$23
+beq $23,L.542
+ldt $f30,Y
+stt $f30,Underflow
+L.542:
+lda $27,4
+stl $27,I
+ldt $f30,E1
+ldt $f29,Zero
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.544
+lda $27,3
+stl $27,I
+L.544:
+ldt $f30,UfThold
+ldt $f29,Zero
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.546
+ldl $27,I
+subl $27,2,$27
+stl $27,I
+L.546:
+lda $27,1
+stl $27,UfNGrad
+ldl $27,I
+cmplt $27,1,$23
+bne $23,L.548
+cmple $27,4,$23
+beq $23,L.548
+subl $27,1,$27
+sll $27,3,$27
+ldq $27,L.571($27)
+jmp ($27)
+.rdata
+.align 3
+L.571:
+.quad L.550
+.quad L.557
+.quad L.562
+.quad L.563
+.text
+L.550:
+ldt $f30,Underflow
+stt $f30,UfThold
+ldt $f30,CInvrse
+ldt $f29,Q
+mult $f30,$f29,$f29
+ldt $f28,Y
+mult $f30,$f28,$f30
+ldt $f28,S
+mult $f30,$f28,$f30
+cmpteq $f29,$f30,$f1
+fbne $f1,L.551
+ldt $f30,Y
+stt $f30,UfThold
+mov $31,$16
+lda $17,L.553
+jsr $26,BadCond
+ldgp $gp,0($26)
+lda $16,L.554
+ldt $f17,UfThold
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.555
+ldt $f17,C
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.556
+jsr $26,printf
+ldgp $gp,0($26)
+L.551:
+jsr $26,Pause
+ldgp $gp,0($26)
+br L.549
+L.557:
+mov $31,$16
+lda $17,L.558
+jsr $26,BadCond
+ldgp $gp,0($26)
+lda $16,L.559
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.560
+ldt $f17,Q
+ldt $f18,Y2
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,Q
+ldt $f29,Y2
+subt $f30,$f29,$f16
+jsr $26,fabs
+ldgp $gp,0($26)
+fmov $f0,$f30
+lda $16,L.561
+fmov $f30,$f17
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,Q
+stt $f30,UfThold
+br L.549
+L.562:
+ldt $f30,X
+stt $f30,X
+br L.549
+L.563:
+ldt $f30,UfThold
+ldt $f29,Q
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.564
+ldt $f29,E1
+ldt $f28,E0
+cmpteq $f29,$f28,$f1
+fbeq $f1,L.564
+ldt $f28,E9
+divt $f29,$f28,$f29
+subt $f30,$f29,$f16
+jsr $26,fabs
+ldgp $gp,0($26)
+ldt $f29,E1
+cmptle $f0,$f29,$f1
+fbeq $f1,L.564
+stl $31,UfNGrad
+lda $16,L.566
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.567
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,E0
+ldt $f29,CInvrse
+mult $f30,$f29,$f28
+stt $f28,Y
+ldt $f28,U2
+ldt $f27,Y
+ldt $f26,OneAndHalf
+addt $f26,$f28,$f26
+mult $f27,$f26,$f27
+stt $f27,Y
+ldt $f27,One
+addt $f27,$f28,$f28
+mult $f29,$f28,$f29
+stt $f29,X
+ldt $f29,Y
+ldt $f28,X
+divt $f29,$f28,$f29
+stt $f29,Y
+ldt $f29,Y
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.569
+lda $27,1
+stl $27,-172+256($sp)
+br L.570
+L.569:
+stl $31,-172+256($sp)
+L.570:
+ldl $27,-172+256($sp)
+stl $27,IEEE
+L.564:
+L.548:
+L.549:
+ldl $27,UfNGrad
+cmpeq $27,$31,$23
+bne $23,L.572
+lda $16,L.45
+jsr $26,printf
+ldgp $gp,0($26)
+lda $27,sigfpe
+stq $27,sigsave
+lda $16,ovfl_buf
+jsr $26,setjmp
+ldgp $gp,0($26)
+cmpeq $0,$31,$23
+bne $23,L.574
+lda $16,L.576
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,H
+addt $f30,$f30,$f30
+stt $f30,R
+br L.575
+L.574:
+ldt $f30,Underflow
+ldt $f29,UfThold
+divt $f30,$f29,$f16
+jsr $26,sqrt
+ldgp $gp,0($26)
+stt $f0,R
+L.575:
+stq $31,sigsave
+ldt $f30,R
+ldt $f29,H
+cmptle $f30,$f29,$f1
+fbeq $f1,L.577
+ldt $f30,R
+ldt $f29,UfThold
+mult $f30,$f29,$f29
+stt $f29,Z
+ldt $f29,One
+ldt $f28,H
+ldt $f27,Z
+mult $f30,$f28,$f30
+addt $f29,$f28,$f28
+mult $f30,$f28,$f30
+addt $f29,$f30,$f30
+mult $f27,$f30,$f30
+stt $f30,X
+br L.578
+L.577:
+ldt $f30,UfThold
+stt $f30,Z
+ldt $f30,One
+ldt $f29,H
+ldt $f28,Z
+mult $f29,$f29,$f27
+addt $f30,$f29,$f29
+mult $f27,$f29,$f29
+addt $f30,$f29,$f30
+mult $f28,$f30,$f30
+stt $f30,X
+L.578:
+ldt $f30,X
+ldt $f29,Z
+cmpteq $f30,$f29,$f1
+fbne $f1,L.579
+subt $f30,$f29,$f30
+ldt $f29,Zero
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.579
+lda $16,3
+lda $17,L.158
+jsr $26,BadCond
+ldgp $gp,0($26)
+lda $16,L.581
+ldt $f17,X
+ldt $f18,Z
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,X
+ldt $f29,Z
+subt $f30,$f29,$f30
+stt $f30,Z9
+lda $16,L.582
+ldt $f17,Z9
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.583
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.584
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.585
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.586
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.587
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.588
+jsr $26,printf
+ldgp $gp,0($26)
+lda $27,sigfpe
+stq $27,sigsave
+lda $16,ovfl_buf
+jsr $26,setjmp
+ldgp $gp,0($26)
+cmpeq $0,$31,$23
+bne $23,L.589
+lda $16,L.591
+jsr $26,printf
+ldgp $gp,0($26)
+br L.590
+L.589:
+lda $16,L.592
+ldt $f30,Half
+ldt $f29,X
+ldt $f28,Z
+divt $f29,$f28,$f29
+subt $f29,$f30,$f29
+subt $f29,$f30,$f17
+jsr $26,printf
+ldgp $gp,0($26)
+L.590:
+stq $31,sigsave
+L.579:
+L.572:
+lda $16,L.593
+ldt $f17,UfThold
+lda $18,L.594
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.595
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.596
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,U1
+mult $f30,$f30,$f29
+stt $f29,Y2
+ldt $f29,Y2
+mult $f29,$f29,$f29
+stt $f29,Y
+ldt $f29,Y
+mult $f29,$f30,$f30
+stt $f30,Y2
+ldt $f30,Y2
+ldt $f29,UfThold
+cmptle $f30,$f29,$f1
+fbeq $f1,L.597
+ldt $f30,Y
+ldt $f29,E0
+cmptle $f30,$f29,$f1
+fbne $f1,L.599
+lda $16,2
+lda $17,L.158
+jsr $26,BadCond
+ldgp $gp,0($26)
+lda $27,5
+stl $27,I
+br L.600
+L.599:
+lda $16,1
+lda $17,L.158
+jsr $26,BadCond
+ldgp $gp,0($26)
+lda $27,4
+stl $27,I
+L.600:
+lda $16,L.601
+ldl $17,I
+jsr $26,printf
+ldgp $gp,0($26)
+L.597:
+lda $27,130
+stl $27,Milestone
+ldt $f16,UfThold
+jsr $26,log
+ldgp $gp,0($26)
+fmov $f0,$f30
+stt $f30,-176+256($sp)
+ldt $f16,HInvrse
+jsr $26,log
+ldgp $gp,0($26)
+ldt $f29,Half
+ldt $f28,TwoForty
+ldt $f27,-176+256($sp)
+mult $f28,$f27,$f28
+divt $f28,$f0,$f30
+subt $f29,$f30,$f16
+jsr $26,floor
+ldgp $gp,0($26)
+negt $f0,$f30
+ldt $f29,TwoForty
+divt $f30,$f29,$f30
+stt $f30,Y
+ldt $f30,Y
+addt $f30,$f30,$f30
+stt $f30,Y2
+lda $16,L.602
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.603
+ldt $f17,HInvrse
+ldt $f18,Y
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.604
+ldt $f17,HInvrse
+ldt $f18,Y
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f16,HInvrse
+ldt $f17,Y2
+jsr $26,pow
+ldgp $gp,0($26)
+stt $f0,V9
+lda $16,L.605
+ldt $f17,V9
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,V9
+ldt $f29,Zero
+cmptlt $f30,$f29,$f1
+fbne $f1,L.608
+ldt $f29,Radix
+addt $f29,$f29,$f29
+ldt $f28,E9
+addt $f29,$f28,$f29
+ldt $f28,UfThold
+mult $f29,$f28,$f29
+cmptle $f30,$f29,$f1
+fbne $f1,L.606
+L.608:
+lda $16,1
+lda $17,L.609
+jsr $26,BadCond
+ldgp $gp,0($26)
+lda $16,L.610
+ldt $f17,UfThold
+jsr $26,printf
+ldgp $gp,0($26)
+br L.607
+L.606:
+ldt $f30,V9
+ldt $f29,UfThold
+ldt $f28,One
+ldt $f27,E9
+addt $f28,$f27,$f28
+mult $f29,$f28,$f29
+cmptle $f30,$f29,$f1
+fbeq $f1,L.611
+lda $16,L.613
+jsr $26,printf
+ldgp $gp,0($26)
+br L.612
+L.611:
+lda $16,2
+lda $17,L.609
+jsr $26,BadCond
+ldgp $gp,0($26)
+lda $16,L.610
+ldt $f17,UfThold
+jsr $26,printf
+ldgp $gp,0($26)
+L.612:
+L.607:
+lda $27,140
+stl $27,Milestone
+lda $16,L.45
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,Zero
+stt $f30,X
+lda $27,2
+stl $27,I
+ldt $f29,Two
+ldt $f28,Three
+mult $f29,$f28,$f29
+stt $f29,Y
+stt $f30,Q
+stl $31,N
+L.614:
+ldt $f30,X
+stt $f30,Z
+ldl $27,I
+lda $27,1($27)
+stl $27,I
+ldl $27,I
+ldt $f30,Y
+addl $27,$27,$27
+stq $27,-56+256($sp)
+ldt $f29,-56+256($sp)
+cvtqt $f29,$f29
+divt $f30,$f29,$f30
+stt $f30,Y
+ldt $f30,Y
+ldt $f29,Q
+addt $f30,$f29,$f30
+stt $f30,R
+ldt $f30,Z
+ldt $f29,R
+addt $f30,$f29,$f28
+stt $f28,X
+ldt $f28,X
+subt $f30,$f28,$f30
+addt $f30,$f29,$f30
+stt $f30,Q
+L.615:
+ldt $f30,X
+ldt $f29,Z
+cmptle $f30,$f29,$f1
+fbeq $f1,L.614
+ldt $f30,OneAndHalf
+ldt $f29,One
+ldt $f28,Eight
+divt $f29,$f28,$f29
+addt $f30,$f29,$f29
+ldt $f28,X
+ldt $f27,ThirtyTwo
+mult $f30,$f27,$f30
+divt $f28,$f30,$f30
+addt $f29,$f30,$f30
+stt $f30,Z
+ldt $f30,Z
+mult $f30,$f30,$f30
+stt $f30,X
+ldt $f30,X
+mult $f30,$f30,$f30
+stt $f30,Exp2
+ldt $f30,F9
+stt $f30,X
+ldt $f30,X
+ldt $f29,U1
+subt $f30,$f29,$f30
+stt $f30,Y
+lda $16,L.617
+ldt $f17,Exp2
+jsr $26,printf
+ldgp $gp,0($26)
+lda $27,1
+stl $27,I
+L.618:
+ldt $f30,X
+ldt $f29,BInvrse
+subt $f30,$f29,$f28
+stt $f28,Z
+ldt $f28,One
+addt $f30,$f28,$f27
+ldt $f26,Z
+subt $f28,$f29,$f29
+subt $f26,$f29,$f29
+divt $f27,$f29,$f29
+stt $f29,Z
+fmov $f30,$f16
+ldt $f17,Z
+jsr $26,pow
+ldgp $gp,0($26)
+ldt $f29,Exp2
+subt $f0,$f29,$f30
+stt $f30,Q
+ldt $f16,Q
+jsr $26,fabs
+ldgp $gp,0($26)
+ldt $f29,TwoForty
+ldt $f28,U2
+mult $f29,$f28,$f29
+cmptle $f0,$f29,$f1
+fbne $f1,L.622
+lda $27,1
+stl $27,N
+ldt $f30,BInvrse
+ldt $f29,X
+subt $f29,$f30,$f29
+ldt $f28,One
+subt $f28,$f30,$f30
+subt $f29,$f30,$f30
+stt $f30,V9
+lda $16,2
+lda $17,L.624
+jsr $26,BadCond
+ldgp $gp,0($26)
+ldt $f16,X
+ldt $f17,Z
+jsr $26,pow
+ldgp $gp,0($26)
+fmov $f0,$f30
+lda $16,L.625
+fmov $f30,$f17
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.626
+ldt $f17,V9
+ldt $f18,Z
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.627
+ldt $f17,Q
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.628
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.629
+jsr $26,printf
+ldgp $gp,0($26)
+br L.620
+L.622:
+ldt $f30,Y
+ldt $f29,X
+subt $f30,$f29,$f29
+ldt $f28,Two
+mult $f29,$f28,$f29
+addt $f29,$f30,$f29
+stt $f29,Z
+stt $f30,X
+ldt $f30,Z
+stt $f30,Y
+ldt $f30,X
+ldt $f29,F9
+subt $f30,$f29,$f30
+ldt $f29,One
+mult $f30,$f30,$f30
+addt $f29,$f30,$f30
+stt $f30,Z
+ldt $f30,Z
+ldt $f29,One
+cmptle $f30,$f29,$f1
+fbne $f1,L.630
+ldl $27,I
+ldl $25,NoTrials
+cmplt $27,$25,$23
+beq $23,L.630
+ldl $27,I
+lda $27,1($27)
+stl $27,I
+br L.618
+L.630:
+ldt $f30,X
+ldt $f29,One
+cmptle $f30,$f29,$f1
+fbne $f1,L.632
+ldl $27,N
+cmpeq $27,$31,$23
+beq $23,L.620
+lda $16,L.636
+jsr $26,printf
+ldgp $gp,0($26)
+br L.620
+L.632:
+ldt $f30,U2
+ldt $f29,One
+addt $f29,$f30,$f29
+stt $f29,X
+addt $f30,$f30,$f30
+stt $f30,Y
+ldt $f30,Y
+ldt $f29,X
+addt $f30,$f29,$f30
+stt $f30,Y
+lda $27,1
+stl $27,I
+br L.618
+L.620:
+lda $27,150
+stl $27,Milestone
+lda $16,L.637
+jsr $26,printf
+ldgp $gp,0($26)
+stl $31,N
+ldt $f30,A1
+stt $f30,Z
+ldt $f16,C
+jsr $26,log
+ldgp $gp,0($26)
+fmov $f0,$f30
+stt $f30,-184+256($sp)
+ldt $f16,A1
+jsr $26,log
+ldgp $gp,0($26)
+ldt $f29,Half
+ldt $f28,-184+256($sp)
+divt $f28,$f0,$f30
+subt $f29,$f30,$f16
+jsr $26,floor
+ldgp $gp,0($26)
+stt $f0,Q
+stl $31,Break
+L.638:
+ldt $f30,CInvrse
+stt $f30,X
+ldt $f16,Z
+ldt $f17,Q
+jsr $26,pow
+ldgp $gp,0($26)
+stt $f0,Y
+jsr $26,IsYeqX
+ldgp $gp,0($26)
+ldt $f30,Q
+negt $f30,$f30
+stt $f30,Q
+ldt $f30,C
+stt $f30,X
+ldt $f16,Z
+ldt $f17,Q
+jsr $26,pow
+ldgp $gp,0($26)
+stt $f0,Y
+jsr $26,IsYeqX
+ldgp $gp,0($26)
+ldt $f30,Z
+ldt $f29,One
+cmptlt $f30,$f29,$f1
+fbeq $f1,L.641
+lda $27,1
+stl $27,Break
+br L.642
+L.641:
+ldt $f30,AInvrse
+stt $f30,Z
+L.642:
+L.639:
+ldl $27,Break
+cmpeq $27,$31,$23
+bne $23,L.638
+jsr $26,PrintIfNPositive
+ldgp $gp,0($26)
+ldl $27,N
+cmpeq $27,$31,$23
+beq $23,L.643
+lda $16,L.645
+jsr $26,printf
+ldgp $gp,0($26)
+L.643:
+lda $16,L.45
+jsr $26,printf
+ldgp $gp,0($26)
+lda $27,160
+stl $27,Milestone
+jsr $26,Pause
+ldgp $gp,0($26)
+lda $16,L.646
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.647
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,CInvrse
+negt $f30,$f30
+stt $f30,Y
+ldt $f30,HInvrse
+ldt $f29,Y
+mult $f30,$f29,$f30
+stt $f30,V9
+lda $27,sigfpe
+stq $27,sigsave
+lda $16,ovfl_buf
+jsr $26,setjmp
+ldgp $gp,0($26)
+cmpeq $0,$31,$23
+bne $23,L.648
+stl $31,I
+ldt $f30,Y
+stt $f30,V9
+br L.650
+L.648:
+L.651:
+ldt $f30,Y
+stt $f30,V
+ldt $f30,V9
+stt $f30,Y
+ldt $f30,HInvrse
+ldt $f29,Y
+mult $f30,$f29,$f30
+stt $f30,V9
+L.652:
+ldt $f30,V9
+ldt $f29,Y
+cmptlt $f30,$f29,$f1
+fbne $f1,L.651
+lda $27,1
+stl $27,I
+L.650:
+stq $31,sigsave
+ldt $f30,V9
+stt $f30,Z
+lda $16,L.654
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.655
+ldt $f17,Y
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,Y
+negt $f30,$f29
+stt $f29,V9
+ldt $f29,V9
+stt $f29,V0
+ldt $f29,V
+subt $f29,$f30,$f30
+ldt $f28,V0
+addt $f29,$f28,$f29
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.656
+lda $16,L.658
+jsr $26,printf
+ldgp $gp,0($26)
+br L.657
+L.656:
+lda $16,L.659
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,3
+lda $17,L.660
+jsr $26,BadCond
+ldgp $gp,0($26)
+L.657:
+ldt $f30,Z
+ldt $f29,Y
+cmpteq $f30,$f29,$f1
+fbne $f1,L.661
+lda $16,1
+lda $17,L.158
+jsr $26,BadCond
+ldgp $gp,0($26)
+lda $16,L.663
+ldt $f17,Y
+ldt $f18,Z
+jsr $26,printf
+ldgp $gp,0($26)
+L.661:
+ldl $27,I
+cmpeq $27,$31,$23
+bne $23,L.664
+ldt $f30,V
+ldt $f29,HInvrse
+ldt $f28,U2
+mult $f29,$f28,$f27
+subt $f27,$f29,$f27
+mult $f30,$f27,$f27
+stt $f27,Y
+ldt $f27,Y
+ldt $f26,One
+subt $f26,$f29,$f29
+mult $f29,$f28,$f29
+mult $f29,$f30,$f30
+addt $f27,$f30,$f30
+stt $f30,Z
+ldt $f30,Z
+ldt $f29,V0
+cmptlt $f30,$f29,$f1
+fbeq $f1,L.666
+ldt $f30,Z
+stt $f30,Y
+L.666:
+ldt $f30,Y
+ldt $f29,V0
+cmptlt $f30,$f29,$f1
+fbeq $f1,L.668
+ldt $f30,Y
+stt $f30,V
+L.668:
+ldt $f30,V0
+ldt $f29,V
+subt $f30,$f29,$f29
+cmptlt $f29,$f30,$f1
+fbeq $f1,L.665
+ldt $f30,V0
+stt $f30,V
+br L.665
+L.664:
+ldt $f30,Y
+ldt $f29,HInvrse
+ldt $f28,U2
+mult $f29,$f28,$f27
+subt $f27,$f29,$f27
+mult $f30,$f27,$f27
+stt $f27,V
+ldt $f27,V
+ldt $f26,One
+subt $f26,$f29,$f29
+mult $f29,$f28,$f29
+mult $f29,$f30,$f30
+addt $f27,$f30,$f30
+stt $f30,V
+L.665:
+lda $16,L.672
+ldt $f17,V
+jsr $26,printf
+ldgp $gp,0($26)
+ldl $27,I
+cmpeq $27,$31,$23
+bne $23,L.673
+lda $16,L.675
+ldt $f17,V0
+jsr $26,printf
+ldgp $gp,0($26)
+br L.674
+L.673:
+lda $16,L.676
+jsr $26,printf
+ldgp $gp,0($26)
+L.674:
+ldt $f30,V
+ldt $f29,One
+mult $f30,$f29,$f30
+stt $f30,V9
+lda $16,L.677
+ldt $f17,V9
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,V
+ldt $f29,One
+divt $f30,$f29,$f30
+stt $f30,V9
+lda $16,L.678
+ldt $f17,V9
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.679
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.680
+jsr $26,printf
+ldgp $gp,0($26)
+lda $27,170
+stl $27,Milestone
+ldt $f30,V
+negt $f30,$f29
+cmptlt $f29,$f30,$f1
+fbeq $f1,L.685
+ldt $f29,V0
+negt $f29,$f28
+cmptlt $f28,$f29,$f1
+fbeq $f1,L.685
+ldt $f29,UfThold
+negt $f29,$f28
+cmptlt $f28,$f30,$f1
+fbeq $f1,L.685
+cmptlt $f29,$f30,$f1
+fbne $f1,L.681
+L.685:
+mov $31,$16
+lda $17,L.686
+jsr $26,BadCond
+ldgp $gp,0($26)
+lda $16,L.687
+ldt $f17,V
+ldt $f18,V0
+ldt $f19,UfThold
+jsr $26,printf
+ldgp $gp,0($26)
+L.681:
+lda $27,175
+stl $27,Milestone
+lda $16,L.45
+jsr $26,printf
+ldgp $gp,0($26)
+lda $27,1
+stl $27,Indx
+L.688:
+ldl $27,Indx
+cmpeq $27,1,$23
+bne $23,L.694
+cmpeq $27,2,$23
+bne $23,L.695
+cmpeq $27,3,$23
+bne $23,L.696
+br L.692
+L.694:
+ldt $f30,UfThold
+stt $f30,Z
+br L.693
+L.695:
+ldt $f30,E0
+stt $f30,Z
+br L.693
+L.696:
+ldt $f30,PseudoZero
+stt $f30,Z
+L.692:
+L.693:
+ldt $f30,Z
+ldt $f29,Zero
+cmpteq $f30,$f29,$f1
+fbne $f1,L.697
+ldt $f16,Z
+jsr $26,sqrt
+ldgp $gp,0($26)
+stt $f0,V9
+ldt $f30,V9
+mult $f30,$f30,$f30
+stt $f30,Y
+ldt $f30,Y
+ldt $f29,One
+ldt $f28,Radix
+ldt $f27,E9
+mult $f28,$f27,$f28
+ldt $f27,Z
+subt $f29,$f28,$f26
+divt $f30,$f26,$f26
+cmptlt $f26,$f27,$f1
+fbne $f1,L.701
+addt $f29,$f28,$f29
+mult $f29,$f27,$f29
+cmptle $f30,$f29,$f1
+fbne $f1,L.699
+L.701:
+ldt $f30,V9
+ldt $f29,U1
+cmptle $f30,$f29,$f1
+fbne $f1,L.702
+lda $16,1
+lda $17,L.158
+jsr $26,BadCond
+ldgp $gp,0($26)
+br L.703
+L.702:
+lda $16,2
+lda $17,L.158
+jsr $26,BadCond
+ldgp $gp,0($26)
+L.703:
+lda $16,L.704
+ldt $f17,Z
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.705
+ldt $f17,Y
+jsr $26,printf
+ldgp $gp,0($26)
+L.699:
+L.697:
+L.689:
+ldl $27,Indx
+lda $27,1($27)
+stl $27,Indx
+ldl $27,Indx
+cmple $27,3,$23
+bne $23,L.688
+lda $27,180
+stl $27,Milestone
+lda $27,1
+stl $27,Indx
+L.706:
+ldl $27,Indx
+cmpeq $27,1,$23
+beq $23,L.710
+ldt $f30,V
+stt $f30,Z
+br L.711
+L.710:
+ldt $f30,V0
+stt $f30,Z
+L.711:
+ldt $f16,Z
+jsr $26,sqrt
+ldgp $gp,0($26)
+stt $f0,V9
+ldt $f30,V9
+ldt $f29,One
+ldt $f28,Radix
+ldt $f27,E9
+mult $f28,$f27,$f28
+subt $f29,$f28,$f29
+mult $f29,$f30,$f29
+stt $f29,X
+ldt $f29,X
+mult $f30,$f29,$f30
+stt $f30,V9
+ldt $f30,V9
+ldt $f29,Z
+ldt $f28,One
+ldt $f27,Two
+ldt $f26,Radix
+mult $f27,$f26,$f27
+ldt $f26,E9
+mult $f27,$f26,$f27
+subt $f28,$f27,$f28
+mult $f28,$f29,$f28
+cmptlt $f30,$f28,$f1
+fbne $f1,L.714
+cmptle $f30,$f29,$f1
+fbne $f1,L.712
+L.714:
+ldt $f30,V9
+stt $f30,Y
+ldt $f30,X
+ldt $f29,W
+cmptlt $f30,$f29,$f1
+fbeq $f1,L.715
+lda $16,1
+lda $17,L.158
+jsr $26,BadCond
+ldgp $gp,0($26)
+br L.716
+L.715:
+lda $16,2
+lda $17,L.158
+jsr $26,BadCond
+ldgp $gp,0($26)
+L.716:
+lda $16,L.717
+ldt $f17,Z
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.718
+ldt $f17,Y
+jsr $26,printf
+ldgp $gp,0($26)
+L.712:
+L.707:
+ldl $27,Indx
+lda $27,1($27)
+stl $27,Indx
+ldl $27,Indx
+cmple $27,2,$23
+bne $23,L.706
+lda $27,190
+stl $27,Milestone
+jsr $26,Pause
+ldgp $gp,0($26)
+ldt $f30,UfThold
+ldt $f29,V
+mult $f30,$f29,$f30
+stt $f30,X
+ldt $f30,Radix
+mult $f30,$f30,$f30
+stt $f30,Y
+ldt $f30,X
+ldt $f29,Y
+mult $f30,$f29,$f28
+ldt $f27,One
+cmptlt $f28,$f27,$f1
+fbne $f1,L.721
+cmptle $f30,$f29,$f1
+fbne $f1,L.719
+L.721:
+ldt $f30,X
+ldt $f29,Y
+ldt $f28,U1
+mult $f30,$f29,$f27
+cmptlt $f27,$f28,$f1
+fbne $f1,L.724
+divt $f29,$f28,$f29
+cmptle $f30,$f29,$f1
+fbne $f1,L.722
+L.724:
+lda $16,2
+lda $17,L.725
+jsr $26,BadCond
+ldgp $gp,0($26)
+br L.723
+L.722:
+lda $16,3
+lda $17,L.158
+jsr $26,BadCond
+ldgp $gp,0($26)
+L.723:
+lda $16,L.726
+ldt $f17,X
+lda $18,L.727
+jsr $26,printf
+ldgp $gp,0($26)
+L.719:
+lda $27,200
+stl $27,Milestone
+lda $27,1
+stl $27,Indx
+L.728:
+ldt $f30,F9
+stt $f30,X
+ldl $27,Indx
+cmplt $27,2,$23
+bne $23,L.732
+cmple $27,5,$23
+beq $23,L.732
+subl $27,2,$27
+sll $27,3,$27
+ldq $27,L.738($27)
+jmp ($27)
+.rdata
+.align 3
+L.738:
+.quad L.734
+.quad L.735
+.quad L.736
+.quad L.737
+.text
+L.734:
+ldt $f30,One
+ldt $f29,U2
+addt $f30,$f29,$f30
+stt $f30,X
+br L.733
+L.735:
+ldt $f30,V
+stt $f30,X
+br L.733
+L.736:
+ldt $f30,UfThold
+stt $f30,X
+br L.733
+L.737:
+ldt $f30,Radix
+stt $f30,X
+L.732:
+L.733:
+ldt $f30,X
+stt $f30,Y
+lda $27,sigfpe
+stq $27,sigsave
+lda $16,ovfl_buf
+jsr $26,setjmp
+ldgp $gp,0($26)
+cmpeq $0,$31,$23
+bne $23,L.739
+lda $16,L.741
+ldt $f17,X
+jsr $26,printf
+ldgp $gp,0($26)
+br L.740
+L.739:
+ldt $f30,Half
+ldt $f29,Y
+ldt $f28,X
+divt $f29,$f28,$f29
+subt $f29,$f30,$f29
+subt $f29,$f30,$f30
+stt $f30,V9
+ldt $f30,V9
+ldt $f29,Zero
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.742
+br L.729
+L.742:
+ldt $f30,V9
+ldt $f29,U1
+negt $f29,$f29
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.744
+ldl $27,Indx
+cmplt $27,5,$23
+beq $23,L.744
+lda $16,3
+lda $17,L.158
+jsr $26,BadCond
+ldgp $gp,0($26)
+br L.745
+L.744:
+lda $16,1
+lda $17,L.158
+jsr $26,BadCond
+ldgp $gp,0($26)
+L.745:
+lda $16,L.746
+ldt $f17,X
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.747
+ldt $f17,V9
+jsr $26,printf
+ldgp $gp,0($26)
+L.740:
+stq $31,sigsave
+L.729:
+ldl $27,Indx
+lda $27,1($27)
+stl $27,Indx
+ldl $27,Indx
+cmple $27,5,$23
+bne $23,L.728
+lda $27,210
+stl $27,Milestone
+ldt $f30,Zero
+stt $f30,MyZero
+lda $16,L.45
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.748
+jsr $26,printf
+ldgp $gp,0($26)
+lda $27,sigfpe
+stq $27,sigsave
+lda $16,L.749
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,ovfl_buf
+jsr $26,setjmp
+ldgp $gp,0($26)
+cmpeq $0,$31,$23
+beq $23,L.750
+lda $16,L.752
+ldt $f30,One
+ldt $f29,MyZero
+divt $f30,$f29,$f17
+jsr $26,printf
+ldgp $gp,0($26)
+L.750:
+stq $31,sigsave
+lda $27,sigfpe
+stq $27,sigsave
+lda $16,L.753
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,ovfl_buf
+jsr $26,setjmp
+ldgp $gp,0($26)
+cmpeq $0,$31,$23
+beq $23,L.754
+lda $16,L.752
+ldt $f30,Zero
+ldt $f29,MyZero
+divt $f30,$f29,$f17
+jsr $26,printf
+ldgp $gp,0($26)
+L.754:
+stq $31,sigsave
+lda $27,220
+stl $27,Milestone
+jsr $26,Pause
+ldgp $gp,0($26)
+lda $16,L.45
+jsr $26,printf
+ldgp $gp,0($26)
+stl $31,-188+256($sp)
+L.761:
+ldl $27,-188+256($sp)
+sll $27,2,$27
+ldl $27,ErrCnt($27)
+cmpeq $27,$31,$23
+bne $23,L.765
+lda $16,L.767
+ldl $27,-188+256($sp)
+sll $27,3,$25
+ldq $17,L.756($25)
+sll $27,2,$27
+ldl $18,ErrCnt($27)
+jsr $26,printf
+ldgp $gp,0($26)
+L.765:
+L.762:
+ldl $27,-188+256($sp)
+lda $27,1($27)
+stl $27,-188+256($sp)
+ldl $27,-188+256($sp)
+cmplt $27,4,$23
+bne $23,L.761
+lda $16,L.45
+jsr $26,printf
+ldgp $gp,0($26)
+ldl $27,ErrCnt
+ldl $25,ErrCnt+4
+addl $27,$25,$27
+ldl $25,ErrCnt+8
+addl $27,$25,$27
+ldl $25,ErrCnt+12
+addl $27,$25,$27
+cmple $27,$31,$23
+bne $23,L.768
+ldl $25,ErrCnt
+ldl $22,ErrCnt+4
+addl $25,$22,$25
+ldl $22,ErrCnt+8
+addl $25,$22,$25
+cmpeq $25,$31,$23
+beq $23,L.773
+ldl $25,ErrCnt+12
+cmple $25,$31,$23
+bne $23,L.773
+lda $16,L.778
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.779
+jsr $26,printf
+ldgp $gp,0($26)
+L.773:
+ldl $25,ErrCnt
+ldl $22,ErrCnt+4
+addl $25,$22,$25
+cmpeq $25,$31,$23
+beq $23,L.780
+ldl $25,ErrCnt+8
+cmple $25,$31,$23
+bne $23,L.780
+lda $16,L.784
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.785
+jsr $26,printf
+ldgp $gp,0($26)
+L.780:
+ldl $27,ErrCnt
+ldl $25,ErrCnt+4
+addl $27,$25,$27
+cmple $27,$31,$23
+bne $23,L.786
+lda $16,L.789
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.790
+jsr $26,printf
+ldgp $gp,0($26)
+L.786:
+ldl $27,ErrCnt
+cmple $27,$31,$23
+bne $23,L.769
+lda $16,L.793
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.794
+jsr $26,printf
+ldgp $gp,0($26)
+br L.769
+L.768:
+lda $16,L.795
+jsr $26,printf
+ldgp $gp,0($26)
+ldl $27,RMult
+cmpeq $27,1,$23
+beq $23,L.800
+ldl $27,RDiv
+cmpeq $27,1,$23
+beq $23,L.800
+ldl $27,RAddSub
+cmpeq $27,1,$23
+beq $23,L.800
+ldl $27,RSqrt
+cmpeq $27,1,$23
+bne $23,L.796
+L.800:
+lda $16,L.801
+jsr $26,printf
+ldgp $gp,0($26)
+br L.797
+L.796:
+ldt $f30,One
+ldt $f29,StickyBit
+cmptlt $f29,$f30,$f1
+fbne $f1,L.802
+ldt $f29,Radix
+ldt $f28,Two
+subt $f29,$f28,$f28
+ldt $f27,Nine
+subt $f29,$f27,$f29
+subt $f29,$f30,$f30
+mult $f28,$f30,$f30
+ldt $f29,Zero
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.802
+lda $16,L.804
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.805
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,Two
+ldt $f29,Radix
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.806
+ldt $f29,Precision
+ldt $f28,TwentySeven
+ldt $f27,Four
+ldt $f26,Three
+mult $f27,$f26,$f27
+mult $f27,$f30,$f30
+subt $f29,$f30,$f30
+subt $f29,$f28,$f29
+subt $f29,$f28,$f29
+ldt $f28,One
+addt $f29,$f28,$f29
+mult $f30,$f29,$f30
+ldt $f29,Zero
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.806
+lda $16,L.808
+jsr $26,printf
+ldgp $gp,0($26)
+br L.807
+L.806:
+lda $16,L.809
+jsr $26,printf
+ldgp $gp,0($26)
+L.807:
+ldl $27,IEEE
+cmpeq $27,$31,$23
+bne $23,L.810
+lda $16,L.812
+jsr $26,printf
+ldgp $gp,0($26)
+br L.811
+L.810:
+lda $16,L.813
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.814
+jsr $26,printf
+ldgp $gp,0($26)
+L.811:
+L.802:
+lda $16,L.815
+jsr $26,printf
+ldgp $gp,0($26)
+L.797:
+L.769:
+ldl $27,fpecount
+cmpeq $27,$31,$23
+bne $23,L.816
+lda $16,L.818
+ldl $17,fpecount
+jsr $26,printf
+ldgp $gp,0($26)
+L.816:
+lda $16,L.819
+jsr $26,printf
+ldgp $gp,0($26)
+mov $31,$0
+L.7:
+ldq $9,0($sp)
+ldq $10,8($sp)
+ldq $11,16($sp)
+ldq $12,24($sp)
+ldq $13,32($sp)
+ldq $14,40($sp)
+ldq $26,48($sp)
+lda $sp,256($sp)
+ret
+.end main
+.globl Sign
+.text
+.ent Sign
+Sign:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.fmask 0x200,-80
+.mask 0x4000000,-72
+.frame $sp,80,$26,48
+stt $f9,0($sp)
+stq $26,8($sp)
+.prologue 1
+ldt $f30,L.8
+cmptlt $f16,$f30,$f1
+fbne $f1,L.822
+ldt $f9,L.9
+br L.823
+L.822:
+ldt $f9,L.824
+L.823:
+fmov $f9,$f0
+L.820:
+ldt $f9,0($sp)
+ldq $26,8($sp)
+lda $sp,80($sp)
+ret
+.end Sign
+.globl Pause
+.text
+.ent Pause
+Pause:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+.prologue 1
+lda $16,L.826
+ldl $17,Milestone
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.827
+ldl $17,PageNo
+jsr $26,printf
+ldgp $gp,0($26)
+ldl $27,Milestone
+lda $27,1($27)
+stl $27,Milestone
+ldl $27,PageNo
+lda $27,1($27)
+stl $27,PageNo
+mov $31,$0
+L.825:
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end Pause
+.globl TstCond
+.text
+.ent TstCond
+TstCond:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+stq $16,16($sp)
+stq $17,24($sp)
+stq $18,32($sp)
+.prologue 1
+ldl $27,-40+64($sp)
+cmpeq $27,$31,$23
+beq $23,L.829
+ldl $16,-48+64($sp)
+ldq $17,-32+64($sp)
+jsr $26,BadCond
+ldgp $gp,0($26)
+lda $16,L.812
+jsr $26,printf
+ldgp $gp,0($26)
+L.829:
+mov $31,$0
+L.828:
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end TstCond
+.sdata
+.align 3
+L.832:
+.quad L.833
+.quad L.834
+.quad L.835
+.quad L.836
+.globl BadCond
+.text
+.text
+.ent BadCond
+BadCond:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4004000,-72
+.frame $sp,80,$26,48
+stq $14,0($sp)
+stq $26,8($sp)
+mov $16,$14
+stq $17,40($sp)
+.prologue 1
+sll $14,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+lda $27,ErrCnt($27)
+ldl $25,($27)
+lda $25,1($25)
+stl $25,($27)
+lda $16,L.837
+sll $14,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,3,$27
+ldq $17,L.832($27)
+ldq $18,-40+80($sp)
+jsr $26,printf
+ldgp $gp,0($26)
+mov $31,$0
+L.831:
+ldq $14,0($sp)
+ldq $26,8($sp)
+lda $sp,80($sp)
+ret
+.end BadCond
+.globl Random
+.text
+.ent Random
+Random:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.fmask 0x300,-72
+.mask 0x4000000,-64
+.frame $sp,80,$26,48
+stt $f8,0($sp)
+stt $f9,8($sp)
+stq $26,16($sp)
+.prologue 1
+ldt $f30,Random1
+ldt $f29,Random9
+addt $f30,$f29,$f9
+mult $f9,$f9,$f8
+mult $f8,$f8,$f8
+mult $f9,$f8,$f9
+fmov $f9,$f16
+jsr $26,floor
+ldgp $gp,0($26)
+subt $f9,$f0,$f8
+ldt $f30,L.839
+mult $f30,$f9,$f30
+addt $f8,$f30,$f30
+stt $f30,Random1
+ldt $f0,Random1
+L.838:
+ldt $f8,0($sp)
+ldt $f9,8($sp)
+ldq $26,16($sp)
+lda $sp,80($sp)
+ret
+.end Random
+.globl SqXMinX
+.text
+.ent SqXMinX
+SqXMinX:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.fmask 0x200,-80
+.mask 0x4000000,-72
+.frame $sp,80,$26,48
+stt $f9,0($sp)
+stq $26,8($sp)
+stq $16,32($sp)
+.prologue 1
+ldt $f30,X
+ldt $f29,BInvrse
+mult $f30,$f29,$f9
+subt $f30,$f9,$f29
+stt $f29,-64+80($sp)
+mult $f30,$f30,$f16
+jsr $26,sqrt
+ldgp $gp,0($26)
+subt $f0,$f9,$f30
+ldt $f29,-64+80($sp)
+subt $f30,$f29,$f30
+ldt $f29,OneUlp
+divt $f30,$f29,$f30
+stt $f30,SqEr
+ldt $f30,SqEr
+ldt $f29,Zero
+cmpteq $f30,$f29,$f1
+fbne $f1,L.841
+ldt $f30,SqEr
+ldt $f29,MinSqEr
+cmptlt $f30,$f29,$f1
+fbeq $f1,L.843
+ldt $f30,SqEr
+stt $f30,MinSqEr
+L.843:
+ldt $f30,SqEr
+ldt $f29,MaxSqEr
+cmptle $f30,$f29,$f1
+fbne $f1,L.845
+ldt $f30,SqEr
+stt $f30,MaxSqEr
+L.845:
+ldt $f30,J
+ldt $f29,L.9
+addt $f30,$f29,$f30
+stt $f30,J
+ldl $16,-48+80($sp)
+lda $17,L.45
+jsr $26,BadCond
+ldgp $gp,0($26)
+lda $16,L.847
+ldt $f30,X
+mult $f30,$f30,$f17
+fmov $f30,$f18
+ldt $f30,OneUlp
+ldt $f29,SqEr
+mult $f30,$f29,$f19
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.848
+jsr $26,printf
+ldgp $gp,0($26)
+L.841:
+mov $31,$0
+L.840:
+ldt $f9,0($sp)
+ldq $26,8($sp)
+lda $sp,80($sp)
+ret
+.end SqXMinX
+.globl NewD
+.text
+.ent NewD
+NewD:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+.prologue 1
+ldt $f30,Z1
+ldt $f29,Q
+mult $f30,$f29,$f30
+stt $f30,X
+ldt $f30,Half
+ldt $f29,X
+ldt $f28,Radix
+divt $f29,$f28,$f29
+subt $f30,$f29,$f16
+jsr $26,floor
+ldgp $gp,0($26)
+ldt $f29,Radix
+mult $f0,$f29,$f30
+ldt $f28,X
+addt $f30,$f28,$f30
+stt $f30,X
+ldt $f30,X
+ldt $f28,Z
+ldt $f27,D
+ldt $f26,Q
+mult $f30,$f28,$f25
+subt $f26,$f25,$f26
+divt $f26,$f29,$f26
+mult $f30,$f30,$f25
+divt $f27,$f29,$f29
+mult $f25,$f29,$f29
+addt $f26,$f29,$f29
+stt $f29,Q
+ldt $f29,Two
+mult $f29,$f30,$f30
+mult $f30,$f27,$f30
+subt $f28,$f30,$f30
+stt $f30,Z
+ldt $f30,Z
+ldt $f29,Zero
+cmptle $f30,$f29,$f1
+fbeq $f1,L.850
+ldt $f30,Z
+negt $f30,$f30
+stt $f30,Z
+ldt $f30,Z1
+negt $f30,$f30
+stt $f30,Z1
+L.850:
+ldt $f30,Radix
+ldt $f29,D
+mult $f30,$f29,$f30
+stt $f30,D
+mov $31,$0
+L.849:
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end NewD
+.globl SR3750
+.text
+.ent SR3750
+SR3750:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+.prologue 1
+ldt $f30,X
+ldt $f29,Radix
+ldt $f28,Z2
+subt $f30,$f29,$f27
+subt $f28,$f29,$f29
+cmptlt $f27,$f29,$f1
+fbne $f1,L.853
+subt $f30,$f28,$f30
+ldt $f29,W
+subt $f29,$f28,$f29
+cmptle $f30,$f29,$f1
+fbeq $f1,L.853
+ldl $27,I
+lda $27,1($27)
+stl $27,I
+ldt $f30,X
+ldt $f29,D
+mult $f30,$f29,$f16
+jsr $26,sqrt
+ldgp $gp,0($26)
+stt $f0,X2
+ldt $f30,Z2
+ldt $f29,Y
+ldt $f28,X2
+subt $f28,$f30,$f28
+subt $f29,$f30,$f30
+subt $f28,$f30,$f30
+stt $f30,Y2
+ldt $f30,Half
+ldt $f28,X8
+subt $f29,$f30,$f29
+divt $f28,$f29,$f29
+stt $f29,X2
+ldt $f29,X2
+mult $f30,$f29,$f28
+mult $f28,$f29,$f28
+subt $f29,$f28,$f29
+stt $f29,X2
+ldt $f29,Y2
+addt $f29,$f30,$f29
+ldt $f28,X2
+subt $f30,$f28,$f30
+addt $f29,$f30,$f30
+stt $f30,SqEr
+ldt $f30,SqEr
+ldt $f29,MinSqEr
+cmptlt $f30,$f29,$f1
+fbeq $f1,L.855
+ldt $f30,SqEr
+stt $f30,MinSqEr
+L.855:
+ldt $f30,Y2
+ldt $f29,X2
+subt $f30,$f29,$f30
+stt $f30,SqEr
+ldt $f30,SqEr
+ldt $f29,MaxSqEr
+cmptle $f30,$f29,$f1
+fbne $f1,L.857
+ldt $f30,SqEr
+stt $f30,MaxSqEr
+L.857:
+L.853:
+mov $31,$0
+L.852:
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end SR3750
+.globl IsYeqX
+.text
+.ent IsYeqX
+IsYeqX:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+.prologue 1
+ldt $f30,Y
+ldt $f29,X
+cmpteq $f30,$f29,$f1
+fbne $f1,L.860
+ldl $27,N
+cmple $27,$31,$23
+beq $23,L.862
+ldt $f30,Zero
+ldt $f29,Z
+cmpteq $f29,$f30,$f1
+fbeq $f1,L.864
+ldt $f29,Q
+cmptle $f29,$f30,$f1
+fbeq $f1,L.864
+lda $16,L.866
+jsr $26,printf
+ldgp $gp,0($26)
+br L.865
+L.864:
+lda $16,2
+lda $17,L.867
+jsr $26,BadCond
+ldgp $gp,0($26)
+L.865:
+lda $16,L.868
+ldt $f17,Z
+ldt $f18,Q
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.869
+ldt $f17,Y
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.870
+ldt $f17,X
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.871
+ldt $f30,Y
+ldt $f29,X
+subt $f30,$f29,$f17
+jsr $26,printf
+ldgp $gp,0($26)
+L.862:
+ldl $27,N
+lda $27,1($27)
+stl $27,N
+L.860:
+mov $31,$0
+L.859:
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end IsYeqX
+.globl SR3980
+.text
+.ent SR3980
+SR3980:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+.prologue 1
+L.873:
+lds $f30,I
+cvtlq $f30,$f30
+cvtqt $f30,$f30
+stt $f30,Q
+ldt $f16,Z
+ldt $f17,Q
+jsr $26,pow
+ldgp $gp,0($26)
+stt $f0,Y
+jsr $26,IsYeqX
+ldgp $gp,0($26)
+ldl $27,I
+lda $27,1($27)
+stl $27,I
+ldl $25,M
+cmple $27,$25,$23
+bne $23,L.876
+br L.875
+L.876:
+ldt $f30,Z
+ldt $f29,X
+mult $f30,$f29,$f30
+stt $f30,X
+L.874:
+ldt $f30,X
+ldt $f29,W
+cmptlt $f30,$f29,$f1
+fbne $f1,L.873
+L.875:
+mov $31,$0
+L.872:
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end SR3980
+.globl PrintIfNPositive
+.text
+.ent PrintIfNPositive
+PrintIfNPositive:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+.prologue 1
+ldl $27,N
+cmple $27,$31,$23
+bne $23,L.879
+lda $16,L.881
+ldl $17,N
+jsr $26,printf
+ldgp $gp,0($26)
+L.879:
+mov $31,$0
+L.878:
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end PrintIfNPositive
+.globl TstPtUf
+.text
+.ent TstPtUf
+TstPtUf:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+.prologue 1
+stl $31,N
+ldt $f30,Z
+ldt $f29,Zero
+cmpteq $f30,$f29,$f1
+fbne $f1,L.883
+lda $16,L.885
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.886
+jsr $26,printf
+ldgp $gp,0($26)
+lda $27,sigfpe
+stq $27,sigsave
+lda $16,ovfl_buf
+jsr $26,setjmp
+ldgp $gp,0($26)
+cmpeq $0,$31,$23
+bne $23,L.887
+br L.889
+L.887:
+ldt $f30,Z
+addt $f30,$f30,$f29
+divt $f29,$f30,$f30
+stt $f30,Q9
+lda $16,L.890
+ldt $f17,Q9
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,Q9
+ldt $f29,Two
+subt $f30,$f29,$f16
+jsr $26,fabs
+ldgp $gp,0($26)
+ldt $f29,Radix
+ldt $f28,U2
+mult $f29,$f28,$f29
+cmptlt $f0,$f29,$f1
+fbeq $f1,L.891
+lda $16,L.893
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.894
+jsr $26,printf
+ldgp $gp,0($26)
+br L.892
+L.891:
+ldt $f30,Q9
+ldt $f29,One
+cmptlt $f30,$f29,$f1
+fbne $f1,L.897
+ldt $f29,Two
+cmptle $f30,$f29,$f1
+fbne $f1,L.895
+L.897:
+L.889:
+lda $27,1
+stl $27,N
+ldl $27,ErrCnt+4
+lda $27,1($27)
+stl $27,ErrCnt+4
+lda $16,L.900
+jsr $26,printf
+ldgp $gp,0($26)
+br L.896
+L.895:
+lda $27,1
+stl $27,N
+ldl $27,ErrCnt+8
+lda $27,1($27)
+stl $27,ErrCnt+8
+lda $16,L.903
+jsr $26,printf
+ldgp $gp,0($26)
+L.896:
+L.892:
+stq $31,sigsave
+ldt $f30,Z
+ldt $f29,One
+mult $f30,$f29,$f28
+stt $f28,V9
+ldt $f28,V9
+stt $f28,Random1
+mult $f29,$f30,$f28
+stt $f28,V9
+ldt $f28,V9
+stt $f28,Random2
+divt $f30,$f29,$f30
+stt $f30,V9
+ldt $f30,Z
+ldt $f29,Random1
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.904
+ldt $f29,Random2
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.904
+ldt $f29,V9
+cmpteq $f30,$f29,$f1
+fbeq $f1,L.904
+ldl $27,N
+cmple $27,$31,$23
+bne $23,L.905
+jsr $26,Pause
+ldgp $gp,0($26)
+br L.905
+L.904:
+lda $27,1
+stl $27,N
+lda $16,2
+lda $17,L.908
+jsr $26,BadCond
+ldgp $gp,0($26)
+lda $16,L.909
+ldt $f17,Z
+jsr $26,printf
+ldgp $gp,0($26)
+ldt $f30,Z
+ldt $f29,Random1
+cmpteq $f30,$f29,$f1
+fbne $f1,L.910
+lda $16,L.912
+ldt $f17,Random1
+jsr $26,printf
+ldgp $gp,0($26)
+L.910:
+ldt $f30,Random2
+ldt $f29,Z
+cmpteq $f29,$f30,$f1
+fbne $f1,L.913
+ldt $f29,Random1
+cmpteq $f30,$f29,$f1
+fbne $f1,L.913
+lda $16,L.915
+ldt $f17,Random2
+jsr $26,printf
+ldgp $gp,0($26)
+L.913:
+ldt $f30,Z
+ldt $f29,V9
+cmpteq $f30,$f29,$f1
+fbne $f1,L.916
+lda $16,L.918
+ldt $f17,V9
+jsr $26,printf
+ldgp $gp,0($26)
+L.916:
+ldt $f30,Random2
+ldt $f29,Random1
+cmpteq $f30,$f29,$f1
+fbne $f1,L.919
+ldl $27,ErrCnt+8
+lda $27,1($27)
+stl $27,ErrCnt+8
+lda $16,2
+lda $17,L.923
+jsr $26,BadCond
+ldgp $gp,0($26)
+lda $16,L.924
+ldt $f17,Random2
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.925
+ldt $f17,Random1
+jsr $26,printf
+ldgp $gp,0($26)
+L.919:
+jsr $26,Pause
+ldgp $gp,0($26)
+L.905:
+L.883:
+mov $31,$0
+L.882:
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end TstPtUf
+.globl notify
+.text
+.ent notify
+notify:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+stq $16,16($sp)
+.prologue 1
+lda $16,L.927
+ldq $17,-48+64($sp)
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,L.928
+jsr $26,printf
+ldgp $gp,0($26)
+mov $31,$0
+L.926:
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end notify
+.globl msglist
+.text
+.ent msglist
+msglist:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4004000,-72
+.frame $sp,80,$26,48
+stq $14,0($sp)
+stq $26,8($sp)
+mov $16,$14
+.prologue 1
+br L.931
+L.930:
+lda $16,L.933
+mov $14,$27
+lda $14,8($27)
+ldq $17,($27)
+jsr $26,printf
+ldgp $gp,0($26)
+L.931:
+ldq $27,($14)
+cmpeq $27,$31,$23
+beq $23,L.930
+mov $31,$0
+L.929:
+ldq $14,0($sp)
+ldq $26,8($sp)
+lda $sp,80($sp)
+ret
+.end msglist
+.sdata
+.align 3
+L.935:
+.quad L.936
+.quad L.937
+.quad L.938
+.quad L.939
+.quad L.940
+.quad L.941
+.quad L.942
+.quad L.943
+.quad L.944
+.quad 0x0
+.globl Instructions
+.text
+.text
+.ent Instructions
+Instructions:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+.prologue 1
+lda $16,L.935
+jsr $26,msglist
+ldgp $gp,0($26)
+mov $31,$0
+L.934:
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end Instructions
+.sdata
+.align 3
+L.946:
+.quad L.947
+.quad L.948
+.quad L.949
+.quad L.950
+.quad L.951
+.quad L.952
+.quad L.953
+.quad L.954
+.quad L.955
+.quad L.956
+.quad L.957
+.quad L.958
+.quad L.959
+.quad L.960
+.quad 0x0
+.globl Heading
+.text
+.text
+.ent Heading
+Heading:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+.prologue 1
+lda $16,L.946
+jsr $26,msglist
+ldgp $gp,0($26)
+mov $31,$0
+L.945:
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end Heading
+.sdata
+.align 3
+L.962:
+.quad L.963
+.quad L.964
+.quad L.965
+.quad L.966
+.quad L.967
+.quad L.968
+.quad L.969
+.quad L.970
+.quad L.971
+.quad L.972
+.quad L.973
+.quad L.974
+.quad L.975
+.quad L.976
+.quad L.977
+.quad L.978
+.quad L.979
+.quad L.980
+.quad L.981
+.quad 0x0
+.globl Characteristics
+.text
+.text
+.ent Characteristics
+Characteristics:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+.prologue 1
+lda $16,L.962
+jsr $26,msglist
+ldgp $gp,0($26)
+mov $31,$0
+L.961:
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end Characteristics
+.sdata
+.align 3
+L.983:
+.quad L.984
+.quad L.985
+.quad L.986
+.quad L.987
+.quad L.988
+.quad L.989
+.quad L.990
+.quad L.991
+.quad L.992
+.quad L.993
+.quad L.994
+.quad L.995
+.quad L.996
+.quad L.997
+.quad L.998
+.quad L.999
+.quad L.1000
+.quad 0x0
+.globl History
+.text
+.text
+.ent History
+History:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+.prologue 1
+lda $16,L.983
+jsr $26,msglist
+ldgp $gp,0($26)
+mov $31,$0
+L.982:
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end History
+.globl pow
+.text
+.ent pow
+pow:
+ldgp $gp,0($27)
+lda $sp,-128($sp)
+.fmask 0x380,-112
+.mask 0x4006000,-88
+.frame $sp,128,$26,48
+stt $f7,0($sp)
+stt $f8,8($sp)
+stt $f9,16($sp)
+stq $13,24($sp)
+stq $14,32($sp)
+stq $26,40($sp)
+fmov $f16,$f9
+fmov $f17,$f8
+.prologue 1
+mov $31,$13
+stl $31,-64+128($sp)
+ldt $f30,L.8
+cmpteq $f8,$f30,$f1
+fbeq $f1,L.1002
+ldt $f0,L.9
+br L.1001
+L.1002:
+ldt $f30,L.1007
+cmptlt $f8,$f30,$f1
+fbne $f1,L.1006
+ldt $f30,L.1008
+cmptle $f8,$f30,$f1
+fbne $f1,L.1004
+L.1006:
+ldt $f30,L.824
+cmpteq $f9,$f30,$f1
+fbne $f1,L.1004
+fmov $f9,$f16
+jsr $26,log
+ldgp $gp,0($26)
+fmov $f0,$f30
+mult $f8,$f30,$f16
+jsr $26,exp
+ldgp $gp,0($26)
+fmov $f0,$f30
+br L.1001
+L.1004:
+ldt $f30,L.8
+cmptlt $f8,$f30,$f1
+fbeq $f1,L.1009
+negt $f8,$f8
+lda $27,1
+stl $27,-64+128($sp)
+L.1009:
+fmov $f8,$f16
+lda $17,-72+128($sp)
+jsr $26,modf
+ldgp $gp,0($26)
+fmov $f0,$f8
+ldt $f30,L.8
+cmpteq $f8,$f30,$f1
+fbne $f1,L.1011
+fmov $f9,$f16
+jsr $26,log
+ldgp $gp,0($26)
+fmov $f0,$f30
+mult $f8,$f30,$f16
+jsr $26,exp
+ldgp $gp,0($26)
+fmov $f0,$f7
+br L.1012
+L.1011:
+ldt $f7,L.9
+L.1012:
+fmov $f9,$f16
+lda $17,-60+128($sp)
+jsr $26,frexp
+ldgp $gp,0($26)
+fmov $f0,$f9
+ldt $f30,-72+128($sp)
+cvttqc $f30,$f1
+stt $f1,-56+128($sp)
+ldq $27,-56+128($sp)
+mov $27,$14
+cmpeq $27,$31,$23
+bne $23,L.1013
+L.1015:
+and $14,1,$27
+cmpeq $27,$31,$23
+bne $23,L.1019
+mult $f7,$f9,$f7
+ldl $27,-60+128($sp)
+addl $13,$27,$13
+L.1019:
+sra $14,1,$27
+mov $27,$14
+cmpeq $27,$31,$23
+beq $23,L.1021
+br L.1017
+L.1021:
+mult $f9,$f9,$f9
+ldl $27,-60+128($sp)
+sll $27,1,$27
+addl $27,0,$27
+stl $27,-60+128($sp)
+ldt $f30,L.1025
+cmptlt $f9,$f30,$f1
+fbeq $f1,L.1015
+ldt $f30,L.1026
+mult $f30,$f9,$f9
+ldl $27,-60+128($sp)
+subl $27,1,$27
+stl $27,-60+128($sp)
+br L.1015
+L.1017:
+L.1013:
+ldl $27,-64+128($sp)
+cmpeq $27,$31,$23
+bne $23,L.1027
+ldt $f30,L.9
+divt $f30,$f7,$f7
+negl $13,$13
+L.1027:
+fmov $f7,$f16
+mov $13,$17
+jsr $26,ldexp
+ldgp $gp,0($26)
+fmov $f0,$f30
+L.1001:
+ldt $f7,0($sp)
+ldt $f8,8($sp)
+ldt $f9,16($sp)
+ldq $13,24($sp)
+ldq $14,32($sp)
+ldq $26,40($sp)
+lda $sp,128($sp)
+ret
+.end pow
+.globl UfNGrad
+.comm UfNGrad,4
+.globl SqRWrng
+.comm SqRWrng,4
+.globl IEEE
+.comm IEEE,4
+.globl Anomaly
+.comm Anomaly,4
+.globl Monot
+.comm Monot,4
+.globl NotMonot
+.comm NotMonot,4
+.globl Done
+.comm Done,4
+.globl Break
+.comm Break,4
+.globl RSqrt
+.comm RSqrt,4
+.globl RAddSub
+.comm RAddSub,4
+.globl RDiv
+.comm RDiv,4
+.globl RMult
+.comm RMult,4
+.globl GAddSub
+.comm GAddSub,4
+.globl GDiv
+.comm GDiv,4
+.globl GMult
+.comm GMult,4
+.globl N1
+.comm N1,4
+.globl N
+.comm N,4
+.globl M
+.comm M,4
+.globl PageNo
+.comm PageNo,4
+.globl Milestone
+.comm Milestone,4
+.globl fpecount
+.comm fpecount,4
+.globl ErrCnt
+.comm ErrCnt,16
+.globl Z9
+.comm Z9,8
+.globl Z2
+.comm Z2,8
+.globl Z1
+.comm Z1,8
+.globl PseudoZero
+.comm PseudoZero,8
+.globl Z
+.comm Z,8
+.globl Random2
+.comm Random2,8
+.globl Y2
+.comm Y2,8
+.globl Y1
+.comm Y1,8
+.globl Y
+.comm Y,8
+.globl Random1
+.comm Random1,8
+.globl X8
+.comm X8,8
+.globl X2
+.comm X2,8
+.globl X1
+.comm X1,8
+.globl X
+.comm X,8
+.globl W
+.comm W,8
+.globl V9
+.comm V9,8
+.globl V0
+.comm V0,8
+.globl V
+.comm V,8
+.globl U2
+.comm U2,8
+.globl U1
+.comm U1,8
+.globl UfThold
+.comm UfThold,8
+.globl OneUlp
+.comm OneUlp,8
+.globl S
+.comm S,8
+.globl Underflow
+.comm Underflow,8
+.globl T
+.comm T,8
+.globl Random9
+.comm Random9,8
+.globl R
+.comm R,8
+.globl Q9
+.comm Q9,8
+.globl Q
+.comm Q,8
+.globl Precision
+.comm Precision,8
+.globl MyZero
+.comm MyZero,8
+.globl J
+.comm J,8
+.globl StickyBit
+.comm StickyBit,8
+.globl I
+.comm I,4
+.globl HInvrse
+.comm HInvrse,8
+.globl H
+.comm H,8
+.globl F9
+.comm F9,8
+.globl F6
+.comm F6,8
+.globl Third
+.comm Third,8
+.globl E9
+.comm E9,8
+.globl MaxSqEr
+.comm MaxSqEr,8
+.globl SqEr
+.comm SqEr,8
+.globl MinSqEr
+.comm MinSqEr,8
+.globl E3
+.comm E3,8
+.globl Exp2
+.comm Exp2,8
+.globl E1
+.comm E1,8
+.globl E0
+.comm E0,8
+.globl FourD
+.comm FourD,8
+.globl D
+.comm D,8
+.globl CInvrse
+.comm CInvrse,8
+.globl C
+.comm C,8
+.globl A1
+.comm A1,8
+.globl AInvrse
+.comm AInvrse,8
+.globl ch
+.comm ch,8
+.globl Indx
+.comm Indx,4
+.globl BMinusU2
+.comm BMinusU2,8
+.globl RadixD2
+.comm RadixD2,8
+.globl BInvrse
+.comm BInvrse,8
+.globl Radix
+.comm Radix,8
+.globl sigsave
+.comm sigsave,8
+.globl ovfl_buf
+.comm ovfl_buf,336
+.extern _iob 0
+.rdata
+.align 3
+L.1026:
+.long 0x0
+.long 0x40000000
+.align 3
+L.1025:
+.long 0x0
+.long 0x3fe00000
+.align 3
+L.1008:
+.long 0x0
+.long 0x40913000
+.align 3
+L.1007:
+.long 0x0
+.long 0xc0913000
+.align 0
+L.1000:
+.byte 115
+.byte 101
+.byte 101
+.byte 32
+.byte 115
+.byte 111
+.byte 117
+.byte 114
+.byte 99
+.byte 101
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 109
+.byte 111
+.byte 114
+.byte 101
+.byte 32
+.byte 104
+.byte 105
+.byte 115
+.byte 116
+.byte 111
+.byte 114
+.byte 121
+.byte 46
+.byte 0
+.align 0
+L.999:
+.byte 66
+.byte 65
+.byte 83
+.byte 73
+.byte 67
+.byte 32
+.byte 118
+.byte 101
+.byte 114
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 40
+.byte 67
+.byte 41
+.byte 32
+.byte 49
+.byte 57
+.byte 56
+.byte 51
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 80
+.byte 114
+.byte 111
+.byte 102
+.byte 46
+.byte 32
+.byte 87
+.byte 46
+.byte 32
+.byte 77
+.byte 46
+.byte 32
+.byte 75
+.byte 97
+.byte 104
+.byte 97
+.byte 110
+.byte 59
+.byte 0
+.align 0
+L.998:
+.byte 97
+.byte 115
+.byte 32
+.byte 117
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 99
+.byte 101
+.byte 114
+.byte 116
+.byte 97
+.byte 105
+.byte 110
+.byte 32
+.byte 101
+.byte 97
+.byte 114
+.byte 108
+.byte 121
+.byte 32
+.byte 87
+.byte 65
+.byte 78
+.byte 71
+.byte 32
+.byte 109
+.byte 97
+.byte 99
+.byte 104
+.byte 105
+.byte 110
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.997:
+.byte 102
+.byte 108
+.byte 111
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 45
+.byte 112
+.byte 111
+.byte 105
+.byte 110
+.byte 116
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 115
+.byte 44
+.byte 32
+.byte 98
+.byte 117
+.byte 116
+.byte 32
+.byte 97
+.byte 108
+.byte 115
+.byte 111
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 111
+.byte 119
+.byte 115
+.byte 32
+.byte 108
+.byte 111
+.byte 103
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 105
+.byte 99
+.byte 32
+.byte 101
+.byte 110
+.byte 99
+.byte 111
+.byte 100
+.byte 105
+.byte 110
+.byte 103
+.byte 0
+.align 0
+L.996:
+.byte 10
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 98
+.byte 97
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 117
+.byte 112
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 118
+.byte 101
+.byte 110
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 97
+.byte 108
+.byte 32
+.byte 114
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 114
+.byte 101
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 101
+.byte 110
+.byte 116
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 0
+.align 0
+L.995:
+.byte 111
+.byte 102
+.byte 32
+.byte 112
+.byte 97
+.byte 116
+.byte 104
+.byte 111
+.byte 108
+.byte 111
+.byte 103
+.byte 105
+.byte 101
+.byte 115
+.byte 44
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 115
+.byte 97
+.byte 121
+.byte 32
+.byte 104
+.byte 111
+.byte 119
+.byte 32
+.byte 119
+.byte 101
+.byte 108
+.byte 108
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 109
+.byte 112
+.byte 108
+.byte 101
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 101
+.byte 100
+.byte 46
+.byte 0
+.align 0
+L.994:
+.byte 111
+.byte 102
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 44
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 116
+.byte 114
+.byte 105
+.byte 101
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 111
+.byte 112
+.byte 101
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 97
+.byte 32
+.byte 119
+.byte 105
+.byte 100
+.byte 101
+.byte 114
+.byte 32
+.byte 118
+.byte 97
+.byte 114
+.byte 105
+.byte 101
+.byte 116
+.byte 121
+.byte 0
+.align 0
+L.993:
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 44
+.byte 32
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 114
+.byte 97
+.byte 110
+.byte 103
+.byte 101
+.byte 32
+.byte 40
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 47
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 115
+.byte 41
+.byte 0
+.align 0
+L.992:
+.byte 87
+.byte 46
+.byte 32
+.byte 74
+.byte 46
+.byte 32
+.byte 67
+.byte 111
+.byte 100
+.byte 121
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 87
+.byte 46
+.byte 32
+.byte 87
+.byte 97
+.byte 105
+.byte 116
+.byte 101
+.byte 46
+.byte 32
+.byte 65
+.byte 108
+.byte 116
+.byte 104
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 32
+.byte 98
+.byte 111
+.byte 116
+.byte 104
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 115
+.byte 32
+.byte 116
+.byte 114
+.byte 121
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 0
+.align 0
+L.991:
+.byte 98
+.byte 111
+.byte 111
+.byte 107
+.byte 32
+.byte 32
+.byte 96
+.byte 83
+.byte 111
+.byte 102
+.byte 116
+.byte 119
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 77
+.byte 97
+.byte 110
+.byte 117
+.byte 97
+.byte 108
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 69
+.byte 108
+.byte 101
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 97
+.byte 114
+.byte 121
+.byte 32
+.byte 70
+.byte 117
+.byte 110
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 39
+.byte 32
+.byte 40
+.byte 49
+.byte 57
+.byte 56
+.byte 48
+.byte 41
+.byte 32
+.byte 98
+.byte 121
+.byte 0
+.align 0
+L.990:
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 99
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 100
+.byte 32
+.byte 96
+.byte 77
+.byte 65
+.byte 67
+.byte 72
+.byte 65
+.byte 82
+.byte 39
+.byte 44
+.byte 32
+.byte 119
+.byte 104
+.byte 105
+.byte 99
+.byte 104
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 101
+.byte 110
+.byte 100
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 0
+.align 0
+L.989:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 99
+.byte 97
+.byte 112
+.byte 97
+.byte 98
+.byte 105
+.byte 108
+.byte 105
+.byte 116
+.byte 105
+.byte 101
+.byte 115
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 103
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 121
+.byte 111
+.byte 110
+.byte 100
+.byte 32
+.byte 97
+.byte 110
+.byte 32
+.byte 101
+.byte 97
+.byte 114
+.byte 108
+.byte 105
+.byte 101
+.byte 114
+.byte 0
+.align 0
+L.988:
+.byte 70
+.byte 97
+.byte 105
+.byte 108
+.byte 117
+.byte 114
+.byte 101
+.byte 115
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 115
+.byte 101
+.byte 113
+.byte 117
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.987:
+.byte 32
+.byte 32
+.byte 32
+.byte 70
+.byte 65
+.byte 73
+.byte 76
+.byte 85
+.byte 82
+.byte 69
+.byte 115
+.byte 44
+.byte 32
+.byte 108
+.byte 105
+.byte 107
+.byte 101
+.byte 32
+.byte 50
+.byte 43
+.byte 50
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 53
+.byte 32
+.byte 46
+.byte 0
+.align 0
+L.986:
+.byte 32
+.byte 32
+.byte 32
+.byte 83
+.byte 101
+.byte 114
+.byte 105
+.byte 111
+.byte 117
+.byte 115
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 115
+.byte 44
+.byte 32
+.byte 108
+.byte 105
+.byte 107
+.byte 101
+.byte 32
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 97
+.byte 32
+.byte 103
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 44
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 0
+.align 0
+L.985:
+.byte 32
+.byte 32
+.byte 32
+.byte 70
+.byte 76
+.byte 65
+.byte 87
+.byte 115
+.byte 44
+.byte 32
+.byte 108
+.byte 105
+.byte 107
+.byte 101
+.byte 32
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 97
+.byte 32
+.byte 115
+.byte 116
+.byte 105
+.byte 99
+.byte 107
+.byte 121
+.byte 32
+.byte 98
+.byte 105
+.byte 116
+.byte 44
+.byte 0
+.align 0
+L.984:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 97
+.byte 116
+.byte 116
+.byte 101
+.byte 109
+.byte 112
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 114
+.byte 105
+.byte 109
+.byte 105
+.byte 110
+.byte 97
+.byte 116
+.byte 101
+.byte 32
+.byte 97
+.byte 109
+.byte 111
+.byte 110
+.byte 103
+.byte 0
+.align 0
+L.981:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 68
+.byte 101
+.byte 99
+.byte 105
+.byte 109
+.byte 97
+.byte 108
+.byte 45
+.byte 66
+.byte 105
+.byte 110
+.byte 97
+.byte 114
+.byte 121
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 118
+.byte 101
+.byte 114
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 78
+.byte 79
+.byte 84
+.byte 32
+.byte 89
+.byte 69
+.byte 84
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 97
+.byte 99
+.byte 99
+.byte 117
+.byte 114
+.byte 97
+.byte 99
+.byte 121
+.byte 46
+.byte 0
+.align 0
+L.980:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 69
+.byte 120
+.byte 116
+.byte 114
+.byte 97
+.byte 45
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 101
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 101
+.byte 120
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 101
+.byte 118
+.byte 101
+.byte 97
+.byte 108
+.byte 101
+.byte 100
+.byte 32
+.byte 98
+.byte 117
+.byte 116
+.byte 32
+.byte 78
+.byte 79
+.byte 84
+.byte 32
+.byte 89
+.byte 69
+.byte 84
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 101
+.byte 100
+.byte 46
+.byte 0
+.align 0
+L.979:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 83
+.byte 113
+.byte 114
+.byte 116
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 101
+.byte 100
+.byte 46
+.byte 32
+.byte 32
+.byte 89
+.byte 94
+.byte 88
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 101
+.byte 100
+.byte 46
+.byte 0
+.align 0
+L.978:
+.byte 9
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 116
+.byte 97
+.byte 109
+.byte 105
+.byte 110
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 112
+.byte 115
+.byte 101
+.byte 117
+.byte 100
+.byte 111
+.byte 45
+.byte 122
+.byte 101
+.byte 114
+.byte 111
+.byte 115
+.byte 46
+.byte 0
+.align 0
+L.977:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 99
+.byte 104
+.byte 101
+.byte 99
+.byte 107
+.byte 101
+.byte 100
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 115
+.byte 105
+.byte 115
+.byte 116
+.byte 101
+.byte 110
+.byte 99
+.byte 121
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 0
+.align 0
+L.976:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 86
+.byte 48
+.byte 32
+.byte 32
+.byte 116
+.byte 101
+.byte 108
+.byte 108
+.byte 115
+.byte 44
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 108
+.byte 121
+.byte 44
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 32
+.byte 73
+.byte 110
+.byte 102
+.byte 105
+.byte 110
+.byte 105
+.byte 116
+.byte 121
+.byte 32
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 114
+.byte 101
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 101
+.byte 110
+.byte 116
+.byte 101
+.byte 100
+.byte 46
+.byte 0
+.align 0
+L.975:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 86
+.byte 32
+.byte 61
+.byte 32
+.byte 97
+.byte 110
+.byte 32
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 44
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 108
+.byte 121
+.byte 46
+.byte 0
+.align 0
+L.974:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 69
+.byte 48
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 80
+.byte 115
+.byte 101
+.byte 117
+.byte 100
+.byte 111
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 116
+.byte 101
+.byte 108
+.byte 108
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 97
+.byte 98
+.byte 114
+.byte 117
+.byte 112
+.byte 116
+.byte 44
+.byte 32
+.byte 103
+.byte 114
+.byte 97
+.byte 100
+.byte 117
+.byte 97
+.byte 108
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 102
+.byte 117
+.byte 122
+.byte 122
+.byte 121
+.byte 46
+.byte 0
+.align 0
+L.973:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 84
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 61
+.byte 32
+.byte 97
+.byte 110
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 46
+.byte 0
+.align 0
+L.972:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 87
+.byte 104
+.byte 101
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 97
+.byte 32
+.byte 83
+.byte 116
+.byte 105
+.byte 99
+.byte 107
+.byte 121
+.byte 32
+.byte 66
+.byte 105
+.byte 116
+.byte 32
+.byte 117
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 105
+.byte 110
+.byte 103
+.byte 46
+.byte 0
+.align 0
+L.971:
+.byte 9
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 46
+.byte 44
+.byte 32
+.byte 68
+.byte 105
+.byte 118
+.byte 46
+.byte 44
+.byte 32
+.byte 65
+.byte 100
+.byte 100
+.byte 47
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 46
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 83
+.byte 113
+.byte 114
+.byte 116
+.byte 46
+.byte 0
+.align 0
+L.970:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 87
+.byte 104
+.byte 101
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 44
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 100
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 115
+.byte 111
+.byte 109
+.byte 101
+.byte 116
+.byte 104
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 101
+.byte 108
+.byte 115
+.byte 101
+.byte 0
+.align 0
+L.969:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 65
+.byte 100
+.byte 101
+.byte 113
+.byte 117
+.byte 97
+.byte 99
+.byte 121
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 103
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 46
+.byte 44
+.byte 32
+.byte 68
+.byte 105
+.byte 118
+.byte 46
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 46
+.byte 0
+.align 0
+L.968:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 85
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 49
+.byte 47
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 94
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 61
+.byte 32
+.byte 79
+.byte 110
+.byte 101
+.byte 32
+.byte 85
+.byte 108
+.byte 112
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 108
+.byte 105
+.byte 116
+.byte 116
+.byte 108
+.byte 101
+.byte 32
+.byte 108
+.byte 101
+.byte 115
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 110
+.byte 32
+.byte 49
+.byte 46
+.byte 48
+.byte 32
+.byte 46
+.byte 0
+.align 0
+L.967:
+.byte 9
+.byte 40
+.byte 79
+.byte 110
+.byte 101
+.byte 85
+.byte 108
+.byte 112
+.byte 110
+.byte 105
+.byte 116
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 76
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 80
+.byte 108
+.byte 97
+.byte 99
+.byte 101
+.byte 41
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 49
+.byte 46
+.byte 48
+.byte 48
+.byte 48
+.byte 120
+.byte 120
+.byte 120
+.byte 32
+.byte 46
+.byte 0
+.align 0
+L.966:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 85
+.byte 50
+.byte 32
+.byte 61
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 47
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 94
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 61
+.byte 32
+.byte 79
+.byte 110
+.byte 101
+.byte 32
+.byte 85
+.byte 108
+.byte 112
+.byte 0
+.align 0
+L.965:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 61
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 105
+.byte 102
+.byte 105
+.byte 99
+.byte 97
+.byte 110
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 99
+.byte 97
+.byte 114
+.byte 114
+.byte 105
+.byte 101
+.byte 100
+.byte 46
+.byte 0
+.align 0
+L.964:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 49
+.byte 44
+.byte 32
+.byte 50
+.byte 44
+.byte 32
+.byte 52
+.byte 44
+.byte 32
+.byte 56
+.byte 44
+.byte 32
+.byte 49
+.byte 48
+.byte 44
+.byte 32
+.byte 49
+.byte 54
+.byte 44
+.byte 32
+.byte 49
+.byte 48
+.byte 48
+.byte 44
+.byte 32
+.byte 50
+.byte 53
+.byte 54
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 0
+.align 0
+L.963:
+.byte 82
+.byte 117
+.byte 110
+.byte 110
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 114
+.byte 101
+.byte 118
+.byte 101
+.byte 97
+.byte 108
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 115
+.byte 101
+.byte 32
+.byte 99
+.byte 104
+.byte 97
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 101
+.byte 114
+.byte 105
+.byte 115
+.byte 116
+.byte 105
+.byte 99
+.byte 115
+.byte 58
+.byte 0
+.align 0
+L.960:
+.byte 9
+.byte 79
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 114
+.byte 101
+.byte 108
+.byte 101
+.byte 118
+.byte 97
+.byte 110
+.byte 116
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 105
+.byte 108
+.byte 101
+.byte 114
+.byte 32
+.byte 111
+.byte 112
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 58
+.byte 0
+.align 0
+L.959:
+.byte 9
+.byte 79
+.byte 112
+.byte 116
+.byte 105
+.byte 109
+.byte 105
+.byte 122
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 108
+.byte 101
+.byte 118
+.byte 101
+.byte 108
+.byte 58
+.byte 10
+.byte 0
+.align 0
+L.958:
+.byte 9
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 105
+.byte 108
+.byte 101
+.byte 114
+.byte 58
+.byte 10
+.byte 0
+.align 0
+L.957:
+.byte 9
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 114
+.byte 58
+.byte 10
+.byte 0
+.align 0
+L.956:
+.byte 9
+.byte 86
+.byte 101
+.byte 114
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 58
+.byte 9
+.byte 49
+.byte 48
+.byte 32
+.byte 70
+.byte 101
+.byte 98
+.byte 114
+.byte 117
+.byte 97
+.byte 114
+.byte 121
+.byte 32
+.byte 49
+.byte 57
+.byte 56
+.byte 57
+.byte 59
+.byte 0
+.align 0
+L.955:
+.byte 9
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 58
+.byte 9
+.byte 100
+.byte 111
+.byte 117
+.byte 98
+.byte 108
+.byte 101
+.byte 59
+.byte 0
+.align 0
+L.954:
+.byte 73
+.byte 110
+.byte 32
+.byte 100
+.byte 111
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 115
+.byte 111
+.byte 44
+.byte 32
+.byte 112
+.byte 108
+.byte 101
+.byte 97
+.byte 115
+.byte 101
+.byte 32
+.byte 105
+.byte 110
+.byte 99
+.byte 108
+.byte 117
+.byte 100
+.byte 101
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 102
+.byte 111
+.byte 108
+.byte 108
+.byte 111
+.byte 119
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 105
+.byte 110
+.byte 102
+.byte 111
+.byte 114
+.byte 109
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 58
+.byte 0
+.align 0
+L.953:
+.byte 9
+.byte 83
+.byte 97
+.byte 110
+.byte 32
+.byte 70
+.byte 114
+.byte 97
+.byte 110
+.byte 99
+.byte 105
+.byte 115
+.byte 99
+.byte 111
+.byte 44
+.byte 32
+.byte 67
+.byte 65
+.byte 32
+.byte 57
+.byte 52
+.byte 49
+.byte 52
+.byte 51
+.byte 45
+.byte 48
+.byte 55
+.byte 48
+.byte 52
+.byte 44
+.byte 32
+.byte 85
+.byte 83
+.byte 65
+.byte 10
+.byte 0
+.align 0
+L.952:
+.byte 9
+.byte 85
+.byte 110
+.byte 105
+.byte 118
+.byte 101
+.byte 114
+.byte 115
+.byte 105
+.byte 116
+.byte 121
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 67
+.byte 97
+.byte 108
+.byte 105
+.byte 102
+.byte 111
+.byte 114
+.byte 110
+.byte 105
+.byte 97
+.byte 0
+.align 0
+L.951:
+.byte 9
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 67
+.byte 101
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 85
+.byte 45
+.byte 55
+.byte 54
+.byte 0
+.align 0
+L.950:
+.byte 9
+.byte 82
+.byte 105
+.byte 99
+.byte 104
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 75
+.byte 97
+.byte 114
+.byte 112
+.byte 105
+.byte 110
+.byte 115
+.byte 107
+.byte 105
+.byte 0
+.align 0
+L.949:
+.byte 80
+.byte 108
+.byte 101
+.byte 97
+.byte 115
+.byte 101
+.byte 32
+.byte 115
+.byte 101
+.byte 110
+.byte 100
+.byte 32
+.byte 115
+.byte 117
+.byte 103
+.byte 103
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 105
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 114
+.byte 101
+.byte 115
+.byte 117
+.byte 108
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 0
+.align 0
+L.948:
+.byte 99
+.byte 111
+.byte 112
+.byte 101
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 117
+.byte 110
+.byte 97
+.byte 110
+.byte 116
+.byte 105
+.byte 99
+.byte 105
+.byte 112
+.byte 97
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 110
+.byte 101
+.byte 119
+.byte 108
+.byte 121
+.byte 32
+.byte 117
+.byte 110
+.byte 99
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 112
+.byte 97
+.byte 116
+.byte 104
+.byte 111
+.byte 108
+.byte 111
+.byte 103
+.byte 105
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.947:
+.byte 85
+.byte 115
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 105
+.byte 110
+.byte 118
+.byte 105
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 104
+.byte 101
+.byte 108
+.byte 112
+.byte 32
+.byte 100
+.byte 101
+.byte 98
+.byte 117
+.byte 103
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 97
+.byte 117
+.byte 103
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 115
+.byte 111
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 119
+.byte 105
+.byte 108
+.byte 108
+.byte 0
+.align 0
+L.944:
+.byte 65
+.byte 110
+.byte 115
+.byte 119
+.byte 101
+.byte 114
+.byte 32
+.byte 113
+.byte 117
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 89
+.byte 44
+.byte 32
+.byte 121
+.byte 44
+.byte 32
+.byte 78
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 110
+.byte 32
+.byte 40
+.byte 117
+.byte 110
+.byte 108
+.byte 101
+.byte 115
+.byte 115
+.byte 32
+.byte 111
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 119
+.byte 105
+.byte 115
+.byte 101
+.byte 32
+.byte 105
+.byte 110
+.byte 100
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 101
+.byte 100
+.byte 41
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.943:
+.byte 97
+.byte 109
+.byte 101
+.byte 110
+.byte 100
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 109
+.byte 97
+.byte 107
+.byte 101
+.byte 32
+.byte 102
+.byte 117
+.byte 114
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 101
+.byte 115
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.942:
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 97
+.byte 110
+.byte 121
+.byte 119
+.byte 97
+.byte 121
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 115
+.byte 101
+.byte 101
+.byte 32
+.byte 104
+.byte 111
+.byte 119
+.byte 32
+.byte 109
+.byte 97
+.byte 110
+.byte 121
+.byte 32
+.byte 109
+.byte 105
+.byte 108
+.byte 101
+.byte 115
+.byte 116
+.byte 111
+.byte 110
+.byte 101
+.byte 115
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 112
+.byte 97
+.byte 115
+.byte 115
+.byte 101
+.byte 115
+.byte 44
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 110
+.byte 0
+.align 0
+L.941:
+.byte 119
+.byte 97
+.byte 114
+.byte 110
+.byte 105
+.byte 110
+.byte 103
+.byte 46
+.byte 32
+.byte 32
+.byte 73
+.byte 102
+.byte 32
+.byte 112
+.byte 101
+.byte 114
+.byte 115
+.byte 117
+.byte 97
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 118
+.byte 97
+.byte 105
+.byte 108
+.byte 115
+.byte 32
+.byte 110
+.byte 97
+.byte 117
+.byte 103
+.byte 104
+.byte 116
+.byte 44
+.byte 32
+.byte 100
+.byte 111
+.byte 110
+.byte 39
+.byte 116
+.byte 32
+.byte 100
+.byte 101
+.byte 115
+.byte 112
+.byte 97
+.byte 105
+.byte 114
+.byte 32
+.byte 98
+.byte 117
+.byte 116
+.byte 32
+.byte 114
+.byte 117
+.byte 110
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 0
+.align 0
+L.940:
+.byte 116
+.byte 111
+.byte 32
+.byte 112
+.byte 101
+.byte 114
+.byte 115
+.byte 101
+.byte 118
+.byte 101
+.byte 114
+.byte 101
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 97
+.byte 32
+.byte 115
+.byte 117
+.byte 114
+.byte 114
+.byte 111
+.byte 103
+.byte 97
+.byte 116
+.byte 101
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 97
+.byte 102
+.byte 116
+.byte 101
+.byte 114
+.byte 44
+.byte 32
+.byte 112
+.byte 101
+.byte 114
+.byte 104
+.byte 97
+.byte 112
+.byte 115
+.byte 44
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 112
+.byte 108
+.byte 97
+.byte 121
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 115
+.byte 111
+.byte 109
+.byte 101
+.byte 0
+.align 0
+L.939:
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 108
+.byte 105
+.byte 107
+.byte 101
+.byte 32
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 47
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 111
+.byte 99
+.byte 99
+.byte 117
+.byte 114
+.byte 115
+.byte 44
+.byte 32
+.byte 98
+.byte 117
+.byte 116
+.byte 32
+.byte 114
+.byte 97
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 0
+.align 0
+L.938:
+.byte 116
+.byte 114
+.byte 121
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 112
+.byte 101
+.byte 114
+.byte 115
+.byte 117
+.byte 97
+.byte 100
+.byte 101
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 78
+.byte 79
+.byte 84
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 116
+.byte 101
+.byte 114
+.byte 109
+.byte 105
+.byte 110
+.byte 97
+.byte 116
+.byte 101
+.byte 32
+.byte 101
+.byte 120
+.byte 101
+.byte 99
+.byte 117
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 110
+.byte 32
+.byte 97
+.byte 110
+.byte 0
+.align 0
+L.937:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 96
+.byte 69
+.byte 78
+.byte 68
+.byte 32
+.byte 79
+.byte 70
+.byte 32
+.byte 84
+.byte 69
+.byte 83
+.byte 84
+.byte 39
+.byte 44
+.byte 10
+.byte 0
+.align 0
+L.936:
+.byte 76
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 115
+.byte 116
+.byte 111
+.byte 112
+.byte 32
+.byte 112
+.byte 114
+.byte 101
+.byte 109
+.byte 97
+.byte 116
+.byte 117
+.byte 114
+.byte 101
+.byte 108
+.byte 121
+.byte 44
+.byte 32
+.byte 105
+.byte 46
+.byte 101
+.byte 46
+.byte 32
+.byte 98
+.byte 101
+.byte 102
+.byte 111
+.byte 114
+.byte 101
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 112
+.byte 108
+.byte 97
+.byte 121
+.byte 105
+.byte 110
+.byte 103
+.byte 10
+.byte 0
+.align 0
+L.933:
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.928:
+.byte 32
+.byte 32
+.byte 32
+.byte 80
+.byte 76
+.byte 69
+.byte 65
+.byte 83
+.byte 69
+.byte 32
+.byte 78
+.byte 79
+.byte 84
+.byte 73
+.byte 70
+.byte 89
+.byte 32
+.byte 75
+.byte 65
+.byte 82
+.byte 80
+.byte 73
+.byte 78
+.byte 75
+.byte 83
+.byte 73
+.byte 33
+.byte 10
+.byte 0
+.align 0
+L.927:
+.byte 37
+.byte 115
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 105
+.byte 110
+.byte 99
+.byte 111
+.byte 110
+.byte 115
+.byte 105
+.byte 115
+.byte 116
+.byte 101
+.byte 110
+.byte 116
+.byte 46
+.byte 46
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.925:
+.byte 9
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 90
+.byte 32
+.byte 42
+.byte 32
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.924:
+.byte 9
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 49
+.byte 32
+.byte 42
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.923:
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 100
+.byte 111
+.byte 101
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 109
+.byte 117
+.byte 116
+.byte 101
+.byte 33
+.byte 10
+.byte 0
+.align 0
+L.918:
+.byte 90
+.byte 32
+.byte 47
+.byte 32
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.915:
+.byte 49
+.byte 32
+.byte 42
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 37
+.byte 103
+.byte 10
+.byte 0
+.align 0
+L.912:
+.byte 90
+.byte 32
+.byte 42
+.byte 32
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 0
+.align 0
+L.909:
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 9
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 101
+.byte 115
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 32
+.byte 0
+.align 0
+L.908:
+.byte 87
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 112
+.byte 114
+.byte 105
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 0
+.align 0
+L.903:
+.byte 84
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 33
+.byte 10
+.byte 0
+.align 0
+L.900:
+.byte 84
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 86
+.byte 69
+.byte 82
+.byte 89
+.byte 32
+.byte 83
+.byte 69
+.byte 82
+.byte 73
+.byte 79
+.byte 85
+.byte 83
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 33
+.byte 10
+.byte 0
+.align 0
+L.894:
+.byte 32
+.byte 104
+.byte 97
+.byte 115
+.byte 32
+.byte 78
+.byte 79
+.byte 84
+.byte 32
+.byte 106
+.byte 117
+.byte 115
+.byte 116
+.byte 32
+.byte 98
+.byte 101
+.byte 101
+.byte 110
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 97
+.byte 108
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.893:
+.byte 84
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 79
+.byte 46
+.byte 75
+.byte 46
+.byte 44
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 118
+.byte 105
+.byte 100
+.byte 101
+.byte 100
+.byte 32
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 47
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 0
+.align 0
+L.890:
+.byte 87
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 109
+.byte 97
+.byte 99
+.byte 104
+.byte 105
+.byte 110
+.byte 101
+.byte 32
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 40
+.byte 90
+.byte 32
+.byte 43
+.byte 32
+.byte 90
+.byte 41
+.byte 32
+.byte 47
+.byte 32
+.byte 90
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.886:
+.byte 40
+.byte 90
+.byte 32
+.byte 43
+.byte 32
+.byte 90
+.byte 41
+.byte 32
+.byte 47
+.byte 32
+.byte 90
+.byte 32
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 115
+.byte 97
+.byte 102
+.byte 101
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.885:
+.byte 83
+.byte 105
+.byte 110
+.byte 99
+.byte 101
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 100
+.byte 101
+.byte 110
+.byte 105
+.byte 101
+.byte 115
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 101
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 0
+.align 0
+L.881:
+.byte 83
+.byte 105
+.byte 109
+.byte 105
+.byte 108
+.byte 97
+.byte 114
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 114
+.byte 101
+.byte 112
+.byte 97
+.byte 110
+.byte 99
+.byte 105
+.byte 101
+.byte 115
+.byte 32
+.byte 104
+.byte 97
+.byte 118
+.byte 101
+.byte 32
+.byte 111
+.byte 99
+.byte 99
+.byte 117
+.byte 114
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 116
+.byte 105
+.byte 109
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.871:
+.byte 9
+.byte 9
+.byte 116
+.byte 104
+.byte 101
+.byte 121
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.870:
+.byte 9
+.byte 119
+.byte 104
+.byte 105
+.byte 99
+.byte 104
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 117
+.byte 110
+.byte 101
+.byte 113
+.byte 117
+.byte 97
+.byte 108
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 59
+.byte 10
+.byte 0
+.align 0
+L.869:
+.byte 9
+.byte 121
+.byte 105
+.byte 101
+.byte 108
+.byte 100
+.byte 101
+.byte 100
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 59
+.byte 10
+.byte 0
+.align 0
+L.868:
+.byte 9
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 32
+.byte 94
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 10
+.byte 0
+.align 0
+L.867:
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 10
+.byte 0
+.align 0
+L.866:
+.byte 87
+.byte 65
+.byte 82
+.byte 78
+.byte 73
+.byte 78
+.byte 71
+.byte 58
+.byte 32
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 10
+.byte 0
+.align 0
+L.848:
+.byte 9
+.byte 105
+.byte 110
+.byte 115
+.byte 116
+.byte 101
+.byte 97
+.byte 100
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 48
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.847:
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 40
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 32
+.byte 45
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 3
+L.839:
+.long 0x88e368f1
+.long 0x3ed4f8b5
+.align 0
+L.837:
+.byte 37
+.byte 115
+.byte 58
+.byte 32
+.byte 32
+.byte 37
+.byte 115
+.byte 0
+.align 0
+L.836:
+.byte 70
+.byte 76
+.byte 65
+.byte 87
+.byte 0
+.align 0
+L.835:
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 0
+.align 0
+L.834:
+.byte 83
+.byte 69
+.byte 82
+.byte 73
+.byte 79
+.byte 85
+.byte 83
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 0
+.align 0
+L.833:
+.byte 70
+.byte 65
+.byte 73
+.byte 76
+.byte 85
+.byte 82
+.byte 69
+.byte 0
+.align 0
+L.827:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 80
+.byte 97
+.byte 103
+.byte 101
+.byte 58
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 10
+.byte 0
+.align 0
+L.826:
+.byte 10
+.byte 68
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 105
+.byte 115
+.byte 32
+.byte 114
+.byte 101
+.byte 115
+.byte 117
+.byte 109
+.byte 101
+.byte 115
+.byte 32
+.byte 97
+.byte 102
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 109
+.byte 105
+.byte 108
+.byte 101
+.byte 115
+.byte 116
+.byte 111
+.byte 110
+.byte 101
+.byte 32
+.byte 78
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 32
+.byte 37
+.byte 100
+.byte 0
+.align 3
+L.824:
+.long 0x0
+.long 0xbff00000
+.align 0
+L.819:
+.byte 69
+.byte 78
+.byte 68
+.byte 32
+.byte 79
+.byte 70
+.byte 32
+.byte 84
+.byte 69
+.byte 83
+.byte 84
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.818:
+.byte 10
+.byte 65
+.byte 32
+.byte 116
+.byte 111
+.byte 116
+.byte 97
+.byte 108
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 102
+.byte 108
+.byte 111
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 112
+.byte 111
+.byte 105
+.byte 110
+.byte 116
+.byte 32
+.byte 101
+.byte 120
+.byte 99
+.byte 101
+.byte 112
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 119
+.byte 101
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 101
+.byte 103
+.byte 105
+.byte 115
+.byte 116
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.815:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 69
+.byte 120
+.byte 99
+.byte 101
+.byte 108
+.byte 108
+.byte 101
+.byte 110
+.byte 116
+.byte 33
+.byte 10
+.byte 0
+.align 0
+L.814:
+.byte 32
+.byte 100
+.byte 117
+.byte 114
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 71
+.byte 114
+.byte 97
+.byte 100
+.byte 117
+.byte 97
+.byte 108
+.byte 32
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.813:
+.byte 44
+.byte 10
+.byte 101
+.byte 120
+.byte 99
+.byte 101
+.byte 112
+.byte 116
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 112
+.byte 111
+.byte 115
+.byte 115
+.byte 105
+.byte 98
+.byte 108
+.byte 121
+.byte 32
+.byte 68
+.byte 111
+.byte 117
+.byte 98
+.byte 108
+.byte 101
+.byte 32
+.byte 82
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 105
+.byte 110
+.byte 103
+.byte 0
+.align 0
+L.812:
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.809:
+.byte 56
+.byte 53
+.byte 52
+.byte 0
+.align 0
+L.808:
+.byte 55
+.byte 53
+.byte 52
+.byte 0
+.align 0
+L.805:
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 112
+.byte 111
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 73
+.byte 69
+.byte 69
+.byte 69
+.byte 32
+.byte 115
+.byte 116
+.byte 97
+.byte 110
+.byte 100
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 80
+.byte 0
+.align 0
+L.804:
+.byte 82
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 111
+.byte 114
+.byte 109
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 0
+.align 0
+L.801:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 115
+.byte 101
+.byte 101
+.byte 109
+.byte 115
+.byte 32
+.byte 83
+.byte 97
+.byte 116
+.byte 105
+.byte 115
+.byte 102
+.byte 97
+.byte 99
+.byte 116
+.byte 111
+.byte 114
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.795:
+.byte 78
+.byte 111
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 117
+.byte 114
+.byte 101
+.byte 115
+.byte 44
+.byte 32
+.byte 100
+.byte 101
+.byte 102
+.byte 101
+.byte 99
+.byte 116
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 102
+.byte 108
+.byte 97
+.byte 119
+.byte 115
+.byte 32
+.byte 104
+.byte 97
+.byte 118
+.byte 101
+.byte 32
+.byte 98
+.byte 101
+.byte 101
+.byte 110
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.794:
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 39
+.byte 115
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 115
+.byte 101
+.byte 113
+.byte 117
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.793:
+.byte 80
+.byte 111
+.byte 116
+.byte 101
+.byte 110
+.byte 116
+.byte 105
+.byte 97
+.byte 108
+.byte 108
+.byte 121
+.byte 32
+.byte 102
+.byte 97
+.byte 116
+.byte 97
+.byte 108
+.byte 32
+.byte 70
+.byte 65
+.byte 73
+.byte 76
+.byte 85
+.byte 82
+.byte 69
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 104
+.byte 97
+.byte 118
+.byte 101
+.byte 32
+.byte 115
+.byte 112
+.byte 111
+.byte 105
+.byte 108
+.byte 101
+.byte 100
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 0
+.align 0
+L.790:
+.byte 117
+.byte 110
+.byte 97
+.byte 99
+.byte 99
+.byte 101
+.byte 112
+.byte 116
+.byte 97
+.byte 98
+.byte 108
+.byte 101
+.byte 32
+.byte 83
+.byte 101
+.byte 114
+.byte 105
+.byte 111
+.byte 117
+.byte 115
+.byte 32
+.byte 68
+.byte 101
+.byte 102
+.byte 101
+.byte 99
+.byte 116
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.789:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 104
+.byte 97
+.byte 115
+.byte 32
+.byte 0
+.align 0
+L.785:
+.byte 100
+.byte 101
+.byte 115
+.byte 112
+.byte 105
+.byte 116
+.byte 101
+.byte 32
+.byte 105
+.byte 110
+.byte 99
+.byte 111
+.byte 110
+.byte 118
+.byte 101
+.byte 110
+.byte 105
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 68
+.byte 101
+.byte 102
+.byte 101
+.byte 99
+.byte 116
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.784:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 65
+.byte 99
+.byte 99
+.byte 101
+.byte 112
+.byte 116
+.byte 97
+.byte 98
+.byte 108
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.779:
+.byte 83
+.byte 97
+.byte 116
+.byte 105
+.byte 115
+.byte 102
+.byte 97
+.byte 99
+.byte 116
+.byte 111
+.byte 114
+.byte 121
+.byte 32
+.byte 116
+.byte 104
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 32
+.byte 102
+.byte 108
+.byte 97
+.byte 119
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.778:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 115
+.byte 101
+.byte 101
+.byte 109
+.byte 115
+.byte 32
+.byte 0
+.align 0
+L.767:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 32
+.byte 37
+.byte 45
+.byte 50
+.byte 57
+.byte 115
+.byte 32
+.byte 37
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.760:
+.byte 70
+.byte 76
+.byte 65
+.byte 87
+.byte 115
+.byte 32
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 61
+.byte 0
+.align 0
+L.759:
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 115
+.byte 32
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 61
+.byte 0
+.align 0
+L.758:
+.byte 83
+.byte 69
+.byte 82
+.byte 73
+.byte 79
+.byte 85
+.byte 83
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 115
+.byte 32
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 61
+.byte 0
+.align 0
+L.757:
+.byte 70
+.byte 65
+.byte 73
+.byte 76
+.byte 85
+.byte 82
+.byte 69
+.byte 115
+.byte 32
+.byte 32
+.byte 101
+.byte 110
+.byte 99
+.byte 111
+.byte 117
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 61
+.byte 0
+.align 0
+L.753:
+.byte 10
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 84
+.byte 114
+.byte 121
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 32
+.byte 48
+.byte 32
+.byte 47
+.byte 32
+.byte 48
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 100
+.byte 117
+.byte 99
+.byte 101
+.byte 115
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 0
+.align 0
+L.752:
+.byte 32
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.749:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 84
+.byte 114
+.byte 121
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 32
+.byte 49
+.byte 32
+.byte 47
+.byte 32
+.byte 48
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 100
+.byte 117
+.byte 99
+.byte 101
+.byte 115
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 0
+.align 0
+L.748:
+.byte 87
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 109
+.byte 101
+.byte 115
+.byte 115
+.byte 97
+.byte 103
+.byte 101
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 47
+.byte 111
+.byte 114
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 115
+.byte 32
+.byte 100
+.byte 111
+.byte 101
+.byte 115
+.byte 32
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 100
+.byte 117
+.byte 99
+.byte 101
+.byte 63
+.byte 10
+.byte 0
+.align 0
+L.747:
+.byte 32
+.byte 32
+.byte 105
+.byte 110
+.byte 115
+.byte 116
+.byte 101
+.byte 97
+.byte 100
+.byte 44
+.byte 32
+.byte 88
+.byte 32
+.byte 47
+.byte 32
+.byte 88
+.byte 32
+.byte 45
+.byte 32
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 45
+.byte 32
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.746:
+.byte 32
+.byte 32
+.byte 88
+.byte 32
+.byte 47
+.byte 32
+.byte 88
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 49
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 110
+.byte 32
+.byte 88
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.741:
+.byte 32
+.byte 32
+.byte 88
+.byte 32
+.byte 47
+.byte 32
+.byte 88
+.byte 32
+.byte 32
+.byte 116
+.byte 114
+.byte 97
+.byte 112
+.byte 115
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 110
+.byte 32
+.byte 88
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 103
+.byte 10
+.byte 0
+.align 0
+L.727:
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 102
+.byte 97
+.byte 114
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 49
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.726:
+.byte 32
+.byte 117
+.byte 110
+.byte 98
+.byte 97
+.byte 108
+.byte 97
+.byte 110
+.byte 99
+.byte 101
+.byte 100
+.byte 32
+.byte 114
+.byte 97
+.byte 110
+.byte 103
+.byte 101
+.byte 59
+.byte 32
+.byte 85
+.byte 102
+.byte 84
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 42
+.byte 32
+.byte 86
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 9
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.725:
+.byte 66
+.byte 97
+.byte 100
+.byte 108
+.byte 121
+.byte 0
+.align 0
+L.718:
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 102
+.byte 97
+.byte 114
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 40
+.byte 90
+.byte 41
+.byte 32
+.byte 94
+.byte 32
+.byte 50
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.717:
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.705:
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 102
+.byte 97
+.byte 114
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 40
+.byte 90
+.byte 41
+.byte 32
+.byte 94
+.byte 32
+.byte 50
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.704:
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 119
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 112
+.byte 114
+.byte 105
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.687:
+.byte 43
+.byte 45
+.byte 37
+.byte 103
+.byte 44
+.byte 32
+.byte 43
+.byte 45
+.byte 37
+.byte 103
+.byte 10
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 43
+.byte 45
+.byte 37
+.byte 103
+.byte 32
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 117
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 46
+.byte 0
+.align 0
+L.686:
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 105
+.byte 110
+.byte 118
+.byte 111
+.byte 108
+.byte 118
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 0
+.align 0
+L.680:
+.byte 97
+.byte 98
+.byte 111
+.byte 118
+.byte 101
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.679:
+.byte 65
+.byte 110
+.byte 121
+.byte 32
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 97
+.byte 108
+.byte 32
+.byte 115
+.byte 101
+.byte 112
+.byte 97
+.byte 114
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 42
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 111
+.byte 110
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.678:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 86
+.byte 32
+.byte 47
+.byte 32
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.677:
+.byte 78
+.byte 111
+.byte 32
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 97
+.byte 108
+.byte 101
+.byte 100
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 86
+.byte 32
+.byte 42
+.byte 32
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.676:
+.byte 84
+.byte 104
+.byte 101
+.byte 114
+.byte 101
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 32
+.byte 115
+.byte 97
+.byte 116
+.byte 117
+.byte 114
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 98
+.byte 101
+.byte 99
+.byte 97
+.byte 117
+.byte 115
+.byte 101
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 115
+.byte 121
+.byte 115
+.byte 116
+.byte 101
+.byte 109
+.byte 32
+.byte 116
+.byte 114
+.byte 97
+.byte 112
+.byte 115
+.byte 32
+.byte 111
+.byte 110
+.byte 32
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.675:
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 115
+.byte 97
+.byte 116
+.byte 117
+.byte 114
+.byte 97
+.byte 116
+.byte 101
+.byte 115
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 86
+.byte 48
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.672:
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 86
+.byte 32
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.663:
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 112
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 9
+.byte 115
+.byte 104
+.byte 114
+.byte 105
+.byte 110
+.byte 107
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.660:
+.byte 45
+.byte 40
+.byte 45
+.byte 89
+.byte 41
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 89
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.659:
+.byte 102
+.byte 105
+.byte 110
+.byte 100
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 0
+.align 0
+L.658:
+.byte 83
+.byte 101
+.byte 101
+.byte 109
+.byte 115
+.byte 32
+.byte 79
+.byte 46
+.byte 75
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.655:
+.byte 84
+.byte 114
+.byte 121
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 111
+.byte 110
+.byte 32
+.byte 89
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.654:
+.byte 67
+.byte 97
+.byte 110
+.byte 32
+.byte 96
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 45
+.byte 89
+.byte 39
+.byte 32
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 63
+.byte 10
+.byte 0
+.align 0
+L.647:
+.byte 84
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 103
+.byte 101
+.byte 110
+.byte 101
+.byte 114
+.byte 97
+.byte 116
+.byte 101
+.byte 32
+.byte 97
+.byte 110
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.646:
+.byte 83
+.byte 101
+.byte 97
+.byte 114
+.byte 99
+.byte 104
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 58
+.byte 10
+.byte 0
+.align 0
+L.645:
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 32
+.byte 110
+.byte 111
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 114
+.byte 101
+.byte 112
+.byte 97
+.byte 110
+.byte 99
+.byte 105
+.byte 101
+.byte 115
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.637:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 112
+.byte 111
+.byte 119
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 90
+.byte 94
+.byte 81
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 114
+.byte 32
+.byte 110
+.byte 101
+.byte 97
+.byte 114
+.byte 108
+.byte 121
+.byte 32
+.byte 101
+.byte 120
+.byte 116
+.byte 114
+.byte 101
+.byte 109
+.byte 101
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.636:
+.byte 65
+.byte 99
+.byte 99
+.byte 117
+.byte 114
+.byte 97
+.byte 99
+.byte 121
+.byte 32
+.byte 115
+.byte 101
+.byte 101
+.byte 109
+.byte 115
+.byte 32
+.byte 97
+.byte 100
+.byte 101
+.byte 113
+.byte 117
+.byte 97
+.byte 116
+.byte 101
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.629:
+.byte 9
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 105
+.byte 110
+.byte 118
+.byte 111
+.byte 108
+.byte 118
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 105
+.byte 110
+.byte 121
+.byte 32
+.byte 105
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 114
+.byte 97
+.byte 116
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.628:
+.byte 9
+.byte 84
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 109
+.byte 117
+.byte 99
+.byte 104
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 115
+.byte 112
+.byte 111
+.byte 105
+.byte 108
+.byte 32
+.byte 102
+.byte 105
+.byte 110
+.byte 97
+.byte 110
+.byte 99
+.byte 105
+.byte 97
+.byte 108
+.byte 10
+.byte 0
+.align 0
+L.627:
+.byte 9
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.626:
+.byte 9
+.byte 40
+.byte 49
+.byte 32
+.byte 43
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 32
+.byte 94
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 59
+.byte 10
+.byte 0
+.align 0
+L.625:
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 10
+.byte 0
+.align 0
+L.624:
+.byte 67
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 101
+.byte 100
+.byte 0
+.align 0
+L.617:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 88
+.byte 94
+.byte 40
+.byte 40
+.byte 88
+.byte 32
+.byte 43
+.byte 32
+.byte 49
+.byte 41
+.byte 32
+.byte 47
+.byte 32
+.byte 40
+.byte 88
+.byte 32
+.byte 45
+.byte 32
+.byte 49
+.byte 41
+.byte 41
+.byte 32
+.byte 118
+.byte 115
+.byte 46
+.byte 32
+.byte 101
+.byte 120
+.byte 112
+.byte 40
+.byte 50
+.byte 41
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 88
+.byte 32
+.byte 45
+.byte 62
+.byte 32
+.byte 49
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.613:
+.byte 84
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 79
+.byte 46
+.byte 75
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.610:
+.byte 32
+.byte 32
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.609:
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 98
+.byte 101
+.byte 116
+.byte 119
+.byte 101
+.byte 101
+.byte 110
+.byte 32
+.byte 48
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 10
+.byte 0
+.align 0
+L.605:
+.byte 97
+.byte 99
+.byte 116
+.byte 117
+.byte 97
+.byte 108
+.byte 108
+.byte 121
+.byte 32
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 121
+.byte 105
+.byte 101
+.byte 108
+.byte 100
+.byte 115
+.byte 58
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.604:
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 97
+.byte 102
+.byte 102
+.byte 108
+.byte 105
+.byte 99
+.byte 116
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 101
+.byte 120
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 10
+.byte 9
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 32
+.byte 94
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 59
+.byte 10
+.byte 0
+.align 0
+L.603:
+.byte 85
+.byte 102
+.byte 84
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 61
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 32
+.byte 94
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 10
+.byte 111
+.byte 110
+.byte 108
+.byte 121
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 0
+.align 0
+L.602:
+.byte 83
+.byte 105
+.byte 110
+.byte 99
+.byte 101
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 111
+.byte 99
+.byte 99
+.byte 117
+.byte 114
+.byte 115
+.byte 32
+.byte 98
+.byte 101
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.601:
+.byte 82
+.byte 97
+.byte 110
+.byte 103
+.byte 101
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 110
+.byte 97
+.byte 114
+.byte 114
+.byte 111
+.byte 119
+.byte 59
+.byte 32
+.byte 85
+.byte 49
+.byte 94
+.byte 37
+.byte 100
+.byte 32
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.596:
+.byte 109
+.byte 101
+.byte 114
+.byte 101
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 111
+.byte 102
+.byte 102
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.595:
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 115
+.byte 117
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 32
+.byte 108
+.byte 97
+.byte 114
+.byte 103
+.byte 101
+.byte 114
+.byte 32
+.byte 82
+.byte 101
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 110
+.byte 32
+.byte 0
+.align 0
+L.594:
+.byte 32
+.byte 98
+.byte 101
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 119
+.byte 104
+.byte 105
+.byte 99
+.byte 104
+.byte 0
+.align 0
+L.593:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.592:
+.byte 88
+.byte 32
+.byte 47
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 49
+.byte 32
+.byte 43
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.591:
+.byte 88
+.byte 32
+.byte 47
+.byte 32
+.byte 90
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 115
+.byte 33
+.byte 10
+.byte 0
+.align 0
+L.588:
+.byte 101
+.byte 110
+.byte 99
+.byte 111
+.byte 117
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 97
+.byte 108
+.byte 116
+.byte 104
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 32
+.byte 97
+.byte 99
+.byte 116
+.byte 117
+.byte 97
+.byte 108
+.byte 108
+.byte 121
+.byte 10
+.byte 0
+.align 0
+L.587:
+.byte 32
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 32
+.byte 40
+.byte 102
+.byte 40
+.byte 88
+.byte 41
+.byte 32
+.byte 45
+.byte 32
+.byte 102
+.byte 40
+.byte 90
+.byte 41
+.byte 41
+.byte 32
+.byte 47
+.byte 32
+.byte 40
+.byte 88
+.byte 32
+.byte 45
+.byte 32
+.byte 90
+.byte 41
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.586:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 105
+.byte 102
+.byte 32
+.byte 40
+.byte 88
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 90
+.byte 41
+.byte 32
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 32
+.byte 32
+.byte 101
+.byte 108
+.byte 115
+.byte 101
+.byte 0
+.align 0
+L.585:
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 117
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 110
+.byte 32
+.byte 105
+.byte 110
+.byte 110
+.byte 111
+.byte 99
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 115
+.byte 116
+.byte 97
+.byte 116
+.byte 101
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 108
+.byte 105
+.byte 107
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.584:
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 83
+.byte 69
+.byte 82
+.byte 73
+.byte 79
+.byte 85
+.byte 83
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 10
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 99
+.byte 97
+.byte 117
+.byte 115
+.byte 101
+.byte 115
+.byte 32
+.byte 0
+.align 0
+L.583:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 83
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 78
+.byte 79
+.byte 84
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 97
+.byte 108
+.byte 32
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 44
+.byte 32
+.byte 0
+.align 0
+L.582:
+.byte 121
+.byte 101
+.byte 116
+.byte 32
+.byte 88
+.byte 32
+.byte 45
+.byte 32
+.byte 90
+.byte 32
+.byte 121
+.byte 105
+.byte 101
+.byte 108
+.byte 100
+.byte 115
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.581:
+.byte 88
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 9
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 101
+.byte 113
+.byte 117
+.byte 97
+.byte 108
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.576:
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 47
+.byte 32
+.byte 85
+.byte 102
+.byte 84
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 101
+.byte 100
+.byte 33
+.byte 10
+.byte 0
+.align 0
+L.567:
+.byte 40
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 111
+.byte 102
+.byte 102
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 85
+.byte 102
+.byte 84
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 41
+.byte 32
+.byte 60
+.byte 32
+.byte 69
+.byte 48
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.566:
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 103
+.byte 114
+.byte 97
+.byte 100
+.byte 117
+.byte 97
+.byte 108
+.byte 59
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 105
+.byte 110
+.byte 99
+.byte 117
+.byte 114
+.byte 115
+.byte 32
+.byte 65
+.byte 98
+.byte 115
+.byte 111
+.byte 108
+.byte 117
+.byte 116
+.byte 101
+.byte 32
+.byte 69
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 61
+.byte 10
+.byte 0
+.align 0
+L.561:
+.byte 124
+.byte 81
+.byte 32
+.byte 45
+.byte 32
+.byte 89
+.byte 124
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.560:
+.byte 112
+.byte 114
+.byte 105
+.byte 110
+.byte 116
+.byte 32
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 81
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 89
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.559:
+.byte 81
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 89
+.byte 32
+.byte 119
+.byte 104
+.byte 105
+.byte 108
+.byte 101
+.byte 32
+.byte 100
+.byte 101
+.byte 110
+.byte 121
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 124
+.byte 81
+.byte 32
+.byte 45
+.byte 32
+.byte 89
+.byte 124
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 48
+.byte 59
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 115
+.byte 101
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.558:
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 117
+.byte 115
+.byte 101
+.byte 115
+.byte 32
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 44
+.byte 32
+.byte 119
+.byte 104
+.byte 105
+.byte 99
+.byte 104
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 10
+.byte 0
+.align 0
+L.556:
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 101
+.byte 108
+.byte 115
+.byte 101
+.byte 32
+.byte 109
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 109
+.byte 97
+.byte 110
+.byte 121
+.byte 32
+.byte 108
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 119
+.byte 114
+.byte 111
+.byte 110
+.byte 103
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.555:
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 100
+.byte 111
+.byte 119
+.byte 110
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.554:
+.byte 97
+.byte 112
+.byte 112
+.byte 114
+.byte 111
+.byte 97
+.byte 99
+.byte 104
+.byte 32
+.byte 97
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.553:
+.byte 69
+.byte 105
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 97
+.byte 99
+.byte 99
+.byte 117
+.byte 114
+.byte 97
+.byte 99
+.byte 121
+.byte 32
+.byte 100
+.byte 101
+.byte 116
+.byte 101
+.byte 114
+.byte 105
+.byte 111
+.byte 114
+.byte 97
+.byte 116
+.byte 101
+.byte 115
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.541:
+.byte 83
+.byte 109
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 115
+.byte 116
+.byte 114
+.byte 105
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 112
+.byte 111
+.byte 115
+.byte 105
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 69
+.byte 48
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.540:
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 110
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 100
+.byte 117
+.byte 99
+.byte 116
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.539:
+.byte 68
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 101
+.byte 110
+.byte 99
+.byte 101
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 115
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 97
+.byte 32
+.byte 104
+.byte 105
+.byte 103
+.byte 104
+.byte 101
+.byte 114
+.byte 0
+.align 0
+L.536:
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 110
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 101
+.byte 110
+.byte 99
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.535:
+.byte 80
+.byte 114
+.byte 111
+.byte 100
+.byte 117
+.byte 99
+.byte 116
+.byte 115
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 97
+.byte 32
+.byte 104
+.byte 105
+.byte 103
+.byte 104
+.byte 101
+.byte 114
+.byte 0
+.align 0
+L.528:
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 80
+.byte 115
+.byte 101
+.byte 117
+.byte 100
+.byte 111
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 112
+.byte 114
+.byte 105
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.527:
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 32
+.byte 115
+.byte 116
+.byte 105
+.byte 99
+.byte 107
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 97
+.byte 110
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 100
+.byte 108
+.byte 121
+.byte 32
+.byte 112
+.byte 111
+.byte 115
+.byte 105
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.526:
+.byte 112
+.byte 111
+.byte 115
+.byte 105
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 44
+.byte 32
+.byte 105
+.byte 115
+.byte 110
+.byte 39
+.byte 116
+.byte 59
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 112
+.byte 114
+.byte 105
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.525:
+.byte 66
+.byte 117
+.byte 116
+.byte 32
+.byte 45
+.byte 80
+.byte 115
+.byte 101
+.byte 117
+.byte 100
+.byte 111
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 44
+.byte 32
+.byte 119
+.byte 104
+.byte 105
+.byte 99
+.byte 104
+.byte 32
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 98
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.522:
+.byte 80
+.byte 115
+.byte 101
+.byte 117
+.byte 100
+.byte 111
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 112
+.byte 114
+.byte 105
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 97
+.byte 115
+.byte 58
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.521:
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 100
+.byte 108
+.byte 121
+.byte 32
+.byte 110
+.byte 101
+.byte 103
+.byte 97
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.520:
+.byte 80
+.byte 111
+.byte 115
+.byte 105
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 101
+.byte 120
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 97
+.byte 110
+.byte 10
+.byte 0
+.align 0
+L.507:
+.byte 109
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 109
+.byte 97
+.byte 110
+.byte 121
+.byte 32
+.byte 108
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 119
+.byte 114
+.byte 111
+.byte 110
+.byte 103
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.483:
+.byte 83
+.byte 101
+.byte 101
+.byte 107
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 115
+.byte 32
+.byte 85
+.byte 102
+.byte 84
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 69
+.byte 48
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.480:
+.byte 46
+.byte 46
+.byte 46
+.byte 32
+.byte 110
+.byte 111
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 114
+.byte 101
+.byte 112
+.byte 97
+.byte 110
+.byte 99
+.byte 105
+.byte 115
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.477:
+.byte 9
+.byte 105
+.byte 110
+.byte 118
+.byte 111
+.byte 108
+.byte 118
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 105
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 114
+.byte 97
+.byte 116
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.476:
+.byte 69
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 115
+.byte 32
+.byte 108
+.byte 105
+.byte 107
+.byte 101
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 105
+.byte 110
+.byte 118
+.byte 97
+.byte 108
+.byte 105
+.byte 100
+.byte 97
+.byte 116
+.byte 101
+.byte 32
+.byte 102
+.byte 105
+.byte 110
+.byte 97
+.byte 110
+.byte 99
+.byte 105
+.byte 97
+.byte 108
+.byte 32
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.455:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 112
+.byte 111
+.byte 119
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 90
+.byte 94
+.byte 105
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 115
+.byte 109
+.byte 97
+.byte 108
+.byte 108
+.byte 32
+.byte 73
+.byte 110
+.byte 116
+.byte 101
+.byte 103
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 90
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 105
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.452:
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 32
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 109
+.byte 97
+.byte 110
+.byte 121
+.byte 32
+.byte 108
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 119
+.byte 114
+.byte 111
+.byte 110
+.byte 103
+.byte 0
+.align 0
+L.450:
+.byte 116
+.byte 111
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 117
+.byte 108
+.byte 112
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.449:
+.byte 79
+.byte 98
+.byte 115
+.byte 101
+.byte 114
+.byte 118
+.byte 101
+.byte 100
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 115
+.byte 32
+.byte 114
+.byte 117
+.byte 110
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 0
+.align 0
+L.448:
+.byte 83
+.byte 113
+.byte 117
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 111
+.byte 111
+.byte 116
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 101
+.byte 105
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.445:
+.byte 83
+.byte 113
+.byte 117
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 111
+.byte 111
+.byte 116
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.440:
+.byte 83
+.byte 113
+.byte 117
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 111
+.byte 111
+.byte 116
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.435:
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 115
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 115
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.434:
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 94
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.433:
+.byte 65
+.byte 110
+.byte 111
+.byte 109
+.byte 97
+.byte 108
+.byte 111
+.byte 117
+.byte 115
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 73
+.byte 110
+.byte 116
+.byte 101
+.byte 103
+.byte 101
+.byte 114
+.byte 32
+.byte 60
+.byte 32
+.byte 0
+.align 0
+L.393:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 100
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.371:
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 40
+.byte 88
+.byte 41
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 110
+.byte 45
+.byte 109
+.byte 111
+.byte 110
+.byte 111
+.byte 116
+.byte 111
+.byte 110
+.byte 105
+.byte 99
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 88
+.byte 32
+.byte 110
+.byte 101
+.byte 97
+.byte 114
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.370:
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 32
+.byte 104
+.byte 97
+.byte 115
+.byte 32
+.byte 112
+.byte 97
+.byte 115
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 97
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 77
+.byte 111
+.byte 110
+.byte 111
+.byte 116
+.byte 111
+.byte 110
+.byte 105
+.byte 99
+.byte 105
+.byte 116
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.353:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 32
+.byte 109
+.byte 111
+.byte 110
+.byte 111
+.byte 116
+.byte 111
+.byte 110
+.byte 105
+.byte 99
+.byte 105
+.byte 116
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.342:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 105
+.byte 102
+.byte 32
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 40
+.byte 88
+.byte 32
+.byte 42
+.byte 32
+.byte 88
+.byte 41
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 88
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 73
+.byte 110
+.byte 116
+.byte 101
+.byte 103
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 88
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.337:
+.byte 83
+.byte 113
+.byte 117
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 111
+.byte 111
+.byte 116
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 48
+.byte 46
+.byte 48
+.byte 44
+.byte 32
+.byte 45
+.byte 48
+.byte 46
+.byte 48
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 49
+.byte 46
+.byte 48
+.byte 32
+.byte 119
+.byte 114
+.byte 111
+.byte 110
+.byte 103
+.byte 0
+.align 0
+L.335:
+.byte 10
+.byte 82
+.byte 117
+.byte 110
+.byte 110
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 115
+.byte 113
+.byte 117
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 111
+.byte 111
+.byte 116
+.byte 40
+.byte 120
+.byte 41
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.334:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 78
+.byte 111
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 117
+.byte 114
+.byte 101
+.byte 115
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 105
+.byte 110
+.byte 116
+.byte 101
+.byte 103
+.byte 101
+.byte 114
+.byte 32
+.byte 112
+.byte 97
+.byte 105
+.byte 114
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.333:
+.byte 88
+.byte 32
+.byte 42
+.byte 32
+.byte 89
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 89
+.byte 32
+.byte 42
+.byte 32
+.byte 88
+.byte 32
+.byte 116
+.byte 114
+.byte 105
+.byte 97
+.byte 108
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 3
+L.324:
+.long 0x0
+.long 0x40080000
+.align 0
+L.323:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 111
+.byte 110
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 114
+.byte 97
+.byte 110
+.byte 100
+.byte 111
+.byte 109
+.byte 32
+.byte 112
+.byte 97
+.byte 105
+.byte 114
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.322:
+.byte 68
+.byte 111
+.byte 101
+.byte 115
+.byte 32
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 109
+.byte 117
+.byte 116
+.byte 101
+.byte 63
+.byte 32
+.byte 32
+.byte 0
+.align 0
+L.319:
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 40
+.byte 115
+.byte 41
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 103
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 117
+.byte 114
+.byte 101
+.byte 40
+.byte 115
+.byte 41
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 10
+.byte 40
+.byte 110
+.byte 111
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 97
+.byte 98
+.byte 111
+.byte 118
+.byte 101
+.byte 41
+.byte 32
+.byte 99
+.byte 111
+.byte 117
+.byte 110
+.byte 116
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 111
+.byte 110
+.byte 101
+.byte 32
+.byte 102
+.byte 108
+.byte 97
+.byte 119
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 102
+.byte 105
+.byte 110
+.byte 97
+.byte 108
+.byte 32
+.byte 116
+.byte 97
+.byte 108
+.byte 108
+.byte 121
+.byte 32
+.byte 98
+.byte 101
+.byte 108
+.byte 111
+.byte 119
+.byte 0
+.align 0
+L.317:
+.byte 83
+.byte 116
+.byte 105
+.byte 99
+.byte 107
+.byte 121
+.byte 32
+.byte 98
+.byte 105
+.byte 116
+.byte 32
+.byte 117
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 105
+.byte 110
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.316:
+.byte 83
+.byte 116
+.byte 105
+.byte 99
+.byte 107
+.byte 121
+.byte 32
+.byte 98
+.byte 105
+.byte 116
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 97
+.byte 114
+.byte 101
+.byte 110
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 117
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.299:
+.byte 67
+.byte 104
+.byte 101
+.byte 99
+.byte 107
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 115
+.byte 116
+.byte 105
+.byte 99
+.byte 107
+.byte 121
+.byte 32
+.byte 98
+.byte 105
+.byte 116
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.296:
+.byte 40
+.byte 88
+.byte 32
+.byte 45
+.byte 32
+.byte 89
+.byte 41
+.byte 32
+.byte 43
+.byte 32
+.byte 40
+.byte 89
+.byte 32
+.byte 45
+.byte 32
+.byte 88
+.byte 41
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 110
+.byte 32
+.byte 122
+.byte 101
+.byte 114
+.byte 111
+.byte 33
+.byte 10
+.byte 0
+.align 0
+L.293:
+.byte 65
+.byte 100
+.byte 100
+.byte 105
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 47
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 110
+.byte 101
+.byte 105
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.292:
+.byte 65
+.byte 100
+.byte 100
+.byte 47
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 0
+.align 0
+L.289:
+.byte 65
+.byte 100
+.byte 100
+.byte 105
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 47
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.282:
+.byte 65
+.byte 100
+.byte 100
+.byte 47
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.277:
+.byte 73
+.byte 110
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 108
+.byte 101
+.byte 116
+.byte 101
+.byte 32
+.byte 99
+.byte 97
+.byte 114
+.byte 114
+.byte 121
+.byte 45
+.byte 112
+.byte 114
+.byte 111
+.byte 112
+.byte 97
+.byte 103
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 65
+.byte 100
+.byte 100
+.byte 105
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 0
+.align 0
+L.273:
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 42
+.byte 32
+.byte 40
+.byte 32
+.byte 49
+.byte 32
+.byte 47
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 41
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 49
+.byte 0
+.align 0
+L.271:
+.byte 47
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 101
+.byte 105
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.268:
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.265:
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 0
+.align 0
+L.262:
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.257:
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 0
+.align 0
+L.254:
+.byte 42
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 101
+.byte 105
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.253:
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.250:
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.240:
+.byte 88
+.byte 32
+.byte 42
+.byte 32
+.byte 40
+.byte 49
+.byte 47
+.byte 88
+.byte 41
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 49
+.byte 0
+.align 0
+L.221:
+.byte 67
+.byte 104
+.byte 101
+.byte 99
+.byte 107
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 111
+.byte 110
+.byte 32
+.byte 109
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 121
+.byte 44
+.byte 32
+.byte 100
+.byte 105
+.byte 118
+.byte 105
+.byte 100
+.byte 101
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 97
+.byte 100
+.byte 100
+.byte 47
+.byte 115
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.220:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 42
+.byte 44
+.byte 32
+.byte 47
+.byte 44
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 45
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 104
+.byte 97
+.byte 118
+.byte 101
+.byte 32
+.byte 103
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 44
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 121
+.byte 32
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.217:
+.byte 32
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 32
+.byte 32
+.byte 105
+.byte 102
+.byte 32
+.byte 40
+.byte 88
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 49
+.byte 46
+.byte 48
+.byte 41
+.byte 32
+.byte 123
+.byte 46
+.byte 46
+.byte 46
+.byte 46
+.byte 46
+.byte 125
+.byte 32
+.byte 101
+.byte 108
+.byte 115
+.byte 101
+.byte 32
+.byte 123
+.byte 46
+.byte 46
+.byte 46
+.byte 47
+.byte 40
+.byte 88
+.byte 45
+.byte 49
+.byte 46
+.byte 48
+.byte 41
+.byte 46
+.byte 46
+.byte 46
+.byte 125
+.byte 10
+.byte 0
+.align 0
+L.216:
+.byte 32
+.byte 32
+.byte 115
+.byte 117
+.byte 99
+.byte 104
+.byte 32
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 97
+.byte 117
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 97
+.byte 103
+.byte 97
+.byte 105
+.byte 110
+.byte 115
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 122
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 97
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.215:
+.byte 32
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 121
+.byte 105
+.byte 101
+.byte 108
+.byte 100
+.byte 115
+.byte 32
+.byte 32
+.byte 40
+.byte 49
+.byte 45
+.byte 85
+.byte 49
+.byte 41
+.byte 32
+.byte 45
+.byte 32
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 32
+.byte 44
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 101
+.byte 98
+.byte 121
+.byte 32
+.byte 118
+.byte 105
+.byte 116
+.byte 105
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 10
+.byte 0
+.align 0
+L.214:
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 115
+.byte 32
+.byte 32
+.byte 40
+.byte 49
+.byte 45
+.byte 85
+.byte 49
+.byte 41
+.byte 32
+.byte 60
+.byte 32
+.byte 49
+.byte 32
+.byte 32
+.byte 97
+.byte 108
+.byte 116
+.byte 104
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 10
+.byte 0
+.align 0
+L.211:
+.byte 45
+.byte 32
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 115
+.byte 32
+.byte 71
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 68
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 44
+.byte 32
+.byte 115
+.byte 111
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 99
+.byte 101
+.byte 108
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 111
+.byte 98
+.byte 115
+.byte 99
+.byte 117
+.byte 114
+.byte 101
+.byte 100
+.byte 0
+.align 0
+L.206:
+.byte 42
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 47
+.byte 111
+.byte 114
+.byte 32
+.byte 47
+.byte 32
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 109
+.byte 97
+.byte 110
+.byte 121
+.byte 32
+.byte 108
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 119
+.byte 114
+.byte 111
+.byte 110
+.byte 103
+.byte 0
+.align 0
+L.202:
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 49
+.byte 47
+.byte 49
+.byte 46
+.byte 48
+.byte 48
+.byte 48
+.byte 46
+.byte 46
+.byte 49
+.byte 32
+.byte 62
+.byte 61
+.byte 32
+.byte 49
+.byte 0
+.align 0
+L.200:
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 71
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 68
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 44
+.byte 32
+.byte 115
+.byte 111
+.byte 32
+.byte 88
+.byte 47
+.byte 49
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 88
+.byte 0
+.align 0
+L.195:
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 71
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 68
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 44
+.byte 32
+.byte 115
+.byte 111
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 32
+.byte 101
+.byte 120
+.byte 99
+.byte 101
+.byte 101
+.byte 100
+.byte 32
+.byte 49
+.byte 32
+.byte 117
+.byte 108
+.byte 112
+.byte 10
+.byte 111
+.byte 114
+.byte 32
+.byte 32
+.byte 49
+.byte 47
+.byte 51
+.byte 32
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 32
+.byte 51
+.byte 47
+.byte 57
+.byte 32
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 32
+.byte 57
+.byte 47
+.byte 50
+.byte 55
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 97
+.byte 103
+.byte 114
+.byte 101
+.byte 101
+.byte 0
+.align 0
+L.191:
+.byte 42
+.byte 32
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 109
+.byte 97
+.byte 110
+.byte 121
+.byte 32
+.byte 102
+.byte 105
+.byte 110
+.byte 97
+.byte 108
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 119
+.byte 114
+.byte 111
+.byte 110
+.byte 103
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.189:
+.byte 42
+.byte 32
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 71
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 68
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 44
+.byte 32
+.byte 115
+.byte 111
+.byte 32
+.byte 49
+.byte 42
+.byte 88
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 88
+.byte 0
+.align 0
+L.186:
+.byte 10
+.byte 67
+.byte 104
+.byte 101
+.byte 99
+.byte 107
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 103
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 42
+.byte 44
+.byte 32
+.byte 47
+.byte 44
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 45
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.185:
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 109
+.byte 97
+.byte 108
+.byte 105
+.byte 122
+.byte 101
+.byte 100
+.byte 44
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 98
+.byte 101
+.byte 46
+.byte 0
+.align 0
+L.180:
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 109
+.byte 97
+.byte 108
+.byte 105
+.byte 122
+.byte 101
+.byte 100
+.byte 32
+.byte 88
+.byte 61
+.byte 89
+.byte 44
+.byte 88
+.byte 43
+.byte 90
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 89
+.byte 43
+.byte 90
+.byte 33
+.byte 0
+.align 0
+L.176:
+.byte 114
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 108
+.byte 121
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 101
+.byte 120
+.byte 116
+.byte 114
+.byte 97
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 105
+.byte 102
+.byte 105
+.byte 99
+.byte 97
+.byte 110
+.byte 116
+.byte 32
+.byte 100
+.byte 101
+.byte 99
+.byte 105
+.byte 109
+.byte 97
+.byte 108
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.175:
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 101
+.byte 108
+.byte 121
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 97
+.byte 98
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 101
+.byte 120
+.byte 116
+.byte 114
+.byte 97
+.byte 32
+.byte 66
+.byte 45
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 44
+.byte 32
+.byte 105
+.byte 46
+.byte 101
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.174:
+.byte 83
+.byte 111
+.byte 109
+.byte 101
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 101
+.byte 120
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 101
+.byte 120
+.byte 116
+.byte 114
+.byte 97
+.byte 10
+.byte 0
+.align 0
+L.168:
+.byte 111
+.byte 102
+.byte 32
+.byte 97
+.byte 110
+.byte 10
+.byte 101
+.byte 120
+.byte 116
+.byte 114
+.byte 97
+.byte 45
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 0
+.align 0
+L.167:
+.byte 90
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 90
+.byte 50
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 0
+.align 0
+L.166:
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 101
+.byte 120
+.byte 97
+.byte 99
+.byte 116
+.byte 32
+.byte 114
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 97
+.byte 108
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 97
+.byte 32
+.byte 114
+.byte 101
+.byte 115
+.byte 117
+.byte 108
+.byte 116
+.byte 10
+.byte 0
+.align 0
+L.165:
+.byte 66
+.byte 101
+.byte 99
+.byte 97
+.byte 117
+.byte 115
+.byte 101
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 117
+.byte 110
+.byte 117
+.byte 115
+.byte 117
+.byte 97
+.byte 108
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 102
+.byte 0
+.align 0
+L.161:
+.byte 9
+.byte 85
+.byte 50
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 90
+.byte 50
+.byte 32
+.byte 45
+.byte 32
+.byte 85
+.byte 50
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.160:
+.byte 9
+.byte 85
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 90
+.byte 49
+.byte 32
+.byte 45
+.byte 32
+.byte 85
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.159:
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 0
+.align 0
+L.158:
+.byte 0
+.align 0
+L.151:
+.byte 84
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 102
+.byte 101
+.byte 97
+.byte 116
+.byte 117
+.byte 114
+.byte 101
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 102
+.byte 117
+.byte 114
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.146:
+.byte 80
+.byte 111
+.byte 115
+.byte 115
+.byte 105
+.byte 98
+.byte 108
+.byte 121
+.byte 32
+.byte 115
+.byte 111
+.byte 109
+.byte 101
+.byte 32
+.byte 112
+.byte 97
+.byte 114
+.byte 116
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 0
+.align 0
+L.145:
+.byte 98
+.byte 121
+.byte 32
+.byte 101
+.byte 120
+.byte 116
+.byte 114
+.byte 97
+.byte 45
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 101
+.byte 32
+.byte 101
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 101
+.byte 120
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.144:
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 115
+.byte 121
+.byte 109
+.byte 112
+.byte 116
+.byte 111
+.byte 109
+.byte 115
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 105
+.byte 110
+.byte 99
+.byte 111
+.byte 110
+.byte 115
+.byte 105
+.byte 115
+.byte 116
+.byte 101
+.byte 110
+.byte 99
+.byte 105
+.byte 101
+.byte 115
+.byte 32
+.byte 105
+.byte 110
+.byte 116
+.byte 114
+.byte 111
+.byte 100
+.byte 117
+.byte 99
+.byte 101
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.143:
+.byte 114
+.byte 101
+.byte 115
+.byte 112
+.byte 101
+.byte 99
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 108
+.byte 121
+.byte 32
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 44
+.byte 10
+.byte 0
+.align 0
+L.142:
+.byte 68
+.byte 105
+.byte 115
+.byte 97
+.byte 103
+.byte 114
+.byte 101
+.byte 101
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 97
+.byte 109
+.byte 111
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 115
+.byte 32
+.byte 88
+.byte 49
+.byte 44
+.byte 32
+.byte 89
+.byte 49
+.byte 44
+.byte 32
+.byte 90
+.byte 49
+.byte 44
+.byte 10
+.byte 0
+.align 0
+L.120:
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 119
+.byte 111
+.byte 114
+.byte 115
+.byte 101
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 110
+.byte 32
+.byte 53
+.byte 32
+.byte 100
+.byte 101
+.byte 99
+.byte 105
+.byte 109
+.byte 97
+.byte 108
+.byte 32
+.byte 102
+.byte 105
+.byte 103
+.byte 117
+.byte 114
+.byte 101
+.byte 115
+.byte 32
+.byte 32
+.byte 0
+.align 0
+L.118:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 105
+.byte 102
+.byte 105
+.byte 99
+.byte 97
+.byte 110
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 37
+.byte 102
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.117:
+.byte 108
+.byte 111
+.byte 103
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 105
+.byte 99
+.byte 32
+.byte 101
+.byte 110
+.byte 99
+.byte 111
+.byte 100
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 104
+.byte 97
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 99
+.byte 104
+.byte 97
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 101
+.byte 114
+.byte 105
+.byte 122
+.byte 101
+.byte 100
+.byte 32
+.byte 115
+.byte 111
+.byte 108
+.byte 101
+.byte 108
+.byte 121
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 85
+.byte 49
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.114:
+.byte 111
+.byte 102
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 105
+.byte 102
+.byte 105
+.byte 99
+.byte 97
+.byte 110
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 98
+.byte 117
+.byte 116
+.byte 44
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 105
+.byte 116
+.byte 115
+.byte 101
+.byte 108
+.byte 102
+.byte 44
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 109
+.byte 105
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 102
+.byte 108
+.byte 97
+.byte 119
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.113:
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 99
+.byte 104
+.byte 97
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 101
+.byte 114
+.byte 105
+.byte 122
+.byte 101
+.byte 100
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 97
+.byte 110
+.byte 32
+.byte 73
+.byte 110
+.byte 116
+.byte 101
+.byte 103
+.byte 101
+.byte 114
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 10
+.byte 0
+.align 0
+L.100:
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 102
+.byte 117
+.byte 122
+.byte 122
+.byte 121
+.byte 44
+.byte 88
+.byte 61
+.byte 49
+.byte 32
+.byte 98
+.byte 117
+.byte 116
+.byte 32
+.byte 88
+.byte 45
+.byte 49
+.byte 47
+.byte 50
+.byte 45
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 0
+.align 0
+L.96:
+.byte 40
+.byte 49
+.byte 45
+.byte 85
+.byte 49
+.byte 41
+.byte 45
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 60
+.byte 32
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 70
+.byte 65
+.byte 76
+.byte 83
+.byte 69
+.byte 44
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 46
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 115
+.byte 63
+.byte 0
+.align 3
+L.94:
+.long 0x0
+.long 0x40240000
+.align 0
+L.89:
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 103
+.byte 111
+.byte 111
+.byte 100
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 50
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 49
+.byte 48
+.byte 0
+.align 0
+L.85:
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 98
+.byte 105
+.byte 103
+.byte 58
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 111
+.byte 102
+.byte 102
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 98
+.byte 108
+.byte 101
+.byte 109
+.byte 115
+.byte 0
+.align 0
+L.83:
+.byte 77
+.byte 89
+.byte 83
+.byte 84
+.byte 69
+.byte 82
+.byte 89
+.byte 58
+.byte 32
+.byte 114
+.byte 101
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.82:
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 105
+.byte 114
+.byte 109
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 3
+L.79:
+.long 0x47ae147b
+.long 0x3f847ae1
+.align 0
+L.78:
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 98
+.byte 101
+.byte 116
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 99
+.byte 108
+.byte 111
+.byte 115
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 114
+.byte 101
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 115
+.byte 101
+.byte 112
+.byte 97
+.byte 114
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 85
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.77:
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 105
+.byte 114
+.byte 109
+.byte 115
+.byte 32
+.byte 99
+.byte 108
+.byte 111
+.byte 115
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 114
+.byte 101
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 115
+.byte 101
+.byte 112
+.byte 97
+.byte 114
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 85
+.byte 49
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.62:
+.byte 82
+.byte 101
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 114
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 10
+.byte 32
+.byte 0
+.align 0
+L.61:
+.byte 67
+.byte 108
+.byte 111
+.byte 115
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 114
+.byte 101
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 115
+.byte 101
+.byte 112
+.byte 97
+.byte 114
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 85
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 10
+.byte 0
+.align 0
+L.55:
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 102
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.46:
+.byte 83
+.byte 101
+.byte 97
+.byte 114
+.byte 99
+.byte 104
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.45:
+.byte 10
+.byte 0
+.align 0
+L.44:
+.byte 45
+.byte 49
+.byte 44
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 49
+.byte 47
+.byte 50
+.byte 44
+.byte 32
+.byte 49
+.byte 44
+.byte 32
+.byte 50
+.byte 44
+.byte 32
+.byte 51
+.byte 44
+.byte 32
+.byte 52
+.byte 44
+.byte 32
+.byte 53
+.byte 44
+.byte 32
+.byte 57
+.byte 44
+.byte 32
+.byte 50
+.byte 55
+.byte 44
+.byte 32
+.byte 51
+.byte 50
+.byte 32
+.byte 38
+.byte 32
+.byte 50
+.byte 52
+.byte 48
+.byte 32
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 79
+.byte 46
+.byte 75
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.39:
+.byte 53
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 52
+.byte 43
+.byte 49
+.byte 44
+.byte 32
+.byte 50
+.byte 52
+.byte 48
+.byte 47
+.byte 51
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 56
+.byte 48
+.byte 44
+.byte 32
+.byte 50
+.byte 52
+.byte 48
+.byte 47
+.byte 52
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 54
+.byte 48
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 50
+.byte 52
+.byte 48
+.byte 47
+.byte 53
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 52
+.byte 56
+.byte 0
+.align 0
+L.35:
+.byte 57
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 51
+.byte 42
+.byte 51
+.byte 44
+.byte 32
+.byte 50
+.byte 55
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 57
+.byte 42
+.byte 51
+.byte 44
+.byte 32
+.byte 51
+.byte 50
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 56
+.byte 42
+.byte 52
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 51
+.byte 50
+.byte 45
+.byte 50
+.byte 55
+.byte 45
+.byte 52
+.byte 45
+.byte 49
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 0
+.align 0
+L.31:
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 43
+.byte 32
+.byte 40
+.byte 45
+.byte 49
+.byte 41
+.byte 32
+.byte 43
+.byte 32
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 0
+.align 0
+L.27:
+.byte 45
+.byte 49
+.byte 43
+.byte 49
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 40
+.byte 45
+.byte 49
+.byte 41
+.byte 43
+.byte 97
+.byte 98
+.byte 115
+.byte 40
+.byte 49
+.byte 41
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 45
+.byte 49
+.byte 43
+.byte 40
+.byte 45
+.byte 49
+.byte 41
+.byte 42
+.byte 40
+.byte 45
+.byte 49
+.byte 41
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 0
+.align 0
+L.23:
+.byte 51
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 50
+.byte 43
+.byte 49
+.byte 44
+.byte 32
+.byte 52
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 51
+.byte 43
+.byte 49
+.byte 44
+.byte 32
+.byte 52
+.byte 43
+.byte 50
+.byte 42
+.byte 40
+.byte 45
+.byte 50
+.byte 41
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 52
+.byte 45
+.byte 51
+.byte 45
+.byte 49
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 0
+.align 3
+L.21:
+.long 0xd2f1a9fc
+.long 0x3f50624d
+.align 0
+L.20:
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 45
+.byte 48
+.byte 46
+.byte 48
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 78
+.byte 111
+.byte 110
+.byte 45
+.byte 122
+.byte 101
+.byte 114
+.byte 111
+.byte 33
+.byte 10
+.byte 0
+.align 0
+L.15:
+.byte 48
+.byte 43
+.byte 48
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 49
+.byte 45
+.byte 49
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 49
+.byte 32
+.byte 60
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 49
+.byte 43
+.byte 49
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 50
+.byte 0
+.align 0
+L.13:
+.byte 80
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 119
+.byte 32
+.byte 82
+.byte 85
+.byte 78
+.byte 78
+.byte 73
+.byte 78
+.byte 71
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 115
+.byte 32
+.byte 111
+.byte 110
+.byte 32
+.byte 115
+.byte 109
+.byte 97
+.byte 108
+.byte 108
+.byte 32
+.byte 105
+.byte 110
+.byte 116
+.byte 101
+.byte 103
+.byte 101
+.byte 114
+.byte 115
+.byte 58
+.byte 10
+.byte 0
+.align 3
+L.9:
+.long 0x0
+.long 0x3ff00000
+.align 3
+L.8:
+.long 0x0
+.long 0x0
+.align 0
+L.3:
+.byte 10
+.byte 42
+.byte 32
+.byte 42
+.byte 32
+.byte 42
+.byte 32
+.byte 70
+.byte 76
+.byte 79
+.byte 65
+.byte 84
+.byte 73
+.byte 78
+.byte 71
+.byte 45
+.byte 80
+.byte 79
+.byte 73
+.byte 78
+.byte 84
+.byte 32
+.byte 69
+.byte 82
+.byte 82
+.byte 79
+.byte 82
+.byte 32
+.byte 42
+.byte 32
+.byte 42
+.byte 32
+.byte 42
+.byte 10
+.byte 0
diff --git a/lcc/alpha/osf/tst/sort.1bk b/lcc/alpha/osf/tst/sort.1bk
new file mode 100755
index 0000000..380d529
--- /dev/null
+++ b/lcc/alpha/osf/tst/sort.1bk
@@ -0,0 +1,20 @@
+exchange(1,9)
+exchange(3,7)
+exchange(5,6)
+exchange(0,5)
+exchange(0,3)
+exchange(0,0)
+exchange(1,2)
+exchange(6,6)
+exchange(8,9)
+exchange(7,8)
+-51
+-1
+0
+1
+3
+10
+18
+32
+567
+789
diff --git a/lcc/alpha/osf/tst/sort.2bk b/lcc/alpha/osf/tst/sort.2bk
new file mode 100755
index 0000000..27488a1
--- /dev/null
+++ b/lcc/alpha/osf/tst/sort.2bk
@@ -0,0 +1,5 @@
+tst/sort.c:23: warning: missing return value
+tst/sort.c:30: warning: missing return value
+tst/sort.c:37: warning: missing return value
+tst/sort.c:41: warning: missing return value
+tst/sort.c:65: warning: missing return value
diff --git a/lcc/alpha/osf/tst/sort.sbk b/lcc/alpha/osf/tst/sort.sbk
new file mode 100755
index 0000000..cb5b857
--- /dev/null
+++ b/lcc/alpha/osf/tst/sort.sbk
@@ -0,0 +1,323 @@
+.sdata
+.globl in
+.align 2
+in:
+.long 0xa
+.long 0x20
+.long 0xffffffff
+.long 0x237
+.long 0x3
+.long 0x12
+.long 0x1
+.long 0xffffffcd
+.long 0x315
+.long 0x0
+.globl main
+.text
+.text
+.ent main
+main:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4004000,-72
+.frame $sp,80,$26,48
+stq $14,0($sp)
+stq $26,8($sp)
+.prologue 1
+lda $16,in
+lda $17,10
+jsr $26,sort
+ldgp $gp,0($26)
+mov $31,$14
+br L.5
+L.2:
+sll $14,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+ldl $16,in($27)
+jsr $26,putd
+ldgp $gp,0($26)
+lda $16,10
+jsr $26,putchar
+ldgp $gp,0($26)
+L.3:
+lda $14,1($14)
+L.5:
+mov $14,$27
+lda $25,10
+cmpult $27,$25,$23
+bne $23,L.2
+mov $31,$0
+L.1:
+ldq $14,0($sp)
+ldq $26,8($sp)
+lda $sp,80($sp)
+ret
+.end main
+.globl putd
+.text
+.ent putd
+putd:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x5004000,-64
+.frame $sp,80,$26,48
+stq $14,0($sp)
+stq $24,8($sp)
+stq $26,16($sp)
+mov $16,$14
+.prologue 1
+cmplt $14,$31,$23
+beq $23,L.7
+lda $16,45
+jsr $26,putchar
+ldgp $gp,0($26)
+negl $14,$14
+L.7:
+divl $14,10,$27
+cmpeq $27,$31,$23
+bne $23,L.9
+divl $14,10,$16
+jsr $26,putd
+ldgp $gp,0($26)
+L.9:
+reml $14,10,$27
+lda $16,48($27)
+jsr $26,putchar
+ldgp $gp,0($26)
+mov $31,$0
+L.6:
+ldq $14,0($sp)
+ldq $24,8($sp)
+ldq $26,16($sp)
+lda $sp,80($sp)
+ret
+.end putd
+.globl sort
+.text
+.ent sort
+sort:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+stq $16,16($sp)
+stq $17,24($sp)
+.prologue 1
+ldq $27,-48+64($sp)
+stq $27,xx
+mov $27,$16
+mov $31,$17
+ldl $27,-40+64($sp)
+subl $27,1,$27
+stl $27,-40+64($sp)
+mov $27,$18
+jsr $26,quick
+ldgp $gp,0($26)
+mov $31,$0
+L.11:
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end sort
+.globl quick
+.text
+.ent quick
+quick:
+ldgp $gp,0($27)
+lda $sp,-96($sp)
+.mask 0x4007800,-64
+.frame $sp,96,$26,48
+stq $11,0($sp)
+stq $12,8($sp)
+stq $13,16($sp)
+stq $14,24($sp)
+stq $26,32($sp)
+mov $16,$14
+mov $17,$13
+mov $18,$12
+.prologue 1
+cmplt $13,$12,$23
+bne $23,L.13
+br L.12
+L.13:
+mov $14,$16
+mov $13,$17
+mov $12,$18
+jsr $26,partition
+ldgp $gp,0($26)
+mov $0,$11
+mov $14,$16
+mov $13,$17
+subl $11,1,$18
+jsr $26,quick
+ldgp $gp,0($26)
+mov $14,$16
+lda $17,1($11)
+mov $12,$18
+jsr $26,quick
+ldgp $gp,0($26)
+mov $31,$0
+L.12:
+ldq $11,0($sp)
+ldq $12,8($sp)
+ldq $13,16($sp)
+ldq $14,24($sp)
+ldq $26,32($sp)
+lda $sp,96($sp)
+ret
+.end quick
+.globl partition
+.text
+.ent partition
+partition:
+ldgp $gp,0($27)
+lda $sp,-112($sp)
+.mask 0x4007c00,-72
+.frame $sp,112,$26,48
+stq $10,0($sp)
+stq $11,8($sp)
+stq $12,16($sp)
+stq $13,24($sp)
+stq $14,32($sp)
+stq $26,40($sp)
+mov $16,$14
+mov $17,$13
+mov $18,$12
+.prologue 1
+lda $12,1($12)
+mov $13,$10
+sll $10,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+addq $27,$14,$27
+ldl $11,($27)
+br L.17
+L.16:
+lda $13,1($13)
+br L.20
+L.19:
+lda $13,1($13)
+L.20:
+sll $13,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+addq $27,$14,$27
+ldl $27,($27)
+cmplt $27,$11,$23
+bne $23,L.19
+subl $12,1,$12
+br L.23
+L.22:
+subl $12,1,$12
+L.23:
+sll $12,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+addq $27,$14,$27
+ldl $27,($27)
+cmple $27,$11,$23
+beq $23,L.22
+cmplt $13,$12,$23
+beq $23,L.25
+sll $13,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+addq $27,$14,$16
+sll $12,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+addq $27,$14,$17
+jsr $26,exchange
+ldgp $gp,0($26)
+L.25:
+L.17:
+cmplt $13,$12,$23
+bne $23,L.16
+sll $10,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+addq $27,$14,$16
+sll $12,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,2,$27
+addq $27,$14,$17
+jsr $26,exchange
+ldgp $gp,0($26)
+mov $12,$0
+L.15:
+ldq $10,0($sp)
+ldq $11,8($sp)
+ldq $12,16($sp)
+ldq $13,24($sp)
+ldq $14,32($sp)
+ldq $26,40($sp)
+lda $sp,112($sp)
+ret
+.end partition
+.globl exchange
+.text
+.ent exchange
+exchange:
+ldgp $gp,0($27)
+lda $sp,-112($sp)
+.mask 0x5006000,-88
+.frame $sp,112,$26,48
+stq $13,0($sp)
+stq $14,8($sp)
+stq $24,16($sp)
+stq $26,24($sp)
+mov $16,$14
+mov $17,$13
+.prologue 1
+lda $16,L.28
+ldq $27,xx
+stq $27,-80+112($sp)
+mov $14,$25
+subq $25,$27,$25
+stq $25,-72+112($sp)
+divq $25,4,$17
+mov $13,$27
+ldq $25,-80+112($sp)
+subq $27,$25,$27
+divq $27,4,$18
+jsr $26,printf
+ldgp $gp,0($26)
+ldl $27,($14)
+stl $27,-60+112($sp)
+ldl $27,($13)
+stl $27,($14)
+ldl $27,-60+112($sp)
+stl $27,($13)
+mov $31,$0
+L.27:
+ldq $13,0($sp)
+ldq $14,8($sp)
+ldq $24,16($sp)
+ldq $26,24($sp)
+lda $sp,112($sp)
+ret
+.end exchange
+.globl xx
+.comm xx,8
+.rdata
+.align 0
+L.28:
+.byte 101
+.byte 120
+.byte 99
+.byte 104
+.byte 97
+.byte 110
+.byte 103
+.byte 101
+.byte 40
+.byte 37
+.byte 100
+.byte 44
+.byte 37
+.byte 100
+.byte 41
+.byte 10
+.byte 0
diff --git a/lcc/alpha/osf/tst/spill.1bk b/lcc/alpha/osf/tst/spill.1bk
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/alpha/osf/tst/spill.1bk
diff --git a/lcc/alpha/osf/tst/spill.2bk b/lcc/alpha/osf/tst/spill.2bk
new file mode 100755
index 0000000..f7e3521
--- /dev/null
+++ b/lcc/alpha/osf/tst/spill.2bk
@@ -0,0 +1,6 @@
+tst/spill.c:1: warning: missing return value
+tst/spill.c:3: warning: missing return value
+tst/spill.c:5: warning: missing return value
+tst/spill.c:7: warning: missing return value
+tst/spill.c:9: warning: missing return value
+tst/spill.c:17: warning: missing return value
diff --git a/lcc/alpha/osf/tst/spill.sbk b/lcc/alpha/osf/tst/spill.sbk
new file mode 100755
index 0000000..d05e700
--- /dev/null
+++ b/lcc/alpha/osf/tst/spill.sbk
@@ -0,0 +1,272 @@
+.globl main
+.text
+.text
+.ent main
+main:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.frame $sp,64,$26,48
+.prologue 1
+mov $31,$0
+L.1:
+lda $sp,64($sp)
+ret
+.end main
+.globl f
+.text
+.ent f
+f:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4000000,-80
+.frame $sp,80,$26,48
+stq $26,0($sp)
+stq $16,32($sp)
+.prologue 1
+jsr $26,f
+ldgp $gp,0($26)
+mov $0,$27
+stl $27,-60+80($sp)
+jsr $26,f
+ldgp $gp,0($26)
+ldl $25,-60+80($sp)
+addl $25,$0,$27
+stl $27,-48+80($sp)
+mov $31,$0
+L.2:
+ldq $26,0($sp)
+lda $sp,80($sp)
+ret
+.end f
+.globl f2
+.text
+.ent f2
+f2:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4004000,-72
+.frame $sp,80,$26,48
+stq $14,0($sp)
+stq $26,8($sp)
+stq $16,32($sp)
+.prologue 1
+jsr $26,f
+ldgp $gp,0($26)
+mov $0,$27
+stl $27,-60+80($sp)
+ldl $25,-48+80($sp)
+cmpeq $25,$31,$23
+bne $23,L.5
+jsr $26,f
+ldgp $gp,0($26)
+mov $0,$27
+mov $27,$14
+br L.6
+L.5:
+lda $14,1
+L.6:
+ldl $27,-60+80($sp)
+addl $27,$14,$27
+stl $27,-48+80($sp)
+mov $31,$0
+L.3:
+ldq $14,0($sp)
+ldq $26,8($sp)
+lda $sp,80($sp)
+ret
+.end f2
+.globl f3
+.text
+.ent f3
+f3:
+ldgp $gp,0($27)
+lda $sp,-144($sp)
+.mask 0x4007e00,-96
+.frame $sp,144,$26,48
+stq $9,0($sp)
+stq $10,8($sp)
+stq $11,16($sp)
+stq $12,24($sp)
+stq $13,32($sp)
+stq $14,40($sp)
+stq $26,48($sp)
+stq $16,96($sp)
+stq $17,104($sp)
+.prologue 1
+mov $31,$14
+mov $31,$13
+mov $31,$12
+mov $31,$11
+mov $31,$10
+mov $31,$9
+stl $31,-60+144($sp)
+stl $31,-64+144($sp)
+stl $31,-68+144($sp)
+stl $31,-72+144($sp)
+ldq $27,-40+144($sp)
+stq $27,-88+144($sp)
+lda $25,4($27)
+stq $25,-40+144($sp)
+ldl $25,-48+144($sp)
+cmpeq $25,$31,$23
+bne $23,L.9
+jsr $26,f
+ldgp $gp,0($26)
+mov $0,$27
+stl $27,-76+144($sp)
+br L.10
+L.9:
+stl $31,-76+144($sp)
+L.10:
+ldl $27,-76+144($sp)
+ldq $25,-88+144($sp)
+stl $27,($25)
+mov $31,$0
+L.7:
+ldq $9,0($sp)
+ldq $10,8($sp)
+ldq $11,16($sp)
+ldq $12,24($sp)
+ldq $13,32($sp)
+ldq $14,40($sp)
+ldq $26,48($sp)
+lda $sp,144($sp)
+ret
+.end f3
+.globl f4
+.text
+.ent f4
+f4:
+ldgp $gp,0($27)
+lda $sp,-128($sp)
+.mask 0x4007e00,-80
+.frame $sp,128,$26,48
+stq $9,0($sp)
+stq $10,8($sp)
+stq $11,16($sp)
+stq $12,24($sp)
+stq $13,32($sp)
+stq $14,40($sp)
+stq $26,48($sp)
+.prologue 1
+mov $31,$14
+mov $31,$13
+mov $31,$12
+mov $31,$11
+mov $31,$10
+mov $31,$9
+ldl $27,i
+sll $27,8*(8-4),$25
+sra $25,8*(8-4),$25
+sll $25,3,$25
+ldt $f30,a($25)
+ldt $f29,b($25)
+ldt $f28,L.15
+addt $f30,$f29,$f27
+cmpteq $f27,$f28,$f1
+fbne $f1,L.13
+cmpeq $27,$31,$23
+bne $23,L.13
+subt $f30,$f29,$f30
+cmpteq $f30,$f28,$f1
+fbne $f1,L.13
+lda $27,1
+stl $27,-60+128($sp)
+br L.14
+L.13:
+stl $31,-60+128($sp)
+L.14:
+ldl $27,-60+128($sp)
+stl $27,i
+mov $31,$0
+L.11:
+ldq $9,0($sp)
+ldq $10,8($sp)
+ldq $11,16($sp)
+ldq $12,24($sp)
+ldq $13,32($sp)
+ldq $14,40($sp)
+ldq $26,48($sp)
+lda $sp,128($sp)
+ret
+.end f4
+.globl f5
+.text
+.ent f5
+f5:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.frame $sp,64,$26,48
+.prologue 1
+ldl $27,k
+ldl $25,m
+ldq $22,A
+mull $27,$25,$8
+sll $8,8*(8-4),$8
+sra $8,8*(8-4),$8
+sll $8,3,$8
+addq $8,$22,$8
+ldl $7,j
+mull $7,$25,$25
+sll $25,8*(8-4),$25
+sra $25,8*(8-4),$25
+sll $25,3,$25
+addq $25,$22,$25
+ldl $22,n
+ldq $6,B
+mull $27,$22,$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,3,$27
+addq $27,$6,$27
+mull $7,$22,$22
+sll $22,8*(8-4),$22
+sra $22,8*(8-4),$22
+sll $22,3,$22
+addq $22,$6,$22
+ldt $f30,($8)
+ldt $f29,($25)
+mult $f30,$f29,$f30
+ldt $f29,($27)
+ldt $f28,($22)
+mult $f29,$f28,$f29
+addt $f30,$f29,$f30
+stt $f30,x
+ldt $f30,($8)
+ldt $f29,($22)
+mult $f30,$f29,$f30
+ldt $f29,($27)
+ldt $f28,($25)
+mult $f29,$f28,$f29
+subt $f30,$f29,$f30
+stt $f30,x
+mov $31,$0
+L.16:
+lda $sp,64($sp)
+ret
+.end f5
+.globl x
+.comm x,8
+.globl B
+.comm B,8
+.globl A
+.comm A,8
+.globl n
+.comm n,4
+.globl m
+.comm m,4
+.globl k
+.comm k,4
+.globl j
+.comm j,4
+.globl i
+.comm i,4
+.globl b
+.comm b,80
+.globl a
+.comm a,80
+.rdata
+.align 3
+L.15:
+.long 0x0
+.long 0x0
diff --git a/lcc/alpha/osf/tst/stdarg.1bk b/lcc/alpha/osf/tst/stdarg.1bk
new file mode 100755
index 0000000..097aef7
--- /dev/null
+++ b/lcc/alpha/osf/tst/stdarg.1bk
@@ -0,0 +1,6 @@
+test 1
+test 2
+test 3
+test 4
+test 5.000000
+{1 2 3 4} {1 2 3 4} {1 2 3 4} {1 2 3 4} {1 2 3 4} {1 2 3 4}
diff --git a/lcc/alpha/osf/tst/stdarg.2bk b/lcc/alpha/osf/tst/stdarg.2bk
new file mode 100755
index 0000000..a832cf9
--- /dev/null
+++ b/lcc/alpha/osf/tst/stdarg.2bk
@@ -0,0 +1 @@
+tst/stdarg.c:51: warning: missing return value
diff --git a/lcc/alpha/osf/tst/stdarg.sbk b/lcc/alpha/osf/tst/stdarg.sbk
new file mode 100755
index 0000000..e5570c2
--- /dev/null
+++ b/lcc/alpha/osf/tst/stdarg.sbk
@@ -0,0 +1,430 @@
+.sdata
+.globl x
+.align 2
+x:
+.long 0x1
+.long 0x2
+.long 0x3
+.long 0x4
+.globl main
+.text
+.text
+.ent main
+main:
+ldgp $gp,0($27)
+lda $sp,-128($sp)
+.mask 0x4000000,-72
+.frame $sp,128,$26,48
+stq $26,56($sp)
+.prologue 1
+lda $16,L.3
+jsr $26,print
+ldgp $gp,0($26)
+lda $16,L.4
+lda $17,L.5
+jsr $26,print
+ldgp $gp,0($26)
+lda $16,L.6
+lda $17,3
+lda $18,10
+jsr $26,print
+ldgp $gp,0($26)
+lda $16,L.7
+lda $17,L.8
+lda $18,L.9
+lda $19,4
+lda $20,10
+jsr $26,print
+ldgp $gp,0($26)
+lda $16,L.10
+lda $17,L.8
+lda $18,L.9
+ldt $f19,L.11
+lda $20,10
+jsr $26,print
+ldgp $gp,0($26)
+lda $16,L.12
+lda $27,x
+mov $27,$1
+uldq $17,0($1)
+uldq $18,8($1)
+mov $27,$1
+uldq $19,0($1)
+uldq $20,8($1)
+mov $27,$1
+uldq $21,0($1)
+ldl $4,8($1)
+ldl $2,12($1)
+stl $4,0($30)
+stl $2,4($30)
+mov $27,$1
+ldl $4,0($1)
+ldl $2,4($1)
+stl $4,8($30)
+stl $2,12($30)
+ldl $4,8($1)
+ldl $2,12($1)
+stl $4,16($30)
+stl $2,20($30)
+mov $27,$1
+ldl $4,0($1)
+ldl $2,4($1)
+stl $4,24($30)
+stl $2,28($30)
+ldl $4,8($1)
+ldl $2,12($1)
+stl $4,32($30)
+stl $2,36($30)
+mov $27,$1
+ldl $4,0($1)
+ldl $2,4($1)
+stl $4,40($30)
+stl $2,44($30)
+ldl $4,8($1)
+ldl $2,12($1)
+stl $4,48($30)
+stl $2,52($30)
+jsr $26,print
+ldgp $gp,0($26)
+mov $31,$0
+L.2:
+ldq $26,56($sp)
+lda $sp,128($sp)
+ret
+.end main
+.globl print
+.text
+.ent print
+print:
+ldgp $gp,0($27)
+lda $sp,-160($sp)
+.mask 0x4006000,-144
+.frame $sp,160,$26,96
+stq $13,0($sp)
+stq $14,8($sp)
+stq $26,16($sp)
+stq $16,112($sp)
+stq $17,120($sp)
+stt $f17,72($sp)
+stq $18,128($sp)
+stt $f18,80($sp)
+stq $19,136($sp)
+stt $f19,88($sp)
+stq $20,144($sp)
+stt $f20,96($sp)
+stq $21,152($sp)
+stt $f21,104($sp)
+.prologue 1
+lda $27,-48+160($sp)
+stq $27,-120+160($sp)
+lda $27,-40+160($sp)
+ldq $25,-120+160($sp)
+subq $27,$25,$27
+stl $27,-112+160($sp)
+br L.21
+L.18:
+ldq $27,-48+160($sp)
+ldb $27,($27)
+cmpeq $27,37,$23
+beq $23,L.22
+ldq $27,-48+160($sp)
+lda $27,1($27)
+stq $27,-48+160($sp)
+ldb $14,($27)
+lda $27,115
+cmpeq $14,$27,$23
+bne $23,L.74
+cmple $14,$27,$23
+beq $23,L.100
+L.99:
+lda $27,98
+cmplt $14,$27,$23
+bne $23,L.24
+lda $27,102
+cmple $14,$27,$23
+beq $23,L.24
+subl $14,98,$27
+sll $27,3,$27
+ldq $27,L.101($27)
+jmp ($27)
+.rdata
+.align 3
+L.101:
+.quad L.27
+.quad L.41
+.quad L.52
+.quad L.24
+.quad L.85
+.text
+L.100:
+lda $27,119
+cmpeq $14,$27,$23
+bne $23,L.63
+br L.24
+L.27:
+ldl $27,-112+160($sp)
+lda $27,16($27)
+stl $27,-112+160($sp)
+lda $27,-136+160($sp)
+ldl $25,-112+160($sp)
+ldq $22,-120+160($sp)
+addq $25,$22,$25
+lda $1,-16($25)
+ldl $4,0($1)
+ldl $2,4($1)
+stl $4,0($27)
+stl $2,4($27)
+ldl $4,8($1)
+ldl $2,12($1)
+stl $4,8($27)
+stl $2,12($27)
+lda $16,L.37
+ldl $17,-136+160($sp)
+ldl $18,-132+160($sp)
+ldl $19,-128+160($sp)
+ldl $20,-124+160($sp)
+jsr $26,printf
+ldgp $gp,0($26)
+br L.23
+L.41:
+lda $16,L.42
+ldl $27,-112+160($sp)
+lda $27,8($27)
+stl $27,-112+160($sp)
+ldl $27,-112+160($sp)
+ldq $25,-120+160($sp)
+addq $27,$25,$27
+lda $27,-8($27)
+ldb $17,($27)
+jsr $26,printf
+ldgp $gp,0($26)
+br L.23
+L.52:
+lda $16,L.53
+ldl $27,-112+160($sp)
+lda $27,8($27)
+stl $27,-112+160($sp)
+ldl $27,-112+160($sp)
+ldq $25,-120+160($sp)
+addq $27,$25,$27
+ldl $17,-8($27)
+jsr $26,printf
+ldgp $gp,0($26)
+br L.23
+L.63:
+lda $16,L.64
+ldl $27,-112+160($sp)
+lda $27,8($27)
+stl $27,-112+160($sp)
+ldl $27,-112+160($sp)
+ldq $25,-120+160($sp)
+addq $27,$25,$27
+lda $27,-8($27)
+ldw $17,($27)
+jsr $26,printf
+ldgp $gp,0($26)
+br L.23
+L.74:
+lda $16,L.75
+ldl $27,-112+160($sp)
+lda $27,8($27)
+stl $27,-112+160($sp)
+ldl $27,-112+160($sp)
+ldq $25,-120+160($sp)
+addq $27,$25,$27
+ldq $17,-8($27)
+jsr $26,printf
+ldgp $gp,0($26)
+br L.23
+L.85:
+lda $16,L.86
+ldl $27,-112+160($sp)
+lda $27,8($27)
+stl $27,-112+160($sp)
+ldl $27,-112+160($sp)
+cmple $27,48,$23
+beq $23,L.97
+ldl $27,-112+160($sp)
+ldq $25,-120+160($sp)
+addq $27,$25,$27
+lda $13,-56($27)
+br L.98
+L.97:
+ldl $27,-112+160($sp)
+ldq $25,-120+160($sp)
+addq $27,$25,$27
+lda $13,-8($27)
+L.98:
+ldt $f17,($13)
+jsr $26,printf
+ldgp $gp,0($26)
+br L.23
+L.24:
+lda $16,L.42
+ldq $27,-48+160($sp)
+ldb $17,($27)
+jsr $26,printf
+ldgp $gp,0($26)
+br L.23
+L.22:
+lda $16,L.42
+ldq $27,-48+160($sp)
+ldb $17,($27)
+jsr $26,printf
+ldgp $gp,0($26)
+L.23:
+L.19:
+ldq $27,-48+160($sp)
+lda $27,1($27)
+stq $27,-48+160($sp)
+L.21:
+ldq $27,-48+160($sp)
+ldb $27,($27)
+cmpeq $27,$31,$23
+beq $23,L.18
+mov $31,$0
+L.13:
+ldq $13,0($sp)
+ldq $14,8($sp)
+ldq $26,16($sp)
+lda $sp,160($sp)
+ret
+.end print
+.rdata
+.align 0
+L.86:
+.byte 37
+.byte 102
+.byte 0
+.align 0
+L.75:
+.byte 37
+.byte 115
+.byte 0
+.align 0
+L.64:
+.byte 37
+.byte 120
+.byte 0
+.align 0
+L.53:
+.byte 37
+.byte 100
+.byte 0
+.align 0
+L.42:
+.byte 37
+.byte 99
+.byte 0
+.align 0
+L.37:
+.byte 123
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 125
+.byte 0
+.align 0
+L.12:
+.byte 37
+.byte 98
+.byte 32
+.byte 37
+.byte 98
+.byte 32
+.byte 37
+.byte 98
+.byte 32
+.byte 37
+.byte 98
+.byte 32
+.byte 37
+.byte 98
+.byte 32
+.byte 37
+.byte 98
+.byte 10
+.byte 0
+.align 3
+L.11:
+.long 0x0
+.long 0x40140000
+.align 0
+L.10:
+.byte 37
+.byte 115
+.byte 37
+.byte 115
+.byte 32
+.byte 37
+.byte 102
+.byte 37
+.byte 99
+.byte 0
+.align 0
+L.9:
+.byte 115
+.byte 116
+.byte 0
+.align 0
+L.8:
+.byte 116
+.byte 101
+.byte 0
+.align 0
+L.7:
+.byte 37
+.byte 115
+.byte 37
+.byte 115
+.byte 32
+.byte 37
+.byte 119
+.byte 37
+.byte 99
+.byte 0
+.align 0
+L.6:
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 37
+.byte 100
+.byte 37
+.byte 99
+.byte 0
+.align 0
+L.5:
+.byte 50
+.byte 0
+.align 0
+L.4:
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.3:
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 49
+.byte 10
+.byte 0
diff --git a/lcc/alpha/osf/tst/struct.1bk b/lcc/alpha/osf/tst/struct.1bk
new file mode 100755
index 0000000..2358779
--- /dev/null
+++ b/lcc/alpha/osf/tst/struct.1bk
@@ -0,0 +1,5 @@
+(-1,-1) is not within [10,10; 310,310]
+(1,1) is not within [10,10; 310,310]
+(20,300) is within [10,10; 310,310]
+(500,400) is not within [10,10; 310,310]
+ab
diff --git a/lcc/alpha/osf/tst/struct.2bk b/lcc/alpha/osf/tst/struct.2bk
new file mode 100755
index 0000000..8a01bb1
--- /dev/null
+++ b/lcc/alpha/osf/tst/struct.2bk
@@ -0,0 +1,2 @@
+tst/struct.c:49: warning: missing return value
+tst/struct.c:68: warning: missing return value
diff --git a/lcc/alpha/osf/tst/struct.sbk b/lcc/alpha/osf/tst/struct.sbk
new file mode 100755
index 0000000..5fd21f4
--- /dev/null
+++ b/lcc/alpha/osf/tst/struct.sbk
@@ -0,0 +1,443 @@
+.globl addpoint
+.text
+.text
+.ent addpoint
+addpoint:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.frame $sp,64,$26,48
+stq $17,24($sp)
+stq $18,32($sp)
+.prologue 1
+ldl $27,-40+64($sp)
+ldl $25,-32+64($sp)
+addl $27,$25,$27
+stl $27,-40+64($sp)
+ldl $27,-36+64($sp)
+ldl $25,-28+64($sp)
+addl $27,$25,$27
+stl $27,-36+64($sp)
+lda $1,-40+64($sp)
+ldl $4,0($1)
+ldl $2,4($1)
+stl $4,0($16)
+stl $2,4($16)
+L.1:
+lda $sp,64($sp)
+ret
+.end addpoint
+.globl canonrect
+.text
+.ent canonrect
+canonrect:
+ldgp $gp,0($27)
+lda $sp,-112($sp)
+.mask 0x4007800,-80
+.frame $sp,112,$26,48
+stq $11,0($sp)
+stq $12,8($sp)
+stq $13,16($sp)
+stq $14,24($sp)
+stq $26,32($sp)
+stq $17,72($sp)
+stq $18,80($sp)
+.prologue 1
+ldl $27,-40+112($sp)
+ldl $25,-32+112($sp)
+cmplt $27,$25,$23
+beq $23,L.10
+ldl $14,-40+112($sp)
+br L.11
+L.10:
+ldl $14,-32+112($sp)
+L.11:
+stl $14,-72+112($sp)
+ldl $27,-36+112($sp)
+ldl $25,-28+112($sp)
+cmplt $27,$25,$23
+beq $23,L.20
+ldl $13,-36+112($sp)
+br L.21
+L.20:
+ldl $13,-28+112($sp)
+L.21:
+stl $13,-68+112($sp)
+ldl $27,-40+112($sp)
+ldl $25,-32+112($sp)
+cmple $27,$25,$23
+bne $23,L.26
+ldl $12,-40+112($sp)
+br L.27
+L.26:
+ldl $12,-32+112($sp)
+L.27:
+stl $12,-64+112($sp)
+ldl $27,-36+112($sp)
+ldl $25,-28+112($sp)
+cmple $27,$25,$23
+bne $23,L.37
+ldl $11,-36+112($sp)
+br L.38
+L.37:
+ldl $11,-28+112($sp)
+L.38:
+stl $11,-60+112($sp)
+lda $1,-72+112($sp)
+ldl $4,0($1)
+ldl $2,4($1)
+stl $4,0($16)
+stl $2,4($16)
+ldl $4,8($1)
+ldl $2,12($1)
+stl $4,8($16)
+stl $2,12($16)
+L.5:
+ldq $11,0($sp)
+ldq $12,8($sp)
+ldq $13,16($sp)
+ldq $14,24($sp)
+ldq $26,32($sp)
+lda $sp,112($sp)
+ret
+.end canonrect
+.globl makepoint
+.text
+.ent makepoint
+makepoint:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.frame $sp,64,$26,48
+.prologue 1
+stl $17,-64+64($sp)
+stl $18,-60+64($sp)
+lda $1,-64+64($sp)
+ldl $4,0($1)
+ldl $2,4($1)
+stl $4,0($16)
+stl $2,4($16)
+L.39:
+lda $sp,64($sp)
+ret
+.end makepoint
+.globl makerect
+.text
+.ent makerect
+makerect:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4000000,-80
+.frame $sp,80,$26,48
+stq $26,0($sp)
+stq $16,32($sp)
+stq $17,40($sp)
+stq $18,48($sp)
+.prologue 1
+lda $27,-72+80($sp)
+lda $1,-40+80($sp)
+ldl $4,0($1)
+ldl $2,4($1)
+stl $4,0($27)
+stl $2,4($27)
+lda $27,-64+80($sp)
+lda $1,-32+80($sp)
+ldl $4,0($1)
+ldl $2,4($1)
+stl $4,0($27)
+stl $2,4($27)
+ldq $16,-48+80($sp)
+lda $1,-72+80($sp)
+uldq $17,0($1)
+uldq $18,8($1)
+jsr $26,canonrect
+ldgp $gp,0($26)
+L.42:
+ldq $26,0($sp)
+lda $sp,80($sp)
+ret
+.end makerect
+.globl ptinrect
+.text
+.ent ptinrect
+ptinrect:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4004000,-72
+.frame $sp,80,$26,48
+stq $14,0($sp)
+stq $26,8($sp)
+stq $16,32($sp)
+stq $17,40($sp)
+stq $18,48($sp)
+.prologue 1
+ldl $27,-48+80($sp)
+ldl $25,-40+80($sp)
+cmplt $27,$25,$23
+bne $23,L.53
+ldl $25,-32+80($sp)
+cmplt $27,$25,$23
+beq $23,L.53
+ldl $27,-44+80($sp)
+ldl $25,-36+80($sp)
+cmplt $27,$25,$23
+bne $23,L.53
+ldl $27,-44+80($sp)
+ldl $25,-28+80($sp)
+cmplt $27,$25,$23
+beq $23,L.53
+lda $14,1
+br L.54
+L.53:
+mov $31,$14
+L.54:
+mov $14,$0
+L.45:
+ldq $14,0($sp)
+ldq $26,8($sp)
+lda $sp,80($sp)
+ret
+.end ptinrect
+.sdata
+.globl y
+.align 0
+y:
+.byte 97
+.byte 98
+.byte 0
+.globl odd
+.text
+.text
+.ent odd
+odd:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4000000,-80
+.frame $sp,80,$26,48
+stq $26,0($sp)
+stq $16,32($sp)
+.prologue 1
+lda $27,-59+80($sp)
+lda $1,-48+80($sp)
+ldb $4,0($1)
+ldb $2,1($1)
+stb $4,0($27)
+stb $2,1($27)
+ldb $4,2($1)
+stb $4,2($27)
+lda $16,L.56
+lda $17,-59+80($sp)
+jsr $26,printf
+ldgp $gp,0($26)
+mov $31,$0
+L.55:
+ldq $26,0($sp)
+lda $sp,80($sp)
+ret
+.end odd
+.rdata
+.align 2
+L.58:
+.long 0x0
+.long 0x0
+.align 2
+L.59:
+.long 0x140
+.long 0x140
+.align 2
+L.60:
+.long 0xffffffff
+.long 0xffffffff
+.long 0x1
+.long 0x1
+.long 0x14
+.long 0x12c
+.long 0x1f4
+.long 0x190
+.globl main
+.text
+.text
+.ent main
+main:
+ldgp $gp,0($27)
+lda $sp,-176($sp)
+.mask 0x4004000,-168
+.frame $sp,176,$26,48
+stq $14,0($sp)
+stq $26,8($sp)
+.prologue 1
+lda $27,-120+176($sp)
+lda $1,L.58
+ldl $4,0($1)
+ldl $2,4($1)
+stl $4,0($27)
+stl $2,4($27)
+lda $27,-128+176($sp)
+lda $1,L.59
+ldl $4,0($1)
+ldl $2,4($1)
+stl $4,0($27)
+stl $2,4($27)
+lda $27,-88+176($sp)
+lda $1,L.60
+addq $1,32,$1
+addq $27,32,$3
+L.76:
+addq $1,-8,$1
+addq $3,-8,$3
+ldl $4,0($1)
+ldl $2,4($1)
+stl $4,0($3)
+stl $2,4($3)
+cmpult $27,$3,$23
+bne $23,L.76
+lda $16,-136+176($sp)
+lda $27,-10
+mov $27,$17
+mov $27,$18
+jsr $26,makepoint
+ldgp $gp,0($26)
+lda $16,-144+176($sp)
+lda $1,-128+176($sp)
+uldq $17,0($1)
+lda $1,-136+176($sp)
+uldq $18,0($1)
+jsr $26,addpoint
+ldgp $gp,0($26)
+lda $16,-152+176($sp)
+lda $27,10
+mov $27,$17
+mov $27,$18
+jsr $26,makepoint
+ldgp $gp,0($26)
+lda $16,-160+176($sp)
+lda $1,-120+176($sp)
+uldq $17,0($1)
+lda $1,-152+176($sp)
+uldq $18,0($1)
+jsr $26,addpoint
+ldgp $gp,0($26)
+lda $16,-104+176($sp)
+lda $1,-144+176($sp)
+uldq $17,0($1)
+lda $1,-160+176($sp)
+uldq $18,0($1)
+jsr $26,makerect
+ldgp $gp,0($26)
+mov $31,$14
+br L.64
+L.61:
+lda $16,-112+176($sp)
+sll $14,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,3,$27
+lda $25,-88+176($sp)
+addq $27,$25,$25
+ldl $17,($25)
+lda $25,-84+176($sp)
+addq $27,$25,$27
+ldl $18,($27)
+jsr $26,makepoint
+ldgp $gp,0($26)
+lda $16,L.65
+sll $14,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,3,$27
+lda $25,-88+176($sp)
+addq $27,$25,$27
+ldl $17,($27)
+ldl $18,-108+176($sp)
+jsr $26,printf
+ldgp $gp,0($26)
+lda $1,-112+176($sp)
+uldq $16,0($1)
+lda $1,-104+176($sp)
+uldq $17,0($1)
+uldq $18,8($1)
+jsr $26,ptinrect
+ldgp $gp,0($26)
+cmpeq $0,$31,$23
+beq $23,L.68
+lda $16,L.70
+jsr $26,printf
+ldgp $gp,0($26)
+L.68:
+lda $16,L.71
+ldl $17,-104+176($sp)
+ldl $18,-100+176($sp)
+ldl $19,-96+176($sp)
+ldl $20,-92+176($sp)
+jsr $26,printf
+ldgp $gp,0($26)
+L.62:
+lda $14,1($14)
+L.64:
+mov $14,$27
+lda $25,4
+cmpult $27,$25,$23
+bne $23,L.61
+lda $1,y
+uldq $16,0($1)
+jsr $26,odd
+ldgp $gp,0($26)
+mov $31,$16
+jsr $26,exit
+ldgp $gp,0($26)
+mov $31,$0
+L.57:
+ldq $14,0($sp)
+ldq $26,8($sp)
+lda $sp,176($sp)
+ret
+.end main
+.rdata
+.align 0
+L.71:
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 105
+.byte 110
+.byte 32
+.byte 91
+.byte 37
+.byte 100
+.byte 44
+.byte 37
+.byte 100
+.byte 59
+.byte 32
+.byte 37
+.byte 100
+.byte 44
+.byte 37
+.byte 100
+.byte 93
+.byte 10
+.byte 0
+.align 0
+L.70:
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 0
+.align 0
+L.65:
+.byte 40
+.byte 37
+.byte 100
+.byte 44
+.byte 37
+.byte 100
+.byte 41
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 0
+.align 0
+L.56:
+.byte 37
+.byte 115
+.byte 10
+.byte 0
diff --git a/lcc/alpha/osf/tst/switch.1bk b/lcc/alpha/osf/tst/switch.1bk
new file mode 100755
index 0000000..559e8e3
--- /dev/null
+++ b/lcc/alpha/osf/tst/switch.1bk
@@ -0,0 +1,76 @@
+b = 0x8
+f = 0xc
+n = 0xa
+r = 0xd
+t = 0x9
+v = 0xb
+x = 0x78
+f:
+x = 0
+x = 1
+x = 2
+x = 2
+x = 2
+x = 2
+x = 2
+x = 7
+x = 8
+x = 9
+x = 9
+x = 9
+x = 9
+x = 9
+x = 9
+x = 9
+x = 16
+x = 17
+x = 18
+x = 19
+x = 20
+g:
+1 1
+1 2
+2 3
+2 4
+2 5
+3 6
+d 6
+3 7
+d 7
+3 8
+d 8
+d 9
+d 10
+h:
+i = 8
+i = 16
+i = 120
+i = 128
+i = 248
+i = 264
+i = 272
+i = 280
+i = 288
+i = 296
+i = 304
+i = 312
+488 defaults
+x = 0x1000000
+x = 0x2000000
+x = 0x3000000
+x = 0x4000000
+x = 0x5000000
+x = 0x6000000 (default)
+x = 0x7000000 (default)
+0
+1
+2
+3
+4
+5
+0
+1
+2
+3
+4
+5
diff --git a/lcc/alpha/osf/tst/switch.2bk b/lcc/alpha/osf/tst/switch.2bk
new file mode 100755
index 0000000..ee469b4
--- /dev/null
+++ b/lcc/alpha/osf/tst/switch.2bk
@@ -0,0 +1,7 @@
+tst/switch.c:55: warning: missing return value
+tst/switch.c:73: warning: missing return value
+tst/switch.c:97: warning: missing return value
+tst/switch.c:101: warning: overflow in converting constant expression from `int' to `unsigned int'
+tst/switch.c:102: warning: overflow in converting constant expression from `int' to `unsigned int'
+tst/switch.c:112: warning: missing return value
+tst/switch.c:137: warning: missing return value
diff --git a/lcc/alpha/osf/tst/switch.sbk b/lcc/alpha/osf/tst/switch.sbk
new file mode 100755
index 0000000..ec8a537
--- /dev/null
+++ b/lcc/alpha/osf/tst/switch.sbk
@@ -0,0 +1,903 @@
+.globl main
+.text
+.text
+.ent main
+main:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4006000,-64
+.frame $sp,80,$26,48
+stq $13,0($sp)
+stq $14,8($sp)
+stq $26,16($sp)
+.prologue 1
+lda $14,L.6
+br L.5
+L.2:
+ldb $16,($14)
+jsr $26,backslash
+ldgp $gp,0($26)
+mov $0,$27
+lda $16,L.7
+ldb $17,($14)
+mov $27,$18
+jsr $26,printf
+ldgp $gp,0($26)
+L.3:
+lda $14,1($14)
+L.5:
+ldb $27,($14)
+cmpeq $27,$31,$23
+beq $23,L.2
+jsr $26,f
+ldgp $gp,0($26)
+jsr $26,g
+ldgp $gp,0($26)
+jsr $26,h
+ldgp $gp,0($26)
+lda $13,16777216
+br L.11
+L.8:
+mov $13,$16
+jsr $26,big
+ldgp $gp,0($26)
+L.9:
+lda $13,16777216($13)
+L.11:
+and $13,117440512,$27
+addl $27,0,$27
+cmpeq $27,$31,$23
+beq $23,L.8
+jsr $26,limit
+ldgp $gp,0($26)
+mov $31,$0
+L.1:
+ldq $13,0($sp)
+ldq $14,8($sp)
+ldq $26,16($sp)
+lda $sp,80($sp)
+ret
+.end main
+.globl backslash
+.text
+.ent backslash
+backslash:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.frame $sp,64,$26,48
+.prologue 1
+lda $27,102
+cmpeq $16,$27,$23
+bne $23,L.16
+cmple $16,$27,$23
+beq $23,L.22
+L.21:
+lda $27,98
+cmpeq $16,$27,$23
+bne $23,L.15
+br L.13
+L.22:
+lda $27,110
+cmpeq $16,$27,$23
+bne $23,L.17
+cmplt $16,$27,$23
+bne $23,L.13
+L.23:
+lda $27,114
+cmpeq $16,$27,$23
+bne $23,L.18
+lda $27,116
+cmpeq $16,$27,$23
+bne $23,L.19
+lda $27,118
+cmpeq $16,$27,$23
+bne $23,L.20
+br L.13
+L.15:
+lda $0,8
+br L.12
+L.16:
+lda $0,12
+br L.12
+L.17:
+lda $0,10
+br L.12
+L.18:
+lda $0,13
+br L.12
+L.19:
+lda $0,9
+br L.12
+L.20:
+lda $0,11
+br L.12
+L.13:
+mov $16,$0
+L.12:
+lda $sp,64($sp)
+ret
+.end backslash
+.globl f
+.text
+.ent f
+f:
+ldgp $gp,0($27)
+lda $sp,-96($sp)
+.mask 0x4007000,-72
+.frame $sp,96,$26,48
+stq $12,0($sp)
+stq $13,8($sp)
+stq $14,16($sp)
+stq $26,24($sp)
+.prologue 1
+mov $31,$13
+lda $16,L.25
+jsr $26,printf
+ldgp $gp,0($26)
+mov $31,$14
+L.26:
+mov $14,$12
+cmplt $14,1,$23
+bne $23,L.30
+cmple $14,20,$23
+beq $23,L.30
+subl $14,1,$27
+sll $27,3,$27
+ldq $27,L.42($27)
+jmp ($27)
+.rdata
+.align 3
+L.42:
+.quad L.32
+.quad L.33
+.quad L.30
+.quad L.30
+.quad L.30
+.quad L.30
+.quad L.34
+.quad L.35
+.quad L.36
+.quad L.30
+.quad L.30
+.quad L.30
+.quad L.30
+.quad L.30
+.quad L.30
+.quad L.37
+.quad L.38
+.quad L.39
+.quad L.40
+.quad L.41
+.text
+L.32:
+mov $14,$13
+br L.31
+L.33:
+mov $14,$13
+br L.31
+L.34:
+mov $14,$13
+br L.31
+L.35:
+mov $14,$13
+br L.31
+L.36:
+mov $14,$13
+br L.31
+L.37:
+mov $14,$13
+br L.31
+L.38:
+mov $14,$13
+br L.31
+L.39:
+mov $14,$13
+br L.31
+L.40:
+mov $14,$13
+br L.31
+L.41:
+mov $14,$13
+L.30:
+L.31:
+lda $16,L.43
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.27:
+lda $14,1($14)
+cmple $14,20,$23
+bne $23,L.26
+mov $31,$0
+L.24:
+ldq $12,0($sp)
+ldq $13,8($sp)
+ldq $14,16($sp)
+ldq $26,24($sp)
+lda $sp,96($sp)
+ret
+.end f
+.globl g
+.text
+.ent g
+g:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4004000,-72
+.frame $sp,80,$26,48
+stq $14,0($sp)
+stq $26,8($sp)
+.prologue 1
+lda $16,L.45
+jsr $26,printf
+ldgp $gp,0($26)
+lda $14,1
+L.46:
+lda $27,1001
+cmplt $14,$27,$23
+bne $23,L.63
+lda $27,1004
+cmple $14,$27,$23
+beq $23,L.64
+subl $14,1001,$27
+sll $27,3,$27
+ldq $27,L.65($27)
+jmp ($27)
+.rdata
+.align 3
+L.65:
+.quad L.59
+.quad L.59
+.quad L.59
+.quad L.59
+.text
+L.63:
+cmplt $14,1,$23
+bne $23,L.50
+cmple $14,8,$23
+beq $23,L.50
+subl $14,1,$27
+sll $27,3,$27
+ldq $27,L.66($27)
+jmp ($27)
+.rdata
+.align 3
+L.66:
+.quad L.52
+.quad L.52
+.quad L.54
+.quad L.54
+.quad L.54
+.quad L.56
+.quad L.56
+.quad L.56
+.text
+L.64:
+lda $27,3001
+cmplt $14,$27,$23
+bne $23,L.50
+lda $27,3004
+cmple $14,$27,$23
+beq $23,L.50
+subl $14,3001,$27
+sll $27,3,$27
+ldq $27,L.67($27)
+jmp ($27)
+.rdata
+.align 3
+L.67:
+.quad L.61
+.quad L.61
+.quad L.61
+.quad L.61
+.text
+L.52:
+lda $16,L.53
+mov $14,$17
+jsr $26,printf
+ldgp $gp,0($26)
+br L.51
+L.54:
+lda $16,L.55
+mov $14,$17
+jsr $26,printf
+ldgp $gp,0($26)
+br L.51
+L.56:
+lda $16,L.57
+mov $14,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.50:
+lda $16,L.58
+mov $14,$17
+jsr $26,printf
+ldgp $gp,0($26)
+br L.51
+L.59:
+lda $16,L.60
+mov $14,$17
+jsr $26,printf
+ldgp $gp,0($26)
+br L.51
+L.61:
+lda $16,L.62
+mov $14,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.51:
+L.47:
+lda $14,1($14)
+cmple $14,10,$23
+bne $23,L.46
+mov $31,$0
+L.44:
+ldq $14,0($sp)
+ldq $26,8($sp)
+lda $sp,80($sp)
+ret
+.end g
+.globl h
+.text
+.ent h
+h:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4006000,-64
+.frame $sp,80,$26,48
+stq $13,0($sp)
+stq $14,8($sp)
+stq $26,16($sp)
+.prologue 1
+mov $31,$13
+lda $16,L.69
+jsr $26,printf
+ldgp $gp,0($26)
+lda $14,1
+L.70:
+lda $27,264
+cmpeq $14,$27,$23
+bne $23,L.82
+cmple $14,$27,$23
+beq $23,L.90
+L.89:
+lda $27,120
+cmpeq $14,$27,$23
+bne $23,L.80
+cmple $14,$27,$23
+beq $23,L.92
+L.91:
+cmpeq $14,8,$23
+bne $23,L.79
+cmplt $14,8,$23
+bne $23,L.74
+L.93:
+cmpeq $14,16,$23
+bne $23,L.78
+br L.74
+L.92:
+lda $27,128
+cmpeq $14,$27,$23
+bne $23,L.76
+cmplt $14,$27,$23
+bne $23,L.74
+L.94:
+lda $27,248
+cmpeq $14,$27,$23
+bne $23,L.83
+br L.74
+L.90:
+lda $27,288
+cmpeq $14,$27,$23
+bne $23,L.87
+cmple $14,$27,$23
+beq $23,L.96
+L.95:
+lda $27,272
+cmpeq $14,$27,$23
+bne $23,L.84
+cmplt $14,$27,$23
+bne $23,L.74
+L.97:
+lda $27,280
+cmpeq $14,$27,$23
+bne $23,L.81
+br L.74
+L.96:
+lda $27,304
+cmpeq $14,$27,$23
+bne $23,L.85
+cmple $14,$27,$23
+beq $23,L.99
+L.98:
+lda $27,296
+cmpeq $14,$27,$23
+bne $23,L.86
+br L.74
+L.99:
+lda $27,312
+cmpeq $14,$27,$23
+bne $23,L.88
+br L.74
+L.74:
+lda $13,1($13)
+br L.71
+L.76:
+lda $16,L.77
+mov $14,$17
+jsr $26,printf
+ldgp $gp,0($26)
+br L.75
+L.78:
+lda $16,L.77
+mov $14,$17
+jsr $26,printf
+ldgp $gp,0($26)
+br L.75
+L.79:
+lda $16,L.77
+mov $14,$17
+jsr $26,printf
+ldgp $gp,0($26)
+br L.75
+L.80:
+lda $16,L.77
+mov $14,$17
+jsr $26,printf
+ldgp $gp,0($26)
+br L.75
+L.81:
+lda $16,L.77
+mov $14,$17
+jsr $26,printf
+ldgp $gp,0($26)
+br L.75
+L.82:
+lda $16,L.77
+mov $14,$17
+jsr $26,printf
+ldgp $gp,0($26)
+br L.75
+L.83:
+lda $16,L.77
+mov $14,$17
+jsr $26,printf
+ldgp $gp,0($26)
+br L.75
+L.84:
+lda $16,L.77
+mov $14,$17
+jsr $26,printf
+ldgp $gp,0($26)
+br L.75
+L.85:
+lda $16,L.77
+mov $14,$17
+jsr $26,printf
+ldgp $gp,0($26)
+br L.75
+L.86:
+lda $16,L.77
+mov $14,$17
+jsr $26,printf
+ldgp $gp,0($26)
+br L.75
+L.87:
+lda $16,L.77
+mov $14,$17
+jsr $26,printf
+ldgp $gp,0($26)
+br L.75
+L.88:
+lda $16,L.77
+mov $14,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.75:
+L.71:
+lda $14,1($14)
+lda $27,500
+cmple $14,$27,$23
+bne $23,L.70
+lda $16,L.100
+mov $13,$17
+jsr $26,printf
+ldgp $gp,0($26)
+mov $31,$0
+L.68:
+ldq $13,0($sp)
+ldq $14,8($sp)
+ldq $26,16($sp)
+lda $sp,80($sp)
+ret
+.end h
+.globl big
+.text
+.ent big
+big:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4004000,-72
+.frame $sp,80,$26,48
+stq $14,0($sp)
+stq $26,8($sp)
+stq $16,32($sp)
+.prologue 1
+ldl $27,-48+80($sp)
+zap $27,240,$27
+and $27,0x6000000,$14
+lda $25,33554432
+cmpeq $14,$25,$23
+bne $23,L.107
+cmple $14,$25,$23
+beq $23,L.111
+L.110:
+lda $25,-2
+cmpeq $14,$25,$23
+bne $23,L.105
+lda $25,-1
+cmpeq $14,$25,$23
+bne $23,L.105
+cmpeq $14,$31,$23
+bne $23,L.105
+br L.102
+L.111:
+mov $14,$27
+lda $25,67108864
+cmpeq $27,$25,$23
+bne $23,L.108
+br L.102
+L.105:
+lda $16,L.106
+ldl $17,-48+80($sp)
+zap $17,240,$17
+jsr $26,printf
+ldgp $gp,0($26)
+br L.103
+L.107:
+lda $16,L.106
+ldl $17,-48+80($sp)
+zap $17,240,$17
+jsr $26,printf
+ldgp $gp,0($26)
+br L.103
+L.108:
+lda $16,L.106
+ldl $17,-48+80($sp)
+zap $17,240,$17
+jsr $26,printf
+ldgp $gp,0($26)
+br L.103
+L.102:
+lda $16,L.109
+ldl $17,-48+80($sp)
+zap $17,240,$17
+jsr $26,printf
+ldgp $gp,0($26)
+L.103:
+mov $31,$0
+L.101:
+ldq $14,0($sp)
+ldq $26,8($sp)
+lda $sp,80($sp)
+ret
+.end big
+.globl limit
+.text
+.ent limit
+limit:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4004000,-72
+.frame $sp,80,$26,48
+stq $14,0($sp)
+stq $26,8($sp)
+.prologue 1
+lda $14,-2147483648
+L.113:
+lda $27,-2147483648
+cmplt $14,$27,$23
+bne $23,L.117
+lda $27,-2147483644
+cmple $14,$27,$23
+beq $23,L.117
+subl $14,-2147483648,$27
+sll $27,3,$27
+ldq $27,L.130($27)
+jmp ($27)
+.rdata
+.align 3
+L.130:
+.quad L.119
+.quad L.121
+.quad L.123
+.quad L.125
+.quad L.127
+.text
+L.119:
+lda $16,L.120
+jsr $26,printf
+ldgp $gp,0($26)
+br L.118
+L.121:
+lda $16,L.122
+jsr $26,printf
+ldgp $gp,0($26)
+br L.118
+L.123:
+lda $16,L.124
+jsr $26,printf
+ldgp $gp,0($26)
+br L.118
+L.125:
+lda $16,L.126
+jsr $26,printf
+ldgp $gp,0($26)
+br L.118
+L.127:
+lda $16,L.128
+jsr $26,printf
+ldgp $gp,0($26)
+br L.118
+L.117:
+lda $16,L.129
+jsr $26,printf
+ldgp $gp,0($26)
+L.118:
+L.114:
+lda $14,1($14)
+lda $27,-2147483643
+cmple $14,$27,$23
+bne $23,L.113
+lda $14,2147483647
+L.131:
+lda $27,2147483643
+cmplt $14,$27,$23
+bne $23,L.135
+lda $27,2147483647
+cmple $14,$27,$23
+beq $23,L.135
+subl $14,2147483643,$27
+sll $27,3,$27
+ldq $27,L.142($27)
+jmp ($27)
+.rdata
+.align 3
+L.142:
+.quad L.141
+.quad L.140
+.quad L.139
+.quad L.138
+.quad L.137
+.text
+L.137:
+lda $16,L.120
+jsr $26,printf
+ldgp $gp,0($26)
+br L.136
+L.138:
+lda $16,L.122
+jsr $26,printf
+ldgp $gp,0($26)
+br L.136
+L.139:
+lda $16,L.124
+jsr $26,printf
+ldgp $gp,0($26)
+br L.136
+L.140:
+lda $16,L.126
+jsr $26,printf
+ldgp $gp,0($26)
+br L.136
+L.141:
+lda $16,L.128
+jsr $26,printf
+ldgp $gp,0($26)
+br L.136
+L.135:
+lda $16,L.129
+jsr $26,printf
+ldgp $gp,0($26)
+L.136:
+L.132:
+subl $14,1,$14
+lda $27,2147483642
+cmplt $14,$27,$23
+beq $23,L.131
+mov $31,$0
+L.112:
+ldq $14,0($sp)
+ldq $26,8($sp)
+lda $sp,80($sp)
+ret
+.end limit
+.rdata
+.align 0
+L.129:
+.byte 53
+.byte 10
+.byte 0
+.align 0
+L.128:
+.byte 52
+.byte 10
+.byte 0
+.align 0
+L.126:
+.byte 51
+.byte 10
+.byte 0
+.align 0
+L.124:
+.byte 50
+.byte 10
+.byte 0
+.align 0
+L.122:
+.byte 49
+.byte 10
+.byte 0
+.align 0
+L.120:
+.byte 48
+.byte 10
+.byte 0
+.align 0
+L.109:
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 120
+.byte 37
+.byte 120
+.byte 32
+.byte 40
+.byte 100
+.byte 101
+.byte 102
+.byte 97
+.byte 117
+.byte 108
+.byte 116
+.byte 41
+.byte 10
+.byte 0
+.align 0
+L.106:
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 120
+.byte 37
+.byte 120
+.byte 10
+.byte 0
+.align 0
+L.100:
+.byte 37
+.byte 100
+.byte 32
+.byte 100
+.byte 101
+.byte 102
+.byte 97
+.byte 117
+.byte 108
+.byte 116
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.77:
+.byte 105
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.69:
+.byte 104
+.byte 58
+.byte 10
+.byte 0
+.align 0
+L.62:
+.byte 54
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.60:
+.byte 53
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.58:
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.57:
+.byte 51
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.55:
+.byte 50
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.53:
+.byte 49
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.45:
+.byte 103
+.byte 58
+.byte 10
+.byte 0
+.align 0
+L.43:
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.25:
+.byte 102
+.byte 58
+.byte 10
+.byte 0
+.align 0
+L.7:
+.byte 37
+.byte 99
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 120
+.byte 37
+.byte 120
+.byte 10
+.byte 0
+.align 0
+L.6:
+.byte 98
+.byte 102
+.byte 110
+.byte 114
+.byte 116
+.byte 118
+.byte 120
+.byte 0
diff --git a/lcc/alpha/osf/tst/wf1.1bk b/lcc/alpha/osf/tst/wf1.1bk
new file mode 100755
index 0000000..095e087
--- /dev/null
+++ b/lcc/alpha/osf/tst/wf1.1bk
@@ -0,0 +1,74 @@
+5 a
+2 and
+5 buf
+16 c
+8 char
+1 compare
+4 cond
+5 count
+1 d
+1 die
+3 else
+1 entry
+1 eof
+4 err
+1 error
+1 exit
+1 folded
+1 for
+1 free
+1 frequencies
+1 frequency
+1 get
+2 getchar
+3 getword
+14 if
+2 in
+1 index
+1 input
+1 install
+8 int
+1 into
+1 is
+4 isletter
+1 it
+1 itself
+5 left
+1 letter
+7 lookup
+1 main
+2 malloc
+1 message
+2 n
+1 necessary
+12 next
+9 node
+4 of
+1 on
+1 or
+1 otherwise
+2 out
+8 p
+3 print
+2 printf
+16 return
+5 right
+4 root
+25 s
+2 storage
+3 strcmp
+1 strcpy
+1 strlen
+8 struct
+1 structures
+2 subtree
+1 t
+5 tprint
+9 tree
+1 uses
+1 version
+1 wf
+3 while
+21 word
+9 words
+2 z
diff --git a/lcc/alpha/osf/tst/wf1.2bk b/lcc/alpha/osf/tst/wf1.2bk
new file mode 100755
index 0000000..0e7a8a6
--- /dev/null
+++ b/lcc/alpha/osf/tst/wf1.2bk
@@ -0,0 +1,2 @@
+tst/wf1.c:29: warning: missing return value
+tst/wf1.c:87: warning: missing return value
diff --git a/lcc/alpha/osf/tst/wf1.sbk b/lcc/alpha/osf/tst/wf1.sbk
new file mode 100755
index 0000000..22f279e
--- /dev/null
+++ b/lcc/alpha/osf/tst/wf1.sbk
@@ -0,0 +1,400 @@
+.globl main
+.text
+.text
+.ent main
+main:
+ldgp $gp,0($27)
+lda $sp,-96($sp)
+.mask 0x4000000,-96
+.frame $sp,96,$26,48
+stq $26,0($sp)
+.prologue 1
+stq $31,-88+96($sp)
+stl $31,next
+br L.3
+L.2:
+lda $16,-76+96($sp)
+lda $17,-88+96($sp)
+jsr $26,lookup
+ldgp $gp,0($26)
+ldl $25,($0)
+lda $25,1($25)
+stl $25,($0)
+L.3:
+lda $16,-76+96($sp)
+jsr $26,getword
+ldgp $gp,0($26)
+cmpeq $0,$31,$23
+beq $23,L.2
+ldq $16,-88+96($sp)
+jsr $26,tprint
+ldgp $gp,0($26)
+mov $31,$0
+L.1:
+ldq $26,0($sp)
+lda $sp,96($sp)
+ret
+.end main
+.globl err
+.text
+.ent err
+err:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+stq $16,16($sp)
+.prologue 1
+lda $16,L.6
+ldq $17,-48+64($sp)
+jsr $26,printf
+ldgp $gp,0($26)
+lda $16,1
+jsr $26,exit
+ldgp $gp,0($26)
+mov $31,$0
+L.5:
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end err
+.globl getword
+.text
+.ent getword
+getword:
+ldgp $gp,0($27)
+lda $sp,-96($sp)
+.mask 0x5006000,-72
+.frame $sp,96,$26,48
+stq $13,0($sp)
+stq $14,8($sp)
+stq $24,16($sp)
+stq $26,24($sp)
+stq $16,48($sp)
+.prologue 1
+L.8:
+L.9:
+jsr $26,getchar
+ldgp $gp,0($26)
+mov $0,$27
+mov $27,$14
+lda $25,-1
+cmpeq $27,$25,$23
+bne $23,L.11
+mov $14,$16
+jsr $26,isletter
+ldgp $gp,0($26)
+cmpeq $0,$31,$23
+bne $23,L.8
+L.11:
+ldq $13,-48+96($sp)
+br L.15
+L.12:
+mov $13,$27
+lda $13,1($27)
+mov $14,$25
+stb $25,($27)
+L.13:
+jsr $26,getchar
+ldgp $gp,0($26)
+mov $0,$14
+L.15:
+mov $14,$16
+jsr $26,isletter
+ldgp $gp,0($26)
+mov $0,$14
+cmpeq $0,$31,$23
+beq $23,L.12
+stb $31,($13)
+mov $13,$27
+ldq $25,-48+96($sp)
+cmpule $27,$25,$23
+bne $23,L.16
+lda $0,1
+br L.7
+L.16:
+mov $31,$0
+L.7:
+ldq $13,0($sp)
+ldq $14,8($sp)
+ldq $24,16($sp)
+ldq $26,24($sp)
+lda $sp,96($sp)
+ret
+.end getword
+.globl isletter
+.text
+.ent isletter
+isletter:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.frame $sp,64,$26,48
+.prologue 1
+lda $27,65
+cmplt $16,$27,$23
+bne $23,L.19
+lda $27,90
+cmple $16,$27,$23
+beq $23,L.19
+lda $16,32($16)
+L.19:
+lda $27,97
+cmplt $16,$27,$23
+bne $23,L.21
+lda $27,122
+cmple $16,$27,$23
+beq $23,L.21
+mov $16,$0
+br L.18
+L.21:
+mov $31,$0
+L.18:
+lda $sp,64($sp)
+ret
+.end isletter
+.globl lookup
+.text
+.ent lookup
+lookup:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4004000,-72
+.frame $sp,80,$26,48
+stq $14,0($sp)
+stq $26,8($sp)
+stq $16,32($sp)
+mov $17,$14
+.prologue 1
+ldq $27,($14)
+cmpeq $27,$31,$23
+bne $23,L.24
+ldq $16,-48+80($sp)
+ldq $27,($14)
+ldq $17,24($27)
+jsr $26,strcmp
+ldgp $gp,0($26)
+stl $0,-60+80($sp)
+ldl $27,-60+80($sp)
+cmplt $27,$31,$23
+beq $23,L.26
+ldq $16,-48+80($sp)
+ldq $27,($14)
+lda $17,8($27)
+jsr $26,lookup
+ldgp $gp,0($26)
+mov $0,$27
+br L.23
+L.26:
+ldl $27,-60+80($sp)
+cmple $27,$31,$23
+bne $23,L.28
+ldq $16,-48+80($sp)
+ldq $27,($14)
+lda $17,16($27)
+jsr $26,lookup
+ldgp $gp,0($26)
+mov $0,$27
+br L.23
+L.28:
+ldq $0,($14)
+br L.23
+L.24:
+ldl $27,next
+lda $25,2000
+cmplt $27,$25,$23
+bne $23,L.30
+lda $16,L.32
+jsr $26,err
+ldgp $gp,0($26)
+L.30:
+ldl $27,next
+sll $27,5,$27
+stl $31,words($27)
+ldl $27,next
+sll $27,5,$27
+stq $31,words+16($27)
+stq $31,words+8($27)
+ldq $16,-48+80($sp)
+jsr $26,strlen
+ldgp $gp,0($26)
+mov $0,$27
+lda $16,1($27)
+jsr $26,malloc
+ldgp $gp,0($26)
+ldl $25,next
+sll $25,5,$25
+stq $0,words+24($25)
+ldl $27,next
+sll $27,5,$27
+ldq $27,words+24($27)
+cmpeq $27,$31,$23
+beq $23,L.36
+lda $16,L.39
+jsr $26,err
+ldgp $gp,0($26)
+L.36:
+ldl $27,next
+sll $27,5,$27
+ldq $16,words+24($27)
+ldq $17,-48+80($sp)
+jsr $26,strcpy
+ldgp $gp,0($26)
+ldl $27,next
+lda $25,1($27)
+stl $25,next
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,5,$27
+lda $27,words($27)
+stq $27,($14)
+mov $27,$0
+L.23:
+ldq $14,0($sp)
+ldq $26,8($sp)
+lda $sp,80($sp)
+ret
+.end lookup
+.globl tprint
+.text
+.ent tprint
+tprint:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4004000,-72
+.frame $sp,80,$26,48
+stq $14,0($sp)
+stq $26,8($sp)
+mov $16,$14
+.prologue 1
+mov $14,$27
+cmpeq $27,$31,$23
+bne $23,L.42
+ldq $16,8($14)
+jsr $26,tprint
+ldgp $gp,0($26)
+lda $16,L.44
+ldl $17,($14)
+ldq $18,24($14)
+jsr $26,printf
+ldgp $gp,0($26)
+ldq $16,16($14)
+jsr $26,tprint
+ldgp $gp,0($26)
+L.42:
+mov $31,$0
+L.41:
+ldq $14,0($sp)
+ldq $26,8($sp)
+lda $sp,80($sp)
+ret
+.end tprint
+.globl strcmp
+.text
+.ent strcmp
+strcmp:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.frame $sp,64,$26,48
+.prologue 1
+br L.47
+L.46:
+mov $16,$27
+lda $16,1($27)
+ldb $27,($27)
+cmpeq $27,$31,$23
+beq $23,L.49
+mov $31,$0
+br L.45
+L.49:
+lda $17,1($17)
+L.47:
+ldb $27,($16)
+ldb $25,($17)
+cmpeq $27,$25,$23
+bne $23,L.46
+ldb $27,($16)
+cmpeq $27,$31,$23
+beq $23,L.51
+lda $0,-1
+br L.45
+L.51:
+ldb $27,($17)
+cmpeq $27,$31,$23
+beq $23,L.53
+lda $0,1
+br L.45
+L.53:
+ldb $27,($16)
+ldb $25,($17)
+subl $27,$25,$0
+L.45:
+lda $sp,64($sp)
+ret
+.end strcmp
+.globl next
+.comm next,4
+.globl words
+.comm words,64000
+.rdata
+.align 0
+L.44:
+.byte 37
+.byte 100
+.byte 9
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.39:
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 119
+.byte 111
+.byte 114
+.byte 100
+.byte 32
+.byte 115
+.byte 116
+.byte 111
+.byte 114
+.byte 97
+.byte 103
+.byte 101
+.byte 0
+.align 0
+L.32:
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 110
+.byte 111
+.byte 100
+.byte 101
+.byte 32
+.byte 115
+.byte 116
+.byte 111
+.byte 114
+.byte 97
+.byte 103
+.byte 101
+.byte 0
+.align 0
+L.6:
+.byte 63
+.byte 32
+.byte 37
+.byte 115
+.byte 10
+.byte 0
diff --git a/lcc/alpha/osf/tst/yacc.1bk b/lcc/alpha/osf/tst/yacc.1bk
new file mode 100755
index 0000000..b08a02f
--- /dev/null
+++ b/lcc/alpha/osf/tst/yacc.1bk
@@ -0,0 +1,10 @@
+a
+b
+load
+negate
+push 5
+c
+load
+multiply
+add
+store
diff --git a/lcc/alpha/osf/tst/yacc.2bk b/lcc/alpha/osf/tst/yacc.2bk
new file mode 100755
index 0000000..a84aa5b
--- /dev/null
+++ b/lcc/alpha/osf/tst/yacc.2bk
@@ -0,0 +1,3 @@
+tst/yacc.c:345: warning: missing return value
+tst/yacc.c:349: warning: missing return value
+tst/yacc.c:359: warning: missing return value
diff --git a/lcc/alpha/osf/tst/yacc.sbk b/lcc/alpha/osf/tst/yacc.sbk
new file mode 100755
index 0000000..e445a42
--- /dev/null
+++ b/lcc/alpha/osf/tst/yacc.sbk
@@ -0,0 +1,2402 @@
+.sdata
+.globl yyin
+.align 3
+yyin:
+.quad _iob
+.globl yyout
+.align 3
+yyout:
+.quad _iob+56
+.globl yylex
+.text
+.text
+.ent yylex
+yylex:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x4004000,-72
+.frame $sp,80,$26,48
+stq $14,0($sp)
+stq $26,8($sp)
+.prologue 1
+br L.5
+L.4:
+L.7:
+lda $27,-1
+cmplt $14,$27,$23
+bne $23,L.8
+cmple $14,4,$23
+beq $23,L.8
+subl $14,-1,$27
+sll $27,3,$27
+ldq $27,L.19($27)
+jmp ($27)
+.rdata
+.align 3
+L.19:
+.quad L.9
+.quad L.10
+.quad L.13
+.quad L.14
+.quad L.9
+.quad L.16
+.text
+L.10:
+jsr $26,yywrap
+ldgp $gp,0($26)
+cmpeq $0,$31,$23
+bne $23,L.9
+mov $31,$0
+br L.3
+L.13:
+lda $0,257
+br L.3
+L.14:
+lda $0,258
+br L.3
+L.16:
+lda $27,yytext
+ldb $0,($27)
+br L.3
+L.8:
+ldq $16,yyout
+lda $17,L.18
+mov $14,$18
+jsr $26,fprintf
+ldgp $gp,0($26)
+L.9:
+L.5:
+jsr $26,yylook
+ldgp $gp,0($26)
+mov $0,$14
+cmplt $0,$31,$23
+beq $23,L.4
+mov $31,$0
+L.3:
+ldq $14,0($sp)
+ldq $26,8($sp)
+lda $sp,80($sp)
+ret
+.end yylex
+.sdata
+.globl yyvstop
+.align 2
+yyvstop:
+.long 0x0
+.long 0x4
+.long 0x0
+.long 0x3
+.long 0x4
+.long 0x0
+.long 0x2
+.long 0x4
+.long 0x0
+.long 0x1
+.long 0x4
+.long 0x0
+.long 0x2
+.long 0x0
+.long 0x1
+.long 0x0
+.long 0x0
+.globl yycrank
+.align 0
+yycrank:
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x1
+.byte 0x3
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x1
+.byte 0x4
+.byte 0x1
+.byte 0x3
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x1
+.byte 0x5
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x1
+.byte 0x6
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x6
+.byte 0x8
+.byte 0x0
+.byte 0x0
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.globl yysvec
+.align 3
+yysvec:
+.quad 0x0
+.quad 0x0
+.quad 0x0
+.quad yycrank-2
+.quad 0x0
+.quad 0x0
+.quad yycrank
+.quad yysvec+24
+.quad 0x0
+.quad yycrank
+.quad 0x0
+.quad yyvstop+4
+.quad yycrank
+.quad 0x0
+.quad yyvstop+12
+.quad yycrank+4
+.quad 0x0
+.quad yyvstop+24
+.quad yycrank+38
+.quad 0x0
+.quad yyvstop+36
+.quad yycrank
+.quad yysvec+120
+.quad yyvstop+48
+.quad yycrank
+.quad yysvec+144
+.quad yyvstop+56
+.quad 0x0
+.quad 0x0
+.quad 0x0
+.globl yytop
+.align 3
+yytop:
+.quad yycrank+282
+.globl yybgin
+.align 3
+yybgin:
+.quad yysvec+24
+.globl yymatch
+.align 0
+yymatch:
+.byte 0
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 9
+.byte 10
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 9
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 65
+.byte 1
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 0
+.globl yyextra
+.align 0
+yyextra:
+.byte 0
+.byte 0
+.byte 0
+.byte 0
+.byte 0
+.byte 0
+.byte 0
+.byte 0
+.byte 0
+.globl yylineno
+.align 2
+yylineno:
+.long 0x1
+.globl yysptr
+.align 3
+yysptr:
+.quad yysbuf
+.globl yyprevious
+.align 2
+yyprevious:
+.long 0xa
+.globl yylook
+.text
+.text
+.ent yylook
+yylook:
+ldgp $gp,0($27)
+lda $sp,-160($sp)
+.mask 0x5007e00,-104
+.frame $sp,160,$26,48
+stq $9,0($sp)
+stq $10,8($sp)
+stq $11,16($sp)
+stq $12,24($sp)
+stq $13,32($sp)
+stq $14,40($sp)
+stq $24,48($sp)
+stq $26,56($sp)
+.prologue 1
+ldl $27,yymorfg
+cmpeq $27,$31,$23
+beq $23,L.35
+lda $11,yytext
+br L.36
+L.35:
+stl $31,yymorfg
+ldl $27,yyleng
+lda $11,yytext($27)
+L.36:
+L.37:
+lda $13,yylstate
+ldq $27,yybgin
+mov $27,$14
+stq $27,yyestate
+ldl $27,yyprevious
+cmpeq $27,10,$23
+beq $23,L.41
+lda $14,24($14)
+L.41:
+L.43:
+ldq $12,($14)
+mov $12,$27
+lda $25,yycrank
+cmpeq $27,$25,$23
+beq $23,L.47
+ldq $27,8($14)
+stq $27,-64+160($sp)
+ldq $27,-64+160($sp)
+cmpeq $27,$31,$23
+beq $23,L.49
+br L.94
+L.49:
+ldq $27,-64+160($sp)
+ldq $27,($27)
+lda $25,yycrank
+cmpeq $27,$25,$23
+beq $23,L.51
+br L.94
+L.51:
+L.47:
+mov $11,$27
+stq $27,-88+160($sp)
+lda $11,1($27)
+ldq $25,yysptr
+lda $22,yysbuf
+cmpule $25,$22,$23
+bne $23,L.61
+ldq $25,yysptr
+lda $25,-1($25)
+stq $25,yysptr
+ldb $25,($25)
+stl $25,-76+160($sp)
+br L.62
+L.61:
+ldq $25,yyin
+ldl $22,($25)
+subl $22,1,$22
+stl $22,($25)
+cmplt $22,$31,$23
+beq $23,L.63
+ldq $16,yyin
+jsr $26,_filbuf
+ldgp $gp,0($26)
+mov $0,$27
+stl $27,-80+160($sp)
+br L.64
+L.63:
+ldq $27,yyin
+lda $27,8($27)
+ldq $25,($27)
+lda $22,1($25)
+stq $22,($27)
+ldbu $27,($25)
+stl $27,-80+160($sp)
+L.64:
+ldl $27,-80+160($sp)
+stl $27,-76+160($sp)
+L.62:
+ldl $27,-76+160($sp)
+stl $27,yytchar
+cmpeq $27,10,$23
+beq $23,L.59
+ldl $27,yylineno
+lda $27,1($27)
+stl $27,yylineno
+ldl $27,yytchar
+stl $27,-72+160($sp)
+br L.60
+L.59:
+ldl $27,yytchar
+stl $27,-72+160($sp)
+L.60:
+ldl $27,-72+160($sp)
+lda $25,-1
+cmpeq $27,$25,$23
+beq $23,L.57
+stl $31,-68+160($sp)
+br L.58
+L.57:
+ldl $27,yytchar
+stl $27,-68+160($sp)
+L.58:
+ldl $27,-68+160($sp)
+mov $27,$10
+ldq $25,-88+160($sp)
+stb $27,($25)
+L.65:
+mov $12,$9
+mov $12,$27
+lda $25,yycrank
+cmpule $27,$25,$23
+bne $23,L.66
+sll $10,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,1,$27
+addq $27,$9,$12
+mov $12,$27
+ldq $25,yytop
+cmpule $27,$25,$23
+beq $23,L.67
+lda $27,24
+ldb $25,($12)
+sll $25,8*(8-4),$25
+sra $25,8*(8-4),$25
+mulq $27,$25,$27
+lda $27,yysvec($27)
+mov $14,$25
+cmpeq $27,$25,$23
+beq $23,L.67
+lda $27,yysvec
+lda $25,24
+lda $22,1($12)
+ldb $22,($22)
+sll $22,8*(8-4),$22
+sra $22,8*(8-4),$22
+mulq $25,$22,$25
+lda $25,yysvec($25)
+cmpeq $25,$27,$23
+beq $23,L.70
+lda $27,-1($11)
+mov $27,$11
+ldb $27,($27)
+stl $27,yytchar
+ldl $27,yytchar
+cmpeq $27,10,$23
+beq $23,L.72
+ldl $27,yylineno
+subl $27,1,$27
+stl $27,yylineno
+L.72:
+ldq $27,yysptr
+lda $25,1($27)
+stq $25,yysptr
+ldl $25,yytchar
+stb $25,($27)
+br L.94
+L.70:
+mov $13,$27
+lda $13,8($27)
+lda $25,24
+lda $22,1($12)
+ldb $22,($22)
+sll $22,8*(8-4),$22
+sra $22,8*(8-4),$22
+mulq $25,$22,$25
+lda $25,yysvec($25)
+mov $25,$14
+stq $25,($27)
+br L.43
+L.66:
+mov $12,$27
+lda $25,yycrank
+cmpult $27,$25,$23
+beq $23,L.75
+lda $27,yycrank
+mov $12,$25
+subq $27,$25,$27
+divq $27,2,$27
+sll $27,1,$27
+lda $27,yycrank($27)
+mov $27,$9
+mov $27,$12
+sll $10,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,1,$27
+addq $27,$12,$12
+mov $12,$27
+ldq $25,yytop
+cmpule $27,$25,$23
+beq $23,L.77
+lda $27,24
+ldb $25,($12)
+sll $25,8*(8-4),$25
+sra $25,8*(8-4),$25
+mulq $27,$25,$27
+lda $27,yysvec($27)
+mov $14,$25
+cmpeq $27,$25,$23
+beq $23,L.77
+lda $27,yysvec
+lda $25,24
+lda $22,1($12)
+ldb $22,($22)
+sll $22,8*(8-4),$22
+sra $22,8*(8-4),$22
+mulq $25,$22,$25
+lda $25,yysvec($25)
+cmpeq $25,$27,$23
+beq $23,L.79
+lda $27,-1($11)
+mov $27,$11
+ldb $27,($27)
+stl $27,yytchar
+ldl $27,yytchar
+cmpeq $27,10,$23
+beq $23,L.81
+ldl $27,yylineno
+subl $27,1,$27
+stl $27,yylineno
+L.81:
+ldq $27,yysptr
+lda $25,1($27)
+stq $25,yysptr
+ldl $25,yytchar
+stb $25,($27)
+br L.94
+L.79:
+mov $13,$27
+lda $13,8($27)
+lda $25,24
+lda $22,1($12)
+ldb $22,($22)
+sll $22,8*(8-4),$22
+sra $22,8*(8-4),$22
+mulq $25,$22,$25
+lda $25,yysvec($25)
+mov $25,$14
+stq $25,($27)
+br L.43
+L.77:
+lda $27,yymatch($10)
+ldb $27,($27)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,1,$27
+addq $27,$9,$12
+mov $12,$27
+ldq $25,yytop
+cmpule $27,$25,$23
+beq $23,L.83
+lda $27,24
+ldb $25,($12)
+sll $25,8*(8-4),$25
+sra $25,8*(8-4),$25
+mulq $27,$25,$27
+lda $27,yysvec($27)
+mov $14,$25
+cmpeq $27,$25,$23
+beq $23,L.83
+lda $27,yysvec
+lda $25,24
+lda $22,1($12)
+ldb $22,($22)
+sll $22,8*(8-4),$22
+sra $22,8*(8-4),$22
+mulq $25,$22,$25
+lda $25,yysvec($25)
+cmpeq $25,$27,$23
+beq $23,L.85
+lda $27,-1($11)
+mov $27,$11
+ldb $27,($27)
+stl $27,yytchar
+ldl $27,yytchar
+cmpeq $27,10,$23
+beq $23,L.87
+ldl $27,yylineno
+subl $27,1,$27
+stl $27,yylineno
+L.87:
+ldq $27,yysptr
+lda $25,1($27)
+stq $25,yysptr
+ldl $25,yytchar
+stb $25,($27)
+br L.94
+L.85:
+mov $13,$27
+lda $13,8($27)
+lda $25,24
+lda $22,1($12)
+ldb $22,($22)
+sll $22,8*(8-4),$22
+sra $22,8*(8-4),$22
+mulq $25,$22,$25
+lda $25,yysvec($25)
+mov $25,$14
+stq $25,($27)
+br L.43
+L.83:
+L.75:
+L.67:
+ldq $27,8($14)
+mov $27,$14
+cmpeq $27,$31,$23
+bne $23,L.89
+ldq $27,($14)
+mov $27,$12
+lda $25,yycrank
+cmpeq $27,$25,$23
+bne $23,L.89
+br L.65
+L.89:
+lda $27,-1($11)
+mov $27,$11
+ldb $27,($27)
+stl $27,yytchar
+ldl $27,yytchar
+cmpeq $27,10,$23
+beq $23,L.91
+ldl $27,yylineno
+subl $27,1,$27
+stl $27,yylineno
+L.91:
+ldq $27,yysptr
+lda $25,1($27)
+stq $25,yysptr
+ldl $25,yytchar
+stb $25,($27)
+br L.94
+L.93:
+mov $11,$27
+lda $11,-1($27)
+stb $31,($27)
+ldq $27,($13)
+mov $31,$25
+mov $27,$22
+cmpeq $22,$25,$23
+bne $23,L.96
+ldq $27,16($27)
+stq $27,yyfnd
+cmpeq $27,$25,$23
+bne $23,L.96
+ldq $27,yyfnd
+ldl $27,($27)
+cmple $27,$31,$23
+bne $23,L.96
+stq $13,yyolsp
+ldq $27,yyfnd
+ldl $27,($27)
+lda $27,yyextra($27)
+ldb $27,($27)
+cmpeq $27,$31,$23
+bne $23,L.98
+br L.101
+L.100:
+lda $13,-8($13)
+mov $11,$27
+lda $11,-1($27)
+ldb $27,($27)
+stl $27,yytchar
+ldl $27,yytchar
+cmpeq $27,10,$23
+beq $23,L.103
+ldl $27,yylineno
+subl $27,1,$27
+stl $27,yylineno
+L.103:
+ldq $27,yysptr
+lda $25,1($27)
+stq $25,yysptr
+ldl $25,yytchar
+stb $25,($27)
+L.101:
+ldq $27,($13)
+ldq $16,16($27)
+ldq $27,yyfnd
+ldl $27,($27)
+negl $27,$17
+jsr $26,yyback
+ldgp $gp,0($26)
+cmpeq $0,1,$23
+bne $23,L.105
+mov $13,$27
+lda $25,yylstate
+cmpule $27,$25,$23
+beq $23,L.100
+L.105:
+L.98:
+ldb $27,($11)
+stl $27,yyprevious
+stq $13,yylsp
+lda $27,yytext
+mov $11,$25
+subq $25,$27,$27
+lda $27,1($27)
+stl $27,yyleng
+ldl $27,yyleng
+stb $31,yytext($27)
+ldq $27,yyfnd
+lda $25,4($27)
+stq $25,yyfnd
+ldl $0,($27)
+br L.34
+L.96:
+ldb $27,($11)
+stl $27,yytchar
+ldl $27,yytchar
+cmpeq $27,10,$23
+beq $23,L.106
+ldl $27,yylineno
+subl $27,1,$27
+stl $27,yylineno
+L.106:
+ldq $27,yysptr
+lda $25,1($27)
+stq $25,yysptr
+ldl $25,yytchar
+stb $25,($27)
+L.94:
+mov $13,$27
+lda $13,-8($27)
+lda $25,yylstate
+cmpule $27,$25,$23
+beq $23,L.93
+lda $27,yytext
+ldb $27,($27)
+cmpeq $27,$31,$23
+beq $23,L.108
+lda $27,yysbuf
+stq $27,yysptr
+mov $31,$0
+br L.34
+L.108:
+ldq $27,yysptr
+lda $25,yysbuf
+cmpule $27,$25,$23
+bne $23,L.118
+ldq $27,yysptr
+lda $27,-1($27)
+stq $27,yysptr
+ldb $27,($27)
+stl $27,-76+160($sp)
+br L.119
+L.118:
+ldq $27,yyin
+ldl $25,($27)
+subl $25,1,$25
+stl $25,($27)
+cmplt $25,$31,$23
+beq $23,L.120
+ldq $16,yyin
+jsr $26,_filbuf
+ldgp $gp,0($26)
+mov $0,$27
+stl $27,-80+160($sp)
+br L.121
+L.120:
+ldq $27,yyin
+lda $27,8($27)
+ldq $25,($27)
+lda $22,1($25)
+stq $22,($27)
+ldbu $27,($25)
+stl $27,-80+160($sp)
+L.121:
+ldl $27,-80+160($sp)
+stl $27,-76+160($sp)
+L.119:
+ldl $27,-76+160($sp)
+stl $27,yytchar
+cmpeq $27,10,$23
+beq $23,L.116
+ldl $27,yylineno
+lda $27,1($27)
+stl $27,yylineno
+ldl $27,yytchar
+stl $27,-72+160($sp)
+br L.117
+L.116:
+ldl $27,yytchar
+stl $27,-72+160($sp)
+L.117:
+ldl $27,-72+160($sp)
+lda $25,-1
+cmpeq $27,$25,$23
+beq $23,L.114
+stl $31,-68+160($sp)
+br L.115
+L.114:
+ldl $27,yytchar
+stl $27,-68+160($sp)
+L.115:
+ldl $27,-68+160($sp)
+stb $27,yytext
+sll $27,8*(8-1),$27
+sra $27,8*(8-1),$27
+stl $27,yyprevious
+ldl $27,yyprevious
+cmple $27,$31,$23
+bne $23,L.122
+ldq $27,yyout
+ldl $25,($27)
+subl $25,1,$25
+stl $25,($27)
+cmplt $25,$31,$23
+beq $23,L.125
+ldl $27,yyprevious
+and $27,(1<<(8*1))-1,$27
+mov $27,$16
+ldq $17,yyout
+jsr $26,_flsbuf
+ldgp $gp,0($26)
+br L.126
+L.125:
+ldq $27,yyout
+lda $27,8($27)
+ldq $25,($27)
+lda $22,1($25)
+stq $22,($27)
+ldl $27,yyprevious
+stb $27,($25)
+L.126:
+L.122:
+lda $11,yytext
+br L.37
+L.34:
+ldq $9,0($sp)
+ldq $10,8($sp)
+ldq $11,16($sp)
+ldq $12,24($sp)
+ldq $13,32($sp)
+ldq $14,40($sp)
+ldq $24,48($sp)
+ldq $26,56($sp)
+lda $sp,160($sp)
+ret
+.end yylook
+.globl yyback
+.text
+.ent yyback
+yyback:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.frame $sp,64,$26,48
+.prologue 1
+mov $16,$27
+cmpeq $27,$31,$23
+beq $23,L.131
+mov $31,$0
+br L.127
+L.130:
+mov $16,$27
+lda $16,4($27)
+ldl $27,($27)
+cmpeq $27,$17,$23
+beq $23,L.133
+lda $0,1
+br L.127
+L.133:
+L.131:
+ldl $27,($16)
+cmpeq $27,$31,$23
+beq $23,L.130
+mov $31,$0
+L.127:
+lda $sp,64($sp)
+ret
+.end yyback
+.globl yyinput
+.text
+.ent yyinput
+yyinput:
+ldgp $gp,0($27)
+lda $sp,-96($sp)
+.mask 0x4007800,-64
+.frame $sp,96,$26,48
+stq $11,0($sp)
+stq $12,8($sp)
+stq $13,16($sp)
+stq $14,24($sp)
+stq $26,32($sp)
+.prologue 1
+ldq $27,yysptr
+lda $25,yysbuf
+cmpule $27,$25,$23
+bne $23,L.144
+ldq $27,yysptr
+lda $27,-1($27)
+stq $27,yysptr
+ldb $12,($27)
+br L.145
+L.144:
+ldq $27,yyin
+ldl $25,($27)
+subl $25,1,$25
+stl $25,($27)
+cmplt $25,$31,$23
+beq $23,L.146
+ldq $16,yyin
+jsr $26,_filbuf
+ldgp $gp,0($26)
+mov $0,$27
+mov $27,$11
+br L.147
+L.146:
+ldq $27,yyin
+lda $27,8($27)
+ldq $25,($27)
+lda $22,1($25)
+stq $22,($27)
+ldbu $11,($25)
+L.147:
+mov $11,$12
+L.145:
+stl $12,yytchar
+cmpeq $12,10,$23
+beq $23,L.142
+ldl $27,yylineno
+lda $27,1($27)
+stl $27,yylineno
+ldl $13,yytchar
+br L.143
+L.142:
+ldl $13,yytchar
+L.143:
+lda $27,-1
+cmpeq $13,$27,$23
+beq $23,L.140
+mov $31,$14
+br L.141
+L.140:
+ldl $14,yytchar
+L.141:
+mov $14,$0
+L.135:
+ldq $11,0($sp)
+ldq $12,8($sp)
+ldq $13,16($sp)
+ldq $14,24($sp)
+ldq $26,32($sp)
+lda $sp,96($sp)
+ret
+.end yyinput
+.globl yyoutput
+.text
+.ent yyoutput
+yyoutput:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x5000000,-72
+.frame $sp,80,$26,48
+stq $24,0($sp)
+stq $26,8($sp)
+stq $16,32($sp)
+.prologue 1
+ldq $27,yyout
+ldl $25,($27)
+subl $25,1,$25
+stl $25,($27)
+cmplt $25,$31,$23
+beq $23,L.150
+ldl $27,-48+80($sp)
+and $27,(1<<(8*1))-1,$27
+mov $27,$16
+ldq $17,yyout
+jsr $26,_flsbuf
+ldgp $gp,0($26)
+br L.151
+L.150:
+ldq $27,yyout
+lda $27,8($27)
+ldq $25,($27)
+lda $22,1($25)
+stq $22,($27)
+ldl $27,-48+80($sp)
+stb $27,($25)
+L.151:
+mov $31,$0
+L.148:
+ldq $24,0($sp)
+ldq $26,8($sp)
+lda $sp,80($sp)
+ret
+.end yyoutput
+.globl yyunput
+.text
+.ent yyunput
+yyunput:
+ldgp $gp,0($27)
+lda $sp,-80($sp)
+.mask 0x5000000,-72
+.frame $sp,80,$26,48
+stq $24,0($sp)
+stq $26,8($sp)
+.prologue 1
+stl $16,yytchar
+ldl $27,yytchar
+cmpeq $27,10,$23
+beq $23,L.153
+ldl $27,yylineno
+subl $27,1,$27
+stl $27,yylineno
+L.153:
+ldq $27,yysptr
+lda $25,1($27)
+stq $25,yysptr
+ldl $25,yytchar
+stb $25,($27)
+mov $31,$0
+L.152:
+ldq $24,0($sp)
+ldq $26,8($sp)
+lda $sp,80($sp)
+ret
+.end yyunput
+.globl main
+.text
+.ent main
+main:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+.prologue 1
+jsr $26,yyparse
+ldgp $gp,0($26)
+mov $31,$0
+L.155:
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end main
+.globl yyerror
+.text
+.ent yyerror
+yyerror:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.mask 0x4000000,-64
+.frame $sp,64,$26,48
+stq $26,0($sp)
+stq $16,16($sp)
+.prologue 1
+lda $16,L.157
+ldq $17,-48+64($sp)
+jsr $26,printf
+ldgp $gp,0($26)
+mov $31,$0
+L.156:
+ldq $26,0($sp)
+lda $sp,64($sp)
+ret
+.end yyerror
+.sdata
+.globl yyexca
+.align 1
+yyexca:
+.word 0xffff
+.word 0x1
+.word 0x0
+.word 0xffff
+.word 0xfffe
+.word 0x0
+.globl yyact
+.align 1
+yyact:
+.word 0xc
+.word 0x2
+.word 0x9
+.word 0x8
+.word 0x11
+.word 0xb
+.word 0x19
+.word 0x11
+.word 0xf
+.word 0x12
+.word 0x10
+.word 0xa
+.word 0x12
+.word 0x11
+.word 0xf
+.word 0x7
+.word 0x10
+.word 0xd
+.word 0x12
+.word 0x5
+.word 0x3
+.word 0x1
+.word 0x0
+.word 0x13
+.word 0x14
+.word 0x0
+.word 0x0
+.word 0x15
+.word 0x16
+.word 0x17
+.word 0x18
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x6
+.word 0xe
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x4
+.word 0x6
+.globl yypact
+.align 1
+yypact:
+.word 0xfc18
+.word 0xfff7
+.word 0xfc18
+.word 0x5
+.word 0xfff9
+.word 0xffc5
+.word 0xfc18
+.word 0xfc18
+.word 0xfc18
+.word 0xffd8
+.word 0xffe3
+.word 0xffd8
+.word 0xffd8
+.word 0xfc18
+.word 0xfc18
+.word 0xffd8
+.word 0xffd8
+.word 0xffd8
+.word 0xffd8
+.word 0xffda
+.word 0xffdd
+.word 0xffda
+.word 0xffda
+.word 0xfc18
+.word 0xfc18
+.word 0xfc18
+.globl yypgo
+.align 1
+yypgo:
+.word 0x0
+.word 0x15
+.word 0x14
+.word 0x11
+.word 0xb
+.globl yyr1
+.align 1
+yyr1:
+.word 0x0
+.word 0x1
+.word 0x1
+.word 0x1
+.word 0x1
+.word 0x2
+.word 0x4
+.word 0x4
+.word 0x4
+.word 0x4
+.word 0x4
+.word 0x4
+.word 0x4
+.word 0x4
+.word 0x3
+.globl yyr2
+.align 1
+yyr2:
+.word 0x0
+.word 0x0
+.word 0x2
+.word 0x3
+.word 0x3
+.word 0x3
+.word 0x3
+.word 0x3
+.word 0x3
+.word 0x3
+.word 0x2
+.word 0x3
+.word 0x1
+.word 0x1
+.word 0x1
+.globl yychk
+.align 1
+yychk:
+.word 0xfc18
+.word 0xffff
+.word 0xa
+.word 0xfffe
+.word 0x100
+.word 0xfffd
+.word 0x101
+.word 0xa
+.word 0xa
+.word 0x3d
+.word 0xfffc
+.word 0x2d
+.word 0x28
+.word 0xfffd
+.word 0x102
+.word 0x2b
+.word 0x2d
+.word 0x2a
+.word 0x2f
+.word 0xfffc
+.word 0xfffc
+.word 0xfffc
+.word 0xfffc
+.word 0xfffc
+.word 0xfffc
+.word 0x29
+.globl yydef
+.align 1
+yydef:
+.word 0x1
+.word 0xfffe
+.word 0x2
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0xe
+.word 0x3
+.word 0x4
+.word 0x0
+.word 0x5
+.word 0x0
+.word 0x0
+.word 0xc
+.word 0xd
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0xa
+.word 0x0
+.word 0x6
+.word 0x7
+.word 0x8
+.word 0x9
+.word 0xb
+.globl yychar
+.align 2
+yychar:
+.long 0xffffffff
+.globl yynerrs
+.align 2
+yynerrs:
+.long 0x0
+.globl yyerrflag
+.align 1
+yyerrflag:
+.word 0x0
+.globl yyparse
+.text
+.text
+.ent yyparse
+yyparse:
+ldgp $gp,0($27)
+lda $sp,-432($sp)
+.mask 0x5007e00,-376
+.frame $sp,432,$26,48
+stq $9,0($sp)
+stq $10,8($sp)
+stq $11,16($sp)
+stq $12,24($sp)
+stq $13,32($sp)
+stq $14,40($sp)
+stq $24,48($sp)
+stq $26,56($sp)
+.prologue 1
+mov $31,$27
+mov $27,$13
+lda $25,-1
+stl $25,yychar
+stl $31,yynerrs
+stw $27,yyerrflag
+lda $12,-360+432($sp)
+lda $10,yyv-4
+L.161:
+lda $27,2($12)
+mov $27,$12
+lda $25,-58+432($sp)
+cmpule $27,$25,$23
+bne $23,L.162
+lda $16,L.165
+jsr $26,yyerror
+ldgp $gp,0($26)
+lda $0,1
+br L.158
+L.162:
+stw $13,($12)
+lda $10,4($10)
+ldl $27,yyval
+stl $27,($10)
+L.166:
+sll $13,8*(8-2),$27
+sra $27,8*(8-2),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,1,$27
+lda $27,yypact($27)
+ldw $11,($27)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+lda $25,-1000
+cmple $27,$25,$23
+beq $23,L.167
+br L.169
+L.167:
+ldl $27,yychar
+cmplt $27,$31,$23
+beq $23,L.170
+jsr $26,yylex
+ldgp $gp,0($26)
+stl $0,yychar
+cmplt $0,$31,$23
+beq $23,L.172
+stl $31,yychar
+L.172:
+L.170:
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+ldl $25,yychar
+addl $27,$25,$27
+mov $27,$11
+sll $27,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmplt $27,$31,$23
+bne $23,L.176
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+lda $25,249
+cmplt $27,$25,$23
+bne $23,L.174
+L.176:
+br L.169
+L.174:
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,1,$27
+lda $27,yyact($27)
+ldw $27,($27)
+mov $27,$11
+sll $27,8*(8-2),$27
+sra $27,8*(8-2),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,1,$27
+lda $27,yychk($27)
+ldw $27,($27)
+ldl $25,yychar
+cmpeq $27,$25,$23
+beq $23,L.177
+lda $27,-1
+stl $27,yychar
+ldl $27,yylval
+stl $27,yyval
+mov $11,$13
+lda $27,yyerrflag
+ldw $27,($27)
+cmple $27,$31,$23
+bne $23,L.161
+lda $27,yyerrflag
+ldw $27,($27)
+subl $27,1,$27
+stw $27,yyerrflag
+br L.161
+L.177:
+L.169:
+sll $13,8*(8-2),$27
+sra $27,8*(8-2),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,1,$27
+lda $27,yydef($27)
+ldw $27,($27)
+mov $27,$11
+sll $27,8*(8-2),$27
+sra $27,8*(8-2),$27
+lda $25,-2
+cmpeq $27,$25,$23
+beq $23,L.181
+ldl $27,yychar
+cmplt $27,$31,$23
+beq $23,L.183
+jsr $26,yylex
+ldgp $gp,0($26)
+stl $0,yychar
+cmplt $0,$31,$23
+beq $23,L.185
+stl $31,yychar
+L.185:
+L.183:
+lda $9,yyexca
+br L.190
+L.187:
+L.188:
+lda $9,4($9)
+L.190:
+ldw $27,($9)
+lda $25,-1
+cmpeq $27,$25,$23
+beq $23,L.187
+lda $27,2($9)
+ldw $27,($27)
+sll $13,8*(8-2),$25
+sra $25,8*(8-2),$25
+cmpeq $27,$25,$23
+beq $23,L.187
+br L.192
+L.191:
+ldw $27,($9)
+ldl $25,yychar
+cmpeq $27,$25,$23
+beq $23,L.194
+br L.193
+L.194:
+L.192:
+lda $27,4($9)
+mov $27,$9
+ldw $27,($27)
+cmplt $27,$31,$23
+beq $23,L.191
+L.193:
+lda $27,2($9)
+ldw $27,($27)
+mov $27,$11
+sll $27,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmplt $27,$31,$23
+beq $23,L.196
+mov $31,$0
+br L.158
+L.196:
+L.181:
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmpeq $27,$31,$23
+beq $23,L.198
+lda $27,yyerrflag
+ldw $27,($27)
+stl $27,-364+432($sp)
+ldl $27,-364+432($sp)
+cmplt $27,$31,$23
+bne $23,L.200
+cmple $27,3,$23
+beq $23,L.200
+sll $27,3,$27
+ldq $27,L.216($27)
+jmp ($27)
+.rdata
+.align 3
+L.216:
+.quad L.203
+.quad L.206
+.quad L.206
+.quad L.213
+.text
+L.203:
+lda $16,L.204
+jsr $26,yyerror
+ldgp $gp,0($26)
+L.205:
+ldl $27,yynerrs
+lda $27,1($27)
+stl $27,yynerrs
+L.206:
+lda $27,3
+stw $27,yyerrflag
+br L.208
+L.207:
+ldw $27,($12)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,1,$27
+lda $27,yypact($27)
+ldw $27,($27)
+lda $27,256($27)
+mov $27,$11
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+cmplt $27,$31,$23
+bne $23,L.210
+lda $25,249
+cmplt $27,$25,$23
+beq $23,L.210
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,1,$27
+lda $27,yyact($27)
+ldw $27,($27)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,1,$27
+lda $27,yychk($27)
+ldw $27,($27)
+lda $25,256
+cmpeq $27,$25,$23
+beq $23,L.210
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,1,$27
+lda $27,yyact($27)
+ldw $13,($27)
+br L.161
+L.210:
+ldw $27,($12)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,1,$27
+lda $27,yypact($27)
+ldw $11,($27)
+lda $12,-2($12)
+lda $10,-4($10)
+L.208:
+mov $12,$27
+lda $25,-358+432($sp)
+cmpult $27,$25,$23
+beq $23,L.207
+L.212:
+lda $0,1
+br L.158
+L.213:
+ldl $27,yychar
+cmpeq $27,$31,$23
+beq $23,L.214
+br L.212
+L.214:
+lda $27,-1
+stl $27,yychar
+br L.166
+L.200:
+L.198:
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,1,$27
+lda $25,yyr2($27)
+ldw $22,($25)
+sll $22,8*(8-4),$22
+sra $22,8*(8-4),$22
+sll $22,1,$22
+subq $12,$22,$12
+mov $10,$14
+ldw $25,($25)
+sll $25,8*(8-4),$25
+sra $25,8*(8-4),$25
+sll $25,2,$25
+subq $10,$25,$10
+ldl $25,4($10)
+stl $25,yyval
+stw $11,-360+432($sp)
+lda $27,yyr1($27)
+ldw $11,($27)
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,1,$27
+lda $27,yypgo($27)
+ldw $27,($27)
+ldw $25,($12)
+addl $27,$25,$27
+lda $27,1($27)
+stw $27,-58+432($sp)
+lda $27,-58+432($sp)
+ldw $27,($27)
+lda $25,249
+cmplt $27,$25,$23
+beq $23,L.219
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,1,$27
+lda $27,yyact($27)
+ldw $27,($27)
+mov $27,$13
+sll $27,8*(8-2),$27
+sra $27,8*(8-2),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,1,$27
+lda $27,yychk($27)
+ldw $27,($27)
+sll $11,8*(8-2),$25
+sra $25,8*(8-2),$25
+negl $25,$25
+cmpeq $27,$25,$23
+bne $23,L.217
+L.219:
+sll $11,8*(8-2),$27
+sra $27,8*(8-2),$27
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,1,$27
+lda $27,yypgo($27)
+ldw $27,($27)
+sll $27,8*(8-4),$27
+sra $27,8*(8-4),$27
+sll $27,1,$27
+lda $27,yyact($27)
+ldw $13,($27)
+L.217:
+lda $27,-360+432($sp)
+ldw $27,($27)
+stl $27,-364+432($sp)
+ldl $27,-364+432($sp)
+cmplt $27,4,$23
+bne $23,L.161
+cmple $27,14,$23
+beq $23,L.161
+subl $27,4,$27
+sll $27,3,$27
+ldq $27,L.241($27)
+jmp ($27)
+.rdata
+.align 3
+L.241:
+.quad L.223
+.quad L.224
+.quad L.226
+.quad L.228
+.quad L.230
+.quad L.232
+.quad L.234
+.quad L.161
+.quad L.236
+.quad L.238
+.quad L.240
+.text
+L.223:
+stw $31,yyerrflag
+br L.161
+L.224:
+lda $16,L.225
+jsr $26,printf
+ldgp $gp,0($26)
+br L.161
+L.226:
+lda $16,L.227
+jsr $26,printf
+ldgp $gp,0($26)
+br L.161
+L.228:
+lda $16,L.229
+jsr $26,printf
+ldgp $gp,0($26)
+br L.161
+L.230:
+lda $16,L.231
+jsr $26,printf
+ldgp $gp,0($26)
+br L.161
+L.232:
+lda $16,L.233
+jsr $26,printf
+ldgp $gp,0($26)
+br L.161
+L.234:
+lda $16,L.235
+jsr $26,printf
+ldgp $gp,0($26)
+br L.161
+L.236:
+lda $16,L.237
+jsr $26,printf
+ldgp $gp,0($26)
+br L.161
+L.238:
+lda $16,L.239
+lda $17,yytext
+jsr $26,printf
+ldgp $gp,0($26)
+br L.161
+L.240:
+lda $16,L.157
+lda $17,yytext
+jsr $26,printf
+ldgp $gp,0($26)
+br L.161
+L.158:
+ldq $9,0($sp)
+ldq $10,8($sp)
+ldq $11,16($sp)
+ldq $12,24($sp)
+ldq $13,32($sp)
+ldq $14,40($sp)
+ldq $24,48($sp)
+ldq $26,56($sp)
+lda $sp,432($sp)
+ret
+.end yyparse
+.globl yywrap
+.text
+.ent yywrap
+yywrap:
+ldgp $gp,0($27)
+lda $sp,-64($sp)
+.frame $sp,64,$26,48
+.prologue 1
+lda $0,1
+L.242:
+lda $sp,64($sp)
+ret
+.end yywrap
+.globl yyv
+.comm yyv,600
+.globl yyfnd
+.comm yyfnd,8
+.globl yyolsp
+.comm yyolsp,8
+.globl yylsp
+.comm yylsp,8
+.globl yylstate
+.comm yylstate,1600
+.globl yyestate
+.comm yyestate,8
+.globl yytchar
+.comm yytchar,4
+.globl yysbuf
+.comm yysbuf,200
+.globl yymorfg
+.comm yymorfg,4
+.globl yytext
+.comm yytext,200
+.globl yyleng
+.comm yyleng,4
+.extern _iob 0
+.globl yyval
+.comm yyval,4
+.globl yylval
+.comm yylval,4
+.rdata
+.align 0
+L.239:
+.byte 112
+.byte 117
+.byte 115
+.byte 104
+.byte 32
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.237:
+.byte 108
+.byte 111
+.byte 97
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.235:
+.byte 110
+.byte 101
+.byte 103
+.byte 97
+.byte 116
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.233:
+.byte 100
+.byte 105
+.byte 118
+.byte 105
+.byte 100
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.231:
+.byte 109
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 121
+.byte 10
+.byte 0
+.align 0
+L.229:
+.byte 110
+.byte 101
+.byte 103
+.byte 97
+.byte 116
+.byte 101
+.byte 10
+.byte 97
+.byte 100
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.227:
+.byte 97
+.byte 100
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.225:
+.byte 115
+.byte 116
+.byte 111
+.byte 114
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.204:
+.byte 115
+.byte 121
+.byte 110
+.byte 116
+.byte 97
+.byte 120
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 0
+.align 0
+L.165:
+.byte 121
+.byte 97
+.byte 99
+.byte 99
+.byte 32
+.byte 115
+.byte 116
+.byte 97
+.byte 99
+.byte 107
+.byte 32
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 0
+.align 0
+L.157:
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.18:
+.byte 98
+.byte 97
+.byte 100
+.byte 32
+.byte 115
+.byte 119
+.byte 105
+.byte 116
+.byte 99
+.byte 104
+.byte 32
+.byte 121
+.byte 121
+.byte 108
+.byte 111
+.byte 111
+.byte 107
+.byte 32
+.byte 37
+.byte 100
+.byte 0
diff --git a/lcc/bin/lcc.exe b/lcc/bin/lcc.exe
new file mode 100755
index 0000000..4e52b30
--- /dev/null
+++ b/lcc/bin/lcc.exe
Binary files differ
diff --git a/lcc/bin/q3cpp.exe b/lcc/bin/q3cpp.exe
new file mode 100755
index 0000000..e03aee0
--- /dev/null
+++ b/lcc/bin/q3cpp.exe
Binary files differ
diff --git a/lcc/bin/q3rcc.exe b/lcc/bin/q3rcc.exe
new file mode 100755
index 0000000..f545d5d
--- /dev/null
+++ b/lcc/bin/q3rcc.exe
Binary files differ
diff --git a/lcc/buildnt.bat b/lcc/buildnt.bat
new file mode 100755
index 0000000..7c48b13
--- /dev/null
+++ b/lcc/buildnt.bat
@@ -0,0 +1,3 @@
+call vcvars32
+set BUILDDIR=bin
+nmake -f makefile.nt all
diff --git a/lcc/buildnt.sh b/lcc/buildnt.sh
new file mode 100755
index 0000000..5d44b76
--- /dev/null
+++ b/lcc/buildnt.sh
@@ -0,0 +1,4 @@
+#!/bin/sh
+export BUILDDIR=.\\out
+mkdir out
+nmake -f makefile.nt all
diff --git a/lcc/cpp/cpp.c b/lcc/cpp/cpp.c
new file mode 100755
index 0000000..f632332
--- /dev/null
+++ b/lcc/cpp/cpp.c
@@ -0,0 +1,322 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <stdarg.h>
+#include "cpp.h"
+
+char rcsid[] = "cpp.c - faked rcsid";
+
+#define OUTS 16384
+char outbuf[OUTS];
+char *outp = outbuf;
+Source *cursource;
+int nerrs;
+struct token nltoken = { NL, 0, 0, 0, 1, (uchar*)"\n" };
+char *curtime;
+int incdepth;
+int ifdepth;
+int ifsatisfied[NIF];
+int skipping;
+
+
+int
+main(int argc, char **argv)
+{
+ Tokenrow tr;
+ time_t t;
+ char ebuf[BUFSIZ];
+
+ setbuf(stderr, ebuf);
+ t = time(NULL);
+ curtime = ctime(&t);
+ maketokenrow(3, &tr);
+ expandlex();
+ setup(argc, argv);
+ fixlex();
+ iniths();
+ genline();
+ process(&tr);
+ flushout();
+ fflush(stderr);
+ exit(nerrs > 0);
+ return 0;
+}
+
+void
+process(Tokenrow *trp)
+{
+ int anymacros = 0;
+
+ for (;;) {
+ if (trp->tp >= trp->lp) {
+ trp->tp = trp->lp = trp->bp;
+ outp = outbuf;
+ anymacros |= gettokens(trp, 1);
+ trp->tp = trp->bp;
+ }
+ if (trp->tp->type == END) {
+ if (--incdepth>=0) {
+ if (cursource->ifdepth)
+ error(ERROR,
+ "Unterminated conditional in #include");
+ unsetsource();
+ cursource->line += cursource->lineinc;
+ trp->tp = trp->lp;
+ genline();
+ continue;
+ }
+ if (ifdepth)
+ error(ERROR, "Unterminated #if/#ifdef/#ifndef");
+ break;
+ }
+ if (trp->tp->type==SHARP) {
+ trp->tp += 1;
+ control(trp);
+ } else if (!skipping && anymacros)
+ expandrow(trp, NULL);
+ if (skipping)
+ setempty(trp);
+ puttokens(trp);
+ anymacros = 0;
+ cursource->line += cursource->lineinc;
+ if (cursource->lineinc>1) {
+ genline();
+ }
+ }
+}
+
+void
+control(Tokenrow *trp)
+{
+ Nlist *np;
+ Token *tp;
+
+ tp = trp->tp;
+ if (tp->type!=NAME) {
+ if (tp->type==NUMBER)
+ goto kline;
+ if (tp->type != NL)
+ error(ERROR, "Unidentifiable control line");
+ return; /* else empty line */
+ }
+ if ((np = lookup(tp, 0))==NULL || (np->flag&ISKW)==0 && !skipping) {
+ error(WARNING, "Unknown preprocessor control %t", tp);
+ return;
+ }
+ if (skipping) {
+ switch (np->val) {
+ case KENDIF:
+ if (--ifdepth<skipping)
+ skipping = 0;
+ --cursource->ifdepth;
+ setempty(trp);
+ return;
+
+ case KIFDEF:
+ case KIFNDEF:
+ case KIF:
+ if (++ifdepth >= NIF)
+ error(FATAL, "#if too deeply nested");
+ ++cursource->ifdepth;
+ return;
+
+ case KELIF:
+ case KELSE:
+ if (ifdepth<=skipping)
+ break;
+ return;
+
+ default:
+ return;
+ }
+ }
+ switch (np->val) {
+ case KDEFINE:
+ dodefine(trp);
+ break;
+
+ case KUNDEF:
+ tp += 1;
+ if (tp->type!=NAME || trp->lp - trp->bp != 4) {
+ error(ERROR, "Syntax error in #undef");
+ break;
+ }
+ if ((np = lookup(tp, 0)) != NULL)
+ np->flag &= ~ISDEFINED;
+ break;
+
+ case KPRAGMA:
+ return;
+
+ case KIFDEF:
+ case KIFNDEF:
+ case KIF:
+ if (++ifdepth >= NIF)
+ error(FATAL, "#if too deeply nested");
+ ++cursource->ifdepth;
+ ifsatisfied[ifdepth] = 0;
+ if (eval(trp, np->val))
+ ifsatisfied[ifdepth] = 1;
+ else
+ skipping = ifdepth;
+ break;
+
+ case KELIF:
+ if (ifdepth==0) {
+ error(ERROR, "#elif with no #if");
+ return;
+ }
+ if (ifsatisfied[ifdepth]==2)
+ error(ERROR, "#elif after #else");
+ if (eval(trp, np->val)) {
+ if (ifsatisfied[ifdepth])
+ skipping = ifdepth;
+ else {
+ skipping = 0;
+ ifsatisfied[ifdepth] = 1;
+ }
+ } else
+ skipping = ifdepth;
+ break;
+
+ case KELSE:
+ if (ifdepth==0 || cursource->ifdepth==0) {
+ error(ERROR, "#else with no #if");
+ return;
+ }
+ if (ifsatisfied[ifdepth]==2)
+ error(ERROR, "#else after #else");
+ if (trp->lp - trp->bp != 3)
+ error(ERROR, "Syntax error in #else");
+ skipping = ifsatisfied[ifdepth]? ifdepth: 0;
+ ifsatisfied[ifdepth] = 2;
+ break;
+
+ case KENDIF:
+ if (ifdepth==0 || cursource->ifdepth==0) {
+ error(ERROR, "#endif with no #if");
+ return;
+ }
+ --ifdepth;
+ --cursource->ifdepth;
+ if (trp->lp - trp->bp != 3)
+ error(WARNING, "Syntax error in #endif");
+ break;
+
+ case KERROR:
+ trp->tp = tp+1;
+ error(WARNING, "#error directive: %r", trp);
+ break;
+
+ case KLINE:
+ trp->tp = tp+1;
+ expandrow(trp, "<line>");
+ tp = trp->bp+2;
+ kline:
+ if (tp+1>=trp->lp || tp->type!=NUMBER || tp+3<trp->lp
+ || (tp+3==trp->lp && ((tp+1)->type!=STRING)||*(tp+1)->t=='L')){
+ error(ERROR, "Syntax error in #line");
+ return;
+ }
+ cursource->line = atol((char*)tp->t)-1;
+ if (cursource->line<0 || cursource->line>=32768)
+ error(WARNING, "#line specifies number out of range");
+ tp = tp+1;
+ if (tp+1<trp->lp)
+ cursource->filename=(char*)newstring(tp->t+1,tp->len-2,0);
+ return;
+
+ case KDEFINED:
+ error(ERROR, "Bad syntax for control line");
+ break;
+
+ case KINCLUDE:
+ doinclude(trp);
+ trp->lp = trp->bp;
+ return;
+
+ case KEVAL:
+ eval(trp, np->val);
+ break;
+
+ default:
+ error(ERROR, "Preprocessor control `%t' not yet implemented", tp);
+ break;
+ }
+ setempty(trp);
+ return;
+}
+
+void *
+domalloc(int size)
+{
+ void *p = malloc(size);
+
+ if (p==NULL)
+ error(FATAL, "Out of memory from malloc");
+ return p;
+}
+
+void
+dofree(void *p)
+{
+ free(p);
+}
+
+void
+error(enum errtype type, char *string, ...)
+{
+ va_list ap;
+ char *cp, *ep;
+ Token *tp;
+ Tokenrow *trp;
+ Source *s;
+ int i;
+
+ fprintf(stderr, "cpp: ");
+ for (s=cursource; s; s=s->next)
+ if (*s->filename)
+ fprintf(stderr, "%s:%d ", s->filename, s->line);
+ va_start(ap, string);
+ for (ep=string; *ep; ep++) {
+ if (*ep=='%') {
+ switch (*++ep) {
+
+ case 's':
+ cp = va_arg(ap, char *);
+ fprintf(stderr, "%s", cp);
+ break;
+ case 'd':
+ i = va_arg(ap, int);
+ fprintf(stderr, "%d", i);
+ break;
+ case 't':
+ tp = va_arg(ap, Token *);
+ fprintf(stderr, "%.*s", tp->len, tp->t);
+ break;
+
+ case 'r':
+ trp = va_arg(ap, Tokenrow *);
+ for (tp=trp->tp; tp<trp->lp&&tp->type!=NL; tp++) {
+ if (tp>trp->tp && tp->wslen)
+ fputc(' ', stderr);
+ fprintf(stderr, "%.*s", tp->len, tp->t);
+ }
+ break;
+
+ default:
+ fputc(*ep, stderr);
+ break;
+ }
+ } else
+ fputc(*ep, stderr);
+ }
+ va_end(ap);
+ fputc('\n', stderr);
+ if (type==FATAL)
+ exit(1);
+ if (type!=WARNING)
+ nerrs = 1;
+ fflush(stderr);
+}
diff --git a/lcc/cpp/cpp.h b/lcc/cpp/cpp.h
new file mode 100755
index 0000000..3c8a61c
--- /dev/null
+++ b/lcc/cpp/cpp.h
@@ -0,0 +1,163 @@
+#define INS 32768 /* input buffer */
+#define OBS 4096 /* outbut buffer */
+#define NARG 32 /* Max number arguments to a macro */
+#define NINCLUDE 32 /* Max number of include directories (-I) */
+#define NIF 32 /* depth of nesting of #if */
+#ifndef EOF
+#define EOF (-1)
+#endif
+#ifndef NULL
+#define NULL 0
+#endif
+
+#ifndef __alpha
+typedef unsigned char uchar;
+#endif
+
+enum toktype { END, UNCLASS, NAME, NUMBER, STRING, CCON, NL, WS, DSHARP,
+ EQ, NEQ, LEQ, GEQ, LSH, RSH, LAND, LOR, PPLUS, MMINUS,
+ ARROW, SBRA, SKET, LP, RP, DOT, AND, STAR, PLUS, MINUS,
+ TILDE, NOT, SLASH, PCT, LT, GT, CIRC, OR, QUEST,
+ COLON, ASGN, COMMA, SHARP, SEMIC, CBRA, CKET,
+ ASPLUS, ASMINUS, ASSTAR, ASSLASH, ASPCT, ASCIRC, ASLSH,
+ ASRSH, ASOR, ASAND, ELLIPS,
+ DSHARP1, NAME1, DEFINED, UMINUS };
+
+enum kwtype { KIF, KIFDEF, KIFNDEF, KELIF, KELSE, KENDIF, KINCLUDE, KDEFINE,
+ KUNDEF, KLINE, KERROR, KPRAGMA, KDEFINED,
+ KLINENO, KFILE, KDATE, KTIME, KSTDC, KEVAL };
+
+#define ISDEFINED 01 /* has #defined value */
+#define ISKW 02 /* is PP keyword */
+#define ISUNCHANGE 04 /* can't be #defined in PP */
+#define ISMAC 010 /* builtin macro, e.g. __LINE__ */
+
+#define EOB 0xFE /* sentinel for end of input buffer */
+#define EOFC 0xFD /* sentinel for end of input file */
+#define XPWS 1 /* token flag: white space to assure token sep. */
+
+typedef struct token {
+ unsigned char type;
+ unsigned char flag;
+ unsigned short hideset;
+ unsigned int wslen;
+ unsigned int len;
+ uchar *t;
+} Token;
+
+typedef struct tokenrow {
+ Token *tp; /* current one to scan */
+ Token *bp; /* base (allocated value) */
+ Token *lp; /* last+1 token used */
+ int max; /* number allocated */
+} Tokenrow;
+
+typedef struct source {
+ char *filename; /* name of file of the source */
+ int line; /* current line number */
+ int lineinc; /* adjustment for \\n lines */
+ uchar *inb; /* input buffer */
+ uchar *inp; /* input pointer */
+ uchar *inl; /* end of input */
+ int fd; /* input source */
+ int ifdepth; /* conditional nesting in include */
+ struct source *next; /* stack for #include */
+} Source;
+
+typedef struct nlist {
+ struct nlist *next;
+ uchar *name;
+ int len;
+ Tokenrow *vp; /* value as macro */
+ Tokenrow *ap; /* list of argument names, if any */
+ char val; /* value as preprocessor name */
+ char flag; /* is defined, is pp name */
+} Nlist;
+
+typedef struct includelist {
+ char deleted;
+ char always;
+ char *file;
+} Includelist;
+
+#define new(t) (t *)domalloc(sizeof(t))
+#define quicklook(a,b) (namebit[(a)&077] & (1<<((b)&037)))
+#define quickset(a,b) namebit[(a)&077] |= (1<<((b)&037))
+extern unsigned long namebit[077+1];
+
+enum errtype { WARNING, ERROR, FATAL };
+
+void expandlex(void);
+void fixlex(void);
+void setup(int, char **);
+int gettokens(Tokenrow *, int);
+int comparetokens(Tokenrow *, Tokenrow *);
+Source *setsource(char *, int, char *);
+void unsetsource(void);
+void puttokens(Tokenrow *);
+void process(Tokenrow *);
+void *domalloc(int);
+void dofree(void *);
+void error(enum errtype, char *, ...);
+void flushout(void);
+int fillbuf(Source *);
+int trigraph(Source *);
+int foldline(Source *);
+Nlist *lookup(Token *, int);
+void control(Tokenrow *);
+void dodefine(Tokenrow *);
+void doadefine(Tokenrow *, int);
+void doinclude(Tokenrow *);
+void doif(Tokenrow *, enum kwtype);
+void expand(Tokenrow *, Nlist *);
+void builtin(Tokenrow *, int);
+int gatherargs(Tokenrow *, Tokenrow **, int *);
+void substargs(Nlist *, Tokenrow *, Tokenrow **);
+void expandrow(Tokenrow *, char *);
+void maketokenrow(int, Tokenrow *);
+Tokenrow *copytokenrow(Tokenrow *, Tokenrow *);
+Token *growtokenrow(Tokenrow *);
+Tokenrow *normtokenrow(Tokenrow *);
+void adjustrow(Tokenrow *, int);
+void movetokenrow(Tokenrow *, Tokenrow *);
+void insertrow(Tokenrow *, int, Tokenrow *);
+void peektokens(Tokenrow *, char *);
+void doconcat(Tokenrow *);
+Tokenrow *stringify(Tokenrow *);
+int lookuparg(Nlist *, Token *);
+long eval(Tokenrow *, int);
+void genline(void);
+void setempty(Tokenrow *);
+void makespace(Tokenrow *);
+char *outnum(char *, int);
+int digit(int);
+uchar *newstring(uchar *, int, int);
+int checkhideset(int, Nlist *);
+void prhideset(int);
+int newhideset(int, Nlist *);
+int unionhideset(int, int);
+void iniths(void);
+void setobjname(char *);
+#define rowlen(tokrow) ((tokrow)->lp - (tokrow)->bp)
+
+extern char *outp;
+extern Token nltoken;
+extern Source *cursource;
+extern char *curtime;
+extern int incdepth;
+extern int ifdepth;
+extern int ifsatisfied[NIF];
+extern int Mflag;
+extern int skipping;
+extern int verbose;
+extern int Cplusplus;
+extern Nlist *kwdefined;
+extern Includelist includelist[NINCLUDE];
+extern char wd[];
+
+extern int creat(char *, int);
+extern int open(char *, int);
+extern int close(int);
+extern int dup2(int, int);
+extern int write(int, char *, size_t);
+extern int read(int, char *, size_t);
diff --git a/lcc/cpp/eval.c b/lcc/cpp/eval.c
new file mode 100755
index 0000000..2442ac2
--- /dev/null
+++ b/lcc/cpp/eval.c
@@ -0,0 +1,520 @@
+#include <stdlib.h>
+#include <string.h>
+#include "cpp.h"
+
+#define NSTAK 32
+#define SGN 0
+#define UNS 1
+#define UND 2
+
+#define UNSMARK 0x1000
+
+struct value {
+ long val;
+ int type;
+};
+
+/* conversion types */
+#define RELAT 1
+#define ARITH 2
+#define LOGIC 3
+#define SPCL 4
+#define SHIFT 5
+#define UNARY 6
+
+/* operator priority, arity, and conversion type, indexed by tokentype */
+struct pri {
+ char pri;
+ char arity;
+ char ctype;
+} priority[] = {
+ { 0, 0, 0 }, /* END */
+ { 0, 0, 0 }, /* UNCLASS */
+ { 0, 0, 0 }, /* NAME */
+ { 0, 0, 0 }, /* NUMBER */
+ { 0, 0, 0 }, /* STRING */
+ { 0, 0, 0 }, /* CCON */
+ { 0, 0, 0 }, /* NL */
+ { 0, 0, 0 }, /* WS */
+ { 0, 0, 0 }, /* DSHARP */
+ { 11, 2, RELAT }, /* EQ */
+ { 11, 2, RELAT }, /* NEQ */
+ { 12, 2, RELAT }, /* LEQ */
+ { 12, 2, RELAT }, /* GEQ */
+ { 13, 2, SHIFT }, /* LSH */
+ { 13, 2, SHIFT }, /* RSH */
+ { 7, 2, LOGIC }, /* LAND */
+ { 6, 2, LOGIC }, /* LOR */
+ { 0, 0, 0 }, /* PPLUS */
+ { 0, 0, 0 }, /* MMINUS */
+ { 0, 0, 0 }, /* ARROW */
+ { 0, 0, 0 }, /* SBRA */
+ { 0, 0, 0 }, /* SKET */
+ { 3, 0, 0 }, /* LP */
+ { 3, 0, 0 }, /* RP */
+ { 0, 0, 0 }, /* DOT */
+ { 10, 2, ARITH }, /* AND */
+ { 15, 2, ARITH }, /* STAR */
+ { 14, 2, ARITH }, /* PLUS */
+ { 14, 2, ARITH }, /* MINUS */
+ { 16, 1, UNARY }, /* TILDE */
+ { 16, 1, UNARY }, /* NOT */
+ { 15, 2, ARITH }, /* SLASH */
+ { 15, 2, ARITH }, /* PCT */
+ { 12, 2, RELAT }, /* LT */
+ { 12, 2, RELAT }, /* GT */
+ { 9, 2, ARITH }, /* CIRC */
+ { 8, 2, ARITH }, /* OR */
+ { 5, 2, SPCL }, /* QUEST */
+ { 5, 2, SPCL }, /* COLON */
+ { 0, 0, 0 }, /* ASGN */
+ { 4, 2, 0 }, /* COMMA */
+ { 0, 0, 0 }, /* SHARP */
+ { 0, 0, 0 }, /* SEMIC */
+ { 0, 0, 0 }, /* CBRA */
+ { 0, 0, 0 }, /* CKET */
+ { 0, 0, 0 }, /* ASPLUS */
+ { 0, 0, 0 }, /* ASMINUS */
+ { 0, 0, 0 }, /* ASSTAR */
+ { 0, 0, 0 }, /* ASSLASH */
+ { 0, 0, 0 }, /* ASPCT */
+ { 0, 0, 0 }, /* ASCIRC */
+ { 0, 0, 0 }, /* ASLSH */
+ { 0, 0, 0 }, /* ASRSH */
+ { 0, 0, 0 }, /* ASOR */
+ { 0, 0, 0 }, /* ASAND */
+ { 0, 0, 0 }, /* ELLIPS */
+ { 0, 0, 0 }, /* DSHARP1 */
+ { 0, 0, 0 }, /* NAME1 */
+ { 16, 1, UNARY }, /* DEFINED */
+ { 16, 0, UNARY }, /* UMINUS */
+};
+
+int evalop(struct pri);
+struct value tokval(Token *);
+struct value vals[NSTAK], *vp;
+enum toktype ops[NSTAK], *op;
+
+/*
+ * Evaluate an #if #elif #ifdef #ifndef line. trp->tp points to the keyword.
+ */
+long
+eval(Tokenrow *trp, int kw)
+{
+ Token *tp;
+ Nlist *np;
+ int ntok, rand;
+
+ trp->tp++;
+ if (kw==KIFDEF || kw==KIFNDEF) {
+ if (trp->lp - trp->bp != 4 || trp->tp->type!=NAME) {
+ error(ERROR, "Syntax error in #ifdef/#ifndef");
+ return 0;
+ }
+ np = lookup(trp->tp, 0);
+ return (kw==KIFDEF) == (np && np->flag&(ISDEFINED|ISMAC));
+ }
+ ntok = trp->tp - trp->bp;
+ kwdefined->val = KDEFINED; /* activate special meaning of defined */
+ expandrow(trp, "<if>");
+ kwdefined->val = NAME;
+ vp = vals;
+ op = ops;
+ *op++ = END;
+ for (rand=0, tp = trp->bp+ntok; tp < trp->lp; tp++) {
+ switch(tp->type) {
+ case WS:
+ case NL:
+ continue;
+
+ /* nilary */
+ case NAME:
+ case NAME1:
+ case NUMBER:
+ case CCON:
+ case STRING:
+ if (rand)
+ goto syntax;
+ *vp++ = tokval(tp);
+ rand = 1;
+ continue;
+
+ /* unary */
+ case DEFINED:
+ case TILDE:
+ case NOT:
+ if (rand)
+ goto syntax;
+ *op++ = tp->type;
+ continue;
+
+ /* unary-binary */
+ case PLUS: case MINUS: case STAR: case AND:
+ if (rand==0) {
+ if (tp->type==MINUS)
+ *op++ = UMINUS;
+ if (tp->type==STAR || tp->type==AND) {
+ error(ERROR, "Illegal operator * or & in #if/#elsif");
+ return 0;
+ }
+ continue;
+ }
+ /* flow through */
+
+ /* plain binary */
+ case EQ: case NEQ: case LEQ: case GEQ: case LSH: case RSH:
+ case LAND: case LOR: case SLASH: case PCT:
+ case LT: case GT: case CIRC: case OR: case QUEST:
+ case COLON: case COMMA:
+ if (rand==0)
+ goto syntax;
+ if (evalop(priority[tp->type])!=0)
+ return 0;
+ *op++ = tp->type;
+ rand = 0;
+ continue;
+
+ case LP:
+ if (rand)
+ goto syntax;
+ *op++ = LP;
+ continue;
+
+ case RP:
+ if (!rand)
+ goto syntax;
+ if (evalop(priority[RP])!=0)
+ return 0;
+ if (op<=ops || op[-1]!=LP) {
+ goto syntax;
+ }
+ op--;
+ continue;
+
+ default:
+ error(ERROR,"Bad operator (%t) in #if/#elsif", tp);
+ return 0;
+ }
+ }
+ if (rand==0)
+ goto syntax;
+ if (evalop(priority[END])!=0)
+ return 0;
+ if (op!=&ops[1] || vp!=&vals[1]) {
+ error(ERROR, "Botch in #if/#elsif");
+ return 0;
+ }
+ if (vals[0].type==UND)
+ error(ERROR, "Undefined expression value");
+ return vals[0].val;
+syntax:
+ error(ERROR, "Syntax error in #if/#elsif");
+ return 0;
+}
+
+int
+evalop(struct pri pri)
+{
+ struct value v1, v2;
+ long rv1, rv2;
+ int rtype, oper;
+
+ rv2=0;
+ rtype=0;
+ while (pri.pri < priority[op[-1]].pri) {
+ oper = *--op;
+ if (priority[oper].arity==2) {
+ v2 = *--vp;
+ rv2 = v2.val;
+ }
+ v1 = *--vp;
+ rv1 = v1.val;
+/*lint -e574 -e644 */
+ switch (priority[oper].ctype) {
+ case 0:
+ default:
+ error(WARNING, "Syntax error in #if/#endif");
+ return 1;
+ case ARITH:
+ case RELAT:
+ if (v1.type==UNS || v2.type==UNS)
+ rtype = UNS;
+ else
+ rtype = SGN;
+ if (v1.type==UND || v2.type==UND)
+ rtype = UND;
+ if (priority[oper].ctype==RELAT && rtype==UNS) {
+ oper |= UNSMARK;
+ rtype = SGN;
+ }
+ break;
+ case SHIFT:
+ if (v1.type==UND || v2.type==UND)
+ rtype = UND;
+ else
+ rtype = v1.type;
+ if (rtype==UNS)
+ oper |= UNSMARK;
+ break;
+ case UNARY:
+ rtype = v1.type;
+ break;
+ case LOGIC:
+ case SPCL:
+ break;
+ }
+ switch (oper) {
+ case EQ: case EQ|UNSMARK:
+ rv1 = rv1==rv2; break;
+ case NEQ: case NEQ|UNSMARK:
+ rv1 = rv1!=rv2; break;
+ case LEQ:
+ rv1 = rv1<=rv2; break;
+ case GEQ:
+ rv1 = rv1>=rv2; break;
+ case LT:
+ rv1 = rv1<rv2; break;
+ case GT:
+ rv1 = rv1>rv2; break;
+ case LEQ|UNSMARK:
+ rv1 = (unsigned long)rv1<=rv2; break;
+ case GEQ|UNSMARK:
+ rv1 = (unsigned long)rv1>=rv2; break;
+ case LT|UNSMARK:
+ rv1 = (unsigned long)rv1<rv2; break;
+ case GT|UNSMARK:
+ rv1 = (unsigned long)rv1>rv2; break;
+ case LSH:
+ rv1 <<= rv2; break;
+ case LSH|UNSMARK:
+ rv1 = (unsigned long)rv1<<rv2; break;
+ case RSH:
+ rv1 >>= rv2; break;
+ case RSH|UNSMARK:
+ rv1 = (unsigned long)rv1>>rv2; break;
+ case LAND:
+ rtype = UND;
+ if (v1.type==UND)
+ break;
+ if (rv1!=0) {
+ if (v2.type==UND)
+ break;
+ rv1 = rv2!=0;
+ } else
+ rv1 = 0;
+ rtype = SGN;
+ break;
+ case LOR:
+ rtype = UND;
+ if (v1.type==UND)
+ break;
+ if (rv1==0) {
+ if (v2.type==UND)
+ break;
+ rv1 = rv2!=0;
+ } else
+ rv1 = 1;
+ rtype = SGN;
+ break;
+ case AND:
+ rv1 &= rv2; break;
+ case STAR:
+ rv1 *= rv2; break;
+ case PLUS:
+ rv1 += rv2; break;
+ case MINUS:
+ rv1 -= rv2; break;
+ case UMINUS:
+ if (v1.type==UND)
+ rtype = UND;
+ rv1 = -rv1; break;
+ case OR:
+ rv1 |= rv2; break;
+ case CIRC:
+ rv1 ^= rv2; break;
+ case TILDE:
+ rv1 = ~rv1; break;
+ case NOT:
+ rv1 = !rv1; if (rtype!=UND) rtype = SGN; break;
+ case SLASH:
+ if (rv2==0) {
+ rtype = UND;
+ break;
+ }
+ if (rtype==UNS)
+ rv1 /= (unsigned long)rv2;
+ else
+ rv1 /= rv2;
+ break;
+ case PCT:
+ if (rv2==0) {
+ rtype = UND;
+ break;
+ }
+ if (rtype==UNS)
+ rv1 %= (unsigned long)rv2;
+ else
+ rv1 %= rv2;
+ break;
+ case COLON:
+ if (op[-1] != QUEST)
+ error(ERROR, "Bad ?: in #if/endif");
+ else {
+ op--;
+ if ((--vp)->val==0)
+ v1 = v2;
+ rtype = v1.type;
+ rv1 = v1.val;
+ }
+ break;
+ case DEFINED:
+ break;
+ default:
+ error(ERROR, "Eval botch (unknown operator)");
+ return 1;
+ }
+/*lint +e574 +e644 */
+ v1.val = rv1;
+ v1.type = rtype;
+ *vp++ = v1;
+ }
+ return 0;
+}
+
+struct value
+tokval(Token *tp)
+{
+ struct value v;
+ Nlist *np;
+ int i, base, c;
+ unsigned long n;
+ uchar *p;
+
+ v.type = SGN;
+ v.val = 0;
+ switch (tp->type) {
+
+ case NAME:
+ v.val = 0;
+ break;
+
+ case NAME1:
+ if ((np = lookup(tp, 0)) != NULL && np->flag&(ISDEFINED|ISMAC))
+ v.val = 1;
+ break;
+
+ case NUMBER:
+ n = 0;
+ base = 10;
+ p = tp->t;
+ c = p[tp->len];
+ p[tp->len] = '\0';
+ if (*p=='0') {
+ base = 8;
+ if (p[1]=='x' || p[1]=='X') {
+ base = 16;
+ p++;
+ }
+ p++;
+ }
+ for (;; p++) {
+ if ((i = digit(*p)) < 0)
+ break;
+ if (i>=base)
+ error(WARNING,
+ "Bad digit in number %t", tp);
+ n *= base;
+ n += i;
+ }
+ if (n>=0x80000000 && base!=10)
+ v.type = UNS;
+ for (; *p; p++) {
+ if (*p=='u' || *p=='U')
+ v.type = UNS;
+ else if (*p=='l' || *p=='L')
+ ;
+ else {
+ error(ERROR,
+ "Bad number %t in #if/#elsif", tp);
+ break;
+ }
+ }
+ v.val = n;
+ tp->t[tp->len] = c;
+ break;
+
+ case CCON:
+ n = 0;
+ p = tp->t;
+ if (*p=='L') {
+ p += 1;
+ error(WARNING, "Wide char constant value undefined");
+ }
+ p += 1;
+ if (*p=='\\') {
+ p += 1;
+ if ((i = digit(*p))>=0 && i<=7) {
+ n = i;
+ p += 1;
+ if ((i = digit(*p))>=0 && i<=7) {
+ p += 1;
+ n <<= 3;
+ n += i;
+ if ((i = digit(*p))>=0 && i<=7) {
+ p += 1;
+ n <<= 3;
+ n += i;
+ }
+ }
+ } else if (*p=='x') {
+ p += 1;
+ while ((i = digit(*p))>=0 && i<=15) {
+ p += 1;
+ n <<= 4;
+ n += i;
+ }
+ } else {
+ static char cvcon[]
+ = "b\bf\fn\nr\rt\tv\v''\"\"??\\\\";
+ for (i=0; i<sizeof(cvcon); i+=2) {
+ if (*p == cvcon[i]) {
+ n = cvcon[i+1];
+ break;
+ }
+ }
+ p += 1;
+ if (i>=sizeof(cvcon))
+ error(WARNING,
+ "Undefined escape in character constant");
+ }
+ } else if (*p=='\'')
+ error(ERROR, "Empty character constant");
+ else
+ n = *p++;
+ if (*p!='\'')
+ error(WARNING, "Multibyte character constant undefined");
+ else if (n>127)
+ error(WARNING, "Character constant taken as not signed");
+ v.val = n;
+ break;
+
+ case STRING:
+ error(ERROR, "String in #if/#elsif");
+ break;
+ }
+ return v;
+}
+
+int
+digit(int i)
+{
+ if ('0'<=i && i<='9')
+ i -= '0';
+ else if ('a'<=i && i<='f')
+ i -= 'a'-10;
+ else if ('A'<=i && i<='F')
+ i -= 'A'-10;
+ else
+ i = -1;
+ return i;
+}
diff --git a/lcc/cpp/getopt.c b/lcc/cpp/getopt.c
new file mode 100755
index 0000000..69e9ab4
--- /dev/null
+++ b/lcc/cpp/getopt.c
@@ -0,0 +1,52 @@
+#include <stdio.h>
+#define EPR fprintf(stderr,
+#define ERR(str, chr) if(opterr){EPR "%s%c\n", str, chr);}
+int opterr = 1;
+int optind = 1;
+int optopt;
+char *optarg;
+char *strchr();
+
+int
+getopt (int argc, char *const argv[], const char *opts)
+{
+ static int sp = 1;
+ int c;
+ char *cp;
+
+ if (sp == 1)
+ if (optind >= argc ||
+ argv[optind][0] != '-' || argv[optind][1] == '\0')
+ return -1;
+ else if (strcmp(argv[optind], "--") == 0) {
+ optind++;
+ return -1;
+ }
+ optopt = c = argv[optind][sp];
+ if (c == ':' || (cp=strchr(opts, c)) == 0) {
+ ERR (": illegal option -- ", c);
+ if (argv[optind][++sp] == '\0') {
+ optind++;
+ sp = 1;
+ }
+ return '?';
+ }
+ if (*++cp == ':') {
+ if (argv[optind][sp+1] != '\0')
+ optarg = &argv[optind++][sp+1];
+ else if (++optind >= argc) {
+ ERR (": option requires an argument -- ", c);
+ sp = 1;
+ return '?';
+ } else
+ optarg = argv[optind++];
+ sp = 1;
+ } else {
+ if (argv[optind][++sp] == '\0') {
+ sp = 1;
+ optind++;
+ }
+ optarg = 0;
+ }
+ return c;
+}
diff --git a/lcc/cpp/hideset.c b/lcc/cpp/hideset.c
new file mode 100755
index 0000000..637a441
--- /dev/null
+++ b/lcc/cpp/hideset.c
@@ -0,0 +1,112 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "cpp.h"
+
+/*
+ * A hideset is a null-terminated array of Nlist pointers.
+ * They are referred to by indices in the hidesets array.
+ * Hideset 0 is empty.
+ */
+
+#define HSSIZ 32
+typedef Nlist **Hideset;
+Hideset *hidesets;
+int nhidesets = 0;
+int maxhidesets = 3;
+int inserths(Hideset, Hideset, Nlist *);
+
+/*
+ * Test for membership in a hideset
+ */
+int
+checkhideset(int hs, Nlist *np)
+{
+ Hideset hsp;
+
+ if (hs>=nhidesets)
+ abort();
+ for (hsp = hidesets[hs]; *hsp; hsp++) {
+ if (*hsp == np)
+ return 1;
+ }
+ return 0;
+}
+
+/*
+ * Return the (possibly new) hideset obtained by adding np to hs.
+ */
+int
+newhideset(int hs, Nlist *np)
+{
+ int i, len;
+ Nlist *nhs[HSSIZ+3];
+ Hideset hs1, hs2;
+
+ len = inserths(nhs, hidesets[hs], np);
+ for (i=0; i<nhidesets; i++) {
+ for (hs1=nhs, hs2=hidesets[i]; *hs1==*hs2; hs1++, hs2++)
+ if (*hs1 == NULL)
+ return i;
+ }
+ if (len>=HSSIZ)
+ return hs;
+ if (nhidesets >= maxhidesets) {
+ maxhidesets = 3*maxhidesets/2+1;
+ hidesets = (Hideset *)realloc(hidesets, (sizeof (Hideset *))*maxhidesets);
+ if (hidesets == NULL)
+ error(FATAL, "Out of memory from realloc");
+ }
+ hs1 = (Hideset)domalloc(len*sizeof(Hideset));
+ memmove(hs1, nhs, len*sizeof(Hideset));
+ hidesets[nhidesets] = hs1;
+ return nhidesets++;
+}
+
+int
+inserths(Hideset dhs, Hideset shs, Nlist *np)
+{
+ Hideset odhs = dhs;
+
+ while (*shs && *shs < np)
+ *dhs++ = *shs++;
+ if (*shs != np)
+ *dhs++ = np;
+ do {
+ *dhs++ = *shs;
+ } while (*shs++);
+ return dhs - odhs;
+}
+
+/*
+ * Hideset union
+ */
+int
+unionhideset(int hs1, int hs2)
+{
+ Hideset hp;
+
+ for (hp = hidesets[hs2]; *hp; hp++)
+ hs1 = newhideset(hs1, *hp);
+ return hs1;
+}
+
+void
+iniths(void)
+{
+ hidesets = (Hideset *)domalloc(maxhidesets*sizeof(Hideset *));
+ hidesets[0] = (Hideset)domalloc(sizeof(Hideset));
+ *hidesets[0] = NULL;
+ nhidesets++;
+}
+
+void
+prhideset(int hs)
+{
+ Hideset np;
+
+ for (np = hidesets[hs]; *np; np++) {
+ fprintf(stderr, (char*)(*np)->name, (*np)->len);
+ fprintf(stderr, " ");
+ }
+}
diff --git a/lcc/cpp/include.c b/lcc/cpp/include.c
new file mode 100755
index 0000000..66f1fc3
--- /dev/null
+++ b/lcc/cpp/include.c
@@ -0,0 +1,122 @@
+#include <stdlib.h>
+#include <string.h>
+#include "cpp.h"
+
+Includelist includelist[NINCLUDE];
+
+extern char *objname;
+
+void
+doinclude(Tokenrow *trp)
+{
+ char fname[256], iname[256];
+ Includelist *ip;
+ int angled, len, fd, i;
+
+ trp->tp += 1;
+ if (trp->tp>=trp->lp)
+ goto syntax;
+ if (trp->tp->type!=STRING && trp->tp->type!=LT) {
+ len = trp->tp - trp->bp;
+ expandrow(trp, "<include>");
+ trp->tp = trp->bp+len;
+ }
+ if (trp->tp->type==STRING) {
+ len = trp->tp->len-2;
+ if (len > sizeof(fname) - 1)
+ len = sizeof(fname) - 1;
+ strncpy(fname, (char*)trp->tp->t+1, len);
+ angled = 0;
+ } else if (trp->tp->type==LT) {
+ len = 0;
+ trp->tp++;
+ while (trp->tp->type!=GT) {
+ if (trp->tp>trp->lp || len+trp->tp->len+2 >= sizeof(fname))
+ goto syntax;
+ strncpy(fname+len, (char*)trp->tp->t, trp->tp->len);
+ len += trp->tp->len;
+ trp->tp++;
+ }
+ angled = 1;
+ } else
+ goto syntax;
+ trp->tp += 2;
+ if (trp->tp < trp->lp || len==0)
+ goto syntax;
+ fname[len] = '\0';
+ if (fname[0]=='/') {
+ fd = open(fname, 0);
+ strcpy(iname, fname);
+ } else for (fd = -1,i=NINCLUDE-1; i>=0; i--) {
+ ip = &includelist[i];
+ if (ip->file==NULL || ip->deleted || (angled && ip->always==0))
+ continue;
+ if (strlen(fname)+strlen(ip->file)+2 > sizeof(iname))
+ continue;
+ strcpy(iname, ip->file);
+ strcat(iname, "/");
+ strcat(iname, fname);
+ if ((fd = open(iname, 0)) >= 0)
+ break;
+ }
+ if ( Mflag>1 || !angled&&Mflag==1 ) {
+ write(1,objname,strlen(objname));
+ write(1,iname,strlen(iname));
+ write(1,"\n",1);
+ }
+ if (fd >= 0) {
+ if (++incdepth > 10)
+ error(FATAL, "#include too deeply nested");
+ setsource((char*)newstring((uchar*)iname, strlen(iname), 0), fd, NULL);
+ genline();
+ } else {
+ trp->tp = trp->bp+2;
+ error(ERROR, "Could not find include file %r", trp);
+ }
+ return;
+syntax:
+ error(ERROR, "Syntax error in #include");
+ return;
+}
+
+/*
+ * Generate a line directive for cursource
+ */
+void
+genline(void)
+{
+ static Token ta = { UNCLASS };
+ static Tokenrow tr = { &ta, &ta, &ta+1, 1 };
+ uchar *p;
+
+ ta.t = p = (uchar*)outp;
+ strcpy((char*)p, "#line ");
+ p += sizeof("#line ")-1;
+ p = (uchar*)outnum((char*)p, cursource->line);
+ *p++ = ' '; *p++ = '"';
+ if (cursource->filename[0]!='/' && wd[0]) {
+ strcpy((char*)p, wd);
+ p += strlen(wd);
+ *p++ = '/';
+ }
+ strcpy((char*)p, cursource->filename);
+ p += strlen((char*)p);
+ *p++ = '"'; *p++ = '\n';
+ ta.len = (char*)p-outp;
+ outp = (char*)p;
+ tr.tp = tr.bp;
+ puttokens(&tr);
+}
+
+void
+setobjname(char *f)
+{
+ int n = strlen(f);
+ objname = (char*)domalloc(n+5);
+ strcpy(objname,f);
+ if(objname[n-2]=='.'){
+ strcpy(objname+n-1,"$O: ");
+ }else{
+ strcpy(objname+n,"$O: ");
+ }
+}
diff --git a/lcc/cpp/lex.c b/lcc/cpp/lex.c
new file mode 100755
index 0000000..8513a17
--- /dev/null
+++ b/lcc/cpp/lex.c
@@ -0,0 +1,581 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "cpp.h"
+
+/*
+ * lexical FSM encoding
+ * when in state state, and one of the characters
+ * in ch arrives, enter nextstate.
+ * States >= S_SELF are either final, or at least require special action.
+ * In 'fsm' there is a line for each state X charset X nextstate.
+ * List chars that overwrite previous entries later (e.g. C_ALPH
+ * can be overridden by '_' by a later entry; and C_XX is the
+ * the universal set, and should always be first.
+ * States above S_SELF are represented in the big table as negative values.
+ * S_SELF and S_SELFB encode the resulting token type in the upper bits.
+ * These actions differ in that S_SELF doesn't have a lookahead char,
+ * S_SELFB does.
+ *
+ * The encoding is blown out into a big table for time-efficiency.
+ * Entries have
+ * nextstate: 6 bits; ?\ marker: 1 bit; tokentype: 9 bits.
+ */
+
+#define MAXSTATE 32
+#define ACT(tok,act) ((tok<<7)+act)
+#define QBSBIT 0100
+#define GETACT(st) (st>>7)&0x1ff
+
+/* character classes */
+#define C_WS 1
+#define C_ALPH 2
+#define C_NUM 3
+#define C_EOF 4
+#define C_XX 5
+
+enum state {
+ START=0, NUM1, NUM2, NUM3, ID1, ST1, ST2, ST3, COM1, COM2, COM3, COM4,
+ CC1, CC2, WS1, PLUS1, MINUS1, STAR1, SLASH1, PCT1, SHARP1,
+ CIRC1, GT1, GT2, LT1, LT2, OR1, AND1, ASG1, NOT1, DOTS1,
+ S_SELF=MAXSTATE, S_SELFB, S_EOF, S_NL, S_EOFSTR,
+ S_STNL, S_COMNL, S_EOFCOM, S_COMMENT, S_EOB, S_WS, S_NAME
+};
+
+int tottok;
+int tokkind[256];
+struct fsm {
+ int state; /* if in this state */
+ uchar ch[4]; /* and see one of these characters */
+ int nextstate; /* enter this state if +ve */
+};
+
+/*const*/ struct fsm fsm[] = {
+ /* start state */
+ START, { C_XX }, ACT(UNCLASS,S_SELF),
+ START, { ' ', '\t', '\v' }, WS1,
+ START, { C_NUM }, NUM1,
+ START, { '.' }, NUM3,
+ START, { C_ALPH }, ID1,
+ START, { 'L' }, ST1,
+ START, { '"' }, ST2,
+ START, { '\'' }, CC1,
+ START, { '/' }, COM1,
+ START, { EOFC }, S_EOF,
+ START, { '\n' }, S_NL,
+ START, { '-' }, MINUS1,
+ START, { '+' }, PLUS1,
+ START, { '<' }, LT1,
+ START, { '>' }, GT1,
+ START, { '=' }, ASG1,
+ START, { '!' }, NOT1,
+ START, { '&' }, AND1,
+ START, { '|' }, OR1,
+ START, { '#' }, SHARP1,
+ START, { '%' }, PCT1,
+ START, { '[' }, ACT(SBRA,S_SELF),
+ START, { ']' }, ACT(SKET,S_SELF),
+ START, { '(' }, ACT(LP,S_SELF),
+ START, { ')' }, ACT(RP,S_SELF),
+ START, { '*' }, STAR1,
+ START, { ',' }, ACT(COMMA,S_SELF),
+ START, { '?' }, ACT(QUEST,S_SELF),
+ START, { ':' }, ACT(COLON,S_SELF),
+ START, { ';' }, ACT(SEMIC,S_SELF),
+ START, { '{' }, ACT(CBRA,S_SELF),
+ START, { '}' }, ACT(CKET,S_SELF),
+ START, { '~' }, ACT(TILDE,S_SELF),
+ START, { '^' }, CIRC1,
+
+ /* saw a digit */
+ NUM1, { C_XX }, ACT(NUMBER,S_SELFB),
+ NUM1, { C_NUM, C_ALPH, '.' }, NUM1,
+ NUM1, { 'E', 'e' }, NUM2,
+ NUM1, { '_' }, ACT(NUMBER,S_SELFB),
+
+ /* saw possible start of exponent, digits-e */
+ NUM2, { C_XX }, ACT(NUMBER,S_SELFB),
+ NUM2, { '+', '-' }, NUM1,
+ NUM2, { C_NUM, C_ALPH }, NUM1,
+ NUM2, { '_' }, ACT(NUMBER,S_SELFB),
+
+ /* saw a '.', which could be a number or an operator */
+ NUM3, { C_XX }, ACT(DOT,S_SELFB),
+ NUM3, { '.' }, DOTS1,
+ NUM3, { C_NUM }, NUM1,
+
+ DOTS1, { C_XX }, ACT(UNCLASS, S_SELFB),
+ DOTS1, { C_NUM }, NUM1,
+ DOTS1, { '.' }, ACT(ELLIPS, S_SELF),
+
+ /* saw a letter or _ */
+ ID1, { C_XX }, ACT(NAME,S_NAME),
+ ID1, { C_ALPH, C_NUM }, ID1,
+
+ /* saw L (start of wide string?) */
+ ST1, { C_XX }, ACT(NAME,S_NAME),
+ ST1, { C_ALPH, C_NUM }, ID1,
+ ST1, { '"' }, ST2,
+ ST1, { '\'' }, CC1,
+
+ /* saw " beginning string */
+ ST2, { C_XX }, ST2,
+ ST2, { '"' }, ACT(STRING, S_SELF),
+ ST2, { '\\' }, ST3,
+ ST2, { '\n' }, S_STNL,
+ ST2, { EOFC }, S_EOFSTR,
+
+ /* saw \ in string */
+ ST3, { C_XX }, ST2,
+ ST3, { '\n' }, S_STNL,
+ ST3, { EOFC }, S_EOFSTR,
+
+ /* saw ' beginning character const */
+ CC1, { C_XX }, CC1,
+ CC1, { '\'' }, ACT(CCON, S_SELF),
+ CC1, { '\\' }, CC2,
+ CC1, { '\n' }, S_STNL,
+ CC1, { EOFC }, S_EOFSTR,
+
+ /* saw \ in ccon */
+ CC2, { C_XX }, CC1,
+ CC2, { '\n' }, S_STNL,
+ CC2, { EOFC }, S_EOFSTR,
+
+ /* saw /, perhaps start of comment */
+ COM1, { C_XX }, ACT(SLASH, S_SELFB),
+ COM1, { '=' }, ACT(ASSLASH, S_SELF),
+ COM1, { '*' }, COM2,
+ COM1, { '/' }, COM4,
+
+ /* saw / then *, start of comment */
+ COM2, { C_XX }, COM2,
+ COM2, { '\n' }, S_COMNL,
+ COM2, { '*' }, COM3,
+ COM2, { EOFC }, S_EOFCOM,
+
+ /* saw the * possibly ending a comment */
+ COM3, { C_XX }, COM2,
+ COM3, { '\n' }, S_COMNL,
+ COM3, { '*' }, COM3,
+ COM3, { '/' }, S_COMMENT,
+
+ /* // comment */
+ COM4, { C_XX }, COM4,
+ COM4, { '\n' }, S_NL,
+ COM4, { EOFC }, S_EOFCOM,
+
+ /* saw white space, eat it up */
+ WS1, { C_XX }, S_WS,
+ WS1, { ' ', '\t', '\v' }, WS1,
+
+ /* saw -, check --, -=, -> */
+ MINUS1, { C_XX }, ACT(MINUS, S_SELFB),
+ MINUS1, { '-' }, ACT(MMINUS, S_SELF),
+ MINUS1, { '=' }, ACT(ASMINUS,S_SELF),
+ MINUS1, { '>' }, ACT(ARROW,S_SELF),
+
+ /* saw +, check ++, += */
+ PLUS1, { C_XX }, ACT(PLUS, S_SELFB),
+ PLUS1, { '+' }, ACT(PPLUS, S_SELF),
+ PLUS1, { '=' }, ACT(ASPLUS, S_SELF),
+
+ /* saw <, check <<, <<=, <= */
+ LT1, { C_XX }, ACT(LT, S_SELFB),
+ LT1, { '<' }, LT2,
+ LT1, { '=' }, ACT(LEQ, S_SELF),
+ LT2, { C_XX }, ACT(LSH, S_SELFB),
+ LT2, { '=' }, ACT(ASLSH, S_SELF),
+
+ /* saw >, check >>, >>=, >= */
+ GT1, { C_XX }, ACT(GT, S_SELFB),
+ GT1, { '>' }, GT2,
+ GT1, { '=' }, ACT(GEQ, S_SELF),
+ GT2, { C_XX }, ACT(RSH, S_SELFB),
+ GT2, { '=' }, ACT(ASRSH, S_SELF),
+
+ /* = */
+ ASG1, { C_XX }, ACT(ASGN, S_SELFB),
+ ASG1, { '=' }, ACT(EQ, S_SELF),
+
+ /* ! */
+ NOT1, { C_XX }, ACT(NOT, S_SELFB),
+ NOT1, { '=' }, ACT(NEQ, S_SELF),
+
+ /* & */
+ AND1, { C_XX }, ACT(AND, S_SELFB),
+ AND1, { '&' }, ACT(LAND, S_SELF),
+ AND1, { '=' }, ACT(ASAND, S_SELF),
+
+ /* | */
+ OR1, { C_XX }, ACT(OR, S_SELFB),
+ OR1, { '|' }, ACT(LOR, S_SELF),
+ OR1, { '=' }, ACT(ASOR, S_SELF),
+
+ /* # */
+ SHARP1, { C_XX }, ACT(SHARP, S_SELFB),
+ SHARP1, { '#' }, ACT(DSHARP, S_SELF),
+
+ /* % */
+ PCT1, { C_XX }, ACT(PCT, S_SELFB),
+ PCT1, { '=' }, ACT(ASPCT, S_SELF),
+
+ /* * */
+ STAR1, { C_XX }, ACT(STAR, S_SELFB),
+ STAR1, { '=' }, ACT(ASSTAR, S_SELF),
+
+ /* ^ */
+ CIRC1, { C_XX }, ACT(CIRC, S_SELFB),
+ CIRC1, { '=' }, ACT(ASCIRC, S_SELF),
+
+ -1
+};
+
+/* first index is char, second is state */
+/* increase #states to power of 2 to encourage use of shift */
+short bigfsm[256][MAXSTATE];
+
+void
+expandlex(void)
+{
+ /*const*/ struct fsm *fp;
+ int i, j, nstate;
+
+ for (fp = fsm; fp->state>=0; fp++) {
+ for (i=0; fp->ch[i]; i++) {
+ nstate = fp->nextstate;
+ if (nstate >= S_SELF)
+ nstate = ~nstate;
+ switch (fp->ch[i]) {
+
+ case C_XX: /* random characters */
+ for (j=0; j<256; j++)
+ bigfsm[j][fp->state] = nstate;
+ continue;
+ case C_ALPH:
+ for (j=0; j<=256; j++)
+ if ('a'<=j&&j<='z' || 'A'<=j&&j<='Z'
+ || j=='_')
+ bigfsm[j][fp->state] = nstate;
+ continue;
+ case C_NUM:
+ for (j='0'; j<='9'; j++)
+ bigfsm[j][fp->state] = nstate;
+ continue;
+ default:
+ bigfsm[fp->ch[i]][fp->state] = nstate;
+ }
+ }
+ }
+ /* install special cases for ? (trigraphs), \ (splicing), runes, and EOB */
+ for (i=0; i<MAXSTATE; i++) {
+ for (j=0; j<0xFF; j++)
+ if (j=='?' || j=='\\') {
+ if (bigfsm[j][i]>0)
+ bigfsm[j][i] = ~bigfsm[j][i];
+ bigfsm[j][i] &= ~QBSBIT;
+ }
+ bigfsm[EOB][i] = ~S_EOB;
+ if (bigfsm[EOFC][i]>=0)
+ bigfsm[EOFC][i] = ~S_EOF;
+ }
+}
+
+void
+fixlex(void)
+{
+ /* do C++ comments? */
+ if (Cplusplus==0)
+ bigfsm['/'][COM1] = bigfsm['x'][COM1];
+}
+
+/*
+ * fill in a row of tokens from input, terminated by NL or END
+ * First token is put at trp->lp.
+ * Reset is non-zero when the input buffer can be "rewound."
+ * The value is a flag indicating that possible macros have
+ * been seen in the row.
+ */
+int
+gettokens(Tokenrow *trp, int reset)
+{
+ register int c, state, oldstate;
+ register uchar *ip;
+ register Token *tp, *maxp;
+ int runelen;
+ Source *s = cursource;
+ int nmac = 0;
+ extern char outbuf[];
+
+ tp = trp->lp;
+ ip = s->inp;
+ if (reset) {
+ s->lineinc = 0;
+ if (ip>=s->inl) { /* nothing in buffer */
+ s->inl = s->inb;
+ fillbuf(s);
+ ip = s->inp = s->inb;
+ } else if (ip >= s->inb+(3*INS/4)) {
+ memmove(s->inb, ip, 4+s->inl-ip);
+ s->inl = s->inb+(s->inl-ip);
+ ip = s->inp = s->inb;
+ }
+ }
+ maxp = &trp->bp[trp->max];
+ runelen = 1;
+ for (;;) {
+ continue2:
+ if (tp>=maxp) {
+ trp->lp = tp;
+ tp = growtokenrow(trp);
+ maxp = &trp->bp[trp->max];
+ }
+ tp->type = UNCLASS;
+ tp->hideset = 0;
+ tp->t = ip;
+ tp->wslen = 0;
+ tp->flag = 0;
+ state = START;
+ for (;;) {
+ oldstate = state;
+ c = *ip;
+ if ((state = bigfsm[c][state]) >= 0) {
+ ip += runelen;
+ runelen = 1;
+ continue;
+ }
+ state = ~state;
+ reswitch:
+ switch (state&0177) {
+ case S_SELF:
+ ip += runelen;
+ runelen = 1;
+ case S_SELFB:
+ tp->type = GETACT(state);
+ tp->len = ip - tp->t;
+ tp++;
+ goto continue2;
+
+ case S_NAME: /* like S_SELFB but with nmac check */
+ tp->type = NAME;
+ tp->len = ip - tp->t;
+ nmac |= quicklook(tp->t[0], tp->len>1?tp->t[1]:0);
+ tp++;
+ goto continue2;
+
+ case S_WS:
+ tp->wslen = ip - tp->t;
+ tp->t = ip;
+ state = START;
+ continue;
+
+ default:
+ if ((state&QBSBIT)==0) {
+ ip += runelen;
+ runelen = 1;
+ continue;
+ }
+ state &= ~QBSBIT;
+ s->inp = ip;
+ if (c=='?') { /* check trigraph */
+ if (trigraph(s)) {
+ state = oldstate;
+ continue;
+ }
+ goto reswitch;
+ }
+ if (c=='\\') { /* line-folding */
+ if (foldline(s)) {
+ s->lineinc++;
+ state = oldstate;
+ continue;
+ }
+ goto reswitch;
+ }
+ error(WARNING, "Lexical botch in cpp");
+ ip += runelen;
+ runelen = 1;
+ continue;
+
+ case S_EOB:
+ s->inp = ip;
+ fillbuf(cursource);
+ state = oldstate;
+ continue;
+
+ case S_EOF:
+ tp->type = END;
+ tp->len = 0;
+ s->inp = ip;
+ if (tp!=trp->bp && (tp-1)->type!=NL && cursource->fd!=-1)
+ error(WARNING,"No newline at end of file");
+ trp->lp = tp+1;
+ return nmac;
+
+ case S_STNL:
+ error(ERROR, "Unterminated string or char const");
+ case S_NL:
+ tp->t = ip;
+ tp->type = NL;
+ tp->len = 1;
+ tp->wslen = 0;
+ s->lineinc++;
+ s->inp = ip+1;
+ trp->lp = tp+1;
+ return nmac;
+
+ case S_EOFSTR:
+ error(FATAL, "EOF in string or char constant");
+ break;
+
+ case S_COMNL:
+ s->lineinc++;
+ state = COM2;
+ ip += runelen;
+ runelen = 1;
+ if (ip >= s->inb+(7*INS/8)) { /* very long comment */
+ memmove(tp->t, ip, 4+s->inl-ip);
+ s->inl -= ip-tp->t;
+ ip = tp->t+1;
+ }
+ continue;
+
+ case S_EOFCOM:
+ error(WARNING, "EOF inside comment");
+ --ip;
+ case S_COMMENT:
+ ++ip;
+ tp->t = ip;
+ tp->t[-1] = ' ';
+ tp->wslen = 1;
+ state = START;
+ continue;
+ }
+ break;
+ }
+ ip += runelen;
+ runelen = 1;
+ tp->len = ip - tp->t;
+ tp++;
+ }
+}
+
+/* have seen ?; handle the trigraph it starts (if any) else 0 */
+int
+trigraph(Source *s)
+{
+ int c;
+
+ while (s->inp+2 >= s->inl && fillbuf(s)!=EOF)
+ ;
+ if (s->inp[1]!='?')
+ return 0;
+ c = 0;
+ switch(s->inp[2]) {
+ case '=':
+ c = '#'; break;
+ case '(':
+ c = '['; break;
+ case '/':
+ c = '\\'; break;
+ case ')':
+ c = ']'; break;
+ case '\'':
+ c = '^'; break;
+ case '<':
+ c = '{'; break;
+ case '!':
+ c = '|'; break;
+ case '>':
+ c = '}'; break;
+ case '-':
+ c = '~'; break;
+ }
+ if (c) {
+ *s->inp = c;
+ memmove(s->inp+1, s->inp+3, s->inl-s->inp+2);
+ s->inl -= 2;
+ }
+ return c;
+}
+
+int
+foldline(Source *s)
+{
+ while (s->inp+1 >= s->inl && fillbuf(s)!=EOF)
+ ;
+ if (s->inp[1] == '\n') {
+ memmove(s->inp, s->inp+2, s->inl-s->inp+3);
+ s->inl -= 2;
+ return 1;
+ }
+ return 0;
+}
+
+int
+fillbuf(Source *s)
+{
+ int n, nr;
+
+ nr = INS/8;
+ if ((char *)s->inl+nr > (char *)s->inb+INS)
+ error(FATAL, "Input buffer overflow");
+ if (s->fd<0 || (n=read(s->fd, (char *)s->inl, INS/8)) <= 0)
+ n = 0;
+ if ((*s->inp&0xff) == EOB) /* sentinel character appears in input */
+ *s->inp = EOFC;
+ s->inl += n;
+ s->inl[0] = s->inl[1]= s->inl[2]= s->inl[3] = EOB;
+ if (n==0) {
+ s->inl[0] = s->inl[1]= s->inl[2]= s->inl[3] = EOFC;
+ return EOF;
+ }
+ return 0;
+}
+
+/*
+ * Push down to new source of characters.
+ * If fd>0 and str==NULL, then from a file `name';
+ * if fd==-1 and str, then from the string.
+ */
+Source *
+setsource(char *name, int fd, char *str)
+{
+ Source *s = new(Source);
+ int len;
+
+ s->line = 1;
+ s->lineinc = 0;
+ s->fd = fd;
+ s->filename = name;
+ s->next = cursource;
+ s->ifdepth = 0;
+ cursource = s;
+ /* slop at right for EOB */
+ if (str) {
+ len = strlen(str);
+ s->inb = domalloc(len+4);
+ s->inp = s->inb;
+ strncpy((char *)s->inp, str, len);
+ } else {
+ s->inb = domalloc(INS+4);
+ s->inp = s->inb;
+ len = 0;
+ }
+ s->inl = s->inp+len;
+ s->inl[0] = s->inl[1] = EOB;
+ return s;
+}
+
+void
+unsetsource(void)
+{
+ Source *s = cursource;
+
+ if (s->fd>=0) {
+ close(s->fd);
+ dofree(s->inb);
+ }
+ cursource = s->next;
+ dofree(s);
+}
diff --git a/lcc/cpp/macro.c b/lcc/cpp/macro.c
new file mode 100755
index 0000000..2268c4b
--- /dev/null
+++ b/lcc/cpp/macro.c
@@ -0,0 +1,515 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "cpp.h"
+
+/*
+ * do a macro definition. tp points to the name being defined in the line
+ */
+void
+dodefine(Tokenrow *trp)
+{
+ Token *tp;
+ Nlist *np;
+ Tokenrow *def, *args;
+
+ tp = trp->tp+1;
+ if (tp>=trp->lp || tp->type!=NAME) {
+ error(ERROR, "#defined token is not a name");
+ return;
+ }
+ np = lookup(tp, 1);
+ if (np->flag&ISUNCHANGE) {
+ error(ERROR, "#defined token %t can't be redefined", tp);
+ return;
+ }
+ /* collect arguments */
+ tp += 1;
+ args = NULL;
+ if (tp<trp->lp && tp->type==LP && tp->wslen==0) {
+ /* macro with args */
+ int narg = 0;
+ tp += 1;
+ args = new(Tokenrow);
+ maketokenrow(2, args);
+ if (tp->type!=RP) {
+ int err = 0;
+ for (;;) {
+ Token *atp;
+ if (tp->type!=NAME) {
+ err++;
+ break;
+ }
+ if (narg>=args->max)
+ growtokenrow(args);
+ for (atp=args->bp; atp<args->lp; atp++)
+ if (atp->len==tp->len
+ && strncmp((char*)atp->t, (char*)tp->t, tp->len)==0)
+ error(ERROR, "Duplicate macro argument");
+ *args->lp++ = *tp;
+ narg++;
+ tp += 1;
+ if (tp->type==RP)
+ break;
+ if (tp->type!=COMMA) {
+ err++;
+ break;
+ }
+ tp += 1;
+ }
+ if (err) {
+ error(ERROR, "Syntax error in macro parameters");
+ return;
+ }
+ }
+ tp += 1;
+ }
+ trp->tp = tp;
+ if (((trp->lp)-1)->type==NL)
+ trp->lp -= 1;
+ def = normtokenrow(trp);
+ if (np->flag&ISDEFINED) {
+ if (comparetokens(def, np->vp)
+ || (np->ap==NULL) != (args==NULL)
+ || np->ap && comparetokens(args, np->ap))
+ error(ERROR, "Macro redefinition of %t", trp->bp+2);
+ }
+ if (args) {
+ Tokenrow *tap;
+ tap = normtokenrow(args);
+ dofree(args->bp);
+ args = tap;
+ }
+ np->ap = args;
+ np->vp = def;
+ np->flag |= ISDEFINED;
+}
+
+/*
+ * Definition received via -D or -U
+ */
+void
+doadefine(Tokenrow *trp, int type)
+{
+ Nlist *np;
+ static Token onetoken[1] = {{ NUMBER, 0, 0, 0, 1, (uchar*)"1" }};
+ static Tokenrow onetr = { onetoken, onetoken, onetoken+1, 1 };
+
+ trp->tp = trp->bp;
+ if (type=='U') {
+ if (trp->lp-trp->tp != 2 || trp->tp->type!=NAME)
+ goto syntax;
+ if ((np = lookup(trp->tp, 0)) == NULL)
+ return;
+ np->flag &= ~ISDEFINED;
+ return;
+ }
+ if (trp->tp >= trp->lp || trp->tp->type!=NAME)
+ goto syntax;
+ np = lookup(trp->tp, 1);
+ np->flag |= ISDEFINED;
+ trp->tp += 1;
+ if (trp->tp >= trp->lp || trp->tp->type==END) {
+ np->vp = &onetr;
+ return;
+ }
+ if (trp->tp->type!=ASGN)
+ goto syntax;
+ trp->tp += 1;
+ if ((trp->lp-1)->type == END)
+ trp->lp -= 1;
+ np->vp = normtokenrow(trp);
+ return;
+syntax:
+ error(FATAL, "Illegal -D or -U argument %r", trp);
+}
+
+/*
+ * Do macro expansion in a row of tokens.
+ * Flag is NULL if more input can be gathered.
+ */
+void
+expandrow(Tokenrow *trp, char *flag)
+{
+ Token *tp;
+ Nlist *np;
+
+ if (flag)
+ setsource(flag, -1, "");
+ for (tp = trp->tp; tp<trp->lp; ) {
+ if (tp->type!=NAME
+ || quicklook(tp->t[0], tp->len>1?tp->t[1]:0)==0
+ || (np = lookup(tp, 0))==NULL
+ || (np->flag&(ISDEFINED|ISMAC))==0
+ || tp->hideset && checkhideset(tp->hideset, np)) {
+ tp++;
+ continue;
+ }
+ trp->tp = tp;
+ if (np->val==KDEFINED) {
+ tp->type = DEFINED;
+ if ((tp+1)<trp->lp && (tp+1)->type==NAME)
+ (tp+1)->type = NAME1;
+ else if ((tp+3)<trp->lp && (tp+1)->type==LP
+ && (tp+2)->type==NAME && (tp+3)->type==RP)
+ (tp+2)->type = NAME1;
+ else
+ error(ERROR, "Incorrect syntax for `defined'");
+ tp++;
+ continue;
+ }
+ if (np->flag&ISMAC)
+ builtin(trp, np->val);
+ else {
+ expand(trp, np);
+ }
+ tp = trp->tp;
+ }
+ if (flag)
+ unsetsource();
+}
+
+/*
+ * Expand the macro whose name is np, at token trp->tp, in the tokenrow.
+ * Return trp->tp at the first token next to be expanded
+ * (ordinarily the beginning of the expansion)
+ */
+void
+expand(Tokenrow *trp, Nlist *np)
+{
+ Tokenrow ntr;
+ int ntokc, narg, i;
+ Token *tp;
+ Tokenrow *atr[NARG+1];
+ int hs;
+
+ copytokenrow(&ntr, np->vp); /* copy macro value */
+ if (np->ap==NULL) /* parameterless */
+ ntokc = 1;
+ else {
+ ntokc = gatherargs(trp, atr, &narg);
+ if (narg<0) { /* not actually a call (no '(') */
+ trp->tp++;
+ return;
+ }
+ if (narg != rowlen(np->ap)) {
+ error(ERROR, "Disagreement in number of macro arguments");
+ trp->tp->hideset = newhideset(trp->tp->hideset, np);
+ trp->tp += ntokc;
+ return;
+ }
+ substargs(np, &ntr, atr); /* put args into replacement */
+ for (i=0; i<narg; i++) {
+ dofree(atr[i]->bp);
+ dofree(atr[i]);
+ }
+ }
+ doconcat(&ntr); /* execute ## operators */
+ hs = newhideset(trp->tp->hideset, np);
+ for (tp=ntr.bp; tp<ntr.lp; tp++) { /* distribute hidesets */
+ if (tp->type==NAME) {
+ if (tp->hideset==0)
+ tp->hideset = hs;
+ else
+ tp->hideset = unionhideset(tp->hideset, hs);
+ }
+ }
+ ntr.tp = ntr.bp;
+ insertrow(trp, ntokc, &ntr);
+ trp->tp -= rowlen(&ntr);
+ dofree(ntr.bp);
+ return;
+}
+
+/*
+ * Gather an arglist, starting in trp with tp pointing at the macro name.
+ * Return total number of tokens passed, stash number of args found.
+ * trp->tp is not changed relative to the tokenrow.
+ */
+int
+gatherargs(Tokenrow *trp, Tokenrow **atr, int *narg)
+{
+ int parens = 1;
+ int ntok = 0;
+ Token *bp, *lp;
+ Tokenrow ttr;
+ int ntokp;
+ int needspace;
+
+ *narg = -1; /* means that there is no macro call */
+ /* look for the ( */
+ for (;;) {
+ trp->tp++;
+ ntok++;
+ if (trp->tp >= trp->lp) {
+ gettokens(trp, 0);
+ if ((trp->lp-1)->type==END) {
+ trp->lp -= 1;
+ trp->tp -= ntok;
+ return ntok;
+ }
+ }
+ if (trp->tp->type==LP)
+ break;
+ if (trp->tp->type!=NL)
+ return ntok;
+ }
+ *narg = 0;
+ ntok++;
+ ntokp = ntok;
+ trp->tp++;
+ /* search for the terminating ), possibly extending the row */
+ needspace = 0;
+ while (parens>0) {
+ if (trp->tp >= trp->lp)
+ gettokens(trp, 0);
+ if (needspace) {
+ needspace = 0;
+ makespace(trp);
+ }
+ if (trp->tp->type==END) {
+ trp->lp -= 1;
+ trp->tp -= ntok;
+ error(ERROR, "EOF in macro arglist");
+ return ntok;
+ }
+ if (trp->tp->type==NL) {
+ trp->tp += 1;
+ adjustrow(trp, -1);
+ trp->tp -= 1;
+ makespace(trp);
+ needspace = 1;
+ continue;
+ }
+ if (trp->tp->type==LP)
+ parens++;
+ else if (trp->tp->type==RP)
+ parens--;
+ trp->tp++;
+ ntok++;
+ }
+ trp->tp -= ntok;
+ /* Now trp->tp won't move underneath us */
+ lp = bp = trp->tp+ntokp;
+ for (; parens>=0; lp++) {
+ if (lp->type == LP) {
+ parens++;
+ continue;
+ }
+ if (lp->type==RP)
+ parens--;
+ if (lp->type==DSHARP)
+ lp->type = DSHARP1; /* ## not special in arg */
+ if (lp->type==COMMA && parens==0 || parens<0 && (lp-1)->type!=LP) {
+ if (*narg>=NARG-1)
+ error(FATAL, "Sorry, too many macro arguments");
+ ttr.bp = ttr.tp = bp;
+ ttr.lp = lp;
+ atr[(*narg)++] = normtokenrow(&ttr);
+ bp = lp+1;
+ }
+ }
+ return ntok;
+}
+
+/*
+ * substitute the argument list into the replacement string
+ * This would be simple except for ## and #
+ */
+void
+substargs(Nlist *np, Tokenrow *rtr, Tokenrow **atr)
+{
+ Tokenrow tatr;
+ Token *tp;
+ int ntok, argno;
+
+ for (rtr->tp=rtr->bp; rtr->tp<rtr->lp; ) {
+ if (rtr->tp->type==SHARP) { /* string operator */
+ tp = rtr->tp;
+ rtr->tp += 1;
+ if ((argno = lookuparg(np, rtr->tp))<0) {
+ error(ERROR, "# not followed by macro parameter");
+ continue;
+ }
+ ntok = 1 + (rtr->tp - tp);
+ rtr->tp = tp;
+ insertrow(rtr, ntok, stringify(atr[argno]));
+ continue;
+ }
+ if (rtr->tp->type==NAME
+ && (argno = lookuparg(np, rtr->tp)) >= 0) {
+ if ((rtr->tp+1)->type==DSHARP
+ || rtr->tp!=rtr->bp && (rtr->tp-1)->type==DSHARP)
+ insertrow(rtr, 1, atr[argno]);
+ else {
+ copytokenrow(&tatr, atr[argno]);
+ expandrow(&tatr, "<macro>");
+ insertrow(rtr, 1, &tatr);
+ dofree(tatr.bp);
+ }
+ continue;
+ }
+ rtr->tp++;
+ }
+}
+
+/*
+ * Evaluate the ## operators in a tokenrow
+ */
+void
+doconcat(Tokenrow *trp)
+{
+ Token *ltp, *ntp;
+ Tokenrow ntr;
+ int len;
+
+ for (trp->tp=trp->bp; trp->tp<trp->lp; trp->tp++) {
+ if (trp->tp->type==DSHARP1)
+ trp->tp->type = DSHARP;
+ else if (trp->tp->type==DSHARP) {
+ char tt[128];
+ ltp = trp->tp-1;
+ ntp = trp->tp+1;
+ if (ltp<trp->bp || ntp>=trp->lp) {
+ error(ERROR, "## occurs at border of replacement");
+ continue;
+ }
+ len = ltp->len + ntp->len;
+ strncpy((char*)tt, (char*)ltp->t, ltp->len);
+ strncpy((char*)tt+ltp->len, (char*)ntp->t, ntp->len);
+ tt[len] = '\0';
+ setsource("<##>", -1, tt);
+ maketokenrow(3, &ntr);
+ gettokens(&ntr, 1);
+ unsetsource();
+ if (ntr.lp-ntr.bp!=2 || ntr.bp->type==UNCLASS)
+ error(WARNING, "Bad token %r produced by ##", &ntr);
+ ntr.lp = ntr.bp+1;
+ trp->tp = ltp;
+ makespace(&ntr);
+ insertrow(trp, (ntp-ltp)+1, &ntr);
+ dofree(ntr.bp);
+ trp->tp--;
+ }
+ }
+}
+
+/*
+ * tp is a potential parameter name of macro mac;
+ * look it up in mac's arglist, and if found, return the
+ * corresponding index in the argname array. Return -1 if not found.
+ */
+int
+lookuparg(Nlist *mac, Token *tp)
+{
+ Token *ap;
+
+ if (tp->type!=NAME || mac->ap==NULL)
+ return -1;
+ for (ap=mac->ap->bp; ap<mac->ap->lp; ap++) {
+ if (ap->len==tp->len && strncmp((char*)ap->t,(char*)tp->t,ap->len)==0)
+ return ap - mac->ap->bp;
+ }
+ return -1;
+}
+
+/*
+ * Return a quoted version of the tokenrow (from # arg)
+ */
+#define STRLEN 512
+Tokenrow *
+stringify(Tokenrow *vp)
+{
+ static Token t = { STRING };
+ static Tokenrow tr = { &t, &t, &t+1, 1 };
+ Token *tp;
+ uchar s[STRLEN];
+ uchar *sp = s, *cp;
+ int i, instring;
+
+ *sp++ = '"';
+ for (tp = vp->bp; tp < vp->lp; tp++) {
+ instring = tp->type==STRING || tp->type==CCON;
+ if (sp+2*tp->len >= &s[STRLEN-10]) {
+ error(ERROR, "Stringified macro arg is too long");
+ break;
+ }
+ if (tp->wslen && (tp->flag&XPWS)==0)
+ *sp++ = ' ';
+ for (i=0, cp=tp->t; i<tp->len; i++) {
+ if (instring && (*cp=='"' || *cp=='\\'))
+ *sp++ = '\\';
+ *sp++ = *cp++;
+ }
+ }
+ *sp++ = '"';
+ *sp = '\0';
+ sp = s;
+ t.len = strlen((char*)sp);
+ t.t = newstring(sp, t.len, 0);
+ return &tr;
+}
+
+/*
+ * expand a builtin name
+ */
+void
+builtin(Tokenrow *trp, int biname)
+{
+ char *op;
+ Token *tp;
+ Source *s;
+
+ tp = trp->tp;
+ trp->tp++;
+ /* need to find the real source */
+ s = cursource;
+ while (s && s->fd==-1)
+ s = s->next;
+ if (s==NULL)
+ s = cursource;
+ /* most are strings */
+ tp->type = STRING;
+ if (tp->wslen) {
+ *outp++ = ' ';
+ tp->wslen = 1;
+ }
+ op = outp;
+ *op++ = '"';
+ switch (biname) {
+
+ case KLINENO:
+ tp->type = NUMBER;
+ op = outnum(op-1, s->line);
+ break;
+
+ case KFILE: {
+ char *src = s->filename;
+ while ((*op++ = *src++) != 0)
+ if (src[-1] == '\\')
+ *op++ = '\\';
+ op--;
+ break;
+ }
+
+ case KDATE:
+ strncpy(op, curtime+4, 7);
+ strncpy(op+7, curtime+20, 4);
+ op += 11;
+ break;
+
+ case KTIME:
+ strncpy(op, curtime+11, 8);
+ op += 8;
+ break;
+
+ default:
+ error(ERROR, "cpp botch: unknown internal macro");
+ return;
+ }
+ if (tp->type==STRING)
+ *op++ = '"';
+ tp->t = (uchar*)outp;
+ tp->len = op - outp;
+ outp = op;
+}
diff --git a/lcc/cpp/nlist.c b/lcc/cpp/nlist.c
new file mode 100755
index 0000000..c77fff1
--- /dev/null
+++ b/lcc/cpp/nlist.c
@@ -0,0 +1,104 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "cpp.h"
+
+extern int getopt(int, char *const *, const char *);
+extern char *optarg;
+extern int optind;
+extern int verbose;
+extern int Cplusplus;
+Nlist *kwdefined;
+char wd[128];
+
+#define NLSIZE 128
+
+static Nlist *nlist[NLSIZE];
+
+struct kwtab {
+ char *kw;
+ int val;
+ int flag;
+} kwtab[] = {
+ "if", KIF, ISKW,
+ "ifdef", KIFDEF, ISKW,
+ "ifndef", KIFNDEF, ISKW,
+ "elif", KELIF, ISKW,
+ "else", KELSE, ISKW,
+ "endif", KENDIF, ISKW,
+ "include", KINCLUDE, ISKW,
+ "define", KDEFINE, ISKW,
+ "undef", KUNDEF, ISKW,
+ "line", KLINE, ISKW,
+ "error", KERROR, ISKW,
+ "pragma", KPRAGMA, ISKW,
+ "eval", KEVAL, ISKW,
+ "defined", KDEFINED, ISDEFINED+ISUNCHANGE,
+ "__LINE__", KLINENO, ISMAC+ISUNCHANGE,
+ "__FILE__", KFILE, ISMAC+ISUNCHANGE,
+ "__DATE__", KDATE, ISMAC+ISUNCHANGE,
+ "__TIME__", KTIME, ISMAC+ISUNCHANGE,
+ "__STDC__", KSTDC, ISUNCHANGE,
+ NULL
+};
+
+unsigned long namebit[077+1];
+Nlist *np;
+
+void
+setup_kwtab(void)
+{
+ struct kwtab *kp;
+ Nlist *np;
+ Token t;
+ static Token deftoken[1] = {{ NAME, 0, 0, 0, 7, (uchar*)"defined" }};
+ static Tokenrow deftr = { deftoken, deftoken, deftoken+1, 1 };
+
+ for (kp=kwtab; kp->kw; kp++) {
+ t.t = (uchar*)kp->kw;
+ t.len = strlen(kp->kw);
+ np = lookup(&t, 1);
+ np->flag = kp->flag;
+ np->val = kp->val;
+ if (np->val == KDEFINED) {
+ kwdefined = np;
+ np->val = NAME;
+ np->vp = &deftr;
+ np->ap = 0;
+ }
+ }
+}
+
+Nlist *
+lookup(Token *tp, int install)
+{
+ unsigned int h;
+ Nlist *np;
+ uchar *cp, *cpe;
+
+ h = 0;
+ for (cp=tp->t, cpe=cp+tp->len; cp<cpe; )
+ h += *cp++;
+ h %= NLSIZE;
+ np = nlist[h];
+ while (np) {
+ if (*tp->t==*np->name && tp->len==np->len
+ && strncmp((char*)tp->t, (char*)np->name, tp->len)==0)
+ return np;
+ np = np->next;
+ }
+ if (install) {
+ np = new(Nlist);
+ np->vp = NULL;
+ np->ap = NULL;
+ np->flag = 0;
+ np->val = 0;
+ np->len = tp->len;
+ np->name = newstring(tp->t, tp->len, 0);
+ np->next = nlist[h];
+ nlist[h] = np;
+ quickset(tp->t[0], tp->len>1? tp->t[1]:0);
+ return np;
+ }
+ return NULL;
+}
diff --git a/lcc/cpp/tokens.c b/lcc/cpp/tokens.c
new file mode 100755
index 0000000..701cbcc
--- /dev/null
+++ b/lcc/cpp/tokens.c
@@ -0,0 +1,370 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "cpp.h"
+
+static char wbuf[2*OBS];
+static char *wbp = wbuf;
+
+/*
+ * 1 for tokens that don't need whitespace when they get inserted
+ * by macro expansion
+ */
+static const char wstab[] = {
+ 0, /* END */
+ 0, /* UNCLASS */
+ 0, /* NAME */
+ 0, /* NUMBER */
+ 0, /* STRING */
+ 0, /* CCON */
+ 1, /* NL */
+ 0, /* WS */
+ 0, /* DSHARP */
+ 0, /* EQ */
+ 0, /* NEQ */
+ 0, /* LEQ */
+ 0, /* GEQ */
+ 0, /* LSH */
+ 0, /* RSH */
+ 0, /* LAND */
+ 0, /* LOR */
+ 0, /* PPLUS */
+ 0, /* MMINUS */
+ 0, /* ARROW */
+ 1, /* SBRA */
+ 1, /* SKET */
+ 1, /* LP */
+ 1, /* RP */
+ 0, /* DOT */
+ 0, /* AND */
+ 0, /* STAR */
+ 0, /* PLUS */
+ 0, /* MINUS */
+ 0, /* TILDE */
+ 0, /* NOT */
+ 0, /* SLASH */
+ 0, /* PCT */
+ 0, /* LT */
+ 0, /* GT */
+ 0, /* CIRC */
+ 0, /* OR */
+ 0, /* QUEST */
+ 0, /* COLON */
+ 0, /* ASGN */
+ 1, /* COMMA */
+ 0, /* SHARP */
+ 1, /* SEMIC */
+ 1, /* CBRA */
+ 1, /* CKET */
+ 0, /* ASPLUS */
+ 0, /* ASMINUS */
+ 0, /* ASSTAR */
+ 0, /* ASSLASH */
+ 0, /* ASPCT */
+ 0, /* ASCIRC */
+ 0, /* ASLSH */
+ 0, /* ASRSH */
+ 0, /* ASOR */
+ 0, /* ASAND */
+ 0, /* ELLIPS */
+ 0, /* DSHARP1 */
+ 0, /* NAME1 */
+ 0, /* DEFINED */
+ 0, /* UMINUS */
+};
+
+void
+maketokenrow(int size, Tokenrow *trp)
+{
+ trp->max = size;
+ if (size>0)
+ trp->bp = (Token *)domalloc(size*sizeof(Token));
+ else
+ trp->bp = NULL;
+ trp->tp = trp->bp;
+ trp->lp = trp->bp;
+}
+
+Token *
+growtokenrow(Tokenrow *trp)
+{
+ int ncur = trp->tp - trp->bp;
+ int nlast = trp->lp - trp->bp;
+
+ trp->max = 3*trp->max/2 + 1;
+ trp->bp = (Token *)realloc(trp->bp, trp->max*sizeof(Token));
+ if (trp->bp == NULL)
+ error(FATAL, "Out of memory from realloc");
+ trp->lp = &trp->bp[nlast];
+ trp->tp = &trp->bp[ncur];
+ return trp->lp;
+}
+
+/*
+ * Compare a row of tokens, ignoring the content of WS; return !=0 if different
+ */
+int
+comparetokens(Tokenrow *tr1, Tokenrow *tr2)
+{
+ Token *tp1, *tp2;
+
+ tp1 = tr1->tp;
+ tp2 = tr2->tp;
+ if (tr1->lp-tp1 != tr2->lp-tp2)
+ return 1;
+ for (; tp1<tr1->lp ; tp1++, tp2++) {
+ if (tp1->type != tp2->type
+ || (tp1->wslen==0) != (tp2->wslen==0)
+ || tp1->len != tp2->len
+ || strncmp((char*)tp1->t, (char*)tp2->t, tp1->len)!=0)
+ return 1;
+ }
+ return 0;
+}
+
+/*
+ * replace ntok tokens starting at dtr->tp with the contents of str.
+ * tp ends up pointing just beyond the replacement.
+ * Canonical whitespace is assured on each side.
+ */
+void
+insertrow(Tokenrow *dtr, int ntok, Tokenrow *str)
+{
+ int nrtok = rowlen(str);
+
+ dtr->tp += ntok;
+ adjustrow(dtr, nrtok-ntok);
+ dtr->tp -= ntok;
+ movetokenrow(dtr, str);
+ makespace(dtr);
+ dtr->tp += nrtok;
+ makespace(dtr);
+}
+
+/*
+ * make sure there is WS before trp->tp, if tokens might merge in the output
+ */
+void
+makespace(Tokenrow *trp)
+{
+ uchar *tt;
+ Token *tp = trp->tp;
+
+ if (tp >= trp->lp)
+ return;
+ if (tp->wslen) {
+ if (tp->flag&XPWS
+ && (wstab[tp->type] || trp->tp>trp->bp && wstab[(tp-1)->type])) {
+ tp->wslen = 0;
+ return;
+ }
+ tp->t[-1] = ' ';
+ return;
+ }
+ if (wstab[tp->type] || trp->tp>trp->bp && wstab[(tp-1)->type])
+ return;
+ tt = newstring(tp->t, tp->len, 1);
+ *tt++ = ' ';
+ tp->t = tt;
+ tp->wslen = 1;
+ tp->flag |= XPWS;
+}
+
+/*
+ * Copy an entire tokenrow into another, at tp.
+ * It is assumed that there is enough space.
+ * Not strictly conforming.
+ */
+void
+movetokenrow(Tokenrow *dtr, Tokenrow *str)
+{
+ int nby;
+
+ /* nby = sizeof(Token) * (str->lp - str->bp); */
+ nby = (char *)str->lp - (char *)str->bp;
+ memmove(dtr->tp, str->bp, nby);
+}
+
+/*
+ * Move the tokens in a row, starting at tr->tp, rightward by nt tokens;
+ * nt may be negative (left move).
+ * The row may need to be grown.
+ * Non-strictly conforming because of the (char *), but easily fixed
+ */
+void
+adjustrow(Tokenrow *trp, int nt)
+{
+ int nby, size;
+
+ if (nt==0)
+ return;
+ size = (trp->lp - trp->bp) + nt;
+ while (size > trp->max)
+ growtokenrow(trp);
+ /* nby = sizeof(Token) * (trp->lp - trp->tp); */
+ nby = (char *)trp->lp - (char *)trp->tp;
+ if (nby)
+ memmove(trp->tp+nt, trp->tp, nby);
+ trp->lp += nt;
+}
+
+/*
+ * Copy a row of tokens into the destination holder, allocating
+ * the space for the contents. Return the destination.
+ */
+Tokenrow *
+copytokenrow(Tokenrow *dtr, Tokenrow *str)
+{
+ int len = rowlen(str);
+
+ maketokenrow(len, dtr);
+ movetokenrow(dtr, str);
+ dtr->lp += len;
+ return dtr;
+}
+
+/*
+ * Produce a copy of a row of tokens. Start at trp->tp.
+ * The value strings are copied as well. The first token
+ * has WS available.
+ */
+Tokenrow *
+normtokenrow(Tokenrow *trp)
+{
+ Token *tp;
+ Tokenrow *ntrp = new(Tokenrow);
+ int len;
+
+ len = trp->lp - trp->tp;
+ if (len<=0)
+ len = 1;
+ maketokenrow(len, ntrp);
+ for (tp=trp->tp; tp < trp->lp; tp++) {
+ *ntrp->lp = *tp;
+ if (tp->len) {
+ ntrp->lp->t = newstring(tp->t, tp->len, 1);
+ *ntrp->lp->t++ = ' ';
+ if (tp->wslen)
+ ntrp->lp->wslen = 1;
+ }
+ ntrp->lp++;
+ }
+ if (ntrp->lp > ntrp->bp)
+ ntrp->bp->wslen = 0;
+ return ntrp;
+}
+
+/*
+ * Debugging
+ */
+void
+peektokens(Tokenrow *trp, char *str)
+{
+ Token *tp;
+
+ tp = trp->tp;
+ flushout();
+ if (str)
+ fprintf(stderr, "%s ", str);
+ if (tp<trp->bp || tp>trp->lp)
+ fprintf(stderr, "(tp offset %d) ", tp-trp->bp);
+ for (tp=trp->bp; tp<trp->lp && tp<trp->bp+32; tp++) {
+ if (tp->type!=NL) {
+ int c = tp->t[tp->len];
+ tp->t[tp->len] = 0;
+ fprintf(stderr, "%s", tp->t);
+ tp->t[tp->len] = c;
+ }
+ if (tp->type==NAME) {
+ fprintf(stderr, tp==trp->tp?"{*":"{");
+ prhideset(tp->hideset);
+ fprintf(stderr, "} ");
+ } else
+ fprintf(stderr, tp==trp->tp?"{%x*} ":"{%x} ", tp->type);
+ }
+ fprintf(stderr, "\n");
+ fflush(stderr);
+}
+
+void
+puttokens(Tokenrow *trp)
+{
+ Token *tp;
+ int len;
+ uchar *p;
+
+ if (verbose)
+ peektokens(trp, "");
+ tp = trp->bp;
+ for (; tp<trp->lp; tp++) {
+ len = tp->len+tp->wslen;
+ p = tp->t-tp->wslen;
+ while (tp<trp->lp-1 && p+len == (tp+1)->t - (tp+1)->wslen) {
+ tp++;
+ len += tp->wslen+tp->len;
+ }
+ if (len>OBS/2) { /* handle giant token */
+ if (wbp > wbuf)
+ write(1, wbuf, wbp-wbuf);
+ write(1, (char *)p, len);
+ wbp = wbuf;
+ } else {
+ memcpy(wbp, p, len);
+ wbp += len;
+ }
+ if (wbp >= &wbuf[OBS]) {
+ write(1, wbuf, OBS);
+ if (wbp > &wbuf[OBS])
+ memcpy(wbuf, wbuf+OBS, wbp - &wbuf[OBS]);
+ wbp -= OBS;
+ }
+ }
+ trp->tp = tp;
+ if (cursource->fd==0)
+ flushout();
+}
+
+void
+flushout(void)
+{
+ if (wbp>wbuf) {
+ write(1, wbuf, wbp-wbuf);
+ wbp = wbuf;
+ }
+}
+
+/*
+ * turn a row into just a newline
+ */
+void
+setempty(Tokenrow *trp)
+{
+ trp->tp = trp->bp;
+ trp->lp = trp->bp+1;
+ *trp->bp = nltoken;
+}
+
+/*
+ * generate a number
+ */
+char *
+outnum(char *p, int n)
+{
+ if (n>=10)
+ p = outnum(p, n/10);
+ *p++ = n%10 + '0';
+ return p;
+}
+
+/*
+ * allocate and initialize a new string from s, of length l, at offset o
+ * Null terminated.
+ */
+uchar *
+newstring(uchar *s, int l, int o)
+{
+ uchar *ns = (uchar *)domalloc(l+o+1);
+
+ ns[l+o] = '\0';
+ return (uchar*)strncpy((char*)ns+o, (char*)s, l) - o;
+}
diff --git a/lcc/cpp/unix.c b/lcc/cpp/unix.c
new file mode 100755
index 0000000..332ab0c
--- /dev/null
+++ b/lcc/cpp/unix.c
@@ -0,0 +1,116 @@
+#include <stdio.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <string.h>
+#include "cpp.h"
+
+extern int getopt(int, char *const *, const char *);
+extern char *optarg, rcsid[];
+extern int optind;
+int verbose;
+int Mflag; /* only print active include files */
+char *objname; /* "src.$O: " */
+int Cplusplus = 1;
+
+void
+setup(int argc, char **argv)
+{
+ int c, fd, i;
+ char *fp, *dp;
+ Tokenrow tr;
+ extern void setup_kwtab(void);
+
+ setup_kwtab();
+ while ((c = getopt(argc, argv, "MNOVv+I:D:U:F:lg")) != -1)
+ switch (c) {
+ case 'N':
+ for (i=0; i<NINCLUDE; i++)
+ if (includelist[i].always==1)
+ includelist[i].deleted = 1;
+ break;
+ case 'I':
+ for (i=NINCLUDE-2; i>=0; i--) {
+ if (includelist[i].file==NULL) {
+ includelist[i].always = 1;
+ includelist[i].file = optarg;
+ break;
+ }
+ }
+ if (i<0)
+ error(FATAL, "Too many -I directives");
+ break;
+ case 'D':
+ case 'U':
+ setsource("<cmdarg>", -1, optarg);
+ maketokenrow(3, &tr);
+ gettokens(&tr, 1);
+ doadefine(&tr, c);
+ unsetsource();
+ break;
+ case 'M':
+ Mflag++;
+ break;
+ case 'v':
+ fprintf(stderr, "%s %s\n", argv[0], rcsid);
+ break;
+ case 'V':
+ verbose++;
+ break;
+ case '+':
+ Cplusplus++;
+ break;
+ default:
+ break;
+ }
+ dp = ".";
+ fp = "<stdin>";
+ fd = 0;
+ if (optind<argc) {
+ if ((fp = strrchr(argv[optind], '/')) != NULL) {
+ int len = fp - argv[optind];
+ dp = (char*)newstring((uchar*)argv[optind], len+1, 0);
+ dp[len] = '\0';
+ }
+ fp = (char*)newstring((uchar*)argv[optind], strlen(argv[optind]), 0);
+ if ((fd = open(fp, 0)) <= 0)
+ error(FATAL, "Can't open input file %s", fp);
+ }
+ if (optind+1<argc) {
+ int fdo = creat(argv[optind+1], 0666);
+ if (fdo<0)
+ error(FATAL, "Can't open output file %s", argv[optind+1]);
+ dup2(fdo, 1);
+ }
+ if(Mflag)
+ setobjname(fp);
+ includelist[NINCLUDE-1].always = 0;
+ includelist[NINCLUDE-1].file = dp;
+ setsource(fp, fd, NULL);
+}
+
+
+
+/* memmove is defined here because some vendors don't provide it at
+ all and others do a terrible job (like calling malloc) */
+void *
+memmove(void *dp, const void *sp, size_t n)
+{
+ unsigned char *cdp, *csp;
+
+ if (n<=0)
+ return 0;
+ cdp = dp;
+ csp = (unsigned char *)sp;
+ if (cdp < csp) {
+ do {
+ *cdp++ = *csp++;
+ } while (--n);
+ } else {
+ cdp += n;
+ csp += n;
+ do {
+ *--cdp = *--csp;
+ } while (--n);
+ }
+ return 0;
+}
diff --git a/lcc/custom.mk b/lcc/custom.mk
new file mode 100755
index 0000000..2f32731
--- /dev/null
+++ b/lcc/custom.mk
@@ -0,0 +1 @@
+BUILDDIR=/tmp
diff --git a/lcc/doc/4.html b/lcc/doc/4.html
new file mode 100755
index 0000000..0158d8b
--- /dev/null
+++ b/lcc/doc/4.html
@@ -0,0 +1,754 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<html>
+
+<head>
+<link HREF="mailto:drh@microsoft.com" REV="made" TITLE="David R. Hanson">
+<title>The lcc 4.1 Code-Generation Interface</title>
+</head>
+
+<body>
+
+<h1>The lcc 4.1 Code-Generation Interface</h1>
+
+<p ALIGN="LEFT"><strong><a HREF="http://www.research.microsoft.com/~cwfraser/">Christopher
+W. Fraser</a> and <a HREF="http://www.research.microsoft.com/~drh/">David R. Hanson</a>, <a
+HREF="http://www.research.microsoft.com/">Microsoft Research</a></strong></p>
+
+<h2>Contents</h2>
+
+<dir>
+ <li><a HREF="#intro">Introduction</a> </li>
+ <li><a HREF="#metrics">5.1 Type Metrics</a></li>
+ <li><a HREF="#symbols">5.3 Symbols</a> </li>
+ <li><a HREF="#operators">5.5 Dag Operators</a></li>
+ <li><a HREF="#flags">5.6 Interface Flags</a></li>
+ <li><a HREF="#definitions">5.8 Definitions</a></li>
+ <li><a HREF="#constants">5.9 Constants</a></li>
+ <li><a HREF="#upcalls">5.12 Upcalls</a></li>
+</dir>
+
+<h2><a NAME="intro">Introduction</a></h2>
+
+<p>Version 4.1 is the latest release of <a
+HREF="http://www.cs.princeton.edu/software/lcc/">lcc</a>, the ANSI C compiler described in
+our book <cite>A Retargetable C Compiler: Design and Implementation</cite>
+(Addison-Wesley, 1995, ISBN 0-8053-1670-1). This document summarizes the differences
+between the 4.1 code-generation interface and the 3.x interface described in Chap. 5 of <cite>A
+Retargetable C Compiler</cite>.</p>
+
+<p>Previous versions of lcc supported only three sizes of integers, two sizes of floats,
+and insisted that pointers fit in unsigned integers (see Sec. 5.1 of <cite>A Retargetable
+C Compiler</cite>). These assumptions simplified the compiler, and were suitable for
+32-bit architectures. But on 64-bit architectures, such as the DEC ALPHA, it's natural to
+have four sizes of integers and perhaps three sizes of floats, and on 16-bit
+architectures, 32-bit pointers don't fit in unsigned integers. Also, the 3.x constaints
+limited the use of lcc's back ends for other languages, such as Java.</p>
+
+<p>Version 4.x removes all of these restrictions: It supports any number of sizes for
+integers and floats, and the size of pointers need not be related to the size of any of
+the integer types. The major changes in the code-generation interface are:
+
+<ul>
+ <li>The number of type suffixes has been reduced to 6.</li>
+ <li>Dag operators are composed of a generic operator, a type suffix, and a size.</li>
+ <li>Unsigned variants of several operators have been added.</li>
+ <li>Several interface functions have new signatures.</li>
+</ul>
+
+<p>In addition, version 4.x is written in ANSI C and uses the standard I/O library and
+other standard C functions.</p>
+
+<p>The sections below parallel the subsections of Chap. 5 of <cite>A Retargetable C
+Compiler</cite> and summarize the differences between the 3.x and 4.x code-generation
+interface. Unaffected subsections are omitted. Page citations refer to pages in <cite>A
+Retargetable C Compiler</cite>.</p>
+
+<h2><a NAME="metrics">5.1 Type Metrics</a></h2>
+
+<p>There are now 10 metrics in an interface record:</p>
+
+<pre>Metrics charmetric;
+Metrics shortmetric;
+Metrics intmetric;
+Metrics longmetric;
+Metrics longlongmetric;
+Metrics floatmetric;
+Metrics doublemetric;
+Metrics longdoublemetric;
+Metrics ptrmetric;
+Metrics structmetric;</pre>
+
+<p>Each of these specifies the size and alignment of the corresponding type. <code>ptrmetric</code>
+describes all pointers.</p>
+
+<h2><a NAME="symbols">5.3 Symbols</a></h2>
+
+<p>The actual value of a constant is stored in the <code>u.c.v</code> field of a symbol,
+which holds a <code>Value</code>:</p>
+
+<pre>typedef union value {
+ long i;
+ unsigned long u;
+ long double d;
+ void *p;
+ void (*g)(void);
+} Value;</pre>
+
+<p>The value is stored in the appropriate field according to its type, which is given by
+the symbol's <code>type</code> field.</p>
+
+<h2><a NAME="operators">5.5 Dag Operators</a></h2>
+
+<p>The <code>op</code> field a of <code>node</code> structure holds a dag operator, which
+consists of a generic operator, a type suffix, and a size indicator. The type suffixes
+are:</p>
+
+<pre>enum {
+ F=FLOAT,
+ I=INT,
+ U=UNSIGNED,
+ P=POINTER,
+ V=VOID,
+ B=STRUCT
+};
+
+#define sizeop(n) ((n)&lt;&lt;10)</pre>
+
+<p>Given a generic operator <code>o</code>, a type suffix <code>t</code>, and a size <code>s</code>,
+a type- and size-specific operator is formed by <code>o+t+sizeop(s)</code>. For example, <code>ADD+F+sizeop(4)</code>
+forms the operator <code>ADDF4</code>, which denotes the sum of two 4-byte floats.
+Similarly, <code>ADD+F+sizeop(8)</code> forms <code>ADDF8</code>, which denotes 8-byte
+floating addition. In the 3.x code-generation interface, <code>ADDF</code> and <code>ADDD</code>
+denoted these operations. There was no size indicator in the 3.x operators because the
+type suffix supplied both a type and a size.</p>
+
+<p>Table 5.1 lists each generic operator, its valid type suffixes, and the number of <code>kids</code>
+and <code>syms</code> that it uses; multiple values for <code>kids</code> indicate
+type-specific variants. The notations in the <strong>syms</strong> column give the number
+of <code>syms</code> values and a one-letter code that suggests their uses: 1V indicates
+that <code>syms[0]</code> points to a symbol for a variable, 1C indicates that <code>syms[0]</code>
+is a constant, and 1L indicates that <code>syms[0]</code> is a label. For 1S, <code>syms[0]</code>
+is a constant whose value is a size in bytes; 2S adds <code>syms[1]</code>, which is a
+constant whose value is an alignment. For most operators, the type suffix and size
+indicator denote the type and size of operation to perform and the type and size of the
+result.</p>
+
+<table WIDTH="100%" BORDER="0" CELLPADDING="0" CELLSPACING="0">
+ <tr>
+ <td COLSPAN="6" ALIGN="CENTER"><strong>Table 5.1<img SRC="/~drh/resources/dot_clear.gif"
+ ALT="|" WIDTH="18" HEIGHT="1">Node Operators.</strong></td>
+ </tr>
+ <tr>
+ <td><strong>syms</strong></td>
+ <td><strong>kids</strong></td>
+ <td><strong>Operator</strong></td>
+ <td><strong>Type Suffixes</strong></td>
+ <td><strong>Sizes</strong></td>
+ <td><strong>Operation</strong></td>
+ </tr>
+ <tr>
+ <td>1V</td>
+ <td>0</td>
+ <td><code>ADDRF</code></td>
+ <td><code>...P..</code></td>
+ <td>p</td>
+ <td>address of a parameter</td>
+ </tr>
+ <tr>
+ <td>1V</td>
+ <td>0</td>
+ <td><code>ADDRG</code></td>
+ <td><code>...P..</code></td>
+ <td>p</td>
+ <td>address of a global</td>
+ </tr>
+ <tr>
+ <td>1V</td>
+ <td>0</td>
+ <td><code>ADDRL</code></td>
+ <td><code>...P..</code></td>
+ <td>p</td>
+ <td>address of a local</td>
+ </tr>
+ <tr>
+ <td>1C</td>
+ <td>0</td>
+ <td><code>CNST</code></td>
+ <td><code>FIUP..</code></td>
+ <td>fdx csilh p</td>
+ <td>constant</td>
+ </tr>
+ <tr ALIGN="LEFT" VALIGN="TOP">
+ <td><img SRC="/~drh/resources/dot_clear.gif" ALT="|" WIDTH="1" HEIGHT="12"></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ </tr>
+ <tr>
+ <td></td>
+ <td>1</td>
+ <td><code>BCOM</code></td>
+ <td><code>.IU...</code></td>
+ <td>ilh</td>
+ <td>bitwise complement</td>
+ </tr>
+ <tr>
+ <td>1S</td>
+ <td>1</td>
+ <td><code>CVF</code></td>
+ <td><code>FI....</code></td>
+ <td>fdx ilh</td>
+ <td>convert from float</td>
+ </tr>
+ <tr>
+ <td>1S</td>
+ <td>1</td>
+ <td><code>CVI</code></td>
+ <td><code>FIU...</code></td>
+ <td>fdx csilh csilhp</td>
+ <td>convert from signed integer</td>
+ </tr>
+ <tr>
+ <td>1S</td>
+ <td>1</td>
+ <td><code>CVP</code></td>
+ <td><code>..U..</code></td>
+ <td>p</td>
+ <td>convert from pointer</td>
+ </tr>
+ <tr>
+ <td>1S</td>
+ <td>1</td>
+ <td><code>CVU</code></td>
+ <td><code>.IUP..</code></td>
+ <td>csilh p</td>
+ <td>convert from unsigned integer</td>
+ </tr>
+ <tr>
+ <td></td>
+ <td>1</td>
+ <td><code>INDIR</code></td>
+ <td><code>FIUP.B</code></td>
+ <td>fdx csilh p</td>
+ <td>fetch</td>
+ </tr>
+ <tr>
+ <td></td>
+ <td>1</td>
+ <td><code>NEG</code></td>
+ <td><code>FI....</code></td>
+ <td>fdx ilh</td>
+ <td>negation</td>
+ </tr>
+ <tr>
+ <td><img SRC="/~drh/resources/dot_clear.gif" ALT="|" WIDTH="1" HEIGHT="12"></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ </tr>
+ <tr>
+ <td></td>
+ <td>2</td>
+ <td><code>ADD</code></td>
+ <td><code>FIUP..</code></td>
+ <td>fdx ilh ilhp p</td>
+ <td>addition</td>
+ </tr>
+ <tr>
+ <td></td>
+ <td>2</td>
+ <td><code>BAND</code></td>
+ <td><code>.IU...</code></td>
+ <td>ilh</td>
+ <td>bitwise AND</td>
+ </tr>
+ <tr>
+ <td></td>
+ <td>2</td>
+ <td><code>BOR</code></td>
+ <td><code>.IU...</code></td>
+ <td>ilh</td>
+ <td>bitwise inclusive OR</td>
+ </tr>
+ <tr>
+ <td></td>
+ <td>2</td>
+ <td><code>BXOR</code></td>
+ <td><code>.IU...</code></td>
+ <td>ilh</td>
+ <td>bitwise exclusive OR</td>
+ </tr>
+ <tr>
+ <td></td>
+ <td>2</td>
+ <td><code>DIV</code></td>
+ <td><code>FIU...</code></td>
+ <td>fdx ilh</td>
+ <td>division</td>
+ </tr>
+ <tr>
+ <td></td>
+ <td>2</td>
+ <td><code>LSH</code></td>
+ <td><code>.IU...</code></td>
+ <td>ilh</td>
+ <td>left shift</td>
+ </tr>
+ <tr>
+ <td></td>
+ <td>2</td>
+ <td><code>MOD</code></td>
+ <td><code>.IU...</code></td>
+ <td>ilh</td>
+ <td>modulus</td>
+ </tr>
+ <tr>
+ <td></td>
+ <td>2</td>
+ <td><code>MUL</code></td>
+ <td><code>FIU...</code></td>
+ <td>fdx ilh</td>
+ <td>multiplication</td>
+ </tr>
+ <tr>
+ <td></td>
+ <td>2</td>
+ <td><code>RSH</code></td>
+ <td><code>.IU...</code></td>
+ <td>ilh</td>
+ <td>right shift</td>
+ </tr>
+ <tr>
+ <td></td>
+ <td>2</td>
+ <td><code>SUB</code></td>
+ <td><code>FIUP..</code></td>
+ <td>fdx ilh ilhp p</td>
+ <td>subtraction</td>
+ </tr>
+ <tr>
+ <td><img SRC="/~drh/resources/dot_clear.gif" ALT="|" WIDTH="1" HEIGHT="12"></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ </tr>
+ <tr>
+ <td>2S</td>
+ <td>2</td>
+ <td><code>ASGN</code></td>
+ <td><code>FIUP.B</code></td>
+ <td>fdx csilh p</td>
+ <td>assignment</td>
+ </tr>
+ <tr>
+ <td>1L</td>
+ <td>2</td>
+ <td><code>EQ</code></td>
+ <td><code>FIU...</code></td>
+ <td>fdx ilh ilhp</td>
+ <td>jump if equal</td>
+ </tr>
+ <tr>
+ <td>1L</td>
+ <td>2</td>
+ <td><code>GE</code></td>
+ <td><code>FIU...</code></td>
+ <td>fdx ilh ilhp</td>
+ <td>jump if greater than or equal</td>
+ </tr>
+ <tr>
+ <td>1L</td>
+ <td>2</td>
+ <td><code>GT</code></td>
+ <td><code>FIU...</code></td>
+ <td>fdx ilh ilhp</td>
+ <td>jump if greater than</td>
+ </tr>
+ <tr>
+ <td>1L</td>
+ <td>2</td>
+ <td><code>LE</code></td>
+ <td><code>FIU...</code></td>
+ <td>fdx ilh ilhp</td>
+ <td>jump if less than or equal</td>
+ </tr>
+ <tr>
+ <td>1L</td>
+ <td>2</td>
+ <td><code>LT</code></td>
+ <td><code>FIU...</code></td>
+ <td>fdx ilh ilhp</td>
+ <td>jump if less than</td>
+ </tr>
+ <tr>
+ <td>1L</td>
+ <td>2</td>
+ <td><code>NE</code></td>
+ <td><code>FIU...</code></td>
+ <td>fdx ilh ilhp</td>
+ <td>jump if not equal</td>
+ </tr>
+ <tr>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ </tr>
+ <tr>
+ <td>2S</td>
+ <td>1</td>
+ <td><code>ARG</code></td>
+ <td><code>FIUP.B</code></td>
+ <td>fdx ilh p</td>
+ <td>argument</td>
+ </tr>
+ <tr>
+ <td>1</td>
+ <td>1 or 2</td>
+ <td><code>CALL</code></td>
+ <td><code>FIUPVB</code></td>
+ <td>fdx ilh p</td>
+ <td>function call</td>
+ </tr>
+ <tr>
+ <td></td>
+ <td>1</td>
+ <td><code>RET</code></td>
+ <td><code>FIUPV.</code></td>
+ <td>fdx ilh p</td>
+ <td>return from function</td>
+ </tr>
+ <tr>
+ <td><img SRC="/~drh/resources/dot_clear.gif" ALT="|" WIDTH="1" HEIGHT="12"></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ </tr>
+ <tr>
+ <td></td>
+ <td>1</td>
+ <td><code>JUMP</code></td>
+ <td><code>....V.</code></td>
+ <td></td>
+ <td>unconditional jump</td>
+ </tr>
+ <tr>
+ <td>1L</td>
+ <td>0</td>
+ <td><code>LABEL</code></td>
+ <td><code>....V.</code></td>
+ <td></td>
+ <td>label definition</td>
+ </tr>
+</table>
+
+<p>The entries in the <strong>Sizes</strong> column indicate sizes of the operators that
+back ends must implement. Letters denote the size of float (f), double (d), long double
+(x), character (c), short integer (s), integer (i), long integer (l), &quot;long
+long&quot; integer (h) , and pointer (p). These sizes are separated into sets for each
+type suffix, except that a single set is used for both I and U when the set for I is
+identical to the set for U.</p>
+
+<p>The actual values for the size indicators, fdxcsilhp, depend on the target. A
+specification like <code>ADDF</code>f denotes the operator <code>ADD+F+sizeop(</code>f<code>)</code>,
+where &quot;f&quot; is replaced by a target-dependent value, e.g., <code>ADDF4</code> and <code>ADDF8</code>.
+For example, back ends must implement the following <code>CVI</code> and <code>MUL</code>
+operators.</p>
+
+<blockquote>
+ <p><code>CVIF</code>f <code>CVIF</code>d <code>CVIF</code>x<br>
+ <code>CVII</code>c <code>CVII</code>s <code>CVII</code>i <code>CVII</code>l <code>CVII</code>h<br>
+ <code>CVIU</code>c <code>CVIU</code>s <code>CVIU</code>i <code>CVIU</code>l <code>CVIU</code>h
+ <code>CVIU</code>p<br>
+ <br>
+ <code>MULF</code>f <code>MULF</code>d <code>MULF</code>x<br>
+ <code>MULI</code>i <code>MULI</code>l <code>MULI</code>h<br>
+ <code>MULU</code>i <code>MULU</code>l <code>MULU</code>h</p>
+</blockquote>
+
+<p>On most platforms, there are fewer than three sizes of floats and six sizes of
+integers, and pointers are usually the same size as one of the integers. And lcc doesn't
+support the &quot;long long&quot; type, so h is not currently used. So the set of
+platform-specific operators is usually smaller than the list above suggests. For example,
+the X86, SPARC, and MIPS back ends implement the following <code>CVI</code> and <code>MUL</code>
+operators.</p>
+
+<blockquote>
+ <p><code>CVIF</code>4 <code>CVIF</code>8<br>
+ <code>CVII</code>1 <code>CVII</code>2 <code>CVII</code>4<br>
+ <code>CVIU</code>1 <code>CVIU</code>2 <code>CVIU</code>4 <br>
+ <br>
+ <code>MULF</code>4 <code>MULF</code>8<br>
+ <code>MULI</code>4<br>
+ <code>MULU</code>4</p>
+</blockquote>
+
+<p>The set of operators is thus target-dependent; for example, <code>ADDI8</code> appears
+only if the target supports an 8-byte integer type. <a
+HREF="ftp://ftp.cs.princeton.edu/pub/packages/lcc/contrib/ops.c"><code>ops.c</code></a> is
+a program that, given a set of sizes, prints the required operators and their values,
+e.g.,</p>
+
+<blockquote>
+ <pre>% <em>ops c=1 s=2 i=4 l=4 h=4 f=4 d=8 x=8 p=4</em>
+...
+ CVIF4=4225 CVIF8=8321
+ CVII1=1157 CVII2=2181 CVII4=4229
+ CVIU1=1158 CVIU2=2182 CVIU4=4230
+...
+ MULF4=4561 MULF8=8657
+ MULI4=4565
+ MULU4=4566
+...
+131 operators</pre>
+</blockquote>
+
+<p>The type suffix for a conversion operator denotes the type of the result and the size
+indicator gives the size of the result. For example, <code>CVUI4</code> converts an
+unsigned (<code>U</code>) to a 4-byte signed integer (<code>I4</code>). The <code>syms[0]</code>
+field points to a symbol-table entry for a integer constant that gives the size of the
+source operand. For example, if <code>syms[0]</code> in a <code>CVUI4</code> points to a
+symbol-table entry for 2, the conversion widens a 2-byte unsigned integer to a 4-byte
+signed integer. Conversions that widen unsigned integers zero-extend; those that widen
+signed integers sign-extend.</p>
+
+<p>The front end composes conversions between types <em>T</em><sub>1</sub> and <em>T</em><sub>2</sub>
+by widening <em>T</em><sub>1</sub> to it's &quot;supertype&quot;, if necessary, converting
+that result to <em>T</em><sub>2</sub>'s supertype, then narrowing the result to <em>T</em><sub>2</sub>,
+if necessary. The following table lists the supertypes; omitted entries are their own
+supertypes.</p>
+
+<blockquote>
+ <table BORDER="0" CELLPADDING="0" CELLSPACING="0">
+ <tr>
+ <td><strong>Type</strong></td>
+ <td><img SRC="/~drh/resources/dot_clear.gif" ALT="|" WIDTH="24" HEIGHT="1"></td>
+ <td><strong>Supertype</strong></td>
+ </tr>
+ <tr>
+ <td>signed char</td>
+ <td></td>
+ <td>int</td>
+ </tr>
+ <tr>
+ <td>signed short</td>
+ <td></td>
+ <td>int</td>
+ </tr>
+ <tr ALIGN="LEFT" VALIGN="TOP">
+ <td>unsigned char</td>
+ <td></td>
+ <td>int, if sizeof (char) &lt; sizeof (int)<br>
+ unsigned, otherwise</td>
+ </tr>
+ <tr ALIGN="LEFT" VALIGN="TOP">
+ <td>unsigned short</td>
+ <td></td>
+ <td>int, if sizeof (short) &lt; sizeof (int)<br>
+ unsigned, otherwise</td>
+ </tr>
+ <tr ALIGN="LEFT" VALIGN="TOP">
+ <td>void *</td>
+ <td></td>
+ <td>an unsigned type as large as a pointer</td>
+ </tr>
+ </table>
+</blockquote>
+
+<p>Pointers are converted to an unsigned type of the same size, even when that type is not
+one of the integer types.</p>
+
+<p>For example, the front end converts a signed short to a float by first converting it to
+an int and then to a float. It converts an unsigned short to an int with a single <code>CVUI</code>i
+conversion, when shorts are smaller than ints.</p>
+
+<p>There are now signed and unsigned variants of <code>ASGN</code>, <code>INDIR</code>, <code>BCOM</code>,
+<code>BOR</code>, <code>BXOR</code>, <code>BAND</code>, <code>ARG</code>, <code>CALL</code>,
+and <code>RET</code> to simplify code generation on platforms that use different
+instructions or register set for signed and unsigned operations. Likewise there are now
+pointer variants of <code>ASGN</code>, <code>INDIR</code>, <code>ARG</code>, <code>CALL</code>,
+and <code>RET</code>.</p>
+
+<h2><a NAME="flags">5.6 Interface Flags</a></h2>
+
+<pre>unsigned unsigned_char:1;</pre>
+
+<p>tells the front end whether plain characters are signed or unsigned. If it's zero, char
+is a signed type; otherwise, char is an unsigned type.</p>
+
+<p>All the interface flags can be set by command-line options, e.g., <code>-Wf-unsigned_char=1</code>
+causes plain characters to be unsigned.</p>
+
+<h2><a NAME="definitions">5.8 Definitions</a></h2>
+
+<p>The front end announces local variables by calling</p>
+
+<pre>void (*local)(Symbol);</pre>
+
+<p>It announces temporaries likewise; these have the symbol's <code>temporary</code> flag
+set, which indicates that the symbol will be used only in the next call to <code>gen</code>.
+If a temporary's <code>u.t.cse</code> field is nonnull, it points to the node that
+computes the value assigned to the temporary; see page 346.</p>
+
+<p>The front end calls</p>
+
+<pre>void (*address)(Symbol p, Symbol q, long n);</pre>
+
+<p>to initialize <code>q</code> to a symbol that represents an address of the form <em>x</em>+<code>n</code>,
+where <em>x</em> is the address represented by <code>p</code> and the long integer <code>n</code>
+is positive or negative.</p>
+
+<h2><a NAME="constants">5.9 Constants</a></h2>
+
+<p>The interface function</p>
+
+<pre>void (*defconst)(int suffix, int size, Value v);</pre>
+
+<p>initializes constants. defconst emits directives to define a cell and initialize it to
+a constant value. v is the constant value, suffix identifies the type of the value, and
+size is the size of the value in bytes. The value of suffix indicates which field of v
+holds the value, as shown in the following table.</p>
+
+<blockquote>
+ <table BORDER="0" CELLPADDING="1" CELLSPACING="1">
+ <tr>
+ <td><strong>suffix</strong></td>
+ <td><img SRC="/~drh/resources/dot_clear.gif" ALT="|" WIDTH="24" HEIGHT="1"></td>
+ <td><strong>v Field</strong></td>
+ <td><img SRC="/~drh/resources/dot_clear.gif" ALT="|" WIDTH="24" HEIGHT="1"></td>
+ <td><strong>size</strong></td>
+ </tr>
+ <tr>
+ <td><code>F</code></td>
+ <td></td>
+ <td><code>v.d</code></td>
+ <td></td>
+ <td>float, double, long double</td>
+ </tr>
+ <tr>
+ <td><code>I</code></td>
+ <td></td>
+ <td><code>v.i</code></td>
+ <td></td>
+ <td>signed char, signed short, signed int, signed long</td>
+ </tr>
+ <tr>
+ <td><code>U</code></td>
+ <td></td>
+ <td><code>v.u</code></td>
+ <td></td>
+ <td>unsigned char, unsigned short, unsigned int, unsigned long</td>
+ </tr>
+ <tr>
+ <td><code>P</code></td>
+ <td></td>
+ <td><code>v.p</code></td>
+ <td></td>
+ <td>void *</td>
+ </tr>
+ </table>
+</blockquote>
+
+<p><code>defconst</code> must narrow <code>v.</code>x when <code>size</code> is less than <code>sizeof</code>
+<code>v.</code>x; e.g., to emit an unsigned char, <code>defconst</code> should emit <code>(unsigned
+char)v.i</code>.</p>
+
+<h2><a NAME="upcalls">5.12 Upcalls</a></h2>
+
+<p>lcc 4.x uses standard I/O and its I/O functions have been changed accordingly. lcc
+reads input from the standard input, emits code to the standard output, and writes
+diagnostics to the standard error output. It uses <code>freopen</code> to redirect these
+streams to explicit files, when necessary.</p>
+
+<p><code>bp</code>, <code>outflush</code>, and <code>outs</code> have been eliminated.</p>
+
+<pre>extern void fprint(FILE *f, const char *fmt, ...);
+extern void print(const char *fmt, ...);</pre>
+
+<p>print formatted data to file <code>f</code> (<code>fprint</code>) or the standard
+output (<code>print</code>). These functions are like standard C's <code>printf</code> and
+<code>fprintf</code>, but support only some of the standard conversion specifiers and do
+not support flags, precision, and field-width specifications. They support the following
+new conversion specifiers in addition to those described on page 99.</p>
+
+<blockquote>
+ <table BORDER="0" CELLPADDING="0" CELLSPACING="0">
+ <tr>
+ <td><strong>Specifiers</strong></td>
+ <td><img SRC="/~drh/resources/dot_clear.gif" ALT="|" WIDTH="24" HEIGHT="1"></td>
+ <td><strong>Corresponding printf Specifiers</strong></td>
+ </tr>
+ <tr>
+ <td><code>%c</code></td>
+ <td></td>
+ <td><code>%c</code></td>
+ </tr>
+ <tr>
+ <td><code>%d %D</code></td>
+ <td></td>
+ <td><code>%d %ld</code></td>
+ </tr>
+ <tr>
+ <td><code>%u %U</code></td>
+ <td></td>
+ <td><code>%u %lu</code></td>
+ </tr>
+ <tr>
+ <td><code>%x %X</code></td>
+ <td></td>
+ <td><code>%x %lx</code></td>
+ </tr>
+ <tr>
+ <td><code>%f %e %g</code></td>
+ <td></td>
+ <td><code>%e %f %g</code></td>
+ </tr>
+ <tr ALIGN="LEFT" VALIGN="TOP">
+ <td><code>%p</code></td>
+ <td></td>
+ <td>Converts the corresponding void * argument to unsigned long and prints it with the <code>printf</code>
+ <code>%#x</code> specifier or just <code>%x</code> when the argument is null.</td>
+ </tr>
+ <tr ALIGN="LEFT" VALIGN="TOP">
+ <td><code>%I</code></td>
+ <td></td>
+ <td>Prints the number of spaces given by the corresponding argument.</td>
+ </tr>
+ </table>
+</blockquote>
+
+<pre>#define generic(op) ((op)&amp;0x3F0)
+#define specific(op) ((op)&amp;0x3FF)</pre>
+
+<p><code>generic(op)</code> returns the generic variant of <code>op</code>; that is,
+without its type suffix and size indicator. <code>specific(op)</code> returns the
+type-specific variant of <code>op</code>; that is, without its size indicator.</p>
+
+<p><code>newconst</code> has been replaced by</p>
+
+<pre>extern Symbol intconst(int n);</pre>
+
+<p>which installs the integer constant <code>n</code> in the symbol table, if necessary,
+and returns a pointer to the symbol-table entry.</p>
+
+<hr>
+
+<address>
+ <a HREF="http://www.research.microsoft.com/~cwfraser/">Chris Fraser</a> / <a
+ HREF="mailto:cwfraser@microsoft.com">cwfraser@microsoft.com</a><br>
+ <a HREF="http://www.research.microsoft.com/~drh/">David Hanson</a> / <a
+ HREF="mailto:drh@microsoft.com">drh@microsoft.com</a><br>
+ $Revision: 145 $ $Date: 2001-10-17 16:53:10 -0500 (Wed, 17 Oct 2001) $
+</address>
+</body>
+</html>
diff --git a/lcc/doc/bprint.1 b/lcc/doc/bprint.1
new file mode 100755
index 0000000..794c957
--- /dev/null
+++ b/lcc/doc/bprint.1
@@ -0,0 +1,83 @@
+.\" $Id: bprint.1 145 2001-10-17 21:53:10Z timo $
+.TH BPRINT 1 "local \- $Date: 2001-10-17 16:53:10 -0500 (Wed, 17 Oct 2001) $"
+.SH NAME
+bprint \- expression profiler
+.SH SYNOPSIS
+.B bprint
+[
+.I option ...
+]
+[
+.I file ...
+]
+.SH DESCRIPTION
+.I bprint
+produces on the standard output a listing of the programs compiled by
+.I lcc
+with the
+.B \-b
+option.
+Executing an
+.B a.out
+so compiled appends profiling data to
+.BR prof.out .
+The first token of each expression in the listing is preceded
+by the number of times it was executed
+enclosed in angle brackets as determined from the data in
+.BR prof.out .
+.I bprint
+interprets the following options.
+.TP
+.B \-c
+Compress the
+.B prof.out
+file, which otherwise grows with every execution of
+.BR a.out .
+.TP
+.B \-b
+Print an annotated listing as described above.
+.TP
+.B \-n
+Include line numbers in the listing.
+.TP
+.B \-f
+Print only the number of invocations of each function.
+A second
+.B \-f
+summarizes call sites instead of callers.
+.TP
+.BI \-I \*Sdir
+specifies additional directories in which to seek
+files given in
+.B prof.out
+that do not begin with `/'.
+.PP
+If any file names are given, only the requested data for those files are printed
+in the order presented.
+If no options are given,
+.B \-b
+is assumed.
+.SH FILES
+.PP
+.ta \w'$LCCDIR/liblcc.{a,lib}XX'u
+.nf
+prof.out profiling data
+$LCCDIR/liblcc.{a,lib} \fIlcc\fP-specific library
+.SH "SEE ALSO"
+.IR lcc (1),
+.IR prof (1)
+.SH BUGS
+Macros and comments can confuse
+.I bprint
+because it uses post-expansion source coordinates
+to annotate pre-expansion source files.
+If
+.I bprint
+sees that it's about to print a statement count
+.I inside
+a number or identifier, it moves the count to just
+.I before
+the token.
+.PP
+Can't cope with an ill-formed
+.BR prof.out .
diff --git a/lcc/doc/bprint.pdf b/lcc/doc/bprint.pdf
new file mode 100755
index 0000000..1b11963
--- /dev/null
+++ b/lcc/doc/bprint.pdf
Binary files differ
diff --git a/lcc/doc/install.html b/lcc/doc/install.html
new file mode 100755
index 0000000..fd9c88b
--- /dev/null
+++ b/lcc/doc/install.html
@@ -0,0 +1,796 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<html>
+
+<head>
+<link HREF="mailto:drh@cs.princeton.edu" REV="made" TITLE="David R. Hanson">
+<title>Installing lcc</title>
+</head>
+
+<body>
+
+<h1>Installing lcc</h1>
+
+<p ALIGN="LEFT"><strong><a HREF="http://www.research.microsoft.com/~cwfraser/">Christopher
+W. Fraser</a> and <a HREF="http://www.research.microsoft.com/~drh/">David R. Hanson</a>, <a
+HREF="http://www.research.microsoft.com/">Microsoft Research</a></strong></p>
+
+<h2>Contents</h2>
+
+<dir>
+ <li><a HREF="#intro">Introduction</a></li>
+ <li><a HREF="#unix">Installation on UNIX</a></li>
+ <li><a HREF="#driver">Building the Driver</a></li>
+ <li><a HREF="#rcc">Building the Compiler and Accessories</a></li>
+ <li><a HREF="#win32">Installation on Windows NT 4.0 and Windows 95/98</a></li>
+ <li><a HREF="#bugs">Reporting Bugs</a></li>
+ <li><a HREF="#mailinglist">Keeping in Touch</a></li>
+</dir>
+
+<h2><a NAME="intro">Introduction</a></h2>
+
+<p><a HREF="http://www.cs.princeton.edu/software/lcc/">lcc</a> is the ANSI C compiler
+described in our book <cite>A Retargetable C Compiler: Design and Implementation</cite>
+(Addison-Wesley, 1995, ISBN 0-8053-1670-1).</p>
+
+<p>If you're installing lcc on a UNIX system, read the remainder of this section and
+continue with the next section. If you're installing lcc on a Windows NT 4.0 or Windows
+95/98 system, and you intend only to <u>use</u> lcc, you can run the <a
+href="ftp://ftp.cs.princeton.edu/pub/packages/lcc/lcc41.exe">InstallShield executable</a>,
+which installs the binaries and the documentation. If you want to <u>modify</u> lcc or <u>rebuild</u>
+it from the source files, you need the <a
+href="ftp://ftp.cs.princeton.edu/packages/lcc/lcc41.zip">complete distribution</a>, and
+you should read the rest of the section, the following three sections, and the <a
+HREF="#win32">Windows NT/95/98</a> section.</p>
+
+<p>Extract the distribution into its own directory. All non-absolute paths below are
+relative to this directory. The distribution holds the following subdirectories.</p>
+
+<blockquote>
+ <table BORDER="0" CELLPADDING="1" CELLSPACING="1" WIDTH="80%">
+ <tr>
+ <td><a HREF="../src"><code>src</code></a></td>
+ <td></td>
+ <td>source code</td>
+ </tr>
+ <tr>
+ <td><a HREF="../etc"><code>etc</code></a></td>
+ <td></td>
+ <td>driver, accessories</td>
+ </tr>
+ <tr>
+ <td><a HREF="../lib"><code>lib</code></a></td>
+ <td></td>
+ <td>runtime library source code</td>
+ </tr>
+ <tr>
+ <td><a HREF="../cpp"><code>cpp</code></a></td>
+ <td></td>
+ <td>preprocessor source code</td>
+ </tr>
+ <tr>
+ <td><a HREF="../lburg"><code>lburg</code></a></td>
+ <td></td>
+ <td>code-generator generator source code</td>
+ </tr>
+ <tr>
+ <td><a HREF="../doc"><code>doc</code></a></td>
+ <td></td>
+ <td>this document, man pages</td>
+ </tr>
+ <tr>
+ <td><code><a HREF="../include">include</a>/*/*</code></td>
+ <td></td>
+ <td>include files</td>
+ </tr>
+ <tr>
+ <td><a HREF="../tst"><code>tst</code></a></td>
+ <td></td>
+ <td>test suite</td>
+ </tr>
+ <tr>
+ <td><code><a HREF="../alpha">alpha</a>/*/tst</code></td>
+ <td></td>
+ <td>ALPHA test outputs</td>
+ </tr>
+ <tr>
+ <td><code><a HREF="../mips">mips</a>/*/tst</code></td>
+ <td></td>
+ <td>MIPS test outputs</td>
+ </tr>
+ <tr>
+ <td><code><a HREF="../sparc">sparc</a>/*/tst</code></td>
+ <td></td>
+ <td>SPARC test outputs</td>
+ </tr>
+ <tr>
+ <td><code><a HREF="../x86">x86</a>/*/tst</code></td>
+ <td></td>
+ <td>X86 test outputs</td>
+ </tr>
+ </table>
+</blockquote>
+
+<p><code>doc/install.html</code> is the HTML file for this document. <a HREF="4.html"><code>doc/4.html</code></a>
+describes the internal differences between lcc 3.x and 4.1.</p>
+
+<p>The installation makefile is designed so that lcc can be installed from a read-only
+file system or directory, which is common in networked environments, so the distribution
+can be unloaded on a central file server. <strong>You will need an existing ANSI/ISO C
+compiler to build and install lcc.</strong></p>
+
+<h2><a NAME="unix">Installation on UNIX</a></h2>
+
+<p>The compilation components (the preprocessor, include files, and compiler proper, etc.)
+are installed in a single <em>build directory</em>. On multi-platform systems supported by
+a central file server, it's common to store the build directory in a location specific to
+the platform and to the version of lcc, and to point a symbolic link to this location. For
+example,</p>
+
+<blockquote>
+ <pre>% ln -s /usr/local/lib/lcc-4.1/sparc-solaris /usr/local/lib/lcc</pre>
+</blockquote>
+
+<p>points <code>/usr/local/lib/lcc</code> to a build directory for lcc version 4.1 on the
+SPARC under Solaris. Links into <code>/usr/local/lib</code> are created for the programs <code>lcc</code>
+and <code>bprint</code>. Thus, a new distribution can be installed by building it in its
+own build directory and changing one symbolic link to point to that directory. If these
+conventions or their equivalents are followed, the host-specific parts of the driver
+program, <code>lcc</code>, can be used unmodified.</p>
+
+<p>Installation on a UNIX system involves the following steps. Below, the build directory
+is referred to as <code>BUILDDIR</code>.
+
+<ol>
+ <li>Create the build directory, using a version- and platform-specific naming convention as
+ suggested above, and record the name of this directory in the <code>BUILDDIR</code>
+ environment variable:<blockquote>
+ <pre>% setenv BUILDDIR /usr/local/lib/lcc-4.1/sparc-solaris
+% mkdir -p $BUILDDIR</pre>
+ </blockquote>
+ <p>Here and below, commands assume the C shell. Also, you'll need a version of <code>mkdir</code>
+ that supports the <code>-p</code> option, which creates intermediate directories as
+ necessary.</p>
+ </li>
+ <li>Copy the man pages to the repository for local man pages, e.g.,<blockquote>
+ <pre>% cp doc/*.1 /usr/local/man/man1</pre>
+ </blockquote>
+ <p>Some users copy the man pages to the build directory and create the appropriate
+ symbolic links, e.g., </p>
+ <blockquote>
+ <pre>% cp doc/*.1 $BUILDDIR
+% ln -s $BUILDDIR/*.1 /usr/local/man/man1</pre>
+ </blockquote>
+ </li>
+ <li>Platform-specific include files are in directories named <code>include/</code><em>target</em><code>/</code><em>os</em>.
+ Create the include directory in the build directory, and copy the include hierarchy for
+ your platform to this directory, e.g.,<blockquote>
+ <pre>% mkdir $BUILDDIR/include
+% cp -p -R include/sparc/solaris/* $BUILDDIR/include</pre>
+ </blockquote>
+ <p>Again, some users create a symbolic link to the appropriate directory in the
+ distribution instead of copying the include files. For example, at Princeton, the
+ distributions are stored under <code>/proj/pkg/lcc</code>, so the included files are
+ &quot;installed&quot; by creating one symbolic link: </p>
+ <blockquote>
+ <pre>% ln -s /proj/pkg/lcc/4.1/include/sparc/solaris $BUILDDIR/include</pre>
+ </blockquote>
+ <p>If you're installing lcc on Linux, you <em>must</em> also plant a symbolic link named <code>gcc</code>
+ to gcc's library directory, because lcc uses gcc's C preprocessor and most of gcc's header
+ files:</p>
+ <blockquote>
+ <pre>% ln -s /usr/lib/gcc-lib/i486-linux/2.7.2.2 $BUILDDIR/gcc</pre>
+ </blockquote>
+ <p>The library directory shown above may be different on your Linux machine; to determine
+ the correct directory, browse <code>/usr/lib/gcc-lib</code>, or execute</p>
+ <blockquote>
+ <pre>% cc -v tst/8q.c</pre>
+ </blockquote>
+ <p>and examine the diagnostic output. Make sure that <code>$BUILDDIR/gcc/cpp</code> and <code>$BUILDDIR/gcc/include</code>
+ point to, respectively, gcc's C preprocessor and header files. On Linux, lcc looks for
+ include files in <code>$BUILDDIR/include</code>, <code>$BUILDDIR/gcc/include</code>, and <code>/usr/include</code>,
+ in that order; see <a HREF="#driver"><em>Building the Driver</em></a> and <a
+ href="../etc/linux.c"><code>etc/linux.c</code></a> for details.</p>
+ </li>
+ <li>The <a HREF="../makefile"><code>makefile</code></a> includes the file named by the <code>CUSTOM</code>
+ macro; the default is <code>custom.mk</code>, and an empty <code>custom.mk</code> is
+ included in the distribution. If desired, prepare a site-specification customization file
+ and define <code>CUSTOM</code> to the path of that file when invoking make in steps 5 and
+ 6, e.g.,<blockquote>
+ <pre>make CUSTOM=/users/drh/solaris.mk</pre>
+ </blockquote>
+ <p>You can, for example, use customization files to record site-specific values for macros
+ instead of using environment variables, and to record targets for the steps in this list.</p>
+ </li>
+ <li>Build the host-specific driver, creating a custom host-specific part, if necessary. See <a
+ HREF="#driver"><em>Building the Driver</em></a>.</li>
+ <li>Build the preprocessor, compiler proper, library, and other accessories. See <a
+ HREF="#rcc"><em>Building the Compiler</em></a>.</li>
+ <li>Plant symbolic links to the build directory and to the installed programs, e.g.,<blockquote>
+ <pre>% ln -s $BUILDDIR /usr/local/lib/lcc
+% ln -s /usr/local/lib/{lcc,bprint} /usr/local/bin</pre>
+ </blockquote>
+ <p>Some users copy <code>bprint</code> and <code>lcc</code> into <code>/usr/local/bin</code>
+ instead of creating symbolic links. The advantange of creating the links for <code>lcc</code>
+ and <code>bprint</code> as shown is that, once established, they point indirectly to
+ whatever <code>/usr/local/lib/lcc</code> points to; installing a new version of lcc, say,
+ 4.2, can be done by changing <code>/usr/local/lib/lcc</code> to point to the 4.2 build
+ directory.</p>
+ </li>
+</ol>
+
+<h2><a NAME="driver">Building the Driver</a></h2>
+
+<p>The preprocessor, compiler, assembler, and loader are invoked by a driver program, <code>lcc</code>,
+which is similar to <code>cc</code> on most systems. It's described in the man page <code>doc/lcc.1</code>.
+The driver is built by combining the host-independent part, <a href="../etc/lcc.c"><code>etc/lcc.c</code></a>,
+with a small host-specific part. Distributed host-specific parts are named <code>etc/</code><em>os</em><code>.c</code>,
+where <em>os</em> is the name of the operating system for the host on which <code>lcc</code>
+is being installed. If you're following the installations conventions described above, you
+can probably use one of the host-specific parts unmodified; otherwise, pick one that is
+closely related to your platform, copy it to <em>whatever</em><code>.c</code>, and edit it
+as described below. You should not have to edit <code>etc/lcc.c</code>.</p>
+
+<p>We'll use <a HREF="../etc/solaris.c"><code>etc/solaris.c</code></a> as an example in
+describing how the host-specific part works. This example illustrates all the important
+features. Make sure you have the environment variable <code>BUILDDIR</code> set correctly,
+and build the driver with a <code>make</code> command, e.g.,</p>
+
+<blockquote>
+ <pre>% make HOSTFILE=etc/solaris.c lcc
+cc -g -c -DTEMPDIR=\&quot;/tmp\&quot; -o /usr/local/lib/lcc-4.1/sparc-solaris/lcc.o etc/lcc.c
+cc -g -c -o /usr/local/lib/lcc-4.1/sparc-solaris/host.o etc/solaris.c
+cc -g -o /usr/local/lib/lcc-4.1/sparc-solaris/lcc /usr/local/lib/lcc-4.1/sparc-solaris/lcc.o /usr/local/lib/lcc-4.1/sparc-solaris/host.o</pre>
+</blockquote>
+
+<p>The symbolic name <code>HOSTFILE</code> specifies the path to the host-specific part,
+either one in the distribution or <em>whatever</em><code>.c</code>. Some versions of make
+may require the <code>-e</code> option in order to read the environment.</p>
+
+<p>Here's <code>etc/solaris.c</code>:</p>
+
+<blockquote>
+ <pre>/* Sparcs running Solaris 2.5.1 at CS Dept., Princeton University */
+
+#include &lt;string.h&gt;
+
+static char rcsid[] = &quot;$ Id: solaris.c,v 1.10 1998/09/14 20:36:33 drh Exp $&quot;;
+
+#ifndef LCCDIR
+#define LCCDIR &quot;/usr/local/lib/lcc/&quot;
+#endif
+#ifndef SUNDIR
+#define SUNDIR &quot;/opt/SUNWspro/SC4.2/lib/&quot;
+#endif
+
+char *suffixes[] = { &quot;.c&quot;, &quot;.i&quot;, &quot;.s&quot;, &quot;.o&quot;, &quot;.out&quot;, 0 };
+char inputs[256] = &quot;&quot;;
+char *cpp[] = { LCCDIR &quot;cpp&quot;,
+ &quot;-D__STDC__=1&quot;, &quot;-Dsparc&quot;, &quot;-D__sparc__&quot;, &quot;-Dsun&quot;, &quot;-D__sun__&quot;, &quot;-Dunix&quot;,
+ &quot;$1&quot;, &quot;$2&quot;, &quot;$3&quot;, 0 };
+char *include[] = { &quot;-I&quot; LCCDIR &quot;include&quot;, &quot;-I/usr/local/include&quot;,
+ &quot;-I/usr/include&quot;, 0 };
+char *com[] = { LCCDIR &quot;rcc&quot;, &quot;-target=sparc/solaris&quot;,
+ &quot;$1&quot;, &quot;$2&quot;, &quot;$3&quot;, 0 };
+char *as[] = { &quot;/usr/ccs/bin/as&quot;, &quot;-Qy&quot;, &quot;-s&quot;, &quot;-o&quot;, &quot;$3&quot;, &quot;$1&quot;, &quot;$2&quot;, 0 };
+char *ld[] = { &quot;/usr/ccs/bin/ld&quot;, &quot;-o&quot;, &quot;$3&quot;, &quot;$1&quot;,
+ SUNDIR &quot;crti.o&quot;, SUNDIR &quot;crt1.o&quot;,
+ SUNDIR &quot;values-xa.o&quot;, &quot;$2&quot;, &quot;&quot;,
+ &quot;-Y&quot;, &quot;P,&quot; SUNDIR &quot;:/usr/ccs/lib:/usr/lib&quot;, &quot;-Qy&quot;,
+ &quot;-L&quot; LCCDIR, &quot;-llcc&quot;, &quot;-lm&quot;, &quot;-lc&quot;, SUNDIR &quot;crtn.o&quot;, 0 };
+
+extern char *concat(char *, char *);
+
+int option(char *arg) {
+ if (strncmp(arg, &quot;-lccdir=&quot;, 8) == 0) {
+ cpp[0] = concat(&amp;arg[8], &quot;/cpp&quot;);
+ include[0] = concat(&quot;-I&quot;, concat(&amp;arg[8], &quot;/include&quot;));
+ ld[12] = concat(&quot;-L&quot;, &amp;arg[8]);
+ com[0] = concat(&amp;arg[8], &quot;/rcc&quot;);
+ } else if (strcmp(arg, &quot;-p&quot;) == 0) {
+ ld[5] = SUNDIR &quot;mcrt1.o&quot;;
+ ld[10] = &quot;P,&quot; SUNDIR &quot;libp:/usr/ccs/lib/libp:/usr/lib/libp:&quot;
+ SUNDIR &quot;:/usr/ccs/lib:/usr/lib&quot;;
+ } else if (strcmp(arg, &quot;-b&quot;) == 0)
+ ;
+ else if (strncmp(arg, &quot;-ld=&quot;, 4) == 0)
+ ld[0] = &amp;arg[4];
+ else
+ return 0;
+ return 1;
+}</pre>
+</blockquote>
+
+<p><code>LCCDIR</code> defaults to <code>&quot;/usr/local/lib/lcc/&quot;</code> unless
+it's defined by a <code>-D</code> option as part of <code>CFLAGS</code> in the make
+command, e.g.,</p>
+
+<blockquote>
+ <pre>% make HOSTFILE=etc/solaris.c CFLAGS='-DLCCDIR=\&quot;/v/lib/lcc/\&quot;' lcc</pre>
+</blockquote>
+
+<p>Note the trailing slash; <code>SUNDIR</code> is provided so you can use <code>etc/solaris.c</code>
+even if you have a different version of the Sun Pro compiler suite. If you're using the
+gcc compiler tools instead of the Sun Pro tools, see <a HREF="../etc/gcc-solaris.c"><code>etc/gcc-solaris.c</code></a>.</p>
+
+<p>Most of the host-specific code is platform-specific data and templates for the commands
+that invoke the preprocessor, compiler, assembler, and loader. The <code>suffixes</code>
+array lists the file name suffixes for C source files, preprocessed source files, assembly
+language source files, object files, and executable files. <code>suffixes</code> must be
+terminated with a null pointer, as shown above. The initialization of <code>suffixes</code>
+in <code><a HREF="../etc/solaris.c">etc/solaris.c</a></code> are the typical ones for UNIX
+systems. Each element of <code>suffixes</code> is actually a list of suffixes, separated
+by semicolons; <code><a HREF="../etc/win32.c">etc/win32.c</a></code> holds an example:</p>
+
+<blockquote>
+ <pre>char *suffixes[] = { &quot;.c;.C&quot;, &quot;.i;.I&quot;, &quot;.asm;.ASM;.s;.S&quot;, &quot;.obj;.OBJ&quot;, &quot;.exe&quot;, 0 };</pre>
+</blockquote>
+
+<p>When a list is given, the first suffix is used whenever lcc needs to generate a file
+name. For example, with <code><a HREF="../etc/win32.c">etc/win32.c</a></code>, lcc emits
+the generated assembly code into <code>.asm</code> files.</p>
+
+<p>The <code>inputs</code> array holds a null-terminated string of directories separated
+by colons or semicolons. These are used as the default value of <code>LCCINPUTS</code>, if
+the environment variable <code>LCCINPUTS</code> is not set; see the <a HREF="lcc.pdf">man
+page</a>.</p>
+
+<p>Each command template is an array of pointers to strings terminated with a null
+pointer; the strings are full path names of commands, arguments, or argument placeholders,
+which are described below. Commands are executed in a child process, and templates can
+contain multiple commands by separating commands with newlines. The driver runs each
+command in a new process.</p>
+
+<p>The <code>cpp</code> array gives the command for running lcc's preprocessor, <code>cpp</code>.
+Literal arguments specified in templates, e.g., <code>&quot;-Dsparc&quot;</code> in the <code>cpp</code>
+command above, are passed to the command as given.</p>
+
+<p>The strings <code>&quot;$1&quot;</code>, <code>&quot;$2&quot;</code>, and <code>&quot;$3&quot;</code>
+in templates are placeholders for <em>lists</em> of arguments that are substituted in a
+copy of the template before the command is executed. <code>$1</code> is replaced by the <em>options</em>
+specified by the user; for the preprocessor, this list always contains at least <code>-D__LCC__</code>.
+<code>$2</code> is replaced by the <em>input</em> files, and <code>$3</code> is replaced
+by the <em>output</em> file.</p>
+
+<p>Zero-length arguments after replacement are removed from the argument list before the
+command is invoked. So, for example, if the preprocessor is invoked without an output
+file, <code>&quot;$3&quot;</code> becomes <code>&quot;&quot;</code>, which is removed from
+the final argument list.</p>
+
+<p>The <code>include</code> array is a list of <code>-I</code> options that specify which
+directives should be searched to satisfy include directives. These directories are
+searched in the order given. The first directory should be the one to which the ANSI
+header files were copied as described in <a HREF="#unix">UNIX</a> or <a HREF="#win32">Windows</a>
+installation instructions. The driver adds these options to <code>cpp</code>'s arguments
+when it invokes the preprocessor, except when <code>-N</code> is specified.</p>
+
+<p><code>com</code> gives the command for invoking the compiler. This template can appear
+as shown above in a custom host-specific part, but the option <code>-target=sparc/solaris</code>
+should be edited to the <em>target</em><code>/</code><em>os</em> for your platform. If <code>com[1]</code>
+includes the string &quot;<code>win32</code>&quot;, the driver assumes it's running on
+Windows. lcc can generate code for <em>all</em> of the <em>target</em><code>/</code><em>os</em>
+combinations listed in the file <code>src/bind.c</code>. The <code>-target</code> option
+specifies the default combination. The driver's <code>-Wf</code> option can be used to
+specify other combinations; the <a HREF="lcc.pdf">man page</a> elaborates.</p>
+
+<p><code>as</code> gives the command for invoking the assembler. On Linux, you must be
+running at least version 2.8.1 of the GNU assembler; earlier versions mis-assemble some
+instructions emitted by lcc.</p>
+
+<p><code>ld</code> gives the command for invoking the loader. For the other commands, the
+list <code>$2</code> contains a single file; for <code>ld</code>, <code>$2</code> contains
+all &quot;.o&quot; files and libraries, and <code>$3</code> is <code>a.out</code>, unless
+the <code>-o</code> option is specified. As suggested in the code above, <code>ld</code>
+must also specify the appropriate startup code and default libraries, including the lcc
+library, <code>liblcc.a</code>.</p>
+
+<p>The <code>option</code> function is described below; the minimal <code>option</code>
+function just returns 0.</p>
+
+<p>You can test <code>lcc</code> with the options <code>-v -v</code> to display the
+commands that would be executed, e.g.,</p>
+
+<blockquote>
+ <pre>% $BUILDDIR/lcc -v -v foo.c baz.c mylib.a -lX11
+/usr/local/lib/lcc-4.1/lcc $ Id: solaris.c,v 1.10 1998/09/14 20:36:33 drh Exp $
+foo.c:
+/usr/local/lib/lcc/cpp -D__STDC__=1 -Dsparc -D__sparc__ -Dsun -D__sun__ -Dunix -D__LCC__ -I/usr/local/lib/lcc/include -I/usr/local/include -I/usr/include foo.c /tmp/lcc266290.i
+/usr/local/lib/lcc/rcc -target=sparc/solaris -v /tmp/lcc266290.i /tmp/lcc266291.
+s
+/usr/ccs/bin/as -Qy -s -o /tmp/lcc266292.o /tmp/lcc266291.s
+baz.c:
+/usr/local/lib/lcc/cpp -D__STDC__=1 -Dsparc -D__sparc__ -Dsun -D__sun__ -Dunix -D__LCC__ -I/usr/local/lib/lcc/include -I/usr/local/include -I/usr/include baz.c /tmp/lcc266290.i
+/usr/local/lib/lcc/rcc -target=sparc/solaris -v /tmp/lcc266290.i /tmp/lcc266291.s
+/usr/ccs/bin/as -Qy -s -o /tmp/lcc266293.o /tmp/lcc266291.s
+/usr/ccs/bin/ld -o a.out /opt/SUNWspro/SC4.2/lib/crti.o /opt/SUNWspro/SC4.2/lib/crt1.o /opt/SUNWspro/SC4.2/lib/values-xa.o /tmp/lcc266292.o /tmp/lcc266293.o mylib.a -lX11 -Y P,/opt/SUNWspro/SC4.2/lib/:/usr/ccs/lib:/usr/lib -Qy -L/usr/local/lib/lcc/ -llcc -lm -lc /opt/SUNWspro/SC4.2/lib/crtn.o
+rm /tmp/lcc266293.o /tmp/lcc266290.i /tmp/lcc266291.s /tmp/lcc266292.o</pre>
+</blockquote>
+
+<p>As the output shows, <code>lcc</code> places temporary files in <code>/tmp</code>; if
+any of the environment variables <code>TMP</code>, <code>TEMP</code>, and <code>TMPDIR</code>
+are set, they override this default (in the order shown) as does the <code>-tempdir=</code><em>dir</em>
+option. The default can be changed by defining <code>TEMPDIR</code> in <code>CFLAGS</code>
+when building the driver.</p>
+
+<p>The <code>option</code> function is called for the options <code>-Wo</code>, <code>-g</code>,
+<code>-p</code>, <code>-pg</code>, and <code>-b</code> because these compiler options
+might also affect the loader's arguments. For these options, the driver calls <code>option(arg)</code>
+to give the host-specific code an opportunity to edit the <code>ld</code> command, if
+necessary. <code>option</code> can change <code>ld</code>, if necessary, and return 1 to
+announce its acceptance of the option. If the option is unsupported, <code>option</code>
+should return 0.</p>
+
+<p>For example, in response to <code>-g</code>, the <code>option</code> function shown
+above accepts the option but does nothing else, because the <code>ld</code> and <code>as</code>
+commands don't need to be modified on the SPARC. <code>-g</code> will also be added to the
+compiler's options by the host-independent part of the driver. The <code>-p</code> causes <code>option</code>
+to change the name of the startup code and changed the list of libraries. The <code>-b</code>
+option turns on <code>lcc</code>'s per-expression profiling, the code for which is in <code>liblcc.a</code>,
+so <code>option</code> need no nothing.</p>
+
+<p>On SPARCs, the driver also recognizes <code>-Bstatic</code> and <code>-Bdynamic</code>
+as linker options. The driver recognizes but ignores &quot;<code>-target</code> <em>name</em>&quot;
+option.</p>
+
+<p>The option <code>-Wo</code><em>arg</em> causes the driver to pass <em>arg</em> to <code>option</code>.
+Such options have no other effect; this mechanism is provided to support system-specific
+options that affect the commands executed by the driver. As illustrated above,
+host-specific parts should support the <code>-Wo-lccdir=</code><em>dir</em> option, which
+causes lcc's compilation components to be found in <em>dir</em>, because this option is
+used by the test scripts, and because the driver simulates a <code>-Wo-lccdir</code>
+option with the value of the environment variable <code>LCCDIR</code>, if it's defined.
+The code above rebuilds the paths to the include files, preprocessor, compiler, and
+library by calling <code>concat</code>, which is defined in <code>etc/lcc.c</code>.</p>
+
+<h2><a NAME="rcc">Building the Compiler and Accessories</a></h2>
+
+<p>To build the rest of compilation components make sure <code>BUILDDIR</code> is set
+appropriately and type &quot;<code>make all</code>&quot;. This command builds <code>librcc.a</code>
+(the compiler's private library), <code>rcc</code> (the compiler proper), <code>lburg</code>
+(the code-generator generator), <code>cpp</code> (the preprocessor), <code>liblcc.a</code>
+(the runtime library), and <code>bprint</code> (the profile printer), all in <code>BUILDDIR</code>.
+There may be warnings, but there should be no errors. If you're using an ANSI/ISO compiler
+other than <code>cc</code>, specify its name with the <code>CC=</code> option, e.g.,
+&quot;<code>make CC=gcc all</code>&quot;. If you're running on a DEC ALPHA, use &quot;<code>make
+CC='cc -std1' all</code>&quot;; the <code>-std1</code> option is essential on the ALPHA.
+If you're on a DEC 5000 running Ultrix 4.3, use &quot;<code>make CC=c89 all</code>&quot;.</p>
+
+<p>Once <code>rcc</code> is built with the host C compiler, run the test suite to verify
+that <code>rcc</code> is working correctly. If any of the steps below fail, contact us
+(see <a HREF="#bugs"><em>Reporting Bugs</em></a>). The commands in the makefile run the
+shell script <code>src/run.sh</code> on each C program in the test suite, <code>tst/*.c</code>.
+It uses the driver, <code>$BUILDDIR/lcc</code>, so you must have the driver in the build
+directory before testing <code>rcc</code>. The <em>target</em><code>/</code><em>os</em>
+combination is read from the variable <code>TARGET</code>, which must be specified when
+invoking <code>make</code>:</p>
+
+<blockquote>
+ <pre>% make TARGET=sparc/solaris test
+mkdir -p /usr/local/lib/lcc-4.1/sparc-solaris/sparc/solaris/tst
+/usr/local/lib/lcc-4.1/sparc-solaris/rcc -target=sparc/solaris /usr/local/lib/lcc-4.1/sparc-solaris/sparc/solaris/tst/8q.s:
+/usr/local/lib/lcc-4.1/sparc-solaris/rcc -target=sparc/solaris /usr/local/lib/lcc-4.1/sparc-solaris/sparc/solaris/tst/array.s:
+/usr/local/lib/lcc-4.1/sparc-solaris/rcc -target=sparc/solaris /usr/local/lib/lcc-4.1/sparc-solaris/sparc/solaris/tst/cf.s:
+/usr/local/lib/lcc-4.1/sparc-solaris/rcc -target=sparc/solaris /usr/local/lib/lcc-4.1/sparc-solaris/sparc/solaris/tst/cq.s:
+/usr/local/lib/lcc-4.1/sparc-solaris/rcc -target=sparc/solaris /usr/local/lib/lcc-4.1/sparc-solaris/sparc/solaris/tst/cvt.s:
+/usr/local/lib/lcc-4.1/sparc-solaris/rcc -target=sparc/solaris /usr/local/lib/lcc-4.1/sparc-solaris/sparc/solaris/tst/fields.s:
+/usr/local/lib/lcc-4.1/sparc-solaris/rcc -target=sparc/solaris /usr/local/lib/lcc-4.1/sparc-solaris/sparc/solaris/tst/front.s:
+/usr/local/lib/lcc-4.1/sparc-solaris/rcc -target=sparc/solaris /usr/local/lib/lcc-4.1/sparc-solaris/sparc/solaris/tst/incr.s:
+/usr/local/lib/lcc-4.1/sparc-solaris/rcc -target=sparc/solaris /usr/local/lib/lcc-4.1/sparc-solaris/sparc/solaris/tst/init.s:
+/usr/local/lib/lcc-4.1/sparc-solaris/rcc -target=sparc/solaris /usr/local/lib/lcc-4.1/sparc-solaris/sparc/solaris/tst/limits.s:
+/usr/local/lib/lcc-4.1/sparc-solaris/rcc -target=sparc/solaris /usr/local/lib/lcc-4.1/sparc-solaris/sparc/solaris/tst/paranoia.s:
+/usr/local/lib/lcc-4.1/sparc-solaris/rcc -target=sparc/solaris /usr/local/lib/lcc-4.1/sparc-solaris/sparc/solaris/tst/sort.s:
+/usr/local/lib/lcc-4.1/sparc-solaris/rcc -target=sparc/solaris /usr/local/lib/lcc-4.1/sparc-solaris/sparc/solaris/tst/spill.s:
+/usr/local/lib/lcc-4.1/sparc-solaris/rcc -target=sparc/solaris /usr/local/lib/lcc-4.1/sparc-solaris/sparc/solaris/tst/stdarg.s:
+/usr/local/lib/lcc-4.1/sparc-solaris/rcc -target=sparc/solaris /usr/local/lib/lcc-4.1/sparc-solaris/sparc/solaris/tst/struct.s:
+/usr/local/lib/lcc-4.1/sparc-solaris/rcc -target=sparc/solaris /usr/local/lib/lcc-4.1/sparc-solaris/sparc/solaris/tst/switch.s:
+/usr/local/lib/lcc-4.1/sparc-solaris/rcc -target=sparc/solaris /usr/local/lib/lcc-4.1/sparc-solaris/sparc/solaris/tst/wf1.s:
+/usr/local/lib/lcc-4.1/sparc-solaris/rcc -target=sparc/solaris /usr/local/lib/lcc-4.1/sparc-solaris/sparc/solaris/tst/yacc.s:</pre>
+</blockquote>
+
+<p>Each line in the output above is of the form</p>
+
+<blockquote>
+ <p><code>$BUILDDIR/rcc -target=</code><em>target</em><code>/</code><em>os</em><code>$BUILDDIR/</code><em>target</em><code>/</code><em>os</em><code>/</code><em>X</em><code>.s:</code></p>
+</blockquote>
+
+<p>where <em>X</em> is the base name of the C program <em>X</em><code>.c</code> in the
+test suite. This output identifies the compiler and the target, e.g., &quot;<code>$BUILDDIR/rcc</code>
+is generating code for a <code>sparc</code> running the <code>solaris</code> operating
+system.&quot;</p>
+
+<p>For each program in the test suite, <code>src/run.sh</code> compiles the program, drops
+the generated assembly language code in <code>BUILDDIR</code>/<em>target</em><code>/</code><em>os</em>,
+and uses <code>diff</code> to compare the generated assembly code with the expected code
+(the code expected for <code>tst/8q.c</code> on the SPARC under Solaris is in <code>sparc/solaris/tst/8q.sbk</code>,
+etc.). If there are differences, the script executes the generated code with the input
+given in <code>tst</code> (the input for <code>tst/8q.c</code> is in <code>tst/8q.0</code>,
+etc.) and compares the output with the expected output (the expected output from <code>tst/8q.c</code>
+on the SPARC under Solaris is in <code>sparc/solaris/tst/8q.1bk</code>, etc.). The script
+also compares the diagnostics from the compiler with the expected diagnostics.</p>
+
+<p>On some systems, there may be a few differences between the generated code and the
+expected code. These differences occur because the expected code is generated by cross
+compilation and the least significant bits of some floating-point constants differ from
+those bits in constants generated on your system. On Linux, there may be differences
+because of differences in the header files between our system and yours. There should be
+no differences in the output from executing the test programs.</p>
+
+<p>Next, run the &quot;triple test&quot;, which builds <code>rcc</code> using itself:</p>
+
+<blockquote>
+ <pre>% make triple
+/usr/local/lib/lcc-4.1/sparc-solaris/lcc -o /usr/local/lib/lcc-4.1/sparc-solaris/1rcc -d0.6 -Wo-lccdir=/usr/local/lib/lcc-4.1/sparc-solaris -B/usr/local/lib/lcc-4.1/sparc-solaris/ -Isrc src/*.c
+src/alloc.c:
+...
+src/x86.c:
+/usr/local/lib/lcc-4.1/sparc-solaris/lcc -o /usr/local/lib/lcc-4.1/sparc-solaris/1rcc -d0.6 -Wo-lccdir=/usr/local/lib/lcc-4.1/sparc-solaris -B/usr/local/lib/lcc-4.1/sparc-solaris/ -Isrc src/*.c
+src/alloc.c:
+...
+src/x86.c:
+strip /usr/local/lib/lcc-4.1/sparc-solaris/[12]rcc
+dd if=/usr/local/lib/lcc-4.1/sparc-solaris/1rcc of=/usr/local/lib/lcc-4.1/sparc-solaris/rcc1 bs=512 skip=1
+769+1 records in
+769+1 records out
+dd if=/usr/local/lib/lcc-4.1/sparc-solaris/2rcc of=/usr/local/lib/lcc-4.1/sparc-solaris/rcc2 bs=512 skip=1
+769+1 records in
+769+1 records out
+if cmp /usr/local/lib/lcc-4.1/sparc-solaris/rcc[12]; then \
+ mv /usr/local/lib/lcc-4.1/sparc-solaris/2rcc /usr/local/lib/lcc-4.1/sparc-solaris/rcc; \
+ rm -f /usr/local/lib/lcc-4.1/sparc-solaris/1rcc /usr/local/lib/lcc-4.1/sparc-solaris/rcc[12]; fi</pre>
+</blockquote>
+
+<p>This command builds <code>rcc</code> twice; once using the <code>rcc</code> built by <code>cc</code>
+and again using the <code>rcc</code> built by <code>lcc</code>. The resulting binaries are
+compared. They should be identical, as shown at the end of the output above. If they
+aren't, our compiler is generating incorrect code; <a HREF="#bugs">contact</a> us.</p>
+
+<p>The final version of <code>rcc</code> should also pass the test suite; that is, the
+output from</p>
+
+<blockquote>
+ <pre>% make TARGET=sparc/solaris test</pre>
+</blockquote>
+
+<p>should be identical to that from the previous <code>make test</code>.</p>
+
+<p>The command &quot;<code>make clean</code>&quot; cleans up, but does not remove <code>rcc</code>,
+etc., and &quot;<code>make clobber</code>&quot; cleans up and removes <code>lcc</code>, <code>rcc</code>,
+and the other accessories. Test directories under <code>BUILDDIR</code> are <em>not</em>
+removed; you'll need to remove these by hand, e.g.,</p>
+
+<blockquote>
+ <pre>% rm -fr $BUILDDIR/sparc</pre>
+</blockquote>
+
+<p>The code generators for the other targets can be tested by specifying the desired <em>target</em><code>/</code><em>os</em>
+and setting an environment variable that controls what <code>src/run.sh</code> does. For
+example, to test the MIPS code generator, type</p>
+
+<blockquote>
+ <pre>% setenv REMOTEHOST noexecute
+% make TARGET=mips/irix test</pre>
+</blockquote>
+
+<p>As above, <code>src/run.sh</code> compares the MIPS code generated with what's
+expected. There should be no differences. Setting <code>REMOTEHOST</code> to <code>noexecute</code>
+suppresses the assembly and execution of the generated code. If you set <code>REMOTEHOST</code>
+to the name of a MIPS machine to which you can <code>rlogin</code>, <code>src/run.sh</code>
+will <code>rcp</code> the generated code to that machine and execute it there, if
+necessary. See <code>src/run.sh</code> for the details.</p>
+
+<p>You can use lcc as a cross compiler. The options <code>-S</code> and <code>-Wf-target=</code><em>target/os</em>
+generate assembly code for the specified target, which is any of those listed in the file <code>src/bind.c</code>.
+For example, </p>
+
+<blockquote>
+ <pre>% lcc -Wf-target=mips/irix -S tst/8q.c</pre>
+</blockquote>
+
+<p>generates MIPS code for <code>tst/8q.c</code> in <code>8q.s</code>.</p>
+
+<p>lcc can also generate code for a &quot;symbolic&quot; target. This target is used
+routinely in front-end development, and its output is a printable representation of the
+input program, e.g., the dags constructed by the front end are printed, and other
+interface functions print their arguments. You can specify this target with the option <code>-Wf-target=symbolic</code>.
+For example,</p>
+
+<blockquote>
+ <pre>% lcc -Wf-target=symbolic -S tst/8q.c</pre>
+</blockquote>
+
+<p>generates symbolic output for <code>tst/8q.c</code> in <code>8q.s</code>. Adding <code>-Wf-html</code>
+causes the symbolic target to emit HTML instead of plain text. Finally, the option <code>-Wf-target=null</code>
+specifies the &quot;null&quot; target for which lcc emits nothing and thus only checks the
+syntax and semantics of its input files.</p>
+
+<h2><a NAME="win32">Installation on Windows NT 4.0 or Windows 95/98</a></h2>
+
+<p>On Windows NT 4.0 and Windows 95/98, lcc is designed to work with Microsoft's Visual
+C++ 5.0 (VC) and Microsoft's Assembler, MASM 6.11d. It uses the VC header files,
+libraries, and command-line tools, and it uses MASM to assemble the code it generates. If
+you have MASM 6.11, make sure you <a
+HREF="http://support.microsoft.com/support/kb/articles/Q138/9/83.asp">upgrade to 6.11d</a>,
+because earlier 6.11 releases do not generate correct COFF object files.</p>
+
+<p>Building the distribution components from the ground up requires Microsoft's Visual
+C/C++ 5.0 compiler, Microsoft's make, <code>nmake</code>, and the standard Windows command
+interpreter. <a HREF="../makefile.nt"><code>makefile.nt</code></a> is written to use only <code>nmake</code>.
+As on UNIX systems, the compilation components are installed in a single <em>build
+directory</em>, and the top-level programs, <code>lcc.exe</code> and <code>bprint.exe</code>,
+are installed in a directory on the PATH. If the conventions used below are followed, the
+Windows-specific parts of the driver program, <code>lcc.exe</code>, can be used
+unmodified.</p>
+
+<p>Building from the source distribution on a Windows system involves the following steps.
+Below, the build directory is referred to as <code>BUILDDIR</code>, and the distribution
+is in <code>\dist\lcc\4.1</code>.
+
+<ol>
+ <li>Create the build directory, perhaps using a version- and platform-specific naming
+ convention as suggested in <a HREF="#unix"><em>Installation on UNIX</em></a>, and record
+ the name of this directory in the <code>BUILDDIR</code> environment variable:<blockquote>
+ <pre>C:\dist\lcc\4.1&gt;set BUILDDIR=\progra~1\lcc\4.1\bin
+C:\dist\lcc\4.1&gt;mkdir %BUILDDIR%</pre>
+ </blockquote>
+ <p>The default build, or installation, directory is <code>\Program Files\lcc\4.1\bin</code>,
+ but the <code>nmake</code> commands require that you use the corresponding 8.3 file name, <code>progra~1</code>,
+ instead of <code>Program Files</code>.</p>
+ </li>
+ <li><a HREF="../etc/win32.c"><code>etc\win32.c</code></a> is the Windows-specific part of
+ the driver. It assumes that environment variable <code>include</code> gives the locations
+ of the VC header files and that the linker (<code>link.exe</code>) and the assembler (<code>ml.exe</code>)
+ are on the PATH. It also assumes that the macro <code>LCCDIR</code> gives the build
+ directory. If necessary, revise a copy of <a HREF="../etc/win32.c"><code>etc\win32.c</code></a>
+ to reflect the conventions on your computer (see <a HREF="#driver"><em>Building the Driver</em></a>),
+ then build the driver, specifying the default temporary directory, if necessary:<blockquote>
+ <pre>C:\dist\lcc\4.1&gt;nmake -f makefile.nt TEMPDIR=\\temp HOSTFILE=etc/win32.c lcc
+...
+ cl -nologo -Zi -MLd -Fd\progra~1\lcc\4.1\bin\ -c -DTEMPDIR=\&quot;\\temp\&quot; -Fo\progra~1\lcc\4.1\bin\lcc.obj etc/lcc.c
+lcc.c
+ cl -nologo -Zi -MLd -Fd\progra~1\lcc\4.1\bin\ -c -Fo\progra~1\lcc\4.1\bin\host.obj etc/win32.c
+win32.c
+ cl -nologo -Zi -MLd -Fd\progra~1\lcc\4.1\bin\ -Fe\progra~1\lcc\4.1\bin\lcc.exe \progra~1\lcc\4.1\bin\lcc.obj \progra~1\lcc\4.1\bin\host.obj</pre>
+ </blockquote>
+ <p>If you make a copy of <code>etc\win32.c</code>, specify the path of the copy as the
+ value of <code>HOSTFILE</code>. For example, if you copy <code>etc\win32.c</code> to <code>BUILDDIR</code>
+ and edit it, use the command</p>
+ <blockquote>
+ <pre>C:\dist\lcc\4.1&gt;nmake -f makefile.nt TEMPDIR=\\temp HOSTFILE=%BUILDDIR%\win32.c lcc</pre>
+ </blockquote>
+ </li>
+ <li>Build the preprocessor, compiler proper, library, and other accessories (see <a
+ HREF="#rcc"><em>Building the Compiler</em></a>):<blockquote>
+ <pre>C:\dist\lcc\4.1&gt;nmake -f makefile.nt all</pre>
+ </blockquote>
+ <p>This command uses the VC command-line tools <code>cl</code> and <code>lib</code> to
+ build <code>bprint.exe</code>, <code>cpp.exe</code>, <code>lburg.exe</code>, <code>liblcc.lib</code>,
+ <code>librcc.lib</code>, and <code>rcc.exe</code>, all in <code>BUILDDIR</code>. There may
+ be some warnings, but there should be no warnings.</p>
+ </li>
+ <li>Create a test directory and run the test suite:<blockquote>
+ <pre>C:\dist\lcc\4.1&gt;mkdir %BUILDDIR%\x86\win32\tst
+C:\dist\lcc\4.1&gt;nmake -f makefile.nt test</pre>
+ </blockquote>
+ <p>This command compiles each program in <a HREF="../tst">tst</a>, compares the generated
+ assembly code and diagnostics with the expected assembly code and diagnostics, executes
+ the program, and compares the output with the expected output (using <code>fc</code>). For
+ example, when the nmake command compiles <a HREF="../tst/8q.c"><code>tst\8q.c</code></a>,
+ it leaves the generated assembly code and diagnostic output in <code>%BUILDDIR%\x86\win32\tst\8q.s</code>
+ and <code>%BUILDDIR%\x86\win32\tst\8q.2</code>, and it compares them with the expected
+ results in <code>x86\win32\tst\8q.sbk</code>. It builds the executable program in <code>%BUILDDIR%\x86\win32\tst\8q.exe</code>,
+ runs it, and redirects the output to <code>%BUILDDIR%\x86\win32\tst\8q.1</code>, which it
+ compares with <code>x86\win32\tst\8q.1bk</code>. The output from this step is voluminous,
+ but there should be no differences and no errors.</p>
+ </li>
+ <li>Run the &quot;triple&quot; test, which compiles <code>rcc</code> with itself and
+ verifies the results:<blockquote>
+ <pre>C:\dist\lcc\4.1&gt;nmake -f makefile.nt triple
+...
+\progra~1\lcc\4.1\bin\x86.c:
+ Assembling: C:/TEMP/lcc2001.asm
+ fc /b \progra~1\lcc\4.1\bin\1rcc.exe \progra~1\lcc\4.1\bin\2rcc.exe
+Comparing files \progra~1\lcc\4.1\bin\1rcc.exe and \progra~1\lcc\4.1\bin\2RCC.EXE
+00000088: B4 D5</pre>
+ </blockquote>
+ <p>This command builds <code>rcc</code> twice; once using the <code>rcc</code> built by VC
+ and again using the <code>rcc</code> built by <code>lcc</code>. The resulting binaries are
+ compared using <code>fc</code>. They should be identical, except for one or two bytes of
+ timestamp data, as shown at the end of the output above. If they aren't, our compiler is
+ generating incorrect code; <a HREF="#bugs">contact</a> us.</p>
+ </li>
+ <li>Copy <code>lcc.exe</code> and <code>bprint.exe</code> to a directory on your PATH, e.g.,<blockquote>
+ <pre>C:\dist\lcc\4.1&gt;copy %BUILDDIR%\lcc.exe \bin
+ 1 file(s) copied.
+
+C:\dist\lcc\4.1&gt;copy %BUILDDIR%\bprint.exe \bin
+ 1 file(s) copied.</pre>
+ </blockquote>
+ </li>
+ <li>Finally, clean up:<blockquote>
+ <pre>C:\dist\lcc\4.1&gt;nmake -f makefile.nt clean</pre>
+ </blockquote>
+ <p>This command removes the derived files in <code>BUILDDIR</code>, but does not remove <code>rcc.exe</code>,
+ etc.; &quot;<code>nmake -f makefile.nt clobber</code>&quot; cleans up and removes all
+ executables and libraries. Test directories under <code>BUILDDIR</code> are <em>not</em>
+ removed; you'll need to remove these by hand, e.g.,</p>
+ <blockquote>
+ <pre>C:\dist\lcc\4.1&gt;rmdir %BUILDDIR%\x86 /s
+\progra~1\lcc\4.1\bin\x86, Are you sure (Y/N)? y</pre>
+ </blockquote>
+ </li>
+</ol>
+
+<h2><a NAME="bugs">Reporting Bugs</a></h2>
+
+<p>lcc is a large, complex program. We find and repair errors routinely. If you think that
+you've found a error, follow the steps below, which are adapted from the instructions in
+Chapter 1 of <cite>A Retargetable C Compiler: Design and Implementation</cite>.
+
+<ol>
+ <li>If you don't have a source file that displays the error, create one. Most errors are
+ exposed when programmers try to compile a program they think is valid, so you probably
+ have a demonstration program already.</li>
+ <li>Preprocess the source file and capture the preprocessor output. Discard the original
+ code.</li>
+ <li>Prune your source code until it can be pruned no more without sending the error into
+ hiding. We prune most error demonstrations to fewer than five lines.</li>
+ <li>Confirm that the source file displays the error with the <em>distributed</em> version of
+ lcc. If you've changed lcc and the error appears only in your version, then you'll have to
+ chase the error yourself, even if it turns out to be our fault, because we can't work on
+ your code.</li>
+ <li>Annotate your code with comments that explain why you think that lcc is wrong. If lcc
+ dies with an assertion failure, please tell us where it died. If lcc crashes, please
+ report the last part of the call chain if you can. If lcc is rejecting a program you think
+ is valid, please tell us why you think it's valid, and include supporting page numbers in
+ the ANSI Standard, Appendix A in <cite>The C Programming Language</cite>, or the
+ appropriate section in <cite>C: A Reference Manual</cite>, 4th edition by S. B. Harbison
+ and G. L. Steele, Jr. (Prentice Hall, 1995). If lcc silently generates incorrect code for
+ some construct, please include the corrupt assembly code in the comments and flag the
+ incorrect instructions if you can.</li>
+ <li>Confirm that your error hasn't been fixed already. The latest version of lcc is always
+ available for anonymous <code>ftp</code> from <code>ftp.cs.princeton.edu</code> in <a
+ HREF="ftp://ftp.cs.princeton.edu/pub/lcc"><code>pub/lcc</code></a>. A <a
+ HREF="ftp://ftp.cs.princeton.edu/pub/lcc/README"><code>README</code></a> file there gives
+ acquistion details, and the <a HREF="../LOG"><code>LOG</code></a> file reports what errors
+ were fixed and when they were fixed. If you report a error that's been fixed, you might
+ get a canned reply.</li>
+ <li>Send your program by electronic mail to <code>lcc-bugs@cs.princeton.edu</code>. Please
+ send only valid C programs; put all remarks in C comments so that we can process reports
+ semiautomatically.</li>
+</ol>
+
+<h2><a NAME="mailinglist">Keeping in Touch</a></h2>
+
+<p>There is an lcc mailing list for general information about lcc. To be added to the
+list, send a message with the 1-line body</p>
+
+<blockquote>
+ <pre>subscribe lcc</pre>
+</blockquote>
+
+<p>to <code>majordomo@cs.princeton.edu</code>. This line must appear in the message body;
+&quot;Subject:&quot; lines are ignored. To learn more about mailing lists served by <code>majordomo</code>,
+send a message with the 1-word body &quot;<code>help</code>&quot; to <code>majordomo@cs.princeton.edu</code>.
+Mail sent to <code>lcc@cs.princeton.edu</code> is forwarded to everyone on the mailing
+list.</p>
+
+<p>There is also an <code>lcc-bugs</code> mailing list for reporting bugs; subscribe to it
+by sending a message with the 1-line body </p>
+
+<blockquote>
+ <pre>subscribe lcc-bugs</pre>
+</blockquote>
+
+<p>to <code>majordomo@cs.princeton.edu</code>. Mail addressed to <var>lcc-bugs@cs.princeton.edu</var>
+is forwarded to everyone on this list.</p>
+
+<hr>
+
+<address>
+ <a HREF="http://www.research.microsoft.com/~cwfraser/">Chris Fraser</a> / <a
+ HREF="mailto:cwfraser@microsoft.com">cwfraser@microsoft.com</a><br>
+ <a HREF="http://www.research.microsoft.com/~drh/">David Hanson</a> / <a
+ HREF="mailto:drh@microsoft.com">drh@microsoft.com</a><br>
+ $Revision: 145 $ $Date: 2001-10-17 16:53:10 -0500 (Wed, 17 Oct 2001) $
+</address>
+</body>
+</html>
diff --git a/lcc/doc/lcc.1 b/lcc/doc/lcc.1
new file mode 100755
index 0000000..53c2cc5
--- /dev/null
+++ b/lcc/doc/lcc.1
@@ -0,0 +1,605 @@
+.\" $Id: lcc.1 145 2001-10-17 21:53:10Z timo $
+.TH LCC 1 "local \- $Date: 2001-10-17 16:53:10 -0500 (Wed, 17 Oct 2001) $"
+.SH NAME
+lcc \- ANSI C compiler
+.SH SYNOPSIS
+.B lcc
+[
+.I option
+|
+.I file
+]...
+.br
+.SH DESCRIPTION
+.PP
+.I lcc
+is an ANSI C compiler for a variety of platforms.
+.PP
+Arguments whose names end with `.c' (plus `.C' under Windows) are taken to be
+C source programs; they are preprocessed, compiled, and
+each object program is left on the file
+whose name is that of the source with `.o' (UNIX) or `.obj' (Windows)
+substituted for the extension.
+Arguments whose names end with `.i' are treated similarly,
+except they are not preprocessed.
+In the same way,
+arguments ending with `.s' (plus `.S', `.asm', and `.ASM', under Windows)
+are taken to be assembly source programs
+and are assembled, producing an object file.
+If there are no arguments,
+.I lcc
+summarizes its options on the standard error.
+.PP
+.I lcc
+deletes an object file if and only if exactly one
+source file is mentioned and no other file
+(source, object, library) or
+.B \-l
+option is mentioned.
+.PP
+If the environment variable
+.B LCCINPUTS
+is set,
+.I lcc
+assumes it gives a semicolon- or colon-separated list of directories in which to
+look for source and object files whose names do not begin with `/'.
+These directories are also added to the list of directories
+searched for libraries.
+If
+.B LCCINPUTS
+is defined, it must contain `.' in order for the current directory
+to be searched for input files.
+.PP
+.I lcc
+uses ANSI standard header files (see `FILES' below).
+Include files not found in the ANSI header files
+are taken from the normal default include areas,
+which usually includes
+.BR /usr/include .
+Under Windows, if the environment variable
+.B include
+is defined, it gives a semicolon-separated list of directories in which to search for
+header files.
+.PP
+.I lcc
+interprets the following options; unrecognized options are
+taken as loader options (see
+.IR ld (1))
+unless
+.BR \-c ,
+.BR \-S ,
+or
+.B \-E
+precedes them.
+Except for
+.BR \-l ,
+all options are processed before any of the files
+and apply to all of the files.
+Applicable options are passed to each compilation phase in the order given.
+.TP
+.B \-c
+Suppress the loading phase of the compilation, and force
+an object file to be produced even if only one program is compiled.
+.TP
+.B \-g
+Produce additional symbol table information for the local debuggers.
+.I lcc
+warns when
+.B \-g
+is unsupported.
+.TP
+.BI \-Wf\-g n , x
+Set the debugging level to
+.I n
+and emit source code as comments into the generated assembly code;
+.I x
+must be the assembly language comment character.
+If
+.I n
+is omitted, it defaults to 1, which is similar to
+.BR \-g .
+Omitting
+.BI , x
+just sets the debugging level to
+.IR n .
+.TP
+.B \-w
+Suppress warning diagnostics, such as those
+announcing unreferenced statics, locals, and parameters.
+The line
+.I
+#pragma ref id
+simulates a reference to the variable
+.IR id .
+.TP
+.BI \-d n
+Generate jump tables for switches whose density is at least
+.IR n ,
+a floating point constant between zero and one.
+The default is 0.5.
+.TP
+.B \-A
+Warns about
+declarations and casts of function types without prototypes,
+assignments between pointers to ints and pointers to enums, and
+conversions from pointers to smaller integral types.
+A second
+.B \-A
+warns about
+unrecognized control lines,
+nonANSI language extensions and source characters in literals,
+unreferenced variables and static functions,
+declaring arrays of incomplete types,
+and exceeding
+.I some
+ANSI environmental limits, like more than 257 cases in switches.
+It also arranges for duplicate global definitions in separately compiled
+files to cause loader errors.
+.TP
+.B \-P
+Writes declarations for all defined globals on standard error.
+Function declarations include prototypes;
+editing this output can simplify conversion to ANSI C.
+This output may not correspond to the input when
+there are several typedefs for the same type.
+.TP
+.B \-n
+Arrange for the compiler to produce code
+that tests for dereferencing zero pointers.
+The code reports the offending file and line number and calls
+.IR abort (3).
+.TP
+.B \-O
+is ignored.
+.TP
+.B \-S
+Compile the named C programs, and leave the
+assembler-language output on corresponding files suffixed `.s' or `.asm'.
+.TP
+.B \-E
+Run only the preprocessor on the named C programs
+and unsuffixed file arguments,
+and send the result to the standard output.
+.TP
+.BI \-o " output"
+Name the output file
+.IR output .
+If
+.B \-c
+or
+.B \-S
+is specified and there is exactly one source file,
+this option names the object or assembly file, respectively.
+Otherwise, this option names the final executable
+file generated by the loader, and `a.out' (UNIX) or `a.exe' (Windows) is left undisturbed.
+.I lcc
+warns if
+.B \-o
+and
+.B \-c
+or
+.B \-S
+are given with more than one source file and ignores the
+.B \-o
+option.
+.TP
+.BI \-D name=def
+Define the
+.I name
+to the preprocessor, as if by `#define'.
+If
+.I =def
+is omitted, the name is defined as "1".
+.TP
+.BI \-U name
+Remove any initial definition of
+.IR name .
+.TP
+.BI \-I dir
+`#include' files
+whose names do not begin with `/' are always
+sought first in the directory of the
+.I file
+arguments, then in directories named in
+.B \-I
+options, then in directories on a standard list.
+.TP
+.B \-N
+Do not search
+.I any
+of the standard directories for `#include' files.
+Only those directories specified by subsequent explicit
+.B \-I
+options will be searched, in the order given.
+.TP
+.BI \-B str
+Use the compiler
+.BI "" str rcc
+instead of the default version.
+Note that
+.I str
+often requires a trailing slash.
+On Sparcs only,
+.B \-Bstatic
+and
+.BI \-Bdynamic
+are passed to the loader; see
+.IR ld (1).
+.TP
+.BI \-Wo\-lccdir= dir
+Find the preprocessor, compiler proper, and include directory
+in the directory
+.I dir/
+or
+.I
+dir\\.
+If the environment variable
+.B LCCDIR
+is defined, it gives this directory.
+.I lcc
+warns when this option is unsupported.
+.TP
+.B \-Wf-unsigned_char=1
+.br
+.ns
+.TP
+.B \-Wf-unsigned_char=0
+makes plain
+.B char
+an unsigned (1) or signed (0) type; by default,
+.B char
+is signed.
+.TP
+.B \-Wf\-wchar_t=unsigned_char
+.br
+.ns
+.TP
+.B \-Wf\-wchar_t=unsigned_short
+.br
+.ns
+.TP
+.B \-Wf\-wchar_t=unsigned_int
+Makes wide characters the type indicated; by default,
+wide characters are unsigned short ints, and
+.B wchar_t
+is a typedef for unsigned short defined in stddef.h.
+The definition for
+.B wchar_t
+in stddef.h must correspond to the type specified.
+.TP
+.B \-v
+Print commands as they are executed; some of the executed
+programs are directed to print their version numbers.
+More than one occurrence of
+.B \-v
+causes the commands to be printed, but
+.I not
+executed.
+.TP
+.BR \-help " or " \-?
+Print a message on the standard error summarizing
+.IR lcc 's
+options and giving the values of the environment variables
+.B LCCINPUTS
+and
+.BR LCCDIR ,
+if they are defined.
+Under Windows, the values of
+.B include
+and
+.B lib
+are also given, if they are defined.
+.TP
+.B \-b
+Produce code that counts the number of times each expression is executed.
+If loading takes place, arrange for a
+.B prof.out
+file to be written when the object program terminates.
+A listing annotated with execution counts can then be generated with
+.IR bprint (1).
+.I lcc
+warns when
+.B \-b
+is unsupported.
+.B \-Wf\-C
+is similar, but counts only the number of function calls.
+.TP
+.B \-p
+Produce code that counts the number of times each function is called.
+If loading takes place, replace the standard startup
+function by one that automatically calls
+.IR monitor (3)
+at the start and arranges to write a
+.B mon.out
+file when the object program terminates normally.
+An execution profile can then be generated with
+.IR prof (1).
+.I lcc
+warns when
+.B \-p
+is unsupported.
+.TP
+.B \-pg
+Causes the compiler to produce counting code like
+.BR \-p ,
+but invokes a run-time recording mechanism that keeps more
+extensive statistics and produces a
+.B gmon.out
+file at normal termination.
+Also, a profiling library is searched, in lieu of the standard C library.
+An execution profile can then be generated with
+.IR gprof (1).
+.I lcc
+warns when
+.B \-pg
+is unsupported.
+.TP
+.BI \-t name
+.br
+.ns
+.TP
+.BI \-t
+Produce code to print the name of the function, an activation number,
+and the name and value of each argument at function entry.
+At function exit, produce code to print
+the name of the function, the activation number, and the return value.
+By default,
+.I printf
+does the printing; if
+.I name
+appears, it does.
+For null
+.I char*
+values, "(null)" is printed.
+.BI \-target
+.I name
+is accepted, but ignored.
+.TP
+.BI \-tempdir= dir
+Store temporary files in the directory
+.I dir/
+or
+.I
+dir\\.
+The default is usually
+.BR /tmp .
+.TP
+.BI \-W xarg
+pass argument
+.I arg
+to the program indicated by
+.IR x ;
+.I x
+can be one of
+.BR p ,
+.BR f ,
+.BR a ,
+or
+.BR l ,
+which refer, respectively, to the preprocessor, the compiler proper,
+the assembler, and the loader.
+.I arg
+is passed as given; if a
+.B \-
+is expected, it must be given explicitly.
+.BI \-Wo arg
+specifies a system-specific option,
+.IR arg .
+.PP
+Other arguments
+are taken to be either loader option arguments, or C-compatible
+object programs, typically produced by an earlier
+.I lcc
+run, or perhaps libraries of C-compatible routines.
+Duplicate object files are ignored.
+These programs, together with the results of any
+compilations specified, are loaded (in the order
+given) to produce an executable program with name
+.BR a.out
+(UNIX) or
+.BR a.exe
+(Windows).
+.PP
+.I lcc
+assigns the most frequently referenced scalar parameters and
+locals to registers whenever possible.
+For each block,
+explicit register declarations are obeyed first;
+remaining registers are assigned to automatic locals if they
+are `referenced' at least 3 times.
+Each top-level occurrence of an identifier
+counts as 1 reference. Occurrences in a loop,
+either of the then/else arms of an if statement, or a case
+in a switch statement each count, respectively, as 10, 1/2, or 1/10 references.
+These values are adjusted accordingly for nested control structures.
+.B \-Wf\-a
+causes
+.I lcc
+to read a
+.B prof.out
+file from a previous execution and to use the data therein
+to compute reference counts (see
+.BR \-b ).
+.PP
+.I lcc
+is a cross compiler;
+.BI \-Wf\-target= target/os
+causes
+.I lcc
+to generate code for
+.I target
+running the operating system denoted by
+.IR os .
+The supported
+.I target/os
+combinations may include
+.PP
+.RS
+.ta \w'sparc/solarisxx'u
+.nf
+alpha/osf ALPHA, OSF 3.2
+mips/irix big-endian MIPS, IRIX 5.2
+mips/ultrix little-endian MIPS, ULTRIX 4.3
+sparc/solaris SPARC, Solaris 2.3
+x86/win32 x86, Windows NT 4.0/Windows 95/98
+x86/linux x86, Linux
+symbolic text rendition of the generated code
+null no output
+.fi
+.RE
+.PP
+For
+.BR \-Wf\-target=symbolic ,
+the option
+.B \-Wf-html
+causes the text rendition to be emitted as HTML.
+.B
+.SH LIMITATIONS
+.PP
+.I lcc
+accepts the C programming language
+as described in the ANSI standard.
+If
+.I lcc
+is used with the GNU C preprocessor, the
+.B \-Wp\-trigraphs
+option is required to enable trigraph sequences.
+.PP
+Plain int bit fields are signed.
+Bit fields are aligned like unsigned integers but are otherwise laid out
+as by most standard C compilers.
+Some compilers, such as the GNU C compiler,
+may choose other, incompatible layouts.
+.PP
+Likewise, calling conventions are intended to be compatible with
+the host C compiler,
+except possibly for passing and returning structures.
+Specifically,
+.I lcc
+passes and returns structures like host ANSI C compilers
+on most targets, but some older host C compilers use different conventions.
+Consequently, calls to/from such functions compiled with
+older C compilers may not work.
+Calling a function that returns
+a structure without declaring it as such violates
+the ANSI standard and may cause a fault.
+.SH FILES
+.PP
+The file names listed below are
+.IR typical ,
+but vary among installations; installation-dependent variants
+can be displayed by running
+.I lcc
+with the
+.B \-v
+option.
+.PP
+.RS
+.ta \w'$LCCDIR/liblcc.{a,lib}XX'u
+.nf
+file.{c,C} input file
+file.{s,asm} assembly-language file
+file.{o,obj} object file
+a.{out,exe} loaded output
+/tmp/lcc* temporary files
+$LCCDIR/cpp preprocessor
+$LCCDIR/rcc compiler
+$LCCDIR/liblcc.{a,lib} \fIlcc\fP-specific library
+/lib/crt0.o runtime startup (UNIX)
+/lib/[gm]crt0.o startups for profiling (UNIX)
+/lib/libc.a standard library (UNIX)
+$LCCDIR/include ANSI standard headers
+/usr/local/include local headers
+/usr/include traditional headers
+prof.out file produced for \fIbprint\fR(1)
+mon.out file produced for \fIprof\fR(1)
+gmon.out file produced for \fIgprof\fR(1)
+.fi
+.RE
+.PP
+.I lcc
+predefines the macro
+.B __LCC__
+on all systems.
+It may also predefine some installation-dependent symbols; option
+.B \-v
+exposes them.
+.SH "SEE ALSO"
+.PP
+C. W. Fraser and D. R. Hanson,
+.I A Retargetable C Compiler: Design and Implementation,
+Addison-Wesley, 1995. ISBN 0-8053-1670-1.
+.PP
+The World-Wide Web page at http://www.cs.princeton.edu/software/lcc/.
+.PP
+S. P. Harbison and G. L. Steele, Jr.,
+.I C: A Reference Manual,
+4th ed., Prentice-Hall, 1995.
+.PP
+B. W. Kernighan and D. M. Ritchie,
+.I The C Programming Language,
+2nd ed., Prentice-Hall, 1988.
+.PP
+American National Standards Inst.,
+.I American National Standard for Information Systems\(emProgramming
+.IR Language\(emC ,
+ANSI X3.159-1989, New York, 1990.
+.br
+.SH BUGS
+Mail bug reports along with the shortest preprocessed program
+that exposes them and the details reported by
+.IR lcc 's
+.B \-v
+option to lcc-bugs@princeton.edu. The WWW page at
+URL http://www.cs.princeton.edu/software/lcc/
+includes detailed instructions for reporting bugs.
+.PP
+The ANSI standard headers conform to the specifications in
+the Standard, which may be too restrictive for some applications,
+but necessary for portability.
+Functions given in the ANSI headers may be missing from
+some local C libraries (e.g., wide-character functions)
+or may not correspond exactly to the local versions;
+for example, the ANSI standard
+stdio.h
+specifies that
+.IR printf ,
+.IR fprintf ,
+and
+.I sprintf
+return the number of characters written to the file or array,
+but some existing libraries don't implement this convention.
+.PP
+On the MIPS and SPARC, old-style variadic functions must use
+varargs.h
+from MIPS or Sun. New-style is recommended.
+.PP
+With
+.BR \-b ,
+files compiled
+.I without
+.B \-b
+may cause
+.I bprint
+to print erroneous call graphs.
+For example, if
+.B f
+calls
+.B g
+calls
+.B h
+and
+.B f
+and
+.B h
+are compiled with
+.BR \-b ,
+but
+.B g
+is not,
+.B bprint
+will report that
+.B f
+called
+.BR h .
+The total number of calls is correct, however.
diff --git a/lcc/doc/lcc.pdf b/lcc/doc/lcc.pdf
new file mode 100755
index 0000000..6134de6
--- /dev/null
+++ b/lcc/doc/lcc.pdf
Binary files differ
diff --git a/lcc/etc/bprint.c b/lcc/etc/bprint.c
new file mode 100755
index 0000000..856d40b
--- /dev/null
+++ b/lcc/etc/bprint.c
@@ -0,0 +1,475 @@
+#include <assert.h>
+#include <ctype.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+/* bprint [ -c | -Idir... | -f | -b | -n ] [ file... ]
+ * annotate listings of files with prof.out data
+ */
+
+
+#define NDIRS (sizeof dirs/sizeof dirs[0] - 1)
+#define NEW(p,a) ((p) = alloc(sizeof *(p)))
+#define newarray(m,n,a) alloc((m)*(n))
+#define NELEMS(a) ((int)(sizeof (a)/sizeof ((a)[0])))
+
+#define MAXTOKEN 64
+
+struct count { /* count data: */
+ int x, y; /* source coordinate */
+ int count; /* associated execution count */
+};
+
+char *progname;
+int number;
+char *dirs[20];
+int fcount;
+
+struct file { /* per-file prof.out data: */
+ struct file *link; /* link to next file */
+ char *name; /* file name */
+ int size; /* size of counts[] */
+ int count; /* counts[0..count-1] hold valid data */
+ struct count *counts; /* count data */
+ struct func { /* function data: */
+ struct func *link; /* link to next function */
+ char *name; /* function name */
+ struct count count; /* total number of calls */
+ struct caller { /* caller data: */
+ struct caller *link; /* link to next caller */
+ char *name; /* caller's name */
+ char *file; /* call site: file, x, y */
+ int x, y;
+ int count; /* number of calls from this site */
+ } *callers;
+ } *funcs; /* list of functions */
+} *filelist;
+FILE *fp;
+
+extern int process(char *);
+extern int findfunc(char *, char *);
+extern int findcount(char *, int, int);
+
+void *alloc(unsigned);
+char *string(char *);
+int process(char *);
+void emitdata(char *);
+void printfile(struct file *, int);
+void printfuncs(struct file *, int);
+
+/* alloc - allocate n bytes or die */
+void *alloc(unsigned n) {
+ void *new = malloc(n);
+
+ assert(new);
+ return new;
+}
+
+/* emitdata - write prof.out data to file */
+void emitdata(char *file) {
+ FILE *fp;
+
+ if (fp = fopen(file, "w")) {
+ struct file *p;
+ for (p = filelist; p; p = p->link) {
+ int i;
+ struct func *q;
+ struct caller *r;
+ fprintf(fp, "1\n%s\n", p->name);
+ for (i = 0, q = p->funcs; q; i++, q = q->link)
+ if (r = q->callers)
+ for (i--; r; r = r->link)
+ i++;
+ fprintf(fp, "%d\n", i);
+ for (q = p->funcs; q; q = q->link)
+ if (q->count.count == 0 || !q->callers)
+ fprintf(fp, "%s 1 %d %d %d ? ? 0 0\n", q->name, q->count.x,
+ q->count.y, q->count.count);
+ else
+ for (r = q->callers; r; r = r->link)
+ fprintf(fp, "%s 1 %d %d %d %s %s %d %d\n", q->name, q->count.x,
+ q->count.y, r->count, r->name, r->file, r->x, r->y);
+ fprintf(fp, "%d\n", p->count);
+ for (i = 0; i < p->count; i++)
+ fprintf(fp, "1 %d %d %d\n", p->counts[i].x,
+ p->counts[i].y, p->counts[i].count);
+ }
+ fclose(fp);
+ } else
+ fprintf(stderr, "%s: can't create `%s'\n", progname, file);
+}
+
+/* openfile - open name for reading, searching -I directories */
+FILE *openfile(char *name) {
+ int i;
+ FILE *fp;
+
+ if (*name != '/')
+ for (i = 0; dirs[i]; i++) {
+ char buf[200];
+ sprintf(buf, "%s/%s", dirs[i], name);
+ if (fp = fopen(buf, "r"))
+ return fp;
+ }
+ return fopen(name, "r");
+}
+
+/* printfile - print annotated listing for p */
+void printfile(struct file *p, int nf) {
+ int lineno;
+ FILE *fp;
+ char *s, buf[512];
+ struct count *u = p->counts, *r, *uend;
+
+ if (u == 0 || p->count <= 0)
+ return;
+ uend = &p->counts[p->count];
+ if ((fp = openfile(p->name)) == NULL) {
+ fprintf(stderr, "%s: can't open `%s'\n", progname, p->name);
+ return;
+ }
+ if (nf)
+ printf("%s%s:\n\n", nf == 1 ? "" : "\f", p->name);
+ for (lineno = 1; fgets(buf, sizeof buf, fp); lineno++) {
+ if (number)
+ printf("%d\t", lineno);
+ while (u < uend && u->y < lineno)
+ u++;
+ for (s = buf; *s; ) {
+ char *t = s + 1;
+ while (u < uend && u->y == lineno && u->x < s - buf)
+ u++;
+ if (isalnum(*s) || *s == '_')
+ while (isalnum(*t) || *t == '_')
+ t++;
+ while (u < uend && u->y == lineno && u->x < t - buf) {
+ printf("<%d>", u->count);
+ for (r = u++; u < uend && u->x == r->x && u->y == r->y && u->count == r->count; u++)
+ ;
+ }
+ while (s < t)
+ putchar(*s++);
+ }
+ if (*s)
+ printf("%s", s);
+ }
+ fclose(fp);
+}
+
+/* printfuncs - summarize data for functions in p */
+void printfuncs(struct file *p, int nf) {
+ struct func *q;
+
+ if (nf)
+ printf("%s:\n", p->name);
+ for (q = p->funcs; q; q = q->link)
+ if (fcount <= 1 || q->count.count == 0 || !q->callers)
+ printf("%d\t%s\n", q->count.count, q->name);
+ else {
+ struct caller *r;
+ for (r = q->callers; r; r = r->link)
+ printf("%d\t%s\tfrom %s\tin %s:%d.%d\n", r->count, q->name, r->name,
+ r->file, r->y, r->x + 1);
+ }
+
+}
+
+/* string - save a copy of str, if necessary */
+char *string(char *str) {
+ static struct string { struct string *link; char str[1]; } *list;
+ struct string *p;
+
+ for (p = list; p; p = p->link)
+ if (strcmp(p->str, str) == 0)
+ return p->str;
+ p = (struct string *)alloc(strlen(str) + sizeof *p);
+ strcpy(p->str, str);
+ p->link = list;
+ list = p;
+ return p->str;
+}
+/* acaller - add caller and site (file,x,y) to callee's callers list */
+static void acaller(char *caller, char *file, int x, int y, int count, struct func *callee) {
+ struct caller *q;
+
+ assert(callee);
+ for (q = callee->callers; q && (caller != q->name
+ || file != q->file || x != q->x || y != q->y); q = q->link)
+ ;
+ if (!q) {
+ struct caller **r;
+ NEW(q, PERM);
+ q->name = caller;
+ q->file = file;
+ q->x = x;
+ q->y = y;
+ q->count = 0;
+ for (r = &callee->callers; *r && (strcmp(q->name, (*r)->name) > 0
+ || strcmp(q->file, (*r)->file) > 0 || q->y > (*r)->y || q->y > (*r)->y); r = &(*r)->link)
+ ;
+ q->link = *r;
+ *r = q;
+ }
+ q->count += count;
+}
+
+/* compare - return <0, 0, >0 if a<b, a==b, a>b, resp. */
+static int compare(struct count *a, struct count *b) {
+ if (a->y == b->y)
+ return a->x - b->x;
+ return a->y - b->y;
+}
+
+/* findfile - return file name's file list entry, or 0 */
+static struct file *findfile(char *name) {
+ struct file *p;
+
+ for (p = filelist; p; p = p->link)
+ if (p->name == name)
+ return p;
+ return 0;
+}
+
+/* afunction - add function name and its data to file's function list */
+static struct func *afunction(char *name, char *file, int x, int y, int count) {
+ struct file *p = findfile(file);
+ struct func *q;
+
+ assert(p);
+ for (q = p->funcs; q && name != q->name; q = q->link)
+ ;
+ if (!q) {
+ struct func **r;
+ NEW(q, PERM);
+ q->name = name;
+ q->count.x = x;
+ q->count.y = y;
+ q->count.count = 0;
+ q->callers = 0;
+ for (r = &p->funcs; *r && compare(&q->count, &(*r)->count) > 0; r = &(*r)->link)
+ ;
+ q->link = *r;
+ *r = q;
+ }
+ q->count.count += count;
+ return q;
+}
+
+/* apoint - append execution point i to file's data */
+static void apoint(int i, char *file, int x, int y, int count) {
+ struct file *p = findfile(file);
+
+ assert(p);
+ if (i >= p->size) {
+ int j;
+ if (p->size == 0) {
+ p->size = i >= 200 ? 2*i : 200;
+ p->counts = newarray(p->size, sizeof *p->counts, PERM);
+ } else {
+ struct count *new;
+ p->size = 2*i;
+ new = newarray(p->size, sizeof *new, PERM);
+ for (j = 0; j < p->count; j++)
+ new[j] = p->counts[j];
+ p->counts = new;
+ }
+ for (j = p->count; j < p->size; j++) {
+ static struct count z;
+ p->counts[j] = z;
+ }
+ }
+ p->counts[i].x = x;
+ p->counts[i].y = y;
+ p->counts[i].count += count;
+ if (i >= p->count)
+ p->count = i + 1;
+}
+
+/* findcount - return count associated with (file,x,y) or -1 */
+int findcount(char *file, int x, int y) {
+ static struct file *cursor;
+
+ if (cursor == 0 || cursor->name != file)
+ cursor = findfile(file);
+ if (cursor) {
+ int l, u;
+ struct count *c = cursor->counts;
+ for (l = 0, u = cursor->count - 1; l <= u; ) {
+ int k = (l + u)/2;
+ if (c[k].y > y || c[k].y == y && c[k].x > x)
+ u = k - 1;
+ else if (c[k].y < y || c[k].y == y && c[k].x < x)
+ l = k + 1;
+ else
+ return c[k].count;
+ }
+ }
+ return -1;
+}
+
+/* findfunc - return count associated with function name in file or -1 */
+int findfunc(char *name, char *file) {
+ static struct file *cursor;
+
+ if (cursor == 0 || cursor->name != file)
+ cursor = findfile(file);
+ if (cursor) {
+ struct func *p;
+ for (p = cursor->funcs; p; p = p->link)
+ if (p->name == name)
+ return p->count.count;
+ }
+ return -1;
+}
+
+/* getd - read a nonnegative number */
+static int getd(void) {
+ int c, n = 0;
+
+ while ((c = getc(fp)) != EOF && (c == ' ' || c == '\n' || c == '\t'))
+ ;
+ if (c >= '0' && c <= '9') {
+ do
+ n = 10*n + (c - '0');
+ while ((c = getc(fp)) >= '0' && c <= '9');
+ return n;
+ }
+ return -1;
+}
+
+/* getstr - read a string */
+static char *getstr(void) {
+ int c;
+ char buf[MAXTOKEN], *s = buf;
+
+ while ((c = getc(fp)) != EOF && c != ' ' && c != '\n' && c != '\t')
+ if (s - buf < (int)sizeof buf - 2)
+ *s++ = c;
+ *s = 0;
+ return s == buf ? (char *)0 : string(buf);
+}
+
+/* gather - read prof.out data from fd */
+static int gather(void) {
+ int i, nfiles, nfuncs, npoints;
+ char *files[64];
+
+ if ((nfiles = getd()) < 0)
+ return 0;
+ assert(nfiles < NELEMS(files));
+ for (i = 0; i < nfiles; i++) {
+ if ((files[i] = getstr()) == 0)
+ return -1;
+ if (!findfile(files[i])) {
+ struct file *new;
+ NEW(new, PERM);
+ new->name = files[i];
+ new->size = new->count = 0;
+ new->counts = 0;
+ new->funcs = 0;
+ new->link = filelist;
+ filelist = new;
+ }
+ }
+ if ((nfuncs = getd()) < 0)
+ return -1;
+ for (i = 0; i < nfuncs; i++) {
+ struct func *q;
+ char *name, *file;
+ int f, x, y, count;
+ if ((name = getstr()) == 0 || (f = getd()) <= 0
+ || (x = getd()) < 0 || (y = getd()) < 0 || (count = getd()) < 0)
+ return -1;
+ q = afunction(name, files[f-1], x, y, count);
+ if ((name = getstr()) == 0 || (file = getstr()) == 0
+ || (x = getd()) < 0 || (y = getd()) < 0)
+ return -1;
+ if (*name != '?')
+ acaller(name, file, x, y, count, q);
+ }
+ if ((npoints = getd()) < 0)
+ return -1;
+ for (i = 0; i < npoints; i++) {
+ int f, x, y, count;
+ if ((f = getd()) < 0 || (x = getd()) < 0 || (y = getd()) < 0
+ || (count = getd()) < 0)
+ return -1;
+ if (f)
+ apoint(i, files[f-1], x, y, count);
+ }
+ return 1;
+}
+
+/* process - read prof.out data from file */
+int process(char *file) {
+ int more;
+
+ if ((fp = fopen(file, "r")) != NULL) {
+ struct file *p;
+ while ((more = gather()) > 0)
+ ;
+ fclose(fp);
+ if (more < 0)
+ return more;
+ for (p = filelist; p; p = p->link)
+ qsort(p->counts, p->count, sizeof *p->counts,
+ (int (*)(const void *, const void *))
+ compare);
+
+ return 1;
+ }
+ return 0;
+}
+int main(int argc, char *argv[]) {
+ int i;
+ struct file *p;
+ void (*f)(struct file *, int) = printfile;
+
+ progname = argv[0];
+ if ((i = process("prof.out")) <= 0) {
+ fprintf(stderr, "%s: can't %s `%s'\n", progname,
+ i == 0 ? "open" : "interpret", "prof.out");
+ exit(1);
+ }
+ for (i = 1; i < argc && *argv[i] == '-'; i++)
+ if (strcmp(argv[i], "-c") == 0) {
+ emitdata("prof.out");
+ exit(0);
+ } else if (strcmp(argv[i], "-b") == 0)
+ f = printfile;
+ else if (strcmp(argv[i], "-f") == 0) {
+ fcount++;
+ f = printfuncs;
+ } else if (strcmp(argv[i], "-n") == 0)
+ number++;
+ else if (strncmp(argv[i], "-I", 2) == 0) {
+ int j;
+ for (j = 0; j < NDIRS && dirs[j]; j++)
+ ;
+ if (j < NDIRS)
+ dirs[j] = &argv[i][2];
+ else
+ fprintf(stderr, "%s: too many -I options\n", progname);
+ } else {
+ fprintf(stderr, "usage: %s [ -c | -b | -n | -f | -Idir... ] [ file... ]\n", progname);
+ exit(1);
+ }
+ for (p = filelist; p; p = p->link)
+ qsort(p->counts, p->count, sizeof *p->counts,
+ (int (*)(const void *, const void *))compare);
+ if (i < argc) {
+ int nf = i < argc - 1 ? 1 : 0;
+ for ( ; i < argc; i++, nf ? nf++ : 0)
+ if (p = findfile(string(argv[i])))
+ (*f)(p, nf);
+ else
+ fprintf(stderr, "%s: no data for `%s'\n", progname, argv[i]);
+ } else {
+ int nf = filelist && filelist->link ? 1 : 0;
+ for (p = filelist; p; p = p->link, nf ? nf++ : 0)
+ (*f)(p, nf);
+ }
+ return 0;
+}
+
diff --git a/lcc/etc/gcc-solaris.c b/lcc/etc/gcc-solaris.c
new file mode 100755
index 0000000..c38769c
--- /dev/null
+++ b/lcc/etc/gcc-solaris.c
@@ -0,0 +1,50 @@
+/* SPARCs running Solaris 2.5.1 w/GCC tools
+ at CS Dept., Princeton University */
+
+#include <string.h>
+
+
+#ifndef LCCDIR
+#define LCCDIR "/usr/local/lib/lcc/"
+#endif
+#ifndef GCCDIR
+#define GCCDIR "/usr/local/gnu/bin/"
+#endif
+#ifndef GCCLIB
+#define GCCLIB "/usr/local/gnu/lib/gcc-lib/sparc-sun-solaris2.5/2.7.2/"
+#endif
+
+char *suffixes[] = { ".c", ".i", ".s", ".o", ".out", 0 };
+char inputs[256] = "";
+char *cpp[] = { LCCDIR "cpp",
+ "-D__STDC__=1", "-Dsparc", "-D__sparc__", "-Dsun", "-D__sun__", "-Dunix",
+ "$1", "$2", "$3", 0 };
+char *include[] = { "-I" LCCDIR "include", "-I/usr/local/include",
+ "-I" GCCLIB "include", "-I/usr/include", 0 };
+char *com[] = { LCCDIR "rcc", "-target=sparc/solaris",
+ "$1", "$2", "$3", 0 };
+char *as[] = { GCCDIR "as", "-f", "-o", "$3", "$1", "$2", 0 };
+char *ld[] = { GCCDIR "ld", "-o", "$3", "$1",
+ GCCLIB "crti.o", GCCLIB "crt1.o",
+ GCCLIB "crtbegin.o", "$2", "", "", "-L" LCCDIR, "-llcc",
+ "-L" GCCLIB, "-lgcc", "-lm", "-lc", "",
+ GCCLIB "crtend.o", GCCLIB "crtn.o", 0 };
+
+extern char *concat(char *, char *);
+
+int option(char *arg) {
+ if (strncmp(arg, "-lccdir=", 8) == 0) {
+ cpp[0] = concat(&arg[8], "/cpp");
+ include[0] = concat("-I", concat(&arg[8], "/include"));
+ ld[10] = concat("-L", &arg[8]);
+ com[0] = concat(&arg[8], "/rcc");
+ } else if (strcmp(arg, "-g") == 0)
+ ;
+ else if (strcmp(arg, "-pg") == 0) {
+ ld[8] = GCCLIB "gmon.o";
+ } else if (strcmp(arg, "-b") == 0)
+ ;
+ else
+ return 0;
+ return 1;
+}
diff --git a/lcc/etc/irix.c b/lcc/etc/irix.c
new file mode 100755
index 0000000..cc09f1e
--- /dev/null
+++ b/lcc/etc/irix.c
@@ -0,0 +1,64 @@
+/* SGI big endian MIPSes running IRIX 5.2 at CS Dept., Princeton University */
+
+#include <string.h>
+
+
+#ifndef LCCDIR
+#define LCCDIR "/usr/local/lib/lcc/"
+#endif
+
+char *suffixes[] = { ".c", ".i", ".s", ".o", ".out", 0 };
+char inputs[256] = "";
+char *cpp[] = { LCCDIR "cpp", "-D__STDC__=1",
+ "-DLANGUAGE_C",
+ "-DMIPSEB",
+ "-DSYSTYPE_SVR4",
+ "-D_CFE",
+ "-D_LANGUAGE_C",
+ "-D_MIPSEB",
+ "-D_MIPS_FPSET=16",
+ "-D_MIPS_ISA=_MIPS_ISA_MIPS1",
+ "-D_MIPS_SIM=_MIPS_SIM_ABI32",
+ "-D_MIPS_SZINT=32",
+ "-D_MIPS_SZLONG=32",
+ "-D_MIPS_SZPTR=32",
+ "-D_SGI_SOURCE",
+ "-D_SVR4_SOURCE",
+ "-D_SYSTYPE_SVR4",
+ "-D__host_mips",
+ "-D__mips=1",
+ "-D__sgi",
+ "-D__unix",
+ "-Dhost_mips",
+ "-Dmips",
+ "-Dsgi",
+ "-Dunix",
+ "$1", "$2", "$3", 0 };
+char *com[] = { LCCDIR "rcc", "-target=mips/irix", "$1", "$2", "$3", "", 0 };
+char *include[] = { "-I" LCCDIR "include", "-I/usr/local/include",
+ "-I/usr/include", 0 };
+char *as[] = { "/usr/bin/as", "-o", "$3", "$1", "-nocpp", "-KPIC", "$2", 0 };
+char *ld[] = { "/usr/bin/ld", "-require_dynamic_link", "_rld_new_interface",
+ "-elf", "-_SYSTYPE_SVR4", "-Wx,-G", "0", "-g0", "-KPIC", "-dont_warn_unused",
+ "-o", "$3", "/usr/lib/crt1.o", "-L/usr/local/lib",
+ "$1", "$2", "", "-L" LCCDIR, "-llcc", "-lc", "-lm", "/usr/lib/crtn.o", 0
+};
+
+extern char *concat(char *, char *);
+
+int option(char *arg) {
+ if (strncmp(arg, "-lccdir=", 8) == 0) {
+ cpp[0] = concat(&arg[8], "/cpp");
+ include[0] = concat("-I", concat(&arg[8], "/include"));
+ com[0] = concat(&arg[8], "/rcc");
+ ld[17] = concat("-L", &arg[8]);
+ } else if (strcmp(arg, "-g") == 0)
+ ;
+ else if (strcmp(arg, "-p") == 0)
+ ld[12] = "/usr/lib/mcrt1.o";
+ else if (strcmp(arg, "-b") == 0)
+ ;
+ else
+ return 0;
+ return 1;
+}
diff --git a/lcc/etc/lcc.c b/lcc/etc/lcc.c
new file mode 100755
index 0000000..c70abbb
--- /dev/null
+++ b/lcc/etc/lcc.c
@@ -0,0 +1,793 @@
+/*
+ * lcc [ option ]... [ file | -llib ]...
+ * front end for the ANSI C compiler
+ */
+static char rcsid[] = "Id: dummy rcsid";
+
+#include <stdio.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include <ctype.h>
+#include <signal.h>
+
+#ifndef TEMPDIR
+#define TEMPDIR "/tmp"
+#endif
+
+typedef struct list *List;
+struct list { /* circular list nodes: */
+ char *str; /* option or file name */
+ List link; /* next list element */
+};
+
+static void *alloc(int);
+static List append(char *,List);
+extern char *basepath(char *);
+static int callsys(char *[]);
+extern char *concat(char *, char *);
+static int compile(char *, char *);
+static void compose(char *[], List, List, List);
+static void error(char *, char *);
+static char *exists(char *);
+static char *first(char *);
+static int filename(char *, char *);
+static List find(char *, List);
+static void help(void);
+static void initinputs(void);
+static void interrupt(int);
+static void opt(char *);
+static List path2list(const char *);
+extern int main(int, char *[]);
+extern char *replace(const char *, int, int);
+static void rm(List);
+extern char *strsave(const char *);
+extern char *stringf(const char *, ...);
+extern int suffix(char *, char *[], int);
+extern char *tempname(char *);
+
+extern int access(char *, int);
+extern int getpid(void);
+
+extern char *cpp[], *include[], *com[], *as[],*ld[], inputs[], *suffixes[];
+extern int option(char *);
+
+static int errcnt; /* number of errors */
+static int Eflag; /* -E specified */
+static int Sflag; /* -S specified */
+static int cflag; /* -c specified */
+static int verbose; /* incremented for each -v */
+static List llist[2]; /* loader files, flags */
+static List alist; /* assembler flags */
+static List clist; /* compiler flags */
+static List plist; /* preprocessor flags */
+static List ilist; /* list of additional includes from LCCINPUTS */
+static List rmlist; /* list of files to remove */
+static char *outfile; /* ld output file or -[cS] object file */
+static int ac; /* argument count */
+static char **av; /* argument vector */
+char *tempdir = TEMPDIR; /* directory for temporary files */
+static char *progname;
+static List lccinputs; /* list of input directories */
+
+main(int argc, char *argv[]) {
+ int i, j, nf;
+
+ progname = argv[0];
+ ac = argc + 50;
+ av = alloc(ac*sizeof(char *));
+ if (signal(SIGINT, SIG_IGN) != SIG_IGN)
+ signal(SIGINT, interrupt);
+ if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
+ signal(SIGTERM, interrupt);
+#ifdef SIGHUP
+ if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
+ signal(SIGHUP, interrupt);
+#endif
+ if (getenv("TMP"))
+ tempdir = getenv("TMP");
+ else if (getenv("TEMP"))
+ tempdir = getenv("TEMP");
+ else if (getenv("TMPDIR"))
+ tempdir = getenv("TMPDIR");
+ assert(tempdir);
+ i = strlen(tempdir);
+ for (; i > 0 && tempdir[i-1] == '/' || tempdir[i-1] == '\\'; i--)
+ tempdir[i-1] = '\0';
+ if (argc <= 1) {
+ help();
+ exit(0);
+ }
+ plist = append("-D__LCC__", 0);
+ initinputs();
+ if (getenv("LCCDIR"))
+ option(stringf("-lccdir=%s", getenv("LCCDIR")));
+ for (nf = 0, i = j = 1; i < argc; i++) {
+ if (strcmp(argv[i], "-o") == 0) {
+ if (++i < argc) {
+ if (suffix(argv[i], suffixes, 2) >= 0) {
+ error("-o would overwrite %s", argv[i]);
+ exit(8);
+ }
+ outfile = argv[i];
+ continue;
+ } else {
+ error("unrecognized option `%s'", argv[i-1]);
+ exit(8);
+ }
+ } else if (strcmp(argv[i], "-target") == 0) {
+ if (argv[i+1] && *argv[i+1] != '-')
+ i++;
+ continue;
+ } else if (*argv[i] == '-' && argv[i][1] != 'l') {
+ opt(argv[i]);
+ continue;
+ } else if (*argv[i] != '-' && suffix(argv[i], suffixes, 3) >= 0)
+ nf++;
+ argv[j++] = argv[i];
+ }
+ if ((cflag || Sflag) && outfile && nf != 1) {
+ fprintf(stderr, "%s: -o %s ignored\n", progname, outfile);
+ outfile = 0;
+ }
+ argv[j] = 0;
+ for (i = 0; include[i]; i++)
+ plist = append(include[i], plist);
+ if (ilist) {
+ List b = ilist;
+ do {
+ b = b->link;
+ plist = append(b->str, plist);
+ } while (b != ilist);
+ }
+ ilist = 0;
+ for (i = 1; argv[i]; i++)
+ if (*argv[i] == '-')
+ opt(argv[i]);
+ else {
+ char *name = exists(argv[i]);
+ if (name) {
+ if (strcmp(name, argv[i]) != 0
+ || nf > 1 && suffix(name, suffixes, 3) >= 0)
+ fprintf(stderr, "%s:\n", name);
+ filename(name, 0);
+ } else
+ error("can't find `%s'", argv[i]);
+ }
+ if (errcnt == 0 && !Eflag && !Sflag && !cflag && llist[1]) {
+ compose(ld, llist[0], llist[1],
+ append(outfile ? outfile : concat("a", first(suffixes[4])), 0));
+ if (callsys(av))
+ errcnt++;
+ }
+ rm(rmlist);
+ return errcnt ? EXIT_FAILURE : EXIT_SUCCESS;
+}
+
+/* alloc - allocate n bytes or die */
+static void *alloc(int n) {
+ static char *avail, *limit;
+
+ n = (n + sizeof(char *) - 1)&~(sizeof(char *) - 1);
+ if (n >= limit - avail) {
+ avail = malloc(n + 4*1024);
+ assert(avail);
+ limit = avail + n + 4*1024;
+ }
+ avail += n;
+ return avail - n;
+}
+
+/* append - append a node with string str onto list, return new list */
+static List append(char *str, List list) {
+ List p = alloc(sizeof *p);
+
+ p->str = str;
+ if (list) {
+ p->link = list->link;
+ list->link = p;
+ } else
+ p->link = p;
+ return p;
+}
+
+/* basepath - return base name for name, e.g. /usr/drh/foo.c => foo */
+char *basepath(char *name) {
+ char *s, *b, *t = 0;
+
+ for (b = s = name; *s; s++)
+ if (*s == '/' || *s == '\\') {
+ b = s + 1;
+ t = 0;
+ } else if (*s == '.')
+ t = s;
+ s = strsave(b);
+ if (t)
+ s[t-b] = 0;
+ return s;
+}
+
+#ifdef WIN32
+#include <process.h>
+#else
+#define _P_WAIT 0
+extern int fork(void);
+extern int wait(int *);
+extern void execv(const char *, char *[]);
+
+static int _spawnvp(int mode, const char *cmdname, char *argv[]) {
+ int pid, n, status;
+
+ switch (pid = fork()) {
+ case -1:
+ fprintf(stderr, "%s: no more processes\n", progname);
+ return 100;
+ case 0:
+ // TTimo removing hardcoded paths, searching in $PATH
+ execvp(cmdname, argv);
+ fprintf(stderr, "%s: ", progname);
+ perror(cmdname);
+ fflush(stdout);
+ exit(100);
+ }
+ while ((n = wait(&status)) != pid && n != -1)
+ ;
+ if (n == -1)
+ status = -1;
+ if (status&0377) {
+ fprintf(stderr, "%s: fatal error in %s\n", progname, cmdname);
+ status |= 0400;
+ }
+ return (status>>8)&0377;
+}
+#endif
+
+/* callsys - execute the command described by av[0...], return status */
+static int callsys(char **av) {
+ int i, status = 0;
+ static char **argv;
+ static int argc;
+
+ for (i = 0; av[i] != NULL; i++)
+ ;
+ if (i + 1 > argc) {
+ argc = i + 1;
+ if (argv == NULL)
+ argv = malloc(argc*sizeof *argv);
+ else
+ argv = realloc(argv, argc*sizeof *argv);
+ assert(argv);
+ }
+ for (i = 0; status == 0 && av[i] != NULL; ) {
+ int j = 0;
+ char *s;
+ for ( ; av[i] != NULL && (s = strchr(av[i], '\n')) == NULL; i++)
+ argv[j++] = av[i];
+ if (s != NULL) {
+ if (s > av[i])
+ argv[j++] = stringf("%.*s", s - av[i], av[i]);
+ if (s[1] != '\0')
+ av[i] = s + 1;
+ else
+ i++;
+ }
+ argv[j] = NULL;
+ if (verbose > 0) {
+ int k;
+ fprintf(stderr, "%s", argv[0]);
+ for (k = 1; argv[k] != NULL; k++)
+ fprintf(stderr, " %s", argv[k]);
+ fprintf(stderr, "\n");
+ }
+ if (verbose < 2)
+ status = _spawnvp(_P_WAIT, argv[0], argv);
+ if (status == -1) {
+ fprintf(stderr, "%s: ", progname);
+ perror(argv[0]);
+ }
+ }
+ return status;
+}
+
+/* concat - return concatenation of strings s1 and s2 */
+char *concat(char *s1, char *s2) {
+ int n = strlen(s1);
+ char *s = alloc(n + strlen(s2) + 1);
+
+ strcpy(s, s1);
+ strcpy(s + n, s2);
+ return s;
+}
+
+/* compile - compile src into dst, return status */
+static int compile(char *src, char *dst) {
+ compose(com, clist, append(src, 0), append(dst, 0));
+ return callsys(av);
+}
+
+/* compose - compose cmd into av substituting a, b, c for $1, $2, $3, resp. */
+static void compose(char *cmd[], List a, List b, List c) {
+ int i, j;
+ List lists[3];
+
+ lists[0] = a;
+ lists[1] = b;
+ lists[2] = c;
+ for (i = j = 0; cmd[i]; i++) {
+ char *s = strchr(cmd[i], '$');
+ if (s && isdigit(s[1])) {
+ int k = s[1] - '0';
+ assert(k >=1 && k <= 3);
+ if (b = lists[k-1]) {
+ b = b->link;
+ av[j] = alloc(strlen(cmd[i]) + strlen(b->str) - 1);
+ strncpy(av[j], cmd[i], s - cmd[i]);
+ av[j][s-cmd[i]] = '\0';
+ strcat(av[j], b->str);
+ strcat(av[j++], s + 2);
+ while (b != lists[k-1]) {
+ b = b->link;
+ assert(j < ac);
+ av[j++] = b->str;
+ };
+ }
+ } else if (*cmd[i]) {
+ assert(j < ac);
+ av[j++] = cmd[i];
+ }
+ }
+ av[j] = NULL;
+}
+
+/* error - issue error msg according to fmt, bump error count */
+static void error(char *fmt, char *msg) {
+ fprintf(stderr, "%s: ", progname);
+ fprintf(stderr, fmt, msg);
+ fprintf(stderr, "\n");
+ errcnt++;
+}
+
+/* exists - if `name' readable return its path name or return null */
+static char *exists(char *name) {
+ List b;
+
+ if ( (name[0] == '/' || name[0] == '\\' || name[2] == ':')
+ && access(name, 4) == 0)
+ return name;
+ if (!(name[0] == '/' || name[0] == '\\' || name[2] == ':')
+ && (b = lccinputs))
+ do {
+ b = b->link;
+ if (b->str[0]) {
+ char buf[1024];
+ sprintf(buf, "%s/%s", b->str, name);
+ if (access(buf, 4) == 0)
+ return strsave(buf);
+ } else if (access(name, 4) == 0)
+ return name;
+ } while (b != lccinputs);
+ if (verbose > 1)
+ return name;
+ return 0;
+}
+
+/* first - return first component in semicolon separated list */
+static char *first(char *list) {
+ char *s = strchr(list, ';');
+
+ if (s) {
+ char buf[1024];
+ strncpy(buf, list, s-list);
+ buf[s-list] = '\0';
+ return strsave(buf);
+ } else
+ return list;
+}
+
+/* filename - process file name argument `name', return status */
+static int filename(char *name, char *base) {
+ int status = 0;
+ static char *stemp, *itemp;
+
+ if (base == 0)
+ base = basepath(name);
+ switch (suffix(name, suffixes, 4)) {
+ case 0: /* C source files */
+ compose(cpp, plist, append(name, 0), 0);
+ if (Eflag) {
+ status = callsys(av);
+ break;
+ }
+ if (itemp == NULL)
+ itemp = tempname(first(suffixes[1]));
+ compose(cpp, plist, append(name, 0), append(itemp, 0));
+ status = callsys(av);
+ if (status == 0)
+ return filename(itemp, base);
+ break;
+ case 1: /* preprocessed source files */
+ if (Eflag)
+ break;
+ if (Sflag)
+ status = compile(name, outfile ? outfile : concat(base, first(suffixes[2])));
+ else if ((status = compile(name, stemp?stemp:(stemp=tempname(first(suffixes[2]))))) == 0)
+ return filename(stemp, base);
+ break;
+ case 2: /* assembly language files */
+ if (Eflag)
+ break;
+ if (!Sflag) {
+ char *ofile;
+ if (cflag && outfile)
+ ofile = outfile;
+ else if (cflag)
+ ofile = concat(base, first(suffixes[3]));
+ else
+ ofile = tempname(first(suffixes[3]));
+ compose(as, alist, append(name, 0), append(ofile, 0));
+ status = callsys(av);
+ if (!find(ofile, llist[1]))
+ llist[1] = append(ofile, llist[1]);
+ }
+ break;
+ case 3: /* object files */
+ if (!find(name, llist[1]))
+ llist[1] = append(name, llist[1]);
+ break;
+ default:
+ if (Eflag) {
+ compose(cpp, plist, append(name, 0), 0);
+ status = callsys(av);
+ }
+ llist[1] = append(name, llist[1]);
+ break;
+ }
+ if (status)
+ errcnt++;
+ return status;
+}
+
+/* find - find 1st occurrence of str in list, return list node or 0 */
+static List find(char *str, List list) {
+ List b;
+
+ if (b = list)
+ do {
+ if (strcmp(str, b->str) == 0)
+ return b;
+ } while ((b = b->link) != list);
+ return 0;
+}
+
+/* help - print help message */
+static void help(void) {
+ static char *msgs[] = {
+"", " [ option | file ]...\n",
+" except for -l, options are processed left-to-right before files\n",
+" unrecognized options are taken to be linker options\n",
+"-A warn about nonANSI usage; 2nd -A warns more\n",
+"-b emit expression-level profiling code; see bprint(1)\n",
+#ifdef sparc
+"-Bstatic -Bdynamic specify static or dynamic libraries\n",
+#endif
+"-Bdir/ use the compiler named `dir/rcc'\n",
+"-c compile only\n",
+"-dn set switch statement density to `n'\n",
+"-Dname -Dname=def define the preprocessor symbol `name'\n",
+"-E run only the preprocessor on the named C programs and unsuffixed files\n",
+"-g produce symbol table information for debuggers\n",
+"-help or -? print this message\n",
+"-Idir add `dir' to the beginning of the list of #include directories\n",
+"-lx search library `x'\n",
+"-N do not search the standard directories for #include files\n",
+"-n emit code to check for dereferencing zero pointers\n",
+"-O is ignored\n",
+"-o file leave the output in `file'\n",
+"-P print ANSI-style declarations for globals\n",
+"-p -pg emit profiling code; see prof(1) and gprof(1)\n",
+"-S compile to assembly language\n",
+#ifdef linux
+"-static specify static libraries (default is dynamic)\n",
+#endif
+"-t -tname emit function tracing calls to printf or to `name'\n",
+"-target name is ignored\n",
+"-tempdir=dir place temporary files in `dir/'", "\n"
+"-Uname undefine the preprocessor symbol `name'\n",
+"-v show commands as they are executed; 2nd -v suppresses execution\n",
+"-w suppress warnings\n",
+"-Woarg specify system-specific `arg'\n",
+"-W[pfal]arg pass `arg' to the preprocessor, compiler, assembler, or linker\n",
+ 0 };
+ int i;
+ char *s;
+
+ msgs[0] = progname;
+ for (i = 0; msgs[i]; i++) {
+ fprintf(stderr, "%s", msgs[i]);
+ if (strncmp("-tempdir", msgs[i], 8) == 0 && tempdir)
+ fprintf(stderr, "; default=%s", tempdir);
+ }
+#define xx(v) if (s = getenv(#v)) fprintf(stderr, #v "=%s\n", s)
+ xx(LCCINPUTS);
+ xx(LCCDIR);
+#ifdef WIN32
+ xx(include);
+ xx(lib);
+#endif
+#undef xx
+}
+
+/* initinputs - if LCCINPUTS or include is defined, use them to initialize various lists */
+static void initinputs(void) {
+ char *s = getenv("LCCINPUTS");
+ List list, b;
+
+ if (s == 0 || (s = inputs)[0] == 0)
+ s = ".";
+ if (s) {
+ lccinputs = path2list(s);
+ if (b = lccinputs)
+ do {
+ b = b->link;
+ if (strcmp(b->str, ".") != 0) {
+ ilist = append(concat("-I", b->str), ilist);
+ if (strstr(com[1], "win32") == NULL)
+ llist[0] = append(concat("-L", b->str), llist[0]);
+ } else
+ b->str = "";
+ } while (b != lccinputs);
+ }
+#ifdef WIN32
+ if (list = b = path2list(getenv("include")))
+ do {
+ b = b->link;
+ ilist = append(stringf("-I\"%s\"", b->str), ilist);
+ } while (b != list);
+#endif
+}
+
+/* interrupt - catch interrupt signals */
+static void interrupt(int n) {
+ rm(rmlist);
+ exit(n = 100);
+}
+
+/* opt - process option in arg */
+static void opt(char *arg) {
+ switch (arg[1]) { /* multi-character options */
+ case 'W': /* -Wxarg */
+ if (arg[2] && arg[3])
+ switch (arg[2]) {
+ case 'o':
+ if (option(&arg[3]))
+ return;
+ break;
+ case 'p':
+ plist = append(&arg[3], plist);
+ return;
+ case 'f':
+ if (strcmp(&arg[3], "-C") || option("-b")) {
+ clist = append(&arg[3], clist);
+ return;
+ }
+ break; /* and fall thru */
+ case 'a':
+ alist = append(&arg[3], alist);
+ return;
+ case 'l':
+ llist[0] = append(&arg[3], llist[0]);
+ return;
+ }
+ fprintf(stderr, "%s: %s ignored\n", progname, arg);
+ return;
+ case 'd': /* -dn */
+ arg[1] = 's';
+ clist = append(arg, clist);
+ return;
+ case 't': /* -t -tname -tempdir=dir */
+ if (strncmp(arg, "-tempdir=", 9) == 0)
+ tempdir = arg + 9;
+ else
+ clist = append(arg, clist);
+ return;
+ case 'p': /* -p -pg */
+ if (option(arg))
+ clist = append(arg, clist);
+ else
+ fprintf(stderr, "%s: %s ignored\n", progname, arg);
+ return;
+ case 'D': /* -Dname -Dname=def */
+ case 'U': /* -Uname */
+ case 'I': /* -Idir */
+ plist = append(arg, plist);
+ return;
+ case 'B': /* -Bdir -Bstatic -Bdynamic */
+#ifdef sparc
+ if (strcmp(arg, "-Bstatic") == 0 || strcmp(arg, "-Bdynamic") == 0)
+ llist[1] = append(arg, llist[1]);
+ else
+#endif
+ {
+ static char *path;
+ if (path)
+ error("-B overwrites earlier option", 0);
+ path = arg + 2;
+ if (strstr(com[1], "win32") != NULL)
+ com[0] = concat(replace(path, '/', '\\'), concat("rcc", first(suffixes[4])));
+ else
+ com[0] = concat(path, "rcc");
+ if (path[0] == 0)
+ error("missing directory in -B option", 0);
+ }
+ return;
+ case 'h':
+ if (strcmp(arg, "-help") == 0) {
+ static int printed = 0;
+ case '?':
+ if (!printed)
+ help();
+ printed = 1;
+ return;
+ }
+#ifdef linux
+ case 's':
+ if (strcmp(arg,"-static") == 0) {
+ if (!option(arg))
+ fprintf(stderr, "%s: %s ignored\n", progname, arg);
+ return;
+ }
+#endif
+ }
+ if (arg[2] == 0)
+ switch (arg[1]) { /* single-character options */
+ case 'S':
+ Sflag++;
+ return;
+ case 'O':
+ fprintf(stderr, "%s: %s ignored\n", progname, arg);
+ return;
+ case 'A': case 'n': case 'w': case 'P':
+ clist = append(arg, clist);
+ return;
+ case 'g': case 'b':
+ if (option(arg))
+ clist = append(arg[1] == 'g' ? "-g2" : arg, clist);
+ else
+ fprintf(stderr, "%s: %s ignored\n", progname, arg);
+ return;
+ case 'G':
+ if (option(arg)) {
+ clist = append("-g3", clist);
+ llist[0] = append("-N", llist[0]);
+ } else
+ fprintf(stderr, "%s: %s ignored\n", progname, arg);
+ return;
+ case 'E':
+ Eflag++;
+ return;
+ case 'c':
+ cflag++;
+ return;
+ case 'N':
+ if (strcmp(basepath(cpp[0]), "gcc-cpp") == 0)
+ plist = append("-nostdinc", plist);
+ include[0] = 0;
+ ilist = 0;
+ return;
+ case 'v':
+ if (verbose++ == 0) {
+ if (strcmp(basepath(cpp[0]), "gcc-cpp") == 0)
+ plist = append(arg, plist);
+ clist = append(arg, clist);
+ fprintf(stderr, "%s %s\n", progname, rcsid);
+ }
+ return;
+ }
+ if (cflag || Sflag || Eflag)
+ fprintf(stderr, "%s: %s ignored\n", progname, arg);
+ else
+ llist[1] = append(arg, llist[1]);
+}
+
+/* path2list - convert a colon- or semicolon-separated list to a list */
+static List path2list(const char *path) {
+ List list = NULL;
+ char sep = ':';
+
+ if (path == NULL)
+ return NULL;
+ if (strchr(path, ';'))
+ sep = ';';
+ while (*path) {
+ char *p, buf[512];
+ if (p = strchr(path, sep)) {
+ assert(p - path < sizeof buf);
+ strncpy(buf, path, p - path);
+ buf[p-path] = '\0';
+ } else {
+ assert(strlen(path) < sizeof buf);
+ strcpy(buf, path);
+ }
+ if (!find(buf, list))
+ list = append(strsave(buf), list);
+ if (p == 0)
+ break;
+ path = p + 1;
+ }
+ return list;
+}
+
+/* replace - copy str, then replace occurrences of from with to, return the copy */
+char *replace(const char *str, int from, int to) {
+ char *s = strsave(str), *p = s;
+
+ for ( ; (p = strchr(p, from)) != NULL; p++)
+ *p = to;
+ return s;
+}
+
+/* rm - remove files in list */
+static void rm(List list) {
+ if (list) {
+ List b = list;
+ if (verbose)
+ fprintf(stderr, "rm");
+ do {
+ if (verbose)
+ fprintf(stderr, " %s", b->str);
+ if (verbose < 2)
+ remove(b->str);
+ } while ((b = b->link) != list);
+ if (verbose)
+ fprintf(stderr, "\n");
+ }
+}
+
+/* strsave - return a saved copy of string str */
+char *strsave(const char *str) {
+ return strcpy(alloc(strlen(str)+1), str);
+}
+
+/* stringf - format and return a string */
+char *stringf(const char *fmt, ...) {
+ char buf[1024];
+ va_list ap;
+ int n;
+
+ va_start(ap, fmt);
+ n = vsprintf(buf, fmt, ap);
+ va_end(ap);
+ return strsave(buf);
+}
+
+/* suffix - if one of tails[0..n-1] holds a proper suffix of name, return its index */
+int suffix(char *name, char *tails[], int n) {
+ int i, len = strlen(name);
+
+ for (i = 0; i < n; i++) {
+ char *s = tails[i], *t;
+ for ( ; t = strchr(s, ';'); s = t + 1) {
+ int m = t - s;
+ if (len > m && strncmp(&name[len-m], s, m) == 0)
+ return i;
+ }
+ if (*s) {
+ int m = strlen(s);
+ if (len > m && strncmp(&name[len-m], s, m) == 0)
+ return i;
+ }
+ }
+ return -1;
+}
+
+/* tempname - generate a temporary file name in tempdir with given suffix */
+char *tempname(char *suffix) {
+ static int n;
+ char *name = stringf("%s/lcc%d%d%s", tempdir, getpid(), n++, suffix);
+
+ if (strstr(com[1], "win32") != NULL)
+ name = replace(name, '/', '\\');
+ rmlist = append(name, rmlist);
+ return name;
+}
diff --git a/lcc/etc/linux.c b/lcc/etc/linux.c
new file mode 100755
index 0000000..58a8b81
--- /dev/null
+++ b/lcc/etc/linux.c
@@ -0,0 +1,74 @@
+/* x86s running Linux */
+
+#include <string.h>
+
+static char rcsid[] = "Dummy rcsid";
+
+/*
+TTimo - 10-18-2001
+our binaries are named q3lcc q3rcc and q3cpp
+removed hardcoded paths
+removed __linux__ preprocessor define (confuses the preprocessor, we are doing bytecode!)
+*/
+
+#ifndef LCCDIR
+#define LCCDIR ""
+//#define LCCDIR "/usr/local/lib/lcc/"
+#endif
+
+char *suffixes[] = { ".c", ".i", ".asm", ".o", ".out", 0 };
+char inputs[256] = "";
+// TTimo experimental: do not compile with the __linux__ define, we are doing bytecode!
+char *cpp[] = { LCCDIR "q3cpp",
+ "-U__GNUC__", "-D_POSIX_SOURCE", "-D__STDC__=1", "-D__STRICT_ANSI__",
+ "-Dunix", "-Di386", "-Dlinux",
+ "-D__unix__", "-D__i386__", "-D__signed__=signed",
+ "$1", "$2", "$3", 0 };
+char *include[] = {"-I" LCCDIR "include", "-I" LCCDIR "gcc/include", "-I/usr/include",
+ "-I" SYSTEM "include", 0 };
+char *com[] = {LCCDIR "q3rcc", "-target=x86/linux", "$1", "$2", "$3", 0 };
+char *as[] = { "/usr/bin/as", "-o", "$3", "$1", "$2", 0 };
+// NOTE TTimo I don't think we have any use with the native linkage
+// our target is always bytecode..
+char *ld[] = {
+ /* 0 */ "/usr/bin/ld", "-m", "elf_i386", "-dynamic-linker",
+ /* 4 */ "/lib/ld-linux.so.2", "-o", "$3",
+ /* 7 */ "/usr/lib/crt1.o", "/usr/lib/crti.o",
+ /* 9 */ SYSTEM "crtbegin.o",
+ "$1", "$2",
+ /* 12 */ "-L" LCCDIR,
+ /* 13 */ "-llcc",
+ /* 14 */ "-L" LCCDIR "/gcc", "-lgcc", "-lc", "-lm",
+ /* 18 */ "",
+ /* 19 */ SYSTEM "crtend.o", "/usr/lib/crtn.o",
+ /* 20 */ "-L" SYSTEM,
+ 0 };
+
+extern char *concat(char *, char *);
+
+int option(char *arg) {
+ if (strncmp(arg, "-lccdir=", 8) == 0) {
+ cpp[0] = concat(&arg[8], "/gcc/cpp");
+ include[0] = concat("-I", concat(&arg[8], "/include"));
+ include[1] = concat("-I", concat(&arg[8], "/gcc/include"));
+ ld[9] = concat(&arg[8], "/gcc/crtbegin.o");
+ ld[12] = concat("-L", &arg[8]);
+ ld[14] = concat("-L", concat(&arg[8], "/gcc"));
+ ld[19] = concat(&arg[8], "/gcc/crtend.o");
+ com[0] = concat(&arg[8], "/rcc");
+ } else if (strcmp(arg, "-p") == 0 || strcmp(arg, "-pg") == 0) {
+ ld[7] = "/usr/lib/gcrt1.o";
+ ld[18] = "-lgmon";
+ } else if (strcmp(arg, "-b") == 0)
+ ;
+ else if (strcmp(arg, "-g") == 0)
+ ;
+ else if (strncmp(arg, "-ld=", 4) == 0)
+ ld[0] = &arg[4];
+ else if (strcmp(arg, "-static") == 0) {
+ ld[3] = "-static";
+ ld[4] = "";
+ } else
+ return 0;
+ return 1;
+}
diff --git a/lcc/etc/ops.c b/lcc/etc/ops.c
new file mode 100755
index 0000000..dd570b7
--- /dev/null
+++ b/lcc/etc/ops.c
@@ -0,0 +1,190 @@
+#include "c.h"
+
+/* ops [ {csilhfdxp}=n ]...
+ * prints lcc dag operator set for a given set of type sizes.
+ */
+
+
+static char list[] = { 'c', 's', 'i', 'l', 'h', 'f', 'd', 'x', 'p', 0 };
+static int sizes[] = { 1, 2, 4, 4, 8, 4, 8, 16, 8 };
+
+static int doop(int op, int type, const char *sz, const char *opname) {
+ int count = 0;
+ static int last;
+
+ if (op == LOAD)
+ return 0;
+ if (last != 0 && last != op)
+ printf("\n");
+ last = op;
+ if (type == B || type == V) {
+ printf(" %s=%d", opname, op + type);
+ count++;
+ } else {
+ int i, done = 0;
+ const char *s;
+ for (i = 0; sz[i] != '\0' && (s = strchr(list, sz[i])) != NULL; i++) {
+ int n = sizes[s-list];
+ if ((done&(1<<n)) == 0) {
+ printf(" %s%d=%d", opname, n, op + type + sizeop(n));
+ count++;
+ }
+ done |= 1<<n;
+ }
+ }
+ printf("\n");
+ return count;
+}
+
+int main(int argc, char *argv[]) {
+ int i, count = 0;
+
+ for (i = 1; i < argc; i++) {
+ char c, *s;
+ int n;
+ if (sscanf(argv[i], "%c=%d", &c, &n) == 2
+ && n > 0 && (s = strchr(list, c)) != NULL)
+ sizes[s-list] = n;
+ else {
+ fprintf(stderr, "usage: %s [ {csilhfdxp}=n ]...\n", argv[0]);
+ exit(EXIT_FAILURE);
+ }
+ }
+#define gop(x,n)
+#define op(x,t,s) count += doop(x,t,#s,#x #t);
+gop(CNST,1)
+ op(CNST,F,fdx)
+ op(CNST,I,csilh)
+ op(CNST,P,p)
+ op(CNST,U,csilh)
+gop(ARG,2)
+ op(ARG,B,-)
+ op(ARG,F,fdx)
+ op(ARG,I,ilh)
+ op(ARG,P,p)
+ op(ARG,U,ilh)
+gop(ASGN,3)
+ op(ASGN,B,-)
+ op(ASGN,F,fdx)
+ op(ASGN,I,csilh)
+ op(ASGN,P,p)
+ op(ASGN,U,csilh)
+gop(INDIR,4)
+ op(INDIR,B,-)
+ op(INDIR,F,fdx)
+ op(INDIR,I,csilh)
+ op(INDIR,P,p)
+ op(INDIR,U,csilh)
+gop(CVF,7)
+ op(CVF,F,fdx)
+ op(CVF,I,ilh)
+gop(CVI,8)
+ op(CVI,F,fdx)
+ op(CVI,I,csilh)
+ op(CVI,U,csilhp)
+gop(CVP,9)
+ op(CVP,U,p)
+gop(CVU,11)
+ op(CVU,I,csilh)
+ op(CVU,P,p)
+ op(CVU,U,csilh)
+gop(NEG,12)
+ op(NEG,F,fdx)
+ op(NEG,I,ilh)
+gop(CALL,13)
+ op(CALL,B,-)
+ op(CALL,F,fdx)
+ op(CALL,I,ilh)
+ op(CALL,P,p)
+ op(CALL,U,ilh)
+ op(CALL,V,-)
+gop(RET,15)
+ op(RET,F,fdx)
+ op(RET,I,ilh)
+ op(RET,P,p)
+ op(RET,U,ilh)
+ op(RET,V,-)
+gop(ADDRG,16)
+ op(ADDRG,P,p)
+gop(ADDRF,17)
+ op(ADDRF,P,p)
+gop(ADDRL,18)
+ op(ADDRL,P,p)
+gop(ADD,19)
+ op(ADD,F,fdx)
+ op(ADD,I,ilh)
+ op(ADD,P,p)
+ op(ADD,U,ilhp)
+gop(SUB,20)
+ op(SUB,F,fdx)
+ op(SUB,I,ilh)
+ op(SUB,P,p)
+ op(SUB,U,ilhp)
+gop(LSH,21)
+ op(LSH,I,ilh)
+ op(LSH,U,ilh)
+gop(MOD,22)
+ op(MOD,I,ilh)
+ op(MOD,U,ilh)
+gop(RSH,23)
+ op(RSH,I,ilh)
+ op(RSH,U,ilh)
+gop(BAND,24)
+ op(BAND,I,ilh)
+ op(BAND,U,ilh)
+gop(BCOM,25)
+ op(BCOM,I,ilh)
+ op(BCOM,U,ilh)
+gop(BOR,26)
+ op(BOR,I,ilh)
+ op(BOR,U,ilh)
+gop(BXOR,27)
+ op(BXOR,I,ilh)
+ op(BXOR,U,ilh)
+gop(DIV,28)
+ op(DIV,F,fdx)
+ op(DIV,I,ilh)
+ op(DIV,U,ilh)
+gop(MUL,29)
+ op(MUL,F,fdx)
+ op(MUL,I,ilh)
+ op(MUL,U,ilh)
+gop(EQ,30)
+ op(EQ,F,fdx)
+ op(EQ,I,ilh)
+ op(EQ,U,ilhp)
+gop(GE,31)
+ op(GE,F,fdx)
+ op(GE,I,ilh)
+ op(GE,U,ilhp)
+gop(GT,32)
+ op(GT,F,fdx)
+ op(GT,I,ilh)
+ op(GT,U,ilhp)
+gop(LE,33)
+ op(LE,F,fdx)
+ op(LE,I,ilh)
+ op(LE,U,ilhp)
+gop(LT,34)
+ op(LT,F,fdx)
+ op(LT,I,ilh)
+ op(LT,U,ilhp)
+gop(NE,35)
+ op(NE,F,fdx)
+ op(NE,I,ilh)
+ op(NE,U,ilhp)
+gop(JUMP,36)
+ op(JUMP,V,-)
+gop(LABEL,37)
+ op(LABEL,V,-)
+gop(LOAD,14)
+ op(LOAD,B,-)
+ op(LOAD,F,fdx)
+ op(LOAD,I,csilh)
+ op(LOAD,P,p)
+ op(LOAD,U,csilhp)
+#undef gop
+#undef op
+ fprintf(stderr, "%d operators\n", count);
+ return EXIT_SUCCESS;
+}
diff --git a/lcc/etc/osf.c b/lcc/etc/osf.c
new file mode 100755
index 0000000..4c57b09
--- /dev/null
+++ b/lcc/etc/osf.c
@@ -0,0 +1,53 @@
+/* DEC ALPHAs running OSF/1 V3.2A (Rev. 17) at Princeton University */
+
+#include <string.h>
+
+
+#ifndef LCCDIR
+#define LCCDIR "/usr/local/lib/lcc/"
+#endif
+
+char *suffixes[] = { ".c", ".i", ".s", ".o", ".out", 0 };
+char inputs[256] = "";
+char *cpp[] = {
+ LCCDIR "cpp", "-D__STDC__=1",
+ "-DLANGUAGE_C", "-D__LANGUAGE_C__",
+ "-D_unix", "-D__unix__", "-D_osf", "-D__osf__", "-Dunix",
+ "-Dalpha", "-D_alpha", "-D__alpha",
+ "-D__SYSTYPE_BSD", "-D_SYSTYPE_BSD",
+ "$1", "$2", "$3", 0 };
+char *com[] = { LCCDIR "rcc", "-target=alpha/osf", "$1", "$2", "$3", "", 0 };
+char *include[] = { "-I" LCCDIR "include", "-I/usr/local/include",
+ "-I/usr/include", 0 };
+char *as[] = { "/bin/as", "-o", "$3", "", "$1", "-nocpp", "$2", 0 };
+char *ld[] = { "/usr/bin/ld", "-o", "$3", "/usr/lib/cmplrs/cc/crt0.o",
+ "$1", "$2", "", "", "-L" LCCDIR, "-llcc", "-lm", "-lc", 0 };
+
+extern char *concat(char *, char *);
+extern int access(const char *, int);
+
+int option(char *arg) {
+ if (strncmp(arg, "-lccdir=", 8) == 0) {
+ cpp[0] = concat(&arg[8], "/cpp");
+ include[0] = concat("-I", concat(&arg[8], "/include"));
+ com[0] = concat(&arg[8], "/rcc");
+ ld[8] = concat("-L", &arg[8]);
+ } else if (strcmp(arg, "-g4") == 0
+ && access("/u/drh/lib/alpha/rcc", 4) == 0
+ && access("/u/drh/book/cdb/alpha/osf/cdbld", 4) == 0) {
+ com[0] = "/u/drh/lib/alpha/rcc";
+ com[5] = "-g4";
+ ld[0] = "/u/drh/book/cdb/alpha/osf/cdbld";
+ ld[1] = "-o";
+ ld[2] = "$3";
+ ld[3] = "$1";
+ ld[4] = "$2";
+ ld[5] = 0;
+ } else if (strcmp(arg, "-g") == 0)
+ return 1;
+ else if (strcmp(arg, "-b") == 0)
+ ;
+ else
+ return 0;
+ return 1;
+}
diff --git a/lcc/etc/solaris.c b/lcc/etc/solaris.c
new file mode 100755
index 0000000..453b101
--- /dev/null
+++ b/lcc/etc/solaris.c
@@ -0,0 +1,50 @@
+/* SPARCs running Solaris 2.5.1 at CS Dept., Princeton University */
+
+#include <string.h>
+
+
+#ifndef LCCDIR
+#define LCCDIR "/usr/local/lib/lcc/"
+#endif
+#ifndef SUNDIR
+#define SUNDIR "/opt/SUNWspro/SC4.2/lib/"
+#endif
+
+char *suffixes[] = { ".c", ".i", ".s", ".o", ".out", 0 };
+char inputs[256] = "";
+char *cpp[] = { LCCDIR "cpp",
+ "-D__STDC__=1", "-Dsparc", "-D__sparc__", "-Dsun", "-D__sun__", "-Dunix",
+ "$1", "$2", "$3", 0 };
+char *include[] = { "-I" LCCDIR "include", "-I/usr/local/include",
+ "-I/usr/include", 0 };
+char *com[] = { LCCDIR "rcc", "-target=sparc/solaris",
+ "$1", "$2", "$3", 0 };
+char *as[] = { "/usr/ccs/bin/as", "-Qy", "-s", "-o", "$3", "$1", "$2", 0 };
+char *ld[] = { "/usr/ccs/bin/ld", "-o", "$3", "$1",
+ SUNDIR "crti.o", SUNDIR "crt1.o",
+ SUNDIR "values-xa.o", "$2", "",
+ "-Y", "P," SUNDIR ":/usr/ccs/lib:/usr/lib", "-Qy",
+ "-L" LCCDIR, "-llcc", "-lm", "-lc", SUNDIR "crtn.o", 0 };
+
+extern char *concat(char *, char *);
+
+int option(char *arg) {
+ if (strncmp(arg, "-lccdir=", 8) == 0) {
+ cpp[0] = concat(&arg[8], "/cpp");
+ include[0] = concat("-I", concat(&arg[8], "/include"));
+ ld[12] = concat("-L", &arg[8]);
+ com[0] = concat(&arg[8], "/rcc");
+ } else if (strcmp(arg, "-g") == 0)
+ ;
+ else if (strcmp(arg, "-p") == 0) {
+ ld[5] = SUNDIR "mcrt1.o";
+ ld[10] = "P," SUNDIR "libp:/usr/ccs/lib/libp:/usr/lib/libp:"
+ SUNDIR ":/usr/ccs/lib:/usr/lib";
+ } else if (strcmp(arg, "-b") == 0)
+ ;
+ else if (strncmp(arg, "-ld=", 4) == 0)
+ ld[0] = &arg[4];
+ else
+ return 0;
+ return 1;
+}
diff --git a/lcc/etc/win32.c b/lcc/etc/win32.c
new file mode 100755
index 0000000..097fa42
--- /dev/null
+++ b/lcc/etc/win32.c
@@ -0,0 +1,43 @@
+/* x86s running MS Windows NT 4.0 */
+
+#include <string.h>
+
+
+#ifndef LCCDIR
+// JDC #define LCCDIR "\\progra~1\\lcc\\4.1\\bin\\"
+//#define LCCDIR "\\quake3\\source\\lcc\\bin\\" // JDC
+// TTimo: q3cpp q3rcc & no hardcoded paths
+#define LCCDIR ""
+#endif
+
+char *suffixes[] = { ".c;.C", ".i;.I", ".asm;.ASM;.s;.S", ".obj;.OBJ", ".exe", 0 };
+char inputs[256] = "";
+char *cpp[] = { LCCDIR "q3cpp", "-D__STDC__=1", "-Dwin32", "-D_WIN32", "-D_M_IX86",
+ "$1", "$2", "$3", 0 };
+char *include[] = { "-I" LCCDIR "include", 0 };
+char *com[] = { LCCDIR "q3rcc", "-target=x86/win32", "$1", "$2", "$3", 0 };
+char *as[] = { "ml", "-nologo", "-c", "-Cp", "-coff", "-Fo$3", "$1", "$2", 0 };
+char *ld[] = { "link", "-nologo",
+ "-align:0x1000", "-subsystem:console", "-entry:mainCRTStartup",
+ "$2", "-OUT:$3", "$1", LCCDIR "liblcc.lib", "libc.lib", "kernel32.lib", 0 };
+
+extern char *concat(char *, char *);
+extern char *replace(const char *, int, int);
+
+int option(char *arg) {
+ if (strncmp(arg, "-lccdir=", 8) == 0) {
+ arg = replace(arg + 8, '/', '\\');
+ if (arg[strlen(arg)-1] == '\\')
+ arg[strlen(arg)-1] = '\0';
+ cpp[0] = concat(arg, "\\cpp.exe");
+ include[0] = concat("-I", concat(arg, "\\include"));
+ com[0] = concat(arg, "\\rcc.exe");
+ ld[8] = concat(arg, "\\liblcc.lib");
+ } else if (strcmp(arg, "-b") == 0)
+ ;
+ else if (strncmp(arg, "-ld=", 4) == 0)
+ ld[0] = &arg[4];
+ else
+ return 0;
+ return 1;
+}
diff --git a/lcc/include/alpha/osf/assert.h b/lcc/include/alpha/osf/assert.h
new file mode 100755
index 0000000..e7f8777
--- /dev/null
+++ b/lcc/include/alpha/osf/assert.h
@@ -0,0 +1,14 @@
+#ifndef __ASSERT
+#define __ASSERT
+
+void assert(int);
+
+#endif /* __ASSERT */
+
+#undef assert
+#ifdef NDEBUG
+#define assert(ignore) ((void)0)
+#else
+extern void __assert(char *, char *, unsigned);
+#define assert(e) ((void)((e)||(__assert(#e, __FILE__, __LINE__),0)))
+#endif /* NDEBUG */
diff --git a/lcc/include/alpha/osf/ctype.h b/lcc/include/alpha/osf/ctype.h
new file mode 100755
index 0000000..86b8149
--- /dev/null
+++ b/lcc/include/alpha/osf/ctype.h
@@ -0,0 +1,25 @@
+#ifndef __CTYPE
+#define __CTYPE
+
+extern int isalnum(int);
+extern int isalpha(int);
+extern int iscntrl(int);
+extern int isdigit(int);
+extern int isgraph(int);
+extern int islower(int);
+extern int isprint(int);
+extern int ispunct(int);
+extern int isspace(int);
+extern int isupper(int);
+extern int isxdigit(int);
+extern int tolower(int);
+extern int toupper(int);
+
+#define __U 01
+#define __L 02
+#define __N 04
+#define __S 010
+#define __P 020
+#define __C 040
+
+#endif /* __CTYPE */
diff --git a/lcc/include/alpha/osf/errno.h b/lcc/include/alpha/osf/errno.h
new file mode 100755
index 0000000..5ab3f0f
--- /dev/null
+++ b/lcc/include/alpha/osf/errno.h
@@ -0,0 +1,8 @@
+#ifndef __ERRNO
+#define __ERRNO
+
+#define EDOM 33
+#define ERANGE 34
+extern int errno;
+
+#endif /* __ERRNO */
diff --git a/lcc/include/alpha/osf/float.h b/lcc/include/alpha/osf/float.h
new file mode 100755
index 0000000..8a8ddb1
--- /dev/null
+++ b/lcc/include/alpha/osf/float.h
@@ -0,0 +1,37 @@
+#ifndef __FLOAT
+#define __FLOAT
+
+#define FLT_ROUNDS 1
+#define FLT_RADIX 2
+
+#define FLT_DIG 6
+#define FLT_EPSILON 1.19209289550781250000e-07
+#define FLT_MANT_DIG 24
+#define FLT_MAX 3.40282346638528860000e+38
+#define FLT_MAX_10_EXP 38
+#define FLT_MAX_EXP 128
+#define FLT_MIN 1.17549435082228750000e-38
+#define FLT_MIN_10_EXP -37
+#define FLT_MIN_EXP -125
+
+#define DBL_DIG 15
+#define DBL_EPSILON 2.22044604925031310000e-16
+#define DBL_MANT_DIG 53
+#define DBL_MAX 1.79769313486231570000e+308
+#define DBL_MAX_10_EXP 308
+#define DBL_MAX_EXP 1024
+#define DBL_MIN 2.22507385850720140000e-308
+#define DBL_MIN_10_EXP -307
+#define DBL_MIN_EXP -1021
+
+#define LDBL_MANT_DIG DBL_MANT_DIG
+#define LDBL_EPSILON DBL_EPSILON
+#define LDBL_DIG DBL_DIG
+#define LDBL_MIN_EXP DBL_MIN_EXP
+#define LDBL_MIN DBL_MIN
+#define LDBL_MIN_10_EXP DBL_MIN_10_EXP
+#define LDBL_MAX_EXP DBL_MAX_EXP
+#define LDBL_MAX DBL_MAX
+#define LDBL_MAX_10_EXP DBL_MAX_10_EXP
+
+#endif /* __FLOAT */
diff --git a/lcc/include/alpha/osf/limits.h b/lcc/include/alpha/osf/limits.h
new file mode 100755
index 0000000..06b8e28
--- /dev/null
+++ b/lcc/include/alpha/osf/limits.h
@@ -0,0 +1,24 @@
+#ifndef __LIMITS
+#define __LIMITS
+
+#define CHAR_BIT 8
+#define MB_LEN_MAX 1
+
+#define UCHAR_MAX 0xff
+#define USHRT_MAX 0xffff
+#define UINT_MAX (~0U)
+#define ULONG_MAX (~0UL)
+
+#define CHAR_MAX SCHAR_MAX
+#define SCHAR_MAX 0x7f
+#define SHRT_MAX 0x7fff
+#define INT_MAX 0x7fffffff
+#define LONG_MAX 0x7fffffffffffffffL
+
+#define CHAR_MIN SCHAR_MIN
+#define SCHAR_MIN (-SCHAR_MAX-1)
+#define SHRT_MIN (-SHRT_MAX-1)
+#define INT_MIN (-INT_MAX-1)
+#define LONG_MIN (-LONG_MAX-1)
+
+#endif /* __LIMITS */
diff --git a/lcc/include/alpha/osf/locale.h b/lcc/include/alpha/osf/locale.h
new file mode 100755
index 0000000..a861b47
--- /dev/null
+++ b/lcc/include/alpha/osf/locale.h
@@ -0,0 +1,36 @@
+#ifndef __LOCALE
+#define __LOCALE
+
+#define LC_ALL 0
+#define LC_COLLATE 1
+#define LC_CTYPE 2
+#define LC_MONETARY 3
+#define LC_NUMERIC 4
+#define LC_TIME 5
+#define NULL 0
+
+struct lconv {
+ char *decimal_point;
+ char *thousands_sep;
+ char *grouping;
+ char *int_curr_symbol;
+ char *currency_symbol;
+ char *mon_decimal_point;
+ char *mon_thousands_sep;
+ char *mon_grouping;
+ char *positive_sign;
+ char *negative_sign;
+ char int_frac_digits;
+ char frac_digits;
+ char p_cs_precedes;
+ char p_sep_by_space;
+ char n_cs_precedes;
+ char n_sep_by_space;
+ char p_sign_posn;
+ char n_sign_posn;
+};
+
+char *setlocale(int, const char *);
+struct lconv *localeconv(void);
+
+#endif /* __LOCALE */
diff --git a/lcc/include/alpha/osf/math.h b/lcc/include/alpha/osf/math.h
new file mode 100755
index 0000000..bb39d69
--- /dev/null
+++ b/lcc/include/alpha/osf/math.h
@@ -0,0 +1,29 @@
+#ifndef __MATH
+#define __MATH
+
+#define HUGE_VAL 1.79769313486231570000e+308
+
+extern double acos(double);
+extern double asin(double);
+extern double atan(double);
+extern double atan2(double, double);
+extern double cos(double);
+extern double sin(double);
+extern double tan(double);
+extern double cosh(double);
+extern double sinh(double);
+extern double tanh(double);
+extern double exp(double);
+extern double frexp(double, int *);
+extern double ldexp(double, int);
+extern double log(double);
+extern double log10(double);
+extern double modf(double, double *);
+extern double pow(double, double);
+extern double sqrt(double);
+extern double ceil(double);
+extern double fabs(double);
+extern double floor(double);
+extern double fmod(double, double);
+
+#endif /* __MATH */
diff --git a/lcc/include/alpha/osf/setjmp.h b/lcc/include/alpha/osf/setjmp.h
new file mode 100755
index 0000000..83216dd
--- /dev/null
+++ b/lcc/include/alpha/osf/setjmp.h
@@ -0,0 +1,10 @@
+#ifndef __SETJMP
+#define __SETJMP
+
+
+
+typedef int jmp_buf[35+1+48];
+int setjmp(jmp_buf);
+void longjmp(jmp_buf, int);
+
+#endif /* __SETJMP */
diff --git a/lcc/include/alpha/osf/signal.h b/lcc/include/alpha/osf/signal.h
new file mode 100755
index 0000000..22f98bc
--- /dev/null
+++ b/lcc/include/alpha/osf/signal.h
@@ -0,0 +1,20 @@
+#ifndef __SIGNAL
+#define __SIGNAL
+
+typedef int sig_atomic_t;
+
+#define SIG_DFL ((void (*)(int))0)
+#define SIG_ERR ((void (*)(int))-1)
+#define SIG_IGN ((void (*)(int))1)
+
+#define SIGABRT 6
+#define SIGFPE 8
+#define SIGILL 4
+#define SIGINT 2
+#define SIGSEGV 11
+#define SIGTERM 15
+
+void (*signal(int, void (*)(int)))(int);
+int raise(int);
+
+#endif /* __SIGNAL */
diff --git a/lcc/include/alpha/osf/stdarg.h b/lcc/include/alpha/osf/stdarg.h
new file mode 100755
index 0000000..1b4947e
--- /dev/null
+++ b/lcc/include/alpha/osf/stdarg.h
@@ -0,0 +1,28 @@
+#ifndef __STDARG
+#define __STDARG
+
+#if !defined(_VA_LIST)
+#define _VA_LIST
+typedef struct {
+ char *_a0; /* pointer to first homed integer arg */
+ int _offset; /* byte offset of next param */
+ float _tmp;
+} __va_list;
+#endif
+typedef __va_list va_list;
+
+#define va_start(list, start) ((void)( \
+ (list)._a0 = (__typecode(__firstarg)==1 ? \
+ (char*)&__firstarg+48 : (char *)&__firstarg), \
+ (list)._offset = (__typecode(start)==1 ? \
+ (char*)&start+56 : (char *)&start+8)-(list)._a0))
+#define va_arg(list, mode) (*(mode *)( \
+ (list)._offset += (int)((sizeof(mode)+7)&~7), \
+ (__typecode(mode)==1 && sizeof(mode)==4) ? \
+ ((list)._tmp = (float)*(double *)((list)._a0 + (list)._offset - \
+ ((list)._offset <= 48 ? 56 : 8))), (char *)&(list)._tmp : \
+ (__typecode(mode)==1 && (list)._offset <= 48) ? \
+ (list)._a0 + (list)._offset - 56 : \
+ (list)._a0 + (list)._offset - (int)((sizeof(mode)+7)&~7)))
+#define va_end(list) ((void)0)
+#endif
diff --git a/lcc/include/alpha/osf/stddef.h b/lcc/include/alpha/osf/stddef.h
new file mode 100755
index 0000000..459bfd6
--- /dev/null
+++ b/lcc/include/alpha/osf/stddef.h
@@ -0,0 +1,22 @@
+#ifndef __STDDEF
+#define __STDDEF
+
+
+#define NULL 0
+#define offsetof(ty,mem) ((size_t)((char*)&((ty*)0)->mem - (char*)0))
+
+typedef long ptrdiff_t;
+
+#if !defined(_SIZE_T) && !defined(_SIZE_T_)
+#define _SIZE_T
+#define _SIZE_T_
+typedef unsigned long size_t;
+#endif
+
+#if !defined(_WCHAR_T) && !defined(_WCHAR_T_)
+#define _WCHAR_T
+#define _WCHAR_T_
+typedef unsigned short wchar_t;
+#endif
+
+#endif /* __STDDEF */
diff --git a/lcc/include/alpha/osf/stdio.h b/lcc/include/alpha/osf/stdio.h
new file mode 100755
index 0000000..6777a8f
--- /dev/null
+++ b/lcc/include/alpha/osf/stdio.h
@@ -0,0 +1,113 @@
+#ifndef __STDIO
+#define __STDIO
+
+#define _IOFBF 0
+#define _IOLBF 0200
+#define _IONBF 04
+#define BUFSIZ 8192
+#define EOF (-1)
+
+typedef struct _iobuf {
+ int _cnt;
+ unsigned char *_ptr;
+ unsigned char *_base;
+ int _bufsiz;
+ short _flag;
+ short _file;
+ char *__newbase;
+ void *_lock;
+ unsigned char *_bufendp;
+} FILE;
+extern FILE _iob[];
+#define FILENAME_MAX 255
+#define FOPEN_MAX 64
+
+#if !defined(_FPOS_T) && !defined(_FPOS_T_)
+#define _FPOS_T
+#define _FPOS_T_
+typedef long fpos_t;
+#endif
+
+#define L_tmpnam 21
+#define NULL 0
+#define SEEK_CUR 1
+#define SEEK_END 2
+#define SEEK_SET 0
+
+#if !defined(_SIZE_T) && !defined(_SIZE_T_)
+#define _SIZE_T
+#define _SIZE_T_
+typedef unsigned long size_t;
+#endif
+
+#if !defined(_VA_LIST)
+#define _VA_LIST
+typedef struct {
+ char *_a0; /* pointer to first homed integer arg */
+ int _offset; /* byte offset of next param */
+ float _tmp;
+} __va_list;
+#endif
+
+#define stderr (&_iob[2])
+#define stdin (&_iob[0])
+#define stdout (&_iob[1])
+#define TMP_MAX 16384
+
+extern int remove(const char *);
+extern int rename(const char *, const char *);
+extern FILE *tmpfile(void);
+extern char *tmpnam(char *);
+extern int fclose(FILE *);
+extern int fflush(FILE *);
+extern FILE *fopen(const char *, const char *);
+extern FILE *freopen(const char *, const char *, FILE *);
+extern void setbuf(FILE *, char *);
+extern int setvbuf(FILE *, char *, int, size_t);
+extern int fprintf(FILE *, const char *, ...);
+extern int fscanf(FILE *, const char *, ...);
+extern int printf(const char *, ...);
+extern int scanf(const char *, ...);
+extern int sprintf(char *, const char *, ...);
+extern int sscanf(const char *, const char *, ...);
+extern int vfprintf(FILE *, const char *, __va_list);
+extern int vprintf(const char *, __va_list);
+extern int vsprintf(char *, const char *, __va_list);
+extern int fgetc(FILE *);
+extern char *fgets(char *, int, FILE *);
+extern int fputc(int, FILE *);
+extern int fputs(const char *, FILE *);
+extern int getc(FILE *);
+extern int getchar(void);
+extern char *gets(char *);
+extern int putc(int, FILE *);
+extern int putchar(int);
+extern int puts(const char *);
+extern int ungetc(int, FILE *);
+extern size_t fread(void *, size_t, size_t, FILE *);
+extern size_t fwrite(const void *, size_t, size_t, FILE *);
+extern int fgetpos(FILE *, fpos_t *);
+extern int fseek(FILE *, long int, int);
+extern int fsetpos(FILE *, const fpos_t *);
+extern long int ftell(FILE *);
+extern void rewind(FILE *);
+extern void clearerr(FILE *);
+extern int feof(FILE *);
+extern int ferror(FILE *);
+extern void perror(const char *);
+
+#define _IOEOF 020
+#define _IOERR 040
+
+#define getc(p) (--(p)->_cnt < 0 ? _filbuf(p) : (int) *(p)->_ptr++)
+#define putc(x, p) (--(p)->_cnt < 0 ? \
+ _flsbuf((unsigned char) (x), p) : \
+ (int) (*(p)->_ptr++ = (unsigned char) (x)))
+extern int _filbuf(FILE *), _flsbuf(unsigned, FILE *);
+#define feof(p) ((p)->_flag&_IOEOF)
+#define ferror(p) ((p)->_flag&_IOERR)
+#define clearerr(p) ((p)->_flag &= ~(_IOERR|_IOEOF))
+#define getchar() getc(stdin)
+#define putchar(x) putc((x),stdout)
+
+#endif /* __STDIO */
diff --git a/lcc/include/alpha/osf/stdlib.h b/lcc/include/alpha/osf/stdlib.h
new file mode 100755
index 0000000..e224f65
--- /dev/null
+++ b/lcc/include/alpha/osf/stdlib.h
@@ -0,0 +1,54 @@
+#ifndef __STDLIB
+#define __STDLIB
+
+#define EXIT_FAILURE 1
+#define EXIT_SUCCESS 0
+#define MB_CUR_MAX 1
+#define NULL 0
+#define RAND_MAX 32767
+
+typedef struct { int quot, rem; } div_t;
+typedef struct { long quot, rem; } ldiv_t;
+
+#if !defined(_SIZE_T) && !defined(_SIZE_T_)
+#define _SIZE_T
+#define _SIZE_T_
+typedef unsigned long size_t;
+#endif
+
+#if !defined(_WCHAR_T) && !defined(_WCHAR_T_)
+#define _WCHAR_T
+#define _WCHAR_T_
+typedef unsigned char wchar_t;
+#endif
+
+extern double atof(const char *);
+extern int atoi(const char *);
+extern long int atol(const char *);
+extern double strtod(const char *, char **);
+extern long int strtol(const char *, char **, int);
+extern unsigned long int strtoul(const char *, char **, int);
+extern int rand(void);
+extern void srand(unsigned int);
+extern void *calloc(size_t, size_t);
+extern void free(void *);
+extern void *malloc(size_t);
+extern void *realloc(void *, size_t);
+extern void abort(void);
+extern int atexit(void (*)(void));
+extern void exit(int);
+extern char *getenv(const char *);
+extern int system(const char *);
+extern void *bsearch(const void *, const void *, size_t, size_t, int (*)(const void *, const void *));
+extern void qsort(void *, size_t, size_t, int (*)(const void *, const void *));
+extern int abs(int);
+extern div_t div(int, int);
+extern long int labs(long int);
+extern ldiv_t ldiv(long int, long int);
+extern int mblen(const char *, size_t);
+extern int mbtowc(wchar_t *, const char *, size_t);
+extern int wctomb(char *, wchar_t);
+extern size_t mbstowcs(wchar_t *, const char *, size_t);
+extern size_t wcstombs(char *, const wchar_t *, size_t);
+
+#endif /* __STDLIB */
diff --git a/lcc/include/alpha/osf/string.h b/lcc/include/alpha/osf/string.h
new file mode 100755
index 0000000..f19b1e4
--- /dev/null
+++ b/lcc/include/alpha/osf/string.h
@@ -0,0 +1,35 @@
+#ifndef __STRING
+#define __STRING
+
+#define NULL 0
+
+#if !defined(_SIZE_T) && !defined(_SIZE_T_)
+#define _SIZE_T
+#define _SIZE_T_
+typedef unsigned long size_t;
+#endif
+
+void *memcpy(void *, const void *, size_t);
+void *memmove(void *, const void *, size_t);
+char *strcpy(char *, const char *);
+char *strncpy(char *, const char *, size_t);
+char *strcat(char *, const char *);
+char *strncat(char *, const char *, size_t);
+int memcmp(const void *, const void *, size_t);
+int strcmp(const char *, const char *);
+int strcoll(const char *, const char *);
+int strncmp(const char *, const char *, size_t);
+size_t strxfrm(char *, const char *, size_t);
+void *memchr(const void *, int, size_t);
+char *strchr(const char *, int);
+size_t strcspn(const char *, const char *);
+char *strpbrk(const char *, const char *);
+char *strrchr(const char *, int);
+size_t strspn(const char *, const char *);
+char *strstr(const char *, const char *);
+char *strtok(char *, const char *);
+void *memset(void *, int, size_t);
+char *strerror(int);
+size_t strlen(const char *);
+
+#endif /* __STRING */
diff --git a/lcc/include/alpha/osf/time.h b/lcc/include/alpha/osf/time.h
new file mode 100755
index 0000000..019c624
--- /dev/null
+++ b/lcc/include/alpha/osf/time.h
@@ -0,0 +1,50 @@
+#ifndef __TIME
+#define __TIME
+
+#define CLOCKS_PER_SEC 1000000
+#ifndef NULL
+#define NULL 0
+#endif
+
+#if !defined(_CLOCK_T) && !defined(_CLOCK_T_)
+#define _CLOCK_T
+#define _CLOCK_T_
+typedef long clock_t;
+#endif
+
+#if !defined(_TIME_T) && !defined(_TIME_T_)
+#define _TIME_T
+#define _TIME_T_
+typedef long time_t;
+#endif
+
+#if !defined(_SIZE_T) && !defined(_SIZE_T_)
+#define _SIZE_T
+#define _SIZE_T_
+typedef unsigned long size_t;
+#endif
+
+struct tm {
+ int tm_sec;
+ int tm_min;
+ int tm_hour;
+ int tm_mday;
+ int tm_mon;
+ int tm_year;
+ int tm_wday;
+ int tm_yday;
+ int tm_isdst;
+long __tm_gmtoff;
+ char *__tm_zone;
+};
+extern clock_t clock(void);
+extern double difftime(time_t, time_t);
+extern time_t mktime(struct tm *);
+extern time_t time(time_t *);
+extern char *asctime(const struct tm *);
+extern char *ctime(const time_t *);
+extern struct tm *gmtime(const time_t *);
+extern struct tm *localtime(const time_t *);
+extern size_t strftime(char *, size_t, const char *, const struct tm *);
+
+#endif /* __TIME */
diff --git a/lcc/include/mips/irix/assert.h b/lcc/include/mips/irix/assert.h
new file mode 100755
index 0000000..5b4776c
--- /dev/null
+++ b/lcc/include/mips/irix/assert.h
@@ -0,0 +1,14 @@
+#ifndef __ASSERT
+#define __ASSERT
+
+void assert(int);
+
+#endif /* __ASSERT */
+
+#undef assert
+#ifdef NDEBUG
+#define assert(ignore) ((void)0)
+#else
+extern int _assert(char *, char *, unsigned);
+#define assert(e) ((void)((e)||_assert(#e, __FILE__, __LINE__)))
+#endif /* NDEBUG */
diff --git a/lcc/include/mips/irix/ctype.h b/lcc/include/mips/irix/ctype.h
new file mode 100755
index 0000000..7239547
--- /dev/null
+++ b/lcc/include/mips/irix/ctype.h
@@ -0,0 +1,40 @@
+#ifndef __CTYPE
+#define __CTYPE
+
+extern int isalnum(int);
+extern int isalpha(int);
+extern int iscntrl(int);
+extern int isdigit(int);
+extern int isgraph(int);
+extern int islower(int);
+extern int isprint(int);
+extern int ispunct(int);
+extern int isspace(int);
+extern int isupper(int);
+extern int isxdigit(int);
+extern int tolower(int);
+extern int toupper(int);
+
+#define __U 01
+#define __L 02
+#define __N 04
+#define __S 010
+#define __P 020
+#define __C 040
+#define __B 0100
+#define __X 0200
+
+extern unsigned char _ctype[];
+#define isalnum(c) ((_ctype+1)[c]&(__U|__L|__N))
+#define isalpha(c) ((_ctype+1)[c]&(__U|__L))
+#define iscntrl(c) ((_ctype+1)[c]&__C)
+#define isdigit(c) ((_ctype+1)[c]&__N)
+#define isgraph(c) ((_ctype+1)[c]&(__P|__U|__L|__N))
+#define islower(c) ((_ctype+1)[c]&__L)
+#define isprint(c) ((_ctype+1)[c]&(__P|__U|__L|__N|__B))
+#define ispunct(c) ((_ctype+1)[c]&__P)
+#define isspace(c) ((_ctype+1)[c]&__S)
+#define isupper(c) ((_ctype+1)[c]&__U)
+#define isxdigit(c) ((_ctype+1)[c]&__X)
+
+#endif /* __CTYPE */
diff --git a/lcc/include/mips/irix/errno.h b/lcc/include/mips/irix/errno.h
new file mode 100755
index 0000000..5ab3f0f
--- /dev/null
+++ b/lcc/include/mips/irix/errno.h
@@ -0,0 +1,8 @@
+#ifndef __ERRNO
+#define __ERRNO
+
+#define EDOM 33
+#define ERANGE 34
+extern int errno;
+
+#endif /* __ERRNO */
diff --git a/lcc/include/mips/irix/float.h b/lcc/include/mips/irix/float.h
new file mode 100755
index 0000000..8a8ddb1
--- /dev/null
+++ b/lcc/include/mips/irix/float.h
@@ -0,0 +1,37 @@
+#ifndef __FLOAT
+#define __FLOAT
+
+#define FLT_ROUNDS 1
+#define FLT_RADIX 2
+
+#define FLT_DIG 6
+#define FLT_EPSILON 1.19209289550781250000e-07
+#define FLT_MANT_DIG 24
+#define FLT_MAX 3.40282346638528860000e+38
+#define FLT_MAX_10_EXP 38
+#define FLT_MAX_EXP 128
+#define FLT_MIN 1.17549435082228750000e-38
+#define FLT_MIN_10_EXP -37
+#define FLT_MIN_EXP -125
+
+#define DBL_DIG 15
+#define DBL_EPSILON 2.22044604925031310000e-16
+#define DBL_MANT_DIG 53
+#define DBL_MAX 1.79769313486231570000e+308
+#define DBL_MAX_10_EXP 308
+#define DBL_MAX_EXP 1024
+#define DBL_MIN 2.22507385850720140000e-308
+#define DBL_MIN_10_EXP -307
+#define DBL_MIN_EXP -1021
+
+#define LDBL_MANT_DIG DBL_MANT_DIG
+#define LDBL_EPSILON DBL_EPSILON
+#define LDBL_DIG DBL_DIG
+#define LDBL_MIN_EXP DBL_MIN_EXP
+#define LDBL_MIN DBL_MIN
+#define LDBL_MIN_10_EXP DBL_MIN_10_EXP
+#define LDBL_MAX_EXP DBL_MAX_EXP
+#define LDBL_MAX DBL_MAX
+#define LDBL_MAX_10_EXP DBL_MAX_10_EXP
+
+#endif /* __FLOAT */
diff --git a/lcc/include/mips/irix/limits.h b/lcc/include/mips/irix/limits.h
new file mode 100755
index 0000000..98251f8
--- /dev/null
+++ b/lcc/include/mips/irix/limits.h
@@ -0,0 +1,24 @@
+#ifndef __LIMITS
+#define __LIMITS
+
+#define CHAR_BIT 8
+#define MB_LEN_MAX 1
+
+#define UCHAR_MAX 0xff
+#define USHRT_MAX 0xffff
+#define UINT_MAX (~0U)
+#define ULONG_MAX (~0UL)
+
+#define CHAR_MAX SCHAR_MAX
+#define SCHAR_MAX 0x7f
+#define SHRT_MAX 0x7fff
+#define INT_MAX 0x7fffffff
+#define LONG_MAX 0x7fffffffL
+
+#define CHAR_MIN SCHAR_MIN
+#define SCHAR_MIN (-SCHAR_MAX-1)
+#define SHRT_MIN (-SHRT_MAX-1)
+#define INT_MIN (-INT_MAX-1)
+#define LONG_MIN (-LONG_MAX-1)
+
+#endif /* __LIMITS */
diff --git a/lcc/include/mips/irix/locale.h b/lcc/include/mips/irix/locale.h
new file mode 100755
index 0000000..a861b47
--- /dev/null
+++ b/lcc/include/mips/irix/locale.h
@@ -0,0 +1,36 @@
+#ifndef __LOCALE
+#define __LOCALE
+
+#define LC_ALL 0
+#define LC_COLLATE 1
+#define LC_CTYPE 2
+#define LC_MONETARY 3
+#define LC_NUMERIC 4
+#define LC_TIME 5
+#define NULL 0
+
+struct lconv {
+ char *decimal_point;
+ char *thousands_sep;
+ char *grouping;
+ char *int_curr_symbol;
+ char *currency_symbol;
+ char *mon_decimal_point;
+ char *mon_thousands_sep;
+ char *mon_grouping;
+ char *positive_sign;
+ char *negative_sign;
+ char int_frac_digits;
+ char frac_digits;
+ char p_cs_precedes;
+ char p_sep_by_space;
+ char n_cs_precedes;
+ char n_sep_by_space;
+ char p_sign_posn;
+ char n_sign_posn;
+};
+
+char *setlocale(int, const char *);
+struct lconv *localeconv(void);
+
+#endif /* __LOCALE */
diff --git a/lcc/include/mips/irix/math.h b/lcc/include/mips/irix/math.h
new file mode 100755
index 0000000..bb39d69
--- /dev/null
+++ b/lcc/include/mips/irix/math.h
@@ -0,0 +1,29 @@
+#ifndef __MATH
+#define __MATH
+
+#define HUGE_VAL 1.79769313486231570000e+308
+
+extern double acos(double);
+extern double asin(double);
+extern double atan(double);
+extern double atan2(double, double);
+extern double cos(double);
+extern double sin(double);
+extern double tan(double);
+extern double cosh(double);
+extern double sinh(double);
+extern double tanh(double);
+extern double exp(double);
+extern double frexp(double, int *);
+extern double ldexp(double, int);
+extern double log(double);
+extern double log10(double);
+extern double modf(double, double *);
+extern double pow(double, double);
+extern double sqrt(double);
+extern double ceil(double);
+extern double fabs(double);
+extern double floor(double);
+extern double fmod(double, double);
+
+#endif /* __MATH */
diff --git a/lcc/include/mips/irix/setjmp.h b/lcc/include/mips/irix/setjmp.h
new file mode 100755
index 0000000..d4247f9
--- /dev/null
+++ b/lcc/include/mips/irix/setjmp.h
@@ -0,0 +1,10 @@
+#ifndef __SETJMP
+#define __SETJMP
+
+
+
+typedef int jmp_buf[28];
+int setjmp(jmp_buf);
+void longjmp(jmp_buf, int);
+
+#endif /* __SETJMP */
diff --git a/lcc/include/mips/irix/signal.h b/lcc/include/mips/irix/signal.h
new file mode 100755
index 0000000..22f98bc
--- /dev/null
+++ b/lcc/include/mips/irix/signal.h
@@ -0,0 +1,20 @@
+#ifndef __SIGNAL
+#define __SIGNAL
+
+typedef int sig_atomic_t;
+
+#define SIG_DFL ((void (*)(int))0)
+#define SIG_ERR ((void (*)(int))-1)
+#define SIG_IGN ((void (*)(int))1)
+
+#define SIGABRT 6
+#define SIGFPE 8
+#define SIGILL 4
+#define SIGINT 2
+#define SIGSEGV 11
+#define SIGTERM 15
+
+void (*signal(int, void (*)(int)))(int);
+int raise(int);
+
+#endif /* __SIGNAL */
diff --git a/lcc/include/mips/irix/stdarg.h b/lcc/include/mips/irix/stdarg.h
new file mode 100755
index 0000000..6c3a486
--- /dev/null
+++ b/lcc/include/mips/irix/stdarg.h
@@ -0,0 +1,22 @@
+#ifndef __STDARG
+#define __STDARG
+
+#if !defined(_VA_LIST)
+#define _VA_LIST
+typedef char *__va_list;
+#endif
+typedef __va_list va_list;
+
+#define va_start(list, start) ((void)((list) = (sizeof(start)<4 ? \
+ (char *)((int *)&(start)+1) : (char *)(&(start)+1))))
+#define __va_arg(list, mode, n) \
+ (*(mode *)(&(list += ((sizeof(mode)+n)&~n))[-(int)((sizeof(mode)+n)&~n)]))
+#define _bigendian_va_arg(list, mode, n) (\
+ sizeof(mode)==1 ? *(mode *)(&(list += 4)[-1]) : \
+ sizeof(mode)==2 ? *(mode *)(&(list += 4)[-2]) : __va_arg(list, mode, n))
+#define _littleendian_va_arg(list, mode, n) __va_arg(list, mode, n)
+#define va_end(list) ((void)0)
+#define va_arg(list, mode) (sizeof(mode)==8 ? \
+ *(mode *)(&(list = (char*)(((int)list + 15)&~7U))[-8]) : \
+ _bigendian_va_arg(list, mode, 3U))
+#endif
diff --git a/lcc/include/mips/irix/stddef.h b/lcc/include/mips/irix/stddef.h
new file mode 100755
index 0000000..459bfd6
--- /dev/null
+++ b/lcc/include/mips/irix/stddef.h
@@ -0,0 +1,22 @@
+#ifndef __STDDEF
+#define __STDDEF
+
+
+#define NULL 0
+#define offsetof(ty,mem) ((size_t)((char*)&((ty*)0)->mem - (char*)0))
+
+typedef long ptrdiff_t;
+
+#if !defined(_SIZE_T) && !defined(_SIZE_T_)
+#define _SIZE_T
+#define _SIZE_T_
+typedef unsigned long size_t;
+#endif
+
+#if !defined(_WCHAR_T) && !defined(_WCHAR_T_)
+#define _WCHAR_T
+#define _WCHAR_T_
+typedef unsigned short wchar_t;
+#endif
+
+#endif /* __STDDEF */
diff --git a/lcc/include/mips/irix/stdio.h b/lcc/include/mips/irix/stdio.h
new file mode 100755
index 0000000..77d996a
--- /dev/null
+++ b/lcc/include/mips/irix/stdio.h
@@ -0,0 +1,103 @@
+#ifndef __STDIO
+#define __STDIO
+
+#define _IOFBF 0
+#define _IOLBF 0100
+#define _IONBF 04
+#define BUFSIZ 1024
+#define EOF (-1)
+
+extern struct _iobuf {
+ int _cnt;
+ unsigned char *_ptr;
+ unsigned char *_base;
+ char _flag;
+ char _file;
+} _iob[];
+#define FILE struct _iobuf
+#define FILENAME_MAX 256
+#define FOPEN_MAX 100
+
+#if !defined(_FPOS_T) && !defined(_FPOS_T_)
+#define _FPOS_T
+#define _FPOS_T_
+typedef long fpos_t;
+#endif
+
+#define L_tmpnam 25
+#define NULL 0
+#define SEEK_CUR 1
+#define SEEK_END 2
+#define SEEK_SET 0
+
+#if !defined(_SIZE_T) && !defined(_SIZE_T_)
+#define _SIZE_T
+#define _SIZE_T_
+typedef unsigned long size_t;
+#endif
+
+#if !defined(_VA_LIST)
+#define _VA_LIST
+typedef char *__va_list;
+#endif
+
+#define stderr (&_iob[2])
+#define stdin (&_iob[0])
+#define stdout (&_iob[1])
+#define TMP_MAX 17576
+
+extern int remove(const char *);
+extern int rename(const char *, const char *);
+extern FILE *tmpfile(void);
+extern char *tmpnam(char *);
+extern int fclose(FILE *);
+extern int fflush(FILE *);
+extern FILE *fopen(const char *, const char *);
+extern FILE *freopen(const char *, const char *, FILE *);
+extern void setbuf(FILE *, char *);
+extern int setvbuf(FILE *, char *, int, size_t);
+extern int fprintf(FILE *, const char *, ...);
+extern int fscanf(FILE *, const char *, ...);
+extern int printf(const char *, ...);
+extern int scanf(const char *, ...);
+extern int sprintf(char *, const char *, ...);
+extern int sscanf(const char *, const char *, ...);
+extern int vfprintf(FILE *, const char *, __va_list);
+extern int vprintf(const char *, __va_list);
+extern int vsprintf(char *, const char *, __va_list);
+extern int fgetc(FILE *);
+extern char *fgets(char *, int, FILE *);
+extern int fputc(int, FILE *);
+extern int fputs(const char *, FILE *);
+extern int getc(FILE *);
+extern int getchar(void);
+extern char *gets(char *);
+extern int putc(int, FILE *);
+extern int putchar(int);
+extern int puts(const char *);
+extern int ungetc(int, FILE *);
+extern size_t fread(void *, size_t, size_t, FILE *);
+extern size_t fwrite(const void *, size_t, size_t, FILE *);
+extern int fgetpos(FILE *, fpos_t *);
+extern int fseek(FILE *, long int, int);
+extern int fsetpos(FILE *, const fpos_t *);
+extern long int ftell(FILE *);
+extern void rewind(FILE *);
+extern void clearerr(FILE *);
+extern int feof(FILE *);
+extern int ferror(FILE *);
+extern void perror(const char *);
+
+#define _IOEOF 020
+#define _IOERR 040
+
+#define getc(p) (--(p)->_cnt < 0 ? _filbuf(p) : (int) *(p)->_ptr++)
+#define putc(x, p) (--(p)->_cnt < 0 ? _flsbuf((unsigned char) (x), p) : (int) (*(p)->_ptr++ = (unsigned char) (x)))
+extern int _filbuf(FILE *), _flsbuf(unsigned, FILE *);
+#define feof(p) ((p)->_flag&_IOEOF)
+#define ferror(p) ((p)->_flag&_IOERR)
+#define clearerr(p) ((p)->_flag &= ~(_IOERR|_IOEOF))
+#define getchar() getc(stdin)
+#define putchar(x) putc((x),stdout)
+
+#endif /* __STDIO */
diff --git a/lcc/include/mips/irix/stdlib.h b/lcc/include/mips/irix/stdlib.h
new file mode 100755
index 0000000..e224f65
--- /dev/null
+++ b/lcc/include/mips/irix/stdlib.h
@@ -0,0 +1,54 @@
+#ifndef __STDLIB
+#define __STDLIB
+
+#define EXIT_FAILURE 1
+#define EXIT_SUCCESS 0
+#define MB_CUR_MAX 1
+#define NULL 0
+#define RAND_MAX 32767
+
+typedef struct { int quot, rem; } div_t;
+typedef struct { long quot, rem; } ldiv_t;
+
+#if !defined(_SIZE_T) && !defined(_SIZE_T_)
+#define _SIZE_T
+#define _SIZE_T_
+typedef unsigned long size_t;
+#endif
+
+#if !defined(_WCHAR_T) && !defined(_WCHAR_T_)
+#define _WCHAR_T
+#define _WCHAR_T_
+typedef unsigned char wchar_t;
+#endif
+
+extern double atof(const char *);
+extern int atoi(const char *);
+extern long int atol(const char *);
+extern double strtod(const char *, char **);
+extern long int strtol(const char *, char **, int);
+extern unsigned long int strtoul(const char *, char **, int);
+extern int rand(void);
+extern void srand(unsigned int);
+extern void *calloc(size_t, size_t);
+extern void free(void *);
+extern void *malloc(size_t);
+extern void *realloc(void *, size_t);
+extern void abort(void);
+extern int atexit(void (*)(void));
+extern void exit(int);
+extern char *getenv(const char *);
+extern int system(const char *);
+extern void *bsearch(const void *, const void *, size_t, size_t, int (*)(const void *, const void *));
+extern void qsort(void *, size_t, size_t, int (*)(const void *, const void *));
+extern int abs(int);
+extern div_t div(int, int);
+extern long int labs(long int);
+extern ldiv_t ldiv(long int, long int);
+extern int mblen(const char *, size_t);
+extern int mbtowc(wchar_t *, const char *, size_t);
+extern int wctomb(char *, wchar_t);
+extern size_t mbstowcs(wchar_t *, const char *, size_t);
+extern size_t wcstombs(char *, const wchar_t *, size_t);
+
+#endif /* __STDLIB */
diff --git a/lcc/include/mips/irix/string.h b/lcc/include/mips/irix/string.h
new file mode 100755
index 0000000..f19b1e4
--- /dev/null
+++ b/lcc/include/mips/irix/string.h
@@ -0,0 +1,35 @@
+#ifndef __STRING
+#define __STRING
+
+#define NULL 0
+
+#if !defined(_SIZE_T) && !defined(_SIZE_T_)
+#define _SIZE_T
+#define _SIZE_T_
+typedef unsigned long size_t;
+#endif
+
+void *memcpy(void *, const void *, size_t);
+void *memmove(void *, const void *, size_t);
+char *strcpy(char *, const char *);
+char *strncpy(char *, const char *, size_t);
+char *strcat(char *, const char *);
+char *strncat(char *, const char *, size_t);
+int memcmp(const void *, const void *, size_t);
+int strcmp(const char *, const char *);
+int strcoll(const char *, const char *);
+int strncmp(const char *, const char *, size_t);
+size_t strxfrm(char *, const char *, size_t);
+void *memchr(const void *, int, size_t);
+char *strchr(const char *, int);
+size_t strcspn(const char *, const char *);
+char *strpbrk(const char *, const char *);
+char *strrchr(const char *, int);
+size_t strspn(const char *, const char *);
+char *strstr(const char *, const char *);
+char *strtok(char *, const char *);
+void *memset(void *, int, size_t);
+char *strerror(int);
+size_t strlen(const char *);
+
+#endif /* __STRING */
diff --git a/lcc/include/mips/irix/time.h b/lcc/include/mips/irix/time.h
new file mode 100755
index 0000000..55a4922
--- /dev/null
+++ b/lcc/include/mips/irix/time.h
@@ -0,0 +1,48 @@
+#ifndef __TIME
+#define __TIME
+
+#define CLOCKS_PER_SEC 1000000
+#ifndef NULL
+#define NULL 0
+#endif
+
+#if !defined(_CLOCK_T) && !defined(_CLOCK_T_)
+#define _CLOCK_T
+#define _CLOCK_T_
+typedef long clock_t;
+#endif
+
+#if !defined(_TIME_T) && !defined(_TIME_T_)
+#define _TIME_T
+#define _TIME_T_
+typedef long time_t;
+#endif
+
+#if !defined(_SIZE_T) && !defined(_SIZE_T_)
+#define _SIZE_T
+#define _SIZE_T_
+typedef unsigned long size_t;
+#endif
+
+struct tm {
+ int tm_sec;
+ int tm_min;
+ int tm_hour;
+ int tm_mday;
+ int tm_mon;
+ int tm_year;
+ int tm_wday;
+ int tm_yday;
+ int tm_isdst;
+};
+extern clock_t clock(void);
+extern double difftime(time_t, time_t);
+extern time_t mktime(struct tm *);
+extern time_t time(time_t *);
+extern char *asctime(const struct tm *);
+extern char *ctime(const time_t *);
+extern struct tm *gmtime(const time_t *);
+extern struct tm *localtime(const time_t *);
+extern size_t strftime(char *, size_t, const char *, const struct tm *);
+
+#endif /* __TIME */
diff --git a/lcc/include/sparc/solaris/assert.h b/lcc/include/sparc/solaris/assert.h
new file mode 100755
index 0000000..e7f8777
--- /dev/null
+++ b/lcc/include/sparc/solaris/assert.h
@@ -0,0 +1,14 @@
+#ifndef __ASSERT
+#define __ASSERT
+
+void assert(int);
+
+#endif /* __ASSERT */
+
+#undef assert
+#ifdef NDEBUG
+#define assert(ignore) ((void)0)
+#else
+extern void __assert(char *, char *, unsigned);
+#define assert(e) ((void)((e)||(__assert(#e, __FILE__, __LINE__),0)))
+#endif /* NDEBUG */
diff --git a/lcc/include/sparc/solaris/ctype.h b/lcc/include/sparc/solaris/ctype.h
new file mode 100755
index 0000000..368c736
--- /dev/null
+++ b/lcc/include/sparc/solaris/ctype.h
@@ -0,0 +1,46 @@
+#ifndef __CTYPE
+#define __CTYPE
+
+extern int isalnum(int);
+extern int isalpha(int);
+extern int iscntrl(int);
+extern int isdigit(int);
+extern int isgraph(int);
+extern int islower(int);
+extern int isprint(int);
+extern int ispunct(int);
+extern int isspace(int);
+extern int isupper(int);
+extern int isxdigit(int);
+extern int tolower(int);
+extern int toupper(int);
+
+#define __U 01
+#define __L 02
+#define __N 04
+#define __S 010
+#define __P 020
+#define __C 040
+#define _U 01
+#define _L 02
+#define _N 04
+#define _S 010
+#define _P 020
+#define _C 040
+#define _B 0100
+#define _X 0200
+
+extern unsigned char __ctype[];
+#define isalpha(c) ((__ctype + 1)[c] & (_U | _L))
+#define isupper(c) ((__ctype + 1)[c] & _U)
+#define islower(c) ((__ctype + 1)[c] & _L)
+#define isdigit(c) ((__ctype + 1)[c] & _N)
+#define isxdigit(c) ((__ctype + 1)[c] & _X)
+#define isalnum(c) ((__ctype + 1)[c] & (_U | _L | _N))
+#define isspace(c) ((__ctype + 1)[c] & _S)
+#define ispunct(c) ((__ctype + 1)[c] & _P)
+#define isprint(c) ((__ctype + 1)[c] & (_P | _U | _L | _N | _B))
+#define isgraph(c) ((__ctype + 1)[c] & (_P | _U | _L | _N))
+#define iscntrl(c) ((__ctype + 1)[c] & _C)
+
+#endif /* __CTYPE */
diff --git a/lcc/include/sparc/solaris/errno.h b/lcc/include/sparc/solaris/errno.h
new file mode 100755
index 0000000..5ab3f0f
--- /dev/null
+++ b/lcc/include/sparc/solaris/errno.h
@@ -0,0 +1,8 @@
+#ifndef __ERRNO
+#define __ERRNO
+
+#define EDOM 33
+#define ERANGE 34
+extern int errno;
+
+#endif /* __ERRNO */
diff --git a/lcc/include/sparc/solaris/float.h b/lcc/include/sparc/solaris/float.h
new file mode 100755
index 0000000..8a8ddb1
--- /dev/null
+++ b/lcc/include/sparc/solaris/float.h
@@ -0,0 +1,37 @@
+#ifndef __FLOAT
+#define __FLOAT
+
+#define FLT_ROUNDS 1
+#define FLT_RADIX 2
+
+#define FLT_DIG 6
+#define FLT_EPSILON 1.19209289550781250000e-07
+#define FLT_MANT_DIG 24
+#define FLT_MAX 3.40282346638528860000e+38
+#define FLT_MAX_10_EXP 38
+#define FLT_MAX_EXP 128
+#define FLT_MIN 1.17549435082228750000e-38
+#define FLT_MIN_10_EXP -37
+#define FLT_MIN_EXP -125
+
+#define DBL_DIG 15
+#define DBL_EPSILON 2.22044604925031310000e-16
+#define DBL_MANT_DIG 53
+#define DBL_MAX 1.79769313486231570000e+308
+#define DBL_MAX_10_EXP 308
+#define DBL_MAX_EXP 1024
+#define DBL_MIN 2.22507385850720140000e-308
+#define DBL_MIN_10_EXP -307
+#define DBL_MIN_EXP -1021
+
+#define LDBL_MANT_DIG DBL_MANT_DIG
+#define LDBL_EPSILON DBL_EPSILON
+#define LDBL_DIG DBL_DIG
+#define LDBL_MIN_EXP DBL_MIN_EXP
+#define LDBL_MIN DBL_MIN
+#define LDBL_MIN_10_EXP DBL_MIN_10_EXP
+#define LDBL_MAX_EXP DBL_MAX_EXP
+#define LDBL_MAX DBL_MAX
+#define LDBL_MAX_10_EXP DBL_MAX_10_EXP
+
+#endif /* __FLOAT */
diff --git a/lcc/include/sparc/solaris/limits.h b/lcc/include/sparc/solaris/limits.h
new file mode 100755
index 0000000..98251f8
--- /dev/null
+++ b/lcc/include/sparc/solaris/limits.h
@@ -0,0 +1,24 @@
+#ifndef __LIMITS
+#define __LIMITS
+
+#define CHAR_BIT 8
+#define MB_LEN_MAX 1
+
+#define UCHAR_MAX 0xff
+#define USHRT_MAX 0xffff
+#define UINT_MAX (~0U)
+#define ULONG_MAX (~0UL)
+
+#define CHAR_MAX SCHAR_MAX
+#define SCHAR_MAX 0x7f
+#define SHRT_MAX 0x7fff
+#define INT_MAX 0x7fffffff
+#define LONG_MAX 0x7fffffffL
+
+#define CHAR_MIN SCHAR_MIN
+#define SCHAR_MIN (-SCHAR_MAX-1)
+#define SHRT_MIN (-SHRT_MAX-1)
+#define INT_MIN (-INT_MAX-1)
+#define LONG_MIN (-LONG_MAX-1)
+
+#endif /* __LIMITS */
diff --git a/lcc/include/sparc/solaris/locale.h b/lcc/include/sparc/solaris/locale.h
new file mode 100755
index 0000000..a861b47
--- /dev/null
+++ b/lcc/include/sparc/solaris/locale.h
@@ -0,0 +1,36 @@
+#ifndef __LOCALE
+#define __LOCALE
+
+#define LC_ALL 0
+#define LC_COLLATE 1
+#define LC_CTYPE 2
+#define LC_MONETARY 3
+#define LC_NUMERIC 4
+#define LC_TIME 5
+#define NULL 0
+
+struct lconv {
+ char *decimal_point;
+ char *thousands_sep;
+ char *grouping;
+ char *int_curr_symbol;
+ char *currency_symbol;
+ char *mon_decimal_point;
+ char *mon_thousands_sep;
+ char *mon_grouping;
+ char *positive_sign;
+ char *negative_sign;
+ char int_frac_digits;
+ char frac_digits;
+ char p_cs_precedes;
+ char p_sep_by_space;
+ char n_cs_precedes;
+ char n_sep_by_space;
+ char p_sign_posn;
+ char n_sign_posn;
+};
+
+char *setlocale(int, const char *);
+struct lconv *localeconv(void);
+
+#endif /* __LOCALE */
diff --git a/lcc/include/sparc/solaris/math.h b/lcc/include/sparc/solaris/math.h
new file mode 100755
index 0000000..13740db
--- /dev/null
+++ b/lcc/include/sparc/solaris/math.h
@@ -0,0 +1,30 @@
+#ifndef __MATH
+#define __MATH
+
+extern double infinity(void);
+#define HUGE_VAL (infinity())
+
+extern double acos(double);
+extern double asin(double);
+extern double atan(double);
+extern double atan2(double, double);
+extern double cos(double);
+extern double sin(double);
+extern double tan(double);
+extern double cosh(double);
+extern double sinh(double);
+extern double tanh(double);
+extern double exp(double);
+extern double frexp(double, int *);
+extern double ldexp(double, int);
+extern double log(double);
+extern double log10(double);
+extern double modf(double, double *);
+extern double pow(double, double);
+extern double sqrt(double);
+extern double ceil(double);
+extern double fabs(double);
+extern double floor(double);
+extern double fmod(double, double);
+
+#endif /* __MATH */
diff --git a/lcc/include/sparc/solaris/setjmp.h b/lcc/include/sparc/solaris/setjmp.h
new file mode 100755
index 0000000..b6a9ca3
--- /dev/null
+++ b/lcc/include/sparc/solaris/setjmp.h
@@ -0,0 +1,10 @@
+#ifndef __SETJMP
+#define __SETJMP
+
+
+
+typedef int jmp_buf[12];
+int setjmp(jmp_buf);
+void longjmp(jmp_buf, int);
+
+#endif /* __SETJMP */
diff --git a/lcc/include/sparc/solaris/signal.h b/lcc/include/sparc/solaris/signal.h
new file mode 100755
index 0000000..22f98bc
--- /dev/null
+++ b/lcc/include/sparc/solaris/signal.h
@@ -0,0 +1,20 @@
+#ifndef __SIGNAL
+#define __SIGNAL
+
+typedef int sig_atomic_t;
+
+#define SIG_DFL ((void (*)(int))0)
+#define SIG_ERR ((void (*)(int))-1)
+#define SIG_IGN ((void (*)(int))1)
+
+#define SIGABRT 6
+#define SIGFPE 8
+#define SIGILL 4
+#define SIGINT 2
+#define SIGSEGV 11
+#define SIGTERM 15
+
+void (*signal(int, void (*)(int)))(int);
+int raise(int);
+
+#endif /* __SIGNAL */
diff --git a/lcc/include/sparc/solaris/stdarg.h b/lcc/include/sparc/solaris/stdarg.h
new file mode 100755
index 0000000..cbdf869
--- /dev/null
+++ b/lcc/include/sparc/solaris/stdarg.h
@@ -0,0 +1,22 @@
+#ifndef __STDARG
+#define __STDARG
+
+#if !defined(_VA_LIST)
+#define _VA_LIST
+typedef char *__va_list;
+#endif
+typedef __va_list va_list;
+
+#define va_start(list, start) ((void)((list) = (sizeof(start)<4 ? \
+ (char *)((int *)&(start)+1) : (char *)(&(start)+1))))
+#define __va_arg(list, mode, n) \
+ (*(mode *)(&(list += ((sizeof(mode)+n)&~n))[-(int)((sizeof(mode)+n)&~n)]))
+#define _bigendian_va_arg(list, mode, n) (\
+ sizeof(mode)==1 ? *(mode *)(&(list += 4)[-1]) : \
+ sizeof(mode)==2 ? *(mode *)(&(list += 4)[-2]) : __va_arg(list, mode, n))
+#define _littleendian_va_arg(list, mode, n) __va_arg(list, mode, n)
+#define va_end(list) ((void)0)
+#define va_arg(list, mode) (sizeof(mode)>8 ? \
+ **(mode **)(&(list += 4)[-4]) : \
+ _bigendian_va_arg(list, mode, 3U))
+#endif
diff --git a/lcc/include/sparc/solaris/stddef.h b/lcc/include/sparc/solaris/stddef.h
new file mode 100755
index 0000000..459bfd6
--- /dev/null
+++ b/lcc/include/sparc/solaris/stddef.h
@@ -0,0 +1,22 @@
+#ifndef __STDDEF
+#define __STDDEF
+
+
+#define NULL 0
+#define offsetof(ty,mem) ((size_t)((char*)&((ty*)0)->mem - (char*)0))
+
+typedef long ptrdiff_t;
+
+#if !defined(_SIZE_T) && !defined(_SIZE_T_)
+#define _SIZE_T
+#define _SIZE_T_
+typedef unsigned long size_t;
+#endif
+
+#if !defined(_WCHAR_T) && !defined(_WCHAR_T_)
+#define _WCHAR_T
+#define _WCHAR_T_
+typedef unsigned short wchar_t;
+#endif
+
+#endif /* __STDDEF */
diff --git a/lcc/include/sparc/solaris/stdio.h b/lcc/include/sparc/solaris/stdio.h
new file mode 100755
index 0000000..4e4a629
--- /dev/null
+++ b/lcc/include/sparc/solaris/stdio.h
@@ -0,0 +1,104 @@
+#ifndef __STDIO
+#define __STDIO
+
+#define _IOFBF 0
+#define _IOLBF 0100
+#define _IONBF 04
+#define BUFSIZ 1024
+#define EOF (-1)
+
+typedef struct {
+ int _cnt;
+ unsigned char *_ptr;
+ unsigned char *_base;
+ unsigned char _flag;
+ unsigned char _file;
+} FILE;
+extern FILE __iob[];
+#define FILENAME_MAX 1024
+#define FOPEN_MAX 20
+
+#if !defined(_FPOS_T) && !defined(_FPOS_T_)
+#define _FPOS_T
+#define _FPOS_T_
+typedef long fpos_t;
+#endif
+
+#define L_tmpnam 25
+#define NULL 0
+#define SEEK_CUR 1
+#define SEEK_END 2
+#define SEEK_SET 0
+
+#if !defined(_SIZE_T) && !defined(_SIZE_T_)
+#define _SIZE_T
+#define _SIZE_T_
+typedef unsigned long size_t;
+#endif
+
+#if !defined(_VA_LIST)
+#define _VA_LIST
+typedef char *__va_list;
+#endif
+
+#define stderr (&__iob[2])
+#define stdin (&__iob[0])
+#define stdout (&__iob[1])
+#define TMP_MAX 17576
+
+extern int remove(const char *);
+extern int rename(const char *, const char *);
+extern FILE *tmpfile(void);
+extern char *tmpnam(char *);
+extern int fclose(FILE *);
+extern int fflush(FILE *);
+extern FILE *fopen(const char *, const char *);
+extern FILE *freopen(const char *, const char *, FILE *);
+extern void setbuf(FILE *, char *);
+extern int setvbuf(FILE *, char *, int, size_t);
+extern int fprintf(FILE *, const char *, ...);
+extern int fscanf(FILE *, const char *, ...);
+extern int printf(const char *, ...);
+extern int scanf(const char *, ...);
+extern int sprintf(char *, const char *, ...);
+extern int sscanf(const char *, const char *, ...);
+extern int vfprintf(FILE *, const char *, __va_list);
+extern int vprintf(const char *, __va_list);
+extern int vsprintf(char *, const char *, __va_list);
+extern int fgetc(FILE *);
+extern char *fgets(char *, int, FILE *);
+extern int fputc(int, FILE *);
+extern int fputs(const char *, FILE *);
+extern int getc(FILE *);
+extern int getchar(void);
+extern char *gets(char *);
+extern int putc(int, FILE *);
+extern int putchar(int);
+extern int puts(const char *);
+extern int ungetc(int, FILE *);
+extern size_t fread(void *, size_t, size_t, FILE *);
+extern size_t fwrite(const void *, size_t, size_t, FILE *);
+extern int fgetpos(FILE *, fpos_t *);
+extern int fseek(FILE *, long int, int);
+extern int fsetpos(FILE *, const fpos_t *);
+extern long int ftell(FILE *);
+extern void rewind(FILE *);
+extern void clearerr(FILE *);
+extern int feof(FILE *);
+extern int ferror(FILE *);
+extern void perror(const char *);
+
+#define _IOEOF 020
+#define _IOERR 040
+
+#define getc(p) (--(p)->_cnt < 0 ? __filbuf(p) : (int)*(p)->_ptr++)
+#define putc(x, p) (--(p)->_cnt < 0 ? __flsbuf((unsigned char) (x), (p)) \
+ : (int)(*(p)->_ptr++ = (x)))
+extern int __filbuf(FILE *), __flsbuf(unsigned, FILE *);
+#define feof(p) ((p)->_flag&_IOEOF)
+#define ferror(p) ((p)->_flag&_IOERR)
+#define clearerr(p) ((p)->_flag &= ~(_IOERR|_IOEOF))
+#define getchar() getc(stdin)
+#define putchar(x) putc((x),stdout)
+
+#endif /* __STDIO */
diff --git a/lcc/include/sparc/solaris/stdlib.h b/lcc/include/sparc/solaris/stdlib.h
new file mode 100755
index 0000000..e224f65
--- /dev/null
+++ b/lcc/include/sparc/solaris/stdlib.h
@@ -0,0 +1,54 @@
+#ifndef __STDLIB
+#define __STDLIB
+
+#define EXIT_FAILURE 1
+#define EXIT_SUCCESS 0
+#define MB_CUR_MAX 1
+#define NULL 0
+#define RAND_MAX 32767
+
+typedef struct { int quot, rem; } div_t;
+typedef struct { long quot, rem; } ldiv_t;
+
+#if !defined(_SIZE_T) && !defined(_SIZE_T_)
+#define _SIZE_T
+#define _SIZE_T_
+typedef unsigned long size_t;
+#endif
+
+#if !defined(_WCHAR_T) && !defined(_WCHAR_T_)
+#define _WCHAR_T
+#define _WCHAR_T_
+typedef unsigned char wchar_t;
+#endif
+
+extern double atof(const char *);
+extern int atoi(const char *);
+extern long int atol(const char *);
+extern double strtod(const char *, char **);
+extern long int strtol(const char *, char **, int);
+extern unsigned long int strtoul(const char *, char **, int);
+extern int rand(void);
+extern void srand(unsigned int);
+extern void *calloc(size_t, size_t);
+extern void free(void *);
+extern void *malloc(size_t);
+extern void *realloc(void *, size_t);
+extern void abort(void);
+extern int atexit(void (*)(void));
+extern void exit(int);
+extern char *getenv(const char *);
+extern int system(const char *);
+extern void *bsearch(const void *, const void *, size_t, size_t, int (*)(const void *, const void *));
+extern void qsort(void *, size_t, size_t, int (*)(const void *, const void *));
+extern int abs(int);
+extern div_t div(int, int);
+extern long int labs(long int);
+extern ldiv_t ldiv(long int, long int);
+extern int mblen(const char *, size_t);
+extern int mbtowc(wchar_t *, const char *, size_t);
+extern int wctomb(char *, wchar_t);
+extern size_t mbstowcs(wchar_t *, const char *, size_t);
+extern size_t wcstombs(char *, const wchar_t *, size_t);
+
+#endif /* __STDLIB */
diff --git a/lcc/include/sparc/solaris/string.h b/lcc/include/sparc/solaris/string.h
new file mode 100755
index 0000000..f19b1e4
--- /dev/null
+++ b/lcc/include/sparc/solaris/string.h
@@ -0,0 +1,35 @@
+#ifndef __STRING
+#define __STRING
+
+#define NULL 0
+
+#if !defined(_SIZE_T) && !defined(_SIZE_T_)
+#define _SIZE_T
+#define _SIZE_T_
+typedef unsigned long size_t;
+#endif
+
+void *memcpy(void *, const void *, size_t);
+void *memmove(void *, const void *, size_t);
+char *strcpy(char *, const char *);
+char *strncpy(char *, const char *, size_t);
+char *strcat(char *, const char *);
+char *strncat(char *, const char *, size_t);
+int memcmp(const void *, const void *, size_t);
+int strcmp(const char *, const char *);
+int strcoll(const char *, const char *);
+int strncmp(const char *, const char *, size_t);
+size_t strxfrm(char *, const char *, size_t);
+void *memchr(const void *, int, size_t);
+char *strchr(const char *, int);
+size_t strcspn(const char *, const char *);
+char *strpbrk(const char *, const char *);
+char *strrchr(const char *, int);
+size_t strspn(const char *, const char *);
+char *strstr(const char *, const char *);
+char *strtok(char *, const char *);
+void *memset(void *, int, size_t);
+char *strerror(int);
+size_t strlen(const char *);
+
+#endif /* __STRING */
diff --git a/lcc/include/sparc/solaris/time.h b/lcc/include/sparc/solaris/time.h
new file mode 100755
index 0000000..55a4922
--- /dev/null
+++ b/lcc/include/sparc/solaris/time.h
@@ -0,0 +1,48 @@
+#ifndef __TIME
+#define __TIME
+
+#define CLOCKS_PER_SEC 1000000
+#ifndef NULL
+#define NULL 0
+#endif
+
+#if !defined(_CLOCK_T) && !defined(_CLOCK_T_)
+#define _CLOCK_T
+#define _CLOCK_T_
+typedef long clock_t;
+#endif
+
+#if !defined(_TIME_T) && !defined(_TIME_T_)
+#define _TIME_T
+#define _TIME_T_
+typedef long time_t;
+#endif
+
+#if !defined(_SIZE_T) && !defined(_SIZE_T_)
+#define _SIZE_T
+#define _SIZE_T_
+typedef unsigned long size_t;
+#endif
+
+struct tm {
+ int tm_sec;
+ int tm_min;
+ int tm_hour;
+ int tm_mday;
+ int tm_mon;
+ int tm_year;
+ int tm_wday;
+ int tm_yday;
+ int tm_isdst;
+};
+extern clock_t clock(void);
+extern double difftime(time_t, time_t);
+extern time_t mktime(struct tm *);
+extern time_t time(time_t *);
+extern char *asctime(const struct tm *);
+extern char *ctime(const time_t *);
+extern struct tm *gmtime(const time_t *);
+extern struct tm *localtime(const time_t *);
+extern size_t strftime(char *, size_t, const char *, const struct tm *);
+
+#endif /* __TIME */
diff --git a/lcc/include/x86/linux/assert.h b/lcc/include/x86/linux/assert.h
new file mode 100755
index 0000000..5b4776c
--- /dev/null
+++ b/lcc/include/x86/linux/assert.h
@@ -0,0 +1,14 @@
+#ifndef __ASSERT
+#define __ASSERT
+
+void assert(int);
+
+#endif /* __ASSERT */
+
+#undef assert
+#ifdef NDEBUG
+#define assert(ignore) ((void)0)
+#else
+extern int _assert(char *, char *, unsigned);
+#define assert(e) ((void)((e)||_assert(#e, __FILE__, __LINE__)))
+#endif /* NDEBUG */
diff --git a/lcc/include/x86/linux/float.h b/lcc/include/x86/linux/float.h
new file mode 100755
index 0000000..1c0197f
--- /dev/null
+++ b/lcc/include/x86/linux/float.h
@@ -0,0 +1,37 @@
+#ifndef __FLOAT
+#define __FLOAT
+
+#define FLT_ROUNDS (__flt_rounds())
+#define FLT_RADIX 2
+
+#define FLT_DIG 6
+#define FLT_EPSILON 1.19209289550781250000e-07
+#define FLT_MANT_DIG 24
+#define FLT_MAX 3.40282346638528860000e+38
+#define FLT_MAX_10_EXP 38
+#define FLT_MAX_EXP 128
+#define FLT_MIN 1.17549435082228750000e-38
+#define FLT_MIN_10_EXP -37
+#define FLT_MIN_EXP -125
+
+#define DBL_DIG 15
+#define DBL_EPSILON 2.22044604925031310000e-16
+#define DBL_MANT_DIG 53
+#define DBL_MAX 1.79769313486231570000e+308
+#define DBL_MAX_10_EXP 308
+#define DBL_MAX_EXP 1024
+#define DBL_MIN 2.22507385850720140000e-308
+#define DBL_MIN_10_EXP -307
+#define DBL_MIN_EXP -1021
+
+#define LDBL_MANT_DIG DBL_MANT_DIG
+#define LDBL_EPSILON DBL_EPSILON
+#define LDBL_DIG DBL_DIG
+#define LDBL_MIN_EXP DBL_MIN_EXP
+#define LDBL_MIN DBL_MIN
+#define LDBL_MIN_10_EXP DBL_MIN_10_EXP
+#define LDBL_MAX_EXP DBL_MAX_EXP
+#define LDBL_MAX DBL_MAX
+#define LDBL_MAX_10_EXP DBL_MAX_10_EXP
+
+#endif /* __FLOAT */
diff --git a/lcc/include/x86/linux/stdarg.h b/lcc/include/x86/linux/stdarg.h
new file mode 100755
index 0000000..504ee48
--- /dev/null
+++ b/lcc/include/x86/linux/stdarg.h
@@ -0,0 +1,21 @@
+#ifndef __STDARG
+#define __STDARG
+
+#if !defined(_VA_LIST)
+#define _VA_LIST
+typedef char *__va_list;
+#endif
+typedef __va_list va_list;
+
+#define va_start(list, start) ((void)((list) = (sizeof(start)<4 ? \
+ (char *)((int *)&(start)+1) : (char *)(&(start)+1))))
+#define __va_arg(list, mode, n) \
+ (*(mode *)(&(list += ((sizeof(mode)+n)&~n))[-(int)((sizeof(mode)+n)&~n)]))
+#define _bigendian_va_arg(list, mode, n) (\
+ sizeof(mode)==1 ? *(mode *)(&(list += 4)[-1]) : \
+ sizeof(mode)==2 ? *(mode *)(&(list += 4)[-2]) : __va_arg(list, mode, n))
+#define _littleendian_va_arg(list, mode, n) __va_arg(list, mode, n)
+#define va_end(list) ((void)0)
+#define va_arg(list, mode) _littleendian_va_arg(list, mode, 3U)
+typedef void *__gnuc_va_list;
+#endif
diff --git a/lcc/lburg/gram.c b/lcc/lburg/gram.c
new file mode 100755
index 0000000..b484e57
--- /dev/null
+++ b/lcc/lburg/gram.c
@@ -0,0 +1,680 @@
+#if defined(__STDC__) || defined(__cplusplus)
+#define YYCONST const
+#define YYPARAMS(x) x
+#define YYDEFUN(name, arglist, args) name(args)
+#define YYAND ,
+#define YYPTR void *
+#else
+#define YYCONST
+#define YYPARAMS(x) ()
+#define YYDEFUN(name, arglist, args) name arglist args;
+#define YYAND ;
+#define YYPTR char *
+#endif
+#ifndef lint
+YYCONST static char yysccsid[] = "@(#)yaccpar 1.8 (Berkeley +Cygnus.28) 01/20/91";
+#endif
+#define YYBYACC 1
+#ifndef YYDONT_INCLUDE_STDIO
+#include <stdio.h>
+#endif
+#ifdef __cplusplus
+#include <stdlib.h> /* for malloc/realloc/free */
+#endif
+#line 2 "lburg/gram.y"
+#include <stdio.h>
+#include "lburg.h"
+/*lint -e616 -e527 -e652 -esym(552,yynerrs) -esym(563,yynewstate,yyerrlab) */
+static int yylineno = 0;
+#line 8 "lburg/gram.y"
+typedef union {
+ int n;
+ char *string;
+ Tree tree;
+} YYSTYPE;
+#line 37 "y.tab.c"
+#define TERMINAL 257
+#define START 258
+#define PPERCENT 259
+#define ID 260
+#define TEMPLATE 261
+#define CODE 262
+#define INT 263
+#define YYERRCODE 256
+static YYCONST short yylhs[] = { -1,
+ 0, 0, 4, 4, 6, 6, 6, 6, 7, 7,
+ 5, 5, 5, 5, 1, 3, 3, 3, 2,
+};
+static YYCONST short yylen[] = { 2,
+ 3, 1, 0, 2, 3, 3, 1, 2, 0, 4,
+ 0, 7, 2, 3, 1, 1, 4, 6, 1,
+};
+static YYCONST short yydefred[] = { 3,
+ 0, 0, 0, 9, 0, 11, 7, 4, 8, 0,
+ 15, 0, 0, 0, 5, 6, 0, 13, 0, 0,
+ 14, 0, 10, 0, 0, 0, 0, 0, 19, 0,
+ 17, 0, 12, 0, 18,
+};
+static YYCONST short yydgoto[] = { 1,
+ 12, 30, 25, 2, 13, 8, 10,
+};
+static YYCONST short yysindex[] = { 0,
+ 0, -4, -2, 0, -250, 0, 0, 0, 0, -9,
+ 0, 1, -10, -49, 0, 0, 3, 0, -44, -248,
+ 0, -244, 0, -22, -242, -244, -245, -37, 0, 10,
+ 0, -244, 0, -20, 0,
+};
+static YYCONST short yyrindex[] = { 0,
+ 0, 22, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 23, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, -39, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0,
+};
+static YYCONST short yygindex[] = { 0,
+ 11, 0, -23, 0, 0, 0, 0,
+};
+#define YYTABLESIZE 255
+static YYCONST short yytable[] = { 18,
+ 15, 16, 28, 31, 16, 7, 32, 9, 34, 11,
+ 16, 20, 21, 22, 23, 24, 29, 26, 27, 33,
+ 35, 2, 1, 19, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 16, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 17, 0, 0, 0, 11,
+ 14, 3, 4, 5, 6,
+};
+static YYCONST short yycheck[] = { 10,
+ 10, 41, 26, 41, 44, 10, 44, 10, 32, 260,
+ 10, 61, 10, 58, 263, 260, 262, 40, 261, 10,
+ 41, 0, 0, 13, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, 261, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, 256, -1, -1, -1, 260,
+ 260, 256, 257, 258, 259,
+};
+#define YYFINAL 1
+#ifndef YYDEBUG
+#define YYDEBUG 0
+#endif
+#define YYMAXTOKEN 263
+#if YYDEBUG
+static YYCONST char *YYCONST yyname[] = {
+"end-of-file",0,0,0,0,0,0,0,0,0,"'\\n'",0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+0,0,0,0,0,0,0,0,0,"'('","')'",0,0,"','",0,0,0,0,0,0,0,0,0,0,0,0,0,"':'",0,0,
+"'='",0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+"TERMINAL","START","PPERCENT","ID","TEMPLATE","CODE","INT",
+};
+static YYCONST char *YYCONST yyrule[] = {
+"$accept : spec",
+"spec : decls PPERCENT rules",
+"spec : decls",
+"decls :",
+"decls : decls decl",
+"decl : TERMINAL blist '\\n'",
+"decl : START nonterm '\\n'",
+"decl : '\\n'",
+"decl : error '\\n'",
+"blist :",
+"blist : blist ID '=' INT",
+"rules :",
+"rules : rules nonterm ':' tree TEMPLATE cost '\\n'",
+"rules : rules '\\n'",
+"rules : rules error '\\n'",
+"nonterm : ID",
+"tree : ID",
+"tree : ID '(' tree ')'",
+"tree : ID '(' tree ',' tree ')'",
+"cost : CODE",
+};
+#endif
+#define YYLEX yylex()
+#define YYEMPTY -1
+#define yyclearin (yychar=(YYEMPTY))
+#define yyerrok (yyerrflag=0)
+#ifndef YYINITDEPTH
+#define YYINITDEPTH 200
+#endif
+#ifdef YYSTACKSIZE
+#ifndef YYMAXDEPTH
+#define YYMAXDEPTH YYSTACKSIZE
+#endif
+#else
+#ifdef YYMAXDEPTH
+#define YYSTACKSIZE YYMAXDEPTH
+#else
+#define YYSTACKSIZE 500
+#define YYMAXDEPTH 500
+#endif
+#endif
+#ifndef YYMAXSTACKSIZE
+#define YYMAXSTACKSIZE 10000
+#endif
+int yydebug;
+int yynerrs;
+int yyerrflag;
+int yychar;
+YYSTYPE yyval;
+YYSTYPE yylval;
+static short *yyss;
+static YYSTYPE *yyvs;
+static int yystacksize;
+#define yyfree(x) free(x)
+extern int yylex();
+
+static YYPTR
+YYDEFUN (yymalloc, (bytes), unsigned bytes)
+{
+ YYPTR ptr = (YYPTR) malloc (bytes);
+ if (ptr != 0) return (ptr);
+ yyerror ("yyparse: memory exhausted");
+ return (0);
+}
+
+static YYPTR
+YYDEFUN (yyrealloc, (old, bytes), YYPTR old YYAND unsigned bytes)
+{
+ YYPTR ptr = (YYPTR) realloc (old, bytes);
+ if (ptr != 0) return (ptr);
+ yyerror ("yyparse: memory exhausted");
+ return (0);
+}
+
+static int
+#ifdef __GNUC__
+inline
+#endif
+yygrow ()
+{
+ int old_stacksize = yystacksize;
+ short *new_yyss;
+ YYSTYPE *new_yyvs;
+
+ if (yystacksize == YYMAXSTACKSIZE)
+ return (1);
+ yystacksize += (yystacksize + 1 ) / 2;
+ if (yystacksize > YYMAXSTACKSIZE)
+ yystacksize = YYMAXSTACKSIZE;
+#if YYDEBUG
+ if (yydebug)
+ printf("yydebug: growing stack size from %d to %d\n",
+ old_stacksize, yystacksize);
+#endif
+ new_yyss = (short *) yyrealloc ((char *)yyss, yystacksize * sizeof (short));
+ if (new_yyss == 0)
+ return (1);
+ new_yyvs = (YYSTYPE *) yyrealloc ((char *)yyvs, yystacksize * sizeof (YYSTYPE));
+ if (new_yyvs == 0)
+ {
+ yyfree (new_yyss);
+ return (1);
+ }
+ yyss = new_yyss;
+ yyvs = new_yyvs;
+ return (0);
+}
+#line 60 "lburg/gram.y"
+#include <assert.h>
+#include <stdarg.h>
+#include <ctype.h>
+#include <string.h>
+#include <limits.h>
+
+int errcnt = 0;
+FILE *infp = NULL;
+FILE *outfp = NULL;
+static char buf[BUFSIZ], *bp = buf;
+static int ppercent = 0;
+static int code = 0;
+
+static int get(void) {
+ if (*bp == 0) {
+ bp = buf;
+ *bp = 0;
+ if (fgets(buf, sizeof buf, infp) == NULL)
+ return EOF;
+ yylineno++;
+ while (buf[0] == '%' && buf[1] == '{' && buf[2] == '\n') {
+ for (;;) {
+ if (fgets(buf, sizeof buf, infp) == NULL) {
+ yywarn("unterminated %{...%}\n");
+ return EOF;
+ }
+ yylineno++;
+ if (strcmp(buf, "%}\n") == 0)
+ break;
+ fputs(buf, outfp);
+ }
+ if (fgets(buf, sizeof buf, infp) == NULL)
+ return EOF;
+ yylineno++;
+ }
+ }
+ return *bp++;
+}
+
+void yyerror(char *fmt, ...) {
+ va_list ap;
+
+ va_start(ap, fmt);
+ if (yylineno > 0)
+ fprintf(stderr, "line %d: ", yylineno);
+ vfprintf(stderr, fmt, ap);
+ if (fmt[strlen(fmt)-1] != '\n')
+ fprintf(stderr, "\n");
+ errcnt++;
+ va_end(ap);
+}
+
+int yylex(void) {
+ int c;
+
+ if (code) {
+ char *p;
+ bp += strspn(bp, " \t\f");
+ p = strchr(bp, '\n');
+ if (p == NULL)
+ p = strchr(bp, '\n');
+ while (p > bp && isspace(p[-1]))
+ p--;
+ yylval.string = alloc(p - bp + 1);
+ strncpy(yylval.string, bp, p - bp);
+ yylval.string[p - bp] = 0;
+ bp = p;
+ code--;
+ return CODE;
+ }
+ while ((c = get()) != EOF) {
+ switch (c) {
+ case ' ': case '\f': case '\t':
+ continue;
+ case '\n':
+ case '(': case ')': case ',':
+ case ':': case '=':
+ return c;
+ }
+ if (c == '%' && *bp == '%') {
+ bp++;
+ return ppercent++ ? 0 : PPERCENT;
+ } else if (c == '%' && strncmp(bp, "term", 4) == 0
+ && isspace(bp[4])) {
+ bp += 4;
+ return TERMINAL;
+ } else if (c == '%' && strncmp(bp, "start", 5) == 0
+ && isspace(bp[5])) {
+ bp += 5;
+ return START;
+ } else if (c == '"') {
+ char *p = strchr(bp, '"');
+ if (p == NULL) {
+ yyerror("missing \" in assembler template\n");
+ p = strchr(bp, '\n');
+ if (p == NULL)
+ p = strchr(bp, '\0');
+ }
+ assert(p);
+ yylval.string = alloc(p - bp + 1);
+ strncpy(yylval.string, bp, p - bp);
+ yylval.string[p - bp] = 0;
+ bp = *p == '"' ? p + 1 : p;
+ code++;
+ return TEMPLATE;
+ } else if (isdigit(c)) {
+ int n = 0;
+ do {
+ int d = c - '0';
+ if (n > (INT_MAX - d)/10)
+ yyerror("integer greater than %d\n", INT_MAX);
+ else
+ n = 10*n + d;
+ c = get();
+ } while (c != EOF && isdigit(c));
+ bp--;
+ yylval.n = n;
+ return INT;
+ } else if (isalpha(c)) {
+ char *p = bp - 1;
+ while (isalpha(*bp) || isdigit(*bp) || *bp == '_')
+ bp++;
+ yylval.string = alloc(bp - p + 1);
+ strncpy(yylval.string, p, bp - p);
+ yylval.string[bp - p] = 0;
+ return ID;
+ } else if (isprint(c))
+ yyerror("invalid character `%c'\n", c);
+ else
+ yyerror("invalid character `\\%03o'\n", (unsigned char)c);
+ }
+ return 0;
+}
+
+void yywarn(char *fmt, ...) {
+ va_list ap;
+
+ va_start(ap, fmt);
+ if (yylineno > 0)
+ fprintf(stderr, "line %d: ", yylineno);
+ fprintf(stderr, "warning: ");
+ vfprintf(stderr, fmt, ap);
+}
+#line 403 "y.tab.c"
+#define YYABORT goto yyabort
+#define YYACCEPT goto yyaccept
+#define YYERROR goto yyerrlab
+
+#if YYDEBUG
+#ifdef __cplusplus
+extern "C" char *getenv();
+#else
+extern char *getenv();
+#endif
+#endif
+
+int
+yyparse()
+{
+ register int yym, yyn, yystate;
+ register YYSTYPE *yyvsp;
+ register short *yyssp;
+ short *yysse;
+#if YYDEBUG
+ register YYCONST char *yys;
+
+ if (yys = getenv("YYDEBUG"))
+ {
+ yyn = *yys;
+ if (yyn >= '0' && yyn <= '9')
+ yydebug = yyn - '0';
+ }
+#endif
+
+ yynerrs = 0;
+ yyerrflag = 0;
+ yychar = (-1);
+
+ if (yyss == 0)
+ {
+ yyss = (short *) yymalloc (YYSTACKSIZE * sizeof (short));
+ if (yyss == 0)
+ goto yyabort;
+ yyvs = (YYSTYPE *) yymalloc (YYSTACKSIZE * sizeof (YYSTYPE));
+ if (yyvs == 0)
+ {
+ yyfree (yyss);
+ goto yyabort;
+ }
+ yystacksize = YYSTACKSIZE;
+ }
+ yysse = yyss + yystacksize - 1;
+ yyssp = yyss;
+ yyvsp = yyvs;
+ *yyssp = yystate = 0;
+ goto yyloop;
+
+yypush_lex:
+ yyval = yylval;
+ yystate = yytable[yyn];
+yypush:
+ if (yyssp >= yysse)
+ {
+ int depth = yyssp - yyss;
+ if (yygrow() != 0)
+ goto yyoverflow;
+ yysse = yyss + yystacksize -1;
+ yyssp = depth + yyss;
+ yyvsp = depth + yyvs;
+ }
+ *++yyssp = yystate;
+ *++yyvsp = yyval;
+
+yyloop:
+ if (yyn = yydefred[yystate]) goto yyreduce;
+ yyn = yysindex[yystate];
+ if (yychar < 0)
+ {
+ if ((yychar = yylex()) < 0) yychar = 0;
+#if YYDEBUG
+ if (yydebug)
+ {
+ yys = 0;
+ if (yychar <= YYMAXTOKEN) yys = yyname[yychar];
+ if (!yys) yys = "illegal-symbol";
+ printf("yydebug: state %d, reading %d (%s)\n", yystate,
+ yychar, yys);
+ }
+#endif
+ }
+ if (yyn != 0
+ && ((yyn += yychar), ((unsigned)yyn <= (unsigned)YYTABLESIZE))
+ && yycheck[yyn] == yychar)
+ {
+#if YYDEBUG
+ if (yydebug)
+ printf("yydebug: state %d, shifting to state %d\n",
+ yystate, yytable[yyn]);
+#endif
+ if (yyerrflag > 0) --yyerrflag;
+ yychar = (-1);
+ goto yypush_lex;
+ }
+ yyn = yyrindex[yystate];
+ if (yyn != 0
+ && ((yyn += yychar), ((unsigned)yyn <= (unsigned)YYTABLESIZE))
+ && yycheck[yyn] == yychar)
+ {
+ yyn = yytable[yyn];
+ goto yyreduce;
+ }
+ if (yyerrflag) goto yyinrecovery;
+#ifdef lint
+ goto yynewerror;
+#endif
+yynewerror:
+ yyerror("syntax error");
+#ifdef lint
+ goto yyerrlab;
+#endif
+yyerrlab:
+ ++yynerrs;
+yyinrecovery:
+ if (yyerrflag < 3)
+ {
+ yyerrflag = 3;
+ for (;;)
+ {
+ yyn = yysindex[*yyssp];
+ if (yyn != 0
+ && ((yyn += YYERRCODE), ((unsigned)yyn <= (unsigned)YYTABLESIZE))
+ && yycheck[yyn] == YYERRCODE)
+ {
+#if YYDEBUG
+ if (yydebug)
+ printf("yydebug: state %d, error recovery shifting\
+ to state %d\n", *yyssp, yytable[yyn]);
+#endif
+ goto yypush_lex;
+ }
+ else
+ {
+#if YYDEBUG
+ if (yydebug)
+ printf("yydebug: error recovery discarding state %d\n",
+ *yyssp);
+#endif
+ if (yyssp <= yyss) goto yyabort;
+ --yyssp;
+ --yyvsp;
+ }
+ }
+ }
+ else
+ {
+ if (yychar == 0) goto yyabort;
+#if YYDEBUG
+ if (yydebug)
+ {
+ yys = 0;
+ if (yychar <= YYMAXTOKEN) yys = yyname[yychar];
+ if (!yys) yys = "illegal-symbol";
+ printf("yydebug: state %d, error recovery discards token %d (%s)\n",
+ yystate, yychar, yys);
+ }
+#endif
+ yychar = (-1);
+ goto yyloop;
+ }
+yyreduce:
+#if YYDEBUG
+ if (yydebug)
+ printf("yydebug: state %d, reducing by rule %d (%s)\n",
+ yystate, yyn, yyrule[yyn]);
+#endif
+ yym = yylen[yyn];
+ yyval = yyvsp[1-yym];
+ switch (yyn)
+ {
+case 1:
+#line 22 "lburg/gram.y"
+{ yylineno = 0; }
+break;
+case 2:
+#line 23 "lburg/gram.y"
+{ yylineno = 0; }
+break;
+case 6:
+#line 31 "lburg/gram.y"
+{
+ if (nonterm(yyvsp[-1].string)->number != 1)
+ yyerror("redeclaration of the start symbol\n");
+ }
+break;
+case 8:
+#line 36 "lburg/gram.y"
+{ yyerrok; }
+break;
+case 10:
+#line 40 "lburg/gram.y"
+{ term(yyvsp[-2].string, yyvsp[0].n); }
+break;
+case 12:
+#line 44 "lburg/gram.y"
+{ rule(yyvsp[-5].string, yyvsp[-3].tree, yyvsp[-2].string, yyvsp[-1].string); }
+break;
+case 14:
+#line 46 "lburg/gram.y"
+{ yyerrok; }
+break;
+case 15:
+#line 49 "lburg/gram.y"
+{ nonterm(yyval.string = yyvsp[0].string); }
+break;
+case 16:
+#line 52 "lburg/gram.y"
+{ yyval.tree = tree(yyvsp[0].string, 0, 0); }
+break;
+case 17:
+#line 53 "lburg/gram.y"
+{ yyval.tree = tree(yyvsp[-3].string, yyvsp[-1].tree, 0); }
+break;
+case 18:
+#line 54 "lburg/gram.y"
+{ yyval.tree = tree(yyvsp[-5].string, yyvsp[-3].tree, yyvsp[-1].tree); }
+break;
+case 19:
+#line 57 "lburg/gram.y"
+{ if (*yyvsp[0].string == 0) yyval.string = "0"; }
+break;
+#line 630 "y.tab.c"
+ }
+ yyssp -= yym;
+ yyvsp -= yym;
+ yym = yylhs[yyn];
+ yystate = *yyssp;
+ if (yystate == 0 && yym == 0)
+ {
+#if YYDEBUG
+ if (yydebug)
+ printf("yydebug: after reduction, shifting from state 0 to\
+ state %d\n", YYFINAL);
+#endif
+ yystate = YYFINAL;
+ *++yyssp = YYFINAL;
+ *++yyvsp = yyval;
+ if (yychar < 0)
+ {
+ if ((yychar = yylex()) < 0) yychar = 0;
+#if YYDEBUG
+ if (yydebug)
+ {
+ yys = 0;
+ if (yychar <= YYMAXTOKEN) yys = yyname[yychar];
+ if (!yys) yys = "illegal-symbol";
+ printf("yydebug: state %d, reading %d (%s)\n",
+ YYFINAL, yychar, yys);
+ }
+#endif
+ }
+ if (yychar == 0) goto yyaccept;
+ goto yyloop;
+ }
+ yyn = yygindex[yym];
+ if (yyn != 0
+ && ((yyn += yystate), ((unsigned)yyn <= (unsigned)YYTABLESIZE))
+ && yycheck[yyn] == yystate)
+ yystate = yytable[yyn];
+ else
+ yystate = yydgoto[yym];
+#if YYDEBUG
+ if (yydebug)
+ printf("yydebug: after reduction, shifting from state %d \
+to state %d\n", *yyssp, yystate);
+#endif
+ goto yypush;
+yyoverflow:
+ yyerror("yacc stack overflow");
+yyabort:
+ return (1);
+yyaccept:
+ return (0);
+}
diff --git a/lcc/lburg/gram.y b/lcc/lburg/gram.y
new file mode 100755
index 0000000..860d22a
--- /dev/null
+++ b/lcc/lburg/gram.y
@@ -0,0 +1,202 @@
+%{
+#include <stdio.h>
+#include "lburg.h"
+static char rcsid[] = "$Id: gram.y 145 2001-10-17 21:53:10Z timo $";
+/*lint -e616 -e527 -e652 -esym(552,yynerrs) -esym(563,yynewstate,yyerrlab) */
+static int yylineno = 0;
+%}
+%union {
+ int n;
+ char *string;
+ Tree tree;
+}
+%term TERMINAL
+%term START
+%term PPERCENT
+
+%token <string> ID TEMPLATE CODE
+%token <n> INT
+%type <string> nonterm cost
+%type <tree> tree
+%%
+spec : decls PPERCENT rules { yylineno = 0; }
+ | decls { yylineno = 0; }
+ ;
+
+decls : /* lambda */
+ | decls decl
+ ;
+
+decl : TERMINAL blist '\n'
+ | START nonterm '\n' {
+ if (nonterm($2)->number != 1)
+ yyerror("redeclaration of the start symbol\n");
+ }
+ | '\n'
+ | error '\n' { yyerrok; }
+ ;
+
+blist : /* lambda */
+ | blist ID '=' INT { term($2, $4); }
+ ;
+
+rules : /* lambda */
+ | rules nonterm ':' tree TEMPLATE cost '\n' { rule($2, $4, $5, $6); }
+ | rules '\n'
+ | rules error '\n' { yyerrok; }
+ ;
+
+nonterm : ID { nonterm($$ = $1); }
+ ;
+
+tree : ID { $$ = tree($1, 0, 0); }
+ | ID '(' tree ')' { $$ = tree($1, $3, 0); }
+ | ID '(' tree ',' tree ')' { $$ = tree($1, $3, $5); }
+ ;
+
+cost : CODE { if (*$1 == 0) $$ = "0"; }
+ ;
+%%
+#include <assert.h>
+#include <stdarg.h>
+#include <ctype.h>
+#include <string.h>
+#include <limits.h>
+
+int errcnt = 0;
+FILE *infp = NULL;
+FILE *outfp = NULL;
+static char buf[BUFSIZ], *bp = buf;
+static int ppercent = 0;
+static int code = 0;
+
+static int get(void) {
+ if (*bp == 0) {
+ bp = buf;
+ *bp = 0;
+ if (fgets(buf, sizeof buf, infp) == NULL)
+ return EOF;
+ yylineno++;
+ while (buf[0] == '%' && buf[1] == '{' && buf[2] == '\n') {
+ for (;;) {
+ if (fgets(buf, sizeof buf, infp) == NULL) {
+ yywarn("unterminated %{...%}\n");
+ return EOF;
+ }
+ yylineno++;
+ if (strcmp(buf, "%}\n") == 0)
+ break;
+ fputs(buf, outfp);
+ }
+ if (fgets(buf, sizeof buf, infp) == NULL)
+ return EOF;
+ yylineno++;
+ }
+ }
+ return *bp++;
+}
+
+void yyerror(char *fmt, ...) {
+ va_list ap;
+
+ va_start(ap, fmt);
+ if (yylineno > 0)
+ fprintf(stderr, "line %d: ", yylineno);
+ vfprintf(stderr, fmt, ap);
+ if (fmt[strlen(fmt)-1] != '\n')
+ fprintf(stderr, "\n");
+ errcnt++;
+ va_end(ap);
+}
+
+int yylex(void) {
+ int c;
+
+ if (code) {
+ char *p;
+ bp += strspn(bp, " \t\f");
+ p = strchr(bp, '\n');
+ if (p == NULL)
+ p = strchr(bp, '\n');
+ while (p > bp && isspace(p[-1]))
+ p--;
+ yylval.string = alloc(p - bp + 1);
+ strncpy(yylval.string, bp, p - bp);
+ yylval.string[p - bp] = 0;
+ bp = p;
+ code--;
+ return CODE;
+ }
+ while ((c = get()) != EOF) {
+ switch (c) {
+ case ' ': case '\f': case '\t':
+ continue;
+ case '\n':
+ case '(': case ')': case ',':
+ case ':': case '=':
+ return c;
+ }
+ if (c == '%' && *bp == '%') {
+ bp++;
+ return ppercent++ ? 0 : PPERCENT;
+ } else if (c == '%' && strncmp(bp, "term", 4) == 0
+ && isspace(bp[4])) {
+ bp += 4;
+ return TERMINAL;
+ } else if (c == '%' && strncmp(bp, "start", 5) == 0
+ && isspace(bp[5])) {
+ bp += 5;
+ return START;
+ } else if (c == '"') {
+ char *p = strchr(bp, '"');
+ if (p == NULL) {
+ yyerror("missing \" in assembler template\n");
+ p = strchr(bp, '\n');
+ if (p == NULL)
+ p = strchr(bp, '\0');
+ }
+ assert(p);
+ yylval.string = alloc(p - bp + 1);
+ strncpy(yylval.string, bp, p - bp);
+ yylval.string[p - bp] = 0;
+ bp = *p == '"' ? p + 1 : p;
+ code++;
+ return TEMPLATE;
+ } else if (isdigit(c)) {
+ int n = 0;
+ do {
+ int d = c - '0';
+ if (n > (INT_MAX - d)/10)
+ yyerror("integer greater than %d\n", INT_MAX);
+ else
+ n = 10*n + d;
+ c = get();
+ } while (c != EOF && isdigit(c));
+ bp--;
+ yylval.n = n;
+ return INT;
+ } else if (isalpha(c)) {
+ char *p = bp - 1;
+ while (isalpha(*bp) || isdigit(*bp) || *bp == '_')
+ bp++;
+ yylval.string = alloc(bp - p + 1);
+ strncpy(yylval.string, p, bp - p);
+ yylval.string[bp - p] = 0;
+ return ID;
+ } else if (isprint(c))
+ yyerror("invalid character `%c'\n", c);
+ else
+ yyerror("invalid character `\\%03o'\n", (unsigned char)c);
+ }
+ return 0;
+}
+
+void yywarn(char *fmt, ...) {
+ va_list ap;
+
+ va_start(ap, fmt);
+ if (yylineno > 0)
+ fprintf(stderr, "line %d: ", yylineno);
+ fprintf(stderr, "warning: ");
+ vfprintf(stderr, fmt, ap);
+}
diff --git a/lcc/lburg/lburg.1 b/lcc/lburg/lburg.1
new file mode 100755
index 0000000..d633e6b
--- /dev/null
+++ b/lcc/lburg/lburg.1
@@ -0,0 +1,179 @@
+.TH LBURG 1 "local \- 11/30/94"
+.\" $Id: lburg.1 145 2001-10-17 21:53:10Z timo $
+.SH NAME
+lburg \- lcc's code-generator generator
+.SH SYNOPSIS
+.B lburg
+[
+.I option
+]...
+[ [
+.I input
+]
+.I output
+]
+.br
+.SH DESCRIPTION
+.PP
+.I lburg
+reads an lcc-style BURG specification from
+.I input
+and writes a pattern-matching code generator to
+.IR output .
+If
+.I input
+is `\-' or is omitted,
+.I lburg
+reads the standard input;
+If
+.I output
+is `\-' or is omitted,
+.I lburg
+writes to the standard output.
+.PP
+.I lburg
+accepts specifications that conform to the following EBNF grammar.
+Terminals are enclosed in single quotes or are
+given in uppercase, all other symbols are nonterminals or English phrases,
+{X} denotes zero or more instances of X, and [X] denotes an optional X.
+.PP
+.nf
+.RS
+.ft CW
+spec: `%{' configuration `%}' { dcl } `%%' { rule }
+ [ `%%' C code ]
+
+dcl: `%start' nonterm
+ `%term' { ID `=' INT }
+
+rule: nonterm `:' tree template [ C expression ]
+
+tree: term `(' tree `,' tree `)'
+ term `(' tree `)'
+ term
+ nonterm
+
+nonterm: ID
+
+template: `"' { any character except double quote } `"'
+.RE
+.fi
+.PP
+Specifications are structurally similar to
+.IR yacc 's.
+Text between
+`\f(CW%{\fP'
+and
+`\f(CW%}\fP'
+is called the configuration section; there may be several such segments.
+All are concatenated and copied verbatim into the head of the output.
+Text after the second
+`\f(CW%%\fP',
+if any, is also copied verbatim into the output, at the end.
+.PP
+Specifications consist of declarations, a
+`\f(CW%%\fP'
+separator, and rules.
+Input is line-oriented; each declaration and rule must appear on a separate line,
+and declarations must begin in column 1.
+Declarations declare terminals \(em the operators in subject
+trees \(em and associate a unique, positive external symbol
+number with each one.
+Nonterminals are declared by their presence
+on the left side of rules. The
+\f(CW%start\fP
+declaration optionally declares a nonterminal as the start symbol.
+In the grammar above,
+\f(CWterm\fP
+and
+\f(CWnonterm\fP
+denote identifiers that are terminals and nonterminals.
+.PP
+Rules define tree patterns in a fully parenthesized prefix
+form. Every nonterminal denotes a tree.
+Each operator has a fixed
+arity, which is inferred from the rules in which it is used.
+A chain rule is a rule whose pattern is another nonterminal.
+If no start symbol is declared, the nonterminal defined by the first rule is used.
+.PP
+Each rule ends with an expression that computes the cost of matching
+that rule; omitted costs
+default to zero. Costs of chain rules must be constants.
+.PP
+The configuration section configures the output
+for the trees being parsed and the client's environment.
+As shown, this section must define
+\f(CWNODEPTR_TYPE\fP
+to be a visible typedef symbol for a pointer to a
+node in the subject tree.
+The labeller invokes
+\f(CWOP_LABEL(p)\fP,
+\f(CWLEFT\_CHILD(p)\fP, and
+\f(CWRIGHT\_CHILD(p)\fP
+to read the operator and children from the node pointed to by \f(CWp\fP.
+If the configuration section defines these operations as macros, they are implemented in-line;
+otherwise, they must be implemented as functions.
+.PP
+The matcher
+computes and stores a single integral state in each node of the subject tree.
+The configuration section must define a macro
+\f(CWSTATE_LABEL(p)\fP
+to access the state field of the node pointed to
+by \f(CWp\fP. It must be large enough to hold a pointer, and
+a macro is required because it is used as an lvalue.
+.PP
+.SH OPTIONS
+.TP
+.BI \-p \ prefix
+.br
+.ns
+.TP
+.BI \-p prefix
+Use
+.I prefix
+as the disambiquating prefix for visible names and fields.
+The default is `\f(CW_\fP'.
+.TP
+.B \-T
+Arrange for
+.sp
+.nf
+.ft CW
+ void _trace(NODEPTR_TYPE p, int eruleno,
+ int cost, int bestcost);
+.sp
+.fi
+.ft R
+to be called at each successful match.
+\f(CWp\fP
+identifies the node and
+\f(CWeruleno\fP
+identifies the matching rule; the rules are numbered
+beginning at 1 in the order they appear in the input.
+\f(CWcost\fP
+is the cost of the match and
+\f(CWbestcost\fP
+is the cost of the best previous match. The current match
+wins only if
+\f(CWcost\fP
+is less than \f(CWbestcost\fP.
+32767 represents the infinite cost of no previous match.
+\f(CW_trace\fP must be declared in the configuration section.
+.SH "SEE ALSO"
+.IR lcc (1)
+.PP
+C. W. Fraser and D. R. Hanson,
+.IR A Retargetable C Compiler: Design and Implementation ,
+Benjamin/Cummings, Redwood City, CA, 1995,
+ISBN 0-8053-1670-1. Chapter 14.
+.PP
+C. W. Fraser, D. R. Hanson and T. A. Proebsting,
+`Engineering a simple, efficient code generator generator,'
+.I
+ACM Letters on Programming Languages and Systems
+.BR 1 ,
+3 (Sep. 1992), 213-226.
+.br
+.SH BUGS
+Mail bug reports along with the shortest input
+that exposes them to drh@cs.princeton.edu.
diff --git a/lcc/lburg/lburg.c b/lcc/lburg/lburg.c
new file mode 100755
index 0000000..a34e4e7
--- /dev/null
+++ b/lcc/lburg/lburg.c
@@ -0,0 +1,671 @@
+#include <assert.h>
+#include <ctype.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <time.h>
+#include "lburg.h"
+
+static char rcsid[] = "lburg.c - faked rcsid";
+
+static char *prefix = "";
+static int Tflag = 0;
+static int ntnumber = 0;
+static Nonterm start = 0;
+static Term terms;
+static Nonterm nts;
+static Rule rules;
+static int nrules;
+static struct block {
+ struct block *link;
+} *memlist; /* list of allocated blocks */
+
+static char *stringf(char *fmt, ...);
+static void print(char *fmt, ...);
+static void ckreach(Nonterm p);
+static void emitclosure(Nonterm nts);
+static void emitcost(Tree t, char *v);
+static void emitdefs(Nonterm nts, int ntnumber);
+static void emitheader(void);
+static void emitkids(Rule rules, int nrules);
+static void emitnts(Rule rules, int nrules);
+static void emitrecalc(char *pre, Term root, Term kid);
+static void emitrecord(char *pre, Rule r, char *c, int cost);
+static void emitrule(Nonterm nts);
+static void emitlabel(Term terms, Nonterm start, int ntnumber);
+static void emitstring(Rule rules);
+static void emitstruct(Nonterm nts, int ntnumber);
+static void emittest(Tree t, char *v, char *suffix);
+
+int main(int argc, char *argv[]) {
+ int c, i;
+ Nonterm p;
+
+ for (i = 1; i < argc; i++)
+ if (strcmp(argv[i], "-T") == 0)
+ Tflag = 1;
+ else if (strncmp(argv[i], "-p", 2) == 0 && argv[i][2])
+ prefix = &argv[i][2];
+ else if (strncmp(argv[i], "-p", 2) == 0 && i + 1 < argc)
+ prefix = argv[++i];
+ else if (*argv[i] == '-' && argv[i][1]) {
+ yyerror("usage: %s [-T | -p prefix]... [ [ input ] output ] \n",
+ argv[0]);
+ exit(1);
+ } else if (infp == NULL) {
+ if (strcmp(argv[i], "-") == 0)
+ infp = stdin;
+ else if ((infp = fopen(argv[i], "r")) == NULL) {
+ yyerror("%s: can't read `%s'\n", argv[0], argv[i]);
+ exit(1);
+ }
+ } else if (outfp == NULL) {
+ if (strcmp(argv[i], "-") == 0)
+ outfp = stdout;
+ if ((outfp = fopen(argv[i], "w")) == NULL) {
+ yyerror("%s: can't write `%s'\n", argv[0], argv[i]);
+ exit(1);
+ }
+ }
+ if (infp == NULL)
+ infp = stdin;
+ if (outfp == NULL)
+ outfp = stdout;
+ yyparse();
+ if (start)
+ ckreach(start);
+ for (p = nts; p; p = p->link) {
+ if (p->rules == NULL)
+ yyerror("undefined nonterminal `%s'\n", p->name);
+ if (!p->reached)
+ yyerror("can't reach nonterminal `%s'\n", p->name);
+ }
+ emitheader();
+ emitdefs(nts, ntnumber);
+ emitstruct(nts, ntnumber);
+ emitnts(rules, nrules);
+ emitstring(rules);
+ emitrule(nts);
+ emitclosure(nts);
+ if (start)
+ emitlabel(terms, start, ntnumber);
+ emitkids(rules, nrules);
+ if (!feof(infp))
+ while ((c = getc(infp)) != EOF)
+ putc(c, outfp);
+ while (memlist) { /* for purify */
+ struct block *q = memlist->link;
+ free(memlist);
+ memlist = q;
+ }
+ return errcnt > 0;
+}
+
+/* alloc - allocate nbytes or issue fatal error */
+void *alloc(int nbytes) {
+ struct block *p = calloc(1, sizeof *p + nbytes);
+
+ if (p == NULL) {
+ yyerror("out of memory\n");
+ exit(1);
+ }
+ p->link = memlist;
+ memlist = p;
+ return p + 1;
+}
+
+/* stringf - format and save a string */
+static char *stringf(char *fmt, ...) {
+ va_list ap;
+ char buf[512];
+
+ va_start(ap, fmt);
+ vsprintf(buf, fmt, ap);
+ va_end(ap);
+ return strcpy(alloc(strlen(buf) + 1), buf);
+}
+
+struct entry {
+ union {
+ char *name;
+ struct term t;
+ struct nonterm nt;
+ } sym;
+ struct entry *link;
+} *table[211];
+#define HASHSIZE (sizeof table/sizeof table[0])
+
+/* hash - return hash number for str */
+static unsigned hash(char *str) {
+ unsigned h = 0;
+
+ while (*str)
+ h = (h<<1) + *str++;
+ return h;
+}
+
+/* lookup - lookup symbol name */
+static void *lookup(char *name) {
+ struct entry *p = table[hash(name)%HASHSIZE];
+
+ for ( ; p; p = p->link)
+ if (strcmp(name, p->sym.name) == 0)
+ return &p->sym;
+ return 0;
+}
+
+/* install - install symbol name */
+static void *install(char *name) {
+ struct entry *p = alloc(sizeof *p);
+ int i = hash(name)%HASHSIZE;
+
+ p->sym.name = name;
+ p->link = table[i];
+ table[i] = p;
+ return &p->sym;
+}
+
+/* nonterm - create a new terminal id, if necessary */
+Nonterm nonterm(char *id) {
+ Nonterm p = lookup(id), *q = &nts;
+
+ if (p && p->kind == NONTERM)
+ return p;
+ if (p && p->kind == TERM)
+ yyerror("`%s' is a terminal\n", id);
+ p = install(id);
+ p->kind = NONTERM;
+ p->number = ++ntnumber;
+ if (p->number == 1)
+ start = p;
+ while (*q && (*q)->number < p->number)
+ q = &(*q)->link;
+ assert(*q == 0 || (*q)->number != p->number);
+ p->link = *q;
+ *q = p;
+ return p;
+}
+
+/* term - create a new terminal id with external symbol number esn */
+Term term(char *id, int esn) {
+ Term p = lookup(id), *q = &terms;
+
+ if (p)
+ yyerror("redefinition of terminal `%s'\n", id);
+ else
+ p = install(id);
+ p->kind = TERM;
+ p->esn = esn;
+ p->arity = -1;
+ while (*q && (*q)->esn < p->esn)
+ q = &(*q)->link;
+ if (*q && (*q)->esn == p->esn)
+ yyerror("duplicate external symbol number `%s=%d'\n",
+ p->name, p->esn);
+ p->link = *q;
+ *q = p;
+ return p;
+}
+
+/* tree - create & initialize a tree node with the given fields */
+Tree tree(char *id, Tree left, Tree right) {
+ Tree t = alloc(sizeof *t);
+ Term p = lookup(id);
+ int arity = 0;
+
+ if (left && right)
+ arity = 2;
+ else if (left)
+ arity = 1;
+ if (p == NULL && arity > 0) {
+ yyerror("undefined terminal `%s'\n", id);
+ p = term(id, -1);
+ } else if (p == NULL && arity == 0)
+ p = (Term)nonterm(id);
+ else if (p && p->kind == NONTERM && arity > 0) {
+ yyerror("`%s' is a nonterminal\n", id);
+ p = term(id, -1);
+ }
+ if (p->kind == TERM && p->arity == -1)
+ p->arity = arity;
+ if (p->kind == TERM && arity != p->arity)
+ yyerror("inconsistent arity for terminal `%s'\n", id);
+ t->op = p;
+ t->nterms = p->kind == TERM;
+ if ((t->left = left) != NULL)
+ t->nterms += left->nterms;
+ if ((t->right = right) != NULL)
+ t->nterms += right->nterms;
+ return t;
+}
+
+/* rule - create & initialize a rule with the given fields */
+Rule rule(char *id, Tree pattern, char *template, char *code) {
+ Rule r = alloc(sizeof *r), *q;
+ Term p = pattern->op;
+ char *end;
+
+ r->lhs = nonterm(id);
+ r->packed = ++r->lhs->lhscount;
+ for (q = &r->lhs->rules; *q; q = &(*q)->decode)
+ ;
+ *q = r;
+ r->pattern = pattern;
+ r->ern = ++nrules;
+ r->template = template;
+ r->code = code;
+ r->cost = strtol(code, &end, 10);
+ if (*end) {
+ r->cost = -1;
+ r->code = stringf("(%s)", code);
+ }
+ if (p->kind == TERM) {
+ for (q = &p->rules; *q; q = &(*q)->next)
+ ;
+ *q = r;
+ } else if (pattern->left == NULL && pattern->right == NULL) {
+ Nonterm p = pattern->op;
+ r->chain = p->chain;
+ p->chain = r;
+ if (r->cost == -1)
+ yyerror("illegal nonconstant cost `%s'\n", code);
+ }
+ for (q = &rules; *q; q = &(*q)->link)
+ ;
+ r->link = *q;
+ *q = r;
+ return r;
+}
+
+/* print - formatted output */
+static void print(char *fmt, ...) {
+ va_list ap;
+
+ va_start(ap, fmt);
+ for ( ; *fmt; fmt++)
+ if (*fmt == '%')
+ switch (*++fmt) {
+ case 'd': fprintf(outfp, "%d", va_arg(ap, int)); break;
+ case 's': fputs(va_arg(ap, char *), outfp); break;
+ case 'P': fprintf(outfp, "%s_", prefix); break;
+ case 'T': {
+ Tree t = va_arg(ap, Tree);
+ print("%S", t->op);
+ if (t->left && t->right)
+ print("(%T,%T)", t->left, t->right);
+ else if (t->left)
+ print("(%T)", t->left);
+ break;
+ }
+ case 'R': {
+ Rule r = va_arg(ap, Rule);
+ print("%S: %T", r->lhs, r->pattern);
+ break;
+ }
+ case 'S': fputs(va_arg(ap, Term)->name, outfp); break;
+ case '1': case '2': case '3': case '4': case '5': {
+ int n = *fmt - '0';
+ while (n-- > 0)
+ putc('\t', outfp);
+ break;
+ }
+ default: putc(*fmt, outfp); break;
+ }
+ else
+ putc(*fmt, outfp);
+ va_end(ap);
+}
+
+/* reach - mark all nonterminals in tree t as reachable */
+static void reach(Tree t) {
+ Nonterm p = t->op;
+
+ if (p->kind == NONTERM)
+ if (!p->reached)
+ ckreach(p);
+ if (t->left)
+ reach(t->left);
+ if (t->right)
+ reach(t->right);
+}
+
+/* ckreach - mark all nonterminals reachable from p */
+static void ckreach(Nonterm p) {
+ Rule r;
+
+ p->reached = 1;
+ for (r = p->rules; r; r = r->decode)
+ reach(r->pattern);
+}
+
+/* emitcase - emit one case in function state */
+static void emitcase(Term p, int ntnumber) {
+ Rule r;
+
+ print("%1case %d: /* %S */\n", p->esn, p);
+ switch (p->arity) {
+ case 0: case -1:
+ break;
+ case 1:
+ print("%2%Plabel(LEFT_CHILD(a));\n");
+ break;
+ case 2:
+ print("%2%Plabel(LEFT_CHILD(a));\n");
+ print("%2%Plabel(RIGHT_CHILD(a));\n");
+ break;
+ default: assert(0);
+ }
+ for (r = p->rules; r; r = r->next) {
+ char *indent = "\t\t\0";
+ switch (p->arity) {
+ case 0: case -1:
+ print("%2/* %R */\n", r);
+ if (r->cost == -1) {
+ print("%2c = %s;\n", r->code);
+ emitrecord("\t\t", r, "c", 0);
+ } else
+ emitrecord("\t\t", r, r->code, 0);
+ break;
+ case 1:
+ if (r->pattern->nterms > 1) {
+ print("%2if (%1/* %R */\n", r);
+ emittest(r->pattern->left, "LEFT_CHILD(a)", " ");
+ print("%2) {\n");
+ indent = "\t\t\t";
+ } else
+ print("%2/* %R */\n", r);
+ if (r->pattern->nterms == 2 && r->pattern->left
+ && r->pattern->right == NULL)
+ emitrecalc(indent, r->pattern->op, r->pattern->left->op);
+ print("%sc = ", indent);
+ emitcost(r->pattern->left, "LEFT_CHILD(a)");
+ print("%s;\n", r->code);
+ emitrecord(indent, r, "c", 0);
+ if (indent[2])
+ print("%2}\n");
+ break;
+ case 2:
+ if (r->pattern->nterms > 1) {
+ print("%2if (%1/* %R */\n", r);
+ emittest(r->pattern->left, "LEFT_CHILD(a)",
+ r->pattern->right->nterms ? " && " : " ");
+ emittest(r->pattern->right, "RIGHT_CHILD(a)", " ");
+ print("%2) {\n");
+ indent = "\t\t\t";
+ } else
+ print("%2/* %R */\n", r);
+ print("%sc = ", indent);
+ emitcost(r->pattern->left, "LEFT_CHILD(a)");
+ emitcost(r->pattern->right, "RIGHT_CHILD(a)");
+ print("%s;\n", r->code);
+ emitrecord(indent, r, "c", 0);
+ if (indent[2])
+ print("%2}\n");
+ break;
+ default: assert(0);
+ }
+ }
+ print("%2break;\n");
+}
+
+/* emitclosure - emit the closure functions */
+static void emitclosure(Nonterm nts) {
+ Nonterm p;
+
+ for (p = nts; p; p = p->link)
+ if (p->chain)
+ print("static void %Pclosure_%S(NODEPTR_TYPE, int);\n", p);
+ print("\n");
+ for (p = nts; p; p = p->link)
+ if (p->chain) {
+ Rule r;
+ print("static void %Pclosure_%S(NODEPTR_TYPE a, int c) {\n"
+"%1struct %Pstate *p = STATE_LABEL(a);\n", p);
+ for (r = p->chain; r; r = r->chain)
+ emitrecord("\t", r, "c", r->cost);
+ print("}\n\n");
+ }
+}
+
+/* emitcost - emit cost computation for tree t */
+static void emitcost(Tree t, char *v) {
+ Nonterm p = t->op;
+
+ if (p->kind == TERM) {
+ if (t->left)
+ emitcost(t->left, stringf("LEFT_CHILD(%s)", v));
+ if (t->right)
+ emitcost(t->right, stringf("RIGHT_CHILD(%s)", v));
+ } else
+ print("((struct %Pstate *)(%s->x.state))->cost[%P%S_NT] + ", v, p);
+}
+
+/* emitdefs - emit nonterminal defines and data structures */
+static void emitdefs(Nonterm nts, int ntnumber) {
+ Nonterm p;
+
+ for (p = nts; p; p = p->link)
+ print("#define %P%S_NT %d\n", p, p->number);
+ print("\n");
+ print("static char *%Pntname[] = {\n%10,\n");
+ for (p = nts; p; p = p->link)
+ print("%1\"%S\",\n", p);
+ print("%10\n};\n\n");
+}
+
+/* emitheader - emit initial definitions */
+static void emitheader(void) {
+ time_t timer = time(NULL);
+
+ print("/*\ngenerated at %sby %s\n*/\n", ctime(&timer), rcsid);
+ print("static void %Pkids(NODEPTR_TYPE, int, NODEPTR_TYPE[]);\n");
+ print("static void %Plabel(NODEPTR_TYPE);\n");
+ print("static int %Prule(void*, int);\n\n");
+}
+
+/* computekids - compute paths to kids in tree t */
+static char *computekids(Tree t, char *v, char *bp, int *ip) {
+ Term p = t->op;
+
+ if (p->kind == NONTERM) {
+ sprintf(bp, "\t\tkids[%d] = %s;\n", (*ip)++, v);
+ bp += strlen(bp);
+ } else if (p->arity > 0) {
+ bp = computekids(t->left, stringf("LEFT_CHILD(%s)", v), bp, ip);
+ if (p->arity == 2)
+ bp = computekids(t->right, stringf("RIGHT_CHILD(%s)", v), bp, ip);
+ }
+ return bp;
+}
+
+/* emitkids - emit _kids */
+static void emitkids(Rule rules, int nrules) {
+ int i;
+ Rule r, *rc = alloc((nrules + 1 + 1)*sizeof *rc);
+ char **str = alloc((nrules + 1 + 1)*sizeof *str);
+
+ for (i = 0, r = rules; r; r = r->link) {
+ int j = 0;
+ char buf[1024], *bp = buf;
+ *computekids(r->pattern, "p", bp, &j) = 0;
+ for (j = 0; str[j] && strcmp(str[j], buf); j++)
+ ;
+ if (str[j] == NULL)
+ str[j] = strcpy(alloc(strlen(buf) + 1), buf);
+ r->kids = rc[j];
+ rc[j] = r;
+ }
+ print("static void %Pkids(NODEPTR_TYPE p, int eruleno, NODEPTR_TYPE kids[]) {\n"
+"%1if (!p)\n%2fatal(\"%Pkids\", \"Null tree\\n\", 0);\n"
+"%1if (!kids)\n%2fatal(\"%Pkids\", \"Null kids\\n\", 0);\n"
+"%1switch (eruleno) {\n");
+ for (i = 0; (r = rc[i]) != NULL; i++) {
+ for ( ; r; r = r->kids)
+ print("%1case %d: /* %R */\n", r->ern, r);
+ print("%s%2break;\n", str[i]);
+ }
+ print("%1default:\n%2fatal(\"%Pkids\", \"Bad rule number %%d\\n\", eruleno);\n%1}\n}\n\n");
+}
+
+/* emitlabel - emit label function */
+static void emitlabel(Term terms, Nonterm start, int ntnumber) {
+ int i;
+ Term p;
+
+ print("static void %Plabel(NODEPTR_TYPE a) {\n%1int c;\n"
+"%1struct %Pstate *p;\n\n"
+"%1if (!a)\n%2fatal(\"%Plabel\", \"Null tree\\n\", 0);\n");
+ print("%1STATE_LABEL(a) = p = allocate(sizeof *p, FUNC);\n"
+"%1p->rule._stmt = 0;\n");
+ for (i = 1; i <= ntnumber; i++)
+ print("%1p->cost[%d] =\n", i);
+ print("%20x7fff;\n%1switch (OP_LABEL(a)) {\n");
+ for (p = terms; p; p = p->link)
+ emitcase(p, ntnumber);
+ print("%1default:\n"
+"%2fatal(\"%Plabel\", \"Bad terminal %%d\\n\", OP_LABEL(a));\n%1}\n}\n\n");
+}
+
+/* computents - fill in bp with _nts vector for tree t */
+static char *computents(Tree t, char *bp) {
+ if (t) {
+ Nonterm p = t->op;
+ if (p->kind == NONTERM) {
+ sprintf(bp, "%s_%s_NT, ", prefix, p->name);
+ bp += strlen(bp);
+ } else
+ bp = computents(t->right, computents(t->left, bp));
+ }
+ return bp;
+}
+
+/* emitnts - emit _nts ragged array */
+static void emitnts(Rule rules, int nrules) {
+ Rule r;
+ int i, j, *nts = alloc((nrules + 1)*sizeof *nts);
+ char **str = alloc((nrules + 1)*sizeof *str);
+
+ for (i = 0, r = rules; r; r = r->link) {
+ char buf[1024];
+ *computents(r->pattern, buf) = 0;
+ for (j = 0; str[j] && strcmp(str[j], buf); j++)
+ ;
+ if (str[j] == NULL) {
+ print("static short %Pnts_%d[] = { %s0 };\n", j, buf);
+ str[j] = strcpy(alloc(strlen(buf) + 1), buf);
+ }
+ nts[i++] = j;
+ }
+ print("\nstatic short *%Pnts[] = {\n");
+ for (i = j = 0, r = rules; r; r = r->link) {
+ for ( ; j < r->ern; j++)
+ print("%10,%1/* %d */\n", j);
+ print("%1%Pnts_%d,%1/* %d */\n", nts[i++], j++);
+ }
+ print("};\n\n");
+}
+
+/* emitrecalc - emit code that tests for recalculation of INDIR?(VREGP) */
+static void emitrecalc(char *pre, Term root, Term kid) {
+ if (root->kind == TERM && strncmp(root->name, "INDIR", 5) == 0
+ && kid->kind == TERM && strcmp(kid->name, "VREGP" ) == 0) {
+ Nonterm p;
+ print("%sif (mayrecalc(a)) {\n", pre);
+ print("%s%1struct %Pstate *q = a->syms[RX]->u.t.cse->x.state;\n", pre);
+ for (p = nts; p; p = p->link) {
+ print("%s%1if (q->cost[%P%S_NT] == 0) {\n", pre, p);
+ print("%s%2p->cost[%P%S_NT] = 0;\n", pre, p);
+ print("%s%2p->rule.%P%S = q->rule.%P%S;\n", pre, p, p);
+ print("%s%1}\n", pre);
+ }
+ print("%s}\n", pre);
+ }
+}
+
+/* emitrecord - emit code that tests for a winning match of rule r */
+static void emitrecord(char *pre, Rule r, char *c, int cost) {
+ if (Tflag)
+ print("%s%Ptrace(a, %d, %s + %d, p->cost[%P%S_NT]);\n",
+ pre, r->ern, c, cost, r->lhs);
+ print("%sif (", pre);
+ print("%s + %d < p->cost[%P%S_NT]) {\n"
+"%s%1p->cost[%P%S_NT] = %s + %d;\n%s%1p->rule.%P%S = %d;\n",
+ c, cost, r->lhs, pre, r->lhs, c, cost, pre, r->lhs,
+ r->packed);
+ if (r->lhs->chain)
+ print("%s%1%Pclosure_%S(a, %s + %d);\n", pre, r->lhs, c, cost);
+ print("%s}\n", pre);
+}
+
+/* emitrule - emit decoding vectors and _rule */
+static void emitrule(Nonterm nts) {
+ Nonterm p;
+
+ for (p = nts; p; p = p->link) {
+ Rule r;
+ print("static short %Pdecode_%S[] = {\n%10,\n", p);
+ for (r = p->rules; r; r = r->decode)
+ print("%1%d,\n", r->ern);
+ print("};\n\n");
+ }
+ print("static int %Prule(void *state, int goalnt) {\n"
+"%1if (goalnt < 1 || goalnt > %d)\n%2fatal(\"%Prule\", \"Bad goal nonterminal %%d\\n\", goalnt);\n"
+"%1if (!state)\n%2return 0;\n%1switch (goalnt) {\n", ntnumber);
+ for (p = nts; p; p = p->link)
+ print("%1case %P%S_NT:"
+"%1return %Pdecode_%S[((struct %Pstate *)state)->rule.%P%S];\n", p, p, p);
+ print("%1default:\n%2fatal(\"%Prule\", \"Bad goal nonterminal %%d\\n\", goalnt);\n%2return 0;\n%1}\n}\n\n");
+}
+
+/* emitstring - emit arrays of templates, instruction flags, and rules */
+static void emitstring(Rule rules) {
+ Rule r;
+
+ print("static char *%Ptemplates[] = {\n");
+ print("/* 0 */%10,\n");
+ for (r = rules; r; r = r->link)
+ print("/* %d */%1\"%s\",%1/* %R */\n", r->ern, r->template, r);
+ print("};\n");
+ print("\nstatic char %Pisinstruction[] = {\n");
+ print("/* 0 */%10,\n");
+ for (r = rules; r; r = r->link) {
+ int len = strlen(r->template);
+ print("/* %d */%1%d,%1/* %s */\n", r->ern,
+ len >= 2 && r->template[len-2] == '\\' && r->template[len-1] == 'n',
+ r->template);
+ }
+ print("};\n");
+ print("\nstatic char *%Pstring[] = {\n");
+ print("/* 0 */%10,\n");
+ for (r = rules; r; r = r->link)
+ print("/* %d */%1\"%R\",\n", r->ern, r);
+ print("};\n\n");
+}
+
+/* emitstruct - emit the definition of the state structure */
+static void emitstruct(Nonterm nts, int ntnumber) {
+ print("struct %Pstate {\n%1short cost[%d];\n%1struct {\n", ntnumber + 1);
+ for ( ; nts; nts = nts->link) {
+ int n = 1, m = nts->lhscount;
+ while ((m >>= 1) != 0)
+ n++;
+ print("%2unsigned int %P%S:%d;\n", nts, n);
+ }
+ print("%1} rule;\n};\n\n");
+}
+
+/* emittest - emit clause for testing a match */
+static void emittest(Tree t, char *v, char *suffix) {
+ Term p = t->op;
+
+ if (p->kind == TERM) {
+ print("%3%s->op == %d%s/* %S */\n", v, p->esn,
+ t->nterms > 1 ? " && " : suffix, p);
+ if (t->left)
+ emittest(t->left, stringf("LEFT_CHILD(%s)", v),
+ t->right && t->right->nterms ? " && " : suffix);
+ if (t->right)
+ emittest(t->right, stringf("RIGHT_CHILD(%s)", v), suffix);
+ }
+}
diff --git a/lcc/lburg/lburg.h b/lcc/lburg/lburg.h
new file mode 100755
index 0000000..238fe98
--- /dev/null
+++ b/lcc/lburg/lburg.h
@@ -0,0 +1,65 @@
+#ifndef BURG_INCLUDED
+#define BURG_INCLUDED
+
+/* iburg.c: */
+extern void *alloc(int nbytes);
+
+typedef enum { TERM=1, NONTERM } Kind;
+typedef struct rule *Rule;
+typedef struct term *Term;
+struct term { /* terminals: */
+ char *name; /* terminal name */
+ Kind kind; /* TERM */
+ int esn; /* external symbol number */
+ int arity; /* operator arity */
+ Term link; /* next terminal in esn order */
+ Rule rules; /* rules whose pattern starts with term */
+};
+
+typedef struct nonterm *Nonterm;
+struct nonterm { /* nonterminals: */
+ char *name; /* nonterminal name */
+ Kind kind; /* NONTERM */
+ int number; /* identifying number */
+ int lhscount; /* # times nt appears in a rule lhs */
+ int reached; /* 1 iff reached from start nonterminal */
+ Rule rules; /* rules w/nonterminal on lhs */
+ Rule chain; /* chain rules w/nonterminal on rhs */
+ Nonterm link; /* next terminal in number order */
+};
+extern Nonterm nonterm(char *id);
+extern Term term(char *id, int esn);
+
+typedef struct tree *Tree;
+struct tree { /* tree patterns: */
+ void *op; /* a terminal or nonterminal */
+ Tree left, right; /* operands */
+ int nterms; /* number of terminal nodes in this tree */
+};
+extern Tree tree(char *op, Tree left, Tree right);
+
+struct rule { /* rules: */
+ Nonterm lhs; /* lefthand side nonterminal */
+ Tree pattern; /* rule pattern */
+ int ern; /* external rule number */
+ int packed; /* packed external rule number */
+ int cost; /* cost, if a constant */
+ char *code; /* cost, if an expression */
+ char *template; /* assembler template */
+ Rule link; /* next rule in ern order */
+ Rule next; /* next rule with same pattern root */
+ Rule chain; /* next chain rule with same rhs */
+ Rule decode; /* next rule with same lhs */
+ Rule kids; /* next rule with same _kids pattern */
+};
+extern Rule rule(char *id, Tree pattern, char *template, char *code);
+
+/* gram.y: */
+void yyerror(char *fmt, ...);
+int yyparse(void);
+void yywarn(char *fmt, ...);
+extern int errcnt;
+extern FILE *infp;
+extern FILE *outfp;
+
+#endif
diff --git a/lcc/lib/assert.c b/lcc/lib/assert.c
new file mode 100755
index 0000000..5ef6367
--- /dev/null
+++ b/lcc/lib/assert.c
@@ -0,0 +1,15 @@
+#include <stdio.h>
+#include <stdlib.h>
+
+
+int _assert(char *e, char *file, int line) {
+ fprintf(stderr, "assertion failed:");
+ if (e)
+ fprintf(stderr, " %s", e);
+ if (file)
+ fprintf(stderr, " file %s", file);
+ fprintf(stderr, " line %d\n", line);
+ fflush(stderr);
+ abort();
+ return 0;
+}
diff --git a/lcc/lib/bbexit.c b/lcc/lib/bbexit.c
new file mode 100755
index 0000000..1d14bf6
--- /dev/null
+++ b/lcc/lib/bbexit.c
@@ -0,0 +1,123 @@
+#include <stdio.h>
+#include <stdlib.h>
+
+
+struct callsite {
+ char *file, *name;
+ union coordinate {
+ struct { unsigned int index:6,x:10,y:16; } be;
+ struct { unsigned int y:16,x:10,index:6; } le;
+ unsigned int coord;
+ } u;
+} *_caller;
+
+static struct _bbdata {
+ struct _bbdata *link;
+ unsigned npoints, *counts;
+ union coordinate *coords;
+ char **files;
+ struct func {
+ struct func *link;
+ struct caller {
+ struct caller *link;
+ struct callsite *caller;
+ unsigned count;
+ } *callers;
+ char *name;
+ union coordinate src;
+ } *funcs;
+} tail, *_bblist = &tail;
+
+static void unpack(unsigned int coord, int *index, int *x, int *y) {
+ static union { int x; char endian; } little = { 1 };
+ union coordinate u;
+
+ u.coord = coord;
+ if (little.endian) {
+ *index = u.le.index;
+ *x = u.le.x;
+ *y = u.le.y;
+ } else {
+ *index = u.be.index;
+ *x = u.be.x;
+ *y = u.be.y;
+ }
+}
+
+static void profout(struct _bbdata *p, FILE *fp) {
+ int i, index, x, y;
+ struct func *f;
+ struct caller *q;
+
+ for (i = 0; p->files[i]; i++)
+ ;
+ fprintf(fp, "%d\n", i);
+ for (i = 0; p->files[i]; i++)
+ fprintf(fp, "%s\n", p->files[i]);
+ for (i = 0, f = p->funcs; f; i++, f = f->link)
+ if (q = f->callers)
+ for (i--; q; q = q->link)
+ i++;
+ fprintf(fp, "%d\n", i);
+ for (f = p->funcs; f; f = f->link) {
+ int n = 0;
+ for (q = f->callers; q; n += q->count, q = q->link) {
+ unpack(f->src.coord, &index, &x, &y);
+ fprintf(fp, "%s %d %d %d %d", f->name, index, x, y, q->count);
+ if (q->caller) {
+ unpack(q->caller->u.coord, &index, &x, &y);
+ fprintf(fp, " %s %s %d %d\n", q->caller->name, q->caller->file, x, y);
+ } else
+ fprintf(fp, " ? ? 0 0\n");
+ }
+ if (n == 0) {
+ unpack(f->src.coord, &index, &x, &y);
+ fprintf(fp, "%s %d %d %d 0 ? ? 0 0\n", f->name, index, x, y);
+ }
+ }
+ fprintf(fp, "%d\n", p->npoints);
+ for (i = 0; i < p->npoints; i++) {
+ unpack(p->coords[i].coord, &index, &x, &y);
+ fprintf(fp, "%d %d %d %d\n", index, x, y, p->counts[i]);
+ }
+}
+
+static void bbexit(void) {
+ FILE *fp;
+
+ if (_bblist != &tail && (fp = fopen("prof.out", "a"))) {
+ for ( ; _bblist != &tail; _bblist = _bblist->link)
+ profout(_bblist, fp);
+ fclose(fp);
+ }
+}
+
+void _epilogue(struct func *callee) {
+ _caller = 0;
+}
+
+void _prologue(struct func *callee, struct _bbdata *yylink) {
+ static struct caller callers[4096];
+ static int next;
+ struct caller *p;
+
+ if (!yylink->link) {
+ yylink->link = _bblist;
+ _bblist = yylink;
+ if (next == 0)
+ atexit(bbexit);
+ }
+ for (p = callee->callers; p; p = p->link)
+ if (p->caller == _caller) {
+ p->count++;
+ break;
+ }
+ if (!p && next < sizeof callers/sizeof callers[0]) {
+ p = &callers[next++];
+ p->caller = _caller;
+ p->count = 1;
+ p->link = callee->callers;
+ callee->callers = p;
+ }
+ _caller = 0;
+}
diff --git a/lcc/lib/yynull.c b/lcc/lib/yynull.c
new file mode 100755
index 0000000..8c01190
--- /dev/null
+++ b/lcc/lib/yynull.c
@@ -0,0 +1,12 @@
+#include <stdio.h>
+#include <stdlib.h>
+
+
+void _YYnull(char *file, int line) {
+ fprintf(stderr, "null pointer dereferenced:");
+ if (file)
+ fprintf(stderr, " file %s,", file);
+ fprintf(stderr, " line %d\n", line);
+ fflush(stderr);
+ abort();
+}
diff --git a/lcc/makefile b/lcc/makefile
new file mode 100755
index 0000000..475a15e
--- /dev/null
+++ b/lcc/makefile
@@ -0,0 +1,310 @@
+# $Id: makefile 145 2001-10-17 21:53:10Z timo $
+HOSTFILE=etc/linux.c
+TEMPDIR=/tmp
+A=.a
+O=.o
+E=
+CC=cc
+CFLAGS=-g
+LDFLAGS=
+LD=cc
+AR=ar ruv
+RANLIB=ranlib
+DIFF=diff
+RM=rm -f
+RMDIR=rmdir
+TSTDIR=$(BUILDDIR)/$(TARGET)/tst
+CUSTOM=custom.mk
+include $(CUSTOM)
+B=$(BUILDDIR)/
+T=$(TSTDIR)/
+
+# $Id: makefile 145 2001-10-17 21:53:10Z timo $
+
+what:
+ -@echo make all rcc lburg cpp lcc bprint liblcc triple clean clobber
+
+all:: rcc lburg cpp lcc bprint liblcc
+
+rcc: $Brcc$E
+lburg: $Blburg$E
+cpp: $Bcpp$E
+lcc: $Blcc$E
+bprint: $Bbprint$E
+liblcc: $Bliblcc$A
+
+RCCOBJS=$Balloc$O \
+ $Bbind$O \
+ $Bdag$O \
+ $Bdagcheck$O \
+ $Bdecl$O \
+ $Benode$O \
+ $Berror$O \
+ $Bexpr$O \
+ $Bevent$O \
+ $Binit$O \
+ $Binits$O \
+ $Binput$O \
+ $Blex$O \
+ $Blist$O \
+ $Bmain$O \
+ $Boutput$O \
+ $Bprof$O \
+ $Bprofio$O \
+ $Bsimp$O \
+ $Bstmt$O \
+ $Bstring$O \
+ $Bsym$O \
+ $Btrace$O \
+ $Btree$O \
+ $Btypes$O \
+ $Bnull$O \
+ $Bsymbolic$O \
+ $Bgen$O \
+ $Bbytecode$O \
+ $Balpha$O \
+ $Bmips$O \
+ $Bsparc$O \
+ $Bstab$O \
+ $Bx86$O \
+ $Bx86linux$O
+
+$Brcc$E:: $Bmain$O $Blibrcc$A $(EXTRAOBJS)
+ $(LD) $(LDFLAGS) -o $@ $Bmain$O $(EXTRAOBJS) $Blibrcc$A $(EXTRALIBS)
+
+$Blibrcc$A: $(RCCOBJS)
+ $(AR) $@ $(RCCOBJS); $(RANLIB) $@ || true
+
+$(RCCOBJS): src/c.h src/token.h src/config.h
+
+$Balloc$O: src/alloc.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/alloc.c
+$Bbind$O: src/bind.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/bind.c
+$Bdag$O: src/dag.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/dag.c
+$Bdecl$O: src/decl.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/decl.c
+$Benode$O: src/enode.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/enode.c
+$Berror$O: src/error.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/error.c
+$Bevent$O: src/event.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/event.c
+$Bexpr$O: src/expr.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/expr.c
+$Bgen$O: src/gen.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/gen.c
+$Binit$O: src/init.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/init.c
+$Binits$O: src/inits.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/inits.c
+$Binput$O: src/input.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/input.c
+$Blex$O: src/lex.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/lex.c
+$Blist$O: src/list.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/list.c
+$Bmain$O: src/main.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/main.c
+$Bnull$O: src/null.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/null.c
+$Boutput$O: src/output.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/output.c
+$Bprof$O: src/prof.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/prof.c
+$Bprofio$O: src/profio.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/profio.c
+$Bsimp$O: src/simp.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/simp.c
+$Bstmt$O: src/stmt.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/stmt.c
+$Bstring$O: src/string.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/string.c
+$Bsym$O: src/sym.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/sym.c
+$Bsymbolic$O: src/symbolic.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/symbolic.c
+$Bbytecode$O: src/bytecode.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/bytecode.c
+$Btrace$O: src/trace.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/trace.c
+$Btree$O: src/tree.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/tree.c
+$Btypes$O: src/types.c; $(CC) $(CFLAGS) -c -Isrc -o $@ src/types.c
+$Bstab$O: src/stab.c src/stab.h; $(CC) $(CFLAGS) -c -Isrc -o $@ src/stab.c
+
+$Bdagcheck$O: $Bdagcheck.c; $(CC) $(CFLAGS) -c -Isrc -o $@ $Bdagcheck.c
+$Balpha$O: $Balpha.c; $(CC) $(CFLAGS) -c -Isrc -o $@ $Balpha.c
+$Bmips$O: $Bmips.c; $(CC) $(CFLAGS) -c -Isrc -o $@ $Bmips.c
+$Bsparc$O: $Bsparc.c; $(CC) $(CFLAGS) -c -Isrc -o $@ $Bsparc.c
+$Bx86$O: $Bx86.c; $(CC) $(CFLAGS) -c -Isrc -o $@ $Bx86.c
+$Bx86linux$O: $Bx86linux.c; $(CC) $(CFLAGS) -c -Isrc -o $@ $Bx86linux.c
+
+$Bdagcheck.c: $Blburg$E src/dagcheck.md; $Blburg src/dagcheck.md $@
+$Balpha.c: $Blburg$E src/alpha.md; $Blburg src/alpha.md $@
+$Bmips.c: $Blburg$E src/mips.md; $Blburg src/mips.md $@
+$Bsparc.c: $Blburg$E src/sparc.md; $Blburg src/sparc.md $@
+$Bx86.c: $Blburg$E src/x86.md; $Blburg src/x86.md $@
+$Bx86linux.c: $Blburg$E src/x86linux.md; $Blburg src/x86linux.md $@
+
+$Brcc.h: src/rcc.asdl; $(ASDL_HOME)/bin/asdlGen --c -d $B src/rcc.asdl
+$Brcc$O: $Brcc.h; $(CC) $(CFLAGS) -c -Isrc -I$B -I$(ASDL_HOME)/include/asdlGen -o $@ $Brcc.c
+$Basdl$O: src/asdl.c $Brcc.h src/c.h; $(CC) $(CFLAGS) -c -Isrc -I$B -I$(ASDL_HOME)/include/asdlGen -o $@ src/asdl.c
+$Bpass2$O: src/pass2.c $Brcc.h src/c.h; $(CC) $(CFLAGS) -c -Isrc -I$B -I$(ASDL_HOME)/include/asdlGen -o $@ src/pass2.c
+$B2html$O: src/2html.c $Brcc.h src/c.h; $(CC) $(CFLAGS) -c -Isrc -I$B -I$(ASDL_HOME)/include/asdlGen -o $@ src/2html.c
+
+$Bpass2$E: $Bpass2$O $(EXTRAOBJS) $Blibrcc$A; $(LD) $(LDFLAGS) -o $@ $Bpass2$O $(EXTRAOBJS) $Blibrcc$A $(EXTRALIBS)
+$B2html$E: $B2html$O $Brcc$O; $(LD) $(LDFLAGS) -o $@ $B2html$O $Brcc$O $(EXTRALIBS)
+
+$Bbprint$E: $Bbprint$O; $(LD) $(LDFLAGS) -o $@ $Bbprint$O
+
+$Bbprint$O: etc/bprint.c; $(CC) $(CFLAGS) -c -Isrc -o $@ etc/bprint.c
+
+$Blcc$E: $Blcc$O $Bhost$O; $(LD) $(LDFLAGS) -o $@ $Blcc$O $Bhost$O
+
+SYSTEM=$(shell cc -print-search-dirs | head -n 1 | cut -b 10-)
+
+$Blcc$O: etc/lcc.c; $(CC) $(CFLAGS) -c -DTEMPDIR=\"$(TEMPDIR)\" -o $@ etc/lcc.c
+$Bhost$O: $(HOSTFILE); $(CC) $(CFLAGS) -c -DSYSTEM=\"$(SYSTEM)\" -o $@ $(HOSTFILE)
+
+LIBOBJS=$Bassert$O $Bbbexit$O $Byynull$O
+
+$Bliblcc$A: $(LIBOBJS); $(AR) $@ $Bassert$O $Bbbexit$O $Byynull$O; $(RANLIB) $@ || true
+
+$Bassert$O: lib/assert.c; $(CC) $(CFLAGS) -c -o $@ lib/assert.c
+$Byynull$O: lib/yynull.c; $(CC) $(CFLAGS) -c -o $@ lib/yynull.c
+$Bbbexit$O: lib/bbexit.c; $(CC) $(CFLAGS) -c -o $@ lib/bbexit.c
+
+$Blburg$E: $Blburg$O $Bgram$O; $(LD) $(LDFLAGS) -o $@ $Blburg$O $Bgram$O
+
+$Blburg$O $Bgram$O: lburg/lburg.h
+
+$Blburg$O: lburg/lburg.c; $(CC) $(CFLAGS) -c -Ilburg -o $@ lburg/lburg.c
+$Bgram$O: lburg/gram.c; $(CC) $(CFLAGS) -c -Ilburg -o $@ lburg/gram.c
+
+CPPOBJS=$Bcpp$O $Blexer$O $Bnlist$O $Btokens$O $Bmacro$O $Beval$O \
+ $Binclude$O $Bhideset$O $Bgetopt$O $Bunix$O
+
+$Bcpp$E: $(CPPOBJS)
+ $(LD) $(LDFLAGS) -o $@ $(CPPOBJS)
+
+$(CPPOBJS): cpp/cpp.h
+
+$Bcpp$O: cpp/cpp.c; $(CC) $(CFLAGS) -c -Icpp -o $@ cpp/cpp.c
+$Blexer$O: cpp/lex.c; $(CC) $(CFLAGS) -c -Icpp -o $@ cpp/lex.c
+$Bnlist$O: cpp/nlist.c; $(CC) $(CFLAGS) -c -Icpp -o $@ cpp/nlist.c
+$Btokens$O: cpp/tokens.c; $(CC) $(CFLAGS) -c -Icpp -o $@ cpp/tokens.c
+$Bmacro$O: cpp/macro.c; $(CC) $(CFLAGS) -c -Icpp -o $@ cpp/macro.c
+$Beval$O: cpp/eval.c; $(CC) $(CFLAGS) -c -Icpp -o $@ cpp/eval.c
+$Binclude$O: cpp/include.c; $(CC) $(CFLAGS) -c -Icpp -o $@ cpp/include.c
+$Bhideset$O: cpp/hideset.c; $(CC) $(CFLAGS) -c -Icpp -o $@ cpp/hideset.c
+$Bgetopt$O: cpp/getopt.c; $(CC) $(CFLAGS) -c -Icpp -o $@ cpp/getopt.c
+$Bunix$O: cpp/unix.c; $(CC) $(CFLAGS) -c -Icpp -o $@ cpp/unix.c
+
+test: $T8q.s \
+ $Tarray.s \
+ $Tcf.s \
+ $Tcq.s \
+ $Tcvt.s \
+ $Tfields.s \
+ $Tfront.s \
+ $Tincr.s \
+ $Tinit.s \
+ $Tlimits.s \
+ $Tparanoia.s \
+ $Tsort.s \
+ $Tspill.s \
+ $Tstdarg.s \
+ $Tstruct.s \
+ $Tswitch.s \
+ $Twf1.s \
+ $Tyacc.s
+
+$T8q.s: tst/8q.c tst/8q.0 all; @env BUILDDIR=$(BUILDDIR) TSTDIR=$(TSTDIR) src/run.sh $@
+$Tarray.s: tst/array.c tst/array.0 all; @env BUILDDIR=$(BUILDDIR) TSTDIR=$(TSTDIR) src/run.sh $@
+$Tcf.s: tst/cf.c tst/cf.0 all; @env BUILDDIR=$(BUILDDIR) TSTDIR=$(TSTDIR) src/run.sh $@
+$Tcq.s: tst/cq.c tst/cq.0 all; @env BUILDDIR=$(BUILDDIR) TSTDIR=$(TSTDIR) src/run.sh $@
+$Tcvt.s: tst/cvt.c tst/cvt.0 all; @env BUILDDIR=$(BUILDDIR) TSTDIR=$(TSTDIR) src/run.sh $@
+$Tfields.s: tst/fields.c tst/fields.0 all; @env BUILDDIR=$(BUILDDIR) TSTDIR=$(TSTDIR) src/run.sh $@
+$Tfront.s: tst/front.c tst/front.0 all; @env BUILDDIR=$(BUILDDIR) TSTDIR=$(TSTDIR) src/run.sh $@
+$Tincr.s: tst/incr.c tst/incr.0 all; @env BUILDDIR=$(BUILDDIR) TSTDIR=$(TSTDIR) src/run.sh $@
+$Tinit.s: tst/init.c tst/init.0 all; @env BUILDDIR=$(BUILDDIR) TSTDIR=$(TSTDIR) src/run.sh $@
+$Tlimits.s: tst/limits.c tst/limits.0 all; @env BUILDDIR=$(BUILDDIR) TSTDIR=$(TSTDIR) src/run.sh $@
+$Tparanoia.s: tst/paranoia.c tst/paranoia.0 all; @env BUILDDIR=$(BUILDDIR) TSTDIR=$(TSTDIR) src/run.sh $@
+$Tsort.s: tst/sort.c tst/sort.0 all; @env BUILDDIR=$(BUILDDIR) TSTDIR=$(TSTDIR) src/run.sh $@
+$Tspill.s: tst/spill.c tst/spill.0 all; @env BUILDDIR=$(BUILDDIR) TSTDIR=$(TSTDIR) src/run.sh $@
+$Tstdarg.s: tst/stdarg.c tst/stdarg.0 all; @env BUILDDIR=$(BUILDDIR) TSTDIR=$(TSTDIR) src/run.sh $@
+$Tstruct.s: tst/struct.c tst/struct.0 all; @env BUILDDIR=$(BUILDDIR) TSTDIR=$(TSTDIR) src/run.sh $@
+$Tswitch.s: tst/switch.c tst/switch.0 all; @env BUILDDIR=$(BUILDDIR) TSTDIR=$(TSTDIR) src/run.sh $@
+$Twf1.s: tst/wf1.c tst/wf1.0 all; @env BUILDDIR=$(BUILDDIR) TSTDIR=$(TSTDIR) src/run.sh $@
+$Tyacc.s: tst/yacc.c tst/yacc.0 all; @env BUILDDIR=$(BUILDDIR) TSTDIR=$(TSTDIR) src/run.sh $@
+
+testclean:
+ $(RM) $T8q$E $T8q.s $T8q.2 $T8q.1
+ $(RM) $Tarray$E $Tarray.s $Tarray.2 $Tarray.1
+ $(RM) $Tcf$E $Tcf.s $Tcf.2 $Tcf.1
+ $(RM) $Tcq$E $Tcq.s $Tcq.2 $Tcq.1
+ $(RM) $Tcvt$E $Tcvt.s $Tcvt.2 $Tcvt.1
+ $(RM) $Tfields$E $Tfields.s $Tfields.2 $Tfields.1
+ $(RM) $Tfront$E $Tfront.s $Tfront.2 $Tfront.1
+ $(RM) $Tincr$E $Tincr.s $Tincr.2 $Tincr.1
+ $(RM) $Tinit$E $Tinit.s $Tinit.2 $Tinit.1
+ $(RM) $Tlimits$E $Tlimits.s $Tlimits.2 $Tlimits.1
+ $(RM) $Tparanoia$E $Tparanoia.s $Tparanoia.2 $Tparanoia.1
+ $(RM) $Tsort$E $Tsort.s $Tsort.2 $Tsort.1
+ $(RM) $Tspill$E $Tspill.s $Tspill.2 $Tspill.1
+ $(RM) $Tstdarg$E $Tstdarg.s $Tstdarg.2 $Tstdarg.1
+ $(RM) $Tstruct$E $Tstruct.s $Tstruct.2 $Tstruct.1
+ $(RM) $Tswitch$E $Tswitch.s $Tswitch.2 $Tswitch.1
+ $(RM) $Twf1$E $Twf1.s $Twf1.2 $Twf1.1
+ $(RM) $Tyacc$E $Tyacc.s $Tyacc.2 $Tyacc.1
+
+install:: all
+ install -d /usr/local/lib/lcc
+ install -d /usr/local/lib/lcc/gcc
+ install $Blcc$E /usr/local/bin
+ install $Bcpp$E /usr/local/lib/lcc/gcc
+ install $Brcc$E /usr/local/lib/lcc
+ install $Bliblcc$A /usr/local/lib/lcc
+ install $Blibrcc$A /usr/local/lib/lcc
+
+uninstall::
+ $(RM) /usr/local/lib/lcc/librcc$A
+ $(RM) /usr/local/lib/lcc/liblcc$A
+ $(RM) /usr/local/lib/lcc/rcc$E
+ $(RM) /usr/local/lib/lcc/gcc/cpp$E
+ $(RM) /usr/local/bin/lcc$E
+ $(RMDIR) /usr/local/lib/lcc/gcc
+ $(RMDIR) /usr/local/lib/lcc
+
+clean:: testclean
+ $(RM) $B*$O
+ $(RM) $Bdagcheck.c $Balpha.c $Bmips.c $Bx86.c $Bsparc.c $Bx86linux.c $Bgram.c
+ $(RM) $Brcc.c $Brcc.h
+ $(RM) $Brcc1$E $Brcc1$E $B1rcc$E $B2rcc$E
+ $(RM) $B*.ilk
+
+clobber:: clean
+ $(RM) $Brcc$E $B2html$E $Bpass2$E $Blburg$E $Bcpp$E $Blcc$E $Bbprint$E $B*$A
+ $(RM) $B*.pdb $B*.pch
+
+RCCSRCS=src/alloc.c \
+ src/bind.c \
+ src/dag.c \
+ src/decl.c \
+ src/enode.c \
+ src/error.c \
+ src/expr.c \
+ src/event.c \
+ src/init.c \
+ src/inits.c \
+ src/input.c \
+ src/lex.c \
+ src/list.c \
+ src/main.c \
+ src/output.c \
+ src/prof.c \
+ src/profio.c \
+ src/simp.c \
+ src/stmt.c \
+ src/string.c \
+ src/sym.c \
+ src/trace.c \
+ src/tree.c \
+ src/types.c \
+ src/null.c \
+ src/symbolic.c \
+ src/bytecode.c \
+ src/gen.c \
+ src/stab.c \
+ $Bdagcheck.c \
+ $Balpha.c \
+ $Bmips.c \
+ $Bsparc.c \
+ $Bx86linux.c \
+ $Bx86.c
+
+C=$Blcc -A -d0.6 -Wo-lccdir=$(BUILDDIR) -Isrc -I$(BUILDDIR)
+triple: $Brcc$E $Blcc$E $Bcpp$E
+ $C -o $B1rcc$E -B$B $(RCCSRCS)
+ $C -o $B2rcc$E -B$B1 $(RCCSRCS)
+ strip $B1rcc$E $B2rcc$E
+ dd if=$B1rcc$E of=$Brcc1$E bs=512 skip=1
+ dd if=$B2rcc$E of=$Brcc2$E bs=512 skip=1
+ if cmp $Brcc1$E $Brcc2$E; then \
+ mv $B2rcc$E $Brcc$E; \
+ $(RM) $B1rcc$E $Brcc[12]$E; fi
diff --git a/lcc/makefile.nt b/lcc/makefile.nt
new file mode 100755
index 0000000..2cd94b0
--- /dev/null
+++ b/lcc/makefile.nt
@@ -0,0 +1,383 @@
+# $Id: makefile.nt 314 2002-10-05 17:07:57Z timo $
+HOSTFILE=etc/win32.c
+TARGET=x86\win32
+TEMPDIR=\\temp
+A=.lib
+O=.obj
+E=.exe
+CC=cl -nologo
+CFLAGS=-DWIN32 -Zi -MLd -Fd$(BUILDDIR)^\
+LD=cl -nologo
+LDFLAGS=-Zi -MLd -Fd$(BUILDDIR)^\
+B=$(BUILDDIR)^\
+T=$B$(TARGET)\tst^\
+C=$Blcc -Wo-lccdir=$(BUILDDIR) -Wf-target=$(TARGET) -I$B$(TARGET)/include
+# $Id: makefile.nt 314 2002-10-05 17:07:57Z timo $
+
+what:
+ -@echo make all q3rcc lburg q3cpp lcc bprint liblcc triple clean clobber
+
+all:: q3rcc lburg q3cpp lcc bprint liblcc
+
+q3rcc: $Bq3rcc$E
+lburg: $Blburg$E
+q3cpp: $Bq3cpp$E
+lcc: $Blcc$E
+bprint: $Bbprint$E
+liblcc: $Bliblcc$A
+
+RCCOBJS=$Balloc$O \
+ $Bbind$O \
+ $Bdag$O \
+ $Bdagcheck$O \
+ $Bdecl$O \
+ $Benode$O \
+ $Berror$O \
+ $Bexpr$O \
+ $Bevent$O \
+ $Binit$O \
+ $Binits$O \
+ $Binput$O \
+ $Blex$O \
+ $Blist$O \
+ $Bmain$O \
+ $Boutput$O \
+ $Bprof$O \
+ $Bprofio$O \
+ $Bsimp$O \
+ $Bstmt$O \
+ $Bstring$O \
+ $Bsym$O \
+ $Btrace$O \
+ $Btree$O \
+ $Btypes$O \
+ $Bnull$O \
+ $Bsymbolic$O \
+ $Bgen$O \
+ $Bbytecode$O \
+ $Balpha$O \
+ $Bmips$O \
+ $Bsparc$O \
+ $Bstab$O \
+ $Bx86$O \
+ $Bx86linux$O
+
+$Bq3rcc$E:: $Bmain$O $Blibrcc$A $(EXTRAOBJS)
+ $(LD) $(LDFLAGS) -Fe$@ $Bmain$O $(EXTRAOBJS) $Blibrcc$A $(EXTRALIBS)
+
+$Blibrcc$A: $(RCCOBJS)
+ lib -out:$@ $(RCCOBJS)
+
+$(RCCOBJS): src/c.h src/token.h src/config.h
+
+$Balloc$O: src/alloc.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/alloc.c
+$Bbind$O: src/bind.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/bind.c
+$Bdag$O: src/dag.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/dag.c
+$Bdecl$O: src/decl.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/decl.c
+$Benode$O: src/enode.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/enode.c
+$Berror$O: src/error.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/error.c
+$Bevent$O: src/event.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/event.c
+$Bexpr$O: src/expr.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/expr.c
+$Bgen$O: src/gen.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/gen.c
+$Binit$O: src/init.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/init.c
+$Binits$O: src/inits.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/inits.c
+$Binput$O: src/input.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/input.c
+$Blex$O: src/lex.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/lex.c
+$Blist$O: src/list.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/list.c
+$Bmain$O: src/main.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/main.c
+$Bnull$O: src/null.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/null.c
+$Boutput$O: src/output.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/output.c
+$Bprof$O: src/prof.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/prof.c
+$Bprofio$O: src/profio.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/profio.c
+$Bsimp$O: src/simp.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/simp.c
+$Bstmt$O: src/stmt.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/stmt.c
+$Bstring$O: src/string.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/string.c
+$Bsym$O: src/sym.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/sym.c
+$Bsymbolic$O: src/symbolic.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/symbolic.c
+$Bbytecode$O: src/bytecode.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/bytecode.c
+$Btrace$O: src/trace.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/trace.c
+$Btree$O: src/tree.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/tree.c
+$Btypes$O: src/types.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/types.c
+$Bstab$O: src/stab.c src/stab.h; $(CC) $(CFLAGS) -c -Isrc -Fo$@ src/stab.c
+
+$Bdagcheck$O: $Bdagcheck.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ $Bdagcheck.c
+$Balpha$O: $Balpha.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ $Balpha.c
+$Bmips$O: $Bmips.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ $Bmips.c
+$Bsparc$O: $Bsparc.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ $Bsparc.c
+$Bx86$O: $Bx86.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ $Bx86.c
+$Bx86linux$O: $Bx86linux.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ $Bx86linux.c
+
+$Bdagcheck.c: $Blburg$E src/dagcheck.md; $Blburg src/dagcheck.md $@
+$Balpha.c: $Blburg$E src/alpha.md; $Blburg src/alpha.md $@
+$Bmips.c: $Blburg$E src/mips.md; $Blburg src/mips.md $@
+$Bsparc.c: $Blburg$E src/sparc.md; $Blburg src/sparc.md $@
+$Bx86.c: $Blburg$E src/x86.md; $Blburg src/x86.md $@
+$Bx86linux.c: $Blburg$E src/x86linux.md; $Blburg src/x86linux.md $@
+
+$Brcc.h: src/rcc.asdl; $(ASDL_HOME)/bin/asdlGen --c -d $B src/rcc.asdl
+$Brcc$O: $Brcc.h; $(CC) $(CFLAGS) -c -Isrc -I$B -I$(ASDL_HOME)/include/asdlGen -Fo$@ $Brcc.c
+$Basdl$O: src/asdl.c $Brcc.h src/c.h; $(CC) $(CFLAGS) -c -Isrc -I$B -I$(ASDL_HOME)/include/asdlGen -Fo$@ src/asdl.c
+$Bpass2$O: src/pass2.c $Brcc.h src/c.h; $(CC) $(CFLAGS) -c -Isrc -I$B -I$(ASDL_HOME)/include/asdlGen -Fo$@ src/pass2.c
+$B2html$O: src/2html.c $Brcc.h src/c.h; $(CC) $(CFLAGS) -c -Isrc -I$B -I$(ASDL_HOME)/include/asdlGen -Fo$@ src/2html.c
+
+$Bpass2$E: $Bpass2$O $(EXTRAOBJS) $Blibrcc$A; $(LD) $(LDFLAGS) -Fe$@ $Bpass2$O $(EXTRAOBJS) $Blibrcc$A $(EXTRALIBS)
+$B2html$E: $B2html$O $Brcc$O; $(LD) $(LDFLAGS) -Fe$@ $B2html$O $Brcc$O $(EXTRALIBS)
+
+$Bbprint$E: $Bbprint$O; $(LD) $(LDFLAGS) -Fe$@ $Bbprint$O
+
+$Bbprint$O: etc/bprint.c; $(CC) $(CFLAGS) -c -Isrc -Fo$@ etc/bprint.c
+
+$Blcc$E: $Blcc$O $Bhost$O; $(LD) $(LDFLAGS) -Fe$@ $Blcc$O $Bhost$O
+
+$Blcc$O: etc/lcc.c; $(CC) $(CFLAGS) -c -DTEMPDIR=\"$(TEMPDIR)\" -Fo$@ etc/lcc.c
+$Bhost$O: $(HOSTFILE); $(CC) $(CFLAGS) -c -Fo$@ $(HOSTFILE)
+
+LIBOBJS=$Bassert$O $Bbbexit$O $Byynull$O
+
+$Bliblcc$A: $(LIBOBJS); lib -out:$@ $Bassert$O $Bbbexit$O $Byynull$O
+
+$Bassert$O: lib/assert.c; $(CC) -c -Fo$@ lib/assert.c
+$Byynull$O: lib/yynull.c; $(CC) -c -Fo$@ lib/yynull.c
+$Bbbexit$O: lib/bbexit.c; $(CC) -c -Fo$@ lib/bbexit.c
+
+$Blburg$E: $Blburg$O $Bgram$O; $(LD) $(LDFLAGS) -Fe$@ $Blburg$O $Bgram$O
+
+$Blburg$O $Bgram$O: lburg/lburg.h
+
+$Blburg$O: lburg/lburg.c; $(CC) $(CFLAGS) -c -Ilburg -Fo$@ lburg/lburg.c
+$Bgram$O: lburg/gram.c; $(CC) $(CFLAGS) -c -Ilburg -Fo$@ lburg/gram.c
+
+CPPOBJS=$Bcpp$O $Blexer$O $Bnlist$O $Btokens$O $Bmacro$O $Beval$O \
+ $Binclude$O $Bhideset$O $Bgetopt$O $Bunix$O
+
+$Bq3cpp$E: $(CPPOBJS)
+ $(LD) $(LDFLAGS) -Fe$@ $(CPPOBJS)
+
+$(CPPOBJS): cpp/cpp.h
+
+$Bcpp$O: cpp/cpp.c; $(CC) $(CFLAGS) -c -Icpp -Fo$@ cpp/cpp.c
+$Blexer$O: cpp/lex.c; $(CC) $(CFLAGS) -c -Icpp -Fo$@ cpp/lex.c
+$Bnlist$O: cpp/nlist.c; $(CC) $(CFLAGS) -c -Icpp -Fo$@ cpp/nlist.c
+$Btokens$O: cpp/tokens.c; $(CC) $(CFLAGS) -c -Icpp -Fo$@ cpp/tokens.c
+$Bmacro$O: cpp/macro.c; $(CC) $(CFLAGS) -c -Icpp -Fo$@ cpp/macro.c
+$Beval$O: cpp/eval.c; $(CC) $(CFLAGS) -c -Icpp -Fo$@ cpp/eval.c
+$Binclude$O: cpp/include.c; $(CC) $(CFLAGS) -c -Icpp -Fo$@ cpp/include.c
+$Bhideset$O: cpp/hideset.c; $(CC) $(CFLAGS) -c -Icpp -Fo$@ cpp/hideset.c
+$Bgetopt$O: cpp/getopt.c; $(CC) $(CFLAGS) -c -Icpp -Fo$@ cpp/getopt.c
+$Bunix$O: cpp/unix.c; $(CC) $(CFLAGS) -c -Icpp -Fo$@ cpp/unix.c
+
+test: $T8q.s \
+ $Tarray.s \
+ $Tcf.s \
+ $Tcq.s \
+ $Tcvt.s \
+ $Tfields.s \
+ $Tfront.s \
+ $Tincr.s \
+ $Tinit.s \
+ $Tlimits.s \
+ $Tparanoia.s \
+ $Tsort.s \
+ $Tspill.s \
+ $Tstdarg.s \
+ $Tstruct.s \
+ $Tswitch.s \
+ $Twf1.s \
+ $Tyacc.s
+
+$T8q.s: tst\8q.c tst\8q.0 all
+ -$C -S -Wf-errout=$T8q.2 -o $T8q.s tst/8q.c
+ fc $(TARGET)\tst\8q.sbk $T8q.s
+ fc $(TARGET)\tst\8q.2bk $T8q.2
+ $C -o $T8q$E $T8q.s
+ -$T8q$E <tst/8q.0 >$T8q.1
+ fc $(TARGET)\tst\8q.1bk $T8q.1
+$Tarray.s: tst\array.c tst\array.0 all
+ -$C -S -Wf-errout=$Tarray.2 -o $Tarray.s tst/array.c
+ fc $(TARGET)\tst\array.sbk $Tarray.s
+ fc $(TARGET)\tst\array.2bk $Tarray.2
+ $C -o $Tarray$E $Tarray.s
+ -$Tarray$E <tst/array.0 >$Tarray.1
+ fc $(TARGET)\tst\array.1bk $Tarray.1
+$Tcf.s: tst\cf.c tst\cf.0 all
+ -$C -S -Wf-errout=$Tcf.2 -o $Tcf.s tst/cf.c
+ fc $(TARGET)\tst\cf.sbk $Tcf.s
+ fc $(TARGET)\tst\cf.2bk $Tcf.2
+ $C -o $Tcf$E $Tcf.s
+ -$Tcf$E <tst/cf.0 >$Tcf.1
+ fc $(TARGET)\tst\cf.1bk $Tcf.1
+$Tcq.s: tst\cq.c tst\cq.0 all
+ -$C -S -Wf-errout=$Tcq.2 -o $Tcq.s tst/cq.c
+ fc $(TARGET)\tst\cq.sbk $Tcq.s
+ fc $(TARGET)\tst\cq.2bk $Tcq.2
+ $C -o $Tcq$E $Tcq.s
+ -$Tcq$E <tst/cq.0 >$Tcq.1
+ fc $(TARGET)\tst\cq.1bk $Tcq.1
+$Tcvt.s: tst\cvt.c tst\cvt.0 all
+ -$C -S -Wf-errout=$Tcvt.2 -o $Tcvt.s tst/cvt.c
+ fc $(TARGET)\tst\cvt.sbk $Tcvt.s
+ fc $(TARGET)\tst\cvt.2bk $Tcvt.2
+ $C -o $Tcvt$E $Tcvt.s
+ -$Tcvt$E <tst/cvt.0 >$Tcvt.1
+ fc $(TARGET)\tst\cvt.1bk $Tcvt.1
+$Tfields.s: tst\fields.c tst\fields.0 all
+ -$C -S -Wf-errout=$Tfields.2 -o $Tfields.s tst/fields.c
+ fc $(TARGET)\tst\fields.sbk $Tfields.s
+ fc $(TARGET)\tst\fields.2bk $Tfields.2
+ $C -o $Tfields$E $Tfields.s
+ -$Tfields$E <tst/fields.0 >$Tfields.1
+ fc $(TARGET)\tst\fields.1bk $Tfields.1
+$Tfront.s: tst\front.c tst\front.0 all
+ -$C -S -Wf-errout=$Tfront.2 -o $Tfront.s tst/front.c
+ fc $(TARGET)\tst\front.sbk $Tfront.s
+ fc $(TARGET)\tst\front.2bk $Tfront.2
+$Tincr.s: tst\incr.c tst\incr.0 all
+ -$C -S -Wf-errout=$Tincr.2 -o $Tincr.s tst/incr.c
+ fc $(TARGET)\tst\incr.sbk $Tincr.s
+ fc $(TARGET)\tst\incr.2bk $Tincr.2
+ $C -o $Tincr$E $Tincr.s
+ -$Tincr$E <tst/incr.0 >$Tincr.1
+ fc $(TARGET)\tst\incr.1bk $Tincr.1
+$Tinit.s: tst\init.c tst\init.0 all
+ -$C -S -Wf-errout=$Tinit.2 -o $Tinit.s tst/init.c
+ fc $(TARGET)\tst\init.sbk $Tinit.s
+ fc $(TARGET)\tst\init.2bk $Tinit.2
+ $C -o $Tinit$E $Tinit.s
+ -$Tinit$E <tst/init.0 >$Tinit.1
+ fc $(TARGET)\tst\init.1bk $Tinit.1
+$Tlimits.s: tst\limits.c tst\limits.0 all
+ -$C -S -Wf-errout=$Tlimits.2 -o $Tlimits.s tst/limits.c
+ fc $(TARGET)\tst\limits.sbk $Tlimits.s
+ fc $(TARGET)\tst\limits.2bk $Tlimits.2
+ $C -o $Tlimits$E $Tlimits.s
+ -$Tlimits$E <tst/limits.0 >$Tlimits.1
+ fc $(TARGET)\tst\limits.1bk $Tlimits.1
+$Tparanoia.s: tst\paranoia.c tst\paranoia.0 all
+ -$C -S -Wf-errout=$Tparanoia.2 -o $Tparanoia.s tst/paranoia.c
+ fc $(TARGET)\tst\paranoia.sbk $Tparanoia.s
+ fc $(TARGET)\tst\paranoia.2bk $Tparanoia.2
+ $C -o $Tparanoia$E $Tparanoia.s
+ -$Tparanoia$E <tst/paranoia.0 >$Tparanoia.1
+ fc $(TARGET)\tst\paranoia.1bk $Tparanoia.1
+$Tsort.s: tst\sort.c tst\sort.0 all
+ -$C -S -Wf-errout=$Tsort.2 -o $Tsort.s tst/sort.c
+ fc $(TARGET)\tst\sort.sbk $Tsort.s
+ fc $(TARGET)\tst\sort.2bk $Tsort.2
+ $C -o $Tsort$E $Tsort.s
+ -$Tsort$E <tst/sort.0 >$Tsort.1
+ fc $(TARGET)\tst\sort.1bk $Tsort.1
+$Tspill.s: tst\spill.c tst\spill.0 all
+ -$C -S -Wf-errout=$Tspill.2 -o $Tspill.s tst/spill.c
+ fc $(TARGET)\tst\spill.sbk $Tspill.s
+ fc $(TARGET)\tst\spill.2bk $Tspill.2
+ $C -o $Tspill$E $Tspill.s
+ -$Tspill$E <tst/spill.0 >$Tspill.1
+ fc $(TARGET)\tst\spill.1bk $Tspill.1
+$Tstdarg.s: tst\stdarg.c tst\stdarg.0 all
+ -$C -S -Wf-errout=$Tstdarg.2 -o $Tstdarg.s tst/stdarg.c
+ fc $(TARGET)\tst\stdarg.sbk $Tstdarg.s
+ fc $(TARGET)\tst\stdarg.2bk $Tstdarg.2
+ $C -o $Tstdarg$E $Tstdarg.s
+ -$Tstdarg$E <tst/stdarg.0 >$Tstdarg.1
+ fc $(TARGET)\tst\stdarg.1bk $Tstdarg.1
+$Tstruct.s: tst\struct.c tst\struct.0 all
+ -$C -S -Wf-errout=$Tstruct.2 -o $Tstruct.s tst/struct.c
+ fc $(TARGET)\tst\struct.sbk $Tstruct.s
+ fc $(TARGET)\tst\struct.2bk $Tstruct.2
+ $C -o $Tstruct$E $Tstruct.s
+ -$Tstruct$E <tst/struct.0 >$Tstruct.1
+ fc $(TARGET)\tst\struct.1bk $Tstruct.1
+$Tswitch.s: tst\switch.c tst\switch.0 all
+ -$C -S -Wf-errout=$Tswitch.2 -o $Tswitch.s tst/switch.c
+ fc $(TARGET)\tst\switch.sbk $Tswitch.s
+ fc $(TARGET)\tst\switch.2bk $Tswitch.2
+ $C -o $Tswitch$E $Tswitch.s
+ -$Tswitch$E <tst/switch.0 >$Tswitch.1
+ fc $(TARGET)\tst\switch.1bk $Tswitch.1
+$Twf1.s: tst\wf1.c tst\wf1.0 all
+ -$C -S -Wf-errout=$Twf1.2 -o $Twf1.s tst/wf1.c
+ fc $(TARGET)\tst\wf1.sbk $Twf1.s
+ fc $(TARGET)\tst\wf1.2bk $Twf1.2
+ $C -o $Twf1$E $Twf1.s
+ -$Twf1$E <tst/wf1.0 >$Twf1.1
+ fc $(TARGET)\tst\wf1.1bk $Twf1.1
+$Tyacc.s: tst\yacc.c tst\yacc.0 all
+ -$C -S -Wf-errout=$Tyacc.2 -o $Tyacc.s tst/yacc.c
+ fc $(TARGET)\tst\yacc.sbk $Tyacc.s
+ fc $(TARGET)\tst\yacc.2bk $Tyacc.2
+ $C -o $Tyacc$E $Tyacc.s
+ -$Tyacc$E <tst/yacc.0 >$Tyacc.1
+ fc $(TARGET)\tst\yacc.1bk $Tyacc.1
+
+testclean:
+ -del /q $T8q$E $T8q.s $T8q.2 $T8q.1
+ -del /q $Tarray$E $Tarray.s $Tarray.2 $Tarray.1
+ -del /q $Tcf$E $Tcf.s $Tcf.2 $Tcf.1
+ -del /q $Tcq$E $Tcq.s $Tcq.2 $Tcq.1
+ -del /q $Tcvt$E $Tcvt.s $Tcvt.2 $Tcvt.1
+ -del /q $Tfields$E $Tfields.s $Tfields.2 $Tfields.1
+ -del /q $Tfront$E $Tfront.s $Tfront.2 $Tfront.1
+ -del /q $Tincr$E $Tincr.s $Tincr.2 $Tincr.1
+ -del /q $Tinit$E $Tinit.s $Tinit.2 $Tinit.1
+ -del /q $Tlimits$E $Tlimits.s $Tlimits.2 $Tlimits.1
+ -del /q $Tparanoia$E $Tparanoia.s $Tparanoia.2 $Tparanoia.1
+ -del /q $Tsort$E $Tsort.s $Tsort.2 $Tsort.1
+ -del /q $Tspill$E $Tspill.s $Tspill.2 $Tspill.1
+ -del /q $Tstdarg$E $Tstdarg.s $Tstdarg.2 $Tstdarg.1
+ -del /q $Tstruct$E $Tstruct.s $Tstruct.2 $Tstruct.1
+ -del /q $Tswitch$E $Tswitch.s $Tswitch.2 $Tswitch.1
+ -del /q $Twf1$E $Twf1.s $Twf1.2 $Twf1.1
+ -del /q $Tyacc$E $Tyacc.s $Tyacc.2 $Tyacc.1
+
+clean:: testclean
+ -del /q $B*$O
+ -del /q $Bdagcheck.c $Balpha.c $Bmips.c $Bx86.c $Bsparc.c $Bx86linux.c $Bgram.c
+ -del /q $Brcc.c $Brcc.h
+ -del /q $Bq3rcc1$E $Brcc1$E $B1rcc$E $B2rcc$E
+ -del /q $B*.ilk
+
+clobber:: clean
+ -del /q $Bq3rcc$E $B2html$E $Bpass2$E $Blburg$E $Bq3cpp$E $Blcc$E $Bbprint$E $B*$A
+ -del /q $B*.pdb $B*.pch
+
+RCCSRCS=src/alloc.c \
+ src/bind.c \
+ src/dag.c \
+ src/decl.c \
+ src/enode.c \
+ src/error.c \
+ src/expr.c \
+ src/event.c \
+ src/init.c \
+ src/inits.c \
+ src/input.c \
+ src/lex.c \
+ src/list.c \
+ src/main.c \
+ src/output.c \
+ src/prof.c \
+ src/profio.c \
+ src/simp.c \
+ src/stmt.c \
+ src/string.c \
+ src/sym.c \
+ src/trace.c \
+ src/tree.c \
+ src/types.c \
+ src/null.c \
+ src/symbolic.c \
+ src/bytecode.c \
+ src/gen.c \
+ src/stab.c \
+ $Bdagcheck.c \
+ $Balpha.c \
+ $Bmips.c \
+ $Bsparc.c \
+ $Bx86linux.c \
+ $Bx86.c
+
+C=$Blcc -A -d0.6 -Wo-lccdir=$(BUILDDIR) -Isrc -I$(BUILDDIR)
+triple: $Bq3rcc$E $Blcc$E $Bq3cpp$E
+ $C -o $B1rcc$E -B$B $(RCCSRCS)
+ $C -o $B2rcc$E -B$B1 $(RCCSRCS)
+ fc /b $B1rcc$E $B2rcc$E
diff --git a/lcc/mips/irix/tst/8q.1bk b/lcc/mips/irix/tst/8q.1bk
new file mode 100755
index 0000000..c66df8e
--- /dev/null
+++ b/lcc/mips/irix/tst/8q.1bk
@@ -0,0 +1,92 @@
+1 5 8 6 3 7 2 4
+1 6 8 3 7 4 2 5
+1 7 4 6 8 2 5 3
+1 7 5 8 2 4 6 3
+2 4 6 8 3 1 7 5
+2 5 7 1 3 8 6 4
+2 5 7 4 1 8 6 3
+2 6 1 7 4 8 3 5
+2 6 8 3 1 4 7 5
+2 7 3 6 8 5 1 4
+2 7 5 8 1 4 6 3
+2 8 6 1 3 5 7 4
+3 1 7 5 8 2 4 6
+3 5 2 8 1 7 4 6
+3 5 2 8 6 4 7 1
+3 5 7 1 4 2 8 6
+3 5 8 4 1 7 2 6
+3 6 2 5 8 1 7 4
+3 6 2 7 1 4 8 5
+3 6 2 7 5 1 8 4
+3 6 4 1 8 5 7 2
+3 6 4 2 8 5 7 1
+3 6 8 1 4 7 5 2
+3 6 8 1 5 7 2 4
+3 6 8 2 4 1 7 5
+3 7 2 8 5 1 4 6
+3 7 2 8 6 4 1 5
+3 8 4 7 1 6 2 5
+4 1 5 8 2 7 3 6
+4 1 5 8 6 3 7 2
+4 2 5 8 6 1 3 7
+4 2 7 3 6 8 1 5
+4 2 7 3 6 8 5 1
+4 2 7 5 1 8 6 3
+4 2 8 5 7 1 3 6
+4 2 8 6 1 3 5 7
+4 6 1 5 2 8 3 7
+4 6 8 2 7 1 3 5
+4 6 8 3 1 7 5 2
+4 7 1 8 5 2 6 3
+4 7 3 8 2 5 1 6
+4 7 5 2 6 1 3 8
+4 7 5 3 1 6 8 2
+4 8 1 3 6 2 7 5
+4 8 1 5 7 2 6 3
+4 8 5 3 1 7 2 6
+5 1 4 6 8 2 7 3
+5 1 8 4 2 7 3 6
+5 1 8 6 3 7 2 4
+5 2 4 6 8 3 1 7
+5 2 4 7 3 8 6 1
+5 2 6 1 7 4 8 3
+5 2 8 1 4 7 3 6
+5 3 1 6 8 2 4 7
+5 3 1 7 2 8 6 4
+5 3 8 4 7 1 6 2
+5 7 1 3 8 6 4 2
+5 7 1 4 2 8 6 3
+5 7 2 4 8 1 3 6
+5 7 2 6 3 1 4 8
+5 7 2 6 3 1 8 4
+5 7 4 1 3 8 6 2
+5 8 4 1 3 6 2 7
+5 8 4 1 7 2 6 3
+6 1 5 2 8 3 7 4
+6 2 7 1 3 5 8 4
+6 2 7 1 4 8 5 3
+6 3 1 7 5 8 2 4
+6 3 1 8 4 2 7 5
+6 3 1 8 5 2 4 7
+6 3 5 7 1 4 2 8
+6 3 5 8 1 4 2 7
+6 3 7 2 4 8 1 5
+6 3 7 2 8 5 1 4
+6 3 7 4 1 8 2 5
+6 4 1 5 8 2 7 3
+6 4 2 8 5 7 1 3
+6 4 7 1 3 5 2 8
+6 4 7 1 8 2 5 3
+6 8 2 4 1 7 5 3
+7 1 3 8 6 4 2 5
+7 2 4 1 8 5 3 6
+7 2 6 3 1 4 8 5
+7 3 1 6 8 5 2 4
+7 3 8 2 5 1 6 4
+7 4 2 5 8 1 3 6
+7 4 2 8 6 1 3 5
+7 5 3 1 6 8 2 4
+8 2 4 1 7 5 3 6
+8 2 5 3 1 7 4 6
+8 3 1 6 2 5 7 4
+8 4 1 3 6 2 7 5
diff --git a/lcc/mips/irix/tst/8q.2bk b/lcc/mips/irix/tst/8q.2bk
new file mode 100755
index 0000000..fb28350
--- /dev/null
+++ b/lcc/mips/irix/tst/8q.2bk
@@ -0,0 +1,2 @@
+tst/8q.c:30: warning: missing return value
+tst/8q.c:39: warning: missing return value
diff --git a/lcc/mips/irix/tst/8q.sbk b/lcc/mips/irix/tst/8q.sbk
new file mode 100755
index 0000000..20e2fd1
--- /dev/null
+++ b/lcc/mips/irix/tst/8q.sbk
@@ -0,0 +1,169 @@
+.set reorder
+.globl main
+.text
+.text
+.align 2
+.ent main
+main:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2000000,-8
+.cprestore 16
+sw $30,20($sp)
+sw $31,24($sp)
+move $30,$0
+L.2:
+sll $24,$30,2
+la $15,1
+sw $15,down($24)
+sw $15,up($24)
+L.3:
+la $30,1($30)
+la $24,15
+blt $30,$24,L.2
+move $30,$0
+L.6:
+sll $24,$30,2
+la $15,1
+sw $15,rows($24)
+L.7:
+la $30,1($30)
+la $24,8
+blt $30,$24,L.6
+move $4,$0
+jal queens
+move $2,$0
+L.1:
+lw $25,16($sp)
+lw $30,20($sp)
+lw $31,24($sp)
+addu $sp,$sp,32
+j $31
+.end main
+.globl queens
+.text
+.align 2
+.ent queens
+queens:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2800000,-4
+sw $23,16($sp)
+.cprestore 20
+sw $30,24($sp)
+sw $31,28($sp)
+move $30,$4
+move $23,$0
+L.11:
+sll $15,$23,2
+lw $15,rows($15)
+beq $15,$0,L.15
+subu $15,$23,$30
+sll $15,$15,2
+lw $15,up+28($15)
+beq $15,$0,L.15
+addu $15,$23,$30
+sll $15,$15,2
+lw $15,down($15)
+beq $15,$0,L.15
+addu $15,$23,$30
+sll $15,$15,2
+sw $0,down($15)
+subu $15,$23,$30
+sll $15,$15,2
+sw $0,up+28($15)
+sll $15,$23,2
+sw $0,rows($15)
+sll $24,$30,2
+sw $23,x($24)
+la $24,7
+bne $30,$24,L.19
+jal print
+b L.20
+L.19:
+la $4,1($30)
+jal queens
+L.20:
+la $24,1
+addu $15,$23,$30
+sll $15,$15,2
+sw $24,down($15)
+subu $15,$23,$30
+sll $15,$15,2
+sw $24,up+28($15)
+sll $15,$23,2
+sw $24,rows($15)
+L.15:
+L.12:
+la $23,1($23)
+la $24,8
+blt $23,$24,L.11
+move $2,$0
+L.10:
+lw $23,16($sp)
+lw $25,20($sp)
+lw $30,24($sp)
+lw $31,28($sp)
+addu $sp,$sp,32
+j $31
+.end queens
+.globl print
+.text
+.align 2
+.ent print
+print:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2000000,-8
+.cprestore 16
+sw $30,20($sp)
+sw $31,24($sp)
+move $30,$0
+L.23:
+la $4,L.27
+sll $24,$30,2
+lw $24,x($24)
+la $5,49($24)
+jal printf
+L.24:
+la $30,1($30)
+la $24,8
+blt $30,$24,L.23
+la $4,L.28
+jal printf
+move $2,$0
+L.22:
+lw $25,16($sp)
+lw $30,20($sp)
+lw $31,24($sp)
+addu $sp,$sp,32
+j $31
+.end print
+.globl x
+.comm x,32
+.globl rows
+.comm rows,32
+.globl down
+.comm down,60
+.globl up
+.comm up,60
+.rdata
+.align 0
+L.28:
+.byte 10
+.byte 0
+.align 0
+L.27:
+.byte 37
+.byte 99
+.byte 32
+.byte 0
diff --git a/lcc/mips/irix/tst/array.1bk b/lcc/mips/irix/tst/array.1bk
new file mode 100755
index 0000000..e188568
--- /dev/null
+++ b/lcc/mips/irix/tst/array.1bk
@@ -0,0 +1,4 @@
+ 0 1 2 3 1000 1001 1002 1003 2000 2001 2002 2003
+ 0 1 2 3 1000 1001 1002 1003 2000 2001 2002 2003
+ 0 1 2 3 1000 1001 1002 1003 2000 2001 2002 2003
+ 0 1 2 3 1000 1001 1002 1003 2000 2001 2002 2003
diff --git a/lcc/mips/irix/tst/array.2bk b/lcc/mips/irix/tst/array.2bk
new file mode 100755
index 0000000..0a9b206
--- /dev/null
+++ b/lcc/mips/irix/tst/array.2bk
@@ -0,0 +1,2 @@
+tst/array.c:33: warning: missing return value
+tst/array.c:48: warning: missing return value
diff --git a/lcc/mips/irix/tst/array.sbk b/lcc/mips/irix/tst/array.sbk
new file mode 100755
index 0000000..575358e
--- /dev/null
+++ b/lcc/mips/irix/tst/array.sbk
@@ -0,0 +1,235 @@
+.set reorder
+.globl main
+.text
+.text
+.align 2
+.ent main
+main:
+.frame $sp,88,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-88
+.mask 0xc2c00000,-56
+sw $22,16($sp)
+sw $23,20($sp)
+.cprestore 24
+sw $30,28($sp)
+sw $31,32($sp)
+move $23,$0
+L.2:
+move $30,$0
+L.6:
+sll $24,$30,2
+sll $15,$23,4
+la $15,x($15)
+addu $24,$24,$15
+la $15,1000
+mul $15,$15,$23
+addu $15,$15,$30
+sw $15,($24)
+L.7:
+la $30,1($30)
+la $24,4
+blt $30,$24,L.6
+sll $24,$23,2
+sll $15,$23,4
+la $15,x($15)
+sw $15,y($24)
+L.3:
+la $23,1($23)
+la $24,3
+blt $23,$24,L.2
+jal f
+move $23,$0
+L.10:
+sll $24,$23,4
+la $15,-48+88($sp)
+addu $24,$24,$15
+move $22,$24
+sll $15,$23,2
+sw $24,y($15)
+move $30,$0
+L.14:
+sll $24,$30,2
+addu $15,$24,$22
+sll $14,$23,4
+la $14,x($14)
+addu $24,$24,$14
+lw $24,($24)
+sw $24,($15)
+L.15:
+la $30,1($30)
+la $24,4
+blt $30,$24,L.14
+L.11:
+la $23,1($23)
+la $24,3
+blt $23,$24,L.10
+la $4,-48+88($sp)
+la $5,y
+jal g
+move $2,$0
+L.1:
+lw $22,16($sp)
+lw $23,20($sp)
+lw $25,24($sp)
+lw $30,28($sp)
+lw $31,32($sp)
+addu $sp,$sp,88
+j $31
+.end main
+.globl f
+.text
+.align 2
+.ent f
+f:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2800000,-4
+sw $23,16($sp)
+.cprestore 20
+sw $30,24($sp)
+sw $31,28($sp)
+move $23,$0
+L.19:
+move $30,$0
+L.23:
+la $4,L.27
+sll $24,$30,2
+sll $15,$23,4
+la $15,x($15)
+addu $24,$24,$15
+lw $5,($24)
+jal printf
+L.24:
+la $30,1($30)
+la $24,4
+blt $30,$24,L.23
+L.20:
+la $23,1($23)
+la $24,3
+blt $23,$24,L.19
+la $4,L.28
+jal printf
+move $23,$0
+L.29:
+move $30,$0
+L.33:
+la $4,L.27
+sll $24,$30,2
+sll $15,$23,2
+lw $15,y($15)
+addu $24,$24,$15
+lw $5,($24)
+jal printf
+L.34:
+la $30,1($30)
+la $24,4
+blt $30,$24,L.33
+L.30:
+la $23,1($23)
+la $24,3
+blt $23,$24,L.29
+la $4,L.28
+jal printf
+move $2,$0
+L.18:
+lw $23,16($sp)
+lw $25,20($sp)
+lw $30,24($sp)
+lw $31,28($sp)
+addu $sp,$sp,32
+j $31
+.end f
+.globl g
+.text
+.align 2
+.ent g
+g:
+.frame $sp,40,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-40
+.mask 0xc2e00000,-4
+sw $21,16($sp)
+sw $22,20($sp)
+sw $23,24($sp)
+.cprestore 28
+sw $30,32($sp)
+sw $31,36($sp)
+move $30,$4
+move $23,$5
+move $21,$0
+L.38:
+move $22,$0
+L.42:
+la $4,L.27
+sll $24,$22,2
+sll $15,$21,4
+addu $15,$15,$30
+addu $24,$24,$15
+lw $5,($24)
+jal printf
+L.43:
+la $22,1($22)
+la $24,4
+blt $22,$24,L.42
+L.39:
+la $21,1($21)
+la $24,3
+blt $21,$24,L.38
+la $4,L.28
+jal printf
+move $21,$0
+L.46:
+move $22,$0
+L.50:
+la $4,L.27
+sll $24,$22,2
+sll $15,$21,2
+addu $15,$15,$23
+lw $15,($15)
+addu $24,$24,$15
+lw $5,($24)
+jal printf
+L.51:
+la $22,1($22)
+la $24,4
+blt $22,$24,L.50
+L.47:
+la $21,1($21)
+la $24,3
+blt $21,$24,L.46
+la $4,L.28
+jal printf
+move $2,$0
+L.37:
+lw $21,16($sp)
+lw $22,20($sp)
+lw $23,24($sp)
+lw $25,28($sp)
+lw $30,32($sp)
+lw $31,36($sp)
+addu $sp,$sp,40
+j $31
+.end g
+.globl y
+.comm y,12
+.globl x
+.comm x,48
+.rdata
+.align 0
+L.28:
+.byte 10
+.byte 0
+.align 0
+L.27:
+.byte 32
+.byte 37
+.byte 100
+.byte 0
diff --git a/lcc/mips/irix/tst/cf.1bk b/lcc/mips/irix/tst/cf.1bk
new file mode 100755
index 0000000..24e21ba
--- /dev/null
+++ b/lcc/mips/irix/tst/cf.1bk
@@ -0,0 +1,51 @@
+char freq
+011 8.1
+012 6.1
+040 11.9
+! 0.2
+" 1.5
+% 0.6
+& 0.4
+' 0.4
+( 2.9
+) 2.9
+* 0.8
++ 1.3
+, 1.3
+- 0.4
+. 0.6
+/ 1.0
+0 2.5
+1 1.9
+2 0.6
+3 0.2
+7 0.4
+8 0.2
+; 3.8
+< 0.8
+= 2.7
+> 0.2
+[ 1.5
+\ 0.8
+] 1.5
+a 3.1
+c 4.4
+e 2.3
+f 6.0
+g 1.3
+h 1.0
+i 5.0
+l 1.0
+m 0.2
+n 3.3
+o 2.1
+p 1.0
+q 0.4
+r 4.2
+s 0.6
+t 3.8
+u 1.2
+v 0.6
+w 0.2
+{ 0.6
+} 0.6
diff --git a/lcc/mips/irix/tst/cf.2bk b/lcc/mips/irix/tst/cf.2bk
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/mips/irix/tst/cf.2bk
diff --git a/lcc/mips/irix/tst/cf.sbk b/lcc/mips/irix/tst/cf.sbk
new file mode 100755
index 0000000..62189cf
--- /dev/null
+++ b/lcc/mips/irix/tst/cf.sbk
@@ -0,0 +1,153 @@
+.set reorder
+.globl main
+.text
+.text
+.align 2
+.ent main
+main:
+.frame $sp,48,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-48
+.fmask 0xc0000000,-32
+.mask 0xc2c00000,-8
+s.d $f30,16($sp)
+sw $22,24($sp)
+sw $23,28($sp)
+.cprestore 32
+sw $30,36($sp)
+sw $31,40($sp)
+sw $4,48($sp)
+sw $5,52($sp)
+lw $24,0+48($sp)
+la $15,1
+bgt $24,$15,L.2
+l.s $f30,L.4
+b L.3
+L.2:
+lw $24,4+48($sp)
+lw $4,4($24)
+jal atof
+l.s $f16,L.5
+div.s $f30,$f0,$f16
+L.3:
+move $30,$0
+L.6:
+move $24,$30
+la $30,1($24)
+sll $24,$24,2
+l.s $f18,L.4
+s.s $f18,f($24)
+L.7:
+la $24,127
+ble $30,$24,L.6
+move $23,$0
+b L.11
+L.10:
+sll $24,$22,2
+la $24,f($24)
+l.s $f18,($24)
+l.s $f16,L.13
+add.s $f18,$f18,$f16
+s.s $f18,($24)
+la $23,1($23)
+L.11:
+jal getchar
+move $22,$2
+la $15,-1
+bne $2,$15,L.10
+la $4,L.14
+jal printf
+move $30,$0
+L.15:
+sll $24,$30,2
+l.s $f18,f($24)
+l.s $f16,L.4
+c.eq.s $f18,$f16; bc1t L.19
+mtc1 $23,$f16; cvt.s.w $f16,$f16
+div.s $f18,$f18,$f16
+c.lt.s $f18,$f30; bc1t L.19
+la $24,32
+bgt $30,$24,L.21
+la $4,L.23
+move $5,$30
+jal printf
+b L.22
+L.21:
+la $4,L.24
+move $5,$30
+jal printf
+L.22:
+la $4,L.25
+l.s $f18,L.5
+sll $24,$30,2
+l.s $f16,f($24)
+mul.s $f18,$f18,$f16
+mtc1 $23,$f16; cvt.s.w $f16,$f16
+div.s $f18,$f18,$f16
+cvt.d.s $f18,$f18
+mfc1.d $6,$f18
+jal printf
+L.19:
+L.16:
+la $30,1($30)
+la $24,127
+ble $30,$24,L.15
+move $2,$0
+L.1:
+l.d $f30,16($sp)
+lw $22,24($sp)
+lw $23,28($sp)
+lw $25,32($sp)
+lw $30,36($sp)
+lw $31,40($sp)
+addu $sp,$sp,48
+j $31
+.end main
+.globl f
+.comm f,512
+.rdata
+.align 0
+L.25:
+.byte 9
+.byte 37
+.byte 46
+.byte 49
+.byte 102
+.byte 10
+.byte 0
+.align 0
+L.24:
+.byte 37
+.byte 99
+.byte 0
+.align 0
+L.23:
+.byte 37
+.byte 48
+.byte 51
+.byte 111
+.byte 0
+.align 0
+L.14:
+.byte 99
+.byte 104
+.byte 97
+.byte 114
+.byte 9
+.byte 102
+.byte 114
+.byte 101
+.byte 113
+.byte 10
+.byte 0
+.align 2
+L.13:
+.word 0x3f800000
+.align 2
+L.5:
+.word 0x42c80000
+.align 2
+L.4:
+.word 0x0
diff --git a/lcc/mips/irix/tst/cq.1bk b/lcc/mips/irix/tst/cq.1bk
new file mode 100755
index 0000000..b7b7643
--- /dev/null
+++ b/lcc/mips/irix/tst/cq.1bk
@@ -0,0 +1,48 @@
+Section s22 returned 0.
+Decimal and octal/hex constants sometimes give
+ different results when assigned to longs.
+Decimal and octal/hex constants sometimes give
+ different results when assigned to longs.
+Section s241 returned 0.
+Section s243 returned 0.
+Section s244 returned 0.
+Section s25 returned 0.
+ 8 bits in chars.
+ 32 bits in ints.
+ 16 bits in shorts.
+ 32 bits in longs.
+ 32 bits in unsigneds.
+ 32 bits in floats.
+ 64 bits in doubles.
+1.192093e-07 is the least number that can be added to 1. (float).
+2.220446e-16 is the least number that can be added to 1. (double).
+Section s26 returned 0.
+Section s4 returned 0.
+Section s61 returned 0.
+Section s626 returned 0.
+Section s71 returned 0.
+Section s72 returned 0.
+Section s757 returned 0.
+Section s7813 returned 0.
+Section s714 returned 0.
+Section s715 returned 0.
+Register count for char is unreliable.
+Register count for pointer is unreliable.
+Register count for int is unreliable.
+Section s81 returned 0.
+Section s84 returned 0.
+char alignment: 1
+short alignment: 2
+int alignment: 4
+long alignment: 4
+unsigned alignment: 4
+float alignment: 4
+double alignment: 8
+Sign extension in fields
+Be especially careful with 1-bit fields!
+Section s85 returned 0.
+Section s86 returned 0.
+Section s88 returned 0.
+Section s9 returned 0.
+
+No errors detected.
diff --git a/lcc/mips/irix/tst/cq.2bk b/lcc/mips/irix/tst/cq.2bk
new file mode 100755
index 0000000..295f5b6
--- /dev/null
+++ b/lcc/mips/irix/tst/cq.2bk
@@ -0,0 +1,25 @@
+tst/cq.c:394: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:394: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:394: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:395: warning: overflow in constant `4294967296'
+tst/cq.c:395: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:395: warning: overflow in constant `040000000000'
+tst/cq.c:395: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:395: warning: overflow in constant `0x100000000'
+tst/cq.c:395: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:396: warning: overflow in constant `68719476735'
+tst/cq.c:396: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:396: warning: overflow in constant `0777777777777'
+tst/cq.c:396: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:396: warning: overflow in constant `0xfffffffff'
+tst/cq.c:396: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:397: warning: overflow in constant `68719476736'
+tst/cq.c:397: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:397: warning: overflow in constant `01000000000000'
+tst/cq.c:397: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:397: warning: overflow in constant `0x1000000000'
+tst/cq.c:397: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:533: warning: missing return value
+tst/cq.c:1169: warning: missing return value
+tst/cq.c:5294: warning: unreachable code
+tst/cq.c:5303: warning: missing return value
diff --git a/lcc/mips/irix/tst/cq.sbk b/lcc/mips/irix/tst/cq.sbk
new file mode 100755
index 0000000..41cc964
--- /dev/null
+++ b/lcc/mips/irix/tst/cq.sbk
@@ -0,0 +1,13620 @@
+.set reorder
+.data
+.align 2
+L.2:
+.word s22
+.word s241
+.word s243
+.word s244
+.word s25
+.word s26
+.word s4
+.word s61
+.word s626
+.word s71
+.word s72
+.word s757
+.word s7813
+.word s714
+.word s715
+.word s81
+.word s84
+.word s85
+.word s86
+.word s88
+.word s9
+.lcomm L.3,68
+.lcomm L.4,4
+.globl main
+.text
+.text
+.align 2
+.ent main
+main:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2000000,-8
+.cprestore 16
+sw $30,20($sp)
+sw $31,24($sp)
+sw $4,32($sp)
+sw $5,36($sp)
+la $24,1
+sw $24,L.3+36
+la $24,1
+sw $24,L.3+40
+la $24,1
+sw $24,L.3+44
+la $24,1
+sw $24,L.3+48
+la $24,L.3
+sw $24,L.4
+move $30,$0
+b L.12
+L.9:
+lw $4,L.4
+sll $24,$30,2
+lw $25,L.2($24)
+jal $25
+sw $2,L.3+52
+lw $24,L.3+56
+lw $15,L.3+52
+addu $24,$24,$15
+sw $24,L.3+56
+lw $24,L.3+36
+beq $24,$0,L.17
+la $4,L.20
+la $5,L.3+60
+lw $6,L.3+52
+jal printf
+L.17:
+L.10:
+la $30,1($30)
+L.12:
+move $24,$30
+la $15,21
+bltu $24,$15,L.9
+lw $24,L.3+56
+bne $24,$0,L.23
+la $4,L.26
+jal printf
+b L.24
+L.23:
+la $4,L.27
+jal printf
+L.24:
+move $2,$0
+L.1:
+lw $25,16($sp)
+lw $30,20($sp)
+lw $31,24($sp)
+addu $sp,$sp,32
+j $31
+.end main
+.data
+.align 0
+L.29:
+.byte 115
+.byte 50
+.byte 50
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.sdata
+.align 0
+L.30:
+.byte 115
+.byte 50
+.byte 50
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s22
+.text
+.text
+.align 2
+.ent s22
+s22:
+.frame $sp,56,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-56
+.mask 0xc2e00000,-20
+sw $21,16($sp)
+sw $22,20($sp)
+sw $23,24($sp)
+.cprestore 28
+sw $30,32($sp)
+sw $31,36($sp)
+sw $4,56($sp)
+move $22,$0
+la $30,L.30
+lw $24,0+56($sp)
+la $23,60($24)
+L.31:
+L.32:
+move $24,$23
+la $23,1($24)
+move $15,$30
+la $30,1($15)
+lb $15,($15)
+sb $15,($24)
+sll $24,$15,8*(4-1); sra $24,$24,8*(4-1)
+bne $24,$0,L.31
+la $21,1
+la $24,2
+sw $24,-8+56($sp)
+la $24,3
+sw $24,-12+56($sp)
+la $24,4
+sw $24,-4+56($sp)
+lw $24,-8+56($sp)
+addu $24,$21,$24
+lw $15,-12+56($sp)
+addu $24,$24,$15
+lw $15,-4+56($sp)
+addu $24,$24,$15
+la $15,10
+beq $24,$15,L.34
+la $22,1($22)
+lw $24,0+56($sp)
+lw $24,44($24)
+beq $24,$0,L.36
+la $4,L.29
+la $5,1
+jal printf
+L.36:
+L.34:
+la $24,2
+sw $24,-16+56($sp)
+lw $24,-16+56($sp)
+bne $24,$21,L.38
+la $22,4($22)
+lw $24,0+56($sp)
+lw $24,44($24)
+beq $24,$0,L.40
+la $4,L.29
+la $5,4
+jal printf
+L.40:
+L.38:
+move $2,$22
+L.28:
+lw $21,16($sp)
+lw $22,20($sp)
+lw $23,24($sp)
+lw $25,28($sp)
+lw $30,32($sp)
+lw $31,36($sp)
+addu $sp,$sp,56
+j $31
+.end s22
+.data
+.align 0
+L.43:
+.byte 115
+.byte 50
+.byte 52
+.byte 49
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.sdata
+.align 0
+L.44:
+.byte 115
+.byte 50
+.byte 52
+.byte 49
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.data
+.align 2
+L.45:
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x6
+.word 0x0
+.word 0x8
+.word 0x0
+.word 0xc
+.word 0x0
+.word 0x10
+.word 0x0
+.word 0x12
+.word 0x0
+.word 0x14
+.word 0x0
+.word 0x18
+.word 0x0
+.word 0x1c
+.word 0x0
+.word 0x1e
+.word 0x0
+.word 0x20
+.word 0x0
+.word 0x24
+.globl s241
+.text
+.text
+.align 2
+.ent s241
+s241:
+.frame $sp,520,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-520
+.mask 0xc2f00000,-480
+sw $20,16($sp)
+sw $21,20($sp)
+sw $22,24($sp)
+sw $23,28($sp)
+.cprestore 32
+sw $30,36($sp)
+sw $31,40($sp)
+move $30,$4
+move $20,$0
+sw $0,-472+520($sp)
+la $22,L.44
+la $21,60($30)
+L.46:
+L.47:
+move $24,$21
+la $21,1($24)
+move $15,$22
+la $22,1($15)
+lb $15,($15)
+sb $15,($24)
+sll $24,$15,8*(4-1); sra $24,$24,8*(4-1)
+bne $24,$0,L.46
+b L.49
+la $20,1($20)
+lw $24,44($30)
+beq $24,$0,L.51
+la $4,L.43
+la $5,1
+jal printf
+L.51:
+L.49:
+b L.53
+la $20,2($20)
+lw $24,44($30)
+beq $24,$0,L.55
+la $4,L.43
+la $5,2
+jal printf
+L.55:
+L.53:
+b L.57
+la $20,4($20)
+lw $24,44($30)
+beq $24,$0,L.59
+la $4,L.43
+la $5,4
+jal printf
+L.59:
+L.57:
+b L.61
+la $20,8($20)
+lw $24,44($30)
+beq $24,$0,L.63
+la $4,L.43
+la $5,8
+jal printf
+L.63:
+L.61:
+move $23,$0
+L.65:
+sll $24,$23,2
+sw $23,L.45($24)
+L.66:
+la $23,1($23)
+la $24,17
+blt $23,$24,L.65
+la $23,18
+L.69:
+sll $24,$23,2
+la $24,L.45($24)
+sw $24,-476+520($sp)
+lw $4,($24)
+jal pow2
+lw $15,-476+520($sp)
+sw $2,($15)
+sll $24,$23,2
+lw $15,L.45($24)
+subu $15,$15,1
+sw $15,L.45-4($24)
+la $23,2($23)
+L.70:
+la $24,39
+blt $23,$24,L.69
+sw $0,-156+520($sp)
+sw $0,-312+520($sp)
+sw $0,-468+520($sp)
+la $24,1
+sw $24,-152+520($sp)
+la $24,1
+sw $24,-308+520($sp)
+la $24,1
+sw $24,-464+520($sp)
+la $24,2
+sw $24,-148+520($sp)
+la $24,2
+sw $24,-304+520($sp)
+la $24,2
+sw $24,-460+520($sp)
+la $24,3
+sw $24,-144+520($sp)
+la $24,3
+sw $24,-300+520($sp)
+la $24,3
+sw $24,-456+520($sp)
+la $24,4
+sw $24,-140+520($sp)
+la $24,4
+sw $24,-296+520($sp)
+la $24,4
+sw $24,-452+520($sp)
+la $24,5
+sw $24,-136+520($sp)
+la $24,5
+sw $24,-292+520($sp)
+la $24,5
+sw $24,-448+520($sp)
+la $24,6
+sw $24,-132+520($sp)
+la $24,6
+sw $24,-288+520($sp)
+la $24,6
+sw $24,-444+520($sp)
+la $24,7
+sw $24,-128+520($sp)
+la $24,7
+sw $24,-284+520($sp)
+la $24,7
+sw $24,-440+520($sp)
+la $24,8
+sw $24,-124+520($sp)
+la $24,8
+sw $24,-280+520($sp)
+la $24,8
+sw $24,-436+520($sp)
+la $24,9
+sw $24,-120+520($sp)
+la $24,9
+sw $24,-276+520($sp)
+la $24,9
+sw $24,-432+520($sp)
+la $24,10
+sw $24,-116+520($sp)
+la $24,10
+sw $24,-272+520($sp)
+la $24,10
+sw $24,-428+520($sp)
+la $24,11
+sw $24,-112+520($sp)
+la $24,11
+sw $24,-268+520($sp)
+la $24,11
+sw $24,-424+520($sp)
+la $24,12
+sw $24,-108+520($sp)
+la $24,12
+sw $24,-264+520($sp)
+la $24,12
+sw $24,-420+520($sp)
+la $24,13
+sw $24,-104+520($sp)
+la $24,13
+sw $24,-260+520($sp)
+la $24,13
+sw $24,-416+520($sp)
+la $24,14
+sw $24,-100+520($sp)
+la $24,14
+sw $24,-256+520($sp)
+la $24,14
+sw $24,-412+520($sp)
+la $24,15
+sw $24,-96+520($sp)
+la $24,15
+sw $24,-252+520($sp)
+la $24,15
+sw $24,-408+520($sp)
+la $24,16
+sw $24,-92+520($sp)
+la $24,16
+sw $24,-248+520($sp)
+la $24,16
+sw $24,-404+520($sp)
+la $24,63
+sw $24,-88+520($sp)
+la $24,63
+sw $24,-244+520($sp)
+la $24,63
+sw $24,-400+520($sp)
+la $24,64
+sw $24,-84+520($sp)
+la $24,64
+sw $24,-240+520($sp)
+la $24,64
+sw $24,-396+520($sp)
+la $24,255
+sw $24,-80+520($sp)
+la $24,255
+sw $24,-236+520($sp)
+la $24,255
+sw $24,-392+520($sp)
+la $24,256
+sw $24,-76+520($sp)
+la $24,256
+sw $24,-232+520($sp)
+la $24,256
+sw $24,-388+520($sp)
+la $24,4095
+sw $24,-72+520($sp)
+la $24,4095
+sw $24,-228+520($sp)
+la $24,4095
+sw $24,-384+520($sp)
+la $24,4096
+sw $24,-68+520($sp)
+la $24,4096
+sw $24,-224+520($sp)
+la $24,4096
+sw $24,-380+520($sp)
+la $24,65535
+sw $24,-64+520($sp)
+la $24,65535
+sw $24,-220+520($sp)
+la $24,65535
+sw $24,-376+520($sp)
+la $24,65536
+sw $24,-60+520($sp)
+la $24,65536
+sw $24,-216+520($sp)
+la $24,65536
+sw $24,-372+520($sp)
+la $24,262143
+sw $24,-56+520($sp)
+la $24,262143
+sw $24,-212+520($sp)
+la $24,262143
+sw $24,-368+520($sp)
+la $24,262144
+sw $24,-52+520($sp)
+la $24,262144
+sw $24,-208+520($sp)
+la $24,262144
+sw $24,-364+520($sp)
+la $24,1048575
+sw $24,-48+520($sp)
+la $24,1048575
+sw $24,-204+520($sp)
+la $24,1048575
+sw $24,-360+520($sp)
+la $24,1048576
+sw $24,-44+520($sp)
+la $24,1048576
+sw $24,-200+520($sp)
+la $24,1048576
+sw $24,-356+520($sp)
+la $24,16777215
+sw $24,-40+520($sp)
+la $24,16777215
+sw $24,-196+520($sp)
+la $24,16777215
+sw $24,-352+520($sp)
+la $24,16777216
+sw $24,-36+520($sp)
+la $24,16777216
+sw $24,-192+520($sp)
+la $24,16777216
+sw $24,-348+520($sp)
+la $24,268435455
+sw $24,-32+520($sp)
+la $24,268435455
+sw $24,-188+520($sp)
+la $24,268435455
+sw $24,-344+520($sp)
+la $24,268435456
+sw $24,-28+520($sp)
+la $24,268435456
+sw $24,-184+520($sp)
+la $24,268435456
+sw $24,-340+520($sp)
+la $24,1073741823
+sw $24,-24+520($sp)
+la $24,1073741823
+sw $24,-180+520($sp)
+la $24,1073741823
+sw $24,-336+520($sp)
+la $24,1073741824
+sw $24,-20+520($sp)
+la $24,1073741824
+sw $24,-176+520($sp)
+la $24,1073741824
+sw $24,-332+520($sp)
+la $24,0xffffffff
+sw $24,-16+520($sp)
+la $24,0xffffffff
+sw $24,-172+520($sp)
+la $24,0xffffffff
+sw $24,-328+520($sp)
+la $24,0xffffffff
+sw $24,-12+520($sp)
+la $24,0xffffffff
+sw $24,-168+520($sp)
+la $24,0xffffffff
+sw $24,-324+520($sp)
+la $24,0xffffffff
+sw $24,-8+520($sp)
+la $24,0xffffffff
+sw $24,-164+520($sp)
+la $24,0xffffffff
+sw $24,-320+520($sp)
+la $24,0xffffffff
+sw $24,-4+520($sp)
+la $24,0xffffffff
+sw $24,-160+520($sp)
+la $24,0xffffffff
+sw $24,-316+520($sp)
+move $23,$0
+L.188:
+sll $24,$23,2
+la $15,-156+520($sp)
+addu $15,$24,$15
+lw $15,($15)
+lw $14,L.45($24)
+bne $14,$15,L.195
+la $14,-312+520($sp)
+addu $14,$24,$14
+lw $14,($14)
+bne $15,$14,L.195
+la $15,-468+520($sp)
+addu $24,$24,$15
+lw $24,($24)
+beq $14,$24,L.192
+L.195:
+lw $24,40($30)
+beq $24,$0,L.196
+la $4,L.198
+jal printf
+la $4,L.199
+jal printf
+L.196:
+L.192:
+L.189:
+la $23,1($23)
+la $24,39
+blt $23,$24,L.188
+lw $24,-472+520($sp)
+beq $24,$0,L.200
+la $20,16
+L.200:
+move $2,$20
+L.42:
+lw $20,16($sp)
+lw $21,20($sp)
+lw $22,24($sp)
+lw $23,28($sp)
+lw $25,32($sp)
+lw $30,36($sp)
+lw $31,40($sp)
+addu $sp,$sp,520
+j $31
+.end s241
+.globl pow2
+.text
+.align 2
+.ent pow2
+pow2:
+.frame $sp,8,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-8
+.mask 0x40000000,-8
+sw $30,0($sp)
+la $30,1
+b L.204
+L.203:
+sll $30,$30,1
+L.204:
+move $24,$4
+subu $4,$24,1
+bne $24,$0,L.203
+move $2,$30
+L.202:
+lw $30,0($sp)
+addu $sp,$sp,8
+j $31
+.end pow2
+.data
+.align 0
+L.207:
+.byte 115
+.byte 50
+.byte 52
+.byte 51
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.sdata
+.align 0
+L.208:
+.byte 115
+.byte 50
+.byte 52
+.byte 51
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s243
+.text
+.text
+.align 2
+.ent s243
+s243:
+.frame $sp,296,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-296
+.mask 0xc2c00000,-264
+sw $22,16($sp)
+sw $23,20($sp)
+.cprestore 24
+sw $30,28($sp)
+sw $31,32($sp)
+sw $4,296($sp)
+move $22,$0
+la $30,L.208
+lw $24,0+296($sp)
+la $23,60($24)
+L.209:
+L.210:
+move $24,$23
+la $23,1($24)
+move $15,$30
+la $30,1($15)
+lb $15,($15)
+sb $15,($24)
+sll $24,$15,8*(4-1); sra $24,$24,8*(4-1)
+bne $24,$0,L.209
+la $4,-256+296($sp)
+jal zerofill
+la $24,1
+sb $24,-159+296($sp)
+la $24,1
+sb $24,-191+296($sp)
+la $24,1
+sb $24,-130+296($sp)
+la $24,1
+sb $24,-208+296($sp)
+la $24,1
+sb $24,-158+296($sp)
+la $24,1
+sb $24,-190+296($sp)
+la $24,1
+sb $24,-223+296($sp)
+la $24,1
+sb $24,-207+296($sp)
+la $24,1
+sb $24,-157+296($sp)
+la $24,1
+sb $24,-189+296($sp)
+la $24,1
+sb $24,-222+296($sp)
+la $24,1
+sb $24,-206+296($sp)
+la $24,1
+sb $24,-156+296($sp)
+la $24,1
+sb $24,-188+296($sp)
+la $24,1
+sb $24,-221+296($sp)
+la $24,1
+sb $24,-205+296($sp)
+la $24,1
+sb $24,-155+296($sp)
+la $24,1
+sb $24,-187+296($sp)
+la $24,1
+sb $24,-219+296($sp)
+la $24,1
+sb $24,-204+296($sp)
+la $24,1
+sb $24,-154+296($sp)
+la $24,1
+sb $24,-186+296($sp)
+la $24,1
+sb $24,-218+296($sp)
+la $24,1
+sb $24,-203+296($sp)
+la $24,1
+sb $24,-153+296($sp)
+la $24,1
+sb $24,-185+296($sp)
+la $24,1
+sb $24,-216+296($sp)
+la $24,1
+sb $24,-202+296($sp)
+la $24,1
+sb $24,-152+296($sp)
+la $24,1
+sb $24,-184+296($sp)
+la $24,1
+sb $24,-215+296($sp)
+la $24,1
+sb $24,-201+296($sp)
+la $24,1
+sb $24,-151+296($sp)
+la $24,1
+sb $24,-183+296($sp)
+la $24,1
+sb $24,-161+296($sp)
+la $24,1
+sb $24,-200+296($sp)
+la $24,1
+sb $24,-150+296($sp)
+la $24,1
+sb $24,-182+296($sp)
+la $24,1
+sb $24,-195+296($sp)
+la $24,1
+sb $24,-199+296($sp)
+la $24,1
+sb $24,-149+296($sp)
+la $24,1
+sb $24,-181+296($sp)
+la $24,1
+sb $24,-211+296($sp)
+la $24,1
+sb $24,-148+296($sp)
+la $24,1
+sb $24,-180+296($sp)
+la $24,1
+sb $24,-162+296($sp)
+la $24,1
+sb $24,-147+296($sp)
+la $24,1
+sb $24,-179+296($sp)
+la $24,1
+sb $24,-132+296($sp)
+la $24,1
+sb $24,-246+296($sp)
+la $24,1
+sb $24,-146+296($sp)
+la $24,1
+sb $24,-178+296($sp)
+la $24,1
+sb $24,-247+296($sp)
+la $24,1
+sb $24,-145+296($sp)
+la $24,1
+sb $24,-177+296($sp)
+la $24,1
+sb $24,-133+296($sp)
+la $24,1
+sb $24,-248+296($sp)
+la $24,1
+sb $24,-144+296($sp)
+la $24,1
+sb $24,-176+296($sp)
+la $24,1
+sb $24,-131+296($sp)
+la $24,1
+sb $24,-243+296($sp)
+la $24,1
+sb $24,-143+296($sp)
+la $24,1
+sb $24,-175+296($sp)
+la $24,1
+sb $24,-165+296($sp)
+la $24,1
+sb $24,-244+296($sp)
+la $24,1
+sb $24,-142+296($sp)
+la $24,1
+sb $24,-174+296($sp)
+la $24,1
+sb $24,-163+296($sp)
+la $24,1
+sb $24,-141+296($sp)
+la $24,1
+sb $24,-173+296($sp)
+la $24,1
+sb $24,-213+296($sp)
+la $24,1
+sb $24,-164+296($sp)
+la $24,1
+sb $24,-140+296($sp)
+la $24,1
+sb $24,-172+296($sp)
+la $24,1
+sb $24,-197+296($sp)
+la $24,1
+sb $24,-217+296($sp)
+la $24,1
+sb $24,-139+296($sp)
+la $24,1
+sb $24,-171+296($sp)
+la $24,1
+sb $24,-214+296($sp)
+la $24,1
+sb $24,-138+296($sp)
+la $24,1
+sb $24,-170+296($sp)
+la $24,1
+sb $24,-198+296($sp)
+la $24,1
+sb $24,-256+296($sp)
+sb $24,-137+296($sp)
+la $24,1
+sb $24,-169+296($sp)
+la $24,1
+sb $24,-196+296($sp)
+la $24,1
+sb $24,-224+296($sp)
+la $24,1
+sb $24,-136+296($sp)
+la $24,1
+sb $24,-168+296($sp)
+la $24,1
+sb $24,-194+296($sp)
+la $24,1
+sb $24,-135+296($sp)
+la $24,1
+sb $24,-167+296($sp)
+la $24,1
+sb $24,-212+296($sp)
+la $24,1
+sb $24,-134+296($sp)
+la $24,1
+sb $24,-166+296($sp)
+la $24,1
+sb $24,-210+296($sp)
+la $24,1
+sb $24,-193+296($sp)
+la $24,1
+sb $24,-209+296($sp)
+la $4,-256+296($sp)
+jal sumof
+la $15,98
+beq $2,$15,L.309
+la $22,1($22)
+lw $24,0+296($sp)
+lw $24,44($24)
+beq $24,$0,L.311
+la $4,L.207
+la $5,1
+jal printf
+L.311:
+L.309:
+b L.313
+la $22,8($22)
+lw $24,0+296($sp)
+lw $24,44($24)
+beq $24,$0,L.315
+la $4,L.207
+la $5,8
+jal printf
+L.315:
+L.313:
+move $2,$22
+L.206:
+lw $22,16($sp)
+lw $23,20($sp)
+lw $25,24($sp)
+lw $30,28($sp)
+lw $31,32($sp)
+addu $sp,$sp,296
+j $31
+.end s243
+.globl zerofill
+.text
+.align 2
+.ent zerofill
+zerofill:
+.frame $sp,8,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-8
+.mask 0x40000000,-8
+sw $30,0($sp)
+move $30,$0
+L.318:
+move $24,$4
+la $4,1($24)
+sb $0,($24)
+L.319:
+la $30,1($30)
+la $24,256
+blt $30,$24,L.318
+move $2,$0
+L.317:
+lw $30,0($sp)
+addu $sp,$sp,8
+j $31
+.end zerofill
+.globl sumof
+.text
+.align 2
+.ent sumof
+sumof:
+.frame $sp,16,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-16
+.mask 0x40c00000,-8
+sw $22,0($sp)
+sw $23,4($sp)
+sw $30,8($sp)
+move $22,$4
+move $30,$0
+move $23,$0
+L.323:
+move $24,$22
+la $22,1($24)
+lb $24,($24)
+addu $30,$30,$24
+L.324:
+la $23,1($23)
+la $24,256
+blt $23,$24,L.323
+move $2,$30
+L.322:
+lw $22,0($sp)
+lw $23,4($sp)
+lw $30,8($sp)
+addu $sp,$sp,16
+j $31
+.end sumof
+.data
+.align 0
+L.328:
+.byte 115
+.byte 50
+.byte 52
+.byte 52
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.sdata
+.align 0
+L.329:
+.byte 115
+.byte 50
+.byte 52
+.byte 52
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s244
+.text
+.text
+.align 2
+.ent s244
+s244:
+.frame $sp,112,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-112
+.mask 0xc2f00000,-72
+sw $20,16($sp)
+sw $21,20($sp)
+sw $22,24($sp)
+sw $23,28($sp)
+.cprestore 32
+sw $30,36($sp)
+sw $31,40($sp)
+sw $4,112($sp)
+la $23,L.329
+lw $24,0+112($sp)
+la $22,60($24)
+L.330:
+L.331:
+move $24,$22
+la $22,1($24)
+move $15,$23
+la $23,1($15)
+lb $15,($15)
+sb $15,($24)
+sll $24,$15,8*(4-1); sra $24,$24,8*(4-1)
+bne $24,$0,L.330
+move $20,$0
+move $21,$0
+l.d $f18,L.333
+s.d $f18,-64+112($sp)
+s.d $f18,-56+112($sp)
+l.d $f18,L.333
+s.d $f18,-48+112($sp)
+l.d $f18,L.333
+s.d $f18,-40+112($sp)
+l.d $f18,L.333
+s.d $f18,-32+112($sp)
+l.d $f18,L.333
+s.d $f18,-24+112($sp)
+l.d $f18,L.333
+s.d $f18,-16+112($sp)
+l.d $f18,L.333
+s.d $f18,-8+112($sp)
+move $21,$0
+move $30,$0
+L.341:
+sll $24,$30,3
+la $15,-64+112($sp)
+addu $15,$24,$15
+l.d $f18,($15)
+la $15,-56+112($sp)
+addu $24,$24,$15
+l.d $f16,($24)
+c.eq.d $f18,$f16; bc1t L.345
+la $21,1
+L.345:
+L.342:
+la $30,1($30)
+la $24,7
+blt $30,$24,L.341
+beq $21,$0,L.348
+lw $24,0+112($sp)
+lw $24,44($24)
+beq $24,$0,L.350
+la $4,L.328
+la $5,1
+jal printf
+L.350:
+la $20,1($20)
+L.348:
+b L.352
+lw $24,0+112($sp)
+lw $24,44($24)
+beq $24,$0,L.354
+la $4,L.328
+la $5,2
+jal printf
+L.354:
+la $20,2($20)
+L.352:
+move $2,$20
+L.327:
+lw $20,16($sp)
+lw $21,20($sp)
+lw $22,24($sp)
+lw $23,28($sp)
+lw $25,32($sp)
+lw $30,36($sp)
+lw $31,40($sp)
+addu $sp,$sp,112
+j $31
+.end s244
+.data
+.align 0
+L.357:
+.byte 115
+.byte 50
+.byte 53
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.sdata
+.align 0
+L.358:
+.byte 115
+.byte 50
+.byte 53
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s25
+.text
+.text
+.align 2
+.ent s25
+s25:
+.frame $sp,56,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-56
+.mask 0xc2fe0000,-4
+sw $17,16($sp)
+sw $18,20($sp)
+sw $19,24($sp)
+sw $20,28($sp)
+sw $21,32($sp)
+sw $22,36($sp)
+sw $23,40($sp)
+.cprestore 44
+sw $30,48($sp)
+sw $31,52($sp)
+move $30,$4
+la $20,L.358
+la $19,60($30)
+L.359:
+L.360:
+move $24,$19
+la $19,1($24)
+move $15,$20
+la $20,1($15)
+lb $15,($15)
+sb $15,($24)
+sll $24,$15,8*(4-1); sra $24,$24,8*(4-1)
+bne $24,$0,L.359
+move $18,$0
+la $22,L.362
+lb $24,1($22)
+lb $15,($22)
+bne $15,$24,L.366
+lb $15,2($22)
+bne $24,$15,L.366
+la $24,46
+beq $15,$24,L.363
+L.366:
+la $18,1($18)
+lw $24,44($30)
+beq $24,$0,L.367
+la $4,L.357
+la $5,1
+jal printf
+L.367:
+L.363:
+lb $24,3($22)
+beq $24,$0,L.369
+la $18,4($18)
+lw $24,44($30)
+beq $24,$0,L.371
+la $4,L.357
+la $5,4
+jal printf
+L.371:
+L.369:
+lb $24,L.375+1
+la $15,34
+beq $24,$15,L.373
+la $18,8($18)
+lw $24,44($30)
+beq $24,$0,L.377
+la $4,L.357
+la $5,8
+jal printf
+L.377:
+L.373:
+la $22,L.379
+lb $24,($22)
+la $15,10
+bne $24,$15,L.387
+lb $24,1($22)
+la $15,9
+bne $24,$15,L.387
+lb $24,2($22)
+la $15,8
+bne $24,$15,L.387
+lb $24,3($22)
+la $15,13
+bne $24,$15,L.387
+lb $24,4($22)
+la $15,12
+bne $24,$15,L.387
+lb $24,5($22)
+la $15,92
+bne $24,$15,L.387
+lb $24,6($22)
+la $15,39
+beq $24,$15,L.380
+L.387:
+la $18,16($18)
+lw $24,44($30)
+beq $24,$0,L.388
+la $4,L.357
+la $5,16
+jal printf
+L.388:
+L.380:
+la $24,L.390
+move $21,$24
+move $22,$24
+move $17,$0
+move $23,$0
+b L.394
+L.391:
+addu $24,$23,$22
+lb $24,($24)
+addu $15,$23,$21
+lb $15,($15)
+beq $24,$15,L.395
+la $17,1
+L.395:
+L.392:
+la $23,1($23)
+L.394:
+move $24,$23
+la $15,7
+bltu $24,$15,L.391
+beq $17,$0,L.397
+la $18,32($18)
+lw $24,44($30)
+beq $24,$0,L.399
+la $4,L.357
+la $5,32
+jal printf
+L.399:
+L.397:
+move $2,$18
+L.356:
+lw $17,16($sp)
+lw $18,20($sp)
+lw $19,24($sp)
+lw $20,28($sp)
+lw $21,32($sp)
+lw $22,36($sp)
+lw $23,40($sp)
+lw $25,44($sp)
+lw $30,48($sp)
+lw $31,52($sp)
+addu $sp,$sp,56
+j $31
+.end s25
+.sdata
+.align 0
+L.402:
+.byte 115
+.byte 50
+.byte 54
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.data
+.align 0
+L.403:
+.byte 37
+.byte 51
+.byte 100
+.byte 32
+.byte 98
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 37
+.byte 115
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.data
+.align 0
+L.404:
+.byte 37
+.byte 101
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 108
+.byte 101
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 97
+.byte 100
+.byte 100
+.byte 101
+.byte 100
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 49
+.byte 46
+.byte 32
+.byte 40
+.byte 37
+.byte 115
+.byte 41
+.byte 46
+.byte 10
+.byte 0
+.globl s26
+.text
+.text
+.align 2
+.ent s26
+s26:
+.frame $sp,96,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-96
+.fmask 0xffc00000,-40
+.mask 0xc2f00000,-8
+s.d $f22,24($sp)
+s.d $f24,32($sp)
+s.d $f26,40($sp)
+s.d $f28,48($sp)
+s.d $f30,56($sp)
+sw $20,64($sp)
+sw $21,68($sp)
+sw $22,72($sp)
+sw $23,76($sp)
+.cprestore 80
+sw $30,84($sp)
+sw $31,88($sp)
+move $30,$4
+la $22,L.402
+la $21,60($30)
+L.405:
+L.406:
+move $24,$21
+la $21,1($24)
+move $15,$22
+la $22,1($15)
+lb $15,($15)
+sb $15,($24)
+sll $24,$15,8*(4-1); sra $24,$24,8*(4-1)
+bne $24,$0,L.405
+sw $0,($30)
+move $20,$0
+la $23,1
+b L.409
+L.408:
+sll $24,$23,8*(4-1); sra $24,$24,8*(4-1)
+sll $24,$24,1
+move $23,$24
+lw $24,($30)
+la $24,1($24)
+sw $24,($30)
+L.409:
+sll $24,$20,8*(4-1); sra $24,$24,8*(4-1)
+sll $15,$23,8*(4-1); sra $15,$15,8*(4-1)
+bne $24,$15,L.408
+lw $24,($30)
+sll $24,$24,2
+sw $24,4($30)
+lw $24,($30)
+sll $24,$24,1
+sw $24,8($30)
+lw $24,($30)
+sll $24,$24,2
+sw $24,12($30)
+lw $24,($30)
+sll $24,$24,2
+sw $24,16($30)
+lw $24,($30)
+sll $24,$24,2
+sw $24,20($30)
+lw $24,($30)
+sll $24,$24,3
+sw $24,24($30)
+l.s $f18,L.411
+mov.s $f26,$f18
+mov.s $f30,$f18
+l.s $f28,L.412
+b L.414
+L.413:
+add.s $f28,$f26,$f30
+cvt.d.s $f18,$f30
+l.d $f16,L.416
+div.d $f18,$f18,$f16
+cvt.s.d $f30,$f18
+L.414:
+c.eq.s $f28,$f26; bc1f L.413
+l.d $f18,L.417
+cvt.d.s $f16,$f30
+mul.d $f18,$f18,$f16
+cvt.s.d $f18,$f18
+s.s $f18,28($30)
+l.d $f22,L.418
+l.s $f30,L.411
+l.d $f24,L.419
+b L.421
+L.420:
+cvt.d.s $f18,$f30
+add.d $f24,$f22,$f18
+l.d $f16,L.416
+div.d $f18,$f18,$f16
+cvt.s.d $f30,$f18
+L.421:
+c.eq.d $f24,$f22; bc1f L.420
+l.d $f18,L.417
+cvt.d.s $f16,$f30
+mul.d $f18,$f18,$f16
+cvt.s.d $f18,$f18
+s.s $f18,32($30)
+lw $24,40($30)
+beq $24,$0,L.423
+la $4,L.403
+lw $5,($30)
+la $6,L.425
+jal printf
+la $4,L.403
+lw $5,4($30)
+la $6,L.426
+jal printf
+la $4,L.403
+lw $5,8($30)
+la $6,L.427
+jal printf
+la $4,L.403
+lw $5,12($30)
+la $6,L.428
+jal printf
+la $4,L.403
+lw $5,16($30)
+la $6,L.429
+jal printf
+la $4,L.403
+lw $5,20($30)
+la $6,L.430
+jal printf
+la $4,L.403
+lw $5,24($30)
+la $6,L.431
+jal printf
+la $4,L.404
+l.s $f18,28($30)
+cvt.d.s $f18,$f18
+mfc1.d $6,$f18
+la $24,L.430
+sw $24,16($sp)
+jal printf
+la $4,L.404
+l.s $f18,32($30)
+cvt.d.s $f18,$f18
+mfc1.d $6,$f18
+la $24,L.431
+sw $24,16($sp)
+jal printf
+L.423:
+move $2,$0
+L.401:
+l.d $f22,24($sp)
+l.d $f24,32($sp)
+l.d $f26,40($sp)
+l.d $f28,48($sp)
+l.d $f30,56($sp)
+lw $20,64($sp)
+lw $21,68($sp)
+lw $22,72($sp)
+lw $23,76($sp)
+lw $25,80($sp)
+lw $30,84($sp)
+lw $31,88($sp)
+addu $sp,$sp,96
+j $31
+.end s26
+.data
+.align 0
+L.433:
+.byte 115
+.byte 52
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.sdata
+.align 0
+L.434:
+.byte 115
+.byte 52
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s4
+.text
+.text
+.align 2
+.ent s4
+s4:
+.frame $sp,72,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-72
+.mask 0xc2fc0000,-24
+sw $18,16($sp)
+sw $19,20($sp)
+sw $20,24($sp)
+sw $21,28($sp)
+sw $22,32($sp)
+sw $23,36($sp)
+.cprestore 40
+sw $30,44($sp)
+sw $31,48($sp)
+move $30,$4
+move $18,$0
+la $20,L.434
+la $19,60($30)
+L.435:
+L.436:
+move $24,$19
+la $19,1($24)
+move $15,$20
+la $20,1($15)
+lb $15,($15)
+sb $15,($24)
+sll $24,$15,8*(4-1); sra $24,$24,8*(4-1)
+bne $24,$0,L.435
+move $23,$0
+L.438:
+move $4,$23
+jal svtest
+move $24,$2
+sw $24,-16+72($sp)
+jal zero
+lw $15,-16+72($sp)
+beq $15,$2,L.442
+la $18,1
+lw $24,44($30)
+beq $24,$0,L.444
+la $4,L.433
+la $5,1
+jal printf
+L.444:
+L.442:
+L.439:
+la $23,1($23)
+la $24,3
+blt $23,$24,L.438
+jal setev
+jal testev
+beq $2,$0,L.446
+la $18,2($18)
+lw $24,44($30)
+beq $24,$0,L.448
+la $4,L.433
+la $5,2
+jal printf
+L.448:
+L.446:
+b L.450
+la $18,4($18)
+lw $24,44($30)
+beq $24,$0,L.452
+la $4,L.433
+la $5,4
+jal printf
+L.452:
+L.450:
+la $22,0xffffffff
+la $21,1
+move $23,$0
+b L.457
+L.454:
+and $21,$21,$22
+srl $22,$22,1
+L.455:
+la $23,1($23)
+L.457:
+move $24,$23
+lw $15,($30)
+sll $15,$15,2
+bltu $24,$15,L.454
+la $24,1
+bne $21,$24,L.460
+beq $22,$0,L.458
+L.460:
+la $18,8($18)
+lw $24,44($30)
+beq $24,$0,L.461
+la $4,L.433
+la $5,8
+jal printf
+L.461:
+L.458:
+move $2,$18
+L.432:
+lw $18,16($sp)
+lw $19,20($sp)
+lw $20,24($sp)
+lw $21,28($sp)
+lw $22,32($sp)
+lw $23,36($sp)
+lw $25,40($sp)
+lw $30,44($sp)
+lw $31,48($sp)
+addu $sp,$sp,72
+j $31
+.end s4
+.lcomm L.464,4
+.globl svtest
+.text
+.text
+.align 2
+.ent svtest
+svtest:
+.frame $sp,8,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-8
+beq $4,$0,L.467
+la $24,1
+beq $4,$24,L.468
+la $24,2
+beq $4,$24,L.471
+b L.465
+L.467:
+la $24,1978
+sw $24,L.464
+sw $0,-4+8($sp)
+b L.466
+L.468:
+lw $24,L.464
+la $15,1978
+beq $24,$15,L.469
+la $24,1
+sw $24,-4+8($sp)
+b L.466
+L.469:
+la $24,1929
+sw $24,L.464
+sw $0,-4+8($sp)
+b L.466
+L.471:
+lw $24,L.464
+la $15,1929
+beq $24,$15,L.472
+la $24,1
+sw $24,-4+8($sp)
+b L.466
+L.472:
+sw $0,-4+8($sp)
+L.465:
+L.466:
+lw $2,-4+8($sp)
+L.463:
+addu $sp,$sp,8
+j $31
+.end svtest
+.lcomm L.475,4
+.globl zero
+.text
+.text
+.align 2
+.ent zero
+zero:
+.frame $sp,8,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-8
+la $24,2
+sw $24,L.475
+sw $0,-4+8($sp)
+lw $2,-4+8($sp)
+L.474:
+addu $sp,$sp,8
+j $31
+.end zero
+.globl testev
+.text
+.align 2
+.ent testev
+testev:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+lw $24,extvar
+la $15,1066
+beq $24,$15,L.477
+la $2,1
+b L.476
+L.477:
+move $2,$0
+L.476:
+j $31
+.end testev
+.data
+.align 0
+L.480:
+.byte 115
+.byte 54
+.byte 49
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.sdata
+.align 0
+L.481:
+.byte 115
+.byte 54
+.byte 49
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.data
+.align 0
+L.482:
+.byte 65
+.byte 66
+.byte 67
+.byte 68
+.byte 69
+.byte 70
+.byte 71
+.byte 72
+.byte 73
+.byte 74
+.byte 75
+.byte 76
+.byte 77
+.byte 78
+.byte 79
+.byte 80
+.byte 81
+.byte 82
+.byte 83
+.byte 84
+.byte 85
+.byte 86
+.byte 87
+.byte 88
+.byte 89
+.byte 90
+.byte 0
+.data
+.align 0
+L.483:
+.byte 97
+.byte 98
+.byte 99
+.byte 100
+.byte 101
+.byte 102
+.byte 103
+.byte 104
+.byte 105
+.byte 106
+.byte 107
+.byte 108
+.byte 109
+.byte 110
+.byte 111
+.byte 112
+.byte 113
+.byte 114
+.byte 115
+.byte 116
+.byte 117
+.byte 118
+.byte 119
+.byte 120
+.byte 121
+.byte 122
+.byte 0
+.data
+.align 0
+L.484:
+.byte 48
+.byte 49
+.byte 50
+.byte 51
+.byte 52
+.byte 53
+.byte 54
+.byte 55
+.byte 56
+.byte 57
+.byte 0
+.data
+.align 0
+L.485:
+.byte 126
+.byte 33
+.byte 34
+.byte 35
+.byte 37
+.byte 38
+.byte 40
+.byte 41
+.byte 95
+.byte 61
+.byte 45
+.byte 94
+.byte 124
+.byte 123
+.byte 125
+.byte 91
+.byte 93
+.byte 43
+.byte 59
+.byte 42
+.byte 58
+.byte 60
+.byte 62
+.byte 44
+.byte 46
+.byte 63
+.byte 47
+.byte 0
+.data
+.align 0
+L.486:
+.byte 10
+.byte 9
+.byte 8
+.byte 13
+.byte 12
+.byte 92
+.byte 39
+.byte 0
+.data
+.align 0
+L.487:
+.byte 32
+.byte 0
+.byte 0
+.globl s61
+.text
+.text
+.align 2
+.ent s61
+s61:
+.frame $sp,88,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-88
+.mask 0xc2fe0000,-36
+sw $17,16($sp)
+sw $18,20($sp)
+sw $19,24($sp)
+sw $20,28($sp)
+sw $21,32($sp)
+sw $22,36($sp)
+sw $23,40($sp)
+.cprestore 44
+sw $30,48($sp)
+sw $31,52($sp)
+sw $4,88($sp)
+la $22,L.481
+lw $24,0+88($sp)
+la $21,60($24)
+move $19,$0
+L.488:
+L.489:
+move $24,$21
+la $21,1($24)
+move $15,$22
+la $22,1($15)
+lb $15,($15)
+sb $15,($24)
+sll $24,$15,8*(4-1); sra $24,$24,8*(4-1)
+bne $24,$0,L.488
+la $24,-19
+sh $24,-26+88($sp)
+lh $24,-26+88($sp)
+sw $24,-32+88($sp)
+lw $24,-32+88($sp)
+la $15,-19
+beq $24,$15,L.491
+la $19,1($19)
+lw $24,0+88($sp)
+lw $24,44($24)
+beq $24,$0,L.493
+la $4,L.480
+la $5,1
+jal printf
+L.493:
+L.491:
+la $24,L.482
+sw $24,-24+88($sp)
+la $24,L.483
+sw $24,-20+88($sp)
+la $24,L.484
+sw $24,-16+88($sp)
+la $24,L.485
+sw $24,-12+88($sp)
+la $24,L.486
+sw $24,-8+88($sp)
+la $24,L.487
+sw $24,-4+88($sp)
+move $23,$0
+move $30,$0
+b L.505
+L.504:
+sll $24,$30,2
+la $15,-24+88($sp)
+addu $24,$24,$15
+lw $15,($24)
+la $14,1($15)
+sw $14,($24)
+lb $24,($15)
+bge $24,$0,L.507
+la $23,1
+L.507:
+L.505:
+sll $24,$30,2
+la $15,-24+88($sp)
+addu $24,$24,$15
+lw $24,($24)
+lb $24,($24)
+bne $24,$0,L.504
+L.501:
+la $30,1($30)
+la $24,6
+blt $30,$24,L.505
+beq $23,$0,L.509
+la $19,2($19)
+lw $24,0+88($sp)
+lw $24,44($24)
+beq $24,$0,L.511
+la $4,L.480
+la $5,2
+jal printf
+L.511:
+L.509:
+la $20,1048579
+move $18,$20
+move $17,$20
+sll $24,$18,8*(4-2); sra $24,$24,8*(4-2)
+beq $24,$20,L.516
+la $15,3
+bne $24,$15,L.515
+L.516:
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+beq $24,$20,L.513
+la $15,3
+beq $24,$15,L.513
+L.515:
+la $19,8($19)
+lw $24,0+88($sp)
+lw $24,44($24)
+beq $24,$0,L.517
+la $4,L.480
+la $5,8
+jal printf
+L.517:
+L.513:
+move $2,$19
+L.479:
+lw $17,16($sp)
+lw $18,20($sp)
+lw $19,24($sp)
+lw $20,28($sp)
+lw $21,32($sp)
+lw $22,36($sp)
+lw $23,40($sp)
+lw $25,44($sp)
+lw $30,48($sp)
+lw $31,52($sp)
+addu $sp,$sp,88
+j $31
+.end s61
+.data
+.align 0
+L.520:
+.byte 115
+.byte 54
+.byte 50
+.byte 54
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.sdata
+.align 0
+L.521:
+.byte 115
+.byte 54
+.byte 50
+.byte 54
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s626
+.text
+.text
+.align 2
+.ent s626
+s626:
+.frame $sp,152,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-152
+.fmask 0xff000000,-112
+.mask 0xc2ff0000,-64
+s.d $f24,16($sp)
+s.d $f26,24($sp)
+s.d $f28,32($sp)
+s.d $f30,40($sp)
+sw $16,48($sp)
+sw $17,52($sp)
+sw $18,56($sp)
+sw $19,60($sp)
+sw $20,64($sp)
+sw $21,68($sp)
+sw $22,72($sp)
+sw $23,76($sp)
+.cprestore 80
+sw $30,84($sp)
+sw $31,88($sp)
+move $30,$4
+la $20,L.521
+la $19,60($30)
+sw $0,-52+152($sp)
+L.522:
+L.523:
+move $24,$19
+la $19,1($24)
+move $15,$20
+la $20,1($15)
+lb $15,($15)
+sb $15,($24)
+sll $24,$15,8*(4-1); sra $24,$24,8*(4-1)
+bne $24,$0,L.522
+l.s $f30,L.411
+la $24,1
+move $18,$24
+move $22,$24
+move $23,$0
+b L.528
+L.525:
+l.s $f18,L.529
+mul.s $f30,$f18,$f30
+sll $24,$22,1
+or $22,$24,$18
+L.526:
+la $23,1($23)
+L.528:
+lw $24,12($30)
+subu $24,$24,2
+blt $23,$24,L.525
+mtc1 $22,$f18; cvt.s.w $f18,$f18
+s.s $f18,-60+152($sp)
+l.s $f18,-60+152($sp)
+sub.s $f18,$f30,$f18
+div.s $f30,$f18,$f30
+cvt.d.s $f18,$f30
+l.d $f16,L.416
+l.s $f10,28($30)
+cvt.d.s $f10,$f10
+mul.d $f16,$f16,$f10
+c.le.d $f18,$f16; bc1t L.530
+lw $24,-52+152($sp)
+la $24,2($24)
+sw $24,-52+152($sp)
+lw $24,44($30)
+beq $24,$0,L.532
+la $4,L.520
+la $5,2
+jal printf
+L.532:
+L.530:
+la $16,125
+la $24,125
+sh $24,-30+152($sp)
+la $24,125
+sw $24,-36+152($sp)
+la $24,15625
+sw $24,-44+152($sp)
+la $24,125
+sw $24,-40+152($sp)
+la $24,15625
+sw $24,-48+152($sp)
+la $17,125
+la $24,15625
+sw $24,-56+152($sp)
+l.s $f26,L.534
+l.d $f24,L.535
+l.d $f28,L.536
+move $23,$0
+L.537:
+la $24,-28+152($sp)
+addu $24,$23,$24
+sb $0,($24)
+L.538:
+la $23,1($23)
+la $24,28
+blt $23,$24,L.537
+sll $24,$16,8*(4-1); sra $24,$24,8*(4-1)
+mul $24,$24,$24
+lw $15,-44+152($sp)
+beq $24,$15,L.541
+la $24,1
+sb $24,-28+152($sp)
+L.541:
+lh $24,-30+152($sp)
+sll $15,$16,8*(4-1); sra $15,$15,8*(4-1)
+mul $24,$24,$15
+lw $15,-44+152($sp)
+beq $24,$15,L.543
+la $24,1
+sb $24,-27+152($sp)
+L.543:
+lh $24,-30+152($sp)
+mul $24,$24,$24
+lw $15,-44+152($sp)
+beq $24,$15,L.546
+la $24,1
+sb $24,-26+152($sp)
+L.546:
+lw $24,-36+152($sp)
+sll $15,$16,8*(4-1); sra $15,$15,8*(4-1)
+mul $24,$24,$15
+lw $15,-44+152($sp)
+beq $24,$15,L.549
+la $24,1
+sb $24,-25+152($sp)
+L.549:
+lw $24,-36+152($sp)
+lh $15,-30+152($sp)
+mul $24,$24,$15
+lw $15,-44+152($sp)
+beq $24,$15,L.552
+la $24,1
+sb $24,-24+152($sp)
+L.552:
+lw $24,-36+152($sp)
+mul $24,$24,$24
+lw $15,-44+152($sp)
+beq $24,$15,L.555
+la $24,1
+sb $24,-23+152($sp)
+L.555:
+lw $24,-40+152($sp)
+sll $15,$16,8*(4-1); sra $15,$15,8*(4-1)
+mul $24,$24,$15
+lw $15,-48+152($sp)
+beq $24,$15,L.558
+la $24,1
+sb $24,-22+152($sp)
+L.558:
+lw $24,-40+152($sp)
+lh $15,-30+152($sp)
+mul $24,$24,$15
+lw $15,-48+152($sp)
+beq $24,$15,L.561
+la $24,1
+sb $24,-21+152($sp)
+L.561:
+lw $24,-40+152($sp)
+lw $15,-36+152($sp)
+mul $24,$24,$15
+lw $15,-48+152($sp)
+beq $24,$15,L.564
+la $24,1
+sb $24,-20+152($sp)
+L.564:
+lw $24,-40+152($sp)
+mul $24,$24,$24
+lw $15,-48+152($sp)
+beq $24,$15,L.567
+la $24,1
+sb $24,-19+152($sp)
+L.567:
+sll $24,$16,8*(4-1); sra $24,$24,8*(4-1)
+mul $24,$17,$24
+lw $15,-56+152($sp)
+beq $24,$15,L.570
+la $24,1
+sb $24,-18+152($sp)
+L.570:
+lh $24,-30+152($sp)
+mul $24,$17,$24
+lw $15,-56+152($sp)
+beq $24,$15,L.573
+la $24,1
+sb $24,-17+152($sp)
+L.573:
+lw $24,-36+152($sp)
+mul $24,$17,$24
+lw $15,-56+152($sp)
+beq $24,$15,L.576
+la $24,1
+sb $24,-16+152($sp)
+L.576:
+move $24,$17
+lw $15,-40+152($sp)
+mul $24,$24,$15
+lw $15,-48+152($sp)
+beq $24,$15,L.579
+la $24,1
+sb $24,-15+152($sp)
+L.579:
+mul $24,$17,$17
+lw $15,-56+152($sp)
+beq $24,$15,L.582
+la $24,1
+sb $24,-14+152($sp)
+L.582:
+sll $24,$16,8*(4-1); sra $24,$24,8*(4-1)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+mul.s $f18,$f26,$f18
+cvt.d.s $f18,$f18
+c.eq.d $f18,$f28; bc1t L.585
+la $24,1
+sb $24,-13+152($sp)
+L.585:
+lh $24,-30+152($sp)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+mul.s $f18,$f26,$f18
+cvt.d.s $f18,$f18
+c.eq.d $f18,$f28; bc1t L.588
+la $24,1
+sb $24,-12+152($sp)
+L.588:
+lw $24,-36+152($sp)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+mul.s $f18,$f26,$f18
+cvt.d.s $f18,$f18
+c.eq.d $f18,$f28; bc1t L.591
+la $24,1
+sb $24,-11+152($sp)
+L.591:
+lw $24,-40+152($sp)
+l.d $f18,L.596
+srl $15,$24,1
+mtc1 $15,$f16; cvt.d.w $f16,$f16
+mul.d $f18,$f18,$f16
+and $24,$24,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+add.d $f18,$f18,$f16
+cvt.s.d $f18,$f18
+mul.s $f18,$f26,$f18
+cvt.d.s $f18,$f18
+c.eq.d $f18,$f28; bc1t L.594
+la $24,1
+sb $24,-10+152($sp)
+L.594:
+mtc1 $17,$f18; cvt.s.w $f18,$f18
+mul.s $f18,$f26,$f18
+cvt.d.s $f18,$f18
+c.eq.d $f18,$f28; bc1t L.598
+la $24,1
+sb $24,-9+152($sp)
+L.598:
+mul.s $f18,$f26,$f26
+cvt.d.s $f18,$f18
+c.eq.d $f18,$f28; bc1t L.601
+la $24,1
+sb $24,-8+152($sp)
+L.601:
+sll $24,$16,8*(4-1); sra $24,$24,8*(4-1)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+mul.d $f18,$f24,$f18
+c.eq.d $f18,$f28; bc1t L.604
+la $24,1
+sb $24,-7+152($sp)
+L.604:
+lh $24,-30+152($sp)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+mul.d $f18,$f24,$f18
+c.eq.d $f18,$f28; bc1t L.607
+la $24,1
+sb $24,-6+152($sp)
+L.607:
+lw $24,-36+152($sp)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+mul.d $f18,$f24,$f18
+c.eq.d $f18,$f28; bc1t L.610
+la $24,1
+sb $24,-5+152($sp)
+L.610:
+lw $24,-40+152($sp)
+l.d $f18,L.596
+srl $15,$24,1
+mtc1 $15,$f16; cvt.d.w $f16,$f16
+mul.d $f18,$f18,$f16
+and $24,$24,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+add.d $f18,$f18,$f16
+mul.d $f18,$f24,$f18
+c.eq.d $f18,$f28; bc1t L.613
+la $24,1
+sb $24,-4+152($sp)
+L.613:
+mtc1 $17,$f18; cvt.d.w $f18,$f18
+mul.d $f18,$f24,$f18
+c.eq.d $f18,$f28; bc1t L.616
+la $24,1
+sb $24,-3+152($sp)
+L.616:
+cvt.d.s $f18,$f26
+mul.d $f18,$f24,$f18
+c.eq.d $f18,$f28; bc1t L.619
+la $24,1
+sb $24,-2+152($sp)
+L.619:
+mul.d $f18,$f24,$f24
+c.eq.d $f18,$f28; bc1t L.622
+la $24,1
+sb $24,-1+152($sp)
+L.622:
+move $21,$0
+move $23,$0
+L.625:
+sll $24,$21,8*(4-1); sra $24,$24,8*(4-1)
+la $15,-28+152($sp)
+addu $15,$23,$15
+lb $15,($15)
+addu $24,$24,$15
+move $21,$24
+L.626:
+la $23,1($23)
+la $24,28
+blt $23,$24,L.625
+sll $24,$21,8*(4-1); sra $24,$24,8*(4-1)
+beq $24,$0,L.629
+lw $24,-52+152($sp)
+la $24,4($24)
+sw $24,-52+152($sp)
+lw $24,44($30)
+beq $24,$0,L.631
+la $4,L.520
+la $5,4
+jal printf
+la $4,L.633
+jal printf
+move $23,$0
+L.634:
+la $4,L.638
+la $24,-28+152($sp)
+addu $24,$23,$24
+lb $5,($24)
+jal printf
+L.635:
+la $23,1($23)
+la $24,28
+blt $23,$24,L.634
+la $4,L.639
+jal printf
+L.631:
+L.629:
+la $17,32768
+move $24,$17
+la $15,0x8000
+bleu $24,$15,L.640
+lw $24,-52+152($sp)
+la $24,8($24)
+sw $24,-52+152($sp)
+lw $24,44($30)
+beq $24,$0,L.642
+la $4,L.520
+la $5,8
+jal printf
+L.642:
+L.640:
+lw $2,-52+152($sp)
+L.519:
+l.d $f24,16($sp)
+l.d $f26,24($sp)
+l.d $f28,32($sp)
+l.d $f30,40($sp)
+lw $16,48($sp)
+lw $17,52($sp)
+lw $18,56($sp)
+lw $19,60($sp)
+lw $20,64($sp)
+lw $21,68($sp)
+lw $22,72($sp)
+lw $23,76($sp)
+lw $25,80($sp)
+lw $30,84($sp)
+lw $31,88($sp)
+addu $sp,$sp,152
+j $31
+.end s626
+.data
+.align 0
+L.645:
+.byte 115
+.byte 55
+.byte 49
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.sdata
+.align 0
+L.646:
+.byte 115
+.byte 55
+.byte 49
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.sdata
+.align 0
+L.647:
+.byte 0x71
+.globl s71
+.text
+.text
+.align 2
+.ent s71
+s71:
+.frame $sp,96,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-96
+.mask 0xc2f00000,-56
+sw $20,16($sp)
+sw $21,20($sp)
+sw $22,24($sp)
+sw $23,28($sp)
+.cprestore 32
+sw $30,36($sp)
+sw $31,40($sp)
+move $30,$4
+la $23,L.646
+la $22,60($30)
+move $21,$0
+L.648:
+L.649:
+move $24,$22
+la $22,1($24)
+move $15,$23
+la $23,1($15)
+lb $15,($15)
+sb $15,($24)
+sll $24,$15,8*(4-1); sra $24,$24,8*(4-1)
+bne $24,$0,L.648
+lb $24,L.653
+lb $15,L.647
+beq $24,$15,L.651
+la $21,1($21)
+lw $24,44($30)
+beq $24,$0,L.654
+la $4,L.645
+la $5,1
+jal printf
+L.654:
+L.651:
+b L.656
+la $21,2($21)
+lw $24,44($30)
+beq $24,$0,L.658
+la $4,L.645
+la $5,2
+jal printf
+L.658:
+L.656:
+la $24,1942
+sw $24,-20+96($sp)
+lw $24,-20+96($sp)
+la $15,1942
+bne $24,$15,L.666
+lw $24,-20+96($sp)
+lw $15,-20+96($sp)
+beq $24,$15,L.661
+L.666:
+la $21,4($21)
+lw $24,44($30)
+beq $24,$0,L.667
+la $4,L.645
+la $5,4
+jal printf
+L.667:
+L.661:
+la $4,-5
+jal McCarthy
+la $15,91
+beq $2,$15,L.669
+la $21,8($21)
+lw $24,44($30)
+beq $24,$0,L.671
+la $4,L.645
+la $5,8
+jal printf
+L.671:
+L.669:
+la $20,2
+la $24,3
+sw $24,-44+96($sp)
+la $24,-44+96($sp)
+sw $24,-48+96($sp)
+move $4,$20
+lw $5,-48+96($sp)
+jal clobber
+la $24,2
+bne $20,$24,L.675
+lw $15,-44+96($sp)
+beq $15,$24,L.673
+L.675:
+la $21,16($21)
+lw $24,44($30)
+beq $24,$0,L.676
+la $4,L.645
+la $5,16
+jal printf
+L.676:
+L.673:
+l.s $f18,32($30)
+c.eq.s $f18,$f18; bc1t L.678
+la $21,32($21)
+lw $24,44($30)
+beq $24,$0,L.680
+la $4,L.645
+la $5,32
+jal printf
+L.680:
+L.678:
+move $2,$21
+L.644:
+lw $20,16($sp)
+lw $21,20($sp)
+lw $22,24($sp)
+lw $23,28($sp)
+lw $25,32($sp)
+lw $30,36($sp)
+lw $31,40($sp)
+addu $sp,$sp,96
+j $31
+.end s71
+.globl McCarthy
+.text
+.align 2
+.ent McCarthy
+McCarthy:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+sw $4,24($sp)
+lw $24,0+24($sp)
+la $15,100
+ble $24,$15,L.683
+lw $24,0+24($sp)
+subu $2,$24,10
+b L.682
+L.683:
+lw $24,0+24($sp)
+la $4,11($24)
+jal McCarthy
+move $24,$2
+move $4,$24
+jal McCarthy
+move $24,$2
+L.682:
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end McCarthy
+.globl clobber
+.text
+.align 2
+.ent clobber
+clobber:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+la $4,3
+la $24,2
+sw $24,($5)
+move $2,$0
+L.685:
+j $31
+.end clobber
+.data
+.align 0
+L.687:
+.byte 76
+.byte 111
+.byte 99
+.byte 97
+.byte 108
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 37
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.data
+.align 0
+L.688:
+.byte 115
+.byte 55
+.byte 49
+.byte 52
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.sdata
+.align 0
+L.689:
+.byte 115
+.byte 55
+.byte 49
+.byte 52
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s714
+.text
+.text
+.align 2
+.ent s714
+s714:
+.frame $sp,160,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-160
+.fmask 0xff000000,-120
+.mask 0xc2ff0000,-72
+s.d $f24,16($sp)
+s.d $f26,24($sp)
+s.d $f28,32($sp)
+s.d $f30,40($sp)
+sw $16,48($sp)
+sw $17,52($sp)
+sw $18,56($sp)
+sw $19,60($sp)
+sw $20,64($sp)
+sw $21,68($sp)
+sw $22,72($sp)
+sw $23,76($sp)
+.cprestore 80
+sw $30,84($sp)
+sw $31,88($sp)
+sw $4,160($sp)
+la $24,L.689
+sw $24,-16+160($sp)
+lw $24,0+160($sp)
+la $15,60($24)
+sw $15,-20+160($sp)
+sw $0,-24+160($sp)
+move $23,$0
+lw $30,48($24)
+L.690:
+L.691:
+lw $24,-20+160($sp)
+la $15,1($24)
+sw $15,-20+160($sp)
+lw $15,-16+160($sp)
+la $14,1($15)
+sw $14,-16+160($sp)
+lb $15,($15)
+sb $15,($24)
+sll $24,$15,8*(4-1); sra $24,$24,8*(4-1)
+bne $24,$0,L.690
+la $22,5
+la $17,2
+move $22,$17
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,2
+beq $24,$15,L.693
+la $23,1
+beq $30,$0,L.695
+la $4,L.687
+move $5,$23
+jal printf
+L.695:
+L.693:
+la $22,5
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,2
+beq $24,$15,L.697
+la $23,2
+beq $30,$0,L.699
+la $4,L.687
+move $5,$23
+jal printf
+L.699:
+L.697:
+la $22,5
+la $24,2
+sw $24,-4+160($sp)
+lw $15,-4+160($sp)
+move $22,$15
+sll $15,$22,8*(4-1); sra $15,$15,8*(4-1)
+beq $15,$24,L.701
+la $23,3
+beq $30,$0,L.703
+la $4,L.687
+move $5,$23
+jal printf
+L.703:
+L.701:
+la $22,5
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,2
+beq $24,$15,L.705
+la $23,4
+beq $30,$0,L.707
+la $4,L.687
+move $5,$23
+jal printf
+L.707:
+L.705:
+la $22,5
+la $24,2
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,2
+beq $24,$15,L.709
+la $23,5
+beq $30,$0,L.711
+la $4,L.687
+move $5,$23
+jal printf
+L.711:
+L.709:
+la $22,5
+l.s $f26,L.529
+trunc.w.s $f2,$f26,$24; mfc1 $24,$f2
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,2
+beq $24,$15,L.713
+la $23,6
+beq $30,$0,L.715
+la $4,L.687
+move $5,$23
+jal printf
+L.715:
+L.713:
+la $22,5
+l.d $f24,L.416
+trunc.w.d $f2,$f24,$24; mfc1 $24,$f2
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,2
+beq $24,$15,L.717
+la $23,7
+beq $30,$0,L.719
+la $4,L.687
+move $5,$23
+jal printf
+L.719:
+L.717:
+la $21,5
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,2
+beq $24,$15,L.721
+la $23,8
+beq $30,$0,L.723
+la $4,L.687
+move $5,$23
+jal printf
+L.723:
+L.721:
+la $21,5
+la $16,2
+move $21,$16
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,2
+beq $24,$15,L.725
+la $23,9
+beq $30,$0,L.727
+la $4,L.687
+move $5,$23
+jal printf
+L.727:
+L.725:
+la $21,5
+la $24,2
+sw $24,-4+160($sp)
+lw $15,-4+160($sp)
+move $21,$15
+sll $15,$21,8*(4-2); sra $15,$15,8*(4-2)
+beq $15,$24,L.729
+la $23,10
+beq $30,$0,L.731
+la $4,L.687
+move $5,$23
+jal printf
+L.731:
+L.729:
+la $21,5
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,2
+beq $24,$15,L.733
+la $23,11
+beq $30,$0,L.735
+la $4,L.687
+move $5,$23
+jal printf
+L.735:
+L.733:
+la $21,5
+la $24,2
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,2
+beq $24,$15,L.737
+la $23,12
+beq $30,$0,L.739
+la $4,L.687
+move $5,$23
+jal printf
+L.739:
+L.737:
+la $21,5
+l.s $f26,L.529
+trunc.w.s $f2,$f26,$24; mfc1 $24,$f2
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,2
+beq $24,$15,L.741
+la $23,13
+beq $30,$0,L.743
+la $4,L.687
+move $5,$23
+jal printf
+L.743:
+L.741:
+la $21,5
+l.d $f24,L.416
+trunc.w.d $f2,$f24,$24; mfc1 $24,$f2
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,2
+beq $24,$15,L.745
+la $23,14
+beq $30,$0,L.747
+la $4,L.687
+move $5,$23
+jal printf
+L.747:
+L.745:
+la $20,5
+la $17,2
+sll $20,$17,8*(4-1); sra $20,$20,8*(4-1)
+la $24,2
+beq $20,$24,L.749
+la $23,15
+beq $30,$0,L.751
+la $4,L.687
+move $5,$23
+jal printf
+L.751:
+L.749:
+la $20,5
+la $16,2
+sll $20,$16,8*(4-2); sra $20,$20,8*(4-2)
+la $24,2
+beq $20,$24,L.753
+la $23,16
+beq $30,$0,L.755
+la $4,L.687
+move $5,$23
+jal printf
+L.755:
+L.753:
+la $20,5
+la $24,2
+sw $24,-4+160($sp)
+lw $20,-4+160($sp)
+beq $20,$24,L.757
+la $23,17
+beq $30,$0,L.759
+la $4,L.687
+move $5,$23
+jal printf
+L.759:
+L.757:
+la $20,5
+la $24,2
+sw $24,-8+160($sp)
+lw $20,-8+160($sp)
+la $24,2
+beq $20,$24,L.761
+la $23,18
+beq $30,$0,L.763
+la $4,L.687
+move $5,$23
+jal printf
+L.763:
+L.761:
+la $20,5
+la $24,2
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+move $20,$24
+la $24,2
+beq $20,$24,L.765
+la $23,19
+beq $30,$0,L.767
+la $4,L.687
+move $5,$23
+jal printf
+L.767:
+L.765:
+la $20,5
+l.s $f26,L.529
+trunc.w.s $f2,$f26,$20; mfc1 $20,$f2
+la $24,2
+beq $20,$24,L.769
+la $23,20
+beq $30,$0,L.771
+la $4,L.687
+move $5,$23
+jal printf
+L.771:
+L.769:
+la $20,5
+l.d $f24,L.416
+trunc.w.d $f2,$f24,$20; mfc1 $20,$f2
+la $24,2
+beq $20,$24,L.773
+la $23,21
+beq $30,$0,L.775
+la $4,L.687
+move $5,$23
+jal printf
+L.775:
+L.773:
+la $19,5
+la $17,2
+sll $19,$17,8*(4-1); sra $19,$19,8*(4-1)
+la $24,2
+beq $19,$24,L.777
+la $23,22
+beq $30,$0,L.779
+la $4,L.687
+move $5,$23
+jal printf
+L.779:
+L.777:
+la $19,5
+la $16,2
+sll $19,$16,8*(4-2); sra $19,$19,8*(4-2)
+la $24,2
+beq $19,$24,L.781
+la $23,23
+beq $30,$0,L.783
+la $4,L.687
+move $5,$23
+jal printf
+L.783:
+L.781:
+la $19,5
+la $24,2
+sw $24,-4+160($sp)
+lw $19,-4+160($sp)
+la $24,2
+beq $19,$24,L.785
+la $23,24
+beq $30,$0,L.787
+la $4,L.687
+move $5,$23
+jal printf
+L.787:
+L.785:
+la $19,5
+la $24,2
+sw $24,-8+160($sp)
+lw $19,-8+160($sp)
+beq $19,$24,L.789
+la $23,25
+beq $30,$0,L.791
+la $4,L.687
+move $5,$23
+jal printf
+L.791:
+L.789:
+la $19,5
+la $24,2
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+move $19,$24
+la $24,2
+beq $19,$24,L.793
+la $23,26
+beq $30,$0,L.795
+la $4,L.687
+move $5,$23
+jal printf
+L.795:
+L.793:
+la $19,5
+l.s $f26,L.529
+trunc.w.s $f2,$f26,$19; mfc1 $19,$f2
+la $24,2
+beq $19,$24,L.797
+la $23,27
+beq $30,$0,L.799
+la $4,L.687
+move $5,$23
+jal printf
+L.799:
+L.797:
+la $19,5
+l.d $f24,L.416
+trunc.w.d $f2,$f24,$19; mfc1 $19,$f2
+la $24,2
+beq $19,$24,L.801
+la $23,28
+beq $30,$0,L.803
+la $4,L.687
+move $5,$23
+jal printf
+L.803:
+L.801:
+la $18,5
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+move $18,$24
+la $24,2
+beq $18,$24,L.805
+la $23,29
+beq $30,$0,L.807
+la $4,L.687
+move $5,$23
+jal printf
+L.807:
+L.805:
+la $18,5
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+move $18,$24
+la $24,2
+beq $18,$24,L.809
+la $23,30
+beq $30,$0,L.811
+la $4,L.687
+move $5,$23
+jal printf
+L.811:
+L.809:
+la $18,5
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+move $18,$24
+la $24,2
+beq $18,$24,L.813
+la $23,31
+beq $30,$0,L.815
+la $4,L.687
+move $5,$23
+jal printf
+L.815:
+L.813:
+la $18,5
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+move $18,$24
+la $24,2
+beq $18,$24,L.817
+la $23,32
+beq $30,$0,L.819
+la $4,L.687
+move $5,$23
+jal printf
+L.819:
+L.817:
+la $18,5
+la $24,2
+sw $24,-12+160($sp)
+lw $18,-12+160($sp)
+beq $18,$24,L.821
+la $23,33
+beq $30,$0,L.823
+la $4,L.687
+move $5,$23
+jal printf
+L.823:
+L.821:
+la $18,5
+l.s $f26,L.529
+l.s $f18,L.828
+c.lt.s $f26,$f18; bc1t L.826
+sub.s $f18,$f26,$f18
+trunc.w.s $f2,$f18,$24; mfc1 $24,$f2
+la $24,0x80000000($24)
+sw $24,-28+160($sp)
+b L.827
+L.826:
+trunc.w.s $f2,$f26,$24; mfc1 $24,$f2
+sw $24,-28+160($sp)
+L.827:
+lw $18,-28+160($sp)
+la $24,2
+beq $18,$24,L.829
+la $23,34
+beq $30,$0,L.831
+la $4,L.687
+move $5,$23
+jal printf
+L.831:
+L.829:
+la $18,5
+l.d $f24,L.416
+l.d $f18,L.836
+c.lt.d $f24,$f18; bc1t L.834
+sub.d $f18,$f24,$f18
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+la $24,0x80000000($24)
+sw $24,-32+160($sp)
+b L.835
+L.834:
+trunc.w.d $f2,$f24,$24; mfc1 $24,$f2
+sw $24,-32+160($sp)
+L.835:
+lw $18,-32+160($sp)
+la $24,2
+beq $18,$24,L.837
+la $23,35
+beq $30,$0,L.839
+la $4,L.687
+move $5,$23
+jal printf
+L.839:
+L.837:
+l.s $f30,L.841
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+mtc1 $24,$f30; cvt.s.w $f30,$f30
+l.s $f18,L.529
+c.eq.s $f30,$f18; bc1t L.842
+la $23,36
+beq $30,$0,L.844
+la $4,L.687
+move $5,$23
+jal printf
+L.844:
+L.842:
+l.s $f30,L.841
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+mtc1 $24,$f30; cvt.s.w $f30,$f30
+l.s $f18,L.529
+c.eq.s $f30,$f18; bc1t L.846
+la $23,37
+beq $30,$0,L.848
+la $4,L.687
+move $5,$23
+jal printf
+L.848:
+L.846:
+l.s $f30,L.841
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+mtc1 $24,$f30; cvt.s.w $f30,$f30
+l.s $f18,L.529
+c.eq.s $f30,$f18; bc1t L.850
+la $23,38
+beq $30,$0,L.852
+la $4,L.687
+move $5,$23
+jal printf
+L.852:
+L.850:
+l.s $f30,L.841
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+mtc1 $24,$f30; cvt.s.w $f30,$f30
+l.s $f18,L.529
+c.eq.s $f30,$f18; bc1t L.854
+la $23,39
+beq $30,$0,L.856
+la $4,L.687
+move $5,$23
+jal printf
+L.856:
+L.854:
+l.s $f30,L.841
+la $24,2
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+l.d $f18,L.596
+srl $15,$24,1
+mtc1 $15,$f16; cvt.d.w $f16,$f16
+mul.d $f18,$f18,$f16
+and $24,$24,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+add.d $f18,$f18,$f16
+cvt.s.d $f30,$f18
+l.s $f18,L.529
+c.eq.s $f30,$f18; bc1t L.858
+la $23,40
+beq $30,$0,L.860
+la $4,L.687
+move $5,$23
+jal printf
+L.860:
+L.858:
+l.s $f30,L.841
+l.s $f18,L.529
+mov.s $f26,$f18
+mov.s $f30,$f26
+c.eq.s $f30,$f18; bc1t L.862
+la $23,41
+beq $30,$0,L.864
+la $4,L.687
+move $5,$23
+jal printf
+L.864:
+L.862:
+l.s $f30,L.841
+l.d $f24,L.416
+cvt.s.d $f30,$f24
+l.s $f18,L.529
+c.eq.s $f30,$f18; bc1t L.866
+la $23,42
+beq $30,$0,L.868
+la $4,L.687
+move $5,$23
+jal printf
+L.868:
+L.866:
+l.d $f28,L.870
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+mtc1 $24,$f28; cvt.d.w $f28,$f28
+l.d $f18,L.416
+c.eq.d $f28,$f18; bc1t L.871
+la $23,43
+beq $30,$0,L.873
+la $4,L.687
+move $5,$23
+jal printf
+L.873:
+L.871:
+l.d $f28,L.870
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+mtc1 $24,$f28; cvt.d.w $f28,$f28
+l.d $f18,L.416
+c.eq.d $f28,$f18; bc1t L.875
+la $23,44
+beq $30,$0,L.877
+la $4,L.687
+move $5,$23
+jal printf
+L.877:
+L.875:
+l.d $f28,L.870
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+mtc1 $24,$f28; cvt.d.w $f28,$f28
+l.d $f18,L.416
+c.eq.d $f28,$f18; bc1t L.879
+la $23,45
+beq $30,$0,L.881
+la $4,L.687
+move $5,$23
+jal printf
+L.881:
+L.879:
+l.d $f28,L.870
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+mtc1 $24,$f28; cvt.d.w $f28,$f28
+l.d $f18,L.416
+c.eq.d $f28,$f18; bc1t L.883
+la $23,46
+beq $30,$0,L.885
+la $4,L.687
+move $5,$23
+jal printf
+L.885:
+L.883:
+l.d $f28,L.870
+la $24,2
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+l.d $f18,L.596
+srl $15,$24,1
+mtc1 $15,$f16; cvt.d.w $f16,$f16
+mul.d $f18,$f18,$f16
+and $24,$24,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+add.d $f28,$f18,$f16
+l.d $f18,L.416
+c.eq.d $f28,$f18; bc1t L.887
+la $23,47
+beq $30,$0,L.889
+la $4,L.687
+move $5,$23
+jal printf
+L.889:
+L.887:
+l.d $f28,L.870
+l.s $f26,L.529
+cvt.d.s $f28,$f26
+l.d $f18,L.416
+c.eq.d $f28,$f18; bc1t L.891
+la $23,48
+beq $30,$0,L.893
+la $4,L.687
+move $5,$23
+jal printf
+L.893:
+L.891:
+l.d $f28,L.870
+l.d $f18,L.416
+mov.d $f24,$f18
+mov.d $f28,$f24
+c.eq.d $f28,$f18; bc1t L.895
+la $23,49
+beq $30,$0,L.897
+la $4,L.687
+move $5,$23
+jal printf
+L.897:
+L.895:
+la $22,5
+la $17,2
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+sll $15,$17,8*(4-1); sra $15,$15,8*(4-1)
+addu $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,7
+beq $24,$15,L.899
+la $23,50
+beq $30,$0,L.901
+la $4,L.687
+move $5,$23
+jal printf
+L.901:
+L.899:
+la $22,5
+la $16,2
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+sll $15,$16,8*(4-2); sra $15,$15,8*(4-2)
+addu $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,7
+beq $24,$15,L.903
+la $23,51
+beq $30,$0,L.905
+la $4,L.687
+move $5,$23
+jal printf
+L.905:
+L.903:
+la $22,5
+la $24,2
+sw $24,-4+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-4+160($sp)
+addu $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,7
+beq $24,$15,L.907
+la $23,52
+beq $30,$0,L.909
+la $4,L.687
+move $5,$23
+jal printf
+L.909:
+L.907:
+la $22,5
+la $24,2
+sw $24,-8+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-8+160($sp)
+addu $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,7
+beq $24,$15,L.911
+la $23,53
+beq $30,$0,L.913
+la $4,L.687
+move $5,$23
+jal printf
+L.913:
+L.911:
+la $22,5
+la $24,2
+sw $24,-12+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-12+160($sp)
+addu $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,7
+beq $24,$15,L.915
+la $23,54
+beq $30,$0,L.917
+la $4,L.687
+move $5,$23
+jal printf
+L.917:
+L.915:
+la $22,5
+l.s $f26,L.529
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+add.s $f18,$f18,$f26
+trunc.w.s $f2,$f18,$24; mfc1 $24,$f2
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,7
+beq $24,$15,L.919
+la $23,55
+beq $30,$0,L.921
+la $4,L.687
+move $5,$23
+jal printf
+L.921:
+L.919:
+la $22,5
+l.d $f24,L.416
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+add.d $f18,$f18,$f24
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,7
+beq $24,$15,L.923
+la $23,56
+beq $30,$0,L.925
+la $4,L.687
+move $5,$23
+jal printf
+L.925:
+L.923:
+la $21,5
+la $17,2
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $15,$17,8*(4-1); sra $15,$15,8*(4-1)
+addu $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,7
+beq $24,$15,L.927
+la $23,57
+beq $30,$0,L.929
+la $4,L.687
+move $5,$23
+jal printf
+L.929:
+L.927:
+la $21,5
+la $16,2
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $15,$16,8*(4-2); sra $15,$15,8*(4-2)
+addu $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,7
+beq $24,$15,L.931
+la $23,58
+beq $30,$0,L.933
+la $4,L.687
+move $5,$23
+jal printf
+L.933:
+L.931:
+la $21,5
+la $24,2
+sw $24,-4+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-4+160($sp)
+addu $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,7
+beq $24,$15,L.935
+la $23,59
+beq $30,$0,L.937
+la $4,L.687
+move $5,$23
+jal printf
+L.937:
+L.935:
+la $21,5
+la $24,2
+sw $24,-8+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-8+160($sp)
+addu $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,7
+beq $24,$15,L.939
+la $23,60
+beq $30,$0,L.941
+la $4,L.687
+move $5,$23
+jal printf
+L.941:
+L.939:
+la $21,5
+la $24,2
+sw $24,-12+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-12+160($sp)
+addu $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,7
+beq $24,$15,L.943
+la $23,61
+beq $30,$0,L.945
+la $4,L.687
+move $5,$23
+jal printf
+L.945:
+L.943:
+la $21,5
+l.s $f26,L.529
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+add.s $f18,$f18,$f26
+trunc.w.s $f2,$f18,$24; mfc1 $24,$f2
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,7
+beq $24,$15,L.947
+la $23,62
+beq $30,$0,L.949
+la $4,L.687
+move $5,$23
+jal printf
+L.949:
+L.947:
+la $21,5
+l.d $f24,L.416
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+add.d $f18,$f18,$f24
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,7
+beq $24,$15,L.951
+la $23,63
+beq $30,$0,L.953
+la $4,L.687
+move $5,$23
+jal printf
+L.953:
+L.951:
+la $20,5
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+addu $20,$20,$24
+la $24,7
+beq $20,$24,L.955
+la $23,64
+beq $30,$0,L.957
+la $4,L.687
+move $5,$23
+jal printf
+L.957:
+L.955:
+la $20,5
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+addu $20,$20,$24
+la $24,7
+beq $20,$24,L.959
+la $23,65
+beq $30,$0,L.961
+la $4,L.687
+move $5,$23
+jal printf
+L.961:
+L.959:
+la $20,5
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+addu $20,$20,$24
+la $24,7
+beq $20,$24,L.963
+la $23,66
+beq $30,$0,L.965
+la $4,L.687
+move $5,$23
+jal printf
+L.965:
+L.963:
+la $20,5
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+addu $20,$20,$24
+la $24,7
+beq $20,$24,L.967
+la $23,67
+beq $30,$0,L.969
+la $4,L.687
+move $5,$23
+jal printf
+L.969:
+L.967:
+la $20,5
+la $24,2
+sw $24,-12+160($sp)
+move $24,$20
+lw $15,-12+160($sp)
+addu $24,$24,$15
+move $20,$24
+la $24,7
+beq $20,$24,L.971
+la $23,68
+beq $30,$0,L.973
+la $4,L.687
+move $5,$23
+jal printf
+L.973:
+L.971:
+la $20,5
+l.s $f26,L.529
+mtc1 $20,$f18; cvt.s.w $f18,$f18
+add.s $f18,$f18,$f26
+trunc.w.s $f2,$f18,$20; mfc1 $20,$f2
+la $24,7
+beq $20,$24,L.975
+la $23,69
+beq $30,$0,L.977
+la $4,L.687
+move $5,$23
+jal printf
+L.977:
+L.975:
+la $20,5
+l.d $f24,L.416
+mtc1 $20,$f18; cvt.d.w $f18,$f18
+add.d $f18,$f18,$f24
+trunc.w.d $f2,$f18,$20; mfc1 $20,$f2
+la $24,7
+beq $20,$24,L.979
+la $23,70
+beq $30,$0,L.981
+la $4,L.687
+move $5,$23
+jal printf
+L.981:
+L.979:
+la $19,5
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+addu $19,$19,$24
+la $24,7
+beq $19,$24,L.983
+la $23,71
+beq $30,$0,L.985
+la $4,L.687
+move $5,$23
+jal printf
+L.985:
+L.983:
+la $19,5
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+addu $19,$19,$24
+la $24,7
+beq $19,$24,L.987
+la $23,72
+beq $30,$0,L.989
+la $4,L.687
+move $5,$23
+jal printf
+L.989:
+L.987:
+la $19,5
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+addu $19,$19,$24
+la $24,7
+beq $19,$24,L.991
+la $23,73
+beq $30,$0,L.993
+la $4,L.687
+move $5,$23
+jal printf
+L.993:
+L.991:
+la $19,5
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+addu $19,$19,$24
+la $24,7
+beq $19,$24,L.995
+la $23,74
+beq $30,$0,L.997
+la $4,L.687
+move $5,$23
+jal printf
+L.997:
+L.995:
+la $19,5
+la $24,2
+sw $24,-12+160($sp)
+move $24,$19
+lw $15,-12+160($sp)
+addu $24,$24,$15
+move $19,$24
+la $24,7
+beq $19,$24,L.999
+la $23,75
+beq $30,$0,L.1001
+la $4,L.687
+move $5,$23
+jal printf
+L.1001:
+L.999:
+la $19,5
+l.s $f26,L.529
+mtc1 $19,$f18; cvt.s.w $f18,$f18
+add.s $f18,$f18,$f26
+trunc.w.s $f2,$f18,$19; mfc1 $19,$f2
+la $24,7
+beq $19,$24,L.1003
+la $23,76
+beq $30,$0,L.1005
+la $4,L.687
+move $5,$23
+jal printf
+L.1005:
+L.1003:
+la $19,5
+l.d $f24,L.416
+mtc1 $19,$f18; cvt.d.w $f18,$f18
+add.d $f18,$f18,$f24
+trunc.w.d $f2,$f18,$19; mfc1 $19,$f2
+la $24,7
+beq $19,$24,L.1007
+la $23,77
+beq $30,$0,L.1009
+la $4,L.687
+move $5,$23
+jal printf
+L.1009:
+L.1007:
+la $18,5
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+addu $18,$18,$24
+la $24,7
+beq $18,$24,L.1011
+la $23,78
+beq $30,$0,L.1013
+la $4,L.687
+move $5,$23
+jal printf
+L.1013:
+L.1011:
+la $18,5
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+addu $18,$18,$24
+la $24,7
+beq $18,$24,L.1015
+la $23,79
+beq $30,$0,L.1017
+la $4,L.687
+move $5,$23
+jal printf
+L.1017:
+L.1015:
+la $18,5
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+addu $18,$18,$24
+la $24,7
+beq $18,$24,L.1019
+la $23,80
+beq $30,$0,L.1021
+la $4,L.687
+move $5,$23
+jal printf
+L.1021:
+L.1019:
+la $18,5
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+addu $18,$18,$24
+la $24,7
+beq $18,$24,L.1023
+la $23,81
+beq $30,$0,L.1025
+la $4,L.687
+move $5,$23
+jal printf
+L.1025:
+L.1023:
+la $18,5
+la $24,2
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+addu $18,$18,$24
+la $24,7
+beq $18,$24,L.1027
+la $23,82
+beq $30,$0,L.1029
+la $4,L.687
+move $5,$23
+jal printf
+L.1029:
+L.1027:
+la $18,5
+l.s $f26,L.529
+l.d $f18,L.596
+srl $24,$18,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+mul.d $f18,$f18,$f16
+and $24,$18,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+add.d $f18,$f18,$f16
+cvt.s.d $f18,$f18
+add.s $f18,$f18,$f26
+l.s $f16,L.828
+c.lt.s $f18,$f16; bc1t L.1032
+sub.s $f16,$f18,$f16
+trunc.w.s $f2,$f16,$24; mfc1 $24,$f2
+la $24,0x80000000($24)
+sw $24,-36+160($sp)
+b L.1033
+L.1032:
+trunc.w.s $f2,$f18,$24; mfc1 $24,$f2
+sw $24,-36+160($sp)
+L.1033:
+lw $18,-36+160($sp)
+la $24,7
+beq $18,$24,L.1034
+la $23,83
+beq $30,$0,L.1036
+la $4,L.687
+move $5,$23
+jal printf
+L.1036:
+L.1034:
+la $18,5
+l.d $f24,L.416
+l.d $f18,L.596
+srl $24,$18,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+mul.d $f18,$f18,$f16
+and $24,$18,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+add.d $f18,$f18,$f16
+add.d $f18,$f18,$f24
+l.d $f16,L.836
+c.lt.d $f18,$f16; bc1t L.1039
+sub.d $f16,$f18,$f16
+trunc.w.d $f2,$f16,$24; mfc1 $24,$f2
+la $24,0x80000000($24)
+sw $24,-40+160($sp)
+b L.1040
+L.1039:
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+sw $24,-40+160($sp)
+L.1040:
+lw $18,-40+160($sp)
+la $24,7
+beq $18,$24,L.1041
+la $23,84
+beq $30,$0,L.1043
+la $4,L.687
+move $5,$23
+jal printf
+L.1043:
+L.1041:
+l.s $f30,L.841
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+add.s $f30,$f30,$f18
+l.s $f18,L.1047
+c.eq.s $f30,$f18; bc1t L.1045
+la $23,85
+beq $30,$0,L.1048
+la $4,L.687
+move $5,$23
+jal printf
+L.1048:
+L.1045:
+l.s $f30,L.841
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+add.s $f30,$f30,$f18
+l.s $f18,L.1047
+c.eq.s $f30,$f18; bc1t L.1050
+la $23,86
+beq $30,$0,L.1052
+la $4,L.687
+move $5,$23
+jal printf
+L.1052:
+L.1050:
+l.s $f30,L.841
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+add.s $f30,$f30,$f18
+l.s $f18,L.1047
+c.eq.s $f30,$f18; bc1t L.1054
+la $23,87
+beq $30,$0,L.1056
+la $4,L.687
+move $5,$23
+jal printf
+L.1056:
+L.1054:
+l.s $f30,L.841
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+add.s $f30,$f30,$f18
+l.s $f18,L.1047
+c.eq.s $f30,$f18; bc1t L.1058
+la $23,88
+beq $30,$0,L.1060
+la $4,L.687
+move $5,$23
+jal printf
+L.1060:
+L.1058:
+l.s $f30,L.841
+la $24,2
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+l.d $f18,L.596
+srl $15,$24,1
+mtc1 $15,$f16; cvt.d.w $f16,$f16
+mul.d $f18,$f18,$f16
+and $24,$24,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+add.d $f18,$f18,$f16
+cvt.s.d $f18,$f18
+add.s $f30,$f30,$f18
+l.s $f18,L.1047
+c.eq.s $f30,$f18; bc1t L.1062
+la $23,89
+beq $30,$0,L.1064
+la $4,L.687
+move $5,$23
+jal printf
+L.1064:
+L.1062:
+l.s $f30,L.841
+l.s $f26,L.529
+add.s $f30,$f30,$f26
+l.s $f18,L.1047
+c.eq.s $f30,$f18; bc1t L.1066
+la $23,90
+beq $30,$0,L.1068
+la $4,L.687
+move $5,$23
+jal printf
+L.1068:
+L.1066:
+l.s $f30,L.841
+l.d $f24,L.416
+cvt.d.s $f18,$f30
+add.d $f18,$f18,$f24
+cvt.s.d $f30,$f18
+l.s $f18,L.1047
+c.eq.s $f30,$f18; bc1t L.1070
+la $23,91
+beq $30,$0,L.1072
+la $4,L.687
+move $5,$23
+jal printf
+L.1072:
+L.1070:
+l.d $f28,L.870
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+add.d $f28,$f28,$f18
+l.d $f18,L.1076
+c.eq.d $f28,$f18; bc1t L.1074
+la $23,92
+beq $30,$0,L.1077
+la $4,L.687
+move $5,$23
+jal printf
+L.1077:
+L.1074:
+l.d $f28,L.870
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+add.d $f28,$f28,$f18
+l.d $f18,L.1076
+c.eq.d $f28,$f18; bc1t L.1079
+la $23,93
+beq $30,$0,L.1081
+la $4,L.687
+move $5,$23
+jal printf
+L.1081:
+L.1079:
+l.d $f28,L.870
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+add.d $f28,$f28,$f18
+l.d $f18,L.1076
+c.eq.d $f28,$f18; bc1t L.1083
+la $23,94
+beq $30,$0,L.1085
+la $4,L.687
+move $5,$23
+jal printf
+L.1085:
+L.1083:
+l.d $f28,L.870
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+add.d $f28,$f28,$f18
+l.d $f18,L.1076
+c.eq.d $f28,$f18; bc1t L.1087
+la $23,95
+beq $30,$0,L.1089
+la $4,L.687
+move $5,$23
+jal printf
+L.1089:
+L.1087:
+l.d $f28,L.870
+la $24,2
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+l.d $f18,L.596
+srl $15,$24,1
+mtc1 $15,$f16; cvt.d.w $f16,$f16
+mul.d $f18,$f18,$f16
+and $24,$24,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+add.d $f18,$f18,$f16
+add.d $f28,$f28,$f18
+l.d $f18,L.1076
+c.eq.d $f28,$f18; bc1t L.1091
+la $23,96
+beq $30,$0,L.1093
+la $4,L.687
+move $5,$23
+jal printf
+L.1093:
+L.1091:
+l.d $f28,L.870
+l.s $f26,L.529
+cvt.d.s $f18,$f26
+add.d $f28,$f28,$f18
+l.d $f18,L.1076
+c.eq.d $f28,$f18; bc1t L.1095
+la $23,97
+beq $30,$0,L.1097
+la $4,L.687
+move $5,$23
+jal printf
+L.1097:
+L.1095:
+l.d $f28,L.870
+l.d $f24,L.416
+add.d $f28,$f28,$f24
+l.d $f18,L.1076
+c.eq.d $f28,$f18; bc1t L.1099
+la $23,98
+beq $30,$0,L.1101
+la $4,L.687
+move $5,$23
+jal printf
+L.1101:
+L.1099:
+la $22,5
+la $17,2
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+sll $15,$17,8*(4-1); sra $15,$15,8*(4-1)
+subu $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,3
+beq $24,$15,L.1103
+la $23,99
+beq $30,$0,L.1105
+la $4,L.687
+move $5,$23
+jal printf
+L.1105:
+L.1103:
+la $22,5
+la $16,2
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+sll $15,$16,8*(4-2); sra $15,$15,8*(4-2)
+subu $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,3
+beq $24,$15,L.1107
+la $23,100
+beq $30,$0,L.1109
+la $4,L.687
+move $5,$23
+jal printf
+L.1109:
+L.1107:
+la $22,5
+la $24,2
+sw $24,-4+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-4+160($sp)
+subu $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,3
+beq $24,$15,L.1111
+la $23,101
+beq $30,$0,L.1113
+la $4,L.687
+move $5,$23
+jal printf
+L.1113:
+L.1111:
+la $22,5
+la $24,2
+sw $24,-8+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-8+160($sp)
+subu $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,3
+beq $24,$15,L.1115
+la $23,102
+beq $30,$0,L.1117
+la $4,L.687
+move $5,$23
+jal printf
+L.1117:
+L.1115:
+la $22,5
+la $24,2
+sw $24,-12+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-12+160($sp)
+subu $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,3
+beq $24,$15,L.1119
+la $23,103
+beq $30,$0,L.1121
+la $4,L.687
+move $5,$23
+jal printf
+L.1121:
+L.1119:
+la $22,5
+l.s $f26,L.529
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+sub.s $f18,$f18,$f26
+trunc.w.s $f2,$f18,$24; mfc1 $24,$f2
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,3
+beq $24,$15,L.1123
+la $23,104
+beq $30,$0,L.1125
+la $4,L.687
+move $5,$23
+jal printf
+L.1125:
+L.1123:
+la $22,5
+l.d $f24,L.416
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+sub.d $f18,$f18,$f24
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,3
+beq $24,$15,L.1127
+la $23,105
+beq $30,$0,L.1129
+la $4,L.687
+move $5,$23
+jal printf
+L.1129:
+L.1127:
+la $21,5
+la $17,2
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $15,$17,8*(4-1); sra $15,$15,8*(4-1)
+subu $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,3
+beq $24,$15,L.1131
+la $23,106
+beq $30,$0,L.1133
+la $4,L.687
+move $5,$23
+jal printf
+L.1133:
+L.1131:
+la $21,5
+la $16,2
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $15,$16,8*(4-2); sra $15,$15,8*(4-2)
+subu $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,3
+beq $24,$15,L.1135
+la $23,107
+beq $30,$0,L.1137
+la $4,L.687
+move $5,$23
+jal printf
+L.1137:
+L.1135:
+la $21,5
+la $24,2
+sw $24,-4+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-4+160($sp)
+subu $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,3
+beq $24,$15,L.1139
+la $23,108
+beq $30,$0,L.1141
+la $4,L.687
+move $5,$23
+jal printf
+L.1141:
+L.1139:
+la $21,5
+la $24,2
+sw $24,-8+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-8+160($sp)
+subu $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,3
+beq $24,$15,L.1143
+la $23,109
+beq $30,$0,L.1145
+la $4,L.687
+move $5,$23
+jal printf
+L.1145:
+L.1143:
+la $21,5
+la $24,2
+sw $24,-12+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-12+160($sp)
+subu $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,3
+beq $24,$15,L.1147
+la $23,110
+beq $30,$0,L.1149
+la $4,L.687
+move $5,$23
+jal printf
+L.1149:
+L.1147:
+la $21,5
+l.s $f26,L.529
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+sub.s $f18,$f18,$f26
+trunc.w.s $f2,$f18,$24; mfc1 $24,$f2
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,3
+beq $24,$15,L.1151
+la $23,111
+beq $30,$0,L.1153
+la $4,L.687
+move $5,$23
+jal printf
+L.1153:
+L.1151:
+la $21,5
+l.d $f24,L.416
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+sub.d $f18,$f18,$f24
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,3
+beq $24,$15,L.1155
+la $23,112
+beq $30,$0,L.1157
+la $4,L.687
+move $5,$23
+jal printf
+L.1157:
+L.1155:
+la $20,5
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+subu $20,$20,$24
+la $24,3
+beq $20,$24,L.1159
+la $23,113
+beq $30,$0,L.1161
+la $4,L.687
+move $5,$23
+jal printf
+L.1161:
+L.1159:
+la $20,5
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+subu $20,$20,$24
+la $24,3
+beq $20,$24,L.1163
+la $23,114
+beq $30,$0,L.1165
+la $4,L.687
+move $5,$23
+jal printf
+L.1165:
+L.1163:
+la $20,5
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+subu $20,$20,$24
+la $24,3
+beq $20,$24,L.1167
+la $23,115
+beq $30,$0,L.1169
+la $4,L.687
+move $5,$23
+jal printf
+L.1169:
+L.1167:
+la $20,5
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+subu $20,$20,$24
+la $24,3
+beq $20,$24,L.1171
+la $23,116
+beq $30,$0,L.1173
+la $4,L.687
+move $5,$23
+jal printf
+L.1173:
+L.1171:
+la $20,5
+la $24,2
+sw $24,-12+160($sp)
+move $24,$20
+lw $15,-12+160($sp)
+subu $24,$24,$15
+move $20,$24
+la $24,3
+beq $20,$24,L.1175
+la $23,117
+beq $30,$0,L.1177
+la $4,L.687
+move $5,$23
+jal printf
+L.1177:
+L.1175:
+la $20,5
+l.s $f26,L.529
+mtc1 $20,$f18; cvt.s.w $f18,$f18
+sub.s $f18,$f18,$f26
+trunc.w.s $f2,$f18,$20; mfc1 $20,$f2
+la $24,3
+beq $20,$24,L.1179
+la $23,118
+beq $30,$0,L.1181
+la $4,L.687
+move $5,$23
+jal printf
+L.1181:
+L.1179:
+la $20,5
+l.d $f24,L.416
+mtc1 $20,$f18; cvt.d.w $f18,$f18
+sub.d $f18,$f18,$f24
+trunc.w.d $f2,$f18,$20; mfc1 $20,$f2
+la $24,3
+beq $20,$24,L.1183
+la $23,119
+beq $30,$0,L.1185
+la $4,L.687
+move $5,$23
+jal printf
+L.1185:
+L.1183:
+la $19,5
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+subu $19,$19,$24
+la $24,3
+beq $19,$24,L.1187
+la $23,120
+beq $30,$0,L.1189
+la $4,L.687
+move $5,$23
+jal printf
+L.1189:
+L.1187:
+la $19,5
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+subu $19,$19,$24
+la $24,3
+beq $19,$24,L.1191
+la $23,121
+beq $30,$0,L.1193
+la $4,L.687
+move $5,$23
+jal printf
+L.1193:
+L.1191:
+la $19,5
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+subu $19,$19,$24
+la $24,3
+beq $19,$24,L.1195
+la $23,122
+beq $30,$0,L.1197
+la $4,L.687
+move $5,$23
+jal printf
+L.1197:
+L.1195:
+la $19,5
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+subu $19,$19,$24
+la $24,3
+beq $19,$24,L.1199
+la $23,123
+beq $30,$0,L.1201
+la $4,L.687
+move $5,$23
+jal printf
+L.1201:
+L.1199:
+la $19,5
+la $24,2
+sw $24,-12+160($sp)
+move $24,$19
+lw $15,-12+160($sp)
+subu $24,$24,$15
+move $19,$24
+la $24,3
+beq $19,$24,L.1203
+la $23,124
+beq $30,$0,L.1205
+la $4,L.687
+move $5,$23
+jal printf
+L.1205:
+L.1203:
+la $19,5
+l.s $f26,L.529
+mtc1 $19,$f18; cvt.s.w $f18,$f18
+sub.s $f18,$f18,$f26
+trunc.w.s $f2,$f18,$19; mfc1 $19,$f2
+la $24,3
+beq $19,$24,L.1207
+la $23,125
+beq $30,$0,L.1209
+la $4,L.687
+move $5,$23
+jal printf
+L.1209:
+L.1207:
+la $19,5
+l.d $f24,L.416
+mtc1 $19,$f18; cvt.d.w $f18,$f18
+sub.d $f18,$f18,$f24
+trunc.w.d $f2,$f18,$19; mfc1 $19,$f2
+la $24,3
+beq $19,$24,L.1211
+la $23,126
+beq $30,$0,L.1213
+la $4,L.687
+move $5,$23
+jal printf
+L.1213:
+L.1211:
+la $18,5
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+subu $18,$18,$24
+la $24,3
+beq $18,$24,L.1215
+la $23,127
+beq $30,$0,L.1217
+la $4,L.687
+move $5,$23
+jal printf
+L.1217:
+L.1215:
+la $18,5
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+subu $18,$18,$24
+la $24,3
+beq $18,$24,L.1219
+la $23,128
+beq $30,$0,L.1221
+la $4,L.687
+move $5,$23
+jal printf
+L.1221:
+L.1219:
+la $18,5
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+subu $18,$18,$24
+la $24,3
+beq $18,$24,L.1223
+la $23,129
+beq $30,$0,L.1225
+la $4,L.687
+move $5,$23
+jal printf
+L.1225:
+L.1223:
+la $18,5
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+subu $18,$18,$24
+la $24,3
+beq $18,$24,L.1227
+la $23,130
+beq $30,$0,L.1229
+la $4,L.687
+move $5,$23
+jal printf
+L.1229:
+L.1227:
+la $18,5
+la $24,2
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+subu $18,$18,$24
+la $24,3
+beq $18,$24,L.1231
+la $23,131
+beq $30,$0,L.1233
+la $4,L.687
+move $5,$23
+jal printf
+L.1233:
+L.1231:
+la $18,5
+l.s $f26,L.529
+l.d $f18,L.596
+srl $24,$18,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+mul.d $f18,$f18,$f16
+and $24,$18,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+add.d $f18,$f18,$f16
+cvt.s.d $f18,$f18
+sub.s $f18,$f18,$f26
+l.s $f16,L.828
+c.lt.s $f18,$f16; bc1t L.1236
+sub.s $f16,$f18,$f16
+trunc.w.s $f2,$f16,$24; mfc1 $24,$f2
+la $24,0x80000000($24)
+sw $24,-44+160($sp)
+b L.1237
+L.1236:
+trunc.w.s $f2,$f18,$24; mfc1 $24,$f2
+sw $24,-44+160($sp)
+L.1237:
+lw $18,-44+160($sp)
+la $24,3
+beq $18,$24,L.1238
+la $23,132
+beq $30,$0,L.1240
+la $4,L.687
+move $5,$23
+jal printf
+L.1240:
+L.1238:
+la $18,5
+l.d $f24,L.416
+l.d $f18,L.596
+srl $24,$18,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+mul.d $f18,$f18,$f16
+and $24,$18,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+add.d $f18,$f18,$f16
+sub.d $f18,$f18,$f24
+l.d $f16,L.836
+c.lt.d $f18,$f16; bc1t L.1243
+sub.d $f16,$f18,$f16
+trunc.w.d $f2,$f16,$24; mfc1 $24,$f2
+la $24,0x80000000($24)
+sw $24,-48+160($sp)
+b L.1244
+L.1243:
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+sw $24,-48+160($sp)
+L.1244:
+lw $18,-48+160($sp)
+la $24,3
+beq $18,$24,L.1245
+la $23,133
+beq $30,$0,L.1247
+la $4,L.687
+move $5,$23
+jal printf
+L.1247:
+L.1245:
+l.s $f30,L.841
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+sub.s $f30,$f30,$f18
+l.s $f18,L.1251
+c.eq.s $f30,$f18; bc1t L.1249
+la $23,134
+beq $30,$0,L.1252
+la $4,L.687
+move $5,$23
+jal printf
+L.1252:
+L.1249:
+l.s $f30,L.841
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+sub.s $f30,$f30,$f18
+l.s $f18,L.1251
+c.eq.s $f30,$f18; bc1t L.1254
+la $23,135
+beq $30,$0,L.1256
+la $4,L.687
+move $5,$23
+jal printf
+L.1256:
+L.1254:
+l.s $f30,L.841
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+sub.s $f30,$f30,$f18
+l.s $f18,L.1251
+c.eq.s $f30,$f18; bc1t L.1258
+la $23,136
+beq $30,$0,L.1260
+la $4,L.687
+move $5,$23
+jal printf
+L.1260:
+L.1258:
+l.s $f30,L.841
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+sub.s $f30,$f30,$f18
+l.s $f18,L.1251
+c.eq.s $f30,$f18; bc1t L.1262
+la $23,137
+beq $30,$0,L.1264
+la $4,L.687
+move $5,$23
+jal printf
+L.1264:
+L.1262:
+l.s $f30,L.841
+la $24,2
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+l.d $f18,L.596
+srl $15,$24,1
+mtc1 $15,$f16; cvt.d.w $f16,$f16
+mul.d $f18,$f18,$f16
+and $24,$24,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+add.d $f18,$f18,$f16
+cvt.s.d $f18,$f18
+sub.s $f30,$f30,$f18
+l.s $f18,L.1251
+c.eq.s $f30,$f18; bc1t L.1266
+la $23,138
+beq $30,$0,L.1268
+la $4,L.687
+move $5,$23
+jal printf
+L.1268:
+L.1266:
+l.s $f30,L.841
+l.s $f26,L.529
+sub.s $f30,$f30,$f26
+l.s $f18,L.1251
+c.eq.s $f30,$f18; bc1t L.1270
+la $23,139
+beq $30,$0,L.1272
+la $4,L.687
+move $5,$23
+jal printf
+L.1272:
+L.1270:
+l.s $f30,L.841
+l.d $f24,L.416
+cvt.d.s $f18,$f30
+sub.d $f18,$f18,$f24
+cvt.s.d $f30,$f18
+l.s $f18,L.1251
+c.eq.s $f30,$f18; bc1t L.1274
+la $23,140
+beq $30,$0,L.1276
+la $4,L.687
+move $5,$23
+jal printf
+L.1276:
+L.1274:
+l.d $f28,L.870
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+sub.d $f28,$f28,$f18
+l.d $f18,L.1280
+c.eq.d $f28,$f18; bc1t L.1278
+la $23,141
+beq $30,$0,L.1281
+la $4,L.687
+move $5,$23
+jal printf
+L.1281:
+L.1278:
+l.d $f28,L.870
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+sub.d $f28,$f28,$f18
+l.d $f18,L.1280
+c.eq.d $f28,$f18; bc1t L.1283
+la $23,142
+beq $30,$0,L.1285
+la $4,L.687
+move $5,$23
+jal printf
+L.1285:
+L.1283:
+l.d $f28,L.870
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+sub.d $f28,$f28,$f18
+l.d $f18,L.1280
+c.eq.d $f28,$f18; bc1t L.1287
+la $23,143
+beq $30,$0,L.1289
+la $4,L.687
+move $5,$23
+jal printf
+L.1289:
+L.1287:
+l.d $f28,L.870
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+sub.d $f28,$f28,$f18
+l.d $f18,L.1280
+c.eq.d $f28,$f18; bc1t L.1291
+la $23,144
+beq $30,$0,L.1293
+la $4,L.687
+move $5,$23
+jal printf
+L.1293:
+L.1291:
+l.d $f28,L.870
+la $24,2
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+l.d $f18,L.596
+srl $15,$24,1
+mtc1 $15,$f16; cvt.d.w $f16,$f16
+mul.d $f18,$f18,$f16
+and $24,$24,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+add.d $f18,$f18,$f16
+sub.d $f28,$f28,$f18
+l.d $f18,L.1280
+c.eq.d $f28,$f18; bc1t L.1295
+la $23,145
+beq $30,$0,L.1297
+la $4,L.687
+move $5,$23
+jal printf
+L.1297:
+L.1295:
+l.d $f28,L.870
+l.s $f26,L.529
+cvt.d.s $f18,$f26
+sub.d $f28,$f28,$f18
+l.d $f18,L.1280
+c.eq.d $f28,$f18; bc1t L.1299
+la $23,146
+beq $30,$0,L.1301
+la $4,L.687
+move $5,$23
+jal printf
+L.1301:
+L.1299:
+l.d $f28,L.870
+l.d $f24,L.416
+sub.d $f28,$f28,$f24
+l.d $f18,L.1280
+c.eq.d $f28,$f18; bc1t L.1303
+la $23,147
+beq $30,$0,L.1305
+la $4,L.687
+move $5,$23
+jal printf
+L.1305:
+L.1303:
+la $22,5
+la $17,2
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+sll $15,$17,8*(4-1); sra $15,$15,8*(4-1)
+mul $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,10
+beq $24,$15,L.1307
+la $23,148
+beq $30,$0,L.1309
+la $4,L.687
+move $5,$23
+jal printf
+L.1309:
+L.1307:
+la $22,5
+la $16,2
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+sll $15,$16,8*(4-2); sra $15,$15,8*(4-2)
+mul $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,10
+beq $24,$15,L.1311
+la $23,149
+beq $30,$0,L.1313
+la $4,L.687
+move $5,$23
+jal printf
+L.1313:
+L.1311:
+la $22,5
+la $24,2
+sw $24,-4+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-4+160($sp)
+mul $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,10
+beq $24,$15,L.1315
+la $23,150
+beq $30,$0,L.1317
+la $4,L.687
+move $5,$23
+jal printf
+L.1317:
+L.1315:
+la $22,5
+la $24,2
+sw $24,-8+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-8+160($sp)
+mul $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,10
+beq $24,$15,L.1319
+la $23,151
+beq $30,$0,L.1321
+la $4,L.687
+move $5,$23
+jal printf
+L.1321:
+L.1319:
+la $22,5
+la $24,2
+sw $24,-12+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-12+160($sp)
+mul $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,10
+beq $24,$15,L.1323
+la $23,152
+beq $30,$0,L.1325
+la $4,L.687
+move $5,$23
+jal printf
+L.1325:
+L.1323:
+la $22,5
+l.s $f26,L.529
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+mul.s $f18,$f18,$f26
+trunc.w.s $f2,$f18,$24; mfc1 $24,$f2
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,10
+beq $24,$15,L.1327
+la $23,153
+beq $30,$0,L.1329
+la $4,L.687
+move $5,$23
+jal printf
+L.1329:
+L.1327:
+la $22,5
+l.d $f24,L.416
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+mul.d $f18,$f18,$f24
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,10
+beq $24,$15,L.1331
+la $23,154
+beq $30,$0,L.1333
+la $4,L.687
+move $5,$23
+jal printf
+L.1333:
+L.1331:
+la $21,5
+la $17,2
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $15,$17,8*(4-1); sra $15,$15,8*(4-1)
+mul $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,10
+beq $24,$15,L.1335
+la $23,155
+beq $30,$0,L.1337
+la $4,L.687
+move $5,$23
+jal printf
+L.1337:
+L.1335:
+la $21,5
+la $16,2
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $15,$16,8*(4-2); sra $15,$15,8*(4-2)
+mul $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,10
+beq $24,$15,L.1339
+la $23,156
+beq $30,$0,L.1341
+la $4,L.687
+move $5,$23
+jal printf
+L.1341:
+L.1339:
+la $21,5
+la $24,2
+sw $24,-4+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-4+160($sp)
+mul $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,10
+beq $24,$15,L.1343
+la $23,157
+beq $30,$0,L.1345
+la $4,L.687
+move $5,$23
+jal printf
+L.1345:
+L.1343:
+la $21,5
+la $24,2
+sw $24,-8+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-8+160($sp)
+mul $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,10
+beq $24,$15,L.1347
+la $23,158
+beq $30,$0,L.1349
+la $4,L.687
+move $5,$23
+jal printf
+L.1349:
+L.1347:
+la $21,5
+la $24,2
+sw $24,-12+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-12+160($sp)
+mul $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,10
+beq $24,$15,L.1351
+la $23,159
+beq $30,$0,L.1353
+la $4,L.687
+move $5,$23
+jal printf
+L.1353:
+L.1351:
+la $21,5
+l.s $f26,L.529
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+mul.s $f18,$f18,$f26
+trunc.w.s $f2,$f18,$24; mfc1 $24,$f2
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,10
+beq $24,$15,L.1355
+la $23,160
+beq $30,$0,L.1357
+la $4,L.687
+move $5,$23
+jal printf
+L.1357:
+L.1355:
+la $21,5
+l.d $f24,L.416
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+mul.d $f18,$f18,$f24
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,10
+beq $24,$15,L.1359
+la $23,161
+beq $30,$0,L.1361
+la $4,L.687
+move $5,$23
+jal printf
+L.1361:
+L.1359:
+la $20,5
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+mul $20,$20,$24
+la $24,10
+beq $20,$24,L.1363
+la $23,162
+beq $30,$0,L.1365
+la $4,L.687
+move $5,$23
+jal printf
+L.1365:
+L.1363:
+la $20,5
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+mul $20,$20,$24
+la $24,10
+beq $20,$24,L.1367
+la $23,163
+beq $30,$0,L.1369
+la $4,L.687
+move $5,$23
+jal printf
+L.1369:
+L.1367:
+la $20,5
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+mul $20,$20,$24
+la $24,10
+beq $20,$24,L.1371
+la $23,164
+beq $30,$0,L.1373
+la $4,L.687
+move $5,$23
+jal printf
+L.1373:
+L.1371:
+la $20,5
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+mul $20,$20,$24
+la $24,10
+beq $20,$24,L.1375
+la $23,165
+beq $30,$0,L.1377
+la $4,L.687
+move $5,$23
+jal printf
+L.1377:
+L.1375:
+la $20,5
+la $24,2
+sw $24,-12+160($sp)
+move $24,$20
+lw $15,-12+160($sp)
+mul $24,$24,$15
+move $20,$24
+la $24,10
+beq $20,$24,L.1379
+la $23,166
+beq $30,$0,L.1381
+la $4,L.687
+move $5,$23
+jal printf
+L.1381:
+L.1379:
+la $20,5
+l.s $f26,L.529
+mtc1 $20,$f18; cvt.s.w $f18,$f18
+mul.s $f18,$f18,$f26
+trunc.w.s $f2,$f18,$20; mfc1 $20,$f2
+la $24,10
+beq $20,$24,L.1383
+la $23,167
+beq $30,$0,L.1385
+la $4,L.687
+move $5,$23
+jal printf
+L.1385:
+L.1383:
+la $20,5
+l.d $f24,L.416
+mtc1 $20,$f18; cvt.d.w $f18,$f18
+mul.d $f18,$f18,$f24
+trunc.w.d $f2,$f18,$20; mfc1 $20,$f2
+la $24,10
+beq $20,$24,L.1387
+la $23,168
+beq $30,$0,L.1389
+la $4,L.687
+move $5,$23
+jal printf
+L.1389:
+L.1387:
+la $19,5
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+mul $19,$19,$24
+la $24,10
+beq $19,$24,L.1391
+la $23,169
+beq $30,$0,L.1393
+la $4,L.687
+move $5,$23
+jal printf
+L.1393:
+L.1391:
+la $19,5
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+mul $19,$19,$24
+la $24,10
+beq $19,$24,L.1395
+la $23,170
+beq $30,$0,L.1397
+la $4,L.687
+move $5,$23
+jal printf
+L.1397:
+L.1395:
+la $19,5
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+mul $19,$19,$24
+la $24,10
+beq $19,$24,L.1399
+la $23,171
+beq $30,$0,L.1401
+la $4,L.687
+move $5,$23
+jal printf
+L.1401:
+L.1399:
+la $19,5
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+mul $19,$19,$24
+la $24,10
+beq $19,$24,L.1403
+la $23,172
+beq $30,$0,L.1405
+la $4,L.687
+move $5,$23
+jal printf
+L.1405:
+L.1403:
+la $19,5
+la $24,2
+sw $24,-12+160($sp)
+move $24,$19
+lw $15,-12+160($sp)
+mul $24,$24,$15
+move $19,$24
+la $24,10
+beq $19,$24,L.1407
+la $23,173
+beq $30,$0,L.1409
+la $4,L.687
+move $5,$23
+jal printf
+L.1409:
+L.1407:
+la $19,5
+l.s $f26,L.529
+mtc1 $19,$f18; cvt.s.w $f18,$f18
+mul.s $f18,$f18,$f26
+trunc.w.s $f2,$f18,$19; mfc1 $19,$f2
+la $24,10
+beq $19,$24,L.1411
+la $23,174
+beq $30,$0,L.1413
+la $4,L.687
+move $5,$23
+jal printf
+L.1413:
+L.1411:
+la $19,5
+l.d $f24,L.416
+mtc1 $19,$f18; cvt.d.w $f18,$f18
+mul.d $f18,$f18,$f24
+trunc.w.d $f2,$f18,$19; mfc1 $19,$f2
+la $24,10
+beq $19,$24,L.1415
+la $23,175
+beq $30,$0,L.1417
+la $4,L.687
+move $5,$23
+jal printf
+L.1417:
+L.1415:
+la $18,5
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+mul $18,$18,$24
+la $24,10
+beq $18,$24,L.1419
+la $23,176
+beq $30,$0,L.1421
+la $4,L.687
+move $5,$23
+jal printf
+L.1421:
+L.1419:
+la $18,5
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+mul $18,$18,$24
+la $24,10
+beq $18,$24,L.1423
+la $23,177
+beq $30,$0,L.1425
+la $4,L.687
+move $5,$23
+jal printf
+L.1425:
+L.1423:
+la $18,5
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+mul $18,$18,$24
+la $24,10
+beq $18,$24,L.1427
+la $23,178
+beq $30,$0,L.1429
+la $4,L.687
+move $5,$23
+jal printf
+L.1429:
+L.1427:
+la $18,5
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+mul $18,$18,$24
+la $24,10
+beq $18,$24,L.1431
+la $23,179
+beq $30,$0,L.1433
+la $4,L.687
+move $5,$23
+jal printf
+L.1433:
+L.1431:
+la $18,5
+la $24,2
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+mul $18,$18,$24
+la $24,10
+beq $18,$24,L.1435
+la $23,180
+beq $30,$0,L.1437
+la $4,L.687
+move $5,$23
+jal printf
+L.1437:
+L.1435:
+la $18,5
+l.s $f26,L.529
+l.d $f18,L.596
+srl $24,$18,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+mul.d $f18,$f18,$f16
+and $24,$18,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+add.d $f18,$f18,$f16
+cvt.s.d $f18,$f18
+mul.s $f18,$f18,$f26
+l.s $f16,L.828
+c.lt.s $f18,$f16; bc1t L.1440
+sub.s $f16,$f18,$f16
+trunc.w.s $f2,$f16,$24; mfc1 $24,$f2
+la $24,0x80000000($24)
+sw $24,-52+160($sp)
+b L.1441
+L.1440:
+trunc.w.s $f2,$f18,$24; mfc1 $24,$f2
+sw $24,-52+160($sp)
+L.1441:
+lw $18,-52+160($sp)
+la $24,10
+beq $18,$24,L.1442
+la $23,181
+beq $30,$0,L.1444
+la $4,L.687
+move $5,$23
+jal printf
+L.1444:
+L.1442:
+la $18,5
+l.d $f24,L.416
+l.d $f18,L.596
+srl $24,$18,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+mul.d $f18,$f18,$f16
+and $24,$18,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+add.d $f18,$f18,$f16
+mul.d $f18,$f18,$f24
+l.d $f16,L.836
+c.lt.d $f18,$f16; bc1t L.1447
+sub.d $f16,$f18,$f16
+trunc.w.d $f2,$f16,$24; mfc1 $24,$f2
+la $24,0x80000000($24)
+sw $24,-56+160($sp)
+b L.1448
+L.1447:
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+sw $24,-56+160($sp)
+L.1448:
+lw $18,-56+160($sp)
+la $24,10
+beq $18,$24,L.1449
+la $23,182
+beq $30,$0,L.1451
+la $4,L.687
+move $5,$23
+jal printf
+L.1451:
+L.1449:
+l.s $f30,L.841
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+mul.s $f30,$f30,$f18
+l.s $f18,L.1455
+c.eq.s $f30,$f18; bc1t L.1453
+la $23,183
+beq $30,$0,L.1456
+la $4,L.687
+move $5,$23
+jal printf
+L.1456:
+L.1453:
+l.s $f30,L.841
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+mul.s $f30,$f30,$f18
+l.s $f18,L.1455
+c.eq.s $f30,$f18; bc1t L.1458
+la $23,184
+beq $30,$0,L.1460
+la $4,L.687
+move $5,$23
+jal printf
+L.1460:
+L.1458:
+l.s $f30,L.841
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+mul.s $f30,$f30,$f18
+l.s $f18,L.1455
+c.eq.s $f30,$f18; bc1t L.1462
+la $23,185
+beq $30,$0,L.1464
+la $4,L.687
+move $5,$23
+jal printf
+L.1464:
+L.1462:
+l.s $f30,L.841
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+mul.s $f30,$f30,$f18
+l.s $f18,L.1455
+c.eq.s $f30,$f18; bc1t L.1466
+la $23,186
+beq $30,$0,L.1468
+la $4,L.687
+move $5,$23
+jal printf
+L.1468:
+L.1466:
+l.s $f30,L.841
+la $24,2
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+l.d $f18,L.596
+srl $15,$24,1
+mtc1 $15,$f16; cvt.d.w $f16,$f16
+mul.d $f18,$f18,$f16
+and $24,$24,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+add.d $f18,$f18,$f16
+cvt.s.d $f18,$f18
+mul.s $f30,$f30,$f18
+l.s $f18,L.1455
+c.eq.s $f30,$f18; bc1t L.1470
+la $23,187
+beq $30,$0,L.1472
+la $4,L.687
+move $5,$23
+jal printf
+L.1472:
+L.1470:
+l.s $f30,L.841
+l.s $f26,L.529
+mul.s $f30,$f30,$f26
+l.s $f18,L.1455
+c.eq.s $f30,$f18; bc1t L.1474
+la $23,188
+beq $30,$0,L.1476
+la $4,L.687
+move $5,$23
+jal printf
+L.1476:
+L.1474:
+l.s $f30,L.841
+l.d $f24,L.416
+cvt.d.s $f18,$f30
+mul.d $f18,$f18,$f24
+cvt.s.d $f30,$f18
+l.s $f18,L.1455
+c.eq.s $f30,$f18; bc1t L.1478
+la $23,189
+beq $30,$0,L.1480
+la $4,L.687
+move $5,$23
+jal printf
+L.1480:
+L.1478:
+l.d $f28,L.870
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+mul.d $f28,$f28,$f18
+l.d $f18,L.1484
+c.eq.d $f28,$f18; bc1t L.1482
+la $23,190
+beq $30,$0,L.1485
+la $4,L.687
+move $5,$23
+jal printf
+L.1485:
+L.1482:
+l.d $f28,L.870
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+mul.d $f28,$f28,$f18
+l.d $f18,L.1484
+c.eq.d $f28,$f18; bc1t L.1487
+la $23,191
+beq $30,$0,L.1489
+la $4,L.687
+move $5,$23
+jal printf
+L.1489:
+L.1487:
+l.d $f28,L.870
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+mul.d $f28,$f28,$f18
+l.d $f18,L.1484
+c.eq.d $f28,$f18; bc1t L.1491
+la $23,192
+beq $30,$0,L.1493
+la $4,L.687
+move $5,$23
+jal printf
+L.1493:
+L.1491:
+l.d $f28,L.870
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+mul.d $f28,$f28,$f18
+l.d $f18,L.1484
+c.eq.d $f28,$f18; bc1t L.1495
+la $23,193
+beq $30,$0,L.1497
+la $4,L.687
+move $5,$23
+jal printf
+L.1497:
+L.1495:
+l.d $f28,L.870
+la $24,2
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+l.d $f18,L.596
+srl $15,$24,1
+mtc1 $15,$f16; cvt.d.w $f16,$f16
+mul.d $f18,$f18,$f16
+and $24,$24,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+add.d $f18,$f18,$f16
+mul.d $f28,$f28,$f18
+l.d $f18,L.1484
+c.eq.d $f28,$f18; bc1t L.1499
+la $23,194
+beq $30,$0,L.1501
+la $4,L.687
+move $5,$23
+jal printf
+L.1501:
+L.1499:
+l.d $f28,L.870
+l.s $f26,L.529
+cvt.d.s $f18,$f26
+mul.d $f28,$f28,$f18
+l.d $f18,L.1484
+c.eq.d $f28,$f18; bc1t L.1503
+la $23,195
+beq $30,$0,L.1505
+la $4,L.687
+move $5,$23
+jal printf
+L.1505:
+L.1503:
+l.d $f28,L.870
+l.d $f24,L.416
+mul.d $f28,$f28,$f24
+l.d $f18,L.1484
+c.eq.d $f28,$f18; bc1t L.1507
+la $23,196
+beq $30,$0,L.1509
+la $4,L.687
+move $5,$23
+jal printf
+L.1509:
+L.1507:
+la $22,5
+la $17,2
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+sll $15,$17,8*(4-1); sra $15,$15,8*(4-1)
+div $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,2
+beq $24,$15,L.1511
+la $23,197
+beq $30,$0,L.1513
+la $4,L.687
+move $5,$23
+jal printf
+L.1513:
+L.1511:
+la $22,5
+la $16,2
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+sll $15,$16,8*(4-2); sra $15,$15,8*(4-2)
+div $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,2
+beq $24,$15,L.1515
+la $23,198
+beq $30,$0,L.1517
+la $4,L.687
+move $5,$23
+jal printf
+L.1517:
+L.1515:
+la $22,5
+la $24,2
+sw $24,-4+160($sp)
+sll $15,$22,8*(4-1); sra $15,$15,8*(4-1)
+lw $14,-4+160($sp)
+div $15,$15,$14
+move $22,$15
+sll $15,$22,8*(4-1); sra $15,$15,8*(4-1)
+beq $15,$24,L.1519
+la $23,199
+beq $30,$0,L.1521
+la $4,L.687
+move $5,$23
+jal printf
+L.1521:
+L.1519:
+la $22,5
+la $24,2
+sw $24,-8+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-8+160($sp)
+div $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,2
+beq $24,$15,L.1523
+la $23,200
+beq $30,$0,L.1525
+la $4,L.687
+move $5,$23
+jal printf
+L.1525:
+L.1523:
+la $22,5
+la $24,2
+sw $24,-12+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-12+160($sp)
+divu $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,2
+beq $24,$15,L.1527
+la $23,201
+beq $30,$0,L.1529
+la $4,L.687
+move $5,$23
+jal printf
+L.1529:
+L.1527:
+la $22,5
+l.s $f26,L.529
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+div.s $f18,$f18,$f26
+trunc.w.s $f2,$f18,$24; mfc1 $24,$f2
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,2
+beq $24,$15,L.1531
+la $23,202
+beq $30,$0,L.1533
+la $4,L.687
+move $5,$23
+jal printf
+L.1533:
+L.1531:
+la $22,5
+l.d $f24,L.416
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+div.d $f18,$f18,$f24
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,2
+beq $24,$15,L.1535
+la $23,203
+beq $30,$0,L.1537
+la $4,L.687
+move $5,$23
+jal printf
+L.1537:
+L.1535:
+la $21,5
+la $17,2
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $15,$17,8*(4-1); sra $15,$15,8*(4-1)
+div $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,2
+beq $24,$15,L.1539
+la $23,204
+beq $30,$0,L.1541
+la $4,L.687
+move $5,$23
+jal printf
+L.1541:
+L.1539:
+la $21,5
+la $16,2
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $15,$16,8*(4-2); sra $15,$15,8*(4-2)
+div $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,2
+beq $24,$15,L.1543
+la $23,205
+beq $30,$0,L.1545
+la $4,L.687
+move $5,$23
+jal printf
+L.1545:
+L.1543:
+la $21,5
+la $24,2
+sw $24,-4+160($sp)
+sll $15,$21,8*(4-2); sra $15,$15,8*(4-2)
+lw $14,-4+160($sp)
+div $15,$15,$14
+move $21,$15
+sll $15,$21,8*(4-2); sra $15,$15,8*(4-2)
+beq $15,$24,L.1547
+la $23,206
+beq $30,$0,L.1549
+la $4,L.687
+move $5,$23
+jal printf
+L.1549:
+L.1547:
+la $21,5
+la $24,2
+sw $24,-8+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-8+160($sp)
+div $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,2
+beq $24,$15,L.1551
+la $23,207
+beq $30,$0,L.1553
+la $4,L.687
+move $5,$23
+jal printf
+L.1553:
+L.1551:
+la $21,5
+la $24,2
+sw $24,-12+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-12+160($sp)
+divu $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,2
+beq $24,$15,L.1555
+la $23,208
+beq $30,$0,L.1557
+la $4,L.687
+move $5,$23
+jal printf
+L.1557:
+L.1555:
+la $21,5
+l.s $f26,L.529
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+div.s $f18,$f18,$f26
+trunc.w.s $f2,$f18,$24; mfc1 $24,$f2
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,2
+beq $24,$15,L.1559
+la $23,209
+beq $30,$0,L.1561
+la $4,L.687
+move $5,$23
+jal printf
+L.1561:
+L.1559:
+la $21,5
+l.d $f24,L.416
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+div.d $f18,$f18,$f24
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,2
+beq $24,$15,L.1563
+la $23,210
+beq $30,$0,L.1565
+la $4,L.687
+move $5,$23
+jal printf
+L.1565:
+L.1563:
+la $20,5
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+div $20,$20,$24
+la $24,2
+beq $20,$24,L.1567
+la $23,211
+beq $30,$0,L.1569
+la $4,L.687
+move $5,$23
+jal printf
+L.1569:
+L.1567:
+la $20,5
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+div $20,$20,$24
+la $24,2
+beq $20,$24,L.1571
+la $23,212
+beq $30,$0,L.1573
+la $4,L.687
+move $5,$23
+jal printf
+L.1573:
+L.1571:
+la $20,5
+la $24,2
+sw $24,-4+160($sp)
+lw $15,-4+160($sp)
+div $20,$20,$15
+beq $20,$24,L.1575
+la $23,213
+beq $30,$0,L.1577
+la $4,L.687
+move $5,$23
+jal printf
+L.1577:
+L.1575:
+la $20,5
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+div $20,$20,$24
+la $24,2
+beq $20,$24,L.1579
+la $23,214
+beq $30,$0,L.1581
+la $4,L.687
+move $5,$23
+jal printf
+L.1581:
+L.1579:
+la $20,5
+la $24,2
+sw $24,-12+160($sp)
+move $24,$20
+lw $15,-12+160($sp)
+divu $24,$24,$15
+move $20,$24
+la $24,2
+beq $20,$24,L.1583
+la $23,215
+beq $30,$0,L.1585
+la $4,L.687
+move $5,$23
+jal printf
+L.1585:
+L.1583:
+la $20,5
+l.s $f26,L.529
+mtc1 $20,$f18; cvt.s.w $f18,$f18
+div.s $f18,$f18,$f26
+trunc.w.s $f2,$f18,$20; mfc1 $20,$f2
+la $24,2
+beq $20,$24,L.1587
+la $23,216
+beq $30,$0,L.1589
+la $4,L.687
+move $5,$23
+jal printf
+L.1589:
+L.1587:
+la $20,5
+l.d $f24,L.416
+mtc1 $20,$f18; cvt.d.w $f18,$f18
+div.d $f18,$f18,$f24
+trunc.w.d $f2,$f18,$20; mfc1 $20,$f2
+la $24,2
+beq $20,$24,L.1591
+la $23,217
+beq $30,$0,L.1593
+la $4,L.687
+move $5,$23
+jal printf
+L.1593:
+L.1591:
+la $19,5
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+div $19,$19,$24
+la $24,2
+beq $19,$24,L.1595
+la $23,218
+beq $30,$0,L.1597
+la $4,L.687
+move $5,$23
+jal printf
+L.1597:
+L.1595:
+la $19,5
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+div $19,$19,$24
+la $24,2
+beq $19,$24,L.1599
+la $23,219
+beq $30,$0,L.1601
+la $4,L.687
+move $5,$23
+jal printf
+L.1601:
+L.1599:
+la $19,5
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+div $19,$19,$24
+la $24,2
+beq $19,$24,L.1603
+la $23,220
+beq $30,$0,L.1605
+la $4,L.687
+move $5,$23
+jal printf
+L.1605:
+L.1603:
+la $19,5
+la $24,2
+sw $24,-8+160($sp)
+lw $15,-8+160($sp)
+div $19,$19,$15
+beq $19,$24,L.1607
+la $23,221
+beq $30,$0,L.1609
+la $4,L.687
+move $5,$23
+jal printf
+L.1609:
+L.1607:
+la $19,5
+la $24,2
+sw $24,-12+160($sp)
+move $24,$19
+lw $15,-12+160($sp)
+divu $24,$24,$15
+move $19,$24
+la $24,2
+beq $19,$24,L.1611
+la $23,222
+beq $30,$0,L.1613
+la $4,L.687
+move $5,$23
+jal printf
+L.1613:
+L.1611:
+la $19,5
+l.s $f26,L.529
+mtc1 $19,$f18; cvt.s.w $f18,$f18
+div.s $f18,$f18,$f26
+trunc.w.s $f2,$f18,$19; mfc1 $19,$f2
+la $24,2
+beq $19,$24,L.1615
+la $23,223
+beq $30,$0,L.1617
+la $4,L.687
+move $5,$23
+jal printf
+L.1617:
+L.1615:
+la $19,5
+l.d $f24,L.416
+mtc1 $19,$f18; cvt.d.w $f18,$f18
+div.d $f18,$f18,$f24
+trunc.w.d $f2,$f18,$19; mfc1 $19,$f2
+la $24,2
+beq $19,$24,L.1619
+la $23,224
+beq $30,$0,L.1621
+la $4,L.687
+move $5,$23
+jal printf
+L.1621:
+L.1619:
+la $18,5
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+divu $18,$18,$24
+la $24,2
+beq $18,$24,L.1623
+la $23,225
+beq $30,$0,L.1625
+la $4,L.687
+move $5,$23
+jal printf
+L.1625:
+L.1623:
+la $18,5
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+divu $18,$18,$24
+la $24,2
+beq $18,$24,L.1627
+la $23,226
+beq $30,$0,L.1629
+la $4,L.687
+move $5,$23
+jal printf
+L.1629:
+L.1627:
+la $18,5
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+divu $18,$18,$24
+la $24,2
+beq $18,$24,L.1631
+la $23,227
+beq $30,$0,L.1633
+la $4,L.687
+move $5,$23
+jal printf
+L.1633:
+L.1631:
+la $18,5
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+divu $18,$18,$24
+la $24,2
+beq $18,$24,L.1635
+la $23,228
+beq $30,$0,L.1637
+la $4,L.687
+move $5,$23
+jal printf
+L.1637:
+L.1635:
+la $18,5
+la $24,2
+sw $24,-12+160($sp)
+lw $15,-12+160($sp)
+divu $18,$18,$15
+beq $18,$24,L.1639
+la $23,229
+beq $30,$0,L.1641
+la $4,L.687
+move $5,$23
+jal printf
+L.1641:
+L.1639:
+la $18,5
+l.s $f26,L.529
+l.d $f18,L.596
+srl $24,$18,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+mul.d $f18,$f18,$f16
+and $24,$18,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+add.d $f18,$f18,$f16
+cvt.s.d $f18,$f18
+div.s $f18,$f18,$f26
+l.s $f16,L.828
+c.lt.s $f18,$f16; bc1t L.1644
+sub.s $f16,$f18,$f16
+trunc.w.s $f2,$f16,$24; mfc1 $24,$f2
+la $24,0x80000000($24)
+sw $24,-60+160($sp)
+b L.1645
+L.1644:
+trunc.w.s $f2,$f18,$24; mfc1 $24,$f2
+sw $24,-60+160($sp)
+L.1645:
+lw $18,-60+160($sp)
+la $24,2
+beq $18,$24,L.1646
+la $23,230
+beq $30,$0,L.1648
+la $4,L.687
+move $5,$23
+jal printf
+L.1648:
+L.1646:
+la $18,5
+l.d $f24,L.416
+l.d $f18,L.596
+srl $24,$18,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+mul.d $f18,$f18,$f16
+and $24,$18,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+add.d $f18,$f18,$f16
+div.d $f18,$f18,$f24
+l.d $f16,L.836
+c.lt.d $f18,$f16; bc1t L.1651
+sub.d $f16,$f18,$f16
+trunc.w.d $f2,$f16,$24; mfc1 $24,$f2
+la $24,0x80000000($24)
+sw $24,-64+160($sp)
+b L.1652
+L.1651:
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+sw $24,-64+160($sp)
+L.1652:
+lw $18,-64+160($sp)
+la $24,2
+beq $18,$24,L.1653
+la $23,231
+beq $30,$0,L.1655
+la $4,L.687
+move $5,$23
+jal printf
+L.1655:
+L.1653:
+l.s $f30,L.841
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+div.s $f30,$f30,$f18
+cvt.d.s $f18,$f30
+l.d $f16,L.1659
+c.eq.d $f18,$f16; bc1t L.1657
+la $23,232
+beq $30,$0,L.1660
+la $4,L.687
+move $5,$23
+jal printf
+L.1660:
+L.1657:
+l.s $f30,L.841
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+div.s $f30,$f30,$f18
+cvt.d.s $f18,$f30
+l.d $f16,L.1659
+c.eq.d $f18,$f16; bc1t L.1662
+la $23,233
+beq $30,$0,L.1664
+la $4,L.687
+move $5,$23
+jal printf
+L.1664:
+L.1662:
+l.s $f30,L.841
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+div.s $f30,$f30,$f18
+cvt.d.s $f18,$f30
+l.d $f16,L.1659
+c.eq.d $f18,$f16; bc1t L.1666
+la $23,234
+beq $30,$0,L.1668
+la $4,L.687
+move $5,$23
+jal printf
+L.1668:
+L.1666:
+l.s $f30,L.841
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+div.s $f30,$f30,$f18
+cvt.d.s $f18,$f30
+l.d $f16,L.1659
+c.eq.d $f18,$f16; bc1t L.1670
+la $23,235
+beq $30,$0,L.1672
+la $4,L.687
+move $5,$23
+jal printf
+L.1672:
+L.1670:
+l.s $f30,L.841
+la $24,2
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+l.d $f18,L.596
+srl $15,$24,1
+mtc1 $15,$f16; cvt.d.w $f16,$f16
+mul.d $f18,$f18,$f16
+and $24,$24,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+add.d $f18,$f18,$f16
+cvt.s.d $f18,$f18
+div.s $f30,$f30,$f18
+cvt.d.s $f18,$f30
+l.d $f16,L.1659
+c.eq.d $f18,$f16; bc1t L.1674
+la $23,236
+beq $30,$0,L.1676
+la $4,L.687
+move $5,$23
+jal printf
+L.1676:
+L.1674:
+l.s $f30,L.841
+l.s $f26,L.529
+div.s $f30,$f30,$f26
+cvt.d.s $f18,$f30
+l.d $f16,L.1659
+c.eq.d $f18,$f16; bc1t L.1678
+la $23,237
+beq $30,$0,L.1680
+la $4,L.687
+move $5,$23
+jal printf
+L.1680:
+L.1678:
+l.s $f30,L.841
+l.d $f24,L.416
+cvt.d.s $f18,$f30
+div.d $f18,$f18,$f24
+cvt.s.d $f30,$f18
+cvt.d.s $f18,$f30
+l.d $f16,L.1659
+c.eq.d $f18,$f16; bc1t L.1682
+la $23,238
+beq $30,$0,L.1684
+la $4,L.687
+move $5,$23
+jal printf
+L.1684:
+L.1682:
+l.d $f28,L.870
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+div.d $f28,$f28,$f18
+l.d $f18,L.1659
+c.eq.d $f28,$f18; bc1t L.1686
+la $23,239
+beq $30,$0,L.1688
+la $4,L.687
+move $5,$23
+jal printf
+L.1688:
+L.1686:
+l.d $f28,L.870
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+div.d $f28,$f28,$f18
+l.d $f18,L.1659
+c.eq.d $f28,$f18; bc1t L.1690
+la $23,240
+beq $30,$0,L.1692
+la $4,L.687
+move $5,$23
+jal printf
+L.1692:
+L.1690:
+l.d $f28,L.870
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+div.d $f28,$f28,$f18
+l.d $f18,L.1659
+c.eq.d $f28,$f18; bc1t L.1694
+la $23,241
+beq $30,$0,L.1696
+la $4,L.687
+move $5,$23
+jal printf
+L.1696:
+L.1694:
+l.d $f28,L.870
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+div.d $f28,$f28,$f18
+l.d $f18,L.1659
+c.eq.d $f28,$f18; bc1t L.1698
+la $23,242
+beq $30,$0,L.1700
+la $4,L.687
+move $5,$23
+jal printf
+L.1700:
+L.1698:
+l.d $f28,L.870
+la $24,2
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+l.d $f18,L.596
+srl $15,$24,1
+mtc1 $15,$f16; cvt.d.w $f16,$f16
+mul.d $f18,$f18,$f16
+and $24,$24,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+add.d $f18,$f18,$f16
+div.d $f28,$f28,$f18
+l.d $f18,L.1659
+c.eq.d $f28,$f18; bc1t L.1702
+la $23,243
+beq $30,$0,L.1704
+la $4,L.687
+move $5,$23
+jal printf
+L.1704:
+L.1702:
+l.d $f28,L.870
+l.s $f26,L.529
+cvt.d.s $f18,$f26
+div.d $f28,$f28,$f18
+l.d $f18,L.1659
+c.eq.d $f28,$f18; bc1t L.1706
+la $23,244
+beq $30,$0,L.1708
+la $4,L.687
+move $5,$23
+jal printf
+L.1708:
+L.1706:
+l.d $f28,L.870
+l.d $f24,L.416
+div.d $f28,$f28,$f24
+l.d $f18,L.1659
+c.eq.d $f28,$f18; bc1t L.1710
+la $23,245
+beq $30,$0,L.1712
+la $4,L.687
+move $5,$23
+jal printf
+L.1712:
+L.1710:
+la $22,5
+la $17,2
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+sll $15,$17,8*(4-1); sra $15,$15,8*(4-1)
+rem $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,1
+beq $24,$15,L.1714
+la $23,246
+beq $30,$0,L.1716
+la $4,L.687
+move $5,$23
+jal printf
+L.1716:
+L.1714:
+la $22,5
+la $16,2
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+sll $15,$16,8*(4-2); sra $15,$15,8*(4-2)
+rem $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,1
+beq $24,$15,L.1718
+la $23,247
+beq $30,$0,L.1720
+la $4,L.687
+move $5,$23
+jal printf
+L.1720:
+L.1718:
+la $22,5
+la $24,2
+sw $24,-4+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-4+160($sp)
+rem $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,1
+beq $24,$15,L.1722
+la $23,248
+beq $30,$0,L.1724
+la $4,L.687
+move $5,$23
+jal printf
+L.1724:
+L.1722:
+la $22,5
+la $24,2
+sw $24,-8+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-8+160($sp)
+rem $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,1
+beq $24,$15,L.1726
+la $23,249
+beq $30,$0,L.1728
+la $4,L.687
+move $5,$23
+jal printf
+L.1728:
+L.1726:
+la $22,5
+la $24,2
+sw $24,-12+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-12+160($sp)
+remu $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,1
+beq $24,$15,L.1730
+la $23,250
+beq $30,$0,L.1732
+la $4,L.687
+move $5,$23
+jal printf
+L.1732:
+L.1730:
+la $21,5
+la $17,2
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $15,$17,8*(4-1); sra $15,$15,8*(4-1)
+rem $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,1
+beq $24,$15,L.1734
+la $23,251
+beq $30,$0,L.1736
+la $4,L.687
+move $5,$23
+jal printf
+L.1736:
+L.1734:
+la $21,5
+la $16,2
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $15,$16,8*(4-2); sra $15,$15,8*(4-2)
+rem $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,1
+beq $24,$15,L.1738
+la $23,252
+beq $30,$0,L.1740
+la $4,L.687
+move $5,$23
+jal printf
+L.1740:
+L.1738:
+la $21,5
+la $24,2
+sw $24,-4+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-4+160($sp)
+rem $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,1
+beq $24,$15,L.1742
+la $23,253
+beq $30,$0,L.1744
+la $4,L.687
+move $5,$23
+jal printf
+L.1744:
+L.1742:
+la $21,5
+la $24,2
+sw $24,-8+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-8+160($sp)
+rem $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,1
+beq $24,$15,L.1746
+la $23,254
+beq $30,$0,L.1748
+la $4,L.687
+move $5,$23
+jal printf
+L.1748:
+L.1746:
+la $21,5
+la $24,2
+sw $24,-12+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-12+160($sp)
+remu $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,1
+beq $24,$15,L.1750
+la $23,255
+beq $30,$0,L.1752
+la $4,L.687
+move $5,$23
+jal printf
+L.1752:
+L.1750:
+la $20,5
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+rem $20,$20,$24
+la $24,1
+beq $20,$24,L.1754
+la $23,256
+beq $30,$0,L.1756
+la $4,L.687
+move $5,$23
+jal printf
+L.1756:
+L.1754:
+la $20,5
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+rem $20,$20,$24
+la $24,1
+beq $20,$24,L.1758
+la $23,257
+beq $30,$0,L.1760
+la $4,L.687
+move $5,$23
+jal printf
+L.1760:
+L.1758:
+la $20,5
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+rem $20,$20,$24
+la $24,1
+beq $20,$24,L.1762
+la $23,258
+beq $30,$0,L.1764
+la $4,L.687
+move $5,$23
+jal printf
+L.1764:
+L.1762:
+la $20,5
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+rem $20,$20,$24
+la $24,1
+beq $20,$24,L.1766
+la $23,259
+beq $30,$0,L.1768
+la $4,L.687
+move $5,$23
+jal printf
+L.1768:
+L.1766:
+la $20,5
+la $24,2
+sw $24,-12+160($sp)
+move $24,$20
+lw $15,-12+160($sp)
+remu $24,$24,$15
+move $20,$24
+la $24,1
+beq $20,$24,L.1770
+la $23,260
+beq $30,$0,L.1772
+la $4,L.687
+move $5,$23
+jal printf
+L.1772:
+L.1770:
+la $19,5
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+rem $19,$19,$24
+la $24,1
+beq $19,$24,L.1774
+la $23,261
+beq $30,$0,L.1776
+la $4,L.687
+move $5,$23
+jal printf
+L.1776:
+L.1774:
+la $19,5
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+rem $19,$19,$24
+la $24,1
+beq $19,$24,L.1778
+la $23,262
+beq $30,$0,L.1780
+la $4,L.687
+move $5,$23
+jal printf
+L.1780:
+L.1778:
+la $19,5
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+rem $19,$19,$24
+la $24,1
+beq $19,$24,L.1782
+la $23,263
+beq $30,$0,L.1784
+la $4,L.687
+move $5,$23
+jal printf
+L.1784:
+L.1782:
+la $19,5
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+rem $19,$19,$24
+la $24,1
+beq $19,$24,L.1786
+la $23,264
+beq $30,$0,L.1788
+la $4,L.687
+move $5,$23
+jal printf
+L.1788:
+L.1786:
+la $19,5
+la $24,2
+sw $24,-12+160($sp)
+move $24,$19
+lw $15,-12+160($sp)
+remu $24,$24,$15
+move $19,$24
+la $24,1
+beq $19,$24,L.1790
+la $23,265
+beq $30,$0,L.1792
+la $4,L.687
+move $5,$23
+jal printf
+L.1792:
+L.1790:
+la $18,5
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+remu $18,$18,$24
+la $24,1
+beq $18,$24,L.1794
+la $23,266
+beq $30,$0,L.1796
+la $4,L.687
+move $5,$23
+jal printf
+L.1796:
+L.1794:
+la $18,5
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+remu $18,$18,$24
+la $24,1
+beq $18,$24,L.1798
+la $23,267
+beq $30,$0,L.1800
+la $4,L.687
+move $5,$23
+jal printf
+L.1800:
+L.1798:
+la $18,5
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+remu $18,$18,$24
+la $24,1
+beq $18,$24,L.1802
+la $23,268
+beq $30,$0,L.1804
+la $4,L.687
+move $5,$23
+jal printf
+L.1804:
+L.1802:
+la $18,5
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+remu $18,$18,$24
+la $24,1
+beq $18,$24,L.1806
+la $23,269
+beq $30,$0,L.1808
+la $4,L.687
+move $5,$23
+jal printf
+L.1808:
+L.1806:
+la $18,5
+la $24,2
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+remu $18,$18,$24
+la $24,1
+beq $18,$24,L.1810
+la $23,270
+beq $30,$0,L.1812
+la $4,L.687
+move $5,$23
+jal printf
+L.1812:
+L.1810:
+la $22,5
+la $17,2
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+sll $15,$17,8*(4-1); sra $15,$15,8*(4-1)
+sra $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,1
+beq $24,$15,L.1814
+la $23,271
+beq $30,$0,L.1816
+la $4,L.687
+move $5,$23
+jal printf
+L.1816:
+L.1814:
+la $22,5
+la $16,2
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+sll $15,$16,8*(4-2); sra $15,$15,8*(4-2)
+sra $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,1
+beq $24,$15,L.1818
+la $23,272
+beq $30,$0,L.1820
+la $4,L.687
+move $5,$23
+jal printf
+L.1820:
+L.1818:
+la $22,5
+la $24,2
+sw $24,-4+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-4+160($sp)
+sra $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,1
+beq $24,$15,L.1822
+la $23,273
+beq $30,$0,L.1824
+la $4,L.687
+move $5,$23
+jal printf
+L.1824:
+L.1822:
+la $22,5
+la $24,2
+sw $24,-8+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-8+160($sp)
+sra $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,1
+beq $24,$15,L.1826
+la $23,274
+beq $30,$0,L.1828
+la $4,L.687
+move $5,$23
+jal printf
+L.1828:
+L.1826:
+la $22,5
+la $24,2
+sw $24,-12+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-12+160($sp)
+sra $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,1
+beq $24,$15,L.1830
+la $23,275
+beq $30,$0,L.1832
+la $4,L.687
+move $5,$23
+jal printf
+L.1832:
+L.1830:
+la $21,5
+la $17,2
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $15,$17,8*(4-1); sra $15,$15,8*(4-1)
+sra $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,1
+beq $24,$15,L.1834
+la $23,276
+beq $30,$0,L.1836
+la $4,L.687
+move $5,$23
+jal printf
+L.1836:
+L.1834:
+la $21,5
+la $16,2
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $15,$16,8*(4-2); sra $15,$15,8*(4-2)
+sra $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,1
+beq $24,$15,L.1838
+la $23,277
+beq $30,$0,L.1840
+la $4,L.687
+move $5,$23
+jal printf
+L.1840:
+L.1838:
+la $21,5
+la $24,2
+sw $24,-4+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-4+160($sp)
+sra $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,1
+beq $24,$15,L.1842
+la $23,278
+beq $30,$0,L.1844
+la $4,L.687
+move $5,$23
+jal printf
+L.1844:
+L.1842:
+la $21,5
+la $24,2
+sw $24,-8+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-8+160($sp)
+sra $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,1
+beq $24,$15,L.1846
+la $23,279
+beq $30,$0,L.1848
+la $4,L.687
+move $5,$23
+jal printf
+L.1848:
+L.1846:
+la $21,5
+la $24,2
+sw $24,-12+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-12+160($sp)
+sra $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,1
+beq $24,$15,L.1850
+la $23,280
+beq $30,$0,L.1852
+la $4,L.687
+move $5,$23
+jal printf
+L.1852:
+L.1850:
+la $20,5
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+sra $20,$20,$24
+la $24,1
+beq $20,$24,L.1854
+la $23,281
+beq $30,$0,L.1856
+la $4,L.687
+move $5,$23
+jal printf
+L.1856:
+L.1854:
+la $20,5
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+sra $20,$20,$24
+la $24,1
+beq $20,$24,L.1858
+la $23,282
+beq $30,$0,L.1860
+la $4,L.687
+move $5,$23
+jal printf
+L.1860:
+L.1858:
+la $20,5
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+sra $20,$20,$24
+la $24,1
+beq $20,$24,L.1862
+la $23,283
+beq $30,$0,L.1864
+la $4,L.687
+move $5,$23
+jal printf
+L.1864:
+L.1862:
+la $20,5
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+sra $20,$20,$24
+la $24,1
+beq $20,$24,L.1866
+la $23,284
+beq $30,$0,L.1868
+la $4,L.687
+move $5,$23
+jal printf
+L.1868:
+L.1866:
+la $20,5
+la $24,2
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+sra $20,$20,$24
+la $24,1
+beq $20,$24,L.1870
+la $23,285
+beq $30,$0,L.1872
+la $4,L.687
+move $5,$23
+jal printf
+L.1872:
+L.1870:
+la $19,5
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+sra $19,$19,$24
+la $24,1
+beq $19,$24,L.1874
+la $23,286
+beq $30,$0,L.1876
+la $4,L.687
+move $5,$23
+jal printf
+L.1876:
+L.1874:
+la $19,5
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+sra $19,$19,$24
+la $24,1
+beq $19,$24,L.1878
+la $23,287
+beq $30,$0,L.1880
+la $4,L.687
+move $5,$23
+jal printf
+L.1880:
+L.1878:
+la $19,5
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+sra $19,$19,$24
+la $24,1
+beq $19,$24,L.1882
+la $23,288
+beq $30,$0,L.1884
+la $4,L.687
+move $5,$23
+jal printf
+L.1884:
+L.1882:
+la $19,5
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+sra $19,$19,$24
+la $24,1
+beq $19,$24,L.1886
+la $23,289
+beq $30,$0,L.1888
+la $4,L.687
+move $5,$23
+jal printf
+L.1888:
+L.1886:
+la $19,5
+la $24,2
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+sra $19,$19,$24
+la $24,1
+beq $19,$24,L.1890
+la $23,290
+beq $30,$0,L.1892
+la $4,L.687
+move $5,$23
+jal printf
+L.1892:
+L.1890:
+la $18,5
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+srl $18,$18,$24
+la $24,1
+beq $18,$24,L.1894
+la $23,291
+beq $30,$0,L.1896
+la $4,L.687
+move $5,$23
+jal printf
+L.1896:
+L.1894:
+la $18,5
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+srl $18,$18,$24
+la $24,1
+beq $18,$24,L.1898
+la $23,292
+beq $30,$0,L.1900
+la $4,L.687
+move $5,$23
+jal printf
+L.1900:
+L.1898:
+la $18,5
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+srl $18,$18,$24
+la $24,1
+beq $18,$24,L.1902
+la $23,293
+beq $30,$0,L.1904
+la $4,L.687
+move $5,$23
+jal printf
+L.1904:
+L.1902:
+la $18,5
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+srl $18,$18,$24
+la $24,1
+beq $18,$24,L.1906
+la $23,294
+beq $30,$0,L.1908
+la $4,L.687
+move $5,$23
+jal printf
+L.1908:
+L.1906:
+la $18,5
+la $24,2
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+srl $18,$18,$24
+la $24,1
+beq $18,$24,L.1910
+la $23,295
+beq $30,$0,L.1912
+la $4,L.687
+move $5,$23
+jal printf
+L.1912:
+L.1910:
+la $22,5
+la $17,2
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+sll $15,$17,8*(4-1); sra $15,$15,8*(4-1)
+sll $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,20
+beq $24,$15,L.1914
+la $23,296
+beq $30,$0,L.1916
+la $4,L.687
+move $5,$23
+jal printf
+L.1916:
+L.1914:
+la $22,5
+la $16,2
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+sll $15,$16,8*(4-2); sra $15,$15,8*(4-2)
+sll $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,20
+beq $24,$15,L.1918
+la $23,297
+beq $30,$0,L.1920
+la $4,L.687
+move $5,$23
+jal printf
+L.1920:
+L.1918:
+la $22,5
+la $24,2
+sw $24,-4+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-4+160($sp)
+sll $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,20
+beq $24,$15,L.1922
+la $23,298
+beq $30,$0,L.1924
+la $4,L.687
+move $5,$23
+jal printf
+L.1924:
+L.1922:
+la $22,5
+la $24,2
+sw $24,-8+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-8+160($sp)
+sll $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,20
+beq $24,$15,L.1926
+la $23,299
+beq $30,$0,L.1928
+la $4,L.687
+move $5,$23
+jal printf
+L.1928:
+L.1926:
+la $22,5
+la $24,2
+sw $24,-12+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-12+160($sp)
+sll $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,20
+beq $24,$15,L.1930
+la $23,300
+beq $30,$0,L.1932
+la $4,L.687
+move $5,$23
+jal printf
+L.1932:
+L.1930:
+la $21,5
+la $17,2
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $15,$17,8*(4-1); sra $15,$15,8*(4-1)
+sll $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,20
+beq $24,$15,L.1934
+la $23,301
+beq $30,$0,L.1936
+la $4,L.687
+move $5,$23
+jal printf
+L.1936:
+L.1934:
+la $21,5
+la $16,2
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $15,$16,8*(4-2); sra $15,$15,8*(4-2)
+sll $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,20
+beq $24,$15,L.1938
+la $23,302
+beq $30,$0,L.1940
+la $4,L.687
+move $5,$23
+jal printf
+L.1940:
+L.1938:
+la $21,5
+la $24,2
+sw $24,-4+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-4+160($sp)
+sll $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,20
+beq $24,$15,L.1942
+la $23,303
+beq $30,$0,L.1944
+la $4,L.687
+move $5,$23
+jal printf
+L.1944:
+L.1942:
+la $21,5
+la $24,2
+sw $24,-8+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-8+160($sp)
+sll $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,20
+beq $24,$15,L.1946
+la $23,304
+beq $30,$0,L.1948
+la $4,L.687
+move $5,$23
+jal printf
+L.1948:
+L.1946:
+la $21,5
+la $24,2
+sw $24,-12+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-12+160($sp)
+sll $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,20
+beq $24,$15,L.1950
+la $23,305
+beq $30,$0,L.1952
+la $4,L.687
+move $5,$23
+jal printf
+L.1952:
+L.1950:
+la $20,5
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+sll $20,$20,$24
+la $24,20
+beq $20,$24,L.1954
+la $23,306
+beq $30,$0,L.1956
+la $4,L.687
+move $5,$23
+jal printf
+L.1956:
+L.1954:
+la $20,5
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+sll $20,$20,$24
+la $24,20
+beq $20,$24,L.1958
+la $23,307
+beq $30,$0,L.1960
+la $4,L.687
+move $5,$23
+jal printf
+L.1960:
+L.1958:
+la $20,5
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+sll $20,$20,$24
+la $24,20
+beq $20,$24,L.1962
+la $23,308
+beq $30,$0,L.1964
+la $4,L.687
+move $5,$23
+jal printf
+L.1964:
+L.1962:
+la $20,5
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+sll $20,$20,$24
+la $24,20
+beq $20,$24,L.1966
+la $23,309
+beq $30,$0,L.1968
+la $4,L.687
+move $5,$23
+jal printf
+L.1968:
+L.1966:
+la $20,5
+la $24,2
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+sll $20,$20,$24
+la $24,20
+beq $20,$24,L.1970
+la $23,310
+beq $30,$0,L.1972
+la $4,L.687
+move $5,$23
+jal printf
+L.1972:
+L.1970:
+la $19,5
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+sll $19,$19,$24
+la $24,20
+beq $19,$24,L.1974
+la $23,311
+beq $30,$0,L.1976
+la $4,L.687
+move $5,$23
+jal printf
+L.1976:
+L.1974:
+la $19,5
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+sll $19,$19,$24
+la $24,20
+beq $19,$24,L.1978
+la $23,312
+beq $30,$0,L.1980
+la $4,L.687
+move $5,$23
+jal printf
+L.1980:
+L.1978:
+la $19,5
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+sll $19,$19,$24
+la $24,20
+beq $19,$24,L.1982
+la $23,313
+beq $30,$0,L.1984
+la $4,L.687
+move $5,$23
+jal printf
+L.1984:
+L.1982:
+la $19,5
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+sll $19,$19,$24
+la $24,20
+beq $19,$24,L.1986
+la $23,314
+beq $30,$0,L.1988
+la $4,L.687
+move $5,$23
+jal printf
+L.1988:
+L.1986:
+la $19,5
+la $24,2
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+sll $19,$19,$24
+la $24,20
+beq $19,$24,L.1990
+la $23,315
+beq $30,$0,L.1992
+la $4,L.687
+move $5,$23
+jal printf
+L.1992:
+L.1990:
+la $18,5
+la $17,2
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+sll $18,$18,$24
+la $24,20
+beq $18,$24,L.1994
+la $23,316
+beq $30,$0,L.1996
+la $4,L.687
+move $5,$23
+jal printf
+L.1996:
+L.1994:
+la $18,5
+la $16,2
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+sll $18,$18,$24
+la $24,20
+beq $18,$24,L.1998
+la $23,317
+beq $30,$0,L.2000
+la $4,L.687
+move $5,$23
+jal printf
+L.2000:
+L.1998:
+la $18,5
+la $24,2
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+sll $18,$18,$24
+la $24,20
+beq $18,$24,L.2002
+la $23,318
+beq $30,$0,L.2004
+la $4,L.687
+move $5,$23
+jal printf
+L.2004:
+L.2002:
+la $18,5
+la $24,2
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+sll $18,$18,$24
+la $24,20
+beq $18,$24,L.2006
+la $23,319
+beq $30,$0,L.2008
+la $4,L.687
+move $5,$23
+jal printf
+L.2008:
+L.2006:
+la $18,5
+la $24,2
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+sll $18,$18,$24
+la $24,20
+beq $18,$24,L.2010
+la $23,320
+beq $30,$0,L.2012
+la $4,L.687
+move $5,$23
+jal printf
+L.2012:
+L.2010:
+la $22,12
+la $17,10
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+sll $15,$17,8*(4-1); sra $15,$15,8*(4-1)
+and $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,8
+beq $24,$15,L.2014
+la $23,321
+beq $30,$0,L.2016
+la $4,L.687
+move $5,$23
+jal printf
+L.2016:
+L.2014:
+la $22,12
+la $16,10
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+sll $15,$16,8*(4-2); sra $15,$15,8*(4-2)
+and $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,8
+beq $24,$15,L.2018
+la $23,322
+beq $30,$0,L.2020
+la $4,L.687
+move $5,$23
+jal printf
+L.2020:
+L.2018:
+la $22,12
+la $24,10
+sw $24,-4+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-4+160($sp)
+and $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,8
+beq $24,$15,L.2022
+la $23,323
+beq $30,$0,L.2024
+la $4,L.687
+move $5,$23
+jal printf
+L.2024:
+L.2022:
+la $22,12
+la $24,10
+sw $24,-8+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-8+160($sp)
+and $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,8
+beq $24,$15,L.2026
+la $23,324
+beq $30,$0,L.2028
+la $4,L.687
+move $5,$23
+jal printf
+L.2028:
+L.2026:
+la $22,12
+la $24,10
+sw $24,-12+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-12+160($sp)
+and $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,8
+beq $24,$15,L.2030
+la $23,325
+beq $30,$0,L.2032
+la $4,L.687
+move $5,$23
+jal printf
+L.2032:
+L.2030:
+la $21,12
+la $17,10
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $15,$17,8*(4-1); sra $15,$15,8*(4-1)
+and $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,8
+beq $24,$15,L.2034
+la $23,326
+beq $30,$0,L.2036
+la $4,L.687
+move $5,$23
+jal printf
+L.2036:
+L.2034:
+la $21,12
+la $16,10
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $15,$16,8*(4-2); sra $15,$15,8*(4-2)
+and $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,8
+beq $24,$15,L.2038
+la $23,327
+beq $30,$0,L.2040
+la $4,L.687
+move $5,$23
+jal printf
+L.2040:
+L.2038:
+la $21,12
+la $24,10
+sw $24,-4+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-4+160($sp)
+and $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,8
+beq $24,$15,L.2042
+la $23,328
+beq $30,$0,L.2044
+la $4,L.687
+move $5,$23
+jal printf
+L.2044:
+L.2042:
+la $21,12
+la $24,10
+sw $24,-8+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-8+160($sp)
+and $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,8
+beq $24,$15,L.2046
+la $23,329
+beq $30,$0,L.2048
+la $4,L.687
+move $5,$23
+jal printf
+L.2048:
+L.2046:
+la $21,12
+la $24,10
+sw $24,-12+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-12+160($sp)
+and $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,8
+beq $24,$15,L.2050
+la $23,330
+beq $30,$0,L.2052
+la $4,L.687
+move $5,$23
+jal printf
+L.2052:
+L.2050:
+la $20,12
+la $17,10
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+and $20,$20,$24
+la $24,8
+beq $20,$24,L.2054
+la $23,331
+beq $30,$0,L.2056
+la $4,L.687
+move $5,$23
+jal printf
+L.2056:
+L.2054:
+la $20,12
+la $16,10
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+and $20,$20,$24
+la $24,8
+beq $20,$24,L.2058
+la $23,332
+beq $30,$0,L.2060
+la $4,L.687
+move $5,$23
+jal printf
+L.2060:
+L.2058:
+la $20,12
+la $24,10
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+and $20,$20,$24
+la $24,8
+beq $20,$24,L.2062
+la $23,333
+beq $30,$0,L.2064
+la $4,L.687
+move $5,$23
+jal printf
+L.2064:
+L.2062:
+la $20,12
+la $24,10
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+and $20,$20,$24
+la $24,8
+beq $20,$24,L.2066
+la $23,334
+beq $30,$0,L.2068
+la $4,L.687
+move $5,$23
+jal printf
+L.2068:
+L.2066:
+la $20,12
+la $24,10
+sw $24,-12+160($sp)
+move $24,$20
+lw $15,-12+160($sp)
+and $24,$24,$15
+move $20,$24
+la $24,8
+beq $20,$24,L.2070
+la $23,335
+beq $30,$0,L.2072
+la $4,L.687
+move $5,$23
+jal printf
+L.2072:
+L.2070:
+la $19,12
+la $17,10
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+and $19,$19,$24
+la $24,8
+beq $19,$24,L.2074
+la $23,336
+beq $30,$0,L.2076
+la $4,L.687
+move $5,$23
+jal printf
+L.2076:
+L.2074:
+la $19,12
+la $16,10
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+and $19,$19,$24
+la $24,8
+beq $19,$24,L.2078
+la $23,337
+beq $30,$0,L.2080
+la $4,L.687
+move $5,$23
+jal printf
+L.2080:
+L.2078:
+la $19,12
+la $24,10
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+and $19,$19,$24
+la $24,8
+beq $19,$24,L.2082
+la $23,338
+beq $30,$0,L.2084
+la $4,L.687
+move $5,$23
+jal printf
+L.2084:
+L.2082:
+la $19,12
+la $24,10
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+and $19,$19,$24
+la $24,8
+beq $19,$24,L.2086
+la $23,339
+beq $30,$0,L.2088
+la $4,L.687
+move $5,$23
+jal printf
+L.2088:
+L.2086:
+la $19,12
+la $24,10
+sw $24,-12+160($sp)
+move $24,$19
+lw $15,-12+160($sp)
+and $24,$24,$15
+move $19,$24
+la $24,8
+beq $19,$24,L.2090
+la $23,340
+beq $30,$0,L.2092
+la $4,L.687
+move $5,$23
+jal printf
+L.2092:
+L.2090:
+la $18,12
+la $17,10
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+and $18,$18,$24
+la $24,8
+beq $18,$24,L.2094
+la $23,341
+beq $30,$0,L.2096
+la $4,L.687
+move $5,$23
+jal printf
+L.2096:
+L.2094:
+la $18,12
+la $16,10
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+and $18,$18,$24
+la $24,8
+beq $18,$24,L.2098
+la $23,342
+beq $30,$0,L.2100
+la $4,L.687
+move $5,$23
+jal printf
+L.2100:
+L.2098:
+la $18,12
+la $24,10
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+and $18,$18,$24
+la $24,8
+beq $18,$24,L.2102
+la $23,343
+beq $30,$0,L.2104
+la $4,L.687
+move $5,$23
+jal printf
+L.2104:
+L.2102:
+la $18,12
+la $24,10
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+and $18,$18,$24
+la $24,8
+beq $18,$24,L.2106
+la $23,344
+beq $30,$0,L.2108
+la $4,L.687
+move $5,$23
+jal printf
+L.2108:
+L.2106:
+la $18,12
+la $24,10
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+and $18,$18,$24
+la $24,8
+beq $18,$24,L.2110
+la $23,345
+beq $30,$0,L.2112
+la $4,L.687
+move $5,$23
+jal printf
+L.2112:
+L.2110:
+la $22,12
+la $17,10
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+sll $15,$17,8*(4-1); sra $15,$15,8*(4-1)
+xor $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,6
+beq $24,$15,L.2114
+la $23,346
+beq $30,$0,L.2116
+la $4,L.687
+move $5,$23
+jal printf
+L.2116:
+L.2114:
+la $22,12
+la $16,10
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+sll $15,$16,8*(4-2); sra $15,$15,8*(4-2)
+xor $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,6
+beq $24,$15,L.2118
+la $23,347
+beq $30,$0,L.2120
+la $4,L.687
+move $5,$23
+jal printf
+L.2120:
+L.2118:
+la $22,12
+la $24,10
+sw $24,-4+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-4+160($sp)
+xor $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,6
+beq $24,$15,L.2122
+la $23,348
+beq $30,$0,L.2124
+la $4,L.687
+move $5,$23
+jal printf
+L.2124:
+L.2122:
+la $22,12
+la $24,10
+sw $24,-8+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-8+160($sp)
+xor $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,6
+beq $24,$15,L.2126
+la $23,349
+beq $30,$0,L.2128
+la $4,L.687
+move $5,$23
+jal printf
+L.2128:
+L.2126:
+la $22,12
+la $24,10
+sw $24,-12+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-12+160($sp)
+xor $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,6
+beq $24,$15,L.2130
+la $23,350
+beq $30,$0,L.2132
+la $4,L.687
+move $5,$23
+jal printf
+L.2132:
+L.2130:
+la $21,12
+la $17,10
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $15,$17,8*(4-1); sra $15,$15,8*(4-1)
+xor $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,6
+beq $24,$15,L.2134
+la $23,351
+beq $30,$0,L.2136
+la $4,L.687
+move $5,$23
+jal printf
+L.2136:
+L.2134:
+la $21,12
+la $16,10
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $15,$16,8*(4-2); sra $15,$15,8*(4-2)
+xor $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,6
+beq $24,$15,L.2138
+la $23,352
+beq $30,$0,L.2140
+la $4,L.687
+move $5,$23
+jal printf
+L.2140:
+L.2138:
+la $21,12
+la $24,10
+sw $24,-4+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-4+160($sp)
+xor $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,6
+beq $24,$15,L.2142
+la $23,353
+beq $30,$0,L.2144
+la $4,L.687
+move $5,$23
+jal printf
+L.2144:
+L.2142:
+la $21,12
+la $24,10
+sw $24,-8+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-8+160($sp)
+xor $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,6
+beq $24,$15,L.2146
+la $23,354
+beq $30,$0,L.2148
+la $4,L.687
+move $5,$23
+jal printf
+L.2148:
+L.2146:
+la $21,12
+la $24,10
+sw $24,-12+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-12+160($sp)
+xor $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,6
+beq $24,$15,L.2150
+la $23,355
+beq $30,$0,L.2152
+la $4,L.687
+move $5,$23
+jal printf
+L.2152:
+L.2150:
+la $20,12
+la $17,10
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+xor $20,$20,$24
+la $24,6
+beq $20,$24,L.2154
+la $23,356
+beq $30,$0,L.2156
+la $4,L.687
+move $5,$23
+jal printf
+L.2156:
+L.2154:
+la $20,12
+la $16,10
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+xor $20,$20,$24
+la $24,6
+beq $20,$24,L.2158
+la $23,357
+beq $30,$0,L.2160
+la $4,L.687
+move $5,$23
+jal printf
+L.2160:
+L.2158:
+la $20,12
+la $24,10
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+xor $20,$20,$24
+la $24,6
+beq $20,$24,L.2162
+la $23,358
+beq $30,$0,L.2164
+la $4,L.687
+move $5,$23
+jal printf
+L.2164:
+L.2162:
+la $20,12
+la $24,10
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+xor $20,$20,$24
+la $24,6
+beq $20,$24,L.2166
+la $23,359
+beq $30,$0,L.2168
+la $4,L.687
+move $5,$23
+jal printf
+L.2168:
+L.2166:
+la $20,12
+la $24,10
+sw $24,-12+160($sp)
+move $24,$20
+lw $15,-12+160($sp)
+xor $24,$24,$15
+move $20,$24
+la $24,6
+beq $20,$24,L.2170
+la $23,360
+beq $30,$0,L.2172
+la $4,L.687
+move $5,$23
+jal printf
+L.2172:
+L.2170:
+la $19,12
+la $17,10
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+xor $19,$19,$24
+la $24,6
+beq $19,$24,L.2174
+la $23,361
+beq $30,$0,L.2176
+la $4,L.687
+move $5,$23
+jal printf
+L.2176:
+L.2174:
+la $19,12
+la $16,10
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+xor $19,$19,$24
+la $24,6
+beq $19,$24,L.2178
+la $23,362
+beq $30,$0,L.2180
+la $4,L.687
+move $5,$23
+jal printf
+L.2180:
+L.2178:
+la $19,12
+la $24,10
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+xor $19,$19,$24
+la $24,6
+beq $19,$24,L.2182
+la $23,363
+beq $30,$0,L.2184
+la $4,L.687
+move $5,$23
+jal printf
+L.2184:
+L.2182:
+la $19,12
+la $24,10
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+xor $19,$19,$24
+la $24,6
+beq $19,$24,L.2186
+la $23,364
+beq $30,$0,L.2188
+la $4,L.687
+move $5,$23
+jal printf
+L.2188:
+L.2186:
+la $19,12
+la $24,10
+sw $24,-12+160($sp)
+move $24,$19
+lw $15,-12+160($sp)
+xor $24,$24,$15
+move $19,$24
+la $24,6
+beq $19,$24,L.2190
+la $23,365
+beq $30,$0,L.2192
+la $4,L.687
+move $5,$23
+jal printf
+L.2192:
+L.2190:
+la $18,12
+la $17,10
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+xor $18,$18,$24
+la $24,6
+beq $18,$24,L.2194
+la $23,366
+beq $30,$0,L.2196
+la $4,L.687
+move $5,$23
+jal printf
+L.2196:
+L.2194:
+la $18,12
+la $16,10
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+xor $18,$18,$24
+la $24,6
+beq $18,$24,L.2198
+la $23,367
+beq $30,$0,L.2200
+la $4,L.687
+move $5,$23
+jal printf
+L.2200:
+L.2198:
+la $18,12
+la $24,10
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+xor $18,$18,$24
+la $24,6
+beq $18,$24,L.2202
+la $23,368
+beq $30,$0,L.2204
+la $4,L.687
+move $5,$23
+jal printf
+L.2204:
+L.2202:
+la $18,12
+la $24,10
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+xor $18,$18,$24
+la $24,6
+beq $18,$24,L.2206
+la $23,369
+beq $30,$0,L.2208
+la $4,L.687
+move $5,$23
+jal printf
+L.2208:
+L.2206:
+la $18,12
+la $24,10
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+xor $18,$18,$24
+la $24,6
+beq $18,$24,L.2210
+la $23,370
+beq $30,$0,L.2212
+la $4,L.687
+move $5,$23
+jal printf
+L.2212:
+L.2210:
+la $22,12
+la $17,10
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+sll $15,$17,8*(4-1); sra $15,$15,8*(4-1)
+or $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,14
+beq $24,$15,L.2214
+la $23,371
+beq $30,$0,L.2216
+la $4,L.687
+move $5,$23
+jal printf
+L.2216:
+L.2214:
+la $22,12
+la $16,10
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+sll $15,$16,8*(4-2); sra $15,$15,8*(4-2)
+or $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,14
+beq $24,$15,L.2218
+la $23,372
+beq $30,$0,L.2220
+la $4,L.687
+move $5,$23
+jal printf
+L.2220:
+L.2218:
+la $22,12
+la $24,10
+sw $24,-4+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-4+160($sp)
+or $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,14
+beq $24,$15,L.2222
+la $23,373
+beq $30,$0,L.2224
+la $4,L.687
+move $5,$23
+jal printf
+L.2224:
+L.2222:
+la $22,12
+la $24,10
+sw $24,-8+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-8+160($sp)
+or $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,14
+beq $24,$15,L.2226
+la $23,374
+beq $30,$0,L.2228
+la $4,L.687
+move $5,$23
+jal printf
+L.2228:
+L.2226:
+la $22,12
+la $24,10
+sw $24,-12+160($sp)
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+lw $15,-12+160($sp)
+or $24,$24,$15
+move $22,$24
+sll $24,$22,8*(4-1); sra $24,$24,8*(4-1)
+la $15,14
+beq $24,$15,L.2230
+la $23,375
+beq $30,$0,L.2232
+la $4,L.687
+move $5,$23
+jal printf
+L.2232:
+L.2230:
+la $21,12
+la $17,10
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $15,$17,8*(4-1); sra $15,$15,8*(4-1)
+or $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,14
+beq $24,$15,L.2234
+la $23,376
+beq $30,$0,L.2236
+la $4,L.687
+move $5,$23
+jal printf
+L.2236:
+L.2234:
+la $21,12
+la $16,10
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $15,$16,8*(4-2); sra $15,$15,8*(4-2)
+or $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,14
+beq $24,$15,L.2238
+la $23,377
+beq $30,$0,L.2240
+la $4,L.687
+move $5,$23
+jal printf
+L.2240:
+L.2238:
+la $21,12
+la $24,10
+sw $24,-4+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-4+160($sp)
+or $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,14
+beq $24,$15,L.2242
+la $23,378
+beq $30,$0,L.2244
+la $4,L.687
+move $5,$23
+jal printf
+L.2244:
+L.2242:
+la $21,12
+la $24,10
+sw $24,-8+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-8+160($sp)
+or $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,14
+beq $24,$15,L.2246
+la $23,379
+beq $30,$0,L.2248
+la $4,L.687
+move $5,$23
+jal printf
+L.2248:
+L.2246:
+la $21,12
+la $24,10
+sw $24,-12+160($sp)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,-12+160($sp)
+or $24,$24,$15
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,14
+beq $24,$15,L.2250
+la $23,380
+beq $30,$0,L.2252
+la $4,L.687
+move $5,$23
+jal printf
+L.2252:
+L.2250:
+la $20,12
+la $17,10
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+or $20,$20,$24
+la $24,14
+beq $20,$24,L.2254
+la $23,381
+beq $30,$0,L.2256
+la $4,L.687
+move $5,$23
+jal printf
+L.2256:
+L.2254:
+la $20,12
+la $16,10
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+or $20,$20,$24
+la $24,14
+beq $20,$24,L.2258
+la $23,382
+beq $30,$0,L.2260
+la $4,L.687
+move $5,$23
+jal printf
+L.2260:
+L.2258:
+la $20,12
+la $24,10
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+or $20,$20,$24
+la $24,14
+beq $20,$24,L.2262
+la $23,383
+beq $30,$0,L.2264
+la $4,L.687
+move $5,$23
+jal printf
+L.2264:
+L.2262:
+la $20,12
+la $24,10
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+or $20,$20,$24
+la $24,14
+beq $20,$24,L.2266
+la $23,384
+beq $30,$0,L.2268
+la $4,L.687
+move $5,$23
+jal printf
+L.2268:
+L.2266:
+la $20,12
+la $24,10
+sw $24,-12+160($sp)
+move $24,$20
+lw $15,-12+160($sp)
+or $24,$24,$15
+move $20,$24
+la $24,14
+beq $20,$24,L.2270
+la $23,385
+beq $30,$0,L.2272
+la $4,L.687
+move $5,$23
+jal printf
+L.2272:
+L.2270:
+la $19,12
+la $17,10
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+or $19,$19,$24
+la $24,14
+beq $19,$24,L.2274
+la $23,386
+beq $30,$0,L.2276
+la $4,L.687
+move $5,$23
+jal printf
+L.2276:
+L.2274:
+la $19,12
+la $16,10
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+or $19,$19,$24
+la $24,14
+beq $19,$24,L.2278
+la $23,387
+beq $30,$0,L.2280
+la $4,L.687
+move $5,$23
+jal printf
+L.2280:
+L.2278:
+la $19,12
+la $24,10
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+or $19,$19,$24
+la $24,14
+beq $19,$24,L.2282
+la $23,388
+beq $30,$0,L.2284
+la $4,L.687
+move $5,$23
+jal printf
+L.2284:
+L.2282:
+la $19,12
+la $24,10
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+or $19,$19,$24
+la $24,14
+beq $19,$24,L.2286
+la $23,389
+beq $30,$0,L.2288
+la $4,L.687
+move $5,$23
+jal printf
+L.2288:
+L.2286:
+la $19,12
+la $24,10
+sw $24,-12+160($sp)
+move $24,$19
+lw $15,-12+160($sp)
+or $24,$24,$15
+move $19,$24
+la $24,14
+beq $19,$24,L.2290
+la $23,390
+beq $30,$0,L.2292
+la $4,L.687
+move $5,$23
+jal printf
+L.2292:
+L.2290:
+la $18,12
+la $17,10
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+or $18,$18,$24
+la $24,14
+beq $18,$24,L.2294
+la $23,391
+beq $30,$0,L.2296
+la $4,L.687
+move $5,$23
+jal printf
+L.2296:
+L.2294:
+la $18,12
+la $16,10
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+or $18,$18,$24
+la $24,14
+beq $18,$24,L.2298
+la $23,392
+beq $30,$0,L.2300
+la $4,L.687
+move $5,$23
+jal printf
+L.2300:
+L.2298:
+la $18,12
+la $24,10
+sw $24,-4+160($sp)
+lw $24,-4+160($sp)
+or $18,$18,$24
+la $24,14
+beq $18,$24,L.2302
+la $23,393
+beq $30,$0,L.2304
+la $4,L.687
+move $5,$23
+jal printf
+L.2304:
+L.2302:
+la $18,12
+la $24,10
+sw $24,-8+160($sp)
+lw $24,-8+160($sp)
+or $18,$18,$24
+la $24,14
+beq $18,$24,L.2306
+la $23,394
+beq $30,$0,L.2308
+la $4,L.687
+move $5,$23
+jal printf
+L.2308:
+L.2306:
+la $18,12
+la $24,10
+sw $24,-12+160($sp)
+lw $24,-12+160($sp)
+or $18,$18,$24
+la $24,14
+beq $18,$24,L.2310
+la $23,395
+beq $30,$0,L.2312
+la $4,L.687
+move $5,$23
+jal printf
+L.2312:
+L.2310:
+beq $23,$0,L.2314
+la $24,1
+sw $24,-24+160($sp)
+lw $24,0+160($sp)
+lw $24,44($24)
+beq $24,$0,L.2316
+la $4,L.688
+la $5,1
+jal printf
+L.2316:
+L.2314:
+lw $2,-24+160($sp)
+L.686:
+l.d $f24,16($sp)
+l.d $f26,24($sp)
+l.d $f28,32($sp)
+l.d $f30,40($sp)
+lw $16,48($sp)
+lw $17,52($sp)
+lw $18,56($sp)
+lw $19,60($sp)
+lw $20,64($sp)
+lw $21,68($sp)
+lw $22,72($sp)
+lw $23,76($sp)
+lw $25,80($sp)
+lw $30,84($sp)
+lw $31,88($sp)
+addu $sp,$sp,160
+j $31
+.end s714
+.data
+.align 0
+L.2319:
+.byte 115
+.byte 55
+.byte 49
+.byte 53
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.sdata
+.align 0
+L.2320:
+.byte 115
+.byte 55
+.byte 49
+.byte 53
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s715
+.text
+.text
+.align 2
+.ent s715
+s715:
+.frame $sp,56,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-56
+.mask 0xc2e00000,-20
+sw $21,16($sp)
+sw $22,20($sp)
+sw $23,24($sp)
+.cprestore 28
+sw $30,32($sp)
+sw $31,36($sp)
+sw $4,56($sp)
+sw $0,-12+56($sp)
+sw $0,-4+56($sp)
+la $30,L.2320
+lw $15,0+56($sp)
+la $23,60($15)
+move $21,$0
+L.2321:
+L.2322:
+move $24,$23
+la $23,1($24)
+move $15,$30
+la $30,1($15)
+lb $15,($15)
+sb $15,($24)
+sll $24,$15,8*(4-1); sra $24,$24,8*(4-1)
+bne $24,$0,L.2321
+la $24,1
+move $22,$24
+la $22,1($22)
+la $22,1($22)
+la $22,1($22)
+la $22,1($22)
+la $24,1($22)
+move $22,$24
+la $15,6
+beq $24,$15,L.2324
+lw $24,0+56($sp)
+lw $24,44($24)
+beq $24,$0,L.2326
+la $4,L.2319
+la $5,1
+jal printf
+L.2326:
+la $21,1($21)
+L.2324:
+lw $4,-4+56($sp)
+la $24,3
+sw $24,-8+56($sp)
+lw $24,-8+56($sp)
+la $5,2($24)
+lw $6,-12+56($sp)
+jal s715f
+la $15,5
+beq $2,$15,L.2328
+lw $24,0+56($sp)
+lw $24,44($24)
+beq $24,$0,L.2330
+la $4,L.2319
+la $5,2
+jal printf
+L.2330:
+la $21,2($21)
+L.2328:
+move $2,$21
+L.2318:
+lw $21,16($sp)
+lw $22,20($sp)
+lw $23,24($sp)
+lw $25,28($sp)
+lw $30,32($sp)
+lw $31,36($sp)
+addu $sp,$sp,56
+j $31
+.end s715
+.globl s715f
+.text
+.align 2
+.ent s715f
+s715f:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+move $2,$5
+L.2332:
+j $31
+.end s715f
+.data
+.align 0
+L.2334:
+.byte 115
+.byte 55
+.byte 50
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.sdata
+.align 0
+L.2335:
+.byte 115
+.byte 55
+.byte 50
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s72
+.text
+.text
+.align 2
+.ent s72
+s72:
+.frame $sp,96,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-96
+.fmask 0xf0000000,-72
+.mask 0xc2ff0000,-24
+s.d $f28,16($sp)
+s.d $f30,24($sp)
+sw $16,32($sp)
+sw $17,36($sp)
+sw $18,40($sp)
+sw $19,44($sp)
+sw $20,48($sp)
+sw $21,52($sp)
+sw $22,56($sp)
+sw $23,60($sp)
+.cprestore 64
+sw $30,68($sp)
+sw $31,72($sp)
+move $30,$4
+la $22,L.2335
+la $21,60($30)
+move $19,$0
+L.2336:
+L.2337:
+move $24,$21
+la $21,1($24)
+move $15,$22
+la $22,1($15)
+lb $15,($15)
+sb $15,($24)
+sll $24,$15,8*(4-1); sra $24,$24,8*(4-1)
+bne $24,$0,L.2336
+la $24,2
+sw $24,-4+96($sp)
+lw $15,-4+96($sp)
+beq $15,$24,L.2339
+la $24,1
+la $19,1($19)
+la $4,L.2334
+move $5,$24
+jal printf
+L.2339:
+lw $24,-4+96($sp)
+negu $15,$24
+addu $24,$24,$15
+beq $24,$0,L.2341
+la $24,2
+la $19,2($19)
+la $4,L.2334
+move $5,$24
+jal printf
+L.2341:
+sw $0,-4+96($sp)
+move $23,$0
+b L.2346
+L.2343:
+lw $24,-4+96($sp)
+sll $24,$24,1
+or $24,$24,1
+sw $24,-4+96($sp)
+L.2344:
+la $23,1($23)
+L.2346:
+lw $24,4($30)
+blt $23,$24,L.2343
+lw $24,-4+96($sp)
+not $24,$24
+beq $24,$0,L.2347
+la $24,4
+la $19,4($19)
+la $4,L.2334
+move $5,$24
+jal printf
+L.2347:
+la $24,5
+sw $24,-4+96($sp)
+lw $24,-4+96($sp)
+la $24,1($24)
+sw $24,-4+96($sp)
+la $15,6
+bne $24,$15,L.2354
+lw $24,-4+96($sp)
+subu $24,$24,1
+sw $24,-4+96($sp)
+la $14,5
+bne $24,$14,L.2354
+lw $24,-4+96($sp)
+la $13,1($24)
+sw $13,-4+96($sp)
+bne $24,$14,L.2354
+lw $24,-4+96($sp)
+subu $13,$24,1
+sw $13,-4+96($sp)
+bne $24,$15,L.2354
+lw $24,-4+96($sp)
+beq $24,$14,L.2349
+L.2354:
+la $24,8
+la $19,8($19)
+la $4,L.2334
+move $5,$24
+jal printf
+L.2349:
+la $17,26
+la $24,26
+sw $24,-8+96($sp)
+l.d $f30,L.2355
+la $16,26
+la $24,26
+sw $24,-12+96($sp)
+la $18,26
+l.s $f28,L.2356
+move $20,$0
+la $24,26
+sll $15,$16,8*(4-2); sra $15,$15,8*(4-2)
+sll $15,$15,8*(4-1); sra $15,$15,8*(4-1)
+bne $15,$24,L.2363
+move $15,$18
+sll $15,$15,8*(4-1); sra $15,$15,8*(4-1)
+bne $15,$24,L.2363
+lw $15,-8+96($sp)
+sll $15,$15,8*(4-1); sra $15,$15,8*(4-1)
+bne $15,$24,L.2363
+lw $15,-12+96($sp)
+sll $15,$15,8*(4-1); sra $15,$15,8*(4-1)
+bne $15,$24,L.2363
+trunc.w.s $f2,$f28,$15; mfc1 $15,$f2
+sll $15,$15,8*(4-1); sra $15,$15,8*(4-1)
+bne $15,$24,L.2363
+trunc.w.d $f2,$f30,$15; mfc1 $15,$f2
+sll $15,$15,8*(4-1); sra $15,$15,8*(4-1)
+beq $15,$24,L.2357
+L.2363:
+la $20,1($20)
+L.2357:
+la $24,26
+sll $15,$17,8*(4-1); sra $15,$15,8*(4-1)
+sll $15,$15,8*(4-2); sra $15,$15,8*(4-2)
+bne $15,$24,L.2370
+move $15,$18
+sll $15,$15,8*(4-2); sra $15,$15,8*(4-2)
+bne $15,$24,L.2370
+lw $15,-8+96($sp)
+sll $15,$15,8*(4-2); sra $15,$15,8*(4-2)
+bne $15,$24,L.2370
+lw $15,-12+96($sp)
+sll $15,$15,8*(4-2); sra $15,$15,8*(4-2)
+bne $15,$24,L.2370
+trunc.w.s $f2,$f28,$15; mfc1 $15,$f2
+sll $15,$15,8*(4-2); sra $15,$15,8*(4-2)
+bne $15,$24,L.2370
+trunc.w.d $f2,$f30,$15; mfc1 $15,$f2
+sll $15,$15,8*(4-2); sra $15,$15,8*(4-2)
+beq $15,$24,L.2364
+L.2370:
+la $20,2($20)
+L.2364:
+la $24,26
+sll $15,$17,8*(4-1); sra $15,$15,8*(4-1)
+bne $15,$24,L.2377
+sll $15,$16,8*(4-2); sra $15,$15,8*(4-2)
+bne $15,$24,L.2377
+lw $15,-8+96($sp)
+bne $15,$24,L.2377
+lw $15,-12+96($sp)
+bne $15,$24,L.2377
+trunc.w.s $f2,$f28,$15; mfc1 $15,$f2
+bne $15,$24,L.2377
+trunc.w.d $f2,$f30,$15; mfc1 $15,$f2
+beq $15,$24,L.2371
+L.2377:
+la $20,4($20)
+L.2371:
+la $24,26
+sll $15,$17,8*(4-1); sra $15,$15,8*(4-1)
+bne $15,$24,L.2384
+sll $15,$16,8*(4-2); sra $15,$15,8*(4-2)
+bne $15,$24,L.2384
+bne $18,$24,L.2384
+lw $15,-12+96($sp)
+bne $15,$24,L.2384
+trunc.w.s $f2,$f28,$15; mfc1 $15,$f2
+bne $15,$24,L.2384
+trunc.w.d $f2,$f30,$15; mfc1 $15,$f2
+beq $15,$24,L.2378
+L.2384:
+la $20,8($20)
+L.2378:
+la $24,26
+sll $15,$17,8*(4-1); sra $15,$15,8*(4-1)
+bne $15,$24,L.2393
+sll $15,$16,8*(4-2); sra $15,$15,8*(4-2)
+bne $15,$24,L.2393
+move $15,$18
+bne $15,$24,L.2393
+lw $15,-8+96($sp)
+bne $15,$24,L.2393
+l.s $f18,L.828
+c.lt.s $f28,$f18; bc1t L.2394
+sub.s $f18,$f28,$f18
+trunc.w.s $f2,$f18,$24; mfc1 $24,$f2
+la $24,0x80000000($24)
+sw $24,-16+96($sp)
+b L.2395
+L.2394:
+trunc.w.s $f2,$f28,$24; mfc1 $24,$f2
+sw $24,-16+96($sp)
+L.2395:
+lw $24,-16+96($sp)
+la $15,26
+bne $24,$15,L.2393
+l.d $f18,L.836
+c.lt.d $f30,$f18; bc1t L.2396
+sub.d $f18,$f30,$f18
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+la $24,0x80000000($24)
+sw $24,-20+96($sp)
+b L.2397
+L.2396:
+trunc.w.d $f2,$f30,$24; mfc1 $24,$f2
+sw $24,-20+96($sp)
+L.2397:
+lw $24,-20+96($sp)
+la $15,26
+beq $24,$15,L.2385
+L.2393:
+la $20,16($20)
+L.2385:
+l.d $f18,L.2355
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+mtc1 $24,$f16; cvt.s.w $f16,$f16
+cvt.d.s $f16,$f16
+c.eq.d $f16,$f18; bc1f L.2404
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+mtc1 $24,$f16; cvt.s.w $f16,$f16
+cvt.d.s $f16,$f16
+c.eq.d $f16,$f18; bc1f L.2404
+mtc1 $18,$f16; cvt.s.w $f16,$f16
+cvt.d.s $f16,$f16
+c.eq.d $f16,$f18; bc1f L.2404
+lw $24,-8+96($sp)
+mtc1 $24,$f16; cvt.s.w $f16,$f16
+cvt.d.s $f16,$f16
+c.eq.d $f16,$f18; bc1f L.2404
+lw $24,-12+96($sp)
+l.d $f16,L.596
+srl $15,$24,1
+mtc1 $15,$f10; cvt.d.w $f10,$f10
+mul.d $f16,$f16,$f10
+and $24,$24,1
+mtc1 $24,$f10; cvt.d.w $f10,$f10
+add.d $f16,$f16,$f10
+cvt.s.d $f16,$f16
+cvt.d.s $f16,$f16
+c.eq.d $f16,$f18; bc1f L.2404
+cvt.s.d $f16,$f30
+cvt.d.s $f16,$f16
+c.eq.d $f16,$f18; bc1t L.2398
+L.2404:
+la $20,32($20)
+L.2398:
+l.d $f18,L.2355
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+c.eq.d $f16,$f18; bc1f L.2411
+sll $24,$16,8*(4-2); sra $24,$24,8*(4-2)
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+c.eq.d $f16,$f18; bc1f L.2411
+mtc1 $18,$f16; cvt.d.w $f16,$f16
+c.eq.d $f16,$f18; bc1f L.2411
+lw $24,-8+96($sp)
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+c.eq.d $f16,$f18; bc1f L.2411
+lw $24,-12+96($sp)
+l.d $f16,L.596
+srl $15,$24,1
+mtc1 $15,$f10; cvt.d.w $f10,$f10
+mul.d $f16,$f16,$f10
+and $24,$24,1
+mtc1 $24,$f10; cvt.d.w $f10,$f10
+add.d $f16,$f16,$f10
+c.eq.d $f16,$f18; bc1f L.2411
+cvt.d.s $f16,$f28
+c.eq.d $f16,$f18; bc1t L.2405
+L.2411:
+la $20,64($20)
+L.2405:
+beq $20,$0,L.2412
+la $24,16
+la $19,16($19)
+la $4,L.2334
+move $5,$24
+jal printf
+L.2412:
+move $2,$19
+L.2333:
+l.d $f28,16($sp)
+l.d $f30,24($sp)
+lw $16,32($sp)
+lw $17,36($sp)
+lw $18,40($sp)
+lw $19,44($sp)
+lw $20,48($sp)
+lw $21,52($sp)
+lw $22,56($sp)
+lw $23,60($sp)
+lw $25,64($sp)
+lw $30,68($sp)
+lw $31,72($sp)
+addu $sp,$sp,96
+j $31
+.end s72
+.data
+.align 0
+L.2415:
+.byte 115
+.byte 55
+.byte 53
+.byte 55
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.sdata
+.align 0
+L.2416:
+.byte 115
+.byte 55
+.byte 53
+.byte 55
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s757
+.text
+.text
+.align 2
+.ent s757
+s757:
+.frame $sp,176,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-176
+.mask 0xc2ff0000,-120
+sw $16,16($sp)
+sw $17,20($sp)
+sw $18,24($sp)
+sw $19,28($sp)
+sw $20,32($sp)
+sw $21,36($sp)
+sw $22,40($sp)
+sw $23,44($sp)
+.cprestore 48
+sw $30,52($sp)
+sw $31,56($sp)
+move $30,$4
+la $24,L.2416
+sw $24,-80+176($sp)
+la $24,60($30)
+sw $24,-84+176($sp)
+sw $0,-88+176($sp)
+L.2417:
+L.2418:
+lw $24,-84+176($sp)
+la $15,1($24)
+sw $15,-84+176($sp)
+lw $15,-80+176($sp)
+la $14,1($15)
+sw $14,-80+176($sp)
+lb $15,($15)
+sb $15,($24)
+sll $24,$15,8*(4-1); sra $24,$24,8*(4-1)
+bne $24,$0,L.2417
+la $24,40
+sw $24,-92+176($sp)
+lw $24,-92+176($sp)
+sll $15,$24,3
+sll $15,$15,2
+la $14,1280
+bne $15,$14,L.2422
+sra $24,$24,3
+sra $24,$24,2
+la $15,1
+beq $24,$15,L.2420
+L.2422:
+lw $24,-88+176($sp)
+la $24,1($24)
+sw $24,-88+176($sp)
+lw $24,44($30)
+beq $24,$0,L.2423
+la $4,L.2415
+la $5,1
+jal printf
+L.2423:
+L.2420:
+move $19,$0
+sw $0,-68+176($sp)
+b L.2428
+L.2425:
+la $17,1
+lw $24,16($30)
+subu $24,$24,1
+sll $16,$17,$24
+sw $0,-72+176($sp)
+lw $24,-72+176($sp)
+not $24,$24
+lw $15,-68+176($sp)
+srl $14,$24,$15
+sw $14,-76+176($sp)
+sll $24,$24,$15
+sw $24,-72+176($sp)
+move $18,$0
+b L.2432
+L.2429:
+lw $24,-68+176($sp)
+bge $18,$24,L.2440
+la $24,1
+sw $24,-100+176($sp)
+b L.2441
+L.2440:
+sw $0,-100+176($sp)
+L.2441:
+lw $24,-72+176($sp)
+and $24,$17,$24
+bne $24,$0,L.2442
+la $24,1
+sw $24,-104+176($sp)
+b L.2443
+L.2442:
+sw $0,-104+176($sp)
+L.2443:
+lw $24,-100+176($sp)
+lw $15,-104+176($sp)
+bne $24,$15,L.2439
+lw $24,-68+176($sp)
+bge $18,$24,L.2444
+la $24,1
+sw $24,-108+176($sp)
+b L.2445
+L.2444:
+sw $0,-108+176($sp)
+L.2445:
+lw $24,-76+176($sp)
+and $24,$16,$24
+bne $24,$0,L.2446
+la $24,1
+sw $24,-112+176($sp)
+b L.2447
+L.2446:
+sw $0,-112+176($sp)
+L.2447:
+lw $24,-108+176($sp)
+lw $15,-112+176($sp)
+beq $24,$15,L.2433
+L.2439:
+la $19,1
+L.2433:
+sll $17,$17,1
+srl $16,$16,1
+L.2430:
+la $18,1($18)
+L.2432:
+lw $24,16($30)
+blt $18,$24,L.2429
+L.2426:
+lw $24,-68+176($sp)
+la $24,1($24)
+sw $24,-68+176($sp)
+L.2428:
+lw $24,-68+176($sp)
+lw $15,16($30)
+blt $24,$15,L.2425
+beq $19,$0,L.2448
+lw $24,-88+176($sp)
+la $24,2($24)
+sw $24,-88+176($sp)
+lw $24,44($30)
+beq $24,$0,L.2450
+la $4,L.2415
+la $5,2
+jal printf
+L.2450:
+L.2448:
+la $20,3
+la $21,2
+la $22,1
+bge $20,$21,L.2458
+la $24,1
+sw $24,-104+176($sp)
+b L.2459
+L.2458:
+sw $0,-104+176($sp)
+L.2459:
+lw $24,-104+176($sp)
+bge $24,$22,L.2456
+la $24,1
+sw $24,-100+176($sp)
+b L.2457
+L.2456:
+sw $0,-100+176($sp)
+L.2457:
+lw $24,-100+176($sp)
+la $15,1
+beq $24,$15,L.2452
+lw $24,-88+176($sp)
+la $24,4($24)
+sw $24,-88+176($sp)
+lw $24,44($30)
+beq $24,$0,L.2460
+la $4,L.2415
+la $5,4
+jal printf
+L.2460:
+L.2452:
+la $24,-60+176($sp)
+la $15,-64+176($sp)
+bne $24,$15,L.2462
+lw $24,-88+176($sp)
+la $24,8($24)
+sw $24,-88+176($sp)
+lw $24,44($30)
+beq $24,$0,L.2465
+la $4,L.2415
+la $5,8
+jal printf
+L.2465:
+L.2462:
+la $24,-60+176($sp)
+la $15,-64+176($sp)
+bgeu $24,$15,L.2467
+lw $24,40($30)
+beq $24,$0,L.2470
+la $4,L.2472
+jal printf
+L.2470:
+L.2467:
+move $19,$0
+move $18,$0
+L.2473:
+sll $24,$18,2
+la $15,-64+176($sp)
+addu $24,$24,$15
+la $15,1
+sw $15,($24)
+L.2474:
+la $18,1($18)
+la $24,16
+blt $18,$24,L.2473
+sw $0,-60+176($sp)
+sw $0,-48+176($sp)
+sw $0,-40+176($sp)
+sw $0,-36+176($sp)
+sw $0,-28+176($sp)
+sw $0,-12+176($sp)
+move $20,$0
+L.2483:
+move $21,$0
+L.2487:
+move $22,$0
+L.2491:
+move $23,$0
+L.2495:
+bge $20,$21,L.2506
+la $24,1
+sw $24,-112+176($sp)
+b L.2507
+L.2506:
+sw $0,-112+176($sp)
+L.2507:
+bge $22,$23,L.2508
+la $24,1
+sw $24,-116+176($sp)
+b L.2509
+L.2508:
+sw $0,-116+176($sp)
+L.2509:
+lw $24,-112+176($sp)
+lw $15,-116+176($sp)
+bne $24,$15,L.2504
+la $24,1
+sw $24,-108+176($sp)
+b L.2505
+L.2504:
+sw $0,-108+176($sp)
+L.2505:
+lw $24,-108+176($sp)
+sll $15,$20,3
+sll $14,$21,2
+addu $15,$15,$14
+sll $14,$22,1
+addu $15,$15,$14
+addu $15,$15,$23
+sll $15,$15,2
+la $14,-64+176($sp)
+addu $15,$15,$14
+lw $15,($15)
+beq $24,$15,L.2499
+la $19,1
+L.2499:
+L.2496:
+la $23,1($23)
+la $24,2
+blt $23,$24,L.2495
+L.2492:
+la $22,1($22)
+la $24,2
+blt $22,$24,L.2491
+L.2488:
+la $21,1($21)
+la $24,2
+blt $21,$24,L.2487
+L.2484:
+la $20,1($20)
+la $24,2
+blt $20,$24,L.2483
+beq $19,$0,L.2510
+lw $24,-88+176($sp)
+la $24,16($24)
+sw $24,-88+176($sp)
+lw $24,44($30)
+beq $24,$0,L.2512
+la $4,L.2415
+la $5,16
+jal printf
+L.2512:
+L.2510:
+sw $0,-96+176($sp)
+lw $24,-96+176($sp)
+beq $24,$0,L.2514
+lw $24,-88+176($sp)
+la $24,32($24)
+sw $24,-88+176($sp)
+lw $24,44($30)
+beq $24,$0,L.2516
+la $4,L.2415
+la $5,32
+jal printf
+L.2516:
+L.2514:
+lw $2,-88+176($sp)
+L.2414:
+lw $16,16($sp)
+lw $17,20($sp)
+lw $18,24($sp)
+lw $19,28($sp)
+lw $20,32($sp)
+lw $21,36($sp)
+lw $22,40($sp)
+lw $23,44($sp)
+lw $25,48($sp)
+lw $30,52($sp)
+lw $31,56($sp)
+addu $sp,$sp,176
+j $31
+.end s757
+.data
+.align 0
+L.2519:
+.byte 76
+.byte 111
+.byte 99
+.byte 97
+.byte 108
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 37
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.data
+.align 0
+L.2520:
+.byte 115
+.byte 55
+.byte 56
+.byte 49
+.byte 51
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.sdata
+.align 0
+L.2521:
+.byte 115
+.byte 55
+.byte 56
+.byte 49
+.byte 51
+.byte 32
+.byte 32
+.byte 0
+.globl s7813
+.text
+.text
+.align 2
+.ent s7813
+s7813:
+.frame $sp,112,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-112
+.mask 0xc2ff0000,-56
+sw $16,16($sp)
+sw $17,20($sp)
+sw $18,24($sp)
+sw $19,28($sp)
+sw $20,32($sp)
+sw $21,36($sp)
+sw $22,40($sp)
+sw $23,44($sp)
+.cprestore 48
+sw $30,52($sp)
+sw $31,56($sp)
+sw $4,112($sp)
+la $19,L.2521
+lw $24,0+112($sp)
+la $18,60($24)
+move $23,$0
+move $17,$0
+lw $30,48($24)
+L.2522:
+L.2523:
+move $24,$18
+la $18,1($24)
+move $15,$19
+la $19,1($15)
+lb $15,($15)
+sb $15,($24)
+sll $24,$15,8*(4-1); sra $24,$24,8*(4-1)
+bne $24,$0,L.2522
+b L.2525
+la $23,1
+beq $30,$0,L.2527
+la $4,L.2519
+move $5,$23
+jal printf
+L.2527:
+L.2525:
+b L.2529
+la $23,2
+beq $30,$0,L.2531
+la $4,L.2519
+move $5,$23
+jal printf
+L.2531:
+L.2529:
+b L.2533
+la $23,3
+beq $30,$0,L.2535
+la $4,L.2519
+move $5,$23
+jal printf
+L.2535:
+L.2533:
+b L.2537
+la $23,4
+beq $30,$0,L.2539
+la $4,L.2519
+move $5,$23
+jal printf
+L.2539:
+L.2537:
+b L.2541
+la $23,5
+beq $30,$0,L.2543
+la $4,L.2519
+move $5,$23
+jal printf
+L.2543:
+L.2541:
+b L.2545
+la $23,6
+beq $30,$0,L.2547
+la $4,L.2519
+move $5,$23
+jal printf
+L.2547:
+L.2545:
+b L.2549
+la $23,7
+beq $30,$0,L.2551
+la $4,L.2519
+move $5,$23
+jal printf
+L.2551:
+L.2549:
+b L.2553
+la $23,8
+beq $30,$0,L.2555
+la $4,L.2519
+move $5,$23
+jal printf
+L.2555:
+L.2553:
+b L.2557
+la $23,9
+beq $30,$0,L.2559
+la $4,L.2519
+move $5,$23
+jal printf
+L.2559:
+L.2557:
+b L.2561
+la $23,10
+beq $30,$0,L.2563
+la $4,L.2519
+move $5,$23
+jal printf
+L.2563:
+L.2561:
+b L.2565
+la $23,11
+beq $30,$0,L.2567
+la $4,L.2519
+move $5,$23
+jal printf
+L.2567:
+L.2565:
+b L.2569
+la $23,12
+beq $30,$0,L.2571
+la $4,L.2519
+move $5,$23
+jal printf
+L.2571:
+L.2569:
+b L.2573
+la $23,13
+beq $30,$0,L.2575
+la $4,L.2519
+move $5,$23
+jal printf
+L.2575:
+L.2573:
+b L.2577
+la $23,14
+beq $30,$0,L.2579
+la $4,L.2519
+move $5,$23
+jal printf
+L.2579:
+L.2577:
+b L.2581
+la $23,15
+beq $30,$0,L.2583
+la $4,L.2519
+move $5,$23
+jal printf
+L.2583:
+L.2581:
+b L.2585
+la $23,16
+beq $30,$0,L.2587
+la $4,L.2519
+move $5,$23
+jal printf
+L.2587:
+L.2585:
+b L.2589
+la $23,17
+beq $30,$0,L.2591
+la $4,L.2519
+move $5,$23
+jal printf
+L.2591:
+L.2589:
+b L.2593
+la $23,18
+beq $30,$0,L.2595
+la $4,L.2519
+move $5,$23
+jal printf
+L.2595:
+L.2593:
+b L.2597
+la $23,16
+beq $30,$0,L.2599
+la $4,L.2519
+move $5,$23
+jal printf
+L.2599:
+L.2597:
+b L.2601
+la $23,20
+beq $30,$0,L.2603
+la $4,L.2519
+move $5,$23
+jal printf
+L.2603:
+L.2601:
+b L.2605
+la $23,21
+beq $30,$0,L.2607
+la $4,L.2519
+move $5,$23
+jal printf
+L.2607:
+L.2605:
+b L.2609
+la $23,22
+beq $30,$0,L.2611
+la $4,L.2519
+move $5,$23
+jal printf
+L.2611:
+L.2609:
+b L.2613
+la $23,23
+beq $30,$0,L.2615
+la $4,L.2519
+move $5,$23
+jal printf
+L.2615:
+L.2613:
+b L.2617
+la $23,24
+beq $30,$0,L.2619
+la $4,L.2519
+move $5,$23
+jal printf
+L.2619:
+L.2617:
+b L.2621
+la $23,25
+beq $30,$0,L.2623
+la $4,L.2519
+move $5,$23
+jal printf
+L.2623:
+L.2621:
+b L.2625
+la $23,26
+beq $30,$0,L.2627
+la $4,L.2519
+move $5,$23
+jal printf
+L.2627:
+L.2625:
+b L.2629
+la $23,27
+beq $30,$0,L.2631
+la $4,L.2519
+move $5,$23
+jal printf
+L.2631:
+L.2629:
+b L.2633
+la $23,28
+beq $30,$0,L.2635
+la $4,L.2519
+move $5,$23
+jal printf
+L.2635:
+L.2633:
+b L.2637
+la $23,26
+beq $30,$0,L.2639
+la $4,L.2519
+move $5,$23
+jal printf
+L.2639:
+L.2637:
+b L.2641
+la $23,30
+beq $30,$0,L.2643
+la $4,L.2519
+move $5,$23
+jal printf
+L.2643:
+L.2641:
+b L.2645
+la $23,31
+beq $30,$0,L.2647
+la $4,L.2519
+move $5,$23
+jal printf
+L.2647:
+L.2645:
+b L.2649
+la $23,32
+beq $30,$0,L.2651
+la $4,L.2519
+move $5,$23
+jal printf
+L.2651:
+L.2649:
+b L.2653
+la $23,33
+beq $30,$0,L.2655
+la $4,L.2519
+move $5,$23
+jal printf
+L.2655:
+L.2653:
+b L.2657
+la $23,34
+beq $30,$0,L.2659
+la $4,L.2519
+move $5,$23
+jal printf
+L.2659:
+L.2657:
+b L.2661
+la $23,35
+beq $30,$0,L.2663
+la $4,L.2519
+move $5,$23
+jal printf
+L.2663:
+L.2661:
+b L.2665
+la $23,36
+beq $30,$0,L.2667
+la $4,L.2519
+move $5,$23
+jal printf
+L.2667:
+L.2665:
+b L.2669
+la $23,37
+beq $30,$0,L.2671
+la $4,L.2519
+move $5,$23
+jal printf
+L.2671:
+L.2669:
+b L.2673
+la $23,38
+beq $30,$0,L.2675
+la $4,L.2519
+move $5,$23
+jal printf
+L.2675:
+L.2673:
+b L.2677
+la $23,39
+beq $30,$0,L.2679
+la $4,L.2519
+move $5,$23
+jal printf
+L.2679:
+L.2677:
+b L.2681
+la $23,40
+beq $30,$0,L.2683
+la $4,L.2519
+move $5,$23
+jal printf
+L.2683:
+L.2681:
+b L.2685
+la $23,41
+beq $30,$0,L.2687
+la $4,L.2519
+move $5,$23
+jal printf
+L.2687:
+L.2685:
+b L.2689
+la $23,42
+beq $30,$0,L.2691
+la $4,L.2519
+move $5,$23
+jal printf
+L.2691:
+L.2689:
+b L.2693
+la $23,43
+beq $30,$0,L.2695
+la $4,L.2519
+move $5,$23
+jal printf
+L.2695:
+L.2693:
+b L.2697
+la $23,44
+beq $30,$0,L.2699
+la $4,L.2519
+move $5,$23
+jal printf
+L.2699:
+L.2697:
+b L.2701
+la $23,45
+beq $30,$0,L.2703
+la $4,L.2519
+move $5,$23
+jal printf
+L.2703:
+L.2701:
+b L.2705
+la $23,46
+beq $30,$0,L.2707
+la $4,L.2519
+move $5,$23
+jal printf
+L.2707:
+L.2705:
+b L.2709
+la $23,47
+beq $30,$0,L.2711
+la $4,L.2519
+move $5,$23
+jal printf
+L.2711:
+L.2709:
+b L.2713
+la $23,48
+beq $30,$0,L.2715
+la $4,L.2519
+move $5,$23
+jal printf
+L.2715:
+L.2713:
+b L.2717
+la $23,49
+beq $30,$0,L.2719
+la $4,L.2519
+move $5,$23
+jal printf
+L.2719:
+L.2717:
+b L.2721
+la $23,50
+beq $30,$0,L.2723
+la $4,L.2519
+move $5,$23
+jal printf
+L.2723:
+L.2721:
+b L.2725
+la $23,51
+beq $30,$0,L.2727
+la $4,L.2519
+move $5,$23
+jal printf
+L.2727:
+L.2725:
+b L.2729
+la $23,52
+beq $30,$0,L.2731
+la $4,L.2519
+move $5,$23
+jal printf
+L.2731:
+L.2729:
+b L.2733
+la $23,53
+beq $30,$0,L.2735
+la $4,L.2519
+move $5,$23
+jal printf
+L.2735:
+L.2733:
+b L.2737
+la $23,54
+beq $30,$0,L.2739
+la $4,L.2519
+move $5,$23
+jal printf
+L.2739:
+L.2737:
+b L.2741
+la $23,55
+beq $30,$0,L.2743
+la $4,L.2519
+move $5,$23
+jal printf
+L.2743:
+L.2741:
+b L.2745
+la $23,56
+beq $30,$0,L.2747
+la $4,L.2519
+move $5,$23
+jal printf
+L.2747:
+L.2745:
+b L.2749
+la $23,57
+beq $30,$0,L.2751
+la $4,L.2519
+move $5,$23
+jal printf
+L.2751:
+L.2749:
+b L.2753
+la $23,58
+beq $30,$0,L.2755
+la $4,L.2519
+move $5,$23
+jal printf
+L.2755:
+L.2753:
+b L.2757
+la $23,56
+beq $30,$0,L.2759
+la $4,L.2519
+move $5,$23
+jal printf
+L.2759:
+L.2757:
+b L.2761
+la $23,60
+beq $30,$0,L.2763
+la $4,L.2519
+move $5,$23
+jal printf
+L.2763:
+L.2761:
+b L.2765
+la $23,61
+beq $30,$0,L.2767
+la $4,L.2519
+move $5,$23
+jal printf
+L.2767:
+L.2765:
+b L.2769
+la $23,62
+beq $30,$0,L.2771
+la $4,L.2519
+move $5,$23
+jal printf
+L.2771:
+L.2769:
+b L.2773
+la $23,63
+beq $30,$0,L.2775
+la $4,L.2519
+move $5,$23
+jal printf
+L.2775:
+L.2773:
+b L.2777
+la $23,64
+beq $30,$0,L.2779
+la $4,L.2519
+move $5,$23
+jal printf
+L.2779:
+L.2777:
+b L.2781
+la $23,65
+beq $30,$0,L.2783
+la $4,L.2519
+move $5,$23
+jal printf
+L.2783:
+L.2781:
+b L.2785
+la $23,66
+beq $30,$0,L.2787
+la $4,L.2519
+move $5,$23
+jal printf
+L.2787:
+L.2785:
+b L.2789
+la $23,67
+beq $30,$0,L.2791
+la $4,L.2519
+move $5,$23
+jal printf
+L.2791:
+L.2789:
+b L.2793
+la $23,68
+beq $30,$0,L.2795
+la $4,L.2519
+move $5,$23
+jal printf
+L.2795:
+L.2793:
+b L.2797
+la $23,69
+beq $30,$0,L.2799
+la $4,L.2519
+move $5,$23
+jal printf
+L.2799:
+L.2797:
+b L.2801
+la $23,70
+beq $30,$0,L.2803
+la $4,L.2519
+move $5,$23
+jal printf
+L.2803:
+L.2801:
+b L.2805
+la $23,71
+beq $30,$0,L.2807
+la $4,L.2519
+move $5,$23
+jal printf
+L.2807:
+L.2805:
+b L.2809
+la $23,72
+beq $30,$0,L.2811
+la $4,L.2519
+move $5,$23
+jal printf
+L.2811:
+L.2809:
+b L.2813
+la $23,73
+beq $30,$0,L.2815
+la $4,L.2519
+move $5,$23
+jal printf
+L.2815:
+L.2813:
+b L.2817
+la $23,74
+beq $30,$0,L.2819
+la $4,L.2519
+move $5,$23
+jal printf
+L.2819:
+L.2817:
+b L.2821
+la $23,75
+beq $30,$0,L.2823
+la $4,L.2519
+move $5,$23
+jal printf
+L.2823:
+L.2821:
+beq $23,$0,L.2825
+lw $24,0+112($sp)
+lw $24,44($24)
+beq $24,$0,L.2827
+la $4,L.2520
+la $5,1
+jal printf
+L.2827:
+la $17,1($17)
+L.2825:
+move $23,$0
+move $21,$0
+move $22,$0
+move $24,$22
+la $22,1($24)
+move $15,$0
+beq $24,$15,L.2830
+move $24,$21
+la $21,1($24)
+beq $24,$15,L.2830
+la $24,1
+sw $24,-8+112($sp)
+b L.2831
+L.2830:
+sw $0,-8+112($sp)
+L.2831:
+lw $20,-8+112($sp)
+la $24,1
+beq $22,$24,L.2832
+la $23,1
+beq $30,$0,L.2834
+la $4,L.2519
+move $5,$23
+jal printf
+L.2834:
+L.2832:
+beq $21,$0,L.2836
+la $23,2
+beq $30,$0,L.2838
+la $4,L.2519
+move $5,$23
+jal printf
+L.2838:
+L.2836:
+beq $20,$0,L.2840
+la $23,3
+beq $30,$0,L.2842
+la $4,L.2519
+move $5,$23
+jal printf
+L.2842:
+L.2840:
+beq $22,$0,L.2845
+move $15,$21
+la $21,1($15)
+beq $15,$0,L.2845
+la $24,1
+sw $24,-12+112($sp)
+b L.2846
+L.2845:
+sw $0,-12+112($sp)
+L.2846:
+lw $20,-12+112($sp)
+la $24,1
+beq $22,$24,L.2847
+la $23,4
+beq $30,$0,L.2849
+la $4,L.2519
+move $5,$23
+jal printf
+L.2849:
+L.2847:
+la $24,1
+beq $21,$24,L.2851
+la $23,5
+beq $30,$0,L.2853
+la $4,L.2519
+move $5,$23
+jal printf
+L.2853:
+L.2851:
+beq $20,$0,L.2855
+la $23,6
+beq $30,$0,L.2857
+la $4,L.2519
+move $5,$23
+jal printf
+L.2857:
+L.2855:
+move $24,$22
+subu $22,$24,1
+move $15,$0
+beq $24,$15,L.2860
+beq $21,$15,L.2860
+la $24,1
+sw $24,-16+112($sp)
+b L.2861
+L.2860:
+sw $0,-16+112($sp)
+L.2861:
+lw $20,-16+112($sp)
+beq $22,$0,L.2862
+la $23,7
+beq $30,$0,L.2864
+la $4,L.2519
+move $5,$23
+jal printf
+L.2864:
+L.2862:
+la $24,1
+beq $21,$24,L.2866
+la $23,8
+beq $30,$0,L.2868
+la $4,L.2519
+move $5,$23
+jal printf
+L.2868:
+L.2866:
+la $24,1
+beq $20,$24,L.2870
+la $23,9
+beq $30,$0,L.2872
+la $4,L.2519
+move $5,$23
+jal printf
+L.2872:
+L.2870:
+beq $22,$0,L.2875
+move $15,$21
+subu $21,$15,1
+beq $15,$0,L.2875
+la $24,1
+sw $24,-20+112($sp)
+b L.2876
+L.2875:
+sw $0,-20+112($sp)
+L.2876:
+lw $20,-20+112($sp)
+beq $22,$0,L.2877
+la $23,10
+beq $30,$0,L.2879
+la $4,L.2519
+move $5,$23
+jal printf
+L.2879:
+L.2877:
+la $24,1
+beq $21,$24,L.2881
+la $23,11
+beq $30,$0,L.2883
+la $4,L.2519
+move $5,$23
+jal printf
+L.2883:
+L.2881:
+beq $20,$0,L.2885
+la $23,12
+beq $30,$0,L.2887
+la $4,L.2519
+move $5,$23
+jal printf
+L.2887:
+L.2885:
+beq $23,$0,L.2889
+lw $24,0+112($sp)
+lw $24,44($24)
+beq $24,$0,L.2891
+la $4,L.2520
+la $5,2
+jal printf
+L.2891:
+la $17,2($17)
+L.2889:
+move $23,$0
+move $21,$0
+move $22,$0
+move $24,$22
+la $22,1($24)
+move $15,$0
+bne $24,$15,L.2896
+beq $21,$15,L.2894
+L.2896:
+la $24,1
+sw $24,-24+112($sp)
+b L.2895
+L.2894:
+sw $0,-24+112($sp)
+L.2895:
+lw $20,-24+112($sp)
+la $24,1
+beq $22,$24,L.2897
+la $23,1
+beq $30,$0,L.2899
+la $4,L.2519
+move $5,$23
+jal printf
+L.2899:
+L.2897:
+beq $21,$0,L.2901
+la $23,2
+beq $30,$0,L.2903
+la $4,L.2519
+move $5,$23
+jal printf
+L.2903:
+L.2901:
+beq $20,$0,L.2905
+la $23,3
+beq $30,$0,L.2907
+la $4,L.2519
+move $5,$23
+jal printf
+L.2907:
+L.2905:
+move $24,$21
+la $21,1($24)
+move $15,$0
+bne $24,$15,L.2912
+beq $22,$15,L.2910
+L.2912:
+la $24,1
+sw $24,-28+112($sp)
+b L.2911
+L.2910:
+sw $0,-28+112($sp)
+L.2911:
+lw $20,-28+112($sp)
+la $24,1
+beq $22,$24,L.2913
+la $23,4
+beq $30,$0,L.2915
+la $4,L.2519
+move $5,$23
+jal printf
+L.2915:
+L.2913:
+la $24,1
+beq $21,$24,L.2917
+la $23,5
+beq $30,$0,L.2919
+la $4,L.2519
+move $5,$23
+jal printf
+L.2919:
+L.2917:
+la $24,1
+beq $20,$24,L.2921
+la $23,6
+beq $30,$0,L.2923
+la $4,L.2519
+move $5,$23
+jal printf
+L.2923:
+L.2921:
+move $24,$22
+subu $22,$24,1
+move $15,$0
+bne $24,$15,L.2928
+move $24,$21
+subu $21,$24,1
+beq $24,$15,L.2926
+L.2928:
+la $24,1
+sw $24,-32+112($sp)
+b L.2927
+L.2926:
+sw $0,-32+112($sp)
+L.2927:
+lw $20,-32+112($sp)
+beq $22,$0,L.2929
+la $23,7
+beq $30,$0,L.2931
+la $4,L.2519
+move $5,$23
+jal printf
+L.2931:
+L.2929:
+la $24,1
+beq $21,$24,L.2933
+la $23,8
+beq $30,$0,L.2935
+la $4,L.2519
+move $5,$23
+jal printf
+L.2935:
+L.2933:
+la $24,1
+beq $20,$24,L.2937
+la $23,9
+beq $30,$0,L.2939
+la $4,L.2519
+move $5,$23
+jal printf
+L.2939:
+L.2937:
+move $24,$0
+bne $22,$24,L.2944
+move $15,$21
+subu $21,$15,1
+beq $15,$24,L.2942
+L.2944:
+la $24,1
+sw $24,-36+112($sp)
+b L.2943
+L.2942:
+sw $0,-36+112($sp)
+L.2943:
+lw $20,-36+112($sp)
+beq $22,$0,L.2945
+la $23,10
+beq $30,$0,L.2947
+la $4,L.2519
+move $5,$23
+jal printf
+L.2947:
+L.2945:
+beq $21,$0,L.2949
+la $23,11
+beq $30,$0,L.2951
+la $4,L.2519
+move $5,$23
+jal printf
+L.2951:
+L.2949:
+la $24,1
+beq $20,$24,L.2953
+la $23,12
+beq $30,$0,L.2955
+la $4,L.2519
+move $5,$23
+jal printf
+L.2955:
+L.2953:
+beq $23,$0,L.2957
+lw $24,0+112($sp)
+lw $24,44($24)
+beq $24,$0,L.2959
+la $4,L.2520
+la $5,4
+jal printf
+L.2959:
+la $17,4($17)
+L.2957:
+move $24,$0
+move $21,$24
+move $22,$24
+move $16,$24
+la $15,1
+sw $15,-4+112($sp)
+lw $15,-4+112($sp)
+beq $15,$24,L.2963
+sw $16,-40+112($sp)
+b L.2964
+L.2963:
+lw $24,-4+112($sp)
+beq $24,$0,L.2965
+move $24,$22
+la $22,1($24)
+sw $24,-44+112($sp)
+b L.2966
+L.2965:
+move $24,$21
+la $21,1($24)
+sw $24,-44+112($sp)
+L.2966:
+lw $24,-44+112($sp)
+sw $24,-40+112($sp)
+L.2964:
+lw $20,-40+112($sp)
+bne $20,$0,L.2970
+bne $22,$0,L.2970
+beq $21,$0,L.2967
+L.2970:
+lw $24,0+112($sp)
+lw $24,44($24)
+beq $24,$0,L.2971
+la $4,L.2520
+la $5,8
+jal printf
+L.2971:
+la $17,8($17)
+L.2967:
+lw $24,-4+112($sp)
+beq $24,$0,L.2978
+sw $16,-48+112($sp)
+b L.2979
+L.2978:
+la $24,1
+sw $24,-48+112($sp)
+L.2979:
+lw $15,-48+112($sp)
+bne $15,$0,L.2977
+beq $16,$0,L.2980
+la $24,1
+sw $24,-52+112($sp)
+b L.2981
+L.2980:
+sw $16,-52+112($sp)
+L.2981:
+lw $24,-52+112($sp)
+beq $24,$0,L.2973
+L.2977:
+lw $24,0+112($sp)
+lw $24,44($24)
+beq $24,$0,L.2982
+la $4,L.2520
+la $5,16
+jal printf
+L.2982:
+la $17,16($17)
+L.2973:
+move $2,$17
+L.2518:
+lw $16,16($sp)
+lw $17,20($sp)
+lw $18,24($sp)
+lw $19,28($sp)
+lw $20,32($sp)
+lw $21,36($sp)
+lw $22,40($sp)
+lw $23,44($sp)
+lw $25,48($sp)
+lw $30,52($sp)
+lw $31,56($sp)
+addu $sp,$sp,112
+j $31
+.end s7813
+.data
+.align 0
+L.2985:
+.byte 115
+.byte 56
+.byte 49
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.sdata
+.align 0
+L.2986:
+.byte 115
+.byte 56
+.byte 49
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.data
+.align 0
+L.2987:
+.byte 82
+.byte 101
+.byte 103
+.byte 105
+.byte 115
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 99
+.byte 111
+.byte 117
+.byte 110
+.byte 116
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 37
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 117
+.byte 110
+.byte 114
+.byte 101
+.byte 108
+.byte 105
+.byte 97
+.byte 98
+.byte 108
+.byte 101
+.byte 46
+.byte 10
+.byte 0
+.data
+.align 0
+L.2988:
+.byte 37
+.byte 100
+.byte 32
+.byte 114
+.byte 101
+.byte 103
+.byte 105
+.byte 115
+.byte 116
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 97
+.byte 115
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 101
+.byte 100
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 37
+.byte 115
+.byte 32
+.byte 118
+.byte 97
+.byte 114
+.byte 105
+.byte 97
+.byte 98
+.byte 108
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.globl s81
+.text
+.text
+.align 2
+.ent s81
+s81:
+.frame $sp,80,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-80
+.mask 0xc2ff0000,-24
+sw $16,16($sp)
+sw $17,20($sp)
+sw $18,24($sp)
+sw $19,28($sp)
+sw $20,32($sp)
+sw $21,36($sp)
+sw $22,40($sp)
+sw $23,44($sp)
+.cprestore 48
+sw $30,52($sp)
+sw $31,56($sp)
+sw $4,80($sp)
+sw $0,-20+80($sp)
+sw $0,-8+80($sp)
+sw $0,-12+80($sp)
+sw $0,-16+80($sp)
+la $17,L.2986
+lw $24,0+80($sp)
+la $16,60($24)
+L.2989:
+L.2990:
+move $24,$16
+la $16,1($24)
+move $15,$17
+la $17,1($15)
+lb $15,($15)
+sb $15,($24)
+sll $24,$15,8*(4-1); sra $24,$24,8*(4-1)
+bne $24,$0,L.2989
+la $24,1
+sw $24,-4+80($sp)
+move $21,$0
+L.2992:
+lw $24,-4+80($sp)
+move $15,$24
+move $30,$15
+move $20,$15
+la $23,-4+80($sp)
+la $19,-4+80($sp)
+move $22,$24
+move $18,$24
+sll $24,$30,8*(4-1); sra $24,$24,8*(4-1)
+sll $15,$20,8*(4-1); sra $15,$15,8*(4-1)
+beq $24,$15,L.2996
+la $24,1
+sw $24,-8+80($sp)
+L.2996:
+move $24,$23
+move $15,$19
+beq $24,$15,L.2998
+la $24,1
+sw $24,-12+80($sp)
+L.2998:
+beq $22,$18,L.3000
+la $24,1
+sw $24,-16+80($sp)
+L.3000:
+lw $24,-4+80($sp)
+sll $24,$24,1
+sw $24,-4+80($sp)
+L.2993:
+la $21,1($21)
+la $24,50
+blt $21,$24,L.2992
+lw $24,-8+80($sp)
+beq $24,$0,L.3002
+lw $24,-20+80($sp)
+la $24,1($24)
+sw $24,-20+80($sp)
+lw $24,0+80($sp)
+lw $24,44($24)
+beq $24,$0,L.3004
+la $4,L.2985
+la $5,1
+jal printf
+L.3004:
+L.3002:
+lw $24,-12+80($sp)
+beq $24,$0,L.3006
+lw $24,-20+80($sp)
+la $24,2($24)
+sw $24,-20+80($sp)
+lw $24,0+80($sp)
+lw $24,44($24)
+beq $24,$0,L.3008
+la $4,L.2985
+la $5,2
+jal printf
+L.3008:
+L.3006:
+lw $24,-16+80($sp)
+beq $24,$0,L.3010
+lw $24,-20+80($sp)
+la $24,4($24)
+sw $24,-20+80($sp)
+lw $24,0+80($sp)
+lw $24,44($24)
+beq $24,$0,L.3012
+la $4,L.2985
+la $5,4
+jal printf
+L.3012:
+L.3010:
+jal regc
+sw $2,-4+80($sp)
+lw $24,0+80($sp)
+lw $24,40($24)
+beq $24,$0,L.3014
+lw $24,-4+80($sp)
+bge $24,$0,L.3016
+la $4,L.2987
+la $5,L.425
+jal printf
+b L.3017
+L.3016:
+la $4,L.2988
+lw $5,-4+80($sp)
+la $6,L.425
+jal printf
+L.3017:
+L.3014:
+jal regp
+sw $2,-4+80($sp)
+lw $24,0+80($sp)
+lw $24,40($24)
+beq $24,$0,L.3018
+lw $24,-4+80($sp)
+bge $24,$0,L.3020
+la $4,L.2987
+la $5,L.3022
+jal printf
+b L.3021
+L.3020:
+la $4,L.2988
+lw $5,-4+80($sp)
+la $6,L.3022
+jal printf
+L.3021:
+L.3018:
+jal regi
+sw $2,-4+80($sp)
+lw $24,0+80($sp)
+lw $24,40($24)
+beq $24,$0,L.3023
+lw $24,-4+80($sp)
+bge $24,$0,L.3025
+la $4,L.2987
+la $5,L.426
+jal printf
+b L.3026
+L.3025:
+la $4,L.2988
+lw $5,-4+80($sp)
+la $6,L.426
+jal printf
+L.3026:
+L.3023:
+lw $2,-20+80($sp)
+L.2984:
+lw $16,16($sp)
+lw $17,20($sp)
+lw $18,24($sp)
+lw $19,28($sp)
+lw $20,32($sp)
+lw $21,36($sp)
+lw $22,40($sp)
+lw $23,44($sp)
+lw $25,48($sp)
+lw $30,52($sp)
+lw $31,56($sp)
+addu $sp,$sp,80
+j $31
+.end s81
+.globl regc
+.text
+.align 2
+.ent regc
+regc:
+.frame $sp,176,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-176
+.mask 0x40ff0000,-144
+sw $16,0($sp)
+sw $17,4($sp)
+sw $18,8($sp)
+sw $19,12($sp)
+sw $20,16($sp)
+sw $21,20($sp)
+sw $22,24($sp)
+sw $23,28($sp)
+sw $30,32($sp)
+sb $0,-130+176($sp)
+la $24,1
+sb $24,-109+176($sp)
+la $24,2
+sb $24,-110+176($sp)
+la $24,3
+sb $24,-111+176($sp)
+la $30,4
+la $24,5
+sb $24,-112+176($sp)
+la $23,6
+la $24,7
+sb $24,-113+176($sp)
+la $22,8
+la $24,9
+sb $24,-114+176($sp)
+la $21,10
+la $24,11
+sb $24,-115+176($sp)
+la $20,12
+la $24,13
+sb $24,-116+176($sp)
+la $19,14
+la $24,15
+sb $24,-117+176($sp)
+la $18,16
+la $24,17
+sb $24,-118+176($sp)
+la $17,18
+la $24,19
+sb $24,-119+176($sp)
+la $16,20
+la $24,21
+sb $24,-120+176($sp)
+la $24,22
+sb $24,-1+176($sp)
+la $24,23
+sb $24,-121+176($sp)
+la $24,24
+sb $24,-2+176($sp)
+la $24,25
+sb $24,-122+176($sp)
+la $24,26
+sb $24,-3+176($sp)
+la $24,27
+sb $24,-123+176($sp)
+la $24,28
+sb $24,-4+176($sp)
+la $24,29
+sb $24,-124+176($sp)
+la $24,30
+sb $24,-5+176($sp)
+la $24,31
+sb $24,-125+176($sp)
+la $24,32
+sb $24,-6+176($sp)
+la $24,33
+sb $24,-126+176($sp)
+la $24,34
+sb $24,-7+176($sp)
+la $24,35
+sb $24,-127+176($sp)
+la $24,36
+sb $24,-128+176($sp)
+la $24,37
+sb $24,-129+176($sp)
+la $24,38
+sb $24,-131+176($sp)
+la $24,-109+176($sp)
+la $15,-130+176($sp)
+subu $15,$24,$15
+sw $15,-96+176($sp)
+la $15,-110+176($sp)
+subu $24,$15,$24
+sw $24,-92+176($sp)
+la $24,-111+176($sp)
+la $15,-110+176($sp)
+subu $24,$24,$15
+sw $24,-88+176($sp)
+la $24,-112+176($sp)
+la $15,-111+176($sp)
+subu $24,$24,$15
+sw $24,-84+176($sp)
+la $24,-113+176($sp)
+la $15,-112+176($sp)
+subu $24,$24,$15
+sw $24,-80+176($sp)
+la $24,-114+176($sp)
+la $15,-113+176($sp)
+subu $24,$24,$15
+sw $24,-76+176($sp)
+la $24,-115+176($sp)
+la $15,-114+176($sp)
+subu $24,$24,$15
+sw $24,-72+176($sp)
+la $24,-116+176($sp)
+la $15,-115+176($sp)
+subu $24,$24,$15
+sw $24,-68+176($sp)
+la $24,-117+176($sp)
+la $15,-116+176($sp)
+subu $24,$24,$15
+sw $24,-64+176($sp)
+la $24,-118+176($sp)
+la $15,-117+176($sp)
+subu $24,$24,$15
+sw $24,-60+176($sp)
+la $24,-119+176($sp)
+la $15,-118+176($sp)
+subu $24,$24,$15
+sw $24,-56+176($sp)
+la $24,-120+176($sp)
+la $15,-119+176($sp)
+subu $24,$24,$15
+sw $24,-52+176($sp)
+la $24,-121+176($sp)
+la $15,-120+176($sp)
+subu $24,$24,$15
+sw $24,-48+176($sp)
+la $24,-122+176($sp)
+la $15,-121+176($sp)
+subu $24,$24,$15
+sw $24,-44+176($sp)
+la $24,-123+176($sp)
+la $15,-122+176($sp)
+subu $24,$24,$15
+sw $24,-40+176($sp)
+la $24,-124+176($sp)
+la $15,-123+176($sp)
+subu $24,$24,$15
+sw $24,-36+176($sp)
+la $24,-125+176($sp)
+la $15,-124+176($sp)
+subu $24,$24,$15
+sw $24,-32+176($sp)
+la $24,-126+176($sp)
+la $15,-125+176($sp)
+subu $24,$24,$15
+sw $24,-28+176($sp)
+la $24,-127+176($sp)
+la $15,-126+176($sp)
+subu $24,$24,$15
+sw $24,-24+176($sp)
+la $24,-128+176($sp)
+la $15,-127+176($sp)
+subu $24,$24,$15
+sw $24,-20+176($sp)
+la $24,-129+176($sp)
+la $15,-128+176($sp)
+subu $24,$24,$15
+sw $24,-16+176($sp)
+la $24,-131+176($sp)
+la $15,-129+176($sp)
+subu $24,$24,$15
+sw $24,-12+176($sp)
+lw $24,-96+176($sp)
+sw $24,-108+176($sp)
+la $24,1
+sw $24,-104+176($sp)
+sw $0,-100+176($sp)
+L.3049:
+lw $24,-104+176($sp)
+la $15,1
+beq $24,$15,L.3055
+la $15,2
+beq $24,$15,L.3058
+la $15,3
+beq $24,$15,L.3063
+b L.3053
+L.3055:
+lw $24,-100+176($sp)
+sll $24,$24,2
+la $15,-96+176($sp)
+addu $24,$24,$15
+lw $24,($24)
+lw $15,-108+176($sp)
+beq $24,$15,L.3054
+la $24,2
+lw $15,-100+176($sp)
+sll $15,$15,2
+la $14,-96+176($sp)
+addu $15,$15,$14
+lw $15,($15)
+sw $15,-140+176($sp)
+sw $24,-104+176($sp)
+la $24,1
+sw $24,-136+176($sp)
+b L.3054
+L.3058:
+lw $24,-100+176($sp)
+sll $24,$24,2
+la $15,-96+176($sp)
+addu $24,$24,$15
+lw $24,($24)
+lw $15,-108+176($sp)
+bne $24,$15,L.3059
+la $24,3
+sw $24,-104+176($sp)
+b L.3054
+L.3059:
+lw $24,-100+176($sp)
+sll $24,$24,2
+la $15,-96+176($sp)
+addu $24,$24,$15
+lw $24,($24)
+lw $15,-140+176($sp)
+bne $24,$15,L.3061
+lw $24,-136+176($sp)
+la $24,1($24)
+sw $24,-136+176($sp)
+b L.3054
+L.3061:
+la $24,4
+sw $24,-104+176($sp)
+b L.3054
+L.3063:
+lw $24,-100+176($sp)
+sll $24,$24,2
+la $15,-96+176($sp)
+addu $24,$24,$15
+lw $24,($24)
+lw $15,-108+176($sp)
+beq $24,$15,L.3054
+la $24,4
+sw $24,-104+176($sp)
+L.3053:
+L.3054:
+L.3050:
+lw $24,-100+176($sp)
+la $24,1($24)
+sw $24,-100+176($sp)
+lw $24,-100+176($sp)
+la $15,22
+blt $24,$15,L.3049
+lw $24,-104+176($sp)
+la $15,3
+bne $24,$15,L.3066
+la $24,16
+lw $15,-136+176($sp)
+subu $2,$24,$15
+b L.3027
+L.3066:
+la $2,-1
+L.3027:
+lw $16,0($sp)
+lw $17,4($sp)
+lw $18,8($sp)
+lw $19,12($sp)
+lw $20,16($sp)
+lw $21,20($sp)
+lw $22,24($sp)
+lw $23,28($sp)
+lw $30,32($sp)
+addu $sp,$sp,176
+j $31
+.end regc
+.globl regi
+.text
+.align 2
+.ent regi
+regi:
+.frame $sp,264,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-264
+.mask 0x40ff0000,-232
+sw $16,0($sp)
+sw $17,4($sp)
+sw $18,8($sp)
+sw $19,12($sp)
+sw $20,16($sp)
+sw $21,20($sp)
+sw $22,24($sp)
+sw $23,28($sp)
+sw $30,32($sp)
+sw $0,-216+264($sp)
+la $24,1
+sw $24,-132+264($sp)
+la $24,2
+sw $24,-136+264($sp)
+la $24,3
+sw $24,-140+264($sp)
+la $30,4
+la $24,5
+sw $24,-144+264($sp)
+la $23,6
+la $24,7
+sw $24,-148+264($sp)
+la $22,8
+la $24,9
+sw $24,-152+264($sp)
+la $21,10
+la $24,11
+sw $24,-156+264($sp)
+la $20,12
+la $24,13
+sw $24,-160+264($sp)
+la $19,14
+la $24,15
+sw $24,-164+264($sp)
+la $18,16
+la $24,17
+sw $24,-168+264($sp)
+la $17,18
+la $24,19
+sw $24,-172+264($sp)
+la $16,20
+la $24,21
+sw $24,-176+264($sp)
+la $24,22
+sw $24,-4+264($sp)
+la $24,23
+sw $24,-180+264($sp)
+la $24,24
+sw $24,-8+264($sp)
+la $24,25
+sw $24,-184+264($sp)
+la $24,26
+sw $24,-12+264($sp)
+la $24,27
+sw $24,-188+264($sp)
+la $24,28
+sw $24,-16+264($sp)
+la $24,29
+sw $24,-192+264($sp)
+la $24,30
+sw $24,-20+264($sp)
+la $24,31
+sw $24,-196+264($sp)
+la $24,32
+sw $24,-24+264($sp)
+la $24,33
+sw $24,-200+264($sp)
+la $24,34
+sw $24,-28+264($sp)
+la $24,35
+sw $24,-204+264($sp)
+la $24,36
+sw $24,-208+264($sp)
+la $24,37
+sw $24,-212+264($sp)
+la $24,38
+sw $24,-220+264($sp)
+la $24,-132+264($sp)
+la $15,4
+la $14,-216+264($sp)
+subu $14,$24,$14
+div $14,$14,$15
+sw $14,-116+264($sp)
+la $14,-136+264($sp)
+subu $24,$14,$24
+div $24,$24,$15
+sw $24,-112+264($sp)
+la $24,-140+264($sp)
+la $15,-136+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-108+264($sp)
+la $24,-144+264($sp)
+la $15,-140+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-104+264($sp)
+la $24,-148+264($sp)
+la $15,-144+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-100+264($sp)
+la $24,-152+264($sp)
+la $15,-148+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-96+264($sp)
+la $24,-156+264($sp)
+la $15,-152+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-92+264($sp)
+la $24,-160+264($sp)
+la $15,-156+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-88+264($sp)
+la $24,-164+264($sp)
+la $15,-160+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-84+264($sp)
+la $24,-168+264($sp)
+la $15,-164+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-80+264($sp)
+la $24,-172+264($sp)
+la $15,-168+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-76+264($sp)
+la $24,-176+264($sp)
+la $15,-172+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-72+264($sp)
+la $24,-180+264($sp)
+la $15,-176+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-68+264($sp)
+la $24,-184+264($sp)
+la $15,-180+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-64+264($sp)
+la $24,-188+264($sp)
+la $15,-184+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-60+264($sp)
+la $24,-192+264($sp)
+la $15,-188+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-56+264($sp)
+la $24,-196+264($sp)
+la $15,-192+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-52+264($sp)
+la $24,-200+264($sp)
+la $15,-196+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-48+264($sp)
+la $24,-204+264($sp)
+la $15,-200+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-44+264($sp)
+la $24,-208+264($sp)
+la $15,-204+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-40+264($sp)
+la $24,-212+264($sp)
+la $15,-208+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-36+264($sp)
+la $24,-220+264($sp)
+la $15,-212+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-32+264($sp)
+lw $24,-116+264($sp)
+sw $24,-128+264($sp)
+la $24,1
+sw $24,-124+264($sp)
+sw $0,-120+264($sp)
+L.3090:
+lw $24,-124+264($sp)
+la $15,1
+beq $24,$15,L.3096
+la $15,2
+beq $24,$15,L.3099
+la $15,3
+beq $24,$15,L.3104
+b L.3094
+L.3096:
+lw $24,-120+264($sp)
+sll $24,$24,2
+la $15,-116+264($sp)
+addu $24,$24,$15
+lw $24,($24)
+lw $15,-128+264($sp)
+beq $24,$15,L.3095
+la $24,2
+lw $15,-120+264($sp)
+sll $15,$15,2
+la $14,-116+264($sp)
+addu $15,$15,$14
+lw $15,($15)
+sw $15,-228+264($sp)
+sw $24,-124+264($sp)
+la $24,1
+sw $24,-224+264($sp)
+b L.3095
+L.3099:
+lw $24,-120+264($sp)
+sll $24,$24,2
+la $15,-116+264($sp)
+addu $24,$24,$15
+lw $24,($24)
+lw $15,-128+264($sp)
+bne $24,$15,L.3100
+la $24,3
+sw $24,-124+264($sp)
+b L.3095
+L.3100:
+lw $24,-120+264($sp)
+sll $24,$24,2
+la $15,-116+264($sp)
+addu $24,$24,$15
+lw $24,($24)
+lw $15,-228+264($sp)
+bne $24,$15,L.3102
+lw $24,-224+264($sp)
+la $24,1($24)
+sw $24,-224+264($sp)
+b L.3095
+L.3102:
+la $24,4
+sw $24,-124+264($sp)
+b L.3095
+L.3104:
+lw $24,-120+264($sp)
+sll $24,$24,2
+la $15,-116+264($sp)
+addu $24,$24,$15
+lw $24,($24)
+lw $15,-128+264($sp)
+beq $24,$15,L.3095
+la $24,4
+sw $24,-124+264($sp)
+L.3094:
+L.3095:
+L.3091:
+lw $24,-120+264($sp)
+la $24,1($24)
+sw $24,-120+264($sp)
+lw $24,-120+264($sp)
+la $15,22
+blt $24,$15,L.3090
+lw $24,-124+264($sp)
+la $15,3
+bne $24,$15,L.3107
+la $24,16
+lw $15,-224+264($sp)
+subu $2,$24,$15
+b L.3068
+L.3107:
+la $2,-1
+L.3068:
+lw $16,0($sp)
+lw $17,4($sp)
+lw $18,8($sp)
+lw $19,12($sp)
+lw $20,16($sp)
+lw $21,20($sp)
+lw $22,24($sp)
+lw $23,28($sp)
+lw $30,32($sp)
+addu $sp,$sp,264
+j $31
+.end regi
+.globl regp
+.text
+.align 2
+.ent regp
+regp:
+.frame $sp,264,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-264
+.mask 0x40ff0000,-232
+sw $16,0($sp)
+sw $17,4($sp)
+sw $18,8($sp)
+sw $19,12($sp)
+sw $20,16($sp)
+sw $21,20($sp)
+sw $22,24($sp)
+sw $23,28($sp)
+sw $30,32($sp)
+la $24,-216+264($sp)
+sw $24,-216+264($sp)
+la $24,-192+264($sp)
+sw $24,-192+264($sp)
+la $24,-196+264($sp)
+sw $24,-196+264($sp)
+la $24,-200+264($sp)
+sw $24,-200+264($sp)
+la $30,-128+264($sp)
+la $24,-128+264($sp)
+sw $24,-128+264($sp)
+la $23,-132+264($sp)
+la $24,-132+264($sp)
+sw $24,-132+264($sp)
+la $22,-136+264($sp)
+la $24,-136+264($sp)
+sw $24,-136+264($sp)
+la $21,-140+264($sp)
+la $24,-140+264($sp)
+sw $24,-140+264($sp)
+la $20,-144+264($sp)
+la $24,-144+264($sp)
+sw $24,-144+264($sp)
+la $19,-148+264($sp)
+la $24,-148+264($sp)
+sw $24,-148+264($sp)
+la $18,-152+264($sp)
+la $24,-152+264($sp)
+sw $24,-152+264($sp)
+la $17,-156+264($sp)
+la $24,-156+264($sp)
+sw $24,-156+264($sp)
+la $16,-160+264($sp)
+la $24,-160+264($sp)
+sw $24,-160+264($sp)
+la $24,-164+264($sp)
+sw $24,-4+264($sp)
+la $24,-164+264($sp)
+sw $24,-164+264($sp)
+la $24,-168+264($sp)
+sw $24,-8+264($sp)
+la $24,-168+264($sp)
+sw $24,-168+264($sp)
+la $24,-172+264($sp)
+sw $24,-12+264($sp)
+la $24,-172+264($sp)
+sw $24,-172+264($sp)
+la $24,-176+264($sp)
+sw $24,-16+264($sp)
+la $24,-176+264($sp)
+sw $24,-176+264($sp)
+la $24,-180+264($sp)
+sw $24,-20+264($sp)
+la $24,-180+264($sp)
+sw $24,-180+264($sp)
+la $24,-184+264($sp)
+sw $24,-24+264($sp)
+la $24,-184+264($sp)
+sw $24,-184+264($sp)
+la $24,-188+264($sp)
+sw $24,-28+264($sp)
+la $24,-188+264($sp)
+sw $24,-188+264($sp)
+la $24,-204+264($sp)
+sw $24,-204+264($sp)
+la $24,-208+264($sp)
+sw $24,-208+264($sp)
+la $24,-220+264($sp)
+sw $24,-220+264($sp)
+la $24,-192+264($sp)
+la $15,4
+la $14,-216+264($sp)
+subu $14,$24,$14
+div $14,$14,$15
+sw $14,-116+264($sp)
+la $14,-196+264($sp)
+subu $24,$14,$24
+div $24,$24,$15
+sw $24,-112+264($sp)
+la $24,-200+264($sp)
+la $15,-196+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-108+264($sp)
+la $24,-128+264($sp)
+la $15,-200+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-104+264($sp)
+la $24,-132+264($sp)
+la $15,-128+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-100+264($sp)
+la $24,-136+264($sp)
+la $15,-132+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-96+264($sp)
+la $24,-140+264($sp)
+la $15,-136+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-92+264($sp)
+la $24,-144+264($sp)
+la $15,-140+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-88+264($sp)
+la $24,-148+264($sp)
+la $15,-144+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-84+264($sp)
+la $24,-152+264($sp)
+la $15,-148+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-80+264($sp)
+la $24,-156+264($sp)
+la $15,-152+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-76+264($sp)
+la $24,-160+264($sp)
+la $15,-156+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-72+264($sp)
+la $24,-164+264($sp)
+la $15,-160+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-68+264($sp)
+la $24,-168+264($sp)
+la $15,-164+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-64+264($sp)
+la $24,-172+264($sp)
+la $15,-168+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-60+264($sp)
+la $24,-176+264($sp)
+la $15,-172+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-56+264($sp)
+la $24,-180+264($sp)
+la $15,-176+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-52+264($sp)
+la $24,-184+264($sp)
+la $15,-180+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-48+264($sp)
+la $24,-188+264($sp)
+la $15,-184+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-44+264($sp)
+la $24,-204+264($sp)
+la $15,-188+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-40+264($sp)
+la $24,-208+264($sp)
+la $15,-204+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-36+264($sp)
+la $24,-220+264($sp)
+la $15,-208+264($sp)
+subu $24,$24,$15
+la $15,4
+div $24,$24,$15
+sw $24,-32+264($sp)
+lw $24,-116+264($sp)
+sw $24,-212+264($sp)
+la $24,1
+sw $24,-124+264($sp)
+sw $0,-120+264($sp)
+L.3131:
+lw $24,-124+264($sp)
+la $15,1
+beq $24,$15,L.3137
+la $15,2
+beq $24,$15,L.3140
+la $15,3
+beq $24,$15,L.3145
+b L.3135
+L.3137:
+lw $24,-120+264($sp)
+sll $24,$24,2
+la $15,-116+264($sp)
+addu $24,$24,$15
+lw $24,($24)
+lw $15,-212+264($sp)
+beq $24,$15,L.3136
+la $24,2
+lw $15,-120+264($sp)
+sll $15,$15,2
+la $14,-116+264($sp)
+addu $15,$15,$14
+lw $15,($15)
+sw $15,-228+264($sp)
+sw $24,-124+264($sp)
+la $24,1
+sw $24,-224+264($sp)
+b L.3136
+L.3140:
+lw $24,-120+264($sp)
+sll $24,$24,2
+la $15,-116+264($sp)
+addu $24,$24,$15
+lw $24,($24)
+lw $15,-212+264($sp)
+bne $24,$15,L.3141
+la $24,3
+sw $24,-124+264($sp)
+b L.3136
+L.3141:
+lw $24,-120+264($sp)
+sll $24,$24,2
+la $15,-116+264($sp)
+addu $24,$24,$15
+lw $24,($24)
+lw $15,-228+264($sp)
+bne $24,$15,L.3143
+lw $24,-224+264($sp)
+la $24,1($24)
+sw $24,-224+264($sp)
+b L.3136
+L.3143:
+la $24,4
+sw $24,-124+264($sp)
+b L.3136
+L.3145:
+lw $24,-120+264($sp)
+sll $24,$24,2
+la $15,-116+264($sp)
+addu $24,$24,$15
+lw $24,($24)
+lw $15,-212+264($sp)
+beq $24,$15,L.3136
+la $24,4
+sw $24,-124+264($sp)
+L.3135:
+L.3136:
+L.3132:
+lw $24,-120+264($sp)
+la $24,1($24)
+sw $24,-120+264($sp)
+lw $24,-120+264($sp)
+la $15,22
+blt $24,$15,L.3131
+lw $24,-124+264($sp)
+la $15,3
+bne $24,$15,L.3148
+la $24,16
+lw $15,-224+264($sp)
+subu $2,$24,$15
+b L.3109
+L.3148:
+la $2,-1
+L.3109:
+lw $16,0($sp)
+lw $17,4($sp)
+lw $18,8($sp)
+lw $19,12($sp)
+lw $20,16($sp)
+lw $21,20($sp)
+lw $22,24($sp)
+lw $23,28($sp)
+lw $30,32($sp)
+addu $sp,$sp,264
+j $31
+.end regp
+.lcomm L.3151,420
+.data
+.align 0
+L.3152:
+.byte 115
+.byte 56
+.byte 52
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.sdata
+.align 0
+L.3153:
+.byte 115
+.byte 56
+.byte 52
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s84
+.text
+.text
+.align 2
+.ent s84
+s84:
+.frame $sp,216,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-216
+.fmask 0xc0000000,-200
+.mask 0xc2fc0000,-160
+s.d $f30,16($sp)
+sw $18,24($sp)
+sw $19,28($sp)
+sw $20,32($sp)
+sw $21,36($sp)
+sw $22,40($sp)
+sw $23,44($sp)
+.cprestore 48
+sw $30,52($sp)
+sw $31,56($sp)
+move $30,$4
+la $20,L.3153
+la $19,60($30)
+move $18,$0
+L.3154:
+L.3155:
+move $24,$19
+la $19,1($24)
+move $15,$20
+la $20,1($15)
+lb $15,($15)
+sb $15,($24)
+sll $24,$15,8*(4-1); sra $24,$24,8*(4-1)
+bne $24,$0,L.3154
+la $4,3
+jal fip
+sw $2,-140+216($sp)
+lw $24,-140+216($sp)
+lw $24,($24)
+la $15,3
+beq $24,$15,L.3157
+lw $24,44($30)
+beq $24,$0,L.3159
+la $4,L.3152
+la $5,1
+jal printf
+L.3159:
+la $18,1($18)
+L.3157:
+la $24,glork
+sw $24,-144+216($sp)
+la $4,4
+lw $25,-144+216($sp)
+jal $25
+la $15,4
+beq $2,$15,L.3161
+lw $24,44($30)
+beq $24,$0,L.3163
+la $4,L.3152
+la $5,2
+jal printf
+L.3163:
+la $18,2($18)
+L.3161:
+move $22,$0
+L.3165:
+sll $24,$22,2
+la $15,-68+216($sp)
+addu $24,$24,$15
+mtc1 $22,$f18; cvt.s.w $f18,$f18
+s.s $f18,($24)
+sll $24,$22,2
+la $15,-136+216($sp)
+addu $15,$24,$15
+la $14,-68+216($sp)
+addu $24,$24,$14
+sw $24,($15)
+L.3166:
+la $22,1($22)
+la $24,17
+blt $22,$24,L.3165
+l.s $f30,L.412
+move $22,$0
+L.3169:
+sll $24,$22,2
+la $15,-136+216($sp)
+addu $24,$24,$15
+lw $24,($24)
+l.s $f18,($24)
+add.s $f30,$f30,$f18
+L.3170:
+la $22,1($22)
+la $24,17
+blt $22,$24,L.3169
+l.s $f18,L.3175
+c.eq.s $f30,$f18; bc1t L.3173
+lw $24,44($30)
+beq $24,$0,L.3176
+la $4,L.3152
+la $5,4
+jal printf
+L.3176:
+la $18,4($18)
+L.3173:
+move $21,$0
+L.3178:
+move $22,$0
+L.3182:
+move $23,$0
+L.3186:
+sll $24,$23,2
+la $15,28
+mul $15,$15,$22
+la $14,140
+mul $14,$14,$21
+la $14,L.3151($14)
+addu $15,$15,$14
+addu $24,$24,$15
+la $15,35
+mul $15,$15,$21
+la $14,7
+mul $14,$14,$22
+addu $15,$15,$14
+addu $15,$15,$23
+sw $15,($24)
+L.3187:
+la $23,1($23)
+la $24,7
+blt $23,$24,L.3186
+L.3183:
+la $22,1($22)
+la $24,5
+blt $22,$24,L.3182
+L.3179:
+la $21,1($21)
+la $24,3
+blt $21,$24,L.3178
+la $21,1
+la $22,2
+la $23,3
+la $4,L.3151
+la $5,105
+move $6,$0
+jal array
+move $24,$2
+sw $24,-148+216($sp)
+la $15,140
+mul $15,$15,$21
+la $4,L.3151($15)
+la $15,35
+move $5,$15
+move $6,$15
+jal array
+move $24,$2
+sw $24,-152+216($sp)
+la $15,28
+mul $15,$15,$22
+la $14,140
+mul $14,$14,$21
+la $14,L.3151($14)
+addu $4,$15,$14
+la $5,7
+la $6,49
+jal array
+lw $15,-148+216($sp)
+lw $14,-152+216($sp)
+addu $15,$15,$14
+addu $24,$15,$2
+sll $15,$23,2
+la $14,28
+mul $14,$14,$22
+la $13,140
+mul $13,$13,$21
+la $13,L.3151($13)
+addu $14,$14,$13
+addu $15,$15,$14
+lw $15,($15)
+addu $24,$24,$15
+subu $24,$24,52
+beq $24,$0,L.3190
+lw $24,44($30)
+beq $24,$0,L.3192
+la $4,L.3152
+la $5,8
+jal printf
+L.3192:
+la $18,8($18)
+L.3190:
+move $2,$18
+L.3150:
+l.d $f30,16($sp)
+lw $18,24($sp)
+lw $19,28($sp)
+lw $20,32($sp)
+lw $21,36($sp)
+lw $22,40($sp)
+lw $23,44($sp)
+lw $25,48($sp)
+lw $30,52($sp)
+lw $31,56($sp)
+addu $sp,$sp,216
+j $31
+.end s84
+.globl array
+.text
+.align 2
+.ent array
+array:
+.frame $sp,8,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-8
+.mask 0x40000000,-8
+sw $30,0($sp)
+move $30,$0
+b L.3198
+L.3195:
+sll $24,$30,2
+addu $24,$24,$4
+lw $24,($24)
+addu $15,$30,$6
+beq $24,$15,L.3199
+la $2,1
+b L.3194
+L.3199:
+L.3196:
+la $30,1($30)
+L.3198:
+blt $30,$5,L.3195
+move $2,$0
+L.3194:
+lw $30,0($sp)
+addu $sp,$sp,8
+j $31
+.end array
+.lcomm L.3202,4
+.globl fip
+.text
+.text
+.align 2
+.ent fip
+fip:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+la $24,L.3202
+sw $4,L.3202
+move $2,$24
+L.3201:
+j $31
+.end fip
+.globl glork
+.text
+.align 2
+.ent glork
+glork:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+move $2,$4
+L.3203:
+j $31
+.end glork
+.data
+.align 0
+L.3205:
+.byte 115
+.byte 56
+.byte 53
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.sdata
+.align 0
+L.3206:
+.byte 115
+.byte 56
+.byte 53
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.data
+.align 2
+L.3214:
+.word L.425
+.word L.427
+.word L.426
+.word L.428
+.word L.429
+.word L.430
+.word L.431
+.data
+.align 0
+L.3215:
+.byte 32
+.byte 97
+.byte 108
+.byte 105
+.byte 103
+.byte 110
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 58
+.byte 32
+.byte 0
+.globl s85
+.text
+.text
+.align 2
+.ent s85
+s85:
+.frame $sp,440,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-440
+.mask 0xc2f00000,-400
+sw $20,16($sp)
+sw $21,20($sp)
+sw $22,24($sp)
+sw $23,28($sp)
+.cprestore 32
+sw $30,36($sp)
+sw $31,40($sp)
+move $30,$4
+la $22,L.3206
+la $21,60($30)
+move $20,$0
+L.3219:
+L.3220:
+move $24,$21
+la $21,1($24)
+move $15,$22
+la $22,1($15)
+lb $15,($15)
+sb $15,($24)
+sll $24,$15,8*(4-1); sra $24,$24,8*(4-1)
+bne $24,$0,L.3219
+la $15,-284+440($sp)
+la $14,-304+440($sp)
+subu $15,$15,$14
+ble $15,$0,L.3230
+la $15,-280+440($sp)
+la $14,-284+440($sp)
+subu $15,$15,$14
+ble $15,$0,L.3230
+la $15,-276+440($sp)
+la $14,-280+440($sp)
+subu $15,$15,$14
+bgt $15,$0,L.3222
+L.3230:
+lw $24,44($30)
+beq $24,$0,L.3231
+la $4,L.3205
+la $5,1
+jal printf
+L.3231:
+la $20,1($20)
+L.3222:
+la $24,-337+440($sp)
+la $15,-338+440($sp)
+subu $24,$24,$15
+sw $24,-268+440($sp)
+la $24,-340+440($sp)
+la $15,-342+440($sp)
+subu $24,$24,$15
+sw $24,-264+440($sp)
+la $24,-348+440($sp)
+la $15,-352+440($sp)
+subu $24,$24,$15
+sw $24,-260+440($sp)
+la $24,-356+440($sp)
+la $15,-360+440($sp)
+subu $24,$24,$15
+sw $24,-256+440($sp)
+la $24,-364+440($sp)
+la $15,-368+440($sp)
+subu $24,$24,$15
+sw $24,-252+440($sp)
+la $24,-372+440($sp)
+la $15,-376+440($sp)
+subu $24,$24,$15
+sw $24,-248+440($sp)
+la $24,-384+440($sp)
+la $15,-392+440($sp)
+subu $24,$24,$15
+sw $24,-244+440($sp)
+lw $24,40($30)
+beq $24,$0,L.3246
+move $23,$0
+L.3248:
+la $4,L.3252
+sll $24,$23,2
+lw $5,L.3214($24)
+la $6,L.3215
+la $15,-268+440($sp)
+addu $24,$24,$15
+lw $7,($24)
+jal printf
+L.3249:
+la $23,1($23)
+la $24,7
+blt $23,$24,L.3248
+L.3246:
+lw $24,-272+440($sp)
+or $24,$24,0x1c000000
+sw $24,-272+440($sp)
+lw $24,-272+440($sp)
+move $15,$24
+and $15,$15,0x3fffffff
+sll $24,$24,3
+sra $24,$24,29
+sll $24,$24,30
+sra $24,$24,30
+sll $24,$24,30
+and $24,$24,0xc0000000
+or $24,$15,$24
+sw $24,-272+440($sp)
+lw $24,-272+440($sp)
+move $15,$24
+and $15,$15,0xe3ffffff
+sra $24,$24,30
+sll $24,$24,29
+sra $24,$24,29
+sll $24,$24,26
+and $24,$24,0x1c000000
+or $24,$15,$24
+sw $24,-272+440($sp)
+la $24,3
+lw $15,-272+440($sp)
+sll $15,$15,3
+sra $15,$15,29
+beq $15,$24,L.3253
+lw $24,-272+440($sp)
+sll $24,$24,3
+sra $24,$24,29
+la $15,-1
+bne $24,$15,L.3255
+lw $24,40($30)
+beq $24,$0,L.3256
+la $4,L.3259
+jal printf
+b L.3256
+L.3255:
+lw $24,44($30)
+beq $24,$0,L.3260
+la $4,L.3205
+la $5,2
+jal printf
+L.3260:
+la $20,2($20)
+L.3256:
+L.3253:
+lw $24,-272+440($sp)
+or $24,$24,0x2000000
+sw $24,-272+440($sp)
+lw $24,-272+440($sp)
+sll $24,$24,6
+sra $24,$24,31
+la $15,1
+beq $24,$15,L.3262
+lw $24,40($30)
+beq $24,$0,L.3264
+la $4,L.3266
+jal printf
+L.3264:
+L.3262:
+la $24,-240+440($sp)
+subu $24,$24,$24
+bne $24,$0,L.3274
+bne $24,$0,L.3274
+bne $24,$0,L.3274
+bne $24,$0,L.3274
+bne $24,$0,L.3274
+bne $24,$0,L.3274
+beq $24,$0,L.3267
+L.3274:
+lw $24,44($30)
+beq $24,$0,L.3275
+la $4,L.3205
+la $5,4
+jal printf
+L.3275:
+la $20,4($20)
+L.3267:
+b L.3277
+lw $24,44($30)
+beq $24,$0,L.3279
+la $4,L.3205
+la $5,8
+jal printf
+L.3279:
+la $20,8($20)
+L.3277:
+la $24,-336+440($sp)
+sw $24,-276+440($sp)
+la $24,2
+sb $24,-336+440($sp)
+lw $24,-276+440($sp)
+lb $15,($24)
+la $15,1($15)
+sb $15,($24)
+lb $24,-336+440($sp)
+la $15,3
+beq $24,$15,L.3283
+lw $24,44($30)
+beq $24,$0,L.3285
+la $4,L.3205
+la $5,16
+jal printf
+L.3285:
+la $20,16($20)
+L.3283:
+move $2,$20
+L.3204:
+lw $20,16($sp)
+lw $21,20($sp)
+lw $22,24($sp)
+lw $23,28($sp)
+lw $25,32($sp)
+lw $30,36($sp)
+lw $31,40($sp)
+addu $sp,$sp,440
+j $31
+.end s85
+.data
+.align 0
+L.3288:
+.byte 115
+.byte 56
+.byte 54
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.sdata
+.align 0
+L.3289:
+.byte 115
+.byte 56
+.byte 54
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.data
+.align 2
+L.3290:
+.word 0x1
+.word 0x3
+.word 0x5
+.sdata
+.align 2
+L.3291:
+.word L.3290+8
+.lcomm L.3293,40
+.data
+.align 2
+L.3294:
+.word 0x3f800000
+.word 0x40400000
+.word 0x40a00000
+.word 0x40000000
+.word 0x40800000
+.word 0x40c00000
+.word 0x40400000
+.word 0x40a00000
+.word 0x40e00000
+.word 0x0
+.word 0x0
+.word 0x0
+.data
+.align 2
+L.3295:
+.word 0x3f800000
+.word 0x40400000
+.word 0x40a00000
+.word 0x40000000
+.word 0x40800000
+.word 0x40c00000
+.word 0x40400000
+.word 0x40a00000
+.word 0x40e00000
+.space 12
+.data
+.align 2
+L.3296:
+.word 0x3f800000
+.word 0x40400000
+.word 0x40a00000
+.word 0x40000000
+.word 0x40800000
+.word 0x40c00000
+.word 0x40400000
+.word 0x40a00000
+.word 0x40e00000
+.space 12
+.data
+.align 2
+L.3297:
+.word 0x3f800000
+.space 8
+.word 0x40000000
+.space 8
+.word 0x40400000
+.space 8
+.word 0x40800000
+.space 8
+.globl s86
+.text
+.text
+.align 2
+.ent s86
+s86:
+.frame $sp,64,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-64
+.mask 0xc2ff0000,-8
+sw $16,16($sp)
+sw $17,20($sp)
+sw $18,24($sp)
+sw $19,28($sp)
+sw $20,32($sp)
+sw $21,36($sp)
+sw $22,40($sp)
+sw $23,44($sp)
+.cprestore 48
+sw $30,52($sp)
+sw $31,56($sp)
+sw $4,64($sp)
+lw $24,L.3291
+la $16,-4($24)
+jal one
+sll $24,$2,2
+addu $30,$24,$16
+la $19,L.3289
+lw $24,0+64($sp)
+la $18,60($24)
+move $17,$0
+L.3298:
+L.3299:
+move $24,$18
+la $18,1($24)
+move $15,$19
+la $19,1($15)
+lb $15,($15)
+sb $15,($24)
+sll $24,$15,8*(4-1); sra $24,$24,8*(4-1)
+bne $24,$0,L.3298
+lw $24,L.3291
+lw $24,($24)
+la $15,5
+beq $24,$15,L.3301
+lw $24,0+64($sp)
+lw $24,44($24)
+beq $24,$0,L.3303
+la $4,L.3288
+la $5,1
+jal printf
+L.3303:
+la $17,1($17)
+L.3301:
+lw $24,($16)
+la $15,3
+beq $24,$15,L.3305
+lw $24,0+64($sp)
+lw $24,44($24)
+beq $24,$0,L.3307
+la $4,L.3288
+la $5,2
+jal printf
+L.3307:
+la $17,2($17)
+L.3305:
+lw $24,($30)
+la $15,5
+beq $24,$15,L.3309
+lw $24,0+64($sp)
+lw $24,44($24)
+beq $24,$0,L.3311
+la $4,L.3288
+la $5,4
+jal printf
+L.3311:
+la $17,4($17)
+L.3309:
+move $20,$0
+move $23,$0
+L.3313:
+sll $24,$23,2
+lw $24,L.3293($24)
+beq $24,$0,L.3317
+la $20,1
+L.3317:
+L.3314:
+la $23,1($23)
+la $24,10
+blt $23,$24,L.3313
+beq $20,$0,L.3319
+lw $24,0+64($sp)
+lw $24,44($24)
+beq $24,$0,L.3321
+la $4,L.3288
+la $5,8
+jal printf
+L.3321:
+la $17,8($17)
+L.3319:
+move $20,$0
+move $22,$0
+L.3323:
+move $23,$0
+L.3327:
+la $24,3
+mul $24,$24,$22
+addu $21,$24,$23
+sll $24,$23,2
+la $15,12
+mul $15,$15,$22
+la $14,L.3295($15)
+addu $14,$24,$14
+l.s $f18,($14)
+la $15,L.3296($15)
+addu $24,$24,$15
+l.s $f16,($24)
+c.eq.s $f18,$f16; bc1f L.3333
+sll $24,$21,2
+l.s $f16,L.3294($24)
+c.eq.s $f18,$f16; bc1t L.3331
+L.3333:
+la $20,1
+L.3331:
+L.3328:
+la $23,1($23)
+la $24,3
+blt $23,$24,L.3327
+L.3324:
+la $22,1($22)
+la $24,4
+blt $22,$24,L.3323
+beq $20,$0,L.3334
+lw $24,0+64($sp)
+lw $24,44($24)
+beq $24,$0,L.3336
+la $4,L.3288
+la $5,16
+jal printf
+L.3336:
+la $17,16($17)
+L.3334:
+move $20,$0
+move $23,$0
+L.3338:
+la $24,12
+mul $24,$24,$23
+l.s $f18,L.3297($24)
+la $24,1($23)
+mtc1 $24,$f16; cvt.s.w $f16,$f16
+c.eq.s $f18,$f16; bc1t L.3342
+la $20,1
+L.3342:
+L.3339:
+la $23,1($23)
+la $24,4
+blt $23,$24,L.3338
+beq $20,$0,L.3344
+lw $24,0+64($sp)
+lw $24,44($24)
+beq $24,$0,L.3346
+la $4,L.3288
+la $5,32
+jal printf
+L.3346:
+la $17,32($17)
+L.3344:
+move $2,$17
+L.3287:
+lw $16,16($sp)
+lw $17,20($sp)
+lw $18,24($sp)
+lw $19,28($sp)
+lw $20,32($sp)
+lw $21,36($sp)
+lw $22,40($sp)
+lw $23,44($sp)
+lw $25,48($sp)
+lw $30,52($sp)
+lw $31,56($sp)
+addu $sp,$sp,64
+j $31
+.end s86
+.globl one
+.text
+.align 2
+.ent one
+one:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+la $2,1
+L.3348:
+j $31
+.end one
+.data
+.align 0
+L.3350:
+.byte 115
+.byte 56
+.byte 56
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.sdata
+.align 0
+L.3351:
+.byte 115
+.byte 56
+.byte 56
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s88
+.text
+.text
+.align 2
+.ent s88
+s88:
+.frame $sp,64,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-64
+.mask 0xc2e00000,-28
+sw $21,16($sp)
+sw $22,20($sp)
+sw $23,24($sp)
+.cprestore 28
+sw $30,32($sp)
+sw $31,36($sp)
+sw $4,64($sp)
+la $30,L.3351
+lw $24,0+64($sp)
+la $23,60($24)
+move $22,$0
+L.3353:
+L.3354:
+move $24,$23
+la $23,1($24)
+move $15,$30
+la $30,1($15)
+lb $15,($15)
+sb $15,($24)
+sll $24,$15,8*(4-1); sra $24,$24,8*(4-1)
+bne $24,$0,L.3353
+b L.3356
+lw $24,0+64($sp)
+lw $24,44($24)
+beq $24,$0,L.3358
+la $4,L.3350
+la $5,1
+jal printf
+L.3358:
+la $22,1($22)
+L.3356:
+la $24,-20+64($sp)
+sw $24,metricp
+la $24,2
+sw $24,-20+64($sp)
+lw $24,metricp
+la $15,3
+sw $15,($24)
+lw $24,-20+64($sp)
+la $15,3
+beq $24,$15,L.3360
+lw $24,0+64($sp)
+lw $24,44($24)
+beq $24,$0,L.3362
+la $4,L.3350
+la $5,2
+jal printf
+L.3362:
+la $22,2($22)
+L.3360:
+l.d $f18,L.419
+s.d $f18,-16+64($sp)
+s.d $f18,-8+64($sp)
+la $21,-16+64($sp)
+l.d $f18,L.418
+s.d $f18,($21)
+l.d $f18,L.418
+s.d $f18,8($21)
+l.d $f18,-16+64($sp)
+l.d $f16,-8+64($sp)
+add.d $f18,$f18,$f16
+l.d $f16,L.416
+c.eq.d $f18,$f16; bc1t L.3365
+lw $24,0+64($sp)
+lw $24,44($24)
+beq $24,$0,L.3368
+la $4,L.3350
+la $5,4
+jal printf
+L.3368:
+la $22,4($22)
+L.3365:
+move $2,$22
+L.3349:
+lw $21,16($sp)
+lw $22,20($sp)
+lw $23,24($sp)
+lw $25,28($sp)
+lw $30,32($sp)
+lw $31,36($sp)
+addu $sp,$sp,64
+j $31
+.end s88
+.data
+.align 0
+L.3371:
+.byte 115
+.byte 57
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.sdata
+.align 0
+L.3372:
+.byte 115
+.byte 57
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s9
+.text
+.text
+.align 2
+.ent s9
+s9:
+.frame $sp,64,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-64
+.mask 0xc2ff0000,-8
+sw $16,16($sp)
+sw $17,20($sp)
+sw $18,24($sp)
+sw $19,28($sp)
+sw $20,32($sp)
+sw $21,36($sp)
+sw $22,40($sp)
+sw $23,44($sp)
+.cprestore 48
+sw $30,52($sp)
+sw $31,56($sp)
+sw $4,64($sp)
+la $22,L.3372
+lw $24,0+64($sp)
+la $21,60($24)
+move $20,$0
+L.3373:
+L.3374:
+move $24,$21
+la $21,1($24)
+move $15,$22
+la $22,1($15)
+lb $15,($15)
+sb $15,($24)
+sll $24,$15,8*(4-1); sra $24,$24,8*(4-1)
+bne $24,$0,L.3373
+move $23,$0
+move $30,$0
+L.3376:
+la $24,2
+move $19,$24
+move $18,$24
+la $24,3
+move $17,$24
+move $16,$24
+la $24,3
+bne $16,$24,L.3382
+beq $17,$24,L.3380
+L.3382:
+la $23,1
+L.3380:
+la $24,2
+bne $18,$24,L.3385
+beq $19,$24,L.3383
+L.3385:
+la $23,1
+L.3383:
+L.3377:
+la $30,1($30)
+la $24,2
+blt $30,$24,L.3376
+beq $23,$0,L.3390
+lw $24,0+64($sp)
+lw $24,44($24)
+beq $24,$0,L.3388
+la $4,L.3371
+la $5,1
+jal printf
+L.3388:
+la $20,1($20)
+b L.3390
+lw $24,0+64($sp)
+lw $24,44($24)
+beq $24,$0,L.3391
+la $4,L.3371
+la $5,2
+jal printf
+L.3391:
+la $20,2($20)
+L.3390:
+move $2,$20
+L.3370:
+lw $16,16($sp)
+lw $17,20($sp)
+lw $18,24($sp)
+lw $19,28($sp)
+lw $20,32($sp)
+lw $21,36($sp)
+lw $22,40($sp)
+lw $23,44($sp)
+lw $25,48($sp)
+lw $30,52($sp)
+lw $31,56($sp)
+addu $sp,$sp,64
+j $31
+.end s9
+.globl setev
+.text
+.align 2
+.ent setev
+setev:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+la $24,1066
+sw $24,extvar
+move $2,$0
+L.3393:
+j $31
+.end setev
+.globl rfs
+.comm rfs,8
+.globl crc
+.comm crc,4
+.globl rrc
+.comm rrc,4
+.globl flgl
+.comm flgl,4
+.globl flgd
+.comm flgd,4
+.globl flgm
+.comm flgm,4
+.globl flgs
+.comm flgs,4
+.globl dprec
+.comm dprec,4
+.globl fprec
+.comm fprec,4
+.globl dbits
+.comm dbits,4
+.globl fbits
+.comm fbits,4
+.globl ubits
+.comm ubits,4
+.globl lbits
+.comm lbits,4
+.globl metricp
+.comm metricp,4
+.globl extvar
+.comm extvar,4
+.rdata
+.align 0
+L.3266:
+.byte 66
+.byte 101
+.byte 32
+.byte 101
+.byte 115
+.byte 112
+.byte 101
+.byte 99
+.byte 105
+.byte 97
+.byte 108
+.byte 108
+.byte 121
+.byte 32
+.byte 99
+.byte 97
+.byte 114
+.byte 101
+.byte 102
+.byte 117
+.byte 108
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 49
+.byte 45
+.byte 98
+.byte 105
+.byte 116
+.byte 32
+.byte 102
+.byte 105
+.byte 101
+.byte 108
+.byte 100
+.byte 115
+.byte 33
+.byte 10
+.byte 0
+.align 0
+L.3259:
+.byte 83
+.byte 105
+.byte 103
+.byte 110
+.byte 32
+.byte 101
+.byte 120
+.byte 116
+.byte 101
+.byte 110
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 102
+.byte 105
+.byte 101
+.byte 108
+.byte 100
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.3252:
+.byte 37
+.byte 115
+.byte 37
+.byte 115
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 2
+L.3175:
+.word 0x43080000
+.align 0
+L.3022:
+.byte 112
+.byte 111
+.byte 105
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 0
+.align 0
+L.2472:
+.byte 73
+.byte 110
+.byte 99
+.byte 114
+.byte 101
+.byte 97
+.byte 115
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 97
+.byte 114
+.byte 114
+.byte 97
+.byte 121
+.byte 32
+.byte 101
+.byte 108
+.byte 101
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 97
+.byte 115
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 101
+.byte 100
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 100
+.byte 101
+.byte 99
+.byte 114
+.byte 101
+.byte 97
+.byte 115
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 108
+.byte 111
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 10
+.byte 0
+.align 2
+L.2356:
+.word 0x41d00000
+.align 3
+L.2355:
+.word 0x403a0000
+.word 0x0
+.align 3
+L.1659:
+.word 0x40040000
+.word 0x0
+.align 3
+L.1484:
+.word 0x40240000
+.word 0x0
+.align 2
+L.1455:
+.word 0x41200000
+.align 3
+L.1280:
+.word 0x40080000
+.word 0x0
+.align 2
+L.1251:
+.word 0x40400000
+.align 3
+L.1076:
+.word 0x401c0000
+.word 0x0
+.align 2
+L.1047:
+.word 0x40e00000
+.align 3
+L.870:
+.word 0x40140000
+.word 0x0
+.align 2
+L.841:
+.word 0x40a00000
+.align 3
+L.836:
+.word 0x41e00000
+.word 0x0
+.align 2
+L.828:
+.word 0x4f000000
+.align 0
+L.653:
+.byte 113
+.byte 117
+.byte 101
+.byte 101
+.byte 112
+.byte 0
+.align 0
+L.639:
+.byte 10
+.byte 0
+.align 0
+L.638:
+.byte 37
+.byte 100
+.byte 0
+.align 0
+L.633:
+.byte 32
+.byte 32
+.byte 32
+.byte 107
+.byte 101
+.byte 121
+.byte 61
+.byte 0
+.align 3
+L.596:
+.word 0x40000000
+.word 0x0
+.align 3
+L.536:
+.word 0x40ce8480
+.word 0x0
+.align 3
+L.535:
+.word 0x405f4000
+.word 0x0
+.align 2
+L.534:
+.word 0x42fa0000
+.align 2
+L.529:
+.word 0x40000000
+.align 0
+L.431:
+.byte 100
+.byte 111
+.byte 117
+.byte 98
+.byte 108
+.byte 101
+.byte 0
+.align 0
+L.430:
+.byte 102
+.byte 108
+.byte 111
+.byte 97
+.byte 116
+.byte 0
+.align 0
+L.429:
+.byte 117
+.byte 110
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 101
+.byte 100
+.byte 0
+.align 0
+L.428:
+.byte 108
+.byte 111
+.byte 110
+.byte 103
+.byte 0
+.align 0
+L.427:
+.byte 115
+.byte 104
+.byte 111
+.byte 114
+.byte 116
+.byte 0
+.align 0
+L.426:
+.byte 105
+.byte 110
+.byte 116
+.byte 0
+.align 0
+L.425:
+.byte 99
+.byte 104
+.byte 97
+.byte 114
+.byte 0
+.align 3
+L.419:
+.word 0x0
+.word 0x0
+.align 3
+L.418:
+.word 0x3ff00000
+.word 0x0
+.align 3
+L.417:
+.word 0x40100000
+.word 0x0
+.align 3
+L.416:
+.word 0x40000000
+.word 0x0
+.align 2
+L.412:
+.word 0x0
+.align 2
+L.411:
+.word 0x3f800000
+.align 0
+L.390:
+.byte 113
+.byte 117
+.byte 101
+.byte 101
+.byte 112
+.byte 33
+.byte 0
+.align 0
+L.379:
+.byte 10
+.byte 9
+.byte 8
+.byte 13
+.byte 12
+.byte 92
+.byte 39
+.byte 0
+.align 0
+L.375:
+.byte 46
+.byte 34
+.byte 46
+.byte 0
+.align 0
+L.362:
+.byte 46
+.byte 46
+.byte 46
+.byte 0
+.align 3
+L.333:
+.word 0x40938800
+.word 0x0
+.align 0
+L.199:
+.byte 32
+.byte 32
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 114
+.byte 101
+.byte 115
+.byte 117
+.byte 108
+.byte 116
+.byte 115
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 110
+.byte 32
+.byte 97
+.byte 115
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 101
+.byte 100
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 108
+.byte 111
+.byte 110
+.byte 103
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.198:
+.byte 68
+.byte 101
+.byte 99
+.byte 105
+.byte 109
+.byte 97
+.byte 108
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 111
+.byte 99
+.byte 116
+.byte 97
+.byte 108
+.byte 47
+.byte 104
+.byte 101
+.byte 120
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 115
+.byte 116
+.byte 97
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 115
+.byte 111
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 109
+.byte 101
+.byte 115
+.byte 32
+.byte 103
+.byte 105
+.byte 118
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.27:
+.byte 10
+.byte 70
+.byte 97
+.byte 105
+.byte 108
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.26:
+.byte 10
+.byte 78
+.byte 111
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 115
+.byte 32
+.byte 100
+.byte 101
+.byte 116
+.byte 101
+.byte 99
+.byte 116
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.20:
+.byte 83
+.byte 101
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 37
+.byte 115
+.byte 32
+.byte 114
+.byte 101
+.byte 116
+.byte 117
+.byte 114
+.byte 110
+.byte 101
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 46
+.byte 10
+.byte 0
diff --git a/lcc/mips/irix/tst/cvt.1bk b/lcc/mips/irix/tst/cvt.1bk
new file mode 100755
index 0000000..74c79f1
--- /dev/null
+++ b/lcc/mips/irix/tst/cvt.1bk
@@ -0,0 +1,11 @@
+1 1 1 1 1 1 1 1 1.000000 1.000000 1.000000
+2 2 2 2 2 2 2 2 2.000000 2.000000 2.000000
+3 3 3 3 3 3 3 3 3.000000 3.000000 3.000000
+4 4 4 4 4 4 4 4 4.000000 4.000000 4.000000
+5 5 5 5 5 5 5 5 5.000000 5.000000 5.000000
+6 6 6 6 6 6 6 6 6.000000 6.000000 6.000000
+7 7 7 7 7 7 7 7 7.000000 7.000000 7.000000
+8 8 8 8 8 8 8 8 8.000000 8.000000 8.000000
+9 9 9 9 9 9 9 9 9.000000 9.000000 9.000000
+10 10 10 10 10 10 10 10 10.000000 10.000000 10.000000
+11 11 11 11 11 11 11 11 11.000000 11.000000 11.000000
diff --git a/lcc/mips/irix/tst/cvt.2bk b/lcc/mips/irix/tst/cvt.2bk
new file mode 100755
index 0000000..b3ab360
--- /dev/null
+++ b/lcc/mips/irix/tst/cvt.2bk
@@ -0,0 +1,2 @@
+tst/cvt.c:32: warning: conversion from `pointer to void function(void)' to `pointer to void' is compiler dependent
+tst/cvt.c:33: warning: conversion from `pointer to void' to `pointer to void function(void)' is compiler dependent
diff --git a/lcc/mips/irix/tst/cvt.sbk b/lcc/mips/irix/tst/cvt.sbk
new file mode 100755
index 0000000..426b826
--- /dev/null
+++ b/lcc/mips/irix/tst/cvt.sbk
@@ -0,0 +1,557 @@
+.set reorder
+.globl print
+.text
+.text
+.align 2
+.ent print
+print:
+.frame $sp,72,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-72
+.mask 0x82000000,-4
+.cprestore 64
+sw $31,68($sp)
+la $4,L.2
+lb $5,c
+lh $6,s
+lw $7,i
+lw $24,l
+sw $24,16($sp)
+lbu $24,C
+sw $24,20($sp)
+lhu $24,S
+sw $24,24($sp)
+lw $24,I
+sw $24,28($sp)
+lw $24,L
+sw $24,32($sp)
+l.s $f18,f
+cvt.d.s $f18,$f18
+s.d $f18,40($sp)
+l.d $f18,d
+s.d $f18,48($sp)
+l.d $f18,D
+s.d $f18,56($sp)
+jal printf
+L.1:
+lw $25,64($sp)
+lw $31,68($sp)
+addu $sp,$sp,72
+j $31
+.end print
+.globl main
+.text
+.align 2
+.ent main
+main:
+.frame $sp,72,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-72
+.mask 0xc2ff0000,-16
+sw $16,16($sp)
+sw $17,20($sp)
+sw $18,24($sp)
+sw $19,28($sp)
+sw $20,32($sp)
+sw $21,36($sp)
+sw $22,40($sp)
+sw $23,44($sp)
+.cprestore 48
+sw $30,52($sp)
+sw $31,56($sp)
+la $24,1
+sb $24,c
+lb $24,c
+move $15,$24
+sh $15,s
+sw $24,i
+sw $24,l
+move $15,$24
+move $14,$15
+sb $14,C
+move $14,$15
+sh $14,S
+sw $15,I
+sw $15,L
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+s.s $f18,f
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+s.d $f18,d
+s.d $f18,D
+jal print
+la $24,2
+sh $24,s
+lh $24,s
+move $15,$24
+sb $15,c
+sw $24,i
+sw $24,l
+move $15,$24
+move $14,$15
+sb $14,C
+move $14,$15
+sh $14,S
+sw $15,I
+sw $15,L
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+s.s $f18,f
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+s.d $f18,d
+s.d $f18,D
+jal print
+la $24,3
+sw $24,i
+lw $24,i
+move $15,$24
+sb $15,c
+move $15,$24
+sh $15,s
+sw $24,l
+move $15,$24
+move $14,$15
+sb $14,C
+move $14,$15
+sh $14,S
+sw $15,I
+sw $15,L
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+s.s $f18,f
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+s.d $f18,d
+s.d $f18,D
+jal print
+la $24,4
+sw $24,l
+lw $24,l
+move $15,$24
+sb $15,c
+move $15,$24
+sh $15,s
+sw $24,i
+move $15,$24
+move $14,$15
+sb $14,C
+move $14,$15
+sh $14,S
+sw $15,I
+sw $15,L
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+s.s $f18,f
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+s.d $f18,d
+s.d $f18,D
+jal print
+la $24,5
+sb $24,C
+lbu $24,C
+move $15,$24
+sb $15,c
+move $15,$24
+sh $15,s
+sw $24,i
+sw $24,l
+move $15,$24
+move $14,$15
+sh $14,S
+sw $15,I
+sw $15,L
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+s.s $f18,f
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+s.d $f18,d
+s.d $f18,D
+jal print
+la $24,6
+sh $24,S
+lhu $24,S
+move $15,$24
+sb $15,c
+move $15,$24
+sh $15,s
+sw $24,i
+sw $24,l
+move $15,$24
+move $14,$15
+sb $14,C
+sw $15,I
+sw $15,L
+mtc1 $24,$f18; cvt.s.w $f18,$f18
+s.s $f18,f
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+s.d $f18,d
+s.d $f18,D
+jal print
+la $24,7
+sw $24,I
+lw $24,I
+move $14,$24
+sb $14,c
+move $14,$24
+sh $14,s
+sw $24,i
+sw $24,l
+move $15,$24
+sb $15,C
+move $15,$24
+sh $15,S
+sw $24,L
+l.d $f18,L.4
+srl $15,$24,1
+mtc1 $15,$f16; cvt.d.w $f16,$f16
+mul.d $f18,$f18,$f16
+and $24,$24,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+add.d $f18,$f18,$f16
+cvt.s.d $f16,$f18
+s.s $f16,f
+s.d $f18,d
+s.d $f18,D
+jal print
+la $24,8
+sw $24,L
+lw $24,L
+move $14,$24
+sb $14,c
+move $14,$24
+sh $14,s
+sw $24,i
+sw $24,l
+move $15,$24
+sb $15,C
+move $15,$24
+sh $15,S
+lhu $15,S
+sw $15,I
+l.d $f18,L.4
+srl $15,$24,1
+mtc1 $15,$f16; cvt.d.w $f16,$f16
+mul.d $f18,$f18,$f16
+and $24,$24,1
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+add.d $f18,$f18,$f16
+cvt.s.d $f16,$f18
+s.s $f16,f
+s.d $f18,d
+s.d $f18,D
+jal print
+l.s $f18,L.5
+s.s $f18,f
+l.s $f18,f
+trunc.w.s $f2,$f18,$24; mfc1 $24,$f2
+move $15,$24
+sb $15,c
+move $15,$24
+sh $15,s
+sw $24,i
+sw $24,l
+l.s $f16,L.9
+c.lt.s $f18,$f16; bc1t L.7
+sub.s $f16,$f18,$f16
+trunc.w.s $f2,$f16,$24; mfc1 $24,$f2
+la $30,0x80000000($24)
+b L.8
+L.7:
+trunc.w.s $f2,$f18,$24; mfc1 $24,$f2
+move $30,$24
+L.8:
+move $24,$30
+sb $24,C
+l.s $f18,f
+l.s $f16,L.9
+c.lt.s $f18,$f16; bc1t L.11
+sub.s $f16,$f18,$f16
+trunc.w.s $f2,$f16,$24; mfc1 $24,$f2
+la $23,0x80000000($24)
+b L.12
+L.11:
+trunc.w.s $f2,$f18,$24; mfc1 $24,$f2
+move $23,$24
+L.12:
+move $24,$23
+sh $24,S
+l.s $f18,f
+l.s $f16,L.9
+c.lt.s $f18,$f16; bc1t L.14
+sub.s $f16,$f18,$f16
+trunc.w.s $f2,$f16,$24; mfc1 $24,$f2
+la $22,0x80000000($24)
+b L.15
+L.14:
+trunc.w.s $f2,$f18,$24; mfc1 $24,$f2
+move $22,$24
+L.15:
+sw $22,I
+l.s $f18,f
+l.s $f16,L.9
+c.lt.s $f18,$f16; bc1t L.17
+sub.s $f16,$f18,$f16
+trunc.w.s $f2,$f16,$24; mfc1 $24,$f2
+la $21,0x80000000($24)
+b L.18
+L.17:
+trunc.w.s $f2,$f18,$24; mfc1 $24,$f2
+move $21,$24
+L.18:
+sw $21,L
+l.s $f18,f
+cvt.d.s $f18,$f18
+s.d $f18,d
+s.d $f18,D
+jal print
+l.d $f18,L.19
+s.d $f18,d
+l.d $f18,d
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+move $15,$24
+sb $15,c
+move $15,$24
+sh $15,s
+sw $24,i
+sw $24,l
+l.d $f16,L.23
+c.lt.d $f18,$f16; bc1t L.21
+sub.d $f16,$f18,$f16
+trunc.w.d $f2,$f16,$24; mfc1 $24,$f2
+la $20,0x80000000($24)
+b L.22
+L.21:
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+move $20,$24
+L.22:
+move $24,$20
+sb $24,C
+l.d $f18,d
+l.d $f16,L.23
+c.lt.d $f18,$f16; bc1t L.25
+sub.d $f16,$f18,$f16
+trunc.w.d $f2,$f16,$24; mfc1 $24,$f2
+la $19,0x80000000($24)
+b L.26
+L.25:
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+move $19,$24
+L.26:
+move $24,$19
+sh $24,S
+l.d $f18,d
+l.d $f16,L.23
+c.lt.d $f18,$f16; bc1t L.28
+sub.d $f16,$f18,$f16
+trunc.w.d $f2,$f16,$24; mfc1 $24,$f2
+la $18,0x80000000($24)
+b L.29
+L.28:
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+move $18,$24
+L.29:
+sw $18,I
+l.d $f18,d
+l.d $f16,L.23
+c.lt.d $f18,$f16; bc1t L.31
+sub.d $f16,$f18,$f16
+trunc.w.d $f2,$f16,$24; mfc1 $24,$f2
+la $17,0x80000000($24)
+b L.32
+L.31:
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+move $17,$24
+L.32:
+sw $17,L
+l.d $f18,d
+cvt.s.d $f16,$f18
+s.s $f16,f
+s.d $f18,D
+jal print
+l.d $f18,L.33
+s.d $f18,D
+l.d $f18,D
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+move $15,$24
+sb $15,c
+move $15,$24
+sh $15,s
+sw $24,i
+sw $24,l
+l.d $f16,L.37
+c.lt.d $f18,$f16; bc1t L.35
+sub.d $f16,$f18,$f16
+trunc.w.d $f2,$f16,$24; mfc1 $24,$f2
+la $16,0x80000000($24)
+b L.36
+L.35:
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+move $16,$24
+L.36:
+move $24,$16
+sb $24,C
+l.d $f18,D
+l.d $f16,L.37
+c.lt.d $f18,$f16; bc1t L.39
+sub.d $f16,$f18,$f16
+trunc.w.d $f2,$f16,$24; mfc1 $24,$f2
+la $24,0x80000000($24)
+sw $24,-4+72($sp)
+b L.40
+L.39:
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+sw $24,-4+72($sp)
+L.40:
+lw $24,-4+72($sp)
+sh $24,S
+l.d $f18,D
+l.d $f16,L.37
+c.lt.d $f18,$f16; bc1t L.42
+sub.d $f16,$f18,$f16
+trunc.w.d $f2,$f16,$24; mfc1 $24,$f2
+la $24,0x80000000($24)
+sw $24,-8+72($sp)
+b L.43
+L.42:
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+sw $24,-8+72($sp)
+L.43:
+lw $24,-8+72($sp)
+sw $24,I
+l.d $f18,D
+l.d $f16,L.37
+c.lt.d $f18,$f16; bc1t L.45
+sub.d $f16,$f18,$f16
+trunc.w.d $f2,$f16,$24; mfc1 $24,$f2
+la $24,0x80000000($24)
+sw $24,-12+72($sp)
+b L.46
+L.45:
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+sw $24,-12+72($sp)
+L.46:
+lw $24,-12+72($sp)
+sw $24,L
+l.d $f18,D
+cvt.s.d $f16,$f18
+s.s $f16,f
+s.d $f18,d
+jal print
+sw $0,p
+sw $0,p
+sw $0,p
+sw $0,p
+lw $24,P
+sw $24,p
+sw $0,P
+sw $0,P
+sw $0,P
+sw $0,P
+lw $24,p
+sw $24,P
+move $2,$0
+L.3:
+lw $16,16($sp)
+lw $17,20($sp)
+lw $18,24($sp)
+lw $19,28($sp)
+lw $20,32($sp)
+lw $21,36($sp)
+lw $22,40($sp)
+lw $23,44($sp)
+lw $25,48($sp)
+lw $30,52($sp)
+lw $31,56($sp)
+addu $sp,$sp,72
+j $31
+.end main
+.globl P
+.comm P,4
+.globl p
+.comm p,4
+.globl D
+.comm D,8
+.globl d
+.comm d,8
+.globl f
+.comm f,4
+.globl L
+.comm L,4
+.globl I
+.comm I,4
+.globl S
+.comm S,2
+.globl C
+.comm C,1
+.globl l
+.comm l,4
+.globl i
+.comm i,4
+.globl s
+.comm s,2
+.globl c
+.comm c,1
+.rdata
+.align 3
+L.37:
+.word 0x41e00000
+.word 0x0
+.align 3
+L.33:
+.word 0x40260000
+.word 0x0
+.align 3
+L.23:
+.word 0x41e00000
+.word 0x0
+.align 3
+L.19:
+.word 0x40240000
+.word 0x0
+.align 2
+L.9:
+.word 0x4f000000
+.align 2
+L.5:
+.word 0x41100000
+.align 3
+L.4:
+.word 0x40000000
+.word 0x0
+.align 0
+L.2:
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 108
+.byte 100
+.byte 32
+.byte 37
+.byte 117
+.byte 32
+.byte 37
+.byte 117
+.byte 32
+.byte 37
+.byte 117
+.byte 32
+.byte 37
+.byte 108
+.byte 117
+.byte 32
+.byte 37
+.byte 102
+.byte 32
+.byte 37
+.byte 102
+.byte 32
+.byte 37
+.byte 108
+.byte 102
+.byte 10
+.byte 0
diff --git a/lcc/mips/irix/tst/fields.1bk b/lcc/mips/irix/tst/fields.1bk
new file mode 100755
index 0000000..f30b13f
--- /dev/null
+++ b/lcc/mips/irix/tst/fields.1bk
@@ -0,0 +1,5 @@
+x = 1 2 3 4 -3 6
+y = 3 8 9
+x = 1 2 3 0 0 6
+y = 2 8 16
+p->a = 0x3, p->b = 0xf
diff --git a/lcc/mips/irix/tst/fields.2bk b/lcc/mips/irix/tst/fields.2bk
new file mode 100755
index 0000000..e689d78
--- /dev/null
+++ b/lcc/mips/irix/tst/fields.2bk
@@ -0,0 +1,4 @@
+tst/fields.c:6: warning: initializer exceeds bit-field width
+tst/fields.c:8: warning: initializer exceeds bit-field width
+tst/fields.c:30: warning: missing return value
+tst/fields.c:34: warning: missing return value
diff --git a/lcc/mips/irix/tst/fields.sbk b/lcc/mips/irix/tst/fields.sbk
new file mode 100755
index 0000000..cd60540
--- /dev/null
+++ b/lcc/mips/irix/tst/fields.sbk
@@ -0,0 +1,304 @@
+.set reorder
+.globl x
+.data
+.align 2
+x:
+.word 0x1
+.byte 0x2
+.space 3
+.byte 0x0
+.byte 0x34
+.space 2
+.byte 0xa
+.byte 0x6
+.space 2
+.globl i
+.sdata
+.align 2
+i:
+.word 0x10
+.globl y
+.sdata
+.align 2
+y:
+.byte 0xe0
+.space 3
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x9
+.globl main
+.text
+.text
+.align 2
+.ent main
+main:
+.frame $sp,40,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-40
+.mask 0x82000000,-8
+.cprestore 28
+sw $31,32($sp)
+la $4,L.4
+lw $5,x
+lb $6,x+4
+lw $24,x+8
+sra $7,$24,20
+lw $24,x+8
+sll $24,$24,12
+sra $24,$24,28
+sw $24,16($sp)
+lw $24,x+12
+sll $24,$24,4
+sra $24,$24,29
+sw $24,20($sp)
+lb $24,x+13
+sw $24,24($sp)
+jal printf
+la $4,L.10
+lw $24,y
+srl $15,$24,30
+and $5,$15,3
+srl $24,$24,26
+and $6,$24,15
+lw $7,y+4
+jal printf
+lw $24,x+8
+and $24,$24,0xfff0ffff
+lw $15,i
+sll $15,$15,28
+sra $15,$15,28
+sll $15,$15,16
+and $15,$15,0xf0000
+or $24,$24,$15
+sw $24,x+8
+lw $24,x+12
+and $24,$24,0xf1ffffff
+sw $24,x+12
+la $4,L.4
+lw $5,x
+lb $6,x+4
+lw $24,x+8
+sra $7,$24,20
+lw $24,x+8
+sll $24,$24,12
+sra $24,$24,28
+sw $24,16($sp)
+lw $24,x+12
+sll $24,$24,4
+sra $24,$24,29
+sw $24,20($sp)
+lb $24,x+13
+sw $24,24($sp)
+jal printf
+lw $24,y
+and $24,$24,0x3fffffff
+or $24,$24,0x80000000
+sw $24,y
+lw $24,i
+sw $24,y+4
+la $4,L.10
+lw $24,y
+srl $15,$24,30
+and $5,$15,3
+srl $24,$24,26
+and $6,$24,15
+lw $7,y+4
+jal printf
+la $4,x
+jal f2
+move $2,$0
+L.3:
+lw $25,28($sp)
+lw $31,32($sp)
+addu $sp,$sp,40
+j $31
+.end main
+.globl f1
+.text
+.align 2
+.ent f1
+f1:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2000000,-8
+.cprestore 16
+sw $30,20($sp)
+sw $31,24($sp)
+move $30,$4
+lw $24,($30)
+and $24,$24,0xc3ffffff
+sw $24,($30)
+lw $24,($30)
+and $24,$24,0x3fffffff
+and $15,$0,3
+sll $15,$15,30
+and $15,$15,0xc0000000
+or $24,$24,$15
+sw $24,($30)
+lw $24,($30)
+and $24,$24,0x3c000000
+beq $24,$0,L.22
+la $4,L.24
+jal printf
+L.22:
+lw $24,($30)
+or $24,$24,0xc0000000
+sw $24,($30)
+lw $24,($30)
+or $24,$24,0x3c000000
+sw $24,($30)
+la $4,L.25
+lw $24,($30)
+srl $15,$24,30
+and $5,$15,3
+srl $24,$24,26
+and $6,$24,15
+jal printf
+move $2,$0
+L.21:
+lw $25,16($sp)
+lw $30,20($sp)
+lw $31,24($sp)
+addu $sp,$sp,32
+j $31
+.end f1
+.globl f2
+.text
+.align 2
+.ent f2
+f2:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2800000,-4
+sw $23,16($sp)
+.cprestore 20
+sw $30,24($sp)
+sw $31,28($sp)
+move $30,$4
+lw $24,i
+bne $24,$0,L.28
+la $23,1
+b L.29
+L.28:
+move $23,$0
+L.29:
+lw $24,($30)
+and $24,$24,0x3fffffff
+move $15,$23
+and $15,$15,3
+sll $15,$15,30
+and $15,$15,0xc0000000
+or $24,$24,$15
+sw $24,($30)
+move $4,$30
+jal f1
+lw $24,($30)
+and $24,$24,0xc3ffffff
+move $15,$0
+and $15,$15,15
+sll $15,$15,26
+and $15,$15,0x3c000000
+or $24,$24,$15
+sw $24,($30)
+move $2,$0
+L.26:
+lw $23,16($sp)
+lw $25,20($sp)
+lw $30,24($sp)
+lw $31,28($sp)
+addu $sp,$sp,32
+j $31
+.end f2
+.rdata
+.align 0
+L.25:
+.byte 112
+.byte 45
+.byte 62
+.byte 97
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 120
+.byte 37
+.byte 120
+.byte 44
+.byte 32
+.byte 112
+.byte 45
+.byte 62
+.byte 98
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 120
+.byte 37
+.byte 120
+.byte 10
+.byte 0
+.align 0
+L.24:
+.byte 112
+.byte 45
+.byte 62
+.byte 98
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 33
+.byte 10
+.byte 0
+.align 0
+L.10:
+.byte 121
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.4:
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
diff --git a/lcc/mips/irix/tst/front.2bk b/lcc/mips/irix/tst/front.2bk
new file mode 100755
index 0000000..841e6a5
--- /dev/null
+++ b/lcc/mips/irix/tst/front.2bk
@@ -0,0 +1,29 @@
+tst/front.c:3: warning: missing return value
+tst/front.c:10: warning: missing return value
+tst/front.c:20: type error in argument 1 to `s'; found `pointer to struct D' expected `pointer to incomplete struct D defined at tst/front.c:14'
+tst/front.c:21: warning: missing return value
+tst/front.c:32: warning: missing return value
+tst/front.c:36: operands of = have illegal types `pointer to int' and `pointer to const int'
+tst/front.c:38: warning: missing return value
+tst/front.c:62: operands of = have illegal types `pointer to char' and `pointer to const void'
+tst/front.c:63: warning: missing return value
+tst/front.c:68: warning: missing return value
+tst/front.c:69: warning: inconsistent linkage for `yy' previously declared at tst/front.c:68
+tst/front.c:69: warning: missing return value
+tst/front.c:71: invalid storage class `static' for `int function goo'
+tst/front.c:71: warning: declaration of `goo' does not match previous declaration at tst/front.c:70
+tst/front.c:71: warning: missing return value
+tst/front.c:74: warning: declaration of `xr' does not match previous declaration at tst/front.c:72
+tst/front.c:74: warning: missing return value
+tst/front.c:81: warning: missing return value
+tst/front.c:82: warning: declaration of `ss2' does not match previous declaration at tst/front.c:81
+tst/front.c:84: warning: inconsistent linkage for `ss5' previously declared at tst/front.c:80
+tst/front.c:92: type error in argument 1 to `gx1'; found `pointer to double' expected `double'
+tst/front.c:92: warning: missing return value
+tst/front.c:95: redeclaration of `hx1' previously declared at tst/front.c:94
+tst/front.c:98: warning: missing return value
+tst/front.c:101: conflicting argument declarations for function `gg1'
+tst/front.c:101: warning: missing return value
+tst/front.c:112: type error in argument 4 to `qsort'; found `pointer to int function(pointer to pointer to char,pointer to pointer to char)' expected `pointer to int function(pointer to const void,pointer to const void)'
+tst/front.c:113: warning: missing return value
+tst/front.c:120: warning: missing return value
diff --git a/lcc/mips/irix/tst/front.sbk b/lcc/mips/irix/tst/front.sbk
new file mode 100755
index 0000000..2b8add0
--- /dev/null
+++ b/lcc/mips/irix/tst/front.sbk
@@ -0,0 +1,416 @@
+.set reorder
+.globl main
+.text
+.text
+.align 2
+.ent main
+main:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+move $4,$0
+jal exit
+move $2,$0
+L.1:
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end main
+.globl nested
+.text
+.align 2
+.ent nested
+nested:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+la $24,4
+bge $4,$24,L.6
+la $24,114
+beq $5,$24,L.9
+L.6:
+la $24,1
+bne $4,$24,L.8
+la $24,104
+beq $5,$24,L.9
+la $24,105
+beq $5,$24,L.9
+L.8:
+la $24,2
+bne $4,$24,L.3
+la $24,111
+beq $5,$24,L.9
+la $24,121
+bne $5,$24,L.3
+L.9:
+move $4,$5
+L.3:
+move $2,$0
+L.2:
+j $31
+.end nested
+.globl s
+.text
+.align 2
+.ent s
+s:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+L.10:
+j $31
+.end s
+.globl Dy
+.sdata
+.align 2
+Dy:
+.word 0x0
+.space 4
+.globl Dz
+.sdata
+.align 2
+Dz:
+.word 0x1
+.space 4
+.globl Dfunc
+.text
+.text
+.align 2
+.ent Dfunc
+Dfunc:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end Dfunc
+.globl f
+.text
+.align 2
+.ent f
+f:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+j $31
+.end f
+.globl f1
+.text
+.align 2
+.ent f1
+f1:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+j $31
+.end f1
+.globl f2
+.text
+.align 2
+.ent f2
+f2:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+sw $4,24($sp)
+sw $5,28($sp)
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end f2
+.globl g
+.text
+.align 2
+.ent g
+g:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+sw $4,24($sp)
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end g
+.globl h
+.text
+.align 2
+.ent h
+h:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+sw $4,24($sp)
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end h
+.globl h1
+.text
+.align 2
+.ent h1
+h1:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+sw $4,24($sp)
+sw $5,28($sp)
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end h1
+.globl h2
+.text
+.align 2
+.ent h2
+h2:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+j $31
+.end h2
+.sdata
+.align 2
+L.21:
+.word 0x1
+.globl set1
+.text
+.text
+.align 2
+.ent set1
+set1:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+j $31
+.end set1
+.sdata
+.align 2
+L.23:
+.word 0x2
+.globl set2
+.text
+.text
+.align 2
+.ent set2
+set2:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+j $31
+.end set2
+.text
+.align 2
+.ent goo
+goo:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+j $31
+.end goo
+.globl sss
+.text
+.align 2
+.ent sss
+sss:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+j $31
+.end sss
+.lcomm L.27,4
+.globl rrr
+.text
+.text
+.align 2
+.ent rrr
+rrr:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+j $31
+.end rrr
+.globl setstatic
+.text
+.align 2
+.ent setstatic
+setstatic:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+j $31
+.end setstatic
+.globl gx1
+.text
+.align 2
+.ent gx1
+gx1:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+s.d $f12,24($sp)
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end gx1
+.globl ff1
+.text
+.align 2
+.ent ff1
+ff1:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+j $31
+.end ff1
+.globl gg1
+.text
+.align 2
+.ent gg1
+gg1:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+j $31
+.end gg1
+.globl hh1
+.text
+.align 2
+.ent hh1
+hh1:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+j $31
+.end hh1
+.globl cmp
+.text
+.align 2
+.ent cmp
+cmp:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+sw $4,24($sp)
+sw $5,28($sp)
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end cmp
+.globl sort
+.text
+.align 2
+.ent sort
+sort:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end sort
+.globl onearg
+.text
+.align 2
+.ent onearg
+onearg:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end onearg
+.extern xr 4
+.globl ss4
+.comm ss4,4
+.lcomm ss2,4
+.lcomm ss5,4
+.globl ss3
+.comm ss3,4
+.lcomm ss1,4
+.lcomm yy,4
+.globl z
+.comm z,4
+.globl y
+.comm y,4
+.globl x
+.comm x,4
+.globl b
+.comm b,4
+.globl a
+.comm a,4
diff --git a/lcc/mips/irix/tst/incr.2bk b/lcc/mips/irix/tst/incr.2bk
new file mode 100755
index 0000000..b86c400
--- /dev/null
+++ b/lcc/mips/irix/tst/incr.2bk
@@ -0,0 +1,9 @@
+tst/incr.c:1: warning: missing return value
+tst/incr.c:6: warning: expression with no effect elided
+tst/incr.c:6: warning: expression with no effect elided
+tst/incr.c:11: warning: missing return value
+tst/incr.c:16: warning: expression with no effect elided
+tst/incr.c:16: warning: expression with no effect elided
+tst/incr.c:21: warning: missing return value
+tst/incr.c:30: warning: missing return value
+tst/incr.c:39: warning: missing return value
diff --git a/lcc/mips/irix/tst/incr.sbk b/lcc/mips/irix/tst/incr.sbk
new file mode 100755
index 0000000..84c71c0
--- /dev/null
+++ b/lcc/mips/irix/tst/incr.sbk
@@ -0,0 +1,149 @@
+.set reorder
+.globl main
+.text
+.text
+.align 2
+.ent main
+main:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+move $2,$0
+L.1:
+j $31
+.end main
+.globl memchar
+.text
+.align 2
+.ent memchar
+memchar:
+.frame $sp,8,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-8
+lw $24,-8+8($sp)
+la $15,1($24)
+sw $15,-8+8($sp)
+lb $24,($24)
+sb $24,-1+8($sp)
+lw $24,-8+8($sp)
+la $24,1($24)
+sw $24,-8+8($sp)
+lb $24,($24)
+sb $24,-1+8($sp)
+lw $24,-8+8($sp)
+la $15,-1($24)
+sw $15,-8+8($sp)
+lb $24,($24)
+sb $24,-1+8($sp)
+lw $24,-8+8($sp)
+la $24,-1($24)
+sw $24,-8+8($sp)
+lb $24,($24)
+sb $24,-1+8($sp)
+move $2,$0
+L.2:
+addu $sp,$sp,8
+j $31
+.end memchar
+.globl memint
+.text
+.align 2
+.ent memint
+memint:
+.frame $sp,8,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-8
+lw $24,-8+8($sp)
+la $15,4($24)
+sw $15,-8+8($sp)
+lw $24,($24)
+sw $24,-4+8($sp)
+lw $24,-8+8($sp)
+la $24,4($24)
+sw $24,-8+8($sp)
+lw $24,($24)
+sw $24,-4+8($sp)
+lw $24,-8+8($sp)
+la $15,-4($24)
+sw $15,-8+8($sp)
+lw $24,($24)
+sw $24,-4+8($sp)
+lw $24,-8+8($sp)
+la $24,-4($24)
+sw $24,-8+8($sp)
+lw $24,($24)
+sw $24,-4+8($sp)
+move $2,$0
+L.3:
+addu $sp,$sp,8
+j $31
+.end memint
+.globl regchar
+.text
+.align 2
+.ent regchar
+regchar:
+.frame $sp,8,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-8
+.mask 0x40800000,-4
+sw $23,0($sp)
+sw $30,4($sp)
+move $24,$23
+la $23,1($24)
+lb $30,($24)
+la $24,1($23)
+move $23,$24
+lb $30,($24)
+move $24,$23
+la $23,-1($24)
+lb $30,($24)
+la $24,-1($23)
+move $23,$24
+lb $30,($24)
+move $2,$0
+L.4:
+lw $23,0($sp)
+lw $30,4($sp)
+addu $sp,$sp,8
+j $31
+.end regchar
+.globl regint
+.text
+.align 2
+.ent regint
+regint:
+.frame $sp,8,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-8
+.mask 0x40800000,-4
+sw $23,0($sp)
+sw $30,4($sp)
+move $24,$23
+la $23,4($24)
+lw $30,($24)
+la $24,4($23)
+move $23,$24
+lw $30,($24)
+move $24,$23
+la $23,-4($24)
+lw $30,($24)
+la $24,-4($23)
+move $23,$24
+lw $30,($24)
+move $2,$0
+L.5:
+lw $23,0($sp)
+lw $30,4($sp)
+addu $sp,$sp,8
+j $31
+.end regint
diff --git a/lcc/mips/irix/tst/init.1bk b/lcc/mips/irix/tst/init.1bk
new file mode 100755
index 0000000..042f3bb
--- /dev/null
+++ b/lcc/mips/irix/tst/init.1bk
@@ -0,0 +1,16 @@
+ 1 2 3 4
+ 5 6
+ 7
+if
+for
+else
+while
+1 2 3 if
+4 5 0 for
+6 7 8 else
+9 10 11 while
+1 2 3 if
+4 5 0 for
+6 7 8 else
+9 10 11 while
+0 0 0
diff --git a/lcc/mips/irix/tst/init.2bk b/lcc/mips/irix/tst/init.2bk
new file mode 100755
index 0000000..da08062
--- /dev/null
+++ b/lcc/mips/irix/tst/init.2bk
@@ -0,0 +1,3 @@
+tst/init.c:36: warning: missing return value
+tst/init.c:49: warning: missing return value
+tst/init.c:59: warning: missing return value
diff --git a/lcc/mips/irix/tst/init.sbk b/lcc/mips/irix/tst/init.sbk
new file mode 100755
index 0000000..9ad285d
--- /dev/null
+++ b/lcc/mips/irix/tst/init.sbk
@@ -0,0 +1,325 @@
+.set reorder
+.globl words
+.data
+.align 2
+words:
+.word 0x1
+.word 0x2
+.word 0x3
+.byte 105
+.byte 102
+.byte 0
+.space 3
+.space 2
+.word 0x4
+.word 0x5
+.space 4
+.byte 102
+.byte 111
+.byte 114
+.space 3
+.space 2
+.word 0x6
+.word 0x7
+.word 0x8
+.byte 101
+.byte 108
+.byte 115
+.byte 101
+.byte 0
+.space 1
+.space 2
+.word 0x9
+.word 0xa
+.word 0xb
+.byte 119
+.byte 104
+.byte 105
+.byte 108
+.byte 101
+.space 1
+.space 2
+.word 0x0
+.space 8
+.space 8
+.globl wordlist
+.sdata
+.align 2
+wordlist:
+.word words
+.globl x
+.data
+.align 2
+x:
+.word 0x1
+.word 0x2
+.word 0x3
+.word 0x4
+.word 0x0
+.word 0x5
+.word 0x6
+.space 12
+.word 0x7
+.space 16
+.globl y
+.data
+.align 2
+y:
+.word x
+.word x+20
+.word x+40
+.word 0x0
+.globl main
+.text
+.text
+.align 2
+.ent main
+main:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2800000,-4
+sw $23,16($sp)
+.cprestore 20
+sw $30,24($sp)
+sw $31,28($sp)
+move $23,$0
+b L.8
+L.5:
+move $30,$0
+b L.12
+L.9:
+la $4,L.13
+sll $24,$30,2
+sll $15,$23,2
+lw $15,y($15)
+addu $24,$24,$15
+lw $5,($24)
+jal printf
+L.10:
+la $30,1($30)
+L.12:
+sll $24,$30,2
+sll $15,$23,2
+lw $15,y($15)
+addu $24,$24,$15
+lw $24,($24)
+bne $24,$0,L.9
+la $4,L.14
+jal printf
+L.6:
+la $23,1($23)
+L.8:
+sll $24,$23,2
+lw $24,y($24)
+bne $24,$0,L.5
+jal f
+lw $4,wordlist
+jal g
+move $2,$0
+L.4:
+lw $23,16($sp)
+lw $25,20($sp)
+lw $30,24($sp)
+lw $31,28($sp)
+addu $sp,$sp,32
+j $31
+.end main
+.data
+.align 2
+L.16:
+.word L.17
+.word L.18
+.word L.19
+.word L.20
+.word 0x0
+.globl f
+.text
+.text
+.align 2
+.ent f
+f:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2000000,-8
+.cprestore 16
+sw $30,20($sp)
+sw $31,24($sp)
+la $30,L.16
+b L.24
+L.21:
+la $4,L.25
+lw $5,($30)
+jal printf
+L.22:
+la $30,4($30)
+L.24:
+lw $24,($30)
+bne $24,$0,L.21
+move $2,$0
+L.15:
+lw $25,16($sp)
+lw $30,20($sp)
+lw $31,24($sp)
+addu $sp,$sp,32
+j $31
+.end f
+.globl g
+.text
+.align 2
+.ent g
+g:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2800000,-4
+sw $23,16($sp)
+.cprestore 20
+sw $30,24($sp)
+sw $31,28($sp)
+move $30,$4
+b L.30
+L.27:
+move $23,$0
+b L.34
+L.31:
+la $4,L.35
+sll $24,$23,2
+addu $24,$24,$30
+lw $5,($24)
+jal printf
+L.32:
+la $23,1($23)
+L.34:
+move $24,$23
+la $15,3
+bltu $24,$15,L.31
+la $4,L.25
+la $5,12($30)
+jal printf
+L.28:
+la $30,20($30)
+L.30:
+lw $24,($30)
+bne $24,$0,L.27
+jal h
+move $2,$0
+L.26:
+lw $23,16($sp)
+lw $25,20($sp)
+lw $30,24($sp)
+lw $31,28($sp)
+addu $sp,$sp,32
+j $31
+.end g
+.globl h
+.text
+.align 2
+.ent h
+h:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2000000,-4
+.cprestore 20
+sw $30,24($sp)
+sw $31,28($sp)
+move $30,$0
+b L.40
+L.37:
+la $4,L.41
+la $24,20
+mul $24,$24,$30
+lw $5,words($24)
+lw $6,words+4($24)
+lw $7,words+8($24)
+la $24,words+12($24)
+sw $24,16($sp)
+jal printf
+L.38:
+la $30,1($30)
+L.40:
+move $24,$30
+la $15,5
+bltu $24,$15,L.37
+move $2,$0
+L.36:
+lw $25,20($sp)
+lw $30,24($sp)
+lw $31,28($sp)
+addu $sp,$sp,32
+j $31
+.end h
+.rdata
+.align 0
+L.41:
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.35:
+.byte 37
+.byte 100
+.byte 32
+.byte 0
+.align 0
+L.25:
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.20:
+.byte 119
+.byte 104
+.byte 105
+.byte 108
+.byte 101
+.byte 0
+.align 0
+L.19:
+.byte 101
+.byte 108
+.byte 115
+.byte 101
+.byte 0
+.align 0
+L.18:
+.byte 102
+.byte 111
+.byte 114
+.byte 0
+.align 0
+L.17:
+.byte 105
+.byte 102
+.byte 0
+.align 0
+L.14:
+.byte 10
+.byte 0
+.align 0
+L.13:
+.byte 32
+.byte 37
+.byte 100
+.byte 0
diff --git a/lcc/mips/irix/tst/limits.1bk b/lcc/mips/irix/tst/limits.1bk
new file mode 100755
index 0000000..f0c1dc8
--- /dev/null
+++ b/lcc/mips/irix/tst/limits.1bk
@@ -0,0 +1,14 @@
+UCHAR_MAX: 000000ff=255
+USHRT_MAX: 0000ffff=65535
+UINT_MAX: ffffffff=-1
+ULONG_MAX: ffffffff=-1
+CHAR_MAX: 0000007f=127
+SCHAR_MAX: 0000007f=127
+SHRT_MAX: 00007fff=32767
+INT_MAX: 7fffffff=2147483647
+LONG_MAX: 7fffffff=2147483647
+CHAR_MIN: ffffff80=-128
+SCHAR_MIN: ffffff80=-128
+SHRT_MIN: ffff8000=-32768
+INT_MIN: 80000000=-2147483648
+LONG_MIN: 80000000=-2147483648
diff --git a/lcc/mips/irix/tst/limits.2bk b/lcc/mips/irix/tst/limits.2bk
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/mips/irix/tst/limits.2bk
diff --git a/lcc/mips/irix/tst/limits.sbk b/lcc/mips/irix/tst/limits.sbk
new file mode 100755
index 0000000..2634913
--- /dev/null
+++ b/lcc/mips/irix/tst/limits.sbk
@@ -0,0 +1,396 @@
+.set reorder
+.globl main
+.text
+.text
+.align 2
+.ent main
+main:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+la $4,L.2
+la $24,255
+move $5,$24
+move $6,$24
+jal printf
+la $4,L.3
+la $24,65535
+move $5,$24
+move $6,$24
+jal printf
+la $4,L.4
+la $24,0xffffffff
+move $5,$24
+move $6,$24
+jal printf
+la $4,L.5
+la $24,0xffffffff
+move $5,$24
+move $6,$24
+jal printf
+la $4,L.6
+la $24,127
+move $5,$24
+move $6,$24
+jal printf
+la $4,L.7
+la $24,127
+move $5,$24
+move $6,$24
+jal printf
+la $4,L.8
+la $24,32767
+move $5,$24
+move $6,$24
+jal printf
+la $4,L.9
+la $24,2147483647
+move $5,$24
+move $6,$24
+jal printf
+la $4,L.10
+la $24,2147483647
+move $5,$24
+move $6,$24
+jal printf
+la $4,L.11
+la $24,-128
+move $5,$24
+move $6,$24
+jal printf
+la $4,L.12
+la $24,-128
+move $5,$24
+move $6,$24
+jal printf
+la $4,L.13
+la $24,-32768
+move $5,$24
+move $6,$24
+jal printf
+la $4,L.14
+la $24,-2147483648
+move $5,$24
+move $6,$24
+jal printf
+la $4,L.15
+la $24,-2147483648
+move $5,$24
+move $6,$24
+jal printf
+move $2,$0
+L.1:
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end main
+.rdata
+.align 0
+L.15:
+.byte 76
+.byte 79
+.byte 78
+.byte 71
+.byte 95
+.byte 77
+.byte 73
+.byte 78
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 108
+.byte 120
+.byte 61
+.byte 37
+.byte 108
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.14:
+.byte 73
+.byte 78
+.byte 84
+.byte 95
+.byte 77
+.byte 73
+.byte 78
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.13:
+.byte 83
+.byte 72
+.byte 82
+.byte 84
+.byte 95
+.byte 77
+.byte 73
+.byte 78
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.12:
+.byte 83
+.byte 67
+.byte 72
+.byte 65
+.byte 82
+.byte 95
+.byte 77
+.byte 73
+.byte 78
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.11:
+.byte 67
+.byte 72
+.byte 65
+.byte 82
+.byte 95
+.byte 77
+.byte 73
+.byte 78
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.10:
+.byte 76
+.byte 79
+.byte 78
+.byte 71
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 108
+.byte 120
+.byte 61
+.byte 37
+.byte 108
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.9:
+.byte 73
+.byte 78
+.byte 84
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.8:
+.byte 83
+.byte 72
+.byte 82
+.byte 84
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.7:
+.byte 83
+.byte 67
+.byte 72
+.byte 65
+.byte 82
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.6:
+.byte 67
+.byte 72
+.byte 65
+.byte 82
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.5:
+.byte 85
+.byte 76
+.byte 79
+.byte 78
+.byte 71
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 108
+.byte 120
+.byte 61
+.byte 37
+.byte 108
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.4:
+.byte 85
+.byte 73
+.byte 78
+.byte 84
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.3:
+.byte 85
+.byte 83
+.byte 72
+.byte 82
+.byte 84
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.2:
+.byte 85
+.byte 67
+.byte 72
+.byte 65
+.byte 82
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
diff --git a/lcc/mips/irix/tst/paranoia.1bk b/lcc/mips/irix/tst/paranoia.1bk
new file mode 100755
index 0000000..6842a77
--- /dev/null
+++ b/lcc/mips/irix/tst/paranoia.1bk
@@ -0,0 +1,178 @@
+Lest this program stop prematurely, i.e. before displaying
+
+ `END OF TEST',
+
+try to persuade the computer NOT to terminate execution when an
+error like Over/Underflow or Division by Zero occurs, but rather
+to persevere with a surrogate value after, perhaps, displaying some
+warning. If persuasion avails naught, don't despair but run this
+program anyway to see how many milestones it passes, and then
+amend it to make further progress.
+
+Answer questions with Y, y, N or n (unless otherwise indicated).
+
+
+Diagnosis resumes after milestone Number 0 Page: 1
+
+Users are invited to help debug and augment this program so it will
+cope with unanticipated and newly uncovered arithmetic pathologies.
+
+Please send suggestions and interesting results to
+ Richard Karpinski
+ Computer Center U-76
+ University of California
+ San Francisco, CA 94143-0704, USA
+
+In doing so, please include the following information:
+ Precision: double;
+ Version: 10 February 1989;
+ Computer:
+
+ Compiler:
+
+ Optimization level:
+
+ Other relevant compiler options:
+
+Diagnosis resumes after milestone Number 1 Page: 2
+
+Running this program should reveal these characteristics:
+ Radix = 1, 2, 4, 8, 10, 16, 100, 256 ...
+ Precision = number of significant digits carried.
+ U2 = Radix/Radix^Precision = One Ulp
+ (OneUlpnit in the Last Place) of 1.000xxx .
+ U1 = 1/Radix^Precision = One Ulp of numbers a little less than 1.0 .
+ Adequacy of guard digits for Mult., Div. and Subt.
+ Whether arithmetic is chopped, correctly rounded, or something else
+ for Mult., Div., Add/Subt. and Sqrt.
+ Whether a Sticky Bit used correctly for rounding.
+ UnderflowThreshold = an underflow threshold.
+ E0 and PseudoZero tell whether underflow is abrupt, gradual, or fuzzy.
+ V = an overflow threshold, roughly.
+ V0 tells, roughly, whether Infinity is represented.
+ Comparisions are checked for consistency with subtraction
+ and for contamination with pseudo-zeros.
+ Sqrt is tested. Y^X is not tested.
+ Extra-precise subexpressions are revealed but NOT YET tested.
+ Decimal-Binary conversion is NOT YET tested for accuracy.
+
+Diagnosis resumes after milestone Number 2 Page: 3
+
+The program attempts to discriminate among
+ FLAWs, like lack of a sticky bit,
+ Serious DEFECTs, like lack of a guard digit, and
+ FAILUREs, like 2+2 == 5 .
+Failures may confound subsequent diagnoses.
+
+The diagnostic capabilities of this program go beyond an earlier
+program called `MACHAR', which can be found at the end of the
+book `Software Manual for the Elementary Functions' (1980) by
+W. J. Cody and W. Waite. Although both programs try to discover
+the Radix, Precision and range (over/underflow thresholds)
+of the arithmetic, this program tries to cope with a wider variety
+of pathologies, and to say how well the arithmetic is implemented.
+
+The program is based upon a conventional radix representation for
+floating-point numbers, but also allows logarithmic encoding
+as used by certain early WANG machines.
+
+BASIC version of this program (C) 1983 by Prof. W. M. Kahan;
+see source comments for more history.
+
+Diagnosis resumes after milestone Number 3 Page: 4
+
+Program is now RUNNING tests on small integers:
+-1, 0, 1/2, 1, 2, 3, 4, 5, 9, 27, 32 & 240 are O.K.
+
+Searching for Radix and Precision.
+Radix = 2.000000 .
+Closest relative separation found is U1 = 1.1102230e-16 .
+
+Recalculating radix and precision
+ confirms closest relative separation U1 .
+Radix confirmed.
+The number of significant digits of the Radix is 53.000000 .
+
+Diagnosis resumes after milestone Number 30 Page: 5
+
+Subtraction appears to be normalized, as it should be.
+Checking for guard digit in *, /, and -.
+ *, /, and - appear to have guard digits, as they should.
+
+Diagnosis resumes after milestone Number 40 Page: 6
+
+Checking rounding on multiply, divide and add/subtract.
+Multiplication appears to round correctly.
+Division appears to round correctly.
+Addition/Subtraction appears to round correctly.
+Checking for sticky bit.
+Sticky bit apparently used correctly.
+
+Does Multiplication commute? Testing on 20 random pairs.
+ No failures found in 20 integer pairs.
+
+Running test of square root(x).
+Testing if sqrt(X * X) == X for 20 Integers X.
+Test for sqrt monotonicity.
+sqrt has passed a test for Monotonicity.
+Testing whether sqrt is rounded or chopped.
+Square root appears to be correctly rounded.
+
+Diagnosis resumes after milestone Number 90 Page: 7
+
+Testing powers Z^i for small Integers Z and i.
+... no discrepancis found.
+
+Seeking Underflow thresholds UfThold and E0.
+Smallest strictly positive number found is E0 = 4.94066e-324 .
+Since comparison denies Z = 0, evaluating (Z + Z) / Z should be safe.
+What the machine gets for (Z + Z) / Z is 2.00000000000000000e+00 .
+This is O.K., provided Over/Underflow has NOT just been signaled.
+Underflow is gradual; it incurs Absolute Error =
+(roundoff in UfThold) < E0.
+The Underflow threshold is 2.22507385850720190e-308, below which
+calculation may suffer larger Relative error than merely roundoff.
+Since underflow occurs below the threshold
+UfThold = (2.00000000000000000e+00) ^ (-1.02200000000000000e+03)
+only underflow should afflict the expression
+ (2.00000000000000000e+00) ^ (-1.02200000000000000e+03);
+actually calculating yields: 0.00000000000000000e+00 .
+This computed value is O.K.
+
+Testing X^((X + 1) / (X - 1)) vs. exp(2) = 7.38905609893065220e+00 as X -> 1.
+Accuracy seems adequate.
+Testing powers Z^Q at four nearly extreme values.
+ ... no discrepancies found.
+
+
+Diagnosis resumes after milestone Number 160 Page: 8
+
+Searching for Overflow threshold:
+This may generate an error.
+Can `Z = -Y' overflow?
+Trying it on Y = -inf .
+Seems O.K.
+Overflow threshold is V = 1.79769313486231570e+308 .
+Overflow saturates at V0 = inf .
+No Overflow should be signaled for V * 1 = 1.79769313486231570e+308
+ nor for V / 1 = 1.79769313486231570e+308 .
+Any overflow signal separating this * from the one
+above is a DEFECT.
+
+
+Diagnosis resumes after milestone Number 190 Page: 9
+
+
+What message and/or values does Division by Zero produce?
+ Trying to compute 1 / 0 produces ... inf .
+
+ Trying to compute 0 / 0 produces ... nan .
+
+Diagnosis resumes after milestone Number 220 Page: 10
+
+
+
+No failures, defects nor flaws have been discovered.
+Rounding appears to conform to the proposed IEEE standard P754.
+The arithmetic diagnosed appears to be Excellent!
+END OF TEST.
diff --git a/lcc/mips/irix/tst/paranoia.2bk b/lcc/mips/irix/tst/paranoia.2bk
new file mode 100755
index 0000000..f6ddf16
--- /dev/null
+++ b/lcc/mips/irix/tst/paranoia.2bk
@@ -0,0 +1,16 @@
+tst/paranoia.c:1867: warning: missing return value
+tst/paranoia.c:1874: warning: missing return value
+tst/paranoia.c:1884: warning: missing return value
+tst/paranoia.c:1924: warning: missing return value
+tst/paranoia.c:1939: warning: missing return value
+tst/paranoia.c:1956: warning: missing return value
+tst/paranoia.c:1975: warning: missing return value
+tst/paranoia.c:1988: warning: missing return value
+tst/paranoia.c:1995: warning: missing return value
+tst/paranoia.c:2055: warning: missing return value
+tst/paranoia.c:2062: warning: missing return value
+tst/paranoia.c:2070: warning: missing return value
+tst/paranoia.c:2087: warning: missing return value
+tst/paranoia.c:2115: warning: missing return value
+tst/paranoia.c:2144: warning: missing return value
+tst/paranoia.c:2173: warning: missing return value
diff --git a/lcc/mips/irix/tst/paranoia.sbk b/lcc/mips/irix/tst/paranoia.sbk
new file mode 100755
index 0000000..a0af0f9
--- /dev/null
+++ b/lcc/mips/irix/tst/paranoia.sbk
@@ -0,0 +1,18657 @@
+.set reorder
+.globl Zero
+.sdata
+.align 3
+Zero:
+.word 0x0
+.word 0x0
+.globl Half
+.sdata
+.align 3
+Half:
+.word 0x3fe00000
+.word 0x0
+.globl One
+.sdata
+.align 3
+One:
+.word 0x3ff00000
+.word 0x0
+.globl Two
+.sdata
+.align 3
+Two:
+.word 0x40000000
+.word 0x0
+.globl Three
+.sdata
+.align 3
+Three:
+.word 0x40080000
+.word 0x0
+.globl Four
+.sdata
+.align 3
+Four:
+.word 0x40100000
+.word 0x0
+.globl Five
+.sdata
+.align 3
+Five:
+.word 0x40140000
+.word 0x0
+.globl Eight
+.sdata
+.align 3
+Eight:
+.word 0x40200000
+.word 0x0
+.globl Nine
+.sdata
+.align 3
+Nine:
+.word 0x40220000
+.word 0x0
+.globl TwentySeven
+.sdata
+.align 3
+TwentySeven:
+.word 0x403b0000
+.word 0x0
+.globl ThirtyTwo
+.sdata
+.align 3
+ThirtyTwo:
+.word 0x40400000
+.word 0x0
+.globl TwoForty
+.sdata
+.align 3
+TwoForty:
+.word 0x406e0000
+.word 0x0
+.globl MinusOne
+.sdata
+.align 3
+MinusOne:
+.word 0xbff00000
+.word 0x0
+.globl OneAndHalf
+.sdata
+.align 3
+OneAndHalf:
+.word 0x3ff80000
+.word 0x0
+.globl NoTrials
+.sdata
+.align 2
+NoTrials:
+.word 0x14
+.globl sigfpe
+.text
+.text
+.align 2
+.ent sigfpe
+sigfpe:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+sw $4,24($sp)
+lw $24,fpecount
+la $24,1($24)
+sw $24,fpecount
+la $4,L.2
+jal printf
+la $4,_iob+16
+jal fflush
+lw $24,sigsave
+beq $24,$0,L.4
+la $4,8
+lw $5,sigsave
+jal signal
+sw $0,sigsave
+la $4,ovfl_buf
+la $5,1
+jal longjmp
+L.4:
+jal abort
+L.1:
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end sigfpe
+.data
+.align 2
+L.757:
+.word L.758
+.word L.759
+.word L.760
+.word L.761
+.globl main
+.text
+.text
+.align 2
+.ent main
+main:
+.frame $sp,240,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-240
+.mask 0xc2ff0000,-168
+sw $16,32($sp)
+sw $17,36($sp)
+sw $18,40($sp)
+sw $19,44($sp)
+sw $20,48($sp)
+sw $21,52($sp)
+sw $22,56($sp)
+sw $23,60($sp)
+.cprestore 64
+sw $30,68($sp)
+sw $31,72($sp)
+l.d $f18,L.7
+s.d $f18,Zero
+l.d $f18,L.8
+s.d $f18,One
+l.d $f18,One
+add.d $f16,$f18,$f18
+s.d $f16,Two
+l.d $f16,Two
+add.d $f10,$f16,$f18
+s.d $f10,Three
+l.d $f10,Three
+add.d $f8,$f10,$f18
+s.d $f8,Four
+l.d $f8,Four
+add.d $f6,$f8,$f18
+s.d $f6,Five
+add.d $f6,$f8,$f8
+s.d $f6,Eight
+mul.d $f6,$f10,$f10
+s.d $f6,Nine
+l.d $f6,Nine
+mul.d $f6,$f6,$f10
+s.d $f6,TwentySeven
+l.d $f6,Eight
+mul.d $f6,$f8,$f6
+s.d $f6,ThirtyTwo
+l.d $f6,Five
+mul.d $f6,$f8,$f6
+mul.d $f10,$f6,$f10
+mul.d $f10,$f10,$f8
+s.d $f10,TwoForty
+neg.d $f10,$f18
+s.d $f10,MinusOne
+div.d $f16,$f18,$f16
+s.d $f16,Half
+l.d $f16,Half
+add.d $f18,$f18,$f16
+s.d $f18,OneAndHalf
+sw $0,ErrCnt
+sw $0,ErrCnt+4
+sw $0,ErrCnt+8
+sw $0,ErrCnt+12
+la $24,1
+sw $24,PageNo
+sw $0,Milestone
+la $4,8
+la $5,sigfpe
+jal signal
+jal Instructions
+jal Pause
+jal Heading
+jal Pause
+jal Characteristics
+jal Pause
+jal History
+jal Pause
+la $24,7
+sw $24,Milestone
+la $4,L.12
+jal printf
+move $4,$0
+l.d $f18,Zero
+add.d $f16,$f18,$f18
+c.eq.d $f16,$f18; bc1f L.15
+l.d $f16,One
+sub.d $f10,$f16,$f16
+c.eq.d $f10,$f18; bc1f L.15
+c.le.d $f16,$f18; bc1t L.15
+add.d $f18,$f16,$f16
+l.d $f16,Two
+c.eq.d $f18,$f16; bc1f L.15
+la $30,1
+b L.16
+L.15:
+move $30,$0
+L.16:
+move $5,$30
+la $6,L.14
+jal TstCond
+l.d $f18,Zero
+neg.d $f18,$f18
+s.d $f18,Z
+l.d $f18,Z
+l.d $f16,L.7
+c.eq.d $f18,$f16; bc1t L.17
+lw $24,ErrCnt
+la $24,1($24)
+sw $24,ErrCnt
+la $4,L.19
+jal printf
+l.d $f18,L.20
+s.d $f18,U1
+l.d $f18,L.8
+s.d $f18,Radix
+jal TstPtUf
+L.17:
+move $4,$0
+l.d $f18,Three
+l.d $f16,Two
+l.d $f10,One
+add.d $f8,$f16,$f10
+c.eq.d $f18,$f8; bc1f L.23
+l.d $f8,Four
+add.d $f6,$f18,$f10
+c.eq.d $f8,$f6; bc1f L.23
+l.d $f6,Zero
+neg.d $f4,$f16
+mul.d $f16,$f16,$f4
+add.d $f16,$f8,$f16
+c.eq.d $f16,$f6; bc1f L.23
+sub.d $f18,$f8,$f18
+sub.d $f18,$f18,$f10
+c.eq.d $f18,$f6; bc1f L.23
+la $23,1
+b L.24
+L.23:
+move $23,$0
+L.24:
+move $5,$23
+la $6,L.22
+jal TstCond
+l.d $f18,MinusOne
+s.d $f18,-8+240($sp)
+l.d $f16,One
+l.d $f10,L.7
+sub.d $f10,$f10,$f16
+c.eq.d $f18,$f10; bc1f L.27
+l.d $f10,Zero
+add.d $f8,$f18,$f16
+c.eq.d $f8,$f10; bc1f L.27
+add.d $f8,$f16,$f18
+c.eq.d $f8,$f10; bc1f L.27
+mov.d $f12,$f16
+jal fabs
+l.d $f16,Zero
+l.d $f10,-8+240($sp)
+add.d $f18,$f10,$f0
+c.eq.d $f18,$f16; bc1f L.27
+l.d $f18,MinusOne
+mul.d $f10,$f18,$f18
+add.d $f18,$f18,$f10
+c.eq.d $f18,$f16; bc1f L.27
+la $22,1
+b L.28
+L.27:
+move $22,$0
+L.28:
+move $4,$0
+move $5,$22
+la $6,L.26
+jal TstCond
+move $4,$0
+l.d $f18,Half
+l.d $f16,MinusOne
+add.d $f16,$f18,$f16
+add.d $f18,$f16,$f18
+l.d $f16,Zero
+c.eq.d $f18,$f16; bc1f L.31
+la $21,1
+b L.32
+L.31:
+move $21,$0
+L.32:
+move $5,$21
+la $6,L.30
+jal TstCond
+la $24,10
+sw $24,Milestone
+move $4,$0
+l.d $f18,Nine
+l.d $f16,Three
+mul.d $f10,$f16,$f16
+c.eq.d $f18,$f10; bc1f L.35
+l.d $f10,TwentySeven
+mul.d $f18,$f18,$f16
+c.eq.d $f10,$f18; bc1f L.35
+l.d $f18,Eight
+l.d $f16,Four
+add.d $f8,$f16,$f16
+c.eq.d $f18,$f8; bc1f L.35
+l.d $f8,ThirtyTwo
+mul.d $f18,$f18,$f16
+c.eq.d $f8,$f18; bc1f L.35
+sub.d $f18,$f8,$f10
+sub.d $f18,$f18,$f16
+l.d $f16,One
+sub.d $f18,$f18,$f16
+l.d $f16,Zero
+c.eq.d $f18,$f16; bc1f L.35
+la $20,1
+b L.36
+L.35:
+move $20,$0
+L.36:
+move $5,$20
+la $6,L.34
+jal TstCond
+move $4,$0
+l.d $f18,Five
+l.d $f16,Four
+l.d $f10,One
+add.d $f10,$f16,$f10
+c.eq.d $f18,$f10; bc1f L.39
+l.d $f10,TwoForty
+l.d $f8,Three
+s.d $f8,-16+240($sp)
+mul.d $f6,$f16,$f18
+mul.d $f6,$f6,$f8
+mul.d $f6,$f6,$f16
+c.eq.d $f10,$f6; bc1f L.39
+l.d $f6,Zero
+div.d $f4,$f10,$f8
+mul.d $f8,$f16,$f16
+mul.d $f8,$f8,$f18
+sub.d $f8,$f4,$f8
+c.eq.d $f8,$f6; bc1f L.39
+div.d $f8,$f10,$f16
+l.d $f4,-16+240($sp)
+mul.d $f4,$f18,$f4
+mul.d $f4,$f4,$f16
+sub.d $f8,$f8,$f4
+c.eq.d $f8,$f6; bc1f L.39
+div.d $f18,$f10,$f18
+l.d $f10,-16+240($sp)
+mul.d $f10,$f16,$f10
+mul.d $f16,$f10,$f16
+sub.d $f18,$f18,$f16
+c.eq.d $f18,$f6; bc1f L.39
+la $19,1
+b L.40
+L.39:
+move $19,$0
+L.40:
+move $5,$19
+la $6,L.38
+jal TstCond
+lw $24,ErrCnt
+bne $24,$0,L.41
+la $4,L.43
+jal printf
+la $4,L.44
+jal printf
+L.41:
+la $4,L.45
+jal printf
+l.d $f18,One
+s.d $f18,W
+L.46:
+l.d $f18,W
+add.d $f18,$f18,$f18
+s.d $f18,W
+l.d $f18,W
+l.d $f16,One
+add.d $f10,$f18,$f16
+s.d $f10,Y
+l.d $f10,Y
+sub.d $f18,$f10,$f18
+s.d $f18,Z
+l.d $f18,Z
+sub.d $f18,$f18,$f16
+s.d $f18,Y
+L.47:
+l.d $f12,Y
+jal fabs
+l.d $f16,MinusOne
+add.d $f18,$f16,$f0
+l.d $f16,Zero
+c.lt.d $f18,$f16; bc1t L.46
+l.d $f18,Zero
+s.d $f18,Precision
+l.d $f18,One
+s.d $f18,Y
+L.49:
+l.d $f18,W
+l.d $f16,Y
+add.d $f10,$f18,$f16
+s.d $f10,Radix
+add.d $f16,$f16,$f16
+s.d $f16,Y
+l.d $f16,Radix
+sub.d $f18,$f16,$f18
+s.d $f18,Radix
+L.50:
+l.d $f18,Radix
+l.d $f16,Zero
+c.eq.d $f18,$f16; bc1t L.49
+l.d $f18,Radix
+l.d $f16,Two
+c.lt.d $f18,$f16; bc1f L.52
+l.d $f18,One
+s.d $f18,Radix
+L.52:
+la $4,L.54
+l.d $f18,Radix
+mfc1.d $6,$f18
+jal printf
+l.d $f18,Radix
+l.d $f16,L.8
+c.eq.d $f18,$f16; bc1t L.55
+l.d $f18,One
+s.d $f18,W
+L.57:
+l.d $f18,One
+l.d $f16,Precision
+add.d $f16,$f16,$f18
+s.d $f16,Precision
+l.d $f16,W
+l.d $f10,Radix
+mul.d $f16,$f16,$f10
+s.d $f16,W
+l.d $f16,W
+add.d $f18,$f16,$f18
+s.d $f18,Y
+L.58:
+l.d $f18,Y
+l.d $f16,W
+sub.d $f18,$f18,$f16
+l.d $f16,One
+c.eq.d $f18,$f16; bc1t L.57
+L.55:
+l.d $f18,One
+l.d $f16,W
+div.d $f18,$f18,$f16
+s.d $f18,U1
+l.d $f18,U1
+l.d $f16,Radix
+mul.d $f16,$f16,$f18
+s.d $f16,U2
+la $4,L.60
+mfc1.d $6,$f18
+jal printf
+la $4,L.61
+jal printf
+l.d $f18,Radix
+s.d $f18,E0
+l.d $f18,U1
+s.d $f18,E1
+l.d $f18,U2
+s.d $f18,E9
+l.d $f18,Precision
+s.d $f18,E3
+l.d $f18,Four
+l.d $f16,Three
+div.d $f18,$f18,$f16
+s.d $f18,X
+l.d $f18,X
+l.d $f16,One
+sub.d $f18,$f18,$f16
+s.d $f18,Third
+l.d $f18,Third
+l.d $f16,Half
+sub.d $f16,$f16,$f18
+s.d $f16,F6
+l.d $f16,F6
+add.d $f16,$f16,$f16
+s.d $f16,X
+l.d $f16,X
+sub.d $f12,$f16,$f18
+jal fabs
+s.d $f0,X
+l.d $f18,X
+l.d $f16,U2
+c.lt.d $f18,$f16; bc1f L.62
+l.d $f18,U2
+s.d $f18,X
+L.62:
+L.64:
+l.d $f18,X
+s.d $f18,U2
+l.d $f18,U2
+l.d $f16,Half
+mul.d $f16,$f16,$f18
+l.d $f10,ThirtyTwo
+mul.d $f10,$f10,$f18
+mul.d $f18,$f10,$f18
+add.d $f18,$f16,$f18
+s.d $f18,Y
+l.d $f18,One
+l.d $f16,Y
+add.d $f16,$f18,$f16
+s.d $f16,Y
+l.d $f16,Y
+sub.d $f18,$f16,$f18
+s.d $f18,X
+L.65:
+l.d $f18,X
+l.d $f16,U2
+c.le.d $f16,$f18; bc1t L.67
+l.d $f16,Zero
+c.le.d $f18,$f16; bc1f L.64
+L.67:
+l.d $f18,Two
+l.d $f16,Three
+div.d $f18,$f18,$f16
+s.d $f18,X
+l.d $f18,Half
+l.d $f16,X
+sub.d $f16,$f16,$f18
+s.d $f16,F6
+l.d $f16,F6
+add.d $f10,$f16,$f16
+s.d $f10,Third
+l.d $f10,Third
+sub.d $f18,$f10,$f18
+s.d $f18,X
+l.d $f18,X
+add.d $f12,$f18,$f16
+jal fabs
+s.d $f0,X
+l.d $f18,X
+l.d $f16,U1
+c.lt.d $f18,$f16; bc1f L.68
+l.d $f18,U1
+s.d $f18,X
+L.68:
+L.70:
+l.d $f18,X
+s.d $f18,U1
+l.d $f18,Half
+l.d $f16,U1
+mul.d $f10,$f18,$f16
+l.d $f8,ThirtyTwo
+mul.d $f8,$f8,$f16
+mul.d $f16,$f8,$f16
+add.d $f16,$f10,$f16
+s.d $f16,Y
+l.d $f16,Y
+sub.d $f16,$f18,$f16
+s.d $f16,Y
+l.d $f16,Y
+add.d $f16,$f18,$f16
+s.d $f16,X
+l.d $f16,X
+sub.d $f16,$f18,$f16
+s.d $f16,Y
+l.d $f16,Y
+add.d $f18,$f18,$f16
+s.d $f18,X
+L.71:
+l.d $f18,X
+l.d $f16,U1
+c.le.d $f16,$f18; bc1t L.73
+l.d $f16,Zero
+c.le.d $f18,$f16; bc1f L.70
+L.73:
+l.d $f18,U1
+l.d $f16,E1
+c.eq.d $f18,$f16; bc1f L.74
+la $4,L.76
+jal printf
+b L.75
+L.74:
+la $4,L.77
+l.d $f18,U1
+mfc1.d $6,$f18
+jal printf
+L.75:
+l.d $f18,U1
+l.d $f16,One
+div.d $f16,$f16,$f18
+s.d $f16,W
+l.d $f16,Half
+sub.d $f10,$f16,$f18
+add.d $f16,$f10,$f16
+s.d $f16,F9
+l.d $f16,U2
+div.d $f18,$f16,$f18
+l.d $f16,L.78
+add.d $f12,$f18,$f16
+jal floor
+s.d $f0,Radix
+l.d $f18,Radix
+l.d $f16,E0
+c.eq.d $f18,$f16; bc1f L.79
+la $4,L.81
+jal printf
+b L.80
+L.79:
+la $4,L.82
+l.d $f18,Radix
+mfc1.d $6,$f18
+jal printf
+L.80:
+la $4,2
+l.d $f18,Eight
+l.d $f16,Radix
+add.d $f18,$f18,$f18
+c.le.d $f16,$f18; bc1f L.85
+la $18,1
+b L.86
+L.85:
+move $18,$0
+L.86:
+move $5,$18
+la $6,L.84
+jal TstCond
+la $4,3
+l.d $f18,Radix
+l.d $f16,Two
+c.eq.d $f18,$f16; bc1t L.92
+l.d $f16,L.93
+c.eq.d $f18,$f16; bc1t L.92
+l.d $f16,One
+c.eq.d $f18,$f16; bc1f L.89
+L.92:
+la $17,1
+b L.90
+L.89:
+move $17,$0
+L.90:
+move $5,$17
+la $6,L.88
+jal TstCond
+la $24,20
+sw $24,Milestone
+move $4,$0
+l.d $f18,Half
+l.d $f16,F9
+sub.d $f16,$f16,$f18
+c.lt.d $f16,$f18; bc1f L.96
+la $16,1
+b L.97
+L.96:
+move $16,$0
+L.97:
+move $5,$16
+la $6,L.95
+jal TstCond
+l.d $f18,F9
+s.d $f18,X
+la $24,1
+sw $24,I
+l.d $f18,Half
+l.d $f16,X
+sub.d $f16,$f16,$f18
+s.d $f16,Y
+l.d $f16,Y
+sub.d $f18,$f16,$f18
+s.d $f18,Z
+move $4,$0
+l.d $f18,X
+l.d $f16,One
+c.eq.d $f18,$f16; bc1f L.102
+l.d $f18,Z
+l.d $f16,Zero
+c.eq.d $f18,$f16; bc1f L.100
+L.102:
+la $24,1
+sw $24,-20+240($sp)
+b L.101
+L.100:
+sw $0,-20+240($sp)
+L.101:
+lw $5,-20+240($sp)
+la $6,L.99
+jal TstCond
+l.d $f18,One
+l.d $f16,U2
+add.d $f10,$f18,$f16
+s.d $f10,X
+sw $0,I
+la $24,25
+sw $24,Milestone
+l.d $f10,Radix
+sub.d $f8,$f10,$f18
+s.d $f8,BMinusU2
+l.d $f8,BMinusU2
+sub.d $f16,$f8,$f16
+add.d $f16,$f16,$f18
+s.d $f16,BMinusU2
+c.eq.d $f10,$f18; bc1t L.103
+l.d $f12,U1
+jal log
+mov.d $f18,$f0
+s.d $f18,-32+240($sp)
+l.d $f12,Radix
+jal log
+l.d $f16,TwoForty
+neg.d $f16,$f16
+l.d $f10,-32+240($sp)
+mul.d $f16,$f16,$f10
+div.d $f18,$f16,$f0
+s.d $f18,X
+l.d $f18,Half
+l.d $f16,X
+add.d $f12,$f18,$f16
+jal floor
+s.d $f0,Y
+l.d $f18,X
+l.d $f16,Y
+sub.d $f12,$f18,$f16
+jal fabs
+l.d $f16,Four
+mul.d $f18,$f0,$f16
+l.d $f16,One
+c.lt.d $f18,$f16; bc1f L.105
+l.d $f18,Y
+s.d $f18,X
+L.105:
+l.d $f18,X
+l.d $f16,TwoForty
+div.d $f18,$f18,$f16
+s.d $f18,Precision
+l.d $f18,Half
+l.d $f16,Precision
+add.d $f12,$f18,$f16
+jal floor
+s.d $f0,Y
+l.d $f18,Precision
+l.d $f16,Y
+sub.d $f12,$f18,$f16
+jal fabs
+l.d $f16,TwoForty
+mul.d $f18,$f0,$f16
+l.d $f16,Half
+c.lt.d $f18,$f16; bc1f L.107
+l.d $f18,Y
+s.d $f18,Precision
+L.107:
+L.103:
+l.d $f18,Precision
+s.d $f18,-32+240($sp)
+mov.d $f12,$f18
+jal floor
+l.d $f16,-32+240($sp)
+c.eq.d $f16,$f0; bc1f L.111
+l.d $f18,Radix
+l.d $f16,One
+c.eq.d $f18,$f16; bc1f L.109
+L.111:
+la $4,L.112
+jal printf
+la $4,L.113
+jal printf
+L.109:
+l.d $f18,Radix
+l.d $f16,One
+c.eq.d $f18,$f16; bc1f L.114
+la $4,L.116
+jal printf
+b L.115
+L.114:
+la $4,L.117
+l.d $f18,Precision
+mfc1.d $6,$f18
+jal printf
+L.115:
+la $4,1
+l.d $f18,Nine
+l.d $f16,U2
+mul.d $f16,$f16,$f18
+mul.d $f18,$f16,$f18
+l.d $f16,TwoForty
+mul.d $f18,$f18,$f16
+l.d $f16,One
+c.lt.d $f18,$f16; bc1f L.120
+la $24,1
+sw $24,-36+240($sp)
+b L.121
+L.120:
+sw $0,-36+240($sp)
+L.121:
+lw $5,-36+240($sp)
+la $6,L.119
+jal TstCond
+la $24,30
+sw $24,Milestone
+l.d $f18,Four
+l.d $f16,Three
+l.d $f10,One
+div.d $f8,$f10,$f18
+div.d $f18,$f18,$f16
+sub.d $f18,$f18,$f10
+sub.d $f18,$f18,$f8
+mul.d $f18,$f18,$f16
+sub.d $f12,$f18,$f8
+jal fabs
+s.d $f0,X
+L.122:
+l.d $f18,X
+s.d $f18,Z2
+l.d $f18,One
+l.d $f16,Z2
+l.d $f10,Half
+mul.d $f10,$f10,$f16
+l.d $f8,ThirtyTwo
+mul.d $f8,$f8,$f16
+mul.d $f16,$f8,$f16
+add.d $f16,$f10,$f16
+add.d $f16,$f18,$f16
+sub.d $f18,$f16,$f18
+s.d $f18,X
+L.123:
+l.d $f18,X
+l.d $f16,Z2
+c.le.d $f16,$f18; bc1t L.125
+l.d $f16,Zero
+c.le.d $f18,$f16; bc1f L.122
+L.125:
+l.d $f18,Three
+l.d $f16,Four
+div.d $f10,$f18,$f16
+l.d $f8,Two
+div.d $f8,$f8,$f18
+sub.d $f10,$f10,$f8
+mul.d $f18,$f10,$f18
+l.d $f10,One
+div.d $f16,$f10,$f16
+sub.d $f12,$f18,$f16
+jal fabs
+s.d $f0,Z
+s.d $f0,Y
+s.d $f0,X
+L.126:
+l.d $f18,Z
+s.d $f18,Z1
+l.d $f18,One
+l.d $f16,Two
+div.d $f18,$f18,$f16
+l.d $f16,Z1
+l.d $f10,Half
+mul.d $f10,$f10,$f16
+l.d $f8,ThirtyTwo
+mul.d $f8,$f8,$f16
+mul.d $f16,$f8,$f16
+add.d $f16,$f10,$f16
+sub.d $f16,$f18,$f16
+add.d $f16,$f16,$f18
+sub.d $f16,$f18,$f16
+add.d $f18,$f16,$f18
+s.d $f18,Z
+L.127:
+l.d $f18,Z
+l.d $f16,Z1
+c.le.d $f16,$f18; bc1t L.129
+l.d $f16,Zero
+c.le.d $f18,$f16; bc1f L.126
+L.129:
+L.130:
+L.133:
+l.d $f18,Y
+s.d $f18,Y1
+l.d $f18,Half
+l.d $f16,Y1
+mul.d $f10,$f18,$f16
+l.d $f8,ThirtyTwo
+mul.d $f8,$f8,$f16
+mul.d $f16,$f8,$f16
+add.d $f16,$f10,$f16
+sub.d $f16,$f18,$f16
+add.d $f16,$f16,$f18
+sub.d $f16,$f18,$f16
+add.d $f18,$f16,$f18
+s.d $f18,Y
+L.134:
+l.d $f18,Y
+l.d $f16,Y1
+c.le.d $f16,$f18; bc1t L.136
+l.d $f16,Zero
+c.le.d $f18,$f16; bc1f L.133
+L.136:
+l.d $f18,X
+s.d $f18,X1
+l.d $f18,X1
+l.d $f16,F9
+l.d $f10,Half
+mul.d $f10,$f10,$f18
+l.d $f8,ThirtyTwo
+mul.d $f8,$f8,$f18
+mul.d $f18,$f8,$f18
+add.d $f18,$f10,$f18
+sub.d $f18,$f18,$f16
+add.d $f18,$f18,$f16
+s.d $f18,X
+L.131:
+l.d $f18,X
+l.d $f16,X1
+c.le.d $f16,$f18; bc1t L.137
+l.d $f16,Zero
+c.le.d $f18,$f16; bc1f L.130
+L.137:
+l.d $f18,X1
+l.d $f16,Y1
+c.eq.d $f18,$f16; bc1f L.140
+l.d $f16,Z1
+c.eq.d $f18,$f16; bc1t L.138
+L.140:
+la $4,1
+la $5,L.141
+jal BadCond
+la $4,L.142
+l.d $f18,X1
+mfc1.d $6,$f18
+l.d $f18,Y1
+s.d $f18,16($sp)
+l.d $f18,Z1
+s.d $f18,24($sp)
+jal printf
+la $4,L.143
+jal printf
+la $4,L.144
+jal printf
+la $4,L.145
+jal notify
+l.d $f18,U1
+l.d $f16,X1
+c.eq.d $f16,$f18; bc1t L.149
+l.d $f16,Y1
+c.eq.d $f16,$f18; bc1t L.149
+l.d $f16,Z1
+c.eq.d $f16,$f18; bc1f L.139
+L.149:
+la $4,L.150
+jal printf
+b L.139
+L.138:
+l.d $f18,Z1
+l.d $f16,U1
+c.eq.d $f18,$f16; bc1f L.153
+l.d $f18,Z2
+l.d $f16,U2
+c.eq.d $f18,$f16; bc1t L.151
+L.153:
+l.d $f18,Z1
+l.d $f16,U1
+c.lt.d $f18,$f16; bc1f L.156
+l.d $f18,Z2
+l.d $f16,U2
+c.lt.d $f18,$f16; bc1t L.154
+L.156:
+move $4,$0
+la $5,L.157
+jal BadCond
+la $4,L.158
+jal notify
+la $4,L.159
+l.d $f18,U1
+mfc1.d $6,$f18
+l.d $f16,Z1
+sub.d $f18,$f16,$f18
+s.d $f18,16($sp)
+jal printf
+la $4,L.160
+l.d $f18,U2
+mfc1.d $6,$f18
+l.d $f16,Z2
+sub.d $f18,$f16,$f18
+s.d $f18,16($sp)
+jal printf
+b L.155
+L.154:
+l.d $f18,Zero
+l.d $f16,Z1
+c.le.d $f16,$f18; bc1t L.163
+l.d $f16,Z2
+c.le.d $f16,$f18; bc1f L.161
+L.163:
+la $4,L.164
+l.d $f18,Radix
+mfc1.d $6,$f18
+jal printf
+la $4,L.165
+jal printf
+la $4,L.166
+l.d $f18,Z1
+mfc1.d $6,$f18
+l.d $f18,Z2
+s.d $f18,16($sp)
+jal printf
+la $4,L.167
+jal notify
+L.161:
+l.d $f18,Z1
+l.d $f16,Z2
+c.eq.d $f18,$f16; bc1f L.170
+l.d $f16,Zero
+c.le.d $f18,$f16; bc1t L.168
+L.170:
+l.d $f18,Z1
+l.d $f16,U1
+div.d $f18,$f18,$f16
+s.d $f18,X
+l.d $f18,Z2
+l.d $f16,U2
+div.d $f18,$f18,$f16
+s.d $f18,Y
+l.d $f18,Y
+l.d $f16,X
+c.le.d $f18,$f16; bc1t L.171
+l.d $f18,Y
+s.d $f18,X
+L.171:
+l.d $f12,X
+jal log
+neg.d $f18,$f0
+s.d $f18,Q
+la $4,L.173
+jal printf
+l.d $f12,Radix
+jal log
+la $4,L.174
+l.d $f16,Q
+div.d $f18,$f16,$f0
+mfc1.d $6,$f18
+jal printf
+l.d $f12,L.93
+jal log
+la $4,L.175
+l.d $f16,Q
+div.d $f18,$f16,$f0
+mfc1.d $6,$f18
+jal printf
+L.168:
+la $4,L.150
+jal printf
+L.155:
+L.151:
+L.139:
+jal Pause
+la $24,35
+sw $24,Milestone
+l.d $f18,Radix
+l.d $f16,Two
+c.lt.d $f18,$f16; bc1t L.176
+l.d $f18,Radix
+l.d $f16,W
+mul.d $f18,$f18,$f18
+div.d $f18,$f16,$f18
+s.d $f18,X
+l.d $f18,X
+l.d $f16,One
+add.d $f16,$f18,$f16
+s.d $f16,Y
+l.d $f16,Y
+sub.d $f18,$f16,$f18
+s.d $f18,Z
+l.d $f18,Z
+l.d $f16,U2
+add.d $f10,$f18,$f16
+s.d $f10,T
+l.d $f10,T
+sub.d $f18,$f10,$f18
+s.d $f18,X
+move $4,$0
+l.d $f18,X
+c.eq.d $f18,$f16; bc1f L.180
+la $24,1
+sw $24,-40+240($sp)
+b L.181
+L.180:
+sw $0,-40+240($sp)
+L.181:
+lw $5,-40+240($sp)
+la $6,L.179
+jal TstCond
+l.d $f18,X
+l.d $f16,U2
+c.eq.d $f18,$f16; bc1f L.182
+la $4,L.184
+jal printf
+L.182:
+L.176:
+la $4,L.185
+jal printf
+l.d $f18,F9
+l.d $f16,One
+mul.d $f10,$f18,$f16
+s.d $f10,Y
+mul.d $f10,$f16,$f18
+s.d $f10,Z
+l.d $f10,Half
+sub.d $f18,$f18,$f10
+s.d $f18,X
+l.d $f18,X
+l.d $f8,Y
+sub.d $f8,$f8,$f10
+sub.d $f8,$f8,$f18
+s.d $f8,Y
+l.d $f8,Z
+sub.d $f10,$f8,$f10
+sub.d $f18,$f10,$f18
+s.d $f18,Z
+l.d $f18,U2
+add.d $f10,$f16,$f18
+s.d $f10,X
+l.d $f10,X
+l.d $f8,Radix
+mul.d $f6,$f10,$f8
+s.d $f6,T
+mul.d $f10,$f8,$f10
+s.d $f10,R
+l.d $f10,T
+sub.d $f10,$f10,$f8
+s.d $f10,X
+mul.d $f18,$f8,$f18
+l.d $f10,X
+sub.d $f10,$f10,$f18
+s.d $f10,X
+l.d $f10,R
+sub.d $f10,$f10,$f8
+s.d $f10,T
+l.d $f10,T
+sub.d $f18,$f10,$f18
+s.d $f18,T
+sub.d $f18,$f8,$f16
+l.d $f16,X
+mul.d $f16,$f16,$f18
+s.d $f16,X
+l.d $f16,T
+mul.d $f18,$f16,$f18
+s.d $f18,T
+l.d $f18,Zero
+l.d $f16,X
+c.eq.d $f16,$f18; bc1f L.186
+l.d $f16,Y
+c.eq.d $f16,$f18; bc1f L.186
+l.d $f16,Z
+c.eq.d $f16,$f18; bc1f L.186
+l.d $f16,T
+c.eq.d $f16,$f18; bc1f L.186
+la $24,1
+sw $24,GMult
+b L.187
+L.186:
+move $24,$0
+sw $24,GMult
+la $4,1
+move $5,$24
+la $6,L.188
+jal TstCond
+L.187:
+l.d $f18,Radix
+l.d $f16,U2
+mul.d $f18,$f18,$f16
+s.d $f18,Z
+l.d $f18,Z
+l.d $f16,One
+add.d $f16,$f16,$f18
+s.d $f16,X
+l.d $f16,X
+add.d $f18,$f16,$f18
+mul.d $f16,$f16,$f16
+sub.d $f12,$f18,$f16
+jal fabs
+l.d $f16,U2
+sub.d $f18,$f0,$f16
+s.d $f18,Y
+l.d $f18,One
+sub.d $f18,$f18,$f16
+s.d $f18,X
+l.d $f18,X
+sub.d $f16,$f18,$f16
+mul.d $f18,$f18,$f18
+sub.d $f12,$f16,$f18
+jal fabs
+l.d $f16,U1
+sub.d $f18,$f0,$f16
+s.d $f18,Z
+move $4,$0
+l.d $f18,Zero
+l.d $f16,Y
+c.le.d $f16,$f18; bc1f L.191
+l.d $f16,Z
+c.le.d $f16,$f18; bc1f L.191
+la $24,1
+sw $24,-40+240($sp)
+b L.192
+L.191:
+sw $0,-40+240($sp)
+L.192:
+lw $5,-40+240($sp)
+la $6,L.190
+jal TstCond
+l.d $f18,One
+l.d $f16,U2
+sub.d $f10,$f18,$f16
+s.d $f10,Y
+add.d $f16,$f18,$f16
+s.d $f16,X
+l.d $f16,Y
+div.d $f16,$f18,$f16
+s.d $f16,Z
+l.d $f16,Z
+l.d $f10,X
+sub.d $f16,$f16,$f10
+s.d $f16,Y
+l.d $f16,Three
+div.d $f18,$f18,$f16
+s.d $f18,X
+l.d $f18,Nine
+div.d $f16,$f16,$f18
+s.d $f16,Z
+l.d $f16,Z
+l.d $f10,X
+sub.d $f10,$f10,$f16
+s.d $f10,X
+l.d $f10,TwentySeven
+div.d $f18,$f18,$f10
+s.d $f18,T
+l.d $f18,T
+sub.d $f18,$f16,$f18
+s.d $f18,Z
+la $4,2
+l.d $f18,Zero
+l.d $f16,X
+c.eq.d $f16,$f18; bc1f L.195
+l.d $f16,Y
+c.eq.d $f16,$f18; bc1f L.195
+l.d $f16,Z
+c.eq.d $f16,$f18; bc1f L.195
+la $24,1
+sw $24,-44+240($sp)
+b L.196
+L.195:
+sw $0,-44+240($sp)
+L.196:
+lw $5,-44+240($sp)
+la $6,L.194
+jal TstCond
+l.d $f18,F9
+l.d $f16,One
+div.d $f10,$f18,$f16
+s.d $f10,Y
+l.d $f10,Half
+sub.d $f18,$f18,$f10
+s.d $f18,X
+l.d $f18,Y
+sub.d $f18,$f18,$f10
+l.d $f10,X
+sub.d $f18,$f18,$f10
+s.d $f18,Y
+l.d $f18,U2
+add.d $f18,$f16,$f18
+s.d $f18,X
+l.d $f18,X
+div.d $f16,$f18,$f16
+s.d $f16,T
+l.d $f16,T
+sub.d $f18,$f16,$f18
+s.d $f18,X
+l.d $f18,Zero
+l.d $f16,X
+c.eq.d $f16,$f18; bc1f L.197
+l.d $f16,Y
+c.eq.d $f16,$f18; bc1f L.197
+l.d $f16,Z
+c.eq.d $f16,$f18; bc1f L.197
+la $24,1
+sw $24,GDiv
+b L.198
+L.197:
+move $24,$0
+sw $24,GDiv
+la $4,1
+move $5,$24
+la $6,L.199
+jal TstCond
+L.198:
+l.d $f18,One
+l.d $f16,U2
+add.d $f16,$f18,$f16
+div.d $f18,$f18,$f16
+s.d $f18,X
+l.d $f18,Half
+l.d $f16,X
+sub.d $f16,$f16,$f18
+sub.d $f18,$f16,$f18
+s.d $f18,Y
+la $4,1
+l.d $f18,Y
+l.d $f16,Zero
+c.lt.d $f18,$f16; bc1f L.202
+la $24,1
+sw $24,-48+240($sp)
+b L.203
+L.202:
+sw $0,-48+240($sp)
+L.203:
+lw $5,-48+240($sp)
+la $6,L.201
+jal TstCond
+l.d $f18,One
+l.d $f16,U2
+sub.d $f10,$f18,$f16
+s.d $f10,X
+l.d $f10,Radix
+mul.d $f16,$f10,$f16
+add.d $f18,$f18,$f16
+s.d $f18,Y
+l.d $f18,X
+mul.d $f16,$f18,$f10
+s.d $f16,Z
+l.d $f16,Y
+mul.d $f8,$f16,$f10
+s.d $f8,T
+l.d $f8,Z
+div.d $f8,$f8,$f10
+s.d $f8,R
+l.d $f8,T
+div.d $f10,$f8,$f10
+s.d $f10,StickyBit
+l.d $f10,R
+sub.d $f18,$f10,$f18
+s.d $f18,X
+l.d $f18,StickyBit
+sub.d $f18,$f18,$f16
+s.d $f18,Y
+move $4,$0
+l.d $f18,Zero
+l.d $f16,X
+c.eq.d $f16,$f18; bc1f L.206
+l.d $f16,Y
+c.eq.d $f16,$f18; bc1f L.206
+la $24,1
+sw $24,-52+240($sp)
+b L.207
+L.206:
+sw $0,-52+240($sp)
+L.207:
+lw $5,-52+240($sp)
+la $6,L.205
+jal TstCond
+l.d $f18,One
+l.d $f16,U1
+sub.d $f16,$f18,$f16
+s.d $f16,Y
+l.d $f16,F9
+sub.d $f16,$f18,$f16
+s.d $f16,X
+l.d $f16,Y
+sub.d $f18,$f18,$f16
+s.d $f18,Y
+l.d $f18,Radix
+l.d $f16,U2
+sub.d $f16,$f18,$f16
+s.d $f16,T
+l.d $f16,BMinusU2
+sub.d $f16,$f18,$f16
+s.d $f16,Z
+l.d $f16,T
+sub.d $f18,$f18,$f16
+s.d $f18,T
+l.d $f18,U1
+l.d $f16,X
+c.eq.d $f16,$f18; bc1f L.208
+l.d $f16,Y
+c.eq.d $f16,$f18; bc1f L.208
+l.d $f18,U2
+l.d $f16,Z
+c.eq.d $f16,$f18; bc1f L.208
+l.d $f16,T
+c.eq.d $f16,$f18; bc1f L.208
+la $24,1
+sw $24,GAddSub
+b L.209
+L.208:
+move $24,$0
+sw $24,GAddSub
+la $4,1
+move $5,$24
+la $6,L.210
+jal TstCond
+L.209:
+l.d $f18,F9
+l.d $f16,One
+c.eq.d $f18,$f16; bc1t L.211
+sub.d $f18,$f18,$f16
+l.d $f16,Zero
+c.lt.d $f18,$f16; bc1t L.211
+la $4,1
+la $5,L.213
+jal BadCond
+la $4,L.214
+jal printf
+la $4,L.215
+jal printf
+la $4,L.216
+jal printf
+L.211:
+la $24,1
+lw $15,GMult
+bne $15,$24,L.217
+lw $15,GDiv
+bne $15,$24,L.217
+lw $15,GAddSub
+bne $15,$24,L.217
+la $4,L.219
+jal printf
+L.217:
+la $24,40
+sw $24,Milestone
+jal Pause
+la $4,L.220
+jal printf
+sw $0,RMult
+sw $0,RDiv
+sw $0,RAddSub
+l.d $f18,Two
+l.d $f16,Radix
+div.d $f16,$f16,$f18
+s.d $f16,RadixD2
+s.d $f18,A1
+sw $0,Done
+L.221:
+l.d $f18,Radix
+s.d $f18,AInvrse
+L.224:
+l.d $f18,AInvrse
+s.d $f18,X
+l.d $f16,A1
+div.d $f18,$f18,$f16
+s.d $f18,AInvrse
+L.225:
+l.d $f12,AInvrse
+jal floor
+l.d $f16,AInvrse
+c.eq.d $f0,$f16; bc1t L.224
+l.d $f18,X
+l.d $f16,One
+c.eq.d $f18,$f16; bc1t L.230
+l.d $f18,A1
+l.d $f16,Three
+c.le.d $f18,$f16; bc1t L.228
+L.230:
+la $24,1
+sw $24,-56+240($sp)
+b L.229
+L.228:
+sw $0,-56+240($sp)
+L.229:
+lw $24,-56+240($sp)
+sw $24,Done
+lw $24,Done
+bne $24,$0,L.231
+l.d $f18,Nine
+l.d $f16,One
+add.d $f18,$f18,$f16
+s.d $f18,A1
+L.231:
+L.222:
+lw $24,Done
+beq $24,$0,L.221
+l.d $f18,X
+l.d $f16,One
+c.eq.d $f18,$f16; bc1f L.233
+l.d $f18,Radix
+s.d $f18,A1
+L.233:
+l.d $f18,A1
+l.d $f16,One
+div.d $f16,$f16,$f18
+s.d $f16,AInvrse
+s.d $f18,X
+l.d $f18,AInvrse
+s.d $f18,Y
+sw $0,Done
+L.235:
+l.d $f18,Half
+l.d $f16,X
+l.d $f10,Y
+mul.d $f16,$f16,$f10
+sub.d $f16,$f16,$f18
+s.d $f16,Z
+move $4,$0
+l.d $f16,Z
+c.eq.d $f16,$f18; bc1f L.240
+la $24,1
+sw $24,-56+240($sp)
+b L.241
+L.240:
+sw $0,-56+240($sp)
+L.241:
+lw $5,-56+240($sp)
+la $6,L.239
+jal TstCond
+l.d $f18,X
+l.d $f16,Radix
+c.eq.d $f18,$f16; bc1f L.243
+la $24,1
+sw $24,-60+240($sp)
+b L.244
+L.243:
+sw $0,-60+240($sp)
+L.244:
+lw $24,-60+240($sp)
+sw $24,Done
+l.d $f18,Radix
+s.d $f18,X
+l.d $f18,One
+l.d $f16,X
+div.d $f18,$f18,$f16
+s.d $f18,Y
+L.236:
+lw $24,Done
+beq $24,$0,L.235
+l.d $f18,One
+l.d $f16,U2
+add.d $f10,$f18,$f16
+s.d $f10,Y2
+sub.d $f18,$f18,$f16
+s.d $f18,Y1
+l.d $f18,OneAndHalf
+s.d $f18,-64+240($sp)
+sub.d $f10,$f18,$f16
+s.d $f10,X
+add.d $f10,$f18,$f16
+s.d $f10,Y
+l.d $f10,X
+l.d $f8,Y2
+sub.d $f6,$f10,$f16
+mul.d $f6,$f6,$f8
+s.d $f6,Z
+l.d $f6,Y
+l.d $f4,Y1
+mul.d $f18,$f6,$f4
+s.d $f18,T
+l.d $f18,Z
+sub.d $f18,$f18,$f10
+s.d $f18,Z
+l.d $f18,T
+sub.d $f18,$f18,$f10
+s.d $f18,T
+mul.d $f18,$f10,$f8
+s.d $f18,X
+add.d $f18,$f6,$f16
+mul.d $f18,$f18,$f4
+s.d $f18,Y
+l.d $f18,X
+l.d $f16,-64+240($sp)
+sub.d $f18,$f18,$f16
+s.d $f18,X
+l.d $f18,Y
+l.d $f16,-64+240($sp)
+sub.d $f18,$f18,$f16
+s.d $f18,Y
+l.d $f18,Zero
+l.d $f16,X
+c.eq.d $f16,$f18; bc1f L.245
+l.d $f16,Y
+c.eq.d $f16,$f18; bc1f L.245
+l.d $f16,Z
+c.eq.d $f16,$f18; bc1f L.245
+l.d $f16,T
+c.le.d $f16,$f18; bc1f L.245
+l.d $f18,OneAndHalf
+l.d $f16,U2
+add.d $f10,$f18,$f16
+l.d $f8,Y2
+mul.d $f6,$f10,$f8
+s.d $f6,X
+sub.d $f18,$f18,$f16
+sub.d $f6,$f18,$f16
+s.d $f6,Y
+add.d $f10,$f10,$f16
+s.d $f10,Z
+l.d $f10,Y1
+mul.d $f18,$f18,$f10
+s.d $f18,T
+l.d $f18,Z
+add.d $f6,$f18,$f16
+s.d $f6,-72+240($sp)
+l.d $f4,X
+sub.d $f4,$f4,$f6
+s.d $f4,X
+l.d $f4,Y
+mul.d $f6,$f4,$f10
+s.d $f6,StickyBit
+mul.d $f18,$f18,$f8
+s.d $f18,S
+l.d $f18,T
+sub.d $f18,$f18,$f4
+s.d $f18,T
+sub.d $f18,$f16,$f4
+l.d $f6,StickyBit
+add.d $f18,$f18,$f6
+s.d $f18,Y
+l.d $f18,S
+l.d $f6,-72+240($sp)
+add.d $f6,$f6,$f16
+sub.d $f18,$f18,$f6
+s.d $f18,Z
+add.d $f18,$f8,$f16
+mul.d $f18,$f18,$f10
+s.d $f18,StickyBit
+mul.d $f18,$f8,$f10
+s.d $f18,Y1
+l.d $f18,StickyBit
+sub.d $f18,$f18,$f8
+s.d $f18,StickyBit
+l.d $f18,Y1
+l.d $f16,Half
+sub.d $f18,$f18,$f16
+s.d $f18,Y1
+l.d $f18,Zero
+l.d $f16,X
+c.eq.d $f16,$f18; bc1f L.247
+l.d $f16,Y
+c.eq.d $f16,$f18; bc1f L.247
+l.d $f16,Z
+c.eq.d $f16,$f18; bc1f L.247
+l.d $f16,T
+c.eq.d $f16,$f18; bc1f L.247
+l.d $f16,StickyBit
+c.eq.d $f16,$f18; bc1f L.247
+l.d $f18,Y1
+l.d $f16,Half
+c.eq.d $f18,$f16; bc1f L.247
+la $24,1
+sw $24,RMult
+la $4,L.249
+jal printf
+b L.248
+L.247:
+l.d $f18,U2
+l.d $f16,Zero
+l.d $f10,X
+add.d $f10,$f10,$f18
+c.eq.d $f10,$f16; bc1f L.250
+l.d $f10,Y
+c.lt.d $f10,$f16; bc1f L.250
+l.d $f10,Z
+add.d $f10,$f10,$f18
+c.eq.d $f10,$f16; bc1f L.250
+l.d $f10,T
+c.lt.d $f10,$f16; bc1f L.250
+l.d $f10,StickyBit
+add.d $f18,$f10,$f18
+c.eq.d $f18,$f16; bc1f L.250
+l.d $f18,Y1
+l.d $f16,Half
+c.lt.d $f18,$f16; bc1f L.250
+la $24,2
+sw $24,RMult
+la $4,L.252
+jal printf
+b L.251
+L.250:
+la $4,L.253
+jal printf
+L.251:
+L.248:
+lw $24,RMult
+la $15,1
+bne $24,$15,L.246
+lw $24,GMult
+bne $24,$0,L.246
+la $4,L.256
+jal notify
+b L.246
+L.245:
+la $4,L.253
+jal printf
+L.246:
+la $24,45
+sw $24,Milestone
+l.d $f18,One
+l.d $f16,U2
+add.d $f10,$f18,$f16
+s.d $f10,Y2
+sub.d $f18,$f18,$f16
+s.d $f18,Y1
+l.d $f18,OneAndHalf
+s.d $f18,-80+240($sp)
+add.d $f10,$f18,$f16
+s.d $f10,-72+240($sp)
+add.d $f8,$f10,$f16
+s.d $f8,Z
+l.d $f8,Z
+l.d $f6,Y2
+div.d $f4,$f8,$f6
+s.d $f4,X
+sub.d $f4,$f18,$f16
+sub.d $f4,$f4,$f16
+s.d $f4,T
+l.d $f4,T
+l.d $f10,Y1
+sub.d $f18,$f4,$f16
+div.d $f18,$f18,$f10
+s.d $f18,Y
+add.d $f18,$f8,$f16
+div.d $f18,$f18,$f6
+s.d $f18,Z
+l.d $f18,X
+l.d $f8,-80+240($sp)
+sub.d $f18,$f18,$f8
+s.d $f18,X
+l.d $f18,Y
+sub.d $f18,$f18,$f4
+s.d $f18,Y
+div.d $f18,$f4,$f10
+s.d $f18,T
+l.d $f18,Z
+l.d $f10,-72+240($sp)
+sub.d $f18,$f18,$f10
+s.d $f18,Z
+l.d $f18,-80+240($sp)
+sub.d $f18,$f16,$f18
+l.d $f16,T
+add.d $f18,$f18,$f16
+s.d $f18,T
+l.d $f18,Zero
+l.d $f16,X
+c.le.d $f16,$f18; bc1f L.257
+l.d $f16,Y
+c.le.d $f16,$f18; bc1f L.257
+l.d $f16,Z
+c.le.d $f16,$f18; bc1f L.257
+l.d $f16,T
+c.le.d $f16,$f18; bc1f L.257
+l.d $f18,OneAndHalf
+l.d $f16,Y2
+div.d $f10,$f18,$f16
+s.d $f10,X
+l.d $f10,U2
+sub.d $f8,$f18,$f10
+s.d $f8,Y
+add.d $f8,$f18,$f10
+s.d $f8,Z
+l.d $f8,Y
+l.d $f6,X
+sub.d $f6,$f6,$f8
+s.d $f6,X
+l.d $f6,Y1
+div.d $f4,$f18,$f6
+s.d $f4,T
+div.d $f8,$f8,$f6
+s.d $f8,Y
+l.d $f8,Z
+l.d $f6,T
+add.d $f4,$f8,$f10
+sub.d $f6,$f6,$f4
+s.d $f6,T
+l.d $f6,Y
+sub.d $f6,$f6,$f8
+s.d $f6,Y
+div.d $f8,$f8,$f16
+s.d $f8,Z
+add.d $f10,$f16,$f10
+div.d $f10,$f10,$f16
+s.d $f10,Y1
+l.d $f10,Z
+sub.d $f18,$f10,$f18
+s.d $f18,Z
+l.d $f18,Y1
+sub.d $f18,$f18,$f16
+s.d $f18,Y2
+l.d $f18,F9
+l.d $f16,U1
+sub.d $f16,$f18,$f16
+div.d $f18,$f16,$f18
+s.d $f18,Y1
+l.d $f18,Zero
+l.d $f16,X
+c.eq.d $f16,$f18; bc1f L.259
+l.d $f16,Y
+c.eq.d $f16,$f18; bc1f L.259
+l.d $f16,Z
+c.eq.d $f16,$f18; bc1f L.259
+l.d $f16,T
+c.eq.d $f16,$f18; bc1f L.259
+l.d $f16,Y2
+c.eq.d $f16,$f18; bc1f L.259
+c.eq.d $f16,$f18; bc1f L.259
+l.d $f18,Half
+l.d $f16,Y1
+sub.d $f16,$f16,$f18
+l.d $f10,F9
+sub.d $f18,$f10,$f18
+c.eq.d $f16,$f18; bc1f L.259
+la $24,1
+sw $24,RDiv
+la $4,L.261
+jal printf
+lw $24,GDiv
+bne $24,$0,L.260
+la $4,L.264
+jal notify
+b L.260
+L.259:
+l.d $f18,Zero
+l.d $f16,X
+c.lt.d $f16,$f18; bc1f L.265
+l.d $f16,Y
+c.lt.d $f16,$f18; bc1f L.265
+l.d $f16,Z
+c.lt.d $f16,$f18; bc1f L.265
+l.d $f16,T
+c.lt.d $f16,$f18; bc1f L.265
+l.d $f16,Y2
+c.lt.d $f16,$f18; bc1f L.265
+l.d $f18,Half
+l.d $f16,Y1
+sub.d $f16,$f16,$f18
+l.d $f10,F9
+sub.d $f18,$f10,$f18
+c.lt.d $f16,$f18; bc1f L.265
+la $24,2
+sw $24,RDiv
+la $4,L.267
+jal printf
+L.265:
+L.260:
+L.257:
+lw $24,RDiv
+bne $24,$0,L.268
+la $4,L.270
+jal printf
+L.268:
+l.d $f18,Radix
+l.d $f16,One
+div.d $f16,$f16,$f18
+s.d $f16,BInvrse
+move $4,$0
+l.d $f16,Half
+l.d $f10,BInvrse
+mul.d $f18,$f10,$f18
+sub.d $f18,$f18,$f16
+c.eq.d $f18,$f16; bc1f L.273
+la $24,1
+sw $24,-84+240($sp)
+b L.274
+L.273:
+sw $0,-84+240($sp)
+L.274:
+lw $5,-84+240($sp)
+la $6,L.272
+jal TstCond
+la $24,50
+sw $24,Milestone
+move $4,$0
+l.d $f18,Half
+l.d $f16,F9
+l.d $f10,U1
+add.d $f16,$f16,$f10
+sub.d $f16,$f16,$f18
+c.eq.d $f16,$f18; bc1f L.277
+l.d $f18,One
+l.d $f16,BMinusU2
+l.d $f10,U2
+add.d $f16,$f16,$f10
+sub.d $f16,$f16,$f18
+l.d $f10,Radix
+sub.d $f18,$f10,$f18
+c.eq.d $f16,$f18; bc1f L.277
+la $24,1
+sw $24,-88+240($sp)
+b L.278
+L.277:
+sw $0,-88+240($sp)
+L.278:
+lw $5,-88+240($sp)
+la $6,L.276
+jal TstCond
+l.d $f18,One
+l.d $f16,U1
+mul.d $f16,$f16,$f16
+sub.d $f16,$f18,$f16
+s.d $f16,X
+l.d $f16,U2
+sub.d $f10,$f18,$f16
+mul.d $f16,$f16,$f10
+add.d $f16,$f18,$f16
+s.d $f16,Y
+l.d $f16,Half
+l.d $f10,F9
+sub.d $f10,$f10,$f16
+s.d $f10,Z
+l.d $f10,X
+sub.d $f16,$f10,$f16
+l.d $f10,Z
+sub.d $f16,$f16,$f10
+s.d $f16,X
+l.d $f16,Y
+sub.d $f18,$f16,$f18
+s.d $f18,Y
+l.d $f18,Zero
+l.d $f16,X
+c.eq.d $f16,$f18; bc1f L.279
+l.d $f16,Y
+c.eq.d $f16,$f18; bc1f L.279
+la $24,2
+sw $24,RAddSub
+la $4,L.281
+jal printf
+L.279:
+lw $24,GAddSub
+la $15,1
+bne $24,$15,L.282
+l.d $f18,Half
+l.d $f16,U2
+add.d $f10,$f18,$f16
+mul.d $f10,$f10,$f16
+s.d $f10,X
+sub.d $f18,$f18,$f16
+mul.d $f18,$f18,$f16
+s.d $f18,Y
+l.d $f18,One
+l.d $f10,X
+add.d $f10,$f18,$f10
+s.d $f10,X
+l.d $f10,Y
+add.d $f10,$f18,$f10
+s.d $f10,Y
+add.d $f16,$f18,$f16
+l.d $f10,X
+sub.d $f16,$f16,$f10
+s.d $f16,X
+l.d $f16,Y
+sub.d $f18,$f18,$f16
+s.d $f18,Y
+l.d $f18,Zero
+l.d $f16,X
+c.eq.d $f16,$f18; bc1f L.284
+l.d $f16,Y
+c.eq.d $f16,$f18; bc1f L.284
+l.d $f18,Half
+l.d $f16,U2
+l.d $f10,U1
+add.d $f8,$f18,$f16
+mul.d $f8,$f8,$f10
+s.d $f8,X
+sub.d $f18,$f18,$f16
+mul.d $f18,$f18,$f10
+s.d $f18,Y
+l.d $f18,One
+l.d $f16,X
+sub.d $f16,$f18,$f16
+s.d $f16,X
+l.d $f16,Y
+sub.d $f16,$f18,$f16
+s.d $f16,Y
+l.d $f16,F9
+l.d $f10,X
+sub.d $f16,$f16,$f10
+s.d $f16,X
+l.d $f16,Y
+sub.d $f18,$f18,$f16
+s.d $f18,Y
+l.d $f18,Zero
+l.d $f16,X
+c.eq.d $f16,$f18; bc1f L.286
+l.d $f16,Y
+c.eq.d $f16,$f18; bc1f L.286
+la $24,1
+sw $24,RAddSub
+la $4,L.288
+jal printf
+lw $24,GAddSub
+bne $24,$0,L.283
+la $4,L.291
+jal notify
+b L.283
+L.286:
+la $4,L.292
+jal printf
+b L.283
+L.284:
+la $4,L.292
+jal printf
+b L.283
+L.282:
+la $4,L.292
+jal printf
+L.283:
+l.d $f18,One
+s.d $f18,S
+l.d $f16,Half
+add.d $f10,$f18,$f16
+mul.d $f10,$f16,$f10
+add.d $f10,$f18,$f10
+s.d $f10,X
+l.d $f10,U2
+add.d $f18,$f18,$f10
+mul.d $f18,$f18,$f16
+s.d $f18,Y
+l.d $f18,X
+l.d $f16,Y
+sub.d $f10,$f18,$f16
+s.d $f10,Z
+sub.d $f18,$f16,$f18
+s.d $f18,T
+l.d $f18,Z
+l.d $f16,T
+add.d $f18,$f18,$f16
+s.d $f18,StickyBit
+l.d $f18,StickyBit
+l.d $f16,Zero
+c.eq.d $f18,$f16; bc1t L.293
+l.d $f18,Zero
+s.d $f18,S
+la $4,3
+la $5,L.295
+jal BadCond
+L.293:
+l.d $f18,Zero
+s.d $f18,StickyBit
+la $24,1
+lw $15,GMult
+bne $15,$24,L.296
+lw $15,GDiv
+bne $15,$24,L.296
+lw $15,GAddSub
+bne $15,$24,L.296
+lw $15,RMult
+bne $15,$24,L.296
+lw $15,RDiv
+bne $15,$24,L.296
+lw $15,RAddSub
+bne $15,$24,L.296
+l.d $f12,RadixD2
+jal floor
+l.d $f16,RadixD2
+c.eq.d $f0,$f16; bc1f L.296
+la $4,L.298
+jal printf
+l.d $f18,Half
+l.d $f16,U2
+l.d $f10,U1
+add.d $f10,$f18,$f10
+mul.d $f10,$f10,$f16
+s.d $f10,X
+mul.d $f18,$f18,$f16
+s.d $f18,Y
+l.d $f18,One
+l.d $f16,Y
+add.d $f16,$f18,$f16
+s.d $f16,Z
+l.d $f16,X
+add.d $f18,$f18,$f16
+s.d $f18,T
+l.d $f18,One
+l.d $f16,Z
+sub.d $f16,$f16,$f18
+l.d $f10,Zero
+c.le.d $f16,$f10; bc1f L.299
+l.d $f16,T
+sub.d $f18,$f16,$f18
+l.d $f16,U2
+c.lt.d $f18,$f16; bc1t L.299
+l.d $f18,T
+l.d $f16,Y
+add.d $f18,$f18,$f16
+s.d $f18,Z
+l.d $f18,Z
+l.d $f16,X
+sub.d $f18,$f18,$f16
+s.d $f18,Y
+l.d $f18,T
+l.d $f16,Z
+sub.d $f16,$f16,$f18
+l.d $f10,U2
+c.lt.d $f16,$f10; bc1t L.301
+l.d $f16,Y
+sub.d $f18,$f16,$f18
+l.d $f16,Zero
+c.eq.d $f18,$f16; bc1f L.301
+l.d $f18,Half
+l.d $f16,U1
+add.d $f10,$f18,$f16
+mul.d $f10,$f10,$f16
+s.d $f10,X
+mul.d $f18,$f18,$f16
+s.d $f18,Y
+l.d $f18,One
+l.d $f16,Y
+sub.d $f16,$f18,$f16
+s.d $f16,Z
+l.d $f16,X
+sub.d $f18,$f18,$f16
+s.d $f18,T
+l.d $f18,Zero
+l.d $f16,Z
+l.d $f10,One
+sub.d $f16,$f16,$f10
+c.eq.d $f16,$f18; bc1f L.303
+l.d $f16,T
+l.d $f10,F9
+sub.d $f16,$f16,$f10
+c.eq.d $f16,$f18; bc1f L.303
+l.d $f18,U1
+l.d $f16,Half
+sub.d $f16,$f16,$f18
+mul.d $f18,$f16,$f18
+s.d $f18,Z
+l.d $f18,F9
+l.d $f16,Z
+sub.d $f16,$f18,$f16
+s.d $f16,T
+l.d $f16,Y
+sub.d $f18,$f18,$f16
+s.d $f18,Q
+l.d $f18,F9
+l.d $f16,Zero
+l.d $f10,T
+sub.d $f10,$f10,$f18
+c.eq.d $f10,$f16; bc1f L.305
+l.d $f10,U1
+sub.d $f18,$f18,$f10
+l.d $f10,Q
+sub.d $f18,$f18,$f10
+c.eq.d $f18,$f16; bc1f L.305
+l.d $f18,One
+l.d $f16,U2
+l.d $f10,OneAndHalf
+add.d $f8,$f18,$f16
+mul.d $f8,$f8,$f10
+s.d $f8,Z
+add.d $f10,$f10,$f16
+l.d $f8,Z
+sub.d $f10,$f10,$f8
+add.d $f10,$f10,$f16
+s.d $f10,T
+l.d $f10,Radix
+l.d $f8,Half
+div.d $f8,$f8,$f10
+add.d $f8,$f18,$f8
+s.d $f8,X
+mul.d $f16,$f10,$f16
+add.d $f18,$f18,$f16
+s.d $f18,Y
+l.d $f18,X
+l.d $f16,Y
+mul.d $f18,$f18,$f16
+s.d $f18,Z
+l.d $f18,Zero
+l.d $f16,T
+c.eq.d $f16,$f18; bc1f L.307
+l.d $f16,X
+l.d $f10,Radix
+l.d $f8,U2
+mul.d $f10,$f10,$f8
+add.d $f16,$f16,$f10
+l.d $f10,Z
+sub.d $f16,$f16,$f10
+c.eq.d $f16,$f18; bc1f L.307
+l.d $f18,Radix
+l.d $f16,Two
+c.eq.d $f18,$f16; bc1t L.309
+l.d $f18,Two
+l.d $f16,U2
+add.d $f16,$f18,$f16
+s.d $f16,X
+l.d $f16,X
+div.d $f18,$f16,$f18
+s.d $f18,Y
+l.d $f18,Y
+l.d $f16,One
+sub.d $f18,$f18,$f16
+l.d $f16,Zero
+c.eq.d $f18,$f16; bc1f L.310
+l.d $f18,S
+s.d $f18,StickyBit
+b L.310
+L.309:
+l.d $f18,S
+s.d $f18,StickyBit
+L.310:
+L.307:
+L.305:
+L.303:
+L.301:
+L.299:
+L.296:
+l.d $f18,StickyBit
+l.d $f16,One
+c.eq.d $f18,$f16; bc1f L.313
+la $4,L.315
+jal printf
+b L.314
+L.313:
+la $4,L.316
+jal printf
+L.314:
+la $4,3
+lw $15,GMult
+beq $15,$0,L.319
+lw $15,GDiv
+beq $15,$0,L.319
+lw $15,GAddSub
+beq $15,$0,L.319
+lw $15,RMult
+beq $15,$0,L.319
+lw $15,RDiv
+beq $15,$0,L.319
+lw $15,RAddSub
+beq $15,$0,L.319
+la $24,1
+sw $24,-92+240($sp)
+b L.320
+L.319:
+sw $0,-92+240($sp)
+L.320:
+lw $5,-92+240($sp)
+la $6,L.318
+jal TstCond
+la $24,60
+sw $24,Milestone
+la $4,L.44
+jal printf
+la $4,L.321
+jal printf
+la $4,L.322
+lw $5,NoTrials
+jal printf
+l.d $f12,L.323
+jal sqrt
+s.d $f0,Random9
+l.d $f18,Third
+s.d $f18,Random1
+la $24,1
+sw $24,I
+L.324:
+jal Random
+s.d $f0,X
+jal Random
+s.d $f0,Y
+l.d $f18,Y
+l.d $f16,X
+mul.d $f10,$f18,$f16
+s.d $f10,Z9
+mul.d $f18,$f16,$f18
+s.d $f18,Z
+l.d $f18,Z
+l.d $f16,Z9
+sub.d $f18,$f18,$f16
+s.d $f18,Z9
+lw $24,I
+la $24,1($24)
+sw $24,I
+L.325:
+lw $24,I
+lw $15,NoTrials
+bgt $24,$15,L.327
+l.d $f18,Z9
+l.d $f16,Zero
+c.eq.d $f18,$f16; bc1t L.324
+L.327:
+lw $24,I
+lw $15,NoTrials
+bne $24,$15,L.328
+l.d $f18,One
+l.d $f16,Half
+l.d $f10,Three
+div.d $f16,$f16,$f10
+add.d $f16,$f18,$f16
+s.d $f16,Random1
+l.d $f10,U2
+l.d $f8,U1
+add.d $f10,$f10,$f8
+add.d $f18,$f10,$f18
+s.d $f18,Random2
+l.d $f10,Random1
+l.d $f8,Random2
+mul.d $f6,$f10,$f8
+s.d $f6,Z
+mul.d $f10,$f8,$f10
+s.d $f10,Y
+mul.d $f18,$f16,$f18
+sub.d $f18,$f18,$f18
+s.d $f18,Z9
+L.328:
+lw $24,I
+lw $15,NoTrials
+beq $24,$15,L.330
+l.d $f18,Z9
+l.d $f16,Zero
+c.eq.d $f18,$f16; bc1t L.330
+la $4,2
+la $5,L.332
+jal BadCond
+b L.331
+L.330:
+la $4,L.333
+lw $5,NoTrials
+jal printf
+L.331:
+la $24,70
+sw $24,Milestone
+la $4,L.334
+jal printf
+l.d $f18,Zero
+s.d $f18,-104+240($sp)
+mov.d $f12,$f18
+jal sqrt
+l.d $f16,-104+240($sp)
+c.eq.d $f16,$f0; bc1f L.337
+l.d $f18,Zero
+neg.d $f18,$f18
+s.d $f18,-112+240($sp)
+mov.d $f12,$f18
+jal sqrt
+l.d $f16,-112+240($sp)
+c.eq.d $f16,$f0; bc1f L.337
+l.d $f18,One
+s.d $f18,-120+240($sp)
+mov.d $f12,$f18
+jal sqrt
+mov.d $f18,$f0
+l.d $f16,-120+240($sp)
+c.eq.d $f16,$f18; bc1f L.337
+la $24,1
+sw $24,-96+240($sp)
+b L.338
+L.337:
+sw $0,-96+240($sp)
+L.338:
+move $4,$0
+lw $5,-96+240($sp)
+la $6,L.336
+jal TstCond
+l.d $f18,Zero
+s.d $f18,MinSqEr
+s.d $f18,MaxSqEr
+s.d $f18,J
+l.d $f18,Radix
+s.d $f18,X
+l.d $f18,U2
+s.d $f18,OneUlp
+la $4,1
+jal SqXMinX
+l.d $f18,BInvrse
+s.d $f18,X
+l.d $f16,U1
+mul.d $f18,$f18,$f16
+s.d $f18,OneUlp
+la $4,1
+jal SqXMinX
+l.d $f18,U1
+s.d $f18,X
+mul.d $f18,$f18,$f18
+s.d $f18,OneUlp
+la $4,1
+jal SqXMinX
+l.d $f18,J
+l.d $f16,Zero
+c.eq.d $f18,$f16; bc1t L.339
+jal Pause
+L.339:
+la $4,L.341
+lw $5,NoTrials
+jal printf
+l.d $f18,Zero
+s.d $f18,J
+l.d $f18,Two
+s.d $f18,X
+l.d $f18,Radix
+s.d $f18,Y
+l.d $f16,One
+c.eq.d $f18,$f16; bc1t L.342
+L.344:
+l.d $f18,Y
+s.d $f18,X
+l.d $f16,Radix
+mul.d $f18,$f16,$f18
+s.d $f18,Y
+L.345:
+l.d $f18,Y
+l.d $f16,X
+sub.d $f18,$f18,$f16
+lw $24,NoTrials
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+c.lt.d $f18,$f16; bc1t L.344
+L.342:
+l.d $f18,X
+l.d $f16,U2
+mul.d $f18,$f18,$f16
+s.d $f18,OneUlp
+la $24,1
+sw $24,I
+b L.348
+L.347:
+l.d $f18,X
+l.d $f16,One
+add.d $f18,$f18,$f16
+s.d $f18,X
+la $4,2
+jal SqXMinX
+l.d $f18,J
+l.d $f16,Zero
+c.le.d $f18,$f16; bc1t L.350
+b L.349
+L.350:
+lw $24,I
+la $24,1($24)
+sw $24,I
+L.348:
+lw $24,I
+lw $15,NoTrials
+ble $24,$15,L.347
+L.349:
+la $4,L.352
+jal printf
+la $24,-1
+sw $24,I
+l.d $f18,BMinusU2
+s.d $f18,X
+l.d $f18,Radix
+s.d $f18,Y
+l.d $f16,U2
+mul.d $f16,$f18,$f16
+add.d $f18,$f18,$f16
+s.d $f18,Z
+sw $0,NotMonot
+sw $0,Monot
+b L.354
+L.353:
+lw $24,I
+la $24,1($24)
+sw $24,I
+l.d $f12,X
+jal sqrt
+s.d $f0,X
+l.d $f12,Y
+jal sqrt
+s.d $f0,Q
+l.d $f12,Z
+jal sqrt
+s.d $f0,Z
+l.d $f18,Q
+l.d $f16,X
+c.le.d $f16,$f18; bc1f L.358
+l.d $f16,Z
+c.le.d $f18,$f16; bc1t L.356
+L.358:
+la $24,1
+sw $24,NotMonot
+b L.357
+L.356:
+l.d $f18,Q
+l.d $f16,Half
+add.d $f12,$f18,$f16
+jal floor
+s.d $f0,Q
+lw $24,I
+bgt $24,$0,L.361
+l.d $f18,Q
+l.d $f16,Radix
+mul.d $f18,$f18,$f18
+c.eq.d $f16,$f18; bc1f L.359
+L.361:
+la $24,1
+sw $24,Monot
+b L.360
+L.359:
+lw $24,I
+ble $24,$0,L.362
+lw $24,I
+la $15,1
+ble $24,$15,L.364
+la $24,1
+sw $24,Monot
+b L.363
+L.364:
+l.d $f18,Y
+l.d $f16,BInvrse
+mul.d $f18,$f18,$f16
+s.d $f18,Y
+l.d $f18,Y
+l.d $f16,U1
+sub.d $f10,$f18,$f16
+s.d $f10,X
+add.d $f18,$f18,$f16
+s.d $f18,Z
+b L.363
+L.362:
+l.d $f18,Q
+s.d $f18,Y
+l.d $f18,Y
+l.d $f16,U2
+sub.d $f10,$f18,$f16
+s.d $f10,X
+add.d $f18,$f18,$f16
+s.d $f18,Z
+L.363:
+L.360:
+L.357:
+L.354:
+lw $15,NotMonot
+bne $15,$0,L.366
+lw $15,Monot
+beq $15,$0,L.353
+L.366:
+lw $24,Monot
+beq $24,$0,L.367
+la $4,L.369
+jal printf
+b L.368
+L.367:
+la $4,2
+la $5,L.157
+jal BadCond
+la $4,L.370
+l.d $f18,Y
+mfc1.d $6,$f18
+jal printf
+L.368:
+la $24,80
+sw $24,Milestone
+l.d $f18,Half
+l.d $f16,MinSqEr
+add.d $f16,$f16,$f18
+s.d $f16,MinSqEr
+l.d $f16,MaxSqEr
+sub.d $f18,$f16,$f18
+s.d $f18,MaxSqEr
+l.d $f18,One
+l.d $f16,U2
+add.d $f12,$f18,$f16
+jal sqrt
+l.d $f16,One
+l.d $f10,U2
+sub.d $f18,$f0,$f16
+div.d $f18,$f18,$f10
+s.d $f18,Y
+l.d $f18,Y
+sub.d $f18,$f18,$f16
+l.d $f16,Eight
+div.d $f16,$f10,$f16
+add.d $f18,$f18,$f16
+s.d $f18,SqEr
+l.d $f18,SqEr
+l.d $f16,MaxSqEr
+c.le.d $f18,$f16; bc1t L.371
+l.d $f18,SqEr
+s.d $f18,MaxSqEr
+L.371:
+l.d $f18,Y
+l.d $f16,U2
+l.d $f10,Eight
+div.d $f16,$f16,$f10
+add.d $f18,$f18,$f16
+s.d $f18,SqEr
+l.d $f18,SqEr
+l.d $f16,MinSqEr
+c.lt.d $f18,$f16; bc1f L.373
+l.d $f18,SqEr
+s.d $f18,MinSqEr
+L.373:
+l.d $f12,F9
+jal sqrt
+l.d $f16,U2
+l.d $f10,U1
+sub.d $f18,$f0,$f16
+l.d $f8,One
+sub.d $f16,$f8,$f16
+sub.d $f18,$f18,$f16
+div.d $f18,$f18,$f10
+s.d $f18,Y
+l.d $f18,Y
+l.d $f16,Eight
+div.d $f16,$f10,$f16
+add.d $f18,$f18,$f16
+s.d $f18,SqEr
+l.d $f18,SqEr
+l.d $f16,MaxSqEr
+c.le.d $f18,$f16; bc1t L.375
+l.d $f18,SqEr
+s.d $f18,MaxSqEr
+L.375:
+l.d $f18,Y
+l.d $f16,One
+add.d $f18,$f18,$f16
+l.d $f16,U1
+l.d $f10,Eight
+div.d $f16,$f16,$f10
+add.d $f18,$f18,$f16
+s.d $f18,SqEr
+l.d $f18,SqEr
+l.d $f16,MinSqEr
+c.lt.d $f18,$f16; bc1f L.377
+l.d $f18,SqEr
+s.d $f18,MinSqEr
+L.377:
+l.d $f18,U2
+s.d $f18,OneUlp
+l.d $f18,OneUlp
+s.d $f18,X
+la $24,1
+sw $24,Indx
+L.379:
+l.d $f18,X
+l.d $f16,U1
+add.d $f16,$f18,$f16
+add.d $f18,$f16,$f18
+l.d $f16,F9
+add.d $f12,$f18,$f16
+jal sqrt
+s.d $f0,Y
+l.d $f18,U2
+l.d $f16,X
+l.d $f10,OneUlp
+l.d $f8,Y
+sub.d $f8,$f8,$f18
+l.d $f6,One
+sub.d $f18,$f6,$f18
+add.d $f18,$f18,$f16
+sub.d $f18,$f8,$f18
+div.d $f18,$f18,$f10
+s.d $f18,Y
+l.d $f18,Half
+l.d $f8,U1
+sub.d $f8,$f8,$f16
+l.d $f6,F9
+add.d $f8,$f8,$f6
+mul.d $f8,$f8,$f18
+mul.d $f8,$f8,$f16
+mul.d $f16,$f8,$f16
+div.d $f16,$f16,$f10
+s.d $f16,Z
+l.d $f16,Y
+add.d $f18,$f16,$f18
+l.d $f16,Z
+add.d $f18,$f18,$f16
+s.d $f18,SqEr
+l.d $f18,SqEr
+l.d $f16,MinSqEr
+c.lt.d $f18,$f16; bc1f L.383
+l.d $f18,SqEr
+s.d $f18,MinSqEr
+L.383:
+l.d $f18,Y
+l.d $f16,Half
+sub.d $f18,$f18,$f16
+l.d $f16,Z
+add.d $f18,$f18,$f16
+s.d $f18,SqEr
+l.d $f18,SqEr
+l.d $f16,MaxSqEr
+c.le.d $f18,$f16; bc1t L.385
+l.d $f18,SqEr
+s.d $f18,MaxSqEr
+L.385:
+lw $24,Indx
+la $15,1
+beq $24,$15,L.389
+la $15,3
+bne $24,$15,L.387
+L.389:
+l.d $f12,X
+jal Sign
+mov.d $f18,$f0
+s.d $f18,-128+240($sp)
+l.d $f12,OneUlp
+jal sqrt
+l.d $f16,Eight
+l.d $f10,Nine
+mul.d $f18,$f10,$f0
+div.d $f12,$f16,$f18
+jal floor
+l.d $f16,OneUlp
+l.d $f10,-128+240($sp)
+mul.d $f16,$f16,$f10
+mul.d $f18,$f16,$f0
+s.d $f18,X
+b L.388
+L.387:
+l.d $f18,U1
+s.d $f18,OneUlp
+l.d $f18,OneUlp
+neg.d $f18,$f18
+s.d $f18,X
+L.388:
+L.380:
+lw $24,Indx
+la $24,1($24)
+sw $24,Indx
+lw $24,Indx
+la $15,3
+ble $24,$15,L.379
+la $24,85
+sw $24,Milestone
+sw $0,SqRWrng
+sw $0,Anomaly
+sw $0,RSqrt
+l.d $f18,Radix
+l.d $f16,One
+c.eq.d $f18,$f16; bc1t L.390
+la $4,L.392
+jal printf
+l.d $f18,Precision
+s.d $f18,-128+240($sp)
+mov.d $f12,$f18
+jal floor
+mov.d $f18,$f0
+l.d $f12,Radix
+l.d $f16,One
+l.d $f10,-128+240($sp)
+add.d $f16,$f16,$f10
+sub.d $f14,$f16,$f18
+jal pow
+mov.d $f18,$f0
+l.d $f16,Half
+add.d $f12,$f16,$f18
+jal floor
+s.d $f0,D
+l.d $f18,D
+l.d $f16,Radix
+div.d $f16,$f18,$f16
+s.d $f16,X
+l.d $f16,A1
+div.d $f18,$f18,$f16
+s.d $f18,Y
+l.d $f18,X
+s.d $f18,-136+240($sp)
+mov.d $f12,$f18
+jal floor
+l.d $f16,-136+240($sp)
+c.eq.d $f16,$f0; bc1f L.395
+l.d $f18,Y
+s.d $f18,-144+240($sp)
+mov.d $f12,$f18
+jal floor
+l.d $f16,-144+240($sp)
+c.eq.d $f16,$f0; bc1t L.393
+L.395:
+la $24,1
+sw $24,Anomaly
+b L.394
+L.393:
+l.d $f18,Zero
+s.d $f18,X
+l.d $f18,X
+s.d $f18,Z2
+l.d $f18,One
+s.d $f18,Y
+l.d $f16,Y
+s.d $f16,Y2
+l.d $f16,Radix
+sub.d $f18,$f16,$f18
+s.d $f18,Z1
+l.d $f18,Four
+l.d $f16,D
+mul.d $f18,$f18,$f16
+s.d $f18,FourD
+L.396:
+l.d $f18,Y2
+l.d $f16,Z2
+c.le.d $f18,$f16; bc1t L.399
+l.d $f18,Radix
+s.d $f18,Q
+l.d $f18,Y
+s.d $f18,Y1
+L.401:
+l.d $f18,Q
+s.d $f18,-152+240($sp)
+l.d $f16,Half
+l.d $f10,Y1
+div.d $f10,$f18,$f10
+sub.d $f12,$f16,$f10
+jal floor
+l.d $f16,Y1
+mul.d $f18,$f0,$f16
+l.d $f16,-152+240($sp)
+add.d $f12,$f16,$f18
+jal fabs
+s.d $f0,X1
+l.d $f18,Y1
+s.d $f18,Q
+l.d $f18,X1
+s.d $f18,Y1
+L.402:
+l.d $f18,X1
+l.d $f16,Zero
+c.le.d $f18,$f16; bc1f L.401
+l.d $f18,Q
+l.d $f16,One
+c.le.d $f18,$f16; bc1f L.404
+l.d $f18,Y2
+s.d $f18,Z2
+l.d $f18,Y
+s.d $f18,Z
+L.404:
+L.399:
+l.d $f18,Y
+l.d $f16,Two
+add.d $f18,$f18,$f16
+s.d $f18,Y
+l.d $f18,X
+l.d $f16,Eight
+add.d $f18,$f18,$f16
+s.d $f18,X
+l.d $f18,Y2
+l.d $f16,X
+add.d $f18,$f18,$f16
+s.d $f18,Y2
+l.d $f18,Y2
+l.d $f16,FourD
+c.lt.d $f18,$f16; bc1t L.406
+l.d $f18,Y2
+l.d $f16,FourD
+sub.d $f18,$f18,$f16
+s.d $f18,Y2
+L.406:
+L.397:
+l.d $f18,Y
+l.d $f16,D
+c.lt.d $f18,$f16; bc1t L.396
+l.d $f18,FourD
+l.d $f16,Z2
+sub.d $f16,$f18,$f16
+s.d $f16,X8
+l.d $f16,X8
+l.d $f10,Z
+mul.d $f10,$f10,$f10
+add.d $f10,$f16,$f10
+div.d $f18,$f10,$f18
+s.d $f18,Q
+l.d $f18,Eight
+div.d $f18,$f16,$f18
+s.d $f18,X8
+l.d $f18,Q
+s.d $f18,-152+240($sp)
+mov.d $f12,$f18
+jal floor
+l.d $f16,-152+240($sp)
+c.eq.d $f16,$f0; bc1t L.408
+la $24,1
+sw $24,Anomaly
+b L.409
+L.408:
+sw $0,Break
+L.410:
+l.d $f18,Z1
+l.d $f16,Z
+mul.d $f18,$f18,$f16
+s.d $f18,X
+l.d $f18,X
+s.d $f18,-160+240($sp)
+l.d $f16,Radix
+div.d $f12,$f18,$f16
+jal floor
+l.d $f16,Radix
+mul.d $f18,$f0,$f16
+l.d $f16,-160+240($sp)
+sub.d $f18,$f16,$f18
+s.d $f18,X
+l.d $f18,X
+l.d $f16,One
+c.eq.d $f18,$f16; bc1f L.413
+la $24,1
+sw $24,Break
+b L.414
+L.413:
+l.d $f18,Z1
+l.d $f16,One
+sub.d $f18,$f18,$f16
+s.d $f18,Z1
+L.414:
+L.411:
+lw $24,Break
+bne $24,$0,L.415
+l.d $f18,Z1
+l.d $f16,Zero
+c.le.d $f18,$f16; bc1f L.410
+L.415:
+l.d $f18,Z1
+l.d $f16,Zero
+c.le.d $f18,$f16; bc1f L.416
+lw $24,Break
+bne $24,$0,L.416
+la $24,1
+sw $24,Anomaly
+b L.417
+L.416:
+l.d $f18,Z1
+l.d $f16,RadixD2
+c.le.d $f18,$f16; bc1t L.418
+l.d $f18,Z1
+l.d $f16,Radix
+sub.d $f18,$f18,$f16
+s.d $f18,Z1
+L.418:
+L.420:
+jal NewD
+L.421:
+l.d $f18,U2
+l.d $f16,D
+mul.d $f18,$f18,$f16
+l.d $f16,F9
+c.lt.d $f18,$f16; bc1t L.420
+l.d $f18,D
+l.d $f16,Radix
+mul.d $f16,$f18,$f16
+sub.d $f16,$f16,$f18
+l.d $f10,W
+sub.d $f18,$f10,$f18
+c.eq.d $f16,$f18; bc1t L.423
+la $24,1
+sw $24,Anomaly
+b L.424
+L.423:
+l.d $f18,D
+s.d $f18,Z2
+sw $0,I
+l.d $f16,Z
+l.d $f10,One
+add.d $f10,$f10,$f16
+l.d $f8,Half
+mul.d $f10,$f10,$f8
+add.d $f10,$f18,$f10
+s.d $f10,Y
+add.d $f18,$f18,$f16
+l.d $f16,Q
+add.d $f18,$f18,$f16
+s.d $f18,X
+jal SR3750
+l.d $f18,D
+l.d $f16,Z
+l.d $f10,One
+sub.d $f10,$f10,$f16
+l.d $f8,Half
+mul.d $f10,$f10,$f8
+add.d $f10,$f18,$f10
+add.d $f10,$f10,$f18
+s.d $f10,Y
+sub.d $f16,$f18,$f16
+add.d $f18,$f16,$f18
+s.d $f18,X
+l.d $f18,X
+l.d $f16,Q
+add.d $f16,$f18,$f16
+add.d $f18,$f16,$f18
+s.d $f18,X
+jal SR3750
+jal NewD
+l.d $f18,Z2
+l.d $f16,D
+sub.d $f16,$f16,$f18
+l.d $f10,W
+sub.d $f18,$f10,$f18
+c.eq.d $f16,$f18; bc1t L.425
+la $24,1
+sw $24,Anomaly
+b L.426
+L.425:
+l.d $f18,Z2
+l.d $f16,D
+sub.d $f16,$f16,$f18
+l.d $f10,Z
+l.d $f8,One
+sub.d $f8,$f8,$f10
+l.d $f6,Half
+mul.d $f8,$f8,$f6
+add.d $f8,$f18,$f8
+add.d $f8,$f16,$f8
+s.d $f8,Y
+sub.d $f18,$f18,$f10
+l.d $f10,Q
+add.d $f18,$f18,$f10
+add.d $f18,$f16,$f18
+s.d $f18,X
+jal SR3750
+l.d $f18,One
+l.d $f16,Z
+add.d $f18,$f18,$f16
+l.d $f16,Half
+mul.d $f18,$f18,$f16
+s.d $f18,Y
+l.d $f18,Q
+s.d $f18,X
+jal SR3750
+lw $24,I
+bne $24,$0,L.427
+la $24,1
+sw $24,Anomaly
+L.427:
+L.426:
+L.424:
+L.417:
+L.409:
+L.394:
+lw $15,I
+beq $15,$0,L.431
+lw $15,Anomaly
+beq $15,$0,L.429
+L.431:
+move $4,$0
+la $5,L.432
+jal BadCond
+la $4,L.433
+l.d $f18,W
+mfc1.d $6,$f18
+jal printf
+la $4,L.434
+jal printf
+la $24,1
+sw $24,SqRWrng
+L.429:
+L.390:
+lw $24,Anomaly
+bne $24,$0,L.435
+l.d $f18,Zero
+l.d $f16,MinSqEr
+c.lt.d $f16,$f18; bc1t L.437
+l.d $f16,MaxSqEr
+c.le.d $f16,$f18; bc1f L.437
+la $24,1
+sw $24,RSqrt
+la $4,L.439
+jal printf
+b L.438
+L.437:
+l.d $f18,U2
+l.d $f16,Half
+l.d $f10,MaxSqEr
+add.d $f10,$f10,$f18
+sub.d $f18,$f18,$f16
+c.le.d $f10,$f18; bc1f L.443
+l.d $f18,MinSqEr
+c.le.d $f18,$f16; bc1f L.443
+l.d $f10,Radix
+add.d $f18,$f18,$f10
+c.lt.d $f18,$f16; bc1f L.440
+L.443:
+la $24,1
+sw $24,SqRWrng
+b L.441
+L.440:
+la $24,2
+sw $24,RSqrt
+la $4,L.444
+jal printf
+L.441:
+L.438:
+L.435:
+lw $24,SqRWrng
+beq $24,$0,L.445
+la $4,L.447
+jal printf
+la $4,L.448
+l.d $f18,MinSqEr
+l.d $f16,Half
+sub.d $f18,$f18,$f16
+mfc1.d $6,$f18
+jal printf
+la $4,L.449
+l.d $f18,Half
+l.d $f16,MaxSqEr
+add.d $f18,$f18,$f16
+mfc1.d $6,$f18
+jal printf
+la $4,1
+l.d $f18,Radix
+l.d $f16,MaxSqEr
+l.d $f10,MinSqEr
+sub.d $f16,$f16,$f10
+mul.d $f18,$f18,$f18
+c.lt.d $f16,$f18; bc1f L.452
+la $24,1
+sw $24,-124+240($sp)
+b L.453
+L.452:
+sw $0,-124+240($sp)
+L.453:
+lw $5,-124+240($sp)
+la $6,L.451
+jal TstCond
+L.445:
+la $24,90
+sw $24,Milestone
+jal Pause
+la $4,L.454
+jal printf
+sw $0,N
+sw $0,I
+l.d $f18,Zero
+neg.d $f18,$f18
+s.d $f18,Z
+la $15,3
+sw $15,M
+sw $0,Break
+L.455:
+l.d $f18,One
+s.d $f18,X
+jal SR3980
+lw $24,I
+la $15,10
+bgt $24,$15,L.458
+la $24,1023
+sw $24,I
+jal SR3980
+L.458:
+l.d $f18,Z
+l.d $f16,MinusOne
+c.eq.d $f18,$f16; bc1f L.460
+la $24,1
+sw $24,Break
+b L.461
+L.460:
+l.d $f18,MinusOne
+s.d $f18,Z
+jal PrintIfNPositive
+sw $0,N
+la $24,-4
+sw $24,I
+L.461:
+L.456:
+lw $24,Break
+beq $24,$0,L.455
+jal PrintIfNPositive
+lw $24,N
+sw $24,N1
+sw $0,N
+l.d $f18,A1
+s.d $f18,Z
+l.d $f12,W
+jal log
+mov.d $f18,$f0
+s.d $f18,-128+240($sp)
+l.d $f12,A1
+jal log
+mov.d $f18,$f0
+l.d $f16,Two
+l.d $f10,-128+240($sp)
+mul.d $f16,$f16,$f10
+div.d $f12,$f16,$f18
+jal floor
+trunc.w.d $f2,$f0,$24; mfc1 $24,$f2
+sw $24,M
+sw $0,Break
+L.462:
+l.d $f18,Z
+s.d $f18,X
+la $24,1
+sw $24,I
+jal SR3980
+l.d $f18,Z
+l.d $f16,AInvrse
+c.eq.d $f18,$f16; bc1f L.465
+la $24,1
+sw $24,Break
+b L.466
+L.465:
+l.d $f18,AInvrse
+s.d $f18,Z
+L.466:
+L.463:
+lw $24,Break
+beq $24,$0,L.462
+la $24,100
+sw $24,Milestone
+lw $24,NoTrials
+sw $24,M
+l.d $f18,Three
+s.d $f18,Z
+L.467:
+l.d $f18,Z
+s.d $f18,X
+la $24,1
+sw $24,I
+jal SR3980
+L.470:
+l.d $f18,Z
+l.d $f16,Two
+add.d $f18,$f18,$f16
+s.d $f18,Z
+L.471:
+l.d $f18,Three
+s.d $f18,-136+240($sp)
+l.d $f16,Z
+div.d $f12,$f16,$f18
+jal floor
+l.d $f16,-136+240($sp)
+mul.d $f18,$f16,$f0
+l.d $f16,Z
+c.eq.d $f18,$f16; bc1t L.470
+L.468:
+l.d $f18,Z
+l.d $f16,Eight
+l.d $f10,Three
+mul.d $f16,$f16,$f10
+c.lt.d $f18,$f16; bc1t L.467
+lw $24,N
+ble $24,$0,L.473
+la $4,L.475
+jal printf
+la $4,L.476
+jal printf
+L.473:
+jal PrintIfNPositive
+lw $24,N
+lw $15,N1
+addu $24,$24,$15
+sw $24,N
+lw $24,N
+bne $24,$0,L.477
+la $4,L.479
+jal printf
+L.477:
+lw $24,N
+ble $24,$0,L.480
+jal Pause
+b L.481
+L.480:
+la $4,L.44
+jal printf
+L.481:
+la $24,110
+sw $24,Milestone
+la $4,L.482
+jal printf
+l.d $f18,U1
+s.d $f18,D
+l.d $f18,Precision
+s.d $f18,-136+240($sp)
+mov.d $f12,$f18
+jal floor
+l.d $f16,-136+240($sp)
+c.eq.d $f16,$f0; bc1t L.483
+l.d $f18,BInvrse
+s.d $f18,D
+l.d $f18,Precision
+s.d $f18,X
+L.485:
+l.d $f18,D
+l.d $f16,BInvrse
+mul.d $f18,$f18,$f16
+s.d $f18,D
+l.d $f18,X
+l.d $f16,One
+sub.d $f18,$f18,$f16
+s.d $f18,X
+L.486:
+l.d $f18,X
+l.d $f16,Zero
+c.le.d $f18,$f16; bc1f L.485
+L.483:
+l.d $f18,One
+s.d $f18,Y
+l.d $f18,D
+s.d $f18,Z
+L.488:
+l.d $f18,Y
+s.d $f18,C
+l.d $f18,Z
+s.d $f18,Y
+l.d $f18,Y
+mul.d $f18,$f18,$f18
+s.d $f18,Z
+L.489:
+l.d $f18,Z
+l.d $f16,Y
+c.le.d $f16,$f18; bc1t L.491
+add.d $f16,$f18,$f18
+c.le.d $f16,$f18; bc1f L.488
+L.491:
+l.d $f18,C
+s.d $f18,Y
+l.d $f18,Y
+l.d $f16,D
+mul.d $f18,$f18,$f16
+s.d $f18,Z
+L.492:
+l.d $f18,Y
+s.d $f18,C
+l.d $f18,Z
+s.d $f18,Y
+l.d $f18,Y
+l.d $f16,D
+mul.d $f18,$f18,$f16
+s.d $f18,Z
+L.493:
+l.d $f18,Z
+l.d $f16,Y
+c.le.d $f16,$f18; bc1t L.495
+add.d $f16,$f18,$f18
+c.le.d $f16,$f18; bc1f L.492
+L.495:
+l.d $f18,Radix
+l.d $f16,Two
+c.lt.d $f18,$f16; bc1f L.496
+l.d $f18,Two
+s.d $f18,HInvrse
+b L.497
+L.496:
+l.d $f18,Radix
+s.d $f18,HInvrse
+L.497:
+l.d $f18,One
+l.d $f16,HInvrse
+div.d $f16,$f18,$f16
+s.d $f16,H
+l.d $f16,C
+div.d $f18,$f18,$f16
+s.d $f18,CInvrse
+s.d $f16,E0
+l.d $f18,E0
+l.d $f16,H
+mul.d $f18,$f18,$f16
+s.d $f18,Z
+L.498:
+l.d $f18,E0
+s.d $f18,Y
+l.d $f18,Z
+s.d $f18,E0
+l.d $f18,E0
+l.d $f16,H
+mul.d $f18,$f18,$f16
+s.d $f18,Z
+L.499:
+l.d $f18,Z
+l.d $f16,E0
+c.le.d $f16,$f18; bc1t L.501
+add.d $f16,$f18,$f18
+c.le.d $f16,$f18; bc1f L.498
+L.501:
+l.d $f18,E0
+s.d $f18,UfThold
+l.d $f18,Zero
+s.d $f18,E1
+s.d $f18,Q
+l.d $f18,U2
+s.d $f18,E9
+l.d $f18,One
+l.d $f16,E9
+add.d $f18,$f18,$f16
+s.d $f18,S
+l.d $f18,C
+l.d $f16,S
+mul.d $f16,$f18,$f16
+s.d $f16,D
+l.d $f16,D
+c.le.d $f16,$f18; bc1f L.502
+l.d $f18,Radix
+l.d $f16,U2
+mul.d $f18,$f18,$f16
+s.d $f18,E9
+l.d $f18,One
+l.d $f16,E9
+add.d $f18,$f18,$f16
+s.d $f18,S
+l.d $f18,C
+l.d $f16,S
+mul.d $f16,$f18,$f16
+s.d $f16,D
+l.d $f16,D
+c.le.d $f16,$f18; bc1f L.503
+move $4,$0
+la $5,L.506
+jal BadCond
+l.d $f18,E0
+s.d $f18,Underflow
+l.d $f18,Zero
+s.d $f18,Y1
+l.d $f18,Z
+s.d $f18,PseudoZero
+jal Pause
+b L.503
+L.502:
+l.d $f18,D
+s.d $f18,Underflow
+l.d $f18,Underflow
+l.d $f16,H
+mul.d $f18,$f18,$f16
+s.d $f18,PseudoZero
+l.d $f18,Zero
+s.d $f18,UfThold
+L.507:
+l.d $f18,Underflow
+s.d $f18,Y1
+l.d $f18,PseudoZero
+s.d $f18,Underflow
+l.d $f18,E1
+add.d $f16,$f18,$f18
+c.le.d $f16,$f18; bc1f L.510
+l.d $f18,Underflow
+l.d $f16,HInvrse
+mul.d $f18,$f18,$f16
+s.d $f18,Y2
+l.d $f18,Y1
+l.d $f16,Y2
+sub.d $f12,$f18,$f16
+jal fabs
+s.d $f0,E1
+l.d $f18,Y1
+s.d $f18,Q
+l.d $f18,UfThold
+l.d $f16,Zero
+c.eq.d $f18,$f16; bc1f L.512
+l.d $f18,Y1
+l.d $f16,Y2
+c.eq.d $f18,$f16; bc1t L.512
+l.d $f18,Y1
+s.d $f18,UfThold
+L.512:
+L.510:
+l.d $f18,PseudoZero
+l.d $f16,H
+mul.d $f18,$f18,$f16
+s.d $f18,PseudoZero
+L.508:
+l.d $f18,PseudoZero
+l.d $f16,Underflow
+c.le.d $f16,$f18; bc1t L.514
+add.d $f16,$f18,$f18
+c.le.d $f16,$f18; bc1f L.507
+L.514:
+L.503:
+l.d $f18,PseudoZero
+l.d $f16,Zero
+c.eq.d $f18,$f16; bc1t L.515
+la $4,L.44
+jal printf
+l.d $f18,PseudoZero
+s.d $f18,Z
+l.d $f16,Zero
+c.le.d $f18,$f16; bc1f L.517
+move $4,$0
+la $5,L.519
+jal BadCond
+la $4,L.520
+jal printf
+la $4,L.521
+l.d $f18,PseudoZero
+mfc1.d $6,$f18
+jal printf
+l.d $f18,PseudoZero
+neg.d $f18,$f18
+s.d $f18,X
+l.d $f18,X
+l.d $f16,Zero
+c.le.d $f18,$f16; bc1f L.518
+la $4,L.524
+jal printf
+la $4,L.525
+l.d $f18,X
+mfc1.d $6,$f18
+jal printf
+b L.518
+L.517:
+la $4,3
+la $5,L.526
+jal BadCond
+la $4,L.527
+l.d $f18,PseudoZero
+mfc1.d $6,$f18
+jal printf
+L.518:
+jal TstPtUf
+L.515:
+la $24,120
+sw $24,Milestone
+l.d $f18,CInvrse
+l.d $f16,Y
+mul.d $f16,$f18,$f16
+l.d $f10,Y1
+mul.d $f18,$f18,$f10
+c.le.d $f16,$f18; bc1t L.528
+l.d $f18,H
+l.d $f16,S
+mul.d $f18,$f18,$f16
+s.d $f18,S
+l.d $f18,Underflow
+s.d $f18,E0
+L.528:
+l.d $f18,E1
+l.d $f16,Zero
+c.eq.d $f18,$f16; bc1t L.530
+l.d $f16,E0
+c.eq.d $f18,$f16; bc1t L.530
+la $4,2
+la $5,L.157
+jal BadCond
+l.d $f18,E1
+l.d $f16,E0
+c.lt.d $f18,$f16; bc1f L.532
+la $4,L.534
+jal printf
+la $4,L.535
+jal printf
+l.d $f18,PseudoZero
+l.d $f16,Zero
+c.eq.d $f18,$f16; bc1f L.533
+l.d $f18,E1
+s.d $f18,E0
+b L.533
+L.532:
+la $4,L.538
+jal printf
+la $4,L.539
+jal printf
+L.533:
+L.530:
+la $4,L.540
+l.d $f18,E0
+mfc1.d $6,$f18
+jal printf
+l.d $f18,E0
+s.d $f18,Z
+jal TstPtUf
+l.d $f18,E0
+s.d $f18,Underflow
+lw $24,N
+la $15,1
+bne $24,$15,L.541
+l.d $f18,Y
+s.d $f18,Underflow
+L.541:
+la $24,4
+sw $24,I
+l.d $f18,E1
+l.d $f16,Zero
+c.eq.d $f18,$f16; bc1f L.543
+la $24,3
+sw $24,I
+L.543:
+l.d $f18,UfThold
+l.d $f16,Zero
+c.eq.d $f18,$f16; bc1f L.545
+lw $24,I
+subu $24,$24,2
+sw $24,I
+L.545:
+la $24,1
+sw $24,UfNGrad
+lw $24,I
+la $15,1
+blt $24,$15,L.547
+la $15,4
+bgt $24,$15,L.547
+sll $24,$24,2
+lw $24,L.570-4($24)
+.cpadd $24
+j $24
+.rdata
+.align 2
+L.570:
+.gpword L.549
+.gpword L.556
+.gpword L.561
+.gpword L.562
+.text
+L.549:
+l.d $f18,Underflow
+s.d $f18,UfThold
+l.d $f18,CInvrse
+l.d $f16,Q
+mul.d $f16,$f18,$f16
+l.d $f10,Y
+mul.d $f18,$f18,$f10
+l.d $f10,S
+mul.d $f18,$f18,$f10
+c.eq.d $f16,$f18; bc1t L.550
+l.d $f18,Y
+s.d $f18,UfThold
+move $4,$0
+la $5,L.552
+jal BadCond
+la $4,L.553
+l.d $f18,UfThold
+mfc1.d $6,$f18
+jal printf
+la $4,L.554
+l.d $f18,C
+mfc1.d $6,$f18
+jal printf
+la $4,L.555
+jal printf
+L.550:
+jal Pause
+b L.548
+L.556:
+move $4,$0
+la $5,L.557
+jal BadCond
+la $4,L.558
+jal printf
+la $4,L.559
+l.d $f18,Q
+mfc1.d $6,$f18
+l.d $f18,Y2
+s.d $f18,16($sp)
+jal printf
+l.d $f18,Q
+l.d $f16,Y2
+sub.d $f12,$f18,$f16
+jal fabs
+mov.d $f18,$f0
+la $4,L.560
+mfc1.d $6,$f18
+jal printf
+l.d $f18,Q
+s.d $f18,UfThold
+b L.548
+L.561:
+l.d $f18,X
+s.d $f18,X
+b L.548
+L.562:
+l.d $f18,UfThold
+l.d $f16,Q
+c.eq.d $f16,$f18; bc1f L.563
+l.d $f16,E1
+l.d $f10,E0
+c.eq.d $f16,$f10; bc1f L.563
+l.d $f10,E9
+div.d $f16,$f16,$f10
+sub.d $f12,$f18,$f16
+jal fabs
+l.d $f16,E1
+c.le.d $f0,$f16; bc1f L.563
+sw $0,UfNGrad
+la $4,L.565
+jal printf
+la $4,L.566
+jal printf
+l.d $f18,E0
+l.d $f16,CInvrse
+mul.d $f10,$f18,$f16
+s.d $f10,Y
+l.d $f10,U2
+l.d $f8,Y
+l.d $f6,OneAndHalf
+add.d $f6,$f6,$f10
+mul.d $f8,$f8,$f6
+s.d $f8,Y
+l.d $f8,One
+add.d $f10,$f8,$f10
+mul.d $f16,$f16,$f10
+s.d $f16,X
+l.d $f16,Y
+l.d $f10,X
+div.d $f16,$f16,$f10
+s.d $f16,Y
+l.d $f16,Y
+c.eq.d $f16,$f18; bc1f L.568
+la $24,1
+sw $24,-140+240($sp)
+b L.569
+L.568:
+sw $0,-140+240($sp)
+L.569:
+lw $24,-140+240($sp)
+sw $24,IEEE
+L.563:
+L.547:
+L.548:
+lw $24,UfNGrad
+beq $24,$0,L.572
+la $4,L.44
+jal printf
+la $24,sigfpe
+sw $24,sigsave
+la $4,ovfl_buf
+jal setjmp
+beq $2,$0,L.574
+la $4,L.576
+jal printf
+l.d $f18,H
+add.d $f18,$f18,$f18
+s.d $f18,R
+b L.575
+L.574:
+l.d $f18,Underflow
+l.d $f16,UfThold
+div.d $f12,$f18,$f16
+jal sqrt
+s.d $f0,R
+L.575:
+sw $0,sigsave
+l.d $f18,R
+l.d $f16,H
+c.le.d $f18,$f16; bc1f L.577
+l.d $f18,R
+l.d $f16,UfThold
+mul.d $f16,$f18,$f16
+s.d $f16,Z
+l.d $f16,One
+l.d $f10,H
+l.d $f8,Z
+mul.d $f18,$f18,$f10
+add.d $f10,$f16,$f10
+mul.d $f18,$f18,$f10
+add.d $f18,$f16,$f18
+mul.d $f18,$f8,$f18
+s.d $f18,X
+b L.578
+L.577:
+l.d $f18,UfThold
+s.d $f18,Z
+l.d $f18,One
+l.d $f16,H
+l.d $f10,Z
+mul.d $f8,$f16,$f16
+add.d $f16,$f18,$f16
+mul.d $f16,$f8,$f16
+add.d $f18,$f18,$f16
+mul.d $f18,$f10,$f18
+s.d $f18,X
+L.578:
+l.d $f18,X
+l.d $f16,Z
+c.eq.d $f18,$f16; bc1t L.579
+sub.d $f18,$f18,$f16
+l.d $f16,Zero
+c.eq.d $f18,$f16; bc1f L.579
+la $4,3
+la $5,L.157
+jal BadCond
+la $4,L.581
+l.d $f18,X
+mfc1.d $6,$f18
+l.d $f18,Z
+s.d $f18,16($sp)
+jal printf
+l.d $f18,X
+l.d $f16,Z
+sub.d $f18,$f18,$f16
+s.d $f18,Z9
+la $4,L.582
+l.d $f18,Z9
+mfc1.d $6,$f18
+jal printf
+la $4,L.583
+jal printf
+la $4,L.584
+jal printf
+la $4,L.585
+jal printf
+la $4,L.586
+jal printf
+la $4,L.587
+jal printf
+la $4,L.588
+jal printf
+la $24,sigfpe
+sw $24,sigsave
+la $4,ovfl_buf
+jal setjmp
+beq $2,$0,L.589
+la $4,L.591
+jal printf
+b L.590
+L.589:
+la $4,L.592
+l.d $f18,Half
+l.d $f16,X
+l.d $f10,Z
+div.d $f16,$f16,$f10
+sub.d $f16,$f16,$f18
+sub.d $f18,$f16,$f18
+mfc1.d $6,$f18
+jal printf
+L.590:
+sw $0,sigsave
+L.579:
+L.572:
+la $4,L.593
+l.d $f18,UfThold
+mfc1.d $6,$f18
+la $24,L.594
+sw $24,16($sp)
+jal printf
+la $4,L.595
+jal printf
+la $4,L.596
+jal printf
+l.d $f18,U1
+mul.d $f16,$f18,$f18
+s.d $f16,Y2
+l.d $f16,Y2
+mul.d $f16,$f16,$f16
+s.d $f16,Y
+l.d $f16,Y
+mul.d $f18,$f16,$f18
+s.d $f18,Y2
+l.d $f18,Y2
+l.d $f16,UfThold
+c.le.d $f18,$f16; bc1f L.597
+l.d $f18,Y
+l.d $f16,E0
+c.le.d $f18,$f16; bc1t L.599
+la $4,2
+la $5,L.157
+jal BadCond
+la $24,5
+sw $24,I
+b L.600
+L.599:
+la $4,1
+la $5,L.157
+jal BadCond
+la $24,4
+sw $24,I
+L.600:
+la $4,L.601
+lw $5,I
+jal printf
+L.597:
+la $24,130
+sw $24,Milestone
+l.d $f12,UfThold
+jal log
+mov.d $f18,$f0
+s.d $f18,-144+240($sp)
+l.d $f12,HInvrse
+jal log
+l.d $f16,Half
+l.d $f10,TwoForty
+l.d $f8,-144+240($sp)
+mul.d $f10,$f10,$f8
+div.d $f18,$f10,$f0
+sub.d $f12,$f16,$f18
+jal floor
+neg.d $f18,$f0
+l.d $f16,TwoForty
+div.d $f18,$f18,$f16
+s.d $f18,Y
+l.d $f18,Y
+add.d $f18,$f18,$f18
+s.d $f18,Y2
+la $4,L.602
+jal printf
+la $4,L.603
+l.d $f18,HInvrse
+mfc1.d $6,$f18
+l.d $f18,Y
+s.d $f18,16($sp)
+jal printf
+la $4,L.604
+l.d $f18,HInvrse
+mfc1.d $6,$f18
+l.d $f18,Y
+s.d $f18,16($sp)
+jal printf
+l.d $f12,HInvrse
+l.d $f14,Y2
+jal pow
+s.d $f0,V9
+la $4,L.605
+l.d $f18,V9
+mfc1.d $6,$f18
+jal printf
+l.d $f18,V9
+l.d $f16,Zero
+c.lt.d $f18,$f16; bc1t L.608
+l.d $f16,Radix
+add.d $f16,$f16,$f16
+l.d $f10,E9
+add.d $f16,$f16,$f10
+l.d $f10,UfThold
+mul.d $f16,$f16,$f10
+c.le.d $f18,$f16; bc1t L.606
+L.608:
+la $4,1
+la $5,L.609
+jal BadCond
+la $4,L.610
+l.d $f18,UfThold
+mfc1.d $6,$f18
+jal printf
+b L.607
+L.606:
+l.d $f18,V9
+l.d $f16,UfThold
+l.d $f10,One
+l.d $f8,E9
+add.d $f10,$f10,$f8
+mul.d $f16,$f16,$f10
+c.le.d $f18,$f16; bc1f L.611
+la $4,L.613
+jal printf
+b L.612
+L.611:
+la $4,2
+la $5,L.609
+jal BadCond
+la $4,L.610
+l.d $f18,UfThold
+mfc1.d $6,$f18
+jal printf
+L.612:
+L.607:
+la $24,140
+sw $24,Milestone
+la $4,L.44
+jal printf
+l.d $f18,Zero
+s.d $f18,X
+la $24,2
+sw $24,I
+l.d $f16,Two
+l.d $f10,Three
+mul.d $f16,$f16,$f10
+s.d $f16,Y
+s.d $f18,Q
+sw $0,N
+L.614:
+l.d $f18,X
+s.d $f18,Z
+lw $24,I
+la $24,1($24)
+sw $24,I
+lw $24,I
+l.d $f18,Y
+addu $24,$24,$24
+mtc1 $24,$f16; cvt.d.w $f16,$f16
+div.d $f18,$f18,$f16
+s.d $f18,Y
+l.d $f18,Y
+l.d $f16,Q
+add.d $f18,$f18,$f16
+s.d $f18,R
+l.d $f18,Z
+l.d $f16,R
+add.d $f10,$f18,$f16
+s.d $f10,X
+l.d $f10,X
+sub.d $f18,$f18,$f10
+add.d $f18,$f18,$f16
+s.d $f18,Q
+L.615:
+l.d $f18,X
+l.d $f16,Z
+c.le.d $f18,$f16; bc1f L.614
+l.d $f18,OneAndHalf
+l.d $f16,One
+l.d $f10,Eight
+div.d $f16,$f16,$f10
+add.d $f16,$f18,$f16
+l.d $f10,X
+l.d $f8,ThirtyTwo
+mul.d $f18,$f18,$f8
+div.d $f18,$f10,$f18
+add.d $f18,$f16,$f18
+s.d $f18,Z
+l.d $f18,Z
+mul.d $f18,$f18,$f18
+s.d $f18,X
+l.d $f18,X
+mul.d $f18,$f18,$f18
+s.d $f18,Exp2
+l.d $f18,F9
+s.d $f18,X
+l.d $f18,X
+l.d $f16,U1
+sub.d $f18,$f18,$f16
+s.d $f18,Y
+la $4,L.617
+l.d $f18,Exp2
+mfc1.d $6,$f18
+jal printf
+la $24,1
+sw $24,I
+L.618:
+l.d $f18,X
+l.d $f16,BInvrse
+sub.d $f10,$f18,$f16
+s.d $f10,Z
+l.d $f10,One
+add.d $f8,$f18,$f10
+l.d $f6,Z
+sub.d $f16,$f10,$f16
+sub.d $f16,$f6,$f16
+div.d $f16,$f8,$f16
+s.d $f16,Z
+mov.d $f12,$f18
+l.d $f14,Z
+jal pow
+l.d $f16,Exp2
+sub.d $f18,$f0,$f16
+s.d $f18,Q
+l.d $f12,Q
+jal fabs
+l.d $f16,TwoForty
+l.d $f10,U2
+mul.d $f16,$f16,$f10
+c.le.d $f0,$f16; bc1t L.622
+la $24,1
+sw $24,N
+l.d $f18,BInvrse
+l.d $f16,X
+sub.d $f16,$f16,$f18
+l.d $f10,One
+sub.d $f18,$f10,$f18
+sub.d $f18,$f16,$f18
+s.d $f18,V9
+la $4,2
+la $5,L.624
+jal BadCond
+l.d $f12,X
+l.d $f14,Z
+jal pow
+mov.d $f18,$f0
+la $4,L.625
+mfc1.d $6,$f18
+jal printf
+la $4,L.626
+l.d $f18,V9
+mfc1.d $6,$f18
+l.d $f18,Z
+s.d $f18,16($sp)
+jal printf
+la $4,L.627
+l.d $f18,Q
+mfc1.d $6,$f18
+jal printf
+la $4,L.628
+jal printf
+la $4,L.629
+jal printf
+b L.620
+L.622:
+l.d $f18,Y
+l.d $f16,X
+sub.d $f16,$f18,$f16
+l.d $f10,Two
+mul.d $f16,$f16,$f10
+add.d $f16,$f16,$f18
+s.d $f16,Z
+s.d $f18,X
+l.d $f18,Z
+s.d $f18,Y
+l.d $f18,X
+l.d $f16,F9
+sub.d $f18,$f18,$f16
+l.d $f16,One
+mul.d $f18,$f18,$f18
+add.d $f18,$f16,$f18
+s.d $f18,Z
+l.d $f18,Z
+l.d $f16,One
+c.le.d $f18,$f16; bc1t L.630
+lw $24,I
+lw $15,NoTrials
+bge $24,$15,L.630
+lw $24,I
+la $24,1($24)
+sw $24,I
+b L.618
+L.630:
+l.d $f18,X
+l.d $f16,One
+c.le.d $f18,$f16; bc1t L.632
+lw $24,N
+bne $24,$0,L.620
+la $4,L.636
+jal printf
+b L.620
+L.632:
+l.d $f18,U2
+l.d $f16,One
+add.d $f16,$f16,$f18
+s.d $f16,X
+add.d $f18,$f18,$f18
+s.d $f18,Y
+l.d $f18,Y
+l.d $f16,X
+add.d $f18,$f18,$f16
+s.d $f18,Y
+la $24,1
+sw $24,I
+b L.618
+L.620:
+la $24,150
+sw $24,Milestone
+la $4,L.637
+jal printf
+sw $0,N
+l.d $f18,A1
+s.d $f18,Z
+l.d $f12,C
+jal log
+mov.d $f18,$f0
+s.d $f18,-152+240($sp)
+l.d $f12,A1
+jal log
+l.d $f16,Half
+l.d $f10,-152+240($sp)
+div.d $f18,$f10,$f0
+sub.d $f12,$f16,$f18
+jal floor
+s.d $f0,Q
+sw $0,Break
+L.638:
+l.d $f18,CInvrse
+s.d $f18,X
+l.d $f12,Z
+l.d $f14,Q
+jal pow
+s.d $f0,Y
+jal IsYeqX
+l.d $f18,Q
+neg.d $f18,$f18
+s.d $f18,Q
+l.d $f18,C
+s.d $f18,X
+l.d $f12,Z
+l.d $f14,Q
+jal pow
+s.d $f0,Y
+jal IsYeqX
+l.d $f18,Z
+l.d $f16,One
+c.lt.d $f18,$f16; bc1f L.641
+la $24,1
+sw $24,Break
+b L.642
+L.641:
+l.d $f18,AInvrse
+s.d $f18,Z
+L.642:
+L.639:
+lw $24,Break
+beq $24,$0,L.638
+jal PrintIfNPositive
+lw $24,N
+bne $24,$0,L.643
+la $4,L.645
+jal printf
+L.643:
+la $4,L.44
+jal printf
+la $24,160
+sw $24,Milestone
+jal Pause
+la $4,L.646
+jal printf
+la $4,L.647
+jal printf
+l.d $f18,CInvrse
+neg.d $f18,$f18
+s.d $f18,Y
+l.d $f18,HInvrse
+l.d $f16,Y
+mul.d $f18,$f18,$f16
+s.d $f18,V9
+la $24,sigfpe
+sw $24,sigsave
+la $4,ovfl_buf
+jal setjmp
+beq $2,$0,L.648
+sw $0,I
+l.d $f18,Y
+s.d $f18,V9
+b L.650
+L.648:
+L.651:
+l.d $f18,Y
+s.d $f18,V
+l.d $f18,V9
+s.d $f18,Y
+l.d $f18,HInvrse
+l.d $f16,Y
+mul.d $f18,$f18,$f16
+s.d $f18,V9
+L.652:
+l.d $f18,V9
+l.d $f16,Y
+c.lt.d $f18,$f16; bc1t L.651
+la $24,1
+sw $24,I
+L.650:
+sw $0,sigsave
+l.d $f18,V9
+s.d $f18,Z
+la $4,L.654
+jal printf
+la $4,L.655
+l.d $f18,Y
+mfc1.d $6,$f18
+jal printf
+l.d $f18,Y
+neg.d $f16,$f18
+s.d $f16,V9
+l.d $f16,V9
+s.d $f16,V0
+l.d $f16,V
+sub.d $f18,$f16,$f18
+l.d $f10,V0
+add.d $f16,$f16,$f10
+c.eq.d $f18,$f16; bc1f L.656
+la $4,L.658
+jal printf
+b L.657
+L.656:
+la $4,L.659
+jal printf
+la $4,3
+la $5,L.660
+jal BadCond
+L.657:
+l.d $f18,Z
+l.d $f16,Y
+c.eq.d $f18,$f16; bc1t L.661
+la $4,1
+la $5,L.157
+jal BadCond
+la $4,L.663
+l.d $f18,Y
+mfc1.d $6,$f18
+l.d $f18,Z
+s.d $f18,16($sp)
+jal printf
+L.661:
+lw $24,I
+beq $24,$0,L.664
+l.d $f18,V
+l.d $f16,HInvrse
+l.d $f10,U2
+mul.d $f8,$f16,$f10
+sub.d $f8,$f8,$f16
+mul.d $f8,$f18,$f8
+s.d $f8,Y
+l.d $f8,Y
+l.d $f6,One
+sub.d $f16,$f6,$f16
+mul.d $f16,$f16,$f10
+mul.d $f18,$f16,$f18
+add.d $f18,$f8,$f18
+s.d $f18,Z
+l.d $f18,Z
+l.d $f16,V0
+c.lt.d $f18,$f16; bc1f L.666
+l.d $f18,Z
+s.d $f18,Y
+L.666:
+l.d $f18,Y
+l.d $f16,V0
+c.lt.d $f18,$f16; bc1f L.668
+l.d $f18,Y
+s.d $f18,V
+L.668:
+l.d $f18,V0
+l.d $f16,V
+sub.d $f16,$f18,$f16
+c.lt.d $f16,$f18; bc1f L.665
+l.d $f18,V0
+s.d $f18,V
+b L.665
+L.664:
+l.d $f18,Y
+l.d $f16,HInvrse
+l.d $f10,U2
+mul.d $f8,$f16,$f10
+sub.d $f8,$f8,$f16
+mul.d $f8,$f18,$f8
+s.d $f8,V
+l.d $f8,V
+l.d $f6,One
+sub.d $f16,$f6,$f16
+mul.d $f16,$f16,$f10
+mul.d $f18,$f16,$f18
+add.d $f18,$f8,$f18
+s.d $f18,V
+L.665:
+la $4,L.672
+l.d $f18,V
+mfc1.d $6,$f18
+jal printf
+lw $24,I
+beq $24,$0,L.673
+la $4,L.675
+l.d $f18,V0
+mfc1.d $6,$f18
+jal printf
+b L.674
+L.673:
+la $4,L.676
+jal printf
+L.674:
+l.d $f18,V
+l.d $f16,One
+mul.d $f18,$f18,$f16
+s.d $f18,V9
+la $4,L.677
+l.d $f18,V9
+mfc1.d $6,$f18
+jal printf
+l.d $f18,V
+l.d $f16,One
+div.d $f18,$f18,$f16
+s.d $f18,V9
+la $4,L.678
+l.d $f18,V9
+mfc1.d $6,$f18
+jal printf
+la $4,L.679
+jal printf
+la $4,L.680
+jal printf
+la $24,170
+sw $24,Milestone
+l.d $f18,V
+neg.d $f16,$f18
+c.lt.d $f16,$f18; bc1f L.685
+l.d $f16,V0
+neg.d $f10,$f16
+c.lt.d $f10,$f16; bc1f L.685
+l.d $f16,UfThold
+neg.d $f10,$f16
+c.lt.d $f10,$f18; bc1f L.685
+c.lt.d $f16,$f18; bc1t L.681
+L.685:
+move $4,$0
+la $5,L.686
+jal BadCond
+la $4,L.687
+l.d $f18,V
+mfc1.d $6,$f18
+l.d $f18,V0
+s.d $f18,16($sp)
+l.d $f18,UfThold
+s.d $f18,24($sp)
+jal printf
+L.681:
+la $24,175
+sw $24,Milestone
+la $4,L.44
+jal printf
+la $24,1
+sw $24,Indx
+L.688:
+lw $24,Indx
+la $15,1
+beq $24,$15,L.694
+la $15,2
+beq $24,$15,L.695
+la $15,3
+beq $24,$15,L.696
+b L.692
+L.694:
+l.d $f18,UfThold
+s.d $f18,Z
+b L.693
+L.695:
+l.d $f18,E0
+s.d $f18,Z
+b L.693
+L.696:
+l.d $f18,PseudoZero
+s.d $f18,Z
+L.692:
+L.693:
+l.d $f18,Z
+l.d $f16,Zero
+c.eq.d $f18,$f16; bc1t L.697
+l.d $f12,Z
+jal sqrt
+s.d $f0,V9
+l.d $f18,V9
+mul.d $f18,$f18,$f18
+s.d $f18,Y
+l.d $f18,Y
+l.d $f16,One
+l.d $f10,Radix
+l.d $f8,E9
+mul.d $f10,$f10,$f8
+l.d $f8,Z
+sub.d $f6,$f16,$f10
+div.d $f6,$f18,$f6
+c.lt.d $f6,$f8; bc1t L.701
+add.d $f16,$f16,$f10
+mul.d $f16,$f16,$f8
+c.le.d $f18,$f16; bc1t L.699
+L.701:
+l.d $f18,V9
+l.d $f16,U1
+c.le.d $f18,$f16; bc1t L.702
+la $4,1
+la $5,L.157
+jal BadCond
+b L.703
+L.702:
+la $4,2
+la $5,L.157
+jal BadCond
+L.703:
+la $4,L.704
+l.d $f18,Z
+mfc1.d $6,$f18
+jal printf
+la $4,L.705
+l.d $f18,Y
+mfc1.d $6,$f18
+jal printf
+L.699:
+L.697:
+L.689:
+lw $24,Indx
+la $24,1($24)
+sw $24,Indx
+lw $24,Indx
+la $15,3
+ble $24,$15,L.688
+la $24,180
+sw $24,Milestone
+la $24,1
+sw $24,Indx
+L.706:
+lw $24,Indx
+la $15,1
+bne $24,$15,L.710
+l.d $f18,V
+s.d $f18,Z
+b L.711
+L.710:
+l.d $f18,V0
+s.d $f18,Z
+L.711:
+l.d $f12,Z
+jal sqrt
+s.d $f0,V9
+l.d $f18,V9
+l.d $f16,One
+l.d $f10,Radix
+l.d $f8,E9
+mul.d $f10,$f10,$f8
+sub.d $f16,$f16,$f10
+mul.d $f16,$f16,$f18
+s.d $f16,X
+l.d $f16,X
+mul.d $f18,$f18,$f16
+s.d $f18,V9
+l.d $f18,V9
+l.d $f16,Z
+l.d $f10,One
+l.d $f8,Two
+l.d $f6,Radix
+mul.d $f8,$f8,$f6
+l.d $f6,E9
+mul.d $f8,$f8,$f6
+sub.d $f10,$f10,$f8
+mul.d $f10,$f10,$f16
+c.lt.d $f18,$f10; bc1t L.714
+c.le.d $f18,$f16; bc1t L.712
+L.714:
+l.d $f18,V9
+s.d $f18,Y
+l.d $f18,X
+l.d $f16,W
+c.lt.d $f18,$f16; bc1f L.715
+la $4,1
+la $5,L.157
+jal BadCond
+b L.716
+L.715:
+la $4,2
+la $5,L.157
+jal BadCond
+L.716:
+la $4,L.717
+l.d $f18,Z
+mfc1.d $6,$f18
+jal printf
+la $4,L.718
+l.d $f18,Y
+mfc1.d $6,$f18
+jal printf
+L.712:
+L.707:
+lw $24,Indx
+la $24,1($24)
+sw $24,Indx
+lw $24,Indx
+la $15,2
+ble $24,$15,L.706
+la $24,190
+sw $24,Milestone
+jal Pause
+l.d $f18,UfThold
+l.d $f16,V
+mul.d $f18,$f18,$f16
+s.d $f18,X
+l.d $f18,Radix
+mul.d $f18,$f18,$f18
+s.d $f18,Y
+l.d $f18,X
+l.d $f16,Y
+mul.d $f10,$f18,$f16
+l.d $f8,One
+c.lt.d $f10,$f8; bc1t L.721
+c.le.d $f18,$f16; bc1t L.719
+L.721:
+l.d $f18,X
+l.d $f16,Y
+l.d $f10,U1
+mul.d $f8,$f18,$f16
+c.lt.d $f8,$f10; bc1t L.724
+div.d $f16,$f16,$f10
+c.le.d $f18,$f16; bc1t L.722
+L.724:
+la $4,2
+la $5,L.725
+jal BadCond
+b L.723
+L.722:
+la $4,3
+la $5,L.157
+jal BadCond
+L.723:
+la $4,L.726
+l.d $f18,X
+mfc1.d $6,$f18
+la $24,L.727
+sw $24,16($sp)
+jal printf
+L.719:
+la $24,200
+sw $24,Milestone
+la $24,1
+sw $24,Indx
+L.728:
+l.d $f18,F9
+s.d $f18,X
+lw $24,Indx
+la $15,2
+blt $24,$15,L.732
+la $15,5
+bgt $24,$15,L.732
+sll $24,$24,2
+lw $24,L.738-8($24)
+.cpadd $24
+j $24
+.rdata
+.align 2
+L.738:
+.gpword L.734
+.gpword L.735
+.gpword L.736
+.gpword L.737
+.text
+L.734:
+l.d $f18,One
+l.d $f16,U2
+add.d $f18,$f18,$f16
+s.d $f18,X
+b L.733
+L.735:
+l.d $f18,V
+s.d $f18,X
+b L.733
+L.736:
+l.d $f18,UfThold
+s.d $f18,X
+b L.733
+L.737:
+l.d $f18,Radix
+s.d $f18,X
+L.732:
+L.733:
+l.d $f18,X
+s.d $f18,Y
+la $24,sigfpe
+sw $24,sigsave
+la $4,ovfl_buf
+jal setjmp
+beq $2,$0,L.740
+la $4,L.742
+l.d $f18,X
+mfc1.d $6,$f18
+jal printf
+b L.741
+L.740:
+l.d $f18,Half
+l.d $f16,Y
+l.d $f10,X
+div.d $f16,$f16,$f10
+sub.d $f16,$f16,$f18
+sub.d $f18,$f16,$f18
+s.d $f18,V9
+l.d $f18,V9
+l.d $f16,Zero
+c.eq.d $f18,$f16; bc1f L.743
+b L.729
+L.743:
+l.d $f18,V9
+l.d $f16,U1
+neg.d $f16,$f16
+c.eq.d $f18,$f16; bc1f L.745
+lw $24,Indx
+la $15,5
+bge $24,$15,L.745
+la $4,3
+la $5,L.157
+jal BadCond
+b L.746
+L.745:
+la $4,1
+la $5,L.157
+jal BadCond
+L.746:
+la $4,L.747
+l.d $f18,X
+mfc1.d $6,$f18
+jal printf
+la $4,L.748
+l.d $f18,V9
+mfc1.d $6,$f18
+jal printf
+L.741:
+sw $0,sigsave
+L.729:
+lw $24,Indx
+la $24,1($24)
+sw $24,Indx
+lw $24,Indx
+la $15,5
+ble $24,$15,L.728
+la $24,210
+sw $24,Milestone
+l.d $f18,Zero
+s.d $f18,MyZero
+la $4,L.44
+jal printf
+la $4,L.749
+jal printf
+la $24,sigfpe
+sw $24,sigsave
+la $4,L.750
+jal printf
+la $4,ovfl_buf
+jal setjmp
+bne $2,$0,L.751
+la $4,L.753
+l.d $f18,One
+l.d $f16,MyZero
+div.d $f18,$f18,$f16
+mfc1.d $6,$f18
+jal printf
+L.751:
+sw $0,sigsave
+la $24,sigfpe
+sw $24,sigsave
+la $4,L.754
+jal printf
+la $4,ovfl_buf
+jal setjmp
+bne $2,$0,L.755
+la $4,L.753
+l.d $f18,Zero
+l.d $f16,MyZero
+div.d $f18,$f18,$f16
+mfc1.d $6,$f18
+jal printf
+L.755:
+sw $0,sigsave
+la $24,220
+sw $24,Milestone
+jal Pause
+la $4,L.44
+jal printf
+sw $0,-156+240($sp)
+L.762:
+lw $24,-156+240($sp)
+sll $24,$24,2
+lw $24,ErrCnt($24)
+beq $24,$0,L.766
+la $4,L.768
+lw $24,-156+240($sp)
+sll $24,$24,2
+lw $5,L.757($24)
+lw $6,ErrCnt($24)
+jal printf
+L.766:
+L.763:
+lw $24,-156+240($sp)
+la $24,1($24)
+sw $24,-156+240($sp)
+lw $24,-156+240($sp)
+la $15,4
+blt $24,$15,L.762
+la $4,L.44
+jal printf
+lw $24,ErrCnt
+lw $15,ErrCnt+4
+addu $24,$24,$15
+lw $15,ErrCnt+8
+addu $24,$24,$15
+lw $15,ErrCnt+12
+addu $24,$24,$15
+ble $24,$0,L.769
+lw $15,ErrCnt
+lw $14,ErrCnt+4
+addu $15,$15,$14
+lw $14,ErrCnt+8
+addu $15,$15,$14
+bne $15,$0,L.774
+lw $15,ErrCnt+12
+ble $15,$0,L.774
+la $4,L.779
+jal printf
+la $4,L.780
+jal printf
+L.774:
+lw $15,ErrCnt
+lw $14,ErrCnt+4
+addu $15,$15,$14
+bne $15,$0,L.781
+lw $15,ErrCnt+8
+ble $15,$0,L.781
+la $4,L.785
+jal printf
+la $4,L.786
+jal printf
+L.781:
+lw $24,ErrCnt
+lw $15,ErrCnt+4
+addu $24,$24,$15
+ble $24,$0,L.787
+la $4,L.790
+jal printf
+la $4,L.791
+jal printf
+L.787:
+lw $24,ErrCnt
+ble $24,$0,L.770
+la $4,L.794
+jal printf
+la $4,L.795
+jal printf
+b L.770
+L.769:
+la $4,L.796
+jal printf
+la $24,1
+lw $15,RMult
+bne $15,$24,L.801
+lw $15,RDiv
+bne $15,$24,L.801
+lw $15,RAddSub
+bne $15,$24,L.801
+lw $15,RSqrt
+beq $15,$24,L.797
+L.801:
+la $4,L.802
+jal printf
+b L.798
+L.797:
+l.d $f18,One
+l.d $f16,StickyBit
+c.lt.d $f16,$f18; bc1t L.803
+l.d $f16,Radix
+l.d $f10,Two
+sub.d $f10,$f16,$f10
+l.d $f8,Nine
+sub.d $f16,$f16,$f8
+sub.d $f18,$f16,$f18
+mul.d $f18,$f10,$f18
+l.d $f16,Zero
+c.eq.d $f18,$f16; bc1f L.803
+la $4,L.805
+jal printf
+la $4,L.806
+jal printf
+l.d $f18,Two
+l.d $f16,Radix
+c.eq.d $f16,$f18; bc1f L.807
+l.d $f16,Precision
+l.d $f10,TwentySeven
+l.d $f8,Four
+l.d $f6,Three
+mul.d $f8,$f8,$f6
+mul.d $f18,$f8,$f18
+sub.d $f18,$f16,$f18
+sub.d $f16,$f16,$f10
+sub.d $f16,$f16,$f10
+l.d $f10,One
+add.d $f16,$f16,$f10
+mul.d $f18,$f18,$f16
+l.d $f16,Zero
+c.eq.d $f18,$f16; bc1f L.807
+la $4,L.809
+jal printf
+b L.808
+L.807:
+la $4,L.810
+jal printf
+L.808:
+lw $24,IEEE
+beq $24,$0,L.811
+la $4,L.813
+jal printf
+b L.812
+L.811:
+la $4,L.814
+jal printf
+la $4,L.815
+jal printf
+L.812:
+L.803:
+la $4,L.816
+jal printf
+L.798:
+L.770:
+lw $24,fpecount
+beq $24,$0,L.817
+la $4,L.819
+lw $5,fpecount
+jal printf
+L.817:
+la $4,L.820
+jal printf
+move $2,$0
+L.6:
+lw $16,32($sp)
+lw $17,36($sp)
+lw $18,40($sp)
+lw $19,44($sp)
+lw $20,48($sp)
+lw $21,52($sp)
+lw $22,56($sp)
+lw $23,60($sp)
+lw $25,64($sp)
+lw $30,68($sp)
+lw $31,72($sp)
+addu $sp,$sp,240
+j $31
+.end main
+.globl Sign
+.text
+.align 2
+.ent Sign
+Sign:
+.frame $sp,8,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-8
+.fmask 0xc0000000,-8
+s.d $f30,0($sp)
+l.d $f18,L.7
+c.lt.d $f12,$f18; bc1t L.823
+l.d $f30,L.8
+b L.824
+L.823:
+l.d $f30,L.825
+L.824:
+mov.d $f0,$f30
+L.821:
+l.d $f30,0($sp)
+addu $sp,$sp,8
+j $31
+.end Sign
+.globl Pause
+.text
+.align 2
+.ent Pause
+Pause:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+la $4,L.827
+lw $5,Milestone
+jal printf
+la $4,L.828
+lw $5,PageNo
+jal printf
+lw $24,Milestone
+la $24,1($24)
+sw $24,Milestone
+lw $24,PageNo
+la $24,1($24)
+sw $24,PageNo
+move $2,$0
+L.826:
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end Pause
+.globl TstCond
+.text
+.align 2
+.ent TstCond
+TstCond:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+sw $4,24($sp)
+sw $5,28($sp)
+sw $6,32($sp)
+lw $24,4+24($sp)
+bne $24,$0,L.830
+lw $4,0+24($sp)
+lw $5,8+24($sp)
+jal BadCond
+la $4,L.813
+jal printf
+L.830:
+move $2,$0
+L.829:
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end TstCond
+.data
+.align 2
+L.833:
+.word L.834
+.word L.835
+.word L.836
+.word L.837
+.globl BadCond
+.text
+.text
+.align 2
+.ent BadCond
+BadCond:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2000000,-8
+.cprestore 16
+sw $30,20($sp)
+sw $31,24($sp)
+move $30,$4
+sw $5,36($sp)
+sll $24,$30,2
+la $24,ErrCnt($24)
+lw $15,($24)
+la $15,1($15)
+sw $15,($24)
+la $4,L.838
+sll $24,$30,2
+lw $5,L.833($24)
+lw $6,4+32($sp)
+jal printf
+move $2,$0
+L.832:
+lw $25,16($sp)
+lw $30,20($sp)
+lw $31,24($sp)
+addu $sp,$sp,32
+j $31
+.end BadCond
+.globl Random
+.text
+.align 2
+.ent Random
+Random:
+.frame $sp,40,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-40
+.fmask 0xf0000000,-16
+.mask 0x82000000,-4
+s.d $f28,16($sp)
+s.d $f30,24($sp)
+.cprestore 32
+sw $31,36($sp)
+l.d $f18,Random1
+l.d $f16,Random9
+add.d $f30,$f18,$f16
+mul.d $f28,$f30,$f30
+mul.d $f28,$f28,$f28
+mul.d $f30,$f30,$f28
+mov.d $f12,$f30
+jal floor
+sub.d $f28,$f30,$f0
+l.d $f18,L.840
+mul.d $f18,$f18,$f30
+add.d $f18,$f28,$f18
+s.d $f18,Random1
+l.d $f0,Random1
+L.839:
+l.d $f28,16($sp)
+l.d $f30,24($sp)
+lw $25,32($sp)
+lw $31,36($sp)
+addu $sp,$sp,40
+j $31
+.end Random
+.globl SqXMinX
+.text
+.align 2
+.ent SqXMinX
+SqXMinX:
+.frame $sp,56,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-56
+.fmask 0xc0000000,-24
+.mask 0x82000000,-12
+s.d $f30,32($sp)
+.cprestore 40
+sw $31,44($sp)
+sw $4,56($sp)
+l.d $f18,X
+l.d $f16,BInvrse
+mul.d $f30,$f18,$f16
+sub.d $f16,$f18,$f30
+s.d $f16,-8+56($sp)
+mul.d $f12,$f18,$f18
+jal sqrt
+sub.d $f18,$f0,$f30
+l.d $f16,-8+56($sp)
+sub.d $f18,$f18,$f16
+l.d $f16,OneUlp
+div.d $f18,$f18,$f16
+s.d $f18,SqEr
+l.d $f18,SqEr
+l.d $f16,Zero
+c.eq.d $f18,$f16; bc1t L.842
+l.d $f18,SqEr
+l.d $f16,MinSqEr
+c.lt.d $f18,$f16; bc1f L.844
+l.d $f18,SqEr
+s.d $f18,MinSqEr
+L.844:
+l.d $f18,SqEr
+l.d $f16,MaxSqEr
+c.le.d $f18,$f16; bc1t L.846
+l.d $f18,SqEr
+s.d $f18,MaxSqEr
+L.846:
+l.d $f18,J
+l.d $f16,L.8
+add.d $f18,$f18,$f16
+s.d $f18,J
+lw $4,0+56($sp)
+la $5,L.44
+jal BadCond
+la $4,L.848
+l.d $f18,X
+mul.d $f16,$f18,$f18
+mfc1.d $6,$f16
+s.d $f18,16($sp)
+l.d $f18,OneUlp
+l.d $f16,SqEr
+mul.d $f18,$f18,$f16
+s.d $f18,24($sp)
+jal printf
+la $4,L.849
+jal printf
+L.842:
+move $2,$0
+L.841:
+l.d $f30,32($sp)
+lw $25,40($sp)
+lw $31,44($sp)
+addu $sp,$sp,56
+j $31
+.end SqXMinX
+.globl NewD
+.text
+.align 2
+.ent NewD
+NewD:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+l.d $f18,Z1
+l.d $f16,Q
+mul.d $f18,$f18,$f16
+s.d $f18,X
+l.d $f18,Half
+l.d $f16,X
+l.d $f10,Radix
+div.d $f16,$f16,$f10
+sub.d $f12,$f18,$f16
+jal floor
+l.d $f16,Radix
+mul.d $f18,$f0,$f16
+l.d $f10,X
+add.d $f18,$f18,$f10
+s.d $f18,X
+l.d $f18,X
+l.d $f10,Z
+l.d $f8,D
+l.d $f6,Q
+mul.d $f4,$f18,$f10
+sub.d $f6,$f6,$f4
+div.d $f6,$f6,$f16
+mul.d $f4,$f18,$f18
+div.d $f16,$f8,$f16
+mul.d $f16,$f4,$f16
+add.d $f16,$f6,$f16
+s.d $f16,Q
+l.d $f16,Two
+mul.d $f18,$f16,$f18
+mul.d $f18,$f18,$f8
+sub.d $f18,$f10,$f18
+s.d $f18,Z
+l.d $f18,Z
+l.d $f16,Zero
+c.le.d $f18,$f16; bc1f L.851
+l.d $f18,Z
+neg.d $f18,$f18
+s.d $f18,Z
+l.d $f18,Z1
+neg.d $f18,$f18
+s.d $f18,Z1
+L.851:
+l.d $f18,Radix
+l.d $f16,D
+mul.d $f18,$f18,$f16
+s.d $f18,D
+move $2,$0
+L.850:
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end NewD
+.globl SR3750
+.text
+.align 2
+.ent SR3750
+SR3750:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+l.d $f18,X
+l.d $f16,Radix
+l.d $f10,Z2
+sub.d $f8,$f18,$f16
+sub.d $f16,$f10,$f16
+c.lt.d $f8,$f16; bc1t L.854
+sub.d $f18,$f18,$f10
+l.d $f16,W
+sub.d $f16,$f16,$f10
+c.le.d $f18,$f16; bc1f L.854
+lw $24,I
+la $24,1($24)
+sw $24,I
+l.d $f18,X
+l.d $f16,D
+mul.d $f12,$f18,$f16
+jal sqrt
+s.d $f0,X2
+l.d $f18,Z2
+l.d $f16,Y
+l.d $f10,X2
+sub.d $f10,$f10,$f18
+sub.d $f18,$f16,$f18
+sub.d $f18,$f10,$f18
+s.d $f18,Y2
+l.d $f18,Half
+l.d $f10,X8
+sub.d $f16,$f16,$f18
+div.d $f16,$f10,$f16
+s.d $f16,X2
+l.d $f16,X2
+mul.d $f10,$f18,$f16
+mul.d $f10,$f10,$f16
+sub.d $f16,$f16,$f10
+s.d $f16,X2
+l.d $f16,Y2
+add.d $f16,$f16,$f18
+l.d $f10,X2
+sub.d $f18,$f18,$f10
+add.d $f18,$f16,$f18
+s.d $f18,SqEr
+l.d $f18,SqEr
+l.d $f16,MinSqEr
+c.lt.d $f18,$f16; bc1f L.856
+l.d $f18,SqEr
+s.d $f18,MinSqEr
+L.856:
+l.d $f18,Y2
+l.d $f16,X2
+sub.d $f18,$f18,$f16
+s.d $f18,SqEr
+l.d $f18,SqEr
+l.d $f16,MaxSqEr
+c.le.d $f18,$f16; bc1t L.858
+l.d $f18,SqEr
+s.d $f18,MaxSqEr
+L.858:
+L.854:
+move $2,$0
+L.853:
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end SR3750
+.globl IsYeqX
+.text
+.align 2
+.ent IsYeqX
+IsYeqX:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0x82000000,-4
+.cprestore 24
+sw $31,28($sp)
+l.d $f18,Y
+l.d $f16,X
+c.eq.d $f18,$f16; bc1t L.861
+lw $24,N
+bgt $24,$0,L.863
+l.d $f18,Zero
+l.d $f16,Z
+c.eq.d $f16,$f18; bc1f L.865
+l.d $f16,Q
+c.le.d $f16,$f18; bc1f L.865
+la $4,L.867
+jal printf
+b L.866
+L.865:
+la $4,2
+la $5,L.868
+jal BadCond
+L.866:
+la $4,L.869
+l.d $f18,Z
+mfc1.d $6,$f18
+l.d $f18,Q
+s.d $f18,16($sp)
+jal printf
+la $4,L.870
+l.d $f18,Y
+mfc1.d $6,$f18
+jal printf
+la $4,L.871
+l.d $f18,X
+mfc1.d $6,$f18
+jal printf
+la $4,L.872
+l.d $f18,Y
+l.d $f16,X
+sub.d $f18,$f18,$f16
+mfc1.d $6,$f18
+jal printf
+L.863:
+lw $24,N
+la $24,1($24)
+sw $24,N
+L.861:
+move $2,$0
+L.860:
+lw $25,24($sp)
+lw $31,28($sp)
+addu $sp,$sp,32
+j $31
+.end IsYeqX
+.globl SR3980
+.text
+.align 2
+.ent SR3980
+SR3980:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+L.874:
+lw $24,I
+mtc1 $24,$f18; cvt.d.w $f18,$f18
+s.d $f18,Q
+l.d $f12,Z
+l.d $f14,Q
+jal pow
+s.d $f0,Y
+jal IsYeqX
+lw $24,I
+la $24,1($24)
+sw $24,I
+lw $15,M
+ble $24,$15,L.877
+b L.876
+L.877:
+l.d $f18,Z
+l.d $f16,X
+mul.d $f18,$f18,$f16
+s.d $f18,X
+L.875:
+l.d $f18,X
+l.d $f16,W
+c.lt.d $f18,$f16; bc1t L.874
+L.876:
+move $2,$0
+L.873:
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end SR3980
+.globl PrintIfNPositive
+.text
+.align 2
+.ent PrintIfNPositive
+PrintIfNPositive:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+lw $24,N
+ble $24,$0,L.880
+la $4,L.882
+lw $5,N
+jal printf
+L.880:
+move $2,$0
+L.879:
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end PrintIfNPositive
+.globl TstPtUf
+.text
+.align 2
+.ent TstPtUf
+TstPtUf:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+sw $0,N
+l.d $f18,Z
+l.d $f16,Zero
+c.eq.d $f18,$f16; bc1t L.884
+la $4,L.886
+jal printf
+la $4,L.887
+jal printf
+la $24,sigfpe
+sw $24,sigsave
+la $4,ovfl_buf
+jal setjmp
+beq $2,$0,L.888
+b L.890
+L.888:
+l.d $f18,Z
+add.d $f16,$f18,$f18
+div.d $f18,$f16,$f18
+s.d $f18,Q9
+la $4,L.891
+l.d $f18,Q9
+mfc1.d $6,$f18
+jal printf
+l.d $f18,Q9
+l.d $f16,Two
+sub.d $f12,$f18,$f16
+jal fabs
+l.d $f16,Radix
+l.d $f10,U2
+mul.d $f16,$f16,$f10
+c.lt.d $f0,$f16; bc1f L.892
+la $4,L.894
+jal printf
+la $4,L.895
+jal printf
+b L.893
+L.892:
+l.d $f18,Q9
+l.d $f16,One
+c.lt.d $f18,$f16; bc1t L.898
+l.d $f16,Two
+c.le.d $f18,$f16; bc1t L.896
+L.898:
+L.890:
+la $24,1
+sw $24,N
+lw $24,ErrCnt+4
+la $24,1($24)
+sw $24,ErrCnt+4
+la $4,L.901
+jal printf
+b L.897
+L.896:
+la $24,1
+sw $24,N
+lw $24,ErrCnt+8
+la $24,1($24)
+sw $24,ErrCnt+8
+la $4,L.904
+jal printf
+L.897:
+L.893:
+sw $0,sigsave
+l.d $f18,Z
+l.d $f16,One
+mul.d $f10,$f18,$f16
+s.d $f10,V9
+l.d $f10,V9
+s.d $f10,Random1
+mul.d $f10,$f16,$f18
+s.d $f10,V9
+l.d $f10,V9
+s.d $f10,Random2
+div.d $f18,$f18,$f16
+s.d $f18,V9
+l.d $f18,Z
+l.d $f16,Random1
+c.eq.d $f18,$f16; bc1f L.905
+l.d $f16,Random2
+c.eq.d $f18,$f16; bc1f L.905
+l.d $f16,V9
+c.eq.d $f18,$f16; bc1f L.905
+lw $24,N
+ble $24,$0,L.906
+jal Pause
+b L.906
+L.905:
+la $24,1
+sw $24,N
+la $4,2
+la $5,L.909
+jal BadCond
+la $4,L.910
+l.d $f18,Z
+mfc1.d $6,$f18
+jal printf
+l.d $f18,Z
+l.d $f16,Random1
+c.eq.d $f18,$f16; bc1t L.911
+la $4,L.913
+l.d $f18,Random1
+mfc1.d $6,$f18
+jal printf
+L.911:
+l.d $f18,Random2
+l.d $f16,Z
+c.eq.d $f16,$f18; bc1t L.914
+l.d $f16,Random1
+c.eq.d $f18,$f16; bc1t L.914
+la $4,L.916
+l.d $f18,Random2
+mfc1.d $6,$f18
+jal printf
+L.914:
+l.d $f18,Z
+l.d $f16,V9
+c.eq.d $f18,$f16; bc1t L.917
+la $4,L.919
+l.d $f18,V9
+mfc1.d $6,$f18
+jal printf
+L.917:
+l.d $f18,Random2
+l.d $f16,Random1
+c.eq.d $f18,$f16; bc1t L.920
+lw $24,ErrCnt+8
+la $24,1($24)
+sw $24,ErrCnt+8
+la $4,2
+la $5,L.924
+jal BadCond
+la $4,L.925
+l.d $f18,Random2
+mfc1.d $6,$f18
+jal printf
+la $4,L.926
+l.d $f18,Random1
+mfc1.d $6,$f18
+jal printf
+L.920:
+jal Pause
+L.906:
+L.884:
+move $2,$0
+L.883:
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end TstPtUf
+.globl notify
+.text
+.align 2
+.ent notify
+notify:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+sw $4,24($sp)
+la $4,L.928
+lw $5,0+24($sp)
+jal printf
+la $4,L.929
+jal printf
+move $2,$0
+L.927:
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end notify
+.globl msglist
+.text
+.align 2
+.ent msglist
+msglist:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2000000,-8
+.cprestore 16
+sw $30,20($sp)
+sw $31,24($sp)
+move $30,$4
+b L.932
+L.931:
+la $4,L.934
+move $24,$30
+la $30,4($24)
+lw $5,($24)
+jal printf
+L.932:
+lw $24,($30)
+bne $24,$0,L.931
+move $2,$0
+L.930:
+lw $25,16($sp)
+lw $30,20($sp)
+lw $31,24($sp)
+addu $sp,$sp,32
+j $31
+.end msglist
+.data
+.align 2
+L.936:
+.word L.937
+.word L.938
+.word L.939
+.word L.940
+.word L.941
+.word L.942
+.word L.943
+.word L.944
+.word L.945
+.word 0x0
+.globl Instructions
+.text
+.text
+.align 2
+.ent Instructions
+Instructions:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+la $4,L.936
+jal msglist
+move $2,$0
+L.935:
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end Instructions
+.data
+.align 2
+L.947:
+.word L.948
+.word L.949
+.word L.950
+.word L.951
+.word L.952
+.word L.953
+.word L.954
+.word L.955
+.word L.956
+.word L.957
+.word L.958
+.word L.959
+.word L.960
+.word L.961
+.word 0x0
+.globl Heading
+.text
+.text
+.align 2
+.ent Heading
+Heading:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+la $4,L.947
+jal msglist
+move $2,$0
+L.946:
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end Heading
+.data
+.align 2
+L.963:
+.word L.964
+.word L.965
+.word L.966
+.word L.967
+.word L.968
+.word L.969
+.word L.970
+.word L.971
+.word L.972
+.word L.973
+.word L.974
+.word L.975
+.word L.976
+.word L.977
+.word L.978
+.word L.979
+.word L.980
+.word L.981
+.word L.982
+.word 0x0
+.globl Characteristics
+.text
+.text
+.align 2
+.ent Characteristics
+Characteristics:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+la $4,L.963
+jal msglist
+move $2,$0
+L.962:
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end Characteristics
+.data
+.align 2
+L.984:
+.word L.985
+.word L.986
+.word L.987
+.word L.988
+.word L.989
+.word L.990
+.word L.991
+.word L.992
+.word L.993
+.word L.994
+.word L.995
+.word L.996
+.word L.997
+.word L.998
+.word L.999
+.word L.1000
+.word L.1001
+.word 0x0
+.globl History
+.text
+.text
+.align 2
+.ent History
+History:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+la $4,L.984
+jal msglist
+move $2,$0
+L.983:
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end History
+.globl pow
+.text
+.align 2
+.ent pow
+pow:
+.frame $sp,72,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-72
+.fmask 0xfc000000,-40
+.mask 0xc2800000,-20
+s.d $f26,16($sp)
+s.d $f28,24($sp)
+s.d $f30,32($sp)
+sw $23,40($sp)
+.cprestore 44
+sw $30,48($sp)
+sw $31,52($sp)
+mov.d $f30,$f12
+mov.d $f28,$f14
+move $23,$0
+sw $0,-8+72($sp)
+l.d $f18,L.7
+c.eq.d $f28,$f18; bc1f L.1003
+l.d $f0,L.8
+b L.1002
+L.1003:
+l.d $f18,L.1008
+c.lt.d $f28,$f18; bc1t L.1007
+l.d $f18,L.1009
+c.le.d $f28,$f18; bc1t L.1005
+L.1007:
+l.d $f18,L.825
+c.eq.d $f30,$f18; bc1t L.1005
+mov.d $f12,$f30
+jal log
+mov.d $f18,$f0
+mul.d $f12,$f28,$f18
+jal exp
+mov.d $f18,$f0
+b L.1002
+L.1005:
+l.d $f18,L.7
+c.lt.d $f28,$f18; bc1f L.1010
+neg.d $f28,$f28
+la $24,1
+sw $24,-8+72($sp)
+L.1010:
+mov.d $f12,$f28
+la $6,-16+72($sp)
+jal modf
+mov.d $f28,$f0
+l.d $f18,L.7
+c.eq.d $f28,$f18; bc1t L.1012
+mov.d $f12,$f30
+jal log
+mov.d $f18,$f0
+mul.d $f12,$f28,$f18
+jal exp
+mov.d $f26,$f0
+b L.1013
+L.1012:
+l.d $f26,L.8
+L.1013:
+mov.d $f12,$f30
+la $6,-4+72($sp)
+jal frexp
+mov.d $f30,$f0
+l.d $f18,-16+72($sp)
+trunc.w.d $f2,$f18,$24; mfc1 $24,$f2
+move $30,$24
+beq $24,$0,L.1014
+L.1016:
+and $24,$30,1
+beq $24,$0,L.1020
+mul.d $f26,$f26,$f30
+lw $24,-4+72($sp)
+addu $23,$23,$24
+L.1020:
+sra $24,$30,1
+move $30,$24
+bne $24,$0,L.1022
+b L.1018
+L.1022:
+mul.d $f30,$f30,$f30
+lw $24,-4+72($sp)
+sll $24,$24,1
+sw $24,-4+72($sp)
+l.d $f18,L.1026
+c.lt.d $f30,$f18; bc1f L.1016
+l.d $f18,L.1027
+mul.d $f30,$f18,$f30
+lw $24,-4+72($sp)
+subu $24,$24,1
+sw $24,-4+72($sp)
+b L.1016
+L.1018:
+L.1014:
+lw $24,-8+72($sp)
+beq $24,$0,L.1028
+l.d $f18,L.8
+div.d $f26,$f18,$f26
+negu $23,$23
+L.1028:
+mov.d $f12,$f26
+move $6,$23
+jal ldexp
+mov.d $f18,$f0
+L.1002:
+l.d $f26,16($sp)
+l.d $f28,24($sp)
+l.d $f30,32($sp)
+lw $23,40($sp)
+lw $25,44($sp)
+lw $30,48($sp)
+lw $31,52($sp)
+addu $sp,$sp,72
+j $31
+.end pow
+.globl UfNGrad
+.comm UfNGrad,4
+.globl SqRWrng
+.comm SqRWrng,4
+.globl IEEE
+.comm IEEE,4
+.globl Anomaly
+.comm Anomaly,4
+.globl Monot
+.comm Monot,4
+.globl NotMonot
+.comm NotMonot,4
+.globl Done
+.comm Done,4
+.globl Break
+.comm Break,4
+.globl RSqrt
+.comm RSqrt,4
+.globl RAddSub
+.comm RAddSub,4
+.globl RDiv
+.comm RDiv,4
+.globl RMult
+.comm RMult,4
+.globl GAddSub
+.comm GAddSub,4
+.globl GDiv
+.comm GDiv,4
+.globl GMult
+.comm GMult,4
+.globl N1
+.comm N1,4
+.globl N
+.comm N,4
+.globl M
+.comm M,4
+.globl PageNo
+.comm PageNo,4
+.globl Milestone
+.comm Milestone,4
+.globl fpecount
+.comm fpecount,4
+.globl ErrCnt
+.comm ErrCnt,16
+.globl Z9
+.comm Z9,8
+.globl Z2
+.comm Z2,8
+.globl Z1
+.comm Z1,8
+.globl PseudoZero
+.comm PseudoZero,8
+.globl Z
+.comm Z,8
+.globl Random2
+.comm Random2,8
+.globl Y2
+.comm Y2,8
+.globl Y1
+.comm Y1,8
+.globl Y
+.comm Y,8
+.globl Random1
+.comm Random1,8
+.globl X8
+.comm X8,8
+.globl X2
+.comm X2,8
+.globl X1
+.comm X1,8
+.globl X
+.comm X,8
+.globl W
+.comm W,8
+.globl V9
+.comm V9,8
+.globl V0
+.comm V0,8
+.globl V
+.comm V,8
+.globl U2
+.comm U2,8
+.globl U1
+.comm U1,8
+.globl UfThold
+.comm UfThold,8
+.globl OneUlp
+.comm OneUlp,8
+.globl S
+.comm S,8
+.globl Underflow
+.comm Underflow,8
+.globl T
+.comm T,8
+.globl Random9
+.comm Random9,8
+.globl R
+.comm R,8
+.globl Q9
+.comm Q9,8
+.globl Q
+.comm Q,8
+.globl Precision
+.comm Precision,8
+.globl MyZero
+.comm MyZero,8
+.globl J
+.comm J,8
+.globl StickyBit
+.comm StickyBit,8
+.globl I
+.comm I,4
+.globl HInvrse
+.comm HInvrse,8
+.globl H
+.comm H,8
+.globl F9
+.comm F9,8
+.globl F6
+.comm F6,8
+.globl Third
+.comm Third,8
+.globl E9
+.comm E9,8
+.globl MaxSqEr
+.comm MaxSqEr,8
+.globl SqEr
+.comm SqEr,8
+.globl MinSqEr
+.comm MinSqEr,8
+.globl E3
+.comm E3,8
+.globl Exp2
+.comm Exp2,8
+.globl E1
+.comm E1,8
+.globl E0
+.comm E0,8
+.globl FourD
+.comm FourD,8
+.globl D
+.comm D,8
+.globl CInvrse
+.comm CInvrse,8
+.globl C
+.comm C,8
+.globl A1
+.comm A1,8
+.globl AInvrse
+.comm AInvrse,8
+.globl ch
+.comm ch,8
+.globl Indx
+.comm Indx,4
+.globl BMinusU2
+.comm BMinusU2,8
+.globl RadixD2
+.comm RadixD2,8
+.globl BInvrse
+.comm BInvrse,8
+.globl Radix
+.comm Radix,8
+.globl sigsave
+.comm sigsave,4
+.globl ovfl_buf
+.comm ovfl_buf,112
+.extern _iob 0
+.rdata
+.align 3
+L.1027:
+.word 0x40000000
+.word 0x0
+.align 3
+L.1026:
+.word 0x3fe00000
+.word 0x0
+.align 3
+L.1009:
+.word 0x40913000
+.word 0x0
+.align 3
+L.1008:
+.word 0xc0913000
+.word 0x0
+.align 0
+L.1001:
+.byte 115
+.byte 101
+.byte 101
+.byte 32
+.byte 115
+.byte 111
+.byte 117
+.byte 114
+.byte 99
+.byte 101
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 109
+.byte 111
+.byte 114
+.byte 101
+.byte 32
+.byte 104
+.byte 105
+.byte 115
+.byte 116
+.byte 111
+.byte 114
+.byte 121
+.byte 46
+.byte 0
+.align 0
+L.1000:
+.byte 66
+.byte 65
+.byte 83
+.byte 73
+.byte 67
+.byte 32
+.byte 118
+.byte 101
+.byte 114
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 40
+.byte 67
+.byte 41
+.byte 32
+.byte 49
+.byte 57
+.byte 56
+.byte 51
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 80
+.byte 114
+.byte 111
+.byte 102
+.byte 46
+.byte 32
+.byte 87
+.byte 46
+.byte 32
+.byte 77
+.byte 46
+.byte 32
+.byte 75
+.byte 97
+.byte 104
+.byte 97
+.byte 110
+.byte 59
+.byte 0
+.align 0
+L.999:
+.byte 97
+.byte 115
+.byte 32
+.byte 117
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 99
+.byte 101
+.byte 114
+.byte 116
+.byte 97
+.byte 105
+.byte 110
+.byte 32
+.byte 101
+.byte 97
+.byte 114
+.byte 108
+.byte 121
+.byte 32
+.byte 87
+.byte 65
+.byte 78
+.byte 71
+.byte 32
+.byte 109
+.byte 97
+.byte 99
+.byte 104
+.byte 105
+.byte 110
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.998:
+.byte 102
+.byte 108
+.byte 111
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 45
+.byte 112
+.byte 111
+.byte 105
+.byte 110
+.byte 116
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 115
+.byte 44
+.byte 32
+.byte 98
+.byte 117
+.byte 116
+.byte 32
+.byte 97
+.byte 108
+.byte 115
+.byte 111
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 111
+.byte 119
+.byte 115
+.byte 32
+.byte 108
+.byte 111
+.byte 103
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 105
+.byte 99
+.byte 32
+.byte 101
+.byte 110
+.byte 99
+.byte 111
+.byte 100
+.byte 105
+.byte 110
+.byte 103
+.byte 0
+.align 0
+L.997:
+.byte 10
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 98
+.byte 97
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 117
+.byte 112
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 118
+.byte 101
+.byte 110
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 97
+.byte 108
+.byte 32
+.byte 114
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 114
+.byte 101
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 101
+.byte 110
+.byte 116
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 0
+.align 0
+L.996:
+.byte 111
+.byte 102
+.byte 32
+.byte 112
+.byte 97
+.byte 116
+.byte 104
+.byte 111
+.byte 108
+.byte 111
+.byte 103
+.byte 105
+.byte 101
+.byte 115
+.byte 44
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 115
+.byte 97
+.byte 121
+.byte 32
+.byte 104
+.byte 111
+.byte 119
+.byte 32
+.byte 119
+.byte 101
+.byte 108
+.byte 108
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 109
+.byte 112
+.byte 108
+.byte 101
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 101
+.byte 100
+.byte 46
+.byte 0
+.align 0
+L.995:
+.byte 111
+.byte 102
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 44
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 116
+.byte 114
+.byte 105
+.byte 101
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 111
+.byte 112
+.byte 101
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 97
+.byte 32
+.byte 119
+.byte 105
+.byte 100
+.byte 101
+.byte 114
+.byte 32
+.byte 118
+.byte 97
+.byte 114
+.byte 105
+.byte 101
+.byte 116
+.byte 121
+.byte 0
+.align 0
+L.994:
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 44
+.byte 32
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 114
+.byte 97
+.byte 110
+.byte 103
+.byte 101
+.byte 32
+.byte 40
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 47
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 115
+.byte 41
+.byte 0
+.align 0
+L.993:
+.byte 87
+.byte 46
+.byte 32
+.byte 74
+.byte 46
+.byte 32
+.byte 67
+.byte 111
+.byte 100
+.byte 121
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 87
+.byte 46
+.byte 32
+.byte 87
+.byte 97
+.byte 105
+.byte 116
+.byte 101
+.byte 46
+.byte 32
+.byte 65
+.byte 108
+.byte 116
+.byte 104
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 32
+.byte 98
+.byte 111
+.byte 116
+.byte 104
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 115
+.byte 32
+.byte 116
+.byte 114
+.byte 121
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 0
+.align 0
+L.992:
+.byte 98
+.byte 111
+.byte 111
+.byte 107
+.byte 32
+.byte 32
+.byte 96
+.byte 83
+.byte 111
+.byte 102
+.byte 116
+.byte 119
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 77
+.byte 97
+.byte 110
+.byte 117
+.byte 97
+.byte 108
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 69
+.byte 108
+.byte 101
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 97
+.byte 114
+.byte 121
+.byte 32
+.byte 70
+.byte 117
+.byte 110
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 39
+.byte 32
+.byte 40
+.byte 49
+.byte 57
+.byte 56
+.byte 48
+.byte 41
+.byte 32
+.byte 98
+.byte 121
+.byte 0
+.align 0
+L.991:
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 99
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 100
+.byte 32
+.byte 96
+.byte 77
+.byte 65
+.byte 67
+.byte 72
+.byte 65
+.byte 82
+.byte 39
+.byte 44
+.byte 32
+.byte 119
+.byte 104
+.byte 105
+.byte 99
+.byte 104
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 101
+.byte 110
+.byte 100
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 0
+.align 0
+L.990:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 99
+.byte 97
+.byte 112
+.byte 97
+.byte 98
+.byte 105
+.byte 108
+.byte 105
+.byte 116
+.byte 105
+.byte 101
+.byte 115
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 103
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 121
+.byte 111
+.byte 110
+.byte 100
+.byte 32
+.byte 97
+.byte 110
+.byte 32
+.byte 101
+.byte 97
+.byte 114
+.byte 108
+.byte 105
+.byte 101
+.byte 114
+.byte 0
+.align 0
+L.989:
+.byte 70
+.byte 97
+.byte 105
+.byte 108
+.byte 117
+.byte 114
+.byte 101
+.byte 115
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 115
+.byte 101
+.byte 113
+.byte 117
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.988:
+.byte 32
+.byte 32
+.byte 32
+.byte 70
+.byte 65
+.byte 73
+.byte 76
+.byte 85
+.byte 82
+.byte 69
+.byte 115
+.byte 44
+.byte 32
+.byte 108
+.byte 105
+.byte 107
+.byte 101
+.byte 32
+.byte 50
+.byte 43
+.byte 50
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 53
+.byte 32
+.byte 46
+.byte 0
+.align 0
+L.987:
+.byte 32
+.byte 32
+.byte 32
+.byte 83
+.byte 101
+.byte 114
+.byte 105
+.byte 111
+.byte 117
+.byte 115
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 115
+.byte 44
+.byte 32
+.byte 108
+.byte 105
+.byte 107
+.byte 101
+.byte 32
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 97
+.byte 32
+.byte 103
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 44
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 0
+.align 0
+L.986:
+.byte 32
+.byte 32
+.byte 32
+.byte 70
+.byte 76
+.byte 65
+.byte 87
+.byte 115
+.byte 44
+.byte 32
+.byte 108
+.byte 105
+.byte 107
+.byte 101
+.byte 32
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 97
+.byte 32
+.byte 115
+.byte 116
+.byte 105
+.byte 99
+.byte 107
+.byte 121
+.byte 32
+.byte 98
+.byte 105
+.byte 116
+.byte 44
+.byte 0
+.align 0
+L.985:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 97
+.byte 116
+.byte 116
+.byte 101
+.byte 109
+.byte 112
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 114
+.byte 105
+.byte 109
+.byte 105
+.byte 110
+.byte 97
+.byte 116
+.byte 101
+.byte 32
+.byte 97
+.byte 109
+.byte 111
+.byte 110
+.byte 103
+.byte 0
+.align 0
+L.982:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 68
+.byte 101
+.byte 99
+.byte 105
+.byte 109
+.byte 97
+.byte 108
+.byte 45
+.byte 66
+.byte 105
+.byte 110
+.byte 97
+.byte 114
+.byte 121
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 118
+.byte 101
+.byte 114
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 78
+.byte 79
+.byte 84
+.byte 32
+.byte 89
+.byte 69
+.byte 84
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 97
+.byte 99
+.byte 99
+.byte 117
+.byte 114
+.byte 97
+.byte 99
+.byte 121
+.byte 46
+.byte 0
+.align 0
+L.981:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 69
+.byte 120
+.byte 116
+.byte 114
+.byte 97
+.byte 45
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 101
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 101
+.byte 120
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 101
+.byte 118
+.byte 101
+.byte 97
+.byte 108
+.byte 101
+.byte 100
+.byte 32
+.byte 98
+.byte 117
+.byte 116
+.byte 32
+.byte 78
+.byte 79
+.byte 84
+.byte 32
+.byte 89
+.byte 69
+.byte 84
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 101
+.byte 100
+.byte 46
+.byte 0
+.align 0
+L.980:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 83
+.byte 113
+.byte 114
+.byte 116
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 101
+.byte 100
+.byte 46
+.byte 32
+.byte 32
+.byte 89
+.byte 94
+.byte 88
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 101
+.byte 100
+.byte 46
+.byte 0
+.align 0
+L.979:
+.byte 9
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 116
+.byte 97
+.byte 109
+.byte 105
+.byte 110
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 112
+.byte 115
+.byte 101
+.byte 117
+.byte 100
+.byte 111
+.byte 45
+.byte 122
+.byte 101
+.byte 114
+.byte 111
+.byte 115
+.byte 46
+.byte 0
+.align 0
+L.978:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 99
+.byte 104
+.byte 101
+.byte 99
+.byte 107
+.byte 101
+.byte 100
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 115
+.byte 105
+.byte 115
+.byte 116
+.byte 101
+.byte 110
+.byte 99
+.byte 121
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 0
+.align 0
+L.977:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 86
+.byte 48
+.byte 32
+.byte 32
+.byte 116
+.byte 101
+.byte 108
+.byte 108
+.byte 115
+.byte 44
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 108
+.byte 121
+.byte 44
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 32
+.byte 73
+.byte 110
+.byte 102
+.byte 105
+.byte 110
+.byte 105
+.byte 116
+.byte 121
+.byte 32
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 114
+.byte 101
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 101
+.byte 110
+.byte 116
+.byte 101
+.byte 100
+.byte 46
+.byte 0
+.align 0
+L.976:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 86
+.byte 32
+.byte 61
+.byte 32
+.byte 97
+.byte 110
+.byte 32
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 44
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 108
+.byte 121
+.byte 46
+.byte 0
+.align 0
+L.975:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 69
+.byte 48
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 80
+.byte 115
+.byte 101
+.byte 117
+.byte 100
+.byte 111
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 116
+.byte 101
+.byte 108
+.byte 108
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 97
+.byte 98
+.byte 114
+.byte 117
+.byte 112
+.byte 116
+.byte 44
+.byte 32
+.byte 103
+.byte 114
+.byte 97
+.byte 100
+.byte 117
+.byte 97
+.byte 108
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 102
+.byte 117
+.byte 122
+.byte 122
+.byte 121
+.byte 46
+.byte 0
+.align 0
+L.974:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 84
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 61
+.byte 32
+.byte 97
+.byte 110
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 46
+.byte 0
+.align 0
+L.973:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 87
+.byte 104
+.byte 101
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 97
+.byte 32
+.byte 83
+.byte 116
+.byte 105
+.byte 99
+.byte 107
+.byte 121
+.byte 32
+.byte 66
+.byte 105
+.byte 116
+.byte 32
+.byte 117
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 105
+.byte 110
+.byte 103
+.byte 46
+.byte 0
+.align 0
+L.972:
+.byte 9
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 46
+.byte 44
+.byte 32
+.byte 68
+.byte 105
+.byte 118
+.byte 46
+.byte 44
+.byte 32
+.byte 65
+.byte 100
+.byte 100
+.byte 47
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 46
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 83
+.byte 113
+.byte 114
+.byte 116
+.byte 46
+.byte 0
+.align 0
+L.971:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 87
+.byte 104
+.byte 101
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 44
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 100
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 115
+.byte 111
+.byte 109
+.byte 101
+.byte 116
+.byte 104
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 101
+.byte 108
+.byte 115
+.byte 101
+.byte 0
+.align 0
+L.970:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 65
+.byte 100
+.byte 101
+.byte 113
+.byte 117
+.byte 97
+.byte 99
+.byte 121
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 103
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 46
+.byte 44
+.byte 32
+.byte 68
+.byte 105
+.byte 118
+.byte 46
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 46
+.byte 0
+.align 0
+L.969:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 85
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 49
+.byte 47
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 94
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 61
+.byte 32
+.byte 79
+.byte 110
+.byte 101
+.byte 32
+.byte 85
+.byte 108
+.byte 112
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 108
+.byte 105
+.byte 116
+.byte 116
+.byte 108
+.byte 101
+.byte 32
+.byte 108
+.byte 101
+.byte 115
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 110
+.byte 32
+.byte 49
+.byte 46
+.byte 48
+.byte 32
+.byte 46
+.byte 0
+.align 0
+L.968:
+.byte 9
+.byte 40
+.byte 79
+.byte 110
+.byte 101
+.byte 85
+.byte 108
+.byte 112
+.byte 110
+.byte 105
+.byte 116
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 76
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 80
+.byte 108
+.byte 97
+.byte 99
+.byte 101
+.byte 41
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 49
+.byte 46
+.byte 48
+.byte 48
+.byte 48
+.byte 120
+.byte 120
+.byte 120
+.byte 32
+.byte 46
+.byte 0
+.align 0
+L.967:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 85
+.byte 50
+.byte 32
+.byte 61
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 47
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 94
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 61
+.byte 32
+.byte 79
+.byte 110
+.byte 101
+.byte 32
+.byte 85
+.byte 108
+.byte 112
+.byte 0
+.align 0
+L.966:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 61
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 105
+.byte 102
+.byte 105
+.byte 99
+.byte 97
+.byte 110
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 99
+.byte 97
+.byte 114
+.byte 114
+.byte 105
+.byte 101
+.byte 100
+.byte 46
+.byte 0
+.align 0
+L.965:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 49
+.byte 44
+.byte 32
+.byte 50
+.byte 44
+.byte 32
+.byte 52
+.byte 44
+.byte 32
+.byte 56
+.byte 44
+.byte 32
+.byte 49
+.byte 48
+.byte 44
+.byte 32
+.byte 49
+.byte 54
+.byte 44
+.byte 32
+.byte 49
+.byte 48
+.byte 48
+.byte 44
+.byte 32
+.byte 50
+.byte 53
+.byte 54
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 0
+.align 0
+L.964:
+.byte 82
+.byte 117
+.byte 110
+.byte 110
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 114
+.byte 101
+.byte 118
+.byte 101
+.byte 97
+.byte 108
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 115
+.byte 101
+.byte 32
+.byte 99
+.byte 104
+.byte 97
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 101
+.byte 114
+.byte 105
+.byte 115
+.byte 116
+.byte 105
+.byte 99
+.byte 115
+.byte 58
+.byte 0
+.align 0
+L.961:
+.byte 9
+.byte 79
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 114
+.byte 101
+.byte 108
+.byte 101
+.byte 118
+.byte 97
+.byte 110
+.byte 116
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 105
+.byte 108
+.byte 101
+.byte 114
+.byte 32
+.byte 111
+.byte 112
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 58
+.byte 0
+.align 0
+L.960:
+.byte 9
+.byte 79
+.byte 112
+.byte 116
+.byte 105
+.byte 109
+.byte 105
+.byte 122
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 108
+.byte 101
+.byte 118
+.byte 101
+.byte 108
+.byte 58
+.byte 10
+.byte 0
+.align 0
+L.959:
+.byte 9
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 105
+.byte 108
+.byte 101
+.byte 114
+.byte 58
+.byte 10
+.byte 0
+.align 0
+L.958:
+.byte 9
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 114
+.byte 58
+.byte 10
+.byte 0
+.align 0
+L.957:
+.byte 9
+.byte 86
+.byte 101
+.byte 114
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 58
+.byte 9
+.byte 49
+.byte 48
+.byte 32
+.byte 70
+.byte 101
+.byte 98
+.byte 114
+.byte 117
+.byte 97
+.byte 114
+.byte 121
+.byte 32
+.byte 49
+.byte 57
+.byte 56
+.byte 57
+.byte 59
+.byte 0
+.align 0
+L.956:
+.byte 9
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 58
+.byte 9
+.byte 100
+.byte 111
+.byte 117
+.byte 98
+.byte 108
+.byte 101
+.byte 59
+.byte 0
+.align 0
+L.955:
+.byte 73
+.byte 110
+.byte 32
+.byte 100
+.byte 111
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 115
+.byte 111
+.byte 44
+.byte 32
+.byte 112
+.byte 108
+.byte 101
+.byte 97
+.byte 115
+.byte 101
+.byte 32
+.byte 105
+.byte 110
+.byte 99
+.byte 108
+.byte 117
+.byte 100
+.byte 101
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 102
+.byte 111
+.byte 108
+.byte 108
+.byte 111
+.byte 119
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 105
+.byte 110
+.byte 102
+.byte 111
+.byte 114
+.byte 109
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 58
+.byte 0
+.align 0
+L.954:
+.byte 9
+.byte 83
+.byte 97
+.byte 110
+.byte 32
+.byte 70
+.byte 114
+.byte 97
+.byte 110
+.byte 99
+.byte 105
+.byte 115
+.byte 99
+.byte 111
+.byte 44
+.byte 32
+.byte 67
+.byte 65
+.byte 32
+.byte 57
+.byte 52
+.byte 49
+.byte 52
+.byte 51
+.byte 45
+.byte 48
+.byte 55
+.byte 48
+.byte 52
+.byte 44
+.byte 32
+.byte 85
+.byte 83
+.byte 65
+.byte 10
+.byte 0
+.align 0
+L.953:
+.byte 9
+.byte 85
+.byte 110
+.byte 105
+.byte 118
+.byte 101
+.byte 114
+.byte 115
+.byte 105
+.byte 116
+.byte 121
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 67
+.byte 97
+.byte 108
+.byte 105
+.byte 102
+.byte 111
+.byte 114
+.byte 110
+.byte 105
+.byte 97
+.byte 0
+.align 0
+L.952:
+.byte 9
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 67
+.byte 101
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 85
+.byte 45
+.byte 55
+.byte 54
+.byte 0
+.align 0
+L.951:
+.byte 9
+.byte 82
+.byte 105
+.byte 99
+.byte 104
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 75
+.byte 97
+.byte 114
+.byte 112
+.byte 105
+.byte 110
+.byte 115
+.byte 107
+.byte 105
+.byte 0
+.align 0
+L.950:
+.byte 80
+.byte 108
+.byte 101
+.byte 97
+.byte 115
+.byte 101
+.byte 32
+.byte 115
+.byte 101
+.byte 110
+.byte 100
+.byte 32
+.byte 115
+.byte 117
+.byte 103
+.byte 103
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 105
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 114
+.byte 101
+.byte 115
+.byte 117
+.byte 108
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 0
+.align 0
+L.949:
+.byte 99
+.byte 111
+.byte 112
+.byte 101
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 117
+.byte 110
+.byte 97
+.byte 110
+.byte 116
+.byte 105
+.byte 99
+.byte 105
+.byte 112
+.byte 97
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 110
+.byte 101
+.byte 119
+.byte 108
+.byte 121
+.byte 32
+.byte 117
+.byte 110
+.byte 99
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 112
+.byte 97
+.byte 116
+.byte 104
+.byte 111
+.byte 108
+.byte 111
+.byte 103
+.byte 105
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.948:
+.byte 85
+.byte 115
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 105
+.byte 110
+.byte 118
+.byte 105
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 104
+.byte 101
+.byte 108
+.byte 112
+.byte 32
+.byte 100
+.byte 101
+.byte 98
+.byte 117
+.byte 103
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 97
+.byte 117
+.byte 103
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 115
+.byte 111
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 119
+.byte 105
+.byte 108
+.byte 108
+.byte 0
+.align 0
+L.945:
+.byte 65
+.byte 110
+.byte 115
+.byte 119
+.byte 101
+.byte 114
+.byte 32
+.byte 113
+.byte 117
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 89
+.byte 44
+.byte 32
+.byte 121
+.byte 44
+.byte 32
+.byte 78
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 110
+.byte 32
+.byte 40
+.byte 117
+.byte 110
+.byte 108
+.byte 101
+.byte 115
+.byte 115
+.byte 32
+.byte 111
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 119
+.byte 105
+.byte 115
+.byte 101
+.byte 32
+.byte 105
+.byte 110
+.byte 100
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 101
+.byte 100
+.byte 41
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.944:
+.byte 97
+.byte 109
+.byte 101
+.byte 110
+.byte 100
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 109
+.byte 97
+.byte 107
+.byte 101
+.byte 32
+.byte 102
+.byte 117
+.byte 114
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 101
+.byte 115
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.943:
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 97
+.byte 110
+.byte 121
+.byte 119
+.byte 97
+.byte 121
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 115
+.byte 101
+.byte 101
+.byte 32
+.byte 104
+.byte 111
+.byte 119
+.byte 32
+.byte 109
+.byte 97
+.byte 110
+.byte 121
+.byte 32
+.byte 109
+.byte 105
+.byte 108
+.byte 101
+.byte 115
+.byte 116
+.byte 111
+.byte 110
+.byte 101
+.byte 115
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 112
+.byte 97
+.byte 115
+.byte 115
+.byte 101
+.byte 115
+.byte 44
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 110
+.byte 0
+.align 0
+L.942:
+.byte 119
+.byte 97
+.byte 114
+.byte 110
+.byte 105
+.byte 110
+.byte 103
+.byte 46
+.byte 32
+.byte 32
+.byte 73
+.byte 102
+.byte 32
+.byte 112
+.byte 101
+.byte 114
+.byte 115
+.byte 117
+.byte 97
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 118
+.byte 97
+.byte 105
+.byte 108
+.byte 115
+.byte 32
+.byte 110
+.byte 97
+.byte 117
+.byte 103
+.byte 104
+.byte 116
+.byte 44
+.byte 32
+.byte 100
+.byte 111
+.byte 110
+.byte 39
+.byte 116
+.byte 32
+.byte 100
+.byte 101
+.byte 115
+.byte 112
+.byte 97
+.byte 105
+.byte 114
+.byte 32
+.byte 98
+.byte 117
+.byte 116
+.byte 32
+.byte 114
+.byte 117
+.byte 110
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 0
+.align 0
+L.941:
+.byte 116
+.byte 111
+.byte 32
+.byte 112
+.byte 101
+.byte 114
+.byte 115
+.byte 101
+.byte 118
+.byte 101
+.byte 114
+.byte 101
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 97
+.byte 32
+.byte 115
+.byte 117
+.byte 114
+.byte 114
+.byte 111
+.byte 103
+.byte 97
+.byte 116
+.byte 101
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 97
+.byte 102
+.byte 116
+.byte 101
+.byte 114
+.byte 44
+.byte 32
+.byte 112
+.byte 101
+.byte 114
+.byte 104
+.byte 97
+.byte 112
+.byte 115
+.byte 44
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 112
+.byte 108
+.byte 97
+.byte 121
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 115
+.byte 111
+.byte 109
+.byte 101
+.byte 0
+.align 0
+L.940:
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 108
+.byte 105
+.byte 107
+.byte 101
+.byte 32
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 47
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 111
+.byte 99
+.byte 99
+.byte 117
+.byte 114
+.byte 115
+.byte 44
+.byte 32
+.byte 98
+.byte 117
+.byte 116
+.byte 32
+.byte 114
+.byte 97
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 0
+.align 0
+L.939:
+.byte 116
+.byte 114
+.byte 121
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 112
+.byte 101
+.byte 114
+.byte 115
+.byte 117
+.byte 97
+.byte 100
+.byte 101
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 78
+.byte 79
+.byte 84
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 116
+.byte 101
+.byte 114
+.byte 109
+.byte 105
+.byte 110
+.byte 97
+.byte 116
+.byte 101
+.byte 32
+.byte 101
+.byte 120
+.byte 101
+.byte 99
+.byte 117
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 110
+.byte 32
+.byte 97
+.byte 110
+.byte 0
+.align 0
+L.938:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 96
+.byte 69
+.byte 78
+.byte 68
+.byte 32
+.byte 79
+.byte 70
+.byte 32
+.byte 84
+.byte 69
+.byte 83
+.byte 84
+.byte 39
+.byte 44
+.byte 10
+.byte 0
+.align 0
+L.937:
+.byte 76
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 115
+.byte 116
+.byte 111
+.byte 112
+.byte 32
+.byte 112
+.byte 114
+.byte 101
+.byte 109
+.byte 97
+.byte 116
+.byte 117
+.byte 114
+.byte 101
+.byte 108
+.byte 121
+.byte 44
+.byte 32
+.byte 105
+.byte 46
+.byte 101
+.byte 46
+.byte 32
+.byte 98
+.byte 101
+.byte 102
+.byte 111
+.byte 114
+.byte 101
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 112
+.byte 108
+.byte 97
+.byte 121
+.byte 105
+.byte 110
+.byte 103
+.byte 10
+.byte 0
+.align 0
+L.934:
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.929:
+.byte 32
+.byte 32
+.byte 32
+.byte 80
+.byte 76
+.byte 69
+.byte 65
+.byte 83
+.byte 69
+.byte 32
+.byte 78
+.byte 79
+.byte 84
+.byte 73
+.byte 70
+.byte 89
+.byte 32
+.byte 75
+.byte 65
+.byte 82
+.byte 80
+.byte 73
+.byte 78
+.byte 75
+.byte 83
+.byte 73
+.byte 33
+.byte 10
+.byte 0
+.align 0
+L.928:
+.byte 37
+.byte 115
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 105
+.byte 110
+.byte 99
+.byte 111
+.byte 110
+.byte 115
+.byte 105
+.byte 115
+.byte 116
+.byte 101
+.byte 110
+.byte 116
+.byte 46
+.byte 46
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.926:
+.byte 9
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 90
+.byte 32
+.byte 42
+.byte 32
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.925:
+.byte 9
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 49
+.byte 32
+.byte 42
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.924:
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 100
+.byte 111
+.byte 101
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 109
+.byte 117
+.byte 116
+.byte 101
+.byte 33
+.byte 10
+.byte 0
+.align 0
+L.919:
+.byte 90
+.byte 32
+.byte 47
+.byte 32
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.916:
+.byte 49
+.byte 32
+.byte 42
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 37
+.byte 103
+.byte 10
+.byte 0
+.align 0
+L.913:
+.byte 90
+.byte 32
+.byte 42
+.byte 32
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 0
+.align 0
+L.910:
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 9
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 101
+.byte 115
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 32
+.byte 0
+.align 0
+L.909:
+.byte 87
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 112
+.byte 114
+.byte 105
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 0
+.align 0
+L.904:
+.byte 84
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 33
+.byte 10
+.byte 0
+.align 0
+L.901:
+.byte 84
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 86
+.byte 69
+.byte 82
+.byte 89
+.byte 32
+.byte 83
+.byte 69
+.byte 82
+.byte 73
+.byte 79
+.byte 85
+.byte 83
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 33
+.byte 10
+.byte 0
+.align 0
+L.895:
+.byte 32
+.byte 104
+.byte 97
+.byte 115
+.byte 32
+.byte 78
+.byte 79
+.byte 84
+.byte 32
+.byte 106
+.byte 117
+.byte 115
+.byte 116
+.byte 32
+.byte 98
+.byte 101
+.byte 101
+.byte 110
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 97
+.byte 108
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.894:
+.byte 84
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 79
+.byte 46
+.byte 75
+.byte 46
+.byte 44
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 118
+.byte 105
+.byte 100
+.byte 101
+.byte 100
+.byte 32
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 47
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 0
+.align 0
+L.891:
+.byte 87
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 109
+.byte 97
+.byte 99
+.byte 104
+.byte 105
+.byte 110
+.byte 101
+.byte 32
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 40
+.byte 90
+.byte 32
+.byte 43
+.byte 32
+.byte 90
+.byte 41
+.byte 32
+.byte 47
+.byte 32
+.byte 90
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.887:
+.byte 40
+.byte 90
+.byte 32
+.byte 43
+.byte 32
+.byte 90
+.byte 41
+.byte 32
+.byte 47
+.byte 32
+.byte 90
+.byte 32
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 115
+.byte 97
+.byte 102
+.byte 101
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.886:
+.byte 83
+.byte 105
+.byte 110
+.byte 99
+.byte 101
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 100
+.byte 101
+.byte 110
+.byte 105
+.byte 101
+.byte 115
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 101
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 0
+.align 0
+L.882:
+.byte 83
+.byte 105
+.byte 109
+.byte 105
+.byte 108
+.byte 97
+.byte 114
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 114
+.byte 101
+.byte 112
+.byte 97
+.byte 110
+.byte 99
+.byte 105
+.byte 101
+.byte 115
+.byte 32
+.byte 104
+.byte 97
+.byte 118
+.byte 101
+.byte 32
+.byte 111
+.byte 99
+.byte 99
+.byte 117
+.byte 114
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 116
+.byte 105
+.byte 109
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.872:
+.byte 9
+.byte 9
+.byte 116
+.byte 104
+.byte 101
+.byte 121
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.871:
+.byte 9
+.byte 119
+.byte 104
+.byte 105
+.byte 99
+.byte 104
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 117
+.byte 110
+.byte 101
+.byte 113
+.byte 117
+.byte 97
+.byte 108
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 59
+.byte 10
+.byte 0
+.align 0
+L.870:
+.byte 9
+.byte 121
+.byte 105
+.byte 101
+.byte 108
+.byte 100
+.byte 101
+.byte 100
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 59
+.byte 10
+.byte 0
+.align 0
+L.869:
+.byte 9
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 32
+.byte 94
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 10
+.byte 0
+.align 0
+L.868:
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 10
+.byte 0
+.align 0
+L.867:
+.byte 87
+.byte 65
+.byte 82
+.byte 78
+.byte 73
+.byte 78
+.byte 71
+.byte 58
+.byte 32
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 10
+.byte 0
+.align 0
+L.849:
+.byte 9
+.byte 105
+.byte 110
+.byte 115
+.byte 116
+.byte 101
+.byte 97
+.byte 100
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 48
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.848:
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 40
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 32
+.byte 45
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 3
+L.840:
+.word 0x3ed4f8b5
+.word 0x88e368f1
+.align 0
+L.838:
+.byte 37
+.byte 115
+.byte 58
+.byte 32
+.byte 32
+.byte 37
+.byte 115
+.byte 0
+.align 0
+L.837:
+.byte 70
+.byte 76
+.byte 65
+.byte 87
+.byte 0
+.align 0
+L.836:
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 0
+.align 0
+L.835:
+.byte 83
+.byte 69
+.byte 82
+.byte 73
+.byte 79
+.byte 85
+.byte 83
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 0
+.align 0
+L.834:
+.byte 70
+.byte 65
+.byte 73
+.byte 76
+.byte 85
+.byte 82
+.byte 69
+.byte 0
+.align 0
+L.828:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 80
+.byte 97
+.byte 103
+.byte 101
+.byte 58
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 10
+.byte 0
+.align 0
+L.827:
+.byte 10
+.byte 68
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 105
+.byte 115
+.byte 32
+.byte 114
+.byte 101
+.byte 115
+.byte 117
+.byte 109
+.byte 101
+.byte 115
+.byte 32
+.byte 97
+.byte 102
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 109
+.byte 105
+.byte 108
+.byte 101
+.byte 115
+.byte 116
+.byte 111
+.byte 110
+.byte 101
+.byte 32
+.byte 78
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 32
+.byte 37
+.byte 100
+.byte 0
+.align 3
+L.825:
+.word 0xbff00000
+.word 0x0
+.align 0
+L.820:
+.byte 69
+.byte 78
+.byte 68
+.byte 32
+.byte 79
+.byte 70
+.byte 32
+.byte 84
+.byte 69
+.byte 83
+.byte 84
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.819:
+.byte 10
+.byte 65
+.byte 32
+.byte 116
+.byte 111
+.byte 116
+.byte 97
+.byte 108
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 102
+.byte 108
+.byte 111
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 112
+.byte 111
+.byte 105
+.byte 110
+.byte 116
+.byte 32
+.byte 101
+.byte 120
+.byte 99
+.byte 101
+.byte 112
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 119
+.byte 101
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 101
+.byte 103
+.byte 105
+.byte 115
+.byte 116
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.816:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 69
+.byte 120
+.byte 99
+.byte 101
+.byte 108
+.byte 108
+.byte 101
+.byte 110
+.byte 116
+.byte 33
+.byte 10
+.byte 0
+.align 0
+L.815:
+.byte 32
+.byte 100
+.byte 117
+.byte 114
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 71
+.byte 114
+.byte 97
+.byte 100
+.byte 117
+.byte 97
+.byte 108
+.byte 32
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.814:
+.byte 44
+.byte 10
+.byte 101
+.byte 120
+.byte 99
+.byte 101
+.byte 112
+.byte 116
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 112
+.byte 111
+.byte 115
+.byte 115
+.byte 105
+.byte 98
+.byte 108
+.byte 121
+.byte 32
+.byte 68
+.byte 111
+.byte 117
+.byte 98
+.byte 108
+.byte 101
+.byte 32
+.byte 82
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 105
+.byte 110
+.byte 103
+.byte 0
+.align 0
+L.813:
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.810:
+.byte 56
+.byte 53
+.byte 52
+.byte 0
+.align 0
+L.809:
+.byte 55
+.byte 53
+.byte 52
+.byte 0
+.align 0
+L.806:
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 112
+.byte 111
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 73
+.byte 69
+.byte 69
+.byte 69
+.byte 32
+.byte 115
+.byte 116
+.byte 97
+.byte 110
+.byte 100
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 80
+.byte 0
+.align 0
+L.805:
+.byte 82
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 111
+.byte 114
+.byte 109
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 0
+.align 0
+L.802:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 115
+.byte 101
+.byte 101
+.byte 109
+.byte 115
+.byte 32
+.byte 83
+.byte 97
+.byte 116
+.byte 105
+.byte 115
+.byte 102
+.byte 97
+.byte 99
+.byte 116
+.byte 111
+.byte 114
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.796:
+.byte 78
+.byte 111
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 117
+.byte 114
+.byte 101
+.byte 115
+.byte 44
+.byte 32
+.byte 100
+.byte 101
+.byte 102
+.byte 101
+.byte 99
+.byte 116
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 102
+.byte 108
+.byte 97
+.byte 119
+.byte 115
+.byte 32
+.byte 104
+.byte 97
+.byte 118
+.byte 101
+.byte 32
+.byte 98
+.byte 101
+.byte 101
+.byte 110
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.795:
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 39
+.byte 115
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 115
+.byte 101
+.byte 113
+.byte 117
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.794:
+.byte 80
+.byte 111
+.byte 116
+.byte 101
+.byte 110
+.byte 116
+.byte 105
+.byte 97
+.byte 108
+.byte 108
+.byte 121
+.byte 32
+.byte 102
+.byte 97
+.byte 116
+.byte 97
+.byte 108
+.byte 32
+.byte 70
+.byte 65
+.byte 73
+.byte 76
+.byte 85
+.byte 82
+.byte 69
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 104
+.byte 97
+.byte 118
+.byte 101
+.byte 32
+.byte 115
+.byte 112
+.byte 111
+.byte 105
+.byte 108
+.byte 101
+.byte 100
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 0
+.align 0
+L.791:
+.byte 117
+.byte 110
+.byte 97
+.byte 99
+.byte 99
+.byte 101
+.byte 112
+.byte 116
+.byte 97
+.byte 98
+.byte 108
+.byte 101
+.byte 32
+.byte 83
+.byte 101
+.byte 114
+.byte 105
+.byte 111
+.byte 117
+.byte 115
+.byte 32
+.byte 68
+.byte 101
+.byte 102
+.byte 101
+.byte 99
+.byte 116
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.790:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 104
+.byte 97
+.byte 115
+.byte 32
+.byte 0
+.align 0
+L.786:
+.byte 100
+.byte 101
+.byte 115
+.byte 112
+.byte 105
+.byte 116
+.byte 101
+.byte 32
+.byte 105
+.byte 110
+.byte 99
+.byte 111
+.byte 110
+.byte 118
+.byte 101
+.byte 110
+.byte 105
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 68
+.byte 101
+.byte 102
+.byte 101
+.byte 99
+.byte 116
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.785:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 65
+.byte 99
+.byte 99
+.byte 101
+.byte 112
+.byte 116
+.byte 97
+.byte 98
+.byte 108
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.780:
+.byte 83
+.byte 97
+.byte 116
+.byte 105
+.byte 115
+.byte 102
+.byte 97
+.byte 99
+.byte 116
+.byte 111
+.byte 114
+.byte 121
+.byte 32
+.byte 116
+.byte 104
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 32
+.byte 102
+.byte 108
+.byte 97
+.byte 119
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.779:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 115
+.byte 101
+.byte 101
+.byte 109
+.byte 115
+.byte 32
+.byte 0
+.align 0
+L.768:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 32
+.byte 37
+.byte 45
+.byte 50
+.byte 57
+.byte 115
+.byte 32
+.byte 37
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.761:
+.byte 70
+.byte 76
+.byte 65
+.byte 87
+.byte 115
+.byte 32
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 61
+.byte 0
+.align 0
+L.760:
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 115
+.byte 32
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 61
+.byte 0
+.align 0
+L.759:
+.byte 83
+.byte 69
+.byte 82
+.byte 73
+.byte 79
+.byte 85
+.byte 83
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 115
+.byte 32
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 61
+.byte 0
+.align 0
+L.758:
+.byte 70
+.byte 65
+.byte 73
+.byte 76
+.byte 85
+.byte 82
+.byte 69
+.byte 115
+.byte 32
+.byte 32
+.byte 101
+.byte 110
+.byte 99
+.byte 111
+.byte 117
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 61
+.byte 0
+.align 0
+L.754:
+.byte 10
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 84
+.byte 114
+.byte 121
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 32
+.byte 48
+.byte 32
+.byte 47
+.byte 32
+.byte 48
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 100
+.byte 117
+.byte 99
+.byte 101
+.byte 115
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 0
+.align 0
+L.753:
+.byte 32
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.750:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 84
+.byte 114
+.byte 121
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 32
+.byte 49
+.byte 32
+.byte 47
+.byte 32
+.byte 48
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 100
+.byte 117
+.byte 99
+.byte 101
+.byte 115
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 0
+.align 0
+L.749:
+.byte 87
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 109
+.byte 101
+.byte 115
+.byte 115
+.byte 97
+.byte 103
+.byte 101
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 47
+.byte 111
+.byte 114
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 115
+.byte 32
+.byte 100
+.byte 111
+.byte 101
+.byte 115
+.byte 32
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 100
+.byte 117
+.byte 99
+.byte 101
+.byte 63
+.byte 10
+.byte 0
+.align 0
+L.748:
+.byte 32
+.byte 32
+.byte 105
+.byte 110
+.byte 115
+.byte 116
+.byte 101
+.byte 97
+.byte 100
+.byte 44
+.byte 32
+.byte 88
+.byte 32
+.byte 47
+.byte 32
+.byte 88
+.byte 32
+.byte 45
+.byte 32
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 45
+.byte 32
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.747:
+.byte 32
+.byte 32
+.byte 88
+.byte 32
+.byte 47
+.byte 32
+.byte 88
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 49
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 110
+.byte 32
+.byte 88
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.742:
+.byte 32
+.byte 32
+.byte 88
+.byte 32
+.byte 47
+.byte 32
+.byte 88
+.byte 32
+.byte 32
+.byte 116
+.byte 114
+.byte 97
+.byte 112
+.byte 115
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 110
+.byte 32
+.byte 88
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 103
+.byte 10
+.byte 0
+.align 0
+L.727:
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 102
+.byte 97
+.byte 114
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 49
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.726:
+.byte 32
+.byte 117
+.byte 110
+.byte 98
+.byte 97
+.byte 108
+.byte 97
+.byte 110
+.byte 99
+.byte 101
+.byte 100
+.byte 32
+.byte 114
+.byte 97
+.byte 110
+.byte 103
+.byte 101
+.byte 59
+.byte 32
+.byte 85
+.byte 102
+.byte 84
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 42
+.byte 32
+.byte 86
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 9
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.725:
+.byte 66
+.byte 97
+.byte 100
+.byte 108
+.byte 121
+.byte 0
+.align 0
+L.718:
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 102
+.byte 97
+.byte 114
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 40
+.byte 90
+.byte 41
+.byte 32
+.byte 94
+.byte 32
+.byte 50
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.717:
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.705:
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 102
+.byte 97
+.byte 114
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 40
+.byte 90
+.byte 41
+.byte 32
+.byte 94
+.byte 32
+.byte 50
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.704:
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 119
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 112
+.byte 114
+.byte 105
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.687:
+.byte 43
+.byte 45
+.byte 37
+.byte 103
+.byte 44
+.byte 32
+.byte 43
+.byte 45
+.byte 37
+.byte 103
+.byte 10
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 43
+.byte 45
+.byte 37
+.byte 103
+.byte 32
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 117
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 46
+.byte 0
+.align 0
+L.686:
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 105
+.byte 110
+.byte 118
+.byte 111
+.byte 108
+.byte 118
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 0
+.align 0
+L.680:
+.byte 97
+.byte 98
+.byte 111
+.byte 118
+.byte 101
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.679:
+.byte 65
+.byte 110
+.byte 121
+.byte 32
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 97
+.byte 108
+.byte 32
+.byte 115
+.byte 101
+.byte 112
+.byte 97
+.byte 114
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 42
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 111
+.byte 110
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.678:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 86
+.byte 32
+.byte 47
+.byte 32
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.677:
+.byte 78
+.byte 111
+.byte 32
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 97
+.byte 108
+.byte 101
+.byte 100
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 86
+.byte 32
+.byte 42
+.byte 32
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.676:
+.byte 84
+.byte 104
+.byte 101
+.byte 114
+.byte 101
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 32
+.byte 115
+.byte 97
+.byte 116
+.byte 117
+.byte 114
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 98
+.byte 101
+.byte 99
+.byte 97
+.byte 117
+.byte 115
+.byte 101
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 115
+.byte 121
+.byte 115
+.byte 116
+.byte 101
+.byte 109
+.byte 32
+.byte 116
+.byte 114
+.byte 97
+.byte 112
+.byte 115
+.byte 32
+.byte 111
+.byte 110
+.byte 32
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.675:
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 115
+.byte 97
+.byte 116
+.byte 117
+.byte 114
+.byte 97
+.byte 116
+.byte 101
+.byte 115
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 86
+.byte 48
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.672:
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 86
+.byte 32
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.663:
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 112
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 9
+.byte 115
+.byte 104
+.byte 114
+.byte 105
+.byte 110
+.byte 107
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.660:
+.byte 45
+.byte 40
+.byte 45
+.byte 89
+.byte 41
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 89
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.659:
+.byte 102
+.byte 105
+.byte 110
+.byte 100
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 0
+.align 0
+L.658:
+.byte 83
+.byte 101
+.byte 101
+.byte 109
+.byte 115
+.byte 32
+.byte 79
+.byte 46
+.byte 75
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.655:
+.byte 84
+.byte 114
+.byte 121
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 111
+.byte 110
+.byte 32
+.byte 89
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.654:
+.byte 67
+.byte 97
+.byte 110
+.byte 32
+.byte 96
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 45
+.byte 89
+.byte 39
+.byte 32
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 63
+.byte 10
+.byte 0
+.align 0
+L.647:
+.byte 84
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 103
+.byte 101
+.byte 110
+.byte 101
+.byte 114
+.byte 97
+.byte 116
+.byte 101
+.byte 32
+.byte 97
+.byte 110
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.646:
+.byte 83
+.byte 101
+.byte 97
+.byte 114
+.byte 99
+.byte 104
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 58
+.byte 10
+.byte 0
+.align 0
+L.645:
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 32
+.byte 110
+.byte 111
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 114
+.byte 101
+.byte 112
+.byte 97
+.byte 110
+.byte 99
+.byte 105
+.byte 101
+.byte 115
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.637:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 112
+.byte 111
+.byte 119
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 90
+.byte 94
+.byte 81
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 114
+.byte 32
+.byte 110
+.byte 101
+.byte 97
+.byte 114
+.byte 108
+.byte 121
+.byte 32
+.byte 101
+.byte 120
+.byte 116
+.byte 114
+.byte 101
+.byte 109
+.byte 101
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.636:
+.byte 65
+.byte 99
+.byte 99
+.byte 117
+.byte 114
+.byte 97
+.byte 99
+.byte 121
+.byte 32
+.byte 115
+.byte 101
+.byte 101
+.byte 109
+.byte 115
+.byte 32
+.byte 97
+.byte 100
+.byte 101
+.byte 113
+.byte 117
+.byte 97
+.byte 116
+.byte 101
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.629:
+.byte 9
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 105
+.byte 110
+.byte 118
+.byte 111
+.byte 108
+.byte 118
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 105
+.byte 110
+.byte 121
+.byte 32
+.byte 105
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 114
+.byte 97
+.byte 116
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.628:
+.byte 9
+.byte 84
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 109
+.byte 117
+.byte 99
+.byte 104
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 115
+.byte 112
+.byte 111
+.byte 105
+.byte 108
+.byte 32
+.byte 102
+.byte 105
+.byte 110
+.byte 97
+.byte 110
+.byte 99
+.byte 105
+.byte 97
+.byte 108
+.byte 10
+.byte 0
+.align 0
+L.627:
+.byte 9
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.626:
+.byte 9
+.byte 40
+.byte 49
+.byte 32
+.byte 43
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 32
+.byte 94
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 59
+.byte 10
+.byte 0
+.align 0
+L.625:
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 10
+.byte 0
+.align 0
+L.624:
+.byte 67
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 101
+.byte 100
+.byte 0
+.align 0
+L.617:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 88
+.byte 94
+.byte 40
+.byte 40
+.byte 88
+.byte 32
+.byte 43
+.byte 32
+.byte 49
+.byte 41
+.byte 32
+.byte 47
+.byte 32
+.byte 40
+.byte 88
+.byte 32
+.byte 45
+.byte 32
+.byte 49
+.byte 41
+.byte 41
+.byte 32
+.byte 118
+.byte 115
+.byte 46
+.byte 32
+.byte 101
+.byte 120
+.byte 112
+.byte 40
+.byte 50
+.byte 41
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 88
+.byte 32
+.byte 45
+.byte 62
+.byte 32
+.byte 49
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.613:
+.byte 84
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 79
+.byte 46
+.byte 75
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.610:
+.byte 32
+.byte 32
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.609:
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 98
+.byte 101
+.byte 116
+.byte 119
+.byte 101
+.byte 101
+.byte 110
+.byte 32
+.byte 48
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 10
+.byte 0
+.align 0
+L.605:
+.byte 97
+.byte 99
+.byte 116
+.byte 117
+.byte 97
+.byte 108
+.byte 108
+.byte 121
+.byte 32
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 121
+.byte 105
+.byte 101
+.byte 108
+.byte 100
+.byte 115
+.byte 58
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.604:
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 97
+.byte 102
+.byte 102
+.byte 108
+.byte 105
+.byte 99
+.byte 116
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 101
+.byte 120
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 10
+.byte 9
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 32
+.byte 94
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 59
+.byte 10
+.byte 0
+.align 0
+L.603:
+.byte 85
+.byte 102
+.byte 84
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 61
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 32
+.byte 94
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 10
+.byte 111
+.byte 110
+.byte 108
+.byte 121
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 0
+.align 0
+L.602:
+.byte 83
+.byte 105
+.byte 110
+.byte 99
+.byte 101
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 111
+.byte 99
+.byte 99
+.byte 117
+.byte 114
+.byte 115
+.byte 32
+.byte 98
+.byte 101
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.601:
+.byte 82
+.byte 97
+.byte 110
+.byte 103
+.byte 101
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 110
+.byte 97
+.byte 114
+.byte 114
+.byte 111
+.byte 119
+.byte 59
+.byte 32
+.byte 85
+.byte 49
+.byte 94
+.byte 37
+.byte 100
+.byte 32
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.596:
+.byte 109
+.byte 101
+.byte 114
+.byte 101
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 111
+.byte 102
+.byte 102
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.595:
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 115
+.byte 117
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 32
+.byte 108
+.byte 97
+.byte 114
+.byte 103
+.byte 101
+.byte 114
+.byte 32
+.byte 82
+.byte 101
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 110
+.byte 32
+.byte 0
+.align 0
+L.594:
+.byte 32
+.byte 98
+.byte 101
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 119
+.byte 104
+.byte 105
+.byte 99
+.byte 104
+.byte 0
+.align 0
+L.593:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.592:
+.byte 88
+.byte 32
+.byte 47
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 49
+.byte 32
+.byte 43
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.591:
+.byte 88
+.byte 32
+.byte 47
+.byte 32
+.byte 90
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 115
+.byte 33
+.byte 10
+.byte 0
+.align 0
+L.588:
+.byte 101
+.byte 110
+.byte 99
+.byte 111
+.byte 117
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 97
+.byte 108
+.byte 116
+.byte 104
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 32
+.byte 97
+.byte 99
+.byte 116
+.byte 117
+.byte 97
+.byte 108
+.byte 108
+.byte 121
+.byte 10
+.byte 0
+.align 0
+L.587:
+.byte 32
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 32
+.byte 40
+.byte 102
+.byte 40
+.byte 88
+.byte 41
+.byte 32
+.byte 45
+.byte 32
+.byte 102
+.byte 40
+.byte 90
+.byte 41
+.byte 41
+.byte 32
+.byte 47
+.byte 32
+.byte 40
+.byte 88
+.byte 32
+.byte 45
+.byte 32
+.byte 90
+.byte 41
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.586:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 105
+.byte 102
+.byte 32
+.byte 40
+.byte 88
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 90
+.byte 41
+.byte 32
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 32
+.byte 32
+.byte 101
+.byte 108
+.byte 115
+.byte 101
+.byte 0
+.align 0
+L.585:
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 117
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 110
+.byte 32
+.byte 105
+.byte 110
+.byte 110
+.byte 111
+.byte 99
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 115
+.byte 116
+.byte 97
+.byte 116
+.byte 101
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 108
+.byte 105
+.byte 107
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.584:
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 83
+.byte 69
+.byte 82
+.byte 73
+.byte 79
+.byte 85
+.byte 83
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 10
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 99
+.byte 97
+.byte 117
+.byte 115
+.byte 101
+.byte 115
+.byte 32
+.byte 0
+.align 0
+L.583:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 83
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 78
+.byte 79
+.byte 84
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 97
+.byte 108
+.byte 32
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 44
+.byte 32
+.byte 0
+.align 0
+L.582:
+.byte 121
+.byte 101
+.byte 116
+.byte 32
+.byte 88
+.byte 32
+.byte 45
+.byte 32
+.byte 90
+.byte 32
+.byte 121
+.byte 105
+.byte 101
+.byte 108
+.byte 100
+.byte 115
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.581:
+.byte 88
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 9
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 101
+.byte 113
+.byte 117
+.byte 97
+.byte 108
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.576:
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 47
+.byte 32
+.byte 85
+.byte 102
+.byte 84
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 101
+.byte 100
+.byte 33
+.byte 10
+.byte 0
+.align 0
+L.566:
+.byte 40
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 111
+.byte 102
+.byte 102
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 85
+.byte 102
+.byte 84
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 41
+.byte 32
+.byte 60
+.byte 32
+.byte 69
+.byte 48
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.565:
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 103
+.byte 114
+.byte 97
+.byte 100
+.byte 117
+.byte 97
+.byte 108
+.byte 59
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 105
+.byte 110
+.byte 99
+.byte 117
+.byte 114
+.byte 115
+.byte 32
+.byte 65
+.byte 98
+.byte 115
+.byte 111
+.byte 108
+.byte 117
+.byte 116
+.byte 101
+.byte 32
+.byte 69
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 61
+.byte 10
+.byte 0
+.align 0
+L.560:
+.byte 124
+.byte 81
+.byte 32
+.byte 45
+.byte 32
+.byte 89
+.byte 124
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.559:
+.byte 112
+.byte 114
+.byte 105
+.byte 110
+.byte 116
+.byte 32
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 81
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 89
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.558:
+.byte 81
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 89
+.byte 32
+.byte 119
+.byte 104
+.byte 105
+.byte 108
+.byte 101
+.byte 32
+.byte 100
+.byte 101
+.byte 110
+.byte 121
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 124
+.byte 81
+.byte 32
+.byte 45
+.byte 32
+.byte 89
+.byte 124
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 48
+.byte 59
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 115
+.byte 101
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.557:
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 117
+.byte 115
+.byte 101
+.byte 115
+.byte 32
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 44
+.byte 32
+.byte 119
+.byte 104
+.byte 105
+.byte 99
+.byte 104
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 10
+.byte 0
+.align 0
+L.555:
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 101
+.byte 108
+.byte 115
+.byte 101
+.byte 32
+.byte 109
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 109
+.byte 97
+.byte 110
+.byte 121
+.byte 32
+.byte 108
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 119
+.byte 114
+.byte 111
+.byte 110
+.byte 103
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.554:
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 100
+.byte 111
+.byte 119
+.byte 110
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.553:
+.byte 97
+.byte 112
+.byte 112
+.byte 114
+.byte 111
+.byte 97
+.byte 99
+.byte 104
+.byte 32
+.byte 97
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.552:
+.byte 69
+.byte 105
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 97
+.byte 99
+.byte 99
+.byte 117
+.byte 114
+.byte 97
+.byte 99
+.byte 121
+.byte 32
+.byte 100
+.byte 101
+.byte 116
+.byte 101
+.byte 114
+.byte 105
+.byte 111
+.byte 114
+.byte 97
+.byte 116
+.byte 101
+.byte 115
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.540:
+.byte 83
+.byte 109
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 115
+.byte 116
+.byte 114
+.byte 105
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 112
+.byte 111
+.byte 115
+.byte 105
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 69
+.byte 48
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.539:
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 110
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 100
+.byte 117
+.byte 99
+.byte 116
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.538:
+.byte 68
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 101
+.byte 110
+.byte 99
+.byte 101
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 115
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 97
+.byte 32
+.byte 104
+.byte 105
+.byte 103
+.byte 104
+.byte 101
+.byte 114
+.byte 0
+.align 0
+L.535:
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 110
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 101
+.byte 110
+.byte 99
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.534:
+.byte 80
+.byte 114
+.byte 111
+.byte 100
+.byte 117
+.byte 99
+.byte 116
+.byte 115
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 97
+.byte 32
+.byte 104
+.byte 105
+.byte 103
+.byte 104
+.byte 101
+.byte 114
+.byte 0
+.align 0
+L.527:
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 80
+.byte 115
+.byte 101
+.byte 117
+.byte 100
+.byte 111
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 112
+.byte 114
+.byte 105
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.526:
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 32
+.byte 115
+.byte 116
+.byte 105
+.byte 99
+.byte 107
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 97
+.byte 110
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 100
+.byte 108
+.byte 121
+.byte 32
+.byte 112
+.byte 111
+.byte 115
+.byte 105
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.525:
+.byte 112
+.byte 111
+.byte 115
+.byte 105
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 44
+.byte 32
+.byte 105
+.byte 115
+.byte 110
+.byte 39
+.byte 116
+.byte 59
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 112
+.byte 114
+.byte 105
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.524:
+.byte 66
+.byte 117
+.byte 116
+.byte 32
+.byte 45
+.byte 80
+.byte 115
+.byte 101
+.byte 117
+.byte 100
+.byte 111
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 44
+.byte 32
+.byte 119
+.byte 104
+.byte 105
+.byte 99
+.byte 104
+.byte 32
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 98
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.521:
+.byte 80
+.byte 115
+.byte 101
+.byte 117
+.byte 100
+.byte 111
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 112
+.byte 114
+.byte 105
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 97
+.byte 115
+.byte 58
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.520:
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 100
+.byte 108
+.byte 121
+.byte 32
+.byte 110
+.byte 101
+.byte 103
+.byte 97
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.519:
+.byte 80
+.byte 111
+.byte 115
+.byte 105
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 101
+.byte 120
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 97
+.byte 110
+.byte 10
+.byte 0
+.align 0
+L.506:
+.byte 109
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 109
+.byte 97
+.byte 110
+.byte 121
+.byte 32
+.byte 108
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 119
+.byte 114
+.byte 111
+.byte 110
+.byte 103
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.482:
+.byte 83
+.byte 101
+.byte 101
+.byte 107
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 115
+.byte 32
+.byte 85
+.byte 102
+.byte 84
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 69
+.byte 48
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.479:
+.byte 46
+.byte 46
+.byte 46
+.byte 32
+.byte 110
+.byte 111
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 114
+.byte 101
+.byte 112
+.byte 97
+.byte 110
+.byte 99
+.byte 105
+.byte 115
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.476:
+.byte 9
+.byte 105
+.byte 110
+.byte 118
+.byte 111
+.byte 108
+.byte 118
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 105
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 114
+.byte 97
+.byte 116
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.475:
+.byte 69
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 115
+.byte 32
+.byte 108
+.byte 105
+.byte 107
+.byte 101
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 105
+.byte 110
+.byte 118
+.byte 97
+.byte 108
+.byte 105
+.byte 100
+.byte 97
+.byte 116
+.byte 101
+.byte 32
+.byte 102
+.byte 105
+.byte 110
+.byte 97
+.byte 110
+.byte 99
+.byte 105
+.byte 97
+.byte 108
+.byte 32
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.454:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 112
+.byte 111
+.byte 119
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 90
+.byte 94
+.byte 105
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 115
+.byte 109
+.byte 97
+.byte 108
+.byte 108
+.byte 32
+.byte 73
+.byte 110
+.byte 116
+.byte 101
+.byte 103
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 90
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 105
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.451:
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 32
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 109
+.byte 97
+.byte 110
+.byte 121
+.byte 32
+.byte 108
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 119
+.byte 114
+.byte 111
+.byte 110
+.byte 103
+.byte 0
+.align 0
+L.449:
+.byte 116
+.byte 111
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 117
+.byte 108
+.byte 112
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.448:
+.byte 79
+.byte 98
+.byte 115
+.byte 101
+.byte 114
+.byte 118
+.byte 101
+.byte 100
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 115
+.byte 32
+.byte 114
+.byte 117
+.byte 110
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 0
+.align 0
+L.447:
+.byte 83
+.byte 113
+.byte 117
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 111
+.byte 111
+.byte 116
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 101
+.byte 105
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.444:
+.byte 83
+.byte 113
+.byte 117
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 111
+.byte 111
+.byte 116
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.439:
+.byte 83
+.byte 113
+.byte 117
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 111
+.byte 111
+.byte 116
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.434:
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 115
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 115
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.433:
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 94
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.432:
+.byte 65
+.byte 110
+.byte 111
+.byte 109
+.byte 97
+.byte 108
+.byte 111
+.byte 117
+.byte 115
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 73
+.byte 110
+.byte 116
+.byte 101
+.byte 103
+.byte 101
+.byte 114
+.byte 32
+.byte 60
+.byte 32
+.byte 0
+.align 0
+L.392:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 100
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.370:
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 40
+.byte 88
+.byte 41
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 110
+.byte 45
+.byte 109
+.byte 111
+.byte 110
+.byte 111
+.byte 116
+.byte 111
+.byte 110
+.byte 105
+.byte 99
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 88
+.byte 32
+.byte 110
+.byte 101
+.byte 97
+.byte 114
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.369:
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 32
+.byte 104
+.byte 97
+.byte 115
+.byte 32
+.byte 112
+.byte 97
+.byte 115
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 97
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 77
+.byte 111
+.byte 110
+.byte 111
+.byte 116
+.byte 111
+.byte 110
+.byte 105
+.byte 99
+.byte 105
+.byte 116
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.352:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 32
+.byte 109
+.byte 111
+.byte 110
+.byte 111
+.byte 116
+.byte 111
+.byte 110
+.byte 105
+.byte 99
+.byte 105
+.byte 116
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.341:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 105
+.byte 102
+.byte 32
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 40
+.byte 88
+.byte 32
+.byte 42
+.byte 32
+.byte 88
+.byte 41
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 88
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 73
+.byte 110
+.byte 116
+.byte 101
+.byte 103
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 88
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.336:
+.byte 83
+.byte 113
+.byte 117
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 111
+.byte 111
+.byte 116
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 48
+.byte 46
+.byte 48
+.byte 44
+.byte 32
+.byte 45
+.byte 48
+.byte 46
+.byte 48
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 49
+.byte 46
+.byte 48
+.byte 32
+.byte 119
+.byte 114
+.byte 111
+.byte 110
+.byte 103
+.byte 0
+.align 0
+L.334:
+.byte 10
+.byte 82
+.byte 117
+.byte 110
+.byte 110
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 115
+.byte 113
+.byte 117
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 111
+.byte 111
+.byte 116
+.byte 40
+.byte 120
+.byte 41
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.333:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 78
+.byte 111
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 117
+.byte 114
+.byte 101
+.byte 115
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 105
+.byte 110
+.byte 116
+.byte 101
+.byte 103
+.byte 101
+.byte 114
+.byte 32
+.byte 112
+.byte 97
+.byte 105
+.byte 114
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.332:
+.byte 88
+.byte 32
+.byte 42
+.byte 32
+.byte 89
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 89
+.byte 32
+.byte 42
+.byte 32
+.byte 88
+.byte 32
+.byte 116
+.byte 114
+.byte 105
+.byte 97
+.byte 108
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 3
+L.323:
+.word 0x40080000
+.word 0x0
+.align 0
+L.322:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 111
+.byte 110
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 114
+.byte 97
+.byte 110
+.byte 100
+.byte 111
+.byte 109
+.byte 32
+.byte 112
+.byte 97
+.byte 105
+.byte 114
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.321:
+.byte 68
+.byte 111
+.byte 101
+.byte 115
+.byte 32
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 109
+.byte 117
+.byte 116
+.byte 101
+.byte 63
+.byte 32
+.byte 32
+.byte 0
+.align 0
+L.318:
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 40
+.byte 115
+.byte 41
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 103
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 117
+.byte 114
+.byte 101
+.byte 40
+.byte 115
+.byte 41
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 10
+.byte 40
+.byte 110
+.byte 111
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 97
+.byte 98
+.byte 111
+.byte 118
+.byte 101
+.byte 41
+.byte 32
+.byte 99
+.byte 111
+.byte 117
+.byte 110
+.byte 116
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 111
+.byte 110
+.byte 101
+.byte 32
+.byte 102
+.byte 108
+.byte 97
+.byte 119
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 102
+.byte 105
+.byte 110
+.byte 97
+.byte 108
+.byte 32
+.byte 116
+.byte 97
+.byte 108
+.byte 108
+.byte 121
+.byte 32
+.byte 98
+.byte 101
+.byte 108
+.byte 111
+.byte 119
+.byte 0
+.align 0
+L.316:
+.byte 83
+.byte 116
+.byte 105
+.byte 99
+.byte 107
+.byte 121
+.byte 32
+.byte 98
+.byte 105
+.byte 116
+.byte 32
+.byte 117
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 105
+.byte 110
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.315:
+.byte 83
+.byte 116
+.byte 105
+.byte 99
+.byte 107
+.byte 121
+.byte 32
+.byte 98
+.byte 105
+.byte 116
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 97
+.byte 114
+.byte 101
+.byte 110
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 117
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.298:
+.byte 67
+.byte 104
+.byte 101
+.byte 99
+.byte 107
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 115
+.byte 116
+.byte 105
+.byte 99
+.byte 107
+.byte 121
+.byte 32
+.byte 98
+.byte 105
+.byte 116
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.295:
+.byte 40
+.byte 88
+.byte 32
+.byte 45
+.byte 32
+.byte 89
+.byte 41
+.byte 32
+.byte 43
+.byte 32
+.byte 40
+.byte 89
+.byte 32
+.byte 45
+.byte 32
+.byte 88
+.byte 41
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 110
+.byte 32
+.byte 122
+.byte 101
+.byte 114
+.byte 111
+.byte 33
+.byte 10
+.byte 0
+.align 0
+L.292:
+.byte 65
+.byte 100
+.byte 100
+.byte 105
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 47
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 110
+.byte 101
+.byte 105
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.291:
+.byte 65
+.byte 100
+.byte 100
+.byte 47
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 0
+.align 0
+L.288:
+.byte 65
+.byte 100
+.byte 100
+.byte 105
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 47
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.281:
+.byte 65
+.byte 100
+.byte 100
+.byte 47
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.276:
+.byte 73
+.byte 110
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 108
+.byte 101
+.byte 116
+.byte 101
+.byte 32
+.byte 99
+.byte 97
+.byte 114
+.byte 114
+.byte 121
+.byte 45
+.byte 112
+.byte 114
+.byte 111
+.byte 112
+.byte 97
+.byte 103
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 65
+.byte 100
+.byte 100
+.byte 105
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 0
+.align 0
+L.272:
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 42
+.byte 32
+.byte 40
+.byte 32
+.byte 49
+.byte 32
+.byte 47
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 41
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 49
+.byte 0
+.align 0
+L.270:
+.byte 47
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 101
+.byte 105
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.267:
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.264:
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 0
+.align 0
+L.261:
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.256:
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 0
+.align 0
+L.253:
+.byte 42
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 101
+.byte 105
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.252:
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.249:
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.239:
+.byte 88
+.byte 32
+.byte 42
+.byte 32
+.byte 40
+.byte 49
+.byte 47
+.byte 88
+.byte 41
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 49
+.byte 0
+.align 0
+L.220:
+.byte 67
+.byte 104
+.byte 101
+.byte 99
+.byte 107
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 111
+.byte 110
+.byte 32
+.byte 109
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 121
+.byte 44
+.byte 32
+.byte 100
+.byte 105
+.byte 118
+.byte 105
+.byte 100
+.byte 101
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 97
+.byte 100
+.byte 100
+.byte 47
+.byte 115
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.219:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 42
+.byte 44
+.byte 32
+.byte 47
+.byte 44
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 45
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 104
+.byte 97
+.byte 118
+.byte 101
+.byte 32
+.byte 103
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 44
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 121
+.byte 32
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.216:
+.byte 32
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 32
+.byte 32
+.byte 105
+.byte 102
+.byte 32
+.byte 40
+.byte 88
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 49
+.byte 46
+.byte 48
+.byte 41
+.byte 32
+.byte 123
+.byte 46
+.byte 46
+.byte 46
+.byte 46
+.byte 46
+.byte 125
+.byte 32
+.byte 101
+.byte 108
+.byte 115
+.byte 101
+.byte 32
+.byte 123
+.byte 46
+.byte 46
+.byte 46
+.byte 47
+.byte 40
+.byte 88
+.byte 45
+.byte 49
+.byte 46
+.byte 48
+.byte 41
+.byte 46
+.byte 46
+.byte 46
+.byte 125
+.byte 10
+.byte 0
+.align 0
+L.215:
+.byte 32
+.byte 32
+.byte 115
+.byte 117
+.byte 99
+.byte 104
+.byte 32
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 97
+.byte 117
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 97
+.byte 103
+.byte 97
+.byte 105
+.byte 110
+.byte 115
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 122
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 97
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.214:
+.byte 32
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 121
+.byte 105
+.byte 101
+.byte 108
+.byte 100
+.byte 115
+.byte 32
+.byte 32
+.byte 40
+.byte 49
+.byte 45
+.byte 85
+.byte 49
+.byte 41
+.byte 32
+.byte 45
+.byte 32
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 32
+.byte 44
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 101
+.byte 98
+.byte 121
+.byte 32
+.byte 118
+.byte 105
+.byte 116
+.byte 105
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 10
+.byte 0
+.align 0
+L.213:
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 115
+.byte 32
+.byte 32
+.byte 40
+.byte 49
+.byte 45
+.byte 85
+.byte 49
+.byte 41
+.byte 32
+.byte 60
+.byte 32
+.byte 49
+.byte 32
+.byte 32
+.byte 97
+.byte 108
+.byte 116
+.byte 104
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 10
+.byte 0
+.align 0
+L.210:
+.byte 45
+.byte 32
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 115
+.byte 32
+.byte 71
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 68
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 44
+.byte 32
+.byte 115
+.byte 111
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 99
+.byte 101
+.byte 108
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 111
+.byte 98
+.byte 115
+.byte 99
+.byte 117
+.byte 114
+.byte 101
+.byte 100
+.byte 0
+.align 0
+L.205:
+.byte 42
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 47
+.byte 111
+.byte 114
+.byte 32
+.byte 47
+.byte 32
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 109
+.byte 97
+.byte 110
+.byte 121
+.byte 32
+.byte 108
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 119
+.byte 114
+.byte 111
+.byte 110
+.byte 103
+.byte 0
+.align 0
+L.201:
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 49
+.byte 47
+.byte 49
+.byte 46
+.byte 48
+.byte 48
+.byte 48
+.byte 46
+.byte 46
+.byte 49
+.byte 32
+.byte 62
+.byte 61
+.byte 32
+.byte 49
+.byte 0
+.align 0
+L.199:
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 71
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 68
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 44
+.byte 32
+.byte 115
+.byte 111
+.byte 32
+.byte 88
+.byte 47
+.byte 49
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 88
+.byte 0
+.align 0
+L.194:
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 71
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 68
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 44
+.byte 32
+.byte 115
+.byte 111
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 32
+.byte 101
+.byte 120
+.byte 99
+.byte 101
+.byte 101
+.byte 100
+.byte 32
+.byte 49
+.byte 32
+.byte 117
+.byte 108
+.byte 112
+.byte 10
+.byte 111
+.byte 114
+.byte 32
+.byte 32
+.byte 49
+.byte 47
+.byte 51
+.byte 32
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 32
+.byte 51
+.byte 47
+.byte 57
+.byte 32
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 32
+.byte 57
+.byte 47
+.byte 50
+.byte 55
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 97
+.byte 103
+.byte 114
+.byte 101
+.byte 101
+.byte 0
+.align 0
+L.190:
+.byte 42
+.byte 32
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 109
+.byte 97
+.byte 110
+.byte 121
+.byte 32
+.byte 102
+.byte 105
+.byte 110
+.byte 97
+.byte 108
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 119
+.byte 114
+.byte 111
+.byte 110
+.byte 103
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.188:
+.byte 42
+.byte 32
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 71
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 68
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 44
+.byte 32
+.byte 115
+.byte 111
+.byte 32
+.byte 49
+.byte 42
+.byte 88
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 88
+.byte 0
+.align 0
+L.185:
+.byte 10
+.byte 67
+.byte 104
+.byte 101
+.byte 99
+.byte 107
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 103
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 42
+.byte 44
+.byte 32
+.byte 47
+.byte 44
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 45
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.184:
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 109
+.byte 97
+.byte 108
+.byte 105
+.byte 122
+.byte 101
+.byte 100
+.byte 44
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 98
+.byte 101
+.byte 46
+.byte 0
+.align 0
+L.179:
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 109
+.byte 97
+.byte 108
+.byte 105
+.byte 122
+.byte 101
+.byte 100
+.byte 32
+.byte 88
+.byte 61
+.byte 89
+.byte 44
+.byte 88
+.byte 43
+.byte 90
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 89
+.byte 43
+.byte 90
+.byte 33
+.byte 0
+.align 0
+L.175:
+.byte 114
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 108
+.byte 121
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 101
+.byte 120
+.byte 116
+.byte 114
+.byte 97
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 105
+.byte 102
+.byte 105
+.byte 99
+.byte 97
+.byte 110
+.byte 116
+.byte 32
+.byte 100
+.byte 101
+.byte 99
+.byte 105
+.byte 109
+.byte 97
+.byte 108
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.174:
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 101
+.byte 108
+.byte 121
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 97
+.byte 98
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 101
+.byte 120
+.byte 116
+.byte 114
+.byte 97
+.byte 32
+.byte 66
+.byte 45
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 44
+.byte 32
+.byte 105
+.byte 46
+.byte 101
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.173:
+.byte 83
+.byte 111
+.byte 109
+.byte 101
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 101
+.byte 120
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 101
+.byte 120
+.byte 116
+.byte 114
+.byte 97
+.byte 10
+.byte 0
+.align 0
+L.167:
+.byte 111
+.byte 102
+.byte 32
+.byte 97
+.byte 110
+.byte 10
+.byte 101
+.byte 120
+.byte 116
+.byte 114
+.byte 97
+.byte 45
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 0
+.align 0
+L.166:
+.byte 90
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 90
+.byte 50
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 0
+.align 0
+L.165:
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 101
+.byte 120
+.byte 97
+.byte 99
+.byte 116
+.byte 32
+.byte 114
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 97
+.byte 108
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 97
+.byte 32
+.byte 114
+.byte 101
+.byte 115
+.byte 117
+.byte 108
+.byte 116
+.byte 10
+.byte 0
+.align 0
+L.164:
+.byte 66
+.byte 101
+.byte 99
+.byte 97
+.byte 117
+.byte 115
+.byte 101
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 117
+.byte 110
+.byte 117
+.byte 115
+.byte 117
+.byte 97
+.byte 108
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 102
+.byte 0
+.align 0
+L.160:
+.byte 9
+.byte 85
+.byte 50
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 90
+.byte 50
+.byte 32
+.byte 45
+.byte 32
+.byte 85
+.byte 50
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.159:
+.byte 9
+.byte 85
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 90
+.byte 49
+.byte 32
+.byte 45
+.byte 32
+.byte 85
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.158:
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 0
+.align 0
+L.157:
+.byte 0
+.align 0
+L.150:
+.byte 84
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 102
+.byte 101
+.byte 97
+.byte 116
+.byte 117
+.byte 114
+.byte 101
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 102
+.byte 117
+.byte 114
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.145:
+.byte 80
+.byte 111
+.byte 115
+.byte 115
+.byte 105
+.byte 98
+.byte 108
+.byte 121
+.byte 32
+.byte 115
+.byte 111
+.byte 109
+.byte 101
+.byte 32
+.byte 112
+.byte 97
+.byte 114
+.byte 116
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 0
+.align 0
+L.144:
+.byte 98
+.byte 121
+.byte 32
+.byte 101
+.byte 120
+.byte 116
+.byte 114
+.byte 97
+.byte 45
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 101
+.byte 32
+.byte 101
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 101
+.byte 120
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.143:
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 115
+.byte 121
+.byte 109
+.byte 112
+.byte 116
+.byte 111
+.byte 109
+.byte 115
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 105
+.byte 110
+.byte 99
+.byte 111
+.byte 110
+.byte 115
+.byte 105
+.byte 115
+.byte 116
+.byte 101
+.byte 110
+.byte 99
+.byte 105
+.byte 101
+.byte 115
+.byte 32
+.byte 105
+.byte 110
+.byte 116
+.byte 114
+.byte 111
+.byte 100
+.byte 117
+.byte 99
+.byte 101
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.142:
+.byte 114
+.byte 101
+.byte 115
+.byte 112
+.byte 101
+.byte 99
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 108
+.byte 121
+.byte 32
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 44
+.byte 10
+.byte 0
+.align 0
+L.141:
+.byte 68
+.byte 105
+.byte 115
+.byte 97
+.byte 103
+.byte 114
+.byte 101
+.byte 101
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 97
+.byte 109
+.byte 111
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 115
+.byte 32
+.byte 88
+.byte 49
+.byte 44
+.byte 32
+.byte 89
+.byte 49
+.byte 44
+.byte 32
+.byte 90
+.byte 49
+.byte 44
+.byte 10
+.byte 0
+.align 0
+L.119:
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 119
+.byte 111
+.byte 114
+.byte 115
+.byte 101
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 110
+.byte 32
+.byte 53
+.byte 32
+.byte 100
+.byte 101
+.byte 99
+.byte 105
+.byte 109
+.byte 97
+.byte 108
+.byte 32
+.byte 102
+.byte 105
+.byte 103
+.byte 117
+.byte 114
+.byte 101
+.byte 115
+.byte 32
+.byte 32
+.byte 0
+.align 0
+L.117:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 105
+.byte 102
+.byte 105
+.byte 99
+.byte 97
+.byte 110
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 37
+.byte 102
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.116:
+.byte 108
+.byte 111
+.byte 103
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 105
+.byte 99
+.byte 32
+.byte 101
+.byte 110
+.byte 99
+.byte 111
+.byte 100
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 104
+.byte 97
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 99
+.byte 104
+.byte 97
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 101
+.byte 114
+.byte 105
+.byte 122
+.byte 101
+.byte 100
+.byte 32
+.byte 115
+.byte 111
+.byte 108
+.byte 101
+.byte 108
+.byte 121
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 85
+.byte 49
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.113:
+.byte 111
+.byte 102
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 105
+.byte 102
+.byte 105
+.byte 99
+.byte 97
+.byte 110
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 98
+.byte 117
+.byte 116
+.byte 44
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 105
+.byte 116
+.byte 115
+.byte 101
+.byte 108
+.byte 102
+.byte 44
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 109
+.byte 105
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 102
+.byte 108
+.byte 97
+.byte 119
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.112:
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 99
+.byte 104
+.byte 97
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 101
+.byte 114
+.byte 105
+.byte 122
+.byte 101
+.byte 100
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 97
+.byte 110
+.byte 32
+.byte 73
+.byte 110
+.byte 116
+.byte 101
+.byte 103
+.byte 101
+.byte 114
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 10
+.byte 0
+.align 0
+L.99:
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 102
+.byte 117
+.byte 122
+.byte 122
+.byte 121
+.byte 44
+.byte 88
+.byte 61
+.byte 49
+.byte 32
+.byte 98
+.byte 117
+.byte 116
+.byte 32
+.byte 88
+.byte 45
+.byte 49
+.byte 47
+.byte 50
+.byte 45
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 0
+.align 0
+L.95:
+.byte 40
+.byte 49
+.byte 45
+.byte 85
+.byte 49
+.byte 41
+.byte 45
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 60
+.byte 32
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 70
+.byte 65
+.byte 76
+.byte 83
+.byte 69
+.byte 44
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 46
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 115
+.byte 63
+.byte 0
+.align 3
+L.93:
+.word 0x40240000
+.word 0x0
+.align 0
+L.88:
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 103
+.byte 111
+.byte 111
+.byte 100
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 50
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 49
+.byte 48
+.byte 0
+.align 0
+L.84:
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 98
+.byte 105
+.byte 103
+.byte 58
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 111
+.byte 102
+.byte 102
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 98
+.byte 108
+.byte 101
+.byte 109
+.byte 115
+.byte 0
+.align 0
+L.82:
+.byte 77
+.byte 89
+.byte 83
+.byte 84
+.byte 69
+.byte 82
+.byte 89
+.byte 58
+.byte 32
+.byte 114
+.byte 101
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.81:
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 105
+.byte 114
+.byte 109
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 3
+L.78:
+.word 0x3f847ae1
+.word 0x47ae147b
+.align 0
+L.77:
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 98
+.byte 101
+.byte 116
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 99
+.byte 108
+.byte 111
+.byte 115
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 114
+.byte 101
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 115
+.byte 101
+.byte 112
+.byte 97
+.byte 114
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 85
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.76:
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 105
+.byte 114
+.byte 109
+.byte 115
+.byte 32
+.byte 99
+.byte 108
+.byte 111
+.byte 115
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 114
+.byte 101
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 115
+.byte 101
+.byte 112
+.byte 97
+.byte 114
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 85
+.byte 49
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.61:
+.byte 82
+.byte 101
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 114
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 10
+.byte 32
+.byte 0
+.align 0
+L.60:
+.byte 67
+.byte 108
+.byte 111
+.byte 115
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 114
+.byte 101
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 115
+.byte 101
+.byte 112
+.byte 97
+.byte 114
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 85
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 10
+.byte 0
+.align 0
+L.54:
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 102
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.45:
+.byte 83
+.byte 101
+.byte 97
+.byte 114
+.byte 99
+.byte 104
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.44:
+.byte 10
+.byte 0
+.align 0
+L.43:
+.byte 45
+.byte 49
+.byte 44
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 49
+.byte 47
+.byte 50
+.byte 44
+.byte 32
+.byte 49
+.byte 44
+.byte 32
+.byte 50
+.byte 44
+.byte 32
+.byte 51
+.byte 44
+.byte 32
+.byte 52
+.byte 44
+.byte 32
+.byte 53
+.byte 44
+.byte 32
+.byte 57
+.byte 44
+.byte 32
+.byte 50
+.byte 55
+.byte 44
+.byte 32
+.byte 51
+.byte 50
+.byte 32
+.byte 38
+.byte 32
+.byte 50
+.byte 52
+.byte 48
+.byte 32
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 79
+.byte 46
+.byte 75
+.byte 46
+.byte 10
+.byte 0
+.align 0
+L.38:
+.byte 53
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 52
+.byte 43
+.byte 49
+.byte 44
+.byte 32
+.byte 50
+.byte 52
+.byte 48
+.byte 47
+.byte 51
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 56
+.byte 48
+.byte 44
+.byte 32
+.byte 50
+.byte 52
+.byte 48
+.byte 47
+.byte 52
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 54
+.byte 48
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 50
+.byte 52
+.byte 48
+.byte 47
+.byte 53
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 52
+.byte 56
+.byte 0
+.align 0
+L.34:
+.byte 57
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 51
+.byte 42
+.byte 51
+.byte 44
+.byte 32
+.byte 50
+.byte 55
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 57
+.byte 42
+.byte 51
+.byte 44
+.byte 32
+.byte 51
+.byte 50
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 56
+.byte 42
+.byte 52
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 51
+.byte 50
+.byte 45
+.byte 50
+.byte 55
+.byte 45
+.byte 52
+.byte 45
+.byte 49
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 0
+.align 0
+L.30:
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 43
+.byte 32
+.byte 40
+.byte 45
+.byte 49
+.byte 41
+.byte 32
+.byte 43
+.byte 32
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 0
+.align 0
+L.26:
+.byte 45
+.byte 49
+.byte 43
+.byte 49
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 40
+.byte 45
+.byte 49
+.byte 41
+.byte 43
+.byte 97
+.byte 98
+.byte 115
+.byte 40
+.byte 49
+.byte 41
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 45
+.byte 49
+.byte 43
+.byte 40
+.byte 45
+.byte 49
+.byte 41
+.byte 42
+.byte 40
+.byte 45
+.byte 49
+.byte 41
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 0
+.align 0
+L.22:
+.byte 51
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 50
+.byte 43
+.byte 49
+.byte 44
+.byte 32
+.byte 52
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 51
+.byte 43
+.byte 49
+.byte 44
+.byte 32
+.byte 52
+.byte 43
+.byte 50
+.byte 42
+.byte 40
+.byte 45
+.byte 50
+.byte 41
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 52
+.byte 45
+.byte 51
+.byte 45
+.byte 49
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 0
+.align 3
+L.20:
+.word 0x3f50624d
+.word 0xd2f1a9fc
+.align 0
+L.19:
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 45
+.byte 48
+.byte 46
+.byte 48
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 78
+.byte 111
+.byte 110
+.byte 45
+.byte 122
+.byte 101
+.byte 114
+.byte 111
+.byte 33
+.byte 10
+.byte 0
+.align 0
+L.14:
+.byte 48
+.byte 43
+.byte 48
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 49
+.byte 45
+.byte 49
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 49
+.byte 32
+.byte 60
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 49
+.byte 43
+.byte 49
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 50
+.byte 0
+.align 0
+L.12:
+.byte 80
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 119
+.byte 32
+.byte 82
+.byte 85
+.byte 78
+.byte 78
+.byte 73
+.byte 78
+.byte 71
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 115
+.byte 32
+.byte 111
+.byte 110
+.byte 32
+.byte 115
+.byte 109
+.byte 97
+.byte 108
+.byte 108
+.byte 32
+.byte 105
+.byte 110
+.byte 116
+.byte 101
+.byte 103
+.byte 101
+.byte 114
+.byte 115
+.byte 58
+.byte 10
+.byte 0
+.align 3
+L.8:
+.word 0x3ff00000
+.word 0x0
+.align 3
+L.7:
+.word 0x0
+.word 0x0
+.align 0
+L.2:
+.byte 10
+.byte 42
+.byte 32
+.byte 42
+.byte 32
+.byte 42
+.byte 32
+.byte 70
+.byte 76
+.byte 79
+.byte 65
+.byte 84
+.byte 73
+.byte 78
+.byte 71
+.byte 45
+.byte 80
+.byte 79
+.byte 73
+.byte 78
+.byte 84
+.byte 32
+.byte 69
+.byte 82
+.byte 82
+.byte 79
+.byte 82
+.byte 32
+.byte 42
+.byte 32
+.byte 42
+.byte 32
+.byte 42
+.byte 10
+.byte 0
diff --git a/lcc/mips/irix/tst/sort.1bk b/lcc/mips/irix/tst/sort.1bk
new file mode 100755
index 0000000..380d529
--- /dev/null
+++ b/lcc/mips/irix/tst/sort.1bk
@@ -0,0 +1,20 @@
+exchange(1,9)
+exchange(3,7)
+exchange(5,6)
+exchange(0,5)
+exchange(0,3)
+exchange(0,0)
+exchange(1,2)
+exchange(6,6)
+exchange(8,9)
+exchange(7,8)
+-51
+-1
+0
+1
+3
+10
+18
+32
+567
+789
diff --git a/lcc/mips/irix/tst/sort.2bk b/lcc/mips/irix/tst/sort.2bk
new file mode 100755
index 0000000..27488a1
--- /dev/null
+++ b/lcc/mips/irix/tst/sort.2bk
@@ -0,0 +1,5 @@
+tst/sort.c:23: warning: missing return value
+tst/sort.c:30: warning: missing return value
+tst/sort.c:37: warning: missing return value
+tst/sort.c:41: warning: missing return value
+tst/sort.c:65: warning: missing return value
diff --git a/lcc/mips/irix/tst/sort.sbk b/lcc/mips/irix/tst/sort.sbk
new file mode 100755
index 0000000..57d33f6
--- /dev/null
+++ b/lcc/mips/irix/tst/sort.sbk
@@ -0,0 +1,308 @@
+.set reorder
+.globl in
+.data
+.align 2
+in:
+.word 0xa
+.word 0x20
+.word 0xffffffff
+.word 0x237
+.word 0x3
+.word 0x12
+.word 0x1
+.word 0xffffffcd
+.word 0x315
+.word 0x0
+.globl main
+.text
+.text
+.align 2
+.ent main
+main:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2000000,-8
+.cprestore 16
+sw $30,20($sp)
+sw $31,24($sp)
+la $4,in
+la $5,10
+jal sort
+move $30,$0
+b L.5
+L.2:
+sll $24,$30,2
+lw $4,in($24)
+jal putd
+la $4,10
+jal putchar
+L.3:
+la $30,1($30)
+L.5:
+move $24,$30
+la $15,10
+bltu $24,$15,L.2
+move $2,$0
+L.1:
+lw $25,16($sp)
+lw $30,20($sp)
+lw $31,24($sp)
+addu $sp,$sp,32
+j $31
+.end main
+.globl putd
+.text
+.align 2
+.ent putd
+putd:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2000000,-8
+.cprestore 16
+sw $30,20($sp)
+sw $31,24($sp)
+move $30,$4
+bge $30,$0,L.7
+la $4,45
+jal putchar
+negu $30,$30
+L.7:
+la $24,10
+div $24,$30,$24
+beq $24,$0,L.9
+la $24,10
+div $4,$30,$24
+jal putd
+L.9:
+la $24,10
+rem $24,$30,$24
+la $4,48($24)
+jal putchar
+move $2,$0
+L.6:
+lw $25,16($sp)
+lw $30,20($sp)
+lw $31,24($sp)
+addu $sp,$sp,32
+j $31
+.end putd
+.globl sort
+.text
+.align 2
+.ent sort
+sort:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+sw $4,24($sp)
+sw $5,28($sp)
+lw $24,0+24($sp)
+sw $24,xx
+move $4,$24
+move $5,$0
+lw $24,4+24($sp)
+subu $24,$24,1
+sw $24,4+24($sp)
+move $6,$24
+jal quick
+move $2,$0
+L.11:
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end sort
+.globl quick
+.text
+.align 2
+.ent quick
+quick:
+.frame $sp,40,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-40
+.mask 0xc2e00000,-4
+sw $21,16($sp)
+sw $22,20($sp)
+sw $23,24($sp)
+.cprestore 28
+sw $30,32($sp)
+sw $31,36($sp)
+move $30,$4
+move $23,$5
+move $22,$6
+blt $23,$22,L.13
+b L.12
+L.13:
+move $4,$30
+move $5,$23
+move $6,$22
+jal partition
+move $21,$2
+move $4,$30
+move $5,$23
+subu $6,$21,1
+jal quick
+move $4,$30
+la $5,1($21)
+move $6,$22
+jal quick
+move $2,$0
+L.12:
+lw $21,16($sp)
+lw $22,20($sp)
+lw $23,24($sp)
+lw $25,28($sp)
+lw $30,32($sp)
+lw $31,36($sp)
+addu $sp,$sp,40
+j $31
+.end quick
+.globl partition
+.text
+.align 2
+.ent partition
+partition:
+.frame $sp,48,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-48
+.mask 0xc2f00000,-8
+sw $20,16($sp)
+sw $21,20($sp)
+sw $22,24($sp)
+sw $23,28($sp)
+.cprestore 32
+sw $30,36($sp)
+sw $31,40($sp)
+move $30,$4
+move $23,$5
+move $22,$6
+la $22,1($22)
+move $20,$23
+sll $24,$20,2
+addu $24,$24,$30
+lw $21,($24)
+b L.17
+L.16:
+la $23,1($23)
+b L.20
+L.19:
+la $23,1($23)
+L.20:
+sll $24,$23,2
+addu $24,$24,$30
+lw $24,($24)
+blt $24,$21,L.19
+subu $22,$22,1
+b L.23
+L.22:
+subu $22,$22,1
+L.23:
+sll $24,$22,2
+addu $24,$24,$30
+lw $24,($24)
+bgt $24,$21,L.22
+bge $23,$22,L.25
+sll $24,$23,2
+addu $4,$24,$30
+sll $24,$22,2
+addu $5,$24,$30
+jal exchange
+L.25:
+L.17:
+blt $23,$22,L.16
+sll $24,$20,2
+addu $4,$24,$30
+sll $24,$22,2
+addu $5,$24,$30
+jal exchange
+move $2,$22
+L.15:
+lw $20,16($sp)
+lw $21,20($sp)
+lw $22,24($sp)
+lw $23,28($sp)
+lw $25,32($sp)
+lw $30,36($sp)
+lw $31,40($sp)
+addu $sp,$sp,48
+j $31
+.end partition
+.globl exchange
+.text
+.align 2
+.ent exchange
+exchange:
+.frame $sp,40,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-40
+.mask 0xc2800000,-12
+sw $23,16($sp)
+.cprestore 20
+sw $30,24($sp)
+sw $31,28($sp)
+move $30,$4
+move $23,$5
+la $4,L.28
+lw $24,xx
+la $15,4
+move $14,$30
+subu $14,$14,$24
+div $5,$14,$15
+move $14,$23
+subu $24,$14,$24
+div $6,$24,$15
+jal printf
+lw $24,($30)
+sw $24,-4+40($sp)
+lw $24,($23)
+sw $24,($30)
+lw $24,-4+40($sp)
+sw $24,($23)
+move $2,$0
+L.27:
+lw $23,16($sp)
+lw $25,20($sp)
+lw $30,24($sp)
+lw $31,28($sp)
+addu $sp,$sp,40
+j $31
+.end exchange
+.globl xx
+.comm xx,4
+.rdata
+.align 0
+L.28:
+.byte 101
+.byte 120
+.byte 99
+.byte 104
+.byte 97
+.byte 110
+.byte 103
+.byte 101
+.byte 40
+.byte 37
+.byte 100
+.byte 44
+.byte 37
+.byte 100
+.byte 41
+.byte 10
+.byte 0
diff --git a/lcc/mips/irix/tst/spill.2bk b/lcc/mips/irix/tst/spill.2bk
new file mode 100755
index 0000000..f7e3521
--- /dev/null
+++ b/lcc/mips/irix/tst/spill.2bk
@@ -0,0 +1,6 @@
+tst/spill.c:1: warning: missing return value
+tst/spill.c:3: warning: missing return value
+tst/spill.c:5: warning: missing return value
+tst/spill.c:7: warning: missing return value
+tst/spill.c:9: warning: missing return value
+tst/spill.c:17: warning: missing return value
diff --git a/lcc/mips/irix/tst/spill.sbk b/lcc/mips/irix/tst/spill.sbk
new file mode 100755
index 0000000..5b9fb25
--- /dev/null
+++ b/lcc/mips/irix/tst/spill.sbk
@@ -0,0 +1,271 @@
+.set reorder
+.globl main
+.text
+.text
+.align 2
+.ent main
+main:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+move $2,$0
+L.1:
+j $31
+.end main
+.globl f
+.text
+.align 2
+.ent f
+f:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0x82000000,-12
+.cprestore 16
+sw $31,20($sp)
+sw $4,32($sp)
+jal f
+move $24,$2
+sw $24,-4+32($sp)
+jal f
+lw $15,-4+32($sp)
+addu $24,$15,$2
+sw $24,0+32($sp)
+move $2,$0
+L.2:
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,32
+j $31
+.end f
+.globl f2
+.text
+.align 2
+.ent f2
+f2:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2000000,-8
+.cprestore 16
+sw $30,20($sp)
+sw $31,24($sp)
+sw $4,32($sp)
+jal f
+move $24,$2
+sw $24,-4+32($sp)
+lw $15,0+32($sp)
+beq $15,$0,L.5
+jal f
+move $24,$2
+move $30,$24
+b L.6
+L.5:
+la $30,1
+L.6:
+lw $24,-4+32($sp)
+addu $24,$24,$30
+sw $24,0+32($sp)
+move $2,$0
+L.3:
+lw $25,16($sp)
+lw $30,20($sp)
+lw $31,24($sp)
+addu $sp,$sp,32
+j $31
+.end f2
+.globl f3
+.text
+.align 2
+.ent f3
+f3:
+.frame $sp,72,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-72
+.mask 0xc2ff0000,-16
+sw $16,16($sp)
+sw $17,20($sp)
+sw $18,24($sp)
+sw $19,28($sp)
+sw $20,32($sp)
+sw $21,36($sp)
+sw $22,40($sp)
+sw $23,44($sp)
+.cprestore 48
+sw $30,52($sp)
+sw $31,56($sp)
+sw $4,72($sp)
+sw $5,76($sp)
+move $30,$0
+move $23,$0
+move $22,$0
+move $21,$0
+move $20,$0
+move $19,$0
+move $18,$0
+move $17,$0
+move $16,$0
+sw $0,-4+72($sp)
+lw $24,4+72($sp)
+sw $24,-12+72($sp)
+la $15,4($24)
+sw $15,4+72($sp)
+lw $15,0+72($sp)
+beq $15,$0,L.9
+jal f
+move $24,$2
+sw $24,-8+72($sp)
+b L.10
+L.9:
+sw $0,-8+72($sp)
+L.10:
+lw $24,-8+72($sp)
+lw $15,-12+72($sp)
+sw $24,($15)
+move $2,$0
+L.7:
+lw $16,16($sp)
+lw $17,20($sp)
+lw $18,24($sp)
+lw $19,28($sp)
+lw $20,32($sp)
+lw $21,36($sp)
+lw $22,40($sp)
+lw $23,44($sp)
+lw $25,48($sp)
+lw $30,52($sp)
+lw $31,56($sp)
+addu $sp,$sp,72
+j $31
+.end f3
+.globl f4
+.text
+.align 2
+.ent f4
+f4:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0x40fc0000,-8
+sw $18,0($sp)
+sw $19,4($sp)
+sw $20,8($sp)
+sw $21,12($sp)
+sw $22,16($sp)
+sw $23,20($sp)
+sw $30,24($sp)
+move $30,$0
+move $23,$0
+move $22,$0
+move $21,$0
+move $20,$0
+move $19,$0
+lw $24,i
+sll $15,$24,3
+l.d $f18,a($15)
+l.d $f16,b($15)
+l.d $f10,L.15
+add.d $f8,$f18,$f16
+c.eq.d $f8,$f10; bc1t L.13
+beq $24,$0,L.13
+sub.d $f18,$f18,$f16
+c.eq.d $f18,$f10; bc1t L.13
+la $18,1
+b L.14
+L.13:
+move $18,$0
+L.14:
+sw $18,i
+move $2,$0
+L.11:
+lw $18,0($sp)
+lw $19,4($sp)
+lw $20,8($sp)
+lw $21,12($sp)
+lw $22,16($sp)
+lw $23,20($sp)
+lw $30,24($sp)
+addu $sp,$sp,32
+j $31
+.end f4
+.globl f5
+.text
+.align 2
+.ent f5
+f5:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+lw $24,k
+lw $15,m
+lw $14,A
+mul $13,$24,$15
+sll $13,$13,3
+addu $13,$13,$14
+lw $12,j
+mul $15,$12,$15
+sll $15,$15,3
+addu $15,$15,$14
+lw $14,n
+lw $11,B
+mul $24,$24,$14
+sll $24,$24,3
+addu $24,$24,$11
+mul $14,$12,$14
+sll $14,$14,3
+addu $14,$14,$11
+l.d $f18,($13)
+l.d $f16,($15)
+mul.d $f18,$f18,$f16
+l.d $f16,($24)
+l.d $f10,($14)
+mul.d $f16,$f16,$f10
+add.d $f18,$f18,$f16
+s.d $f18,x
+l.d $f18,($13)
+l.d $f16,($14)
+mul.d $f18,$f18,$f16
+l.d $f16,($24)
+l.d $f10,($15)
+mul.d $f16,$f16,$f10
+sub.d $f18,$f18,$f16
+s.d $f18,x
+move $2,$0
+L.16:
+j $31
+.end f5
+.globl x
+.comm x,8
+.globl B
+.comm B,4
+.globl A
+.comm A,4
+.globl n
+.comm n,4
+.globl m
+.comm m,4
+.globl k
+.comm k,4
+.globl j
+.comm j,4
+.globl i
+.comm i,4
+.globl b
+.comm b,80
+.globl a
+.comm a,80
+.rdata
+.align 3
+L.15:
+.word 0x0
+.word 0x0
diff --git a/lcc/mips/irix/tst/stdarg.1bk b/lcc/mips/irix/tst/stdarg.1bk
new file mode 100755
index 0000000..097aef7
--- /dev/null
+++ b/lcc/mips/irix/tst/stdarg.1bk
@@ -0,0 +1,6 @@
+test 1
+test 2
+test 3
+test 4
+test 5.000000
+{1 2 3 4} {1 2 3 4} {1 2 3 4} {1 2 3 4} {1 2 3 4} {1 2 3 4}
diff --git a/lcc/mips/irix/tst/stdarg.2bk b/lcc/mips/irix/tst/stdarg.2bk
new file mode 100755
index 0000000..a832cf9
--- /dev/null
+++ b/lcc/mips/irix/tst/stdarg.2bk
@@ -0,0 +1 @@
+tst/stdarg.c:51: warning: missing return value
diff --git a/lcc/mips/irix/tst/stdarg.sbk b/lcc/mips/irix/tst/stdarg.sbk
new file mode 100755
index 0000000..556c8b2
--- /dev/null
+++ b/lcc/mips/irix/tst/stdarg.sbk
@@ -0,0 +1,395 @@
+.set reorder
+.globl x
+.data
+.align 2
+x:
+.word 0x1
+.word 0x2
+.word 0x3
+.word 0x4
+.globl main
+.text
+.text
+.align 2
+.ent main
+main:
+.frame $sp,112,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-112
+.mask 0x82000000,-8
+.cprestore 100
+sw $31,104($sp)
+la $4,L.2
+jal print
+la $4,L.3
+la $5,L.4
+jal print
+la $4,L.5
+la $5,3
+la $6,10
+jal print
+la $4,L.6
+la $5,L.7
+la $6,L.8
+la $7,4
+la $24,10
+sw $24,16($sp)
+jal print
+la $4,L.9
+la $5,L.7
+la $6,L.8
+l.d $f18,L.10
+s.d $f18,16($sp)
+la $24,10
+sw $24,24($sp)
+jal print
+la $4,L.11
+la $24,x
+move $8,$24
+lw $3,0($8)
+lw $9,4($8)
+sw $3,4($29)
+sw $9,8($29)
+lw $3,8($8)
+lw $9,12($8)
+sw $3,12($29)
+sw $9,16($29)
+lw $5,4($sp)
+lw $6,8($sp)
+lw $7,12($sp)
+move $8,$24
+lw $3,0($8)
+lw $9,4($8)
+sw $3,20($29)
+sw $9,24($29)
+lw $3,8($8)
+lw $9,12($8)
+sw $3,28($29)
+sw $9,32($29)
+move $8,$24
+lw $3,0($8)
+lw $9,4($8)
+sw $3,36($29)
+sw $9,40($29)
+lw $3,8($8)
+lw $9,12($8)
+sw $3,44($29)
+sw $9,48($29)
+move $8,$24
+lw $3,0($8)
+lw $9,4($8)
+sw $3,52($29)
+sw $9,56($29)
+lw $3,8($8)
+lw $9,12($8)
+sw $3,60($29)
+sw $9,64($29)
+move $8,$24
+lw $3,0($8)
+lw $9,4($8)
+sw $3,68($29)
+sw $9,72($29)
+lw $3,8($8)
+lw $9,12($8)
+sw $3,76($29)
+sw $9,80($29)
+move $8,$24
+lw $3,0($8)
+lw $9,4($8)
+sw $3,84($29)
+sw $9,88($29)
+lw $3,8($8)
+lw $9,12($8)
+sw $3,92($29)
+sw $9,96($29)
+jal print
+move $2,$0
+L.1:
+lw $25,100($sp)
+lw $31,104($sp)
+addu $sp,$sp,112
+j $31
+.end main
+.globl print
+.text
+.align 2
+.ent print
+print:
+.frame $sp,56,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-56
+.mask 0xc2800000,-24
+sw $23,20($sp)
+.cprestore 24
+sw $30,28($sp)
+sw $31,32($sp)
+sw $4,56($sp)
+sw $5,60($sp)
+sw $6,64($sp)
+sw $7,68($sp)
+la $30,4+56($sp)
+b L.18
+L.15:
+lw $24,0+56($sp)
+lb $24,($24)
+la $15,37
+bne $24,$15,L.19
+lw $24,0+56($sp)
+la $24,1($24)
+sw $24,0+56($sp)
+lb $23,($24)
+la $24,115
+beq $23,$24,L.35
+bgt $23,$24,L.40
+L.39:
+la $24,98
+blt $23,$24,L.21
+la $24,102
+bgt $23,$24,L.21
+sll $24,$23,2
+lw $24,L.41-392($24)
+.cpadd $24
+j $24
+.rdata
+.align 2
+L.41:
+.gpword L.24
+.gpword L.29
+.gpword L.31
+.gpword L.21
+.gpword L.37
+.text
+L.40:
+la $24,119
+beq $23,$24,L.33
+b L.21
+L.24:
+la $24,16($30)
+move $30,$24
+la $15,-16+56($sp)
+la $8,-16($24)
+lw $3,0($8)
+lw $9,4($8)
+sw $3,0($15)
+sw $9,4($15)
+lw $3,8($8)
+lw $9,12($8)
+sw $3,8($15)
+sw $9,12($15)
+la $4,L.25
+lw $5,-16+56($sp)
+lw $6,-12+56($sp)
+lw $7,-8+56($sp)
+lw $24,-4+56($sp)
+sw $24,16($sp)
+jal printf
+b L.20
+L.29:
+la $4,L.30
+la $24,4($30)
+move $30,$24
+lb $5,-1($24)
+jal printf
+b L.20
+L.31:
+la $4,L.32
+la $24,4($30)
+move $30,$24
+lw $5,-4($24)
+jal printf
+b L.20
+L.33:
+la $4,L.34
+la $24,4($30)
+move $30,$24
+lh $5,-2($24)
+jal printf
+b L.20
+L.35:
+la $4,L.36
+la $24,4($30)
+move $30,$24
+lw $5,-4($24)
+jal printf
+b L.20
+L.37:
+la $4,L.38
+move $24,$30
+la $24,15($24)
+and $24,$24,0xfffffff8
+move $30,$24
+l.d $f18,-8($24)
+mfc1.d $6,$f18
+jal printf
+b L.20
+L.21:
+la $4,L.30
+lw $24,0+56($sp)
+lb $5,($24)
+jal printf
+b L.20
+L.19:
+la $4,L.30
+lw $24,0+56($sp)
+lb $5,($24)
+jal printf
+L.20:
+L.16:
+lw $24,0+56($sp)
+la $24,1($24)
+sw $24,0+56($sp)
+L.18:
+lw $24,0+56($sp)
+lb $24,($24)
+bne $24,$0,L.15
+move $2,$0
+L.12:
+lw $23,20($sp)
+lw $25,24($sp)
+lw $30,28($sp)
+lw $31,32($sp)
+addu $sp,$sp,56
+j $31
+.end print
+.rdata
+.align 0
+L.38:
+.byte 37
+.byte 102
+.byte 0
+.align 0
+L.36:
+.byte 37
+.byte 115
+.byte 0
+.align 0
+L.34:
+.byte 37
+.byte 120
+.byte 0
+.align 0
+L.32:
+.byte 37
+.byte 100
+.byte 0
+.align 0
+L.30:
+.byte 37
+.byte 99
+.byte 0
+.align 0
+L.25:
+.byte 123
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 125
+.byte 0
+.align 0
+L.11:
+.byte 37
+.byte 98
+.byte 32
+.byte 37
+.byte 98
+.byte 32
+.byte 37
+.byte 98
+.byte 32
+.byte 37
+.byte 98
+.byte 32
+.byte 37
+.byte 98
+.byte 32
+.byte 37
+.byte 98
+.byte 10
+.byte 0
+.align 3
+L.10:
+.word 0x40140000
+.word 0x0
+.align 0
+L.9:
+.byte 37
+.byte 115
+.byte 37
+.byte 115
+.byte 32
+.byte 37
+.byte 102
+.byte 37
+.byte 99
+.byte 0
+.align 0
+L.8:
+.byte 115
+.byte 116
+.byte 0
+.align 0
+L.7:
+.byte 116
+.byte 101
+.byte 0
+.align 0
+L.6:
+.byte 37
+.byte 115
+.byte 37
+.byte 115
+.byte 32
+.byte 37
+.byte 119
+.byte 37
+.byte 99
+.byte 0
+.align 0
+L.5:
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 37
+.byte 100
+.byte 37
+.byte 99
+.byte 0
+.align 0
+L.4:
+.byte 50
+.byte 0
+.align 0
+L.3:
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.2:
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 49
+.byte 10
+.byte 0
diff --git a/lcc/mips/irix/tst/struct.1bk b/lcc/mips/irix/tst/struct.1bk
new file mode 100755
index 0000000..2358779
--- /dev/null
+++ b/lcc/mips/irix/tst/struct.1bk
@@ -0,0 +1,5 @@
+(-1,-1) is not within [10,10; 310,310]
+(1,1) is not within [10,10; 310,310]
+(20,300) is within [10,10; 310,310]
+(500,400) is not within [10,10; 310,310]
+ab
diff --git a/lcc/mips/irix/tst/struct.2bk b/lcc/mips/irix/tst/struct.2bk
new file mode 100755
index 0000000..8a01bb1
--- /dev/null
+++ b/lcc/mips/irix/tst/struct.2bk
@@ -0,0 +1,2 @@
+tst/struct.c:49: warning: missing return value
+tst/struct.c:68: warning: missing return value
diff --git a/lcc/mips/irix/tst/struct.sbk b/lcc/mips/irix/tst/struct.sbk
new file mode 100755
index 0000000..0eaa438
--- /dev/null
+++ b/lcc/mips/irix/tst/struct.sbk
@@ -0,0 +1,485 @@
+.set reorder
+.globl addpoint
+.text
+.text
+.align 2
+.ent addpoint
+addpoint:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+sw $5,4($sp)
+sw $6,8($sp)
+sw $7,12($sp)
+lw $24,4+0($sp)
+lw $15,12+0($sp)
+addu $24,$24,$15
+sw $24,4+0($sp)
+lw $24,8+0($sp)
+lw $15,16+0($sp)
+addu $24,$24,$15
+sw $24,8+0($sp)
+la $8,4+0($sp)
+lw $3,0($8)
+lw $9,4($8)
+sw $3,0($4)
+sw $9,4($4)
+L.1:
+j $31
+.end addpoint
+.globl canonrect
+.text
+.align 2
+.ent canonrect
+canonrect:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0x40e00000,-20
+sw $21,0($sp)
+sw $22,4($sp)
+sw $23,8($sp)
+sw $30,12($sp)
+sw $5,36($sp)
+sw $6,40($sp)
+sw $7,44($sp)
+lw $24,4+32($sp)
+lw $15,12+32($sp)
+bge $24,$15,L.10
+lw $30,4+32($sp)
+b L.11
+L.10:
+lw $30,12+32($sp)
+L.11:
+sw $30,-16+32($sp)
+lw $24,8+32($sp)
+lw $15,16+32($sp)
+bge $24,$15,L.20
+lw $23,8+32($sp)
+b L.21
+L.20:
+lw $23,16+32($sp)
+L.21:
+sw $23,-12+32($sp)
+lw $24,4+32($sp)
+lw $15,12+32($sp)
+ble $24,$15,L.26
+lw $22,4+32($sp)
+b L.27
+L.26:
+lw $22,12+32($sp)
+L.27:
+sw $22,-8+32($sp)
+lw $24,8+32($sp)
+lw $15,16+32($sp)
+ble $24,$15,L.37
+lw $21,8+32($sp)
+b L.38
+L.37:
+lw $21,16+32($sp)
+L.38:
+sw $21,-4+32($sp)
+la $8,-16+32($sp)
+lw $3,0($8)
+lw $9,4($8)
+sw $3,0($4)
+sw $9,4($4)
+lw $3,8($8)
+lw $9,12($8)
+sw $3,8($4)
+sw $9,12($4)
+L.5:
+lw $21,0($sp)
+lw $22,4($sp)
+lw $23,8($sp)
+lw $30,12($sp)
+addu $sp,$sp,32
+j $31
+.end canonrect
+.globl makepoint
+.text
+.align 2
+.ent makepoint
+makepoint:
+.frame $sp,8,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-8
+sw $5,-8+8($sp)
+sw $6,-4+8($sp)
+la $8,-8+8($sp)
+lw $3,0($8)
+lw $9,4($8)
+sw $3,0($4)
+sw $9,4($4)
+L.39:
+addu $sp,$sp,8
+j $31
+.end makepoint
+.globl makerect
+.text
+.align 2
+.ent makerect
+makerect:
+.frame $sp,48,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-48
+.mask 0x82000000,-24
+.cprestore 20
+sw $31,24($sp)
+sw $4,48($sp)
+sw $5,52($sp)
+sw $6,56($sp)
+sw $7,60($sp)
+la $24,-16+48($sp)
+la $8,4+48($sp)
+lw $3,0($8)
+lw $9,4($8)
+sw $3,0($24)
+sw $9,4($24)
+la $24,-8+48($sp)
+la $8,12+48($sp)
+lw $3,0($8)
+lw $9,4($8)
+sw $3,0($24)
+sw $9,4($24)
+lw $4,0+48($sp)
+la $8,-16+48($sp)
+lw $3,0($8)
+lw $9,4($8)
+sw $3,4($29)
+sw $9,8($29)
+lw $3,8($8)
+lw $9,12($8)
+sw $3,12($29)
+sw $9,16($29)
+lw $5,4($sp)
+lw $6,8($sp)
+lw $7,12($sp)
+jal canonrect
+L.42:
+lw $25,20($sp)
+lw $31,24($sp)
+addu $sp,$sp,48
+j $31
+.end makerect
+.globl ptinrect
+.text
+.align 2
+.ent ptinrect
+ptinrect:
+.frame $sp,8,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-8
+.mask 0x40000000,-8
+sw $30,0($sp)
+sw $4,8($sp)
+sw $5,12($sp)
+sw $6,16($sp)
+sw $7,20($sp)
+lw $24,0+8($sp)
+lw $15,8+8($sp)
+blt $24,$15,L.53
+lw $15,16+8($sp)
+bge $24,$15,L.53
+lw $24,4+8($sp)
+lw $15,12+8($sp)
+blt $24,$15,L.53
+lw $24,4+8($sp)
+lw $15,20+8($sp)
+bge $24,$15,L.53
+la $30,1
+b L.54
+L.53:
+move $30,$0
+L.54:
+move $2,$30
+L.45:
+lw $30,0($sp)
+addu $sp,$sp,8
+j $31
+.end ptinrect
+.globl y
+.sdata
+.align 0
+y:
+.byte 97
+.byte 98
+.byte 0
+.globl odd
+.text
+.text
+.align 2
+.ent odd
+odd:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0x82000000,-12
+.cprestore 16
+sw $31,20($sp)
+sw $4,32($sp)
+la $24,-3+32($sp)
+la $8,0+32($sp)
+ulhu $3,0($8)
+ush $3,0($24)
+lbu $3,2($8)
+sb $3,2($24)
+la $4,L.56
+la $5,-3+32($sp)
+jal printf
+move $2,$0
+L.55:
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,32
+j $31
+.end odd
+.rdata
+.align 2
+L.58:
+.word 0x0
+.word 0x0
+.align 2
+L.59:
+.word 0x140
+.word 0x140
+.align 2
+L.60:
+.word 0xffffffff
+.word 0xffffffff
+.word 0x1
+.word 0x1
+.word 0x14
+.word 0x12c
+.word 0x1f4
+.word 0x190
+.globl main
+.text
+.text
+.align 2
+.ent main
+main:
+.frame $sp,144,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-144
+.mask 0xc2000000,-112
+.cprestore 24
+sw $30,28($sp)
+sw $31,32($sp)
+la $24,-64+144($sp)
+la $8,L.58
+lw $3,0($8)
+lw $9,4($8)
+sw $3,0($24)
+sw $9,4($24)
+la $24,-72+144($sp)
+la $8,L.59
+lw $3,0($8)
+lw $9,4($8)
+sw $3,0($24)
+sw $9,4($24)
+la $24,-32+144($sp)
+la $8,L.60
+addu $8,$8,32
+addu $10,$24,32
+L.76:
+addu $8,$8,-8
+addu $10,$10,-8
+lw $3,0($8)
+lw $9,4($8)
+sw $3,0($10)
+sw $9,4($10)
+bltu $24,$10,L.76
+la $4,-80+144($sp)
+la $24,-10
+move $5,$24
+move $6,$24
+jal makepoint
+la $4,-88+144($sp)
+la $8,-72+144($sp)
+lw $3,0($8)
+lw $9,4($8)
+sw $3,4($29)
+sw $9,8($29)
+lw $5,4($sp)
+lw $6,8($sp)
+la $8,-80+144($sp)
+lw $3,0($8)
+lw $9,4($8)
+sw $3,12($29)
+sw $9,16($29)
+lw $7,12($sp)
+jal addpoint
+la $4,-96+144($sp)
+la $24,10
+move $5,$24
+move $6,$24
+jal makepoint
+la $4,-104+144($sp)
+la $8,-64+144($sp)
+lw $3,0($8)
+lw $9,4($8)
+sw $3,4($29)
+sw $9,8($29)
+lw $5,4($sp)
+lw $6,8($sp)
+la $8,-96+144($sp)
+lw $3,0($8)
+lw $9,4($8)
+sw $3,12($29)
+sw $9,16($29)
+lw $7,12($sp)
+jal addpoint
+la $4,-48+144($sp)
+la $8,-88+144($sp)
+lw $3,0($8)
+lw $9,4($8)
+sw $3,4($29)
+sw $9,8($29)
+lw $5,4($sp)
+lw $6,8($sp)
+la $8,-104+144($sp)
+lw $3,0($8)
+lw $9,4($8)
+sw $3,12($29)
+sw $9,16($29)
+lw $7,12($sp)
+jal makerect
+move $30,$0
+b L.64
+L.61:
+la $4,-56+144($sp)
+sll $24,$30,3
+la $15,-32+144($sp)
+addu $15,$24,$15
+lw $5,($15)
+la $15,-28+144($sp)
+addu $24,$24,$15
+lw $6,($24)
+jal makepoint
+la $4,L.65
+sll $24,$30,3
+la $15,-32+144($sp)
+addu $24,$24,$15
+lw $5,($24)
+lw $6,-52+144($sp)
+jal printf
+la $8,-56+144($sp)
+lw $3,0($8)
+lw $9,4($8)
+sw $3,0($29)
+sw $9,4($29)
+lw $4,0($sp)
+lw $5,4($sp)
+la $8,-48+144($sp)
+lw $3,0($8)
+lw $9,4($8)
+sw $3,8($29)
+sw $9,12($29)
+lw $3,8($8)
+lw $9,12($8)
+sw $3,16($29)
+sw $9,20($29)
+lw $6,8($sp)
+lw $7,12($sp)
+jal ptinrect
+bne $2,$0,L.68
+la $4,L.70
+jal printf
+L.68:
+la $4,L.71
+lw $5,-48+144($sp)
+lw $6,-44+144($sp)
+lw $7,-40+144($sp)
+lw $24,-36+144($sp)
+sw $24,16($sp)
+jal printf
+L.62:
+la $30,1($30)
+L.64:
+move $24,$30
+la $15,4
+bltu $24,$15,L.61
+la $8,y
+ulhu $3,0($8)
+sh $3,0($29)
+lbu $3,2($8)
+sb $3,2($29)
+lw $4,0($sp)
+jal odd
+move $4,$0
+jal exit
+move $2,$0
+L.57:
+lw $25,24($sp)
+lw $30,28($sp)
+lw $31,32($sp)
+addu $sp,$sp,144
+j $31
+.end main
+.rdata
+.align 0
+L.71:
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 105
+.byte 110
+.byte 32
+.byte 91
+.byte 37
+.byte 100
+.byte 44
+.byte 37
+.byte 100
+.byte 59
+.byte 32
+.byte 37
+.byte 100
+.byte 44
+.byte 37
+.byte 100
+.byte 93
+.byte 10
+.byte 0
+.align 0
+L.70:
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 0
+.align 0
+L.65:
+.byte 40
+.byte 37
+.byte 100
+.byte 44
+.byte 37
+.byte 100
+.byte 41
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 0
+.align 0
+L.56:
+.byte 37
+.byte 115
+.byte 10
+.byte 0
diff --git a/lcc/mips/irix/tst/switch.1bk b/lcc/mips/irix/tst/switch.1bk
new file mode 100755
index 0000000..559e8e3
--- /dev/null
+++ b/lcc/mips/irix/tst/switch.1bk
@@ -0,0 +1,76 @@
+b = 0x8
+f = 0xc
+n = 0xa
+r = 0xd
+t = 0x9
+v = 0xb
+x = 0x78
+f:
+x = 0
+x = 1
+x = 2
+x = 2
+x = 2
+x = 2
+x = 2
+x = 7
+x = 8
+x = 9
+x = 9
+x = 9
+x = 9
+x = 9
+x = 9
+x = 9
+x = 16
+x = 17
+x = 18
+x = 19
+x = 20
+g:
+1 1
+1 2
+2 3
+2 4
+2 5
+3 6
+d 6
+3 7
+d 7
+3 8
+d 8
+d 9
+d 10
+h:
+i = 8
+i = 16
+i = 120
+i = 128
+i = 248
+i = 264
+i = 272
+i = 280
+i = 288
+i = 296
+i = 304
+i = 312
+488 defaults
+x = 0x1000000
+x = 0x2000000
+x = 0x3000000
+x = 0x4000000
+x = 0x5000000
+x = 0x6000000 (default)
+x = 0x7000000 (default)
+0
+1
+2
+3
+4
+5
+0
+1
+2
+3
+4
+5
diff --git a/lcc/mips/irix/tst/switch.2bk b/lcc/mips/irix/tst/switch.2bk
new file mode 100755
index 0000000..76387b3
--- /dev/null
+++ b/lcc/mips/irix/tst/switch.2bk
@@ -0,0 +1,5 @@
+tst/switch.c:55: warning: missing return value
+tst/switch.c:73: warning: missing return value
+tst/switch.c:97: warning: missing return value
+tst/switch.c:112: warning: missing return value
+tst/switch.c:137: warning: missing return value
diff --git a/lcc/mips/irix/tst/switch.sbk b/lcc/mips/irix/tst/switch.sbk
new file mode 100755
index 0000000..969b490
--- /dev/null
+++ b/lcc/mips/irix/tst/switch.sbk
@@ -0,0 +1,836 @@
+.set reorder
+.globl main
+.text
+.text
+.align 2
+.ent main
+main:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2800000,-4
+sw $23,16($sp)
+.cprestore 20
+sw $30,24($sp)
+sw $31,28($sp)
+la $30,L.6
+b L.5
+L.2:
+lb $4,($30)
+jal backslash
+move $24,$2
+la $4,L.7
+lb $5,($30)
+move $6,$24
+jal printf
+L.3:
+la $30,1($30)
+L.5:
+lb $24,($30)
+bne $24,$0,L.2
+jal f
+jal g
+jal h
+la $23,16777216
+b L.11
+L.8:
+move $4,$23
+jal big
+L.9:
+la $23,16777216($23)
+L.11:
+and $24,$23,117440512
+bne $24,$0,L.8
+jal limit
+move $2,$0
+L.1:
+lw $23,16($sp)
+lw $25,20($sp)
+lw $30,24($sp)
+lw $31,28($sp)
+addu $sp,$sp,32
+j $31
+.end main
+.globl backslash
+.text
+.align 2
+.ent backslash
+backslash:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+la $24,102
+beq $4,$24,L.16
+bgt $4,$24,L.22
+L.21:
+la $24,98
+beq $4,$24,L.15
+b L.13
+L.22:
+la $24,110
+beq $4,$24,L.17
+blt $4,$24,L.13
+L.23:
+la $24,114
+beq $4,$24,L.18
+la $24,116
+beq $4,$24,L.19
+la $24,118
+beq $4,$24,L.20
+b L.13
+L.15:
+la $2,8
+b L.12
+L.16:
+la $2,12
+b L.12
+L.17:
+la $2,10
+b L.12
+L.18:
+la $2,13
+b L.12
+L.19:
+la $2,9
+b L.12
+L.20:
+la $2,11
+b L.12
+L.13:
+move $2,$4
+L.12:
+j $31
+.end backslash
+.globl f
+.text
+.align 2
+.ent f
+f:
+.frame $sp,40,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-40
+.mask 0xc2c00000,-8
+sw $22,16($sp)
+sw $23,20($sp)
+.cprestore 24
+sw $30,28($sp)
+sw $31,32($sp)
+move $23,$0
+la $4,L.25
+jal printf
+move $30,$0
+L.26:
+move $22,$30
+la $24,1
+blt $30,$24,L.30
+la $24,20
+bgt $30,$24,L.30
+sll $24,$30,2
+lw $24,L.42-4($24)
+.cpadd $24
+j $24
+.rdata
+.align 2
+L.42:
+.gpword L.32
+.gpword L.33
+.gpword L.30
+.gpword L.30
+.gpword L.30
+.gpword L.30
+.gpword L.34
+.gpword L.35
+.gpword L.36
+.gpword L.30
+.gpword L.30
+.gpword L.30
+.gpword L.30
+.gpword L.30
+.gpword L.30
+.gpword L.37
+.gpword L.38
+.gpword L.39
+.gpword L.40
+.gpword L.41
+.text
+L.32:
+move $23,$30
+b L.31
+L.33:
+move $23,$30
+b L.31
+L.34:
+move $23,$30
+b L.31
+L.35:
+move $23,$30
+b L.31
+L.36:
+move $23,$30
+b L.31
+L.37:
+move $23,$30
+b L.31
+L.38:
+move $23,$30
+b L.31
+L.39:
+move $23,$30
+b L.31
+L.40:
+move $23,$30
+b L.31
+L.41:
+move $23,$30
+L.30:
+L.31:
+la $4,L.44
+move $5,$23
+jal printf
+L.27:
+la $30,1($30)
+la $24,20
+ble $30,$24,L.26
+move $2,$0
+L.24:
+lw $22,16($sp)
+lw $23,20($sp)
+lw $25,24($sp)
+lw $30,28($sp)
+lw $31,32($sp)
+addu $sp,$sp,40
+j $31
+.end f
+.globl g
+.text
+.align 2
+.ent g
+g:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2000000,-8
+.cprestore 16
+sw $30,20($sp)
+sw $31,24($sp)
+la $4,L.46
+jal printf
+la $30,1
+L.47:
+la $24,1001
+blt $30,$24,L.64
+la $24,1004
+bgt $30,$24,L.65
+sll $24,$30,2
+lw $24,L.66-4004($24)
+.cpadd $24
+j $24
+.rdata
+.align 2
+L.66:
+.gpword L.60
+.gpword L.60
+.gpword L.60
+.gpword L.60
+.text
+L.64:
+la $24,1
+blt $30,$24,L.51
+la $24,8
+bgt $30,$24,L.51
+sll $24,$30,2
+lw $24,L.68-4($24)
+.cpadd $24
+j $24
+.rdata
+.align 2
+L.68:
+.gpword L.53
+.gpword L.53
+.gpword L.55
+.gpword L.55
+.gpword L.55
+.gpword L.57
+.gpword L.57
+.gpword L.57
+.text
+L.65:
+la $24,3001
+blt $30,$24,L.51
+la $24,3004
+bgt $30,$24,L.51
+sll $24,$30,2
+lw $24,L.70-12004($24)
+.cpadd $24
+j $24
+.rdata
+.align 2
+L.70:
+.gpword L.62
+.gpword L.62
+.gpword L.62
+.gpword L.62
+.text
+L.53:
+la $4,L.54
+move $5,$30
+jal printf
+b L.52
+L.55:
+la $4,L.56
+move $5,$30
+jal printf
+b L.52
+L.57:
+la $4,L.58
+move $5,$30
+jal printf
+L.51:
+la $4,L.59
+move $5,$30
+jal printf
+b L.52
+L.60:
+la $4,L.61
+move $5,$30
+jal printf
+b L.52
+L.62:
+la $4,L.63
+move $5,$30
+jal printf
+L.52:
+L.48:
+la $30,1($30)
+la $24,10
+ble $30,$24,L.47
+move $2,$0
+L.45:
+lw $25,16($sp)
+lw $30,20($sp)
+lw $31,24($sp)
+addu $sp,$sp,32
+j $31
+.end g
+.globl h
+.text
+.align 2
+.ent h
+h:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2800000,-4
+sw $23,16($sp)
+.cprestore 20
+sw $30,24($sp)
+sw $31,28($sp)
+move $23,$0
+la $4,L.73
+jal printf
+la $30,1
+L.74:
+la $24,264
+beq $30,$24,L.86
+bgt $30,$24,L.94
+L.93:
+la $24,120
+beq $30,$24,L.84
+bgt $30,$24,L.96
+L.95:
+la $24,8
+beq $30,$24,L.83
+blt $30,$24,L.78
+L.97:
+la $24,16
+beq $30,$24,L.82
+b L.78
+L.96:
+la $24,128
+beq $30,$24,L.80
+blt $30,$24,L.78
+L.98:
+la $24,248
+beq $30,$24,L.87
+b L.78
+L.94:
+la $24,288
+beq $30,$24,L.91
+bgt $30,$24,L.100
+L.99:
+la $24,272
+beq $30,$24,L.88
+blt $30,$24,L.78
+L.101:
+la $24,280
+beq $30,$24,L.85
+b L.78
+L.100:
+la $24,304
+beq $30,$24,L.89
+bgt $30,$24,L.103
+L.102:
+la $24,296
+beq $30,$24,L.90
+b L.78
+L.103:
+la $24,312
+beq $30,$24,L.92
+b L.78
+L.78:
+la $23,1($23)
+b L.75
+L.80:
+la $4,L.81
+move $5,$30
+jal printf
+b L.79
+L.82:
+la $4,L.81
+move $5,$30
+jal printf
+b L.79
+L.83:
+la $4,L.81
+move $5,$30
+jal printf
+b L.79
+L.84:
+la $4,L.81
+move $5,$30
+jal printf
+b L.79
+L.85:
+la $4,L.81
+move $5,$30
+jal printf
+b L.79
+L.86:
+la $4,L.81
+move $5,$30
+jal printf
+b L.79
+L.87:
+la $4,L.81
+move $5,$30
+jal printf
+b L.79
+L.88:
+la $4,L.81
+move $5,$30
+jal printf
+b L.79
+L.89:
+la $4,L.81
+move $5,$30
+jal printf
+b L.79
+L.90:
+la $4,L.81
+move $5,$30
+jal printf
+b L.79
+L.91:
+la $4,L.81
+move $5,$30
+jal printf
+b L.79
+L.92:
+la $4,L.81
+move $5,$30
+jal printf
+L.79:
+L.75:
+la $30,1($30)
+la $24,500
+ble $30,$24,L.74
+la $4,L.104
+move $5,$23
+jal printf
+move $2,$0
+L.72:
+lw $23,16($sp)
+lw $25,20($sp)
+lw $30,24($sp)
+lw $31,28($sp)
+addu $sp,$sp,32
+j $31
+.end h
+.globl big
+.text
+.align 2
+.ent big
+big:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2000000,-8
+.cprestore 16
+sw $30,20($sp)
+sw $31,24($sp)
+sw $4,32($sp)
+lw $24,0+32($sp)
+and $30,$24,0x6000000
+la $15,33554432
+beq $30,$15,L.111
+bgt $30,$15,L.115
+L.114:
+la $15,-2
+beq $30,$15,L.109
+la $15,-1
+beq $30,$15,L.109
+beq $30,$0,L.109
+b L.106
+L.115:
+move $24,$30
+la $15,67108864
+beq $24,$15,L.112
+b L.106
+L.109:
+la $4,L.110
+lw $5,0+32($sp)
+jal printf
+b L.107
+L.111:
+la $4,L.110
+lw $5,0+32($sp)
+jal printf
+b L.107
+L.112:
+la $4,L.110
+lw $5,0+32($sp)
+jal printf
+b L.107
+L.106:
+la $4,L.113
+lw $5,0+32($sp)
+jal printf
+L.107:
+move $2,$0
+L.105:
+lw $25,16($sp)
+lw $30,20($sp)
+lw $31,24($sp)
+addu $sp,$sp,32
+j $31
+.end big
+.globl limit
+.text
+.align 2
+.ent limit
+limit:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2000000,-8
+.cprestore 16
+sw $30,20($sp)
+sw $31,24($sp)
+la $30,-2147483648
+L.117:
+la $24,-2147483648
+blt $30,$24,L.121
+la $15,-2147483644
+bgt $30,$15,L.121
+sll $15,$30,2
+sll $24,$24,2
+subu $24,$15,$24
+lw $24,L.134($24)
+.cpadd $24
+j $24
+.rdata
+.align 2
+L.134:
+.gpword L.123
+.gpword L.125
+.gpword L.127
+.gpword L.129
+.gpword L.131
+.text
+L.123:
+la $4,L.124
+jal printf
+b L.122
+L.125:
+la $4,L.126
+jal printf
+b L.122
+L.127:
+la $4,L.128
+jal printf
+b L.122
+L.129:
+la $4,L.130
+jal printf
+b L.122
+L.131:
+la $4,L.132
+jal printf
+b L.122
+L.121:
+la $4,L.133
+jal printf
+L.122:
+L.118:
+la $30,1($30)
+la $24,-2147483643
+ble $30,$24,L.117
+la $30,2147483647
+L.135:
+la $24,2147483643
+blt $30,$24,L.139
+la $15,2147483647
+bgt $30,$15,L.139
+sll $15,$30,2
+sll $24,$24,2
+subu $24,$15,$24
+lw $24,L.146($24)
+.cpadd $24
+j $24
+.rdata
+.align 2
+L.146:
+.gpword L.145
+.gpword L.144
+.gpword L.143
+.gpword L.142
+.gpword L.141
+.text
+L.141:
+la $4,L.124
+jal printf
+b L.140
+L.142:
+la $4,L.126
+jal printf
+b L.140
+L.143:
+la $4,L.128
+jal printf
+b L.140
+L.144:
+la $4,L.130
+jal printf
+b L.140
+L.145:
+la $4,L.132
+jal printf
+b L.140
+L.139:
+la $4,L.133
+jal printf
+L.140:
+L.136:
+subu $30,$30,1
+la $24,2147483642
+bge $30,$24,L.135
+move $2,$0
+L.116:
+lw $25,16($sp)
+lw $30,20($sp)
+lw $31,24($sp)
+addu $sp,$sp,32
+j $31
+.end limit
+.rdata
+.align 0
+L.133:
+.byte 53
+.byte 10
+.byte 0
+.align 0
+L.132:
+.byte 52
+.byte 10
+.byte 0
+.align 0
+L.130:
+.byte 51
+.byte 10
+.byte 0
+.align 0
+L.128:
+.byte 50
+.byte 10
+.byte 0
+.align 0
+L.126:
+.byte 49
+.byte 10
+.byte 0
+.align 0
+L.124:
+.byte 48
+.byte 10
+.byte 0
+.align 0
+L.113:
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 120
+.byte 37
+.byte 120
+.byte 32
+.byte 40
+.byte 100
+.byte 101
+.byte 102
+.byte 97
+.byte 117
+.byte 108
+.byte 116
+.byte 41
+.byte 10
+.byte 0
+.align 0
+L.110:
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 120
+.byte 37
+.byte 120
+.byte 10
+.byte 0
+.align 0
+L.104:
+.byte 37
+.byte 100
+.byte 32
+.byte 100
+.byte 101
+.byte 102
+.byte 97
+.byte 117
+.byte 108
+.byte 116
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.81:
+.byte 105
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.73:
+.byte 104
+.byte 58
+.byte 10
+.byte 0
+.align 0
+L.63:
+.byte 54
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.61:
+.byte 53
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.59:
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.58:
+.byte 51
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.56:
+.byte 50
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.54:
+.byte 49
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.46:
+.byte 103
+.byte 58
+.byte 10
+.byte 0
+.align 0
+L.44:
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.25:
+.byte 102
+.byte 58
+.byte 10
+.byte 0
+.align 0
+L.7:
+.byte 37
+.byte 99
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 120
+.byte 37
+.byte 120
+.byte 10
+.byte 0
+.align 0
+L.6:
+.byte 98
+.byte 102
+.byte 110
+.byte 114
+.byte 116
+.byte 118
+.byte 120
+.byte 0
diff --git a/lcc/mips/irix/tst/wf1.1bk b/lcc/mips/irix/tst/wf1.1bk
new file mode 100755
index 0000000..095e087
--- /dev/null
+++ b/lcc/mips/irix/tst/wf1.1bk
@@ -0,0 +1,74 @@
+5 a
+2 and
+5 buf
+16 c
+8 char
+1 compare
+4 cond
+5 count
+1 d
+1 die
+3 else
+1 entry
+1 eof
+4 err
+1 error
+1 exit
+1 folded
+1 for
+1 free
+1 frequencies
+1 frequency
+1 get
+2 getchar
+3 getword
+14 if
+2 in
+1 index
+1 input
+1 install
+8 int
+1 into
+1 is
+4 isletter
+1 it
+1 itself
+5 left
+1 letter
+7 lookup
+1 main
+2 malloc
+1 message
+2 n
+1 necessary
+12 next
+9 node
+4 of
+1 on
+1 or
+1 otherwise
+2 out
+8 p
+3 print
+2 printf
+16 return
+5 right
+4 root
+25 s
+2 storage
+3 strcmp
+1 strcpy
+1 strlen
+8 struct
+1 structures
+2 subtree
+1 t
+5 tprint
+9 tree
+1 uses
+1 version
+1 wf
+3 while
+21 word
+9 words
+2 z
diff --git a/lcc/mips/irix/tst/wf1.2bk b/lcc/mips/irix/tst/wf1.2bk
new file mode 100755
index 0000000..0e7a8a6
--- /dev/null
+++ b/lcc/mips/irix/tst/wf1.2bk
@@ -0,0 +1,2 @@
+tst/wf1.c:29: warning: missing return value
+tst/wf1.c:87: warning: missing return value
diff --git a/lcc/mips/irix/tst/wf1.sbk b/lcc/mips/irix/tst/wf1.sbk
new file mode 100755
index 0000000..9892c1c
--- /dev/null
+++ b/lcc/mips/irix/tst/wf1.sbk
@@ -0,0 +1,378 @@
+.set reorder
+.globl main
+.text
+.text
+.align 2
+.ent main
+main:
+.frame $sp,48,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-48
+.mask 0x82000000,-28
+.cprestore 16
+sw $31,20($sp)
+sw $0,-24+48($sp)
+sw $0,next
+b L.3
+L.2:
+la $4,-20+48($sp)
+la $5,-24+48($sp)
+jal lookup
+lw $15,($2)
+la $15,1($15)
+sw $15,($2)
+L.3:
+la $4,-20+48($sp)
+jal getword
+bne $2,$0,L.2
+lw $4,-24+48($sp)
+jal tprint
+move $2,$0
+L.1:
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,48
+j $31
+.end main
+.globl err
+.text
+.align 2
+.ent err
+err:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+sw $4,24($sp)
+la $4,L.6
+lw $5,0+24($sp)
+jal printf
+la $4,1
+jal exit
+move $2,$0
+L.5:
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end err
+.globl getword
+.text
+.align 2
+.ent getword
+getword:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2800000,-4
+sw $23,16($sp)
+.cprestore 20
+sw $30,24($sp)
+sw $31,28($sp)
+sw $4,32($sp)
+L.8:
+L.9:
+jal getchar
+move $24,$2
+move $30,$24
+la $15,-1
+beq $24,$15,L.11
+move $4,$30
+jal isletter
+beq $2,$0,L.8
+L.11:
+lw $23,0+32($sp)
+b L.15
+L.12:
+move $24,$23
+la $23,1($24)
+move $15,$30
+sb $15,($24)
+L.13:
+jal getchar
+move $30,$2
+L.15:
+move $4,$30
+jal isletter
+move $30,$2
+bne $2,$0,L.12
+sb $0,($23)
+move $24,$23
+lw $15,0+32($sp)
+bleu $24,$15,L.16
+la $2,1
+b L.7
+L.16:
+move $2,$0
+L.7:
+lw $23,16($sp)
+lw $25,20($sp)
+lw $30,24($sp)
+lw $31,28($sp)
+addu $sp,$sp,32
+j $31
+.end getword
+.globl isletter
+.text
+.align 2
+.ent isletter
+isletter:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+la $24,65
+blt $4,$24,L.19
+la $24,90
+bgt $4,$24,L.19
+la $4,32($4)
+L.19:
+la $24,97
+blt $4,$24,L.21
+la $24,122
+bgt $4,$24,L.21
+move $2,$4
+b L.18
+L.21:
+move $2,$0
+L.18:
+j $31
+.end isletter
+.globl lookup
+.text
+.align 2
+.ent lookup
+lookup:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2000000,-8
+.cprestore 16
+sw $30,20($sp)
+sw $31,24($sp)
+sw $4,32($sp)
+move $30,$5
+lw $24,($30)
+beq $24,$0,L.24
+lw $4,0+32($sp)
+lw $24,($30)
+lw $5,12($24)
+jal strcmp
+sw $2,-4+32($sp)
+lw $24,-4+32($sp)
+bge $24,$0,L.26
+lw $4,0+32($sp)
+lw $24,($30)
+la $5,4($24)
+jal lookup
+move $24,$2
+b L.23
+L.26:
+lw $24,-4+32($sp)
+ble $24,$0,L.28
+lw $4,0+32($sp)
+lw $24,($30)
+la $5,8($24)
+jal lookup
+move $24,$2
+b L.23
+L.28:
+lw $2,($30)
+b L.23
+L.24:
+lw $24,next
+la $15,2000
+blt $24,$15,L.30
+la $4,L.32
+jal err
+L.30:
+lw $24,next
+sll $24,$24,4
+sw $0,words($24)
+lw $24,next
+sll $24,$24,4
+sw $0,words+8($24)
+sw $0,words+4($24)
+lw $4,0+32($sp)
+jal strlen
+move $24,$2
+la $4,1($24)
+jal malloc
+lw $15,next
+sll $15,$15,4
+sw $2,words+12($15)
+lw $24,next
+sll $24,$24,4
+lw $24,words+12($24)
+bne $24,$0,L.36
+la $4,L.39
+jal err
+L.36:
+lw $24,next
+sll $24,$24,4
+lw $4,words+12($24)
+lw $5,0+32($sp)
+jal strcpy
+lw $24,next
+la $15,1($24)
+sw $15,next
+sll $24,$24,4
+la $24,words($24)
+sw $24,($30)
+move $2,$24
+L.23:
+lw $25,16($sp)
+lw $30,20($sp)
+lw $31,24($sp)
+addu $sp,$sp,32
+j $31
+.end lookup
+.globl tprint
+.text
+.align 2
+.ent tprint
+tprint:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2000000,-8
+.cprestore 16
+sw $30,20($sp)
+sw $31,24($sp)
+move $30,$4
+move $24,$30
+beq $24,$0,L.42
+lw $4,4($30)
+jal tprint
+la $4,L.44
+lw $5,($30)
+lw $6,12($30)
+jal printf
+lw $4,8($30)
+jal tprint
+L.42:
+move $2,$0
+L.41:
+lw $25,16($sp)
+lw $30,20($sp)
+lw $31,24($sp)
+addu $sp,$sp,32
+j $31
+.end tprint
+.globl strcmp
+.text
+.align 2
+.ent strcmp
+strcmp:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+b L.47
+L.46:
+move $24,$4
+la $4,1($24)
+lb $24,($24)
+bne $24,$0,L.49
+move $2,$0
+b L.45
+L.49:
+la $5,1($5)
+L.47:
+lb $24,($4)
+lb $15,($5)
+beq $24,$15,L.46
+lb $24,($4)
+bne $24,$0,L.51
+la $2,-1
+b L.45
+L.51:
+lb $24,($5)
+bne $24,$0,L.53
+la $2,1
+b L.45
+L.53:
+lb $24,($4)
+lb $15,($5)
+subu $2,$24,$15
+L.45:
+j $31
+.end strcmp
+.globl next
+.comm next,4
+.globl words
+.comm words,32000
+.rdata
+.align 0
+L.44:
+.byte 37
+.byte 100
+.byte 9
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.39:
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 119
+.byte 111
+.byte 114
+.byte 100
+.byte 32
+.byte 115
+.byte 116
+.byte 111
+.byte 114
+.byte 97
+.byte 103
+.byte 101
+.byte 0
+.align 0
+L.32:
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 110
+.byte 111
+.byte 100
+.byte 101
+.byte 32
+.byte 115
+.byte 116
+.byte 111
+.byte 114
+.byte 97
+.byte 103
+.byte 101
+.byte 0
+.align 0
+L.6:
+.byte 63
+.byte 32
+.byte 37
+.byte 115
+.byte 10
+.byte 0
diff --git a/lcc/mips/irix/tst/yacc.1bk b/lcc/mips/irix/tst/yacc.1bk
new file mode 100755
index 0000000..b08a02f
--- /dev/null
+++ b/lcc/mips/irix/tst/yacc.1bk
@@ -0,0 +1,10 @@
+a
+b
+load
+negate
+push 5
+c
+load
+multiply
+add
+store
diff --git a/lcc/mips/irix/tst/yacc.2bk b/lcc/mips/irix/tst/yacc.2bk
new file mode 100755
index 0000000..a84aa5b
--- /dev/null
+++ b/lcc/mips/irix/tst/yacc.2bk
@@ -0,0 +1,3 @@
+tst/yacc.c:345: warning: missing return value
+tst/yacc.c:349: warning: missing return value
+tst/yacc.c:359: warning: missing return value
diff --git a/lcc/mips/irix/tst/yacc.sbk b/lcc/mips/irix/tst/yacc.sbk
new file mode 100755
index 0000000..bf9ced2
--- /dev/null
+++ b/lcc/mips/irix/tst/yacc.sbk
@@ -0,0 +1,2236 @@
+.set reorder
+.globl yyin
+.sdata
+.align 2
+yyin:
+.word _iob
+.globl yyout
+.sdata
+.align 2
+yyout:
+.word _iob+16
+.globl yylex
+.text
+.text
+.align 2
+.ent yylex
+yylex:
+.frame $sp,32,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-32
+.mask 0xc2000000,-8
+.cprestore 16
+sw $30,20($sp)
+sw $31,24($sp)
+b L.4
+L.3:
+L.6:
+la $24,-1
+blt $30,$24,L.7
+la $24,4
+bgt $30,$24,L.7
+sll $24,$30,2
+lw $24,L.18+4($24)
+.cpadd $24
+j $24
+.rdata
+.align 2
+L.18:
+.gpword L.8
+.gpword L.9
+.gpword L.12
+.gpword L.13
+.gpword L.8
+.gpword L.15
+.text
+L.9:
+jal yywrap
+beq $2,$0,L.8
+move $2,$0
+b L.2
+L.12:
+la $2,257
+b L.2
+L.13:
+la $2,258
+b L.2
+L.15:
+lb $2,yytext
+b L.2
+L.7:
+lw $4,yyout
+la $5,L.17
+move $6,$30
+jal fprintf
+L.8:
+L.4:
+jal yylook
+move $30,$2
+bge $2,$0,L.3
+move $2,$0
+L.2:
+lw $25,16($sp)
+lw $30,20($sp)
+lw $31,24($sp)
+addu $sp,$sp,32
+j $31
+.end yylex
+.globl yyvstop
+.data
+.align 2
+yyvstop:
+.word 0x0
+.word 0x4
+.word 0x0
+.word 0x3
+.word 0x4
+.word 0x0
+.word 0x2
+.word 0x4
+.word 0x0
+.word 0x1
+.word 0x4
+.word 0x0
+.word 0x2
+.word 0x0
+.word 0x1
+.word 0x0
+.word 0x0
+.globl yycrank
+.data
+.align 0
+yycrank:
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x1
+.byte 0x3
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x1
+.byte 0x4
+.byte 0x1
+.byte 0x3
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x1
+.byte 0x5
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x1
+.byte 0x6
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x6
+.byte 0x8
+.byte 0x0
+.byte 0x0
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.globl yysvec
+.data
+.align 2
+yysvec:
+.word 0x0
+.word 0x0
+.word 0x0
+.word yycrank-2
+.word 0x0
+.word 0x0
+.word yycrank
+.word yysvec+12
+.word 0x0
+.word yycrank
+.word 0x0
+.word yyvstop+4
+.word yycrank
+.word 0x0
+.word yyvstop+12
+.word yycrank+4
+.word 0x0
+.word yyvstop+24
+.word yycrank+38
+.word 0x0
+.word yyvstop+36
+.word yycrank
+.word yysvec+60
+.word yyvstop+48
+.word yycrank
+.word yysvec+72
+.word yyvstop+56
+.word 0x0
+.word 0x0
+.word 0x0
+.globl yytop
+.sdata
+.align 2
+yytop:
+.word yycrank+282
+.globl yybgin
+.sdata
+.align 2
+yybgin:
+.word yysvec+12
+.globl yymatch
+.data
+.align 0
+yymatch:
+.byte 0
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 9
+.byte 10
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 9
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 65
+.byte 1
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 0
+.globl yyextra
+.data
+.align 0
+yyextra:
+.byte 0
+.byte 0
+.byte 0
+.byte 0
+.byte 0
+.byte 0
+.byte 0
+.byte 0
+.byte 0
+.globl yylineno
+.sdata
+.align 2
+yylineno:
+.word 0x1
+.globl yysptr
+.sdata
+.align 2
+yysptr:
+.word yysbuf
+.globl yyprevious
+.sdata
+.align 2
+yyprevious:
+.word 0xa
+.globl yylook
+.text
+.text
+.align 2
+.ent yylook
+yylook:
+.frame $sp,72,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-72
+.mask 0xc2ff0000,-16
+sw $16,16($sp)
+sw $17,20($sp)
+sw $18,24($sp)
+sw $19,28($sp)
+sw $20,32($sp)
+sw $21,36($sp)
+sw $22,40($sp)
+sw $23,44($sp)
+.cprestore 48
+sw $30,52($sp)
+sw $31,56($sp)
+lw $24,yymorfg
+bne $24,$0,L.35
+la $21,yytext
+b L.36
+L.35:
+sw $0,yymorfg
+lw $24,yyleng
+la $21,yytext($24)
+L.36:
+L.37:
+la $23,yylstate
+lw $24,yybgin
+move $30,$24
+sw $24,yyestate
+lw $24,yyprevious
+la $15,10
+bne $24,$15,L.41
+la $30,12($30)
+L.41:
+L.43:
+lw $22,($30)
+move $24,$22
+la $15,yycrank
+bne $24,$15,L.47
+lw $18,4($30)
+move $24,$18
+bne $24,$0,L.49
+b L.94
+L.49:
+lw $24,($18)
+la $15,yycrank
+bne $24,$15,L.51
+b L.94
+L.51:
+L.47:
+move $24,$21
+sw $24,-12+72($sp)
+la $21,1($24)
+lw $15,yysptr
+la $14,yysbuf
+bleu $15,$14,L.61
+lw $15,yysptr
+la $15,-1($15)
+sw $15,yysptr
+lb $15,($15)
+sw $15,-4+72($sp)
+b L.62
+L.61:
+lw $15,yyin
+lw $14,($15)
+subu $14,$14,1
+sw $14,($15)
+bge $14,$0,L.63
+lw $4,yyin
+jal _filbuf
+move $24,$2
+sw $24,-8+72($sp)
+b L.64
+L.63:
+lw $24,yyin
+la $24,4($24)
+lw $15,($24)
+la $14,1($15)
+sw $14,($24)
+lbu $24,($15)
+sw $24,-8+72($sp)
+L.64:
+lw $24,-8+72($sp)
+sw $24,-4+72($sp)
+L.62:
+lw $24,-4+72($sp)
+sw $24,yytchar
+la $15,10
+bne $24,$15,L.59
+lw $24,yylineno
+la $24,1($24)
+sw $24,yylineno
+lw $16,yytchar
+b L.60
+L.59:
+lw $16,yytchar
+L.60:
+la $24,-1
+bne $16,$24,L.57
+move $17,$0
+b L.58
+L.57:
+lw $17,yytchar
+L.58:
+move $20,$17
+move $24,$17
+lw $15,-12+72($sp)
+sb $24,($15)
+L.65:
+move $19,$22
+move $24,$22
+la $15,yycrank
+bleu $24,$15,L.66
+sll $24,$20,1
+addu $22,$24,$19
+move $24,$22
+lw $15,yytop
+bgtu $24,$15,L.67
+la $24,12
+lb $15,($22)
+mul $24,$24,$15
+la $24,yysvec($24)
+move $15,$30
+bne $24,$15,L.67
+la $24,yysvec
+la $15,12
+lb $14,1($22)
+mul $15,$15,$14
+la $15,yysvec($15)
+bne $15,$24,L.70
+la $24,-1($21)
+move $21,$24
+lb $24,($24)
+sw $24,yytchar
+lw $24,yytchar
+la $15,10
+bne $24,$15,L.72
+lw $24,yylineno
+subu $24,$24,1
+sw $24,yylineno
+L.72:
+lw $24,yysptr
+la $15,1($24)
+sw $15,yysptr
+lw $15,yytchar
+sb $15,($24)
+b L.94
+L.70:
+move $24,$23
+la $23,4($24)
+la $15,12
+lb $14,1($22)
+mul $15,$15,$14
+la $15,yysvec($15)
+move $30,$15
+sw $15,($24)
+b L.43
+L.66:
+move $24,$22
+la $15,yycrank
+bgeu $24,$15,L.75
+la $24,yycrank
+move $15,$22
+subu $24,$24,$15
+la $15,2
+div $24,$24,$15
+sll $24,$24,1
+la $24,yycrank($24)
+move $19,$24
+move $22,$24
+sll $24,$20,1
+addu $22,$24,$22
+move $24,$22
+lw $15,yytop
+bgtu $24,$15,L.77
+la $24,12
+lb $15,($22)
+mul $24,$24,$15
+la $24,yysvec($24)
+move $15,$30
+bne $24,$15,L.77
+la $24,yysvec
+la $15,12
+lb $14,1($22)
+mul $15,$15,$14
+la $15,yysvec($15)
+bne $15,$24,L.79
+la $24,-1($21)
+move $21,$24
+lb $24,($24)
+sw $24,yytchar
+lw $24,yytchar
+la $15,10
+bne $24,$15,L.81
+lw $24,yylineno
+subu $24,$24,1
+sw $24,yylineno
+L.81:
+lw $24,yysptr
+la $15,1($24)
+sw $15,yysptr
+lw $15,yytchar
+sb $15,($24)
+b L.94
+L.79:
+move $24,$23
+la $23,4($24)
+la $15,12
+lb $14,1($22)
+mul $15,$15,$14
+la $15,yysvec($15)
+move $30,$15
+sw $15,($24)
+b L.43
+L.77:
+lb $24,yymatch($20)
+sll $24,$24,1
+addu $22,$24,$19
+move $24,$22
+lw $15,yytop
+bgtu $24,$15,L.83
+la $24,12
+lb $15,($22)
+mul $24,$24,$15
+la $24,yysvec($24)
+move $15,$30
+bne $24,$15,L.83
+la $24,yysvec
+la $15,12
+lb $14,1($22)
+mul $15,$15,$14
+la $15,yysvec($15)
+bne $15,$24,L.85
+la $24,-1($21)
+move $21,$24
+lb $24,($24)
+sw $24,yytchar
+lw $24,yytchar
+la $15,10
+bne $24,$15,L.87
+lw $24,yylineno
+subu $24,$24,1
+sw $24,yylineno
+L.87:
+lw $24,yysptr
+la $15,1($24)
+sw $15,yysptr
+lw $15,yytchar
+sb $15,($24)
+b L.94
+L.85:
+move $24,$23
+la $23,4($24)
+la $15,12
+lb $14,1($22)
+mul $15,$15,$14
+la $15,yysvec($15)
+move $30,$15
+sw $15,($24)
+b L.43
+L.83:
+L.75:
+L.67:
+lw $24,4($30)
+move $30,$24
+beq $24,$0,L.89
+lw $24,($30)
+move $22,$24
+la $15,yycrank
+beq $24,$15,L.89
+b L.65
+L.89:
+la $24,-1($21)
+move $21,$24
+lb $24,($24)
+sw $24,yytchar
+lw $24,yytchar
+la $15,10
+bne $24,$15,L.91
+lw $24,yylineno
+subu $24,$24,1
+sw $24,yylineno
+L.91:
+lw $24,yysptr
+la $15,1($24)
+sw $15,yysptr
+lw $15,yytchar
+sb $15,($24)
+b L.94
+L.93:
+move $24,$21
+la $21,-1($24)
+sb $0,($24)
+lw $24,($23)
+move $15,$0
+move $14,$24
+beq $14,$15,L.96
+lw $24,8($24)
+sw $24,yyfnd
+beq $24,$15,L.96
+lw $24,yyfnd
+lw $24,($24)
+ble $24,$0,L.96
+sw $23,yyolsp
+lw $24,yyfnd
+lw $24,($24)
+lb $24,yyextra($24)
+beq $24,$0,L.98
+b L.101
+L.100:
+la $23,-4($23)
+move $24,$21
+la $21,-1($24)
+lb $24,($24)
+sw $24,yytchar
+lw $24,yytchar
+la $15,10
+bne $24,$15,L.103
+lw $24,yylineno
+subu $24,$24,1
+sw $24,yylineno
+L.103:
+lw $24,yysptr
+la $15,1($24)
+sw $15,yysptr
+lw $15,yytchar
+sb $15,($24)
+L.101:
+lw $24,($23)
+lw $4,8($24)
+lw $24,yyfnd
+lw $24,($24)
+negu $5,$24
+jal yyback
+la $15,1
+beq $2,$15,L.105
+move $24,$23
+la $15,yylstate
+bgtu $24,$15,L.100
+L.105:
+L.98:
+lb $24,($21)
+sw $24,yyprevious
+sw $23,yylsp
+la $24,yytext
+move $15,$21
+subu $24,$15,$24
+la $24,1($24)
+sw $24,yyleng
+lw $24,yyleng
+sb $0,yytext($24)
+lw $24,yyfnd
+la $15,4($24)
+sw $15,yyfnd
+lw $2,($24)
+b L.34
+L.96:
+lb $24,($21)
+sw $24,yytchar
+lw $24,yytchar
+la $15,10
+bne $24,$15,L.106
+lw $24,yylineno
+subu $24,$24,1
+sw $24,yylineno
+L.106:
+lw $24,yysptr
+la $15,1($24)
+sw $15,yysptr
+lw $15,yytchar
+sb $15,($24)
+L.94:
+move $24,$23
+la $23,-4($24)
+la $15,yylstate
+bgtu $24,$15,L.93
+lb $24,yytext
+bne $24,$0,L.108
+la $24,yysbuf
+sw $24,yysptr
+move $2,$0
+b L.34
+L.108:
+lw $24,yysptr
+la $15,yysbuf
+bleu $24,$15,L.118
+lw $24,yysptr
+la $24,-1($24)
+sw $24,yysptr
+lb $24,($24)
+sw $24,-4+72($sp)
+b L.119
+L.118:
+lw $24,yyin
+lw $15,($24)
+subu $15,$15,1
+sw $15,($24)
+bge $15,$0,L.120
+lw $4,yyin
+jal _filbuf
+move $24,$2
+sw $24,-8+72($sp)
+b L.121
+L.120:
+lw $24,yyin
+la $24,4($24)
+lw $15,($24)
+la $14,1($15)
+sw $14,($24)
+lbu $24,($15)
+sw $24,-8+72($sp)
+L.121:
+lw $24,-8+72($sp)
+sw $24,-4+72($sp)
+L.119:
+lw $24,-4+72($sp)
+sw $24,yytchar
+la $15,10
+bne $24,$15,L.116
+lw $24,yylineno
+la $24,1($24)
+sw $24,yylineno
+lw $16,yytchar
+b L.117
+L.116:
+lw $16,yytchar
+L.117:
+la $24,-1
+bne $16,$24,L.114
+move $17,$0
+b L.115
+L.114:
+lw $17,yytchar
+L.115:
+sb $17,yytext
+sll $24,$17,8*(4-1); sra $24,$24,8*(4-1)
+sw $24,yyprevious
+lw $24,yyprevious
+ble $24,$0,L.122
+lw $24,yyout
+lw $15,($24)
+subu $15,$15,1
+sw $15,($24)
+bge $15,$0,L.125
+lw $24,yyprevious
+and $24,$24,(1<<(8*1))-1
+move $4,$24
+lw $5,yyout
+jal _flsbuf
+b L.126
+L.125:
+lw $24,yyout
+la $24,4($24)
+lw $15,($24)
+la $14,1($15)
+sw $14,($24)
+lw $24,yyprevious
+sb $24,($15)
+L.126:
+L.122:
+la $21,yytext
+b L.37
+L.34:
+lw $16,16($sp)
+lw $17,20($sp)
+lw $18,24($sp)
+lw $19,28($sp)
+lw $20,32($sp)
+lw $21,36($sp)
+lw $22,40($sp)
+lw $23,44($sp)
+lw $25,48($sp)
+lw $30,52($sp)
+lw $31,56($sp)
+addu $sp,$sp,72
+j $31
+.end yylook
+.globl yyback
+.text
+.align 2
+.ent yyback
+yyback:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+move $24,$4
+bne $24,$0,L.131
+move $2,$0
+b L.127
+L.130:
+move $24,$4
+la $4,4($24)
+lw $24,($24)
+bne $24,$5,L.133
+la $2,1
+b L.127
+L.133:
+L.131:
+lw $24,($4)
+bne $24,$0,L.130
+move $2,$0
+L.127:
+j $31
+.end yyback
+.globl yyinput
+.text
+.align 2
+.ent yyinput
+yyinput:
+.frame $sp,40,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-40
+.mask 0xc2e00000,-4
+sw $21,16($sp)
+sw $22,20($sp)
+sw $23,24($sp)
+.cprestore 28
+sw $30,32($sp)
+sw $31,36($sp)
+lw $24,yysptr
+la $15,yysbuf
+bleu $24,$15,L.144
+lw $24,yysptr
+la $24,-1($24)
+sw $24,yysptr
+lb $22,($24)
+b L.145
+L.144:
+lw $24,yyin
+lw $15,($24)
+subu $15,$15,1
+sw $15,($24)
+bge $15,$0,L.146
+lw $4,yyin
+jal _filbuf
+move $24,$2
+move $21,$24
+b L.147
+L.146:
+lw $24,yyin
+la $24,4($24)
+lw $15,($24)
+la $14,1($15)
+sw $14,($24)
+lbu $21,($15)
+L.147:
+move $22,$21
+L.145:
+sw $22,yytchar
+la $24,10
+bne $22,$24,L.142
+lw $24,yylineno
+la $24,1($24)
+sw $24,yylineno
+lw $23,yytchar
+b L.143
+L.142:
+lw $23,yytchar
+L.143:
+la $24,-1
+bne $23,$24,L.140
+move $30,$0
+b L.141
+L.140:
+lw $30,yytchar
+L.141:
+move $2,$30
+L.135:
+lw $21,16($sp)
+lw $22,20($sp)
+lw $23,24($sp)
+lw $25,28($sp)
+lw $30,32($sp)
+lw $31,36($sp)
+addu $sp,$sp,40
+j $31
+.end yyinput
+.globl yyoutput
+.text
+.align 2
+.ent yyoutput
+yyoutput:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+sw $4,24($sp)
+lw $24,yyout
+lw $15,($24)
+subu $15,$15,1
+sw $15,($24)
+bge $15,$0,L.150
+lw $24,0+24($sp)
+and $24,$24,(1<<(8*1))-1
+move $4,$24
+lw $5,yyout
+jal _flsbuf
+b L.151
+L.150:
+lw $24,yyout
+la $24,4($24)
+lw $15,($24)
+la $14,1($15)
+sw $14,($24)
+lw $24,0+24($sp)
+sb $24,($15)
+L.151:
+move $2,$0
+L.148:
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end yyoutput
+.globl yyunput
+.text
+.align 2
+.ent yyunput
+yyunput:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+sw $4,yytchar
+lw $24,yytchar
+la $15,10
+bne $24,$15,L.153
+lw $24,yylineno
+subu $24,$24,1
+sw $24,yylineno
+L.153:
+lw $24,yysptr
+la $15,1($24)
+sw $15,yysptr
+lw $15,yytchar
+sb $15,($24)
+move $2,$0
+L.152:
+j $31
+.end yyunput
+.globl main
+.text
+.align 2
+.ent main
+main:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+jal yyparse
+move $2,$0
+L.155:
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end main
+.globl yyerror
+.text
+.align 2
+.ent yyerror
+yyerror:
+.frame $sp,24,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-24
+.mask 0x82000000,-4
+.cprestore 16
+sw $31,20($sp)
+sw $4,24($sp)
+la $4,L.157
+lw $5,0+24($sp)
+jal printf
+move $2,$0
+L.156:
+lw $25,16($sp)
+lw $31,20($sp)
+addu $sp,$sp,24
+j $31
+.end yyerror
+.globl yyexca
+.data
+.align 1
+yyexca:
+.half 0xffffffff
+.half 0x1
+.half 0x0
+.half 0xffffffff
+.half 0xfffffffe
+.half 0x0
+.globl yyact
+.data
+.align 1
+yyact:
+.half 0xc
+.half 0x2
+.half 0x9
+.half 0x8
+.half 0x11
+.half 0xb
+.half 0x19
+.half 0x11
+.half 0xf
+.half 0x12
+.half 0x10
+.half 0xa
+.half 0x12
+.half 0x11
+.half 0xf
+.half 0x7
+.half 0x10
+.half 0xd
+.half 0x12
+.half 0x5
+.half 0x3
+.half 0x1
+.half 0x0
+.half 0x13
+.half 0x14
+.half 0x0
+.half 0x0
+.half 0x15
+.half 0x16
+.half 0x17
+.half 0x18
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x6
+.half 0xe
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x4
+.half 0x6
+.globl yypact
+.data
+.align 1
+yypact:
+.half 0xfffffc18
+.half 0xfffffff7
+.half 0xfffffc18
+.half 0x5
+.half 0xfffffff9
+.half 0xffffffc5
+.half 0xfffffc18
+.half 0xfffffc18
+.half 0xfffffc18
+.half 0xffffffd8
+.half 0xffffffe3
+.half 0xffffffd8
+.half 0xffffffd8
+.half 0xfffffc18
+.half 0xfffffc18
+.half 0xffffffd8
+.half 0xffffffd8
+.half 0xffffffd8
+.half 0xffffffd8
+.half 0xffffffda
+.half 0xffffffdd
+.half 0xffffffda
+.half 0xffffffda
+.half 0xfffffc18
+.half 0xfffffc18
+.half 0xfffffc18
+.globl yypgo
+.data
+.align 1
+yypgo:
+.half 0x0
+.half 0x15
+.half 0x14
+.half 0x11
+.half 0xb
+.globl yyr1
+.data
+.align 1
+yyr1:
+.half 0x0
+.half 0x1
+.half 0x1
+.half 0x1
+.half 0x1
+.half 0x2
+.half 0x4
+.half 0x4
+.half 0x4
+.half 0x4
+.half 0x4
+.half 0x4
+.half 0x4
+.half 0x4
+.half 0x3
+.globl yyr2
+.data
+.align 1
+yyr2:
+.half 0x0
+.half 0x0
+.half 0x2
+.half 0x3
+.half 0x3
+.half 0x3
+.half 0x3
+.half 0x3
+.half 0x3
+.half 0x3
+.half 0x2
+.half 0x3
+.half 0x1
+.half 0x1
+.half 0x1
+.globl yychk
+.data
+.align 1
+yychk:
+.half 0xfffffc18
+.half 0xffffffff
+.half 0xa
+.half 0xfffffffe
+.half 0x100
+.half 0xfffffffd
+.half 0x101
+.half 0xa
+.half 0xa
+.half 0x3d
+.half 0xfffffffc
+.half 0x2d
+.half 0x28
+.half 0xfffffffd
+.half 0x102
+.half 0x2b
+.half 0x2d
+.half 0x2a
+.half 0x2f
+.half 0xfffffffc
+.half 0xfffffffc
+.half 0xfffffffc
+.half 0xfffffffc
+.half 0xfffffffc
+.half 0xfffffffc
+.half 0x29
+.globl yydef
+.data
+.align 1
+yydef:
+.half 0x1
+.half 0xfffffffe
+.half 0x2
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0xe
+.half 0x3
+.half 0x4
+.half 0x0
+.half 0x5
+.half 0x0
+.half 0x0
+.half 0xc
+.half 0xd
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0xa
+.half 0x0
+.half 0x6
+.half 0x7
+.half 0x8
+.half 0x9
+.half 0xb
+.globl yychar
+.sdata
+.align 2
+yychar:
+.word 0xffffffff
+.globl yynerrs
+.sdata
+.align 2
+yynerrs:
+.word 0x0
+.globl yyerrflag
+.sdata
+.align 1
+yyerrflag:
+.half 0x0
+.globl yyparse
+.text
+.text
+.align 2
+.ent yyparse
+yyparse:
+.frame $sp,360,$31
+.set noreorder
+.cpload $25
+.set reorder
+addu $sp,$sp,-360
+.mask 0xc2fe0000,-308
+sw $17,16($sp)
+sw $18,20($sp)
+sw $19,24($sp)
+sw $20,28($sp)
+sw $21,32($sp)
+sw $22,36($sp)
+sw $23,40($sp)
+.cprestore 44
+sw $30,48($sp)
+sw $31,52($sp)
+move $24,$0
+move $23,$24
+la $15,-1
+sw $15,yychar
+sw $0,yynerrs
+sh $24,yyerrflag
+la $22,-302+360($sp)
+la $20,yyv-4
+L.161:
+la $24,2($22)
+move $22,$24
+la $15,0+360($sp)
+bleu $24,$15,L.162
+la $4,L.165
+jal yyerror
+la $2,1
+b L.158
+L.162:
+sh $23,($22)
+la $20,4($20)
+lw $24,yyval
+sw $24,($20)
+L.166:
+sll $24,$23,8*(4-2); sra $24,$24,8*(4-2)
+sll $24,$24,1
+lh $21,yypact($24)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,-1000
+bgt $24,$15,L.167
+b L.169
+L.167:
+lw $24,yychar
+bge $24,$0,L.170
+jal yylex
+sw $2,yychar
+bge $2,$0,L.172
+sw $0,yychar
+L.172:
+L.170:
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+lw $15,yychar
+addu $24,$24,$15
+move $21,$24
+sll $24,$24,8*(4-2); sra $24,$24,8*(4-2)
+blt $24,$0,L.176
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+la $15,249
+blt $24,$15,L.174
+L.176:
+b L.169
+L.174:
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $24,$24,1
+lh $24,yyact($24)
+move $21,$24
+sll $24,$24,8*(4-2); sra $24,$24,8*(4-2)
+sll $24,$24,1
+lh $24,yychk($24)
+lw $15,yychar
+bne $24,$15,L.177
+la $24,-1
+sw $24,yychar
+lw $24,yylval
+sw $24,yyval
+move $23,$21
+lh $24,yyerrflag
+ble $24,$0,L.161
+lh $24,yyerrflag
+subu $24,$24,1
+sh $24,yyerrflag
+b L.161
+L.177:
+L.169:
+sll $24,$23,8*(4-2); sra $24,$24,8*(4-2)
+sll $24,$24,1
+lh $24,yydef($24)
+move $21,$24
+sll $24,$24,8*(4-2); sra $24,$24,8*(4-2)
+la $15,-2
+bne $24,$15,L.181
+lw $24,yychar
+bge $24,$0,L.183
+jal yylex
+sw $2,yychar
+bge $2,$0,L.185
+sw $0,yychar
+L.185:
+L.183:
+la $19,yyexca
+b L.190
+L.187:
+L.188:
+la $19,4($19)
+L.190:
+lh $24,($19)
+la $15,-1
+bne $24,$15,L.187
+lh $24,2($19)
+sll $15,$23,8*(4-2); sra $15,$15,8*(4-2)
+bne $24,$15,L.187
+b L.192
+L.191:
+lh $24,($19)
+lw $15,yychar
+bne $24,$15,L.194
+b L.193
+L.194:
+L.192:
+la $24,4($19)
+move $19,$24
+lh $24,($24)
+bge $24,$0,L.191
+L.193:
+lh $24,2($19)
+move $21,$24
+sll $24,$24,8*(4-2); sra $24,$24,8*(4-2)
+bge $24,$0,L.196
+move $2,$0
+b L.158
+L.196:
+L.181:
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+bne $24,$0,L.198
+lh $17,yyerrflag
+blt $17,$0,L.200
+la $24,3
+bgt $17,$24,L.200
+sll $24,$17,2
+lw $24,L.216($24)
+.cpadd $24
+j $24
+.rdata
+.align 2
+L.216:
+.gpword L.203
+.gpword L.206
+.gpword L.206
+.gpword L.213
+.text
+L.203:
+la $4,L.204
+jal yyerror
+L.205:
+lw $24,yynerrs
+la $24,1($24)
+sw $24,yynerrs
+L.206:
+la $24,3
+sh $24,yyerrflag
+b L.208
+L.207:
+lh $24,($22)
+sll $24,$24,1
+lh $24,yypact($24)
+la $24,256($24)
+move $21,$24
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+blt $24,$0,L.210
+la $15,249
+bge $24,$15,L.210
+sll $24,$24,1
+lh $24,yyact($24)
+sll $24,$24,1
+lh $24,yychk($24)
+la $15,256
+bne $24,$15,L.210
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $24,$24,1
+lh $23,yyact($24)
+b L.161
+L.210:
+lh $24,($22)
+sll $24,$24,1
+lh $21,yypact($24)
+la $22,-2($22)
+la $20,-4($20)
+L.208:
+move $24,$22
+la $15,-300+360($sp)
+bgeu $24,$15,L.207
+L.212:
+la $2,1
+b L.158
+L.213:
+lw $24,yychar
+bne $24,$0,L.214
+b L.212
+L.214:
+la $24,-1
+sw $24,yychar
+b L.166
+L.200:
+L.198:
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $24,$24,1
+la $15,yyr2($24)
+lh $14,($15)
+sll $14,$14,1
+subu $22,$22,$14
+move $30,$20
+lh $15,($15)
+sll $15,$15,2
+subu $20,$20,$15
+lw $15,4($20)
+sw $15,yyval
+sh $21,-302+360($sp)
+lh $21,yyr1($24)
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $24,$24,1
+lh $24,yypgo($24)
+lh $15,($22)
+addu $24,$24,$15
+la $24,1($24)
+move $18,$24
+sll $24,$18,8*(4-2); sra $24,$24,8*(4-2)
+la $15,249
+bge $24,$15,L.219
+sll $24,$24,1
+lh $24,yyact($24)
+move $23,$24
+sll $24,$24,8*(4-2); sra $24,$24,8*(4-2)
+sll $24,$24,1
+lh $24,yychk($24)
+sll $15,$21,8*(4-2); sra $15,$15,8*(4-2)
+negu $15,$15
+beq $24,$15,L.217
+L.219:
+sll $24,$21,8*(4-2); sra $24,$24,8*(4-2)
+sll $24,$24,1
+lh $24,yypgo($24)
+sll $24,$24,1
+lh $23,yyact($24)
+L.217:
+lh $17,-302+360($sp)
+la $24,4
+blt $17,$24,L.161
+la $24,14
+bgt $17,$24,L.161
+sll $24,$17,2
+lw $24,L.241-16($24)
+.cpadd $24
+j $24
+.rdata
+.align 2
+L.241:
+.gpword L.223
+.gpword L.224
+.gpword L.226
+.gpword L.228
+.gpword L.230
+.gpword L.232
+.gpword L.234
+.gpword L.161
+.gpword L.236
+.gpword L.238
+.gpword L.240
+.text
+L.223:
+sh $0,yyerrflag
+b L.161
+L.224:
+la $4,L.225
+jal printf
+b L.161
+L.226:
+la $4,L.227
+jal printf
+b L.161
+L.228:
+la $4,L.229
+jal printf
+b L.161
+L.230:
+la $4,L.231
+jal printf
+b L.161
+L.232:
+la $4,L.233
+jal printf
+b L.161
+L.234:
+la $4,L.235
+jal printf
+b L.161
+L.236:
+la $4,L.237
+jal printf
+b L.161
+L.238:
+la $4,L.239
+la $5,yytext
+jal printf
+b L.161
+L.240:
+la $4,L.157
+la $5,yytext
+jal printf
+b L.161
+L.158:
+lw $17,16($sp)
+lw $18,20($sp)
+lw $19,24($sp)
+lw $20,28($sp)
+lw $21,32($sp)
+lw $22,36($sp)
+lw $23,40($sp)
+lw $25,44($sp)
+lw $30,48($sp)
+lw $31,52($sp)
+addu $sp,$sp,360
+j $31
+.end yyparse
+.globl yywrap
+.text
+.align 2
+.ent yywrap
+yywrap:
+.frame $sp,0,$31
+.set noreorder
+.cpload $25
+.set reorder
+la $2,1
+L.243:
+j $31
+.end yywrap
+.globl yyv
+.comm yyv,600
+.globl yyfnd
+.comm yyfnd,4
+.globl yyolsp
+.comm yyolsp,4
+.globl yylsp
+.comm yylsp,4
+.globl yylstate
+.comm yylstate,800
+.globl yyestate
+.comm yyestate,4
+.globl yytchar
+.comm yytchar,4
+.globl yysbuf
+.comm yysbuf,200
+.globl yymorfg
+.comm yymorfg,4
+.globl yytext
+.comm yytext,200
+.globl yyleng
+.comm yyleng,4
+.extern _iob 0
+.globl yyval
+.comm yyval,4
+.globl yylval
+.comm yylval,4
+.rdata
+.align 0
+L.239:
+.byte 112
+.byte 117
+.byte 115
+.byte 104
+.byte 32
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.237:
+.byte 108
+.byte 111
+.byte 97
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.235:
+.byte 110
+.byte 101
+.byte 103
+.byte 97
+.byte 116
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.233:
+.byte 100
+.byte 105
+.byte 118
+.byte 105
+.byte 100
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.231:
+.byte 109
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 121
+.byte 10
+.byte 0
+.align 0
+L.229:
+.byte 110
+.byte 101
+.byte 103
+.byte 97
+.byte 116
+.byte 101
+.byte 10
+.byte 97
+.byte 100
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.227:
+.byte 97
+.byte 100
+.byte 100
+.byte 10
+.byte 0
+.align 0
+L.225:
+.byte 115
+.byte 116
+.byte 111
+.byte 114
+.byte 101
+.byte 10
+.byte 0
+.align 0
+L.204:
+.byte 115
+.byte 121
+.byte 110
+.byte 116
+.byte 97
+.byte 120
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 0
+.align 0
+L.165:
+.byte 121
+.byte 97
+.byte 99
+.byte 99
+.byte 32
+.byte 115
+.byte 116
+.byte 97
+.byte 99
+.byte 107
+.byte 32
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 0
+.align 0
+L.157:
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 0
+L.17:
+.byte 98
+.byte 97
+.byte 100
+.byte 32
+.byte 115
+.byte 119
+.byte 105
+.byte 116
+.byte 99
+.byte 104
+.byte 32
+.byte 121
+.byte 121
+.byte 108
+.byte 111
+.byte 111
+.byte 107
+.byte 32
+.byte 37
+.byte 100
+.byte 0
diff --git a/lcc/msdev/rcc.dsp b/lcc/msdev/rcc.dsp
new file mode 100755
index 0000000..7830702
--- /dev/null
+++ b/lcc/msdev/rcc.dsp
@@ -0,0 +1,240 @@
+# Microsoft Developer Studio Project File - Name="rcc" - Package Owner=<4>
+# Microsoft Developer Studio Generated Build File, Format Version 6.00
+# ** DO NOT EDIT **
+
+# TARGTYPE "Win32 (x86) Console Application" 0x0103
+
+CFG=rcc - Win32 Debug
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,
+!MESSAGE use the Export Makefile command and run
+!MESSAGE
+!MESSAGE NMAKE /f "rcc.mak".
+!MESSAGE
+!MESSAGE You can specify a configuration when running NMAKE
+!MESSAGE by defining the macro CFG on the command line. For example:
+!MESSAGE
+!MESSAGE NMAKE /f "rcc.mak" CFG="rcc - Win32 Debug"
+!MESSAGE
+!MESSAGE Possible choices for configuration are:
+!MESSAGE
+!MESSAGE "rcc - Win32 Release" (based on "Win32 (x86) Console Application")
+!MESSAGE "rcc - Win32 Debug" (based on "Win32 (x86) Console Application")
+!MESSAGE
+
+# Begin Project
+# PROP AllowPerConfigDependencies 0
+# PROP Scc_ProjName ""
+# PROP Scc_LocalPath ""
+CPP=cl.exe
+RSC=rc.exe
+
+!IF "$(CFG)" == "rcc - Win32 Release"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir "Release"
+# PROP BASE Intermediate_Dir "Release"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir "Release"
+# PROP Intermediate_Dir "Release"
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
+# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
+# ADD BASE RSC /l 0x409 /d "NDEBUG"
+# ADD RSC /l 0x409 /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
+
+!ELSEIF "$(CFG)" == "rcc - Win32 Debug"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 1
+# PROP BASE Output_Dir "Debug"
+# PROP BASE Intermediate_Dir "Debug"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 1
+# PROP Output_Dir "Debug"
+# PROP Intermediate_Dir "Debug"
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c
+# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c
+# ADD BASE RSC /l 0x409 /d "_DEBUG"
+# ADD RSC /l 0x409 /d "_DEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept
+
+!ENDIF
+
+# Begin Target
+
+# Name "rcc - Win32 Release"
+# Name "rcc - Win32 Debug"
+# Begin Group "Source Files"
+
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
+# Begin Source File
+
+SOURCE=..\src\2html.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\alloc.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\asdl.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\bind.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\bytecode.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\c.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\config.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\dag.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\decl.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\enode.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\error.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\event.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\expr.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\gen.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\init.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\inits.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\input.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\lex.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\list.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\main.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\null.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\output.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\pass2.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\prof.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\profio.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\simp.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\stab.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\stab.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\stmt.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\string.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\sym.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\symbolic.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\token.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\trace.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\tree.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\src\types.c
+# End Source File
+# End Group
+# Begin Group "Header Files"
+
+# PROP Default_Filter "h;hpp;hxx;hm;inl"
+# End Group
+# Begin Group "Resource Files"
+
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
+# End Group
+# End Target
+# End Project
diff --git a/lcc/msdev/rcc.dsw b/lcc/msdev/rcc.dsw
new file mode 100755
index 0000000..3d97352
--- /dev/null
+++ b/lcc/msdev/rcc.dsw
@@ -0,0 +1,29 @@
+Microsoft Developer Studio Workspace File, Format Version 6.00
+# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!
+
+###############################################################################
+
+Project: "rcc"=.\rcc.dsp - Package Owner=<4>
+
+Package=<5>
+{{{
+}}}
+
+Package=<4>
+{{{
+}}}
+
+###############################################################################
+
+Global:
+
+Package=<5>
+{{{
+}}}
+
+Package=<3>
+{{{
+}}}
+
+###############################################################################
+
diff --git a/lcc/packing.lst b/lcc/packing.lst
new file mode 100755
index 0000000..e62e4b8
--- /dev/null
+++ b/lcc/packing.lst
@@ -0,0 +1,432 @@
+README
+CPYRIGHT
+LOG
+makefile
+makefile.nt
+src/2html.c
+src/alloc.c
+src/asdl.c
+src/bind.c
+src/bytecode.c
+src/c.h
+src/config.h
+src/dag.c
+src/decl.c
+src/enode.c
+src/error.c
+src/event.c
+src/expr.c
+src/gen.c
+src/init.c
+src/inits.c
+src/input.c
+src/lex.c
+src/list.c
+src/main.c
+src/null.c
+src/output.c
+src/pass2.c
+src/prof.c
+src/profio.c
+src/simp.c
+src/stab.c
+src/stab.h
+src/stmt.c
+src/string.c
+src/sym.c
+src/symbolic.c
+src/token.h
+src/trace.c
+src/tree.c
+src/types.c
+src/alpha.md
+src/dagcheck.md
+src/mips.md
+src/sparc.md
+src/x86.md
+src/x86linux.md
+src/run.sh
+src/rcc.asdl
+lib/assert.c
+lib/bbexit.c
+lib/yynull.c
+tst/8q.0
+tst/8q.c
+tst/array.0
+tst/array.c
+tst/cf.0
+tst/cf.c
+tst/cq.0
+tst/cq.c
+tst/cvt.0
+tst/cvt.c
+tst/fields.0
+tst/fields.c
+tst/front.0
+tst/front.c
+tst/incr.0
+tst/incr.c
+tst/init.0
+tst/init.c
+tst/limits.0
+tst/limits.c
+tst/paranoia.0
+tst/paranoia.c
+tst/sort.0
+tst/sort.c
+tst/spill.0
+tst/spill.c
+tst/stdarg.0
+tst/stdarg.c
+tst/struct.0
+tst/struct.c
+tst/switch.0
+tst/switch.c
+tst/wf1.0
+tst/wf1.c
+tst/yacc.0
+tst/yacc.c
+etc/bprint.c
+etc/gcc-solaris.c
+etc/irix.c
+etc/lcc.c
+etc/linux.c
+etc/ops.c
+etc/osf.c
+etc/solaris.c
+etc/win32.c
+cpp/cpp.c
+cpp/cpp.h
+cpp/eval.c
+cpp/getopt.c
+cpp/hideset.c
+cpp/include.c
+cpp/lex.c
+cpp/macro.c
+cpp/nlist.c
+cpp/tokens.c
+cpp/unix.c
+lburg/gram.c
+lburg/gram.y
+lburg/lburg.1
+lburg/lburg.c
+lburg/lburg.h
+include/alpha/osf/assert.h
+include/alpha/osf/ctype.h
+include/alpha/osf/errno.h
+include/alpha/osf/float.h
+include/alpha/osf/limits.h
+include/alpha/osf/locale.h
+include/alpha/osf/math.h
+include/alpha/osf/setjmp.h
+include/alpha/osf/signal.h
+include/alpha/osf/stdarg.h
+include/alpha/osf/stddef.h
+include/alpha/osf/stdio.h
+include/alpha/osf/stdlib.h
+include/alpha/osf/string.h
+include/alpha/osf/time.h
+include/sparc/solaris/assert.h
+include/sparc/solaris/ctype.h
+include/sparc/solaris/errno.h
+include/sparc/solaris/float.h
+include/sparc/solaris/limits.h
+include/sparc/solaris/locale.h
+include/sparc/solaris/math.h
+include/sparc/solaris/setjmp.h
+include/sparc/solaris/signal.h
+include/sparc/solaris/stdarg.h
+include/sparc/solaris/stddef.h
+include/sparc/solaris/stdio.h
+include/sparc/solaris/stdlib.h
+include/sparc/solaris/string.h
+include/sparc/solaris/time.h
+include/mips/irix/assert.h
+include/mips/irix/ctype.h
+include/mips/irix/errno.h
+include/mips/irix/float.h
+include/mips/irix/limits.h
+include/mips/irix/locale.h
+include/mips/irix/math.h
+include/mips/irix/setjmp.h
+include/mips/irix/signal.h
+include/mips/irix/stdarg.h
+include/mips/irix/stddef.h
+include/mips/irix/stdio.h
+include/mips/irix/stdlib.h
+include/mips/irix/string.h
+include/mips/irix/time.h
+include/x86/linux/assert.h
+include/x86/linux/float.h
+include/x86/linux/stdarg.h
+doc/4.html
+doc/install.html
+doc/bprint.1
+doc/lcc.1
+doc/bprint.pdf
+doc/lcc.pdf
+alpha/osf/tst/8q.1bk
+alpha/osf/tst/8q.2bk
+alpha/osf/tst/8q.sbk
+alpha/osf/tst/array.1bk
+alpha/osf/tst/array.2bk
+alpha/osf/tst/array.sbk
+alpha/osf/tst/cf.1bk
+alpha/osf/tst/cf.2bk
+alpha/osf/tst/cf.sbk
+alpha/osf/tst/cq.1bk
+alpha/osf/tst/cq.2bk
+alpha/osf/tst/cq.sbk
+alpha/osf/tst/cvt.1bk
+alpha/osf/tst/cvt.2bk
+alpha/osf/tst/cvt.sbk
+alpha/osf/tst/fields.1bk
+alpha/osf/tst/fields.2bk
+alpha/osf/tst/fields.sbk
+alpha/osf/tst/front.2bk
+alpha/osf/tst/front.sbk
+alpha/osf/tst/incr.1bk
+alpha/osf/tst/incr.2bk
+alpha/osf/tst/incr.sbk
+alpha/osf/tst/init.1bk
+alpha/osf/tst/init.2bk
+alpha/osf/tst/init.sbk
+alpha/osf/tst/limits.1bk
+alpha/osf/tst/limits.2bk
+alpha/osf/tst/limits.sbk
+alpha/osf/tst/paranoia.1bk
+alpha/osf/tst/paranoia.2bk
+alpha/osf/tst/paranoia.sbk
+alpha/osf/tst/sort.1bk
+alpha/osf/tst/sort.2bk
+alpha/osf/tst/sort.sbk
+alpha/osf/tst/spill.1bk
+alpha/osf/tst/spill.2bk
+alpha/osf/tst/spill.sbk
+alpha/osf/tst/stdarg.1bk
+alpha/osf/tst/stdarg.2bk
+alpha/osf/tst/stdarg.sbk
+alpha/osf/tst/struct.1bk
+alpha/osf/tst/struct.2bk
+alpha/osf/tst/struct.sbk
+alpha/osf/tst/switch.1bk
+alpha/osf/tst/switch.2bk
+alpha/osf/tst/switch.sbk
+alpha/osf/tst/wf1.1bk
+alpha/osf/tst/wf1.2bk
+alpha/osf/tst/wf1.sbk
+alpha/osf/tst/yacc.1bk
+alpha/osf/tst/yacc.2bk
+alpha/osf/tst/yacc.sbk
+sparc/solaris/tst/8q.1bk
+sparc/solaris/tst/8q.2bk
+sparc/solaris/tst/8q.sbk
+sparc/solaris/tst/array.1bk
+sparc/solaris/tst/array.2bk
+sparc/solaris/tst/array.sbk
+sparc/solaris/tst/cf.1bk
+sparc/solaris/tst/cf.2bk
+sparc/solaris/tst/cf.sbk
+sparc/solaris/tst/cq.1bk
+sparc/solaris/tst/cq.2bk
+sparc/solaris/tst/cq.sbk
+sparc/solaris/tst/cvt.1bk
+sparc/solaris/tst/cvt.2bk
+sparc/solaris/tst/cvt.sbk
+sparc/solaris/tst/fields.1bk
+sparc/solaris/tst/fields.2bk
+sparc/solaris/tst/fields.sbk
+sparc/solaris/tst/front.2bk
+sparc/solaris/tst/front.sbk
+sparc/solaris/tst/incr.1bk
+sparc/solaris/tst/incr.2bk
+sparc/solaris/tst/incr.sbk
+sparc/solaris/tst/init.1bk
+sparc/solaris/tst/init.2bk
+sparc/solaris/tst/init.sbk
+sparc/solaris/tst/limits.1bk
+sparc/solaris/tst/limits.2bk
+sparc/solaris/tst/limits.sbk
+sparc/solaris/tst/paranoia.1bk
+sparc/solaris/tst/paranoia.2bk
+sparc/solaris/tst/paranoia.sbk
+sparc/solaris/tst/sort.1bk
+sparc/solaris/tst/sort.2bk
+sparc/solaris/tst/sort.sbk
+sparc/solaris/tst/spill.1bk
+sparc/solaris/tst/spill.2bk
+sparc/solaris/tst/spill.sbk
+sparc/solaris/tst/stdarg.1bk
+sparc/solaris/tst/stdarg.2bk
+sparc/solaris/tst/stdarg.sbk
+sparc/solaris/tst/struct.1bk
+sparc/solaris/tst/struct.2bk
+sparc/solaris/tst/struct.sbk
+sparc/solaris/tst/switch.1bk
+sparc/solaris/tst/switch.2bk
+sparc/solaris/tst/switch.sbk
+sparc/solaris/tst/wf1.1bk
+sparc/solaris/tst/wf1.2bk
+sparc/solaris/tst/wf1.sbk
+sparc/solaris/tst/yacc.1bk
+sparc/solaris/tst/yacc.2bk
+sparc/solaris/tst/yacc.sbk
+mips/irix/tst/8q.1bk
+mips/irix/tst/8q.2bk
+mips/irix/tst/8q.sbk
+mips/irix/tst/array.1bk
+mips/irix/tst/array.2bk
+mips/irix/tst/array.sbk
+mips/irix/tst/cf.1bk
+mips/irix/tst/cf.2bk
+mips/irix/tst/cf.sbk
+mips/irix/tst/cq.1bk
+mips/irix/tst/cq.2bk
+mips/irix/tst/cq.sbk
+mips/irix/tst/cvt.1bk
+mips/irix/tst/cvt.2bk
+mips/irix/tst/cvt.sbk
+mips/irix/tst/fields.1bk
+mips/irix/tst/fields.2bk
+mips/irix/tst/fields.sbk
+mips/irix/tst/front.2bk
+mips/irix/tst/front.sbk
+mips/irix/tst/incr.2bk
+mips/irix/tst/incr.sbk
+mips/irix/tst/init.1bk
+mips/irix/tst/init.2bk
+mips/irix/tst/init.sbk
+mips/irix/tst/limits.1bk
+mips/irix/tst/limits.2bk
+mips/irix/tst/limits.sbk
+mips/irix/tst/paranoia.1bk
+mips/irix/tst/paranoia.2bk
+mips/irix/tst/paranoia.sbk
+mips/irix/tst/sort.1bk
+mips/irix/tst/sort.2bk
+mips/irix/tst/sort.sbk
+mips/irix/tst/spill.2bk
+mips/irix/tst/spill.sbk
+mips/irix/tst/stdarg.1bk
+mips/irix/tst/stdarg.2bk
+mips/irix/tst/stdarg.sbk
+mips/irix/tst/struct.1bk
+mips/irix/tst/struct.2bk
+mips/irix/tst/struct.sbk
+mips/irix/tst/switch.1bk
+mips/irix/tst/switch.2bk
+mips/irix/tst/switch.sbk
+mips/irix/tst/wf1.1bk
+mips/irix/tst/wf1.2bk
+mips/irix/tst/wf1.sbk
+mips/irix/tst/yacc.1bk
+mips/irix/tst/yacc.2bk
+mips/irix/tst/yacc.sbk
+x86/linux/tst/8q.1bk
+x86/linux/tst/8q.2bk
+x86/linux/tst/8q.sbk
+x86/linux/tst/array.1bk
+x86/linux/tst/array.2bk
+x86/linux/tst/array.sbk
+x86/linux/tst/cf.1bk
+x86/linux/tst/cf.2bk
+x86/linux/tst/cf.sbk
+x86/linux/tst/cq.1bk
+x86/linux/tst/cq.2bk
+x86/linux/tst/cq.sbk
+x86/linux/tst/cvt.1bk
+x86/linux/tst/cvt.2bk
+x86/linux/tst/cvt.sbk
+x86/linux/tst/fields.1bk
+x86/linux/tst/fields.2bk
+x86/linux/tst/fields.sbk
+x86/linux/tst/front.2bk
+x86/linux/tst/front.sbk
+x86/linux/tst/incr.1bk
+x86/linux/tst/incr.2bk
+x86/linux/tst/incr.sbk
+x86/linux/tst/init.1bk
+x86/linux/tst/init.2bk
+x86/linux/tst/init.sbk
+x86/linux/tst/limits.1bk
+x86/linux/tst/limits.2bk
+x86/linux/tst/limits.sbk
+x86/linux/tst/paranoia.1bk
+x86/linux/tst/paranoia.2bk
+x86/linux/tst/paranoia.sbk
+x86/linux/tst/sort.1bk
+x86/linux/tst/sort.2bk
+x86/linux/tst/sort.sbk
+x86/linux/tst/spill.1bk
+x86/linux/tst/spill.2bk
+x86/linux/tst/spill.sbk
+x86/linux/tst/stdarg.1bk
+x86/linux/tst/stdarg.2bk
+x86/linux/tst/stdarg.sbk
+x86/linux/tst/struct.1bk
+x86/linux/tst/struct.2bk
+x86/linux/tst/struct.sbk
+x86/linux/tst/switch.1bk
+x86/linux/tst/switch.2bk
+x86/linux/tst/switch.sbk
+x86/linux/tst/wf1.1bk
+x86/linux/tst/wf1.2bk
+x86/linux/tst/wf1.sbk
+x86/linux/tst/yacc.1bk
+x86/linux/tst/yacc.2bk
+x86/linux/tst/yacc.sbk
+x86/win32/tst/8q.1bk
+x86/win32/tst/8q.2bk
+x86/win32/tst/8q.sbk
+x86/win32/tst/array.1bk
+x86/win32/tst/array.2bk
+x86/win32/tst/array.sbk
+x86/win32/tst/cf.1bk
+x86/win32/tst/cf.2bk
+x86/win32/tst/cf.sbk
+x86/win32/tst/cq.1bk
+x86/win32/tst/cq.2bk
+x86/win32/tst/cq.sbk
+x86/win32/tst/cvt.1bk
+x86/win32/tst/cvt.2bk
+x86/win32/tst/cvt.sbk
+x86/win32/tst/fields.1bk
+x86/win32/tst/fields.2bk
+x86/win32/tst/fields.sbk
+x86/win32/tst/front.2bk
+x86/win32/tst/front.sbk
+x86/win32/tst/incr.1bk
+x86/win32/tst/incr.2bk
+x86/win32/tst/incr.sbk
+x86/win32/tst/init.1bk
+x86/win32/tst/init.2bk
+x86/win32/tst/init.sbk
+x86/win32/tst/limits.1bk
+x86/win32/tst/limits.2bk
+x86/win32/tst/limits.sbk
+x86/win32/tst/paranoia.1bk
+x86/win32/tst/paranoia.2bk
+x86/win32/tst/paranoia.sbk
+x86/win32/tst/sort.1bk
+x86/win32/tst/sort.2bk
+x86/win32/tst/sort.sbk
+x86/win32/tst/spill.1bk
+x86/win32/tst/spill.2bk
+x86/win32/tst/spill.sbk
+x86/win32/tst/stdarg.1bk
+x86/win32/tst/stdarg.2bk
+x86/win32/tst/stdarg.sbk
+x86/win32/tst/struct.1bk
+x86/win32/tst/struct.2bk
+x86/win32/tst/struct.sbk
+x86/win32/tst/switch.1bk
+x86/win32/tst/switch.2bk
+x86/win32/tst/switch.sbk
+x86/win32/tst/wf1.1bk
+x86/win32/tst/wf1.2bk
+x86/win32/tst/wf1.sbk
+x86/win32/tst/yacc.1bk
+x86/win32/tst/yacc.2bk
+x86/win32/tst/yacc.sbk
+custom.mk
+packing.lst
diff --git a/lcc/sparc/solaris/tst/8q.1bk b/lcc/sparc/solaris/tst/8q.1bk
new file mode 100755
index 0000000..c66df8e
--- /dev/null
+++ b/lcc/sparc/solaris/tst/8q.1bk
@@ -0,0 +1,92 @@
+1 5 8 6 3 7 2 4
+1 6 8 3 7 4 2 5
+1 7 4 6 8 2 5 3
+1 7 5 8 2 4 6 3
+2 4 6 8 3 1 7 5
+2 5 7 1 3 8 6 4
+2 5 7 4 1 8 6 3
+2 6 1 7 4 8 3 5
+2 6 8 3 1 4 7 5
+2 7 3 6 8 5 1 4
+2 7 5 8 1 4 6 3
+2 8 6 1 3 5 7 4
+3 1 7 5 8 2 4 6
+3 5 2 8 1 7 4 6
+3 5 2 8 6 4 7 1
+3 5 7 1 4 2 8 6
+3 5 8 4 1 7 2 6
+3 6 2 5 8 1 7 4
+3 6 2 7 1 4 8 5
+3 6 2 7 5 1 8 4
+3 6 4 1 8 5 7 2
+3 6 4 2 8 5 7 1
+3 6 8 1 4 7 5 2
+3 6 8 1 5 7 2 4
+3 6 8 2 4 1 7 5
+3 7 2 8 5 1 4 6
+3 7 2 8 6 4 1 5
+3 8 4 7 1 6 2 5
+4 1 5 8 2 7 3 6
+4 1 5 8 6 3 7 2
+4 2 5 8 6 1 3 7
+4 2 7 3 6 8 1 5
+4 2 7 3 6 8 5 1
+4 2 7 5 1 8 6 3
+4 2 8 5 7 1 3 6
+4 2 8 6 1 3 5 7
+4 6 1 5 2 8 3 7
+4 6 8 2 7 1 3 5
+4 6 8 3 1 7 5 2
+4 7 1 8 5 2 6 3
+4 7 3 8 2 5 1 6
+4 7 5 2 6 1 3 8
+4 7 5 3 1 6 8 2
+4 8 1 3 6 2 7 5
+4 8 1 5 7 2 6 3
+4 8 5 3 1 7 2 6
+5 1 4 6 8 2 7 3
+5 1 8 4 2 7 3 6
+5 1 8 6 3 7 2 4
+5 2 4 6 8 3 1 7
+5 2 4 7 3 8 6 1
+5 2 6 1 7 4 8 3
+5 2 8 1 4 7 3 6
+5 3 1 6 8 2 4 7
+5 3 1 7 2 8 6 4
+5 3 8 4 7 1 6 2
+5 7 1 3 8 6 4 2
+5 7 1 4 2 8 6 3
+5 7 2 4 8 1 3 6
+5 7 2 6 3 1 4 8
+5 7 2 6 3 1 8 4
+5 7 4 1 3 8 6 2
+5 8 4 1 3 6 2 7
+5 8 4 1 7 2 6 3
+6 1 5 2 8 3 7 4
+6 2 7 1 3 5 8 4
+6 2 7 1 4 8 5 3
+6 3 1 7 5 8 2 4
+6 3 1 8 4 2 7 5
+6 3 1 8 5 2 4 7
+6 3 5 7 1 4 2 8
+6 3 5 8 1 4 2 7
+6 3 7 2 4 8 1 5
+6 3 7 2 8 5 1 4
+6 3 7 4 1 8 2 5
+6 4 1 5 8 2 7 3
+6 4 2 8 5 7 1 3
+6 4 7 1 3 5 2 8
+6 4 7 1 8 2 5 3
+6 8 2 4 1 7 5 3
+7 1 3 8 6 4 2 5
+7 2 4 1 8 5 3 6
+7 2 6 3 1 4 8 5
+7 3 1 6 8 5 2 4
+7 3 8 2 5 1 6 4
+7 4 2 5 8 1 3 6
+7 4 2 8 6 1 3 5
+7 5 3 1 6 8 2 4
+8 2 4 1 7 5 3 6
+8 2 5 3 1 7 4 6
+8 3 1 6 2 5 7 4
+8 4 1 3 6 2 7 5
diff --git a/lcc/sparc/solaris/tst/8q.2bk b/lcc/sparc/solaris/tst/8q.2bk
new file mode 100755
index 0000000..fb28350
--- /dev/null
+++ b/lcc/sparc/solaris/tst/8q.2bk
@@ -0,0 +1,2 @@
+tst/8q.c:30: warning: missing return value
+tst/8q.c:39: warning: missing return value
diff --git a/lcc/sparc/solaris/tst/8q.sbk b/lcc/sparc/solaris/tst/8q.sbk
new file mode 100755
index 0000000..5418dd7
--- /dev/null
+++ b/lcc/sparc/solaris/tst/8q.sbk
@@ -0,0 +1,144 @@
+.global main
+.section ".text"
+.align 4
+main:
+save %sp,-96,%sp
+mov %g0,%i5
+.L2:
+sll %i5,2,%i4
+set 1,%i3
+set down,%i2
+st %i3,[%i4+%i2]
+set up,%i2
+st %i3,[%i4+%i2]
+.L3:
+add %i5,1,%i5
+cmp %i5,15; bl .L2; nop
+mov %g0,%i5
+.L6:
+sll %i5,2,%i4
+set rows,%i3
+set 1,%i2
+st %i2,[%i4+%i3]
+.L7:
+add %i5,1,%i5
+cmp %i5,8; bl .L6; nop
+mov %g0,%o0
+call queens; nop
+mov %g0,%i0
+.L1:
+ret; restore
+.type main,#function
+.size main,.-main
+.global queens
+.align 4
+queens:
+save %sp,-96,%sp
+mov %g0,%i5
+.L11:
+sll %i5,2,%i3
+set rows,%i2
+ld [%i3+%i2],%i3
+cmp %i3,%g0; be .L15; nop
+sub %i5,%i0,%i3
+sll %i3,2,%i3
+set up+28,%i2
+ld [%i3+%i2],%i3
+cmp %i3,%g0; be .L15; nop
+add %i5,%i0,%i3
+sll %i3,2,%i3
+set down,%i2
+ld [%i3+%i2],%i3
+cmp %i3,%g0; be .L15; nop
+add %i5,%i0,%i3
+sll %i3,2,%i3
+set down,%i2
+st %g0,[%i3+%i2]
+sub %i5,%i0,%i3
+sll %i3,2,%i3
+set up+28,%i2
+st %g0,[%i3+%i2]
+sll %i5,2,%i3
+set rows,%i2
+st %g0,[%i3+%i2]
+sll %i0,2,%i4
+set x,%i3
+st %i5,[%i4+%i3]
+cmp %i0,7; bne .L19; nop
+call print; nop
+ba .L20; nop
+.L19:
+add %i0,1,%o0
+call queens; nop
+.L20:
+set 1,%i4
+add %i5,%i0,%i3
+sll %i3,2,%i3
+set down,%i2
+st %i4,[%i3+%i2]
+sub %i5,%i0,%i3
+sll %i3,2,%i3
+set up+28,%i2
+st %i4,[%i3+%i2]
+sll %i5,2,%i3
+set rows,%i2
+st %i4,[%i3+%i2]
+.L15:
+.L12:
+add %i5,1,%i5
+cmp %i5,8; bl .L11; nop
+mov %g0,%i0
+.L10:
+ret; restore
+.type queens,#function
+.size queens,.-queens
+.global print
+.align 4
+print:
+save %sp,-96,%sp
+mov %g0,%i5
+.L23:
+set .L27,%o0
+sll %i5,2,%i4
+set x,%i3
+ld [%i4+%i3],%i4
+add %i4,49,%o1
+call printf; nop
+.L24:
+add %i5,1,%i5
+cmp %i5,8; bl .L23; nop
+set .L28,%o0
+call printf; nop
+mov %g0,%i0
+.L22:
+ret; restore
+.type print,#function
+.size print,.-print
+.section ".bss"
+.global x
+.type x,#object
+.size x,32
+.common x,32,4
+.global rows
+.type rows,#object
+.size rows,32
+.common rows,32,4
+.global down
+.type down,#object
+.size down,60
+.common down,60,4
+.global up
+.type up,#object
+.size up,60
+.common up,60,4
+.section ".rodata"
+.align 1
+.L28:
+.byte 10
+.byte 0
+.align 1
+.L27:
+.byte 37
+.byte 99
+.byte 32
+.byte 0
diff --git a/lcc/sparc/solaris/tst/array.1bk b/lcc/sparc/solaris/tst/array.1bk
new file mode 100755
index 0000000..e188568
--- /dev/null
+++ b/lcc/sparc/solaris/tst/array.1bk
@@ -0,0 +1,4 @@
+ 0 1 2 3 1000 1001 1002 1003 2000 2001 2002 2003
+ 0 1 2 3 1000 1001 1002 1003 2000 2001 2002 2003
+ 0 1 2 3 1000 1001 1002 1003 2000 2001 2002 2003
+ 0 1 2 3 1000 1001 1002 1003 2000 2001 2002 2003
diff --git a/lcc/sparc/solaris/tst/array.2bk b/lcc/sparc/solaris/tst/array.2bk
new file mode 100755
index 0000000..0a9b206
--- /dev/null
+++ b/lcc/sparc/solaris/tst/array.2bk
@@ -0,0 +1,2 @@
+tst/array.c:33: warning: missing return value
+tst/array.c:48: warning: missing return value
diff --git a/lcc/sparc/solaris/tst/array.sbk b/lcc/sparc/solaris/tst/array.sbk
new file mode 100755
index 0000000..2dead90
--- /dev/null
+++ b/lcc/sparc/solaris/tst/array.sbk
@@ -0,0 +1,172 @@
+.global main
+.section ".text"
+.align 4
+main:
+save %sp,-144,%sp
+mov %g0,%i4
+.L2:
+mov %g0,%i5
+.L6:
+sll %i5,2,%i2
+sll %i4,4,%i1
+set x,%i0
+add %i1,%i0,%i1
+smul %i4,1000,%i0
+add %i0,%i5,%i0
+st %i0,[%i2+%i1]
+.L7:
+add %i5,1,%i5
+cmp %i5,4; bl .L6; nop
+sll %i4,2,%i2
+set y,%i1
+sll %i4,4,%i0
+set x,%l7
+add %i0,%l7,%i0
+st %i0,[%i2+%i1]
+.L3:
+add %i4,1,%i4
+cmp %i4,3; bl .L2; nop
+call f; nop
+mov %g0,%i4
+.L10:
+sll %i4,4,%i2
+add -48,%fp,%i1
+add %i2,%i1,%i2
+mov %i2,%i3
+sll %i4,2,%i1
+set y,%i0
+st %i2,[%i1+%i0]
+mov %g0,%i5
+.L14:
+sll %i5,2,%i2
+sll %i4,4,%i1
+set x,%i0
+add %i1,%i0,%i1
+ld [%i2+%i1],%i1
+st %i1,[%i2+%i3]
+.L15:
+add %i5,1,%i5
+cmp %i5,4; bl .L14; nop
+.L11:
+add %i4,1,%i4
+cmp %i4,3; bl .L10; nop
+add -48,%fp,%o0
+set y,%o1
+call g; nop
+mov %g0,%i0
+.L1:
+ret; restore
+.type main,#function
+.size main,.-main
+.global f
+.align 4
+f:
+save %sp,-96,%sp
+mov %g0,%i4
+.L19:
+mov %g0,%i5
+.L23:
+set .L27,%o0
+sll %i5,2,%i3
+sll %i4,4,%i2
+set x,%i1
+add %i2,%i1,%i2
+ld [%i3+%i2],%o1
+call printf; nop
+.L24:
+add %i5,1,%i5
+cmp %i5,4; bl .L23; nop
+.L20:
+add %i4,1,%i4
+cmp %i4,3; bl .L19; nop
+set .L28,%o0
+call printf; nop
+mov %g0,%i4
+.L29:
+mov %g0,%i5
+.L33:
+set .L27,%o0
+sll %i5,2,%i3
+sll %i4,2,%i2
+set y,%i1
+ld [%i2+%i1],%i2
+ld [%i3+%i2],%o1
+call printf; nop
+.L34:
+add %i5,1,%i5
+cmp %i5,4; bl .L33; nop
+.L30:
+add %i4,1,%i4
+cmp %i4,3; bl .L29; nop
+set .L28,%o0
+call printf; nop
+mov %g0,%i0
+.L18:
+ret; restore
+.type f,#function
+.size f,.-f
+.global g
+.align 4
+g:
+save %sp,-96,%sp
+mov %g0,%i4
+.L38:
+mov %g0,%i5
+.L42:
+set .L27,%o0
+sll %i5,2,%i3
+sll %i4,4,%i2
+add %i2,%i0,%i2
+ld [%i3+%i2],%o1
+call printf; nop
+.L43:
+add %i5,1,%i5
+cmp %i5,4; bl .L42; nop
+.L39:
+add %i4,1,%i4
+cmp %i4,3; bl .L38; nop
+set .L28,%o0
+call printf; nop
+mov %g0,%i4
+.L46:
+mov %g0,%i5
+.L50:
+set .L27,%o0
+sll %i5,2,%i3
+sll %i4,2,%i2
+ld [%i2+%i1],%i2
+ld [%i3+%i2],%o1
+call printf; nop
+.L51:
+add %i5,1,%i5
+cmp %i5,4; bl .L50; nop
+.L47:
+add %i4,1,%i4
+cmp %i4,3; bl .L46; nop
+set .L28,%o0
+call printf; nop
+mov %g0,%i0
+.L37:
+ret; restore
+.type g,#function
+.size g,.-g
+.section ".bss"
+.global y
+.type y,#object
+.size y,12
+.common y,12,4
+.global x
+.type x,#object
+.size x,48
+.common x,48,4
+.section ".rodata"
+.align 1
+.L28:
+.byte 10
+.byte 0
+.align 1
+.L27:
+.byte 32
+.byte 37
+.byte 100
+.byte 0
diff --git a/lcc/sparc/solaris/tst/cf.1bk b/lcc/sparc/solaris/tst/cf.1bk
new file mode 100755
index 0000000..24e21ba
--- /dev/null
+++ b/lcc/sparc/solaris/tst/cf.1bk
@@ -0,0 +1,51 @@
+char freq
+011 8.1
+012 6.1
+040 11.9
+! 0.2
+" 1.5
+% 0.6
+& 0.4
+' 0.4
+( 2.9
+) 2.9
+* 0.8
++ 1.3
+, 1.3
+- 0.4
+. 0.6
+/ 1.0
+0 2.5
+1 1.9
+2 0.6
+3 0.2
+7 0.4
+8 0.2
+; 3.8
+< 0.8
+= 2.7
+> 0.2
+[ 1.5
+\ 0.8
+] 1.5
+a 3.1
+c 4.4
+e 2.3
+f 6.0
+g 1.3
+h 1.0
+i 5.0
+l 1.0
+m 0.2
+n 3.3
+o 2.1
+p 1.0
+q 0.4
+r 4.2
+s 0.6
+t 3.8
+u 1.2
+v 0.6
+w 0.2
+{ 0.6
+} 0.6
diff --git a/lcc/sparc/solaris/tst/cf.2bk b/lcc/sparc/solaris/tst/cf.2bk
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/sparc/solaris/tst/cf.2bk
diff --git a/lcc/sparc/solaris/tst/cf.sbk b/lcc/sparc/solaris/tst/cf.sbk
new file mode 100755
index 0000000..a9c7d30
--- /dev/null
+++ b/lcc/sparc/solaris/tst/cf.sbk
@@ -0,0 +1,143 @@
+.global main
+.section ".text"
+.align 4
+main:
+save %sp,-96,%sp
+cmp %i0,1; bg .L2; nop
+set .L4,%i2
+ld [%i2],%f31
+st %f31,[%fp+-4]
+ba .L3; nop
+.L2:
+ld [%i1+4],%o0
+call atof; nop
+fmovs %f0,%f31
+set .L5,%i2
+ld [%i2],%f30
+fdivs %f31,%f30,%f31
+st %f31,[%fp+-4]
+.L3:
+mov %g0,%i5
+.L6:
+mov %i5,%i2
+add %i2,1,%i5
+sll %i2,2,%i2
+set f,%l7
+set .L4,%l6
+ld [%l6],%f31
+st %f31,[%i2+%l7]
+.L7:
+cmp %i5,127; ble .L6; nop
+mov %g0,%i4
+ba .L11; nop
+.L10:
+sll %i3,2,%i2
+set f,%l7
+add %i2,%l7,%i2
+ld [%i2],%f31
+set .L13,%l7
+ld [%l7],%f30
+fadds %f31,%f30,%f31
+st %f31,[%i2]
+add %i4,1,%i4
+.L11:
+call getchar; nop
+mov %o0,%i3
+cmp %o0,-1; bne .L10; nop
+set .L14,%o0
+call printf; nop
+mov %g0,%i5
+.L15:
+sll %i5,2,%i2
+set f,%l7
+ld [%i2+%l7],%f31
+set .L4,%i2
+ld [%i2],%f30
+fcmpes %f31,%f30; nop; fbue .L19; nop
+st %i4,[%sp+64]; ld [%sp+64],%f30; fitos %f30,%f30
+fdivs %f31,%f30,%f31
+ld [%fp+-4],%f30
+fcmpes %f31,%f30; nop; fbul .L19; nop
+cmp %i5,32; bg .L21; nop
+set .L23,%o0
+mov %i5,%o1
+call printf; nop
+ba .L22; nop
+.L21:
+set .L24,%o0
+mov %i5,%o1
+call printf; nop
+.L22:
+set .L25,%o0
+set .L5,%i2
+ld [%i2],%f31
+sll %i5,2,%i2
+set f,%l7
+ld [%i2+%l7],%f30
+fmuls %f31,%f30,%f31
+st %i4,[%sp+64]; ld [%sp+64],%f30; fitos %f30,%f30
+fdivs %f31,%f30,%f31
+fstod %f31,%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+.L19:
+.L16:
+add %i5,1,%i5
+cmp %i5,127; ble .L15; nop
+mov %g0,%i0
+.L1:
+ret; restore
+.type main,#function
+.size main,.-main
+.section ".bss"
+.global f
+.type f,#object
+.size f,512
+.common f,512,4
+.section ".rodata"
+.align 1
+.L25:
+.byte 9
+.byte 37
+.byte 46
+.byte 49
+.byte 102
+.byte 10
+.byte 0
+.align 1
+.L24:
+.byte 37
+.byte 99
+.byte 0
+.align 1
+.L23:
+.byte 37
+.byte 48
+.byte 51
+.byte 111
+.byte 0
+.align 1
+.L14:
+.byte 99
+.byte 104
+.byte 97
+.byte 114
+.byte 9
+.byte 102
+.byte 114
+.byte 101
+.byte 113
+.byte 10
+.byte 0
+.align 4
+.L13:
+.word 0x3f800000
+.align 4
+.L5:
+.word 0x42c80000
+.align 4
+.L4:
+.word 0x0
diff --git a/lcc/sparc/solaris/tst/cq.1bk b/lcc/sparc/solaris/tst/cq.1bk
new file mode 100755
index 0000000..b7b7643
--- /dev/null
+++ b/lcc/sparc/solaris/tst/cq.1bk
@@ -0,0 +1,48 @@
+Section s22 returned 0.
+Decimal and octal/hex constants sometimes give
+ different results when assigned to longs.
+Decimal and octal/hex constants sometimes give
+ different results when assigned to longs.
+Section s241 returned 0.
+Section s243 returned 0.
+Section s244 returned 0.
+Section s25 returned 0.
+ 8 bits in chars.
+ 32 bits in ints.
+ 16 bits in shorts.
+ 32 bits in longs.
+ 32 bits in unsigneds.
+ 32 bits in floats.
+ 64 bits in doubles.
+1.192093e-07 is the least number that can be added to 1. (float).
+2.220446e-16 is the least number that can be added to 1. (double).
+Section s26 returned 0.
+Section s4 returned 0.
+Section s61 returned 0.
+Section s626 returned 0.
+Section s71 returned 0.
+Section s72 returned 0.
+Section s757 returned 0.
+Section s7813 returned 0.
+Section s714 returned 0.
+Section s715 returned 0.
+Register count for char is unreliable.
+Register count for pointer is unreliable.
+Register count for int is unreliable.
+Section s81 returned 0.
+Section s84 returned 0.
+char alignment: 1
+short alignment: 2
+int alignment: 4
+long alignment: 4
+unsigned alignment: 4
+float alignment: 4
+double alignment: 8
+Sign extension in fields
+Be especially careful with 1-bit fields!
+Section s85 returned 0.
+Section s86 returned 0.
+Section s88 returned 0.
+Section s9 returned 0.
+
+No errors detected.
diff --git a/lcc/sparc/solaris/tst/cq.2bk b/lcc/sparc/solaris/tst/cq.2bk
new file mode 100755
index 0000000..295f5b6
--- /dev/null
+++ b/lcc/sparc/solaris/tst/cq.2bk
@@ -0,0 +1,25 @@
+tst/cq.c:394: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:394: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:394: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:395: warning: overflow in constant `4294967296'
+tst/cq.c:395: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:395: warning: overflow in constant `040000000000'
+tst/cq.c:395: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:395: warning: overflow in constant `0x100000000'
+tst/cq.c:395: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:396: warning: overflow in constant `68719476735'
+tst/cq.c:396: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:396: warning: overflow in constant `0777777777777'
+tst/cq.c:396: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:396: warning: overflow in constant `0xfffffffff'
+tst/cq.c:396: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:397: warning: overflow in constant `68719476736'
+tst/cq.c:397: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:397: warning: overflow in constant `01000000000000'
+tst/cq.c:397: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:397: warning: overflow in constant `0x1000000000'
+tst/cq.c:397: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:533: warning: missing return value
+tst/cq.c:1169: warning: missing return value
+tst/cq.c:5294: warning: unreachable code
+tst/cq.c:5303: warning: missing return value
diff --git a/lcc/sparc/solaris/tst/cq.sbk b/lcc/sparc/solaris/tst/cq.sbk
new file mode 100755
index 0000000..b924ce4
--- /dev/null
+++ b/lcc/sparc/solaris/tst/cq.sbk
@@ -0,0 +1,13322 @@
+.section ".data"
+.type .2,#object
+.align 4
+.2:
+.word s22
+.word s241
+.word s243
+.word s244
+.word s25
+.word s26
+.word s4
+.word s61
+.word s626
+.word s71
+.word s72
+.word s757
+.word s7813
+.word s714
+.word s715
+.word s81
+.word s84
+.word s85
+.word s86
+.word s88
+.word s9
+.section ".bss"
+.size .2,84
+.type .3,#object
+.size .3,68
+.local .3
+.common .3,68,4
+.type .4,#object
+.size .4,4
+.local .4
+.common .4,4,4
+.global main
+.section ".text"
+.align 4
+main:
+save %sp,-96,%sp
+set .3+36,%i4
+set 1,%i3
+st %i3,[%i4]
+set .3+40,%i4
+set 1,%i3
+st %i3,[%i4]
+set .3+44,%i4
+set 1,%i3
+st %i3,[%i4]
+set .3+48,%i4
+set 1,%i3
+st %i3,[%i4]
+set .4,%i4
+set .3,%i3
+st %i3,[%i4]
+mov %g0,%i5
+ba .L12; nop
+.L9:
+set .4,%i4
+ld [%i4],%o0
+sll %i5,2,%i4
+set .2,%i3
+ld [%i4+%i3],%i4
+call %i4; nop
+set .3+52,%i3
+st %o0,[%i3]
+set .3+56,%i4
+set .3+56,%i3
+ld [%i3],%i3
+set .3+52,%i2
+ld [%i2],%i2
+add %i3,%i2,%i3
+st %i3,[%i4]
+set .3+36,%i4
+ld [%i4],%i4
+cmp %i4,0; be .L17; nop
+set .L20,%o0
+set .3+60,%o1
+set .3+52,%i4
+ld [%i4],%o2
+call printf; nop
+.L17:
+.L10:
+add %i5,1,%i5
+.L12:
+mov %i5,%i4
+set 21,%i3
+cmp %i4,%i3; blu .L9; nop
+set .3+56,%i4
+ld [%i4],%i4
+cmp %i4,0; bne .L23; nop
+set .L26,%o0
+call printf; nop
+ba .L24; nop
+.L23:
+set .L27,%o0
+call printf; nop
+.L24:
+mov %g0,%i0
+.L1:
+ret; restore
+.type main,#function
+.size main,.-main
+.section ".data"
+.type .29,#object
+.align 1
+.29:
+.byte 115
+.byte 50
+.byte 50
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size .29,10
+.type .30,#object
+.size .30,8
+.align 1
+.30:
+.byte 115
+.byte 50
+.byte 50
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.global s22
+.section ".text"
+.align 4
+s22:
+save %sp,-96,%sp
+mov %g0,%i3
+set .30,%i5
+add %i0,60,%i4
+.L31:
+.L32:
+mov %i4,%l4
+add %l4,1,%i4
+mov %i5,%l3
+add %l3,1,%i5
+ldsb [%l3],%l3
+stb %l3,[%l4]
+sll %l3,8*(4-1),%l4; sra %l4,8*(4-1),%l4
+cmp %l4,0; bne .L31; nop
+set 1,%i2
+set 2,%l7
+set 3,%l6
+set 4,%i1
+add %i2,%l7,%l4
+add %l4,%l6,%l4
+add %l4,%i1,%l4
+cmp %l4,10; be .L34; nop
+add %i3,1,%i3
+ld [%i0+44],%l4
+cmp %l4,0; be .L36; nop
+set .29,%o0
+set 1,%o1
+call printf; nop
+.L36:
+.L34:
+set 2,%l5
+cmp %l5,%i2; bne .L38; nop
+add %i3,4,%i3
+ld [%i0+44],%l4
+cmp %l4,0; be .L40; nop
+set .29,%o0
+set 4,%o1
+call printf; nop
+.L40:
+.L38:
+mov %i3,%i0
+.L28:
+ret; restore
+.type s22,#function
+.size s22,.-s22
+.section ".data"
+.type .43,#object
+.align 1
+.43:
+.byte 115
+.byte 50
+.byte 52
+.byte 49
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size .43,11
+.type .44,#object
+.size .44,8
+.align 1
+.44:
+.byte 115
+.byte 50
+.byte 52
+.byte 49
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.type .45,#object
+.size .45,156
+.align 4
+.45:
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x0
+.word 0x6
+.word 0x0
+.word 0x8
+.word 0x0
+.word 0xc
+.word 0x0
+.word 0x10
+.word 0x0
+.word 0x12
+.word 0x0
+.word 0x14
+.word 0x0
+.word 0x18
+.word 0x0
+.word 0x1c
+.word 0x0
+.word 0x1e
+.word 0x0
+.word 0x20
+.word 0x0
+.word 0x24
+.global s241
+.section ".text"
+.align 4
+s241:
+save %sp,-560,%sp
+mov %g0,%i2
+mov %g0,%i1
+set .44,%i4
+add %i0,60,%i3
+.L46:
+.L47:
+mov %i3,%l7
+add %l7,1,%i3
+mov %i4,%l6
+add %l6,1,%i4
+ldsb [%l6],%l6
+stb %l6,[%l7]
+sll %l6,8*(4-1),%l7; sra %l7,8*(4-1),%l7
+cmp %l7,0; bne .L46; nop
+ba .L49; nop
+add %i2,1,%i2
+ld [%i0+44],%l7
+cmp %l7,0; be .L51; nop
+set .43,%o0
+set 1,%o1
+call printf; nop
+.L51:
+.L49:
+ba .L53; nop
+add %i2,2,%i2
+ld [%i0+44],%l7
+cmp %l7,0; be .L55; nop
+set .43,%o0
+set 2,%o1
+call printf; nop
+.L55:
+.L53:
+ba .L57; nop
+add %i2,4,%i2
+ld [%i0+44],%l7
+cmp %l7,0; be .L59; nop
+set .43,%o0
+set 4,%o1
+call printf; nop
+.L59:
+.L57:
+ba .L61; nop
+add %i2,8,%i2
+ld [%i0+44],%l7
+cmp %l7,0; be .L63; nop
+set .43,%o0
+set 8,%o1
+call printf; nop
+.L63:
+.L61:
+mov %g0,%i5
+.L65:
+sll %i5,2,%l7
+set .45,%l6
+st %i5,[%l7+%l6]
+.L66:
+add %i5,1,%i5
+cmp %i5,17; bl .L65; nop
+set 18,%i5
+.L69:
+sll %i5,2,%l7
+set .45,%l6
+add %l7,%l6,%l7
+ld [%l7],%o0
+call pow2; nop
+st %o0,[%l7]
+sll %i5,2,%l7
+set .45-4,%l6
+set .45,%l5
+ld [%l7+%l5],%l5
+sub %l5,1,%l5
+st %l5,[%l7+%l6]
+add %i5,2,%i5
+.L70:
+cmp %i5,39; bl .L69; nop
+st %g0,[%fp+-156]
+st %g0,[%fp+-312]
+st %g0,[%fp+-468]
+set 1,%l7
+st %l7,[%fp+-152]
+set 1,%l7
+st %l7,[%fp+-308]
+set 1,%l7
+st %l7,[%fp+-464]
+set 2,%l7
+st %l7,[%fp+-148]
+set 2,%l7
+st %l7,[%fp+-304]
+set 2,%l7
+st %l7,[%fp+-460]
+set 3,%l7
+st %l7,[%fp+-144]
+set 3,%l7
+st %l7,[%fp+-300]
+set 3,%l7
+st %l7,[%fp+-456]
+set 4,%l7
+st %l7,[%fp+-140]
+set 4,%l7
+st %l7,[%fp+-296]
+set 4,%l7
+st %l7,[%fp+-452]
+set 5,%l7
+st %l7,[%fp+-136]
+set 5,%l7
+st %l7,[%fp+-292]
+set 5,%l7
+st %l7,[%fp+-448]
+set 6,%l7
+st %l7,[%fp+-132]
+set 6,%l7
+st %l7,[%fp+-288]
+set 6,%l7
+st %l7,[%fp+-444]
+set 7,%l7
+st %l7,[%fp+-128]
+set 7,%l7
+st %l7,[%fp+-284]
+set 7,%l7
+st %l7,[%fp+-440]
+set 8,%l7
+st %l7,[%fp+-124]
+set 8,%l7
+st %l7,[%fp+-280]
+set 8,%l7
+st %l7,[%fp+-436]
+set 9,%l7
+st %l7,[%fp+-120]
+set 9,%l7
+st %l7,[%fp+-276]
+set 9,%l7
+st %l7,[%fp+-432]
+set 10,%l7
+st %l7,[%fp+-116]
+set 10,%l7
+st %l7,[%fp+-272]
+set 10,%l7
+st %l7,[%fp+-428]
+set 11,%l7
+st %l7,[%fp+-112]
+set 11,%l7
+st %l7,[%fp+-268]
+set 11,%l7
+st %l7,[%fp+-424]
+set 12,%l7
+st %l7,[%fp+-108]
+set 12,%l7
+st %l7,[%fp+-264]
+set 12,%l7
+st %l7,[%fp+-420]
+set 13,%l7
+st %l7,[%fp+-104]
+set 13,%l7
+st %l7,[%fp+-260]
+set 13,%l7
+st %l7,[%fp+-416]
+set 14,%l7
+st %l7,[%fp+-100]
+set 14,%l7
+st %l7,[%fp+-256]
+set 14,%l7
+st %l7,[%fp+-412]
+set 15,%l7
+st %l7,[%fp+-96]
+set 15,%l7
+st %l7,[%fp+-252]
+set 15,%l7
+st %l7,[%fp+-408]
+set 16,%l7
+st %l7,[%fp+-92]
+set 16,%l7
+st %l7,[%fp+-248]
+set 16,%l7
+st %l7,[%fp+-404]
+set 63,%l7
+st %l7,[%fp+-88]
+set 63,%l7
+st %l7,[%fp+-244]
+set 63,%l7
+st %l7,[%fp+-400]
+set 64,%l7
+st %l7,[%fp+-84]
+set 64,%l7
+st %l7,[%fp+-240]
+set 64,%l7
+st %l7,[%fp+-396]
+set 255,%l7
+st %l7,[%fp+-80]
+set 255,%l7
+st %l7,[%fp+-236]
+set 255,%l7
+st %l7,[%fp+-392]
+set 256,%l7
+st %l7,[%fp+-76]
+set 256,%l7
+st %l7,[%fp+-232]
+set 256,%l7
+st %l7,[%fp+-388]
+set 4095,%l7
+st %l7,[%fp+-72]
+set 4095,%l7
+st %l7,[%fp+-228]
+set 4095,%l7
+st %l7,[%fp+-384]
+set 4096,%l7
+st %l7,[%fp+-68]
+set 4096,%l7
+st %l7,[%fp+-224]
+set 4096,%l7
+st %l7,[%fp+-380]
+set 65535,%l7
+st %l7,[%fp+-64]
+set 65535,%l7
+st %l7,[%fp+-220]
+set 65535,%l7
+st %l7,[%fp+-376]
+set 65536,%l7
+st %l7,[%fp+-60]
+set 65536,%l7
+st %l7,[%fp+-216]
+set 65536,%l7
+st %l7,[%fp+-372]
+set 262143,%l7
+st %l7,[%fp+-56]
+set 262143,%l7
+st %l7,[%fp+-212]
+set 262143,%l7
+st %l7,[%fp+-368]
+set 262144,%l7
+st %l7,[%fp+-52]
+set 262144,%l7
+st %l7,[%fp+-208]
+set 262144,%l7
+st %l7,[%fp+-364]
+set 1048575,%l7
+st %l7,[%fp+-48]
+set 1048575,%l7
+st %l7,[%fp+-204]
+set 1048575,%l7
+st %l7,[%fp+-360]
+set 1048576,%l7
+st %l7,[%fp+-44]
+set 1048576,%l7
+st %l7,[%fp+-200]
+set 1048576,%l7
+st %l7,[%fp+-356]
+set 16777215,%l7
+st %l7,[%fp+-40]
+set 16777215,%l7
+st %l7,[%fp+-196]
+set 16777215,%l7
+st %l7,[%fp+-352]
+set 16777216,%l7
+st %l7,[%fp+-36]
+set 16777216,%l7
+st %l7,[%fp+-192]
+set 16777216,%l7
+st %l7,[%fp+-348]
+set 268435455,%l7
+st %l7,[%fp+-32]
+set 268435455,%l7
+st %l7,[%fp+-188]
+set 268435455,%l7
+st %l7,[%fp+-344]
+set 268435456,%l7
+st %l7,[%fp+-28]
+set 268435456,%l7
+st %l7,[%fp+-184]
+set 268435456,%l7
+st %l7,[%fp+-340]
+set 1073741823,%l7
+st %l7,[%fp+-24]
+set 1073741823,%l7
+st %l7,[%fp+-180]
+set 1073741823,%l7
+st %l7,[%fp+-336]
+set 1073741824,%l7
+st %l7,[%fp+-20]
+set 1073741824,%l7
+st %l7,[%fp+-176]
+set 1073741824,%l7
+st %l7,[%fp+-332]
+set 0xffffffff,%l7
+st %l7,[%fp+-16]
+set 0xffffffff,%l7
+st %l7,[%fp+-172]
+set 0xffffffff,%l7
+st %l7,[%fp+-328]
+set 0xffffffff,%l7
+st %l7,[%fp+-12]
+set 0xffffffff,%l7
+st %l7,[%fp+-168]
+set 0xffffffff,%l7
+st %l7,[%fp+-324]
+set 0xffffffff,%l7
+st %l7,[%fp+-8]
+set 0xffffffff,%l7
+st %l7,[%fp+-164]
+set 0xffffffff,%l7
+st %l7,[%fp+-320]
+set 0xffffffff,%l7
+st %l7,[%fp+-4]
+set 0xffffffff,%l7
+st %l7,[%fp+-160]
+set 0xffffffff,%l7
+st %l7,[%fp+-316]
+mov %g0,%i5
+.L188:
+sll %i5,2,%l7
+add -156,%fp,%l6
+ld [%l7+%l6],%l6
+set .45,%l5
+ld [%l7+%l5],%l5
+cmp %l5,%l6; bne .L195; nop
+add -312,%fp,%l5
+ld [%l7+%l5],%l5
+cmp %l6,%l5; bne .L195; nop
+add -468,%fp,%l6
+ld [%l7+%l6],%l7
+cmp %l5,%l7; be .L192; nop
+.L195:
+ld [%i0+40],%l7
+cmp %l7,0; be .L196; nop
+set .L198,%o0
+call printf; nop
+set .L199,%o0
+call printf; nop
+.L196:
+.L192:
+.L189:
+add %i5,1,%i5
+cmp %i5,39; bl .L188; nop
+cmp %i1,0; be .L200; nop
+set 16,%i2
+.L200:
+mov %i2,%i0
+.L42:
+ret; restore
+.type s241,#function
+.size s241,.-s241
+.global pow2
+.align 4
+pow2:
+set 1,%o5
+ba .L204; nop
+.L203:
+sll %o5,1,%o5
+.L204:
+mov %o0,%o4
+sub %o4,1,%o0
+cmp %o4,0; bne .L203; nop
+mov %o5,%o0
+.L202:
+retl; nop
+.type pow2,#function
+.size pow2,.-pow2
+.section ".data"
+.type .207,#object
+.align 1
+.207:
+.byte 115
+.byte 50
+.byte 52
+.byte 51
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size .207,11
+.type .208,#object
+.size .208,8
+.align 1
+.208:
+.byte 115
+.byte 50
+.byte 52
+.byte 51
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.global s243
+.section ".text"
+.align 4
+s243:
+save %sp,-352,%sp
+mov %g0,%i3
+set .208,%i5
+add %i0,60,%i4
+.L209:
+.L210:
+mov %i4,%i2
+add %i2,1,%i4
+mov %i5,%i1
+add %i1,1,%i5
+ldsb [%i1],%i1
+stb %i1,[%i2]
+sll %i1,8*(4-1),%i2; sra %i2,8*(4-1),%i2
+cmp %i2,0; bne .L209; nop
+add -256,%fp,%o0
+call zerofill; nop
+set 1,%i2
+stb %i2,[%fp+-159]
+set 1,%i2
+stb %i2,[%fp+-191]
+set 1,%i2
+stb %i2,[%fp+-130]
+set 1,%i2
+stb %i2,[%fp+-208]
+set 1,%i2
+stb %i2,[%fp+-158]
+set 1,%i2
+stb %i2,[%fp+-190]
+set 1,%i2
+stb %i2,[%fp+-223]
+set 1,%i2
+stb %i2,[%fp+-207]
+set 1,%i2
+stb %i2,[%fp+-157]
+set 1,%i2
+stb %i2,[%fp+-189]
+set 1,%i2
+stb %i2,[%fp+-222]
+set 1,%i2
+stb %i2,[%fp+-206]
+set 1,%i2
+stb %i2,[%fp+-156]
+set 1,%i2
+stb %i2,[%fp+-188]
+set 1,%i2
+stb %i2,[%fp+-221]
+set 1,%i2
+stb %i2,[%fp+-205]
+set 1,%i2
+stb %i2,[%fp+-155]
+set 1,%i2
+stb %i2,[%fp+-187]
+set 1,%i2
+stb %i2,[%fp+-219]
+set 1,%i2
+stb %i2,[%fp+-204]
+set 1,%i2
+stb %i2,[%fp+-154]
+set 1,%i2
+stb %i2,[%fp+-186]
+set 1,%i2
+stb %i2,[%fp+-218]
+set 1,%i2
+stb %i2,[%fp+-203]
+set 1,%i2
+stb %i2,[%fp+-153]
+set 1,%i2
+stb %i2,[%fp+-185]
+set 1,%i2
+stb %i2,[%fp+-216]
+set 1,%i2
+stb %i2,[%fp+-202]
+set 1,%i2
+stb %i2,[%fp+-152]
+set 1,%i2
+stb %i2,[%fp+-184]
+set 1,%i2
+stb %i2,[%fp+-215]
+set 1,%i2
+stb %i2,[%fp+-201]
+set 1,%i2
+stb %i2,[%fp+-151]
+set 1,%i2
+stb %i2,[%fp+-183]
+set 1,%i2
+stb %i2,[%fp+-161]
+set 1,%i2
+stb %i2,[%fp+-200]
+set 1,%i2
+stb %i2,[%fp+-150]
+set 1,%i2
+stb %i2,[%fp+-182]
+set 1,%i2
+stb %i2,[%fp+-195]
+set 1,%i2
+stb %i2,[%fp+-199]
+set 1,%i2
+stb %i2,[%fp+-149]
+set 1,%i2
+stb %i2,[%fp+-181]
+set 1,%i2
+stb %i2,[%fp+-211]
+set 1,%i2
+stb %i2,[%fp+-148]
+set 1,%i2
+stb %i2,[%fp+-180]
+set 1,%i2
+stb %i2,[%fp+-162]
+set 1,%i2
+stb %i2,[%fp+-147]
+set 1,%i2
+stb %i2,[%fp+-179]
+set 1,%i2
+stb %i2,[%fp+-132]
+set 1,%i2
+stb %i2,[%fp+-246]
+set 1,%i2
+stb %i2,[%fp+-146]
+set 1,%i2
+stb %i2,[%fp+-178]
+set 1,%i2
+stb %i2,[%fp+-247]
+set 1,%i2
+stb %i2,[%fp+-145]
+set 1,%i2
+stb %i2,[%fp+-177]
+set 1,%i2
+stb %i2,[%fp+-133]
+set 1,%i2
+stb %i2,[%fp+-248]
+set 1,%i2
+stb %i2,[%fp+-144]
+set 1,%i2
+stb %i2,[%fp+-176]
+set 1,%i2
+stb %i2,[%fp+-131]
+set 1,%i2
+stb %i2,[%fp+-243]
+set 1,%i2
+stb %i2,[%fp+-143]
+set 1,%i2
+stb %i2,[%fp+-175]
+set 1,%i2
+stb %i2,[%fp+-165]
+set 1,%i2
+stb %i2,[%fp+-244]
+set 1,%i2
+stb %i2,[%fp+-142]
+set 1,%i2
+stb %i2,[%fp+-174]
+set 1,%i2
+stb %i2,[%fp+-163]
+set 1,%i2
+stb %i2,[%fp+-141]
+set 1,%i2
+stb %i2,[%fp+-173]
+set 1,%i2
+stb %i2,[%fp+-213]
+set 1,%i2
+stb %i2,[%fp+-164]
+set 1,%i2
+stb %i2,[%fp+-140]
+set 1,%i2
+stb %i2,[%fp+-172]
+set 1,%i2
+stb %i2,[%fp+-197]
+set 1,%i2
+stb %i2,[%fp+-217]
+set 1,%i2
+stb %i2,[%fp+-139]
+set 1,%i2
+stb %i2,[%fp+-171]
+set 1,%i2
+stb %i2,[%fp+-214]
+set 1,%i2
+stb %i2,[%fp+-138]
+set 1,%i2
+stb %i2,[%fp+-170]
+set 1,%i2
+stb %i2,[%fp+-198]
+set 1,%i2
+stb %i2,[%fp+-256]
+stb %i2,[%fp+-137]
+set 1,%i2
+stb %i2,[%fp+-169]
+set 1,%i2
+stb %i2,[%fp+-196]
+set 1,%i2
+stb %i2,[%fp+-224]
+set 1,%i2
+stb %i2,[%fp+-136]
+set 1,%i2
+stb %i2,[%fp+-168]
+set 1,%i2
+stb %i2,[%fp+-194]
+set 1,%i2
+stb %i2,[%fp+-135]
+set 1,%i2
+stb %i2,[%fp+-167]
+set 1,%i2
+stb %i2,[%fp+-212]
+set 1,%i2
+stb %i2,[%fp+-134]
+set 1,%i2
+stb %i2,[%fp+-166]
+set 1,%i2
+stb %i2,[%fp+-210]
+set 1,%i2
+stb %i2,[%fp+-193]
+set 1,%i2
+stb %i2,[%fp+-209]
+add -256,%fp,%o0
+call sumof; nop
+cmp %o0,98; be .L309; nop
+add %i3,1,%i3
+ld [%i0+44],%i2
+cmp %i2,0; be .L311; nop
+set .207,%o0
+set 1,%o1
+call printf; nop
+.L311:
+.L309:
+ba .L313; nop
+add %i3,8,%i3
+ld [%i0+44],%i2
+cmp %i2,0; be .L315; nop
+set .207,%o0
+set 8,%o1
+call printf; nop
+.L315:
+.L313:
+mov %i3,%i0
+.L206:
+ret; restore
+.type s243,#function
+.size s243,.-s243
+.global zerofill
+.align 4
+zerofill:
+mov %g0,%o5
+.L318:
+mov %o0,%o4
+add %o4,1,%o0
+stb %g0,[%o4]
+.L319:
+add %o5,1,%o5
+cmp %o5,256; bl .L318; nop
+mov %g0,%o0
+.L317:
+retl; nop
+.type zerofill,#function
+.size zerofill,.-zerofill
+.global sumof
+.align 4
+sumof:
+mov %o0,%o3
+mov %g0,%o5
+mov %g0,%o4
+.L323:
+mov %o3,%o2
+add %o2,1,%o3
+ldsb [%o2],%o2
+add %o5,%o2,%o5
+.L324:
+add %o4,1,%o4
+cmp %o4,256; bl .L323; nop
+mov %o5,%o0
+.L322:
+retl; nop
+.type sumof,#function
+.size sumof,.-sumof
+.section ".data"
+.type .328,#object
+.align 1
+.328:
+.byte 115
+.byte 50
+.byte 52
+.byte 52
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size .328,11
+.type .329,#object
+.size .329,8
+.align 1
+.329:
+.byte 115
+.byte 50
+.byte 52
+.byte 52
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.global s244
+.section ".text"
+.align 4
+s244:
+save %sp,-160,%sp
+set .329,%i4
+add %i0,60,%i3
+.L330:
+.L331:
+mov %i3,%l7
+add %l7,1,%i3
+mov %i4,%l6
+add %l6,1,%i4
+ldsb [%l6],%l6
+stb %l6,[%l7]
+sll %l6,8*(4-1),%l7; sra %l7,8*(4-1),%l7
+cmp %l7,0; bne .L330; nop
+mov %g0,%i1
+mov %g0,%i2
+set .L333,%l7
+ld2 [%l7],%f30
+std %f30,[%fp+-64]
+std %f30,[%fp+-56]
+set .L333,%l7
+ld2 [%l7],%f30
+std %f30,[%fp+-48]
+set .L333,%l7
+ld2 [%l7],%f30
+std %f30,[%fp+-40]
+set .L333,%l7
+ld2 [%l7],%f30
+std %f30,[%fp+-32]
+set .L333,%l7
+ld2 [%l7],%f30
+std %f30,[%fp+-24]
+set .L333,%l7
+ld2 [%l7],%f30
+std %f30,[%fp+-16]
+set .L333,%l7
+ld2 [%l7],%f30
+std %f30,[%fp+-8]
+mov %g0,%i2
+mov %g0,%i5
+.L341:
+sll %i5,3,%l7
+add -64,%fp,%l6
+add %l7,%l6,%l6
+ld2 [%l6],%f30
+add -56,%fp,%l6
+add %l7,%l6,%l7
+ld2 [%l7],%f28
+fcmped %f30,%f28; nop; fbue .L345; nop
+set 1,%i2
+.L345:
+.L342:
+add %i5,1,%i5
+cmp %i5,7; bl .L341; nop
+cmp %i2,0; be .L348; nop
+ld [%i0+44],%l7
+cmp %l7,0; be .L350; nop
+set .328,%o0
+set 1,%o1
+call printf; nop
+.L350:
+add %i1,1,%i1
+.L348:
+ba .L352; nop
+ld [%i0+44],%l7
+cmp %l7,0; be .L354; nop
+set .328,%o0
+set 2,%o1
+call printf; nop
+.L354:
+add %i1,2,%i1
+.L352:
+mov %i1,%i0
+.L327:
+ret; restore
+.type s244,#function
+.size s244,.-s244
+.section ".data"
+.type .357,#object
+.align 1
+.357:
+.byte 115
+.byte 50
+.byte 53
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size .357,10
+.type .358,#object
+.size .358,8
+.align 1
+.358:
+.byte 115
+.byte 50
+.byte 53
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.global s25
+.section ".text"
+.align 4
+s25:
+save %sp,-96,%sp
+set .358,%i2
+add %i0,60,%i1
+.L359:
+.L360:
+mov %i1,%l5
+add %l5,1,%i1
+mov %i2,%l4
+add %l4,1,%i2
+ldsb [%l4],%l4
+stb %l4,[%l5]
+sll %l4,8*(4-1),%l5; sra %l5,8*(4-1),%l5
+cmp %l5,0; bne .L359; nop
+mov %g0,%l7
+set .L362,%i4
+ldsb [%i4+1],%l5
+ldsb [%i4],%l4
+cmp %l4,%l5; bne .L366; nop
+ldsb [%i4+2],%l4
+cmp %l5,%l4; bne .L366; nop
+cmp %l4,46; be .L363; nop
+.L366:
+add %l7,1,%l7
+ld [%i0+44],%l5
+cmp %l5,0; be .L367; nop
+set .357,%o0
+set 1,%o1
+call printf; nop
+.L367:
+.L363:
+ldsb [%i4+3],%l5
+cmp %l5,0; be .L369; nop
+add %l7,4,%l7
+ld [%i0+44],%l5
+cmp %l5,0; be .L371; nop
+set .357,%o0
+set 4,%o1
+call printf; nop
+.L371:
+.L369:
+set .L375+1,%l5
+ldsb [%l5],%l5
+cmp %l5,34; be .L373; nop
+add %l7,8,%l7
+ld [%i0+44],%l5
+cmp %l5,0; be .L377; nop
+set .357,%o0
+set 8,%o1
+call printf; nop
+.L377:
+.L373:
+set .L379,%i4
+ldsb [%i4],%l5
+cmp %l5,10; bne .L387; nop
+ldsb [%i4+1],%l5
+cmp %l5,9; bne .L387; nop
+ldsb [%i4+2],%l5
+cmp %l5,8; bne .L387; nop
+ldsb [%i4+3],%l5
+cmp %l5,13; bne .L387; nop
+ldsb [%i4+4],%l5
+cmp %l5,12; bne .L387; nop
+ldsb [%i4+5],%l5
+cmp %l5,92; bne .L387; nop
+ldsb [%i4+6],%l5
+cmp %l5,39; be .L380; nop
+.L387:
+add %l7,16,%l7
+ld [%i0+44],%l5
+cmp %l5,0; be .L388; nop
+set .357,%o0
+set 16,%o1
+call printf; nop
+.L388:
+.L380:
+set .L390,%l5
+mov %l5,%i3
+mov %l5,%i4
+mov %g0,%l6
+mov %g0,%i5
+ba .L394; nop
+.L391:
+ldsb [%i5+%i4],%l5
+ldsb [%i5+%i3],%l4
+cmp %l5,%l4; be .L395; nop
+set 1,%l6
+.L395:
+.L392:
+add %i5,1,%i5
+.L394:
+mov %i5,%l5
+set 7,%l4
+cmp %l5,%l4; blu .L391; nop
+cmp %l6,0; be .L397; nop
+add %l7,32,%l7
+ld [%i0+44],%l5
+cmp %l5,0; be .L399; nop
+set .357,%o0
+set 32,%o1
+call printf; nop
+.L399:
+.L397:
+mov %l7,%i0
+.L356:
+ret; restore
+.type s25,#function
+.size s25,.-s25
+.section ".data"
+.type .402,#object
+.size .402,8
+.align 1
+.402:
+.byte 115
+.byte 50
+.byte 54
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.type .403,#object
+.align 1
+.403:
+.byte 37
+.byte 51
+.byte 100
+.byte 32
+.byte 98
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 37
+.byte 115
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.size .403,18
+.type .404,#object
+.align 1
+.404:
+.byte 37
+.byte 101
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 108
+.byte 101
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 97
+.byte 100
+.byte 100
+.byte 101
+.byte 100
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 49
+.byte 46
+.byte 32
+.byte 40
+.byte 37
+.byte 115
+.byte 41
+.byte 46
+.byte 10
+.byte 0
+.size .404,54
+.global s26
+.section ".text"
+.align 4
+s26:
+save %sp,-128,%sp
+set .402,%i4
+add %i0,60,%i3
+.L405:
+.L406:
+mov %i3,%i1
+add %i1,1,%i3
+mov %i4,%l7
+add %l7,1,%i4
+ldsb [%l7],%l7
+stb %l7,[%i1]
+sll %l7,8*(4-1),%i1; sra %i1,8*(4-1),%i1
+cmp %i1,0; bne .L405; nop
+st %g0,[%i0]
+mov %g0,%i2
+set 1,%i5
+ba .L409; nop
+.L408:
+sll %i5,8*(4-1),%i1; sra %i1,8*(4-1),%i1
+sll %i1,1,%i1
+mov %i1,%i5
+ld [%i0],%i1
+add %i1,1,%i1
+st %i1,[%i0]
+.L409:
+sll %i2,8*(4-1),%i1; sra %i1,8*(4-1),%i1
+sll %i5,8*(4-1),%l7; sra %l7,8*(4-1),%l7
+cmp %i1,%l7; bne .L408; nop
+ld [%i0],%i1
+sll %i1,2,%i1
+st %i1,[%i0+4]
+ld [%i0],%i1
+sll %i1,1,%i1
+st %i1,[%i0+8]
+ld [%i0],%i1
+sll %i1,2,%i1
+st %i1,[%i0+12]
+ld [%i0],%i1
+sll %i1,2,%i1
+st %i1,[%i0+16]
+ld [%i0],%i1
+sll %i1,2,%i1
+st %i1,[%i0+20]
+ld [%i0],%i1
+sll %i1,3,%i1
+st %i1,[%i0+24]
+set .L411,%i1
+ld [%i1],%f31
+st %f31,[%fp+-12]
+st %f31,[%fp+-4]
+set .L412,%i1
+ld [%i1],%f31
+st %f31,[%fp+-8]
+ba .L414; nop
+.L413:
+ld [%fp+-4],%f31
+ld [%fp+-12],%f30
+fadds %f30,%f31,%f30
+st %f30,[%fp+-8]
+fstod %f31,%f30
+set .L416,%i1
+ld2 [%i1],%f28
+fdivd %f30,%f28,%f30
+fdtos %f30,%f31
+st %f31,[%fp+-4]
+.L414:
+ld [%fp+-8],%f31
+ld [%fp+-12],%f30
+fcmpes %f31,%f30; nop; fbne .L413; nop
+set .L417,%i1
+ld2 [%i1],%f30
+ld [%fp+-4],%f29
+fstod %f29,%f28
+fmuld %f30,%f28,%f30
+fdtos %f30,%f31
+st %f31,[%i0+28]
+set .L418,%i1
+ld2 [%i1],%f30
+std %f30,[%fp+-32]
+set .L411,%i1
+ld [%i1],%f31
+st %f31,[%fp+-4]
+set .L419,%i1
+ld2 [%i1],%f30
+std %f30,[%fp+-24]
+ba .L421; nop
+.L420:
+ld [%fp+-4],%f31
+fstod %f31,%f30
+ldd [%fp+-32],%f28
+faddd %f28,%f30,%f28
+std %f28,[%fp+-24]
+set .L416,%i1
+ld2 [%i1],%f28
+fdivd %f30,%f28,%f30
+fdtos %f30,%f31
+st %f31,[%fp+-4]
+.L421:
+ldd [%fp+-24],%f30
+ldd [%fp+-32],%f28
+fcmped %f30,%f28; nop; fbne .L420; nop
+set .L417,%i1
+ld2 [%i1],%f30
+ld [%fp+-4],%f29
+fstod %f29,%f28
+fmuld %f30,%f28,%f30
+fdtos %f30,%f31
+st %f31,[%i0+32]
+ld [%i0+40],%i1
+cmp %i1,0; be .L423; nop
+set .403,%o0
+ld [%i0],%o1
+set .L425,%o2
+call printf; nop
+set .403,%o0
+ld [%i0+4],%o1
+set .L426,%o2
+call printf; nop
+set .403,%o0
+ld [%i0+8],%o1
+set .L427,%o2
+call printf; nop
+set .403,%o0
+ld [%i0+12],%o1
+set .L428,%o2
+call printf; nop
+set .403,%o0
+ld [%i0+16],%o1
+set .L429,%o2
+call printf; nop
+set .403,%o0
+ld [%i0+20],%o1
+set .L430,%o2
+call printf; nop
+set .403,%o0
+ld [%i0+24],%o1
+set .L431,%o2
+call printf; nop
+set .404,%o0
+ld [%i0+28],%f31
+fstod %f31,%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+set .L430,%o3
+call printf; nop
+set .404,%o0
+ld [%i0+32],%f31
+fstod %f31,%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+set .L431,%o3
+call printf; nop
+.L423:
+mov %g0,%i0
+.L401:
+ret; restore
+.type s26,#function
+.size s26,.-s26
+.section ".data"
+.type .433,#object
+.align 1
+.433:
+.byte 115
+.byte 52
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size .433,9
+.type .434,#object
+.size .434,8
+.align 1
+.434:
+.byte 115
+.byte 52
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.global s4
+.section ".text"
+.align 4
+s4:
+save %sp,-96,%sp
+mov %g0,%l7
+set .434,%i2
+add %i0,60,%i1
+.L435:
+.L436:
+mov %i1,%l3
+add %l3,1,%i1
+mov %i2,%l2
+add %l2,1,%i2
+ldsb [%l2],%l2
+stb %l2,[%l3]
+sll %l2,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,0; bne .L435; nop
+mov %g0,%i5
+.L438:
+mov %i5,%o0
+call svtest; nop
+mov %o0,%l3
+call zero; nop
+cmp %l3,%o0; be .L442; nop
+set 1,%l7
+ld [%i0+44],%l3
+cmp %l3,0; be .L444; nop
+set .433,%o0
+set 1,%o1
+call printf; nop
+.L444:
+.L442:
+.L439:
+add %i5,1,%i5
+cmp %i5,3; bl .L438; nop
+call setev; nop
+call testev; nop
+cmp %o0,0; be .L446; nop
+add %l7,2,%l7
+ld [%i0+44],%l3
+cmp %l3,0; be .L448; nop
+set .433,%o0
+set 2,%o1
+call printf; nop
+.L448:
+.L446:
+ba .L450; nop
+add %l7,4,%l7
+ld [%i0+44],%l3
+cmp %l3,0; be .L452; nop
+set .433,%o0
+set 4,%o1
+call printf; nop
+.L452:
+.L450:
+set 0xffffffff,%i4
+set 1,%i3
+mov %g0,%i5
+ba .L457; nop
+.L454:
+and %i3,%i4,%i3
+srl %i4,1,%i4
+.L455:
+add %i5,1,%i5
+.L457:
+mov %i5,%l3
+ld [%i0],%l2
+sll %l2,2,%l2
+cmp %l3,%l2; blu .L454; nop
+set 1,%l3
+cmp %i3,%l3; bne .L460; nop
+cmp %i4,%g0; be .L458; nop
+.L460:
+add %l7,8,%l7
+ld [%i0+44],%l3
+cmp %l3,0; be .L461; nop
+set .433,%o0
+set 8,%o1
+call printf; nop
+.L461:
+.L458:
+mov %l7,%i0
+.L432:
+ret; restore
+.type s4,#function
+.size s4,.-s4
+.section ".bss"
+.type .464,#object
+.size .464,4
+.local .464
+.common .464,4,4
+.global svtest
+.section ".text"
+.align 4
+svtest:
+cmp %o0,0; be .L467; nop
+cmp %o0,1; be .L468; nop
+cmp %o0,2; be .L471; nop
+ba .L465; nop
+.L467:
+set .464,%o4
+set 1978,%o3
+st %o3,[%o4]
+mov %g0,%o5
+ba .L466; nop
+.L468:
+set .464,%o4
+ld [%o4],%o4
+cmp %o4,1978; be .L469; nop
+set 1,%o5
+ba .L466; nop
+.L469:
+set .464,%o4
+set 1929,%o3
+st %o3,[%o4]
+mov %g0,%o5
+ba .L466; nop
+.L471:
+set .464,%o4
+ld [%o4],%o4
+cmp %o4,1929; be .L472; nop
+set 1,%o5
+ba .L466; nop
+.L472:
+mov %g0,%o5
+.L465:
+.L466:
+mov %o5,%o0
+.L463:
+retl; nop
+.type svtest,#function
+.size svtest,.-svtest
+.section ".bss"
+.type .475,#object
+.size .475,4
+.local .475
+.common .475,4,4
+.global zero
+.section ".text"
+.align 4
+zero:
+set .475,%o4
+set 2,%o3
+st %o3,[%o4]
+mov %g0,%o5
+mov %o5,%o0
+.L474:
+retl; nop
+.type zero,#function
+.size zero,.-zero
+.global testev
+.align 4
+testev:
+set extvar,%o5
+ld [%o5],%o5
+cmp %o5,1066; be .L477; nop
+set 1,%o0
+ba .L476; nop
+.L477:
+mov %g0,%o0
+.L476:
+retl; nop
+.type testev,#function
+.size testev,.-testev
+.section ".data"
+.type .480,#object
+.align 1
+.480:
+.byte 115
+.byte 54
+.byte 49
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size .480,10
+.type .481,#object
+.size .481,8
+.align 1
+.481:
+.byte 115
+.byte 54
+.byte 49
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.type .482,#object
+.align 1
+.482:
+.byte 65
+.byte 66
+.byte 67
+.byte 68
+.byte 69
+.byte 70
+.byte 71
+.byte 72
+.byte 73
+.byte 74
+.byte 75
+.byte 76
+.byte 77
+.byte 78
+.byte 79
+.byte 80
+.byte 81
+.byte 82
+.byte 83
+.byte 84
+.byte 85
+.byte 86
+.byte 87
+.byte 88
+.byte 89
+.byte 90
+.byte 0
+.size .482,27
+.type .483,#object
+.align 1
+.483:
+.byte 97
+.byte 98
+.byte 99
+.byte 100
+.byte 101
+.byte 102
+.byte 103
+.byte 104
+.byte 105
+.byte 106
+.byte 107
+.byte 108
+.byte 109
+.byte 110
+.byte 111
+.byte 112
+.byte 113
+.byte 114
+.byte 115
+.byte 116
+.byte 117
+.byte 118
+.byte 119
+.byte 120
+.byte 121
+.byte 122
+.byte 0
+.size .483,27
+.type .484,#object
+.align 1
+.484:
+.byte 48
+.byte 49
+.byte 50
+.byte 51
+.byte 52
+.byte 53
+.byte 54
+.byte 55
+.byte 56
+.byte 57
+.byte 0
+.size .484,11
+.type .485,#object
+.align 1
+.485:
+.byte 126
+.byte 33
+.byte 34
+.byte 35
+.byte 37
+.byte 38
+.byte 40
+.byte 41
+.byte 95
+.byte 61
+.byte 45
+.byte 94
+.byte 124
+.byte 123
+.byte 125
+.byte 91
+.byte 93
+.byte 43
+.byte 59
+.byte 42
+.byte 58
+.byte 60
+.byte 62
+.byte 44
+.byte 46
+.byte 63
+.byte 47
+.byte 0
+.size .485,28
+.type .486,#object
+.align 1
+.486:
+.byte 10
+.byte 9
+.byte 8
+.byte 13
+.byte 12
+.byte 92
+.byte 39
+.byte 0
+.size .486,8
+.type .487,#object
+.align 1
+.487:
+.byte 32
+.byte 0
+.byte 0
+.size .487,3
+.global s61
+.section ".text"
+.align 4
+s61:
+save %sp,-120,%sp
+set .481,%i3
+add %i0,60,%i2
+mov %g0,%l7
+.L488:
+.L489:
+mov %i2,%l3
+add %l3,1,%i2
+mov %i3,%l2
+add %l2,1,%i3
+ldsb [%l2],%l2
+stb %l2,[%l3]
+sll %l2,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,0; bne .L488; nop
+set -19,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+st %l3,[%fp+-28]
+ld [%fp+-28],%l3
+cmp %l3,-19; be .L491; nop
+add %l7,1,%l7
+ld [%i0+44],%l3
+cmp %l3,0; be .L493; nop
+set .480,%o0
+set 1,%o1
+call printf; nop
+.L493:
+.L491:
+set .482,%l3
+st %l3,[%fp+-24]
+set .483,%l3
+st %l3,[%fp+-20]
+set .484,%l3
+st %l3,[%fp+-16]
+set .485,%l3
+st %l3,[%fp+-12]
+set .486,%l3
+st %l3,[%fp+-8]
+set .487,%l3
+st %l3,[%fp+-4]
+mov %g0,%i4
+mov %g0,%i5
+ba .L505; nop
+.L504:
+sll %i5,2,%l3
+add -24,%fp,%l2
+add %l3,%l2,%l3
+ld [%l3],%l2
+add %l2,1,%l1
+st %l1,[%l3]
+ldsb [%l2],%l3
+cmp %l3,0; bge .L507; nop
+set 1,%i4
+.L507:
+.L505:
+sll %i5,2,%l3
+add -24,%fp,%l2
+ld [%l3+%l2],%l3
+ldsb [%l3],%l3
+cmp %l3,0; bne .L504; nop
+.L501:
+add %i5,1,%i5
+cmp %i5,6; bl .L505; nop
+cmp %i4,0; be .L509; nop
+add %l7,2,%l7
+ld [%i0+44],%l3
+cmp %l3,0; be .L511; nop
+set .480,%o0
+set 2,%o1
+call printf; nop
+.L511:
+.L509:
+set 1048579,%i1
+mov %i1,%l6
+mov %i1,%l5
+sll %l6,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,%i1; be .L516; nop
+cmp %l3,3; bne .L515; nop
+.L516:
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,%i1; be .L513; nop
+cmp %l3,3; be .L513; nop
+.L515:
+add %l7,8,%l7
+ld [%i0+44],%l3
+cmp %l3,0; be .L517; nop
+set .480,%o0
+set 8,%o1
+call printf; nop
+.L517:
+.L513:
+mov %l7,%i0
+.L479:
+ret; restore
+.type s61,#function
+.size s61,.-s61
+.section ".data"
+.type .520,#object
+.align 1
+.520:
+.byte 115
+.byte 54
+.byte 50
+.byte 54
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size .520,11
+.type .521,#object
+.size .521,8
+.align 1
+.521:
+.byte 115
+.byte 54
+.byte 50
+.byte 54
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.global s626
+.section ".text"
+.align 4
+s626:
+save %sp,-176,%sp
+set .521,%i2
+add %i0,60,%i1
+st %g0,[%fp+-76]
+.L522:
+.L523:
+mov %i1,%l3
+add %l3,1,%i1
+mov %i2,%l2
+add %l2,1,%i2
+ldsb [%l2],%l2
+stb %l2,[%l3]
+sll %l2,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,0; bne .L522; nop
+set .L411,%l3
+ld [%l3],%f31
+st %f31,[%fp+-32]
+set 1,%l3
+mov %l3,%l7
+mov %l3,%i4
+mov %g0,%i5
+ba .L528; nop
+.L525:
+set .L529,%l3
+ld [%l3],%f31
+ld [%fp+-32],%f30
+fmuls %f31,%f30,%f31
+st %f31,[%fp+-32]
+sll %i4,1,%l3
+or %l3,%l7,%i4
+.L526:
+add %i5,1,%i5
+.L528:
+ld [%i0+12],%l3
+sub %l3,2,%l3
+cmp %i5,%l3; bl .L525; nop
+st %i4,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+st %f31,[%fp+-84]
+ld [%fp+-32],%f31
+ld [%fp+-84],%f30
+fsubs %f31,%f30,%f30
+fdivs %f30,%f31,%f31
+st %f31,[%fp+-32]
+ld [%fp+-32],%f31
+fstod %f31,%f30
+set .L416,%l3
+ld2 [%l3],%f28
+ld [%i0+28],%f27
+fstod %f27,%f26
+fmuld %f28,%f26,%f28
+fcmped %f30,%f28; nop; fbule .L530; nop
+ld [%fp+-76],%l3
+add %l3,2,%l3
+st %l3,[%fp+-76]
+ld [%i0+44],%l3
+cmp %l3,0; be .L532; nop
+set .520,%o0
+set 2,%o1
+call printf; nop
+.L532:
+.L530:
+set 125,%l5
+set 125,%l4
+set 125,%l3
+st %l3,[%fp+-48]
+set 15625,%l3
+st %l3,[%fp+-68]
+set 125,%l3
+st %l3,[%fp+-52]
+set 15625,%l3
+st %l3,[%fp+-72]
+set 125,%l6
+set 15625,%l3
+st %l3,[%fp+-80]
+set .L534,%l3
+ld [%l3],%f31
+st %f31,[%fp+-44]
+set .L535,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-64]
+set .L536,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+mov %g0,%i5
+.L537:
+add -28,%fp,%l3
+stb %g0,[%i5+%l3]
+.L538:
+add %i5,1,%i5
+cmp %i5,28; bl .L537; nop
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+smul %l3,%l3,%l3
+ld [%fp+-68],%l2
+cmp %l3,%l2; be .L541; nop
+set 1,%l3
+stb %l3,[%fp+-28]
+.L541:
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %l5,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+smul %l2,%l3,%l3
+ld [%fp+-68],%l2
+cmp %l3,%l2; be .L543; nop
+set 1,%l3
+stb %l3,[%fp+-27]
+.L543:
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+smul %l3,%l3,%l3
+ld [%fp+-68],%l2
+cmp %l3,%l2; be .L546; nop
+set 1,%l3
+stb %l3,[%fp+-26]
+.L546:
+ld [%fp+-48],%l3
+sll %l5,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+smul %l2,%l3,%l3
+ld [%fp+-68],%l2
+cmp %l3,%l2; be .L549; nop
+set 1,%l3
+stb %l3,[%fp+-25]
+.L549:
+ld [%fp+-48],%l3
+sll %l4,8*(4-2),%l2; sra %l2,8*(4-2),%l2
+smul %l2,%l3,%l3
+ld [%fp+-68],%l2
+cmp %l3,%l2; be .L552; nop
+set 1,%l3
+stb %l3,[%fp+-24]
+.L552:
+ld [%fp+-48],%l3
+smul %l3,%l3,%l3
+ld [%fp+-68],%l2
+cmp %l3,%l2; be .L555; nop
+set 1,%l3
+stb %l3,[%fp+-23]
+.L555:
+ld [%fp+-52],%l3
+sll %l5,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+umul %l2,%l3,%l3
+ld [%fp+-72],%l2
+cmp %l3,%l2; be .L558; nop
+set 1,%l3
+stb %l3,[%fp+-22]
+.L558:
+ld [%fp+-52],%l3
+sll %l4,8*(4-2),%l2; sra %l2,8*(4-2),%l2
+umul %l2,%l3,%l3
+ld [%fp+-72],%l2
+cmp %l3,%l2; be .L561; nop
+set 1,%l3
+stb %l3,[%fp+-21]
+.L561:
+ld [%fp+-52],%l3
+ld [%fp+-48],%l2
+umul %l2,%l3,%l3
+ld [%fp+-72],%l2
+cmp %l3,%l2; be .L564; nop
+set 1,%l3
+stb %l3,[%fp+-20]
+.L564:
+ld [%fp+-52],%l3
+umul %l3,%l3,%l3
+ld [%fp+-72],%l2
+cmp %l3,%l2; be .L567; nop
+set 1,%l3
+stb %l3,[%fp+-19]
+.L567:
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+smul %l3,%l6,%l3
+ld [%fp+-80],%l2
+cmp %l3,%l2; be .L570; nop
+set 1,%l3
+stb %l3,[%fp+-18]
+.L570:
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+smul %l3,%l6,%l3
+ld [%fp+-80],%l2
+cmp %l3,%l2; be .L573; nop
+set 1,%l3
+stb %l3,[%fp+-17]
+.L573:
+ld [%fp+-48],%l3
+smul %l3,%l6,%l3
+ld [%fp+-80],%l2
+cmp %l3,%l2; be .L576; nop
+set 1,%l3
+stb %l3,[%fp+-16]
+.L576:
+mov %l6,%l3
+ld [%fp+-52],%l2
+umul %l2,%l3,%l3
+ld [%fp+-72],%l2
+cmp %l3,%l2; be .L579; nop
+set 1,%l3
+stb %l3,[%fp+-15]
+.L579:
+smul %l6,%l6,%l3
+ld [%fp+-80],%l2
+cmp %l3,%l2; be .L582; nop
+set 1,%l3
+stb %l3,[%fp+-14]
+.L582:
+ld [%fp+-44],%f31
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitos %f30,%f30
+fmuls %f31,%f30,%f31
+fstod %f31,%f30
+ldd [%fp+-40],%f28
+fcmped %f30,%f28; nop; fbue .L585; nop
+set 1,%l3
+stb %l3,[%fp+-13]
+.L585:
+ld [%fp+-44],%f31
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitos %f30,%f30
+fmuls %f31,%f30,%f31
+fstod %f31,%f30
+ldd [%fp+-40],%f28
+fcmped %f30,%f28; nop; fbue .L588; nop
+set 1,%l3
+stb %l3,[%fp+-12]
+.L588:
+ld [%fp+-44],%f31
+ld [%fp+-48],%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitos %f30,%f30
+fmuls %f31,%f30,%f31
+fstod %f31,%f30
+ldd [%fp+-40],%f28
+fcmped %f30,%f28; nop; fbue .L591; nop
+set 1,%l3
+stb %l3,[%fp+-11]
+.L591:
+ld [%fp+-52],%l3
+ld [%fp+-44],%f31
+set .L596,%l2
+ld2 [%l2],%f28
+srl %l3,1,%l2
+st %l2,[%sp+64]; ld [%sp+64],%f26; fitod %f26,%f26
+fmuld %f28,%f26,%f28
+set 1,%l2
+and %l3,%l2,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f26; fitod %f26,%f26
+faddd %f28,%f26,%f28
+fdtos %f28,%f30
+fmuls %f31,%f30,%f31
+fstod %f31,%f30
+ldd [%fp+-40],%f28
+fcmped %f30,%f28; nop; fbue .L594; nop
+set 1,%l3
+stb %l3,[%fp+-10]
+.L594:
+ld [%fp+-44],%f31
+st %l6,[%sp+64]; ld [%sp+64],%f30; fitos %f30,%f30
+fmuls %f31,%f30,%f31
+fstod %f31,%f30
+ldd [%fp+-40],%f28
+fcmped %f30,%f28; nop; fbue .L598; nop
+set 1,%l3
+stb %l3,[%fp+-9]
+.L598:
+ld [%fp+-44],%f31
+fmuls %f31,%f31,%f31
+fstod %f31,%f30
+ldd [%fp+-40],%f28
+fcmped %f30,%f28; nop; fbue .L601; nop
+set 1,%l3
+stb %l3,[%fp+-8]
+.L601:
+ldd [%fp+-64],%f30
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fmuld %f30,%f28,%f30
+ldd [%fp+-40],%f28
+fcmped %f30,%f28; nop; fbue .L604; nop
+set 1,%l3
+stb %l3,[%fp+-7]
+.L604:
+ldd [%fp+-64],%f30
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fmuld %f30,%f28,%f30
+ldd [%fp+-40],%f28
+fcmped %f30,%f28; nop; fbue .L607; nop
+set 1,%l3
+stb %l3,[%fp+-6]
+.L607:
+ldd [%fp+-64],%f30
+ld [%fp+-48],%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fmuld %f30,%f28,%f30
+ldd [%fp+-40],%f28
+fcmped %f30,%f28; nop; fbue .L610; nop
+set 1,%l3
+stb %l3,[%fp+-5]
+.L610:
+ld [%fp+-52],%l3
+ldd [%fp+-64],%f30
+set .L596,%l2
+ld2 [%l2],%f28
+srl %l3,1,%l2
+st %l2,[%sp+64]; ld [%sp+64],%f26; fitod %f26,%f26
+fmuld %f28,%f26,%f28
+set 1,%l2
+and %l3,%l2,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f26; fitod %f26,%f26
+faddd %f28,%f26,%f28
+fmuld %f30,%f28,%f30
+ldd [%fp+-40],%f28
+fcmped %f30,%f28; nop; fbue .L613; nop
+set 1,%l3
+stb %l3,[%fp+-4]
+.L613:
+ldd [%fp+-64],%f30
+st %l6,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fmuld %f30,%f28,%f30
+ldd [%fp+-40],%f28
+fcmped %f30,%f28; nop; fbue .L616; nop
+set 1,%l3
+stb %l3,[%fp+-3]
+.L616:
+ldd [%fp+-64],%f30
+ld [%fp+-44],%f29
+fstod %f29,%f28
+fmuld %f30,%f28,%f30
+ldd [%fp+-40],%f28
+fcmped %f30,%f28; nop; fbue .L619; nop
+set 1,%l3
+stb %l3,[%fp+-2]
+.L619:
+ldd [%fp+-64],%f30
+fmuld %f30,%f30,%f30
+ldd [%fp+-40],%f28
+fcmped %f30,%f28; nop; fbue .L622; nop
+set 1,%l3
+stb %l3,[%fp+-1]
+.L622:
+mov %g0,%i3
+mov %g0,%i5
+.L625:
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+add -28,%fp,%l2
+ldsb [%i5+%l2],%l2
+add %l3,%l2,%l3
+mov %l3,%i3
+.L626:
+add %i5,1,%i5
+cmp %i5,28; bl .L625; nop
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,0; be .L629; nop
+ld [%fp+-76],%l3
+add %l3,4,%l3
+st %l3,[%fp+-76]
+ld [%i0+44],%l3
+cmp %l3,0; be .L631; nop
+set .520,%o0
+set 4,%o1
+call printf; nop
+set .L633,%o0
+call printf; nop
+mov %g0,%i5
+.L634:
+set .L638,%o0
+add -28,%fp,%l3
+ldsb [%i5+%l3],%o1
+call printf; nop
+.L635:
+add %i5,1,%i5
+cmp %i5,28; bl .L634; nop
+set .L639,%o0
+call printf; nop
+.L631:
+.L629:
+set 32768,%l6
+mov %l6,%l3
+set 0x8000,%l2
+cmp %l3,%l2; bleu .L640; nop
+ld [%fp+-76],%l3
+add %l3,8,%l3
+st %l3,[%fp+-76]
+ld [%i0+44],%l3
+cmp %l3,0; be .L642; nop
+set .520,%o0
+set 8,%o1
+call printf; nop
+.L642:
+.L640:
+ld [%fp+-76],%i0
+.L519:
+ret; restore
+.type s626,#function
+.size s626,.-s626
+.section ".data"
+.type .645,#object
+.align 1
+.645:
+.byte 115
+.byte 55
+.byte 49
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size .645,10
+.type .646,#object
+.size .646,8
+.align 1
+.646:
+.byte 115
+.byte 55
+.byte 49
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.type .647,#object
+.size .647,1
+.align 1
+.647:
+.byte 0x71
+.global s71
+.section ".text"
+.align 4
+s71:
+save %sp,-136,%sp
+set .646,%i5
+add %i0,60,%i4
+mov %g0,%i3
+.L648:
+.L649:
+mov %i4,%l7
+add %l7,1,%i4
+mov %i5,%l6
+add %l6,1,%i5
+ldsb [%l6],%l6
+stb %l6,[%l7]
+sll %l6,8*(4-1),%l7; sra %l7,8*(4-1),%l7
+cmp %l7,0; bne .L648; nop
+set .L653,%l7
+ldsb [%l7],%l7
+set .647,%l6
+ldsb [%l6],%l6
+cmp %l7,%l6; be .L651; nop
+add %i3,1,%i3
+ld [%i0+44],%l7
+cmp %l7,0; be .L654; nop
+set .645,%o0
+set 1,%o1
+call printf; nop
+.L654:
+.L651:
+ba .L656; nop
+add %i3,2,%i3
+ld [%i0+44],%l7
+cmp %l7,0; be .L658; nop
+set .645,%o0
+set 2,%o1
+call printf; nop
+.L658:
+.L656:
+set 1942,%l7
+st %l7,[%fp+-20]
+ld [%fp+-20],%l7
+cmp %l7,1942; bne .L666; nop
+ld [%fp+-20],%l7
+ld [%fp+-20],%l6
+cmp %l7,%l6; be .L661; nop
+.L666:
+add %i3,4,%i3
+ld [%i0+44],%l7
+cmp %l7,0; be .L667; nop
+set .645,%o0
+set 4,%o1
+call printf; nop
+.L667:
+.L661:
+set -5,%o0
+call McCarthy; nop
+cmp %o0,91; be .L669; nop
+add %i3,8,%i3
+ld [%i0+44],%l7
+cmp %l7,0; be .L671; nop
+set .645,%o0
+set 8,%o1
+call printf; nop
+.L671:
+.L669:
+set 2,%i2
+set 3,%l7
+st %l7,[%fp+-44]
+add -44,%fp,%i1
+mov %i2,%o0
+mov %i1,%o1
+call clobber; nop
+cmp %i2,2; bne .L675; nop
+ld [%fp+-44],%l7
+cmp %l7,2; be .L673; nop
+.L675:
+add %i3,16,%i3
+ld [%i0+44],%l7
+cmp %l7,0; be .L676; nop
+set .645,%o0
+set 16,%o1
+call printf; nop
+.L676:
+.L673:
+ld [%i0+32],%f31
+fcmpes %f31,%f31; nop; fbue .L678; nop
+add %i3,32,%i3
+ld [%i0+44],%l7
+cmp %l7,0; be .L680; nop
+set .645,%o0
+set 32,%o1
+call printf; nop
+.L680:
+.L678:
+mov %i3,%i0
+.L644:
+ret; restore
+.type s71,#function
+.size s71,.-s71
+.global McCarthy
+.align 4
+McCarthy:
+save %sp,-96,%sp
+cmp %i0,100; ble .L683; nop
+sub %i0,10,%i0
+ba .L682; nop
+.L683:
+add %i0,11,%o0
+call McCarthy; nop
+mov %o0,%i5
+call McCarthy; nop
+mov %o0,%i0
+.L682:
+ret; restore
+.type McCarthy,#function
+.size McCarthy,.-McCarthy
+.global clobber
+.align 4
+clobber:
+set 3,%o0
+set 2,%o5
+st %o5,[%o1]
+mov %g0,%o0
+.L685:
+retl; nop
+.type clobber,#function
+.size clobber,.-clobber
+.section ".data"
+.type .687,#object
+.align 1
+.687:
+.byte 76
+.byte 111
+.byte 99
+.byte 97
+.byte 108
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 37
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.size .687,17
+.type .688,#object
+.align 1
+.688:
+.byte 115
+.byte 55
+.byte 49
+.byte 52
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size .688,11
+.type .689,#object
+.size .689,8
+.align 1
+.689:
+.byte 115
+.byte 55
+.byte 49
+.byte 52
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.global s714
+.section ".text"
+.align 4
+s714:
+save %sp,-184,%sp
+set .689,%l3
+st %l3,[%fp+-44]
+add %i0,60,%l3
+st %l3,[%fp+-48]
+st %g0,[%fp+-52]
+mov %g0,%i4
+ld [%i0+48],%i5
+.L690:
+.L691:
+ld [%fp+-48],%l3
+add %l3,1,%l2
+st %l2,[%fp+-48]
+ld [%fp+-44],%l2
+add %l2,1,%l1
+st %l1,[%fp+-44]
+ldsb [%l2],%l2
+stb %l2,[%l3]
+sll %l2,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,0; bne .L690; nop
+set 5,%i3
+set 2,%l5
+mov %l5,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,2; be .L693; nop
+set 1,%i4
+cmp %i5,0; be .L695; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L695:
+.L693:
+set 5,%i3
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,2; be .L697; nop
+set 2,%i4
+cmp %i5,0; be .L699; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L699:
+.L697:
+set 5,%i3
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,2; be .L701; nop
+set 3,%i4
+cmp %i5,0; be .L703; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L703:
+.L701:
+set 5,%i3
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,2; be .L705; nop
+set 4,%i4
+cmp %i5,0; be .L707; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L707:
+.L705:
+set 5,%i3
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,2; be .L709; nop
+set 5,%i4
+cmp %i5,0; be .L711; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L711:
+.L709:
+set 5,%i3
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+ld [%fp+-28],%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,2; be .L713; nop
+set 6,%i4
+cmp %i5,0; be .L715; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L715:
+.L713:
+set 5,%i3
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+ldd [%fp+-40],%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,2; be .L717; nop
+set 7,%i4
+cmp %i5,0; be .L719; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L719:
+.L717:
+set 5,%i2
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,2; be .L721; nop
+set 8,%i4
+cmp %i5,0; be .L723; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L723:
+.L721:
+set 5,%i2
+set 2,%l4
+mov %l4,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,2; be .L725; nop
+set 9,%i4
+cmp %i5,0; be .L727; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L727:
+.L725:
+set 5,%i2
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,2; be .L729; nop
+set 10,%i4
+cmp %i5,0; be .L731; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L731:
+.L729:
+set 5,%i2
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,2; be .L733; nop
+set 11,%i4
+cmp %i5,0; be .L735; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L735:
+.L733:
+set 5,%i2
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,2; be .L737; nop
+set 12,%i4
+cmp %i5,0; be .L739; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L739:
+.L737:
+set 5,%i2
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+ld [%fp+-28],%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,2; be .L741; nop
+set 13,%i4
+cmp %i5,0; be .L743; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L743:
+.L741:
+set 5,%i2
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+ldd [%fp+-40],%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,2; be .L745; nop
+set 14,%i4
+cmp %i5,0; be .L747; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L747:
+.L745:
+set 5,%i1
+set 2,%l5
+sll %l5,8*(4-1),%i1; sra %i1,8*(4-1),%i1
+cmp %i1,2; be .L749; nop
+set 15,%i4
+cmp %i5,0; be .L751; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L751:
+.L749:
+set 5,%i1
+set 2,%l4
+sll %l4,8*(4-2),%i1; sra %i1,8*(4-2),%i1
+cmp %i1,2; be .L753; nop
+set 16,%i4
+cmp %i5,0; be .L755; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L755:
+.L753:
+set 5,%i1
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%i1
+cmp %i1,2; be .L757; nop
+set 17,%i4
+cmp %i5,0; be .L759; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L759:
+.L757:
+set 5,%i1
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%i1
+cmp %i1,2; be .L761; nop
+set 18,%i4
+cmp %i5,0; be .L763; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L763:
+.L761:
+set 5,%i1
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+mov %l3,%i1
+cmp %i1,2; be .L765; nop
+set 19,%i4
+cmp %i5,0; be .L767; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L767:
+.L765:
+set 5,%i1
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+ld [%fp+-28],%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%i1
+cmp %i1,2; be .L769; nop
+set 20,%i4
+cmp %i5,0; be .L771; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L771:
+.L769:
+set 5,%i1
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+ldd [%fp+-40],%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%i1
+cmp %i1,2; be .L773; nop
+set 21,%i4
+cmp %i5,0; be .L775; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L775:
+.L773:
+set 5,%l7
+set 2,%l5
+sll %l5,8*(4-1),%l7; sra %l7,8*(4-1),%l7
+cmp %l7,2; be .L777; nop
+set 22,%i4
+cmp %i5,0; be .L779; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L779:
+.L777:
+set 5,%l7
+set 2,%l4
+sll %l4,8*(4-2),%l7; sra %l7,8*(4-2),%l7
+cmp %l7,2; be .L781; nop
+set 23,%i4
+cmp %i5,0; be .L783; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L783:
+.L781:
+set 5,%l7
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l7
+cmp %l7,2; be .L785; nop
+set 24,%i4
+cmp %i5,0; be .L787; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L787:
+.L785:
+set 5,%l7
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l7
+cmp %l7,2; be .L789; nop
+set 25,%i4
+cmp %i5,0; be .L791; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L791:
+.L789:
+set 5,%l7
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+mov %l3,%l7
+cmp %l7,2; be .L793; nop
+set 26,%i4
+cmp %i5,0; be .L795; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L795:
+.L793:
+set 5,%l7
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+ld [%fp+-28],%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l7
+cmp %l7,2; be .L797; nop
+set 27,%i4
+cmp %i5,0; be .L799; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L799:
+.L797:
+set 5,%l7
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+ldd [%fp+-40],%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l7
+cmp %l7,2; be .L801; nop
+set 28,%i4
+cmp %i5,0; be .L803; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L803:
+.L801:
+set 5,%l6
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+mov %l3,%l6
+set 2,%l3
+cmp %l6,%l3; be .L805; nop
+set 29,%i4
+cmp %i5,0; be .L807; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L807:
+.L805:
+set 5,%l6
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+mov %l3,%l6
+set 2,%l3
+cmp %l6,%l3; be .L809; nop
+set 30,%i4
+cmp %i5,0; be .L811; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L811:
+.L809:
+set 5,%l6
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+mov %l3,%l6
+set 2,%l3
+cmp %l6,%l3; be .L813; nop
+set 31,%i4
+cmp %i5,0; be .L815; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L815:
+.L813:
+set 5,%l6
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+mov %l3,%l6
+set 2,%l3
+cmp %l6,%l3; be .L817; nop
+set 32,%i4
+cmp %i5,0; be .L819; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L819:
+.L817:
+set 5,%l6
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l6
+cmp %l6,%l3; be .L821; nop
+set 33,%i4
+cmp %i5,0; be .L823; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L823:
+.L821:
+set 5,%l6
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+ld [%fp+-28],%f31
+set .L828,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbul .L826; nop
+fsubs %f31,%f30,%f30
+fstoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+set 0x80000000,%l2
+add %l3,%l2,%l3
+st %l3,[%fp+-56]
+ba .L827; nop
+.L826:
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+st %l3,[%fp+-56]
+.L827:
+ld [%fp+-56],%l6
+set 2,%l3
+cmp %l6,%l3; be .L829; nop
+set 34,%i4
+cmp %i5,0; be .L831; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L831:
+.L829:
+set 5,%l6
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+ldd [%fp+-40],%f30
+set .L836,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbul .L834; nop
+fsubd %f30,%f28,%f28
+fdtoi %f28,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+set 0x80000000,%l2
+add %l3,%l2,%l3
+st %l3,[%fp+-60]
+ba .L835; nop
+.L834:
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+st %l3,[%fp+-60]
+.L835:
+ld [%fp+-60],%l6
+set 2,%l3
+cmp %l6,%l3; be .L837; nop
+set 35,%i4
+cmp %i5,0; be .L839; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L839:
+.L837:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L529,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L842; nop
+set 36,%i4
+cmp %i5,0; be .L844; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L844:
+.L842:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L529,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L846; nop
+set 37,%i4
+cmp %i5,0; be .L848; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L848:
+.L846:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+st %l3,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L529,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L850; nop
+set 38,%i4
+cmp %i5,0; be .L852; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L852:
+.L850:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+st %l3,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L529,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L854; nop
+set 39,%i4
+cmp %i5,0; be .L856; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L856:
+.L854:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+set .L596,%l2
+ld2 [%l2],%f30
+srl %l3,1,%l2
+st %l2,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fmuld %f30,%f28,%f30
+set 1,%l2
+and %l3,%l2,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+faddd %f30,%f28,%f30
+fdtos %f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L529,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L858; nop
+set 40,%i4
+cmp %i5,0; be .L860; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L860:
+.L858:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+ld [%fp+-28],%f30
+st %f30,[%fp+-16]
+ld [%fp+-16],%f30
+fcmpes %f30,%f31; nop; fbue .L862; nop
+set 41,%i4
+cmp %i5,0; be .L864; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L864:
+.L862:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+ldd [%fp+-40],%f30
+fdtos %f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L529,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L866; nop
+set 42,%i4
+cmp %i5,0; be .L868; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L868:
+.L866:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L416,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L871; nop
+set 43,%i4
+cmp %i5,0; be .L873; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L873:
+.L871:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L416,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L875; nop
+set 44,%i4
+cmp %i5,0; be .L877; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L877:
+.L875:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L416,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L879; nop
+set 45,%i4
+cmp %i5,0; be .L881; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L881:
+.L879:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L416,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L883; nop
+set 46,%i4
+cmp %i5,0; be .L885; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L885:
+.L883:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+set .L596,%l2
+ld2 [%l2],%f30
+srl %l3,1,%l2
+st %l2,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fmuld %f30,%f28,%f30
+set 1,%l2
+and %l3,%l2,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+faddd %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L416,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L887; nop
+set 47,%i4
+cmp %i5,0; be .L889; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L889:
+.L887:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+ld [%fp+-28],%f31
+fstod %f31,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L416,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L891; nop
+set 48,%i4
+cmp %i5,0; be .L893; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L893:
+.L891:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+ldd [%fp+-40],%f28
+std %f28,[%fp+-24]
+ldd [%fp+-24],%f28
+fcmped %f28,%f30; nop; fbue .L895; nop
+set 49,%i4
+cmp %i5,0; be .L897; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L897:
+.L895:
+set 5,%i3
+set 2,%l5
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %l5,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+add %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,7; be .L899; nop
+set 50,%i4
+cmp %i5,0; be .L901; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L901:
+.L899:
+set 5,%i3
+set 2,%l4
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %l4,8*(4-2),%l2; sra %l2,8*(4-2),%l2
+add %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,7; be .L903; nop
+set 51,%i4
+cmp %i5,0; be .L905; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L905:
+.L903:
+set 5,%i3
+set 2,%l3
+st %l3,[%fp+-4]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-4],%l2
+add %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,7; be .L907; nop
+set 52,%i4
+cmp %i5,0; be .L909; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L909:
+.L907:
+set 5,%i3
+set 2,%l3
+st %l3,[%fp+-8]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-8],%l2
+add %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,7; be .L911; nop
+set 53,%i4
+cmp %i5,0; be .L913; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L913:
+.L911:
+set 5,%i3
+set 2,%l3
+st %l3,[%fp+-12]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-12],%l2
+add %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,7; be .L915; nop
+set 54,%i4
+cmp %i5,0; be .L917; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L917:
+.L915:
+set 5,%i3
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+ld [%fp+-28],%f30
+fadds %f31,%f30,%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,7; be .L919; nop
+set 55,%i4
+cmp %i5,0; be .L921; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L921:
+.L919:
+set 5,%i3
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+ldd [%fp+-40],%f28
+faddd %f30,%f28,%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,7; be .L923; nop
+set 56,%i4
+cmp %i5,0; be .L925; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L925:
+.L923:
+set 5,%i2
+set 2,%l5
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %l5,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+add %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,7; be .L927; nop
+set 57,%i4
+cmp %i5,0; be .L929; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L929:
+.L927:
+set 5,%i2
+set 2,%l4
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %l4,8*(4-2),%l2; sra %l2,8*(4-2),%l2
+add %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,7; be .L931; nop
+set 58,%i4
+cmp %i5,0; be .L933; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L933:
+.L931:
+set 5,%i2
+set 2,%l3
+st %l3,[%fp+-4]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-4],%l2
+add %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,7; be .L935; nop
+set 59,%i4
+cmp %i5,0; be .L937; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L937:
+.L935:
+set 5,%i2
+set 2,%l3
+st %l3,[%fp+-8]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-8],%l2
+add %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,7; be .L939; nop
+set 60,%i4
+cmp %i5,0; be .L941; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L941:
+.L939:
+set 5,%i2
+set 2,%l3
+st %l3,[%fp+-12]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-12],%l2
+add %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,7; be .L943; nop
+set 61,%i4
+cmp %i5,0; be .L945; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L945:
+.L943:
+set 5,%i2
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+ld [%fp+-28],%f30
+fadds %f31,%f30,%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,7; be .L947; nop
+set 62,%i4
+cmp %i5,0; be .L949; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L949:
+.L947:
+set 5,%i2
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+ldd [%fp+-40],%f28
+faddd %f30,%f28,%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,7; be .L951; nop
+set 63,%i4
+cmp %i5,0; be .L953; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L953:
+.L951:
+set 5,%i1
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+add %i1,%l3,%i1
+cmp %i1,7; be .L955; nop
+set 64,%i4
+cmp %i5,0; be .L957; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L957:
+.L955:
+set 5,%i1
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+add %i1,%l3,%i1
+cmp %i1,7; be .L959; nop
+set 65,%i4
+cmp %i5,0; be .L961; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L961:
+.L959:
+set 5,%i1
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+add %i1,%l3,%i1
+cmp %i1,7; be .L963; nop
+set 66,%i4
+cmp %i5,0; be .L965; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L965:
+.L963:
+set 5,%i1
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+add %i1,%l3,%i1
+cmp %i1,7; be .L967; nop
+set 67,%i4
+cmp %i5,0; be .L969; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L969:
+.L967:
+set 5,%i1
+set 2,%l3
+st %l3,[%fp+-12]
+mov %i1,%l3
+ld [%fp+-12],%l2
+add %l3,%l2,%l3
+mov %l3,%i1
+cmp %i1,7; be .L971; nop
+set 68,%i4
+cmp %i5,0; be .L973; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L973:
+.L971:
+set 5,%i1
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+st %i1,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+ld [%fp+-28],%f30
+fadds %f31,%f30,%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%i1
+cmp %i1,7; be .L975; nop
+set 69,%i4
+cmp %i5,0; be .L977; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L977:
+.L975:
+set 5,%i1
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+st %i1,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+ldd [%fp+-40],%f28
+faddd %f30,%f28,%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%i1
+cmp %i1,7; be .L979; nop
+set 70,%i4
+cmp %i5,0; be .L981; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L981:
+.L979:
+set 5,%l7
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+add %l7,%l3,%l7
+cmp %l7,7; be .L983; nop
+set 71,%i4
+cmp %i5,0; be .L985; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L985:
+.L983:
+set 5,%l7
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+add %l7,%l3,%l7
+cmp %l7,7; be .L987; nop
+set 72,%i4
+cmp %i5,0; be .L989; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L989:
+.L987:
+set 5,%l7
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+add %l7,%l3,%l7
+cmp %l7,7; be .L991; nop
+set 73,%i4
+cmp %i5,0; be .L993; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L993:
+.L991:
+set 5,%l7
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+add %l7,%l3,%l7
+cmp %l7,7; be .L995; nop
+set 74,%i4
+cmp %i5,0; be .L997; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L997:
+.L995:
+set 5,%l7
+set 2,%l3
+st %l3,[%fp+-12]
+mov %l7,%l3
+ld [%fp+-12],%l2
+add %l3,%l2,%l3
+mov %l3,%l7
+cmp %l7,7; be .L999; nop
+set 75,%i4
+cmp %i5,0; be .L1001; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1001:
+.L999:
+set 5,%l7
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+st %l7,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+ld [%fp+-28],%f30
+fadds %f31,%f30,%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l7
+cmp %l7,7; be .L1003; nop
+set 76,%i4
+cmp %i5,0; be .L1005; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1005:
+.L1003:
+set 5,%l7
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+st %l7,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+ldd [%fp+-40],%f28
+faddd %f30,%f28,%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l7
+cmp %l7,7; be .L1007; nop
+set 77,%i4
+cmp %i5,0; be .L1009; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1009:
+.L1007:
+set 5,%l6
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+add %l6,%l3,%l6
+set 7,%l3
+cmp %l6,%l3; be .L1011; nop
+set 78,%i4
+cmp %i5,0; be .L1013; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1013:
+.L1011:
+set 5,%l6
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+add %l6,%l3,%l6
+set 7,%l3
+cmp %l6,%l3; be .L1015; nop
+set 79,%i4
+cmp %i5,0; be .L1017; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1017:
+.L1015:
+set 5,%l6
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+add %l6,%l3,%l6
+set 7,%l3
+cmp %l6,%l3; be .L1019; nop
+set 80,%i4
+cmp %i5,0; be .L1021; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1021:
+.L1019:
+set 5,%l6
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+add %l6,%l3,%l6
+set 7,%l3
+cmp %l6,%l3; be .L1023; nop
+set 81,%i4
+cmp %i5,0; be .L1025; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1025:
+.L1023:
+set 5,%l6
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+add %l6,%l3,%l6
+set 7,%l3
+cmp %l6,%l3; be .L1027; nop
+set 82,%i4
+cmp %i5,0; be .L1029; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1029:
+.L1027:
+set 5,%l6
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+set .L596,%l3
+ld2 [%l3],%f30
+srl %l6,1,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fmuld %f30,%f28,%f30
+set 1,%l3
+and %l6,%l3,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+faddd %f30,%f28,%f30
+fdtos %f30,%f31
+ld [%fp+-28],%f30
+fadds %f31,%f30,%f31
+set .L828,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbul .L1032; nop
+fsubs %f31,%f30,%f30
+fstoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+set 0x80000000,%l2
+add %l3,%l2,%l3
+st %l3,[%fp+-64]
+ba .L1033; nop
+.L1032:
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+st %l3,[%fp+-64]
+.L1033:
+ld [%fp+-64],%l6
+set 7,%l3
+cmp %l6,%l3; be .L1034; nop
+set 83,%i4
+cmp %i5,0; be .L1036; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1036:
+.L1034:
+set 5,%l6
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+set .L596,%l3
+ld2 [%l3],%f30
+srl %l6,1,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fmuld %f30,%f28,%f30
+set 1,%l3
+and %l6,%l3,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+faddd %f30,%f28,%f30
+ldd [%fp+-40],%f28
+faddd %f30,%f28,%f30
+set .L836,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbul .L1039; nop
+fsubd %f30,%f28,%f28
+fdtoi %f28,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+set 0x80000000,%l2
+add %l3,%l2,%l3
+st %l3,[%fp+-68]
+ba .L1040; nop
+.L1039:
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+st %l3,[%fp+-68]
+.L1040:
+ld [%fp+-68],%l6
+set 7,%l3
+cmp %l6,%l3; be .L1041; nop
+set 84,%i4
+cmp %i5,0; be .L1043; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1043:
+.L1041:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l5
+ld [%fp+-16],%f31
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitos %f30,%f30
+fadds %f31,%f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L1047,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L1045; nop
+set 85,%i4
+cmp %i5,0; be .L1048; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1048:
+.L1045:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l4
+ld [%fp+-16],%f31
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitos %f30,%f30
+fadds %f31,%f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L1047,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L1050; nop
+set 86,%i4
+cmp %i5,0; be .L1052; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1052:
+.L1050:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-16],%f31
+ld [%fp+-4],%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitos %f30,%f30
+fadds %f31,%f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L1047,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L1054; nop
+set 87,%i4
+cmp %i5,0; be .L1056; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1056:
+.L1054:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-16],%f31
+ld [%fp+-8],%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitos %f30,%f30
+fadds %f31,%f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L1047,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L1058; nop
+set 88,%i4
+cmp %i5,0; be .L1060; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1060:
+.L1058:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+ld [%fp+-16],%f31
+set .L596,%l2
+ld2 [%l2],%f28
+srl %l3,1,%l2
+st %l2,[%sp+64]; ld [%sp+64],%f26; fitod %f26,%f26
+fmuld %f28,%f26,%f28
+set 1,%l2
+and %l3,%l2,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f26; fitod %f26,%f26
+faddd %f28,%f26,%f28
+fdtos %f28,%f30
+fadds %f31,%f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L1047,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L1062; nop
+set 89,%i4
+cmp %i5,0; be .L1064; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1064:
+.L1062:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+ld [%fp+-16],%f31
+ld [%fp+-28],%f30
+fadds %f31,%f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L1047,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L1066; nop
+set 90,%i4
+cmp %i5,0; be .L1068; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1068:
+.L1066:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+ld [%fp+-16],%f31
+fstod %f31,%f30
+ldd [%fp+-40],%f28
+faddd %f30,%f28,%f30
+fdtos %f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L1047,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L1070; nop
+set 91,%i4
+cmp %i5,0; be .L1072; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1072:
+.L1070:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l5
+ldd [%fp+-24],%f30
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+faddd %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1076,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1074; nop
+set 92,%i4
+cmp %i5,0; be .L1077; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1077:
+.L1074:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l4
+ldd [%fp+-24],%f30
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+faddd %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1076,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1079; nop
+set 93,%i4
+cmp %i5,0; be .L1081; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1081:
+.L1079:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l3
+st %l3,[%fp+-4]
+ldd [%fp+-24],%f30
+ld [%fp+-4],%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+faddd %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1076,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1083; nop
+set 94,%i4
+cmp %i5,0; be .L1085; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1085:
+.L1083:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l3
+st %l3,[%fp+-8]
+ldd [%fp+-24],%f30
+ld [%fp+-8],%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+faddd %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1076,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1087; nop
+set 95,%i4
+cmp %i5,0; be .L1089; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1089:
+.L1087:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+ldd [%fp+-24],%f30
+set .L596,%l2
+ld2 [%l2],%f28
+srl %l3,1,%l2
+st %l2,[%sp+64]; ld [%sp+64],%f26; fitod %f26,%f26
+fmuld %f28,%f26,%f28
+set 1,%l2
+and %l3,%l2,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f26; fitod %f26,%f26
+faddd %f28,%f26,%f28
+faddd %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1076,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1091; nop
+set 96,%i4
+cmp %i5,0; be .L1093; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1093:
+.L1091:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+ldd [%fp+-24],%f30
+ld [%fp+-28],%f29
+fstod %f29,%f28
+faddd %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1076,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1095; nop
+set 97,%i4
+cmp %i5,0; be .L1097; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1097:
+.L1095:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+ldd [%fp+-24],%f30
+ldd [%fp+-40],%f28
+faddd %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1076,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1099; nop
+set 98,%i4
+cmp %i5,0; be .L1101; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1101:
+.L1099:
+set 5,%i3
+set 2,%l5
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %l5,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+sub %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,3; be .L1103; nop
+set 99,%i4
+cmp %i5,0; be .L1105; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1105:
+.L1103:
+set 5,%i3
+set 2,%l4
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %l4,8*(4-2),%l2; sra %l2,8*(4-2),%l2
+sub %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,3; be .L1107; nop
+set 100,%i4
+cmp %i5,0; be .L1109; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1109:
+.L1107:
+set 5,%i3
+set 2,%l3
+st %l3,[%fp+-4]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-4],%l2
+sub %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,3; be .L1111; nop
+set 101,%i4
+cmp %i5,0; be .L1113; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1113:
+.L1111:
+set 5,%i3
+set 2,%l3
+st %l3,[%fp+-8]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-8],%l2
+sub %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,3; be .L1115; nop
+set 102,%i4
+cmp %i5,0; be .L1117; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1117:
+.L1115:
+set 5,%i3
+set 2,%l3
+st %l3,[%fp+-12]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-12],%l2
+sub %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,3; be .L1119; nop
+set 103,%i4
+cmp %i5,0; be .L1121; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1121:
+.L1119:
+set 5,%i3
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+ld [%fp+-28],%f30
+fsubs %f31,%f30,%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,3; be .L1123; nop
+set 104,%i4
+cmp %i5,0; be .L1125; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1125:
+.L1123:
+set 5,%i3
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+ldd [%fp+-40],%f28
+fsubd %f30,%f28,%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,3; be .L1127; nop
+set 105,%i4
+cmp %i5,0; be .L1129; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1129:
+.L1127:
+set 5,%i2
+set 2,%l5
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %l5,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+sub %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,3; be .L1131; nop
+set 106,%i4
+cmp %i5,0; be .L1133; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1133:
+.L1131:
+set 5,%i2
+set 2,%l4
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %l4,8*(4-2),%l2; sra %l2,8*(4-2),%l2
+sub %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,3; be .L1135; nop
+set 107,%i4
+cmp %i5,0; be .L1137; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1137:
+.L1135:
+set 5,%i2
+set 2,%l3
+st %l3,[%fp+-4]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-4],%l2
+sub %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,3; be .L1139; nop
+set 108,%i4
+cmp %i5,0; be .L1141; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1141:
+.L1139:
+set 5,%i2
+set 2,%l3
+st %l3,[%fp+-8]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-8],%l2
+sub %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,3; be .L1143; nop
+set 109,%i4
+cmp %i5,0; be .L1145; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1145:
+.L1143:
+set 5,%i2
+set 2,%l3
+st %l3,[%fp+-12]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-12],%l2
+sub %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,3; be .L1147; nop
+set 110,%i4
+cmp %i5,0; be .L1149; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1149:
+.L1147:
+set 5,%i2
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+ld [%fp+-28],%f30
+fsubs %f31,%f30,%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,3; be .L1151; nop
+set 111,%i4
+cmp %i5,0; be .L1153; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1153:
+.L1151:
+set 5,%i2
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+ldd [%fp+-40],%f28
+fsubd %f30,%f28,%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,3; be .L1155; nop
+set 112,%i4
+cmp %i5,0; be .L1157; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1157:
+.L1155:
+set 5,%i1
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sub %i1,%l3,%i1
+cmp %i1,3; be .L1159; nop
+set 113,%i4
+cmp %i5,0; be .L1161; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1161:
+.L1159:
+set 5,%i1
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sub %i1,%l3,%i1
+cmp %i1,3; be .L1163; nop
+set 114,%i4
+cmp %i5,0; be .L1165; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1165:
+.L1163:
+set 5,%i1
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+sub %i1,%l3,%i1
+cmp %i1,3; be .L1167; nop
+set 115,%i4
+cmp %i5,0; be .L1169; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1169:
+.L1167:
+set 5,%i1
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+sub %i1,%l3,%i1
+cmp %i1,3; be .L1171; nop
+set 116,%i4
+cmp %i5,0; be .L1173; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1173:
+.L1171:
+set 5,%i1
+set 2,%l3
+st %l3,[%fp+-12]
+mov %i1,%l3
+ld [%fp+-12],%l2
+sub %l3,%l2,%l3
+mov %l3,%i1
+cmp %i1,3; be .L1175; nop
+set 117,%i4
+cmp %i5,0; be .L1177; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1177:
+.L1175:
+set 5,%i1
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+st %i1,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+ld [%fp+-28],%f30
+fsubs %f31,%f30,%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%i1
+cmp %i1,3; be .L1179; nop
+set 118,%i4
+cmp %i5,0; be .L1181; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1181:
+.L1179:
+set 5,%i1
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+st %i1,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+ldd [%fp+-40],%f28
+fsubd %f30,%f28,%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%i1
+cmp %i1,3; be .L1183; nop
+set 119,%i4
+cmp %i5,0; be .L1185; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1185:
+.L1183:
+set 5,%l7
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sub %l7,%l3,%l7
+cmp %l7,3; be .L1187; nop
+set 120,%i4
+cmp %i5,0; be .L1189; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1189:
+.L1187:
+set 5,%l7
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sub %l7,%l3,%l7
+cmp %l7,3; be .L1191; nop
+set 121,%i4
+cmp %i5,0; be .L1193; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1193:
+.L1191:
+set 5,%l7
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+sub %l7,%l3,%l7
+cmp %l7,3; be .L1195; nop
+set 122,%i4
+cmp %i5,0; be .L1197; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1197:
+.L1195:
+set 5,%l7
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+sub %l7,%l3,%l7
+cmp %l7,3; be .L1199; nop
+set 123,%i4
+cmp %i5,0; be .L1201; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1201:
+.L1199:
+set 5,%l7
+set 2,%l3
+st %l3,[%fp+-12]
+mov %l7,%l3
+ld [%fp+-12],%l2
+sub %l3,%l2,%l3
+mov %l3,%l7
+cmp %l7,3; be .L1203; nop
+set 124,%i4
+cmp %i5,0; be .L1205; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1205:
+.L1203:
+set 5,%l7
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+st %l7,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+ld [%fp+-28],%f30
+fsubs %f31,%f30,%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l7
+cmp %l7,3; be .L1207; nop
+set 125,%i4
+cmp %i5,0; be .L1209; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1209:
+.L1207:
+set 5,%l7
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+st %l7,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+ldd [%fp+-40],%f28
+fsubd %f30,%f28,%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l7
+cmp %l7,3; be .L1211; nop
+set 126,%i4
+cmp %i5,0; be .L1213; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1213:
+.L1211:
+set 5,%l6
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sub %l6,%l3,%l6
+set 3,%l3
+cmp %l6,%l3; be .L1215; nop
+set 127,%i4
+cmp %i5,0; be .L1217; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1217:
+.L1215:
+set 5,%l6
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sub %l6,%l3,%l6
+set 3,%l3
+cmp %l6,%l3; be .L1219; nop
+set 128,%i4
+cmp %i5,0; be .L1221; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1221:
+.L1219:
+set 5,%l6
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+sub %l6,%l3,%l6
+set 3,%l3
+cmp %l6,%l3; be .L1223; nop
+set 129,%i4
+cmp %i5,0; be .L1225; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1225:
+.L1223:
+set 5,%l6
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+sub %l6,%l3,%l6
+set 3,%l3
+cmp %l6,%l3; be .L1227; nop
+set 130,%i4
+cmp %i5,0; be .L1229; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1229:
+.L1227:
+set 5,%l6
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+sub %l6,%l3,%l6
+set 3,%l3
+cmp %l6,%l3; be .L1231; nop
+set 131,%i4
+cmp %i5,0; be .L1233; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1233:
+.L1231:
+set 5,%l6
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+set .L596,%l3
+ld2 [%l3],%f30
+srl %l6,1,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fmuld %f30,%f28,%f30
+set 1,%l3
+and %l6,%l3,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+faddd %f30,%f28,%f30
+fdtos %f30,%f31
+ld [%fp+-28],%f30
+fsubs %f31,%f30,%f31
+set .L828,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbul .L1236; nop
+fsubs %f31,%f30,%f30
+fstoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+set 0x80000000,%l2
+add %l3,%l2,%l3
+st %l3,[%fp+-72]
+ba .L1237; nop
+.L1236:
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+st %l3,[%fp+-72]
+.L1237:
+ld [%fp+-72],%l6
+set 3,%l3
+cmp %l6,%l3; be .L1238; nop
+set 132,%i4
+cmp %i5,0; be .L1240; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1240:
+.L1238:
+set 5,%l6
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+set .L596,%l3
+ld2 [%l3],%f30
+srl %l6,1,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fmuld %f30,%f28,%f30
+set 1,%l3
+and %l6,%l3,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+faddd %f30,%f28,%f30
+ldd [%fp+-40],%f28
+fsubd %f30,%f28,%f30
+set .L836,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbul .L1243; nop
+fsubd %f30,%f28,%f28
+fdtoi %f28,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+set 0x80000000,%l2
+add %l3,%l2,%l3
+st %l3,[%fp+-76]
+ba .L1244; nop
+.L1243:
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+st %l3,[%fp+-76]
+.L1244:
+ld [%fp+-76],%l6
+set 3,%l3
+cmp %l6,%l3; be .L1245; nop
+set 133,%i4
+cmp %i5,0; be .L1247; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1247:
+.L1245:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l5
+ld [%fp+-16],%f31
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitos %f30,%f30
+fsubs %f31,%f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L1251,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L1249; nop
+set 134,%i4
+cmp %i5,0; be .L1252; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1252:
+.L1249:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l4
+ld [%fp+-16],%f31
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitos %f30,%f30
+fsubs %f31,%f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L1251,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L1254; nop
+set 135,%i4
+cmp %i5,0; be .L1256; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1256:
+.L1254:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-16],%f31
+ld [%fp+-4],%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitos %f30,%f30
+fsubs %f31,%f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L1251,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L1258; nop
+set 136,%i4
+cmp %i5,0; be .L1260; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1260:
+.L1258:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-16],%f31
+ld [%fp+-8],%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitos %f30,%f30
+fsubs %f31,%f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L1251,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L1262; nop
+set 137,%i4
+cmp %i5,0; be .L1264; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1264:
+.L1262:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+ld [%fp+-16],%f31
+set .L596,%l2
+ld2 [%l2],%f28
+srl %l3,1,%l2
+st %l2,[%sp+64]; ld [%sp+64],%f26; fitod %f26,%f26
+fmuld %f28,%f26,%f28
+set 1,%l2
+and %l3,%l2,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f26; fitod %f26,%f26
+faddd %f28,%f26,%f28
+fdtos %f28,%f30
+fsubs %f31,%f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L1251,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L1266; nop
+set 138,%i4
+cmp %i5,0; be .L1268; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1268:
+.L1266:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+ld [%fp+-16],%f31
+ld [%fp+-28],%f30
+fsubs %f31,%f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L1251,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L1270; nop
+set 139,%i4
+cmp %i5,0; be .L1272; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1272:
+.L1270:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+ld [%fp+-16],%f31
+fstod %f31,%f30
+ldd [%fp+-40],%f28
+fsubd %f30,%f28,%f30
+fdtos %f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L1251,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L1274; nop
+set 140,%i4
+cmp %i5,0; be .L1276; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1276:
+.L1274:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l5
+ldd [%fp+-24],%f30
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fsubd %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1280,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1278; nop
+set 141,%i4
+cmp %i5,0; be .L1281; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1281:
+.L1278:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l4
+ldd [%fp+-24],%f30
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fsubd %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1280,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1283; nop
+set 142,%i4
+cmp %i5,0; be .L1285; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1285:
+.L1283:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l3
+st %l3,[%fp+-4]
+ldd [%fp+-24],%f30
+ld [%fp+-4],%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fsubd %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1280,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1287; nop
+set 143,%i4
+cmp %i5,0; be .L1289; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1289:
+.L1287:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l3
+st %l3,[%fp+-8]
+ldd [%fp+-24],%f30
+ld [%fp+-8],%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fsubd %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1280,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1291; nop
+set 144,%i4
+cmp %i5,0; be .L1293; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1293:
+.L1291:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+ldd [%fp+-24],%f30
+set .L596,%l2
+ld2 [%l2],%f28
+srl %l3,1,%l2
+st %l2,[%sp+64]; ld [%sp+64],%f26; fitod %f26,%f26
+fmuld %f28,%f26,%f28
+set 1,%l2
+and %l3,%l2,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f26; fitod %f26,%f26
+faddd %f28,%f26,%f28
+fsubd %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1280,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1295; nop
+set 145,%i4
+cmp %i5,0; be .L1297; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1297:
+.L1295:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+ldd [%fp+-24],%f30
+ld [%fp+-28],%f29
+fstod %f29,%f28
+fsubd %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1280,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1299; nop
+set 146,%i4
+cmp %i5,0; be .L1301; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1301:
+.L1299:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+ldd [%fp+-24],%f30
+ldd [%fp+-40],%f28
+fsubd %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1280,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1303; nop
+set 147,%i4
+cmp %i5,0; be .L1305; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1305:
+.L1303:
+set 5,%i3
+set 2,%l5
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %l5,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+smul %l2,%l3,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,10; be .L1307; nop
+set 148,%i4
+cmp %i5,0; be .L1309; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1309:
+.L1307:
+set 5,%i3
+set 2,%l4
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %l4,8*(4-2),%l2; sra %l2,8*(4-2),%l2
+smul %l2,%l3,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,10; be .L1311; nop
+set 149,%i4
+cmp %i5,0; be .L1313; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1313:
+.L1311:
+set 5,%i3
+set 2,%l3
+st %l3,[%fp+-4]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-4],%l2
+smul %l2,%l3,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,10; be .L1315; nop
+set 150,%i4
+cmp %i5,0; be .L1317; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1317:
+.L1315:
+set 5,%i3
+set 2,%l3
+st %l3,[%fp+-8]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-8],%l2
+smul %l2,%l3,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,10; be .L1319; nop
+set 151,%i4
+cmp %i5,0; be .L1321; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1321:
+.L1319:
+set 5,%i3
+set 2,%l3
+st %l3,[%fp+-12]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-12],%l2
+umul %l2,%l3,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,10; be .L1323; nop
+set 152,%i4
+cmp %i5,0; be .L1325; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1325:
+.L1323:
+set 5,%i3
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+ld [%fp+-28],%f30
+fmuls %f31,%f30,%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,10; be .L1327; nop
+set 153,%i4
+cmp %i5,0; be .L1329; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1329:
+.L1327:
+set 5,%i3
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+ldd [%fp+-40],%f28
+fmuld %f30,%f28,%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,10; be .L1331; nop
+set 154,%i4
+cmp %i5,0; be .L1333; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1333:
+.L1331:
+set 5,%i2
+set 2,%l5
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %l5,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+smul %l2,%l3,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,10; be .L1335; nop
+set 155,%i4
+cmp %i5,0; be .L1337; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1337:
+.L1335:
+set 5,%i2
+set 2,%l4
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %l4,8*(4-2),%l2; sra %l2,8*(4-2),%l2
+smul %l2,%l3,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,10; be .L1339; nop
+set 156,%i4
+cmp %i5,0; be .L1341; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1341:
+.L1339:
+set 5,%i2
+set 2,%l3
+st %l3,[%fp+-4]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-4],%l2
+smul %l2,%l3,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,10; be .L1343; nop
+set 157,%i4
+cmp %i5,0; be .L1345; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1345:
+.L1343:
+set 5,%i2
+set 2,%l3
+st %l3,[%fp+-8]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-8],%l2
+smul %l2,%l3,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,10; be .L1347; nop
+set 158,%i4
+cmp %i5,0; be .L1349; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1349:
+.L1347:
+set 5,%i2
+set 2,%l3
+st %l3,[%fp+-12]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-12],%l2
+umul %l2,%l3,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,10; be .L1351; nop
+set 159,%i4
+cmp %i5,0; be .L1353; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1353:
+.L1351:
+set 5,%i2
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+ld [%fp+-28],%f30
+fmuls %f31,%f30,%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,10; be .L1355; nop
+set 160,%i4
+cmp %i5,0; be .L1357; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1357:
+.L1355:
+set 5,%i2
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+ldd [%fp+-40],%f28
+fmuld %f30,%f28,%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,10; be .L1359; nop
+set 161,%i4
+cmp %i5,0; be .L1361; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1361:
+.L1359:
+set 5,%i1
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+smul %l3,%i1,%i1
+cmp %i1,10; be .L1363; nop
+set 162,%i4
+cmp %i5,0; be .L1365; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1365:
+.L1363:
+set 5,%i1
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+smul %l3,%i1,%i1
+cmp %i1,10; be .L1367; nop
+set 163,%i4
+cmp %i5,0; be .L1369; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1369:
+.L1367:
+set 5,%i1
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+smul %l3,%i1,%i1
+cmp %i1,10; be .L1371; nop
+set 164,%i4
+cmp %i5,0; be .L1373; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1373:
+.L1371:
+set 5,%i1
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+smul %l3,%i1,%i1
+cmp %i1,10; be .L1375; nop
+set 165,%i4
+cmp %i5,0; be .L1377; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1377:
+.L1375:
+set 5,%i1
+set 2,%l3
+st %l3,[%fp+-12]
+mov %i1,%l3
+ld [%fp+-12],%l2
+umul %l2,%l3,%l3
+mov %l3,%i1
+cmp %i1,10; be .L1379; nop
+set 166,%i4
+cmp %i5,0; be .L1381; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1381:
+.L1379:
+set 5,%i1
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+st %i1,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+ld [%fp+-28],%f30
+fmuls %f31,%f30,%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%i1
+cmp %i1,10; be .L1383; nop
+set 167,%i4
+cmp %i5,0; be .L1385; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1385:
+.L1383:
+set 5,%i1
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+st %i1,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+ldd [%fp+-40],%f28
+fmuld %f30,%f28,%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%i1
+cmp %i1,10; be .L1387; nop
+set 168,%i4
+cmp %i5,0; be .L1389; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1389:
+.L1387:
+set 5,%l7
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+smul %l3,%l7,%l7
+cmp %l7,10; be .L1391; nop
+set 169,%i4
+cmp %i5,0; be .L1393; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1393:
+.L1391:
+set 5,%l7
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+smul %l3,%l7,%l7
+cmp %l7,10; be .L1395; nop
+set 170,%i4
+cmp %i5,0; be .L1397; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1397:
+.L1395:
+set 5,%l7
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+smul %l3,%l7,%l7
+cmp %l7,10; be .L1399; nop
+set 171,%i4
+cmp %i5,0; be .L1401; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1401:
+.L1399:
+set 5,%l7
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+smul %l3,%l7,%l7
+cmp %l7,10; be .L1403; nop
+set 172,%i4
+cmp %i5,0; be .L1405; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1405:
+.L1403:
+set 5,%l7
+set 2,%l3
+st %l3,[%fp+-12]
+mov %l7,%l3
+ld [%fp+-12],%l2
+umul %l2,%l3,%l3
+mov %l3,%l7
+cmp %l7,10; be .L1407; nop
+set 173,%i4
+cmp %i5,0; be .L1409; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1409:
+.L1407:
+set 5,%l7
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+st %l7,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+ld [%fp+-28],%f30
+fmuls %f31,%f30,%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l7
+cmp %l7,10; be .L1411; nop
+set 174,%i4
+cmp %i5,0; be .L1413; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1413:
+.L1411:
+set 5,%l7
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+st %l7,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+ldd [%fp+-40],%f28
+fmuld %f30,%f28,%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l7
+cmp %l7,10; be .L1415; nop
+set 175,%i4
+cmp %i5,0; be .L1417; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1417:
+.L1415:
+set 5,%l6
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+umul %l3,%l6,%l6
+set 10,%l3
+cmp %l6,%l3; be .L1419; nop
+set 176,%i4
+cmp %i5,0; be .L1421; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1421:
+.L1419:
+set 5,%l6
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+umul %l3,%l6,%l6
+set 10,%l3
+cmp %l6,%l3; be .L1423; nop
+set 177,%i4
+cmp %i5,0; be .L1425; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1425:
+.L1423:
+set 5,%l6
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+umul %l3,%l6,%l6
+set 10,%l3
+cmp %l6,%l3; be .L1427; nop
+set 178,%i4
+cmp %i5,0; be .L1429; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1429:
+.L1427:
+set 5,%l6
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+umul %l3,%l6,%l6
+set 10,%l3
+cmp %l6,%l3; be .L1431; nop
+set 179,%i4
+cmp %i5,0; be .L1433; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1433:
+.L1431:
+set 5,%l6
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+umul %l3,%l6,%l6
+set 10,%l3
+cmp %l6,%l3; be .L1435; nop
+set 180,%i4
+cmp %i5,0; be .L1437; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1437:
+.L1435:
+set 5,%l6
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+set .L596,%l3
+ld2 [%l3],%f30
+srl %l6,1,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fmuld %f30,%f28,%f30
+set 1,%l3
+and %l6,%l3,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+faddd %f30,%f28,%f30
+fdtos %f30,%f31
+ld [%fp+-28],%f30
+fmuls %f31,%f30,%f31
+set .L828,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbul .L1440; nop
+fsubs %f31,%f30,%f30
+fstoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+set 0x80000000,%l2
+add %l3,%l2,%l3
+st %l3,[%fp+-80]
+ba .L1441; nop
+.L1440:
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+st %l3,[%fp+-80]
+.L1441:
+ld [%fp+-80],%l6
+set 10,%l3
+cmp %l6,%l3; be .L1442; nop
+set 181,%i4
+cmp %i5,0; be .L1444; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1444:
+.L1442:
+set 5,%l6
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+set .L596,%l3
+ld2 [%l3],%f30
+srl %l6,1,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fmuld %f30,%f28,%f30
+set 1,%l3
+and %l6,%l3,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+faddd %f30,%f28,%f30
+ldd [%fp+-40],%f28
+fmuld %f30,%f28,%f30
+set .L836,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbul .L1447; nop
+fsubd %f30,%f28,%f28
+fdtoi %f28,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+set 0x80000000,%l2
+add %l3,%l2,%l3
+st %l3,[%fp+-84]
+ba .L1448; nop
+.L1447:
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+st %l3,[%fp+-84]
+.L1448:
+ld [%fp+-84],%l6
+set 10,%l3
+cmp %l6,%l3; be .L1449; nop
+set 182,%i4
+cmp %i5,0; be .L1451; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1451:
+.L1449:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l5
+ld [%fp+-16],%f31
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitos %f30,%f30
+fmuls %f31,%f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L1455,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L1453; nop
+set 183,%i4
+cmp %i5,0; be .L1456; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1456:
+.L1453:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l4
+ld [%fp+-16],%f31
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitos %f30,%f30
+fmuls %f31,%f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L1455,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L1458; nop
+set 184,%i4
+cmp %i5,0; be .L1460; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1460:
+.L1458:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-16],%f31
+ld [%fp+-4],%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitos %f30,%f30
+fmuls %f31,%f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L1455,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L1462; nop
+set 185,%i4
+cmp %i5,0; be .L1464; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1464:
+.L1462:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-16],%f31
+ld [%fp+-8],%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitos %f30,%f30
+fmuls %f31,%f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L1455,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L1466; nop
+set 186,%i4
+cmp %i5,0; be .L1468; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1468:
+.L1466:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+ld [%fp+-16],%f31
+set .L596,%l2
+ld2 [%l2],%f28
+srl %l3,1,%l2
+st %l2,[%sp+64]; ld [%sp+64],%f26; fitod %f26,%f26
+fmuld %f28,%f26,%f28
+set 1,%l2
+and %l3,%l2,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f26; fitod %f26,%f26
+faddd %f28,%f26,%f28
+fdtos %f28,%f30
+fmuls %f31,%f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L1455,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L1470; nop
+set 187,%i4
+cmp %i5,0; be .L1472; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1472:
+.L1470:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+ld [%fp+-16],%f31
+ld [%fp+-28],%f30
+fmuls %f31,%f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L1455,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L1474; nop
+set 188,%i4
+cmp %i5,0; be .L1476; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1476:
+.L1474:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+ld [%fp+-16],%f31
+fstod %f31,%f30
+ldd [%fp+-40],%f28
+fmuld %f30,%f28,%f30
+fdtos %f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+set .L1455,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbue .L1478; nop
+set 189,%i4
+cmp %i5,0; be .L1480; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1480:
+.L1478:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l5
+ldd [%fp+-24],%f30
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fmuld %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1484,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1482; nop
+set 190,%i4
+cmp %i5,0; be .L1485; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1485:
+.L1482:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l4
+ldd [%fp+-24],%f30
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fmuld %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1484,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1487; nop
+set 191,%i4
+cmp %i5,0; be .L1489; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1489:
+.L1487:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l3
+st %l3,[%fp+-4]
+ldd [%fp+-24],%f30
+ld [%fp+-4],%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fmuld %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1484,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1491; nop
+set 192,%i4
+cmp %i5,0; be .L1493; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1493:
+.L1491:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l3
+st %l3,[%fp+-8]
+ldd [%fp+-24],%f30
+ld [%fp+-8],%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fmuld %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1484,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1495; nop
+set 193,%i4
+cmp %i5,0; be .L1497; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1497:
+.L1495:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+ldd [%fp+-24],%f30
+set .L596,%l2
+ld2 [%l2],%f28
+srl %l3,1,%l2
+st %l2,[%sp+64]; ld [%sp+64],%f26; fitod %f26,%f26
+fmuld %f28,%f26,%f28
+set 1,%l2
+and %l3,%l2,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f26; fitod %f26,%f26
+faddd %f28,%f26,%f28
+fmuld %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1484,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1499; nop
+set 194,%i4
+cmp %i5,0; be .L1501; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1501:
+.L1499:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+ldd [%fp+-24],%f30
+ld [%fp+-28],%f29
+fstod %f29,%f28
+fmuld %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1484,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1503; nop
+set 195,%i4
+cmp %i5,0; be .L1505; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1505:
+.L1503:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+ldd [%fp+-24],%f30
+ldd [%fp+-40],%f28
+fmuld %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1484,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1507; nop
+set 196,%i4
+cmp %i5,0; be .L1509; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1509:
+.L1507:
+set 5,%i3
+set 2,%l5
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %l5,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,2; be .L1511; nop
+set 197,%i4
+cmp %i5,0; be .L1513; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1513:
+.L1511:
+set 5,%i3
+set 2,%l4
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %l4,8*(4-2),%l2; sra %l2,8*(4-2),%l2
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,2; be .L1515; nop
+set 198,%i4
+cmp %i5,0; be .L1517; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1517:
+.L1515:
+set 5,%i3
+set 2,%l3
+st %l3,[%fp+-4]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-4],%l2
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,2; be .L1519; nop
+set 199,%i4
+cmp %i5,0; be .L1521; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1521:
+.L1519:
+set 5,%i3
+set 2,%l3
+st %l3,[%fp+-8]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-8],%l2
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,2; be .L1523; nop
+set 200,%i4
+cmp %i5,0; be .L1525; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1525:
+.L1523:
+set 5,%i3
+set 2,%l3
+st %l3,[%fp+-12]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-12],%l2
+wr %g0,%g0,%y; nop; nop; nop; udiv %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,2; be .L1527; nop
+set 201,%i4
+cmp %i5,0; be .L1529; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1529:
+.L1527:
+set 5,%i3
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+ld [%fp+-28],%f30
+fdivs %f31,%f30,%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,2; be .L1531; nop
+set 202,%i4
+cmp %i5,0; be .L1533; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1533:
+.L1531:
+set 5,%i3
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+ldd [%fp+-40],%f28
+fdivd %f30,%f28,%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,2; be .L1535; nop
+set 203,%i4
+cmp %i5,0; be .L1537; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1537:
+.L1535:
+set 5,%i2
+set 2,%l5
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %l5,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,2; be .L1539; nop
+set 204,%i4
+cmp %i5,0; be .L1541; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1541:
+.L1539:
+set 5,%i2
+set 2,%l4
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %l4,8*(4-2),%l2; sra %l2,8*(4-2),%l2
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,2; be .L1543; nop
+set 205,%i4
+cmp %i5,0; be .L1545; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1545:
+.L1543:
+set 5,%i2
+set 2,%l3
+st %l3,[%fp+-4]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-4],%l2
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,2; be .L1547; nop
+set 206,%i4
+cmp %i5,0; be .L1549; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1549:
+.L1547:
+set 5,%i2
+set 2,%l3
+st %l3,[%fp+-8]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-8],%l2
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,2; be .L1551; nop
+set 207,%i4
+cmp %i5,0; be .L1553; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1553:
+.L1551:
+set 5,%i2
+set 2,%l3
+st %l3,[%fp+-12]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-12],%l2
+wr %g0,%g0,%y; nop; nop; nop; udiv %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,2; be .L1555; nop
+set 208,%i4
+cmp %i5,0; be .L1557; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1557:
+.L1555:
+set 5,%i2
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+ld [%fp+-28],%f30
+fdivs %f31,%f30,%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,2; be .L1559; nop
+set 209,%i4
+cmp %i5,0; be .L1561; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1561:
+.L1559:
+set 5,%i2
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+ldd [%fp+-40],%f28
+fdivd %f30,%f28,%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,2; be .L1563; nop
+set 210,%i4
+cmp %i5,0; be .L1565; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1565:
+.L1563:
+set 5,%i1
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sra %i1,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %i1,%l3,%i1
+cmp %i1,2; be .L1567; nop
+set 211,%i4
+cmp %i5,0; be .L1569; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1569:
+.L1567:
+set 5,%i1
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sra %i1,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %i1,%l3,%i1
+cmp %i1,2; be .L1571; nop
+set 212,%i4
+cmp %i5,0; be .L1573; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1573:
+.L1571:
+set 5,%i1
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+sra %i1,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %i1,%l3,%i1
+cmp %i1,2; be .L1575; nop
+set 213,%i4
+cmp %i5,0; be .L1577; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1577:
+.L1575:
+set 5,%i1
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+sra %i1,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %i1,%l3,%i1
+cmp %i1,2; be .L1579; nop
+set 214,%i4
+cmp %i5,0; be .L1581; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1581:
+.L1579:
+set 5,%i1
+set 2,%l3
+st %l3,[%fp+-12]
+mov %i1,%l3
+ld [%fp+-12],%l2
+wr %g0,%g0,%y; nop; nop; nop; udiv %l3,%l2,%l3
+mov %l3,%i1
+cmp %i1,2; be .L1583; nop
+set 215,%i4
+cmp %i5,0; be .L1585; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1585:
+.L1583:
+set 5,%i1
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+st %i1,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+ld [%fp+-28],%f30
+fdivs %f31,%f30,%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%i1
+cmp %i1,2; be .L1587; nop
+set 216,%i4
+cmp %i5,0; be .L1589; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1589:
+.L1587:
+set 5,%i1
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+st %i1,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+ldd [%fp+-40],%f28
+fdivd %f30,%f28,%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%i1
+cmp %i1,2; be .L1591; nop
+set 217,%i4
+cmp %i5,0; be .L1593; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1593:
+.L1591:
+set 5,%l7
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sra %l7,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l7,%l3,%l7
+cmp %l7,2; be .L1595; nop
+set 218,%i4
+cmp %i5,0; be .L1597; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1597:
+.L1595:
+set 5,%l7
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sra %l7,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l7,%l3,%l7
+cmp %l7,2; be .L1599; nop
+set 219,%i4
+cmp %i5,0; be .L1601; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1601:
+.L1599:
+set 5,%l7
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+sra %l7,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l7,%l3,%l7
+cmp %l7,2; be .L1603; nop
+set 220,%i4
+cmp %i5,0; be .L1605; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1605:
+.L1603:
+set 5,%l7
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+sra %l7,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l7,%l3,%l7
+cmp %l7,2; be .L1607; nop
+set 221,%i4
+cmp %i5,0; be .L1609; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1609:
+.L1607:
+set 5,%l7
+set 2,%l3
+st %l3,[%fp+-12]
+mov %l7,%l3
+ld [%fp+-12],%l2
+wr %g0,%g0,%y; nop; nop; nop; udiv %l3,%l2,%l3
+mov %l3,%l7
+cmp %l7,2; be .L1611; nop
+set 222,%i4
+cmp %i5,0; be .L1613; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1613:
+.L1611:
+set 5,%l7
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+st %l7,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+ld [%fp+-28],%f30
+fdivs %f31,%f30,%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l7
+cmp %l7,2; be .L1615; nop
+set 223,%i4
+cmp %i5,0; be .L1617; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1617:
+.L1615:
+set 5,%l7
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+st %l7,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+ldd [%fp+-40],%f28
+fdivd %f30,%f28,%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l7
+cmp %l7,2; be .L1619; nop
+set 224,%i4
+cmp %i5,0; be .L1621; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1621:
+.L1619:
+set 5,%l6
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+wr %g0,%g0,%y; nop; nop; nop; udiv %l6,%l3,%l6
+set 2,%l3
+cmp %l6,%l3; be .L1623; nop
+set 225,%i4
+cmp %i5,0; be .L1625; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1625:
+.L1623:
+set 5,%l6
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+wr %g0,%g0,%y; nop; nop; nop; udiv %l6,%l3,%l6
+set 2,%l3
+cmp %l6,%l3; be .L1627; nop
+set 226,%i4
+cmp %i5,0; be .L1629; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1629:
+.L1627:
+set 5,%l6
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+wr %g0,%g0,%y; nop; nop; nop; udiv %l6,%l3,%l6
+set 2,%l3
+cmp %l6,%l3; be .L1631; nop
+set 227,%i4
+cmp %i5,0; be .L1633; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1633:
+.L1631:
+set 5,%l6
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+wr %g0,%g0,%y; nop; nop; nop; udiv %l6,%l3,%l6
+set 2,%l3
+cmp %l6,%l3; be .L1635; nop
+set 228,%i4
+cmp %i5,0; be .L1637; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1637:
+.L1635:
+set 5,%l6
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l2
+wr %g0,%g0,%y; nop; nop; nop; udiv %l6,%l2,%l6
+cmp %l6,%l3; be .L1639; nop
+set 229,%i4
+cmp %i5,0; be .L1641; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1641:
+.L1639:
+set 5,%l6
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+set .L596,%l3
+ld2 [%l3],%f30
+srl %l6,1,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fmuld %f30,%f28,%f30
+set 1,%l3
+and %l6,%l3,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+faddd %f30,%f28,%f30
+fdtos %f30,%f31
+ld [%fp+-28],%f30
+fdivs %f31,%f30,%f31
+set .L828,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbul .L1644; nop
+fsubs %f31,%f30,%f30
+fstoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+set 0x80000000,%l2
+add %l3,%l2,%l3
+st %l3,[%fp+-88]
+ba .L1645; nop
+.L1644:
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+st %l3,[%fp+-88]
+.L1645:
+ld [%fp+-88],%l6
+set 2,%l3
+cmp %l6,%l3; be .L1646; nop
+set 230,%i4
+cmp %i5,0; be .L1648; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1648:
+.L1646:
+set 5,%l6
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+set .L596,%l3
+ld2 [%l3],%f30
+srl %l6,1,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fmuld %f30,%f28,%f30
+set 1,%l3
+and %l6,%l3,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+faddd %f30,%f28,%f30
+ldd [%fp+-40],%f28
+fdivd %f30,%f28,%f30
+set .L836,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbul .L1651; nop
+fsubd %f30,%f28,%f28
+fdtoi %f28,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+set 0x80000000,%l2
+add %l3,%l2,%l3
+st %l3,[%fp+-92]
+ba .L1652; nop
+.L1651:
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+st %l3,[%fp+-92]
+.L1652:
+ld [%fp+-92],%l6
+set 2,%l3
+cmp %l6,%l3; be .L1653; nop
+set 231,%i4
+cmp %i5,0; be .L1655; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1655:
+.L1653:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l5
+ld [%fp+-16],%f31
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitos %f30,%f30
+fdivs %f31,%f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+fstod %f31,%f30
+set .L1659,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1657; nop
+set 232,%i4
+cmp %i5,0; be .L1660; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1660:
+.L1657:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l4
+ld [%fp+-16],%f31
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitos %f30,%f30
+fdivs %f31,%f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+fstod %f31,%f30
+set .L1659,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1662; nop
+set 233,%i4
+cmp %i5,0; be .L1664; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1664:
+.L1662:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-16],%f31
+ld [%fp+-4],%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitos %f30,%f30
+fdivs %f31,%f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+fstod %f31,%f30
+set .L1659,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1666; nop
+set 234,%i4
+cmp %i5,0; be .L1668; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1668:
+.L1666:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-16],%f31
+ld [%fp+-8],%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitos %f30,%f30
+fdivs %f31,%f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+fstod %f31,%f30
+set .L1659,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1670; nop
+set 235,%i4
+cmp %i5,0; be .L1672; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1672:
+.L1670:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+ld [%fp+-16],%f31
+set .L596,%l2
+ld2 [%l2],%f28
+srl %l3,1,%l2
+st %l2,[%sp+64]; ld [%sp+64],%f26; fitod %f26,%f26
+fmuld %f28,%f26,%f28
+set 1,%l2
+and %l3,%l2,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f26; fitod %f26,%f26
+faddd %f28,%f26,%f28
+fdtos %f28,%f30
+fdivs %f31,%f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+fstod %f31,%f30
+set .L1659,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1674; nop
+set 236,%i4
+cmp %i5,0; be .L1676; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1676:
+.L1674:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+ld [%fp+-16],%f31
+ld [%fp+-28],%f30
+fdivs %f31,%f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+fstod %f31,%f30
+set .L1659,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1678; nop
+set 237,%i4
+cmp %i5,0; be .L1680; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1680:
+.L1678:
+set .L841,%l3
+ld [%l3],%f31
+st %f31,[%fp+-16]
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+ld [%fp+-16],%f31
+fstod %f31,%f30
+ldd [%fp+-40],%f28
+fdivd %f30,%f28,%f30
+fdtos %f30,%f31
+st %f31,[%fp+-16]
+ld [%fp+-16],%f31
+fstod %f31,%f30
+set .L1659,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1682; nop
+set 238,%i4
+cmp %i5,0; be .L1684; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1684:
+.L1682:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l5
+ldd [%fp+-24],%f30
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fdivd %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1659,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1686; nop
+set 239,%i4
+cmp %i5,0; be .L1688; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1688:
+.L1686:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l4
+ldd [%fp+-24],%f30
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fdivd %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1659,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1690; nop
+set 240,%i4
+cmp %i5,0; be .L1692; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1692:
+.L1690:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l3
+st %l3,[%fp+-4]
+ldd [%fp+-24],%f30
+ld [%fp+-4],%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fdivd %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1659,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1694; nop
+set 241,%i4
+cmp %i5,0; be .L1696; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1696:
+.L1694:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l3
+st %l3,[%fp+-8]
+ldd [%fp+-24],%f30
+ld [%fp+-8],%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fdivd %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1659,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1698; nop
+set 242,%i4
+cmp %i5,0; be .L1700; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1700:
+.L1698:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+ldd [%fp+-24],%f30
+set .L596,%l2
+ld2 [%l2],%f28
+srl %l3,1,%l2
+st %l2,[%sp+64]; ld [%sp+64],%f26; fitod %f26,%f26
+fmuld %f28,%f26,%f28
+set 1,%l2
+and %l3,%l2,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f26; fitod %f26,%f26
+faddd %f28,%f26,%f28
+fdivd %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1659,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1702; nop
+set 243,%i4
+cmp %i5,0; be .L1704; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1704:
+.L1702:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set .L529,%l3
+ld [%l3],%f31
+st %f31,[%fp+-28]
+ldd [%fp+-24],%f30
+ld [%fp+-28],%f29
+fstod %f29,%f28
+fdivd %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1659,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1706; nop
+set 244,%i4
+cmp %i5,0; be .L1708; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1708:
+.L1706:
+set .L870,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-24]
+set .L416,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-40]
+ldd [%fp+-24],%f30
+ldd [%fp+-40],%f28
+fdivd %f30,%f28,%f30
+std %f30,[%fp+-24]
+ldd [%fp+-24],%f30
+set .L1659,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L1710; nop
+set 245,%i4
+cmp %i5,0; be .L1712; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1712:
+.L1710:
+set 5,%i3
+set 2,%l5
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %l5,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,%l2,%g1
+; smul %g1,%l2,%g1; sub %l3,%g1,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,1; be .L1714; nop
+set 246,%i4
+cmp %i5,0; be .L1716; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1716:
+.L1714:
+set 5,%i3
+set 2,%l4
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %l4,8*(4-2),%l2; sra %l2,8*(4-2),%l2
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,%l2,%g1
+; smul %g1,%l2,%g1; sub %l3,%g1,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,1; be .L1718; nop
+set 247,%i4
+cmp %i5,0; be .L1720; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1720:
+.L1718:
+set 5,%i3
+set 2,%l3
+st %l3,[%fp+-4]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-4],%l2
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,%l2,%g1
+; smul %g1,%l2,%g1; sub %l3,%g1,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,1; be .L1722; nop
+set 248,%i4
+cmp %i5,0; be .L1724; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1724:
+.L1722:
+set 5,%i3
+set 2,%l3
+st %l3,[%fp+-8]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-8],%l2
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,%l2,%g1
+; smul %g1,%l2,%g1; sub %l3,%g1,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,1; be .L1726; nop
+set 249,%i4
+cmp %i5,0; be .L1728; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1728:
+.L1726:
+set 5,%i3
+set 2,%l3
+st %l3,[%fp+-12]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-12],%l2
+wr %g0,%g0,%y; nop; nop; nop; udiv %l3,%l2,%g1
+; umul %g1,%l2,%g1; sub %l3,%g1,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,1; be .L1730; nop
+set 250,%i4
+cmp %i5,0; be .L1732; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1732:
+.L1730:
+set 5,%i2
+set 2,%l5
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %l5,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,%l2,%g1
+; smul %g1,%l2,%g1; sub %l3,%g1,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,1; be .L1734; nop
+set 251,%i4
+cmp %i5,0; be .L1736; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1736:
+.L1734:
+set 5,%i2
+set 2,%l4
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %l4,8*(4-2),%l2; sra %l2,8*(4-2),%l2
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,%l2,%g1
+; smul %g1,%l2,%g1; sub %l3,%g1,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,1; be .L1738; nop
+set 252,%i4
+cmp %i5,0; be .L1740; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1740:
+.L1738:
+set 5,%i2
+set 2,%l3
+st %l3,[%fp+-4]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-4],%l2
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,%l2,%g1
+; smul %g1,%l2,%g1; sub %l3,%g1,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,1; be .L1742; nop
+set 253,%i4
+cmp %i5,0; be .L1744; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1744:
+.L1742:
+set 5,%i2
+set 2,%l3
+st %l3,[%fp+-8]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-8],%l2
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,%l2,%g1
+; smul %g1,%l2,%g1; sub %l3,%g1,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,1; be .L1746; nop
+set 254,%i4
+cmp %i5,0; be .L1748; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1748:
+.L1746:
+set 5,%i2
+set 2,%l3
+st %l3,[%fp+-12]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-12],%l2
+wr %g0,%g0,%y; nop; nop; nop; udiv %l3,%l2,%g1
+; umul %g1,%l2,%g1; sub %l3,%g1,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,1; be .L1750; nop
+set 255,%i4
+cmp %i5,0; be .L1752; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1752:
+.L1750:
+set 5,%i1
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sra %i1,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %i1,%l3,%g1
+; smul %g1,%l3,%g1; sub %i1,%g1,%i1
+cmp %i1,1; be .L1754; nop
+set 256,%i4
+cmp %i5,0; be .L1756; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1756:
+.L1754:
+set 5,%i1
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sra %i1,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %i1,%l3,%g1
+; smul %g1,%l3,%g1; sub %i1,%g1,%i1
+cmp %i1,1; be .L1758; nop
+set 257,%i4
+cmp %i5,0; be .L1760; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1760:
+.L1758:
+set 5,%i1
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+sra %i1,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %i1,%l3,%g1
+; smul %g1,%l3,%g1; sub %i1,%g1,%i1
+cmp %i1,1; be .L1762; nop
+set 258,%i4
+cmp %i5,0; be .L1764; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1764:
+.L1762:
+set 5,%i1
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+sra %i1,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %i1,%l3,%g1
+; smul %g1,%l3,%g1; sub %i1,%g1,%i1
+cmp %i1,1; be .L1766; nop
+set 259,%i4
+cmp %i5,0; be .L1768; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1768:
+.L1766:
+set 5,%i1
+set 2,%l3
+st %l3,[%fp+-12]
+mov %i1,%l3
+ld [%fp+-12],%l2
+wr %g0,%g0,%y; nop; nop; nop; udiv %l3,%l2,%g1
+; umul %g1,%l2,%g1; sub %l3,%g1,%l3
+mov %l3,%i1
+cmp %i1,1; be .L1770; nop
+set 260,%i4
+cmp %i5,0; be .L1772; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1772:
+.L1770:
+set 5,%l7
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sra %l7,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l7,%l3,%g1
+; smul %g1,%l3,%g1; sub %l7,%g1,%l7
+cmp %l7,1; be .L1774; nop
+set 261,%i4
+cmp %i5,0; be .L1776; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1776:
+.L1774:
+set 5,%l7
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sra %l7,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l7,%l3,%g1
+; smul %g1,%l3,%g1; sub %l7,%g1,%l7
+cmp %l7,1; be .L1778; nop
+set 262,%i4
+cmp %i5,0; be .L1780; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1780:
+.L1778:
+set 5,%l7
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+sra %l7,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l7,%l3,%g1
+; smul %g1,%l3,%g1; sub %l7,%g1,%l7
+cmp %l7,1; be .L1782; nop
+set 263,%i4
+cmp %i5,0; be .L1784; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1784:
+.L1782:
+set 5,%l7
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+sra %l7,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l7,%l3,%g1
+; smul %g1,%l3,%g1; sub %l7,%g1,%l7
+cmp %l7,1; be .L1786; nop
+set 264,%i4
+cmp %i5,0; be .L1788; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1788:
+.L1786:
+set 5,%l7
+set 2,%l3
+st %l3,[%fp+-12]
+mov %l7,%l3
+ld [%fp+-12],%l2
+wr %g0,%g0,%y; nop; nop; nop; udiv %l3,%l2,%g1
+; umul %g1,%l2,%g1; sub %l3,%g1,%l3
+mov %l3,%l7
+cmp %l7,1; be .L1790; nop
+set 265,%i4
+cmp %i5,0; be .L1792; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1792:
+.L1790:
+set 5,%l6
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+wr %g0,%g0,%y; nop; nop; nop; udiv %l6,%l3,%g1
+; umul %g1,%l3,%g1; sub %l6,%g1,%l6
+set 1,%l3
+cmp %l6,%l3; be .L1794; nop
+set 266,%i4
+cmp %i5,0; be .L1796; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1796:
+.L1794:
+set 5,%l6
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+wr %g0,%g0,%y; nop; nop; nop; udiv %l6,%l3,%g1
+; umul %g1,%l3,%g1; sub %l6,%g1,%l6
+set 1,%l3
+cmp %l6,%l3; be .L1798; nop
+set 267,%i4
+cmp %i5,0; be .L1800; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1800:
+.L1798:
+set 5,%l6
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+wr %g0,%g0,%y; nop; nop; nop; udiv %l6,%l3,%g1
+; umul %g1,%l3,%g1; sub %l6,%g1,%l6
+set 1,%l3
+cmp %l6,%l3; be .L1802; nop
+set 268,%i4
+cmp %i5,0; be .L1804; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1804:
+.L1802:
+set 5,%l6
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+wr %g0,%g0,%y; nop; nop; nop; udiv %l6,%l3,%g1
+; umul %g1,%l3,%g1; sub %l6,%g1,%l6
+set 1,%l3
+cmp %l6,%l3; be .L1806; nop
+set 269,%i4
+cmp %i5,0; be .L1808; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1808:
+.L1806:
+set 5,%l6
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+wr %g0,%g0,%y; nop; nop; nop; udiv %l6,%l3,%g1
+; umul %g1,%l3,%g1; sub %l6,%g1,%l6
+set 1,%l3
+cmp %l6,%l3; be .L1810; nop
+set 270,%i4
+cmp %i5,0; be .L1812; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1812:
+.L1810:
+set 5,%i3
+set 2,%l5
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %l5,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+sra %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,1; be .L1814; nop
+set 271,%i4
+cmp %i5,0; be .L1816; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1816:
+.L1814:
+set 5,%i3
+set 2,%l4
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %l4,8*(4-2),%l2; sra %l2,8*(4-2),%l2
+sra %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,1; be .L1818; nop
+set 272,%i4
+cmp %i5,0; be .L1820; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1820:
+.L1818:
+set 5,%i3
+set 2,%l3
+st %l3,[%fp+-4]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-4],%l2
+sra %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,1; be .L1822; nop
+set 273,%i4
+cmp %i5,0; be .L1824; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1824:
+.L1822:
+set 5,%i3
+set 2,%l3
+st %l3,[%fp+-8]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-8],%l2
+sra %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,1; be .L1826; nop
+set 274,%i4
+cmp %i5,0; be .L1828; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1828:
+.L1826:
+set 5,%i3
+set 2,%l3
+st %l3,[%fp+-12]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-12],%l2
+sra %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,1; be .L1830; nop
+set 275,%i4
+cmp %i5,0; be .L1832; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1832:
+.L1830:
+set 5,%i2
+set 2,%l5
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %l5,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+sra %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,1; be .L1834; nop
+set 276,%i4
+cmp %i5,0; be .L1836; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1836:
+.L1834:
+set 5,%i2
+set 2,%l4
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %l4,8*(4-2),%l2; sra %l2,8*(4-2),%l2
+sra %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,1; be .L1838; nop
+set 277,%i4
+cmp %i5,0; be .L1840; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1840:
+.L1838:
+set 5,%i2
+set 2,%l3
+st %l3,[%fp+-4]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-4],%l2
+sra %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,1; be .L1842; nop
+set 278,%i4
+cmp %i5,0; be .L1844; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1844:
+.L1842:
+set 5,%i2
+set 2,%l3
+st %l3,[%fp+-8]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-8],%l2
+sra %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,1; be .L1846; nop
+set 279,%i4
+cmp %i5,0; be .L1848; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1848:
+.L1846:
+set 5,%i2
+set 2,%l3
+st %l3,[%fp+-12]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-12],%l2
+sra %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,1; be .L1850; nop
+set 280,%i4
+cmp %i5,0; be .L1852; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1852:
+.L1850:
+set 5,%i1
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sra %i1,%l3,%i1
+cmp %i1,1; be .L1854; nop
+set 281,%i4
+cmp %i5,0; be .L1856; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1856:
+.L1854:
+set 5,%i1
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sra %i1,%l3,%i1
+cmp %i1,1; be .L1858; nop
+set 282,%i4
+cmp %i5,0; be .L1860; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1860:
+.L1858:
+set 5,%i1
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+sra %i1,%l3,%i1
+cmp %i1,1; be .L1862; nop
+set 283,%i4
+cmp %i5,0; be .L1864; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1864:
+.L1862:
+set 5,%i1
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+sra %i1,%l3,%i1
+cmp %i1,1; be .L1866; nop
+set 284,%i4
+cmp %i5,0; be .L1868; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1868:
+.L1866:
+set 5,%i1
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+sra %i1,%l3,%i1
+cmp %i1,1; be .L1870; nop
+set 285,%i4
+cmp %i5,0; be .L1872; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1872:
+.L1870:
+set 5,%l7
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sra %l7,%l3,%l7
+cmp %l7,1; be .L1874; nop
+set 286,%i4
+cmp %i5,0; be .L1876; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1876:
+.L1874:
+set 5,%l7
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sra %l7,%l3,%l7
+cmp %l7,1; be .L1878; nop
+set 287,%i4
+cmp %i5,0; be .L1880; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1880:
+.L1878:
+set 5,%l7
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+sra %l7,%l3,%l7
+cmp %l7,1; be .L1882; nop
+set 288,%i4
+cmp %i5,0; be .L1884; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1884:
+.L1882:
+set 5,%l7
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+sra %l7,%l3,%l7
+cmp %l7,1; be .L1886; nop
+set 289,%i4
+cmp %i5,0; be .L1888; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1888:
+.L1886:
+set 5,%l7
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+sra %l7,%l3,%l7
+cmp %l7,1; be .L1890; nop
+set 290,%i4
+cmp %i5,0; be .L1892; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1892:
+.L1890:
+set 5,%l6
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+srl %l6,%l3,%l6
+set 1,%l3
+cmp %l6,%l3; be .L1894; nop
+set 291,%i4
+cmp %i5,0; be .L1896; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1896:
+.L1894:
+set 5,%l6
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+srl %l6,%l3,%l6
+set 1,%l3
+cmp %l6,%l3; be .L1898; nop
+set 292,%i4
+cmp %i5,0; be .L1900; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1900:
+.L1898:
+set 5,%l6
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+srl %l6,%l3,%l6
+set 1,%l3
+cmp %l6,%l3; be .L1902; nop
+set 293,%i4
+cmp %i5,0; be .L1904; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1904:
+.L1902:
+set 5,%l6
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+srl %l6,%l3,%l6
+set 1,%l3
+cmp %l6,%l3; be .L1906; nop
+set 294,%i4
+cmp %i5,0; be .L1908; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1908:
+.L1906:
+set 5,%l6
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+srl %l6,%l3,%l6
+set 1,%l3
+cmp %l6,%l3; be .L1910; nop
+set 295,%i4
+cmp %i5,0; be .L1912; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1912:
+.L1910:
+set 5,%i3
+set 2,%l5
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %l5,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+sll %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,20; be .L1914; nop
+set 296,%i4
+cmp %i5,0; be .L1916; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1916:
+.L1914:
+set 5,%i3
+set 2,%l4
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %l4,8*(4-2),%l2; sra %l2,8*(4-2),%l2
+sll %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,20; be .L1918; nop
+set 297,%i4
+cmp %i5,0; be .L1920; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1920:
+.L1918:
+set 5,%i3
+set 2,%l3
+st %l3,[%fp+-4]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-4],%l2
+sll %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,20; be .L1922; nop
+set 298,%i4
+cmp %i5,0; be .L1924; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1924:
+.L1922:
+set 5,%i3
+set 2,%l3
+st %l3,[%fp+-8]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-8],%l2
+sll %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,20; be .L1926; nop
+set 299,%i4
+cmp %i5,0; be .L1928; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1928:
+.L1926:
+set 5,%i3
+set 2,%l3
+st %l3,[%fp+-12]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-12],%l2
+sll %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,20; be .L1930; nop
+set 300,%i4
+cmp %i5,0; be .L1932; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1932:
+.L1930:
+set 5,%i2
+set 2,%l5
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %l5,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+sll %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,20; be .L1934; nop
+set 301,%i4
+cmp %i5,0; be .L1936; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1936:
+.L1934:
+set 5,%i2
+set 2,%l4
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %l4,8*(4-2),%l2; sra %l2,8*(4-2),%l2
+sll %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,20; be .L1938; nop
+set 302,%i4
+cmp %i5,0; be .L1940; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1940:
+.L1938:
+set 5,%i2
+set 2,%l3
+st %l3,[%fp+-4]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-4],%l2
+sll %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,20; be .L1942; nop
+set 303,%i4
+cmp %i5,0; be .L1944; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1944:
+.L1942:
+set 5,%i2
+set 2,%l3
+st %l3,[%fp+-8]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-8],%l2
+sll %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,20; be .L1946; nop
+set 304,%i4
+cmp %i5,0; be .L1948; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1948:
+.L1946:
+set 5,%i2
+set 2,%l3
+st %l3,[%fp+-12]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-12],%l2
+sll %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,20; be .L1950; nop
+set 305,%i4
+cmp %i5,0; be .L1952; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1952:
+.L1950:
+set 5,%i1
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %i1,%l3,%i1
+cmp %i1,20; be .L1954; nop
+set 306,%i4
+cmp %i5,0; be .L1956; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1956:
+.L1954:
+set 5,%i1
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %i1,%l3,%i1
+cmp %i1,20; be .L1958; nop
+set 307,%i4
+cmp %i5,0; be .L1960; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1960:
+.L1958:
+set 5,%i1
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+sll %i1,%l3,%i1
+cmp %i1,20; be .L1962; nop
+set 308,%i4
+cmp %i5,0; be .L1964; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1964:
+.L1962:
+set 5,%i1
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+sll %i1,%l3,%i1
+cmp %i1,20; be .L1966; nop
+set 309,%i4
+cmp %i5,0; be .L1968; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1968:
+.L1966:
+set 5,%i1
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+sll %i1,%l3,%i1
+cmp %i1,20; be .L1970; nop
+set 310,%i4
+cmp %i5,0; be .L1972; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1972:
+.L1970:
+set 5,%l7
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %l7,%l3,%l7
+cmp %l7,20; be .L1974; nop
+set 311,%i4
+cmp %i5,0; be .L1976; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1976:
+.L1974:
+set 5,%l7
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %l7,%l3,%l7
+cmp %l7,20; be .L1978; nop
+set 312,%i4
+cmp %i5,0; be .L1980; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1980:
+.L1978:
+set 5,%l7
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+sll %l7,%l3,%l7
+cmp %l7,20; be .L1982; nop
+set 313,%i4
+cmp %i5,0; be .L1984; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1984:
+.L1982:
+set 5,%l7
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+sll %l7,%l3,%l7
+cmp %l7,20; be .L1986; nop
+set 314,%i4
+cmp %i5,0; be .L1988; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1988:
+.L1986:
+set 5,%l7
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+sll %l7,%l3,%l7
+cmp %l7,20; be .L1990; nop
+set 315,%i4
+cmp %i5,0; be .L1992; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1992:
+.L1990:
+set 5,%l6
+set 2,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %l6,%l3,%l6
+set 20,%l3
+cmp %l6,%l3; be .L1994; nop
+set 316,%i4
+cmp %i5,0; be .L1996; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L1996:
+.L1994:
+set 5,%l6
+set 2,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %l6,%l3,%l6
+set 20,%l3
+cmp %l6,%l3; be .L1998; nop
+set 317,%i4
+cmp %i5,0; be .L2000; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2000:
+.L1998:
+set 5,%l6
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+sll %l6,%l3,%l6
+set 20,%l3
+cmp %l6,%l3; be .L2002; nop
+set 318,%i4
+cmp %i5,0; be .L2004; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2004:
+.L2002:
+set 5,%l6
+set 2,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+sll %l6,%l3,%l6
+set 20,%l3
+cmp %l6,%l3; be .L2006; nop
+set 319,%i4
+cmp %i5,0; be .L2008; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2008:
+.L2006:
+set 5,%l6
+set 2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+sll %l6,%l3,%l6
+set 20,%l3
+cmp %l6,%l3; be .L2010; nop
+set 320,%i4
+cmp %i5,0; be .L2012; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2012:
+.L2010:
+set 12,%i3
+set 10,%l5
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %l5,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+and %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,8; be .L2014; nop
+set 321,%i4
+cmp %i5,0; be .L2016; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2016:
+.L2014:
+set 12,%i3
+set 10,%l4
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %l4,8*(4-2),%l2; sra %l2,8*(4-2),%l2
+and %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,8; be .L2018; nop
+set 322,%i4
+cmp %i5,0; be .L2020; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2020:
+.L2018:
+set 12,%i3
+set 10,%l3
+st %l3,[%fp+-4]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-4],%l2
+and %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,8; be .L2022; nop
+set 323,%i4
+cmp %i5,0; be .L2024; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2024:
+.L2022:
+set 12,%i3
+set 10,%l3
+st %l3,[%fp+-8]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-8],%l2
+and %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,8; be .L2026; nop
+set 324,%i4
+cmp %i5,0; be .L2028; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2028:
+.L2026:
+set 12,%i3
+set 10,%l3
+st %l3,[%fp+-12]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-12],%l2
+and %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,8; be .L2030; nop
+set 325,%i4
+cmp %i5,0; be .L2032; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2032:
+.L2030:
+set 12,%i2
+set 10,%l5
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %l5,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+and %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,8; be .L2034; nop
+set 326,%i4
+cmp %i5,0; be .L2036; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2036:
+.L2034:
+set 12,%i2
+set 10,%l4
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %l4,8*(4-2),%l2; sra %l2,8*(4-2),%l2
+and %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,8; be .L2038; nop
+set 327,%i4
+cmp %i5,0; be .L2040; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2040:
+.L2038:
+set 12,%i2
+set 10,%l3
+st %l3,[%fp+-4]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-4],%l2
+and %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,8; be .L2042; nop
+set 328,%i4
+cmp %i5,0; be .L2044; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2044:
+.L2042:
+set 12,%i2
+set 10,%l3
+st %l3,[%fp+-8]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-8],%l2
+and %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,8; be .L2046; nop
+set 329,%i4
+cmp %i5,0; be .L2048; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2048:
+.L2046:
+set 12,%i2
+set 10,%l3
+st %l3,[%fp+-12]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-12],%l2
+and %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,8; be .L2050; nop
+set 330,%i4
+cmp %i5,0; be .L2052; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2052:
+.L2050:
+set 12,%i1
+set 10,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+and %i1,%l3,%i1
+cmp %i1,8; be .L2054; nop
+set 331,%i4
+cmp %i5,0; be .L2056; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2056:
+.L2054:
+set 12,%i1
+set 10,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+and %i1,%l3,%i1
+cmp %i1,8; be .L2058; nop
+set 332,%i4
+cmp %i5,0; be .L2060; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2060:
+.L2058:
+set 12,%i1
+set 10,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+and %i1,%l3,%i1
+cmp %i1,8; be .L2062; nop
+set 333,%i4
+cmp %i5,0; be .L2064; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2064:
+.L2062:
+set 12,%i1
+set 10,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+and %i1,%l3,%i1
+cmp %i1,8; be .L2066; nop
+set 334,%i4
+cmp %i5,0; be .L2068; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2068:
+.L2066:
+set 12,%i1
+set 10,%l3
+st %l3,[%fp+-12]
+mov %i1,%l3
+ld [%fp+-12],%l2
+and %l3,%l2,%l3
+mov %l3,%i1
+cmp %i1,8; be .L2070; nop
+set 335,%i4
+cmp %i5,0; be .L2072; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2072:
+.L2070:
+set 12,%l7
+set 10,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+and %l7,%l3,%l7
+cmp %l7,8; be .L2074; nop
+set 336,%i4
+cmp %i5,0; be .L2076; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2076:
+.L2074:
+set 12,%l7
+set 10,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+and %l7,%l3,%l7
+cmp %l7,8; be .L2078; nop
+set 337,%i4
+cmp %i5,0; be .L2080; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2080:
+.L2078:
+set 12,%l7
+set 10,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+and %l7,%l3,%l7
+cmp %l7,8; be .L2082; nop
+set 338,%i4
+cmp %i5,0; be .L2084; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2084:
+.L2082:
+set 12,%l7
+set 10,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+and %l7,%l3,%l7
+cmp %l7,8; be .L2086; nop
+set 339,%i4
+cmp %i5,0; be .L2088; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2088:
+.L2086:
+set 12,%l7
+set 10,%l3
+st %l3,[%fp+-12]
+mov %l7,%l3
+ld [%fp+-12],%l2
+and %l3,%l2,%l3
+mov %l3,%l7
+cmp %l7,8; be .L2090; nop
+set 340,%i4
+cmp %i5,0; be .L2092; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2092:
+.L2090:
+set 12,%l6
+set 10,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+and %l6,%l3,%l6
+set 8,%l3
+cmp %l6,%l3; be .L2094; nop
+set 341,%i4
+cmp %i5,0; be .L2096; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2096:
+.L2094:
+set 12,%l6
+set 10,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+and %l6,%l3,%l6
+set 8,%l3
+cmp %l6,%l3; be .L2098; nop
+set 342,%i4
+cmp %i5,0; be .L2100; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2100:
+.L2098:
+set 12,%l6
+set 10,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+and %l6,%l3,%l6
+set 8,%l3
+cmp %l6,%l3; be .L2102; nop
+set 343,%i4
+cmp %i5,0; be .L2104; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2104:
+.L2102:
+set 12,%l6
+set 10,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+and %l6,%l3,%l6
+set 8,%l3
+cmp %l6,%l3; be .L2106; nop
+set 344,%i4
+cmp %i5,0; be .L2108; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2108:
+.L2106:
+set 12,%l6
+set 10,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+and %l6,%l3,%l6
+set 8,%l3
+cmp %l6,%l3; be .L2110; nop
+set 345,%i4
+cmp %i5,0; be .L2112; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2112:
+.L2110:
+set 12,%i3
+set 10,%l5
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %l5,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+xor %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,6; be .L2114; nop
+set 346,%i4
+cmp %i5,0; be .L2116; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2116:
+.L2114:
+set 12,%i3
+set 10,%l4
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %l4,8*(4-2),%l2; sra %l2,8*(4-2),%l2
+xor %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,6; be .L2118; nop
+set 347,%i4
+cmp %i5,0; be .L2120; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2120:
+.L2118:
+set 12,%i3
+set 10,%l3
+st %l3,[%fp+-4]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-4],%l2
+xor %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,6; be .L2122; nop
+set 348,%i4
+cmp %i5,0; be .L2124; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2124:
+.L2122:
+set 12,%i3
+set 10,%l3
+st %l3,[%fp+-8]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-8],%l2
+xor %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,6; be .L2126; nop
+set 349,%i4
+cmp %i5,0; be .L2128; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2128:
+.L2126:
+set 12,%i3
+set 10,%l3
+st %l3,[%fp+-12]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-12],%l2
+xor %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,6; be .L2130; nop
+set 350,%i4
+cmp %i5,0; be .L2132; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2132:
+.L2130:
+set 12,%i2
+set 10,%l5
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %l5,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+xor %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,6; be .L2134; nop
+set 351,%i4
+cmp %i5,0; be .L2136; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2136:
+.L2134:
+set 12,%i2
+set 10,%l4
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %l4,8*(4-2),%l2; sra %l2,8*(4-2),%l2
+xor %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,6; be .L2138; nop
+set 352,%i4
+cmp %i5,0; be .L2140; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2140:
+.L2138:
+set 12,%i2
+set 10,%l3
+st %l3,[%fp+-4]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-4],%l2
+xor %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,6; be .L2142; nop
+set 353,%i4
+cmp %i5,0; be .L2144; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2144:
+.L2142:
+set 12,%i2
+set 10,%l3
+st %l3,[%fp+-8]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-8],%l2
+xor %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,6; be .L2146; nop
+set 354,%i4
+cmp %i5,0; be .L2148; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2148:
+.L2146:
+set 12,%i2
+set 10,%l3
+st %l3,[%fp+-12]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-12],%l2
+xor %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,6; be .L2150; nop
+set 355,%i4
+cmp %i5,0; be .L2152; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2152:
+.L2150:
+set 12,%i1
+set 10,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+xor %i1,%l3,%i1
+cmp %i1,6; be .L2154; nop
+set 356,%i4
+cmp %i5,0; be .L2156; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2156:
+.L2154:
+set 12,%i1
+set 10,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+xor %i1,%l3,%i1
+cmp %i1,6; be .L2158; nop
+set 357,%i4
+cmp %i5,0; be .L2160; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2160:
+.L2158:
+set 12,%i1
+set 10,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+xor %i1,%l3,%i1
+cmp %i1,6; be .L2162; nop
+set 358,%i4
+cmp %i5,0; be .L2164; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2164:
+.L2162:
+set 12,%i1
+set 10,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+xor %i1,%l3,%i1
+cmp %i1,6; be .L2166; nop
+set 359,%i4
+cmp %i5,0; be .L2168; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2168:
+.L2166:
+set 12,%i1
+set 10,%l3
+st %l3,[%fp+-12]
+mov %i1,%l3
+ld [%fp+-12],%l2
+xor %l3,%l2,%l3
+mov %l3,%i1
+cmp %i1,6; be .L2170; nop
+set 360,%i4
+cmp %i5,0; be .L2172; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2172:
+.L2170:
+set 12,%l7
+set 10,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+xor %l7,%l3,%l7
+cmp %l7,6; be .L2174; nop
+set 361,%i4
+cmp %i5,0; be .L2176; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2176:
+.L2174:
+set 12,%l7
+set 10,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+xor %l7,%l3,%l7
+cmp %l7,6; be .L2178; nop
+set 362,%i4
+cmp %i5,0; be .L2180; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2180:
+.L2178:
+set 12,%l7
+set 10,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+xor %l7,%l3,%l7
+cmp %l7,6; be .L2182; nop
+set 363,%i4
+cmp %i5,0; be .L2184; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2184:
+.L2182:
+set 12,%l7
+set 10,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+xor %l7,%l3,%l7
+cmp %l7,6; be .L2186; nop
+set 364,%i4
+cmp %i5,0; be .L2188; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2188:
+.L2186:
+set 12,%l7
+set 10,%l3
+st %l3,[%fp+-12]
+mov %l7,%l3
+ld [%fp+-12],%l2
+xor %l3,%l2,%l3
+mov %l3,%l7
+cmp %l7,6; be .L2190; nop
+set 365,%i4
+cmp %i5,0; be .L2192; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2192:
+.L2190:
+set 12,%l6
+set 10,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+xor %l6,%l3,%l6
+set 6,%l3
+cmp %l6,%l3; be .L2194; nop
+set 366,%i4
+cmp %i5,0; be .L2196; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2196:
+.L2194:
+set 12,%l6
+set 10,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+xor %l6,%l3,%l6
+set 6,%l3
+cmp %l6,%l3; be .L2198; nop
+set 367,%i4
+cmp %i5,0; be .L2200; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2200:
+.L2198:
+set 12,%l6
+set 10,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+xor %l6,%l3,%l6
+set 6,%l3
+cmp %l6,%l3; be .L2202; nop
+set 368,%i4
+cmp %i5,0; be .L2204; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2204:
+.L2202:
+set 12,%l6
+set 10,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+xor %l6,%l3,%l6
+set 6,%l3
+cmp %l6,%l3; be .L2206; nop
+set 369,%i4
+cmp %i5,0; be .L2208; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2208:
+.L2206:
+set 12,%l6
+set 10,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+xor %l6,%l3,%l6
+set 6,%l3
+cmp %l6,%l3; be .L2210; nop
+set 370,%i4
+cmp %i5,0; be .L2212; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2212:
+.L2210:
+set 12,%i3
+set 10,%l5
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %l5,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+or %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,14; be .L2214; nop
+set 371,%i4
+cmp %i5,0; be .L2216; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2216:
+.L2214:
+set 12,%i3
+set 10,%l4
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %l4,8*(4-2),%l2; sra %l2,8*(4-2),%l2
+or %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,14; be .L2218; nop
+set 372,%i4
+cmp %i5,0; be .L2220; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2220:
+.L2218:
+set 12,%i3
+set 10,%l3
+st %l3,[%fp+-4]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-4],%l2
+or %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,14; be .L2222; nop
+set 373,%i4
+cmp %i5,0; be .L2224; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2224:
+.L2222:
+set 12,%i3
+set 10,%l3
+st %l3,[%fp+-8]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-8],%l2
+or %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,14; be .L2226; nop
+set 374,%i4
+cmp %i5,0; be .L2228; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2228:
+.L2226:
+set 12,%i3
+set 10,%l3
+st %l3,[%fp+-12]
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+ld [%fp+-12],%l2
+or %l3,%l2,%l3
+mov %l3,%i3
+sll %i3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,14; be .L2230; nop
+set 375,%i4
+cmp %i5,0; be .L2232; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2232:
+.L2230:
+set 12,%i2
+set 10,%l5
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %l5,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+or %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,14; be .L2234; nop
+set 376,%i4
+cmp %i5,0; be .L2236; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2236:
+.L2234:
+set 12,%i2
+set 10,%l4
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %l4,8*(4-2),%l2; sra %l2,8*(4-2),%l2
+or %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,14; be .L2238; nop
+set 377,%i4
+cmp %i5,0; be .L2240; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2240:
+.L2238:
+set 12,%i2
+set 10,%l3
+st %l3,[%fp+-4]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-4],%l2
+or %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,14; be .L2242; nop
+set 378,%i4
+cmp %i5,0; be .L2244; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2244:
+.L2242:
+set 12,%i2
+set 10,%l3
+st %l3,[%fp+-8]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-8],%l2
+or %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,14; be .L2246; nop
+set 379,%i4
+cmp %i5,0; be .L2248; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2248:
+.L2246:
+set 12,%i2
+set 10,%l3
+st %l3,[%fp+-12]
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+ld [%fp+-12],%l2
+or %l3,%l2,%l3
+mov %l3,%i2
+sll %i2,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,14; be .L2250; nop
+set 380,%i4
+cmp %i5,0; be .L2252; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2252:
+.L2250:
+set 12,%i1
+set 10,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+or %i1,%l3,%i1
+cmp %i1,14; be .L2254; nop
+set 381,%i4
+cmp %i5,0; be .L2256; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2256:
+.L2254:
+set 12,%i1
+set 10,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+or %i1,%l3,%i1
+cmp %i1,14; be .L2258; nop
+set 382,%i4
+cmp %i5,0; be .L2260; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2260:
+.L2258:
+set 12,%i1
+set 10,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+or %i1,%l3,%i1
+cmp %i1,14; be .L2262; nop
+set 383,%i4
+cmp %i5,0; be .L2264; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2264:
+.L2262:
+set 12,%i1
+set 10,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+or %i1,%l3,%i1
+cmp %i1,14; be .L2266; nop
+set 384,%i4
+cmp %i5,0; be .L2268; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2268:
+.L2266:
+set 12,%i1
+set 10,%l3
+st %l3,[%fp+-12]
+mov %i1,%l3
+ld [%fp+-12],%l2
+or %l3,%l2,%l3
+mov %l3,%i1
+cmp %i1,14; be .L2270; nop
+set 385,%i4
+cmp %i5,0; be .L2272; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2272:
+.L2270:
+set 12,%l7
+set 10,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+or %l7,%l3,%l7
+cmp %l7,14; be .L2274; nop
+set 386,%i4
+cmp %i5,0; be .L2276; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2276:
+.L2274:
+set 12,%l7
+set 10,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+or %l7,%l3,%l7
+cmp %l7,14; be .L2278; nop
+set 387,%i4
+cmp %i5,0; be .L2280; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2280:
+.L2278:
+set 12,%l7
+set 10,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+or %l7,%l3,%l7
+cmp %l7,14; be .L2282; nop
+set 388,%i4
+cmp %i5,0; be .L2284; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2284:
+.L2282:
+set 12,%l7
+set 10,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+or %l7,%l3,%l7
+cmp %l7,14; be .L2286; nop
+set 389,%i4
+cmp %i5,0; be .L2288; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2288:
+.L2286:
+set 12,%l7
+set 10,%l3
+st %l3,[%fp+-12]
+mov %l7,%l3
+ld [%fp+-12],%l2
+or %l3,%l2,%l3
+mov %l3,%l7
+cmp %l7,14; be .L2290; nop
+set 390,%i4
+cmp %i5,0; be .L2292; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2292:
+.L2290:
+set 12,%l6
+set 10,%l5
+sll %l5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+or %l6,%l3,%l6
+set 14,%l3
+cmp %l6,%l3; be .L2294; nop
+set 391,%i4
+cmp %i5,0; be .L2296; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2296:
+.L2294:
+set 12,%l6
+set 10,%l4
+sll %l4,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+or %l6,%l3,%l6
+set 14,%l3
+cmp %l6,%l3; be .L2298; nop
+set 392,%i4
+cmp %i5,0; be .L2300; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2300:
+.L2298:
+set 12,%l6
+set 10,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+or %l6,%l3,%l6
+set 14,%l3
+cmp %l6,%l3; be .L2302; nop
+set 393,%i4
+cmp %i5,0; be .L2304; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2304:
+.L2302:
+set 12,%l6
+set 10,%l3
+st %l3,[%fp+-8]
+ld [%fp+-8],%l3
+or %l6,%l3,%l6
+set 14,%l3
+cmp %l6,%l3; be .L2306; nop
+set 394,%i4
+cmp %i5,0; be .L2308; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2308:
+.L2306:
+set 12,%l6
+set 10,%l3
+st %l3,[%fp+-12]
+ld [%fp+-12],%l3
+or %l6,%l3,%l6
+set 14,%l3
+cmp %l6,%l3; be .L2310; nop
+set 395,%i4
+cmp %i5,0; be .L2312; nop
+set .687,%o0
+mov %i4,%o1
+call printf; nop
+.L2312:
+.L2310:
+cmp %i4,0; be .L2314; nop
+set 1,%l3
+st %l3,[%fp+-52]
+ld [%i0+44],%l3
+cmp %l3,0; be .L2316; nop
+set .688,%o0
+set 1,%o1
+call printf; nop
+.L2316:
+.L2314:
+ld [%fp+-52],%i0
+.L686:
+ret; restore
+.type s714,#function
+.size s714,.-s714
+.section ".data"
+.type .2319,#object
+.align 1
+.2319:
+.byte 115
+.byte 55
+.byte 49
+.byte 53
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size .2319,11
+.type .2320,#object
+.size .2320,8
+.align 1
+.2320:
+.byte 115
+.byte 55
+.byte 49
+.byte 53
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.global s715
+.section ".text"
+.align 4
+s715:
+save %sp,-96,%sp
+mov %g0,%l6
+mov %g0,%i1
+set .2320,%i5
+add %i0,60,%i4
+mov %g0,%i2
+.L2321:
+.L2322:
+mov %i4,%l5
+add %l5,1,%i4
+mov %i5,%l4
+add %l4,1,%i5
+ldsb [%l4],%l4
+stb %l4,[%l5]
+sll %l4,8*(4-1),%l5; sra %l5,8*(4-1),%l5
+cmp %l5,0; bne .L2321; nop
+set 1,%l5
+mov %l5,%i3
+add %i3,1,%i3
+add %i3,1,%i3
+add %i3,1,%i3
+add %i3,1,%i3
+add %i3,1,%l5
+mov %l5,%i3
+cmp %l5,6; be .L2324; nop
+ld [%i0+44],%l5
+cmp %l5,0; be .L2326; nop
+set .2319,%o0
+set 1,%o1
+call printf; nop
+.L2326:
+add %i2,1,%i2
+.L2324:
+mov %i1,%o0
+set 3,%l7
+add %l7,2,%o1
+mov %l6,%o2
+call s715f; nop
+cmp %o0,5; be .L2328; nop
+ld [%i0+44],%l5
+cmp %l5,0; be .L2330; nop
+set .2319,%o0
+set 2,%o1
+call printf; nop
+.L2330:
+add %i2,2,%i2
+.L2328:
+mov %i2,%i0
+.L2318:
+ret; restore
+.type s715,#function
+.size s715,.-s715
+.global s715f
+.align 4
+s715f:
+mov %o1,%o0
+.L2332:
+retl; nop
+.type s715f,#function
+.size s715f,.-s715f
+.section ".data"
+.type .2334,#object
+.align 1
+.2334:
+.byte 115
+.byte 55
+.byte 50
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size .2334,10
+.type .2335,#object
+.size .2335,8
+.align 1
+.2335:
+.byte 115
+.byte 55
+.byte 50
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.global s72
+.section ".text"
+.align 4
+s72:
+save %sp,-120,%sp
+set .2335,%i4
+add %i0,60,%i3
+mov %g0,%i1
+.L2336:
+.L2337:
+mov %i3,%l3
+add %l3,1,%i3
+mov %i4,%l2
+add %l2,1,%i4
+ldsb [%l2],%l2
+stb %l2,[%l3]
+sll %l2,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,0; bne .L2336; nop
+set 2,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+cmp %l3,2; be .L2339; nop
+set 1,%l3
+add %i1,1,%i1
+set .2334,%o0
+mov %l3,%o1
+call printf; nop
+.L2339:
+ld [%fp+-4],%l3
+neg %l3,%l2
+add %l3,%l2,%l3
+cmp %l3,0; be .L2341; nop
+set 2,%l3
+add %i1,2,%i1
+set .2334,%o0
+mov %l3,%o1
+call printf; nop
+.L2341:
+st %g0,[%fp+-4]
+mov %g0,%i5
+ba .L2346; nop
+.L2343:
+ld [%fp+-4],%l3
+sll %l3,1,%l3
+or %l3,1,%l3
+st %l3,[%fp+-4]
+.L2344:
+add %i5,1,%i5
+.L2346:
+ld [%i0+4],%l3
+cmp %i5,%l3; bl .L2343; nop
+ld [%fp+-4],%l3
+not %l3,%l3
+cmp %l3,0; be .L2347; nop
+set 4,%l3
+add %i1,4,%i1
+set .2334,%o0
+mov %l3,%o1
+call printf; nop
+.L2347:
+set 5,%l3
+st %l3,[%fp+-4]
+ld [%fp+-4],%l3
+add %l3,1,%l3
+st %l3,[%fp+-4]
+cmp %l3,6; bne .L2354; nop
+ld [%fp+-4],%l3
+sub %l3,1,%l3
+st %l3,[%fp+-4]
+cmp %l3,5; bne .L2354; nop
+ld [%fp+-4],%l3
+add %l3,1,%l2
+st %l2,[%fp+-4]
+cmp %l3,5; bne .L2354; nop
+ld [%fp+-4],%l3
+sub %l3,1,%l2
+st %l2,[%fp+-4]
+cmp %l3,6; bne .L2354; nop
+ld [%fp+-4],%l3
+cmp %l3,5; be .L2349; nop
+.L2354:
+set 8,%l3
+add %i1,8,%i1
+set .2334,%o0
+mov %l3,%o1
+call printf; nop
+.L2349:
+set 26,%l6
+set 26,%l4
+set .L2355,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-16]
+set 26,%l5
+set 26,%l3
+st %l3,[%fp+-8]
+set 26,%l7
+set .L2356,%l3
+ld [%l3],%f31
+st %f31,[%fp+-20]
+mov %g0,%i2
+sll %l5,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+sll %l3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,26; bne .L2363; nop
+mov %l7,%l3
+sll %l3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,26; bne .L2363; nop
+mov %l4,%l3
+sll %l3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,26; bne .L2363; nop
+ld [%fp+-8],%l3
+sll %l3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,26; bne .L2363; nop
+ld [%fp+-20],%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+sll %l3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,26; bne .L2363; nop
+ldd [%fp+-16],%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+sll %l3,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,26; be .L2357; nop
+.L2363:
+add %i2,1,%i2
+.L2357:
+sll %l6,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %l3,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,26; bne .L2370; nop
+mov %l7,%l3
+sll %l3,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,26; bne .L2370; nop
+mov %l4,%l3
+sll %l3,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,26; bne .L2370; nop
+ld [%fp+-8],%l3
+sll %l3,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,26; bne .L2370; nop
+ld [%fp+-20],%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+sll %l3,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,26; bne .L2370; nop
+ldd [%fp+-16],%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+sll %l3,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,26; be .L2364; nop
+.L2370:
+add %i2,2,%i2
+.L2364:
+sll %l6,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,26; bne .L2377; nop
+sll %l5,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,26; bne .L2377; nop
+cmp %l4,26; bne .L2377; nop
+ld [%fp+-8],%l3
+cmp %l3,26; bne .L2377; nop
+ld [%fp+-20],%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+cmp %l3,26; bne .L2377; nop
+ldd [%fp+-16],%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+cmp %l3,26; be .L2371; nop
+.L2377:
+add %i2,4,%i2
+.L2371:
+sll %l6,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,26; bne .L2384; nop
+sll %l5,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+cmp %l3,26; bne .L2384; nop
+cmp %l7,26; bne .L2384; nop
+ld [%fp+-8],%l3
+cmp %l3,26; bne .L2384; nop
+ld [%fp+-20],%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+cmp %l3,26; bne .L2384; nop
+ldd [%fp+-16],%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+cmp %l3,26; be .L2378; nop
+.L2384:
+add %i2,8,%i2
+.L2378:
+set 26,%l3
+sll %l6,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+cmp %l2,%l3; bne .L2393; nop
+sll %l5,8*(4-2),%l2; sra %l2,8*(4-2),%l2
+cmp %l2,%l3; bne .L2393; nop
+mov %l7,%l2
+cmp %l2,%l3; bne .L2393; nop
+mov %l4,%l2
+cmp %l2,%l3; bne .L2393; nop
+ld [%fp+-20],%f31
+set .L828,%l3
+ld [%l3],%f30
+fcmpes %f31,%f30; nop; fbul .L2394; nop
+fsubs %f31,%f30,%f30
+fstoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+set 0x80000000,%l2
+add %l3,%l2,%l3
+st %l3,[%fp+-24]
+ba .L2395; nop
+.L2394:
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+st %l3,[%fp+-24]
+.L2395:
+ld [%fp+-24],%l3
+set 26,%l2
+cmp %l3,%l2; bne .L2393; nop
+ldd [%fp+-16],%f30
+set .L836,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbul .L2396; nop
+fsubd %f30,%f28,%f28
+fdtoi %f28,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+set 0x80000000,%l2
+add %l3,%l2,%l3
+st %l3,[%fp+-28]
+ba .L2397; nop
+.L2396:
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+st %l3,[%fp+-28]
+.L2397:
+ld [%fp+-28],%l3
+set 26,%l2
+cmp %l3,%l2; be .L2385; nop
+.L2393:
+add %i2,16,%i2
+.L2385:
+set .L2355,%l3
+ld2 [%l3],%f30
+sll %l6,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f29; fitos %f29,%f29
+fstod %f29,%f28
+fcmped %f28,%f30; nop; fbne .L2404; nop
+sll %l5,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f29; fitos %f29,%f29
+fstod %f29,%f28
+fcmped %f28,%f30; nop; fbne .L2404; nop
+st %l7,[%sp+64]; ld [%sp+64],%f29; fitos %f29,%f29
+fstod %f29,%f28
+fcmped %f28,%f30; nop; fbne .L2404; nop
+st %l4,[%sp+64]; ld [%sp+64],%f29; fitos %f29,%f29
+fstod %f29,%f28
+fcmped %f28,%f30; nop; fbne .L2404; nop
+ld [%fp+-8],%l3
+set .L596,%l2
+ld2 [%l2],%f28
+srl %l3,1,%l2
+st %l2,[%sp+64]; ld [%sp+64],%f26; fitod %f26,%f26
+fmuld %f28,%f26,%f28
+set 1,%l2
+and %l3,%l2,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f26; fitod %f26,%f26
+faddd %f28,%f26,%f28
+fdtos %f28,%f29
+fstod %f29,%f28
+fcmped %f28,%f30; nop; fbne .L2404; nop
+ldd [%fp+-16],%f28
+fdtos %f28,%f29
+fstod %f29,%f28
+fcmped %f28,%f30; nop; fbue .L2398; nop
+.L2404:
+add %i2,32,%i2
+.L2398:
+set .L2355,%l3
+ld2 [%l3],%f30
+sll %l6,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fcmped %f28,%f30; nop; fbne .L2411; nop
+sll %l5,8*(4-2),%l3; sra %l3,8*(4-2),%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fcmped %f28,%f30; nop; fbne .L2411; nop
+st %l7,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fcmped %f28,%f30; nop; fbne .L2411; nop
+st %l4,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fcmped %f28,%f30; nop; fbne .L2411; nop
+ld [%fp+-8],%l3
+set .L596,%l2
+ld2 [%l2],%f28
+srl %l3,1,%l2
+st %l2,[%sp+64]; ld [%sp+64],%f26; fitod %f26,%f26
+fmuld %f28,%f26,%f28
+set 1,%l2
+and %l3,%l2,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f26; fitod %f26,%f26
+faddd %f28,%f26,%f28
+fcmped %f28,%f30; nop; fbne .L2411; nop
+ld [%fp+-20],%f29
+fstod %f29,%f28
+fcmped %f28,%f30; nop; fbue .L2405; nop
+.L2411:
+add %i2,64,%i2
+.L2405:
+cmp %i2,0; be .L2412; nop
+set 16,%l3
+add %i1,16,%i1
+set .2334,%o0
+mov %l3,%o1
+call printf; nop
+.L2412:
+mov %i1,%i0
+.L2333:
+ret; restore
+.type s72,#function
+.size s72,.-s72
+.section ".data"
+.type .2415,#object
+.align 1
+.2415:
+.byte 115
+.byte 55
+.byte 53
+.byte 55
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size .2415,11
+.type .2416,#object
+.size .2416,8
+.align 1
+.2416:
+.byte 115
+.byte 55
+.byte 53
+.byte 55
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.global s757
+.section ".text"
+.align 4
+s757:
+save %sp,-208,%sp
+set .2416,%l3
+st %l3,[%fp+-76]
+add %i0,60,%l3
+st %l3,[%fp+-80]
+st %g0,[%fp+-84]
+.L2417:
+.L2418:
+ld [%fp+-80],%l3
+add %l3,1,%l2
+st %l2,[%fp+-80]
+ld [%fp+-76],%l2
+add %l2,1,%l1
+st %l1,[%fp+-76]
+ldsb [%l2],%l2
+stb %l2,[%l3]
+sll %l2,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,0; bne .L2417; nop
+set 40,%l3
+st %l3,[%fp+-88]
+ld [%fp+-88],%l3
+sll %l3,3,%l2
+sll %l2,2,%l2
+cmp %l2,1280; bne .L2422; nop
+sra %l3,3,%l3
+sra %l3,2,%l3
+cmp %l3,1; be .L2420; nop
+.L2422:
+ld [%fp+-84],%l3
+add %l3,1,%l3
+st %l3,[%fp+-84]
+ld [%i0+44],%l3
+cmp %l3,0; be .L2423; nop
+set .2415,%o0
+set 1,%o1
+call printf; nop
+.L2423:
+.L2420:
+mov %g0,%i1
+mov %g0,%l4
+ba .L2428; nop
+.L2425:
+set 1,%l6
+ld [%i0+16],%l3
+sub %l3,1,%l3
+sll %l6,%l3,%l5
+st %g0,[%fp+-68]
+ld [%fp+-68],%l3
+not %l3,%l3
+srl %l3,%l4,%l2
+st %l2,[%fp+-72]
+sll %l3,%l4,%l3
+st %l3,[%fp+-68]
+mov %g0,%l7
+ba .L2432; nop
+.L2429:
+cmp %l7,%l4; bge .L2440; nop
+set 1,%l3
+st %l3,[%fp+-96]
+ba .L2441; nop
+.L2440:
+st %g0,[%fp+-96]
+.L2441:
+ld [%fp+-68],%l3
+and %l6,%l3,%l3
+cmp %l3,%g0; bne .L2442; nop
+set 1,%l3
+st %l3,[%fp+-100]
+ba .L2443; nop
+.L2442:
+st %g0,[%fp+-100]
+.L2443:
+ld [%fp+-96],%l3
+ld [%fp+-100],%l2
+cmp %l3,%l2; bne .L2439; nop
+cmp %l7,%l4; bge .L2444; nop
+set 1,%l3
+st %l3,[%fp+-104]
+ba .L2445; nop
+.L2444:
+st %g0,[%fp+-104]
+.L2445:
+ld [%fp+-72],%l3
+and %l5,%l3,%l3
+cmp %l3,%g0; bne .L2446; nop
+set 1,%l3
+st %l3,[%fp+-108]
+ba .L2447; nop
+.L2446:
+st %g0,[%fp+-108]
+.L2447:
+ld [%fp+-104],%l3
+ld [%fp+-108],%l2
+cmp %l3,%l2; be .L2433; nop
+.L2439:
+set 1,%i1
+.L2433:
+sll %l6,1,%l6
+srl %l5,1,%l5
+.L2430:
+add %l7,1,%l7
+.L2432:
+ld [%i0+16],%l3
+cmp %l7,%l3; bl .L2429; nop
+.L2426:
+add %l4,1,%l4
+.L2428:
+ld [%i0+16],%l3
+cmp %l4,%l3; bl .L2425; nop
+cmp %i1,0; be .L2448; nop
+ld [%fp+-84],%l3
+add %l3,2,%l3
+st %l3,[%fp+-84]
+ld [%i0+44],%l3
+cmp %l3,0; be .L2450; nop
+set .2415,%o0
+set 2,%o1
+call printf; nop
+.L2450:
+.L2448:
+set 3,%i2
+set 2,%i3
+set 1,%i4
+cmp %i2,%i3; bge .L2458; nop
+set 1,%l3
+st %l3,[%fp+-100]
+ba .L2459; nop
+.L2458:
+st %g0,[%fp+-100]
+.L2459:
+ld [%fp+-100],%l3
+cmp %l3,%i4; bge .L2456; nop
+set 1,%l3
+st %l3,[%fp+-96]
+ba .L2457; nop
+.L2456:
+st %g0,[%fp+-96]
+.L2457:
+ld [%fp+-96],%l3
+cmp %l3,1; be .L2452; nop
+ld [%fp+-84],%l3
+add %l3,4,%l3
+st %l3,[%fp+-84]
+ld [%i0+44],%l3
+cmp %l3,0; be .L2460; nop
+set .2415,%o0
+set 4,%o1
+call printf; nop
+.L2460:
+.L2452:
+add -60,%fp,%l3
+add -64,%fp,%l2
+cmp %l3,%l2; bne .L2462; nop
+ld [%fp+-84],%l3
+add %l3,8,%l3
+st %l3,[%fp+-84]
+ld [%i0+44],%l3
+cmp %l3,0; be .L2465; nop
+set .2415,%o0
+set 8,%o1
+call printf; nop
+.L2465:
+.L2462:
+add -60,%fp,%l3
+add -64,%fp,%l2
+cmp %l3,%l2; bgeu .L2467; nop
+ld [%i0+40],%l3
+cmp %l3,0; be .L2470; nop
+set .L2472,%o0
+call printf; nop
+.L2470:
+.L2467:
+mov %g0,%i1
+mov %g0,%l7
+.L2473:
+sll %l7,2,%l3
+add -64,%fp,%l2
+set 1,%l1
+st %l1,[%l3+%l2]
+.L2474:
+add %l7,1,%l7
+cmp %l7,16; bl .L2473; nop
+st %g0,[%fp+-60]
+st %g0,[%fp+-48]
+st %g0,[%fp+-40]
+st %g0,[%fp+-36]
+st %g0,[%fp+-28]
+st %g0,[%fp+-12]
+mov %g0,%i2
+.L2483:
+mov %g0,%i3
+.L2487:
+mov %g0,%i4
+.L2491:
+mov %g0,%i5
+.L2495:
+cmp %i2,%i3; bge .L2506; nop
+set 1,%l3
+st %l3,[%fp+-108]
+ba .L2507; nop
+.L2506:
+st %g0,[%fp+-108]
+.L2507:
+cmp %i4,%i5; bge .L2508; nop
+set 1,%l3
+st %l3,[%fp+-112]
+ba .L2509; nop
+.L2508:
+st %g0,[%fp+-112]
+.L2509:
+ld [%fp+-108],%l3
+ld [%fp+-112],%l2
+cmp %l3,%l2; bne .L2504; nop
+set 1,%l3
+st %l3,[%fp+-104]
+ba .L2505; nop
+.L2504:
+st %g0,[%fp+-104]
+.L2505:
+ld [%fp+-104],%l3
+sll %i2,3,%l2
+sll %i3,2,%l1
+add %l2,%l1,%l2
+sll %i4,1,%l1
+add %l2,%l1,%l2
+add %l2,%i5,%l2
+sll %l2,2,%l2
+add -64,%fp,%l1
+ld [%l2+%l1],%l2
+cmp %l3,%l2; be .L2499; nop
+set 1,%i1
+.L2499:
+.L2496:
+add %i5,1,%i5
+cmp %i5,2; bl .L2495; nop
+.L2492:
+add %i4,1,%i4
+cmp %i4,2; bl .L2491; nop
+.L2488:
+add %i3,1,%i3
+cmp %i3,2; bl .L2487; nop
+.L2484:
+add %i2,1,%i2
+cmp %i2,2; bl .L2483; nop
+cmp %i1,0; be .L2510; nop
+ld [%fp+-84],%l3
+add %l3,16,%l3
+st %l3,[%fp+-84]
+ld [%i0+44],%l3
+cmp %l3,0; be .L2512; nop
+set .2415,%o0
+set 16,%o1
+call printf; nop
+.L2512:
+.L2510:
+st %g0,[%fp+-92]
+ld [%fp+-92],%l3
+cmp %l3,%g0; be .L2514; nop
+ld [%fp+-84],%l3
+add %l3,32,%l3
+st %l3,[%fp+-84]
+ld [%i0+44],%l3
+cmp %l3,0; be .L2516; nop
+set .2415,%o0
+set 32,%o1
+call printf; nop
+.L2516:
+.L2514:
+ld [%fp+-84],%i0
+.L2414:
+ret; restore
+.type s757,#function
+.size s757,.-s757
+.section ".data"
+.type .2519,#object
+.align 1
+.2519:
+.byte 76
+.byte 111
+.byte 99
+.byte 97
+.byte 108
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 37
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.size .2519,17
+.type .2520,#object
+.align 1
+.2520:
+.byte 115
+.byte 55
+.byte 56
+.byte 49
+.byte 51
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size .2520,12
+.type .2521,#object
+.size .2521,8
+.align 1
+.2521:
+.byte 115
+.byte 55
+.byte 56
+.byte 49
+.byte 51
+.byte 32
+.byte 32
+.byte 0
+.global s7813
+.section ".text"
+.align 4
+s7813:
+save %sp,-144,%sp
+set .2521,%l7
+add %i0,60,%l6
+mov %g0,%i4
+mov %g0,%l5
+ld [%i0+48],%i5
+.L2522:
+.L2523:
+mov %l6,%l3
+add %l3,1,%l6
+mov %l7,%l2
+add %l2,1,%l7
+ldsb [%l2],%l2
+stb %l2,[%l3]
+sll %l2,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,0; bne .L2522; nop
+ba .L2525; nop
+set 1,%i4
+cmp %i5,0; be .L2527; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2527:
+.L2525:
+ba .L2529; nop
+set 2,%i4
+cmp %i5,0; be .L2531; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2531:
+.L2529:
+ba .L2533; nop
+set 3,%i4
+cmp %i5,0; be .L2535; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2535:
+.L2533:
+ba .L2537; nop
+set 4,%i4
+cmp %i5,0; be .L2539; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2539:
+.L2537:
+ba .L2541; nop
+set 5,%i4
+cmp %i5,0; be .L2543; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2543:
+.L2541:
+ba .L2545; nop
+set 6,%i4
+cmp %i5,0; be .L2547; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2547:
+.L2545:
+ba .L2549; nop
+set 7,%i4
+cmp %i5,0; be .L2551; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2551:
+.L2549:
+ba .L2553; nop
+set 8,%i4
+cmp %i5,0; be .L2555; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2555:
+.L2553:
+ba .L2557; nop
+set 9,%i4
+cmp %i5,0; be .L2559; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2559:
+.L2557:
+ba .L2561; nop
+set 10,%i4
+cmp %i5,0; be .L2563; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2563:
+.L2561:
+ba .L2565; nop
+set 11,%i4
+cmp %i5,0; be .L2567; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2567:
+.L2565:
+ba .L2569; nop
+set 12,%i4
+cmp %i5,0; be .L2571; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2571:
+.L2569:
+ba .L2573; nop
+set 13,%i4
+cmp %i5,0; be .L2575; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2575:
+.L2573:
+ba .L2577; nop
+set 14,%i4
+cmp %i5,0; be .L2579; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2579:
+.L2577:
+ba .L2581; nop
+set 15,%i4
+cmp %i5,0; be .L2583; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2583:
+.L2581:
+ba .L2585; nop
+set 16,%i4
+cmp %i5,0; be .L2587; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2587:
+.L2585:
+ba .L2589; nop
+set 17,%i4
+cmp %i5,0; be .L2591; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2591:
+.L2589:
+ba .L2593; nop
+set 18,%i4
+cmp %i5,0; be .L2595; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2595:
+.L2593:
+ba .L2597; nop
+set 16,%i4
+cmp %i5,0; be .L2599; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2599:
+.L2597:
+ba .L2601; nop
+set 20,%i4
+cmp %i5,0; be .L2603; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2603:
+.L2601:
+ba .L2605; nop
+set 21,%i4
+cmp %i5,0; be .L2607; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2607:
+.L2605:
+ba .L2609; nop
+set 22,%i4
+cmp %i5,0; be .L2611; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2611:
+.L2609:
+ba .L2613; nop
+set 23,%i4
+cmp %i5,0; be .L2615; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2615:
+.L2613:
+ba .L2617; nop
+set 24,%i4
+cmp %i5,0; be .L2619; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2619:
+.L2617:
+ba .L2621; nop
+set 25,%i4
+cmp %i5,0; be .L2623; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2623:
+.L2621:
+ba .L2625; nop
+set 26,%i4
+cmp %i5,0; be .L2627; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2627:
+.L2625:
+ba .L2629; nop
+set 27,%i4
+cmp %i5,0; be .L2631; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2631:
+.L2629:
+ba .L2633; nop
+set 28,%i4
+cmp %i5,0; be .L2635; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2635:
+.L2633:
+ba .L2637; nop
+set 26,%i4
+cmp %i5,0; be .L2639; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2639:
+.L2637:
+ba .L2641; nop
+set 30,%i4
+cmp %i5,0; be .L2643; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2643:
+.L2641:
+ba .L2645; nop
+set 31,%i4
+cmp %i5,0; be .L2647; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2647:
+.L2645:
+ba .L2649; nop
+set 32,%i4
+cmp %i5,0; be .L2651; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2651:
+.L2649:
+ba .L2653; nop
+set 33,%i4
+cmp %i5,0; be .L2655; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2655:
+.L2653:
+ba .L2657; nop
+set 34,%i4
+cmp %i5,0; be .L2659; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2659:
+.L2657:
+ba .L2661; nop
+set 35,%i4
+cmp %i5,0; be .L2663; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2663:
+.L2661:
+ba .L2665; nop
+set 36,%i4
+cmp %i5,0; be .L2667; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2667:
+.L2665:
+ba .L2669; nop
+set 37,%i4
+cmp %i5,0; be .L2671; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2671:
+.L2669:
+ba .L2673; nop
+set 38,%i4
+cmp %i5,0; be .L2675; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2675:
+.L2673:
+ba .L2677; nop
+set 39,%i4
+cmp %i5,0; be .L2679; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2679:
+.L2677:
+ba .L2681; nop
+set 40,%i4
+cmp %i5,0; be .L2683; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2683:
+.L2681:
+ba .L2685; nop
+set 41,%i4
+cmp %i5,0; be .L2687; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2687:
+.L2685:
+ba .L2689; nop
+set 42,%i4
+cmp %i5,0; be .L2691; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2691:
+.L2689:
+ba .L2693; nop
+set 43,%i4
+cmp %i5,0; be .L2695; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2695:
+.L2693:
+ba .L2697; nop
+set 44,%i4
+cmp %i5,0; be .L2699; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2699:
+.L2697:
+ba .L2701; nop
+set 45,%i4
+cmp %i5,0; be .L2703; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2703:
+.L2701:
+ba .L2705; nop
+set 46,%i4
+cmp %i5,0; be .L2707; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2707:
+.L2705:
+ba .L2709; nop
+set 47,%i4
+cmp %i5,0; be .L2711; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2711:
+.L2709:
+ba .L2713; nop
+set 48,%i4
+cmp %i5,0; be .L2715; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2715:
+.L2713:
+ba .L2717; nop
+set 49,%i4
+cmp %i5,0; be .L2719; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2719:
+.L2717:
+ba .L2721; nop
+set 50,%i4
+cmp %i5,0; be .L2723; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2723:
+.L2721:
+ba .L2725; nop
+set 51,%i4
+cmp %i5,0; be .L2727; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2727:
+.L2725:
+ba .L2729; nop
+set 52,%i4
+cmp %i5,0; be .L2731; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2731:
+.L2729:
+ba .L2733; nop
+set 53,%i4
+cmp %i5,0; be .L2735; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2735:
+.L2733:
+ba .L2737; nop
+set 54,%i4
+cmp %i5,0; be .L2739; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2739:
+.L2737:
+ba .L2741; nop
+set 55,%i4
+cmp %i5,0; be .L2743; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2743:
+.L2741:
+ba .L2745; nop
+set 56,%i4
+cmp %i5,0; be .L2747; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2747:
+.L2745:
+ba .L2749; nop
+set 57,%i4
+cmp %i5,0; be .L2751; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2751:
+.L2749:
+ba .L2753; nop
+set 58,%i4
+cmp %i5,0; be .L2755; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2755:
+.L2753:
+ba .L2757; nop
+set 56,%i4
+cmp %i5,0; be .L2759; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2759:
+.L2757:
+ba .L2761; nop
+set 60,%i4
+cmp %i5,0; be .L2763; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2763:
+.L2761:
+ba .L2765; nop
+set 61,%i4
+cmp %i5,0; be .L2767; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2767:
+.L2765:
+ba .L2769; nop
+set 62,%i4
+cmp %i5,0; be .L2771; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2771:
+.L2769:
+ba .L2773; nop
+set 63,%i4
+cmp %i5,0; be .L2775; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2775:
+.L2773:
+ba .L2777; nop
+set 64,%i4
+cmp %i5,0; be .L2779; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2779:
+.L2777:
+ba .L2781; nop
+set 65,%i4
+cmp %i5,0; be .L2783; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2783:
+.L2781:
+ba .L2785; nop
+set 66,%i4
+cmp %i5,0; be .L2787; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2787:
+.L2785:
+ba .L2789; nop
+set 67,%i4
+cmp %i5,0; be .L2791; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2791:
+.L2789:
+ba .L2793; nop
+set 68,%i4
+cmp %i5,0; be .L2795; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2795:
+.L2793:
+ba .L2797; nop
+set 69,%i4
+cmp %i5,0; be .L2799; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2799:
+.L2797:
+ba .L2801; nop
+set 70,%i4
+cmp %i5,0; be .L2803; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2803:
+.L2801:
+ba .L2805; nop
+set 71,%i4
+cmp %i5,0; be .L2807; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2807:
+.L2805:
+ba .L2809; nop
+set 72,%i4
+cmp %i5,0; be .L2811; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2811:
+.L2809:
+ba .L2813; nop
+set 73,%i4
+cmp %i5,0; be .L2815; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2815:
+.L2813:
+ba .L2817; nop
+set 74,%i4
+cmp %i5,0; be .L2819; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2819:
+.L2817:
+ba .L2821; nop
+set 75,%i4
+cmp %i5,0; be .L2823; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2823:
+.L2821:
+cmp %i4,0; be .L2825; nop
+ld [%i0+44],%l3
+cmp %l3,0; be .L2827; nop
+set .2520,%o0
+set 1,%o1
+call printf; nop
+.L2827:
+add %l5,1,%l5
+.L2825:
+mov %g0,%i4
+mov %g0,%i2
+mov %g0,%i3
+mov %i3,%l3
+add %l3,1,%i3
+mov %g0,%l2
+cmp %l3,%l2; be .L2830; nop
+mov %i2,%l3
+add %l3,1,%i2
+cmp %l3,%l2; be .L2830; nop
+set 1,%l3
+st %l3,[%fp+-8]
+ba .L2831; nop
+.L2830:
+st %g0,[%fp+-8]
+.L2831:
+ld [%fp+-8],%i1
+cmp %i3,1; be .L2832; nop
+set 1,%i4
+cmp %i5,0; be .L2834; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2834:
+.L2832:
+cmp %i2,0; be .L2836; nop
+set 2,%i4
+cmp %i5,0; be .L2838; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2838:
+.L2836:
+cmp %i1,0; be .L2840; nop
+set 3,%i4
+cmp %i5,0; be .L2842; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2842:
+.L2840:
+cmp %i3,%g0; be .L2845; nop
+mov %i2,%l2
+add %l2,1,%i2
+cmp %l2,%g0; be .L2845; nop
+set 1,%l3
+st %l3,[%fp+-12]
+ba .L2846; nop
+.L2845:
+st %g0,[%fp+-12]
+.L2846:
+ld [%fp+-12],%i1
+cmp %i3,1; be .L2847; nop
+set 4,%i4
+cmp %i5,0; be .L2849; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2849:
+.L2847:
+cmp %i2,1; be .L2851; nop
+set 5,%i4
+cmp %i5,0; be .L2853; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2853:
+.L2851:
+cmp %i1,0; be .L2855; nop
+set 6,%i4
+cmp %i5,0; be .L2857; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2857:
+.L2855:
+mov %i3,%l3
+sub %l3,1,%i3
+mov %g0,%l2
+cmp %l3,%l2; be .L2860; nop
+cmp %i2,%l2; be .L2860; nop
+set 1,%l3
+st %l3,[%fp+-16]
+ba .L2861; nop
+.L2860:
+st %g0,[%fp+-16]
+.L2861:
+ld [%fp+-16],%i1
+cmp %i3,0; be .L2862; nop
+set 7,%i4
+cmp %i5,0; be .L2864; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2864:
+.L2862:
+cmp %i2,1; be .L2866; nop
+set 8,%i4
+cmp %i5,0; be .L2868; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2868:
+.L2866:
+cmp %i1,1; be .L2870; nop
+set 9,%i4
+cmp %i5,0; be .L2872; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2872:
+.L2870:
+cmp %i3,%g0; be .L2875; nop
+mov %i2,%l2
+sub %l2,1,%i2
+cmp %l2,%g0; be .L2875; nop
+set 1,%l3
+st %l3,[%fp+-20]
+ba .L2876; nop
+.L2875:
+st %g0,[%fp+-20]
+.L2876:
+ld [%fp+-20],%i1
+cmp %i3,0; be .L2877; nop
+set 10,%i4
+cmp %i5,0; be .L2879; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2879:
+.L2877:
+cmp %i2,1; be .L2881; nop
+set 11,%i4
+cmp %i5,0; be .L2883; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2883:
+.L2881:
+cmp %i1,0; be .L2885; nop
+set 12,%i4
+cmp %i5,0; be .L2887; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2887:
+.L2885:
+cmp %i4,0; be .L2889; nop
+ld [%i0+44],%l3
+cmp %l3,0; be .L2891; nop
+set .2520,%o0
+set 2,%o1
+call printf; nop
+.L2891:
+add %l5,2,%l5
+.L2889:
+mov %g0,%i4
+mov %g0,%i2
+mov %g0,%i3
+mov %i3,%l3
+add %l3,1,%i3
+mov %g0,%l2
+cmp %l3,%l2; bne .L2896; nop
+cmp %i2,%l2; be .L2894; nop
+.L2896:
+set 1,%l3
+st %l3,[%fp+-24]
+ba .L2895; nop
+.L2894:
+st %g0,[%fp+-24]
+.L2895:
+ld [%fp+-24],%i1
+cmp %i3,1; be .L2897; nop
+set 1,%i4
+cmp %i5,0; be .L2899; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2899:
+.L2897:
+cmp %i2,0; be .L2901; nop
+set 2,%i4
+cmp %i5,0; be .L2903; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2903:
+.L2901:
+cmp %i1,0; be .L2905; nop
+set 3,%i4
+cmp %i5,0; be .L2907; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2907:
+.L2905:
+mov %i2,%l3
+add %l3,1,%i2
+mov %g0,%l2
+cmp %l3,%l2; bne .L2912; nop
+cmp %i3,%l2; be .L2910; nop
+.L2912:
+set 1,%l3
+st %l3,[%fp+-28]
+ba .L2911; nop
+.L2910:
+st %g0,[%fp+-28]
+.L2911:
+ld [%fp+-28],%i1
+cmp %i3,1; be .L2913; nop
+set 4,%i4
+cmp %i5,0; be .L2915; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2915:
+.L2913:
+cmp %i2,1; be .L2917; nop
+set 5,%i4
+cmp %i5,0; be .L2919; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2919:
+.L2917:
+cmp %i1,1; be .L2921; nop
+set 6,%i4
+cmp %i5,0; be .L2923; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2923:
+.L2921:
+mov %i3,%l3
+sub %l3,1,%i3
+mov %g0,%l2
+cmp %l3,%l2; bne .L2928; nop
+mov %i2,%l3
+sub %l3,1,%i2
+cmp %l3,%l2; be .L2926; nop
+.L2928:
+set 1,%l3
+st %l3,[%fp+-32]
+ba .L2927; nop
+.L2926:
+st %g0,[%fp+-32]
+.L2927:
+ld [%fp+-32],%i1
+cmp %i3,0; be .L2929; nop
+set 7,%i4
+cmp %i5,0; be .L2931; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2931:
+.L2929:
+cmp %i2,1; be .L2933; nop
+set 8,%i4
+cmp %i5,0; be .L2935; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2935:
+.L2933:
+cmp %i1,1; be .L2937; nop
+set 9,%i4
+cmp %i5,0; be .L2939; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2939:
+.L2937:
+mov %g0,%l3
+cmp %i3,%l3; bne .L2944; nop
+mov %i2,%l2
+sub %l2,1,%i2
+cmp %l2,%l3; be .L2942; nop
+.L2944:
+set 1,%l3
+st %l3,[%fp+-36]
+ba .L2943; nop
+.L2942:
+st %g0,[%fp+-36]
+.L2943:
+ld [%fp+-36],%i1
+cmp %i3,0; be .L2945; nop
+set 10,%i4
+cmp %i5,0; be .L2947; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2947:
+.L2945:
+cmp %i2,0; be .L2949; nop
+set 11,%i4
+cmp %i5,0; be .L2951; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2951:
+.L2949:
+cmp %i1,1; be .L2953; nop
+set 12,%i4
+cmp %i5,0; be .L2955; nop
+set .2519,%o0
+mov %i4,%o1
+call printf; nop
+.L2955:
+.L2953:
+cmp %i4,0; be .L2957; nop
+ld [%i0+44],%l3
+cmp %l3,0; be .L2959; nop
+set .2520,%o0
+set 4,%o1
+call printf; nop
+.L2959:
+add %l5,4,%l5
+.L2957:
+mov %g0,%l3
+mov %l3,%i2
+mov %l3,%i3
+mov %l3,%l4
+set 1,%l2
+st %l2,[%fp+-4]
+ld [%fp+-4],%l2
+cmp %l2,%l3; be .L2963; nop
+st %l4,[%fp+-40]
+ba .L2964; nop
+.L2963:
+ld [%fp+-4],%l3
+cmp %l3,0; be .L2965; nop
+mov %i3,%l3
+add %l3,1,%i3
+st %l3,[%fp+-44]
+ba .L2966; nop
+.L2965:
+mov %i2,%l3
+add %l3,1,%i2
+st %l3,[%fp+-44]
+.L2966:
+ld [%fp+-44],%l3
+st %l3,[%fp+-40]
+.L2964:
+ld [%fp+-40],%i1
+cmp %i1,%g0; bne .L2970; nop
+cmp %i3,%g0; bne .L2970; nop
+cmp %i2,%g0; be .L2967; nop
+.L2970:
+ld [%i0+44],%l3
+cmp %l3,0; be .L2971; nop
+set .2520,%o0
+set 8,%o1
+call printf; nop
+.L2971:
+add %l5,8,%l5
+.L2967:
+ld [%fp+-4],%l3
+cmp %l3,0; be .L2978; nop
+st %l4,[%fp+-48]
+ba .L2979; nop
+.L2978:
+set 1,%l3
+st %l3,[%fp+-48]
+.L2979:
+ld [%fp+-48],%l2
+cmp %l2,%g0; bne .L2977; nop
+cmp %l4,%g0; be .L2980; nop
+set 1,%l3
+st %l3,[%fp+-52]
+ba .L2981; nop
+.L2980:
+st %l4,[%fp+-52]
+.L2981:
+ld [%fp+-52],%l3
+cmp %l3,0; be .L2973; nop
+.L2977:
+ld [%i0+44],%l3
+cmp %l3,0; be .L2982; nop
+set .2520,%o0
+set 16,%o1
+call printf; nop
+.L2982:
+add %l5,16,%l5
+.L2973:
+mov %l5,%i0
+.L2518:
+ret; restore
+.type s7813,#function
+.size s7813,.-s7813
+.section ".data"
+.type .2985,#object
+.align 1
+.2985:
+.byte 115
+.byte 56
+.byte 49
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size .2985,10
+.type .2986,#object
+.size .2986,8
+.align 1
+.2986:
+.byte 115
+.byte 56
+.byte 49
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.type .2987,#object
+.align 1
+.2987:
+.byte 82
+.byte 101
+.byte 103
+.byte 105
+.byte 115
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 99
+.byte 111
+.byte 117
+.byte 110
+.byte 116
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 37
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 117
+.byte 110
+.byte 114
+.byte 101
+.byte 108
+.byte 105
+.byte 97
+.byte 98
+.byte 108
+.byte 101
+.byte 46
+.byte 10
+.byte 0
+.size .2987,38
+.type .2988,#object
+.align 1
+.2988:
+.byte 37
+.byte 100
+.byte 32
+.byte 114
+.byte 101
+.byte 103
+.byte 105
+.byte 115
+.byte 116
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 97
+.byte 115
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 101
+.byte 100
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 37
+.byte 115
+.byte 32
+.byte 118
+.byte 97
+.byte 114
+.byte 105
+.byte 97
+.byte 98
+.byte 108
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.size .2988,40
+.global s81
+.section ".text"
+.align 4
+s81:
+save %sp,-112,%sp
+st %g0,[%fp+-20]
+st %g0,[%fp+-8]
+st %g0,[%fp+-12]
+st %g0,[%fp+-16]
+set .2986,%l5
+add %i0,60,%l4
+.L2989:
+.L2990:
+mov %l4,%l3
+add %l3,1,%l4
+mov %l5,%l2
+add %l2,1,%l5
+ldsb [%l2],%l2
+stb %l2,[%l3]
+sll %l2,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,0; bne .L2989; nop
+set 1,%l3
+st %l3,[%fp+-4]
+mov %g0,%i2
+.L2992:
+ld [%fp+-4],%l3
+mov %l3,%l2
+mov %l2,%i5
+mov %l2,%i1
+add -4,%fp,%i4
+add -4,%fp,%l7
+mov %l3,%i3
+mov %l3,%l6
+sll %i5,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+sll %i1,8*(4-1),%l2; sra %l2,8*(4-1),%l2
+cmp %l3,%l2; be .L2996; nop
+set 1,%l3
+st %l3,[%fp+-8]
+.L2996:
+mov %i4,%l3
+mov %l7,%l2
+cmp %l3,%l2; be .L2998; nop
+set 1,%l3
+st %l3,[%fp+-12]
+.L2998:
+cmp %i3,%l6; be .L3000; nop
+set 1,%l3
+st %l3,[%fp+-16]
+.L3000:
+ld [%fp+-4],%l3
+sll %l3,1,%l3
+st %l3,[%fp+-4]
+.L2993:
+add %i2,1,%i2
+cmp %i2,50; bl .L2992; nop
+ld [%fp+-8],%l3
+cmp %l3,0; be .L3002; nop
+ld [%fp+-20],%l3
+add %l3,1,%l3
+st %l3,[%fp+-20]
+ld [%i0+44],%l3
+cmp %l3,0; be .L3004; nop
+set .2985,%o0
+set 1,%o1
+call printf; nop
+.L3004:
+.L3002:
+ld [%fp+-12],%l3
+cmp %l3,0; be .L3006; nop
+ld [%fp+-20],%l3
+add %l3,2,%l3
+st %l3,[%fp+-20]
+ld [%i0+44],%l3
+cmp %l3,0; be .L3008; nop
+set .2985,%o0
+set 2,%o1
+call printf; nop
+.L3008:
+.L3006:
+ld [%fp+-16],%l3
+cmp %l3,0; be .L3010; nop
+ld [%fp+-20],%l3
+add %l3,4,%l3
+st %l3,[%fp+-20]
+ld [%i0+44],%l3
+cmp %l3,0; be .L3012; nop
+set .2985,%o0
+set 4,%o1
+call printf; nop
+.L3012:
+.L3010:
+call regc; nop
+st %o0,[%fp+-4]
+ld [%i0+40],%l3
+cmp %l3,0; be .L3014; nop
+ld [%fp+-4],%l3
+cmp %l3,0; bge .L3016; nop
+set .2987,%o0
+set .L425,%o1
+call printf; nop
+ba .L3017; nop
+.L3016:
+set .2988,%o0
+ld [%fp+-4],%o1
+set .L425,%o2
+call printf; nop
+.L3017:
+.L3014:
+call regp; nop
+st %o0,[%fp+-4]
+ld [%i0+40],%l3
+cmp %l3,0; be .L3018; nop
+ld [%fp+-4],%l3
+cmp %l3,0; bge .L3020; nop
+set .2987,%o0
+set .L3022,%o1
+call printf; nop
+ba .L3021; nop
+.L3020:
+set .2988,%o0
+ld [%fp+-4],%o1
+set .L3022,%o2
+call printf; nop
+.L3021:
+.L3018:
+call regi; nop
+st %o0,[%fp+-4]
+ld [%i0+40],%l3
+cmp %l3,0; be .L3023; nop
+ld [%fp+-4],%l3
+cmp %l3,0; bge .L3025; nop
+set .2987,%o0
+set .L426,%o1
+call printf; nop
+ba .L3026; nop
+.L3025:
+set .2988,%o0
+ld [%fp+-4],%o1
+set .L426,%o2
+call printf; nop
+.L3026:
+.L3023:
+ld [%fp+-20],%i0
+.L2984:
+ret; restore
+.type s81,#function
+.size s81,.-s81
+.global regc
+.align 4
+regc:
+save %sp,-232,%sp
+stb %g0,[%fp+-130]
+set 1,%l3
+stb %l3,[%fp+-109]
+set 2,%l3
+stb %l3,[%fp+-110]
+set 3,%l3
+stb %l3,[%fp+-111]
+set 4,%i5
+set 5,%l3
+stb %l3,[%fp+-112]
+set 6,%i4
+set 7,%l3
+stb %l3,[%fp+-113]
+set 8,%i3
+set 9,%l3
+stb %l3,[%fp+-114]
+set 10,%i2
+set 11,%l3
+stb %l3,[%fp+-115]
+set 12,%i1
+set 13,%l3
+stb %l3,[%fp+-116]
+set 14,%i0
+set 15,%l3
+stb %l3,[%fp+-117]
+set 16,%l7
+set 17,%l3
+stb %l3,[%fp+-118]
+set 18,%l6
+set 19,%l3
+stb %l3,[%fp+-119]
+set 20,%l5
+set 21,%l3
+stb %l3,[%fp+-120]
+set 22,%l4
+set 23,%l3
+stb %l3,[%fp+-121]
+set 24,%l3
+stb %l3,[%fp+-1]
+set 25,%l3
+stb %l3,[%fp+-122]
+set 26,%l3
+stb %l3,[%fp+-2]
+set 27,%l3
+stb %l3,[%fp+-123]
+set 28,%l3
+stb %l3,[%fp+-3]
+set 29,%l3
+stb %l3,[%fp+-124]
+set 30,%l3
+stb %l3,[%fp+-4]
+set 31,%l3
+stb %l3,[%fp+-125]
+set 32,%l3
+stb %l3,[%fp+-5]
+set 33,%l3
+stb %l3,[%fp+-126]
+set 34,%l3
+stb %l3,[%fp+-6]
+set 35,%l3
+stb %l3,[%fp+-127]
+set 36,%l3
+stb %l3,[%fp+-128]
+set 37,%l3
+stb %l3,[%fp+-129]
+set 38,%l3
+stb %l3,[%fp+-131]
+add -109,%fp,%l3
+add -130,%fp,%l2
+sub %l3,%l2,%l2
+st %l2,[%fp+-96]
+add -110,%fp,%l2
+sub %l2,%l3,%l3
+st %l3,[%fp+-92]
+add -111,%fp,%l3
+add -110,%fp,%l2
+sub %l3,%l2,%l3
+st %l3,[%fp+-88]
+add -112,%fp,%l3
+add -111,%fp,%l2
+sub %l3,%l2,%l3
+st %l3,[%fp+-84]
+add -113,%fp,%l3
+add -112,%fp,%l2
+sub %l3,%l2,%l3
+st %l3,[%fp+-80]
+add -114,%fp,%l3
+add -113,%fp,%l2
+sub %l3,%l2,%l3
+st %l3,[%fp+-76]
+add -115,%fp,%l3
+add -114,%fp,%l2
+sub %l3,%l2,%l3
+st %l3,[%fp+-72]
+add -116,%fp,%l3
+add -115,%fp,%l2
+sub %l3,%l2,%l3
+st %l3,[%fp+-68]
+add -117,%fp,%l3
+add -116,%fp,%l2
+sub %l3,%l2,%l3
+st %l3,[%fp+-64]
+add -118,%fp,%l3
+add -117,%fp,%l2
+sub %l3,%l2,%l3
+st %l3,[%fp+-60]
+add -119,%fp,%l3
+add -118,%fp,%l2
+sub %l3,%l2,%l3
+st %l3,[%fp+-56]
+add -120,%fp,%l3
+add -119,%fp,%l2
+sub %l3,%l2,%l3
+st %l3,[%fp+-52]
+add -121,%fp,%l3
+add -120,%fp,%l2
+sub %l3,%l2,%l3
+st %l3,[%fp+-48]
+add -122,%fp,%l3
+add -121,%fp,%l2
+sub %l3,%l2,%l3
+st %l3,[%fp+-44]
+add -123,%fp,%l3
+add -122,%fp,%l2
+sub %l3,%l2,%l3
+st %l3,[%fp+-40]
+add -124,%fp,%l3
+add -123,%fp,%l2
+sub %l3,%l2,%l3
+st %l3,[%fp+-36]
+add -125,%fp,%l3
+add -124,%fp,%l2
+sub %l3,%l2,%l3
+st %l3,[%fp+-32]
+add -126,%fp,%l3
+add -125,%fp,%l2
+sub %l3,%l2,%l3
+st %l3,[%fp+-28]
+add -127,%fp,%l3
+add -126,%fp,%l2
+sub %l3,%l2,%l3
+st %l3,[%fp+-24]
+add -128,%fp,%l3
+add -127,%fp,%l2
+sub %l3,%l2,%l3
+st %l3,[%fp+-20]
+add -129,%fp,%l3
+add -128,%fp,%l2
+sub %l3,%l2,%l3
+st %l3,[%fp+-16]
+add -131,%fp,%l3
+add -129,%fp,%l2
+sub %l3,%l2,%l3
+st %l3,[%fp+-12]
+ld [%fp+-96],%l3
+st %l3,[%fp+-108]
+set 1,%l3
+st %l3,[%fp+-104]
+st %g0,[%fp+-100]
+.L3049:
+ld [%fp+-104],%l3
+cmp %l3,1; be .L3055; nop
+cmp %l3,2; be .L3058; nop
+cmp %l3,3; be .L3063; nop
+ba .L3053; nop
+.L3055:
+ld [%fp+-100],%l3
+sll %l3,2,%l3
+add -96,%fp,%l2
+ld [%l3+%l2],%l3
+ld [%fp+-108],%l2
+cmp %l3,%l2; be .L3054; nop
+set 2,%l3
+ld [%fp+-100],%l2
+sll %l2,2,%l2
+add -96,%fp,%l1
+ld [%l2+%l1],%l2
+st %l2,[%fp+-140]
+st %l3,[%fp+-104]
+set 1,%l3
+st %l3,[%fp+-136]
+ba .L3054; nop
+.L3058:
+ld [%fp+-100],%l3
+sll %l3,2,%l3
+add -96,%fp,%l2
+ld [%l3+%l2],%l3
+ld [%fp+-108],%l2
+cmp %l3,%l2; bne .L3059; nop
+set 3,%l3
+st %l3,[%fp+-104]
+ba .L3054; nop
+.L3059:
+ld [%fp+-100],%l3
+sll %l3,2,%l3
+add -96,%fp,%l2
+ld [%l3+%l2],%l3
+ld [%fp+-140],%l2
+cmp %l3,%l2; bne .L3061; nop
+ld [%fp+-136],%l3
+add %l3,1,%l3
+st %l3,[%fp+-136]
+ba .L3054; nop
+.L3061:
+set 4,%l3
+st %l3,[%fp+-104]
+ba .L3054; nop
+.L3063:
+ld [%fp+-100],%l3
+sll %l3,2,%l3
+add -96,%fp,%l2
+ld [%l3+%l2],%l3
+ld [%fp+-108],%l2
+cmp %l3,%l2; be .L3054; nop
+set 4,%l3
+st %l3,[%fp+-104]
+.L3053:
+.L3054:
+.L3050:
+ld [%fp+-100],%l3
+add %l3,1,%l3
+st %l3,[%fp+-100]
+ld [%fp+-100],%l3
+cmp %l3,22; bl .L3049; nop
+ld [%fp+-104],%l3
+cmp %l3,3; bne .L3066; nop
+set 16,%l3
+ld [%fp+-136],%l2
+sub %l3,%l2,%i0
+ba .L3027; nop
+.L3066:
+set -1,%i0
+.L3027:
+ret; restore
+.type regc,#function
+.size regc,.-regc
+.global regi
+.align 4
+regi:
+save %sp,-320,%sp
+st %g0,[%fp+-212]
+set 1,%l3
+st %l3,[%fp+-128]
+set 2,%l3
+st %l3,[%fp+-132]
+set 3,%l3
+st %l3,[%fp+-136]
+set 4,%i5
+set 5,%l3
+st %l3,[%fp+-140]
+set 6,%i4
+set 7,%l3
+st %l3,[%fp+-144]
+set 8,%i3
+set 9,%l3
+st %l3,[%fp+-148]
+set 10,%i2
+set 11,%l3
+st %l3,[%fp+-152]
+set 12,%i1
+set 13,%l3
+st %l3,[%fp+-156]
+set 14,%i0
+set 15,%l3
+st %l3,[%fp+-160]
+set 16,%l7
+set 17,%l3
+st %l3,[%fp+-164]
+set 18,%l6
+set 19,%l3
+st %l3,[%fp+-168]
+set 20,%l5
+set 21,%l3
+st %l3,[%fp+-172]
+set 22,%l4
+set 23,%l3
+st %l3,[%fp+-176]
+set 24,%l3
+st %l3,[%fp+-4]
+set 25,%l3
+st %l3,[%fp+-180]
+set 26,%l3
+st %l3,[%fp+-8]
+set 27,%l3
+st %l3,[%fp+-184]
+set 28,%l3
+st %l3,[%fp+-12]
+set 29,%l3
+st %l3,[%fp+-188]
+set 30,%l3
+st %l3,[%fp+-16]
+set 31,%l3
+st %l3,[%fp+-192]
+set 32,%l3
+st %l3,[%fp+-20]
+set 33,%l3
+st %l3,[%fp+-196]
+set 34,%l3
+st %l3,[%fp+-24]
+set 35,%l3
+st %l3,[%fp+-200]
+set 36,%l3
+st %l3,[%fp+-204]
+set 37,%l3
+st %l3,[%fp+-208]
+set 38,%l3
+st %l3,[%fp+-216]
+add -128,%fp,%l3
+add -212,%fp,%l2
+sub %l3,%l2,%l2
+sra %l2,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l2,4,%l2
+st %l2,[%fp+-112]
+add -132,%fp,%l2
+sub %l2,%l3,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-108]
+add -136,%fp,%l3
+add -132,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-104]
+add -140,%fp,%l3
+add -136,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-100]
+add -144,%fp,%l3
+add -140,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-96]
+add -148,%fp,%l3
+add -144,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-92]
+add -152,%fp,%l3
+add -148,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-88]
+add -156,%fp,%l3
+add -152,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-84]
+add -160,%fp,%l3
+add -156,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-80]
+add -164,%fp,%l3
+add -160,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-76]
+add -168,%fp,%l3
+add -164,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-72]
+add -172,%fp,%l3
+add -168,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-68]
+add -176,%fp,%l3
+add -172,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-64]
+add -180,%fp,%l3
+add -176,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-60]
+add -184,%fp,%l3
+add -180,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-56]
+add -188,%fp,%l3
+add -184,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-52]
+add -192,%fp,%l3
+add -188,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-48]
+add -196,%fp,%l3
+add -192,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-44]
+add -200,%fp,%l3
+add -196,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-40]
+add -204,%fp,%l3
+add -200,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-36]
+add -208,%fp,%l3
+add -204,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-32]
+add -216,%fp,%l3
+add -208,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-28]
+ld [%fp+-112],%l3
+st %l3,[%fp+-124]
+set 1,%l3
+st %l3,[%fp+-120]
+st %g0,[%fp+-116]
+.L3090:
+ld [%fp+-120],%l3
+cmp %l3,1; be .L3096; nop
+cmp %l3,2; be .L3099; nop
+cmp %l3,3; be .L3104; nop
+ba .L3094; nop
+.L3096:
+ld [%fp+-116],%l3
+sll %l3,2,%l3
+add -112,%fp,%l2
+ld [%l3+%l2],%l3
+ld [%fp+-124],%l2
+cmp %l3,%l2; be .L3095; nop
+set 2,%l3
+ld [%fp+-116],%l2
+sll %l2,2,%l2
+add -112,%fp,%l1
+ld [%l2+%l1],%l2
+st %l2,[%fp+-224]
+st %l3,[%fp+-120]
+set 1,%l3
+st %l3,[%fp+-220]
+ba .L3095; nop
+.L3099:
+ld [%fp+-116],%l3
+sll %l3,2,%l3
+add -112,%fp,%l2
+ld [%l3+%l2],%l3
+ld [%fp+-124],%l2
+cmp %l3,%l2; bne .L3100; nop
+set 3,%l3
+st %l3,[%fp+-120]
+ba .L3095; nop
+.L3100:
+ld [%fp+-116],%l3
+sll %l3,2,%l3
+add -112,%fp,%l2
+ld [%l3+%l2],%l3
+ld [%fp+-224],%l2
+cmp %l3,%l2; bne .L3102; nop
+ld [%fp+-220],%l3
+add %l3,1,%l3
+st %l3,[%fp+-220]
+ba .L3095; nop
+.L3102:
+set 4,%l3
+st %l3,[%fp+-120]
+ba .L3095; nop
+.L3104:
+ld [%fp+-116],%l3
+sll %l3,2,%l3
+add -112,%fp,%l2
+ld [%l3+%l2],%l3
+ld [%fp+-124],%l2
+cmp %l3,%l2; be .L3095; nop
+set 4,%l3
+st %l3,[%fp+-120]
+.L3094:
+.L3095:
+.L3091:
+ld [%fp+-116],%l3
+add %l3,1,%l3
+st %l3,[%fp+-116]
+ld [%fp+-116],%l3
+cmp %l3,22; bl .L3090; nop
+ld [%fp+-120],%l3
+cmp %l3,3; bne .L3107; nop
+set 16,%l3
+ld [%fp+-220],%l2
+sub %l3,%l2,%i0
+ba .L3068; nop
+.L3107:
+set -1,%i0
+.L3068:
+ret; restore
+.type regi,#function
+.size regi,.-regi
+.global regp
+.align 4
+regp:
+save %sp,-320,%sp
+add -212,%fp,%l3
+st %l3,[%fp+-212]
+add -188,%fp,%l3
+st %l3,[%fp+-188]
+add -192,%fp,%l3
+st %l3,[%fp+-192]
+add -196,%fp,%l3
+st %l3,[%fp+-196]
+add -124,%fp,%i5
+add -124,%fp,%l3
+st %l3,[%fp+-124]
+add -128,%fp,%i4
+add -128,%fp,%l3
+st %l3,[%fp+-128]
+add -132,%fp,%i3
+add -132,%fp,%l3
+st %l3,[%fp+-132]
+add -136,%fp,%i2
+add -136,%fp,%l3
+st %l3,[%fp+-136]
+add -140,%fp,%i1
+add -140,%fp,%l3
+st %l3,[%fp+-140]
+add -144,%fp,%i0
+add -144,%fp,%l3
+st %l3,[%fp+-144]
+add -148,%fp,%l7
+add -148,%fp,%l3
+st %l3,[%fp+-148]
+add -152,%fp,%l6
+add -152,%fp,%l3
+st %l3,[%fp+-152]
+add -156,%fp,%l5
+add -156,%fp,%l3
+st %l3,[%fp+-156]
+add -160,%fp,%l4
+add -160,%fp,%l3
+st %l3,[%fp+-160]
+add -164,%fp,%l3
+st %l3,[%fp+-4]
+add -164,%fp,%l3
+st %l3,[%fp+-164]
+add -168,%fp,%l3
+st %l3,[%fp+-8]
+add -168,%fp,%l3
+st %l3,[%fp+-168]
+add -172,%fp,%l3
+st %l3,[%fp+-12]
+add -172,%fp,%l3
+st %l3,[%fp+-172]
+add -176,%fp,%l3
+st %l3,[%fp+-16]
+add -176,%fp,%l3
+st %l3,[%fp+-176]
+add -180,%fp,%l3
+st %l3,[%fp+-20]
+add -180,%fp,%l3
+st %l3,[%fp+-180]
+add -184,%fp,%l3
+st %l3,[%fp+-24]
+add -184,%fp,%l3
+st %l3,[%fp+-184]
+add -200,%fp,%l3
+st %l3,[%fp+-200]
+add -204,%fp,%l3
+st %l3,[%fp+-204]
+add -216,%fp,%l3
+st %l3,[%fp+-216]
+add -188,%fp,%l3
+add -212,%fp,%l2
+sub %l3,%l2,%l2
+sra %l2,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l2,4,%l2
+st %l2,[%fp+-112]
+add -192,%fp,%l2
+sub %l2,%l3,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-108]
+add -196,%fp,%l3
+add -192,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-104]
+add -124,%fp,%l3
+add -196,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-100]
+add -128,%fp,%l3
+add -124,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-96]
+add -132,%fp,%l3
+add -128,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-92]
+add -136,%fp,%l3
+add -132,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-88]
+add -140,%fp,%l3
+add -136,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-84]
+add -144,%fp,%l3
+add -140,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-80]
+add -148,%fp,%l3
+add -144,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-76]
+add -152,%fp,%l3
+add -148,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-72]
+add -156,%fp,%l3
+add -152,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-68]
+add -160,%fp,%l3
+add -156,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-64]
+add -164,%fp,%l3
+add -160,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-60]
+add -168,%fp,%l3
+add -164,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-56]
+add -172,%fp,%l3
+add -168,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-52]
+add -176,%fp,%l3
+add -172,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-48]
+add -180,%fp,%l3
+add -176,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-44]
+add -184,%fp,%l3
+add -180,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-40]
+add -200,%fp,%l3
+add -184,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-36]
+add -204,%fp,%l3
+add -200,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-32]
+add -216,%fp,%l3
+add -204,%fp,%l2
+sub %l3,%l2,%l3
+sra %l3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l3,4,%l3
+st %l3,[%fp+-28]
+ld [%fp+-112],%l3
+st %l3,[%fp+-208]
+set 1,%l3
+st %l3,[%fp+-120]
+st %g0,[%fp+-116]
+.L3131:
+ld [%fp+-120],%l3
+cmp %l3,1; be .L3137; nop
+cmp %l3,2; be .L3140; nop
+cmp %l3,3; be .L3145; nop
+ba .L3135; nop
+.L3137:
+ld [%fp+-116],%l3
+sll %l3,2,%l3
+add -112,%fp,%l2
+ld [%l3+%l2],%l3
+ld [%fp+-208],%l2
+cmp %l3,%l2; be .L3136; nop
+set 2,%l3
+ld [%fp+-116],%l2
+sll %l2,2,%l2
+add -112,%fp,%l1
+ld [%l2+%l1],%l2
+st %l2,[%fp+-224]
+st %l3,[%fp+-120]
+set 1,%l3
+st %l3,[%fp+-220]
+ba .L3136; nop
+.L3140:
+ld [%fp+-116],%l3
+sll %l3,2,%l3
+add -112,%fp,%l2
+ld [%l3+%l2],%l3
+ld [%fp+-208],%l2
+cmp %l3,%l2; bne .L3141; nop
+set 3,%l3
+st %l3,[%fp+-120]
+ba .L3136; nop
+.L3141:
+ld [%fp+-116],%l3
+sll %l3,2,%l3
+add -112,%fp,%l2
+ld [%l3+%l2],%l3
+ld [%fp+-224],%l2
+cmp %l3,%l2; bne .L3143; nop
+ld [%fp+-220],%l3
+add %l3,1,%l3
+st %l3,[%fp+-220]
+ba .L3136; nop
+.L3143:
+set 4,%l3
+st %l3,[%fp+-120]
+ba .L3136; nop
+.L3145:
+ld [%fp+-116],%l3
+sll %l3,2,%l3
+add -112,%fp,%l2
+ld [%l3+%l2],%l3
+ld [%fp+-208],%l2
+cmp %l3,%l2; be .L3136; nop
+set 4,%l3
+st %l3,[%fp+-120]
+.L3135:
+.L3136:
+.L3132:
+ld [%fp+-116],%l3
+add %l3,1,%l3
+st %l3,[%fp+-116]
+ld [%fp+-116],%l3
+cmp %l3,22; bl .L3131; nop
+ld [%fp+-120],%l3
+cmp %l3,3; bne .L3148; nop
+set 16,%l3
+ld [%fp+-220],%l2
+sub %l3,%l2,%i0
+ba .L3109; nop
+.L3148:
+set -1,%i0
+.L3109:
+ret; restore
+.type regp,#function
+.size regp,.-regp
+.section ".bss"
+.type .3151,#object
+.size .3151,420
+.local .3151
+.common .3151,420,4
+.section ".data"
+.type .3152,#object
+.align 1
+.3152:
+.byte 115
+.byte 56
+.byte 52
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size .3152,10
+.type .3153,#object
+.size .3153,8
+.align 1
+.3153:
+.byte 115
+.byte 56
+.byte 52
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.global s84
+.section ".text"
+.align 4
+s84:
+save %sp,-232,%sp
+set .3153,%i2
+add %i0,60,%i1
+mov %g0,%l7
+.L3154:
+.L3155:
+mov %i1,%l4
+add %l4,1,%i1
+mov %i2,%l3
+add %l3,1,%i2
+ldsb [%l3],%l3
+stb %l3,[%l4]
+sll %l3,8*(4-1),%l4; sra %l4,8*(4-1),%l4
+cmp %l4,0; bne .L3154; nop
+set 3,%o0
+call fip; nop
+mov %o0,%l6
+ld [%l6],%l4
+cmp %l4,3; be .L3157; nop
+ld [%i0+44],%l4
+cmp %l4,0; be .L3159; nop
+set .3152,%o0
+set 1,%o1
+call printf; nop
+.L3159:
+add %l7,1,%l7
+.L3157:
+set glork,%l5
+set 4,%o0
+call %l5; nop
+cmp %o0,4; be .L3161; nop
+ld [%i0+44],%l4
+cmp %l4,0; be .L3163; nop
+set .3152,%o0
+set 2,%o1
+call printf; nop
+.L3163:
+add %l7,2,%l7
+.L3161:
+mov %g0,%i4
+.L3165:
+sll %i4,2,%l4
+add -68,%fp,%l3
+st %i4,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+st %f31,[%l4+%l3]
+sll %i4,2,%l4
+add -136,%fp,%l3
+add -68,%fp,%l2
+add %l4,%l2,%l2
+st %l2,[%l4+%l3]
+.L3166:
+add %i4,1,%i4
+cmp %i4,17; bl .L3165; nop
+set .L412,%l4
+ld [%l4],%f31
+st %f31,[%fp+-140]
+mov %g0,%i4
+.L3169:
+ld [%fp+-140],%f31
+sll %i4,2,%l4
+add -136,%fp,%l3
+ld [%l4+%l3],%l4
+ld [%l4],%f30
+fadds %f31,%f30,%f31
+st %f31,[%fp+-140]
+.L3170:
+add %i4,1,%i4
+cmp %i4,17; bl .L3169; nop
+ld [%fp+-140],%f31
+set .L3175,%l4
+ld [%l4],%f30
+fcmpes %f31,%f30; nop; fbue .L3173; nop
+ld [%i0+44],%l4
+cmp %l4,0; be .L3176; nop
+set .3152,%o0
+set 4,%o1
+call printf; nop
+.L3176:
+add %l7,4,%l7
+.L3173:
+mov %g0,%i3
+.L3178:
+mov %g0,%i4
+.L3182:
+mov %g0,%i5
+.L3186:
+sll %i5,2,%l4
+smul %i4,28,%l3
+smul %i3,140,%l2
+set .3151,%l1
+add %l2,%l1,%l2
+add %l3,%l2,%l3
+smul %i3,35,%l2
+smul %i4,7,%l1
+add %l2,%l1,%l2
+add %l2,%i5,%l2
+st %l2,[%l4+%l3]
+.L3187:
+add %i5,1,%i5
+cmp %i5,7; bl .L3186; nop
+.L3183:
+add %i4,1,%i4
+cmp %i4,5; bl .L3182; nop
+.L3179:
+add %i3,1,%i3
+cmp %i3,3; bl .L3178; nop
+set 1,%i3
+set 2,%i4
+set 3,%i5
+set .3151,%o0
+set 105,%o1
+mov %g0,%o2
+call array; nop
+mov %o0,%l4
+smul %i3,140,%l3
+set .3151,%l2
+add %l3,%l2,%o0
+set 35,%l3
+mov %l3,%o1
+mov %l3,%o2
+call array; nop
+mov %o0,%l3
+smul %i4,28,%l2
+smul %i3,140,%l1
+set .3151,%l0
+add %l1,%l0,%l1
+add %l2,%l1,%o0
+set 7,%o1
+set 49,%o2
+call array; nop
+add %l4,%l3,%l4
+add %l4,%o0,%l4
+sll %i5,2,%l3
+smul %i4,28,%l2
+smul %i3,140,%l1
+set .3151,%l0
+add %l1,%l0,%l1
+add %l2,%l1,%l2
+ld [%l3+%l2],%l3
+add %l4,%l3,%l4
+sub %l4,52,%l4
+cmp %l4,0; be .L3190; nop
+ld [%i0+44],%l4
+cmp %l4,0; be .L3192; nop
+set .3152,%o0
+set 8,%o1
+call printf; nop
+.L3192:
+add %l7,8,%l7
+.L3190:
+mov %l7,%i0
+.L3150:
+ret; restore
+.type s84,#function
+.size s84,.-s84
+.global array
+.align 4
+array:
+mov %g0,%o5
+ba .L3198; nop
+.L3195:
+sll %o5,2,%o4
+ld [%o4+%o0],%o4
+add %o5,%o2,%o3
+cmp %o4,%o3; be .L3199; nop
+set 1,%o0
+ba .L3194; nop
+.L3199:
+.L3196:
+add %o5,1,%o5
+.L3198:
+cmp %o5,%o1; bl .L3195; nop
+mov %g0,%o0
+.L3194:
+retl; nop
+.type array,#function
+.size array,.-array
+.section ".bss"
+.type .3202,#object
+.size .3202,4
+.local .3202
+.common .3202,4,4
+.global fip
+.section ".text"
+.align 4
+fip:
+set .3202,%o5
+st %o0,[%o5]
+mov %o5,%o0
+.L3201:
+retl; nop
+.type fip,#function
+.size fip,.-fip
+.global glork
+.align 4
+glork:
+.L3203:
+retl; nop
+.type glork,#function
+.size glork,.-glork
+.section ".data"
+.type .3205,#object
+.align 1
+.3205:
+.byte 115
+.byte 56
+.byte 53
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size .3205,10
+.type .3206,#object
+.size .3206,8
+.align 1
+.3206:
+.byte 115
+.byte 56
+.byte 53
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.type .3214,#object
+.align 4
+.3214:
+.word .L425
+.word .L427
+.word .L426
+.word .L428
+.word .L429
+.word .L430
+.word .L431
+.size .3214,28
+.type .3215,#object
+.align 1
+.3215:
+.byte 32
+.byte 97
+.byte 108
+.byte 105
+.byte 103
+.byte 110
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 58
+.byte 32
+.byte 0
+.size .3215,13
+.global s85
+.section ".text"
+.align 4
+s85:
+save %sp,-488,%sp
+set .3206,%i4
+add %i0,60,%i3
+mov %g0,%i2
+.L3219:
+.L3220:
+mov %i3,%i1
+add %i1,1,%i3
+mov %i4,%l7
+add %l7,1,%i4
+ldsb [%l7],%l7
+stb %l7,[%i1]
+sll %l7,8*(4-1),%i1; sra %i1,8*(4-1),%i1
+cmp %i1,0; bne .L3219; nop
+add -284,%fp,%l7
+add -304,%fp,%l6
+sub %l7,%l6,%l7
+cmp %l7,%g0; ble .L3230; nop
+add -280,%fp,%l7
+add -284,%fp,%l6
+sub %l7,%l6,%l7
+cmp %l7,%g0; ble .L3230; nop
+add -276,%fp,%l7
+add -280,%fp,%l6
+sub %l7,%l6,%l7
+cmp %l7,%g0; bg .L3222; nop
+.L3230:
+ld [%i0+44],%i1
+cmp %i1,0; be .L3231; nop
+set .3205,%o0
+set 1,%o1
+call printf; nop
+.L3231:
+add %i2,1,%i2
+.L3222:
+add -337,%fp,%i1
+add -338,%fp,%l7
+sub %i1,%l7,%i1
+st %i1,[%fp+-268]
+add -340,%fp,%i1
+add -342,%fp,%l7
+sub %i1,%l7,%i1
+st %i1,[%fp+-264]
+add -348,%fp,%i1
+add -352,%fp,%l7
+sub %i1,%l7,%i1
+st %i1,[%fp+-260]
+add -356,%fp,%i1
+add -360,%fp,%l7
+sub %i1,%l7,%i1
+st %i1,[%fp+-256]
+add -364,%fp,%i1
+add -368,%fp,%l7
+sub %i1,%l7,%i1
+st %i1,[%fp+-252]
+add -372,%fp,%i1
+add -376,%fp,%l7
+sub %i1,%l7,%i1
+st %i1,[%fp+-248]
+add -384,%fp,%i1
+add -392,%fp,%l7
+sub %i1,%l7,%i1
+st %i1,[%fp+-244]
+ld [%i0+40],%i1
+cmp %i1,0; be .L3246; nop
+mov %g0,%i5
+.L3248:
+set .L3252,%o0
+sll %i5,2,%i1
+set .3214,%l7
+ld [%i1+%l7],%o1
+set .3215,%o2
+add -268,%fp,%l7
+ld [%i1+%l7],%o3
+call printf; nop
+.L3249:
+add %i5,1,%i5
+cmp %i5,7; bl .L3248; nop
+.L3246:
+ld [%fp+-272],%i1
+set 0x1c000000,%l7
+or %i1,%l7,%i1
+st %i1,[%fp+-272]
+ld [%fp+-272],%i1
+mov %i1,%l7
+set 0x3fffffff,%l6
+and %l7,%l6,%l7
+sll %i1,3,%i1
+sra %i1,29,%i1
+sll %i1,30,%i1
+sra %i1,30,%i1
+sll %i1,30,%i1
+set 0xc0000000,%l6
+and %i1,%l6,%i1
+or %l7,%i1,%i1
+st %i1,[%fp+-272]
+ld [%fp+-272],%i1
+mov %i1,%l7
+set 0xe3ffffff,%l6
+and %l7,%l6,%l7
+sra %i1,30,%i1
+sll %i1,29,%i1
+sra %i1,29,%i1
+sll %i1,26,%i1
+set 0x1c000000,%l6
+and %i1,%l6,%i1
+or %l7,%i1,%i1
+st %i1,[%fp+-272]
+ld [%fp+-272],%i1
+sll %i1,3,%i1
+sra %i1,29,%i1
+cmp %i1,3; be .L3253; nop
+ld [%fp+-272],%i1
+sll %i1,3,%i1
+sra %i1,29,%i1
+cmp %i1,-1; bne .L3255; nop
+ld [%i0+40],%i1
+cmp %i1,0; be .L3256; nop
+set .L3259,%o0
+call printf; nop
+ba .L3256; nop
+.L3255:
+ld [%i0+44],%i1
+cmp %i1,0; be .L3260; nop
+set .3205,%o0
+set 2,%o1
+call printf; nop
+.L3260:
+add %i2,2,%i2
+.L3256:
+.L3253:
+ld [%fp+-272],%i1
+set 0x2000000,%l7
+or %i1,%l7,%i1
+st %i1,[%fp+-272]
+ld [%fp+-272],%i1
+sll %i1,6,%i1
+sra %i1,31,%i1
+cmp %i1,1; be .L3262; nop
+ld [%i0+40],%i1
+cmp %i1,0; be .L3264; nop
+set .L3266,%o0
+call printf; nop
+.L3264:
+.L3262:
+add -240,%fp,%i1
+sub %i1,%i1,%i1
+cmp %i1,%g0; bne .L3274; nop
+cmp %i1,%g0; bne .L3274; nop
+cmp %i1,%g0; bne .L3274; nop
+cmp %i1,%g0; bne .L3274; nop
+cmp %i1,%g0; bne .L3274; nop
+cmp %i1,%g0; bne .L3274; nop
+cmp %i1,%g0; be .L3267; nop
+.L3274:
+ld [%i0+44],%i1
+cmp %i1,0; be .L3275; nop
+set .3205,%o0
+set 4,%o1
+call printf; nop
+.L3275:
+add %i2,4,%i2
+.L3267:
+ba .L3277; nop
+ld [%i0+44],%i1
+cmp %i1,0; be .L3279; nop
+set .3205,%o0
+set 8,%o1
+call printf; nop
+.L3279:
+add %i2,8,%i2
+.L3277:
+add -336,%fp,%i1
+st %i1,[%fp+-276]
+set 2,%i1
+stb %i1,[%fp+-336]
+ld [%fp+-276],%i1
+ldsb [%i1],%l7
+add %l7,1,%l7
+stb %l7,[%i1]
+ldsb [%fp+-336],%i1
+cmp %i1,3; be .L3283; nop
+ld [%i0+44],%i1
+cmp %i1,0; be .L3285; nop
+set .3205,%o0
+set 16,%o1
+call printf; nop
+.L3285:
+add %i2,16,%i2
+.L3283:
+mov %i2,%i0
+.L3204:
+ret; restore
+.type s85,#function
+.size s85,.-s85
+.section ".data"
+.type .3288,#object
+.align 1
+.3288:
+.byte 115
+.byte 56
+.byte 54
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size .3288,10
+.type .3289,#object
+.size .3289,8
+.align 1
+.3289:
+.byte 115
+.byte 56
+.byte 54
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.type .3290,#object
+.align 4
+.3290:
+.word 0x1
+.word 0x3
+.word 0x5
+.size .3290,12
+.type .3291,#object
+.size .3291,4
+.align 4
+.3291:
+.word .3290+8
+.section ".bss"
+.type .3293,#object
+.size .3293,40
+.local .3293
+.common .3293,40,4
+.section ".data"
+.type .3294,#object
+.align 4
+.3294:
+.word 0x3f800000
+.word 0x40400000
+.word 0x40a00000
+.word 0x40000000
+.word 0x40800000
+.word 0x40c00000
+.word 0x40400000
+.word 0x40a00000
+.word 0x40e00000
+.word 0x0
+.word 0x0
+.word 0x0
+.size .3294,48
+.type .3295,#object
+.size .3295,48
+.align 4
+.3295:
+.word 0x3f800000
+.word 0x40400000
+.word 0x40a00000
+.word 0x40000000
+.word 0x40800000
+.word 0x40c00000
+.word 0x40400000
+.word 0x40a00000
+.word 0x40e00000
+.skip 12
+.type .3296,#object
+.size .3296,48
+.align 4
+.3296:
+.word 0x3f800000
+.word 0x40400000
+.word 0x40a00000
+.word 0x40000000
+.word 0x40800000
+.word 0x40c00000
+.word 0x40400000
+.word 0x40a00000
+.word 0x40e00000
+.skip 12
+.type .3297,#object
+.size .3297,48
+.align 4
+.3297:
+.word 0x3f800000
+.skip 8
+.word 0x40000000
+.skip 8
+.word 0x40400000
+.skip 8
+.word 0x40800000
+.skip 8
+.global s86
+.section ".text"
+.align 4
+s86:
+save %sp,-96,%sp
+set .3291,%l3
+ld [%l3],%l3
+add %l3,-4,%l4
+call one; nop
+sll %o0,2,%l3
+add %l3,%l4,%i5
+set .3289,%l7
+add %i0,60,%l6
+mov %g0,%l5
+.L3298:
+.L3299:
+mov %l6,%l3
+add %l3,1,%l6
+mov %l7,%l2
+add %l2,1,%l7
+ldsb [%l2],%l2
+stb %l2,[%l3]
+sll %l2,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+cmp %l3,0; bne .L3298; nop
+set .3291,%l3
+ld [%l3],%l3
+ld [%l3],%l3
+cmp %l3,5; be .L3301; nop
+ld [%i0+44],%l3
+cmp %l3,0; be .L3303; nop
+set .3288,%o0
+set 1,%o1
+call printf; nop
+.L3303:
+add %l5,1,%l5
+.L3301:
+ld [%l4],%l3
+cmp %l3,3; be .L3305; nop
+ld [%i0+44],%l3
+cmp %l3,0; be .L3307; nop
+set .3288,%o0
+set 2,%o1
+call printf; nop
+.L3307:
+add %l5,2,%l5
+.L3305:
+ld [%i5],%l3
+cmp %l3,5; be .L3309; nop
+ld [%i0+44],%l3
+cmp %l3,0; be .L3311; nop
+set .3288,%o0
+set 4,%o1
+call printf; nop
+.L3311:
+add %l5,4,%l5
+.L3309:
+mov %g0,%i1
+mov %g0,%i4
+.L3313:
+sll %i4,2,%l3
+set .3293,%l2
+ld [%l3+%l2],%l3
+cmp %l3,0; be .L3317; nop
+set 1,%i1
+.L3317:
+.L3314:
+add %i4,1,%i4
+cmp %i4,10; bl .L3313; nop
+cmp %i1,0; be .L3319; nop
+ld [%i0+44],%l3
+cmp %l3,0; be .L3321; nop
+set .3288,%o0
+set 8,%o1
+call printf; nop
+.L3321:
+add %l5,8,%l5
+.L3319:
+mov %g0,%i1
+mov %g0,%i3
+.L3323:
+mov %g0,%i4
+.L3327:
+smul %i3,3,%l3
+add %l3,%i4,%i2
+sll %i4,2,%l3
+smul %i3,12,%l2
+set .3295,%l1
+add %l2,%l1,%l1
+ld [%l3+%l1],%f31
+set .3296,%l1
+add %l2,%l1,%l2
+ld [%l3+%l2],%f30
+fcmpes %f31,%f30; nop; fbne .L3333; nop
+sll %i2,2,%l3
+set .3294,%l2
+ld [%l3+%l2],%f30
+fcmpes %f31,%f30; nop; fbue .L3331; nop
+.L3333:
+set 1,%i1
+.L3331:
+.L3328:
+add %i4,1,%i4
+cmp %i4,3; bl .L3327; nop
+.L3324:
+add %i3,1,%i3
+cmp %i3,4; bl .L3323; nop
+cmp %i1,0; be .L3334; nop
+ld [%i0+44],%l3
+cmp %l3,0; be .L3336; nop
+set .3288,%o0
+set 16,%o1
+call printf; nop
+.L3336:
+add %l5,16,%l5
+.L3334:
+mov %g0,%i1
+mov %g0,%i4
+.L3338:
+smul %i4,12,%l3
+set .3297,%l2
+ld [%l3+%l2],%f31
+add %i4,1,%l3
+st %l3,[%sp+64]; ld [%sp+64],%f30; fitos %f30,%f30
+fcmpes %f31,%f30; nop; fbue .L3342; nop
+set 1,%i1
+.L3342:
+.L3339:
+add %i4,1,%i4
+cmp %i4,4; bl .L3338; nop
+cmp %i1,0; be .L3344; nop
+ld [%i0+44],%l3
+cmp %l3,0; be .L3346; nop
+set .3288,%o0
+set 32,%o1
+call printf; nop
+.L3346:
+add %l5,32,%l5
+.L3344:
+mov %l5,%i0
+.L3287:
+ret; restore
+.type s86,#function
+.size s86,.-s86
+.global one
+.align 4
+one:
+set 1,%o0
+.L3348:
+retl; nop
+.type one,#function
+.size one,.-one
+.section ".data"
+.type .3350,#object
+.align 1
+.3350:
+.byte 115
+.byte 56
+.byte 56
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size .3350,10
+.type .3351,#object
+.size .3351,8
+.align 1
+.3351:
+.byte 115
+.byte 56
+.byte 56
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.global s88
+.section ".text"
+.align 4
+s88:
+save %sp,-112,%sp
+set .3351,%i5
+add %i0,60,%i4
+mov %g0,%i3
+.L3353:
+.L3354:
+mov %i4,%i1
+add %i1,1,%i4
+mov %i5,%l7
+add %l7,1,%i5
+ldsb [%l7],%l7
+stb %l7,[%i1]
+sll %l7,8*(4-1),%i1; sra %i1,8*(4-1),%i1
+cmp %i1,0; bne .L3353; nop
+ba .L3356; nop
+ld [%i0+44],%i1
+cmp %i1,0; be .L3358; nop
+set .3350,%o0
+set 1,%o1
+call printf; nop
+.L3358:
+add %i3,1,%i3
+.L3356:
+set metricp,%i1
+add -20,%fp,%l7
+st %l7,[%i1]
+set 2,%l7
+st %l7,[%fp+-20]
+ld [%i1],%i1
+set 3,%l7
+st %l7,[%i1]
+ld [%fp+-20],%i1
+cmp %i1,3; be .L3360; nop
+ld [%i0+44],%i1
+cmp %i1,0; be .L3362; nop
+set .3350,%o0
+set 2,%o1
+call printf; nop
+.L3362:
+add %i3,2,%i3
+.L3360:
+set .L419,%i1
+ld2 [%i1],%f30
+std %f30,[%fp+-16]
+std %f30,[%fp+-8]
+add -16,%fp,%i2
+set .L418,%i1
+ld2 [%i1],%f30
+st2 %f30,[%i2]
+set .L418,%i1
+ld2 [%i1],%f30
+st2 %f30,[%i2+8]
+ldd [%fp+-16],%f30
+ldd [%fp+-8],%f28
+faddd %f30,%f28,%f30
+set .L416,%i1
+ld2 [%i1],%f28
+fcmped %f30,%f28; nop; fbue .L3365; nop
+ld [%i0+44],%i1
+cmp %i1,0; be .L3368; nop
+set .3350,%o0
+set 4,%o1
+call printf; nop
+.L3368:
+add %i3,4,%i3
+.L3365:
+mov %i3,%i0
+.L3349:
+ret; restore
+.type s88,#function
+.size s88,.-s88
+.section ".data"
+.type .3371,#object
+.align 1
+.3371:
+.byte 115
+.byte 57
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size .3371,9
+.type .3372,#object
+.size .3372,8
+.align 1
+.3372:
+.byte 115
+.byte 57
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.global s9
+.section ".text"
+.align 4
+s9:
+save %sp,-96,%sp
+set .3372,%i3
+add %i0,60,%i2
+mov %g0,%i1
+.L3373:
+.L3374:
+mov %i2,%l7
+add %l7,1,%i2
+mov %i3,%l6
+add %l6,1,%i3
+ldsb [%l6],%l6
+stb %l6,[%l7]
+sll %l6,8*(4-1),%l7; sra %l7,8*(4-1),%l7
+cmp %l7,0; bne .L3373; nop
+mov %g0,%i4
+mov %g0,%i5
+.L3376:
+set 2,%l5
+mov %l5,%l7
+mov %l5,%l6
+set 3,%l3
+mov %l3,%l5
+mov %l3,%l4
+cmp %l4,3; bne .L3382; nop
+cmp %l5,3; be .L3380; nop
+.L3382:
+set 1,%i4
+.L3380:
+cmp %l6,2; bne .L3385; nop
+cmp %l7,2; be .L3383; nop
+.L3385:
+set 1,%i4
+.L3383:
+.L3377:
+add %i5,1,%i5
+cmp %i5,2; bl .L3376; nop
+cmp %i4,0; be .L3390; nop
+ld [%i0+44],%l7
+cmp %l7,0; be .L3388; nop
+set .3371,%o0
+set 1,%o1
+call printf; nop
+.L3388:
+add %i1,1,%i1
+ba .L3390; nop
+ld [%i0+44],%l7
+cmp %l7,0; be .L3391; nop
+set .3371,%o0
+set 2,%o1
+call printf; nop
+.L3391:
+add %i1,2,%i1
+.L3390:
+mov %i1,%i0
+.L3370:
+ret; restore
+.type s9,#function
+.size s9,.-s9
+.global setev
+.align 4
+setev:
+set extvar,%o5
+set 1066,%o4
+st %o4,[%o5]
+mov %g0,%o0
+.L3393:
+retl; nop
+.type setev,#function
+.size setev,.-setev
+.section ".bss"
+.global rfs
+.type rfs,#object
+.size rfs,8
+.common rfs,8,1
+.global crc
+.type crc,#object
+.size crc,4
+.common crc,4,4
+.global rrc
+.type rrc,#object
+.size rrc,4
+.common rrc,4,4
+.global flgl
+.type flgl,#object
+.size flgl,4
+.common flgl,4,4
+.global flgd
+.type flgd,#object
+.size flgd,4
+.common flgd,4,4
+.global flgm
+.type flgm,#object
+.size flgm,4
+.common flgm,4,4
+.global flgs
+.type flgs,#object
+.size flgs,4
+.common flgs,4,4
+.global dprec
+.type dprec,#object
+.size dprec,4
+.common dprec,4,4
+.global fprec
+.type fprec,#object
+.size fprec,4
+.common fprec,4,4
+.global dbits
+.type dbits,#object
+.size dbits,4
+.common dbits,4,4
+.global fbits
+.type fbits,#object
+.size fbits,4
+.common fbits,4,4
+.global ubits
+.type ubits,#object
+.size ubits,4
+.common ubits,4,4
+.global lbits
+.type lbits,#object
+.size lbits,4
+.common lbits,4,4
+.global metricp
+.type metricp,#object
+.size metricp,4
+.common metricp,4,4
+.global extvar
+.type extvar,#object
+.size extvar,4
+.common extvar,4,4
+.section ".rodata"
+.align 1
+.L3266:
+.byte 66
+.byte 101
+.byte 32
+.byte 101
+.byte 115
+.byte 112
+.byte 101
+.byte 99
+.byte 105
+.byte 97
+.byte 108
+.byte 108
+.byte 121
+.byte 32
+.byte 99
+.byte 97
+.byte 114
+.byte 101
+.byte 102
+.byte 117
+.byte 108
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 49
+.byte 45
+.byte 98
+.byte 105
+.byte 116
+.byte 32
+.byte 102
+.byte 105
+.byte 101
+.byte 108
+.byte 100
+.byte 115
+.byte 33
+.byte 10
+.byte 0
+.align 1
+.L3259:
+.byte 83
+.byte 105
+.byte 103
+.byte 110
+.byte 32
+.byte 101
+.byte 120
+.byte 116
+.byte 101
+.byte 110
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 102
+.byte 105
+.byte 101
+.byte 108
+.byte 100
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.L3252:
+.byte 37
+.byte 115
+.byte 37
+.byte 115
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 4
+.L3175:
+.word 0x43080000
+.align 1
+.L3022:
+.byte 112
+.byte 111
+.byte 105
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 0
+.align 1
+.L2472:
+.byte 73
+.byte 110
+.byte 99
+.byte 114
+.byte 101
+.byte 97
+.byte 115
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 97
+.byte 114
+.byte 114
+.byte 97
+.byte 121
+.byte 32
+.byte 101
+.byte 108
+.byte 101
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 97
+.byte 115
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 101
+.byte 100
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 100
+.byte 101
+.byte 99
+.byte 114
+.byte 101
+.byte 97
+.byte 115
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 108
+.byte 111
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 10
+.byte 0
+.align 4
+.L2356:
+.word 0x41d00000
+.align 8
+.L2355:
+.word 0x403a0000
+.word 0x0
+.align 8
+.L1659:
+.word 0x40040000
+.word 0x0
+.align 8
+.L1484:
+.word 0x40240000
+.word 0x0
+.align 4
+.L1455:
+.word 0x41200000
+.align 8
+.L1280:
+.word 0x40080000
+.word 0x0
+.align 4
+.L1251:
+.word 0x40400000
+.align 8
+.L1076:
+.word 0x401c0000
+.word 0x0
+.align 4
+.L1047:
+.word 0x40e00000
+.align 8
+.L870:
+.word 0x40140000
+.word 0x0
+.align 4
+.L841:
+.word 0x40a00000
+.align 8
+.L836:
+.word 0x41e00000
+.word 0x0
+.align 4
+.L828:
+.word 0x4f000000
+.align 1
+.L653:
+.byte 113
+.byte 117
+.byte 101
+.byte 101
+.byte 112
+.byte 0
+.align 1
+.L639:
+.byte 10
+.byte 0
+.align 1
+.L638:
+.byte 37
+.byte 100
+.byte 0
+.align 1
+.L633:
+.byte 32
+.byte 32
+.byte 32
+.byte 107
+.byte 101
+.byte 121
+.byte 61
+.byte 0
+.align 8
+.L596:
+.word 0x40000000
+.word 0x0
+.align 8
+.L536:
+.word 0x40ce8480
+.word 0x0
+.align 8
+.L535:
+.word 0x405f4000
+.word 0x0
+.align 4
+.L534:
+.word 0x42fa0000
+.align 4
+.L529:
+.word 0x40000000
+.align 1
+.L431:
+.byte 100
+.byte 111
+.byte 117
+.byte 98
+.byte 108
+.byte 101
+.byte 0
+.align 1
+.L430:
+.byte 102
+.byte 108
+.byte 111
+.byte 97
+.byte 116
+.byte 0
+.align 1
+.L429:
+.byte 117
+.byte 110
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 101
+.byte 100
+.byte 0
+.align 1
+.L428:
+.byte 108
+.byte 111
+.byte 110
+.byte 103
+.byte 0
+.align 1
+.L427:
+.byte 115
+.byte 104
+.byte 111
+.byte 114
+.byte 116
+.byte 0
+.align 1
+.L426:
+.byte 105
+.byte 110
+.byte 116
+.byte 0
+.align 1
+.L425:
+.byte 99
+.byte 104
+.byte 97
+.byte 114
+.byte 0
+.align 8
+.L419:
+.word 0x0
+.word 0x0
+.align 8
+.L418:
+.word 0x3ff00000
+.word 0x0
+.align 8
+.L417:
+.word 0x40100000
+.word 0x0
+.align 8
+.L416:
+.word 0x40000000
+.word 0x0
+.align 4
+.L412:
+.word 0x0
+.align 4
+.L411:
+.word 0x3f800000
+.align 1
+.L390:
+.byte 113
+.byte 117
+.byte 101
+.byte 101
+.byte 112
+.byte 33
+.byte 0
+.align 1
+.L379:
+.byte 10
+.byte 9
+.byte 8
+.byte 13
+.byte 12
+.byte 92
+.byte 39
+.byte 0
+.align 1
+.L375:
+.byte 46
+.byte 34
+.byte 46
+.byte 0
+.align 1
+.L362:
+.byte 46
+.byte 46
+.byte 46
+.byte 0
+.align 8
+.L333:
+.word 0x40938800
+.word 0x0
+.align 1
+.L199:
+.byte 32
+.byte 32
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 114
+.byte 101
+.byte 115
+.byte 117
+.byte 108
+.byte 116
+.byte 115
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 110
+.byte 32
+.byte 97
+.byte 115
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 101
+.byte 100
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 108
+.byte 111
+.byte 110
+.byte 103
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L198:
+.byte 68
+.byte 101
+.byte 99
+.byte 105
+.byte 109
+.byte 97
+.byte 108
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 111
+.byte 99
+.byte 116
+.byte 97
+.byte 108
+.byte 47
+.byte 104
+.byte 101
+.byte 120
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 115
+.byte 116
+.byte 97
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 115
+.byte 111
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 109
+.byte 101
+.byte 115
+.byte 32
+.byte 103
+.byte 105
+.byte 118
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.L27:
+.byte 10
+.byte 70
+.byte 97
+.byte 105
+.byte 108
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L26:
+.byte 10
+.byte 78
+.byte 111
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 115
+.byte 32
+.byte 100
+.byte 101
+.byte 116
+.byte 101
+.byte 99
+.byte 116
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L20:
+.byte 83
+.byte 101
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 37
+.byte 115
+.byte 32
+.byte 114
+.byte 101
+.byte 116
+.byte 117
+.byte 114
+.byte 110
+.byte 101
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 46
+.byte 10
+.byte 0
diff --git a/lcc/sparc/solaris/tst/cvt.1bk b/lcc/sparc/solaris/tst/cvt.1bk
new file mode 100755
index 0000000..74c79f1
--- /dev/null
+++ b/lcc/sparc/solaris/tst/cvt.1bk
@@ -0,0 +1,11 @@
+1 1 1 1 1 1 1 1 1.000000 1.000000 1.000000
+2 2 2 2 2 2 2 2 2.000000 2.000000 2.000000
+3 3 3 3 3 3 3 3 3.000000 3.000000 3.000000
+4 4 4 4 4 4 4 4 4.000000 4.000000 4.000000
+5 5 5 5 5 5 5 5 5.000000 5.000000 5.000000
+6 6 6 6 6 6 6 6 6.000000 6.000000 6.000000
+7 7 7 7 7 7 7 7 7.000000 7.000000 7.000000
+8 8 8 8 8 8 8 8 8.000000 8.000000 8.000000
+9 9 9 9 9 9 9 9 9.000000 9.000000 9.000000
+10 10 10 10 10 10 10 10 10.000000 10.000000 10.000000
+11 11 11 11 11 11 11 11 11.000000 11.000000 11.000000
diff --git a/lcc/sparc/solaris/tst/cvt.2bk b/lcc/sparc/solaris/tst/cvt.2bk
new file mode 100755
index 0000000..b3ab360
--- /dev/null
+++ b/lcc/sparc/solaris/tst/cvt.2bk
@@ -0,0 +1,2 @@
+tst/cvt.c:32: warning: conversion from `pointer to void function(void)' to `pointer to void' is compiler dependent
+tst/cvt.c:33: warning: conversion from `pointer to void' to `pointer to void function(void)' is compiler dependent
diff --git a/lcc/sparc/solaris/tst/cvt.sbk b/lcc/sparc/solaris/tst/cvt.sbk
new file mode 100755
index 0000000..382a40a
--- /dev/null
+++ b/lcc/sparc/solaris/tst/cvt.sbk
@@ -0,0 +1,715 @@
+.global print
+.section ".text"
+.align 4
+print:
+save %sp,-128,%sp
+set .L2,%o0
+set c,%i5
+ldsb [%i5],%o1
+set s,%i5
+ldsh [%i5],%o2
+set i,%i5
+ld [%i5],%o3
+set l,%i5
+ld [%i5],%o4
+set C,%i5
+ldub [%i5],%o5
+set S,%i5
+lduh [%i5],%i5
+st %i5,[%sp+4*6+68]
+set I,%i5
+ld [%i5],%i5
+st %i5,[%sp+4*7+68]
+set L,%i5
+ld [%i5],%i5
+st %i5,[%sp+4*8+68]
+set f,%i5
+ld [%i5],%f31
+fstod %f31,%f30
+st %f30,[%sp+4*9+68]
+st %f31,[%sp+4*10+68]
+set d,%i5
+ld2 [%i5],%f30
+st %f30,[%sp+4*11+68]
+st %f31,[%sp+4*12+68]
+set D,%i5
+ld2 [%i5],%f30
+st %f30,[%sp+4*13+68]
+st %f31,[%sp+4*14+68]
+call printf; nop
+.L1:
+ret; restore
+.type print,#function
+.size print,.-print
+.global main
+.align 4
+main:
+save %sp,-104,%sp
+set c,%i5
+set 1,%i4
+stb %i4,[%i5]
+ldsb [%i5],%i5
+set s,%i4
+mov %i5,%i3
+sth %i3,[%i4]
+set i,%i4
+st %i5,[%i4]
+set l,%i4
+st %i5,[%i4]
+set C,%i3
+mov %i5,%i2
+stb %i2,[%i3]
+set S,%i3
+mov %i5,%i2
+sth %i2,[%i3]
+set I,%i3
+st %i5,[%i3]
+set L,%i3
+st %i5,[%i3]
+set f,%i4
+st %i5,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+st %f31,[%i4]
+st %i5,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+set d,%i5
+st2 %f30,[%i5]
+set D,%i5
+st2 %f30,[%i5]
+call print; nop
+set s,%i5
+set 2,%i4
+sth %i4,[%i5]
+ldsh [%i5],%i5
+set c,%i4
+mov %i5,%i3
+stb %i3,[%i4]
+set i,%i4
+st %i5,[%i4]
+set l,%i4
+st %i5,[%i4]
+set C,%i3
+mov %i5,%i2
+stb %i2,[%i3]
+set S,%i3
+mov %i5,%i2
+sth %i2,[%i3]
+set I,%i3
+st %i5,[%i3]
+set L,%i3
+st %i5,[%i3]
+set f,%i4
+st %i5,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+st %f31,[%i4]
+st %i5,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+set d,%i5
+st2 %f30,[%i5]
+set D,%i5
+st2 %f30,[%i5]
+call print; nop
+set i,%i5
+set 3,%i4
+st %i4,[%i5]
+ld [%i5],%i5
+set c,%i4
+mov %i5,%i3
+stb %i3,[%i4]
+set s,%i4
+mov %i5,%i3
+sth %i3,[%i4]
+set l,%i4
+st %i5,[%i4]
+set C,%i3
+mov %i5,%i2
+stb %i2,[%i3]
+set S,%i3
+mov %i5,%i2
+sth %i2,[%i3]
+set I,%i3
+st %i5,[%i3]
+set L,%i3
+st %i5,[%i3]
+set f,%i4
+st %i5,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+st %f31,[%i4]
+st %i5,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+set d,%i5
+st2 %f30,[%i5]
+set D,%i5
+st2 %f30,[%i5]
+call print; nop
+set l,%i5
+set 4,%i4
+st %i4,[%i5]
+ld [%i5],%i5
+set c,%i4
+mov %i5,%i3
+stb %i3,[%i4]
+set s,%i4
+mov %i5,%i3
+sth %i3,[%i4]
+set i,%i4
+st %i5,[%i4]
+set C,%i3
+mov %i5,%i2
+stb %i2,[%i3]
+set S,%i3
+mov %i5,%i2
+sth %i2,[%i3]
+set I,%i3
+st %i5,[%i3]
+set L,%i3
+st %i5,[%i3]
+set f,%i4
+st %i5,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+st %f31,[%i4]
+st %i5,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+set d,%i5
+st2 %f30,[%i5]
+set D,%i5
+st2 %f30,[%i5]
+call print; nop
+set C,%i5
+set 5,%i4
+stb %i4,[%i5]
+ldub [%i5],%i5
+set c,%i4
+mov %i5,%i3
+stb %i3,[%i4]
+set s,%i4
+mov %i5,%i3
+sth %i3,[%i4]
+set i,%i4
+st %i5,[%i4]
+set l,%i4
+st %i5,[%i4]
+set S,%i3
+mov %i5,%i2
+sth %i2,[%i3]
+set I,%i3
+st %i5,[%i3]
+set L,%i3
+st %i5,[%i3]
+set f,%i4
+st %i5,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+st %f31,[%i4]
+st %i5,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+set d,%i5
+st2 %f30,[%i5]
+set D,%i5
+st2 %f30,[%i5]
+call print; nop
+set S,%i5
+set 6,%i4
+sth %i4,[%i5]
+lduh [%i5],%i5
+set c,%i4
+mov %i5,%i3
+stb %i3,[%i4]
+set s,%i4
+mov %i5,%i3
+sth %i3,[%i4]
+set i,%i4
+st %i5,[%i4]
+set l,%i4
+st %i5,[%i4]
+set C,%i3
+mov %i5,%i2
+stb %i2,[%i3]
+set I,%i3
+st %i5,[%i3]
+set L,%i3
+st %i5,[%i3]
+set f,%i4
+st %i5,[%sp+64]; ld [%sp+64],%f31; fitos %f31,%f31
+st %f31,[%i4]
+st %i5,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+set d,%i5
+st2 %f30,[%i5]
+set D,%i5
+st2 %f30,[%i5]
+call print; nop
+set I,%i5
+set 7,%i4
+st %i4,[%i5]
+ld [%i5],%i5
+set c,%i3
+mov %i5,%i2
+stb %i2,[%i3]
+set s,%i3
+mov %i5,%i2
+sth %i2,[%i3]
+set i,%i3
+st %i5,[%i3]
+set l,%i3
+st %i5,[%i3]
+set C,%i4
+mov %i5,%i3
+stb %i3,[%i4]
+set S,%i4
+mov %i5,%i3
+sth %i3,[%i4]
+set L,%i4
+st %i5,[%i4]
+set .L4,%i4
+ld2 [%i4],%f30
+srl %i5,1,%i4
+st %i4,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fmuld %f30,%f28,%f30
+set 1,%i4
+and %i5,%i4,%i5
+st %i5,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+faddd %f30,%f28,%f30
+set f,%i5
+fdtos %f30,%f29
+st %f29,[%i5]
+set d,%i5
+st2 %f30,[%i5]
+set D,%i5
+st2 %f30,[%i5]
+call print; nop
+set L,%i5
+set 8,%i4
+st %i4,[%i5]
+ld [%i5],%i5
+set c,%i3
+mov %i5,%i2
+stb %i2,[%i3]
+set s,%i3
+mov %i5,%i2
+sth %i2,[%i3]
+set i,%i3
+st %i5,[%i3]
+set l,%i3
+st %i5,[%i3]
+set C,%i4
+mov %i5,%i3
+stb %i3,[%i4]
+set S,%i4
+mov %i5,%i3
+sth %i3,[%i4]
+set I,%i3
+lduh [%i4],%i4
+st %i4,[%i3]
+set .L4,%i4
+ld2 [%i4],%f30
+srl %i5,1,%i4
+st %i4,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fmuld %f30,%f28,%f30
+set 1,%i4
+and %i5,%i4,%i5
+st %i5,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+faddd %f30,%f28,%f30
+set f,%i5
+fdtos %f30,%f29
+st %f29,[%i5]
+set d,%i5
+st2 %f30,[%i5]
+set D,%i5
+st2 %f30,[%i5]
+call print; nop
+set f,%i1
+set .L5,%i0
+ld [%i0],%f31
+st %f31,[%i1]
+ld [%i1],%f31
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%i1
+set c,%i0
+mov %i1,%l7
+stb %l7,[%i0]
+set s,%i0
+mov %i1,%l7
+sth %l7,[%i0]
+set i,%i0
+st %i1,[%i0]
+set l,%i0
+st %i1,[%i0]
+set .L9,%i1
+ld [%i1],%f30
+fcmpes %f31,%f30; nop; fbul .L7; nop
+fsubs %f31,%f30,%f30
+fstoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%i1
+set 0x80000000,%i0
+add %i1,%i0,%i5
+ba .L8; nop
+.L7:
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%i1
+mov %i1,%i5
+.L8:
+set C,%i1
+mov %i5,%i0
+stb %i0,[%i1]
+set f,%i1
+ld [%i1],%f31
+set .L9,%i1
+ld [%i1],%f30
+fcmpes %f31,%f30; nop; fbul .L11; nop
+fsubs %f31,%f30,%f30
+fstoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%i1
+set 0x80000000,%i0
+add %i1,%i0,%i4
+ba .L12; nop
+.L11:
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%i1
+mov %i1,%i4
+.L12:
+set S,%i1
+mov %i4,%i0
+sth %i0,[%i1]
+set f,%i1
+ld [%i1],%f31
+set .L9,%i1
+ld [%i1],%f30
+fcmpes %f31,%f30; nop; fbul .L14; nop
+fsubs %f31,%f30,%f30
+fstoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%i1
+set 0x80000000,%i0
+add %i1,%i0,%i3
+ba .L15; nop
+.L14:
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%i1
+mov %i1,%i3
+.L15:
+set I,%i1
+st %i3,[%i1]
+set f,%i1
+ld [%i1],%f31
+set .L9,%i1
+ld [%i1],%f30
+fcmpes %f31,%f30; nop; fbul .L17; nop
+fsubs %f31,%f30,%f30
+fstoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%i1
+set 0x80000000,%i0
+add %i1,%i0,%i2
+ba .L18; nop
+.L17:
+fstoi %f31,%f0; st %f0,[%sp+64]; ld [%sp+64],%i1
+mov %i1,%i2
+.L18:
+set L,%i1
+st %i2,[%i1]
+set f,%i1
+ld [%i1],%f31
+fstod %f31,%f30
+set d,%i1
+st2 %f30,[%i1]
+set D,%i1
+st2 %f30,[%i1]
+call print; nop
+set d,%l5
+set .L19,%l4
+ld2 [%l4],%f30
+st2 %f30,[%l5]
+ld2 [%l5],%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l5
+set c,%l4
+mov %l5,%l3
+stb %l3,[%l4]
+set s,%l4
+mov %l5,%l3
+sth %l3,[%l4]
+set i,%l4
+st %l5,[%l4]
+set l,%l4
+st %l5,[%l4]
+set .L23,%l5
+ld2 [%l5],%f28
+fcmped %f30,%f28; nop; fbul .L21; nop
+fsubd %f30,%f28,%f28
+fdtoi %f28,%f0; st %f0,[%sp+64]; ld [%sp+64],%l5
+set 0x80000000,%l4
+add %l5,%l4,%i1
+ba .L22; nop
+.L21:
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l5
+mov %l5,%i1
+.L22:
+set C,%l5
+mov %i1,%l4
+stb %l4,[%l5]
+set d,%l5
+ld2 [%l5],%f30
+set .L23,%l5
+ld2 [%l5],%f28
+fcmped %f30,%f28; nop; fbul .L25; nop
+fsubd %f30,%f28,%f28
+fdtoi %f28,%f0; st %f0,[%sp+64]; ld [%sp+64],%l5
+set 0x80000000,%l4
+add %l5,%l4,%i0
+ba .L26; nop
+.L25:
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l5
+mov %l5,%i0
+.L26:
+set S,%l5
+mov %i0,%l4
+sth %l4,[%l5]
+set d,%l5
+ld2 [%l5],%f30
+set .L23,%l5
+ld2 [%l5],%f28
+fcmped %f30,%f28; nop; fbul .L28; nop
+fsubd %f30,%f28,%f28
+fdtoi %f28,%f0; st %f0,[%sp+64]; ld [%sp+64],%l5
+set 0x80000000,%l4
+add %l5,%l4,%l7
+ba .L29; nop
+.L28:
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l5
+mov %l5,%l7
+.L29:
+set I,%l5
+st %l7,[%l5]
+set d,%l5
+ld2 [%l5],%f30
+set .L23,%l5
+ld2 [%l5],%f28
+fcmped %f30,%f28; nop; fbul .L31; nop
+fsubd %f30,%f28,%f28
+fdtoi %f28,%f0; st %f0,[%sp+64]; ld [%sp+64],%l5
+set 0x80000000,%l4
+add %l5,%l4,%l6
+ba .L32; nop
+.L31:
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l5
+mov %l5,%l6
+.L32:
+set L,%l5
+st %l6,[%l5]
+set d,%l5
+ld2 [%l5],%f30
+set f,%l5
+fdtos %f30,%f29
+st %f29,[%l5]
+set D,%l5
+st2 %f30,[%l5]
+call print; nop
+set D,%l3
+set .L33,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+ld2 [%l3],%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+set c,%l2
+mov %l3,%l1
+stb %l1,[%l2]
+set s,%l2
+mov %l3,%l1
+sth %l1,[%l2]
+set i,%l2
+st %l3,[%l2]
+set l,%l2
+st %l3,[%l2]
+set .L37,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbul .L35; nop
+fsubd %f30,%f28,%f28
+fdtoi %f28,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+set 0x80000000,%l2
+add %l3,%l2,%l5
+ba .L36; nop
+.L35:
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+mov %l3,%l5
+.L36:
+set C,%l3
+mov %l5,%l2
+stb %l2,[%l3]
+set D,%l3
+ld2 [%l3],%f30
+set .L37,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbul .L39; nop
+fsubd %f30,%f28,%f28
+fdtoi %f28,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+set 0x80000000,%l2
+add %l3,%l2,%l4
+ba .L40; nop
+.L39:
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+mov %l3,%l4
+.L40:
+set S,%l3
+mov %l4,%l2
+sth %l2,[%l3]
+set D,%l3
+ld2 [%l3],%f30
+set .L37,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbul .L42; nop
+fsubd %f30,%f28,%f28
+fdtoi %f28,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+set 0x80000000,%l2
+add %l3,%l2,%l3
+st %l3,[%fp+-4]
+ba .L43; nop
+.L42:
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+st %l3,[%fp+-4]
+.L43:
+set I,%l3
+ld [%fp+-4],%l2
+st %l2,[%l3]
+set D,%l3
+ld2 [%l3],%f30
+set .L37,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbul .L45; nop
+fsubd %f30,%f28,%f28
+fdtoi %f28,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+set 0x80000000,%l2
+add %l3,%l2,%l3
+st %l3,[%fp+-8]
+ba .L46; nop
+.L45:
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l3
+st %l3,[%fp+-8]
+.L46:
+set L,%l3
+ld [%fp+-8],%l2
+st %l2,[%l3]
+set D,%l3
+ld2 [%l3],%f30
+set f,%l3
+fdtos %f30,%f29
+st %f29,[%l3]
+set d,%l3
+st2 %f30,[%l3]
+call print; nop
+set p,%l3
+st %g0,[%l3]
+st %g0,[%l3]
+st %g0,[%l3]
+st %g0,[%l3]
+set P,%l2
+ld [%l2],%l1
+st %l1,[%l3]
+mov %g0,%l1
+st %l1,[%l2]
+st %l1,[%l2]
+st %l1,[%l2]
+st %l1,[%l2]
+ld [%l3],%l3
+st %l3,[%l2]
+mov %g0,%i0
+.L3:
+ret; restore
+.type main,#function
+.size main,.-main
+.section ".bss"
+.global P
+.type P,#object
+.size P,4
+.common P,4,4
+.global p
+.type p,#object
+.size p,4
+.common p,4,4
+.global D
+.type D,#object
+.size D,8
+.common D,8,8
+.global d
+.type d,#object
+.size d,8
+.common d,8,8
+.global f
+.type f,#object
+.size f,4
+.common f,4,4
+.global L
+.type L,#object
+.size L,4
+.common L,4,4
+.global I
+.type I,#object
+.size I,4
+.common I,4,4
+.global S
+.type S,#object
+.size S,2
+.common S,2,2
+.global C
+.type C,#object
+.size C,1
+.common C,1,1
+.global l
+.type l,#object
+.size l,4
+.common l,4,4
+.global i
+.type i,#object
+.size i,4
+.common i,4,4
+.global s
+.type s,#object
+.size s,2
+.common s,2,2
+.global c
+.type c,#object
+.size c,1
+.common c,1,1
+.section ".rodata"
+.align 8
+.L37:
+.word 0x41e00000
+.word 0x0
+.align 8
+.L33:
+.word 0x40260000
+.word 0x0
+.align 8
+.L23:
+.word 0x41e00000
+.word 0x0
+.align 8
+.L19:
+.word 0x40240000
+.word 0x0
+.align 4
+.L9:
+.word 0x4f000000
+.align 4
+.L5:
+.word 0x41100000
+.align 8
+.L4:
+.word 0x40000000
+.word 0x0
+.align 1
+.L2:
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 108
+.byte 100
+.byte 32
+.byte 37
+.byte 117
+.byte 32
+.byte 37
+.byte 117
+.byte 32
+.byte 37
+.byte 117
+.byte 32
+.byte 37
+.byte 108
+.byte 117
+.byte 32
+.byte 37
+.byte 102
+.byte 32
+.byte 37
+.byte 102
+.byte 32
+.byte 37
+.byte 108
+.byte 102
+.byte 10
+.byte 0
diff --git a/lcc/sparc/solaris/tst/fields.1bk b/lcc/sparc/solaris/tst/fields.1bk
new file mode 100755
index 0000000..f30b13f
--- /dev/null
+++ b/lcc/sparc/solaris/tst/fields.1bk
@@ -0,0 +1,5 @@
+x = 1 2 3 4 -3 6
+y = 3 8 9
+x = 1 2 3 0 0 6
+y = 2 8 16
+p->a = 0x3, p->b = 0xf
diff --git a/lcc/sparc/solaris/tst/fields.2bk b/lcc/sparc/solaris/tst/fields.2bk
new file mode 100755
index 0000000..e689d78
--- /dev/null
+++ b/lcc/sparc/solaris/tst/fields.2bk
@@ -0,0 +1,4 @@
+tst/fields.c:6: warning: initializer exceeds bit-field width
+tst/fields.c:8: warning: initializer exceeds bit-field width
+tst/fields.c:30: warning: missing return value
+tst/fields.c:34: warning: missing return value
diff --git a/lcc/sparc/solaris/tst/fields.sbk b/lcc/sparc/solaris/tst/fields.sbk
new file mode 100755
index 0000000..c535964
--- /dev/null
+++ b/lcc/sparc/solaris/tst/fields.sbk
@@ -0,0 +1,309 @@
+.section ".data"
+.global x
+.type x,#object
+.size x,16
+.align 4
+x:
+.word 0x1
+.byte 0x2
+.skip 3
+.byte 0x0
+.byte 0x34
+.skip 2
+.byte 0xa
+.byte 0x6
+.skip 2
+.global i
+.type i,#object
+.size i,4
+.align 4
+i:
+.word 0x10
+.global y
+.type y,#object
+.size y,8
+.align 4
+y:
+.byte 0xe0
+.skip 3
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x9
+.global main
+.section ".text"
+.align 4
+main:
+save %sp,-96,%sp
+set .L4,%o0
+set x,%i5
+ld [%i5],%o1
+set x+4,%i5
+ldsb [%i5],%o2
+set x+8,%i5
+ld [%i5],%i5
+sra %i5,20,%o3
+set x+8,%i5
+ld [%i5],%i5
+sll %i5,12,%i5
+sra %i5,28,%o4
+set x+12,%i5
+ld [%i5],%i5
+sll %i5,4,%i5
+sra %i5,29,%o5
+set x+13,%i5
+ldsb [%i5],%i5
+st %i5,[%sp+4*6+68]
+call printf; nop
+set .L10,%o0
+set y,%i5
+ld [%i5],%i5
+srl %i5,30,%i4
+set 3,%i3
+and %i4,%i3,%o1
+srl %i5,26,%i5
+set 15,%i4
+and %i5,%i4,%o2
+set y+4,%i5
+ld [%i5],%o3
+call printf; nop
+set x+8,%i5
+ld [%i5],%i4
+set 0xfff0ffff,%i3
+and %i4,%i3,%i4
+set i,%i3
+ld [%i3],%i3
+sll %i3,28,%i3
+sra %i3,28,%i3
+sll %i3,16,%i3
+set 0xf0000,%i2
+and %i3,%i2,%i3
+or %i4,%i3,%i4
+st %i4,[%i5]
+set x+12,%i5
+ld [%i5],%i4
+set 0xf1ffffff,%i3
+and %i4,%i3,%i4
+st %i4,[%i5]
+set .L4,%o0
+set x,%i5
+ld [%i5],%o1
+set x+4,%i5
+ldsb [%i5],%o2
+set x+8,%i5
+ld [%i5],%i5
+sra %i5,20,%o3
+set x+8,%i5
+ld [%i5],%i5
+sll %i5,12,%i5
+sra %i5,28,%o4
+set x+12,%i5
+ld [%i5],%i5
+sll %i5,4,%i5
+sra %i5,29,%o5
+set x+13,%i5
+ldsb [%i5],%i5
+st %i5,[%sp+4*6+68]
+call printf; nop
+set y,%i5
+ld [%i5],%i4
+set 0x3fffffff,%i3
+and %i4,%i3,%i4
+set 0x80000000,%i3
+or %i4,%i3,%i4
+st %i4,[%i5]
+set y+4,%i5
+set i,%i4
+ld [%i4],%i4
+st %i4,[%i5]
+set .L10,%o0
+set y,%i5
+ld [%i5],%i5
+srl %i5,30,%i4
+set 3,%i3
+and %i4,%i3,%o1
+srl %i5,26,%i5
+set 15,%i4
+and %i5,%i4,%o2
+set y+4,%i5
+ld [%i5],%o3
+call printf; nop
+set x,%o0
+call f2; nop
+mov %g0,%i0
+.L3:
+ret; restore
+.type main,#function
+.size main,.-main
+.global f1
+.align 4
+f1:
+save %sp,-96,%sp
+ld [%i0],%i5
+set 0xc3ffffff,%i4
+and %i5,%i4,%i5
+st %i5,[%i0]
+ld [%i0],%i5
+set 0x3fffffff,%i4
+and %i5,%i4,%i5
+set 3,%i4
+and %g0,%i4,%i4
+sll %i4,30,%i4
+set 0xc0000000,%i3
+and %i4,%i3,%i4
+or %i5,%i4,%i5
+st %i5,[%i0]
+ld [%i0],%i5
+set 0x3c000000,%i4
+and %i5,%i4,%i5
+cmp %i5,%g0; be .L22; nop
+set .L24,%o0
+call printf; nop
+.L22:
+ld [%i0],%i5
+set 0xc0000000,%i4
+or %i5,%i4,%i5
+st %i5,[%i0]
+ld [%i0],%i5
+set 0x3c000000,%i4
+or %i5,%i4,%i5
+st %i5,[%i0]
+set .L25,%o0
+ld [%i0],%i5
+srl %i5,30,%i4
+set 3,%i3
+and %i4,%i3,%o1
+srl %i5,26,%i5
+set 15,%i4
+and %i5,%i4,%o2
+call printf; nop
+mov %g0,%i0
+.L21:
+ret; restore
+.type f1,#function
+.size f1,.-f1
+.global f2
+.align 4
+f2:
+save %sp,-96,%sp
+set i,%i4
+ld [%i4],%i4
+cmp %i4,0; bne .L28; nop
+set 1,%i5
+ba .L29; nop
+.L28:
+mov %g0,%i5
+.L29:
+ld [%i0],%i4
+set 0x3fffffff,%i3
+and %i4,%i3,%i4
+mov %i5,%i3
+set 3,%i2
+and %i3,%i2,%i3
+sll %i3,30,%i3
+set 0xc0000000,%i2
+and %i3,%i2,%i3
+or %i4,%i3,%i4
+st %i4,[%i0]
+mov %i0,%o0
+call f1; nop
+ld [%i0],%i4
+set 0xc3ffffff,%i3
+and %i4,%i3,%i4
+mov %g0,%i3
+set 15,%i2
+and %i3,%i2,%i3
+sll %i3,26,%i3
+set 0x3c000000,%i2
+and %i3,%i2,%i3
+or %i4,%i3,%i4
+st %i4,[%i0]
+mov %g0,%i0
+.L26:
+ret; restore
+.type f2,#function
+.size f2,.-f2
+.section ".rodata"
+.align 1
+.L25:
+.byte 112
+.byte 45
+.byte 62
+.byte 97
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 120
+.byte 37
+.byte 120
+.byte 44
+.byte 32
+.byte 112
+.byte 45
+.byte 62
+.byte 98
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 120
+.byte 37
+.byte 120
+.byte 10
+.byte 0
+.align 1
+.L24:
+.byte 112
+.byte 45
+.byte 62
+.byte 98
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 33
+.byte 10
+.byte 0
+.align 1
+.L10:
+.byte 121
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L4:
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
diff --git a/lcc/sparc/solaris/tst/front.2bk b/lcc/sparc/solaris/tst/front.2bk
new file mode 100755
index 0000000..841e6a5
--- /dev/null
+++ b/lcc/sparc/solaris/tst/front.2bk
@@ -0,0 +1,29 @@
+tst/front.c:3: warning: missing return value
+tst/front.c:10: warning: missing return value
+tst/front.c:20: type error in argument 1 to `s'; found `pointer to struct D' expected `pointer to incomplete struct D defined at tst/front.c:14'
+tst/front.c:21: warning: missing return value
+tst/front.c:32: warning: missing return value
+tst/front.c:36: operands of = have illegal types `pointer to int' and `pointer to const int'
+tst/front.c:38: warning: missing return value
+tst/front.c:62: operands of = have illegal types `pointer to char' and `pointer to const void'
+tst/front.c:63: warning: missing return value
+tst/front.c:68: warning: missing return value
+tst/front.c:69: warning: inconsistent linkage for `yy' previously declared at tst/front.c:68
+tst/front.c:69: warning: missing return value
+tst/front.c:71: invalid storage class `static' for `int function goo'
+tst/front.c:71: warning: declaration of `goo' does not match previous declaration at tst/front.c:70
+tst/front.c:71: warning: missing return value
+tst/front.c:74: warning: declaration of `xr' does not match previous declaration at tst/front.c:72
+tst/front.c:74: warning: missing return value
+tst/front.c:81: warning: missing return value
+tst/front.c:82: warning: declaration of `ss2' does not match previous declaration at tst/front.c:81
+tst/front.c:84: warning: inconsistent linkage for `ss5' previously declared at tst/front.c:80
+tst/front.c:92: type error in argument 1 to `gx1'; found `pointer to double' expected `double'
+tst/front.c:92: warning: missing return value
+tst/front.c:95: redeclaration of `hx1' previously declared at tst/front.c:94
+tst/front.c:98: warning: missing return value
+tst/front.c:101: conflicting argument declarations for function `gg1'
+tst/front.c:101: warning: missing return value
+tst/front.c:112: type error in argument 4 to `qsort'; found `pointer to int function(pointer to pointer to char,pointer to pointer to char)' expected `pointer to int function(pointer to const void,pointer to const void)'
+tst/front.c:113: warning: missing return value
+tst/front.c:120: warning: missing return value
diff --git a/lcc/sparc/solaris/tst/front.sbk b/lcc/sparc/solaris/tst/front.sbk
new file mode 100755
index 0000000..37a6f0d
--- /dev/null
+++ b/lcc/sparc/solaris/tst/front.sbk
@@ -0,0 +1,260 @@
+.global main
+.section ".text"
+.align 4
+main:
+save %sp,-96,%sp
+mov %g0,%o0
+call exit; nop
+mov %g0,%i0
+.L1:
+ret; restore
+.type main,#function
+.size main,.-main
+.global nested
+.align 4
+nested:
+cmp %o0,4; bge .L6; nop
+cmp %o1,114; be .L9; nop
+.L6:
+cmp %o0,1; bne .L8; nop
+cmp %o1,104; be .L9; nop
+cmp %o1,105; be .L9; nop
+.L8:
+cmp %o0,2; bne .L3; nop
+cmp %o1,111; be .L9; nop
+cmp %o1,121; bne .L3; nop
+.L9:
+mov %o1,%o0
+.L3:
+mov %g0,%o0
+.L2:
+retl; nop
+.type nested,#function
+.size nested,.-nested
+.global s
+.align 4
+s:
+.L10:
+retl; nop
+.type s,#function
+.size s,.-s
+.section ".data"
+.global Dy
+.type Dy,#object
+.size Dy,8
+.align 4
+Dy:
+.word 0x0
+.skip 4
+.global Dz
+.type Dz,#object
+.size Dz,8
+.align 4
+Dz:
+.word 0x1
+.skip 4
+.global Dfunc
+.section ".text"
+.align 4
+Dfunc:
+save %sp,-96,%sp
+ret; restore
+.type Dfunc,#function
+.size Dfunc,.-Dfunc
+.global f
+.align 4
+f:
+retl; nop
+.type f,#function
+.size f,.-f
+.global f1
+.align 4
+f1:
+retl; nop
+.type f1,#function
+.size f1,.-f1
+.global f2
+.align 4
+f2:
+save %sp,-96,%sp
+ret; restore
+.type f2,#function
+.size f2,.-f2
+.global g
+.align 4
+g:
+save %sp,-96,%sp
+ret; restore
+.type g,#function
+.size g,.-g
+.global h
+.align 4
+h:
+save %sp,-96,%sp
+ret; restore
+.type h,#function
+.size h,.-h
+.global h1
+.align 4
+h1:
+save %sp,-96,%sp
+ret; restore
+.type h1,#function
+.size h1,.-h1
+.global h2
+.align 4
+h2:
+retl; nop
+.type h2,#function
+.size h2,.-h2
+.section ".data"
+.type .21,#object
+.size .21,4
+.align 4
+.21:
+.word 0x1
+.global set1
+.section ".text"
+.align 4
+set1:
+retl; nop
+.type set1,#function
+.size set1,.-set1
+.section ".data"
+.type .23,#object
+.size .23,4
+.align 4
+.23:
+.word 0x2
+.global set2
+.section ".text"
+.align 4
+set2:
+retl; nop
+.type set2,#function
+.size set2,.-set2
+.align 4
+goo:
+retl; nop
+.type goo,#function
+.size goo,.-goo
+.global sss
+.align 4
+sss:
+retl; nop
+.type sss,#function
+.size sss,.-sss
+.section ".bss"
+.type .27,#object
+.size .27,4
+.local .27
+.common .27,4,4
+.global rrr
+.section ".text"
+.align 4
+rrr:
+retl; nop
+.type rrr,#function
+.size rrr,.-rrr
+.global setstatic
+.align 4
+setstatic:
+retl; nop
+.type setstatic,#function
+.size setstatic,.-setstatic
+.global gx1
+.align 4
+gx1:
+save %sp,-96,%sp
+st %r24,[%fp+68]
+st %r25,[%fp+72]
+ret; restore
+.type gx1,#function
+.size gx1,.-gx1
+.global ff1
+.align 4
+ff1:
+save %sp,-96,%sp
+st %r24,[%fp+68]
+st %r25,[%fp+72]
+ret; restore
+.type ff1,#function
+.size ff1,.-ff1
+.global gg1
+.align 4
+gg1:
+retl; nop
+.type gg1,#function
+.size gg1,.-gg1
+.global hh1
+.align 4
+hh1:
+retl; nop
+.type hh1,#function
+.size hh1,.-hh1
+.global cmp
+.align 4
+cmp:
+save %sp,-96,%sp
+ret; restore
+.type cmp,#function
+.size cmp,.-cmp
+.global sort
+.align 4
+sort:
+save %sp,-96,%sp
+ret; restore
+.type sort,#function
+.size sort,.-sort
+.global onearg
+.align 4
+onearg:
+save %sp,-96,%sp
+ret; restore
+.type onearg,#function
+.size onearg,.-onearg
+.section ".bss"
+.global ss4
+.type ss4,#object
+.size ss4,4
+.common ss4,4,4
+.type ss2,#object
+.size ss2,4
+.local ss2
+.common ss2,4,4
+.type ss5,#object
+.size ss5,4
+.local ss5
+.common ss5,4,4
+.global ss3
+.type ss3,#object
+.size ss3,4
+.common ss3,4,4
+.type ss1,#object
+.size ss1,4
+.local ss1
+.common ss1,4,4
+.type yy,#object
+.size yy,4
+.local yy
+.common yy,4,4
+.global z
+.type z,#object
+.size z,4
+.common z,4,4
+.global y
+.type y,#object
+.size y,4
+.common y,4,4
+.global x
+.type x,#object
+.size x,4
+.common x,4,4
+.global b
+.type b,#object
+.size b,4
+.common b,4,4
+.global a
+.type a,#object
+.size a,4
+.common a,4,4
diff --git a/lcc/sparc/solaris/tst/incr.1bk b/lcc/sparc/solaris/tst/incr.1bk
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/sparc/solaris/tst/incr.1bk
diff --git a/lcc/sparc/solaris/tst/incr.2bk b/lcc/sparc/solaris/tst/incr.2bk
new file mode 100755
index 0000000..b86c400
--- /dev/null
+++ b/lcc/sparc/solaris/tst/incr.2bk
@@ -0,0 +1,9 @@
+tst/incr.c:1: warning: missing return value
+tst/incr.c:6: warning: expression with no effect elided
+tst/incr.c:6: warning: expression with no effect elided
+tst/incr.c:11: warning: missing return value
+tst/incr.c:16: warning: expression with no effect elided
+tst/incr.c:16: warning: expression with no effect elided
+tst/incr.c:21: warning: missing return value
+tst/incr.c:30: warning: missing return value
+tst/incr.c:39: warning: missing return value
diff --git a/lcc/sparc/solaris/tst/incr.sbk b/lcc/sparc/solaris/tst/incr.sbk
new file mode 100755
index 0000000..752c97d
--- /dev/null
+++ b/lcc/sparc/solaris/tst/incr.sbk
@@ -0,0 +1,107 @@
+.global main
+.section ".text"
+.align 4
+main:
+mov %g0,%o0
+.L1:
+retl; nop
+.type main,#function
+.size main,.-main
+.global memchar
+.align 4
+memchar:
+save %sp,-104,%sp
+ld [%fp+-8],%i5
+add %i5,1,%i4
+st %i4,[%fp+-8]
+ldsb [%i5],%i5
+stb %i5,[%fp+-1]
+ld [%fp+-8],%i5
+add %i5,1,%i5
+st %i5,[%fp+-8]
+ldsb [%i5],%i5
+stb %i5,[%fp+-1]
+ld [%fp+-8],%i5
+add %i5,-1,%i4
+st %i4,[%fp+-8]
+ldsb [%i5],%i5
+stb %i5,[%fp+-1]
+ld [%fp+-8],%i5
+add %i5,-1,%i5
+st %i5,[%fp+-8]
+ldsb [%i5],%i5
+stb %i5,[%fp+-1]
+mov %g0,%i0
+.L2:
+ret; restore
+.type memchar,#function
+.size memchar,.-memchar
+.global memint
+.align 4
+memint:
+save %sp,-104,%sp
+ld [%fp+-8],%i5
+add %i5,4,%i4
+st %i4,[%fp+-8]
+ld [%i5],%i5
+st %i5,[%fp+-4]
+ld [%fp+-8],%i5
+add %i5,4,%i5
+st %i5,[%fp+-8]
+ld [%i5],%i5
+st %i5,[%fp+-4]
+ld [%fp+-8],%i5
+add %i5,-4,%i4
+st %i4,[%fp+-8]
+ld [%i5],%i5
+st %i5,[%fp+-4]
+ld [%fp+-8],%i5
+add %i5,-4,%i5
+st %i5,[%fp+-8]
+ld [%i5],%i5
+st %i5,[%fp+-4]
+mov %g0,%i0
+.L3:
+ret; restore
+.type memint,#function
+.size memint,.-memint
+.global regchar
+.align 4
+regchar:
+mov %o4,%o3
+add %o3,1,%o4
+ldsb [%o3],%o5
+add %o4,1,%o3
+mov %o3,%o4
+ldsb [%o3],%o5
+mov %o4,%o3
+add %o3,-1,%o4
+ldsb [%o3],%o5
+add %o4,-1,%o3
+mov %o3,%o4
+ldsb [%o3],%o5
+mov %g0,%o0
+.L4:
+retl; nop
+.type regchar,#function
+.size regchar,.-regchar
+.global regint
+.align 4
+regint:
+mov %o4,%o3
+add %o3,4,%o4
+ld [%o3],%o5
+add %o4,4,%o3
+mov %o3,%o4
+ld [%o3],%o5
+mov %o4,%o3
+add %o3,-4,%o4
+ld [%o3],%o5
+add %o4,-4,%o3
+mov %o3,%o4
+ld [%o3],%o5
+mov %g0,%o0
+.L5:
+retl; nop
+.type regint,#function
+.size regint,.-regint
diff --git a/lcc/sparc/solaris/tst/init.1bk b/lcc/sparc/solaris/tst/init.1bk
new file mode 100755
index 0000000..042f3bb
--- /dev/null
+++ b/lcc/sparc/solaris/tst/init.1bk
@@ -0,0 +1,16 @@
+ 1 2 3 4
+ 5 6
+ 7
+if
+for
+else
+while
+1 2 3 if
+4 5 0 for
+6 7 8 else
+9 10 11 while
+1 2 3 if
+4 5 0 for
+6 7 8 else
+9 10 11 while
+0 0 0
diff --git a/lcc/sparc/solaris/tst/init.2bk b/lcc/sparc/solaris/tst/init.2bk
new file mode 100755
index 0000000..da08062
--- /dev/null
+++ b/lcc/sparc/solaris/tst/init.2bk
@@ -0,0 +1,3 @@
+tst/init.c:36: warning: missing return value
+tst/init.c:49: warning: missing return value
+tst/init.c:59: warning: missing return value
diff --git a/lcc/sparc/solaris/tst/init.sbk b/lcc/sparc/solaris/tst/init.sbk
new file mode 100755
index 0000000..2b10055
--- /dev/null
+++ b/lcc/sparc/solaris/tst/init.sbk
@@ -0,0 +1,277 @@
+.section ".data"
+.global words
+.type words,#object
+.align 4
+words:
+.word 0x1
+.word 0x2
+.word 0x3
+.byte 105
+.byte 102
+.byte 0
+.skip 3
+.skip 2
+.word 0x4
+.word 0x5
+.skip 4
+.byte 102
+.byte 111
+.byte 114
+.skip 3
+.skip 2
+.word 0x6
+.word 0x7
+.word 0x8
+.byte 101
+.byte 108
+.byte 115
+.byte 101
+.byte 0
+.skip 1
+.skip 2
+.word 0x9
+.word 0xa
+.word 0xb
+.byte 119
+.byte 104
+.byte 105
+.byte 108
+.byte 101
+.skip 1
+.skip 2
+.word 0x0
+.skip 8
+.skip 8
+.size words,100
+.global wordlist
+.type wordlist,#object
+.size wordlist,4
+.align 4
+wordlist:
+.word words
+.global x
+.type x,#object
+.align 4
+x:
+.word 0x1
+.word 0x2
+.word 0x3
+.word 0x4
+.word 0x0
+.word 0x5
+.word 0x6
+.skip 12
+.word 0x7
+.skip 16
+.size x,60
+.global y
+.type y,#object
+.align 4
+y:
+.word x
+.word x+20
+.word x+40
+.word 0x0
+.size y,16
+.global main
+.section ".text"
+.align 4
+main:
+save %sp,-96,%sp
+mov %g0,%i4
+ba .L8; nop
+.L5:
+mov %g0,%i5
+ba .L12; nop
+.L9:
+set .L13,%o0
+sll %i5,2,%i3
+sll %i4,2,%i2
+set y,%i1
+ld [%i2+%i1],%i2
+ld [%i3+%i2],%o1
+call printf; nop
+.L10:
+add %i5,1,%i5
+.L12:
+sll %i5,2,%i3
+sll %i4,2,%i2
+set y,%i1
+ld [%i2+%i1],%i2
+ld [%i3+%i2],%i3
+cmp %i3,0; bne .L9; nop
+set .L14,%o0
+call printf; nop
+.L6:
+add %i4,1,%i4
+.L8:
+sll %i4,2,%i3
+set y,%i2
+ld [%i3+%i2],%i3
+cmp %i3,%g0; bne .L5; nop
+call f; nop
+set wordlist,%i3
+ld [%i3],%o0
+call g; nop
+mov %g0,%i0
+.L4:
+ret; restore
+.type main,#function
+.size main,.-main
+.section ".data"
+.type .16,#object
+.align 4
+.16:
+.word .L17
+.word .L18
+.word .L19
+.word .L20
+.word 0x0
+.size .16,20
+.global f
+.section ".text"
+.align 4
+f:
+save %sp,-96,%sp
+set .16,%i5
+ba .L24; nop
+.L21:
+set .L25,%o0
+ld [%i5],%o1
+call printf; nop
+.L22:
+add %i5,4,%i5
+.L24:
+ld [%i5],%i4
+cmp %i4,%g0; bne .L21; nop
+mov %g0,%i0
+.L15:
+ret; restore
+.type f,#function
+.size f,.-f
+.global g
+.align 4
+g:
+save %sp,-96,%sp
+ba .L30; nop
+.L27:
+mov %g0,%i5
+ba .L34; nop
+.L31:
+set .L35,%o0
+sll %i5,2,%i4
+ld [%i4+%i0],%o1
+call printf; nop
+.L32:
+add %i5,1,%i5
+.L34:
+mov %i5,%i4
+set 3,%i3
+cmp %i4,%i3; blu .L31; nop
+set .L25,%o0
+add %i0,12,%o1
+call printf; nop
+.L28:
+add %i0,20,%i0
+.L30:
+ld [%i0],%i4
+cmp %i4,0; bne .L27; nop
+call h; nop
+mov %g0,%i0
+.L26:
+ret; restore
+.type g,#function
+.size g,.-g
+.global h
+.align 4
+h:
+save %sp,-96,%sp
+mov %g0,%i5
+ba .L40; nop
+.L37:
+set .L41,%o0
+smul %i5,20,%i4
+set words,%i3
+ld [%i4+%i3],%o1
+set words+4,%i3
+ld [%i4+%i3],%o2
+set words+8,%i3
+ld [%i4+%i3],%o3
+set words+12,%i3
+add %i4,%i3,%o4
+call printf; nop
+.L38:
+add %i5,1,%i5
+.L40:
+mov %i5,%i4
+set 5,%i3
+cmp %i4,%i3; blu .L37; nop
+mov %g0,%i0
+.L36:
+ret; restore
+.type h,#function
+.size h,.-h
+.section ".rodata"
+.align 1
+.L41:
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.L35:
+.byte 37
+.byte 100
+.byte 32
+.byte 0
+.align 1
+.L25:
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.L20:
+.byte 119
+.byte 104
+.byte 105
+.byte 108
+.byte 101
+.byte 0
+.align 1
+.L19:
+.byte 101
+.byte 108
+.byte 115
+.byte 101
+.byte 0
+.align 1
+.L18:
+.byte 102
+.byte 111
+.byte 114
+.byte 0
+.align 1
+.L17:
+.byte 105
+.byte 102
+.byte 0
+.align 1
+.L14:
+.byte 10
+.byte 0
+.align 1
+.L13:
+.byte 32
+.byte 37
+.byte 100
+.byte 0
diff --git a/lcc/sparc/solaris/tst/limits.1bk b/lcc/sparc/solaris/tst/limits.1bk
new file mode 100755
index 0000000..f0c1dc8
--- /dev/null
+++ b/lcc/sparc/solaris/tst/limits.1bk
@@ -0,0 +1,14 @@
+UCHAR_MAX: 000000ff=255
+USHRT_MAX: 0000ffff=65535
+UINT_MAX: ffffffff=-1
+ULONG_MAX: ffffffff=-1
+CHAR_MAX: 0000007f=127
+SCHAR_MAX: 0000007f=127
+SHRT_MAX: 00007fff=32767
+INT_MAX: 7fffffff=2147483647
+LONG_MAX: 7fffffff=2147483647
+CHAR_MIN: ffffff80=-128
+SCHAR_MIN: ffffff80=-128
+SHRT_MIN: ffff8000=-32768
+INT_MIN: 80000000=-2147483648
+LONG_MIN: 80000000=-2147483648
diff --git a/lcc/sparc/solaris/tst/limits.2bk b/lcc/sparc/solaris/tst/limits.2bk
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/sparc/solaris/tst/limits.2bk
diff --git a/lcc/sparc/solaris/tst/limits.sbk b/lcc/sparc/solaris/tst/limits.sbk
new file mode 100755
index 0000000..c80d328
--- /dev/null
+++ b/lcc/sparc/solaris/tst/limits.sbk
@@ -0,0 +1,384 @@
+.global main
+.section ".text"
+.align 4
+main:
+save %sp,-96,%sp
+set .L2,%o0
+set 255,%i5
+mov %i5,%o1
+mov %i5,%o2
+call printf; nop
+set .L3,%o0
+set 65535,%i5
+mov %i5,%o1
+mov %i5,%o2
+call printf; nop
+set .L4,%o0
+set 0xffffffff,%i5
+mov %i5,%o1
+mov %i5,%o2
+call printf; nop
+set .L5,%o0
+set 0xffffffff,%i5
+mov %i5,%o1
+mov %i5,%o2
+call printf; nop
+set .L6,%o0
+set 127,%i5
+mov %i5,%o1
+mov %i5,%o2
+call printf; nop
+set .L7,%o0
+set 127,%i5
+mov %i5,%o1
+mov %i5,%o2
+call printf; nop
+set .L8,%o0
+set 32767,%i5
+mov %i5,%o1
+mov %i5,%o2
+call printf; nop
+set .L9,%o0
+set 2147483647,%i5
+mov %i5,%o1
+mov %i5,%o2
+call printf; nop
+set .L10,%o0
+set 2147483647,%i5
+mov %i5,%o1
+mov %i5,%o2
+call printf; nop
+set .L11,%o0
+set -128,%i5
+mov %i5,%o1
+mov %i5,%o2
+call printf; nop
+set .L12,%o0
+set -128,%i5
+mov %i5,%o1
+mov %i5,%o2
+call printf; nop
+set .L13,%o0
+set -32768,%i5
+mov %i5,%o1
+mov %i5,%o2
+call printf; nop
+set .L14,%o0
+set -2147483648,%i5
+mov %i5,%o1
+mov %i5,%o2
+call printf; nop
+set .L15,%o0
+set -2147483648,%i5
+mov %i5,%o1
+mov %i5,%o2
+call printf; nop
+mov %g0,%i0
+.L1:
+ret; restore
+.type main,#function
+.size main,.-main
+.section ".rodata"
+.align 1
+.L15:
+.byte 76
+.byte 79
+.byte 78
+.byte 71
+.byte 95
+.byte 77
+.byte 73
+.byte 78
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 108
+.byte 120
+.byte 61
+.byte 37
+.byte 108
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L14:
+.byte 73
+.byte 78
+.byte 84
+.byte 95
+.byte 77
+.byte 73
+.byte 78
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L13:
+.byte 83
+.byte 72
+.byte 82
+.byte 84
+.byte 95
+.byte 77
+.byte 73
+.byte 78
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L12:
+.byte 83
+.byte 67
+.byte 72
+.byte 65
+.byte 82
+.byte 95
+.byte 77
+.byte 73
+.byte 78
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L11:
+.byte 67
+.byte 72
+.byte 65
+.byte 82
+.byte 95
+.byte 77
+.byte 73
+.byte 78
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L10:
+.byte 76
+.byte 79
+.byte 78
+.byte 71
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 108
+.byte 120
+.byte 61
+.byte 37
+.byte 108
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L9:
+.byte 73
+.byte 78
+.byte 84
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L8:
+.byte 83
+.byte 72
+.byte 82
+.byte 84
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L7:
+.byte 83
+.byte 67
+.byte 72
+.byte 65
+.byte 82
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L6:
+.byte 67
+.byte 72
+.byte 65
+.byte 82
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L5:
+.byte 85
+.byte 76
+.byte 79
+.byte 78
+.byte 71
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 108
+.byte 120
+.byte 61
+.byte 37
+.byte 108
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L4:
+.byte 85
+.byte 73
+.byte 78
+.byte 84
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L3:
+.byte 85
+.byte 83
+.byte 72
+.byte 82
+.byte 84
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L2:
+.byte 85
+.byte 67
+.byte 72
+.byte 65
+.byte 82
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
diff --git a/lcc/sparc/solaris/tst/paranoia.1bk b/lcc/sparc/solaris/tst/paranoia.1bk
new file mode 100755
index 0000000..30c3470
--- /dev/null
+++ b/lcc/sparc/solaris/tst/paranoia.1bk
@@ -0,0 +1,178 @@
+Lest this program stop prematurely, i.e. before displaying
+
+ `END OF TEST',
+
+try to persuade the computer NOT to terminate execution when an
+error like Over/Underflow or Division by Zero occurs, but rather
+to persevere with a surrogate value after, perhaps, displaying some
+warning. If persuasion avails naught, don't despair but run this
+program anyway to see how many milestones it passes, and then
+amend it to make further progress.
+
+Answer questions with Y, y, N or n (unless otherwise indicated).
+
+
+Diagnosis resumes after milestone Number 0 Page: 1
+
+Users are invited to help debug and augment this program so it will
+cope with unanticipated and newly uncovered arithmetic pathologies.
+
+Please send suggestions and interesting results to
+ Richard Karpinski
+ Computer Center U-76
+ University of California
+ San Francisco, CA 94143-0704, USA
+
+In doing so, please include the following information:
+ Precision: double;
+ Version: 10 February 1989;
+ Computer:
+
+ Compiler:
+
+ Optimization level:
+
+ Other relevant compiler options:
+
+Diagnosis resumes after milestone Number 1 Page: 2
+
+Running this program should reveal these characteristics:
+ Radix = 1, 2, 4, 8, 10, 16, 100, 256 ...
+ Precision = number of significant digits carried.
+ U2 = Radix/Radix^Precision = One Ulp
+ (OneUlpnit in the Last Place) of 1.000xxx .
+ U1 = 1/Radix^Precision = One Ulp of numbers a little less than 1.0 .
+ Adequacy of guard digits for Mult., Div. and Subt.
+ Whether arithmetic is chopped, correctly rounded, or something else
+ for Mult., Div., Add/Subt. and Sqrt.
+ Whether a Sticky Bit used correctly for rounding.
+ UnderflowThreshold = an underflow threshold.
+ E0 and PseudoZero tell whether underflow is abrupt, gradual, or fuzzy.
+ V = an overflow threshold, roughly.
+ V0 tells, roughly, whether Infinity is represented.
+ Comparisions are checked for consistency with subtraction
+ and for contamination with pseudo-zeros.
+ Sqrt is tested. Y^X is not tested.
+ Extra-precise subexpressions are revealed but NOT YET tested.
+ Decimal-Binary conversion is NOT YET tested for accuracy.
+
+Diagnosis resumes after milestone Number 2 Page: 3
+
+The program attempts to discriminate among
+ FLAWs, like lack of a sticky bit,
+ Serious DEFECTs, like lack of a guard digit, and
+ FAILUREs, like 2+2 == 5 .
+Failures may confound subsequent diagnoses.
+
+The diagnostic capabilities of this program go beyond an earlier
+program called `MACHAR', which can be found at the end of the
+book `Software Manual for the Elementary Functions' (1980) by
+W. J. Cody and W. Waite. Although both programs try to discover
+the Radix, Precision and range (over/underflow thresholds)
+of the arithmetic, this program tries to cope with a wider variety
+of pathologies, and to say how well the arithmetic is implemented.
+
+The program is based upon a conventional radix representation for
+floating-point numbers, but also allows logarithmic encoding
+as used by certain early WANG machines.
+
+BASIC version of this program (C) 1983 by Prof. W. M. Kahan;
+see source comments for more history.
+
+Diagnosis resumes after milestone Number 3 Page: 4
+
+Program is now RUNNING tests on small integers:
+-1, 0, 1/2, 1, 2, 3, 4, 5, 9, 27, 32 & 240 are O.K.
+
+Searching for Radix and Precision.
+Radix = 2.000000 .
+Closest relative separation found is U1 = 1.1102230e-16 .
+
+Recalculating radix and precision
+ confirms closest relative separation U1 .
+Radix confirmed.
+The number of significant digits of the Radix is 53.000000 .
+
+Diagnosis resumes after milestone Number 30 Page: 5
+
+Subtraction appears to be normalized, as it should be.
+Checking for guard digit in *, /, and -.
+ *, /, and - appear to have guard digits, as they should.
+
+Diagnosis resumes after milestone Number 40 Page: 6
+
+Checking rounding on multiply, divide and add/subtract.
+Multiplication appears to round correctly.
+Division appears to round correctly.
+Addition/Subtraction appears to round correctly.
+Checking for sticky bit.
+Sticky bit apparently used correctly.
+
+Does Multiplication commute? Testing on 20 random pairs.
+ No failures found in 20 integer pairs.
+
+Running test of square root(x).
+Testing if sqrt(X * X) == X for 20 Integers X.
+Test for sqrt monotonicity.
+sqrt has passed a test for Monotonicity.
+Testing whether sqrt is rounded or chopped.
+Square root appears to be correctly rounded.
+
+Diagnosis resumes after milestone Number 90 Page: 7
+
+Testing powers Z^i for small Integers Z and i.
+... no discrepancis found.
+
+Seeking Underflow thresholds UfThold and E0.
+Smallest strictly positive number found is E0 = 4.94066e-324 .
+Since comparison denies Z = 0, evaluating (Z + Z) / Z should be safe.
+What the machine gets for (Z + Z) / Z is 2.00000000000000000e+00 .
+This is O.K., provided Over/Underflow has NOT just been signaled.
+Underflow is gradual; it incurs Absolute Error =
+(roundoff in UfThold) < E0.
+The Underflow threshold is 2.22507385850720188e-308, below which
+calculation may suffer larger Relative error than merely roundoff.
+Since underflow occurs below the threshold
+UfThold = (2.00000000000000000e+00) ^ (-1.02200000000000000e+03)
+only underflow should afflict the expression
+ (2.00000000000000000e+00) ^ (-1.02200000000000000e+03);
+actually calculating yields: 0.00000000000000000e+00 .
+This computed value is O.K.
+
+Testing X^((X + 1) / (X - 1)) vs. exp(2) = 7.38905609893065218e+00 as X -> 1.
+Accuracy seems adequate.
+Testing powers Z^Q at four nearly extreme values.
+ ... no discrepancies found.
+
+
+Diagnosis resumes after milestone Number 160 Page: 8
+
+Searching for Overflow threshold:
+This may generate an error.
+Can `Z = -Y' overflow?
+Trying it on Y = -Infinity .
+Seems O.K.
+Overflow threshold is V = 1.79769313486231571e+308 .
+Overflow saturates at V0 = Infinity .
+No Overflow should be signaled for V * 1 = 1.79769313486231571e+308
+ nor for V / 1 = 1.79769313486231571e+308 .
+Any overflow signal separating this * from the one
+above is a DEFECT.
+
+
+Diagnosis resumes after milestone Number 190 Page: 9
+
+
+What message and/or values does Division by Zero produce?
+ Trying to compute 1 / 0 produces ... Infinity .
+
+ Trying to compute 0 / 0 produces ... NaN .
+
+Diagnosis resumes after milestone Number 220 Page: 10
+
+
+
+No failures, defects nor flaws have been discovered.
+Rounding appears to conform to the proposed IEEE standard P754.
+The arithmetic diagnosed appears to be Excellent!
+END OF TEST.
diff --git a/lcc/sparc/solaris/tst/paranoia.2bk b/lcc/sparc/solaris/tst/paranoia.2bk
new file mode 100755
index 0000000..f6ddf16
--- /dev/null
+++ b/lcc/sparc/solaris/tst/paranoia.2bk
@@ -0,0 +1,16 @@
+tst/paranoia.c:1867: warning: missing return value
+tst/paranoia.c:1874: warning: missing return value
+tst/paranoia.c:1884: warning: missing return value
+tst/paranoia.c:1924: warning: missing return value
+tst/paranoia.c:1939: warning: missing return value
+tst/paranoia.c:1956: warning: missing return value
+tst/paranoia.c:1975: warning: missing return value
+tst/paranoia.c:1988: warning: missing return value
+tst/paranoia.c:1995: warning: missing return value
+tst/paranoia.c:2055: warning: missing return value
+tst/paranoia.c:2062: warning: missing return value
+tst/paranoia.c:2070: warning: missing return value
+tst/paranoia.c:2087: warning: missing return value
+tst/paranoia.c:2115: warning: missing return value
+tst/paranoia.c:2144: warning: missing return value
+tst/paranoia.c:2173: warning: missing return value
diff --git a/lcc/sparc/solaris/tst/paranoia.sbk b/lcc/sparc/solaris/tst/paranoia.sbk
new file mode 100755
index 0000000..e455699
--- /dev/null
+++ b/lcc/sparc/solaris/tst/paranoia.sbk
@@ -0,0 +1,21068 @@
+.section ".data"
+.global Zero
+.type Zero,#object
+.size Zero,8
+.align 8
+Zero:
+.word 0x0
+.word 0x0
+.global Half
+.type Half,#object
+.size Half,8
+.align 8
+Half:
+.word 0x3fe00000
+.word 0x0
+.global One
+.type One,#object
+.size One,8
+.align 8
+One:
+.word 0x3ff00000
+.word 0x0
+.global Two
+.type Two,#object
+.size Two,8
+.align 8
+Two:
+.word 0x40000000
+.word 0x0
+.global Three
+.type Three,#object
+.size Three,8
+.align 8
+Three:
+.word 0x40080000
+.word 0x0
+.global Four
+.type Four,#object
+.size Four,8
+.align 8
+Four:
+.word 0x40100000
+.word 0x0
+.global Five
+.type Five,#object
+.size Five,8
+.align 8
+Five:
+.word 0x40140000
+.word 0x0
+.global Eight
+.type Eight,#object
+.size Eight,8
+.align 8
+Eight:
+.word 0x40200000
+.word 0x0
+.global Nine
+.type Nine,#object
+.size Nine,8
+.align 8
+Nine:
+.word 0x40220000
+.word 0x0
+.global TwentySeven
+.type TwentySeven,#object
+.size TwentySeven,8
+.align 8
+TwentySeven:
+.word 0x403b0000
+.word 0x0
+.global ThirtyTwo
+.type ThirtyTwo,#object
+.size ThirtyTwo,8
+.align 8
+ThirtyTwo:
+.word 0x40400000
+.word 0x0
+.global TwoForty
+.type TwoForty,#object
+.size TwoForty,8
+.align 8
+TwoForty:
+.word 0x406e0000
+.word 0x0
+.global MinusOne
+.type MinusOne,#object
+.size MinusOne,8
+.align 8
+MinusOne:
+.word 0xbff00000
+.word 0x0
+.global OneAndHalf
+.type OneAndHalf,#object
+.size OneAndHalf,8
+.align 8
+OneAndHalf:
+.word 0x3ff80000
+.word 0x0
+.global NoTrials
+.type NoTrials,#object
+.size NoTrials,4
+.align 4
+NoTrials:
+.word 0x14
+.global sigfpe
+.section ".text"
+.align 4
+sigfpe:
+save %sp,-96,%sp
+set fpecount,%i5
+ld [%i5],%i4
+add %i4,1,%i4
+st %i4,[%i5]
+set .L3,%o0
+call printf; nop
+set __iob+16,%o0
+call fflush; nop
+set sigsave,%i5
+ld [%i5],%i5
+cmp %i5,%g0; be .L5; nop
+set 8,%o0
+set sigsave,%i5
+ld [%i5],%o1
+call signal; nop
+set sigsave,%i5
+st %g0,[%i5]
+set ovfl_buf,%o0
+set 1,%o1
+call longjmp; nop
+.L5:
+call abort; nop
+.L2:
+ret; restore
+.type sigfpe,#function
+.size sigfpe,.-sigfpe
+.section ".data"
+.type .758,#object
+.align 4
+.758:
+.word .L759
+.word .L760
+.word .L761
+.word .L762
+.size .758,16
+.global main
+.section ".text"
+.align 4
+main:
+save %sp,-216,%sp
+set Zero,%i5
+set .L8,%i4
+ld2 [%i4],%f30
+st2 %f30,[%i5]
+set One,%i5
+set .L9,%i4
+ld2 [%i4],%f30
+st2 %f30,[%i5]
+set Two,%i4
+ld2 [%i5],%f30
+faddd %f30,%f30,%f28
+st2 %f28,[%i4]
+set Three,%i5
+ld2 [%i4],%f28
+faddd %f28,%f30,%f26
+st2 %f26,[%i5]
+set Four,%i4
+ld2 [%i5],%f26
+faddd %f26,%f30,%f24
+st2 %f24,[%i4]
+set Five,%i5
+ld2 [%i4],%f24
+faddd %f24,%f30,%f22
+st2 %f22,[%i5]
+set Eight,%i4
+faddd %f24,%f24,%f22
+st2 %f22,[%i4]
+set Nine,%i3
+fmuld %f26,%f26,%f22
+st2 %f22,[%i3]
+set TwentySeven,%i2
+ld2 [%i3],%f22
+fmuld %f22,%f26,%f22
+st2 %f22,[%i2]
+set ThirtyTwo,%i3
+ld2 [%i4],%f22
+fmuld %f24,%f22,%f22
+st2 %f22,[%i3]
+set TwoForty,%i4
+ld2 [%i5],%f22
+fmuld %f24,%f22,%f22
+fmuld %f22,%f26,%f26
+fmuld %f26,%f24,%f26
+st2 %f26,[%i4]
+set MinusOne,%i5
+fnegs %f30,%f26; fmovs %f31,%f27
+st2 %f26,[%i5]
+set Half,%i5
+fdivd %f30,%f28,%f28
+st2 %f28,[%i5]
+set OneAndHalf,%i4
+ld2 [%i5],%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%i4]
+set ErrCnt,%i4
+st %g0,[%i4]
+set ErrCnt+4,%i4
+st %g0,[%i4]
+set ErrCnt+8,%i5
+st %g0,[%i5]
+set ErrCnt+12,%i5
+st %g0,[%i5]
+set PageNo,%i5
+set 1,%i4
+st %i4,[%i5]
+set Milestone,%i5
+st %g0,[%i5]
+set 8,%o0
+set sigfpe,%o1
+call signal; nop
+call Instructions; nop
+call Pause; nop
+call Heading; nop
+call Pause; nop
+call Characteristics; nop
+call Pause; nop
+call History; nop
+call Pause; nop
+set Milestone,%i5
+set 7,%i4
+st %i4,[%i5]
+set .L13,%o0
+call printf; nop
+mov %g0,%o0
+set Zero,%i4
+ld2 [%i4],%f30
+faddd %f30,%f30,%f28
+fcmped %f28,%f30; nop; fbne .L16; nop
+set One,%i4
+ld2 [%i4],%f28
+fsubd %f28,%f28,%f26
+fcmped %f26,%f30; nop; fbne .L16; nop
+fcmped %f28,%f30; nop; fbule .L16; nop
+faddd %f28,%f28,%f30
+set Two,%i4
+ld2 [%i4],%f28
+fcmped %f30,%f28; nop; fbne .L16; nop
+set 1,%i5
+ba .L17; nop
+.L16:
+mov %g0,%i5
+.L17:
+mov %i5,%o1
+set .L15,%o2
+call TstCond; nop
+set Z,%i4
+set Zero,%i3
+ld2 [%i3],%f30
+fnegs %f30,%f30; fmovs %f31,%f31
+st2 %f30,[%i4]
+ld2 [%i4],%f30
+set .L8,%i4
+ld2 [%i4],%f28
+fcmped %f30,%f28; nop; fbue .L18; nop
+set ErrCnt,%i4
+ld [%i4],%i3
+add %i3,1,%i3
+st %i3,[%i4]
+set .L20,%o0
+call printf; nop
+set U1,%i4
+set .L21,%i3
+ld2 [%i3],%f30
+st2 %f30,[%i4]
+set Radix,%i4
+set .L9,%i3
+ld2 [%i3],%f30
+st2 %f30,[%i4]
+call TstPtUf; nop
+.L18:
+mov %g0,%o0
+set Three,%i3
+ld2 [%i3],%f30
+set Two,%i3
+ld2 [%i3],%f28
+set One,%i3
+ld2 [%i3],%f26
+faddd %f28,%f26,%f24
+fcmped %f30,%f24; nop; fbne .L24; nop
+set Four,%i3
+ld2 [%i3],%f24
+faddd %f30,%f26,%f22
+fcmped %f24,%f22; nop; fbne .L24; nop
+set Zero,%i3
+ld2 [%i3],%f22
+fnegs %f28,%f20; fmovs %f29,%f21
+fmuld %f28,%f20,%f28
+faddd %f24,%f28,%f28
+fcmped %f28,%f22; nop; fbne .L24; nop
+fsubd %f24,%f30,%f30
+fsubd %f30,%f26,%f30
+fcmped %f30,%f22; nop; fbne .L24; nop
+set 1,%i4
+ba .L25; nop
+.L24:
+mov %g0,%i4
+.L25:
+mov %i4,%o1
+set .L23,%o2
+call TstCond; nop
+set MinusOne,%i2
+ld2 [%i2],%f30
+std %f30,[%fp+-8]
+set One,%i2
+ld2 [%i2],%f28
+set .L8,%i2
+ld2 [%i2],%f26
+fsubd %f26,%f28,%f26
+fcmped %f30,%f26; nop; fbne .L28; nop
+set Zero,%i2
+ld2 [%i2],%f26
+faddd %f30,%f28,%f24
+fcmped %f24,%f26; nop; fbne .L28; nop
+faddd %f28,%f30,%f24
+fcmped %f24,%f26; nop; fbne .L28; nop
+st %f28,[%sp+4*0+68]
+st %f29,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call fabs; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Zero,%i2
+ld2 [%i2],%f28
+ldd [%fp+-8],%f26
+faddd %f26,%f30,%f30
+fcmped %f30,%f28; nop; fbne .L28; nop
+set MinusOne,%i2
+ld2 [%i2],%f30
+fmuld %f30,%f30,%f26
+faddd %f30,%f26,%f30
+fcmped %f30,%f28; nop; fbne .L28; nop
+set 1,%i3
+ba .L29; nop
+.L28:
+mov %g0,%i3
+.L29:
+mov %g0,%o0
+mov %i3,%o1
+set .L27,%o2
+call TstCond; nop
+mov %g0,%o0
+set Half,%i1
+ld2 [%i1],%f30
+set MinusOne,%i1
+ld2 [%i1],%f28
+faddd %f30,%f28,%f28
+faddd %f28,%f30,%f30
+set Zero,%i1
+ld2 [%i1],%f28
+fcmped %f30,%f28; nop; fbne .L32; nop
+set 1,%i2
+ba .L33; nop
+.L32:
+mov %g0,%i2
+.L33:
+mov %i2,%o1
+set .L31,%o2
+call TstCond; nop
+set Milestone,%i0
+set 10,%l7
+st %l7,[%i0]
+mov %g0,%o0
+set Nine,%i0
+ld2 [%i0],%f30
+set Three,%i0
+ld2 [%i0],%f28
+fmuld %f28,%f28,%f26
+fcmped %f30,%f26; nop; fbne .L36; nop
+set TwentySeven,%i0
+ld2 [%i0],%f26
+fmuld %f30,%f28,%f30
+fcmped %f26,%f30; nop; fbne .L36; nop
+set Eight,%i0
+ld2 [%i0],%f30
+set Four,%i0
+ld2 [%i0],%f28
+faddd %f28,%f28,%f24
+fcmped %f30,%f24; nop; fbne .L36; nop
+set ThirtyTwo,%i0
+ld2 [%i0],%f24
+fmuld %f30,%f28,%f30
+fcmped %f24,%f30; nop; fbne .L36; nop
+fsubd %f24,%f26,%f30
+fsubd %f30,%f28,%f30
+set One,%i0
+ld2 [%i0],%f28
+fsubd %f30,%f28,%f30
+set Zero,%i0
+ld2 [%i0],%f28
+fcmped %f30,%f28; nop; fbne .L36; nop
+set 1,%i1
+ba .L37; nop
+.L36:
+mov %g0,%i1
+.L37:
+mov %i1,%o1
+set .L35,%o2
+call TstCond; nop
+mov %g0,%o0
+set Five,%l7
+ld2 [%l7],%f30
+set Four,%l7
+ld2 [%l7],%f28
+set One,%l7
+ld2 [%l7],%f26
+faddd %f28,%f26,%f26
+fcmped %f30,%f26; nop; fbne .L40; nop
+set TwoForty,%l7
+ld2 [%l7],%f26
+set Three,%l7
+ld2 [%l7],%f24
+fmuld %f28,%f30,%f22
+fmuld %f22,%f24,%f22
+fmuld %f22,%f28,%f22
+fcmped %f26,%f22; nop; fbne .L40; nop
+set Zero,%l7
+ld2 [%l7],%f22
+fdivd %f26,%f24,%f20
+fmuld %f28,%f28,%f18
+fmuld %f18,%f30,%f18
+fsubd %f20,%f18,%f20
+fcmped %f20,%f22; nop; fbne .L40; nop
+fdivd %f26,%f28,%f20
+fmuld %f30,%f24,%f18
+fmuld %f18,%f28,%f18
+fsubd %f20,%f18,%f20
+fcmped %f20,%f22; nop; fbne .L40; nop
+fdivd %f26,%f30,%f30
+fmuld %f28,%f24,%f26
+fmuld %f26,%f28,%f28
+fsubd %f30,%f28,%f30
+fcmped %f30,%f22; nop; fbne .L40; nop
+set 1,%i0
+ba .L41; nop
+.L40:
+mov %g0,%i0
+.L41:
+mov %i0,%o1
+set .L39,%o2
+call TstCond; nop
+set ErrCnt,%l7
+ld [%l7],%l7
+cmp %l7,0; bne .L42; nop
+set .L44,%o0
+call printf; nop
+set .L45,%o0
+call printf; nop
+.L42:
+set .L46,%o0
+call printf; nop
+set W,%l7
+set One,%l6
+ld2 [%l6],%f30
+st2 %f30,[%l7]
+.L47:
+set W,%l7
+ld2 [%l7],%f30
+faddd %f30,%f30,%f30
+st2 %f30,[%l7]
+set Y,%l6
+ld2 [%l7],%f30
+set One,%l7
+ld2 [%l7],%f28
+faddd %f30,%f28,%f26
+st2 %f26,[%l6]
+set Z,%l7
+ld2 [%l6],%f26
+fsubd %f26,%f30,%f30
+st2 %f30,[%l7]
+ld2 [%l7],%f30
+fsubd %f30,%f28,%f30
+st2 %f30,[%l6]
+.L48:
+set Y,%l7
+ld2 [%l7],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call fabs; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set MinusOne,%l7
+ld2 [%l7],%f28
+faddd %f28,%f30,%f30
+set Zero,%l7
+ld2 [%l7],%f28
+fcmped %f30,%f28; nop; fbul .L47; nop
+set Precision,%l7
+set Zero,%l6
+ld2 [%l6],%f30
+st2 %f30,[%l7]
+set Y,%l7
+set One,%l6
+ld2 [%l6],%f30
+st2 %f30,[%l7]
+.L50:
+set Radix,%l7
+set W,%l6
+ld2 [%l6],%f30
+set Y,%l6
+ld2 [%l6],%f28
+faddd %f30,%f28,%f26
+st2 %f26,[%l7]
+faddd %f28,%f28,%f28
+st2 %f28,[%l6]
+ld2 [%l7],%f28
+fsubd %f28,%f30,%f30
+st2 %f30,[%l7]
+.L51:
+set Radix,%l7
+ld2 [%l7],%f30
+set Zero,%l7
+ld2 [%l7],%f28
+fcmped %f30,%f28; nop; fbue .L50; nop
+set Radix,%l7
+ld2 [%l7],%f30
+set Two,%l7
+ld2 [%l7],%f28
+fcmped %f30,%f28; nop; fbuge .L53; nop
+set Radix,%l7
+set One,%l6
+ld2 [%l6],%f30
+st2 %f30,[%l7]
+.L53:
+set .L55,%o0
+set Radix,%l7
+ld2 [%l7],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set Radix,%l7
+ld2 [%l7],%f30
+set .L9,%l7
+ld2 [%l7],%f28
+fcmped %f30,%f28; nop; fbue .L56; nop
+set W,%l7
+set One,%l6
+ld2 [%l6],%f30
+st2 %f30,[%l7]
+.L58:
+set Precision,%l7
+set One,%l6
+ld2 [%l6],%f30
+ld2 [%l7],%f28
+faddd %f28,%f30,%f28
+st2 %f28,[%l7]
+set W,%l7
+ld2 [%l7],%f28
+set Radix,%l6
+ld2 [%l6],%f26
+fmuld %f28,%f26,%f28
+st2 %f28,[%l7]
+set Y,%l6
+ld2 [%l7],%f28
+faddd %f28,%f30,%f30
+st2 %f30,[%l6]
+.L59:
+set Y,%l7
+ld2 [%l7],%f30
+set W,%l7
+ld2 [%l7],%f28
+fsubd %f30,%f28,%f30
+set One,%l7
+ld2 [%l7],%f28
+fcmped %f30,%f28; nop; fbue .L58; nop
+.L56:
+set U1,%l7
+set One,%l6
+ld2 [%l6],%f30
+set W,%l6
+ld2 [%l6],%f28
+fdivd %f30,%f28,%f30
+st2 %f30,[%l7]
+ld2 [%l7],%f30
+set U2,%l7
+set Radix,%l6
+ld2 [%l6],%f28
+fmuld %f28,%f30,%f28
+st2 %f28,[%l7]
+set .L61,%o0
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set .L62,%o0
+call printf; nop
+set E0,%l7
+set Radix,%l6
+ld2 [%l6],%f30
+st2 %f30,[%l7]
+set E1,%l7
+set U1,%l6
+ld2 [%l6],%f30
+st2 %f30,[%l7]
+set E9,%l7
+set U2,%l6
+ld2 [%l6],%f30
+st2 %f30,[%l7]
+set E3,%l7
+set Precision,%l6
+ld2 [%l6],%f30
+st2 %f30,[%l7]
+set X,%l7
+set Four,%l6
+ld2 [%l6],%f30
+set Three,%l6
+ld2 [%l6],%f28
+fdivd %f30,%f28,%f30
+st2 %f30,[%l7]
+set Third,%l6
+ld2 [%l7],%f30
+set One,%l5
+ld2 [%l5],%f28
+fsubd %f30,%f28,%f30
+st2 %f30,[%l6]
+set F6,%l5
+ld2 [%l6],%f30
+set Half,%l6
+ld2 [%l6],%f28
+fsubd %f28,%f30,%f28
+st2 %f28,[%l5]
+ld2 [%l5],%f28
+faddd %f28,%f28,%f28
+st2 %f28,[%l7]
+ld2 [%l7],%f28
+fsubd %f28,%f30,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call fabs; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+st2 %f30,[%l7]
+set X,%l7
+ld2 [%l7],%f30
+set U2,%l7
+ld2 [%l7],%f28
+fcmped %f30,%f28; nop; fbuge .L63; nop
+set X,%l7
+set U2,%l6
+ld2 [%l6],%f30
+st2 %f30,[%l7]
+.L63:
+.L65:
+set U2,%l7
+set X,%l6
+ld2 [%l6],%f30
+st2 %f30,[%l7]
+set Y,%l5
+ld2 [%l7],%f30
+set Half,%l7
+ld2 [%l7],%f28
+fmuld %f28,%f30,%f28
+set ThirtyTwo,%l7
+ld2 [%l7],%f26
+fmuld %f26,%f30,%f26
+fmuld %f26,%f30,%f30
+faddd %f28,%f30,%f30
+st2 %f30,[%l5]
+set One,%l7
+ld2 [%l7],%f30
+ld2 [%l5],%f28
+faddd %f30,%f28,%f28
+st2 %f28,[%l5]
+ld2 [%l5],%f28
+fsubd %f28,%f30,%f30
+st2 %f30,[%l6]
+.L66:
+set X,%l7
+ld2 [%l7],%f30
+set U2,%l7
+ld2 [%l7],%f28
+fcmped %f28,%f30; nop; fbule .L68; nop
+set Zero,%l7
+ld2 [%l7],%f28
+fcmped %f30,%f28; nop; fbug .L65; nop
+.L68:
+set X,%l7
+set Two,%l6
+ld2 [%l6],%f30
+set Three,%l6
+ld2 [%l6],%f28
+fdivd %f30,%f28,%f30
+st2 %f30,[%l7]
+set F6,%l6
+set Half,%l5
+ld2 [%l5],%f30
+ld2 [%l7],%f28
+fsubd %f28,%f30,%f28
+st2 %f28,[%l6]
+set Third,%l5
+ld2 [%l6],%f28
+faddd %f28,%f28,%f26
+st2 %f26,[%l5]
+ld2 [%l5],%f26
+fsubd %f26,%f30,%f30
+st2 %f30,[%l7]
+ld2 [%l7],%f30
+faddd %f30,%f28,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call fabs; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+st2 %f30,[%l7]
+set X,%l7
+ld2 [%l7],%f30
+set U1,%l7
+ld2 [%l7],%f28
+fcmped %f30,%f28; nop; fbuge .L69; nop
+set X,%l7
+set U1,%l6
+ld2 [%l6],%f30
+st2 %f30,[%l7]
+.L69:
+.L71:
+set U1,%l7
+set X,%l6
+ld2 [%l6],%f30
+st2 %f30,[%l7]
+set Y,%l5
+set Half,%l4
+ld2 [%l4],%f30
+ld2 [%l7],%f28
+fmuld %f30,%f28,%f26
+set ThirtyTwo,%l7
+ld2 [%l7],%f24
+fmuld %f24,%f28,%f24
+fmuld %f24,%f28,%f28
+faddd %f26,%f28,%f28
+st2 %f28,[%l5]
+ld2 [%l5],%f28
+fsubd %f30,%f28,%f28
+st2 %f28,[%l5]
+ld2 [%l5],%f28
+faddd %f30,%f28,%f28
+st2 %f28,[%l6]
+ld2 [%l6],%f28
+fsubd %f30,%f28,%f28
+st2 %f28,[%l5]
+ld2 [%l5],%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l6]
+.L72:
+set X,%l7
+ld2 [%l7],%f30
+set U1,%l7
+ld2 [%l7],%f28
+fcmped %f28,%f30; nop; fbule .L74; nop
+set Zero,%l7
+ld2 [%l7],%f28
+fcmped %f30,%f28; nop; fbug .L71; nop
+.L74:
+set U1,%l7
+ld2 [%l7],%f30
+set E1,%l7
+ld2 [%l7],%f28
+fcmped %f30,%f28; nop; fbne .L75; nop
+set .L77,%o0
+call printf; nop
+ba .L76; nop
+.L75:
+set .L78,%o0
+set U1,%l7
+ld2 [%l7],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+.L76:
+set U1,%l7
+ld2 [%l7],%f30
+set W,%l7
+set One,%l6
+ld2 [%l6],%f28
+fdivd %f28,%f30,%f28
+st2 %f28,[%l7]
+set Half,%l7
+ld2 [%l7],%f28
+set F9,%l7
+fsubd %f28,%f30,%f26
+faddd %f26,%f28,%f28
+st2 %f28,[%l7]
+set U2,%l7
+ld2 [%l7],%f28
+fdivd %f28,%f30,%f30
+set .L79,%l7
+ld2 [%l7],%f28
+faddd %f30,%f28,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call floor; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Radix,%l7
+st2 %f30,[%l7]
+set Radix,%l7
+ld2 [%l7],%f30
+set E0,%l7
+ld2 [%l7],%f28
+fcmped %f30,%f28; nop; fbne .L80; nop
+set .L82,%o0
+call printf; nop
+ba .L81; nop
+.L80:
+set .L83,%o0
+set Radix,%l7
+ld2 [%l7],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+.L81:
+set 2,%o0
+set Eight,%l6
+ld2 [%l6],%f30
+set Radix,%l6
+ld2 [%l6],%f28
+faddd %f30,%f30,%f30
+fcmped %f28,%f30; nop; fbug .L86; nop
+set 1,%l7
+ba .L87; nop
+.L86:
+mov %g0,%l7
+.L87:
+mov %l7,%o1
+set .L85,%o2
+call TstCond; nop
+set 3,%o0
+set Radix,%l5
+ld2 [%l5],%f30
+set Two,%l5
+ld2 [%l5],%f28
+fcmped %f30,%f28; nop; fbue .L93; nop
+set .L94,%l5
+ld2 [%l5],%f28
+fcmped %f30,%f28; nop; fbue .L93; nop
+set One,%l5
+ld2 [%l5],%f28
+fcmped %f30,%f28; nop; fbne .L90; nop
+.L93:
+set 1,%l6
+ba .L91; nop
+.L90:
+mov %g0,%l6
+.L91:
+mov %l6,%o1
+set .L89,%o2
+call TstCond; nop
+set Milestone,%l4
+set 20,%l3
+st %l3,[%l4]
+mov %g0,%o0
+set Half,%l4
+ld2 [%l4],%f30
+set F9,%l4
+ld2 [%l4],%f28
+fsubd %f28,%f30,%f28
+fcmped %f28,%f30; nop; fbuge .L97; nop
+set 1,%l5
+ba .L98; nop
+.L97:
+mov %g0,%l5
+.L98:
+mov %l5,%o1
+set .L96,%o2
+call TstCond; nop
+set X,%l3
+set F9,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set I,%l2
+set 1,%l1
+st %l1,[%l2]
+set Y,%l2
+set Half,%l1
+ld2 [%l1],%f30
+ld2 [%l3],%f28
+fsubd %f28,%f30,%f28
+st2 %f28,[%l2]
+set Z,%l3
+ld2 [%l2],%f28
+fsubd %f28,%f30,%f30
+st2 %f30,[%l3]
+mov %g0,%o0
+set X,%l3
+ld2 [%l3],%f30
+set One,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L103; nop
+set Z,%l3
+ld2 [%l3],%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L101; nop
+.L103:
+set 1,%l4
+ba .L102; nop
+.L101:
+mov %g0,%l4
+.L102:
+mov %l4,%o1
+set .L100,%o2
+call TstCond; nop
+set One,%l3
+ld2 [%l3],%f30
+set U2,%l3
+ld2 [%l3],%f28
+set X,%l3
+faddd %f30,%f28,%f26
+st2 %f26,[%l3]
+set I,%l3
+st %g0,[%l3]
+set Milestone,%l3
+set 25,%l2
+st %l2,[%l3]
+set BMinusU2,%l3
+set Radix,%l2
+ld2 [%l2],%f26
+fsubd %f26,%f30,%f24
+st2 %f24,[%l3]
+ld2 [%l3],%f24
+fsubd %f24,%f28,%f28
+faddd %f28,%f30,%f28
+st2 %f28,[%l3]
+fcmped %f26,%f30; nop; fbue .L104; nop
+set U1,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call log; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+std %f30,[%fp+-16]
+set Radix,%l3
+ld2 [%l3],%f28
+st %f28,[%sp+4*0+68]
+st %f29,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call log; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set X,%l3
+set TwoForty,%l2
+ld2 [%l2],%f28
+fnegs %f28,%f28; fmovs %f29,%f29
+ldd [%fp+-16],%f26
+fmuld %f28,%f26,%f28
+fdivd %f28,%f30,%f30
+st2 %f30,[%l3]
+set Half,%l3
+ld2 [%l3],%f30
+set X,%l3
+ld2 [%l3],%f28
+faddd %f30,%f28,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call floor; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Y,%l3
+st2 %f30,[%l3]
+set X,%l3
+ld2 [%l3],%f30
+set Y,%l3
+ld2 [%l3],%f28
+fsubd %f30,%f28,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call fabs; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Four,%l3
+ld2 [%l3],%f28
+fmuld %f30,%f28,%f30
+set One,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbuge .L106; nop
+set X,%l3
+set Y,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L106:
+set Precision,%l3
+set X,%l2
+ld2 [%l2],%f30
+set TwoForty,%l2
+ld2 [%l2],%f28
+fdivd %f30,%f28,%f30
+st2 %f30,[%l3]
+set Half,%l2
+ld2 [%l2],%f30
+ld2 [%l3],%f28
+faddd %f30,%f28,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call floor; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Y,%l3
+st2 %f30,[%l3]
+set Precision,%l3
+ld2 [%l3],%f30
+set Y,%l3
+ld2 [%l3],%f28
+fsubd %f30,%f28,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call fabs; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set TwoForty,%l3
+ld2 [%l3],%f28
+fmuld %f30,%f28,%f30
+set Half,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbuge .L108; nop
+set Precision,%l3
+set Y,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L108:
+.L104:
+set Precision,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-16]
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call floor; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+ldd [%fp+-16],%f28
+fcmped %f28,%f30; nop; fbne .L112; nop
+set Radix,%l3
+ld2 [%l3],%f30
+set One,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L110; nop
+.L112:
+set .L113,%o0
+call printf; nop
+set .L114,%o0
+call printf; nop
+.L110:
+set Radix,%l3
+ld2 [%l3],%f30
+set One,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L115; nop
+set .L117,%o0
+call printf; nop
+ba .L116; nop
+.L115:
+set .L118,%o0
+set Precision,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+.L116:
+set 1,%o0
+set Nine,%l3
+ld2 [%l3],%f30
+set U2,%l3
+ld2 [%l3],%f28
+fmuld %f28,%f30,%f28
+fmuld %f28,%f30,%f30
+set TwoForty,%l3
+ld2 [%l3],%f28
+fmuld %f30,%f28,%f30
+set One,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbuge .L121; nop
+set 1,%l3
+st %l3,[%fp+-20]
+ba .L122; nop
+.L121:
+st %g0,[%fp+-20]
+.L122:
+ld [%fp+-20],%o1
+set .L120,%o2
+call TstCond; nop
+set Milestone,%l3
+set 30,%l2
+st %l2,[%l3]
+set Four,%l3
+ld2 [%l3],%f30
+set Three,%l3
+ld2 [%l3],%f28
+set One,%l3
+ld2 [%l3],%f26
+fdivd %f26,%f30,%f24
+fdivd %f30,%f28,%f30
+fsubd %f30,%f26,%f30
+fsubd %f30,%f24,%f30
+fmuld %f30,%f28,%f30
+fsubd %f30,%f24,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call fabs; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set X,%l3
+st2 %f30,[%l3]
+.L123:
+set Z2,%l3
+set X,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set One,%l1
+ld2 [%l1],%f30
+ld2 [%l3],%f28
+set Half,%l3
+ld2 [%l3],%f26
+fmuld %f26,%f28,%f26
+set ThirtyTwo,%l3
+ld2 [%l3],%f24
+fmuld %f24,%f28,%f24
+fmuld %f24,%f28,%f28
+faddd %f26,%f28,%f28
+faddd %f30,%f28,%f28
+fsubd %f28,%f30,%f30
+st2 %f30,[%l2]
+.L124:
+set X,%l3
+ld2 [%l3],%f30
+set Z2,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbule .L126; nop
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbug .L123; nop
+.L126:
+set Three,%l3
+ld2 [%l3],%f30
+set Four,%l3
+ld2 [%l3],%f28
+fdivd %f30,%f28,%f26
+set Two,%l3
+ld2 [%l3],%f24
+fdivd %f24,%f30,%f24
+fsubd %f26,%f24,%f26
+fmuld %f26,%f30,%f30
+set One,%l3
+ld2 [%l3],%f26
+fdivd %f26,%f28,%f28
+fsubd %f30,%f28,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call fabs; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Z,%l3
+st2 %f30,[%l3]
+set Y,%l3
+st2 %f30,[%l3]
+set X,%l3
+st2 %f30,[%l3]
+.L127:
+set Z1,%l3
+set Z,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set One,%l1
+ld2 [%l1],%f30
+set Two,%l1
+ld2 [%l1],%f28
+fdivd %f30,%f28,%f30
+ld2 [%l3],%f28
+set Half,%l3
+ld2 [%l3],%f26
+fmuld %f26,%f28,%f26
+set ThirtyTwo,%l3
+ld2 [%l3],%f24
+fmuld %f24,%f28,%f24
+fmuld %f24,%f28,%f28
+faddd %f26,%f28,%f28
+fsubd %f30,%f28,%f28
+faddd %f28,%f30,%f28
+fsubd %f30,%f28,%f28
+faddd %f28,%f30,%f30
+st2 %f30,[%l2]
+.L128:
+set Z,%l3
+ld2 [%l3],%f30
+set Z1,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbule .L130; nop
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbug .L127; nop
+.L130:
+.L131:
+.L134:
+set Y1,%l3
+set Y,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set Half,%l1
+ld2 [%l1],%f30
+ld2 [%l3],%f28
+fmuld %f30,%f28,%f26
+set ThirtyTwo,%l3
+ld2 [%l3],%f24
+fmuld %f24,%f28,%f24
+fmuld %f24,%f28,%f28
+faddd %f26,%f28,%f28
+fsubd %f30,%f28,%f28
+faddd %f28,%f30,%f28
+fsubd %f30,%f28,%f28
+faddd %f28,%f30,%f30
+st2 %f30,[%l2]
+.L135:
+set Y,%l3
+ld2 [%l3],%f30
+set Y1,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbule .L137; nop
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbug .L134; nop
+.L137:
+set X1,%l3
+set X,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+ld2 [%l3],%f30
+set F9,%l3
+ld2 [%l3],%f28
+set Half,%l3
+ld2 [%l3],%f26
+fmuld %f26,%f30,%f26
+set ThirtyTwo,%l3
+ld2 [%l3],%f24
+fmuld %f24,%f30,%f24
+fmuld %f24,%f30,%f30
+faddd %f26,%f30,%f30
+fsubd %f30,%f28,%f30
+faddd %f30,%f28,%f30
+st2 %f30,[%l2]
+.L132:
+set X,%l3
+ld2 [%l3],%f30
+set X1,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbule .L138; nop
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbug .L131; nop
+.L138:
+set X1,%l3
+ld2 [%l3],%f30
+set Y1,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L141; nop
+set Z1,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L139; nop
+.L141:
+set 1,%o0
+set .L142,%o1
+call BadCond; nop
+set .L143,%o0
+set X1,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+set Y1,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*3+68]
+st %f31,[%sp+4*4+68]
+ld [%sp+4*3+68],%o3
+ld [%sp+4*4+68],%o4
+set Z1,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*5+68]
+st %f31,[%sp+4*6+68]
+ld [%sp+4*5+68],%o5
+call printf; nop
+set .L144,%o0
+call printf; nop
+set .L145,%o0
+call printf; nop
+set .L146,%o0
+call notify; nop
+set U1,%l3
+ld2 [%l3],%f30
+set X1,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbue .L150; nop
+set Y1,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbue .L150; nop
+set Z1,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L140; nop
+.L150:
+set .L151,%o0
+call printf; nop
+ba .L140; nop
+.L139:
+set Z1,%l3
+ld2 [%l3],%f30
+set U1,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L154; nop
+set Z2,%l3
+ld2 [%l3],%f30
+set U2,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L152; nop
+.L154:
+set Z1,%l3
+ld2 [%l3],%f30
+set U1,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbuge .L157; nop
+set Z2,%l3
+ld2 [%l3],%f30
+set U2,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbul .L155; nop
+.L157:
+mov %g0,%o0
+set .L158,%o1
+call BadCond; nop
+set .L159,%o0
+call notify; nop
+set .L160,%o0
+set U1,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+set Z1,%l3
+ld2 [%l3],%f28
+fsubd %f28,%f30,%f30
+st %f30,[%sp+4*3+68]
+st %f31,[%sp+4*4+68]
+ld [%sp+4*3+68],%o3
+ld [%sp+4*4+68],%o4
+call printf; nop
+set .L161,%o0
+set U2,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+set Z2,%l3
+ld2 [%l3],%f28
+fsubd %f28,%f30,%f30
+st %f30,[%sp+4*3+68]
+st %f31,[%sp+4*4+68]
+ld [%sp+4*3+68],%o3
+ld [%sp+4*4+68],%o4
+call printf; nop
+ba .L156; nop
+.L155:
+set Zero,%l3
+ld2 [%l3],%f30
+set Z1,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbule .L164; nop
+set Z2,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbug .L162; nop
+.L164:
+set .L165,%o0
+set Radix,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set .L166,%o0
+call printf; nop
+set .L167,%o0
+set Z1,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+set Z2,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*3+68]
+st %f31,[%sp+4*4+68]
+ld [%sp+4*3+68],%o3
+ld [%sp+4*4+68],%o4
+call printf; nop
+set .L168,%o0
+call notify; nop
+.L162:
+set Z1,%l3
+ld2 [%l3],%f30
+set Z2,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L171; nop
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbule .L169; nop
+.L171:
+set X,%l3
+set Z1,%l2
+ld2 [%l2],%f30
+set U1,%l2
+ld2 [%l2],%f28
+fdivd %f30,%f28,%f30
+st2 %f30,[%l3]
+set Y,%l2
+set Z2,%l1
+ld2 [%l1],%f30
+set U2,%l1
+ld2 [%l1],%f28
+fdivd %f30,%f28,%f30
+st2 %f30,[%l2]
+ld2 [%l2],%f30
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbule .L172; nop
+set X,%l3
+set Y,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L172:
+set X,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call log; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Q,%l3
+fnegs %f30,%f30; fmovs %f31,%f31
+st2 %f30,[%l3]
+set .L174,%o0
+call printf; nop
+set Radix,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call log; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set .L175,%o0
+set Q,%l3
+ld2 [%l3],%f28
+fdivd %f28,%f30,%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set .L94,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call log; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set .L176,%o0
+set Q,%l3
+ld2 [%l3],%f28
+fdivd %f28,%f30,%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+.L169:
+set .L151,%o0
+call printf; nop
+.L156:
+.L152:
+.L140:
+call Pause; nop
+set Milestone,%l3
+set 35,%l2
+st %l2,[%l3]
+set Radix,%l3
+ld2 [%l3],%f30
+set Two,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbul .L177; nop
+set X,%l3
+set Radix,%l2
+ld2 [%l2],%f30
+set W,%l2
+ld2 [%l2],%f28
+fmuld %f30,%f30,%f30
+fdivd %f28,%f30,%f30
+st2 %f30,[%l3]
+set Y,%l2
+ld2 [%l3],%f30
+set One,%l1
+ld2 [%l1],%f28
+faddd %f30,%f28,%f28
+st2 %f28,[%l2]
+set Z,%l1
+ld2 [%l2],%f28
+fsubd %f28,%f30,%f30
+st2 %f30,[%l1]
+set T,%l2
+ld2 [%l1],%f30
+set U2,%l1
+ld2 [%l1],%f28
+faddd %f30,%f28,%f26
+st2 %f26,[%l2]
+ld2 [%l2],%f26
+fsubd %f26,%f30,%f30
+st2 %f30,[%l3]
+mov %g0,%o0
+ld2 [%l3],%f30
+fcmped %f30,%f28; nop; fbne .L181; nop
+set 1,%l3
+st %l3,[%fp+-24]
+ba .L182; nop
+.L181:
+st %g0,[%fp+-24]
+.L182:
+ld [%fp+-24],%o1
+set .L180,%o2
+call TstCond; nop
+set X,%l3
+ld2 [%l3],%f30
+set U2,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L183; nop
+set .L185,%o0
+call printf; nop
+.L183:
+.L177:
+set .L186,%o0
+call printf; nop
+set Y,%l3
+set F9,%l2
+ld2 [%l2],%f30
+set One,%l2
+ld2 [%l2],%f28
+fmuld %f30,%f28,%f26
+st2 %f26,[%l3]
+set Z,%l2
+fmuld %f28,%f30,%f26
+st2 %f26,[%l2]
+set X,%l1
+set Half,%l0
+ld2 [%l0],%f26
+fsubd %f30,%f26,%f30
+st2 %f30,[%l1]
+ld2 [%l1],%f30
+ld2 [%l3],%f24
+fsubd %f24,%f26,%f24
+fsubd %f24,%f30,%f24
+st2 %f24,[%l3]
+ld2 [%l2],%f24
+fsubd %f24,%f26,%f26
+fsubd %f26,%f30,%f30
+st2 %f30,[%l2]
+set U2,%l3
+ld2 [%l3],%f30
+faddd %f28,%f30,%f26
+st2 %f26,[%l1]
+set T,%l3
+ld2 [%l1],%f26
+set Radix,%l2
+ld2 [%l2],%f24
+fmuld %f26,%f24,%f22
+st2 %f22,[%l3]
+set R,%l2
+fmuld %f24,%f26,%f26
+st2 %f26,[%l2]
+ld2 [%l3],%f26
+fsubd %f26,%f24,%f26
+st2 %f26,[%l1]
+fmuld %f24,%f30,%f30
+ld2 [%l1],%f26
+fsubd %f26,%f30,%f26
+st2 %f26,[%l1]
+ld2 [%l2],%f26
+fsubd %f26,%f24,%f26
+st2 %f26,[%l3]
+ld2 [%l3],%f26
+fsubd %f26,%f30,%f30
+st2 %f30,[%l3]
+fsubd %f24,%f28,%f30
+ld2 [%l1],%f28
+fmuld %f28,%f30,%f28
+st2 %f28,[%l1]
+ld2 [%l3],%f28
+fmuld %f28,%f30,%f30
+st2 %f30,[%l3]
+set Zero,%l3
+ld2 [%l3],%f30
+set X,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L187; nop
+set Y,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L187; nop
+set Z,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L187; nop
+set T,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L187; nop
+set GMult,%l3
+set 1,%l2
+st %l2,[%l3]
+ba .L188; nop
+.L187:
+mov %g0,%l3
+set GMult,%l2
+st %l3,[%l2]
+set 1,%o0
+mov %l3,%o1
+set .L189,%o2
+call TstCond; nop
+.L188:
+set Z,%l3
+set Radix,%l2
+ld2 [%l2],%f30
+set U2,%l2
+ld2 [%l2],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%l3]
+set X,%l2
+ld2 [%l3],%f30
+set One,%l3
+ld2 [%l3],%f28
+faddd %f28,%f30,%f28
+st2 %f28,[%l2]
+ld2 [%l2],%f28
+faddd %f28,%f30,%f30
+fmuld %f28,%f28,%f28
+fsubd %f30,%f28,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call fabs; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set U2,%l3
+ld2 [%l3],%f28
+set Y,%l3
+fsubd %f30,%f28,%f30
+st2 %f30,[%l3]
+set X,%l3
+set One,%l2
+ld2 [%l2],%f30
+fsubd %f30,%f28,%f30
+st2 %f30,[%l3]
+ld2 [%l3],%f30
+fsubd %f30,%f28,%f28
+fmuld %f30,%f30,%f30
+fsubd %f28,%f30,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call fabs; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Z,%l3
+set U1,%l2
+ld2 [%l2],%f28
+fsubd %f30,%f28,%f30
+st2 %f30,[%l3]
+mov %g0,%o0
+set Zero,%l3
+ld2 [%l3],%f30
+set Y,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbug .L192; nop
+set Z,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbug .L192; nop
+set 1,%l3
+st %l3,[%fp+-24]
+ba .L193; nop
+.L192:
+st %g0,[%fp+-24]
+.L193:
+ld [%fp+-24],%o1
+set .L191,%o2
+call TstCond; nop
+set Y,%l3
+set One,%l2
+ld2 [%l2],%f30
+set U2,%l2
+ld2 [%l2],%f28
+fsubd %f30,%f28,%f26
+st2 %f26,[%l3]
+set X,%l2
+faddd %f30,%f28,%f28
+st2 %f28,[%l2]
+set Z,%l1
+ld2 [%l3],%f28
+fdivd %f30,%f28,%f28
+st2 %f28,[%l1]
+ld2 [%l1],%f28
+ld2 [%l2],%f26
+fsubd %f28,%f26,%f28
+st2 %f28,[%l3]
+set Three,%l3
+ld2 [%l3],%f28
+fdivd %f30,%f28,%f30
+st2 %f30,[%l2]
+set Nine,%l3
+ld2 [%l3],%f30
+fdivd %f28,%f30,%f28
+st2 %f28,[%l1]
+ld2 [%l1],%f28
+ld2 [%l2],%f26
+fsubd %f26,%f28,%f26
+st2 %f26,[%l2]
+set T,%l3
+set TwentySeven,%l2
+ld2 [%l2],%f26
+fdivd %f30,%f26,%f30
+st2 %f30,[%l3]
+ld2 [%l3],%f30
+fsubd %f28,%f30,%f30
+st2 %f30,[%l1]
+set 2,%o0
+set Zero,%l3
+ld2 [%l3],%f30
+set X,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L196; nop
+set Y,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L196; nop
+set Z,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L196; nop
+set 1,%l3
+st %l3,[%fp+-28]
+ba .L197; nop
+.L196:
+st %g0,[%fp+-28]
+.L197:
+ld [%fp+-28],%o1
+set .L195,%o2
+call TstCond; nop
+set Y,%l3
+set F9,%l2
+ld2 [%l2],%f30
+set One,%l2
+ld2 [%l2],%f28
+fdivd %f30,%f28,%f26
+st2 %f26,[%l3]
+set X,%l2
+set Half,%l1
+ld2 [%l1],%f26
+fsubd %f30,%f26,%f30
+st2 %f30,[%l2]
+ld2 [%l3],%f30
+fsubd %f30,%f26,%f30
+ld2 [%l2],%f26
+fsubd %f30,%f26,%f30
+st2 %f30,[%l3]
+set U2,%l3
+ld2 [%l3],%f30
+faddd %f28,%f30,%f30
+st2 %f30,[%l2]
+set T,%l3
+ld2 [%l2],%f30
+fdivd %f30,%f28,%f28
+st2 %f28,[%l3]
+ld2 [%l3],%f28
+fsubd %f28,%f30,%f30
+st2 %f30,[%l2]
+set Zero,%l3
+ld2 [%l3],%f30
+set X,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L198; nop
+set Y,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L198; nop
+set Z,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L198; nop
+set GDiv,%l3
+set 1,%l2
+st %l2,[%l3]
+ba .L199; nop
+.L198:
+mov %g0,%l3
+set GDiv,%l2
+st %l3,[%l2]
+set 1,%o0
+mov %l3,%o1
+set .L200,%o2
+call TstCond; nop
+.L199:
+set X,%l3
+set One,%l2
+ld2 [%l2],%f30
+set U2,%l2
+ld2 [%l2],%f28
+faddd %f30,%f28,%f28
+fdivd %f30,%f28,%f30
+st2 %f30,[%l3]
+set Y,%l2
+set Half,%l1
+ld2 [%l1],%f30
+ld2 [%l3],%f28
+fsubd %f28,%f30,%f28
+fsubd %f28,%f30,%f30
+st2 %f30,[%l2]
+set 1,%o0
+ld2 [%l2],%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbuge .L203; nop
+set 1,%l3
+st %l3,[%fp+-32]
+ba .L204; nop
+.L203:
+st %g0,[%fp+-32]
+.L204:
+ld [%fp+-32],%o1
+set .L202,%o2
+call TstCond; nop
+set X,%l3
+set One,%l2
+ld2 [%l2],%f30
+set U2,%l2
+ld2 [%l2],%f28
+fsubd %f30,%f28,%f26
+st2 %f26,[%l3]
+set Y,%l2
+set Radix,%l1
+ld2 [%l1],%f26
+fmuld %f26,%f28,%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l2]
+set Z,%l1
+ld2 [%l3],%f30
+fmuld %f30,%f26,%f28
+st2 %f28,[%l1]
+set T,%l0
+ld2 [%l2],%f28
+fmuld %f28,%f26,%f24
+st2 %f24,[%l0]
+set R,%o5
+ld2 [%l1],%f24
+fdivd %f24,%f26,%f24
+st2 %f24,[%o5]
+set StickyBit,%l1
+ld2 [%l0],%f24
+fdivd %f24,%f26,%f26
+st2 %f26,[%l1]
+ld2 [%o5],%f26
+fsubd %f26,%f30,%f30
+st2 %f30,[%l3]
+ld2 [%l1],%f30
+fsubd %f30,%f28,%f30
+st2 %f30,[%l2]
+mov %g0,%o0
+set Zero,%l3
+ld2 [%l3],%f30
+set X,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L207; nop
+set Y,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L207; nop
+set 1,%l3
+st %l3,[%fp+-36]
+ba .L208; nop
+.L207:
+st %g0,[%fp+-36]
+.L208:
+ld [%fp+-36],%o1
+set .L206,%o2
+call TstCond; nop
+set Y,%l3
+set One,%l2
+ld2 [%l2],%f30
+set U1,%l2
+ld2 [%l2],%f28
+fsubd %f30,%f28,%f28
+st2 %f28,[%l3]
+set X,%l2
+set F9,%l1
+ld2 [%l1],%f28
+fsubd %f30,%f28,%f28
+st2 %f28,[%l2]
+ld2 [%l3],%f28
+fsubd %f30,%f28,%f30
+st2 %f30,[%l3]
+set T,%l3
+set Radix,%l2
+ld2 [%l2],%f30
+set U2,%l2
+ld2 [%l2],%f28
+fsubd %f30,%f28,%f28
+st2 %f28,[%l3]
+set Z,%l2
+set BMinusU2,%l1
+ld2 [%l1],%f28
+fsubd %f30,%f28,%f28
+st2 %f28,[%l2]
+ld2 [%l3],%f28
+fsubd %f30,%f28,%f30
+st2 %f30,[%l3]
+set U1,%l3
+ld2 [%l3],%f30
+set X,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L209; nop
+set Y,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L209; nop
+set U2,%l3
+ld2 [%l3],%f30
+set Z,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L209; nop
+set T,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L209; nop
+set GAddSub,%l3
+set 1,%l2
+st %l2,[%l3]
+ba .L210; nop
+.L209:
+mov %g0,%l3
+set GAddSub,%l2
+st %l3,[%l2]
+set 1,%o0
+mov %l3,%o1
+set .L211,%o2
+call TstCond; nop
+.L210:
+set F9,%l3
+ld2 [%l3],%f30
+set One,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L212; nop
+fsubd %f30,%f28,%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbul .L212; nop
+set 1,%o0
+set .L214,%o1
+call BadCond; nop
+set .L215,%o0
+call printf; nop
+set .L216,%o0
+call printf; nop
+set .L217,%o0
+call printf; nop
+.L212:
+set GMult,%l3
+ld [%l3],%l3
+cmp %l3,1; bne .L218; nop
+set GDiv,%l3
+ld [%l3],%l3
+cmp %l3,1; bne .L218; nop
+set GAddSub,%l3
+ld [%l3],%l3
+cmp %l3,1; bne .L218; nop
+set .L220,%o0
+call printf; nop
+.L218:
+set Milestone,%l3
+set 40,%l2
+st %l2,[%l3]
+call Pause; nop
+set .L221,%o0
+call printf; nop
+set RMult,%l2
+st %g0,[%l2]
+set RDiv,%l2
+st %g0,[%l2]
+set RAddSub,%l2
+st %g0,[%l2]
+set Two,%l2
+ld2 [%l2],%f30
+set RadixD2,%l2
+set Radix,%l1
+ld2 [%l1],%f28
+fdivd %f28,%f30,%f28
+st2 %f28,[%l2]
+set A1,%l2
+st2 %f30,[%l2]
+set Done,%l2
+st %g0,[%l2]
+.L222:
+set AInvrse,%l3
+set Radix,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L225:
+set AInvrse,%l3
+ld2 [%l3],%f30
+set X,%l2
+st2 %f30,[%l2]
+set A1,%l2
+ld2 [%l2],%f28
+fdivd %f30,%f28,%f30
+st2 %f30,[%l3]
+.L226:
+set AInvrse,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call floor; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set AInvrse,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L225; nop
+set X,%l3
+ld2 [%l3],%f30
+set One,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L231; nop
+set A1,%l3
+ld2 [%l3],%f30
+set Three,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbule .L229; nop
+.L231:
+set 1,%l3
+st %l3,[%fp+-40]
+ba .L230; nop
+.L229:
+st %g0,[%fp+-40]
+.L230:
+set Done,%l3
+ld [%fp+-40],%l2
+st %l2,[%l3]
+set Done,%l3
+ld [%l3],%l3
+cmp %l3,0; bne .L232; nop
+set A1,%l3
+set Nine,%l2
+ld2 [%l2],%f30
+set One,%l2
+ld2 [%l2],%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l3]
+.L232:
+.L223:
+set Done,%l3
+ld [%l3],%l3
+cmp %l3,0; be .L222; nop
+set X,%l3
+ld2 [%l3],%f30
+set One,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L234; nop
+set A1,%l3
+set Radix,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L234:
+set AInvrse,%l3
+set A1,%l2
+ld2 [%l2],%f30
+set One,%l2
+ld2 [%l2],%f28
+fdivd %f28,%f30,%f28
+st2 %f28,[%l3]
+set X,%l2
+st2 %f30,[%l2]
+set Y,%l2
+ld2 [%l3],%f30
+st2 %f30,[%l2]
+set Done,%l3
+st %g0,[%l3]
+.L236:
+set Z,%l3
+set Half,%l2
+ld2 [%l2],%f30
+set X,%l2
+ld2 [%l2],%f28
+set Y,%l2
+ld2 [%l2],%f26
+fmuld %f28,%f26,%f28
+fsubd %f28,%f30,%f28
+st2 %f28,[%l3]
+mov %g0,%o0
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L241; nop
+set 1,%l3
+st %l3,[%fp+-40]
+ba .L242; nop
+.L241:
+st %g0,[%fp+-40]
+.L242:
+ld [%fp+-40],%o1
+set .L240,%o2
+call TstCond; nop
+set X,%l3
+ld2 [%l3],%f30
+set Radix,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L244; nop
+set 1,%l3
+st %l3,[%fp+-44]
+ba .L245; nop
+.L244:
+st %g0,[%fp+-44]
+.L245:
+set Done,%l3
+ld [%fp+-44],%l2
+st %l2,[%l3]
+set X,%l3
+set Radix,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set Y,%l2
+set One,%l1
+ld2 [%l1],%f30
+ld2 [%l3],%f28
+fdivd %f30,%f28,%f30
+st2 %f30,[%l2]
+.L237:
+set Done,%l3
+ld [%l3],%l3
+cmp %l3,0; be .L236; nop
+set Y2,%l3
+set One,%l2
+ld2 [%l2],%f30
+set U2,%l2
+ld2 [%l2],%f28
+faddd %f30,%f28,%f26
+st2 %f26,[%l3]
+set Y1,%l2
+fsubd %f30,%f28,%f30
+st2 %f30,[%l2]
+set X,%l1
+set OneAndHalf,%l0
+ld2 [%l0],%f30
+fsubd %f30,%f28,%f26
+st2 %f26,[%l1]
+set Y,%l0
+faddd %f30,%f28,%f26
+st2 %f26,[%l0]
+set Z,%o5
+ld2 [%l1],%f26
+ld2 [%l3],%f24
+fsubd %f26,%f28,%f22
+fmuld %f22,%f24,%f22
+st2 %f22,[%o5]
+set T,%l3
+ld2 [%l0],%f22
+ld2 [%l2],%f20
+fmuld %f22,%f20,%f18
+st2 %f18,[%l3]
+ld2 [%o5],%f18
+fsubd %f18,%f26,%f18
+st2 %f18,[%o5]
+ld2 [%l3],%f18
+fsubd %f18,%f26,%f18
+st2 %f18,[%l3]
+fmuld %f26,%f24,%f26
+st2 %f26,[%l1]
+faddd %f22,%f28,%f28
+fmuld %f28,%f20,%f28
+st2 %f28,[%l0]
+ld2 [%l1],%f28
+fsubd %f28,%f30,%f28
+st2 %f28,[%l1]
+ld2 [%l0],%f28
+fsubd %f28,%f30,%f30
+st2 %f30,[%l0]
+set Zero,%l3
+ld2 [%l3],%f30
+set X,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L246; nop
+set Y,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L246; nop
+set Z,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L246; nop
+set T,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbug .L246; nop
+set X,%l3
+set OneAndHalf,%l2
+ld2 [%l2],%f30
+set U2,%l2
+ld2 [%l2],%f28
+faddd %f30,%f28,%f26
+set Y2,%l2
+ld2 [%l2],%f24
+fmuld %f26,%f24,%f22
+st2 %f22,[%l3]
+set Y,%l2
+fsubd %f30,%f28,%f30
+fsubd %f30,%f28,%f22
+st2 %f22,[%l2]
+set Z,%l1
+faddd %f26,%f28,%f26
+st2 %f26,[%l1]
+set T,%l0
+set Y1,%o5
+ld2 [%o5],%f26
+fmuld %f30,%f26,%f30
+st2 %f30,[%l0]
+ld2 [%l1],%f30
+faddd %f30,%f28,%f22
+ld2 [%l3],%f20
+fsubd %f20,%f22,%f20
+st2 %f20,[%l3]
+set StickyBit,%l3
+ld2 [%l2],%f20
+fmuld %f20,%f26,%f18
+st2 %f18,[%l3]
+set S,%o4
+fmuld %f30,%f24,%f30
+st2 %f30,[%o4]
+ld2 [%l0],%f30
+fsubd %f30,%f20,%f30
+st2 %f30,[%l0]
+fsubd %f28,%f20,%f30
+ld2 [%l3],%f20
+faddd %f30,%f20,%f30
+st2 %f30,[%l2]
+ld2 [%o4],%f30
+faddd %f22,%f28,%f22
+fsubd %f30,%f22,%f30
+st2 %f30,[%l1]
+faddd %f24,%f28,%f30
+fmuld %f30,%f26,%f30
+st2 %f30,[%l3]
+fmuld %f24,%f26,%f30
+st2 %f30,[%o5]
+ld2 [%l3],%f30
+fsubd %f30,%f24,%f30
+st2 %f30,[%l3]
+ld2 [%o5],%f30
+set Half,%l3
+ld2 [%l3],%f28
+fsubd %f30,%f28,%f30
+st2 %f30,[%o5]
+set Zero,%l3
+ld2 [%l3],%f30
+set X,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L248; nop
+set Y,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L248; nop
+set Z,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L248; nop
+set T,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L248; nop
+set StickyBit,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L248; nop
+set Y1,%l3
+ld2 [%l3],%f30
+set Half,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L248; nop
+set RMult,%l3
+set 1,%l2
+st %l2,[%l3]
+set .L250,%o0
+call printf; nop
+ba .L249; nop
+.L248:
+set U2,%l3
+ld2 [%l3],%f30
+set Zero,%l3
+ld2 [%l3],%f28
+set X,%l3
+ld2 [%l3],%f26
+faddd %f26,%f30,%f26
+fcmped %f26,%f28; nop; fbne .L251; nop
+set Y,%l3
+ld2 [%l3],%f26
+fcmped %f26,%f28; nop; fbuge .L251; nop
+set Z,%l3
+ld2 [%l3],%f26
+faddd %f26,%f30,%f26
+fcmped %f26,%f28; nop; fbne .L251; nop
+set T,%l3
+ld2 [%l3],%f26
+fcmped %f26,%f28; nop; fbuge .L251; nop
+set StickyBit,%l3
+ld2 [%l3],%f26
+faddd %f26,%f30,%f30
+fcmped %f30,%f28; nop; fbne .L251; nop
+set Y1,%l3
+ld2 [%l3],%f30
+set Half,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbuge .L251; nop
+set RMult,%l3
+set 2,%l2
+st %l2,[%l3]
+set .L253,%o0
+call printf; nop
+ba .L252; nop
+.L251:
+set .L254,%o0
+call printf; nop
+.L252:
+.L249:
+set RMult,%l3
+ld [%l3],%l3
+cmp %l3,1; bne .L247; nop
+set GMult,%l3
+ld [%l3],%l3
+cmp %l3,0; bne .L247; nop
+set .L257,%o0
+call notify; nop
+ba .L247; nop
+.L246:
+set .L254,%o0
+call printf; nop
+.L247:
+set Milestone,%l3
+set 45,%l2
+st %l2,[%l3]
+set Y2,%l3
+set One,%l2
+ld2 [%l2],%f30
+set U2,%l2
+ld2 [%l2],%f28
+faddd %f30,%f28,%f26
+st2 %f26,[%l3]
+set Y1,%l2
+fsubd %f30,%f28,%f30
+st2 %f30,[%l2]
+set Z,%l1
+set OneAndHalf,%l0
+ld2 [%l0],%f30
+faddd %f30,%f28,%f26
+faddd %f26,%f28,%f24
+st2 %f24,[%l1]
+set X,%l0
+ld2 [%l1],%f24
+ld2 [%l3],%f22
+fdivd %f24,%f22,%f20
+st2 %f20,[%l0]
+set T,%l3
+fsubd %f30,%f28,%f20
+fsubd %f20,%f28,%f20
+st2 %f20,[%l3]
+set Y,%o5
+ld2 [%l3],%f20
+ld2 [%l2],%f18
+fsubd %f20,%f28,%f16
+fdivd %f16,%f18,%f16
+st2 %f16,[%o5]
+faddd %f24,%f28,%f24
+fdivd %f24,%f22,%f24
+st2 %f24,[%l1]
+ld2 [%l0],%f24
+fsubd %f24,%f30,%f24
+st2 %f24,[%l0]
+ld2 [%o5],%f24
+fsubd %f24,%f20,%f24
+st2 %f24,[%o5]
+fdivd %f20,%f18,%f24
+st2 %f24,[%l3]
+ld2 [%l1],%f24
+fsubd %f24,%f26,%f26
+st2 %f26,[%l1]
+fsubd %f28,%f30,%f30
+ld2 [%l3],%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l3]
+set Zero,%l3
+ld2 [%l3],%f30
+set X,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbug .L258; nop
+set Y,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbug .L258; nop
+set Z,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbug .L258; nop
+set T,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbug .L258; nop
+set X,%l3
+set OneAndHalf,%l2
+ld2 [%l2],%f30
+set Y2,%l2
+ld2 [%l2],%f28
+fdivd %f30,%f28,%f26
+st2 %f26,[%l3]
+set Y,%l1
+set U2,%l0
+ld2 [%l0],%f26
+fsubd %f30,%f26,%f24
+st2 %f24,[%l1]
+set Z,%l0
+faddd %f30,%f26,%f24
+st2 %f24,[%l0]
+ld2 [%l1],%f24
+ld2 [%l3],%f22
+fsubd %f22,%f24,%f22
+st2 %f22,[%l3]
+set T,%l3
+set Y1,%o5
+ld2 [%o5],%f22
+fdivd %f30,%f22,%f20
+st2 %f20,[%l3]
+fdivd %f24,%f22,%f24
+st2 %f24,[%l1]
+ld2 [%l0],%f24
+ld2 [%l3],%f22
+faddd %f24,%f26,%f20
+fsubd %f22,%f20,%f22
+st2 %f22,[%l3]
+ld2 [%l1],%f22
+fsubd %f22,%f24,%f22
+st2 %f22,[%l1]
+fdivd %f24,%f28,%f24
+st2 %f24,[%l0]
+faddd %f28,%f26,%f26
+fdivd %f26,%f28,%f26
+st2 %f26,[%o5]
+ld2 [%l0],%f26
+fsubd %f26,%f30,%f30
+st2 %f30,[%l0]
+ld2 [%o5],%f30
+fsubd %f30,%f28,%f30
+st2 %f30,[%l2]
+set F9,%l3
+ld2 [%l3],%f30
+set U1,%l3
+ld2 [%l3],%f28
+fsubd %f30,%f28,%f28
+fdivd %f28,%f30,%f30
+st2 %f30,[%o5]
+set Zero,%l3
+ld2 [%l3],%f30
+set X,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L260; nop
+set Y,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L260; nop
+set Z,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L260; nop
+set T,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L260; nop
+set Y2,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L260; nop
+fcmped %f28,%f30; nop; fbne .L260; nop
+set Half,%l3
+ld2 [%l3],%f30
+set Y1,%l3
+ld2 [%l3],%f28
+fsubd %f28,%f30,%f28
+set F9,%l3
+ld2 [%l3],%f26
+fsubd %f26,%f30,%f30
+fcmped %f28,%f30; nop; fbne .L260; nop
+set RDiv,%l3
+set 1,%l2
+st %l2,[%l3]
+set .L262,%o0
+call printf; nop
+set GDiv,%l3
+ld [%l3],%l3
+cmp %l3,0; bne .L261; nop
+set .L265,%o0
+call notify; nop
+ba .L261; nop
+.L260:
+set Zero,%l3
+ld2 [%l3],%f30
+set X,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbuge .L266; nop
+set Y,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbuge .L266; nop
+set Z,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbuge .L266; nop
+set T,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbuge .L266; nop
+set Y2,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbuge .L266; nop
+set Half,%l3
+ld2 [%l3],%f30
+set Y1,%l3
+ld2 [%l3],%f28
+fsubd %f28,%f30,%f28
+set F9,%l3
+ld2 [%l3],%f26
+fsubd %f26,%f30,%f30
+fcmped %f28,%f30; nop; fbuge .L266; nop
+set RDiv,%l3
+set 2,%l2
+st %l2,[%l3]
+set .L268,%o0
+call printf; nop
+.L266:
+.L261:
+.L258:
+set RDiv,%l3
+ld [%l3],%l3
+cmp %l3,0; bne .L269; nop
+set .L271,%o0
+call printf; nop
+.L269:
+set BInvrse,%l3
+set Radix,%l2
+ld2 [%l2],%f30
+set One,%l2
+ld2 [%l2],%f28
+fdivd %f28,%f30,%f28
+st2 %f28,[%l3]
+mov %g0,%o0
+set Half,%l2
+ld2 [%l2],%f28
+ld2 [%l3],%f26
+fmuld %f26,%f30,%f30
+fsubd %f30,%f28,%f30
+fcmped %f30,%f28; nop; fbne .L274; nop
+set 1,%l3
+st %l3,[%fp+-40]
+ba .L275; nop
+.L274:
+st %g0,[%fp+-40]
+.L275:
+ld [%fp+-40],%o1
+set .L273,%o2
+call TstCond; nop
+set Milestone,%l3
+set 50,%l2
+st %l2,[%l3]
+mov %g0,%o0
+set Half,%l3
+ld2 [%l3],%f30
+set F9,%l3
+ld2 [%l3],%f28
+set U1,%l3
+ld2 [%l3],%f26
+faddd %f28,%f26,%f28
+fsubd %f28,%f30,%f28
+fcmped %f28,%f30; nop; fbne .L278; nop
+set One,%l3
+ld2 [%l3],%f30
+set BMinusU2,%l3
+ld2 [%l3],%f28
+set U2,%l3
+ld2 [%l3],%f26
+faddd %f28,%f26,%f28
+fsubd %f28,%f30,%f28
+set Radix,%l3
+ld2 [%l3],%f26
+fsubd %f26,%f30,%f30
+fcmped %f28,%f30; nop; fbne .L278; nop
+set 1,%l3
+st %l3,[%fp+-44]
+ba .L279; nop
+.L278:
+st %g0,[%fp+-44]
+.L279:
+ld [%fp+-44],%o1
+set .L277,%o2
+call TstCond; nop
+set X,%l3
+set One,%l2
+ld2 [%l2],%f30
+set U1,%l2
+ld2 [%l2],%f28
+fmuld %f28,%f28,%f28
+fsubd %f30,%f28,%f28
+st2 %f28,[%l3]
+set Y,%l2
+set U2,%l1
+ld2 [%l1],%f28
+fsubd %f30,%f28,%f26
+fmuld %f28,%f26,%f28
+faddd %f30,%f28,%f28
+st2 %f28,[%l2]
+set Z,%l1
+set Half,%l0
+ld2 [%l0],%f28
+set F9,%l0
+ld2 [%l0],%f26
+fsubd %f26,%f28,%f26
+st2 %f26,[%l1]
+ld2 [%l3],%f26
+fsubd %f26,%f28,%f28
+ld2 [%l1],%f26
+fsubd %f28,%f26,%f28
+st2 %f28,[%l3]
+ld2 [%l2],%f28
+fsubd %f28,%f30,%f30
+st2 %f30,[%l2]
+set Zero,%l3
+ld2 [%l3],%f30
+set X,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L280; nop
+set Y,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L280; nop
+set RAddSub,%l3
+set 2,%l2
+st %l2,[%l3]
+set .L282,%o0
+call printf; nop
+.L280:
+set GAddSub,%l3
+ld [%l3],%l3
+cmp %l3,1; bne .L283; nop
+set X,%l3
+set Half,%l2
+ld2 [%l2],%f30
+set U2,%l2
+ld2 [%l2],%f28
+faddd %f30,%f28,%f26
+fmuld %f26,%f28,%f26
+st2 %f26,[%l3]
+set Y,%l2
+fsubd %f30,%f28,%f30
+fmuld %f30,%f28,%f30
+st2 %f30,[%l2]
+set One,%l1
+ld2 [%l1],%f30
+ld2 [%l3],%f26
+faddd %f30,%f26,%f26
+st2 %f26,[%l3]
+ld2 [%l2],%f26
+faddd %f30,%f26,%f26
+st2 %f26,[%l2]
+faddd %f30,%f28,%f28
+ld2 [%l3],%f26
+fsubd %f28,%f26,%f28
+st2 %f28,[%l3]
+ld2 [%l2],%f28
+fsubd %f30,%f28,%f30
+st2 %f30,[%l2]
+set Zero,%l3
+ld2 [%l3],%f30
+set X,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L285; nop
+set Y,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L285; nop
+set X,%l3
+set Half,%l2
+ld2 [%l2],%f30
+set U2,%l2
+ld2 [%l2],%f28
+set U1,%l2
+ld2 [%l2],%f26
+faddd %f30,%f28,%f24
+fmuld %f24,%f26,%f24
+st2 %f24,[%l3]
+set Y,%l2
+fsubd %f30,%f28,%f30
+fmuld %f30,%f26,%f30
+st2 %f30,[%l2]
+set One,%l1
+ld2 [%l1],%f30
+ld2 [%l3],%f28
+fsubd %f30,%f28,%f28
+st2 %f28,[%l3]
+ld2 [%l2],%f28
+fsubd %f30,%f28,%f28
+st2 %f28,[%l2]
+set F9,%l1
+ld2 [%l1],%f28
+ld2 [%l3],%f26
+fsubd %f28,%f26,%f28
+st2 %f28,[%l3]
+ld2 [%l2],%f28
+fsubd %f30,%f28,%f30
+st2 %f30,[%l2]
+set Zero,%l3
+ld2 [%l3],%f30
+set X,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L287; nop
+set Y,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L287; nop
+set RAddSub,%l3
+set 1,%l2
+st %l2,[%l3]
+set .L289,%o0
+call printf; nop
+set GAddSub,%l3
+ld [%l3],%l3
+cmp %l3,0; bne .L284; nop
+set .L292,%o0
+call notify; nop
+ba .L284; nop
+.L287:
+set .L293,%o0
+call printf; nop
+ba .L284; nop
+.L285:
+set .L293,%o0
+call printf; nop
+ba .L284; nop
+.L283:
+set .L293,%o0
+call printf; nop
+.L284:
+set One,%l3
+ld2 [%l3],%f30
+set S,%l3
+st2 %f30,[%l3]
+set X,%l3
+set Half,%l2
+ld2 [%l2],%f28
+faddd %f30,%f28,%f26
+fmuld %f28,%f26,%f26
+faddd %f30,%f26,%f26
+st2 %f26,[%l3]
+set Y,%l2
+set U2,%l1
+ld2 [%l1],%f26
+faddd %f30,%f26,%f30
+fmuld %f30,%f28,%f30
+st2 %f30,[%l2]
+set Z,%l1
+ld2 [%l3],%f30
+ld2 [%l2],%f28
+fsubd %f30,%f28,%f26
+st2 %f26,[%l1]
+set T,%l3
+fsubd %f28,%f30,%f30
+st2 %f30,[%l3]
+set StickyBit,%l2
+ld2 [%l1],%f30
+ld2 [%l3],%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l2]
+ld2 [%l2],%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L294; nop
+set S,%l3
+set Zero,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set 3,%o0
+set .L296,%o1
+call BadCond; nop
+.L294:
+set StickyBit,%l3
+set Zero,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set GMult,%l3
+ld [%l3],%l3
+cmp %l3,1; bne .L297; nop
+set GDiv,%l3
+ld [%l3],%l3
+cmp %l3,1; bne .L297; nop
+set GAddSub,%l3
+ld [%l3],%l3
+cmp %l3,1; bne .L297; nop
+set RMult,%l3
+ld [%l3],%l3
+cmp %l3,1; bne .L297; nop
+set RDiv,%l3
+ld [%l3],%l3
+cmp %l3,1; bne .L297; nop
+set RAddSub,%l3
+ld [%l3],%l3
+cmp %l3,1; bne .L297; nop
+set RadixD2,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call floor; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set RadixD2,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L297; nop
+set .L299,%o0
+call printf; nop
+set X,%l3
+set Half,%l2
+ld2 [%l2],%f30
+set U2,%l2
+ld2 [%l2],%f28
+set U1,%l2
+ld2 [%l2],%f26
+faddd %f30,%f26,%f26
+fmuld %f26,%f28,%f26
+st2 %f26,[%l3]
+set Y,%l2
+fmuld %f30,%f28,%f30
+st2 %f30,[%l2]
+set One,%l1
+ld2 [%l1],%f30
+set Z,%l1
+ld2 [%l2],%f28
+faddd %f30,%f28,%f28
+st2 %f28,[%l1]
+set T,%l2
+ld2 [%l3],%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l2]
+set One,%l3
+ld2 [%l3],%f30
+set Z,%l3
+ld2 [%l3],%f28
+fsubd %f28,%f30,%f28
+set Zero,%l3
+ld2 [%l3],%f26
+fcmped %f28,%f26; nop; fbug .L300; nop
+set T,%l3
+ld2 [%l3],%f28
+fsubd %f28,%f30,%f30
+set U2,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbul .L300; nop
+set Z,%l3
+set Y,%l2
+set T,%l1
+ld2 [%l1],%f30
+ld2 [%l2],%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l3]
+ld2 [%l3],%f30
+set X,%l3
+ld2 [%l3],%f28
+fsubd %f30,%f28,%f30
+st2 %f30,[%l2]
+set T,%l3
+ld2 [%l3],%f30
+set Z,%l3
+ld2 [%l3],%f28
+fsubd %f28,%f30,%f28
+set U2,%l3
+ld2 [%l3],%f26
+fcmped %f28,%f26; nop; fbul .L302; nop
+set Y,%l3
+ld2 [%l3],%f28
+fsubd %f28,%f30,%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L302; nop
+set X,%l3
+set Half,%l2
+ld2 [%l2],%f30
+set U1,%l2
+ld2 [%l2],%f28
+faddd %f30,%f28,%f26
+fmuld %f26,%f28,%f26
+st2 %f26,[%l3]
+set Y,%l2
+fmuld %f30,%f28,%f30
+st2 %f30,[%l2]
+set One,%l1
+ld2 [%l1],%f30
+set Z,%l1
+ld2 [%l2],%f28
+fsubd %f30,%f28,%f28
+st2 %f28,[%l1]
+set T,%l2
+ld2 [%l3],%f28
+fsubd %f30,%f28,%f30
+st2 %f30,[%l2]
+set Zero,%l3
+ld2 [%l3],%f30
+set Z,%l3
+ld2 [%l3],%f28
+set One,%l3
+ld2 [%l3],%f26
+fsubd %f28,%f26,%f28
+fcmped %f28,%f30; nop; fbne .L304; nop
+set T,%l3
+ld2 [%l3],%f28
+set F9,%l3
+ld2 [%l3],%f26
+fsubd %f28,%f26,%f28
+fcmped %f28,%f30; nop; fbne .L304; nop
+set Z,%l3
+set U1,%l2
+ld2 [%l2],%f30
+set Half,%l2
+ld2 [%l2],%f28
+fsubd %f28,%f30,%f28
+fmuld %f28,%f30,%f30
+st2 %f30,[%l3]
+set F9,%l2
+ld2 [%l2],%f30
+set T,%l2
+ld2 [%l3],%f28
+fsubd %f30,%f28,%f28
+st2 %f28,[%l2]
+set Q,%l3
+set Y,%l2
+ld2 [%l2],%f28
+fsubd %f30,%f28,%f30
+st2 %f30,[%l3]
+set F9,%l3
+ld2 [%l3],%f30
+set Zero,%l3
+ld2 [%l3],%f28
+set T,%l3
+ld2 [%l3],%f26
+fsubd %f26,%f30,%f26
+fcmped %f26,%f28; nop; fbne .L306; nop
+set U1,%l3
+ld2 [%l3],%f26
+fsubd %f30,%f26,%f30
+set Q,%l3
+ld2 [%l3],%f26
+fsubd %f30,%f26,%f30
+fcmped %f30,%f28; nop; fbne .L306; nop
+set Z,%l3
+set One,%l2
+ld2 [%l2],%f30
+set U2,%l2
+ld2 [%l2],%f28
+set OneAndHalf,%l2
+ld2 [%l2],%f26
+faddd %f30,%f28,%f24
+fmuld %f24,%f26,%f24
+st2 %f24,[%l3]
+set T,%l2
+faddd %f26,%f28,%f26
+ld2 [%l3],%f24
+fsubd %f26,%f24,%f26
+faddd %f26,%f28,%f26
+st2 %f26,[%l2]
+set X,%l2
+set Radix,%l1
+ld2 [%l1],%f26
+set Half,%l1
+ld2 [%l1],%f24
+fdivd %f24,%f26,%f24
+faddd %f30,%f24,%f24
+st2 %f24,[%l2]
+set Y,%l1
+fmuld %f26,%f28,%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l1]
+ld2 [%l2],%f30
+ld2 [%l1],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%l3]
+set Zero,%l3
+ld2 [%l3],%f30
+set T,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L308; nop
+set X,%l3
+ld2 [%l3],%f28
+set Radix,%l3
+ld2 [%l3],%f26
+set U2,%l3
+ld2 [%l3],%f24
+fmuld %f26,%f24,%f26
+faddd %f28,%f26,%f28
+set Z,%l3
+ld2 [%l3],%f26
+fsubd %f28,%f26,%f28
+fcmped %f28,%f30; nop; fbne .L308; nop
+set Radix,%l3
+ld2 [%l3],%f30
+set Two,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L310; nop
+set X,%l3
+set Two,%l2
+ld2 [%l2],%f30
+set U2,%l2
+ld2 [%l2],%f28
+faddd %f30,%f28,%f28
+st2 %f28,[%l3]
+set Y,%l2
+ld2 [%l3],%f28
+fdivd %f28,%f30,%f30
+st2 %f30,[%l2]
+ld2 [%l2],%f30
+set One,%l3
+ld2 [%l3],%f28
+fsubd %f30,%f28,%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L311; nop
+set StickyBit,%l3
+set S,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+ba .L311; nop
+.L310:
+set StickyBit,%l3
+set S,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L311:
+.L308:
+.L306:
+.L304:
+.L302:
+.L300:
+.L297:
+set StickyBit,%l3
+ld2 [%l3],%f30
+set One,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L314; nop
+set .L316,%o0
+call printf; nop
+ba .L315; nop
+.L314:
+set .L317,%o0
+call printf; nop
+.L315:
+set 3,%o0
+set GMult,%l2
+ld [%l2],%l2
+cmp %l2,%g0; be .L320; nop
+set GDiv,%l2
+ld [%l2],%l2
+cmp %l2,%g0; be .L320; nop
+set GAddSub,%l2
+ld [%l2],%l2
+cmp %l2,%g0; be .L320; nop
+set RMult,%l2
+ld [%l2],%l2
+cmp %l2,%g0; be .L320; nop
+set RDiv,%l2
+ld [%l2],%l2
+cmp %l2,%g0; be .L320; nop
+set RAddSub,%l2
+ld [%l2],%l2
+cmp %l2,%g0; be .L320; nop
+set 1,%l3
+st %l3,[%fp+-48]
+ba .L321; nop
+.L320:
+st %g0,[%fp+-48]
+.L321:
+ld [%fp+-48],%o1
+set .L319,%o2
+call TstCond; nop
+set Milestone,%l3
+set 60,%l2
+st %l2,[%l3]
+set .L45,%o0
+call printf; nop
+set .L322,%o0
+call printf; nop
+set .L323,%o0
+set NoTrials,%l3
+ld [%l3],%o1
+call printf; nop
+set .L324,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call sqrt; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Random9,%l3
+st2 %f30,[%l3]
+set Random1,%l3
+set Third,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set I,%l3
+set 1,%l2
+st %l2,[%l3]
+.L325:
+call Random; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set X,%l3
+st2 %f30,[%l3]
+call Random; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Y,%l3
+st2 %f30,[%l3]
+set Z9,%l3
+set Y,%l2
+ld2 [%l2],%f30
+set X,%l2
+ld2 [%l2],%f28
+fmuld %f30,%f28,%f26
+st2 %f26,[%l3]
+set Z,%l2
+fmuld %f28,%f30,%f30
+st2 %f30,[%l2]
+ld2 [%l2],%f30
+ld2 [%l3],%f28
+fsubd %f30,%f28,%f30
+st2 %f30,[%l3]
+set I,%l3
+ld [%l3],%l2
+add %l2,1,%l2
+st %l2,[%l3]
+.L326:
+set I,%l3
+ld [%l3],%l3
+set NoTrials,%l2
+ld [%l2],%l2
+cmp %l3,%l2; bg .L328; nop
+set Z9,%l3
+ld2 [%l3],%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L325; nop
+.L328:
+set I,%l3
+ld [%l3],%l3
+set NoTrials,%l2
+ld [%l2],%l2
+cmp %l3,%l2; bne .L329; nop
+set Random1,%l3
+set One,%l2
+ld2 [%l2],%f30
+set Half,%l2
+ld2 [%l2],%f28
+set Three,%l2
+ld2 [%l2],%f26
+fdivd %f28,%f26,%f28
+faddd %f30,%f28,%f28
+st2 %f28,[%l3]
+set Random2,%l2
+set U2,%l1
+ld2 [%l1],%f26
+set U1,%l1
+ld2 [%l1],%f24
+faddd %f26,%f24,%f26
+faddd %f26,%f30,%f30
+st2 %f30,[%l2]
+ld2 [%l3],%f26
+ld2 [%l2],%f24
+set Z,%l3
+fmuld %f26,%f24,%f22
+st2 %f22,[%l3]
+set Y,%l3
+fmuld %f24,%f26,%f26
+st2 %f26,[%l3]
+fmuld %f28,%f30,%f30
+set Z9,%l3
+fsubd %f30,%f30,%f30
+st2 %f30,[%l3]
+.L329:
+set I,%l3
+ld [%l3],%l3
+set NoTrials,%l2
+ld [%l2],%l2
+cmp %l3,%l2; be .L331; nop
+set Z9,%l3
+ld2 [%l3],%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L331; nop
+set 2,%o0
+set .L333,%o1
+call BadCond; nop
+ba .L332; nop
+.L331:
+set .L334,%o0
+set NoTrials,%l3
+ld [%l3],%o1
+call printf; nop
+.L332:
+set Milestone,%l3
+set 70,%l2
+st %l2,[%l3]
+set .L335,%o0
+call printf; nop
+set Zero,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-64]
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call sqrt; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+ldd [%fp+-64],%f28
+fcmped %f28,%f30; nop; fbne .L338; nop
+set Zero,%l3
+ld2 [%l3],%f30
+fnegs %f30,%f30; fmovs %f31,%f31
+std %f30,[%fp+-72]
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call sqrt; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+ldd [%fp+-72],%f28
+fcmped %f28,%f30; nop; fbne .L338; nop
+set One,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-80]
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call sqrt; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+ldd [%fp+-80],%f28
+fcmped %f28,%f30; nop; fbne .L338; nop
+set 1,%l3
+st %l3,[%fp+-52]
+ba .L339; nop
+.L338:
+st %g0,[%fp+-52]
+.L339:
+mov %g0,%o0
+ld [%fp+-52],%o1
+set .L337,%o2
+call TstCond; nop
+set Zero,%l3
+ld2 [%l3],%f30
+set MinSqEr,%l3
+st2 %f30,[%l3]
+set MaxSqEr,%l3
+st2 %f30,[%l3]
+set J,%l3
+st2 %f30,[%l3]
+set X,%l3
+set Radix,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set OneUlp,%l3
+set U2,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set 1,%o0
+call SqXMinX; nop
+set BInvrse,%l3
+ld2 [%l3],%f30
+set X,%l3
+st2 %f30,[%l3]
+set OneUlp,%l3
+set U1,%l2
+ld2 [%l2],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%l3]
+set 1,%o0
+call SqXMinX; nop
+set U1,%l3
+ld2 [%l3],%f30
+set X,%l3
+st2 %f30,[%l3]
+set OneUlp,%l3
+fmuld %f30,%f30,%f30
+st2 %f30,[%l3]
+set 1,%o0
+call SqXMinX; nop
+set J,%l3
+ld2 [%l3],%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L340; nop
+call Pause; nop
+.L340:
+set .L342,%o0
+set NoTrials,%l3
+ld [%l3],%o1
+call printf; nop
+set J,%l3
+set Zero,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set X,%l3
+set Two,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set Radix,%l3
+ld2 [%l3],%f30
+set Y,%l3
+st2 %f30,[%l3]
+set One,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L343; nop
+.L345:
+set Y,%l3
+ld2 [%l3],%f30
+set X,%l2
+st2 %f30,[%l2]
+set Radix,%l2
+ld2 [%l2],%f28
+fmuld %f28,%f30,%f30
+st2 %f30,[%l3]
+.L346:
+set Y,%l3
+ld2 [%l3],%f30
+set X,%l3
+ld2 [%l3],%f28
+fsubd %f30,%f28,%f30
+set NoTrials,%l3
+ld [%l3],%l3
+st %l3,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fcmped %f30,%f28; nop; fbul .L345; nop
+.L343:
+set OneUlp,%l3
+set X,%l2
+ld2 [%l2],%f30
+set U2,%l2
+ld2 [%l2],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%l3]
+set I,%l3
+set 1,%l2
+st %l2,[%l3]
+ba .L349; nop
+.L348:
+set X,%l3
+ld2 [%l3],%f30
+set One,%l2
+ld2 [%l2],%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l3]
+set 2,%o0
+call SqXMinX; nop
+set J,%l3
+ld2 [%l3],%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbule .L351; nop
+ba .L350; nop
+.L351:
+set I,%l3
+ld [%l3],%l2
+add %l2,1,%l2
+st %l2,[%l3]
+.L349:
+set I,%l3
+ld [%l3],%l3
+set NoTrials,%l2
+ld [%l2],%l2
+cmp %l3,%l2; ble .L348; nop
+.L350:
+set .L353,%o0
+call printf; nop
+set I,%l3
+set -1,%l2
+st %l2,[%l3]
+set X,%l3
+set BMinusU2,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set Radix,%l3
+ld2 [%l3],%f30
+set Y,%l3
+st2 %f30,[%l3]
+set Z,%l3
+set U2,%l2
+ld2 [%l2],%f28
+fmuld %f30,%f28,%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l3]
+set NotMonot,%l2
+st %g0,[%l2]
+set Monot,%l2
+st %g0,[%l2]
+ba .L355; nop
+.L354:
+set I,%l3
+ld [%l3],%l2
+add %l2,1,%l2
+st %l2,[%l3]
+set X,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call sqrt; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+st2 %f30,[%l3]
+set Y,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call sqrt; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Q,%l3
+st2 %f30,[%l3]
+set Z,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call sqrt; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+st2 %f30,[%l3]
+set Q,%l3
+ld2 [%l3],%f30
+set X,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbug .L359; nop
+set Z,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbule .L357; nop
+.L359:
+set NotMonot,%l3
+set 1,%l2
+st %l2,[%l3]
+ba .L358; nop
+.L357:
+set Q,%l3
+ld2 [%l3],%f30
+set Half,%l2
+ld2 [%l2],%f28
+faddd %f30,%f28,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call floor; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+st2 %f30,[%l3]
+set I,%l3
+ld [%l3],%l3
+cmp %l3,0; bg .L362; nop
+set Q,%l3
+ld2 [%l3],%f30
+set Radix,%l3
+ld2 [%l3],%f28
+fmuld %f30,%f30,%f30
+fcmped %f28,%f30; nop; fbne .L360; nop
+.L362:
+set Monot,%l3
+set 1,%l2
+st %l2,[%l3]
+ba .L361; nop
+.L360:
+set I,%l3
+ld [%l3],%l3
+cmp %l3,0; ble .L363; nop
+set I,%l3
+ld [%l3],%l3
+cmp %l3,1; ble .L365; nop
+set Monot,%l3
+set 1,%l2
+st %l2,[%l3]
+ba .L364; nop
+.L365:
+set Y,%l3
+ld2 [%l3],%f30
+set BInvrse,%l2
+ld2 [%l2],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%l3]
+ld2 [%l3],%f30
+set U1,%l3
+ld2 [%l3],%f28
+set X,%l3
+fsubd %f30,%f28,%f26
+st2 %f26,[%l3]
+set Z,%l3
+faddd %f30,%f28,%f30
+st2 %f30,[%l3]
+ba .L364; nop
+.L363:
+set Y,%l3
+set Q,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+ld2 [%l3],%f30
+set U2,%l3
+ld2 [%l3],%f28
+set X,%l3
+fsubd %f30,%f28,%f26
+st2 %f26,[%l3]
+set Z,%l3
+faddd %f30,%f28,%f30
+st2 %f30,[%l3]
+.L364:
+.L361:
+.L358:
+.L355:
+set NotMonot,%l2
+ld [%l2],%l2
+cmp %l2,%g0; bne .L367; nop
+set Monot,%l2
+ld [%l2],%l2
+cmp %l2,%g0; be .L354; nop
+.L367:
+set Monot,%l3
+ld [%l3],%l3
+cmp %l3,0; be .L368; nop
+set .L370,%o0
+call printf; nop
+ba .L369; nop
+.L368:
+set 2,%o0
+set .L158,%o1
+call BadCond; nop
+set .L371,%o0
+set Y,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+.L369:
+set Milestone,%l3
+set 80,%l2
+st %l2,[%l3]
+set MinSqEr,%l3
+set Half,%l2
+ld2 [%l2],%f30
+ld2 [%l3],%f28
+faddd %f28,%f30,%f28
+st2 %f28,[%l3]
+set MaxSqEr,%l3
+ld2 [%l3],%f28
+fsubd %f28,%f30,%f30
+st2 %f30,[%l3]
+set One,%l3
+ld2 [%l3],%f30
+set U2,%l3
+ld2 [%l3],%f28
+faddd %f30,%f28,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call sqrt; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set One,%l3
+ld2 [%l3],%f28
+set U2,%l3
+ld2 [%l3],%f26
+set Y,%l3
+fsubd %f30,%f28,%f30
+fdivd %f30,%f26,%f30
+st2 %f30,[%l3]
+set SqEr,%l3
+set Y,%l2
+ld2 [%l2],%f30
+fsubd %f30,%f28,%f30
+set Eight,%l2
+ld2 [%l2],%f28
+fdivd %f26,%f28,%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l3]
+ld2 [%l3],%f30
+set MaxSqEr,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbule .L372; nop
+set MaxSqEr,%l3
+set SqEr,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L372:
+set SqEr,%l3
+set Y,%l2
+ld2 [%l2],%f30
+set U2,%l2
+ld2 [%l2],%f28
+set Eight,%l2
+ld2 [%l2],%f26
+fdivd %f28,%f26,%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l3]
+ld2 [%l3],%f30
+set MinSqEr,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbuge .L374; nop
+set MinSqEr,%l3
+set SqEr,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L374:
+set F9,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call sqrt; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set U2,%l3
+ld2 [%l3],%f28
+set U1,%l3
+ld2 [%l3],%f26
+set Y,%l3
+fsubd %f30,%f28,%f30
+set One,%l2
+ld2 [%l2],%f24
+fsubd %f24,%f28,%f28
+fsubd %f30,%f28,%f30
+fdivd %f30,%f26,%f30
+st2 %f30,[%l3]
+set SqEr,%l3
+set Y,%l2
+ld2 [%l2],%f30
+set Eight,%l2
+ld2 [%l2],%f28
+fdivd %f26,%f28,%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l3]
+ld2 [%l3],%f30
+set MaxSqEr,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbule .L376; nop
+set MaxSqEr,%l3
+set SqEr,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L376:
+set SqEr,%l3
+set Y,%l2
+ld2 [%l2],%f30
+set One,%l2
+ld2 [%l2],%f28
+faddd %f30,%f28,%f30
+set U1,%l2
+ld2 [%l2],%f28
+set Eight,%l2
+ld2 [%l2],%f26
+fdivd %f28,%f26,%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l3]
+ld2 [%l3],%f30
+set MinSqEr,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbuge .L378; nop
+set MinSqEr,%l3
+set SqEr,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L378:
+set OneUlp,%l3
+set U2,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set X,%l2
+ld2 [%l3],%f30
+st2 %f30,[%l2]
+set Indx,%l3
+set 1,%l2
+st %l2,[%l3]
+.L380:
+set X,%l3
+ld2 [%l3],%f30
+set U1,%l3
+ld2 [%l3],%f28
+faddd %f30,%f28,%f28
+faddd %f28,%f30,%f30
+set F9,%l3
+ld2 [%l3],%f28
+faddd %f30,%f28,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call sqrt; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Y,%l3
+st2 %f30,[%l3]
+set Y,%l3
+set U2,%l2
+ld2 [%l2],%f30
+set X,%l2
+ld2 [%l2],%f28
+set OneUlp,%l2
+ld2 [%l2],%f26
+ld2 [%l3],%f24
+fsubd %f24,%f30,%f24
+set One,%l2
+ld2 [%l2],%f22
+fsubd %f22,%f30,%f30
+faddd %f30,%f28,%f30
+fsubd %f24,%f30,%f30
+fdivd %f30,%f26,%f30
+st2 %f30,[%l3]
+set Z,%l2
+set Half,%l1
+ld2 [%l1],%f30
+set U1,%l1
+ld2 [%l1],%f24
+fsubd %f24,%f28,%f24
+set F9,%l1
+ld2 [%l1],%f22
+faddd %f24,%f22,%f24
+fmuld %f24,%f30,%f24
+fmuld %f24,%f28,%f24
+fmuld %f24,%f28,%f28
+fdivd %f28,%f26,%f28
+st2 %f28,[%l2]
+set SqEr,%l1
+ld2 [%l3],%f28
+faddd %f28,%f30,%f30
+ld2 [%l2],%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l1]
+ld2 [%l1],%f30
+set MinSqEr,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbuge .L384; nop
+set MinSqEr,%l3
+set SqEr,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L384:
+set SqEr,%l3
+set Y,%l2
+ld2 [%l2],%f30
+set Half,%l2
+ld2 [%l2],%f28
+fsubd %f30,%f28,%f30
+set Z,%l2
+ld2 [%l2],%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l3]
+ld2 [%l3],%f30
+set MaxSqEr,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbule .L386; nop
+set MaxSqEr,%l3
+set SqEr,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L386:
+set Indx,%l3
+ld [%l3],%l3
+cmp %l3,1; be .L390; nop
+cmp %l3,3; bne .L388; nop
+.L390:
+set X,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call Sign; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+std %f30,[%fp+-88]
+set OneUlp,%l2
+ld2 [%l2],%f28
+st %f28,[%sp+4*0+68]
+st %f29,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call sqrt; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Eight,%l2
+ld2 [%l2],%f28
+set Nine,%l2
+ld2 [%l2],%f26
+fmuld %f26,%f30,%f30
+fdivd %f28,%f30,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call floor; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set OneUlp,%l2
+ld2 [%l2],%f28
+ldd [%fp+-88],%f26
+fmuld %f28,%f26,%f28
+fmuld %f28,%f30,%f30
+st2 %f30,[%l3]
+ba .L389; nop
+.L388:
+set OneUlp,%l3
+set U1,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set X,%l2
+ld2 [%l3],%f30
+fnegs %f30,%f30; fmovs %f31,%f31
+st2 %f30,[%l2]
+.L389:
+.L381:
+set Indx,%l3
+ld [%l3],%l2
+add %l2,1,%l2
+st %l2,[%l3]
+set Indx,%l3
+ld [%l3],%l3
+cmp %l3,3; ble .L380; nop
+set Milestone,%l3
+set 85,%l2
+st %l2,[%l3]
+set SqRWrng,%l2
+st %g0,[%l2]
+set Anomaly,%l2
+st %g0,[%l2]
+set RSqrt,%l2
+st %g0,[%l2]
+set Radix,%l3
+ld2 [%l3],%f30
+set One,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L391; nop
+set .L393,%o0
+call printf; nop
+set Precision,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-88]
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call floor; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Radix,%l3
+ld2 [%l3],%f28
+st %f28,[%sp+4*0+68]
+st %f29,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+set One,%l3
+ld2 [%l3],%f28
+ldd [%fp+-88],%f26
+faddd %f28,%f26,%f28
+fsubd %f28,%f30,%f30
+st %f30,[%sp+4*2+68]
+st %f31,[%sp+4*3+68]
+ld [%sp+4*2+68],%o2
+ld [%sp+4*3+68],%o3
+call pow; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Half,%l3
+ld2 [%l3],%f28
+faddd %f28,%f30,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call floor; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set D,%l3
+st2 %f30,[%l3]
+set D,%l3
+ld2 [%l3],%f30
+set X,%l3
+set Radix,%l2
+ld2 [%l2],%f28
+fdivd %f30,%f28,%f28
+st2 %f28,[%l3]
+set Y,%l3
+set A1,%l2
+ld2 [%l2],%f28
+fdivd %f30,%f28,%f30
+st2 %f30,[%l3]
+set X,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-96]
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call floor; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+ldd [%fp+-96],%f28
+fcmped %f28,%f30; nop; fbne .L396; nop
+set Y,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-104]
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call floor; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+ldd [%fp+-104],%f28
+fcmped %f28,%f30; nop; fbue .L394; nop
+.L396:
+set Anomaly,%l3
+set 1,%l2
+st %l2,[%l3]
+ba .L395; nop
+.L394:
+set X,%l3
+set Zero,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set Z2,%l2
+ld2 [%l3],%f30
+st2 %f30,[%l2]
+set Y,%l3
+set One,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set Y2,%l2
+ld2 [%l3],%f28
+st2 %f28,[%l2]
+set Z1,%l3
+set Radix,%l2
+ld2 [%l2],%f28
+fsubd %f28,%f30,%f30
+st2 %f30,[%l3]
+set FourD,%l3
+set Four,%l2
+ld2 [%l2],%f30
+set D,%l2
+ld2 [%l2],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%l3]
+.L397:
+set Y2,%l3
+ld2 [%l3],%f30
+set Z2,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbule .L400; nop
+set Q,%l3
+set Radix,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set Y1,%l3
+set Y,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L402:
+set Q,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-112]
+set Half,%l3
+ld2 [%l3],%f28
+set Y1,%l3
+ld2 [%l3],%f26
+fdivd %f30,%f26,%f26
+fsubd %f28,%f26,%f28
+st %f28,[%sp+4*0+68]
+st %f29,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call floor; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Y1,%l3
+ld2 [%l3],%f28
+fmuld %f30,%f28,%f30
+ldd [%fp+-112],%f28
+faddd %f28,%f30,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call fabs; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set X1,%l3
+st2 %f30,[%l3]
+set Y1,%l3
+set Q,%l2
+ld2 [%l3],%f30
+st2 %f30,[%l2]
+set X1,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L403:
+set X1,%l3
+ld2 [%l3],%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbug .L402; nop
+set Q,%l3
+ld2 [%l3],%f30
+set One,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbug .L405; nop
+set Z2,%l3
+set Y2,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set Z,%l3
+set Y,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L405:
+.L400:
+set Y,%l3
+ld2 [%l3],%f30
+set Two,%l2
+ld2 [%l2],%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l3]
+set X,%l3
+ld2 [%l3],%f30
+set Eight,%l2
+ld2 [%l2],%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l3]
+set Y2,%l2
+ld2 [%l2],%f30
+ld2 [%l3],%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l2]
+ld2 [%l2],%f30
+set FourD,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbul .L407; nop
+set Y2,%l3
+ld2 [%l3],%f30
+set FourD,%l2
+ld2 [%l2],%f28
+fsubd %f30,%f28,%f30
+st2 %f30,[%l3]
+.L407:
+.L398:
+set Y,%l3
+ld2 [%l3],%f30
+set D,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbul .L397; nop
+set X8,%l3
+set FourD,%l2
+ld2 [%l2],%f30
+set Z2,%l2
+ld2 [%l2],%f28
+fsubd %f30,%f28,%f28
+st2 %f28,[%l3]
+set Q,%l2
+ld2 [%l3],%f28
+set Z,%l1
+ld2 [%l1],%f26
+fmuld %f26,%f26,%f26
+faddd %f28,%f26,%f26
+fdivd %f26,%f30,%f30
+st2 %f30,[%l2]
+set Eight,%l1
+ld2 [%l1],%f30
+fdivd %f28,%f30,%f30
+st2 %f30,[%l3]
+ld2 [%l2],%f30
+std %f30,[%fp+-112]
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call floor; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+ldd [%fp+-112],%f28
+fcmped %f28,%f30; nop; fbue .L409; nop
+set Anomaly,%l3
+set 1,%l2
+st %l2,[%l3]
+ba .L410; nop
+.L409:
+set Break,%l3
+st %g0,[%l3]
+.L411:
+set X,%l3
+set Z1,%l2
+ld2 [%l2],%f30
+set Z,%l2
+ld2 [%l2],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%l3]
+ld2 [%l3],%f30
+std %f30,[%fp+-120]
+set Radix,%l2
+ld2 [%l2],%f28
+fdivd %f30,%f28,%f28
+st %f28,[%sp+4*0+68]
+st %f29,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call floor; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Radix,%l2
+ld2 [%l2],%f28
+fmuld %f30,%f28,%f30
+ldd [%fp+-120],%f28
+fsubd %f28,%f30,%f30
+st2 %f30,[%l3]
+set X,%l3
+ld2 [%l3],%f30
+set One,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L414; nop
+set Break,%l3
+set 1,%l2
+st %l2,[%l3]
+ba .L415; nop
+.L414:
+set Z1,%l3
+ld2 [%l3],%f30
+set One,%l2
+ld2 [%l2],%f28
+fsubd %f30,%f28,%f30
+st2 %f30,[%l3]
+.L415:
+.L412:
+set Break,%l3
+ld [%l3],%l3
+cmp %l3,0; bne .L416; nop
+set Z1,%l3
+ld2 [%l3],%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbug .L411; nop
+.L416:
+set Z1,%l3
+ld2 [%l3],%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbug .L417; nop
+set Break,%l3
+ld [%l3],%l3
+cmp %l3,0; bne .L417; nop
+set Anomaly,%l3
+set 1,%l2
+st %l2,[%l3]
+ba .L418; nop
+.L417:
+set Z1,%l3
+ld2 [%l3],%f30
+set RadixD2,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbule .L419; nop
+set Z1,%l3
+ld2 [%l3],%f30
+set Radix,%l2
+ld2 [%l2],%f28
+fsubd %f30,%f28,%f30
+st2 %f30,[%l3]
+.L419:
+.L421:
+call NewD; nop
+.L422:
+set U2,%l3
+ld2 [%l3],%f30
+set D,%l3
+ld2 [%l3],%f28
+fmuld %f30,%f28,%f30
+set F9,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbul .L421; nop
+set D,%l3
+ld2 [%l3],%f30
+set Radix,%l3
+ld2 [%l3],%f28
+fmuld %f30,%f28,%f28
+fsubd %f28,%f30,%f28
+set W,%l3
+ld2 [%l3],%f26
+fsubd %f26,%f30,%f30
+fcmped %f28,%f30; nop; fbue .L424; nop
+set Anomaly,%l3
+set 1,%l2
+st %l2,[%l3]
+ba .L425; nop
+.L424:
+set D,%l3
+ld2 [%l3],%f30
+set Z2,%l3
+st2 %f30,[%l3]
+set I,%l3
+st %g0,[%l3]
+set Z,%l3
+ld2 [%l3],%f28
+set Y,%l3
+set One,%l2
+ld2 [%l2],%f26
+faddd %f26,%f28,%f26
+set Half,%l2
+ld2 [%l2],%f24
+fmuld %f26,%f24,%f26
+faddd %f30,%f26,%f26
+st2 %f26,[%l3]
+set X,%l3
+faddd %f30,%f28,%f30
+set Q,%l2
+ld2 [%l2],%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l3]
+call SR3750; nop
+set D,%l3
+ld2 [%l3],%f30
+set Z,%l3
+ld2 [%l3],%f28
+set Y,%l3
+set One,%l2
+ld2 [%l2],%f26
+fsubd %f26,%f28,%f26
+set Half,%l2
+ld2 [%l2],%f24
+fmuld %f26,%f24,%f26
+faddd %f30,%f26,%f26
+faddd %f26,%f30,%f26
+st2 %f26,[%l3]
+set X,%l3
+fsubd %f30,%f28,%f28
+faddd %f28,%f30,%f30
+st2 %f30,[%l3]
+ld2 [%l3],%f30
+set Q,%l2
+ld2 [%l2],%f28
+faddd %f30,%f28,%f28
+faddd %f28,%f30,%f30
+st2 %f30,[%l3]
+call SR3750; nop
+call NewD; nop
+set Z2,%l3
+ld2 [%l3],%f30
+set D,%l3
+ld2 [%l3],%f28
+fsubd %f28,%f30,%f28
+set W,%l3
+ld2 [%l3],%f26
+fsubd %f26,%f30,%f30
+fcmped %f28,%f30; nop; fbue .L426; nop
+set Anomaly,%l3
+set 1,%l2
+st %l2,[%l3]
+ba .L427; nop
+.L426:
+set Z2,%l3
+ld2 [%l3],%f30
+set D,%l3
+ld2 [%l3],%f28
+fsubd %f28,%f30,%f28
+set Z,%l3
+ld2 [%l3],%f26
+set Y,%l3
+set One,%l2
+ld2 [%l2],%f24
+fsubd %f24,%f26,%f24
+set Half,%l2
+ld2 [%l2],%f22
+fmuld %f24,%f22,%f24
+faddd %f30,%f24,%f24
+faddd %f28,%f24,%f24
+st2 %f24,[%l3]
+set X,%l3
+fsubd %f30,%f26,%f30
+set Q,%l2
+ld2 [%l2],%f26
+faddd %f30,%f26,%f30
+faddd %f28,%f30,%f30
+st2 %f30,[%l3]
+call SR3750; nop
+set Y,%l3
+set One,%l2
+ld2 [%l2],%f30
+set Z,%l2
+ld2 [%l2],%f28
+faddd %f30,%f28,%f30
+set Half,%l2
+ld2 [%l2],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%l3]
+set X,%l3
+set Q,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+call SR3750; nop
+set I,%l3
+ld [%l3],%l3
+cmp %l3,0; bne .L428; nop
+set Anomaly,%l3
+set 1,%l2
+st %l2,[%l3]
+.L428:
+.L427:
+.L425:
+.L418:
+.L410:
+.L395:
+set I,%l2
+ld [%l2],%l2
+cmp %l2,%g0; be .L432; nop
+set Anomaly,%l2
+ld [%l2],%l2
+cmp %l2,%g0; be .L430; nop
+.L432:
+mov %g0,%o0
+set .L433,%o1
+call BadCond; nop
+set .L434,%o0
+set W,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set .L435,%o0
+call printf; nop
+set SqRWrng,%l3
+set 1,%l2
+st %l2,[%l3]
+.L430:
+.L391:
+set Anomaly,%l3
+ld [%l3],%l3
+cmp %l3,0; bne .L436; nop
+set Zero,%l3
+ld2 [%l3],%f30
+set MinSqEr,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbul .L438; nop
+set MaxSqEr,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbug .L438; nop
+set RSqrt,%l3
+set 1,%l2
+st %l2,[%l3]
+set .L440,%o0
+call printf; nop
+ba .L439; nop
+.L438:
+set U2,%l3
+ld2 [%l3],%f30
+set Half,%l3
+ld2 [%l3],%f28
+set MaxSqEr,%l3
+ld2 [%l3],%f26
+faddd %f26,%f30,%f26
+fsubd %f30,%f28,%f30
+fcmped %f26,%f30; nop; fbug .L444; nop
+set MinSqEr,%l3
+ld2 [%l3],%f30
+fcmped %f30,%f28; nop; fbug .L444; nop
+set Radix,%l3
+ld2 [%l3],%f26
+faddd %f30,%f26,%f30
+fcmped %f30,%f28; nop; fbuge .L441; nop
+.L444:
+set SqRWrng,%l3
+set 1,%l2
+st %l2,[%l3]
+ba .L442; nop
+.L441:
+set RSqrt,%l3
+set 2,%l2
+st %l2,[%l3]
+set .L445,%o0
+call printf; nop
+.L442:
+.L439:
+.L436:
+set SqRWrng,%l3
+ld [%l3],%l3
+cmp %l3,0; be .L446; nop
+set .L448,%o0
+call printf; nop
+set .L449,%o0
+set MinSqEr,%l3
+ld2 [%l3],%f30
+set Half,%l3
+ld2 [%l3],%f28
+fsubd %f30,%f28,%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set .L450,%o0
+set Half,%l3
+ld2 [%l3],%f30
+set MaxSqEr,%l3
+ld2 [%l3],%f28
+faddd %f30,%f28,%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set 1,%o0
+set Radix,%l3
+ld2 [%l3],%f30
+set MaxSqEr,%l3
+ld2 [%l3],%f28
+set MinSqEr,%l3
+ld2 [%l3],%f26
+fsubd %f28,%f26,%f28
+fmuld %f30,%f30,%f30
+fcmped %f28,%f30; nop; fbuge .L453; nop
+set 1,%l3
+st %l3,[%fp+-84]
+ba .L454; nop
+.L453:
+st %g0,[%fp+-84]
+.L454:
+ld [%fp+-84],%o1
+set .L452,%o2
+call TstCond; nop
+.L446:
+set Milestone,%l3
+set 90,%l2
+st %l2,[%l3]
+call Pause; nop
+set .L455,%o0
+call printf; nop
+set N,%l2
+st %g0,[%l2]
+set I,%l2
+st %g0,[%l2]
+set Z,%l2
+set Zero,%l1
+ld2 [%l1],%f30
+fnegs %f30,%f30; fmovs %f31,%f31
+st2 %f30,[%l2]
+set M,%l2
+set 3,%l1
+st %l1,[%l2]
+set Break,%l2
+st %g0,[%l2]
+.L456:
+set X,%l3
+set One,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+call SR3980; nop
+set I,%l3
+ld [%l3],%l3
+cmp %l3,10; bg .L459; nop
+set I,%l3
+set 1023,%l2
+st %l2,[%l3]
+call SR3980; nop
+.L459:
+set Z,%l3
+ld2 [%l3],%f30
+set MinusOne,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L461; nop
+set Break,%l3
+set 1,%l2
+st %l2,[%l3]
+ba .L462; nop
+.L461:
+set Z,%l3
+set MinusOne,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+call PrintIfNPositive; nop
+set N,%l3
+st %g0,[%l3]
+set I,%l3
+set -4,%l2
+st %l2,[%l3]
+.L462:
+.L457:
+set Break,%l3
+ld [%l3],%l3
+cmp %l3,0; be .L456; nop
+call PrintIfNPositive; nop
+set N,%l3
+set N1,%l2
+ld [%l3],%l1
+st %l1,[%l2]
+st %g0,[%l3]
+set Z,%l3
+set A1,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set W,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call log; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+std %f30,[%fp+-88]
+set A1,%l3
+ld2 [%l3],%f28
+st %f28,[%sp+4*0+68]
+st %f29,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call log; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Two,%l3
+ld2 [%l3],%f28
+ldd [%fp+-88],%f26
+fmuld %f28,%f26,%f28
+fdivd %f28,%f30,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call floor; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set M,%l3
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%l2
+st %l2,[%l3]
+set Break,%l3
+st %g0,[%l3]
+.L463:
+set X,%l3
+set Z,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set I,%l3
+set 1,%l2
+st %l2,[%l3]
+call SR3980; nop
+set Z,%l3
+ld2 [%l3],%f30
+set AInvrse,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L466; nop
+set Break,%l3
+set 1,%l2
+st %l2,[%l3]
+ba .L467; nop
+.L466:
+set Z,%l3
+set AInvrse,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L467:
+.L464:
+set Break,%l3
+ld [%l3],%l3
+cmp %l3,0; be .L463; nop
+set Milestone,%l3
+set 100,%l2
+st %l2,[%l3]
+set M,%l3
+set NoTrials,%l2
+ld [%l2],%l2
+st %l2,[%l3]
+set Z,%l3
+set Three,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L468:
+set X,%l3
+set Z,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set I,%l3
+set 1,%l2
+st %l2,[%l3]
+call SR3980; nop
+.L471:
+set Z,%l3
+ld2 [%l3],%f30
+set Two,%l2
+ld2 [%l2],%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l3]
+.L472:
+set Three,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-96]
+set Z,%l3
+ld2 [%l3],%f28
+fdivd %f28,%f30,%f28
+st %f28,[%sp+4*0+68]
+st %f29,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call floor; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+ldd [%fp+-96],%f28
+fmuld %f28,%f30,%f30
+set Z,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L471; nop
+.L469:
+set Z,%l3
+ld2 [%l3],%f30
+set Eight,%l3
+ld2 [%l3],%f28
+set Three,%l3
+ld2 [%l3],%f26
+fmuld %f28,%f26,%f28
+fcmped %f30,%f28; nop; fbul .L468; nop
+set N,%l3
+ld [%l3],%l3
+cmp %l3,0; ble .L474; nop
+set .L476,%o0
+call printf; nop
+set .L477,%o0
+call printf; nop
+.L474:
+call PrintIfNPositive; nop
+set N,%l3
+ld [%l3],%l2
+set N1,%l1
+ld [%l1],%l1
+add %l2,%l1,%l2
+st %l2,[%l3]
+ld [%l3],%l3
+cmp %l3,0; bne .L478; nop
+set .L480,%o0
+call printf; nop
+.L478:
+set N,%l3
+ld [%l3],%l3
+cmp %l3,0; ble .L481; nop
+call Pause; nop
+ba .L482; nop
+.L481:
+set .L45,%o0
+call printf; nop
+.L482:
+set Milestone,%l3
+set 110,%l2
+st %l2,[%l3]
+set .L483,%o0
+call printf; nop
+set D,%l3
+set U1,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set Precision,%l3
+ld2 [%l3],%f30
+std %f30,[%fp+-96]
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call floor; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+ldd [%fp+-96],%f28
+fcmped %f28,%f30; nop; fbue .L484; nop
+set D,%l3
+set BInvrse,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set X,%l3
+set Precision,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L486:
+set D,%l3
+ld2 [%l3],%f30
+set BInvrse,%l2
+ld2 [%l2],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%l3]
+set X,%l3
+ld2 [%l3],%f30
+set One,%l2
+ld2 [%l2],%f28
+fsubd %f30,%f28,%f30
+st2 %f30,[%l3]
+.L487:
+set X,%l3
+ld2 [%l3],%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbug .L486; nop
+.L484:
+set Y,%l3
+set One,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set Z,%l3
+set D,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L489:
+set Y,%l3
+set C,%l2
+ld2 [%l3],%f30
+st2 %f30,[%l2]
+set Z,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+ld2 [%l3],%f30
+fmuld %f30,%f30,%f30
+st2 %f30,[%l2]
+.L490:
+set Z,%l3
+ld2 [%l3],%f30
+set Y,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbule .L492; nop
+faddd %f30,%f30,%f28
+fcmped %f28,%f30; nop; fbug .L489; nop
+.L492:
+set Y,%l3
+set C,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set Z,%l2
+ld2 [%l3],%f30
+set D,%l3
+ld2 [%l3],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%l2]
+.L493:
+set Y,%l3
+set C,%l2
+ld2 [%l3],%f30
+st2 %f30,[%l2]
+set Z,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+ld2 [%l3],%f30
+set D,%l3
+ld2 [%l3],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%l2]
+.L494:
+set Z,%l3
+ld2 [%l3],%f30
+set Y,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbule .L496; nop
+faddd %f30,%f30,%f28
+fcmped %f28,%f30; nop; fbug .L493; nop
+.L496:
+set Radix,%l3
+ld2 [%l3],%f30
+set Two,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbuge .L497; nop
+set HInvrse,%l3
+set Two,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+ba .L498; nop
+.L497:
+set HInvrse,%l3
+set Radix,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L498:
+set H,%l3
+set One,%l2
+ld2 [%l2],%f30
+set HInvrse,%l2
+ld2 [%l2],%f28
+fdivd %f30,%f28,%f28
+st2 %f28,[%l3]
+set C,%l2
+ld2 [%l2],%f28
+set CInvrse,%l2
+fdivd %f30,%f28,%f30
+st2 %f30,[%l2]
+set E0,%l2
+st2 %f28,[%l2]
+set Z,%l1
+ld2 [%l2],%f30
+ld2 [%l3],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%l1]
+.L499:
+set E0,%l3
+set Y,%l2
+ld2 [%l3],%f30
+st2 %f30,[%l2]
+set Z,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+ld2 [%l3],%f30
+set H,%l3
+ld2 [%l3],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%l2]
+.L500:
+set Z,%l3
+ld2 [%l3],%f30
+set E0,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbule .L502; nop
+faddd %f30,%f30,%f28
+fcmped %f28,%f30; nop; fbug .L499; nop
+.L502:
+set UfThold,%l3
+set E0,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set Zero,%l3
+ld2 [%l3],%f30
+set E1,%l3
+st2 %f30,[%l3]
+set Q,%l3
+st2 %f30,[%l3]
+set E9,%l3
+set U2,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set S,%l2
+set One,%l1
+ld2 [%l1],%f30
+ld2 [%l3],%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l2]
+set D,%l3
+set C,%l1
+ld2 [%l1],%f30
+ld2 [%l2],%f28
+fmuld %f30,%f28,%f28
+st2 %f28,[%l3]
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbug .L503; nop
+set E9,%l3
+set Radix,%l2
+ld2 [%l2],%f30
+set U2,%l2
+ld2 [%l2],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%l3]
+set S,%l2
+set One,%l1
+ld2 [%l1],%f30
+ld2 [%l3],%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l2]
+set D,%l3
+set C,%l1
+ld2 [%l1],%f30
+ld2 [%l2],%f28
+fmuld %f30,%f28,%f28
+st2 %f28,[%l3]
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbug .L504; nop
+mov %g0,%o0
+set .L507,%o1
+call BadCond; nop
+set Underflow,%l3
+set E0,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set Y1,%l3
+set Zero,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set PseudoZero,%l3
+set Z,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+call Pause; nop
+ba .L504; nop
+.L503:
+set Underflow,%l3
+set D,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set PseudoZero,%l2
+ld2 [%l3],%f30
+set H,%l3
+ld2 [%l3],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%l2]
+set UfThold,%l3
+set Zero,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L508:
+set Underflow,%l3
+set Y1,%l2
+ld2 [%l3],%f30
+st2 %f30,[%l2]
+set PseudoZero,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set E1,%l3
+ld2 [%l3],%f30
+faddd %f30,%f30,%f28
+fcmped %f28,%f30; nop; fbug .L511; nop
+set Y2,%l3
+set Underflow,%l2
+ld2 [%l2],%f30
+set HInvrse,%l2
+ld2 [%l2],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%l3]
+set Y1,%l2
+ld2 [%l2],%f30
+ld2 [%l3],%f28
+fsubd %f30,%f28,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call fabs; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set E1,%l3
+st2 %f30,[%l3]
+set Q,%l3
+set Y1,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set UfThold,%l3
+ld2 [%l3],%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L513; nop
+set Y1,%l3
+ld2 [%l3],%f30
+set Y2,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L513; nop
+set UfThold,%l3
+set Y1,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L513:
+.L511:
+set PseudoZero,%l3
+ld2 [%l3],%f30
+set H,%l2
+ld2 [%l2],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%l3]
+.L509:
+set PseudoZero,%l3
+ld2 [%l3],%f30
+set Underflow,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbule .L515; nop
+faddd %f30,%f30,%f28
+fcmped %f28,%f30; nop; fbug .L508; nop
+.L515:
+.L504:
+set PseudoZero,%l3
+ld2 [%l3],%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L516; nop
+set .L45,%o0
+call printf; nop
+set PseudoZero,%l3
+ld2 [%l3],%f30
+set Z,%l3
+st2 %f30,[%l3]
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbug .L518; nop
+mov %g0,%o0
+set .L520,%o1
+call BadCond; nop
+set .L521,%o0
+call printf; nop
+set .L522,%o0
+set PseudoZero,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set X,%l3
+set PseudoZero,%l2
+ld2 [%l2],%f30
+fnegs %f30,%f30; fmovs %f31,%f31
+st2 %f30,[%l3]
+ld2 [%l3],%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbug .L519; nop
+set .L525,%o0
+call printf; nop
+set .L526,%o0
+set X,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+ba .L519; nop
+.L518:
+set 3,%o0
+set .L527,%o1
+call BadCond; nop
+set .L528,%o0
+set PseudoZero,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+.L519:
+call TstPtUf; nop
+.L516:
+set Milestone,%l3
+set 120,%l2
+st %l2,[%l3]
+set CInvrse,%l3
+ld2 [%l3],%f30
+set Y,%l3
+ld2 [%l3],%f28
+fmuld %f30,%f28,%f28
+set Y1,%l3
+ld2 [%l3],%f26
+fmuld %f30,%f26,%f30
+fcmped %f28,%f30; nop; fbule .L529; nop
+set S,%l3
+set H,%l2
+ld2 [%l2],%f30
+ld2 [%l3],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%l3]
+set E0,%l3
+set Underflow,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L529:
+set E1,%l3
+ld2 [%l3],%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L531; nop
+set E0,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L531; nop
+set 2,%o0
+set .L158,%o1
+call BadCond; nop
+set E1,%l3
+ld2 [%l3],%f30
+set E0,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbuge .L533; nop
+set .L535,%o0
+call printf; nop
+set .L536,%o0
+call printf; nop
+set PseudoZero,%l3
+ld2 [%l3],%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L534; nop
+set E0,%l3
+set E1,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+ba .L534; nop
+.L533:
+set .L539,%o0
+call printf; nop
+set .L540,%o0
+call printf; nop
+.L534:
+.L531:
+set .L541,%o0
+set E0,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set Z,%l3
+set E0,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+call TstPtUf; nop
+set Underflow,%l3
+set E0,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set N,%l3
+ld [%l3],%l3
+cmp %l3,1; bne .L542; nop
+set Underflow,%l3
+set Y,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L542:
+set I,%l3
+set 4,%l2
+st %l2,[%l3]
+set E1,%l3
+ld2 [%l3],%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L544; nop
+set I,%l3
+set 3,%l2
+st %l2,[%l3]
+.L544:
+set UfThold,%l3
+ld2 [%l3],%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L546; nop
+set I,%l3
+ld [%l3],%l2
+sub %l2,2,%l2
+st %l2,[%l3]
+.L546:
+set UfNGrad,%l3
+set 1,%l2
+st %l2,[%l3]
+set I,%l3
+ld [%l3],%l3
+cmp %l3,1; bl .L548; nop
+cmp %l3,4; bg .L548; nop
+sll %l3,2,%l3
+set .L571-4,%l2
+ld [%l3+%l2],%l3
+jmp %l3; nop
+.section ".rodata"
+.align 4
+.L571:
+.word .L550
+.word .L557
+.word .L562
+.word .L563
+.section ".text"
+.L550:
+set UfThold,%l3
+set Underflow,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set CInvrse,%l3
+ld2 [%l3],%f30
+set Q,%l3
+ld2 [%l3],%f28
+fmuld %f30,%f28,%f28
+set Y,%l3
+ld2 [%l3],%f26
+fmuld %f30,%f26,%f30
+set S,%l3
+ld2 [%l3],%f26
+fmuld %f30,%f26,%f30
+fcmped %f28,%f30; nop; fbue .L551; nop
+set UfThold,%l3
+set Y,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+mov %g0,%o0
+set .L553,%o1
+call BadCond; nop
+set .L554,%o0
+set UfThold,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set .L555,%o0
+set C,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set .L556,%o0
+call printf; nop
+.L551:
+call Pause; nop
+ba .L549; nop
+.L557:
+mov %g0,%o0
+set .L558,%o1
+call BadCond; nop
+set .L559,%o0
+call printf; nop
+set .L560,%o0
+set Q,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+set Y2,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*3+68]
+st %f31,[%sp+4*4+68]
+ld [%sp+4*3+68],%o3
+ld [%sp+4*4+68],%o4
+call printf; nop
+set Q,%l3
+ld2 [%l3],%f30
+set Y2,%l3
+ld2 [%l3],%f28
+fsubd %f30,%f28,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call fabs; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set .L561,%o0
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set UfThold,%l3
+set Q,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+ba .L549; nop
+.L562:
+set X,%l3
+ld2 [%l3],%f30
+st2 %f30,[%l3]
+ba .L549; nop
+.L563:
+set UfThold,%l3
+ld2 [%l3],%f30
+set Q,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L564; nop
+set E1,%l3
+ld2 [%l3],%f28
+set E0,%l3
+ld2 [%l3],%f26
+fcmped %f28,%f26; nop; fbne .L564; nop
+set E9,%l3
+ld2 [%l3],%f26
+fdivd %f28,%f26,%f28
+fsubd %f30,%f28,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call fabs; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set E1,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbug .L564; nop
+set UfNGrad,%l3
+st %g0,[%l3]
+set .L566,%o0
+call printf; nop
+set .L567,%o0
+call printf; nop
+set Y,%l3
+set E0,%l2
+ld2 [%l2],%f30
+set CInvrse,%l2
+ld2 [%l2],%f28
+fmuld %f30,%f28,%f26
+st2 %f26,[%l3]
+set U2,%l2
+ld2 [%l2],%f26
+ld2 [%l3],%f24
+set OneAndHalf,%l2
+ld2 [%l2],%f22
+faddd %f22,%f26,%f22
+fmuld %f24,%f22,%f24
+st2 %f24,[%l3]
+set X,%l2
+set One,%l1
+ld2 [%l1],%f24
+faddd %f24,%f26,%f26
+fmuld %f28,%f26,%f28
+st2 %f28,[%l2]
+ld2 [%l3],%f28
+ld2 [%l2],%f26
+fdivd %f28,%f26,%f28
+st2 %f28,[%l3]
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L569; nop
+set 1,%l3
+st %l3,[%fp+-100]
+ba .L570; nop
+.L569:
+st %g0,[%fp+-100]
+.L570:
+set IEEE,%l3
+ld [%fp+-100],%l2
+st %l2,[%l3]
+.L564:
+.L548:
+.L549:
+set UfNGrad,%l3
+ld [%l3],%l3
+cmp %l3,0; be .L573; nop
+set .L45,%o0
+call printf; nop
+set sigsave,%l3
+set sigfpe,%l2
+st %l2,[%l3]
+set ovfl_buf,%o0
+call setjmp; nop
+cmp %o0,0; be .L575; nop
+set .L577,%o0
+call printf; nop
+set H,%l3
+ld2 [%l3],%f30
+set R,%l3
+faddd %f30,%f30,%f30
+st2 %f30,[%l3]
+ba .L576; nop
+.L575:
+set Underflow,%l3
+ld2 [%l3],%f30
+set UfThold,%l3
+ld2 [%l3],%f28
+fdivd %f30,%f28,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call sqrt; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set R,%l3
+st2 %f30,[%l3]
+.L576:
+set sigsave,%l3
+st %g0,[%l3]
+set R,%l3
+ld2 [%l3],%f30
+set H,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbug .L578; nop
+set Z,%l3
+set R,%l2
+ld2 [%l2],%f30
+set UfThold,%l2
+ld2 [%l2],%f28
+fmuld %f30,%f28,%f28
+st2 %f28,[%l3]
+set One,%l2
+ld2 [%l2],%f28
+set H,%l2
+ld2 [%l2],%f26
+set X,%l2
+ld2 [%l3],%f24
+fmuld %f30,%f26,%f30
+faddd %f28,%f26,%f26
+fmuld %f30,%f26,%f30
+faddd %f28,%f30,%f30
+fmuld %f24,%f30,%f30
+st2 %f30,[%l2]
+ba .L579; nop
+.L578:
+set Z,%l3
+set UfThold,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set One,%l2
+ld2 [%l2],%f30
+set H,%l2
+ld2 [%l2],%f28
+set X,%l2
+ld2 [%l3],%f26
+fmuld %f28,%f28,%f24
+faddd %f30,%f28,%f28
+fmuld %f24,%f28,%f28
+faddd %f30,%f28,%f30
+fmuld %f26,%f30,%f30
+st2 %f30,[%l2]
+.L579:
+set X,%l3
+ld2 [%l3],%f30
+set Z,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L580; nop
+fsubd %f30,%f28,%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L580; nop
+set 3,%o0
+set .L158,%o1
+call BadCond; nop
+set .L582,%o0
+set X,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+set Z,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*3+68]
+st %f31,[%sp+4*4+68]
+ld [%sp+4*3+68],%o3
+ld [%sp+4*4+68],%o4
+call printf; nop
+set Z9,%l3
+set X,%l2
+ld2 [%l2],%f30
+set Z,%l2
+ld2 [%l2],%f28
+fsubd %f30,%f28,%f30
+st2 %f30,[%l3]
+set .L583,%o0
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set .L584,%o0
+call printf; nop
+set .L585,%o0
+call printf; nop
+set .L586,%o0
+call printf; nop
+set .L587,%o0
+call printf; nop
+set .L588,%o0
+call printf; nop
+set .L589,%o0
+call printf; nop
+set sigsave,%l3
+set sigfpe,%l2
+st %l2,[%l3]
+set ovfl_buf,%o0
+call setjmp; nop
+cmp %o0,0; be .L590; nop
+set .L592,%o0
+call printf; nop
+ba .L591; nop
+.L590:
+set .L593,%o0
+set Half,%l3
+ld2 [%l3],%f30
+set X,%l3
+ld2 [%l3],%f28
+set Z,%l3
+ld2 [%l3],%f26
+fdivd %f28,%f26,%f28
+fsubd %f28,%f30,%f28
+fsubd %f28,%f30,%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+.L591:
+set sigsave,%l3
+st %g0,[%l3]
+.L580:
+.L573:
+set .L594,%o0
+set UfThold,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+set .L595,%o3
+call printf; nop
+set .L596,%o0
+call printf; nop
+set .L597,%o0
+call printf; nop
+set Y2,%l3
+set U1,%l2
+ld2 [%l2],%f30
+fmuld %f30,%f30,%f28
+st2 %f28,[%l3]
+set Y,%l2
+ld2 [%l3],%f28
+fmuld %f28,%f28,%f28
+st2 %f28,[%l2]
+ld2 [%l2],%f28
+fmuld %f28,%f30,%f30
+st2 %f30,[%l3]
+ld2 [%l3],%f30
+set UfThold,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbug .L598; nop
+set Y,%l3
+ld2 [%l3],%f30
+set E0,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbule .L600; nop
+set 2,%o0
+set .L158,%o1
+call BadCond; nop
+set I,%l3
+set 5,%l2
+st %l2,[%l3]
+ba .L601; nop
+.L600:
+set 1,%o0
+set .L158,%o1
+call BadCond; nop
+set I,%l3
+set 4,%l2
+st %l2,[%l3]
+.L601:
+set .L602,%o0
+set I,%l3
+ld [%l3],%o1
+call printf; nop
+.L598:
+set Milestone,%l3
+set 130,%l2
+st %l2,[%l3]
+set UfThold,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call log; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+std %f30,[%fp+-104]
+set HInvrse,%l3
+ld2 [%l3],%f28
+st %f28,[%sp+4*0+68]
+st %f29,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call log; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Half,%l3
+ld2 [%l3],%f28
+set TwoForty,%l3
+ld2 [%l3],%f26
+ldd [%fp+-104],%f24
+fmuld %f26,%f24,%f26
+fdivd %f26,%f30,%f30
+fsubd %f28,%f30,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call floor; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Y,%l3
+fnegs %f30,%f30; fmovs %f31,%f31
+set TwoForty,%l2
+ld2 [%l2],%f28
+fdivd %f30,%f28,%f30
+st2 %f30,[%l3]
+set Y,%l3
+ld2 [%l3],%f30
+set Y2,%l3
+faddd %f30,%f30,%f30
+st2 %f30,[%l3]
+set .L603,%o0
+call printf; nop
+set .L604,%o0
+set HInvrse,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+set Y,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*3+68]
+st %f31,[%sp+4*4+68]
+ld [%sp+4*3+68],%o3
+ld [%sp+4*4+68],%o4
+call printf; nop
+set .L605,%o0
+set HInvrse,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+set Y,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*3+68]
+st %f31,[%sp+4*4+68]
+ld [%sp+4*3+68],%o3
+ld [%sp+4*4+68],%o4
+call printf; nop
+set HInvrse,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+set Y2,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*2+68]
+st %f31,[%sp+4*3+68]
+ld [%sp+4*2+68],%o2
+ld [%sp+4*3+68],%o3
+call pow; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set V9,%l3
+st2 %f30,[%l3]
+set .L606,%o0
+set V9,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set V9,%l3
+ld2 [%l3],%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbul .L609; nop
+set Radix,%l3
+ld2 [%l3],%f28
+faddd %f28,%f28,%f28
+set E9,%l3
+ld2 [%l3],%f26
+faddd %f28,%f26,%f28
+set UfThold,%l3
+ld2 [%l3],%f26
+fmuld %f28,%f26,%f28
+fcmped %f30,%f28; nop; fbule .L607; nop
+.L609:
+set 1,%o0
+set .L610,%o1
+call BadCond; nop
+set .L611,%o0
+set UfThold,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+ba .L608; nop
+.L607:
+set V9,%l3
+ld2 [%l3],%f30
+set UfThold,%l3
+ld2 [%l3],%f28
+set One,%l3
+ld2 [%l3],%f26
+set E9,%l3
+ld2 [%l3],%f24
+faddd %f26,%f24,%f26
+fmuld %f28,%f26,%f28
+fcmped %f30,%f28; nop; fbug .L612; nop
+set .L614,%o0
+call printf; nop
+ba .L613; nop
+.L612:
+set 2,%o0
+set .L610,%o1
+call BadCond; nop
+set .L611,%o0
+set UfThold,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+.L613:
+.L608:
+set Milestone,%l3
+set 140,%l2
+st %l2,[%l3]
+set .L45,%o0
+call printf; nop
+set Zero,%l3
+ld2 [%l3],%f30
+set X,%l3
+st2 %f30,[%l3]
+set I,%l3
+set 2,%l2
+st %l2,[%l3]
+set Y,%l3
+set Two,%l2
+ld2 [%l2],%f28
+set Three,%l2
+ld2 [%l2],%f26
+fmuld %f28,%f26,%f28
+st2 %f28,[%l3]
+set Q,%l3
+st2 %f30,[%l3]
+set N,%l3
+st %g0,[%l3]
+.L615:
+set Z,%l3
+set X,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set I,%l1
+ld [%l1],%l0
+add %l0,1,%l0
+st %l0,[%l1]
+set Y,%l0
+ld [%l1],%l1
+ld2 [%l0],%f30
+add %l1,%l1,%l1
+st %l1,[%sp+64]; ld [%sp+64],%f28; fitod %f28,%f28
+fdivd %f30,%f28,%f30
+st2 %f30,[%l0]
+set R,%l1
+set Q,%o5
+ld2 [%l0],%f30
+ld2 [%o5],%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l1]
+ld2 [%l3],%f30
+ld2 [%l1],%f28
+faddd %f30,%f28,%f26
+st2 %f26,[%l2]
+ld2 [%l2],%f26
+fsubd %f30,%f26,%f30
+faddd %f30,%f28,%f30
+st2 %f30,[%o5]
+.L616:
+set X,%l3
+ld2 [%l3],%f30
+set Z,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbug .L615; nop
+set Z,%l3
+set OneAndHalf,%l2
+ld2 [%l2],%f30
+set X,%l2
+set One,%l1
+ld2 [%l1],%f28
+set Eight,%l1
+ld2 [%l1],%f26
+fdivd %f28,%f26,%f28
+faddd %f30,%f28,%f28
+ld2 [%l2],%f26
+set ThirtyTwo,%l1
+ld2 [%l1],%f24
+fmuld %f30,%f24,%f30
+fdivd %f26,%f30,%f30
+faddd %f28,%f30,%f30
+st2 %f30,[%l3]
+ld2 [%l3],%f30
+fmuld %f30,%f30,%f30
+st2 %f30,[%l2]
+set Exp2,%l3
+ld2 [%l2],%f30
+fmuld %f30,%f30,%f30
+st2 %f30,[%l3]
+set F9,%l1
+ld2 [%l1],%f30
+st2 %f30,[%l2]
+set Y,%l1
+ld2 [%l2],%f30
+set U1,%l2
+ld2 [%l2],%f28
+fsubd %f30,%f28,%f30
+st2 %f30,[%l1]
+set .L618,%o0
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set I,%l3
+set 1,%l2
+st %l2,[%l3]
+.L619:
+set Z,%l3
+set X,%l2
+ld2 [%l2],%f30
+set BInvrse,%l2
+ld2 [%l2],%f28
+fsubd %f30,%f28,%f26
+st2 %f26,[%l3]
+set One,%l2
+ld2 [%l2],%f26
+faddd %f30,%f26,%f24
+ld2 [%l3],%f22
+fsubd %f26,%f28,%f28
+fsubd %f22,%f28,%f28
+fdivd %f24,%f28,%f28
+st2 %f28,[%l3]
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+ld2 [%l3],%f30
+st %f30,[%sp+4*2+68]
+st %f31,[%sp+4*3+68]
+ld [%sp+4*2+68],%o2
+ld [%sp+4*3+68],%o3
+call pow; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Q,%l3
+set Exp2,%l2
+ld2 [%l2],%f28
+fsubd %f30,%f28,%f30
+st2 %f30,[%l3]
+set Q,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call fabs; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set TwoForty,%l3
+ld2 [%l3],%f28
+set U2,%l3
+ld2 [%l3],%f26
+fmuld %f28,%f26,%f28
+fcmped %f30,%f28; nop; fbule .L623; nop
+set N,%l3
+set 1,%l2
+st %l2,[%l3]
+set BInvrse,%l3
+ld2 [%l3],%f30
+set V9,%l3
+set X,%l2
+ld2 [%l2],%f28
+fsubd %f28,%f30,%f28
+set One,%l2
+ld2 [%l2],%f26
+fsubd %f26,%f30,%f30
+fsubd %f28,%f30,%f30
+st2 %f30,[%l3]
+set 2,%o0
+set .L625,%o1
+call BadCond; nop
+set X,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+set Z,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*2+68]
+st %f31,[%sp+4*3+68]
+ld [%sp+4*2+68],%o2
+ld [%sp+4*3+68],%o3
+call pow; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set .L626,%o0
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set .L627,%o0
+set V9,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+set Z,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*3+68]
+st %f31,[%sp+4*4+68]
+ld [%sp+4*3+68],%o3
+ld [%sp+4*4+68],%o4
+call printf; nop
+set .L628,%o0
+set Q,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set .L629,%o0
+call printf; nop
+set .L630,%o0
+call printf; nop
+ba .L621; nop
+.L623:
+set Z,%l3
+set Y,%l2
+ld2 [%l2],%f30
+set X,%l1
+ld2 [%l1],%f28
+fsubd %f30,%f28,%f28
+set Two,%l0
+ld2 [%l0],%f26
+fmuld %f28,%f26,%f28
+faddd %f28,%f30,%f28
+st2 %f28,[%l3]
+st2 %f30,[%l1]
+ld2 [%l3],%f30
+st2 %f30,[%l2]
+ld2 [%l1],%f30
+set F9,%l2
+ld2 [%l2],%f28
+fsubd %f30,%f28,%f30
+set One,%l2
+ld2 [%l2],%f28
+fmuld %f30,%f30,%f30
+faddd %f28,%f30,%f30
+st2 %f30,[%l3]
+set Z,%l3
+ld2 [%l3],%f30
+set One,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbule .L631; nop
+set I,%l3
+ld [%l3],%l3
+set NoTrials,%l2
+ld [%l2],%l2
+cmp %l3,%l2; bge .L631; nop
+set I,%l3
+ld [%l3],%l2
+add %l2,1,%l2
+st %l2,[%l3]
+ba .L619; nop
+.L631:
+set X,%l3
+ld2 [%l3],%f30
+set One,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbule .L633; nop
+set N,%l3
+ld [%l3],%l3
+cmp %l3,0; bne .L621; nop
+set .L637,%o0
+call printf; nop
+ba .L621; nop
+.L633:
+set X,%l3
+set U2,%l2
+ld2 [%l2],%f30
+set One,%l2
+ld2 [%l2],%f28
+faddd %f28,%f30,%f28
+st2 %f28,[%l3]
+set Y,%l2
+faddd %f30,%f30,%f30
+st2 %f30,[%l2]
+ld2 [%l2],%f30
+ld2 [%l3],%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l2]
+set I,%l3
+set 1,%l2
+st %l2,[%l3]
+ba .L619; nop
+.L621:
+set Milestone,%l3
+set 150,%l2
+st %l2,[%l3]
+set .L638,%o0
+call printf; nop
+set N,%l3
+st %g0,[%l3]
+set Z,%l3
+set A1,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set C,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call log; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+std %f30,[%fp+-112]
+set A1,%l3
+ld2 [%l3],%f28
+st %f28,[%sp+4*0+68]
+st %f29,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call log; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Half,%l3
+ld2 [%l3],%f28
+ldd [%fp+-112],%f26
+fdivd %f26,%f30,%f30
+fsubd %f28,%f30,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call floor; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Q,%l3
+st2 %f30,[%l3]
+set Break,%l3
+st %g0,[%l3]
+.L639:
+set X,%l3
+set CInvrse,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set Z,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+set Q,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*2+68]
+st %f31,[%sp+4*3+68]
+ld [%sp+4*2+68],%o2
+ld [%sp+4*3+68],%o3
+call pow; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Y,%l3
+st2 %f30,[%l3]
+call IsYeqX; nop
+set Q,%l3
+ld2 [%l3],%f30
+fnegs %f30,%f30; fmovs %f31,%f31
+st2 %f30,[%l3]
+set X,%l2
+set C,%l1
+ld2 [%l1],%f30
+st2 %f30,[%l2]
+set Z,%l2
+ld2 [%l2],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+ld2 [%l3],%f30
+st %f30,[%sp+4*2+68]
+st %f31,[%sp+4*3+68]
+ld [%sp+4*2+68],%o2
+ld [%sp+4*3+68],%o3
+call pow; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Y,%l3
+st2 %f30,[%l3]
+call IsYeqX; nop
+set Z,%l3
+ld2 [%l3],%f30
+set One,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbuge .L642; nop
+set Break,%l3
+set 1,%l2
+st %l2,[%l3]
+ba .L643; nop
+.L642:
+set Z,%l3
+set AInvrse,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L643:
+.L640:
+set Break,%l3
+ld [%l3],%l3
+cmp %l3,0; be .L639; nop
+call PrintIfNPositive; nop
+set N,%l3
+ld [%l3],%l3
+cmp %l3,0; bne .L644; nop
+set .L646,%o0
+call printf; nop
+.L644:
+set .L45,%o0
+call printf; nop
+set Milestone,%l3
+set 160,%l2
+st %l2,[%l3]
+call Pause; nop
+set .L647,%o0
+call printf; nop
+set .L648,%o0
+call printf; nop
+set Y,%l3
+set CInvrse,%l2
+ld2 [%l2],%f30
+fnegs %f30,%f30; fmovs %f31,%f31
+st2 %f30,[%l3]
+set V9,%l2
+set HInvrse,%l1
+ld2 [%l1],%f30
+ld2 [%l3],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%l2]
+set sigsave,%l3
+set sigfpe,%l2
+st %l2,[%l3]
+set ovfl_buf,%o0
+call setjmp; nop
+cmp %o0,0; be .L649; nop
+set I,%l3
+st %g0,[%l3]
+set V9,%l3
+set Y,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+ba .L651; nop
+.L649:
+.L652:
+set Y,%l3
+set V,%l2
+ld2 [%l3],%f30
+st2 %f30,[%l2]
+set V9,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set HInvrse,%l1
+ld2 [%l1],%f30
+ld2 [%l3],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%l2]
+.L653:
+set V9,%l3
+ld2 [%l3],%f30
+set Y,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbul .L652; nop
+set I,%l3
+set 1,%l2
+st %l2,[%l3]
+.L651:
+set sigsave,%l3
+st %g0,[%l3]
+set Z,%l3
+set V9,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set .L655,%o0
+call printf; nop
+set .L656,%o0
+set Y,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set V9,%l3
+set Y,%l2
+ld2 [%l2],%f30
+fnegs %f30,%f28; fmovs %f31,%f29
+st2 %f28,[%l3]
+set V0,%l2
+ld2 [%l3],%f28
+st2 %f28,[%l2]
+set V,%l3
+ld2 [%l3],%f28
+fsubd %f28,%f30,%f30
+ld2 [%l2],%f26
+faddd %f28,%f26,%f28
+fcmped %f30,%f28; nop; fbne .L657; nop
+set .L659,%o0
+call printf; nop
+ba .L658; nop
+.L657:
+set .L660,%o0
+call printf; nop
+set 3,%o0
+set .L661,%o1
+call BadCond; nop
+.L658:
+set Z,%l3
+ld2 [%l3],%f30
+set Y,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L662; nop
+set 1,%o0
+set .L158,%o1
+call BadCond; nop
+set .L664,%o0
+set Y,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+set Z,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*3+68]
+st %f31,[%sp+4*4+68]
+ld [%sp+4*3+68],%o3
+ld [%sp+4*4+68],%o4
+call printf; nop
+.L662:
+set I,%l3
+ld [%l3],%l3
+cmp %l3,0; be .L665; nop
+set Y,%l3
+set V,%l2
+ld2 [%l2],%f30
+set HInvrse,%l2
+ld2 [%l2],%f28
+set U2,%l2
+ld2 [%l2],%f26
+fmuld %f28,%f26,%f24
+fsubd %f24,%f28,%f24
+fmuld %f30,%f24,%f24
+st2 %f24,[%l3]
+set Z,%l2
+ld2 [%l3],%f24
+set One,%l3
+ld2 [%l3],%f22
+fsubd %f22,%f28,%f28
+fmuld %f28,%f26,%f28
+fmuld %f28,%f30,%f30
+faddd %f24,%f30,%f30
+st2 %f30,[%l2]
+ld2 [%l2],%f30
+set V0,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbuge .L667; nop
+set Y,%l3
+set Z,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L667:
+set Y,%l3
+ld2 [%l3],%f30
+set V0,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbuge .L669; nop
+set V,%l3
+set Y,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L669:
+set V0,%l3
+ld2 [%l3],%f30
+set V,%l3
+ld2 [%l3],%f28
+fsubd %f30,%f28,%f28
+fcmped %f28,%f30; nop; fbuge .L666; nop
+set V,%l3
+set V0,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+ba .L666; nop
+.L665:
+set V,%l3
+set Y,%l2
+ld2 [%l2],%f30
+set HInvrse,%l2
+ld2 [%l2],%f28
+set U2,%l2
+ld2 [%l2],%f26
+fmuld %f28,%f26,%f24
+fsubd %f24,%f28,%f24
+fmuld %f30,%f24,%f24
+st2 %f24,[%l3]
+ld2 [%l3],%f24
+set One,%l2
+ld2 [%l2],%f22
+fsubd %f22,%f28,%f28
+fmuld %f28,%f26,%f28
+fmuld %f28,%f30,%f30
+faddd %f24,%f30,%f30
+st2 %f30,[%l3]
+.L666:
+set .L673,%o0
+set V,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set I,%l3
+ld [%l3],%l3
+cmp %l3,0; be .L674; nop
+set .L676,%o0
+set V0,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+ba .L675; nop
+.L674:
+set .L677,%o0
+call printf; nop
+.L675:
+set V9,%l3
+set V,%l2
+ld2 [%l2],%f30
+set One,%l2
+ld2 [%l2],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%l3]
+set .L678,%o0
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set V9,%l3
+set V,%l2
+ld2 [%l2],%f30
+set One,%l2
+ld2 [%l2],%f28
+fdivd %f30,%f28,%f30
+st2 %f30,[%l3]
+set .L679,%o0
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set .L680,%o0
+call printf; nop
+set .L681,%o0
+call printf; nop
+set Milestone,%l3
+set 170,%l2
+st %l2,[%l3]
+set V,%l3
+ld2 [%l3],%f30
+fnegs %f30,%f28; fmovs %f31,%f29
+fcmped %f28,%f30; nop; fbuge .L686; nop
+set V0,%l3
+ld2 [%l3],%f28
+fnegs %f28,%f26; fmovs %f29,%f27
+fcmped %f26,%f28; nop; fbuge .L686; nop
+set UfThold,%l3
+ld2 [%l3],%f28
+fnegs %f28,%f26; fmovs %f29,%f27
+fcmped %f26,%f30; nop; fbuge .L686; nop
+fcmped %f28,%f30; nop; fbul .L682; nop
+.L686:
+mov %g0,%o0
+set .L687,%o1
+call BadCond; nop
+set .L688,%o0
+set V,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+set V0,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*3+68]
+st %f31,[%sp+4*4+68]
+ld [%sp+4*3+68],%o3
+ld [%sp+4*4+68],%o4
+set UfThold,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*5+68]
+st %f31,[%sp+4*6+68]
+ld [%sp+4*5+68],%o5
+call printf; nop
+.L682:
+set Milestone,%l3
+set 175,%l2
+st %l2,[%l3]
+set .L45,%o0
+call printf; nop
+set Indx,%l3
+set 1,%l2
+st %l2,[%l3]
+.L689:
+set Indx,%l3
+ld [%l3],%l3
+cmp %l3,1; be .L695; nop
+cmp %l3,2; be .L696; nop
+cmp %l3,3; be .L697; nop
+ba .L693; nop
+.L695:
+set Z,%l3
+set UfThold,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+ba .L694; nop
+.L696:
+set Z,%l3
+set E0,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+ba .L694; nop
+.L697:
+set Z,%l3
+set PseudoZero,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L693:
+.L694:
+set Z,%l3
+ld2 [%l3],%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbue .L698; nop
+set Z,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call sqrt; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set V9,%l3
+st2 %f30,[%l3]
+set V9,%l3
+ld2 [%l3],%f30
+set Y,%l3
+fmuld %f30,%f30,%f30
+st2 %f30,[%l3]
+set Y,%l3
+ld2 [%l3],%f30
+set One,%l3
+ld2 [%l3],%f28
+set Radix,%l3
+ld2 [%l3],%f26
+set E9,%l3
+ld2 [%l3],%f24
+fmuld %f26,%f24,%f26
+set Z,%l3
+ld2 [%l3],%f24
+fsubd %f28,%f26,%f22
+fdivd %f30,%f22,%f22
+fcmped %f22,%f24; nop; fbul .L702; nop
+faddd %f28,%f26,%f28
+fmuld %f28,%f24,%f28
+fcmped %f30,%f28; nop; fbule .L700; nop
+.L702:
+set V9,%l3
+ld2 [%l3],%f30
+set U1,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbule .L703; nop
+set 1,%o0
+set .L158,%o1
+call BadCond; nop
+ba .L704; nop
+.L703:
+set 2,%o0
+set .L158,%o1
+call BadCond; nop
+.L704:
+set .L705,%o0
+set Z,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set .L706,%o0
+set Y,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+.L700:
+.L698:
+.L690:
+set Indx,%l3
+ld [%l3],%l2
+add %l2,1,%l2
+st %l2,[%l3]
+set Indx,%l3
+ld [%l3],%l3
+cmp %l3,3; ble .L689; nop
+set Milestone,%l3
+set 180,%l2
+st %l2,[%l3]
+set Indx,%l3
+set 1,%l2
+st %l2,[%l3]
+.L707:
+set Indx,%l3
+ld [%l3],%l3
+cmp %l3,1; bne .L711; nop
+set Z,%l3
+set V,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+ba .L712; nop
+.L711:
+set Z,%l3
+set V0,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L712:
+set Z,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call sqrt; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set V9,%l3
+st2 %f30,[%l3]
+set X,%l3
+set V9,%l2
+ld2 [%l2],%f30
+set One,%l1
+ld2 [%l1],%f28
+set Radix,%l1
+ld2 [%l1],%f26
+set E9,%l1
+ld2 [%l1],%f24
+fmuld %f26,%f24,%f26
+fsubd %f28,%f26,%f28
+fmuld %f28,%f30,%f28
+st2 %f28,[%l3]
+ld2 [%l3],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%l2]
+set V9,%l3
+ld2 [%l3],%f30
+set Z,%l3
+ld2 [%l3],%f28
+set One,%l3
+ld2 [%l3],%f26
+set Two,%l3
+ld2 [%l3],%f24
+set Radix,%l3
+ld2 [%l3],%f22
+fmuld %f24,%f22,%f24
+set E9,%l3
+ld2 [%l3],%f22
+fmuld %f24,%f22,%f24
+fsubd %f26,%f24,%f26
+fmuld %f26,%f28,%f26
+fcmped %f30,%f26; nop; fbul .L715; nop
+fcmped %f30,%f28; nop; fbule .L713; nop
+.L715:
+set Y,%l3
+set V9,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set X,%l3
+ld2 [%l3],%f30
+set W,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbuge .L716; nop
+set 1,%o0
+set .L158,%o1
+call BadCond; nop
+ba .L717; nop
+.L716:
+set 2,%o0
+set .L158,%o1
+call BadCond; nop
+.L717:
+set .L718,%o0
+set Z,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set .L719,%o0
+set Y,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+.L713:
+.L708:
+set Indx,%l3
+ld [%l3],%l2
+add %l2,1,%l2
+st %l2,[%l3]
+set Indx,%l3
+ld [%l3],%l3
+cmp %l3,2; ble .L707; nop
+set Milestone,%l3
+set 190,%l2
+st %l2,[%l3]
+call Pause; nop
+set X,%l3
+set UfThold,%l2
+ld2 [%l2],%f30
+set V,%l2
+ld2 [%l2],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%l3]
+set Radix,%l3
+ld2 [%l3],%f30
+set Y,%l3
+fmuld %f30,%f30,%f30
+st2 %f30,[%l3]
+set X,%l3
+ld2 [%l3],%f30
+set Y,%l3
+ld2 [%l3],%f28
+fmuld %f30,%f28,%f26
+set One,%l3
+ld2 [%l3],%f24
+fcmped %f26,%f24; nop; fbul .L722; nop
+fcmped %f30,%f28; nop; fbule .L720; nop
+.L722:
+set X,%l3
+ld2 [%l3],%f30
+set Y,%l3
+ld2 [%l3],%f28
+set U1,%l3
+ld2 [%l3],%f26
+fmuld %f30,%f28,%f24
+fcmped %f24,%f26; nop; fbul .L725; nop
+fdivd %f28,%f26,%f28
+fcmped %f30,%f28; nop; fbule .L723; nop
+.L725:
+set 2,%o0
+set .L726,%o1
+call BadCond; nop
+ba .L724; nop
+.L723:
+set 3,%o0
+set .L158,%o1
+call BadCond; nop
+.L724:
+set .L727,%o0
+set X,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+set .L728,%o3
+call printf; nop
+.L720:
+set Milestone,%l3
+set 200,%l2
+st %l2,[%l3]
+set Indx,%l3
+set 1,%l2
+st %l2,[%l3]
+.L729:
+set X,%l3
+set F9,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set Indx,%l3
+ld [%l3],%l3
+cmp %l3,2; bl .L733; nop
+cmp %l3,5; bg .L733; nop
+sll %l3,2,%l3
+set .L739-8,%l2
+ld [%l3+%l2],%l3
+jmp %l3; nop
+.section ".rodata"
+.align 4
+.L739:
+.word .L735
+.word .L736
+.word .L737
+.word .L738
+.section ".text"
+.L735:
+set X,%l3
+set One,%l2
+ld2 [%l2],%f30
+set U2,%l2
+ld2 [%l2],%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%l3]
+ba .L734; nop
+.L736:
+set X,%l3
+set V,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+ba .L734; nop
+.L737:
+set X,%l3
+set UfThold,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+ba .L734; nop
+.L738:
+set X,%l3
+set Radix,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+.L733:
+.L734:
+set Y,%l3
+set X,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set sigsave,%l3
+set sigfpe,%l2
+st %l2,[%l3]
+set ovfl_buf,%o0
+call setjmp; nop
+cmp %o0,0; be .L741; nop
+set .L743,%o0
+set X,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+ba .L742; nop
+.L741:
+set V9,%l3
+set Half,%l2
+ld2 [%l2],%f30
+set Y,%l2
+ld2 [%l2],%f28
+set X,%l2
+ld2 [%l2],%f26
+fdivd %f28,%f26,%f28
+fsubd %f28,%f30,%f28
+fsubd %f28,%f30,%f30
+st2 %f30,[%l3]
+ld2 [%l3],%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L744; nop
+ba .L730; nop
+.L744:
+set V9,%l3
+ld2 [%l3],%f30
+set U1,%l3
+ld2 [%l3],%f28
+fnegs %f28,%f28; fmovs %f29,%f29
+fcmped %f30,%f28; nop; fbne .L746; nop
+set Indx,%l3
+ld [%l3],%l3
+cmp %l3,5; bge .L746; nop
+set 3,%o0
+set .L158,%o1
+call BadCond; nop
+ba .L747; nop
+.L746:
+set 1,%o0
+set .L158,%o1
+call BadCond; nop
+.L747:
+set .L748,%o0
+set X,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set .L749,%o0
+set V9,%l3
+ld2 [%l3],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+.L742:
+set sigsave,%l3
+st %g0,[%l3]
+.L730:
+set Indx,%l3
+ld [%l3],%l2
+add %l2,1,%l2
+st %l2,[%l3]
+set Indx,%l3
+ld [%l3],%l3
+cmp %l3,5; ble .L729; nop
+set Milestone,%l3
+set 210,%l2
+st %l2,[%l3]
+set MyZero,%l3
+set Zero,%l2
+ld2 [%l2],%f30
+st2 %f30,[%l3]
+set .L45,%o0
+call printf; nop
+set .L750,%o0
+call printf; nop
+set sigsave,%l3
+set sigfpe,%l2
+st %l2,[%l3]
+set .L751,%o0
+call printf; nop
+set ovfl_buf,%o0
+call setjmp; nop
+cmp %o0,0; bne .L752; nop
+set .L754,%o0
+set One,%l3
+ld2 [%l3],%f30
+set MyZero,%l3
+ld2 [%l3],%f28
+fdivd %f30,%f28,%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+.L752:
+set sigsave,%l3
+st %g0,[%l3]
+set sigfpe,%l2
+st %l2,[%l3]
+set .L755,%o0
+call printf; nop
+set ovfl_buf,%o0
+call setjmp; nop
+cmp %o0,0; bne .L756; nop
+set .L754,%o0
+set Zero,%l3
+ld2 [%l3],%f30
+set MyZero,%l3
+ld2 [%l3],%f28
+fdivd %f30,%f28,%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+.L756:
+set sigsave,%l3
+st %g0,[%l3]
+set Milestone,%l3
+set 220,%l2
+st %l2,[%l3]
+call Pause; nop
+set .L45,%o0
+call printf; nop
+st %g0,[%fp+-116]
+.L763:
+ld [%fp+-116],%l3
+sll %l3,2,%l3
+set ErrCnt,%l2
+ld [%l3+%l2],%l3
+cmp %l3,0; be .L767; nop
+set .L769,%o0
+ld [%fp+-116],%l3
+sll %l3,2,%l3
+set .758,%l2
+ld [%l3+%l2],%o1
+set ErrCnt,%l2
+ld [%l3+%l2],%o2
+call printf; nop
+.L767:
+.L764:
+ld [%fp+-116],%l3
+add %l3,1,%l3
+st %l3,[%fp+-116]
+ld [%fp+-116],%l3
+cmp %l3,4; bl .L763; nop
+set .L45,%o0
+call printf; nop
+set ErrCnt,%l3
+ld [%l3],%l3
+set ErrCnt+4,%l2
+ld [%l2],%l2
+add %l3,%l2,%l3
+set ErrCnt+8,%l2
+ld [%l2],%l2
+add %l3,%l2,%l3
+set ErrCnt+12,%l2
+ld [%l2],%l2
+add %l3,%l2,%l3
+cmp %l3,0; ble .L770; nop
+set ErrCnt,%l2
+ld [%l2],%l2
+set ErrCnt+4,%l1
+ld [%l1],%l1
+add %l2,%l1,%l2
+set ErrCnt+8,%l1
+ld [%l1],%l1
+add %l2,%l1,%l2
+cmp %l2,%g0; bne .L775; nop
+set ErrCnt+12,%l2
+ld [%l2],%l2
+cmp %l2,%g0; ble .L775; nop
+set .L780,%o0
+call printf; nop
+set .L781,%o0
+call printf; nop
+.L775:
+set ErrCnt,%l2
+ld [%l2],%l2
+set ErrCnt+4,%l1
+ld [%l1],%l1
+add %l2,%l1,%l2
+cmp %l2,%g0; bne .L782; nop
+set ErrCnt+8,%l2
+ld [%l2],%l2
+cmp %l2,%g0; ble .L782; nop
+set .L786,%o0
+call printf; nop
+set .L787,%o0
+call printf; nop
+.L782:
+set ErrCnt,%l3
+ld [%l3],%l3
+set ErrCnt+4,%l2
+ld [%l2],%l2
+add %l3,%l2,%l3
+cmp %l3,0; ble .L788; nop
+set .L791,%o0
+call printf; nop
+set .L792,%o0
+call printf; nop
+.L788:
+set ErrCnt,%l3
+ld [%l3],%l3
+cmp %l3,0; ble .L771; nop
+set .L795,%o0
+call printf; nop
+set .L796,%o0
+call printf; nop
+ba .L771; nop
+.L770:
+set .L797,%o0
+call printf; nop
+set RMult,%l3
+ld [%l3],%l3
+cmp %l3,1; bne .L802; nop
+set RDiv,%l3
+ld [%l3],%l3
+cmp %l3,1; bne .L802; nop
+set RAddSub,%l3
+ld [%l3],%l3
+cmp %l3,1; bne .L802; nop
+set RSqrt,%l3
+ld [%l3],%l3
+cmp %l3,1; be .L798; nop
+.L802:
+set .L803,%o0
+call printf; nop
+ba .L799; nop
+.L798:
+set One,%l3
+ld2 [%l3],%f30
+set StickyBit,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbul .L804; nop
+set Radix,%l3
+ld2 [%l3],%f28
+set Two,%l3
+ld2 [%l3],%f26
+fsubd %f28,%f26,%f26
+set Nine,%l3
+ld2 [%l3],%f24
+fsubd %f28,%f24,%f28
+fsubd %f28,%f30,%f30
+fmuld %f26,%f30,%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L804; nop
+set .L806,%o0
+call printf; nop
+set .L807,%o0
+call printf; nop
+set Two,%l3
+ld2 [%l3],%f30
+set Radix,%l3
+ld2 [%l3],%f28
+fcmped %f28,%f30; nop; fbne .L808; nop
+set Precision,%l3
+ld2 [%l3],%f28
+set TwentySeven,%l3
+ld2 [%l3],%f26
+set Four,%l3
+ld2 [%l3],%f24
+set Three,%l3
+ld2 [%l3],%f22
+fmuld %f24,%f22,%f24
+fmuld %f24,%f30,%f30
+fsubd %f28,%f30,%f30
+fsubd %f28,%f26,%f28
+fsubd %f28,%f26,%f28
+set One,%l3
+ld2 [%l3],%f26
+faddd %f28,%f26,%f28
+fmuld %f30,%f28,%f30
+set Zero,%l3
+ld2 [%l3],%f28
+fcmped %f30,%f28; nop; fbne .L808; nop
+set .L810,%o0
+call printf; nop
+ba .L809; nop
+.L808:
+set .L811,%o0
+call printf; nop
+.L809:
+set IEEE,%l3
+ld [%l3],%l3
+cmp %l3,0; be .L812; nop
+set .L814,%o0
+call printf; nop
+ba .L813; nop
+.L812:
+set .L815,%o0
+call printf; nop
+set .L816,%o0
+call printf; nop
+.L813:
+.L804:
+set .L817,%o0
+call printf; nop
+.L799:
+.L771:
+set fpecount,%l3
+ld [%l3],%l3
+cmp %l3,0; be .L818; nop
+set .L820,%o0
+set fpecount,%l3
+ld [%l3],%o1
+call printf; nop
+.L818:
+set .L821,%o0
+call printf; nop
+mov %g0,%i0
+.L7:
+ret; restore
+.type main,#function
+.size main,.-main
+.global Sign
+.align 4
+Sign:
+save %sp,-104,%sp
+st %r24,[%fp+68]
+st %r25,[%fp+72]
+ld2 [%fp+68],%f30
+set .L8,%i5
+ld2 [%i5],%f28
+fcmped %f30,%f28; nop; fbul .L824; nop
+set .L9,%i5
+ld2 [%i5],%f30
+std %f30,[%fp+-8]
+ba .L825; nop
+.L824:
+set .L826,%i5
+ld2 [%i5],%f30
+std %f30,[%fp+-8]
+.L825:
+ldd [%fp+-8],%f0
+.L822:
+ret; restore
+.type Sign,#function
+.size Sign,.-Sign
+.global Pause
+.align 4
+Pause:
+save %sp,-96,%sp
+set .L828,%o0
+set Milestone,%i5
+ld [%i5],%o1
+call printf; nop
+set .L829,%o0
+set PageNo,%i5
+ld [%i5],%o1
+call printf; nop
+set Milestone,%i5
+ld [%i5],%i4
+add %i4,1,%i4
+st %i4,[%i5]
+set PageNo,%i5
+ld [%i5],%i4
+add %i4,1,%i4
+st %i4,[%i5]
+mov %g0,%i0
+.L827:
+ret; restore
+.type Pause,#function
+.size Pause,.-Pause
+.global TstCond
+.align 4
+TstCond:
+save %sp,-96,%sp
+cmp %i1,0; bne .L831; nop
+mov %i0,%o0
+mov %i2,%o1
+call BadCond; nop
+set .L814,%o0
+call printf; nop
+.L831:
+mov %g0,%i0
+.L830:
+ret; restore
+.type TstCond,#function
+.size TstCond,.-TstCond
+.section ".data"
+.type .834,#object
+.align 4
+.834:
+.word .L835
+.word .L836
+.word .L837
+.word .L838
+.size .834,16
+.global BadCond
+.section ".text"
+.align 4
+BadCond:
+save %sp,-96,%sp
+sll %i0,2,%i5
+set ErrCnt,%i4
+add %i5,%i4,%i5
+ld [%i5],%i4
+add %i4,1,%i4
+st %i4,[%i5]
+set .L839,%o0
+sll %i0,2,%i5
+set .834,%i4
+ld [%i5+%i4],%o1
+mov %i1,%o2
+call printf; nop
+mov %g0,%i0
+.L833:
+ret; restore
+.type BadCond,#function
+.size BadCond,.-BadCond
+.global Random
+.align 4
+Random:
+save %sp,-120,%sp
+set Random1,%i5
+ld2 [%i5],%f30
+set Random9,%i5
+ld2 [%i5],%f28
+faddd %f30,%f28,%f30
+std %f30,[%fp+-8]
+ldd [%fp+-8],%f30
+fmuld %f30,%f30,%f28
+std %f28,[%fp+-16]
+ldd [%fp+-16],%f28
+fmuld %f28,%f28,%f28
+std %f28,[%fp+-16]
+ldd [%fp+-16],%f28
+fmuld %f30,%f28,%f30
+std %f30,[%fp+-8]
+ldd [%fp+-8],%f30
+std %f30,[%fp+-24]
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call floor; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+ldd [%fp+-24],%f28
+fsubd %f28,%f30,%f30
+std %f30,[%fp+-16]
+set Random1,%i5
+ldd [%fp+-16],%f30
+set .L841,%i4
+ld2 [%i4],%f28
+ldd [%fp+-8],%f26
+fmuld %f28,%f26,%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%i5]
+ld2 [%i5],%f0
+.L840:
+ret; restore
+.type Random,#function
+.size Random,.-Random
+.global SqXMinX
+.align 4
+SqXMinX:
+save %sp,-112,%sp
+set X,%i5
+ld2 [%i5],%f30
+set BInvrse,%i5
+ld2 [%i5],%f28
+fmuld %f30,%f28,%f28
+std %f28,[%fp+-8]
+ldd [%fp+-8],%f28
+fsubd %f30,%f28,%f28
+std %f28,[%fp+-16]
+fmuld %f30,%f30,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call sqrt; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set SqEr,%i5
+ldd [%fp+-8],%f28
+fsubd %f30,%f28,%f30
+ldd [%fp+-16],%f28
+fsubd %f30,%f28,%f30
+set OneUlp,%i4
+ld2 [%i4],%f28
+fdivd %f30,%f28,%f30
+st2 %f30,[%i5]
+set SqEr,%i5
+ld2 [%i5],%f30
+set Zero,%i5
+ld2 [%i5],%f28
+fcmped %f30,%f28; nop; fbue .L843; nop
+set SqEr,%i5
+ld2 [%i5],%f30
+set MinSqEr,%i5
+ld2 [%i5],%f28
+fcmped %f30,%f28; nop; fbuge .L845; nop
+set MinSqEr,%i5
+set SqEr,%i4
+ld2 [%i4],%f30
+st2 %f30,[%i5]
+.L845:
+set SqEr,%i5
+ld2 [%i5],%f30
+set MaxSqEr,%i5
+ld2 [%i5],%f28
+fcmped %f30,%f28; nop; fbule .L847; nop
+set MaxSqEr,%i5
+set SqEr,%i4
+ld2 [%i4],%f30
+st2 %f30,[%i5]
+.L847:
+set J,%i5
+ld2 [%i5],%f30
+set .L9,%i4
+ld2 [%i4],%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%i5]
+mov %i0,%o0
+set .L45,%o1
+call BadCond; nop
+set .L849,%o0
+set X,%i5
+ld2 [%i5],%f30
+fmuld %f30,%f30,%f28
+st %f28,[%sp+4*1+68]
+st %f29,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+st %f30,[%sp+4*3+68]
+st %f31,[%sp+4*4+68]
+ld [%sp+4*3+68],%o3
+ld [%sp+4*4+68],%o4
+set OneUlp,%i5
+ld2 [%i5],%f30
+set SqEr,%i5
+ld2 [%i5],%f28
+fmuld %f30,%f28,%f30
+st %f30,[%sp+4*5+68]
+st %f31,[%sp+4*6+68]
+ld [%sp+4*5+68],%o5
+call printf; nop
+set .L850,%o0
+call printf; nop
+.L843:
+mov %g0,%i0
+.L842:
+ret; restore
+.type SqXMinX,#function
+.size SqXMinX,.-SqXMinX
+.global NewD
+.align 4
+NewD:
+save %sp,-96,%sp
+set X,%i5
+set Z1,%i4
+ld2 [%i4],%f30
+set Q,%i4
+ld2 [%i4],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%i5]
+set Half,%i4
+ld2 [%i4],%f30
+ld2 [%i5],%f28
+set Radix,%i4
+ld2 [%i4],%f26
+fdivd %f28,%f26,%f28
+fsubd %f30,%f28,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call floor; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Radix,%i4
+ld2 [%i4],%f28
+set X,%i4
+fmuld %f30,%f28,%f30
+ld2 [%i4],%f26
+faddd %f30,%f26,%f30
+st2 %f30,[%i5]
+set Q,%i5
+ld2 [%i4],%f30
+set Z,%i4
+ld2 [%i4],%f26
+set D,%i3
+ld2 [%i3],%f24
+ld2 [%i5],%f22
+fmuld %f30,%f26,%f20
+fsubd %f22,%f20,%f22
+fdivd %f22,%f28,%f22
+fmuld %f30,%f30,%f20
+fdivd %f24,%f28,%f28
+fmuld %f20,%f28,%f28
+faddd %f22,%f28,%f28
+st2 %f28,[%i5]
+set Two,%i5
+ld2 [%i5],%f28
+fmuld %f28,%f30,%f30
+fmuld %f30,%f24,%f30
+fsubd %f26,%f30,%f30
+st2 %f30,[%i4]
+ld2 [%i4],%f30
+set Zero,%i5
+ld2 [%i5],%f28
+fcmped %f30,%f28; nop; fbug .L852; nop
+set Z,%i5
+ld2 [%i5],%f30
+fnegs %f30,%f30; fmovs %f31,%f31
+st2 %f30,[%i5]
+set Z1,%i5
+ld2 [%i5],%f30
+fnegs %f30,%f30; fmovs %f31,%f31
+st2 %f30,[%i5]
+.L852:
+set D,%i5
+set Radix,%i4
+ld2 [%i4],%f30
+ld2 [%i5],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%i5]
+mov %g0,%i0
+.L851:
+ret; restore
+.type NewD,#function
+.size NewD,.-NewD
+.global SR3750
+.align 4
+SR3750:
+save %sp,-96,%sp
+set X,%i5
+ld2 [%i5],%f30
+set Radix,%i5
+ld2 [%i5],%f28
+set Z2,%i5
+ld2 [%i5],%f26
+fsubd %f30,%f28,%f24
+fsubd %f26,%f28,%f28
+fcmped %f24,%f28; nop; fbul .L855; nop
+fsubd %f30,%f26,%f30
+set W,%i5
+ld2 [%i5],%f28
+fsubd %f28,%f26,%f28
+fcmped %f30,%f28; nop; fbug .L855; nop
+set I,%i5
+ld [%i5],%i4
+add %i4,1,%i4
+st %i4,[%i5]
+set X,%i5
+ld2 [%i5],%f30
+set D,%i5
+ld2 [%i5],%f28
+fmuld %f30,%f28,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call sqrt; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set X2,%i5
+st2 %f30,[%i5]
+set Y2,%i5
+set X2,%i4
+set Z2,%i3
+ld2 [%i3],%f30
+set Y,%i3
+ld2 [%i3],%f28
+ld2 [%i4],%f26
+fsubd %f26,%f30,%f26
+fsubd %f28,%f30,%f30
+fsubd %f26,%f30,%f30
+st2 %f30,[%i5]
+set Half,%i3
+ld2 [%i3],%f30
+set X8,%i3
+ld2 [%i3],%f26
+fsubd %f28,%f30,%f28
+fdivd %f26,%f28,%f28
+st2 %f28,[%i4]
+ld2 [%i4],%f28
+fmuld %f30,%f28,%f26
+fmuld %f26,%f28,%f26
+fsubd %f28,%f26,%f28
+st2 %f28,[%i4]
+set SqEr,%i3
+ld2 [%i5],%f28
+faddd %f28,%f30,%f28
+ld2 [%i4],%f26
+fsubd %f30,%f26,%f30
+faddd %f28,%f30,%f30
+st2 %f30,[%i3]
+ld2 [%i3],%f30
+set MinSqEr,%i5
+ld2 [%i5],%f28
+fcmped %f30,%f28; nop; fbuge .L857; nop
+set MinSqEr,%i5
+set SqEr,%i4
+ld2 [%i4],%f30
+st2 %f30,[%i5]
+.L857:
+set SqEr,%i5
+set Y2,%i4
+ld2 [%i4],%f30
+set X2,%i4
+ld2 [%i4],%f28
+fsubd %f30,%f28,%f30
+st2 %f30,[%i5]
+ld2 [%i5],%f30
+set MaxSqEr,%i5
+ld2 [%i5],%f28
+fcmped %f30,%f28; nop; fbule .L859; nop
+set MaxSqEr,%i5
+set SqEr,%i4
+ld2 [%i4],%f30
+st2 %f30,[%i5]
+.L859:
+.L855:
+mov %g0,%i0
+.L854:
+ret; restore
+.type SR3750,#function
+.size SR3750,.-SR3750
+.global IsYeqX
+.align 4
+IsYeqX:
+save %sp,-96,%sp
+set Y,%i5
+ld2 [%i5],%f30
+set X,%i5
+ld2 [%i5],%f28
+fcmped %f30,%f28; nop; fbue .L862; nop
+set N,%i5
+ld [%i5],%i5
+cmp %i5,0; bg .L864; nop
+set Zero,%i5
+ld2 [%i5],%f30
+set Z,%i5
+ld2 [%i5],%f28
+fcmped %f28,%f30; nop; fbne .L866; nop
+set Q,%i5
+ld2 [%i5],%f28
+fcmped %f28,%f30; nop; fbug .L866; nop
+set .L868,%o0
+call printf; nop
+ba .L867; nop
+.L866:
+set 2,%o0
+set .L869,%o1
+call BadCond; nop
+.L867:
+set .L870,%o0
+set Z,%i5
+ld2 [%i5],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+set Q,%i5
+ld2 [%i5],%f30
+st %f30,[%sp+4*3+68]
+st %f31,[%sp+4*4+68]
+ld [%sp+4*3+68],%o3
+ld [%sp+4*4+68],%o4
+call printf; nop
+set .L871,%o0
+set Y,%i5
+ld2 [%i5],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set .L872,%o0
+set X,%i5
+ld2 [%i5],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set .L873,%o0
+set Y,%i5
+ld2 [%i5],%f30
+set X,%i5
+ld2 [%i5],%f28
+fsubd %f30,%f28,%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+.L864:
+set N,%i5
+ld [%i5],%i4
+add %i4,1,%i4
+st %i4,[%i5]
+.L862:
+mov %g0,%i0
+.L861:
+ret; restore
+.type IsYeqX,#function
+.size IsYeqX,.-IsYeqX
+.global SR3980
+.align 4
+SR3980:
+save %sp,-96,%sp
+.L875:
+set Q,%i5
+set I,%i4
+ld [%i4],%i4
+st %i4,[%sp+64]; ld [%sp+64],%f30; fitod %f30,%f30
+st2 %f30,[%i5]
+set Z,%i4
+ld2 [%i4],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+ld2 [%i5],%f30
+st %f30,[%sp+4*2+68]
+st %f31,[%sp+4*3+68]
+ld [%sp+4*2+68],%o2
+ld [%sp+4*3+68],%o3
+call pow; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Y,%i5
+st2 %f30,[%i5]
+call IsYeqX; nop
+set I,%i5
+ld [%i5],%i4
+add %i4,1,%i4
+st %i4,[%i5]
+set M,%i5
+ld [%i5],%i5
+cmp %i4,%i5; ble .L878; nop
+ba .L877; nop
+.L878:
+set X,%i5
+set Z,%i4
+ld2 [%i4],%f30
+ld2 [%i5],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%i5]
+.L876:
+set X,%i5
+ld2 [%i5],%f30
+set W,%i5
+ld2 [%i5],%f28
+fcmped %f30,%f28; nop; fbul .L875; nop
+.L877:
+mov %g0,%i0
+.L874:
+ret; restore
+.type SR3980,#function
+.size SR3980,.-SR3980
+.global PrintIfNPositive
+.align 4
+PrintIfNPositive:
+save %sp,-96,%sp
+set N,%i5
+ld [%i5],%i5
+cmp %i5,0; ble .L881; nop
+set .L883,%o0
+set N,%i5
+ld [%i5],%o1
+call printf; nop
+.L881:
+mov %g0,%i0
+.L880:
+ret; restore
+.type PrintIfNPositive,#function
+.size PrintIfNPositive,.-PrintIfNPositive
+.global TstPtUf
+.align 4
+TstPtUf:
+save %sp,-96,%sp
+set N,%i5
+st %g0,[%i5]
+set Z,%i5
+ld2 [%i5],%f30
+set Zero,%i5
+ld2 [%i5],%f28
+fcmped %f30,%f28; nop; fbue .L885; nop
+set .L887,%o0
+call printf; nop
+set .L888,%o0
+call printf; nop
+set sigsave,%i5
+set sigfpe,%i4
+st %i4,[%i5]
+set ovfl_buf,%o0
+call setjmp; nop
+cmp %o0,0; be .L889; nop
+ba .L891; nop
+.L889:
+set Q9,%i5
+set Z,%i4
+ld2 [%i4],%f30
+faddd %f30,%f30,%f28
+fdivd %f28,%f30,%f30
+st2 %f30,[%i5]
+set .L892,%o0
+ld2 [%i5],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set Q9,%i5
+ld2 [%i5],%f30
+set Two,%i5
+ld2 [%i5],%f28
+fsubd %f30,%f28,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call fabs; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+set Radix,%i5
+ld2 [%i5],%f28
+set U2,%i5
+ld2 [%i5],%f26
+fmuld %f28,%f26,%f28
+fcmped %f30,%f28; nop; fbuge .L893; nop
+set .L895,%o0
+call printf; nop
+set .L896,%o0
+call printf; nop
+ba .L894; nop
+.L893:
+set Q9,%i5
+ld2 [%i5],%f30
+set One,%i5
+ld2 [%i5],%f28
+fcmped %f30,%f28; nop; fbul .L899; nop
+set Two,%i5
+ld2 [%i5],%f28
+fcmped %f30,%f28; nop; fbule .L897; nop
+.L899:
+.L891:
+set 1,%i5
+set N,%i4
+st %i5,[%i4]
+set ErrCnt+4,%i5
+set ErrCnt+4,%i4
+ld [%i4],%i4
+add %i4,1,%i4
+st %i4,[%i5]
+set .L902,%o0
+call printf; nop
+ba .L898; nop
+.L897:
+set 1,%i5
+set N,%i4
+st %i5,[%i4]
+set ErrCnt+8,%i5
+set ErrCnt+8,%i4
+ld [%i4],%i4
+add %i4,1,%i4
+st %i4,[%i5]
+set .L905,%o0
+call printf; nop
+.L898:
+.L894:
+set sigsave,%i5
+st %g0,[%i5]
+set V9,%i5
+set Z,%i4
+ld2 [%i4],%f30
+set One,%i4
+ld2 [%i4],%f28
+fmuld %f30,%f28,%f26
+st2 %f26,[%i5]
+set Random1,%i4
+ld2 [%i5],%f26
+st2 %f26,[%i4]
+fmuld %f28,%f30,%f26
+st2 %f26,[%i5]
+set Random2,%i4
+ld2 [%i5],%f26
+st2 %f26,[%i4]
+fdivd %f30,%f28,%f30
+st2 %f30,[%i5]
+set Z,%i5
+ld2 [%i5],%f30
+set Random1,%i5
+ld2 [%i5],%f28
+fcmped %f30,%f28; nop; fbne .L906; nop
+set Random2,%i5
+ld2 [%i5],%f28
+fcmped %f30,%f28; nop; fbne .L906; nop
+set V9,%i5
+ld2 [%i5],%f28
+fcmped %f30,%f28; nop; fbne .L906; nop
+set N,%i5
+ld [%i5],%i5
+cmp %i5,0; ble .L907; nop
+call Pause; nop
+ba .L907; nop
+.L906:
+set N,%i5
+set 1,%i4
+st %i4,[%i5]
+set 2,%o0
+set .L910,%o1
+call BadCond; nop
+set .L911,%o0
+set Z,%i5
+ld2 [%i5],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set Z,%i5
+ld2 [%i5],%f30
+set Random1,%i5
+ld2 [%i5],%f28
+fcmped %f30,%f28; nop; fbue .L912; nop
+set .L914,%o0
+set Random1,%i5
+ld2 [%i5],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+.L912:
+set Random2,%i5
+ld2 [%i5],%f30
+set Z,%i5
+ld2 [%i5],%f28
+fcmped %f28,%f30; nop; fbue .L915; nop
+set Random1,%i5
+ld2 [%i5],%f28
+fcmped %f30,%f28; nop; fbue .L915; nop
+set .L917,%o0
+set Random2,%i5
+ld2 [%i5],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+.L915:
+set Z,%i5
+ld2 [%i5],%f30
+set V9,%i5
+ld2 [%i5],%f28
+fcmped %f30,%f28; nop; fbue .L918; nop
+set .L920,%o0
+set V9,%i5
+ld2 [%i5],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+.L918:
+set Random2,%i5
+ld2 [%i5],%f30
+set Random1,%i5
+ld2 [%i5],%f28
+fcmped %f30,%f28; nop; fbue .L921; nop
+set ErrCnt+8,%i5
+set ErrCnt+8,%i4
+ld [%i4],%i4
+add %i4,1,%i4
+st %i4,[%i5]
+set 2,%o0
+set .L925,%o1
+call BadCond; nop
+set .L926,%o0
+set Random2,%i5
+ld2 [%i5],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+set .L927,%o0
+set Random1,%i5
+ld2 [%i5],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+.L921:
+call Pause; nop
+.L907:
+.L885:
+mov %g0,%i0
+.L884:
+ret; restore
+.type TstPtUf,#function
+.size TstPtUf,.-TstPtUf
+.global notify
+.align 4
+notify:
+save %sp,-96,%sp
+set .L929,%o0
+mov %i0,%o1
+call printf; nop
+set .L930,%o0
+call printf; nop
+mov %g0,%i0
+.L928:
+ret; restore
+.type notify,#function
+.size notify,.-notify
+.global msglist
+.align 4
+msglist:
+save %sp,-96,%sp
+ba .L933; nop
+.L932:
+set .L935,%o0
+mov %i0,%i5
+add %i5,4,%i0
+ld [%i5],%o1
+call printf; nop
+.L933:
+ld [%i0],%i5
+cmp %i5,%g0; bne .L932; nop
+mov %g0,%i0
+.L931:
+ret; restore
+.type msglist,#function
+.size msglist,.-msglist
+.section ".data"
+.type .937,#object
+.align 4
+.937:
+.word .L938
+.word .L939
+.word .L940
+.word .L941
+.word .L942
+.word .L943
+.word .L944
+.word .L945
+.word .L946
+.word 0x0
+.size .937,40
+.global Instructions
+.section ".text"
+.align 4
+Instructions:
+save %sp,-96,%sp
+set .937,%o0
+call msglist; nop
+mov %g0,%i0
+.L936:
+ret; restore
+.type Instructions,#function
+.size Instructions,.-Instructions
+.section ".data"
+.type .948,#object
+.align 4
+.948:
+.word .L949
+.word .L950
+.word .L951
+.word .L952
+.word .L953
+.word .L954
+.word .L955
+.word .L956
+.word .L957
+.word .L958
+.word .L959
+.word .L960
+.word .L961
+.word .L962
+.word 0x0
+.size .948,60
+.global Heading
+.section ".text"
+.align 4
+Heading:
+save %sp,-96,%sp
+set .948,%o0
+call msglist; nop
+mov %g0,%i0
+.L947:
+ret; restore
+.type Heading,#function
+.size Heading,.-Heading
+.section ".data"
+.type .964,#object
+.align 4
+.964:
+.word .L965
+.word .L966
+.word .L967
+.word .L968
+.word .L969
+.word .L970
+.word .L971
+.word .L972
+.word .L973
+.word .L974
+.word .L975
+.word .L976
+.word .L977
+.word .L978
+.word .L979
+.word .L980
+.word .L981
+.word .L982
+.word .L983
+.word 0x0
+.size .964,80
+.global Characteristics
+.section ".text"
+.align 4
+Characteristics:
+save %sp,-96,%sp
+set .964,%o0
+call msglist; nop
+mov %g0,%i0
+.L963:
+ret; restore
+.type Characteristics,#function
+.size Characteristics,.-Characteristics
+.section ".data"
+.type .985,#object
+.align 4
+.985:
+.word .L986
+.word .L987
+.word .L988
+.word .L989
+.word .L990
+.word .L991
+.word .L992
+.word .L993
+.word .L994
+.word .L995
+.word .L996
+.word .L997
+.word .L998
+.word .L999
+.word .L1000
+.word .L1001
+.word .L1002
+.word 0x0
+.size .985,72
+.global History
+.section ".text"
+.align 4
+History:
+save %sp,-96,%sp
+set .985,%o0
+call msglist; nop
+mov %g0,%i0
+.L984:
+ret; restore
+.type History,#function
+.size History,.-History
+.global pow
+.align 4
+pow:
+save %sp,-120,%sp
+st %r24,[%fp+68]
+st %r25,[%fp+72]
+st %r26,[%fp+76]
+st %r27,[%fp+80]
+mov %g0,%i4
+mov %g0,%i3
+ld2 [%fp+76],%f30
+set .L8,%i2
+ld2 [%i2],%f28
+fcmped %f30,%f28; nop; fbne .L1004; nop
+set .L9,%i2
+ld2 [%i2],%f0
+ba .L1003; nop
+.L1004:
+ld2 [%fp+76],%f30
+set .L1009,%i2
+ld2 [%i2],%f28
+fcmped %f30,%f28; nop; fbul .L1008; nop
+set .L1010,%i2
+ld2 [%i2],%f28
+fcmped %f30,%f28; nop; fbule .L1006; nop
+.L1008:
+ld2 [%fp+68],%f30
+set .L826,%i2
+ld2 [%i2],%f28
+fcmped %f30,%f28; nop; fbue .L1006; nop
+ld2 [%fp+68],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call log; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+ld2 [%fp+76],%f28
+fmuld %f28,%f30,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call exp; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+fmovs %f30,%f0; fmovs %f31,%f1
+ba .L1003; nop
+.L1006:
+ld2 [%fp+76],%f30
+set .L8,%i2
+ld2 [%i2],%f28
+fcmped %f30,%f28; nop; fbuge .L1011; nop
+ld2 [%fp+76],%f30
+fnegs %f30,%f30; fmovs %f31,%f31
+st2 %f30,[%fp+76]
+set 1,%i3
+.L1011:
+ld2 [%fp+76],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+add -24,%fp,%o2
+call modf; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+st2 %f30,[%fp+76]
+ld2 [%fp+76],%f30
+set .L8,%i2
+ld2 [%i2],%f28
+fcmped %f30,%f28; nop; fbue .L1013; nop
+ld2 [%fp+68],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call log; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+ld2 [%fp+76],%f28
+fmuld %f28,%f30,%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+call exp; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+std %f30,[%fp+-16]
+ba .L1014; nop
+.L1013:
+set .L9,%i2
+ld2 [%i2],%f30
+std %f30,[%fp+-16]
+.L1014:
+ld2 [%fp+68],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+add -4,%fp,%o2
+call frexp; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+st2 %f30,[%fp+68]
+ldd [%fp+-24],%f30
+fdtoi %f30,%f0; st %f0,[%sp+64]; ld [%sp+64],%i2
+mov %i2,%i5
+cmp %i2,0; be .L1015; nop
+.L1017:
+and %i5,1,%i2
+cmp %i2,0; be .L1021; nop
+ldd [%fp+-16],%f30
+ld2 [%fp+68],%f28
+fmuld %f30,%f28,%f30
+std %f30,[%fp+-16]
+ld [%fp+-4],%i2
+add %i4,%i2,%i4
+.L1021:
+sra %i5,1,%i2
+mov %i2,%i5
+cmp %i2,0; bne .L1023; nop
+ba .L1019; nop
+.L1023:
+ld2 [%fp+68],%f30
+fmuld %f30,%f30,%f30
+st2 %f30,[%fp+68]
+ld [%fp+-4],%i2
+sll %i2,1,%i2
+st %i2,[%fp+-4]
+ld2 [%fp+68],%f30
+set .L1027,%i2
+ld2 [%i2],%f28
+fcmped %f30,%f28; nop; fbuge .L1017; nop
+set .L1028,%i2
+ld2 [%i2],%f30
+ld2 [%fp+68],%f28
+fmuld %f30,%f28,%f30
+st2 %f30,[%fp+68]
+ld [%fp+-4],%i2
+sub %i2,1,%i2
+st %i2,[%fp+-4]
+ba .L1017; nop
+.L1019:
+.L1015:
+cmp %i3,0; be .L1029; nop
+set .L9,%i2
+ld2 [%i2],%f30
+ldd [%fp+-16],%f28
+fdivd %f30,%f28,%f30
+std %f30,[%fp+-16]
+neg %i4,%i4
+.L1029:
+ldd [%fp+-16],%f30
+st %f30,[%sp+4*0+68]
+st %f31,[%sp+4*1+68]
+ld [%sp+4*0+68],%o0
+ld [%sp+4*1+68],%o1
+mov %i4,%o2
+call ldexp; nop
+fmovs %f0,%f30; fmovs %f1,%f31
+fmovs %f30,%f0; fmovs %f31,%f1
+.L1003:
+ret; restore
+.type pow,#function
+.size pow,.-pow
+.section ".bss"
+.global UfNGrad
+.type UfNGrad,#object
+.size UfNGrad,4
+.common UfNGrad,4,4
+.global SqRWrng
+.type SqRWrng,#object
+.size SqRWrng,4
+.common SqRWrng,4,4
+.global IEEE
+.type IEEE,#object
+.size IEEE,4
+.common IEEE,4,4
+.global Anomaly
+.type Anomaly,#object
+.size Anomaly,4
+.common Anomaly,4,4
+.global Monot
+.type Monot,#object
+.size Monot,4
+.common Monot,4,4
+.global NotMonot
+.type NotMonot,#object
+.size NotMonot,4
+.common NotMonot,4,4
+.global Done
+.type Done,#object
+.size Done,4
+.common Done,4,4
+.global Break
+.type Break,#object
+.size Break,4
+.common Break,4,4
+.global RSqrt
+.type RSqrt,#object
+.size RSqrt,4
+.common RSqrt,4,4
+.global RAddSub
+.type RAddSub,#object
+.size RAddSub,4
+.common RAddSub,4,4
+.global RDiv
+.type RDiv,#object
+.size RDiv,4
+.common RDiv,4,4
+.global RMult
+.type RMult,#object
+.size RMult,4
+.common RMult,4,4
+.global GAddSub
+.type GAddSub,#object
+.size GAddSub,4
+.common GAddSub,4,4
+.global GDiv
+.type GDiv,#object
+.size GDiv,4
+.common GDiv,4,4
+.global GMult
+.type GMult,#object
+.size GMult,4
+.common GMult,4,4
+.global N1
+.type N1,#object
+.size N1,4
+.common N1,4,4
+.global N
+.type N,#object
+.size N,4
+.common N,4,4
+.global M
+.type M,#object
+.size M,4
+.common M,4,4
+.global PageNo
+.type PageNo,#object
+.size PageNo,4
+.common PageNo,4,4
+.global Milestone
+.type Milestone,#object
+.size Milestone,4
+.common Milestone,4,4
+.global fpecount
+.type fpecount,#object
+.size fpecount,4
+.common fpecount,4,4
+.global ErrCnt
+.type ErrCnt,#object
+.size ErrCnt,16
+.common ErrCnt,16,4
+.global Z9
+.type Z9,#object
+.size Z9,8
+.common Z9,8,8
+.global Z2
+.type Z2,#object
+.size Z2,8
+.common Z2,8,8
+.global Z1
+.type Z1,#object
+.size Z1,8
+.common Z1,8,8
+.global PseudoZero
+.type PseudoZero,#object
+.size PseudoZero,8
+.common PseudoZero,8,8
+.global Z
+.type Z,#object
+.size Z,8
+.common Z,8,8
+.global Random2
+.type Random2,#object
+.size Random2,8
+.common Random2,8,8
+.global Y2
+.type Y2,#object
+.size Y2,8
+.common Y2,8,8
+.global Y1
+.type Y1,#object
+.size Y1,8
+.common Y1,8,8
+.global Y
+.type Y,#object
+.size Y,8
+.common Y,8,8
+.global Random1
+.type Random1,#object
+.size Random1,8
+.common Random1,8,8
+.global X8
+.type X8,#object
+.size X8,8
+.common X8,8,8
+.global X2
+.type X2,#object
+.size X2,8
+.common X2,8,8
+.global X1
+.type X1,#object
+.size X1,8
+.common X1,8,8
+.global X
+.type X,#object
+.size X,8
+.common X,8,8
+.global W
+.type W,#object
+.size W,8
+.common W,8,8
+.global V9
+.type V9,#object
+.size V9,8
+.common V9,8,8
+.global V0
+.type V0,#object
+.size V0,8
+.common V0,8,8
+.global V
+.type V,#object
+.size V,8
+.common V,8,8
+.global U2
+.type U2,#object
+.size U2,8
+.common U2,8,8
+.global U1
+.type U1,#object
+.size U1,8
+.common U1,8,8
+.global UfThold
+.type UfThold,#object
+.size UfThold,8
+.common UfThold,8,8
+.global OneUlp
+.type OneUlp,#object
+.size OneUlp,8
+.common OneUlp,8,8
+.global S
+.type S,#object
+.size S,8
+.common S,8,8
+.global Underflow
+.type Underflow,#object
+.size Underflow,8
+.common Underflow,8,8
+.global T
+.type T,#object
+.size T,8
+.common T,8,8
+.global Random9
+.type Random9,#object
+.size Random9,8
+.common Random9,8,8
+.global R
+.type R,#object
+.size R,8
+.common R,8,8
+.global Q9
+.type Q9,#object
+.size Q9,8
+.common Q9,8,8
+.global Q
+.type Q,#object
+.size Q,8
+.common Q,8,8
+.global Precision
+.type Precision,#object
+.size Precision,8
+.common Precision,8,8
+.global MyZero
+.type MyZero,#object
+.size MyZero,8
+.common MyZero,8,8
+.global J
+.type J,#object
+.size J,8
+.common J,8,8
+.global StickyBit
+.type StickyBit,#object
+.size StickyBit,8
+.common StickyBit,8,8
+.global I
+.type I,#object
+.size I,4
+.common I,4,4
+.global HInvrse
+.type HInvrse,#object
+.size HInvrse,8
+.common HInvrse,8,8
+.global H
+.type H,#object
+.size H,8
+.common H,8,8
+.global F9
+.type F9,#object
+.size F9,8
+.common F9,8,8
+.global F6
+.type F6,#object
+.size F6,8
+.common F6,8,8
+.global Third
+.type Third,#object
+.size Third,8
+.common Third,8,8
+.global E9
+.type E9,#object
+.size E9,8
+.common E9,8,8
+.global MaxSqEr
+.type MaxSqEr,#object
+.size MaxSqEr,8
+.common MaxSqEr,8,8
+.global SqEr
+.type SqEr,#object
+.size SqEr,8
+.common SqEr,8,8
+.global MinSqEr
+.type MinSqEr,#object
+.size MinSqEr,8
+.common MinSqEr,8,8
+.global E3
+.type E3,#object
+.size E3,8
+.common E3,8,8
+.global Exp2
+.type Exp2,#object
+.size Exp2,8
+.common Exp2,8,8
+.global E1
+.type E1,#object
+.size E1,8
+.common E1,8,8
+.global E0
+.type E0,#object
+.size E0,8
+.common E0,8,8
+.global FourD
+.type FourD,#object
+.size FourD,8
+.common FourD,8,8
+.global D
+.type D,#object
+.size D,8
+.common D,8,8
+.global CInvrse
+.type CInvrse,#object
+.size CInvrse,8
+.common CInvrse,8,8
+.global C
+.type C,#object
+.size C,8
+.common C,8,8
+.global A1
+.type A1,#object
+.size A1,8
+.common A1,8,8
+.global AInvrse
+.type AInvrse,#object
+.size AInvrse,8
+.common AInvrse,8,8
+.global ch
+.type ch,#object
+.size ch,8
+.common ch,8,1
+.global Indx
+.type Indx,#object
+.size Indx,4
+.common Indx,4,4
+.global BMinusU2
+.type BMinusU2,#object
+.size BMinusU2,8
+.common BMinusU2,8,8
+.global RadixD2
+.type RadixD2,#object
+.size RadixD2,8
+.common RadixD2,8,8
+.global BInvrse
+.type BInvrse,#object
+.size BInvrse,8
+.common BInvrse,8,8
+.global Radix
+.type Radix,#object
+.size Radix,8
+.common Radix,8,8
+.global sigsave
+.type sigsave,#object
+.size sigsave,4
+.common sigsave,4,4
+.global ovfl_buf
+.type ovfl_buf,#object
+.size ovfl_buf,48
+.common ovfl_buf,48,4
+.section ".rodata"
+.align 8
+.L1028:
+.word 0x40000000
+.word 0x0
+.align 8
+.L1027:
+.word 0x3fe00000
+.word 0x0
+.align 8
+.L1010:
+.word 0x40913000
+.word 0x0
+.align 8
+.L1009:
+.word 0xc0913000
+.word 0x0
+.align 1
+.L1002:
+.byte 115
+.byte 101
+.byte 101
+.byte 32
+.byte 115
+.byte 111
+.byte 117
+.byte 114
+.byte 99
+.byte 101
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 109
+.byte 111
+.byte 114
+.byte 101
+.byte 32
+.byte 104
+.byte 105
+.byte 115
+.byte 116
+.byte 111
+.byte 114
+.byte 121
+.byte 46
+.byte 0
+.align 1
+.L1001:
+.byte 66
+.byte 65
+.byte 83
+.byte 73
+.byte 67
+.byte 32
+.byte 118
+.byte 101
+.byte 114
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 40
+.byte 67
+.byte 41
+.byte 32
+.byte 49
+.byte 57
+.byte 56
+.byte 51
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 80
+.byte 114
+.byte 111
+.byte 102
+.byte 46
+.byte 32
+.byte 87
+.byte 46
+.byte 32
+.byte 77
+.byte 46
+.byte 32
+.byte 75
+.byte 97
+.byte 104
+.byte 97
+.byte 110
+.byte 59
+.byte 0
+.align 1
+.L1000:
+.byte 97
+.byte 115
+.byte 32
+.byte 117
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 99
+.byte 101
+.byte 114
+.byte 116
+.byte 97
+.byte 105
+.byte 110
+.byte 32
+.byte 101
+.byte 97
+.byte 114
+.byte 108
+.byte 121
+.byte 32
+.byte 87
+.byte 65
+.byte 78
+.byte 71
+.byte 32
+.byte 109
+.byte 97
+.byte 99
+.byte 104
+.byte 105
+.byte 110
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L999:
+.byte 102
+.byte 108
+.byte 111
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 45
+.byte 112
+.byte 111
+.byte 105
+.byte 110
+.byte 116
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 115
+.byte 44
+.byte 32
+.byte 98
+.byte 117
+.byte 116
+.byte 32
+.byte 97
+.byte 108
+.byte 115
+.byte 111
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 111
+.byte 119
+.byte 115
+.byte 32
+.byte 108
+.byte 111
+.byte 103
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 105
+.byte 99
+.byte 32
+.byte 101
+.byte 110
+.byte 99
+.byte 111
+.byte 100
+.byte 105
+.byte 110
+.byte 103
+.byte 0
+.align 1
+.L998:
+.byte 10
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 98
+.byte 97
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 117
+.byte 112
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 118
+.byte 101
+.byte 110
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 97
+.byte 108
+.byte 32
+.byte 114
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 114
+.byte 101
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 101
+.byte 110
+.byte 116
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 0
+.align 1
+.L997:
+.byte 111
+.byte 102
+.byte 32
+.byte 112
+.byte 97
+.byte 116
+.byte 104
+.byte 111
+.byte 108
+.byte 111
+.byte 103
+.byte 105
+.byte 101
+.byte 115
+.byte 44
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 115
+.byte 97
+.byte 121
+.byte 32
+.byte 104
+.byte 111
+.byte 119
+.byte 32
+.byte 119
+.byte 101
+.byte 108
+.byte 108
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 109
+.byte 112
+.byte 108
+.byte 101
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 101
+.byte 100
+.byte 46
+.byte 0
+.align 1
+.L996:
+.byte 111
+.byte 102
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 44
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 116
+.byte 114
+.byte 105
+.byte 101
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 111
+.byte 112
+.byte 101
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 97
+.byte 32
+.byte 119
+.byte 105
+.byte 100
+.byte 101
+.byte 114
+.byte 32
+.byte 118
+.byte 97
+.byte 114
+.byte 105
+.byte 101
+.byte 116
+.byte 121
+.byte 0
+.align 1
+.L995:
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 44
+.byte 32
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 114
+.byte 97
+.byte 110
+.byte 103
+.byte 101
+.byte 32
+.byte 40
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 47
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 115
+.byte 41
+.byte 0
+.align 1
+.L994:
+.byte 87
+.byte 46
+.byte 32
+.byte 74
+.byte 46
+.byte 32
+.byte 67
+.byte 111
+.byte 100
+.byte 121
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 87
+.byte 46
+.byte 32
+.byte 87
+.byte 97
+.byte 105
+.byte 116
+.byte 101
+.byte 46
+.byte 32
+.byte 65
+.byte 108
+.byte 116
+.byte 104
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 32
+.byte 98
+.byte 111
+.byte 116
+.byte 104
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 115
+.byte 32
+.byte 116
+.byte 114
+.byte 121
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 0
+.align 1
+.L993:
+.byte 98
+.byte 111
+.byte 111
+.byte 107
+.byte 32
+.byte 32
+.byte 96
+.byte 83
+.byte 111
+.byte 102
+.byte 116
+.byte 119
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 77
+.byte 97
+.byte 110
+.byte 117
+.byte 97
+.byte 108
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 69
+.byte 108
+.byte 101
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 97
+.byte 114
+.byte 121
+.byte 32
+.byte 70
+.byte 117
+.byte 110
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 39
+.byte 32
+.byte 40
+.byte 49
+.byte 57
+.byte 56
+.byte 48
+.byte 41
+.byte 32
+.byte 98
+.byte 121
+.byte 0
+.align 1
+.L992:
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 99
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 100
+.byte 32
+.byte 96
+.byte 77
+.byte 65
+.byte 67
+.byte 72
+.byte 65
+.byte 82
+.byte 39
+.byte 44
+.byte 32
+.byte 119
+.byte 104
+.byte 105
+.byte 99
+.byte 104
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 101
+.byte 110
+.byte 100
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 0
+.align 1
+.L991:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 99
+.byte 97
+.byte 112
+.byte 97
+.byte 98
+.byte 105
+.byte 108
+.byte 105
+.byte 116
+.byte 105
+.byte 101
+.byte 115
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 103
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 121
+.byte 111
+.byte 110
+.byte 100
+.byte 32
+.byte 97
+.byte 110
+.byte 32
+.byte 101
+.byte 97
+.byte 114
+.byte 108
+.byte 105
+.byte 101
+.byte 114
+.byte 0
+.align 1
+.L990:
+.byte 70
+.byte 97
+.byte 105
+.byte 108
+.byte 117
+.byte 114
+.byte 101
+.byte 115
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 115
+.byte 101
+.byte 113
+.byte 117
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L989:
+.byte 32
+.byte 32
+.byte 32
+.byte 70
+.byte 65
+.byte 73
+.byte 76
+.byte 85
+.byte 82
+.byte 69
+.byte 115
+.byte 44
+.byte 32
+.byte 108
+.byte 105
+.byte 107
+.byte 101
+.byte 32
+.byte 50
+.byte 43
+.byte 50
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 53
+.byte 32
+.byte 46
+.byte 0
+.align 1
+.L988:
+.byte 32
+.byte 32
+.byte 32
+.byte 83
+.byte 101
+.byte 114
+.byte 105
+.byte 111
+.byte 117
+.byte 115
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 115
+.byte 44
+.byte 32
+.byte 108
+.byte 105
+.byte 107
+.byte 101
+.byte 32
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 97
+.byte 32
+.byte 103
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 44
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 0
+.align 1
+.L987:
+.byte 32
+.byte 32
+.byte 32
+.byte 70
+.byte 76
+.byte 65
+.byte 87
+.byte 115
+.byte 44
+.byte 32
+.byte 108
+.byte 105
+.byte 107
+.byte 101
+.byte 32
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 97
+.byte 32
+.byte 115
+.byte 116
+.byte 105
+.byte 99
+.byte 107
+.byte 121
+.byte 32
+.byte 98
+.byte 105
+.byte 116
+.byte 44
+.byte 0
+.align 1
+.L986:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 97
+.byte 116
+.byte 116
+.byte 101
+.byte 109
+.byte 112
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 114
+.byte 105
+.byte 109
+.byte 105
+.byte 110
+.byte 97
+.byte 116
+.byte 101
+.byte 32
+.byte 97
+.byte 109
+.byte 111
+.byte 110
+.byte 103
+.byte 0
+.align 1
+.L983:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 68
+.byte 101
+.byte 99
+.byte 105
+.byte 109
+.byte 97
+.byte 108
+.byte 45
+.byte 66
+.byte 105
+.byte 110
+.byte 97
+.byte 114
+.byte 121
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 118
+.byte 101
+.byte 114
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 78
+.byte 79
+.byte 84
+.byte 32
+.byte 89
+.byte 69
+.byte 84
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 97
+.byte 99
+.byte 99
+.byte 117
+.byte 114
+.byte 97
+.byte 99
+.byte 121
+.byte 46
+.byte 0
+.align 1
+.L982:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 69
+.byte 120
+.byte 116
+.byte 114
+.byte 97
+.byte 45
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 101
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 101
+.byte 120
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 101
+.byte 118
+.byte 101
+.byte 97
+.byte 108
+.byte 101
+.byte 100
+.byte 32
+.byte 98
+.byte 117
+.byte 116
+.byte 32
+.byte 78
+.byte 79
+.byte 84
+.byte 32
+.byte 89
+.byte 69
+.byte 84
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 101
+.byte 100
+.byte 46
+.byte 0
+.align 1
+.L981:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 83
+.byte 113
+.byte 114
+.byte 116
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 101
+.byte 100
+.byte 46
+.byte 32
+.byte 32
+.byte 89
+.byte 94
+.byte 88
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 101
+.byte 100
+.byte 46
+.byte 0
+.align 1
+.L980:
+.byte 9
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 116
+.byte 97
+.byte 109
+.byte 105
+.byte 110
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 112
+.byte 115
+.byte 101
+.byte 117
+.byte 100
+.byte 111
+.byte 45
+.byte 122
+.byte 101
+.byte 114
+.byte 111
+.byte 115
+.byte 46
+.byte 0
+.align 1
+.L979:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 99
+.byte 104
+.byte 101
+.byte 99
+.byte 107
+.byte 101
+.byte 100
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 115
+.byte 105
+.byte 115
+.byte 116
+.byte 101
+.byte 110
+.byte 99
+.byte 121
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 0
+.align 1
+.L978:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 86
+.byte 48
+.byte 32
+.byte 32
+.byte 116
+.byte 101
+.byte 108
+.byte 108
+.byte 115
+.byte 44
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 108
+.byte 121
+.byte 44
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 32
+.byte 73
+.byte 110
+.byte 102
+.byte 105
+.byte 110
+.byte 105
+.byte 116
+.byte 121
+.byte 32
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 114
+.byte 101
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 101
+.byte 110
+.byte 116
+.byte 101
+.byte 100
+.byte 46
+.byte 0
+.align 1
+.L977:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 86
+.byte 32
+.byte 61
+.byte 32
+.byte 97
+.byte 110
+.byte 32
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 44
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 108
+.byte 121
+.byte 46
+.byte 0
+.align 1
+.L976:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 69
+.byte 48
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 80
+.byte 115
+.byte 101
+.byte 117
+.byte 100
+.byte 111
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 116
+.byte 101
+.byte 108
+.byte 108
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 97
+.byte 98
+.byte 114
+.byte 117
+.byte 112
+.byte 116
+.byte 44
+.byte 32
+.byte 103
+.byte 114
+.byte 97
+.byte 100
+.byte 117
+.byte 97
+.byte 108
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 102
+.byte 117
+.byte 122
+.byte 122
+.byte 121
+.byte 46
+.byte 0
+.align 1
+.L975:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 84
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 61
+.byte 32
+.byte 97
+.byte 110
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 46
+.byte 0
+.align 1
+.L974:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 87
+.byte 104
+.byte 101
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 97
+.byte 32
+.byte 83
+.byte 116
+.byte 105
+.byte 99
+.byte 107
+.byte 121
+.byte 32
+.byte 66
+.byte 105
+.byte 116
+.byte 32
+.byte 117
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 105
+.byte 110
+.byte 103
+.byte 46
+.byte 0
+.align 1
+.L973:
+.byte 9
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 46
+.byte 44
+.byte 32
+.byte 68
+.byte 105
+.byte 118
+.byte 46
+.byte 44
+.byte 32
+.byte 65
+.byte 100
+.byte 100
+.byte 47
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 46
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 83
+.byte 113
+.byte 114
+.byte 116
+.byte 46
+.byte 0
+.align 1
+.L972:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 87
+.byte 104
+.byte 101
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 44
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 100
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 115
+.byte 111
+.byte 109
+.byte 101
+.byte 116
+.byte 104
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 101
+.byte 108
+.byte 115
+.byte 101
+.byte 0
+.align 1
+.L971:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 65
+.byte 100
+.byte 101
+.byte 113
+.byte 117
+.byte 97
+.byte 99
+.byte 121
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 103
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 46
+.byte 44
+.byte 32
+.byte 68
+.byte 105
+.byte 118
+.byte 46
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 46
+.byte 0
+.align 1
+.L970:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 85
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 49
+.byte 47
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 94
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 61
+.byte 32
+.byte 79
+.byte 110
+.byte 101
+.byte 32
+.byte 85
+.byte 108
+.byte 112
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 108
+.byte 105
+.byte 116
+.byte 116
+.byte 108
+.byte 101
+.byte 32
+.byte 108
+.byte 101
+.byte 115
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 110
+.byte 32
+.byte 49
+.byte 46
+.byte 48
+.byte 32
+.byte 46
+.byte 0
+.align 1
+.L969:
+.byte 9
+.byte 40
+.byte 79
+.byte 110
+.byte 101
+.byte 85
+.byte 108
+.byte 112
+.byte 110
+.byte 105
+.byte 116
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 76
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 80
+.byte 108
+.byte 97
+.byte 99
+.byte 101
+.byte 41
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 49
+.byte 46
+.byte 48
+.byte 48
+.byte 48
+.byte 120
+.byte 120
+.byte 120
+.byte 32
+.byte 46
+.byte 0
+.align 1
+.L968:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 85
+.byte 50
+.byte 32
+.byte 61
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 47
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 94
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 61
+.byte 32
+.byte 79
+.byte 110
+.byte 101
+.byte 32
+.byte 85
+.byte 108
+.byte 112
+.byte 0
+.align 1
+.L967:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 61
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 105
+.byte 102
+.byte 105
+.byte 99
+.byte 97
+.byte 110
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 99
+.byte 97
+.byte 114
+.byte 114
+.byte 105
+.byte 101
+.byte 100
+.byte 46
+.byte 0
+.align 1
+.L966:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 49
+.byte 44
+.byte 32
+.byte 50
+.byte 44
+.byte 32
+.byte 52
+.byte 44
+.byte 32
+.byte 56
+.byte 44
+.byte 32
+.byte 49
+.byte 48
+.byte 44
+.byte 32
+.byte 49
+.byte 54
+.byte 44
+.byte 32
+.byte 49
+.byte 48
+.byte 48
+.byte 44
+.byte 32
+.byte 50
+.byte 53
+.byte 54
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 0
+.align 1
+.L965:
+.byte 82
+.byte 117
+.byte 110
+.byte 110
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 114
+.byte 101
+.byte 118
+.byte 101
+.byte 97
+.byte 108
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 115
+.byte 101
+.byte 32
+.byte 99
+.byte 104
+.byte 97
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 101
+.byte 114
+.byte 105
+.byte 115
+.byte 116
+.byte 105
+.byte 99
+.byte 115
+.byte 58
+.byte 0
+.align 1
+.L962:
+.byte 9
+.byte 79
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 114
+.byte 101
+.byte 108
+.byte 101
+.byte 118
+.byte 97
+.byte 110
+.byte 116
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 105
+.byte 108
+.byte 101
+.byte 114
+.byte 32
+.byte 111
+.byte 112
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 58
+.byte 0
+.align 1
+.L961:
+.byte 9
+.byte 79
+.byte 112
+.byte 116
+.byte 105
+.byte 109
+.byte 105
+.byte 122
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 108
+.byte 101
+.byte 118
+.byte 101
+.byte 108
+.byte 58
+.byte 10
+.byte 0
+.align 1
+.L960:
+.byte 9
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 105
+.byte 108
+.byte 101
+.byte 114
+.byte 58
+.byte 10
+.byte 0
+.align 1
+.L959:
+.byte 9
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 114
+.byte 58
+.byte 10
+.byte 0
+.align 1
+.L958:
+.byte 9
+.byte 86
+.byte 101
+.byte 114
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 58
+.byte 9
+.byte 49
+.byte 48
+.byte 32
+.byte 70
+.byte 101
+.byte 98
+.byte 114
+.byte 117
+.byte 97
+.byte 114
+.byte 121
+.byte 32
+.byte 49
+.byte 57
+.byte 56
+.byte 57
+.byte 59
+.byte 0
+.align 1
+.L957:
+.byte 9
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 58
+.byte 9
+.byte 100
+.byte 111
+.byte 117
+.byte 98
+.byte 108
+.byte 101
+.byte 59
+.byte 0
+.align 1
+.L956:
+.byte 73
+.byte 110
+.byte 32
+.byte 100
+.byte 111
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 115
+.byte 111
+.byte 44
+.byte 32
+.byte 112
+.byte 108
+.byte 101
+.byte 97
+.byte 115
+.byte 101
+.byte 32
+.byte 105
+.byte 110
+.byte 99
+.byte 108
+.byte 117
+.byte 100
+.byte 101
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 102
+.byte 111
+.byte 108
+.byte 108
+.byte 111
+.byte 119
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 105
+.byte 110
+.byte 102
+.byte 111
+.byte 114
+.byte 109
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 58
+.byte 0
+.align 1
+.L955:
+.byte 9
+.byte 83
+.byte 97
+.byte 110
+.byte 32
+.byte 70
+.byte 114
+.byte 97
+.byte 110
+.byte 99
+.byte 105
+.byte 115
+.byte 99
+.byte 111
+.byte 44
+.byte 32
+.byte 67
+.byte 65
+.byte 32
+.byte 57
+.byte 52
+.byte 49
+.byte 52
+.byte 51
+.byte 45
+.byte 48
+.byte 55
+.byte 48
+.byte 52
+.byte 44
+.byte 32
+.byte 85
+.byte 83
+.byte 65
+.byte 10
+.byte 0
+.align 1
+.L954:
+.byte 9
+.byte 85
+.byte 110
+.byte 105
+.byte 118
+.byte 101
+.byte 114
+.byte 115
+.byte 105
+.byte 116
+.byte 121
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 67
+.byte 97
+.byte 108
+.byte 105
+.byte 102
+.byte 111
+.byte 114
+.byte 110
+.byte 105
+.byte 97
+.byte 0
+.align 1
+.L953:
+.byte 9
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 67
+.byte 101
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 85
+.byte 45
+.byte 55
+.byte 54
+.byte 0
+.align 1
+.L952:
+.byte 9
+.byte 82
+.byte 105
+.byte 99
+.byte 104
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 75
+.byte 97
+.byte 114
+.byte 112
+.byte 105
+.byte 110
+.byte 115
+.byte 107
+.byte 105
+.byte 0
+.align 1
+.L951:
+.byte 80
+.byte 108
+.byte 101
+.byte 97
+.byte 115
+.byte 101
+.byte 32
+.byte 115
+.byte 101
+.byte 110
+.byte 100
+.byte 32
+.byte 115
+.byte 117
+.byte 103
+.byte 103
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 105
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 114
+.byte 101
+.byte 115
+.byte 117
+.byte 108
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 0
+.align 1
+.L950:
+.byte 99
+.byte 111
+.byte 112
+.byte 101
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 117
+.byte 110
+.byte 97
+.byte 110
+.byte 116
+.byte 105
+.byte 99
+.byte 105
+.byte 112
+.byte 97
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 110
+.byte 101
+.byte 119
+.byte 108
+.byte 121
+.byte 32
+.byte 117
+.byte 110
+.byte 99
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 112
+.byte 97
+.byte 116
+.byte 104
+.byte 111
+.byte 108
+.byte 111
+.byte 103
+.byte 105
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L949:
+.byte 85
+.byte 115
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 105
+.byte 110
+.byte 118
+.byte 105
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 104
+.byte 101
+.byte 108
+.byte 112
+.byte 32
+.byte 100
+.byte 101
+.byte 98
+.byte 117
+.byte 103
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 97
+.byte 117
+.byte 103
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 115
+.byte 111
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 119
+.byte 105
+.byte 108
+.byte 108
+.byte 0
+.align 1
+.L946:
+.byte 65
+.byte 110
+.byte 115
+.byte 119
+.byte 101
+.byte 114
+.byte 32
+.byte 113
+.byte 117
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 89
+.byte 44
+.byte 32
+.byte 121
+.byte 44
+.byte 32
+.byte 78
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 110
+.byte 32
+.byte 40
+.byte 117
+.byte 110
+.byte 108
+.byte 101
+.byte 115
+.byte 115
+.byte 32
+.byte 111
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 119
+.byte 105
+.byte 115
+.byte 101
+.byte 32
+.byte 105
+.byte 110
+.byte 100
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 101
+.byte 100
+.byte 41
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L945:
+.byte 97
+.byte 109
+.byte 101
+.byte 110
+.byte 100
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 109
+.byte 97
+.byte 107
+.byte 101
+.byte 32
+.byte 102
+.byte 117
+.byte 114
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 101
+.byte 115
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L944:
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 97
+.byte 110
+.byte 121
+.byte 119
+.byte 97
+.byte 121
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 115
+.byte 101
+.byte 101
+.byte 32
+.byte 104
+.byte 111
+.byte 119
+.byte 32
+.byte 109
+.byte 97
+.byte 110
+.byte 121
+.byte 32
+.byte 109
+.byte 105
+.byte 108
+.byte 101
+.byte 115
+.byte 116
+.byte 111
+.byte 110
+.byte 101
+.byte 115
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 112
+.byte 97
+.byte 115
+.byte 115
+.byte 101
+.byte 115
+.byte 44
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 110
+.byte 0
+.align 1
+.L943:
+.byte 119
+.byte 97
+.byte 114
+.byte 110
+.byte 105
+.byte 110
+.byte 103
+.byte 46
+.byte 32
+.byte 32
+.byte 73
+.byte 102
+.byte 32
+.byte 112
+.byte 101
+.byte 114
+.byte 115
+.byte 117
+.byte 97
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 118
+.byte 97
+.byte 105
+.byte 108
+.byte 115
+.byte 32
+.byte 110
+.byte 97
+.byte 117
+.byte 103
+.byte 104
+.byte 116
+.byte 44
+.byte 32
+.byte 100
+.byte 111
+.byte 110
+.byte 39
+.byte 116
+.byte 32
+.byte 100
+.byte 101
+.byte 115
+.byte 112
+.byte 97
+.byte 105
+.byte 114
+.byte 32
+.byte 98
+.byte 117
+.byte 116
+.byte 32
+.byte 114
+.byte 117
+.byte 110
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 0
+.align 1
+.L942:
+.byte 116
+.byte 111
+.byte 32
+.byte 112
+.byte 101
+.byte 114
+.byte 115
+.byte 101
+.byte 118
+.byte 101
+.byte 114
+.byte 101
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 97
+.byte 32
+.byte 115
+.byte 117
+.byte 114
+.byte 114
+.byte 111
+.byte 103
+.byte 97
+.byte 116
+.byte 101
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 97
+.byte 102
+.byte 116
+.byte 101
+.byte 114
+.byte 44
+.byte 32
+.byte 112
+.byte 101
+.byte 114
+.byte 104
+.byte 97
+.byte 112
+.byte 115
+.byte 44
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 112
+.byte 108
+.byte 97
+.byte 121
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 115
+.byte 111
+.byte 109
+.byte 101
+.byte 0
+.align 1
+.L941:
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 108
+.byte 105
+.byte 107
+.byte 101
+.byte 32
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 47
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 111
+.byte 99
+.byte 99
+.byte 117
+.byte 114
+.byte 115
+.byte 44
+.byte 32
+.byte 98
+.byte 117
+.byte 116
+.byte 32
+.byte 114
+.byte 97
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 0
+.align 1
+.L940:
+.byte 116
+.byte 114
+.byte 121
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 112
+.byte 101
+.byte 114
+.byte 115
+.byte 117
+.byte 97
+.byte 100
+.byte 101
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 78
+.byte 79
+.byte 84
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 116
+.byte 101
+.byte 114
+.byte 109
+.byte 105
+.byte 110
+.byte 97
+.byte 116
+.byte 101
+.byte 32
+.byte 101
+.byte 120
+.byte 101
+.byte 99
+.byte 117
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 110
+.byte 32
+.byte 97
+.byte 110
+.byte 0
+.align 1
+.L939:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 96
+.byte 69
+.byte 78
+.byte 68
+.byte 32
+.byte 79
+.byte 70
+.byte 32
+.byte 84
+.byte 69
+.byte 83
+.byte 84
+.byte 39
+.byte 44
+.byte 10
+.byte 0
+.align 1
+.L938:
+.byte 76
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 115
+.byte 116
+.byte 111
+.byte 112
+.byte 32
+.byte 112
+.byte 114
+.byte 101
+.byte 109
+.byte 97
+.byte 116
+.byte 117
+.byte 114
+.byte 101
+.byte 108
+.byte 121
+.byte 44
+.byte 32
+.byte 105
+.byte 46
+.byte 101
+.byte 46
+.byte 32
+.byte 98
+.byte 101
+.byte 102
+.byte 111
+.byte 114
+.byte 101
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 112
+.byte 108
+.byte 97
+.byte 121
+.byte 105
+.byte 110
+.byte 103
+.byte 10
+.byte 0
+.align 1
+.L935:
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.L930:
+.byte 32
+.byte 32
+.byte 32
+.byte 80
+.byte 76
+.byte 69
+.byte 65
+.byte 83
+.byte 69
+.byte 32
+.byte 78
+.byte 79
+.byte 84
+.byte 73
+.byte 70
+.byte 89
+.byte 32
+.byte 75
+.byte 65
+.byte 82
+.byte 80
+.byte 73
+.byte 78
+.byte 75
+.byte 83
+.byte 73
+.byte 33
+.byte 10
+.byte 0
+.align 1
+.L929:
+.byte 37
+.byte 115
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 105
+.byte 110
+.byte 99
+.byte 111
+.byte 110
+.byte 115
+.byte 105
+.byte 115
+.byte 116
+.byte 101
+.byte 110
+.byte 116
+.byte 46
+.byte 46
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L927:
+.byte 9
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 90
+.byte 32
+.byte 42
+.byte 32
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.L926:
+.byte 9
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 49
+.byte 32
+.byte 42
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.L925:
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 100
+.byte 111
+.byte 101
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 109
+.byte 117
+.byte 116
+.byte 101
+.byte 33
+.byte 10
+.byte 0
+.align 1
+.L920:
+.byte 90
+.byte 32
+.byte 47
+.byte 32
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.L917:
+.byte 49
+.byte 32
+.byte 42
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 37
+.byte 103
+.byte 10
+.byte 0
+.align 1
+.L914:
+.byte 90
+.byte 32
+.byte 42
+.byte 32
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 0
+.align 1
+.L911:
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 9
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 101
+.byte 115
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 32
+.byte 0
+.align 1
+.L910:
+.byte 87
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 112
+.byte 114
+.byte 105
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 0
+.align 1
+.L905:
+.byte 84
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 33
+.byte 10
+.byte 0
+.align 1
+.L902:
+.byte 84
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 86
+.byte 69
+.byte 82
+.byte 89
+.byte 32
+.byte 83
+.byte 69
+.byte 82
+.byte 73
+.byte 79
+.byte 85
+.byte 83
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 33
+.byte 10
+.byte 0
+.align 1
+.L896:
+.byte 32
+.byte 104
+.byte 97
+.byte 115
+.byte 32
+.byte 78
+.byte 79
+.byte 84
+.byte 32
+.byte 106
+.byte 117
+.byte 115
+.byte 116
+.byte 32
+.byte 98
+.byte 101
+.byte 101
+.byte 110
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 97
+.byte 108
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L895:
+.byte 84
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 79
+.byte 46
+.byte 75
+.byte 46
+.byte 44
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 118
+.byte 105
+.byte 100
+.byte 101
+.byte 100
+.byte 32
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 47
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 0
+.align 1
+.L892:
+.byte 87
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 109
+.byte 97
+.byte 99
+.byte 104
+.byte 105
+.byte 110
+.byte 101
+.byte 32
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 40
+.byte 90
+.byte 32
+.byte 43
+.byte 32
+.byte 90
+.byte 41
+.byte 32
+.byte 47
+.byte 32
+.byte 90
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L888:
+.byte 40
+.byte 90
+.byte 32
+.byte 43
+.byte 32
+.byte 90
+.byte 41
+.byte 32
+.byte 47
+.byte 32
+.byte 90
+.byte 32
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 115
+.byte 97
+.byte 102
+.byte 101
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L887:
+.byte 83
+.byte 105
+.byte 110
+.byte 99
+.byte 101
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 100
+.byte 101
+.byte 110
+.byte 105
+.byte 101
+.byte 115
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 101
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 0
+.align 1
+.L883:
+.byte 83
+.byte 105
+.byte 109
+.byte 105
+.byte 108
+.byte 97
+.byte 114
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 114
+.byte 101
+.byte 112
+.byte 97
+.byte 110
+.byte 99
+.byte 105
+.byte 101
+.byte 115
+.byte 32
+.byte 104
+.byte 97
+.byte 118
+.byte 101
+.byte 32
+.byte 111
+.byte 99
+.byte 99
+.byte 117
+.byte 114
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 116
+.byte 105
+.byte 109
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L873:
+.byte 9
+.byte 9
+.byte 116
+.byte 104
+.byte 101
+.byte 121
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L872:
+.byte 9
+.byte 119
+.byte 104
+.byte 105
+.byte 99
+.byte 104
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 117
+.byte 110
+.byte 101
+.byte 113
+.byte 117
+.byte 97
+.byte 108
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 59
+.byte 10
+.byte 0
+.align 1
+.L871:
+.byte 9
+.byte 121
+.byte 105
+.byte 101
+.byte 108
+.byte 100
+.byte 101
+.byte 100
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 59
+.byte 10
+.byte 0
+.align 1
+.L870:
+.byte 9
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 32
+.byte 94
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 10
+.byte 0
+.align 1
+.L869:
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 10
+.byte 0
+.align 1
+.L868:
+.byte 87
+.byte 65
+.byte 82
+.byte 78
+.byte 73
+.byte 78
+.byte 71
+.byte 58
+.byte 32
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 10
+.byte 0
+.align 1
+.L850:
+.byte 9
+.byte 105
+.byte 110
+.byte 115
+.byte 116
+.byte 101
+.byte 97
+.byte 100
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 48
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L849:
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 40
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 32
+.byte 45
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 8
+.L841:
+.word 0x3ed4f8b5
+.word 0x88e368f1
+.align 1
+.L839:
+.byte 37
+.byte 115
+.byte 58
+.byte 32
+.byte 32
+.byte 37
+.byte 115
+.byte 0
+.align 1
+.L838:
+.byte 70
+.byte 76
+.byte 65
+.byte 87
+.byte 0
+.align 1
+.L837:
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 0
+.align 1
+.L836:
+.byte 83
+.byte 69
+.byte 82
+.byte 73
+.byte 79
+.byte 85
+.byte 83
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 0
+.align 1
+.L835:
+.byte 70
+.byte 65
+.byte 73
+.byte 76
+.byte 85
+.byte 82
+.byte 69
+.byte 0
+.align 1
+.L829:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 80
+.byte 97
+.byte 103
+.byte 101
+.byte 58
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 10
+.byte 0
+.align 1
+.L828:
+.byte 10
+.byte 68
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 105
+.byte 115
+.byte 32
+.byte 114
+.byte 101
+.byte 115
+.byte 117
+.byte 109
+.byte 101
+.byte 115
+.byte 32
+.byte 97
+.byte 102
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 109
+.byte 105
+.byte 108
+.byte 101
+.byte 115
+.byte 116
+.byte 111
+.byte 110
+.byte 101
+.byte 32
+.byte 78
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 32
+.byte 37
+.byte 100
+.byte 0
+.align 8
+.L826:
+.word 0xbff00000
+.word 0x0
+.align 1
+.L821:
+.byte 69
+.byte 78
+.byte 68
+.byte 32
+.byte 79
+.byte 70
+.byte 32
+.byte 84
+.byte 69
+.byte 83
+.byte 84
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L820:
+.byte 10
+.byte 65
+.byte 32
+.byte 116
+.byte 111
+.byte 116
+.byte 97
+.byte 108
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 102
+.byte 108
+.byte 111
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 112
+.byte 111
+.byte 105
+.byte 110
+.byte 116
+.byte 32
+.byte 101
+.byte 120
+.byte 99
+.byte 101
+.byte 112
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 119
+.byte 101
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 101
+.byte 103
+.byte 105
+.byte 115
+.byte 116
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L817:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 69
+.byte 120
+.byte 99
+.byte 101
+.byte 108
+.byte 108
+.byte 101
+.byte 110
+.byte 116
+.byte 33
+.byte 10
+.byte 0
+.align 1
+.L816:
+.byte 32
+.byte 100
+.byte 117
+.byte 114
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 71
+.byte 114
+.byte 97
+.byte 100
+.byte 117
+.byte 97
+.byte 108
+.byte 32
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L815:
+.byte 44
+.byte 10
+.byte 101
+.byte 120
+.byte 99
+.byte 101
+.byte 112
+.byte 116
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 112
+.byte 111
+.byte 115
+.byte 115
+.byte 105
+.byte 98
+.byte 108
+.byte 121
+.byte 32
+.byte 68
+.byte 111
+.byte 117
+.byte 98
+.byte 108
+.byte 101
+.byte 32
+.byte 82
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 105
+.byte 110
+.byte 103
+.byte 0
+.align 1
+.L814:
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L811:
+.byte 56
+.byte 53
+.byte 52
+.byte 0
+.align 1
+.L810:
+.byte 55
+.byte 53
+.byte 52
+.byte 0
+.align 1
+.L807:
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 112
+.byte 111
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 73
+.byte 69
+.byte 69
+.byte 69
+.byte 32
+.byte 115
+.byte 116
+.byte 97
+.byte 110
+.byte 100
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 80
+.byte 0
+.align 1
+.L806:
+.byte 82
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 111
+.byte 114
+.byte 109
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 0
+.align 1
+.L803:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 115
+.byte 101
+.byte 101
+.byte 109
+.byte 115
+.byte 32
+.byte 83
+.byte 97
+.byte 116
+.byte 105
+.byte 115
+.byte 102
+.byte 97
+.byte 99
+.byte 116
+.byte 111
+.byte 114
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L797:
+.byte 78
+.byte 111
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 117
+.byte 114
+.byte 101
+.byte 115
+.byte 44
+.byte 32
+.byte 100
+.byte 101
+.byte 102
+.byte 101
+.byte 99
+.byte 116
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 102
+.byte 108
+.byte 97
+.byte 119
+.byte 115
+.byte 32
+.byte 104
+.byte 97
+.byte 118
+.byte 101
+.byte 32
+.byte 98
+.byte 101
+.byte 101
+.byte 110
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L796:
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 39
+.byte 115
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 115
+.byte 101
+.byte 113
+.byte 117
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L795:
+.byte 80
+.byte 111
+.byte 116
+.byte 101
+.byte 110
+.byte 116
+.byte 105
+.byte 97
+.byte 108
+.byte 108
+.byte 121
+.byte 32
+.byte 102
+.byte 97
+.byte 116
+.byte 97
+.byte 108
+.byte 32
+.byte 70
+.byte 65
+.byte 73
+.byte 76
+.byte 85
+.byte 82
+.byte 69
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 104
+.byte 97
+.byte 118
+.byte 101
+.byte 32
+.byte 115
+.byte 112
+.byte 111
+.byte 105
+.byte 108
+.byte 101
+.byte 100
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 0
+.align 1
+.L792:
+.byte 117
+.byte 110
+.byte 97
+.byte 99
+.byte 99
+.byte 101
+.byte 112
+.byte 116
+.byte 97
+.byte 98
+.byte 108
+.byte 101
+.byte 32
+.byte 83
+.byte 101
+.byte 114
+.byte 105
+.byte 111
+.byte 117
+.byte 115
+.byte 32
+.byte 68
+.byte 101
+.byte 102
+.byte 101
+.byte 99
+.byte 116
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L791:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 104
+.byte 97
+.byte 115
+.byte 32
+.byte 0
+.align 1
+.L787:
+.byte 100
+.byte 101
+.byte 115
+.byte 112
+.byte 105
+.byte 116
+.byte 101
+.byte 32
+.byte 105
+.byte 110
+.byte 99
+.byte 111
+.byte 110
+.byte 118
+.byte 101
+.byte 110
+.byte 105
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 68
+.byte 101
+.byte 102
+.byte 101
+.byte 99
+.byte 116
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L786:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 65
+.byte 99
+.byte 99
+.byte 101
+.byte 112
+.byte 116
+.byte 97
+.byte 98
+.byte 108
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.L781:
+.byte 83
+.byte 97
+.byte 116
+.byte 105
+.byte 115
+.byte 102
+.byte 97
+.byte 99
+.byte 116
+.byte 111
+.byte 114
+.byte 121
+.byte 32
+.byte 116
+.byte 104
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 32
+.byte 102
+.byte 108
+.byte 97
+.byte 119
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L780:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 115
+.byte 101
+.byte 101
+.byte 109
+.byte 115
+.byte 32
+.byte 0
+.align 1
+.L769:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 32
+.byte 37
+.byte 45
+.byte 50
+.byte 57
+.byte 115
+.byte 32
+.byte 37
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L762:
+.byte 70
+.byte 76
+.byte 65
+.byte 87
+.byte 115
+.byte 32
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 61
+.byte 0
+.align 1
+.L761:
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 115
+.byte 32
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 61
+.byte 0
+.align 1
+.L760:
+.byte 83
+.byte 69
+.byte 82
+.byte 73
+.byte 79
+.byte 85
+.byte 83
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 115
+.byte 32
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 61
+.byte 0
+.align 1
+.L759:
+.byte 70
+.byte 65
+.byte 73
+.byte 76
+.byte 85
+.byte 82
+.byte 69
+.byte 115
+.byte 32
+.byte 32
+.byte 101
+.byte 110
+.byte 99
+.byte 111
+.byte 117
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 61
+.byte 0
+.align 1
+.L755:
+.byte 10
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 84
+.byte 114
+.byte 121
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 32
+.byte 48
+.byte 32
+.byte 47
+.byte 32
+.byte 48
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 100
+.byte 117
+.byte 99
+.byte 101
+.byte 115
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 0
+.align 1
+.L754:
+.byte 32
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L751:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 84
+.byte 114
+.byte 121
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 32
+.byte 49
+.byte 32
+.byte 47
+.byte 32
+.byte 48
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 100
+.byte 117
+.byte 99
+.byte 101
+.byte 115
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 0
+.align 1
+.L750:
+.byte 87
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 109
+.byte 101
+.byte 115
+.byte 115
+.byte 97
+.byte 103
+.byte 101
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 47
+.byte 111
+.byte 114
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 115
+.byte 32
+.byte 100
+.byte 111
+.byte 101
+.byte 115
+.byte 32
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 100
+.byte 117
+.byte 99
+.byte 101
+.byte 63
+.byte 10
+.byte 0
+.align 1
+.L749:
+.byte 32
+.byte 32
+.byte 105
+.byte 110
+.byte 115
+.byte 116
+.byte 101
+.byte 97
+.byte 100
+.byte 44
+.byte 32
+.byte 88
+.byte 32
+.byte 47
+.byte 32
+.byte 88
+.byte 32
+.byte 45
+.byte 32
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 45
+.byte 32
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L748:
+.byte 32
+.byte 32
+.byte 88
+.byte 32
+.byte 47
+.byte 32
+.byte 88
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 49
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 110
+.byte 32
+.byte 88
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.L743:
+.byte 32
+.byte 32
+.byte 88
+.byte 32
+.byte 47
+.byte 32
+.byte 88
+.byte 32
+.byte 32
+.byte 116
+.byte 114
+.byte 97
+.byte 112
+.byte 115
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 110
+.byte 32
+.byte 88
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 103
+.byte 10
+.byte 0
+.align 1
+.L728:
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 102
+.byte 97
+.byte 114
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 49
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L727:
+.byte 32
+.byte 117
+.byte 110
+.byte 98
+.byte 97
+.byte 108
+.byte 97
+.byte 110
+.byte 99
+.byte 101
+.byte 100
+.byte 32
+.byte 114
+.byte 97
+.byte 110
+.byte 103
+.byte 101
+.byte 59
+.byte 32
+.byte 85
+.byte 102
+.byte 84
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 42
+.byte 32
+.byte 86
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 9
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.L726:
+.byte 66
+.byte 97
+.byte 100
+.byte 108
+.byte 121
+.byte 0
+.align 1
+.L719:
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 102
+.byte 97
+.byte 114
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 40
+.byte 90
+.byte 41
+.byte 32
+.byte 94
+.byte 32
+.byte 50
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L718:
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.L706:
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 102
+.byte 97
+.byte 114
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 40
+.byte 90
+.byte 41
+.byte 32
+.byte 94
+.byte 32
+.byte 50
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L705:
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 119
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 112
+.byte 114
+.byte 105
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.L688:
+.byte 43
+.byte 45
+.byte 37
+.byte 103
+.byte 44
+.byte 32
+.byte 43
+.byte 45
+.byte 37
+.byte 103
+.byte 10
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 43
+.byte 45
+.byte 37
+.byte 103
+.byte 32
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 117
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 46
+.byte 0
+.align 1
+.L687:
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 105
+.byte 110
+.byte 118
+.byte 111
+.byte 108
+.byte 118
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 0
+.align 1
+.L681:
+.byte 97
+.byte 98
+.byte 111
+.byte 118
+.byte 101
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L680:
+.byte 65
+.byte 110
+.byte 121
+.byte 32
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 97
+.byte 108
+.byte 32
+.byte 115
+.byte 101
+.byte 112
+.byte 97
+.byte 114
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 42
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 111
+.byte 110
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.L679:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 86
+.byte 32
+.byte 47
+.byte 32
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L678:
+.byte 78
+.byte 111
+.byte 32
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 97
+.byte 108
+.byte 101
+.byte 100
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 86
+.byte 32
+.byte 42
+.byte 32
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.L677:
+.byte 84
+.byte 104
+.byte 101
+.byte 114
+.byte 101
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 32
+.byte 115
+.byte 97
+.byte 116
+.byte 117
+.byte 114
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 98
+.byte 101
+.byte 99
+.byte 97
+.byte 117
+.byte 115
+.byte 101
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 115
+.byte 121
+.byte 115
+.byte 116
+.byte 101
+.byte 109
+.byte 32
+.byte 116
+.byte 114
+.byte 97
+.byte 112
+.byte 115
+.byte 32
+.byte 111
+.byte 110
+.byte 32
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L676:
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 115
+.byte 97
+.byte 116
+.byte 117
+.byte 114
+.byte 97
+.byte 116
+.byte 101
+.byte 115
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 86
+.byte 48
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L673:
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 86
+.byte 32
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L664:
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 112
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 9
+.byte 115
+.byte 104
+.byte 114
+.byte 105
+.byte 110
+.byte 107
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L661:
+.byte 45
+.byte 40
+.byte 45
+.byte 89
+.byte 41
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 89
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L660:
+.byte 102
+.byte 105
+.byte 110
+.byte 100
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 0
+.align 1
+.L659:
+.byte 83
+.byte 101
+.byte 101
+.byte 109
+.byte 115
+.byte 32
+.byte 79
+.byte 46
+.byte 75
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L656:
+.byte 84
+.byte 114
+.byte 121
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 111
+.byte 110
+.byte 32
+.byte 89
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L655:
+.byte 67
+.byte 97
+.byte 110
+.byte 32
+.byte 96
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 45
+.byte 89
+.byte 39
+.byte 32
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 63
+.byte 10
+.byte 0
+.align 1
+.L648:
+.byte 84
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 103
+.byte 101
+.byte 110
+.byte 101
+.byte 114
+.byte 97
+.byte 116
+.byte 101
+.byte 32
+.byte 97
+.byte 110
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L647:
+.byte 83
+.byte 101
+.byte 97
+.byte 114
+.byte 99
+.byte 104
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 58
+.byte 10
+.byte 0
+.align 1
+.L646:
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 32
+.byte 110
+.byte 111
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 114
+.byte 101
+.byte 112
+.byte 97
+.byte 110
+.byte 99
+.byte 105
+.byte 101
+.byte 115
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L638:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 112
+.byte 111
+.byte 119
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 90
+.byte 94
+.byte 81
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 114
+.byte 32
+.byte 110
+.byte 101
+.byte 97
+.byte 114
+.byte 108
+.byte 121
+.byte 32
+.byte 101
+.byte 120
+.byte 116
+.byte 114
+.byte 101
+.byte 109
+.byte 101
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L637:
+.byte 65
+.byte 99
+.byte 99
+.byte 117
+.byte 114
+.byte 97
+.byte 99
+.byte 121
+.byte 32
+.byte 115
+.byte 101
+.byte 101
+.byte 109
+.byte 115
+.byte 32
+.byte 97
+.byte 100
+.byte 101
+.byte 113
+.byte 117
+.byte 97
+.byte 116
+.byte 101
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L630:
+.byte 9
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 105
+.byte 110
+.byte 118
+.byte 111
+.byte 108
+.byte 118
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 105
+.byte 110
+.byte 121
+.byte 32
+.byte 105
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 114
+.byte 97
+.byte 116
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L629:
+.byte 9
+.byte 84
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 109
+.byte 117
+.byte 99
+.byte 104
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 115
+.byte 112
+.byte 111
+.byte 105
+.byte 108
+.byte 32
+.byte 102
+.byte 105
+.byte 110
+.byte 97
+.byte 110
+.byte 99
+.byte 105
+.byte 97
+.byte 108
+.byte 10
+.byte 0
+.align 1
+.L628:
+.byte 9
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L627:
+.byte 9
+.byte 40
+.byte 49
+.byte 32
+.byte 43
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 32
+.byte 94
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 59
+.byte 10
+.byte 0
+.align 1
+.L626:
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 10
+.byte 0
+.align 1
+.L625:
+.byte 67
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 101
+.byte 100
+.byte 0
+.align 1
+.L618:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 88
+.byte 94
+.byte 40
+.byte 40
+.byte 88
+.byte 32
+.byte 43
+.byte 32
+.byte 49
+.byte 41
+.byte 32
+.byte 47
+.byte 32
+.byte 40
+.byte 88
+.byte 32
+.byte 45
+.byte 32
+.byte 49
+.byte 41
+.byte 41
+.byte 32
+.byte 118
+.byte 115
+.byte 46
+.byte 32
+.byte 101
+.byte 120
+.byte 112
+.byte 40
+.byte 50
+.byte 41
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 88
+.byte 32
+.byte 45
+.byte 62
+.byte 32
+.byte 49
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L614:
+.byte 84
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 79
+.byte 46
+.byte 75
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L611:
+.byte 32
+.byte 32
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L610:
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 98
+.byte 101
+.byte 116
+.byte 119
+.byte 101
+.byte 101
+.byte 110
+.byte 32
+.byte 48
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 10
+.byte 0
+.align 1
+.L606:
+.byte 97
+.byte 99
+.byte 116
+.byte 117
+.byte 97
+.byte 108
+.byte 108
+.byte 121
+.byte 32
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 121
+.byte 105
+.byte 101
+.byte 108
+.byte 100
+.byte 115
+.byte 58
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L605:
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 97
+.byte 102
+.byte 102
+.byte 108
+.byte 105
+.byte 99
+.byte 116
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 101
+.byte 120
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 10
+.byte 9
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 32
+.byte 94
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 59
+.byte 10
+.byte 0
+.align 1
+.L604:
+.byte 85
+.byte 102
+.byte 84
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 61
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 32
+.byte 94
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 10
+.byte 111
+.byte 110
+.byte 108
+.byte 121
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 0
+.align 1
+.L603:
+.byte 83
+.byte 105
+.byte 110
+.byte 99
+.byte 101
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 111
+.byte 99
+.byte 99
+.byte 117
+.byte 114
+.byte 115
+.byte 32
+.byte 98
+.byte 101
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L602:
+.byte 82
+.byte 97
+.byte 110
+.byte 103
+.byte 101
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 110
+.byte 97
+.byte 114
+.byte 114
+.byte 111
+.byte 119
+.byte 59
+.byte 32
+.byte 85
+.byte 49
+.byte 94
+.byte 37
+.byte 100
+.byte 32
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L597:
+.byte 109
+.byte 101
+.byte 114
+.byte 101
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 111
+.byte 102
+.byte 102
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L596:
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 115
+.byte 117
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 32
+.byte 108
+.byte 97
+.byte 114
+.byte 103
+.byte 101
+.byte 114
+.byte 32
+.byte 82
+.byte 101
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 110
+.byte 32
+.byte 0
+.align 1
+.L595:
+.byte 32
+.byte 98
+.byte 101
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 119
+.byte 104
+.byte 105
+.byte 99
+.byte 104
+.byte 0
+.align 1
+.L594:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.L593:
+.byte 88
+.byte 32
+.byte 47
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 49
+.byte 32
+.byte 43
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L592:
+.byte 88
+.byte 32
+.byte 47
+.byte 32
+.byte 90
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 115
+.byte 33
+.byte 10
+.byte 0
+.align 1
+.L589:
+.byte 101
+.byte 110
+.byte 99
+.byte 111
+.byte 117
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 97
+.byte 108
+.byte 116
+.byte 104
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 32
+.byte 97
+.byte 99
+.byte 116
+.byte 117
+.byte 97
+.byte 108
+.byte 108
+.byte 121
+.byte 10
+.byte 0
+.align 1
+.L588:
+.byte 32
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 32
+.byte 40
+.byte 102
+.byte 40
+.byte 88
+.byte 41
+.byte 32
+.byte 45
+.byte 32
+.byte 102
+.byte 40
+.byte 90
+.byte 41
+.byte 41
+.byte 32
+.byte 47
+.byte 32
+.byte 40
+.byte 88
+.byte 32
+.byte 45
+.byte 32
+.byte 90
+.byte 41
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L587:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 105
+.byte 102
+.byte 32
+.byte 40
+.byte 88
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 90
+.byte 41
+.byte 32
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 32
+.byte 32
+.byte 101
+.byte 108
+.byte 115
+.byte 101
+.byte 0
+.align 1
+.L586:
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 117
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 110
+.byte 32
+.byte 105
+.byte 110
+.byte 110
+.byte 111
+.byte 99
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 115
+.byte 116
+.byte 97
+.byte 116
+.byte 101
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 108
+.byte 105
+.byte 107
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.L585:
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 83
+.byte 69
+.byte 82
+.byte 73
+.byte 79
+.byte 85
+.byte 83
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 10
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 99
+.byte 97
+.byte 117
+.byte 115
+.byte 101
+.byte 115
+.byte 32
+.byte 0
+.align 1
+.L584:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 83
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 78
+.byte 79
+.byte 84
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 97
+.byte 108
+.byte 32
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 44
+.byte 32
+.byte 0
+.align 1
+.L583:
+.byte 121
+.byte 101
+.byte 116
+.byte 32
+.byte 88
+.byte 32
+.byte 45
+.byte 32
+.byte 90
+.byte 32
+.byte 121
+.byte 105
+.byte 101
+.byte 108
+.byte 100
+.byte 115
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L582:
+.byte 88
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 9
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 101
+.byte 113
+.byte 117
+.byte 97
+.byte 108
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L577:
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 47
+.byte 32
+.byte 85
+.byte 102
+.byte 84
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 101
+.byte 100
+.byte 33
+.byte 10
+.byte 0
+.align 1
+.L567:
+.byte 40
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 111
+.byte 102
+.byte 102
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 85
+.byte 102
+.byte 84
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 41
+.byte 32
+.byte 60
+.byte 32
+.byte 69
+.byte 48
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L566:
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 103
+.byte 114
+.byte 97
+.byte 100
+.byte 117
+.byte 97
+.byte 108
+.byte 59
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 105
+.byte 110
+.byte 99
+.byte 117
+.byte 114
+.byte 115
+.byte 32
+.byte 65
+.byte 98
+.byte 115
+.byte 111
+.byte 108
+.byte 117
+.byte 116
+.byte 101
+.byte 32
+.byte 69
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 61
+.byte 10
+.byte 0
+.align 1
+.L561:
+.byte 124
+.byte 81
+.byte 32
+.byte 45
+.byte 32
+.byte 89
+.byte 124
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L560:
+.byte 112
+.byte 114
+.byte 105
+.byte 110
+.byte 116
+.byte 32
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 81
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 89
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L559:
+.byte 81
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 89
+.byte 32
+.byte 119
+.byte 104
+.byte 105
+.byte 108
+.byte 101
+.byte 32
+.byte 100
+.byte 101
+.byte 110
+.byte 121
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 124
+.byte 81
+.byte 32
+.byte 45
+.byte 32
+.byte 89
+.byte 124
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 48
+.byte 59
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 115
+.byte 101
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.L558:
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 117
+.byte 115
+.byte 101
+.byte 115
+.byte 32
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 44
+.byte 32
+.byte 119
+.byte 104
+.byte 105
+.byte 99
+.byte 104
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 10
+.byte 0
+.align 1
+.L556:
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 101
+.byte 108
+.byte 115
+.byte 101
+.byte 32
+.byte 109
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 109
+.byte 97
+.byte 110
+.byte 121
+.byte 32
+.byte 108
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 119
+.byte 114
+.byte 111
+.byte 110
+.byte 103
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L555:
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 100
+.byte 111
+.byte 119
+.byte 110
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.L554:
+.byte 97
+.byte 112
+.byte 112
+.byte 114
+.byte 111
+.byte 97
+.byte 99
+.byte 104
+.byte 32
+.byte 97
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.L553:
+.byte 69
+.byte 105
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 97
+.byte 99
+.byte 99
+.byte 117
+.byte 114
+.byte 97
+.byte 99
+.byte 121
+.byte 32
+.byte 100
+.byte 101
+.byte 116
+.byte 101
+.byte 114
+.byte 105
+.byte 111
+.byte 114
+.byte 97
+.byte 116
+.byte 101
+.byte 115
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.L541:
+.byte 83
+.byte 109
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 115
+.byte 116
+.byte 114
+.byte 105
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 112
+.byte 111
+.byte 115
+.byte 105
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 69
+.byte 48
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L540:
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 110
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 100
+.byte 117
+.byte 99
+.byte 116
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L539:
+.byte 68
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 101
+.byte 110
+.byte 99
+.byte 101
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 115
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 97
+.byte 32
+.byte 104
+.byte 105
+.byte 103
+.byte 104
+.byte 101
+.byte 114
+.byte 0
+.align 1
+.L536:
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 110
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 101
+.byte 110
+.byte 99
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L535:
+.byte 80
+.byte 114
+.byte 111
+.byte 100
+.byte 117
+.byte 99
+.byte 116
+.byte 115
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 97
+.byte 32
+.byte 104
+.byte 105
+.byte 103
+.byte 104
+.byte 101
+.byte 114
+.byte 0
+.align 1
+.L528:
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 80
+.byte 115
+.byte 101
+.byte 117
+.byte 100
+.byte 111
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 112
+.byte 114
+.byte 105
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L527:
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 32
+.byte 115
+.byte 116
+.byte 105
+.byte 99
+.byte 107
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 97
+.byte 110
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 100
+.byte 108
+.byte 121
+.byte 32
+.byte 112
+.byte 111
+.byte 115
+.byte 105
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.L526:
+.byte 112
+.byte 111
+.byte 115
+.byte 105
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 44
+.byte 32
+.byte 105
+.byte 115
+.byte 110
+.byte 39
+.byte 116
+.byte 59
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 112
+.byte 114
+.byte 105
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L525:
+.byte 66
+.byte 117
+.byte 116
+.byte 32
+.byte 45
+.byte 80
+.byte 115
+.byte 101
+.byte 117
+.byte 100
+.byte 111
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 44
+.byte 32
+.byte 119
+.byte 104
+.byte 105
+.byte 99
+.byte 104
+.byte 32
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 98
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.L522:
+.byte 80
+.byte 115
+.byte 101
+.byte 117
+.byte 100
+.byte 111
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 112
+.byte 114
+.byte 105
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 97
+.byte 115
+.byte 58
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L521:
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 100
+.byte 108
+.byte 121
+.byte 32
+.byte 110
+.byte 101
+.byte 103
+.byte 97
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.L520:
+.byte 80
+.byte 111
+.byte 115
+.byte 105
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 101
+.byte 120
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 97
+.byte 110
+.byte 10
+.byte 0
+.align 1
+.L507:
+.byte 109
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 109
+.byte 97
+.byte 110
+.byte 121
+.byte 32
+.byte 108
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 119
+.byte 114
+.byte 111
+.byte 110
+.byte 103
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L483:
+.byte 83
+.byte 101
+.byte 101
+.byte 107
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 115
+.byte 32
+.byte 85
+.byte 102
+.byte 84
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 69
+.byte 48
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L480:
+.byte 46
+.byte 46
+.byte 46
+.byte 32
+.byte 110
+.byte 111
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 114
+.byte 101
+.byte 112
+.byte 97
+.byte 110
+.byte 99
+.byte 105
+.byte 115
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L477:
+.byte 9
+.byte 105
+.byte 110
+.byte 118
+.byte 111
+.byte 108
+.byte 118
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 105
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 114
+.byte 97
+.byte 116
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L476:
+.byte 69
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 115
+.byte 32
+.byte 108
+.byte 105
+.byte 107
+.byte 101
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 105
+.byte 110
+.byte 118
+.byte 97
+.byte 108
+.byte 105
+.byte 100
+.byte 97
+.byte 116
+.byte 101
+.byte 32
+.byte 102
+.byte 105
+.byte 110
+.byte 97
+.byte 110
+.byte 99
+.byte 105
+.byte 97
+.byte 108
+.byte 32
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.L455:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 112
+.byte 111
+.byte 119
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 90
+.byte 94
+.byte 105
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 115
+.byte 109
+.byte 97
+.byte 108
+.byte 108
+.byte 32
+.byte 73
+.byte 110
+.byte 116
+.byte 101
+.byte 103
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 90
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 105
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L452:
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 32
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 109
+.byte 97
+.byte 110
+.byte 121
+.byte 32
+.byte 108
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 119
+.byte 114
+.byte 111
+.byte 110
+.byte 103
+.byte 0
+.align 1
+.L450:
+.byte 116
+.byte 111
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 117
+.byte 108
+.byte 112
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L449:
+.byte 79
+.byte 98
+.byte 115
+.byte 101
+.byte 114
+.byte 118
+.byte 101
+.byte 100
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 115
+.byte 32
+.byte 114
+.byte 117
+.byte 110
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 0
+.align 1
+.L448:
+.byte 83
+.byte 113
+.byte 117
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 111
+.byte 111
+.byte 116
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 101
+.byte 105
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L445:
+.byte 83
+.byte 113
+.byte 117
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 111
+.byte 111
+.byte 116
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L440:
+.byte 83
+.byte 113
+.byte 117
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 111
+.byte 111
+.byte 116
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L435:
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 115
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 115
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L434:
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 94
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.L433:
+.byte 65
+.byte 110
+.byte 111
+.byte 109
+.byte 97
+.byte 108
+.byte 111
+.byte 117
+.byte 115
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 73
+.byte 110
+.byte 116
+.byte 101
+.byte 103
+.byte 101
+.byte 114
+.byte 32
+.byte 60
+.byte 32
+.byte 0
+.align 1
+.L393:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 100
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L371:
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 40
+.byte 88
+.byte 41
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 110
+.byte 45
+.byte 109
+.byte 111
+.byte 110
+.byte 111
+.byte 116
+.byte 111
+.byte 110
+.byte 105
+.byte 99
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 88
+.byte 32
+.byte 110
+.byte 101
+.byte 97
+.byte 114
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L370:
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 32
+.byte 104
+.byte 97
+.byte 115
+.byte 32
+.byte 112
+.byte 97
+.byte 115
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 97
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 77
+.byte 111
+.byte 110
+.byte 111
+.byte 116
+.byte 111
+.byte 110
+.byte 105
+.byte 99
+.byte 105
+.byte 116
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L353:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 32
+.byte 109
+.byte 111
+.byte 110
+.byte 111
+.byte 116
+.byte 111
+.byte 110
+.byte 105
+.byte 99
+.byte 105
+.byte 116
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L342:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 105
+.byte 102
+.byte 32
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 40
+.byte 88
+.byte 32
+.byte 42
+.byte 32
+.byte 88
+.byte 41
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 88
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 73
+.byte 110
+.byte 116
+.byte 101
+.byte 103
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 88
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L337:
+.byte 83
+.byte 113
+.byte 117
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 111
+.byte 111
+.byte 116
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 48
+.byte 46
+.byte 48
+.byte 44
+.byte 32
+.byte 45
+.byte 48
+.byte 46
+.byte 48
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 49
+.byte 46
+.byte 48
+.byte 32
+.byte 119
+.byte 114
+.byte 111
+.byte 110
+.byte 103
+.byte 0
+.align 1
+.L335:
+.byte 10
+.byte 82
+.byte 117
+.byte 110
+.byte 110
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 115
+.byte 113
+.byte 117
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 111
+.byte 111
+.byte 116
+.byte 40
+.byte 120
+.byte 41
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L334:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 78
+.byte 111
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 117
+.byte 114
+.byte 101
+.byte 115
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 105
+.byte 110
+.byte 116
+.byte 101
+.byte 103
+.byte 101
+.byte 114
+.byte 32
+.byte 112
+.byte 97
+.byte 105
+.byte 114
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L333:
+.byte 88
+.byte 32
+.byte 42
+.byte 32
+.byte 89
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 89
+.byte 32
+.byte 42
+.byte 32
+.byte 88
+.byte 32
+.byte 116
+.byte 114
+.byte 105
+.byte 97
+.byte 108
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 8
+.L324:
+.word 0x40080000
+.word 0x0
+.align 1
+.L323:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 111
+.byte 110
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 114
+.byte 97
+.byte 110
+.byte 100
+.byte 111
+.byte 109
+.byte 32
+.byte 112
+.byte 97
+.byte 105
+.byte 114
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L322:
+.byte 68
+.byte 111
+.byte 101
+.byte 115
+.byte 32
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 109
+.byte 117
+.byte 116
+.byte 101
+.byte 63
+.byte 32
+.byte 32
+.byte 0
+.align 1
+.L319:
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 40
+.byte 115
+.byte 41
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 103
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 117
+.byte 114
+.byte 101
+.byte 40
+.byte 115
+.byte 41
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 10
+.byte 40
+.byte 110
+.byte 111
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 97
+.byte 98
+.byte 111
+.byte 118
+.byte 101
+.byte 41
+.byte 32
+.byte 99
+.byte 111
+.byte 117
+.byte 110
+.byte 116
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 111
+.byte 110
+.byte 101
+.byte 32
+.byte 102
+.byte 108
+.byte 97
+.byte 119
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 102
+.byte 105
+.byte 110
+.byte 97
+.byte 108
+.byte 32
+.byte 116
+.byte 97
+.byte 108
+.byte 108
+.byte 121
+.byte 32
+.byte 98
+.byte 101
+.byte 108
+.byte 111
+.byte 119
+.byte 0
+.align 1
+.L317:
+.byte 83
+.byte 116
+.byte 105
+.byte 99
+.byte 107
+.byte 121
+.byte 32
+.byte 98
+.byte 105
+.byte 116
+.byte 32
+.byte 117
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 105
+.byte 110
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L316:
+.byte 83
+.byte 116
+.byte 105
+.byte 99
+.byte 107
+.byte 121
+.byte 32
+.byte 98
+.byte 105
+.byte 116
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 97
+.byte 114
+.byte 101
+.byte 110
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 117
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L299:
+.byte 67
+.byte 104
+.byte 101
+.byte 99
+.byte 107
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 115
+.byte 116
+.byte 105
+.byte 99
+.byte 107
+.byte 121
+.byte 32
+.byte 98
+.byte 105
+.byte 116
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L296:
+.byte 40
+.byte 88
+.byte 32
+.byte 45
+.byte 32
+.byte 89
+.byte 41
+.byte 32
+.byte 43
+.byte 32
+.byte 40
+.byte 89
+.byte 32
+.byte 45
+.byte 32
+.byte 88
+.byte 41
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 110
+.byte 32
+.byte 122
+.byte 101
+.byte 114
+.byte 111
+.byte 33
+.byte 10
+.byte 0
+.align 1
+.L293:
+.byte 65
+.byte 100
+.byte 100
+.byte 105
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 47
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 110
+.byte 101
+.byte 105
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L292:
+.byte 65
+.byte 100
+.byte 100
+.byte 47
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 0
+.align 1
+.L289:
+.byte 65
+.byte 100
+.byte 100
+.byte 105
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 47
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L282:
+.byte 65
+.byte 100
+.byte 100
+.byte 47
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L277:
+.byte 73
+.byte 110
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 108
+.byte 101
+.byte 116
+.byte 101
+.byte 32
+.byte 99
+.byte 97
+.byte 114
+.byte 114
+.byte 121
+.byte 45
+.byte 112
+.byte 114
+.byte 111
+.byte 112
+.byte 97
+.byte 103
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 65
+.byte 100
+.byte 100
+.byte 105
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 0
+.align 1
+.L273:
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 42
+.byte 32
+.byte 40
+.byte 32
+.byte 49
+.byte 32
+.byte 47
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 41
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 49
+.byte 0
+.align 1
+.L271:
+.byte 47
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 101
+.byte 105
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L268:
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L265:
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 0
+.align 1
+.L262:
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L257:
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 0
+.align 1
+.L254:
+.byte 42
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 101
+.byte 105
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L253:
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L250:
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L240:
+.byte 88
+.byte 32
+.byte 42
+.byte 32
+.byte 40
+.byte 49
+.byte 47
+.byte 88
+.byte 41
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 49
+.byte 0
+.align 1
+.L221:
+.byte 67
+.byte 104
+.byte 101
+.byte 99
+.byte 107
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 111
+.byte 110
+.byte 32
+.byte 109
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 121
+.byte 44
+.byte 32
+.byte 100
+.byte 105
+.byte 118
+.byte 105
+.byte 100
+.byte 101
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 97
+.byte 100
+.byte 100
+.byte 47
+.byte 115
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L220:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 42
+.byte 44
+.byte 32
+.byte 47
+.byte 44
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 45
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 104
+.byte 97
+.byte 118
+.byte 101
+.byte 32
+.byte 103
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 44
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 121
+.byte 32
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L217:
+.byte 32
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 32
+.byte 32
+.byte 105
+.byte 102
+.byte 32
+.byte 40
+.byte 88
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 49
+.byte 46
+.byte 48
+.byte 41
+.byte 32
+.byte 123
+.byte 46
+.byte 46
+.byte 46
+.byte 46
+.byte 46
+.byte 125
+.byte 32
+.byte 101
+.byte 108
+.byte 115
+.byte 101
+.byte 32
+.byte 123
+.byte 46
+.byte 46
+.byte 46
+.byte 47
+.byte 40
+.byte 88
+.byte 45
+.byte 49
+.byte 46
+.byte 48
+.byte 41
+.byte 46
+.byte 46
+.byte 46
+.byte 125
+.byte 10
+.byte 0
+.align 1
+.L216:
+.byte 32
+.byte 32
+.byte 115
+.byte 117
+.byte 99
+.byte 104
+.byte 32
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 97
+.byte 117
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 97
+.byte 103
+.byte 97
+.byte 105
+.byte 110
+.byte 115
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 122
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 97
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.L215:
+.byte 32
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 121
+.byte 105
+.byte 101
+.byte 108
+.byte 100
+.byte 115
+.byte 32
+.byte 32
+.byte 40
+.byte 49
+.byte 45
+.byte 85
+.byte 49
+.byte 41
+.byte 32
+.byte 45
+.byte 32
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 32
+.byte 44
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 101
+.byte 98
+.byte 121
+.byte 32
+.byte 118
+.byte 105
+.byte 116
+.byte 105
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 10
+.byte 0
+.align 1
+.L214:
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 115
+.byte 32
+.byte 32
+.byte 40
+.byte 49
+.byte 45
+.byte 85
+.byte 49
+.byte 41
+.byte 32
+.byte 60
+.byte 32
+.byte 49
+.byte 32
+.byte 32
+.byte 97
+.byte 108
+.byte 116
+.byte 104
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 10
+.byte 0
+.align 1
+.L211:
+.byte 45
+.byte 32
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 115
+.byte 32
+.byte 71
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 68
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 44
+.byte 32
+.byte 115
+.byte 111
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 99
+.byte 101
+.byte 108
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 111
+.byte 98
+.byte 115
+.byte 99
+.byte 117
+.byte 114
+.byte 101
+.byte 100
+.byte 0
+.align 1
+.L206:
+.byte 42
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 47
+.byte 111
+.byte 114
+.byte 32
+.byte 47
+.byte 32
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 109
+.byte 97
+.byte 110
+.byte 121
+.byte 32
+.byte 108
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 119
+.byte 114
+.byte 111
+.byte 110
+.byte 103
+.byte 0
+.align 1
+.L202:
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 49
+.byte 47
+.byte 49
+.byte 46
+.byte 48
+.byte 48
+.byte 48
+.byte 46
+.byte 46
+.byte 49
+.byte 32
+.byte 62
+.byte 61
+.byte 32
+.byte 49
+.byte 0
+.align 1
+.L200:
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 71
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 68
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 44
+.byte 32
+.byte 115
+.byte 111
+.byte 32
+.byte 88
+.byte 47
+.byte 49
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 88
+.byte 0
+.align 1
+.L195:
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 71
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 68
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 44
+.byte 32
+.byte 115
+.byte 111
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 32
+.byte 101
+.byte 120
+.byte 99
+.byte 101
+.byte 101
+.byte 100
+.byte 32
+.byte 49
+.byte 32
+.byte 117
+.byte 108
+.byte 112
+.byte 10
+.byte 111
+.byte 114
+.byte 32
+.byte 32
+.byte 49
+.byte 47
+.byte 51
+.byte 32
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 32
+.byte 51
+.byte 47
+.byte 57
+.byte 32
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 32
+.byte 57
+.byte 47
+.byte 50
+.byte 55
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 97
+.byte 103
+.byte 114
+.byte 101
+.byte 101
+.byte 0
+.align 1
+.L191:
+.byte 42
+.byte 32
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 109
+.byte 97
+.byte 110
+.byte 121
+.byte 32
+.byte 102
+.byte 105
+.byte 110
+.byte 97
+.byte 108
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 119
+.byte 114
+.byte 111
+.byte 110
+.byte 103
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L189:
+.byte 42
+.byte 32
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 71
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 68
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 44
+.byte 32
+.byte 115
+.byte 111
+.byte 32
+.byte 49
+.byte 42
+.byte 88
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 88
+.byte 0
+.align 1
+.L186:
+.byte 10
+.byte 67
+.byte 104
+.byte 101
+.byte 99
+.byte 107
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 103
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 42
+.byte 44
+.byte 32
+.byte 47
+.byte 44
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 45
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L185:
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 109
+.byte 97
+.byte 108
+.byte 105
+.byte 122
+.byte 101
+.byte 100
+.byte 44
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 98
+.byte 101
+.byte 46
+.byte 0
+.align 1
+.L180:
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 109
+.byte 97
+.byte 108
+.byte 105
+.byte 122
+.byte 101
+.byte 100
+.byte 32
+.byte 88
+.byte 61
+.byte 89
+.byte 44
+.byte 88
+.byte 43
+.byte 90
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 89
+.byte 43
+.byte 90
+.byte 33
+.byte 0
+.align 1
+.L176:
+.byte 114
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 108
+.byte 121
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 101
+.byte 120
+.byte 116
+.byte 114
+.byte 97
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 105
+.byte 102
+.byte 105
+.byte 99
+.byte 97
+.byte 110
+.byte 116
+.byte 32
+.byte 100
+.byte 101
+.byte 99
+.byte 105
+.byte 109
+.byte 97
+.byte 108
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L175:
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 101
+.byte 108
+.byte 121
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 97
+.byte 98
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 101
+.byte 120
+.byte 116
+.byte 114
+.byte 97
+.byte 32
+.byte 66
+.byte 45
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 44
+.byte 32
+.byte 105
+.byte 46
+.byte 101
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L174:
+.byte 83
+.byte 111
+.byte 109
+.byte 101
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 101
+.byte 120
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 101
+.byte 120
+.byte 116
+.byte 114
+.byte 97
+.byte 10
+.byte 0
+.align 1
+.L168:
+.byte 111
+.byte 102
+.byte 32
+.byte 97
+.byte 110
+.byte 10
+.byte 101
+.byte 120
+.byte 116
+.byte 114
+.byte 97
+.byte 45
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 0
+.align 1
+.L167:
+.byte 90
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 90
+.byte 50
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 0
+.align 1
+.L166:
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 101
+.byte 120
+.byte 97
+.byte 99
+.byte 116
+.byte 32
+.byte 114
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 97
+.byte 108
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 97
+.byte 32
+.byte 114
+.byte 101
+.byte 115
+.byte 117
+.byte 108
+.byte 116
+.byte 10
+.byte 0
+.align 1
+.L165:
+.byte 66
+.byte 101
+.byte 99
+.byte 97
+.byte 117
+.byte 115
+.byte 101
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 117
+.byte 110
+.byte 117
+.byte 115
+.byte 117
+.byte 97
+.byte 108
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 102
+.byte 0
+.align 1
+.L161:
+.byte 9
+.byte 85
+.byte 50
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 90
+.byte 50
+.byte 32
+.byte 45
+.byte 32
+.byte 85
+.byte 50
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.L160:
+.byte 9
+.byte 85
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 90
+.byte 49
+.byte 32
+.byte 45
+.byte 32
+.byte 85
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.L159:
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 0
+.align 1
+.L158:
+.byte 0
+.align 1
+.L151:
+.byte 84
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 102
+.byte 101
+.byte 97
+.byte 116
+.byte 117
+.byte 114
+.byte 101
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 102
+.byte 117
+.byte 114
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L146:
+.byte 80
+.byte 111
+.byte 115
+.byte 115
+.byte 105
+.byte 98
+.byte 108
+.byte 121
+.byte 32
+.byte 115
+.byte 111
+.byte 109
+.byte 101
+.byte 32
+.byte 112
+.byte 97
+.byte 114
+.byte 116
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 0
+.align 1
+.L145:
+.byte 98
+.byte 121
+.byte 32
+.byte 101
+.byte 120
+.byte 116
+.byte 114
+.byte 97
+.byte 45
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 101
+.byte 32
+.byte 101
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 101
+.byte 120
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L144:
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 115
+.byte 121
+.byte 109
+.byte 112
+.byte 116
+.byte 111
+.byte 109
+.byte 115
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 105
+.byte 110
+.byte 99
+.byte 111
+.byte 110
+.byte 115
+.byte 105
+.byte 115
+.byte 116
+.byte 101
+.byte 110
+.byte 99
+.byte 105
+.byte 101
+.byte 115
+.byte 32
+.byte 105
+.byte 110
+.byte 116
+.byte 114
+.byte 111
+.byte 100
+.byte 117
+.byte 99
+.byte 101
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L143:
+.byte 114
+.byte 101
+.byte 115
+.byte 112
+.byte 101
+.byte 99
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 108
+.byte 121
+.byte 32
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 44
+.byte 10
+.byte 0
+.align 1
+.L142:
+.byte 68
+.byte 105
+.byte 115
+.byte 97
+.byte 103
+.byte 114
+.byte 101
+.byte 101
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 97
+.byte 109
+.byte 111
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 115
+.byte 32
+.byte 88
+.byte 49
+.byte 44
+.byte 32
+.byte 89
+.byte 49
+.byte 44
+.byte 32
+.byte 90
+.byte 49
+.byte 44
+.byte 10
+.byte 0
+.align 1
+.L120:
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 119
+.byte 111
+.byte 114
+.byte 115
+.byte 101
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 110
+.byte 32
+.byte 53
+.byte 32
+.byte 100
+.byte 101
+.byte 99
+.byte 105
+.byte 109
+.byte 97
+.byte 108
+.byte 32
+.byte 102
+.byte 105
+.byte 103
+.byte 117
+.byte 114
+.byte 101
+.byte 115
+.byte 32
+.byte 32
+.byte 0
+.align 1
+.L118:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 105
+.byte 102
+.byte 105
+.byte 99
+.byte 97
+.byte 110
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 37
+.byte 102
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L117:
+.byte 108
+.byte 111
+.byte 103
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 105
+.byte 99
+.byte 32
+.byte 101
+.byte 110
+.byte 99
+.byte 111
+.byte 100
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 104
+.byte 97
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 99
+.byte 104
+.byte 97
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 101
+.byte 114
+.byte 105
+.byte 122
+.byte 101
+.byte 100
+.byte 32
+.byte 115
+.byte 111
+.byte 108
+.byte 101
+.byte 108
+.byte 121
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 85
+.byte 49
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L114:
+.byte 111
+.byte 102
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 105
+.byte 102
+.byte 105
+.byte 99
+.byte 97
+.byte 110
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 98
+.byte 117
+.byte 116
+.byte 44
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 105
+.byte 116
+.byte 115
+.byte 101
+.byte 108
+.byte 102
+.byte 44
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 109
+.byte 105
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 102
+.byte 108
+.byte 97
+.byte 119
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L113:
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 99
+.byte 104
+.byte 97
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 101
+.byte 114
+.byte 105
+.byte 122
+.byte 101
+.byte 100
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 97
+.byte 110
+.byte 32
+.byte 73
+.byte 110
+.byte 116
+.byte 101
+.byte 103
+.byte 101
+.byte 114
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 10
+.byte 0
+.align 1
+.L100:
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 102
+.byte 117
+.byte 122
+.byte 122
+.byte 121
+.byte 44
+.byte 88
+.byte 61
+.byte 49
+.byte 32
+.byte 98
+.byte 117
+.byte 116
+.byte 32
+.byte 88
+.byte 45
+.byte 49
+.byte 47
+.byte 50
+.byte 45
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 0
+.align 1
+.L96:
+.byte 40
+.byte 49
+.byte 45
+.byte 85
+.byte 49
+.byte 41
+.byte 45
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 60
+.byte 32
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 70
+.byte 65
+.byte 76
+.byte 83
+.byte 69
+.byte 44
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 46
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 115
+.byte 63
+.byte 0
+.align 8
+.L94:
+.word 0x40240000
+.word 0x0
+.align 1
+.L89:
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 103
+.byte 111
+.byte 111
+.byte 100
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 50
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 49
+.byte 48
+.byte 0
+.align 1
+.L85:
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 98
+.byte 105
+.byte 103
+.byte 58
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 111
+.byte 102
+.byte 102
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 98
+.byte 108
+.byte 101
+.byte 109
+.byte 115
+.byte 0
+.align 1
+.L83:
+.byte 77
+.byte 89
+.byte 83
+.byte 84
+.byte 69
+.byte 82
+.byte 89
+.byte 58
+.byte 32
+.byte 114
+.byte 101
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L82:
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 105
+.byte 114
+.byte 109
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 8
+.L79:
+.word 0x3f847ae1
+.word 0x47ae147b
+.align 1
+.L78:
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 98
+.byte 101
+.byte 116
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 99
+.byte 108
+.byte 111
+.byte 115
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 114
+.byte 101
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 115
+.byte 101
+.byte 112
+.byte 97
+.byte 114
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 85
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L77:
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 105
+.byte 114
+.byte 109
+.byte 115
+.byte 32
+.byte 99
+.byte 108
+.byte 111
+.byte 115
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 114
+.byte 101
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 115
+.byte 101
+.byte 112
+.byte 97
+.byte 114
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 85
+.byte 49
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L62:
+.byte 82
+.byte 101
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 114
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 10
+.byte 32
+.byte 0
+.align 1
+.L61:
+.byte 67
+.byte 108
+.byte 111
+.byte 115
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 114
+.byte 101
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 115
+.byte 101
+.byte 112
+.byte 97
+.byte 114
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 85
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 10
+.byte 0
+.align 1
+.L55:
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 102
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L46:
+.byte 83
+.byte 101
+.byte 97
+.byte 114
+.byte 99
+.byte 104
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L45:
+.byte 10
+.byte 0
+.align 1
+.L44:
+.byte 45
+.byte 49
+.byte 44
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 49
+.byte 47
+.byte 50
+.byte 44
+.byte 32
+.byte 49
+.byte 44
+.byte 32
+.byte 50
+.byte 44
+.byte 32
+.byte 51
+.byte 44
+.byte 32
+.byte 52
+.byte 44
+.byte 32
+.byte 53
+.byte 44
+.byte 32
+.byte 57
+.byte 44
+.byte 32
+.byte 50
+.byte 55
+.byte 44
+.byte 32
+.byte 51
+.byte 50
+.byte 32
+.byte 38
+.byte 32
+.byte 50
+.byte 52
+.byte 48
+.byte 32
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 79
+.byte 46
+.byte 75
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.L39:
+.byte 53
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 52
+.byte 43
+.byte 49
+.byte 44
+.byte 32
+.byte 50
+.byte 52
+.byte 48
+.byte 47
+.byte 51
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 56
+.byte 48
+.byte 44
+.byte 32
+.byte 50
+.byte 52
+.byte 48
+.byte 47
+.byte 52
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 54
+.byte 48
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 50
+.byte 52
+.byte 48
+.byte 47
+.byte 53
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 52
+.byte 56
+.byte 0
+.align 1
+.L35:
+.byte 57
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 51
+.byte 42
+.byte 51
+.byte 44
+.byte 32
+.byte 50
+.byte 55
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 57
+.byte 42
+.byte 51
+.byte 44
+.byte 32
+.byte 51
+.byte 50
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 56
+.byte 42
+.byte 52
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 51
+.byte 50
+.byte 45
+.byte 50
+.byte 55
+.byte 45
+.byte 52
+.byte 45
+.byte 49
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 0
+.align 1
+.L31:
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 43
+.byte 32
+.byte 40
+.byte 45
+.byte 49
+.byte 41
+.byte 32
+.byte 43
+.byte 32
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 0
+.align 1
+.L27:
+.byte 45
+.byte 49
+.byte 43
+.byte 49
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 40
+.byte 45
+.byte 49
+.byte 41
+.byte 43
+.byte 97
+.byte 98
+.byte 115
+.byte 40
+.byte 49
+.byte 41
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 45
+.byte 49
+.byte 43
+.byte 40
+.byte 45
+.byte 49
+.byte 41
+.byte 42
+.byte 40
+.byte 45
+.byte 49
+.byte 41
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 0
+.align 1
+.L23:
+.byte 51
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 50
+.byte 43
+.byte 49
+.byte 44
+.byte 32
+.byte 52
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 51
+.byte 43
+.byte 49
+.byte 44
+.byte 32
+.byte 52
+.byte 43
+.byte 50
+.byte 42
+.byte 40
+.byte 45
+.byte 50
+.byte 41
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 52
+.byte 45
+.byte 51
+.byte 45
+.byte 49
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 0
+.align 8
+.L21:
+.word 0x3f50624d
+.word 0xd2f1a9fc
+.align 1
+.L20:
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 45
+.byte 48
+.byte 46
+.byte 48
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 78
+.byte 111
+.byte 110
+.byte 45
+.byte 122
+.byte 101
+.byte 114
+.byte 111
+.byte 33
+.byte 10
+.byte 0
+.align 1
+.L15:
+.byte 48
+.byte 43
+.byte 48
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 49
+.byte 45
+.byte 49
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 49
+.byte 32
+.byte 60
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 49
+.byte 43
+.byte 49
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 50
+.byte 0
+.align 1
+.L13:
+.byte 80
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 119
+.byte 32
+.byte 82
+.byte 85
+.byte 78
+.byte 78
+.byte 73
+.byte 78
+.byte 71
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 115
+.byte 32
+.byte 111
+.byte 110
+.byte 32
+.byte 115
+.byte 109
+.byte 97
+.byte 108
+.byte 108
+.byte 32
+.byte 105
+.byte 110
+.byte 116
+.byte 101
+.byte 103
+.byte 101
+.byte 114
+.byte 115
+.byte 58
+.byte 10
+.byte 0
+.align 8
+.L9:
+.word 0x3ff00000
+.word 0x0
+.align 8
+.L8:
+.word 0x0
+.word 0x0
+.align 1
+.L3:
+.byte 10
+.byte 42
+.byte 32
+.byte 42
+.byte 32
+.byte 42
+.byte 32
+.byte 70
+.byte 76
+.byte 79
+.byte 65
+.byte 84
+.byte 73
+.byte 78
+.byte 71
+.byte 45
+.byte 80
+.byte 79
+.byte 73
+.byte 78
+.byte 84
+.byte 32
+.byte 69
+.byte 82
+.byte 82
+.byte 79
+.byte 82
+.byte 32
+.byte 42
+.byte 32
+.byte 42
+.byte 32
+.byte 42
+.byte 10
+.byte 0
diff --git a/lcc/sparc/solaris/tst/sort.1bk b/lcc/sparc/solaris/tst/sort.1bk
new file mode 100755
index 0000000..380d529
--- /dev/null
+++ b/lcc/sparc/solaris/tst/sort.1bk
@@ -0,0 +1,20 @@
+exchange(1,9)
+exchange(3,7)
+exchange(5,6)
+exchange(0,5)
+exchange(0,3)
+exchange(0,0)
+exchange(1,2)
+exchange(6,6)
+exchange(8,9)
+exchange(7,8)
+-51
+-1
+0
+1
+3
+10
+18
+32
+567
+789
diff --git a/lcc/sparc/solaris/tst/sort.2bk b/lcc/sparc/solaris/tst/sort.2bk
new file mode 100755
index 0000000..27488a1
--- /dev/null
+++ b/lcc/sparc/solaris/tst/sort.2bk
@@ -0,0 +1,5 @@
+tst/sort.c:23: warning: missing return value
+tst/sort.c:30: warning: missing return value
+tst/sort.c:37: warning: missing return value
+tst/sort.c:41: warning: missing return value
+tst/sort.c:65: warning: missing return value
diff --git a/lcc/sparc/solaris/tst/sort.sbk b/lcc/sparc/solaris/tst/sort.sbk
new file mode 100755
index 0000000..8f67ef5
--- /dev/null
+++ b/lcc/sparc/solaris/tst/sort.sbk
@@ -0,0 +1,202 @@
+.section ".data"
+.global in
+.type in,#object
+.align 4
+in:
+.word 0xa
+.word 0x20
+.word 0xffffffff
+.word 0x237
+.word 0x3
+.word 0x12
+.word 0x1
+.word 0xffffffcd
+.word 0x315
+.word 0x0
+.size in,40
+.global main
+.section ".text"
+.align 4
+main:
+save %sp,-96,%sp
+set in,%o0
+set 10,%o1
+call sort; nop
+mov %g0,%i5
+ba .L5; nop
+.L2:
+sll %i5,2,%i4
+set in,%i3
+ld [%i4+%i3],%o0
+call putd; nop
+set 10,%o0
+call putchar; nop
+.L3:
+add %i5,1,%i5
+.L5:
+mov %i5,%i4
+set 10,%i3
+cmp %i4,%i3; blu .L2; nop
+mov %g0,%i0
+.L1:
+ret; restore
+.type main,#function
+.size main,.-main
+.global putd
+.align 4
+putd:
+save %sp,-96,%sp
+cmp %i0,0; bge .L7; nop
+set 45,%o0
+call putchar; nop
+neg %i0,%i0
+.L7:
+sra %i0,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %i0,10,%i5
+cmp %i5,0; be .L9; nop
+sra %i0,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %i0,10,%o0
+call putd; nop
+.L9:
+sra %i0,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %i0,10,%g1
+; smul %g1,10,%g1; sub %i0,%g1,%i5
+add %i5,48,%o0
+call putchar; nop
+mov %g0,%i0
+.L6:
+ret; restore
+.type putd,#function
+.size putd,.-putd
+.global sort
+.align 4
+sort:
+save %sp,-96,%sp
+set xx,%i5
+st %i0,[%i5]
+mov %i0,%o0
+mov %g0,%o1
+sub %i1,1,%i5
+mov %i5,%i1
+mov %i5,%o2
+call quick; nop
+mov %g0,%i0
+.L11:
+ret; restore
+.type sort,#function
+.size sort,.-sort
+.global quick
+.align 4
+quick:
+save %sp,-96,%sp
+cmp %i1,%i2; bl .L13; nop
+ba .L12; nop
+.L13:
+mov %i0,%o0
+mov %i1,%o1
+mov %i2,%o2
+call partition; nop
+mov %o0,%i5
+mov %i0,%o0
+mov %i1,%o1
+sub %i5,1,%o2
+call quick; nop
+mov %i0,%o0
+add %i5,1,%o1
+mov %i2,%o2
+call quick; nop
+mov %g0,%i0
+.L12:
+ret; restore
+.type quick,#function
+.size quick,.-quick
+.global partition
+.align 4
+partition:
+save %sp,-96,%sp
+add %i2,1,%i2
+mov %i1,%i4
+sll %i4,2,%i3
+ld [%i3+%i0],%i5
+ba .L17; nop
+.L16:
+add %i1,1,%i1
+ba .L20; nop
+.L19:
+add %i1,1,%i1
+.L20:
+sll %i1,2,%i3
+ld [%i3+%i0],%i3
+cmp %i3,%i5; bl .L19; nop
+sub %i2,1,%i2
+ba .L23; nop
+.L22:
+sub %i2,1,%i2
+.L23:
+sll %i2,2,%i3
+ld [%i3+%i0],%i3
+cmp %i3,%i5; bg .L22; nop
+cmp %i1,%i2; bge .L25; nop
+sll %i1,2,%i3
+add %i3,%i0,%o0
+sll %i2,2,%i3
+add %i3,%i0,%o1
+call exchange; nop
+.L25:
+.L17:
+cmp %i1,%i2; bl .L16; nop
+sll %i4,2,%i3
+add %i3,%i0,%o0
+sll %i2,2,%i3
+add %i3,%i0,%o1
+call exchange; nop
+mov %i2,%i0
+.L15:
+ret; restore
+.type partition,#function
+.size partition,.-partition
+.global exchange
+.align 4
+exchange:
+save %sp,-96,%sp
+set .L28,%o0
+set xx,%i4
+ld [%i4],%i4
+mov %i0,%i3
+sub %i3,%i4,%i3
+sra %i3,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %i3,4,%o1
+mov %i1,%i3
+sub %i3,%i4,%i4
+sra %i4,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %i4,4,%o2
+call printf; nop
+ld [%i0],%i5
+ld [%i1],%i4
+st %i4,[%i0]
+st %i5,[%i1]
+mov %g0,%i0
+.L27:
+ret; restore
+.type exchange,#function
+.size exchange,.-exchange
+.section ".bss"
+.global xx
+.type xx,#object
+.size xx,4
+.common xx,4,4
+.section ".rodata"
+.align 1
+.L28:
+.byte 101
+.byte 120
+.byte 99
+.byte 104
+.byte 97
+.byte 110
+.byte 103
+.byte 101
+.byte 40
+.byte 37
+.byte 100
+.byte 44
+.byte 37
+.byte 100
+.byte 41
+.byte 10
+.byte 0
diff --git a/lcc/sparc/solaris/tst/spill.1bk b/lcc/sparc/solaris/tst/spill.1bk
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/sparc/solaris/tst/spill.1bk
diff --git a/lcc/sparc/solaris/tst/spill.2bk b/lcc/sparc/solaris/tst/spill.2bk
new file mode 100755
index 0000000..f7e3521
--- /dev/null
+++ b/lcc/sparc/solaris/tst/spill.2bk
@@ -0,0 +1,6 @@
+tst/spill.c:1: warning: missing return value
+tst/spill.c:3: warning: missing return value
+tst/spill.c:5: warning: missing return value
+tst/spill.c:7: warning: missing return value
+tst/spill.c:9: warning: missing return value
+tst/spill.c:17: warning: missing return value
diff --git a/lcc/sparc/solaris/tst/spill.sbk b/lcc/sparc/solaris/tst/spill.sbk
new file mode 100755
index 0000000..f30c800
--- /dev/null
+++ b/lcc/sparc/solaris/tst/spill.sbk
@@ -0,0 +1,207 @@
+.global main
+.section ".text"
+.align 4
+main:
+mov %g0,%o0
+.L1:
+retl; nop
+.type main,#function
+.size main,.-main
+.global f
+.align 4
+f:
+save %sp,-96,%sp
+call f; nop
+mov %o0,%i5
+call f; nop
+add %i5,%o0,%i0
+mov %g0,%i0
+.L2:
+ret; restore
+.type f,#function
+.size f,.-f
+.global f2
+.align 4
+f2:
+save %sp,-96,%sp
+call f; nop
+mov %o0,%i4
+cmp %i0,0; be .L5; nop
+call f; nop
+mov %o0,%i3
+mov %i3,%i5
+ba .L6; nop
+.L5:
+set 1,%i5
+.L6:
+add %i4,%i5,%i0
+mov %g0,%i0
+.L3:
+ret; restore
+.type f2,#function
+.size f2,.-f2
+.global f3
+.align 4
+f3:
+save %sp,-104,%sp
+mov %g0,%i5
+mov %g0,%i4
+mov %g0,%i3
+mov %g0,%i2
+mov %g0,%l7
+mov %g0,%l6
+mov %g0,%l5
+mov %g0,%l4
+st %g0,[%fp+-4]
+st %g0,[%fp+-8]
+mov %i1,%l3
+add %l3,4,%i1
+cmp %i0,0; be .L9; nop
+call f; nop
+mov %o0,%l2
+st %l2,[%fp+-12]
+ba .L10; nop
+.L9:
+st %g0,[%fp+-12]
+.L10:
+ld [%fp+-12],%l2
+st %l2,[%l3]
+mov %g0,%i0
+.L7:
+ret; restore
+.type f3,#function
+.size f3,.-f3
+.global f4
+.align 4
+f4:
+save %sp,-96,%sp
+mov %g0,%i5
+mov %g0,%i4
+mov %g0,%i3
+mov %g0,%i2
+mov %g0,%i1
+mov %g0,%i0
+set i,%l6
+ld [%l6],%l6
+sll %l6,3,%l5
+set a,%l4
+add %l5,%l4,%l4
+ld2 [%l4],%f30
+set b,%l4
+add %l5,%l4,%l5
+ld2 [%l5],%f28
+set .L15,%l5
+ld2 [%l5],%f26
+faddd %f30,%f28,%f24
+fcmped %f24,%f26; nop; fbue .L13; nop
+cmp %l6,0; be .L13; nop
+fsubd %f30,%f28,%f30
+fcmped %f30,%f26; nop; fbue .L13; nop
+set 1,%l7
+ba .L14; nop
+.L13:
+mov %g0,%l7
+.L14:
+set i,%l6
+st %l7,[%l6]
+mov %g0,%i0
+.L11:
+ret; restore
+.type f4,#function
+.size f4,.-f4
+.global f5
+.align 4
+f5:
+save %sp,-96,%sp
+set x,%i5
+set k,%i4
+ld [%i4],%i4
+set m,%i3
+ld [%i3],%i3
+set A,%i2
+ld [%i2],%i2
+smul %i3,%i4,%i1
+sll %i1,3,%i1
+add %i1,%i2,%i1
+set j,%i0
+ld [%i0],%i0
+smul %i3,%i0,%i3
+sll %i3,3,%i3
+add %i3,%i2,%i3
+set n,%i2
+ld [%i2],%i2
+set B,%l7
+ld [%l7],%l7
+smul %i2,%i4,%i4
+sll %i4,3,%i4
+add %i4,%l7,%i4
+smul %i2,%i0,%i2
+sll %i2,3,%i2
+add %i2,%l7,%i2
+ld2 [%i1],%f30
+ld2 [%i3],%f28
+fmuld %f30,%f28,%f30
+ld2 [%i4],%f28
+ld2 [%i2],%f26
+fmuld %f28,%f26,%f28
+faddd %f30,%f28,%f30
+st2 %f30,[%i5]
+ld2 [%i1],%f30
+ld2 [%i2],%f28
+fmuld %f30,%f28,%f30
+ld2 [%i4],%f28
+ld2 [%i3],%f26
+fmuld %f28,%f26,%f28
+fsubd %f30,%f28,%f30
+st2 %f30,[%i5]
+mov %g0,%i0
+.L16:
+ret; restore
+.type f5,#function
+.size f5,.-f5
+.section ".bss"
+.global x
+.type x,#object
+.size x,8
+.common x,8,8
+.global B
+.type B,#object
+.size B,4
+.common B,4,4
+.global A
+.type A,#object
+.size A,4
+.common A,4,4
+.global n
+.type n,#object
+.size n,4
+.common n,4,4
+.global m
+.type m,#object
+.size m,4
+.common m,4,4
+.global k
+.type k,#object
+.size k,4
+.common k,4,4
+.global j
+.type j,#object
+.size j,4
+.common j,4,4
+.global i
+.type i,#object
+.size i,4
+.common i,4,4
+.global b
+.type b,#object
+.size b,80
+.common b,80,8
+.global a
+.type a,#object
+.size a,80
+.common a,80,8
+.section ".rodata"
+.align 8
+.L15:
+.word 0x0
+.word 0x0
diff --git a/lcc/sparc/solaris/tst/stdarg.1bk b/lcc/sparc/solaris/tst/stdarg.1bk
new file mode 100755
index 0000000..097aef7
--- /dev/null
+++ b/lcc/sparc/solaris/tst/stdarg.1bk
@@ -0,0 +1,6 @@
+test 1
+test 2
+test 3
+test 4
+test 5.000000
+{1 2 3 4} {1 2 3 4} {1 2 3 4} {1 2 3 4} {1 2 3 4} {1 2 3 4}
diff --git a/lcc/sparc/solaris/tst/stdarg.2bk b/lcc/sparc/solaris/tst/stdarg.2bk
new file mode 100755
index 0000000..a832cf9
--- /dev/null
+++ b/lcc/sparc/solaris/tst/stdarg.2bk
@@ -0,0 +1 @@
+tst/stdarg.c:51: warning: missing return value
diff --git a/lcc/sparc/solaris/tst/stdarg.sbk b/lcc/sparc/solaris/tst/stdarg.sbk
new file mode 100755
index 0000000..1ceae3f
--- /dev/null
+++ b/lcc/sparc/solaris/tst/stdarg.sbk
@@ -0,0 +1,376 @@
+.section ".data"
+.global x
+.type x,#object
+.size x,16
+.align 4
+x:
+.word 0x1
+.word 0x2
+.word 0x3
+.word 0x4
+.global main
+.section ".text"
+.align 4
+main:
+save %sp,-192,%sp
+set .L2,%o0
+call print; nop
+set .L3,%o0
+set .L4,%o1
+call print; nop
+set .L5,%o0
+set 3,%o1
+set 10,%o2
+call print; nop
+set .L6,%o0
+set .L7,%o1
+set .L8,%o2
+set 4,%o3
+set 10,%o4
+call print; nop
+set .L9,%o0
+set .L7,%o1
+set .L8,%o2
+set .L10,%i5
+ld2 [%i5],%f30
+st %f30,[%sp+4*3+68]
+st %f31,[%sp+4*4+68]
+ld [%sp+4*3+68],%o3
+ld [%sp+4*4+68],%o4
+set 10,%o5
+call print; nop
+set .L11,%o0
+set x,%i5
+add -16,%fp,%i4
+ld [%r29+0],%r1
+ld [%r29+4],%r2
+st %r1,[%r28+0]
+st %r2,[%r28+4]
+ld [%r29+8],%r1
+ld [%r29+12],%r2
+st %r1,[%r28+8]
+st %r2,[%r28+12]
+add -16,%fp,%o1
+add -32,%fp,%i4
+ld [%r29+0],%r1
+ld [%r29+4],%r2
+st %r1,[%r28+0]
+st %r2,[%r28+4]
+ld [%r29+8],%r1
+ld [%r29+12],%r2
+st %r1,[%r28+8]
+st %r2,[%r28+12]
+add -32,%fp,%o2
+add -48,%fp,%i4
+ld [%r29+0],%r1
+ld [%r29+4],%r2
+st %r1,[%r28+0]
+st %r2,[%r28+4]
+ld [%r29+8],%r1
+ld [%r29+12],%r2
+st %r1,[%r28+8]
+st %r2,[%r28+12]
+add -48,%fp,%o3
+add -64,%fp,%i4
+ld [%r29+0],%r1
+ld [%r29+4],%r2
+st %r1,[%r28+0]
+st %r2,[%r28+4]
+ld [%r29+8],%r1
+ld [%r29+12],%r2
+st %r1,[%r28+8]
+st %r2,[%r28+12]
+add -64,%fp,%o4
+add -80,%fp,%i4
+ld [%r29+0],%r1
+ld [%r29+4],%r2
+st %r1,[%r28+0]
+st %r2,[%r28+4]
+ld [%r29+8],%r1
+ld [%r29+12],%r2
+st %r1,[%r28+8]
+st %r2,[%r28+12]
+add -80,%fp,%o5
+add -96,%fp,%i4
+ld [%r29+0],%r1
+ld [%r29+4],%r2
+st %r1,[%r28+0]
+st %r2,[%r28+4]
+ld [%r29+8],%r1
+ld [%r29+12],%r2
+st %r1,[%r28+8]
+st %r2,[%r28+12]
+add -96,%fp,%i5
+st %i5,[%sp+4*6+68]
+call print; nop
+mov %g0,%i0
+.L1:
+ret; restore
+.type main,#function
+.size main,.-main
+.global print
+.align 4
+print:
+save %sp,-112,%sp
+st %i1,[%fp+72]
+st %i2,[%fp+76]
+st %i3,[%fp+80]
+st %i4,[%fp+84]
+st %i5,[%fp+88]
+st %i0,[%fp+68]
+add 72,%fp,%i5
+ba .L18; nop
+.L15:
+ld [%fp+68],%i4
+ldsb [%i4],%i4
+cmp %i4,37; bne .L19; nop
+ld [%fp+68],%i3
+add %i3,1,%i3
+st %i3,[%fp+68]
+ldsb [%i3],%i4
+cmp %i4,115; be .L35; nop
+cmp %i4,115; bg .L40; nop
+.L39:
+cmp %i4,98; bl .L21; nop
+cmp %i4,102; bg .L21; nop
+sll %i4,2,%i3
+set .L41-392,%i2
+ld [%i3+%i2],%i3
+jmp %i3; nop
+.section ".rodata"
+.align 4
+.L41:
+.word .L24
+.word .L29
+.word .L31
+.word .L21
+.word .L37
+.section ".text"
+.L40:
+cmp %i4,119; be .L33; nop
+ba .L21; nop
+.L24:
+add %i5,4,%i3
+mov %i3,%i5
+add -16,%fp,%i2
+ld [%i3+-4],%i3
+ld [%r27+0],%r1
+ld [%r27+4],%r2
+st %r1,[%r26+0]
+st %r2,[%r26+4]
+ld [%r27+8],%r1
+ld [%r27+12],%r2
+st %r1,[%r26+8]
+st %r2,[%r26+12]
+set .L25,%o0
+ld [%fp+-16],%o1
+ld [%fp+-12],%o2
+ld [%fp+-8],%o3
+ld [%fp+-4],%o4
+call printf; nop
+ba .L20; nop
+.L29:
+set .L30,%o0
+add %i5,4,%i3
+mov %i3,%i5
+ldsb [%i3+-1],%o1
+call printf; nop
+ba .L20; nop
+.L31:
+set .L32,%o0
+set 4,%i3
+add %i5,%i3,%i3
+mov %i3,%i5
+ld [%i3+-4],%o1
+call printf; nop
+ba .L20; nop
+.L33:
+set .L34,%o0
+add %i5,4,%i3
+mov %i3,%i5
+ldsh [%i3+-2],%o1
+call printf; nop
+ba .L20; nop
+.L35:
+set .L36,%o0
+set 4,%i3
+add %i5,%i3,%i3
+mov %i3,%i5
+ld [%i3+-4],%o1
+call printf; nop
+ba .L20; nop
+.L37:
+set .L38,%o0
+set 8,%i3
+add %i5,%i3,%i3
+mov %i3,%i5
+ld2 [%i3+-8],%f30
+st %f30,[%sp+4*1+68]
+st %f31,[%sp+4*2+68]
+ld [%sp+4*1+68],%o1
+ld [%sp+4*2+68],%o2
+call printf; nop
+ba .L20; nop
+.L21:
+set .L30,%o0
+ld [%fp+68],%i3
+ldsb [%i3],%o1
+call printf; nop
+ba .L20; nop
+.L19:
+set .L30,%o0
+ld [%fp+68],%i3
+ldsb [%i3],%o1
+call printf; nop
+.L20:
+.L16:
+ld [%fp+68],%i3
+add %i3,1,%i3
+st %i3,[%fp+68]
+.L18:
+ld [%fp+68],%i3
+ldsb [%i3],%i3
+cmp %i3,0; bne .L15; nop
+mov %g0,%i0
+.L12:
+ret; restore
+.type print,#function
+.size print,.-print
+.section ".rodata"
+.align 1
+.L38:
+.byte 37
+.byte 102
+.byte 0
+.align 1
+.L36:
+.byte 37
+.byte 115
+.byte 0
+.align 1
+.L34:
+.byte 37
+.byte 120
+.byte 0
+.align 1
+.L32:
+.byte 37
+.byte 100
+.byte 0
+.align 1
+.L30:
+.byte 37
+.byte 99
+.byte 0
+.align 1
+.L25:
+.byte 123
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 125
+.byte 0
+.align 1
+.L11:
+.byte 37
+.byte 98
+.byte 32
+.byte 37
+.byte 98
+.byte 32
+.byte 37
+.byte 98
+.byte 32
+.byte 37
+.byte 98
+.byte 32
+.byte 37
+.byte 98
+.byte 32
+.byte 37
+.byte 98
+.byte 10
+.byte 0
+.align 8
+.L10:
+.word 0x40140000
+.word 0x0
+.align 1
+.L9:
+.byte 37
+.byte 115
+.byte 37
+.byte 115
+.byte 32
+.byte 37
+.byte 102
+.byte 37
+.byte 99
+.byte 0
+.align 1
+.L8:
+.byte 115
+.byte 116
+.byte 0
+.align 1
+.L7:
+.byte 116
+.byte 101
+.byte 0
+.align 1
+.L6:
+.byte 37
+.byte 115
+.byte 37
+.byte 115
+.byte 32
+.byte 37
+.byte 119
+.byte 37
+.byte 99
+.byte 0
+.align 1
+.L5:
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 37
+.byte 100
+.byte 37
+.byte 99
+.byte 0
+.align 1
+.L4:
+.byte 50
+.byte 0
+.align 1
+.L3:
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.L2:
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 49
+.byte 10
+.byte 0
diff --git a/lcc/sparc/solaris/tst/struct.1bk b/lcc/sparc/solaris/tst/struct.1bk
new file mode 100755
index 0000000..2358779
--- /dev/null
+++ b/lcc/sparc/solaris/tst/struct.1bk
@@ -0,0 +1,5 @@
+(-1,-1) is not within [10,10; 310,310]
+(1,1) is not within [10,10; 310,310]
+(20,300) is within [10,10; 310,310]
+(500,400) is not within [10,10; 310,310]
+ab
diff --git a/lcc/sparc/solaris/tst/struct.2bk b/lcc/sparc/solaris/tst/struct.2bk
new file mode 100755
index 0000000..8a01bb1
--- /dev/null
+++ b/lcc/sparc/solaris/tst/struct.2bk
@@ -0,0 +1,2 @@
+tst/struct.c:49: warning: missing return value
+tst/struct.c:68: warning: missing return value
diff --git a/lcc/sparc/solaris/tst/struct.sbk b/lcc/sparc/solaris/tst/struct.sbk
new file mode 100755
index 0000000..720b5a9
--- /dev/null
+++ b/lcc/sparc/solaris/tst/struct.sbk
@@ -0,0 +1,377 @@
+.global addpoint
+.section ".text"
+.align 4
+addpoint:
+save %sp,-96,%sp
+ld [%i0],%i5
+ld [%i1],%i4
+add %i5,%i4,%i5
+st %i5,[%i0]
+add %i0,4,%i5
+ld [%i5],%i4
+ld [%i1+4],%i3
+add %i4,%i3,%i4
+st %i4,[%i5]
+ld [%fp+64],%i5
+ld [%r24+0],%r1
+ld [%r24+4],%r2
+st %r1,[%r29+0]
+st %r2,[%r29+4]
+.L1:
+jmp %i7+12; restore
+.type addpoint,#function
+.size addpoint,.-addpoint
+.global canonrect
+.align 4
+canonrect:
+save %sp,-112,%sp
+ld [%i0],%i3
+ld [%i0+8],%i2
+cmp %i3,%i2; bge .L6; nop
+ld [%i0],%i5
+ba .L7; nop
+.L6:
+ld [%i0+8],%i5
+.L7:
+st %i5,[%fp+-16]
+ld [%i0+4],%i3
+ld [%i0+12],%i2
+cmp %i3,%i2; bge .L10; nop
+ld [%i0+4],%i4
+ba .L11; nop
+.L10:
+ld [%i0+12],%i4
+.L11:
+st %i4,[%fp+-12]
+ld [%i0],%i2
+ld [%i0+8],%i1
+cmp %i2,%i1; ble .L14; nop
+ld [%i0],%i3
+ba .L15; nop
+.L14:
+ld [%i0+8],%i3
+.L15:
+st %i3,[%fp+-8]
+ld [%i0+4],%i1
+ld [%i0+12],%l7
+cmp %i1,%l7; ble .L19; nop
+ld [%i0+4],%i2
+ba .L20; nop
+.L19:
+ld [%i0+12],%i2
+.L20:
+st %i2,[%fp+-4]
+ld [%fp+64],%i1
+add -16,%fp,%l7
+ld [%r23+0],%r1
+ld [%r23+4],%r2
+st %r1,[%r25+0]
+st %r2,[%r25+4]
+ld [%r23+8],%r1
+ld [%r23+12],%r2
+st %r1,[%r25+8]
+st %r2,[%r25+12]
+.L3:
+jmp %i7+12; restore
+.type canonrect,#function
+.size canonrect,.-canonrect
+.global makepoint
+.align 4
+makepoint:
+save %sp,-104,%sp
+st %i0,[%fp+-8]
+st %i1,[%fp+-4]
+ld [%fp+64],%i5
+add -8,%fp,%i4
+ld [%r28+0],%r1
+ld [%r28+4],%r2
+st %r1,[%r29+0]
+st %r2,[%r29+4]
+.L21:
+jmp %i7+12; restore
+.type makepoint,#function
+.size makepoint,.-makepoint
+.global makerect
+.align 4
+makerect:
+save %sp,-128,%sp
+add -16,%fp,%i5
+ld [%r24+0],%r1
+ld [%r24+4],%r2
+st %r1,[%r29+0]
+st %r2,[%r29+4]
+add -8,%fp,%i5
+ld [%r25+0],%r1
+ld [%r25+4],%r2
+st %r1,[%r29+0]
+st %r2,[%r29+4]
+add -32,%fp,%i5
+add -16,%fp,%i4
+ld [%r28+0],%r1
+ld [%r28+4],%r2
+st %r1,[%r29+0]
+st %r2,[%r29+4]
+ld [%r28+8],%r1
+ld [%r28+12],%r2
+st %r1,[%r29+8]
+st %r2,[%r29+12]
+add -32,%fp,%o0
+ld [%fp+64],%i5
+call canonrect; st %i5,[%sp+64]; unimp 16&0xfff
+.L24:
+jmp %i7+12; restore
+.type makerect,#function
+.size makerect,.-makerect
+.global ptinrect
+.align 4
+ptinrect:
+ld [%o0],%o4
+ld [%o1],%o3
+cmp %o4,%o3; bl .L29; nop
+ld [%o1+8],%o3
+cmp %o4,%o3; bge .L29; nop
+ld [%o0+4],%o4
+ld [%o1+4],%o3
+cmp %o4,%o3; bl .L29; nop
+ld [%o1+12],%o3
+cmp %o4,%o3; bge .L29; nop
+set 1,%o5
+ba .L30; nop
+.L29:
+mov %g0,%o5
+.L30:
+mov %o5,%o0
+.L27:
+retl; nop
+.type ptinrect,#function
+.size ptinrect,.-ptinrect
+.section ".data"
+.global y
+.type y,#object
+.size y,3
+.align 1
+y:
+.byte 97
+.byte 98
+.byte 0
+.global odd
+.section ".text"
+.align 4
+odd:
+save %sp,-96,%sp
+add -3,%fp,%i5
+ldub [%r24+0],%r1
+ldub [%r24+1],%r2
+stb %r1,[%r29+0]
+stb %r2,[%r29+1]
+ldub [%r24+2],%r1
+stb %r1,[%r29+2]
+set .L32,%o0
+add -3,%fp,%o1
+call printf; nop
+mov %g0,%i0
+.L31:
+ret; restore
+.type odd,#function
+.size odd,.-odd
+.section ".rodata"
+.align 4
+.L34:
+.word 0x0
+.word 0x0
+.align 4
+.L35:
+.word 0x140
+.word 0x140
+.align 4
+.L36:
+.word 0xffffffff
+.word 0xffffffff
+.word 0x1
+.word 0x1
+.word 0x14
+.word 0x12c
+.word 0x1f4
+.word 0x190
+.global main
+.section ".text"
+.align 4
+main:
+save %sp,-240,%sp
+add -64,%fp,%i4
+set .L34,%i3
+ld [%r27+0],%r1
+ld [%r27+4],%r2
+st %r1,[%r28+0]
+st %r2,[%r28+4]
+add -72,%fp,%i4
+set .L35,%i3
+ld [%r27+0],%r1
+ld [%r27+4],%r2
+st %r1,[%r28+0]
+st %r2,[%r28+4]
+add -32,%fp,%i4
+set .L36,%i3
+add %r27,32,%r27
+add %r28,32,%r3
+1: dec 8,%r3
+ld [%r27+-8],%r1
+ld [%r27+-4],%r2
+st %r1,[%r3+0]
+st %r2,[%r3+4]
+cmp %r3,%r28; bgt 1b; dec 8,%r27
+set -10,%i4
+mov %i4,%o0
+mov %i4,%o1
+add -80,%fp,%i4
+call makepoint; st %i4,[%sp+64]; unimp 8&0xfff
+add -88,%fp,%i4
+add -72,%fp,%i3
+ld [%r27+0],%r1
+ld [%r27+4],%r2
+st %r1,[%r28+0]
+st %r2,[%r28+4]
+add -88,%fp,%o0
+add -80,%fp,%o1
+add -96,%fp,%i4
+call addpoint; st %i4,[%sp+64]; unimp 8&0xfff
+set 10,%i4
+mov %i4,%o0
+mov %i4,%o1
+add -104,%fp,%i4
+call makepoint; st %i4,[%sp+64]; unimp 8&0xfff
+add -112,%fp,%i4
+add -64,%fp,%i3
+ld [%r27+0],%r1
+ld [%r27+4],%r2
+st %r1,[%r28+0]
+st %r2,[%r28+4]
+add -112,%fp,%o0
+add -104,%fp,%o1
+add -120,%fp,%i4
+call addpoint; st %i4,[%sp+64]; unimp 8&0xfff
+add -96,%fp,%o0
+add -120,%fp,%o1
+add -48,%fp,%i4
+call makerect; st %i4,[%sp+64]; unimp 16&0xfff
+mov %g0,%i5
+ba .L40; nop
+.L37:
+sll %i5,3,%i4
+add -32,%fp,%i3
+ld [%i4+%i3],%o0
+add -28,%fp,%i3
+ld [%i4+%i3],%o1
+add -56,%fp,%i4
+call makepoint; st %i4,[%sp+64]; unimp 8&0xfff
+set .L41,%o0
+sll %i5,3,%i4
+add -32,%fp,%i3
+ld [%i4+%i3],%o1
+ld [%fp+-52],%o2
+call printf; nop
+add -128,%fp,%i4
+add -56,%fp,%i3
+ld [%r27+0],%r1
+ld [%r27+4],%r2
+st %r1,[%r28+0]
+st %r2,[%r28+4]
+add -128,%fp,%o0
+add -144,%fp,%i4
+add -48,%fp,%i3
+ld [%r27+0],%r1
+ld [%r27+4],%r2
+st %r1,[%r28+0]
+st %r2,[%r28+4]
+ld [%r27+8],%r1
+ld [%r27+12],%r2
+st %r1,[%r28+8]
+st %r2,[%r28+12]
+add -144,%fp,%o1
+call ptinrect; nop
+cmp %o0,0; bne .L44; nop
+set .L46,%o0
+call printf; nop
+.L44:
+set .L47,%o0
+ld [%fp+-48],%o1
+ld [%fp+-44],%o2
+ld [%fp+-40],%o3
+ld [%fp+-36],%o4
+call printf; nop
+.L38:
+add %i5,1,%i5
+.L40:
+mov %i5,%i4
+set 4,%i3
+cmp %i4,%i3; blu .L37; nop
+add -123,%fp,%i4
+set y,%i3
+ldub [%r27+0],%r1
+ldub [%r27+1],%r2
+stb %r1,[%r28+0]
+stb %r2,[%r28+1]
+ldub [%r27+2],%r1
+stb %r1,[%r28+2]
+add -123,%fp,%o0
+call odd; nop
+mov %g0,%o0
+call exit; nop
+mov %g0,%i0
+.L33:
+ret; restore
+.type main,#function
+.size main,.-main
+.section ".rodata"
+.align 1
+.L47:
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 105
+.byte 110
+.byte 32
+.byte 91
+.byte 37
+.byte 100
+.byte 44
+.byte 37
+.byte 100
+.byte 59
+.byte 32
+.byte 37
+.byte 100
+.byte 44
+.byte 37
+.byte 100
+.byte 93
+.byte 10
+.byte 0
+.align 1
+.L46:
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 0
+.align 1
+.L41:
+.byte 40
+.byte 37
+.byte 100
+.byte 44
+.byte 37
+.byte 100
+.byte 41
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 0
+.align 1
+.L32:
+.byte 37
+.byte 115
+.byte 10
+.byte 0
diff --git a/lcc/sparc/solaris/tst/switch.1bk b/lcc/sparc/solaris/tst/switch.1bk
new file mode 100755
index 0000000..559e8e3
--- /dev/null
+++ b/lcc/sparc/solaris/tst/switch.1bk
@@ -0,0 +1,76 @@
+b = 0x8
+f = 0xc
+n = 0xa
+r = 0xd
+t = 0x9
+v = 0xb
+x = 0x78
+f:
+x = 0
+x = 1
+x = 2
+x = 2
+x = 2
+x = 2
+x = 2
+x = 7
+x = 8
+x = 9
+x = 9
+x = 9
+x = 9
+x = 9
+x = 9
+x = 9
+x = 16
+x = 17
+x = 18
+x = 19
+x = 20
+g:
+1 1
+1 2
+2 3
+2 4
+2 5
+3 6
+d 6
+3 7
+d 7
+3 8
+d 8
+d 9
+d 10
+h:
+i = 8
+i = 16
+i = 120
+i = 128
+i = 248
+i = 264
+i = 272
+i = 280
+i = 288
+i = 296
+i = 304
+i = 312
+488 defaults
+x = 0x1000000
+x = 0x2000000
+x = 0x3000000
+x = 0x4000000
+x = 0x5000000
+x = 0x6000000 (default)
+x = 0x7000000 (default)
+0
+1
+2
+3
+4
+5
+0
+1
+2
+3
+4
+5
diff --git a/lcc/sparc/solaris/tst/switch.2bk b/lcc/sparc/solaris/tst/switch.2bk
new file mode 100755
index 0000000..76387b3
--- /dev/null
+++ b/lcc/sparc/solaris/tst/switch.2bk
@@ -0,0 +1,5 @@
+tst/switch.c:55: warning: missing return value
+tst/switch.c:73: warning: missing return value
+tst/switch.c:97: warning: missing return value
+tst/switch.c:112: warning: missing return value
+tst/switch.c:137: warning: missing return value
diff --git a/lcc/sparc/solaris/tst/switch.sbk b/lcc/sparc/solaris/tst/switch.sbk
new file mode 100755
index 0000000..6a11cd9
--- /dev/null
+++ b/lcc/sparc/solaris/tst/switch.sbk
@@ -0,0 +1,713 @@
+.global main
+.section ".text"
+.align 4
+main:
+save %sp,-96,%sp
+set .L6,%i5
+ba .L5; nop
+.L2:
+ldsb [%i5],%o0
+call backslash; nop
+mov %o0,%i3
+set .L7,%o0
+ldsb [%i5],%o1
+mov %i3,%o2
+call printf; nop
+.L3:
+add %i5,1,%i5
+.L5:
+ldsb [%i5],%i3
+cmp %i3,0; bne .L2; nop
+call f; nop
+call g; nop
+call h; nop
+set 16777216,%i4
+ba .L11; nop
+.L8:
+mov %i4,%o0
+call big; nop
+.L9:
+set 16777216,%i3
+add %i4,%i3,%i4
+.L11:
+set 117440512,%i3
+and %i4,%i3,%i3
+cmp %i3,0; bne .L8; nop
+call limit; nop
+mov %g0,%i0
+.L1:
+ret; restore
+.type main,#function
+.size main,.-main
+.global backslash
+.align 4
+backslash:
+cmp %o0,102; be .L16; nop
+cmp %o0,102; bg .L22; nop
+.L21:
+cmp %o0,98; be .L15; nop
+ba .L13; nop
+.L22:
+cmp %o0,110; be .L17; nop
+cmp %o0,110; bl .L13; nop
+.L23:
+cmp %o0,114; be .L18; nop
+cmp %o0,116; be .L19; nop
+cmp %o0,118; be .L20; nop
+ba .L13; nop
+.L15:
+set 8,%o0
+ba .L12; nop
+.L16:
+set 12,%o0
+ba .L12; nop
+.L17:
+set 10,%o0
+ba .L12; nop
+.L18:
+set 13,%o0
+ba .L12; nop
+.L19:
+set 9,%o0
+ba .L12; nop
+.L20:
+set 11,%o0
+ba .L12; nop
+.L13:
+.L12:
+retl; nop
+.type backslash,#function
+.size backslash,.-backslash
+.global f
+.align 4
+f:
+save %sp,-96,%sp
+mov %g0,%i4
+set .L25,%o0
+call printf; nop
+mov %g0,%i5
+.L26:
+mov %i5,%i3
+cmp %i5,1; bl .L30; nop
+cmp %i5,20; bg .L30; nop
+sll %i5,2,%i2
+set .L42-4,%i1
+ld [%i2+%i1],%i2
+jmp %i2; nop
+.section ".rodata"
+.align 4
+.L42:
+.word .L32
+.word .L33
+.word .L30
+.word .L30
+.word .L30
+.word .L30
+.word .L34
+.word .L35
+.word .L36
+.word .L30
+.word .L30
+.word .L30
+.word .L30
+.word .L30
+.word .L30
+.word .L37
+.word .L38
+.word .L39
+.word .L40
+.word .L41
+.section ".text"
+.L32:
+mov %i5,%i4
+ba .L31; nop
+.L33:
+mov %i5,%i4
+ba .L31; nop
+.L34:
+mov %i5,%i4
+ba .L31; nop
+.L35:
+mov %i5,%i4
+ba .L31; nop
+.L36:
+mov %i5,%i4
+ba .L31; nop
+.L37:
+mov %i5,%i4
+ba .L31; nop
+.L38:
+mov %i5,%i4
+ba .L31; nop
+.L39:
+mov %i5,%i4
+ba .L31; nop
+.L40:
+mov %i5,%i4
+ba .L31; nop
+.L41:
+mov %i5,%i4
+.L30:
+.L31:
+set .L44,%o0
+mov %i4,%o1
+call printf; nop
+.L27:
+add %i5,1,%i5
+cmp %i5,20; ble .L26; nop
+mov %g0,%i0
+.L24:
+ret; restore
+.type f,#function
+.size f,.-f
+.global g
+.align 4
+g:
+save %sp,-96,%sp
+set .L46,%o0
+call printf; nop
+set 1,%i5
+.L47:
+cmp %i5,1001; bl .L64; nop
+cmp %i5,1004; bg .L65; nop
+sll %i5,2,%i4
+set .L66-4004,%i3
+ld [%i4+%i3],%i4
+jmp %i4; nop
+.section ".rodata"
+.align 4
+.L66:
+.word .L60
+.word .L60
+.word .L60
+.word .L60
+.section ".text"
+.L64:
+cmp %i5,1; bl .L51; nop
+cmp %i5,8; bg .L51; nop
+sll %i5,2,%i4
+set .L68-4,%i3
+ld [%i4+%i3],%i4
+jmp %i4; nop
+.section ".rodata"
+.align 4
+.L68:
+.word .L53
+.word .L53
+.word .L55
+.word .L55
+.word .L55
+.word .L57
+.word .L57
+.word .L57
+.section ".text"
+.L65:
+cmp %i5,3001; bl .L51; nop
+cmp %i5,3004; bg .L51; nop
+sll %i5,2,%i4
+set .L70-12004,%i3
+ld [%i4+%i3],%i4
+jmp %i4; nop
+.section ".rodata"
+.align 4
+.L70:
+.word .L62
+.word .L62
+.word .L62
+.word .L62
+.section ".text"
+.L53:
+set .L54,%o0
+mov %i5,%o1
+call printf; nop
+ba .L52; nop
+.L55:
+set .L56,%o0
+mov %i5,%o1
+call printf; nop
+ba .L52; nop
+.L57:
+set .L58,%o0
+mov %i5,%o1
+call printf; nop
+.L51:
+set .L59,%o0
+mov %i5,%o1
+call printf; nop
+ba .L52; nop
+.L60:
+set .L61,%o0
+mov %i5,%o1
+call printf; nop
+ba .L52; nop
+.L62:
+set .L63,%o0
+mov %i5,%o1
+call printf; nop
+.L52:
+.L48:
+add %i5,1,%i5
+cmp %i5,10; ble .L47; nop
+mov %g0,%i0
+.L45:
+ret; restore
+.type g,#function
+.size g,.-g
+.global h
+.align 4
+h:
+save %sp,-96,%sp
+mov %g0,%i4
+set .L73,%o0
+call printf; nop
+set 1,%i5
+.L74:
+cmp %i5,264; be .L86; nop
+cmp %i5,264; bg .L94; nop
+.L93:
+cmp %i5,120; be .L84; nop
+cmp %i5,120; bg .L96; nop
+.L95:
+cmp %i5,8; be .L83; nop
+cmp %i5,8; bl .L78; nop
+.L97:
+cmp %i5,16; be .L82; nop
+ba .L78; nop
+.L96:
+cmp %i5,128; be .L80; nop
+cmp %i5,128; bl .L78; nop
+.L98:
+cmp %i5,248; be .L87; nop
+ba .L78; nop
+.L94:
+cmp %i5,288; be .L91; nop
+cmp %i5,288; bg .L100; nop
+.L99:
+cmp %i5,272; be .L88; nop
+cmp %i5,272; bl .L78; nop
+.L101:
+cmp %i5,280; be .L85; nop
+ba .L78; nop
+.L100:
+cmp %i5,304; be .L89; nop
+cmp %i5,304; bg .L103; nop
+.L102:
+cmp %i5,296; be .L90; nop
+ba .L78; nop
+.L103:
+cmp %i5,312; be .L92; nop
+ba .L78; nop
+.L78:
+add %i4,1,%i4
+ba .L75; nop
+.L80:
+set .L81,%o0
+mov %i5,%o1
+call printf; nop
+ba .L79; nop
+.L82:
+set .L81,%o0
+mov %i5,%o1
+call printf; nop
+ba .L79; nop
+.L83:
+set .L81,%o0
+mov %i5,%o1
+call printf; nop
+ba .L79; nop
+.L84:
+set .L81,%o0
+mov %i5,%o1
+call printf; nop
+ba .L79; nop
+.L85:
+set .L81,%o0
+mov %i5,%o1
+call printf; nop
+ba .L79; nop
+.L86:
+set .L81,%o0
+mov %i5,%o1
+call printf; nop
+ba .L79; nop
+.L87:
+set .L81,%o0
+mov %i5,%o1
+call printf; nop
+ba .L79; nop
+.L88:
+set .L81,%o0
+mov %i5,%o1
+call printf; nop
+ba .L79; nop
+.L89:
+set .L81,%o0
+mov %i5,%o1
+call printf; nop
+ba .L79; nop
+.L90:
+set .L81,%o0
+mov %i5,%o1
+call printf; nop
+ba .L79; nop
+.L91:
+set .L81,%o0
+mov %i5,%o1
+call printf; nop
+ba .L79; nop
+.L92:
+set .L81,%o0
+mov %i5,%o1
+call printf; nop
+.L79:
+.L75:
+add %i5,1,%i5
+cmp %i5,500; ble .L74; nop
+set .L104,%o0
+mov %i4,%o1
+call printf; nop
+mov %g0,%i0
+.L72:
+ret; restore
+.type h,#function
+.size h,.-h
+.global big
+.align 4
+big:
+save %sp,-96,%sp
+set 0x6000000,%i4
+and %i0,%i4,%i5
+set 33554432,%i3
+cmp %i5,%i3; be .L111; nop
+cmp %i5,%i3; bg .L115; nop
+.L114:
+cmp %i5,-2; be .L109; nop
+cmp %i5,-1; be .L109; nop
+cmp %i5,0; be .L109; nop
+ba .L106; nop
+.L115:
+mov %i5,%i4
+set 67108864,%i3
+cmp %i4,%i3; be .L112; nop
+ba .L106; nop
+.L109:
+set .L110,%o0
+mov %i0,%o1
+call printf; nop
+ba .L107; nop
+.L111:
+set .L110,%o0
+mov %i0,%o1
+call printf; nop
+ba .L107; nop
+.L112:
+set .L110,%o0
+mov %i0,%o1
+call printf; nop
+ba .L107; nop
+.L106:
+set .L113,%o0
+mov %i0,%o1
+call printf; nop
+.L107:
+mov %g0,%i0
+.L105:
+ret; restore
+.type big,#function
+.size big,.-big
+.global limit
+.align 4
+limit:
+save %sp,-96,%sp
+set -2147483648,%i5
+.L117:
+set -2147483648,%i4
+cmp %i5,%i4; bl .L121; nop
+set -2147483644,%i3
+cmp %i5,%i3; bg .L121; nop
+sll %i5,2,%i3
+sll %i4,2,%i4
+sub %i3,%i4,%i4
+set .L134,%i3
+ld [%i4+%i3],%i4
+jmp %i4; nop
+.section ".rodata"
+.align 4
+.L134:
+.word .L123
+.word .L125
+.word .L127
+.word .L129
+.word .L131
+.section ".text"
+.L123:
+set .L124,%o0
+call printf; nop
+ba .L122; nop
+.L125:
+set .L126,%o0
+call printf; nop
+ba .L122; nop
+.L127:
+set .L128,%o0
+call printf; nop
+ba .L122; nop
+.L129:
+set .L130,%o0
+call printf; nop
+ba .L122; nop
+.L131:
+set .L132,%o0
+call printf; nop
+ba .L122; nop
+.L121:
+set .L133,%o0
+call printf; nop
+.L122:
+.L118:
+add %i5,1,%i5
+set -2147483643,%i4
+cmp %i5,%i4; ble .L117; nop
+set 2147483647,%i5
+.L135:
+set 2147483643,%i4
+cmp %i5,%i4; bl .L139; nop
+set 2147483647,%i3
+cmp %i5,%i3; bg .L139; nop
+sll %i5,2,%i3
+sll %i4,2,%i4
+sub %i3,%i4,%i4
+set .L146,%i3
+ld [%i4+%i3],%i4
+jmp %i4; nop
+.section ".rodata"
+.align 4
+.L146:
+.word .L145
+.word .L144
+.word .L143
+.word .L142
+.word .L141
+.section ".text"
+.L141:
+set .L124,%o0
+call printf; nop
+ba .L140; nop
+.L142:
+set .L126,%o0
+call printf; nop
+ba .L140; nop
+.L143:
+set .L128,%o0
+call printf; nop
+ba .L140; nop
+.L144:
+set .L130,%o0
+call printf; nop
+ba .L140; nop
+.L145:
+set .L132,%o0
+call printf; nop
+ba .L140; nop
+.L139:
+set .L133,%o0
+call printf; nop
+.L140:
+.L136:
+sub %i5,1,%i5
+set 2147483642,%i4
+cmp %i5,%i4; bge .L135; nop
+mov %g0,%i0
+.L116:
+ret; restore
+.type limit,#function
+.size limit,.-limit
+.section ".rodata"
+.align 1
+.L133:
+.byte 53
+.byte 10
+.byte 0
+.align 1
+.L132:
+.byte 52
+.byte 10
+.byte 0
+.align 1
+.L130:
+.byte 51
+.byte 10
+.byte 0
+.align 1
+.L128:
+.byte 50
+.byte 10
+.byte 0
+.align 1
+.L126:
+.byte 49
+.byte 10
+.byte 0
+.align 1
+.L124:
+.byte 48
+.byte 10
+.byte 0
+.align 1
+.L113:
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 120
+.byte 37
+.byte 120
+.byte 32
+.byte 40
+.byte 100
+.byte 101
+.byte 102
+.byte 97
+.byte 117
+.byte 108
+.byte 116
+.byte 41
+.byte 10
+.byte 0
+.align 1
+.L110:
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 120
+.byte 37
+.byte 120
+.byte 10
+.byte 0
+.align 1
+.L104:
+.byte 37
+.byte 100
+.byte 32
+.byte 100
+.byte 101
+.byte 102
+.byte 97
+.byte 117
+.byte 108
+.byte 116
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.L81:
+.byte 105
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L73:
+.byte 104
+.byte 58
+.byte 10
+.byte 0
+.align 1
+.L63:
+.byte 54
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L61:
+.byte 53
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L59:
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L58:
+.byte 51
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L56:
+.byte 50
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L54:
+.byte 49
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L46:
+.byte 103
+.byte 58
+.byte 10
+.byte 0
+.align 1
+.L44:
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L25:
+.byte 102
+.byte 58
+.byte 10
+.byte 0
+.align 1
+.L7:
+.byte 37
+.byte 99
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 120
+.byte 37
+.byte 120
+.byte 10
+.byte 0
+.align 1
+.L6:
+.byte 98
+.byte 102
+.byte 110
+.byte 114
+.byte 116
+.byte 118
+.byte 120
+.byte 0
diff --git a/lcc/sparc/solaris/tst/wf1.1bk b/lcc/sparc/solaris/tst/wf1.1bk
new file mode 100755
index 0000000..095e087
--- /dev/null
+++ b/lcc/sparc/solaris/tst/wf1.1bk
@@ -0,0 +1,74 @@
+5 a
+2 and
+5 buf
+16 c
+8 char
+1 compare
+4 cond
+5 count
+1 d
+1 die
+3 else
+1 entry
+1 eof
+4 err
+1 error
+1 exit
+1 folded
+1 for
+1 free
+1 frequencies
+1 frequency
+1 get
+2 getchar
+3 getword
+14 if
+2 in
+1 index
+1 input
+1 install
+8 int
+1 into
+1 is
+4 isletter
+1 it
+1 itself
+5 left
+1 letter
+7 lookup
+1 main
+2 malloc
+1 message
+2 n
+1 necessary
+12 next
+9 node
+4 of
+1 on
+1 or
+1 otherwise
+2 out
+8 p
+3 print
+2 printf
+16 return
+5 right
+4 root
+25 s
+2 storage
+3 strcmp
+1 strcpy
+1 strlen
+8 struct
+1 structures
+2 subtree
+1 t
+5 tprint
+9 tree
+1 uses
+1 version
+1 wf
+3 while
+21 word
+9 words
+2 z
diff --git a/lcc/sparc/solaris/tst/wf1.2bk b/lcc/sparc/solaris/tst/wf1.2bk
new file mode 100755
index 0000000..0e7a8a6
--- /dev/null
+++ b/lcc/sparc/solaris/tst/wf1.2bk
@@ -0,0 +1,2 @@
+tst/wf1.c:29: warning: missing return value
+tst/wf1.c:87: warning: missing return value
diff --git a/lcc/sparc/solaris/tst/wf1.sbk b/lcc/sparc/solaris/tst/wf1.sbk
new file mode 100755
index 0000000..2a8fb0f
--- /dev/null
+++ b/lcc/sparc/solaris/tst/wf1.sbk
@@ -0,0 +1,311 @@
+.global main
+.section ".text"
+.align 4
+main:
+save %sp,-120,%sp
+st %g0,[%fp+-24]
+set next,%i5
+st %g0,[%i5]
+ba .L3; nop
+.L2:
+add -20,%fp,%o0
+add -24,%fp,%o1
+call lookup; nop
+ld [%o0],%i4
+add %i4,1,%i4
+st %i4,[%o0]
+.L3:
+add -20,%fp,%o0
+call getword; nop
+cmp %o0,0; bne .L2; nop
+ld [%fp+-24],%o0
+call tprint; nop
+mov %g0,%i0
+.L1:
+ret; restore
+.type main,#function
+.size main,.-main
+.global err
+.align 4
+err:
+save %sp,-96,%sp
+set .L6,%o0
+mov %i0,%o1
+call printf; nop
+set 1,%o0
+call exit; nop
+mov %g0,%i0
+.L5:
+ret; restore
+.type err,#function
+.size err,.-err
+.global getword
+.align 4
+getword:
+save %sp,-96,%sp
+.L8:
+.L9:
+call getchar; nop
+mov %o0,%i3
+mov %i3,%i5
+cmp %i3,-1; be .L11; nop
+mov %i5,%o0
+call isletter; nop
+cmp %o0,0; be .L8; nop
+.L11:
+mov %i0,%i4
+ba .L15; nop
+.L12:
+mov %i4,%i3
+add %i3,1,%i4
+mov %i5,%i2
+stb %i2,[%i3]
+.L13:
+call getchar; nop
+mov %o0,%i5
+.L15:
+mov %i5,%o0
+call isletter; nop
+mov %o0,%i5
+cmp %o0,0; bne .L12; nop
+stb %g0,[%i4]
+mov %i4,%i3
+mov %i0,%i2
+cmp %i3,%i2; bleu .L16; nop
+set 1,%i0
+ba .L7; nop
+.L16:
+mov %g0,%i0
+.L7:
+ret; restore
+.type getword,#function
+.size getword,.-getword
+.global isletter
+.align 4
+isletter:
+cmp %o0,65; bl .L19; nop
+cmp %o0,90; bg .L19; nop
+add %o0,32,%o0
+.L19:
+cmp %o0,97; bl .L21; nop
+cmp %o0,122; bg .L21; nop
+ba .L18; nop
+.L21:
+mov %g0,%o0
+.L18:
+retl; nop
+.type isletter,#function
+.size isletter,.-isletter
+.global lookup
+.align 4
+lookup:
+save %sp,-96,%sp
+ld [%i1],%i4
+cmp %i4,%g0; be .L24; nop
+mov %i0,%o0
+ld [%i1],%i4
+ld [%i4+12],%o1
+call strcmp; nop
+mov %o0,%i5
+cmp %i5,0; bge .L26; nop
+mov %i0,%o0
+ld [%i1],%i4
+add %i4,4,%o1
+call lookup; nop
+mov %o0,%i0
+ba .L23; nop
+.L26:
+cmp %i5,0; ble .L28; nop
+mov %i0,%o0
+ld [%i1],%i4
+add %i4,8,%o1
+call lookup; nop
+mov %o0,%i0
+ba .L23; nop
+.L28:
+ld [%i1],%i0
+ba .L23; nop
+.L24:
+set next,%i4
+ld [%i4],%i4
+cmp %i4,2000; bl .L30; nop
+set .L32,%o0
+call err; nop
+.L30:
+set next,%i4
+ld [%i4],%i4
+sll %i4,4,%i4
+set words,%i3
+st %g0,[%i4+%i3]
+set next,%i4
+ld [%i4],%i4
+sll %i4,4,%i4
+set words+8,%i2
+st %g0,[%i4+%i2]
+set words+4,%i2
+st %g0,[%i4+%i2]
+mov %i0,%o0
+call strlen; nop
+mov %o0,%i4
+add %i4,1,%o0
+call malloc; nop
+set next,%i3
+ld [%i3],%i3
+sll %i3,4,%i3
+set words+12,%i2
+st %o0,[%i3+%i2]
+set next,%i4
+ld [%i4],%i4
+sll %i4,4,%i4
+set words+12,%i3
+ld [%i4+%i3],%i4
+cmp %i4,%g0; bne .L36; nop
+set .L39,%o0
+call err; nop
+.L36:
+set next,%i4
+ld [%i4],%i4
+sll %i4,4,%i4
+set words+12,%i3
+ld [%i4+%i3],%o0
+mov %i0,%o1
+call strcpy; nop
+set next,%i4
+ld [%i4],%i3
+add %i3,1,%i2
+st %i2,[%i4]
+sll %i3,4,%i4
+set words,%i3
+add %i4,%i3,%i4
+st %i4,[%i1]
+mov %i4,%i0
+.L23:
+ret; restore
+.type lookup,#function
+.size lookup,.-lookup
+.global tprint
+.align 4
+tprint:
+save %sp,-96,%sp
+mov %i0,%i5
+cmp %i5,%g0; be .L42; nop
+ld [%i0+4],%o0
+call tprint; nop
+set .L44,%o0
+ld [%i0],%o1
+ld [%i0+12],%o2
+call printf; nop
+ld [%i0+8],%o0
+call tprint; nop
+.L42:
+mov %g0,%i0
+.L41:
+ret; restore
+.type tprint,#function
+.size tprint,.-tprint
+.global strcmp
+.align 4
+strcmp:
+save %sp,-96,%sp
+ba .L47; nop
+.L46:
+mov %i0,%i5
+add %i5,1,%i0
+ldsb [%i5],%i5
+cmp %i5,0; bne .L49; nop
+mov %g0,%i0
+ba .L45; nop
+.L49:
+add %i1,1,%i1
+.L47:
+ldsb [%i0],%i5
+ldsb [%i1],%i4
+cmp %i5,%i4; be .L46; nop
+ldsb [%i0],%i5
+cmp %i5,0; bne .L51; nop
+set -1,%i0
+ba .L45; nop
+.L51:
+ldsb [%i1],%i5
+cmp %i5,0; bne .L53; nop
+set 1,%i0
+ba .L45; nop
+.L53:
+ldsb [%i0],%i5
+ldsb [%i1],%i4
+sub %i5,%i4,%i0
+.L45:
+ret; restore
+.type strcmp,#function
+.size strcmp,.-strcmp
+.section ".bss"
+.global next
+.type next,#object
+.size next,4
+.common next,4,4
+.global words
+.type words,#object
+.size words,32000
+.common words,32000,4
+.section ".rodata"
+.align 1
+.L44:
+.byte 37
+.byte 100
+.byte 9
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.L39:
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 119
+.byte 111
+.byte 114
+.byte 100
+.byte 32
+.byte 115
+.byte 116
+.byte 111
+.byte 114
+.byte 97
+.byte 103
+.byte 101
+.byte 0
+.align 1
+.L32:
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 110
+.byte 111
+.byte 100
+.byte 101
+.byte 32
+.byte 115
+.byte 116
+.byte 111
+.byte 114
+.byte 97
+.byte 103
+.byte 101
+.byte 0
+.align 1
+.L6:
+.byte 63
+.byte 32
+.byte 37
+.byte 115
+.byte 10
+.byte 0
diff --git a/lcc/sparc/solaris/tst/yacc.1bk b/lcc/sparc/solaris/tst/yacc.1bk
new file mode 100755
index 0000000..b08a02f
--- /dev/null
+++ b/lcc/sparc/solaris/tst/yacc.1bk
@@ -0,0 +1,10 @@
+a
+b
+load
+negate
+push 5
+c
+load
+multiply
+add
+store
diff --git a/lcc/sparc/solaris/tst/yacc.2bk b/lcc/sparc/solaris/tst/yacc.2bk
new file mode 100755
index 0000000..a84aa5b
--- /dev/null
+++ b/lcc/sparc/solaris/tst/yacc.2bk
@@ -0,0 +1,3 @@
+tst/yacc.c:345: warning: missing return value
+tst/yacc.c:349: warning: missing return value
+tst/yacc.c:359: warning: missing return value
diff --git a/lcc/sparc/solaris/tst/yacc.sbk b/lcc/sparc/solaris/tst/yacc.sbk
new file mode 100755
index 0000000..3c29bf5
--- /dev/null
+++ b/lcc/sparc/solaris/tst/yacc.sbk
@@ -0,0 +1,2247 @@
+.section ".data"
+.global yyin
+.type yyin,#object
+.size yyin,4
+.align 4
+yyin:
+.word __iob
+.global yyout
+.type yyout,#object
+.size yyout,4
+.align 4
+yyout:
+.word __iob+16
+.global yylex
+.section ".text"
+.align 4
+yylex:
+save %sp,-96,%sp
+ba .L5; nop
+.L4:
+.L7:
+cmp %i5,-1; bl .L8; nop
+cmp %i5,4; bg .L8; nop
+sll %i5,2,%i4
+set .L19+4,%i3
+ld [%i4+%i3],%i4
+jmp %i4; nop
+.section ".rodata"
+.align 4
+.L19:
+.word .L9
+.word .L10
+.word .L13
+.word .L14
+.word .L9
+.word .L16
+.section ".text"
+.L10:
+call yywrap; nop
+cmp %o0,0; be .L9; nop
+mov %g0,%i0
+ba .L3; nop
+.L13:
+set 257,%i0
+ba .L3; nop
+.L14:
+set 258,%i0
+ba .L3; nop
+.L16:
+set yytext,%i4
+ldsb [%i4],%i0
+ba .L3; nop
+.L8:
+set yyout,%i4
+ld [%i4],%o0
+set .L18,%o1
+mov %i5,%o2
+call fprintf; nop
+.L9:
+.L5:
+call yylook; nop
+mov %o0,%i5
+cmp %o0,0; bge .L4; nop
+mov %g0,%i0
+.L3:
+ret; restore
+.type yylex,#function
+.size yylex,.-yylex
+.section ".data"
+.global yyvstop
+.type yyvstop,#object
+.align 4
+yyvstop:
+.word 0x0
+.word 0x4
+.word 0x0
+.word 0x3
+.word 0x4
+.word 0x0
+.word 0x2
+.word 0x4
+.word 0x0
+.word 0x1
+.word 0x4
+.word 0x0
+.word 0x2
+.word 0x0
+.word 0x1
+.word 0x0
+.word 0x0
+.size yyvstop,68
+.global yycrank
+.type yycrank,#object
+.align 1
+yycrank:
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x1
+.byte 0x3
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x1
+.byte 0x4
+.byte 0x1
+.byte 0x3
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x1
+.byte 0x5
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x5
+.byte 0x7
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x1
+.byte 0x6
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x6
+.byte 0x8
+.byte 0x0
+.byte 0x0
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x6
+.byte 0x8
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.byte 0x0
+.size yycrank,290
+.global yysvec
+.type yysvec,#object
+.align 4
+yysvec:
+.word 0x0
+.word 0x0
+.word 0x0
+.word yycrank-2
+.word 0x0
+.word 0x0
+.word yycrank
+.word yysvec+12
+.word 0x0
+.word yycrank
+.word 0x0
+.word yyvstop+4
+.word yycrank
+.word 0x0
+.word yyvstop+12
+.word yycrank+4
+.word 0x0
+.word yyvstop+24
+.word yycrank+38
+.word 0x0
+.word yyvstop+36
+.word yycrank
+.word yysvec+60
+.word yyvstop+48
+.word yycrank
+.word yysvec+72
+.word yyvstop+56
+.word 0x0
+.word 0x0
+.word 0x0
+.size yysvec,120
+.global yytop
+.type yytop,#object
+.size yytop,4
+.align 4
+yytop:
+.word yycrank+282
+.global yybgin
+.type yybgin,#object
+.size yybgin,4
+.align 4
+yybgin:
+.word yysvec+12
+.global yymatch
+.type yymatch,#object
+.align 1
+yymatch:
+.byte 0
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 9
+.byte 10
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 9
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 65
+.byte 1
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 0
+.size yymatch,129
+.global yyextra
+.type yyextra,#object
+.align 1
+yyextra:
+.byte 0
+.byte 0
+.byte 0
+.byte 0
+.byte 0
+.byte 0
+.byte 0
+.byte 0
+.byte 0
+.size yyextra,9
+.global yylineno
+.type yylineno,#object
+.size yylineno,4
+.align 4
+yylineno:
+.word 0x1
+.global yysptr
+.type yysptr,#object
+.size yysptr,4
+.align 4
+yysptr:
+.word yysbuf
+.global yyprevious
+.type yyprevious,#object
+.size yyprevious,4
+.align 4
+yyprevious:
+.word 0xa
+.global yylook
+.section ".text"
+.align 4
+yylook:
+save %sp,-96,%sp
+set yymorfg,%l6
+ld [%l6],%l6
+cmp %l6,0; bne .L36; nop
+set yytext,%i2
+ba .L37; nop
+.L36:
+set yymorfg,%l6
+st %g0,[%l6]
+set yyleng,%l6
+ld [%l6],%l6
+set yytext,%l5
+add %l6,%l5,%i2
+.L37:
+.L38:
+set yylstate,%i4
+set yybgin,%l6
+ld [%l6],%l6
+mov %l6,%i5
+set yyestate,%l5
+st %l6,[%l5]
+set yyprevious,%l6
+ld [%l6],%l6
+cmp %l6,10; bne .L42; nop
+add %i5,12,%i5
+.L42:
+.L44:
+ld [%i5],%i3
+mov %i3,%l6
+set yycrank,%l5
+cmp %l6,%l5; bne .L48; nop
+ld [%i5+4],%l7
+mov %l7,%l6
+cmp %l6,%g0; bne .L50; nop
+ba .L95; nop
+.L50:
+ld [%l7],%l6
+set yycrank,%l5
+cmp %l6,%l5; bne .L52; nop
+ba .L95; nop
+.L52:
+.L48:
+mov %i2,%l3
+add %l3,1,%i2
+set yysptr,%l2
+ld [%l2],%l2
+set yysbuf,%l1
+cmp %l2,%l1; bleu .L62; nop
+set yysptr,%l2
+ld [%l2],%l1
+add %l1,-1,%l1
+st %l1,[%l2]
+ldsb [%l1],%l4
+ba .L63; nop
+.L62:
+set yyin,%l2
+ld [%l2],%l2
+ld [%l2],%l1
+sub %l1,1,%l1
+st %l1,[%l2]
+cmp %l1,0; bge .L64; nop
+set yyin,%l2
+ld [%l2],%o0
+call __filbuf; nop
+mov %o0,%l2
+st %l2,[%fp+-4]
+ba .L65; nop
+.L64:
+set yyin,%l2
+ld [%l2],%l2
+add %l2,4,%l2
+ld [%l2],%l1
+add %l1,1,%l0
+st %l0,[%l2]
+ldub [%l1],%l2
+st %l2,[%fp+-4]
+.L65:
+ld [%fp+-4],%l4
+.L63:
+set yytchar,%l2
+st %l4,[%l2]
+cmp %l4,10; bne .L60; nop
+set yylineno,%l2
+ld [%l2],%l1
+add %l1,1,%l1
+st %l1,[%l2]
+set yytchar,%l2
+ld [%l2],%l5
+ba .L61; nop
+.L60:
+set yytchar,%l2
+ld [%l2],%l5
+.L61:
+cmp %l5,-1; bne .L58; nop
+mov %g0,%l6
+ba .L59; nop
+.L58:
+set yytchar,%l2
+ld [%l2],%l6
+.L59:
+mov %l6,%i1
+mov %l6,%l2
+stb %l2,[%l3]
+.L66:
+mov %i3,%i0
+mov %i3,%l3
+set yycrank,%l2
+cmp %l3,%l2; bleu .L67; nop
+sll %i1,1,%l3
+add %l3,%i0,%i3
+mov %i3,%l3
+set yytop,%l2
+ld [%l2],%l2
+cmp %l3,%l2; bgu .L68; nop
+ldsb [%i3],%l3
+smul %l3,12,%l3
+set yysvec,%l2
+add %l3,%l2,%l3
+mov %i5,%l2
+cmp %l3,%l2; bne .L68; nop
+set yysvec,%l3
+ldsb [%i3+1],%l2
+smul %l2,12,%l2
+add %l2,%l3,%l2
+cmp %l2,%l3; bne .L71; nop
+add %i2,-1,%l3
+mov %l3,%i2
+set yytchar,%l2
+ldsb [%l3],%l3
+st %l3,[%l2]
+ld [%l2],%l3
+cmp %l3,10; bne .L73; nop
+set yylineno,%l3
+ld [%l3],%l2
+sub %l2,1,%l2
+st %l2,[%l3]
+.L73:
+set yysptr,%l3
+ld [%l3],%l2
+add %l2,1,%l1
+st %l1,[%l3]
+set yytchar,%l3
+ld [%l3],%l3
+stb %l3,[%l2]
+ba .L95; nop
+.L71:
+mov %i4,%l3
+add %l3,4,%i4
+ldsb [%i3+1],%l2
+smul %l2,12,%l2
+set yysvec,%l1
+add %l2,%l1,%l2
+mov %l2,%i5
+st %l2,[%l3]
+ba .L44; nop
+.L67:
+mov %i3,%l3
+set yycrank,%l2
+cmp %l3,%l2; bgeu .L76; nop
+set yycrank,%l3
+mov %l3,%l2
+mov %i3,%l1
+sub %l2,%l1,%l2
+sra %l2,31,%g1; wr %g0,%g1,%y; nop; nop; nop; sdiv %l2,2,%l2
+sll %l2,1,%l2
+add %l2,%l3,%l3
+mov %l3,%i0
+mov %l3,%i3
+sll %i1,1,%l3
+add %l3,%i3,%i3
+mov %i3,%l3
+set yytop,%l2
+ld [%l2],%l2
+cmp %l3,%l2; bgu .L78; nop
+ldsb [%i3],%l3
+smul %l3,12,%l3
+set yysvec,%l2
+add %l3,%l2,%l3
+mov %i5,%l2
+cmp %l3,%l2; bne .L78; nop
+set yysvec,%l3
+ldsb [%i3+1],%l2
+smul %l2,12,%l2
+add %l2,%l3,%l2
+cmp %l2,%l3; bne .L80; nop
+add %i2,-1,%l3
+mov %l3,%i2
+set yytchar,%l2
+ldsb [%l3],%l3
+st %l3,[%l2]
+ld [%l2],%l3
+cmp %l3,10; bne .L82; nop
+set yylineno,%l3
+ld [%l3],%l2
+sub %l2,1,%l2
+st %l2,[%l3]
+.L82:
+set yysptr,%l3
+ld [%l3],%l2
+add %l2,1,%l1
+st %l1,[%l3]
+set yytchar,%l3
+ld [%l3],%l3
+stb %l3,[%l2]
+ba .L95; nop
+.L80:
+mov %i4,%l3
+add %l3,4,%i4
+ldsb [%i3+1],%l2
+smul %l2,12,%l2
+set yysvec,%l1
+add %l2,%l1,%l2
+mov %l2,%i5
+st %l2,[%l3]
+ba .L44; nop
+.L78:
+set yymatch,%l3
+ldsb [%i1+%l3],%l3
+sll %l3,1,%l3
+add %l3,%i0,%i3
+mov %i3,%l3
+set yytop,%l2
+ld [%l2],%l2
+cmp %l3,%l2; bgu .L84; nop
+ldsb [%i3],%l3
+smul %l3,12,%l3
+set yysvec,%l2
+add %l3,%l2,%l3
+mov %i5,%l2
+cmp %l3,%l2; bne .L84; nop
+set yysvec,%l3
+ldsb [%i3+1],%l2
+smul %l2,12,%l2
+add %l2,%l3,%l2
+cmp %l2,%l3; bne .L86; nop
+add %i2,-1,%l3
+mov %l3,%i2
+set yytchar,%l2
+ldsb [%l3],%l3
+st %l3,[%l2]
+ld [%l2],%l3
+cmp %l3,10; bne .L88; nop
+set yylineno,%l3
+ld [%l3],%l2
+sub %l2,1,%l2
+st %l2,[%l3]
+.L88:
+set yysptr,%l3
+ld [%l3],%l2
+add %l2,1,%l1
+st %l1,[%l3]
+set yytchar,%l3
+ld [%l3],%l3
+stb %l3,[%l2]
+ba .L95; nop
+.L86:
+mov %i4,%l3
+add %l3,4,%i4
+ldsb [%i3+1],%l2
+smul %l2,12,%l2
+set yysvec,%l1
+add %l2,%l1,%l2
+mov %l2,%i5
+st %l2,[%l3]
+ba .L44; nop
+.L84:
+.L76:
+.L68:
+ld [%i5+4],%l3
+mov %l3,%i5
+cmp %l3,%g0; be .L90; nop
+ld [%i5],%l3
+mov %l3,%i3
+set yycrank,%l2
+cmp %l3,%l2; be .L90; nop
+ba .L66; nop
+.L90:
+add %i2,-1,%l3
+mov %l3,%i2
+set yytchar,%l2
+ldsb [%l3],%l3
+st %l3,[%l2]
+ld [%l2],%l3
+cmp %l3,10; bne .L92; nop
+set yylineno,%l3
+ld [%l3],%l2
+sub %l2,1,%l2
+st %l2,[%l3]
+.L92:
+set yysptr,%l3
+ld [%l3],%l2
+add %l2,1,%l1
+st %l1,[%l3]
+set yytchar,%l3
+ld [%l3],%l3
+stb %l3,[%l2]
+ba .L95; nop
+.L94:
+mov %i2,%l6
+add %l6,-1,%i2
+stb %g0,[%l6]
+ld [%i4],%l6
+mov %l6,%l4
+cmp %l4,%g0; be .L97; nop
+set yyfnd,%l4
+ld [%l6+8],%l6
+st %l6,[%l4]
+cmp %l6,%g0; be .L97; nop
+ld [%l4],%l6
+ld [%l6],%l6
+cmp %l6,0; ble .L97; nop
+set yyolsp,%l6
+st %i4,[%l6]
+set yyfnd,%l6
+ld [%l6],%l6
+ld [%l6],%l6
+set yyextra,%l5
+ldsb [%l6+%l5],%l6
+cmp %l6,0; be .L99; nop
+ba .L102; nop
+.L101:
+add %i4,-4,%i4
+mov %i2,%l6
+add %l6,-1,%i2
+set yytchar,%l5
+ldsb [%l6],%l6
+st %l6,[%l5]
+ld [%l5],%l6
+cmp %l6,10; bne .L104; nop
+set yylineno,%l6
+ld [%l6],%l5
+sub %l5,1,%l5
+st %l5,[%l6]
+.L104:
+set yysptr,%l6
+ld [%l6],%l5
+add %l5,1,%l4
+st %l4,[%l6]
+set yytchar,%l6
+ld [%l6],%l6
+stb %l6,[%l5]
+.L102:
+ld [%i4],%l6
+ld [%l6+8],%o0
+set yyfnd,%l6
+ld [%l6],%l6
+ld [%l6],%l6
+neg %l6,%o1
+call yyback; nop
+cmp %o0,1; be .L106; nop
+mov %i4,%l6
+set yylstate,%l5
+cmp %l6,%l5; bgu .L101; nop
+.L106:
+.L99:
+set yyprevious,%l6
+ldsb [%i2],%l5
+st %l5,[%l6]
+set yylsp,%l6
+st %i4,[%l6]
+set yyleng,%l6
+set yytext,%l5
+mov %i2,%l4
+mov %l5,%l3
+sub %l4,%l3,%l4
+add %l4,1,%l4
+st %l4,[%l6]
+ld [%l6],%l6
+stb %g0,[%l6+%l5]
+set yyfnd,%l6
+ld [%l6],%l5
+add %l5,4,%l4
+st %l4,[%l6]
+ld [%l5],%i0
+ba .L35; nop
+.L97:
+set yytchar,%l6
+ldsb [%i2],%l5
+st %l5,[%l6]
+ld [%l6],%l6
+cmp %l6,10; bne .L107; nop
+set yylineno,%l6
+ld [%l6],%l5
+sub %l5,1,%l5
+st %l5,[%l6]
+.L107:
+set yysptr,%l6
+ld [%l6],%l5
+add %l5,1,%l4
+st %l4,[%l6]
+set yytchar,%l6
+ld [%l6],%l6
+stb %l6,[%l5]
+.L95:
+mov %i4,%l6
+add %l6,-4,%i4
+set yylstate,%l5
+cmp %l6,%l5; bgu .L94; nop
+set yytext,%l6
+ldsb [%l6],%l6
+cmp %l6,0; bne .L109; nop
+set yysptr,%l6
+set yysbuf,%l5
+st %l5,[%l6]
+mov %g0,%i0
+ba .L35; nop
+.L109:
+set yysptr,%l3
+ld [%l3],%l3
+set yysbuf,%l2
+cmp %l3,%l2; bleu .L119; nop
+set yysptr,%l3
+ld [%l3],%l2
+add %l2,-1,%l2
+st %l2,[%l3]
+ldsb [%l2],%l4
+ba .L120; nop
+.L119:
+set yyin,%l3
+ld [%l3],%l3
+ld [%l3],%l2
+sub %l2,1,%l2
+st %l2,[%l3]
+cmp %l2,0; bge .L121; nop
+set yyin,%l3
+ld [%l3],%o0
+call __filbuf; nop
+mov %o0,%l3
+st %l3,[%fp+-4]
+ba .L122; nop
+.L121:
+set yyin,%l3
+ld [%l3],%l3
+add %l3,4,%l3
+ld [%l3],%l2
+add %l2,1,%l1
+st %l1,[%l3]
+ldub [%l2],%l3
+st %l3,[%fp+-4]
+.L122:
+ld [%fp+-4],%l4
+.L120:
+set yytchar,%l3
+st %l4,[%l3]
+cmp %l4,10; bne .L117; nop
+set yylineno,%l3
+ld [%l3],%l2
+add %l2,1,%l2
+st %l2,[%l3]
+set yytchar,%l3
+ld [%l3],%l5
+ba .L118; nop
+.L117:
+set yytchar,%l3
+ld [%l3],%l5
+.L118:
+cmp %l5,-1; bne .L115; nop
+mov %g0,%l6
+ba .L116; nop
+.L115:
+set yytchar,%l3
+ld [%l3],%l6
+.L116:
+set yytext,%l2
+stb %l6,[%l2]
+set yyprevious,%l2
+sll %l6,8*(4-1),%l3; sra %l3,8*(4-1),%l3
+st %l3,[%l2]
+set yyprevious,%l3
+ld [%l3],%l3
+cmp %l3,0; ble .L123; nop
+set yyout,%l3
+ld [%l3],%l3
+ld [%l3],%l2
+sub %l2,1,%l2
+st %l2,[%l3]
+cmp %l2,0; bge .L126; nop
+set yyprevious,%l3
+ld [%l3],%l3
+and %l3,0xff,%l3
+mov %l3,%o0
+set yyout,%l3
+ld [%l3],%o1
+call __flsbuf; nop
+ba .L127; nop
+.L126:
+set yyout,%l3
+ld [%l3],%l3
+add %l3,4,%l3
+ld [%l3],%l2
+add %l2,1,%l1
+st %l1,[%l3]
+set yyprevious,%l3
+ld [%l3],%l3
+stb %l3,[%l2]
+.L127:
+.L123:
+set yytext,%i2
+ba .L38; nop
+.L35:
+ret; restore
+.type yylook,#function
+.size yylook,.-yylook
+.global yyback
+.align 4
+yyback:
+save %sp,-96,%sp
+mov %i0,%i5
+cmp %i5,%g0; bne .L132; nop
+mov %g0,%i0
+ba .L128; nop
+.L131:
+mov %i0,%i5
+add %i5,4,%i0
+ld [%i5],%i5
+cmp %i5,%i1; bne .L134; nop
+set 1,%i0
+ba .L128; nop
+.L134:
+.L132:
+ld [%i0],%i5
+cmp %i5,0; bne .L131; nop
+mov %g0,%i0
+.L128:
+ret; restore
+.type yyback,#function
+.size yyback,.-yyback
+.global yyinput
+.align 4
+yyinput:
+save %sp,-96,%sp
+set yysptr,%i1
+ld [%i1],%i1
+set yysbuf,%i0
+cmp %i1,%i0; bleu .L145; nop
+set yysptr,%i1
+ld [%i1],%i0
+add %i0,-1,%i0
+st %i0,[%i1]
+ldsb [%i0],%i3
+ba .L146; nop
+.L145:
+set yyin,%i1
+ld [%i1],%i1
+ld [%i1],%i0
+sub %i0,1,%i0
+st %i0,[%i1]
+cmp %i0,0; bge .L147; nop
+set yyin,%i1
+ld [%i1],%o0
+call __filbuf; nop
+mov %o0,%i1
+mov %i1,%i2
+ba .L148; nop
+.L147:
+set yyin,%i1
+ld [%i1],%i1
+add %i1,4,%i1
+ld [%i1],%i0
+add %i0,1,%l7
+st %l7,[%i1]
+ldub [%i0],%i2
+.L148:
+mov %i2,%i3
+.L146:
+set yytchar,%i1
+st %i3,[%i1]
+cmp %i3,10; bne .L143; nop
+set yylineno,%i1
+ld [%i1],%i0
+add %i0,1,%i0
+st %i0,[%i1]
+set yytchar,%i1
+ld [%i1],%i4
+ba .L144; nop
+.L143:
+set yytchar,%i1
+ld [%i1],%i4
+.L144:
+cmp %i4,-1; bne .L141; nop
+mov %g0,%i5
+ba .L142; nop
+.L141:
+set yytchar,%i1
+ld [%i1],%i5
+.L142:
+mov %i5,%i0
+.L136:
+ret; restore
+.type yyinput,#function
+.size yyinput,.-yyinput
+.global yyoutput
+.align 4
+yyoutput:
+save %sp,-96,%sp
+set yyout,%i5
+ld [%i5],%i5
+ld [%i5],%i4
+sub %i4,1,%i4
+st %i4,[%i5]
+cmp %i4,0; bge .L151; nop
+mov %i0,%i5
+and %i5,0xff,%i5
+mov %i5,%o0
+set yyout,%i5
+ld [%i5],%o1
+call __flsbuf; nop
+ba .L152; nop
+.L151:
+set yyout,%i5
+ld [%i5],%i5
+add %i5,4,%i5
+ld [%i5],%i4
+add %i4,1,%i3
+st %i3,[%i5]
+mov %i0,%i5
+stb %i5,[%i4]
+.L152:
+mov %g0,%i0
+.L149:
+ret; restore
+.type yyoutput,#function
+.size yyoutput,.-yyoutput
+.global yyunput
+.align 4
+yyunput:
+save %sp,-96,%sp
+set yytchar,%i5
+st %i0,[%i5]
+ld [%i5],%i5
+cmp %i5,10; bne .L154; nop
+set yylineno,%i5
+ld [%i5],%i4
+sub %i4,1,%i4
+st %i4,[%i5]
+.L154:
+set yysptr,%i5
+ld [%i5],%i4
+add %i4,1,%i3
+st %i3,[%i5]
+set yytchar,%i5
+ld [%i5],%i5
+stb %i5,[%i4]
+mov %g0,%i0
+.L153:
+ret; restore
+.type yyunput,#function
+.size yyunput,.-yyunput
+.global main
+.align 4
+main:
+save %sp,-96,%sp
+call yyparse; nop
+mov %g0,%i0
+.L156:
+ret; restore
+.type main,#function
+.size main,.-main
+.global yyerror
+.align 4
+yyerror:
+save %sp,-96,%sp
+set .L158,%o0
+mov %i0,%o1
+call printf; nop
+mov %g0,%i0
+.L157:
+ret; restore
+.type yyerror,#function
+.size yyerror,.-yyerror
+.section ".data"
+.global yyexca
+.type yyexca,#object
+.align 2
+yyexca:
+.half 0xffffffff
+.half 0x1
+.half 0x0
+.half 0xffffffff
+.half 0xfffffffe
+.half 0x0
+.size yyexca,12
+.global yyact
+.type yyact,#object
+.align 2
+yyact:
+.half 0xc
+.half 0x2
+.half 0x9
+.half 0x8
+.half 0x11
+.half 0xb
+.half 0x19
+.half 0x11
+.half 0xf
+.half 0x12
+.half 0x10
+.half 0xa
+.half 0x12
+.half 0x11
+.half 0xf
+.half 0x7
+.half 0x10
+.half 0xd
+.half 0x12
+.half 0x5
+.half 0x3
+.half 0x1
+.half 0x0
+.half 0x13
+.half 0x14
+.half 0x0
+.half 0x0
+.half 0x15
+.half 0x16
+.half 0x17
+.half 0x18
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x6
+.half 0xe
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x4
+.half 0x6
+.size yyact,498
+.global yypact
+.type yypact,#object
+.align 2
+yypact:
+.half 0xfffffc18
+.half 0xfffffff7
+.half 0xfffffc18
+.half 0x5
+.half 0xfffffff9
+.half 0xffffffc5
+.half 0xfffffc18
+.half 0xfffffc18
+.half 0xfffffc18
+.half 0xffffffd8
+.half 0xffffffe3
+.half 0xffffffd8
+.half 0xffffffd8
+.half 0xfffffc18
+.half 0xfffffc18
+.half 0xffffffd8
+.half 0xffffffd8
+.half 0xffffffd8
+.half 0xffffffd8
+.half 0xffffffda
+.half 0xffffffdd
+.half 0xffffffda
+.half 0xffffffda
+.half 0xfffffc18
+.half 0xfffffc18
+.half 0xfffffc18
+.size yypact,52
+.global yypgo
+.type yypgo,#object
+.align 2
+yypgo:
+.half 0x0
+.half 0x15
+.half 0x14
+.half 0x11
+.half 0xb
+.size yypgo,10
+.global yyr1
+.type yyr1,#object
+.align 2
+yyr1:
+.half 0x0
+.half 0x1
+.half 0x1
+.half 0x1
+.half 0x1
+.half 0x2
+.half 0x4
+.half 0x4
+.half 0x4
+.half 0x4
+.half 0x4
+.half 0x4
+.half 0x4
+.half 0x4
+.half 0x3
+.size yyr1,30
+.global yyr2
+.type yyr2,#object
+.align 2
+yyr2:
+.half 0x0
+.half 0x0
+.half 0x2
+.half 0x3
+.half 0x3
+.half 0x3
+.half 0x3
+.half 0x3
+.half 0x3
+.half 0x3
+.half 0x2
+.half 0x3
+.half 0x1
+.half 0x1
+.half 0x1
+.size yyr2,30
+.global yychk
+.type yychk,#object
+.align 2
+yychk:
+.half 0xfffffc18
+.half 0xffffffff
+.half 0xa
+.half 0xfffffffe
+.half 0x100
+.half 0xfffffffd
+.half 0x101
+.half 0xa
+.half 0xa
+.half 0x3d
+.half 0xfffffffc
+.half 0x2d
+.half 0x28
+.half 0xfffffffd
+.half 0x102
+.half 0x2b
+.half 0x2d
+.half 0x2a
+.half 0x2f
+.half 0xfffffffc
+.half 0xfffffffc
+.half 0xfffffffc
+.half 0xfffffffc
+.half 0xfffffffc
+.half 0xfffffffc
+.half 0x29
+.size yychk,52
+.global yydef
+.type yydef,#object
+.align 2
+yydef:
+.half 0x1
+.half 0xfffffffe
+.half 0x2
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0xe
+.half 0x3
+.half 0x4
+.half 0x0
+.half 0x5
+.half 0x0
+.half 0x0
+.half 0xc
+.half 0xd
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0x0
+.half 0xa
+.half 0x0
+.half 0x6
+.half 0x7
+.half 0x8
+.half 0x9
+.half 0xb
+.size yydef,52
+.global yychar
+.type yychar,#object
+.size yychar,4
+.align 4
+yychar:
+.word 0xffffffff
+.global yynerrs
+.type yynerrs,#object
+.size yynerrs,4
+.align 4
+yynerrs:
+.word 0x0
+.global yyerrflag
+.type yyerrflag,#object
+.size yyerrflag,2
+.align 2
+yyerrflag:
+.half 0x0
+.global yyparse
+.section ".text"
+.align 4
+yyparse:
+save %sp,-392,%sp
+mov %g0,%l5
+mov %l5,%i4
+set yychar,%l4
+set -1,%l3
+st %l3,[%l4]
+set yynerrs,%l4
+st %g0,[%l4]
+set yyerrflag,%l4
+sth %l5,[%l4]
+add -302,%fp,%i3
+set yyv-4,%i1
+.L162:
+add %i3,2,%l5
+mov %l5,%i3
+add 0,%fp,%l4
+cmp %l5,%l4; bleu .L163; nop
+set .L166,%o0
+call yyerror; nop
+set 1,%i0
+ba .L159; nop
+.L163:
+sth %i4,[%i3]
+add %i1,4,%i1
+set yyval,%l5
+ld [%l5],%l5
+st %l5,[%i1]
+.L167:
+sll %i4,8*(4-2),%l5; sra %l5,8*(4-2),%l5
+sll %l5,1,%l5
+set yypact,%l4
+ldsh [%l5+%l4],%i2
+sll %i2,8*(4-2),%l5; sra %l5,8*(4-2),%l5
+cmp %l5,-1000; bg .L168; nop
+ba .L170; nop
+.L168:
+set yychar,%l5
+ld [%l5],%l5
+cmp %l5,0; bge .L171; nop
+call yylex; nop
+set yychar,%l4
+st %o0,[%l4]
+cmp %o0,0; bge .L173; nop
+set yychar,%l5
+st %g0,[%l5]
+.L173:
+.L171:
+sll %i2,8*(4-2),%l5; sra %l5,8*(4-2),%l5
+set yychar,%l4
+ld [%l4],%l4
+add %l5,%l4,%l5
+mov %l5,%i2
+sll %l5,8*(4-2),%l5; sra %l5,8*(4-2),%l5
+cmp %l5,0; bl .L177; nop
+sll %i2,8*(4-2),%l5; sra %l5,8*(4-2),%l5
+cmp %l5,249; bl .L175; nop
+.L177:
+ba .L170; nop
+.L175:
+sll %i2,8*(4-2),%l5; sra %l5,8*(4-2),%l5
+sll %l5,1,%l5
+set yyact,%l4
+ldsh [%l5+%l4],%l5
+mov %l5,%i2
+sll %l5,8*(4-2),%l5; sra %l5,8*(4-2),%l5
+sll %l5,1,%l5
+set yychk,%l4
+ldsh [%l5+%l4],%l5
+set yychar,%l4
+ld [%l4],%l4
+cmp %l5,%l4; bne .L178; nop
+set yychar,%l5
+set -1,%l4
+st %l4,[%l5]
+set yyval,%l5
+set yylval,%l4
+ld [%l4],%l4
+st %l4,[%l5]
+mov %i2,%i4
+set yyerrflag,%l5
+ldsh [%l5],%l5
+cmp %l5,0; ble .L162; nop
+set yyerrflag,%l5
+ldsh [%l5],%l4
+sub %l4,1,%l4
+sth %l4,[%l5]
+ba .L162; nop
+.L178:
+.L170:
+sll %i4,8*(4-2),%l5; sra %l5,8*(4-2),%l5
+sll %l5,1,%l5
+set yydef,%l4
+ldsh [%l5+%l4],%l5
+mov %l5,%i2
+sll %l5,8*(4-2),%l5; sra %l5,8*(4-2),%l5
+cmp %l5,-2; bne .L182; nop
+set yychar,%l5
+ld [%l5],%l5
+cmp %l5,0; bge .L184; nop
+call yylex; nop
+set yychar,%l4
+st %o0,[%l4]
+cmp %o0,0; bge .L186; nop
+set yychar,%l5
+st %g0,[%l5]
+.L186:
+.L184:
+set yyexca,%i0
+ba .L191; nop
+.L188:
+.L189:
+add %i0,4,%i0
+.L191:
+ldsh [%i0],%l5
+cmp %l5,-1; bne .L188; nop
+ldsh [%i0+2],%l5
+sll %i4,8*(4-2),%l4; sra %l4,8*(4-2),%l4
+cmp %l5,%l4; bne .L188; nop
+ba .L193; nop
+.L192:
+ldsh [%i0],%l5
+set yychar,%l4
+ld [%l4],%l4
+cmp %l5,%l4; bne .L195; nop
+ba .L194; nop
+.L195:
+.L193:
+add %i0,4,%l5
+mov %l5,%i0
+ldsh [%l5],%l5
+cmp %l5,0; bge .L192; nop
+.L194:
+ldsh [%i0+2],%l5
+mov %l5,%i2
+sll %l5,8*(4-2),%l5; sra %l5,8*(4-2),%l5
+cmp %l5,0; bge .L197; nop
+mov %g0,%i0
+ba .L159; nop
+.L197:
+.L182:
+sll %i2,8*(4-2),%l5; sra %l5,8*(4-2),%l5
+cmp %l5,0; bne .L199; nop
+set yyerrflag,%l4
+ldsh [%l4],%l5
+cmp %l5,0; bl .L201; nop
+cmp %l5,3; bg .L201; nop
+sll %l5,2,%l4
+set .L217,%l3
+ld [%l4+%l3],%l4
+jmp %l4; nop
+.section ".rodata"
+.align 4
+.L217:
+.word .L204
+.word .L207
+.word .L207
+.word .L214
+.section ".text"
+.L204:
+set .L205,%o0
+call yyerror; nop
+.L206:
+set yynerrs,%l4
+ld [%l4],%l3
+add %l3,1,%l3
+st %l3,[%l4]
+.L207:
+set yyerrflag,%l4
+set 3,%l3
+sth %l3,[%l4]
+ba .L209; nop
+.L208:
+ldsh [%i3],%l4
+sll %l4,1,%l4
+set yypact,%l3
+ldsh [%l4+%l3],%l4
+add %l4,256,%l4
+mov %l4,%i2
+sll %i2,8*(4-2),%l4; sra %l4,8*(4-2),%l4
+cmp %l4,0; bl .L211; nop
+cmp %l4,249; bge .L211; nop
+sll %l4,1,%l4
+set yyact,%l3
+ldsh [%l4+%l3],%l4
+sll %l4,1,%l4
+set yychk,%l3
+ldsh [%l4+%l3],%l4
+cmp %l4,256; bne .L211; nop
+sll %i2,8*(4-2),%l4; sra %l4,8*(4-2),%l4
+sll %l4,1,%l4
+set yyact,%l3
+ldsh [%l4+%l3],%i4
+ba .L162; nop
+.L211:
+ldsh [%i3],%l4
+sll %l4,1,%l4
+set yypact,%l3
+ldsh [%l4+%l3],%i2
+add %i3,-2,%i3
+add %i1,-4,%i1
+.L209:
+mov %i3,%l4
+add -300,%fp,%l3
+cmp %l4,%l3; bgeu .L208; nop
+.L213:
+set 1,%i0
+ba .L159; nop
+.L214:
+set yychar,%l4
+ld [%l4],%l4
+cmp %l4,0; bne .L215; nop
+ba .L213; nop
+.L215:
+set yychar,%l4
+set -1,%l3
+st %l3,[%l4]
+ba .L167; nop
+.L201:
+.L199:
+sll %i2,8*(4-2),%l5; sra %l5,8*(4-2),%l5
+sll %l5,1,%l5
+set yyr2,%l4
+add %l5,%l4,%l4
+ldsh [%l4],%l3
+sll %l3,1,%l3
+sub %i3,%l3,%i3
+mov %i1,%i5
+ldsh [%l4],%l4
+sll %l4,2,%l4
+sub %i1,%l4,%i1
+set yyval,%l4
+ld [%i1+4],%l3
+st %l3,[%l4]
+mov %i2,%l6
+set yyr1,%l4
+ldsh [%l5+%l4],%i2
+sll %i2,8*(4-2),%l5; sra %l5,8*(4-2),%l5
+sll %l5,1,%l5
+set yypgo,%l4
+ldsh [%l5+%l4],%l5
+ldsh [%i3],%l4
+add %l5,%l4,%l5
+add %l5,1,%l5
+mov %l5,%l7
+sll %l7,8*(4-2),%l5; sra %l5,8*(4-2),%l5
+cmp %l5,249; bge .L220; nop
+sll %l5,1,%l5
+set yyact,%l4
+ldsh [%l5+%l4],%l5
+mov %l5,%i4
+sll %l5,8*(4-2),%l5; sra %l5,8*(4-2),%l5
+sll %l5,1,%l5
+set yychk,%l4
+ldsh [%l5+%l4],%l5
+sll %i2,8*(4-2),%l4; sra %l4,8*(4-2),%l4
+neg %l4,%l4
+cmp %l5,%l4; be .L218; nop
+.L220:
+sll %i2,8*(4-2),%l5; sra %l5,8*(4-2),%l5
+sll %l5,1,%l5
+set yypgo,%l4
+ldsh [%l5+%l4],%l5
+sll %l5,1,%l5
+set yyact,%l4
+ldsh [%l5+%l4],%i4
+.L218:
+sll %l6,8*(4-2),%l5; sra %l5,8*(4-2),%l5
+cmp %l5,4; bl .L162; nop
+cmp %l5,14; bg .L162; nop
+sll %l5,2,%l4
+set .L242-16,%l3
+ld [%l4+%l3],%l4
+jmp %l4; nop
+.section ".rodata"
+.align 4
+.L242:
+.word .L224
+.word .L225
+.word .L227
+.word .L229
+.word .L231
+.word .L233
+.word .L235
+.word .L162
+.word .L237
+.word .L239
+.word .L241
+.section ".text"
+.L224:
+set yyerrflag,%l4
+sth %g0,[%l4]
+ba .L162; nop
+.L225:
+set .L226,%o0
+call printf; nop
+ba .L162; nop
+.L227:
+set .L228,%o0
+call printf; nop
+ba .L162; nop
+.L229:
+set .L230,%o0
+call printf; nop
+ba .L162; nop
+.L231:
+set .L232,%o0
+call printf; nop
+ba .L162; nop
+.L233:
+set .L234,%o0
+call printf; nop
+ba .L162; nop
+.L235:
+set .L236,%o0
+call printf; nop
+ba .L162; nop
+.L237:
+set .L238,%o0
+call printf; nop
+ba .L162; nop
+.L239:
+set .L240,%o0
+set yytext,%o1
+call printf; nop
+ba .L162; nop
+.L241:
+set .L158,%o0
+set yytext,%o1
+call printf; nop
+ba .L162; nop
+.L159:
+ret; restore
+.type yyparse,#function
+.size yyparse,.-yyparse
+.global yywrap
+.align 4
+yywrap:
+set 1,%o0
+.L244:
+retl; nop
+.type yywrap,#function
+.size yywrap,.-yywrap
+.section ".bss"
+.global yyv
+.type yyv,#object
+.size yyv,600
+.common yyv,600,4
+.global yyfnd
+.type yyfnd,#object
+.size yyfnd,4
+.common yyfnd,4,4
+.global yyolsp
+.type yyolsp,#object
+.size yyolsp,4
+.common yyolsp,4,4
+.global yylsp
+.type yylsp,#object
+.size yylsp,4
+.common yylsp,4,4
+.global yylstate
+.type yylstate,#object
+.size yylstate,800
+.common yylstate,800,4
+.global yyestate
+.type yyestate,#object
+.size yyestate,4
+.common yyestate,4,4
+.global yytchar
+.type yytchar,#object
+.size yytchar,4
+.common yytchar,4,4
+.global yysbuf
+.type yysbuf,#object
+.size yysbuf,200
+.common yysbuf,200,1
+.global yymorfg
+.type yymorfg,#object
+.size yymorfg,4
+.common yymorfg,4,4
+.global yytext
+.type yytext,#object
+.size yytext,200
+.common yytext,200,1
+.global yyleng
+.type yyleng,#object
+.size yyleng,4
+.common yyleng,4,4
+.global yyval
+.type yyval,#object
+.size yyval,4
+.common yyval,4,4
+.global yylval
+.type yylval,#object
+.size yylval,4
+.common yylval,4,4
+.section ".rodata"
+.align 1
+.L240:
+.byte 112
+.byte 117
+.byte 115
+.byte 104
+.byte 32
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.L238:
+.byte 108
+.byte 111
+.byte 97
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L236:
+.byte 110
+.byte 101
+.byte 103
+.byte 97
+.byte 116
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.L234:
+.byte 100
+.byte 105
+.byte 118
+.byte 105
+.byte 100
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.L232:
+.byte 109
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 121
+.byte 10
+.byte 0
+.align 1
+.L230:
+.byte 110
+.byte 101
+.byte 103
+.byte 97
+.byte 116
+.byte 101
+.byte 10
+.byte 97
+.byte 100
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L228:
+.byte 97
+.byte 100
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.L226:
+.byte 115
+.byte 116
+.byte 111
+.byte 114
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.L205:
+.byte 115
+.byte 121
+.byte 110
+.byte 116
+.byte 97
+.byte 120
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 0
+.align 1
+.L166:
+.byte 121
+.byte 97
+.byte 99
+.byte 99
+.byte 32
+.byte 115
+.byte 116
+.byte 97
+.byte 99
+.byte 107
+.byte 32
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 0
+.align 1
+.L158:
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.L18:
+.byte 98
+.byte 97
+.byte 100
+.byte 32
+.byte 115
+.byte 119
+.byte 105
+.byte 116
+.byte 99
+.byte 104
+.byte 32
+.byte 121
+.byte 121
+.byte 108
+.byte 111
+.byte 111
+.byte 107
+.byte 32
+.byte 37
+.byte 100
+.byte 0
diff --git a/lcc/src/2html.c b/lcc/src/2html.c
new file mode 100755
index 0000000..3c9b146
--- /dev/null
+++ b/lcc/src/2html.c
@@ -0,0 +1,555 @@
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include "c.h"
+#include "rcc.h"
+#if WIN32
+#include <fcntl.h>
+#include <io.h>
+#endif
+
+
+static void do_int(int x) {
+ printf("%d", x);
+}
+
+static void do_scope(int x) {
+#define xx(c) if (x == c) { printf(#c); return; }
+ xx(CONSTANTS)
+ xx(LABELS)
+ xx(GLOBAL)
+ xx(PARAM)
+ xx(LOCAL)
+#undef xx
+ if (x > LOCAL)
+ printf("LOCAL+%d", x-LOCAL);
+ else
+ do_int(x);
+}
+
+static void do_sclass(int x) {
+#define xx(c) if (x == c) { printf(#c); return; }
+ xx(REGISTER)
+ xx(AUTO)
+ xx(EXTERN)
+ xx(STATIC)
+ xx(TYPEDEF)
+#undef xx
+ do_int(x);
+}
+
+static void do_flags(int x) {
+ char *bar = "";
+#define xx(f,n) if ((x>>n)&1) { printf("%s" #f, bar); bar = "|"; }
+ xx(structarg,0)
+ xx(addressed,1)
+ xx(computed,2)
+ xx(temporary,3)
+ xx(generated,4)
+#undef xx
+ if (*bar == '\0')
+ do_int(x);
+}
+
+static void do_seg(int x) {
+#define xx(s) if (x == s) { printf(#s); return; }
+ xx(CODE)
+ xx(BSS)
+ xx(DATA)
+ xx(LIT)
+#undef xx
+ do_int(x);
+}
+
+#define xx(ptr,field,type) do { printf("<li>" #field " = "); do_##type(ptr->field); printf("</li>\n"); } while (0)
+
+static void do_op(int x) {
+ static char *opnames[] = {
+ "",
+ "CNST",
+ "ARG",
+ "ASGN",
+ "INDIR",
+ "CVC",
+ "CVD",
+ "CVF",
+ "CVI",
+ "CVP",
+ "CVS",
+ "CVU",
+ "NEG",
+ "CALL",
+ "*LOAD*",
+ "RET",
+ "ADDRG",
+ "ADDRF",
+ "ADDRL",
+ "ADD",
+ "SUB",
+ "LSH",
+ "MOD",
+ "RSH",
+ "BAND",
+ "BCOM",
+ "BOR",
+ "BXOR",
+ "DIV",
+ "MUL",
+ "EQ",
+ "GE",
+ "GT",
+ "LE",
+ "LT",
+ "NE",
+ "JUMP",
+ "LABEL",
+ "AND",
+ "NOT",
+ "OR",
+ "COND",
+ "RIGHT",
+ "FIELD"
+ };
+ int op = opindex(x);
+ if (op < 1 || op >= sizeof opnames/sizeof opnames[0])
+ printf("%d", x);
+ else
+ printf("%s", opnames[op]);
+}
+
+static void do_define_uid(int x) {
+ printf("<strong id=uid%d>%d</strong>", x, x);
+}
+
+static void do_define_label(int x) {
+ printf("<strong id=ll%d>%d</strong>", x, x);
+}
+
+static void do_uid(int x) {
+ printf("<a href='#%d'>%d</a>", x, x, x);
+}
+
+static void do_label(int x) {
+ printf("<a href='#L%d'>%d</a>", x, x, x);
+}
+
+static int nextid;
+
+static void do_list(list_ty x, void do_one(void *), char *type, char *listhtml, char *separator) {
+ int count = Seq_length(x);
+
+ if (count == 0)
+ printf("<em>empty %s list</em>\n", type);
+ else {
+ int i;
+ printf("<em>%s list</em>", type);
+ if (listhtml != NULL)
+ printf("<%s>\n", listhtml);
+ for (i = 0; i < count; i++) {
+ if (listhtml != NULL)
+ printf("<li>");
+ printf(separator);
+ do_one(Seq_get(x, i));
+ if (listhtml != NULL)
+ printf("</li>\n");
+ }
+ if (listhtml != NULL)
+ printf("</%s>\n", listhtml);
+ }
+}
+
+static void do_uid_list(list_ty x) {
+ int i, count = Seq_length(x);
+
+ if (count == 0)
+ printf("<em>empty int list</em>\n");
+ else {
+ int i;
+ printf("<em>int list</em>");
+ for (i= 0; i < count; i++) {
+ printf(" ");
+ do_uid(*(int *)Seq_get(x, i));
+ }
+ }
+}
+
+static void do_identifier(const char *x) {
+ printf("%s", x);
+}
+
+static void do_real(rcc_real_ty x) {
+ double d;
+ unsigned *p = (unsigned *)&d;
+ static union { int x; char endian; } little = { 1 };
+
+ p[1-little.endian] = x->msb;
+ p[little.endian] = x->lsb;
+ printf("(%#X,%#X) = %g", x->msb, x->lsb, d);
+}
+
+static void do_suffix(int x) {
+ static char suffixes[] = "0F234IUPVB";
+
+ if (x < 0 || x >= (sizeof suffixes/sizeof suffixes[0]) - 1)
+ printf("%d", x);
+ else
+ printf("%c", suffixes[x]);
+}
+
+static void do_enum(void *x) {
+ rcc_enum__ty e = x;
+
+ do_identifier(e->id);
+ printf("=");
+ do_int(e->value);
+}
+
+static void do_enum_list(list_ty x) {
+ do_list(x, do_enum, "enum", NULL, " ");
+}
+
+static void do_field(void *x) {
+ rcc_field_ty f = x;
+
+ printf("<em>field</em><ul>\n");
+ xx(f,id,identifier);
+ xx(f,type,uid);
+ xx(f,offset,int);
+ xx(f,bitsize,int);
+ xx(f,lsb,int);
+ printf("</ul>\n");
+}
+
+static void do_field_list(list_ty x) {
+ do_list(x, do_field, "field", "ol", "");
+}
+
+static void do_symbol(rcc_symbol_ty x) {
+ printf("<em>symbol</em><ul>\n");
+ xx(x,id,identifier);
+ xx(x,type,uid);
+ xx(x,scope,scope);
+ xx(x,sclass,sclass);
+ xx(x,ref,int);
+ xx(x,flags,flags);
+ printf("</ul>\n");
+}
+
+#define caselabel(kind) case rcc_##kind##_enum: \
+ printf("<strong>" #kind "</strong> : <em>%s</em>", typename); \
+ printf("<ul>\n"); attributes
+#define yy(kind,field,type) xx((&x->v.rcc_##kind),field,type)
+
+static void do_type(rcc_type_ty x) {
+#define attributes xx(x,size,int); xx(x,align,int)
+ switch (x->kind) {
+ static char *typename = "type";
+ caselabel(INT); break;
+ caselabel(UNSIGNED); break;
+ caselabel(FLOAT); break;
+ caselabel(VOID); break;
+ caselabel(POINTER);
+ yy(POINTER,type,uid);
+ break;
+ caselabel(ENUM);
+ yy(ENUM,tag,identifier);
+ yy(ENUM,ids,enum_list);
+ break;
+ caselabel(STRUCT);
+ yy(STRUCT,tag,identifier);
+ yy(STRUCT,fields,field_list);
+ break;
+ caselabel(UNION);
+ yy(UNION,tag,identifier);
+ yy(UNION,fields,field_list);
+ break;
+ caselabel(ARRAY);
+ yy(ARRAY,type,uid);
+ break;
+ caselabel(FUNCTION);
+ yy(FUNCTION,type,uid);
+ yy(FUNCTION,formals,uid_list);
+ break;
+ caselabel(CONST);
+ yy(CONST,type,uid);
+ break;
+ caselabel(VOLATILE);
+ yy(VOLATILE,type,uid);
+ break;
+ default: assert(0);
+ }
+#undef attributes
+ printf("</ul>\n");
+}
+
+static void do_item(rcc_item_ty x) {
+ printf("<a name='%d'>", x->uid);
+#define attributes xx(x,uid,define_uid)
+ printf("</a>");
+ switch (x->kind) {
+ static char *typename = "item";
+ caselabel(Symbol);
+ yy(Symbol,symbol,symbol);
+ break;
+ caselabel(Type);
+ yy(Type,type,type);
+ break;
+ default: assert(0);
+ }
+#undef attributes
+ printf("</ul>\n");
+}
+
+static void do_item_list(list_ty x) {
+ int count = Seq_length(x);
+
+ if (count == 0)
+ printf("<em>empty item list</em>\n");
+ else {
+ int i;
+ printf("<em>item list</em>");
+ printf("<ol>\n");
+ for (i = 0; i < count; i++) {
+ rcc_item_ty item = Seq_get(x, i);
+ printf("<li value=%d>", item->uid);
+ do_item(item);
+ printf("</li>\n");
+ }
+ printf("</ol>\n");
+ }
+}
+
+static void do_string(string_ty x) {
+ printf("%d,<code>'%s'</code>", x.len, x.str);
+}
+
+static void do_generic_string(void *x) {
+ do_string(*(string_ty *)x);
+}
+
+static void do_string_list(list_ty x) {
+ do_list(x, do_generic_string, "string", "ol", "");
+}
+
+static void do_node(void *y) {
+ rcc_node_ty x = y;
+
+ if (x->kind == rcc_LABEL_enum)
+ printf("<a name='L%d'></a>", x->v.rcc_LABEL.label);
+#define attributes xx(x,suffix,suffix); xx(x,size,int)
+ switch (x->kind) {
+ static char *typename = "node";
+ caselabel(CNST);
+ yy(CNST,value,int);
+ break;
+ caselabel(CNSTF);
+ yy(CNSTF,value,real);
+ break;
+ caselabel(ARG);
+ yy(ARG,left,node);
+ yy(ARG,len,int);
+ yy(ARG,align,int);
+ break;
+ caselabel(ASGN);
+ yy(ASGN,left,node);
+ yy(ASGN,right,node);
+ yy(ASGN,len,int);
+ yy(ASGN,align,int);
+ break;
+ caselabel(CVT);
+ yy(CVT,op,op);
+ yy(CVT,left,node);
+ yy(CVT,fromsize,int);
+ break;
+ caselabel(CALL);
+ yy(CALL,left,node);
+ yy(CALL,type,uid);
+ break;
+ caselabel(CALLB);
+ yy(CALLB,left,node);
+ yy(CALLB,right,node);
+ yy(CALLB,type,uid);
+ break;
+ caselabel(RET); break;
+ caselabel(ADDRG);
+ yy(ADDRG,uid,uid);
+ break;
+ caselabel(ADDRL);
+ yy(ADDRL,uid,uid);
+ break;
+ caselabel(ADDRF);
+ yy(ADDRF,uid,uid);
+ break;
+ caselabel(Unary);
+ yy(Unary,op,op);
+ yy(Unary,left,node);
+ break;
+ caselabel(Binary);
+ yy(Binary,op,op);
+ yy(Binary,left,node);
+ yy(Binary,right,node);
+ break;
+ caselabel(Compare);
+ yy(Compare,op,op);
+ yy(Compare,left,node);
+ yy(Compare,right,node);
+ yy(Compare,label,label);
+ break;
+ caselabel(LABEL);
+ yy(LABEL,label,define_label);
+ break;
+ caselabel(BRANCH);
+ yy(BRANCH,label,label);
+ break;
+ caselabel(CSE);
+ yy(CSE,uid,uid);
+ yy(CSE,node,node);
+ break;
+ default: assert(0);
+ }
+#undef attributes
+ printf("</ul>");
+}
+
+static void do_node_list(list_ty x) {
+ do_list(x, do_node, "node", "ol", "");
+}
+
+static void do_interface(void *);
+
+static void do_interface_list(list_ty x) {
+ do_list(x, do_interface, "interface", "ol", "");
+}
+
+static void do_interface(void *y) {
+ rcc_interface_ty x = y;
+
+ if (x->kind == rcc_Address_enum)
+ printf("<a name='%d'></a>", x->v.rcc_Address.uid);
+ else if (x->kind == rcc_Local_enum)
+ printf("<a name='%d'></a>", x->v.rcc_Local.uid);
+#define attributes
+ switch (x->kind) {
+ static char *typename = "interface";
+ caselabel(Export);
+ yy(Export,p,uid);
+ break;
+ caselabel(Import);
+ yy(Import,p,uid);
+ break;
+ caselabel(Global);
+ yy(Global,p,uid);
+ yy(Global,seg,seg);
+ break;
+ caselabel(Local);
+ yy(Local,uid,define_uid);
+ yy(Local,p,symbol);
+ break;
+ caselabel(Address);
+ yy(Address,uid,define_uid);
+ yy(Address,q,symbol);
+ yy(Address,p,uid);
+ yy(Address,n,int);
+ break;
+ caselabel(Segment);
+ yy(Segment,seg,seg);
+ break;
+ caselabel(Defaddress);
+ yy(Defaddress,p,uid);
+ break;
+ caselabel(Deflabel);
+ yy(Deflabel,label,label);
+ break;
+ caselabel(Defconst);
+ yy(Defconst,suffix,suffix);
+ yy(Defconst,size,int);
+ yy(Defconst,value,int);
+ break;
+ caselabel(Defconstf);
+ yy(Defconstf,size,int);
+ yy(Defconstf,value,real);
+ break;
+ caselabel(Defstring);
+ yy(Defstring,s,string);
+ break;
+ caselabel(Space);
+ yy(Space,n,int);
+ break;
+ caselabel(Function);
+ yy(Function,f,uid);
+ yy(Function,caller,uid_list);
+ yy(Function,callee,uid_list);
+ yy(Function,ncalls,int);
+ yy(Function,codelist,interface_list);
+ break;
+ caselabel(Forest);
+ yy(Forest,nodes,node_list);
+ break;
+ case rcc_Blockbeg_enum: printf("<strong>Blockbeg</strong> : <em>%s</em>", typename); return;
+ case rcc_Blockend_enum: printf("<strong>Blockend</strong> : <em>%s</em>", typename); return;
+ default: assert(0);
+ }
+#undef attributes
+ printf("</ul>\n");
+}
+
+static void do_program(rcc_program_ty x) {
+ printf("<ul>\n");
+ xx(x,nuids,int);
+ xx(x,nlabels,int);
+ xx(x,items,item_list);
+ xx(x,interfaces,interface_list);
+ xx(x,argc,int);
+ xx(x,argv,string_list);
+ printf("</ul>\n");
+}
+
+int main(int argc, char *argv[]) {
+ int i, version;
+ float stamp = (assert(strstr(rcsid, ",v")), strtod(strstr(rcsid, ",v")+2, NULL))
+;
+ char *infile = NULL, *outfile = NULL;
+ rcc_program_ty pickle;
+
+ for (i = 1; i < argc; i++)
+ if (*argv[i] != '-' || strcmp(argv[i], "-") == 0) {
+ if (infile == NULL)
+ infile = argv[i];
+ else if (outfile == NULL)
+ outfile = argv[i];
+ }
+ if (infile != NULL && strcmp(infile, "-") != 0
+ && freopen(infile, "rb", stdin) == NULL) {
+ fprintf(stderr, "%s: can't read `%s'\n", argv[0], infile);
+ exit(EXIT_FAILURE);
+ }
+ if (infile == NULL || strcmp(infile, "-") == 0)
+ infile = "Standard Input";
+#if WIN32
+ else
+ _setmode(_fileno(stdin), _O_BINARY);
+#endif
+ if (outfile != NULL && strcmp(outfile, "-") != 0
+ && freopen(outfile, "w", stdout) == NULL) {
+ fprintf(stderr, "%s: can't write `%s'\n", argv[0], outfile);
+ exit(EXIT_FAILURE);
+ }
+ version = read_int(stdin);
+ assert(version/100 == (int)stamp);
+ pickle = rcc_read_program(stdin);
+ printf("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\"\n");
+ printf("<html><head><title>%s</title>\n"
+ "<link rev=made href=\"mailto:drh@microsoft.com\">\n"
+ "</head><body>\n<h1>%s</h1>\n", infile, infile);
+ printf("<p>version = %d.%d</p>", version/100, version%100);
+ do_program(pickle);
+ {
+ time_t t;
+ time(&t);
+ printf("<hr><address>%s</address>\n", ctime(&t));
+ }
+ printf("</body></html>\n");
+ return EXIT_SUCCESS;
+}
diff --git a/lcc/src/alloc.c b/lcc/src/alloc.c
new file mode 100755
index 0000000..698da4f
--- /dev/null
+++ b/lcc/src/alloc.c
@@ -0,0 +1,94 @@
+#include "c.h"
+struct block {
+ struct block *next;
+ char *limit;
+ char *avail;
+};
+union align {
+ long l;
+ char *p;
+ double d;
+ int (*f)(void);
+};
+union header {
+ struct block b;
+ union align a;
+};
+#ifdef PURIFY
+union header *arena[3];
+
+void *allocate(unsigned long n, unsigned a) {
+ union header *new = malloc(sizeof *new + n);
+
+ assert(a < NELEMS(arena));
+ if (new == NULL) {
+ error("insufficient memory\n");
+ exit(1);
+ }
+ new->b.next = (void *)arena[a];
+ arena[a] = new;
+ return new + 1;
+}
+
+void deallocate(unsigned a) {
+ union header *p, *q;
+
+ assert(a < NELEMS(arena));
+ for (p = arena[a]; p; p = q) {
+ q = (void *)p->b.next;
+ free(p);
+ }
+ arena[a] = NULL;
+}
+
+void *newarray(unsigned long m, unsigned long n, unsigned a) {
+ return allocate(m*n, a);
+}
+#else
+static struct block
+ first[] = { { NULL }, { NULL }, { NULL } },
+ *arena[] = { &first[0], &first[1], &first[2] };
+static struct block *freeblocks;
+
+void *allocate(unsigned long n, unsigned a) {
+ struct block *ap;
+
+ assert(a < NELEMS(arena));
+ assert(n > 0);
+ ap = arena[a];
+ n = roundup(n, sizeof (union align));
+ while (n > ap->limit - ap->avail) {
+ if ((ap->next = freeblocks) != NULL) {
+ freeblocks = freeblocks->next;
+ ap = ap->next;
+ } else
+ {
+ unsigned m = sizeof (union header) + n + roundup(10*1024, sizeof (union align));
+ ap->next = malloc(m);
+ ap = ap->next;
+ if (ap == NULL) {
+ error("insufficient memory\n");
+ exit(1);
+ }
+ ap->limit = (char *)ap + m;
+ }
+ ap->avail = (char *)((union header *)ap + 1);
+ ap->next = NULL;
+ arena[a] = ap;
+
+ }
+ ap->avail += n;
+ return ap->avail - n;
+}
+
+void *newarray(unsigned long m, unsigned long n, unsigned a) {
+ return allocate(m*n, a);
+}
+void deallocate(unsigned a) {
+ assert(a < NELEMS(arena));
+ arena[a]->next = freeblocks;
+ freeblocks = first[a].next;
+ first[a].next = NULL;
+ arena[a] = &first[a];
+}
+#endif
diff --git a/lcc/src/alpha.md b/lcc/src/alpha.md
new file mode 100755
index 0000000..fe7140a
--- /dev/null
+++ b/lcc/src/alpha.md
@@ -0,0 +1,1192 @@
+%{
+#define INTTMP ((0xff<<1)|(1<<22)|(1<<25)|(1<<27))
+#define INTVAR (0x3f<<9)
+#define FLTTMP ((0x3f<<10)|(0x1ff<<22))
+#define FLTVAR (0xff<<2)
+
+#define INTRET 0x00000001
+#define FLTRET 0x00000003
+
+#define readsreg(p) \
+ (generic((p)->op)==INDIR && (p)->kids[0]->op==VREG+P)
+#define setsrc(d) ((d) && (d)->x.regnode && \
+ (d)->x.regnode->set == src->x.regnode->set && \
+ (d)->x.regnode->mask&src->x.regnode->mask)
+
+#define relink(a, b) ((b)->x.prev = (a), (a)->x.next = (b))
+
+#include "c.h"
+#define NODEPTR_TYPE Node
+#define OP_LABEL(p) ((p)->op)
+#define LEFT_CHILD(p) ((p)->kids[0])
+#define RIGHT_CHILD(p) ((p)->kids[1])
+#define STATE_LABEL(p) ((p)->x.state)
+static void address(Symbol, Symbol, long);
+static void blkfetch(int, int, int, int);
+static void blkloop(int, int, int, int, int, int[]);
+static void blkstore(int, int, int, int);
+static void defaddress(Symbol);
+static void defconst(int, int, Value);
+static void defstring(int, char *);
+static void defsymbol(Symbol);
+static void doarg(Node);
+static void emit2(Node);
+static void export(Symbol);
+static void clobber(Node);
+static void function(Symbol, Symbol [], Symbol [], int);
+static void global(Symbol);
+static void import(Symbol);
+static void local(Symbol);
+static void progbeg(int, char **);
+static void progend(void);
+static void segment(int);
+static void space(int);
+static void target(Node);
+static Symbol ireg[32], freg[32];
+static Symbol iregw, fregw;
+
+static int tmpregs[] = {4, 2, 3};
+static Symbol blkreg;
+
+static int cseg;
+
+static char *currentfile;
+
+%}
+%start stmt
+%term CNSTF4=4113
+%term CNSTF8=8209
+%term CNSTF16=16401
+%term CNSTI1=1045
+%term CNSTI2=2069
+%term CNSTI4=4117
+%term CNSTI8=8213
+%term CNSTP4=4119
+%term CNSTP8=8215
+%term CNSTU1=1046
+%term CNSTU2=2070
+%term CNSTU4=4118
+%term CNSTU8=8214
+
+%term ARGB=41
+%term ARGF4=4129
+%term ARGF8=8225
+%term ARGF16=16417
+%term ARGI4=4133
+%term ARGI8=8229
+%term ARGP4=4135
+%term ARGP8=8231
+%term ARGU4=4134
+%term ARGU8=8230
+
+%term ASGNB=57
+%term ASGNF4=4145
+%term ASGNF8=8241
+%term ASGNF16=16433
+%term ASGNI1=1077
+%term ASGNI2=2101
+%term ASGNI4=4149
+%term ASGNI8=8245
+%term ASGNP4=4151
+%term ASGNP8=8247
+%term ASGNU1=1078
+%term ASGNU2=2102
+%term ASGNU4=4150
+%term ASGNU8=8246
+
+%term INDIRB=73
+%term INDIRF4=4161
+%term INDIRF8=8257
+%term INDIRF16=16449
+%term INDIRI1=1093
+%term INDIRI2=2117
+%term INDIRI4=4165
+%term INDIRI8=8261
+%term INDIRP4=4167
+%term INDIRP8=8263
+%term INDIRU1=1094
+%term INDIRU2=2118
+%term INDIRU4=4166
+%term INDIRU8=8262
+
+%term CVFF4=4209
+%term CVFF8=8305
+%term CVFF16=16497
+%term CVFI4=4213
+%term CVFI8=8309
+
+%term CVIF4=4225
+%term CVIF8=8321
+%term CVIF16=16513
+%term CVII1=1157
+%term CVII2=2181
+%term CVII4=4229
+%term CVII8=8325
+%term CVIU1=1158
+%term CVIU2=2182
+%term CVIU4=4230
+%term CVIU8=8326
+
+%term CVPP4=4247
+%term CVPP8=8343
+%term CVPP16=16535
+%term CVPU4=4246
+%term CVPU8=8342
+
+%term CVUI1=1205
+%term CVUI2=2229
+%term CVUI4=4277
+%term CVUI8=8373
+%term CVUP4=4279
+%term CVUP8=8375
+%term CVUP16=16567
+%term CVUU1=1206
+%term CVUU2=2230
+%term CVUU4=4278
+%term CVUU8=8374
+
+%term NEGF4=4289
+%term NEGF8=8385
+%term NEGF16=16577
+%term NEGI4=4293
+%term NEGI8=8389
+
+%term CALLB=217
+%term CALLF4=4305
+%term CALLF8=8401
+%term CALLF16=16593
+%term CALLI4=4309
+%term CALLI8=8405
+%term CALLP4=4311
+%term CALLP8=8407
+%term CALLU4=4310
+%term CALLU8=8406
+%term CALLV=216
+
+%term RETF4=4337
+%term RETF8=8433
+%term RETF16=16625
+%term RETI4=4341
+%term RETI8=8437
+%term RETP4=4343
+%term RETP8=8439
+%term RETU4=4342
+%term RETU8=8438
+%term RETV=248
+
+%term ADDRGP4=4359
+%term ADDRGP8=8455
+
+%term ADDRFP4=4375
+%term ADDRFP8=8471
+
+%term ADDRLP4=4391
+%term ADDRLP8=8487
+
+%term ADDF4=4401
+%term ADDF8=8497
+%term ADDF16=16689
+%term ADDI4=4405
+%term ADDI8=8501
+%term ADDP4=4407
+%term ADDP8=8503
+%term ADDU4=4406
+%term ADDU8=8502
+
+%term SUBF4=4417
+%term SUBF8=8513
+%term SUBF16=16705
+%term SUBI4=4421
+%term SUBI8=8517
+%term SUBP4=4423
+%term SUBP8=8519
+%term SUBU4=4422
+%term SUBU8=8518
+
+%term LSHI4=4437
+%term LSHI8=8533
+%term LSHU4=4438
+%term LSHU8=8534
+
+%term MODI4=4453
+%term MODI8=8549
+%term MODU4=4454
+%term MODU8=8550
+
+%term RSHI4=4469
+%term RSHI8=8565
+%term RSHU4=4470
+%term RSHU8=8566
+
+%term BANDI4=4485
+%term BANDI8=8581
+%term BANDU4=4486
+%term BANDU8=8582
+
+%term BCOMI4=4501
+%term BCOMI8=8597
+%term BCOMU4=4502
+%term BCOMU8=8598
+
+%term BORI4=4517
+%term BORI8=8613
+%term BORU4=4518
+%term BORU8=8614
+
+%term BXORI4=4533
+%term BXORI8=8629
+%term BXORU4=4534
+%term BXORU8=8630
+
+%term DIVF4=4545
+%term DIVF8=8641
+%term DIVF16=16833
+%term DIVI4=4549
+%term DIVI8=8645
+%term DIVU4=4550
+%term DIVU8=8646
+
+%term MULF4=4561
+%term MULF8=8657
+%term MULF16=16849
+%term MULI4=4565
+%term MULI8=8661
+%term MULU4=4566
+%term MULU8=8662
+
+%term EQF4=4577
+%term EQF8=8673
+%term EQF16=16865
+%term EQI4=4581
+%term EQI8=8677
+%term EQU4=4582
+%term EQU8=8678
+
+%term GEF4=4593
+%term GEF8=8689
+%term GEI4=4597
+%term GEI8=8693
+%term GEI16=16885
+%term GEU4=4598
+%term GEU8=8694
+
+%term GTF4=4609
+%term GTF8=8705
+%term GTF16=16897
+%term GTI4=4613
+%term GTI8=8709
+%term GTU4=4614
+%term GTU8=8710
+
+%term LEF4=4625
+%term LEF8=8721
+%term LEF16=16913
+%term LEI4=4629
+%term LEI8=8725
+%term LEU4=4630
+%term LEU8=8726
+
+%term LTF4=4641
+%term LTF8=8737
+%term LTF16=16929
+%term LTI4=4645
+%term LTI8=8741
+%term LTU4=4646
+%term LTU8=8742
+
+%term NEF4=4657
+%term NEF8=8753
+%term NEF16=16945
+%term NEI4=4661
+%term NEI8=8757
+%term NEU4=4662
+%term NEU8=8758
+
+%term JUMPV=584
+
+%term LABELV=600
+
+%term LOADB=233
+%term LOADF4=4321
+%term LOADF8=8417
+%term LOADF16=16609
+%term LOADI1=1253
+%term LOADI2=2277
+%term LOADI4=4325
+%term LOADI8=8421
+%term LOADP4=4327
+%term LOADP8=8423
+%term LOADU1=1254
+%term LOADU2=2278
+%term LOADU4=4326
+%term LOADU8=8422
+
+%term VREGP=711
+%%
+reg: INDIRI1(VREGP) "# read register\n"
+reg: INDIRU1(VREGP) "# read register\n"
+
+reg: INDIRI2(VREGP) "# read register\n"
+reg: INDIRU2(VREGP) "# read register\n"
+
+reg: INDIRF4(VREGP) "# read register\n"
+reg: INDIRI4(VREGP) "# read register\n"
+reg: INDIRP4(VREGP) "# read register\n"
+reg: INDIRU4(VREGP) "# read register\n"
+
+reg: INDIRF8(VREGP) "# read register\n"
+reg: INDIRI8(VREGP) "# read register\n"
+reg: INDIRP8(VREGP) "# read register\n"
+reg: INDIRU8(VREGP) "# read register\n"
+
+stmt: ASGNI1(VREGP,reg) "# write register\n"
+stmt: ASGNU1(VREGP,reg) "# write register\n"
+
+stmt: ASGNI2(VREGP,reg) "# write register\n"
+stmt: ASGNU2(VREGP,reg) "# write register\n"
+
+stmt: ASGNF4(VREGP,reg) "# write register\n"
+stmt: ASGNI4(VREGP,reg) "# write register\n"
+stmt: ASGNP4(VREGP,reg) "# write register\n"
+stmt: ASGNU4(VREGP,reg) "# write register\n"
+
+stmt: ASGNF8(VREGP,reg) "# write register\n"
+stmt: ASGNI8(VREGP,reg) "# write register\n"
+stmt: ASGNP8(VREGP,reg) "# write register\n"
+stmt: ASGNU8(VREGP,reg) "# write register\n"
+con: CNSTI1 "%a"
+con: CNSTU1 "%a"
+
+con: CNSTI2 "%a"
+con: CNSTU2 "%a"
+
+con: CNSTI4 "%a"
+con: CNSTU4 "%a"
+con: CNSTP4 "%a"
+
+con: CNSTI8 "%a"
+con: CNSTU8 "%a"
+con: CNSTP8 "%a"
+stmt: reg ""
+acon: con "%0"
+acon: ADDRGP8 "%a"
+
+addr: ADDI4(reg,acon) "%1($%0)"
+addr: ADDI8(reg,acon) "%1($%0)"
+addr: ADDU8(reg,acon) "%1($%0)"
+addr: ADDP8(reg,acon) "%1($%0)"
+
+addr: acon "%0"
+addr: reg "($%0)"
+
+addr: ADDRFP8 "%a+%F($sp)"
+addr: ADDRLP8 "%a+%F($sp)"
+
+reg: addr "lda $%c,%0\n" 1
+
+reg: CNSTI1 "# reg\n" range(a, 0, 0)
+reg: CNSTI2 "# reg\n" range(a, 0, 0)
+reg: CNSTI4 "# reg\n" range(a, 0, 0)
+reg: CNSTI8 "# reg\n" range(a, 0, 0)
+reg: CNSTU1 "# reg\n" range(a, 0, 0)
+reg: CNSTU2 "# reg\n" range(a, 0, 0)
+reg: CNSTU4 "# reg\n" range(a, 0, 0)
+reg: CNSTU8 "# reg\n" range(a, 0, 0)
+reg: CNSTP8 "# reg\n" range(a, 0, 0)
+
+stmt: ASGNI1(addr,reg) "stb $%1,%0\n" 1
+stmt: ASGNU1(addr,reg) "stb $%1,%0\n" 1
+stmt: ASGNI2(addr,reg) "stw $%1,%0\n" 1
+stmt: ASGNU2(addr,reg) "stw $%1,%0\n" 1
+
+stmt: ASGNI4(addr,reg) "stl $%1,%0\n" 1
+stmt: ASGNU4(addr,reg) "stl $%1,%0\n" 1
+stmt: ASGNI8(addr,reg) "stq $%1,%0\n" 1
+stmt: ASGNU8(addr,reg) "stq $%1,%0\n" 1
+stmt: ASGNP8(addr,reg) "stq $%1,%0\n" 1
+
+reg: INDIRI1(reg) "ldb $%c,($%0)\n" 1
+reg: INDIRI2(reg) "ldw $%c,($%0)\n" 1
+reg: INDIRI4(addr) "ldl $%c,%0\n" 1
+reg: INDIRI8(addr) "ldq $%c,%0\n" 1
+reg: INDIRP8(addr) "ldq $%c,%0\n" 1
+reg: INDIRU1(reg) "ldbu $%c,($%0)\n" 1
+reg: INDIRU2(reg) "ldwu $%c,($%0)\n" 1
+reg: INDIRU4(addr) "ldl $%c,%0\nzap $%c,240,$%c\n" 2
+reg: INDIRU8(addr) "ldq $%c,%0\n" 1
+
+reg: CVII4(INDIRI1(reg)) "ldb $%c,($%0)\n" 1
+reg: CVII8(INDIRI1(reg)) "ldb $%c,($%0)\n" 1
+reg: CVII4(INDIRI2(reg)) "ldw $%c,($%0)\n" 1
+reg: CVII8(INDIRI2(reg)) "ldw $%c,($%0)\n" 1
+reg: CVII8(INDIRI4(addr)) "ldl $%c,%0\n" 1
+
+reg: CVUU4(INDIRU1(reg)) "ldbu $%c,($%0)\n" 1
+reg: CVUU8(INDIRU1(reg)) "ldbu $%c,($%0)\n" 1
+reg: CVUU4(INDIRU2(reg)) "ldwu $%c,($%0)\n" 1
+reg: CVUU8(INDIRU2(reg)) "ldwu $%c,($%0)\n" 1
+reg: CVUU8(INDIRU4(addr)) "ldl $%c,%0\nzap $%c,240,$%c\n" 2
+
+reg: CVUI4(INDIRU1(reg)) "ldbu $%c,($%0)\n" 1
+reg: CVUI8(INDIRU1(reg)) "ldbu $%c,($%0)\n" 1
+reg: CVUI4(INDIRU2(reg)) "ldwu $%c,($%0)\n" 1
+reg: CVUI8(INDIRU2(reg)) "ldwu $%c,($%0)\n" 1
+reg: CVUI8(INDIRU4(addr)) "ldl $%c,%0\nzap $%c,240,$%c\n" 2
+
+reg: CVIU8(reg) "mov $%0,$%c\n" move(a)
+
+reg: INDIRF4(addr) "lds $f%c,%0\n" 1
+reg: INDIRF8(addr) "ldt $f%c,%0\n" 1
+stmt: ASGNF4(addr,reg) "sts $f%1,%0\n" 1
+stmt: ASGNF8(addr,reg) "stt $f%1,%0\n" 1
+
+reg: MULI4(reg,rc) "mull $%0,%1,$%c\n" 1
+reg: MULI8(reg,rc) "mulq $%0,%1,$%c\n" 1
+reg: MULU4(reg,rc) "mull $%0,%1,$%c\nzap $%c,240,$%c\n" 2
+reg: MULU8(reg,rc) "mulq $%0,%1,$%c\n" 1
+
+reg: DIVI4(reg,rc) "divl $%0,%1,$%c\n" 1
+reg: DIVI8(reg,rc) "divq $%0,%1,$%c\n" 1
+reg: DIVU4(reg,rc) "divlu $%0,%1,$%c\n" 1
+reg: DIVU8(reg,rc) "divqu $%0,%1,$%c\n" 1
+reg: MODI4(reg,rc) "reml $%0,%1,$%c\n" 1
+reg: MODI8(reg,rc) "remq $%0,%1,$%c\n" 1
+reg: MODU4(reg,rc) "remlu $%0,%1,$%c\n" 1
+reg: MODU8(reg,rc) "remqu $%0,%1,$%c\n" 1
+
+rc: con "%0"
+rc: reg "$%0"
+
+reg: ADDI4(reg,rc) "addl $%0,%1,$%c\n" 1
+reg: ADDI8(reg,rc) "addq $%0,%1,$%c\n" 1
+reg: ADDP8(reg,rc) "addq $%0,%1,$%c\n" 1
+reg: ADDU4(reg,rc) "addl $%0,%1,$%c\nzap $%c,240,$%c\n" 2
+reg: ADDU8(reg,rc) "addq $%0,%1,$%c\n" 1
+reg: SUBI4(reg,rc) "subl $%0,%1,$%c\n" 1
+reg: SUBI8(reg,rc) "subq $%0,%1,$%c\n" 1
+reg: SUBP8(reg,rc) "subq $%0,%1,$%c\n" 1
+reg: SUBU4(reg,rc) "subl $%0,%1,$%c\nzap $%c,240,$%c\n" 2
+reg: SUBU8(reg,rc) "subq $%0,%1,$%c\n" 1
+
+reg: BANDI4(reg,rc) "and $%0,%1,$%c\naddl $%c,0,$%c\n" 2
+reg: BANDI8(reg,rc) "and $%0,%1,$%c\n" 1
+reg: BANDU4(reg,rc) "and $%0,%1,$%c\n" 1
+reg: BANDU8(reg,rc) "and $%0,%1,$%c\n" 1
+reg: BORI4(reg,rc) "or $%0,%1,$%c\naddl $%c,0,$%c\n" 2
+reg: BORI8(reg,rc) "or $%0,%1,$%c\n" 1
+reg: BORU4(reg,rc) "or $%0,%1,$%c\n" 1
+reg: BORU8(reg,rc) "or $%0,%1,$%c\n" 1
+reg: BXORI4(reg,rc) "xor $%0,%1,$%c\naddl $%c,0,$%c\n" 2
+reg: BXORI8(reg,rc) "xor $%0,%1,$%c\n" 1
+reg: BXORU4(reg,rc) "xor $%0,%1,$%c\n" 1
+reg: BXORU8(reg,rc) "xor $%0,%1,$%c\n" 1
+
+rc6: CNSTI4 "%a" range(a,0,63)
+rc6: CNSTI8 "%a" range(a,0,63)
+rc6: reg "$%0"
+
+reg: LSHI4(reg,rc6) "sll $%0,%1,$%c\naddl $%c,0,$%c\n" 2
+reg: LSHI8(reg,rc6) "sll $%0,%1,$%c\n" 1
+reg: LSHU4(reg,rc6) "sll $%0,%1,$%c\nzap $%c,240,$%c\n" 2
+reg: LSHU8(reg,rc6) "sll $%0,%1,$%c\n" 1
+reg: RSHI4(reg,rc6) "sra $%0,%1,$%c\naddl $%c,0,$%c\n" 2
+reg: RSHI8(reg,rc6) "sra $%0,%1,$%c\n" 1
+reg: RSHU4(reg,rc6) "srl $%0,%1,$%c\n" 1
+reg: RSHU8(reg,rc6) "srl $%0,%1,$%c\n" 1
+
+reg: BCOMI4(reg) "not $%0,$%c\naddl $%c,0,$%c\n" 2
+reg: BCOMU4(reg) "not $%0,$%c\nzap $%c,240,$%c\n" 2
+reg: BCOMI8(reg) "not $%0,$%c\n" 1
+reg: BCOMU8(reg) "not $%0,$%c\n" 1
+reg: NEGI4(reg) "negl $%0,$%c\n" 1
+reg: NEGI8(reg) "negq $%0,$%c\n" 1
+reg: LOADI1(reg) "mov $%0,$%c\n" move(a)
+reg: LOADI2(reg) "mov $%0,$%c\n" move(a)
+reg: LOADI4(reg) "mov $%0,$%c\n" move(a)
+reg: LOADI8(reg) "mov $%0,$%c\n" move(a)
+reg: LOADP8(reg) "mov $%0,$%c\n" move(a)
+reg: LOADU1(reg) "mov $%0,$%c\n" move(a)
+reg: LOADU2(reg) "mov $%0,$%c\n" move(a)
+reg: LOADU4(reg) "mov $%0,$%c\n" move(a)
+reg: LOADU8(reg) "mov $%0,$%c\n" move(a)
+
+reg: ADDF4(reg,reg) "adds $f%0,$f%1,$f%c\n" 1
+reg: ADDF8(reg,reg) "addt $f%0,$f%1,$f%c\n" 1
+reg: DIVF4(reg,reg) "divs $f%0,$f%1,$f%c\n" 1
+reg: DIVF8(reg,reg) "divt $f%0,$f%1,$f%c\n" 1
+reg: MULF4(reg,reg) "muls $f%0,$f%1,$f%c\n" 1
+reg: MULF8(reg,reg) "mult $f%0,$f%1,$f%c\n" 1
+reg: SUBF4(reg,reg) "subs $f%0,$f%1,$f%c\n" 1
+reg: SUBF8(reg,reg) "subt $f%0,$f%1,$f%c\n" 1
+reg: LOADF4(reg) "fmov $f%0,$f%c\n" move(a)
+reg: LOADF8(reg) "fmov $f%0,$f%c\n" move(a)
+reg: NEGF4(reg) "negs $f%0,$f%c\n" 1
+reg: NEGF8(reg) "negt $f%0,$f%c\n" 1
+reg: CVII4(reg) "sll $%0,8*(8-%a),$%c\nsra $%c,8*(8-%a),$%c\n" 2
+reg: CVII8(reg) "sll $%0,8*(8-%a),$%c\nsra $%c,8*(8-%a),$%c\n" 2
+reg: CVUI4(reg) "and $%0,(1<<(8*%a))-1,$%c\n" 1
+reg: CVUI8(reg) "and $%0,(1<<(8*%a))-1,$%c\n" 1
+reg: CVUU4(reg) "and $%0,(1<<(8*%a))-1,$%c\n" 1
+reg: CVUU8(reg) "and $%0,(1<<(8*%a))-1,$%c\n" 1
+
+reg: CVUP8(reg) "and $%0,(1<<(8*%a))-1,$%c\n" 1
+
+reg: CVFF4(reg) "cvtts $f%0,$f%c\n" 1
+reg: CVFF8(reg) "cvtst $f%0,$f%c\n" 1
+
+reg: CVIF4(reg) "stq $%0,-56+%F($sp)\nldt $%f%c,-56+%F($sp)\ncvtqs $f%c,$f%c\n" 3
+reg: CVIF8(reg) "stq $%0,-56+%F($sp)\nldt $%f%c,-56+%F($sp)\ncvtqt $f%c,$f%c\n" 3
+reg: CVIF4(INDIRI4(addr)) "lds $f%c,%0\ncvtlq $f%c,$f%c\ncvtqs $f%c,$f%c\n" 3
+reg: CVIF4(INDIRI8(addr)) "ldt $f%c,%0\ncvtqs $f%c,$f%c\n" 2
+reg: CVIF8(INDIRI4(addr)) "lds $f%c,%0\ncvtlq $f%c,$f%c\ncvtqt $f%c,$f%c\n" 3
+reg: CVIF8(INDIRI8(addr)) "ldt $f%c,%0\ncvtqt $f%c,$f%c\n" 2
+
+reg: CVFI4(reg) "cvttqc $f%0,$f1\ncvtql $f1,$f1\nsts $f1,-56+%F($sp)\nldl $%c,-56+%F($sp)\n" 4
+reg: CVFI8(reg) "cvttqc $f%0,$f1\nstt $f1,-56+%F($sp)\nldq $%c,-56+%F($sp)\n" 3
+
+stmt: LABELV "%a:\n"
+
+stmt: JUMPV(acon) "br %0\n" 1
+stmt: JUMPV(reg) "jmp ($%0)\n" 1
+
+stmt: EQI4(reg,rc6) "cmpeq $%0,%1,$23\nbne $23,%a\n" 2
+stmt: EQU4(reg,rc6) "cmpeq $%0,%1,$23\nbne $23,%a\n" 2
+stmt: EQI8(reg,rc6) "cmpeq $%0,%1,$23\nbne $23,%a\n" 2
+stmt: EQU8(reg,rc6) "cmpeq $%0,%1,$23\nbne $23,%a\n" 2
+stmt: NEI4(reg,rc6) "cmpeq $%0,%1,$23\nbeq $23,%a\n" 2
+stmt: NEU4(reg,rc6) "cmpeq $%0,%1,$23\nbeq $23,%a\n" 2
+stmt: NEI8(reg,rc6) "cmpeq $%0,%1,$23\nbeq $23,%a\n" 2
+stmt: NEU8(reg,rc6) "cmpeq $%0,%1,$23\nbeq $23,%a\n" 2
+stmt: GEI4(reg,rc6) "cmplt $%0,%1,$23\nbeq $23,%a\n" 2
+stmt: GEI8(reg,rc6) "cmplt $%0,%1,$23\nbeq $23,%a\n" 2
+stmt: GEU4(reg,rc6) "cmpult $%0,%1,$23\nbeq $23,%a\n" 1
+stmt: GEU8(reg,rc6) "cmpult $%0,%1,$23\nbeq $23,%a\n" 1
+stmt: GTI4(reg,rc6) "cmple $%0,%1,$23\nbeq $23,%a\n" 2
+stmt: GTI8(reg,rc6) "cmple $%0,%1,$23\nbeq $23,%a\n" 2
+stmt: GTU4(reg,rc6) "cmpule $%0,%1,$23\nbeq $23,%a\n" 1
+stmt: GTU8(reg,rc6) "cmpule $%0,%1,$23\nbeq $23,%a\n" 1
+stmt: LEI4(reg,rc6) "cmple $%0,%1,$23\nbne $23,%a\n" 2
+stmt: LEI8(reg,rc6) "cmple $%0,%1,$23\nbne $23,%a\n" 2
+stmt: LEU4(reg,rc6) "cmpule $%0,%1,$23\nbne $23,%a\n" 2
+stmt: LEU8(reg,rc6) "cmpule $%0,%1,$23\nbne $23,%a\n" 2
+stmt: LTI4(reg,rc6) "cmplt $%0,%1,$23\nbne $23,%a\n" 2
+stmt: LTI8(reg,rc6) "cmplt $%0,%1,$23\nbne $23,%a\n" 2
+stmt: LTU4(reg,rc6) "cmpult $%0,%1,$23\nbne $23,%a\n" 2
+stmt: LTU8(reg,rc6) "cmpult $%0,%1,$23\nbne $23,%a\n" 2
+
+stmt: EQF4(reg,reg) "cmpteq $f%0,$f%1,$f1\nfbne $f1,%a\n" 2
+stmt: EQF8(reg,reg) "cmpteq $f%0,$f%1,$f1\nfbne $f1,%a\n" 2
+stmt: LEF4(reg,reg) "cmptle $f%0,$f%1,$f1\nfbne $f1,%a\n" 2
+stmt: LEF8(reg,reg) "cmptle $f%0,$f%1,$f1\nfbne $f1,%a\n" 2
+stmt: LTF4(reg,reg) "cmptlt $f%0,$f%1,$f1\nfbne $f1,%a\n" 2
+stmt: LTF8(reg,reg) "cmptlt $f%0,$f%1,$f1\nfbne $f1,%a\n" 2
+
+stmt: NEF4(reg,reg) "cmpteq $f%0,$f%1,$f1\nfbeq $f1,%a\n" 2
+stmt: NEF8(reg,reg) "cmpteq $f%0,$f%1,$f1\nfbeq $f1,%a\n" 2
+stmt: GEF4(reg,reg) "cmptlt $f%0,$f%1,$f1\nfbeq $f1,%a\n" 2
+stmt: GEF8(reg,reg) "cmptlt $f%0,$f%1,$f1\nfbeq $f1,%a\n" 2
+stmt: GTF4(reg,reg) "cmptle $f%0,$f%1,$f1\nfbeq $f1,%a\n" 2
+stmt: GTF8(reg,reg) "cmptle $f%0,$f%1,$f1\nfbeq $f1,%a\n" 2
+
+ar: ADDRGP8 "%a"
+ar: reg "($%0)"
+
+reg: CALLF4(ar) "jsr $26,%0\nldgp $gp,0($26)\n" 2
+reg: CALLF8(ar) "jsr $26,%0\nldgp $gp,0($26)\n" 2
+reg: CALLI4(ar) "jsr $26,%0\nldgp $gp,0($26)\n" 2
+reg: CALLI8(ar) "jsr $26,%0\nldgp $gp,0($26)\n" 2
+reg: CALLP8(ar) "jsr $26,%0\nldgp $gp,0($26)\n" 2
+reg: CALLU4(ar) "jsr $26,%0\nldgp $gp,0($26)\n" 2
+reg: CALLU8(ar) "jsr $26,%0\nldgp $gp,0($26)\n" 2
+stmt: CALLV(ar) "jsr $26,%0\nldgp $gp,0($26)\n" 2
+
+stmt: RETF4(reg) "# ret\n" 1
+stmt: RETF8(reg) "# ret\n" 1
+stmt: RETI4(reg) "# ret\n" 1
+stmt: RETU4(reg) "# ret\n" 1
+stmt: RETI8(reg) "# ret\n" 1
+stmt: RETU8(reg) "# ret\n" 1
+stmt: RETP8(reg) "# ret\n" 1
+stmt: RETV(reg) "# ret\n" 1
+
+stmt: ARGF4(reg) "# arg\n" 1
+stmt: ARGF8(reg) "# arg\n" 1
+stmt: ARGI4(reg) "# arg\n" 1
+stmt: ARGI8(reg) "# arg\n" 1
+stmt: ARGP8(reg) "# arg\n" 1
+stmt: ARGU4(reg) "# arg\n" 1
+stmt: ARGU8(reg) "# arg\n" 1
+
+stmt: ARGB(INDIRB(reg)) "# argb %0\n" 1
+stmt: ASGNB(reg,INDIRB(reg)) "# asgnb %0 %1\n" 1
+
+%%
+static void progend(void){}
+
+static void progbeg(int argc, char *argv[]) {
+ int i;
+
+ {
+ union {
+ char c;
+ int i;
+ } u;
+ u.i = 0;
+ u.c = 1;
+ swap = ((int)(u.i == 1)) != IR->little_endian;
+ }
+ parseflags(argc, argv);
+
+ for (i = 0; i < 32; i++)
+ freg[i] = mkreg("%d", i, 1, FREG);
+ for (i = 0; i < 32; i++)
+ ireg[i] = mkreg("%d", i, 1, IREG);
+ ireg[29]->x.name = "gp";
+ ireg[30]->x.name = "sp";
+ fregw = mkwildcard(freg);
+ iregw = mkwildcard(ireg);
+
+ tmask[IREG] = INTTMP; tmask[FREG] = FLTTMP;
+ vmask[IREG] = INTVAR; vmask[FREG] = FLTVAR;
+
+ blkreg = mkreg("1", 1, 0xf, IREG);
+
+}
+
+static Symbol rmap(int opk) {
+ switch (optype(opk)) {
+ case I: case U: case P: case B:
+ return iregw;
+ case F:
+ return fregw;
+ default:
+ return 0;
+ }
+}
+
+static Symbol argreg(int offset, int ty) {
+ if (offset >= 48)
+ return NULL;
+ else if (ty == F)
+ return freg[(offset/8) + 16];
+ else
+ return ireg[(offset/8) + 16];
+}
+
+static void target(Node p) {
+ assert(p);
+ switch (specific(p->op)) {
+ case CNST+I: case CNST+U: case CNST+P:
+ if (range(p, 0, 0) == 0) {
+ setreg(p, ireg[31]);
+ p->x.registered = 1;
+ }
+ break;
+ case CNST+F:
+ if (p->syms[0]->u.c.v.d == 0) {
+ setreg(p, freg[31]);
+ p->x.registered = 1;
+ }
+ break;
+
+ case CALL+V:
+ rtarget(p, 0, ireg[27]);
+ break;
+ case CALL+F:
+ rtarget(p, 0, ireg[27]);
+ setreg(p, freg[0]);
+ break;
+ case CALL+I: case CALL+P: case CALL+U:
+ rtarget(p, 0, ireg[27]);
+ setreg(p, ireg[0]);
+ break;
+ case RET+F:
+ rtarget(p, 0, freg[0]);
+ break;
+ case RET+I: case RET+U: case RET+P:
+ rtarget(p, 0, ireg[0]);
+ break;
+
+ case ARG+F: case ARG+I: case ARG+P: case ARG+U: {
+ Symbol q = argreg(p->syms[2]->u.c.v.i, optype(p->op));
+ if (q)
+ rtarget(p, 0, q);
+ break;
+ }
+
+
+ case ASGN+B: rtarget(p->kids[1], 0, blkreg); break;
+ case ARG+B: rtarget(p->kids[0], 0, blkreg); break;
+
+ }
+}
+
+static void clobber(Node p) {
+ assert(p);
+ switch (specific(p->op)) {
+ case ASGN+I: case ASGN+U:
+ if (opsize(p->op) <= 2)
+ spill(1<<24, IREG, p);
+ break;
+
+ case DIV+I: case DIV+U: case MOD+I: case MOD+U:
+ spill(((1<<27)|(3<<24))&~p->syms[RX]->x.regnode->mask, IREG, p);
+ break;
+
+ case CALL+F:
+ spill(INTTMP | INTRET, IREG, p);
+ spill(FLTTMP, FREG, p);
+ break;
+ case CALL+I: case CALL+P: case CALL+U:
+ spill(INTTMP, IREG, p);
+ spill(FLTTMP | FLTRET, FREG, p);
+ break;
+ case CALL+V:
+ spill(INTTMP | INTRET, IREG, p);
+ spill(FLTTMP | FLTRET, FREG, p);
+ break;
+
+ }
+}
+
+static void emit2(Node p) {
+ int dst, n, src, sz, ty;
+ static int ty0;
+ Symbol q;
+
+ switch (specific(p->op)) {
+ case ARG+F: case ARG+I: case ARG+P: case ARG+U:
+ ty = optype(p->op);
+ sz = opsize(p->op);
+ q = argreg(p->syms[2]->u.c.v.i, ty);
+ src = getregnum(p->x.kids[0]);
+ if (q)
+ break;
+ else if (ty == F && sz == 4)
+ print("sts $f%d,%d($sp)\n", src, p->syms[2]->u.c.v.i - 48);
+ else if (ty == F && sz == 8)
+ print("stt $f%d,%d($sp)\n", src, p->syms[2]->u.c.v.i - 48);
+ else if (sz == 4)
+ print("stq $%d,%d($sp)\n", src, p->syms[2]->u.c.v.i - 48);
+ else if (sz == 8)
+ print("stq $%d,%d($sp)\n", src, p->syms[2]->u.c.v.i - 48);
+ else
+ assert(0);
+ break;
+
+ case ASGN+B:
+ dalign = salign = p->syms[1]->u.c.v.i;
+ blkcopy(getregnum(p->x.kids[0]), 0,
+ getregnum(p->x.kids[1]), 0,
+ p->syms[0]->u.c.v.i, tmpregs);
+ break;
+
+
+ case ARG+B: {
+ int doff = p->syms[2]->u.c.v.i, soff = 0, sreg = getregnum(p->x.kids[0]);
+ dalign = 8;
+ salign = p->syms[1]->u.c.v.i;
+ n = p->syms[0]->u.c.v.i;
+ for ( ; doff <= 40 && n > 0; doff += 8) {
+ print("uldq $%d,%d($%d)\n", (doff/8)+16, soff, sreg);
+ soff += 8;
+ n -= 8;
+ }
+ if (n > 0)
+ blkcopy(30, doff - 48, sreg, soff, n, tmpregs);
+ break;
+ }
+
+ }
+}
+
+static void doarg(Node p) {
+ p->syms[2] = intconst(mkactual(8, roundup(p->syms[0]->u.c.v.i,8)));
+}
+
+static void local(Symbol p) {
+ if (askregvar(p, rmap(ttob(p->type))) == 0)
+ mkauto(p);
+}
+
+static int bitcount(unsigned mask) {
+ unsigned i, n = 0;
+
+ for (i = 1; i; i <<= 1)
+ if (mask&i)
+ n++;
+ return n;
+}
+
+static void function(Symbol f, Symbol caller[], Symbol callee[], int ncalls) {
+ int i, sizeargs, saved, sizefsave, sizeisave, varargs;
+ Symbol r, argregs[6];
+
+ usedmask[0] = usedmask[1] = 0;
+ freemask[0] = freemask[1] = ~(unsigned)0;
+ maxargoffset = offset = maxoffset = 0;
+
+ for (i = 0; callee[i]; i++)
+ ;
+ varargs = variadic(f->type)
+ || i > 0 && strcmp(callee[i-1]->name, "va_alist") == 0;
+ if (varargs)
+ sizeargs = 2*48;
+ else
+ sizeargs = 48;
+
+ for (i = 0; callee[i]; i++) {
+ Symbol p = callee[i];
+ Symbol q = caller[i];
+ assert(q);
+ if (isfloat(p->type) && varargs) {
+ p->x.offset = q->x.offset = offset - 2*48;
+ p->x.name = q->x.name = stringd(offset - 2*48);
+ } else {
+ p->x.offset = q->x.offset = offset - 48;
+ p->x.name = q->x.name = stringd(offset - 48);
+ }
+ offset = roundup(offset, q->type->align);
+ r = argreg(offset, optype(ttob(q->type)));
+ if (i < 6)
+ argregs[i] = r;
+ offset = roundup(offset + q->type->size, 8);
+ if (varargs)
+ p->sclass = AUTO;
+ else if (r && ncalls == 0 && !isstruct(q->type) && !p->addressed
+) {
+ p->sclass = q->sclass = REGISTER;
+ askregvar(p, r);
+ assert(p->x.regnode && p->x.regnode->vbl == p);
+ q->x = p->x;
+ q->type = p->type;
+ } else if (askregvar(p, rmap(ttob(p->type)))
+ && r != NULL /*
+ && (isint(p->type) || p->type == q->type) */
+) {
+ assert(q->sclass != REGISTER);
+ p->sclass = q->sclass = REGISTER;
+ q->type = p->type;
+ }
+
+ }
+ assert(!caller[i]);
+
+ offset = sizeargs + 8;
+ gencode(caller, callee);
+ usedmask[IREG] &= ~(INTTMP|(0x3f<<16)|INTRET);
+ usedmask[FREG] &= ~(FLTTMP|(0x3f<<16)|FLTRET);
+ if (ncalls || usedmask[IREG] || usedmask[FREG])
+ usedmask[IREG] |= 1<<26;
+ sizefsave = 8*bitcount(usedmask[FREG]);
+ sizeisave = 8*bitcount(usedmask[IREG]);
+ if (maxargoffset > 48)
+ maxargoffset -= 48;
+ else
+ maxargoffset = 0;
+ if (maxoffset < sizeargs)
+ maxoffset = sizeargs;
+ framesize = roundup(maxargoffset + sizefsave + sizeisave + maxoffset, 16);
+ segment(CODE);
+ print(".ent %s\n", f->x.name);
+ print("%s:\n", f->x.name);
+ print("ldgp $gp,0($27)\n");
+ i = maxargoffset + sizefsave - framesize;
+ if (framesize > 0)
+ print("lda $sp,%d($sp)\n", -framesize);
+ if (usedmask[FREG])
+ print(".fmask 0x%x,%d\n", usedmask[FREG], i - 8);
+ if (usedmask[IREG])
+ print(".mask 0x%x,%d\n", usedmask[IREG], i + sizeisave - 8);
+ print(".frame $sp,%d,$26,%d\n", framesize, sizeargs);
+
+ saved = maxargoffset;
+ for (i = 2; i <= 9; i++)
+ if (usedmask[FREG]&(1<<i)) {
+ print("stt $f%d,%d($sp)\n", i, saved);
+ saved += 8;
+ }
+
+ for (i = 9; i <= 26; i++)
+ if (usedmask[IREG]&(1<<i)) {
+ print("stq $%d,%d($sp)\n", i, saved);
+ saved += 8;
+ }
+ for (i = 0; i < 6 && callee[i]; i++) {
+ r = argregs[i];
+ if (r && r->x.regnode != callee[i]->x.regnode) {
+ Symbol out = callee[i];
+ Symbol in = caller[i];
+ int rn = r->x.regnode->number;
+ int rs = r->x.regnode->set;
+ int tyin = ttob(in->type);
+
+ assert(out && in && r && r->x.regnode);
+ assert(out->sclass != REGISTER || out->x.regnode);
+ if (out->sclass == REGISTER) {
+ if (rs == FREG)
+ print("fmov $f%d,$f%d\n", rn, out->x.regnode->number);
+ else
+ print("mov $%d,$%d\n", rn, out->x.regnode->number);
+
+ } else {
+ int off = in->x.offset + framesize;
+ if (rs == FREG && tyin == F+sizeop(8))
+ print("stt $f%d,%d($sp)\n", rn, off);
+ else if (rs == FREG && tyin == F+sizeop(4))
+ print("sts $f%d,%d($sp)\n", rn, off);
+ else {
+ int i, n = (in->type->size + 7)/8;
+ for (i = rn; i < rn+n && i <= 21; i++)
+ print("stq $%d,%d($sp)\n", i, off + (i-rn)*8);
+ }
+
+ }
+
+ }
+ }
+ if (varargs && callee[i-1]) {
+ i = callee[i-1]->x.offset + roundup(callee[i-1]->type->size, 8);
+ for (i = (48+i)/8; i < 6; i++) {
+ print("stq $%d,%d($sp)\n", i + 16, framesize - 48 + 8*i);
+ print("stt $f%d,%d($sp)\n", i + 16, framesize - 2*48 + 8*i);
+ }
+ }
+ print(".prologue 1\n");
+
+ emitcode();
+ saved = maxargoffset;
+ for (i = 2; i <= 9; i++)
+ if (usedmask[FREG]&(1<<i)) {
+ print("ldt $f%d,%d($sp)\n", i, saved);
+ saved += 8;
+ }
+ for (i = 9; i <= 26; i++)
+ if (usedmask[IREG]&(1<<i)) {
+ print("ldq $%d,%d($sp)\n", i, saved);
+ saved += 8;
+ }
+ if (framesize > 0)
+ print("lda $sp,%d($sp)\n", framesize);
+ print("ret\n");
+ print(".end %s\n", f->x.name);
+
+}
+
+static void defconst(int suffix, int size, Value v) {
+ if (suffix == F && size == 4) {
+ float f = v.d;
+ print(".long 0x%x\n", *(unsigned *)&f);
+ } else if (suffix == F && size == 8) {
+ double d = v.d;
+ unsigned *p = (unsigned *)&d;
+ print(".long 0x%x\n.long 0x%x\n", p[swap], p[!swap]);
+ } else if (suffix == P)
+ print(".quad 0x%X\n", v.p);
+ else if (size == 1)
+ print(".byte 0x%x\n", suffix == I ? v.i : v.u);
+ else if (size == 2)
+ print(".word 0x%x\n", suffix == I ? v.i&0xFFFF : v.u&0xFFFF);
+ else if (size == 4)
+ print(".long 0x%x\n", suffix == I ? v.i : v.u);
+ else if (size == 8)
+ print(".quad 0x%X\n", suffix == I ? v.i : v.u);
+
+}
+
+static void defaddress(Symbol p) {
+ print(".quad %s\n", p->x.name);
+}
+
+static void defstring(int n, char *str) {
+ char *s;
+
+ for (s = str; s < str + n; s++)
+ print(".byte %d\n", (*s)&0377);
+}
+
+static void export(Symbol p) {
+ print(".globl %s\n", p->x.name);
+}
+
+static void import(Symbol p) {
+ if (!isfunc(p->type))
+ print(".extern %s %d\n", p->name, p->type->size);
+}
+
+static void defsymbol(Symbol p) {
+ if (p->scope >= LOCAL && p->sclass == STATIC)
+ p->x.name = stringf("L.%d", genlabel(1));
+ else if (p->generated)
+ p->x.name = stringf("L.%s", p->name);
+ else
+ assert(p->scope != CONSTANTS || isint(p->type) || isptr(p->type)),
+ p->x.name = p->name;
+}
+
+static void address(Symbol q, Symbol p, long n) {
+ if (p->scope == GLOBAL
+ || p->sclass == STATIC || p->sclass == EXTERN)
+ q->x.name = stringf("%s%s%D", p->x.name,
+ n >= 0 ? "+" : "", n);
+ else {
+ assert(n <= INT_MAX && n >= INT_MIN);
+ q->x.offset = p->x.offset + n;
+ q->x.name = stringd(q->x.offset);
+ }
+}
+
+static void global(Symbol p) {
+ if (p->u.seg == DATA || p->u.seg == LIT) {
+ assert(p->type->align <= 8);
+ print(".align %c\n", ".01.2...3"[p->type->align]);
+ print("%s:\n", p->x.name);
+ } else if (p->sclass == STATIC || Aflag >= 2)
+ print(".lcomm %s,%d\n", p->x.name, p->type->size);
+ else
+ print( ".comm %s,%d\n", p->x.name, p->type->size);
+}
+
+static void segment(int n) {
+ cseg = n;
+ switch (n) {
+ case DATA: print(".sdata\n"); break;
+ case CODE: print(".text\n"); break;
+ case LIT: print(".rdata\n"); break;
+ }
+}
+
+static void space(int n) {
+ if (cseg != BSS)
+ print(".space %d\n", n);
+}
+
+static void blkloop(int dreg, int doff, int sreg, int soff, int size, int tmps[]) {
+ int lab = genlabel(1);
+
+ print("addq $%d,%d,$%d\n", sreg, size&~7, sreg);
+ print("addq $%d,%d,$%d\n", dreg, size&~7, tmps[2]);
+ blkcopy(tmps[2], doff, sreg, soff, size&7, tmps);
+ print("L.%d:\n", lab);
+ print("addq $%d,%d,$%d\n", sreg, -8, sreg);
+ print("addq $%d,%d,$%d\n", tmps[2], -8, tmps[2]);
+ blkcopy(tmps[2], doff, sreg, soff, 8, tmps);
+ print("cmpult $%d,$%d,$23\nbne $23,L.%d\n", dreg, tmps[2], lab);
+}
+
+static void blkfetch(int size, int off, int reg, int tmp) {
+ assert(size == 1 || size == 2 || size == 4 || size == 8);
+ if (size == 1)
+ print("ldb $%d,%d($%d)\n", tmp, off, reg);
+ else if (size == 2)
+ print("ldw $%d,%d($%d)\n", tmp, off, reg);
+ else if (salign >= size && size == 4)
+ print("ldl $%d,%d($%d)\n", tmp, off, reg);
+ else if (salign >= size && size == 8)
+ print("ldq $%d,%d($%d)\n", tmp, off, reg);
+ else if (size == 4)
+ print("uldl $%d,%d($%d)\n", tmp, off, reg);
+ else
+ print("uldq $%d,%d($%d)\n", tmp, off, reg);
+}
+
+static void blkstore(int size, int off, int reg, int tmp) {
+ assert(size == 1 || size == 2 || size == 4 || size == 8);
+ if (size == 1)
+ print("stb $%d,%d($%d)\n", tmp, off, reg);
+ else if (size == 2)
+ print("stw $%d,%d($%d)\n", tmp, off, reg);
+ else if (dalign >= size && size == 4)
+ print("stl $%d,%d($%d)\n", tmp, off, reg);
+ else if (dalign >= size && size == 8)
+ print("stq $%d,%d($%d)\n", tmp, off, reg);
+ else if (size == 4)
+ print("ustl $%d,%d($%d)\n", tmp, off, reg);
+ else
+ print("ustq $%d,%d($%d)\n", tmp, off, reg);
+}
+
+/* stabinit - initialize stab output */
+static void stabinit(char *file, int argc, char *argv[]) {
+ if (file) {
+ print(".file 2,\"%s\"\n", file);
+ currentfile = file;
+ }
+}
+
+/* stabline - emit stab entry for source coordinate *cp */
+static void stabline(Coordinate *cp) {
+ if (cp->file && cp->file != currentfile) {
+ print(".file 2,\"%s\"\n", cp->file);
+ currentfile = cp->file;
+ }
+ print(".loc 2,%d\n", cp->y);
+}
+
+/* stabsym - output a stab entry for symbol p */
+static void stabsym(Symbol p) {
+ if (p == cfunc && IR->stabline)
+ (*IR->stabline)(&p->src);
+}
+Interface alphaIR = {
+ 1, 1, 0, /* char */
+ 2, 2, 0, /* short */
+ 4, 4, 0, /* int */
+ 8, 8, 0, /* long */
+ 8, 8, 0, /* long long */
+ 4, 4, 1, /* float */
+ 8, 8, 1, /* double */
+ 8, 8, 1, /* long double */
+ 8, 8, 0, /* T * */
+ 0, 1, 0, /* struct */
+
+ 1, /* little_endian */
+ 0, /* mulops_calls */
+ 0, /* wants_callb */
+ 1, /* wants_argb */
+ 1, /* left_to_right */
+ 0, /* wants_dag */
+ 0, /* unsigned_char */
+ address,
+ blockbeg,
+ blockend,
+ defaddress,
+ defconst,
+ defstring,
+ defsymbol,
+ emit,
+ export,
+ function,
+ gen,
+ global,
+ import,
+ local,
+ progbeg,
+ progend,
+ segment,
+ space,
+ 0, 0, 0, stabinit, stabline, stabsym, 0,
+ {
+ 1, /* max_unaligned_load */
+ rmap,
+ blkfetch, blkstore, blkloop,
+ _label,
+ _rule,
+ _nts,
+ _kids,
+ _string,
+ _templates,
+ _isinstruction,
+ _ntname,
+ emit2,
+ doarg,
+ target,
+ clobber,
+
+ }
+
+};
+
+
+static char rcsid[] = "$Id: alpha.md 145 2001-10-17 21:53:10Z timo $";
+
diff --git a/lcc/src/asdl.c b/lcc/src/asdl.c
new file mode 100755
index 0000000..1c01c0c
--- /dev/null
+++ b/lcc/src/asdl.c
@@ -0,0 +1,399 @@
+#include "c.h"
+#include "rcc.h"
+#if WIN32
+#include <fcntl.h>
+#include <io.h>
+#endif
+
+
+static list_ty interfaces;
+static rcc_program_ty pickle;
+
+char *string(const char *str) {
+ return (char *)Atom_string(str);
+}
+
+char *stringd(long n) {
+ return (char *)Atom_int(n);
+}
+
+char *stringn(const char *str, int len) {
+ return (char *)Atom_new(str, len);
+}
+
+static void put(rcc_interface_ty node) {
+ Seq_addhi(interfaces, node);
+}
+
+static int typeuid(Type ty) {
+ rcc_type_ty type;
+
+ assert(ty);
+ if (ty->x.typeno != 0)
+ return ty->x.typeno;
+ ty->x.typeno = pickle->nuids++;
+ switch (ty->op) {
+#define xx(op) case op: type = rcc_##op(ty->size, ty->align); break
+ xx(INT);
+ xx(UNSIGNED);
+ xx(FLOAT);
+ xx(VOID);
+#undef xx
+#define xx(op) case op: type = rcc_##op(ty->size, ty->align, typeuid(ty->type)); break
+ xx(POINTER);
+ xx(ARRAY);
+ xx(CONST);
+ xx(VOLATILE);
+#undef xx
+ case CONST+VOLATILE:
+ type = rcc_CONST(ty->size, ty->align, typeuid(ty->type));
+ break;
+ case ENUM: {
+ list_ty ids = Seq_new(0);
+ int i;
+ for (i = 0; ty->u.sym->u.idlist[i] != NULL; i++)
+ Seq_addhi(ids, rcc_enum_(ty->u.sym->u.idlist[i]->name,
+ ty->u.sym->u.idlist[i]->u.value));
+ assert(i > 0);
+ type = rcc_ENUM(ty->size, ty->align, ty->u.sym->name, ids);
+ break;
+ }
+ case STRUCT: case UNION: {
+ list_ty fields = Seq_new(0);
+ Field p = fieldlist(ty);
+ for ( ; p != NULL; p = p->link)
+ Seq_addhi(fields, rcc_field(p->name, typeuid(p->type), p->offset, p->bitsize, p->lsb));
+ if (ty->op == STRUCT)
+ type = rcc_STRUCT(ty->size, ty->align, ty->u.sym->name, fields);
+ else
+ type = rcc_UNION (ty->size, ty->align, ty->u.sym->name, fields);
+ break;
+ }
+ case FUNCTION: {
+ list_ty formals = Seq_new(0);
+ if (ty->u.f.proto != NULL && ty->u.f.proto[0] != NULL) {
+ int i;
+ for (i = 0; ty->u.f.proto[i] != NULL; i++)
+ Seq_addhi(formals, to_generic_int(typeuid(ty->u.f.proto[i])));
+ } else if (ty->u.f.proto != NULL && ty->u.f.proto[0] == NULL)
+ Seq_addhi(formals, to_generic_int(typeuid(voidtype)));
+ type = rcc_FUNCTION(ty->size, ty->align, typeuid(ty->type), formals);
+ break;
+ }
+ default: assert(0);
+ }
+ Seq_addhi(pickle->items, rcc_Type(ty->x.typeno, type));
+ return ty->x.typeno;
+}
+
+static int symboluid(Symbol p) {
+ assert(p);
+ assert(p->scope != CONSTANTS && p->scope != LABELS);
+ if (p->x.offset == 0)
+ p->x.offset = pickle->nuids++;
+ return p->x.offset;
+}
+
+static rcc_symbol_ty mk_symbol(Symbol p) {
+ int flags = 0, ref = 10000*p->ref;
+
+ if (p->ref > 0 && ref == 0)
+ ref++;
+#define xx(f,n) flags |= p->f<<n;
+ xx(structarg,0)
+ xx(addressed,1)
+ xx(computed,2)
+ xx(temporary,3)
+ xx(generated,4)
+#undef xx
+ return rcc_symbol(p->name, typeuid(p->type), p->scope, p->sclass, ref, flags);
+}
+
+static rcc_real_ty mk_real(int size, Value v) {
+ unsigned *p = (unsigned *)&v.d;
+ return rcc_real(p[swap], p[1-swap]);
+}
+
+static void asdl_segment(int n) {
+ static int cseg;
+
+ if (cseg != n)
+ put(rcc_Segment(cseg = n));
+}
+
+static void asdl_address(Symbol q, Symbol p, long n) {
+ assert(q->x.offset == 0);
+ put(rcc_Address(symboluid(q), mk_symbol(q), symboluid(p), n));
+}
+
+static void asdl_blockbeg(Env *e) {
+ put(rcc_Blockbeg());
+}
+
+static void asdl_blockend(Env *e) {
+ put(rcc_Blockend());
+}
+
+static void asdl_defaddress(Symbol p) {
+ if (p->scope == LABELS)
+ put(rcc_Deflabel(p->u.l.label));
+ else
+ put(rcc_Defaddress(symboluid(p)));
+}
+
+static void asdl_defconst(int suffix, int size, Value v) {
+ switch (suffix) {
+ case I: put(rcc_Defconst(suffix, size, v.i)); return;
+ case U: put(rcc_Defconst(suffix, size, v.u)); return;
+ case P: put(rcc_Defconst(suffix, size, (unsigned long)v.p)); return; /* FIXME */
+ case F: put(rcc_Defconstf(size, mk_real(size, v))); return;
+ assert(0);
+ }
+}
+
+static void asdl_defstring(int len, char *str) {
+ put(rcc_Defstring(Text_box(stringn(str, len), len)));
+}
+
+static void asdl_defsymbol(Symbol p) {
+ if (p->scope >= GLOBAL)
+ symboluid(p);
+}
+
+static Symbol temps;
+
+static rcc_node_ty visit(Node p) {
+ Symbol q;
+ rcc_node_ty left = NULL, right = NULL;
+ int suffix = optype(p->op), size = opsize(p->op);
+
+ assert(p);
+ for (q = temps; q; q = q->u.t.next)
+ if (q->u.t.cse == p) {
+ q->u.t.cse = NULL;
+ return rcc_CSE(0, 0, symboluid(q), visit(p));
+ }
+ if (p->kids[0] != NULL)
+ left = visit(p->kids[0]);
+ if (p->kids[1] != NULL)
+ right = visit(p->kids[1]);
+ switch (specific(p->op)) {
+ case CNST+F:
+ assert(p->syms[0]);
+ return rcc_CNSTF(suffix, size, mk_real(size, p->syms[0]->u.c.v));
+ case CALL+B:
+ assert(p->syms[0]);
+ assert(p->syms[0]->type);
+ return rcc_CALLB(suffix, size, left, right, typeuid(p->syms[0]->type));
+ case RET+V:
+ return rcc_RET(suffix, size);
+ case LABEL+V:
+ assert(p->syms[0]);
+ return rcc_LABEL(suffix, size, p->syms[0]->u.l.label);
+ }
+ switch (generic(p->op)) {
+ case CNST:
+ assert(p->syms[0]);
+ return rcc_CNST(suffix, size, p->syms[0]->u.c.v.i); /* FIXME */
+ case ARG:
+ assert(p->syms[0]);
+ return rcc_ARG(suffix, size, left, p->syms[0]->u.c.v.i, p->syms[1]->u.c.v.i);
+ case ASGN:
+ assert(p->syms[0]);
+ assert(p->syms[1]);
+ return rcc_ASGN(suffix, size, left, right, p->syms[0]->u.c.v.i, p->syms[1]->u.c.v.i);
+ case CVF: case CVI: case CVP: case CVU:
+ assert(p->syms[0]);
+ return rcc_CVT(suffix, size, generic(p->op), left, p->syms[0]->u.c.v.i);
+ case CALL:
+ assert(p->syms[0]);
+ assert(p->syms[0]->type);
+ return rcc_CALL(suffix, size, left, typeuid(p->syms[0]->type));
+#define xx(op) case op: return rcc_##op(suffix, size, symboluid(p->syms[0]))
+ xx(ADDRG);
+ xx(ADDRF);
+#undef xx
+ case ADDRL:
+ if (!p->syms[0]->defined)
+ (*IR->local)(p->syms[0]);
+ p->syms[0]->defined = 1;
+ return rcc_ADDRL(suffix, size, symboluid(p->syms[0]));
+ case JUMP:
+ if (p->syms[0] != NULL)
+ return rcc_BRANCH(suffix, size, p->syms[0]->u.l.label);
+ return rcc_Unary(suffix, size, generic(p->op), left);
+ case INDIR: case RET: case NEG: case BCOM:
+ return rcc_Unary(suffix, size, generic(p->op), left);
+ case BOR: case BAND: case BXOR: case RSH: case LSH:
+ case ADD: case SUB: case DIV: case MUL: case MOD:
+ return rcc_Binary(suffix, size, generic(p->op), left, right);
+ case EQ: case NE: case GT: case GE: case LE: case LT:
+ assert(p->syms[0]);
+ return rcc_Compare(suffix, size, generic(p->op), left, right, p->syms[0]->u.l.label);
+ }
+ assert(0);
+ return NULL;
+}
+
+static void asdl_emit(Node p) {}
+
+static void asdl_local(Symbol p) {
+ assert(p->x.offset == 0);
+ put(rcc_Local(symboluid(p), mk_symbol(p)));
+ if (p->temporary && p->u.t.cse) {
+ p->u.t.next = temps;
+ temps = p;
+ }
+}
+
+static Symbol pending = NULL;
+
+static void dopending(Symbol p) {
+ if (pending != NULL) {
+ int uid = symboluid(pending);
+ rcc_symbol_ty symbol = mk_symbol(pending);
+ Seq_addhi(pickle->items, rcc_Symbol(uid, symbol));
+ }
+ pending = p;
+}
+
+
+static void asdl_export(Symbol p) {
+ put(rcc_Export(symboluid(p)));
+}
+
+static void asdl_function(Symbol f, Symbol caller[], Symbol callee[], int ncalls) {
+ list_ty codelist = Seq_new(0), save, calleelist = Seq_new(0), callerlist = Seq_new(0);
+ int i;
+
+ dopending(f);
+ for (i = 0; caller[i] != NULL; i++) {
+ asdl_local(caller[i]);
+ Seq_addhi(callerlist, to_generic_int(symboluid(caller[i])));
+ }
+ for (i = 0; callee[i] != NULL; i++) {
+ asdl_local(callee[i]);
+ Seq_addhi(calleelist, to_generic_int(symboluid(callee[i])));
+ }
+ save = interfaces;
+ interfaces = codelist;
+ gencode(caller, callee);
+ asdl_segment(CODE);
+ emitcode();
+ interfaces = save;
+ put(rcc_Function(symboluid(f), callerlist, calleelist, ncalls, codelist));
+}
+
+static Node asdl_gen(Node p) {
+ Node q;
+ list_ty forest = Seq_new(0);
+
+ for (q = p; p != NULL; p = p->link)
+ if (specific(p->op) == JUMP+V && specific(p->kids[0]->op) == ADDRG+P
+ && p->kids[0]->syms[0]->scope == LABELS) {
+ p->syms[0] = p->kids[0]->syms[0];
+ p->kids[0] = NULL;
+ }
+ for (p = q; p != NULL; p = p->link)
+ Seq_addhi(forest, visit(p));
+ put(rcc_Forest(forest));
+ temps = NULL;
+ return q;
+}
+
+static void asdl_global(Symbol p) {
+ dopending(p);
+ put(rcc_Global(symboluid(p), p->u.seg));
+}
+
+static void asdl_import(Symbol p) {
+ dopending(p);
+ put(rcc_Import(symboluid(p)));
+}
+
+static void asdl_progbeg(int argc, char *argv[]) {
+ int i;
+
+#if WIN32
+ _setmode(_fileno(stdout), _O_BINARY);
+#endif
+ pickle = rcc_program(1, 0, Seq_new(0), Seq_new(0), argc, Seq_new(0));
+ for (i = 0; i < argc; i++)
+ Seq_addhi(pickle->argv, to_generic_string(Text_box(argv[i], strlen(argv[i]) + 1)));
+ interfaces = pickle->interfaces;
+}
+
+static int checkuid(list_ty list) {
+ int i, n = 0, count = Seq_length(list);
+
+ for (i = 0; i < count; i++) {
+ rcc_interface_ty in = Seq_get(list, i);
+ if (in->kind == rcc_Local_enum
+ || in->kind == rcc_Address_enum)
+ n++;
+ else if (in->kind == rcc_Function_enum)
+ n += checkuid(in->v.rcc_Function.codelist);
+ }
+ return n;
+}
+
+static void asdl_progend(void) {
+ dopending(NULL);
+ {
+ int n = checkuid(pickle->interfaces) + Seq_length(pickle->items);
+ if (n != pickle->nuids - 1)
+ fprintf(stderr, "?bogus uid count: have %d should have %d\n",
+ n, pickle->nuids-1);
+ }
+ pickle->nlabels = genlabel(0);
+ write_int((int)(100*(assert(strstr(rcsid, ",v")), strtod(strstr(rcsid, ",v")+2, NULL))
+), stdout);
+ rcc_write_program(pickle, stdout);
+}
+static void asdl_space(int n) {
+ put(rcc_Space(n));
+}
+
+void asdl_init(int argc, char *argv[]) {
+ int i;
+ static int inited;
+
+ if (inited)
+ return;
+ inited = 1;
+ for (i = 1; i < argc; i++)
+ if (strcmp(argv[i], "-asdl") == 0) {
+#define xx(f) IR->f = asdl_##f
+ xx(address);
+ xx(blockbeg);
+ xx(blockend);
+ xx(defaddress);
+ xx(defconst);
+ xx(defstring);
+ xx(defsymbol);
+ xx(emit);
+ xx(export);
+ xx(function);
+ xx(gen);
+ xx(global);
+ xx(import);
+ xx(local);
+ xx(progbeg);
+ xx(progend);
+ xx(segment);
+ xx(space);
+#undef xx
+#define xx(f) IR->f = 0
+ xx(stabblock);
+ xx(stabend);
+ xx(stabfend);
+ xx(stabinit);
+ xx(stabline);
+ xx(stabsym);
+ xx(stabtype);
+#undef xx
+ IR->wants_dag = 0;
+ prunetemps = 0; /* pass2 prunes useless temps */
+ assignargs = 0; /* pass2 generates caller to callee assignments */
+ }
+}
diff --git a/lcc/src/bind.c b/lcc/src/bind.c
new file mode 100755
index 0000000..3723e37
--- /dev/null
+++ b/lcc/src/bind.c
@@ -0,0 +1,23 @@
+#include "c.h"
+extern Interface alphaIR;
+extern Interface mipsebIR, mipselIR;
+extern Interface sparcIR, solarisIR;
+extern Interface x86IR, x86linuxIR;
+extern Interface symbolicIR, symbolic64IR;
+extern Interface nullIR;
+extern Interface bytecodeIR;
+Binding bindings[] = {
+ "alpha/osf", &alphaIR,
+ "mips/irix", &mipsebIR,
+ "mips/ultrix", &mipselIR,
+ "sparc/sun", &sparcIR,
+ "sparc/solaris", &solarisIR,
+ "x86/win32", &x86IR,
+ "x86/linux", &x86linuxIR,
+ "symbolic/osf", &symbolic64IR,
+ "symbolic/irix", &symbolicIR,
+ "symbolic", &symbolicIR,
+ "null", &nullIR,
+ "bytecode", &bytecodeIR,
+ NULL, NULL
+};
diff --git a/lcc/src/bytecode.c b/lcc/src/bytecode.c
new file mode 100755
index 0000000..f32a04f
--- /dev/null
+++ b/lcc/src/bytecode.c
@@ -0,0 +1,365 @@
+#include "c.h"
+#define I(f) b_##f
+
+
+static void I(segment)(int n) {
+ static int cseg;
+
+ if (cseg != n)
+ switch (cseg = n) {
+ case CODE: print("code\n"); return;
+ case DATA: print("data\n"); return;
+ case BSS: print("bss\n"); return;
+ case LIT: print("lit\n"); return;
+ default: assert(0);
+ }
+}
+
+static void I(address)(Symbol q, Symbol p, long n) {
+ q->x.name = stringf("%s%s%D", p->x.name, n > 0 ? "+" : "", n);
+}
+
+static void I(defaddress)(Symbol p) {
+ print("address %s\n", p->x.name);
+}
+
+static void I(defconst)(int suffix, int size, Value v) {
+ switch (suffix) {
+ case I:
+ if (size > sizeof (int))
+ print("byte %d %D\n", size, v.i);
+ else
+ print("byte %d %d\n", size, v.i);
+ return;
+ case U:
+ if (size > sizeof (unsigned))
+ print("byte %d %U\n", size, v.u);
+ else
+ print("byte %d %u\n", size, v.u);
+ return;
+ case P: print("byte %d %U\n", size, (unsigned long)v.p); return;
+ case F:
+ if (size == 4) {
+ float f = v.d;
+ print("byte 4 %u\n", *(unsigned *)&f);
+ } else {
+ unsigned *p = (unsigned *)&v.d;
+ print("byte 4 %u\n", p[swap]);
+ print("byte 4 %u\n", p[1 - swap]);
+ }
+ return;
+ }
+ assert(0);
+}
+
+static void I(defstring)(int len, char *str) {
+ char *s;
+
+ for (s = str; s < str + len; s++)
+ print("byte 1 %d\n", (*s)&0377);
+}
+
+static void I(defsymbol)(Symbol p) {
+ if (p->scope == CONSTANTS)
+ switch (optype(ttob(p->type))) {
+ case I: p->x.name = stringf("%D", p->u.c.v.i); break;
+ case U: p->x.name = stringf("%U", p->u.c.v.u); break;
+ case P: p->x.name = stringf("%U", p->u.c.v.p); break;
+ case F:
+ { // JDC: added this to get inline floats
+ unsigned temp;
+
+ *(float *)&temp = p->u.c.v.d;
+ p->x.name = stringf("%U", temp );
+ }
+ break;// JDC: added this
+ default: assert(0);
+ }
+ else if (p->scope >= LOCAL && p->sclass == STATIC)
+ p->x.name = stringf("$%d", genlabel(1));
+ else if (p->scope == LABELS || p->generated)
+ p->x.name = stringf("$%s", p->name);
+ else
+ p->x.name = p->name;
+}
+
+static void dumptree(Node p) {
+ switch (specific(p->op)) {
+ case ASGN+B:
+ assert(p->kids[0]);
+ assert(p->kids[1]);
+ assert(p->syms[0]);
+ dumptree(p->kids[0]);
+ dumptree(p->kids[1]);
+ print("%s %d\n", opname(p->op), p->syms[0]->u.c.v.u);
+ return;
+ case RET+V:
+ assert(!p->kids[0]);
+ assert(!p->kids[1]);
+ print("%s\n", opname(p->op));
+ return;
+ }
+ switch (generic(p->op)) {
+ case CNST: case ADDRG: case ADDRF: case ADDRL: case LABEL:
+ assert(!p->kids[0]);
+ assert(!p->kids[1]);
+ assert(p->syms[0] && p->syms[0]->x.name);
+ print("%s %s\n", opname(p->op), p->syms[0]->x.name);
+ return;
+ case CVF: case CVI: case CVP: case CVU:
+ assert(p->kids[0]);
+ assert(!p->kids[1]);
+ assert(p->syms[0]);
+ dumptree(p->kids[0]);
+ print("%s %d\n", opname(p->op), p->syms[0]->u.c.v.i);
+ return;
+ case ARG: case BCOM: case NEG: case INDIR: case JUMP: case RET:
+ assert(p->kids[0]);
+ assert(!p->kids[1]);
+ dumptree(p->kids[0]);
+ print("%s\n", opname(p->op));
+ return;
+ case CALL:
+ assert(p->kids[0]);
+ assert(!p->kids[1]);
+ assert(optype(p->op) != B);
+ dumptree(p->kids[0]);
+ print("%s\n", opname(p->op));
+ if ( !p->count ) { printf("pop\n"); }; // JDC
+ return;
+ case ASGN: case BOR: case BAND: case BXOR: case RSH: case LSH:
+ case ADD: case SUB: case DIV: case MUL: case MOD:
+ assert(p->kids[0]);
+ assert(p->kids[1]);
+ dumptree(p->kids[0]);
+ dumptree(p->kids[1]);
+ print("%s\n", opname(p->op));
+ return;
+ case EQ: case NE: case GT: case GE: case LE: case LT:
+ assert(p->kids[0]);
+ assert(p->kids[1]);
+ assert(p->syms[0]);
+ assert(p->syms[0]->x.name);
+ dumptree(p->kids[0]);
+ dumptree(p->kids[1]);
+ print("%s %s\n", opname(p->op), p->syms[0]->x.name);
+ return;
+ }
+ assert(0);
+}
+
+static void I(emit)(Node p) {
+ for (; p; p = p->link)
+ dumptree(p);
+}
+
+static void I(export)(Symbol p) {
+ print("export %s\n", p->x.name);
+}
+
+static void I(function)(Symbol f, Symbol caller[], Symbol callee[], int ncalls) {
+ int i;
+
+ (*IR->segment)(CODE);
+ offset = 0;
+ for (i = 0; caller[i] && callee[i]; i++) {
+ offset = roundup(offset, caller[i]->type->align);
+ caller[i]->x.name = callee[i]->x.name = stringf("%d", offset);
+ caller[i]->x.offset = callee[i]->x.offset = offset;
+ offset += caller[i]->type->size;
+ }
+ maxargoffset = maxoffset = argoffset = offset = 0;
+ gencode(caller, callee);
+ print("proc %s %d %d\n", f->x.name, maxoffset, maxargoffset);
+ emitcode();
+ print("endproc %s %d %d\n", f->x.name, maxoffset, maxargoffset);
+
+}
+
+static void gen02(Node p) {
+ assert(p);
+ if (generic(p->op) == ARG) {
+ assert(p->syms[0]);
+ argoffset += (p->syms[0]->u.c.v.i < 4 ? 4 : p->syms[0]->u.c.v.i);
+ } else if (generic(p->op) == CALL) {
+ maxargoffset = (argoffset > maxargoffset ? argoffset : maxargoffset);
+ argoffset = 0;
+ }
+}
+
+static void gen01(Node p) {
+ if (p) {
+ gen01(p->kids[0]);
+ gen01(p->kids[1]);
+ gen02(p);
+ }
+}
+
+static Node I(gen)(Node p) {
+ Node q;
+
+ assert(p);
+ for (q = p; q; q = q->link)
+ gen01(q);
+ return p;
+}
+
+static void I(global)(Symbol p) {
+ print("align %d\n", p->type->align > 4 ? 4 : p->type->align);
+ print("LABELV %s\n", p->x.name);
+}
+
+static void I(import)(Symbol p) {
+ print("import %s\n", p->x.name);
+}
+
+static void I(local)(Symbol p) {
+ offset = roundup(offset, p->type->align);
+ p->x.name = stringf("%d", offset);
+ p->x.offset = offset;
+ offset += p->type->size;
+}
+
+static void I(progbeg)(int argc, char *argv[]) {}
+
+static void I(progend)(void) {}
+
+static void I(space)(int n) {
+ print("skip %d\n", n);
+}
+
+//========================================================
+
+// JDC: hacked up to get interleaved source lines in asm code
+static char *sourceFile;
+static char *sourcePtr;
+static int sourceLine;
+
+static int filelength( FILE *f ) {
+ int pos;
+ int end;
+
+ pos = ftell (f);
+ fseek (f, 0, SEEK_END);
+ end = ftell (f);
+ fseek (f, pos, SEEK_SET);
+
+ return end;
+}
+
+static void LoadSourceFile( const char *filename ) {
+ FILE *f;
+ int length;
+
+ f = fopen( filename, "r" );
+ if ( !f ) {
+ print( ";couldn't open %s\n", filename );
+ sourceFile = NULL;
+ return;
+ }
+ length = filelength( f );
+ sourceFile = malloc( length + 1 );
+ if ( sourceFile ) {
+ fread( sourceFile, length, 1, f );
+ sourceFile[length] = 0;
+ }
+
+ fclose( f );
+ sourceLine = 1;
+ sourcePtr = sourceFile;
+}
+
+static void PrintToSourceLine( int line ) {
+ int c;
+
+ if ( !sourceFile ) {
+ return;
+ }
+ while ( sourceLine <= line ) {
+ int i;
+
+ for ( i = 0 ; sourcePtr[i] && sourcePtr[i] != '\n' ; i++ ) {
+ }
+ c = sourcePtr[i];
+ if ( c == '\n' ) {
+ sourcePtr[i] = 0;
+ }
+ print( ";%d:%s\n", sourceLine, sourcePtr );
+ if ( c == 0 ) {
+ sourcePtr += i; // end of file
+ } else {
+ sourcePtr += i+1;
+ }
+ sourceLine++;
+ }
+}
+
+static void I(stabline)(Coordinate *cp) {
+ static char *prevfile;
+ static int prevline;
+
+ if (cp->file && (prevfile == NULL || strcmp(prevfile, cp->file) != 0)) {
+ print("file \"%s\"\n", prevfile = cp->file);
+ prevline = 0;
+ if ( sourceFile ) {
+ free( sourceFile );
+ sourceFile = NULL;
+ }
+ // load the new source file
+ LoadSourceFile( cp->file );
+ }
+ if (cp->y != prevline) {
+ print("line %d\n", prevline = cp->y);
+ PrintToSourceLine( cp->y );
+ }
+}
+
+//========================================================
+
+#define b_blockbeg blockbeg
+#define b_blockend blockend
+
+Interface bytecodeIR = {
+ 1, 1, 0, /* char */
+ 2, 2, 0, /* short */
+ 4, 4, 0, /* int */
+ 4, 4, 0, /* long */
+ 4, 4, 0, /* long long */
+ 4, 4, 0, /* float */ // JDC: use inline floats
+ 4, 4, 0, /* double */ // JDC: don't ever emit 8 byte double code
+ 4, 4, 0, /* long double */ // JDC: don't ever emit 8 byte double code
+ 4, 4, 0, /* T* */
+ 0, 4, 0, /* struct */
+ 0, /* little_endian */
+ 0, /* mulops_calls */
+ 0, /* wants_callb */
+ 0, /* wants_argb */
+ 1, /* left_to_right */
+ 0, /* wants_dag */
+ 0, /* unsigned_char */
+ I(address),
+ I(blockbeg),
+ I(blockend),
+ I(defaddress),
+ I(defconst),
+ I(defstring),
+ I(defsymbol),
+ I(emit),
+ I(export),
+ I(function),
+ I(gen),
+ I(global),
+ I(import),
+ I(local),
+ I(progbeg),
+ I(progend),
+ I(segment),
+ I(space),
+ 0, /* I(stabblock) */
+ 0, /* I(stabend) */
+ 0, /* I(stabfend) */
+ 0, /* I(stabinit) */
+ I(stabline),
+ 0, /* I(stabsym) */
+ 0, /* I(stabtype) */
+};
diff --git a/lcc/src/c.h b/lcc/src/c.h
new file mode 100755
index 0000000..e21419d
--- /dev/null
+++ b/lcc/src/c.h
@@ -0,0 +1,723 @@
+#include <assert.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <limits.h>
+#include <string.h>
+
+#define NEW(p,a) ((p) = allocate(sizeof *(p), (a)))
+#define NEW0(p,a) memset(NEW((p),(a)), 0, sizeof *(p))
+#define isaddrop(op) (specific(op)==ADDRG+P || specific(op)==ADDRL+P \
+ || specific(op)==ADDRF+P)
+
+#define MAXLINE 512
+#define BUFSIZE 4096
+
+#define istypename(t,tsym) (kind[t] == CHAR \
+ || t == ID && tsym && tsym->sclass == TYPEDEF)
+#define sizeop(n) ((n)<<10)
+#define generic(op) ((op)&0x3F0)
+#define specific(op) ((op)&0x3FF)
+#define opindex(op) (((op)>>4)&0x3F)
+#define opkind(op) ((op)&~0x3F0)
+#define opsize(op) ((op)>>10)
+#define optype(op) ((op)&0xF)
+#ifdef __LCC__
+#ifndef __STDC__
+#define __STDC__
+#endif
+#endif
+#define NELEMS(a) ((int)(sizeof (a)/sizeof ((a)[0])))
+#undef roundup
+#define roundup(x,n) (((x)+((n)-1))&(~((n)-1)))
+#define mkop(op,ty) (specific((op) + ttob(ty)))
+
+#define extend(x,ty) ((x)&(1<<(8*(ty)->size-1)) ? (x)|((~0UL)<<(8*(ty)->size-1)) : (x)&ones(8*(ty)->size))
+#define ones(n) ((n)>=8*sizeof (unsigned long) ? ~0UL : ~((~0UL)<<(n)))
+
+#define isqual(t) ((t)->op >= CONST)
+#define unqual(t) (isqual(t) ? (t)->type : (t))
+
+#define isvolatile(t) ((t)->op == VOLATILE \
+ || (t)->op == CONST+VOLATILE)
+#define isconst(t) ((t)->op == CONST \
+ || (t)->op == CONST+VOLATILE)
+#define isarray(t) (unqual(t)->op == ARRAY)
+#define isstruct(t) (unqual(t)->op == STRUCT \
+ || unqual(t)->op == UNION)
+#define isunion(t) (unqual(t)->op == UNION)
+#define isfunc(t) (unqual(t)->op == FUNCTION)
+#define isptr(t) (unqual(t)->op == POINTER)
+#define ischar(t) ((t)->size == 1 && isint(t))
+#define isint(t) (unqual(t)->op == INT \
+ || unqual(t)->op == UNSIGNED)
+#define isfloat(t) (unqual(t)->op == FLOAT)
+#define isarith(t) (unqual(t)->op <= UNSIGNED)
+#define isunsigned(t) (unqual(t)->op == UNSIGNED)
+#define isscalar(t) (unqual(t)->op <= POINTER \
+ || unqual(t)->op == ENUM)
+#define isenum(t) (unqual(t)->op == ENUM)
+#define fieldsize(p) (p)->bitsize
+#define fieldright(p) ((p)->lsb - 1)
+#define fieldleft(p) (8*(p)->type->size - \
+ fieldsize(p) - fieldright(p))
+#define fieldmask(p) (~(~(unsigned)0<<fieldsize(p)))
+typedef struct node *Node;
+
+typedef struct list *List;
+
+typedef struct code *Code;
+
+typedef struct swtch *Swtch;
+
+typedef struct symbol *Symbol;
+
+typedef struct coord {
+ char *file;
+ unsigned x, y;
+} Coordinate;
+typedef struct table *Table;
+
+typedef union value {
+ long i;
+ unsigned long u;
+ long double d;
+ void *p;
+ void (*g)(void);
+} Value;
+typedef struct tree *Tree;
+
+typedef struct type *Type;
+
+typedef struct field *Field;
+
+typedef struct {
+ unsigned printed:1;
+ unsigned marked;
+ unsigned short typeno;
+ void *xt;
+} Xtype;
+
+#include "config.h"
+typedef struct metrics {
+ unsigned char size, align, outofline;
+} Metrics;
+typedef struct interface {
+ Metrics charmetric;
+ Metrics shortmetric;
+ Metrics intmetric;
+ Metrics longmetric;
+ Metrics longlongmetric;
+ Metrics floatmetric;
+ Metrics doublemetric;
+ Metrics longdoublemetric;
+ Metrics ptrmetric;
+ Metrics structmetric;
+ unsigned little_endian:1;
+ unsigned mulops_calls:1;
+ unsigned wants_callb:1;
+ unsigned wants_argb:1;
+ unsigned left_to_right:1;
+ unsigned wants_dag:1;
+ unsigned unsigned_char:1;
+void (*address)(Symbol p, Symbol q, long n);
+void (*blockbeg)(Env *);
+void (*blockend)(Env *);
+void (*defaddress)(Symbol);
+void (*defconst) (int suffix, int size, Value v);
+void (*defstring)(int n, char *s);
+void (*defsymbol)(Symbol);
+void (*emit) (Node);
+void (*export)(Symbol);
+void (*function)(Symbol, Symbol[], Symbol[], int);
+Node (*gen) (Node);
+void (*global)(Symbol);
+void (*import)(Symbol);
+void (*local)(Symbol);
+void (*progbeg)(int argc, char *argv[]);
+void (*progend)(void);
+void (*segment)(int);
+void (*space)(int);
+void (*stabblock)(int, int, Symbol*);
+void (*stabend) (Coordinate *, Symbol, Coordinate **, Symbol *, Symbol *);
+void (*stabfend) (Symbol, int);
+void (*stabinit) (char *, int, char *[]);
+void (*stabline) (Coordinate *);
+void (*stabsym) (Symbol);
+void (*stabtype) (Symbol);
+ Xinterface x;
+} Interface;
+typedef struct binding {
+ char *name;
+ Interface *ir;
+} Binding;
+
+extern Binding bindings[];
+extern Interface *IR;
+typedef struct {
+ List blockentry;
+ List blockexit;
+ List entry;
+ List exit;
+ List returns;
+ List points;
+ List calls;
+ List end;
+} Events;
+
+enum {
+#define xx(a,b,c,d,e,f,g) a=b,
+#define yy(a,b,c,d,e,f,g)
+#include "token.h"
+ LAST
+};
+struct node {
+ short op;
+ short count;
+ Symbol syms[3];
+ Node kids[2];
+ Node link;
+ Xnode x;
+};
+enum {
+ F=FLOAT,
+ I=INT,
+ U=UNSIGNED,
+ P=POINTER,
+ V=VOID,
+ B=STRUCT
+};
+#define gop(name,value) name=value<<4,
+#define op(name,type,sizes)
+
+enum { gop(CNST,1)
+ op(CNST,F,fdx)
+ op(CNST,I,csilh)
+ op(CNST,P,p)
+ op(CNST,U,csilh)
+ gop(ARG,2)
+ op(ARG,B,-)
+ op(ARG,F,fdx)
+ op(ARG,I,ilh)
+ op(ARG,P,p)
+ op(ARG,U,ilh)
+ gop(ASGN,3)
+ op(ASGN,B,-)
+ op(ASGN,F,fdx)
+ op(ASGN,I,csilh)
+ op(ASGN,P,p)
+ op(ASGN,U,csilh)
+ gop(INDIR,4)
+ op(INDIR,B,-)
+ op(INDIR,F,fdx)
+ op(INDIR,I,csilh)
+ op(INDIR,P,p)
+ op(INDIR,U,csilh)
+ gop(CVF,7)
+ op(CVF,F,fdx)
+ op(CVF,I,ilh)
+ gop(CVI,8)
+ op(CVI,F,fdx)
+ op(CVI,I,csilh)
+ op(CVI,U,csilhp)
+ gop(CVP,9)
+ op(CVP,U,p)
+ gop(CVU,11)
+ op(CVU,I,csilh)
+ op(CVU,P,p)
+ op(CVU,U,csilh)
+ gop(NEG,12)
+ op(NEG,F,fdx)
+ op(NEG,I,ilh)
+ gop(CALL,13)
+ op(CALL,B,-)
+ op(CALL,F,fdx)
+ op(CALL,I,ilh)
+ op(CALL,P,p)
+ op(CALL,U,ilh)
+ op(CALL,V,-)
+ gop(RET,15)
+ op(RET,F,fdx)
+ op(RET,I,ilh)
+ op(RET,P,p)
+ op(RET,U,ilh)
+ op(RET,V,-)
+ gop(ADDRG,16)
+ op(ADDRG,P,p)
+ gop(ADDRF,17)
+ op(ADDRF,P,p)
+ gop(ADDRL,18)
+ op(ADDRL,P,p)
+ gop(ADD,19)
+ op(ADD,F,fdx)
+ op(ADD,I,ilh)
+ op(ADD,P,p)
+ op(ADD,U,ilhp)
+ gop(SUB,20)
+ op(SUB,F,fdx)
+ op(SUB,I,ilh)
+ op(SUB,P,p)
+ op(SUB,U,ilhp)
+ gop(LSH,21)
+ op(LSH,I,ilh)
+ op(LSH,U,ilh)
+ gop(MOD,22)
+ op(MOD,I,ilh)
+ op(MOD,U,ilh)
+ gop(RSH,23)
+ op(RSH,I,ilh)
+ op(RSH,U,ilh)
+ gop(BAND,24)
+ op(BAND,I,ilh)
+ op(BAND,U,ilh)
+ gop(BCOM,25)
+ op(BCOM,I,ilh)
+ op(BCOM,U,ilh)
+ gop(BOR,26)
+ op(BOR,I,ilh)
+ op(BOR,U,ilh)
+ gop(BXOR,27)
+ op(BXOR,I,ilh)
+ op(BXOR,U,ilh)
+ gop(DIV,28)
+ op(DIV,F,fdx)
+ op(DIV,I,ilh)
+ op(DIV,U,ilh)
+ gop(MUL,29)
+ op(MUL,F,fdx)
+ op(MUL,I,ilh)
+ op(MUL,U,ilh)
+ gop(EQ,30)
+ op(EQ,F,fdx)
+ op(EQ,I,ilh)
+ op(EQ,U,ilhp)
+ gop(GE,31)
+ op(GE,F,fdx)
+ op(GE,I,ilh)
+ op(GE,U,ilhp)
+ gop(GT,32)
+ op(GT,F,fdx)
+ op(GT,I,ilh)
+ op(GT,U,ilhp)
+ gop(LE,33)
+ op(LE,F,fdx)
+ op(LE,I,ilh)
+ op(LE,U,ilhp)
+ gop(LT,34)
+ op(LT,F,fdx)
+ op(LT,I,ilh)
+ op(LT,U,ilhp)
+ gop(NE,35)
+ op(NE,F,fdx)
+ op(NE,I,ilh)
+ op(NE,U,ilhp)
+ gop(JUMP,36)
+ op(JUMP,V,-)
+ gop(LABEL,37)
+ op(LABEL,V,-)
+ gop(LOAD,14)
+ op(LOAD,B,-)
+ op(LOAD,F,fdx)
+ op(LOAD,I,csilh)
+ op(LOAD,P,p)
+ op(LOAD,U,csilhp) LASTOP };
+
+#undef gop
+#undef op
+enum { CODE=1, BSS, DATA, LIT };
+enum { PERM=0, FUNC, STMT };
+struct list {
+ void *x;
+ List link;
+};
+
+struct code {
+ enum { Blockbeg, Blockend, Local, Address, Defpoint,
+ Label, Start, Gen, Jump, Switch
+ } kind;
+ Code prev, next;
+ union {
+ struct {
+ int level;
+ Symbol *locals;
+ Table identifiers, types;
+ Env x;
+ } block;
+ Code begin;
+ Symbol var;
+
+ struct {
+ Symbol sym;
+ Symbol base;
+ long offset;
+ } addr;
+ struct {
+ Coordinate src;
+ int point;
+ } point;
+ Node forest;
+ struct {
+ Symbol sym;
+ Symbol table;
+ Symbol deflab;
+ int size;
+ long *values;
+ Symbol *labels;
+ } swtch;
+
+ } u;
+};
+struct swtch {
+ Symbol sym;
+ int lab;
+ Symbol deflab;
+ int ncases;
+ int size;
+ long *values;
+ Symbol *labels;
+};
+struct symbol {
+ char *name;
+ int scope;
+ Coordinate src;
+ Symbol up;
+ List uses;
+ int sclass;
+ unsigned structarg:1;
+
+ unsigned addressed:1;
+ unsigned computed:1;
+ unsigned temporary:1;
+ unsigned generated:1;
+ unsigned defined:1;
+ Type type;
+ float ref;
+ union {
+ struct {
+ int label;
+ Symbol equatedto;
+ } l;
+ struct {
+ unsigned cfields:1;
+ unsigned vfields:1;
+ Table ftab; /* omit */
+ Field flist;
+ } s;
+ int value;
+ Symbol *idlist;
+ struct {
+ Value min, max;
+ } limits;
+ struct {
+ Value v;
+ Symbol loc;
+ } c;
+ struct {
+ Coordinate pt;
+ int label;
+ int ncalls;
+ Symbol *callee;
+ } f;
+ int seg;
+ Symbol alias;
+ struct {
+ Node cse;
+ int replace;
+ Symbol next;
+ } t;
+ } u;
+ Xsymbol x;
+};
+enum { CONSTANTS=1, LABELS, GLOBAL, PARAM, LOCAL };
+struct tree {
+ int op;
+ Type type;
+ Tree kids[2];
+ Node node;
+ union {
+ Value v;
+ Symbol sym;
+
+ Field field;
+ } u;
+};
+enum {
+ AND=38<<4,
+ NOT=39<<4,
+ OR=40<<4,
+ COND=41<<4,
+ RIGHT=42<<4,
+ FIELD=43<<4
+};
+struct type {
+ int op;
+ Type type;
+ int align;
+ int size;
+ union {
+ Symbol sym;
+ struct {
+ unsigned oldstyle:1;
+ Type *proto;
+ } f;
+ } u;
+ Xtype x;
+};
+struct field {
+ char *name;
+ Type type;
+ int offset;
+ short bitsize;
+ short lsb;
+ Field link;
+};
+extern int assignargs;
+extern int prunetemps;
+extern int nodecount;
+extern Symbol cfunc;
+extern Symbol retv;
+extern Tree (*optree[])(int, Tree, Tree);
+
+extern char kind[];
+extern int errcnt;
+extern int errlimit;
+extern int wflag;
+extern Events events;
+extern float refinc;
+
+extern unsigned char *cp;
+extern unsigned char *limit;
+extern char *firstfile;
+extern char *file;
+extern char *line;
+extern int lineno;
+extern int t;
+extern char *token;
+extern Symbol tsym;
+extern Coordinate src;
+extern int Aflag;
+extern int Pflag;
+extern Symbol YYnull;
+extern Symbol YYcheck;
+extern int glevel;
+extern int xref;
+
+extern int ncalled;
+extern int npoints;
+
+extern int needconst;
+extern int explicitCast;
+extern struct code codehead;
+extern Code codelist;
+extern Table stmtlabs;
+extern float density;
+extern Table constants;
+extern Table externals;
+extern Table globals;
+extern Table identifiers;
+extern Table labels;
+extern Table types;
+extern int level;
+
+extern List loci, symbols;
+
+extern List symbols;
+
+extern int where;
+extern Type chartype;
+extern Type doubletype;
+extern Type floattype;
+extern Type inttype;
+extern Type longdouble;
+extern Type longtype;
+extern Type longlong;
+extern Type shorttype;
+extern Type signedchar;
+extern Type unsignedchar;
+extern Type unsignedlonglong;
+extern Type unsignedlong;
+extern Type unsignedshort;
+extern Type unsignedtype;
+extern Type charptype;
+extern Type funcptype;
+extern Type voidptype;
+extern Type voidtype;
+extern Type unsignedptr;
+extern Type signedptr;
+extern Type widechar;
+extern void *allocate(unsigned long n, unsigned a);
+extern void deallocate(unsigned a);
+extern void *newarray(unsigned long m, unsigned long n, unsigned a);
+extern void walk(Tree e, int tlab, int flab);
+extern Node listnodes(Tree e, int tlab, int flab);
+extern Node newnode(int op, Node left, Node right, Symbol p);
+extern Tree cvtconst(Tree);
+extern void printdag(Node, int);
+extern void compound(int, Swtch, int);
+extern void defglobal(Symbol, int);
+extern void finalize(void);
+extern void program(void);
+
+extern Tree vcall(Symbol func, Type ty, ...);
+extern Tree addrof(Tree);
+extern Tree asgn(Symbol, Tree);
+extern Tree asgntree(int, Tree, Tree);
+extern Type assign(Type, Tree);
+extern Tree bittree(int, Tree, Tree);
+extern Tree call(Tree, Type, Coordinate);
+extern Tree calltree(Tree, Type, Tree, Symbol);
+extern Tree condtree(Tree, Tree, Tree);
+extern Tree cnsttree(Type, ...);
+extern Tree consttree(unsigned int, Type);
+extern Tree eqtree(int, Tree, Tree);
+extern int iscallb(Tree);
+extern Tree shtree(int, Tree, Tree);
+extern void typeerror(int, Tree, Tree);
+
+extern void test(int tok, char set[]);
+extern void expect(int tok);
+extern void skipto(int tok, char set[]);
+extern void error(const char *, ...);
+extern int fatal(const char *, const char *, int);
+extern void warning(const char *, ...);
+
+typedef void (*Apply)(void *, void *, void *);
+extern void attach(Apply, void *, List *);
+extern void apply(List event, void *arg1, void *arg2);
+extern Tree retype(Tree p, Type ty);
+extern Tree rightkid(Tree p);
+extern int hascall(Tree p);
+extern Type binary(Type, Type);
+extern Tree cast(Tree, Type);
+extern Tree cond(Tree);
+extern Tree expr0(int);
+extern Tree expr(int);
+extern Tree expr1(int);
+extern Tree field(Tree, const char *);
+extern char *funcname(Tree);
+extern Tree idtree(Symbol);
+extern Tree incr(int, Tree, Tree);
+extern Tree lvalue(Tree);
+extern Tree nullcall(Type, Symbol, Tree, Tree);
+extern Tree pointer(Tree);
+extern Tree rvalue(Tree);
+extern Tree value(Tree);
+
+extern void defpointer(Symbol);
+extern Type initializer(Type, int);
+extern void swtoseg(int);
+
+extern void input_init(int, char *[]);
+extern void fillbuf(void);
+extern void nextline(void);
+
+extern int getchr(void);
+extern int gettok(void);
+
+extern void emitcode(void);
+extern void gencode (Symbol[], Symbol[]);
+extern void fprint(FILE *f, const char *fmt, ...);
+extern char *stringf(const char *, ...);
+extern void check(Node);
+extern void print(const char *, ...);
+
+extern List append(void *x, List list);
+extern int length(List list);
+extern void *ltov (List *list, unsigned a);
+extern void init(int, char *[]);
+
+extern Type typename(void);
+extern void checklab(Symbol p, void *cl);
+extern Type enumdcl(void);
+extern void main_init(int, char *[]);
+extern int main(int, char *[]);
+
+extern void vfprint(FILE *, char *, const char *, va_list);
+
+extern int process(char *);
+extern int findfunc(char *, char *);
+extern int findcount(char *, int, int);
+
+extern Tree constexpr(int);
+extern int intexpr(int, int);
+extern Tree simplify(int, Type, Tree, Tree);
+extern int ispow2(unsigned long u);
+
+extern int reachable(int);
+
+extern void addlocal(Symbol);
+extern void branch(int);
+extern Code code(int);
+extern void definelab(int);
+extern void definept(Coordinate *);
+extern void equatelab(Symbol, Symbol);
+extern Node jump(int);
+extern void retcode(Tree);
+extern void statement(int, Swtch, int);
+extern void swcode(Swtch, int *, int, int);
+extern void swgen(Swtch);
+
+extern char * string(const char *str);
+extern char *stringn(const char *str, int len);
+extern char *stringd(long n);
+extern Symbol relocate(const char *name, Table src, Table dst);
+extern void use(Symbol p, Coordinate src);
+extern void locus(Table tp, Coordinate *cp);
+extern Symbol allsymbols(Table);
+
+extern Symbol constant(Type, Value);
+extern void enterscope(void);
+extern void exitscope(void);
+extern Symbol findlabel(int);
+extern Symbol findtype(Type);
+extern void foreach(Table, int, void (*)(Symbol, void *), void *);
+extern Symbol genident(int, Type, int);
+extern int genlabel(int);
+extern Symbol install(const char *, Table *, int, int);
+extern Symbol intconst(int);
+extern Symbol lookup(const char *, Table);
+extern Symbol mkstr(char *);
+extern Symbol mksymbol(int, const char *, Type);
+extern Symbol newtemp(int, int, int);
+extern Table table(Table, int);
+extern Symbol temporary(int, Type);
+extern char *vtoa(Type, Value);
+
+extern int nodeid(Tree);
+extern char *opname(int);
+extern int *printed(int);
+extern void printtree(Tree, int);
+extern Tree root(Tree);
+extern Tree texpr(Tree (*)(int), int, int);
+extern Tree tree(int, Type, Tree, Tree);
+
+extern void type_init(int, char *[]);
+
+extern Type signedint(Type);
+
+extern int hasproto(Type);
+extern void outtype(Type, FILE *);
+extern void printdecl (Symbol p, Type ty);
+extern void printproto(Symbol p, Symbol args[]);
+extern char *typestring(Type ty, char *id);
+extern Field fieldref(const char *name, Type ty);
+extern Type array(Type, int, int);
+extern Type atop(Type);
+extern Type btot(int, int);
+extern Type compose(Type, Type);
+extern Type deref(Type);
+extern int eqtype(Type, Type, int);
+extern Field fieldlist(Type);
+extern Type freturn(Type);
+extern Type ftype(Type, Type);
+extern Type func(Type, Type *, int);
+extern Field newfield(char *, Type, Type);
+extern Type newstruct(int, char *);
+extern void printtype(Type, int);
+extern Type promote(Type);
+extern Type ptr(Type);
+extern Type qual(int, Type);
+extern void rmtypes(int);
+extern int ttob(Type);
+extern int variadic(Type);
+
diff --git a/lcc/src/config.h b/lcc/src/config.h
new file mode 100755
index 0000000..20d115c
--- /dev/null
+++ b/lcc/src/config.h
@@ -0,0 +1,102 @@
+typedef struct {
+ unsigned char max_unaligned_load;
+ Symbol (*rmap)(int);
+
+ void (*blkfetch)(int size, int off, int reg, int tmp);
+ void (*blkstore)(int size, int off, int reg, int tmp);
+ void (*blkloop)(int dreg, int doff,
+ int sreg, int soff,
+ int size, int tmps[]);
+ void (*_label)(Node);
+ int (*_rule)(void*, int);
+ short **_nts;
+ void (*_kids)(Node, int, Node*);
+ char **_string;
+ char **_templates;
+ char *_isinstruction;
+ char **_ntname;
+ void (*emit2)(Node);
+ void (*doarg)(Node);
+ void (*target)(Node);
+ void (*clobber)(Node);
+} Xinterface;
+extern int askregvar(Symbol, Symbol);
+extern void blkcopy(int, int, int, int, int, int[]);
+extern int getregnum(Node);
+extern int mayrecalc(Node);
+extern int mkactual(int, int);
+extern void mkauto(Symbol);
+extern Symbol mkreg(char *, int, int, int);
+extern Symbol mkwildcard(Symbol *);
+extern int move(Node);
+extern int notarget(Node);
+extern void parseflags(int, char **);
+extern int range(Node, int, int);
+extern unsigned regloc(Symbol); /* omit */
+extern void rtarget(Node, int, Symbol);
+extern void setreg(Node, Symbol);
+extern void spill(unsigned, int, Node);
+extern int widens(Node);
+
+extern int argoffset, maxargoffset;
+extern int bflag, dflag;
+extern int dalign, salign;
+extern int framesize;
+extern unsigned freemask[], usedmask[];
+extern int offset, maxoffset;
+extern int swap;
+extern unsigned tmask[], vmask[];
+typedef struct {
+ unsigned listed:1;
+ unsigned registered:1;
+ unsigned emitted:1;
+ unsigned copy:1;
+ unsigned equatable:1;
+ unsigned spills:1;
+ unsigned mayrecalc:1;
+ void *state;
+ short inst;
+ Node kids[3];
+ Node prev, next;
+ Node prevuse;
+ short argno;
+} Xnode;
+typedef struct {
+ Symbol vbl;
+ short set;
+ short number;
+ unsigned mask;
+} *Regnode;
+enum { IREG=0, FREG=1 };
+typedef struct {
+ char *name;
+ unsigned int eaddr; /* omit */
+ int offset;
+ Node lastuse;
+ int usecount;
+ Regnode regnode;
+ Symbol *wildcard;
+} Xsymbol;
+enum { RX=2 };
+typedef struct {
+ int offset;
+ unsigned freemask[2];
+} Env;
+
+#define LBURG_MAX SHRT_MAX
+
+enum { VREG=(44<<4) };
+
+/* Exported for the front end */
+extern void blockbeg(Env *);
+extern void blockend(Env *);
+extern void emit(Node);
+extern Node gen(Node);
+
+extern unsigned emitbin(Node, int);
+
+#ifdef NDEBUG
+#define debug(x) (void)0
+#else
+#define debug(x) (void)(dflag&&((x),0))
+#endif
diff --git a/lcc/src/dag.c b/lcc/src/dag.c
new file mode 100755
index 0000000..6e931ae
--- /dev/null
+++ b/lcc/src/dag.c
@@ -0,0 +1,735 @@
+#include "c.h"
+
+
+#define iscall(op) (generic(op) == CALL \
+ || IR->mulops_calls \
+ && (generic(op)==DIV||generic(op)==MOD||generic(op)==MUL) \
+ && ( optype(op)==U || optype(op)==I))
+static Node forest;
+static struct dag {
+ struct node node;
+ struct dag *hlink;
+} *buckets[16];
+int nodecount;
+static Tree firstarg;
+int assignargs = 1;
+int prunetemps = -1;
+static Node *tail;
+
+static int depth = 0;
+static Node replace(Node);
+static Node prune(Node);
+static Node asgnnode(Symbol, Node);
+static struct dag *dagnode(int, Node, Node, Symbol);
+static Symbol equated(Symbol);
+static void fixup(Node);
+static void labelnode(int);
+static void list(Node);
+static void kill(Symbol);
+static Node node(int, Node, Node, Symbol);
+static void printdag1(Node, int, int);
+static void printnode(Node, int, int);
+static void reset(void);
+static Node tmpnode(Node);
+static void typestab(Symbol, void *);
+static Node undag(Node);
+static Node visit(Node, int);
+static void unlist(void);
+void walk(Tree tp, int tlab, int flab) {
+ listnodes(tp, tlab, flab);
+ if (forest) {
+ Node list = forest->link;
+ forest->link = NULL;
+ if (!IR->wants_dag)
+ list = undag(list);
+ code(Gen)->u.forest = list;
+ forest = NULL;
+ }
+ reset();
+ deallocate(STMT);
+}
+
+static Node node(int op, Node l, Node r, Symbol sym) {
+ int i;
+ struct dag *p;
+
+ i = (opindex(op)^((unsigned long)sym>>2))&(NELEMS(buckets)-1);
+ for (p = buckets[i]; p; p = p->hlink)
+ if (p->node.op == op && p->node.syms[0] == sym
+ && p->node.kids[0] == l && p->node.kids[1] == r)
+ return &p->node;
+ p = dagnode(op, l, r, sym);
+ p->hlink = buckets[i];
+ buckets[i] = p;
+ ++nodecount;
+ return &p->node;
+}
+static struct dag *dagnode(int op, Node l, Node r, Symbol sym) {
+ struct dag *p;
+
+ NEW0(p, FUNC);
+ p->node.op = op;
+ if ((p->node.kids[0] = l) != NULL)
+ ++l->count;
+ if ((p->node.kids[1] = r) != NULL)
+ ++r->count;
+ p->node.syms[0] = sym;
+ return p;
+}
+Node newnode(int op, Node l, Node r, Symbol sym) {
+ return &dagnode(op, l, r, sym)->node;
+}
+static void kill(Symbol p) {
+ int i;
+ struct dag **q;
+
+ for (i = 0; i < NELEMS(buckets); i++)
+ for (q = &buckets[i]; *q; )
+ if (generic((*q)->node.op) == INDIR &&
+ (!isaddrop((*q)->node.kids[0]->op)
+ || (*q)->node.kids[0]->syms[0] == p)) {
+ *q = (*q)->hlink;
+ --nodecount;
+ } else
+ q = &(*q)->hlink;
+}
+static void reset(void) {
+ if (nodecount > 0)
+ memset(buckets, 0, sizeof buckets);
+ nodecount = 0;
+}
+Node listnodes(Tree tp, int tlab, int flab) {
+ Node p = NULL, l, r;
+ int op;
+
+ assert(tlab || flab || tlab == 0 && flab == 0);
+ if (tp == NULL)
+ return NULL;
+ if (tp->node)
+ return tp->node;
+ op = tp->op + sizeop(tp->type->size);
+ switch (generic(tp->op)) {
+ case AND: { if (depth++ == 0) reset();
+ if (flab) {
+ listnodes(tp->kids[0], 0, flab);
+ listnodes(tp->kids[1], 0, flab);
+ } else {
+ listnodes(tp->kids[0], 0, flab = genlabel(1));
+ listnodes(tp->kids[1], tlab, 0);
+ labelnode(flab);
+ }
+ depth--; } break;
+ case OR: { if (depth++ == 0)
+ reset();
+ if (tlab) {
+ listnodes(tp->kids[0], tlab, 0);
+ listnodes(tp->kids[1], tlab, 0);
+ } else {
+ tlab = genlabel(1);
+ listnodes(tp->kids[0], tlab, 0);
+ listnodes(tp->kids[1], 0, flab);
+ labelnode(tlab);
+ }
+ depth--;
+ } break;
+ case NOT: { return listnodes(tp->kids[0], flab, tlab); }
+ case COND: { Tree q = tp->kids[1];
+ assert(tlab == 0 && flab == 0);
+ if (tp->u.sym)
+ addlocal(tp->u.sym);
+ flab = genlabel(2);
+ listnodes(tp->kids[0], 0, flab);
+ assert(q && q->op == RIGHT);
+ reset();
+ listnodes(q->kids[0], 0, 0);
+ if (forest->op == LABEL+V) {
+ equatelab(forest->syms[0], findlabel(flab + 1));
+ unlist();
+ }
+ list(jump(flab + 1));
+ labelnode(flab);
+ listnodes(q->kids[1], 0, 0);
+ if (forest->op == LABEL+V) {
+ equatelab(forest->syms[0], findlabel(flab + 1));
+ unlist();
+ }
+ labelnode(flab + 1);
+
+ if (tp->u.sym)
+ p = listnodes(idtree(tp->u.sym), 0, 0); } break;
+ case CNST: { Type ty = unqual(tp->type);
+ assert(ty->u.sym);
+ if (tlab || flab) {
+ assert(ty == inttype);
+ if (tlab && tp->u.v.i != 0)
+ list(jump(tlab));
+ else if (flab && tp->u.v.i == 0)
+ list(jump(flab));
+ }
+ else if (ty->u.sym->addressed)
+ p = listnodes(cvtconst(tp), 0, 0);
+ else
+ p = node(op, NULL, NULL, constant(ty, tp->u.v)); } break;
+ case RIGHT: { if ( tp->kids[0] && tp->kids[1]
+ && generic(tp->kids[1]->op) == ASGN
+ && (generic(tp->kids[0]->op) == INDIR
+ && tp->kids[0]->kids[0] == tp->kids[1]->kids[0]
+ || (tp->kids[0]->op == FIELD
+ && tp->kids[0] == tp->kids[1]->kids[0]))) {
+ assert(tlab == 0 && flab == 0);
+ if (generic(tp->kids[0]->op) == INDIR) {
+ p = listnodes(tp->kids[0], 0, 0);
+ list(p);
+ listnodes(tp->kids[1], 0, 0);
+ }
+ else {
+ assert(generic(tp->kids[0]->kids[0]->op) == INDIR);
+ list(listnodes(tp->kids[0]->kids[0], 0, 0));
+ p = listnodes(tp->kids[0], 0, 0);
+ listnodes(tp->kids[1], 0, 0);
+ }
+ } else if (tp->kids[1]) {
+ listnodes(tp->kids[0], 0, 0);
+ p = listnodes(tp->kids[1], tlab, flab);
+ } else
+ p = listnodes(tp->kids[0], tlab, flab); } break;
+ case JUMP: { assert(tlab == 0 && flab == 0);
+ assert(tp->u.sym == 0);
+ assert(tp->kids[0]);
+ l = listnodes(tp->kids[0], 0, 0);
+ list(newnode(JUMP+V, l, NULL, NULL));
+ reset(); } break;
+ case CALL: { Tree save = firstarg;
+ firstarg = NULL;
+ assert(tlab == 0 && flab == 0);
+ if (tp->op == CALL+B && !IR->wants_callb) {
+ Tree arg0 = tree(ARG+P, tp->kids[1]->type,
+ tp->kids[1], NULL);
+ if (IR->left_to_right)
+ firstarg = arg0;
+ l = listnodes(tp->kids[0], 0, 0);
+ if (!IR->left_to_right || firstarg) {
+ firstarg = NULL;
+ listnodes(arg0, 0, 0);
+ }
+ p = newnode(CALL+V, l, NULL, NULL);
+ } else {
+ l = listnodes(tp->kids[0], 0, 0);
+ r = listnodes(tp->kids[1], 0, 0);
+ p = newnode(tp->op == CALL+B ? tp->op : op, l, r, NULL);
+ }
+ NEW0(p->syms[0], FUNC);
+ assert(isptr(tp->kids[0]->type));
+ assert(isfunc(tp->kids[0]->type->type));
+ p->syms[0]->type = tp->kids[0]->type->type;
+ list(p);
+ reset();
+ cfunc->u.f.ncalls++;
+ firstarg = save;
+ } break;
+ case ARG: { assert(tlab == 0 && flab == 0);
+ if (IR->left_to_right)
+ listnodes(tp->kids[1], 0, 0);
+ if (firstarg) {
+ Tree arg = firstarg;
+ firstarg = NULL;
+ listnodes(arg, 0, 0);
+ }
+ l = listnodes(tp->kids[0], 0, 0);
+ list(newnode(tp->op == ARG+B ? tp->op : op, l, NULL, NULL));
+ forest->syms[0] = intconst(tp->type->size);
+ forest->syms[1] = intconst(tp->type->align);
+ if (!IR->left_to_right)
+ listnodes(tp->kids[1], 0, 0); } break;
+ case EQ: case NE: case GT: case GE: case LE:
+ case LT: { assert(tp->u.sym == 0);
+ assert(errcnt || tlab || flab);
+ l = listnodes(tp->kids[0], 0, 0);
+ r = listnodes(tp->kids[1], 0, 0);
+ assert(errcnt || opkind(l->op) == opkind(r->op));
+ assert(errcnt || optype(op) == optype(l->op));
+ if (tlab)
+ assert(flab == 0),
+ list(newnode(generic(tp->op) + opkind(l->op), l, r, findlabel(tlab)));
+ else if (flab) {
+ switch (generic(tp->op)) {
+ case EQ: op = NE; break;
+ case NE: op = EQ; break;
+ case GT: op = LE; break;
+ case LT: op = GE; break;
+ case GE: op = LT; break;
+ case LE: op = GT; break;
+ default: assert(0);
+ }
+ list(newnode(op + opkind(l->op), l, r, findlabel(flab)));
+ }
+ if (forest && forest->syms[0])
+ forest->syms[0]->ref++; } break;
+ case ASGN: { assert(tlab == 0 && flab == 0);
+ if (tp->kids[0]->op == FIELD) {
+ Tree x = tp->kids[0]->kids[0];
+ Field f = tp->kids[0]->u.field;
+ assert(generic(x->op) == INDIR);
+ reset();
+ l = listnodes(lvalue(x), 0, 0);
+ if (fieldsize(f) < 8*f->type->size) {
+ unsigned int fmask = fieldmask(f);
+ unsigned int mask = fmask<<fieldright(f);
+ Tree q = tp->kids[1];
+ if (q->op == CNST+I && q->u.v.i == 0
+ || q->op == CNST+U && q->u.v.u == 0)
+ q = bittree(BAND, x, cnsttree(unsignedtype, (unsigned long)~mask));
+ else if (q->op == CNST+I && (q->u.v.i&fmask) == fmask
+ || q->op == CNST+U && (q->u.v.u&fmask) == fmask)
+ q = bittree(BOR, x, cnsttree(unsignedtype, (unsigned long)mask));
+ else {
+ listnodes(q, 0, 0);
+ q = bittree(BOR,
+ bittree(BAND, rvalue(lvalue(x)),
+ cnsttree(unsignedtype, (unsigned long)~mask)),
+ bittree(BAND, shtree(LSH, cast(q, unsignedtype),
+ cnsttree(unsignedtype, (unsigned long)fieldright(f))),
+ cnsttree(unsignedtype, (unsigned long)mask)));
+ }
+ r = listnodes(q, 0, 0);
+ op = ASGN + ttob(q->type);
+ } else {
+ r = listnodes(tp->kids[1], 0, 0);
+ op = ASGN + ttob(tp->kids[1]->type);
+ }
+ } else {
+ l = listnodes(tp->kids[0], 0, 0);
+ r = listnodes(tp->kids[1], 0, 0);
+ }
+ list(newnode(tp->op == ASGN+B ? tp->op : op, l, r, NULL));
+ forest->syms[0] = intconst(tp->kids[1]->type->size);
+ forest->syms[1] = intconst(tp->kids[1]->type->align);
+ if (isaddrop(tp->kids[0]->op)
+ && !tp->kids[0]->u.sym->computed)
+ kill(tp->kids[0]->u.sym);
+ else
+ reset();
+ p = listnodes(tp->kids[1], 0, 0); } break;
+ case BOR: case BAND: case BXOR:
+ case ADD: case SUB: case RSH:
+ case LSH: { assert(tlab == 0 && flab == 0);
+ l = listnodes(tp->kids[0], 0, 0);
+ r = listnodes(tp->kids[1], 0, 0);
+ p = node(op, l, r, NULL); } break;
+ case DIV: case MUL:
+ case MOD: { assert(tlab == 0 && flab == 0);
+ l = listnodes(tp->kids[0], 0, 0);
+ r = listnodes(tp->kids[1], 0, 0);
+ p = node(op, l, r, NULL);
+ if (IR->mulops_calls && isint(tp->type)) {
+ list(p);
+ cfunc->u.f.ncalls++;
+ } } break;
+ case RET: { assert(tlab == 0 && flab == 0);
+ l = listnodes(tp->kids[0], 0, 0);
+ list(newnode(op, l, NULL, NULL)); } break;
+ case CVF: case CVI: case CVP:
+ case CVU: { assert(tlab == 0 && flab == 0);
+ assert(optype(tp->kids[0]->op) != optype(tp->op) || tp->kids[0]->type->size != tp->type->size);
+ l = listnodes(tp->kids[0], 0, 0);
+ p = node(op, l, NULL, intconst(tp->kids[0]->type->size));
+ } break;
+ case BCOM:
+ case NEG: { assert(tlab == 0 && flab == 0);
+ l = listnodes(tp->kids[0], 0, 0);
+ p = node(op, l, NULL, NULL); } break;
+ case INDIR: { Type ty = tp->kids[0]->type;
+ assert(tlab == 0 && flab == 0);
+ l = listnodes(tp->kids[0], 0, 0);
+ if (isptr(ty))
+ ty = unqual(ty)->type;
+ if (isvolatile(ty)
+ || (isstruct(ty) && unqual(ty)->u.sym->u.s.vfields))
+ p = newnode(tp->op == INDIR+B ? tp->op : op, l, NULL, NULL);
+ else
+ p = node(tp->op == INDIR+B ? tp->op : op, l, NULL, NULL); } break;
+ case FIELD: { Tree q = tp->kids[0];
+ if (tp->type == inttype) {
+ long n = fieldleft(tp->u.field);
+ q = shtree(RSH,
+ shtree(LSH, q, cnsttree(inttype, n)),
+ cnsttree(inttype, n + fieldright(tp->u.field)));
+ } else if (fieldsize(tp->u.field) < 8*tp->u.field->type->size)
+ q = bittree(BAND,
+ shtree(RSH, q, cnsttree(inttype, (long)fieldright(tp->u.field))),
+ cnsttree(unsignedtype, (unsigned long)fieldmask(tp->u.field)));
+ assert(tlab == 0 && flab == 0);
+ p = listnodes(q, 0, 0); } break;
+ case ADDRG:
+ case ADDRF: { assert(tlab == 0 && flab == 0);
+ p = node(tp->op + sizeop(voidptype->size), NULL, NULL, tp->u.sym);
+ } break;
+ case ADDRL: { assert(tlab == 0 && flab == 0);
+ if (tp->u.sym->temporary)
+ addlocal(tp->u.sym);
+ p = node(tp->op + sizeop(voidptype->size), NULL, NULL, tp->u.sym); } break;
+ default:assert(0);
+ }
+ tp->node = p;
+ return p;
+}
+static void list(Node p) {
+ if (p && p->link == NULL) {
+ if (forest) {
+ p->link = forest->link;
+ forest->link = p;
+ } else
+ p->link = p;
+ forest = p;
+ }
+}
+static void labelnode(int lab) {
+ assert(lab);
+ if (forest && forest->op == LABEL+V)
+ equatelab(findlabel(lab), forest->syms[0]);
+ else
+ list(newnode(LABEL+V, NULL, NULL, findlabel(lab)));
+ reset();
+}
+static void unlist(void) {
+ Node p;
+
+ assert(forest);
+ assert(forest != forest->link);
+ p = forest->link;
+ while (p->link != forest)
+ p = p->link;
+ p->link = forest->link;
+ forest = p;
+}
+Tree cvtconst(Tree p) {
+ Symbol q = constant(p->type, p->u.v);
+ Tree e;
+
+ if (q->u.c.loc == NULL)
+ q->u.c.loc = genident(STATIC, p->type, GLOBAL);
+ if (isarray(p->type)) {
+ e = simplify(ADDRG, atop(p->type), NULL, NULL);
+ e->u.sym = q->u.c.loc;
+ } else
+ e = idtree(q->u.c.loc);
+ return e;
+}
+void gencode(Symbol caller[], Symbol callee[]) {
+ Code cp;
+ Coordinate save;
+
+ if (prunetemps == -1)
+ prunetemps = !IR->wants_dag;
+ save = src;
+ if (assignargs) {
+ int i;
+ Symbol p, q;
+ cp = codehead.next->next;
+ codelist = codehead.next;
+ for (i = 0; (p = callee[i]) != NULL
+ && (q = caller[i]) != NULL; i++)
+ if (p->sclass != q->sclass || p->type != q->type)
+ walk(asgn(p, idtree(q)), 0, 0);
+ codelist->next = cp;
+ cp->prev = codelist;
+ }
+ if (glevel && IR->stabsym) {
+ int i;
+ Symbol p, q;
+ for (i = 0; (p = callee[i]) != NULL
+ && (q = caller[i]) != NULL; i++) {
+ (*IR->stabsym)(p);
+ if (p->sclass != q->sclass || p->type != q->type)
+ (*IR->stabsym)(q);
+ }
+ swtoseg(CODE);
+ }
+ cp = codehead.next;
+ for ( ; errcnt <= 0 && cp; cp = cp->next)
+ switch (cp->kind) {
+ case Address: (*IR->address)(cp->u.addr.sym, cp->u.addr.base,
+ cp->u.addr.offset); break;
+ case Blockbeg: {
+ Symbol *p = cp->u.block.locals;
+ (*IR->blockbeg)(&cp->u.block.x);
+ for ( ; *p; p++)
+ if ((*p)->ref != 0.0)
+ (*IR->local)(*p);
+ else if (glevel) (*IR->local)(*p);
+ }
+ break;
+ case Blockend: (*IR->blockend)(&cp->u.begin->u.block.x); break;
+ case Defpoint: src = cp->u.point.src; break;
+ case Gen: case Jump:
+ case Label: if (prunetemps)
+ cp->u.forest = prune(cp->u.forest);
+ fixup(cp->u.forest);
+ cp->u.forest = (*IR->gen)(cp->u.forest); break;
+ case Local: (*IR->local)(cp->u.var); break;
+ case Switch: break;
+ default: assert(0);
+ }
+ src = save;
+}
+static void fixup(Node p) {
+ for ( ; p; p = p->link)
+ switch (generic(p->op)) {
+ case JUMP:
+ if (specific(p->kids[0]->op) == ADDRG+P)
+ p->kids[0]->syms[0] =
+ equated(p->kids[0]->syms[0]);
+ break;
+ case LABEL: assert(p->syms[0] == equated(p->syms[0])); break;
+ case EQ: case GE: case GT: case LE: case LT: case NE:
+ assert(p->syms[0]);
+ p->syms[0] = equated(p->syms[0]);
+ }
+}
+static Symbol equated(Symbol p) {
+ { Symbol q; for (q = p->u.l.equatedto; q; q = q->u.l.equatedto) assert(p != q); }
+ while (p->u.l.equatedto)
+ p = p->u.l.equatedto;
+ return p;
+}
+void emitcode(void) {
+ Code cp;
+ Coordinate save;
+
+ save = src;
+ cp = codehead.next;
+ for ( ; errcnt <= 0 && cp; cp = cp->next)
+ switch (cp->kind) {
+ case Address: break;
+ case Blockbeg: if (glevel && IR->stabblock) {
+ (*IR->stabblock)('{', cp->u.block.level - LOCAL, cp->u.block.locals);
+ swtoseg(CODE);
+ }
+ break;
+ case Blockend: if (glevel && IR->stabblock) {
+ Code bp = cp->u.begin;
+ foreach(bp->u.block.identifiers, bp->u.block.level, typestab, NULL);
+ foreach(bp->u.block.types, bp->u.block.level, typestab, NULL);
+ (*IR->stabblock)('}', bp->u.block.level - LOCAL, bp->u.block.locals);
+ swtoseg(CODE);
+ }
+ break;
+ case Defpoint: src = cp->u.point.src;
+ if (glevel > 0 && IR->stabline) {
+ (*IR->stabline)(&cp->u.point.src); swtoseg(CODE); } break;
+ case Gen: case Jump:
+ case Label: if (cp->u.forest)
+ (*IR->emit)(cp->u.forest); break;
+ case Local: if (glevel && IR->stabsym) {
+ (*IR->stabsym)(cp->u.var);
+ swtoseg(CODE);
+ } break;
+ case Switch: { int i;
+ defglobal(cp->u.swtch.table, LIT);
+ (*IR->defaddress)(equated(cp->u.swtch.labels[0]));
+ for (i = 1; i < cp->u.swtch.size; i++) {
+ long k = cp->u.swtch.values[i-1];
+ while (++k < cp->u.swtch.values[i])
+ assert(k < LONG_MAX),
+ (*IR->defaddress)(equated(cp->u.swtch.deflab));
+ (*IR->defaddress)(equated(cp->u.swtch.labels[i]));
+ }
+ swtoseg(CODE);
+ } break;
+ default: assert(0);
+ }
+ src = save;
+}
+
+static Node undag(Node forest) {
+ Node p;
+
+ tail = &forest;
+ for (p = forest; p; p = p->link)
+ if (generic(p->op) == INDIR) {
+ assert(p->count >= 1);
+ visit(p, 1);
+ if (p->syms[2]) {
+ assert(p->syms[2]->u.t.cse);
+ p->syms[2]->u.t.cse = NULL;
+ addlocal(p->syms[2]);
+ }
+ } else if (iscall(p->op) && p->count >= 1)
+ visit(p, 1);
+ else {
+ assert(p->count == 0),
+ visit(p, 1);
+ *tail = p;
+ tail = &p->link;
+ }
+ *tail = NULL;
+ return forest;
+}
+static Node replace(Node p) {
+ if (p && ( generic(p->op) == INDIR
+ && generic(p->kids[0]->op) == ADDRL
+ && p->kids[0]->syms[0]->temporary
+ && p->kids[0]->syms[0]->u.t.replace)) {
+ p = p->kids[0]->syms[0]->u.t.cse;
+ if (generic(p->op) == INDIR && isaddrop(p->kids[0]->op))
+ p = newnode(p->op, newnode(p->kids[0]->op, NULL, NULL,
+ p->kids[0]->syms[0]), NULL, NULL);
+ else if (generic(p->op) == ADDRG)
+ p = newnode(p->op, NULL, NULL, p->syms[0]);
+ else
+ assert(0);
+ p->count = 1;
+ } else if (p) {
+ p->kids[0] = replace(p->kids[0]);
+ p->kids[1] = replace(p->kids[1]);
+ }
+ return p;
+}
+static Node prune(Node forest) {
+ Node p, *tail = &forest;
+ int count = 0;
+
+ for (p = forest; p; p = p->link) {
+ if (count > 0) {
+ p->kids[0] = replace(p->kids[0]);
+ p->kids[1] = replace(p->kids[1]);
+ }
+ if (( generic(p->op) == ASGN
+ && generic(p->kids[0]->op) == ADDRL
+ && p->kids[0]->syms[0]->temporary
+ && p->kids[0]->syms[0]->u.t.cse == p->kids[1])) {
+ Symbol tmp = p->kids[0]->syms[0];
+ if (!tmp->defined)
+ (*IR->local)(tmp);
+ tmp->defined = 1;
+ if (( generic(p->kids[1]->op) == INDIR
+ && isaddrop(p->kids[1]->kids[0]->op)
+ && p->kids[1]->kids[0]->syms[0]->sclass == REGISTER)
+ || (( generic(p->kids[1]->op) == INDIR
+ && isaddrop(p->kids[1]->kids[0]->op)) && tmp->sclass == AUTO)
+ || (generic(p->kids[1]->op) == ADDRG && tmp->sclass == AUTO)) {
+ tmp->u.t.replace = 1;
+ count++;
+ continue; /* and omit the assignment */
+ }
+ }
+ /* keep the assignment and other roots */
+ *tail = p;
+ tail = &(*tail)->link;
+ }
+ assert(*tail == NULL);
+ return forest;
+}
+static Node visit(Node p, int listed) {
+ if (p)
+ if (p->syms[2])
+ p = tmpnode(p);
+ else if (p->count <= 1 && !iscall(p->op)
+ || p->count == 0 && iscall(p->op)) {
+ p->kids[0] = visit(p->kids[0], 0);
+ p->kids[1] = visit(p->kids[1], 0);
+ }
+
+ else if (specific(p->op) == ADDRL+P || specific(p->op) == ADDRF+P) {
+ assert(!listed);
+ p = newnode(p->op, NULL, NULL, p->syms[0]);
+ p->count = 1;
+ }
+ else if (p->op == INDIR+B) {
+ p = newnode(p->op, p->kids[0], NULL, NULL);
+ p->count = 1;
+ p->kids[0] = visit(p->kids[0], 0);
+ p->kids[1] = visit(p->kids[1], 0);
+ }
+ else {
+ p->kids[0] = visit(p->kids[0], 0);
+ p->kids[1] = visit(p->kids[1], 0);
+ p->syms[2] = temporary(REGISTER, btot(p->op, opsize(p->op)));
+ assert(!p->syms[2]->defined);
+ p->syms[2]->ref = 1;
+ p->syms[2]->u.t.cse = p;
+
+ *tail = asgnnode(p->syms[2], p);
+ tail = &(*tail)->link;
+ if (!listed)
+ p = tmpnode(p);
+ };
+ return p;
+}
+static Node tmpnode(Node p) {
+ Symbol tmp = p->syms[2];
+
+ assert(tmp);
+ if (--p->count == 0)
+ p->syms[2] = NULL;
+ p = newnode(INDIR + ttob(tmp->type),
+ newnode(ADDRL + ttob(voidptype), NULL, NULL, tmp), NULL, NULL);
+ p->count = 1;
+ return p;
+}
+static Node asgnnode(Symbol tmp, Node p) {
+ p = newnode(ASGN + ttob(tmp->type),
+ newnode(ADDRL + ttob(voidptype), NULL, NULL, tmp), p, NULL);
+ p->syms[0] = intconst(tmp->type->size);
+ p->syms[1] = intconst(tmp->type->align);
+ return p;
+}
+/* printdag - print dag p on fd, or the node list if p == 0 */
+void printdag(Node p, int fd) {
+ FILE *f = fd == 1 ? stdout : stderr;
+
+ printed(0);
+ if (p == 0) {
+ if ((p = forest) != NULL)
+ do {
+ p = p->link;
+ printdag1(p, fd, 0);
+ } while (p != forest);
+ } else if (*printed(nodeid((Tree)p)))
+ fprint(f, "node'%d printed above\n", nodeid((Tree)p));
+ else
+ printdag1(p, fd, 0);
+}
+
+/* printdag1 - recursively print dag p */
+static void printdag1(Node p, int fd, int lev) {
+ int id, i;
+
+ if (p == 0 || *printed(id = nodeid((Tree)p)))
+ return;
+ *printed(id) = 1;
+ for (i = 0; i < NELEMS(p->kids); i++)
+ printdag1(p->kids[i], fd, lev + 1);
+ printnode(p, fd, lev);
+}
+
+/* printnode - print fields of dag p */
+static void printnode(Node p, int fd, int lev) {
+ if (p) {
+ FILE *f = fd == 1 ? stdout : stderr;
+ int i, id = nodeid((Tree)p);
+ fprint(f, "%c%d%s", lev == 0 ? '\'' : '#', id,
+ &" "[id < 10 ? 0 : id < 100 ? 1 : 2]);
+ fprint(f, "%s count=%d", opname(p->op), p->count);
+ for (i = 0; i < NELEMS(p->kids) && p->kids[i]; i++)
+ fprint(f, " #%d", nodeid((Tree)p->kids[i]));
+ if (generic(p->op) == CALL && p->syms[0] && p->syms[0]->type)
+ fprint(f, " {%t}", p->syms[0]->type);
+ else
+ for (i = 0; i < NELEMS(p->syms) && p->syms[i]; i++)
+ if (p->syms[i]->name)
+ fprint(f, " %s", p->syms[i]->name);
+ else
+ fprint(f, " %p", p->syms[i]);
+ fprint(f, "\n");
+ }
+}
+
+/* typestab - emit stab entries for p */
+static void typestab(Symbol p, void *cl) {
+ if (!isfunc(p->type) && (p->sclass == EXTERN || p->sclass == STATIC) && IR->stabsym)
+ (*IR->stabsym)(p);
+ else if ((p->sclass == TYPEDEF || p->sclass == 0) && IR->stabtype)
+ (*IR->stabtype)(p);
+}
+
diff --git a/lcc/src/dagcheck.md b/lcc/src/dagcheck.md
new file mode 100755
index 0000000..5deec0d
--- /dev/null
+++ b/lcc/src/dagcheck.md
@@ -0,0 +1,210 @@
+%{
+#include "c.h"
+typedef Node NODEPTR_TYPE;
+#define OP_LABEL(p) (specific((p)->op))
+#define LEFT_CHILD(p) ((p)->kids[0])
+#define RIGHT_CHILD(p) ((p)->kids[1])
+#define STATE_LABEL(p) ((p)->x.state)
+#define PANIC error
+%}
+%term CNSTF=17 CNSTI=21 CNSTP=23 CNSTU=22
+%term ARGB=41 ARGF=33 ARGI=37 ARGP=39 ARGU=38
+%term ASGNB=57 ASGNF=49 ASGNI=53 ASGNP=55 ASGNU=54
+%term INDIRB=73 INDIRF=65 INDIRI=69 INDIRP=71 INDIRU=70
+%term CVFF=113 CVFI=117
+%term CVIF=129 CVII=133 CVIU=134
+%term CVPP=151 CVPU=150
+%term CVUI=181 CVUP=183 CVUU=182
+%term NEGF=193 NEGI=197
+%term CALLB=217 CALLF=209 CALLI=213 CALLP=215 CALLU=214 CALLV=216
+%term RETF=241 RETI=245 RETP=247 RETU=246 RETV=248
+%term ADDRGP=263
+%term ADDRFP=279
+%term ADDRLP=295
+%term ADDF=305 ADDI=309 ADDP=311 ADDU=310
+%term SUBF=321 SUBI=325 SUBP=327 SUBU=326
+%term LSHI=341 LSHU=342
+%term MODI=357 MODU=358
+%term RSHI=373 RSHU=374
+%term BANDI=389 BANDU=390
+%term BCOMI=405 BCOMU=406
+%term BORI=421 BORU=422
+%term BXORI=437 BXORU=438
+%term DIVF=449 DIVI=453 DIVU=454
+%term MULF=465 MULI=469 MULU=470
+%term EQF=481 EQI=485 EQU=486
+%term GEF=497 GEI=501 GEU=502
+%term GTF=513 GTI=517 GTU=518
+%term LEF=529 LEI=533 LEU=534
+%term LTF=545 LTI=549 LTU=550
+%term NEF=561 NEI=565 NEU=566
+%term JUMPV=584
+%term LABELV=600
+%%
+stmt: INDIRB(P) ""
+stmt: INDIRF(P) ""
+stmt: INDIRI(P) ""
+stmt: INDIRU(P) ""
+stmt: INDIRP(P) ""
+stmt: CALLF(P) ""
+stmt: CALLI(P) ""
+stmt: CALLU(P) ""
+stmt: CALLP(P) ""
+stmt: V ""
+bogus: I "" 1
+bogus: U "" 1
+bogus: P "" 1
+bogus: F "" 1
+bogus: B "" 1
+bogus: V "" 1
+I: bogus "" 1
+U: bogus "" 1
+P: bogus "" 1
+F: bogus "" 1
+B: bogus "" 1
+V: bogus "" 1
+F: CNSTF ""
+I: CNSTI ""
+P: CNSTP ""
+U: CNSTU ""
+V: ARGB(B) ""
+V: ARGF(F) ""
+V: ARGI(I) ""
+V: ARGU(U) ""
+V: ARGP(P) ""
+V: ASGNB(P,B) ""
+V: ASGNF(P,F) ""
+V: ASGNI(P,I) ""
+V: ASGNU(P,U) ""
+V: ASGNP(P,P) ""
+B: INDIRB(P) ""
+F: INDIRF(P) ""
+I: INDIRI(P) ""
+U: INDIRU(P) ""
+P: INDIRP(P) ""
+I: CVII(I) ""
+I: CVUI(U) ""
+I: CVFI(F) ""
+U: CVIU(I) ""
+U: CVUU(U) ""
+U: CVPU(P) ""
+F: CVIF(I) ""
+F: CVFF(F) ""
+P: CVUP(U) ""
+P: CVPP(P) ""
+F: NEGF(F) ""
+I: NEGI(I) ""
+V: CALLB(P,P) ""
+F: CALLF(P) ""
+I: CALLI(P) ""
+U: CALLU(P) ""
+P: CALLP(P) ""
+V: CALLV(P) ""
+V: RETF(F) ""
+V: RETI(I) ""
+V: RETU(U) ""
+V: RETP(P) ""
+V: RETV ""
+P: ADDRGP ""
+P: ADDRFP ""
+P: ADDRLP ""
+F: ADDF(F,F) ""
+I: ADDI(I,I) ""
+P: ADDP(P,I) ""
+P: ADDP(I,P) ""
+P: ADDP(U,P) ""
+P: ADDP(P,U) ""
+U: ADDU(U,U) ""
+F: SUBF(F,F) ""
+I: SUBI(I,I) ""
+P: SUBP(P,I) ""
+P: SUBP(P,U) ""
+U: SUBU(U,U) ""
+I: LSHI(I,I) ""
+U: LSHU(U,I) ""
+I: MODI(I,I) ""
+U: MODU(U,U) ""
+I: RSHI(I,I) ""
+U: RSHU(U,I) ""
+U: BANDU(U,U) ""
+I: BANDI(I,I) ""
+U: BCOMU(U) ""
+I: BCOMI(I) ""
+I: BORI(I,I) ""
+U: BORU(U,U) ""
+U: BXORU(U,U) ""
+I: BXORI(I,I) ""
+F: DIVF(F,F) ""
+I: DIVI(I,I) ""
+U: DIVU(U,U) ""
+F: MULF(F,F) ""
+I: MULI(I,I) ""
+U: MULU(U,U) ""
+V: EQF(F,F) ""
+V: EQI(I,I) ""
+V: EQU(U,U) ""
+V: GEF(F,F) ""
+V: GEI(I,I) ""
+V: GEU(U,U) ""
+V: GTF(F,F) ""
+V: GTI(I,I) ""
+V: GTU(U,U) ""
+V: LEF(F,F) ""
+V: LEI(I,I) ""
+V: LEU(U,U) ""
+V: LTF(F,F) ""
+V: LTI(I,I) ""
+V: LTU(U,U) ""
+V: NEF(F,F) ""
+V: NEI(I,I) ""
+V: NEU(U,U) ""
+V: JUMPV(P) ""
+V: LABELV ""
+%%
+
+static void reduce(NODEPTR_TYPE p, int goalnt) {
+ int i, sz = opsize(p->op), rulenumber = _rule(p->x.state, goalnt);
+ short *nts = _nts[rulenumber];
+ NODEPTR_TYPE kids[10];
+
+ assert(rulenumber);
+ _kids(p, rulenumber, kids);
+ for (i = 0; nts[i]; i++)
+ reduce(kids[i], nts[i]);
+ switch (optype(p->op)) {
+#define xx(ty) if (sz == ty->size) return
+ case I:
+ case U:
+ xx(chartype);
+ xx(shorttype);
+ xx(inttype);
+ xx(longtype);
+ xx(longlong);
+ break;
+ case F:
+ xx(floattype);
+ xx(doubletype);
+ xx(longdouble);
+ break;
+ case P:
+ xx(voidptype);
+ xx(funcptype);
+ break;
+ case V:
+ case B: if (sz == 0) return;
+#undef xx
+ }
+ printdag(p, 2);
+ assert(0);
+}
+
+void check(Node p) {
+ struct _state { short cost[1]; };
+
+ _label(p);
+ if (((struct _state *)p->x.state)->cost[1] > 0) {
+ printdag(p, 2);
+ assert(0);
+ }
+ reduce(p, 1);
+}
diff --git a/lcc/src/decl.c b/lcc/src/decl.c
new file mode 100755
index 0000000..59e0850
--- /dev/null
+++ b/lcc/src/decl.c
@@ -0,0 +1,1160 @@
+#include "c.h"
+
+
+#define add(x,n) (x > inttype->u.sym->u.limits.max.i-(n) ? (overflow=1,x) : x+(n))
+#define chkoverflow(x,n) ((void)add(x,n))
+#define bits2bytes(n) (((n) + 7)/8)
+static int regcount;
+
+static List autos, registers;
+Symbol cfunc; /* current function */
+Symbol retv; /* return value location for structs */
+
+static void checkref(Symbol, void *);
+static Symbol dclglobal(int, char *, Type, Coordinate *);
+static Symbol dcllocal(int, char *, Type, Coordinate *);
+static Symbol dclparam(int, char *, Type, Coordinate *);
+static Type dclr(Type, char **, Symbol **, int);
+static Type dclr1(char **, Symbol **, int);
+static void decl(Symbol (*)(int, char *, Type, Coordinate *));
+extern void doconst(Symbol, void *);
+static void doglobal(Symbol, void *);
+static void doextern(Symbol, void *);
+static void exitparams(Symbol []);
+static void fields(Type);
+static void funcdefn(int, char *, Type, Symbol [], Coordinate);
+static void initglobal(Symbol, int);
+static void oldparam(Symbol, void *);
+static Symbol *parameters(Type);
+static Type specifier(int *);
+static Type structdcl(int);
+static Type tnode(int, Type);
+void program(void) {
+ int n;
+
+ level = GLOBAL;
+ for (n = 0; t != EOI; n++)
+ if (kind[t] == CHAR || kind[t] == STATIC
+ || t == ID || t == '*' || t == '(') {
+ decl(dclglobal);
+ deallocate(STMT);
+ if (!(glevel >= 3 || xref))
+ deallocate(FUNC);
+ } else if (t == ';') {
+ warning("empty declaration\n");
+ t = gettok();
+ } else {
+ error("unrecognized declaration\n");
+ t = gettok();
+ }
+ if (n == 0)
+ warning("empty input file\n");
+}
+static Type specifier(int *sclass) {
+ int cls, cons, sign, size, type, vol;
+ Type ty = NULL;
+
+ cls = vol = cons = sign = size = type = 0;
+ if (sclass == NULL)
+ cls = AUTO;
+ for (;;) {
+ int *p, tt = t;
+ switch (t) {
+ case AUTO:
+ case REGISTER: if (level <= GLOBAL && cls == 0)
+ error("invalid use of `%k'\n", t);
+ p = &cls; t = gettok(); break;
+ case STATIC: case EXTERN:
+ case TYPEDEF: p = &cls; t = gettok(); break;
+ case CONST: p = &cons; t = gettok(); break;
+ case VOLATILE: p = &vol; t = gettok(); break;
+ case SIGNED:
+ case UNSIGNED: p = &sign; t = gettok(); break;
+ case LONG: if (size == LONG) {
+ size = 0;
+ tt = LONG+LONG;
+ }
+ p = &size; t = gettok(); break;
+ case SHORT: p = &size; t = gettok(); break;
+ case VOID: case CHAR: case INT: case FLOAT:
+ case DOUBLE: p = &type; ty = tsym->type;
+ t = gettok(); break;
+ case ENUM: p = &type; ty = enumdcl(); break;
+ case STRUCT:
+ case UNION: p = &type; ty = structdcl(t); break;
+ case ID:
+ if (istypename(t, tsym) && type == 0
+ && sign == 0 && size == 0) {
+ use(tsym, src);
+ ty = tsym->type;
+ if (isqual(ty)
+ && ty->size != ty->type->size) {
+ ty = unqual(ty);
+ if (isconst(tsym->type))
+ ty = qual(CONST, ty);
+ if (isvolatile(tsym->type))
+ ty = qual(VOLATILE, ty);
+ tsym->type = ty;
+ }
+ p = &type;
+ t = gettok();
+ } else
+ p = NULL;
+ break;
+ default: p = NULL;
+ }
+ if (p == NULL)
+ break;
+ if (*p)
+ error("invalid use of `%k'\n", tt);
+ *p = tt;
+ }
+ if (sclass)
+ *sclass = cls;
+ if (type == 0) {
+ type = INT;
+ ty = inttype;
+ }
+ if (size == SHORT && type != INT
+ || size == LONG+LONG && type != INT
+ || size == LONG && type != INT && type != DOUBLE
+ || sign && type != INT && type != CHAR)
+ error("invalid type specification\n");
+ if (type == CHAR && sign)
+ ty = sign == UNSIGNED ? unsignedchar : signedchar;
+ else if (size == SHORT)
+ ty = sign == UNSIGNED ? unsignedshort : shorttype;
+ else if (size == LONG && type == DOUBLE)
+ ty = longdouble;
+ else if (size == LONG+LONG) {
+ ty = sign == UNSIGNED ? unsignedlonglong : longlong;
+ if (Aflag >= 1)
+ warning("`%t' is a non-ANSI type\n", ty);
+ } else if (size == LONG)
+ ty = sign == UNSIGNED ? unsignedlong : longtype;
+ else if (sign == UNSIGNED && type == INT)
+ ty = unsignedtype;
+ if (cons == CONST)
+ ty = qual(CONST, ty);
+ if (vol == VOLATILE)
+ ty = qual(VOLATILE, ty);
+ return ty;
+}
+static void decl(Symbol (*dcl)(int, char *, Type, Coordinate *)) {
+ int sclass;
+ Type ty, ty1;
+ static char stop[] = { CHAR, STATIC, ID, 0 };
+
+ ty = specifier(&sclass);
+ if (t == ID || t == '*' || t == '(' || t == '[') {
+ char *id;
+ Coordinate pos;
+ id = NULL;
+ pos = src;
+ if (level == GLOBAL) {
+ Symbol *params = NULL;
+ ty1 = dclr(ty, &id, &params, 0);
+ if (params && id && isfunc(ty1)
+ && (t == '{' || istypename(t, tsym)
+ || (kind[t] == STATIC && t != TYPEDEF))) {
+ if (sclass == TYPEDEF) {
+ error("invalid use of `typedef'\n");
+ sclass = EXTERN;
+ }
+ if (ty1->u.f.oldstyle)
+ exitscope();
+ funcdefn(sclass, id, ty1, params, pos);
+ return;
+ } else if (params)
+ exitparams(params);
+ } else
+ ty1 = dclr(ty, &id, NULL, 0);
+ for (;;) {
+ if (Aflag >= 1 && !hasproto(ty1))
+ warning("missing prototype\n");
+ if (id == NULL)
+ error("missing identifier\n");
+ else if (sclass == TYPEDEF)
+ {
+ Symbol p = lookup(id, identifiers);
+ if (p && p->scope == level)
+ error("redeclaration of `%s'\n", id);
+ p = install(id, &identifiers, level,
+ level < LOCAL ? PERM : FUNC);
+ p->type = ty1;
+ p->sclass = TYPEDEF;
+ p->src = pos;
+ }
+ else
+ (void)(*dcl)(sclass, id, ty1, &pos);
+ if (t != ',')
+ break;
+ t = gettok();
+ id = NULL;
+ pos = src;
+ ty1 = dclr(ty, &id, NULL, 0);
+ }
+ } else if (ty == NULL
+ || !(isenum(ty) ||
+ isstruct(ty) && (*unqual(ty)->u.sym->name < '1' || *unqual(ty)->u.sym->name > '9')))
+ error("empty declaration\n");
+ test(';', stop);
+}
+static Symbol dclglobal(int sclass, char *id, Type ty, Coordinate *pos) {
+ Symbol p;
+
+ if (sclass == 0)
+ sclass = AUTO;
+ else if (sclass != EXTERN && sclass != STATIC) {
+ error("invalid storage class `%k' for `%t %s'\n",
+ sclass, ty, id);
+ sclass = AUTO;
+ }
+ p = lookup(id, identifiers);
+ if (p && p->scope == GLOBAL) {
+ if (p->sclass != TYPEDEF && eqtype(ty, p->type, 1))
+ ty = compose(ty, p->type);
+ else
+ error("redeclaration of `%s' previously declared at %w\n", p->name, &p->src);
+
+ if (!isfunc(ty) && p->defined && t == '=')
+ error("redefinition of `%s' previously defined at %w\n", p->name, &p->src);
+
+ if (p->sclass == EXTERN && sclass == STATIC
+ || p->sclass == STATIC && sclass == AUTO
+ || p->sclass == AUTO && sclass == STATIC)
+ warning("inconsistent linkage for `%s' previously declared at %w\n", p->name, &p->src);
+
+ }
+ if (p == NULL || p->scope != GLOBAL) {
+ Symbol q = lookup(id, externals);
+ if (q) {
+ if (sclass == STATIC || !eqtype(ty, q->type, 1))
+ warning("declaration of `%s' does not match previous declaration at %w\n", id, &q->src);
+
+ p = relocate(id, externals, globals);
+ p->sclass = sclass;
+ } else {
+ p = install(id, &globals, GLOBAL, PERM);
+ p->sclass = sclass;
+ (*IR->defsymbol)(p);
+ }
+ if (p->sclass != STATIC) {
+ static int nglobals;
+ nglobals++;
+ if (Aflag >= 2 && nglobals == 512)
+ warning("more than 511 external identifiers\n");
+ }
+ } else if (p->sclass == EXTERN)
+ p->sclass = sclass;
+ p->type = ty;
+ p->src = *pos;
+ if (t == '=' && isfunc(p->type)) {
+ error("illegal initialization for `%s'\n", p->name);
+ t = gettok();
+ initializer(p->type, 0);
+ } else if (t == '=') {
+ initglobal(p, 0);
+ if (glevel > 0 && IR->stabsym) {
+ (*IR->stabsym)(p); swtoseg(p->u.seg); }
+ } else if (p->sclass == STATIC && !isfunc(p->type)
+ && p->type->size == 0)
+ error("undefined size for `%t %s'\n", p->type, p->name);
+ return p;
+}
+static void initglobal(Symbol p, int flag) {
+ Type ty;
+
+ if (t == '=' || flag) {
+ if (p->sclass == STATIC) {
+ for (ty = p->type; isarray(ty); ty = ty->type)
+ ;
+ defglobal(p, isconst(ty) ? LIT : DATA);
+ } else
+ defglobal(p, DATA);
+ if (t == '=')
+ t = gettok();
+ ty = initializer(p->type, 0);
+ if (isarray(p->type) && p->type->size == 0)
+ p->type = ty;
+ if (p->sclass == EXTERN)
+ p->sclass = AUTO;
+ }
+}
+void defglobal(Symbol p, int seg) {
+ p->u.seg = seg;
+ swtoseg(p->u.seg);
+ if (p->sclass != STATIC)
+ (*IR->export)(p);
+ (*IR->global)(p);
+ p->defined = 1;
+}
+
+static Type dclr(Type basety, char **id, Symbol **params, int abstract) {
+ Type ty = dclr1(id, params, abstract);
+
+ for ( ; ty; ty = ty->type)
+ switch (ty->op) {
+ case POINTER:
+ basety = ptr(basety);
+ break;
+ case FUNCTION:
+ basety = func(basety, ty->u.f.proto,
+ ty->u.f.oldstyle);
+ break;
+ case ARRAY:
+ basety = array(basety, ty->size, 0);
+ break;
+ case CONST: case VOLATILE:
+ basety = qual(ty->op, basety);
+ break;
+ default: assert(0);
+ }
+ if (Aflag >= 2 && basety->size > 32767)
+ warning("more than 32767 bytes in `%t'\n", basety);
+ return basety;
+}
+static Type tnode(int op, Type type) {
+ Type ty;
+
+ NEW0(ty, STMT);
+ ty->op = op;
+ ty->type = type;
+ return ty;
+}
+static Type dclr1(char **id, Symbol **params, int abstract) {
+ Type ty = NULL;
+
+ switch (t) {
+ case ID: if (id)
+ *id = token;
+ else
+ error("extraneous identifier `%s'\n", token);
+ t = gettok(); break;
+ case '*': t = gettok(); if (t == CONST || t == VOLATILE) {
+ Type ty1;
+ ty1 = ty = tnode(t, NULL);
+ while ((t = gettok()) == CONST || t == VOLATILE)
+ ty1 = tnode(t, ty1);
+ ty->type = dclr1(id, params, abstract);
+ ty = ty1;
+ } else
+ ty = dclr1(id, params, abstract);
+ ty = tnode(POINTER, ty); break;
+ case '(': t = gettok(); if (abstract
+ && (t == REGISTER || istypename(t, tsym) || t == ')')) {
+ Symbol *args;
+ ty = tnode(FUNCTION, ty);
+ enterscope();
+ if (level > PARAM)
+ enterscope();
+ args = parameters(ty);
+ exitparams(args);
+ } else {
+ ty = dclr1(id, params, abstract);
+ expect(')');
+ if (abstract && ty == NULL
+ && (id == NULL || *id == NULL))
+ return tnode(FUNCTION, NULL);
+ } break;
+ case '[': break;
+ default: return ty;
+ }
+ while (t == '(' || t == '[')
+ switch (t) {
+ case '(': t = gettok(); { Symbol *args;
+ ty = tnode(FUNCTION, ty);
+ enterscope();
+ if (level > PARAM)
+ enterscope();
+ args = parameters(ty);
+ if (params && *params == NULL)
+ *params = args;
+ else
+ exitparams(args);
+ }
+ break;
+ case '[': t = gettok(); { int n = 0;
+ if (kind[t] == ID) {
+ n = intexpr(']', 1);
+ if (n <= 0) {
+ error("`%d' is an illegal array size\n", n);
+ n = 1;
+ }
+ } else
+ expect(']');
+ ty = tnode(ARRAY, ty);
+ ty->size = n; } break;
+ default: assert(0);
+ }
+ return ty;
+}
+static Symbol *parameters(Type fty) {
+ List list = NULL;
+ Symbol *params;
+
+ if (kind[t] == STATIC || istypename(t, tsym)) {
+ int n = 0;
+ Type ty1 = NULL;
+ for (;;) {
+ Type ty;
+ int sclass = 0;
+ char *id = NULL;
+ if (ty1 && t == ELLIPSIS) {
+ static struct symbol sentinel;
+ if (sentinel.type == NULL) {
+ sentinel.type = voidtype;
+ sentinel.defined = 1;
+ }
+ if (ty1 == voidtype)
+ error("illegal formal parameter types\n");
+ list = append(&sentinel, list);
+ t = gettok();
+ break;
+ }
+ if (!istypename(t, tsym) && t != REGISTER)
+ error("missing parameter type\n");
+ n++;
+ ty = dclr(specifier(&sclass), &id, NULL, 1);
+ if ( ty == voidtype && (ty1 || id)
+ || ty1 == voidtype)
+ error("illegal formal parameter types\n");
+ if (id == NULL)
+ id = stringd(n);
+ if (ty != voidtype)
+ list = append(dclparam(sclass, id, ty, &src), list);
+ if (Aflag >= 1 && !hasproto(ty))
+ warning("missing prototype\n");
+ if (ty1 == NULL)
+ ty1 = ty;
+ if (t != ',')
+ break;
+ t = gettok();
+ }
+ fty->u.f.proto = newarray(length(list) + 1,
+ sizeof (Type *), PERM);
+ params = ltov(&list, FUNC);
+ for (n = 0; params[n]; n++)
+ fty->u.f.proto[n] = params[n]->type;
+ fty->u.f.proto[n] = NULL;
+ fty->u.f.oldstyle = 0;
+ } else {
+ if (t == ID)
+ for (;;) {
+ Symbol p;
+ if (t != ID) {
+ error("expecting an identifier\n");
+ break;
+ }
+ p = dclparam(0, token, inttype, &src);
+ p->defined = 0;
+ list = append(p, list);
+ t = gettok();
+ if (t != ',')
+ break;
+ t = gettok();
+ }
+ params = ltov(&list, FUNC);
+ fty->u.f.proto = NULL;
+ fty->u.f.oldstyle = 1;
+ }
+ if (t != ')') {
+ static char stop[] = { CHAR, STATIC, IF, ')', 0 };
+ expect(')');
+ skipto('{', stop);
+ }
+ if (t == ')')
+ t = gettok();
+ return params;
+}
+static void exitparams(Symbol params[]) {
+ assert(params);
+ if (params[0] && !params[0]->defined)
+ error("extraneous old-style parameter list\n");
+ if (level > PARAM)
+ exitscope();
+ exitscope();
+}
+
+static Symbol dclparam(int sclass, char *id, Type ty, Coordinate *pos) {
+ Symbol p;
+
+ if (isfunc(ty))
+ ty = ptr(ty);
+ else if (isarray(ty))
+ ty = atop(ty);
+ if (sclass == 0)
+ sclass = AUTO;
+ else if (sclass != REGISTER) {
+ error("invalid storage class `%k' for `%t%s\n",
+ sclass, ty, stringf(id ? " %s'" : "' parameter", id));
+ sclass = AUTO;
+ } else if (isvolatile(ty) || isstruct(ty)) {
+ warning("register declaration ignored for `%t%s\n",
+ ty, stringf(id ? " %s'" : "' parameter", id));
+ sclass = AUTO;
+ }
+
+ p = lookup(id, identifiers);
+ if (p && p->scope == level)
+ error("duplicate declaration for `%s' previously declared at %w\n", id, &p->src);
+
+ else
+ p = install(id, &identifiers, level, FUNC);
+ p->sclass = sclass;
+ p->src = *pos;
+ p->type = ty;
+ p->defined = 1;
+ if (t == '=') {
+ error("illegal initialization for parameter `%s'\n", id);
+ t = gettok();
+ (void)expr1(0);
+ }
+ return p;
+}
+static Type structdcl(int op) {
+ char *tag;
+ Type ty;
+ Symbol p;
+ Coordinate pos;
+
+ t = gettok();
+ pos = src;
+ if (t == ID) {
+ tag = token;
+ t = gettok();
+ } else
+ tag = "";
+ if (t == '{') {
+ static char stop[] = { IF, ',', 0 };
+ ty = newstruct(op, tag);
+ ty->u.sym->src = pos;
+ ty->u.sym->defined = 1;
+ t = gettok();
+ if (istypename(t, tsym))
+ fields(ty);
+ else
+ error("invalid %k field declarations\n", op);
+ test('}', stop);
+ }
+ else if (*tag && (p = lookup(tag, types)) != NULL
+ && p->type->op == op) {
+ ty = p->type;
+ if (t == ';' && p->scope < level)
+ ty = newstruct(op, tag);
+ }
+ else {
+ if (*tag == 0)
+ error("missing %k tag\n", op);
+ ty = newstruct(op, tag);
+ }
+ if (*tag && xref)
+ use(ty->u.sym, pos);
+ return ty;
+}
+static void fields(Type ty) {
+ { int n = 0;
+ while (istypename(t, tsym)) {
+ static char stop[] = { IF, CHAR, '}', 0 };
+ Type ty1 = specifier(NULL);
+ for (;;) {
+ Field p;
+ char *id = NULL;
+ Type fty = dclr(ty1, &id, NULL, 0);
+ p = newfield(id, ty, fty);
+ if (Aflag >= 1 && !hasproto(p->type))
+ warning("missing prototype\n");
+ if (t == ':') {
+ if (unqual(p->type) != inttype
+ && unqual(p->type) != unsignedtype) {
+ error("`%t' is an illegal bit-field type\n",
+ p->type);
+ p->type = inttype;
+ }
+ t = gettok();
+ p->bitsize = intexpr(0, 0);
+ if (p->bitsize > 8*inttype->size || p->bitsize < 0) {
+ error("`%d' is an illegal bit-field size\n",
+ p->bitsize);
+ p->bitsize = 8*inttype->size;
+ } else if (p->bitsize == 0 && id) {
+ warning("extraneous 0-width bit field `%t %s' ignored\n", p->type, id);
+
+ p->name = stringd(genlabel(1));
+ }
+ p->lsb = 1;
+ }
+ else {
+ if (id == NULL)
+ error("field name missing\n");
+ else if (isfunc(p->type))
+ error("`%t' is an illegal field type\n", p->type);
+ else if (p->type->size == 0)
+ error("undefined size for field `%t %s'\n",
+ p->type, id);
+ }
+ if (isconst(p->type))
+ ty->u.sym->u.s.cfields = 1;
+ if (isvolatile(p->type))
+ ty->u.sym->u.s.vfields = 1;
+ n++;
+ if (Aflag >= 2 && n == 128)
+ warning("more than 127 fields in `%t'\n", ty);
+ if (t != ',')
+ break;
+ t = gettok();
+ }
+ test(';', stop);
+ } }
+ { int bits = 0, off = 0, overflow = 0;
+ Field p, *q = &ty->u.sym->u.s.flist;
+ ty->align = IR->structmetric.align;
+ for (p = *q; p; p = p->link) {
+ int a = p->type->align ? p->type->align : 1;
+ if (p->lsb)
+ a = unsignedtype->align;
+ if (ty->op == UNION)
+ off = bits = 0;
+ else if (p->bitsize == 0 || bits == 0
+ || bits - 1 + p->bitsize > 8*unsignedtype->size) {
+ off = add(off, bits2bytes(bits-1));
+ bits = 0;
+ chkoverflow(off, a - 1);
+ off = roundup(off, a);
+ }
+ if (a > ty->align)
+ ty->align = a;
+ p->offset = off;
+
+ if (p->lsb) {
+ if (bits == 0)
+ bits = 1;
+ if (IR->little_endian)
+ p->lsb = bits;
+ else
+ p->lsb = 8*unsignedtype->size - bits + 1
+ - p->bitsize + 1;
+ bits += p->bitsize;
+ } else
+ off = add(off, p->type->size);
+ if (off + bits2bytes(bits-1) > ty->size)
+ ty->size = off + bits2bytes(bits-1);
+ if (p->name == NULL
+ || !('1' <= *p->name && *p->name <= '9')) {
+ *q = p;
+ q = &p->link;
+ }
+ }
+ *q = NULL;
+ chkoverflow(ty->size, ty->align - 1);
+ ty->size = roundup(ty->size, ty->align);
+ if (overflow) {
+ error("size of `%t' exceeds %d bytes\n", ty, inttype->u.sym->u.limits.max.i);
+ ty->size = inttype->u.sym->u.limits.max.i&(~(ty->align - 1));
+ } }
+}
+static void funcdefn(int sclass, char *id, Type ty, Symbol params[], Coordinate pt) {
+ int i, n;
+ Symbol *callee, *caller, p;
+ Type rty = freturn(ty);
+
+ if (isstruct(rty) && rty->size == 0)
+ error("illegal use of incomplete type `%t'\n", rty);
+ for (n = 0; params[n]; n++)
+ ;
+ if (n > 0 && params[n-1]->name == NULL)
+ params[--n] = NULL;
+ if (Aflag >= 2 && n > 31)
+ warning("more than 31 parameters in function `%s'\n", id);
+ if (ty->u.f.oldstyle) {
+ if (Aflag >= 1)
+ warning("old-style function definition for `%s'\n", id);
+ caller = params;
+ callee = newarray(n + 1, sizeof *callee, FUNC);
+ memcpy(callee, caller, (n+1)*sizeof *callee);
+ enterscope();
+ assert(level == PARAM);
+ while (kind[t] == STATIC || istypename(t, tsym))
+ decl(dclparam);
+ foreach(identifiers, PARAM, oldparam, callee);
+
+ for (i = 0; (p = callee[i]) != NULL; i++) {
+ if (!p->defined)
+ callee[i] = dclparam(0, p->name, inttype, &p->src);
+ *caller[i] = *p;
+ caller[i]->sclass = AUTO;
+ caller[i]->type = promote(p->type);
+ }
+ p = lookup(id, identifiers);
+ if (p && p->scope == GLOBAL && isfunc(p->type)
+ && p->type->u.f.proto) {
+ Type *proto = p->type->u.f.proto;
+ for (i = 0; caller[i] && proto[i]; i++) {
+ Type ty = unqual(proto[i]);
+ if (eqtype(isenum(ty) ? ty->type : ty,
+ unqual(caller[i]->type), 1) == 0)
+ break;
+ else if (isenum(ty) && !isenum(unqual(caller[i]->type)))
+ warning("compatibility of `%t' and `%t' is compiler dependent\n",
+ proto[i], caller[i]->type);
+ }
+ if (proto[i] || caller[i])
+ error("conflicting argument declarations for function `%s'\n", id);
+
+ }
+ else {
+ Type *proto = newarray(n + 1, sizeof *proto, PERM);
+ if (Aflag >= 1)
+ warning("missing prototype for `%s'\n", id);
+ for (i = 0; i < n; i++)
+ proto[i] = caller[i]->type;
+ proto[i] = NULL;
+ ty = func(rty, proto, 1);
+ }
+ } else {
+ callee = params;
+ caller = newarray(n + 1, sizeof *caller, FUNC);
+ for (i = 0; (p = callee[i]) != NULL && p->name; i++) {
+ NEW(caller[i], FUNC);
+ *caller[i] = *p;
+ if (isint(p->type))
+ caller[i]->type = promote(p->type);
+ caller[i]->sclass = AUTO;
+ if ('1' <= *p->name && *p->name <= '9')
+ error("missing name for parameter %d to function `%s'\n", i + 1, id);
+
+ }
+ caller[i] = NULL;
+ }
+ for (i = 0; (p = callee[i]) != NULL; i++)
+ if (p->type->size == 0) {
+ error("undefined size for parameter `%t %s'\n",
+ p->type, p->name);
+ caller[i]->type = p->type = inttype;
+ }
+ if (Aflag >= 2 && sclass != STATIC && strcmp(id, "main") == 0) {
+ if (ty->u.f.oldstyle)
+ warning("`%t %s()' is a non-ANSI definition\n", rty, id);
+ else if (!(rty == inttype
+ && (n == 0 && callee[0] == NULL
+ || n == 2 && callee[0]->type == inttype
+ && isptr(callee[1]->type) && callee[1]->type->type == charptype
+ && !variadic(ty))))
+ warning("`%s' is a non-ANSI definition\n", typestring(ty, id));
+ }
+ p = lookup(id, identifiers);
+ if (p && isfunc(p->type) && p->defined)
+ error("redefinition of `%s' previously defined at %w\n",
+ p->name, &p->src);
+ cfunc = dclglobal(sclass, id, ty, &pt);
+ cfunc->u.f.label = genlabel(1);
+ cfunc->u.f.callee = callee;
+ cfunc->u.f.pt = src;
+ cfunc->defined = 1;
+ if (xref)
+ use(cfunc, cfunc->src);
+ if (Pflag)
+ printproto(cfunc, cfunc->u.f.callee);
+ if (ncalled >= 0)
+ ncalled = findfunc(cfunc->name, pt.file);
+ labels = table(NULL, LABELS);
+ stmtlabs = table(NULL, LABELS);
+ refinc = 1.0;
+ regcount = 0;
+ codelist = &codehead;
+ codelist->next = NULL;
+ if (!IR->wants_callb && isstruct(rty))
+ retv = genident(AUTO, ptr(rty), PARAM);
+ compound(0, NULL, 0);
+
+ {
+ Code cp;
+ for (cp = codelist; cp->kind < Label; cp = cp->prev)
+ ;
+ if (cp->kind != Jump) {
+ if (rty != voidtype) {
+ warning("missing return value\n");
+ retcode(cnsttree(inttype, 0L));
+ } else
+ retcode(NULL);
+ }
+ }
+ definelab(cfunc->u.f.label);
+ if (events.exit)
+ apply(events.exit, cfunc, NULL);
+ walk(NULL, 0, 0);
+ exitscope();
+ assert(level == PARAM);
+ foreach(identifiers, level, checkref, NULL);
+ if (!IR->wants_callb && isstruct(rty)) {
+ Symbol *a;
+ a = newarray(n + 2, sizeof *a, FUNC);
+ a[0] = retv;
+ memcpy(&a[1], callee, (n+1)*sizeof *callee);
+ callee = a;
+ a = newarray(n + 2, sizeof *a, FUNC);
+ NEW(a[0], FUNC);
+ *a[0] = *retv;
+ memcpy(&a[1], caller, (n+1)*sizeof *callee);
+ caller = a;
+ }
+ if (!IR->wants_argb)
+ for (i = 0; caller[i]; i++)
+ if (isstruct(caller[i]->type)) {
+ caller[i]->type = ptr(caller[i]->type);
+ callee[i]->type = ptr(callee[i]->type);
+ caller[i]->structarg = callee[i]->structarg = 1;
+ }
+ if (glevel > 1) for (i = 0; callee[i]; i++) callee[i]->sclass = AUTO;
+ if (cfunc->sclass != STATIC)
+ (*IR->export)(cfunc);
+ if (glevel && IR->stabsym) {
+ swtoseg(CODE); (*IR->stabsym)(cfunc); }
+ swtoseg(CODE);
+ (*IR->function)(cfunc, caller, callee, cfunc->u.f.ncalls);
+ if (glevel && IR->stabfend)
+ (*IR->stabfend)(cfunc, lineno);
+ foreach(stmtlabs, LABELS, checklab, NULL);
+ exitscope();
+ expect('}');
+ labels = stmtlabs = NULL;
+ retv = NULL;
+ cfunc = NULL;
+}
+static void oldparam(Symbol p, void *cl) {
+ int i;
+ Symbol *callee = cl;
+
+ for (i = 0; callee[i]; i++)
+ if (p->name == callee[i]->name) {
+ callee[i] = p;
+ return;
+ }
+ error("declared parameter `%s' is missing\n", p->name);
+}
+void compound(int loop, struct swtch *swp, int lev) {
+ Code cp;
+ int nregs;
+
+ walk(NULL, 0, 0);
+ cp = code(Blockbeg);
+ enterscope();
+ assert(level >= LOCAL);
+ if (level == LOCAL && events.entry)
+ apply(events.entry, cfunc, NULL);
+ definept(NULL);
+ expect('{');
+ autos = registers = NULL;
+ if (level == LOCAL && IR->wants_callb
+ && isstruct(freturn(cfunc->type))) {
+ retv = genident(AUTO, ptr(freturn(cfunc->type)), level);
+ retv->defined = 1;
+ retv->ref = 1;
+ registers = append(retv, registers);
+ }
+ while (kind[t] == CHAR || kind[t] == STATIC
+ || istypename(t, tsym) && getchr() != ':')
+ decl(dcllocal);
+ {
+ int i;
+ Symbol *a = ltov(&autos, STMT);
+ nregs = length(registers);
+ for (i = 0; a[i]; i++)
+ registers = append(a[i], registers);
+ cp->u.block.locals = ltov(&registers, FUNC);
+ }
+ if (events.blockentry)
+ apply(events.blockentry, cp->u.block.locals, NULL);
+ while (kind[t] == IF || kind[t] == ID)
+ statement(loop, swp, lev);
+ walk(NULL, 0, 0);
+ foreach(identifiers, level, checkref, NULL);
+ {
+ int i = nregs, j;
+ Symbol p;
+ for ( ; (p = cp->u.block.locals[i]) != NULL; i++) {
+ for (j = i; j > nregs
+ && cp->u.block.locals[j-1]->ref < p->ref; j--)
+ cp->u.block.locals[j] = cp->u.block.locals[j-1];
+ cp->u.block.locals[j] = p;
+ }
+ }
+ if (events.blockexit)
+ apply(events.blockexit, cp->u.block.locals, NULL);
+ cp->u.block.level = level;
+ cp->u.block.identifiers = identifiers;
+ cp->u.block.types = types;
+ code(Blockend)->u.begin = cp;
+ if (reachable(Gen))
+ definept(NULL);
+ if (level > LOCAL) {
+ exitscope();
+ expect('}');
+ }
+}
+static void checkref(Symbol p, void *cl) {
+ if (p->scope >= PARAM
+ && (isvolatile(p->type) || isfunc(p->type)))
+ p->addressed = 1;
+ if (Aflag >= 2 && p->defined && p->ref == 0) {
+ if (p->sclass == STATIC)
+ warning("static `%t %s' is not referenced\n",
+ p->type, p->name);
+ else if (p->scope == PARAM)
+ warning("parameter `%t %s' is not referenced\n",
+ p->type, p->name);
+ else if (p->scope >= LOCAL && p->sclass != EXTERN)
+ warning("local `%t %s' is not referenced\n",
+ p->type, p->name);
+ }
+ if (p->sclass == AUTO
+ && (p->scope == PARAM && regcount == 0
+ || p->scope >= LOCAL)
+ && !p->addressed && isscalar(p->type) && p->ref >= 3.0)
+ p->sclass = REGISTER;
+ if (level == GLOBAL && p->sclass == STATIC && !p->defined
+ && isfunc(p->type) && p->ref)
+ error("undefined static `%t %s'\n", p->type, p->name);
+ assert(!(level == GLOBAL && p->sclass == STATIC && !p->defined && !isfunc(p->type)));
+}
+static Symbol dcllocal(int sclass, char *id, Type ty, Coordinate *pos) {
+ Symbol p, q;
+
+ if (sclass == 0)
+ sclass = isfunc(ty) ? EXTERN : AUTO;
+ else if (isfunc(ty) && sclass != EXTERN) {
+ error("invalid storage class `%k' for `%t %s'\n",
+ sclass, ty, id);
+ sclass = EXTERN;
+ } else if (sclass == REGISTER
+ && (isvolatile(ty) || isstruct(ty) || isarray(ty))) {
+ warning("register declaration ignored for `%t %s'\n",
+ ty, id);
+ sclass = AUTO;
+ }
+ q = lookup(id, identifiers);
+ if (q && q->scope >= level
+ || q && q->scope == PARAM && level == LOCAL)
+ if (sclass == EXTERN && q->sclass == EXTERN
+ && eqtype(q->type, ty, 1))
+ ty = compose(ty, q->type);
+ else
+ error("redeclaration of `%s' previously declared at %w\n", q->name, &q->src);
+
+ assert(level >= LOCAL);
+ p = install(id, &identifiers, level, sclass == STATIC || sclass == EXTERN ? PERM : FUNC);
+ p->type = ty;
+ p->sclass = sclass;
+ p->src = *pos;
+ switch (sclass) {
+ case EXTERN: q = lookup(id, globals);
+ if (q == NULL || q->sclass == TYPEDEF || q->sclass == ENUM) {
+ q = lookup(id, externals);
+ if (q == NULL) {
+ q = install(p->name, &externals, GLOBAL, PERM);
+ q->type = p->type;
+ q->sclass = EXTERN;
+ q->src = src;
+ (*IR->defsymbol)(q);
+ }
+ }
+ if (!eqtype(p->type, q->type, 1))
+ warning("declaration of `%s' does not match previous declaration at %w\n", q->name, &q->src);
+
+ p->u.alias = q; break;
+ case STATIC: (*IR->defsymbol)(p);
+ initglobal(p, 0);
+ if (!p->defined)
+ if (p->type->size > 0) {
+ defglobal(p, BSS);
+ (*IR->space)(p->type->size);
+ } else
+ error("undefined size for `%t %s'\n",
+ p->type, p->name);
+ p->defined = 1; break;
+ case REGISTER: registers = append(p, registers);
+ regcount++;
+ p->defined = 1;
+ break;
+ case AUTO: autos = append(p, autos);
+ p->defined = 1; break;
+ default: assert(0);
+ }
+ if (t == '=') {
+ Tree e;
+ if (sclass == EXTERN)
+ error("illegal initialization of `extern %s'\n", id);
+ t = gettok();
+ definept(NULL);
+ if (isscalar(p->type)
+ || isstruct(p->type) && t != '{') {
+ if (t == '{') {
+ t = gettok();
+ e = expr1(0);
+ expect('}');
+ } else
+ e = expr1(0);
+ } else {
+ Symbol t1;
+ Type ty = p->type, ty1 = ty;
+ while (isarray(ty1))
+ ty1 = ty1->type;
+ if (!isconst(ty) && (!isarray(ty) || !isconst(ty1)))
+ ty = qual(CONST, ty);
+ t1 = genident(STATIC, ty, GLOBAL);
+ initglobal(t1, 1);
+ if (isarray(p->type) && p->type->size == 0
+ && t1->type->size > 0)
+ p->type = array(p->type->type,
+ t1->type->size/t1->type->type->size, 0);
+ e = idtree(t1);
+ }
+ walk(root(asgn(p, e)), 0, 0);
+ p->ref = 1;
+ }
+ if (!isfunc(p->type) && p->defined && p->type->size <= 0)
+ error("undefined size for `%t %s'\n", p->type, id);
+ return p;
+}
+void finalize(void) {
+ foreach(externals, GLOBAL, doextern, NULL);
+ foreach(identifiers, GLOBAL, doglobal, NULL);
+ foreach(identifiers, GLOBAL, checkref, NULL);
+ foreach(constants, CONSTANTS, doconst, NULL);
+}
+static void doextern(Symbol p, void *cl) {
+ (*IR->import)(p);
+}
+static void doglobal(Symbol p, void *cl) {
+ if (!p->defined && (p->sclass == EXTERN
+ || isfunc(p->type) && p->sclass == AUTO))
+ (*IR->import)(p);
+ else if (!p->defined && !isfunc(p->type)
+ && (p->sclass == AUTO || p->sclass == STATIC)) {
+ if (isarray(p->type)
+ && p->type->size == 0 && p->type->type->size > 0)
+ p->type = array(p->type->type, 1, 0);
+ if (p->type->size > 0) {
+ defglobal(p, BSS);
+ (*IR->space)(p->type->size);
+ if (glevel > 0 && IR->stabsym)
+ (*IR->stabsym)(p);
+ } else
+ error("undefined size for `%t %s'\n",
+ p->type, p->name);
+ p->defined = 1;
+ }
+ if (Pflag
+ && !isfunc(p->type)
+ && !p->generated && p->sclass != EXTERN)
+ printdecl(p, p->type);
+}
+void doconst(Symbol p, void *cl) {
+ if (p->u.c.loc) {
+ assert(p->u.c.loc->u.seg == 0);
+ defglobal(p->u.c.loc, LIT);
+ if (isarray(p->type) && p->type->type == widechar) {
+ unsigned int *s = p->u.c.v.p;
+ int n = p->type->size/widechar->size;
+ while (n-- > 0) {
+ Value v;
+ v.u = *s++;
+ (*IR->defconst)(widechar->op, widechar->size, v);
+ }
+ } else if (isarray(p->type))
+ (*IR->defstring)(p->type->size, p->u.c.v.p);
+ else
+ (*IR->defconst)(p->type->op, p->type->size, p->u.c.v);
+ p->u.c.loc = NULL;
+ }
+}
+void checklab(Symbol p, void *cl) {
+ if (!p->defined)
+ error("undefined label `%s'\n", p->name);
+ p->defined = 1;
+}
+
+Type enumdcl(void) {
+ char *tag;
+ Type ty;
+ Symbol p;
+ Coordinate pos;
+
+ t = gettok();
+ pos = src;
+ if (t == ID) {
+ tag = token;
+ t = gettok();
+ } else
+ tag = "";
+ if (t == '{') {
+ static char follow[] = { IF, 0 };
+ int n = 0;
+ long k = -1;
+ List idlist = 0;
+ ty = newstruct(ENUM, tag);
+ t = gettok();
+ if (t != ID)
+ error("expecting an enumerator identifier\n");
+ while (t == ID) {
+ char *id = token;
+ Coordinate s;
+ if (tsym && tsym->scope == level)
+ error("redeclaration of `%s' previously declared at %w\n",
+ token, &tsym->src);
+ s = src;
+ t = gettok();
+ if (t == '=') {
+ t = gettok();
+ k = intexpr(0, 0);
+ } else {
+ if (k == inttype->u.sym->u.limits.max.i)
+ error("overflow in value for enumeration constant `%s'\n", id);
+ k++;
+ }
+ p = install(id, &identifiers, level, level < LOCAL ? PERM : FUNC);
+ p->src = s;
+ p->type = ty;
+ p->sclass = ENUM;
+ p->u.value = k;
+ idlist = append(p, idlist);
+ n++;
+ if (Aflag >= 2 && n == 128)
+ warning("more than 127 enumeration constants in `%t'\n", ty);
+ if (t != ',')
+ break;
+ t = gettok();
+ if (Aflag >= 2 && t == '}')
+ warning("non-ANSI trailing comma in enumerator list\n");
+ }
+ test('}', follow);
+ ty->type = inttype;
+ ty->size = ty->type->size;
+ ty->align = ty->type->align;
+ ty->u.sym->u.idlist = ltov(&idlist, PERM);
+ ty->u.sym->defined = 1;
+ } else if ((p = lookup(tag, types)) != NULL && p->type->op == ENUM) {
+ ty = p->type;
+ if (t == ';')
+ error("empty declaration\n");
+ } else {
+ error("unknown enumeration `%s'\n", tag);
+ ty = newstruct(ENUM, tag);
+ ty->type = inttype;
+ }
+ if (*tag && xref)
+ use(p, pos);
+ return ty;
+}
+
+Type typename(void) {
+ Type ty = specifier(NULL);
+
+ if (t == '*' || t == '(' || t == '[') {
+ ty = dclr(ty, NULL, NULL, 1);
+ if (Aflag >= 1 && !hasproto(ty))
+ warning("missing prototype\n");
+ }
+ return ty;
+}
+
diff --git a/lcc/src/enode.c b/lcc/src/enode.c
new file mode 100755
index 0000000..a81c632
--- /dev/null
+++ b/lcc/src/enode.c
@@ -0,0 +1,543 @@
+#include "c.h"
+
+
+static Tree addtree(int, Tree, Tree);
+static Tree andtree(int, Tree, Tree);
+static Tree cmptree(int, Tree, Tree);
+static int compatible(Type, Type);
+static int isnullptr(Tree e);
+static Tree multree(int, Tree, Tree);
+static Tree subtree(int, Tree, Tree);
+#define isvoidptr(ty) \
+ (isptr(ty) && unqual(ty->type) == voidtype)
+
+Tree (*optree[])(int, Tree, Tree) = {
+#define xx(a,b,c,d,e,f,g) e,
+#define yy(a,b,c,d,e,f,g) e,
+#include "token.h"
+};
+Tree call(Tree f, Type fty, Coordinate src) {
+ int n = 0;
+ Tree args = NULL, r = NULL, e;
+ Type *proto, rty = unqual(freturn(fty));
+ Symbol t3 = NULL;
+
+ if (fty->u.f.oldstyle)
+ proto = NULL;
+ else
+ proto = fty->u.f.proto;
+ if (hascall(f))
+ r = f;
+ if (isstruct(rty))
+ {
+ t3 = temporary(AUTO, unqual(rty));
+ if (rty->size == 0)
+ error("illegal use of incomplete type `%t'\n", rty);
+ }
+ if (t != ')')
+ for (;;) {
+ Tree q = pointer(expr1(0));
+ if (proto && *proto && *proto != voidtype)
+ {
+ Type aty;
+ q = value(q);
+ aty = assign(*proto, q);
+ if (aty)
+ q = cast(q, aty);
+ else
+ error("type error in argument %d to %s; found `%t' expected `%t'\n", n + 1, funcname(f),
+
+ q->type, *proto);
+ if ((isint(q->type) || isenum(q->type))
+ && q->type->size != inttype->size)
+ q = cast(q, promote(q->type));
+ ++proto;
+ }
+ else
+ {
+ if (!fty->u.f.oldstyle && *proto == NULL)
+ error("too many arguments to %s\n", funcname(f));
+ q = value(q);
+ if (isarray(q->type) || q->type->size == 0)
+ error("type error in argument %d to %s; `%t' is illegal\n", n + 1, funcname(f), q->type);
+
+ else
+ q = cast(q, promote(q->type));
+ }
+ if (!IR->wants_argb && isstruct(q->type))
+ if (iscallb(q))
+ q = addrof(q);
+ else {
+ Symbol t1 = temporary(AUTO, unqual(q->type));
+ q = asgn(t1, q);
+ q = tree(RIGHT, ptr(t1->type),
+ root(q), lvalue(idtree(t1)));
+ }
+ if (q->type->size == 0)
+ q->type = inttype;
+ if (hascall(q))
+ r = r ? tree(RIGHT, voidtype, r, q) : q;
+ args = tree(mkop(ARG, q->type), q->type, q, args);
+ n++;
+ if (Aflag >= 2 && n == 32)
+ warning("more than 31 arguments in a call to %s\n",
+ funcname(f));
+ if (t != ',')
+ break;
+ t = gettok();
+ }
+ expect(')');
+ if (proto && *proto && *proto != voidtype)
+ error("insufficient number of arguments to %s\n",
+ funcname(f));
+ if (r)
+ args = tree(RIGHT, voidtype, r, args);
+ e = calltree(f, rty, args, t3);
+ if (events.calls)
+ apply(events.calls, &src, &e);
+ return e;
+}
+Tree calltree(Tree f, Type ty, Tree args, Symbol t3) {
+ Tree p;
+
+ if (args)
+ f = tree(RIGHT, f->type, args, f);
+ if (isstruct(ty))
+ assert(t3),
+ p = tree(RIGHT, ty,
+ tree(CALL+B, ty, f, addrof(idtree(t3))),
+ idtree(t3));
+ else {
+ Type rty = ty;
+ if (isenum(ty))
+ rty = unqual(ty)->type;
+ if (!isfloat(rty))
+ rty = promote(rty);
+ p = tree(mkop(CALL, rty), rty, f, NULL);
+ if (isptr(ty) || p->type->size > ty->size)
+ p = cast(p, ty);
+ }
+ return p;
+}
+Tree vcall(Symbol func, Type ty, ...) {
+ va_list ap;
+ Tree args = NULL, e, f = pointer(idtree(func)), r = NULL;
+
+ assert(isfunc(func->type));
+ if (ty == NULL)
+ ty = freturn(func->type);
+ va_start(ap, ty);
+ while ((e = va_arg(ap, Tree)) != NULL) {
+ if (hascall(e))
+ r = r == NULL ? e : tree(RIGHT, voidtype, r, e);
+ args = tree(mkop(ARG, e->type), e->type, e, args);
+ }
+ va_end(ap);
+ if (r != NULL)
+ args = tree(RIGHT, voidtype, r, args);
+ return calltree(f, ty, args, NULL);
+}
+int iscallb(Tree e) {
+ return e->op == RIGHT && e->kids[0] && e->kids[1]
+ && e->kids[0]->op == CALL+B
+ && e->kids[1]->op == INDIR+B
+ && isaddrop(e->kids[1]->kids[0]->op)
+ && e->kids[1]->kids[0]->u.sym->temporary;
+}
+
+static Tree addtree(int op, Tree l, Tree r) {
+ Type ty = inttype;
+
+ if (isarith(l->type) && isarith(r->type)) {
+ ty = binary(l->type, r->type);
+ l = cast(l, ty);
+ r = cast(r, ty);
+ } else if (isptr(l->type) && isint(r->type))
+ return addtree(ADD, r, l);
+ else if ( isptr(r->type) && isint(l->type)
+ && !isfunc(r->type->type))
+ {
+ long n;
+ ty = unqual(r->type);
+ n = unqual(ty->type)->size;
+ if (n == 0)
+ error("unknown size for type `%t'\n", ty->type);
+ l = cast(l, promote(l->type));
+ if (n > 1)
+ l = multree(MUL, cnsttree(signedptr, n), l);
+ if (YYcheck && !isaddrop(r->op)) /* omit */
+ return nullcall(ty, YYcheck, r, l); /* omit */
+ return simplify(ADD, ty, l, r);
+ }
+
+ else
+ typeerror(op, l, r);
+ return simplify(op, ty, l, r);
+}
+
+Tree cnsttree(Type ty, ...) {
+ Tree p = tree(mkop(CNST,ty), ty, NULL, NULL);
+ va_list ap;
+
+ va_start(ap, ty);
+ switch (ty->op) {
+ case INT: p->u.v.i = va_arg(ap, long); break;
+ case UNSIGNED:p->u.v.u = va_arg(ap, unsigned long)&ones(8*ty->size); break;
+ case FLOAT: p->u.v.d = va_arg(ap, long double); break;
+ case POINTER: p->u.v.p = va_arg(ap, void *); break;
+ default: assert(0);
+ }
+ va_end(ap);
+ return p;
+}
+
+Tree consttree(unsigned n, Type ty) {
+ if (isarray(ty))
+ ty = atop(ty);
+ else assert(isint(ty));
+ return cnsttree(ty, (unsigned long)n);
+}
+static Tree cmptree(int op, Tree l, Tree r) {
+ Type ty;
+
+ if (isarith(l->type) && isarith(r->type)) {
+ ty = binary(l->type, r->type);
+ l = cast(l, ty);
+ r = cast(r, ty);
+ } else if (compatible(l->type, r->type)) {
+ ty = unsignedptr;
+ l = cast(l, ty);
+ r = cast(r, ty);
+ } else {
+ ty = unsignedtype;
+ typeerror(op, l, r);
+ }
+ return simplify(mkop(op,ty), inttype, l, r);
+}
+static int compatible(Type ty1, Type ty2) {
+ return isptr(ty1) && !isfunc(ty1->type)
+ && isptr(ty2) && !isfunc(ty2->type)
+ && eqtype(unqual(ty1->type), unqual(ty2->type), 0);
+}
+static int isnullptr(Tree e) {
+ Type ty = unqual(e->type);
+
+ return generic(e->op) == CNST
+ && (ty->op == INT && e->u.v.i == 0
+ || ty->op == UNSIGNED && e->u.v.u == 0
+ || isvoidptr(ty) && e->u.v.p == NULL);
+}
+Tree eqtree(int op, Tree l, Tree r) {
+ Type xty = l->type, yty = r->type;
+
+ if (isptr(xty) && isnullptr(r)
+ || isptr(xty) && !isfunc(xty->type) && isvoidptr(yty)
+ || (isptr(xty) && isptr(yty)
+ && eqtype(unqual(xty->type), unqual(yty->type), 1))) {
+ Type ty = unsignedptr;
+ l = cast(l, ty);
+ r = cast(r, ty);
+ return simplify(mkop(op,ty), inttype, l, r);
+ }
+ if (isptr(yty) && isnullptr(l)
+ || isptr(yty) && !isfunc(yty->type) && isvoidptr(xty))
+ return eqtree(op, r, l);
+ return cmptree(op, l, r);
+}
+
+Type assign(Type xty, Tree e) {
+ Type yty = unqual(e->type);
+
+ xty = unqual(xty);
+ if (isenum(xty))
+ xty = xty->type;
+ if (xty->size == 0 || yty->size == 0)
+ return NULL;
+ if ( isarith(xty) && isarith(yty)
+ || isstruct(xty) && xty == yty)
+ return xty;
+ if (isptr(xty) && isnullptr(e))
+ return xty;
+ if ((isvoidptr(xty) && isptr(yty)
+ || isptr(xty) && isvoidptr(yty))
+ && ( (isconst(xty->type) || !isconst(yty->type))
+ && (isvolatile(xty->type) || !isvolatile(yty->type))))
+ return xty;
+
+ if ((isptr(xty) && isptr(yty)
+ && eqtype(unqual(xty->type), unqual(yty->type), 1))
+ && ( (isconst(xty->type) || !isconst(yty->type))
+ && (isvolatile(xty->type) || !isvolatile(yty->type))))
+ return xty;
+ if (isptr(xty) && isptr(yty)
+ && ( (isconst(xty->type) || !isconst(yty->type))
+ && (isvolatile(xty->type) || !isvolatile(yty->type)))) {
+ Type lty = unqual(xty->type), rty = unqual(yty->type);
+ if (isenum(lty) && rty == inttype
+ || isenum(rty) && lty == inttype) {
+ if (Aflag >= 1)
+ warning("assignment between `%t' and `%t' is compiler-dependent\n",
+ xty, yty);
+ return xty;
+ }
+ }
+ return NULL;
+}
+Tree asgntree(int op, Tree l, Tree r) {
+ Type aty, ty;
+
+ r = pointer(r);
+ ty = assign(l->type, r);
+ if (ty)
+ r = cast(r, ty);
+ else {
+ typeerror(ASGN, l, r);
+ if (r->type == voidtype)
+ r = retype(r, inttype);
+ ty = r->type;
+ }
+ if (l->op != FIELD)
+ l = lvalue(l);
+ aty = l->type;
+ if (isptr(aty))
+ aty = unqual(aty)->type;
+ if ( isconst(aty)
+ || isstruct(aty) && unqual(aty)->u.sym->u.s.cfields)
+ if (isaddrop(l->op)
+ && !l->u.sym->computed && !l->u.sym->generated)
+ error("assignment to const identifier `%s'\n",
+ l->u.sym->name);
+ else
+ error("assignment to const location\n");
+ if (l->op == FIELD) {
+ long n = 8*l->u.field->type->size - fieldsize(l->u.field);
+ if (n > 0 && isunsigned(l->u.field->type))
+ r = bittree(BAND, r,
+ cnsttree(r->type, (unsigned long)fieldmask(l->u.field)));
+ else if (n > 0) {
+ if (r->op == CNST+I) {
+ n = r->u.v.i;
+ if (n&(1<<(fieldsize(l->u.field)-1)))
+ n |= ~0UL<<fieldsize(l->u.field);
+ r = cnsttree(r->type, n);
+ } else
+ r = shtree(RSH,
+ shtree(LSH, r, cnsttree(inttype, n)),
+ cnsttree(inttype, n));
+ }
+ }
+ if (isstruct(ty) && isaddrop(l->op) && iscallb(r))
+ return tree(RIGHT, ty,
+ tree(CALL+B, ty, r->kids[0]->kids[0], l),
+ idtree(l->u.sym));
+ return tree(mkop(op,ty), ty, l, r);
+}
+Tree condtree(Tree e, Tree l, Tree r) {
+ Symbol t1;
+ Type ty, xty = l->type, yty = r->type;
+ Tree p;
+
+ if (isarith(xty) && isarith(yty))
+ ty = binary(xty, yty);
+ else if (eqtype(xty, yty, 1))
+ ty = unqual(xty);
+ else if (isptr(xty) && isnullptr(r))
+ ty = xty;
+ else if (isnullptr(l) && isptr(yty))
+ ty = yty;
+ else if (isptr(xty) && !isfunc(xty->type) && isvoidptr(yty)
+ || isptr(yty) && !isfunc(yty->type) && isvoidptr(xty))
+ ty = voidptype;
+ else if ((isptr(xty) && isptr(yty)
+ && eqtype(unqual(xty->type), unqual(yty->type), 1)))
+ ty = xty;
+ else {
+ typeerror(COND, l, r);
+ return consttree(0, inttype);
+ }
+ if (isptr(ty)) {
+ ty = unqual(unqual(ty)->type);
+ if (isptr(xty) && isconst(unqual(xty)->type)
+ || isptr(yty) && isconst(unqual(yty)->type))
+ ty = qual(CONST, ty);
+ if (isptr(xty) && isvolatile(unqual(xty)->type)
+ || isptr(yty) && isvolatile(unqual(yty)->type))
+ ty = qual(VOLATILE, ty);
+ ty = ptr(ty);
+ }
+ switch (e->op) {
+ case CNST+I: return cast(e->u.v.i != 0 ? l : r, ty);
+ case CNST+U: return cast(e->u.v.u != 0 ? l : r, ty);
+ case CNST+P: return cast(e->u.v.p != 0 ? l : r, ty);
+ case CNST+F: return cast(e->u.v.d != 0.0 ? l : r, ty);
+ }
+ if (ty != voidtype && ty->size > 0) {
+ t1 = genident(REGISTER, unqual(ty), level);
+ /* t1 = temporary(REGISTER, unqual(ty)); */
+ l = asgn(t1, l);
+ r = asgn(t1, r);
+ } else
+ t1 = NULL;
+ p = tree(COND, ty, cond(e),
+ tree(RIGHT, ty, root(l), root(r)));
+ p->u.sym = t1;
+ return p;
+}
+/* addrof - address of p */
+Tree addrof(Tree p) {
+ Tree q = p;
+
+ for (;;)
+ switch (generic(q->op)) {
+ case RIGHT:
+ assert(q->kids[0] || q->kids[1]);
+ q = q->kids[1] ? q->kids[1] : q->kids[0];
+ continue;
+ case ASGN:
+ q = q->kids[1];
+ continue;
+ case COND: {
+ Symbol t1 = q->u.sym;
+ q->u.sym = 0;
+ q = idtree(t1);
+ /* fall thru */
+ }
+ case INDIR:
+ if (p == q)
+ return q->kids[0];
+ q = q->kids[0];
+ return tree(RIGHT, q->type, root(p), q);
+ default:
+ error("addressable object required\n");
+ return value(p);
+ }
+}
+
+/* andtree - construct tree for l [&& ||] r */
+static Tree andtree(int op, Tree l, Tree r) {
+ if (!isscalar(l->type) || !isscalar(r->type))
+ typeerror(op, l, r);
+ return simplify(op, inttype, cond(l), cond(r));
+}
+
+/* asgn - generate tree for assignment of expr e to symbol p sans qualifiers */
+Tree asgn(Symbol p, Tree e) {
+ if (isarray(p->type))
+ e = tree(ASGN+B, p->type, idtree(p),
+ tree(INDIR+B, e->type, e, NULL));
+ else {
+ Type ty = p->type;
+ p->type = unqual(p->type);
+ if (isstruct(p->type) && p->type->u.sym->u.s.cfields) {
+ p->type->u.sym->u.s.cfields = 0;
+ e = asgntree(ASGN, idtree(p), e);
+ p->type->u.sym->u.s.cfields = 1;
+ } else
+ e = asgntree(ASGN, idtree(p), e);
+ p->type = ty;
+ }
+ return e;
+}
+
+/* bittree - construct tree for l [& | ^ %] r */
+Tree bittree(int op, Tree l, Tree r) {
+ Type ty = inttype;
+
+ if (isint(l->type) && isint(r->type)) {
+ ty = binary(l->type, r->type);
+ l = cast(l, ty);
+ r = cast(r, ty);
+ } else
+ typeerror(op, l, r);
+ return simplify(op, ty, l, r);
+}
+
+/* multree - construct tree for l [* /] r */
+static Tree multree(int op, Tree l, Tree r) {
+ Type ty = inttype;
+
+ if (isarith(l->type) && isarith(r->type)) {
+ ty = binary(l->type, r->type);
+ l = cast(l, ty);
+ r = cast(r, ty);
+ } else
+ typeerror(op, l, r);
+ return simplify(op, ty, l, r);
+}
+
+/* shtree - construct tree for l [>> <<] r */
+Tree shtree(int op, Tree l, Tree r) {
+ Type ty = inttype;
+
+ if (isint(l->type) && isint(r->type)) {
+ ty = promote(l->type);
+ l = cast(l, ty);
+ r = cast(r, inttype);
+ } else
+ typeerror(op, l, r);
+ return simplify(op, ty, l, r);
+}
+
+/* subtree - construct tree for l - r */
+static Tree subtree(int op, Tree l, Tree r) {
+ long n;
+ Type ty = inttype;
+
+ if (isarith(l->type) && isarith(r->type)) {
+ ty = binary(l->type, r->type);
+ l = cast(l, ty);
+ r = cast(r, ty);
+ } else if (isptr(l->type) && !isfunc(l->type->type) && isint(r->type)) {
+ ty = unqual(l->type);
+ n = unqual(ty->type)->size;
+ if (n == 0)
+ error("unknown size for type `%t'\n", ty->type);
+ r = cast(r, promote(r->type));
+ if (n > 1)
+ r = multree(MUL, cnsttree(signedptr, n), r);
+ if (isunsigned(r->type))
+ r = cast(r, unsignedptr);
+ else
+ r = cast(r, signedptr);
+ return simplify(SUB+P, ty, l, r);
+ } else if (compatible(l->type, r->type)) {
+ ty = unqual(l->type);
+ n = unqual(ty->type)->size;
+ if (n == 0)
+ error("unknown size for type `%t'\n", ty->type);
+ l = simplify(SUB+U, unsignedptr,
+ cast(l, unsignedptr), cast(r, unsignedptr));
+ return simplify(DIV+I, longtype,
+ cast(l, longtype), cnsttree(longtype, n));
+ } else
+ typeerror(op, l, r);
+ return simplify(op, ty, l, r);
+}
+
+/* typeerror - issue "operands of op have illegal types `l' and `r'" */
+void typeerror(int op, Tree l, Tree r) {
+ int i;
+ static struct { int op; char *name; } ops[] = {
+ ASGN, "=", INDIR, "*", NEG, "-",
+ ADD, "+", SUB, "-", LSH, "<<",
+ MOD, "%", RSH, ">>", BAND, "&",
+ BCOM, "~", BOR, "|", BXOR, "^",
+ DIV, "/", MUL, "*", EQ, "==",
+ GE, ">=", GT, ">", LE, "<=",
+ LT, "<", NE, "!=", AND, "&&",
+ NOT, "!", OR, "||", COND, "?:",
+ 0, 0
+ };
+
+ op = generic(op);
+ for (i = 0; ops[i].op; i++)
+ if (op == ops[i].op)
+ break;
+ assert(ops[i].name);
+ if (r)
+ error("operands of %s have illegal types `%t' and `%t'\n",
+ ops[i].name, l->type, r->type);
+ else
+ error("operand of unary %s has illegal type `%t'\n", ops[i].name,
+ l->type);
+}
diff --git a/lcc/src/error.c b/lcc/src/error.c
new file mode 100755
index 0000000..56d164c
--- /dev/null
+++ b/lcc/src/error.c
@@ -0,0 +1,137 @@
+#include "c.h"
+
+
+static void printtoken(void);
+int errcnt = 0;
+int errlimit = 20;
+char kind[] = {
+#define xx(a,b,c,d,e,f,g) f,
+#define yy(a,b,c,d,e,f,g) f,
+#include "token.h"
+};
+int wflag; /* != 0 to suppress warning messages */
+
+void test(int tok, char set[]) {
+ if (t == tok)
+ t = gettok();
+ else {
+ expect(tok);
+ skipto(tok, set);
+ if (t == tok)
+ t = gettok();
+ }
+}
+void expect(int tok) {
+ if (t == tok)
+ t = gettok();
+ else {
+ error("syntax error; found");
+ printtoken();
+ fprint(stderr, " expecting `%k'\n", tok);
+ }
+}
+void error(const char *fmt, ...) {
+ va_list ap;
+
+ if (errcnt++ >= errlimit) {
+ errcnt = -1;
+ error("too many errors\n");
+ exit(1);
+ }
+ va_start(ap, fmt);
+ if (firstfile != file && firstfile && *firstfile)
+ fprint(stderr, "%s: ", firstfile);
+ fprint(stderr, "%w: ", &src);
+ vfprint(stderr, NULL, fmt, ap);
+ va_end(ap);
+}
+
+void skipto(int tok, char set[]) {
+ int n;
+ char *s;
+
+ assert(set);
+ for (n = 0; t != EOI && t != tok; t = gettok()) {
+ for (s = set; *s && kind[t] != *s; s++)
+ ;
+ if (kind[t] == *s)
+ break;
+ if (n++ == 0)
+ error("skipping");
+ if (n <= 8)
+ printtoken();
+ else if (n == 9)
+ fprint(stderr, " ...");
+ }
+ if (n > 8) {
+ fprint(stderr, " up to");
+ printtoken();
+ }
+ if (n > 0)
+ fprint(stderr, "\n");
+}
+/* fatal - issue fatal error message and exit */
+int fatal(const char *name, const char *fmt, int n) {
+ print("\n");
+ errcnt = -1;
+ error("compiler error in %s--", name);
+ fprint(stderr, fmt, n);
+ exit(EXIT_FAILURE);
+ return 0;
+}
+
+/* printtoken - print current token preceeded by a space */
+static void printtoken(void) {
+ switch (t) {
+ case ID: fprint(stderr, " `%s'", token); break;
+ case ICON:
+ fprint(stderr, " `%s'", vtoa(tsym->type, tsym->u.c.v));
+ break;
+ case SCON: {
+ int i, n;
+ if (ischar(tsym->type->type)) {
+ char *s = tsym->u.c.v.p;
+ n = tsym->type->size;
+ fprint(stderr, " \"");
+ for (i = 0; i < 20 && i < n && *s; s++, i++)
+ if (*s < ' ' || *s >= 0177)
+ fprint(stderr, "\\%o", *s);
+ else
+ fprint(stderr, "%c", *s);
+ } else { /* wchar_t string */
+ unsigned int *s = tsym->u.c.v.p;
+ assert(tsym->type->type->size == widechar->size);
+ n = tsym->type->size/widechar->size;
+ fprint(stderr, " L\"");
+ for (i = 0; i < 20 && i < n && *s; s++, i++)
+ if (*s < ' ' || *s >= 0177)
+ fprint(stderr, "\\x%x", *s);
+ else
+ fprint(stderr, "%c", *s);
+ }
+ if (i < n)
+ fprint(stderr, " ...");
+ else
+ fprint(stderr, "\"");
+ break;
+ }
+ case FCON:
+ fprint(stderr, " `%S'", token, (char*)cp - token);
+ break;
+ case '`': case '\'': fprint(stderr, " \"%k\"", t); break;
+ default: fprint(stderr, " `%k'", t);
+ }
+}
+
+/* warning - issue warning error message */
+void warning(const char *fmt, ...) {
+ va_list ap;
+
+ va_start(ap, fmt);
+ if (wflag == 0) {
+ errcnt--;
+ error("warning: ");
+ vfprint(stderr, NULL, fmt, ap);
+ }
+ va_end(ap);
+}
diff --git a/lcc/src/event.c b/lcc/src/event.c
new file mode 100755
index 0000000..12f409f
--- /dev/null
+++ b/lcc/src/event.c
@@ -0,0 +1,28 @@
+#include "c.h"
+
+
+struct entry {
+ Apply func;
+ void *cl;
+};
+
+Events events;
+void attach(Apply func, void *cl, List *list) {
+ struct entry *p;
+
+ NEW(p, PERM);
+ p->func = func;
+ p->cl = cl;
+ *list = append(p, *list);
+}
+void apply(List event, void *arg1, void *arg2) {
+ if (event) {
+ List lp = event;
+ do {
+ struct entry *p = lp->x;
+ (*p->func)(p->cl, arg1, arg2);
+ lp = lp->link;
+ } while (lp != event);
+ }
+}
+
diff --git a/lcc/src/expr.c b/lcc/src/expr.c
new file mode 100755
index 0000000..30b79cc
--- /dev/null
+++ b/lcc/src/expr.c
@@ -0,0 +1,709 @@
+#include "c.h"
+
+
+static char prec[] = {
+#define xx(a,b,c,d,e,f,g) c,
+#define yy(a,b,c,d,e,f,g) c,
+#include "token.h"
+};
+static int oper[] = {
+#define xx(a,b,c,d,e,f,g) d,
+#define yy(a,b,c,d,e,f,g) d,
+#include "token.h"
+};
+float refinc = 1.0;
+static Tree expr2(void);
+static Tree expr3(int);
+static Tree nullcheck(Tree);
+static Tree postfix(Tree);
+static Tree unary(void);
+static Tree primary(void);
+static Type super(Type ty);
+
+static Type super(Type ty) {
+ switch (ty->op) {
+ case INT:
+ if (ty->size < inttype->size)
+ return inttype;
+ break;
+ case UNSIGNED:
+ if (ty->size < unsignedtype->size)
+ return unsignedtype;
+ break;
+ case POINTER:
+ return unsignedptr;
+ }
+ return ty;
+}
+Tree expr(int tok) {
+ static char stop[] = { IF, ID, '}', 0 };
+ Tree p = expr1(0);
+
+ while (t == ',') {
+ Tree q;
+ t = gettok();
+ q = pointer(expr1(0));
+ p = tree(RIGHT, q->type, root(value(p)), q);
+ }
+ if (tok)
+ test(tok, stop);
+ return p;
+}
+Tree expr0(int tok) {
+ return root(expr(tok));
+}
+Tree expr1(int tok) {
+ static char stop[] = { IF, ID, 0 };
+ Tree p = expr2();
+
+ if (t == '='
+ || (prec[t] >= 6 && prec[t] <= 8)
+ || (prec[t] >= 11 && prec[t] <= 13)) {
+ int op = t;
+ t = gettok();
+ if (oper[op] == ASGN)
+ p = asgntree(ASGN, p, value(expr1(0)));
+ else
+ {
+ expect('=');
+ p = incr(op, p, expr1(0));
+ }
+ }
+ if (tok)
+ test(tok, stop);
+ return p;
+}
+Tree incr(int op, Tree v, Tree e) {
+ return asgntree(ASGN, v, (*optree[op])(oper[op], v, e));
+}
+static Tree expr2(void) {
+ Tree p = expr3(4);
+
+ if (t == '?') {
+ Tree l, r;
+ Coordinate pts[2];
+ if (Aflag > 1 && isfunc(p->type))
+ warning("%s used in a conditional expression\n",
+ funcname(p));
+ p = pointer(p);
+ t = gettok();
+ pts[0] = src;
+ l = pointer(expr(':'));
+ pts[1] = src;
+ r = pointer(expr2());
+ if (events.points)
+ {
+ apply(events.points, &pts[0], &l);
+ apply(events.points, &pts[1], &r);
+ }
+ p = condtree(p, l, r);
+ }
+ return p;
+}
+Tree value(Tree p) {
+ int op = generic(rightkid(p)->op);
+
+ if (p->type != voidtype
+ && (op==AND || op==OR || op==NOT || op==EQ || op==NE
+ || op== LE || op==LT || op== GE || op==GT))
+ p = condtree(p, consttree(1, inttype),
+ consttree(0, inttype));
+ return p;
+}
+static Tree expr3(int k) {
+ int k1;
+ Tree p = unary();
+
+ for (k1 = prec[t]; k1 >= k; k1--)
+ while (prec[t] == k1 && *cp != '=') {
+ Tree r;
+ Coordinate pt;
+ int op = t;
+ t = gettok();
+ pt = src;
+ p = pointer(p);
+ if (op == ANDAND || op == OROR) {
+ r = pointer(expr3(k1));
+ if (events.points)
+ apply(events.points, &pt, &r);
+ } else
+ r = pointer(expr3(k1 + 1));
+ p = (*optree[op])(oper[op], p, r);
+ }
+ return p;
+}
+static Tree unary(void) {
+ Tree p;
+
+ switch (t) {
+ case '*': t = gettok(); p = unary(); p = pointer(p);
+ if (isptr(p->type)
+ && (isfunc(p->type->type) || isarray(p->type->type)))
+ p = retype(p, p->type->type);
+ else {
+ if (YYnull)
+ p = nullcheck(p);
+ p = rvalue(p);
+ } break;
+ case '&': t = gettok(); p = unary(); if (isarray(p->type) || isfunc(p->type))
+ p = retype(p, ptr(p->type));
+ else
+ p = lvalue(p);
+ if (isaddrop(p->op) && p->u.sym->sclass == REGISTER)
+ error("invalid operand of unary &; `%s' is declared register\n", p->u.sym->name);
+
+ else if (isaddrop(p->op))
+ p->u.sym->addressed = 1;
+ break;
+ case '+': t = gettok(); p = unary(); p = pointer(p);
+ if (isarith(p->type))
+ p = cast(p, promote(p->type));
+ else
+ typeerror(ADD, p, NULL); break;
+ case '-': t = gettok(); p = unary(); p = pointer(p);
+ if (isarith(p->type)) {
+ Type ty = promote(p->type);
+ p = cast(p, ty);
+ if (isunsigned(ty)) {
+ warning("unsigned operand of unary -\n");
+ p = simplify(ADD, ty, simplify(BCOM, ty, p, NULL), cnsttree(ty, 1UL));
+ } else
+ p = simplify(NEG, ty, p, NULL);
+ } else
+ typeerror(SUB, p, NULL); break;
+ case '~': t = gettok(); p = unary(); p = pointer(p);
+ if (isint(p->type)) {
+ Type ty = promote(p->type);
+ p = simplify(BCOM, ty, cast(p, ty), NULL);
+ } else
+ typeerror(BCOM, p, NULL); break;
+ case '!': t = gettok(); p = unary(); p = pointer(p);
+ if (isscalar(p->type))
+ p = simplify(NOT, inttype, cond(p), NULL);
+ else
+ typeerror(NOT, p, NULL); break;
+ case INCR: t = gettok(); p = unary(); p = incr(INCR, pointer(p), consttree(1, inttype)); break;
+ case DECR: t = gettok(); p = unary(); p = incr(DECR, pointer(p), consttree(1, inttype)); break;
+ case TYPECODE: case SIZEOF: { int op = t;
+ Type ty;
+ p = NULL;
+ t = gettok();
+ if (t == '(') {
+ t = gettok();
+ if (istypename(t, tsym)) {
+ ty = typename();
+ expect(')');
+ } else {
+ p = postfix(expr(')'));
+ ty = p->type;
+ }
+ } else {
+ p = unary();
+ ty = p->type;
+ }
+ assert(ty);
+ if (op == TYPECODE)
+ p = cnsttree(inttype, (long)ty->op);
+ else {
+ if (isfunc(ty) || ty->size == 0)
+ error("invalid type argument `%t' to `sizeof'\n", ty);
+ else if (p && rightkid(p)->op == FIELD)
+ error("`sizeof' applied to a bit field\n");
+ p = cnsttree(unsignedlong, (unsigned long)ty->size);
+ } } break;
+ case '(':
+ t = gettok();
+ if (istypename(t, tsym)) {
+ Type ty, ty1 = typename(), pty;
+ expect(')');
+ ty = unqual(ty1);
+ if (isenum(ty)) {
+ Type ty2 = ty->type;
+ if (isconst(ty1))
+ ty2 = qual(CONST, ty2);
+ if (isvolatile(ty1))
+ ty2 = qual(VOLATILE, ty2);
+ ty1 = ty2;
+ ty = ty->type;
+ }
+ p = pointer(unary());
+ pty = p->type;
+ if (isenum(pty))
+ pty = pty->type;
+ if (isarith(pty) && isarith(ty)
+ || isptr(pty) && isptr(ty)) {
+ explicitCast++;
+ p = cast(p, ty);
+ explicitCast--;
+ } else if (isptr(pty) && isint(ty)
+ || isint(pty) && isptr(ty)) {
+ if (Aflag >= 1 && ty->size < pty->size)
+ warning("conversion from `%t' to `%t' is compiler dependent\n", p->type, ty);
+
+ p = cast(p, ty);
+ } else if (ty != voidtype) {
+ error("cast from `%t' to `%t' is illegal\n",
+ p->type, ty1);
+ ty1 = inttype;
+ }
+ if (generic(p->op) == INDIR || ty->size == 0)
+ p = tree(RIGHT, ty1, NULL, p);
+ else
+ p = retype(p, ty1);
+ } else
+ p = postfix(expr(')'));
+ break;
+ default:
+ p = postfix(primary());
+ }
+ return p;
+}
+
+static Tree postfix(Tree p) {
+ for (;;)
+ switch (t) {
+ case INCR: p = tree(RIGHT, p->type,
+ tree(RIGHT, p->type,
+ p,
+ incr(t, p, consttree(1, inttype))),
+ p);
+ t = gettok(); break;
+ case DECR: p = tree(RIGHT, p->type,
+ tree(RIGHT, p->type,
+ p,
+ incr(t, p, consttree(1, inttype))),
+ p);
+ t = gettok(); break;
+ case '[': {
+ Tree q;
+ t = gettok();
+ q = expr(']');
+ if (YYnull)
+ if (isptr(p->type))
+ p = nullcheck(p);
+ else if (isptr(q->type))
+ q = nullcheck(q);
+ p = (*optree['+'])(ADD, pointer(p), pointer(q));
+ if (isptr(p->type) && isarray(p->type->type))
+ p = retype(p, p->type->type);
+ else
+ p = rvalue(p);
+ } break;
+ case '(': {
+ Type ty;
+ Coordinate pt;
+ p = pointer(p);
+ if (isptr(p->type) && isfunc(p->type->type))
+ ty = p->type->type;
+ else {
+ error("found `%t' expected a function\n", p->type);
+ ty = func(voidtype, NULL, 1);
+ p = retype(p, ptr(ty));
+ }
+ pt = src;
+ t = gettok();
+ p = call(p, ty, pt);
+ } break;
+ case '.': t = gettok();
+ if (t == ID) {
+ if (isstruct(p->type)) {
+ Tree q = addrof(p);
+ p = field(q, token);
+ q = rightkid(q);
+ if (isaddrop(q->op) && q->u.sym->temporary)
+ p = tree(RIGHT, p->type, p, NULL);
+ } else
+ error("left operand of . has incompatible type `%t'\n",
+ p->type);
+ t = gettok();
+ } else
+ error("field name expected\n"); break;
+ case DEREF: t = gettok();
+ p = pointer(p);
+ if (t == ID) {
+ if (isptr(p->type) && isstruct(p->type->type)) {
+ if (YYnull)
+ p = nullcheck(p);
+ p = field(p, token);
+ } else
+ error("left operand of -> has incompatible type `%t'\n", p->type);
+
+ t = gettok();
+ } else
+ error("field name expected\n"); break;
+ default:
+ return p;
+ }
+}
+static Tree primary(void) {
+ Tree p;
+
+ assert(t != '(');
+ switch (t) {
+ case ICON:
+ case FCON: p = tree(mkop(CNST,tsym->type), tsym->type, NULL, NULL);
+ p->u.v = tsym->u.c.v;
+ break;
+ case SCON: if (ischar(tsym->type->type))
+ tsym->u.c.v.p = stringn(tsym->u.c.v.p, tsym->type->size);
+ else
+ tsym->u.c.v.p = memcpy(allocate(tsym->type->size, PERM), tsym->u.c.v.p, tsym->type->size);
+ tsym = constant(tsym->type, tsym->u.c.v);
+ if (tsym->u.c.loc == NULL)
+ tsym->u.c.loc = genident(STATIC, tsym->type, GLOBAL);
+ p = idtree(tsym->u.c.loc); break;
+ case ID: if (tsym == NULL)
+ {
+ Symbol p = install(token, &identifiers, level, FUNC);
+ p->src = src;
+ if (getchr() == '(') {
+ Symbol q = lookup(token, externals);
+ p->type = func(inttype, NULL, 1);
+ p->sclass = EXTERN;
+ if (Aflag >= 1)
+ warning("missing prototype\n");
+ if (q && !eqtype(q->type, p->type, 1))
+ warning("implicit declaration of `%s' does not match previous declaration at %w\n", q->name, &q->src);
+
+ if (q == NULL) {
+ q = install(p->name, &externals, GLOBAL, PERM);
+ q->type = p->type;
+ q->sclass = EXTERN;
+ q->src = src;
+ (*IR->defsymbol)(q);
+ }
+ p->u.alias = q;
+ } else {
+ error("undeclared identifier `%s'\n", p->name);
+ p->sclass = AUTO;
+ p->type = inttype;
+ if (p->scope == GLOBAL)
+ (*IR->defsymbol)(p);
+ else
+ addlocal(p);
+ }
+ t = gettok();
+ if (xref)
+ use(p, src);
+ return idtree(p);
+ }
+ if (xref)
+ use(tsym, src);
+ if (tsym->sclass == ENUM)
+ p = consttree(tsym->u.value, inttype);
+ else {
+ if (tsym->sclass == TYPEDEF)
+ error("illegal use of type name `%s'\n", tsym->name);
+ p = idtree(tsym);
+ } break;
+ case FIRSTARG:
+ if (level > PARAM && cfunc && cfunc->u.f.callee[0])
+ p = idtree(cfunc->u.f.callee[0]);
+ else {
+ error("illegal use of `%k'\n", FIRSTARG);
+ p = cnsttree(inttype, 0L);
+ }
+ break;
+ default:
+ error("illegal expression\n");
+ p = cnsttree(inttype, 0L);
+ }
+ t = gettok();
+ return p;
+}
+Tree idtree(Symbol p) {
+ int op;
+ Tree e;
+ Type ty = p->type ? unqual(p->type) : voidptype;
+
+ if (p->scope == GLOBAL || p->sclass == STATIC)
+ op = ADDRG;
+ else if (p->scope == PARAM) {
+ op = ADDRF;
+ if (isstruct(p->type) && !IR->wants_argb)
+ {
+ e = tree(mkop(op,voidptype), ptr(ptr(p->type)), NULL, NULL);
+ e->u.sym = p;
+ return rvalue(rvalue(e));
+ }
+ } else if (p->sclass == EXTERN) {
+ assert(p->u.alias);
+ p = p->u.alias;
+ op = ADDRG;
+ } else
+ op = ADDRL;
+ p->ref += refinc;
+ if (isarray(ty))
+ e = tree(mkop(op,voidptype), p->type, NULL, NULL);
+ else if (isfunc(ty))
+ e = tree(mkop(op,funcptype), p->type, NULL, NULL);
+ else
+ e = tree(mkop(op,voidptype), ptr(p->type), NULL, NULL);
+ e->u.sym = p;
+ if (isptr(e->type))
+ e = rvalue(e);
+ return e;
+}
+
+Tree rvalue(Tree p) {
+ Type ty = deref(p->type);
+
+ ty = unqual(ty);
+ return tree(mkop(INDIR,ty), ty, p, NULL);
+}
+Tree lvalue(Tree p) {
+ if (generic(p->op) != INDIR) {
+ error("lvalue required\n");
+ return value(p);
+ } else if (unqual(p->type) == voidtype)
+ warning("`%t' used as an lvalue\n", p->type);
+ return p->kids[0];
+}
+Tree retype(Tree p, Type ty) {
+ Tree q;
+
+ if (p->type == ty)
+ return p;
+ q = tree(p->op, ty, p->kids[0], p->kids[1]);
+ q->node = p->node;
+ q->u = p->u;
+ return q;
+}
+Tree rightkid(Tree p) {
+ while (p && p->op == RIGHT)
+ if (p->kids[1])
+ p = p->kids[1];
+ else if (p->kids[0])
+ p = p->kids[0];
+ else
+ assert(0);
+ assert(p);
+ return p;
+}
+int hascall(Tree p) {
+ if (p == 0)
+ return 0;
+ if (generic(p->op) == CALL || (IR->mulops_calls &&
+ (p->op == DIV+I || p->op == MOD+I || p->op == MUL+I
+ || p->op == DIV+U || p->op == MOD+U || p->op == MUL+U)))
+ return 1;
+ return hascall(p->kids[0]) || hascall(p->kids[1]);
+}
+Type binary(Type xty, Type yty) {
+#define xx(t) if (xty == t || yty == t) return t
+ xx(longdouble);
+ xx(doubletype);
+ xx(floattype);
+ xx(unsignedlonglong);
+ xx(longlong);
+ xx(unsignedlong);
+ if (xty == longtype && yty == unsignedtype
+ || xty == unsignedtype && yty == longtype)
+ if (longtype->size > unsignedtype->size)
+ return longtype;
+ else
+ return unsignedlong;
+ xx(longtype);
+ xx(unsignedtype);
+ return inttype;
+#undef xx
+}
+Tree pointer(Tree p) {
+ if (isarray(p->type))
+ /* assert(p->op != RIGHT || p->u.sym == NULL), */
+ p = retype(p, atop(p->type));
+ else if (isfunc(p->type))
+ p = retype(p, ptr(p->type));
+ return p;
+}
+Tree cond(Tree p) {
+ int op = generic(rightkid(p)->op);
+
+ if (op == AND || op == OR || op == NOT
+ || op == EQ || op == NE
+ || op == LE || op == LT || op == GE || op == GT)
+ return p;
+ p = pointer(p);
+ return (*optree[NEQ])(NE, p, consttree(0, inttype));
+}
+Tree cast(Tree p, Type type) {
+ Type src, dst;
+
+ p = value(p);
+ if (p->type == type)
+ return p;
+ dst = unqual(type);
+ src = unqual(p->type);
+ if (src->op != dst->op || src->size != dst->size) {
+ switch (src->op) {
+ case INT:
+ if (src->size < inttype->size)
+ p = simplify(CVI, inttype, p, NULL);
+ break;
+ case UNSIGNED:
+ if (src->size < inttype->size)
+ p = simplify(CVU, inttype, p, NULL);
+ else if (src->size < unsignedtype->size)
+ p = simplify(CVU, unsignedtype, p, NULL);
+ break;
+ case ENUM:
+ p = retype(p, inttype);
+ break;
+ case POINTER:
+ if (isint(dst) && src->size > dst->size)
+ warning("conversion from `%t' to `%t' is undefined\n", p->type, type);
+ p = simplify(CVP, super(src), p, NULL);
+ break;
+ case FLOAT:
+ break;
+ default: assert(0);
+ }
+ {
+ src = unqual(p->type);
+ dst = super(dst);
+ if (src->op != dst->op)
+ switch (src->op) {
+ case INT:
+ p = simplify(CVI, dst, p, NULL);
+ break;
+ case UNSIGNED:
+ if (isfloat(dst)) {
+ Type ssrc = signedint(src);
+ Tree two = cnsttree(longdouble, (long double)2.0);
+ p = (*optree['+'])(ADD,
+ (*optree['*'])(MUL,
+ two,
+ simplify(CVU, ssrc,
+ simplify(RSH, src,
+ p, consttree(1, inttype)), NULL)),
+ simplify(CVU, ssrc,
+ simplify(BAND, src,
+ p, consttree(1, unsignedtype)), NULL));
+ } else
+ p = simplify(CVU, dst, p, NULL);
+ break;
+ case FLOAT:
+ if (isunsigned(dst)) {
+ Type sdst = signedint(dst);
+ Tree c = cast(cnsttree(longdouble, (long double)sdst->u.sym->u.limits.max.i + 1), src);
+ p = condtree(
+ simplify(GE, src, p, c),
+ (*optree['+'])(ADD,
+ cast(cast(simplify(SUB, src, p, c), sdst), dst),
+ cast(cnsttree(unsignedlong, (unsigned long)sdst->u.sym->u.limits.max.i + 1), dst)),
+ simplify(CVF, sdst, p, NULL));
+ } else
+ p = simplify(CVF, dst, p, NULL);
+ break;
+ default: assert(0);
+ }
+ dst = unqual(type);
+ }
+ }
+ src = unqual(p->type);
+ switch (src->op) {
+ case INT:
+ if (src->op != dst->op || src->size != dst->size)
+ p = simplify(CVI, dst, p, NULL);
+ break;
+ case UNSIGNED:
+ if (src->op != dst->op || src->size != dst->size)
+ p = simplify(CVU, dst, p, NULL);
+ break;
+ case FLOAT:
+ if (src->op != dst->op || src->size != dst->size)
+ p = simplify(CVF, dst, p, NULL);
+ break;
+ case POINTER:
+ if (src->op != dst->op)
+ p = simplify(CVP, dst, p, NULL);
+ else {
+ if (isfunc(src->type) && !isfunc(dst->type)
+ || !isfunc(src->type) && isfunc(dst->type))
+ warning("conversion from `%t' to `%t' is compiler dependent\n", p->type, type);
+
+ if (src->size != dst->size)
+ p = simplify(CVP, dst, p, NULL);
+ }
+ break;
+ default: assert(0);
+ }
+ return retype(p, type);
+}
+Tree field(Tree p, const char *name) {
+ Field q;
+ Type ty1, ty = p->type;
+
+ if (isptr(ty))
+ ty = deref(ty);
+ ty1 = ty;
+ ty = unqual(ty);
+ if ((q = fieldref(name, ty)) != NULL) {
+ if (isarray(q->type)) {
+ ty = q->type->type;
+ if (isconst(ty1) && !isconst(ty))
+ ty = qual(CONST, ty);
+ if (isvolatile(ty1) && !isvolatile(ty))
+ ty = qual(VOLATILE, ty);
+ ty = array(ty, q->type->size/ty->size, q->type->align);
+ } else {
+ ty = q->type;
+ if (isconst(ty1) && !isconst(ty))
+ ty = qual(CONST, ty);
+ if (isvolatile(ty1) && !isvolatile(ty))
+ ty = qual(VOLATILE, ty);
+ ty = ptr(ty);
+ }
+ if (YYcheck && !isaddrop(p->op) && q->offset > 0) /* omit */
+ p = nullcall(ty, YYcheck, p, consttree(q->offset, inttype)); /* omit */
+ else /* omit */
+ p = simplify(ADD+P, ty, p, consttree(q->offset, inttype));
+
+ if (q->lsb) {
+ p = tree(FIELD, ty->type, rvalue(p), NULL);
+ p->u.field = q;
+ } else if (!isarray(q->type))
+ p = rvalue(p);
+
+ } else {
+ error("unknown field `%s' of `%t'\n", name, ty);
+ p = rvalue(retype(p, ptr(inttype)));
+ }
+ return p;
+}
+/* funcname - return name of function f or a function' */
+char *funcname(Tree f) {
+ if (isaddrop(f->op))
+ return stringf("`%s'", f->u.sym->name);
+ return "a function";
+}
+static Tree nullcheck(Tree p) {
+ if (!needconst && YYnull && isptr(p->type)) {
+ p = value(p);
+ if (strcmp(YYnull->name, "_YYnull") == 0) {
+ Symbol t1 = temporary(REGISTER, voidptype);
+ p = tree(RIGHT, p->type,
+ tree(OR, voidtype,
+ cond(asgn(t1, cast(p, voidptype))),
+ vcall(YYnull, voidtype, (file && *file ? pointer(idtree(mkstr(file)->u.c.loc)) : cnsttree(voidptype, NULL)), cnsttree(inttype, (long)lineno) , NULL)),
+ idtree(t1));
+ }
+
+ else
+ p = nullcall(p->type, YYnull, p, cnsttree(inttype, 0L));
+
+ }
+ return p;
+}
+Tree nullcall(Type pty, Symbol f, Tree p, Tree e) {
+ Type ty;
+
+ if (isarray(pty))
+ return retype(nullcall(atop(pty), f, p, e), pty);
+ ty = unqual(unqual(p->type)->type);
+ return vcall(f, pty,
+ p, e,
+ cnsttree(inttype, (long)ty->size),
+ cnsttree(inttype, (long)ty->align),
+ (file && *file ? pointer(idtree(mkstr(file)->u.c.loc)) : cnsttree(voidptype, NULL)), cnsttree(inttype, (long)lineno) , NULL);
+}
diff --git a/lcc/src/gen.c b/lcc/src/gen.c
new file mode 100755
index 0000000..ab8506a
--- /dev/null
+++ b/lcc/src/gen.c
@@ -0,0 +1,830 @@
+#include "c.h"
+
+
+#define readsreg(p) \
+ (generic((p)->op)==INDIR && (p)->kids[0]->op==VREG+P)
+#define setsrc(d) ((d) && (d)->x.regnode && \
+ (d)->x.regnode->set == src->x.regnode->set && \
+ (d)->x.regnode->mask&src->x.regnode->mask)
+
+#define relink(a, b) ((b)->x.prev = (a), (a)->x.next = (b))
+
+static Symbol askfixedreg(Symbol);
+static Symbol askreg(Symbol, unsigned*);
+static void blkunroll(int, int, int, int, int, int, int[]);
+static void docall(Node);
+static void dumpcover(Node, int, int);
+static void dumpregs(char *, char *, char *);
+static void dumprule(int);
+static void dumptree(Node);
+static unsigned emitasm(Node, int);
+static void genreload(Node, Symbol, int);
+static void genspill(Symbol, Node, Symbol);
+static Symbol getreg(Symbol, unsigned*, Node);
+static int getrule(Node, int);
+static void linearize(Node, Node);
+static int moveself(Node);
+static void prelabel(Node);
+static Node* prune(Node, Node*);
+static void putreg(Symbol);
+static void ralloc(Node);
+static void reduce(Node, int);
+static int reprune(Node*, int, int, Node);
+static int requate(Node);
+static Node reuse(Node, int);
+static void rewrite(Node);
+static Symbol spillee(Symbol, unsigned mask[], Node);
+static void spillr(Symbol, Node);
+static int uses(Node, Regnode);
+
+int offset;
+
+int maxoffset;
+
+int framesize;
+int argoffset;
+
+int maxargoffset;
+
+int dalign, salign;
+int bflag = 0; /* omit */
+int dflag = 0;
+
+int swap;
+
+unsigned (*emitter)(Node, int) = emitasm;
+static char NeedsReg[] = {
+ 0, /* unused */
+ 1, /* CNST */
+ 0, 0, /* ARG ASGN */
+ 1, /* INDIR */
+ 0, 0, 1, 1, /* - - CVF CVI */
+ 1, 0, 1, 1, /* CVP - CVU NEG */
+ 1, /* CALL */
+ 1, /* LOAD */
+ 0, /* RET */
+ 1, 1, 1, /* ADDRG ADDRF ADDRL */
+ 1, 1, 1, 1, 1, /* ADD SUB LSH MOD RSH */
+ 1, 1, 1, 1, /* BAND BCOM BOR BXOR */
+ 1, 1, /* DIV MUL */
+ 0, 0, 0, 0, 0, 0, /* EQ GE GT LE LT NE */
+ 0, 0 /* JUMP LABEL */
+};
+Node head;
+
+unsigned freemask[2];
+unsigned usedmask[2];
+unsigned tmask[2];
+unsigned vmask[2];
+Symbol mkreg(char *fmt, int n, int mask, int set) {
+ Symbol p;
+
+ NEW0(p, PERM);
+ p->name = p->x.name = stringf(fmt, n);
+ NEW0(p->x.regnode, PERM);
+ p->x.regnode->number = n;
+ p->x.regnode->mask = mask<<n;
+ p->x.regnode->set = set;
+ return p;
+}
+Symbol mkwildcard(Symbol *syms) {
+ Symbol p;
+
+ NEW0(p, PERM);
+ p->name = p->x.name = "wildcard";
+ p->x.wildcard = syms;
+ return p;
+}
+void mkauto(Symbol p) {
+ assert(p->sclass == AUTO);
+ offset = roundup(offset + p->type->size, p->type->align);
+ p->x.offset = -offset;
+ p->x.name = stringd(-offset);
+}
+void blockbeg(Env *e) {
+ e->offset = offset;
+ e->freemask[IREG] = freemask[IREG];
+ e->freemask[FREG] = freemask[FREG];
+}
+void blockend(Env *e) {
+ if (offset > maxoffset)
+ maxoffset = offset;
+ offset = e->offset;
+ freemask[IREG] = e->freemask[IREG];
+ freemask[FREG] = e->freemask[FREG];
+}
+int mkactual(int align, int size) {
+ int n = roundup(argoffset, align);
+
+ argoffset = n + size;
+ return n;
+}
+static void docall(Node p) {
+ p->syms[1] = p->syms[0];
+ p->syms[0] = intconst(argoffset);
+ if (argoffset > maxargoffset)
+ maxargoffset = argoffset;
+ argoffset = 0;
+}
+void blkcopy(int dreg, int doff, int sreg, int soff, int size, int tmp[]) {
+ assert(size >= 0);
+ if (size == 0)
+ return;
+ else if (size <= 2)
+ blkunroll(size, dreg, doff, sreg, soff, size, tmp);
+ else if (size == 3) {
+ blkunroll(2, dreg, doff, sreg, soff, 2, tmp);
+ blkunroll(1, dreg, doff+2, sreg, soff+2, 1, tmp);
+ }
+ else if (size <= 16) {
+ blkunroll(4, dreg, doff, sreg, soff, size&~3, tmp);
+ blkcopy(dreg, doff+(size&~3),
+ sreg, soff+(size&~3), size&3, tmp);
+ }
+ else
+ (*IR->x.blkloop)(dreg, doff, sreg, soff, size, tmp);
+}
+static void blkunroll(int k, int dreg, int doff, int sreg, int soff, int size, int tmp[]) {
+ int i;
+
+ assert(IR->x.max_unaligned_load);
+ if (k > IR->x.max_unaligned_load
+ && (k > salign || k > dalign))
+ k = IR->x.max_unaligned_load;
+ for (i = 0; i+k < size; i += 2*k) {
+ (*IR->x.blkfetch)(k, soff+i, sreg, tmp[0]);
+ (*IR->x.blkfetch)(k, soff+i+k, sreg, tmp[1]);
+ (*IR->x.blkstore)(k, doff+i, dreg, tmp[0]);
+ (*IR->x.blkstore)(k, doff+i+k, dreg, tmp[1]);
+ }
+ if (i < size) {
+ (*IR->x.blkfetch)(k, i+soff, sreg, tmp[0]);
+ (*IR->x.blkstore)(k, i+doff, dreg, tmp[0]);
+ }
+}
+void parseflags(int argc, char *argv[]) {
+ int i;
+
+ for (i = 0; i < argc; i++)
+ if (strcmp(argv[i], "-d") == 0)
+ dflag = 1;
+ else if (strcmp(argv[i], "-b") == 0) /* omit */
+ bflag = 1; /* omit */
+}
+static int getrule(Node p, int nt) {
+ int rulenum;
+
+ assert(p);
+ rulenum = (*IR->x._rule)(p->x.state, nt);
+ if (!rulenum) {
+ fprint(stderr, "(%x->op=%s at %w is corrupt.)\n", p, opname(p->op), &src);
+ assert(0);
+ }
+ return rulenum;
+}
+static void reduce(Node p, int nt) {
+ int rulenum, i;
+ short *nts;
+ Node kids[10];
+
+ p = reuse(p, nt);
+ rulenum = getrule(p, nt);
+ nts = IR->x._nts[rulenum];
+ (*IR->x._kids)(p, rulenum, kids);
+ for (i = 0; nts[i]; i++)
+ reduce(kids[i], nts[i]);
+ if (IR->x._isinstruction[rulenum]) {
+ assert(p->x.inst == 0 || p->x.inst == nt);
+ p->x.inst = nt;
+ if (p->syms[RX] && p->syms[RX]->temporary) {
+ debug(fprint(stderr, "(using %s)\n", p->syms[RX]->name));
+ p->syms[RX]->x.usecount++;
+ }
+ }
+}
+static Node reuse(Node p, int nt) {
+ struct _state {
+ short cost[1];
+ };
+ Symbol r = p->syms[RX];
+
+ if (generic(p->op) == INDIR && p->kids[0]->op == VREG+P
+ && r->u.t.cse && p->x.mayrecalc
+ && ((struct _state*)r->u.t.cse->x.state)->cost[nt] == 0)
+ return r->u.t.cse;
+ else
+ return p;
+}
+
+int mayrecalc(Node p) {
+ int op;
+
+ assert(p && p->syms[RX]);
+ if (p->syms[RX]->u.t.cse == NULL)
+ return 0;
+ op = generic(p->syms[RX]->u.t.cse->op);
+ if (op == CNST || op == ADDRF || op == ADDRG || op == ADDRL) {
+ p->x.mayrecalc = 1;
+ return 1;
+ } else
+ return 0;
+}
+static Node *prune(Node p, Node pp[]) {
+ if (p == NULL)
+ return pp;
+ p->x.kids[0] = p->x.kids[1] = p->x.kids[2] = NULL;
+ if (p->x.inst == 0)
+ return prune(p->kids[1], prune(p->kids[0], pp));
+ else if (p->syms[RX] && p->syms[RX]->temporary
+ && p->syms[RX]->x.usecount < 2) {
+ p->x.inst = 0;
+ debug(fprint(stderr, "(clobbering %s)\n", p->syms[RX]->name));
+ return prune(p->kids[1], prune(p->kids[0], pp));
+ }
+ else {
+ prune(p->kids[1], prune(p->kids[0], &p->x.kids[0]));
+ *pp = p;
+ return pp + 1;
+ }
+}
+
+#define ck(i) return (i) ? 0 : LBURG_MAX
+
+int range(Node p, int lo, int hi) {
+ Symbol s = p->syms[0];
+
+ switch (specific(p->op)) {
+ case ADDRF+P:
+ case ADDRL+P: ck(s->x.offset >= lo && s->x.offset <= hi);
+ case CNST+I: ck(s->u.c.v.i >= lo && s->u.c.v.i <= hi);
+ case CNST+U: ck(s->u.c.v.u >= lo && s->u.c.v.u <= hi);
+ case CNST+P: ck(s->u.c.v.p == 0 && lo <= 0 && hi >= 0);
+ }
+ return LBURG_MAX;
+}
+static void dumptree(Node p) {
+ if (p->op == VREG+P && p->syms[0]) {
+ fprint(stderr, "VREGP(%s)", p->syms[0]->name);
+ return;
+ } else if (generic(p->op) == LOAD) {
+ fprint(stderr, "LOAD(");
+ dumptree(p->kids[0]);
+ fprint(stderr, ")");
+ return;
+ }
+ fprint(stderr, "%s(", opname(p->op));
+ switch (generic(p->op)) {
+ case CNST: case LABEL:
+ case ADDRG: case ADDRF: case ADDRL:
+ if (p->syms[0])
+ fprint(stderr, "%s", p->syms[0]->name);
+ break;
+ case RET:
+ if (p->kids[0])
+ dumptree(p->kids[0]);
+ break;
+ case CVF: case CVI: case CVP: case CVU: case JUMP:
+ case ARG: case BCOM: case NEG: case INDIR:
+ dumptree(p->kids[0]);
+ break;
+ case CALL:
+ if (optype(p->op) != B) {
+ dumptree(p->kids[0]);
+ break;
+ }
+ /* else fall thru */
+ case EQ: case NE: case GT: case GE: case LE: case LT:
+ case ASGN: case BOR: case BAND: case BXOR: case RSH: case LSH:
+ case ADD: case SUB: case DIV: case MUL: case MOD:
+ dumptree(p->kids[0]);
+ fprint(stderr, ", ");
+ dumptree(p->kids[1]);
+ break;
+ default: assert(0);
+ }
+ fprint(stderr, ")");
+}
+static void dumpcover(Node p, int nt, int in) {
+ int rulenum, i;
+ short *nts;
+ Node kids[10];
+
+ p = reuse(p, nt);
+ rulenum = getrule(p, nt);
+ nts = IR->x._nts[rulenum];
+ fprint(stderr, "dumpcover(%x) = ", p);
+ for (i = 0; i < in; i++)
+ fprint(stderr, " ");
+ dumprule(rulenum);
+ (*IR->x._kids)(p, rulenum, kids);
+ for (i = 0; nts[i]; i++)
+ dumpcover(kids[i], nts[i], in+1);
+}
+
+static void dumprule(int rulenum) {
+ assert(rulenum);
+ fprint(stderr, "%s / %s", IR->x._string[rulenum],
+ IR->x._templates[rulenum]);
+ if (!IR->x._isinstruction[rulenum])
+ fprint(stderr, "\n");
+}
+static unsigned emitasm(Node p, int nt) {
+ int rulenum;
+ short *nts;
+ char *fmt;
+ Node kids[10];
+
+ p = reuse(p, nt);
+ rulenum = getrule(p, nt);
+ nts = IR->x._nts[rulenum];
+ fmt = IR->x._templates[rulenum];
+ assert(fmt);
+ if (IR->x._isinstruction[rulenum] && p->x.emitted)
+ print("%s", p->syms[RX]->x.name);
+ else if (*fmt == '#')
+ (*IR->x.emit2)(p);
+ else {
+ if (*fmt == '?') {
+ fmt++;
+ assert(p->kids[0]);
+ if (p->syms[RX] == p->x.kids[0]->syms[RX])
+ while (*fmt++ != '\n')
+ ;
+ }
+ for ((*IR->x._kids)(p, rulenum, kids); *fmt; fmt++)
+ if (*fmt != '%')
+ (void)putchar(*fmt);
+ else if (*++fmt == 'F')
+ print("%d", framesize);
+ else if (*fmt >= '0' && *fmt <= '9')
+ emitasm(kids[*fmt - '0'], nts[*fmt - '0']);
+ else if (*fmt >= 'a' && *fmt < 'a' + NELEMS(p->syms))
+ fputs(p->syms[*fmt - 'a']->x.name, stdout);
+ else
+ (void)putchar(*fmt);
+ }
+ return 0;
+}
+void emit(Node p) {
+ for (; p; p = p->x.next) {
+ assert(p->x.registered);
+ if (p->x.equatable && requate(p) || moveself(p))
+ ;
+ else
+ (*emitter)(p, p->x.inst);
+ p->x.emitted = 1;
+ }
+}
+static int moveself(Node p) {
+ return p->x.copy
+ && p->syms[RX]->x.name == p->x.kids[0]->syms[RX]->x.name;
+}
+int move(Node p) {
+ p->x.copy = 1;
+ return 1;
+}
+static int requate(Node q) {
+ Symbol src = q->x.kids[0]->syms[RX];
+ Symbol tmp = q->syms[RX];
+ Node p;
+ int n = 0;
+
+ debug(fprint(stderr, "(requate(%x): tmp=%s src=%s)\n", q, tmp->x.name, src->x.name));
+ for (p = q->x.next; p; p = p->x.next)
+ if (p->x.copy && p->syms[RX] == src
+ && p->x.kids[0]->syms[RX] == tmp)
+ debug(fprint(stderr, "(requate arm 0 at %x)\n", p)),
+ p->syms[RX] = tmp;
+ else if (setsrc(p->syms[RX]) && !moveself(p) && !readsreg(p))
+ return 0;
+ else if (p->x.spills)
+ return 0;
+ else if (generic(p->op) == CALL && p->x.next)
+ return 0;
+ else if (p->op == LABEL+V && p->x.next)
+ return 0;
+ else if (p->syms[RX] == tmp && readsreg(p))
+ debug(fprint(stderr, "(requate arm 5 at %x)\n", p)),
+ n++;
+ else if (p->syms[RX] == tmp)
+ break;
+ debug(fprint(stderr, "(requate arm 7 at %x)\n", p));
+ assert(n > 0);
+ for (p = q->x.next; p; p = p->x.next)
+ if (p->syms[RX] == tmp && readsreg(p)) {
+ p->syms[RX] = src;
+ if (--n <= 0)
+ break;
+ }
+ return 1;
+}
+static void prelabel(Node p) {
+ if (p == NULL)
+ return;
+ prelabel(p->kids[0]);
+ prelabel(p->kids[1]);
+ if (NeedsReg[opindex(p->op)])
+ setreg(p, (*IR->x.rmap)(opkind(p->op)));
+ switch (generic(p->op)) {
+ case ADDRF: case ADDRL:
+ if (p->syms[0]->sclass == REGISTER)
+ p->op = VREG+P;
+ break;
+ case INDIR:
+ if (p->kids[0]->op == VREG+P)
+ setreg(p, p->kids[0]->syms[0]);
+ break;
+ case ASGN:
+ if (p->kids[0]->op == VREG+P)
+ rtarget(p, 1, p->kids[0]->syms[0]);
+ break;
+ case CVI: case CVU: case CVP:
+ if (optype(p->op) != F
+ && opsize(p->op) <= p->syms[0]->u.c.v.i)
+ p->op = LOAD + opkind(p->op);
+ break;
+ }
+ (IR->x.target)(p);
+}
+void setreg(Node p, Symbol r) {
+ p->syms[RX] = r;
+}
+void rtarget(Node p, int n, Symbol r) {
+ Node q = p->kids[n];
+
+ assert(q);
+ assert(r);
+ assert(r->sclass == REGISTER || !r->x.wildcard);
+ assert(q->syms[RX]);
+ if (r != q->syms[RX] && !q->syms[RX]->x.wildcard) {
+ q = newnode(LOAD + opkind(q->op),
+ q, NULL, q->syms[0]);
+ if (r->u.t.cse == p->kids[n])
+ r->u.t.cse = q;
+ p->kids[n] = p->x.kids[n] = q;
+ q->x.kids[0] = q->kids[0];
+ }
+ setreg(q, r);
+ debug(fprint(stderr, "(targeting %x->x.kids[%d]=%x to %s)\n", p, n, p->kids[n], r->x.name));
+}
+static void rewrite(Node p) {
+ assert(p->x.inst == 0);
+ prelabel(p);
+ debug(dumptree(p));
+ debug(fprint(stderr, "\n"));
+ (*IR->x._label)(p);
+ debug(dumpcover(p, 1, 0));
+ reduce(p, 1);
+}
+Node gen(Node forest) {
+ int i;
+ struct node sentinel;
+ Node dummy, p;
+
+ head = forest;
+ for (p = forest; p; p = p->link) {
+ assert(p->count == 0);
+ if (generic(p->op) == CALL)
+ docall(p);
+ else if ( generic(p->op) == ASGN
+ && generic(p->kids[1]->op) == CALL)
+ docall(p->kids[1]);
+ else if (generic(p->op) == ARG)
+ (*IR->x.doarg)(p);
+ rewrite(p);
+ p->x.listed = 1;
+ }
+ for (p = forest; p; p = p->link)
+ prune(p, &dummy);
+ relink(&sentinel, &sentinel);
+ for (p = forest; p; p = p->link)
+ linearize(p, &sentinel);
+ forest = sentinel.x.next;
+ assert(forest);
+ sentinel.x.next->x.prev = NULL;
+ sentinel.x.prev->x.next = NULL;
+ for (p = forest; p; p = p->x.next)
+ for (i = 0; i < NELEMS(p->x.kids) && p->x.kids[i]; i++) {
+ assert(p->x.kids[i]->syms[RX]);
+ if (p->x.kids[i]->syms[RX]->temporary) {
+ p->x.kids[i]->x.prevuse =
+ p->x.kids[i]->syms[RX]->x.lastuse;
+ p->x.kids[i]->syms[RX]->x.lastuse = p->x.kids[i];
+ }
+ }
+ for (p = forest; p; p = p->x.next) {
+ ralloc(p);
+ if (p->x.listed && NeedsReg[opindex(p->op)]
+ && (*IR->x.rmap)(opkind(p->op))) {
+ assert(generic(p->op) == CALL || generic(p->op) == LOAD);
+ putreg(p->syms[RX]);
+ }
+ }
+ return forest;
+}
+int notarget(Node p) {
+ return p->syms[RX]->x.wildcard ? 0 : LBURG_MAX;
+}
+static void putreg(Symbol r) {
+ assert(r && r->x.regnode);
+ freemask[r->x.regnode->set] |= r->x.regnode->mask;
+ debug(dumpregs("(freeing %s)\n", r->x.name, NULL));
+}
+static Symbol askfixedreg(Symbol s) {
+ Regnode r = s->x.regnode;
+ int n = r->set;
+
+ if (r->mask&~freemask[n])
+ return NULL;
+ else {
+ freemask[n] &= ~r->mask;
+ usedmask[n] |= r->mask;
+ return s;
+ }
+}
+static Symbol askreg(Symbol rs, unsigned rmask[]) {
+ int i;
+
+ if (rs->x.wildcard == NULL)
+ return askfixedreg(rs);
+ for (i = 31; i >= 0; i--) {
+ Symbol r = rs->x.wildcard[i];
+ if (r != NULL
+ && !(r->x.regnode->mask&~rmask[r->x.regnode->set])
+ && askfixedreg(r))
+ return r;
+ }
+ return NULL;
+}
+
+static Symbol getreg(Symbol s, unsigned mask[], Node p) {
+ Symbol r = askreg(s, mask);
+ if (r == NULL) {
+ r = spillee(s, mask, p);
+ assert(r && r->x.regnode);
+ spill(r->x.regnode->mask, r->x.regnode->set, p);
+ r = askreg(s, mask);
+ }
+ assert(r && r->x.regnode);
+ r->x.regnode->vbl = NULL;
+ return r;
+}
+int askregvar(Symbol p, Symbol regs) {
+ Symbol r;
+
+ assert(p);
+ if (p->sclass != REGISTER)
+ return 0;
+ else if (!isscalar(p->type)) {
+ p->sclass = AUTO;
+ return 0;
+ }
+ else if (p->temporary) {
+ p->x.name = "?";
+ return 1;
+ }
+ else if ((r = askreg(regs, vmask)) != NULL) {
+ p->x.regnode = r->x.regnode;
+ p->x.regnode->vbl = p;
+ p->x.name = r->x.name;
+ debug(dumpregs("(allocating %s to symbol %s)\n", p->x.name, p->name));
+ return 1;
+ }
+ else {
+ p->sclass = AUTO;
+ return 0;
+ }
+}
+static void linearize(Node p, Node next) {
+ int i;
+
+ for (i = 0; i < NELEMS(p->x.kids) && p->x.kids[i]; i++)
+ linearize(p->x.kids[i], next);
+ relink(next->x.prev, p);
+ relink(p, next);
+ debug(fprint(stderr, "(listing %x)\n", p));
+}
+static void ralloc(Node p) {
+ int i;
+ unsigned mask[2];
+
+ mask[0] = tmask[0];
+ mask[1] = tmask[1];
+ assert(p);
+ debug(fprint(stderr, "(rallocing %x)\n", p));
+ for (i = 0; i < NELEMS(p->x.kids) && p->x.kids[i]; i++) {
+ Node kid = p->x.kids[i];
+ Symbol r = kid->syms[RX];
+ assert(r && kid->x.registered);
+ if (r->sclass != REGISTER && r->x.lastuse == kid)
+ putreg(r);
+ }
+ if (!p->x.registered && NeedsReg[opindex(p->op)]
+ && (*IR->x.rmap)(opkind(p->op))) {
+ Symbol sym = p->syms[RX], set = sym;
+ assert(sym);
+ if (sym->temporary)
+ set = (*IR->x.rmap)(opkind(p->op));
+ assert(set);
+ if (set->sclass != REGISTER) {
+ Symbol r;
+ if (*IR->x._templates[getrule(p, p->x.inst)] == '?')
+ for (i = 1; i < NELEMS(p->x.kids) && p->x.kids[i]; i++) {
+ Symbol r = p->x.kids[i]->syms[RX];
+ assert(p->x.kids[i]->x.registered);
+ assert(r && r->x.regnode);
+ assert(sym->x.wildcard || sym != r);
+ mask[r->x.regnode->set] &= ~r->x.regnode->mask;
+ }
+ r = getreg(set, mask, p);
+ if (sym->temporary) {
+ Node q;
+ r->x.lastuse = sym->x.lastuse;
+ for (q = sym->x.lastuse; q; q = q->x.prevuse) {
+ q->syms[RX] = r;
+ q->x.registered = 1;
+ if (sym->u.t.cse && q->x.copy)
+ q->x.equatable = 1;
+ }
+ } else {
+ p->syms[RX] = r;
+ r->x.lastuse = p;
+ }
+ debug(dumpregs("(allocating %s to node %x)\n", r->x.name, (char *) p));
+ }
+ }
+ p->x.registered = 1;
+ (*IR->x.clobber)(p);
+}
+static Symbol spillee(Symbol set, unsigned mask[], Node here) {
+ Symbol bestreg = NULL;
+ int bestdist = -1, i;
+
+ assert(set);
+ if (!set->x.wildcard)
+ bestreg = set;
+ else {
+ for (i = 31; i >= 0; i--) {
+ Symbol ri = set->x.wildcard[i];
+ if (
+ ri != NULL &&
+ ri->x.lastuse &&
+ (ri->x.regnode->mask&tmask[ri->x.regnode->set]&mask[ri->x.regnode->set])
+ ) {
+ Regnode rn = ri->x.regnode;
+ Node q = here;
+ int dist = 0;
+ for (; q && !uses(q, rn); q = q->x.next)
+ dist++;
+ if (q && dist > bestdist) {
+ bestdist = dist;
+ bestreg = ri;
+ }
+ }
+ }
+ }
+ assert(bestreg); /* Must be able to spill something. Reconfigure the register allocator
+ to ensure that we can allocate a register for all nodes without spilling
+ the node's necessary input regs. */
+ assert(bestreg->x.regnode->vbl == NULL); /* Can't spill register variables because
+ the reload site might be in other blocks. Reconfigure the register allocator
+ to ensure that this register is never allocated to a variable. */
+ return bestreg;
+}
+static int uses(Node p, Regnode rn) {
+ int i;
+
+ for (i = 0; i < NELEMS(p->x.kids); i++)
+ if (
+ p->x.kids[i] &&
+ p->x.kids[i]->x.registered &&
+ rn->set == p->x.kids[i]->syms[RX]->x.regnode->set &&
+ (rn->mask&p->x.kids[i]->syms[RX]->x.regnode->mask)
+ )
+ return 1;
+ return 0;
+}
+static void spillr(Symbol r, Node here) {
+ int i;
+ Symbol tmp;
+ Node p = r->x.lastuse;
+ assert(p);
+ while (p->x.prevuse)
+ assert(r == p->syms[RX]),
+ p = p->x.prevuse;
+ assert(p->x.registered && !readsreg(p));
+ tmp = newtemp(AUTO, optype(p->op), opsize(p->op));
+ genspill(r, p, tmp);
+ for (p = here->x.next; p; p = p->x.next)
+ for (i = 0; i < NELEMS(p->x.kids) && p->x.kids[i]; i++) {
+ Node k = p->x.kids[i];
+ if (k->x.registered && k->syms[RX] == r)
+ genreload(p, tmp, i);
+ }
+ putreg(r);
+}
+static void genspill(Symbol r, Node last, Symbol tmp) {
+ Node p, q;
+ Symbol s;
+ unsigned ty;
+
+ debug(fprint(stderr, "(spilling %s to local %s)\n", r->x.name, tmp->x.name));
+ debug(fprint(stderr, "(genspill: "));
+ debug(dumptree(last));
+ debug(fprint(stderr, ")\n"));
+ ty = opkind(last->op);
+ NEW0(s, FUNC);
+ s->sclass = REGISTER;
+ s->name = s->x.name = r->x.name;
+ s->x.regnode = r->x.regnode;
+ q = newnode(ADDRL+P + sizeop(IR->ptrmetric.size), NULL, NULL, s);
+ q = newnode(INDIR + ty, q, NULL, NULL);
+ p = newnode(ADDRL+P + sizeop(IR->ptrmetric.size), NULL, NULL, tmp);
+ p = newnode(ASGN + ty, p, q, NULL);
+ p->x.spills = 1;
+ rewrite(p);
+ prune(p, &q);
+ q = last->x.next;
+ linearize(p, q);
+ for (p = last->x.next; p != q; p = p->x.next) {
+ ralloc(p);
+ assert(!p->x.listed || !NeedsReg[opindex(p->op)] || !(*IR->x.rmap)(opkind(p->op)));
+ }
+}
+
+static void genreload(Node p, Symbol tmp, int i) {
+ Node q;
+ int ty;
+
+ debug(fprint(stderr, "(replacing %x with a reload from %s)\n", p->x.kids[i], tmp->x.name));
+ debug(fprint(stderr, "(genreload: "));
+ debug(dumptree(p->x.kids[i]));
+ debug(fprint(stderr, ")\n"));
+ ty = opkind(p->x.kids[i]->op);
+ q = newnode(ADDRL+P + sizeop(IR->ptrmetric.size), NULL, NULL, tmp);
+ p->x.kids[i] = newnode(INDIR + ty, q, NULL, NULL);
+ rewrite(p->x.kids[i]);
+ prune(p->x.kids[i], &q);
+ reprune(&p->kids[1], reprune(&p->kids[0], 0, i, p), i, p);
+ prune(p, &q);
+ linearize(p->x.kids[i], p);
+}
+static int reprune(Node *pp, int k, int n, Node p) {
+ struct node x, *q = *pp;
+
+ if (q == NULL || k > n)
+ return k;
+ else if (q->x.inst == 0)
+ return reprune(&q->kids[1],
+ reprune(&q->kids[0], k, n, p), n, p);
+ if (k == n) {
+ debug(fprint(stderr, "(reprune changes %x from %x to %x)\n", pp, *pp, p->x.kids[n]));
+ *pp = p->x.kids[n];
+ x = *p;
+ (IR->x.target)(&x);
+ }
+ return k + 1;
+}
+void spill(unsigned mask, int n, Node here) {
+ int i;
+ Node p;
+
+ here->x.spills = 1;
+ usedmask[n] |= mask;
+ if (mask&~freemask[n]) {
+
+ assert( /* It makes no sense for a node to clobber() its target. */
+ here->x.registered == 0 || /* call isn't coming through clobber() */
+ here->syms[RX] == NULL ||
+ here->syms[RX]->x.regnode == NULL ||
+ here->syms[RX]->x.regnode->set != n ||
+ (here->syms[RX]->x.regnode->mask&mask) == 0
+ );
+
+ for (p = here; p; p = p->x.next)
+ for (i = 0; i < NELEMS(p->x.kids) && p->x.kids[i]; i++) {
+ Symbol r = p->x.kids[i]->syms[RX];
+ assert(r);
+ if (p->x.kids[i]->x.registered && r->x.regnode->set == n
+ && r->x.regnode->mask&mask)
+ spillr(r, here);
+ }
+ }
+}
+static void dumpregs(char *msg, char *a, char *b) {
+ fprint(stderr, msg, a, b);
+ fprint(stderr, "(free[0]=%x)\n", freemask[0]);
+ fprint(stderr, "(free[1]=%x)\n", freemask[1]);
+}
+
+int getregnum(Node p) {
+ assert(p && p->syms[RX] && p->syms[RX]->x.regnode);
+ return p->syms[RX]->x.regnode->number;
+}
+
+
+unsigned regloc(Symbol p) {
+ assert(p && p->sclass == REGISTER && p->sclass == REGISTER && p->x.regnode);
+ return p->x.regnode->set<<8 | p->x.regnode->number;
+}
+
diff --git a/lcc/src/init.c b/lcc/src/init.c
new file mode 100755
index 0000000..67bcc69
--- /dev/null
+++ b/lcc/src/init.c
@@ -0,0 +1,318 @@
+#include "c.h"
+
+
+static int curseg; /* current segment */
+
+/* defpointer - initialize a pointer to p or to 0 if p==0 */
+void defpointer(Symbol p) {
+ if (p) {
+ (*IR->defaddress)(p);
+ p->ref++;
+ } else {
+ static Value v;
+ (*IR->defconst)(P, voidptype->size, v);
+ }
+}
+
+/* genconst - generate/check constant expression e; return size */
+static int genconst(Tree e, int def) {
+ for (;;)
+ switch (generic(e->op)) {
+ case ADDRG:
+ if (def)
+ (*IR->defaddress)(e->u.sym);
+ return e->type->size;
+ case CNST:
+ if (e->op == CNST+P && isarray(e->type)) {
+ e = cvtconst(e);
+ continue;
+ }
+ if (def)
+ (*IR->defconst)(e->type->op, e->type->size, e->u.v);
+ return e->type->size;
+ case RIGHT:
+ assert(e->kids[0] || e->kids[1]);
+ if (e->kids[1] && e->kids[0])
+ error("initializer must be constant\n");
+ e = e->kids[1] ? e->kids[1] : e->kids[0];
+ continue;
+ case CVP:
+ if (isarith(e->type))
+ error("cast from `%t' to `%t' is illegal in constant expressions\n",
+ e->kids[0]->type, e->type);
+ /* fall thru */
+ case CVI: case CVU: case CVF:
+ e = e->kids[0];
+ continue;
+ default:
+ error("initializer must be constant\n");
+ if (def)
+ genconst(consttree(0, inttype), def);
+ return inttype->size;
+ }
+}
+
+/* initvalue - evaluate a constant expression for a value of integer type ty */
+static Tree initvalue(Type ty) {
+ Type aty;
+ Tree e;
+
+ needconst++;
+ e = expr1(0);
+ if ((aty = assign(ty, e)) != NULL)
+ e = cast(e, aty);
+ else {
+ error("invalid initialization type; found `%t' expected `%t'\n",
+ e->type, ty);
+ e = retype(consttree(0, inttype), ty);
+ }
+ needconst--;
+ if (generic(e->op) != CNST) {
+ error("initializer must be constant\n");
+ e = retype(consttree(0, inttype), ty);
+ }
+ return e;
+}
+
+/* initarray - initialize array of ty of <= len bytes; if len == 0, go to } */
+static int initarray(int len, Type ty, int lev) {
+ int n = 0;
+
+ do {
+ initializer(ty, lev);
+ n += ty->size;
+ if (len > 0 && n >= len || t != ',')
+ break;
+ t = gettok();
+ } while (t != '}');
+ return n;
+}
+
+/* initchar - initialize array of <= len ty characters; if len == 0, go to } */
+static int initchar(int len, Type ty) {
+ int n = 0;
+ char buf[16], *s = buf;
+
+ do {
+ *s++ = initvalue(ty)->u.v.i;
+ if (++n%inttype->size == 0) {
+ (*IR->defstring)(inttype->size, buf);
+ s = buf;
+ }
+ if (len > 0 && n >= len || t != ',')
+ break;
+ t = gettok();
+ } while (t != '}');
+ if (s > buf)
+ (*IR->defstring)(s - buf, buf);
+ return n;
+}
+
+/* initend - finish off an initialization at level lev; accepts trailing comma */
+static void initend(int lev, char follow[]) {
+ if (lev == 0 && t == ',')
+ t = gettok();
+ test('}', follow);
+}
+
+/* initfields - initialize <= an unsigned's worth of bit fields in fields p to q */
+static int initfields(Field p, Field q) {
+ unsigned int bits = 0;
+ int i, n = 0;
+
+ do {
+ i = initvalue(inttype)->u.v.i;
+ if (fieldsize(p) < 8*p->type->size) {
+ if (p->type == inttype &&
+ (i < -(int)(fieldmask(p)>>1)-1 || i > (int)(fieldmask(p)>>1))
+ || p->type == unsignedtype && (i&~fieldmask(p)) != 0)
+ warning("initializer exceeds bit-field width\n");
+ i &= fieldmask(p);
+ }
+ bits |= i<<fieldright(p);
+ if (IR->little_endian) {
+ if (fieldsize(p) + fieldright(p) > n)
+ n = fieldsize(p) + fieldright(p);
+ } else {
+ if (fieldsize(p) + fieldleft(p) > n)
+ n = fieldsize(p) + fieldleft(p);
+ }
+ if (p->link == q)
+ break;
+ p = p->link;
+ } while (t == ',' && (t = gettok()) != 0);
+ n = (n + 7)/8;
+ for (i = 0; i < n; i++) {
+ Value v;
+ if (IR->little_endian) {
+ v.u = (unsigned char)bits;
+ bits >>= 8;
+ } else { /* a big endian */
+ v.u = (unsigned char)(bits>>(8*(unsignedtype->size - 1)));
+ bits <<= 8;
+ }
+ (*IR->defconst)(U, unsignedchar->size, v);
+ }
+ return n;
+}
+
+/* initstruct - initialize a struct ty of <= len bytes; if len == 0, go to } */
+static int initstruct(int len, Type ty, int lev) {
+ int a, n = 0;
+ Field p = ty->u.sym->u.s.flist;
+
+ do {
+ if (p->offset > n) {
+ (*IR->space)(p->offset - n);
+ n += p->offset - n;
+ }
+ if (p->lsb) {
+ Field q = p;
+ while (q->link && q->link->offset == p->offset)
+ q = q->link;
+ n += initfields(p, q->link);
+ p = q;
+ } else {
+ initializer(p->type, lev);
+ n += p->type->size;
+ }
+ if (p->link) {
+ p = p->link;
+ a = p->type->align;
+ } else
+ a = ty->align;
+ if (a && n%a) {
+ (*IR->space)(a - n%a);
+ n = roundup(n, a);
+ }
+ if (len > 0 && n >= len || t != ',')
+ break;
+ t = gettok();
+ } while (t != '}');
+ return n;
+}
+
+/* initializer - constexpr | { constexpr ( , constexpr )* [ , ] } */
+Type initializer(Type ty, int lev) {
+ int n = 0;
+ Tree e;
+ Type aty = NULL;
+ static char follow[] = { IF, CHAR, STATIC, 0 };
+
+ ty = unqual(ty);
+ if (isscalar(ty)) {
+ needconst++;
+ if (t == '{') {
+ t = gettok();
+ e = expr1(0);
+ initend(lev, follow);
+ } else
+ e = expr1(0);
+ e = pointer(e);
+ if ((aty = assign(ty, e)) != NULL)
+ e = cast(e, aty);
+ else
+ error("invalid initialization type; found `%t' expected `%t'\n",
+ e->type, ty);
+ n = genconst(e, 1);
+ deallocate(STMT);
+ needconst--;
+ }
+ if ((isunion(ty) || isstruct(ty)) && ty->size == 0) {
+ static char follow[] = { CHAR, STATIC, 0 };
+ error("cannot initialize undefined `%t'\n", ty);
+ skipto(';', follow);
+ return ty;
+ } else if (isunion(ty)) {
+ if (t == '{') {
+ t = gettok();
+ n = initstruct(ty->u.sym->u.s.flist->type->size, ty, lev + 1);
+ initend(lev, follow);
+ } else {
+ if (lev == 0)
+ error("missing { in initialization of `%t'\n", ty);
+ n = initstruct(ty->u.sym->u.s.flist->type->size, ty, lev + 1);
+ }
+ } else if (isstruct(ty)) {
+ if (t == '{') {
+ t = gettok();
+ n = initstruct(0, ty, lev + 1);
+ test('}', follow);
+ } else if (lev > 0)
+ n = initstruct(ty->size, ty, lev + 1);
+ else {
+ error("missing { in initialization of `%t'\n", ty);
+ n = initstruct(ty->u.sym->u.s.flist->type->size, ty, lev + 1);
+ }
+ }
+ if (isarray(ty))
+ aty = unqual(ty->type);
+ if (isarray(ty) && ischar(aty)) {
+ if (t == SCON) {
+ if (ty->size > 0 && ty->size == tsym->type->size - 1)
+ tsym->type = array(chartype, ty->size, 0);
+ n = tsym->type->size;
+ (*IR->defstring)(tsym->type->size, tsym->u.c.v.p);
+ t = gettok();
+ } else if (t == '{') {
+ t = gettok();
+ if (t == SCON) {
+ ty = initializer(ty, lev + 1);
+ initend(lev, follow);
+ return ty;
+ }
+ n = initchar(0, aty);
+ test('}', follow);
+ } else if (lev > 0 && ty->size > 0)
+ n = initchar(ty->size, aty);
+ else { /* eg, char c[] = 0; */
+ error("missing { in initialization of `%t'\n", ty);
+ n = initchar(1, aty);
+ }
+ } else if (isarray(ty)) {
+ if (t == SCON && aty == widechar) {
+ int i;
+ unsigned int *s = tsym->u.c.v.p;
+ if (ty->size > 0 && ty->size == tsym->type->size - widechar->size)
+ tsym->type = array(widechar, ty->size/widechar->size, 0);
+ n = tsym->type->size;
+ for (i = 0; i < n; i += widechar->size) {
+ Value v;
+ v.u = *s++;
+ (*IR->defconst)(widechar->op, widechar->size, v);
+ }
+ t = gettok();
+ } else if (t == '{') {
+ t = gettok();
+ if (t == SCON && aty == widechar) {
+ ty = initializer(ty, lev + 1);
+ initend(lev, follow);
+ return ty;
+ }
+ n = initarray(0, aty, lev + 1);
+ test('}', follow);
+ } else if (lev > 0 && ty->size > 0)
+ n = initarray(ty->size, aty, lev + 1);
+ else {
+ error("missing { in initialization of `%t'\n", ty);
+ n = initarray(aty->size, aty, lev + 1);
+ }
+ }
+ if (ty->size) {
+ if (n > ty->size)
+ error("too many initializers\n");
+ else if (n < ty->size)
+ (*IR->space)(ty->size - n);
+ } else if (isarray(ty) && ty->type->size > 0)
+ ty = array(ty->type, n/ty->type->size, 0);
+ else
+ ty->size = n;
+ return ty;
+}
+
+/* swtoseg - switch to segment seg, if necessary */
+void swtoseg(int seg) {
+ if (curseg != seg)
+ (*IR->segment)(seg);
+ curseg = seg;
+}
diff --git a/lcc/src/inits.c b/lcc/src/inits.c
new file mode 100755
index 0000000..d4d49df
--- /dev/null
+++ b/lcc/src/inits.c
@@ -0,0 +1,8 @@
+void init(int argc, char *argv[]) {
+ {extern void input_init(int, char *[]); input_init(argc, argv);}
+ {extern void main_init(int, char *[]); main_init(argc, argv);}
+ {extern void prof_init(int, char *[]); prof_init(argc, argv);}
+ {extern void trace_init(int, char *[]); trace_init(argc, argv);}
+ {extern void type_init(int, char *[]); type_init(argc, argv);}
+ {extern void x86linux_init(int, char *[]); x86linux_init(argc, argv);}
+}
diff --git a/lcc/src/input.c b/lcc/src/input.c
new file mode 100755
index 0000000..2f34420
--- /dev/null
+++ b/lcc/src/input.c
@@ -0,0 +1,134 @@
+#include "c.h"
+
+
+static void pragma(void);
+static void resynch(void);
+
+static int bsize;
+static unsigned char buffer[MAXLINE+1 + BUFSIZE+1];
+unsigned char *cp; /* current input character */
+char *file; /* current input file name */
+char *firstfile; /* first input file */
+unsigned char *limit; /* points to last character + 1 */
+char *line; /* current line */
+int lineno; /* line number of current line */
+
+void nextline(void) {
+ do {
+ if (cp >= limit) {
+ fillbuf();
+ if (cp >= limit)
+ cp = limit;
+ if (cp == limit)
+ return;
+ } else {
+ lineno++;
+ for (line = (char *)cp; *cp==' ' || *cp=='\t'; cp++)
+ ;
+ if (*cp == '#') {
+ resynch();
+ nextline();
+ }
+ }
+ } while (*cp == '\n' && cp == limit);
+}
+void fillbuf(void) {
+ if (bsize == 0)
+ return;
+ if (cp >= limit)
+ cp = &buffer[MAXLINE+1];
+ else
+ {
+ int n = limit - cp;
+ unsigned char *s = &buffer[MAXLINE+1] - n;
+ assert(s >= buffer);
+ line = (char *)s - ((char *)cp - line);
+ while (cp < limit)
+ *s++ = *cp++;
+ cp = &buffer[MAXLINE+1] - n;
+ }
+ if (feof(stdin))
+ bsize = 0;
+ else
+ bsize = fread(&buffer[MAXLINE+1], 1, BUFSIZE, stdin);
+ if (bsize < 0) {
+ error("read error\n");
+ exit(EXIT_FAILURE);
+ }
+ limit = &buffer[MAXLINE+1+bsize];
+ *limit = '\n';
+}
+void input_init(int argc, char *argv[]) {
+ static int inited;
+
+ if (inited)
+ return;
+ inited = 1;
+ main_init(argc, argv);
+ limit = cp = &buffer[MAXLINE+1];
+ bsize = -1;
+ lineno = 0;
+ file = NULL;
+ fillbuf();
+ if (cp >= limit)
+ cp = limit;
+ nextline();
+}
+
+/* pragma - handle #pragma ref id... */
+static void pragma(void) {
+ if ((t = gettok()) == ID && strcmp(token, "ref") == 0)
+ for (;;) {
+ while (*cp == ' ' || *cp == '\t')
+ cp++;
+ if (*cp == '\n' || *cp == 0)
+ break;
+ if ((t = gettok()) == ID && tsym) {
+ tsym->ref++;
+ use(tsym, src);
+ }
+ }
+}
+
+/* resynch - set line number/file name in # n [ "file" ] and #pragma ... */
+static void resynch(void) {
+ for (cp++; *cp == ' ' || *cp == '\t'; )
+ cp++;
+ if (limit - cp < MAXLINE)
+ fillbuf();
+ if (strncmp((char *)cp, "pragma", 6) == 0) {
+ cp += 6;
+ pragma();
+ } else if (*cp >= '0' && *cp <= '9') {
+ line: for (lineno = 0; *cp >= '0' && *cp <= '9'; )
+ lineno = 10*lineno + *cp++ - '0';
+ lineno--;
+ while (*cp == ' ' || *cp == '\t')
+ cp++;
+ if (*cp == '"') {
+ file = (char *)++cp;
+ while (*cp && *cp != '"' && *cp != '\n')
+ cp++;
+ file = stringn(file, (char *)cp - file);
+ if (*cp == '\n')
+ warning("missing \" in preprocessor line\n");
+ if (firstfile == 0)
+ firstfile = file;
+ }
+ } else if (strncmp((char *)cp, "line", 4) == 0) {
+ for (cp += 4; *cp == ' ' || *cp == '\t'; )
+ cp++;
+ if (*cp >= '0' && *cp <= '9')
+ goto line;
+ if (Aflag >= 2)
+ warning("unrecognized control line\n");
+ } else if (Aflag >= 2 && *cp != '\n')
+ warning("unrecognized control line\n");
+ while (*cp)
+ if (*cp++ == '\n')
+ if (cp == limit + 1)
+ nextline();
+ else
+ break;
+}
+
diff --git a/lcc/src/lex.c b/lcc/src/lex.c
new file mode 100755
index 0000000..09c50f3
--- /dev/null
+++ b/lcc/src/lex.c
@@ -0,0 +1,922 @@
+#include "c.h"
+#include <float.h>
+#include <errno.h>
+
+
+#define MAXTOKEN 32
+
+enum { BLANK=01, NEWLINE=02, LETTER=04,
+ DIGIT=010, HEX=020, OTHER=040 };
+
+static unsigned char map[256] = { /* 000 nul */ 0,
+ /* 001 soh */ 0,
+ /* 002 stx */ 0,
+ /* 003 etx */ 0,
+ /* 004 eot */ 0,
+ /* 005 enq */ 0,
+ /* 006 ack */ 0,
+ /* 007 bel */ 0,
+ /* 010 bs */ 0,
+ /* 011 ht */ BLANK,
+ /* 012 nl */ NEWLINE,
+ /* 013 vt */ BLANK,
+ /* 014 ff */ BLANK,
+ /* 015 cr */ 0,
+ /* 016 so */ 0,
+ /* 017 si */ 0,
+ /* 020 dle */ 0,
+ /* 021 dc1 */ 0,
+ /* 022 dc2 */ 0,
+ /* 023 dc3 */ 0,
+ /* 024 dc4 */ 0,
+ /* 025 nak */ 0,
+ /* 026 syn */ 0,
+ /* 027 etb */ 0,
+ /* 030 can */ 0,
+ /* 031 em */ 0,
+ /* 032 sub */ 0,
+ /* 033 esc */ 0,
+ /* 034 fs */ 0,
+ /* 035 gs */ 0,
+ /* 036 rs */ 0,
+ /* 037 us */ 0,
+ /* 040 sp */ BLANK,
+ /* 041 ! */ OTHER,
+ /* 042 " */ OTHER,
+ /* 043 # */ OTHER,
+ /* 044 $ */ 0,
+ /* 045 % */ OTHER,
+ /* 046 & */ OTHER,
+ /* 047 ' */ OTHER,
+ /* 050 ( */ OTHER,
+ /* 051 ) */ OTHER,
+ /* 052 * */ OTHER,
+ /* 053 + */ OTHER,
+ /* 054 , */ OTHER,
+ /* 055 - */ OTHER,
+ /* 056 . */ OTHER,
+ /* 057 / */ OTHER,
+ /* 060 0 */ DIGIT,
+ /* 061 1 */ DIGIT,
+ /* 062 2 */ DIGIT,
+ /* 063 3 */ DIGIT,
+ /* 064 4 */ DIGIT,
+ /* 065 5 */ DIGIT,
+ /* 066 6 */ DIGIT,
+ /* 067 7 */ DIGIT,
+ /* 070 8 */ DIGIT,
+ /* 071 9 */ DIGIT,
+ /* 072 : */ OTHER,
+ /* 073 ; */ OTHER,
+ /* 074 < */ OTHER,
+ /* 075 = */ OTHER,
+ /* 076 > */ OTHER,
+ /* 077 ? */ OTHER,
+ /* 100 @ */ 0,
+ /* 101 A */ LETTER|HEX,
+ /* 102 B */ LETTER|HEX,
+ /* 103 C */ LETTER|HEX,
+ /* 104 D */ LETTER|HEX,
+ /* 105 E */ LETTER|HEX,
+ /* 106 F */ LETTER|HEX,
+ /* 107 G */ LETTER,
+ /* 110 H */ LETTER,
+ /* 111 I */ LETTER,
+ /* 112 J */ LETTER,
+ /* 113 K */ LETTER,
+ /* 114 L */ LETTER,
+ /* 115 M */ LETTER,
+ /* 116 N */ LETTER,
+ /* 117 O */ LETTER,
+ /* 120 P */ LETTER,
+ /* 121 Q */ LETTER,
+ /* 122 R */ LETTER,
+ /* 123 S */ LETTER,
+ /* 124 T */ LETTER,
+ /* 125 U */ LETTER,
+ /* 126 V */ LETTER,
+ /* 127 W */ LETTER,
+ /* 130 X */ LETTER,
+ /* 131 Y */ LETTER,
+ /* 132 Z */ LETTER,
+ /* 133 [ */ OTHER,
+ /* 134 \ */ OTHER,
+ /* 135 ] */ OTHER,
+ /* 136 ^ */ OTHER,
+ /* 137 _ */ LETTER,
+ /* 140 ` */ 0,
+ /* 141 a */ LETTER|HEX,
+ /* 142 b */ LETTER|HEX,
+ /* 143 c */ LETTER|HEX,
+ /* 144 d */ LETTER|HEX,
+ /* 145 e */ LETTER|HEX,
+ /* 146 f */ LETTER|HEX,
+ /* 147 g */ LETTER,
+ /* 150 h */ LETTER,
+ /* 151 i */ LETTER,
+ /* 152 j */ LETTER,
+ /* 153 k */ LETTER,
+ /* 154 l */ LETTER,
+ /* 155 m */ LETTER,
+ /* 156 n */ LETTER,
+ /* 157 o */ LETTER,
+ /* 160 p */ LETTER,
+ /* 161 q */ LETTER,
+ /* 162 r */ LETTER,
+ /* 163 s */ LETTER,
+ /* 164 t */ LETTER,
+ /* 165 u */ LETTER,
+ /* 166 v */ LETTER,
+ /* 167 w */ LETTER,
+ /* 170 x */ LETTER,
+ /* 171 y */ LETTER,
+ /* 172 z */ LETTER,
+ /* 173 { */ OTHER,
+ /* 174 | */ OTHER,
+ /* 175 } */ OTHER,
+ /* 176 ~ */ OTHER, };
+static struct symbol tval;
+static char cbuf[BUFSIZE+1];
+static unsigned int wcbuf[BUFSIZE+1];
+
+Coordinate src; /* current source coordinate */
+int t;
+char *token; /* current token */
+Symbol tsym; /* symbol table entry for current token */
+
+static void *cput(int c, void *cl);
+static void *wcput(int c, void *cl);
+static void *scon(int q, void *put(int c, void *cl), void *cl);
+static int backslash(int q);
+static Symbol fcon(void);
+static Symbol icon(unsigned long, int, int);
+static void ppnumber(char *);
+
+int gettok(void) {
+ for (;;) {
+ register unsigned char *rcp = cp;
+ while (map[*rcp]&BLANK)
+ rcp++;
+ if (limit - rcp < MAXTOKEN) {
+ cp = rcp;
+ fillbuf();
+ rcp = cp;
+ }
+ src.file = file;
+ src.x = (char *)rcp - line;
+ src.y = lineno;
+ cp = rcp + 1;
+ switch (*rcp++) {
+ case '/': if (*rcp == '*') {
+ int c = 0;
+ for (rcp++; *rcp != '/' || c != '*'; )
+ if (map[*rcp]&NEWLINE) {
+ if (rcp < limit)
+ c = *rcp;
+ cp = rcp + 1;
+ nextline();
+ rcp = cp;
+ if (rcp == limit)
+ break;
+ } else
+ c = *rcp++;
+ if (rcp < limit)
+ rcp++;
+ else
+ error("unclosed comment\n");
+ cp = rcp;
+ continue;
+ }
+ return '/';
+ case '<':
+ if (*rcp == '=') return cp++, LEQ;
+ if (*rcp == '<') return cp++, LSHIFT;
+ return '<';
+ case '>':
+ if (*rcp == '=') return cp++, GEQ;
+ if (*rcp == '>') return cp++, RSHIFT;
+ return '>';
+ case '-':
+ if (*rcp == '>') return cp++, DEREF;
+ if (*rcp == '-') return cp++, DECR;
+ return '-';
+ case '=': return *rcp == '=' ? cp++, EQL : '=';
+ case '!': return *rcp == '=' ? cp++, NEQ : '!';
+ case '|': return *rcp == '|' ? cp++, OROR : '|';
+ case '&': return *rcp == '&' ? cp++, ANDAND : '&';
+ case '+': return *rcp == '+' ? cp++, INCR : '+';
+ case ';': case ',': case ':':
+ case '*': case '~': case '%': case '^': case '?':
+ case '[': case ']': case '{': case '}': case '(': case ')':
+ return rcp[-1];
+ case '\n': case '\v': case '\r': case '\f':
+ nextline();
+ if (cp == limit) {
+ tsym = NULL;
+ return EOI;
+ }
+ continue;
+
+ case 'i':
+ if (rcp[0] == 'f'
+ && !(map[rcp[1]]&(DIGIT|LETTER))) {
+ cp = rcp + 1;
+ return IF;
+ }
+ if (rcp[0] == 'n'
+ && rcp[1] == 't'
+ && !(map[rcp[2]]&(DIGIT|LETTER))) {
+ cp = rcp + 2;
+ tsym = inttype->u.sym;
+ return INT;
+ }
+ goto id;
+ case 'h': case 'j': case 'k': case 'm': case 'n': case 'o':
+ case 'p': case 'q': case 'x': case 'y': case 'z':
+ case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
+ case 'G': case 'H': case 'I': case 'J': case 'K':
+ case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
+ case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
+ case 'Y': case 'Z':
+ id:
+ if (limit - rcp < MAXLINE) {
+ cp = rcp - 1;
+ fillbuf();
+ rcp = ++cp;
+ }
+ assert(cp == rcp);
+ token = (char *)rcp - 1;
+ while (map[*rcp]&(DIGIT|LETTER))
+ rcp++;
+ token = stringn(token, (char *)rcp - token);
+ tsym = lookup(token, identifiers);
+ cp = rcp;
+ return ID;
+ case '0': case '1': case '2': case '3': case '4':
+ case '5': case '6': case '7': case '8': case '9': {
+ unsigned long n = 0;
+ if (limit - rcp < MAXLINE) {
+ cp = rcp - 1;
+ fillbuf();
+ rcp = ++cp;
+ }
+ assert(cp == rcp);
+ token = (char *)rcp - 1;
+ if (*token == '0' && (*rcp == 'x' || *rcp == 'X')) {
+ int d, overflow = 0;
+ while (*++rcp) {
+ if (map[*rcp]&DIGIT)
+ d = *rcp - '0';
+ else if (*rcp >= 'a' && *rcp <= 'f')
+ d = *rcp - 'a' + 10;
+ else if (*rcp >= 'A' && *rcp <= 'F')
+ d = *rcp - 'A' + 10;
+ else
+ break;
+ if (n&~(~0UL >> 4))
+ overflow = 1;
+ else
+ n = (n<<4) + d;
+ }
+ if ((char *)rcp - token <= 2)
+ error("invalid hexadecimal constant `%S'\n", token, (char *)rcp-token);
+ cp = rcp;
+ tsym = icon(n, overflow, 16);
+ } else if (*token == '0') {
+ int err = 0, overflow = 0;
+ for ( ; map[*rcp]&DIGIT; rcp++) {
+ if (*rcp == '8' || *rcp == '9')
+ err = 1;
+ if (n&~(~0UL >> 3))
+ overflow = 1;
+ else
+ n = (n<<3) + (*rcp - '0');
+ }
+ if (*rcp == '.' || *rcp == 'e' || *rcp == 'E') {
+ cp = rcp;
+ tsym = fcon();
+ return FCON;
+ }
+ cp = rcp;
+ tsym = icon(n, overflow, 8);
+ if (err)
+ error("invalid octal constant `%S'\n", token, (char*)cp-token);
+ } else {
+ int overflow = 0;
+ for (n = *token - '0'; map[*rcp]&DIGIT; ) {
+ int d = *rcp++ - '0';
+ if (n > (ULONG_MAX - d)/10)
+ overflow = 1;
+ else
+ n = 10*n + d;
+ }
+ if (*rcp == '.' || *rcp == 'e' || *rcp == 'E') {
+ cp = rcp;
+ tsym = fcon();
+ return FCON;
+ }
+ cp = rcp;
+ tsym = icon(n, overflow, 10);
+ }
+ return ICON;
+ }
+ case '.':
+ if (rcp[0] == '.' && rcp[1] == '.') {
+ cp += 2;
+ return ELLIPSIS;
+ }
+ if ((map[*rcp]&DIGIT) == 0)
+ return '.';
+ if (limit - rcp < MAXLINE) {
+ cp = rcp - 1;
+ fillbuf();
+ rcp = ++cp;
+ }
+ assert(cp == rcp);
+ cp = rcp - 1;
+ token = (char *)cp;
+ tsym = fcon();
+ return FCON;
+ case 'L':
+ if (*rcp == '\'') {
+ unsigned int *s = scon(*cp, wcput, wcbuf);
+ if (s - wcbuf > 2)
+ warning("excess characters in wide-character literal ignored\n");
+ tval.type = widechar;
+ tval.u.c.v.u = wcbuf[0];
+ tsym = &tval;
+ return ICON;
+ } else if (*rcp == '"') {
+ unsigned int *s = scon(*cp, wcput, wcbuf);
+ tval.type = array(widechar, s - wcbuf, 0);
+ tval.u.c.v.p = wcbuf;
+ tsym = &tval;
+ return SCON;
+ } else
+ goto id;
+ case '\'': {
+ char *s = scon(*--cp, cput, cbuf);
+ if (s - cbuf > 2)
+ warning("excess characters in multibyte character literal ignored\n");
+ tval.type = inttype;
+ if (chartype->op == INT)
+ tval.u.c.v.i = extend(cbuf[0], chartype);
+ else
+ tval.u.c.v.i = cbuf[0]&0xFF;
+ tsym = &tval;
+ return ICON;
+ }
+ case '"': {
+ char *s = scon(*--cp, cput, cbuf);
+ tval.type = array(chartype, s - cbuf, 0);
+ tval.u.c.v.p = cbuf;
+ tsym = &tval;
+ return SCON;
+ }
+ case 'a':
+ if (rcp[0] == 'u'
+ && rcp[1] == 't'
+ && rcp[2] == 'o'
+ && !(map[rcp[3]]&(DIGIT|LETTER))) {
+ cp = rcp + 3;
+ return AUTO;
+ }
+ goto id;
+ case 'b':
+ if (rcp[0] == 'r'
+ && rcp[1] == 'e'
+ && rcp[2] == 'a'
+ && rcp[3] == 'k'
+ && !(map[rcp[4]]&(DIGIT|LETTER))) {
+ cp = rcp + 4;
+ return BREAK;
+ }
+ goto id;
+ case 'c':
+ if (rcp[0] == 'a'
+ && rcp[1] == 's'
+ && rcp[2] == 'e'
+ && !(map[rcp[3]]&(DIGIT|LETTER))) {
+ cp = rcp + 3;
+ return CASE;
+ }
+ if (rcp[0] == 'h'
+ && rcp[1] == 'a'
+ && rcp[2] == 'r'
+ && !(map[rcp[3]]&(DIGIT|LETTER))) {
+ cp = rcp + 3;
+ tsym = chartype->u.sym;
+ return CHAR;
+ }
+ if (rcp[0] == 'o'
+ && rcp[1] == 'n'
+ && rcp[2] == 's'
+ && rcp[3] == 't'
+ && !(map[rcp[4]]&(DIGIT|LETTER))) {
+ cp = rcp + 4;
+ return CONST;
+ }
+ if (rcp[0] == 'o'
+ && rcp[1] == 'n'
+ && rcp[2] == 't'
+ && rcp[3] == 'i'
+ && rcp[4] == 'n'
+ && rcp[5] == 'u'
+ && rcp[6] == 'e'
+ && !(map[rcp[7]]&(DIGIT|LETTER))) {
+ cp = rcp + 7;
+ return CONTINUE;
+ }
+ goto id;
+ case 'd':
+ if (rcp[0] == 'e'
+ && rcp[1] == 'f'
+ && rcp[2] == 'a'
+ && rcp[3] == 'u'
+ && rcp[4] == 'l'
+ && rcp[5] == 't'
+ && !(map[rcp[6]]&(DIGIT|LETTER))) {
+ cp = rcp + 6;
+ return DEFAULT;
+ }
+ if (rcp[0] == 'o'
+ && rcp[1] == 'u'
+ && rcp[2] == 'b'
+ && rcp[3] == 'l'
+ && rcp[4] == 'e'
+ && !(map[rcp[5]]&(DIGIT|LETTER))) {
+ cp = rcp + 5;
+ tsym = doubletype->u.sym;
+ return DOUBLE;
+ }
+ if (rcp[0] == 'o'
+ && !(map[rcp[1]]&(DIGIT|LETTER))) {
+ cp = rcp + 1;
+ return DO;
+ }
+ goto id;
+ case 'e':
+ if (rcp[0] == 'l'
+ && rcp[1] == 's'
+ && rcp[2] == 'e'
+ && !(map[rcp[3]]&(DIGIT|LETTER))) {
+ cp = rcp + 3;
+ return ELSE;
+ }
+ if (rcp[0] == 'n'
+ && rcp[1] == 'u'
+ && rcp[2] == 'm'
+ && !(map[rcp[3]]&(DIGIT|LETTER))) {
+ cp = rcp + 3;
+ return ENUM;
+ }
+ if (rcp[0] == 'x'
+ && rcp[1] == 't'
+ && rcp[2] == 'e'
+ && rcp[3] == 'r'
+ && rcp[4] == 'n'
+ && !(map[rcp[5]]&(DIGIT|LETTER))) {
+ cp = rcp + 5;
+ return EXTERN;
+ }
+ goto id;
+ case 'f':
+ if (rcp[0] == 'l'
+ && rcp[1] == 'o'
+ && rcp[2] == 'a'
+ && rcp[3] == 't'
+ && !(map[rcp[4]]&(DIGIT|LETTER))) {
+ cp = rcp + 4;
+ tsym = floattype->u.sym;
+ return FLOAT;
+ }
+ if (rcp[0] == 'o'
+ && rcp[1] == 'r'
+ && !(map[rcp[2]]&(DIGIT|LETTER))) {
+ cp = rcp + 2;
+ return FOR;
+ }
+ goto id;
+ case 'g':
+ if (rcp[0] == 'o'
+ && rcp[1] == 't'
+ && rcp[2] == 'o'
+ && !(map[rcp[3]]&(DIGIT|LETTER))) {
+ cp = rcp + 3;
+ return GOTO;
+ }
+ goto id;
+ case 'l':
+ if (rcp[0] == 'o'
+ && rcp[1] == 'n'
+ && rcp[2] == 'g'
+ && !(map[rcp[3]]&(DIGIT|LETTER))) {
+ cp = rcp + 3;
+ return LONG;
+ }
+ goto id;
+ case 'r':
+ if (rcp[0] == 'e'
+ && rcp[1] == 'g'
+ && rcp[2] == 'i'
+ && rcp[3] == 's'
+ && rcp[4] == 't'
+ && rcp[5] == 'e'
+ && rcp[6] == 'r'
+ && !(map[rcp[7]]&(DIGIT|LETTER))) {
+ cp = rcp + 7;
+ return REGISTER;
+ }
+ if (rcp[0] == 'e'
+ && rcp[1] == 't'
+ && rcp[2] == 'u'
+ && rcp[3] == 'r'
+ && rcp[4] == 'n'
+ && !(map[rcp[5]]&(DIGIT|LETTER))) {
+ cp = rcp + 5;
+ return RETURN;
+ }
+ goto id;
+ case 's':
+ if (rcp[0] == 'h'
+ && rcp[1] == 'o'
+ && rcp[2] == 'r'
+ && rcp[3] == 't'
+ && !(map[rcp[4]]&(DIGIT|LETTER))) {
+ cp = rcp + 4;
+ return SHORT;
+ }
+ if (rcp[0] == 'i'
+ && rcp[1] == 'g'
+ && rcp[2] == 'n'
+ && rcp[3] == 'e'
+ && rcp[4] == 'd'
+ && !(map[rcp[5]]&(DIGIT|LETTER))) {
+ cp = rcp + 5;
+ return SIGNED;
+ }
+ if (rcp[0] == 'i'
+ && rcp[1] == 'z'
+ && rcp[2] == 'e'
+ && rcp[3] == 'o'
+ && rcp[4] == 'f'
+ && !(map[rcp[5]]&(DIGIT|LETTER))) {
+ cp = rcp + 5;
+ return SIZEOF;
+ }
+ if (rcp[0] == 't'
+ && rcp[1] == 'a'
+ && rcp[2] == 't'
+ && rcp[3] == 'i'
+ && rcp[4] == 'c'
+ && !(map[rcp[5]]&(DIGIT|LETTER))) {
+ cp = rcp + 5;
+ return STATIC;
+ }
+ if (rcp[0] == 't'
+ && rcp[1] == 'r'
+ && rcp[2] == 'u'
+ && rcp[3] == 'c'
+ && rcp[4] == 't'
+ && !(map[rcp[5]]&(DIGIT|LETTER))) {
+ cp = rcp + 5;
+ return STRUCT;
+ }
+ if (rcp[0] == 'w'
+ && rcp[1] == 'i'
+ && rcp[2] == 't'
+ && rcp[3] == 'c'
+ && rcp[4] == 'h'
+ && !(map[rcp[5]]&(DIGIT|LETTER))) {
+ cp = rcp + 5;
+ return SWITCH;
+ }
+ goto id;
+ case 't':
+ if (rcp[0] == 'y'
+ && rcp[1] == 'p'
+ && rcp[2] == 'e'
+ && rcp[3] == 'd'
+ && rcp[4] == 'e'
+ && rcp[5] == 'f'
+ && !(map[rcp[6]]&(DIGIT|LETTER))) {
+ cp = rcp + 6;
+ return TYPEDEF;
+ }
+ goto id;
+ case 'u':
+ if (rcp[0] == 'n'
+ && rcp[1] == 'i'
+ && rcp[2] == 'o'
+ && rcp[3] == 'n'
+ && !(map[rcp[4]]&(DIGIT|LETTER))) {
+ cp = rcp + 4;
+ return UNION;
+ }
+ if (rcp[0] == 'n'
+ && rcp[1] == 's'
+ && rcp[2] == 'i'
+ && rcp[3] == 'g'
+ && rcp[4] == 'n'
+ && rcp[5] == 'e'
+ && rcp[6] == 'd'
+ && !(map[rcp[7]]&(DIGIT|LETTER))) {
+ cp = rcp + 7;
+ return UNSIGNED;
+ }
+ goto id;
+ case 'v':
+ if (rcp[0] == 'o'
+ && rcp[1] == 'i'
+ && rcp[2] == 'd'
+ && !(map[rcp[3]]&(DIGIT|LETTER))) {
+ cp = rcp + 3;
+ tsym = voidtype->u.sym;
+ return VOID;
+ }
+ if (rcp[0] == 'o'
+ && rcp[1] == 'l'
+ && rcp[2] == 'a'
+ && rcp[3] == 't'
+ && rcp[4] == 'i'
+ && rcp[5] == 'l'
+ && rcp[6] == 'e'
+ && !(map[rcp[7]]&(DIGIT|LETTER))) {
+ cp = rcp + 7;
+ return VOLATILE;
+ }
+ goto id;
+ case 'w':
+ if (rcp[0] == 'h'
+ && rcp[1] == 'i'
+ && rcp[2] == 'l'
+ && rcp[3] == 'e'
+ && !(map[rcp[4]]&(DIGIT|LETTER))) {
+ cp = rcp + 4;
+ return WHILE;
+ }
+ goto id;
+ case '_':
+ if (rcp[0] == '_'
+ && rcp[1] == 't'
+ && rcp[2] == 'y'
+ && rcp[3] == 'p'
+ && rcp[4] == 'e'
+ && rcp[5] == 'c'
+ && rcp[6] == 'o'
+ && rcp[7] == 'd'
+ && rcp[8] == 'e'
+ && !(map[rcp[9]]&(DIGIT|LETTER))) {
+ cp = rcp + 9;
+ return TYPECODE;
+ }
+ if (rcp[0] == '_'
+ && rcp[1] == 'f'
+ && rcp[2] == 'i'
+ && rcp[3] == 'r'
+ && rcp[4] == 's'
+ && rcp[5] == 't'
+ && rcp[6] == 'a'
+ && rcp[7] == 'r'
+ && rcp[8] == 'g'
+ && !(map[rcp[9]]&(DIGIT|LETTER))) {
+ cp = rcp + 9;
+ return FIRSTARG;
+ }
+ goto id;
+ default:
+ if ((map[cp[-1]]&BLANK) == 0)
+ if (cp[-1] < ' ' || cp[-1] >= 0177)
+ error("illegal character `\\0%o'\n", cp[-1]);
+ else
+ error("illegal character `%c'\n", cp[-1]);
+ }
+ }
+}
+static Symbol icon(unsigned long n, int overflow, int base) {
+ if ((*cp=='u'||*cp=='U') && (cp[1]=='l'||cp[1]=='L')
+ || (*cp=='l'||*cp=='L') && (cp[1]=='u'||cp[1]=='U')) {
+ tval.type = unsignedlong;
+ cp += 2;
+ } else if (*cp == 'u' || *cp == 'U') {
+ if (overflow || n > unsignedtype->u.sym->u.limits.max.i)
+ tval.type = unsignedlong;
+ else
+ tval.type = unsignedtype;
+ cp += 1;
+ } else if (*cp == 'l' || *cp == 'L') {
+ if (overflow || n > longtype->u.sym->u.limits.max.i)
+ tval.type = unsignedlong;
+ else
+ tval.type = longtype;
+ cp += 1;
+ } else if (overflow || n > longtype->u.sym->u.limits.max.i)
+ tval.type = unsignedlong;
+ else if (n > inttype->u.sym->u.limits.max.i)
+ tval.type = longtype;
+ else if (base != 10 && n > inttype->u.sym->u.limits.max.i)
+ tval.type = unsignedtype;
+ else
+ tval.type = inttype;
+ switch (tval.type->op) {
+ case INT:
+ if (overflow || n > tval.type->u.sym->u.limits.max.i) {
+ warning("overflow in constant `%S'\n", token,
+ (char*)cp - token);
+ tval.u.c.v.i = tval.type->u.sym->u.limits.max.i;
+ } else
+ tval.u.c.v.i = n;
+ break;
+ case UNSIGNED:
+ if (overflow || n > tval.type->u.sym->u.limits.max.u) {
+ warning("overflow in constant `%S'\n", token,
+ (char*)cp - token);
+ tval.u.c.v.u = tval.type->u.sym->u.limits.max.u;
+ } else
+ tval.u.c.v.u = n;
+ break;
+ default: assert(0);
+ }
+ ppnumber("integer");
+ return &tval;
+}
+static void ppnumber(char *which) {
+ unsigned char *rcp = cp--;
+
+ for ( ; (map[*cp]&(DIGIT|LETTER)) || *cp == '.'; cp++)
+ if ((cp[0] == 'E' || cp[0] == 'e')
+ && (cp[1] == '-' || cp[1] == '+'))
+ cp++;
+ if (cp > rcp)
+ error("`%S' is a preprocessing number but an invalid %s constant\n", token,
+
+ (char*)cp-token, which);
+}
+static Symbol fcon(void) {
+ if (*cp == '.')
+ do
+ cp++;
+ while (map[*cp]&DIGIT);
+ if (*cp == 'e' || *cp == 'E') {
+ if (*++cp == '-' || *cp == '+')
+ cp++;
+ if (map[*cp]&DIGIT)
+ do
+ cp++;
+ while (map[*cp]&DIGIT);
+ else
+ error("invalid floating constant `%S'\n", token,
+ (char*)cp - token);
+ }
+
+ errno = 0;
+ tval.u.c.v.d = strtod(token, NULL);
+ if (errno == ERANGE)
+ warning("overflow in floating constant `%S'\n", token,
+ (char*)cp - token);
+ if (*cp == 'f' || *cp == 'F') {
+ ++cp;
+ if (tval.u.c.v.d > floattype->u.sym->u.limits.max.d)
+ warning("overflow in floating constant `%S'\n", token,
+ (char*)cp - token);
+ tval.type = floattype;
+ } else if (*cp == 'l' || *cp == 'L') {
+ cp++;
+ tval.type = longdouble;
+ } else {
+ if (tval.u.c.v.d > doubletype->u.sym->u.limits.max.d)
+ warning("overflow in floating constant `%S'\n", token,
+ (char*)cp - token);
+ tval.type = doubletype;
+ }
+ ppnumber("floating");
+ return &tval;
+}
+
+static void *cput(int c, void *cl) {
+ char *s = cl;
+
+ if (c < 0 || c > 255)
+ warning("overflow in escape sequence with resulting value `%d'\n", c);
+ *s++ = c;
+ return s;
+}
+
+static void *wcput(int c, void *cl) {
+ unsigned int *s = cl;
+
+ *s++ = c;
+ return s;
+}
+
+static void *scon(int q, void *put(int c, void *cl), void *cl) {
+ int n = 0, nbad = 0;
+
+ do {
+ cp++;
+ while (*cp != q) {
+ int c;
+ if (map[*cp]&NEWLINE) {
+ if (cp < limit)
+ break;
+ cp++;
+ nextline();
+ if (cp == limit)
+ break;
+ continue;
+ }
+ c = *cp++;
+ if (c == '\\') {
+ if (map[*cp]&NEWLINE) {
+ if (cp < limit)
+ break;
+ cp++;
+ nextline();
+ }
+ if (limit - cp < MAXTOKEN)
+ fillbuf();
+ c = backslash(q);
+ } else if (c < 0 || c > 255 || map[c] == 0)
+ nbad++;
+ if (n++ < BUFSIZE)
+ cl = put(c, cl);
+ }
+ if (*cp == q)
+ cp++;
+ else
+ error("missing %c\n", q);
+ } while (q == '"' && getchr() == '"');
+ cl = put(0, cl);
+ if (n >= BUFSIZE)
+ error("%s literal too long\n", q == '"' ? "string" : "character");
+ if (Aflag >= 2 && q == '"' && n > 509)
+ warning("more than 509 characters in a string literal\n");
+ if (Aflag >= 2 && nbad > 0)
+ warning("%s literal contains non-portable characters\n",
+ q == '"' ? "string" : "character");
+ return cl;
+}
+int getchr(void) {
+ for (;;) {
+ while (map[*cp]&BLANK)
+ cp++;
+ if (!(map[*cp]&NEWLINE))
+ return *cp;
+ cp++;
+ nextline();
+ if (cp == limit)
+ return EOI;
+ }
+}
+static int backslash(int q) {
+ unsigned int c;
+
+ switch (*cp++) {
+ case 'a': return 7;
+ case 'b': return '\b';
+ case 'f': return '\f';
+ case 'n': return '\n';
+ case 'r': return '\r';
+ case 't': return '\t';
+ case 'v': return '\v';
+ case '\'': case '"': case '\\': case '\?': break;
+ case 'x': {
+ int overflow = 0;
+ if ((map[*cp]&(DIGIT|HEX)) == 0) {
+ if (*cp < ' ' || *cp == 0177)
+ error("ill-formed hexadecimal escape sequence\n");
+ else
+ error("ill-formed hexadecimal escape sequence `\\x%c'\n", *cp);
+ if (*cp != q)
+ cp++;
+ return 0;
+ }
+ for (c = 0; map[*cp]&(DIGIT|HEX); cp++) {
+ if (c >> (8*widechar->size - 4))
+ overflow = 1;
+ if (map[*cp]&DIGIT)
+ c = (c<<4) + *cp - '0';
+ else
+ c = (c<<4) + (*cp&~040) - 'A' + 10;
+ }
+ if (overflow)
+ warning("overflow in hexadecimal escape sequence\n");
+ return c&ones(8*widechar->size);
+ }
+ case '0': case '1': case '2': case '3':
+ case '4': case '5': case '6': case '7':
+ c = *(cp-1) - '0';
+ if (*cp >= '0' && *cp <= '7') {
+ c = (c<<3) + *cp++ - '0';
+ if (*cp >= '0' && *cp <= '7')
+ c = (c<<3) + *cp++ - '0';
+ }
+ return c;
+ default:
+ if (cp[-1] < ' ' || cp[-1] >= 0177)
+ warning("unrecognized character escape sequence\n");
+ else
+ warning("unrecognized character escape sequence `\\%c'\n", cp[-1]);
+ }
+ return cp[-1];
+}
diff --git a/lcc/src/list.c b/lcc/src/list.c
new file mode 100755
index 0000000..dbd63ed
--- /dev/null
+++ b/lcc/src/list.c
@@ -0,0 +1,56 @@
+#include "c.h"
+
+
+static List freenodes; /* free list nodes */
+
+/* append - append x to list, return new list */
+List append(void *x, List list) {
+ List new;
+
+ if ((new = freenodes) != NULL)
+ freenodes = freenodes->link;
+ else
+ NEW(new, PERM);
+ if (list) {
+ new->link = list->link;
+ list->link = new;
+ } else
+ new->link = new;
+ new->x = x;
+ return new;
+}
+
+/* length - # elements in list */
+int length(List list) {
+ int n = 0;
+
+ if (list) {
+ List lp = list;
+ do
+ n++;
+ while ((lp = lp->link) != list);
+ }
+ return n;
+}
+
+/* ltov - convert list to an NULL-terminated vector allocated in arena */
+void *ltov(List *list, unsigned arena) {
+ int i = 0;
+ void **array = newarray(length(*list) + 1, sizeof array[0], arena);
+
+ if (*list) {
+ List lp = *list;
+ do {
+ lp = lp->link;
+ array[i++] = lp->x;
+ } while (lp != *list);
+#ifndef PURIFY
+ lp = (*list)->link;
+ (*list)->link = freenodes;
+ freenodes = lp;
+#endif
+ }
+ *list = NULL;
+ array[i] = NULL;
+ return array;
+}
diff --git a/lcc/src/main.c b/lcc/src/main.c
new file mode 100755
index 0000000..1367fa0
--- /dev/null
+++ b/lcc/src/main.c
@@ -0,0 +1,225 @@
+#include "c.h"
+
+static char rcsid[] = "main.c - faked rcsid";
+
+static void typestab(Symbol, void *);
+
+static void stabline(Coordinate *);
+static void stabend(Coordinate *, Symbol, Coordinate **, Symbol *, Symbol *);
+Interface *IR = NULL;
+
+int Aflag; /* >= 0 if -A specified */
+int Pflag; /* != 0 if -P specified */
+int glevel; /* == [0-9] if -g[0-9] specified */
+int xref; /* != 0 for cross-reference data */
+Symbol YYnull; /* _YYnull symbol if -n or -nvalidate specified */
+Symbol YYcheck; /* _YYcheck symbol if -nvalidate,check specified */
+
+static char *comment;
+static Interface stabIR;
+static char *currentfile; /* current file name */
+static int currentline; /* current line number */
+static FILE *srcfp; /* stream for current file, if non-NULL */
+static int srcpos; /* position of srcfp, if srcfp is non-NULL */
+int main(int argc, char *argv[]) {
+ int i, j;
+ for (i = argc - 1; i > 0; i--)
+ if (strncmp(argv[i], "-target=", 8) == 0)
+ break;
+ if (i > 0) {
+ char *s = strchr(argv[i], '\\');
+ if (s != NULL)
+ *s = '/';
+ for (j = 0; bindings[j].name && bindings[j].ir; j++)
+ if (strcmp(&argv[i][8], bindings[j].name) == 0) {
+ IR = bindings[j].ir;
+ break;
+ }
+ if (s != NULL)
+ *s = '\\';
+ }
+ if (!IR) {
+ fprint(stderr, "%s: unknown target", argv[0]);
+ if (i > 0)
+ fprint(stderr, " `%s'", &argv[i][8]);
+ fprint(stderr, "; must specify one of\n");
+ for (i = 0; bindings[i].name; i++)
+ fprint(stderr, "\t-target=%s\n", bindings[i].name);
+ exit(EXIT_FAILURE);
+ }
+ init(argc, argv);
+ t = gettok();
+ (*IR->progbeg)(argc, argv);
+ if (glevel && IR->stabinit)
+ (*IR->stabinit)(firstfile, argc, argv);
+ program();
+ if (events.end)
+ apply(events.end, NULL, NULL);
+ memset(&events, 0, sizeof events);
+ if (glevel || xref) {
+ Symbol symroot = NULL;
+ Coordinate src;
+ foreach(types, GLOBAL, typestab, &symroot);
+ foreach(identifiers, GLOBAL, typestab, &symroot);
+ src.file = firstfile;
+ src.x = 0;
+ src.y = lineno;
+ if ((glevel > 2 || xref) && IR->stabend)
+ (*IR->stabend)(&src, symroot,
+ ltov(&loci, PERM),
+ ltov(&symbols, PERM), NULL);
+ else if (IR->stabend)
+ (*IR->stabend)(&src, NULL, NULL, NULL, NULL);
+ }
+ finalize();
+ (*IR->progend)();
+ deallocate(PERM);
+ return errcnt > 0;
+}
+/* main_init - process program arguments */
+void main_init(int argc, char *argv[]) {
+ char *infile = NULL, *outfile = NULL;
+ int i;
+ static int inited;
+
+ if (inited)
+ return;
+ inited = 1;
+ type_init(argc, argv);
+ for (i = 1; i < argc; i++)
+ if (strcmp(argv[i], "-g") == 0 || strcmp(argv[i], "-g2") == 0)
+ glevel = 2;
+ else if (strncmp(argv[i], "-g", 2) == 0) { /* -gn[,x] */
+ char *p = strchr(argv[i], ',');
+ glevel = atoi(argv[i]+2);
+ if (p) {
+ comment = p + 1;
+ if (glevel == 0)
+ glevel = 1;
+ if (stabIR.stabline == NULL) {
+ stabIR.stabline = IR->stabline;
+ stabIR.stabend = IR->stabend;
+ IR->stabline = stabline;
+ IR->stabend = stabend;
+ }
+ }
+ } else if (strcmp(argv[i], "-x") == 0)
+ xref++;
+ else if (strcmp(argv[i], "-A") == 0) {
+ ++Aflag;
+ } else if (strcmp(argv[i], "-P") == 0)
+ Pflag++;
+ else if (strcmp(argv[i], "-w") == 0)
+ wflag++;
+ else if (strcmp(argv[i], "-n") == 0) {
+ if (!YYnull) {
+ YYnull = install(string("_YYnull"), &globals, GLOBAL, PERM);
+ YYnull->type = func(voidptype, NULL, 1);
+ YYnull->sclass = EXTERN;
+ (*IR->defsymbol)(YYnull);
+ }
+ } else if (strncmp(argv[i], "-n", 2) == 0) { /* -nvalid[,check] */
+ char *p = strchr(argv[i], ',');
+ if (p) {
+ YYcheck = install(string(p+1), &globals, GLOBAL, PERM);
+ YYcheck->type = func(voidptype, NULL, 1);
+ YYcheck->sclass = EXTERN;
+ (*IR->defsymbol)(YYcheck);
+ p = stringn(argv[i]+2, p - (argv[i]+2));
+ } else
+ p = string(argv[i]+2);
+ YYnull = install(p, &globals, GLOBAL, PERM);
+ YYnull->type = func(voidptype, NULL, 1);
+ YYnull->sclass = EXTERN;
+ (*IR->defsymbol)(YYnull);
+ } else if (strcmp(argv[i], "-v") == 0)
+ fprint(stderr, "%s %s\n", argv[0], rcsid);
+ else if (strncmp(argv[i], "-s", 2) == 0)
+ density = strtod(&argv[i][2], NULL);
+ else if (strncmp(argv[i], "-errout=", 8) == 0) {
+ FILE *f = fopen(argv[i]+8, "w");
+ if (f == NULL) {
+ fprint(stderr, "%s: can't write errors to `%s'\n", argv[0], argv[i]+8);
+ exit(EXIT_FAILURE);
+ }
+ fclose(f);
+ f = freopen(argv[i]+8, "w", stderr);
+ assert(f);
+ } else if (strncmp(argv[i], "-e", 2) == 0) {
+ int x;
+ if ((x = strtol(&argv[i][2], NULL, 0)) > 0)
+ errlimit = x;
+ } else if (strncmp(argv[i], "-little_endian=", 15) == 0)
+ IR->little_endian = argv[i][15] - '0';
+ else if (strncmp(argv[i], "-mulops_calls=", 18) == 0)
+ IR->mulops_calls = argv[i][18] - '0';
+ else if (strncmp(argv[i], "-wants_callb=", 13) == 0)
+ IR->wants_callb = argv[i][13] - '0';
+ else if (strncmp(argv[i], "-wants_argb=", 12) == 0)
+ IR->wants_argb = argv[i][12] - '0';
+ else if (strncmp(argv[i], "-left_to_right=", 15) == 0)
+ IR->left_to_right = argv[i][15] - '0';
+ else if (strncmp(argv[i], "-wants_dag=", 11) == 0)
+ IR->wants_dag = argv[i][11] - '0';
+ else if (*argv[i] != '-' || strcmp(argv[i], "-") == 0) {
+ if (infile == NULL)
+ infile = argv[i];
+ else if (outfile == NULL)
+ outfile = argv[i];
+ }
+
+ if (infile != NULL && strcmp(infile, "-") != 0
+ && freopen(infile, "r", stdin) == NULL) {
+ fprint(stderr, "%s: can't read `%s'\n", argv[0], infile);
+ exit(EXIT_FAILURE);
+ }
+ if (outfile != NULL && strcmp(outfile, "-") != 0
+ && freopen(outfile, "w", stdout) == NULL) {
+ fprint(stderr, "%s: can't write `%s'\n", argv[0], outfile);
+ exit(EXIT_FAILURE);
+ }
+}
+/* typestab - emit stab entries for p */
+static void typestab(Symbol p, void *cl) {
+ if (*(Symbol *)cl == 0 && p->sclass && p->sclass != TYPEDEF)
+ *(Symbol *)cl = p;
+ if ((p->sclass == TYPEDEF || p->sclass == 0) && IR->stabtype)
+ (*IR->stabtype)(p);
+}
+
+/* stabline - emit source code for source coordinate *cp */
+static void stabline(Coordinate *cp) {
+ if (cp->file && cp->file != currentfile) {
+ if (srcfp)
+ fclose(srcfp);
+ currentfile = cp->file;
+ srcfp = fopen(currentfile, "r");
+ srcpos = 0;
+ currentline = 0;
+ }
+ if (currentline != cp->y && srcfp) {
+ char buf[512];
+ if (srcpos > cp->y) {
+ rewind(srcfp);
+ srcpos = 0;
+ }
+ for ( ; srcpos < cp->y; srcpos++)
+ if (fgets(buf, sizeof buf, srcfp) == NULL) {
+ fclose(srcfp);
+ srcfp = NULL;
+ break;
+ }
+ if (srcfp && srcpos == cp->y)
+ print("%s%s", comment, buf);
+ }
+ currentline = cp->y;
+ if (stabIR.stabline)
+ (*stabIR.stabline)(cp);
+}
+
+static void stabend(Coordinate *cp, Symbol p, Coordinate **cpp, Symbol *sp, Symbol *stab) {
+ if (stabIR.stabend)
+ (*stabIR.stabend)(cp, p, cpp, sp, stab);
+ if (srcfp)
+ fclose(srcfp);
+}
diff --git a/lcc/src/mips.md b/lcc/src/mips.md
new file mode 100755
index 0000000..7e643fb
--- /dev/null
+++ b/lcc/src/mips.md
@@ -0,0 +1,1120 @@
+%{
+#define INTTMP 0x0100ff00
+#define INTVAR 0x40ff0000
+#define FLTTMP 0x000f0ff0
+#define FLTVAR 0xfff00000
+
+#define INTRET 0x00000004
+#define FLTRET 0x00000003
+
+#define readsreg(p) \
+ (generic((p)->op)==INDIR && (p)->kids[0]->op==VREG+P)
+#define setsrc(d) ((d) && (d)->x.regnode && \
+ (d)->x.regnode->set == src->x.regnode->set && \
+ (d)->x.regnode->mask&src->x.regnode->mask)
+
+#define relink(a, b) ((b)->x.prev = (a), (a)->x.next = (b))
+
+#include "c.h"
+#define NODEPTR_TYPE Node
+#define OP_LABEL(p) ((p)->op)
+#define LEFT_CHILD(p) ((p)->kids[0])
+#define RIGHT_CHILD(p) ((p)->kids[1])
+#define STATE_LABEL(p) ((p)->x.state)
+static void address(Symbol, Symbol, long);
+static void blkfetch(int, int, int, int);
+static void blkloop(int, int, int, int, int, int[]);
+static void blkstore(int, int, int, int);
+static void defaddress(Symbol);
+static void defconst(int, int, Value);
+static void defstring(int, char *);
+static void defsymbol(Symbol);
+static void doarg(Node);
+static void emit2(Node);
+static void export(Symbol);
+static void clobber(Node);
+static void function(Symbol, Symbol [], Symbol [], int);
+static void global(Symbol);
+static void import(Symbol);
+static void local(Symbol);
+static void progbeg(int, char **);
+static void progend(void);
+static void segment(int);
+static void space(int);
+static void target(Node);
+static int bitcount (unsigned);
+static Symbol argreg (int, int, int, int, int);
+
+static Symbol ireg[32], freg2[32], d6;
+static Symbol iregw, freg2w;
+static int tmpregs[] = {3, 9, 10};
+static Symbol blkreg;
+
+static int gnum = 8;
+static int pic;
+
+static int cseg;
+%}
+%start stmt
+%term CNSTF4=4113
+%term CNSTF8=8209
+%term CNSTF16=16401
+%term CNSTI1=1045
+%term CNSTI2=2069
+%term CNSTI4=4117
+%term CNSTI8=8213
+%term CNSTP4=4119
+%term CNSTP8=8215
+%term CNSTU1=1046
+%term CNSTU2=2070
+%term CNSTU4=4118
+%term CNSTU8=8214
+
+%term ARGB=41
+%term ARGF4=4129
+%term ARGF8=8225
+%term ARGF16=16417
+%term ARGI4=4133
+%term ARGI8=8229
+%term ARGP4=4135
+%term ARGP8=8231
+%term ARGU4=4134
+%term ARGU8=8230
+
+%term ASGNB=57
+%term ASGNF4=4145
+%term ASGNF8=8241
+%term ASGNF16=16433
+%term ASGNI1=1077
+%term ASGNI2=2101
+%term ASGNI4=4149
+%term ASGNI8=8245
+%term ASGNP4=4151
+%term ASGNP8=8247
+%term ASGNU1=1078
+%term ASGNU2=2102
+%term ASGNU4=4150
+%term ASGNU8=8246
+
+%term INDIRB=73
+%term INDIRF4=4161
+%term INDIRF8=8257
+%term INDIRF16=16449
+%term INDIRI1=1093
+%term INDIRI2=2117
+%term INDIRI4=4165
+%term INDIRI8=8261
+%term INDIRP4=4167
+%term INDIRP8=8263
+%term INDIRU1=1094
+%term INDIRU2=2118
+%term INDIRU4=4166
+%term INDIRU8=8262
+
+%term CVFF4=4209
+%term CVFF8=8305
+%term CVFF16=16497
+%term CVFI4=4213
+%term CVFI8=8309
+
+%term CVIF4=4225
+%term CVIF8=8321
+%term CVIF16=16513
+%term CVII1=1157
+%term CVII2=2181
+%term CVII4=4229
+%term CVII8=8325
+%term CVIU1=1158
+%term CVIU2=2182
+%term CVIU4=4230
+%term CVIU8=8326
+
+%term CVPP4=4247
+%term CVPP8=8343
+%term CVPP16=16535
+%term CVPU4=4246
+%term CVPU8=8342
+
+%term CVUI1=1205
+%term CVUI2=2229
+%term CVUI4=4277
+%term CVUI8=8373
+%term CVUP4=4279
+%term CVUP8=8375
+%term CVUP16=16567
+%term CVUU1=1206
+%term CVUU2=2230
+%term CVUU4=4278
+%term CVUU8=8374
+
+%term NEGF4=4289
+%term NEGF8=8385
+%term NEGF16=16577
+%term NEGI4=4293
+%term NEGI8=8389
+
+%term CALLB=217
+%term CALLF4=4305
+%term CALLF8=8401
+%term CALLF16=16593
+%term CALLI4=4309
+%term CALLI8=8405
+%term CALLP4=4311
+%term CALLP8=8407
+%term CALLU4=4310
+%term CALLU8=8406
+%term CALLV=216
+
+%term RETF4=4337
+%term RETF8=8433
+%term RETF16=16625
+%term RETI4=4341
+%term RETI8=8437
+%term RETP4=4343
+%term RETP8=8439
+%term RETU4=4342
+%term RETU8=8438
+%term RETV=248
+
+%term ADDRGP4=4359
+%term ADDRGP8=8455
+
+%term ADDRFP4=4375
+%term ADDRFP8=8471
+
+%term ADDRLP4=4391
+%term ADDRLP8=8487
+
+%term ADDF4=4401
+%term ADDF8=8497
+%term ADDF16=16689
+%term ADDI4=4405
+%term ADDI8=8501
+%term ADDP4=4407
+%term ADDP8=8503
+%term ADDU4=4406
+%term ADDU8=8502
+
+%term SUBF4=4417
+%term SUBF8=8513
+%term SUBF16=16705
+%term SUBI4=4421
+%term SUBI8=8517
+%term SUBP4=4423
+%term SUBP8=8519
+%term SUBU4=4422
+%term SUBU8=8518
+
+%term LSHI4=4437
+%term LSHI8=8533
+%term LSHU4=4438
+%term LSHU8=8534
+
+%term MODI4=4453
+%term MODI8=8549
+%term MODU4=4454
+%term MODU8=8550
+
+%term RSHI4=4469
+%term RSHI8=8565
+%term RSHU4=4470
+%term RSHU8=8566
+
+%term BANDI4=4485
+%term BANDI8=8581
+%term BANDU4=4486
+%term BANDU8=8582
+
+%term BCOMI4=4501
+%term BCOMI8=8597
+%term BCOMU4=4502
+%term BCOMU8=8598
+
+%term BORI4=4517
+%term BORI8=8613
+%term BORU4=4518
+%term BORU8=8614
+
+%term BXORI4=4533
+%term BXORI8=8629
+%term BXORU4=4534
+%term BXORU8=8630
+
+%term DIVF4=4545
+%term DIVF8=8641
+%term DIVF16=16833
+%term DIVI4=4549
+%term DIVI8=8645
+%term DIVU4=4550
+%term DIVU8=8646
+
+%term MULF4=4561
+%term MULF8=8657
+%term MULF16=16849
+%term MULI4=4565
+%term MULI8=8661
+%term MULU4=4566
+%term MULU8=8662
+
+%term EQF4=4577
+%term EQF8=8673
+%term EQF16=16865
+%term EQI4=4581
+%term EQI8=8677
+%term EQU4=4582
+%term EQU8=8678
+
+%term GEF4=4593
+%term GEF8=8689
+%term GEI4=4597
+%term GEI8=8693
+%term GEI16=16885
+%term GEU4=4598
+%term GEU8=8694
+
+%term GTF4=4609
+%term GTF8=8705
+%term GTF16=16897
+%term GTI4=4613
+%term GTI8=8709
+%term GTU4=4614
+%term GTU8=8710
+
+%term LEF4=4625
+%term LEF8=8721
+%term LEF16=16913
+%term LEI4=4629
+%term LEI8=8725
+%term LEU4=4630
+%term LEU8=8726
+
+%term LTF4=4641
+%term LTF8=8737
+%term LTF16=16929
+%term LTI4=4645
+%term LTI8=8741
+%term LTU4=4646
+%term LTU8=8742
+
+%term NEF4=4657
+%term NEF8=8753
+%term NEF16=16945
+%term NEI4=4661
+%term NEI8=8757
+%term NEU4=4662
+%term NEU8=8758
+
+%term JUMPV=584
+
+%term LABELV=600
+
+%term LOADB=233
+%term LOADF4=4321
+%term LOADF8=8417
+%term LOADF16=16609
+%term LOADI1=1253
+%term LOADI2=2277
+%term LOADI4=4325
+%term LOADI8=8421
+%term LOADP4=4327
+%term LOADP8=8423
+%term LOADU1=1254
+%term LOADU2=2278
+%term LOADU4=4326
+%term LOADU8=8422
+
+%term VREGP=711
+%%
+reg: INDIRI1(VREGP) "# read register\n"
+reg: INDIRU1(VREGP) "# read register\n"
+
+reg: INDIRI2(VREGP) "# read register\n"
+reg: INDIRU2(VREGP) "# read register\n"
+
+reg: INDIRF4(VREGP) "# read register\n"
+reg: INDIRI4(VREGP) "# read register\n"
+reg: INDIRP4(VREGP) "# read register\n"
+reg: INDIRU4(VREGP) "# read register\n"
+
+reg: INDIRF8(VREGP) "# read register\n"
+reg: INDIRI8(VREGP) "# read register\n"
+reg: INDIRP8(VREGP) "# read register\n"
+reg: INDIRU8(VREGP) "# read register\n"
+
+stmt: ASGNI1(VREGP,reg) "# write register\n"
+stmt: ASGNU1(VREGP,reg) "# write register\n"
+
+stmt: ASGNI2(VREGP,reg) "# write register\n"
+stmt: ASGNU2(VREGP,reg) "# write register\n"
+
+stmt: ASGNF4(VREGP,reg) "# write register\n"
+stmt: ASGNI4(VREGP,reg) "# write register\n"
+stmt: ASGNP4(VREGP,reg) "# write register\n"
+stmt: ASGNU4(VREGP,reg) "# write register\n"
+
+stmt: ASGNF8(VREGP,reg) "# write register\n"
+stmt: ASGNI8(VREGP,reg) "# write register\n"
+stmt: ASGNP8(VREGP,reg) "# write register\n"
+stmt: ASGNU8(VREGP,reg) "# write register\n"
+con: CNSTI1 "%a"
+con: CNSTU1 "%a"
+
+con: CNSTI2 "%a"
+con: CNSTU2 "%a"
+
+con: CNSTI4 "%a"
+con: CNSTU4 "%a"
+con: CNSTP4 "%a"
+
+con: CNSTI8 "%a"
+con: CNSTU8 "%a"
+con: CNSTP8 "%a"
+stmt: reg ""
+acon: con "%0"
+acon: ADDRGP4 "%a"
+addr: ADDI4(reg,acon) "%1($%0)"
+addr: ADDU4(reg,acon) "%1($%0)"
+addr: ADDP4(reg,acon) "%1($%0)"
+addr: acon "%0"
+addr: reg "($%0)"
+addr: ADDRFP4 "%a+%F($sp)"
+addr: ADDRLP4 "%a+%F($sp)"
+reg: addr "la $%c,%0\n" 1
+reg: CNSTI1 "# reg\n" range(a, 0, 0)
+reg: CNSTI2 "# reg\n" range(a, 0, 0)
+reg: CNSTI4 "# reg\n" range(a, 0, 0)
+reg: CNSTU1 "# reg\n" range(a, 0, 0)
+reg: CNSTU2 "# reg\n" range(a, 0, 0)
+reg: CNSTU4 "# reg\n" range(a, 0, 0)
+reg: CNSTP4 "# reg\n" range(a, 0, 0)
+stmt: ASGNI1(addr,reg) "sb $%1,%0\n" 1
+stmt: ASGNU1(addr,reg) "sb $%1,%0\n" 1
+stmt: ASGNI2(addr,reg) "sh $%1,%0\n" 1
+stmt: ASGNU2(addr,reg) "sh $%1,%0\n" 1
+stmt: ASGNI4(addr,reg) "sw $%1,%0\n" 1
+stmt: ASGNU4(addr,reg) "sw $%1,%0\n" 1
+stmt: ASGNP4(addr,reg) "sw $%1,%0\n" 1
+reg: INDIRI1(addr) "lb $%c,%0\n" 1
+reg: INDIRU1(addr) "lbu $%c,%0\n" 1
+reg: INDIRI2(addr) "lh $%c,%0\n" 1
+reg: INDIRU2(addr) "lhu $%c,%0\n" 1
+reg: INDIRI4(addr) "lw $%c,%0\n" 1
+reg: INDIRU4(addr) "lw $%c,%0\n" 1
+reg: INDIRP4(addr) "lw $%c,%0\n" 1
+
+reg: CVII4(INDIRI1(addr)) "lb $%c,%0\n" 1
+reg: CVII4(INDIRI2(addr)) "lh $%c,%0\n" 1
+reg: CVUU4(INDIRU1(addr)) "lbu $%c,%0\n" 1
+reg: CVUU4(INDIRU2(addr)) "lhu $%c,%0\n" 1
+reg: CVUI4(INDIRU1(addr)) "lbu $%c,%0\n" 1
+reg: CVUI4(INDIRU2(addr)) "lhu $%c,%0\n" 1
+reg: INDIRF4(addr) "l.s $f%c,%0\n" 1
+reg: INDIRF8(addr) "l.d $f%c,%0\n" 1
+stmt: ASGNF4(addr,reg) "s.s $f%1,%0\n" 1
+stmt: ASGNF8(addr,reg) "s.d $f%1,%0\n" 1
+reg: DIVI4(reg,reg) "div $%c,$%0,$%1\n" 1
+reg: DIVU4(reg,reg) "divu $%c,$%0,$%1\n" 1
+reg: MODI4(reg,reg) "rem $%c,$%0,$%1\n" 1
+reg: MODU4(reg,reg) "remu $%c,$%0,$%1\n" 1
+reg: MULI4(reg,reg) "mul $%c,$%0,$%1\n" 1
+reg: MULU4(reg,reg) "mul $%c,$%0,$%1\n" 1
+rc: con "%0"
+rc: reg "$%0"
+
+reg: ADDI4(reg,rc) "addu $%c,$%0,%1\n" 1
+reg: ADDP4(reg,rc) "addu $%c,$%0,%1\n" 1
+reg: ADDU4(reg,rc) "addu $%c,$%0,%1\n" 1
+reg: BANDI4(reg,rc) "and $%c,$%0,%1\n" 1
+reg: BORI4(reg,rc) "or $%c,$%0,%1\n" 1
+reg: BXORI4(reg,rc) "xor $%c,$%0,%1\n" 1
+reg: BANDU4(reg,rc) "and $%c,$%0,%1\n" 1
+reg: BORU4(reg,rc) "or $%c,$%0,%1\n" 1
+reg: BXORU4(reg,rc) "xor $%c,$%0,%1\n" 1
+reg: SUBI4(reg,rc) "subu $%c,$%0,%1\n" 1
+reg: SUBP4(reg,rc) "subu $%c,$%0,%1\n" 1
+reg: SUBU4(reg,rc) "subu $%c,$%0,%1\n" 1
+rc5: CNSTI4 "%a" range(a,0,31)
+rc5: reg "$%0"
+
+reg: LSHI4(reg,rc5) "sll $%c,$%0,%1\n" 1
+reg: LSHU4(reg,rc5) "sll $%c,$%0,%1\n" 1
+reg: RSHI4(reg,rc5) "sra $%c,$%0,%1\n" 1
+reg: RSHU4(reg,rc5) "srl $%c,$%0,%1\n" 1
+reg: BCOMI4(reg) "not $%c,$%0\n" 1
+reg: BCOMU4(reg) "not $%c,$%0\n" 1
+reg: NEGI4(reg) "negu $%c,$%0\n" 1
+reg: LOADI1(reg) "move $%c,$%0\n" move(a)
+reg: LOADU1(reg) "move $%c,$%0\n" move(a)
+reg: LOADI2(reg) "move $%c,$%0\n" move(a)
+reg: LOADU2(reg) "move $%c,$%0\n" move(a)
+reg: LOADI4(reg) "move $%c,$%0\n" move(a)
+reg: LOADP4(reg) "move $%c,$%0\n" move(a)
+reg: LOADU4(reg) "move $%c,$%0\n" move(a)
+reg: ADDF4(reg,reg) "add.s $f%c,$f%0,$f%1\n" 1
+reg: ADDF8(reg,reg) "add.d $f%c,$f%0,$f%1\n" 1
+reg: DIVF4(reg,reg) "div.s $f%c,$f%0,$f%1\n" 1
+reg: DIVF8(reg,reg) "div.d $f%c,$f%0,$f%1\n" 1
+reg: MULF4(reg,reg) "mul.s $f%c,$f%0,$f%1\n" 1
+reg: MULF8(reg,reg) "mul.d $f%c,$f%0,$f%1\n" 1
+reg: SUBF4(reg,reg) "sub.s $f%c,$f%0,$f%1\n" 1
+reg: SUBF8(reg,reg) "sub.d $f%c,$f%0,$f%1\n" 1
+reg: LOADF4(reg) "mov.s $f%c,$f%0\n" move(a)
+reg: LOADF8(reg) "mov.d $f%c,$f%0\n" move(a)
+reg: NEGF4(reg) "neg.s $f%c,$f%0\n" 1
+reg: NEGF8(reg) "neg.d $f%c,$f%0\n" 1
+reg: CVII4(reg) "sll $%c,$%0,8*(4-%a); sra $%c,$%c,8*(4-%a)\n" 2
+reg: CVUI4(reg) "and $%c,$%0,(1<<(8*%a))-1\n" 1
+reg: CVUU4(reg) "and $%c,$%0,(1<<(8*%a))-1\n" 1
+reg: CVFF4(reg) "cvt.s.d $f%c,$f%0\n" 1
+reg: CVFF8(reg) "cvt.d.s $f%c,$f%0\n" 1
+reg: CVIF4(reg) "mtc1 $%0,$f%c; cvt.s.w $f%c,$f%c\n" 2
+reg: CVIF8(reg) "mtc1 $%0,$f%c; cvt.d.w $f%c,$f%c\n" 2
+reg: CVFI4(reg) "trunc.w.s $f2,$f%0,$%c; mfc1 $%c,$f2\n" (a->syms[0]->u.c.v.i==4?2:LBURG_MAX)
+reg: CVFI4(reg) "trunc.w.d $f2,$f%0,$%c; mfc1 $%c,$f2\n" (a->syms[0]->u.c.v.i==8?2:LBURG_MAX)
+stmt: LABELV "%a:\n"
+stmt: JUMPV(acon) "b %0\n" 1
+stmt: JUMPV(reg) ".cpadd $%0\nj $%0\n" !pic
+stmt: JUMPV(reg) "j $%0\n" pic
+stmt: EQI4(reg,reg) "beq $%0,$%1,%a\n" 1
+stmt: EQU4(reg,reg) "beq $%0,$%1,%a\n" 1
+stmt: GEI4(reg,reg) "bge $%0,$%1,%a\n" 1
+stmt: GEU4(reg,reg) "bgeu $%0,$%1,%a\n" 1
+stmt: GTI4(reg,reg) "bgt $%0,$%1,%a\n" 1
+stmt: GTU4(reg,reg) "bgtu $%0,$%1,%a\n" 1
+stmt: LEI4(reg,reg) "ble $%0,$%1,%a\n" 1
+stmt: LEU4(reg,reg) "bleu $%0,$%1,%a\n" 1
+stmt: LTI4(reg,reg) "blt $%0,$%1,%a\n" 1
+stmt: LTU4(reg,reg) "bltu $%0,$%1,%a\n" 1
+stmt: NEI4(reg,reg) "bne $%0,$%1,%a\n" 1
+stmt: NEU4(reg,reg) "bne $%0,$%1,%a\n" 1
+stmt: EQF4(reg,reg) "c.eq.s $f%0,$f%1; bc1t %a\n" 2
+stmt: EQF8(reg,reg) "c.eq.d $f%0,$f%1; bc1t %a\n" 2
+stmt: LEF4(reg,reg) "c.le.s $f%0,$f%1; bc1t %a\n" 2
+stmt: LEF8(reg,reg) "c.le.d $f%0,$f%1; bc1t %a\n" 2
+stmt: LTF4(reg,reg) "c.lt.s $f%0,$f%1; bc1t %a\n" 2
+stmt: LTF8(reg,reg) "c.lt.d $f%0,$f%1; bc1t %a\n" 2
+stmt: GEF4(reg,reg) "c.lt.s $f%0,$f%1; bc1f %a\n" 2
+stmt: GEF8(reg,reg) "c.lt.d $f%0,$f%1; bc1f %a\n" 2
+stmt: GTF4(reg,reg) "c.le.s $f%0,$f%1; bc1f %a\n" 2
+stmt: GTF8(reg,reg) "c.le.d $f%0,$f%1; bc1f %a\n" 2
+stmt: NEF4(reg,reg) "c.eq.s $f%0,$f%1; bc1f %a\n" 2
+stmt: NEF8(reg,reg) "c.eq.d $f%0,$f%1; bc1f %a\n" 2
+ar: ADDRGP4 "%a"
+
+reg: CALLF4(ar) "jal %0\n" 1
+reg: CALLF8(ar) "jal %0\n" 1
+reg: CALLI4(ar) "jal %0\n" 1
+reg: CALLP4(ar) "jal %0\n" 1
+reg: CALLU4(ar) "jal %0\n" 1
+stmt: CALLV(ar) "jal %0\n" 1
+ar: reg "$%0"
+ar: CNSTP4 "%a" range(a, 0, 0x0fffffff)
+stmt: RETF4(reg) "# ret\n" 1
+stmt: RETF8(reg) "# ret\n" 1
+stmt: RETI4(reg) "# ret\n" 1
+stmt: RETU4(reg) "# ret\n" 1
+stmt: RETP4(reg) "# ret\n" 1
+stmt: RETV(reg) "# ret\n" 1
+stmt: ARGF4(reg) "# arg\n" 1
+stmt: ARGF8(reg) "# arg\n" 1
+stmt: ARGI4(reg) "# arg\n" 1
+stmt: ARGP4(reg) "# arg\n" 1
+stmt: ARGU4(reg) "# arg\n" 1
+
+stmt: ARGB(INDIRB(reg)) "# argb %0\n" 1
+stmt: ASGNB(reg,INDIRB(reg)) "# asgnb %0 %1\n" 1
+%%
+static void progend(void){}
+static void progbeg(int argc, char *argv[]) {
+ int i;
+
+ {
+ union {
+ char c;
+ int i;
+ } u;
+ u.i = 0;
+ u.c = 1;
+ swap = ((int)(u.i == 1)) != IR->little_endian;
+ }
+ print(".set reorder\n");
+ pic = !IR->little_endian;
+ parseflags(argc, argv);
+ for (i = 0; i < argc; i++)
+ if (strncmp(argv[i], "-G", 2) == 0)
+ gnum = atoi(argv[i] + 2);
+ else if (strcmp(argv[i], "-pic=1") == 0
+ || strcmp(argv[i], "-pic=0") == 0)
+ pic = argv[i][5]-'0';
+ for (i = 0; i < 31; i += 2)
+ freg2[i] = mkreg("%d", i, 3, FREG);
+ for (i = 0; i < 32; i++)
+ ireg[i] = mkreg("%d", i, 1, IREG);
+ ireg[29]->x.name = "sp";
+ d6 = mkreg("6", 6, 3, IREG);
+ freg2w = mkwildcard(freg2);
+ iregw = mkwildcard(ireg);
+ tmask[IREG] = INTTMP; tmask[FREG] = FLTTMP;
+ vmask[IREG] = INTVAR; vmask[FREG] = FLTVAR;
+ blkreg = mkreg("8", 8, 7, IREG);
+}
+static Symbol rmap(int opk) {
+ switch (optype(opk)) {
+ case I: case U: case P: case B:
+ return iregw;
+ case F:
+ return freg2w;
+ default:
+ return 0;
+ }
+}
+static void target(Node p) {
+ assert(p);
+ switch (specific(p->op)) {
+ case CNST+I: case CNST+U: case CNST+P:
+ if (range(p, 0, 0) == 0) {
+ setreg(p, ireg[0]);
+ p->x.registered = 1;
+ }
+ break;
+ case CALL+V:
+ rtarget(p, 0, ireg[25]);
+ break;
+ case CALL+F:
+ rtarget(p, 0, ireg[25]);
+ setreg(p, freg2[0]);
+ break;
+ case CALL+I: case CALL+P: case CALL+U:
+ rtarget(p, 0, ireg[25]);
+ setreg(p, ireg[2]);
+ break;
+ case RET+F:
+ rtarget(p, 0, freg2[0]);
+ break;
+ case RET+I: case RET+U: case RET+P:
+ rtarget(p, 0, ireg[2]);
+ break;
+ case ARG+F: case ARG+I: case ARG+P: case ARG+U: {
+ static int ty0;
+ int ty = optype(p->op);
+ Symbol q;
+
+ q = argreg(p->x.argno, p->syms[2]->u.c.v.i, ty, opsize(p->op), ty0);
+ if (p->x.argno == 0)
+ ty0 = ty;
+ if (q &&
+ !(ty == F && q->x.regnode->set == IREG))
+ rtarget(p, 0, q);
+ break;
+ }
+ case ASGN+B: rtarget(p->kids[1], 0, blkreg); break;
+ case ARG+B: rtarget(p->kids[0], 0, blkreg); break;
+ }
+}
+static void clobber(Node p) {
+ assert(p);
+ switch (specific(p->op)) {
+ case CALL+F:
+ spill(INTTMP | INTRET, IREG, p);
+ spill(FLTTMP, FREG, p);
+ break;
+ case CALL+I: case CALL+P: case CALL+U:
+ spill(INTTMP, IREG, p);
+ spill(FLTTMP | FLTRET, FREG, p);
+ break;
+ case CALL+V:
+ spill(INTTMP | INTRET, IREG, p);
+ spill(FLTTMP | FLTRET, FREG, p);
+ break;
+ }
+}
+static void emit2(Node p) {
+ int dst, n, src, sz, ty;
+ static int ty0;
+ Symbol q;
+
+ switch (specific(p->op)) {
+ case ARG+F: case ARG+I: case ARG+P: case ARG+U:
+ ty = optype(p->op);
+ sz = opsize(p->op);
+ if (p->x.argno == 0)
+ ty0 = ty;
+ q = argreg(p->x.argno, p->syms[2]->u.c.v.i, ty, sz, ty0);
+ src = getregnum(p->x.kids[0]);
+ if (q == NULL && ty == F && sz == 4)
+ print("s.s $f%d,%d($sp)\n", src, p->syms[2]->u.c.v.i);
+ else if (q == NULL && ty == F)
+ print("s.d $f%d,%d($sp)\n", src, p->syms[2]->u.c.v.i);
+ else if (q == NULL)
+ print("sw $%d,%d($sp)\n", src, p->syms[2]->u.c.v.i);
+ else if (ty == F && sz == 4 && q->x.regnode->set == IREG)
+ print("mfc1 $%d,$f%d\n", q->x.regnode->number, src);
+ else if (ty == F && q->x.regnode->set == IREG)
+ print("mfc1.d $%d,$f%d\n", q->x.regnode->number, src);
+ break;
+ case ASGN+B:
+ dalign = salign = p->syms[1]->u.c.v.i;
+ blkcopy(getregnum(p->x.kids[0]), 0,
+ getregnum(p->x.kids[1]), 0,
+ p->syms[0]->u.c.v.i, tmpregs);
+ break;
+ case ARG+B:
+ dalign = 4;
+ salign = p->syms[1]->u.c.v.i;
+ blkcopy(29, p->syms[2]->u.c.v.i,
+ getregnum(p->x.kids[0]), 0,
+ p->syms[0]->u.c.v.i, tmpregs);
+ n = p->syms[2]->u.c.v.i + p->syms[0]->u.c.v.i;
+ dst = p->syms[2]->u.c.v.i;
+ for ( ; dst <= 12 && dst < n; dst += 4)
+ print("lw $%d,%d($sp)\n", (dst/4)+4, dst);
+ break;
+ }
+}
+static Symbol argreg(int argno, int offset, int ty, int sz, int ty0) {
+ assert((offset&3) == 0);
+ if (offset > 12)
+ return NULL;
+ else if (argno == 0 && ty == F)
+ return freg2[12];
+ else if (argno == 1 && ty == F && ty0 == F)
+ return freg2[14];
+ else if (argno == 1 && ty == F && sz == 8)
+ return d6; /* Pair! */
+ else
+ return ireg[(offset/4) + 4];
+}
+static void doarg(Node p) {
+ static int argno;
+ int align;
+
+ if (argoffset == 0)
+ argno = 0;
+ p->x.argno = argno++;
+ align = p->syms[1]->u.c.v.i < 4 ? 4 : p->syms[1]->u.c.v.i;
+ p->syms[2] = intconst(mkactual(align,
+ p->syms[0]->u.c.v.i));
+}
+static void local(Symbol p) {
+ if (askregvar(p, rmap(ttob(p->type))) == 0)
+ mkauto(p);
+}
+static void function(Symbol f, Symbol caller[], Symbol callee[], int ncalls) {
+ int i, saved, sizefsave, sizeisave, varargs;
+ Symbol r, argregs[4];
+
+ usedmask[0] = usedmask[1] = 0;
+ freemask[0] = freemask[1] = ~(unsigned)0;
+ offset = maxoffset = maxargoffset = 0;
+ for (i = 0; callee[i]; i++)
+ ;
+ varargs = variadic(f->type)
+ || i > 0 && strcmp(callee[i-1]->name, "va_alist") == 0;
+ for (i = 0; callee[i]; i++) {
+ Symbol p = callee[i];
+ Symbol q = caller[i];
+ assert(q);
+ offset = roundup(offset, q->type->align);
+ p->x.offset = q->x.offset = offset;
+ p->x.name = q->x.name = stringd(offset);
+ r = argreg(i, offset, optype(ttob(q->type)), q->type->size, optype(ttob(caller[0]->type)));
+ if (i < 4)
+ argregs[i] = r;
+ offset = roundup(offset + q->type->size, 4);
+ if (varargs)
+ p->sclass = AUTO;
+ else if (r && ncalls == 0 &&
+ !isstruct(q->type) && !p->addressed &&
+ !(isfloat(q->type) && r->x.regnode->set == IREG)
+) {
+ p->sclass = q->sclass = REGISTER;
+ askregvar(p, r);
+ assert(p->x.regnode && p->x.regnode->vbl == p);
+ q->x = p->x;
+ q->type = p->type;
+ }
+ else if (askregvar(p, rmap(ttob(p->type)))
+ && r != NULL
+ && (isint(p->type) || p->type == q->type)) {
+ assert(q->sclass != REGISTER);
+ p->sclass = q->sclass = REGISTER;
+ q->type = p->type;
+ }
+ }
+ assert(!caller[i]);
+ offset = 0;
+ gencode(caller, callee);
+ if (ncalls)
+ usedmask[IREG] |= ((unsigned)1)<<31;
+ usedmask[IREG] &= 0xc0ff0000;
+ usedmask[FREG] &= 0xfff00000;
+ if (pic && ncalls)
+ usedmask[IREG] |= 1<<25;
+ maxargoffset = roundup(maxargoffset, usedmask[FREG] ? 8 : 4);
+ if (ncalls && maxargoffset < 16)
+ maxargoffset = 16;
+ sizefsave = 4*bitcount(usedmask[FREG]);
+ sizeisave = 4*bitcount(usedmask[IREG]);
+ framesize = roundup(maxargoffset + sizefsave
+ + sizeisave + maxoffset, 8);
+ segment(CODE);
+ print(".align 2\n");
+ print(".ent %s\n", f->x.name);
+ print("%s:\n", f->x.name);
+ i = maxargoffset + sizefsave - framesize;
+ print(".frame $sp,%d,$31\n", framesize);
+ if (pic)
+ print(".set noreorder\n.cpload $25\n.set reorder\n");
+ if (framesize > 0)
+ print("addu $sp,$sp,%d\n", -framesize);
+ if (usedmask[FREG])
+ print(".fmask 0x%x,%d\n", usedmask[FREG], i - 8);
+ if (usedmask[IREG])
+ print(".mask 0x%x,%d\n", usedmask[IREG],
+ i + sizeisave - 4);
+ saved = maxargoffset;
+ for (i = 20; i <= 30; i += 2)
+ if (usedmask[FREG]&(3<<i)) {
+ print("s.d $f%d,%d($sp)\n", i, saved);
+ saved += 8;
+ }
+
+ for (i = 16; i <= 31; i++)
+ if (usedmask[IREG]&(1<<i)) {
+ if (i == 25)
+ print(".cprestore %d\n", saved);
+ else
+ print("sw $%d,%d($sp)\n", i, saved);
+ saved += 4;
+ }
+ for (i = 0; i < 4 && callee[i]; i++) {
+ r = argregs[i];
+ if (r && r->x.regnode != callee[i]->x.regnode) {
+ Symbol out = callee[i];
+ Symbol in = caller[i];
+ int rn = r->x.regnode->number;
+ int rs = r->x.regnode->set;
+ int tyin = ttob(in->type);
+
+ assert(out && in && r && r->x.regnode);
+ assert(out->sclass != REGISTER || out->x.regnode);
+ if (out->sclass == REGISTER
+ && (isint(out->type) || out->type == in->type)) {
+ int outn = out->x.regnode->number;
+ if (rs == FREG && tyin == F+sizeop(8))
+ print("mov.d $f%d,$f%d\n", outn, rn);
+ else if (rs == FREG && tyin == F+sizeop(4))
+ print("mov.s $f%d,$f%d\n", outn, rn);
+ else if (rs == IREG && tyin == F+sizeop(8))
+ print("mtc1.d $%d,$f%d\n", rn, outn);
+ else if (rs == IREG && tyin == F+sizeop(4))
+ print("mtc1 $%d,$f%d\n", rn, outn);
+ else
+ print("move $%d,$%d\n", outn, rn);
+ } else {
+ int off = in->x.offset + framesize;
+ if (rs == FREG && tyin == F+sizeop(8))
+ print("s.d $f%d,%d($sp)\n", rn, off);
+ else if (rs == FREG && tyin == F+sizeop(4))
+ print("s.s $f%d,%d($sp)\n", rn, off);
+ else {
+ int i, n = (in->type->size + 3)/4;
+ for (i = rn; i < rn+n && i <= 7; i++)
+ print("sw $%d,%d($sp)\n", i, off + (i-rn)*4);
+ }
+ }
+ }
+ }
+ if (varargs && callee[i-1]) {
+ i = callee[i-1]->x.offset + callee[i-1]->type->size;
+ for (i = roundup(i, 4)/4; i <= 3; i++)
+ print("sw $%d,%d($sp)\n", i + 4, framesize + 4*i);
+ }
+ emitcode();
+ saved = maxargoffset;
+ for (i = 20; i <= 30; i += 2)
+ if (usedmask[FREG]&(3<<i)) {
+ print("l.d $f%d,%d($sp)\n", i, saved);
+ saved += 8;
+ }
+ for (i = 16; i <= 31; i++)
+ if (usedmask[IREG]&(1<<i)) {
+ print("lw $%d,%d($sp)\n", i, saved);
+ saved += 4;
+ }
+ if (framesize > 0)
+ print("addu $sp,$sp,%d\n", framesize);
+ print("j $31\n");
+ print(".end %s\n", f->x.name);
+}
+static void defconst(int suffix, int size, Value v) {
+ if (suffix == F && size == 4) {
+ float f = v.d;
+ print(".word 0x%x\n", *(unsigned *)&f);
+ }
+ else if (suffix == F && size == 8) {
+ double d = v.d;
+ unsigned *p = (unsigned *)&d;
+ print(".word 0x%x\n.word 0x%x\n", p[swap], p[!swap]);
+ }
+ else if (suffix == P)
+ print(".word 0x%x\n", v.p);
+ else if (size == 1)
+ print(".byte 0x%x\n", suffix == I ? v.i : v.u);
+ else if (size == 2)
+ print(".half 0x%x\n", suffix == I ? v.i : v.u);
+ else if (size == 4)
+ print(".word 0x%x\n", suffix == I ? v.i : v.u);
+}
+static void defaddress(Symbol p) {
+ if (pic && p->scope == LABELS)
+ print(".gpword %s\n", p->x.name);
+ else
+ print(".word %s\n", p->x.name);
+}
+static void defstring(int n, char *str) {
+ char *s;
+
+ for (s = str; s < str + n; s++)
+ print(".byte %d\n", (*s)&0377);
+}
+static void export(Symbol p) {
+ print(".globl %s\n", p->x.name);
+}
+static void import(Symbol p) {
+ if (!isfunc(p->type))
+ print(".extern %s %d\n", p->name, p->type->size);
+}
+static void defsymbol(Symbol p) {
+ if (p->scope >= LOCAL && p->sclass == STATIC)
+ p->x.name = stringf("L.%d", genlabel(1));
+ else if (p->generated)
+ p->x.name = stringf("L.%s", p->name);
+ else
+ assert(p->scope != CONSTANTS || isint(p->type) || isptr(p->type)),
+ p->x.name = p->name;
+}
+static void address(Symbol q, Symbol p, long n) {
+ if (p->scope == GLOBAL
+ || p->sclass == STATIC || p->sclass == EXTERN)
+ q->x.name = stringf("%s%s%D", p->x.name,
+ n >= 0 ? "+" : "", n);
+ else {
+ assert(n <= INT_MAX && n >= INT_MIN);
+ q->x.offset = p->x.offset + n;
+ q->x.name = stringd(q->x.offset);
+ }
+}
+static void global(Symbol p) {
+ if (p->u.seg == BSS) {
+ if (p->sclass == STATIC || Aflag >= 2)
+ print(".lcomm %s,%d\n", p->x.name, p->type->size);
+ else
+ print( ".comm %s,%d\n", p->x.name, p->type->size);
+ } else {
+ if (p->u.seg == DATA
+ && (p->type->size == 0 || p->type->size > gnum))
+ print(".data\n");
+ else if (p->u.seg == DATA)
+ print(".sdata\n");
+ print(".align %c\n", ".01.2...3"[p->type->align]);
+ print("%s:\n", p->x.name);
+ }
+}
+static void segment(int n) {
+ cseg = n;
+ switch (n) {
+ case CODE: print(".text\n"); break;
+ case LIT: print(".rdata\n"); break;
+ }
+}
+static void space(int n) {
+ if (cseg != BSS)
+ print(".space %d\n", n);
+}
+static void blkloop(int dreg, int doff, int sreg, int soff, int size, int tmps[]) {
+ int lab = genlabel(1);
+
+ print("addu $%d,$%d,%d\n", sreg, sreg, size&~7);
+ print("addu $%d,$%d,%d\n", tmps[2], dreg, size&~7);
+ blkcopy(tmps[2], doff, sreg, soff, size&7, tmps);
+ print("L.%d:\n", lab);
+ print("addu $%d,$%d,%d\n", sreg, sreg, -8);
+ print("addu $%d,$%d,%d\n", tmps[2], tmps[2], -8);
+ blkcopy(tmps[2], doff, sreg, soff, 8, tmps);
+ print("bltu $%d,$%d,L.%d\n", dreg, tmps[2], lab);
+}
+static void blkfetch(int size, int off, int reg, int tmp) {
+ assert(size == 1 || size == 2 || size == 4);
+ if (size == 1)
+ print("lbu $%d,%d($%d)\n", tmp, off, reg);
+ else if (salign >= size && size == 2)
+ print("lhu $%d,%d($%d)\n", tmp, off, reg);
+ else if (salign >= size)
+ print("lw $%d,%d($%d)\n", tmp, off, reg);
+ else if (size == 2)
+ print("ulhu $%d,%d($%d)\n", tmp, off, reg);
+ else
+ print("ulw $%d,%d($%d)\n", tmp, off, reg);
+}
+static void blkstore(int size, int off, int reg, int tmp) {
+ if (size == 1)
+ print("sb $%d,%d($%d)\n", tmp, off, reg);
+ else if (dalign >= size && size == 2)
+ print("sh $%d,%d($%d)\n", tmp, off, reg);
+ else if (dalign >= size)
+ print("sw $%d,%d($%d)\n", tmp, off, reg);
+ else if (size == 2)
+ print("ush $%d,%d($%d)\n", tmp, off, reg);
+ else
+ print("usw $%d,%d($%d)\n", tmp, off, reg);
+}
+static void stabinit(char *, int, char *[]);
+static void stabline(Coordinate *);
+static void stabsym(Symbol);
+
+static char *currentfile;
+
+static int bitcount(unsigned mask) {
+ unsigned i, n = 0;
+
+ for (i = 1; i; i <<= 1)
+ if (mask&i)
+ n++;
+ return n;
+}
+
+/* stabinit - initialize stab output */
+static void stabinit(char *file, int argc, char *argv[]) {
+ if (file) {
+ print(".file 2,\"%s\"\n", file);
+ currentfile = file;
+ }
+}
+
+/* stabline - emit stab entry for source coordinate *cp */
+static void stabline(Coordinate *cp) {
+ if (cp->file && cp->file != currentfile) {
+ print(".file 2,\"%s\"\n", cp->file);
+ currentfile = cp->file;
+ }
+ print(".loc 2,%d\n", cp->y);
+}
+
+/* stabsym - output a stab entry for symbol p */
+static void stabsym(Symbol p) {
+ if (p == cfunc && IR->stabline)
+ (*IR->stabline)(&p->src);
+}
+Interface mipsebIR = {
+ 1, 1, 0, /* char */
+ 2, 2, 0, /* short */
+ 4, 4, 0, /* int */
+ 4, 4, 0, /* long */
+ 4, 4, 0, /* long long */
+ 4, 4, 1, /* float */
+ 8, 8, 1, /* double */
+ 8, 8, 1, /* long double */
+ 4, 4, 0, /* T * */
+ 0, 1, 0, /* struct */
+ 0, /* little_endian */
+ 0, /* mulops_calls */
+ 0, /* wants_callb */
+ 1, /* wants_argb */
+ 1, /* left_to_right */
+ 0, /* wants_dag */
+ 0, /* unsigned_char */
+ address,
+ blockbeg,
+ blockend,
+ defaddress,
+ defconst,
+ defstring,
+ defsymbol,
+ emit,
+ export,
+ function,
+ gen,
+ global,
+ import,
+ local,
+ progbeg,
+ progend,
+ segment,
+ space,
+ 0, 0, 0, stabinit, stabline, stabsym, 0,
+ {
+ 4, /* max_unaligned_load */
+ rmap,
+ blkfetch, blkstore, blkloop,
+ _label,
+ _rule,
+ _nts,
+ _kids,
+ _string,
+ _templates,
+ _isinstruction,
+ _ntname,
+ emit2,
+ doarg,
+ target,
+ clobber,
+
+ }
+}, mipselIR = {
+ 1, 1, 0, /* char */
+ 2, 2, 0, /* short */
+ 4, 4, 0, /* int */
+ 4, 4, 0, /* long */
+ 4, 4, 0, /* long long */
+ 4, 4, 1, /* float */
+ 8, 8, 1, /* double */
+ 8, 8, 1, /* long double */
+ 4, 4, 0, /* T * */
+ 0, 1, 0, /* struct */
+ 1, /* little_endian */
+ 0, /* mulops_calls */
+ 0, /* wants_callb */
+ 1, /* wants_argb */
+ 1, /* left_to_right */
+ 0, /* wants_dag */
+ 0, /* unsigned_char */
+ address,
+ blockbeg,
+ blockend,
+ defaddress,
+ defconst,
+ defstring,
+ defsymbol,
+ emit,
+ export,
+ function,
+ gen,
+ global,
+ import,
+ local,
+ progbeg,
+ progend,
+ segment,
+ space,
+ 0, 0, 0, stabinit, stabline, stabsym, 0,
+ {
+ 4, /* max_unaligned_load */
+ rmap,
+ blkfetch, blkstore, blkloop,
+ _label,
+ _rule,
+ _nts,
+ _kids,
+ _string,
+ _templates,
+ _isinstruction,
+ _ntname,
+ emit2,
+ doarg,
+ target,
+ clobber,
+
+ }
+};
+static char rcsid[] = "$Id: mips.md 145 2001-10-17 21:53:10Z timo $";
diff --git a/lcc/src/null.c b/lcc/src/null.c
new file mode 100755
index 0000000..52129fc
--- /dev/null
+++ b/lcc/src/null.c
@@ -0,0 +1,74 @@
+#include "c.h"
+#define I(f) null_##f
+
+static Node I(gen)(Node p) { return p; }
+static void I(address)(Symbol q, Symbol p, long n) {}
+static void I(blockbeg)(Env *e) {}
+static void I(blockend)(Env *e) {}
+static void I(defaddress)(Symbol p) {}
+static void I(defconst)(int suffix, int size, Value v) {}
+static void I(defstring)(int len, char *s) {}
+static void I(defsymbol)(Symbol p) {}
+static void I(emit)(Node p) {}
+static void I(export)(Symbol p) {}
+static void I(function)(Symbol f, Symbol caller[], Symbol callee[], int ncalls) {}
+static void I(global)(Symbol p) {}
+static void I(import)(Symbol p) {}
+static void I(local)(Symbol p) {}
+static void I(progbeg)(int argc, char *argv[]) {}
+static void I(progend)(void) {}
+static void I(segment)(int s) {}
+static void I(space)(int n) {}
+static void I(stabblock)(int brace, int lev, Symbol *p) {}
+static void I(stabend)(Coordinate *cp, Symbol p, Coordinate **cpp, Symbol *sp, Symbol *stab) {}
+static void I(stabfend)(Symbol p, int lineno) {}
+static void I(stabinit)(char *file, int argc, char *argv[]) {}
+static void I(stabline)(Coordinate *cp) {}
+static void I(stabsym)(Symbol p) {}
+static void I(stabtype)(Symbol p) {}
+
+
+Interface nullIR = {
+ 1, 1, 0, /* char */
+ 2, 2, 0, /* short */
+ 4, 4, 0, /* int */
+ 8, 8, 1, /* long */
+ 8 ,8, 1, /* long long */
+ 4, 4, 1, /* float */
+ 8, 8, 1, /* double */
+ 16,16,1, /* long double */
+ 4, 4, 0, /* T* */
+ 0, 4, 0, /* struct */
+ 1, /* little_endian */
+ 0, /* mulops_calls */
+ 0, /* wants_callb */
+ 0, /* wants_argb */
+ 1, /* left_to_right */
+ 0, /* wants_dag */
+ 0, /* unsigned_char */
+ I(address),
+ I(blockbeg),
+ I(blockend),
+ I(defaddress),
+ I(defconst),
+ I(defstring),
+ I(defsymbol),
+ I(emit),
+ I(export),
+ I(function),
+ I(gen),
+ I(global),
+ I(import),
+ I(local),
+ I(progbeg),
+ I(progend),
+ I(segment),
+ I(space),
+ I(stabblock),
+ I(stabend),
+ I(stabfend),
+ I(stabinit),
+ I(stabline),
+ I(stabsym),
+ I(stabtype)
+};
diff --git a/lcc/src/output.c b/lcc/src/output.c
new file mode 100755
index 0000000..e8fe6f5
--- /dev/null
+++ b/lcc/src/output.c
@@ -0,0 +1,134 @@
+#include "c.h"
+
+
+static char *outs(const char *str, FILE *f, char *bp) {
+ if (f)
+ fputs(str, f);
+ else
+ while (*bp = *str++)
+ bp++;
+ return bp;
+}
+
+static char *outd(long n, FILE *f, char *bp) {
+ unsigned long m;
+ char buf[25], *s = buf + sizeof buf;
+
+ *--s = '\0';
+ if (n < 0)
+ m = -n;
+ else
+ m = n;
+ do
+ *--s = m%10 + '0';
+ while ((m /= 10) != 0);
+ if (n < 0)
+ *--s = '-';
+ return outs(s, f, bp);
+}
+
+static char *outu(unsigned long n, int base, FILE *f, char *bp) {
+ char buf[25], *s = buf + sizeof buf;
+
+ *--s = '\0';
+ do
+ *--s = "0123456789abcdef"[n%base];
+ while ((n /= base) != 0);
+ return outs(s, f, bp);
+}
+void print(const char *fmt, ...) {
+ va_list ap;
+
+ va_start(ap, fmt);
+ vfprint(stdout, NULL, fmt, ap);
+ va_end(ap);
+}
+/* fprint - formatted output to f */
+void fprint(FILE *f, const char *fmt, ...) {
+ va_list ap;
+
+ va_start(ap, fmt);
+ vfprint(f, NULL, fmt, ap);
+ va_end(ap);
+}
+
+/* stringf - formatted output to a saved string */
+char *stringf(const char *fmt, ...) {
+ char buf[1024];
+ va_list ap;
+
+ va_start(ap, fmt);
+ vfprint(NULL, buf, fmt, ap);
+ va_end(ap);
+ return string(buf);
+}
+
+/* vfprint - formatted output to f or string bp */
+void vfprint(FILE *f, char *bp, const char *fmt, va_list ap) {
+ for (; *fmt; fmt++)
+ if (*fmt == '%')
+ switch (*++fmt) {
+ case 'd': bp = outd(va_arg(ap, int), f, bp); break;
+ case 'D': bp = outd(va_arg(ap, long), f, bp); break;
+ case 'U': bp = outu(va_arg(ap, unsigned long), 10, f, bp); break;
+ case 'u': bp = outu(va_arg(ap, unsigned), 10, f, bp); break;
+ case 'o': bp = outu(va_arg(ap, unsigned), 8, f, bp); break;
+ case 'X': bp = outu(va_arg(ap, unsigned long), 16, f, bp); break;
+ case 'x': bp = outu(va_arg(ap, unsigned), 16, f, bp); break;
+ case 'f': case 'e':
+ case 'g': {
+ static char format[] = "%f";
+ char buf[128];
+ format[1] = *fmt;
+ sprintf(buf, format, va_arg(ap, double));
+ bp = outs(buf, f, bp);
+ }
+; break;
+ case 's': bp = outs(va_arg(ap, char *), f, bp); break;
+ case 'p': {
+ void *p = va_arg(ap, void *);
+ if (p)
+ bp = outs("0x", f, bp);
+ bp = outu((unsigned long)p, 16, f, bp);
+ break;
+ }
+ case 'c': if (f) fputc(va_arg(ap, int), f); else *bp++ = va_arg(ap, int); break;
+ case 'S': { char *s = va_arg(ap, char *);
+ int n = va_arg(ap, int);
+ if (s)
+ for ( ; n-- > 0; s++)
+ if (f) (void)putc(*s, f); else *bp++ = *s;
+ } break;
+ case 'k': { int t = va_arg(ap, int);
+ static char *tokens[] = {
+#define xx(a,b,c,d,e,f,g) g,
+#define yy(a,b,c,d,e,f,g) g,
+#include "token.h"
+ };
+ assert(tokens[t&0177]);
+ bp = outs(tokens[t&0177], f, bp);
+ } break;
+ case 't': { Type ty = va_arg(ap, Type);
+ assert(f);
+ outtype(ty ? ty : voidtype, f);
+ } break;
+ case 'w': { Coordinate *p = va_arg(ap, Coordinate *);
+ if (p->file && *p->file) {
+ bp = outs(p->file, f, bp);
+ bp = outs(":", f, bp);
+ }
+ bp = outd(p->y, f, bp);
+ } break;
+ case 'I': { int n = va_arg(ap, int);
+ while (--n >= 0)
+ if (f) (void)putc(' ', f); else *bp++ = ' ';
+ } break;
+ default: if (f) (void)putc(*fmt, f); else *bp++ = *fmt; break;
+ }
+ else if (f)
+ (void)putc(*fmt, f);
+ else
+ *bp++ = *fmt;
+ if (!f)
+ *bp = '\0';
+}
diff --git a/lcc/src/pass2.c b/lcc/src/pass2.c
new file mode 100755
index 0000000..f9e41cf
--- /dev/null
+++ b/lcc/src/pass2.c
@@ -0,0 +1,665 @@
+#include "c.h"
+#include "rcc.h"
+#if WIN32
+#include <fcntl.h>
+#include <io.h>
+#endif
+
+
+Interface *IR = NULL;
+int Aflag; /* >= 0 if -A specified */
+int Pflag; /* != 0 if -P specified */
+int glevel; /* == [0-9] if -g[0-9] specified */
+int xref; /* != 0 for cross-reference data */
+Symbol YYnull; /* _YYnull symbol if -n or -nvalidate specified */
+Symbol YYcheck; /* _YYcheck symbol if -nvalidate,check specified */
+
+static int verbose = 1;
+#define VERBOSE(n,arg) (verbose >= n ? (void)(arg):(void)0)
+static int nuids;
+static rcc_item_ty *items;
+static void **itemmap;
+
+static void *uid2type(int uid) {
+ assert(uid >= 0 && uid < nuids);
+ if (itemmap[uid] == NULL) {
+ Type ty;
+ rcc_type_ty type = (void *)items[uid];
+ assert(items[uid]);
+ assert(items[uid]->uid == uid);
+ assert(items[uid]->kind == rcc_Type_enum);
+ type = items[uid]->v.rcc_Type.type;
+ assert(type);
+ switch (type->kind) {
+ case rcc_INT_enum:
+ ty = btot(INT, type->size);
+ assert(ty->align == type->align);
+ break;
+ case rcc_UNSIGNED_enum:
+ ty = btot(UNSIGNED, type->size);
+ assert(ty->align == type->align);
+ break;
+ case rcc_FLOAT_enum:
+ ty = btot(FLOAT, type->size);
+ assert(ty->align == type->align);
+ break;
+ case rcc_VOID_enum:
+ ty = voidtype;
+ break;
+ case rcc_POINTER_enum:
+ ty = ptr(uid2type(type->v.rcc_POINTER.type));
+ break;
+ case rcc_ARRAY_enum:
+ ty = uid2type(type->v.rcc_ARRAY.type);
+ assert(ty->size > 0);
+ ty = array(ty, type->size/ty->size, 0);
+ break;
+ case rcc_CONST_enum:
+ ty = qual(CONST, uid2type(type->v.rcc_CONST.type));
+ break;
+ case rcc_VOLATILE_enum:
+ ty = qual(VOLATILE, uid2type(type->v.rcc_VOLATILE.type));
+ break;
+ case rcc_ENUM_enum: {
+ int i, n = Seq_length(type->v.rcc_ENUM.ids);
+ ty = newstruct(ENUM, string(type->v.rcc_ENUM.tag));
+ ty->type = inttype;
+ ty->size = ty->type->size;
+ ty->align = ty->type->align;
+ ty->u.sym->u.idlist = newarray(n + 1, sizeof *ty->u.sym->u.idlist, PERM);
+ for (i = 0; i < n; i++) {
+ rcc_enum__ty e = Seq_remlo(type->v.rcc_ENUM.ids);
+ Symbol p = install(e->id, &identifiers, GLOBAL, PERM);
+ p->type = ty;
+ p->sclass = ENUM;
+ p->u.value = e->value;
+ ty->u.sym->u.idlist[i] = p;
+ free(e);
+ }
+ ty->u.sym->u.idlist[i] = NULL;
+ Seq_free(&type->v.rcc_ENUM.ids);
+ break;
+ }
+ case rcc_STRUCT_enum: case rcc_UNION_enum: {
+ int i, n;
+ Field *tail;
+ list_ty fields;
+ if (type->kind == rcc_STRUCT_enum) {
+ ty = newstruct(STRUCT, string(type->v.rcc_STRUCT.tag));
+ fields = type->v.rcc_STRUCT.fields;
+ } else {
+ ty = newstruct(UNION, string(type->v.rcc_UNION.tag));
+ fields = type->v.rcc_UNION.fields;
+ }
+ itemmap[uid] = ty; /* recursive types */
+ ty->size = type->size;
+ ty->align = type->align;
+ tail = &ty->u.sym->u.s.flist;
+ n = Seq_length(fields);
+ for (i = 0; i < n; i++) {
+ rcc_field_ty field = Seq_remlo(fields);
+ NEW0(*tail, PERM);
+ (*tail)->name = (char *)field->id;
+ (*tail)->type = uid2type(field->type);
+ (*tail)->offset = field->offset;
+ (*tail)->bitsize = field->bitsize;
+ (*tail)->lsb = field->lsb;
+ if (isconst((*tail)->type))
+ ty->u.sym->u.s.cfields = 1;
+ if (isvolatile((*tail)->type))
+ ty->u.sym->u.s.vfields = 1;
+ tail = &(*tail)->link;
+ free(field);
+ }
+ Seq_free(&fields);
+ break;
+ }
+ case rcc_FUNCTION_enum: {
+ int n = Seq_length(type->v.rcc_FUNCTION.formals);
+ if (n > 0) {
+ int i;
+ Type *proto = newarray(n + 1, sizeof *proto, PERM);
+ for (i = 0; i < n; i++) {
+ int *formal = Seq_remlo(type->v.rcc_FUNCTION.formals);
+ proto[i] = uid2type(*formal);
+ free(formal);
+ }
+ proto[i] = NULL;
+ ty = func(uid2type(type->v.rcc_FUNCTION.type), proto, 0);
+ } else
+ ty = func(uid2type(type->v.rcc_FUNCTION.type), NULL, 1);
+ Seq_free(&type->v.rcc_FUNCTION.formals);
+ break;
+ }
+ default: assert(0);
+ }
+ if (itemmap[uid] == NULL) {
+ itemmap[uid] = ty;
+ free(type);
+ free(items[uid]);
+ items[uid] = NULL;
+ } else
+ assert(itemmap[uid] == ty);
+ }
+ return itemmap[uid];
+}
+
+static Symbol uid2symbol(int uid) {
+ assert(uid >= 0 && uid < nuids);
+ if (itemmap[uid] == NULL) {
+ Symbol p;
+ rcc_symbol_ty symbol;
+ assert(items[uid]);
+ assert(items[uid]->uid == uid);
+ assert(items[uid]->kind == rcc_Symbol_enum);
+ symbol = items[uid]->v.rcc_Symbol.symbol;
+ assert(symbol);
+ NEW0(p, PERM);
+ p->name = (char *)symbol->id;
+ p->scope = symbol->scope;
+ p->sclass = symbol->sclass;
+ p->type = uid2type(symbol->type);
+#define xx(f,n) p->f = symbol->flags>>n;
+ xx(structarg,0)
+ xx(addressed,1)
+ xx(computed,2)
+ xx(temporary,3)
+ xx(generated,4)
+#undef xx
+ p->ref = symbol->ref/10000.0;
+ assert(p->scope != CONSTANTS && p->scope != LABELS);
+ if (p->scope == GLOBAL || p->sclass == STATIC || p->sclass == EXTERN)
+ (*IR->defsymbol)(p);
+ itemmap[uid] = p;
+ free(symbol);
+ free(items[uid]);
+ items[uid] = NULL;
+ }
+ return itemmap[uid];
+}
+
+#define xx(s) static void do##s(rcc_interface_ty);
+xx(Export)
+xx(Import)
+xx(Global)
+xx(Local)
+xx(Address)
+xx(Segment)
+xx(Defaddress)
+xx(Deflabel)
+xx(Defconst)
+xx(Defconstf)
+xx(Defstring)
+xx(Space)
+xx(Function)
+xx(Blockbeg)
+xx(Blockend)
+xx(Forest)
+#undef xx
+static void (*doX[])(rcc_interface_ty in) = {
+#define xx(s) 0,
+xx(Export)
+xx(Import)
+xx(Global)
+xx(Local)
+xx(Address)
+xx(Segment)
+xx(Defaddress)
+xx(Deflabel)
+xx(Defconst)
+xx(Defconstf)
+xx(Defstring)
+xx(Space)
+xx(Function)
+xx(Blockbeg)
+xx(Blockend)
+xx(Forest)
+ 0
+#undef xx
+};
+
+static void interface(rcc_interface_ty in) {
+ assert(in);
+ (*doX[in->kind])(in);
+ free(in);
+}
+
+static void doExport(rcc_interface_ty in) {
+ (*IR->export)(uid2symbol(in->v.rcc_Export.p));
+}
+
+static void doImport(rcc_interface_ty in) {
+ Symbol p = uid2symbol(in->v.rcc_Export.p);
+
+ (*IR->import)(p);
+ p->defined = 1;
+}
+
+static void doGlobal(rcc_interface_ty in) {
+ Symbol p = uid2symbol(in->v.rcc_Global.p);
+
+ p->u.seg = in->v.rcc_Global.seg;
+ (*IR->global)(p);
+ p->defined = 1;
+}
+
+static void doLocal(rcc_interface_ty in) {
+ int uid = in->v.rcc_Local.uid;
+
+ assert(uid >= 0 && uid < nuids);
+ assert(items[uid] == NULL);
+ items[uid] = rcc_Symbol(uid, in->v.rcc_Local.p);
+ if (in->v.rcc_Local.p->scope >= LOCAL)
+ addlocal(uid2symbol(uid));
+}
+
+static void doAddress(rcc_interface_ty in) {
+ int uid = in->v.rcc_Address.uid;
+ Symbol p = uid2symbol(in->v.rcc_Address.p);
+
+ assert(uid >= 0 && uid < nuids);
+ assert(items[uid] == NULL);
+ items[uid] = rcc_Symbol(uid, in->v.rcc_Address.q);
+ if (p->scope == GLOBAL || p->sclass == STATIC || p->sclass == EXTERN)
+ (*IR->address)(uid2symbol(uid), p, in->v.rcc_Address.n);
+ else {
+ Code cp = code(Address);
+ cp->u.addr.sym = uid2symbol(uid);
+ cp->u.addr.base = p;
+ cp->u.addr.offset = in->v.rcc_Address.n;
+ }
+}
+
+static void doSegment(rcc_interface_ty in) {
+ (*IR->segment)(in->v.rcc_Segment.seg);
+}
+
+static void doDefaddress(rcc_interface_ty in) {
+ (*IR->defaddress)(uid2symbol(in->v.rcc_Defaddress.p));
+}
+
+static void doDeflabel(rcc_interface_ty in) {
+ (*IR->defaddress)(findlabel(in->v.rcc_Deflabel.label));
+}
+
+static void doDefconst(rcc_interface_ty in) {
+ Value v;
+
+ v.i = in->v.rcc_Defconst.value;
+ (*IR->defconst)(in->v.rcc_Defconst.suffix, in->v.rcc_Defconst.size, v);
+}
+
+static void doDefconstf(rcc_interface_ty in) {
+ Value v;
+ unsigned *p = (unsigned *)&v.d;
+
+ p[swap] = in->v.rcc_Defconstf.value->msb;
+ p[1-swap] = in->v.rcc_Defconstf.value->lsb;
+ (*IR->defconst)(F, in->v.rcc_Defconstf.size, v);
+ free(in->v.rcc_Defconstf.value);
+}
+
+static void doDefstring(rcc_interface_ty in) {
+ (*IR->defstring)(in->v.rcc_Defstring.s.len, (char *)in->v.rcc_Defstring.s.str);
+ free((char *)in->v.rcc_Defstring.s.str);
+}
+
+static void doSpace(rcc_interface_ty in) {
+ (*IR->space)(in->v.rcc_Space.n);
+}
+
+static void doFunction(rcc_interface_ty in) {
+ int i, n;
+ Symbol *caller, *callee;
+
+ /*
+ Initialize:
+ define the function symbol,
+ initialize callee and caller arrays.
+ */
+ cfunc = uid2symbol(in->v.rcc_Function.f);
+ labels = table(NULL, LABELS);
+ enterscope();
+ n = Seq_length(in->v.rcc_Function.caller);
+ caller = newarray(n + 1, sizeof *caller, FUNC);
+ for (i = 0; i < n; i++) {
+ int *uid = Seq_remlo(in->v.rcc_Function.caller);
+ caller[i] = uid2symbol(*uid);
+ free(uid);
+ }
+ caller[i] = NULL;
+ Seq_free(&in->v.rcc_Function.caller);
+ callee = newarray(n + 1, sizeof *callee, FUNC);
+ for (i = 0; i < n; i++) {
+ int *uid = Seq_remlo(in->v.rcc_Function.callee);
+ callee[i] = uid2symbol(*uid);
+ free(uid);
+ }
+ callee[i] = NULL;
+ Seq_free(&in->v.rcc_Function.callee);
+ cfunc->u.f.callee = callee;
+ cfunc->defined = 1;
+ /*
+ Initialize the code list,
+ traverse the interfaces inside the function;
+ each call appends code list entries.
+ */
+ codelist = &codehead;
+ codelist->next = NULL;
+ n = Seq_length(in->v.rcc_Function.codelist);
+ for (i = 0; i < n; i++)
+ interface(Seq_remlo(in->v.rcc_Function.codelist));
+ Seq_free(&in->v.rcc_Function.codelist);
+ /*
+ Call the back end,
+ Wrap-up.
+ */
+ exitscope();
+ (*IR->function)(cfunc, caller, callee, in->v.rcc_Function.ncalls);
+ cfunc = NULL;
+ labels = NULL;
+}
+
+static struct block {
+ Code begin;
+ struct block *prev;
+} *blockstack = NULL;
+
+static void doBlockbeg(rcc_interface_ty in) {
+ struct block *b;
+ Code cp = code(Blockbeg);
+
+ enterscope();
+ cp->u.block.level = level;
+ cp->u.block.locals = newarray(1, sizeof *cp->u.block.locals, FUNC);
+ cp->u.block.locals[0] = NULL;
+ cp->u.block.identifiers = NULL;
+ cp->u.block.types = NULL;
+ NEW(b, FUNC);
+ b->begin = cp;
+ b->prev = blockstack;
+ blockstack = b;
+}
+
+static void doBlockend(rcc_interface_ty in) {
+ assert(blockstack);
+ code(Blockend)->u.begin = blockstack->begin;
+ blockstack = blockstack->prev;
+ exitscope();
+}
+
+static Node visit(rcc_node_ty node) {
+ int op;
+ Node left = NULL, right = NULL, p = NULL;
+ Symbol sym = NULL;
+
+ switch (node->kind) {
+#define T(x) rcc_##x##_enum
+ case T(CSE): {
+ Symbol q = uid2symbol(node->v.rcc_CSE.uid);
+ assert(q->temporary);
+ q->u.t.cse = p = visit(node->v.rcc_CSE.node);
+ break;
+ }
+ case T(CNST): {
+ Value v;
+ v.i = node->v.rcc_CNST.value;
+ sym = constant(btot(node->suffix, node->size), v);
+ op = CNST;
+ break;
+ }
+ case T(CNSTF): {
+ Value v;
+ unsigned *p = (unsigned *)&v.d;
+ p[swap] = node->v.rcc_CNSTF.value->msb;
+ p[1-swap] = node->v.rcc_CNSTF.value->lsb;
+ sym = constant(btot(node->suffix, node->size), v);
+ free(node->v.rcc_CNSTF.value);
+ op = CNST;
+ break;
+ }
+ case T(ARG):
+ p = newnode(ARG + node->suffix + sizeop(node->size),
+ visit(node->v.rcc_ARG.left), NULL,
+ intconst(node->v.rcc_ARG.len));
+ p->syms[1] = intconst(node->v.rcc_ARG.align);
+ break;
+ case T(ASGN):
+ p = newnode(ASGN + node->suffix + sizeop(node->size),
+ visit(node->v.rcc_ASGN.left), visit(node->v.rcc_ASGN.right),
+ intconst(node->v.rcc_ASGN.len));
+ p->syms[1] = intconst(node->v.rcc_ASGN.align);
+ break;
+ case T(CVT):
+ op = node->v.rcc_CVT.op;
+ left = visit(node->v.rcc_CVT.left);
+ sym = intconst(node->v.rcc_CVT.fromsize);
+ break;
+ case T(CALL):
+ op = CALL;
+ left = visit(node->v.rcc_CALL.left);
+ NEW0(sym, FUNC);
+ sym->type = uid2type(node->v.rcc_CALL.type);
+ break;
+ case T(CALLB):
+ op = CALL;
+ left = visit(node->v.rcc_CALLB.left);
+ right = visit(node->v.rcc_CALLB.right);
+ NEW0(sym, FUNC);
+ sym->type = uid2type(node->v.rcc_CALLB.type);
+ break;
+ case T(RET):
+ op = RET;
+ break;
+ case T(ADDRG):
+ op = ADDRG;
+ sym = uid2symbol(node->v.rcc_ADDRG.uid);
+ break;
+ case T(ADDRL):
+ op = ADDRL;
+ sym = uid2symbol(node->v.rcc_ADDRG.uid);
+ break;
+ case T(ADDRF):
+ op = ADDRF;
+ sym = uid2symbol(node->v.rcc_ADDRG.uid);
+ break;
+ case T(Unary):
+ op = node->v.rcc_Unary.op;
+ left = visit(node->v.rcc_Unary.left);
+ break;
+ case T(Binary):
+ op = node->v.rcc_Binary.op;
+ left = visit(node->v.rcc_Binary.left);
+ right = visit(node->v.rcc_Binary.right);
+ break;
+ case T(Compare):
+ op = node->v.rcc_Compare.op;
+ left = visit(node->v.rcc_Compare.left);
+ right = visit(node->v.rcc_Compare.right);
+ sym = findlabel(node->v.rcc_Compare.label);
+ break;
+ case T(LABEL):
+ op = LABEL;
+ sym = findlabel(node->v.rcc_LABEL.label);
+ break;
+ case T(BRANCH):
+ op = JUMP;
+ left = newnode(ADDRG+P+sizeop(voidptype->size), NULL, NULL, findlabel(node->v.rcc_BRANCH.label));
+ break;
+#undef T
+ default: assert(0);
+ }
+ if (p == NULL)
+ p = newnode(op + node->suffix + sizeop(node->size), left, right, sym);
+ free(node);
+ return p;
+}
+
+static void doForest(rcc_interface_ty in) {
+ Node *tail = &code(Gen)->u.forest;
+ int i, n = Seq_length(in->v.rcc_Forest.nodes);
+
+ for (i = 0; i < n; i++) {
+ *tail = visit(Seq_remlo(in->v.rcc_Forest.nodes));
+ assert(*tail);
+ tail = &(*tail)->link;
+ }
+ *tail = NULL;
+ Seq_free(&in->v.rcc_Forest.nodes);
+}
+
+int main(int argc, char *argv[]) {
+ int i, version;
+ float stamp = (assert(strstr(rcsid, ",v")), strtod(strstr(rcsid, ",v")+2, NULL))
+;
+ char *infile = NULL, *outfile = NULL;
+ rcc_program_ty pickle;
+
+ for (i = 1; i < argc; i++)
+ if (*argv[i] != '-' || strcmp(argv[i], "-") == 0) {
+ if (infile == NULL)
+ infile = argv[i];
+ else if (outfile == NULL)
+ outfile = argv[i];
+ }
+ if (infile != NULL && strcmp(infile, "-") != 0
+ && freopen(infile, "rb", stdin) == NULL) {
+ fprint(stderr, "%s: can't read `%s'\n", argv[0], infile);
+ exit(EXIT_FAILURE);
+ }
+#if WIN32
+ else
+ _setmode(_fileno(stdin), _O_BINARY);
+#endif
+ if (outfile != NULL && strcmp(outfile, "-") != 0
+ && freopen(outfile, "w", stdout) == NULL) {
+ fprint(stderr, "%s: can't write `%s'\n", argv[0], outfile);
+ exit(EXIT_FAILURE);
+ }
+ version = read_int(stdin);
+ assert(version/100 == (int)stamp);
+ pickle = rcc_read_program(stdin);
+ argc = pickle->argc;
+ argv = newarray(argc + 1, sizeof *argv, PERM);
+ {
+ for (i = 0; i < argc; i++) {
+ string_ty *arg = Seq_remlo(pickle->argv);
+ argv[i] = (char *)arg->str;
+ free(arg);
+ }
+ argv[i] = NULL;
+ assert(i == argc);
+ Seq_free(&pickle->argv);
+ }
+ for (i = argc - 1; i > 0; i--)
+ if (strncmp(argv[i], "-target=", 8) == 0)
+ break;
+ if (i > 0) {
+ int j;
+ for (j = 0; bindings[j].name && bindings[j].ir; j++)
+ if (strcmp(&argv[i][8], bindings[j].name) == 0) {
+ IR = bindings[j].ir;
+ break;
+ }
+ }
+ if (!IR) {
+ fprint(stderr, "%s: unknown target", argv[0]);
+ if (i > 0)
+ fprint(stderr, " `%s'", &argv[i][8]);
+ fprint(stderr, "; must specify one of\n");
+ for (i = 0; bindings[i].name; i++)
+ fprint(stderr, "\t-target=%s\n", bindings[i].name);
+ exit(EXIT_FAILURE);
+ }
+ IR->wants_dag = 0; /* pickle's hold trees */
+ init(argc, argv);
+ genlabel(pickle->nlabels);
+ level = GLOBAL;
+ {
+ int i, count;
+ nuids = pickle->nuids;
+ items = newarray(nuids, sizeof *items, PERM);
+ itemmap = newarray(nuids, sizeof *items, PERM);
+ for (i = 0; i < nuids; i++) {
+ itemmap[i] = NULL;
+ items[i] = NULL;
+ }
+ (*IR->progbeg)(argc, argv);
+ count = Seq_length(pickle->items);
+ for (i = 0; i < count; i++) {
+ rcc_item_ty item = Seq_remlo(pickle->items);
+ int uid = item->uid;
+ assert(uid >= 0 && uid < nuids);
+ assert(items[uid] == NULL);
+ items[uid] = item;
+ }
+ Seq_free(&pickle->items);
+#define xx(s) assert(rcc_##s##_enum < sizeof doX/sizeof doX[0] && doX[rcc_##s##_enum]==0); \
+ doX[rcc_##s##_enum] = do##s;
+ xx(Export)
+ xx(Import)
+ xx(Global)
+ xx(Local)
+ xx(Address)
+ xx(Segment)
+ xx(Defaddress)
+ xx(Deflabel)
+ xx(Defconst)
+ xx(Defconstf)
+ xx(Defstring)
+ xx(Space)
+ xx(Function)
+ xx(Blockbeg)
+ xx(Blockend)
+ xx(Forest)
+#undef xx
+ count = Seq_length(pickle->interfaces);
+ for (i = 0; i < count; i++)
+ interface(Seq_remlo(pickle->interfaces));
+ Seq_free(&pickle->interfaces);
+ free(pickle);
+ (*IR->progend)();
+ }
+ deallocate(PERM);
+ return errcnt > 0;
+}
+
+/* main_init - process program arguments */
+void main_init(int argc, char *argv[]) {
+ int i;
+ static int inited;
+
+ if (inited)
+ return;
+ inited = 1;
+ for (i = 1; i < argc; i++)
+ if (strcmp(argv[i], "-g") == 0 || strcmp(argv[i], "-g2") == 0)
+ glevel = 2;
+ else if (strcmp(argv[i], "-w") == 0)
+ wflag++;
+ else if (strcmp(argv[i], "-v") == 0) {
+ fprint(stderr, "%s %s\n", argv[0], rcsid);
+ verbose++;
+ } else if (strncmp(argv[i], "-errout=", 8) == 0) {
+ FILE *f = fopen(argv[i]+8, "w");
+ if (f == NULL) {
+ fprint(stderr, "%s: can't write errors to `%s'\n", argv[0], argv[i]+8);
+ exit(EXIT_FAILURE);
+ }
+ fclose(f);
+ f = freopen(argv[i]+8, "w", stderr);
+ assert(f);
+ } else if (strncmp(argv[i], "-e", 2) == 0) {
+ int x;
+ if ((x = strtol(&argv[i][2], NULL, 0)) > 0)
+ errlimit = x;
+ }
+}
+
+void init(int argc, char *argv[]) {
+ {extern void main_init(int, char *[]); main_init(argc, argv);}
+ {extern void prof_init(int, char *[]); prof_init(argc, argv);}
+ {extern void trace_init(int, char *[]); trace_init(argc, argv);}
+ {extern void type_init(int, char *[]); type_init(argc, argv);}
+ {extern void x86linux_init(int, char *[]); x86linux_init(argc, argv);}
+}
diff --git a/lcc/src/prof.c b/lcc/src/prof.c
new file mode 100755
index 0000000..59ce879
--- /dev/null
+++ b/lcc/src/prof.c
@@ -0,0 +1,227 @@
+#include "c.h"
+
+
+struct callsite {
+ char *file, *name;
+ union coordinate {
+ unsigned int coord;
+ struct { unsigned int y:16,x:10,index:6; } le;
+ struct { unsigned int index:6,x:10,y:16; } be;
+ } u;
+};
+struct func {
+ struct func *link;
+ struct caller *callers;
+ char *name;
+ union coordinate src;
+};
+struct map { /* source code map; 200 coordinates/map */
+ int size;
+ union coordinate u[200];
+};
+
+int npoints; /* # of execution points if -b specified */
+int ncalled = -1; /* #times prof.out says current function was called */
+static Symbol YYlink; /* symbol for file's struct _bbdata */
+static Symbol YYcounts; /* symbol for _YYcounts if -b specified */
+static List maplist; /* list of struct map *'s */
+static List filelist; /* list of file names */
+static Symbol funclist; /* list of struct func *'s */
+static Symbol afunc; /* current function's struct func */
+
+/* bbcall - build tree to set _callsite at call site *cp, emit call site data */
+static void bbcall(Symbol yycounts, Coordinate *cp, Tree *e) {
+ static Symbol caller;
+ Value v;
+ union coordinate u;
+ Symbol p = genident(STATIC, array(voidptype, 0, 0), GLOBAL);
+ Tree t = *e;
+
+ defglobal(p, LIT);
+ defpointer(cp->file ? mkstr(cp->file)->u.c.loc : (Symbol)0);
+ defpointer(mkstr(cfunc->name)->u.c.loc);
+ if (IR->little_endian) {
+ u.le.x = cp->x;
+ u.le.y = cp->y;
+ } else {
+ u.be.x = cp->x;
+ u.be.y = cp->y;
+ }
+ (*IR->defconst)(U, unsignedtype->size, (v.u = u.coord, v));
+ if (caller == 0) {
+ caller = mksymbol(EXTERN, "_caller", ptr(voidptype));
+ caller->defined = 0;
+ }
+ if (generic((*e)->op) != CALL)
+ t = (*e)->kids[0];
+ assert(generic(t->op) == CALL);
+ t = tree(t->op, t->type,
+ tree(RIGHT, t->kids[0]->type,
+ t->kids[0],
+ tree(RIGHT, t->kids[0]->type, asgn(caller, idtree(p)), t->kids[0])),
+ t->kids[1]);
+ if (generic((*e)->op) != CALL)
+ t = tree((*e)->op, (*e)->type, t, (*e)->kids[1]);
+ *e = t;
+}
+
+/* bbentry - return tree for _prologue(&afunc, &YYlink)' */
+static void bbentry(Symbol yylink, Symbol f) {
+ static Symbol prologue;
+
+ afunc = genident(STATIC, array(voidptype, 4, 0), GLOBAL);
+ if (prologue == 0) {
+ prologue = mksymbol(EXTERN, "_prologue", ftype(inttype, voidptype));
+ prologue->defined = 0;
+ }
+ walk(vcall(prologue, voidtype, pointer(idtree(afunc)), pointer(idtree(yylink)), NULL), 0, 0);
+
+}
+
+/* bbexit - return tree for _epilogue(&afunc)' */
+static void bbexit(Symbol yylink, Symbol f, Tree e) {
+ static Symbol epilogue;
+
+ if (epilogue == 0) {
+ epilogue = mksymbol(EXTERN, "_epilogue", ftype(inttype, voidptype));
+ epilogue->defined = 0;
+ }
+ walk(vcall(epilogue, voidtype, pointer(idtree(afunc)), NULL), 0, 0);
+}
+
+/* bbfile - add file to list of file names, return its index */
+static int bbfile(char *file) {
+ if (file) {
+ List lp;
+ int i = 1;
+ if ((lp = filelist) != NULL)
+ do {
+ lp = lp->link;
+ if (((Symbol)lp->x)->u.c.v.p == file)
+ return i;
+ i++;
+ } while (lp != filelist);
+ filelist = append(mkstr(file), filelist);
+ return i;
+ }
+ return 0;
+}
+
+/* bbfunc - emit function name and src coordinates */
+static void bbfunc(Symbol yylink, Symbol f) {
+ Value v;
+ union coordinate u;
+
+ defglobal(afunc, DATA);
+ defpointer(funclist);
+ defpointer(NULL);
+ defpointer(mkstr(f->name)->u.c.loc);
+ if (IR->little_endian) {
+ u.le.x = f->u.f.pt.x;
+ u.le.y = f->u.f.pt.y;
+ u.le.index = bbfile(f->u.f.pt.file);
+ } else {
+ u.be.x = f->u.f.pt.x;
+ u.be.y = f->u.f.pt.y;
+ u.be.index = bbfile(f->u.f.pt.file);
+ }
+ (*IR->defconst)(U, unsignedtype->size, (v.u = u.coord, v));
+ funclist = afunc;
+}
+
+/* bbincr - build tree to increment execution point at *cp */
+static void bbincr(Symbol yycounts, Coordinate *cp, Tree *e) {
+ struct map *mp = maplist->x;
+ Tree t;
+
+ /* append *cp to source map */
+ if (mp->size >= NELEMS(mp->u)) {
+ NEW(mp, PERM);
+ mp->size = 0;
+ maplist = append(mp, maplist);
+ }
+ if (IR->little_endian) {
+ mp->u[mp->size].le.x = cp->x;
+ mp->u[mp->size].le.y = cp->y;
+ mp->u[mp->size++].le.index = bbfile(cp->file);
+ } else {
+ mp->u[mp->size].be.x = cp->x;
+ mp->u[mp->size].be.y = cp->y;
+ mp->u[mp->size++].be.index = bbfile(cp->file);
+ }
+ t = incr('+', rvalue((*optree['+'])(ADD, pointer(idtree(yycounts)),
+ consttree(npoints++, inttype))), consttree(1, inttype));
+ if (*e)
+ *e = tree(RIGHT, (*e)->type, t, *e);
+ else
+ *e = t;
+}
+
+/* bbvars - emit definition for basic block counting data */
+static void bbvars(Symbol yylink) {
+ int i, j, n = npoints;
+ Value v;
+ struct map **mp;
+ Symbol coords, files, *p;
+
+ if (!YYcounts && !yylink)
+ return;
+ if (YYcounts) {
+ if (n <= 0)
+ n = 1;
+ YYcounts->type = array(unsignedtype, n, 0);
+ defglobal(YYcounts, BSS);
+ }
+ files = genident(STATIC, array(charptype, 1, 0), GLOBAL);
+ defglobal(files, LIT);
+ for (p = ltov(&filelist, PERM); *p; p++)
+ defpointer((*p)->u.c.loc);
+ defpointer(NULL);
+ coords = genident(STATIC, array(unsignedtype, n, 0), GLOBAL);
+ defglobal(coords, LIT);
+ for (i = n, mp = ltov(&maplist, PERM); *mp; i -= (*mp)->size, mp++)
+ for (j = 0; j < (*mp)->size; j++)
+ (*IR->defconst)(U, unsignedtype->size, (v.u = (*mp)->u[j].coord, v));
+ if (i > 0)
+ (*IR->space)(i*coords->type->type->size);
+ defpointer(NULL);
+ defglobal(yylink, DATA);
+ defpointer(NULL);
+ (*IR->defconst)(U, unsignedtype->size, (v.u = n, v));
+ defpointer(YYcounts);
+ defpointer(coords);
+ defpointer(files);
+ defpointer(funclist);
+}
+
+/* profInit - initialize basic block profiling options */
+void prof_init(int argc, char *argv[]) {
+ int i;
+ static int inited;
+
+ if (inited)
+ return;
+ inited = 1;
+ type_init(argc, argv);
+ if (IR)
+ for (i = 1; i < argc; i++)
+ if (strncmp(argv[i], "-a", 2) == 0) {
+ if (ncalled == -1
+ && process(argv[i][2] ? &argv[i][2] : "prof.out") > 0)
+ ncalled = 0;
+ } else if ((strcmp(argv[i], "-b") == 0
+ || strcmp(argv[i], "-C") == 0) && YYlink == 0) {
+ YYlink = genident(STATIC, array(unsignedtype, 0, 0), GLOBAL);
+ attach((Apply)bbentry, YYlink, &events.entry);
+ attach((Apply)bbexit, YYlink, &events.returns);
+ attach((Apply)bbfunc, YYlink, &events.exit);
+ attach((Apply)bbvars, YYlink, &events.end);
+ if (strcmp(argv[i], "-b") == 0) {
+ YYcounts = genident(STATIC, array(unsignedtype, 0, 0), GLOBAL);
+ maplist = append(allocate(sizeof (struct map), PERM), maplist);
+ ((struct map *)maplist->x)->size = 0;
+ attach((Apply)bbcall, YYcounts, &events.calls);
+ attach((Apply)bbincr, YYcounts, &events.points);
+ }
+ }
+}
diff --git a/lcc/src/profio.c b/lcc/src/profio.c
new file mode 100755
index 0000000..3e74770
--- /dev/null
+++ b/lcc/src/profio.c
@@ -0,0 +1,276 @@
+/* C compiler: prof.out input
+
+prof.out format:
+#files
+ name
+ ... (#files-1 times)
+#functions
+ name file# x y count caller file x y
+ ... (#functions-1 times)
+#points
+ file# x y count
+ ... (#points-1 times)
+*/
+#include "c.h"
+
+
+struct count { /* count data: */
+ int x, y; /* source coordinate */
+ int count; /* associated execution count */
+};
+
+#define MAXTOKEN 64
+
+struct file { /* per-file prof.out data: */
+ struct file *link; /* link to next file */
+ char *name; /* file name */
+ int size; /* size of counts[] */
+ int count; /* counts[0..count-1] hold valid data */
+ struct count *counts; /* count data */
+ struct func { /* function data: */
+ struct func *link; /* link to next function */
+ char *name; /* function name */
+ struct count count; /* total number of calls */
+ struct caller { /* caller data: */
+ struct caller *link; /* link to next caller */
+ char *name; /* caller's name */
+ char *file; /* call site: file, x, y */
+ int x, y;
+ int count; /* number of calls from this site */
+ } *callers;
+ } *funcs; /* list of functions */
+} *filelist;
+FILE *fp;
+
+/* acaller - add caller and site (file,x,y) to callee's callers list */
+static void acaller(char *caller, char *file, int x, int y, int count, struct func *callee) {
+ struct caller *q;
+
+ assert(callee);
+ for (q = callee->callers; q && (caller != q->name
+ || file != q->file || x != q->x || y != q->y); q = q->link)
+ ;
+ if (!q) {
+ struct caller **r;
+ NEW(q, PERM);
+ q->name = caller;
+ q->file = file;
+ q->x = x;
+ q->y = y;
+ q->count = 0;
+ for (r = &callee->callers; *r && (strcmp(q->name, (*r)->name) > 0
+ || strcmp(q->file, (*r)->file) > 0 || q->y > (*r)->y || q->y > (*r)->y); r = &(*r)->link)
+ ;
+ q->link = *r;
+ *r = q;
+ }
+ q->count += count;
+}
+
+/* compare - return <0, 0, >0 if a<b, a==b, a>b, resp. */
+static int compare(struct count *a, struct count *b) {
+ if (a->y == b->y)
+ return a->x - b->x;
+ return a->y - b->y;
+}
+
+/* findfile - return file name's file list entry, or 0 */
+static struct file *findfile(char *name) {
+ struct file *p;
+
+ for (p = filelist; p; p = p->link)
+ if (p->name == name)
+ return p;
+ return 0;
+}
+
+/* afunction - add function name and its data to file's function list */
+static struct func *afunction(char *name, char *file, int x, int y, int count) {
+ struct file *p = findfile(file);
+ struct func *q;
+
+ assert(p);
+ for (q = p->funcs; q && name != q->name; q = q->link)
+ ;
+ if (!q) {
+ struct func **r;
+ NEW(q, PERM);
+ q->name = name;
+ q->count.x = x;
+ q->count.y = y;
+ q->count.count = 0;
+ q->callers = 0;
+ for (r = &p->funcs; *r && compare(&q->count, &(*r)->count) > 0; r = &(*r)->link)
+ ;
+ q->link = *r;
+ *r = q;
+ }
+ q->count.count += count;
+ return q;
+}
+
+/* apoint - append execution point i to file's data */
+static void apoint(int i, char *file, int x, int y, int count) {
+ struct file *p = findfile(file);
+
+ assert(p);
+ if (i >= p->size) {
+ int j;
+ if (p->size == 0) {
+ p->size = i >= 200 ? 2*i : 200;
+ p->counts = newarray(p->size, sizeof *p->counts, PERM);
+ } else {
+ struct count *new;
+ p->size = 2*i;
+ new = newarray(p->size, sizeof *new, PERM);
+ for (j = 0; j < p->count; j++)
+ new[j] = p->counts[j];
+ p->counts = new;
+ }
+ for (j = p->count; j < p->size; j++) {
+ static struct count z;
+ p->counts[j] = z;
+ }
+ }
+ p->counts[i].x = x;
+ p->counts[i].y = y;
+ p->counts[i].count += count;
+ if (i >= p->count)
+ p->count = i + 1;
+}
+
+/* findcount - return count associated with (file,x,y) or -1 */
+int findcount(char *file, int x, int y) {
+ static struct file *cursor;
+
+ if (cursor == 0 || cursor->name != file)
+ cursor = findfile(file);
+ if (cursor) {
+ int l, u;
+ struct count *c = cursor->counts;
+ for (l = 0, u = cursor->count - 1; l <= u; ) {
+ int k = (l + u)/2;
+ if (c[k].y > y || c[k].y == y && c[k].x > x)
+ u = k - 1;
+ else if (c[k].y < y || c[k].y == y && c[k].x < x)
+ l = k + 1;
+ else
+ return c[k].count;
+ }
+ }
+ return -1;
+}
+
+/* findfunc - return count associated with function name in file or -1 */
+int findfunc(char *name, char *file) {
+ static struct file *cursor;
+
+ if (cursor == 0 || cursor->name != file)
+ cursor = findfile(file);
+ if (cursor) {
+ struct func *p;
+ for (p = cursor->funcs; p; p = p->link)
+ if (p->name == name)
+ return p->count.count;
+ }
+ return -1;
+}
+
+/* getd - read a nonnegative number */
+static int getd(void) {
+ int c, n = 0;
+
+ while ((c = getc(fp)) != EOF && (c == ' ' || c == '\n' || c == '\t'))
+ ;
+ if (c >= '0' && c <= '9') {
+ do
+ n = 10*n + (c - '0');
+ while ((c = getc(fp)) >= '0' && c <= '9');
+ return n;
+ }
+ return -1;
+}
+
+/* getstr - read a string */
+static char *getstr(void) {
+ int c;
+ char buf[MAXTOKEN], *s = buf;
+
+ while ((c = getc(fp)) != EOF && c != ' ' && c != '\n' && c != '\t')
+ if (s - buf < (int)sizeof buf - 2)
+ *s++ = c;
+ *s = 0;
+ return s == buf ? (char *)0 : string(buf);
+}
+
+/* gather - read prof.out data from fd */
+static int gather(void) {
+ int i, nfiles, nfuncs, npoints;
+ char *files[64];
+
+ if ((nfiles = getd()) < 0)
+ return 0;
+ assert(nfiles < NELEMS(files));
+ for (i = 0; i < nfiles; i++) {
+ if ((files[i] = getstr()) == 0)
+ return -1;
+ if (!findfile(files[i])) {
+ struct file *new;
+ NEW(new, PERM);
+ new->name = files[i];
+ new->size = new->count = 0;
+ new->counts = 0;
+ new->funcs = 0;
+ new->link = filelist;
+ filelist = new;
+ }
+ }
+ if ((nfuncs = getd()) < 0)
+ return -1;
+ for (i = 0; i < nfuncs; i++) {
+ struct func *q;
+ char *name, *file;
+ int f, x, y, count;
+ if ((name = getstr()) == 0 || (f = getd()) <= 0
+ || (x = getd()) < 0 || (y = getd()) < 0 || (count = getd()) < 0)
+ return -1;
+ q = afunction(name, files[f-1], x, y, count);
+ if ((name = getstr()) == 0 || (file = getstr()) == 0
+ || (x = getd()) < 0 || (y = getd()) < 0)
+ return -1;
+ if (*name != '?')
+ acaller(name, file, x, y, count, q);
+ }
+ if ((npoints = getd()) < 0)
+ return -1;
+ for (i = 0; i < npoints; i++) {
+ int f, x, y, count;
+ if ((f = getd()) < 0 || (x = getd()) < 0 || (y = getd()) < 0
+ || (count = getd()) < 0)
+ return -1;
+ if (f)
+ apoint(i, files[f-1], x, y, count);
+ }
+ return 1;
+}
+
+/* process - read prof.out data from file */
+int process(char *file) {
+ int more;
+
+ if ((fp = fopen(file, "r")) != NULL) {
+ struct file *p;
+ while ((more = gather()) > 0)
+ ;
+ fclose(fp);
+ if (more < 0)
+ return more;
+ for (p = filelist; p; p = p->link)
+ qsort(p->counts, p->count, sizeof *p->counts,
+ (int (*)(const void *, const void *))
+ compare);
+
+ return 1;
+ }
+ return 0;
+}
diff --git a/lcc/src/rcc.asdl b/lcc/src/rcc.asdl
new file mode 100755
index 0000000..833478e
--- /dev/null
+++ b/lcc/src/rcc.asdl
@@ -0,0 +1,70 @@
+-- lcc IR
+-- $Id: rcc.asdl 145 2001-10-17 21:53:10Z timo $
+module rcc {
+
+-- Pickles start with an int version number, followed by rcc.program
+
+program = (int nuids,int nlabels,item* items,interface* interfaces,int argc,string *argv)
+
+real = (int msb,int lsb)
+
+item = Symbol(symbol symbol)
+ | Type(type type)
+ attributes(int uid)
+
+symbol = (identifier id,int type,int scope,int sclass,int ref,int flags)
+
+field = (identifier id,int type,int offset,int bitsize,int lsb)
+
+enum = (identifier id,int value)
+
+type = INT
+ | UNSIGNED
+ | FLOAT
+ | VOID
+ | POINTER(int type)
+ | ENUM(identifier tag,enum* ids)
+ | STRUCT(identifier tag,field* fields)
+ | UNION(identifier tag,field* fields)
+ | ARRAY(int type)
+ | FUNCTION(int type,int* formals)
+ | CONST(int type)
+ | VOLATILE(int type)
+ attributes(int size,int align)
+
+interface = Export(int p)
+ | Import(int p)
+ | Global(int p,int seg)
+ | Local(int uid,symbol p) -- includes formals
+ | Address(int uid,symbol q,int p,int n)
+ | Segment(int seg)
+ | Defaddress(int p)
+ | Deflabel(int label)
+ | Defconst(int suffix,int size,int value)
+ | Defconstf(int size,real value)
+ | Defstring(string s)
+ | Space(int n)
+ | Function(int f,int* caller,int* callee,int ncalls,interface* codelist)
+ | Blockbeg
+ | Blockend
+ | Forest(node* nodes)
+
+node = CNST(int value)
+ | CNSTF(real value)
+ | ARG(node left,int len,int align)
+ | ASGN(node left,node right,int len,int align)
+ | CVT(int op,node left,int fromsize)
+ | CALL(node left,int type)
+ | CALLB(node left,node right,int type)
+ | RET
+ | ADDRG(int uid)
+ | ADDRL(int uid)
+ | ADDRF(int uid)
+ | Unary(int op,node left) -- INDIR RET JUMP NEG BCOM
+ | Binary(int op,node left,node right) -- ADD SUB DIV MUL MOD BOR BAND BXOR RSH LSH
+ | Compare(int op,node left,node right,int label) -- EQ NE GT GE LE LT
+ | LABEL(int label)
+ | BRANCH(int label)
+ | CSE(int uid,node node)
+ attributes(int suffix,int size)
+}
diff --git a/lcc/src/run.sh b/lcc/src/run.sh
new file mode 100755
index 0000000..432872e
--- /dev/null
+++ b/lcc/src/run.sh
@@ -0,0 +1,51 @@
+#!/bin/sh
+# run .../target/os/tst/foo.s [ remotehost ]
+
+# set -x
+target=`echo $1 | awk -F/ '{ print $(NF-3) }'`
+os=`echo $1 | awk -F/ '{ print $(NF-2) }'`
+dir=$target/$os
+
+case "$1" in
+*symbolic/irix*) idir=include/mips/irix; remotehost=noexecute ;;
+*symbolic/osf*) idir=include/alpha/osf; remotehost=noexecute ;;
+*) idir=include/$dir; remotehost=${2-$REMOTEHOST} ;;
+esac
+
+if [ ! -d "$target/$os" -o ! -d "$idir" ]; then
+ echo 2>&1 $0: unknown combination '"'$target/$os'"'
+ exit 1
+fi
+
+C=`basename $1 .s`
+BUILDDIR=${BUILDDIR-.} LCC="${LCC-${BUILDDIR}/lcc} -Wo-lccdir=$BUILDDIR"
+TSTDIR=${TSTDIR-${BUILDDIR}/$dir/tst}
+if [ ! -d $TSTDIR ]; then mkdir -p $TSTDIR; fi
+
+echo ${BUILDDIR}/rcc$EXE -target=$target/$os $1: 1>&2
+$LCC -S -I$idir -Ualpha -Usun -Uvax -Umips -Ux86 \
+ -Wf-errout=$TSTDIR/$C.2 -D$target -Wf-g0 \
+ -Wf-target=$target/$os -o $1 tst/$C.c
+if [ $? != 0 ]; then remotehost=noexecute; fi
+if [ -r $dir/tst/$C.2bk ]; then
+ diff $dir/tst/$C.2bk $TSTDIR/$C.2
+fi
+if [ -r $dir/tst/$C.sbk ]; then
+ if diff $dir/tst/$C.sbk $TSTDIR/$C.s; then exit 0; fi
+fi
+
+case "$remotehost" in
+noexecute) exit 0 ;;
+""|"-") $LCC -o $TSTDIR/$C$EXE $1; $TSTDIR/$C$EXE <tst/$C.0 >$TSTDIR/$C.1 ;;
+*) rcp $1 $remotehost:
+ if expr "$remotehost" : '.*@' >/dev/null ; then
+ remotehost="`expr $remotehost : '.*@\(.*\)'` -l `expr $remotehost : '\(.*\)@'`"
+ fi
+ rsh $remotehost "cc -o $C$EXE $C.s -lm;./$C$EXE;rm -f $C$EXE $C.[so]" <tst/$C.0 >$TSTDIR/$C.1
+ ;;
+esac
+if [ -r $dir/tst/$C.1bk ]; then
+ diff $dir/tst/$C.1bk $TSTDIR/$C.1
+ exit $?
+fi
+exit 0
diff --git a/lcc/src/simp.c b/lcc/src/simp.c
new file mode 100755
index 0000000..04699bb
--- /dev/null
+++ b/lcc/src/simp.c
@@ -0,0 +1,587 @@
+#include "c.h"
+#include <float.h>
+
+
+#define foldcnst(TYPE,VAR,OP) \
+ if (l->op == CNST+TYPE && r->op == CNST+TYPE) \
+ return cnsttree(ty, l->u.v.VAR OP r->u.v.VAR)
+#define commute(L,R) \
+ if (generic(R->op) == CNST && generic(L->op) != CNST) \
+ do { Tree t = L; L = R; R = t; } while(0)
+#define xfoldcnst(TYPE,VAR,OP,FUNC)\
+ if (l->op == CNST+TYPE && r->op == CNST+TYPE\
+ && FUNC(l->u.v.VAR,r->u.v.VAR,\
+ ty->u.sym->u.limits.min.VAR,\
+ ty->u.sym->u.limits.max.VAR, needconst)) \
+ return cnsttree(ty, l->u.v.VAR OP r->u.v.VAR)
+#define xcvtcnst(FTYPE,SRC,DST,VAR,EXPR) \
+ if (l->op == CNST+FTYPE) do {\
+ if (!explicitCast\
+ && ((SRC) < DST->u.sym->u.limits.min.VAR || (SRC) > DST->u.sym->u.limits.max.VAR))\
+ warning("overflow in converting constant expression from `%t' to `%t'\n", l->type, DST);\
+ if (needconst\
+ || !((SRC) < DST->u.sym->u.limits.min.VAR || (SRC) > DST->u.sym->u.limits.max.VAR))\
+ return cnsttree(ty, (EXPR)); } while(0)
+#define identity(X,Y,TYPE,VAR,VAL) \
+ if (X->op == CNST+TYPE && X->u.v.VAR == VAL) return Y
+#define zerofield(OP,TYPE,VAR) \
+ if (l->op == FIELD \
+ && r->op == CNST+TYPE && r->u.v.VAR == 0)\
+ return eqtree(OP, bittree(BAND, l->kids[0],\
+ cnsttree(unsignedtype, \
+ (unsigned long)fieldmask(l->u.field)<<fieldright(l->u.field))), r)
+#define cfoldcnst(TYPE,VAR,OP) \
+ if (l->op == CNST+TYPE && r->op == CNST+TYPE) \
+ return cnsttree(inttype, (long)(l->u.v.VAR OP r->u.v.VAR))
+#define foldaddp(L,R,RTYPE,VAR) \
+ if (L->op == CNST+P && R->op == CNST+RTYPE) { \
+ Tree e = tree(CNST+P, ty, NULL, NULL);\
+ e->u.v.p = (char *)L->u.v.p + R->u.v.VAR;\
+ return e; }
+#define ufoldcnst(TYPE,EXP) if (l->op == CNST+TYPE) return EXP
+#define sfoldcnst(OP) \
+ if (l->op == CNST+U && r->op == CNST+I \
+ && r->u.v.i >= 0 && r->u.v.i < 8*l->type->size) \
+ return cnsttree(ty, (unsigned long)(l->u.v.u OP r->u.v.i))
+#define geu(L,R,V) \
+ if (R->op == CNST+U && R->u.v.u == 0) do { \
+ warning("result of unsigned comparison is constant\n"); \
+ return tree(RIGHT, inttype, root(L), cnsttree(inttype, (long)(V))); } while(0)
+#define idempotent(OP) if (l->op == OP) return l->kids[0]
+
+int needconst;
+int explicitCast;
+static int addi(long x, long y, long min, long max, int needconst) {
+ int cond = x == 0 || y == 0
+ || x < 0 && y < 0 && x >= min - y
+ || x < 0 && y > 0
+ || x > 0 && y < 0
+ || x > 0 && y > 0 && x <= max - y;
+ if (!cond && needconst) {
+ warning("overflow in constant expression\n");
+ cond = 1;
+ }
+ return cond;
+
+
+}
+
+static int addd(double x, double y, double min, double max, int needconst) {
+ int cond = x == 0 || y == 0
+ || x < 0 && y < 0 && x >= min - y
+ || x < 0 && y > 0
+ || x > 0 && y < 0
+ || x > 0 && y > 0 && x <= max - y;
+ if (!cond && needconst) {
+ warning("overflow in constant expression\n");
+ cond = 1;
+ }
+ return cond;
+
+
+}
+
+static Tree addrtree(Tree e, long n, Type ty) {
+ Symbol p = e->u.sym, q;
+
+ if (p->scope == GLOBAL
+ || p->sclass == STATIC || p->sclass == EXTERN)
+ NEW0(q, PERM);
+ else
+ NEW0(q, FUNC);
+ q->name = stringd(genlabel(1));
+ q->sclass = p->sclass;
+ q->scope = p->scope;
+ assert(isptr(ty) || isarray(ty));
+ q->type = isptr(ty) ? ty->type : ty;
+ q->temporary = p->temporary;
+ q->generated = p->generated;
+ q->addressed = p->addressed;
+ q->computed = 1;
+ q->defined = 1;
+ q->ref = 1;
+ if (p->scope == GLOBAL
+ || p->sclass == STATIC || p->sclass == EXTERN) {
+ if (p->sclass == AUTO)
+ q->sclass = STATIC;
+ (*IR->address)(q, p, n);
+ } else {
+ Code cp;
+ addlocal(p);
+ cp = code(Address);
+ cp->u.addr.sym = q;
+ cp->u.addr.base = p;
+ cp->u.addr.offset = n;
+ }
+ e = tree(e->op, ty, NULL, NULL);
+ e->u.sym = q;
+ return e;
+}
+
+/* div[id] - return 1 if min <= x/y <= max, 0 otherwise */
+static int divi(long x, long y, long min, long max, int needconst) {
+ int cond = y != 0 && !(x == min && y == -1);
+ if (!cond && needconst) {
+ warning("overflow in constant expression\n");
+ cond = 1;
+ }
+ return cond;
+
+
+}
+
+static int divd(double x, double y, double min, double max, int needconst) {
+ int cond;
+
+ if (x < 0) x = -x;
+ if (y < 0) y = -y;
+ cond = y != 0 && !(y < 1 && x > max*y);
+ if (!cond && needconst) {
+ warning("overflow in constant expression\n");
+ cond = 1;
+ }
+ return cond;
+
+}
+
+/* mul[id] - return 1 if min <= x*y <= max, 0 otherwise */
+static int muli(long x, long y, long min, long max, int needconst) {
+ int cond = x > -1 && x <= 1 || y > -1 && y <= 1
+ || x < 0 && y < 0 && -x <= max/-y
+ || x < 0 && y > 0 && x >= min/y
+ || x > 0 && y < 0 && y >= min/x
+ || x > 0 && y > 0 && x <= max/y;
+ if (!cond && needconst) {
+ warning("overflow in constant expression\n");
+ cond = 1;
+ }
+ return cond;
+
+
+}
+
+static int muld(double x, double y, double min, double max, int needconst) {
+ int cond = x >= -1 && x <= 1 || y >= -1 && y <= 1
+ || x < 0 && y < 0 && -x <= max/-y
+ || x < 0 && y > 0 && x >= min/y
+ || x > 0 && y < 0 && y >= min/x
+ || x > 0 && y > 0 && x <= max/y;
+ if (!cond && needconst) {
+ warning("overflow in constant expression\n");
+ cond = 1;
+ }
+ return cond;
+
+
+}
+/* sub[id] - return 1 if min <= x-y <= max, 0 otherwise */
+static int subi(long x, long y, long min, long max, int needconst) {
+ return addi(x, -y, min, max, needconst);
+}
+
+static int subd(double x, double y, double min, double max, int needconst) {
+ return addd(x, -y, min, max, needconst);
+}
+Tree constexpr(int tok) {
+ Tree p;
+
+ needconst++;
+ p = expr1(tok);
+ needconst--;
+ return p;
+}
+
+int intexpr(int tok, int n) {
+ Tree p = constexpr(tok);
+
+ needconst++;
+ if (p->op == CNST+I || p->op == CNST+U)
+ n = cast(p, inttype)->u.v.i;
+ else
+ error("integer expression must be constant\n");
+ needconst--;
+ return n;
+}
+Tree simplify(int op, Type ty, Tree l, Tree r) {
+ int n;
+ Tree p;
+
+ if (optype(op) == 0)
+ op = mkop(op, ty);
+ switch (op) {
+ case ADD+U:
+ foldcnst(U,u,+);
+ commute(r,l);
+ identity(r,l,U,u,0);
+ break;
+ case ADD+I:
+ xfoldcnst(I,i,+,addi);
+ commute(r,l);
+ identity(r,l,I,i,0);
+ break;
+ case CVI+I:
+ xcvtcnst(I,l->u.v.i,ty,i,(long)extend(l->u.v.i,ty));
+ break;
+ case CVU+I:
+ if (l->op == CNST+U) {
+ if (!explicitCast && l->u.v.u > ty->u.sym->u.limits.max.i)
+ warning("overflow in converting constant expression from `%t' to `%t'\n", l->type, ty);
+ if (needconst || !(l->u.v.u > ty->u.sym->u.limits.max.i))
+ return cnsttree(ty, (long)extend(l->u.v.u,ty));
+ }
+ break;
+ case CVP+U:
+ xcvtcnst(P,(unsigned long)l->u.v.p,ty,u,(unsigned long)l->u.v.p);
+ break;
+ case CVU+P:
+ xcvtcnst(U,(void*)l->u.v.u,ty,p,(void*)l->u.v.u);
+ break;
+ case CVP+P:
+ xcvtcnst(P,l->u.v.p,ty,p,l->u.v.p);
+ break;
+ case CVI+U:
+ xcvtcnst(I,l->u.v.i,ty,u,((unsigned long)l->u.v.i)&ones(8*ty->size));
+ break;
+ case CVU+U:
+ xcvtcnst(U,l->u.v.u,ty,u,l->u.v.u&ones(8*ty->size));
+ break;
+
+ case CVI+F:
+ xcvtcnst(I,l->u.v.i,ty,d,(long double)l->u.v.i);
+ case CVU+F:
+ xcvtcnst(U,l->u.v.u,ty,d,(long double)l->u.v.u);
+ break;
+ case CVF+I:
+ xcvtcnst(F,l->u.v.d,ty,i,(long)l->u.v.d);
+ break;
+ case CVF+F: {
+ float d;
+ if (l->op == CNST+F)
+ if (l->u.v.d < ty->u.sym->u.limits.min.d)
+ d = ty->u.sym->u.limits.min.d;
+ else if (l->u.v.d > ty->u.sym->u.limits.max.d)
+ d = ty->u.sym->u.limits.max.d;
+ else
+ d = l->u.v.d;
+ xcvtcnst(F,l->u.v.d,ty,d,(long double)d);
+ break;
+ }
+ case BAND+U:
+ foldcnst(U,u,&);
+ commute(r,l);
+ identity(r,l,U,u,ones(8*ty->size));
+ if (r->op == CNST+U && r->u.v.u == 0)
+ return tree(RIGHT, ty, root(l), cnsttree(ty, 0UL));
+ break;
+ case BAND+I:
+ foldcnst(I,i,&);
+ commute(r,l);
+ identity(r,l,I,i,ones(8*ty->size));
+ if (r->op == CNST+I && r->u.v.u == 0)
+ return tree(RIGHT, ty, root(l), cnsttree(ty, 0L));
+ break;
+
+ case MUL+U:
+ commute(l,r);
+ if (l->op == CNST+U && (n = ispow2(l->u.v.u)) != 0)
+ return simplify(LSH, ty, r, cnsttree(inttype, (long)n));
+ foldcnst(U,u,*);
+ identity(r,l,U,u,1);
+ break;
+ case NE+I:
+ cfoldcnst(I,i,!=);
+ commute(r,l);
+ zerofield(NE,I,i);
+ break;
+
+ case EQ+I:
+ cfoldcnst(I,i,==);
+ commute(r,l);
+ zerofield(EQ,I,i);
+ break;
+ case ADD+P:
+ foldaddp(l,r,I,i);
+ foldaddp(l,r,U,u);
+ foldaddp(r,l,I,i);
+ foldaddp(r,l,U,u);
+ commute(r,l);
+ identity(r,retype(l,ty),I,i,0);
+ identity(r,retype(l,ty),U,u,0);
+ if (isaddrop(l->op)
+ && (r->op == CNST+I && r->u.v.i <= longtype->u.sym->u.limits.max.i
+ && r->u.v.i >= longtype->u.sym->u.limits.min.i
+ || r->op == CNST+U && r->u.v.u <= longtype->u.sym->u.limits.max.i))
+ return addrtree(l, cast(r, longtype)->u.v.i, ty);
+ if (l->op == ADD+P && isaddrop(l->kids[1]->op)
+ && (r->op == CNST+I && r->u.v.i <= longtype->u.sym->u.limits.max.i
+ && r->u.v.i >= longtype->u.sym->u.limits.min.i
+ || r->op == CNST+U && r->u.v.u <= longtype->u.sym->u.limits.max.i))
+ return simplify(ADD+P, ty, l->kids[0],
+ addrtree(l->kids[1], cast(r, longtype)->u.v.i, ty));
+ if ((l->op == ADD+I || l->op == SUB+I)
+ && l->kids[1]->op == CNST+I && isaddrop(r->op))
+ return simplify(ADD+P, ty, l->kids[0],
+ simplify(generic(l->op)+P, ty, r, l->kids[1]));
+ if (l->op == ADD+P && generic(l->kids[1]->op) == CNST
+ && generic(r->op) == CNST)
+ return simplify(ADD+P, ty, l->kids[0],
+ simplify(ADD, l->kids[1]->type, l->kids[1], r));
+ if (l->op == ADD+I && generic(l->kids[1]->op) == CNST
+ && r->op == ADD+P && generic(r->kids[1]->op) == CNST)
+ return simplify(ADD+P, ty, l->kids[0],
+ simplify(ADD+P, ty, r->kids[0],
+ simplify(ADD, r->kids[1]->type, l->kids[1], r->kids[1])));
+ if (l->op == RIGHT && l->kids[1])
+ return tree(RIGHT, ty, l->kids[0],
+ simplify(ADD+P, ty, l->kids[1], r));
+ else if (l->op == RIGHT && l->kids[0])
+ return tree(RIGHT, ty,
+ simplify(ADD+P, ty, l->kids[0], r), NULL);
+ break;
+
+ case ADD+F:
+ xfoldcnst(F,d,+,addd);
+ commute(r,l);
+ break;
+ case AND+I:
+ op = AND;
+ ufoldcnst(I,l->u.v.i ? cond(r) : l); /* 0&&r => 0, 1&&r => r */
+ break;
+ case OR+I:
+ op = OR;
+ /* 0||r => r, 1||r => 1 */
+ ufoldcnst(I,l->u.v.i ? cnsttree(ty, 1L) : cond(r));
+ break;
+ case BCOM+I:
+ ufoldcnst(I,cnsttree(ty, (long)extend((~l->u.v.i)&ones(8*ty->size), ty)));
+ idempotent(BCOM+U);
+ break;
+ case BCOM+U:
+ ufoldcnst(U,cnsttree(ty, (unsigned long)((~l->u.v.u)&ones(8*ty->size))));
+ idempotent(BCOM+U);
+ break;
+ case BOR+U:
+ foldcnst(U,u,|);
+ commute(r,l);
+ identity(r,l,U,u,0);
+ break;
+ case BOR+I:
+ foldcnst(I,i,|);
+ commute(r,l);
+ identity(r,l,I,i,0);
+ break;
+ case BXOR+U:
+ foldcnst(U,u,^);
+ commute(r,l);
+ identity(r,l,U,u,0);
+ break;
+ case BXOR+I:
+ foldcnst(I,i,^);
+ commute(r,l);
+ identity(r,l,I,i,0);
+ break;
+ case DIV+F:
+ xfoldcnst(F,d,/,divd);
+ break;
+ case DIV+I:
+ identity(r,l,I,i,1);
+ if (r->op == CNST+I && r->u.v.i == 0
+ || l->op == CNST+I && l->u.v.i == ty->u.sym->u.limits.min.i
+ && r->op == CNST+I && r->u.v.i == -1)
+ break;
+ xfoldcnst(I,i,/,divi);
+ break;
+ case DIV+U:
+ identity(r,l,U,u,1);
+ if (r->op == CNST+U && r->u.v.u == 0)
+ break;
+ if (r->op == CNST+U && (n = ispow2(r->u.v.u)) != 0)
+ return simplify(RSH, ty, l, cnsttree(inttype, (long)n));
+ foldcnst(U,u,/);
+ break;
+ case EQ+F:
+ cfoldcnst(F,d,==);
+ commute(r,l);
+ break;
+ case EQ+U:
+ cfoldcnst(U,u,==);
+ commute(r,l);
+ zerofield(EQ,U,u);
+ break;
+ case GE+F: cfoldcnst(F,d,>=); break;
+ case GE+I: cfoldcnst(I,i,>=); break;
+ case GE+U:
+ geu(l,r,1); /* l >= 0 => (l,1) */
+ cfoldcnst(U,u,>=);
+ if (l->op == CNST+U && l->u.v.u == 0) /* 0 >= r => r == 0 */
+ return eqtree(EQ, r, l);
+ break;
+ case GT+F: cfoldcnst(F,d, >); break;
+ case GT+I: cfoldcnst(I,i, >); break;
+ case GT+U:
+ geu(r,l,0); /* 0 > r => (r,0) */
+ cfoldcnst(U,u, >);
+ if (r->op == CNST+U && r->u.v.u == 0) /* l > 0 => l != 0 */
+ return eqtree(NE, l, r);
+ break;
+ case LE+F: cfoldcnst(F,d,<=); break;
+ case LE+I: cfoldcnst(I,i,<=); break;
+ case LE+U:
+ geu(r,l,1); /* 0 <= r => (r,1) */
+ cfoldcnst(U,u,<=);
+ if (r->op == CNST+U && r->u.v.u == 0) /* l <= 0 => l == 0 */
+ return eqtree(EQ, l, r);
+ break;
+ case LSH+I:
+ identity(r,l,I,i,0);
+ if (l->op == CNST+I && r->op == CNST+I
+ && r->u.v.i >= 0 && r->u.v.i < 8*l->type->size
+ && muli(l->u.v.i, 1<<r->u.v.i, ty->u.sym->u.limits.min.i, ty->u.sym->u.limits.max.i, needconst))
+ return cnsttree(ty, (long)(l->u.v.i<<r->u.v.i));
+ if (r->op == CNST+I && (r->u.v.i >= 8*ty->size || r->u.v.i < 0)) {
+ warning("shifting an `%t' by %d bits is undefined\n", ty, r->u.v.i);
+ break;
+ }
+
+ break;
+ case LSH+U:
+ identity(r,l,I,i,0);
+ sfoldcnst(<<);
+ if (r->op == CNST+I && (r->u.v.i >= 8*ty->size || r->u.v.i < 0)) {
+ warning("shifting an `%t' by %d bits is undefined\n", ty, r->u.v.i);
+ break;
+ }
+
+ break;
+
+ case LT+F: cfoldcnst(F,d, <); break;
+ case LT+I: cfoldcnst(I,i, <); break;
+ case LT+U:
+ geu(l,r,0); /* l < 0 => (l,0) */
+ cfoldcnst(U,u, <);
+ if (l->op == CNST+U && l->u.v.u == 0) /* 0 < r => r != 0 */
+ return eqtree(NE, r, l);
+ break;
+ case MOD+I:
+ if (r->op == CNST+I && r->u.v.i == 1) /* l%1 => (l,0) */
+ return tree(RIGHT, ty, root(l), cnsttree(ty, 0L));
+ if (r->op == CNST+I && r->u.v.i == 0
+ || l->op == CNST+I && l->u.v.i == ty->u.sym->u.limits.min.i
+ && r->op == CNST+I && r->u.v.i == -1)
+ break;
+ xfoldcnst(I,i,%,divi);
+ break;
+ case MOD+U:
+ if (r->op == CNST+U && ispow2(r->u.v.u)) /* l%2^n => l&(2^n-1) */
+ return bittree(BAND, l, cnsttree(ty, r->u.v.u - 1));
+ if (r->op == CNST+U && r->u.v.u == 0)
+ break;
+ foldcnst(U,u,%);
+ break;
+ case MUL+F:
+ xfoldcnst(F,d,*,muld);
+ commute(l,r);
+ break;
+ case MUL+I:
+ commute(l,r);
+ xfoldcnst(I,i,*,muli);
+ if (l->op == CNST+I && r->op == ADD+I && r->kids[1]->op == CNST+I)
+ /* c1*(x + c2) => c1*x + c1*c2 */
+ return simplify(ADD, ty, simplify(MUL, ty, l, r->kids[0]),
+ simplify(MUL, ty, l, r->kids[1]));
+ if (l->op == CNST+I && r->op == SUB+I && r->kids[1]->op == CNST+I)
+ /* c1*(x - c2) => c1*x - c1*c2 */
+ return simplify(SUB, ty, simplify(MUL, ty, l, r->kids[0]),
+ simplify(MUL, ty, l, r->kids[1]));
+ if (l->op == CNST+I && l->u.v.i > 0 && (n = ispow2(l->u.v.i)) != 0)
+ /* 2^n * r => r<<n */
+ return simplify(LSH, ty, r, cnsttree(inttype, (long)n));
+ identity(r,l,I,i,1);
+ break;
+ case NE+F:
+ cfoldcnst(F,d,!=);
+ commute(r,l);
+ break;
+ case NE+U:
+ cfoldcnst(U,u,!=);
+ commute(r,l);
+ zerofield(NE,U,u);
+ break;
+ case NEG+F:
+ ufoldcnst(F,cnsttree(ty, -l->u.v.d));
+ idempotent(NEG+F);
+ break;
+ case NEG+I:
+ if (l->op == CNST+I) {
+ if (needconst && l->u.v.i == ty->u.sym->u.limits.min.i)
+ warning("overflow in constant expression\n");
+ if (needconst || l->u.v.i != ty->u.sym->u.limits.min.i)
+ return cnsttree(ty, -l->u.v.i);
+ }
+ idempotent(NEG+I);
+ break;
+ case NOT+I:
+ op = NOT;
+ ufoldcnst(I,cnsttree(ty, !l->u.v.i));
+ break;
+ case RSH+I:
+ identity(r,l,I,i,0);
+ if (l->op == CNST+I && r->op == CNST+I
+ && r->u.v.i >= 0 && r->u.v.i < 8*l->type->size) {
+ long n = l->u.v.i>>r->u.v.i;
+ if (l->u.v.i < 0)
+ n |= ~0UL<<(8*l->type->size - r->u.v.i);
+ return cnsttree(ty, n);
+ }
+ if (r->op == CNST+I && (r->u.v.i >= 8*ty->size || r->u.v.i < 0)) {
+ warning("shifting an `%t' by %d bits is undefined\n", ty, r->u.v.i);
+ break;
+ }
+
+ break;
+ case RSH+U:
+ identity(r,l,I,i,0);
+ sfoldcnst(>>);
+ if (r->op == CNST+I && (r->u.v.i >= 8*ty->size || r->u.v.i < 0)) {
+ warning("shifting an `%t' by %d bits is undefined\n", ty, r->u.v.i);
+ break;
+ }
+
+ break;
+ case SUB+F:
+ xfoldcnst(F,d,-,subd);
+ break;
+ case SUB+I:
+ xfoldcnst(I,i,-,subi);
+ identity(r,l,I,i,0);
+ break;
+ case SUB+U:
+ foldcnst(U,u,-);
+ identity(r,l,U,u,0);
+ break;
+ case SUB+P:
+ if (l->op == CNST+P && r->op == CNST+P)
+ return cnsttree(ty, (long)((char *)l->u.v.p - (char *)r->u.v.p));
+ if (r->op == CNST+I || r->op == CNST+U)
+ return simplify(ADD, ty, l,
+ cnsttree(inttype, r->op == CNST+I ? -r->u.v.i : -(long)r->u.v.u));
+ if (isaddrop(l->op) && r->op == ADD+I && r->kids[1]->op == CNST+I)
+ /* l - (x + c) => l-c - x */
+ return simplify(SUB, ty,
+ simplify(SUB, ty, l, r->kids[1]), r->kids[0]);
+ break;
+ default:assert(0);
+ }
+ return tree(op, ty, l, r);
+}
+/* ispow2 - if u > 1 && u == 2^n, return n, otherwise return 0 */
+int ispow2(unsigned long u) {
+ int n;
+
+ if (u > 1 && (u&(u-1)) == 0)
+ for (n = 0; u; u >>= 1, n++)
+ if (u&1)
+ return n;
+ return 0;
+}
+
diff --git a/lcc/src/sparc.md b/lcc/src/sparc.md
new file mode 100755
index 0000000..0171492
--- /dev/null
+++ b/lcc/src/sparc.md
@@ -0,0 +1,1163 @@
+%{
+#include "c.h"
+#define NODEPTR_TYPE Node
+#define OP_LABEL(p) ((p)->op)
+#define LEFT_CHILD(p) ((p)->kids[0])
+#define RIGHT_CHILD(p) ((p)->kids[1])
+#define STATE_LABEL(p) ((p)->x.state)
+static void address(Symbol, Symbol, long);
+static void blkfetch(int, int, int, int);
+static void blkloop(int, int, int, int, int, int[]);
+static void blkstore(int, int, int, int);
+static void defaddress(Symbol);
+static void defconst(int, int, Value);
+static void defstring(int, char *);
+static void defsymbol(Symbol);
+static void doarg(Node);
+static void emit2(Node);
+static void export(Symbol);
+static void clobber(Node);
+static void function(Symbol, Symbol [], Symbol [], int);
+static void global(Symbol);
+static void import(Symbol);
+static void local(Symbol);
+static void progbeg(int, char **);
+static void progend(void);
+static void segment(int);
+static void space(int);
+static void target(Node);
+static int imm(Node);
+static void renameregs(void);
+extern Interface sparcIR, solarisIR;
+static void defsymbol2(Symbol);
+static void export2(Symbol);
+static void globalend(void);
+static void global2(Symbol);
+static void segment2(int);
+static void progend2(void);
+
+extern char *stabprefix;
+extern void stabblock(int, int, Symbol*);
+extern void stabend(Coordinate *, Symbol, Coordinate **, Symbol *, Symbol *);
+extern void stabfend(Symbol, int);
+extern void stabinit(char *, int, char *[]);
+extern void stabline(Coordinate *);
+extern void stabsym(Symbol);
+extern void stabtype(Symbol);
+static Symbol greg[32], gregw;
+static Symbol *oreg = &greg[8], *ireg = &greg[24];
+static Symbol freg[32], freg2[32];
+static Symbol fregw, freg2w;
+
+static int regvars;
+static int retstruct;
+
+static int pflag = 0;
+
+static int cseg;
+
+%}
+%start stmt
+%term CNSTF4=4113
+%term CNSTF8=8209
+%term CNSTF16=16401
+%term CNSTI1=1045
+%term CNSTI2=2069
+%term CNSTI4=4117
+%term CNSTI8=8213
+%term CNSTP4=4119
+%term CNSTP8=8215
+%term CNSTU1=1046
+%term CNSTU2=2070
+%term CNSTU4=4118
+%term CNSTU8=8214
+
+%term ARGB=41
+%term ARGF4=4129
+%term ARGF8=8225
+%term ARGF16=16417
+%term ARGI4=4133
+%term ARGI8=8229
+%term ARGP4=4135
+%term ARGP8=8231
+%term ARGU4=4134
+%term ARGU8=8230
+
+%term ASGNB=57
+%term ASGNF4=4145
+%term ASGNF8=8241
+%term ASGNF16=16433
+%term ASGNI1=1077
+%term ASGNI2=2101
+%term ASGNI4=4149
+%term ASGNI8=8245
+%term ASGNP4=4151
+%term ASGNP8=8247
+%term ASGNU1=1078
+%term ASGNU2=2102
+%term ASGNU4=4150
+%term ASGNU8=8246
+
+%term INDIRB=73
+%term INDIRF4=4161
+%term INDIRF8=8257
+%term INDIRF16=16449
+%term INDIRI1=1093
+%term INDIRI2=2117
+%term INDIRI4=4165
+%term INDIRI8=8261
+%term INDIRP4=4167
+%term INDIRP8=8263
+%term INDIRU1=1094
+%term INDIRU2=2118
+%term INDIRU4=4166
+%term INDIRU8=8262
+
+%term CVFF4=4209
+%term CVFF8=8305
+%term CVFF16=16497
+%term CVFI4=4213
+%term CVFI8=8309
+
+%term CVIF4=4225
+%term CVIF8=8321
+%term CVIF16=16513
+%term CVII1=1157
+%term CVII2=2181
+%term CVII4=4229
+%term CVII8=8325
+%term CVIU1=1158
+%term CVIU2=2182
+%term CVIU4=4230
+%term CVIU8=8326
+
+%term CVPP4=4247
+%term CVPP8=8343
+%term CVPP16=16535
+%term CVPU4=4246
+%term CVPU8=8342
+
+%term CVUI1=1205
+%term CVUI2=2229
+%term CVUI4=4277
+%term CVUI8=8373
+%term CVUP4=4279
+%term CVUP8=8375
+%term CVUP16=16567
+%term CVUU1=1206
+%term CVUU2=2230
+%term CVUU4=4278
+%term CVUU8=8374
+
+%term NEGF4=4289
+%term NEGF8=8385
+%term NEGF16=16577
+%term NEGI4=4293
+%term NEGI8=8389
+
+%term CALLB=217
+%term CALLF4=4305
+%term CALLF8=8401
+%term CALLF16=16593
+%term CALLI4=4309
+%term CALLI8=8405
+%term CALLP4=4311
+%term CALLP8=8407
+%term CALLU4=4310
+%term CALLU8=8406
+%term CALLV=216
+
+%term RETF4=4337
+%term RETF8=8433
+%term RETF16=16625
+%term RETI4=4341
+%term RETI8=8437
+%term RETP4=4343
+%term RETP8=8439
+%term RETU4=4342
+%term RETU8=8438
+%term RETV=248
+
+%term ADDRGP4=4359
+%term ADDRGP8=8455
+
+%term ADDRFP4=4375
+%term ADDRFP8=8471
+
+%term ADDRLP4=4391
+%term ADDRLP8=8487
+
+%term ADDF4=4401
+%term ADDF8=8497
+%term ADDF16=16689
+%term ADDI4=4405
+%term ADDI8=8501
+%term ADDP4=4407
+%term ADDP8=8503
+%term ADDU4=4406
+%term ADDU8=8502
+
+%term SUBF4=4417
+%term SUBF8=8513
+%term SUBF16=16705
+%term SUBI4=4421
+%term SUBI8=8517
+%term SUBP4=4423
+%term SUBP8=8519
+%term SUBU4=4422
+%term SUBU8=8518
+
+%term LSHI4=4437
+%term LSHI8=8533
+%term LSHU4=4438
+%term LSHU8=8534
+
+%term MODI4=4453
+%term MODI8=8549
+%term MODU4=4454
+%term MODU8=8550
+
+%term RSHI4=4469
+%term RSHI8=8565
+%term RSHU4=4470
+%term RSHU8=8566
+
+%term BANDI4=4485
+%term BANDI8=8581
+%term BANDU4=4486
+%term BANDU8=8582
+
+%term BCOMI4=4501
+%term BCOMI8=8597
+%term BCOMU4=4502
+%term BCOMU8=8598
+
+%term BORI4=4517
+%term BORI8=8613
+%term BORU4=4518
+%term BORU8=8614
+
+%term BXORI4=4533
+%term BXORI8=8629
+%term BXORU4=4534
+%term BXORU8=8630
+
+%term DIVF4=4545
+%term DIVF8=8641
+%term DIVF16=16833
+%term DIVI4=4549
+%term DIVI8=8645
+%term DIVU4=4550
+%term DIVU8=8646
+
+%term MULF4=4561
+%term MULF8=8657
+%term MULF16=16849
+%term MULI4=4565
+%term MULI8=8661
+%term MULU4=4566
+%term MULU8=8662
+
+%term EQF4=4577
+%term EQF8=8673
+%term EQF16=16865
+%term EQI4=4581
+%term EQI8=8677
+%term EQU4=4582
+%term EQU8=8678
+
+%term GEF4=4593
+%term GEF8=8689
+%term GEI4=4597
+%term GEI8=8693
+%term GEI16=16885
+%term GEU4=4598
+%term GEU8=8694
+
+%term GTF4=4609
+%term GTF8=8705
+%term GTF16=16897
+%term GTI4=4613
+%term GTI8=8709
+%term GTU4=4614
+%term GTU8=8710
+
+%term LEF4=4625
+%term LEF8=8721
+%term LEF16=16913
+%term LEI4=4629
+%term LEI8=8725
+%term LEU4=4630
+%term LEU8=8726
+
+%term LTF4=4641
+%term LTF8=8737
+%term LTF16=16929
+%term LTI4=4645
+%term LTI8=8741
+%term LTU4=4646
+%term LTU8=8742
+
+%term NEF4=4657
+%term NEF8=8753
+%term NEF16=16945
+%term NEI4=4661
+%term NEI8=8757
+%term NEU4=4662
+%term NEU8=8758
+
+%term JUMPV=584
+
+%term LABELV=600
+
+%term LOADB=233
+%term LOADF4=4321
+%term LOADF8=8417
+%term LOADF16=16609
+%term LOADI1=1253
+%term LOADI2=2277
+%term LOADI4=4325
+%term LOADI8=8421
+%term LOADP4=4327
+%term LOADP8=8423
+%term LOADU1=1254
+%term LOADU2=2278
+%term LOADU4=4326
+%term LOADU8=8422
+
+%term VREGP=711
+%%
+reg: INDIRI1(VREGP) "# read register\n"
+reg: INDIRU1(VREGP) "# read register\n"
+
+reg: INDIRI2(VREGP) "# read register\n"
+reg: INDIRU2(VREGP) "# read register\n"
+
+reg: INDIRF4(VREGP) "# read register\n"
+reg: INDIRI4(VREGP) "# read register\n"
+reg: INDIRP4(VREGP) "# read register\n"
+reg: INDIRU4(VREGP) "# read register\n"
+
+reg: INDIRF8(VREGP) "# read register\n"
+reg: INDIRI8(VREGP) "# read register\n"
+reg: INDIRP8(VREGP) "# read register\n"
+reg: INDIRU8(VREGP) "# read register\n"
+
+stmt: ASGNI1(VREGP,reg) "# write register\n"
+stmt: ASGNU1(VREGP,reg) "# write register\n"
+
+stmt: ASGNI2(VREGP,reg) "# write register\n"
+stmt: ASGNU2(VREGP,reg) "# write register\n"
+
+stmt: ASGNF4(VREGP,reg) "# write register\n"
+stmt: ASGNI4(VREGP,reg) "# write register\n"
+stmt: ASGNP4(VREGP,reg) "# write register\n"
+stmt: ASGNU4(VREGP,reg) "# write register\n"
+
+stmt: ASGNF8(VREGP,reg) "# write register\n"
+stmt: ASGNI8(VREGP,reg) "# write register\n"
+stmt: ASGNP8(VREGP,reg) "# write register\n"
+stmt: ASGNU8(VREGP,reg) "# write register\n"
+con: CNSTI1 "%a"
+con: CNSTU1 "%a"
+
+con: CNSTI2 "%a"
+con: CNSTU2 "%a"
+
+con: CNSTI4 "%a"
+con: CNSTU4 "%a"
+con: CNSTP4 "%a"
+
+con: CNSTI8 "%a"
+con: CNSTU8 "%a"
+con: CNSTP8 "%a"
+stmt: reg ""
+reg: ADDRGP4 "set %a,%%%c\n" 1
+stk13: ADDRFP4 "%a" imm(a)
+stk13: ADDRLP4 "%a" imm(a)
+reg: stk13 "add %0,%%fp,%%%c\n" 1
+stk: ADDRFP4 "set %a,%%%c\n" 2
+stk: ADDRLP4 "set %a,%%%c\n" 2
+reg: ADDRFP4 "set %a,%%%c\nadd %%%c,%%fp,%%%c\n" 3
+reg: ADDRLP4 "set %a,%%%c\nadd %%%c,%%fp,%%%c\n" 3
+con13: CNSTI1 "%a" imm(a)
+con13: CNSTI2 "%a" imm(a)
+con13: CNSTI4 "%a" imm(a)
+con13: CNSTU1 "%a" imm(a)
+con13: CNSTU2 "%a" imm(a)
+con13: CNSTU4 "%a" imm(a)
+con13: CNSTP4 "%a" imm(a)
+base: ADDI4(reg,con13) "%%%0+%1"
+base: ADDP4(reg,con13) "%%%0+%1"
+base: ADDU4(reg,con13) "%%%0+%1"
+base: reg "%%%0"
+base: con13 "%0"
+base: stk13 "%%fp+%0"
+addr: base "%0"
+addr: ADDI4(reg,reg) "%%%0+%%%1"
+addr: ADDP4(reg,reg) "%%%0+%%%1"
+addr: ADDU4(reg,reg) "%%%0+%%%1"
+addr: stk "%%fp+%%%0"
+reg: INDIRI1(addr) "ldsb [%0],%%%c\n" 1
+reg: INDIRI2(addr) "ldsh [%0],%%%c\n" 1
+reg: INDIRI4(addr) "ld [%0],%%%c\n" 1
+reg: INDIRU1(addr) "ldub [%0],%%%c\n" 1
+reg: INDIRU2(addr) "lduh [%0],%%%c\n" 1
+reg: INDIRU4(addr) "ld [%0],%%%c\n" 1
+reg: INDIRP4(addr) "ld [%0],%%%c\n" 1
+reg: INDIRF4(addr) "ld [%0],%%f%c\n" 1
+stmt: ASGNI1(addr,reg) "stb %%%1,[%0]\n" 1
+stmt: ASGNI2(addr,reg) "sth %%%1,[%0]\n" 1
+stmt: ASGNI4(addr,reg) "st %%%1,[%0]\n" 1
+stmt: ASGNU1(addr,reg) "stb %%%1,[%0]\n" 1
+stmt: ASGNU2(addr,reg) "sth %%%1,[%0]\n" 1
+stmt: ASGNU4(addr,reg) "st %%%1,[%0]\n" 1
+stmt: ASGNP4(addr,reg) "st %%%1,[%0]\n" 1
+stmt: ASGNF4(addr,reg) "st %%f%1,[%0]\n" 1
+addrl: ADDRLP4 "%%%fp+%a" imm(a)
+
+reg: INDIRF8(addrl) "ldd [%0],%%f%c\n" 1
+stmt: ASGNF8(addrl,reg) "std %%f%1,[%0]\n" 1
+reg: INDIRF8(base) "ld2 [%0],%%f%c\n" 2
+stmt: ASGNF8(base,reg) "st2 %%f%1,[%0]\n" 2
+spill: ADDRLP4 "%a" !imm(a)
+
+stmt: ASGNI1(spill,reg) "set %0,%%g1\nstb %%%1,[%%fp+%%g1]\n"
+stmt: ASGNI2(spill,reg) "set %0,%%g1\nsth %%%1,[%%fp+%%g1]\n"
+stmt: ASGNI4(spill,reg) "set %0,%%g1\nst %%%1,[%%fp+%%g1]\n"
+stmt: ASGNU1(spill,reg) "set %0,%%g1\nstb %%%1,[%%fp+%%g1]\n"
+stmt: ASGNU2(spill,reg) "set %0,%%g1\nsth %%%1,[%%fp+%%g1]\n"
+stmt: ASGNU4(spill,reg) "set %0,%%g1\nst %%%1,[%%fp+%%g1]\n"
+stmt: ASGNP4(spill,reg) "set %0,%%g1\nst %%%1,[%%fp+%%g1]\n"
+stmt: ASGNF4(spill,reg) "set %0,%%g1\nst %%f%1,[%%fp+%%g1]\n"
+stmt: ASGNF8(spill,reg) "set %0,%%g1\nstd %%f%1,[%%fp+%%g1]\n"
+reg: CVII4(INDIRI1(addr)) "ldsb [%0],%%%c\n" 1
+reg: CVII4(INDIRI2(addr)) "ldsh [%0],%%%c\n" 1
+reg: CVUU4(INDIRU1(addr)) "ldub [%0],%%%c\n" 1
+reg: CVUU4(INDIRU2(addr)) "lduh [%0],%%%c\n" 1
+reg: CVUI4(INDIRU1(addr)) "ldub [%0],%%%c\n" 1
+reg: CVUI4(INDIRU2(addr)) "lduh [%0],%%%c\n" 1
+reg: LOADI1(reg) "mov %%%0,%%%c\n" move(a)
+reg: LOADI2(reg) "mov %%%0,%%%c\n" move(a)
+reg: LOADI4(reg) "mov %%%0,%%%c\n" move(a)
+reg: LOADP4(reg) "mov %%%0,%%%c\n" move(a)
+reg: LOADU1(reg) "mov %%%0,%%%c\n" move(a)
+reg: LOADU2(reg) "mov %%%0,%%%c\n" move(a)
+reg: LOADU4(reg) "mov %%%0,%%%c\n" move(a)
+reg: CNSTI1 "# reg\n" range(a, 0, 0)
+reg: CNSTI2 "# reg\n" range(a, 0, 0)
+reg: CNSTI4 "# reg\n" range(a, 0, 0)
+reg: CNSTP4 "# reg\n" range(a, 0, 0)
+reg: CNSTU1 "# reg\n" range(a, 0, 0)
+reg: CNSTU2 "# reg\n" range(a, 0, 0)
+reg: CNSTU4 "# reg\n" range(a, 0, 0)
+reg: con "set %0,%%%c\n" 1
+rc: con13 "%0"
+rc: reg "%%%0"
+reg: ADDI4(reg,rc) "add %%%0,%1,%%%c\n" 1
+reg: ADDP4(reg,rc) "add %%%0,%1,%%%c\n" 1
+reg: ADDU4(reg,rc) "add %%%0,%1,%%%c\n" 1
+reg: BANDI4(reg,rc) "and %%%0,%1,%%%c\n" 1
+reg: BORI4(reg,rc) "or %%%0,%1,%%%c\n" 1
+reg: BXORI4(reg,rc) "xor %%%0,%1,%%%c\n" 1
+reg: BANDU4(reg,rc) "and %%%0,%1,%%%c\n" 1
+reg: BORU4(reg,rc) "or %%%0,%1,%%%c\n" 1
+reg: BXORU4(reg,rc) "xor %%%0,%1,%%%c\n" 1
+reg: SUBI4(reg,rc) "sub %%%0,%1,%%%c\n" 1
+reg: SUBP4(reg,rc) "sub %%%0,%1,%%%c\n" 1
+reg: SUBU4(reg,rc) "sub %%%0,%1,%%%c\n" 1
+rc5: CNSTI4 "%a" range(a, 0, 31)
+rc5: reg "%%%0"
+reg: LSHI4(reg,rc5) "sll %%%0,%1,%%%c\n" 1
+reg: LSHU4(reg,rc5) "sll %%%0,%1,%%%c\n" 1
+reg: RSHI4(reg,rc5) "sra %%%0,%1,%%%c\n" 1
+reg: RSHU4(reg,rc5) "srl %%%0,%1,%%%c\n" 1
+reg: BANDI4(reg,BCOMI4(rc)) "andn %%%0,%1,%%%c\n" 1
+reg: BORI4(reg,BCOMI4(rc)) "orn %%%0,%1,%%%c\n" 1
+reg: BXORI4(reg,BCOMI4(rc)) "xnor %%%0,%1,%%%c\n" 1
+reg: BANDU4(reg,BCOMU4(rc)) "andn %%%0,%1,%%%c\n" 1
+reg: BORU4(reg,BCOMU4(rc)) "orn %%%0,%1,%%%c\n" 1
+reg: BXORU4(reg,BCOMU4(rc)) "xnor %%%0,%1,%%%c\n" 1
+reg: NEGI4(reg) "neg %%%0,%%%c\n" 1
+reg: BCOMI4(reg) "not %%%0,%%%c\n" 1
+reg: BCOMU4(reg) "not %%%0,%%%c\n" 1
+reg: CVII4(reg) "sll %%%0,8*(4-%a),%%%c; sra %%%c,8*(4-%a),%%%c\n" 2
+reg: CVUU4(reg) "sll %%%0,8*(4-%a),%%%c; srl %%%c,8*(4-%a),%%%c\n" 2
+reg: CVUU4(reg) "and %%%0,0xff,%%%c\n" (a->syms[0]->u.c.v.i == 1 ? 1 : LBURG_MAX)
+reg: CVUU4(reg) "set 0xffff,%%g1; and %%%0,%%g1,%%%c\n" 2
+reg: CVUI4(reg) "and %%%0,0xff,%%%c\n" (a->syms[0]->u.c.v.i == 1 ? 1 : LBURG_MAX)
+reg: CVUI4(reg) "set 0xffff,%%g1; and %%%0,%%g1,%%%c\n" 2
+addrg: ADDRGP4 "%a"
+stmt: JUMPV(addrg) "ba %0; nop\n" 2
+stmt: JUMPV(addr) "jmp %0; nop\n" 2
+stmt: LABELV "%a:\n"
+stmt: EQI4(reg,rc) "cmp %%%0,%1; be %a; nop\n" 3
+stmt: EQU4(reg,rc) "cmp %%%0,%1; be %a; nop\n" 3
+stmt: GEI4(reg,rc) "cmp %%%0,%1; bge %a; nop\n" 3
+stmt: GEU4(reg,rc) "cmp %%%0,%1; bgeu %a; nop\n" 3
+stmt: GTI4(reg,rc) "cmp %%%0,%1; bg %a; nop\n" 3
+stmt: GTU4(reg,rc) "cmp %%%0,%1; bgu %a; nop\n" 3
+stmt: LEI4(reg,rc) "cmp %%%0,%1; ble %a; nop\n" 3
+stmt: LEU4(reg,rc) "cmp %%%0,%1; bleu %a; nop\n" 3
+stmt: LTI4(reg,rc) "cmp %%%0,%1; bl %a; nop\n" 3
+stmt: LTU4(reg,rc) "cmp %%%0,%1; blu %a; nop\n" 3
+stmt: NEI4(reg,rc) "cmp %%%0,%1; bne %a; nop\n" 3
+stmt: NEU4(reg,rc) "cmp %%%0,%1; bne %a; nop\n" 3
+call: ADDRGP4 "%a"
+call: addr "%0"
+reg: CALLF8(call) "call %0; nop\n" 2
+reg: CALLF4(call) "call %0; nop\n" 2
+reg: CALLI4(call) "call %0; nop\n" 2
+reg: CALLP4(call) "call %0; nop\n" 2
+reg: CALLU4(call) "call %0; nop\n" 2
+stmt: CALLV(call) "call %0; nop\n" 2
+stmt: CALLB(call,reg) "call %0; st %%%1,[%%sp+64]; unimp %b&0xfff\n" 3
+
+stmt: RETF8(reg) "# ret\n" 1
+stmt: RETF4(reg) "# ret\n" 1
+stmt: RETI4(reg) "# ret\n" 1
+stmt: RETU4(reg) "# ret\n" 1
+stmt: RETP4(reg) "# ret\n" 1
+stmt: ARGI4(reg) "st %%%0,[%%sp+4*%c+68]\n" 1
+stmt: ARGU4(reg) "st %%%0,[%%sp+4*%c+68]\n" 1
+stmt: ARGP4(reg) "st %%%0,[%%sp+4*%c+68]\n" 1
+stmt: ARGF4(reg) "# ARGF4\n" 1
+stmt: ARGF8(reg) "# ARGF8\n" 1
+
+reg: DIVI4(reg,rc) "sra %%%0,31,%%g1; wr %%g0,%%g1,%%y; nop; nop; nop; sdiv %%%0,%1,%%%c\n" 6
+
+reg: DIVU4(reg,rc) "wr %%g0,%%g0,%%y; nop; nop; nop; udiv %%%0,%1,%%%c\n" 5
+
+reg: MODI4(reg,rc) "sra %%%0,31,%%g1; wr %%g0,%%g1,%%y; nop; nop; nop; sdiv %%%0,%1,%%g1\n; smul %%g1,%1,%%g1; sub %%%0,%%g1,%%%c\n" 8
+
+
+reg: MODU4(reg,rc) "wr %%g0,%%g0,%%y; nop; nop; nop; udiv %%%0,%1,%%g1\n; umul %%g1,%1,%%g1; sub %%%0,%%g1,%%%c\n" 7
+
+
+reg: MULI4(rc,reg) "smul %%%1,%0,%%%c\n" 1
+reg: MULU4(rc,reg) "umul %%%1,%0,%%%c\n" 1
+reg: ADDF8(reg,reg) "faddd %%f%0,%%f%1,%%f%c\n" 1
+reg: ADDF4(reg,reg) "fadds %%f%0,%%f%1,%%f%c\n" 1
+reg: DIVF8(reg,reg) "fdivd %%f%0,%%f%1,%%f%c\n" 1
+reg: DIVF4(reg,reg) "fdivs %%f%0,%%f%1,%%f%c\n" 1
+reg: MULF8(reg,reg) "fmuld %%f%0,%%f%1,%%f%c\n" 1
+reg: MULF4(reg,reg) "fmuls %%f%0,%%f%1,%%f%c\n" 1
+reg: SUBF8(reg,reg) "fsubd %%f%0,%%f%1,%%f%c\n" 1
+reg: SUBF4(reg,reg) "fsubs %%f%0,%%f%1,%%f%c\n" 1
+reg: NEGF4(reg) "fnegs %%f%0,%%f%c\n" 1
+reg: LOADF4(reg) "fmovs %%f%0,%%f%c\n" 1
+reg: CVFF4(reg) "fdtos %%f%0,%%f%c\n" 1
+reg: CVFF8(reg) "fstod %%f%0,%%f%c\n" 1
+reg: CVFI4(reg) "fstoi %%f%0,%%f0; st %%f0,[%%sp+64]; ld [%%sp+64],%%%c\n" (a->syms[0]->u.c.v.i==4?3:LBURG_MAX)
+
+reg: CVFI4(reg) "fdtoi %%f%0,%%f0; st %%f0,[%%sp+64]; ld [%%sp+64],%%%c\n" (a->syms[0]->u.c.v.i==8?3:LBURG_MAX)
+
+reg: CVIF4(reg) "st %%%0,[%%sp+64]; ld [%%sp+64],%%f%c; fitos %%f%c,%%f%c\n" 3
+
+reg: CVIF8(reg) "st %%%0,[%%sp+64]; ld [%%sp+64],%%f%c; fitod %%f%c,%%f%c\n" 3
+
+rel: EQF8(reg,reg) "fcmped %%f%0,%%f%1; nop; fbue"
+rel: EQF4(reg,reg) "fcmpes %%f%0,%%f%1; nop; fbue"
+rel: GEF8(reg,reg) "fcmped %%f%0,%%f%1; nop; fbuge"
+rel: GEF4(reg,reg) "fcmpes %%f%0,%%f%1; nop; fbuge"
+rel: GTF8(reg,reg) "fcmped %%f%0,%%f%1; nop; fbug"
+rel: GTF4(reg,reg) "fcmpes %%f%0,%%f%1; nop; fbug"
+rel: LEF8(reg,reg) "fcmped %%f%0,%%f%1; nop; fbule"
+rel: LEF4(reg,reg) "fcmpes %%f%0,%%f%1; nop; fbule"
+rel: LTF8(reg,reg) "fcmped %%f%0,%%f%1; nop; fbul"
+rel: LTF4(reg,reg) "fcmpes %%f%0,%%f%1; nop; fbul"
+rel: NEF8(reg,reg) "fcmped %%f%0,%%f%1; nop; fbne"
+rel: NEF4(reg,reg) "fcmpes %%f%0,%%f%1; nop; fbne"
+
+stmt: rel "%0 %a; nop\n" 4
+reg: LOADF8(reg) "# LOADD\n" 2
+
+reg: NEGF8(reg) "# NEGD\n" 2
+
+stmt: ASGNB(reg,INDIRB(reg)) "# ASGNB\n"
+
+%%
+static void progend(void){}
+static void progbeg(int argc, char *argv[]) {
+ int i;
+
+ {
+ union {
+ char c;
+ int i;
+ } u;
+ u.i = 0;
+ u.c = 1;
+ swap = ((int)(u.i == 1)) != IR->little_endian;
+ }
+ parseflags(argc, argv);
+ for (i = 0; i < argc; i++)
+ if (strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "-pg") == 0)
+ pflag = 1;
+ if (IR == &solarisIR)
+ stabprefix = ".LL";
+ else
+ stabprefix = "L";
+ for (i = 0; i < 8; i++) {
+ greg[i + 0] = mkreg(stringf("g%d", i), i + 0, 1, IREG);
+ greg[i + 8] = mkreg(stringf("o%d", i), i + 8, 1, IREG);
+ greg[i + 16] = mkreg(stringf("l%d", i), i + 16, 1, IREG);
+ greg[i + 24] = mkreg(stringf("i%d", i), i + 24, 1, IREG);
+ }
+ gregw = mkwildcard(greg);
+ for (i = 0; i < 32; i++)
+ freg[i] = mkreg("%d", i, 1, FREG);
+ for (i = 0; i < 31; i += 2)
+ freg2[i] = mkreg("%d", i, 3, FREG);
+ fregw = mkwildcard(freg);
+ freg2w = mkwildcard(freg2);
+ tmask[IREG] = 0x3fff3e00;
+ vmask[IREG] = 0x3ff00000;
+ tmask[FREG] = ~(unsigned)0;
+ vmask[FREG] = 0;
+}
+static Symbol rmap(int opk) {
+ switch (optype(opk)) {
+ case I: case U: case P: case B:
+ return gregw;
+ case F:
+ return opsize(opk) == 4 ? fregw : freg2w;
+ default:
+ return 0;
+ }
+}
+static void target(Node p) {
+ assert(p);
+ switch (specific(p->op)) {
+ case CNST+I: case CNST+U: case CNST+P:
+ if (range(p, 0, 0) == 0) {
+ setreg(p, greg[0]);
+ p->x.registered = 1;
+ }
+ break;
+ case CALL+B:
+ assert(p->syms[1] && p->syms[1]->type && isfunc(p->syms[1]->type));
+ p->syms[1] = intconst(freturn(p->syms[1]->type)->size);
+ break;
+ case CALL+F: setreg(p, opsize(p->op)==4?freg[0]:freg2[0]); break;
+ case CALL+I: case CALL+P: case CALL+U:
+ case CALL+V: setreg(p, oreg[0]); break;
+ case RET+F: rtarget(p, 0, opsize(p->op)==4?freg[0]:freg2[0]); break;
+ case RET+I: case RET+P: case RET+U:
+ rtarget(p, 0, ireg[0]);
+ p->kids[0]->x.registered = 1;
+ break;
+ case ARG+I: case ARG+P: case ARG+U:
+ if (p->syms[RX]->u.c.v.i < 6) {
+ rtarget(p, 0, oreg[p->syms[RX]->u.c.v.i]);
+ p->op = LOAD+opkind(p->op);
+ setreg(p, oreg[p->syms[RX]->u.c.v.i]);
+ }
+ break;
+ }
+}
+static void clobber(Node p) {
+ assert(p);
+ switch (specific(p->op)) {
+ case CALL+B: case CALL+F: case CALL+I:
+ spill(~(unsigned)3, FREG, p);
+ break;
+ case CALL+V:
+ spill(oreg[0]->x.regnode->mask, IREG, p);
+ spill(~(unsigned)3, FREG, p);
+ break;
+ case ARG+F:
+ if (opsize(p->op) == 4 && p->syms[2]->u.c.v.i <= 6)
+ spill((1<<(p->syms[2]->u.c.v.i + 8)), IREG, p);
+ else if (opsize(p->op) == 8 && p->syms[2]->u.c.v.i <= 5)
+ spill((3<<(p->syms[2]->u.c.v.i + 8))&0xff00, IREG, p);
+ break;
+ }
+}
+static int imm(Node p) {
+ return range(p, -4096, 4091);
+}
+static void doarg(Node p) {
+ assert(p && p->syms[0] && p->op != ARG+B);
+ p->syms[RX] = intconst(mkactual(4,
+ p->syms[0]->u.c.v.i)/4);
+}
+static void emit2(Node p) {
+ switch (p->op) {
+ case ARG+F+sizeop(4): {
+ int n = p->syms[RX]->u.c.v.i;
+ print("st %%f%d,[%%sp+4*%d+68]\n",
+ getregnum(p->x.kids[0]), n);
+ if (n <= 5)
+ print("ld [%%sp+4*%d+68],%%o%d\n", n, n);
+ break;
+ }
+ case ARG+F+sizeop(8): {
+ int n = p->syms[RX]->u.c.v.i;
+ int src = getregnum(p->x.kids[0]);
+ print("st %%f%d,[%%sp+4*%d+68]\n", src, n);
+ print("st %%f%d,[%%sp+4*%d+68]\n", src+1, n+1);
+ if (n <= 5)
+ print("ld [%%sp+4*%d+68],%%o%d\n", n, n);
+ if (n <= 4)
+ print("ld [%%sp+4*%d+68],%%o%d\n", n+1, n+1);
+ break;
+ }
+ case LOAD+F+sizeop(8): {
+ int dst = getregnum(p);
+ int src = getregnum(p->x.kids[0]);
+ print("fmovs %%f%d,%%f%d; ", src, dst);
+ print("fmovs %%f%d,%%f%d\n", src+1, dst+1);
+ break;
+ }
+ case NEG+F+sizeop(8): {
+ int dst = getregnum(p);
+ int src = getregnum(p->x.kids[0]);
+ print("fnegs %%f%d,%%f%d; ", src, dst);
+ print("fmovs %%f%d,%%f%d\n", src+1, dst+1);
+ break;
+ }
+ case ASGN+B: {
+ static int tmpregs[] = { 1, 2, 3 };
+ dalign = salign = p->syms[1]->u.c.v.i;
+ blkcopy(getregnum(p->x.kids[0]), 0,
+ getregnum(p->x.kids[1]), 0,
+ p->syms[0]->u.c.v.i, tmpregs);
+ break;
+ }
+ }
+}
+static void local(Symbol p) {
+ if (retstruct) {
+ assert(p == retv);
+ p->x.name = stringd(4*16);
+ p->x.offset = 4*16;
+ p->sclass = AUTO;
+ retstruct = 0;
+ return;
+ }
+ if (isscalar(p->type) && !p->addressed && !isfloat(p->type))
+ p->sclass = REGISTER;
+ if (askregvar(p, rmap(ttob(p->type))) == 0)
+ mkauto(p);
+ else if (p->scope > LOCAL)
+ regvars++;
+}
+static void function(Symbol f, Symbol caller[], Symbol callee[], int ncalls) {
+ int autos = 0, i, leaf, reg, varargs;
+
+ if (IR == &solarisIR)
+ globalend();
+ regvars = 0;
+ for (i = 0; callee[i]; i++)
+ ;
+ varargs = variadic(f->type)
+ || i > 0 && strcmp(callee[i-1]->name,
+ "__builtin_va_alist") == 0;
+ usedmask[0] = usedmask[1] = 0;
+ freemask[0] = freemask[1] = ~(unsigned)0;
+ for (i = 0; i < 8; i++)
+ ireg[i]->x.regnode->vbl = NULL;
+ offset = 68;
+ maxargoffset = 24;
+ reg = 0;
+ for (i = 0; callee[i]; i++) {
+ Symbol p = callee[i], q = caller[i];
+ int size = roundup(q->type->size, 4);
+ assert(q);
+ if (isfloat(p->type) || reg >= 6) {
+ p->x.offset = q->x.offset = offset;
+ p->x.name = q->x.name = stringd(offset);
+ p->sclass = q->sclass = AUTO;
+ autos++;
+ }
+ else if (p->addressed || varargs) {
+ p->x.offset = offset;
+ p->x.name = stringd(p->x.offset);
+ p->sclass = AUTO;
+ q->sclass = REGISTER;
+ askregvar(q, ireg[reg]);
+ assert(q->x.regnode);
+ autos++;
+ }
+ else {
+ p->sclass = q->sclass = REGISTER;
+ askregvar(p, ireg[reg]);
+ assert(p->x.regnode);
+ q->x.name = p->x.name;
+ }
+ offset += size;
+ reg += isstruct(p->type) ? 1 : size/4;
+ }
+ assert(caller[i] == 0);
+ offset = maxoffset = 0;
+ retstruct = isstruct(freturn(f->type));
+ gencode(caller, callee);
+ maxargoffset = roundup(maxargoffset, 4);
+ framesize = roundup(maxoffset + maxargoffset + 4*(16+1), 8);
+ assert(!varargs || autos);
+ leaf = (!ncalls
+ && !maxoffset && !autos && !regvars
+ && !isstruct(freturn(f->type))
+ && !(usedmask[IREG]&0x00ffff01)
+ && !(usedmask[FREG]&~(unsigned)3)
+ && !pflag && !glevel);
+ print(".align 4\n%s:\n", f->x.name);
+ if (leaf) {
+ for (i = 0; caller[i] && callee[i]; i++) {
+ Symbol p = caller[i], q = callee[i];
+ if (p->sclass == REGISTER && q->sclass == REGISTER) {
+ assert(q->x.regnode);
+ assert(q->x.regnode->set == IREG);
+ assert(q->x.regnode->number >= 24);
+ assert(q->x.regnode->number <= 31);
+ p->x.name = greg[q->x.regnode->number - 16]->x.name;
+ }
+ }
+ renameregs();
+ } else if (framesize <= 4095)
+ print("save %%sp,%d,%%sp\n", -framesize);
+ else
+ print("set %d,%%g1; save %%sp,%%g1,%%sp\n", -framesize);
+ if (varargs)
+ for (; reg < 6; reg++)
+ print("st %%i%d,[%%fp+%d]\n", reg, 4*reg + 68);
+ else {
+ offset = 4*(16 + 1);
+ reg = 0;
+ for (i = 0; caller[i]; i++) {
+ Symbol p = caller[i];
+ if (isfloat(p->type) && p->type->size == 8 && reg <= 4) {
+ print("st %%r%d,[%%fp+%d]\n",
+ ireg[reg++]->x.regnode->number, offset);
+ print("st %%r%d,[%%fp+%d]\n",
+ ireg[reg++]->x.regnode->number, offset + 4);
+ } else if (isfloat(p->type) && p->type->size == 4 && reg <= 5)
+ print("st %%r%d,[%%fp+%d]\n",
+ ireg[reg++]->x.regnode->number, offset);
+ else
+ reg++;
+ offset += roundup(p->type->size, 4);
+ }
+ }
+ if (pflag) {
+ int lab = genlabel(1);
+ print("set L%d,%%o0; call mcount; nop\n", lab);
+ print(".seg \"data\"\n.align 4; L%d:.word 0\n.seg \"text\"\n", lab);
+ }
+ emitcode();
+ if (isstruct(freturn(f->type)))
+ print("jmp %%i7+12; restore\n");
+ else if (!leaf)
+ print("ret; restore\n");
+ else {
+ renameregs();
+ print("retl; nop\n");
+ }
+ if (IR == &solarisIR) {
+ print(".type %s,#function\n", f->x.name);
+ print(".size %s,.-%s\n", f->x.name, f->x.name);
+ }
+}
+#define exch(x, y, t) (((t) = x), ((x) = (y)), ((y) = (t)))
+
+static void renameregs(void) {
+ int i;
+
+ for (i = 0; i < 8; i++) {
+ char *ptmp;
+ int itmp;
+ if (ireg[i]->x.regnode->vbl)
+ ireg[i]->x.regnode->vbl->x.name = oreg[i]->x.name;
+ exch(ireg[i]->x.name, oreg[i]->x.name, ptmp);
+ exch(ireg[i]->x.regnode->number,
+ oreg[i]->x.regnode->number, itmp);
+ }
+}
+static void defconst(int suffix, int size, Value v) {
+ if (suffix == F && size == 4) {
+ float f = v.d;
+ print(".word 0x%x\n", *(unsigned *)&f);
+ } else if (suffix == F && size == 8) {
+ double d = v.d;
+ unsigned *p = (unsigned *)&d;
+ print(".word 0x%x\n.word 0x%x\n", p[swap], p[!swap]);
+ } else if (suffix == P)
+ print(".word 0x%x\n", v.p);
+ else if (size == 1)
+ print(".byte 0x%x\n", suffix == I ? v.i : v.u);
+ else if (size == 2)
+ print(".half 0x%x\n", suffix == I ? v.i : v.u);
+ else if (size == 4)
+ print(".word 0x%x\n", suffix == I ? v.i : v.u);
+ else assert(0);
+}
+
+static void defaddress(Symbol p) {
+ print(".word %s\n", p->x.name);
+}
+
+static void defstring(int n, char *str) {
+ char *s;
+
+ for (s = str; s < str + n; s++)
+ print(".byte %d\n", (*s)&0377);
+}
+
+static void address(Symbol q, Symbol p, long n) {
+ if (p->scope == GLOBAL || p->sclass == STATIC || p->sclass == EXTERN)
+ q->x.name = stringf("%s%s%D", p->x.name, n >= 0 ? "+" : "", n);
+ else {
+ assert(n <= INT_MAX && n >= INT_MIN);
+ q->x.offset = p->x.offset + n;
+ q->x.name = stringd(q->x.offset);
+ }
+}
+static void export(Symbol p) {
+ print(".global %s\n", p->x.name);
+}
+static void import(Symbol p) {}
+static void defsymbol(Symbol p) {
+ if (p->scope >= LOCAL && p->sclass == STATIC)
+ p->x.name = stringf("%d", genlabel(1));
+ else
+ assert(p->scope != CONSTANTS || isint(p->type) || isptr(p->type)),
+ p->x.name = p->name;
+ if (p->scope >= LABELS)
+ p->x.name = stringf(p->generated ? "L%s" : "_%s",
+ p->x.name);
+}
+static void segment(int n) {
+ cseg = n;
+ switch (n) {
+ case CODE: print(".seg \"text\"\n"); break;
+ case BSS: print(".seg \"bss\"\n"); break;
+ case DATA: print(".seg \"data\"\n"); break;
+ case LIT: print(".seg \"text\"\n"); break;
+ }
+}
+static void space(int n) {
+ if (cseg != BSS)
+ print(".skip %d\n", n);
+}
+static void global(Symbol p) {
+ print(".align %d\n", p->type->align);
+ assert(p->u.seg);
+ if (p->u.seg == BSS
+ && (p->sclass == STATIC || Aflag >= 2))
+ print(".reserve %s,%d\n", p->x.name, p->type->size);
+ else if (p->u.seg == BSS)
+ print(".common %s,%d\n", p->x.name, p->type->size);
+ else
+ print("%s:\n", p->x.name);
+}
+static void blkfetch(int k, int off, int reg, int tmp) {
+ assert(k == 1 || k == 2 || k == 4);
+ assert(salign >= k);
+ if (k == 1)
+ print("ldub [%%r%d+%d],%%r%d\n", reg, off, tmp);
+ else if (k == 2)
+ print("lduh [%%r%d+%d],%%r%d\n", reg, off, tmp);
+ else
+ print("ld [%%r%d+%d],%%r%d\n", reg, off, tmp);
+}
+static void blkstore(int k, int off, int reg, int tmp) {
+ assert(k == 1 || k == 2 || k == 4);
+ assert(dalign >= k);
+ if (k == 1)
+ print("stb %%r%d,[%%r%d+%d]\n", tmp, reg, off);
+ else if (k == 2)
+ print("sth %%r%d,[%%r%d+%d]\n", tmp, reg, off);
+ else
+ print("st %%r%d,[%%r%d+%d]\n", tmp, reg, off);
+}
+static void blkloop(int dreg, int doff, int sreg, int soff, int size, int tmps[]) {
+ if ((size&~7) < 4096) {
+ print("add %%r%d,%d,%%r%d\n", sreg, size&~7, sreg);
+ print("add %%r%d,%d,%%r%d\n", dreg, size&~7, tmps[2]);
+ } else {
+ print("set %d,%%r%d\n", size&~7, tmps[2]);
+ print("add %%r%d,%%r%d,%%r%d\n", sreg, tmps[2], sreg);
+ print("add %%r%d,%%r%d,%%r%d\n", dreg, tmps[2], tmps[2]);
+ }
+ blkcopy(tmps[2], doff, sreg, soff, size&7, tmps);
+ print("1: dec 8,%%r%d\n", tmps[2]);
+ blkcopy(tmps[2], doff, sreg, soff - 8, 8, tmps);
+ print("cmp %%r%d,%%r%d; ", tmps[2], dreg);
+ print("bgt 1b; ");
+ print("dec 8,%%r%d\n", sreg);
+}
+static void defsymbol2(Symbol p) {
+ if (p->scope >= LOCAL && p->sclass == STATIC)
+ p->x.name = stringf(".%d", genlabel(1));
+ else
+ assert(p->scope != CONSTANTS || isint(p->type) || isptr(p->type)),
+ p->x.name = p->name;
+ if (p->scope >= LABELS)
+ p->x.name = stringf(p->generated ? ".L%s" : "%s",
+ p->x.name);
+}
+
+static Symbol prevg;
+
+static void globalend(void) {
+ if (prevg && prevg->type->size > 0)
+ print(".size %s,%d\n", prevg->x.name, prevg->type->size);
+ prevg = NULL;
+}
+
+static void export2(Symbol p) {
+ globalend();
+ print(".global %s\n", p->x.name);
+}
+
+static void progend2(void) {
+ globalend();
+}
+
+static void global2(Symbol p) {
+ globalend();
+ assert(p->u.seg);
+ if (!p->generated) {
+ print(".type %s,#%s\n", p->x.name,
+ isfunc(p->type) ? "function" : "object");
+ if (p->type->size > 0)
+ print(".size %s,%d\n", p->x.name, p->type->size);
+ else
+ prevg = p;
+ }
+ if (p->u.seg == BSS && p->sclass == STATIC)
+ print(".local %s\n.common %s,%d,%d\n", p->x.name, p->x.name,
+ p->type->size, p->type->align);
+ else if (p->u.seg == BSS && Aflag >= 2)
+ print(".align %d\n%s:.skip %d\n", p->type->align, p->x.name,
+ p->type->size);
+ else if (p->u.seg == BSS)
+ print(".common %s,%d,%d\n", p->x.name, p->type->size, p->type->align);
+ else
+ print(".align %d\n%s:\n", p->type->align, p->x.name);
+}
+
+static void segment2(int n) {
+ cseg = n;
+ switch (n) {
+ case CODE: print(".section \".text\"\n"); break;
+ case BSS: print(".section \".bss\"\n"); break;
+ case DATA: print(".section \".data\"\n"); break;
+ case LIT: print(".section \".rodata\"\n"); break;
+ }
+}
+Interface sparcIR = {
+ 1, 1, 0, /* char */
+ 2, 2, 0, /* short */
+ 4, 4, 0, /* int */
+ 4, 4, 0, /* long */
+ 4, 4, 0, /* long long */
+ 4, 4, 1, /* float */
+ 8, 8, 1, /* double */
+ 8, 8, 1, /* long double */
+ 4, 4, 0, /* T * */
+ 0, 1, 0, /* struct */
+ 0, /* little_endian */
+ 0, /* mulops_calls */
+ 1, /* wants_callb */
+ 0, /* wants_argb */
+ 1, /* left_to_right */
+ 0, /* wants_dag */
+ 0, /* unsigned_char */
+ address,
+ blockbeg,
+ blockend,
+ defaddress,
+ defconst,
+ defstring,
+ defsymbol,
+ emit,
+ export,
+ function,
+ gen,
+ global,
+ import,
+ local,
+ progbeg,
+ progend,
+ segment,
+ space,
+ stabblock, 0, 0, stabinit, stabline, stabsym, stabtype,
+ {
+ 1, /* max_unaligned_load */
+ rmap,
+ blkfetch, blkstore, blkloop,
+ _label,
+ _rule,
+ _nts,
+ _kids,
+ _string,
+ _templates,
+ _isinstruction,
+ _ntname,
+ emit2,
+ doarg,
+ target,
+ clobber,
+
+ }
+};
+
+Interface solarisIR = {
+ 1, 1, 0, /* char */
+ 2, 2, 0, /* short */
+ 4, 4, 0, /* int */
+ 4, 4, 0, /* long */
+ 4, 4, 0, /* long long */
+ 4, 4, 1, /* float */
+ 8, 8, 1, /* double */
+ 8, 8, 1, /* long double */
+ 4, 4, 0, /* T * */
+ 0, 1, 0, /* struct */
+ 0, /* little_endian */
+ 0, /* mulops_calls */
+ 1, /* wants_callb */
+ 0, /* wants_argb */
+ 1, /* left_to_right */
+ 0, /* wants_dag */
+ 0, /* unsigned_char */
+ address,
+ blockbeg,
+ blockend,
+ defaddress,
+ defconst,
+ defstring,
+ defsymbol2,
+ emit,
+ export2,
+ function,
+ gen,
+ global2,
+ import,
+ local,
+ progbeg,
+ progend2,
+ segment2,
+ space,
+ stabblock, 0, 0, stabinit, stabline, stabsym, stabtype,
+ {
+ 1, /* max_unaligned_load */
+ rmap,
+ blkfetch, blkstore, blkloop,
+ _label,
+ _rule,
+ _nts,
+ _kids,
+ _string,
+ _templates,
+ _isinstruction,
+ _ntname,
+ emit2,
+ doarg,
+ target,
+ clobber,
+
+ }
+};
+static char rcsid[] = "$Id: sparc.md 145 2001-10-17 21:53:10Z timo $";
diff --git a/lcc/src/stab.c b/lcc/src/stab.c
new file mode 100755
index 0000000..152b778
--- /dev/null
+++ b/lcc/src/stab.c
@@ -0,0 +1,330 @@
+#include <string.h>
+#include <stdlib.h>
+#include "c.h"
+#include "stab.h"
+
+
+static char *currentfile; /* current file name */
+static int ntypes;
+
+extern Interface sparcIR;
+
+char *stabprefix = "L";
+
+extern char *stabprefix;
+extern void stabblock(int, int, Symbol*);
+extern void stabend(Coordinate *, Symbol, Coordinate **, Symbol *, Symbol *);
+extern void stabfend(Symbol, int);
+extern void stabinit(char *, int, char *[]);
+extern void stabline(Coordinate *);
+extern void stabsym(Symbol);
+extern void stabtype(Symbol);
+
+static void asgncode(Type, int);
+static void dbxout(Type);
+static int dbxtype(Type);
+static int emittype(Type, int, int);
+
+/* asgncode - assign type code to ty */
+static void asgncode(Type ty, int lev) {
+ if (ty->x.marked || ty->x.typeno)
+ return;
+ ty->x.marked = 1;
+ switch (ty->op) {
+ case VOLATILE: case CONST: case VOLATILE+CONST:
+ asgncode(ty->type, lev);
+ ty->x.typeno = ty->type->x.typeno;
+ break;
+ case POINTER: case FUNCTION: case ARRAY:
+ asgncode(ty->type, lev + 1);
+ /* fall thru */
+ case VOID: case INT: case UNSIGNED: case FLOAT:
+ break;
+ case STRUCT: case UNION: {
+ Field p;
+ for (p = fieldlist(ty); p; p = p->link)
+ asgncode(p->type, lev + 1);
+ /* fall thru */
+ case ENUM:
+ if (ty->x.typeno == 0)
+ ty->x.typeno = ++ntypes;
+ if (lev > 0 && (*ty->u.sym->name < '0' || *ty->u.sym->name > '9'))
+ dbxout(ty);
+ break;
+ }
+ default:
+ assert(0);
+ }
+}
+
+/* dbxout - output .stabs entry for type ty */
+static void dbxout(Type ty) {
+ ty = unqual(ty);
+ if (!ty->x.printed) {
+ int col = 0;
+ print(".stabs \""), col += 8;
+ if (ty->u.sym && !(isfunc(ty) || isarray(ty) || isptr(ty)))
+ print("%s", ty->u.sym->name), col += strlen(ty->u.sym->name);
+ print(":%c", isstruct(ty) || isenum(ty) ? 'T' : 't'), col += 2;
+ emittype(ty, 0, col);
+ print("\",%d,0,0,0\n", N_LSYM);
+ }
+}
+
+/* dbxtype - emit a stabs entry for type ty, return type code */
+static int dbxtype(Type ty) {
+ asgncode(ty, 0);
+ dbxout(ty);
+ return ty->x.typeno;
+}
+
+/*
+ * emittype - emit ty's type number, emitting its definition if necessary.
+ * Returns the output column number after emission; col is the approximate
+ * output column before emission and is used to emit continuation lines for long
+ * struct, union, and enum types. Continuations are not emitted for other types,
+ * even if the definition is long. lev is the depth of calls to emittype.
+ */
+static int emittype(Type ty, int lev, int col) {
+ int tc = ty->x.typeno;
+
+ if (isconst(ty) || isvolatile(ty)) {
+ col = emittype(ty->type, lev, col);
+ ty->x.typeno = ty->type->x.typeno;
+ ty->x.printed = 1;
+ return col;
+ }
+ if (tc == 0) {
+ ty->x.typeno = tc = ++ntypes;
+/* fprint(2,"`%t'=%d\n", ty, tc); */
+ }
+ print("%d", tc), col += 3;
+ if (ty->x.printed)
+ return col;
+ ty->x.printed = 1;
+ switch (ty->op) {
+ case VOID: /* void is defined as itself */
+ print("=%d", tc), col += 1+3;
+ break;
+ case INT:
+ if (ty == chartype) /* plain char is a subrange of itself */
+ print("=r%d;%d;%d;", tc, ty->u.sym->u.limits.min.i, ty->u.sym->u.limits.max.i),
+ col += 2+3+2*2.408*ty->size+2;
+ else /* other signed ints are subranges of int */
+ print("=r1;%D;%D;", ty->u.sym->u.limits.min.i, ty->u.sym->u.limits.max.i),
+ col += 4+2*2.408*ty->size+2;
+ break;
+ case UNSIGNED:
+ if (ty == chartype) /* plain char is a subrange of itself */
+ print("=r%d;0;%u;", tc, ty->u.sym->u.limits.max.i),
+ col += 2+3+2+2.408*ty->size+1;
+ else /* other signed ints are subranges of int */
+ print("=r1;0;%U;", ty->u.sym->u.limits.max.i),
+ col += 4+2.408*ty->size+1;
+ break;
+ case FLOAT: /* float, double, long double get sizes, not ranges */
+ print("=r1;%d;0;", ty->size), col += 4+1+3;
+ break;
+ case POINTER:
+ print("=*"), col += 2;
+ col = emittype(ty->type, lev + 1, col);
+ break;
+ case FUNCTION:
+ print("=f"), col += 2;
+ col = emittype(ty->type, lev + 1, col);
+ break;
+ case ARRAY: /* array includes subscript as an int range */
+ if (ty->size && ty->type->size)
+ print("=ar1;0;%d;", ty->size/ty->type->size - 1), col += 7+3+1;
+ else
+ print("=ar1;0;-1;"), col += 10;
+ col = emittype(ty->type, lev + 1, col);
+ break;
+ case STRUCT: case UNION: {
+ Field p;
+ if (!ty->u.sym->defined) {
+ print("=x%c%s:", ty->op == STRUCT ? 's' : 'u', ty->u.sym->name);
+ col += 2+1+strlen(ty->u.sym->name)+1;
+ break;
+ }
+ if (lev > 0 && (*ty->u.sym->name < '0' || *ty->u.sym->name > '9')) {
+ ty->x.printed = 0;
+ break;
+ }
+ print("=%c%d", ty->op == STRUCT ? 's' : 'u', ty->size), col += 1+1+3;
+ for (p = fieldlist(ty); p; p = p->link) {
+ if (p->name)
+ print("%s:", p->name), col += strlen(p->name)+1;
+ else
+ print(":"), col += 1;
+ col = emittype(p->type, lev + 1, col);
+ if (p->lsb)
+ print(",%d,%d;", 8*p->offset +
+ (IR->little_endian ? fieldright(p) : fieldleft(p)),
+ fieldsize(p));
+ else
+ print(",%d,%d;", 8*p->offset, 8*p->type->size);
+ col += 1+3+1+3+1; /* accounts for ,%d,%d; */
+ if (col >= 80 && p->link) {
+ print("\\\\\",%d,0,0,0\n.stabs \"", N_LSYM);
+ col = 8;
+ }
+ }
+ print(";"), col += 1;
+ break;
+ }
+ case ENUM: {
+ Symbol *p;
+ if (lev > 0 && (*ty->u.sym->name < '0' || *ty->u.sym->name > '9')) {
+ ty->x.printed = 0;
+ break;
+ }
+ print("=e"), col += 2;
+ for (p = ty->u.sym->u.idlist; *p; p++) {
+ print("%s:%d,", (*p)->name, (*p)->u.value), col += strlen((*p)->name)+3;
+ if (col >= 80 && p[1]) {
+ print("\\\\\",%d,0,0,0\n.stabs \"", N_LSYM);
+ col = 8;
+ }
+ }
+ print(";"), col += 1;
+ break;
+ }
+ default:
+ assert(0);
+ }
+ return col;
+}
+
+/* stabblock - output a stab entry for '{' or '}' at level lev */
+void stabblock(int brace, int lev, Symbol *p) {
+ if (brace == '{')
+ while (*p)
+ stabsym(*p++);
+ if (IR == &sparcIR)
+ print(".stabd 0x%x,0,%d\n", brace == '{' ? N_LBRAC : N_RBRAC, lev);
+ else {
+ int lab = genlabel(1);
+ print(".stabn 0x%x,0,%d,%s%d-%s\n", brace == '{' ? N_LBRAC : N_RBRAC, lev,
+ stabprefix, lab, cfunc->x.name);
+ print("%s%d:\n", stabprefix, lab);
+ }
+}
+
+/* stabinit - initialize stab output */
+void stabinit(char *file, int argc, char *argv[]) {
+ typedef void (*Closure)(Symbol, void *);
+ extern char *getcwd(char *, size_t);
+
+ print(".stabs \"lcc4_compiled.\",0x%x,0,0,0\n", N_OPT);
+ if (file && *file) {
+ char buf[1024], *cwd = getcwd(buf, sizeof buf);
+ if (cwd)
+ print(".stabs \"%s/\",0x%x,0,3,%stext0\n", cwd, N_SO, stabprefix);
+ print(".stabs \"%s\",0x%x,0,3,%stext0\n", file, N_SO, stabprefix);
+ (*IR->segment)(CODE);
+ print("%stext0:\n", stabprefix, N_SO);
+ currentfile = file;
+ }
+ dbxtype(inttype);
+ dbxtype(chartype);
+ dbxtype(doubletype);
+ dbxtype(floattype);
+ dbxtype(longdouble);
+ dbxtype(longtype);
+ dbxtype(longlong);
+ dbxtype(shorttype);
+ dbxtype(signedchar);
+ dbxtype(unsignedchar);
+ dbxtype(unsignedlong);
+ dbxtype(unsignedlonglong);
+ dbxtype(unsignedshort);
+ dbxtype(unsignedtype);
+ dbxtype(voidtype);
+ foreach(types, GLOBAL, (Closure)stabtype, NULL);
+}
+
+/* stabline - emit stab entry for source coordinate *cp */
+void stabline(Coordinate *cp) {
+ if (cp->file && cp->file != currentfile) {
+ int lab = genlabel(1);
+ print(".stabs \"%s\",0x%x,0,0,%s%d\n", cp->file, N_SOL, stabprefix, lab);
+ print("%s%d:\n", stabprefix, lab);
+ currentfile = cp->file;
+ }
+ if (IR == &sparcIR)
+ print(".stabd 0x%x,0,%d\n", N_SLINE, cp->y);
+ else {
+ int lab = genlabel(1);
+ print(".stabn 0x%x,0,%d,%s%d-%s\n", N_SLINE, cp->y,
+ stabprefix, lab, cfunc->x.name);
+ print("%s%d:\n", stabprefix, lab);
+ }
+}
+
+/* stabsym - output a stab entry for symbol p */
+void stabsym(Symbol p) {
+ int code, tc, sz = p->type->size;
+
+ if (p->generated || p->computed)
+ return;
+ if (isfunc(p->type)) {
+ print(".stabs \"%s:%c%d\",%d,0,0,%s\n", p->name,
+ p->sclass == STATIC ? 'f' : 'F', dbxtype(freturn(p->type)),
+ N_FUN, p->x.name);
+ return;
+ }
+ if (!IR->wants_argb && p->scope == PARAM && p->structarg) {
+ assert(isptr(p->type) && isstruct(p->type->type));
+ tc = dbxtype(p->type->type);
+ sz = p->type->type->size;
+ } else
+ tc = dbxtype(p->type);
+ if (p->sclass == AUTO && p->scope == GLOBAL || p->sclass == EXTERN) {
+ print(".stabs \"%s:G", p->name);
+ code = N_GSYM;
+ } else if (p->sclass == STATIC) {
+ print(".stabs \"%s:%c%d\",%d,0,0,%s\n", p->name, p->scope == GLOBAL ? 'S' : 'V',
+ tc, p->u.seg == BSS ? N_LCSYM : N_STSYM, p->x.name);
+ return;
+ } else if (p->sclass == REGISTER) {
+ if (p->x.regnode) {
+ int r = p->x.regnode->number;
+ if (p->x.regnode->set == FREG)
+ r += 32; /* floating point */
+ print(".stabs \"%s:%c%d\",%d,0,", p->name,
+ p->scope == PARAM ? 'P' : 'r', tc, N_RSYM);
+ print("%d,%d\n", sz, r);
+ }
+ return;
+ } else if (p->scope == PARAM) {
+ print(".stabs \"%s:p", p->name);
+ code = N_PSYM;
+ } else if (p->scope >= LOCAL) {
+ print(".stabs \"%s:", p->name);
+ code = N_LSYM;
+ } else
+ assert(0);
+ print("%d\",%d,0,0,%s\n", tc, code,
+ p->scope >= PARAM && p->sclass != EXTERN ? p->x.name : "0");
+}
+
+/* stabtype - output a stab entry for type *p */
+void stabtype(Symbol p) {
+ if (p->type) {
+ if (p->sclass == 0)
+ dbxtype(p->type);
+ else if (p->sclass == TYPEDEF)
+ print(".stabs \"%s:t%d\",%d,0,0,0\n", p->name, dbxtype(p->type), N_LSYM);
+ }
+}
+
+/* stabend - finalize a function */
+void stabfend(Symbol p, int lineno) {}
+
+/* stabend - finalize stab output */
+void stabend(Coordinate *cp, Symbol p, Coordinate **cpp, Symbol *sp, Symbol *stab) {
+ (*IR->segment)(CODE);
+ print(".stabs \"\", %d, 0, 0,%setext\n", N_SO, stabprefix);
+ print("%setext:\n", stabprefix);
+}
diff --git a/lcc/src/stab.h b/lcc/src/stab.h
new file mode 100755
index 0000000..bfb7ebf
--- /dev/null
+++ b/lcc/src/stab.h
@@ -0,0 +1,113 @@
+/* @(#)stab.h 1.11 92/05/11 SMI */
+/*
+ * Copyright (c) 1990 by Sun Microsystems, Inc.
+ */
+
+/*
+ * This file gives definitions supplementing <a.out.h>
+ * for permanent symbol table entries.
+ * These must have one of the N_STAB bits on,
+ * and are subject to relocation according to the masks in <a.out.h>.
+ */
+
+#ifndef _STAB_H
+#define _STAB_H
+
+
+#if !defined(_a_out_h) && !defined(_A_OUT_H)
+/* this file contains fragments of a.out.h and stab.h relevant to
+ * support of stabX processing within ELF files - see the
+ * Format of a symbol table entry
+ */
+struct nlist {
+ union {
+ char *n_name; /* for use when in-core */
+ long n_strx; /* index into file string table */
+ } n_un;
+ unsigned char n_type; /* type flag (N_TEXT,..) */
+ char n_other; /* unused */
+ short n_desc; /* see <stab.h> */
+ unsigned long n_value; /* value of symbol (or sdb offset) */
+};
+
+/*
+ * Simple values for n_type.
+ */
+#define N_UNDF 0x0 /* undefined */
+#define N_ABS 0x2 /* absolute */
+#define N_TEXT 0x4 /* text */
+#define N_DATA 0x6 /* data */
+#define N_BSS 0x8 /* bss */
+#define N_COMM 0x12 /* common (internal to ld) */
+#define N_FN 0x1f /* file name symbol */
+
+#define N_EXT 01 /* external bit, or'ed in */
+#define N_TYPE 0x1e /* mask for all the type bits */
+
+#endif
+
+/*
+ * for symbolic debugger, sdb(1):
+ */
+#define N_GSYM 0x20 /* global symbol: name,,0,type,0 */
+#define N_FNAME 0x22 /* procedure name (f77 kludge): name,,0 */
+#define N_FUN 0x24 /* procedure: name,,0,linenumber,address */
+#define N_STSYM 0x26 /* static symbol: name,,0,type,address */
+#define N_LCSYM 0x28 /* .lcomm symbol: name,,0,type,address */
+#define N_MAIN 0x2a /* name of main routine : name,,0,0,0 */
+#define N_ROSYM 0x2c /* ro_data objects */
+#define N_OBJ 0x38 /* object file path or name */
+#define N_OPT 0x3c /* compiler options */
+#define N_RSYM 0x40 /* register sym: name,,0,type,register */
+#define N_SLINE 0x44 /* src line: 0,,0,linenumber,address */
+#define N_FLINE 0x4c /* function start.end */
+#define N_SSYM 0x60 /* structure elt: name,,0,type,struct_offset */
+#define N_ENDM 0x62 /* last stab emitted for module */
+#define N_SO 0x64 /* source file name: name,,0,0,address */
+#define N_LSYM 0x80 /* local sym: name,,0,type,offset */
+#define N_BINCL 0x82 /* header file: name,,0,0,0 */
+#define N_SOL 0x84 /* #included file name: name,,0,0,address */
+#define N_PSYM 0xa0 /* parameter: name,,0,type,offset */
+#define N_EINCL 0xa2 /* end of include file */
+#define N_ENTRY 0xa4 /* alternate entry: name,linenumber,address */
+#define N_LBRAC 0xc0 /* left bracket: 0,,0,nesting level,address */
+#define N_EXCL 0xc2 /* excluded include file */
+#define N_RBRAC 0xe0 /* right bracket: 0,,0,nesting level,address */
+#define N_BCOMM 0xe2 /* begin common: name,, */
+#define N_ECOMM 0xe4 /* end common: name,, */
+#define N_ECOML 0xe8 /* end common (local name): ,,address */
+#define N_LENG 0xfe /* second stab entry with length information */
+
+/*
+ * for the berkeley pascal compiler, pc(1):
+ */
+#define N_PC 0x30 /* global pascal symbol: name,,0,subtype,line */
+#define N_WITH 0xea /* pascal with statement: type,,0,0,offset */
+
+/*
+ * for code browser only
+ */
+#define N_BROWS 0x48 /* path to associated .cb file */
+
+/*
+ * Optional langauge designations for N_SO
+ */
+#define N_SO_AS 1 /* Assembler */
+#define N_SO_C 2 /* C */
+#define N_SO_ANSI_C 3 /* ANSI C */
+#define N_SO_CC 4 /* C++ */
+#define N_SO_FORTRAN 5 /* Fortran 77 */
+#define N_SO_PASCAL 6 /* Pascal */
+
+/*
+ * Floating point type values
+ */
+#define NF_NONE 0 /* Undefined type */
+#define NF_SINGLE 1 /* IEEE 32 bit float */
+#define NF_DOUBLE 2 /* IEEE 64 bit float */
+#define NF_COMPLEX 3 /* Fortran complex */
+#define NF_COMPLEX16 4 /* Fortran double complex */
+#define NF_COMPLEX32 5 /* Fortran complex*16 */
+#define NF_LDOUBLE 6 /* Long double */
+
+#endif
diff --git a/lcc/src/stmt.c b/lcc/src/stmt.c
new file mode 100755
index 0000000..b742a32
--- /dev/null
+++ b/lcc/src/stmt.c
@@ -0,0 +1,697 @@
+#include "c.h"
+
+
+#define SWSIZE 512
+
+#define den(i,j) ((j-buckets[i]+1.0)/(v[j]-v[buckets[i]]+1))
+
+struct code codehead = { Start };
+Code codelist = &codehead;
+float density = 0.5;
+Table stmtlabs;
+
+static int foldcond(Tree e1, Tree e2);
+static void caselabel(Swtch, long, int);
+static void cmp(int, Symbol, long, int);
+static Tree conditional(int);
+static void dostmt(int, Swtch, int);
+static int equal(Symbol, Symbol);
+static void forstmt(int, Swtch, int);
+static void ifstmt(int, int, Swtch, int);
+static Symbol localaddr(Tree);
+static void stmtlabel(void);
+static void swstmt(int, int, int);
+static void whilestmt(int, Swtch, int);
+Code code(int kind) {
+ Code cp;
+
+ if (!reachable(kind))
+ warning("unreachable code\n");
+
+ NEW(cp, FUNC);
+ cp->kind = kind;
+ cp->prev = codelist;
+ cp->next = NULL;
+ codelist->next = cp;
+ codelist = cp;
+ return cp;
+}
+int reachable(int kind) {
+ Code cp;
+
+ if (kind > Start) {
+ Code cp;
+ for (cp = codelist; cp->kind < Label; )
+ cp = cp->prev;
+ if (cp->kind == Jump || cp->kind == Switch)
+ return 0;
+ }
+ return 1;
+}
+void addlocal(Symbol p) {
+ if (!p->defined) {
+ code(Local)->u.var = p;
+ p->defined = 1;
+ p->scope = level;
+ }
+}
+void definept(Coordinate *p) {
+ Code cp = code(Defpoint);
+
+ cp->u.point.src = p ? *p : src;
+ cp->u.point.point = npoints;
+ if (ncalled > 0) {
+ int n = findcount(cp->u.point.src.file,
+ cp->u.point.src.x, cp->u.point.src.y);
+ if (n > 0)
+ refinc = (float)n/ncalled;
+ }
+ if (glevel > 2) locus(identifiers, &cp->u.point.src);
+ if (events.points && reachable(Gen))
+ {
+ Tree e = NULL;
+ apply(events.points, &cp->u.point.src, &e);
+ if (e)
+ listnodes(e, 0, 0);
+ }
+}
+void statement(int loop, Swtch swp, int lev) {
+ float ref = refinc;
+
+ if (Aflag >= 2 && lev == 15)
+ warning("more than 15 levels of nested statements\n");
+ switch (t) {
+ case IF: ifstmt(genlabel(2), loop, swp, lev + 1);
+ break;
+ case WHILE: whilestmt(genlabel(3), swp, lev + 1); break;
+ case DO: dostmt(genlabel(3), swp, lev + 1); expect(';');
+ break;
+
+ case FOR: forstmt(genlabel(4), swp, lev + 1);
+ break;
+ case BREAK: walk(NULL, 0, 0);
+ definept(NULL);
+ if (swp && swp->lab > loop)
+ branch(swp->lab + 1);
+ else if (loop)
+ branch(loop + 2);
+ else
+ error("illegal break statement\n");
+ t = gettok(); expect(';');
+ break;
+
+ case CONTINUE: walk(NULL, 0, 0);
+ definept(NULL);
+ if (loop)
+ branch(loop + 1);
+ else
+ error("illegal continue statement\n");
+ t = gettok(); expect(';');
+ break;
+
+ case SWITCH: swstmt(loop, genlabel(2), lev + 1);
+ break;
+ case CASE: {
+ int lab = genlabel(1);
+ if (swp == NULL)
+ error("illegal case label\n");
+ definelab(lab);
+ while (t == CASE) {
+ static char stop[] = { IF, ID, 0 };
+ Tree p;
+ t = gettok();
+ p = constexpr(0);
+ if (generic(p->op) == CNST && isint(p->type)) {
+ if (swp) {
+ needconst++;
+ p = cast(p, swp->sym->type);
+ if (p->type->op == UNSIGNED)
+ p->u.v.i = extend(p->u.v.u, p->type);
+ needconst--;
+ caselabel(swp, p->u.v.i, lab);
+ }
+ } else
+ error("case label must be a constant integer expression\n");
+
+ test(':', stop);
+ }
+ statement(loop, swp, lev);
+ } break;
+ case DEFAULT: if (swp == NULL)
+ error("illegal default label\n");
+ else if (swp->deflab)
+ error("extra default label\n");
+ else {
+ swp->deflab = findlabel(swp->lab);
+ definelab(swp->deflab->u.l.label);
+ }
+ t = gettok();
+ expect(':');
+ statement(loop, swp, lev); break;
+ case RETURN: {
+ Type rty = freturn(cfunc->type);
+ t = gettok();
+ definept(NULL);
+ if (t != ';')
+ if (rty == voidtype) {
+ error("extraneous return value\n");
+ expr(0);
+ retcode(NULL);
+ } else
+ retcode(expr(0));
+ else {
+ if (rty != voidtype)
+ warning("missing return value\n");
+ retcode(NULL);
+ }
+ branch(cfunc->u.f.label);
+ } expect(';');
+ break;
+
+ case '{': compound(loop, swp, lev + 1); break;
+ case ';': definept(NULL); t = gettok(); break;
+ case GOTO: walk(NULL, 0, 0);
+ definept(NULL);
+ t = gettok();
+ if (t == ID) {
+ Symbol p = lookup(token, stmtlabs);
+ if (p == NULL) {
+ p = install(token, &stmtlabs, 0, FUNC);
+ p->scope = LABELS;
+ p->u.l.label = genlabel(1);
+ p->src = src;
+ }
+ use(p, src);
+ branch(p->u.l.label);
+ t = gettok();
+ } else
+ error("missing label in goto\n"); expect(';');
+ break;
+
+ case ID: if (getchr() == ':') {
+ stmtlabel();
+ statement(loop, swp, lev);
+ break;
+ }
+ default: definept(NULL);
+ if (kind[t] != ID) {
+ error("unrecognized statement\n");
+ t = gettok();
+ } else {
+ Tree e = expr0(0);
+ listnodes(e, 0, 0);
+ if (nodecount == 0 || nodecount > 200)
+ walk(NULL, 0, 0);
+ else if (glevel) walk(NULL, 0, 0);
+ deallocate(STMT);
+ } expect(';');
+ break;
+
+ }
+ if (kind[t] != IF && kind[t] != ID
+ && t != '}' && t != EOI) {
+ static char stop[] = { IF, ID, '}', 0 };
+ error("illegal statement termination\n");
+ skipto(0, stop);
+ }
+ refinc = ref;
+}
+
+static void ifstmt(int lab, int loop, Swtch swp, int lev) {
+ t = gettok();
+ expect('(');
+ definept(NULL);
+ walk(conditional(')'), 0, lab);
+ refinc /= 2.0;
+ statement(loop, swp, lev);
+ if (t == ELSE) {
+ branch(lab + 1);
+ t = gettok();
+ definelab(lab);
+ statement(loop, swp, lev);
+ if (findlabel(lab + 1)->ref)
+ definelab(lab + 1);
+ } else
+ definelab(lab);
+}
+static Tree conditional(int tok) {
+ Tree p = expr(tok);
+
+ if (Aflag > 1 && isfunc(p->type))
+ warning("%s used in a conditional expression\n",
+ funcname(p));
+ return cond(p);
+}
+static void stmtlabel(void) {
+ Symbol p = lookup(token, stmtlabs);
+
+ if (p == NULL) {
+ p = install(token, &stmtlabs, 0, FUNC);
+ p->scope = LABELS;
+ p->u.l.label = genlabel(1);
+ p->src = src;
+ }
+ if (p->defined)
+ error("redefinition of label `%s' previously defined at %w\n", p->name, &p->src);
+
+ p->defined = 1;
+ definelab(p->u.l.label);
+ t = gettok();
+ expect(':');
+}
+static void forstmt(int lab, Swtch swp, int lev) {
+ int once = 0;
+ Tree e1 = NULL, e2 = NULL, e3 = NULL;
+ Coordinate pt2, pt3;
+
+ t = gettok();
+ expect('(');
+ definept(NULL);
+ if (kind[t] == ID)
+ e1 = texpr(expr0, ';', FUNC);
+ else
+ expect(';');
+ walk(e1, 0, 0);
+ pt2 = src;
+ refinc *= 10.0;
+ if (kind[t] == ID)
+ e2 = texpr(conditional, ';', FUNC);
+ else
+ expect(';');
+ pt3 = src;
+ if (kind[t] == ID)
+ e3 = texpr(expr0, ')', FUNC);
+ else {
+ static char stop[] = { IF, ID, '}', 0 };
+ test(')', stop);
+ }
+ if (e2) {
+ once = foldcond(e1, e2);
+ if (!once)
+ branch(lab + 3);
+ }
+ definelab(lab);
+ statement(lab, swp, lev);
+ definelab(lab + 1);
+ definept(&pt3);
+ if (e3)
+ walk(e3, 0, 0);
+ if (e2) {
+ if (!once)
+ definelab(lab + 3);
+ definept(&pt2);
+ walk(e2, lab, 0);
+ } else {
+ definept(&pt2);
+ branch(lab);
+ }
+ if (findlabel(lab + 2)->ref)
+ definelab(lab + 2);
+}
+static void swstmt(int loop, int lab, int lev) {
+ Tree e;
+ struct swtch sw;
+ Code head, tail;
+
+ t = gettok();
+ expect('(');
+ definept(NULL);
+ e = expr(')');
+ if (!isint(e->type)) {
+ error("illegal type `%t' in switch expression\n",
+ e->type);
+ e = retype(e, inttype);
+ }
+ e = cast(e, promote(e->type));
+ if (generic(e->op) == INDIR && isaddrop(e->kids[0]->op)
+ && e->kids[0]->u.sym->type == e->type
+ && !isvolatile(e->kids[0]->u.sym->type)) {
+ sw.sym = e->kids[0]->u.sym;
+ walk(NULL, 0, 0);
+ } else {
+ sw.sym = genident(REGISTER, e->type, level);
+ addlocal(sw.sym);
+ walk(asgn(sw.sym, e), 0, 0);
+ }
+ head = code(Switch);
+ sw.lab = lab;
+ sw.deflab = NULL;
+ sw.ncases = 0;
+ sw.size = SWSIZE;
+ sw.values = newarray(SWSIZE, sizeof *sw.values, FUNC);
+ sw.labels = newarray(SWSIZE, sizeof *sw.labels, FUNC);
+ refinc /= 10.0;
+ statement(loop, &sw, lev);
+ if (sw.deflab == NULL) {
+ sw.deflab = findlabel(lab);
+ definelab(lab);
+ if (sw.ncases == 0)
+ warning("switch statement with no cases\n");
+ }
+ if (findlabel(lab + 1)->ref)
+ definelab(lab + 1);
+ tail = codelist;
+ codelist = head->prev;
+ codelist->next = head->prev = NULL;
+ if (sw.ncases > 0)
+ swgen(&sw);
+ branch(lab);
+ head->next->prev = codelist;
+ codelist->next = head->next;
+ codelist = tail;
+}
+static void caselabel(Swtch swp, long val, int lab) {
+ int k;
+
+ if (swp->ncases >= swp->size)
+ {
+ long *vals = swp->values;
+ Symbol *labs = swp->labels;
+ swp->size *= 2;
+ swp->values = newarray(swp->size, sizeof *swp->values, FUNC);
+ swp->labels = newarray(swp->size, sizeof *swp->labels, FUNC);
+ for (k = 0; k < swp->ncases; k++) {
+ swp->values[k] = vals[k];
+ swp->labels[k] = labs[k];
+ }
+ }
+ k = swp->ncases;
+ for ( ; k > 0 && swp->values[k-1] >= val; k--) {
+ swp->values[k] = swp->values[k-1];
+ swp->labels[k] = swp->labels[k-1];
+ }
+ if (k < swp->ncases && swp->values[k] == val)
+ error("duplicate case label `%d'\n", val);
+ swp->values[k] = val;
+ swp->labels[k] = findlabel(lab);
+ ++swp->ncases;
+ if (Aflag >= 2 && swp->ncases == 258)
+ warning("more than 257 cases in a switch\n");
+}
+void swgen(Swtch swp) {
+ int *buckets, k, n;
+ long *v = swp->values;
+
+ buckets = newarray(swp->ncases + 1,
+ sizeof *buckets, FUNC);
+ for (n = k = 0; k < swp->ncases; k++, n++) {
+ buckets[n] = k;
+ while (n > 0 && den(n-1, k) >= density)
+ n--;
+ }
+ buckets[n] = swp->ncases;
+ swcode(swp, buckets, 0, n - 1);
+}
+void swcode(Swtch swp, int b[], int lb, int ub) {
+ int hilab, lolab, l, u, k = (lb + ub)/2;
+ long *v = swp->values;
+
+ if (k > lb && k < ub) {
+ lolab = genlabel(1);
+ hilab = genlabel(1);
+ } else if (k > lb) {
+ lolab = genlabel(1);
+ hilab = swp->deflab->u.l.label;
+ } else if (k < ub) {
+ lolab = swp->deflab->u.l.label;
+ hilab = genlabel(1);
+ } else
+ lolab = hilab = swp->deflab->u.l.label;
+ l = b[k];
+ u = b[k+1] - 1;
+ if (u - l + 1 <= 3)
+ {
+ int i;
+ for (i = l; i <= u; i++)
+ cmp(EQ, swp->sym, v[i], swp->labels[i]->u.l.label);
+ if (k > lb && k < ub)
+ cmp(GT, swp->sym, v[u], hilab);
+ else if (k > lb)
+ cmp(GT, swp->sym, v[u], hilab);
+ else if (k < ub)
+ cmp(LT, swp->sym, v[l], lolab);
+ else
+ assert(lolab == hilab),
+ branch(lolab);
+ walk(NULL, 0, 0);
+ }
+ else {
+ Tree e;
+ Type ty = signedint(swp->sym->type);
+ Symbol table = genident(STATIC,
+ array(voidptype, u - l + 1, 0), GLOBAL);
+ (*IR->defsymbol)(table);
+ if (!isunsigned(swp->sym->type) || v[l] != 0)
+ cmp(LT, swp->sym, v[l], lolab);
+ cmp(GT, swp->sym, v[u], hilab);
+ e = (*optree['-'])(SUB, cast(idtree(swp->sym), ty), cnsttree(ty, v[l]));
+ if (e->type->size < unsignedptr->size)
+ e = cast(e, unsignedlong);
+ walk(tree(JUMP, voidtype,
+ rvalue((*optree['+'])(ADD, pointer(idtree(table)), e)), NULL),
+ 0, 0);
+ code(Switch);
+ codelist->u.swtch.table = table;
+ codelist->u.swtch.sym = swp->sym;
+ codelist->u.swtch.deflab = swp->deflab;
+ codelist->u.swtch.size = u - l + 1;
+ codelist->u.swtch.values = &v[l];
+ codelist->u.swtch.labels = &swp->labels[l];
+ if (v[u] - v[l] + 1 >= 10000)
+ warning("switch generates a huge table\n");
+ }
+ if (k > lb) {
+ assert(lolab != swp->deflab->u.l.label);
+ definelab(lolab);
+ swcode(swp, b, lb, k - 1);
+ }
+ if (k < ub) {
+ assert(hilab != swp->deflab->u.l.label);
+ definelab(hilab);
+ swcode(swp, b, k + 1, ub);
+ }
+}
+static void cmp(int op, Symbol p, long n, int lab) {
+ Type ty = signedint(p->type);
+
+ listnodes(eqtree(op,
+ cast(idtree(p), ty),
+ cnsttree(ty, n)),
+ lab, 0);
+}
+void retcode(Tree p) {
+ Type ty;
+
+ if (p == NULL) {
+ if (events.returns)
+ apply(events.returns, cfunc, NULL);
+ return;
+ }
+ p = pointer(p);
+ ty = assign(freturn(cfunc->type), p);
+ if (ty == NULL) {
+ error("illegal return type; found `%t' expected `%t'\n",
+ p->type, freturn(cfunc->type));
+ return;
+ }
+ p = cast(p, ty);
+ if (retv)
+ {
+ if (iscallb(p))
+ p = tree(RIGHT, p->type,
+ tree(CALL+B, p->type,
+ p->kids[0]->kids[0], idtree(retv)),
+ rvalue(idtree(retv)));
+ else
+ p = asgntree(ASGN, rvalue(idtree(retv)), p);
+ walk(p, 0, 0);
+ if (events.returns)
+ apply(events.returns, cfunc, rvalue(idtree(retv)));
+ return;
+ }
+ if (events.returns)
+ {
+ Symbol t1 = genident(AUTO, p->type, level);
+ addlocal(t1);
+ walk(asgn(t1, p), 0, 0);
+ apply(events.returns, cfunc, idtree(t1));
+ p = idtree(t1);
+ }
+ if (!isfloat(p->type))
+ p = cast(p, promote(p->type));
+ if (isptr(p->type))
+ {
+ Symbol q = localaddr(p);
+ if (q && (q->computed || q->generated))
+ warning("pointer to a %s is an illegal return value\n",
+ q->scope == PARAM ? "parameter" : "local");
+ else if (q)
+ warning("pointer to %s `%s' is an illegal return value\n",
+ q->scope == PARAM ? "parameter" : "local", q->name);
+ }
+ walk(tree(mkop(RET,p->type), p->type, p, NULL), 0, 0);
+}
+void definelab(int lab) {
+ Code cp;
+ Symbol p = findlabel(lab);
+
+ assert(lab);
+ walk(NULL, 0, 0);
+ code(Label)->u.forest = newnode(LABEL+V, NULL, NULL, p);
+ for (cp = codelist->prev; cp->kind <= Label; )
+ cp = cp->prev;
+ while ( cp->kind == Jump
+ && cp->u.forest->kids[0]
+ && specific(cp->u.forest->kids[0]->op) == ADDRG+P
+ && cp->u.forest->kids[0]->syms[0] == p) {
+ assert(cp->u.forest->kids[0]->syms[0]->u.l.label == lab);
+ p->ref--;
+ assert(cp->next);
+ assert(cp->prev);
+ cp->prev->next = cp->next;
+ cp->next->prev = cp->prev;
+ cp = cp->prev;
+ while (cp->kind <= Label)
+ cp = cp->prev;
+ }
+}
+Node jump(int lab) {
+ Symbol p = findlabel(lab);
+
+ p->ref++;
+ return newnode(JUMP+V, newnode(ADDRG+ttob(voidptype), NULL, NULL, p),
+ NULL, NULL);
+}
+void branch(int lab) {
+ Code cp;
+ Symbol p = findlabel(lab);
+
+ assert(lab);
+ walk(NULL, 0, 0);
+ code(Label)->u.forest = jump(lab);
+ for (cp = codelist->prev; cp->kind < Label; )
+ cp = cp->prev;
+ while ( cp->kind == Label
+ && cp->u.forest->op == LABEL+V
+ && !equal(cp->u.forest->syms[0], p)) {
+ equatelab(cp->u.forest->syms[0], p);
+ assert(cp->next);
+ assert(cp->prev);
+ cp->prev->next = cp->next;
+ cp->next->prev = cp->prev;
+ cp = cp->prev;
+ while (cp->kind < Label)
+ cp = cp->prev;
+ }
+ if (cp->kind == Jump || cp->kind == Switch) {
+ p->ref--;
+ codelist->prev->next = NULL;
+ codelist = codelist->prev;
+ } else {
+ codelist->kind = Jump;
+ if (cp->kind == Label
+ && cp->u.forest->op == LABEL+V
+ && equal(cp->u.forest->syms[0], p))
+ warning("source code specifies an infinite loop");
+ }
+}
+void equatelab(Symbol old, Symbol new) {
+ assert(old->u.l.equatedto == NULL);
+ old->u.l.equatedto = new;
+ new->ref++;
+}
+static int equal(Symbol lprime, Symbol dst) {
+ assert(dst && lprime);
+ for ( ; dst; dst = dst->u.l.equatedto)
+ if (lprime == dst)
+ return 1;
+ return 0;
+}
+/* dostmt - do statement while ( expression ) */
+static void dostmt(int lab, Swtch swp, int lev) {
+ refinc *= 10.0;
+ t = gettok();
+ definelab(lab);
+ statement(lab, swp, lev);
+ definelab(lab + 1);
+ expect(WHILE);
+ expect('(');
+ definept(NULL);
+ walk(conditional(')'), lab, 0);
+ if (findlabel(lab + 2)->ref)
+ definelab(lab + 2);
+}
+
+/* foldcond - check if initial test in for(e1;e2;e3) S is necessary */
+static int foldcond(Tree e1, Tree e2) {
+ int op = generic(e2->op);
+ Symbol v;
+
+ if (e1 == 0 || e2 == 0)
+ return 0;
+ if (generic(e1->op) == ASGN && isaddrop(e1->kids[0]->op)
+ && generic(e1->kids[1]->op) == CNST) {
+ v = e1->kids[0]->u.sym;
+ e1 = e1->kids[1];
+ } else
+ return 0;
+ if ((op==LE || op==LT || op==EQ || op==NE || op==GT || op==GE)
+ && generic(e2->kids[0]->op) == INDIR
+ && e2->kids[0]->kids[0]->u.sym == v
+ && e2->kids[1]->op == e1->op) {
+ e1 = simplify(op, e2->type, e1, e2->kids[1]);
+ if (e1->op == CNST+I)
+ return e1->u.v.i;
+ }
+ return 0;
+}
+
+/* localaddr - returns q if p yields the address of local/parameter q; otherwise returns 0 */
+static Symbol localaddr(Tree p) {
+ if (p == NULL)
+ return NULL;
+ switch (generic(p->op)) {
+ case INDIR: case CALL: case ARG:
+ return NULL;
+ case ADDRL: case ADDRF:
+ return p->u.sym;
+ case RIGHT: case ASGN:
+ if (p->kids[1])
+ return localaddr(p->kids[1]);
+ return localaddr(p->kids[0]);
+ case COND: {
+ Symbol q;
+ assert(p->kids[1] && p->kids[1]->op == RIGHT);
+ if ((q = localaddr(p->kids[1]->kids[0])) != NULL)
+ return q;
+ return localaddr(p->kids[1]->kids[1]);
+ }
+ default: {
+ Symbol q;
+ if (p->kids[0] && (q = localaddr(p->kids[0])) != NULL)
+ return q;
+ return localaddr(p->kids[1]);
+ }
+ }
+}
+
+/* whilestmt - while ( expression ) statement */
+static void whilestmt(int lab, Swtch swp, int lev) {
+ Coordinate pt;
+ Tree e;
+
+ refinc *= 10.0;
+ t = gettok();
+ expect('(');
+ walk(NULL, 0, 0);
+ pt = src;
+ e = texpr(conditional, ')', FUNC);
+ branch(lab + 1);
+ definelab(lab);
+ statement(lab, swp, lev);
+ definelab(lab + 1);
+ definept(&pt);
+ walk(e, lab, 0);
+ if (findlabel(lab + 2)->ref)
+ definelab(lab + 2);
+}
diff --git a/lcc/src/string.c b/lcc/src/string.c
new file mode 100755
index 0000000..4fee2c9
--- /dev/null
+++ b/lcc/src/string.c
@@ -0,0 +1,122 @@
+#include "c.h"
+
+
+static struct string {
+ char *str;
+ int len;
+ struct string *link;
+} *buckets[1024];
+static int scatter[] = { /* map characters to random values */
+ 2078917053, 143302914, 1027100827, 1953210302, 755253631,
+ 2002600785, 1405390230, 45248011, 1099951567, 433832350,
+ 2018585307, 438263339, 813528929, 1703199216, 618906479,
+ 573714703, 766270699, 275680090, 1510320440, 1583583926,
+ 1723401032, 1965443329, 1098183682, 1636505764, 980071615,
+ 1011597961, 643279273, 1315461275, 157584038, 1069844923,
+ 471560540, 89017443, 1213147837, 1498661368, 2042227746,
+ 1968401469, 1353778505, 1300134328, 2013649480, 306246424,
+ 1733966678, 1884751139, 744509763, 400011959, 1440466707,
+ 1363416242, 973726663, 59253759, 1639096332, 336563455,
+ 1642837685, 1215013716, 154523136, 593537720, 704035832,
+ 1134594751, 1605135681, 1347315106, 302572379, 1762719719,
+ 269676381, 774132919, 1851737163, 1482824219, 125310639,
+ 1746481261, 1303742040, 1479089144, 899131941, 1169907872,
+ 1785335569, 485614972, 907175364, 382361684, 885626931,
+ 200158423, 1745777927, 1859353594, 259412182, 1237390611,
+ 48433401, 1902249868, 304920680, 202956538, 348303940,
+ 1008956512, 1337551289, 1953439621, 208787970, 1640123668,
+ 1568675693, 478464352, 266772940, 1272929208, 1961288571,
+ 392083579, 871926821, 1117546963, 1871172724, 1771058762,
+ 139971187, 1509024645, 109190086, 1047146551, 1891386329,
+ 994817018, 1247304975, 1489680608, 706686964, 1506717157,
+ 579587572, 755120366, 1261483377, 884508252, 958076904,
+ 1609787317, 1893464764, 148144545, 1415743291, 2102252735,
+ 1788268214, 836935336, 433233439, 2055041154, 2109864544,
+ 247038362, 299641085, 834307717, 1364585325, 23330161,
+ 457882831, 1504556512, 1532354806, 567072918, 404219416,
+ 1276257488, 1561889936, 1651524391, 618454448, 121093252,
+ 1010757900, 1198042020, 876213618, 124757630, 2082550272,
+ 1834290522, 1734544947, 1828531389, 1982435068, 1002804590,
+ 1783300476, 1623219634, 1839739926, 69050267, 1530777140,
+ 1802120822, 316088629, 1830418225, 488944891, 1680673954,
+ 1853748387, 946827723, 1037746818, 1238619545, 1513900641,
+ 1441966234, 367393385, 928306929, 946006977, 985847834,
+ 1049400181, 1956764878, 36406206, 1925613800, 2081522508,
+ 2118956479, 1612420674, 1668583807, 1800004220, 1447372094,
+ 523904750, 1435821048, 923108080, 216161028, 1504871315,
+ 306401572, 2018281851, 1820959944, 2136819798, 359743094,
+ 1354150250, 1843084537, 1306570817, 244413420, 934220434,
+ 672987810, 1686379655, 1301613820, 1601294739, 484902984,
+ 139978006, 503211273, 294184214, 176384212, 281341425,
+ 228223074, 147857043, 1893762099, 1896806882, 1947861263,
+ 1193650546, 273227984, 1236198663, 2116758626, 489389012,
+ 593586330, 275676551, 360187215, 267062626, 265012701,
+ 719930310, 1621212876, 2108097238, 2026501127, 1865626297,
+ 894834024, 552005290, 1404522304, 48964196, 5816381,
+ 1889425288, 188942202, 509027654, 36125855, 365326415,
+ 790369079, 264348929, 513183458, 536647531, 13672163,
+ 313561074, 1730298077, 286900147, 1549759737, 1699573055,
+ 776289160, 2143346068, 1975249606, 1136476375, 262925046,
+ 92778659, 1856406685, 1884137923, 53392249, 1735424165,
+ 1602280572
+};
+char *string(const char *str) {
+ const char *s;
+
+ for (s = str; *s; s++)
+ ;
+ return stringn(str, s - str);
+}
+char *stringd(long n) {
+ char str[25], *s = str + sizeof (str);
+ unsigned long m;
+
+ if (n == LONG_MIN)
+ m = (unsigned long)LONG_MAX + 1;
+ else if (n < 0)
+ m = -n;
+ else
+ m = n;
+ do
+ *--s = m%10 + '0';
+ while ((m /= 10) != 0);
+ if (n < 0)
+ *--s = '-';
+ return stringn(s, str + sizeof (str) - s);
+}
+char *stringn(const char *str, int len) {
+ int i;
+ unsigned int h;
+ const char *end;
+ struct string *p;
+
+ assert(str);
+ for (h = 0, i = len, end = str; i > 0; i--)
+ h = (h<<1) + scatter[*(unsigned char *)end++];
+ h &= NELEMS(buckets)-1;
+ for (p = buckets[h]; p; p = p->link)
+ if (len == p->len) {
+ const char *s1 = str;
+ char *s2 = p->str;
+ do {
+ if (s1 == end)
+ return p->str;
+ } while (*s1++ == *s2++);
+ }
+ {
+ static char *next, *strlimit;
+ if (len + 1 >= strlimit - next) {
+ int n = len + 4*1024;
+ next = allocate(n, PERM);
+ strlimit = next + n;
+ }
+ NEW(p, PERM);
+ p->len = len;
+ for (p->str = next; str < end; )
+ *next++ = *str++;
+ *next++ = 0;
+ p->link = buckets[h];
+ buckets[h] = p;
+ return p->str;
+ }
+}
diff --git a/lcc/src/sym.c b/lcc/src/sym.c
new file mode 100755
index 0000000..1d754d4
--- /dev/null
+++ b/lcc/src/sym.c
@@ -0,0 +1,315 @@
+#include "c.h"
+#include <stdio.h>
+
+
+#define equalp(x) v.x == p->sym.u.c.v.x
+
+struct table {
+ int level;
+ Table previous;
+ struct entry {
+ struct symbol sym;
+ struct entry *link;
+ } *buckets[256];
+ Symbol all;
+};
+#define HASHSIZE NELEMS(((Table)0)->buckets)
+static struct table
+ cns = { CONSTANTS },
+ ext = { GLOBAL },
+ ids = { GLOBAL },
+ tys = { GLOBAL };
+Table constants = &cns;
+Table externals = &ext;
+Table identifiers = &ids;
+Table globals = &ids;
+Table types = &tys;
+Table labels;
+int level = GLOBAL;
+static int tempid;
+List loci, symbols;
+
+Table table(Table tp, int level) {
+ Table new;
+
+ NEW0(new, FUNC);
+ new->previous = tp;
+ new->level = level;
+ if (tp)
+ new->all = tp->all;
+ return new;
+}
+void foreach(Table tp, int lev, void (*apply)(Symbol, void *), void *cl) {
+ assert(tp);
+ while (tp && tp->level > lev)
+ tp = tp->previous;
+ if (tp && tp->level == lev) {
+ Symbol p;
+ Coordinate sav;
+ sav = src;
+ for (p = tp->all; p && p->scope == lev; p = p->up) {
+ src = p->src;
+ (*apply)(p, cl);
+ }
+ src = sav;
+ }
+}
+void enterscope(void) {
+ if (++level == LOCAL)
+ tempid = 0;
+}
+void exitscope(void) {
+ rmtypes(level);
+ if (types->level == level)
+ types = types->previous;
+ if (identifiers->level == level) {
+ if (Aflag >= 2) {
+ int n = 0;
+ Symbol p;
+ for (p = identifiers->all; p && p->scope == level; p = p->up)
+ if (++n > 127) {
+ warning("more than 127 identifiers declared in a block\n");
+ break;
+ }
+ }
+ identifiers = identifiers->previous;
+ }
+ assert(level >= GLOBAL);
+ --level;
+}
+Symbol install(const char *name, Table *tpp, int level, int arena) {
+ Table tp = *tpp;
+ struct entry *p;
+ unsigned h = (unsigned long)name&(HASHSIZE-1);
+
+ assert(level == 0 || level >= tp->level);
+ if (level > 0 && tp->level < level)
+ tp = *tpp = table(tp, level);
+ NEW0(p, arena);
+ p->sym.name = (char *)name;
+ p->sym.scope = level;
+ p->sym.up = tp->all;
+ tp->all = &p->sym;
+ p->link = tp->buckets[h];
+ tp->buckets[h] = p;
+ return &p->sym;
+}
+Symbol relocate(const char *name, Table src, Table dst) {
+ struct entry *p, **q;
+ Symbol *r;
+ unsigned h = (unsigned long)name&(HASHSIZE-1);
+
+ for (q = &src->buckets[h]; *q; q = &(*q)->link)
+ if (name == (*q)->sym.name)
+ break;
+ assert(*q);
+ /*
+ Remove the entry from src's hash chain
+ and from its list of all symbols.
+ */
+ p = *q;
+ *q = (*q)->link;
+ for (r = &src->all; *r && *r != &p->sym; r = &(*r)->up)
+ ;
+ assert(*r == &p->sym);
+ *r = p->sym.up;
+ /*
+ Insert the entry into dst's hash chain
+ and into its list of all symbols.
+ Return the symbol-table entry.
+ */
+ p->link = dst->buckets[h];
+ dst->buckets[h] = p;
+ p->sym.up = dst->all;
+ dst->all = &p->sym;
+ return &p->sym;
+}
+Symbol lookup(const char *name, Table tp) {
+ struct entry *p;
+ unsigned h = (unsigned long)name&(HASHSIZE-1);
+
+ assert(tp);
+ do
+ for (p = tp->buckets[h]; p; p = p->link)
+ if (name == p->sym.name)
+ return &p->sym;
+ while ((tp = tp->previous) != NULL);
+ return NULL;
+}
+int genlabel(int n) {
+ static int label = 1;
+
+ label += n;
+ return label - n;
+}
+Symbol findlabel(int lab) {
+ struct entry *p;
+ unsigned h = lab&(HASHSIZE-1);
+
+ for (p = labels->buckets[h]; p; p = p->link)
+ if (lab == p->sym.u.l.label)
+ return &p->sym;
+ NEW0(p, FUNC);
+ p->sym.name = stringd(lab);
+ p->sym.scope = LABELS;
+ p->sym.up = labels->all;
+ labels->all = &p->sym;
+ p->link = labels->buckets[h];
+ labels->buckets[h] = p;
+ p->sym.generated = 1;
+ p->sym.u.l.label = lab;
+ (*IR->defsymbol)(&p->sym);
+ return &p->sym;
+}
+Symbol constant(Type ty, Value v) {
+ struct entry *p;
+ unsigned h = v.u&(HASHSIZE-1);
+
+ ty = unqual(ty);
+ for (p = constants->buckets[h]; p; p = p->link)
+ if (eqtype(ty, p->sym.type, 1))
+ switch (ty->op) {
+ case INT: if (equalp(i)) return &p->sym; break;
+ case UNSIGNED: if (equalp(u)) return &p->sym; break;
+ case FLOAT: if (equalp(d)) return &p->sym; break;
+ case FUNCTION: if (equalp(g)) return &p->sym; break;
+ case ARRAY:
+ case POINTER: if (equalp(p)) return &p->sym; break;
+ default: assert(0);
+ }
+ NEW0(p, PERM);
+ p->sym.name = vtoa(ty, v);
+ p->sym.scope = CONSTANTS;
+ p->sym.type = ty;
+ p->sym.sclass = STATIC;
+ p->sym.u.c.v = v;
+ p->link = constants->buckets[h];
+ p->sym.up = constants->all;
+ constants->all = &p->sym;
+ constants->buckets[h] = p;
+ if (ty->u.sym && !ty->u.sym->addressed)
+ (*IR->defsymbol)(&p->sym);
+ p->sym.defined = 1;
+ return &p->sym;
+}
+Symbol intconst(int n) {
+ Value v;
+
+ v.i = n;
+ return constant(inttype, v);
+}
+Symbol genident(int scls, Type ty, int lev) {
+ Symbol p;
+
+ NEW0(p, lev >= LOCAL ? FUNC : PERM);
+ p->name = stringd(genlabel(1));
+ p->scope = lev;
+ p->sclass = scls;
+ p->type = ty;
+ p->generated = 1;
+ if (lev == GLOBAL)
+ (*IR->defsymbol)(p);
+ return p;
+}
+
+Symbol temporary(int scls, Type ty) {
+ Symbol p;
+
+ NEW0(p, FUNC);
+ p->name = stringd(++tempid);
+ p->scope = level < LOCAL ? LOCAL : level;
+ p->sclass = scls;
+ p->type = ty;
+ p->temporary = 1;
+ p->generated = 1;
+ return p;
+}
+Symbol newtemp(int sclass, int tc, int size) {
+ Symbol p = temporary(sclass, btot(tc, size));
+
+ (*IR->local)(p);
+ p->defined = 1;
+ return p;
+}
+
+Symbol allsymbols(Table tp) {
+ return tp->all;
+}
+
+void locus(Table tp, Coordinate *cp) {
+ loci = append(cp, loci);
+ symbols = append(allsymbols(tp), symbols);
+}
+
+void use(Symbol p, Coordinate src) {
+ Coordinate *cp;
+
+ NEW(cp, PERM);
+ *cp = src;
+ p->uses = append(cp, p->uses);
+}
+/* findtype - find type ty in identifiers */
+Symbol findtype(Type ty) {
+ Table tp = identifiers;
+ int i;
+ struct entry *p;
+
+ assert(tp);
+ do
+ for (i = 0; i < HASHSIZE; i++)
+ for (p = tp->buckets[i]; p; p = p->link)
+ if (p->sym.type == ty && p->sym.sclass == TYPEDEF)
+ return &p->sym;
+ while ((tp = tp->previous) != NULL);
+ return NULL;
+}
+
+/* mkstr - make a string constant */
+Symbol mkstr(char *str) {
+ Value v;
+ Symbol p;
+
+ v.p = str;
+ p = constant(array(chartype, strlen(v.p) + 1, 0), v);
+ if (p->u.c.loc == NULL)
+ p->u.c.loc = genident(STATIC, p->type, GLOBAL);
+ return p;
+}
+
+/* mksymbol - make a symbol for name, install in &globals if sclass==EXTERN */
+Symbol mksymbol(int sclass, const char *name, Type ty) {
+ Symbol p;
+
+ if (sclass == EXTERN)
+ p = install(string(name), &globals, GLOBAL, PERM);
+ else {
+ NEW0(p, PERM);
+ p->name = string(name);
+ p->scope = GLOBAL;
+ }
+ p->sclass = sclass;
+ p->type = ty;
+ (*IR->defsymbol)(p);
+ p->defined = 1;
+ return p;
+}
+
+/* vtoa - return string for the constant v of type ty */
+char *vtoa(Type ty, Value v) {
+ char buf[50];
+
+ ty = unqual(ty);
+ switch (ty->op) {
+ case INT: return stringd(v.i);
+ case UNSIGNED: return stringf((v.u&~0x7FFF) ? "0x%X" : "%U", v.u);
+ case FLOAT: return stringf("%g", (double)v.d);
+ case ARRAY:
+ if (ty->type == chartype || ty->type == signedchar
+ || ty->type == unsignedchar)
+ return v.p;
+ return stringf("%p", v.p);
+ case POINTER: return stringf("%p", v.p);
+ case FUNCTION: return stringf("%p", v.g);
+ }
+ assert(0); return NULL;
+}
diff --git a/lcc/src/symbolic.c b/lcc/src/symbolic.c
new file mode 100755
index 0000000..35ff55c
--- /dev/null
+++ b/lcc/src/symbolic.c
@@ -0,0 +1,494 @@
+#include <time.h>
+#include <ctype.h>
+#include "c.h"
+
+#define I(f) s_##f
+
+static Node *tail;
+static int off, maxoff, uid = 0, verbose = 0, html = 0;
+
+static const char *yyBEGIN(const char *tag) {
+ if (html)
+ print("<%s>", tag);
+ return tag;
+}
+
+static void yyEND(const char *tag) {
+ if (html)
+ print("</%s>", tag);
+ if (isupper(*tag))
+ print("\n");
+}
+
+#define BEGIN(tag) do { const char *yytag=yyBEGIN(#tag);
+#define END yyEND(yytag); } while (0)
+#define ITEM BEGIN(li)
+#define START BEGIN(LI)
+#define ANCHOR(attr,code) do { const char *yytag="a"; if (html) { printf("<a " #attr "=\""); code; print("\">"); }
+#define NEWLINE print(html ? "<br>\n" : "\n")
+
+static void emitCoord(Coordinate src) {
+ if (src.file && *src.file) {
+ ANCHOR(href,print("%s", src.file)); print("%s", src.file); END;
+ print(":");
+ }
+ print("%d.%d", src.y, src.x);
+}
+
+static void emitString(int len, const char *s) {
+ for ( ; len-- > 0; s++)
+ if (*s == '&' && html)
+ print("&amp;");
+ else if (*s == '<' && html)
+ print("&lt;");
+ else if (*s == '>' && html)
+ print("&lt;");
+ else if (*s == '"' || *s == '\\')
+ print("\\%c", *s);
+ else if (*s >= ' ' && *s < 0177)
+ print("%c", *s);
+ else
+ print("\\%d%d%d", (*s>>6)&3, (*s>>3)&7, *s&7);
+}
+
+static void emitSymRef(Symbol p) {
+ (*IR->defsymbol)(p);
+ ANCHOR(href,print("#%s", p->x.name)); BEGIN(code); print("%s", p->name); END; END;
+}
+
+static void emitSymbol(Symbol p) {
+ (*IR->defsymbol)(p);
+ ANCHOR(name,print("%s", p->x.name)); BEGIN(code); print("%s", p->name); END; END;
+ BEGIN(ul);
+#define xx(field,code) ITEM; if (!html) print(" "); print(#field "="); code; END
+ if (verbose && (src.y || src.x))
+ xx(src,emitCoord(p->src));
+ xx(type,print("%t", p->type));
+ xx(sclass,print("%k", p->sclass));
+ switch (p->scope) {
+ case CONSTANTS: xx(scope,print("CONSTANTS")); break;
+ case LABELS: xx(scope,print("LABELS")); break;
+ case GLOBAL: xx(scope,print("GLOBAL")); break;
+ case PARAM: xx(scope,print("PARAM")); break;
+ case LOCAL: xx(scope,print("LOCAL")); break;
+ default:
+ if (p->scope > LOCAL)
+ xx(scope,print("LOCAL+%d", p->scope-LOCAL));
+ else
+ xx(scope,print("%d", p->scope));
+ }
+ if (p->scope >= PARAM && p->sclass != STATIC)
+ xx(offset,print("%d", p->x.offset));
+ xx(ref,print("%f", p->ref));
+ if (p->temporary && p->u.t.cse)
+ xx(u.t.cse,print("%p", p->u.t.cse));
+ END;
+#undef xx
+}
+
+/* address - initialize q for addressing expression p+n */
+static void I(address)(Symbol q, Symbol p, long n) {
+ q->name = stringf("%s%s%D", p->name, n > 0 ? "+" : "", n);
+ (*IR->defsymbol)(q);
+ START; print("address "); emitSymbol(q); END;
+}
+
+/* blockbeg - start a block */
+static void I(blockbeg)(Env *e) {
+ e->offset = off;
+ START; print("blockbeg off=%d", off); END;
+}
+
+/* blockend - start a block */
+static void I(blockend)(Env *e) {
+ if (off > maxoff)
+ maxoff = off;
+ START; print("blockend off=%d", off); END;
+ off = e->offset;
+}
+
+/* defaddress - initialize an address */
+static void I(defaddress)(Symbol p){
+ START; print("defaddress "); emitSymRef(p); END;
+}
+
+/* defconst - define a constant */
+static void I(defconst)(int suffix, int size, Value v) {
+ START;
+ print("defconst ");
+ switch (suffix) {
+ case I:
+ print("int.%d ", size);
+ BEGIN(code);
+ if (size > sizeof (int))
+ print("%D", v.i);
+ else
+ print("%d", (int)v.i);
+ END;
+ break;
+ case U:
+ print("unsigned.%d ", size);
+ BEGIN(code);
+ if (size > sizeof (unsigned))
+ print("%U", v.u);
+ else
+ print("%u", (unsigned)v.u);
+ END;
+ break;
+ case P: print("void*.%d ", size); BEGIN(code); print("%p", v.p); END; break;
+ case F: print("float.%d ", size); BEGIN(code); print("%g", (double)v.d); END; break;
+ default: assert(0);
+ }
+ END;
+}
+
+/* defstring - emit a string constant */
+static void I(defstring)(int len, char *s) {
+ START; print("defstring ");
+ BEGIN(code); print("\""); emitString(len, s); print("\""); END;
+ END;
+}
+
+/* defsymbol - define a symbol: initialize p->x */
+static void I(defsymbol)(Symbol p) {
+ if (p->x.name == NULL)
+ p->x.name = stringd(++uid);
+}
+
+/* emit - emit the dags on list p */
+static void I(emit)(Node p){
+ ITEM;
+ if (!html)
+ print(" ");
+ for (; p; p = p->x.next) {
+ if (p->op == LABEL+V) {
+ assert(p->syms[0]);
+ ANCHOR(name,print("%s", p->syms[0]->x.name));
+ BEGIN(code); print("%s", p->syms[0]->name); END;
+ END;
+ print(":");
+ } else {
+ int i;
+ if (p->x.listed) {
+ BEGIN(strong); print("%d", p->x.inst); END; print("'");
+ print(" %s", opname(p->op));
+ } else
+ print("%d. %s", p->x.inst, opname(p->op));
+ if (p->count > 1)
+ print(" count=%d", p->count);
+ for (i = 0; i < NELEMS(p->kids) && p->kids[i]; i++)
+ print(" #%d", p->kids[i]->x.inst);
+ if (generic(p->op) == CALL && p->syms[0] && p->syms[0]->type)
+ print(" {%t}", p->syms[0]->type);
+ else
+ for (i = 0; i < NELEMS(p->syms) && p->syms[i]; i++) {
+ print(" ");
+ if (p->syms[i]->scope == CONSTANTS)
+ print(p->syms[i]->name);
+ else
+ emitSymRef(p->syms[i]);
+ }
+ }
+ NEWLINE;
+ }
+ END;
+}
+
+/* export - announce p as exported */
+static void I(export)(Symbol p) {
+ START; print("export "); emitSymRef(p); END;
+}
+
+/* function - generate code for a function */
+static void I(function)(Symbol f, Symbol caller[], Symbol callee[], int ncalls) {
+ int i;
+
+ (*IR->defsymbol)(f);
+ off = 0;
+ for (i = 0; caller[i] && callee[i]; i++) {
+ off = roundup(off, caller[i]->type->align);
+ caller[i]->x.offset = callee[i]->x.offset = off;
+ off += caller[i]->type->size;
+ }
+ if (!html) {
+ print("function ");
+ emitSymbol(f);
+ print(" ncalls=%d\n", ncalls);
+ for (i = 0; caller[i]; i++)
+ START; print("caller "); emitSymbol(caller[i]); END;
+ for (i = 0; callee[i]; i++)
+ START; print("callee "); emitSymbol(callee[i]); END;
+ } else {
+ START;
+ print("function");
+ BEGIN(UL);
+#define xx(field,code) ITEM; print(#field "="); code; END
+ xx(f,emitSymbol(f));
+ xx(ncalls,print("%d", ncalls));
+ if (caller[0]) {
+ ITEM; print("caller"); BEGIN(OL);
+ for (i = 0; caller[i]; i++)
+ ITEM; emitSymbol(caller[i]); END;
+ END; END;
+ ITEM; print("callee"); BEGIN(OL);
+ for (i = 0; callee[i]; i++)
+ ITEM; emitSymbol(callee[i]); END;
+ END; END;
+ } else {
+ xx(caller,BEGIN(em); print("empty"); END);
+ xx(callee,BEGIN(em); print("empty"); END);
+ }
+ END;
+ END;
+ }
+ maxoff = off = 0;
+ gencode(caller, callee);
+ if (html)
+ START; print("emitcode"); BEGIN(ul); emitcode(); END; END;
+ else
+ emitcode();
+ START; print("maxoff=%d", maxoff); END;
+#undef xx
+}
+
+/* visit - generate code for *p */
+static int visit(Node p, int n) {
+ if (p && p->x.inst == 0) {
+ p->x.inst = ++n;
+ n = visit(p->kids[0], n);
+ n = visit(p->kids[1], n);
+ *tail = p;
+ tail = &p->x.next;
+ }
+ return n;
+}
+
+/* gen0 - generate code for the dags on list p */
+static Node I(gen)(Node p) {
+ int n;
+ Node nodelist;
+
+ tail = &nodelist;
+ for (n = 0; p; p = p->link) {
+ switch (generic(p->op)) { /* check for valid forest */
+ case CALL:
+ assert(IR->wants_dag || p->count == 0);
+ break;
+ case ARG:
+ case ASGN: case JUMP: case LABEL: case RET:
+ case EQ: case GE: case GT: case LE: case LT: case NE:
+ assert(p->count == 0);
+ break;
+ case INDIR:
+ assert(IR->wants_dag && p->count > 0);
+ break;
+ default:
+ assert(0);
+ }
+ check(p);
+ p->x.listed = 1;
+ n = visit(p, n);
+ }
+ *tail = 0;
+ return nodelist;
+}
+
+/* global - announce a global */
+static void I(global)(Symbol p) {
+ START; print("global "); emitSymbol(p); END;
+}
+
+/* import - import a symbol */
+static void I(import)(Symbol p) {
+ START; print("import "); emitSymRef(p); END;
+}
+
+/* local - local variable */
+static void I(local)(Symbol p) {
+ if (p->temporary)
+ p->name = stringf("t%s", p->name);
+ (*IR->defsymbol)(p);
+ off = roundup(off, p->type->align);
+ p->x.offset = off;
+ off += p->type->size;
+ START; print(p->temporary ? "temporary " : "local "); emitSymbol(p); END;
+}
+
+/* progbeg - beginning of program */
+static void I(progbeg)(int argc, char *argv[]) {
+ int i;
+
+ for (i = 1; i < argc; i++)
+ if (strcmp(argv[i], "-v") == 0)
+ verbose++;
+ else if (strcmp(argv[i], "-html") == 0)
+ html++;
+ if (html) {
+ print("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">\n");
+ print("<html>");
+ BEGIN(head);
+ if (firstfile && *firstfile)
+ BEGIN(title); emitString(strlen(firstfile), firstfile); END;
+ print("<link rev=made href=\"mailto:drh@microsoft.com\">\n");
+ END;
+ print("<body>\n");
+ if (firstfile && *firstfile)
+ BEGIN(h1); emitString(strlen(firstfile), firstfile); END;
+ BEGIN(P); BEGIN(em);
+ print("Links lead from uses of identifiers and labels to their definitions.");
+ END; END;
+ print("<ul>\n");
+ START;
+ print("progbeg");
+ BEGIN(ol);
+ for (i = 1; i < argc; i++) {
+ ITEM;
+ BEGIN(code); print("\""); emitString(strlen(argv[i]), argv[i]); print("\""); END;
+ END;
+ }
+ END;
+ END;
+ }
+}
+
+/* progend - end of program */
+static void I(progend)(void) {
+ START; print("progend"); END;
+ if (html) {
+ time_t t;
+ print("</ul>\n");
+ time(&t);
+ print("<hr><address>%s</address>\n", ctime(&t));
+ print("</body></html>\n");
+ }
+}
+
+/* segment - switch to segment s */
+static void I(segment)(int s) {
+ START; print("segment %s", &"text\0bss\0.data\0lit\0.sym\0."[5*s-5]); END;
+}
+
+/* space - initialize n bytes of space */
+static void I(space)(int n) {
+ START; print("space %d", n); END;
+}
+
+static void I(stabblock)(int brace, int lev, Symbol *p) {}
+
+/* stabend - finalize stab output */
+static void I(stabend)(Coordinate *cp, Symbol p, Coordinate **cpp, Symbol *sp, Symbol *stab) {
+ int i;
+
+ if (p)
+ emitSymRef(p);
+ print("\n");
+ if (cpp && sp)
+ for (i = 0; cpp[i] && sp[i]; i++) {
+ print("%w.%d: ", cpp[i], cpp[i]->x);
+ emitSymRef(sp[i]);
+ print("\n");
+ }
+}
+
+static void I(stabfend)(Symbol p, int lineno) {}
+static void I(stabinit)(char *file, int argc, char *argv[]) {}
+
+/* stabline - emit line number information for source coordinate *cp */
+static void I(stabline)(Coordinate *cp) {
+ if (cp->file)
+ print("%s:", cp->file);
+ print("%d.%d:\n", cp->y, cp->x);
+}
+
+static void I(stabsym)(Symbol p) {}
+static void I(stabtype)(Symbol p) {}
+
+Interface symbolicIR = {
+ 1, 1, 0, /* char */
+ 2, 2, 0, /* short */
+ 4, 4, 0, /* int */
+ 4, 4, 0, /* long */
+ 4, 4, 0, /* long long */
+ 4, 4, 1, /* float */
+ 8, 8, 1, /* double */
+ 8, 8, 1, /* long double */
+ 4, 4, 0, /* T* */
+ 0, 4, 0, /* struct */
+ 0, /* little_endian */
+ 0, /* mulops_calls */
+ 0, /* wants_callb */
+ 1, /* wants_argb */
+ 1, /* left_to_right */
+ 1, /* wants_dag */
+ 0, /* unsigned_char */
+ I(address),
+ I(blockbeg),
+ I(blockend),
+ I(defaddress),
+ I(defconst),
+ I(defstring),
+ I(defsymbol),
+ I(emit),
+ I(export),
+ I(function),
+ I(gen),
+ I(global),
+ I(import),
+ I(local),
+ I(progbeg),
+ I(progend),
+ I(segment),
+ I(space),
+ I(stabblock),
+ I(stabend),
+ I(stabfend),
+ I(stabinit),
+ I(stabline),
+ I(stabsym),
+ I(stabtype)
+};
+
+Interface symbolic64IR = {
+ 1, 1, 0, /* char */
+ 2, 2, 0, /* short */
+ 4, 4, 0, /* int */
+ 8, 8, 0, /* long */
+ 8, 8, 0, /* long long */
+ 4, 4, 1, /* float */
+ 8, 8, 1, /* double */
+ 8, 8, 1, /* long double */
+ 8, 8, 0, /* T* */
+ 0, 1, 0, /* struct */
+ 1, /* little_endian */
+ 0, /* mulops_calls */
+ 0, /* wants_callb */
+ 1, /* wants_argb */
+ 1, /* left_to_right */
+ 1, /* wants_dag */
+ 0, /* unsigned_char */
+ I(address),
+ I(blockbeg),
+ I(blockend),
+ I(defaddress),
+ I(defconst),
+ I(defstring),
+ I(defsymbol),
+ I(emit),
+ I(export),
+ I(function),
+ I(gen),
+ I(global),
+ I(import),
+ I(local),
+ I(progbeg),
+ I(progend),
+ I(segment),
+ I(space),
+ I(stabblock),
+ I(stabend),
+ I(stabfend),
+ I(stabinit),
+ I(stabline),
+ I(stabsym),
+ I(stabtype)
+};
diff --git a/lcc/src/token.h b/lcc/src/token.h
new file mode 100755
index 0000000..f92bf6a
--- /dev/null
+++ b/lcc/src/token.h
@@ -0,0 +1,133 @@
+/*
+xx(symbol, value, prec, op, optree, kind, string)
+*/
+yy(0, 0, 0, 0, 0, 0, 0)
+xx(FLOAT, 1, 0, 0, 0, CHAR, "float")
+xx(DOUBLE, 2, 0, 0, 0, CHAR, "double")
+xx(CHAR, 3, 0, 0, 0, CHAR, "char")
+xx(SHORT, 4, 0, 0, 0, CHAR, "short")
+xx(INT, 5, 0, 0, 0, CHAR, "int")
+xx(UNSIGNED, 6, 0, 0, 0, CHAR, "unsigned")
+xx(POINTER, 7, 0, 0, 0, 0, "pointer")
+xx(VOID, 8, 0, 0, 0, CHAR, "void")
+xx(STRUCT, 9, 0, 0, 0, CHAR, "struct")
+xx(UNION, 10, 0, 0, 0, CHAR, "union")
+xx(FUNCTION, 11, 0, 0, 0, 0, "function")
+xx(ARRAY, 12, 0, 0, 0, 0, "array")
+xx(ENUM, 13, 0, 0, 0, CHAR, "enum")
+xx(LONG, 14, 0, 0, 0, CHAR, "long")
+xx(CONST, 15, 0, 0, 0, CHAR, "const")
+xx(VOLATILE, 16, 0, 0, 0, CHAR, "volatile")
+yy(0, 17, 0, 0, 0, 0, 0)
+yy(0, 18, 0, 0, 0, 0, 0)
+yy(0, 19, 0, 0, 0, 0, 0)
+yy(0, 20, 0, 0, 0, 0, 0)
+yy(0, 21, 0, 0, 0, 0, 0)
+yy(0, 22, 0, 0, 0, 0, 0)
+yy(0, 23, 0, 0, 0, 0, 0)
+yy(0, 24, 0, 0, 0, 0, 0)
+yy(0, 25, 0, 0, 0, 0, 0)
+yy(0, 26, 0, 0, 0, 0, 0)
+yy(0, 27, 0, 0, 0, 0, 0)
+yy(0, 28, 0, 0, 0, 0, "long long")
+yy(0, 29, 0, 0, 0, 0, 0)
+yy(0, 30, 0, 0, 0, 0, 0)
+yy(0, 31, 0, 0, 0, 0, "const volatile")
+xx(ID, 32, 0, 0, 0, ID, "identifier")
+yy(0, 33, 0, 0, 0, ID, "!")
+xx(FCON, 34, 0, 0, 0, ID, "floating constant")
+xx(ICON, 35, 0, 0, 0, ID, "integer constant")
+xx(SCON, 36, 0, 0, 0, ID, "string constant")
+yy(0, 37, 13, MOD, bittree,'%', "%")
+yy(0, 38, 8, BAND, bittree,ID, "&")
+xx(INCR, 39, 0, ADD, addtree,ID, "++")
+yy(0, 40, 0, 0, 0, ID, "(")
+yy(0, 41, 0, 0, 0, ')', ")")
+yy(0, 42, 13, MUL, multree,ID, "*")
+yy(0, 43, 12, ADD, addtree,ID, "+")
+yy(0, 44, 1, 0, 0, ',', ",")
+yy(0, 45, 12, SUB, subtree,ID, "-")
+yy(0, 46, 0, 0, 0, '.', ".")
+yy(0, 47, 13, DIV, multree,'/', "/")
+xx(DECR, 48, 0, SUB, subtree,ID, "--")
+xx(DEREF, 49, 0, 0, 0, DEREF, "->")
+xx(ANDAND, 50, 5, AND, andtree,ANDAND, "&&")
+xx(OROR, 51, 4, OR, andtree,OROR, "||")
+xx(LEQ, 52, 10, LE, cmptree,LEQ, "<=")
+xx(EQL, 53, 9, EQ, eqtree, EQL, "==")
+xx(NEQ, 54, 9, NE, eqtree, NEQ, "!=")
+xx(GEQ, 55, 10, GE, cmptree,GEQ, ">=")
+xx(RSHIFT, 56, 11, RSH, shtree, RSHIFT, ">>")
+xx(LSHIFT, 57, 11, LSH, shtree, LSHIFT, "<<")
+yy(0, 58, 0, 0, 0, ':', ":")
+yy(0, 59, 0, 0, 0, IF, ";")
+yy(0, 60, 10, LT, cmptree,'<', "<")
+yy(0, 61, 2, ASGN, asgntree,'=', "=")
+yy(0, 62, 10, GT, cmptree,'>', ">")
+yy(0, 63, 0, 0, 0, '?', "?")
+xx(ELLIPSIS, 64, 0, 0, 0, ELLIPSIS,"...")
+xx(SIZEOF, 65, 0, 0, 0, ID, "sizeof")
+yy(0, 66, 0, 0, 0, 0, 0)
+xx(AUTO, 67, 0, 0, 0, STATIC, "auto")
+xx(BREAK, 68, 0, 0, 0, IF, "break")
+xx(CASE, 69, 0, 0, 0, IF, "case")
+xx(CONTINUE, 70, 0, 0, 0, IF, "continue")
+xx(DEFAULT, 71, 0, 0, 0, IF, "default")
+xx(DO, 72, 0, 0, 0, IF, "do")
+xx(ELSE, 73, 0, 0, 0, IF, "else")
+xx(EXTERN, 74, 0, 0, 0, STATIC, "extern")
+xx(FOR, 75, 0, 0, 0, IF, "for")
+xx(GOTO, 76, 0, 0, 0, IF, "goto")
+xx(IF, 77, 0, 0, 0, IF, "if")
+xx(REGISTER, 78, 0, 0, 0, STATIC, "register")
+xx(RETURN, 79, 0, 0, 0, IF, "return")
+xx(SIGNED, 80, 0, 0, 0, CHAR, "signed")
+xx(STATIC, 81, 0, 0, 0, STATIC, "static")
+xx(SWITCH, 82, 0, 0, 0, IF, "switch")
+xx(TYPEDEF, 83, 0, 0, 0, STATIC, "typedef")
+xx(WHILE, 84, 0, 0, 0, IF, "while")
+xx(TYPECODE, 85, 0, 0, 0, ID, "__typecode")
+xx(FIRSTARG, 86, 0, 0, 0, ID, "__firstarg")
+yy(0, 87, 0, 0, 0, 0, 0)
+yy(0, 88, 0, 0, 0, 0, 0)
+yy(0, 89, 0, 0, 0, 0, 0)
+yy(0, 90, 0, 0, 0, 0, 0)
+yy(0, 91, 0, 0, 0, '[', "[")
+yy(0, 92, 0, 0, 0, 0, 0)
+yy(0, 93, 0, 0, 0, ']', "]")
+yy(0, 94, 7, BXOR, bittree,'^', "^")
+yy(0, 95, 0, 0, 0, 0, 0)
+yy(0, 96, 0, 0, 0, 0, 0)
+yy(0, 97, 0, 0, 0, 0, 0)
+yy(0, 98, 0, 0, 0, 0, 0)
+yy(0, 99, 0, 0, 0, 0, 0)
+yy(0, 100, 0, 0, 0, 0, 0)
+yy(0, 101, 0, 0, 0, 0, 0)
+yy(0, 102, 0, 0, 0, 0, 0)
+yy(0, 103, 0, 0, 0, 0, 0)
+yy(0, 104, 0, 0, 0, 0, 0)
+yy(0, 105, 0, 0, 0, 0, 0)
+yy(0, 106, 0, 0, 0, 0, 0)
+yy(0, 107, 0, 0, 0, 0, 0)
+yy(0, 108, 0, 0, 0, 0, 0)
+yy(0, 109, 0, 0, 0, 0, 0)
+yy(0, 110, 0, 0, 0, 0, 0)
+yy(0, 111, 0, 0, 0, 0, 0)
+yy(0, 112, 0, 0, 0, 0, 0)
+yy(0, 113, 0, 0, 0, 0, 0)
+yy(0, 114, 0, 0, 0, 0, 0)
+yy(0, 115, 0, 0, 0, 0, 0)
+yy(0, 116, 0, 0, 0, 0, 0)
+yy(0, 117, 0, 0, 0, 0, 0)
+yy(0, 118, 0, 0, 0, 0, 0)
+yy(0, 119, 0, 0, 0, 0, 0)
+yy(0, 120, 0, 0, 0, 0, 0)
+yy(0, 121, 0, 0, 0, 0, 0)
+yy(0, 122, 0, 0, 0, 0, 0)
+yy(0, 123, 0, 0, 0, IF, "{")
+yy(0, 124, 6, BOR, bittree,'|', "|")
+yy(0, 125, 0, 0, 0, '}', "}")
+yy(0, 126, 0, BCOM, 0, ID, "~")
+xx(EOI, 127, 0, 0, 0, EOI, "end of input")
+#undef xx
+#undef yy
diff --git a/lcc/src/trace.c b/lcc/src/trace.c
new file mode 100755
index 0000000..55b18a1
--- /dev/null
+++ b/lcc/src/trace.c
@@ -0,0 +1,180 @@
+#include "c.h"
+
+
+static char *fmt, *fp, *fmtend; /* format string, current & limit pointer */
+static Tree args; /* printf arguments */
+static Symbol frameno; /* local holding frame number */
+
+/* appendstr - append str to the evolving format string, expanding it if necessary */
+static void appendstr(char *str) {
+ do
+ if (fp == fmtend)
+ if (fp) {
+ char *s = allocate(2*(fmtend - fmt), FUNC);
+ strncpy(s, fmt, fmtend - fmt);
+ fp = s + (fmtend - fmt);
+ fmtend = s + 2*(fmtend - fmt);
+ fmt = s;
+ } else {
+ fp = fmt = allocate(80, FUNC);
+ fmtend = fmt + 80;
+ }
+ while ((*fp++ = *str++) != 0);
+ fp--;
+}
+
+/* tracevalue - append format and argument to print the value of e */
+static void tracevalue(Tree e, int lev) {
+ Type ty = unqual(e->type);
+
+ switch (ty->op) {
+ case INT:
+ if (ty == chartype || ty == signedchar)
+ appendstr("'\\x%02x'");
+ else if (ty == longtype)
+ appendstr("0x%ld");
+ else
+ appendstr("0x%d");
+ break;
+ case UNSIGNED:
+ if (ty == chartype || ty == unsignedchar)
+ appendstr("'\\x%02x'");
+ else if (ty == unsignedlong)
+ appendstr("0x%lx");
+ else
+ appendstr("0x%x");
+ break;
+ case FLOAT:
+ if (ty == longdouble)
+ appendstr("%Lg");
+ else
+ appendstr("%g");
+ break;
+ case POINTER:
+ if (unqual(ty->type) == chartype
+ || unqual(ty->type) == signedchar
+ || unqual(ty->type) == unsignedchar) {
+ static Symbol null;
+ if (null == NULL)
+ null = mkstr("(null)");
+ tracevalue(cast(e, unsignedtype), lev + 1);
+ appendstr(" \"%.30s\"");
+ e = condtree(e, e, pointer(idtree(null->u.c.loc)));
+ } else {
+ appendstr("("); appendstr(typestring(ty, "")); appendstr(")0x%x");
+ }
+ break;
+ case STRUCT: {
+ Field q;
+ appendstr("("); appendstr(typestring(ty, "")); appendstr("){");
+ for (q = ty->u.sym->u.s.flist; q; q = q->link) {
+ appendstr(q->name); appendstr("=");
+ tracevalue(field(addrof(e), q->name), lev + 1);
+ if (q->link)
+ appendstr(",");
+ }
+ appendstr("}");
+ return;
+ }
+ case UNION:
+ appendstr("("); appendstr(typestring(ty, "")); appendstr("){...}");
+ return;
+ case ARRAY:
+ if (lev && ty->type->size > 0) {
+ int i;
+ e = pointer(e);
+ appendstr("{");
+ for (i = 0; i < ty->size/ty->type->size; i++) {
+ Tree p = (*optree['+'])(ADD, e, consttree(i, inttype));
+ if (isptr(p->type) && isarray(p->type->type))
+ p = retype(p, p->type->type);
+ else
+ p = rvalue(p);
+ if (i)
+ appendstr(",");
+ tracevalue(p, lev + 1);
+ }
+ appendstr("}");
+ } else
+ appendstr(typestring(ty, ""));
+ return;
+ default:
+ assert(0);
+ }
+ e = cast(e, promote(ty));
+ args = tree(mkop(ARG,e->type), e->type, e, args);
+}
+
+/* tracefinis - complete & generate the trace call to print */
+static void tracefinis(Symbol printer) {
+ Tree *ap;
+ Symbol p;
+
+ *fp = 0;
+ p = mkstr(string(fmt));
+ for (ap = &args; *ap; ap = &(*ap)->kids[1])
+ ;
+ *ap = tree(ARG+P, charptype, pointer(idtree(p->u.c.loc)), 0);
+ walk(calltree(pointer(idtree(printer)), freturn(printer->type), args, NULL), 0, 0);
+ args = 0;
+ fp = fmtend = 0;
+}
+
+/* tracecall - generate code to trace entry to f */
+static void tracecall(Symbol printer, Symbol f) {
+ int i;
+ Symbol counter = genident(STATIC, inttype, GLOBAL);
+
+ defglobal(counter, BSS);
+ (*IR->space)(counter->type->size);
+ frameno = genident(AUTO, inttype, level);
+ addlocal(frameno);
+ appendstr(f->name); appendstr("#");
+ tracevalue(asgn(frameno, incr(INCR, idtree(counter), consttree(1, inttype))), 0);
+ appendstr("(");
+ for (i = 0; f->u.f.callee[i]; i++) {
+ if (i)
+ appendstr(",");
+ appendstr(f->u.f.callee[i]->name); appendstr("=");
+ tracevalue(idtree(f->u.f.callee[i]), 0);
+ }
+ if (variadic(f->type))
+ appendstr(",...");
+ appendstr(") called\n");
+ tracefinis(printer);
+}
+
+/* tracereturn - generate code to trace return e */
+static void tracereturn(Symbol printer, Symbol f, Tree e) {
+ appendstr(f->name); appendstr("#");
+ tracevalue(idtree(frameno), 0);
+ appendstr(" returned");
+ if (freturn(f->type) != voidtype && e) {
+ appendstr(" ");
+ tracevalue(e, 0);
+ }
+ appendstr("\n");
+ tracefinis(printer);
+}
+
+/* trace_init - initialize for tracing */
+void trace_init(int argc, char *argv[]) {
+ int i;
+ static int inited;
+
+ if (inited)
+ return;
+ inited = 1;
+ type_init(argc, argv);
+ if (IR)
+ for (i = 1; i < argc; i++)
+ if (strncmp(argv[i], "-t", 2) == 0 && strchr(argv[i], '=') == NULL) {
+ Symbol printer = mksymbol(EXTERN,
+ argv[i][2] ? &argv[i][2] : "printf",
+ ftype(inttype, ptr(qual(CONST, chartype))));
+ printer->defined = 0;
+ attach((Apply)tracecall, printer, &events.entry);
+ attach((Apply)tracereturn, printer, &events.returns);
+ break;
+ }
+}
diff --git a/lcc/src/tree.c b/lcc/src/tree.c
new file mode 100755
index 0000000..1f5b49c
--- /dev/null
+++ b/lcc/src/tree.c
@@ -0,0 +1,223 @@
+#include "c.h"
+
+
+int where = STMT;
+static int warn;
+static int nid = 1; /* identifies trees & nodes in debugging output */
+static struct nodeid {
+ int printed;
+ Tree node;
+} ids[500]; /* if ids[i].node == p, then p's id is i */
+
+static void printtree1(Tree, int, int);
+
+Tree tree(int op, Type type, Tree left, Tree right) {
+ Tree p;
+
+ NEW0(p, where);
+ p->op = op;
+ p->type = type;
+ p->kids[0] = left;
+ p->kids[1] = right;
+ return p;
+}
+
+Tree texpr(Tree (*f)(int), int tok, int a) {
+ int save = where;
+ Tree p;
+
+ where = a;
+ p = (*f)(tok);
+ where = save;
+ return p;
+}
+static Tree root1(Tree p) {
+ if (p == NULL)
+ return p;
+ if (p->type == voidtype)
+ warn++;
+ switch (generic(p->op)) {
+ case COND: {
+ Tree q = p->kids[1];
+ assert(q && q->op == RIGHT);
+ if (p->u.sym && q->kids[0] && generic(q->kids[0]->op) == ASGN)
+ q->kids[0] = root1(q->kids[0]->kids[1]);
+ else
+ q->kids[0] = root1(q->kids[0]);
+ if (p->u.sym && q->kids[1] && generic(q->kids[1]->op) == ASGN)
+ q->kids[1] = root1(q->kids[1]->kids[1]);
+ else
+ q->kids[1] = root1(q->kids[1]);
+ p->u.sym = 0;
+ if (q->kids[0] == 0 && q->kids[1] == 0)
+ p = root1(p->kids[0]);
+ }
+ break;
+ case AND: case OR:
+ if ((p->kids[1] = root1(p->kids[1])) == 0)
+ p = root1(p->kids[0]);
+ break;
+ case NOT:
+ if (warn++ == 0)
+ warning("expression with no effect elided\n");
+ return root1(p->kids[0]);
+ case RIGHT:
+ if (p->kids[1] == 0)
+ return root1(p->kids[0]);
+ if (p->kids[0] && p->kids[0]->op == CALL+B
+ && p->kids[1] && p->kids[1]->op == INDIR+B)
+ /* avoid premature release of the CALL+B temporary */
+ return p->kids[0];
+ if (p->kids[0] && p->kids[0]->op == RIGHT
+ && p->kids[1] == p->kids[0]->kids[0])
+ /* de-construct e++ construction */
+ return p->kids[0]->kids[1];
+ p = tree(RIGHT, p->type, root1(p->kids[0]), root1(p->kids[1]));
+ return p->kids[0] || p->kids[1] ? p : (Tree)0;
+ case EQ: case NE: case GT: case GE: case LE: case LT:
+ case ADD: case SUB: case MUL: case DIV: case MOD:
+ case LSH: case RSH: case BAND: case BOR: case BXOR:
+ if (warn++ == 0)
+ warning("expression with no effect elided\n");
+ p = tree(RIGHT, p->type, root1(p->kids[0]), root1(p->kids[1]));
+ return p->kids[0] || p->kids[1] ? p : (Tree)0;
+ case INDIR:
+ if (p->type->size == 0 && unqual(p->type) != voidtype)
+ warning("reference to `%t' elided\n", p->type);
+ if (isptr(p->kids[0]->type) && isvolatile(p->kids[0]->type->type))
+ warning("reference to `volatile %t' elided\n", p->type);
+ /* fall thru */
+ case CVI: case CVF: case CVU: case CVP:
+ case NEG: case BCOM: case FIELD:
+ if (warn++ == 0)
+ warning("expression with no effect elided\n");
+ return root1(p->kids[0]);
+ case ADDRL: case ADDRG: case ADDRF: case CNST:
+ if (needconst)
+ return p;
+ if (warn++ == 0)
+ warning("expression with no effect elided\n");
+ return NULL;
+ case ARG: case ASGN: case CALL: case JUMP: case LABEL:
+ break;
+ default: assert(0);
+ }
+ return p;
+}
+
+Tree root(Tree p) {
+ warn = 0;
+ return root1(p);
+}
+
+char *opname(int op) {
+ static char *opnames[] = {
+ "",
+ "CNST",
+ "ARG",
+ "ASGN",
+ "INDIR",
+ "CVC",
+ "CVD",
+ "CVF",
+ "CVI",
+ "CVP",
+ "CVS",
+ "CVU",
+ "NEG",
+ "CALL",
+ "*LOAD*",
+ "RET",
+ "ADDRG",
+ "ADDRF",
+ "ADDRL",
+ "ADD",
+ "SUB",
+ "LSH",
+ "MOD",
+ "RSH",
+ "BAND",
+ "BCOM",
+ "BOR",
+ "BXOR",
+ "DIV",
+ "MUL",
+ "EQ",
+ "GE",
+ "GT",
+ "LE",
+ "LT",
+ "NE",
+ "JUMP",
+ "LABEL",
+ "AND",
+ "NOT",
+ "OR",
+ "COND",
+ "RIGHT",
+ "FIELD"
+ }, *suffixes[] = {
+ "0", "F", "D", "C", "S", "I", "U", "P", "V", "B",
+ "10","11","12","13","14","15"
+ };
+
+ if (generic(op) >= AND && generic(op) <= FIELD && opsize(op) == 0)
+ return opnames[opindex(op)];
+ return stringf("%s%s%s",
+ opindex(op) > 0 && opindex(op) < NELEMS(opnames) ?
+ opnames[opindex(op)] : stringd(opindex(op)),
+ suffixes[optype(op)], opsize(op) > 0 ? stringd(opsize(op)) : "");
+}
+
+int nodeid(Tree p) {
+ int i = 1;
+
+ ids[nid].node = p;
+ while (ids[i].node != p)
+ i++;
+ if (i == nid)
+ ids[nid++].printed = 0;
+ return i;
+}
+
+/* printed - return pointer to ids[id].printed */
+int *printed(int id) {
+ if (id)
+ return &ids[id].printed;
+ nid = 1;
+ return 0;
+}
+
+/* printtree - print tree p on fd */
+void printtree(Tree p, int fd) {
+ (void)printed(0);
+ printtree1(p, fd, 1);
+}
+
+/* printtree1 - recursively print tree p */
+static void printtree1(Tree p, int fd, int lev) {
+ FILE *f = fd == 1 ? stdout : stderr;
+ int i;
+ static char blanks[] = " ";
+
+ if (p == 0 || *printed(i = nodeid(p)))
+ return;
+ fprint(f, "#%d%S%S", i, blanks, i < 10 ? 2 : i < 100 ? 1 : 0, blanks, lev);
+ fprint(f, "%s %t", opname(p->op), p->type);
+ *printed(i) = 1;
+ for (i = 0; i < NELEMS(p->kids); i++)
+ if (p->kids[i])
+ fprint(f, " #%d", nodeid(p->kids[i]));
+ if (p->op == FIELD && p->u.field)
+ fprint(f, " %s %d..%d", p->u.field->name,
+ fieldsize(p->u.field) + fieldright(p->u.field), fieldright(p->u.field));
+ else if (generic(p->op) == CNST)
+ fprint(f, " %s", vtoa(p->type, p->u.v));
+ else if (p->u.sym)
+ fprint(f, " %s", p->u.sym->name);
+ if (p->node)
+ fprint(f, " node=%p", p->node);
+ fprint(f, "\n");
+ for (i = 0; i < NELEMS(p->kids); i++)
+ printtree1(p->kids[i], fd, lev + 1);
+}
diff --git a/lcc/src/types.c b/lcc/src/types.c
new file mode 100755
index 0000000..eead3e1
--- /dev/null
+++ b/lcc/src/types.c
@@ -0,0 +1,748 @@
+#include "c.h"
+#include <float.h>
+
+
+static Field isfield(const char *, Field);
+static Type type(int, Type, int, int, void *);
+
+static struct entry {
+ struct type type;
+ struct entry *link;
+} *typetable[128];
+static int maxlevel;
+
+static Symbol pointersym;
+
+Type chartype; /* char */
+Type doubletype; /* double */
+Type floattype; /* float */
+Type inttype; /* signed int */
+Type longdouble; /* long double */
+Type longtype; /* long */
+Type longlong; /* long long */
+Type shorttype; /* signed short int */
+Type signedchar; /* signed char */
+Type unsignedchar; /* unsigned char */
+Type unsignedlong; /* unsigned long int */
+Type unsignedlonglong; /* unsigned long long int */
+Type unsignedshort; /* unsigned short int */
+Type unsignedtype; /* unsigned int */
+Type funcptype; /* void (*)() */
+Type charptype; /* char* */
+Type voidptype; /* void* */
+Type voidtype; /* basic types: void */
+Type unsignedptr; /* unsigned type to hold void* */
+Type signedptr; /* signed type to hold void* */
+Type widechar; /* unsigned type that represents wchar_t */
+
+static Type xxinit(int op, char *name, Metrics m) {
+ Symbol p = install(string(name), &types, GLOBAL, PERM);
+ Type ty = type(op, 0, m.size, m.align, p);
+
+ assert(ty->align == 0 || ty->size%ty->align == 0);
+ p->type = ty;
+ p->addressed = m.outofline;
+ switch (ty->op) {
+ case INT:
+ p->u.limits.max.i = ones(8*ty->size)>>1;
+ p->u.limits.min.i = -p->u.limits.max.i - 1;
+ break;
+ case UNSIGNED:
+ p->u.limits.max.u = ones(8*ty->size);
+ p->u.limits.min.u = 0;
+ break;
+ case FLOAT:
+ if (ty->size == sizeof (float))
+ p->u.limits.max.d = FLT_MAX;
+ else if (ty->size == sizeof (double))
+ p->u.limits.max.d = DBL_MAX;
+ else
+ p->u.limits.max.d = LDBL_MAX;
+ p->u.limits.min.d = -p->u.limits.max.d;
+ break;
+ default: assert(0);
+ }
+ return ty;
+}
+static Type type(int op, Type ty, int size, int align, void *sym) {
+ unsigned h = (op^((unsigned long)ty>>3))
+&(NELEMS(typetable)-1);
+ struct entry *tn;
+
+ if (op != FUNCTION && (op != ARRAY || size > 0))
+ for (tn = typetable[h]; tn; tn = tn->link)
+ if (tn->type.op == op && tn->type.type == ty
+ && tn->type.size == size && tn->type.align == align
+ && tn->type.u.sym == sym)
+ return &tn->type;
+ NEW0(tn, PERM);
+ tn->type.op = op;
+ tn->type.type = ty;
+ tn->type.size = size;
+ tn->type.align = align;
+ tn->type.u.sym = sym;
+ tn->link = typetable[h];
+ typetable[h] = tn;
+ return &tn->type;
+}
+void type_init(int argc, char *argv[]) {
+ static int inited;
+ int i;
+
+ if (inited)
+ return;
+ inited = 1;
+ if (!IR)
+ return;
+ for (i = 1; i < argc; i++) {
+ int size, align, outofline;
+ if (strncmp(argv[i], "-unsigned_char=", 15) == 0)
+ IR->unsigned_char = argv[i][15] - '0';
+#define xx(name) \
+ else if (sscanf(argv[i], "-" #name "=%d,%d,%d", &size, &align, &outofline) == 3) { \
+ IR->name.size = size; IR->name.align = align; \
+ IR->name.outofline = outofline; }
+ xx(charmetric)
+ xx(shortmetric)
+ xx(intmetric)
+ xx(longmetric)
+ xx(longlongmetric)
+ xx(floatmetric)
+ xx(doublemetric)
+ xx(longdoublemetric)
+ xx(ptrmetric)
+ xx(structmetric)
+#undef xx
+ }
+#define xx(v,name,op,metrics) v=xxinit(op,name,IR->metrics)
+ xx(chartype, "char", IR->unsigned_char ? UNSIGNED : INT,charmetric);
+ xx(doubletype, "double", FLOAT, doublemetric);
+ xx(floattype, "float", FLOAT, floatmetric);
+ xx(inttype, "int", INT, intmetric);
+ xx(longdouble, "long double", FLOAT, longdoublemetric);
+ xx(longtype, "long int", INT, longmetric);
+ xx(longlong, "long long int", INT, longlongmetric);
+ xx(shorttype, "short", INT, shortmetric);
+ xx(signedchar, "signed char", INT, charmetric);
+ xx(unsignedchar, "unsigned char", UNSIGNED,charmetric);
+ xx(unsignedlong, "unsigned long", UNSIGNED,longmetric);
+ xx(unsignedshort, "unsigned short", UNSIGNED,shortmetric);
+ xx(unsignedtype, "unsigned int", UNSIGNED,intmetric);
+ xx(unsignedlonglong,"unsigned long long",UNSIGNED,longlongmetric);
+#undef xx
+ {
+ Symbol p;
+ p = install(string("void"), &types, GLOBAL, PERM);
+ voidtype = type(VOID, NULL, 0, 0, p);
+ p->type = voidtype;
+ }
+ pointersym = install(string("T*"), &types, GLOBAL, PERM);
+ pointersym->addressed = IR->ptrmetric.outofline;
+ pointersym->u.limits.max.p = (void*)ones(8*IR->ptrmetric.size);
+ pointersym->u.limits.min.p = 0;
+ voidptype = ptr(voidtype);
+ funcptype = ptr(func(voidtype, NULL, 1));
+ charptype = ptr(chartype);
+#define xx(v,t) if (v==NULL && t->size==voidptype->size && t->align==voidptype->align) v=t
+ xx(unsignedptr,unsignedshort);
+ xx(unsignedptr,unsignedtype);
+ xx(unsignedptr,unsignedlong);
+ xx(unsignedptr,unsignedlonglong);
+ if (unsignedptr == NULL)
+ unsignedptr = type(UNSIGNED, NULL, voidptype->size, voidptype->align, voidptype->u.sym);
+ xx(signedptr,shorttype);
+ xx(signedptr,inttype);
+ xx(signedptr,longtype);
+ xx(signedptr,longlong);
+ if (signedptr == NULL)
+ signedptr = type(INT, NULL, voidptype->size, voidptype->align, voidptype->u.sym);
+#undef xx
+ widechar = unsignedshort;
+ for (i = 0; i < argc; i++) {
+#define xx(name,type) \
+ if (strcmp(argv[i], "-wchar_t=" #name) == 0) \
+ widechar = type;
+ xx(unsigned_char,unsignedchar)
+ xx(unsigned_int,unsignedtype)
+ xx(unsigned_short,unsignedshort)
+ }
+#undef xx
+}
+void rmtypes(int lev) {
+ if (maxlevel >= lev) {
+ int i;
+ maxlevel = 0;
+ for (i = 0; i < NELEMS(typetable); i++) {
+ struct entry *tn, **tq = &typetable[i];
+ while ((tn = *tq) != NULL)
+ if (tn->type.op == FUNCTION)
+ tq = &tn->link;
+ else if (tn->type.u.sym && tn->type.u.sym->scope >= lev)
+ *tq = tn->link;
+ else {
+ if (tn->type.u.sym && tn->type.u.sym->scope > maxlevel)
+ maxlevel = tn->type.u.sym->scope;
+ tq = &tn->link;
+ }
+
+ }
+ }
+}
+Type ptr(Type ty) {
+ return type(POINTER, ty, IR->ptrmetric.size,
+ IR->ptrmetric.align, pointersym);
+}
+Type deref(Type ty) {
+ if (isptr(ty))
+ ty = ty->type;
+ else
+ error("type error: %s\n", "pointer expected");
+ return isenum(ty) ? unqual(ty)->type : ty;
+}
+Type array(Type ty, int n, int a) {
+ assert(ty);
+ if (isfunc(ty)) {
+ error("illegal type `array of %t'\n", ty);
+ return array(inttype, n, 0);
+ }
+ if (isarray(ty) && ty->size == 0)
+ error("missing array size\n");
+ if (ty->size == 0) {
+ if (unqual(ty) == voidtype)
+ error("illegal type `array of %t'\n", ty);
+ else if (Aflag >= 2)
+ warning("declaring type array of %t' is undefined\n", ty);
+
+ } else if (n > INT_MAX/ty->size) {
+ error("size of `array of %t' exceeds %d bytes\n",
+ ty, INT_MAX);
+ n = 1;
+ }
+ return type(ARRAY, ty, n*ty->size,
+ a ? a : ty->align, NULL);
+}
+Type atop(Type ty) {
+ if (isarray(ty))
+ return ptr(ty->type);
+ error("type error: %s\n", "array expected");
+ return ptr(ty);
+}
+Type qual(int op, Type ty) {
+ if (isarray(ty))
+ ty = type(ARRAY, qual(op, ty->type), ty->size,
+ ty->align, NULL);
+ else if (isfunc(ty))
+ warning("qualified function type ignored\n");
+ else if (isconst(ty) && op == CONST
+ || isvolatile(ty) && op == VOLATILE)
+ error("illegal type `%k %t'\n", op, ty);
+ else {
+ if (isqual(ty)) {
+ op += ty->op;
+ ty = ty->type;
+ }
+ ty = type(op, ty, ty->size, ty->align, NULL);
+ }
+ return ty;
+}
+Type func(Type ty, Type *proto, int style) {
+ if (ty && (isarray(ty) || isfunc(ty)))
+ error("illegal return type `%t'\n", ty);
+ ty = type(FUNCTION, ty, 0, 0, NULL);
+ ty->u.f.proto = proto;
+ ty->u.f.oldstyle = style;
+ return ty;
+}
+Type freturn(Type ty) {
+ if (isfunc(ty))
+ return ty->type;
+ error("type error: %s\n", "function expected");
+ return inttype;
+}
+int variadic(Type ty) {
+ if (isfunc(ty) && ty->u.f.proto) {
+ int i;
+ for (i = 0; ty->u.f.proto[i]; i++)
+ ;
+ return i > 1 && ty->u.f.proto[i-1] == voidtype;
+ }
+ return 0;
+}
+Type newstruct(int op, char *tag) {
+ Symbol p;
+
+ assert(tag);
+ if (*tag == 0)
+ tag = stringd(genlabel(1));
+ else
+ if ((p = lookup(tag, types)) != NULL && (p->scope == level
+ || p->scope == PARAM && level == PARAM+1)) {
+ if (p->type->op == op && !p->defined)
+ return p->type;
+ error("redefinition of `%s' previously defined at %w\n",
+ p->name, &p->src);
+ }
+ p = install(tag, &types, level, PERM);
+ p->type = type(op, NULL, 0, 0, p);
+ if (p->scope > maxlevel)
+ maxlevel = p->scope;
+ p->src = src;
+ return p->type;
+}
+Field newfield(char *name, Type ty, Type fty) {
+ Field p, *q = &ty->u.sym->u.s.flist;
+
+ if (name == NULL)
+ name = stringd(genlabel(1));
+ for (p = *q; p; q = &p->link, p = *q)
+ if (p->name == name)
+ error("duplicate field name `%s' in `%t'\n",
+ name, ty);
+ NEW0(p, PERM);
+ *q = p;
+ p->name = name;
+ p->type = fty;
+ if (xref) { /* omit */
+ if (ty->u.sym->u.s.ftab == NULL) /* omit */
+ ty->u.sym->u.s.ftab = table(NULL, level); /* omit */
+ install(name, &ty->u.sym->u.s.ftab, 0, PERM)->src = src;/* omit */
+ } /* omit */
+ return p;
+}
+int eqtype(Type ty1, Type ty2, int ret) {
+ if (ty1 == ty2)
+ return 1;
+ if (ty1->op != ty2->op)
+ return 0;
+ switch (ty1->op) {
+ case ENUM: case UNION: case STRUCT:
+ case UNSIGNED: case INT: case FLOAT:
+ return 0;
+ case POINTER: return eqtype(ty1->type, ty2->type, 1);
+ case VOLATILE: case CONST+VOLATILE:
+ case CONST: return eqtype(ty1->type, ty2->type, 1);
+ case ARRAY: if (eqtype(ty1->type, ty2->type, 1)) {
+ if (ty1->size == ty2->size)
+ return 1;
+ if (ty1->size == 0 || ty2->size == 0)
+ return ret;
+ }
+ return 0;
+ case FUNCTION: if (eqtype(ty1->type, ty2->type, 1)) {
+ Type *p1 = ty1->u.f.proto, *p2 = ty2->u.f.proto;
+ if (p1 == p2)
+ return 1;
+ if (p1 && p2) {
+ for ( ; *p1 && *p2; p1++, p2++)
+ if (eqtype(unqual(*p1), unqual(*p2), 1) == 0)
+ return 0;
+ if (*p1 == NULL && *p2 == NULL)
+ return 1;
+ } else {
+ if (variadic(p1 ? ty1 : ty2))
+ return 0;
+ if (p1 == NULL)
+ p1 = p2;
+ for ( ; *p1; p1++) {
+ Type ty = unqual(*p1);
+ if (promote(ty) != (isenum(ty) ? ty->type : ty))
+ return 0;
+ }
+ return 1;
+ }
+ }
+ return 0;
+ }
+ assert(0); return 0;
+}
+Type promote(Type ty) {
+ ty = unqual(ty);
+ switch (ty->op) {
+ case ENUM:
+ return inttype;
+ case INT:
+ if (ty->size < inttype->size)
+ return inttype;
+ break;
+ case UNSIGNED:
+ if (ty->size < inttype->size)
+ return inttype;
+ if (ty->size < unsignedtype->size)
+ return unsignedtype;
+ break;
+ case FLOAT:
+ if (ty->size < doubletype->size)
+ return doubletype;
+ }
+ return ty;
+}
+Type signedint(Type ty) {
+ if (ty->op == INT)
+ return ty;
+ assert(ty->op == UNSIGNED);
+#define xx(t) if (ty->size == t->size) return t
+ xx(inttype);
+ xx(longtype);
+ xx(longlong);
+#undef xx
+ assert(0); return NULL;
+}
+Type compose(Type ty1, Type ty2) {
+ if (ty1 == ty2)
+ return ty1;
+ assert(ty1->op == ty2->op);
+ switch (ty1->op) {
+ case POINTER:
+ return ptr(compose(ty1->type, ty2->type));
+ case CONST+VOLATILE:
+ return qual(CONST, qual(VOLATILE,
+ compose(ty1->type, ty2->type)));
+ case CONST: case VOLATILE:
+ return qual(ty1->op, compose(ty1->type, ty2->type));
+ case ARRAY: { Type ty = compose(ty1->type, ty2->type);
+ if (ty1->size && (ty1->type->size && ty2->size == 0 || ty1->size == ty2->size))
+ return array(ty, ty1->size/ty1->type->size, ty1->align);
+ if (ty2->size && ty2->type->size && ty1->size == 0)
+ return array(ty, ty2->size/ty2->type->size, ty2->align);
+ return array(ty, 0, 0); }
+ case FUNCTION: { Type *p1 = ty1->u.f.proto, *p2 = ty2->u.f.proto;
+ Type ty = compose(ty1->type, ty2->type);
+ List tlist = NULL;
+ if (p1 == NULL && p2 == NULL)
+ return func(ty, NULL, 1);
+ if (p1 && p2 == NULL)
+ return func(ty, p1, ty1->u.f.oldstyle);
+ if (p2 && p1 == NULL)
+ return func(ty, p2, ty2->u.f.oldstyle);
+ for ( ; *p1 && *p2; p1++, p2++) {
+ Type ty = compose(unqual(*p1), unqual(*p2));
+ if (isconst(*p1) || isconst(*p2))
+ ty = qual(CONST, ty);
+ if (isvolatile(*p1) || isvolatile(*p2))
+ ty = qual(VOLATILE, ty);
+ tlist = append(ty, tlist);
+ }
+ assert(*p1 == NULL && *p2 == NULL);
+ return func(ty, ltov(&tlist, PERM), 0); }
+ }
+ assert(0); return NULL;
+}
+int ttob(Type ty) {
+ switch (ty->op) {
+ case CONST: case VOLATILE: case CONST+VOLATILE:
+ return ttob(ty->type);
+ case VOID: case INT: case UNSIGNED: case FLOAT:
+ return ty->op + sizeop(ty->size);
+ case POINTER:
+ return POINTER + sizeop(voidptype->size);
+ case FUNCTION:
+ return POINTER + sizeop(funcptype->size);
+ case ARRAY: case STRUCT: case UNION:
+ return STRUCT;
+ case ENUM:
+ return INT + sizeop(inttype->size);
+ }
+ assert(0); return INT;
+}
+Type btot(int op, int size) {
+#define xx(ty) if (size == (ty)->size) return ty;
+ switch (optype(op)) {
+ case F:
+ xx(floattype);
+ xx(doubletype);
+ xx(longdouble);
+ assert(0); return 0;
+ case I:
+ if (chartype->op == INT)
+ xx(chartype);
+ xx(signedchar);
+ xx(shorttype);
+ xx(inttype);
+ xx(longtype);
+ xx(longlong);
+ assert(0); return 0;
+ case U:
+ if (chartype->op == UNSIGNED)
+ xx(chartype);
+ xx(unsignedchar);
+ xx(unsignedshort);
+ xx(unsignedtype);
+ xx(unsignedlong);
+ xx(unsignedlonglong);
+ assert(0); return 0;
+ case P:
+ xx(voidptype);
+ xx(funcptype);
+ assert(0); return 0;
+ }
+#undef xx
+ assert(0); return 0;
+}
+int hasproto(Type ty) {
+ if (ty == 0)
+ return 1;
+ switch (ty->op) {
+ case CONST: case VOLATILE: case CONST+VOLATILE: case POINTER:
+ case ARRAY:
+ return hasproto(ty->type);
+ case FUNCTION:
+ return hasproto(ty->type) && ty->u.f.proto;
+ case STRUCT: case UNION:
+ case VOID: case FLOAT: case ENUM: case INT: case UNSIGNED:
+ return 1;
+ }
+ assert(0); return 0;
+}
+/* fieldlist - construct a flat list of fields in type ty */
+Field fieldlist(Type ty) {
+ return ty->u.sym->u.s.flist;
+}
+
+/* fieldref - find field name of type ty, return entry */
+Field fieldref(const char *name, Type ty) {
+ Field p = isfield(name, unqual(ty)->u.sym->u.s.flist);
+
+ if (p && xref) {
+ Symbol q;
+ assert(unqual(ty)->u.sym->u.s.ftab);
+ q = lookup(name, unqual(ty)->u.sym->u.s.ftab);
+ assert(q);
+ use(q, src);
+ }
+ return p;
+}
+
+/* ftype - return a function type for rty function (ty,...)' */
+Type ftype(Type rty, Type ty) {
+ List list = append(ty, NULL);
+
+ list = append(voidtype, list);
+ return func(rty, ltov(&list, PERM), 0);
+}
+
+/* isfield - if name is a field in flist, return pointer to the field structure */
+static Field isfield(const char *name, Field flist) {
+ for ( ; flist; flist = flist->link)
+ if (flist->name == name)
+ break;
+ return flist;
+}
+
+/* outtype - output type ty */
+void outtype(Type ty, FILE *f) {
+ switch (ty->op) {
+ case CONST+VOLATILE: case CONST: case VOLATILE:
+ fprint(f, "%k %t", ty->op, ty->type);
+ break;
+ case STRUCT: case UNION: case ENUM:
+ assert(ty->u.sym);
+ if (ty->size == 0)
+ fprint(f, "incomplete ");
+ assert(ty->u.sym->name);
+ if (*ty->u.sym->name >= '1' && *ty->u.sym->name <= '9') {
+ Symbol p = findtype(ty);
+ if (p == 0)
+ fprint(f, "%k defined at %w", ty->op, &ty->u.sym->src);
+ else
+ fprint(f, p->name);
+ } else {
+ fprint(f, "%k %s", ty->op, ty->u.sym->name);
+ if (ty->size == 0)
+ fprint(f, " defined at %w", &ty->u.sym->src);
+ }
+ break;
+ case VOID: case FLOAT: case INT: case UNSIGNED:
+ fprint(f, ty->u.sym->name);
+ break;
+ case POINTER:
+ fprint(f, "pointer to %t", ty->type);
+ break;
+ case FUNCTION:
+ fprint(f, "%t function", ty->type);
+ if (ty->u.f.proto && ty->u.f.proto[0]) {
+ int i;
+ fprint(f, "(%t", ty->u.f.proto[0]);
+ for (i = 1; ty->u.f.proto[i]; i++)
+ if (ty->u.f.proto[i] == voidtype)
+ fprint(f, ",...");
+ else
+ fprint(f, ",%t", ty->u.f.proto[i]);
+ fprint(f, ")");
+ } else if (ty->u.f.proto && ty->u.f.proto[0] == 0)
+ fprint(f, "(void)");
+
+ break;
+ case ARRAY:
+ if (ty->size > 0 && ty->type && ty->type->size > 0) {
+ fprint(f, "array %d", ty->size/ty->type->size);
+ while (ty->type && isarray(ty->type) && ty->type->type->size > 0) {
+ ty = ty->type;
+ fprint(f, ",%d", ty->size/ty->type->size);
+ }
+ } else
+ fprint(f, "incomplete array");
+ if (ty->type)
+ fprint(f, " of %t", ty->type);
+ break;
+ default: assert(0);
+ }
+}
+
+/* printdecl - output a C declaration for symbol p of type ty */
+void printdecl(Symbol p, Type ty) {
+ switch (p->sclass) {
+ case AUTO:
+ fprint(stderr, "%s;\n", typestring(ty, p->name));
+ break;
+ case STATIC: case EXTERN:
+ fprint(stderr, "%k %s;\n", p->sclass, typestring(ty, p->name));
+ break;
+ case TYPEDEF: case ENUM:
+ break;
+ default: assert(0);
+ }
+}
+
+/* printproto - output a prototype declaration for function p */
+void printproto(Symbol p, Symbol callee[]) {
+ if (p->type->u.f.proto)
+ printdecl(p, p->type);
+ else {
+ int i;
+ List list = 0;
+ if (callee[0] == 0)
+ list = append(voidtype, list);
+ else
+ for (i = 0; callee[i]; i++)
+ list = append(callee[i]->type, list);
+ printdecl(p, func(freturn(p->type), ltov(&list, PERM), 0));
+ }
+}
+
+/* prtype - print details of type ty on f with given indent */
+static void prtype(Type ty, FILE *f, int indent, unsigned mark) {
+ switch (ty->op) {
+ default:
+ fprint(f, "(%d %d %d [%p])", ty->op, ty->size, ty->align, ty->u.sym);
+ break;
+ case FLOAT: case INT: case UNSIGNED: case VOID:
+ fprint(f, "(%k %d %d [\"%s\"])", ty->op, ty->size, ty->align, ty->u.sym->name);
+ break;
+ case CONST+VOLATILE: case CONST: case VOLATILE: case POINTER: case ARRAY:
+ fprint(f, "(%k %d %d ", ty->op, ty->size, ty->align);
+ prtype(ty->type, f, indent+1, mark);
+ fprint(f, ")");
+ break;
+ case STRUCT: case UNION:
+ fprint(f, "(%k %d %d [\"%s\"]", ty->op, ty->size, ty->align, ty->u.sym->name);
+ if (ty->x.marked != mark) {
+ Field p;
+ ty->x.marked = mark;
+ for (p = ty->u.sym->u.s.flist; p; p = p->link) {
+ fprint(f, "\n%I", indent+1);
+ prtype(p->type, f, indent+1, mark);
+ fprint(f, " %s@%d", p->name, p->offset);
+ if (p->lsb)
+ fprint(f, ":%d..%d",
+ fieldsize(p) + fieldright(p), fieldright(p));
+ }
+ fprint(f, "\n%I", indent);
+ }
+ fprint(f, ")");
+ break;
+ case ENUM:
+ fprint(f, "(%k %d %d [\"%s\"]", ty->op, ty->size, ty->align, ty->u.sym->name);
+ if (ty->x.marked != mark) {
+ int i;
+ Symbol *p = ty->u.sym->u.idlist;
+ ty->x.marked = mark;
+ for (i = 0; p[i] != NULL; i++)
+ fprint(f, "%I%s=%d\n", indent+1, p[i]->name, p[i]->u.value);
+ }
+ fprint(f, ")");
+ break;
+ case FUNCTION:
+ fprint(f, "(%k %d %d ", ty->op, ty->size, ty->align);
+ prtype(ty->type, f, indent+1, mark);
+ if (ty->u.f.proto) {
+ int i;
+ fprint(f, "\n%I{", indent+1);
+ for (i = 0; ty->u.f.proto[i]; i++) {
+ if (i > 0)
+ fprint(f, "%I", indent+2);
+ prtype(ty->u.f.proto[i], f, indent+2, mark);
+ fprint(f, "\n");
+ }
+ fprint(f, "%I}", indent+1);
+ }
+ fprint(f, ")");
+ break;
+ }
+}
+
+/* printtype - print details of type ty on fd */
+void printtype(Type ty, int fd) {
+ static unsigned mark;
+ prtype(ty, fd == 1 ? stdout : stderr, 0, ++mark);
+ fprint(fd == 1 ? stdout : stderr, "\n");
+}
+
+/* typestring - return ty as C declaration for str, which may be "" */
+char *typestring(Type ty, char *str) {
+ for ( ; ty; ty = ty->type) {
+ Symbol p;
+ switch (ty->op) {
+ case CONST+VOLATILE: case CONST: case VOLATILE:
+ if (isptr(ty->type))
+ str = stringf("%k %s", ty->op, str);
+ else
+ return stringf("%k %s", ty->op, typestring(ty->type, str));
+ break;
+ case STRUCT: case UNION: case ENUM:
+ assert(ty->u.sym);
+ if ((p = findtype(ty)) != NULL)
+ return *str ? stringf("%s %s", p->name, str) : p->name;
+ if (*ty->u.sym->name >= '1' && *ty->u.sym->name <= '9')
+ warning("unnamed %k in prototype\n", ty->op);
+ if (*str)
+ return stringf("%k %s %s", ty->op, ty->u.sym->name, str);
+ else
+ return stringf("%k %s", ty->op, ty->u.sym->name);
+ case VOID: case FLOAT: case INT: case UNSIGNED:
+ return *str ? stringf("%s %s", ty->u.sym->name, str) : ty->u.sym->name;
+ case POINTER:
+ if (!ischar(ty->type) && (p = findtype(ty)) != NULL)
+ return *str ? stringf("%s %s", p->name, str) : p->name;
+ str = stringf(isarray(ty->type) || isfunc(ty->type) ? "(*%s)" : "*%s", str);
+ break;
+ case FUNCTION:
+ if ((p = findtype(ty)) != NULL)
+ return *str ? stringf("%s %s", p->name, str) : p->name;
+ if (ty->u.f.proto == 0)
+ str = stringf("%s()", str);
+ else if (ty->u.f.proto[0]) {
+ int i;
+ str = stringf("%s(%s", str, typestring(ty->u.f.proto[0], ""));
+ for (i = 1; ty->u.f.proto[i]; i++)
+ if (ty->u.f.proto[i] == voidtype)
+ str = stringf("%s, ...", str);
+ else
+ str = stringf("%s, %s", str, typestring(ty->u.f.proto[i], ""));
+ str = stringf("%s)", str);
+ } else
+ str = stringf("%s(void)", str);
+ break;
+ case ARRAY:
+ if ((p = findtype(ty)) != NULL)
+ return *str ? stringf("%s %s", p->name, str) : p->name;
+ if (ty->type && ty->type->size > 0)
+ str = stringf("%s[%d]", str, ty->size/ty->type->size);
+ else
+ str = stringf("%s[]", str);
+ break;
+ default: assert(0);
+ }
+ }
+ assert(0); return 0;
+}
+
diff --git a/lcc/src/x86.md b/lcc/src/x86.md
new file mode 100755
index 0000000..7e8b84f
--- /dev/null
+++ b/lcc/src/x86.md
@@ -0,0 +1,998 @@
+%{
+enum { EAX=0, ECX=1, EDX=2, EBX=3, ESI=6, EDI=7 };
+#include "c.h"
+#define NODEPTR_TYPE Node
+#define OP_LABEL(p) ((p)->op)
+#define LEFT_CHILD(p) ((p)->kids[0])
+#define RIGHT_CHILD(p) ((p)->kids[1])
+#define STATE_LABEL(p) ((p)->x.state)
+static void address(Symbol, Symbol, long);
+static void blkfetch(int, int, int, int);
+static void blkloop(int, int, int, int, int, int[]);
+static void blkstore(int, int, int, int);
+static void defaddress(Symbol);
+static void defconst(int, int, Value);
+static void defstring(int, char *);
+static void defsymbol(Symbol);
+static void doarg(Node);
+static void emit2(Node);
+static void export(Symbol);
+static void clobber(Node);
+static void function(Symbol, Symbol [], Symbol [], int);
+static void global(Symbol);
+static void import(Symbol);
+static void local(Symbol);
+static void progbeg(int, char **);
+static void progend(void);
+static void segment(int);
+static void space(int);
+static void target(Node);
+extern int ckstack(Node, int);
+extern int memop(Node);
+extern int sametree(Node, Node);
+static Symbol charreg[32], shortreg[32], intreg[32];
+static Symbol fltreg[32];
+
+static Symbol charregw, shortregw, intregw, fltregw;
+
+static int cseg;
+
+static Symbol quo, rem;
+
+%}
+%start stmt
+%term CNSTF4=4113
+%term CNSTF8=8209
+%term CNSTF16=16401
+%term CNSTI1=1045
+%term CNSTI2=2069
+%term CNSTI4=4117
+%term CNSTI8=8213
+%term CNSTP4=4119
+%term CNSTP8=8215
+%term CNSTU1=1046
+%term CNSTU2=2070
+%term CNSTU4=4118
+%term CNSTU8=8214
+
+%term ARGB=41
+%term ARGF4=4129
+%term ARGF8=8225
+%term ARGF16=16417
+%term ARGI4=4133
+%term ARGI8=8229
+%term ARGP4=4135
+%term ARGP8=8231
+%term ARGU4=4134
+%term ARGU8=8230
+
+%term ASGNB=57
+%term ASGNF4=4145
+%term ASGNF8=8241
+%term ASGNF16=16433
+%term ASGNI1=1077
+%term ASGNI2=2101
+%term ASGNI4=4149
+%term ASGNI8=8245
+%term ASGNP4=4151
+%term ASGNP8=8247
+%term ASGNU1=1078
+%term ASGNU2=2102
+%term ASGNU4=4150
+%term ASGNU8=8246
+
+%term INDIRB=73
+%term INDIRF4=4161
+%term INDIRF8=8257
+%term INDIRF16=16449
+%term INDIRI1=1093
+%term INDIRI2=2117
+%term INDIRI4=4165
+%term INDIRI8=8261
+%term INDIRP4=4167
+%term INDIRP8=8263
+%term INDIRU1=1094
+%term INDIRU2=2118
+%term INDIRU4=4166
+%term INDIRU8=8262
+
+%term CVFF4=4209
+%term CVFF8=8305
+%term CVFF16=16497
+%term CVFI4=4213
+%term CVFI8=8309
+
+%term CVIF4=4225
+%term CVIF8=8321
+%term CVIF16=16513
+%term CVII1=1157
+%term CVII2=2181
+%term CVII4=4229
+%term CVII8=8325
+%term CVIU1=1158
+%term CVIU2=2182
+%term CVIU4=4230
+%term CVIU8=8326
+
+%term CVPP4=4247
+%term CVPP8=8343
+%term CVPP16=16535
+%term CVPU4=4246
+%term CVPU8=8342
+
+%term CVUI1=1205
+%term CVUI2=2229
+%term CVUI4=4277
+%term CVUI8=8373
+%term CVUP4=4279
+%term CVUP8=8375
+%term CVUP16=16567
+%term CVUU1=1206
+%term CVUU2=2230
+%term CVUU4=4278
+%term CVUU8=8374
+
+%term NEGF4=4289
+%term NEGF8=8385
+%term NEGF16=16577
+%term NEGI4=4293
+%term NEGI8=8389
+
+%term CALLB=217
+%term CALLF4=4305
+%term CALLF8=8401
+%term CALLF16=16593
+%term CALLI4=4309
+%term CALLI8=8405
+%term CALLP4=4311
+%term CALLP8=8407
+%term CALLU4=4310
+%term CALLU8=8406
+%term CALLV=216
+
+%term RETF4=4337
+%term RETF8=8433
+%term RETF16=16625
+%term RETI4=4341
+%term RETI8=8437
+%term RETP4=4343
+%term RETP8=8439
+%term RETU4=4342
+%term RETU8=8438
+%term RETV=248
+
+%term ADDRGP4=4359
+%term ADDRGP8=8455
+
+%term ADDRFP4=4375
+%term ADDRFP8=8471
+
+%term ADDRLP4=4391
+%term ADDRLP8=8487
+
+%term ADDF4=4401
+%term ADDF8=8497
+%term ADDF16=16689
+%term ADDI4=4405
+%term ADDI8=8501
+%term ADDP4=4407
+%term ADDP8=8503
+%term ADDU4=4406
+%term ADDU8=8502
+
+%term SUBF4=4417
+%term SUBF8=8513
+%term SUBF16=16705
+%term SUBI4=4421
+%term SUBI8=8517
+%term SUBP4=4423
+%term SUBP8=8519
+%term SUBU4=4422
+%term SUBU8=8518
+
+%term LSHI4=4437
+%term LSHI8=8533
+%term LSHU4=4438
+%term LSHU8=8534
+
+%term MODI4=4453
+%term MODI8=8549
+%term MODU4=4454
+%term MODU8=8550
+
+%term RSHI4=4469
+%term RSHI8=8565
+%term RSHU4=4470
+%term RSHU8=8566
+
+%term BANDI4=4485
+%term BANDI8=8581
+%term BANDU4=4486
+%term BANDU8=8582
+
+%term BCOMI4=4501
+%term BCOMI8=8597
+%term BCOMU4=4502
+%term BCOMU8=8598
+
+%term BORI4=4517
+%term BORI8=8613
+%term BORU4=4518
+%term BORU8=8614
+
+%term BXORI4=4533
+%term BXORI8=8629
+%term BXORU4=4534
+%term BXORU8=8630
+
+%term DIVF4=4545
+%term DIVF8=8641
+%term DIVF16=16833
+%term DIVI4=4549
+%term DIVI8=8645
+%term DIVU4=4550
+%term DIVU8=8646
+
+%term MULF4=4561
+%term MULF8=8657
+%term MULF16=16849
+%term MULI4=4565
+%term MULI8=8661
+%term MULU4=4566
+%term MULU8=8662
+
+%term EQF4=4577
+%term EQF8=8673
+%term EQF16=16865
+%term EQI4=4581
+%term EQI8=8677
+%term EQU4=4582
+%term EQU8=8678
+
+%term GEF4=4593
+%term GEF8=8689
+%term GEI4=4597
+%term GEI8=8693
+%term GEI16=16885
+%term GEU4=4598
+%term GEU8=8694
+
+%term GTF4=4609
+%term GTF8=8705
+%term GTF16=16897
+%term GTI4=4613
+%term GTI8=8709
+%term GTU4=4614
+%term GTU8=8710
+
+%term LEF4=4625
+%term LEF8=8721
+%term LEF16=16913
+%term LEI4=4629
+%term LEI8=8725
+%term LEU4=4630
+%term LEU8=8726
+
+%term LTF4=4641
+%term LTF8=8737
+%term LTF16=16929
+%term LTI4=4645
+%term LTI8=8741
+%term LTU4=4646
+%term LTU8=8742
+
+%term NEF4=4657
+%term NEF8=8753
+%term NEF16=16945
+%term NEI4=4661
+%term NEI8=8757
+%term NEU4=4662
+%term NEU8=8758
+
+%term JUMPV=584
+
+%term LABELV=600
+
+%term LOADB=233
+%term LOADF4=4321
+%term LOADF8=8417
+%term LOADF16=16609
+%term LOADI1=1253
+%term LOADI2=2277
+%term LOADI4=4325
+%term LOADI8=8421
+%term LOADP4=4327
+%term LOADP8=8423
+%term LOADU1=1254
+%term LOADU2=2278
+%term LOADU4=4326
+%term LOADU8=8422
+
+%term VREGP=711
+%%
+reg: INDIRI1(VREGP) "# read register\n"
+reg: INDIRU1(VREGP) "# read register\n"
+
+reg: INDIRI2(VREGP) "# read register\n"
+reg: INDIRU2(VREGP) "# read register\n"
+
+reg: INDIRF4(VREGP) "# read register\n"
+reg: INDIRI4(VREGP) "# read register\n"
+reg: INDIRP4(VREGP) "# read register\n"
+reg: INDIRU4(VREGP) "# read register\n"
+
+reg: INDIRF8(VREGP) "# read register\n"
+reg: INDIRI8(VREGP) "# read register\n"
+reg: INDIRP8(VREGP) "# read register\n"
+reg: INDIRU8(VREGP) "# read register\n"
+
+stmt: ASGNI1(VREGP,reg) "# write register\n"
+stmt: ASGNU1(VREGP,reg) "# write register\n"
+
+stmt: ASGNI2(VREGP,reg) "# write register\n"
+stmt: ASGNU2(VREGP,reg) "# write register\n"
+
+stmt: ASGNF4(VREGP,reg) "# write register\n"
+stmt: ASGNI4(VREGP,reg) "# write register\n"
+stmt: ASGNP4(VREGP,reg) "# write register\n"
+stmt: ASGNU4(VREGP,reg) "# write register\n"
+
+stmt: ASGNF8(VREGP,reg) "# write register\n"
+stmt: ASGNI8(VREGP,reg) "# write register\n"
+stmt: ASGNP8(VREGP,reg) "# write register\n"
+stmt: ASGNU8(VREGP,reg) "# write register\n"
+con: CNSTI1 "%a"
+con: CNSTU1 "%a"
+
+con: CNSTI2 "%a"
+con: CNSTU2 "%a"
+
+con: CNSTI4 "%a"
+con: CNSTU4 "%a"
+con: CNSTP4 "%a"
+
+con: CNSTI8 "%a"
+con: CNSTU8 "%a"
+con: CNSTP8 "%a"
+stmt: reg ""
+acon: ADDRGP4 "(%a)"
+acon: con "(%0)"
+base: ADDRGP4 "(%a)"
+base: reg "[%0]"
+base: ADDI4(reg,acon) "%1[%0]"
+base: ADDP4(reg,acon) "%1[%0]"
+base: ADDU4(reg,acon) "%1[%0]"
+base: ADDRFP4 "(%a)[ebp]"
+base: ADDRLP4 "(%a)[ebp]"
+index: reg "%0"
+index: LSHI4(reg,con1) "%0*2"
+index: LSHI4(reg,con2) "%0*4"
+index: LSHI4(reg,con3) "%0*8"
+
+con1: CNSTI4 "1" range(a, 1, 1)
+con1: CNSTU4 "1" range(a, 1, 1)
+con2: CNSTI4 "2" range(a, 2, 2)
+con2: CNSTU4 "2" range(a, 2, 2)
+con3: CNSTI4 "3" range(a, 3, 3)
+con3: CNSTU4 "3" range(a, 3, 3)
+index: LSHU4(reg,con1) "%0*2"
+index: LSHU4(reg,con2) "%0*4"
+index: LSHU4(reg,con3) "%0*8"
+addr: base "%0"
+addr: ADDI4(index,base) "%1[%0]"
+addr: ADDP4(index,base) "%1[%0]"
+addr: ADDU4(index,base) "%1[%0]"
+addr: index "[%0]"
+mem: INDIRI1(addr) "byte ptr %0"
+mem: INDIRI2(addr) "word ptr %0"
+mem: INDIRI4(addr) "dword ptr %0"
+mem: INDIRU1(addr) "byte ptr %0"
+mem: INDIRU2(addr) "word ptr %0"
+mem: INDIRU4(addr) "dword ptr %0"
+mem: INDIRP4(addr) "dword ptr %0"
+rc: reg "%0"
+rc: con "%0"
+
+mr: reg "%0"
+mr: mem "%0"
+
+mrc0: mem "%0"
+mrc0: rc "%0"
+mrc1: mem "%0" 1
+mrc1: rc "%0"
+
+mrc3: mem "%0" 3
+mrc3: rc "%0"
+reg: addr "lea %c,%0\n" 1
+reg: mrc0 "mov %c,%0\n" 1
+reg: LOADI1(reg) "# move\n" 1
+reg: LOADI2(reg) "# move\n" 1
+reg: LOADI4(reg) "# move\n" move(a)
+reg: LOADU1(reg) "# move\n" 1
+reg: LOADU2(reg) "# move\n" 1
+reg: LOADU4(reg) "# move\n" move(a)
+reg: LOADP4(reg) "# move\n" move(a)
+reg: ADDI4(reg,mrc1) "?mov %c,%0\nadd %c,%1\n" 1
+reg: ADDP4(reg,mrc1) "?mov %c,%0\nadd %c,%1\n" 1
+reg: ADDU4(reg,mrc1) "?mov %c,%0\nadd %c,%1\n" 1
+reg: SUBI4(reg,mrc1) "?mov %c,%0\nsub %c,%1\n" 1
+reg: SUBP4(reg,mrc1) "?mov %c,%0\nsub %c,%1\n" 1
+reg: SUBU4(reg,mrc1) "?mov %c,%0\nsub %c,%1\n" 1
+reg: BANDI4(reg,mrc1) "?mov %c,%0\nand %c,%1\n" 1
+reg: BORI4(reg,mrc1) "?mov %c,%0\nor %c,%1\n" 1
+reg: BXORI4(reg,mrc1) "?mov %c,%0\nxor %c,%1\n" 1
+reg: BANDU4(reg,mrc1) "?mov %c,%0\nand %c,%1\n" 1
+reg: BORU4(reg,mrc1) "?mov %c,%0\nor %c,%1\n" 1
+reg: BXORU4(reg,mrc1) "?mov %c,%0\nxor %c,%1\n" 1
+stmt: ASGNI4(addr,ADDI4(mem,con1)) "inc %1\n" memop(a)
+stmt: ASGNI4(addr,ADDU4(mem,con1)) "inc %1\n" memop(a)
+stmt: ASGNP4(addr,ADDP4(mem,con1)) "inc %1\n" memop(a)
+stmt: ASGNI4(addr,SUBI4(mem,con1)) "dec %1\n" memop(a)
+stmt: ASGNI4(addr,SUBU4(mem,con1)) "dec %1\n" memop(a)
+stmt: ASGNP4(addr,SUBP4(mem,con1)) "dec %1\n" memop(a)
+stmt: ASGNI4(addr,ADDI4(mem,rc)) "add %1,%2\n" memop(a)
+stmt: ASGNI4(addr,SUBI4(mem,rc)) "sub %1,%2\n" memop(a)
+stmt: ASGNU4(addr,ADDU4(mem,rc)) "add %1,%2\n" memop(a)
+stmt: ASGNU4(addr,SUBU4(mem,rc)) "sub %1,%2\n" memop(a)
+
+stmt: ASGNI4(addr,BANDI4(mem,rc)) "and %1,%2\n" memop(a)
+stmt: ASGNI4(addr,BORI4(mem,rc)) "or %1,%2\n" memop(a)
+stmt: ASGNI4(addr,BXORI4(mem,rc)) "xor %1,%2\n" memop(a)
+stmt: ASGNU4(addr,BANDU4(mem,rc)) "and %1,%2\n" memop(a)
+stmt: ASGNU4(addr,BORU4(mem,rc)) "or %1,%2\n" memop(a)
+stmt: ASGNU4(addr,BXORU4(mem,rc)) "xor %1,%2\n" memop(a)
+reg: BCOMI4(reg) "?mov %c,%0\nnot %c\n" 2
+reg: BCOMU4(reg) "?mov %c,%0\nnot %c\n" 2
+reg: NEGI4(reg) "?mov %c,%0\nneg %c\n" 2
+
+stmt: ASGNI4(addr,BCOMI4(mem)) "not %1\n" memop(a)
+stmt: ASGNU4(addr,BCOMU4(mem)) "not %1\n" memop(a)
+stmt: ASGNI4(addr,NEGI4(mem)) "neg %1\n" memop(a)
+reg: LSHI4(reg,con5) "?mov %c,%0\nsal %c,%1\n" 2
+reg: LSHU4(reg,con5) "?mov %c,%0\nshl %c,%1\n" 2
+reg: RSHI4(reg,con5) "?mov %c,%0\nsar %c,%1\n" 2
+reg: RSHU4(reg,con5) "?mov %c,%0\nshr %c,%1\n" 2
+
+stmt: ASGNI4(addr,LSHI4(mem,con5)) "sal %1,%2\n" memop(a)
+stmt: ASGNI4(addr,LSHU4(mem,con5)) "shl %1,%2\n" memop(a)
+stmt: ASGNI4(addr,RSHI4(mem,con5)) "sar %1,%2\n" memop(a)
+stmt: ASGNI4(addr,RSHU4(mem,con5)) "shr %1,%2\n" memop(a)
+
+con5: CNSTI4 "%a" range(a, 0, 31)
+
+reg: LSHI4(reg,reg) "?mov %c,%0\nmov ecx,%1\nsal %c,cl\n" 3
+reg: LSHU4(reg,reg) "?mov %c,%0\nmov ecx,%1\nshl %c,cl\n" 2
+reg: RSHI4(reg,reg) "?mov %c,%0\nmov ecx,%1\nsar %c,cl\n" 2
+reg: RSHU4(reg,reg) "?mov %c,%0\nmov ecx,%1\nshr %c,cl\n" 2
+reg: MULI4(reg,mrc3) "?mov %c,%0\nimul %c,%1\n" 14
+reg: MULI4(con,mr) "imul %c,%1,%0\n" 13
+reg: MULU4(reg,mr) "mul %1\n" 13
+reg: DIVU4(reg,reg) "xor edx,edx\ndiv %1\n"
+reg: MODU4(reg,reg) "xor edx,edx\ndiv %1\n"
+reg: DIVI4(reg,reg) "cdq\nidiv %1\n"
+reg: MODI4(reg,reg) "cdq\nidiv %1\n"
+reg: CVPU4(reg) "mov %c,%0\n" move(a)
+reg: CVUP4(reg) "mov %c,%0\n" move(a)
+reg: CVII4(INDIRI1(addr)) "movsx %c,byte ptr %0\n" 3
+reg: CVII4(INDIRI2(addr)) "movsx %c,word ptr %0\n" 3
+reg: CVUU4(INDIRU1(addr)) "movzx %c,byte ptr %0\n" 3
+reg: CVUU4(INDIRU2(addr)) "movzx %c,word ptr %0\n" 3
+reg: CVII4(reg) "# extend\n" 3
+reg: CVIU4(reg) "# extend\n" 3
+reg: CVUI4(reg) "# extend\n" 3
+reg: CVUU4(reg) "# extend\n" 3
+
+reg: CVII1(reg) "# truncate\n" 1
+reg: CVII2(reg) "# truncate\n" 1
+reg: CVUU1(reg) "# truncate\n" 1
+reg: CVUU2(reg) "# truncate\n" 1
+stmt: ASGNI1(addr,rc) "mov byte ptr %0,%1\n" 1
+stmt: ASGNI2(addr,rc) "mov word ptr %0,%1\n" 1
+stmt: ASGNI4(addr,rc) "mov dword ptr %0,%1\n" 1
+stmt: ASGNU1(addr,rc) "mov byte ptr %0,%1\n" 1
+stmt: ASGNU2(addr,rc) "mov word ptr %0,%1\n" 1
+stmt: ASGNU4(addr,rc) "mov dword ptr %0,%1\n" 1
+stmt: ASGNP4(addr,rc) "mov dword ptr %0,%1\n" 1
+stmt: ARGI4(mrc3) "push %0\n" 1
+stmt: ARGU4(mrc3) "push %0\n" 1
+stmt: ARGP4(mrc3) "push %0\n" 1
+stmt: ASGNB(reg,INDIRB(reg)) "mov ecx,%a\nrep movsb\n"
+stmt: ARGB(INDIRB(reg)) "sub esp,%a\nmov edi,esp\nmov ecx,%a\nrep movsb\n"
+
+memf: INDIRF8(addr) "qword ptr %0"
+memf: INDIRF4(addr) "dword ptr %0"
+memf: CVFF8(INDIRF4(addr)) "dword ptr %0"
+reg: memf "fld %0\n" 3
+stmt: ASGNF8(addr,reg) "fstp qword ptr %0\n" 7
+stmt: ASGNF4(addr,reg) "fstp dword ptr %0\n" 7
+stmt: ASGNF4(addr,CVFF4(reg)) "fstp dword ptr %0\n" 7
+stmt: ARGF8(reg) "sub esp,8\nfstp qword ptr [esp]\n"
+stmt: ARGF4(reg) "sub esp,4\nfstp dword ptr [esp]\n"
+reg: NEGF8(reg) "fchs\n"
+reg: NEGF4(reg) "fchs\n"
+flt: memf " %0"
+flt: reg "p st(1),st"
+reg: ADDF8(reg,flt) "fadd%1\n"
+reg: ADDF4(reg,flt) "fadd%1\n"
+reg: DIVF8(reg,flt) "fdiv%1\n"
+reg: DIVF4(reg,flt) "fdiv%1\n"
+reg: MULF8(reg,flt) "fmul%1\n"
+reg: MULF4(reg,flt) "fmul%1\n"
+reg: SUBF8(reg,flt) "fsub%1\n"
+reg: SUBF4(reg,flt) "fsub%1\n"
+reg: CVFF8(reg) "# CVFF8\n"
+reg: CVFF4(reg) "sub esp,4\nfstp dword ptr 0[esp]\nfld dword ptr 0[esp]\nadd esp,4\n" 12
+
+reg: CVFI4(reg) "call __ftol\n" 31
+reg: CVIF8(INDIRI4(addr)) "fild dword ptr %0\n" 10
+reg: CVIF4(reg) "push %0\nfild dword ptr 0[esp]\nadd esp,4\n" 12
+
+reg: CVIF8(reg) "push %0\nfild dword ptr 0[esp]\nadd esp,4\n" 12
+
+addrj: ADDRGP4 "%a"
+addrj: reg "%0" 2
+addrj: mem "%0" 2
+
+stmt: JUMPV(addrj) "jmp %0\n" 3
+stmt: LABELV "%a:\n"
+stmt: EQI4(mem,rc) "cmp %0,%1\nje %a\n" 5
+stmt: GEI4(mem,rc) "cmp %0,%1\njge %a\n" 5
+stmt: GTI4(mem,rc) "cmp %0,%1\njg %a\n" 5
+stmt: LEI4(mem,rc) "cmp %0,%1\njle %a\n" 5
+stmt: LTI4(mem,rc) "cmp %0,%1\njl %a\n" 5
+stmt: NEI4(mem,rc) "cmp %0,%1\njne %a\n" 5
+stmt: GEU4(mem,rc) "cmp %0,%1\njae %a\n" 5
+stmt: GTU4(mem,rc) "cmp %0,%1\nja %a\n" 5
+stmt: LEU4(mem,rc) "cmp %0,%1\njbe %a\n" 5
+stmt: LTU4(mem,rc) "cmp %0,%1\njb %a\n" 5
+stmt: EQI4(reg,mrc1) "cmp %0,%1\nje %a\n" 4
+stmt: GEI4(reg,mrc1) "cmp %0,%1\njge %a\n" 4
+stmt: GTI4(reg,mrc1) "cmp %0,%1\njg %a\n" 4
+stmt: LEI4(reg,mrc1) "cmp %0,%1\njle %a\n" 4
+stmt: LTI4(reg,mrc1) "cmp %0,%1\njl %a\n" 4
+stmt: NEI4(reg,mrc1) "cmp %0,%1\njne %a\n" 4
+
+stmt: EQU4(reg,mrc1) "cmp %0,%1\nje %a\n" 4
+stmt: GEU4(reg,mrc1) "cmp %0,%1\njae %a\n" 4
+stmt: GTU4(reg,mrc1) "cmp %0,%1\nja %a\n" 4
+stmt: LEU4(reg,mrc1) "cmp %0,%1\njbe %a\n" 4
+stmt: LTU4(reg,mrc1) "cmp %0,%1\njb %a\n" 4
+stmt: NEU4(reg,mrc1) "cmp %0,%1\njne %a\n" 4
+cmpf: memf " %0"
+cmpf: reg "p"
+stmt: EQF8(cmpf,reg) "fcomp%0\nfstsw ax\nsahf\nje %a\n"
+stmt: GEF8(cmpf,reg) "fcomp%0\nfstsw ax\nsahf\njbe %a\n"
+stmt: GTF8(cmpf,reg) "fcomp%0\nfstsw ax\nsahf\njb %a\n"
+stmt: LEF8(cmpf,reg) "fcomp%0\nfstsw ax\nsahf\njae %a\n"
+stmt: LTF8(cmpf,reg) "fcomp%0\nfstsw ax\nsahf\nja %a\n"
+stmt: NEF8(cmpf,reg) "fcomp%0\nfstsw ax\nsahf\njne %a\n"
+
+stmt: EQF4(cmpf,reg) "fcomp%0\nfstsw ax\nsahf\nje %a\n"
+stmt: GEF4(cmpf,reg) "fcomp%0\nfstsw ax\nsahf\njbe %a\n"
+stmt: GTF4(cmpf,reg) "fcomp%0\nfstsw ax\nsahf\njb %a\n"
+stmt: LEF4(cmpf,reg) "fcomp%0\nfstsw ax\nsahf\njae %a\n"
+stmt: LTF4(cmpf,reg) "fcomp%0\nfstsw ax\nsahf\nja %a\n"
+stmt: NEF4(cmpf,reg) "fcomp%0\nfstsw ax\nsahf\njne %a\n"
+reg: CALLI4(addrj) "call %0\nadd esp,%a\n"
+reg: CALLU4(addrj) "call %0\nadd esp,%a\n"
+reg: CALLP4(addrj) "call %0\nadd esp,%a\n"
+stmt: CALLV(addrj) "call %0\nadd esp,%a\n"
+reg: CALLF4(addrj) "call %0\nadd esp,%a\n"
+reg: CALLF8(addrj) "call %0\nadd esp,%a\n"
+stmt: CALLF4(addrj) "call %0\nadd esp,%a\nfstp\n"
+stmt: CALLF8(addrj) "call %0\nadd esp,%a\nfstp\n"
+
+stmt: RETI4(reg) "# ret\n"
+stmt: RETU4(reg) "# ret\n"
+stmt: RETP4(reg) "# ret\n"
+stmt: RETF4(reg) "# ret\n"
+stmt: RETF8(reg) "# ret\n"
+%%
+static void progbeg(int argc, char *argv[]) {
+ int i;
+
+ {
+ union {
+ char c;
+ int i;
+ } u;
+ u.i = 0;
+ u.c = 1;
+ swap = ((int)(u.i == 1)) != IR->little_endian;
+ }
+ parseflags(argc, argv);
+ intreg[EAX] = mkreg("eax", EAX, 1, IREG);
+ intreg[EDX] = mkreg("edx", EDX, 1, IREG);
+ intreg[ECX] = mkreg("ecx", ECX, 1, IREG);
+ intreg[EBX] = mkreg("ebx", EBX, 1, IREG);
+ intreg[ESI] = mkreg("esi", ESI, 1, IREG);
+ intreg[EDI] = mkreg("edi", EDI, 1, IREG);
+
+ shortreg[EAX] = mkreg("ax", EAX, 1, IREG);
+ shortreg[ECX] = mkreg("cx", ECX, 1, IREG);
+ shortreg[EDX] = mkreg("dx", EDX, 1, IREG);
+ shortreg[EBX] = mkreg("bx", EBX, 1, IREG);
+ shortreg[ESI] = mkreg("si", ESI, 1, IREG);
+ shortreg[EDI] = mkreg("di", EDI, 1, IREG);
+
+ charreg[EAX] = mkreg("al", EAX, 1, IREG);
+ charreg[ECX] = mkreg("cl", ECX, 1, IREG);
+ charreg[EDX] = mkreg("dl", EDX, 1, IREG);
+ charreg[EBX] = mkreg("bl", EBX, 1, IREG);
+ for (i = 0; i < 8; i++)
+ fltreg[i] = mkreg("%d", i, 0, FREG);
+ charregw = mkwildcard(charreg);
+ shortregw = mkwildcard(shortreg);
+ intregw = mkwildcard(intreg);
+ fltregw = mkwildcard(fltreg);
+
+ tmask[IREG] = (1<<EDI) | (1<<ESI) | (1<<EBX)
+ | (1<<EDX) | (1<<ECX) | (1<<EAX);
+ vmask[IREG] = 0;
+ tmask[FREG] = 0xff;
+ vmask[FREG] = 0;
+ print(".486\n");
+ print(".model flat\n");
+ print("extrn __fltused:near\n");
+ print("extrn __ftol:near\n");
+ cseg = 0;
+ quo = mkreg("eax", EAX, 1, IREG);
+ quo->x.regnode->mask |= 1<<EDX;
+ rem = mkreg("edx", EDX, 1, IREG);
+ rem->x.regnode->mask |= 1<<EAX;
+}
+static Symbol rmap(int opk) {
+ switch (optype(opk)) {
+ case B: case P:
+ return intregw;
+ case I: case U:
+ if (opsize(opk) == 1)
+ return charregw;
+ else if (opsize(opk) == 2)
+ return shortregw;
+ else
+ return intregw;
+ case F:
+ return fltregw;
+ default:
+ return 0;
+ }
+}
+static void segment(int n) {
+ if (n == cseg)
+ return;
+ if (cseg == CODE || cseg == LIT)
+ print("_TEXT ends\n");
+ else if (cseg == DATA || cseg == BSS)
+ print("_DATA ends\n");
+ cseg = n;
+ if (cseg == CODE || cseg == LIT)
+ print("_TEXT segment\n");
+ else if (cseg == DATA || cseg == BSS)
+ print("_DATA segment\n");
+}
+static void progend(void) {
+ segment(0);
+ print("end\n");
+}
+static void target(Node p) {
+ assert(p);
+ switch (specific(p->op)) {
+ case MUL+U:
+ setreg(p, quo);
+ rtarget(p, 0, intreg[EAX]);
+ break;
+ case DIV+I: case DIV+U:
+ setreg(p, quo);
+ rtarget(p, 0, quo);
+ break;
+ case MOD+I: case MOD+U:
+ setreg(p, rem);
+ rtarget(p, 0, quo);
+ break;
+ case ASGN+B:
+ rtarget(p, 0, intreg[EDI]);
+ rtarget(p->kids[1], 0, intreg[ESI]);
+ break;
+ case ARG+B:
+ rtarget(p->kids[0], 0, intreg[ESI]);
+ break;
+ case CVF+I:
+ setreg(p, intreg[EAX]);
+ break;
+ case CALL+I: case CALL+U: case CALL+P: case CALL+V:
+ setreg(p, intreg[EAX]);
+ break;
+ case RET+I: case RET+U: case RET+P:
+ rtarget(p, 0, intreg[EAX]);
+ break;
+ }
+}
+
+static void clobber(Node p) {
+ static int nstack = 0;
+
+ assert(p);
+ nstack = ckstack(p, nstack);
+ switch (specific(p->op)) {
+ case RSH+I: case RSH+U: case LSH+I: case LSH+U:
+ if (generic(p->kids[1]->op) != CNST
+ && !( generic(p->kids[1]->op) == INDIR
+ && specific(p->kids[1]->kids[0]->op) == VREG+P
+ && p->kids[1]->syms[RX]->u.t.cse
+ && generic(p->kids[1]->syms[RX]->u.t.cse->op) == CNST
+)) {
+ spill(1<<ECX, 1, p);
+ }
+ break;
+ case ASGN+B: case ARG+B:
+ spill(1<<ECX | 1<<ESI | 1<<EDI, IREG, p);
+ break;
+ case EQ+F: case LE+F: case GE+F: case LT+F: case GT+F: case NE+F:
+ spill(1<<EAX, IREG, p);
+ break;
+ case CALL+F:
+ spill(1<<EDX | 1<<EAX | 1<<ECX, IREG, p);
+ break;
+ case CALL+I: case CALL+U: case CALL+P: case CALL+V:
+ spill(1<<EDX | 1<<ECX, IREG, p);
+ break;
+ }
+}
+#define isfp(p) (optype((p)->op)==F)
+
+int ckstack(Node p, int n) {
+ int i;
+
+ for (i = 0; i < NELEMS(p->x.kids) && p->x.kids[i]; i++)
+ if (isfp(p->x.kids[i]))
+ n--;
+ if (isfp(p) && p->count > 0)
+ n++;
+ if (n > 8)
+ error("expression too complicated\n");
+ debug(fprint(stderr, "(ckstack(%x)=%d)\n", p, n));
+ assert(n >= 0);
+ return n;
+}
+int memop(Node p) {
+ assert(p);
+ assert(generic(p->op) == ASGN);
+ assert(p->kids[0]);
+ assert(p->kids[1]);
+ if (generic(p->kids[1]->kids[0]->op) == INDIR
+ && sametree(p->kids[0], p->kids[1]->kids[0]->kids[0]))
+ return 3;
+ else
+ return LBURG_MAX;
+}
+int sametree(Node p, Node q) {
+ return p == NULL && q == NULL
+ || p && q && p->op == q->op && p->syms[0] == q->syms[0]
+ && sametree(p->kids[0], q->kids[0])
+ && sametree(p->kids[1], q->kids[1]);
+}
+static void emit2(Node p) {
+ int op = specific(p->op);
+#define preg(f) ((f)[getregnum(p->x.kids[0])]->x.name)
+
+ if (op == CVI+I && opsize(p->op) == 4 && opsize(p->x.kids[0]->op) == 1)
+ print("movsx %s,%s\n", p->syms[RX]->x.name
+, preg(charreg));
+ else if (op == CVI+U && opsize(p->op) == 4 && opsize(p->x.kids[0]->op) == 1)
+ print("movsx %s,%s\n", p->syms[RX]->x.name
+, preg(charreg));
+ else if (op == CVI+I && opsize(p->op) == 4 && opsize(p->x.kids[0]->op) == 2)
+ print("movsx %s,%s\n", p->syms[RX]->x.name
+, preg(shortreg));
+ else if (op == CVI+U && opsize(p->op) == 4 && opsize(p->x.kids[0]->op) == 2)
+ print("movsx %s,%s\n", p->syms[RX]->x.name
+, preg(shortreg));
+
+ else if (op == CVU+I && opsize(p->op) == 4 && opsize(p->x.kids[0]->op) == 1)
+ print("movzx %s,%s\n", p->syms[RX]->x.name
+, preg(charreg));
+ else if (op == CVU+U && opsize(p->op) == 4 && opsize(p->x.kids[0]->op) == 1)
+ print("movzx %s,%s\n", p->syms[RX]->x.name
+, preg(charreg));
+ else if (op == CVU+I && opsize(p->op) == 4 && opsize(p->x.kids[0]->op) == 2)
+ print("movzx %s,%s\n", p->syms[RX]->x.name
+, preg(shortreg));
+ else if (op == CVU+U && opsize(p->op) == 4 && opsize(p->x.kids[0]->op) == 2)
+ print("movzx %s,%s\n", p->syms[RX]->x.name
+, preg(shortreg));
+ else if (generic(op) == CVI || generic(op) == CVU || generic(op) == LOAD) {
+ char *dst = intreg[getregnum(p)]->x.name;
+ char *src = preg(intreg);
+ assert(opsize(p->op) <= opsize(p->x.kids[0]->op));
+ if (dst != src)
+ print("mov %s,%s\n", dst, src);
+ }
+}
+
+static void doarg(Node p) {
+ assert(p && p->syms[0]);
+ mkactual(4, p->syms[0]->u.c.v.i);
+}
+static void blkfetch(int k, int off, int reg, int tmp) {}
+static void blkstore(int k, int off, int reg, int tmp) {}
+static void blkloop(int dreg, int doff, int sreg, int soff,
+ int size, int tmps[]) {}
+static void local(Symbol p) {
+ if (isfloat(p->type))
+ p->sclass = AUTO;
+ if (askregvar(p, (*IR->x.rmap)(ttob(p->type))) == 0)
+ mkauto(p);
+}
+static void function(Symbol f, Symbol caller[], Symbol callee[], int n) {
+ int i;
+
+ print("%s:\n", f->x.name);
+ print("push ebx\n");
+ print("push esi\n");
+ print("push edi\n");
+ print("push ebp\n");
+ print("mov ebp,esp\n");
+ usedmask[0] = usedmask[1] = 0;
+ freemask[0] = freemask[1] = ~(unsigned)0;
+ offset = 16 + 4;
+ for (i = 0; callee[i]; i++) {
+ Symbol p = callee[i];
+ Symbol q = caller[i];
+ assert(q);
+ p->x.offset = q->x.offset = offset;
+ p->x.name = q->x.name = stringf("%d", p->x.offset);
+ p->sclass = q->sclass = AUTO;
+ offset += roundup(q->type->size, 4);
+ }
+ assert(caller[i] == 0);
+ offset = maxoffset = 0;
+ gencode(caller, callee);
+ framesize = roundup(maxoffset, 4);
+ if (framesize > 0)
+ print("sub esp,%d\n", framesize);
+ emitcode();
+ print("mov esp,ebp\n");
+ print("pop ebp\n");
+ print("pop edi\n");
+ print("pop esi\n");
+ print("pop ebx\n");
+ print("ret\n");
+}
+static void defsymbol(Symbol p) {
+ if (p->scope >= LOCAL && p->sclass == STATIC)
+ p->x.name = stringf("L%d", genlabel(1));
+ else if (p->generated)
+ p->x.name = stringf("L%s", p->name);
+ else if (p->scope == GLOBAL || p->sclass == EXTERN)
+ p->x.name = stringf("_%s", p->name);
+ else if (p->scope == CONSTANTS
+ && (isint(p->type) || isptr(p->type))
+ && p->name[0] == '0' && p->name[1] == 'x')
+ p->x.name = stringf("0%sH", &p->name[2]);
+ else
+ p->x.name = p->name;
+}
+static void address(Symbol q, Symbol p, long n) {
+ if (p->scope == GLOBAL
+ || p->sclass == STATIC || p->sclass == EXTERN)
+ q->x.name = stringf("%s%s%D",
+ p->x.name, n >= 0 ? "+" : "", n);
+ else {
+ assert(n <= INT_MAX && n >= INT_MIN);
+ q->x.offset = p->x.offset + n;
+ q->x.name = stringd(q->x.offset);
+ }
+}
+static void defconst(int suffix, int size, Value v) {
+ if (suffix == I && size == 1)
+ print("db %d\n", v.u);
+ else if (suffix == I && size == 2)
+ print("dw %d\n", v.i);
+ else if (suffix == I && size == 4)
+ print("dd %d\n", v.i);
+ else if (suffix == U && size == 1)
+ print("db 0%xH\n", v.u);
+ else if (suffix == U && size == 2)
+ print("dw 0%xH\n", v.u);
+ else if (suffix == U && size == 4)
+ print("dd 0%xH\n", v.u);
+ else if (suffix == P && size == 4)
+ print("dd 0%xH\n", v.p);
+ else if (suffix == F && size == 4) {
+ float f = v.d;
+ print("dd 0%xH\n", *(unsigned *)&f);
+ }
+ else if (suffix == F && size == 8) {
+ double d = v.d;
+ unsigned *p = (unsigned *)&d;
+ print("dd 0%xH\ndd 0%xH\n", p[swap], p[!swap]);
+ }
+ else assert(0);
+}
+static void defaddress(Symbol p) {
+ print("dd %s\n", p->x.name);
+}
+static void defstring(int n, char *str) {
+ char *s;
+
+ for (s = str; s < str + n; s++)
+ print("db %d\n", (*s)&0377);
+}
+static void export(Symbol p) {
+ print("public %s\n", p->x.name);
+}
+static void import(Symbol p) {
+ int oldseg = cseg;
+
+ if (p->ref > 0) {
+ segment(0);
+ print("extrn %s:near\n", p->x.name);
+ segment(oldseg);
+ }
+}
+static void global(Symbol p) {
+ print("align %d\n",
+ p->type->align > 4 ? 4 : p->type->align);
+ print("%s label byte\n", p->x.name);
+ if (p->u.seg == BSS)
+ print("db %d dup (0)\n", p->type->size);
+}
+static void space(int n) {
+ if (cseg != BSS)
+ print("db %d dup (0)\n", n);
+}
+Interface x86IR = {
+ 1, 1, 0, /* char */
+ 2, 2, 0, /* short */
+ 4, 4, 0, /* int */
+ 4, 4, 0, /* long */
+ 4, 4, 0, /* long long */
+ 4, 4, 1, /* float */
+ 8, 4, 1, /* double */
+ 8, 4, 1, /* long double */
+ 4, 4, 0, /* T * */
+ 0, 4, 0, /* struct; so that ARGB keeps stack aligned */
+ 1, /* little_endian */
+ 0, /* mulops_calls */
+ 0, /* wants_callb */
+ 1, /* wants_argb */
+ 0, /* left_to_right */
+ 0, /* wants_dag */
+ 0, /* unsigned_char */
+ address,
+ blockbeg,
+ blockend,
+ defaddress,
+ defconst,
+ defstring,
+ defsymbol,
+ emit,
+ export,
+ function,
+ gen,
+ global,
+ import,
+ local,
+ progbeg,
+ progend,
+ segment,
+ space,
+ 0, 0, 0, 0, 0, 0, 0,
+ {1, rmap,
+ blkfetch, blkstore, blkloop,
+ _label,
+ _rule,
+ _nts,
+ _kids,
+ _string,
+ _templates,
+ _isinstruction,
+ _ntname,
+ emit2,
+ doarg,
+ target,
+ clobber,
+}
+};
+static char rcsid[] = "$Id: x86.md 145 2001-10-17 21:53:10Z timo $";
diff --git a/lcc/src/x86linux.md b/lcc/src/x86linux.md
new file mode 100755
index 0000000..b7baaff
--- /dev/null
+++ b/lcc/src/x86linux.md
@@ -0,0 +1,1081 @@
+%{
+/* x86/linux lburg spec. Derived from x86.md by
+Marcos Ramirez <marcos@inf.utfsm.cl>
+Horst von Brand <vonbrand@sleipnir.valparaiso.cl>
+Jacob Navia <jacob@jacob.remcomp.fr>
+*/
+enum { EAX=0, ECX=1, EDX=2, EBX=3, ESI=6, EDI=7 };
+#include "c.h"
+#define NODEPTR_TYPE Node
+#define OP_LABEL(p) ((p)->op)
+#define LEFT_CHILD(p) ((p)->kids[0])
+#define RIGHT_CHILD(p) ((p)->kids[1])
+#define STATE_LABEL(p) ((p)->x.state)
+extern int ckstack(Node, int);
+extern int memop(Node);
+extern int sametree(Node, Node);
+static Symbol charreg[32], shortreg[32], intreg[32];
+static Symbol fltreg[32];
+
+static Symbol charregw, shortregw, intregw, fltregw;
+
+static int cseg;
+
+static Symbol quo, rem;
+
+extern char *stabprefix;
+extern void stabblock(int, int, Symbol*);
+extern void stabend(Coordinate *, Symbol, Coordinate **, Symbol *, Symbol *);
+extern void stabfend(Symbol, int);
+extern void stabinit(char *, int, char *[]);
+extern void stabline(Coordinate *);
+extern void stabsym(Symbol);
+extern void stabtype(Symbol);
+
+static int pflag = 0;
+static char rcsid[] = "$Id: x86linux.md 145 2001-10-17 21:53:10Z timo $";
+
+#define hasargs(p) (p->syms[0] && p->syms[0]->u.c.v.i > 0 ? 0 : LBURG_MAX)
+%}
+%start stmt
+%term CNSTF4=4113
+%term CNSTF8=8209
+%term CNSTF16=16401
+%term CNSTI1=1045
+%term CNSTI2=2069
+%term CNSTI4=4117
+%term CNSTI8=8213
+%term CNSTP4=4119
+%term CNSTP8=8215
+%term CNSTU1=1046
+%term CNSTU2=2070
+%term CNSTU4=4118
+%term CNSTU8=8214
+
+%term ARGB=41
+%term ARGF4=4129
+%term ARGF8=8225
+%term ARGF16=16417
+%term ARGI4=4133
+%term ARGI8=8229
+%term ARGP4=4135
+%term ARGP8=8231
+%term ARGU4=4134
+%term ARGU8=8230
+
+%term ASGNB=57
+%term ASGNF4=4145
+%term ASGNF8=8241
+%term ASGNF16=16433
+%term ASGNI1=1077
+%term ASGNI2=2101
+%term ASGNI4=4149
+%term ASGNI8=8245
+%term ASGNP4=4151
+%term ASGNP8=8247
+%term ASGNU1=1078
+%term ASGNU2=2102
+%term ASGNU4=4150
+%term ASGNU8=8246
+
+%term INDIRB=73
+%term INDIRF4=4161
+%term INDIRF8=8257
+%term INDIRF16=16449
+%term INDIRI1=1093
+%term INDIRI2=2117
+%term INDIRI4=4165
+%term INDIRI8=8261
+%term INDIRP4=4167
+%term INDIRP8=8263
+%term INDIRU1=1094
+%term INDIRU2=2118
+%term INDIRU4=4166
+%term INDIRU8=8262
+
+%term CVFF4=4209
+%term CVFF8=8305
+%term CVFF16=16497
+%term CVFI4=4213
+%term CVFI8=8309
+
+%term CVIF4=4225
+%term CVIF8=8321
+%term CVIF16=16513
+%term CVII1=1157
+%term CVII2=2181
+%term CVII4=4229
+%term CVII8=8325
+%term CVIU1=1158
+%term CVIU2=2182
+%term CVIU4=4230
+%term CVIU8=8326
+
+%term CVPP4=4247
+%term CVPP8=8343
+%term CVPP16=16535
+%term CVPU4=4246
+%term CVPU8=8342
+
+%term CVUI1=1205
+%term CVUI2=2229
+%term CVUI4=4277
+%term CVUI8=8373
+%term CVUP4=4279
+%term CVUP8=8375
+%term CVUP16=16567
+%term CVUU1=1206
+%term CVUU2=2230
+%term CVUU4=4278
+%term CVUU8=8374
+
+%term NEGF4=4289
+%term NEGF8=8385
+%term NEGF16=16577
+%term NEGI4=4293
+%term NEGI8=8389
+
+%term CALLB=217
+%term CALLF4=4305
+%term CALLF8=8401
+%term CALLF16=16593
+%term CALLI4=4309
+%term CALLI8=8405
+%term CALLP4=4311
+%term CALLP8=8407
+%term CALLU4=4310
+%term CALLU8=8406
+%term CALLV=216
+
+%term RETF4=4337
+%term RETF8=8433
+%term RETF16=16625
+%term RETI4=4341
+%term RETI8=8437
+%term RETP4=4343
+%term RETP8=8439
+%term RETU4=4342
+%term RETU8=8438
+%term RETV=248
+
+%term ADDRGP4=4359
+%term ADDRGP8=8455
+
+%term ADDRFP4=4375
+%term ADDRFP8=8471
+
+%term ADDRLP4=4391
+%term ADDRLP8=8487
+
+%term ADDF4=4401
+%term ADDF8=8497
+%term ADDF16=16689
+%term ADDI4=4405
+%term ADDI8=8501
+%term ADDP4=4407
+%term ADDP8=8503
+%term ADDU4=4406
+%term ADDU8=8502
+
+%term SUBF4=4417
+%term SUBF8=8513
+%term SUBF16=16705
+%term SUBI4=4421
+%term SUBI8=8517
+%term SUBP4=4423
+%term SUBP8=8519
+%term SUBU4=4422
+%term SUBU8=8518
+
+%term LSHI4=4437
+%term LSHI8=8533
+%term LSHU4=4438
+%term LSHU8=8534
+
+%term MODI4=4453
+%term MODI8=8549
+%term MODU4=4454
+%term MODU8=8550
+
+%term RSHI4=4469
+%term RSHI8=8565
+%term RSHU4=4470
+%term RSHU8=8566
+
+%term BANDI4=4485
+%term BANDI8=8581
+%term BANDU4=4486
+%term BANDU8=8582
+
+%term BCOMI4=4501
+%term BCOMI8=8597
+%term BCOMU4=4502
+%term BCOMU8=8598
+
+%term BORI4=4517
+%term BORI8=8613
+%term BORU4=4518
+%term BORU8=8614
+
+%term BXORI4=4533
+%term BXORI8=8629
+%term BXORU4=4534
+%term BXORU8=8630
+
+%term DIVF4=4545
+%term DIVF8=8641
+%term DIVF16=16833
+%term DIVI4=4549
+%term DIVI8=8645
+%term DIVU4=4550
+%term DIVU8=8646
+
+%term MULF4=4561
+%term MULF8=8657
+%term MULF16=16849
+%term MULI4=4565
+%term MULI8=8661
+%term MULU4=4566
+%term MULU8=8662
+
+%term EQF4=4577
+%term EQF8=8673
+%term EQF16=16865
+%term EQI4=4581
+%term EQI8=8677
+%term EQU4=4582
+%term EQU8=8678
+
+%term GEF4=4593
+%term GEF8=8689
+%term GEI4=4597
+%term GEI8=8693
+%term GEI16=16885
+%term GEU4=4598
+%term GEU8=8694
+
+%term GTF4=4609
+%term GTF8=8705
+%term GTF16=16897
+%term GTI4=4613
+%term GTI8=8709
+%term GTU4=4614
+%term GTU8=8710
+
+%term LEF4=4625
+%term LEF8=8721
+%term LEF16=16913
+%term LEI4=4629
+%term LEI8=8725
+%term LEU4=4630
+%term LEU8=8726
+
+%term LTF4=4641
+%term LTF8=8737
+%term LTF16=16929
+%term LTI4=4645
+%term LTI8=8741
+%term LTU4=4646
+%term LTU8=8742
+
+%term NEF4=4657
+%term NEF8=8753
+%term NEF16=16945
+%term NEI4=4661
+%term NEI8=8757
+%term NEU4=4662
+%term NEU8=8758
+
+%term JUMPV=584
+
+%term LABELV=600
+
+%term LOADB=233
+%term LOADF4=4321
+%term LOADF8=8417
+%term LOADF16=16609
+%term LOADI1=1253
+%term LOADI2=2277
+%term LOADI4=4325
+%term LOADI8=8421
+%term LOADP4=4327
+%term LOADP8=8423
+%term LOADU1=1254
+%term LOADU2=2278
+%term LOADU4=4326
+%term LOADU8=8422
+
+%term VREGP=711
+%%
+reg: INDIRI1(VREGP) "# read register\n"
+reg: INDIRU1(VREGP) "# read register\n"
+
+reg: INDIRI2(VREGP) "# read register\n"
+reg: INDIRU2(VREGP) "# read register\n"
+
+reg: INDIRI4(VREGP) "# read register\n"
+reg: INDIRP4(VREGP) "# read register\n"
+reg: INDIRU4(VREGP) "# read register\n"
+
+reg: INDIRI8(VREGP) "# read register\n"
+reg: INDIRP8(VREGP) "# read register\n"
+reg: INDIRU8(VREGP) "# read register\n"
+
+freg: INDIRF4(VREGP) "# read register\n"
+freg: INDIRF8(VREGP) "# read register\n"
+
+stmt: ASGNI1(VREGP,reg) "# write register\n"
+stmt: ASGNU1(VREGP,reg) "# write register\n"
+
+stmt: ASGNI2(VREGP,reg) "# write register\n"
+stmt: ASGNU2(VREGP,reg) "# write register\n"
+
+stmt: ASGNF4(VREGP,reg) "# write register\n"
+stmt: ASGNI4(VREGP,reg) "# write register\n"
+stmt: ASGNP4(VREGP,reg) "# write register\n"
+stmt: ASGNU4(VREGP,reg) "# write register\n"
+
+stmt: ASGNF8(VREGP,reg) "# write register\n"
+stmt: ASGNI8(VREGP,reg) "# write register\n"
+stmt: ASGNP8(VREGP,reg) "# write register\n"
+stmt: ASGNU8(VREGP,reg) "# write register\n"
+
+cnst: CNSTI1 "%a"
+cnst: CNSTU1 "%a"
+
+cnst: CNSTI2 "%a"
+cnst: CNSTU2 "%a"
+
+cnst: CNSTI4 "%a"
+cnst: CNSTU4 "%a"
+cnst: CNSTP4 "%a"
+
+cnst: CNSTI8 "%a"
+cnst: CNSTU8 "%a"
+cnst: CNSTP8 "%a"
+
+con: cnst "$%0"
+
+stmt: reg ""
+stmt: freg ""
+
+acon: ADDRGP4 "%a"
+acon: ADDRGP8 "%a"
+acon: cnst "%0"
+
+baseaddr: ADDRGP4 "%a"
+base: reg "(%0)"
+base: ADDI4(reg,acon) "%1(%0)"
+base: ADDP4(reg,acon) "%1(%0)"
+base: ADDU4(reg,acon) "%1(%0)"
+base: ADDRFP4 "%a(%%ebp)"
+base: ADDRLP4 "%a(%%ebp)"
+
+index: reg "%0"
+index: LSHI4(reg,con1) "%0,2"
+index: LSHI4(reg,con2) "%0,4"
+index: LSHI4(reg,con3) "%0,8"
+index: LSHU4(reg,con1) "%0,2"
+index: LSHU4(reg,con2) "%0,4"
+index: LSHU4(reg,con3) "%0,8"
+
+con0: CNSTI4 "1" range(a, 0, 0)
+con0: CNSTU4 "1" range(a, 0, 0)
+con1: CNSTI4 "1" range(a, 1, 1)
+con1: CNSTU4 "1" range(a, 1, 1)
+con2: CNSTI4 "2" range(a, 2, 2)
+con2: CNSTU4 "2" range(a, 2, 2)
+con3: CNSTI4 "3" range(a, 3, 3)
+con3: CNSTU4 "3" range(a, 3, 3)
+
+addr: base "%0"
+addr: baseaddr "%0"
+addr: ADDI4(index,baseaddr) "%1(,%0)"
+addr: ADDP4(index,baseaddr) "%1(,%0)"
+addr: ADDU4(index,baseaddr) "%1(,%0)"
+
+addr: ADDI4(reg,baseaddr) "%1(%0)"
+addr: ADDP4(reg,baseaddr) "%1(%0)"
+addr: ADDU4(reg,baseaddr) "%1(%0)"
+
+addr: ADDI4(index,reg) "(%1,%0)"
+addr: ADDP4(index,reg) "(%1,%0)"
+addr: ADDU4(index,reg) "(%1,%0)"
+
+addr: index "(,%0)"
+
+mem1: INDIRI1(addr) "%0"
+mem1: INDIRU1(addr) "%0"
+mem2: INDIRI2(addr) "%0"
+mem2: INDIRU2(addr) "%0"
+mem4: INDIRI4(addr) "%0"
+mem4: INDIRU4(addr) "%0"
+mem4: INDIRP4(addr) "%0"
+
+rc: reg "%0"
+rc: con "%0"
+
+mr: reg "%0"
+mr: mem4 "%0"
+
+mr1: reg "%0"
+mr1: mem1 "%0"
+
+mr2: reg "%0"
+mr2: mem2 "%0"
+
+mrc: mem4 "%0" 1
+mrc: mem1 "%0" 1
+mrc: mem2 "%0" 1
+mrc: rc "%0"
+
+reg: addr "leal %0,%c\n" 1
+reg: mr "movl %0,%c\n" 1
+reg: mr1 "movb %0,%c\n" 1
+reg: mr2 "movw %0,%c\n" 1
+reg: con "movl %0,%c\n" 1
+
+reg: LOADI1(reg) "# move\n" 1
+reg: LOADI2(reg) "# move\n" 1
+reg: LOADI4(reg) "# move\n" move(a)
+reg: LOADU1(reg) "# move\n" 1
+reg: LOADU2(reg) "# move\n" 1
+reg: LOADU4(reg) "# move\n" move(a)
+reg: LOADP4(reg) "# move\n" move(a)
+reg: ADDI4(reg,mrc) "?movl %0,%c\naddl %1,%c\n" 1
+reg: ADDP4(reg,mrc) "?movl %0,%c\naddl %1,%c\n" 1
+reg: ADDU4(reg,mrc) "?movl %0,%c\naddl %1,%c\n" 1
+reg: SUBI4(reg,mrc) "?movl %0,%c\nsubl %1,%c\n" 1
+reg: SUBP4(reg,mrc) "?movl %0,%c\nsubl %1,%c\n" 1
+reg: SUBU4(reg,mrc) "?movl %0,%c\nsubl %1,%c\n" 1
+reg: BANDI4(reg,mrc) "?movl %0,%c\nandl %1,%c\n" 1
+reg: BORI4(reg,mrc) "?movl %0,%c\norl %1,%c\n" 1
+reg: BXORI4(reg,mrc) "?movl %0,%c\nxorl %1,%c\n" 1
+reg: BANDU4(reg,mrc) "?movl %0,%c\nandl %1,%c\n" 1
+reg: BORU4(reg,mrc) "?movl %0,%c\norl %1,%c\n" 1
+reg: BXORU4(reg,mrc) "?movl %0,%c\nxorl %1,%c\n" 1
+
+stmt: ASGNI4(addr,ADDI4(mem4,con1)) "incl %1\n" memop(a)
+stmt: ASGNI4(addr,ADDU4(mem4,con1)) "incl %1\n" memop(a)
+stmt: ASGNP4(addr,ADDP4(mem4,con1)) "incl %1\n" memop(a)
+stmt: ASGNI4(addr,SUBI4(mem4,con1)) "decl %1\n" memop(a)
+stmt: ASGNI4(addr,SUBU4(mem4,con1)) "decl %1\n" memop(a)
+stmt: ASGNP4(addr,SUBP4(mem4,con1)) "decl %1\n" memop(a)
+stmt: ASGNI4(addr,ADDI4(mem4,rc)) "addl %2,%1\n" memop(a)
+stmt: ASGNI4(addr,SUBI4(mem4,rc)) "sub %2,%1\n" memop(a)
+stmt: ASGNU4(addr,ADDU4(mem4,rc)) "add %2,%1\n" memop(a)
+stmt: ASGNU4(addr,SUBU4(mem4,rc)) "sub %2,%1\n" memop(a)
+
+stmt: ASGNI4(addr,BANDI4(mem4,rc)) "andl %2,%1\n" memop(a)
+stmt: ASGNI4(addr,BORI4(mem4,rc)) "orl %2,%1\n" memop(a)
+stmt: ASGNI4(addr,BXORI4(mem4,rc)) "xorl %2,%1\n" memop(a)
+stmt: ASGNU4(addr,BANDU4(mem4,rc)) "andl %2,%1\n" memop(a)
+stmt: ASGNU4(addr,BORU4(mem4,rc)) "orl %2,%1\n" memop(a)
+stmt: ASGNU4(addr,BXORU4(mem4,rc)) "xorl %2,%1\n" memop(a)
+reg: BCOMI4(reg) "?movl %0,%c\nnotl %c\n" 2
+reg: BCOMU4(reg) "?movl %0,%c\nnotl %c\n" 2
+reg: NEGI4(reg) "?movl %0,%c\nnegl %c\n" 2
+
+stmt: ASGNI4(addr,BCOMI4(mem4)) "notl %1\n" memop(a)
+stmt: ASGNU4(addr,BCOMU4(mem4)) "notl %1\n" memop(a)
+stmt: ASGNI4(addr,NEGI4(mem4)) "negl %1\n" memop(a)
+reg: LSHI4(reg,rc5) "?movl %0,%c\nsall %1,%c\n" 2
+reg: LSHU4(reg,rc5) "?movl %0,%c\nshll %1,%c\n" 2
+reg: RSHI4(reg,rc5) "?movl %0,%c\nsarl %1,%c\n" 2
+reg: RSHU4(reg,rc5) "?movl %0,%c\nshrl %1,%c\n" 2
+
+stmt: ASGNI4(addr,LSHI4(mem4,rc5)) "sall %2,%1\n" memop(a)
+stmt: ASGNI4(addr,LSHU4(mem4,rc5)) "shll %2,%1\n" memop(a)
+stmt: ASGNI4(addr,RSHI4(mem4,rc5)) "sarl %2,%1\n" memop(a)
+stmt: ASGNI4(addr,RSHU4(mem4,rc5)) "shrl %2,%1\n" memop(a)
+
+rc5: CNSTI4 "$%a" range(a, 0, 31)
+rc5: reg "%%cl"
+reg: MULI4(reg,mrc) "?movl %0,%c\nimull %1,%c\n" 14
+reg: MULI4(con,mr) "imul %0,%1,%c\n" 13
+reg: MULU4(reg,mr) "mull %1\n" 13
+reg: DIVU4(reg,reg) "xorl %%edx,%%edx\ndivl %1\n"
+reg: MODU4(reg,reg) "xorl %%edx,%%edx\ndivl %1\n"
+reg: DIVI4(reg,reg) "cdq\nidivl %1\n"
+reg: MODI4(reg,reg) "cdq\nidivl %1\n"
+reg: CVPU4(reg) "movl %0,%c\n" move(a)
+reg: CVUP4(reg) "movl %0,%c\n" move(a)
+reg: CVII4(INDIRI1(addr)) "movsbl %0,%c\n" 3
+reg: CVII4(INDIRI2(addr)) "movswl %0,%c\n" 3
+reg: CVUU4(INDIRU1(addr)) "movzbl %0,%c\n" 3
+reg: CVUU4(INDIRU2(addr)) "movzwl %0,%c\n" 3
+reg: CVII4(reg) "# extend\n" 3
+reg: CVIU4(reg) "# extend\n" 3
+reg: CVUI4(reg) "# extend\n" 3
+reg: CVUU4(reg) "# extend\n" 3
+
+reg: CVII1(reg) "# truncate\n" 1
+reg: CVII2(reg) "# truncate\n" 1
+reg: CVUU1(reg) "# truncate\n" 1
+reg: CVUU2(reg) "# truncate\n" 1
+
+mrca: mem4 "%0"
+mrca: rc "%0"
+mrca: ADDRGP4 "$%a"
+mrca: ADDRGP8 "$%a"
+
+stmt: ASGNI1(addr,rc) "movb %1,%0\n" 1
+stmt: ASGNI2(addr,rc) "movw %1,%0\n" 1
+stmt: ASGNI4(addr,rc) "movl %1,%0\n" 1
+stmt: ASGNU1(addr,rc) "movb %1,%0\n" 1
+stmt: ASGNU2(addr,rc) "movw %1,%0\n" 1
+stmt: ASGNU4(addr,rc) "movl %1,%0\n" 1
+stmt: ASGNP4(addr,rc) "movl %1,%0\n" 1
+stmt: ARGI4(mrca) "pushl %0\n" 1
+stmt: ARGU4(mrca) "pushl %0\n" 1
+stmt: ARGP4(mrca) "pushl %0\n" 1
+stmt: ASGNB(reg,INDIRB(reg)) "movl $%a,%%ecx\nrep\nmovsb\n"
+stmt: ARGB(INDIRB(reg)) "subl $%a,%%esp\nmovl %%esp,%%edi\nmovl $%a,%%ecx\nrep\nmovsb\n"
+
+memf: INDIRF8(addr) "l %0"
+memf: INDIRF4(addr) "s %0"
+memf: CVFF8(INDIRF4(addr)) "s %0"
+memf: CVFF4(INDIRF8(addr)) "l %0"
+
+freg: memf "fld%0\n" 3
+
+stmt: ASGNF8(addr,freg) "fstpl %0\n" 7
+stmt: ASGNF4(addr,freg) "fstps %0\n" 7
+stmt: ASGNF4(addr,CVFF4(freg)) "fstps %0\n" 7
+
+stmt: ARGF8(freg) "subl $8,%%esp\nfstpl (%%esp)\n"
+stmt: ARGF4(freg) "subl $4,%%esp\nfstps (%%esp)\n"
+freg: NEGF8(freg) "fchs\n"
+freg: NEGF4(freg) "fchs\n"
+
+flt: memf "%0"
+flt: freg "p %%st(1),%%st"
+
+freg: ADDF4(freg,flt) "fadd%1\n"
+freg: ADDF8(freg,flt) "fadd%1\n"
+
+freg: DIVF4(freg,flt) "fdiv%1\n"
+freg: DIVF8(freg,flt) "fdiv%1\n"
+
+freg: MULF4(freg,flt) "fmul%1\n"
+freg: MULF8(freg,flt) "fmul%1\n"
+
+freg: SUBF4(freg,flt) "fsub%1\n"
+freg: SUBF8(freg,flt) "fsub%1\n"
+
+freg: CVFF8(freg) "# CVFF8\n"
+freg: CVFF4(freg) "sub $4,%%esp\nfstps (%%esp)\nflds (%%esp)\naddl $4,%%esp\n" 12
+
+stmt: ASGNI4(addr,CVFI4(freg)) "fistpl %0\n" 29
+reg: CVFI4(freg) "subl $4,%%esp\nfistpl 0(%%esp)\npopl %c\n" 31
+
+freg: CVIF8(INDIRI4(addr)) "fildl %0\n" 10
+freg: CVIF8(reg) "pushl %0\nfildl (%%esp)\naddl $4,%%esp\n" 12
+
+freg: CVIF4(INDIRI4(addr)) "fildl %0\n" 10
+freg: CVIF4(reg) "pushl %0\nfildl (%%esp)\naddl $4,%%esp\n" 12
+
+addrj: ADDRGP4 "%a"
+addrj: reg "*%0" 2
+addrj: mem4 "*%0" 2
+
+stmt: LABELV "%a:\n"
+stmt: JUMPV(addrj) "jmp %0\n" 3
+stmt: EQI4(mem4,rc) "cmpl %1,%0\nje %a\n" 5
+stmt: GEI4(mem4,rc) "cmpl %1,%0\njge %a\n" 5
+stmt: GTI4(mem4,rc) "cmpl %1,%0\njg %a\n" 5
+stmt: LEI4(mem4,rc) "cmpl %1,%0\njle %a\n" 5
+stmt: LTI4(mem4,rc) "cmpl %1,%0\njl %a\n" 5
+stmt: NEI4(mem4,rc) "cmpl %1,%0\njne %a\n" 5
+stmt: GEU4(mem4,rc) "cmpl %1,%0\njae %a\n" 5
+stmt: GTU4(mem4,rc) "cmpl %1,%0\nja %a\n" 5
+stmt: LEU4(mem4,rc) "cmpl %1,%0\njbe %a\n" 5
+stmt: LTU4(mem4,rc) "cmpl %1,%0\njb %a\n" 5
+stmt: EQI4(reg,mrc) "cmpl %1,%0\nje %a\n" 4
+stmt: GEI4(reg,mrc) "cmpl %1,%0\njge %a\n" 4
+stmt: GTI4(reg,mrc) "cmpl %1,%0\njg %a\n" 4
+stmt: LEI4(reg,mrc) "cmpl %1,%0\njle %a\n" 4
+stmt: LTI4(reg,mrc) "cmpl %1,%0\njl %a\n" 4
+stmt: NEI4(reg,mrc) "cmpl %1,%0\njne %a\n" 4
+
+stmt: EQU4(reg,mrc) "cmpl %1,%0\nje %a\n" 4
+stmt: GEU4(reg,mrc) "cmpl %1,%0\njae %a\n" 4
+stmt: GTU4(reg,mrc) "cmpl %1,%0\nja %a\n" 4
+stmt: LEU4(reg,mrc) "cmpl %1,%0\njbe %a\n" 4
+stmt: LTU4(reg,mrc) "cmpl %1,%0\njb %a\n" 4
+stmt: NEU4(reg,mrc) "cmpl %1,%0\njne %a\n" 4
+
+stmt: EQI4(BANDU4(mr,con),con0) "testl %1,%0\nje %a\n" 3
+stmt: NEI4(BANDU4(mr,con),con0) "testl %1,%0\njne %a\n"
+
+stmt: EQI4(BANDU4(CVII2(INDIRI2(addr)),con),con0) "testw %1,%0\nje %a\n"
+stmt: NEI4(BANDU4(CVII2(INDIRI2(addr)),con),con0) "testw %1,%0\njne %a\n"
+stmt: EQI4(BANDU4(CVIU2(INDIRI2(addr)),con),con0) "testw %1,%0\nje %a\n"
+stmt: NEI4(BANDU4(CVIU2(INDIRI2(addr)),con),con0) "testw %1,%0\njne %a\n"
+stmt: EQI4(BANDU4(CVII1(INDIRI1(addr)),con),con0) "testb %1,%0\nje %a\n"
+
+cmpf: INDIRF8(addr) "l %0"
+cmpf: INDIRF4(addr) "s %0"
+cmpf: CVFF8(INDIRF4(addr)) "s %0"
+cmpf: freg "p"
+
+stmt: EQF8(cmpf,freg) "fcomp%0\nfstsw %%ax\nsahf\nje %a\n"
+stmt: GEF8(cmpf,freg) "fcomp%0\nfstsw %%ax\nsahf\njbe %a\n"
+stmt: GTF8(cmpf,freg) "fcomp%0\nfstsw %%ax\nsahf\njb %a\n"
+stmt: LEF8(cmpf,freg) "fcomp%0\nfstsw %%ax\nsahf\njae %a\n"
+stmt: LTF8(cmpf,freg) "fcomp%0\nfstsw %%ax\nsahf\nja %a\n"
+stmt: NEF8(cmpf,freg) "fcomp%0\nfstsw %%ax\nsahf\njne %a\n"
+
+stmt: EQF4(cmpf,freg) "fcomp%0\nfstsw %%ax\nsahf\nje %a\n"
+stmt: GEF4(cmpf,freg) "fcomp%0\nfstsw %%ax\nsahf\njbe %a\n"
+stmt: GTF4(cmpf,freg) "fcomp%0\nfstsw %%ax\nsahf\njb %a\n"
+stmt: LEF4(cmpf,freg) "fcomp%0\nfstsw %%ax\nsahf\njae %a\n"
+stmt: LTF4(cmpf,freg) "fcomp%0\nfstsw %%ax\nsahf\nja %a\n"
+stmt: NEF4(cmpf,freg) "fcomp%0\nfstsw %%ax\nsahf\njne %a\n"
+
+freg: DIVF8(freg,CVIF8(INDIRI4(addr))) "fidivl %1\n"
+freg: DIVF8(CVIF8(INDIRI4(addr)),freg) "fidivrl %0\n"
+freg: DIVF8(freg,CVIF8(CVII2(INDIRI2(addr)))) "fidivs %1\n"
+freg: DIVF8(CVIF8(CVII2(INDIRI2(addr))),freg) "fidivrs %0\n"
+freg: MULF8(freg,CVIF8(INDIRI4(addr))) "fimull %1\n"
+freg: MULF8(freg,CVIF8(CVII2(INDIRI2(addr)))) "fimuls %1\n"
+freg: SUBF8(freg,CVIF8(INDIRI4(addr))) "fisubl %1\n"
+freg: SUBF8(CVIF8(INDIRI4(addr)),freg) "fisubrl %0\n"
+freg: SUBF8(freg,CVIF8(CVII2(INDIRI2(addr)))) "fisubs %1\n"
+freg: SUBF8(CVIF8(CVII2(INDIRI2(addr))),freg) "fisubrs %0\n"
+freg: ADDF8(freg,CVIF8(INDIRI4(addr))) "fiaddl %1\n"
+freg: ADDF8(freg,CVIF8(CVII2(INDIRI2(addr)))) "fiadds %1\n"
+freg: ADDF8(freg,CVFF8(INDIRF4(addr))) "fdivs %1\n"
+freg: SUBF8(freg,CVFF8(INDIRF4(addr))) "fsubs %1\n"
+freg: MULF8(freg,CVFF8(INDIRF4(addr))) "fmuls %1\n"
+freg: DIVF8(freg,CVFF8(INDIRF4(addr))) "fdivs %1\n"
+freg: LOADF8(memf) "fld%0\n"
+
+reg: CALLI4(addrj) "call %0\naddl $%a,%%esp\n" hasargs(a)
+reg: CALLU4(addrj) "call %0\naddl $%a,%%esp\n" hasargs(a)
+reg: CALLP4(addrj) "call %0\naddl $%a,%%esp\n" hasargs(a)
+
+reg: CALLI4(addrj) "call %0\n" 1
+reg: CALLU4(addrj) "call %0\n" 1
+reg: CALLP4(addrj) "call %0\n" 1
+
+stmt: CALLV(addrj) "call %0\naddl $%a,%%esp\n" hasargs(a)
+stmt: CALLV(addrj) "call %0\n" 1
+
+freg: CALLF4(addrj) "call %0\naddl $%a,%%esp\n" hasargs(a)
+freg: CALLF4(addrj) "call %0\n" 1
+
+stmt: CALLF4(addrj) "call %0\naddl $%a,%%esp\nfstp %%st(0)\n" hasargs(a)
+stmt: CALLF4(addrj) "call %0\nfstp %%st(0)\n" 1
+
+freg: CALLF8(addrj) "call %0\naddl $%a,%%esp\n" hasargs(a)
+freg: CALLF8(addrj) "call %0\n" 1
+
+stmt: CALLF8(addrj) "call %0\naddl $%a,%%esp\nfstp %%st(0)\n" hasargs(a)
+stmt: CALLF8(addrj) "call %0\nfstp %%st(0)\n" 1
+
+stmt: RETI4(reg) "# ret\n"
+stmt: RETU4(reg) "# ret\n"
+stmt: RETP4(reg) "# ret\n"
+stmt: RETF4(freg) "# ret\n"
+stmt: RETF8(freg) "# ret\n"
+%%
+static void progbeg(int argc, char *argv[]) {
+ int i;
+
+ {
+ union {
+ char c;
+ int i;
+ } u;
+ u.i = 0;
+ u.c = 1;
+ swap = ((int)(u.i == 1)) != IR->little_endian;
+ }
+ parseflags(argc, argv);
+ for (i = 0; i < argc; i++)
+ if (strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "-pg") == 0)
+ pflag = 1;
+ intreg[EAX] = mkreg("%%eax", EAX, 1, IREG);
+ intreg[EDX] = mkreg("%%edx", EDX, 1, IREG);
+ intreg[ECX] = mkreg("%%ecx", ECX, 1, IREG);
+ intreg[EBX] = mkreg("%%ebx", EBX, 1, IREG);
+ intreg[ESI] = mkreg("%%esi", ESI, 1, IREG);
+ intreg[EDI] = mkreg("%%edi", EDI, 1, IREG);
+ shortreg[EAX] = mkreg("%%ax", EAX, 1, IREG);
+ shortreg[ECX] = mkreg("%%cx", ECX, 1, IREG);
+ shortreg[EDX] = mkreg("%%dx", EDX, 1, IREG);
+ shortreg[EBX] = mkreg("%%bx", EBX, 1, IREG);
+ shortreg[ESI] = mkreg("%%si", ESI, 1, IREG);
+ shortreg[EDI] = mkreg("%%di", EDI, 1, IREG);
+ charreg[EAX] = mkreg("%%al", EAX, 1, IREG);
+ charreg[ECX] = mkreg("%%cl", ECX, 1, IREG);
+ charreg[EDX] = mkreg("%%dl", EDX, 1, IREG);
+ charreg[EBX] = mkreg("%%bl", EBX, 1, IREG);
+ for (i = 0; i < 8; i++)
+ fltreg[i] = mkreg("%d", i, 0, FREG);
+ charregw = mkwildcard(charreg);
+ shortregw = mkwildcard(shortreg);
+ intregw = mkwildcard(intreg);
+ fltregw = mkwildcard(fltreg);
+
+ tmask[IREG] = (1<<EDI) | (1<<ESI) | (1<<EBX)
+ | (1<<EDX) | (1<<ECX) | (1<<EAX);
+ vmask[IREG] = 0;
+ tmask[FREG] = 0xff;
+ vmask[FREG] = 0;
+
+ cseg = 0;
+ quo = mkreg("%%eax", EAX, 1, IREG);
+ quo->x.regnode->mask |= 1<<EDX;
+ rem = mkreg("%%edx", EDX, 1, IREG);
+ rem->x.regnode->mask |= 1<<EAX;
+
+ stabprefix = ".LL";
+}
+
+static Symbol rmap(int opk) {
+ switch (optype(opk)) {
+ case B: case P:
+ return intregw;
+ case I: case U:
+ if (opsize(opk) == 1)
+ return charregw;
+ else if (opsize(opk) == 2)
+ return shortregw;
+ else
+ return intregw;
+ case F:
+ return fltregw;
+ default:
+ return 0;
+ }
+}
+
+static Symbol prevg;
+
+static void globalend(void) {
+ if (prevg && prevg->type->size > 0)
+ print(".size %s,%d\n", prevg->x.name, prevg->type->size);
+ prevg = NULL;
+}
+
+static void progend(void) {
+ globalend();
+ (*IR->segment)(CODE);
+ print(".ident \"LCC: 4.1\"\n");
+}
+
+static void target(Node p) {
+ assert(p);
+ switch (specific(p->op)) {
+ case RSH+I: case RSH+U: case LSH+I: case LSH+U:
+ if (generic(p->kids[1]->op) != CNST
+ && !( generic(p->kids[1]->op) == INDIR
+ && specific(p->kids[1]->kids[0]->op) == VREG+P
+ && p->kids[1]->syms[RX]->u.t.cse
+ && generic(p->kids[1]->syms[RX]->u.t.cse->op) == CNST)) {
+ rtarget(p, 1, intreg[ECX]);
+ setreg(p, intreg[EAX]);
+ }
+ break;
+ case MUL+U:
+ setreg(p, quo);
+ rtarget(p, 0, intreg[EAX]);
+ break;
+ case DIV+I: case DIV+U:
+ setreg(p, quo);
+ rtarget(p, 0, intreg[EAX]);
+ rtarget(p, 1, intreg[ECX]);
+ break;
+ case MOD+I: case MOD+U:
+ setreg(p, rem);
+ rtarget(p, 0, intreg[EAX]);
+ rtarget(p, 1, intreg[ECX]);
+ break;
+ case ASGN+B:
+ rtarget(p, 0, intreg[EDI]);
+ rtarget(p->kids[1], 0, intreg[ESI]);
+ break;
+ case ARG+B:
+ rtarget(p->kids[0], 0, intreg[ESI]);
+ break;
+ case CVF+I:
+ setreg(p, intreg[EAX]);
+ break;
+ case CALL+I: case CALL+U: case CALL+P: case CALL+V:
+ setreg(p, intreg[EAX]);
+ break;
+ case RET+I: case RET+U: case RET+P:
+ rtarget(p, 0, intreg[EAX]);
+ break;
+ }
+}
+
+static void clobber(Node p) {
+ static int nstack = 0;
+
+ assert(p);
+ nstack = ckstack(p, nstack);
+ switch (specific(p->op)) {
+ case ASGN+B: case ARG+B:
+ spill(1<<ECX | 1<<ESI | 1<<EDI, IREG, p);
+ break;
+ case EQ+F: case LE+F: case GE+F: case LT+F: case GT+F: case NE+F:
+ spill(1<<EAX, IREG, p);
+ break;
+ case CALL+F:
+ spill(1<<EDX | 1<<EAX | 1<<ECX, IREG, p);
+ break;
+ case CALL+I: case CALL+U: case CALL+P: case CALL+V:
+ spill(1<<EDX | 1<<ECX, IREG, p);
+ break;
+ }
+}
+
+static void emit2(Node p) {
+ int op = specific(p->op);
+#define preg(f) ((f)[getregnum(p->x.kids[0])]->x.name)
+
+ if (op == CVI+I && opsize(p->op) == 4 && opsize(p->x.kids[0]->op) == 1)
+ print("movsbl %s,%s\n", preg(charreg), p->syms[RX]->x.name);
+ else if (op == CVI+U && opsize(p->op) == 4 && opsize(p->x.kids[0]->op) == 1)
+ print("movsbl %s,%s\n", preg(charreg), p->syms[RX]->x.name);
+ else if (op == CVI+I && opsize(p->op) == 4 && opsize(p->x.kids[0]->op) == 2)
+ print("movswl %s,%s\n", preg(shortreg), p->syms[RX]->x.name);
+ else if (op == CVI+U && opsize(p->op) == 4 && opsize(p->x.kids[0]->op) == 2)
+ print("movswl %s,%s\n", preg(shortreg), p->syms[RX]->x.name);
+ else if (op == CVU+I && opsize(p->op) == 4 && opsize(p->x.kids[0]->op) == 1)
+ print("movzbl %s,%s\n", preg(charreg), p->syms[RX]->x.name);
+ else if (op == CVU+U && opsize(p->op) == 4 && opsize(p->x.kids[0]->op) == 1)
+ print("movzbl %s,%s\n", preg(charreg), p->syms[RX]->x.name);
+ else if (op == CVU+I && opsize(p->op) == 4 && opsize(p->x.kids[0]->op) == 2)
+ print("movzwl %s,%s\n", preg(shortreg), p->syms[RX]->x.name);
+ else if (op == CVU+U && opsize(p->op) == 4 && opsize(p->x.kids[0]->op) == 2)
+ print("movzwl %s,%s\n", preg(shortreg), p->syms[RX]->x.name);
+ else if (generic(op) == CVI || generic(op) == CVU || generic(op) == LOAD) {
+ char *dst = intreg[getregnum(p)]->x.name;
+ char *src = preg(intreg);
+ assert(opsize(p->op) <= opsize(p->x.kids[0]->op));
+ if (dst != src)
+ print("movl %s,%s\n", src, dst);
+ }
+}
+
+static void function(Symbol f, Symbol caller[], Symbol callee[], int n) {
+ int i;
+
+ globalend();
+ print(".align 16\n");
+ print(".type %s,@function\n", f->x.name);
+ print("%s:\n", f->x.name);
+ print("pushl %%ebp\n");
+ if (pflag) {
+ static int plab;
+ print("movl %%esp,%%ebp\n");
+ (*IR->segment)(DATA);
+ print(".align 4\n.LP%d:\n.long 0\n", plab);
+ (*IR->segment)(CODE);
+ print("movl $.LP%d,%%edx\ncall mcount\n", plab);
+ plab++;
+ }
+ print("pushl %%ebx\n");
+ print("pushl %%esi\n");
+ print("pushl %%edi\n");
+ print("movl %%esp,%%ebp\n");
+
+ usedmask[0] = usedmask[1] = 0;
+ freemask[0] = freemask[1] = ~0U;
+ offset = 16 + 4;
+ for (i = 0; callee[i]; i++) {
+ Symbol p = callee[i];
+ Symbol q = caller[i];
+ assert(q);
+ offset = roundup(offset, q->type->align);
+ p->x.offset = q->x.offset = offset;
+ p->x.name = q->x.name = stringf("%d", p->x.offset);
+ p->sclass = q->sclass = AUTO;
+ offset += roundup(q->type->size, 4);
+ }
+ assert(caller[i] == 0);
+ offset = maxoffset = 0;
+ gencode(caller, callee);
+ framesize = roundup(maxoffset, 4);
+ if (framesize > 0)
+ print("subl $%d,%%esp\n", framesize);
+ emitcode();
+ print("movl %%ebp,%%esp\n");
+ print("popl %%edi\n");
+ print("popl %%esi\n");
+ print("popl %%ebx\n");
+ print("popl %%ebp\n");
+ print("ret\n");
+ { int l = genlabel(1);
+ print(".Lf%d:\n", l);
+ print(".size %s,.Lf%d-%s\n", f->x.name, l, f->x.name);
+ }
+}
+
+static void defsymbol(Symbol p) {
+ if (p->scope >= LOCAL && p->sclass == STATIC)
+ p->x.name = stringf("%s.%d", p->name, genlabel(1));
+ else if (p->generated)
+ p->x.name = stringf(".LC%s", p->name);
+ else if (p->scope == GLOBAL || p->sclass == EXTERN)
+ p->x.name = stringf("%s", p->name);
+ else
+ p->x.name = p->name;
+}
+
+static void segment(int n) {
+ if (n == cseg)
+ return;
+ cseg = n;
+ if (cseg == CODE)
+ print(".text\n");
+ else if (cseg == BSS)
+ print(".bss\n");
+ else if (cseg == DATA || cseg == LIT)
+ print(".data\n");
+}
+
+static void defconst(int suffix, int size, Value v) {
+ if (suffix == I && size == 1)
+ print(".byte %d\n", v.u);
+ else if (suffix == I && size == 2)
+ print(".word %d\n", v.i);
+ else if (suffix == I && size == 4)
+ print(".long %d\n", v.i);
+ else if (suffix == U && size == 1)
+ print(".byte %d\n", v.u);
+ else if (suffix == U && size == 2)
+ print(".word %d\n", v.u);
+ else if (suffix == U && size == 4)
+ print(".long %d\n", v.u);
+ else if (suffix == P && size == 4)
+ print(".long %d\n", v.p);
+ else if (suffix == F && size == 4) {
+ float f = v.d;
+ print(".long %d\n", *(unsigned *)&f);
+ } else if (suffix == F && size == 8) {
+ double d = v.d;
+ unsigned *p = (unsigned *)&d;
+ print(".long %d\n.long %d\n", p[swap], p[!swap]);
+ }
+ else assert(0);
+}
+
+static void defaddress(Symbol p) {
+ print(".long %s\n", p->x.name);
+}
+
+static void defstring(int n, char *str) {
+ char *s;
+
+ for (s = str; s < str + n; s++)
+ print(".byte %d\n", (*s)&0377);
+}
+
+static void export(Symbol p) {
+ globalend();
+ print(".globl %s\n", p->x.name);
+}
+
+static void import(Symbol p) {}
+
+static void global(Symbol p) {
+ globalend();
+ print(".align %d\n", p->type->align > 4 ? 4 : p->type->align);
+ if (!p->generated) {
+ print(".type %s,@%s\n", p->x.name,
+ isfunc(p->type) ? "function" : "object");
+ if (p->type->size > 0)
+ print(".size %s,%d\n", p->x.name, p->type->size);
+ else
+ prevg = p;
+ }
+ if (p->u.seg == BSS) {
+ if (p->sclass == STATIC)
+ print(".lcomm %s,%d\n", p->x.name, p->type->size);
+ else
+ print(".comm %s,%d\n", p->x.name, p->type->size);
+ } else {
+ print("%s:\n", p->x.name);
+ }
+}
+
+static void space(int n) {
+ if (cseg != BSS)
+ print(".space %d\n", n);
+}
+
+Interface x86linuxIR = {
+ 1, 1, 0, /* char */
+ 2, 2, 0, /* short */
+ 4, 4, 0, /* int */
+ 4, 4, 0, /* long */
+ 4, 4, 0, /* long long */
+ 4, 4, 1, /* float */
+ 8, 4, 1, /* double */
+ 8, 4, 1, /* long double */
+ 4, 4, 0, /* T * */
+ 0, 4, 0, /* struct; so that ARGB keeps stack aligned */
+ 1, /* little_endian */
+ 0, /* mulops_calls */
+ 0, /* wants_callb */
+ 1, /* wants_argb */
+ 0, /* left_to_right */
+ 0, /* wants_dag */
+ 0, /* unsigned_char */
+ 0, /* address */
+ blockbeg,
+ blockend,
+ defaddress,
+ defconst,
+ defstring,
+ defsymbol,
+ emit,
+ export,
+ function,
+ gen,
+ global,
+ import,
+ 0, /* local */
+ progbeg,
+ progend,
+ segment,
+ space,
+ stabblock, stabend, 0, stabinit, stabline, stabsym, stabtype,
+ {1, rmap,
+ 0, 0, 0, /* blkfetch, blkstore, blkloop */
+ _label,
+ _rule,
+ _nts,
+ _kids,
+ _string,
+ _templates,
+ _isinstruction,
+ _ntname,
+ emit2,
+ 0, /* doarg */
+ target,
+ clobber,
+ }
+};
+
+void x86linux_init(int argc, char *argv[]) {
+ static int inited;
+ extern Interface x86IR;
+
+ if (inited)
+ return;
+ inited = 1;
+#define xx(f) assert(!x86linuxIR.f); x86linuxIR.f = x86IR.f
+ xx(address);
+ xx(local);
+ xx(x.blkfetch);
+ xx(x.blkstore);
+ xx(x.blkloop);
+ xx(x.doarg);
+#undef xx
+}
diff --git a/lcc/tst/8q.0 b/lcc/tst/8q.0
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/tst/8q.0
diff --git a/lcc/tst/8q.c b/lcc/tst/8q.c
new file mode 100755
index 0000000..e55ba1a
--- /dev/null
+++ b/lcc/tst/8q.c
@@ -0,0 +1,39 @@
+int up[15], down[15], rows[8], x[8];
+int queens(), print();
+
+main()
+{
+ int i;
+
+ for (i = 0; i < 15; i++)
+ up[i] = down[i] = 1;
+ for (i = 0; i < 8; i++)
+ rows[i] = 1;
+ queens(0);
+ return 0;
+}
+
+queens(c)
+{
+ int r;
+
+ for (r = 0; r < 8; r++)
+ if (rows[r] && up[r-c+7] && down[r+c]) {
+ rows[r] = up[r-c+7] = down[r+c] = 0;
+ x[c] = r;
+ if (c == 7)
+ print();
+ else
+ queens(c + 1);
+ rows[r] = up[r-c+7] = down[r+c] = 1;
+ }
+}
+
+print()
+{
+ int k;
+
+ for (k = 0; k < 8; k++)
+ printf("%c ", x[k]+'1');
+ printf("\n");
+}
diff --git a/lcc/tst/array.0 b/lcc/tst/array.0
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/tst/array.0
diff --git a/lcc/tst/array.c b/lcc/tst/array.c
new file mode 100755
index 0000000..7b03da5
--- /dev/null
+++ b/lcc/tst/array.c
@@ -0,0 +1,48 @@
+int x[3][4], *y[3];
+
+main() {
+ int z[3][4];
+ int i, j, *p;
+
+ for (i = 0; i < 3; i++) {
+ for (j = 0; j < 4; j++)
+ x[i][j] = 1000*i + j;
+ y[i] = x[i];
+ }
+ f();
+ for (i = 0; i < 3; i++) {
+ y[i] = p = &z[i][0];
+ for (j = 0; j < 4; j++)
+ p[j] = x[i][j];
+ }
+ g(z, y);
+ return 0;
+}
+
+f() {
+ int i, j;
+
+ for (i = 0; i < 3; i++)
+ for (j = 0; j < 4; j++)
+ printf(" %d", x[i][j]);
+ printf("\n");
+ for (i = 0; i < 3; i++)
+ for (j = 0; j < 4; j++)
+ printf(" %d", y[i][j]);
+ printf("\n");
+}
+
+g(x, y)
+int x[][4], *y[];
+{
+ int i, j;
+
+ for (i = 0; i < 3; i++)
+ for (j = 0; j < 4; j++)
+ printf(" %d", x[i][j]);
+ printf("\n");
+ for (i = 0; i < 3; i++)
+ for (j = 0; j < 4; j++)
+ printf(" %d", y[i][j]);
+ printf("\n");
+}
diff --git a/lcc/tst/cf.0 b/lcc/tst/cf.0
new file mode 100755
index 0000000..1c9226a
--- /dev/null
+++ b/lcc/tst/cf.0
@@ -0,0 +1,32 @@
+/* cf - print character frequencies */
+float f[128];
+
+main(argc, argv)
+int argc;
+char *argv[];
+{
+ int i, c, nc;
+ float cutoff, atof();
+
+ if (argc <= 1)
+ cutoff = 0.0;
+ else
+ cutoff = atof(argv[1])/100;
+ for (i = 0; i <= 127; )
+ f[i++] = 0.0;
+ nc = 0;
+ while ((c = getchar()) != -1) {
+ f[c] += 1;
+ nc++;
+ }
+ printf("char\tfreq\n");
+ for (i = 0; i <= 127; ++i)
+ if (f[i] && f[i]/nc >= cutoff) {
+ if (i <= ' ')
+ printf("%03o", i);
+ else
+ printf("%c", i);
+ printf("\t%.1f\n", 100*f[i]/nc);
+ }
+ return 0;
+}
diff --git a/lcc/tst/cf.c b/lcc/tst/cf.c
new file mode 100755
index 0000000..1c9226a
--- /dev/null
+++ b/lcc/tst/cf.c
@@ -0,0 +1,32 @@
+/* cf - print character frequencies */
+float f[128];
+
+main(argc, argv)
+int argc;
+char *argv[];
+{
+ int i, c, nc;
+ float cutoff, atof();
+
+ if (argc <= 1)
+ cutoff = 0.0;
+ else
+ cutoff = atof(argv[1])/100;
+ for (i = 0; i <= 127; )
+ f[i++] = 0.0;
+ nc = 0;
+ while ((c = getchar()) != -1) {
+ f[c] += 1;
+ nc++;
+ }
+ printf("char\tfreq\n");
+ for (i = 0; i <= 127; ++i)
+ if (f[i] && f[i]/nc >= cutoff) {
+ if (i <= ' ')
+ printf("%03o", i);
+ else
+ printf("%c", i);
+ printf("\t%.1f\n", 100*f[i]/nc);
+ }
+ return 0;
+}
diff --git a/lcc/tst/cq.0 b/lcc/tst/cq.0
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/tst/cq.0
diff --git a/lcc/tst/cq.c b/lcc/tst/cq.c
new file mode 100755
index 0000000..55d18d1
--- /dev/null
+++ b/lcc/tst/cq.c
@@ -0,0 +1,5316 @@
+ struct defs {
+ int cbits; /* No. of bits per char */
+ int ibits; /* int */
+ int sbits; /* short */
+ int lbits; /* long */
+ int ubits; /* unsigned */
+ int fbits; /* float */
+ int dbits; /* double */
+ float fprec; /* Smallest number that can be */
+ float dprec; /* significantly added to 1. */
+ int flgs; /* Print return codes, by section */
+ int flgm; /* Announce machine dependencies */
+ int flgd; /* give explicit diagnostics */
+ int flgl; /* Report local return codes. */
+ int rrc; /* recent return code */
+ int crc; /* Cumulative return code */
+ char rfs[8]; /* Return from section */
+ };
+main(n,args) /* C REFERENCE MANUAL */
+int n;
+char **args;
+{
+
+/* This program performs a series of tests on a C compiler,
+based on information in the
+
+ C REFERENCE MANUAL
+
+which appears as Appendix A to the book "The C Programming
+Language" by Brian W. Kernighan and Dennis M. Ritchie
+(Prentice-Hall, 1978, $10.95). This Appendix is hereafter
+referred to as "the Manual".
+
+ The rules followed in writing this program are:
+
+ 1. The entire program is written in legal C, according
+ to the Manual. It should compile with no error messages,
+ although some warning messages may be produced by some
+ compilers. Failure to compile should be interpreted as
+ a compiler error.
+
+ 2. The program is clean, in that it does not make use
+ of any features of the operating system on which it runs,
+ with the sole exceptions of the printf() function, and an
+ internal "options" routine, which is easily excised.
+
+ 3. No global variables are used, except for the spec-
+ ific purpose of testing the global variable facility.
+
+ The program is divided into modules having names of the
+form snnn... These modules correspond to those sections of the
+Manual, as identified by boldface type headings, in which
+there is something to test. For example, s241() corresponds
+to section 2.4.1 of the Manual (Integer constants) and tests
+the facilities described therein. The module numbering
+scheme is ambiguous, especially when it names modules
+referring to more than one section; module s7813, for ex-
+ample, deals with sections 7.8 through 7.13. Nonetheless,
+it is surprisingly easy to find a section in the Manual
+corresponding to a section of code, and vice versa.
+
+ Note also that there seem to be "holes" in the program,
+at least from the point of view that there exist sections in the
+Manual for which there is no corresponding code. Such holes
+arise from three causes: (a) there is nothing in that partic-
+ular section to test, (b) everything in that section is tested
+elsewhere, and (c) it was deemed advisable not to check cer-
+tain features like preprocessor or listing control features.
+
+ Modules are called by a main program main(). The mod-
+ules that are called, and the sequence in which they are
+called, are determined by two lists in main(), in which the
+module names appear. The first list (an extern statement)
+declares the module names to be external. The second (a stat-
+ic int statement) names the modules and defines the sequence
+in which they are called. There is no need for these lists
+to be in the same order, but it is probably a good idea to keep
+them that way in the interest of clarity. Since there are no
+cross-linkages between modules, new modules may be added,
+or old ones deleted, simply by editing the lists, with one
+exception: section s26, which pokes around at the hardware
+trying to figure out the characteristics of the machine that
+it is running on, saves information that is subsequently
+used by sections s626, s72, and s757. If this program is
+to be broken up into smallish pieces, say for running on
+a microcomputer, take care to see that s26 is called before
+calling any of the latter three sections. The size
+of the lists, i.e., the number of modules to be called, is
+not explicitly specified as a program parameter, but is
+determined dynamically using the sizeof operator.
+
+ Communication between the main program and the modules
+takes place in two ways. In all cases, a pointer to a structure
+is passed to the called module. The structure contains flags
+that will determine the type of information to be published
+by the module, and fields that may be written in by the
+module. The former include "flgm" and "flgd", which, if set
+to a nonzero value, specify that machine dependencies are to
+be announced or that error messages are to be printed, re-
+spectively. The called module's name, and the hardware char-
+acteristics probed in s26() comprise the latter.
+
+
+ Also, in all cases, a return code is returned by the called
+module. A return code of zero indicates that all has gone well;
+nonzero indicates otherwise. Since more than one type of error
+may be detected by a module, the return code is a composite
+of error indicators, which, individually, are given as numbers
+that are powers of two. Thus, a return code of 10 indicates
+that two specific errors, 8 and 2, were detected. Whether or
+not the codes returned by the modules are printed by the main
+program is determined by setting "flgs" to 1 (resp. 0).
+
+ The entire logic of the main program is contained in the
+half-dozen or so lines at the end. The somewhat cryptic
+statement:
+
+ d0.rrc = (*sec[j])(pd0);
+
+in the for loop calls the modules. The rest of the code is
+reasonably straightforward.
+
+ Finally, in each of the modules, there is the following
+prologue:
+
+ snnn(pd0)
+ struct defs *pd0;
+ {
+ static char snnner[] = "snnn,er%d\n";
+ static char qsnnn[8] = "snnn ";
+ char *ps, *pt;
+ int rc;
+
+ rc = 0;
+ ps = qsnnn;
+ pt = pd0->rfs;
+ while(*pt++ = *ps++);
+
+used for housekeeping, handshaking and module initialization.
+
+ */
+ extern
+ s22(),
+ s241(),
+ s243(),
+ s244(),
+ s25(),
+ s26(),
+ s4(),
+ s61(),
+ s626(),
+ s71(),
+ s72(),
+ s757(),
+ s7813(),
+ s714(),
+ s715(),
+ s81(),
+ s84(),
+ s85(),
+ s86(),
+ s88(),
+ s9()
+ ;
+
+ int j;
+ static int (*sec[])() = {
+ s22,
+ s241,
+ s243,
+ s244,
+ s25,
+ s26,
+ s4,
+ s61,
+ s626,
+ s71,
+ s72,
+ s757,
+ s7813,
+ s714,
+ s715,
+ s81,
+ s84,
+ s85,
+ s86,
+ s88,
+ s9
+ };
+
+ static struct defs d0, *pd0;
+
+ d0.flgs = 1; /* These flags dictate */
+ d0.flgm = 1; /* the verbosity of */
+ d0.flgd = 1; /* the program. */
+ d0.flgl = 1;
+
+ pd0 = &d0;
+
+ for (j=0; j<sizeof(sec) / sizeof(sec[0]); j++) {
+ d0.rrc = (*sec[j])(pd0);
+ d0.crc = d0.crc+d0.rrc;
+ if(d0.flgs != 0) printf("Section %s returned %d.\n",d0.rfs,d0.rrc);
+ }
+
+ if(d0.crc == 0) printf("\nNo errors detected.\n");
+ else printf("\nFailed.\n");
+ return 0;
+}
+s22(pd0) /* 2.2 Identifiers (Names) */
+struct defs *pd0;
+{
+ int a234, a;
+ int _, _234, A, rc;
+
+ static char s22er[] = "s22,er%d\n";
+ static char qs22[8] = "s22 ";
+
+ char *ps, *pt;
+ /* Initialize */
+
+ rc = 0;
+ ps = qs22;
+ pt = pd0 -> rfs;
+ while (*pt++ = *ps++);
+
+ /* An identifier is a sequence of letters and digits;
+ the first character must be a letter. The under-
+ score _ counts as a letter. */
+
+ a=1;
+ _=2;
+ _234=3;
+ a234=4;
+ if(a+_+_234+a234 != 10) {
+ rc = rc+1;
+ if(pd0->flgd != 0) printf(s22er,1);
+ }
+
+ /* Upper and lower case letters are different. */
+
+ A = 2;
+ if (A == a) {
+ rc = rc+4;
+ if (pd0->flgd != 0) printf(s22er,4);
+ }
+
+ return(rc);
+}
+s241(pd0) /* 2.4.1 Integer constants
+ 2.4.2 Explicit long constants */
+struct defs *pd0;
+{
+ long pow2();
+ static char s241er[] = "s241,er%d\n";
+ static char qs241[8] = "s241 ";
+ char *ps, *pt;
+ int rc, j, lrc;
+ static long g[39] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,6,0,8,0,12,0,16,0,18,0,20,0,24,
+ 0,28,0,30,0,32,0,36};
+ long d[39], o[39], x[39];
+
+ rc = 0;
+ lrc = 0;
+ ps = qs241;
+ pt = pd0 -> rfs;
+ while (*pt++ = *ps++);
+
+ /* An integer constant consisting of a sequence of digits is
+ taken to be octal if it begins with 0 (digit zero), decimal
+ otherwise. */
+
+ if ( 8 != 010
+ || 16 != 020
+ || 24 != 030
+ || 32 != 040
+ || 40 != 050
+ || 48 != 060
+ || 56 != 070
+ || 64 != 0100
+ || 72 != 0110
+ || 80 != 0120
+ || 9 != 0011
+ || 17 != 0021
+ || 25 != 0031
+ || 33 != 0041
+ || 41 != 0051
+ || 49 != 0061
+ || 57 != 0071
+ || 65 != 0101
+ || 73 != 0111
+ || 81 != 0121 ){
+
+ rc = rc+1;
+ if( pd0->flgd != 0 ) printf(s241er,1);
+ }
+
+ /* A sequence of digits preceded by 0x or 0X (digit zero)
+ is taken to be a hexadecimal integer. The hexadecimal
+ digits include a or A through f or F with values 10
+ through 15. */
+
+ if ( 0x00abcdef != 0xabcdef
+ || 0xabcdef != 0Xabcdef || 0Xabcdef != 0XAbcdef
+ || 0XAbcdef != 0XABcdef || 0XABcdef != 0XABCdef
+ || 0XABCdef != 0XABCDef || 0XABCDef != 0XABCDEf
+ || 0XABCDEf != 0XABCDEF || 0xABCDEF != 11259375 ){
+
+ rc = rc+2;
+ if( pd0->flgd != 0 ) printf(s241er,2);
+ }
+
+ /* A decimal constant whose value exceeds the largest signed
+ machine integer is taken to be long; an octal or hex con-
+ stant which exceeds the largest unsigned machine integer
+ is likewise taken to be long. */
+
+ if ( sizeof 010000000000 != sizeof(long) /* 2**30 */
+ || sizeof 1073741824 != sizeof(long) /* ditto */
+ || sizeof 0x40000000 != sizeof(long) ){ /* " */
+
+ rc = rc+4;
+ if( pd0->flgd != 0 ) printf(s241er,4);
+ }
+
+ /* A decimal, octal, or hexadecimal constant immediately followed
+ by l (letter ell) or L is a long constant. */
+
+ if ( sizeof 67l != sizeof(long)
+ || sizeof 67L != sizeof(long)
+ || sizeof 067l != sizeof(long)
+ || sizeof 067L != sizeof(long)
+ || sizeof 0X67l != sizeof(long)
+ || sizeof 0x67L != sizeof(long) ){
+
+ rc = rc+8;
+ if( pd0 -> flgd != 0 ) printf(s241er,8);
+ }
+
+ /* Finally, we test to see that decimal (d), octal (o),
+ and hexadecimal (x) constants representing the same values
+ agree among themselves, and with computed values, at spec-
+ ified points over an appropriate range. The points select-
+ ed here are those with the greatest potential for caus-
+ ing trouble, i.e., zero, 1-16, and values of 2**n and
+ 2**n - 1 where n is some multiple of 4 or 6. Unfortunately,
+ just what happens when a value is too big to fit in a
+ long is undefined; however, it would be nice if what
+ happened were at least consistent... */
+
+ for ( j=0; j<17; j++ ) g[j] = j;
+ for ( j=18; j<39; ) {
+ g[j] = pow2(g[j]);
+ g[j-1] = g[j] - 1;
+ j = j+2;
+ }
+
+ d[0] = 0; o[0] = 00; x[0] = 0x0;
+ d[1] = 1; o[1] = 01; x[1] = 0x1;
+ d[2] = 2; o[2] = 02; x[2] = 0x2;
+ d[3] = 3; o[3] = 03; x[3] = 0x3;
+ d[4] = 4; o[4] = 04; x[4] = 0x4;
+ d[5] = 5; o[5] = 05; x[5] = 0x5;
+ d[6] = 6; o[6] = 06; x[6] = 0x6;
+ d[7] = 7; o[7] = 07; x[7] = 0x7;
+ d[8] = 8; o[8] = 010; x[8] = 0x8;
+ d[9] = 9; o[9] = 011; x[9] = 0x9;
+ d[10] = 10; o[10] = 012; x[10] = 0xa;
+ d[11] = 11; o[11] = 013; x[11] = 0xb;
+ d[12] = 12; o[12] = 014; x[12] = 0xc;
+ d[13] = 13; o[13] = 015; x[13] = 0xd;
+ d[14] = 14; o[14] = 016; x[14] = 0xe;
+ d[15] = 15; o[15] = 017; x[15] = 0xf;
+ d[16] = 16; o[16] = 020; x[16] = 0x10;
+ d[17] = 63; o[17] = 077; x[17] = 0x3f;
+ d[18] = 64; o[18] = 0100; x[18] = 0x40;
+ d[19] = 255; o[19] = 0377; x[19] = 0xff;
+ d[20] = 256; o[20] = 0400; x[20] = 0x100;
+ d[21] = 4095; o[21] = 07777; x[21] = 0xfff;
+ d[22] = 4096; o[22] = 010000; x[22] = 0x1000;
+ d[23] = 65535; o[23] = 0177777; x[23] = 0xffff;
+ d[24] = 65536; o[24] = 0200000; x[24] = 0x10000;
+ d[25] = 262143; o[25] = 0777777; x[25] = 0x3ffff;
+ d[26] = 262144; o[26] = 01000000; x[26] = 0x40000;
+ d[27] = 1048575; o[27] = 03777777; x[27] = 0xfffff;
+ d[28] = 1048576; o[28] = 04000000; x[28] = 0x100000;
+ d[29] = 16777215; o[29] = 077777777; x[29] = 0xffffff;
+ d[30] = 16777216; o[30] = 0100000000; x[30] = 0x1000000;
+ d[31] = 268435455; o[31] = 01777777777; x[31] = 0xfffffff;
+ d[32] = 268435456; o[32] = 02000000000; x[32] = 0x10000000;
+ d[33] = 1073741823; o[33] = 07777777777; x[33] = 0x3fffffff;
+ d[34] = 1073741824; o[34] = 010000000000; x[34] = 0x40000000;
+ d[35] = 4294967295; o[35] = 037777777777; x[35] = 0xffffffff;
+ d[36] = 4294967296; o[36] = 040000000000; x[36] = 0x100000000;
+ d[37] = 68719476735; o[37] = 0777777777777; x[37] = 0xfffffffff;
+ d[38] = 68719476736; o[38] = 01000000000000; x[38] = 0x1000000000;
+
+ /* WHEW! */
+
+ for (j=0; j<39; j++){
+ if ( g[j] != d[j]
+ || d[j] != o[j]
+ || o[j] != x[j]) {
+
+ if( pd0 -> flgm != 0 ) {
+/* printf(s241er,16); save in case opinions change... */
+ printf("Decimal and octal/hex constants sometimes give\n");
+ printf(" different results when assigned to longs.\n");
+ }
+/* lrc = 1; save... */
+ }
+ }
+
+ if (lrc != 0) rc =16;
+
+ return rc;
+}
+
+long pow2(n) /* Calculate 2**n by multiplying, not shifting */
+long n;
+{
+ long s;
+ s = 1;
+ while(n--) s = s*2;
+ return s;
+}
+s243(pd0) /* 2.4.3 Character constants */
+struct defs *pd0;
+{
+ static char s243er[] = "s243,er%d\n";
+ static char qs243[8] = "s243 ";
+ char *ps, *pt;
+ int rc;
+ char chars[256];
+
+ rc = 0;
+ ps = qs243;
+ pt = pd0->rfs;
+ while(*pt++ = *ps++);
+
+ /* One of the problems that arises when testing character constants
+ is that of definition: What, exactly, is the character set?
+ In order to guarantee a certain amount of machine independence,
+ the character set we will use here is the set of characters writ-
+ able as escape sequences in C, plus those characters used in writ-
+ ing C programs, i.e.,
+
+ letters:
+ ABCDEFGHIJKLMNOPQRSTUVWXYZ 26
+ abcdefghijklmnopqrstuvwxyz 26
+ numbers:
+ 0123456789 10
+ special characters:
+ ~!"#%&()_=-^|{}[]+;*:<>,.?/ 27
+ extra special characters:
+ newline \n
+ horizontal tab \t
+ backspace \b
+ carriage return \r
+ form feed \f
+ backslash \\
+ single quote \' 7
+ blank & NUL 2
+ ---
+ 98
+
+ Any specific implementation of C may of course support additional
+ characters. */
+
+ /* Since the value of a character constant is the numerical value
+ of the character in the machine's character set, there should
+ be a one-to-one correspondence between characters and values. */
+
+ zerofill(chars);
+
+ chars['a'] = 1; chars['A'] = 1; chars['~'] = 1; chars['0'] = 1;
+ chars['b'] = 1; chars['B'] = 1; chars['!'] = 1; chars['1'] = 1;
+ chars['c'] = 1; chars['C'] = 1; chars['"'] = 1; chars['2'] = 1;
+ chars['d'] = 1; chars['D'] = 1; chars['#'] = 1; chars['3'] = 1;
+ chars['e'] = 1; chars['E'] = 1; chars['%'] = 1; chars['4'] = 1;
+ chars['f'] = 1; chars['F'] = 1; chars['&'] = 1; chars['5'] = 1;
+ chars['g'] = 1; chars['G'] = 1; chars['('] = 1; chars['6'] = 1;
+ chars['h'] = 1; chars['H'] = 1; chars[')'] = 1; chars['7'] = 1;
+ chars['i'] = 1; chars['I'] = 1; chars['_'] = 1; chars['8'] = 1;
+ chars['j'] = 1; chars['J'] = 1; chars['='] = 1; chars['9'] = 1;
+ chars['k'] = 1; chars['K'] = 1; chars['-'] = 1;
+ chars['l'] = 1; chars['L'] = 1; chars['^'] = 1;
+ chars['m'] = 1; chars['M'] = 1; chars['|'] = 1; chars['\n'] = 1;
+ chars['n'] = 1; chars['N'] = 1; chars['\t'] = 1;
+ chars['o'] = 1; chars['O'] = 1; chars['{'] = 1; chars['\b'] = 1;
+ chars['p'] = 1; chars['P'] = 1; chars['}'] = 1; chars['\r'] = 1;
+ chars['q'] = 1; chars['Q'] = 1; chars['['] = 1; chars['\f'] = 1;
+ chars['r'] = 1; chars['R'] = 1; chars[']'] = 1;
+ chars['s'] = 1; chars['S'] = 1; chars['+'] = 1; chars['\\'] = 1;
+ chars['t'] = 1; chars['T'] = 1; chars[';'] = 1; chars['\''] = 1;
+ chars['u'] = 1; chars['U'] = 1; chars['*'] = 1;
+ chars['v'] = 1; chars['V'] = 1; chars[':'] = 1; chars['\0'] = 1;
+ chars['w'] = 1; chars['W'] = 1; chars['<'] = 1; chars[' '] = 1;
+ chars['x'] = 1; chars['X'] = 1; chars['>'] = 1;
+ chars['y'] = 1; chars['Y'] = 1; chars[','] = 1;
+ chars['z'] = 1; chars['Z'] = 1; chars['.'] = 1;
+ chars['?'] = 1;
+ chars['/'] = 1;
+
+ if(sumof(chars) != 98){
+ rc = rc+1;
+ if(pd0->flgd != 0) printf(s243er,1);
+ }
+
+ /* Finally, the escape \ddd consists of the backslash followed
+ by 1, 2, or 3 octal digits which are taken to specify the
+ desired character. */
+
+ if( '\0' != 0 || '\01' != 1 || '\02' != 2
+ || '\03' != 3 || '\04' != 4 || '\05' != 5
+ || '\06' != 6 || '\07' != 7 || '\10' != 8
+ || '\17' != 15 || '\20' != 16 || '\77' != 63
+ || '\100' != 64 || '\177' != 127 ){
+
+ rc = rc+8;
+ if(pd0->flgd != 0) printf(s243er,8);
+ }
+
+ return rc;
+}
+zerofill(x)
+char *x;
+{
+ int j;
+
+ for (j=0; j<256; j++) *x++ = 0;
+}
+sumof(x)
+char *x;
+{
+ char *p;
+ int total, j;
+
+ p = x;
+ total = 0;
+
+ for(j=0; j<256; j++) total = total+ *p++;
+ return total;
+}
+s244(pd0)
+struct defs *pd0;
+{
+ double a[8];
+ int rc, lrc, j;
+ static char s244er[] = "s244,er%d\n";
+ static char qs244[8] = "s244 ";
+ char *ps, *pt;
+
+ ps = qs244;
+ pt = pd0->rfs;
+ while(*pt++ = *ps++);
+ rc = 0;
+ lrc = 0;
+
+ /* Unfortunately, there's not a lot we can do with floating constants.
+ We can check to see that the various representations can be com-
+ piled, that the conversion is such that they yield the same hard-
+ ware representations in all cases, and that all representations
+ thus checked are double precision. */
+
+ a[0] = .1250E+04;
+ a[1] = 1.250E3;
+ a[2] = 12.50E02;
+ a[3] = 125.0e+1;
+ a[4] = 1250e00;
+ a[5] = 12500.e-01;
+ a[6] = 125000e-2;
+ a[7] = 1250.;
+
+ lrc = 0;
+ for (j=0; j<7; j++) if(a[j] != a[j+1]) lrc = 1;
+
+ if(lrc != 0) {
+ if(pd0->flgd != 0) printf(s244er,1);
+ rc = rc+1;
+ }
+
+ if ( (sizeof .1250E+04 ) != sizeof(double)
+ || (sizeof 1.250E3 ) != sizeof(double)
+ || (sizeof 12.50E02 ) != sizeof(double)
+ || (sizeof 1.250e+1 ) != sizeof(double)
+ || (sizeof 1250e00 ) != sizeof(double)
+ || (sizeof 12500.e-01) != sizeof(double)
+ || (sizeof 125000e-2 ) != sizeof(double)
+ || (sizeof 1250. ) != sizeof(double)){
+
+ if(pd0->flgd != 0) printf(s244er,2);
+ rc = rc+2;
+ }
+
+ return rc;
+}
+s25(pd0)
+struct defs *pd0;
+{
+ char *s, *s2;
+ int rc, lrc, j;
+ static char s25er[] = "s25,er%d\n";
+ static char qs25[8] = "s25 ";
+ char *ps, *pt;
+
+ ps = qs25;
+ pt = pd0->rfs;
+ while(*pt++ = *ps++);
+ rc = 0;
+
+ /* A string is a sequence of characters surrounded by double
+ quotes, as in "...". */
+
+ s = "...";
+
+ /* A string has type "array of characters" and storage class
+ static and is initialized with the given characters. */
+
+ if ( s[0] != s[1] || s[1] != s[2]
+ || s[2] != '.' ) {
+
+ rc = rc+1;
+ if(pd0->flgd != 0) printf(s25er,1);
+ }
+
+ /* The compiler places a null byte \0 at the end of each string
+ so the program which scans the string can find its end. */
+
+ if( s[3] != '\0' ){
+ rc = rc+4;
+ if(pd0->flgd != 0) printf(s25er,4);
+ }
+
+ /* In a string, the double quote character " must be preceded
+ by a \. */
+
+ if( ".\"."[1] != '"' ){
+ rc = rc+8;
+ if(pd0->flgd != 0) printf(s25er,8);
+ }
+
+ /* In addition, the same escapes described for character constants
+ may be used. */
+
+ s = "\n\t\b\r\f\\\'";
+
+ if( s[0] != '\n'
+ || s[1] != '\t'
+ || s[2] != '\b'
+ || s[3] != '\r'
+ || s[4] != '\f'
+ || s[5] != '\\'
+ || s[6] != '\'' ){
+
+ rc = rc+16;
+ if( pd0->flgd != 0) printf(s25er,16);
+ }
+
+ /* Finally, a \ and an immediately following newline are ignored */
+
+ s2 = "queep!";
+ s = "queep!";
+
+ lrc = 0;
+ for (j=0; j<sizeof "queep!"; j++) if(s[j] != s2[j]) lrc = 1;
+ if (lrc != 0){
+ rc = rc+32;
+ if(pd0->flgd != 0) printf(s25er,32);
+ }
+ return rc;
+}
+s26(pd0) /* 2.6 Hardware Characteristics */
+struct defs *pd0;
+{
+ static char qs26[8] = "s26 ";
+ char *ps, *pt;
+ char c0, c1;
+ float temp, one, delta;
+ double tempd, oned;
+ static char s[] = "%3d bits in %ss.\n";
+ static char s2[] = "%e is the least number that can be added to 1. (%s).\n";
+
+ ps = qs26;
+ pt = pd0->rfs;
+
+ while(*pt++ = *ps++);
+
+ /* Here, we shake the machinery a little to see what falls
+ out. First, we find out how many bits are in a char. */
+
+ pd0->cbits = 0;
+ c0 = 0;
+ c1 = 1;
+
+ while(c0 != c1) {
+ c1 = c1<<1;
+ pd0->cbits = pd0->cbits+1;
+ }
+ /* That information lets us determine the size of everything else. */
+
+ pd0->ibits = pd0->cbits * sizeof(int);
+ pd0->sbits = pd0->cbits * sizeof(short);
+ pd0->lbits = pd0->cbits * sizeof(long);
+ pd0->ubits = pd0->cbits * sizeof(unsigned);
+ pd0->fbits = pd0->cbits * sizeof(float);
+ pd0->dbits = pd0->cbits * sizeof(double);
+
+ /* We have now almost reconstructed the table in section 2.6, the
+ exception being the range of the floating point hardware.
+ Now there are just so many ways to conjure up a floating point
+ representation system that it's damned near impossible to guess
+ what's going on by writing a program to interpret bit patterns.
+ Further, the information isn't all that useful, if we consider
+ the fact that machines that won't handle numbers between 10**30
+ and 10**-30 are very hard to find, and that people playing with
+ numbers outside that range have a lot more to worry about than
+ just the capacity of the characteristic.
+
+ A much more useful measure is the precision, which can be ex-
+ pressed in terms of the smallest number that can be added to
+ 1. without loss of significance. We calculate that here, for
+ float and double. */
+
+ one = 1.;
+ delta = 1.;
+ temp = 0.;
+ while(temp != one) {
+ temp = one+delta;
+ delta = delta/2.;
+ }
+ pd0->fprec = delta * 4.;
+ oned = 1.;
+ delta = 1.;
+ tempd = 0.;
+ while(tempd != oned) {
+ tempd = oned+delta;
+ delta = delta/2.;
+ }
+ pd0->dprec = delta * 4.;
+
+ /* Now, if anyone's interested, we publish the results. */
+
+ if(pd0->flgm != 0) {
+ printf(s,pd0->cbits,"char");
+ printf(s,pd0->ibits,"int");
+ printf(s,pd0->sbits,"short");
+ printf(s,pd0->lbits,"long");
+ printf(s,pd0->ubits,"unsigned");
+ printf(s,pd0->fbits,"float");
+ printf(s,pd0->dbits,"double");
+ printf(s2,pd0->fprec,"float");
+ printf(s2,pd0->dprec,"double");
+ }
+ /* Since we are only exploring and perhaps reporting, but not
+ testing any features, we cannot return an error code. */
+
+ return 0;
+}
+int extvar;
+s4(pd0) /* 4. What's in a name? */
+struct defs *pd0;
+{
+ static char s4er[] = "s4,er%d\n";
+ static char qs4[8] = "s4 ";
+ char *ps, *pt;
+ int j, rc;
+
+ short sint; /* short integer, for size test */
+ int pint; /* plain */
+ long lint; /* long */
+ unsigned target;
+ unsigned int mask;
+
+ rc = 0;
+ ps = qs4;
+ pt = pd0->rfs;
+
+ while(*pt++ = *ps++);
+
+/* There are four declarable storage classes: automatic,
+static, external, and register. Automatic variables have
+been dealt with extensively thus far, and will not be specif-
+ically treated in this section. Register variables are treated
+in section s81.
+
+ Static variables are local to a block, but retain their
+values upon reentry to a block, even after control has left
+the block. */
+
+ for (j=0; j<3; j++)
+ if(svtest(j) != zero()){
+ rc = 1;
+ if(pd0->flgd != 0) printf(s4er,1);
+ }
+ ;
+
+/* External variables exist and retain their values throughout
+the execution of the entire program, and may be used for comm-
+unication between functions, even separately compiled functions.
+ */
+
+ setev();
+ if(testev() != 0){
+ rc=rc+2;
+ if(pd0->flgd != 0) printf(s4er,2);
+ }
+/*
+ Characters have been tested elsewhere (in s243).
+
+ Up to three sizes of integer, declared short int, int, and
+long int, are available. Longer integers provide no less storage
+than shorter ones, but implementation may make either short
+integers, or long integers, or both, equivalent to plain
+integers.
+ */
+
+ if(sizeof lint < sizeof pint || sizeof pint < sizeof sint){
+
+ rc = rc+4;
+ if(pd0->flgd != 0) printf(s4er,4);
+ }
+
+/* Unsigned integers, declared unsigned, obey the laws of
+arithmetic modulo 2**n, where n is the number of bits in the
+implementation */
+
+ target = ~0U;
+ mask = 1;
+
+ for(j=0; j<(sizeof target)*pd0->cbits; j++){
+
+ mask = mask&target;
+ target = target>>1;
+ }
+
+ if(mask != 1 || target != 0){
+
+ rc = rc+8;
+ if(pd0->flgd != 0) printf(s4er,8);
+ }
+
+ return rc;
+}
+svtest(n)
+int n;
+{
+ static k;
+ int rc;
+ switch (n) {
+
+ case 0: k = 1978;
+ rc = 0;
+ break;
+
+ case 1: if(k != 1978) rc = 1;
+ else{
+ k = 1929;
+ rc = 0;
+ }
+ break;
+
+ case 2: if(k != 1929) rc = 1;
+ else rc = 0;
+ break;
+ }
+ return rc;
+}
+zero(){ /* Returns a value of zero, possibly */
+ static k; /* with side effects, as it's called */
+ int rc; /* alternately with svtest, above, */
+ k = 2; /* and has the same internal storage */
+ rc = 0; /* requirements. */
+ return rc;
+}
+testev(){
+ if(extvar != 1066) return 1;
+ else return 0;
+}
+s61(pd0) /* Characters and integers */
+struct defs *pd0;
+{
+ static char s61er[] = "s61,er%d\n";
+ static char qs61[8] = "s61 ";
+ short from, shortint;
+ long int to, longint;
+ int rc, lrc;
+ int j;
+ char fromc, charint;
+ char *wd, *pc[6];
+
+ static char upper_alpha[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+ static char lower_alpha[] = "abcdefghijklmnopqrstuvwxyz";
+ static char numbers[] = "0123456789";
+ static char special_characters[] = "~!\"#%&()_=-^|{}[]+;*:<>,.?/";
+ static char extra_special_characters[] = "\n\t\b\r\f\\\'";
+ static char blank_and_NUL[] = " \0";
+
+ char *ps, *pt;
+ ps = qs61;
+ pt = pd0->rfs;
+ rc = 0;
+ while (*pt++ = *ps++);
+
+/* A character or a short integer may be used wherever
+an integer may be used. In all cases, the value is converted
+to integer. This principle is extensively used throughout this
+program, and will not be explicitly tested here. */
+
+/* Conversion of a shorter integer to a longer always
+involves sign extension. */
+
+ from = -19;
+ to = from;
+
+ if(to != -19){
+ rc = rc+1;
+ if(pd0->flgd != 0) printf(s61er,1);
+ }
+
+/* It is guaranteed that a member of the standard char-
+acter set is nonnegative. */
+
+ pc[0] = upper_alpha;
+ pc[1] = lower_alpha;
+ pc[2] = numbers;
+ pc[3] = special_characters;
+ pc[4] = extra_special_characters;
+ pc[5] = blank_and_NUL;
+
+ lrc = 0;
+ for (j=0; j<6; j++)
+ while(*pc[j]) if(*pc[j]++ < 0) lrc =1;
+
+ if(lrc != 0){
+ rc=rc+2;
+ if(pd0->flgd != 0) printf(s61er,2);
+ }
+
+/* When a longer integer is converted to a shorter or
+to a char, it is truncated on the left; excess bits are
+simply discarded. */
+
+ longint = 1048579; /* =2**20+3 */
+ shortint = longint;
+ charint = longint;
+
+ if((shortint != longint && shortint != 3) ||
+ (charint != longint && charint != 3)) {
+ rc = rc+8;
+ if(pd0->flgd != 0) printf(s61er,8);
+ }
+
+ return rc;
+}
+s626(pd0) /* 6.2 Float and double */
+ /* 6.3 Floating and integral */
+ /* 6.4 Pointers and integers */
+ /* 6.5 Unsigned */
+ /* 6.6 Arithmetic conversions */
+struct defs *pd0;
+{
+ static char s626er[] = "s626,er%d\n";
+ static char qs626[8] = "s626 ";
+ int rc;
+ char *ps, *pt;
+ float eps, f1, f2, f3, f4, f;
+ long lint1, lint2, l, ls;
+ char c, t[28], t0;
+ short s;
+ int is, i, j;
+ unsigned u, us;
+ double d, ds;
+ ps = qs626;
+ pt = pd0->rfs;
+ rc = 0;
+ while (*pt++ = *ps++);
+
+ /* Conversions of integral values to floating type are
+ well-behaved. */
+
+ f1 = 1.;
+ lint1 = 1.;
+ lint2 = 1.;
+
+ for(j=0;j<pd0->lbits-2;j++){
+ f1 = f1*2;
+ lint2 = (lint2<<1)|lint1;
+ }
+ f2 = lint2;
+ f1 = (f1-f2)/f1;
+ if(f1>2.*pd0->fprec){
+
+ rc = rc+2;
+ if(pd0->flgd != 0) printf(s626er,2);
+ }
+
+ /* Pointer-integer combinations are discussed in s74,
+ "Additive operators". The unsigned-int combination
+ appears below. */
+
+ c = 125;
+ s = 125;
+ i = 125; is = 15625;
+ u = 125; us = 15625;
+ l = 125; ls = 15625;
+ f = 125.;
+ d = 125.; ds = 15625.;
+
+ for(j=0;j<28;j++) t[j] = 0;
+
+ if(c*c != is) t[ 0] = 1;
+ if(s*c != is) t[ 1] = 1;
+ if(s*s != is) t[ 2] = 1;
+ if(i*c != is) t[ 3] = 1;
+ if(i*s != is) t[ 4] = 1;
+ if(i*i != is) t[ 5] = 1;
+ if(u*c != us) t[ 6] = 1;
+ if(u*s != us) t[ 7] = 1;
+ if(u*i != us) t[ 8] = 1;
+ if(u*u != us) t[ 9] = 1;
+ if(l*c != ls) t[10] = 1;
+ if(l*s != ls) t[11] = 1;
+ if(l*i != ls) t[12] = 1;
+ if(l*u != us) t[13] = 1;
+ if(l*l != ls) t[14] = 1;
+ if(f*c != ds) t[15] = 1;
+ if(f*s != ds) t[16] = 1;
+ if(f*i != ds) t[17] = 1;
+ if(f*u != ds) t[18] = 1;
+ if(f*l != ds) t[19] = 1;
+ if(f*f != ds) t[20] = 1;
+ if(d*c != ds) t[21] = 1;
+ if(d*s != ds) t[22] = 1;
+ if(d*i != ds) t[23] = 1;
+ if(d*u != ds) t[24] = 1;
+ if(d*l != ds) t[25] = 1;
+ if(d*f != ds) t[26] = 1;
+ if(d*d != ds) t[27] = 1;
+
+ t0 = 0;
+ for(j=0; j<28; j++) t0 = t0+t[j];
+
+ if(t0 != 0){
+
+ rc = rc+4;
+ if(pd0->flgd != 0){
+
+ printf(s626er,4);
+ printf(" key=");
+ for(j=0;j<28;j++) printf("%d",t[j]);
+ printf("\n");
+ }
+ }
+
+ /* When an unsigned integer is converted to long,
+ the value of the result is the same numerically
+ as that of the unsigned integer. */
+
+ l = (unsigned)0100000;
+ if((long)l > (unsigned)0100000){
+
+ rc = rc+8;
+ if(pd0->flgd != 0) printf(s626er,8);
+ }
+
+ return rc;
+}
+s71(pd0) /* 7.1 Primary expressions */
+struct defs *pd0;
+{
+ static char s71er[] = "s71,er%d\n";
+ static char qs71[8] = "s71 ";
+ int rc;
+ char *ps, *pt;
+ static char q = 'q';
+ int x[10], McCarthy(), clobber(), a, b, *p;
+ ps = qs71;
+ pt = pd0->rfs;
+ rc = 0;
+ while (*pt++ = *ps++);
+
+/* Testing of expressions and operators is quite complicated,
+ because (a) problems are apt to surface in queer combinations
+ of operators and operands, rather than in isolation,
+ and (b) the number of expressions needed to provoke a case
+ of improper behaviour may be quite large. Hence, we take the
+ following approach: for this section, and for subsequent
+ sections through 7.15, we will check the primitive operations
+ in isolation, thus verifying that the primitives work,
+ after a fashion. The job of testing combinations, we will
+ leave to a separate, machine-generated program, to be included
+ in the C test package at some later date.
+ */
+
+/* A string is a primary expression. The identifier points to
+ the first character of a string.
+ */
+
+ if(*"queep" != q){
+ rc = rc+1;
+ if(pd0->flgd != 0) printf(s71er,1);
+ }
+/* A parenthesized expression is a primary expression whose
+ type and value are the same as those of the unadorned
+ expression.
+ */
+ if((2+3) != 2+3) {
+ rc = rc+2;
+ if(pd0->flgd != 0) printf(s71er,2);
+ }
+
+/* A primary expression followed by an expression in square
+ brackets is a primary expression. The intuitive meaning is
+ that of a subscript. The expression E1[E2] is identical
+ (by definition) to *((E1)+(E2)).
+ */
+
+ x[5] = 1942;
+ if(x[5] != 1942 || x[5] != *((x)+(5))){
+ rc = rc+4;
+ if(pd0->flgd != 0) printf(s71er,4);
+ }
+
+/* If the various flavors of function calls didn't work, we
+ would never have gotten this far; however, we do need to
+ show that functions can be recursive...
+ */
+
+ if ( McCarthy(-5) != 91){
+ rc = rc+8;
+ if(pd0->flgd != 0) printf(s71er,8);
+ }
+
+/* and that argument passing is strictly by value. */
+
+ a = 2;
+ b = 3;
+ p = &b;
+
+ clobber(a,p);
+
+ if(a != 2 || b != 2){
+ rc = rc+16;
+ if(pd0->flgd != 0) printf(s71er,16);
+ }
+
+/* Finally, structures and unions are addressed thusly: */
+
+ if(pd0->dprec != (*pd0).dprec){
+ rc = rc+32;
+ if(pd0->flgd != 0) printf(s71er,32);
+ }
+
+ return rc;
+}
+McCarthy(x)
+int x;
+{
+ if(x>100) return x-10;
+ else return McCarthy( McCarthy(x+11));
+}
+clobber(x,y)
+int x, *y;
+{
+ x = 3;
+ *y = 2;
+}
+s714(pd0) /* 7.14 Assignment operators */
+struct defs *pd0;
+{
+ static char f[] = "Local error %d.\n";
+ static char s714er[] = "s714,er%d\n";
+ static char qs714[8] = "s714 ";
+ register int prlc, lrc;
+ int rc;
+ char cl, cr;
+ short sl, sr;
+ int il, ir;
+ long ll, lr;
+ unsigned ul, ur;
+ float fl, fr;
+ double dl, dr;
+ char *ps, *pt;
+ ps = qs714;
+ pt = pd0->rfs;
+ rc = 0;
+ lrc = 0;
+ prlc = pd0->flgl;
+ while (*pt++ = *ps++);
+
+ /* This section tests the assignment operators.
+
+ It is an exhaustive test of all assignment statements
+ of the form:
+
+ vl op vr
+
+ where vl and vr are variables from the set
+ {char,short,int,long,unsigned,float,double} and op is
+ one of the assignment operators. There are 395 such
+ statements.
+
+ The initial values for the variables have been chosen
+ so that both the initial values and the results will
+ "fit" in just about any implementation, and that the re-
+ sults will be such that they test for the proper form-
+ ation of composite operators, rather than checking for
+ the valid operation of those operators' components.
+ For example, in checking >>=, we want to verify that
+ a right shift and a move take place, rather than
+ whether or not there may be some peculiarities about
+ the right shift. Such tests have been made previously,
+ and to repeat them here would be to throw out a red
+ herring.
+
+ The table below lists the operators, assignment targets,
+ initial values for left and right operands, and the
+ expected values of the results.
+
+
+ = += -= *= /= %= >>= <<= &= ^= |=
+char 2 7 3 10 2 1 1 20 8 6 14
+short 2 7 3 10 2 1 1 20 8 6 14
+int 2 7 3 10 2 1 1 20 8 6 14
+long 2 7 3 10 2 1 1 20 8 6 14
+unsigned 2 7 3 10 2 1 1 20 8 6 14
+float 2 7 3 10 2.5 | |
+double 2 7 3 10 2.5 | |
+ | |
+initial (5,2) | (5,2) | (12,10)
+
+ The following machine-generated program reflects the
+ tests described in the table.
+ */
+
+ cl = 5; cr = 2;
+ cl = cr;
+ if(cl != 2){
+ lrc = 1;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; sr = 2;
+ cl = sr;
+ if(cl != 2){
+ lrc = 2;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; ir = 2;
+ cl = ir;
+ if(cl != 2){
+ lrc = 3;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; lr = 2;
+ cl = lr;
+ if(cl != 2){
+ lrc = 4;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; ur = 2;
+ cl = ur;
+ if(cl != 2){
+ lrc = 5;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; fr = 2;
+ cl = fr;
+ if(cl != 2){
+ lrc = 6;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; dr = 2;
+ cl = dr;
+ if(cl != 2){
+ lrc = 7;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; cr = 2;
+ sl = cr;
+ if(sl != 2){
+ lrc = 8;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; sr = 2;
+ sl = sr;
+ if(sl != 2){
+ lrc = 9;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; ir = 2;
+ sl = ir;
+ if(sl != 2){
+ lrc = 10;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; lr = 2;
+ sl = lr;
+ if(sl != 2){
+ lrc = 11;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; ur = 2;
+ sl = ur;
+ if(sl != 2){
+ lrc = 12;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; fr = 2;
+ sl = fr;
+ if(sl != 2){
+ lrc = 13;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; dr = 2;
+ sl = dr;
+ if(sl != 2){
+ lrc = 14;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; cr = 2;
+ il = cr;
+ if(il != 2){
+ lrc = 15;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; sr = 2;
+ il = sr;
+ if(il != 2){
+ lrc = 16;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; ir = 2;
+ il = ir;
+ if(il != 2){
+ lrc = 17;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; lr = 2;
+ il = lr;
+ if(il != 2){
+ lrc = 18;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; ur = 2;
+ il = ur;
+ if(il != 2){
+ lrc = 19;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; fr = 2;
+ il = fr;
+ if(il != 2){
+ lrc = 20;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; dr = 2;
+ il = dr;
+ if(il != 2){
+ lrc = 21;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; cr = 2;
+ ll = cr;
+ if(ll != 2){
+ lrc = 22;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; sr = 2;
+ ll = sr;
+ if(ll != 2){
+ lrc = 23;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; ir = 2;
+ ll = ir;
+ if(ll != 2){
+ lrc = 24;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; lr = 2;
+ ll = lr;
+ if(ll != 2){
+ lrc = 25;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; ur = 2;
+ ll = ur;
+ if(ll != 2){
+ lrc = 26;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; fr = 2;
+ ll = fr;
+ if(ll != 2){
+ lrc = 27;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; dr = 2;
+ ll = dr;
+ if(ll != 2){
+ lrc = 28;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; cr = 2;
+ ul = cr;
+ if(ul != 2){
+ lrc = 29;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; sr = 2;
+ ul = sr;
+ if(ul != 2){
+ lrc = 30;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; ir = 2;
+ ul = ir;
+ if(ul != 2){
+ lrc = 31;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; lr = 2;
+ ul = lr;
+ if(ul != 2){
+ lrc = 32;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; ur = 2;
+ ul = ur;
+ if(ul != 2){
+ lrc = 33;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; fr = 2;
+ ul = fr;
+ if(ul != 2){
+ lrc = 34;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; dr = 2;
+ ul = dr;
+ if(ul != 2){
+ lrc = 35;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; cr = 2;
+ fl = cr;
+ if(fl != 2){
+ lrc = 36;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; sr = 2;
+ fl = sr;
+ if(fl != 2){
+ lrc = 37;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; ir = 2;
+ fl = ir;
+ if(fl != 2){
+ lrc = 38;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; lr = 2;
+ fl = lr;
+ if(fl != 2){
+ lrc = 39;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; ur = 2;
+ fl = ur;
+ if(fl != 2){
+ lrc = 40;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; fr = 2;
+ fl = fr;
+ if(fl != 2){
+ lrc = 41;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; dr = 2;
+ fl = dr;
+ if(fl != 2){
+ lrc = 42;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; cr = 2;
+ dl = cr;
+ if(dl != 2){
+ lrc = 43;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; sr = 2;
+ dl = sr;
+ if(dl != 2){
+ lrc = 44;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; ir = 2;
+ dl = ir;
+ if(dl != 2){
+ lrc = 45;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; lr = 2;
+ dl = lr;
+ if(dl != 2){
+ lrc = 46;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; ur = 2;
+ dl = ur;
+ if(dl != 2){
+ lrc = 47;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; fr = 2;
+ dl = fr;
+ if(dl != 2){
+ lrc = 48;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; dr = 2;
+ dl = dr;
+ if(dl != 2){
+ lrc = 49;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; cr = 2;
+ cl += cr;
+ if(cl != 7){
+ lrc = 50;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; sr = 2;
+ cl += sr;
+ if(cl != 7){
+ lrc = 51;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; ir = 2;
+ cl += ir;
+ if(cl != 7){
+ lrc = 52;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; lr = 2;
+ cl += lr;
+ if(cl != 7){
+ lrc = 53;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; ur = 2;
+ cl += ur;
+ if(cl != 7){
+ lrc = 54;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; fr = 2;
+ cl += fr;
+ if(cl != 7){
+ lrc = 55;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; dr = 2;
+ cl += dr;
+ if(cl != 7){
+ lrc = 56;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; cr = 2;
+ sl += cr;
+ if(sl != 7){
+ lrc = 57;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; sr = 2;
+ sl += sr;
+ if(sl != 7){
+ lrc = 58;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; ir = 2;
+ sl += ir;
+ if(sl != 7){
+ lrc = 59;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; lr = 2;
+ sl += lr;
+ if(sl != 7){
+ lrc = 60;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; ur = 2;
+ sl += ur;
+ if(sl != 7){
+ lrc = 61;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; fr = 2;
+ sl += fr;
+ if(sl != 7){
+ lrc = 62;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; dr = 2;
+ sl += dr;
+ if(sl != 7){
+ lrc = 63;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; cr = 2;
+ il += cr;
+ if(il != 7){
+ lrc = 64;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; sr = 2;
+ il += sr;
+ if(il != 7){
+ lrc = 65;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; ir = 2;
+ il += ir;
+ if(il != 7){
+ lrc = 66;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; lr = 2;
+ il += lr;
+ if(il != 7){
+ lrc = 67;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; ur = 2;
+ il += ur;
+ if(il != 7){
+ lrc = 68;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; fr = 2;
+ il += fr;
+ if(il != 7){
+ lrc = 69;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; dr = 2;
+ il += dr;
+ if(il != 7){
+ lrc = 70;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; cr = 2;
+ ll += cr;
+ if(ll != 7){
+ lrc = 71;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; sr = 2;
+ ll += sr;
+ if(ll != 7){
+ lrc = 72;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; ir = 2;
+ ll += ir;
+ if(ll != 7){
+ lrc = 73;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; lr = 2;
+ ll += lr;
+ if(ll != 7){
+ lrc = 74;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; ur = 2;
+ ll += ur;
+ if(ll != 7){
+ lrc = 75;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; fr = 2;
+ ll += fr;
+ if(ll != 7){
+ lrc = 76;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; dr = 2;
+ ll += dr;
+ if(ll != 7){
+ lrc = 77;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; cr = 2;
+ ul += cr;
+ if(ul != 7){
+ lrc = 78;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; sr = 2;
+ ul += sr;
+ if(ul != 7){
+ lrc = 79;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; ir = 2;
+ ul += ir;
+ if(ul != 7){
+ lrc = 80;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; lr = 2;
+ ul += lr;
+ if(ul != 7){
+ lrc = 81;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; ur = 2;
+ ul += ur;
+ if(ul != 7){
+ lrc = 82;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; fr = 2;
+ ul += fr;
+ if(ul != 7){
+ lrc = 83;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; dr = 2;
+ ul += dr;
+ if(ul != 7){
+ lrc = 84;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; cr = 2;
+ fl += cr;
+ if(fl != 7){
+ lrc = 85;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; sr = 2;
+ fl += sr;
+ if(fl != 7){
+ lrc = 86;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; ir = 2;
+ fl += ir;
+ if(fl != 7){
+ lrc = 87;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; lr = 2;
+ fl += lr;
+ if(fl != 7){
+ lrc = 88;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; ur = 2;
+ fl += ur;
+ if(fl != 7){
+ lrc = 89;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; fr = 2;
+ fl += fr;
+ if(fl != 7){
+ lrc = 90;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; dr = 2;
+ fl += dr;
+ if(fl != 7){
+ lrc = 91;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; cr = 2;
+ dl += cr;
+ if(dl != 7){
+ lrc = 92;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; sr = 2;
+ dl += sr;
+ if(dl != 7){
+ lrc = 93;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; ir = 2;
+ dl += ir;
+ if(dl != 7){
+ lrc = 94;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; lr = 2;
+ dl += lr;
+ if(dl != 7){
+ lrc = 95;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; ur = 2;
+ dl += ur;
+ if(dl != 7){
+ lrc = 96;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; fr = 2;
+ dl += fr;
+ if(dl != 7){
+ lrc = 97;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; dr = 2;
+ dl += dr;
+ if(dl != 7){
+ lrc = 98;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; cr = 2;
+ cl -= cr;
+ if(cl != 3){
+ lrc = 99;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; sr = 2;
+ cl -= sr;
+ if(cl != 3){
+ lrc = 100;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; ir = 2;
+ cl -= ir;
+ if(cl != 3){
+ lrc = 101;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; lr = 2;
+ cl -= lr;
+ if(cl != 3){
+ lrc = 102;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; ur = 2;
+ cl -= ur;
+ if(cl != 3){
+ lrc = 103;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; fr = 2;
+ cl -= fr;
+ if(cl != 3){
+ lrc = 104;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; dr = 2;
+ cl -= dr;
+ if(cl != 3){
+ lrc = 105;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; cr = 2;
+ sl -= cr;
+ if(sl != 3){
+ lrc = 106;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; sr = 2;
+ sl -= sr;
+ if(sl != 3){
+ lrc = 107;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; ir = 2;
+ sl -= ir;
+ if(sl != 3){
+ lrc = 108;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; lr = 2;
+ sl -= lr;
+ if(sl != 3){
+ lrc = 109;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; ur = 2;
+ sl -= ur;
+ if(sl != 3){
+ lrc = 110;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; fr = 2;
+ sl -= fr;
+ if(sl != 3){
+ lrc = 111;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; dr = 2;
+ sl -= dr;
+ if(sl != 3){
+ lrc = 112;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; cr = 2;
+ il -= cr;
+ if(il != 3){
+ lrc = 113;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; sr = 2;
+ il -= sr;
+ if(il != 3){
+ lrc = 114;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; ir = 2;
+ il -= ir;
+ if(il != 3){
+ lrc = 115;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; lr = 2;
+ il -= lr;
+ if(il != 3){
+ lrc = 116;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; ur = 2;
+ il -= ur;
+ if(il != 3){
+ lrc = 117;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; fr = 2;
+ il -= fr;
+ if(il != 3){
+ lrc = 118;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; dr = 2;
+ il -= dr;
+ if(il != 3){
+ lrc = 119;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; cr = 2;
+ ll -= cr;
+ if(ll != 3){
+ lrc = 120;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; sr = 2;
+ ll -= sr;
+ if(ll != 3){
+ lrc = 121;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; ir = 2;
+ ll -= ir;
+ if(ll != 3){
+ lrc = 122;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; lr = 2;
+ ll -= lr;
+ if(ll != 3){
+ lrc = 123;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; ur = 2;
+ ll -= ur;
+ if(ll != 3){
+ lrc = 124;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; fr = 2;
+ ll -= fr;
+ if(ll != 3){
+ lrc = 125;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; dr = 2;
+ ll -= dr;
+ if(ll != 3){
+ lrc = 126;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; cr = 2;
+ ul -= cr;
+ if(ul != 3){
+ lrc = 127;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; sr = 2;
+ ul -= sr;
+ if(ul != 3){
+ lrc = 128;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; ir = 2;
+ ul -= ir;
+ if(ul != 3){
+ lrc = 129;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; lr = 2;
+ ul -= lr;
+ if(ul != 3){
+ lrc = 130;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; ur = 2;
+ ul -= ur;
+ if(ul != 3){
+ lrc = 131;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; fr = 2;
+ ul -= fr;
+ if(ul != 3){
+ lrc = 132;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; dr = 2;
+ ul -= dr;
+ if(ul != 3){
+ lrc = 133;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; cr = 2;
+ fl -= cr;
+ if(fl != 3){
+ lrc = 134;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; sr = 2;
+ fl -= sr;
+ if(fl != 3){
+ lrc = 135;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; ir = 2;
+ fl -= ir;
+ if(fl != 3){
+ lrc = 136;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; lr = 2;
+ fl -= lr;
+ if(fl != 3){
+ lrc = 137;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; ur = 2;
+ fl -= ur;
+ if(fl != 3){
+ lrc = 138;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; fr = 2;
+ fl -= fr;
+ if(fl != 3){
+ lrc = 139;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; dr = 2;
+ fl -= dr;
+ if(fl != 3){
+ lrc = 140;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; cr = 2;
+ dl -= cr;
+ if(dl != 3){
+ lrc = 141;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; sr = 2;
+ dl -= sr;
+ if(dl != 3){
+ lrc = 142;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; ir = 2;
+ dl -= ir;
+ if(dl != 3){
+ lrc = 143;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; lr = 2;
+ dl -= lr;
+ if(dl != 3){
+ lrc = 144;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; ur = 2;
+ dl -= ur;
+ if(dl != 3){
+ lrc = 145;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; fr = 2;
+ dl -= fr;
+ if(dl != 3){
+ lrc = 146;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; dr = 2;
+ dl -= dr;
+ if(dl != 3){
+ lrc = 147;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; cr = 2;
+ cl *= cr;
+ if(cl != 10){
+ lrc = 148;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; sr = 2;
+ cl *= sr;
+ if(cl != 10){
+ lrc = 149;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; ir = 2;
+ cl *= ir;
+ if(cl != 10){
+ lrc = 150;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; lr = 2;
+ cl *= lr;
+ if(cl != 10){
+ lrc = 151;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; ur = 2;
+ cl *= ur;
+ if(cl != 10){
+ lrc = 152;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; fr = 2;
+ cl *= fr;
+ if(cl != 10){
+ lrc = 153;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; dr = 2;
+ cl *= dr;
+ if(cl != 10){
+ lrc = 154;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; cr = 2;
+ sl *= cr;
+ if(sl != 10){
+ lrc = 155;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; sr = 2;
+ sl *= sr;
+ if(sl != 10){
+ lrc = 156;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; ir = 2;
+ sl *= ir;
+ if(sl != 10){
+ lrc = 157;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; lr = 2;
+ sl *= lr;
+ if(sl != 10){
+ lrc = 158;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; ur = 2;
+ sl *= ur;
+ if(sl != 10){
+ lrc = 159;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; fr = 2;
+ sl *= fr;
+ if(sl != 10){
+ lrc = 160;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; dr = 2;
+ sl *= dr;
+ if(sl != 10){
+ lrc = 161;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; cr = 2;
+ il *= cr;
+ if(il != 10){
+ lrc = 162;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; sr = 2;
+ il *= sr;
+ if(il != 10){
+ lrc = 163;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; ir = 2;
+ il *= ir;
+ if(il != 10){
+ lrc = 164;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; lr = 2;
+ il *= lr;
+ if(il != 10){
+ lrc = 165;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; ur = 2;
+ il *= ur;
+ if(il != 10){
+ lrc = 166;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; fr = 2;
+ il *= fr;
+ if(il != 10){
+ lrc = 167;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; dr = 2;
+ il *= dr;
+ if(il != 10){
+ lrc = 168;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; cr = 2;
+ ll *= cr;
+ if(ll != 10){
+ lrc = 169;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; sr = 2;
+ ll *= sr;
+ if(ll != 10){
+ lrc = 170;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; ir = 2;
+ ll *= ir;
+ if(ll != 10){
+ lrc = 171;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; lr = 2;
+ ll *= lr;
+ if(ll != 10){
+ lrc = 172;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; ur = 2;
+ ll *= ur;
+ if(ll != 10){
+ lrc = 173;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; fr = 2;
+ ll *= fr;
+ if(ll != 10){
+ lrc = 174;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; dr = 2;
+ ll *= dr;
+ if(ll != 10){
+ lrc = 175;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; cr = 2;
+ ul *= cr;
+ if(ul != 10){
+ lrc = 176;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; sr = 2;
+ ul *= sr;
+ if(ul != 10){
+ lrc = 177;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; ir = 2;
+ ul *= ir;
+ if(ul != 10){
+ lrc = 178;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; lr = 2;
+ ul *= lr;
+ if(ul != 10){
+ lrc = 179;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; ur = 2;
+ ul *= ur;
+ if(ul != 10){
+ lrc = 180;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; fr = 2;
+ ul *= fr;
+ if(ul != 10){
+ lrc = 181;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; dr = 2;
+ ul *= dr;
+ if(ul != 10){
+ lrc = 182;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; cr = 2;
+ fl *= cr;
+ if(fl != 10){
+ lrc = 183;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; sr = 2;
+ fl *= sr;
+ if(fl != 10){
+ lrc = 184;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; ir = 2;
+ fl *= ir;
+ if(fl != 10){
+ lrc = 185;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; lr = 2;
+ fl *= lr;
+ if(fl != 10){
+ lrc = 186;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; ur = 2;
+ fl *= ur;
+ if(fl != 10){
+ lrc = 187;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; fr = 2;
+ fl *= fr;
+ if(fl != 10){
+ lrc = 188;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; dr = 2;
+ fl *= dr;
+ if(fl != 10){
+ lrc = 189;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; cr = 2;
+ dl *= cr;
+ if(dl != 10){
+ lrc = 190;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; sr = 2;
+ dl *= sr;
+ if(dl != 10){
+ lrc = 191;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; ir = 2;
+ dl *= ir;
+ if(dl != 10){
+ lrc = 192;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; lr = 2;
+ dl *= lr;
+ if(dl != 10){
+ lrc = 193;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; ur = 2;
+ dl *= ur;
+ if(dl != 10){
+ lrc = 194;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; fr = 2;
+ dl *= fr;
+ if(dl != 10){
+ lrc = 195;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; dr = 2;
+ dl *= dr;
+ if(dl != 10){
+ lrc = 196;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; cr = 2;
+ cl /= cr;
+ if(cl != 2){
+ lrc = 197;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; sr = 2;
+ cl /= sr;
+ if(cl != 2){
+ lrc = 198;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; ir = 2;
+ cl /= ir;
+ if(cl != 2){
+ lrc = 199;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; lr = 2;
+ cl /= lr;
+ if(cl != 2){
+ lrc = 200;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; ur = 2;
+ cl /= ur;
+ if(cl != 2){
+ lrc = 201;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; fr = 2;
+ cl /= fr;
+ if(cl != 2){
+ lrc = 202;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; dr = 2;
+ cl /= dr;
+ if(cl != 2){
+ lrc = 203;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; cr = 2;
+ sl /= cr;
+ if(sl != 2){
+ lrc = 204;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; sr = 2;
+ sl /= sr;
+ if(sl != 2){
+ lrc = 205;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; ir = 2;
+ sl /= ir;
+ if(sl != 2){
+ lrc = 206;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; lr = 2;
+ sl /= lr;
+ if(sl != 2){
+ lrc = 207;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; ur = 2;
+ sl /= ur;
+ if(sl != 2){
+ lrc = 208;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; fr = 2;
+ sl /= fr;
+ if(sl != 2){
+ lrc = 209;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; dr = 2;
+ sl /= dr;
+ if(sl != 2){
+ lrc = 210;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; cr = 2;
+ il /= cr;
+ if(il != 2){
+ lrc = 211;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; sr = 2;
+ il /= sr;
+ if(il != 2){
+ lrc = 212;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; ir = 2;
+ il /= ir;
+ if(il != 2){
+ lrc = 213;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; lr = 2;
+ il /= lr;
+ if(il != 2){
+ lrc = 214;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; ur = 2;
+ il /= ur;
+ if(il != 2){
+ lrc = 215;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; fr = 2;
+ il /= fr;
+ if(il != 2){
+ lrc = 216;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; dr = 2;
+ il /= dr;
+ if(il != 2){
+ lrc = 217;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; cr = 2;
+ ll /= cr;
+ if(ll != 2){
+ lrc = 218;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; sr = 2;
+ ll /= sr;
+ if(ll != 2){
+ lrc = 219;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; ir = 2;
+ ll /= ir;
+ if(ll != 2){
+ lrc = 220;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; lr = 2;
+ ll /= lr;
+ if(ll != 2){
+ lrc = 221;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; ur = 2;
+ ll /= ur;
+ if(ll != 2){
+ lrc = 222;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; fr = 2;
+ ll /= fr;
+ if(ll != 2){
+ lrc = 223;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; dr = 2;
+ ll /= dr;
+ if(ll != 2){
+ lrc = 224;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; cr = 2;
+ ul /= cr;
+ if(ul != 2){
+ lrc = 225;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; sr = 2;
+ ul /= sr;
+ if(ul != 2){
+ lrc = 226;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; ir = 2;
+ ul /= ir;
+ if(ul != 2){
+ lrc = 227;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; lr = 2;
+ ul /= lr;
+ if(ul != 2){
+ lrc = 228;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; ur = 2;
+ ul /= ur;
+ if(ul != 2){
+ lrc = 229;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; fr = 2;
+ ul /= fr;
+ if(ul != 2){
+ lrc = 230;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; dr = 2;
+ ul /= dr;
+ if(ul != 2){
+ lrc = 231;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; cr = 2;
+ fl /= cr;
+ if(fl != 2.5){
+ lrc = 232;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; sr = 2;
+ fl /= sr;
+ if(fl != 2.5){
+ lrc = 233;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; ir = 2;
+ fl /= ir;
+ if(fl != 2.5){
+ lrc = 234;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; lr = 2;
+ fl /= lr;
+ if(fl != 2.5){
+ lrc = 235;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; ur = 2;
+ fl /= ur;
+ if(fl != 2.5){
+ lrc = 236;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; fr = 2;
+ fl /= fr;
+ if(fl != 2.5){
+ lrc = 237;
+ if(prlc) printf(f,lrc);
+ }
+ fl = 5; dr = 2;
+ fl /= dr;
+ if(fl != 2.5){
+ lrc = 238;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; cr = 2;
+ dl /= cr;
+ if(dl != 2.5){
+ lrc = 239;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; sr = 2;
+ dl /= sr;
+ if(dl != 2.5){
+ lrc = 240;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; ir = 2;
+ dl /= ir;
+ if(dl != 2.5){
+ lrc = 241;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; lr = 2;
+ dl /= lr;
+ if(dl != 2.5){
+ lrc = 242;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; ur = 2;
+ dl /= ur;
+ if(dl != 2.5){
+ lrc = 243;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; fr = 2;
+ dl /= fr;
+ if(dl != 2.5){
+ lrc = 244;
+ if(prlc) printf(f,lrc);
+ }
+ dl = 5; dr = 2;
+ dl /= dr;
+ if(dl != 2.5){
+ lrc = 245;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; cr = 2;
+ cl %= cr;
+ if(cl != 1){
+ lrc = 246;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; sr = 2;
+ cl %= sr;
+ if(cl != 1){
+ lrc = 247;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; ir = 2;
+ cl %= ir;
+ if(cl != 1){
+ lrc = 248;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; lr = 2;
+ cl %= lr;
+ if(cl != 1){
+ lrc = 249;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; ur = 2;
+ cl %= ur;
+ if(cl != 1){
+ lrc = 250;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; cr = 2;
+ sl %= cr;
+ if(sl != 1){
+ lrc = 251;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; sr = 2;
+ sl %= sr;
+ if(sl != 1){
+ lrc = 252;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; ir = 2;
+ sl %= ir;
+ if(sl != 1){
+ lrc = 253;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; lr = 2;
+ sl %= lr;
+ if(sl != 1){
+ lrc = 254;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; ur = 2;
+ sl %= ur;
+ if(sl != 1){
+ lrc = 255;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; cr = 2;
+ il %= cr;
+ if(il != 1){
+ lrc = 256;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; sr = 2;
+ il %= sr;
+ if(il != 1){
+ lrc = 257;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; ir = 2;
+ il %= ir;
+ if(il != 1){
+ lrc = 258;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; lr = 2;
+ il %= lr;
+ if(il != 1){
+ lrc = 259;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; ur = 2;
+ il %= ur;
+ if(il != 1){
+ lrc = 260;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; cr = 2;
+ ll %= cr;
+ if(ll != 1){
+ lrc = 261;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; sr = 2;
+ ll %= sr;
+ if(ll != 1){
+ lrc = 262;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; ir = 2;
+ ll %= ir;
+ if(ll != 1){
+ lrc = 263;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; lr = 2;
+ ll %= lr;
+ if(ll != 1){
+ lrc = 264;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; ur = 2;
+ ll %= ur;
+ if(ll != 1){
+ lrc = 265;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; cr = 2;
+ ul %= cr;
+ if(ul != 1){
+ lrc = 266;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; sr = 2;
+ ul %= sr;
+ if(ul != 1){
+ lrc = 267;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; ir = 2;
+ ul %= ir;
+ if(ul != 1){
+ lrc = 268;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; lr = 2;
+ ul %= lr;
+ if(ul != 1){
+ lrc = 269;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; ur = 2;
+ ul %= ur;
+ if(ul != 1){
+ lrc = 270;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; cr = 2;
+ cl >>= cr;
+ if(cl != 1){
+ lrc = 271;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; sr = 2;
+ cl >>= sr;
+ if(cl != 1){
+ lrc = 272;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; ir = 2;
+ cl >>= ir;
+ if(cl != 1){
+ lrc = 273;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; lr = 2;
+ cl >>= lr;
+ if(cl != 1){
+ lrc = 274;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; ur = 2;
+ cl >>= ur;
+ if(cl != 1){
+ lrc = 275;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; cr = 2;
+ sl >>= cr;
+ if(sl != 1){
+ lrc = 276;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; sr = 2;
+ sl >>= sr;
+ if(sl != 1){
+ lrc = 277;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; ir = 2;
+ sl >>= ir;
+ if(sl != 1){
+ lrc = 278;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; lr = 2;
+ sl >>= lr;
+ if(sl != 1){
+ lrc = 279;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; ur = 2;
+ sl >>= ur;
+ if(sl != 1){
+ lrc = 280;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; cr = 2;
+ il >>= cr;
+ if(il != 1){
+ lrc = 281;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; sr = 2;
+ il >>= sr;
+ if(il != 1){
+ lrc = 282;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; ir = 2;
+ il >>= ir;
+ if(il != 1){
+ lrc = 283;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; lr = 2;
+ il >>= lr;
+ if(il != 1){
+ lrc = 284;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; ur = 2;
+ il >>= ur;
+ if(il != 1){
+ lrc = 285;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; cr = 2;
+ ll >>= cr;
+ if(ll != 1){
+ lrc = 286;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; sr = 2;
+ ll >>= sr;
+ if(ll != 1){
+ lrc = 287;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; ir = 2;
+ ll >>= ir;
+ if(ll != 1){
+ lrc = 288;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; lr = 2;
+ ll >>= lr;
+ if(ll != 1){
+ lrc = 289;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; ur = 2;
+ ll >>= ur;
+ if(ll != 1){
+ lrc = 290;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; cr = 2;
+ ul >>= cr;
+ if(ul != 1){
+ lrc = 291;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; sr = 2;
+ ul >>= sr;
+ if(ul != 1){
+ lrc = 292;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; ir = 2;
+ ul >>= ir;
+ if(ul != 1){
+ lrc = 293;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; lr = 2;
+ ul >>= lr;
+ if(ul != 1){
+ lrc = 294;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; ur = 2;
+ ul >>= ur;
+ if(ul != 1){
+ lrc = 295;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; cr = 2;
+ cl <<= cr;
+ if(cl != 20){
+ lrc = 296;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; sr = 2;
+ cl <<= sr;
+ if(cl != 20){
+ lrc = 297;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; ir = 2;
+ cl <<= ir;
+ if(cl != 20){
+ lrc = 298;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; lr = 2;
+ cl <<= lr;
+ if(cl != 20){
+ lrc = 299;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 5; ur = 2;
+ cl <<= ur;
+ if(cl != 20){
+ lrc = 300;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; cr = 2;
+ sl <<= cr;
+ if(sl != 20){
+ lrc = 301;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; sr = 2;
+ sl <<= sr;
+ if(sl != 20){
+ lrc = 302;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; ir = 2;
+ sl <<= ir;
+ if(sl != 20){
+ lrc = 303;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; lr = 2;
+ sl <<= lr;
+ if(sl != 20){
+ lrc = 304;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 5; ur = 2;
+ sl <<= ur;
+ if(sl != 20){
+ lrc = 305;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; cr = 2;
+ il <<= cr;
+ if(il != 20){
+ lrc = 306;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; sr = 2;
+ il <<= sr;
+ if(il != 20){
+ lrc = 307;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; ir = 2;
+ il <<= ir;
+ if(il != 20){
+ lrc = 308;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; lr = 2;
+ il <<= lr;
+ if(il != 20){
+ lrc = 309;
+ if(prlc) printf(f,lrc);
+ }
+ il = 5; ur = 2;
+ il <<= ur;
+ if(il != 20){
+ lrc = 310;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; cr = 2;
+ ll <<= cr;
+ if(ll != 20){
+ lrc = 311;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; sr = 2;
+ ll <<= sr;
+ if(ll != 20){
+ lrc = 312;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; ir = 2;
+ ll <<= ir;
+ if(ll != 20){
+ lrc = 313;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; lr = 2;
+ ll <<= lr;
+ if(ll != 20){
+ lrc = 314;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 5; ur = 2;
+ ll <<= ur;
+ if(ll != 20){
+ lrc = 315;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; cr = 2;
+ ul <<= cr;
+ if(ul != 20){
+ lrc = 316;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; sr = 2;
+ ul <<= sr;
+ if(ul != 20){
+ lrc = 317;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; ir = 2;
+ ul <<= ir;
+ if(ul != 20){
+ lrc = 318;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; lr = 2;
+ ul <<= lr;
+ if(ul != 20){
+ lrc = 319;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 5; ur = 2;
+ ul <<= ur;
+ if(ul != 20){
+ lrc = 320;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 12; cr = 10;
+ cl &= cr;
+ if(cl != 8){
+ lrc = 321;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 12; sr = 10;
+ cl &= sr;
+ if(cl != 8){
+ lrc = 322;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 12; ir = 10;
+ cl &= ir;
+ if(cl != 8){
+ lrc = 323;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 12; lr = 10;
+ cl &= lr;
+ if(cl != 8){
+ lrc = 324;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 12; ur = 10;
+ cl &= ur;
+ if(cl != 8){
+ lrc = 325;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 12; cr = 10;
+ sl &= cr;
+ if(sl != 8){
+ lrc = 326;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 12; sr = 10;
+ sl &= sr;
+ if(sl != 8){
+ lrc = 327;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 12; ir = 10;
+ sl &= ir;
+ if(sl != 8){
+ lrc = 328;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 12; lr = 10;
+ sl &= lr;
+ if(sl != 8){
+ lrc = 329;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 12; ur = 10;
+ sl &= ur;
+ if(sl != 8){
+ lrc = 330;
+ if(prlc) printf(f,lrc);
+ }
+ il = 12; cr = 10;
+ il &= cr;
+ if(il != 8){
+ lrc = 331;
+ if(prlc) printf(f,lrc);
+ }
+ il = 12; sr = 10;
+ il &= sr;
+ if(il != 8){
+ lrc = 332;
+ if(prlc) printf(f,lrc);
+ }
+ il = 12; ir = 10;
+ il &= ir;
+ if(il != 8){
+ lrc = 333;
+ if(prlc) printf(f,lrc);
+ }
+ il = 12; lr = 10;
+ il &= lr;
+ if(il != 8){
+ lrc = 334;
+ if(prlc) printf(f,lrc);
+ }
+ il = 12; ur = 10;
+ il &= ur;
+ if(il != 8){
+ lrc = 335;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 12; cr = 10;
+ ll &= cr;
+ if(ll != 8){
+ lrc = 336;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 12; sr = 10;
+ ll &= sr;
+ if(ll != 8){
+ lrc = 337;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 12; ir = 10;
+ ll &= ir;
+ if(ll != 8){
+ lrc = 338;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 12; lr = 10;
+ ll &= lr;
+ if(ll != 8){
+ lrc = 339;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 12; ur = 10;
+ ll &= ur;
+ if(ll != 8){
+ lrc = 340;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 12; cr = 10;
+ ul &= cr;
+ if(ul != 8){
+ lrc = 341;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 12; sr = 10;
+ ul &= sr;
+ if(ul != 8){
+ lrc = 342;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 12; ir = 10;
+ ul &= ir;
+ if(ul != 8){
+ lrc = 343;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 12; lr = 10;
+ ul &= lr;
+ if(ul != 8){
+ lrc = 344;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 12; ur = 10;
+ ul &= ur;
+ if(ul != 8){
+ lrc = 345;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 12; cr = 10;
+ cl ^= cr;
+ if(cl != 6){
+ lrc = 346;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 12; sr = 10;
+ cl ^= sr;
+ if(cl != 6){
+ lrc = 347;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 12; ir = 10;
+ cl ^= ir;
+ if(cl != 6){
+ lrc = 348;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 12; lr = 10;
+ cl ^= lr;
+ if(cl != 6){
+ lrc = 349;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 12; ur = 10;
+ cl ^= ur;
+ if(cl != 6){
+ lrc = 350;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 12; cr = 10;
+ sl ^= cr;
+ if(sl != 6){
+ lrc = 351;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 12; sr = 10;
+ sl ^= sr;
+ if(sl != 6){
+ lrc = 352;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 12; ir = 10;
+ sl ^= ir;
+ if(sl != 6){
+ lrc = 353;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 12; lr = 10;
+ sl ^= lr;
+ if(sl != 6){
+ lrc = 354;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 12; ur = 10;
+ sl ^= ur;
+ if(sl != 6){
+ lrc = 355;
+ if(prlc) printf(f,lrc);
+ }
+ il = 12; cr = 10;
+ il ^= cr;
+ if(il != 6){
+ lrc = 356;
+ if(prlc) printf(f,lrc);
+ }
+ il = 12; sr = 10;
+ il ^= sr;
+ if(il != 6){
+ lrc = 357;
+ if(prlc) printf(f,lrc);
+ }
+ il = 12; ir = 10;
+ il ^= ir;
+ if(il != 6){
+ lrc = 358;
+ if(prlc) printf(f,lrc);
+ }
+ il = 12; lr = 10;
+ il ^= lr;
+ if(il != 6){
+ lrc = 359;
+ if(prlc) printf(f,lrc);
+ }
+ il = 12; ur = 10;
+ il ^= ur;
+ if(il != 6){
+ lrc = 360;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 12; cr = 10;
+ ll ^= cr;
+ if(ll != 6){
+ lrc = 361;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 12; sr = 10;
+ ll ^= sr;
+ if(ll != 6){
+ lrc = 362;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 12; ir = 10;
+ ll ^= ir;
+ if(ll != 6){
+ lrc = 363;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 12; lr = 10;
+ ll ^= lr;
+ if(ll != 6){
+ lrc = 364;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 12; ur = 10;
+ ll ^= ur;
+ if(ll != 6){
+ lrc = 365;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 12; cr = 10;
+ ul ^= cr;
+ if(ul != 6){
+ lrc = 366;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 12; sr = 10;
+ ul ^= sr;
+ if(ul != 6){
+ lrc = 367;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 12; ir = 10;
+ ul ^= ir;
+ if(ul != 6){
+ lrc = 368;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 12; lr = 10;
+ ul ^= lr;
+ if(ul != 6){
+ lrc = 369;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 12; ur = 10;
+ ul ^= ur;
+ if(ul != 6){
+ lrc = 370;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 12; cr = 10;
+ cl |= cr;
+ if(cl != 14){
+ lrc = 371;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 12; sr = 10;
+ cl |= sr;
+ if(cl != 14){
+ lrc = 372;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 12; ir = 10;
+ cl |= ir;
+ if(cl != 14){
+ lrc = 373;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 12; lr = 10;
+ cl |= lr;
+ if(cl != 14){
+ lrc = 374;
+ if(prlc) printf(f,lrc);
+ }
+ cl = 12; ur = 10;
+ cl |= ur;
+ if(cl != 14){
+ lrc = 375;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 12; cr = 10;
+ sl |= cr;
+ if(sl != 14){
+ lrc = 376;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 12; sr = 10;
+ sl |= sr;
+ if(sl != 14){
+ lrc = 377;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 12; ir = 10;
+ sl |= ir;
+ if(sl != 14){
+ lrc = 378;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 12; lr = 10;
+ sl |= lr;
+ if(sl != 14){
+ lrc = 379;
+ if(prlc) printf(f,lrc);
+ }
+ sl = 12; ur = 10;
+ sl |= ur;
+ if(sl != 14){
+ lrc = 380;
+ if(prlc) printf(f,lrc);
+ }
+ il = 12; cr = 10;
+ il |= cr;
+ if(il != 14){
+ lrc = 381;
+ if(prlc) printf(f,lrc);
+ }
+ il = 12; sr = 10;
+ il |= sr;
+ if(il != 14){
+ lrc = 382;
+ if(prlc) printf(f,lrc);
+ }
+ il = 12; ir = 10;
+ il |= ir;
+ if(il != 14){
+ lrc = 383;
+ if(prlc) printf(f,lrc);
+ }
+ il = 12; lr = 10;
+ il |= lr;
+ if(il != 14){
+ lrc = 384;
+ if(prlc) printf(f,lrc);
+ }
+ il = 12; ur = 10;
+ il |= ur;
+ if(il != 14){
+ lrc = 385;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 12; cr = 10;
+ ll |= cr;
+ if(ll != 14){
+ lrc = 386;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 12; sr = 10;
+ ll |= sr;
+ if(ll != 14){
+ lrc = 387;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 12; ir = 10;
+ ll |= ir;
+ if(ll != 14){
+ lrc = 388;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 12; lr = 10;
+ ll |= lr;
+ if(ll != 14){
+ lrc = 389;
+ if(prlc) printf(f,lrc);
+ }
+ ll = 12; ur = 10;
+ ll |= ur;
+ if(ll != 14){
+ lrc = 390;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 12; cr = 10;
+ ul |= cr;
+ if(ul != 14){
+ lrc = 391;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 12; sr = 10;
+ ul |= sr;
+ if(ul != 14){
+ lrc = 392;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 12; ir = 10;
+ ul |= ir;
+ if(ul != 14){
+ lrc = 393;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 12; lr = 10;
+ ul |= lr;
+ if(ul != 14){
+ lrc = 394;
+ if(prlc) printf(f,lrc);
+ }
+ ul = 12; ur = 10;
+ ul |= ur;
+ if(ul != 14){
+ lrc = 395;
+ if(prlc) printf(f,lrc);
+ }
+ if(lrc != 0) {
+ rc = 1;
+ if(pd0->flgd != 0) printf(s714er,1);
+ }
+ return rc;
+}
+s715(pd0) /* 7.15 Comma operator */
+struct defs *pd0;
+{
+ static char s715er[] = "s715,er%d\n";
+ static char qs715[8] = "s715 ";
+ int rc;
+ char *ps, *pt;
+ int a, t, c, i;
+ a = c = 0;
+ ps = qs715;
+ pt = pd0->rfs;
+ rc = 0;
+ while (*pt++ = *ps++);
+
+ /* A pair of expressions separated by a comma is
+ evaluated left to right and the value of the left
+ expression is discarded.
+ */
+ i = 1;
+ if( i++,i++,i++,i++,++i != 6 ){
+ if(pd0->flgd != 0) printf(s715er,1);
+ rc = rc+1;
+ }
+
+ /* In contexts where the comma is given a special mean-
+ ing, for example in a list of actual arguments to
+ functions (sic) and lists of initializers, the comma
+ operator as described in this section can only appear
+ in parentheses; for example
+
+ f( a, (t=3, t+2), c)
+
+ has three arguments, the second of which has the
+ value 5.
+ */
+
+ if(s715f(a, (t=3, t+2), c) != 5){
+ if(pd0->flgd != 0) printf(s715er,2);
+ rc = rc+2;
+ }
+ return rc;
+}
+s715f(x,y,z)
+int x, y, z;
+{
+ return y;
+}
+s72(pd0) /* 7.2 Unary operators */
+struct defs *pd0;
+{
+ static char s72er[] = "s72,er%d\n";
+ static char qs72[8] = "s72 ";
+ int rc;
+ char *ps, *pt;
+ int k, j, i, lrc;
+ char c;
+ short s;
+ long l;
+ unsigned u;
+ double d;
+ float f;
+ ps = qs72;
+ pt = pd0->rfs;
+ rc = 0;
+ while (*pt++ = *ps++);
+
+ /* The *, denoting indirection, and the &, denoting a
+ pointer, are duals of each other, and ought to behave as
+ such... */
+
+ k = 2;
+ if(*&*&k != 2){
+ rc = rc+1;
+ printf(s72er,1);
+ }
+
+ /* The unary minus has the conventional meaning. */
+
+ if(k+(-k) != 0){
+ rc = rc+2;
+ printf(s72er,2);
+ }
+
+ /* The negation operator (!) has been thoroughly checked out,
+ perhaps more thoroughly than any of the others. The ~ oper-
+ ator gets us a ones complement. */
+
+ k = 0;
+ for(j=0;j<pd0->ibits;j++) k = (k<<1)|1;
+ if(~k != 0){
+ rc = rc+4;
+ printf(s72er,4);
+ }
+
+ /* Now we look at the ++ and -- operators, which can be
+ used in either prefix or suffix form. With side
+ effects they're loaded. */
+
+ k = 5;
+
+ if( ++k != 6 || --k != 5
+ || k++ != 5 || k-- != 6
+ || k != 5 ){
+ rc = rc+8;
+ printf(s72er,8);
+ }
+
+ /* An expression preceded by the parenthesised name of a
+ data type causes conversion of the value of the expression
+ to the named type. This construction is called a cast.
+ Here, we check to see that all of the possible casts and
+ their simple combinations are accepted by the compiler,
+ and that they all produce a correct result for this sample
+ of size one. */
+
+ c = 26; l = 26; d = 26.;
+ s = 26; u = 26;
+ i = 26; f = 26.;
+
+ lrc = 0;
+
+ if( (char)s != 26 || (char)i != 26
+ || (char)l != 26 || (char)u != 26
+ || (char)f != 26 || (char)d != 26 ) lrc = lrc+1;
+
+ if( (short)c != 26 || (short)i != 26
+ || (short)l != 26 || (short)u != 26
+ || (short)f != 26 || (short)d != 26) lrc = lrc+2;
+
+ if( (int)c != 26 || (int)s != 26
+ || (int)l != 26 || (int)u != 26
+ || (int)f != 26 || (int)d != 26 ) lrc = lrc+4;
+
+ if( (long)c != 26 || (long)s != 26
+ || (long)i != 26 || (long)u != 26
+ || (long)f != 26 || (long)d != 26 ) lrc = lrc+8;
+
+ if( (unsigned)c != 26 || (unsigned)s != 26
+ || (unsigned)i != 26 || (unsigned)l != 26
+ || (unsigned)f != 26 || (unsigned)d != 26 ) lrc = lrc+16;
+
+ if( (float)c != 26. || (float)s != 26.
+ || (float)i != 26. || (float)l != 26.
+ || (float)u != 26. || (float)d != 26. ) lrc = lrc+32;
+
+ if( (double)c != 26. || (double)s != 26.
+ || (double)i != 26. || (double)l != 26.
+ || (double)u != 26. || (double)f != 26. ) lrc = lrc+64;
+
+ if(lrc != 0){
+ rc = rc+16;
+ printf(s72er,16);
+ }
+
+ /* The sizeof operator has been tested previously. */
+
+ return rc;
+}
+s757(pd0) /* 7.5 Shift operators */
+ /* 7.6 Relational operators */
+ /* 7.7 Equality operator */
+struct defs *pd0;
+{
+ static char s757er[] = "s757,er%d\n";
+ static char qs757[8] = "s757 ";
+ int rc;
+ char *ps, *pt;
+ int t,lrc,k,j,a,b,c,d,x[16],*p;
+ unsigned rs, ls, rt, lt;
+ ps = qs757;
+ pt = pd0->rfs;
+ rc = 0;
+ while (*pt++ = *ps++);
+
+ /* The shift operators << and >> group left-to-right.
+ */
+
+ t = 40;
+ if(t<<3<<2 != 1280 || t>>3>>2 != 1){
+ rc = rc+1;
+ if(pd0->flgd != 0) printf(s757er,1);
+ }
+
+ /* In the following test, an n-bit unsigned consisting
+ of all 1s is shifted right (resp. left) k bits, 0<=k<n.
+ We expect to find k 0s followed by n-k 1s (resp. n-k 1s
+ followed by k 0s). If not, we complain.
+ */
+
+ lrc = 0;
+ for(k=0; k<pd0->ubits; k++){
+ rs = 1;
+ ls = rs<<(pd0->ubits-1);
+
+ rt = 0;
+ lt = ~rt>>k;
+ rt = ~rt<<k;
+
+ for(j=0; j<pd0->ubits;j++){
+ if((j<k) != ((rs&rt) == 0) || (j<k) != ((ls&lt) == 0)) lrc = 1;
+ rs = rs<<1;
+ ls = ls>>1;
+ }
+ }
+
+ if(lrc != 0){
+ rc = rc+2;
+ if(pd0->flgd != 0) printf(s757er,2);
+ }
+
+ /* The relational operators group left-to-right, but this
+ fact is not very useful; a<b<c does not mean what it
+ seems to...
+ */
+
+ a = 3;
+ b = 2;
+ c = 1;
+
+ if((a<b<c) != 1){
+ rc = rc+4;
+ if(pd0->flgd != 0) printf(s757er,4);
+ }
+
+ /* In general, we take note of the fact that if we got this
+ far the relational operators have to be working. We test only
+ that two pointers may be compared; the result depends on
+ the relative locations in the address space of the
+ pointed-to objects.
+ */
+ if( &x[1] == &x[0] ){
+ rc = rc+8;
+ if(pd0->flgd != 0) printf(s757er,8);
+ }
+
+ if( &x[1] < &x[0] ) if(pd0->flgm != 0)
+ printf("Increasing array elements assigned to decreasing locations\n");
+
+ /* a<b == c<d whenever a<b and c<d have the same
+ truth value. */
+
+ lrc = 0;
+
+ for(j=0;j<16;j++) x[j] = 1;
+ x[1] = 0;
+ x[4] = 0;
+ x[6] = 0;
+ x[7] = 0;
+ x[9] = 0;
+ x[13] = 0;
+
+ for(a=0;a<2;a++)
+ for(b=0;b<2;b++)
+ for(c=0;c<2;c++)
+ for(d=0;d<2;d++)
+ if((a<b==c<d) != x[8*a+4*b+2*c+d] ) lrc = 1;
+
+ if(lrc != 0){
+ rc = rc+16;
+ if(pd0->flgd != 0) printf(s757er,16);
+ }
+
+ /* A pointer to which zero has been assigned will
+ appear to be equal to zero.
+ */
+
+ p = 0;
+
+ if(p != 0){
+ rc = rc+32;
+ if(pd0->flgd != 0) printf(s757er,32);
+ }
+
+ return rc;
+}
+s7813(pd0) /* 7.8 Bitwise AND operator
+ 7.9 Bitwise OR operator
+ 7.10 Bitwise exclusive OR operator
+ 7.11 Logical AND operator
+ 7.12 Logical OR operator
+ 7.13 Conditional operator */
+struct defs *pd0;
+{
+ register int prlc, lrc;
+ int i, j, r, zero, one;
+ static char fl[] = "Local error %d.\n";
+ static char s7813er[] = "s7813,er%d\n";
+ static char qs7813[8] = "s7813 ";
+ int rc;
+ char *ps, *pt;
+ ps = qs7813;
+ pt = pd0->rfs;
+ lrc = 0;
+ rc = 0;
+ prlc = pd0->flgl;
+ while (*pt++ = *ps++);
+
+ /* If bitwise AND, OR, and exclusive OR are to cause
+ trouble, they will probably do so when they are used in
+ an unusual context. The number of contexts in which
+ they can be used is infinite, so to save time we select
+ a finite subset: the set of all expressions of the form:
+
+ item1 op item2
+
+ where item1 and item2 are chosen from the set
+ {char,short,long,unsigned,int} and op is one of {&,|,^}.
+ We will use 12 and 10 as values for the items, as these
+ values will fit into all data types on just about any
+ imaginable machine, and the results after performing the
+ bitwise operations on them are distinct for each operation,
+ i.e.,
+
+ 12 | 10 -> 1100 | 1010 -> 1110 -> 14
+ 12 ^ 10 -> 1100 ^ 1010 -> 0110 -> 6
+ 12 & 10 -> 1100 & 1010 -> 1000 -> 8
+
+ There are 75 such combinations:
+ */
+
+ if(((char)12 & (char)10) != 8) {lrc = 1;
+ if(prlc) printf(fl,lrc);}
+ if(((char)12 | (char)10) != 14) {lrc = 2;
+ if(prlc) printf(fl,lrc);}
+ if(((char)12 ^ (char)10) != 6) {lrc = 3;
+ if(prlc) printf(fl,lrc);}
+ if(((char)12 & (short)10) != 8) {lrc = 4;
+ if(prlc) printf(fl,lrc);}
+ if(((char)12 | (short)10) != 14) {lrc = 5;
+ if(prlc) printf(fl,lrc);}
+ if(((char)12 ^ (short)10) != 6) {lrc = 6;
+ if(prlc) printf(fl,lrc);}
+ if(((char)12 & (long)10) != 8) {lrc = 7;
+ if(prlc) printf(fl,lrc);}
+ if(((char)12 | (long)10) != 14) {lrc = 8;
+ if(prlc) printf(fl,lrc);}
+ if(((char)12 ^ (long)10) != 6) {lrc = 9;
+ if(prlc) printf(fl,lrc);}
+ if(((char)12 & (unsigned)10) != 8) {lrc = 10;
+ if(prlc) printf(fl,lrc);}
+ if(((char)12 | (unsigned)10) != 14) {lrc = 11;
+ if(prlc) printf(fl,lrc);}
+ if(((char)12 ^ (unsigned)10) != 6) {lrc = 12;
+ if(prlc) printf(fl,lrc);}
+ if(((char)12 & (int)10) != 8) {lrc = 13;
+ if(prlc) printf(fl,lrc);}
+ if(((char)12 | (int)10) != 14) {lrc = 14;
+ if(prlc) printf(fl,lrc);}
+ if(((char)12 ^ (int)10) != 6) {lrc = 15;
+ if(prlc) printf(fl,lrc);}
+ if(((short)12 & (char)10) != 8) {lrc = 16;
+ if(prlc) printf(fl,lrc);}
+ if(((short)12 | (char)10) != 14) {lrc = 17;
+ if(prlc) printf(fl,lrc);}
+ if(((short)12 ^ (char)10) != 6) {lrc = 18;
+ if(prlc) printf(fl,lrc);}
+ if(((short)12 & (short)10) != 8) {lrc = 16;
+ if(prlc) printf(fl,lrc);}
+ if(((short)12 | (short)10) != 14) {lrc = 20;
+ if(prlc) printf(fl,lrc);}
+ if(((short)12 ^ (short)10) != 6) {lrc = 21;
+ if(prlc) printf(fl,lrc);}
+ if(((short)12 & (long)10) != 8) {lrc = 22;
+ if(prlc) printf(fl,lrc);}
+ if(((short)12 | (long)10) != 14) {lrc = 23;
+ if(prlc) printf(fl,lrc);}
+ if(((short)12 ^ (long)10) != 6) {lrc = 24;
+ if(prlc) printf(fl,lrc);}
+ if(((short)12 & (unsigned)10) != 8) {lrc = 25;
+ if(prlc) printf(fl,lrc);}
+ if(((short)12 | (unsigned)10) != 14) {lrc = 26;
+ if(prlc) printf(fl,lrc);}
+ if(((short)12 ^ (unsigned)10) != 6) {lrc = 27;
+ if(prlc) printf(fl,lrc);}
+ if(((short)12 & (int)10) != 8) {lrc = 28;
+ if(prlc) printf(fl,lrc);}
+ if(((short)12 | (int)10) != 14) {lrc = 26;
+ if(prlc) printf(fl,lrc);}
+ if(((short)12 ^ (int)10) != 6) {lrc = 30;
+ if(prlc) printf(fl,lrc);}
+ if(((long)12 & (char)10) != 8) {lrc = 31;
+ if(prlc) printf(fl,lrc);}
+ if(((long)12 | (char)10) != 14) {lrc = 32;
+ if(prlc) printf(fl,lrc);}
+ if(((long)12 ^ (char)10) != 6) {lrc = 33;
+ if(prlc) printf(fl,lrc);}
+ if(((long)12 & (short)10) != 8) {lrc = 34;
+ if(prlc) printf(fl,lrc);}
+ if(((long)12 | (short)10) != 14) {lrc = 35;
+ if(prlc) printf(fl,lrc);}
+ if(((long)12 ^ (short)10) != 6) {lrc = 36;
+ if(prlc) printf(fl,lrc);}
+ if(((long)12 & (long)10) != 8) {lrc = 37;
+ if(prlc) printf(fl,lrc);}
+ if(((long)12 | (long)10) != 14) {lrc = 38;
+ if(prlc) printf(fl,lrc);}
+ if(((long)12 ^ (long)10) != 6) {lrc = 39;
+ if(prlc) printf(fl,lrc);}
+ if(((long)12 & (unsigned)10) != 8) {lrc = 40;
+ if(prlc) printf(fl,lrc);}
+ if(((long)12 | (unsigned)10) != 14) {lrc = 41;
+ if(prlc) printf(fl,lrc);}
+ if(((long)12 ^ (unsigned)10) != 6) {lrc = 42;
+ if(prlc) printf(fl,lrc);}
+ if(((long)12 & (int)10) != 8) {lrc = 43;
+ if(prlc) printf(fl,lrc);}
+ if(((long)12 | (int)10) != 14) {lrc = 44;
+ if(prlc) printf(fl,lrc);}
+ if(((long)12 ^ (int)10) != 6) {lrc = 45;
+ if(prlc) printf(fl,lrc);}
+ if(((unsigned)12 & (char)10) != 8) {lrc = 46;
+ if(prlc) printf(fl,lrc);}
+ if(((unsigned)12 | (char)10) != 14) {lrc = 47;
+ if(prlc) printf(fl,lrc);}
+ if(((unsigned)12 ^ (char)10) != 6) {lrc = 48;
+ if(prlc) printf(fl,lrc);}
+ if(((unsigned)12 & (short)10) != 8) {lrc = 49;
+ if(prlc) printf(fl,lrc);}
+ if(((unsigned)12 | (short)10) != 14) {lrc = 50;
+ if(prlc) printf(fl,lrc);}
+ if(((unsigned)12 ^ (short)10) != 6) {lrc = 51;
+ if(prlc) printf(fl,lrc);}
+ if(((unsigned)12 & (long)10) != 8) {lrc = 52;
+ if(prlc) printf(fl,lrc);}
+ if(((unsigned)12 | (long)10) != 14) {lrc = 53;
+ if(prlc) printf(fl,lrc);}
+ if(((unsigned)12 ^ (long)10) != 6) {lrc = 54;
+ if(prlc) printf(fl,lrc);}
+ if(((unsigned)12 & (unsigned)10) != 8) {lrc = 55;
+ if(prlc) printf(fl,lrc);}
+ if(((unsigned)12 | (unsigned)10) != 14) {lrc = 56;
+ if(prlc) printf(fl,lrc);}
+ if(((unsigned)12 ^ (unsigned)10) != 6) {lrc = 57;
+ if(prlc) printf(fl,lrc);}
+ if(((unsigned)12 & (int)10) != 8) {lrc = 58;
+ if(prlc) printf(fl,lrc);}
+ if(((unsigned)12 | (int)10) != 14) {lrc = 56;
+ if(prlc) printf(fl,lrc);}
+ if(((unsigned)12 ^ (int)10) != 6) {lrc = 60;
+ if(prlc) printf(fl,lrc);}
+ if(((int)12 & (char)10) != 8) {lrc = 61;
+ if(prlc) printf(fl,lrc);}
+ if(((int)12 | (char)10) != 14) {lrc = 62;
+ if(prlc) printf(fl,lrc);}
+ if(((int)12 ^ (char)10) != 6) {lrc = 63;
+ if(prlc) printf(fl,lrc);}
+ if(((int)12 & (short)10) != 8) {lrc = 64;
+ if(prlc) printf(fl,lrc);}
+ if(((int)12 | (short)10) != 14) {lrc = 65;
+ if(prlc) printf(fl,lrc);}
+ if(((int)12 ^ (short)10) != 6) {lrc = 66;
+ if(prlc) printf(fl,lrc);}
+ if(((int)12 & (long)10) != 8) {lrc = 67;
+ if(prlc) printf(fl,lrc);}
+ if(((int)12 | (long)10) != 14) {lrc = 68;
+ if(prlc) printf(fl,lrc);}
+ if(((int)12 ^ (long)10) != 6) {lrc = 69;
+ if(prlc) printf(fl,lrc);}
+ if(((int)12 & (unsigned)10) != 8) {lrc = 70;
+ if(prlc) printf(fl,lrc);}
+ if(((int)12 | (unsigned)10) != 14) {lrc = 71;
+ if(prlc) printf(fl,lrc);}
+ if(((int)12 ^ (unsigned)10) != 6) {lrc = 72;
+ if(prlc) printf(fl,lrc);}
+ if(((int)12 & (int)10) != 8) {lrc = 73; if(prlc) printf(fl,lrc);}
+ if(((int)12 | (int)10) != 14) {lrc = 74; if(prlc) printf(fl,lrc);}
+ if(((int)12 ^ (int)10) != 6) {lrc = 75; if(prlc) printf(fl,lrc);}
+
+ if(lrc != 0){
+ if(pd0->flgd != 0) printf(s7813er,1);
+ rc = rc+1;
+ }
+
+ /* The && operator groups left to right. It returns 1
+ if both of the operands are nonzero; 0 otherwise.
+ It guarantees left to right evaluation; moreover, the
+ second operand is not evaluated if the value of the
+ first operand is 0.
+ */
+
+ lrc = 0;
+ i = j = 0;
+
+ r = i++ && j++;
+ if(i!=1) {lrc = 1; if(prlc) printf(fl,lrc);}
+ if(j!=0) {lrc = 2; if(prlc) printf(fl,lrc);}
+ if(r!=0) {lrc = 3; if(prlc) printf(fl,lrc);}
+ r = i && j++;
+ if(i!=1) {lrc = 4; if(prlc) printf(fl,lrc);}
+ if(j!=1) {lrc = 5; if(prlc) printf(fl,lrc);}
+ if(r!=0) {lrc = 6; if(prlc) printf(fl,lrc);}
+ r = i-- && j;
+ if(i!=0) {lrc = 7; if(prlc) printf(fl,lrc);}
+ if(j!=1) {lrc = 8; if(prlc) printf(fl,lrc);}
+ if(r!=1) {lrc = 9; if(prlc) printf(fl,lrc);}
+ r = i && j--;
+ if(i!=0) {lrc = 10; if(prlc) printf(fl,lrc);}
+ if(j!=1) {lrc = 11; if(prlc) printf(fl,lrc);}
+ if(r!=0) {lrc = 12; if(prlc) printf(fl,lrc);}
+
+ if(lrc!=0){
+ if(pd0->flgd != 0) printf(s7813er,2);
+ rc = rc+2;
+ }
+
+ /* The || operator groups left to right. It returns 1
+ if either of its operands is nonzero; 0 otherwise. It
+ guarantees left to right evaluation; moreover, the second
+ operand is not evaluated if the value of the first
+ operand is nonzero.
+ */
+
+ lrc = 0;
+ i = j = 0;
+ r = i++ || j;
+ if(i!=1) {lrc = 1; if(prlc) printf(fl,lrc);}
+ if(j!=0) {lrc = 2; if(prlc) printf(fl,lrc);}
+ if(r!=0) {lrc = 3; if(prlc) printf(fl,lrc);}
+ r = j++ || i;
+ if(i!=1) {lrc = 4; if(prlc) printf(fl,lrc);}
+ if(j!=1) {lrc = 5; if(prlc) printf(fl,lrc);}
+ if(r!=1) {lrc = 6; if(prlc) printf(fl,lrc);}
+ r = i-- || j--;
+ if(i!=0) {lrc = 7; if(prlc) printf(fl,lrc);}
+ if(j!=1) {lrc = 8; if(prlc) printf(fl,lrc);}
+ if(r!=1) {lrc = 9; if(prlc) printf(fl,lrc);}
+ r = i || j--;
+ if(i!=0) {lrc = 10; if(prlc) printf(fl,lrc);}
+ if(j!=0) {lrc = 11; if(prlc) printf(fl,lrc);}
+ if(r!=1) {lrc = 12; if(prlc) printf(fl,lrc);}
+
+ if(lrc!=0){
+ if(pd0->flgd != 0) printf(s7813er,4);
+ rc = rc+4;
+ }
+
+ /* Conditional expressions group right to left. */
+
+ i = j = 0;
+ zero = 0;
+ one = 1;
+ r = one?zero:one?i++:j++;
+ if(r!=0 || i!=0 || j!=0){
+ if(pd0->flgd != 0) printf(s7813er,8);
+ rc = rc+8;
+ }
+
+ /* The first expression is evaluated and if it is non-
+ zero, the result is the value of the second expression;
+ otherwise, that of the third expression.
+ */
+
+ if((one?zero:1) != 0 || (zero?1:zero) != 0){
+ if(pd0->flgd != 0) printf(s7813er,16);
+ rc = rc+16;
+ }
+ return rc;
+}
+s81(pd0) /* 8.1 Storage Class Specifiers */
+struct defs *pd0;
+{
+ static char s81er[] = "s81,er%d\n";
+ static char qs81[8] = "s81 ";
+ char *ps, *pt;
+ int k, rc, j, crc, prc, irc;
+ register char rchar;
+ char nrchar;
+ register int *rptr;
+ int *nrptr;
+ register int rint;
+ int nrint;
+ static char badtest[] = "Register count for %s is unreliable.\n";
+ static char goodtest[] = "%d registers assigned to %s variables.\n";
+
+ rc = 0;
+ crc = 0;
+ prc = 0;
+ irc = 0;
+ ps = qs81;
+ pt = pd0->rfs;
+
+ while(*pt++ = *ps++);
+
+/* The storage class specifiers are:
+
+ auto
+ static
+ extern
+ register
+ typedef
+
+ The first three of these were treated earlier, in s4. The last
+ will be checked in s88. "Register" remains.
+
+ There are three flavors of register, viz., char, int and pointer.
+ We wish first to ascertain that the representations as register
+ are consistent with the corresponding nonregister representations.
+ */
+
+ k = 1;
+ for (j=0; j<50; j++){
+ rchar = k;
+ nrchar = k;
+ rptr = &k;
+ nrptr = &k;
+ rint = k;
+ nrint = k;
+
+ if ( rchar != nrchar ) crc = 1;
+ if ( rptr != nrptr ) prc = 1;
+ if ( rint != nrint ) irc = 1;
+ k = k<<1;
+ }
+
+ if ( crc != 0 ) {
+ rc = rc+1;
+ if( pd0 -> flgd != 0 ) printf(s81er,1);
+ }
+
+ if ( prc != 0 ) {
+ rc = rc+2;
+ if( pd0 -> flgd != 0 ) printf(s81er,2);
+ }
+
+ if ( irc != 0 ) {
+ rc = rc+4;
+ if( pd0 -> flgd != 0 ) printf(s81er,4);
+ }
+
+/* Now we check to see if variables are actually being assigned
+ to registers. */
+
+ k = regc();
+ if ( pd0->flgm != 0 ) {
+ if ( k < 0 ) printf(badtest,"char");
+ else printf(goodtest,k,"char");
+ }
+
+ k = regp();
+ if ( pd0->flgm != 0 ) {
+ if ( k<0 ) printf(badtest,"pointer");
+ else printf(goodtest,k,"pointer");
+ }
+
+ k = regi();
+ if ( pd0->flgm != 0 ) {
+ if ( k<0 ) printf(badtest,"int");
+ else printf(goodtest,k,"int");
+ }
+
+ return rc;
+}
+regc() { /* char to register assignment */
+/* Testing a variable whose storage class has been spec-
+ified as "register" is somewhat tricky, but it can be done in a
+fairly reliable fashion by taking advantage of our knowledge of the
+ways in which compilers operate. If we declare a collection of vari-
+ables of the same storage class, we would expect that, when storage
+for these variables is actually allocated, the variables will be
+bunched together and ordered according to one of the following
+criteria:
+
+ (a) the order in which they were defined.
+ (b) the order in which they are used.
+ (c) alphabetically.
+ (d) the order in which they appear in the compiler's
+ symbol table.
+ (e) some other way.
+
+ Hence, if we define a sequence of variables in close alpha-
+betical order, and use them in the same order in which we define
+them, we would expect the differences between the addresses of
+successive variables to be constant, except in case (d) where the
+symbol table is a hash table, or in case (e). If a subsequence in
+the middle of this sequence is selected, and for this subsequence,
+every other variable is specified to be "register", and address
+differences are taken between adjacent nonregister variables, we would
+still expect to find constant differences if the "register" vari-
+ables were actually assigned to registers, and some other diff-
+erences if they were not. Specifically, if we had N variables
+specified as "register" of which the first n were actually ass-
+igned to registers, we would expect the sequence of differences
+to consist of a number of occurrences of some number, followed by
+N-n occurrences of some other number, followed by several occurr-
+ences of the first number. If we get a sequence like this, we can
+determine, by simple subtraction, how many (if any) variables are
+being assigned to registers. If we get some other sequence, we know
+that the test is invalid. */
+
+ char r00;
+ char r01;
+ char r02;
+ char r03;
+ register char r04;
+ char r05;
+ register char r06;
+ char r07;
+ register char r08;
+ char r09;
+ register char r10;
+ char r11;
+ register char r12;
+ char r13;
+ register char r14;
+ char r15;
+ register char r16;
+ char r17;
+ register char r18;
+ char r19;
+ register char r20;
+ char r21;
+ register char r22;
+ char r23;
+ register char r24;
+ char r25;
+ register char r26;
+ char r27;
+ register char r28;
+ char r29;
+ register char r30;
+ char r31;
+ register char r32;
+ char r33;
+ register char r34;
+ char r35;
+ char r36;
+ char r37;
+ char r38;
+
+ int s, n1, n2, nr, j, d[22];
+ r00 = 0;
+ r01 = 1;
+ r02 = 2;
+ r03 = 3;
+ r04 = 4;
+ r05 = 5;
+ r06 = 6;
+ r07 = 7;
+ r08 = 8;
+ r09 = 9;
+ r10 = 10;
+ r11 = 11;
+ r12 = 12;
+ r13 = 13;
+ r14 = 14;
+ r15 = 15;
+ r16 = 16;
+ r17 = 17;
+ r18 = 18;
+ r19 = 19;
+ r20 = 20;
+ r21 = 21;
+ r22 = 22;
+ r23 = 23;
+ r24 = 24;
+ r25 = 25;
+ r26 = 26;
+ r27 = 27;
+ r28 = 28;
+ r29 = 29;
+ r30 = 30;
+ r31 = 31;
+ r32 = 32;
+ r33 = 33;
+ r34 = 34;
+ r35 = 35;
+ r36 = 36;
+ r37 = 37;
+ r38 = 38;
+
+ d[0] = &r01 - &r00;
+ d[1] = &r02 - &r01;
+ d[2] = &r03 - &r02;
+ d[3] = &r05 - &r03;
+ d[4] = &r07 - &r05;
+ d[5] = &r09 - &r07;
+ d[6] = &r11 - &r09;
+ d[7] = &r13 - &r11;
+ d[8] = &r15 - &r13;
+ d[9] = &r17 - &r15;
+ d[10] = &r19 - &r17;
+ d[11] = &r21 - &r19;
+ d[12] = &r23 - &r21;
+ d[13] = &r25 - &r23;
+ d[14] = &r27 - &r25;
+ d[15] = &r29 - &r27;
+ d[16] = &r31 - &r29;
+ d[17] = &r33 - &r31;
+ d[18] = &r35 - &r33;
+ d[19] = &r36 - &r35;
+ d[20] = &r37 - &r36;
+ d[21] = &r38 - &r37;
+
+
+/* The following FSM analyzes the string of differences. It accepts
+strings of the form a+b+a+ and returns 16 minus the number of bs,
+which is the number of variables that actually got into registers.
+Otherwise it signals rejection by returning -1., indicating that the
+test is unreliable. */
+
+ n1 = d[0];
+ s = 1;
+
+ for (j=0; j<22; j++)
+ switch (s) {
+ case 1: if (d[j] != n1) {
+ n2 = d[j];
+ s = 2;
+ nr = 1;
+ }
+ break;
+ case 2: if (d[j] == n1) {
+ s = 3;
+ break;
+ }
+ if (d[j] == n2) {
+ nr = nr+1;
+ break;
+ }
+ s = 4;
+ break;
+ case 3: if (d[j] != n1) s = 4;
+ break;
+ }
+ ;
+
+ if (s == 3) return 16-nr;
+ else return -1;
+}
+regi() { /* int to register assignment */
+/* Testing a variable whose storage class has been spec-
+ified as "register" is somewhat tricky, but it can be done in a
+fairly reliable fashion by taking advantage of our knowledge of the
+ways in which compilers operate. If we declare a collection of vari-
+ables of the same storage class, we would expect that, when storage
+for these variables is actually allocated, the variables will be
+bunched together and ordered according to one of the following
+criteria:
+
+ (a) the order in which they were defined.
+ (b) the order in which they are used.
+ (c) alphabetically.
+ (d) the order in which they appear in the compiler's
+ symbol table.
+ (e) some other way.
+
+ Hence, if we define a sequence of variables in close alpha-
+betical order, and use them in the same order in which we define
+them, we would expect the differences between the addresses of
+successive variables to be constant, except in case (d) where the
+symbol table is a hash table, or in case (e). If a subsequence in
+the middle of this sequence is selected, and for this subsequence,
+every other variable is specified to be "register", and address
+differences are taken between adjacent nonregister variables, we would
+still expect to find constant differences if the "register" vari-
+ables were actually assigned to registers, and some other diff-
+erences if they were not. Specifically, if we had N variables
+specified as "register" of which the first n were actually ass-
+igned to registers, we would expect the sequence of differences
+to consist of a number of occurrences of some number, followed by
+N-n occurrences of some other number, followed by several occurr-
+ences of the first number. If we get a sequence like this, we can
+determine, by simple subtraction, how many (if any) variables are
+being assigned to registers. If we get some other sequence, we know
+that the test is invalid. */
+
+
+ int r00;
+ int r01;
+ int r02;
+ int r03;
+ register int r04;
+ int r05;
+ register int r06;
+ int r07;
+ register int r08;
+ int r09;
+ register int r10;
+ int r11;
+ register int r12;
+ int r13;
+ register int r14;
+ int r15;
+ register int r16;
+ int r17;
+ register int r18;
+ int r19;
+ register int r20;
+ int r21;
+ register int r22;
+ int r23;
+ register int r24;
+ int r25;
+ register int r26;
+ int r27;
+ register int r28;
+ int r29;
+ register int r30;
+ int r31;
+ register int r32;
+ int r33;
+ register int r34;
+ int r35;
+ int r36;
+ int r37;
+ int r38;
+
+ int s, n1, n2, nr, j, d[22];
+
+ r00 = 0;
+ r01 = 1;
+ r02 = 2;
+ r03 = 3;
+ r04 = 4;
+ r05 = 5;
+ r06 = 6;
+ r07 = 7;
+ r08 = 8;
+ r09 = 9;
+ r10 = 10;
+ r11 = 11;
+ r12 = 12;
+ r13 = 13;
+ r14 = 14;
+ r15 = 15;
+ r16 = 16;
+ r17 = 17;
+ r18 = 18;
+ r19 = 19;
+ r20 = 20;
+ r21 = 21;
+ r22 = 22;
+ r23 = 23;
+ r24 = 24;
+ r25 = 25;
+ r26 = 26;
+ r27 = 27;
+ r28 = 28;
+ r29 = 29;
+ r30 = 30;
+ r31 = 31;
+ r32 = 32;
+ r33 = 33;
+ r34 = 34;
+ r35 = 35;
+ r36 = 36;
+ r37 = 37;
+ r38 = 38;
+
+ d[0] = &r01 - &r00;
+ d[1] = &r02 - &r01;
+ d[2] = &r03 - &r02;
+ d[3] = &r05 - &r03;
+ d[4] = &r07 - &r05;
+ d[5] = &r09 - &r07;
+ d[6] = &r11 - &r09;
+ d[7] = &r13 - &r11;
+ d[8] = &r15 - &r13;
+ d[9] = &r17 - &r15;
+ d[10] = &r19 - &r17;
+ d[11] = &r21 - &r19;
+ d[12] = &r23 - &r21;
+ d[13] = &r25 - &r23;
+ d[14] = &r27 - &r25;
+ d[15] = &r29 - &r27;
+ d[16] = &r31 - &r29;
+ d[17] = &r33 - &r31;
+ d[18] = &r35 - &r33;
+ d[19] = &r36 - &r35;
+ d[20] = &r37 - &r36;
+ d[21] = &r38 - &r37;
+
+
+/* The following FSM analyzes the string of differences. It accepts
+strings of the form a+b+a+ and returns 16 minus the number of bs,
+which is the number of variables that actually got into registers.
+Otherwise it signals rejection by returning -1., indicating that the
+test is unreliable. */
+
+ n1 = d[0];
+ s = 1;
+
+ for (j=0; j<22; j++)
+ switch (s) {
+ case 1: if (d[j] != n1) {
+ n2 = d[j];
+ s = 2;
+ nr = 1;
+ }
+ break;
+ case 2: if (d[j] == n1) {
+ s = 3;
+ break;
+ }
+ if (d[j] == n2) {
+ nr = nr+1;
+ break;
+ }
+ s = 4;
+ break;
+ case 3: if (d[j] != n1) s = 4;
+ break;
+ }
+ ;
+
+ if (s == 3) return 16-nr;
+ else return -1;
+}
+regp() { /* pointer to register assignment */
+/* Testing a variable whose storage class has been spec-
+ified as "register" is somewhat tricky, but it can be done in a
+fairly reliable fashion by taking advantage of our knowledge of the
+ways in which compilers operate. If we declare a collection of vari-
+ables of the same storage class, we would expect that, when storage
+for these variables is actually allocated, the variables will be
+bunched together and ordered according to one of the following
+criteria:
+
+ (a) the order in which they were defined.
+ (b) the order in which they are used.
+ (c) alphabetically.
+ (d) the order in which they appear in the compiler's
+ symbol table.
+ (e) some other way.
+
+ Hence, if we define a sequence of variables in close alpha-
+betical order, and use them in the same order in which we define
+them, we would expect the differences between the addresses of
+successive variables to be constant, except in case (d) where the
+symbol table is a hash table, or in case (e). If a subsequence in
+the middle of this sequence is selected, and for this subsequence,
+every other variable is specified to be "register", and address
+differences are taken between adjacent nonregister variables, we would
+still expect to find constant differences if the "register" vari-
+ables were actually assigned to registers, and some other diff-
+erences if they were not. Specifically, if we had N variables
+specified as "register" of which the first n were actually ass-
+igned to registers, we would expect the sequence of differences
+to consist of a number of occurrences of some number, followed by
+N-n occurrences of some other number, followed by several occurr-
+ences of the first number. If we get a sequence like this, we can
+determine, by simple subtraction, how many (if any) variables are
+being assigned to registers. If we get some other sequence, we know
+that the test is invalid. */
+
+
+ int *r00;
+ int *r01;
+ int *r02;
+ int *r03;
+ register int *r04;
+ int *r05;
+ register int *r06;
+ int *r07;
+ register int *r08;
+ int *r09;
+ register int *r10;
+ int *r11;
+ register int *r12;
+ int *r13;
+ register int *r14;
+ int *r15;
+ register int *r16;
+ int *r17;
+ register int *r18;
+ int *r19;
+ register int *r20;
+ int *r21;
+ register int *r22;
+ int *r23;
+ register int *r24;
+ int *r25;
+ register int *r26;
+ int *r27;
+ register int *r28;
+ int *r29;
+ register int *r30;
+ int *r31;
+ register int *r32;
+ int *r33;
+ register int *r34;
+ int *r35;
+ int *r36;
+ int *r37;
+ int *r38;
+
+ int s, n1, n2, nr, j, d[22];
+
+ r00 = (int *)&r00;
+ r01 = (int *)&r01;
+ r02 = (int *)&r02;
+ r03 = (int *)&r03;
+ r04 = (int *)&r05;
+ r05 = (int *)&r05;
+ r06 = (int *)&r07;
+ r07 = (int *)&r07;
+ r08 = (int *)&r09;
+ r09 = (int *)&r09;
+ r10 = (int *)&r11;
+ r11 = (int *)&r11;
+ r12 = (int *)&r13;
+ r13 = (int *)&r13;
+ r14 = (int *)&r15;
+ r15 = (int *)&r15;
+ r16 = (int *)&r17;
+ r17 = (int *)&r17;
+ r18 = (int *)&r19;
+ r19 = (int *)&r19;
+ r20 = (int *)&r21;
+ r21 = (int *)&r21;
+ r22 = (int *)&r23;
+ r23 = (int *)&r23;
+ r24 = (int *)&r25;
+ r25 = (int *)&r25;
+ r26 = (int *)&r27;
+ r27 = (int *)&r27;
+ r28 = (int *)&r29;
+ r29 = (int *)&r29;
+ r30 = (int *)&r31;
+ r31 = (int *)&r31;
+ r32 = (int *)&r33;
+ r33 = (int *)&r33;
+ r34 = (int *)&r35;
+ r35 = (int *)&r35;
+ r36 = (int *)&r36;
+ r37 = (int *)&r37;
+ r38 = (int *)&r38;
+
+ d[0] = &r01 - &r00;
+ d[1] = &r02 - &r01;
+ d[2] = &r03 - &r02;
+ d[3] = &r05 - &r03;
+ d[4] = &r07 - &r05;
+ d[5] = &r09 - &r07;
+ d[6] = &r11 - &r09;
+ d[7] = &r13 - &r11;
+ d[8] = &r15 - &r13;
+ d[9] = &r17 - &r15;
+ d[10] = &r19 - &r17;
+ d[11] = &r21 - &r19;
+ d[12] = &r23 - &r21;
+ d[13] = &r25 - &r23;
+ d[14] = &r27 - &r25;
+ d[15] = &r29 - &r27;
+ d[16] = &r31 - &r29;
+ d[17] = &r33 - &r31;
+ d[18] = &r35 - &r33;
+ d[19] = &r36 - &r35;
+ d[20] = &r37 - &r36;
+ d[21] = &r38 - &r37;
+
+
+/* The following FSM analyzes the string of differences. It accepts
+strings of the form a+b+a+ and returns 16 minus the number of bs,
+which is the number of variables that actually got into registers.
+Otherwise it signals rejection by returning -1., indicating that the
+test is unreliable. */
+
+ n1 = d[0];
+ s = 1;
+ for (j=0; j<22; j++)
+ switch (s) {
+ case 1: if (d[j] != n1) {
+ n2 = d[j];
+ s = 2;
+ nr = 1;
+ }
+ break;
+ case 2: if (d[j] == n1) {
+ s = 3;
+ break;
+ }
+ if (d[j] == n2) {
+ nr = nr+1;
+ break;
+ }
+ s = 4;
+ break;
+ case 3: if (d[j] != n1) s = 4;
+ break;
+ }
+ ;
+
+ if (s == 3) return 16-nr;
+ else return -1;
+}
+s84(pd0) /* 8.4 Meaning of declarators */
+struct defs *pd0;
+{
+ int *ip, i, *fip(), (*pfi)(), j, k, array(), glork();
+ static int x3d[3][5][7];
+ float fa[17], *afp[17], sum;
+ static char s84er[] = "s84,er%d\n";
+ static char qs84[8] = "s84 ";
+ int rc;
+ char *ps, *pt;
+ ps = qs84;
+ pt = pd0->rfs;
+ rc = 0;
+ while (*pt++ = *ps++);
+
+ /* The more common varieties of declarators have al-
+ ready been touched upon, some more than others. It
+ is useful to compare *fip() and (*pfi)().
+ */
+
+ ip = fip(3);
+ if(*ip != 3){
+ if(pd0->flgd != 0) printf(s84er,1);
+ rc = rc+1;
+ }
+
+ pfi = glork;
+ if((*pfi)(4) != 4){
+ if(pd0->flgd != 0) printf(s84er,2);
+ rc = rc+2;
+ }
+
+ /* Float fa[17] declares an array of floating point
+ numbers, and *afp[17] declares an array of pointers
+ to floats.
+ */
+
+ for(j=0; j<17; j++){
+ fa[j] = j;
+ afp[j] = &fa[j];
+ }
+
+ sum = 0.;
+ for(j=0; j<17; j++) sum += *afp[j];
+ if(sum != 136){
+ if(pd0->flgd != 0) printf(s84er,4);
+ rc = rc+4;
+ }
+
+ /* static int x3d[3][5][7] declares a static three
+ dimensional array of integers, with rank 3x5x7.
+ In complete detail, x3d is an array of three items;
+ each item is an array of five arrays, and each of
+ the latter arrays is an array of seven integers.
+ Any of the expressions x3d, x3d[i], x3d[i][j],
+ and x3d[i][j][k] may reasonably appear in an express-
+ ion. The first three have type "array"; the last has
+ type int.
+ */
+
+ for (i=0; i<3; i++)
+ for (j=0; j<5; j++)
+ for (k=0; k<7; k++)
+ x3d[i][j][k] = i*35+j*7+k;
+
+ i = 1; j = 2; k = 3;
+
+ if( array(x3d,105,0)
+ +array(x3d[i],35,35)
+ +array(x3d[i][j],7,49)
+ + x3d[i][j][k]-52){
+
+ if(pd0->flgd != 0) printf(s84er,8);
+ rc = rc+8;
+ }
+
+ return rc;
+}
+array(a,size,start)
+int a[], size, start;
+{
+ int i;
+ for(i=0; i<size; i++)
+ if(a[i] != i+start) return 1;
+
+ return 0;
+}
+int *fip(x)
+int x;
+{
+ static int y;
+ y = x;
+ return &y;
+}
+glork(x)
+int x;
+{return x;}
+s85(pd0) /* 8.5 Structure and union declarations */
+struct defs *pd0;
+{
+ static char s85er[] = "s85,er%d\n";
+ static char qs85[8] = "s85 ";
+ int rc;
+ char *ps, *pt;
+
+ struct tnode {
+ char tword[20];
+ int count;
+ struct tnode *left;
+ struct tnode *right;
+ };
+
+ struct tnode s1, s2, *sp;
+
+ struct{
+ char cdummy;
+ char c;
+ } sc;
+
+ struct{
+ char cdummy;
+ short s;
+ } ss;
+
+ struct{
+ char cdummy;
+ int i;
+ } si;
+
+ struct{
+ char cdummy;
+ long l;
+ } sl;
+
+ struct{
+ char cdummy;
+ unsigned u;
+ } su;
+
+ struct{
+ char cdummy;
+ float f;
+ } sf;
+
+ struct{
+ char cdummy;
+ double d;
+ } sd;
+
+ int diff[7], j;
+
+ static char *type[] = {
+ "char",
+ "short",
+ "int",
+ "long",
+ "unsigned",
+ "float",
+ "double"
+ };
+
+ static char aln[] = " alignment: ";
+
+ struct{
+ int twobit:2;
+ int :1;
+ int threebit:3;
+ int onebit:1;
+ } s3;
+
+ union{
+ char u1[30];
+ short u2[30];
+ int u3[30];
+ long u4[30];
+ unsigned u5[30];
+ float u6[30];
+ double u7[30];
+ } u0;
+
+ ps = qs85;
+ pt = pd0->rfs;
+ rc = 0;
+ while (*pt++ = *ps++);
+
+ /* Within a structure, the objects declared have
+ addresses which increase as their declarations are
+ read left to right.
+ */
+
+ if( (char *)&s1.count - &s1.tword[0] <= 0
+ ||(char *)&s1.left - (char *)&s1.count <= 0
+ ||(char *)&s1.right - (char *)&s1.left <= 0){
+ if(pd0->flgd != 0) printf(s85er,1);
+ rc = rc+1;
+ }
+
+ /* Each non-field member of a structure begins on an
+ addressing boundary appropriate to its type.
+ */
+
+ diff[0] = &sc.c - &sc.cdummy;
+ diff[1] = (char *)&ss.s - &ss.cdummy;
+ diff[2] = (char *)&si.i - &si.cdummy;
+ diff[3] = (char *)&sl.l - &sl.cdummy;
+ diff[4] = (char *)&su.u - &su.cdummy;
+ diff[5] = (char *)&sf.f - &sf.cdummy;
+ diff[6] = (char *)&sd.d - &sd.cdummy;
+
+ if(pd0->flgm != 0)
+ for(j=0; j<7; j++)
+ printf("%s%s%d\n",type[j],aln,diff[j]);
+
+ /* Field specifications are highly implementation de-
+ pendent. About the only thing we can do here is to
+ check is that the compiler accepts the field constructs,
+ and that they seem to work, after a fashion, at
+ run time...
+ */
+
+ s3.threebit = 7;
+ s3.twobit = s3.threebit;
+ s3.threebit = s3.twobit;
+
+ if(s3.threebit != 3){
+ if(s3.threebit == -1){
+ if(pd0->flgm != 0) printf("Sign extension in fields\n");
+ }
+ else{
+ if(pd0->flgd != 0) printf(s85er,2);
+ rc = rc+2;
+ }
+ }
+
+ s3.onebit = 1;
+ if(s3.onebit != 1){
+ if(pd0->flgm != 0)
+ printf("Be especially careful with 1-bit fields!\n");
+ }
+
+ /* A union may be thought of as a structure all of whose
+ members begin at offset 0 and whose size is sufficient
+ to contain any of its members.
+ */
+
+ if( (char *)u0.u1 - (char *)&u0 != 0
+ ||(char *)u0.u2 - (char *)&u0 != 0
+ ||(char *)u0.u3 - (char *)&u0 != 0
+ ||(char *)u0.u4 - (char *)&u0 != 0
+ ||(char *)u0.u5 - (char *)&u0 != 0
+ ||(char *)u0.u6 - (char *)&u0 != 0
+ ||(char *)u0.u7 - (char *)&u0 != 0){
+
+ if(pd0->flgd != 0) printf(s85er,4);
+ rc = rc+4;
+ }
+
+ if( sizeof u0 < sizeof u0.u1
+ ||sizeof u0 < sizeof u0.u2
+ ||sizeof u0 < sizeof u0.u3
+ ||sizeof u0 < sizeof u0.u4
+ ||sizeof u0 < sizeof u0.u5
+ ||sizeof u0 < sizeof u0.u6
+ ||sizeof u0 < sizeof u0.u7){
+
+ if(pd0->flgd != 0) printf(s85er,8);
+ rc = rc+8;
+ }
+
+ /* Finally, we check that the pointers work. */
+
+ s1.right = &s2;
+ s2.tword[0] = 2;
+ s1.right->tword[0] += 1;
+ if(s2.tword[0] != 3){
+ if(pd0->flgd != 0) printf(s85er,16);
+ rc = rc+16;
+ }
+ return rc;
+}
+s86(pd0) /* 8.6 Initialization */
+struct defs *pd0;
+{
+ static char s86er[] = "s86,er%d\n";
+ static char qs86[8] = "s86 ";
+ int lrc, rc;
+ char *ps, *pt;
+ int one(), i, j, k;
+ static int x[] = {1,3,5};
+ static int *pint = x+2;
+ static int zero[10];
+ int *apint = pint-1;
+ register int *rpint = apint+one();
+ static float y0[] = {1,3,5,2,4,6,3,5,7,0,0,0};
+ static float y1[4][3] = {
+ {1,3,5},
+ {2,4,6},
+ {3,5,7},
+ };
+ static float y2[4][3] = {1,3,5,2,4,6,3,5,7};
+ static float y3[4][3] = {
+ {1},{2},{3},{4}
+ };
+ ps = qs86;
+ pt = pd0->rfs;
+ rc = 0;
+ while (*pt++ = *ps++);
+
+ /* The expression in an initializer for a static or
+ external variable must be a constant expression or
+ an expression that reduces to the address of a pre-
+ viously declared variable, possibly offset by a
+ constant expression.
+ */
+
+ if(*pint != 5){
+ if(pd0->flgd != 0) printf(s86er,1);
+ rc = rc+1;
+ }
+
+ /* Automatic and register variables may be initialized
+ by arbitrary expressions involving constants and previously
+ declared variables and functions.
+ */
+
+ if(*apint != 3){
+ if(pd0->flgd != 0) printf(s86er,2);
+ rc = rc+2;
+ }
+
+ if(*rpint != 5){
+ if(pd0->flgd != 0) printf(s86er,4);
+ rc = rc+4;
+ }
+
+ /* Static variables that are not initialized are guar-
+ anteed to start off as zero.
+ */
+
+ lrc = 0;
+ for(j=0; j<10; j++)
+ if(zero[j] != 0) lrc = 1;
+ if(lrc != 0){
+ if(pd0->flgd != 0) printf(s86er,8);
+ rc = rc+8;
+ }
+
+ /* y0, y1, and y2, as declared, should define and
+ initialize identical arrays.
+ */
+ lrc = 0;
+ for(i=0; i<4; i++)
+ for(j=0; j<3; j++){
+ k = 3*i+j;
+ if( y1[i][j] != y2[i][j]
+ ||y1[i][j] != y0[k]) lrc = 1;
+ }
+
+ if(lrc != 0){
+ if(pd0->flgd != 0) printf(s86er,16);
+ rc = rc+16;
+ }
+
+ /* y3 initializes the first column of the array and
+ leaves the rest zero.
+ */
+
+ lrc = 0;
+ for(j=0; j<4; j++) if(y3[j][0] != j+1) lrc = 1;
+
+ if(lrc != 0){
+ if(pd0->flgd != 0) printf(s86er,32);
+ rc = rc+32;
+ }
+ return rc;
+}
+one(){
+ return 1;
+}
+int *metricp;
+s88(pd0) /* 8.8 Typedef */
+struct defs *pd0;
+{
+ static char s88er[] = "s88,er%d\n";
+ static char qs88[8] = "s88 ";
+ int rc;
+ char *ps, *pt;
+
+ /* Declarations whose "storage class" is typdef do not
+ define storage, but instead define identifiers which
+ can later be used as if they were type keywords naming
+ fundamental or derived types.
+ */
+
+ typedef int MILES, *KLICKSP;
+ typedef struct {double re, im;} complex;
+
+ MILES distance;
+ extern KLICKSP metricp;
+ complex z, *zp;
+
+ ps = qs88;
+ pt = pd0->rfs;
+ rc = 0;
+ while(*pt++ = *ps++);
+
+ /* Hopefully, all of this stuff will compile. After that,
+ we can only make some superficial tests.
+
+ The type of distance is int,
+ */
+
+ if(sizeof distance != sizeof(int)){
+ if(pd0->flgd != 0) printf(s88er,1);
+ rc = rc+1;
+ }
+
+ /* that of metricp is "pointer to int", */
+
+ metricp = &distance;
+ distance = 2;
+ *metricp = 3;
+
+ if(distance != 3){
+ if(pd0->flgd != 0) printf(s88er,2);
+ rc = rc+2;
+ }
+
+ /* and that of z is the specified structure. zp is a
+ pointer to such a structure.
+ */
+
+ z.re = 0.;
+ z.im = 0.;
+ zp = &z;
+ zp->re = 1.;
+ zp->im = 1.;
+ if(z.re+z.im != 2.){
+ if(pd0->flgd != 0) printf(s88er,4);
+ rc = rc+4;
+ }
+
+ return rc;
+}
+s9(pd0) /* 9 Statements */
+struct defs *pd0;
+{
+ static char s9er[] = "s9,er%d\n";
+ static char qs9[8] = "s9 ";
+ int rc;
+ char *ps, *pt;
+ int lrc, i;
+
+ ps = qs9;
+ pt = pd0->rfs;
+ rc = 0;
+ while (*pt++ = *ps++);
+
+ /* One would think that the section on statements would
+ provide the most variety in the entire sequence of tests.
+ As it turns out, most of the material in this section has
+ already been checked in the process of checking out
+ everything else, and the section at this point is somewhat
+ anticlimactic. For this reason, we restrict ourselves
+ to testing two features not already covered.
+
+ Compound statements are delimited by braces. They have the
+ nice property that identifiers of the auto and register
+ variety are pushed and popped. It is currently legal to
+ transfer into a block, but we wont...
+ */
+
+ lrc = 0;
+ for(i=0; i<2; i++){
+ int j;
+ register int k;
+ j = k = 2;
+ {
+ int j;
+ register int k;
+ j = k = 3;
+ if((j != 3) || (k != 3)) lrc = 1;
+ }
+ if((j != 2) || (k != 2)) lrc = 1;
+ }
+
+ if(lrc != 0){
+ if(pd0->flgd != 0) printf(s9er,1);
+ rc = rc+1;
+ }
+
+ /* Goto statements go to labeled statements, we hope. */
+
+ goto nobarf;
+ if(pd0->flgd != 0) printf(s9er,2);
+ rc = rc+2;
+ nobarf:;
+
+ return rc;
+}
+setev(){ /* Sets an external variable. Used */
+ extern int extvar; /* by s4, and should be compiled */
+ extvar = 1066; /* separately from s4. */
+}
+ int lbits; /* long */
+ int ubits; /* unsigned */
+ int fbits; /* float */
+ int dbits; /* double */
+ float fprec; /* Smallest number that can be */
+ float dprec; /* significantly added to 1. */
+ int flgs; /* Print return codes, by section */
+ int flgm; /* Announce machine dependencies */
+ int flgd; /* give explicit diagnostics */
+ int flgl; /* Report local return codes. */
+ int rrc; /* recent return code */
+ int crc; /* Cumulative return code */
+ char rfs[8]; /* Return from section */
diff --git a/lcc/tst/cvt.0 b/lcc/tst/cvt.0
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/tst/cvt.0
diff --git a/lcc/tst/cvt.c b/lcc/tst/cvt.c
new file mode 100755
index 0000000..4fb7186
--- /dev/null
+++ b/lcc/tst/cvt.c
@@ -0,0 +1,35 @@
+signed char c;
+signed short s;
+signed int i;
+signed long int l;
+unsigned char C;
+unsigned short S;
+unsigned int I;
+unsigned long int L;
+float f;
+double d;
+long double D;
+void *p;
+void (*P)(void);
+
+void print(void) {
+ printf("%d %d %d %ld %u %u %u %lu %f %f %lf\n",c,s,i,l,C,S,I,L,f,d,D);
+}
+
+main() {
+ c= 1; s=c;i=c;l=c;C=c;S=c;I=c;L=c;f=c;d=c;D=c; print();
+ s= 2; c=s; i=s;l=s;C=s;S=s;I=s;L=s;f=s;d=s;D=s; print();
+ i= 3; c=i;s=i; l=i;C=i;S=i;I=i;L=i;f=i;d=i;D=i; print();
+ l= 4; c=l;s=l;i=l; C=l;S=l;I=l;L=l;f=l;d=l;D=l; print();
+ C= 5; c=C;s=C;i=C;l=C; S=C;I=C;L=C;f=C;d=C;D=C; print();
+ S= 6; c=S;s=S;i=S;l=S;C=S; I=S;L=S;f=S;d=S;D=S; print();
+ I= 7; c=I;s=I;i=I;l=I;C=I;S=I; L=I;f=I;d=I;D=I; print();
+ L= 8; c=L;s=L;i=L;l=L;C=L;S=L;I=S; f=L;d=L;D=L; print();
+ f= 9; c=f;s=f;i=f;l=f;C=f;S=f;I=f;L=f; d=f;D=f; print();
+ d=10; c=d;s=d;i=d;l=d;C=d;S=d;I=d;L=d;f=d; D=d; print();
+ D=11; c=D;s=D;i=D;l=D;C=D;S=D;I=D;L=D;f=D;d=D; print();
+
+ p=0; p=0L; p=0U; p=0UL; p=P;
+ P=0; P=0L; P=0U; P=0UL; P=p;
+ return 0;
+}
diff --git a/lcc/tst/fields.0 b/lcc/tst/fields.0
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/tst/fields.0
diff --git a/lcc/tst/fields.c b/lcc/tst/fields.c
new file mode 100755
index 0000000..658f4f6
--- /dev/null
+++ b/lcc/tst/fields.c
@@ -0,0 +1,34 @@
+struct foo {
+ int a;
+ char b;
+ int x : 12, y : 4, : 0, : 4, z : 3;
+ char c;
+} x = { 1, 2, 3, 4, 5, 6 };
+int i = 16;
+struct baz { unsigned int a:2, b:4, c:32;} y = { 7, 8, 9};
+
+main()
+{
+ printf("x = %d %d %d %d %d %d\n", x.a, x.b, x.x, x.y, x.z, x.c);
+ printf("y = %d %d %d\n", y.a, y.b, y.c);
+ x.y = i;
+ x.z = 070;
+ printf("x = %d %d %d %d %d %d\n", x.a, x.b, x.x, x.y, x.z, x.c);
+ y.a = 2;
+ y.c = i;
+ printf("y = %d %d %d\n", y.a, y.b, y.c);
+ f2(&x);
+ return 0;
+}
+
+f1(struct baz *p) {
+ p->a = p->b = 0;
+ if (p->b)
+ printf("p->b != 0!\n");
+ p->a = 0x3; p->b = 0xf;
+ printf("p->a = 0x%x, p->b = 0x%x\n", p->a, p->b);
+}
+f2(struct baz *p) {
+ p->a = (i==0);
+ p->b = (f1(p),0);
+}
diff --git a/lcc/tst/front.0 b/lcc/tst/front.0
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/tst/front.0
diff --git a/lcc/tst/front.c b/lcc/tst/front.c
new file mode 100755
index 0000000..0ce8ae7
--- /dev/null
+++ b/lcc/tst/front.c
@@ -0,0 +1,120 @@
+main() {
+ exit(0);
+}
+
+nested(a,b) {
+ if ((a<4 && b == 'r')
+ || (a == 1 && (b == 'h' || b == 'i'))
+ || (a == 2 && (b == 'o' || b == 'y'))
+ ) a=b;
+}
+
+/* type name scope */
+
+void s(struct D *d) {} /* this struct D differs from the one below */
+typedef struct D D;
+struct D {int x, y;} Dy={0};
+D Dz={1};
+Dfunc(){
+ D a; a.y=1;
+ s(&Dy); /* error */
+}
+
+/* qualifiers */
+
+const a; int b;
+const int a, *x; int b, *y;
+volatile unsigned z;
+
+f() {
+ x = y;
+ z = z + z; /* should be 2 references to z's r-value */
+}
+f1() {
+ x = &a;
+ x = &b;
+ y = &a; /* error */
+ y = &b;
+}
+f2(int **a, int **b) {
+ f(&x, &y);
+ **a = 0;
+ return **b;
+}
+g(const int *p) {
+ g(&a);
+ g(&b);
+ return *p;
+}
+h(int *p) {
+ f(&a);
+ f(&b);
+ return *p;
+}
+h1(const int x, int y) {
+ h1(a,b);
+ h1(b,a);
+ return x + y;
+}
+h2() {
+ char *b; const void *p;
+ p = b;
+ b = p; /* error */
+}
+
+
+/* static naming */
+
+extern int yy; set1() { { static yy=1; yy=2;} yy=4;}
+static int yy; set2() { yy=5; {static yy=2; yy=3; }}
+static void goo() {}
+sss() { int goo; { static int goo();} goo=1;}
+rrr(p) float *p; { extern int xr;
+ { static float xr;
+ { extern int *xr; } p=&xr; }}
+
+/* local extern */
+
+static int ss1;
+int ss3;
+extern int ss5;
+setstatic() { extern int ss1,ss2,ss3,ss4; ss1 = ss2; ss3 = ss4; ss5 = 0;}
+static int ss2;
+int ss4;
+static int ss5;
+
+/* function prototypes */
+
+int fx1(void);
+int fx1();
+
+int gx1(double x);
+int gx1(x) double x; { gx1(&x); } /* error */
+
+int hx1();
+int hx1(double x,...); /* error */
+
+int ff1(double x, int *y);
+int ff1(x,y) float x; int y[]; {x=y[0];}
+
+int gg1(int a);
+int gg1(a,b){a=b;}
+
+int hh1(const int x);
+hh1(a) {return a;}
+
+extern int strcmp(const char*, const char*);
+extern void qsort(void*, int, int, int (*)(const void*, const void*));
+extern int cmp(char**a, char**b) { return strcmp(*a,*b); }
+sort() {
+ int n; char *a[100];
+ qsort(a, n, sizeof(char*), (int (*)(const void*, const void*))cmp);
+ qsort(a, n, sizeof(char*), cmp); /* error */
+}
+
+/* nasty calls */
+
+onearg(){
+ int a,b,c,d;
+ f( ( (a? (b = 1): (c = 2)), (d ? 3 : 4) ) ); /* 1 argument */
+}
diff --git a/lcc/tst/incr.0 b/lcc/tst/incr.0
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/tst/incr.0
diff --git a/lcc/tst/incr.c b/lcc/tst/incr.c
new file mode 100755
index 0000000..d3d6144
--- /dev/null
+++ b/lcc/tst/incr.c
@@ -0,0 +1,39 @@
+main() {}
+
+memchar() {
+ char x, *p;
+
+ &x, &p;
+ x = *p++;
+ x = *++p;
+ x = *p--;
+ x = *--p;
+}
+
+memint() {
+ int x, *p;
+
+ &x, &p;
+ x = *p++;
+ x = *++p;
+ x = *p--;
+ x = *--p;
+}
+
+regchar() {
+ register char x, *p;
+
+ x = *p++;
+ x = *++p;
+ x = *p--;
+ x = *--p;
+}
+
+regint() {
+ register int x, *p;
+
+ x = *p++;
+ x = *++p;
+ x = *p--;
+ x = *--p;
+}
diff --git a/lcc/tst/init.0 b/lcc/tst/init.0
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/tst/init.0
diff --git a/lcc/tst/init.c b/lcc/tst/init.c
new file mode 100755
index 0000000..310c707
--- /dev/null
+++ b/lcc/tst/init.c
@@ -0,0 +1,59 @@
+
+typedef struct { int codes[3]; char name[6]; } Word;
+
+Word words[] = {
+ 1, 2, 3, "if",
+ { { 4, 5 }, { 'f', 'o', 'r' } },
+ 6, 7, 8, {"else"},
+ { { 9, 10, 11,}, 'w', 'h', 'i', 'l', 'e', },
+ { 0 },
+}, *wordlist = words;
+
+int x[][5] = { 1, 2, 3, 4, 0, { 5, 6 }, { 7 } };
+int *y[] = { x[0], x[1], x[2], 0 };
+
+
+main()
+{
+ int i, j;
+
+ for (i = 0; y[i]; i++) {
+ for (j = 0; y[i][j]; j++)
+ printf(" %d", y[i][j]);
+ printf("\n");
+ }
+ f();
+ g(wordlist);
+ return 0;
+}
+
+f() {
+ static char *keywords[] = {"if", "for", "else", "while", 0, };
+ char **p;
+
+ for (p = keywords; *p; p++)
+ printf("%s\n", *p);
+}
+
+g(p)
+Word *p;
+{
+ int i;
+
+ for ( ; p->codes[0]; p++) {
+ for (i = 0; i < sizeof p->codes/sizeof(p->codes[0]); i++)
+ printf("%d ", p->codes[i]);
+ printf("%s\n", p->name);
+ }
+ h();
+}
+
+h()
+{
+ int i;
+
+ for (i = 0; i < sizeof(words)/sizeof(Word); i++)
+ printf("%d %d %d %s\n", words[i].codes[0],
+ words[i].codes[1], words[i].codes[2],
+ &words[i].name[0]);
+}
diff --git a/lcc/tst/limits.0 b/lcc/tst/limits.0
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/tst/limits.0
diff --git a/lcc/tst/limits.c b/lcc/tst/limits.c
new file mode 100755
index 0000000..03b1806
--- /dev/null
+++ b/lcc/tst/limits.c
@@ -0,0 +1,19 @@
+#include <limits.h>
+
+main() {
+ printf("UCHAR_MAX: %08x=%d\n", UCHAR_MAX, UCHAR_MAX);
+ printf("USHRT_MAX: %08x=%d\n", USHRT_MAX, USHRT_MAX);
+ printf("UINT_MAX: %08x=%d\n", UINT_MAX, UINT_MAX);
+ printf("ULONG_MAX: %08lx=%ld\n", ULONG_MAX, ULONG_MAX);
+ printf("CHAR_MAX: %08x=%d\n", CHAR_MAX, CHAR_MAX);
+ printf("SCHAR_MAX: %08x=%d\n", SCHAR_MAX, SCHAR_MAX);
+ printf("SHRT_MAX: %08x=%d\n", SHRT_MAX, SHRT_MAX);
+ printf("INT_MAX: %08x=%d\n", INT_MAX, INT_MAX);
+ printf("LONG_MAX: %08lx=%ld\n", LONG_MAX, LONG_MAX);
+ printf("CHAR_MIN: %08x=%d\n", CHAR_MIN, CHAR_MIN);
+ printf("SCHAR_MIN: %08x=%d\n", SCHAR_MIN, SCHAR_MIN);
+ printf("SHRT_MIN: %08x=%d\n", SHRT_MIN, SHRT_MIN);
+ printf("INT_MIN: %08x=%d\n", INT_MIN, INT_MIN);
+ printf("LONG_MIN: %08lx=%ld\n", LONG_MIN, LONG_MIN);
+ return 0;
+}
diff --git a/lcc/tst/paranoia.0 b/lcc/tst/paranoia.0
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/tst/paranoia.0
diff --git a/lcc/tst/paranoia.c b/lcc/tst/paranoia.c
new file mode 100755
index 0000000..76e0f05
--- /dev/null
+++ b/lcc/tst/paranoia.c
@@ -0,0 +1,2203 @@
+#undef V9
+#define NOPAUSE
+/* A C version of Kahan's Floating Point Test "Paranoia"
+
+ Thos Sumner, UCSF, Feb. 1985
+ David Gay, BTL, Jan. 1986
+
+ This is a rewrite from the Pascal version by
+
+ B. A. Wichmann, 18 Jan. 1985
+
+ (and does NOT exhibit good C programming style).
+
+(C) Apr 19 1983 in BASIC version by:
+ Professor W. M. Kahan,
+ 567 Evans Hall
+ Electrical Engineering & Computer Science Dept.
+ University of California
+ Berkeley, California 94720
+ USA
+
+converted to Pascal by:
+ B. A. Wichmann
+ National Physical Laboratory
+ Teddington Middx
+ TW11 OLW
+ UK
+
+converted to C by:
+
+ David M. Gay and Thos Sumner
+ AT&T Bell Labs Computer Center, Rm. U-76
+ 600 Mountain Avenue University of California
+ Murray Hill, NJ 07974 San Francisco, CA 94143
+ USA USA
+
+with simultaneous corrections to the Pascal source (reflected
+in the Pascal source available over netlib).
+[A couple of bug fixes from dgh = sun!dhough incorporated 31 July 1986.]
+
+Reports of results on various systems from all the versions
+of Paranoia are being collected by Richard Karpinski at the
+same address as Thos Sumner. This includes sample outputs,
+bug reports, and criticisms.
+
+You may copy this program freely if you acknowledge its source.
+Comments on the Pascal version to NPL, please.
+
+
+The C version catches signals from floating-point exceptions.
+If signal(SIGFPE,...) is unavailable in your environment, you may
+#define NOSIGNAL to comment out the invocations of signal.
+
+This source file is too big for some C compilers, but may be split
+into pieces. Comments containing "SPLIT" suggest convenient places
+for this splitting. At the end of these comments is an "ed script"
+(for the UNIX(tm) editor ed) that will do this splitting.
+
+By #defining Single when you compile this source, you may obtain
+a single-precision C version of Paranoia.
+
+
+The following is from the introductory commentary from Wichmann's work:
+
+The BASIC program of Kahan is written in Microsoft BASIC using many
+facilities which have no exact analogy in Pascal. The Pascal
+version below cannot therefore be exactly the same. Rather than be
+a minimal transcription of the BASIC program, the Pascal coding
+follows the conventional style of block-structured languages. Hence
+the Pascal version could be useful in producing versions in other
+structured languages.
+
+Rather than use identifiers of minimal length (which therefore have
+little mnemonic significance), the Pascal version uses meaningful
+identifiers as follows [Note: A few changes have been made for C]:
+
+
+BASIC C BASIC C BASIC C
+
+ A J S StickyBit
+ A1 AInverse J0 NoErrors T
+ B Radix [Failure] T0 Underflow
+ B1 BInverse J1 NoErrors T2 ThirtyTwo
+ B2 RadixD2 [SeriousDefect] T5 OneAndHalf
+ B9 BMinusU2 J2 NoErrors T7 TwentySeven
+ C [Defect] T8 TwoForty
+ C1 CInverse J3 NoErrors U OneUlp
+ D [Flaw] U0 UnderflowThreshold
+ D4 FourD K PageNo U1
+ E0 L Milestone U2
+ E1 M V
+ E2 Exp2 N V0
+ E3 N1 V8
+ E5 MinSqEr O Zero V9
+ E6 SqEr O1 One W
+ E7 MaxSqEr O2 Two X
+ E8 O3 Three X1
+ E9 O4 Four X8
+ F1 MinusOne O5 Five X9 Random1
+ F2 Half O8 Eight Y
+ F3 Third O9 Nine Y1
+ F6 P Precision Y2
+ F9 Q Y9 Random2
+ G1 GMult Q8 Z
+ G2 GDiv Q9 Z0 PseudoZero
+ G3 GAddSub R Z1
+ H R1 RMult Z2
+ H1 HInverse R2 RDiv Z9
+ I R3 RAddSub
+ IO NoTrials R4 RSqrt
+ I3 IEEE R9 Random9
+
+ SqRWrng
+
+All the variables in BASIC are true variables and in consequence,
+the program is more difficult to follow since the "constants" must
+be determined (the glossary is very helpful). The Pascal version
+uses Real constants, but checks are added to ensure that the values
+are correctly converted by the compiler.
+
+The major textual change to the Pascal version apart from the
+identifiersis that named procedures are used, inserting parameters
+wherehelpful. New procedures are also introduced. The
+correspondence is as follows:
+
+
+BASIC Pascal
+lines
+
+ 90- 140 Pause
+ 170- 250 Instructions
+ 380- 460 Heading
+ 480- 670 Characteristics
+ 690- 870 History
+2940-2950 Random
+3710-3740 NewD
+4040-4080 DoesYequalX
+4090-4110 PrintIfNPositive
+4640-4850 TestPartialUnderflow
+
+=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
+
+Below is an "ed script" that splits para.c into 10 files
+of the form part[1-8].c, subs.c, and msgs.c, plus a header
+file, paranoia.h, that these files require.
+
+r paranoia.c
+$
+?SPLIT
++,$w msgs.c
+ .,$d
+?SPLIT
+ .d
++d
+-,$w subs.c
+-,$d
+?part8
++d
+?include
+ .,$w part8.c
+ .,$d
+-d
+?part7
++d
+?include
+ .,$w part7.c
+ .,$d
+-d
+?part6
++d
+?include
+ .,$w part6.c
+ .,$d
+-d
+?part5
++d
+?include
+ .,$w part5.c
+ .,$d
+-d
+?part4
++d
+?include
+ .,$w part4.c
+ .,$d
+-d
+?part3
++d
+?include
+ .,$w part3.c
+ .,$d
+-d
+?part2
++d
+?include
+ .,$w part2.c
+ .,$d
+?SPLIT
+ .d
+1,/^#include/-1d
+1,$w part1.c
+/Computed constants/,$d
+1,$s/^int/extern &/
+1,$s/^FLOAT/extern &/
+1,$s/^char/extern &/
+1,$s! = .*!;!
+/^Guard/,/^Round/s/^/extern /
+/^jmp_buf/s/^/extern /
+/^Sig_type/s/^/extern /
+s/$/\
+extern void sigfpe();/
+w paranoia.h
+q
+
+*/
+
+#include <stdio.h>
+#ifndef NOSIGNAL
+#include <signal.h>
+#endif
+#include <setjmp.h>
+
+extern double fabs(), floor(), log(), pow(), sqrt();
+
+#ifdef Single
+#define FLOAT float
+#define FABS(x) (float)fabs((double)(x))
+#define FLOOR(x) (float)floor((double)(x))
+#define LOG(x) (float)log((double)(x))
+#define POW(x,y) (float)pow((double)(x),(double)(y))
+#define SQRT(x) (float)sqrt((double)(x))
+#else
+#define FLOAT double
+#define FABS(x) fabs(x)
+#define FLOOR(x) floor(x)
+#define LOG(x) log(x)
+#define POW(x,y) pow(x,y)
+#define SQRT(x) sqrt(x)
+#endif
+
+jmp_buf ovfl_buf;
+typedef void (*Sig_type)();
+Sig_type sigsave;
+
+#define KEYBOARD 0
+
+FLOAT Radix, BInvrse, RadixD2, BMinusU2;
+FLOAT Sign(), Random();
+
+/*Small floating point constants.*/
+FLOAT Zero = 0.0;
+FLOAT Half = 0.5;
+FLOAT One = 1.0;
+FLOAT Two = 2.0;
+FLOAT Three = 3.0;
+FLOAT Four = 4.0;
+FLOAT Five = 5.0;
+FLOAT Eight = 8.0;
+FLOAT Nine = 9.0;
+FLOAT TwentySeven = 27.0;
+FLOAT ThirtyTwo = 32.0;
+FLOAT TwoForty = 240.0;
+FLOAT MinusOne = -1.0;
+FLOAT OneAndHalf = 1.5;
+/*Integer constants*/
+int NoTrials = 20; /*Number of tests for commutativity. */
+#define False 0
+#define True 1
+
+/* Definitions for declared types
+ Guard == (Yes, No);
+ Rounding == (Chopped, Rounded, Other);
+ Message == packed array [1..40] of char;
+ Class == (Flaw, Defect, Serious, Failure);
+ */
+#define Yes 1
+#define No 0
+#define Chopped 2
+#define Rounded 1
+#define Other 0
+#define Flaw 3
+#define Defect 2
+#define Serious 1
+#define Failure 0
+typedef int Guard, Rounding, Class;
+typedef char Message;
+
+/* Declarations of Variables */
+int Indx;
+char ch[8];
+FLOAT AInvrse, A1;
+FLOAT C, CInvrse;
+FLOAT D, FourD;
+FLOAT E0, E1, Exp2, E3, MinSqEr;
+FLOAT SqEr, MaxSqEr, E9;
+FLOAT Third;
+FLOAT F6, F9;
+FLOAT H, HInvrse;
+int I;
+FLOAT StickyBit, J;
+FLOAT MyZero;
+FLOAT Precision;
+FLOAT Q, Q9;
+FLOAT R, Random9;
+FLOAT T, Underflow, S;
+FLOAT OneUlp, UfThold, U1, U2;
+FLOAT V, V0, V9;
+FLOAT W;
+FLOAT X, X1, X2, X8, Random1;
+FLOAT Y, Y1, Y2, Random2;
+FLOAT Z, PseudoZero, Z1, Z2, Z9;
+int ErrCnt[4];
+int fpecount;
+int Milestone;
+int PageNo;
+int M, N, N1;
+Guard GMult, GDiv, GAddSub;
+Rounding RMult, RDiv, RAddSub, RSqrt;
+int Break, Done, NotMonot, Monot, Anomaly, IEEE,
+ SqRWrng, UfNGrad;
+/* Computed constants. */
+/*U1 gap below 1.0, i.e, 1.0-U1 is next number below 1.0 */
+/*U2 gap above 1.0, i.e, 1.0+U2 is next number above 1.0 */
+
+/* floating point exception receiver */
+ void
+sigfpe(i)
+{
+ fpecount++;
+ printf("\n* * * FLOATING-POINT ERROR * * *\n");
+ fflush(stdout);
+ if (sigsave) {
+#ifndef NOSIGNAL
+ signal(SIGFPE, sigsave);
+#endif
+ sigsave = 0;
+ longjmp(ovfl_buf, 1);
+ }
+ abort();
+}
+
+main()
+{
+#ifdef mc
+ char *out;
+ ieee_flags("set", "precision", "double", &out);
+#endif
+ /* First two assignments use integer right-hand sides. */
+ Zero = 0;
+ One = 1;
+ Two = One + One;
+ Three = Two + One;
+ Four = Three + One;
+ Five = Four + One;
+ Eight = Four + Four;
+ Nine = Three * Three;
+ TwentySeven = Nine * Three;
+ ThirtyTwo = Four * Eight;
+ TwoForty = Four * Five * Three * Four;
+ MinusOne = -One;
+ Half = One / Two;
+ OneAndHalf = One + Half;
+ ErrCnt[Failure] = 0;
+ ErrCnt[Serious] = 0;
+ ErrCnt[Defect] = 0;
+ ErrCnt[Flaw] = 0;
+ PageNo = 1;
+ /*=============================================*/
+ Milestone = 0;
+ /*=============================================*/
+#ifndef NOSIGNAL
+ signal(SIGFPE, sigfpe);
+#endif
+ Instructions();
+ Pause();
+ Heading();
+ Pause();
+ Characteristics();
+ Pause();
+ History();
+ Pause();
+ /*=============================================*/
+ Milestone = 7;
+ /*=============================================*/
+ printf("Program is now RUNNING tests on small integers:\n");
+
+ TstCond (Failure, (Zero + Zero == Zero) && (One - One == Zero)
+ && (One > Zero) && (One + One == Two),
+ "0+0 != 0, 1-1 != 0, 1 <= 0, or 1+1 != 2");
+ Z = - Zero;
+ if (Z != 0.0) {
+ ErrCnt[Failure] = ErrCnt[Failure] + 1;
+ printf("Comparison alleges that -0.0 is Non-zero!\n");
+ U1 = 0.001;
+ Radix = 1;
+ TstPtUf();
+ }
+ TstCond (Failure, (Three == Two + One) && (Four == Three + One)
+ && (Four + Two * (- Two) == Zero)
+ && (Four - Three - One == Zero),
+ "3 != 2+1, 4 != 3+1, 4+2*(-2) != 0, or 4-3-1 != 0");
+ TstCond (Failure, (MinusOne == (0 - One))
+ && (MinusOne + One == Zero ) && (One + MinusOne == Zero)
+ && (MinusOne + FABS(One) == Zero)
+ && (MinusOne + MinusOne * MinusOne == Zero),
+ "-1+1 != 0, (-1)+abs(1) != 0, or -1+(-1)*(-1) != 0");
+ TstCond (Failure, Half + MinusOne + Half == Zero,
+ "1/2 + (-1) + 1/2 != 0");
+ /*=============================================*/
+ /*SPLIT
+ part2();
+ part3();
+ part4();
+ part5();
+ part6();
+ part7();
+ part8();
+ }
+#include "paranoia.h"
+part2(){
+*/
+ Milestone = 10;
+ /*=============================================*/
+ TstCond (Failure, (Nine == Three * Three)
+ && (TwentySeven == Nine * Three) && (Eight == Four + Four)
+ && (ThirtyTwo == Eight * Four)
+ && (ThirtyTwo - TwentySeven - Four - One == Zero),
+ "9 != 3*3, 27 != 9*3, 32 != 8*4, or 32-27-4-1 != 0");
+ TstCond (Failure, (Five == Four + One) &&
+ (TwoForty == Four * Five * Three * Four)
+ && (TwoForty / Three - Four * Four * Five == Zero)
+ && ( TwoForty / Four - Five * Three * Four == Zero)
+ && ( TwoForty / Five - Four * Three * Four == Zero),
+ "5 != 4+1, 240/3 != 80, 240/4 != 60, or 240/5 != 48");
+ if (ErrCnt[Failure] == 0) {
+ printf("-1, 0, 1/2, 1, 2, 3, 4, 5, 9, 27, 32 & 240 are O.K.\n");
+ printf("\n");
+ }
+ printf("Searching for Radix and Precision.\n");
+ W = One;
+ do {
+ W = W + W;
+ Y = W + One;
+ Z = Y - W;
+ Y = Z - One;
+ } while (MinusOne + FABS(Y) < Zero);
+ /*.. now W is just big enough that |((W+1)-W)-1| >= 1 ...*/
+ Precision = Zero;
+ Y = One;
+ do {
+ Radix = W + Y;
+ Y = Y + Y;
+ Radix = Radix - W;
+ } while ( Radix == Zero);
+ if (Radix < Two) Radix = One;
+ printf("Radix = %f .\n", Radix);
+ if (Radix != 1) {
+ W = One;
+ do {
+ Precision = Precision + One;
+ W = W * Radix;
+ Y = W + One;
+ } while ((Y - W) == One);
+ }
+ /*... now W == Radix^Precision is barely too big to satisfy (W+1)-W == 1
+ ...*/
+ U1 = One / W;
+ U2 = Radix * U1;
+ printf("Closest relative separation found is U1 = %.7e .\n\n", U1);
+ printf("Recalculating radix and precision\n ");
+
+ /*save old values*/
+ E0 = Radix;
+ E1 = U1;
+ E9 = U2;
+ E3 = Precision;
+
+ X = Four / Three;
+ Third = X - One;
+ F6 = Half - Third;
+ X = F6 + F6;
+ X = FABS(X - Third);
+ if (X < U2) X = U2;
+
+ /*... now X = (unknown no.) ulps of 1+...*/
+ do {
+ U2 = X;
+ Y = Half * U2 + ThirtyTwo * U2 * U2;
+ Y = One + Y;
+ X = Y - One;
+ } while ( ! ((U2 <= X) || (X <= Zero)));
+
+ /*... now U2 == 1 ulp of 1 + ... */
+ X = Two / Three;
+ F6 = X - Half;
+ Third = F6 + F6;
+ X = Third - Half;
+ X = FABS(X + F6);
+ if (X < U1) X = U1;
+
+ /*... now X == (unknown no.) ulps of 1 -... */
+ do {
+ U1 = X;
+ Y = Half * U1 + ThirtyTwo * U1 * U1;
+ Y = Half - Y;
+ X = Half + Y;
+ Y = Half - X;
+ X = Half + Y;
+ } while ( ! ((U1 <= X) || (X <= Zero)));
+ /*... now U1 == 1 ulp of 1 - ... */
+ if (U1 == E1) printf("confirms closest relative separation U1 .\n");
+ else printf("gets better closest relative separation U1 = %.7e .\n", U1);
+ W = One / U1;
+ F9 = (Half - U1) + Half;
+ Radix = FLOOR(0.01 + U2 / U1);
+ if (Radix == E0) printf("Radix confirmed.\n");
+ else printf("MYSTERY: recalculated Radix = %.7e .\n", Radix);
+ TstCond (Defect, Radix <= Eight + Eight,
+ "Radix is too big: roundoff problems");
+ TstCond (Flaw, (Radix == Two) || (Radix == 10)
+ || (Radix == One), "Radix is not as good as 2 or 10");
+ /*=============================================*/
+ Milestone = 20;
+ /*=============================================*/
+ TstCond (Failure, F9 - Half < Half,
+ "(1-U1)-1/2 < 1/2 is FALSE, prog. fails?");
+ X = F9;
+ I = 1;
+ Y = X - Half;
+ Z = Y - Half;
+ TstCond (Failure, (X != One)
+ || (Z == Zero), "Comparison is fuzzy,X=1 but X-1/2-1/2 != 0");
+ X = One + U2;
+ I = 0;
+ /*=============================================*/
+ Milestone = 25;
+ /*=============================================*/
+ /*... BMinusU2 = nextafter(Radix, 0) */
+ BMinusU2 = Radix - One;
+ BMinusU2 = (BMinusU2 - U2) + One;
+ /* Purify Integers */
+ if (Radix != One) {
+ X = - TwoForty * LOG(U1) / LOG(Radix);
+ Y = FLOOR(Half + X);
+ if (FABS(X - Y) * Four < One) X = Y;
+ Precision = X / TwoForty;
+ Y = FLOOR(Half + Precision);
+ if (FABS(Precision - Y) * TwoForty < Half) Precision = Y;
+ }
+ if ((Precision != FLOOR(Precision)) || (Radix == One)) {
+ printf("Precision cannot be characterized by an Integer number\n");
+ printf("of significant digits but, by itself, this is a minor flaw.\n");
+ }
+ if (Radix == One)
+ printf("logarithmic encoding has precision characterized solely by U1.\n");
+ else printf("The number of significant digits of the Radix is %f .\n",
+ Precision);
+ TstCond (Serious, U2 * Nine * Nine * TwoForty < One,
+ "Precision worse than 5 decimal figures ");
+ /*=============================================*/
+ Milestone = 30;
+ /*=============================================*/
+ /* Test for extra-precise subepressions */
+ X = FABS(((Four / Three - One) - One / Four) * Three - One / Four);
+ do {
+ Z2 = X;
+ X = (One + (Half * Z2 + ThirtyTwo * Z2 * Z2)) - One;
+ } while ( ! ((Z2 <= X) || (X <= Zero)));
+ X = Y = Z = FABS((Three / Four - Two / Three) * Three - One / Four);
+ do {
+ Z1 = Z;
+ Z = (One / Two - ((One / Two - (Half * Z1 + ThirtyTwo * Z1 * Z1))
+ + One / Two)) + One / Two;
+ } while ( ! ((Z1 <= Z) || (Z <= Zero)));
+ do {
+ do {
+ Y1 = Y;
+ Y = (Half - ((Half - (Half * Y1 + ThirtyTwo * Y1 * Y1)) + Half
+ )) + Half;
+ } while ( ! ((Y1 <= Y) || (Y <= Zero)));
+ X1 = X;
+ X = ((Half * X1 + ThirtyTwo * X1 * X1) - F9) + F9;
+ } while ( ! ((X1 <= X) || (X <= Zero)));
+ if ((X1 != Y1) || (X1 != Z1)) {
+ BadCond(Serious, "Disagreements among the values X1, Y1, Z1,\n");
+ printf("respectively %.7e, %.7e, %.7e,\n", X1, Y1, Z1);
+ printf("are symptoms of inconsistencies introduced\n");
+ printf("by extra-precise evaluation of arithmetic subexpressions.\n");
+ notify("Possibly some part of this");
+ if ((X1 == U1) || (Y1 == U1) || (Z1 == U1)) printf(
+ "That feature is not tested further by this program.\n") ;
+ }
+ else {
+ if ((Z1 != U1) || (Z2 != U2)) {
+ if ((Z1 >= U1) || (Z2 >= U2)) {
+ BadCond(Failure, "");
+ notify("Precision");
+ printf("\tU1 = %.7e, Z1 - U1 = %.7e\n",U1,Z1-U1);
+ printf("\tU2 = %.7e, Z2 - U2 = %.7e\n",U2,Z2-U2);
+ }
+ else {
+ if ((Z1 <= Zero) || (Z2 <= Zero)) {
+ printf("Because of unusual Radix = %f", Radix);
+ printf(", or exact rational arithmetic a result\n");
+ printf("Z1 = %.7e, or Z2 = %.7e ", Z1, Z2);
+ notify("of an\nextra-precision");
+ }
+ if (Z1 != Z2 || Z1 > Zero) {
+ X = Z1 / U1;
+ Y = Z2 / U2;
+ if (Y > X) X = Y;
+ Q = - LOG(X);
+ printf("Some subexpressions appear to be calculated extra\n");
+ printf("precisely with about %g extra B-digits, i.e.\n",
+ (Q / LOG(Radix)));
+ printf("roughly %g extra significant decimals.\n",
+ Q / LOG(10.));
+ }
+ printf("That feature is not tested further by this program.\n");
+ }
+ }
+ }
+ Pause();
+ /*=============================================*/
+ /*SPLIT
+ }
+#include "paranoia.h"
+part3(){
+*/
+ Milestone = 35;
+ /*=============================================*/
+ if (Radix >= Two) {
+ X = W / (Radix * Radix);
+ Y = X + One;
+ Z = Y - X;
+ T = Z + U2;
+ X = T - Z;
+ TstCond (Failure, X == U2,
+ "Subtraction is not normalized X=Y,X+Z != Y+Z!");
+ if (X == U2) printf(
+ "Subtraction appears to be normalized, as it should be.");
+ }
+ printf("\nChecking for guard digit in *, /, and -.\n");
+ Y = F9 * One;
+ Z = One * F9;
+ X = F9 - Half;
+ Y = (Y - Half) - X;
+ Z = (Z - Half) - X;
+ X = One + U2;
+ T = X * Radix;
+ R = Radix * X;
+ X = T - Radix;
+ X = X - Radix * U2;
+ T = R - Radix;
+ T = T - Radix * U2;
+ X = X * (Radix - One);
+ T = T * (Radix - One);
+ if ((X == Zero) && (Y == Zero) && (Z == Zero) && (T == Zero)) GMult = Yes;
+ else {
+ GMult = No;
+ TstCond (Serious, False,
+ "* lacks a Guard Digit, so 1*X != X");
+ }
+ Z = Radix * U2;
+ X = One + Z;
+ Y = FABS((X + Z) - X * X) - U2;
+ X = One - U2;
+ Z = FABS((X - U2) - X * X) - U1;
+ TstCond (Failure, (Y <= Zero)
+ && (Z <= Zero), "* gets too many final digits wrong.\n");
+ Y = One - U2;
+ X = One + U2;
+ Z = One / Y;
+ Y = Z - X;
+ X = One / Three;
+ Z = Three / Nine;
+ X = X - Z;
+ T = Nine / TwentySeven;
+ Z = Z - T;
+ TstCond(Defect, X == Zero && Y == Zero && Z == Zero,
+ "Division lacks a Guard Digit, so error can exceed 1 ulp\nor 1/3 and 3/9 and 9/27 may disagree");
+ Y = F9 / One;
+ X = F9 - Half;
+ Y = (Y - Half) - X;
+ X = One + U2;
+ T = X / One;
+ X = T - X;
+ if ((X == Zero) && (Y == Zero) && (Z == Zero)) GDiv = Yes;
+ else {
+ GDiv = No;
+ TstCond (Serious, False,
+ "Division lacks a Guard Digit, so X/1 != X");
+ }
+ X = One / (One + U2);
+ Y = X - Half - Half;
+ TstCond (Serious, Y < Zero,
+ "Computed value of 1/1.000..1 >= 1");
+ X = One - U2;
+ Y = One + Radix * U2;
+ Z = X * Radix;
+ T = Y * Radix;
+ R = Z / Radix;
+ StickyBit = T / Radix;
+ X = R - X;
+ Y = StickyBit - Y;
+ TstCond (Failure, X == Zero && Y == Zero,
+ "* and/or / gets too many last digits wrong");
+ Y = One - U1;
+ X = One - F9;
+ Y = One - Y;
+ T = Radix - U2;
+ Z = Radix - BMinusU2;
+ T = Radix - T;
+ if ((X == U1) && (Y == U1) && (Z == U2) && (T == U2)) GAddSub = Yes;
+ else {
+ GAddSub = No;
+ TstCond (Serious, False,
+ "- lacks Guard Digit, so cancellation is obscured");
+ }
+ if (F9 != One && F9 - One >= Zero) {
+ BadCond(Serious, "comparison alleges (1-U1) < 1 although\n");
+ printf(" subtraction yields (1-U1) - 1 = 0 , thereby vitiating\n");
+ printf(" such precautions against division by zero as\n");
+ printf(" ... if (X == 1.0) {.....} else {.../(X-1.0)...}\n");
+ }
+ if (GMult == Yes && GDiv == Yes && GAddSub == Yes) printf(
+ " *, /, and - appear to have guard digits, as they should.\n");
+ /*=============================================*/
+ Milestone = 40;
+ /*=============================================*/
+ Pause();
+ printf("Checking rounding on multiply, divide and add/subtract.\n");
+ RMult = Other;
+ RDiv = Other;
+ RAddSub = Other;
+ RadixD2 = Radix / Two;
+ A1 = Two;
+ Done = False;
+ do {
+ AInvrse = Radix;
+ do {
+ X = AInvrse;
+ AInvrse = AInvrse / A1;
+ } while ( ! (FLOOR(AInvrse) != AInvrse));
+ Done = (X == One) || (A1 > Three);
+ if (! Done) A1 = Nine + One;
+ } while ( ! (Done));
+ if (X == One) A1 = Radix;
+ AInvrse = One / A1;
+ X = A1;
+ Y = AInvrse;
+ Done = False;
+ do {
+ Z = X * Y - Half;
+ TstCond (Failure, Z == Half,
+ "X * (1/X) differs from 1");
+ Done = X == Radix;
+ X = Radix;
+ Y = One / X;
+ } while ( ! (Done));
+ Y2 = One + U2;
+ Y1 = One - U2;
+ X = OneAndHalf - U2;
+ Y = OneAndHalf + U2;
+ Z = (X - U2) * Y2;
+ T = Y * Y1;
+ Z = Z - X;
+ T = T - X;
+ X = X * Y2;
+ Y = (Y + U2) * Y1;
+ X = X - OneAndHalf;
+ Y = Y - OneAndHalf;
+ if ((X == Zero) && (Y == Zero) && (Z == Zero) && (T <= Zero)) {
+ X = (OneAndHalf + U2) * Y2;
+ Y = OneAndHalf - U2 - U2;
+ Z = OneAndHalf + U2 + U2;
+ T = (OneAndHalf - U2) * Y1;
+ X = X - (Z + U2);
+ StickyBit = Y * Y1;
+ S = Z * Y2;
+ T = T - Y;
+ Y = (U2 - Y) + StickyBit;
+ Z = S - (Z + U2 + U2);
+ StickyBit = (Y2 + U2) * Y1;
+ Y1 = Y2 * Y1;
+ StickyBit = StickyBit - Y2;
+ Y1 = Y1 - Half;
+ if ((X == Zero) && (Y == Zero) && (Z == Zero) && (T == Zero)
+ && ( StickyBit == Zero) && (Y1 == Half)) {
+ RMult = Rounded;
+ printf("Multiplication appears to round correctly.\n");
+ }
+ else if ((X + U2 == Zero) && (Y < Zero) && (Z + U2 == Zero)
+ && (T < Zero) && (StickyBit + U2 == Zero)
+ && (Y1 < Half)) {
+ RMult = Chopped;
+ printf("Multiplication appears to chop.\n");
+ }
+ else printf("* is neither chopped nor correctly rounded.\n");
+ if ((RMult == Rounded) && (GMult == No)) notify("Multiplication");
+ }
+ else printf("* is neither chopped nor correctly rounded.\n");
+ /*=============================================*/
+ Milestone = 45;
+ /*=============================================*/
+ Y2 = One + U2;
+ Y1 = One - U2;
+ Z = OneAndHalf + U2 + U2;
+ X = Z / Y2;
+ T = OneAndHalf - U2 - U2;
+ Y = (T - U2) / Y1;
+ Z = (Z + U2) / Y2;
+ X = X - OneAndHalf;
+ Y = Y - T;
+ T = T / Y1;
+ Z = Z - (OneAndHalf + U2);
+ T = (U2 - OneAndHalf) + T;
+ if (! ((X > Zero) || (Y > Zero) || (Z > Zero) || (T > Zero))) {
+ X = OneAndHalf / Y2;
+ Y = OneAndHalf - U2;
+ Z = OneAndHalf + U2;
+ X = X - Y;
+ T = OneAndHalf / Y1;
+ Y = Y / Y1;
+ T = T - (Z + U2);
+ Y = Y - Z;
+ Z = Z / Y2;
+ Y1 = (Y2 + U2) / Y2;
+ Z = Z - OneAndHalf;
+ Y2 = Y1 - Y2;
+ Y1 = (F9 - U1) / F9;
+ if ((X == Zero) && (Y == Zero) && (Z == Zero) && (T == Zero)
+ && (Y2 == Zero) && (Y2 == Zero)
+ && (Y1 - Half == F9 - Half )) {
+ RDiv = Rounded;
+ printf("Division appears to round correctly.\n");
+ if (GDiv == No) notify("Division");
+ }
+ else if ((X < Zero) && (Y < Zero) && (Z < Zero) && (T < Zero)
+ && (Y2 < Zero) && (Y1 - Half < F9 - Half)) {
+ RDiv = Chopped;
+ printf("Division appears to chop.\n");
+ }
+ }
+ if (RDiv == Other) printf("/ is neither chopped nor correctly rounded.\n");
+ BInvrse = One / Radix;
+ TstCond (Failure, (BInvrse * Radix - Half == Half),
+ "Radix * ( 1 / Radix ) differs from 1");
+ /*=============================================*/
+ /*SPLIT
+ }
+#include "paranoia.h"
+part4(){
+*/
+ Milestone = 50;
+ /*=============================================*/
+ TstCond (Failure, ((F9 + U1) - Half == Half)
+ && ((BMinusU2 + U2 ) - One == Radix - One),
+ "Incomplete carry-propagation in Addition");
+ X = One - U1 * U1;
+ Y = One + U2 * (One - U2);
+ Z = F9 - Half;
+ X = (X - Half) - Z;
+ Y = Y - One;
+ if ((X == Zero) && (Y == Zero)) {
+ RAddSub = Chopped;
+ printf("Add/Subtract appears to be chopped.\n");
+ }
+ if (GAddSub == Yes) {
+ X = (Half + U2) * U2;
+ Y = (Half - U2) * U2;
+ X = One + X;
+ Y = One + Y;
+ X = (One + U2) - X;
+ Y = One - Y;
+ if ((X == Zero) && (Y == Zero)) {
+ X = (Half + U2) * U1;
+ Y = (Half - U2) * U1;
+ X = One - X;
+ Y = One - Y;
+ X = F9 - X;
+ Y = One - Y;
+ if ((X == Zero) && (Y == Zero)) {
+ RAddSub = Rounded;
+ printf("Addition/Subtraction appears to round correctly.\n");
+ if (GAddSub == No) notify("Add/Subtract");
+ }
+ else printf("Addition/Subtraction neither rounds nor chops.\n");
+ }
+ else printf("Addition/Subtraction neither rounds nor chops.\n");
+ }
+ else printf("Addition/Subtraction neither rounds nor chops.\n");
+ S = One;
+ X = One + Half * (One + Half);
+ Y = (One + U2) * Half;
+ Z = X - Y;
+ T = Y - X;
+ StickyBit = Z + T;
+ if (StickyBit != Zero) {
+ S = Zero;
+ BadCond(Flaw, "(X - Y) + (Y - X) is non zero!\n");
+ }
+ StickyBit = Zero;
+ if ((GMult == Yes) && (GDiv == Yes) && (GAddSub == Yes)
+ && (RMult == Rounded) && (RDiv == Rounded)
+ && (RAddSub == Rounded) && (FLOOR(RadixD2) == RadixD2)) {
+ printf("Checking for sticky bit.\n");
+ X = (Half + U1) * U2;
+ Y = Half * U2;
+ Z = One + Y;
+ T = One + X;
+ if ((Z - One <= Zero) && (T - One >= U2)) {
+ Z = T + Y;
+ Y = Z - X;
+ if ((Z - T >= U2) && (Y - T == Zero)) {
+ X = (Half + U1) * U1;
+ Y = Half * U1;
+ Z = One - Y;
+ T = One - X;
+ if ((Z - One == Zero) && (T - F9 == Zero)) {
+ Z = (Half - U1) * U1;
+ T = F9 - Z;
+ Q = F9 - Y;
+ if ((T - F9 == Zero) && (F9 - U1 - Q == Zero)) {
+ Z = (One + U2) * OneAndHalf;
+ T = (OneAndHalf + U2) - Z + U2;
+ X = One + Half / Radix;
+ Y = One + Radix * U2;
+ Z = X * Y;
+ if (T == Zero && X + Radix * U2 - Z == Zero) {
+ if (Radix != Two) {
+ X = Two + U2;
+ Y = X / Two;
+ if ((Y - One == Zero)) StickyBit = S;
+ }
+ else StickyBit = S;
+ }
+ }
+ }
+ }
+ }
+ }
+ if (StickyBit == One) printf("Sticky bit apparently used correctly.\n");
+ else printf("Sticky bit used incorrectly or not at all.\n");
+ TstCond (Flaw, !(GMult == No || GDiv == No || GAddSub == No ||
+ RMult == Other || RDiv == Other || RAddSub == Other),
+ "lack(s) of guard digits or failure(s) to correctly round or chop\n(noted above) count as one flaw in the final tally below");
+ /*=============================================*/
+ Milestone = 60;
+ /*=============================================*/
+ printf("\n");
+ printf("Does Multiplication commute? ");
+ printf("Testing on %d random pairs.\n", NoTrials);
+ Random9 = SQRT(3.0);
+ Random1 = Third;
+ I = 1;
+ do {
+ X = Random();
+ Y = Random();
+ Z9 = Y * X;
+ Z = X * Y;
+ Z9 = Z - Z9;
+ I = I + 1;
+ } while ( ! ((I > NoTrials) || (Z9 != Zero)));
+ if (I == NoTrials) {
+ Random1 = One + Half / Three;
+ Random2 = (U2 + U1) + One;
+ Z = Random1 * Random2;
+ Y = Random2 * Random1;
+ Z9 = (One + Half / Three) * ((U2 + U1) + One) - (One + Half /
+ Three) * ((U2 + U1) + One);
+ }
+ if (! ((I == NoTrials) || (Z9 == Zero)))
+ BadCond(Defect, "X * Y == Y * X trial fails.\n");
+ else printf(" No failures found in %d integer pairs.\n", NoTrials);
+ /*=============================================*/
+ Milestone = 70;
+ /*=============================================*/
+ printf("\nRunning test of square root(x).\n");
+ TstCond (Failure, (Zero == SQRT(Zero))
+ && (- Zero == SQRT(- Zero))
+ && (One == SQRT(One)), "Square root of 0.0, -0.0 or 1.0 wrong");
+ MinSqEr = Zero;
+ MaxSqEr = Zero;
+ J = Zero;
+ X = Radix;
+ OneUlp = U2;
+ SqXMinX (Serious);
+ X = BInvrse;
+ OneUlp = BInvrse * U1;
+ SqXMinX (Serious);
+ X = U1;
+ OneUlp = U1 * U1;
+ SqXMinX (Serious);
+ if (J != Zero) Pause();
+ printf("Testing if sqrt(X * X) == X for %d Integers X.\n", NoTrials);
+ J = Zero;
+ X = Two;
+ Y = Radix;
+ if ((Radix != One)) do {
+ X = Y;
+ Y = Radix * Y;
+ } while ( ! ((Y - X >= NoTrials)));
+ OneUlp = X * U2;
+ I = 1;
+ while (I <= NoTrials) {
+ X = X + One;
+ SqXMinX (Defect);
+ if (J > Zero) break;
+ I = I + 1;
+ }
+ printf("Test for sqrt monotonicity.\n");
+ I = - 1;
+ X = BMinusU2;
+ Y = Radix;
+ Z = Radix + Radix * U2;
+ NotMonot = False;
+ Monot = False;
+ while ( ! (NotMonot || Monot)) {
+ I = I + 1;
+ X = SQRT(X);
+ Q = SQRT(Y);
+ Z = SQRT(Z);
+ if ((X > Q) || (Q > Z)) NotMonot = True;
+ else {
+ Q = FLOOR(Q + Half);
+ if ((I > 0) || (Radix == Q * Q)) Monot = True;
+ else if (I > 0) {
+ if (I > 1) Monot = True;
+ else {
+ Y = Y * BInvrse;
+ X = Y - U1;
+ Z = Y + U1;
+ }
+ }
+ else {
+ Y = Q;
+ X = Y - U2;
+ Z = Y + U2;
+ }
+ }
+ }
+ if (Monot) printf("sqrt has passed a test for Monotonicity.\n");
+ else {
+ BadCond(Defect, "");
+ printf("sqrt(X) is non-monotonic for X near %.7e .\n", Y);
+ }
+ /*=============================================*/
+ /*SPLIT
+ }
+#include "paranoia.h"
+part5(){
+*/
+ Milestone = 80;
+ /*=============================================*/
+ MinSqEr = MinSqEr + Half;
+ MaxSqEr = MaxSqEr - Half;
+ Y = (SQRT(One + U2) - One) / U2;
+ SqEr = (Y - One) + U2 / Eight;
+ if (SqEr > MaxSqEr) MaxSqEr = SqEr;
+ SqEr = Y + U2 / Eight;
+ if (SqEr < MinSqEr) MinSqEr = SqEr;
+ Y = ((SQRT(F9) - U2) - (One - U2)) / U1;
+ SqEr = Y + U1 / Eight;
+ if (SqEr > MaxSqEr) MaxSqEr = SqEr;
+ SqEr = (Y + One) + U1 / Eight;
+ if (SqEr < MinSqEr) MinSqEr = SqEr;
+ OneUlp = U2;
+ X = OneUlp;
+ for( Indx = 1; Indx <= 3; ++Indx) {
+ Y = SQRT((X + U1 + X) + F9);
+ Y = ((Y - U2) - ((One - U2) + X)) / OneUlp;
+ Z = ((U1 - X) + F9) * Half * X * X / OneUlp;
+ SqEr = (Y + Half) + Z;
+ if (SqEr < MinSqEr) MinSqEr = SqEr;
+ SqEr = (Y - Half) + Z;
+ if (SqEr > MaxSqEr) MaxSqEr = SqEr;
+ if (((Indx == 1) || (Indx == 3)))
+ X = OneUlp * Sign (X) * FLOOR(Eight / (Nine * SQRT(OneUlp)));
+ else {
+ OneUlp = U1;
+ X = - OneUlp;
+ }
+ }
+ /*=============================================*/
+ Milestone = 85;
+ /*=============================================*/
+ SqRWrng = False;
+ Anomaly = False;
+ RSqrt = Other; /* ~dgh */
+ if (Radix != One) {
+ printf("Testing whether sqrt is rounded or chopped.\n");
+ D = FLOOR(Half + POW(Radix, One + Precision - FLOOR(Precision)));
+ /* ... == Radix^(1 + fract) if (Precision == Integer + fract. */
+ X = D / Radix;
+ Y = D / A1;
+ if ((X != FLOOR(X)) || (Y != FLOOR(Y))) {
+ Anomaly = True;
+ }
+ else {
+ X = Zero;
+ Z2 = X;
+ Y = One;
+ Y2 = Y;
+ Z1 = Radix - One;
+ FourD = Four * D;
+ do {
+ if (Y2 > Z2) {
+ Q = Radix;
+ Y1 = Y;
+ do {
+ X1 = FABS(Q + FLOOR(Half - Q / Y1) * Y1);
+ Q = Y1;
+ Y1 = X1;
+ } while ( ! (X1 <= Zero));
+ if (Q <= One) {
+ Z2 = Y2;
+ Z = Y;
+ }
+ }
+ Y = Y + Two;
+ X = X + Eight;
+ Y2 = Y2 + X;
+ if (Y2 >= FourD) Y2 = Y2 - FourD;
+ } while ( ! (Y >= D));
+ X8 = FourD - Z2;
+ Q = (X8 + Z * Z) / FourD;
+ X8 = X8 / Eight;
+ if (Q != FLOOR(Q)) Anomaly = True;
+ else {
+ Break = False;
+ do {
+ X = Z1 * Z;
+ X = X - FLOOR(X / Radix) * Radix;
+ if (X == One)
+ Break = True;
+ else
+ Z1 = Z1 - One;
+ } while ( ! (Break || (Z1 <= Zero)));
+ if ((Z1 <= Zero) && (! Break)) Anomaly = True;
+ else {
+ if (Z1 > RadixD2) Z1 = Z1 - Radix;
+ do {
+ NewD();
+ } while ( ! (U2 * D >= F9));
+ if (D * Radix - D != W - D) Anomaly = True;
+ else {
+ Z2 = D;
+ I = 0;
+ Y = D + (One + Z) * Half;
+ X = D + Z + Q;
+ SR3750();
+ Y = D + (One - Z) * Half + D;
+ X = D - Z + D;
+ X = X + Q + X;
+ SR3750();
+ NewD();
+ if (D - Z2 != W - Z2) Anomaly = True;
+ else {
+ Y = (D - Z2) + (Z2 + (One - Z) * Half);
+ X = (D - Z2) + (Z2 - Z + Q);
+ SR3750();
+ Y = (One + Z) * Half;
+ X = Q;
+ SR3750();
+ if (I == 0) Anomaly = True;
+ }
+ }
+ }
+ }
+ }
+ if ((I == 0) || Anomaly) {
+ BadCond(Failure, "Anomalous arithmetic with Integer < ");
+ printf("Radix^Precision = %.7e\n", W);
+ printf(" fails test whether sqrt rounds or chops.\n");
+ SqRWrng = True;
+ }
+ }
+ if (! Anomaly) {
+ if (! ((MinSqEr < Zero) || (MaxSqEr > Zero))) {
+ RSqrt = Rounded;
+ printf("Square root appears to be correctly rounded.\n");
+ }
+ else {
+ if ((MaxSqEr + U2 > U2 - Half) || (MinSqEr > Half)
+ || (MinSqEr + Radix < Half)) SqRWrng = True;
+ else {
+ RSqrt = Chopped;
+ printf("Square root appears to be chopped.\n");
+ }
+ }
+ }
+ if (SqRWrng) {
+ printf("Square root is neither chopped nor correctly rounded.\n");
+ printf("Observed errors run from %.7e ", MinSqEr - Half);
+ printf("to %.7e ulps.\n", Half + MaxSqEr);
+ TstCond (Serious, MaxSqEr - MinSqEr < Radix * Radix,
+ "sqrt gets too many last digits wrong");
+ }
+ /*=============================================*/
+ Milestone = 90;
+ /*=============================================*/
+ Pause();
+ printf("Testing powers Z^i for small Integers Z and i.\n");
+ N = 0;
+ /* ... test powers of zero. */
+ I = 0;
+ Z = -Zero;
+ M = 3.0;
+ Break = False;
+ do {
+ X = One;
+ SR3980();
+ if (I <= 10) {
+ I = 1023;
+ SR3980();
+ }
+ if (Z == MinusOne) Break = True;
+ else {
+ Z = MinusOne;
+ PrintIfNPositive();
+ N = 0;
+ /* .. if(-1)^N is invalid, replace MinusOne by One. */
+ I = - 4;
+ }
+ } while ( ! Break);
+ PrintIfNPositive();
+ N1 = N;
+ N = 0;
+ Z = A1;
+ M = FLOOR(Two * LOG(W) / LOG(A1));
+ Break = False;
+ do {
+ X = Z;
+ I = 1;
+ SR3980();
+ if (Z == AInvrse) Break = True;
+ else Z = AInvrse;
+ } while ( ! (Break));
+ /*=============================================*/
+ Milestone = 100;
+ /*=============================================*/
+ /* Powers of Radix have been tested, */
+ /* next try a few primes */
+ M = NoTrials;
+ Z = Three;
+ do {
+ X = Z;
+ I = 1;
+ SR3980();
+ do {
+ Z = Z + Two;
+ } while ( Three * FLOOR(Z / Three) == Z );
+ } while ( Z < Eight * Three );
+ if (N > 0) {
+ printf("Errors like this may invalidate financial calculations\n");
+ printf("\tinvolving interest rates.\n");
+ }
+ PrintIfNPositive();
+ N += N1;
+ if (N == 0) printf("... no discrepancis found.\n");
+ if (N > 0) Pause();
+ else printf("\n");
+ /*=============================================*/
+ /*SPLIT
+ }
+#include "paranoia.h"
+part6(){
+*/
+ Milestone = 110;
+ /*=============================================*/
+ printf("Seeking Underflow thresholds UfThold and E0.\n");
+ D = U1;
+ if (Precision != FLOOR(Precision)) {
+ D = BInvrse;
+ X = Precision;
+ do {
+ D = D * BInvrse;
+ X = X - One;
+ } while ( X > Zero);
+ }
+ Y = One;
+ Z = D;
+ /* ... D is power of 1/Radix < 1. */
+ do {
+ C = Y;
+ Y = Z;
+ Z = Y * Y;
+ } while ((Y > Z) && (Z + Z > Z));
+ Y = C;
+ Z = Y * D;
+ do {
+ C = Y;
+ Y = Z;
+ Z = Y * D;
+ } while ((Y > Z) && (Z + Z > Z));
+ if (Radix < Two) HInvrse = Two;
+ else HInvrse = Radix;
+ H = One / HInvrse;
+ /* ... 1/HInvrse == H == Min(1/Radix, 1/2) */
+ CInvrse = One / C;
+ E0 = C;
+ Z = E0 * H;
+ /* ...1/Radix^(BIG Integer) << 1 << CInvrse == 1/C */
+ do {
+ Y = E0;
+ E0 = Z;
+ Z = E0 * H;
+ } while ((E0 > Z) && (Z + Z > Z));
+ UfThold = E0;
+ E1 = Zero;
+ Q = Zero;
+ E9 = U2;
+ S = One + E9;
+ D = C * S;
+ if (D <= C) {
+ E9 = Radix * U2;
+ S = One + E9;
+ D = C * S;
+ if (D <= C) {
+ BadCond(Failure, "multiplication gets too many last digits wrong.\n");
+ Underflow = E0;
+ Y1 = Zero;
+ PseudoZero = Z;
+ Pause();
+ }
+ }
+ else {
+ Underflow = D;
+ PseudoZero = Underflow * H;
+ UfThold = Zero;
+ do {
+ Y1 = Underflow;
+ Underflow = PseudoZero;
+ if (E1 + E1 <= E1) {
+ Y2 = Underflow * HInvrse;
+ E1 = FABS(Y1 - Y2);
+ Q = Y1;
+ if ((UfThold == Zero) && (Y1 != Y2)) UfThold = Y1;
+ }
+ PseudoZero = PseudoZero * H;
+ } while ((Underflow > PseudoZero)
+ && (PseudoZero + PseudoZero > PseudoZero));
+ }
+ /* Comment line 4530 .. 4560 */
+ if (PseudoZero != Zero) {
+ printf("\n");
+ Z = PseudoZero;
+ /* ... Test PseudoZero for "phoney- zero" violates */
+ /* ... PseudoZero < Underflow or PseudoZero < PseudoZero + PseudoZero
+ ... */
+ if (PseudoZero <= Zero) {
+ BadCond(Failure, "Positive expressions can underflow to an\n");
+ printf("allegedly negative value\n");
+ printf("PseudoZero that prints out as: %g .\n", PseudoZero);
+ X = - PseudoZero;
+ if (X <= Zero) {
+ printf("But -PseudoZero, which should be\n");
+ printf("positive, isn't; it prints out as %g .\n", X);
+ }
+ }
+ else {
+ BadCond(Flaw, "Underflow can stick at an allegedly positive\n");
+ printf("value PseudoZero that prints out as %g .\n", PseudoZero);
+ }
+ TstPtUf();
+ }
+ /*=============================================*/
+ Milestone = 120;
+ /*=============================================*/
+ if (CInvrse * Y > CInvrse * Y1) {
+ S = H * S;
+ E0 = Underflow;
+ }
+ if (! ((E1 == Zero) || (E1 == E0))) {
+ BadCond(Defect, "");
+ if (E1 < E0) {
+ printf("Products underflow at a higher");
+ printf(" threshold than differences.\n");
+ if (PseudoZero == Zero)
+ E0 = E1;
+ }
+ else {
+ printf("Difference underflows at a higher");
+ printf(" threshold than products.\n");
+ }
+ }
+ printf("Smallest strictly positive number found is E0 = %g .\n", E0);
+ Z = E0;
+ TstPtUf();
+ Underflow = E0;
+ if (N == 1) Underflow = Y;
+ I = 4;
+ if (E1 == Zero) I = 3;
+ if (UfThold == Zero) I = I - 2;
+ UfNGrad = True;
+ switch (I) {
+ case 1:
+ UfThold = Underflow;
+ if ((CInvrse * Q) != ((CInvrse * Y) * S)) {
+ UfThold = Y;
+ BadCond(Failure, "Either accuracy deteriorates as numbers\n");
+ printf("approach a threshold = %.17e\n", UfThold);;
+ printf(" coming down from %.17e\n", C);
+ printf(" or else multiplication gets too many last digits wrong.\n");
+ }
+ Pause();
+ break;
+
+ case 2:
+ BadCond(Failure, "Underflow confuses Comparison, which alleges that\n");
+ printf("Q == Y while denying that |Q - Y| == 0; these values\n");
+ printf("print out as Q = %.17e, Y = %.17e .\n", Q, Y2);
+ printf ("|Q - Y| = %.17e .\n" , FABS(Q - Y2));
+ UfThold = Q;
+ break;
+
+ case 3:
+ X = X;
+ break;
+
+ case 4:
+ if ((Q == UfThold) && (E1 == E0)
+ && (FABS( UfThold - E1 / E9) <= E1)) {
+ UfNGrad = False;
+ printf("Underflow is gradual; it incurs Absolute Error =\n");
+ printf("(roundoff in UfThold) < E0.\n");
+ Y = E0 * CInvrse;
+ Y = Y * (OneAndHalf + U2);
+ X = CInvrse * (One + U2);
+ Y = Y / X;
+ IEEE = (Y == E0);
+ }
+ }
+ if (UfNGrad) {
+ printf("\n");
+ sigsave = sigfpe;
+ if (setjmp(ovfl_buf)) {
+ printf("Underflow / UfThold failed!\n");
+ R = H + H;
+ }
+ else R = SQRT(Underflow / UfThold);
+ sigsave = 0;
+ if (R <= H) {
+ Z = R * UfThold;
+ X = Z * (One + R * H * (One + H));
+ }
+ else {
+ Z = UfThold;
+ X = Z * (One + H * H * (One + H));
+ }
+ if (! ((X == Z) || (X - Z != Zero))) {
+ BadCond(Flaw, "");
+ printf("X = %.17e\n\tis not equal to Z = %.17e .\n", X, Z);
+ Z9 = X - Z;
+ printf("yet X - Z yields %.17e .\n", Z9);
+ printf(" Should this NOT signal Underflow, ");
+ printf("this is a SERIOUS DEFECT\nthat causes ");
+ printf("confusion when innocent statements like\n");;
+ printf(" if (X == Z) ... else");
+ printf(" ... (f(X) - f(Z)) / (X - Z) ...\n");
+ printf("encounter Division by Zero although actually\n");
+ sigsave = sigfpe;
+ if (setjmp(ovfl_buf)) printf("X / Z fails!\n");
+ else printf("X / Z = 1 + %g .\n", (X / Z - Half) - Half);
+ sigsave = 0;
+ }
+ }
+ printf("The Underflow threshold is %.17e, %s\n", UfThold,
+ " below which");
+ printf("calculation may suffer larger Relative error than ");
+ printf("merely roundoff.\n");
+ Y2 = U1 * U1;
+ Y = Y2 * Y2;
+ Y2 = Y * U1;
+ if (Y2 <= UfThold) {
+ if (Y > E0) {
+ BadCond(Defect, "");
+ I = 5;
+ }
+ else {
+ BadCond(Serious, "");
+ I = 4;
+ }
+ printf("Range is too narrow; U1^%d Underflows.\n", I);
+ }
+ /*=============================================*/
+ /*SPLIT
+ }
+#include "paranoia.h"
+part7(){
+*/
+ Milestone = 130;
+ /*=============================================*/
+ Y = - FLOOR(Half - TwoForty * LOG(UfThold) / LOG(HInvrse)) / TwoForty;
+ Y2 = Y + Y;
+ printf("Since underflow occurs below the threshold\n");
+ printf("UfThold = (%.17e) ^ (%.17e)\nonly underflow ", HInvrse, Y);
+ printf("should afflict the expression\n\t(%.17e) ^ (%.17e);\n", HInvrse, Y);
+ V9 = POW(HInvrse, Y2);
+ printf("actually calculating yields: %.17e .\n", V9);
+ if (! ((V9 >= Zero) && (V9 <= (Radix + Radix + E9) * UfThold))) {
+ BadCond(Serious, "this is not between 0 and underflow\n");
+ printf(" threshold = %.17e .\n", UfThold);
+ }
+ else if (! (V9 > UfThold * (One + E9)))
+ printf("This computed value is O.K.\n");
+ else {
+ BadCond(Defect, "this is not between 0 and underflow\n");
+ printf(" threshold = %.17e .\n", UfThold);
+ }
+ /*=============================================*/
+ Milestone = 140;
+ /*=============================================*/
+ printf("\n");
+ /* ...calculate Exp2 == exp(2) == 7.389056099... */
+ X = Zero;
+ I = 2;
+ Y = Two * Three;
+ Q = Zero;
+ N = 0;
+ do {
+ Z = X;
+ I = I + 1;
+ Y = Y / (I + I);
+ R = Y + Q;
+ X = Z + R;
+ Q = (Z - X) + R;
+ } while(X > Z);
+ Z = (OneAndHalf + One / Eight) + X / (OneAndHalf * ThirtyTwo);
+ X = Z * Z;
+ Exp2 = X * X;
+ X = F9;
+ Y = X - U1;
+ printf("Testing X^((X + 1) / (X - 1)) vs. exp(2) = %.17e as X -> 1.\n",
+ Exp2);
+ for(I = 1;;) {
+ Z = X - BInvrse;
+ Z = (X + One) / (Z - (One - BInvrse));
+ Q = POW(X, Z) - Exp2;
+ if (FABS(Q) > TwoForty * U2) {
+ N = 1;
+ V9 = (X - BInvrse) - (One - BInvrse);
+ BadCond(Defect, "Calculated");
+ printf(" %.17e for\n", POW(X,Z));
+ printf("\t(1 + (%.17e) ^ (%.17e);\n", V9, Z);
+ printf("\tdiffers from correct value by %.17e .\n", Q);
+ printf("\tThis much error may spoil financial\n");
+ printf("\tcalculations involving tiny interest rates.\n");
+ break;
+ }
+ else {
+ Z = (Y - X) * Two + Y;
+ X = Y;
+ Y = Z;
+ Z = One + (X - F9)*(X - F9);
+ if (Z > One && I < NoTrials) I++;
+ else {
+ if (X > One) {
+ if (N == 0)
+ printf("Accuracy seems adequate.\n");
+ break;
+ }
+ else {
+ X = One + U2;
+ Y = U2 + U2;
+ Y += X;
+ I = 1;
+ }
+ }
+ }
+ }
+ /*=============================================*/
+ Milestone = 150;
+ /*=============================================*/
+ printf("Testing powers Z^Q at four nearly extreme values.\n");
+ N = 0;
+ Z = A1;
+ Q = FLOOR(Half - LOG(C) / LOG(A1));
+ Break = False;
+ do {
+ X = CInvrse;
+ Y = POW(Z, Q);
+ IsYeqX();
+ Q = - Q;
+ X = C;
+ Y = POW(Z, Q);
+ IsYeqX();
+ if (Z < One) Break = True;
+ else Z = AInvrse;
+ } while ( ! (Break));
+ PrintIfNPositive();
+ if (N == 0) printf(" ... no discrepancies found.\n");
+ printf("\n");
+
+ /*=============================================*/
+ Milestone = 160;
+ /*=============================================*/
+ Pause();
+ printf("Searching for Overflow threshold:\n");
+ printf("This may generate an error.\n");
+ Y = - CInvrse;
+ V9 = HInvrse * Y;
+ sigsave = sigfpe;
+ if (setjmp(ovfl_buf)) { I = 0; V9 = Y; goto overflow; }
+ do {
+ V = Y;
+ Y = V9;
+ V9 = HInvrse * Y;
+ } while(V9 < Y);
+ I = 1;
+overflow:
+ sigsave = 0;
+ Z = V9;
+ printf("Can `Z = -Y' overflow?\n");
+ printf("Trying it on Y = %.17e .\n", Y);
+ V9 = - Y;
+ V0 = V9;
+ if (V - Y == V + V0) printf("Seems O.K.\n");
+ else {
+ printf("finds a ");
+ BadCond(Flaw, "-(-Y) differs from Y.\n");
+ }
+ if (Z != Y) {
+ BadCond(Serious, "");
+ printf("overflow past %.17e\n\tshrinks to %.17e .\n", Y, Z);
+ }
+ if (I) {
+ Y = V * (HInvrse * U2 - HInvrse);
+ Z = Y + ((One - HInvrse) * U2) * V;
+ if (Z < V0) Y = Z;
+ if (Y < V0) V = Y;
+ if (V0 - V < V0) V = V0;
+ }
+ else {
+ V = Y * (HInvrse * U2 - HInvrse);
+ V = V + ((One - HInvrse) * U2) * Y;
+ }
+ printf("Overflow threshold is V = %.17e .\n", V);
+ if (I) printf("Overflow saturates at V0 = %.17e .\n", V0);
+ else printf("There is no saturation value because the system traps on overflow.\n");
+ V9 = V * One;
+ printf("No Overflow should be signaled for V * 1 = %.17e\n", V9);
+ V9 = V / One;
+ printf(" nor for V / 1 = %.17e .\n", V9);
+ printf("Any overflow signal separating this * from the one\n");
+ printf("above is a DEFECT.\n");
+ /*=============================================*/
+ Milestone = 170;
+ /*=============================================*/
+ if (!(-V < V && -V0 < V0 && -UfThold < V && UfThold < V)) {
+ BadCond(Failure, "Comparisons involving ");
+ printf("+-%g, +-%g\nand +-%g are confused by Overflow.",
+ V, V0, UfThold);
+ }
+ /*=============================================*/
+ Milestone = 175;
+ /*=============================================*/
+ printf("\n");
+ for(Indx = 1; Indx <= 3; ++Indx) {
+ switch (Indx) {
+ case 1: Z = UfThold; break;
+ case 2: Z = E0; break;
+ case 3: Z = PseudoZero; break;
+ }
+ if (Z != Zero) {
+ V9 = SQRT(Z);
+ Y = V9 * V9;
+ if (Y / (One - Radix * E9) < Z
+ || Y > (One + Radix * E9) * Z) { /* dgh: + E9 --> * E9 */
+ if (V9 > U1) BadCond(Serious, "");
+ else BadCond(Defect, "");
+ printf("Comparison alleges that what prints as Z = %.17e\n", Z);
+ printf(" is too far from sqrt(Z) ^ 2 = %.17e .\n", Y);
+ }
+ }
+ }
+ /*=============================================*/
+ Milestone = 180;
+ /*=============================================*/
+ for(Indx = 1; Indx <= 2; ++Indx) {
+ if (Indx == 1) Z = V;
+ else Z = V0;
+ V9 = SQRT(Z);
+ X = (One - Radix * E9) * V9;
+ V9 = V9 * X;
+ if (((V9 < (One - Two * Radix * E9) * Z) || (V9 > Z))) {
+ Y = V9;
+ if (X < W) BadCond(Serious, "");
+ else BadCond(Defect, "");
+ printf("Comparison alleges that Z = %17e\n", Z);
+ printf(" is too far from sqrt(Z) ^ 2 (%.17e) .\n", Y);
+ }
+ }
+ /*=============================================*/
+ /*SPLIT
+ }
+#include "paranoia.h"
+part8(){
+*/
+ Milestone = 190;
+ /*=============================================*/
+ Pause();
+ X = UfThold * V;
+ Y = Radix * Radix;
+ if (X*Y < One || X > Y) {
+ if (X * Y < U1 || X > Y/U1) BadCond(Defect, "Badly");
+ else BadCond(Flaw, "");
+
+ printf(" unbalanced range; UfThold * V = %.17e\n\t%s\n",
+ X, "is too far from 1.\n");
+ }
+ /*=============================================*/
+ Milestone = 200;
+ /*=============================================*/
+ for (Indx = 1; Indx <= 5; ++Indx) {
+ X = F9;
+ switch (Indx) {
+ case 2: X = One + U2; break;
+ case 3: X = V; break;
+ case 4: X = UfThold; break;
+ case 5: X = Radix;
+ }
+ Y = X;
+ sigsave = sigfpe;
+ if (setjmp(ovfl_buf))
+ printf(" X / X traps when X = %g\n", X);
+ else {
+ V9 = (Y / X - Half) - Half;
+ if (V9 == Zero) continue;
+ if (V9 == - U1 && Indx < 5) BadCond(Flaw, "");
+ else BadCond(Serious, "");
+ printf(" X / X differs from 1 when X = %.17e\n", X);
+ printf(" instead, X / X - 1/2 - 1/2 = %.17e .\n", V9);
+ }
+ sigsave = 0;
+ }
+ /*=============================================*/
+ Milestone = 210;
+ /*=============================================*/
+ MyZero = Zero;
+ printf("\n");
+ printf("What message and/or values does Division by Zero produce?\n") ;
+#ifndef NOPAUSE
+ printf("This can interupt your program. You can ");
+ printf("skip this part if you wish.\n");
+ printf("Do you wish to compute 1 / 0? ");
+ fflush(stdout);
+ read (KEYBOARD, ch, 8);
+ if ((ch[0] == 'Y') || (ch[0] == 'y')) {
+#endif
+ sigsave = sigfpe;
+ printf(" Trying to compute 1 / 0 produces ...");
+ if (!setjmp(ovfl_buf)) printf(" %.7e .\n", One / MyZero);
+ sigsave = 0;
+#ifndef NOPAUSE
+ }
+ else printf("O.K.\n");
+ printf("\nDo you wish to compute 0 / 0? ");
+ fflush(stdout);
+ read (KEYBOARD, ch, 80);
+ if ((ch[0] == 'Y') || (ch[0] == 'y')) {
+#endif
+ sigsave = sigfpe;
+ printf("\n Trying to compute 0 / 0 produces ...");
+ if (!setjmp(ovfl_buf)) printf(" %.7e .\n", Zero / MyZero);
+ sigsave = 0;
+#ifndef NOPAUSE
+ }
+ else printf("O.K.\n");
+#endif
+ /*=============================================*/
+ Milestone = 220;
+ /*=============================================*/
+ Pause();
+ printf("\n");
+ {
+ static char *msg[] = {
+ "FAILUREs encountered =",
+ "SERIOUS DEFECTs discovered =",
+ "DEFECTs discovered =",
+ "FLAWs discovered =" };
+ int i;
+ for(i = 0; i < 4; i++) if (ErrCnt[i])
+ printf("The number of %-29s %d.\n",
+ msg[i], ErrCnt[i]);
+ }
+ printf("\n");
+ if ((ErrCnt[Failure] + ErrCnt[Serious] + ErrCnt[Defect]
+ + ErrCnt[Flaw]) > 0) {
+ if ((ErrCnt[Failure] + ErrCnt[Serious] + ErrCnt[
+ Defect] == 0) && (ErrCnt[Flaw] > 0)) {
+ printf("The arithmetic diagnosed seems ");
+ printf("Satisfactory though flawed.\n");
+ }
+ if ((ErrCnt[Failure] + ErrCnt[Serious] == 0)
+ && ( ErrCnt[Defect] > 0)) {
+ printf("The arithmetic diagnosed may be Acceptable\n");
+ printf("despite inconvenient Defects.\n");
+ }
+ if ((ErrCnt[Failure] + ErrCnt[Serious]) > 0) {
+ printf("The arithmetic diagnosed has ");
+ printf("unacceptable Serious Defects.\n");
+ }
+ if (ErrCnt[Failure] > 0) {
+ printf("Potentially fatal FAILURE may have spoiled this");
+ printf(" program's subsequent diagnoses.\n");
+ }
+ }
+ else {
+ printf("No failures, defects nor flaws have been discovered.\n");
+ if (! ((RMult == Rounded) && (RDiv == Rounded)
+ && (RAddSub == Rounded) && (RSqrt == Rounded)))
+ printf("The arithmetic diagnosed seems Satisfactory.\n");
+ else {
+ if (StickyBit >= One &&
+ (Radix - Two) * (Radix - Nine - One) == Zero) {
+ printf("Rounding appears to conform to ");
+ printf("the proposed IEEE standard P");
+ if ((Radix == Two) &&
+ ((Precision - Four * Three * Two) *
+ ( Precision - TwentySeven -
+ TwentySeven + One) == Zero))
+ printf("754");
+ else printf("854");
+ if (IEEE) printf(".\n");
+ else {
+ printf(",\nexcept for possibly Double Rounding");
+ printf(" during Gradual Underflow.\n");
+ }
+ }
+ printf("The arithmetic diagnosed appears to be Excellent!\n");
+ }
+ }
+ if (fpecount)
+ printf("\nA total of %d floating point exceptions were registered.\n",
+ fpecount);
+ printf("END OF TEST.\n");
+ return 0;
+ }
+
+/*SPLIT subs.c
+#include "paranoia.h"
+*/
+
+/* Sign */
+
+FLOAT Sign (X)
+FLOAT X;
+{ return X >= 0. ? 1.0 : -1.0; }
+
+/* Pause */
+
+Pause()
+{
+#ifndef NOPAUSE
+ char ch[8];
+
+ printf("\nTo continue, press RETURN");
+ fflush(stdout);
+ read(KEYBOARD, ch, 8);
+#endif
+ printf("\nDiagnosis resumes after milestone Number %d", Milestone);
+ printf(" Page: %d\n\n", PageNo);
+ ++Milestone;
+ ++PageNo;
+ }
+
+ /* TstCond */
+
+TstCond (K, Valid, T)
+int K, Valid;
+char *T;
+{ if (! Valid) { BadCond(K,T); printf(".\n"); } }
+
+BadCond(K, T)
+int K;
+char *T;
+{
+ static char *msg[] = { "FAILURE", "SERIOUS DEFECT", "DEFECT", "FLAW" };
+
+ ErrCnt [K] = ErrCnt [K] + 1;
+ printf("%s: %s", msg[K], T);
+ }
+
+/* Random */
+/* Random computes
+ X = (Random1 + Random9)^5
+ Random1 = X - FLOOR(X) + 0.000005 * X;
+ and returns the new value of Random1
+*/
+
+FLOAT Random()
+{
+ FLOAT X, Y;
+
+ X = Random1 + Random9;
+ Y = X * X;
+ Y = Y * Y;
+ X = X * Y;
+ Y = X - FLOOR(X);
+ Random1 = Y + X * 0.000005;
+ return(Random1);
+ }
+
+/* SqXMinX */
+
+SqXMinX (ErrKind)
+int ErrKind;
+{
+ FLOAT XA, XB;
+
+ XB = X * BInvrse;
+ XA = X - XB;
+ SqEr = ((SQRT(X * X) - XB) - XA) / OneUlp;
+ if (SqEr != Zero) {
+ if (SqEr < MinSqEr) MinSqEr = SqEr;
+ if (SqEr > MaxSqEr) MaxSqEr = SqEr;
+ J = J + 1.0;
+ BadCond(ErrKind, "\n");
+ printf("sqrt( %.17e) - %.17e = %.17e\n", X * X, X, OneUlp * SqEr);
+ printf("\tinstead of correct value 0 .\n");
+ }
+ }
+
+/* NewD */
+
+NewD()
+{
+ X = Z1 * Q;
+ X = FLOOR(Half - X / Radix) * Radix + X;
+ Q = (Q - X * Z) / Radix + X * X * (D / Radix);
+ Z = Z - Two * X * D;
+ if (Z <= Zero) {
+ Z = - Z;
+ Z1 = - Z1;
+ }
+ D = Radix * D;
+ }
+
+/* SR3750 */
+
+SR3750()
+{
+ if (! ((X - Radix < Z2 - Radix) || (X - Z2 > W - Z2))) {
+ I = I + 1;
+ X2 = SQRT(X * D);
+ Y2 = (X2 - Z2) - (Y - Z2);
+ X2 = X8 / (Y - Half);
+ X2 = X2 - Half * X2 * X2;
+ SqEr = (Y2 + Half) + (Half - X2);
+ if (SqEr < MinSqEr) MinSqEr = SqEr;
+ SqEr = Y2 - X2;
+ if (SqEr > MaxSqEr) MaxSqEr = SqEr;
+ }
+ }
+
+/* IsYeqX */
+
+IsYeqX()
+{
+ if (Y != X) {
+ if (N <= 0) {
+ if (Z == Zero && Q <= Zero)
+ printf("WARNING: computing\n");
+ else BadCond(Defect, "computing\n");
+ printf("\t(%.17e) ^ (%.17e)\n", Z, Q);
+ printf("\tyielded %.17e;\n", Y);
+ printf("\twhich compared unequal to correct %.17e ;\n",
+ X);
+ printf("\t\tthey differ by %.17e .\n", Y - X);
+ }
+ N = N + 1; /* ... count discrepancies. */
+ }
+ }
+
+/* SR3980 */
+
+SR3980()
+{
+ do {
+ Q = (FLOAT) I;
+ Y = POW(Z, Q);
+ IsYeqX();
+ if (++I > M) break;
+ X = Z * X;
+ } while ( X < W );
+ }
+
+/* PrintIfNPositive */
+
+PrintIfNPositive()
+{
+ if (N > 0) printf("Similar discrepancies have occurred %d times.\n", N);
+ }
+
+/* TstPtUf */
+
+TstPtUf()
+{
+ N = 0;
+ if (Z != Zero) {
+ printf("Since comparison denies Z = 0, evaluating ");
+ printf("(Z + Z) / Z should be safe.\n");
+ sigsave = sigfpe;
+ if (setjmp(ovfl_buf)) goto very_serious;
+ Q9 = (Z + Z) / Z;
+ printf("What the machine gets for (Z + Z) / Z is %.17e .\n",
+ Q9);
+ if (FABS(Q9 - Two) < Radix * U2) {
+ printf("This is O.K., provided Over/Underflow");
+ printf(" has NOT just been signaled.\n");
+ }
+ else {
+ if ((Q9 < One) || (Q9 > Two)) {
+very_serious:
+ N = 1;
+ ErrCnt [Serious] = ErrCnt [Serious] + 1;
+ printf("This is a VERY SERIOUS DEFECT!\n");
+ }
+ else {
+ N = 1;
+ ErrCnt [Defect] = ErrCnt [Defect] + 1;
+ printf("This is a DEFECT!\n");
+ }
+ }
+ sigsave = 0;
+ V9 = Z * One;
+ Random1 = V9;
+ V9 = One * Z;
+ Random2 = V9;
+ V9 = Z / One;
+ if ((Z == Random1) && (Z == Random2) && (Z == V9)) {
+ if (N > 0) Pause();
+ }
+ else {
+ N = 1;
+ BadCond(Defect, "What prints as Z = ");
+ printf("%.17e\n\tcompares different from ", Z);
+ if (Z != Random1) printf("Z * 1 = %.17e ", Random1);
+ if (! ((Z == Random2)
+ || (Random2 == Random1)))
+ printf("1 * Z == %g\n", Random2);
+ if (! (Z == V9)) printf("Z / 1 = %.17e\n", V9);
+ if (Random2 != Random1) {
+ ErrCnt [Defect] = ErrCnt [Defect] + 1;
+ BadCond(Defect, "Multiplication does not commute!\n");
+ printf("\tComparison alleges that 1 * Z = %.17e\n",
+ Random2);
+ printf("\tdiffers from Z * 1 = %.17e\n", Random1);
+ }
+ Pause();
+ }
+ }
+ }
+
+notify(s)
+char *s;
+{
+ printf("%s test appears to be inconsistent...\n", s);
+ printf(" PLEASE NOTIFY KARPINKSI!\n");
+ }
+
+/*SPLIT msgs.c */
+
+/* Instructions */
+
+msglist(s)
+char **s;
+{ while(*s) printf("%s\n", *s++); }
+
+Instructions()
+{
+ static char *instr[] = {
+ "Lest this program stop prematurely, i.e. before displaying\n",
+ " `END OF TEST',\n",
+ "try to persuade the computer NOT to terminate execution when an",
+ "error like Over/Underflow or Division by Zero occurs, but rather",
+ "to persevere with a surrogate value after, perhaps, displaying some",
+ "warning. If persuasion avails naught, don't despair but run this",
+ "program anyway to see how many milestones it passes, and then",
+ "amend it to make further progress.\n",
+ "Answer questions with Y, y, N or n (unless otherwise indicated).\n",
+ 0};
+
+ msglist(instr);
+ }
+
+/* Heading */
+
+Heading()
+{
+ static char *head[] = {
+ "Users are invited to help debug and augment this program so it will",
+ "cope with unanticipated and newly uncovered arithmetic pathologies.\n",
+ "Please send suggestions and interesting results to",
+ "\tRichard Karpinski",
+ "\tComputer Center U-76",
+ "\tUniversity of California",
+ "\tSan Francisco, CA 94143-0704, USA\n",
+ "In doing so, please include the following information:",
+#ifdef Single
+ "\tPrecision:\tsingle;",
+#else
+ "\tPrecision:\tdouble;",
+#endif
+ "\tVersion:\t10 February 1989;",
+ "\tComputer:\n",
+ "\tCompiler:\n",
+ "\tOptimization level:\n",
+ "\tOther relevant compiler options:",
+ 0};
+
+ msglist(head);
+ }
+
+/* Characteristics */
+
+Characteristics()
+{
+ static char *chars[] = {
+ "Running this program should reveal these characteristics:",
+ " Radix = 1, 2, 4, 8, 10, 16, 100, 256 ...",
+ " Precision = number of significant digits carried.",
+ " U2 = Radix/Radix^Precision = One Ulp",
+ "\t(OneUlpnit in the Last Place) of 1.000xxx .",
+ " U1 = 1/Radix^Precision = One Ulp of numbers a little less than 1.0 .",
+ " Adequacy of guard digits for Mult., Div. and Subt.",
+ " Whether arithmetic is chopped, correctly rounded, or something else",
+ "\tfor Mult., Div., Add/Subt. and Sqrt.",
+ " Whether a Sticky Bit used correctly for rounding.",
+ " UnderflowThreshold = an underflow threshold.",
+ " E0 and PseudoZero tell whether underflow is abrupt, gradual, or fuzzy.",
+ " V = an overflow threshold, roughly.",
+ " V0 tells, roughly, whether Infinity is represented.",
+ " Comparisions are checked for consistency with subtraction",
+ "\tand for contamination with pseudo-zeros.",
+ " Sqrt is tested. Y^X is not tested.",
+ " Extra-precise subexpressions are revealed but NOT YET tested.",
+ " Decimal-Binary conversion is NOT YET tested for accuracy.",
+ 0};
+
+ msglist(chars);
+ }
+
+History()
+
+{ /* History */
+ /* Converted from Brian Wichmann's Pascal version to C by Thos Sumner,
+ with further massaging by David M. Gay. */
+
+ static char *hist[] = {
+ "The program attempts to discriminate among",
+ " FLAWs, like lack of a sticky bit,",
+ " Serious DEFECTs, like lack of a guard digit, and",
+ " FAILUREs, like 2+2 == 5 .",
+ "Failures may confound subsequent diagnoses.\n",
+ "The diagnostic capabilities of this program go beyond an earlier",
+ "program called `MACHAR', which can be found at the end of the",
+ "book `Software Manual for the Elementary Functions' (1980) by",
+ "W. J. Cody and W. Waite. Although both programs try to discover",
+ "the Radix, Precision and range (over/underflow thresholds)",
+ "of the arithmetic, this program tries to cope with a wider variety",
+ "of pathologies, and to say how well the arithmetic is implemented.",
+ "\nThe program is based upon a conventional radix representation for",
+ "floating-point numbers, but also allows logarithmic encoding",
+ "as used by certain early WANG machines.\n",
+ "BASIC version of this program (C) 1983 by Prof. W. M. Kahan;",
+ "see source comments for more history.",
+ 0};
+
+ msglist(hist);
+ }
+
+double
+pow(x, y) /* return x ^ y (exponentiation) */
+double x, y;
+{
+ extern double exp(), frexp(), ldexp(), log(), modf();
+ double xy, ye;
+ long i;
+ int ex, ey = 0, flip = 0;
+
+ if (!y) return 1.0;
+
+ if ((y < -1100. || y > 1100.) && x != -1.) return exp(y * log(x));
+
+ if (y < 0.) { y = -y; flip = 1; }
+ y = modf(y, &ye);
+ if (y) xy = exp(y * log(x));
+ else xy = 1.0;
+ /* next several lines assume >= 32 bit integers */
+ x = frexp(x, &ex);
+ if (i = ye) for(;;) {
+ if (i & 1) { xy *= x; ey += ex; }
+ if (!(i >>= 1)) break;
+ x *= x;
+ ex *= 2;
+ if (x < .5) { x *= 2.; ex -= 1; }
+ }
+ if (flip) { xy = 1. / xy; ey = -ey; }
+ return ldexp(xy, ey);
+}
diff --git a/lcc/tst/sort.0 b/lcc/tst/sort.0
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/tst/sort.0
diff --git a/lcc/tst/sort.c b/lcc/tst/sort.c
new file mode 100755
index 0000000..029de8e
--- /dev/null
+++ b/lcc/tst/sort.c
@@ -0,0 +1,65 @@
+int in[] = {10, 32, -1, 567, 3, 18, 1, -51, 789, 0};
+
+main() {
+ int i;
+
+ sort(in, (sizeof in)/(sizeof in[0]));
+ for (i = 0; i < (sizeof in)/(sizeof in[0]); i++) {
+ putd(in[i]);
+ putchar('\n');
+ }
+ return 0;
+}
+
+/* putd - output decimal number */
+putd(n) {
+ if (n < 0) {
+ putchar('-');
+ n = -n;
+ }
+ if (n/10)
+ putd(n/10);
+ putchar(n%10 + '0');
+}
+
+int *xx;
+
+/* sort - sort a[0..n-1] into increasing order */
+sort(a, n) int a[]; {
+ quick(xx = a, 0, --n);
+}
+
+/* quick - quicksort a[lb..ub] */
+quick(a, lb, ub) int a[]; {
+ int k, partition();
+
+ if (lb >= ub)
+ return;
+ k = partition(a, lb, ub);
+ quick(a, lb, k - 1);
+ quick(a, k + 1, ub);
+}
+
+/* partition - partition a[i..j] */
+int partition(a, i, j) int a[]; {
+ int v, k;
+
+ j++;
+ k = i;
+ v = a[k];
+ while (i < j) {
+ i++; while (a[i] < v) i++;
+ j--; while (a[j] > v) j--;
+ if (i < j) exchange(&a[i], &a[j]);
+ }
+ exchange(&a[k], &a[j]);
+ return j;
+}
+
+/* exchange - exchange *x and *y */
+exchange(x, y) int *x, *y; {
+ int t;
+
+ printf("exchange(%d,%d)\n", x - xx, y - xx);
+ t = *x; *x = *y; *y = t;
+}
diff --git a/lcc/tst/spill.0 b/lcc/tst/spill.0
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/tst/spill.0
diff --git a/lcc/tst/spill.c b/lcc/tst/spill.c
new file mode 100755
index 0000000..4a3d9aa
--- /dev/null
+++ b/lcc/tst/spill.c
@@ -0,0 +1,17 @@
+main(){}
+
+f(i){i=f()+f();}
+
+f2(i){i=f()+(i?f():1);}
+
+f3(int i,int *p){register r1=0,r2=0,r3=0,r4=0,r5=0,r6=0,r7=0,r8=0,r9=0,r10=0;*p++=i?f():0;}
+
+double a[10],b[10];int i;f4(){register r6=0,r7=0,r8=0,r9=0,r10=0,r11=0;i=a[i]+b[i] && i && a[i]-b[i];}
+/* f4 causes parent to spill child on vax when odd double regs are enabled */
+
+int j, k, m, n;
+double *A, *B, x;
+f5(){
+ x=A[k*m]*A[j*m]+B[k*n]*B[j*n];
+ x=A[k*m]*B[j*n]-B[k*n]*A[j*m];
+}
diff --git a/lcc/tst/stdarg.0 b/lcc/tst/stdarg.0
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/tst/stdarg.0
diff --git a/lcc/tst/stdarg.c b/lcc/tst/stdarg.c
new file mode 100755
index 0000000..ff6c918
--- /dev/null
+++ b/lcc/tst/stdarg.c
@@ -0,0 +1,51 @@
+#include <stdarg.h>
+
+struct node { int a[4]; } x = {1,2,3,4};
+
+print(char *fmt, ...);
+
+main() {
+ print("test 1\n");
+ print("test %s\n", "2");
+ print("test %d%c", 3, '\n');
+ print("%s%s %w%c", "te", "st", 4, '\n');
+ print("%s%s %f%c", "te", "st", 5.0, '\n');
+ print("%b %b %b %b %b %b\n", x, x, x, x, x, x);
+ return 0;
+}
+
+print(char *fmt, ...) {
+ va_list ap;
+
+ va_start(ap, fmt);
+ for (; *fmt; fmt++)
+ if (*fmt == '%')
+ switch (*++fmt) {
+ case 'b': {
+ struct node x = va_arg(ap, struct node);
+ printf("{%d %d %d %d}", x.a[0], x.a[1], x.a[2], x.a[3]);
+ break;
+ }
+ case 'c':
+ printf("%c", va_arg(ap, char));
+ break;
+ case 'd':
+ printf("%d", va_arg(ap, int));
+ break;
+ case 'w':
+ printf("%x", va_arg(ap, short));
+ break;
+ case 's':
+ printf("%s", va_arg(ap, char *));
+ break;
+ case 'f':
+ printf("%f", va_arg(ap, double));
+ break;
+ default:
+ printf("%c", *fmt);
+ break;
+ }
+ else
+ printf("%c", *fmt);
+ va_end(ap);
+}
diff --git a/lcc/tst/struct.0 b/lcc/tst/struct.0
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/tst/struct.0
diff --git a/lcc/tst/struct.c b/lcc/tst/struct.c
new file mode 100755
index 0000000..97da897
--- /dev/null
+++ b/lcc/tst/struct.c
@@ -0,0 +1,69 @@
+typedef struct point { int x,y; } point;
+typedef struct rect { point pt1, pt2; } rect;
+
+point addpoint(point p1, point p2) { /* add two points */
+ p1.x += p2.x;
+ p1.y += p2.y;
+ return p1;
+}
+
+#define min(a, b) ((a) < (b) ? (a) : (b))
+#define max(a, b) ((a) > (b) ? (a) : (b))
+
+rect canonrect(rect r) { /* canonicalize rectangle coordinates */
+ rect temp;
+
+ temp.pt1.x = min(r.pt1.x, r.pt2.x);
+ temp.pt1.y = min(r.pt1.y, r.pt2.y);
+ temp.pt2.x = max(r.pt1.x, r.pt2.x);
+ temp.pt2.y = max(r.pt1.y, r.pt2.y);
+ return temp;
+}
+
+point makepoint(int x, int y) { /* make a point from x and y components */
+ point p;
+
+ p.x = x;
+ p.y = y;
+ return p;
+}
+
+rect makerect(point p1, point p2) { /* make a rectangle from two points */
+ rect r;
+
+ r.pt1 = p1;
+ r.pt2 = p2;
+ return canonrect(r);
+}
+
+int ptinrect(point p, rect r) { /* is p in r? */
+ return p.x >= r.pt1.x && p.x < r.pt2.x
+ && p.y >= r.pt1.y && p.y < r.pt2.y;
+}
+
+struct odd {char a[3]; } y = {'a', 'b', 0};
+
+odd(struct odd y) {
+ struct odd x = y;
+ printf("%s\n", x.a);
+}
+
+main() {
+ int i;
+ point x, origin = { 0, 0 }, maxpt = { 320, 320 };
+ point pts[] = { -1, -1, 1, 1, 20, 300, 500, 400 };
+ rect screen = makerect(addpoint(maxpt, makepoint(-10, -10)),
+ addpoint(origin, makepoint(10, 10)));
+
+ for (i = 0; i < sizeof pts/sizeof pts[0]; i++) {
+ printf("(%d,%d) is ", pts[i].x,
+ (x = makepoint(pts[i].x, pts[i].y)).y);
+ if (ptinrect(x, screen) == 0)
+ printf("not ");
+ printf("within [%d,%d; %d,%d]\n", screen.pt1.x, screen.pt1.y,
+ screen.pt2.x, screen.pt2.y);
+ }
+ odd(y);
+ exit(0);
+}
+
diff --git a/lcc/tst/switch.0 b/lcc/tst/switch.0
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/tst/switch.0
diff --git a/lcc/tst/switch.c b/lcc/tst/switch.c
new file mode 100755
index 0000000..0cd48de
--- /dev/null
+++ b/lcc/tst/switch.c
@@ -0,0 +1,137 @@
+main()
+{
+ int i; char *s;
+
+ for (s = "bfnrtvx"; *s; s++)
+ printf("%c = 0x%x\n", *s, backslash(*s));
+ f();
+ g();
+ h();
+ for (i = 0x1000000; i&0x7000000; i += 0x1000000)
+ big(i);
+ limit();
+ return 0;
+}
+
+backslash(c)
+{
+ switch (c) {
+ case 'b':
+ return '\b';
+ case 'f':
+ return '\f';
+ case 'n':
+ return '\n';
+ case 'r':
+ return '\r';
+ case 't':
+ return '\t';
+ case 'v':
+ return '\v';
+ }
+ return c;
+}
+
+f() {
+ int i, x = 0, y;
+
+ printf("f:\n");
+ for (i = 0; i <= 20; i++) {
+ y = i;
+ switch (i) {
+ case 1: x = i; break;
+ case 2: x = i; break;
+ case 7: x = i; break;
+ case 8: x = i; break;
+ case 9: x = i; break;
+ case 16: x = i; break;
+ case 17: x = i; break;
+ case 18: x = i; break;
+ case 19: x = i; break;
+ case 20: x = i; break;
+ }
+ printf("x = %d\n", x);
+ }
+}
+
+g() {
+ int i;
+
+ printf("g:\n");
+ for (i = 1; i <= 10; i++)
+ switch (i) {
+ case 1: case 2: printf("1 %d\n", i); break;
+ case 3: case 4: case 5: printf("2 %d\n", i); break;
+ case 6: case 7: case 8: printf("3 %d\n", i);
+ default:
+ printf("d %d\n", i); break;
+ case 1001: case 1002: case 1003: case 1004:
+ printf("5 %d\n", i); break;
+ case 3001: case 3002: case 3003: case 3004:
+ printf("6 %d\n", i); break;
+ }
+}
+
+h()
+{
+ int i, n=0;
+
+ printf("h:\n");
+ for (i = 1; i <= 500; i++)
+ switch (i) {
+ default: n++; continue;
+ case 128: printf("i = %d\n", i); break;
+ case 16: printf("i = %d\n", i); break;
+ case 8: printf("i = %d\n", i); break;
+ case 120: printf("i = %d\n", i); break;
+ case 280: printf("i = %d\n", i); break;
+ case 264: printf("i = %d\n", i); break;
+ case 248: printf("i = %d\n", i); break;
+ case 272: printf("i = %d\n", i); break;
+ case 304: printf("i = %d\n", i); break;
+ case 296: printf("i = %d\n", i); break;
+ case 288: printf("i = %d\n", i); break;
+ case 312: printf("i = %d\n", i); break;
+ }
+ printf("%d defaults\n", n);
+}
+
+big(x) unsigned x; {
+ switch(x&0x6000000){
+ case -1:
+ case -2:
+ case 0x0000000:
+ printf("x = 0x%x\n", x); break;
+ case 0x2000000:
+ printf("x = 0x%x\n", x); break;
+ case 0x4000000:
+ printf("x = 0x%x\n", x); break;
+ default:
+ printf("x = 0x%x (default)\n", x); break;
+ }
+}
+
+#include <limits.h>
+
+limit() {
+ int i;
+
+ for (i = INT_MIN; i <= INT_MIN+5; i++)
+ switch (i) {
+ case INT_MIN: printf("0\n"); break;
+ case INT_MIN+1: printf("1\n"); break;
+ case INT_MIN+2: printf("2\n"); break;
+ case INT_MIN+3: printf("3\n"); break;
+ case INT_MIN+4: printf("4\n"); break;
+ default: printf("5\n"); break;
+ }
+ for (i = INT_MAX; i >= INT_MAX-5; i--)
+ switch (i) {
+ case INT_MAX: printf("0\n"); break;
+ case INT_MAX-1: printf("1\n"); break;
+ case INT_MAX-2: printf("2\n"); break;
+ case INT_MAX-3: printf("3\n"); break;
+ case INT_MAX-4: printf("4\n"); break;
+ default: printf("5\n"); break;
+ }
+}
diff --git a/lcc/tst/wf1.0 b/lcc/tst/wf1.0
new file mode 100755
index 0000000..28f6ebd
--- /dev/null
+++ b/lcc/tst/wf1.0
@@ -0,0 +1,115 @@
+/* wf1 - print word frequencies; uses structures */
+
+struct node {
+ int count; /* frequency count */
+ struct node *left; /* left subtree */
+ struct node *right; /* right subtree */
+ char *word; /* word itself */
+} words[2000];
+int next; /* index of next free entry in words */
+
+struct node *lookup();
+
+main()
+{
+ struct node *root;
+ char word[20];
+
+ root = 0;
+ next = 0;
+ while (getword(word))
+ lookup(word, &root)->count++;
+ tprint(root);
+ return 0;
+}
+
+/* err - print error message s and die */
+err(s)
+char *s;
+{
+ printf("? %s\n", s);
+ exit(1);
+}
+
+/* getword - get next input word into buf, return 0 on EOF */
+int getword(buf)
+char *buf;
+{
+ char *s;
+ int c;
+
+ while ((c = getchar()) != -1 && isletter(c) == 0)
+ ;
+ for (s = buf; c = isletter(c); c = getchar())
+ *s++ = c;
+ *s = 0;
+ if (s > buf)
+ return (1);
+ return (0);
+}
+
+/* isletter - return folded version of c if it is a letter, 0 otherwise */
+int isletter(c)
+int c;
+{
+ if (c >= 'A' && c <= 'Z')
+ c += 'a' - 'A';
+ if (c >= 'a' && c <= 'z')
+ return (c);
+ return (0);
+}
+
+/* lookup - lookup word in tree; install if necessary */
+struct node *lookup(word, p)
+char *word;
+struct node **p;
+{
+ int cond;
+ char *malloc();
+
+ if (*p) {
+ cond = strcmp(word, (*p)->word);
+ if (cond < 0)
+ return lookup(word, &(*p)->left);
+ else if (cond > 0)
+ return lookup(word, &(*p)->right);
+ else
+ return *p;
+ }
+ if (next >= 2000)
+ err("out of node storage");
+ words[next].count = 0;
+ words[next].left = words[next].right = 0;
+ words[next].word = malloc(strlen(word) + 1);
+ if (words[next].word == 0)
+ err("out of word storage");
+ strcpy(words[next].word, word);
+ return *p = &words[next++];
+}
+
+/* tprint - print tree */
+tprint(tree)
+struct node *tree;
+{
+ if (tree) {
+ tprint(tree->left);
+ printf("%d\t%s\n", tree->count, tree->word);
+ tprint(tree->right);
+ }
+}
+
+/* strcmp - compare s1 and s2, return <0, 0, or >0 */
+int strcmp(s1, s2)
+char *s1, *s2;
+{
+ while (*s1 == *s2) {
+ if (*s1++ == 0)
+ return 0;
+ ++s2;
+ }
+ if (*s1 == 0)
+ return -1;
+ else if (*s2 == 0)
+ return 1;
+ return *s1 - *s2;
+}
diff --git a/lcc/tst/wf1.c b/lcc/tst/wf1.c
new file mode 100755
index 0000000..a95b4ec
--- /dev/null
+++ b/lcc/tst/wf1.c
@@ -0,0 +1,101 @@
+/* wf1 - print word frequencies; uses structures */
+
+struct node {
+ int count; /* frequency count */
+ struct node *left; /* left subtree */
+ struct node *right; /* right subtree */
+ char *word; /* word itself */
+} words[2000];
+int next; /* index of next free entry in words */
+
+struct node *lookup();
+
+main() {
+ struct node *root;
+ char word[20];
+
+ root = 0;
+ next = 0;
+ while (getword(word))
+ lookup(word, &root)->count++;
+ tprint(root);
+ return 0;
+}
+
+/* err - print error message s and die */
+err(s) char *s; {
+ printf("? %s\n", s);
+ exit(1);
+}
+
+/* getword - get next input word into buf, return 0 on EOF */
+int getword(buf) char *buf; {
+ char *s;
+ int c;
+
+ while ((c = getchar()) != -1 && isletter(c) == 0)
+ ;
+ for (s = buf; c = isletter(c); c = getchar())
+ *s++ = c;
+ *s = 0;
+ if (s > buf)
+ return (1);
+ return (0);
+}
+
+/* isletter - return folded version of c if it is a letter, 0 otherwise */
+int isletter(c) {
+ if (c >= 'A' && c <= 'Z')
+ c += 'a' - 'A';
+ if (c >= 'a' && c <= 'z')
+ return (c);
+ return (0);
+}
+
+/* lookup - lookup word in tree; install if necessary */
+struct node *lookup(word, p) char *word; struct node **p; {
+ int cond;
+ char *malloc();
+
+ if (*p) {
+ cond = strcmp(word, (*p)->word);
+ if (cond < 0)
+ return lookup(word, &(*p)->left);
+ else if (cond > 0)
+ return lookup(word, &(*p)->right);
+ else
+ return *p;
+ }
+ if (next >= 2000)
+ err("out of node storage");
+ words[next].count = 0;
+ words[next].left = words[next].right = 0;
+ words[next].word = malloc(strlen(word) + 1);
+ if (words[next].word == 0)
+ err("out of word storage");
+ strcpy(words[next].word, word);
+ return *p = &words[next++];
+}
+
+/* tprint - print tree */
+tprint(tree) struct node *tree; {
+ if (tree) {
+ tprint(tree->left);
+ printf("%d\t%s\n", tree->count, tree->word);
+ tprint(tree->right);
+ }
+}
+
+/* strcmp - compare s1 and s2, return <0, 0, or >0 */
+int strcmp(s1, s2) char *s1, *s2; {
+ while (*s1 == *s2) {
+ if (*s1++ == 0)
+ return 0;
+ ++s2;
+ }
+ if (*s1 == 0)
+ return -1;
+ else if (*s2 == 0)
+ return 1;
+ return *s1 - *s2;
+}
diff --git a/lcc/tst/yacc.0 b/lcc/tst/yacc.0
new file mode 100755
index 0000000..8bea9c4
--- /dev/null
+++ b/lcc/tst/yacc.0
@@ -0,0 +1 @@
+a=-b+5*c
diff --git a/lcc/tst/yacc.c b/lcc/tst/yacc.c
new file mode 100755
index 0000000..cd3e9d0
--- /dev/null
+++ b/lcc/tst/yacc.c
@@ -0,0 +1,591 @@
+# define ID 257
+# define CON 258
+# define UNARYMINUS 259
+#define yyclearin yychar = -1
+#define yyerrok yyerrflag = 0
+extern int yychar;
+extern short yyerrflag;
+#ifndef YYMAXDEPTH
+#define YYMAXDEPTH 150
+#endif
+#ifndef YYSTYPE
+#define YYSTYPE int
+#endif
+YYSTYPE yylval, yyval;
+# define YYERRCODE 256
+
+
+
+#include <stdio.h>
+
+# define U(x) x
+# define NLSTATE yyprevious=YYNEWLINE
+# define BEGIN yybgin = yysvec + 1 +
+# define INITIAL 0
+# define YYLERR yysvec
+# define YYSTATE (yyestate-yysvec-1)
+# define YYOPTIM 1
+# define YYLMAX 200
+# define output(c) (void)putc(c,yyout)
+# define input() (((yytchar=yysptr>yysbuf?U(*--yysptr):getc(yyin))==10?(yylineno++,yytchar):yytchar)==EOF?0:yytchar)
+# define unput(c) {yytchar= (c);if(yytchar=='\n')yylineno--;*yysptr++=yytchar;}
+# define yymore() (yymorfg=1)
+# define ECHO fprintf(yyout, "%s",yytext)
+# define REJECT { nstr = yyreject(); goto yyfussy;}
+int yyleng; extern char yytext[];
+int yymorfg;
+extern char *yysptr, yysbuf[];
+int yytchar;
+FILE *yyin ={stdin}, *yyout ={stdout};
+extern int yylineno;
+struct yysvf {
+ struct yywork *yystoff;
+ struct yysvf *yyother;
+ int *yystops;};
+struct yysvf *yyestate;
+extern struct yysvf yysvec[], *yybgin;
+# define YYNEWLINE 10
+yylex(){
+int nstr; extern int yyprevious;
+while((nstr = yylook()) >= 0)
+yyfussy: switch(nstr){
+case 0:
+if(yywrap()) return(0); break;
+case 1:
+ return ID;
+break;
+case 2:
+ return CON;
+break;
+case 3:
+ ;
+break;
+case 4:
+ return yytext[0];
+break;
+case -1:
+break;
+default:
+fprintf(yyout,"bad switch yylook %d",nstr);
+} return(0); }
+/* end of yylex */
+int yyvstop[] ={
+0,
+
+4,
+0,
+
+3,
+4,
+0,
+
+2,
+4,
+0,
+
+1,
+4,
+0,
+
+2,
+0,
+
+1,
+0,
+0};
+# define YYTYPE char
+struct yywork { YYTYPE verify, advance; } yycrank[] ={
+0,0, 0,0, 1,3, 0,0,
+0,0, 0,0, 0,0, 0,0,
+0,0, 0,0, 1,4, 1,3,
+0,0, 0,0, 0,0, 0,0,
+0,0, 0,0, 0,0, 0,0,
+0,0, 0,0, 0,0, 0,0,
+0,0, 0,0, 0,0, 0,0,
+0,0, 0,0, 0,0, 0,0,
+0,0, 0,0, 0,0, 0,0,
+0,0, 0,0, 0,0, 0,0,
+0,0, 0,0, 0,0, 0,0,
+0,0, 0,0, 0,0, 0,0,
+0,0, 1,5, 5,7, 5,7,
+5,7, 5,7, 5,7, 5,7,
+5,7, 5,7, 5,7, 5,7,
+0,0, 0,0, 0,0, 0,0,
+0,0, 0,0, 1,6, 6,8,
+6,8, 6,8, 6,8, 6,8,
+6,8, 6,8, 6,8, 6,8,
+6,8, 0,0, 0,0, 0,0,
+0,0, 0,0, 0,0, 0,0,
+6,8, 6,8, 6,8, 6,8,
+6,8, 6,8, 6,8, 6,8,
+6,8, 6,8, 6,8, 6,8,
+6,8, 6,8, 6,8, 6,8,
+6,8, 6,8, 6,8, 6,8,
+6,8, 6,8, 6,8, 6,8,
+6,8, 6,8, 0,0, 0,0,
+0,0, 0,0, 6,8, 0,0,
+6,8, 6,8, 6,8, 6,8,
+6,8, 6,8, 6,8, 6,8,
+6,8, 6,8, 6,8, 6,8,
+6,8, 6,8, 6,8, 6,8,
+6,8, 6,8, 6,8, 6,8,
+6,8, 6,8, 6,8, 6,8,
+6,8, 6,8, 0,0, 0,0,
+0,0};
+struct yysvf yysvec[] ={
+0, 0, 0,
+yycrank+-1, 0, 0,
+yycrank+0, yysvec+1, 0,
+yycrank+0, 0, yyvstop+1,
+yycrank+0, 0, yyvstop+3,
+yycrank+2, 0, yyvstop+6,
+yycrank+19, 0, yyvstop+9,
+yycrank+0, yysvec+5, yyvstop+12,
+yycrank+0, yysvec+6, yyvstop+14,
+0, 0, 0};
+struct yywork *yytop = yycrank+141;
+struct yysvf *yybgin = yysvec+1;
+char yymatch[] ={
+00 ,01 ,01 ,01 ,01 ,01 ,01 ,01 ,
+01 ,011 ,012 ,01 ,01 ,01 ,01 ,01 ,
+01 ,01 ,01 ,01 ,01 ,01 ,01 ,01 ,
+01 ,01 ,01 ,01 ,01 ,01 ,01 ,01 ,
+011 ,01 ,01 ,01 ,01 ,01 ,01 ,01 ,
+01 ,01 ,01 ,01 ,01 ,01 ,01 ,01 ,
+'0' ,'0' ,'0' ,'0' ,'0' ,'0' ,'0' ,'0' ,
+'0' ,'0' ,01 ,01 ,01 ,01 ,01 ,01 ,
+01 ,'A' ,'A' ,'A' ,'A' ,'A' ,'A' ,'A' ,
+'A' ,'A' ,'A' ,'A' ,'A' ,'A' ,'A' ,'A' ,
+'A' ,'A' ,'A' ,'A' ,'A' ,'A' ,'A' ,'A' ,
+'A' ,'A' ,'A' ,01 ,01 ,01 ,01 ,'A' ,
+01 ,'A' ,'A' ,'A' ,'A' ,'A' ,'A' ,'A' ,
+'A' ,'A' ,'A' ,'A' ,'A' ,'A' ,'A' ,'A' ,
+'A' ,'A' ,'A' ,'A' ,'A' ,'A' ,'A' ,'A' ,
+'A' ,'A' ,'A' ,01 ,01 ,01 ,01 ,01 ,
+0};
+char yyextra[] ={
+0,0,0,0,0,0,0,0,
+0};
+/* ncform 4.1 83/08/11 */
+
+int yylineno =1;
+# define YYU(x) x
+# define NLSTATE yyprevious=YYNEWLINE
+char yytext[YYLMAX];
+struct yysvf *yylstate [YYLMAX], **yylsp, **yyolsp;
+char yysbuf[YYLMAX];
+char *yysptr = yysbuf;
+int *yyfnd;
+extern struct yysvf *yyestate;
+int yyprevious = YYNEWLINE;
+yylook(){
+ register struct yysvf *yystate, **lsp;
+ register struct yywork *yyt;
+ struct yysvf *yyz;
+ int yych;
+ struct yywork *yyr;
+# ifdef LEXDEBUG
+ int debug;
+# endif
+ char *yylastch;
+ /* start off machines */
+# ifdef LEXDEBUG
+ debug = 0;
+# endif
+ if (!yymorfg)
+ yylastch = yytext;
+ else {
+ yymorfg=0;
+ yylastch = yytext+yyleng;
+ }
+ for(;;){
+ lsp = yylstate;
+ yyestate = yystate = yybgin;
+ if (yyprevious==YYNEWLINE) yystate++;
+ for (;;){
+# ifdef LEXDEBUG
+ if(debug)fprintf(yyout,"state %d\n",yystate-yysvec-1);
+# endif
+ yyt = yystate->yystoff;
+ if(yyt == yycrank){ /* may not be any transitions */
+ yyz = yystate->yyother;
+ if(yyz == 0)break;
+ if(yyz->yystoff == yycrank)break;
+ }
+ *yylastch++ = yych = input();
+ tryagain:
+# ifdef LEXDEBUG
+ if(debug){
+ fprintf(yyout,"char ");
+ allprint(yych);
+ putchar('\n');
+ }
+# endif
+ yyr = yyt;
+ if ( yyt > yycrank){
+ yyt = yyr + yych;
+ if (yyt <= yytop && yyt->verify+yysvec == yystate){
+ if(yyt->advance+yysvec == YYLERR) /* error transitions */
+ {unput(*--yylastch);break;}
+ *lsp++ = yystate = yyt->advance+yysvec;
+ goto contin;
+ }
+ }
+# ifdef YYOPTIM
+ else if(yyt < yycrank) { /* r < yycrank */
+ yyt = yyr = yycrank+(yycrank-yyt);
+# ifdef LEXDEBUG
+ if(debug)fprintf(yyout,"compressed state\n");
+# endif
+ yyt = yyt + yych;
+ if(yyt <= yytop && yyt->verify+yysvec == yystate){
+ if(yyt->advance+yysvec == YYLERR) /* error transitions */
+ {unput(*--yylastch);break;}
+ *lsp++ = yystate = yyt->advance+yysvec;
+ goto contin;
+ }
+ yyt = yyr + YYU(yymatch[yych]);
+# ifdef LEXDEBUG
+ if(debug){
+ fprintf(yyout,"try fall back character ");
+ allprint(YYU(yymatch[yych]));
+ putchar('\n');
+ }
+# endif
+ if(yyt <= yytop && yyt->verify+yysvec == yystate){
+ if(yyt->advance+yysvec == YYLERR) /* error transition */
+ {unput(*--yylastch);break;}
+ *lsp++ = yystate = yyt->advance+yysvec;
+ goto contin;
+ }
+ }
+ if ((yystate = yystate->yyother) && (yyt= yystate->yystoff) != yycrank){
+# ifdef LEXDEBUG
+ if(debug)fprintf(yyout,"fall back to state %d\n",yystate-yysvec-1);
+# endif
+ goto tryagain;
+ }
+# endif
+ else
+ {unput(*--yylastch);break;}
+ contin:
+# ifdef LEXDEBUG
+ if(debug){
+ fprintf(yyout,"state %d char ",yystate-yysvec-1);
+ allprint(yych);
+ putchar('\n');
+ }
+# endif
+ ;
+ }
+# ifdef LEXDEBUG
+ if(debug){
+ fprintf(yyout,"stopped at %d with ",*(lsp-1)-yysvec-1);
+ allprint(yych);
+ putchar('\n');
+ }
+# endif
+ while (lsp-- > yylstate){
+ *yylastch-- = 0;
+ if (*lsp != 0 && (yyfnd= (*lsp)->yystops) && *yyfnd > 0){
+ yyolsp = lsp;
+ if(yyextra[*yyfnd]){ /* must backup */
+ while(yyback((*lsp)->yystops,-*yyfnd) != 1 && lsp > yylstate){
+ lsp--;
+ unput(*yylastch--);
+ }
+ }
+ yyprevious = YYU(*yylastch);
+ yylsp = lsp;
+ yyleng = yylastch-yytext+1;
+ yytext[yyleng] = 0;
+# ifdef LEXDEBUG
+ if(debug){
+ fprintf(yyout,"\nmatch ");
+ sprint(yytext);
+ fprintf(yyout," action %d\n",*yyfnd);
+ }
+# endif
+ return(*yyfnd++);
+ }
+ unput(*yylastch);
+ }
+ if (yytext[0] == 0 /* && feof(yyin) */)
+ {
+ yysptr=yysbuf;
+ return(0);
+ }
+ yyprevious = yytext[0] = input();
+ if (yyprevious>0)
+ output(yyprevious);
+ yylastch=yytext;
+# ifdef LEXDEBUG
+ if(debug)putchar('\n');
+# endif
+ }
+ }
+yyback(p, m)
+ int *p;
+{
+if (p==0) return(0);
+while (*p)
+ {
+ if (*p++ == m)
+ return(1);
+ }
+return(0);
+}
+ /* the following are only used in the lex library */
+yyinput(){
+ return(input());
+ }
+yyoutput(c)
+ int c; {
+ output(c);
+ }
+yyunput(c)
+ int c; {
+ unput(c);
+ }
+
+main() {
+ yyparse();
+ return 0;
+}
+
+/* yyerror - issue error message */
+yyerror(s) char *s; {
+ printf("%s\n", s);
+}
+short yyexca[] ={
+-1, 1,
+ 0, -1,
+ -2, 0,
+ };
+# define YYNPROD 15
+# define YYLAST 249
+short yyact[]={
+
+ 12, 2, 9, 8, 17, 11, 25, 17, 15, 18,
+ 16, 10, 18, 17, 15, 7, 16, 13, 18, 5,
+ 3, 1, 0, 19, 20, 0, 0, 21, 22, 23,
+ 24, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 6, 14, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 4, 6 };
+short yypact[]={
+
+-1000, -9,-1000, 5, -7, -59,-1000,-1000,-1000, -40,
+ -29, -40, -40,-1000,-1000, -40, -40, -40, -40, -38,
+ -35, -38, -38,-1000,-1000,-1000 };
+short yypgo[]={
+
+ 0, 21, 20, 17, 11 };
+short yyr1[]={
+
+ 0, 1, 1, 1, 1, 2, 4, 4, 4, 4,
+ 4, 4, 4, 4, 3 };
+short yyr2[]={
+
+ 0, 0, 2, 3, 3, 3, 3, 3, 3, 3,
+ 2, 3, 1, 1, 1 };
+short yychk[]={
+
+-1000, -1, 10, -2, 256, -3, 257, 10, 10, 61,
+ -4, 45, 40, -3, 258, 43, 45, 42, 47, -4,
+ -4, -4, -4, -4, -4, 41 };
+short yydef[]={
+
+ 1, -2, 2, 0, 0, 0, 14, 3, 4, 0,
+ 5, 0, 0, 12, 13, 0, 0, 0, 0, 10,
+ 0, 6, 7, 8, 9, 11 };
+#ifndef lint
+#endif
+
+# define YYFLAG -1000
+# define YYERROR goto yyerrlab
+# define YYACCEPT return(0)
+# define YYABORT return(1)
+
+/* parser for yacc output */
+
+#ifdef YYDEBUG
+int yydebug = 0; /* 1 for debugging */
+#endif
+YYSTYPE yyv[YYMAXDEPTH]; /* where the values are stored */
+int yychar = -1; /* current input token number */
+int yynerrs = 0; /* number of errors */
+short yyerrflag = 0; /* error recovery flag */
+
+yyparse() {
+
+ short yys[YYMAXDEPTH];
+ short yyj, yym;
+ register YYSTYPE *yypvt;
+ register short yystate, *yyps, yyn;
+ register YYSTYPE *yypv;
+ register short *yyxi;
+
+ yystate = 0;
+ yychar = -1;
+ yynerrs = 0;
+ yyerrflag = 0;
+ yyps= &yys[-1];
+ yypv= &yyv[-1];
+
+ yystack: /* put a state and value onto the stack */
+
+#ifdef YYDEBUG
+ if( yydebug ) printf( "state %d, char 0%o\n", yystate, yychar );
+#endif
+ if( ++yyps> &yys[YYMAXDEPTH] ) { yyerror( "yacc stack overflow" ); return(1); }
+ *yyps = yystate;
+ ++yypv;
+ *yypv = yyval;
+
+ yynewstate:
+
+ yyn = yypact[yystate];
+
+ if( yyn<= YYFLAG ) goto yydefault; /* simple state */
+
+ if( yychar<0 ) if( (yychar=yylex())<0 ) yychar=0;
+ if( (yyn += yychar)<0 || yyn >= YYLAST ) goto yydefault;
+
+ if( yychk[ yyn=yyact[ yyn ] ] == yychar ){ /* valid shift */
+ yychar = -1;
+ yyval = yylval;
+ yystate = yyn;
+ if( yyerrflag > 0 ) --yyerrflag;
+ goto yystack;
+ }
+
+ yydefault:
+ /* default state action */
+
+ if( (yyn=yydef[yystate]) == -2 ) {
+ if( yychar<0 ) if( (yychar=yylex())<0 ) yychar = 0;
+ /* look through exception table */
+
+ for( yyxi=yyexca; (*yyxi!= (-1)) || (yyxi[1]!=yystate) ; yyxi += 2 ) ; /* VOID */
+
+ while( *(yyxi+=2) >= 0 ){
+ if( *yyxi == yychar ) break;
+ }
+ if( (yyn = yyxi[1]) < 0 ) return(0); /* accept */
+ }
+
+ if( yyn == 0 ){ /* error */
+ /* error ... attempt to resume parsing */
+
+ switch( yyerrflag ){
+
+ case 0: /* brand new error */
+
+ yyerror( "syntax error" );
+ yyerrlab:
+ ++yynerrs;
+
+ case 1:
+ case 2: /* incompletely recovered error ... try again */
+
+ yyerrflag = 3;
+
+ /* find a state where "error" is a legal shift action */
+
+ while ( yyps >= yys ) {
+ yyn = yypact[*yyps] + YYERRCODE;
+ if( yyn>= 0 && yyn < YYLAST && yychk[yyact[yyn]] == YYERRCODE ){
+ yystate = yyact[yyn]; /* simulate a shift of "error" */
+ goto yystack;
+ }
+ yyn = yypact[*yyps];
+
+ /* the current yyps has no shift onn "error", pop stack */
+
+#ifdef YYDEBUG
+ if( yydebug ) printf( "error recovery pops state %d, uncovers %d\n", *yyps, yyps[-1] );
+#endif
+ --yyps;
+ --yypv;
+ }
+
+ /* there is no state on the stack with an error shift ... abort */
+
+ yyabort:
+ return(1);
+
+
+ case 3: /* no shift yet; clobber input char */
+
+#ifdef YYDEBUG
+ if( yydebug ) printf( "error recovery discards char %d\n", yychar );
+#endif
+
+ if( yychar == 0 ) goto yyabort; /* don't discard EOF, quit */
+ yychar = -1;
+ goto yynewstate; /* try again in the same state */
+
+ }
+
+ }
+
+ /* reduction by production yyn */
+
+#ifdef YYDEBUG
+ if( yydebug ) printf("reduce %d\n",yyn);
+#endif
+ yyps -= yyr2[yyn];
+ yypvt = yypv;
+ yypv -= yyr2[yyn];
+ yyval = yypv[1];
+ yym=yyn;
+ /* consult goto table to find next state */
+ yyn = yyr1[yyn];
+ yyj = yypgo[yyn] + *yyps + 1;
+ if( yyj>=YYLAST || yychk[ yystate = yyact[yyj] ] != -yyn ) yystate = yyact[yypgo[yyn]];
+ switch(yym){
+
+case 4:
+{ yyerrok; } break;
+case 5:
+{ printf("store\n"); } break;
+case 6:
+{ printf("add\n"); } break;
+case 7:
+{ printf("negate\nadd\n"); } break;
+case 8:
+{ printf("multiply\n"); } break;
+case 9:
+{ printf("divide\n"); } break;
+case 10:
+{ printf("negate\n"); } break;
+case 12:
+{ printf("load\n"); } break;
+case 13:
+{ printf("push %s\n", yytext); } break;
+case 14:
+{ printf("%s\n", yytext); } break;
+ }
+ goto yystack; /* stack new state and value */
+
+ }
+int yywrap() { return 1; }
diff --git a/lcc/x86/linux/tst/8q.1bk b/lcc/x86/linux/tst/8q.1bk
new file mode 100755
index 0000000..c66df8e
--- /dev/null
+++ b/lcc/x86/linux/tst/8q.1bk
@@ -0,0 +1,92 @@
+1 5 8 6 3 7 2 4
+1 6 8 3 7 4 2 5
+1 7 4 6 8 2 5 3
+1 7 5 8 2 4 6 3
+2 4 6 8 3 1 7 5
+2 5 7 1 3 8 6 4
+2 5 7 4 1 8 6 3
+2 6 1 7 4 8 3 5
+2 6 8 3 1 4 7 5
+2 7 3 6 8 5 1 4
+2 7 5 8 1 4 6 3
+2 8 6 1 3 5 7 4
+3 1 7 5 8 2 4 6
+3 5 2 8 1 7 4 6
+3 5 2 8 6 4 7 1
+3 5 7 1 4 2 8 6
+3 5 8 4 1 7 2 6
+3 6 2 5 8 1 7 4
+3 6 2 7 1 4 8 5
+3 6 2 7 5 1 8 4
+3 6 4 1 8 5 7 2
+3 6 4 2 8 5 7 1
+3 6 8 1 4 7 5 2
+3 6 8 1 5 7 2 4
+3 6 8 2 4 1 7 5
+3 7 2 8 5 1 4 6
+3 7 2 8 6 4 1 5
+3 8 4 7 1 6 2 5
+4 1 5 8 2 7 3 6
+4 1 5 8 6 3 7 2
+4 2 5 8 6 1 3 7
+4 2 7 3 6 8 1 5
+4 2 7 3 6 8 5 1
+4 2 7 5 1 8 6 3
+4 2 8 5 7 1 3 6
+4 2 8 6 1 3 5 7
+4 6 1 5 2 8 3 7
+4 6 8 2 7 1 3 5
+4 6 8 3 1 7 5 2
+4 7 1 8 5 2 6 3
+4 7 3 8 2 5 1 6
+4 7 5 2 6 1 3 8
+4 7 5 3 1 6 8 2
+4 8 1 3 6 2 7 5
+4 8 1 5 7 2 6 3
+4 8 5 3 1 7 2 6
+5 1 4 6 8 2 7 3
+5 1 8 4 2 7 3 6
+5 1 8 6 3 7 2 4
+5 2 4 6 8 3 1 7
+5 2 4 7 3 8 6 1
+5 2 6 1 7 4 8 3
+5 2 8 1 4 7 3 6
+5 3 1 6 8 2 4 7
+5 3 1 7 2 8 6 4
+5 3 8 4 7 1 6 2
+5 7 1 3 8 6 4 2
+5 7 1 4 2 8 6 3
+5 7 2 4 8 1 3 6
+5 7 2 6 3 1 4 8
+5 7 2 6 3 1 8 4
+5 7 4 1 3 8 6 2
+5 8 4 1 3 6 2 7
+5 8 4 1 7 2 6 3
+6 1 5 2 8 3 7 4
+6 2 7 1 3 5 8 4
+6 2 7 1 4 8 5 3
+6 3 1 7 5 8 2 4
+6 3 1 8 4 2 7 5
+6 3 1 8 5 2 4 7
+6 3 5 7 1 4 2 8
+6 3 5 8 1 4 2 7
+6 3 7 2 4 8 1 5
+6 3 7 2 8 5 1 4
+6 3 7 4 1 8 2 5
+6 4 1 5 8 2 7 3
+6 4 2 8 5 7 1 3
+6 4 7 1 3 5 2 8
+6 4 7 1 8 2 5 3
+6 8 2 4 1 7 5 3
+7 1 3 8 6 4 2 5
+7 2 4 1 8 5 3 6
+7 2 6 3 1 4 8 5
+7 3 1 6 8 5 2 4
+7 3 8 2 5 1 6 4
+7 4 2 5 8 1 3 6
+7 4 2 8 6 1 3 5
+7 5 3 1 6 8 2 4
+8 2 4 1 7 5 3 6
+8 2 5 3 1 7 4 6
+8 3 1 6 2 5 7 4
+8 4 1 3 6 2 7 5
diff --git a/lcc/x86/linux/tst/8q.2bk b/lcc/x86/linux/tst/8q.2bk
new file mode 100755
index 0000000..fb28350
--- /dev/null
+++ b/lcc/x86/linux/tst/8q.2bk
@@ -0,0 +1,2 @@
+tst/8q.c:30: warning: missing return value
+tst/8q.c:39: warning: missing return value
diff --git a/lcc/x86/linux/tst/8q.sbk b/lcc/x86/linux/tst/8q.sbk
new file mode 100755
index 0000000..34af0f1
--- /dev/null
+++ b/lcc/x86/linux/tst/8q.sbk
@@ -0,0 +1,180 @@
+.globl main
+.text
+.align 16
+.type main,@function
+main:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $4,%esp
+movl $0,-4(%ebp)
+.LC2:
+movl -4(%ebp),%edi
+leal (,%edi,4),%edi
+movl $1,down(%edi)
+movl $1,up(%edi)
+.LC3:
+incl -4(%ebp)
+cmpl $15,-4(%ebp)
+jl .LC2
+movl $0,-4(%ebp)
+.LC6:
+movl -4(%ebp),%edi
+movl $1,rows(,%edi,4)
+.LC7:
+incl -4(%ebp)
+cmpl $8,-4(%ebp)
+jl .LC6
+pushl $0
+call queens
+addl $4,%esp
+movl $0,%eax
+.LC1:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf10:
+.size main,.Lf10-main
+.globl queens
+.align 16
+.type queens,@function
+queens:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $4,%esp
+movl $0,-4(%ebp)
+.LC12:
+movl -4(%ebp),%edi
+cmpl $0,rows(,%edi,4)
+je .LC16
+movl 20(%ebp),%esi
+movl %edi,%ebx
+subl %esi,%ebx
+cmpl $0,up+28(,%ebx,4)
+je .LC16
+leal (%esi,%edi),%edi
+cmpl $0,down(,%edi,4)
+je .LC16
+movl -4(%ebp),%edi
+movl 20(%ebp),%esi
+leal (%esi,%edi),%ebx
+movl $0,down(,%ebx,4)
+movl %edi,%ebx
+subl %esi,%ebx
+movl $0,up+28(,%ebx,4)
+movl $0,rows(,%edi,4)
+movl 20(%ebp),%edi
+movl -4(%ebp),%esi
+movl %esi,x(,%edi,4)
+cmpl $7,20(%ebp)
+jne .LC20
+call print
+jmp .LC21
+.LC20:
+movl 20(%ebp),%edi
+leal 1(%edi),%edi
+pushl %edi
+call queens
+addl $4,%esp
+.LC21:
+movl -4(%ebp),%edi
+movl 20(%ebp),%esi
+leal (%esi,%edi),%ebx
+movl $1,down(,%ebx,4)
+movl %edi,%ebx
+subl %esi,%ebx
+movl $1,up+28(,%ebx,4)
+movl $1,rows(,%edi,4)
+.LC16:
+.LC13:
+incl -4(%ebp)
+cmpl $8,-4(%ebp)
+jl .LC12
+movl $0,%eax
+.LC11:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf23:
+.size queens,.Lf23-queens
+.globl print
+.align 16
+.type print,@function
+print:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $4,%esp
+movl $0,-4(%ebp)
+.LC25:
+movl -4(%ebp),%edi
+movl x(,%edi,4),%edi
+leal 49(%edi),%edi
+pushl %edi
+pushl $.LC29
+call printf
+addl $8,%esp
+.LC26:
+incl -4(%ebp)
+cmpl $8,-4(%ebp)
+jl .LC25
+pushl $.LC30
+call printf
+addl $4,%esp
+movl $0,%eax
+.LC24:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf31:
+.size print,.Lf31-print
+.bss
+.globl x
+.align 4
+.type x,@object
+.size x,32
+.comm x,32
+.globl rows
+.align 4
+.type rows,@object
+.size rows,32
+.comm rows,32
+.globl down
+.align 4
+.type down,@object
+.size down,60
+.comm down,60
+.globl up
+.align 4
+.type up,@object
+.size up,60
+.comm up,60
+.data
+.align 1
+.LC30:
+.byte 10
+.byte 0
+.align 1
+.LC29:
+.byte 37
+.byte 99
+.byte 32
+.byte 0
+.text
+.ident "LCC: 4.1"
diff --git a/lcc/x86/linux/tst/array.1bk b/lcc/x86/linux/tst/array.1bk
new file mode 100755
index 0000000..e188568
--- /dev/null
+++ b/lcc/x86/linux/tst/array.1bk
@@ -0,0 +1,4 @@
+ 0 1 2 3 1000 1001 1002 1003 2000 2001 2002 2003
+ 0 1 2 3 1000 1001 1002 1003 2000 2001 2002 2003
+ 0 1 2 3 1000 1001 1002 1003 2000 2001 2002 2003
+ 0 1 2 3 1000 1001 1002 1003 2000 2001 2002 2003
diff --git a/lcc/x86/linux/tst/array.2bk b/lcc/x86/linux/tst/array.2bk
new file mode 100755
index 0000000..0a9b206
--- /dev/null
+++ b/lcc/x86/linux/tst/array.2bk
@@ -0,0 +1,2 @@
+tst/array.c:33: warning: missing return value
+tst/array.c:48: warning: missing return value
diff --git a/lcc/x86/linux/tst/array.sbk b/lcc/x86/linux/tst/array.sbk
new file mode 100755
index 0000000..2505a6d
--- /dev/null
+++ b/lcc/x86/linux/tst/array.sbk
@@ -0,0 +1,235 @@
+.globl main
+.text
+.align 16
+.type main,@function
+main:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $60,%esp
+movl $0,-8(%ebp)
+.LC2:
+movl $0,-4(%ebp)
+.LC6:
+movl -4(%ebp),%edi
+movl -8(%ebp),%esi
+movl %esi,%ebx
+sall $4,%ebx
+leal x(%ebx),%ebx
+imul $1000,%esi,%esi
+leal (%edi,%esi),%esi
+movl %esi,(%ebx,%edi,4)
+.LC7:
+incl -4(%ebp)
+cmpl $4,-4(%ebp)
+jl .LC6
+movl -8(%ebp),%edi
+movl %edi,%esi
+sall $4,%esi
+leal x(%esi),%esi
+movl %esi,y(,%edi,4)
+.LC3:
+incl -8(%ebp)
+cmpl $3,-8(%ebp)
+jl .LC2
+call f
+movl $0,-8(%ebp)
+.LC10:
+movl -8(%ebp),%edi
+movl %edi,%esi
+sall $4,%esi
+leal -60(%ebp),%ebx
+leal (%ebx,%esi),%esi
+movl %esi,-12(%ebp)
+movl %esi,y(,%edi,4)
+movl $0,-4(%ebp)
+.LC14:
+movl -4(%ebp),%edi
+leal (,%edi,4),%edi
+movl -12(%ebp),%esi
+movl -8(%ebp),%ebx
+sall $4,%ebx
+leal x(%ebx),%ebx
+movl (%ebx,%edi),%ebx
+movl %ebx,(%esi,%edi)
+.LC15:
+incl -4(%ebp)
+cmpl $4,-4(%ebp)
+jl .LC14
+.LC11:
+incl -8(%ebp)
+cmpl $3,-8(%ebp)
+jl .LC10
+pushl $y
+leal -60(%ebp),%edi
+pushl %edi
+call g
+addl $8,%esp
+movl $0,%eax
+.LC1:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf18:
+.size main,.Lf18-main
+.globl f
+.align 16
+.type f,@function
+f:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $8,%esp
+movl $0,-8(%ebp)
+.LC20:
+movl $0,-4(%ebp)
+.LC24:
+movl -4(%ebp),%edi
+movl -8(%ebp),%esi
+sall $4,%esi
+leal x(%esi),%esi
+pushl (%esi,%edi,4)
+pushl $.LC28
+call printf
+addl $8,%esp
+.LC25:
+incl -4(%ebp)
+cmpl $4,-4(%ebp)
+jl .LC24
+.LC21:
+incl -8(%ebp)
+cmpl $3,-8(%ebp)
+jl .LC20
+pushl $.LC29
+call printf
+addl $4,%esp
+movl $0,-8(%ebp)
+.LC30:
+movl $0,-4(%ebp)
+.LC34:
+movl -4(%ebp),%edi
+movl -8(%ebp),%esi
+movl y(,%esi,4),%esi
+pushl (%esi,%edi,4)
+pushl $.LC28
+call printf
+addl $8,%esp
+.LC35:
+incl -4(%ebp)
+cmpl $4,-4(%ebp)
+jl .LC34
+.LC31:
+incl -8(%ebp)
+cmpl $3,-8(%ebp)
+jl .LC30
+pushl $.LC29
+call printf
+addl $4,%esp
+movl $0,%eax
+.LC19:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf38:
+.size f,.Lf38-f
+.globl g
+.align 16
+.type g,@function
+g:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $8,%esp
+movl $0,-8(%ebp)
+.LC40:
+movl $0,-4(%ebp)
+.LC44:
+movl -4(%ebp),%edi
+movl -8(%ebp),%esi
+sall $4,%esi
+movl 20(%ebp),%ebx
+leal (%ebx,%esi),%esi
+pushl (%esi,%edi,4)
+pushl $.LC28
+call printf
+addl $8,%esp
+.LC45:
+incl -4(%ebp)
+cmpl $4,-4(%ebp)
+jl .LC44
+.LC41:
+incl -8(%ebp)
+cmpl $3,-8(%ebp)
+jl .LC40
+pushl $.LC29
+call printf
+addl $4,%esp
+movl $0,-8(%ebp)
+.LC48:
+movl $0,-4(%ebp)
+.LC52:
+movl -4(%ebp),%edi
+movl -8(%ebp),%esi
+movl 24(%ebp),%ebx
+movl (%ebx,%esi,4),%esi
+pushl (%esi,%edi,4)
+pushl $.LC28
+call printf
+addl $8,%esp
+.LC53:
+incl -4(%ebp)
+cmpl $4,-4(%ebp)
+jl .LC52
+.LC49:
+incl -8(%ebp)
+cmpl $3,-8(%ebp)
+jl .LC48
+pushl $.LC29
+call printf
+addl $4,%esp
+movl $0,%eax
+.LC39:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf56:
+.size g,.Lf56-g
+.bss
+.globl y
+.align 4
+.type y,@object
+.size y,12
+.comm y,12
+.globl x
+.align 4
+.type x,@object
+.size x,48
+.comm x,48
+.data
+.align 1
+.LC29:
+.byte 10
+.byte 0
+.align 1
+.LC28:
+.byte 32
+.byte 37
+.byte 100
+.byte 0
+.text
+.ident "LCC: 4.1"
diff --git a/lcc/x86/linux/tst/cf.1bk b/lcc/x86/linux/tst/cf.1bk
new file mode 100755
index 0000000..24e21ba
--- /dev/null
+++ b/lcc/x86/linux/tst/cf.1bk
@@ -0,0 +1,51 @@
+char freq
+011 8.1
+012 6.1
+040 11.9
+! 0.2
+" 1.5
+% 0.6
+& 0.4
+' 0.4
+( 2.9
+) 2.9
+* 0.8
++ 1.3
+, 1.3
+- 0.4
+. 0.6
+/ 1.0
+0 2.5
+1 1.9
+2 0.6
+3 0.2
+7 0.4
+8 0.2
+; 3.8
+< 0.8
+= 2.7
+> 0.2
+[ 1.5
+\ 0.8
+] 1.5
+a 3.1
+c 4.4
+e 2.3
+f 6.0
+g 1.3
+h 1.0
+i 5.0
+l 1.0
+m 0.2
+n 3.3
+o 2.1
+p 1.0
+q 0.4
+r 4.2
+s 0.6
+t 3.8
+u 1.2
+v 0.6
+w 0.2
+{ 0.6
+} 0.6
diff --git a/lcc/x86/linux/tst/cf.2bk b/lcc/x86/linux/tst/cf.2bk
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/x86/linux/tst/cf.2bk
diff --git a/lcc/x86/linux/tst/cf.sbk b/lcc/x86/linux/tst/cf.sbk
new file mode 100755
index 0000000..dc886e0
--- /dev/null
+++ b/lcc/x86/linux/tst/cf.sbk
@@ -0,0 +1,161 @@
+.globl main
+.text
+.align 16
+.type main,@function
+main:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $24,%esp
+cmpl $1,20(%ebp)
+jg .LC2
+flds .LC4
+fstps -16(%ebp)
+jmp .LC3
+.LC2:
+movl 24(%ebp),%edi
+pushl 4(%edi)
+call atof
+addl $4,%esp
+fstps -20(%ebp)
+flds -20(%ebp)
+fdivs .LC5
+fstps -16(%ebp)
+.LC3:
+movl $0,-4(%ebp)
+.LC6:
+movl -4(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-4(%ebp)
+flds .LC4
+fstps f(,%edi,4)
+.LC7:
+cmpl $127,-4(%ebp)
+jle .LC6
+movl $0,-8(%ebp)
+jmp .LC11
+.LC10:
+movl -12(%ebp),%edi
+leal f(,%edi,4),%edi
+flds (,%edi)
+fadds .LC13
+fstps (,%edi)
+incl -8(%ebp)
+.LC11:
+call getchar
+movl %eax,-12(%ebp)
+cmpl $-1,%eax
+jne .LC10
+pushl $.LC14
+call printf
+addl $4,%esp
+movl $0,-4(%ebp)
+.LC15:
+movl -4(%ebp),%edi
+flds f(,%edi,4)
+fstps -24(%ebp)
+flds .LC4
+fcomps -24(%ebp)
+fstsw %ax
+sahf
+je .LC19
+flds -24(%ebp)
+fildl -8(%ebp)
+fdivp %st(1),%st
+flds -16(%ebp)
+fcompp
+fstsw %ax
+sahf
+ja .LC19
+cmpl $32,-4(%ebp)
+jg .LC21
+pushl -4(%ebp)
+pushl $.LC23
+call printf
+addl $8,%esp
+jmp .LC22
+.LC21:
+pushl -4(%ebp)
+pushl $.LC24
+call printf
+addl $8,%esp
+.LC22:
+flds .LC5
+movl -4(%ebp),%edi
+fmuls f(,%edi,4)
+fildl -8(%ebp)
+fdivp %st(1),%st
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC25
+call printf
+addl $12,%esp
+.LC19:
+.LC16:
+incl -4(%ebp)
+cmpl $127,-4(%ebp)
+jle .LC15
+movl $0,%eax
+.LC1:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf26:
+.size main,.Lf26-main
+.bss
+.globl f
+.align 4
+.type f,@object
+.size f,512
+.comm f,512
+.data
+.align 1
+.LC25:
+.byte 9
+.byte 37
+.byte 46
+.byte 49
+.byte 102
+.byte 10
+.byte 0
+.align 1
+.LC24:
+.byte 37
+.byte 99
+.byte 0
+.align 1
+.LC23:
+.byte 37
+.byte 48
+.byte 51
+.byte 111
+.byte 0
+.align 1
+.LC14:
+.byte 99
+.byte 104
+.byte 97
+.byte 114
+.byte 9
+.byte 102
+.byte 114
+.byte 101
+.byte 113
+.byte 10
+.byte 0
+.align 4
+.LC13:
+.long 1065353216
+.align 4
+.LC5:
+.long 1120403456
+.align 4
+.LC4:
+.long 0
+.text
+.ident "LCC: 4.1"
diff --git a/lcc/x86/linux/tst/cq.1bk b/lcc/x86/linux/tst/cq.1bk
new file mode 100755
index 0000000..05acbee
--- /dev/null
+++ b/lcc/x86/linux/tst/cq.1bk
@@ -0,0 +1,48 @@
+Section s22 returned 0.
+Decimal and octal/hex constants sometimes give
+ different results when assigned to longs.
+Decimal and octal/hex constants sometimes give
+ different results when assigned to longs.
+Section s241 returned 0.
+Section s243 returned 0.
+Section s244 returned 0.
+Section s25 returned 0.
+ 8 bits in chars.
+ 32 bits in ints.
+ 16 bits in shorts.
+ 32 bits in longs.
+ 32 bits in unsigneds.
+ 32 bits in floats.
+ 64 bits in doubles.
+1.192093e-07 is the least number that can be added to 1. (float).
+2.220446e-16 is the least number that can be added to 1. (double).
+Section s26 returned 0.
+Section s4 returned 0.
+Section s61 returned 0.
+Section s626 returned 0.
+Section s71 returned 0.
+Section s72 returned 0.
+Section s757 returned 0.
+Section s7813 returned 0.
+Section s714 returned 0.
+Section s715 returned 0.
+Register count for char is unreliable.
+Register count for pointer is unreliable.
+Register count for int is unreliable.
+Section s81 returned 0.
+Section s84 returned 0.
+char alignment: 1
+short alignment: 2
+int alignment: 4
+long alignment: 4
+unsigned alignment: 4
+float alignment: 4
+double alignment: 4
+Sign extension in fields
+Be especially careful with 1-bit fields!
+Section s85 returned 0.
+Section s86 returned 0.
+Section s88 returned 0.
+Section s9 returned 0.
+
+No errors detected.
diff --git a/lcc/x86/linux/tst/cq.2bk b/lcc/x86/linux/tst/cq.2bk
new file mode 100755
index 0000000..295f5b6
--- /dev/null
+++ b/lcc/x86/linux/tst/cq.2bk
@@ -0,0 +1,25 @@
+tst/cq.c:394: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:394: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:394: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:395: warning: overflow in constant `4294967296'
+tst/cq.c:395: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:395: warning: overflow in constant `040000000000'
+tst/cq.c:395: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:395: warning: overflow in constant `0x100000000'
+tst/cq.c:395: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:396: warning: overflow in constant `68719476735'
+tst/cq.c:396: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:396: warning: overflow in constant `0777777777777'
+tst/cq.c:396: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:396: warning: overflow in constant `0xfffffffff'
+tst/cq.c:396: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:397: warning: overflow in constant `68719476736'
+tst/cq.c:397: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:397: warning: overflow in constant `01000000000000'
+tst/cq.c:397: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:397: warning: overflow in constant `0x1000000000'
+tst/cq.c:397: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:533: warning: missing return value
+tst/cq.c:1169: warning: missing return value
+tst/cq.c:5294: warning: unreachable code
+tst/cq.c:5303: warning: missing return value
diff --git a/lcc/x86/linux/tst/cq.sbk b/lcc/x86/linux/tst/cq.sbk
new file mode 100755
index 0000000..6e93567
--- /dev/null
+++ b/lcc/x86/linux/tst/cq.sbk
@@ -0,0 +1,15756 @@
+.data
+.align 4
+.type sec.2,@object
+sec.2:
+.long s22
+.long s241
+.long s243
+.long s244
+.long s25
+.long s26
+.long s4
+.long s61
+.long s626
+.long s71
+.long s72
+.long s757
+.long s7813
+.long s714
+.long s715
+.long s81
+.long s84
+.long s85
+.long s86
+.long s88
+.long s9
+.bss
+.size sec.2,84
+.align 4
+.type d0.3,@object
+.size d0.3,68
+.lcomm d0.3,68
+.align 4
+.type pd0.4,@object
+.size pd0.4,4
+.lcomm pd0.4,4
+.globl main
+.text
+.align 16
+.type main,@function
+main:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $4,%esp
+movl $1,d0.3+36
+movl $1,d0.3+40
+movl $1,d0.3+44
+movl $1,d0.3+48
+leal d0.3,%edi
+movl %edi,pd0.4
+movl $0,-4(%ebp)
+jmp .LC12
+.LC9:
+pushl pd0.4
+movl -4(%ebp),%edi
+call *sec.2(,%edi,4)
+addl $4,%esp
+movl %eax,d0.3+52
+movl d0.3+56,%edi
+movl d0.3+52,%esi
+leal (%esi,%edi),%edi
+movl %edi,d0.3+56
+cmpl $0,d0.3+36
+je .LC17
+pushl d0.3+52
+pushl $d0.3+60
+pushl $.LC20
+call printf
+addl $12,%esp
+.LC17:
+.LC10:
+incl -4(%ebp)
+.LC12:
+movl -4(%ebp),%edi
+cmpl $21,%edi
+jb .LC9
+cmpl $0,d0.3+56
+jne .LC23
+pushl $.LC26
+call printf
+addl $4,%esp
+jmp .LC24
+.LC23:
+pushl $.LC27
+call printf
+addl $4,%esp
+.LC24:
+movl $0,%eax
+.LC1:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf28:
+.size main,.Lf28-main
+.data
+.align 1
+.type s22er.30,@object
+s22er.30:
+.byte 115
+.byte 50
+.byte 50
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size s22er.30,10
+.align 1
+.type qs22.31,@object
+.size qs22.31,8
+qs22.31:
+.byte 115
+.byte 50
+.byte 50
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s22
+.text
+.align 16
+.type s22,@function
+s22:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $32,%esp
+movl $0,-12(%ebp)
+leal qs22.31,%edi
+movl %edi,-4(%ebp)
+movl 20(%ebp),%edi
+leal 60(%edi),%edi
+movl %edi,-8(%ebp)
+.LC32:
+.LC33:
+movl -8(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-8(%ebp)
+movl -4(%ebp),%esi
+leal 1(%esi),%ebx
+movl %ebx,-4(%ebp)
+movb (,%esi),%bl
+movb %bl,(,%edi)
+movsbl %bl,%edi
+cmpl $0,%edi
+jne .LC32
+movl $1,-16(%ebp)
+movl $2,-24(%ebp)
+movl $3,-28(%ebp)
+movl $4,-20(%ebp)
+movl -16(%ebp),%edi
+movl -24(%ebp),%esi
+leal (%esi,%edi),%edi
+movl -28(%ebp),%esi
+leal (%esi,%edi),%edi
+movl -20(%ebp),%esi
+leal (%esi,%edi),%edi
+cmpl $10,%edi
+je .LC35
+incl -12(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC37
+pushl $1
+pushl $s22er.30
+call printf
+addl $8,%esp
+.LC37:
+.LC35:
+movl $2,-32(%ebp)
+movl -16(%ebp),%edi
+cmpl %edi,-32(%ebp)
+jne .LC39
+addl $4,-12(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC41
+pushl $4
+pushl $s22er.30
+call printf
+addl $8,%esp
+.LC41:
+.LC39:
+movl -12(%ebp),%eax
+.LC29:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf43:
+.size s22,.Lf43-s22
+.data
+.align 1
+.type s241er.45,@object
+s241er.45:
+.byte 115
+.byte 50
+.byte 52
+.byte 49
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size s241er.45,11
+.align 1
+.type qs241.46,@object
+.size qs241.46,8
+qs241.46:
+.byte 115
+.byte 50
+.byte 52
+.byte 49
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.align 4
+.type g.47,@object
+.size g.47,156
+g.47:
+.long 0
+.long 0
+.long 0
+.long 0
+.long 0
+.long 0
+.long 0
+.long 0
+.long 0
+.long 0
+.long 0
+.long 0
+.long 0
+.long 0
+.long 0
+.long 0
+.long 0
+.long 0
+.long 6
+.long 0
+.long 8
+.long 0
+.long 12
+.long 0
+.long 16
+.long 0
+.long 18
+.long 0
+.long 20
+.long 0
+.long 24
+.long 0
+.long 28
+.long 0
+.long 30
+.long 0
+.long 32
+.long 0
+.long 36
+.globl s241
+.text
+.align 16
+.type s241,@function
+s241:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $488,%esp
+movl $0,-484(%ebp)
+movl $0,-488(%ebp)
+leal qs241.46,%edi
+movl %edi,-476(%ebp)
+movl 20(%ebp),%edi
+leal 60(%edi),%edi
+movl %edi,-480(%ebp)
+.LC48:
+.LC49:
+movl -480(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-480(%ebp)
+movl -476(%ebp),%esi
+leal 1(%esi),%ebx
+movl %ebx,-476(%ebp)
+movb (,%esi),%bl
+movb %bl,(,%edi)
+movsbl %bl,%edi
+cmpl $0,%edi
+jne .LC48
+jmp .LC51
+incl -484(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC53
+pushl $1
+pushl $s241er.45
+call printf
+addl $8,%esp
+.LC53:
+.LC51:
+jmp .LC55
+addl $2,-484(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC57
+pushl $2
+pushl $s241er.45
+call printf
+addl $8,%esp
+.LC57:
+.LC55:
+jmp .LC59
+addl $4,-484(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC61
+pushl $4
+pushl $s241er.45
+call printf
+addl $8,%esp
+.LC61:
+.LC59:
+jmp .LC63
+addl $8,-484(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC65
+pushl $8
+pushl $s241er.45
+call printf
+addl $8,%esp
+.LC65:
+.LC63:
+movl $0,-4(%ebp)
+.LC67:
+movl -4(%ebp),%edi
+movl %edi,g.47(,%edi,4)
+.LC68:
+incl -4(%ebp)
+cmpl $17,-4(%ebp)
+jl .LC67
+movl $18,-4(%ebp)
+.LC71:
+movl -4(%ebp),%edi
+leal g.47(,%edi,4),%edi
+pushl (,%edi)
+call pow2
+addl $4,%esp
+movl %eax,(,%edi)
+movl -4(%ebp),%edi
+leal (,%edi,4),%edi
+movl g.47(%edi),%esi
+subl $1,%esi
+movl %esi,g.47-4(%edi)
+addl $2,-4(%ebp)
+.LC72:
+cmpl $39,-4(%ebp)
+jl .LC71
+movl $0,-160(%ebp)
+movl $0,-316(%ebp)
+movl $0,-472(%ebp)
+movl $1,-156(%ebp)
+movl $1,-312(%ebp)
+movl $1,-468(%ebp)
+movl $2,-152(%ebp)
+movl $2,-308(%ebp)
+movl $2,-464(%ebp)
+movl $3,-148(%ebp)
+movl $3,-304(%ebp)
+movl $3,-460(%ebp)
+movl $4,-144(%ebp)
+movl $4,-300(%ebp)
+movl $4,-456(%ebp)
+movl $5,-140(%ebp)
+movl $5,-296(%ebp)
+movl $5,-452(%ebp)
+movl $6,-136(%ebp)
+movl $6,-292(%ebp)
+movl $6,-448(%ebp)
+movl $7,-132(%ebp)
+movl $7,-288(%ebp)
+movl $7,-444(%ebp)
+movl $8,-128(%ebp)
+movl $8,-284(%ebp)
+movl $8,-440(%ebp)
+movl $9,-124(%ebp)
+movl $9,-280(%ebp)
+movl $9,-436(%ebp)
+movl $10,-120(%ebp)
+movl $10,-276(%ebp)
+movl $10,-432(%ebp)
+movl $11,-116(%ebp)
+movl $11,-272(%ebp)
+movl $11,-428(%ebp)
+movl $12,-112(%ebp)
+movl $12,-268(%ebp)
+movl $12,-424(%ebp)
+movl $13,-108(%ebp)
+movl $13,-264(%ebp)
+movl $13,-420(%ebp)
+movl $14,-104(%ebp)
+movl $14,-260(%ebp)
+movl $14,-416(%ebp)
+movl $15,-100(%ebp)
+movl $15,-256(%ebp)
+movl $15,-412(%ebp)
+movl $16,-96(%ebp)
+movl $16,-252(%ebp)
+movl $16,-408(%ebp)
+movl $63,-92(%ebp)
+movl $63,-248(%ebp)
+movl $63,-404(%ebp)
+movl $64,-88(%ebp)
+movl $64,-244(%ebp)
+movl $64,-400(%ebp)
+movl $255,-84(%ebp)
+movl $255,-240(%ebp)
+movl $255,-396(%ebp)
+movl $256,-80(%ebp)
+movl $256,-236(%ebp)
+movl $256,-392(%ebp)
+movl $4095,-76(%ebp)
+movl $4095,-232(%ebp)
+movl $4095,-388(%ebp)
+movl $4096,-72(%ebp)
+movl $4096,-228(%ebp)
+movl $4096,-384(%ebp)
+movl $65535,-68(%ebp)
+movl $65535,-224(%ebp)
+movl $65535,-380(%ebp)
+movl $65536,-64(%ebp)
+movl $65536,-220(%ebp)
+movl $65536,-376(%ebp)
+movl $262143,-60(%ebp)
+movl $262143,-216(%ebp)
+movl $262143,-372(%ebp)
+movl $262144,-56(%ebp)
+movl $262144,-212(%ebp)
+movl $262144,-368(%ebp)
+movl $1048575,-52(%ebp)
+movl $1048575,-208(%ebp)
+movl $1048575,-364(%ebp)
+movl $1048576,-48(%ebp)
+movl $1048576,-204(%ebp)
+movl $1048576,-360(%ebp)
+movl $16777215,-44(%ebp)
+movl $16777215,-200(%ebp)
+movl $16777215,-356(%ebp)
+movl $16777216,-40(%ebp)
+movl $16777216,-196(%ebp)
+movl $16777216,-352(%ebp)
+movl $268435455,-36(%ebp)
+movl $268435455,-192(%ebp)
+movl $268435455,-348(%ebp)
+movl $268435456,-32(%ebp)
+movl $268435456,-188(%ebp)
+movl $268435456,-344(%ebp)
+movl $1073741823,-28(%ebp)
+movl $1073741823,-184(%ebp)
+movl $1073741823,-340(%ebp)
+movl $1073741824,-24(%ebp)
+movl $1073741824,-180(%ebp)
+movl $1073741824,-336(%ebp)
+movl $0xffffffff,%edi
+movl %edi,-20(%ebp)
+movl $0xffffffff,%edi
+movl %edi,-176(%ebp)
+movl $0xffffffff,%edi
+movl %edi,-332(%ebp)
+movl $0xffffffff,%edi
+movl %edi,-16(%ebp)
+movl $0xffffffff,%edi
+movl %edi,-172(%ebp)
+movl $0xffffffff,%edi
+movl %edi,-328(%ebp)
+movl $0xffffffff,%edi
+movl %edi,-12(%ebp)
+movl $0xffffffff,%edi
+movl %edi,-168(%ebp)
+movl $0xffffffff,%edi
+movl %edi,-324(%ebp)
+movl $0xffffffff,%edi
+movl %edi,-8(%ebp)
+movl $0xffffffff,%edi
+movl %edi,-164(%ebp)
+movl $0xffffffff,%edi
+movl %edi,-320(%ebp)
+movl $0,-4(%ebp)
+.LC190:
+movl -4(%ebp),%edi
+leal (,%edi,4),%edi
+leal -160(%ebp),%esi
+movl (%esi,%edi),%esi
+cmpl %esi,g.47(%edi)
+jne .LC197
+leal -316(%ebp),%ebx
+movl (%ebx,%edi),%ebx
+cmpl %ebx,%esi
+jne .LC197
+leal -472(%ebp),%esi
+cmpl (%esi,%edi),%ebx
+je .LC194
+.LC197:
+movl 20(%ebp),%edi
+cmpl $0,40(%edi)
+je .LC198
+pushl $.LC200
+call printf
+addl $4,%esp
+pushl $.LC201
+call printf
+addl $4,%esp
+.LC198:
+.LC194:
+.LC191:
+incl -4(%ebp)
+cmpl $39,-4(%ebp)
+jl .LC190
+cmpl $0,-488(%ebp)
+je .LC202
+movl $16,-484(%ebp)
+.LC202:
+movl -484(%ebp),%eax
+.LC44:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf204:
+.size s241,.Lf204-s241
+.globl pow2
+.align 16
+.type pow2,@function
+pow2:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $4,%esp
+movl $1,-4(%ebp)
+jmp .LC207
+.LC206:
+sall $1,-4(%ebp)
+.LC207:
+movl 20(%ebp),%edi
+movl %edi,%esi
+subl $1,%esi
+movl %esi,20(%ebp)
+cmpl $0,%edi
+jne .LC206
+movl -4(%ebp),%eax
+.LC205:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf209:
+.size pow2,.Lf209-pow2
+.data
+.align 1
+.type s243er.211,@object
+s243er.211:
+.byte 115
+.byte 50
+.byte 52
+.byte 51
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size s243er.211,11
+.align 1
+.type qs243.212,@object
+.size qs243.212,8
+qs243.212:
+.byte 115
+.byte 50
+.byte 52
+.byte 51
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s243
+.text
+.align 16
+.type s243,@function
+s243:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $268,%esp
+movl $0,-268(%ebp)
+leal qs243.212,%edi
+movl %edi,-260(%ebp)
+movl 20(%ebp),%edi
+leal 60(%edi),%edi
+movl %edi,-264(%ebp)
+.LC213:
+.LC214:
+movl -264(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-264(%ebp)
+movl -260(%ebp),%esi
+leal 1(%esi),%ebx
+movl %ebx,-260(%ebp)
+movb (,%esi),%bl
+movb %bl,(,%edi)
+movsbl %bl,%edi
+cmpl $0,%edi
+jne .LC213
+leal -256(%ebp),%edi
+pushl %edi
+call zerofill
+addl $4,%esp
+movb $1,-159(%ebp)
+movb $1,-191(%ebp)
+movb $1,-130(%ebp)
+movb $1,-208(%ebp)
+movb $1,-158(%ebp)
+movb $1,-190(%ebp)
+movb $1,-223(%ebp)
+movb $1,-207(%ebp)
+movb $1,-157(%ebp)
+movb $1,-189(%ebp)
+movb $1,-222(%ebp)
+movb $1,-206(%ebp)
+movb $1,-156(%ebp)
+movb $1,-188(%ebp)
+movb $1,-221(%ebp)
+movb $1,-205(%ebp)
+movb $1,-155(%ebp)
+movb $1,-187(%ebp)
+movb $1,-219(%ebp)
+movb $1,-204(%ebp)
+movb $1,-154(%ebp)
+movb $1,-186(%ebp)
+movb $1,-218(%ebp)
+movb $1,-203(%ebp)
+movb $1,-153(%ebp)
+movb $1,-185(%ebp)
+movb $1,-216(%ebp)
+movb $1,-202(%ebp)
+movb $1,-152(%ebp)
+movb $1,-184(%ebp)
+movb $1,-215(%ebp)
+movb $1,-201(%ebp)
+movb $1,-151(%ebp)
+movb $1,-183(%ebp)
+movb $1,-161(%ebp)
+movb $1,-200(%ebp)
+movb $1,-150(%ebp)
+movb $1,-182(%ebp)
+movb $1,-195(%ebp)
+movb $1,-199(%ebp)
+movb $1,-149(%ebp)
+movb $1,-181(%ebp)
+movb $1,-211(%ebp)
+movb $1,-148(%ebp)
+movb $1,-180(%ebp)
+movb $1,-162(%ebp)
+movb $1,-147(%ebp)
+movb $1,-179(%ebp)
+movb $1,-132(%ebp)
+movb $1,-246(%ebp)
+movb $1,-146(%ebp)
+movb $1,-178(%ebp)
+movb $1,-247(%ebp)
+movb $1,-145(%ebp)
+movb $1,-177(%ebp)
+movb $1,-133(%ebp)
+movb $1,-248(%ebp)
+movb $1,-144(%ebp)
+movb $1,-176(%ebp)
+movb $1,-131(%ebp)
+movb $1,-243(%ebp)
+movb $1,-143(%ebp)
+movb $1,-175(%ebp)
+movb $1,-165(%ebp)
+movb $1,-244(%ebp)
+movb $1,-142(%ebp)
+movb $1,-174(%ebp)
+movb $1,-163(%ebp)
+movb $1,-141(%ebp)
+movb $1,-173(%ebp)
+movb $1,-213(%ebp)
+movb $1,-164(%ebp)
+movb $1,-140(%ebp)
+movb $1,-172(%ebp)
+movb $1,-197(%ebp)
+movb $1,-217(%ebp)
+movb $1,-139(%ebp)
+movb $1,-171(%ebp)
+movb $1,-214(%ebp)
+movb $1,-138(%ebp)
+movb $1,-170(%ebp)
+movb $1,-198(%ebp)
+movb $1,-256(%ebp)
+movb $1,-137(%ebp)
+movb $1,-169(%ebp)
+movb $1,-196(%ebp)
+movb $1,-224(%ebp)
+movb $1,-136(%ebp)
+movb $1,-168(%ebp)
+movb $1,-194(%ebp)
+movb $1,-135(%ebp)
+movb $1,-167(%ebp)
+movb $1,-212(%ebp)
+movb $1,-134(%ebp)
+movb $1,-166(%ebp)
+movb $1,-210(%ebp)
+movb $1,-193(%ebp)
+movb $1,-209(%ebp)
+leal -256(%ebp),%edi
+pushl %edi
+call sumof
+addl $4,%esp
+cmpl $98,%eax
+je .LC313
+incl -268(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC315
+pushl $1
+pushl $s243er.211
+call printf
+addl $8,%esp
+.LC315:
+.LC313:
+jmp .LC317
+addl $8,-268(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC319
+pushl $8
+pushl $s243er.211
+call printf
+addl $8,%esp
+.LC319:
+.LC317:
+movl -268(%ebp),%eax
+.LC210:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf321:
+.size s243,.Lf321-s243
+.globl zerofill
+.align 16
+.type zerofill,@function
+zerofill:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $4,%esp
+movl $0,-4(%ebp)
+.LC323:
+movl 20(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,20(%ebp)
+movb $0,(,%edi)
+.LC324:
+incl -4(%ebp)
+cmpl $256,-4(%ebp)
+jl .LC323
+movl $0,%eax
+.LC322:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf327:
+.size zerofill,.Lf327-zerofill
+.globl sumof
+.align 16
+.type sumof,@function
+sumof:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $12,%esp
+movl 20(%ebp),%edi
+movl %edi,-12(%ebp)
+movl $0,-4(%ebp)
+movl $0,-8(%ebp)
+.LC329:
+movl -12(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-12(%ebp)
+movsbl (,%edi),%edi
+addl %edi,-4(%ebp)
+.LC330:
+incl -8(%ebp)
+cmpl $256,-8(%ebp)
+jl .LC329
+movl -4(%ebp),%eax
+.LC328:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf333:
+.size sumof,.Lf333-sumof
+.data
+.align 1
+.type s244er.335,@object
+s244er.335:
+.byte 115
+.byte 50
+.byte 52
+.byte 52
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size s244er.335,11
+.align 1
+.type qs244.336,@object
+.size qs244.336,8
+qs244.336:
+.byte 115
+.byte 50
+.byte 52
+.byte 52
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s244
+.text
+.align 16
+.type s244,@function
+s244:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $92,%esp
+leal qs244.336,%edi
+movl %edi,-72(%ebp)
+movl 20(%ebp),%edi
+leal 60(%edi),%edi
+movl %edi,-76(%ebp)
+.LC337:
+.LC338:
+movl -76(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-76(%ebp)
+movl -72(%ebp),%esi
+leal 1(%esi),%ebx
+movl %ebx,-72(%ebp)
+movb (,%esi),%bl
+movb %bl,(,%edi)
+movsbl %bl,%edi
+cmpl $0,%edi
+jne .LC337
+movl $0,-84(%ebp)
+movl $0,-80(%ebp)
+fldl .LC340
+fstpl -68(%ebp)
+fldl .LC340
+fstpl -60(%ebp)
+fldl .LC340
+fstpl -52(%ebp)
+fldl .LC340
+fstpl -44(%ebp)
+fldl .LC340
+fstpl -36(%ebp)
+fldl .LC340
+fstpl -28(%ebp)
+fldl .LC340
+fstpl -20(%ebp)
+fldl .LC340
+fstpl -12(%ebp)
+movl $0,-80(%ebp)
+movl $0,-4(%ebp)
+.LC348:
+movl -4(%ebp),%edi
+leal (,%edi,8),%edi
+leal -68(%ebp),%esi
+leal -60(%ebp),%ebx
+fldl (%ebx,%edi)
+fcompl (%esi,%edi)
+fstsw %ax
+sahf
+je .LC352
+movl $1,-80(%ebp)
+.LC352:
+.LC349:
+incl -4(%ebp)
+cmpl $7,-4(%ebp)
+jl .LC348
+cmpl $0,-80(%ebp)
+je .LC355
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC357
+pushl $1
+pushl $s244er.335
+call printf
+addl $8,%esp
+.LC357:
+incl -84(%ebp)
+.LC355:
+jmp .LC359
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC361
+pushl $2
+pushl $s244er.335
+call printf
+addl $8,%esp
+.LC361:
+addl $2,-84(%ebp)
+.LC359:
+movl -84(%ebp),%eax
+.LC334:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf363:
+.size s244,.Lf363-s244
+.data
+.align 1
+.type s25er.365,@object
+s25er.365:
+.byte 115
+.byte 50
+.byte 53
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size s25er.365,10
+.align 1
+.type qs25.366,@object
+.size qs25.366,8
+qs25.366:
+.byte 115
+.byte 50
+.byte 53
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s25
+.text
+.align 16
+.type s25,@function
+s25:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $28,%esp
+leal qs25.366,%edi
+movl %edi,-16(%ebp)
+movl 20(%ebp),%edi
+leal 60(%edi),%edi
+movl %edi,-20(%ebp)
+.LC367:
+.LC368:
+movl -20(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-20(%ebp)
+movl -16(%ebp),%esi
+leal 1(%esi),%ebx
+movl %ebx,-16(%ebp)
+movb (,%esi),%bl
+movb %bl,(,%edi)
+movsbl %bl,%edi
+cmpl $0,%edi
+jne .LC367
+movl $0,-24(%ebp)
+leal .LC370,%edi
+movl %edi,-8(%ebp)
+movl -8(%ebp),%edi
+movsbl 1(%edi),%esi
+movsbl (,%edi),%ebx
+cmpl %esi,%ebx
+jne .LC374
+movsbl 2(%edi),%edi
+cmpl %edi,%esi
+jne .LC374
+cmpl $46,%edi
+je .LC371
+.LC374:
+incl -24(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC375
+pushl $1
+pushl $s25er.365
+call printf
+addl $8,%esp
+.LC375:
+.LC371:
+movl -8(%ebp),%edi
+movsbl 3(%edi),%edi
+cmpl $0,%edi
+je .LC377
+addl $4,-24(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC379
+pushl $4
+pushl $s25er.365
+call printf
+addl $8,%esp
+.LC379:
+.LC377:
+movsbl .LC383+1,%edi
+cmpl $34,%edi
+je .LC381
+addl $8,-24(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC385
+pushl $8
+pushl $s25er.365
+call printf
+addl $8,%esp
+.LC385:
+.LC381:
+leal .LC387,%edi
+movl %edi,-8(%ebp)
+movl -8(%ebp),%edi
+movsbl (,%edi),%esi
+cmpl $10,%esi
+jne .LC395
+movsbl 1(%edi),%esi
+cmpl $9,%esi
+jne .LC395
+movsbl 2(%edi),%esi
+cmpl $8,%esi
+jne .LC395
+movsbl 3(%edi),%esi
+cmpl $13,%esi
+jne .LC395
+movsbl 4(%edi),%esi
+cmpl $12,%esi
+jne .LC395
+movsbl 5(%edi),%esi
+cmpl $92,%esi
+jne .LC395
+movsbl 6(%edi),%edi
+cmpl $39,%edi
+je .LC388
+.LC395:
+addl $16,-24(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC396
+pushl $16
+pushl $s25er.365
+call printf
+addl $8,%esp
+.LC396:
+.LC388:
+leal .LC398,%edi
+movl %edi,-12(%ebp)
+movl %edi,-8(%ebp)
+movl $0,-28(%ebp)
+movl $0,-4(%ebp)
+jmp .LC402
+.LC399:
+movl -4(%ebp),%edi
+movl -8(%ebp),%esi
+movsbl (%esi,%edi),%esi
+movl -12(%ebp),%ebx
+movsbl (%ebx,%edi),%edi
+cmpl %edi,%esi
+je .LC403
+movl $1,-28(%ebp)
+.LC403:
+.LC400:
+incl -4(%ebp)
+.LC402:
+movl -4(%ebp),%edi
+cmpl $7,%edi
+jb .LC399
+cmpl $0,-28(%ebp)
+je .LC405
+addl $32,-24(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC407
+pushl $32
+pushl $s25er.365
+call printf
+addl $8,%esp
+.LC407:
+.LC405:
+movl -24(%ebp),%eax
+.LC364:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf409:
+.size s25,.Lf409-s25
+.data
+.align 1
+.type qs26.411,@object
+.size qs26.411,8
+qs26.411:
+.byte 115
+.byte 50
+.byte 54
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.align 1
+.type s.412,@object
+s.412:
+.byte 37
+.byte 51
+.byte 100
+.byte 32
+.byte 98
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 37
+.byte 115
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.size s.412,18
+.align 1
+.type s2.413,@object
+s2.413:
+.byte 37
+.byte 101
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 108
+.byte 101
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 97
+.byte 100
+.byte 100
+.byte 101
+.byte 100
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 49
+.byte 46
+.byte 32
+.byte 40
+.byte 37
+.byte 115
+.byte 41
+.byte 46
+.byte 10
+.byte 0
+.size s2.413,54
+.globl s26
+.text
+.align 16
+.type s26,@function
+s26:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $56,%esp
+leal qs26.411,%edi
+movl %edi,-36(%ebp)
+movl 20(%ebp),%edi
+leal 60(%edi),%edi
+movl %edi,-40(%ebp)
+.LC414:
+.LC415:
+movl -40(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-40(%ebp)
+movl -36(%ebp),%esi
+leal 1(%esi),%ebx
+movl %ebx,-36(%ebp)
+movb (,%esi),%bl
+movb %bl,(,%edi)
+movsbl %bl,%edi
+cmpl $0,%edi
+jne .LC414
+movl 20(%ebp),%edi
+movl $0,(,%edi)
+movb $0,-41(%ebp)
+movb $1,-5(%ebp)
+jmp .LC418
+.LC417:
+movsbl -5(%ebp),%edi
+leal (,%edi,2),%edi
+movl %edi,%ebx
+movb %bl,-5(%ebp)
+movl 20(%ebp),%edi
+incl (,%edi)
+.LC418:
+movsbl -41(%ebp),%edi
+movsbl -5(%ebp),%esi
+cmpl %esi,%edi
+jne .LC417
+movl 20(%ebp),%edi
+movl (,%edi),%esi
+leal (,%esi,4),%esi
+movl %esi,4(%edi)
+movl 20(%ebp),%edi
+movl (,%edi),%esi
+leal (,%esi,2),%esi
+movl %esi,8(%edi)
+movl 20(%ebp),%edi
+movl (,%edi),%esi
+leal (,%esi,4),%esi
+movl %esi,12(%edi)
+movl 20(%ebp),%edi
+movl (,%edi),%esi
+leal (,%esi,4),%esi
+movl %esi,16(%edi)
+movl 20(%ebp),%edi
+movl (,%edi),%esi
+leal (,%esi,4),%esi
+movl %esi,20(%edi)
+movl 20(%ebp),%edi
+movl (,%edi),%esi
+leal (,%esi,8),%esi
+movl %esi,24(%edi)
+flds .LC420
+fstps -16(%ebp)
+flds .LC420
+fstps -4(%ebp)
+flds .LC421
+fstps -12(%ebp)
+jmp .LC423
+.LC422:
+flds -16(%ebp)
+fadds -4(%ebp)
+fstps -12(%ebp)
+flds -4(%ebp)
+fdivl .LC425
+fstps -4(%ebp)
+.LC423:
+flds -16(%ebp)
+fcomps -12(%ebp)
+fstsw %ax
+sahf
+jne .LC422
+movl 20(%ebp),%edi
+fldl .LC426
+fmuls -4(%ebp)
+fstps 28(%edi)
+fldl .LC427
+fstpl -32(%ebp)
+flds .LC420
+fstps -4(%ebp)
+fldl .LC428
+fstpl -24(%ebp)
+jmp .LC430
+.LC429:
+flds -4(%ebp)
+fstpl -56(%ebp)
+fldl -32(%ebp)
+faddl -56(%ebp)
+fstpl -24(%ebp)
+fldl -56(%ebp)
+fdivl .LC425
+fstps -4(%ebp)
+.LC430:
+fldl -32(%ebp)
+fcompl -24(%ebp)
+fstsw %ax
+sahf
+jne .LC429
+movl 20(%ebp),%edi
+fldl .LC426
+fmuls -4(%ebp)
+fstps 32(%edi)
+movl 20(%ebp),%edi
+cmpl $0,40(%edi)
+je .LC432
+pushl $.LC434
+movl 20(%ebp),%edi
+pushl (,%edi)
+pushl $s.412
+call printf
+addl $12,%esp
+pushl $.LC435
+movl 20(%ebp),%edi
+pushl 4(%edi)
+pushl $s.412
+call printf
+addl $12,%esp
+pushl $.LC436
+movl 20(%ebp),%edi
+pushl 8(%edi)
+pushl $s.412
+call printf
+addl $12,%esp
+pushl $.LC437
+movl 20(%ebp),%edi
+pushl 12(%edi)
+pushl $s.412
+call printf
+addl $12,%esp
+pushl $.LC438
+movl 20(%ebp),%edi
+pushl 16(%edi)
+pushl $s.412
+call printf
+addl $12,%esp
+pushl $.LC439
+movl 20(%ebp),%edi
+pushl 20(%edi)
+pushl $s.412
+call printf
+addl $12,%esp
+pushl $.LC440
+movl 20(%ebp),%edi
+pushl 24(%edi)
+pushl $s.412
+call printf
+addl $12,%esp
+pushl $.LC439
+movl 20(%ebp),%edi
+flds 28(%edi)
+subl $8,%esp
+fstpl (%esp)
+pushl $s2.413
+call printf
+addl $16,%esp
+pushl $.LC440
+movl 20(%ebp),%edi
+flds 32(%edi)
+subl $8,%esp
+fstpl (%esp)
+pushl $s2.413
+call printf
+addl $16,%esp
+.LC432:
+movl $0,%eax
+.LC410:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf441:
+.size s26,.Lf441-s26
+.data
+.align 1
+.type s4er.443,@object
+s4er.443:
+.byte 115
+.byte 52
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size s4er.443,9
+.align 1
+.type qs4.444,@object
+.size qs4.444,8
+qs4.444:
+.byte 115
+.byte 52
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s4
+.text
+.align 16
+.type s4,@function
+s4:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $36,%esp
+movl $0,-24(%ebp)
+leal qs4.444,%edi
+movl %edi,-16(%ebp)
+movl 20(%ebp),%edi
+leal 60(%edi),%edi
+movl %edi,-20(%ebp)
+.LC445:
+.LC446:
+movl -20(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-20(%ebp)
+movl -16(%ebp),%esi
+leal 1(%esi),%ebx
+movl %ebx,-16(%ebp)
+movb (,%esi),%bl
+movb %bl,(,%edi)
+movsbl %bl,%edi
+cmpl $0,%edi
+jne .LC445
+movl $0,-4(%ebp)
+.LC448:
+pushl -4(%ebp)
+call svtest
+addl $4,%esp
+movl %eax,%edi
+call zero
+cmpl %eax,%edi
+je .LC452
+movl $1,-24(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC454
+pushl $1
+pushl $s4er.443
+call printf
+addl $8,%esp
+.LC454:
+.LC452:
+.LC449:
+incl -4(%ebp)
+cmpl $3,-4(%ebp)
+jl .LC448
+call setev
+call testev
+cmpl $0,%eax
+je .LC456
+addl $2,-24(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC458
+pushl $2
+pushl $s4er.443
+call printf
+addl $8,%esp
+.LC458:
+.LC456:
+jmp .LC460
+addl $4,-24(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC462
+pushl $4
+pushl $s4er.443
+call printf
+addl $8,%esp
+.LC462:
+.LC460:
+movl $0xffffffff,-8(%ebp)
+movl $1,-12(%ebp)
+movl $0,-4(%ebp)
+jmp .LC467
+.LC464:
+movl -8(%ebp),%edi
+andl %edi,-12(%ebp)
+shrl $1,%edi
+movl %edi,-8(%ebp)
+.LC465:
+incl -4(%ebp)
+.LC467:
+movl -4(%ebp),%edi
+movl 20(%ebp),%esi
+movl (,%esi),%esi
+leal (,%esi,4),%esi
+cmpl %esi,%edi
+jb .LC464
+movl -12(%ebp),%edi
+cmpl $1,%edi
+jne .LC470
+movl -8(%ebp),%edi
+cmpl $0,%edi
+je .LC468
+.LC470:
+addl $8,-24(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC471
+pushl $8
+pushl $s4er.443
+call printf
+addl $8,%esp
+.LC471:
+.LC468:
+movl -24(%ebp),%eax
+.LC442:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf473:
+.size s4,.Lf473-s4
+.bss
+.align 4
+.type k.475,@object
+.size k.475,4
+.lcomm k.475,4
+.globl svtest
+.text
+.align 16
+.type svtest,@function
+svtest:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $4,%esp
+movl 20(%ebp),%edi
+cmpl $0,%edi
+je .LC478
+cmpl $1,%edi
+je .LC479
+cmpl $2,%edi
+je .LC482
+jmp .LC476
+.LC478:
+movl $1978,k.475
+movl $0,-4(%ebp)
+jmp .LC477
+.LC479:
+cmpl $1978,k.475
+je .LC480
+movl $1,-4(%ebp)
+jmp .LC477
+.LC480:
+movl $1929,k.475
+movl $0,-4(%ebp)
+jmp .LC477
+.LC482:
+cmpl $1929,k.475
+je .LC483
+movl $1,-4(%ebp)
+jmp .LC477
+.LC483:
+movl $0,-4(%ebp)
+.LC476:
+.LC477:
+movl -4(%ebp),%eax
+.LC474:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf485:
+.size svtest,.Lf485-svtest
+.bss
+.align 4
+.type k.487,@object
+.size k.487,4
+.lcomm k.487,4
+.globl zero
+.text
+.align 16
+.type zero,@function
+zero:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $4,%esp
+movl $2,k.487
+movl $0,-4(%ebp)
+movl -4(%ebp),%eax
+.LC486:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf488:
+.size zero,.Lf488-zero
+.globl testev
+.align 16
+.type testev,@function
+testev:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+cmpl $1066,extvar
+je .LC490
+movl $1,%eax
+jmp .LC489
+.LC490:
+movl $0,%eax
+.LC489:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf492:
+.size testev,.Lf492-testev
+.data
+.align 1
+.type s61er.494,@object
+s61er.494:
+.byte 115
+.byte 54
+.byte 49
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size s61er.494,10
+.align 1
+.type qs61.495,@object
+.size qs61.495,8
+qs61.495:
+.byte 115
+.byte 54
+.byte 49
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.align 1
+.type upper_alpha.496,@object
+upper_alpha.496:
+.byte 65
+.byte 66
+.byte 67
+.byte 68
+.byte 69
+.byte 70
+.byte 71
+.byte 72
+.byte 73
+.byte 74
+.byte 75
+.byte 76
+.byte 77
+.byte 78
+.byte 79
+.byte 80
+.byte 81
+.byte 82
+.byte 83
+.byte 84
+.byte 85
+.byte 86
+.byte 87
+.byte 88
+.byte 89
+.byte 90
+.byte 0
+.size upper_alpha.496,27
+.align 1
+.type lower_alpha.497,@object
+lower_alpha.497:
+.byte 97
+.byte 98
+.byte 99
+.byte 100
+.byte 101
+.byte 102
+.byte 103
+.byte 104
+.byte 105
+.byte 106
+.byte 107
+.byte 108
+.byte 109
+.byte 110
+.byte 111
+.byte 112
+.byte 113
+.byte 114
+.byte 115
+.byte 116
+.byte 117
+.byte 118
+.byte 119
+.byte 120
+.byte 121
+.byte 122
+.byte 0
+.size lower_alpha.497,27
+.align 1
+.type numbers.498,@object
+numbers.498:
+.byte 48
+.byte 49
+.byte 50
+.byte 51
+.byte 52
+.byte 53
+.byte 54
+.byte 55
+.byte 56
+.byte 57
+.byte 0
+.size numbers.498,11
+.align 1
+.type special_characters.499,@object
+special_characters.499:
+.byte 126
+.byte 33
+.byte 34
+.byte 35
+.byte 37
+.byte 38
+.byte 40
+.byte 41
+.byte 95
+.byte 61
+.byte 45
+.byte 94
+.byte 124
+.byte 123
+.byte 125
+.byte 91
+.byte 93
+.byte 43
+.byte 59
+.byte 42
+.byte 58
+.byte 60
+.byte 62
+.byte 44
+.byte 46
+.byte 63
+.byte 47
+.byte 0
+.size special_characters.499,28
+.align 1
+.type extra_special_characters.500,@object
+extra_special_characters.500:
+.byte 10
+.byte 9
+.byte 8
+.byte 13
+.byte 12
+.byte 92
+.byte 39
+.byte 0
+.size extra_special_characters.500,8
+.align 1
+.type blank_and_NUL.501,@object
+blank_and_NUL.501:
+.byte 32
+.byte 0
+.byte 0
+.size blank_and_NUL.501,3
+.globl s61
+.text
+.align 16
+.type s61,@function
+s61:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $60,%esp
+leal qs61.495,%edi
+movl %edi,-36(%ebp)
+movl 20(%ebp),%edi
+leal 60(%edi),%edi
+movl %edi,-40(%ebp)
+movl $0,-48(%ebp)
+.LC502:
+.LC503:
+movl -40(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-40(%ebp)
+movl -36(%ebp),%esi
+leal 1(%esi),%ebx
+movl %ebx,-36(%ebp)
+movb (,%esi),%bl
+movb %bl,(,%edi)
+movsbl %bl,%edi
+cmpl $0,%edi
+jne .LC502
+movw $-19,-54(%ebp)
+movswl -54(%ebp),%edi
+movl %edi,-60(%ebp)
+cmpl $-19,-60(%ebp)
+je .LC505
+incl -48(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC507
+pushl $1
+pushl $s61er.494
+call printf
+addl $8,%esp
+.LC507:
+.LC505:
+leal upper_alpha.496,%edi
+movl %edi,-28(%ebp)
+leal lower_alpha.497,%edi
+movl %edi,-24(%ebp)
+leal numbers.498,%edi
+movl %edi,-20(%ebp)
+leal special_characters.499,%edi
+movl %edi,-16(%ebp)
+leal extra_special_characters.500,%edi
+movl %edi,-12(%ebp)
+leal blank_and_NUL.501,%edi
+movl %edi,-8(%ebp)
+movl $0,-32(%ebp)
+movl $0,-4(%ebp)
+jmp .LC519
+.LC518:
+movl -4(%ebp),%edi
+leal -28(%ebp),%esi
+leal (%esi,%edi,4),%edi
+movl (,%edi),%esi
+leal 1(%esi),%ebx
+movl %ebx,(,%edi)
+movsbl (,%esi),%edi
+cmpl $0,%edi
+jge .LC521
+movl $1,-32(%ebp)
+.LC521:
+.LC519:
+movl -4(%ebp),%edi
+leal -28(%ebp),%esi
+movl (%esi,%edi,4),%edi
+movsbl (,%edi),%edi
+cmpl $0,%edi
+jne .LC518
+.LC515:
+incl -4(%ebp)
+cmpl $6,-4(%ebp)
+jl .LC519
+cmpl $0,-32(%ebp)
+je .LC523
+addl $2,-48(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC525
+pushl $2
+pushl $s61er.494
+call printf
+addl $8,%esp
+.LC525:
+.LC523:
+movl $1048579,-44(%ebp)
+movl -44(%ebp),%edi
+movl %edi,%esi
+movw %si,-50(%ebp)
+movl %edi,%ebx
+movb %bl,-51(%ebp)
+movswl -50(%ebp),%edi
+cmpl -44(%ebp),%edi
+je .LC530
+cmpl $3,%edi
+jne .LC529
+.LC530:
+movsbl -51(%ebp),%edi
+cmpl -44(%ebp),%edi
+je .LC527
+cmpl $3,%edi
+je .LC527
+.LC529:
+addl $8,-48(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC531
+pushl $8
+pushl $s61er.494
+call printf
+addl $8,%esp
+.LC531:
+.LC527:
+movl -48(%ebp),%eax
+.LC493:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf533:
+.size s61,.Lf533-s61
+.data
+.align 1
+.type s626er.535,@object
+s626er.535:
+.byte 115
+.byte 54
+.byte 50
+.byte 54
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size s626er.535,11
+.align 1
+.type qs626.536,@object
+.size qs626.536,8
+qs626.536:
+.byte 115
+.byte 54
+.byte 50
+.byte 54
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s626
+.text
+.align 16
+.type s626,@function
+s626:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $128,%esp
+leal qs626.536,%edi
+movl %edi,-56(%ebp)
+movl 20(%ebp),%edi
+leal 60(%edi),%edi
+movl %edi,-60(%ebp)
+movl $0,-104(%ebp)
+.LC537:
+.LC538:
+movl -60(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-60(%ebp)
+movl -56(%ebp),%esi
+leal 1(%esi),%ebx
+movl %ebx,-56(%ebp)
+movb (,%esi),%bl
+movb %bl,(,%edi)
+movsbl %bl,%edi
+cmpl $0,%edi
+jne .LC537
+flds .LC420
+fstps -36(%ebp)
+movl $1,-64(%ebp)
+movl $1,-40(%ebp)
+movl $0,-4(%ebp)
+jmp .LC543
+.LC540:
+flds .LC544
+fmuls -36(%ebp)
+fstps -36(%ebp)
+movl -40(%ebp),%edi
+leal (,%edi,2),%edi
+orl -64(%ebp),%edi
+movl %edi,-40(%ebp)
+.LC541:
+incl -4(%ebp)
+.LC543:
+movl 20(%ebp),%edi
+movl 12(%edi),%edi
+subl $2,%edi
+cmpl %edi,-4(%ebp)
+jl .LC540
+fildl -40(%ebp)
+fstps -112(%ebp)
+flds -36(%ebp)
+fsubs -112(%ebp)
+fdivs -36(%ebp)
+fstps -36(%ebp)
+fldl .LC425
+movl 20(%ebp),%edi
+fmuls 28(%edi)
+fcomps -36(%ebp)
+fstsw %ax
+sahf
+jae .LC545
+addl $2,-104(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC547
+pushl $2
+pushl $s626er.535
+call printf
+addl $8,%esp
+.LC547:
+.LC545:
+movb $125,-73(%ebp)
+movw $125,-76(%ebp)
+movl $125,-80(%ebp)
+movl $15625,-96(%ebp)
+movl $125,-84(%ebp)
+movl $15625,-100(%ebp)
+movl $125,-68(%ebp)
+movl $15625,-108(%ebp)
+flds .LC549
+fstps -72(%ebp)
+fldl .LC550
+fstpl -92(%ebp)
+fldl .LC551
+fstpl -52(%ebp)
+movl $0,-4(%ebp)
+.LC552:
+movl -4(%ebp),%edi
+leal -32(%ebp),%esi
+movb $0,(%esi,%edi)
+.LC553:
+incl -4(%ebp)
+cmpl $28,-4(%ebp)
+jl .LC552
+movsbl -73(%ebp),%edi
+movl %edi,%esi
+imull %edi,%esi
+cmpl -96(%ebp),%esi
+je .LC556
+movb $1,-32(%ebp)
+.LC556:
+movswl -76(%ebp),%edi
+movsbl -73(%ebp),%esi
+imull %esi,%edi
+cmpl -96(%ebp),%edi
+je .LC558
+movb $1,-31(%ebp)
+.LC558:
+movswl -76(%ebp),%edi
+movl %edi,%esi
+imull %edi,%esi
+cmpl -96(%ebp),%esi
+je .LC561
+movb $1,-30(%ebp)
+.LC561:
+movl -80(%ebp),%edi
+movsbl -73(%ebp),%esi
+imull %esi,%edi
+cmpl -96(%ebp),%edi
+je .LC564
+movb $1,-29(%ebp)
+.LC564:
+movl -80(%ebp),%edi
+movswl -76(%ebp),%esi
+imull %esi,%edi
+cmpl -96(%ebp),%edi
+je .LC567
+movb $1,-28(%ebp)
+.LC567:
+movl -80(%ebp),%edi
+movl %edi,%esi
+imull %edi,%esi
+cmpl -96(%ebp),%esi
+je .LC570
+movb $1,-27(%ebp)
+.LC570:
+movl -84(%ebp),%eax
+movsbl -73(%ebp),%edi
+mull %edi
+cmpl -100(%ebp),%eax
+je .LC573
+movb $1,-26(%ebp)
+.LC573:
+movl -84(%ebp),%eax
+movswl -76(%ebp),%edi
+mull %edi
+cmpl -100(%ebp),%eax
+je .LC576
+movb $1,-25(%ebp)
+.LC576:
+movl -84(%ebp),%eax
+movl -80(%ebp),%edi
+mull %edi
+cmpl -100(%ebp),%eax
+je .LC579
+movb $1,-24(%ebp)
+.LC579:
+movl -84(%ebp),%edi
+movl %edi,%eax
+mull %edi
+cmpl -100(%ebp),%eax
+je .LC582
+movb $1,-23(%ebp)
+.LC582:
+movl -68(%ebp),%edi
+movsbl -73(%ebp),%esi
+imull %esi,%edi
+cmpl -108(%ebp),%edi
+je .LC585
+movb $1,-22(%ebp)
+.LC585:
+movl -68(%ebp),%edi
+movswl -76(%ebp),%esi
+imull %esi,%edi
+cmpl -108(%ebp),%edi
+je .LC588
+movb $1,-21(%ebp)
+.LC588:
+movl -68(%ebp),%edi
+imull -80(%ebp),%edi
+cmpl -108(%ebp),%edi
+je .LC591
+movb $1,-20(%ebp)
+.LC591:
+movl -68(%ebp),%edi
+movl %edi,%eax
+mull -84(%ebp)
+cmpl -100(%ebp),%eax
+je .LC594
+movb $1,-19(%ebp)
+.LC594:
+movl -68(%ebp),%edi
+movl %edi,%esi
+imull %edi,%esi
+cmpl -108(%ebp),%esi
+je .LC597
+movb $1,-18(%ebp)
+.LC597:
+flds -72(%ebp)
+movsbl -73(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+fldl -52(%ebp)
+fcompp
+fstsw %ax
+sahf
+je .LC600
+movb $1,-17(%ebp)
+.LC600:
+flds -72(%ebp)
+movswl -76(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+fldl -52(%ebp)
+fcompp
+fstsw %ax
+sahf
+je .LC603
+movb $1,-16(%ebp)
+.LC603:
+flds -72(%ebp)
+fildl -80(%ebp)
+fmulp %st(1),%st
+fldl -52(%ebp)
+fcompp
+fstsw %ax
+sahf
+je .LC606
+movb $1,-15(%ebp)
+.LC606:
+movl -84(%ebp),%edi
+flds -72(%ebp)
+fldl .LC611
+movl %edi,%esi
+shrl $1,%esi
+pushl %esi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+andl $1,%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+sub $4,%esp
+fstps (%esp)
+flds (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+fldl -52(%ebp)
+fcompp
+fstsw %ax
+sahf
+je .LC609
+movb $1,-14(%ebp)
+.LC609:
+flds -72(%ebp)
+fildl -68(%ebp)
+fmulp %st(1),%st
+fldl -52(%ebp)
+fcompp
+fstsw %ax
+sahf
+je .LC613
+movb $1,-13(%ebp)
+.LC613:
+flds -72(%ebp)
+fmuls -72(%ebp)
+fldl -52(%ebp)
+fcompp
+fstsw %ax
+sahf
+je .LC616
+movb $1,-12(%ebp)
+.LC616:
+fldl -92(%ebp)
+movsbl -73(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+fldl -52(%ebp)
+fcompp
+fstsw %ax
+sahf
+je .LC619
+movb $1,-11(%ebp)
+.LC619:
+fldl -92(%ebp)
+movswl -76(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+fldl -52(%ebp)
+fcompp
+fstsw %ax
+sahf
+je .LC622
+movb $1,-10(%ebp)
+.LC622:
+fldl -92(%ebp)
+fimull -80(%ebp)
+fldl -52(%ebp)
+fcompp
+fstsw %ax
+sahf
+je .LC625
+movb $1,-9(%ebp)
+.LC625:
+movl -84(%ebp),%edi
+fldl -92(%ebp)
+fldl .LC611
+movl %edi,%esi
+shrl $1,%esi
+pushl %esi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+andl $1,%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+fmulp %st(1),%st
+fldl -52(%ebp)
+fcompp
+fstsw %ax
+sahf
+je .LC628
+movb $1,-8(%ebp)
+.LC628:
+fldl -92(%ebp)
+fimull -68(%ebp)
+fldl -52(%ebp)
+fcompp
+fstsw %ax
+sahf
+je .LC631
+movb $1,-7(%ebp)
+.LC631:
+fldl -92(%ebp)
+fmuls -72(%ebp)
+fldl -52(%ebp)
+fcompp
+fstsw %ax
+sahf
+je .LC634
+movb $1,-6(%ebp)
+.LC634:
+fldl -92(%ebp)
+fmull -92(%ebp)
+fldl -52(%ebp)
+fcompp
+fstsw %ax
+sahf
+je .LC637
+movb $1,-5(%ebp)
+.LC637:
+movb $0,-41(%ebp)
+movl $0,-4(%ebp)
+.LC640:
+movsbl -41(%ebp),%edi
+movl -4(%ebp),%esi
+leal -32(%ebp),%ebx
+movsbl (%ebx,%esi),%esi
+leal (%esi,%edi),%edi
+movl %edi,%ebx
+movb %bl,-41(%ebp)
+.LC641:
+incl -4(%ebp)
+cmpl $28,-4(%ebp)
+jl .LC640
+movsbl -41(%ebp),%edi
+cmpl $0,%edi
+je .LC644
+addl $4,-104(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC646
+pushl $4
+pushl $s626er.535
+call printf
+addl $8,%esp
+pushl $.LC648
+call printf
+addl $4,%esp
+movl $0,-4(%ebp)
+.LC649:
+movl -4(%ebp),%edi
+leal -32(%ebp),%esi
+movsbl (%esi,%edi),%edi
+pushl %edi
+pushl $.LC653
+call printf
+addl $8,%esp
+.LC650:
+incl -4(%ebp)
+cmpl $28,-4(%ebp)
+jl .LC649
+pushl $.LC654
+call printf
+addl $4,%esp
+.LC646:
+.LC644:
+movl $32768,-68(%ebp)
+movl -68(%ebp),%edi
+cmpl $0x8000,%edi
+jbe .LC655
+addl $8,-104(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC657
+pushl $8
+pushl $s626er.535
+call printf
+addl $8,%esp
+.LC657:
+.LC655:
+movl -104(%ebp),%eax
+.LC534:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf659:
+.size s626,.Lf659-s626
+.data
+.align 1
+.type s71er.661,@object
+s71er.661:
+.byte 115
+.byte 55
+.byte 49
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size s71er.661,10
+.align 1
+.type qs71.662,@object
+.size qs71.662,8
+qs71.662:
+.byte 115
+.byte 55
+.byte 49
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.align 1
+.type q.663,@object
+.size q.663,1
+q.663:
+.byte 113
+.globl s71
+.text
+.align 16
+.type s71,@function
+s71:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $68,%esp
+leal qs71.662,%edi
+movl %edi,-4(%ebp)
+movl 20(%ebp),%edi
+leal 60(%edi),%edi
+movl %edi,-8(%ebp)
+movl $0,-12(%ebp)
+.LC664:
+.LC665:
+movl -8(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-8(%ebp)
+movl -4(%ebp),%esi
+leal 1(%esi),%ebx
+movl %ebx,-4(%ebp)
+movb (,%esi),%bl
+movb %bl,(,%edi)
+movsbl %bl,%edi
+cmpl $0,%edi
+jne .LC664
+movsbl .LC669,%edi
+movsbl q.663,%esi
+cmpl %esi,%edi
+je .LC667
+incl -12(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC670
+pushl $1
+pushl $s71er.661
+call printf
+addl $8,%esp
+.LC670:
+.LC667:
+jmp .LC672
+addl $2,-12(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC674
+pushl $2
+pushl $s71er.661
+call printf
+addl $8,%esp
+.LC674:
+.LC672:
+movl $1942,-32(%ebp)
+cmpl $1942,-32(%ebp)
+jne .LC682
+movl -32(%ebp),%edi
+cmpl %edi,-32(%ebp)
+je .LC677
+.LC682:
+addl $4,-12(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC683
+pushl $4
+pushl $s71er.661
+call printf
+addl $8,%esp
+.LC683:
+.LC677:
+pushl $-5
+call McCarthy
+addl $4,%esp
+cmpl $91,%eax
+je .LC685
+addl $8,-12(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC687
+pushl $8
+pushl $s71er.661
+call printf
+addl $8,%esp
+.LC687:
+.LC685:
+movl $2,-56(%ebp)
+movl $3,-60(%ebp)
+leal -60(%ebp),%edi
+movl %edi,-64(%ebp)
+pushl -64(%ebp)
+pushl -56(%ebp)
+call clobber
+addl $8,%esp
+cmpl $2,-56(%ebp)
+jne .LC691
+cmpl $2,-60(%ebp)
+je .LC689
+.LC691:
+addl $16,-12(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC692
+pushl $16
+pushl $s71er.661
+call printf
+addl $8,%esp
+.LC692:
+.LC689:
+movl 20(%ebp),%edi
+flds 32(%edi)
+fstps -68(%ebp)
+flds -68(%ebp)
+fcomps -68(%ebp)
+fstsw %ax
+sahf
+je .LC694
+addl $32,-12(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC696
+pushl $32
+pushl $s71er.661
+call printf
+addl $8,%esp
+.LC696:
+.LC694:
+movl -12(%ebp),%eax
+.LC660:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf698:
+.size s71,.Lf698-s71
+.globl McCarthy
+.align 16
+.type McCarthy,@function
+McCarthy:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+cmpl $100,20(%ebp)
+jle .LC700
+movl 20(%ebp),%edi
+movl %edi,%eax
+subl $10,%eax
+jmp .LC699
+.LC700:
+movl 20(%ebp),%edi
+leal 11(%edi),%edi
+pushl %edi
+call McCarthy
+addl $4,%esp
+movl %eax,%edi
+pushl %edi
+call McCarthy
+addl $4,%esp
+movl %eax,%edi
+.LC699:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf702:
+.size McCarthy,.Lf702-McCarthy
+.globl clobber
+.align 16
+.type clobber,@function
+clobber:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl $3,20(%ebp)
+movl 24(%ebp),%edi
+movl $2,(,%edi)
+movl $0,%eax
+.LC703:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf704:
+.size clobber,.Lf704-clobber
+.data
+.align 1
+.type f.706,@object
+f.706:
+.byte 76
+.byte 111
+.byte 99
+.byte 97
+.byte 108
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 37
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.size f.706,17
+.align 1
+.type s714er.707,@object
+s714er.707:
+.byte 115
+.byte 55
+.byte 49
+.byte 52
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size s714er.707,11
+.align 1
+.type qs714.708,@object
+.size qs714.708,8
+qs714.708:
+.byte 115
+.byte 55
+.byte 49
+.byte 52
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s714
+.text
+.align 16
+.type s714,@function
+s714:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $248,%esp
+leal qs714.708,%edi
+movl %edi,-68(%ebp)
+movl 20(%ebp),%edi
+leal 60(%edi),%esi
+movl %esi,-72(%ebp)
+movl $0,-76(%ebp)
+movl $0,-8(%ebp)
+movl 48(%edi),%edi
+movl %edi,-4(%ebp)
+.LC709:
+.LC710:
+movl -72(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-72(%ebp)
+movl -68(%ebp),%esi
+leal 1(%esi),%ebx
+movl %ebx,-68(%ebp)
+movb (,%esi),%bl
+movb %bl,(,%edi)
+movsbl %bl,%edi
+cmpl $0,%edi
+jne .LC709
+movb $5,-9(%ebp)
+movb $2,-25(%ebp)
+movb -25(%ebp),%bl
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $2,%edi
+je .LC712
+movl $1,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC714
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC714:
+.LC712:
+movb $5,-9(%ebp)
+movw $2,-28(%ebp)
+movswl -28(%ebp),%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $2,%edi
+je .LC716
+movl $2,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC718
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC718:
+.LC716:
+movb $5,-9(%ebp)
+movl $2,-32(%ebp)
+movl -32(%ebp),%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $2,%edi
+je .LC720
+movl $3,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC722
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC722:
+.LC720:
+movb $5,-9(%ebp)
+movl $2,-36(%ebp)
+movl -36(%ebp),%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $2,%edi
+je .LC724
+movl $4,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC726
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC726:
+.LC724:
+movb $5,-9(%ebp)
+movl $2,-40(%ebp)
+movl -40(%ebp),%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $2,%edi
+je .LC728
+movl $5,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC730
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC730:
+.LC728:
+movb $5,-9(%ebp)
+flds .LC544
+fstps -56(%ebp)
+flds -56(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $2,%edi
+je .LC732
+movl $6,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC734
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC734:
+.LC732:
+movb $5,-9(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+fldl -64(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $2,%edi
+je .LC736
+movl $7,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC738
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC738:
+.LC736:
+movw $5,-12(%ebp)
+movb $2,-25(%ebp)
+movsbl -25(%ebp),%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $2,%edi
+je .LC740
+movl $8,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC742
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC742:
+.LC740:
+movw $5,-12(%ebp)
+movw $2,-28(%ebp)
+movw -28(%ebp),%di
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $2,%edi
+je .LC744
+movl $9,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC746
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC746:
+.LC744:
+movw $5,-12(%ebp)
+movl $2,-32(%ebp)
+movl -32(%ebp),%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $2,%edi
+je .LC748
+movl $10,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC750
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC750:
+.LC748:
+movw $5,-12(%ebp)
+movl $2,-36(%ebp)
+movl -36(%ebp),%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $2,%edi
+je .LC752
+movl $11,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC754
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC754:
+.LC752:
+movw $5,-12(%ebp)
+movl $2,-40(%ebp)
+movl -40(%ebp),%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $2,%edi
+je .LC756
+movl $12,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC758
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC758:
+.LC756:
+movw $5,-12(%ebp)
+flds .LC544
+fstps -56(%ebp)
+flds -56(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $2,%edi
+je .LC760
+movl $13,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC762
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC762:
+.LC760:
+movw $5,-12(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+fldl -64(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $2,%edi
+je .LC764
+movl $14,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC766
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC766:
+.LC764:
+movl $5,-16(%ebp)
+movb $2,-25(%ebp)
+movsbl -25(%ebp),%edi
+movl %edi,-16(%ebp)
+cmpl $2,-16(%ebp)
+je .LC768
+movl $15,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC770
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC770:
+.LC768:
+movl $5,-16(%ebp)
+movw $2,-28(%ebp)
+movswl -28(%ebp),%edi
+movl %edi,-16(%ebp)
+cmpl $2,-16(%ebp)
+je .LC772
+movl $16,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC774
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC774:
+.LC772:
+movl $5,-16(%ebp)
+movl $2,-32(%ebp)
+movl -32(%ebp),%edi
+movl %edi,-16(%ebp)
+cmpl $2,-16(%ebp)
+je .LC776
+movl $17,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC778
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC778:
+.LC776:
+movl $5,-16(%ebp)
+movl $2,-36(%ebp)
+movl -36(%ebp),%edi
+movl %edi,-16(%ebp)
+cmpl $2,-16(%ebp)
+je .LC780
+movl $18,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC782
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC782:
+.LC780:
+movl $5,-16(%ebp)
+movl $2,-40(%ebp)
+movl -40(%ebp),%edi
+movl %edi,-16(%ebp)
+cmpl $2,-16(%ebp)
+je .LC784
+movl $19,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC786
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC786:
+.LC784:
+movl $5,-16(%ebp)
+flds .LC544
+fstps -56(%ebp)
+flds -56(%ebp)
+fistpl -16(%ebp)
+cmpl $2,-16(%ebp)
+je .LC788
+movl $20,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC790
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC790:
+.LC788:
+movl $5,-16(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+fldl -64(%ebp)
+fistpl -16(%ebp)
+cmpl $2,-16(%ebp)
+je .LC792
+movl $21,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC794
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC794:
+.LC792:
+movl $5,-20(%ebp)
+movb $2,-25(%ebp)
+movsbl -25(%ebp),%edi
+movl %edi,-20(%ebp)
+cmpl $2,-20(%ebp)
+je .LC796
+movl $22,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC798
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC798:
+.LC796:
+movl $5,-20(%ebp)
+movw $2,-28(%ebp)
+movswl -28(%ebp),%edi
+movl %edi,-20(%ebp)
+cmpl $2,-20(%ebp)
+je .LC800
+movl $23,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC802
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC802:
+.LC800:
+movl $5,-20(%ebp)
+movl $2,-32(%ebp)
+movl -32(%ebp),%edi
+movl %edi,-20(%ebp)
+cmpl $2,-20(%ebp)
+je .LC804
+movl $24,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC806
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC806:
+.LC804:
+movl $5,-20(%ebp)
+movl $2,-36(%ebp)
+movl -36(%ebp),%edi
+movl %edi,-20(%ebp)
+cmpl $2,-20(%ebp)
+je .LC808
+movl $25,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC810
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC810:
+.LC808:
+movl $5,-20(%ebp)
+movl $2,-40(%ebp)
+movl -40(%ebp),%edi
+movl %edi,-20(%ebp)
+cmpl $2,-20(%ebp)
+je .LC812
+movl $26,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC814
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC814:
+.LC812:
+movl $5,-20(%ebp)
+flds .LC544
+fstps -56(%ebp)
+flds -56(%ebp)
+fistpl -20(%ebp)
+cmpl $2,-20(%ebp)
+je .LC816
+movl $27,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC818
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC818:
+.LC816:
+movl $5,-20(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+fldl -64(%ebp)
+fistpl -20(%ebp)
+cmpl $2,-20(%ebp)
+je .LC820
+movl $28,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC822
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC822:
+.LC820:
+movl $5,-24(%ebp)
+movb $2,-25(%ebp)
+movsbl -25(%ebp),%edi
+movl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $2,%edi
+je .LC824
+movl $29,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC826
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC826:
+.LC824:
+movl $5,-24(%ebp)
+movw $2,-28(%ebp)
+movswl -28(%ebp),%edi
+movl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $2,%edi
+je .LC828
+movl $30,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC830
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC830:
+.LC828:
+movl $5,-24(%ebp)
+movl $2,-32(%ebp)
+movl -32(%ebp),%edi
+movl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $2,%edi
+je .LC832
+movl $31,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC834
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC834:
+.LC832:
+movl $5,-24(%ebp)
+movl $2,-36(%ebp)
+movl -36(%ebp),%edi
+movl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $2,%edi
+je .LC836
+movl $32,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC838
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC838:
+.LC836:
+movl $5,-24(%ebp)
+movl $2,-40(%ebp)
+movl -40(%ebp),%edi
+movl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $2,%edi
+je .LC840
+movl $33,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC842
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC842:
+.LC840:
+movl $5,-24(%ebp)
+flds .LC544
+fstps -56(%ebp)
+flds .LC847
+fcomps -56(%ebp)
+fstsw %ax
+sahf
+ja .LC845
+flds -56(%ebp)
+fsubs .LC847
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+leal 0x80000000(%edi),%edi
+movl %edi,-80(%ebp)
+jmp .LC846
+.LC845:
+flds -56(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,-80(%ebp)
+.LC846:
+movl -80(%ebp),%edi
+movl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $2,%edi
+je .LC848
+movl $34,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC850
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC850:
+.LC848:
+movl $5,-24(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+fldl .LC855
+fcompl -64(%ebp)
+fstsw %ax
+sahf
+ja .LC853
+fldl -64(%ebp)
+fsubl .LC855
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+leal 0x80000000(%edi),%edi
+movl %edi,-92(%ebp)
+jmp .LC854
+.LC853:
+fldl -64(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,-92(%ebp)
+.LC854:
+movl -92(%ebp),%edi
+movl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $2,%edi
+je .LC856
+movl $35,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC858
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC858:
+.LC856:
+flds .LC860
+fstps -44(%ebp)
+movb $2,-25(%ebp)
+movsbl -25(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fstps -44(%ebp)
+flds .LC544
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC861
+movl $36,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC863
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC863:
+.LC861:
+flds .LC860
+fstps -44(%ebp)
+movw $2,-28(%ebp)
+movswl -28(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fstps -44(%ebp)
+flds .LC544
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC865
+movl $37,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC867
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC867:
+.LC865:
+flds .LC860
+fstps -44(%ebp)
+movl $2,-32(%ebp)
+fildl -32(%ebp)
+fstps -44(%ebp)
+flds .LC544
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC869
+movl $38,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC871
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC871:
+.LC869:
+flds .LC860
+fstps -44(%ebp)
+movl $2,-36(%ebp)
+fildl -36(%ebp)
+fstps -44(%ebp)
+flds .LC544
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC873
+movl $39,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC875
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC875:
+.LC873:
+flds .LC860
+fstps -44(%ebp)
+movl $2,-40(%ebp)
+movl -40(%ebp),%edi
+fldl .LC611
+movl %edi,%esi
+shrl $1,%esi
+pushl %esi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+andl $1,%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+fstps -44(%ebp)
+flds .LC544
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC877
+movl $40,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC879
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC879:
+.LC877:
+flds .LC860
+fstps -44(%ebp)
+flds .LC544
+fstps -56(%ebp)
+flds -56(%ebp)
+fstps -44(%ebp)
+flds .LC544
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC881
+movl $41,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC883
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC883:
+.LC881:
+flds .LC860
+fstps -44(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+fldl -64(%ebp)
+fstps -44(%ebp)
+flds .LC544
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC885
+movl $42,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC887
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC887:
+.LC885:
+fldl .LC889
+fstpl -52(%ebp)
+movb $2,-25(%ebp)
+movsbl -25(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fstpl -52(%ebp)
+fldl .LC425
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC890
+movl $43,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC892
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC892:
+.LC890:
+fldl .LC889
+fstpl -52(%ebp)
+movw $2,-28(%ebp)
+movswl -28(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fstpl -52(%ebp)
+fldl .LC425
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC894
+movl $44,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC896
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC896:
+.LC894:
+fldl .LC889
+fstpl -52(%ebp)
+movl $2,-32(%ebp)
+fildl -32(%ebp)
+fstpl -52(%ebp)
+fldl .LC425
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC898
+movl $45,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC900
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC900:
+.LC898:
+fldl .LC889
+fstpl -52(%ebp)
+movl $2,-36(%ebp)
+fildl -36(%ebp)
+fstpl -52(%ebp)
+fldl .LC425
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC902
+movl $46,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC904
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC904:
+.LC902:
+fldl .LC889
+fstpl -52(%ebp)
+movl $2,-40(%ebp)
+movl -40(%ebp),%edi
+fldl .LC611
+movl %edi,%esi
+shrl $1,%esi
+pushl %esi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+andl $1,%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+fstpl -52(%ebp)
+fldl .LC425
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC906
+movl $47,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC908
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC908:
+.LC906:
+fldl .LC889
+fstpl -52(%ebp)
+flds .LC544
+fstps -56(%ebp)
+flds -56(%ebp)
+fstpl -52(%ebp)
+fldl .LC425
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC910
+movl $48,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC912
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC912:
+.LC910:
+fldl .LC889
+fstpl -52(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+fldl -64(%ebp)
+fstpl -52(%ebp)
+fldl .LC425
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC914
+movl $49,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC916
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC916:
+.LC914:
+movb $5,-9(%ebp)
+movb $2,-25(%ebp)
+movsbl -9(%ebp),%edi
+movsbl -25(%ebp),%esi
+leal (%esi,%edi),%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $7,%edi
+je .LC918
+movl $50,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC920
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC920:
+.LC918:
+movb $5,-9(%ebp)
+movw $2,-28(%ebp)
+movsbl -9(%ebp),%edi
+movswl -28(%ebp),%esi
+leal (%esi,%edi),%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $7,%edi
+je .LC922
+movl $51,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC924
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC924:
+.LC922:
+movb $5,-9(%ebp)
+movl $2,-32(%ebp)
+movsbl -9(%ebp),%edi
+movl -32(%ebp),%esi
+leal (%esi,%edi),%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $7,%edi
+je .LC926
+movl $52,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC928
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC928:
+.LC926:
+movb $5,-9(%ebp)
+movl $2,-36(%ebp)
+movsbl -9(%ebp),%edi
+movl -36(%ebp),%esi
+leal (%esi,%edi),%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $7,%edi
+je .LC930
+movl $53,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC932
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC932:
+.LC930:
+movb $5,-9(%ebp)
+movl $2,-40(%ebp)
+movsbl -9(%ebp),%edi
+movl -40(%ebp),%esi
+leal (%esi,%edi),%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $7,%edi
+je .LC934
+movl $54,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC936
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC936:
+.LC934:
+movb $5,-9(%ebp)
+flds .LC544
+fstps -56(%ebp)
+movsbl -9(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fadds -56(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $7,%edi
+je .LC938
+movl $55,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC940
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC940:
+.LC938:
+movb $5,-9(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+movsbl -9(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddl -64(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $7,%edi
+je .LC942
+movl $56,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC944
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC944:
+.LC942:
+movw $5,-12(%ebp)
+movb $2,-25(%ebp)
+movswl -12(%ebp),%edi
+movsbl -25(%ebp),%esi
+leal (%esi,%edi),%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $7,%edi
+je .LC946
+movl $57,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC948
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC948:
+.LC946:
+movw $5,-12(%ebp)
+movw $2,-28(%ebp)
+movswl -12(%ebp),%edi
+movswl -28(%ebp),%esi
+leal (%esi,%edi),%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $7,%edi
+je .LC950
+movl $58,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC952
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC952:
+.LC950:
+movw $5,-12(%ebp)
+movl $2,-32(%ebp)
+movswl -12(%ebp),%edi
+movl -32(%ebp),%esi
+leal (%esi,%edi),%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $7,%edi
+je .LC954
+movl $59,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC956
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC956:
+.LC954:
+movw $5,-12(%ebp)
+movl $2,-36(%ebp)
+movswl -12(%ebp),%edi
+movl -36(%ebp),%esi
+leal (%esi,%edi),%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $7,%edi
+je .LC958
+movl $60,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC960
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC960:
+.LC958:
+movw $5,-12(%ebp)
+movl $2,-40(%ebp)
+movswl -12(%ebp),%edi
+movl -40(%ebp),%esi
+leal (%esi,%edi),%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $7,%edi
+je .LC962
+movl $61,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC964
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC964:
+.LC962:
+movw $5,-12(%ebp)
+flds .LC544
+fstps -56(%ebp)
+movswl -12(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fadds -56(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $7,%edi
+je .LC966
+movl $62,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC968
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC968:
+.LC966:
+movw $5,-12(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+movswl -12(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddl -64(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $7,%edi
+je .LC970
+movl $63,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC972
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC972:
+.LC970:
+movl $5,-16(%ebp)
+movb $2,-25(%ebp)
+movsbl -25(%ebp),%edi
+addl %edi,-16(%ebp)
+cmpl $7,-16(%ebp)
+je .LC974
+movl $64,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC976
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC976:
+.LC974:
+movl $5,-16(%ebp)
+movw $2,-28(%ebp)
+movswl -28(%ebp),%edi
+addl %edi,-16(%ebp)
+cmpl $7,-16(%ebp)
+je .LC978
+movl $65,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC980
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC980:
+.LC978:
+movl $5,-16(%ebp)
+movl $2,-32(%ebp)
+movl -32(%ebp),%edi
+addl %edi,-16(%ebp)
+cmpl $7,-16(%ebp)
+je .LC982
+movl $66,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC984
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC984:
+.LC982:
+movl $5,-16(%ebp)
+movl $2,-36(%ebp)
+movl -36(%ebp),%edi
+addl %edi,-16(%ebp)
+cmpl $7,-16(%ebp)
+je .LC986
+movl $67,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC988
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC988:
+.LC986:
+movl $5,-16(%ebp)
+movl $2,-40(%ebp)
+movl -16(%ebp),%edi
+movl -40(%ebp),%esi
+leal (%esi,%edi),%edi
+movl %edi,-16(%ebp)
+cmpl $7,-16(%ebp)
+je .LC990
+movl $68,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC992
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC992:
+.LC990:
+movl $5,-16(%ebp)
+flds .LC544
+fstps -56(%ebp)
+fildl -16(%ebp)
+fadds -56(%ebp)
+fistpl -16(%ebp)
+cmpl $7,-16(%ebp)
+je .LC994
+movl $69,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC996
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC996:
+.LC994:
+movl $5,-16(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+fildl -16(%ebp)
+faddl -64(%ebp)
+fistpl -16(%ebp)
+cmpl $7,-16(%ebp)
+je .LC998
+movl $70,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1000
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1000:
+.LC998:
+movl $5,-20(%ebp)
+movb $2,-25(%ebp)
+movsbl -25(%ebp),%edi
+addl %edi,-20(%ebp)
+cmpl $7,-20(%ebp)
+je .LC1002
+movl $71,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1004
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1004:
+.LC1002:
+movl $5,-20(%ebp)
+movw $2,-28(%ebp)
+movswl -28(%ebp),%edi
+addl %edi,-20(%ebp)
+cmpl $7,-20(%ebp)
+je .LC1006
+movl $72,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1008
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1008:
+.LC1006:
+movl $5,-20(%ebp)
+movl $2,-32(%ebp)
+movl -32(%ebp),%edi
+addl %edi,-20(%ebp)
+cmpl $7,-20(%ebp)
+je .LC1010
+movl $73,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1012
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1012:
+.LC1010:
+movl $5,-20(%ebp)
+movl $2,-36(%ebp)
+movl -36(%ebp),%edi
+addl %edi,-20(%ebp)
+cmpl $7,-20(%ebp)
+je .LC1014
+movl $74,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1016
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1016:
+.LC1014:
+movl $5,-20(%ebp)
+movl $2,-40(%ebp)
+movl -20(%ebp),%edi
+movl -40(%ebp),%esi
+leal (%esi,%edi),%edi
+movl %edi,-20(%ebp)
+cmpl $7,-20(%ebp)
+je .LC1018
+movl $75,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1020
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1020:
+.LC1018:
+movl $5,-20(%ebp)
+flds .LC544
+fstps -56(%ebp)
+fildl -20(%ebp)
+fadds -56(%ebp)
+fistpl -20(%ebp)
+cmpl $7,-20(%ebp)
+je .LC1022
+movl $76,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1024
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1024:
+.LC1022:
+movl $5,-20(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+fildl -20(%ebp)
+faddl -64(%ebp)
+fistpl -20(%ebp)
+cmpl $7,-20(%ebp)
+je .LC1026
+movl $77,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1028
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1028:
+.LC1026:
+movl $5,-24(%ebp)
+movb $2,-25(%ebp)
+movsbl -25(%ebp),%edi
+add %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $7,%edi
+je .LC1030
+movl $78,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1032
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1032:
+.LC1030:
+movl $5,-24(%ebp)
+movw $2,-28(%ebp)
+movswl -28(%ebp),%edi
+add %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $7,%edi
+je .LC1034
+movl $79,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1036
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1036:
+.LC1034:
+movl $5,-24(%ebp)
+movl $2,-32(%ebp)
+movl -32(%ebp),%edi
+add %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $7,%edi
+je .LC1038
+movl $80,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1040
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1040:
+.LC1038:
+movl $5,-24(%ebp)
+movl $2,-36(%ebp)
+movl -36(%ebp),%edi
+add %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $7,%edi
+je .LC1042
+movl $81,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1044
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1044:
+.LC1042:
+movl $5,-24(%ebp)
+movl $2,-40(%ebp)
+movl -40(%ebp),%edi
+add %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $7,%edi
+je .LC1046
+movl $82,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1048
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1048:
+.LC1046:
+movl $5,-24(%ebp)
+flds .LC544
+fstps -56(%ebp)
+movl -24(%ebp),%edi
+fldl .LC611
+movl %edi,%esi
+shrl $1,%esi
+pushl %esi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+andl $1,%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+sub $4,%esp
+fstps (%esp)
+flds (%esp)
+addl $4,%esp
+fadds -56(%ebp)
+fstps -128(%ebp)
+flds .LC847
+fcomps -128(%ebp)
+fstsw %ax
+sahf
+ja .LC1051
+flds -128(%ebp)
+fsubs .LC847
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+leal 0x80000000(%edi),%edi
+movl %edi,-124(%ebp)
+jmp .LC1052
+.LC1051:
+flds -128(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,-124(%ebp)
+.LC1052:
+movl -124(%ebp),%edi
+movl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $7,%edi
+je .LC1053
+movl $83,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1055
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1055:
+.LC1053:
+movl $5,-24(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+movl -24(%ebp),%edi
+fldl .LC611
+movl %edi,%esi
+shrl $1,%esi
+pushl %esi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+andl $1,%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+faddl -64(%ebp)
+fstpl -144(%ebp)
+fldl .LC855
+fcompl -144(%ebp)
+fstsw %ax
+sahf
+ja .LC1058
+fldl -144(%ebp)
+fsubl .LC855
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+leal 0x80000000(%edi),%edi
+movl %edi,-136(%ebp)
+jmp .LC1059
+.LC1058:
+fldl -144(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,-136(%ebp)
+.LC1059:
+movl -136(%ebp),%edi
+movl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $7,%edi
+je .LC1060
+movl $84,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1062
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1062:
+.LC1060:
+flds .LC860
+fstps -44(%ebp)
+movb $2,-25(%ebp)
+flds -44(%ebp)
+movsbl -25(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+fstps -44(%ebp)
+flds .LC1066
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1064
+movl $85,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1067
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1067:
+.LC1064:
+flds .LC860
+fstps -44(%ebp)
+movw $2,-28(%ebp)
+flds -44(%ebp)
+movswl -28(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+fstps -44(%ebp)
+flds .LC1066
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1069
+movl $86,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1071
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1071:
+.LC1069:
+flds .LC860
+fstps -44(%ebp)
+movl $2,-32(%ebp)
+flds -44(%ebp)
+fildl -32(%ebp)
+faddp %st(1),%st
+fstps -44(%ebp)
+flds .LC1066
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1073
+movl $87,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1075
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1075:
+.LC1073:
+flds .LC860
+fstps -44(%ebp)
+movl $2,-36(%ebp)
+flds -44(%ebp)
+fildl -36(%ebp)
+faddp %st(1),%st
+fstps -44(%ebp)
+flds .LC1066
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1077
+movl $88,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1079
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1079:
+.LC1077:
+flds .LC860
+fstps -44(%ebp)
+movl $2,-40(%ebp)
+movl -40(%ebp),%edi
+flds -44(%ebp)
+fldl .LC611
+movl %edi,%esi
+shrl $1,%esi
+pushl %esi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+andl $1,%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+sub $4,%esp
+fstps (%esp)
+flds (%esp)
+addl $4,%esp
+faddp %st(1),%st
+fstps -44(%ebp)
+flds .LC1066
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1081
+movl $89,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1083
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1083:
+.LC1081:
+flds .LC860
+fstps -44(%ebp)
+flds .LC544
+fstps -56(%ebp)
+flds -44(%ebp)
+fadds -56(%ebp)
+fstps -44(%ebp)
+flds .LC1066
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1085
+movl $90,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1087
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1087:
+.LC1085:
+flds .LC860
+fstps -44(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+flds -44(%ebp)
+faddl -64(%ebp)
+fstps -44(%ebp)
+flds .LC1066
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1089
+movl $91,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1091
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1091:
+.LC1089:
+fldl .LC889
+fstpl -52(%ebp)
+movb $2,-25(%ebp)
+fldl -52(%ebp)
+movsbl -25(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+fstpl -52(%ebp)
+fldl .LC1095
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1093
+movl $92,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1096
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1096:
+.LC1093:
+fldl .LC889
+fstpl -52(%ebp)
+movw $2,-28(%ebp)
+fldl -52(%ebp)
+movswl -28(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+fstpl -52(%ebp)
+fldl .LC1095
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1098
+movl $93,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1100
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1100:
+.LC1098:
+fldl .LC889
+fstpl -52(%ebp)
+movl $2,-32(%ebp)
+fldl -52(%ebp)
+fiaddl -32(%ebp)
+fstpl -52(%ebp)
+fldl .LC1095
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1102
+movl $94,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1104
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1104:
+.LC1102:
+fldl .LC889
+fstpl -52(%ebp)
+movl $2,-36(%ebp)
+fldl -52(%ebp)
+fiaddl -36(%ebp)
+fstpl -52(%ebp)
+fldl .LC1095
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1106
+movl $95,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1108
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1108:
+.LC1106:
+fldl .LC889
+fstpl -52(%ebp)
+movl $2,-40(%ebp)
+movl -40(%ebp),%edi
+fldl -52(%ebp)
+fldl .LC611
+movl %edi,%esi
+shrl $1,%esi
+pushl %esi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+andl $1,%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+faddp %st(1),%st
+fstpl -52(%ebp)
+fldl .LC1095
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1110
+movl $96,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1112
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1112:
+.LC1110:
+fldl .LC889
+fstpl -52(%ebp)
+flds .LC544
+fstps -56(%ebp)
+fldl -52(%ebp)
+fadds -56(%ebp)
+fstpl -52(%ebp)
+fldl .LC1095
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1114
+movl $97,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1116
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1116:
+.LC1114:
+fldl .LC889
+fstpl -52(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+fldl -52(%ebp)
+faddl -64(%ebp)
+fstpl -52(%ebp)
+fldl .LC1095
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1118
+movl $98,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1120
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1120:
+.LC1118:
+movb $5,-9(%ebp)
+movb $2,-25(%ebp)
+movsbl -9(%ebp),%edi
+movsbl -25(%ebp),%esi
+subl %esi,%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $3,%edi
+je .LC1122
+movl $99,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1124
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1124:
+.LC1122:
+movb $5,-9(%ebp)
+movw $2,-28(%ebp)
+movsbl -9(%ebp),%edi
+movswl -28(%ebp),%esi
+subl %esi,%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $3,%edi
+je .LC1126
+movl $100,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1128
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1128:
+.LC1126:
+movb $5,-9(%ebp)
+movl $2,-32(%ebp)
+movsbl -9(%ebp),%edi
+subl -32(%ebp),%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $3,%edi
+je .LC1130
+movl $101,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1132
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1132:
+.LC1130:
+movb $5,-9(%ebp)
+movl $2,-36(%ebp)
+movsbl -9(%ebp),%edi
+subl -36(%ebp),%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $3,%edi
+je .LC1134
+movl $102,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1136
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1136:
+.LC1134:
+movb $5,-9(%ebp)
+movl $2,-40(%ebp)
+movsbl -9(%ebp),%edi
+subl -40(%ebp),%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $3,%edi
+je .LC1138
+movl $103,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1140
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1140:
+.LC1138:
+movb $5,-9(%ebp)
+flds .LC544
+fstps -56(%ebp)
+movsbl -9(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fsubs -56(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $3,%edi
+je .LC1142
+movl $104,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1144
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1144:
+.LC1142:
+movb $5,-9(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+movsbl -9(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fsubl -64(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $3,%edi
+je .LC1146
+movl $105,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1148
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1148:
+.LC1146:
+movw $5,-12(%ebp)
+movb $2,-25(%ebp)
+movswl -12(%ebp),%edi
+movsbl -25(%ebp),%esi
+subl %esi,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $3,%edi
+je .LC1150
+movl $106,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1152
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1152:
+.LC1150:
+movw $5,-12(%ebp)
+movw $2,-28(%ebp)
+movswl -12(%ebp),%edi
+movswl -28(%ebp),%esi
+subl %esi,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $3,%edi
+je .LC1154
+movl $107,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1156
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1156:
+.LC1154:
+movw $5,-12(%ebp)
+movl $2,-32(%ebp)
+movswl -12(%ebp),%edi
+subl -32(%ebp),%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $3,%edi
+je .LC1158
+movl $108,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1160
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1160:
+.LC1158:
+movw $5,-12(%ebp)
+movl $2,-36(%ebp)
+movswl -12(%ebp),%edi
+subl -36(%ebp),%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $3,%edi
+je .LC1162
+movl $109,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1164
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1164:
+.LC1162:
+movw $5,-12(%ebp)
+movl $2,-40(%ebp)
+movswl -12(%ebp),%edi
+subl -40(%ebp),%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $3,%edi
+je .LC1166
+movl $110,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1168
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1168:
+.LC1166:
+movw $5,-12(%ebp)
+flds .LC544
+fstps -56(%ebp)
+movswl -12(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fsubs -56(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $3,%edi
+je .LC1170
+movl $111,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1172
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1172:
+.LC1170:
+movw $5,-12(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+movswl -12(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fsubl -64(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $3,%edi
+je .LC1174
+movl $112,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1176
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1176:
+.LC1174:
+movl $5,-16(%ebp)
+movb $2,-25(%ebp)
+movsbl -25(%ebp),%edi
+sub %edi,-16(%ebp)
+cmpl $3,-16(%ebp)
+je .LC1178
+movl $113,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1180
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1180:
+.LC1178:
+movl $5,-16(%ebp)
+movw $2,-28(%ebp)
+movswl -28(%ebp),%edi
+sub %edi,-16(%ebp)
+cmpl $3,-16(%ebp)
+je .LC1182
+movl $114,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1184
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1184:
+.LC1182:
+movl $5,-16(%ebp)
+movl $2,-32(%ebp)
+movl -32(%ebp),%edi
+sub %edi,-16(%ebp)
+cmpl $3,-16(%ebp)
+je .LC1186
+movl $115,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1188
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1188:
+.LC1186:
+movl $5,-16(%ebp)
+movl $2,-36(%ebp)
+movl -36(%ebp),%edi
+sub %edi,-16(%ebp)
+cmpl $3,-16(%ebp)
+je .LC1190
+movl $116,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1192
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1192:
+.LC1190:
+movl $5,-16(%ebp)
+movl $2,-40(%ebp)
+movl -16(%ebp),%edi
+subl -40(%ebp),%edi
+movl %edi,-16(%ebp)
+cmpl $3,-16(%ebp)
+je .LC1194
+movl $117,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1196
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1196:
+.LC1194:
+movl $5,-16(%ebp)
+flds .LC544
+fstps -56(%ebp)
+fildl -16(%ebp)
+fsubs -56(%ebp)
+fistpl -16(%ebp)
+cmpl $3,-16(%ebp)
+je .LC1198
+movl $118,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1200
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1200:
+.LC1198:
+movl $5,-16(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+fldl -64(%ebp)
+fisubrl -16(%ebp)
+fistpl -16(%ebp)
+cmpl $3,-16(%ebp)
+je .LC1202
+movl $119,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1204
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1204:
+.LC1202:
+movl $5,-20(%ebp)
+movb $2,-25(%ebp)
+movsbl -25(%ebp),%edi
+sub %edi,-20(%ebp)
+cmpl $3,-20(%ebp)
+je .LC1206
+movl $120,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1208
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1208:
+.LC1206:
+movl $5,-20(%ebp)
+movw $2,-28(%ebp)
+movswl -28(%ebp),%edi
+sub %edi,-20(%ebp)
+cmpl $3,-20(%ebp)
+je .LC1210
+movl $121,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1212
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1212:
+.LC1210:
+movl $5,-20(%ebp)
+movl $2,-32(%ebp)
+movl -32(%ebp),%edi
+sub %edi,-20(%ebp)
+cmpl $3,-20(%ebp)
+je .LC1214
+movl $122,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1216
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1216:
+.LC1214:
+movl $5,-20(%ebp)
+movl $2,-36(%ebp)
+movl -36(%ebp),%edi
+sub %edi,-20(%ebp)
+cmpl $3,-20(%ebp)
+je .LC1218
+movl $123,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1220
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1220:
+.LC1218:
+movl $5,-20(%ebp)
+movl $2,-40(%ebp)
+movl -20(%ebp),%edi
+subl -40(%ebp),%edi
+movl %edi,-20(%ebp)
+cmpl $3,-20(%ebp)
+je .LC1222
+movl $124,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1224
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1224:
+.LC1222:
+movl $5,-20(%ebp)
+flds .LC544
+fstps -56(%ebp)
+fildl -20(%ebp)
+fsubs -56(%ebp)
+fistpl -20(%ebp)
+cmpl $3,-20(%ebp)
+je .LC1226
+movl $125,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1228
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1228:
+.LC1226:
+movl $5,-20(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+fldl -64(%ebp)
+fisubrl -20(%ebp)
+fistpl -20(%ebp)
+cmpl $3,-20(%ebp)
+je .LC1230
+movl $126,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1232
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1232:
+.LC1230:
+movl $5,-24(%ebp)
+movb $2,-25(%ebp)
+movsbl -25(%ebp),%edi
+sub %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $3,%edi
+je .LC1234
+movl $127,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1236
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1236:
+.LC1234:
+movl $5,-24(%ebp)
+movw $2,-28(%ebp)
+movswl -28(%ebp),%edi
+sub %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $3,%edi
+je .LC1238
+movl $128,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1240
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1240:
+.LC1238:
+movl $5,-24(%ebp)
+movl $2,-32(%ebp)
+movl -32(%ebp),%edi
+sub %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $3,%edi
+je .LC1242
+movl $129,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1244
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1244:
+.LC1242:
+movl $5,-24(%ebp)
+movl $2,-36(%ebp)
+movl -36(%ebp),%edi
+sub %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $3,%edi
+je .LC1246
+movl $130,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1248
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1248:
+.LC1246:
+movl $5,-24(%ebp)
+movl $2,-40(%ebp)
+movl -40(%ebp),%edi
+sub %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $3,%edi
+je .LC1250
+movl $131,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1252
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1252:
+.LC1250:
+movl $5,-24(%ebp)
+flds .LC544
+fstps -56(%ebp)
+movl -24(%ebp),%edi
+fldl .LC611
+movl %edi,%esi
+shrl $1,%esi
+pushl %esi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+andl $1,%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+sub $4,%esp
+fstps (%esp)
+flds (%esp)
+addl $4,%esp
+fsubs -56(%ebp)
+fstps -160(%ebp)
+flds .LC847
+fcomps -160(%ebp)
+fstsw %ax
+sahf
+ja .LC1255
+flds -160(%ebp)
+fsubs .LC847
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+leal 0x80000000(%edi),%edi
+movl %edi,-156(%ebp)
+jmp .LC1256
+.LC1255:
+flds -160(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,-156(%ebp)
+.LC1256:
+movl -156(%ebp),%edi
+movl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $3,%edi
+je .LC1257
+movl $132,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1259
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1259:
+.LC1257:
+movl $5,-24(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+movl -24(%ebp),%edi
+fldl .LC611
+movl %edi,%esi
+shrl $1,%esi
+pushl %esi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+andl $1,%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+fsubl -64(%ebp)
+fstpl -176(%ebp)
+fldl .LC855
+fcompl -176(%ebp)
+fstsw %ax
+sahf
+ja .LC1262
+fldl -176(%ebp)
+fsubl .LC855
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+leal 0x80000000(%edi),%edi
+movl %edi,-168(%ebp)
+jmp .LC1263
+.LC1262:
+fldl -176(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,-168(%ebp)
+.LC1263:
+movl -168(%ebp),%edi
+movl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $3,%edi
+je .LC1264
+movl $133,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1266
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1266:
+.LC1264:
+flds .LC860
+fstps -44(%ebp)
+movb $2,-25(%ebp)
+flds -44(%ebp)
+movsbl -25(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fsubp %st(1),%st
+fstps -44(%ebp)
+flds .LC1270
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1268
+movl $134,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1271
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1271:
+.LC1268:
+flds .LC860
+fstps -44(%ebp)
+movw $2,-28(%ebp)
+flds -44(%ebp)
+movswl -28(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fsubp %st(1),%st
+fstps -44(%ebp)
+flds .LC1270
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1273
+movl $135,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1275
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1275:
+.LC1273:
+flds .LC860
+fstps -44(%ebp)
+movl $2,-32(%ebp)
+flds -44(%ebp)
+fildl -32(%ebp)
+fsubp %st(1),%st
+fstps -44(%ebp)
+flds .LC1270
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1277
+movl $136,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1279
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1279:
+.LC1277:
+flds .LC860
+fstps -44(%ebp)
+movl $2,-36(%ebp)
+flds -44(%ebp)
+fildl -36(%ebp)
+fsubp %st(1),%st
+fstps -44(%ebp)
+flds .LC1270
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1281
+movl $137,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1283
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1283:
+.LC1281:
+flds .LC860
+fstps -44(%ebp)
+movl $2,-40(%ebp)
+movl -40(%ebp),%edi
+flds -44(%ebp)
+fldl .LC611
+movl %edi,%esi
+shrl $1,%esi
+pushl %esi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+andl $1,%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+sub $4,%esp
+fstps (%esp)
+flds (%esp)
+addl $4,%esp
+fsubp %st(1),%st
+fstps -44(%ebp)
+flds .LC1270
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1285
+movl $138,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1287
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1287:
+.LC1285:
+flds .LC860
+fstps -44(%ebp)
+flds .LC544
+fstps -56(%ebp)
+flds -44(%ebp)
+fsubs -56(%ebp)
+fstps -44(%ebp)
+flds .LC1270
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1289
+movl $139,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1291
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1291:
+.LC1289:
+flds .LC860
+fstps -44(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+flds -44(%ebp)
+fsubl -64(%ebp)
+fstps -44(%ebp)
+flds .LC1270
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1293
+movl $140,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1295
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1295:
+.LC1293:
+fldl .LC889
+fstpl -52(%ebp)
+movb $2,-25(%ebp)
+fldl -52(%ebp)
+movsbl -25(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fsubp %st(1),%st
+fstpl -52(%ebp)
+fldl .LC1299
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1297
+movl $141,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1300
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1300:
+.LC1297:
+fldl .LC889
+fstpl -52(%ebp)
+movw $2,-28(%ebp)
+fldl -52(%ebp)
+movswl -28(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fsubp %st(1),%st
+fstpl -52(%ebp)
+fldl .LC1299
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1302
+movl $142,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1304
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1304:
+.LC1302:
+fldl .LC889
+fstpl -52(%ebp)
+movl $2,-32(%ebp)
+fldl -52(%ebp)
+fisubl -32(%ebp)
+fstpl -52(%ebp)
+fldl .LC1299
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1306
+movl $143,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1308
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1308:
+.LC1306:
+fldl .LC889
+fstpl -52(%ebp)
+movl $2,-36(%ebp)
+fldl -52(%ebp)
+fisubl -36(%ebp)
+fstpl -52(%ebp)
+fldl .LC1299
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1310
+movl $144,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1312
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1312:
+.LC1310:
+fldl .LC889
+fstpl -52(%ebp)
+movl $2,-40(%ebp)
+movl -40(%ebp),%edi
+fldl -52(%ebp)
+fldl .LC611
+movl %edi,%esi
+shrl $1,%esi
+pushl %esi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+andl $1,%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+fsubp %st(1),%st
+fstpl -52(%ebp)
+fldl .LC1299
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1314
+movl $145,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1316
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1316:
+.LC1314:
+fldl .LC889
+fstpl -52(%ebp)
+flds .LC544
+fstps -56(%ebp)
+fldl -52(%ebp)
+fsubs -56(%ebp)
+fstpl -52(%ebp)
+fldl .LC1299
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1318
+movl $146,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1320
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1320:
+.LC1318:
+fldl .LC889
+fstpl -52(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+fldl -52(%ebp)
+fsubl -64(%ebp)
+fstpl -52(%ebp)
+fldl .LC1299
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1322
+movl $147,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1324
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1324:
+.LC1322:
+movb $5,-9(%ebp)
+movb $2,-25(%ebp)
+movsbl -9(%ebp),%edi
+movsbl -25(%ebp),%esi
+imull %esi,%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $10,%edi
+je .LC1326
+movl $148,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1328
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1328:
+.LC1326:
+movb $5,-9(%ebp)
+movw $2,-28(%ebp)
+movsbl -9(%ebp),%edi
+movswl -28(%ebp),%esi
+imull %esi,%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $10,%edi
+je .LC1330
+movl $149,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1332
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1332:
+.LC1330:
+movb $5,-9(%ebp)
+movl $2,-32(%ebp)
+movsbl -9(%ebp),%edi
+imull -32(%ebp),%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $10,%edi
+je .LC1334
+movl $150,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1336
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1336:
+.LC1334:
+movb $5,-9(%ebp)
+movl $2,-36(%ebp)
+movsbl -9(%ebp),%edi
+imull -36(%ebp),%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $10,%edi
+je .LC1338
+movl $151,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1340
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1340:
+.LC1338:
+movb $5,-9(%ebp)
+movl $2,-40(%ebp)
+movsbl -9(%ebp),%edi
+movl %edi,%eax
+mull -40(%ebp)
+movl %eax,%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $10,%edi
+je .LC1342
+movl $152,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1344
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1344:
+.LC1342:
+movb $5,-9(%ebp)
+flds .LC544
+fstps -56(%ebp)
+movsbl -9(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fmuls -56(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $10,%edi
+je .LC1346
+movl $153,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1348
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1348:
+.LC1346:
+movb $5,-9(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+movsbl -9(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fmull -64(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $10,%edi
+je .LC1350
+movl $154,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1352
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1352:
+.LC1350:
+movw $5,-12(%ebp)
+movb $2,-25(%ebp)
+movswl -12(%ebp),%edi
+movsbl -25(%ebp),%esi
+imull %esi,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $10,%edi
+je .LC1354
+movl $155,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1356
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1356:
+.LC1354:
+movw $5,-12(%ebp)
+movw $2,-28(%ebp)
+movswl -12(%ebp),%edi
+movswl -28(%ebp),%esi
+imull %esi,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $10,%edi
+je .LC1358
+movl $156,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1360
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1360:
+.LC1358:
+movw $5,-12(%ebp)
+movl $2,-32(%ebp)
+movswl -12(%ebp),%edi
+imull -32(%ebp),%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $10,%edi
+je .LC1362
+movl $157,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1364
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1364:
+.LC1362:
+movw $5,-12(%ebp)
+movl $2,-36(%ebp)
+movswl -12(%ebp),%edi
+imull -36(%ebp),%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $10,%edi
+je .LC1366
+movl $158,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1368
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1368:
+.LC1366:
+movw $5,-12(%ebp)
+movl $2,-40(%ebp)
+movswl -12(%ebp),%edi
+movl %edi,%eax
+mull -40(%ebp)
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $10,%edi
+je .LC1370
+movl $159,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1372
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1372:
+.LC1370:
+movw $5,-12(%ebp)
+flds .LC544
+fstps -56(%ebp)
+movswl -12(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fmuls -56(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $10,%edi
+je .LC1374
+movl $160,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1376
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1376:
+.LC1374:
+movw $5,-12(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+movswl -12(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fmull -64(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $10,%edi
+je .LC1378
+movl $161,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1380
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1380:
+.LC1378:
+movl $5,-16(%ebp)
+movb $2,-25(%ebp)
+movl -16(%ebp),%edi
+movsbl -25(%ebp),%esi
+imull %esi,%edi
+movl %edi,-16(%ebp)
+cmpl $10,-16(%ebp)
+je .LC1382
+movl $162,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1384
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1384:
+.LC1382:
+movl $5,-16(%ebp)
+movw $2,-28(%ebp)
+movl -16(%ebp),%edi
+movswl -28(%ebp),%esi
+imull %esi,%edi
+movl %edi,-16(%ebp)
+cmpl $10,-16(%ebp)
+je .LC1386
+movl $163,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1388
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1388:
+.LC1386:
+movl $5,-16(%ebp)
+movl $2,-32(%ebp)
+movl -16(%ebp),%edi
+imull -32(%ebp),%edi
+movl %edi,-16(%ebp)
+cmpl $10,-16(%ebp)
+je .LC1390
+movl $164,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1392
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1392:
+.LC1390:
+movl $5,-16(%ebp)
+movl $2,-36(%ebp)
+movl -16(%ebp),%edi
+imull -36(%ebp),%edi
+movl %edi,-16(%ebp)
+cmpl $10,-16(%ebp)
+je .LC1394
+movl $165,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1396
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1396:
+.LC1394:
+movl $5,-16(%ebp)
+movl $2,-40(%ebp)
+movl -16(%ebp),%edi
+movl %edi,%eax
+mull -40(%ebp)
+movl %eax,%edi
+movl %edi,-16(%ebp)
+cmpl $10,-16(%ebp)
+je .LC1398
+movl $166,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1400
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1400:
+.LC1398:
+movl $5,-16(%ebp)
+flds .LC544
+fstps -56(%ebp)
+fildl -16(%ebp)
+fmuls -56(%ebp)
+fistpl -16(%ebp)
+cmpl $10,-16(%ebp)
+je .LC1402
+movl $167,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1404
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1404:
+.LC1402:
+movl $5,-16(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+fildl -16(%ebp)
+fmull -64(%ebp)
+fistpl -16(%ebp)
+cmpl $10,-16(%ebp)
+je .LC1406
+movl $168,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1408
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1408:
+.LC1406:
+movl $5,-20(%ebp)
+movb $2,-25(%ebp)
+movl -20(%ebp),%edi
+movsbl -25(%ebp),%esi
+imull %esi,%edi
+movl %edi,-20(%ebp)
+cmpl $10,-20(%ebp)
+je .LC1410
+movl $169,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1412
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1412:
+.LC1410:
+movl $5,-20(%ebp)
+movw $2,-28(%ebp)
+movl -20(%ebp),%edi
+movswl -28(%ebp),%esi
+imull %esi,%edi
+movl %edi,-20(%ebp)
+cmpl $10,-20(%ebp)
+je .LC1414
+movl $170,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1416
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1416:
+.LC1414:
+movl $5,-20(%ebp)
+movl $2,-32(%ebp)
+movl -20(%ebp),%edi
+imull -32(%ebp),%edi
+movl %edi,-20(%ebp)
+cmpl $10,-20(%ebp)
+je .LC1418
+movl $171,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1420
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1420:
+.LC1418:
+movl $5,-20(%ebp)
+movl $2,-36(%ebp)
+movl -20(%ebp),%edi
+imull -36(%ebp),%edi
+movl %edi,-20(%ebp)
+cmpl $10,-20(%ebp)
+je .LC1422
+movl $172,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1424
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1424:
+.LC1422:
+movl $5,-20(%ebp)
+movl $2,-40(%ebp)
+movl -20(%ebp),%edi
+movl %edi,%eax
+mull -40(%ebp)
+movl %eax,%edi
+movl %edi,-20(%ebp)
+cmpl $10,-20(%ebp)
+je .LC1426
+movl $173,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1428
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1428:
+.LC1426:
+movl $5,-20(%ebp)
+flds .LC544
+fstps -56(%ebp)
+fildl -20(%ebp)
+fmuls -56(%ebp)
+fistpl -20(%ebp)
+cmpl $10,-20(%ebp)
+je .LC1430
+movl $174,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1432
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1432:
+.LC1430:
+movl $5,-20(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+fildl -20(%ebp)
+fmull -64(%ebp)
+fistpl -20(%ebp)
+cmpl $10,-20(%ebp)
+je .LC1434
+movl $175,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1436
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1436:
+.LC1434:
+movl $5,-24(%ebp)
+movb $2,-25(%ebp)
+movl -24(%ebp),%eax
+movsbl -25(%ebp),%edi
+mull %edi
+movl %eax,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $10,%edi
+je .LC1438
+movl $176,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1440
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1440:
+.LC1438:
+movl $5,-24(%ebp)
+movw $2,-28(%ebp)
+movl -24(%ebp),%eax
+movswl -28(%ebp),%edi
+mull %edi
+movl %eax,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $10,%edi
+je .LC1442
+movl $177,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1444
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1444:
+.LC1442:
+movl $5,-24(%ebp)
+movl $2,-32(%ebp)
+movl -24(%ebp),%eax
+movl -32(%ebp),%edi
+mull %edi
+movl %eax,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $10,%edi
+je .LC1446
+movl $178,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1448
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1448:
+.LC1446:
+movl $5,-24(%ebp)
+movl $2,-36(%ebp)
+movl -24(%ebp),%eax
+movl -36(%ebp),%edi
+mull %edi
+movl %eax,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $10,%edi
+je .LC1450
+movl $179,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1452
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1452:
+.LC1450:
+movl $5,-24(%ebp)
+movl $2,-40(%ebp)
+movl -24(%ebp),%eax
+mull -40(%ebp)
+movl %eax,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $10,%edi
+je .LC1454
+movl $180,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1456
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1456:
+.LC1454:
+movl $5,-24(%ebp)
+flds .LC544
+fstps -56(%ebp)
+movl -24(%ebp),%edi
+fldl .LC611
+movl %edi,%esi
+shrl $1,%esi
+pushl %esi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+andl $1,%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+sub $4,%esp
+fstps (%esp)
+flds (%esp)
+addl $4,%esp
+fmuls -56(%ebp)
+fstps -192(%ebp)
+flds .LC847
+fcomps -192(%ebp)
+fstsw %ax
+sahf
+ja .LC1459
+flds -192(%ebp)
+fsubs .LC847
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+leal 0x80000000(%edi),%edi
+movl %edi,-188(%ebp)
+jmp .LC1460
+.LC1459:
+flds -192(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,-188(%ebp)
+.LC1460:
+movl -188(%ebp),%edi
+movl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $10,%edi
+je .LC1461
+movl $181,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1463
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1463:
+.LC1461:
+movl $5,-24(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+movl -24(%ebp),%edi
+fldl .LC611
+movl %edi,%esi
+shrl $1,%esi
+pushl %esi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+andl $1,%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+fmull -64(%ebp)
+fstpl -208(%ebp)
+fldl .LC855
+fcompl -208(%ebp)
+fstsw %ax
+sahf
+ja .LC1466
+fldl -208(%ebp)
+fsubl .LC855
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+leal 0x80000000(%edi),%edi
+movl %edi,-200(%ebp)
+jmp .LC1467
+.LC1466:
+fldl -208(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,-200(%ebp)
+.LC1467:
+movl -200(%ebp),%edi
+movl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $10,%edi
+je .LC1468
+movl $182,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1470
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1470:
+.LC1468:
+flds .LC860
+fstps -44(%ebp)
+movb $2,-25(%ebp)
+flds -44(%ebp)
+movsbl -25(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+fstps -44(%ebp)
+flds .LC1474
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1472
+movl $183,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1475
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1475:
+.LC1472:
+flds .LC860
+fstps -44(%ebp)
+movw $2,-28(%ebp)
+flds -44(%ebp)
+movswl -28(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+fstps -44(%ebp)
+flds .LC1474
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1477
+movl $184,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1479
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1479:
+.LC1477:
+flds .LC860
+fstps -44(%ebp)
+movl $2,-32(%ebp)
+flds -44(%ebp)
+fildl -32(%ebp)
+fmulp %st(1),%st
+fstps -44(%ebp)
+flds .LC1474
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1481
+movl $185,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1483
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1483:
+.LC1481:
+flds .LC860
+fstps -44(%ebp)
+movl $2,-36(%ebp)
+flds -44(%ebp)
+fildl -36(%ebp)
+fmulp %st(1),%st
+fstps -44(%ebp)
+flds .LC1474
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1485
+movl $186,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1487
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1487:
+.LC1485:
+flds .LC860
+fstps -44(%ebp)
+movl $2,-40(%ebp)
+movl -40(%ebp),%edi
+flds -44(%ebp)
+fldl .LC611
+movl %edi,%esi
+shrl $1,%esi
+pushl %esi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+andl $1,%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+sub $4,%esp
+fstps (%esp)
+flds (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+fstps -44(%ebp)
+flds .LC1474
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1489
+movl $187,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1491
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1491:
+.LC1489:
+flds .LC860
+fstps -44(%ebp)
+flds .LC544
+fstps -56(%ebp)
+flds -44(%ebp)
+fmuls -56(%ebp)
+fstps -44(%ebp)
+flds .LC1474
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1493
+movl $188,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1495
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1495:
+.LC1493:
+flds .LC860
+fstps -44(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+flds -44(%ebp)
+fmull -64(%ebp)
+fstps -44(%ebp)
+flds .LC1474
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1497
+movl $189,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1499
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1499:
+.LC1497:
+fldl .LC889
+fstpl -52(%ebp)
+movb $2,-25(%ebp)
+fldl -52(%ebp)
+movsbl -25(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+fstpl -52(%ebp)
+fldl .LC1503
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1501
+movl $190,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1504
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1504:
+.LC1501:
+fldl .LC889
+fstpl -52(%ebp)
+movw $2,-28(%ebp)
+fldl -52(%ebp)
+movswl -28(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+fstpl -52(%ebp)
+fldl .LC1503
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1506
+movl $191,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1508
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1508:
+.LC1506:
+fldl .LC889
+fstpl -52(%ebp)
+movl $2,-32(%ebp)
+fldl -52(%ebp)
+fimull -32(%ebp)
+fstpl -52(%ebp)
+fldl .LC1503
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1510
+movl $192,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1512
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1512:
+.LC1510:
+fldl .LC889
+fstpl -52(%ebp)
+movl $2,-36(%ebp)
+fldl -52(%ebp)
+fimull -36(%ebp)
+fstpl -52(%ebp)
+fldl .LC1503
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1514
+movl $193,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1516
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1516:
+.LC1514:
+fldl .LC889
+fstpl -52(%ebp)
+movl $2,-40(%ebp)
+movl -40(%ebp),%edi
+fldl -52(%ebp)
+fldl .LC611
+movl %edi,%esi
+shrl $1,%esi
+pushl %esi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+andl $1,%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+fmulp %st(1),%st
+fstpl -52(%ebp)
+fldl .LC1503
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1518
+movl $194,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1520
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1520:
+.LC1518:
+fldl .LC889
+fstpl -52(%ebp)
+flds .LC544
+fstps -56(%ebp)
+fldl -52(%ebp)
+fmuls -56(%ebp)
+fstpl -52(%ebp)
+fldl .LC1503
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1522
+movl $195,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1524
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1524:
+.LC1522:
+fldl .LC889
+fstpl -52(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+fldl -52(%ebp)
+fmull -64(%ebp)
+fstpl -52(%ebp)
+fldl .LC1503
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1526
+movl $196,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1528
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1528:
+.LC1526:
+movb $5,-9(%ebp)
+movb $2,-25(%ebp)
+movsbl -9(%ebp),%eax
+movsbl -25(%ebp),%ecx
+cdq
+idivl %ecx
+movl %eax,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $2,%edi
+je .LC1530
+movl $197,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1532
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1532:
+.LC1530:
+movb $5,-9(%ebp)
+movw $2,-28(%ebp)
+movsbl -9(%ebp),%eax
+movswl -28(%ebp),%ecx
+cdq
+idivl %ecx
+movl %eax,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $2,%edi
+je .LC1534
+movl $198,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1536
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1536:
+.LC1534:
+movb $5,-9(%ebp)
+movl $2,-32(%ebp)
+movsbl -9(%ebp),%eax
+movl -32(%ebp),%ecx
+cdq
+idivl %ecx
+movl %eax,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $2,%edi
+je .LC1538
+movl $199,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1540
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1540:
+.LC1538:
+movb $5,-9(%ebp)
+movl $2,-36(%ebp)
+movsbl -9(%ebp),%eax
+movl -36(%ebp),%ecx
+cdq
+idivl %ecx
+movl %eax,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $2,%edi
+je .LC1542
+movl $200,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1544
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1544:
+.LC1542:
+movb $5,-9(%ebp)
+movl $2,-40(%ebp)
+movsbl -9(%ebp),%edi
+movl %edi,%eax
+movl -40(%ebp),%ecx
+xorl %edx,%edx
+divl %ecx
+movl %eax,%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $2,%edi
+je .LC1546
+movl $201,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1548
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1548:
+.LC1546:
+movb $5,-9(%ebp)
+flds .LC544
+fstps -56(%ebp)
+movsbl -9(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fdivs -56(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $2,%edi
+je .LC1550
+movl $202,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1552
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1552:
+.LC1550:
+movb $5,-9(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+movsbl -9(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fdivl -64(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $2,%edi
+je .LC1554
+movl $203,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1556
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1556:
+.LC1554:
+movw $5,-12(%ebp)
+movb $2,-25(%ebp)
+movswl -12(%ebp),%eax
+movsbl -25(%ebp),%ecx
+cdq
+idivl %ecx
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $2,%edi
+je .LC1558
+movl $204,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1560
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1560:
+.LC1558:
+movw $5,-12(%ebp)
+movw $2,-28(%ebp)
+movswl -12(%ebp),%eax
+movswl -28(%ebp),%ecx
+cdq
+idivl %ecx
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $2,%edi
+je .LC1562
+movl $205,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1564
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1564:
+.LC1562:
+movw $5,-12(%ebp)
+movl $2,-32(%ebp)
+movswl -12(%ebp),%eax
+movl -32(%ebp),%ecx
+cdq
+idivl %ecx
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $2,%edi
+je .LC1566
+movl $206,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1568
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1568:
+.LC1566:
+movw $5,-12(%ebp)
+movl $2,-36(%ebp)
+movswl -12(%ebp),%eax
+movl -36(%ebp),%ecx
+cdq
+idivl %ecx
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $2,%edi
+je .LC1570
+movl $207,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1572
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1572:
+.LC1570:
+movw $5,-12(%ebp)
+movl $2,-40(%ebp)
+movswl -12(%ebp),%edi
+movl %edi,%eax
+movl -40(%ebp),%ecx
+xorl %edx,%edx
+divl %ecx
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $2,%edi
+je .LC1574
+movl $208,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1576
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1576:
+.LC1574:
+movw $5,-12(%ebp)
+flds .LC544
+fstps -56(%ebp)
+movswl -12(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fdivs -56(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $2,%edi
+je .LC1578
+movl $209,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1580
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1580:
+.LC1578:
+movw $5,-12(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+movswl -12(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fdivl -64(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $2,%edi
+je .LC1582
+movl $210,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1584
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1584:
+.LC1582:
+movl $5,-16(%ebp)
+movb $2,-25(%ebp)
+movl -16(%ebp),%eax
+movsbl -25(%ebp),%ecx
+cdq
+idivl %ecx
+movl %eax,-16(%ebp)
+cmpl $2,-16(%ebp)
+je .LC1586
+movl $211,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1588
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1588:
+.LC1586:
+movl $5,-16(%ebp)
+movw $2,-28(%ebp)
+movl -16(%ebp),%eax
+movswl -28(%ebp),%ecx
+cdq
+idivl %ecx
+movl %eax,-16(%ebp)
+cmpl $2,-16(%ebp)
+je .LC1590
+movl $212,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1592
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1592:
+.LC1590:
+movl $5,-16(%ebp)
+movl $2,-32(%ebp)
+movl -16(%ebp),%eax
+movl -32(%ebp),%ecx
+cdq
+idivl %ecx
+movl %eax,-16(%ebp)
+cmpl $2,-16(%ebp)
+je .LC1594
+movl $213,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1596
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1596:
+.LC1594:
+movl $5,-16(%ebp)
+movl $2,-36(%ebp)
+movl -16(%ebp),%eax
+movl -36(%ebp),%ecx
+cdq
+idivl %ecx
+movl %eax,-16(%ebp)
+cmpl $2,-16(%ebp)
+je .LC1598
+movl $214,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1600
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1600:
+.LC1598:
+movl $5,-16(%ebp)
+movl $2,-40(%ebp)
+movl -16(%ebp),%edi
+movl %edi,%eax
+movl -40(%ebp),%ecx
+xorl %edx,%edx
+divl %ecx
+movl %eax,%edi
+movl %edi,-16(%ebp)
+cmpl $2,-16(%ebp)
+je .LC1602
+movl $215,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1604
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1604:
+.LC1602:
+movl $5,-16(%ebp)
+flds .LC544
+fstps -56(%ebp)
+fildl -16(%ebp)
+fdivs -56(%ebp)
+fistpl -16(%ebp)
+cmpl $2,-16(%ebp)
+je .LC1606
+movl $216,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1608
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1608:
+.LC1606:
+movl $5,-16(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+fldl -64(%ebp)
+fidivrl -16(%ebp)
+fistpl -16(%ebp)
+cmpl $2,-16(%ebp)
+je .LC1610
+movl $217,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1612
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1612:
+.LC1610:
+movl $5,-20(%ebp)
+movb $2,-25(%ebp)
+movl -20(%ebp),%eax
+movsbl -25(%ebp),%ecx
+cdq
+idivl %ecx
+movl %eax,-20(%ebp)
+cmpl $2,-20(%ebp)
+je .LC1614
+movl $218,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1616
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1616:
+.LC1614:
+movl $5,-20(%ebp)
+movw $2,-28(%ebp)
+movl -20(%ebp),%eax
+movswl -28(%ebp),%ecx
+cdq
+idivl %ecx
+movl %eax,-20(%ebp)
+cmpl $2,-20(%ebp)
+je .LC1618
+movl $219,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1620
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1620:
+.LC1618:
+movl $5,-20(%ebp)
+movl $2,-32(%ebp)
+movl -20(%ebp),%eax
+movl -32(%ebp),%ecx
+cdq
+idivl %ecx
+movl %eax,-20(%ebp)
+cmpl $2,-20(%ebp)
+je .LC1622
+movl $220,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1624
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1624:
+.LC1622:
+movl $5,-20(%ebp)
+movl $2,-36(%ebp)
+movl -20(%ebp),%eax
+movl -36(%ebp),%ecx
+cdq
+idivl %ecx
+movl %eax,-20(%ebp)
+cmpl $2,-20(%ebp)
+je .LC1626
+movl $221,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1628
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1628:
+.LC1626:
+movl $5,-20(%ebp)
+movl $2,-40(%ebp)
+movl -20(%ebp),%edi
+movl %edi,%eax
+movl -40(%ebp),%ecx
+xorl %edx,%edx
+divl %ecx
+movl %eax,%edi
+movl %edi,-20(%ebp)
+cmpl $2,-20(%ebp)
+je .LC1630
+movl $222,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1632
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1632:
+.LC1630:
+movl $5,-20(%ebp)
+flds .LC544
+fstps -56(%ebp)
+fildl -20(%ebp)
+fdivs -56(%ebp)
+fistpl -20(%ebp)
+cmpl $2,-20(%ebp)
+je .LC1634
+movl $223,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1636
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1636:
+.LC1634:
+movl $5,-20(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+fldl -64(%ebp)
+fidivrl -20(%ebp)
+fistpl -20(%ebp)
+cmpl $2,-20(%ebp)
+je .LC1638
+movl $224,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1640
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1640:
+.LC1638:
+movl $5,-24(%ebp)
+movb $2,-25(%ebp)
+movl -24(%ebp),%eax
+movsbl -25(%ebp),%edi
+movl %edi,%ecx
+xorl %edx,%edx
+divl %ecx
+movl %eax,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $2,%edi
+je .LC1642
+movl $225,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1644
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1644:
+.LC1642:
+movl $5,-24(%ebp)
+movw $2,-28(%ebp)
+movl -24(%ebp),%eax
+movswl -28(%ebp),%edi
+movl %edi,%ecx
+xorl %edx,%edx
+divl %ecx
+movl %eax,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $2,%edi
+je .LC1646
+movl $226,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1648
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1648:
+.LC1646:
+movl $5,-24(%ebp)
+movl $2,-32(%ebp)
+movl -24(%ebp),%eax
+movl -32(%ebp),%edi
+movl %edi,%ecx
+xorl %edx,%edx
+divl %ecx
+movl %eax,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $2,%edi
+je .LC1650
+movl $227,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1652
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1652:
+.LC1650:
+movl $5,-24(%ebp)
+movl $2,-36(%ebp)
+movl -24(%ebp),%eax
+movl -36(%ebp),%edi
+movl %edi,%ecx
+xorl %edx,%edx
+divl %ecx
+movl %eax,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $2,%edi
+je .LC1654
+movl $228,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1656
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1656:
+.LC1654:
+movl $5,-24(%ebp)
+movl $2,-40(%ebp)
+movl -24(%ebp),%eax
+movl -40(%ebp),%ecx
+xorl %edx,%edx
+divl %ecx
+movl %eax,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $2,%edi
+je .LC1658
+movl $229,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1660
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1660:
+.LC1658:
+movl $5,-24(%ebp)
+flds .LC544
+fstps -56(%ebp)
+movl -24(%ebp),%edi
+fldl .LC611
+movl %edi,%esi
+shrl $1,%esi
+pushl %esi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+andl $1,%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+sub $4,%esp
+fstps (%esp)
+flds (%esp)
+addl $4,%esp
+fdivs -56(%ebp)
+fstps -224(%ebp)
+flds .LC847
+fcomps -224(%ebp)
+fstsw %ax
+sahf
+ja .LC1663
+flds -224(%ebp)
+fsubs .LC847
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+leal 0x80000000(%edi),%edi
+movl %edi,-220(%ebp)
+jmp .LC1664
+.LC1663:
+flds -224(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,-220(%ebp)
+.LC1664:
+movl -220(%ebp),%edi
+movl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $2,%edi
+je .LC1665
+movl $230,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1667
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1667:
+.LC1665:
+movl $5,-24(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+movl -24(%ebp),%edi
+fldl .LC611
+movl %edi,%esi
+shrl $1,%esi
+pushl %esi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+andl $1,%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+fdivl -64(%ebp)
+fstpl -240(%ebp)
+fldl .LC855
+fcompl -240(%ebp)
+fstsw %ax
+sahf
+ja .LC1670
+fldl -240(%ebp)
+fsubl .LC855
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+leal 0x80000000(%edi),%edi
+movl %edi,-232(%ebp)
+jmp .LC1671
+.LC1670:
+fldl -240(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,-232(%ebp)
+.LC1671:
+movl -232(%ebp),%edi
+movl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $2,%edi
+je .LC1672
+movl $231,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1674
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1674:
+.LC1672:
+flds .LC860
+fstps -44(%ebp)
+movb $2,-25(%ebp)
+flds -44(%ebp)
+movsbl -25(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fdivp %st(1),%st
+fstps -44(%ebp)
+fldl .LC1678
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1676
+movl $232,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1679
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1679:
+.LC1676:
+flds .LC860
+fstps -44(%ebp)
+movw $2,-28(%ebp)
+flds -44(%ebp)
+movswl -28(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fdivp %st(1),%st
+fstps -44(%ebp)
+fldl .LC1678
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1681
+movl $233,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1683
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1683:
+.LC1681:
+flds .LC860
+fstps -44(%ebp)
+movl $2,-32(%ebp)
+flds -44(%ebp)
+fildl -32(%ebp)
+fdivp %st(1),%st
+fstps -44(%ebp)
+fldl .LC1678
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1685
+movl $234,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1687
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1687:
+.LC1685:
+flds .LC860
+fstps -44(%ebp)
+movl $2,-36(%ebp)
+flds -44(%ebp)
+fildl -36(%ebp)
+fdivp %st(1),%st
+fstps -44(%ebp)
+fldl .LC1678
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1689
+movl $235,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1691
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1691:
+.LC1689:
+flds .LC860
+fstps -44(%ebp)
+movl $2,-40(%ebp)
+movl -40(%ebp),%edi
+flds -44(%ebp)
+fldl .LC611
+movl %edi,%esi
+shrl $1,%esi
+pushl %esi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+andl $1,%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+sub $4,%esp
+fstps (%esp)
+flds (%esp)
+addl $4,%esp
+fdivp %st(1),%st
+fstps -44(%ebp)
+fldl .LC1678
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1693
+movl $236,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1695
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1695:
+.LC1693:
+flds .LC860
+fstps -44(%ebp)
+flds .LC544
+fstps -56(%ebp)
+flds -44(%ebp)
+fdivs -56(%ebp)
+fstps -44(%ebp)
+fldl .LC1678
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1697
+movl $237,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1699
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1699:
+.LC1697:
+flds .LC860
+fstps -44(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+flds -44(%ebp)
+fdivl -64(%ebp)
+fstps -44(%ebp)
+fldl .LC1678
+fcomps -44(%ebp)
+fstsw %ax
+sahf
+je .LC1701
+movl $238,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1703
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1703:
+.LC1701:
+fldl .LC889
+fstpl -52(%ebp)
+movb $2,-25(%ebp)
+fldl -52(%ebp)
+movsbl -25(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fdivp %st(1),%st
+fstpl -52(%ebp)
+fldl .LC1678
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1705
+movl $239,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1707
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1707:
+.LC1705:
+fldl .LC889
+fstpl -52(%ebp)
+movw $2,-28(%ebp)
+fldl -52(%ebp)
+movswl -28(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fdivp %st(1),%st
+fstpl -52(%ebp)
+fldl .LC1678
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1709
+movl $240,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1711
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1711:
+.LC1709:
+fldl .LC889
+fstpl -52(%ebp)
+movl $2,-32(%ebp)
+fldl -52(%ebp)
+fidivl -32(%ebp)
+fstpl -52(%ebp)
+fldl .LC1678
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1713
+movl $241,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1715
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1715:
+.LC1713:
+fldl .LC889
+fstpl -52(%ebp)
+movl $2,-36(%ebp)
+fldl -52(%ebp)
+fidivl -36(%ebp)
+fstpl -52(%ebp)
+fldl .LC1678
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1717
+movl $242,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1719
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1719:
+.LC1717:
+fldl .LC889
+fstpl -52(%ebp)
+movl $2,-40(%ebp)
+movl -40(%ebp),%edi
+fldl -52(%ebp)
+fldl .LC611
+movl %edi,%esi
+shrl $1,%esi
+pushl %esi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+andl $1,%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+fdivp %st(1),%st
+fstpl -52(%ebp)
+fldl .LC1678
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1721
+movl $243,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1723
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1723:
+.LC1721:
+fldl .LC889
+fstpl -52(%ebp)
+flds .LC544
+fstps -56(%ebp)
+fldl -52(%ebp)
+fdivs -56(%ebp)
+fstpl -52(%ebp)
+fldl .LC1678
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1725
+movl $244,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1727
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1727:
+.LC1725:
+fldl .LC889
+fstpl -52(%ebp)
+fldl .LC425
+fstpl -64(%ebp)
+fldl -52(%ebp)
+fdivl -64(%ebp)
+fstpl -52(%ebp)
+fldl .LC1678
+fcompl -52(%ebp)
+fstsw %ax
+sahf
+je .LC1729
+movl $245,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1731
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1731:
+.LC1729:
+movb $5,-9(%ebp)
+movb $2,-25(%ebp)
+movsbl -9(%ebp),%eax
+movsbl -25(%ebp),%ecx
+cdq
+idivl %ecx
+movl %edx,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $1,%edi
+je .LC1733
+movl $246,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1735
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1735:
+.LC1733:
+movb $5,-9(%ebp)
+movw $2,-28(%ebp)
+movsbl -9(%ebp),%eax
+movswl -28(%ebp),%ecx
+cdq
+idivl %ecx
+movl %edx,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $1,%edi
+je .LC1737
+movl $247,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1739
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1739:
+.LC1737:
+movb $5,-9(%ebp)
+movl $2,-32(%ebp)
+movsbl -9(%ebp),%eax
+movl -32(%ebp),%ecx
+cdq
+idivl %ecx
+movl %edx,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $1,%edi
+je .LC1741
+movl $248,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1743
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1743:
+.LC1741:
+movb $5,-9(%ebp)
+movl $2,-36(%ebp)
+movsbl -9(%ebp),%eax
+movl -36(%ebp),%ecx
+cdq
+idivl %ecx
+movl %edx,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $1,%edi
+je .LC1745
+movl $249,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1747
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1747:
+.LC1745:
+movb $5,-9(%ebp)
+movl $2,-40(%ebp)
+movsbl -9(%ebp),%edi
+movl %edi,%eax
+movl -40(%ebp),%ecx
+xorl %edx,%edx
+divl %ecx
+movl %edx,%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $1,%edi
+je .LC1749
+movl $250,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1751
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1751:
+.LC1749:
+movw $5,-12(%ebp)
+movb $2,-25(%ebp)
+movswl -12(%ebp),%eax
+movsbl -25(%ebp),%ecx
+cdq
+idivl %ecx
+movl %edx,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $1,%edi
+je .LC1753
+movl $251,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1755
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1755:
+.LC1753:
+movw $5,-12(%ebp)
+movw $2,-28(%ebp)
+movswl -12(%ebp),%eax
+movswl -28(%ebp),%ecx
+cdq
+idivl %ecx
+movl %edx,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $1,%edi
+je .LC1757
+movl $252,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1759
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1759:
+.LC1757:
+movw $5,-12(%ebp)
+movl $2,-32(%ebp)
+movswl -12(%ebp),%eax
+movl -32(%ebp),%ecx
+cdq
+idivl %ecx
+movl %edx,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $1,%edi
+je .LC1761
+movl $253,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1763
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1763:
+.LC1761:
+movw $5,-12(%ebp)
+movl $2,-36(%ebp)
+movswl -12(%ebp),%eax
+movl -36(%ebp),%ecx
+cdq
+idivl %ecx
+movl %edx,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $1,%edi
+je .LC1765
+movl $254,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1767
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1767:
+.LC1765:
+movw $5,-12(%ebp)
+movl $2,-40(%ebp)
+movswl -12(%ebp),%edi
+movl %edi,%eax
+movl -40(%ebp),%ecx
+xorl %edx,%edx
+divl %ecx
+movl %edx,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $1,%edi
+je .LC1769
+movl $255,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1771
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1771:
+.LC1769:
+movl $5,-16(%ebp)
+movb $2,-25(%ebp)
+movl -16(%ebp),%eax
+movsbl -25(%ebp),%ecx
+cdq
+idivl %ecx
+movl %edx,-16(%ebp)
+cmpl $1,-16(%ebp)
+je .LC1773
+movl $256,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1775
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1775:
+.LC1773:
+movl $5,-16(%ebp)
+movw $2,-28(%ebp)
+movl -16(%ebp),%eax
+movswl -28(%ebp),%ecx
+cdq
+idivl %ecx
+movl %edx,-16(%ebp)
+cmpl $1,-16(%ebp)
+je .LC1777
+movl $257,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1779
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1779:
+.LC1777:
+movl $5,-16(%ebp)
+movl $2,-32(%ebp)
+movl -16(%ebp),%eax
+movl -32(%ebp),%ecx
+cdq
+idivl %ecx
+movl %edx,-16(%ebp)
+cmpl $1,-16(%ebp)
+je .LC1781
+movl $258,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1783
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1783:
+.LC1781:
+movl $5,-16(%ebp)
+movl $2,-36(%ebp)
+movl -16(%ebp),%eax
+movl -36(%ebp),%ecx
+cdq
+idivl %ecx
+movl %edx,-16(%ebp)
+cmpl $1,-16(%ebp)
+je .LC1785
+movl $259,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1787
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1787:
+.LC1785:
+movl $5,-16(%ebp)
+movl $2,-40(%ebp)
+movl -16(%ebp),%edi
+movl %edi,%eax
+movl -40(%ebp),%ecx
+xorl %edx,%edx
+divl %ecx
+movl %edx,%edi
+movl %edi,-16(%ebp)
+cmpl $1,-16(%ebp)
+je .LC1789
+movl $260,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1791
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1791:
+.LC1789:
+movl $5,-20(%ebp)
+movb $2,-25(%ebp)
+movl -20(%ebp),%eax
+movsbl -25(%ebp),%ecx
+cdq
+idivl %ecx
+movl %edx,-20(%ebp)
+cmpl $1,-20(%ebp)
+je .LC1793
+movl $261,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1795
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1795:
+.LC1793:
+movl $5,-20(%ebp)
+movw $2,-28(%ebp)
+movl -20(%ebp),%eax
+movswl -28(%ebp),%ecx
+cdq
+idivl %ecx
+movl %edx,-20(%ebp)
+cmpl $1,-20(%ebp)
+je .LC1797
+movl $262,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1799
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1799:
+.LC1797:
+movl $5,-20(%ebp)
+movl $2,-32(%ebp)
+movl -20(%ebp),%eax
+movl -32(%ebp),%ecx
+cdq
+idivl %ecx
+movl %edx,-20(%ebp)
+cmpl $1,-20(%ebp)
+je .LC1801
+movl $263,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1803
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1803:
+.LC1801:
+movl $5,-20(%ebp)
+movl $2,-36(%ebp)
+movl -20(%ebp),%eax
+movl -36(%ebp),%ecx
+cdq
+idivl %ecx
+movl %edx,-20(%ebp)
+cmpl $1,-20(%ebp)
+je .LC1805
+movl $264,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1807
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1807:
+.LC1805:
+movl $5,-20(%ebp)
+movl $2,-40(%ebp)
+movl -20(%ebp),%edi
+movl %edi,%eax
+movl -40(%ebp),%ecx
+xorl %edx,%edx
+divl %ecx
+movl %edx,%edi
+movl %edi,-20(%ebp)
+cmpl $1,-20(%ebp)
+je .LC1809
+movl $265,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1811
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1811:
+.LC1809:
+movl $5,-24(%ebp)
+movb $2,-25(%ebp)
+movl -24(%ebp),%eax
+movsbl -25(%ebp),%edi
+movl %edi,%ecx
+xorl %edx,%edx
+divl %ecx
+movl %edx,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $1,%edi
+je .LC1813
+movl $266,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1815
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1815:
+.LC1813:
+movl $5,-24(%ebp)
+movw $2,-28(%ebp)
+movl -24(%ebp),%eax
+movswl -28(%ebp),%edi
+movl %edi,%ecx
+xorl %edx,%edx
+divl %ecx
+movl %edx,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $1,%edi
+je .LC1817
+movl $267,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1819
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1819:
+.LC1817:
+movl $5,-24(%ebp)
+movl $2,-32(%ebp)
+movl -24(%ebp),%eax
+movl -32(%ebp),%edi
+movl %edi,%ecx
+xorl %edx,%edx
+divl %ecx
+movl %edx,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $1,%edi
+je .LC1821
+movl $268,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1823
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1823:
+.LC1821:
+movl $5,-24(%ebp)
+movl $2,-36(%ebp)
+movl -24(%ebp),%eax
+movl -36(%ebp),%edi
+movl %edi,%ecx
+xorl %edx,%edx
+divl %ecx
+movl %edx,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $1,%edi
+je .LC1825
+movl $269,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1827
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1827:
+.LC1825:
+movl $5,-24(%ebp)
+movl $2,-40(%ebp)
+movl -24(%ebp),%eax
+movl -40(%ebp),%ecx
+xorl %edx,%edx
+divl %ecx
+movl %edx,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $1,%edi
+je .LC1829
+movl $270,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1831
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1831:
+.LC1829:
+movb $5,-9(%ebp)
+movb $2,-25(%ebp)
+movsbl -9(%ebp),%edi
+movsbl -25(%ebp),%ecx
+movl %edi,%eax
+sarl %cl,%eax
+movl %eax,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $1,%edi
+je .LC1833
+movl $271,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1835
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1835:
+.LC1833:
+movb $5,-9(%ebp)
+movw $2,-28(%ebp)
+movsbl -9(%ebp),%edi
+movswl -28(%ebp),%ecx
+movl %edi,%eax
+sarl %cl,%eax
+movl %eax,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $1,%edi
+je .LC1837
+movl $272,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1839
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1839:
+.LC1837:
+movb $5,-9(%ebp)
+movl $2,-32(%ebp)
+movsbl -9(%ebp),%edi
+movl -32(%ebp),%ecx
+movl %edi,%eax
+sarl %cl,%eax
+movl %eax,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $1,%edi
+je .LC1841
+movl $273,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1843
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1843:
+.LC1841:
+movb $5,-9(%ebp)
+movl $2,-36(%ebp)
+movsbl -9(%ebp),%edi
+movl -36(%ebp),%ecx
+movl %edi,%eax
+sarl %cl,%eax
+movl %eax,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $1,%edi
+je .LC1845
+movl $274,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1847
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1847:
+.LC1845:
+movb $5,-9(%ebp)
+movl $2,-40(%ebp)
+movsbl -9(%ebp),%edi
+movl -40(%ebp),%esi
+movl %esi,%ecx
+movl %edi,%eax
+sarl %cl,%eax
+movl %eax,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $1,%edi
+je .LC1849
+movl $275,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1851
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1851:
+.LC1849:
+movw $5,-12(%ebp)
+movb $2,-25(%ebp)
+movswl -12(%ebp),%edi
+movsbl -25(%ebp),%ecx
+movl %edi,%eax
+sarl %cl,%eax
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $1,%edi
+je .LC1853
+movl $276,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1855
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1855:
+.LC1853:
+movw $5,-12(%ebp)
+movw $2,-28(%ebp)
+movswl -12(%ebp),%edi
+movswl -28(%ebp),%ecx
+movl %edi,%eax
+sarl %cl,%eax
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $1,%edi
+je .LC1857
+movl $277,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1859
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1859:
+.LC1857:
+movw $5,-12(%ebp)
+movl $2,-32(%ebp)
+movswl -12(%ebp),%edi
+movl -32(%ebp),%ecx
+movl %edi,%eax
+sarl %cl,%eax
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $1,%edi
+je .LC1861
+movl $278,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1863
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1863:
+.LC1861:
+movw $5,-12(%ebp)
+movl $2,-36(%ebp)
+movswl -12(%ebp),%edi
+movl -36(%ebp),%ecx
+movl %edi,%eax
+sarl %cl,%eax
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $1,%edi
+je .LC1865
+movl $279,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1867
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1867:
+.LC1865:
+movw $5,-12(%ebp)
+movl $2,-40(%ebp)
+movswl -12(%ebp),%edi
+movl -40(%ebp),%esi
+movl %esi,%ecx
+movl %edi,%eax
+sarl %cl,%eax
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $1,%edi
+je .LC1869
+movl $280,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1871
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1871:
+.LC1869:
+movl $5,-16(%ebp)
+movb $2,-25(%ebp)
+movsbl -25(%ebp),%ecx
+sarl %cl,-16(%ebp)
+cmpl $1,-16(%ebp)
+je .LC1873
+movl $281,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1875
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1875:
+.LC1873:
+movl $5,-16(%ebp)
+movw $2,-28(%ebp)
+movswl -28(%ebp),%ecx
+sarl %cl,-16(%ebp)
+cmpl $1,-16(%ebp)
+je .LC1877
+movl $282,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1879
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1879:
+.LC1877:
+movl $5,-16(%ebp)
+movl $2,-32(%ebp)
+movl -32(%ebp),%ecx
+sarl %cl,-16(%ebp)
+cmpl $1,-16(%ebp)
+je .LC1881
+movl $283,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1883
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1883:
+.LC1881:
+movl $5,-16(%ebp)
+movl $2,-36(%ebp)
+movl -36(%ebp),%ecx
+sarl %cl,-16(%ebp)
+cmpl $1,-16(%ebp)
+je .LC1885
+movl $284,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1887
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1887:
+.LC1885:
+movl $5,-16(%ebp)
+movl $2,-40(%ebp)
+movl -40(%ebp),%edi
+movl %edi,%ecx
+sarl %cl,-16(%ebp)
+cmpl $1,-16(%ebp)
+je .LC1889
+movl $285,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1891
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1891:
+.LC1889:
+movl $5,-20(%ebp)
+movb $2,-25(%ebp)
+movsbl -25(%ebp),%ecx
+sarl %cl,-20(%ebp)
+cmpl $1,-20(%ebp)
+je .LC1893
+movl $286,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1895
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1895:
+.LC1893:
+movl $5,-20(%ebp)
+movw $2,-28(%ebp)
+movswl -28(%ebp),%ecx
+sarl %cl,-20(%ebp)
+cmpl $1,-20(%ebp)
+je .LC1897
+movl $287,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1899
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1899:
+.LC1897:
+movl $5,-20(%ebp)
+movl $2,-32(%ebp)
+movl -32(%ebp),%ecx
+sarl %cl,-20(%ebp)
+cmpl $1,-20(%ebp)
+je .LC1901
+movl $288,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1903
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1903:
+.LC1901:
+movl $5,-20(%ebp)
+movl $2,-36(%ebp)
+movl -36(%ebp),%ecx
+sarl %cl,-20(%ebp)
+cmpl $1,-20(%ebp)
+je .LC1905
+movl $289,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1907
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1907:
+.LC1905:
+movl $5,-20(%ebp)
+movl $2,-40(%ebp)
+movl -40(%ebp),%edi
+movl %edi,%ecx
+sarl %cl,-20(%ebp)
+cmpl $1,-20(%ebp)
+je .LC1909
+movl $290,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1911
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1911:
+.LC1909:
+movl $5,-24(%ebp)
+movb $2,-25(%ebp)
+movl -24(%ebp),%edi
+movsbl -25(%ebp),%ecx
+movl %edi,%eax
+shrl %cl,%eax
+movl %eax,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $1,%edi
+je .LC1913
+movl $291,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1915
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1915:
+.LC1913:
+movl $5,-24(%ebp)
+movw $2,-28(%ebp)
+movl -24(%ebp),%edi
+movswl -28(%ebp),%ecx
+movl %edi,%eax
+shrl %cl,%eax
+movl %eax,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $1,%edi
+je .LC1917
+movl $292,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1919
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1919:
+.LC1917:
+movl $5,-24(%ebp)
+movl $2,-32(%ebp)
+movl -24(%ebp),%edi
+movl -32(%ebp),%ecx
+movl %edi,%eax
+shrl %cl,%eax
+movl %eax,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $1,%edi
+je .LC1921
+movl $293,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1923
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1923:
+.LC1921:
+movl $5,-24(%ebp)
+movl $2,-36(%ebp)
+movl -24(%ebp),%edi
+movl -36(%ebp),%ecx
+movl %edi,%eax
+shrl %cl,%eax
+movl %eax,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $1,%edi
+je .LC1925
+movl $294,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1927
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1927:
+.LC1925:
+movl $5,-24(%ebp)
+movl $2,-40(%ebp)
+movl -24(%ebp),%edi
+movl -40(%ebp),%esi
+movl %esi,%ecx
+movl %edi,%eax
+shrl %cl,%eax
+movl %eax,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $1,%edi
+je .LC1929
+movl $295,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1931
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1931:
+.LC1929:
+movb $5,-9(%ebp)
+movb $2,-25(%ebp)
+movsbl -9(%ebp),%edi
+movsbl -25(%ebp),%ecx
+movl %edi,%eax
+sall %cl,%eax
+movl %eax,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $20,%edi
+je .LC1933
+movl $296,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1935
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1935:
+.LC1933:
+movb $5,-9(%ebp)
+movw $2,-28(%ebp)
+movsbl -9(%ebp),%edi
+movswl -28(%ebp),%ecx
+movl %edi,%eax
+sall %cl,%eax
+movl %eax,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $20,%edi
+je .LC1937
+movl $297,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1939
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1939:
+.LC1937:
+movb $5,-9(%ebp)
+movl $2,-32(%ebp)
+movsbl -9(%ebp),%edi
+movl -32(%ebp),%ecx
+movl %edi,%eax
+sall %cl,%eax
+movl %eax,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $20,%edi
+je .LC1941
+movl $298,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1943
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1943:
+.LC1941:
+movb $5,-9(%ebp)
+movl $2,-36(%ebp)
+movsbl -9(%ebp),%edi
+movl -36(%ebp),%ecx
+movl %edi,%eax
+sall %cl,%eax
+movl %eax,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $20,%edi
+je .LC1945
+movl $299,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1947
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1947:
+.LC1945:
+movb $5,-9(%ebp)
+movl $2,-40(%ebp)
+movsbl -9(%ebp),%edi
+movl -40(%ebp),%esi
+movl %esi,%ecx
+movl %edi,%eax
+sall %cl,%eax
+movl %eax,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $20,%edi
+je .LC1949
+movl $300,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1951
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1951:
+.LC1949:
+movw $5,-12(%ebp)
+movb $2,-25(%ebp)
+movswl -12(%ebp),%edi
+movsbl -25(%ebp),%ecx
+movl %edi,%eax
+sall %cl,%eax
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $20,%edi
+je .LC1953
+movl $301,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1955
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1955:
+.LC1953:
+movw $5,-12(%ebp)
+movw $2,-28(%ebp)
+movswl -12(%ebp),%edi
+movswl -28(%ebp),%ecx
+movl %edi,%eax
+sall %cl,%eax
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $20,%edi
+je .LC1957
+movl $302,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1959
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1959:
+.LC1957:
+movw $5,-12(%ebp)
+movl $2,-32(%ebp)
+movswl -12(%ebp),%edi
+movl -32(%ebp),%ecx
+movl %edi,%eax
+sall %cl,%eax
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $20,%edi
+je .LC1961
+movl $303,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1963
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1963:
+.LC1961:
+movw $5,-12(%ebp)
+movl $2,-36(%ebp)
+movswl -12(%ebp),%edi
+movl -36(%ebp),%ecx
+movl %edi,%eax
+sall %cl,%eax
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $20,%edi
+je .LC1965
+movl $304,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1967
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1967:
+.LC1965:
+movw $5,-12(%ebp)
+movl $2,-40(%ebp)
+movswl -12(%ebp),%edi
+movl -40(%ebp),%esi
+movl %esi,%ecx
+movl %edi,%eax
+sall %cl,%eax
+movl %eax,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $20,%edi
+je .LC1969
+movl $305,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1971
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1971:
+.LC1969:
+movl $5,-16(%ebp)
+movb $2,-25(%ebp)
+movsbl -25(%ebp),%ecx
+sall %cl,-16(%ebp)
+cmpl $20,-16(%ebp)
+je .LC1973
+movl $306,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1975
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1975:
+.LC1973:
+movl $5,-16(%ebp)
+movw $2,-28(%ebp)
+movswl -28(%ebp),%ecx
+sall %cl,-16(%ebp)
+cmpl $20,-16(%ebp)
+je .LC1977
+movl $307,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1979
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1979:
+.LC1977:
+movl $5,-16(%ebp)
+movl $2,-32(%ebp)
+movl -32(%ebp),%ecx
+sall %cl,-16(%ebp)
+cmpl $20,-16(%ebp)
+je .LC1981
+movl $308,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1983
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1983:
+.LC1981:
+movl $5,-16(%ebp)
+movl $2,-36(%ebp)
+movl -36(%ebp),%ecx
+sall %cl,-16(%ebp)
+cmpl $20,-16(%ebp)
+je .LC1985
+movl $309,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1987
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1987:
+.LC1985:
+movl $5,-16(%ebp)
+movl $2,-40(%ebp)
+movl -40(%ebp),%edi
+movl %edi,%ecx
+sall %cl,-16(%ebp)
+cmpl $20,-16(%ebp)
+je .LC1989
+movl $310,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1991
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1991:
+.LC1989:
+movl $5,-20(%ebp)
+movb $2,-25(%ebp)
+movsbl -25(%ebp),%ecx
+sall %cl,-20(%ebp)
+cmpl $20,-20(%ebp)
+je .LC1993
+movl $311,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1995
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1995:
+.LC1993:
+movl $5,-20(%ebp)
+movw $2,-28(%ebp)
+movswl -28(%ebp),%ecx
+sall %cl,-20(%ebp)
+cmpl $20,-20(%ebp)
+je .LC1997
+movl $312,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC1999
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC1999:
+.LC1997:
+movl $5,-20(%ebp)
+movl $2,-32(%ebp)
+movl -32(%ebp),%ecx
+sall %cl,-20(%ebp)
+cmpl $20,-20(%ebp)
+je .LC2001
+movl $313,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2003
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2003:
+.LC2001:
+movl $5,-20(%ebp)
+movl $2,-36(%ebp)
+movl -36(%ebp),%ecx
+sall %cl,-20(%ebp)
+cmpl $20,-20(%ebp)
+je .LC2005
+movl $314,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2007
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2007:
+.LC2005:
+movl $5,-20(%ebp)
+movl $2,-40(%ebp)
+movl -40(%ebp),%edi
+movl %edi,%ecx
+sall %cl,-20(%ebp)
+cmpl $20,-20(%ebp)
+je .LC2009
+movl $315,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2011
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2011:
+.LC2009:
+movl $5,-24(%ebp)
+movb $2,-25(%ebp)
+movl -24(%ebp),%edi
+movsbl -25(%ebp),%ecx
+movl %edi,%eax
+shll %cl,%eax
+movl %eax,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $20,%edi
+je .LC2013
+movl $316,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2015
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2015:
+.LC2013:
+movl $5,-24(%ebp)
+movw $2,-28(%ebp)
+movl -24(%ebp),%edi
+movswl -28(%ebp),%ecx
+movl %edi,%eax
+shll %cl,%eax
+movl %eax,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $20,%edi
+je .LC2017
+movl $317,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2019
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2019:
+.LC2017:
+movl $5,-24(%ebp)
+movl $2,-32(%ebp)
+movl -24(%ebp),%edi
+movl -32(%ebp),%ecx
+movl %edi,%eax
+shll %cl,%eax
+movl %eax,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $20,%edi
+je .LC2021
+movl $318,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2023
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2023:
+.LC2021:
+movl $5,-24(%ebp)
+movl $2,-36(%ebp)
+movl -24(%ebp),%edi
+movl -36(%ebp),%ecx
+movl %edi,%eax
+shll %cl,%eax
+movl %eax,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $20,%edi
+je .LC2025
+movl $319,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2027
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2027:
+.LC2025:
+movl $5,-24(%ebp)
+movl $2,-40(%ebp)
+movl -24(%ebp),%edi
+movl -40(%ebp),%esi
+movl %esi,%ecx
+movl %edi,%eax
+shll %cl,%eax
+movl %eax,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $20,%edi
+je .LC2029
+movl $320,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2031
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2031:
+.LC2029:
+movb $12,-9(%ebp)
+movb $10,-25(%ebp)
+movsbl -9(%ebp),%edi
+movsbl -25(%ebp),%esi
+andl %esi,%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $8,%edi
+je .LC2033
+movl $321,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2035
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2035:
+.LC2033:
+movb $12,-9(%ebp)
+movw $10,-28(%ebp)
+movsbl -9(%ebp),%edi
+movswl -28(%ebp),%esi
+andl %esi,%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $8,%edi
+je .LC2037
+movl $322,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2039
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2039:
+.LC2037:
+movb $12,-9(%ebp)
+movl $10,-32(%ebp)
+movsbl -9(%ebp),%edi
+andl -32(%ebp),%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $8,%edi
+je .LC2041
+movl $323,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2043
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2043:
+.LC2041:
+movb $12,-9(%ebp)
+movl $10,-36(%ebp)
+movsbl -9(%ebp),%edi
+andl -36(%ebp),%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $8,%edi
+je .LC2045
+movl $324,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2047
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2047:
+.LC2045:
+movb $12,-9(%ebp)
+movl $10,-40(%ebp)
+movsbl -9(%ebp),%edi
+andl -40(%ebp),%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $8,%edi
+je .LC2049
+movl $325,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2051
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2051:
+.LC2049:
+movw $12,-12(%ebp)
+movb $10,-25(%ebp)
+movswl -12(%ebp),%edi
+movsbl -25(%ebp),%esi
+andl %esi,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $8,%edi
+je .LC2053
+movl $326,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2055
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2055:
+.LC2053:
+movw $12,-12(%ebp)
+movw $10,-28(%ebp)
+movswl -12(%ebp),%edi
+movswl -28(%ebp),%esi
+andl %esi,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $8,%edi
+je .LC2057
+movl $327,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2059
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2059:
+.LC2057:
+movw $12,-12(%ebp)
+movl $10,-32(%ebp)
+movswl -12(%ebp),%edi
+andl -32(%ebp),%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $8,%edi
+je .LC2061
+movl $328,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2063
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2063:
+.LC2061:
+movw $12,-12(%ebp)
+movl $10,-36(%ebp)
+movswl -12(%ebp),%edi
+andl -36(%ebp),%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $8,%edi
+je .LC2065
+movl $329,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2067
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2067:
+.LC2065:
+movw $12,-12(%ebp)
+movl $10,-40(%ebp)
+movswl -12(%ebp),%edi
+andl -40(%ebp),%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $8,%edi
+je .LC2069
+movl $330,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2071
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2071:
+.LC2069:
+movl $12,-16(%ebp)
+movb $10,-25(%ebp)
+movsbl -25(%ebp),%edi
+andl %edi,-16(%ebp)
+cmpl $8,-16(%ebp)
+je .LC2073
+movl $331,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2075
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2075:
+.LC2073:
+movl $12,-16(%ebp)
+movw $10,-28(%ebp)
+movswl -28(%ebp),%edi
+andl %edi,-16(%ebp)
+cmpl $8,-16(%ebp)
+je .LC2077
+movl $332,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2079
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2079:
+.LC2077:
+movl $12,-16(%ebp)
+movl $10,-32(%ebp)
+movl -32(%ebp),%edi
+andl %edi,-16(%ebp)
+cmpl $8,-16(%ebp)
+je .LC2081
+movl $333,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2083
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2083:
+.LC2081:
+movl $12,-16(%ebp)
+movl $10,-36(%ebp)
+movl -36(%ebp),%edi
+andl %edi,-16(%ebp)
+cmpl $8,-16(%ebp)
+je .LC2085
+movl $334,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2087
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2087:
+.LC2085:
+movl $12,-16(%ebp)
+movl $10,-40(%ebp)
+movl -16(%ebp),%edi
+andl -40(%ebp),%edi
+movl %edi,-16(%ebp)
+cmpl $8,-16(%ebp)
+je .LC2089
+movl $335,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2091
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2091:
+.LC2089:
+movl $12,-20(%ebp)
+movb $10,-25(%ebp)
+movsbl -25(%ebp),%edi
+andl %edi,-20(%ebp)
+cmpl $8,-20(%ebp)
+je .LC2093
+movl $336,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2095
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2095:
+.LC2093:
+movl $12,-20(%ebp)
+movw $10,-28(%ebp)
+movswl -28(%ebp),%edi
+andl %edi,-20(%ebp)
+cmpl $8,-20(%ebp)
+je .LC2097
+movl $337,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2099
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2099:
+.LC2097:
+movl $12,-20(%ebp)
+movl $10,-32(%ebp)
+movl -32(%ebp),%edi
+andl %edi,-20(%ebp)
+cmpl $8,-20(%ebp)
+je .LC2101
+movl $338,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2103
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2103:
+.LC2101:
+movl $12,-20(%ebp)
+movl $10,-36(%ebp)
+movl -36(%ebp),%edi
+andl %edi,-20(%ebp)
+cmpl $8,-20(%ebp)
+je .LC2105
+movl $339,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2107
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2107:
+.LC2105:
+movl $12,-20(%ebp)
+movl $10,-40(%ebp)
+movl -20(%ebp),%edi
+andl -40(%ebp),%edi
+movl %edi,-20(%ebp)
+cmpl $8,-20(%ebp)
+je .LC2109
+movl $340,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2111
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2111:
+.LC2109:
+movl $12,-24(%ebp)
+movb $10,-25(%ebp)
+movsbl -25(%ebp),%edi
+andl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $8,%edi
+je .LC2113
+movl $341,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2115
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2115:
+.LC2113:
+movl $12,-24(%ebp)
+movw $10,-28(%ebp)
+movswl -28(%ebp),%edi
+andl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $8,%edi
+je .LC2117
+movl $342,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2119
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2119:
+.LC2117:
+movl $12,-24(%ebp)
+movl $10,-32(%ebp)
+movl -32(%ebp),%edi
+andl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $8,%edi
+je .LC2121
+movl $343,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2123
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2123:
+.LC2121:
+movl $12,-24(%ebp)
+movl $10,-36(%ebp)
+movl -36(%ebp),%edi
+andl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $8,%edi
+je .LC2125
+movl $344,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2127
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2127:
+.LC2125:
+movl $12,-24(%ebp)
+movl $10,-40(%ebp)
+movl -40(%ebp),%edi
+andl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $8,%edi
+je .LC2129
+movl $345,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2131
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2131:
+.LC2129:
+movb $12,-9(%ebp)
+movb $10,-25(%ebp)
+movsbl -9(%ebp),%edi
+movsbl -25(%ebp),%esi
+xorl %esi,%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $6,%edi
+je .LC2133
+movl $346,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2135
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2135:
+.LC2133:
+movb $12,-9(%ebp)
+movw $10,-28(%ebp)
+movsbl -9(%ebp),%edi
+movswl -28(%ebp),%esi
+xorl %esi,%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $6,%edi
+je .LC2137
+movl $347,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2139
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2139:
+.LC2137:
+movb $12,-9(%ebp)
+movl $10,-32(%ebp)
+movsbl -9(%ebp),%edi
+xorl -32(%ebp),%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $6,%edi
+je .LC2141
+movl $348,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2143
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2143:
+.LC2141:
+movb $12,-9(%ebp)
+movl $10,-36(%ebp)
+movsbl -9(%ebp),%edi
+xorl -36(%ebp),%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $6,%edi
+je .LC2145
+movl $349,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2147
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2147:
+.LC2145:
+movb $12,-9(%ebp)
+movl $10,-40(%ebp)
+movsbl -9(%ebp),%edi
+xorl -40(%ebp),%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $6,%edi
+je .LC2149
+movl $350,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2151
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2151:
+.LC2149:
+movw $12,-12(%ebp)
+movb $10,-25(%ebp)
+movswl -12(%ebp),%edi
+movsbl -25(%ebp),%esi
+xorl %esi,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $6,%edi
+je .LC2153
+movl $351,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2155
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2155:
+.LC2153:
+movw $12,-12(%ebp)
+movw $10,-28(%ebp)
+movswl -12(%ebp),%edi
+movswl -28(%ebp),%esi
+xorl %esi,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $6,%edi
+je .LC2157
+movl $352,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2159
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2159:
+.LC2157:
+movw $12,-12(%ebp)
+movl $10,-32(%ebp)
+movswl -12(%ebp),%edi
+xorl -32(%ebp),%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $6,%edi
+je .LC2161
+movl $353,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2163
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2163:
+.LC2161:
+movw $12,-12(%ebp)
+movl $10,-36(%ebp)
+movswl -12(%ebp),%edi
+xorl -36(%ebp),%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $6,%edi
+je .LC2165
+movl $354,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2167
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2167:
+.LC2165:
+movw $12,-12(%ebp)
+movl $10,-40(%ebp)
+movswl -12(%ebp),%edi
+xorl -40(%ebp),%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $6,%edi
+je .LC2169
+movl $355,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2171
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2171:
+.LC2169:
+movl $12,-16(%ebp)
+movb $10,-25(%ebp)
+movsbl -25(%ebp),%edi
+xorl %edi,-16(%ebp)
+cmpl $6,-16(%ebp)
+je .LC2173
+movl $356,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2175
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2175:
+.LC2173:
+movl $12,-16(%ebp)
+movw $10,-28(%ebp)
+movswl -28(%ebp),%edi
+xorl %edi,-16(%ebp)
+cmpl $6,-16(%ebp)
+je .LC2177
+movl $357,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2179
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2179:
+.LC2177:
+movl $12,-16(%ebp)
+movl $10,-32(%ebp)
+movl -32(%ebp),%edi
+xorl %edi,-16(%ebp)
+cmpl $6,-16(%ebp)
+je .LC2181
+movl $358,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2183
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2183:
+.LC2181:
+movl $12,-16(%ebp)
+movl $10,-36(%ebp)
+movl -36(%ebp),%edi
+xorl %edi,-16(%ebp)
+cmpl $6,-16(%ebp)
+je .LC2185
+movl $359,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2187
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2187:
+.LC2185:
+movl $12,-16(%ebp)
+movl $10,-40(%ebp)
+movl -16(%ebp),%edi
+xorl -40(%ebp),%edi
+movl %edi,-16(%ebp)
+cmpl $6,-16(%ebp)
+je .LC2189
+movl $360,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2191
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2191:
+.LC2189:
+movl $12,-20(%ebp)
+movb $10,-25(%ebp)
+movsbl -25(%ebp),%edi
+xorl %edi,-20(%ebp)
+cmpl $6,-20(%ebp)
+je .LC2193
+movl $361,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2195
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2195:
+.LC2193:
+movl $12,-20(%ebp)
+movw $10,-28(%ebp)
+movswl -28(%ebp),%edi
+xorl %edi,-20(%ebp)
+cmpl $6,-20(%ebp)
+je .LC2197
+movl $362,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2199
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2199:
+.LC2197:
+movl $12,-20(%ebp)
+movl $10,-32(%ebp)
+movl -32(%ebp),%edi
+xorl %edi,-20(%ebp)
+cmpl $6,-20(%ebp)
+je .LC2201
+movl $363,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2203
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2203:
+.LC2201:
+movl $12,-20(%ebp)
+movl $10,-36(%ebp)
+movl -36(%ebp),%edi
+xorl %edi,-20(%ebp)
+cmpl $6,-20(%ebp)
+je .LC2205
+movl $364,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2207
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2207:
+.LC2205:
+movl $12,-20(%ebp)
+movl $10,-40(%ebp)
+movl -20(%ebp),%edi
+xorl -40(%ebp),%edi
+movl %edi,-20(%ebp)
+cmpl $6,-20(%ebp)
+je .LC2209
+movl $365,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2211
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2211:
+.LC2209:
+movl $12,-24(%ebp)
+movb $10,-25(%ebp)
+movsbl -25(%ebp),%edi
+xorl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $6,%edi
+je .LC2213
+movl $366,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2215
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2215:
+.LC2213:
+movl $12,-24(%ebp)
+movw $10,-28(%ebp)
+movswl -28(%ebp),%edi
+xorl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $6,%edi
+je .LC2217
+movl $367,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2219
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2219:
+.LC2217:
+movl $12,-24(%ebp)
+movl $10,-32(%ebp)
+movl -32(%ebp),%edi
+xorl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $6,%edi
+je .LC2221
+movl $368,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2223
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2223:
+.LC2221:
+movl $12,-24(%ebp)
+movl $10,-36(%ebp)
+movl -36(%ebp),%edi
+xorl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $6,%edi
+je .LC2225
+movl $369,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2227
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2227:
+.LC2225:
+movl $12,-24(%ebp)
+movl $10,-40(%ebp)
+movl -40(%ebp),%edi
+xorl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $6,%edi
+je .LC2229
+movl $370,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2231
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2231:
+.LC2229:
+movb $12,-9(%ebp)
+movb $10,-25(%ebp)
+movsbl -9(%ebp),%edi
+movsbl -25(%ebp),%esi
+orl %esi,%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $14,%edi
+je .LC2233
+movl $371,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2235
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2235:
+.LC2233:
+movb $12,-9(%ebp)
+movw $10,-28(%ebp)
+movsbl -9(%ebp),%edi
+movswl -28(%ebp),%esi
+orl %esi,%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $14,%edi
+je .LC2237
+movl $372,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2239
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2239:
+.LC2237:
+movb $12,-9(%ebp)
+movl $10,-32(%ebp)
+movsbl -9(%ebp),%edi
+orl -32(%ebp),%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $14,%edi
+je .LC2241
+movl $373,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2243
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2243:
+.LC2241:
+movb $12,-9(%ebp)
+movl $10,-36(%ebp)
+movsbl -9(%ebp),%edi
+orl -36(%ebp),%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $14,%edi
+je .LC2245
+movl $374,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2247
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2247:
+.LC2245:
+movb $12,-9(%ebp)
+movl $10,-40(%ebp)
+movsbl -9(%ebp),%edi
+orl -40(%ebp),%edi
+movl %edi,%ebx
+movb %bl,-9(%ebp)
+movsbl -9(%ebp),%edi
+cmpl $14,%edi
+je .LC2249
+movl $375,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2251
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2251:
+.LC2249:
+movw $12,-12(%ebp)
+movb $10,-25(%ebp)
+movswl -12(%ebp),%edi
+movsbl -25(%ebp),%esi
+orl %esi,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $14,%edi
+je .LC2253
+movl $376,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2255
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2255:
+.LC2253:
+movw $12,-12(%ebp)
+movw $10,-28(%ebp)
+movswl -12(%ebp),%edi
+movswl -28(%ebp),%esi
+orl %esi,%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $14,%edi
+je .LC2257
+movl $377,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2259
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2259:
+.LC2257:
+movw $12,-12(%ebp)
+movl $10,-32(%ebp)
+movswl -12(%ebp),%edi
+orl -32(%ebp),%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $14,%edi
+je .LC2261
+movl $378,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2263
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2263:
+.LC2261:
+movw $12,-12(%ebp)
+movl $10,-36(%ebp)
+movswl -12(%ebp),%edi
+orl -36(%ebp),%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $14,%edi
+je .LC2265
+movl $379,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2267
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2267:
+.LC2265:
+movw $12,-12(%ebp)
+movl $10,-40(%ebp)
+movswl -12(%ebp),%edi
+orl -40(%ebp),%edi
+movw %di,-12(%ebp)
+movswl -12(%ebp),%edi
+cmpl $14,%edi
+je .LC2269
+movl $380,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2271
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2271:
+.LC2269:
+movl $12,-16(%ebp)
+movb $10,-25(%ebp)
+movsbl -25(%ebp),%edi
+orl %edi,-16(%ebp)
+cmpl $14,-16(%ebp)
+je .LC2273
+movl $381,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2275
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2275:
+.LC2273:
+movl $12,-16(%ebp)
+movw $10,-28(%ebp)
+movswl -28(%ebp),%edi
+orl %edi,-16(%ebp)
+cmpl $14,-16(%ebp)
+je .LC2277
+movl $382,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2279
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2279:
+.LC2277:
+movl $12,-16(%ebp)
+movl $10,-32(%ebp)
+movl -32(%ebp),%edi
+orl %edi,-16(%ebp)
+cmpl $14,-16(%ebp)
+je .LC2281
+movl $383,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2283
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2283:
+.LC2281:
+movl $12,-16(%ebp)
+movl $10,-36(%ebp)
+movl -36(%ebp),%edi
+orl %edi,-16(%ebp)
+cmpl $14,-16(%ebp)
+je .LC2285
+movl $384,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2287
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2287:
+.LC2285:
+movl $12,-16(%ebp)
+movl $10,-40(%ebp)
+movl -16(%ebp),%edi
+orl -40(%ebp),%edi
+movl %edi,-16(%ebp)
+cmpl $14,-16(%ebp)
+je .LC2289
+movl $385,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2291
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2291:
+.LC2289:
+movl $12,-20(%ebp)
+movb $10,-25(%ebp)
+movsbl -25(%ebp),%edi
+orl %edi,-20(%ebp)
+cmpl $14,-20(%ebp)
+je .LC2293
+movl $386,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2295
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2295:
+.LC2293:
+movl $12,-20(%ebp)
+movw $10,-28(%ebp)
+movswl -28(%ebp),%edi
+orl %edi,-20(%ebp)
+cmpl $14,-20(%ebp)
+je .LC2297
+movl $387,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2299
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2299:
+.LC2297:
+movl $12,-20(%ebp)
+movl $10,-32(%ebp)
+movl -32(%ebp),%edi
+orl %edi,-20(%ebp)
+cmpl $14,-20(%ebp)
+je .LC2301
+movl $388,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2303
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2303:
+.LC2301:
+movl $12,-20(%ebp)
+movl $10,-36(%ebp)
+movl -36(%ebp),%edi
+orl %edi,-20(%ebp)
+cmpl $14,-20(%ebp)
+je .LC2305
+movl $389,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2307
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2307:
+.LC2305:
+movl $12,-20(%ebp)
+movl $10,-40(%ebp)
+movl -20(%ebp),%edi
+orl -40(%ebp),%edi
+movl %edi,-20(%ebp)
+cmpl $14,-20(%ebp)
+je .LC2309
+movl $390,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2311
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2311:
+.LC2309:
+movl $12,-24(%ebp)
+movb $10,-25(%ebp)
+movsbl -25(%ebp),%edi
+orl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $14,%edi
+je .LC2313
+movl $391,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2315
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2315:
+.LC2313:
+movl $12,-24(%ebp)
+movw $10,-28(%ebp)
+movswl -28(%ebp),%edi
+orl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $14,%edi
+je .LC2317
+movl $392,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2319
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2319:
+.LC2317:
+movl $12,-24(%ebp)
+movl $10,-32(%ebp)
+movl -32(%ebp),%edi
+orl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $14,%edi
+je .LC2321
+movl $393,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2323
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2323:
+.LC2321:
+movl $12,-24(%ebp)
+movl $10,-36(%ebp)
+movl -36(%ebp),%edi
+orl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $14,%edi
+je .LC2325
+movl $394,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2327
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2327:
+.LC2325:
+movl $12,-24(%ebp)
+movl $10,-40(%ebp)
+movl -40(%ebp),%edi
+orl %edi,-24(%ebp)
+movl -24(%ebp),%edi
+cmpl $14,%edi
+je .LC2329
+movl $395,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2331
+pushl -8(%ebp)
+pushl $f.706
+call printf
+addl $8,%esp
+.LC2331:
+.LC2329:
+cmpl $0,-8(%ebp)
+je .LC2333
+movl $1,-76(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC2335
+pushl $1
+pushl $s714er.707
+call printf
+addl $8,%esp
+.LC2335:
+.LC2333:
+movl -76(%ebp),%eax
+.LC705:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf2337:
+.size s714,.Lf2337-s714
+.data
+.align 1
+.type s715er.2339,@object
+s715er.2339:
+.byte 115
+.byte 55
+.byte 49
+.byte 53
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size s715er.2339,11
+.align 1
+.type qs715.2340,@object
+.size qs715.2340,8
+qs715.2340:
+.byte 115
+.byte 55
+.byte 49
+.byte 53
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s715
+.text
+.align 16
+.type s715,@function
+s715:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $28,%esp
+movl $0,-28(%ebp)
+movl $0,-20(%ebp)
+leal qs715.2340,%edi
+movl %edi,-4(%ebp)
+movl 20(%ebp),%edi
+leal 60(%edi),%edi
+movl %edi,-8(%ebp)
+movl $0,-16(%ebp)
+.LC2341:
+.LC2342:
+movl -8(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-8(%ebp)
+movl -4(%ebp),%esi
+leal 1(%esi),%ebx
+movl %ebx,-4(%ebp)
+movb (,%esi),%bl
+movb %bl,(,%edi)
+movsbl %bl,%edi
+cmpl $0,%edi
+jne .LC2341
+movl $1,-12(%ebp)
+incl -12(%ebp)
+incl -12(%ebp)
+incl -12(%ebp)
+incl -12(%ebp)
+movl -12(%ebp),%edi
+leal 1(%edi),%edi
+movl %edi,-12(%ebp)
+cmpl $6,%edi
+je .LC2344
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC2346
+pushl $1
+pushl $s715er.2339
+call printf
+addl $8,%esp
+.LC2346:
+incl -16(%ebp)
+.LC2344:
+pushl -28(%ebp)
+movl $3,-24(%ebp)
+movl -24(%ebp),%edi
+leal 2(%edi),%edi
+pushl %edi
+pushl -20(%ebp)
+call s715f
+addl $12,%esp
+cmpl $5,%eax
+je .LC2348
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC2350
+pushl $2
+pushl $s715er.2339
+call printf
+addl $8,%esp
+.LC2350:
+addl $2,-16(%ebp)
+.LC2348:
+movl -16(%ebp),%eax
+.LC2338:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf2352:
+.size s715,.Lf2352-s715
+.globl s715f
+.align 16
+.type s715f,@function
+s715f:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl 24(%ebp),%eax
+.LC2353:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf2354:
+.size s715f,.Lf2354-s715f
+.data
+.align 1
+.type s72er.2356,@object
+s72er.2356:
+.byte 115
+.byte 55
+.byte 50
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size s72er.2356,10
+.align 1
+.type qs72.2357,@object
+.size qs72.2357,8
+qs72.2357:
+.byte 115
+.byte 55
+.byte 50
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s72
+.text
+.align 16
+.type s72,@function
+s72:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $100,%esp
+leal qs72.2357,%edi
+movl %edi,-12(%ebp)
+movl 20(%ebp),%edi
+leal 60(%edi),%edi
+movl %edi,-16(%ebp)
+movl $0,-24(%ebp)
+.LC2358:
+.LC2359:
+movl -16(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-16(%ebp)
+movl -12(%ebp),%esi
+leal 1(%esi),%ebx
+movl %ebx,-12(%ebp)
+movb (,%esi),%bl
+movb %bl,(,%edi)
+movsbl %bl,%edi
+cmpl $0,%edi
+jne .LC2358
+movl $2,-4(%ebp)
+cmpl $2,-4(%ebp)
+je .LC2361
+incl -24(%ebp)
+pushl $1
+pushl $s72er.2356
+call printf
+addl $8,%esp
+.LC2361:
+movl -4(%ebp),%edi
+movl %edi,%esi
+negl %esi
+leal (%esi,%edi),%edi
+cmpl $0,%edi
+je .LC2363
+addl $2,-24(%ebp)
+pushl $2
+pushl $s72er.2356
+call printf
+addl $8,%esp
+.LC2363:
+movl $0,-4(%ebp)
+movl $0,-8(%ebp)
+jmp .LC2368
+.LC2365:
+movl -4(%ebp),%edi
+leal (,%edi,2),%edi
+orl $1,%edi
+movl %edi,-4(%ebp)
+.LC2366:
+incl -8(%ebp)
+.LC2368:
+movl 20(%ebp),%edi
+movl 4(%edi),%edi
+cmpl %edi,-8(%ebp)
+jl .LC2365
+movl -4(%ebp),%edi
+notl %edi
+cmpl $0,%edi
+je .LC2369
+addl $4,-24(%ebp)
+pushl $4
+pushl $s72er.2356
+call printf
+addl $8,%esp
+.LC2369:
+movl $5,-4(%ebp)
+movl -4(%ebp),%edi
+leal 1(%edi),%edi
+movl %edi,-4(%ebp)
+cmpl $6,%edi
+jne .LC2376
+movl -4(%ebp),%edi
+subl $1,%edi
+movl %edi,-4(%ebp)
+cmpl $5,%edi
+jne .LC2376
+movl -4(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-4(%ebp)
+cmpl $5,%edi
+jne .LC2376
+movl -4(%ebp),%edi
+movl %edi,%esi
+subl $1,%esi
+movl %esi,-4(%ebp)
+cmpl $6,%edi
+jne .LC2376
+cmpl $5,-4(%ebp)
+je .LC2371
+.LC2376:
+addl $8,-24(%ebp)
+pushl $8
+pushl $s72er.2356
+call printf
+addl $8,%esp
+.LC2371:
+movb $26,-29(%ebp)
+movl $26,-36(%ebp)
+fldl .LC2377
+fstpl -48(%ebp)
+movw $26,-32(%ebp)
+movl $26,-40(%ebp)
+movl $26,-28(%ebp)
+flds .LC2378
+fstps -52(%ebp)
+movl $0,-20(%ebp)
+movswl -32(%ebp),%edi
+movl %edi,%ebx
+movsbl %bl,%edi
+cmpl $26,%edi
+jne .LC2385
+movl -28(%ebp),%edi
+movl %edi,%ebx
+movsbl %bl,%edi
+cmpl $26,%edi
+jne .LC2385
+movl -36(%ebp),%edi
+movl %edi,%ebx
+movsbl %bl,%edi
+cmpl $26,%edi
+jne .LC2385
+movl -40(%ebp),%edi
+movl %edi,%ebx
+movsbl %bl,%edi
+cmpl $26,%edi
+jne .LC2385
+flds -52(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%ebx
+movsbl %bl,%edi
+cmpl $26,%edi
+jne .LC2385
+fldl -48(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%ebx
+movsbl %bl,%edi
+cmpl $26,%edi
+je .LC2379
+.LC2385:
+incl -20(%ebp)
+.LC2379:
+movsbl -29(%ebp),%edi
+movswl %di,%edi
+cmpl $26,%edi
+jne .LC2392
+movl -28(%ebp),%edi
+movswl %di,%edi
+cmpl $26,%edi
+jne .LC2392
+movl -36(%ebp),%edi
+movswl %di,%edi
+cmpl $26,%edi
+jne .LC2392
+movl -40(%ebp),%edi
+movswl %di,%edi
+cmpl $26,%edi
+jne .LC2392
+flds -52(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movswl %di,%edi
+cmpl $26,%edi
+jne .LC2392
+fldl -48(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movswl %di,%edi
+cmpl $26,%edi
+je .LC2386
+.LC2392:
+addl $2,-20(%ebp)
+.LC2386:
+movsbl -29(%ebp),%edi
+cmpl $26,%edi
+jne .LC2399
+movswl -32(%ebp),%edi
+cmpl $26,%edi
+jne .LC2399
+cmpl $26,-36(%ebp)
+jne .LC2399
+movl -40(%ebp),%edi
+cmpl $26,%edi
+jne .LC2399
+flds -52(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+cmpl $26,%eax
+jne .LC2399
+fldl -48(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+cmpl $26,%eax
+je .LC2393
+.LC2399:
+addl $4,-20(%ebp)
+.LC2393:
+movsbl -29(%ebp),%edi
+cmpl $26,%edi
+jne .LC2406
+movswl -32(%ebp),%edi
+cmpl $26,%edi
+jne .LC2406
+cmpl $26,-28(%ebp)
+jne .LC2406
+movl -40(%ebp),%edi
+cmpl $26,%edi
+jne .LC2406
+flds -52(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+cmpl $26,%eax
+jne .LC2406
+fldl -48(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+cmpl $26,%eax
+je .LC2400
+.LC2406:
+addl $8,-20(%ebp)
+.LC2400:
+movsbl -29(%ebp),%edi
+cmpl $26,%edi
+jne .LC2415
+movswl -32(%ebp),%edi
+cmpl $26,%edi
+jne .LC2415
+movl -28(%ebp),%edi
+cmpl $26,%edi
+jne .LC2415
+movl -36(%ebp),%edi
+cmpl $26,%edi
+jne .LC2415
+flds .LC847
+fcomps -52(%ebp)
+fstsw %ax
+sahf
+ja .LC2416
+flds -52(%ebp)
+fsubs .LC847
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+leal 0x80000000(%edi),%edi
+movl %edi,-56(%ebp)
+jmp .LC2417
+.LC2416:
+flds -52(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,-56(%ebp)
+.LC2417:
+movl -56(%ebp),%edi
+cmpl $26,%edi
+jne .LC2415
+fldl .LC855
+fcompl -48(%ebp)
+fstsw %ax
+sahf
+ja .LC2418
+fldl -48(%ebp)
+fsubl .LC855
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+leal 0x80000000(%edi),%edi
+movl %edi,-60(%ebp)
+jmp .LC2419
+.LC2418:
+fldl -48(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,-60(%ebp)
+.LC2419:
+movl -60(%ebp),%edi
+cmpl $26,%edi
+je .LC2407
+.LC2415:
+addl $16,-20(%ebp)
+.LC2407:
+movsbl -29(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fldl .LC2377
+fcompp
+fstsw %ax
+sahf
+jne .LC2426
+movswl -32(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fldl .LC2377
+fcompp
+fstsw %ax
+sahf
+jne .LC2426
+fildl -28(%ebp)
+fldl .LC2377
+fcompp
+fstsw %ax
+sahf
+jne .LC2426
+fildl -36(%ebp)
+fldl .LC2377
+fcompp
+fstsw %ax
+sahf
+jne .LC2426
+movl -40(%ebp),%edi
+fldl .LC611
+movl %edi,%esi
+shrl $1,%esi
+pushl %esi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+andl $1,%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+sub $4,%esp
+fstps (%esp)
+flds (%esp)
+addl $4,%esp
+fldl .LC2377
+fcompp
+fstsw %ax
+sahf
+jne .LC2426
+fldl -48(%ebp)
+fldl .LC2377
+fcompp
+fstsw %ax
+sahf
+je .LC2420
+.LC2426:
+addl $32,-20(%ebp)
+.LC2420:
+movsbl -29(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fldl .LC2377
+fcompp
+fstsw %ax
+sahf
+jne .LC2433
+movswl -32(%ebp),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fldl .LC2377
+fcompp
+fstsw %ax
+sahf
+jne .LC2433
+fildl -28(%ebp)
+fldl .LC2377
+fcompp
+fstsw %ax
+sahf
+jne .LC2433
+fildl -36(%ebp)
+fldl .LC2377
+fcompp
+fstsw %ax
+sahf
+jne .LC2433
+movl -40(%ebp),%edi
+fldl .LC611
+movl %edi,%esi
+shrl $1,%esi
+pushl %esi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+andl $1,%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+fldl .LC2377
+fcompp
+fstsw %ax
+sahf
+jne .LC2433
+fldl .LC2377
+fcomps -52(%ebp)
+fstsw %ax
+sahf
+je .LC2427
+.LC2433:
+addl $64,-20(%ebp)
+.LC2427:
+cmpl $0,-20(%ebp)
+je .LC2434
+addl $16,-24(%ebp)
+pushl $16
+pushl $s72er.2356
+call printf
+addl $8,%esp
+.LC2434:
+movl -24(%ebp),%eax
+.LC2355:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf2436:
+.size s72,.Lf2436-s72
+.data
+.align 1
+.type s757er.2438,@object
+s757er.2438:
+.byte 115
+.byte 55
+.byte 53
+.byte 55
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size s757er.2438,11
+.align 1
+.type qs757.2439,@object
+.size qs757.2439,8
+qs757.2439:
+.byte 115
+.byte 55
+.byte 53
+.byte 55
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s757
+.text
+.align 16
+.type s757,@function
+s757:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $148,%esp
+leal qs757.2439,%edi
+movl %edi,-112(%ebp)
+movl 20(%ebp),%edi
+leal 60(%edi),%edi
+movl %edi,-116(%ebp)
+movl $0,-120(%ebp)
+.LC2440:
+.LC2441:
+movl -116(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-116(%ebp)
+movl -112(%ebp),%esi
+leal 1(%esi),%ebx
+movl %ebx,-112(%ebp)
+movb (,%esi),%bl
+movb %bl,(,%edi)
+movsbl %bl,%edi
+cmpl $0,%edi
+jne .LC2440
+movl $40,-124(%ebp)
+movl -124(%ebp),%edi
+leal (,%edi,8),%esi
+leal (,%esi,4),%esi
+cmpl $1280,%esi
+jne .LC2445
+sarl $3,%edi
+sarl $2,%edi
+cmpl $1,%edi
+je .LC2443
+.LC2445:
+incl -120(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC2446
+pushl $1
+pushl $s757er.2438
+call printf
+addl $8,%esp
+.LC2446:
+.LC2443:
+movl $0,-84(%ebp)
+movl $0,-100(%ebp)
+jmp .LC2451
+.LC2448:
+movl $1,-92(%ebp)
+movl -92(%ebp),%edi
+movl 20(%ebp),%esi
+movl 16(%esi),%esi
+movl %esi,%ecx
+subl $1,%ecx
+movl %edi,%eax
+shll %cl,%eax
+movl %eax,-96(%ebp)
+movl $0,-104(%ebp)
+movl -104(%ebp),%edi
+notl %edi
+movl -100(%ebp),%esi
+movl %esi,%ecx
+movl %edi,%eax
+shrl %cl,%eax
+movl %eax,-108(%ebp)
+movl %esi,%ecx
+movl %edi,%eax
+shll %cl,%eax
+movl %eax,-104(%ebp)
+movl $0,-88(%ebp)
+jmp .LC2455
+.LC2452:
+movl -100(%ebp),%edi
+cmpl %edi,-88(%ebp)
+jge .LC2463
+movl $1,-132(%ebp)
+jmp .LC2464
+.LC2463:
+movl $0,-132(%ebp)
+.LC2464:
+movl -92(%ebp),%edi
+andl -104(%ebp),%edi
+cmpl $0,%edi
+jne .LC2465
+movl $1,-136(%ebp)
+jmp .LC2466
+.LC2465:
+movl $0,-136(%ebp)
+.LC2466:
+movl -136(%ebp),%edi
+cmpl %edi,-132(%ebp)
+jne .LC2462
+movl -100(%ebp),%edi
+cmpl %edi,-88(%ebp)
+jge .LC2467
+movl $1,-140(%ebp)
+jmp .LC2468
+.LC2467:
+movl $0,-140(%ebp)
+.LC2468:
+movl -96(%ebp),%edi
+andl -108(%ebp),%edi
+cmpl $0,%edi
+jne .LC2469
+movl $1,-144(%ebp)
+jmp .LC2470
+.LC2469:
+movl $0,-144(%ebp)
+.LC2470:
+movl -144(%ebp),%edi
+cmpl %edi,-140(%ebp)
+je .LC2456
+.LC2462:
+movl $1,-84(%ebp)
+.LC2456:
+movl -92(%ebp),%edi
+leal (,%edi,2),%edi
+movl %edi,-92(%ebp)
+movl -96(%ebp),%edi
+shrl $1,%edi
+movl %edi,-96(%ebp)
+.LC2453:
+incl -88(%ebp)
+.LC2455:
+movl 20(%ebp),%edi
+movl 16(%edi),%edi
+cmpl %edi,-88(%ebp)
+jl .LC2452
+.LC2449:
+incl -100(%ebp)
+.LC2451:
+movl 20(%ebp),%edi
+movl 16(%edi),%edi
+cmpl %edi,-100(%ebp)
+jl .LC2448
+cmpl $0,-84(%ebp)
+je .LC2471
+addl $2,-120(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC2473
+pushl $2
+pushl $s757er.2438
+call printf
+addl $8,%esp
+.LC2473:
+.LC2471:
+movl $3,-16(%ebp)
+movl $2,-12(%ebp)
+movl $1,-8(%ebp)
+movl -12(%ebp),%edi
+cmpl %edi,-16(%ebp)
+jge .LC2481
+movl $1,-136(%ebp)
+jmp .LC2482
+.LC2481:
+movl $0,-136(%ebp)
+.LC2482:
+movl -8(%ebp),%edi
+cmpl %edi,-136(%ebp)
+jge .LC2479
+movl $1,-132(%ebp)
+jmp .LC2480
+.LC2479:
+movl $0,-132(%ebp)
+.LC2480:
+cmpl $1,-132(%ebp)
+je .LC2475
+addl $4,-120(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC2483
+pushl $4
+pushl $s757er.2438
+call printf
+addl $8,%esp
+.LC2483:
+.LC2475:
+leal -76(%ebp),%edi
+leal -80(%ebp),%esi
+cmpl %esi,%edi
+jne .LC2485
+addl $8,-120(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC2488
+pushl $8
+pushl $s757er.2438
+call printf
+addl $8,%esp
+.LC2488:
+.LC2485:
+leal -76(%ebp),%edi
+leal -80(%ebp),%esi
+cmpl %esi,%edi
+jae .LC2490
+movl 20(%ebp),%edi
+cmpl $0,40(%edi)
+je .LC2493
+pushl $.LC2495
+call printf
+addl $4,%esp
+.LC2493:
+.LC2490:
+movl $0,-84(%ebp)
+movl $0,-88(%ebp)
+.LC2496:
+movl -88(%ebp),%edi
+leal -80(%ebp),%esi
+movl $1,(%esi,%edi,4)
+.LC2497:
+incl -88(%ebp)
+cmpl $16,-88(%ebp)
+jl .LC2496
+movl $0,-76(%ebp)
+movl $0,-64(%ebp)
+movl $0,-56(%ebp)
+movl $0,-52(%ebp)
+movl $0,-44(%ebp)
+movl $0,-28(%ebp)
+movl $0,-16(%ebp)
+.LC2506:
+movl $0,-12(%ebp)
+.LC2510:
+movl $0,-8(%ebp)
+.LC2514:
+movl $0,-4(%ebp)
+.LC2518:
+movl -12(%ebp),%edi
+cmpl %edi,-16(%ebp)
+jge .LC2529
+movl $1,-144(%ebp)
+jmp .LC2530
+.LC2529:
+movl $0,-144(%ebp)
+.LC2530:
+movl -4(%ebp),%edi
+cmpl %edi,-8(%ebp)
+jge .LC2531
+movl $1,-148(%ebp)
+jmp .LC2532
+.LC2531:
+movl $0,-148(%ebp)
+.LC2532:
+movl -148(%ebp),%edi
+cmpl %edi,-144(%ebp)
+jne .LC2527
+movl $1,-140(%ebp)
+jmp .LC2528
+.LC2527:
+movl $0,-140(%ebp)
+.LC2528:
+movl -16(%ebp),%edi
+movl -12(%ebp),%esi
+leal (,%esi,4),%esi
+leal (%esi,%edi,8),%edi
+movl -8(%ebp),%esi
+leal (,%esi,2),%esi
+leal (%esi,%edi),%edi
+movl -4(%ebp),%esi
+leal (%esi,%edi),%edi
+leal -80(%ebp),%esi
+movl (%esi,%edi,4),%edi
+cmpl %edi,-140(%ebp)
+je .LC2522
+movl $1,-84(%ebp)
+.LC2522:
+.LC2519:
+incl -4(%ebp)
+cmpl $2,-4(%ebp)
+jl .LC2518
+.LC2515:
+incl -8(%ebp)
+cmpl $2,-8(%ebp)
+jl .LC2514
+.LC2511:
+incl -12(%ebp)
+cmpl $2,-12(%ebp)
+jl .LC2510
+.LC2507:
+incl -16(%ebp)
+cmpl $2,-16(%ebp)
+jl .LC2506
+cmpl $0,-84(%ebp)
+je .LC2533
+addl $16,-120(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC2535
+pushl $16
+pushl $s757er.2438
+call printf
+addl $8,%esp
+.LC2535:
+.LC2533:
+movl $0,-128(%ebp)
+movl -128(%ebp),%edi
+cmpl $0,%edi
+je .LC2537
+addl $32,-120(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC2539
+pushl $32
+pushl $s757er.2438
+call printf
+addl $8,%esp
+.LC2539:
+.LC2537:
+movl -120(%ebp),%eax
+.LC2437:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf2541:
+.size s757,.Lf2541-s757
+.data
+.align 1
+.type fl.2543,@object
+fl.2543:
+.byte 76
+.byte 111
+.byte 99
+.byte 97
+.byte 108
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 37
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.size fl.2543,17
+.align 1
+.type s7813er.2544,@object
+s7813er.2544:
+.byte 115
+.byte 55
+.byte 56
+.byte 49
+.byte 51
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size s7813er.2544,12
+.align 1
+.type qs7813.2545,@object
+.size qs7813.2545,8
+qs7813.2545:
+.byte 115
+.byte 55
+.byte 56
+.byte 49
+.byte 51
+.byte 32
+.byte 32
+.byte 0
+.globl s7813
+.text
+.align 16
+.type s7813,@function
+s7813:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $88,%esp
+leal qs7813.2545,%edi
+movl %edi,-24(%ebp)
+movl 20(%ebp),%edi
+leal 60(%edi),%esi
+movl %esi,-28(%ebp)
+movl $0,-8(%ebp)
+movl $0,-32(%ebp)
+movl 48(%edi),%edi
+movl %edi,-4(%ebp)
+.LC2546:
+.LC2547:
+movl -28(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-28(%ebp)
+movl -24(%ebp),%esi
+leal 1(%esi),%ebx
+movl %ebx,-24(%ebp)
+movb (,%esi),%bl
+movb %bl,(,%edi)
+movsbl %bl,%edi
+cmpl $0,%edi
+jne .LC2546
+jmp .LC2549
+movl $1,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2551
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2551:
+.LC2549:
+jmp .LC2553
+movl $2,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2555
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2555:
+.LC2553:
+jmp .LC2557
+movl $3,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2559
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2559:
+.LC2557:
+jmp .LC2561
+movl $4,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2563
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2563:
+.LC2561:
+jmp .LC2565
+movl $5,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2567
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2567:
+.LC2565:
+jmp .LC2569
+movl $6,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2571
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2571:
+.LC2569:
+jmp .LC2573
+movl $7,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2575
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2575:
+.LC2573:
+jmp .LC2577
+movl $8,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2579
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2579:
+.LC2577:
+jmp .LC2581
+movl $9,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2583
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2583:
+.LC2581:
+jmp .LC2585
+movl $10,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2587
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2587:
+.LC2585:
+jmp .LC2589
+movl $11,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2591
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2591:
+.LC2589:
+jmp .LC2593
+movl $12,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2595
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2595:
+.LC2593:
+jmp .LC2597
+movl $13,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2599
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2599:
+.LC2597:
+jmp .LC2601
+movl $14,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2603
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2603:
+.LC2601:
+jmp .LC2605
+movl $15,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2607
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2607:
+.LC2605:
+jmp .LC2609
+movl $16,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2611
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2611:
+.LC2609:
+jmp .LC2613
+movl $17,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2615
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2615:
+.LC2613:
+jmp .LC2617
+movl $18,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2619
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2619:
+.LC2617:
+jmp .LC2621
+movl $16,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2623
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2623:
+.LC2621:
+jmp .LC2625
+movl $20,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2627
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2627:
+.LC2625:
+jmp .LC2629
+movl $21,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2631
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2631:
+.LC2629:
+jmp .LC2633
+movl $22,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2635
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2635:
+.LC2633:
+jmp .LC2637
+movl $23,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2639
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2639:
+.LC2637:
+jmp .LC2641
+movl $24,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2643
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2643:
+.LC2641:
+jmp .LC2645
+movl $25,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2647
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2647:
+.LC2645:
+jmp .LC2649
+movl $26,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2651
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2651:
+.LC2649:
+jmp .LC2653
+movl $27,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2655
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2655:
+.LC2653:
+jmp .LC2657
+movl $28,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2659
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2659:
+.LC2657:
+jmp .LC2661
+movl $26,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2663
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2663:
+.LC2661:
+jmp .LC2665
+movl $30,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2667
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2667:
+.LC2665:
+jmp .LC2669
+movl $31,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2671
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2671:
+.LC2669:
+jmp .LC2673
+movl $32,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2675
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2675:
+.LC2673:
+jmp .LC2677
+movl $33,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2679
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2679:
+.LC2677:
+jmp .LC2681
+movl $34,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2683
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2683:
+.LC2681:
+jmp .LC2685
+movl $35,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2687
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2687:
+.LC2685:
+jmp .LC2689
+movl $36,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2691
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2691:
+.LC2689:
+jmp .LC2693
+movl $37,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2695
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2695:
+.LC2693:
+jmp .LC2697
+movl $38,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2699
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2699:
+.LC2697:
+jmp .LC2701
+movl $39,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2703
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2703:
+.LC2701:
+jmp .LC2705
+movl $40,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2707
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2707:
+.LC2705:
+jmp .LC2709
+movl $41,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2711
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2711:
+.LC2709:
+jmp .LC2713
+movl $42,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2715
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2715:
+.LC2713:
+jmp .LC2717
+movl $43,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2719
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2719:
+.LC2717:
+jmp .LC2721
+movl $44,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2723
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2723:
+.LC2721:
+jmp .LC2725
+movl $45,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2727
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2727:
+.LC2725:
+jmp .LC2729
+movl $46,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2731
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2731:
+.LC2729:
+jmp .LC2733
+movl $47,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2735
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2735:
+.LC2733:
+jmp .LC2737
+movl $48,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2739
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2739:
+.LC2737:
+jmp .LC2741
+movl $49,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2743
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2743:
+.LC2741:
+jmp .LC2745
+movl $50,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2747
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2747:
+.LC2745:
+jmp .LC2749
+movl $51,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2751
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2751:
+.LC2749:
+jmp .LC2753
+movl $52,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2755
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2755:
+.LC2753:
+jmp .LC2757
+movl $53,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2759
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2759:
+.LC2757:
+jmp .LC2761
+movl $54,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2763
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2763:
+.LC2761:
+jmp .LC2765
+movl $55,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2767
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2767:
+.LC2765:
+jmp .LC2769
+movl $56,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2771
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2771:
+.LC2769:
+jmp .LC2773
+movl $57,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2775
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2775:
+.LC2773:
+jmp .LC2777
+movl $58,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2779
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2779:
+.LC2777:
+jmp .LC2781
+movl $56,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2783
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2783:
+.LC2781:
+jmp .LC2785
+movl $60,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2787
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2787:
+.LC2785:
+jmp .LC2789
+movl $61,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2791
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2791:
+.LC2789:
+jmp .LC2793
+movl $62,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2795
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2795:
+.LC2793:
+jmp .LC2797
+movl $63,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2799
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2799:
+.LC2797:
+jmp .LC2801
+movl $64,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2803
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2803:
+.LC2801:
+jmp .LC2805
+movl $65,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2807
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2807:
+.LC2805:
+jmp .LC2809
+movl $66,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2811
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2811:
+.LC2809:
+jmp .LC2813
+movl $67,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2815
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2815:
+.LC2813:
+jmp .LC2817
+movl $68,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2819
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2819:
+.LC2817:
+jmp .LC2821
+movl $69,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2823
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2823:
+.LC2821:
+jmp .LC2825
+movl $70,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2827
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2827:
+.LC2825:
+jmp .LC2829
+movl $71,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2831
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2831:
+.LC2829:
+jmp .LC2833
+movl $72,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2835
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2835:
+.LC2833:
+jmp .LC2837
+movl $73,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2839
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2839:
+.LC2837:
+jmp .LC2841
+movl $74,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2843
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2843:
+.LC2841:
+jmp .LC2845
+movl $75,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2847
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2847:
+.LC2845:
+cmpl $0,-8(%ebp)
+je .LC2849
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC2851
+pushl $1
+pushl $s7813er.2544
+call printf
+addl $8,%esp
+.LC2851:
+incl -32(%ebp)
+.LC2849:
+movl $0,-8(%ebp)
+movl $0,-16(%ebp)
+movl $0,-12(%ebp)
+movl -12(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-12(%ebp)
+cmpl $0,%edi
+je .LC2854
+movl -16(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-16(%ebp)
+cmpl $0,%edi
+je .LC2854
+movl $1,-44(%ebp)
+jmp .LC2855
+.LC2854:
+movl $0,-44(%ebp)
+.LC2855:
+movl -44(%ebp),%edi
+movl %edi,-20(%ebp)
+cmpl $1,-12(%ebp)
+je .LC2856
+movl $1,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2858
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2858:
+.LC2856:
+cmpl $0,-16(%ebp)
+je .LC2860
+movl $2,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2862
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2862:
+.LC2860:
+cmpl $0,-20(%ebp)
+je .LC2864
+movl $3,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2866
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2866:
+.LC2864:
+cmpl $0,-12(%ebp)
+je .LC2869
+movl -16(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-16(%ebp)
+cmpl $0,%edi
+je .LC2869
+movl $1,-48(%ebp)
+jmp .LC2870
+.LC2869:
+movl $0,-48(%ebp)
+.LC2870:
+movl -48(%ebp),%edi
+movl %edi,-20(%ebp)
+cmpl $1,-12(%ebp)
+je .LC2871
+movl $4,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2873
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2873:
+.LC2871:
+cmpl $1,-16(%ebp)
+je .LC2875
+movl $5,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2877
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2877:
+.LC2875:
+cmpl $0,-20(%ebp)
+je .LC2879
+movl $6,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2881
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2881:
+.LC2879:
+movl -12(%ebp),%edi
+movl %edi,%esi
+subl $1,%esi
+movl %esi,-12(%ebp)
+cmpl $0,%edi
+je .LC2884
+cmpl $0,-16(%ebp)
+je .LC2884
+movl $1,-52(%ebp)
+jmp .LC2885
+.LC2884:
+movl $0,-52(%ebp)
+.LC2885:
+movl -52(%ebp),%edi
+movl %edi,-20(%ebp)
+cmpl $0,-12(%ebp)
+je .LC2886
+movl $7,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2888
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2888:
+.LC2886:
+cmpl $1,-16(%ebp)
+je .LC2890
+movl $8,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2892
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2892:
+.LC2890:
+cmpl $1,-20(%ebp)
+je .LC2894
+movl $9,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2896
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2896:
+.LC2894:
+cmpl $0,-12(%ebp)
+je .LC2899
+movl -16(%ebp),%edi
+movl %edi,%esi
+subl $1,%esi
+movl %esi,-16(%ebp)
+cmpl $0,%edi
+je .LC2899
+movl $1,-56(%ebp)
+jmp .LC2900
+.LC2899:
+movl $0,-56(%ebp)
+.LC2900:
+movl -56(%ebp),%edi
+movl %edi,-20(%ebp)
+cmpl $0,-12(%ebp)
+je .LC2901
+movl $10,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2903
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2903:
+.LC2901:
+cmpl $1,-16(%ebp)
+je .LC2905
+movl $11,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2907
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2907:
+.LC2905:
+cmpl $0,-20(%ebp)
+je .LC2909
+movl $12,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2911
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2911:
+.LC2909:
+cmpl $0,-8(%ebp)
+je .LC2913
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC2915
+pushl $2
+pushl $s7813er.2544
+call printf
+addl $8,%esp
+.LC2915:
+addl $2,-32(%ebp)
+.LC2913:
+movl $0,-8(%ebp)
+movl $0,-16(%ebp)
+movl $0,-12(%ebp)
+movl -12(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-12(%ebp)
+cmpl $0,%edi
+jne .LC2920
+cmpl $0,-16(%ebp)
+je .LC2918
+.LC2920:
+movl $1,-60(%ebp)
+jmp .LC2919
+.LC2918:
+movl $0,-60(%ebp)
+.LC2919:
+movl -60(%ebp),%edi
+movl %edi,-20(%ebp)
+cmpl $1,-12(%ebp)
+je .LC2921
+movl $1,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2923
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2923:
+.LC2921:
+cmpl $0,-16(%ebp)
+je .LC2925
+movl $2,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2927
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2927:
+.LC2925:
+cmpl $0,-20(%ebp)
+je .LC2929
+movl $3,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2931
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2931:
+.LC2929:
+movl -16(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-16(%ebp)
+cmpl $0,%edi
+jne .LC2936
+cmpl $0,-12(%ebp)
+je .LC2934
+.LC2936:
+movl $1,-64(%ebp)
+jmp .LC2935
+.LC2934:
+movl $0,-64(%ebp)
+.LC2935:
+movl -64(%ebp),%edi
+movl %edi,-20(%ebp)
+cmpl $1,-12(%ebp)
+je .LC2937
+movl $4,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2939
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2939:
+.LC2937:
+cmpl $1,-16(%ebp)
+je .LC2941
+movl $5,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2943
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2943:
+.LC2941:
+cmpl $1,-20(%ebp)
+je .LC2945
+movl $6,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2947
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2947:
+.LC2945:
+movl -12(%ebp),%edi
+movl %edi,%esi
+subl $1,%esi
+movl %esi,-12(%ebp)
+cmpl $0,%edi
+jne .LC2952
+movl -16(%ebp),%edi
+movl %edi,%esi
+subl $1,%esi
+movl %esi,-16(%ebp)
+cmpl $0,%edi
+je .LC2950
+.LC2952:
+movl $1,-68(%ebp)
+jmp .LC2951
+.LC2950:
+movl $0,-68(%ebp)
+.LC2951:
+movl -68(%ebp),%edi
+movl %edi,-20(%ebp)
+cmpl $0,-12(%ebp)
+je .LC2953
+movl $7,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2955
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2955:
+.LC2953:
+cmpl $1,-16(%ebp)
+je .LC2957
+movl $8,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2959
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2959:
+.LC2957:
+cmpl $1,-20(%ebp)
+je .LC2961
+movl $9,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2963
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2963:
+.LC2961:
+cmpl $0,-12(%ebp)
+jne .LC2968
+movl -16(%ebp),%edi
+movl %edi,%esi
+subl $1,%esi
+movl %esi,-16(%ebp)
+cmpl $0,%edi
+je .LC2966
+.LC2968:
+movl $1,-72(%ebp)
+jmp .LC2967
+.LC2966:
+movl $0,-72(%ebp)
+.LC2967:
+movl -72(%ebp),%edi
+movl %edi,-20(%ebp)
+cmpl $0,-12(%ebp)
+je .LC2969
+movl $10,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2971
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2971:
+.LC2969:
+cmpl $0,-16(%ebp)
+je .LC2973
+movl $11,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2975
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2975:
+.LC2973:
+cmpl $1,-20(%ebp)
+je .LC2977
+movl $12,-8(%ebp)
+cmpl $0,-4(%ebp)
+je .LC2979
+pushl -8(%ebp)
+pushl $fl.2543
+call printf
+addl $8,%esp
+.LC2979:
+.LC2977:
+cmpl $0,-8(%ebp)
+je .LC2981
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC2983
+pushl $4
+pushl $s7813er.2544
+call printf
+addl $8,%esp
+.LC2983:
+addl $4,-32(%ebp)
+.LC2981:
+movl $0,-16(%ebp)
+movl $0,-12(%ebp)
+movl $0,-36(%ebp)
+movl $1,-40(%ebp)
+cmpl $0,-40(%ebp)
+je .LC2987
+movl -36(%ebp),%edi
+movl %edi,-76(%ebp)
+jmp .LC2988
+.LC2987:
+cmpl $0,-40(%ebp)
+je .LC2989
+movl -12(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-12(%ebp)
+movl %edi,-80(%ebp)
+jmp .LC2990
+.LC2989:
+movl -16(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-16(%ebp)
+movl %edi,-80(%ebp)
+.LC2990:
+movl -80(%ebp),%edi
+movl %edi,-76(%ebp)
+.LC2988:
+movl -76(%ebp),%edi
+movl %edi,-20(%ebp)
+cmpl $0,-20(%ebp)
+jne .LC2994
+cmpl $0,-12(%ebp)
+jne .LC2994
+cmpl $0,-16(%ebp)
+je .LC2991
+.LC2994:
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC2995
+pushl $8
+pushl $s7813er.2544
+call printf
+addl $8,%esp
+.LC2995:
+addl $8,-32(%ebp)
+.LC2991:
+cmpl $0,-40(%ebp)
+je .LC3002
+movl -36(%ebp),%edi
+movl %edi,-84(%ebp)
+jmp .LC3003
+.LC3002:
+movl $1,-84(%ebp)
+.LC3003:
+cmpl $0,-84(%ebp)
+jne .LC3001
+cmpl $0,-36(%ebp)
+je .LC3004
+movl $1,-88(%ebp)
+jmp .LC3005
+.LC3004:
+movl -36(%ebp),%edi
+movl %edi,-88(%ebp)
+.LC3005:
+cmpl $0,-88(%ebp)
+je .LC2997
+.LC3001:
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC3006
+pushl $16
+pushl $s7813er.2544
+call printf
+addl $8,%esp
+.LC3006:
+addl $16,-32(%ebp)
+.LC2997:
+movl -32(%ebp),%eax
+.LC2542:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf3008:
+.size s7813,.Lf3008-s7813
+.data
+.align 1
+.type s81er.3010,@object
+s81er.3010:
+.byte 115
+.byte 56
+.byte 49
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size s81er.3010,10
+.align 1
+.type qs81.3011,@object
+.size qs81.3011,8
+qs81.3011:
+.byte 115
+.byte 56
+.byte 49
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.align 1
+.type badtest.3012,@object
+badtest.3012:
+.byte 82
+.byte 101
+.byte 103
+.byte 105
+.byte 115
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 99
+.byte 111
+.byte 117
+.byte 110
+.byte 116
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 37
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 117
+.byte 110
+.byte 114
+.byte 101
+.byte 108
+.byte 105
+.byte 97
+.byte 98
+.byte 108
+.byte 101
+.byte 46
+.byte 10
+.byte 0
+.size badtest.3012,38
+.align 1
+.type goodtest.3013,@object
+goodtest.3013:
+.byte 37
+.byte 100
+.byte 32
+.byte 114
+.byte 101
+.byte 103
+.byte 105
+.byte 115
+.byte 116
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 97
+.byte 115
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 101
+.byte 100
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 37
+.byte 115
+.byte 32
+.byte 118
+.byte 97
+.byte 114
+.byte 105
+.byte 97
+.byte 98
+.byte 108
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.size goodtest.3013,40
+.globl s81
+.text
+.align 16
+.type s81,@function
+s81:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $56,%esp
+movl $0,-56(%ebp)
+movl $0,-44(%ebp)
+movl $0,-48(%ebp)
+movl $0,-52(%ebp)
+leal qs81.3011,%edi
+movl %edi,-36(%ebp)
+movl 20(%ebp),%edi
+leal 60(%edi),%edi
+movl %edi,-40(%ebp)
+.LC3014:
+.LC3015:
+movl -40(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-40(%ebp)
+movl -36(%ebp),%esi
+leal 1(%esi),%ebx
+movl %ebx,-36(%ebp)
+movb (,%esi),%bl
+movb %bl,(,%edi)
+movsbl %bl,%edi
+cmpl $0,%edi
+jne .LC3014
+movl $1,-16(%ebp)
+movl $0,-20(%ebp)
+.LC3017:
+movl -16(%ebp),%edi
+movl %edi,%ebx
+movb %bl,-1(%ebp)
+movb %bl,-21(%ebp)
+leal -16(%ebp),%esi
+movl %esi,-8(%ebp)
+leal -16(%ebp),%esi
+movl %esi,-28(%ebp)
+movl %edi,-12(%ebp)
+movl %edi,-32(%ebp)
+movsbl -1(%ebp),%edi
+movsbl -21(%ebp),%esi
+cmpl %esi,%edi
+je .LC3021
+movl $1,-44(%ebp)
+.LC3021:
+movl -8(%ebp),%edi
+movl -28(%ebp),%esi
+cmpl %esi,%edi
+je .LC3023
+movl $1,-48(%ebp)
+.LC3023:
+movl -32(%ebp),%edi
+cmpl %edi,-12(%ebp)
+je .LC3025
+movl $1,-52(%ebp)
+.LC3025:
+sall $1,-16(%ebp)
+.LC3018:
+incl -20(%ebp)
+cmpl $50,-20(%ebp)
+jl .LC3017
+cmpl $0,-44(%ebp)
+je .LC3027
+incl -56(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC3029
+pushl $1
+pushl $s81er.3010
+call printf
+addl $8,%esp
+.LC3029:
+.LC3027:
+cmpl $0,-48(%ebp)
+je .LC3031
+addl $2,-56(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC3033
+pushl $2
+pushl $s81er.3010
+call printf
+addl $8,%esp
+.LC3033:
+.LC3031:
+cmpl $0,-52(%ebp)
+je .LC3035
+addl $4,-56(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC3037
+pushl $4
+pushl $s81er.3010
+call printf
+addl $8,%esp
+.LC3037:
+.LC3035:
+call regc
+movl %eax,-16(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,40(%edi)
+je .LC3039
+cmpl $0,-16(%ebp)
+jge .LC3041
+pushl $.LC434
+pushl $badtest.3012
+call printf
+addl $8,%esp
+jmp .LC3042
+.LC3041:
+pushl $.LC434
+pushl -16(%ebp)
+pushl $goodtest.3013
+call printf
+addl $12,%esp
+.LC3042:
+.LC3039:
+call regp
+movl %eax,-16(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,40(%edi)
+je .LC3043
+cmpl $0,-16(%ebp)
+jge .LC3045
+pushl $.LC3047
+pushl $badtest.3012
+call printf
+addl $8,%esp
+jmp .LC3046
+.LC3045:
+pushl $.LC3047
+pushl -16(%ebp)
+pushl $goodtest.3013
+call printf
+addl $12,%esp
+.LC3046:
+.LC3043:
+call regi
+movl %eax,-16(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,40(%edi)
+je .LC3048
+cmpl $0,-16(%ebp)
+jge .LC3050
+pushl $.LC435
+pushl $badtest.3012
+call printf
+addl $8,%esp
+jmp .LC3051
+.LC3050:
+pushl $.LC435
+pushl -16(%ebp)
+pushl $goodtest.3013
+call printf
+addl $12,%esp
+.LC3051:
+.LC3048:
+movl -56(%ebp),%eax
+.LC3009:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf3052:
+.size s81,.Lf3052-s81
+.globl regc
+.align 16
+.type regc,@function
+regc:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $148,%esp
+movb $0,-138(%ebp)
+movb $1,-117(%ebp)
+movb $2,-118(%ebp)
+movb $3,-119(%ebp)
+movb $4,-1(%ebp)
+movb $5,-120(%ebp)
+movb $6,-2(%ebp)
+movb $7,-121(%ebp)
+movb $8,-3(%ebp)
+movb $9,-122(%ebp)
+movb $10,-4(%ebp)
+movb $11,-123(%ebp)
+movb $12,-5(%ebp)
+movb $13,-124(%ebp)
+movb $14,-6(%ebp)
+movb $15,-125(%ebp)
+movb $16,-7(%ebp)
+movb $17,-126(%ebp)
+movb $18,-8(%ebp)
+movb $19,-127(%ebp)
+movb $20,-9(%ebp)
+movb $21,-128(%ebp)
+movb $22,-10(%ebp)
+movb $23,-129(%ebp)
+movb $24,-11(%ebp)
+movb $25,-130(%ebp)
+movb $26,-12(%ebp)
+movb $27,-131(%ebp)
+movb $28,-13(%ebp)
+movb $29,-132(%ebp)
+movb $30,-14(%ebp)
+movb $31,-133(%ebp)
+movb $32,-15(%ebp)
+movb $33,-134(%ebp)
+movb $34,-16(%ebp)
+movb $35,-135(%ebp)
+movb $36,-136(%ebp)
+movb $37,-137(%ebp)
+movb $38,-139(%ebp)
+leal -117(%ebp),%edi
+leal -138(%ebp),%esi
+movl %edi,%ebx
+subl %esi,%ebx
+movl %ebx,%esi
+movl %esi,-104(%ebp)
+leal -118(%ebp),%esi
+subl %edi,%esi
+movl %esi,%edi
+movl %edi,-100(%ebp)
+leal -119(%ebp),%edi
+leal -118(%ebp),%esi
+subl %esi,%edi
+movl %edi,-96(%ebp)
+leal -120(%ebp),%edi
+leal -119(%ebp),%esi
+subl %esi,%edi
+movl %edi,-92(%ebp)
+leal -121(%ebp),%edi
+leal -120(%ebp),%esi
+subl %esi,%edi
+movl %edi,-88(%ebp)
+leal -122(%ebp),%edi
+leal -121(%ebp),%esi
+subl %esi,%edi
+movl %edi,-84(%ebp)
+leal -123(%ebp),%edi
+leal -122(%ebp),%esi
+subl %esi,%edi
+movl %edi,-80(%ebp)
+leal -124(%ebp),%edi
+leal -123(%ebp),%esi
+subl %esi,%edi
+movl %edi,-76(%ebp)
+leal -125(%ebp),%edi
+leal -124(%ebp),%esi
+subl %esi,%edi
+movl %edi,-72(%ebp)
+leal -126(%ebp),%edi
+leal -125(%ebp),%esi
+subl %esi,%edi
+movl %edi,-68(%ebp)
+leal -127(%ebp),%edi
+leal -126(%ebp),%esi
+subl %esi,%edi
+movl %edi,-64(%ebp)
+leal -128(%ebp),%edi
+leal -127(%ebp),%esi
+subl %esi,%edi
+movl %edi,-60(%ebp)
+leal -129(%ebp),%edi
+leal -128(%ebp),%esi
+subl %esi,%edi
+movl %edi,-56(%ebp)
+leal -130(%ebp),%edi
+leal -129(%ebp),%esi
+subl %esi,%edi
+movl %edi,-52(%ebp)
+leal -131(%ebp),%edi
+leal -130(%ebp),%esi
+subl %esi,%edi
+movl %edi,-48(%ebp)
+leal -132(%ebp),%edi
+leal -131(%ebp),%esi
+subl %esi,%edi
+movl %edi,-44(%ebp)
+leal -133(%ebp),%edi
+leal -132(%ebp),%esi
+subl %esi,%edi
+movl %edi,-40(%ebp)
+leal -134(%ebp),%edi
+leal -133(%ebp),%esi
+subl %esi,%edi
+movl %edi,-36(%ebp)
+leal -135(%ebp),%edi
+leal -134(%ebp),%esi
+subl %esi,%edi
+movl %edi,-32(%ebp)
+leal -136(%ebp),%edi
+leal -135(%ebp),%esi
+subl %esi,%edi
+movl %edi,-28(%ebp)
+leal -137(%ebp),%edi
+leal -136(%ebp),%esi
+subl %esi,%edi
+movl %edi,-24(%ebp)
+leal -139(%ebp),%edi
+leal -137(%ebp),%esi
+subl %esi,%edi
+movl %edi,-20(%ebp)
+movl -104(%ebp),%edi
+movl %edi,-116(%ebp)
+movl $1,-112(%ebp)
+movl $0,-108(%ebp)
+.LC3075:
+movl -112(%ebp),%edi
+cmpl $1,%edi
+je .LC3081
+cmpl $2,%edi
+je .LC3084
+cmpl $3,%edi
+je .LC3089
+jmp .LC3079
+.LC3081:
+movl -108(%ebp),%edi
+leal -104(%ebp),%esi
+movl -116(%ebp),%ebx
+cmpl %ebx,(%esi,%edi,4)
+je .LC3080
+movl -108(%ebp),%edi
+leal -104(%ebp),%esi
+movl (%esi,%edi,4),%edi
+movl %edi,-148(%ebp)
+movl $2,-112(%ebp)
+movl $1,-144(%ebp)
+jmp .LC3080
+.LC3084:
+movl -108(%ebp),%edi
+leal -104(%ebp),%esi
+movl -116(%ebp),%ebx
+cmpl %ebx,(%esi,%edi,4)
+jne .LC3085
+movl $3,-112(%ebp)
+jmp .LC3080
+.LC3085:
+movl -108(%ebp),%edi
+leal -104(%ebp),%esi
+movl -148(%ebp),%ebx
+cmpl %ebx,(%esi,%edi,4)
+jne .LC3087
+incl -144(%ebp)
+jmp .LC3080
+.LC3087:
+movl $4,-112(%ebp)
+jmp .LC3080
+.LC3089:
+movl -108(%ebp),%edi
+leal -104(%ebp),%esi
+movl -116(%ebp),%ebx
+cmpl %ebx,(%esi,%edi,4)
+je .LC3080
+movl $4,-112(%ebp)
+.LC3079:
+.LC3080:
+.LC3076:
+incl -108(%ebp)
+cmpl $22,-108(%ebp)
+jl .LC3075
+cmpl $3,-112(%ebp)
+jne .LC3092
+movl $16,%edi
+movl %edi,%eax
+subl -144(%ebp),%eax
+jmp .LC3053
+.LC3092:
+movl $-1,%eax
+.LC3053:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf3094:
+.size regc,.Lf3094-regc
+.globl regi
+.align 16
+.type regi,@function
+regi:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $264,%esp
+movl $0,-252(%ebp)
+movl $1,-168(%ebp)
+movl $2,-172(%ebp)
+movl $3,-176(%ebp)
+movl $4,-4(%ebp)
+movl $5,-180(%ebp)
+movl $6,-8(%ebp)
+movl $7,-184(%ebp)
+movl $8,-12(%ebp)
+movl $9,-188(%ebp)
+movl $10,-16(%ebp)
+movl $11,-192(%ebp)
+movl $12,-20(%ebp)
+movl $13,-196(%ebp)
+movl $14,-24(%ebp)
+movl $15,-200(%ebp)
+movl $16,-28(%ebp)
+movl $17,-204(%ebp)
+movl $18,-32(%ebp)
+movl $19,-208(%ebp)
+movl $20,-36(%ebp)
+movl $21,-212(%ebp)
+movl $22,-40(%ebp)
+movl $23,-216(%ebp)
+movl $24,-44(%ebp)
+movl $25,-220(%ebp)
+movl $26,-48(%ebp)
+movl $27,-224(%ebp)
+movl $28,-52(%ebp)
+movl $29,-228(%ebp)
+movl $30,-56(%ebp)
+movl $31,-232(%ebp)
+movl $32,-60(%ebp)
+movl $33,-236(%ebp)
+movl $34,-64(%ebp)
+movl $35,-240(%ebp)
+movl $36,-244(%ebp)
+movl $37,-248(%ebp)
+movl $38,-256(%ebp)
+leal -168(%ebp),%edi
+movl $4,%esi
+leal -252(%ebp),%ebx
+movl %edi,%edx
+subl %ebx,%edx
+movl %edx,%eax
+movl %esi,%ecx
+cdq
+idivl %ecx
+movl %eax,-152(%ebp)
+leal -172(%ebp),%ebx
+subl %edi,%ebx
+movl %ebx,%eax
+movl %esi,%ecx
+cdq
+idivl %ecx
+movl %eax,-148(%ebp)
+leal -176(%ebp),%edi
+leal -172(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-144(%ebp)
+leal -180(%ebp),%edi
+leal -176(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-140(%ebp)
+leal -184(%ebp),%edi
+leal -180(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-136(%ebp)
+leal -188(%ebp),%edi
+leal -184(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-132(%ebp)
+leal -192(%ebp),%edi
+leal -188(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-128(%ebp)
+leal -196(%ebp),%edi
+leal -192(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-124(%ebp)
+leal -200(%ebp),%edi
+leal -196(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-120(%ebp)
+leal -204(%ebp),%edi
+leal -200(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-116(%ebp)
+leal -208(%ebp),%edi
+leal -204(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-112(%ebp)
+leal -212(%ebp),%edi
+leal -208(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-108(%ebp)
+leal -216(%ebp),%edi
+leal -212(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-104(%ebp)
+leal -220(%ebp),%edi
+leal -216(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-100(%ebp)
+leal -224(%ebp),%edi
+leal -220(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-96(%ebp)
+leal -228(%ebp),%edi
+leal -224(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-92(%ebp)
+leal -232(%ebp),%edi
+leal -228(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-88(%ebp)
+leal -236(%ebp),%edi
+leal -232(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-84(%ebp)
+leal -240(%ebp),%edi
+leal -236(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-80(%ebp)
+leal -244(%ebp),%edi
+leal -240(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-76(%ebp)
+leal -248(%ebp),%edi
+leal -244(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-72(%ebp)
+leal -256(%ebp),%edi
+leal -248(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-68(%ebp)
+movl -152(%ebp),%edi
+movl %edi,-164(%ebp)
+movl $1,-160(%ebp)
+movl $0,-156(%ebp)
+.LC3117:
+movl -160(%ebp),%edi
+cmpl $1,%edi
+je .LC3123
+cmpl $2,%edi
+je .LC3126
+cmpl $3,%edi
+je .LC3131
+jmp .LC3121
+.LC3123:
+movl -156(%ebp),%edi
+leal -152(%ebp),%esi
+movl -164(%ebp),%ebx
+cmpl %ebx,(%esi,%edi,4)
+je .LC3122
+movl -156(%ebp),%edi
+leal -152(%ebp),%esi
+movl (%esi,%edi,4),%edi
+movl %edi,-264(%ebp)
+movl $2,-160(%ebp)
+movl $1,-260(%ebp)
+jmp .LC3122
+.LC3126:
+movl -156(%ebp),%edi
+leal -152(%ebp),%esi
+movl -164(%ebp),%ebx
+cmpl %ebx,(%esi,%edi,4)
+jne .LC3127
+movl $3,-160(%ebp)
+jmp .LC3122
+.LC3127:
+movl -156(%ebp),%edi
+leal -152(%ebp),%esi
+movl -264(%ebp),%ebx
+cmpl %ebx,(%esi,%edi,4)
+jne .LC3129
+incl -260(%ebp)
+jmp .LC3122
+.LC3129:
+movl $4,-160(%ebp)
+jmp .LC3122
+.LC3131:
+movl -156(%ebp),%edi
+leal -152(%ebp),%esi
+movl -164(%ebp),%ebx
+cmpl %ebx,(%esi,%edi,4)
+je .LC3122
+movl $4,-160(%ebp)
+.LC3121:
+.LC3122:
+.LC3118:
+incl -156(%ebp)
+cmpl $22,-156(%ebp)
+jl .LC3117
+cmpl $3,-160(%ebp)
+jne .LC3134
+movl $16,%edi
+movl %edi,%eax
+subl -260(%ebp),%eax
+jmp .LC3095
+.LC3134:
+movl $-1,%eax
+.LC3095:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf3136:
+.size regi,.Lf3136-regi
+.globl regp
+.align 16
+.type regp,@function
+regp:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $264,%esp
+leal -252(%ebp),%edi
+movl %edi,-252(%ebp)
+leal -228(%ebp),%edi
+movl %edi,-228(%ebp)
+leal -232(%ebp),%edi
+movl %edi,-232(%ebp)
+leal -236(%ebp),%edi
+movl %edi,-236(%ebp)
+leal -164(%ebp),%edi
+movl %edi,-4(%ebp)
+leal -164(%ebp),%edi
+movl %edi,-164(%ebp)
+leal -168(%ebp),%edi
+movl %edi,-8(%ebp)
+leal -168(%ebp),%edi
+movl %edi,-168(%ebp)
+leal -172(%ebp),%edi
+movl %edi,-12(%ebp)
+leal -172(%ebp),%edi
+movl %edi,-172(%ebp)
+leal -176(%ebp),%edi
+movl %edi,-16(%ebp)
+leal -176(%ebp),%edi
+movl %edi,-176(%ebp)
+leal -180(%ebp),%edi
+movl %edi,-20(%ebp)
+leal -180(%ebp),%edi
+movl %edi,-180(%ebp)
+leal -184(%ebp),%edi
+movl %edi,-24(%ebp)
+leal -184(%ebp),%edi
+movl %edi,-184(%ebp)
+leal -188(%ebp),%edi
+movl %edi,-28(%ebp)
+leal -188(%ebp),%edi
+movl %edi,-188(%ebp)
+leal -192(%ebp),%edi
+movl %edi,-32(%ebp)
+leal -192(%ebp),%edi
+movl %edi,-192(%ebp)
+leal -196(%ebp),%edi
+movl %edi,-36(%ebp)
+leal -196(%ebp),%edi
+movl %edi,-196(%ebp)
+leal -200(%ebp),%edi
+movl %edi,-40(%ebp)
+leal -200(%ebp),%edi
+movl %edi,-200(%ebp)
+leal -204(%ebp),%edi
+movl %edi,-44(%ebp)
+leal -204(%ebp),%edi
+movl %edi,-204(%ebp)
+leal -208(%ebp),%edi
+movl %edi,-48(%ebp)
+leal -208(%ebp),%edi
+movl %edi,-208(%ebp)
+leal -212(%ebp),%edi
+movl %edi,-52(%ebp)
+leal -212(%ebp),%edi
+movl %edi,-212(%ebp)
+leal -216(%ebp),%edi
+movl %edi,-56(%ebp)
+leal -216(%ebp),%edi
+movl %edi,-216(%ebp)
+leal -220(%ebp),%edi
+movl %edi,-60(%ebp)
+leal -220(%ebp),%edi
+movl %edi,-220(%ebp)
+leal -224(%ebp),%edi
+movl %edi,-64(%ebp)
+leal -224(%ebp),%edi
+movl %edi,-224(%ebp)
+leal -240(%ebp),%edi
+movl %edi,-240(%ebp)
+leal -244(%ebp),%edi
+movl %edi,-244(%ebp)
+leal -256(%ebp),%edi
+movl %edi,-256(%ebp)
+leal -228(%ebp),%edi
+movl $4,%esi
+leal -252(%ebp),%ebx
+movl %edi,%edx
+subl %ebx,%edx
+movl %edx,%eax
+movl %esi,%ecx
+cdq
+idivl %ecx
+movl %eax,-152(%ebp)
+leal -232(%ebp),%ebx
+subl %edi,%ebx
+movl %ebx,%eax
+movl %esi,%ecx
+cdq
+idivl %ecx
+movl %eax,-148(%ebp)
+leal -236(%ebp),%edi
+leal -232(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-144(%ebp)
+leal -164(%ebp),%edi
+leal -236(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-140(%ebp)
+leal -168(%ebp),%edi
+leal -164(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-136(%ebp)
+leal -172(%ebp),%edi
+leal -168(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-132(%ebp)
+leal -176(%ebp),%edi
+leal -172(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-128(%ebp)
+leal -180(%ebp),%edi
+leal -176(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-124(%ebp)
+leal -184(%ebp),%edi
+leal -180(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-120(%ebp)
+leal -188(%ebp),%edi
+leal -184(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-116(%ebp)
+leal -192(%ebp),%edi
+leal -188(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-112(%ebp)
+leal -196(%ebp),%edi
+leal -192(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-108(%ebp)
+leal -200(%ebp),%edi
+leal -196(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-104(%ebp)
+leal -204(%ebp),%edi
+leal -200(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-100(%ebp)
+leal -208(%ebp),%edi
+leal -204(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-96(%ebp)
+leal -212(%ebp),%edi
+leal -208(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-92(%ebp)
+leal -216(%ebp),%edi
+leal -212(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-88(%ebp)
+leal -220(%ebp),%edi
+leal -216(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-84(%ebp)
+leal -224(%ebp),%edi
+leal -220(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-80(%ebp)
+leal -240(%ebp),%edi
+leal -224(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-76(%ebp)
+leal -244(%ebp),%edi
+leal -240(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-72(%ebp)
+leal -256(%ebp),%edi
+leal -244(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+movl %eax,-68(%ebp)
+movl -152(%ebp),%edi
+movl %edi,-248(%ebp)
+movl $1,-160(%ebp)
+movl $0,-156(%ebp)
+.LC3159:
+movl -160(%ebp),%edi
+cmpl $1,%edi
+je .LC3165
+cmpl $2,%edi
+je .LC3168
+cmpl $3,%edi
+je .LC3173
+jmp .LC3163
+.LC3165:
+movl -156(%ebp),%edi
+leal -152(%ebp),%esi
+movl -248(%ebp),%ebx
+cmpl %ebx,(%esi,%edi,4)
+je .LC3164
+movl -156(%ebp),%edi
+leal -152(%ebp),%esi
+movl (%esi,%edi,4),%edi
+movl %edi,-264(%ebp)
+movl $2,-160(%ebp)
+movl $1,-260(%ebp)
+jmp .LC3164
+.LC3168:
+movl -156(%ebp),%edi
+leal -152(%ebp),%esi
+movl -248(%ebp),%ebx
+cmpl %ebx,(%esi,%edi,4)
+jne .LC3169
+movl $3,-160(%ebp)
+jmp .LC3164
+.LC3169:
+movl -156(%ebp),%edi
+leal -152(%ebp),%esi
+movl -264(%ebp),%ebx
+cmpl %ebx,(%esi,%edi,4)
+jne .LC3171
+incl -260(%ebp)
+jmp .LC3164
+.LC3171:
+movl $4,-160(%ebp)
+jmp .LC3164
+.LC3173:
+movl -156(%ebp),%edi
+leal -152(%ebp),%esi
+movl -248(%ebp),%ebx
+cmpl %ebx,(%esi,%edi,4)
+je .LC3164
+movl $4,-160(%ebp)
+.LC3163:
+.LC3164:
+.LC3160:
+incl -156(%ebp)
+cmpl $22,-156(%ebp)
+jl .LC3159
+cmpl $3,-160(%ebp)
+jne .LC3176
+movl $16,%edi
+movl %edi,%eax
+subl -260(%ebp),%eax
+jmp .LC3137
+.LC3176:
+movl $-1,%eax
+.LC3137:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf3178:
+.size regp,.Lf3178-regp
+.bss
+.align 4
+.type x3d.3180,@object
+.size x3d.3180,420
+.lcomm x3d.3180,420
+.data
+.align 1
+.type s84er.3181,@object
+s84er.3181:
+.byte 115
+.byte 56
+.byte 52
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size s84er.3181,10
+.align 1
+.type qs84.3182,@object
+.size qs84.3182,8
+qs84.3182:
+.byte 115
+.byte 56
+.byte 52
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s84
+.text
+.align 16
+.type s84,@function
+s84:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $172,%esp
+leal qs84.3182,%edi
+movl %edi,-156(%ebp)
+movl 20(%ebp),%edi
+leal 60(%edi),%edi
+movl %edi,-160(%ebp)
+movl $0,-164(%ebp)
+.LC3183:
+.LC3184:
+movl -160(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-160(%ebp)
+movl -156(%ebp),%esi
+leal 1(%esi),%ebx
+movl %ebx,-156(%ebp)
+movb (,%esi),%bl
+movb %bl,(,%edi)
+movsbl %bl,%edi
+cmpl $0,%edi
+jne .LC3183
+pushl $3
+call fip
+addl $4,%esp
+movl %eax,-168(%ebp)
+movl -168(%ebp),%edi
+cmpl $3,(,%edi)
+je .LC3186
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC3188
+pushl $1
+pushl $s84er.3181
+call printf
+addl $8,%esp
+.LC3188:
+incl -164(%ebp)
+.LC3186:
+leal glork,%edi
+movl %edi,-172(%ebp)
+pushl $4
+call *-172(%ebp)
+addl $4,%esp
+cmpl $4,%eax
+je .LC3190
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC3192
+pushl $2
+pushl $s84er.3181
+call printf
+addl $8,%esp
+.LC3192:
+addl $2,-164(%ebp)
+.LC3190:
+movl $0,-8(%ebp)
+.LC3194:
+movl -8(%ebp),%edi
+leal -80(%ebp),%esi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fstps (%esi,%edi,4)
+movl -8(%ebp),%edi
+leal (,%edi,4),%edi
+leal -148(%ebp),%esi
+leal -80(%ebp),%ebx
+leal (%ebx,%edi),%ebx
+movl %ebx,(%esi,%edi)
+.LC3195:
+incl -8(%ebp)
+cmpl $17,-8(%ebp)
+jl .LC3194
+flds .LC421
+fstps -152(%ebp)
+movl $0,-8(%ebp)
+.LC3198:
+flds -152(%ebp)
+movl -8(%ebp),%edi
+leal -148(%ebp),%esi
+movl (%esi,%edi,4),%edi
+fadds (,%edi)
+fstps -152(%ebp)
+.LC3199:
+incl -8(%ebp)
+cmpl $17,-8(%ebp)
+jl .LC3198
+flds .LC3204
+fcomps -152(%ebp)
+fstsw %ax
+sahf
+je .LC3202
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC3205
+pushl $4
+pushl $s84er.3181
+call printf
+addl $8,%esp
+.LC3205:
+addl $4,-164(%ebp)
+.LC3202:
+movl $0,-12(%ebp)
+.LC3207:
+movl $0,-8(%ebp)
+.LC3211:
+movl $0,-4(%ebp)
+.LC3215:
+movl -4(%ebp),%edi
+movl -8(%ebp),%esi
+movl -12(%ebp),%ebx
+imul $28,%esi,%edx
+imul $140,%ebx,%ecx
+leal x3d.3180(%ecx),%ecx
+leal (%ecx,%edx),%edx
+imul $35,%ebx,%ebx
+imul $7,%esi,%esi
+leal (%esi,%ebx),%esi
+leal (%edi,%esi),%esi
+movl %esi,(%edx,%edi,4)
+.LC3216:
+incl -4(%ebp)
+cmpl $7,-4(%ebp)
+jl .LC3215
+.LC3212:
+incl -8(%ebp)
+cmpl $5,-8(%ebp)
+jl .LC3211
+.LC3208:
+incl -12(%ebp)
+cmpl $3,-12(%ebp)
+jl .LC3207
+movl $1,-12(%ebp)
+movl $2,-8(%ebp)
+movl $3,-4(%ebp)
+pushl $0
+pushl $105
+pushl $x3d.3180
+call array
+addl $12,%esp
+movl %eax,%edi
+pushl $35
+pushl $35
+imul $140,-12(%ebp),%esi
+leal x3d.3180(%esi),%esi
+pushl %esi
+call array
+addl $12,%esp
+movl %eax,%esi
+pushl $49
+pushl $7
+imul $28,-8(%ebp),%ebx
+imul $140,-12(%ebp),%edx
+leal x3d.3180(%edx),%edx
+leal (%edx,%ebx),%ebx
+pushl %ebx
+call array
+addl $12,%esp
+leal (%esi,%edi),%edi
+leal (%eax,%edi),%edi
+movl -4(%ebp),%esi
+imul $28,-8(%ebp),%ebx
+imul $140,-12(%ebp),%edx
+leal x3d.3180(%edx),%edx
+leal (%edx,%ebx),%ebx
+movl (%ebx,%esi,4),%esi
+leal (%esi,%edi),%edi
+subl $52,%edi
+cmpl $0,%edi
+je .LC3219
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC3221
+pushl $8
+pushl $s84er.3181
+call printf
+addl $8,%esp
+.LC3221:
+addl $8,-164(%ebp)
+.LC3219:
+movl -164(%ebp),%eax
+.LC3179:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf3223:
+.size s84,.Lf3223-s84
+.globl array
+.align 16
+.type array,@function
+array:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $4,%esp
+movl $0,-4(%ebp)
+jmp .LC3228
+.LC3225:
+movl -4(%ebp),%edi
+movl 20(%ebp),%esi
+movl 28(%ebp),%ebx
+leal (%ebx,%edi),%ebx
+cmpl %ebx,(%esi,%edi,4)
+je .LC3229
+movl $1,%eax
+jmp .LC3224
+.LC3229:
+.LC3226:
+incl -4(%ebp)
+.LC3228:
+movl 24(%ebp),%edi
+cmpl %edi,-4(%ebp)
+jl .LC3225
+movl $0,%eax
+.LC3224:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf3231:
+.size array,.Lf3231-array
+.bss
+.align 4
+.type y.3233,@object
+.size y.3233,4
+.lcomm y.3233,4
+.globl fip
+.text
+.align 16
+.type fip,@function
+fip:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+leal y.3233,%edi
+movl 20(%ebp),%esi
+movl %esi,y.3233
+movl %edi,%eax
+.LC3232:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf3234:
+.size fip,.Lf3234-fip
+.globl glork
+.align 16
+.type glork,@function
+glork:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl 20(%ebp),%eax
+.LC3235:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf3236:
+.size glork,.Lf3236-glork
+.data
+.align 1
+.type s85er.3238,@object
+s85er.3238:
+.byte 115
+.byte 56
+.byte 53
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size s85er.3238,10
+.align 1
+.type qs85.3239,@object
+.size qs85.3239,8
+qs85.3239:
+.byte 115
+.byte 56
+.byte 53
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.align 4
+.type type.3247,@object
+type.3247:
+.long .LC434
+.long .LC436
+.long .LC435
+.long .LC437
+.long .LC438
+.long .LC439
+.long .LC440
+.size type.3247,28
+.align 1
+.type aln.3248,@object
+aln.3248:
+.byte 32
+.byte 97
+.byte 108
+.byte 105
+.byte 103
+.byte 110
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 58
+.byte 32
+.byte 0
+.size aln.3248,13
+.globl s85
+.text
+.align 16
+.type s85,@function
+s85:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $404,%esp
+leal qs85.3239,%edi
+movl %edi,-276(%ebp)
+movl 20(%ebp),%edi
+leal 60(%edi),%edi
+movl %edi,-280(%ebp)
+movl $0,-320(%ebp)
+.LC3252:
+.LC3253:
+movl -280(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-280(%ebp)
+movl -276(%ebp),%esi
+leal 1(%esi),%ebx
+movl %ebx,-276(%ebp)
+movb (,%esi),%bl
+movb %bl,(,%edi)
+movsbl %bl,%edi
+cmpl $0,%edi
+jne .LC3252
+leal -296(%ebp),%edi
+leal -316(%ebp),%esi
+subl %esi,%edi
+cmpl $0,%edi
+jle .LC3263
+leal -292(%ebp),%edi
+leal -296(%ebp),%esi
+subl %esi,%edi
+cmpl $0,%edi
+jle .LC3263
+leal -288(%ebp),%edi
+leal -292(%ebp),%esi
+subl %esi,%edi
+cmpl $0,%edi
+jg .LC3255
+.LC3263:
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC3264
+pushl $1
+pushl $s85er.3238
+call printf
+addl $8,%esp
+.LC3264:
+incl -320(%ebp)
+.LC3255:
+leal -355(%ebp),%edi
+leal -356(%ebp),%esi
+subl %esi,%edi
+movl %edi,-272(%ebp)
+leal -358(%ebp),%edi
+leal -360(%ebp),%esi
+subl %esi,%edi
+movl %edi,-268(%ebp)
+leal -364(%ebp),%edi
+leal -368(%ebp),%esi
+subl %esi,%edi
+movl %edi,-264(%ebp)
+leal -372(%ebp),%edi
+leal -376(%ebp),%esi
+subl %esi,%edi
+movl %edi,-260(%ebp)
+leal -380(%ebp),%edi
+leal -384(%ebp),%esi
+subl %esi,%edi
+movl %edi,-256(%ebp)
+leal -388(%ebp),%edi
+leal -392(%ebp),%esi
+subl %esi,%edi
+movl %edi,-252(%ebp)
+leal -400(%ebp),%edi
+leal -404(%ebp),%esi
+subl %esi,%edi
+movl %edi,-248(%ebp)
+movl 20(%ebp),%edi
+cmpl $0,40(%edi)
+je .LC3279
+movl $0,-244(%ebp)
+.LC3281:
+movl -244(%ebp),%edi
+leal (,%edi,4),%edi
+leal -272(%ebp),%esi
+pushl (%esi,%edi)
+pushl $aln.3248
+pushl type.3247(%edi)
+pushl $.LC3285
+call printf
+addl $16,%esp
+.LC3282:
+incl -244(%ebp)
+cmpl $7,-244(%ebp)
+jl .LC3281
+.LC3279:
+movl -284(%ebp),%edi
+orl $56,%edi
+movl %edi,-284(%ebp)
+movl -284(%ebp),%edi
+movl %edi,%esi
+andl $0xfffffffc,%esi
+sall $26,%edi
+sarl $29,%edi
+sall $30,%edi
+sarl $30,%edi
+andl $3,%edi
+orl %edi,%esi
+movl %esi,-284(%ebp)
+movl -284(%ebp),%edi
+movl %edi,%esi
+andl $0xffffffc7,%esi
+sall $30,%edi
+sarl $30,%edi
+sall $29,%edi
+sarl $29,%edi
+leal (,%edi,8),%edi
+andl $56,%edi
+orl %edi,%esi
+movl %esi,-284(%ebp)
+movl -284(%ebp),%edi
+sall $26,%edi
+sarl $29,%edi
+cmpl $3,%edi
+je .LC3286
+movl -284(%ebp),%edi
+sall $26,%edi
+sarl $29,%edi
+cmpl $-1,%edi
+jne .LC3288
+movl 20(%ebp),%edi
+cmpl $0,40(%edi)
+je .LC3289
+pushl $.LC3292
+call printf
+addl $4,%esp
+jmp .LC3289
+.LC3288:
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC3293
+pushl $2
+pushl $s85er.3238
+call printf
+addl $8,%esp
+.LC3293:
+addl $2,-320(%ebp)
+.LC3289:
+.LC3286:
+movl -284(%ebp),%edi
+orl $64,%edi
+movl %edi,-284(%ebp)
+movl -284(%ebp),%edi
+sall $25,%edi
+sarl $31,%edi
+cmpl $1,%edi
+je .LC3295
+movl 20(%ebp),%edi
+cmpl $0,40(%edi)
+je .LC3297
+pushl $.LC3299
+call printf
+addl $4,%esp
+.LC3297:
+.LC3295:
+leal -240(%ebp),%edi
+movl %edi,%esi
+subl %edi,%esi
+cmpl $0,%esi
+jne .LC3307
+cmpl $0,%esi
+jne .LC3307
+cmpl $0,%esi
+jne .LC3307
+cmpl $0,%esi
+jne .LC3307
+cmpl $0,%esi
+jne .LC3307
+cmpl $0,%esi
+jne .LC3307
+cmpl $0,%esi
+je .LC3300
+.LC3307:
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC3308
+pushl $4
+pushl $s85er.3238
+call printf
+addl $8,%esp
+.LC3308:
+addl $4,-320(%ebp)
+.LC3300:
+jmp .LC3310
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC3312
+pushl $8
+pushl $s85er.3238
+call printf
+addl $8,%esp
+.LC3312:
+addl $8,-320(%ebp)
+.LC3310:
+leal -352(%ebp),%edi
+movl %edi,-288(%ebp)
+movb $2,-352(%ebp)
+movl -288(%ebp),%edi
+movsbl (,%edi),%esi
+leal 1(%esi),%esi
+movl %esi,%ebx
+movb %bl,(,%edi)
+movsbl -352(%ebp),%edi
+cmpl $3,%edi
+je .LC3316
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC3318
+pushl $16
+pushl $s85er.3238
+call printf
+addl $8,%esp
+.LC3318:
+addl $16,-320(%ebp)
+.LC3316:
+movl -320(%ebp),%eax
+.LC3237:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf3320:
+.size s85,.Lf3320-s85
+.data
+.align 1
+.type s86er.3322,@object
+s86er.3322:
+.byte 115
+.byte 56
+.byte 54
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size s86er.3322,10
+.align 1
+.type qs86.3323,@object
+.size qs86.3323,8
+qs86.3323:
+.byte 115
+.byte 56
+.byte 54
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.align 4
+.type x.3324,@object
+x.3324:
+.long 1
+.long 3
+.long 5
+.size x.3324,12
+.align 4
+.type pint.3325,@object
+.size pint.3325,4
+pint.3325:
+.long x.3324+8
+.bss
+.align 4
+.type zero.3327,@object
+.size zero.3327,40
+.lcomm zero.3327,40
+.data
+.align 4
+.type y0.3328,@object
+y0.3328:
+.long 1065353216
+.long 1077936128
+.long 1084227584
+.long 1073741824
+.long 1082130432
+.long 1086324736
+.long 1077936128
+.long 1084227584
+.long 1088421888
+.long 0
+.long 0
+.long 0
+.size y0.3328,48
+.align 4
+.type y1.3329,@object
+.size y1.3329,48
+y1.3329:
+.long 1065353216
+.long 1077936128
+.long 1084227584
+.long 1073741824
+.long 1082130432
+.long 1086324736
+.long 1077936128
+.long 1084227584
+.long 1088421888
+.space 12
+.align 4
+.type y2.3330,@object
+.size y2.3330,48
+y2.3330:
+.long 1065353216
+.long 1077936128
+.long 1084227584
+.long 1073741824
+.long 1082130432
+.long 1086324736
+.long 1077936128
+.long 1084227584
+.long 1088421888
+.space 12
+.align 4
+.type y3.3331,@object
+.size y3.3331,48
+y3.3331:
+.long 1065353216
+.space 8
+.long 1073741824
+.space 8
+.long 1077936128
+.space 8
+.long 1082130432
+.space 8
+.globl s86
+.text
+.align 16
+.type s86,@function
+s86:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $40,%esp
+movl pint.3325,%edi
+leal -4(%edi),%edi
+movl %edi,-36(%ebp)
+call one
+movl -36(%ebp),%esi
+leal (%esi,%eax,4),%edi
+movl %edi,-4(%ebp)
+leal qs86.3323,%edi
+movl %edi,-24(%ebp)
+movl 20(%ebp),%edi
+leal 60(%edi),%edi
+movl %edi,-28(%ebp)
+movl $0,-32(%ebp)
+.LC3332:
+.LC3333:
+movl -28(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-28(%ebp)
+movl -24(%ebp),%esi
+leal 1(%esi),%ebx
+movl %ebx,-24(%ebp)
+movb (,%esi),%bl
+movb %bl,(,%edi)
+movsbl %bl,%edi
+cmpl $0,%edi
+jne .LC3332
+movl pint.3325,%edi
+cmpl $5,(,%edi)
+je .LC3335
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC3337
+pushl $1
+pushl $s86er.3322
+call printf
+addl $8,%esp
+.LC3337:
+incl -32(%ebp)
+.LC3335:
+movl -36(%ebp),%edi
+cmpl $3,(,%edi)
+je .LC3339
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC3341
+pushl $2
+pushl $s86er.3322
+call printf
+addl $8,%esp
+.LC3341:
+addl $2,-32(%ebp)
+.LC3339:
+movl -4(%ebp),%edi
+cmpl $5,(,%edi)
+je .LC3343
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC3345
+pushl $4
+pushl $s86er.3322
+call printf
+addl $8,%esp
+.LC3345:
+addl $4,-32(%ebp)
+.LC3343:
+movl $0,-20(%ebp)
+movl $0,-8(%ebp)
+.LC3347:
+movl -8(%ebp),%edi
+cmpl $0,zero.3327(,%edi,4)
+je .LC3351
+movl $1,-20(%ebp)
+.LC3351:
+.LC3348:
+incl -8(%ebp)
+cmpl $10,-8(%ebp)
+jl .LC3347
+cmpl $0,-20(%ebp)
+je .LC3353
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC3355
+pushl $8
+pushl $s86er.3322
+call printf
+addl $8,%esp
+.LC3355:
+addl $8,-32(%ebp)
+.LC3353:
+movl $0,-20(%ebp)
+movl $0,-12(%ebp)
+.LC3357:
+movl $0,-8(%ebp)
+.LC3361:
+imul $3,-12(%ebp),%edi
+movl -8(%ebp),%esi
+leal (%esi,%edi),%edi
+movl %edi,-16(%ebp)
+movl -8(%ebp),%edi
+leal (,%edi,4),%edi
+imul $12,-12(%ebp),%esi
+leal y1.3329(%esi),%ebx
+flds (%ebx,%edi)
+fstps -40(%ebp)
+leal y2.3330(%esi),%esi
+flds (%esi,%edi)
+fcomps -40(%ebp)
+fstsw %ax
+sahf
+jne .LC3367
+movl -16(%ebp),%edi
+flds y0.3328(,%edi,4)
+fcomps -40(%ebp)
+fstsw %ax
+sahf
+je .LC3365
+.LC3367:
+movl $1,-20(%ebp)
+.LC3365:
+.LC3362:
+incl -8(%ebp)
+cmpl $3,-8(%ebp)
+jl .LC3361
+.LC3358:
+incl -12(%ebp)
+cmpl $4,-12(%ebp)
+jl .LC3357
+cmpl $0,-20(%ebp)
+je .LC3368
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC3370
+pushl $16
+pushl $s86er.3322
+call printf
+addl $8,%esp
+.LC3370:
+addl $16,-32(%ebp)
+.LC3368:
+movl $0,-20(%ebp)
+movl $0,-8(%ebp)
+.LC3372:
+movl -8(%ebp),%edi
+imul $12,%edi,%esi
+leal 1(%edi),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fcomps y3.3331(%esi)
+fstsw %ax
+sahf
+je .LC3376
+movl $1,-20(%ebp)
+.LC3376:
+.LC3373:
+incl -8(%ebp)
+cmpl $4,-8(%ebp)
+jl .LC3372
+cmpl $0,-20(%ebp)
+je .LC3378
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC3380
+pushl $32
+pushl $s86er.3322
+call printf
+addl $8,%esp
+.LC3380:
+addl $32,-32(%ebp)
+.LC3378:
+movl -32(%ebp),%eax
+.LC3321:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf3382:
+.size s86,.Lf3382-s86
+.globl one
+.align 16
+.type one,@function
+one:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl $1,%eax
+.LC3383:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf3384:
+.size one,.Lf3384-one
+.data
+.align 1
+.type s88er.3386,@object
+s88er.3386:
+.byte 115
+.byte 56
+.byte 56
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size s88er.3386,10
+.align 1
+.type qs88.3387,@object
+.size qs88.3387,8
+qs88.3387:
+.byte 115
+.byte 56
+.byte 56
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s88
+.text
+.align 16
+.type s88,@function
+s88:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $44,%esp
+leal qs88.3387,%edi
+movl %edi,-4(%ebp)
+movl 20(%ebp),%edi
+leal 60(%edi),%edi
+movl %edi,-8(%ebp)
+movl $0,-12(%ebp)
+.LC3389:
+.LC3390:
+movl -8(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-8(%ebp)
+movl -4(%ebp),%esi
+leal 1(%esi),%ebx
+movl %ebx,-4(%ebp)
+movb (,%esi),%bl
+movb %bl,(,%edi)
+movsbl %bl,%edi
+cmpl $0,%edi
+jne .LC3389
+jmp .LC3392
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC3394
+pushl $1
+pushl $s88er.3386
+call printf
+addl $8,%esp
+.LC3394:
+incl -12(%ebp)
+.LC3392:
+leal -32(%ebp),%edi
+movl %edi,metricp
+movl $2,-32(%ebp)
+movl metricp,%edi
+movl $3,(,%edi)
+cmpl $3,-32(%ebp)
+je .LC3396
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC3398
+pushl $2
+pushl $s88er.3386
+call printf
+addl $8,%esp
+.LC3398:
+addl $2,-12(%ebp)
+.LC3396:
+fldl .LC428
+fstpl -28(%ebp)
+fldl .LC428
+fstpl -20(%ebp)
+leal -28(%ebp),%edi
+movl %edi,-36(%ebp)
+movl -36(%ebp),%edi
+fldl .LC427
+fstpl (,%edi)
+movl -36(%ebp),%edi
+fldl .LC427
+fstpl 8(%edi)
+fldl -28(%ebp)
+faddl -20(%ebp)
+fldl .LC425
+fcompp
+fstsw %ax
+sahf
+je .LC3401
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC3404
+pushl $4
+pushl $s88er.3386
+call printf
+addl $8,%esp
+.LC3404:
+addl $4,-12(%ebp)
+.LC3401:
+movl -12(%ebp),%eax
+.LC3385:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf3406:
+.size s88,.Lf3406-s88
+.data
+.align 1
+.type s9er.3408,@object
+s9er.3408:
+.byte 115
+.byte 57
+.byte 44
+.byte 101
+.byte 114
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.size s9er.3408,9
+.align 1
+.type qs9.3409,@object
+.size qs9.3409,8
+qs9.3409:
+.byte 115
+.byte 57
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 0
+.globl s9
+.text
+.align 16
+.type s9,@function
+s9:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $36,%esp
+leal qs9.3409,%edi
+movl %edi,-12(%ebp)
+movl 20(%ebp),%edi
+leal 60(%edi),%edi
+movl %edi,-16(%ebp)
+movl $0,-20(%ebp)
+.LC3410:
+.LC3411:
+movl -16(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-16(%ebp)
+movl -12(%ebp),%esi
+leal 1(%esi),%ebx
+movl %ebx,-12(%ebp)
+movb (,%esi),%bl
+movb %bl,(,%edi)
+movsbl %bl,%edi
+cmpl $0,%edi
+jne .LC3410
+movl $0,-8(%ebp)
+movl $0,-4(%ebp)
+.LC3413:
+movl $2,-24(%ebp)
+movl $2,-28(%ebp)
+movl $3,-32(%ebp)
+movl $3,-36(%ebp)
+cmpl $3,-36(%ebp)
+jne .LC3419
+cmpl $3,-32(%ebp)
+je .LC3417
+.LC3419:
+movl $1,-8(%ebp)
+.LC3417:
+cmpl $2,-28(%ebp)
+jne .LC3422
+cmpl $2,-24(%ebp)
+je .LC3420
+.LC3422:
+movl $1,-8(%ebp)
+.LC3420:
+.LC3414:
+incl -4(%ebp)
+cmpl $2,-4(%ebp)
+jl .LC3413
+cmpl $0,-8(%ebp)
+je .LC3427
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC3425
+pushl $1
+pushl $s9er.3408
+call printf
+addl $8,%esp
+.LC3425:
+incl -20(%ebp)
+jmp .LC3427
+movl 20(%ebp),%edi
+cmpl $0,44(%edi)
+je .LC3428
+pushl $2
+pushl $s9er.3408
+call printf
+addl $8,%esp
+.LC3428:
+addl $2,-20(%ebp)
+.LC3427:
+movl -20(%ebp),%eax
+.LC3407:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf3430:
+.size s9,.Lf3430-s9
+.globl setev
+.align 16
+.type setev,@function
+setev:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl $1066,extvar
+movl $0,%eax
+.LC3431:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf3432:
+.size setev,.Lf3432-setev
+.bss
+.globl rfs
+.align 1
+.type rfs,@object
+.size rfs,8
+.comm rfs,8
+.globl crc
+.align 4
+.type crc,@object
+.size crc,4
+.comm crc,4
+.globl rrc
+.align 4
+.type rrc,@object
+.size rrc,4
+.comm rrc,4
+.globl flgl
+.align 4
+.type flgl,@object
+.size flgl,4
+.comm flgl,4
+.globl flgd
+.align 4
+.type flgd,@object
+.size flgd,4
+.comm flgd,4
+.globl flgm
+.align 4
+.type flgm,@object
+.size flgm,4
+.comm flgm,4
+.globl flgs
+.align 4
+.type flgs,@object
+.size flgs,4
+.comm flgs,4
+.globl dprec
+.align 4
+.type dprec,@object
+.size dprec,4
+.comm dprec,4
+.globl fprec
+.align 4
+.type fprec,@object
+.size fprec,4
+.comm fprec,4
+.globl dbits
+.align 4
+.type dbits,@object
+.size dbits,4
+.comm dbits,4
+.globl fbits
+.align 4
+.type fbits,@object
+.size fbits,4
+.comm fbits,4
+.globl ubits
+.align 4
+.type ubits,@object
+.size ubits,4
+.comm ubits,4
+.globl lbits
+.align 4
+.type lbits,@object
+.size lbits,4
+.comm lbits,4
+.globl metricp
+.align 4
+.type metricp,@object
+.size metricp,4
+.comm metricp,4
+.globl extvar
+.align 4
+.type extvar,@object
+.size extvar,4
+.comm extvar,4
+.data
+.align 1
+.LC3299:
+.byte 66
+.byte 101
+.byte 32
+.byte 101
+.byte 115
+.byte 112
+.byte 101
+.byte 99
+.byte 105
+.byte 97
+.byte 108
+.byte 108
+.byte 121
+.byte 32
+.byte 99
+.byte 97
+.byte 114
+.byte 101
+.byte 102
+.byte 117
+.byte 108
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 49
+.byte 45
+.byte 98
+.byte 105
+.byte 116
+.byte 32
+.byte 102
+.byte 105
+.byte 101
+.byte 108
+.byte 100
+.byte 115
+.byte 33
+.byte 10
+.byte 0
+.align 1
+.LC3292:
+.byte 83
+.byte 105
+.byte 103
+.byte 110
+.byte 32
+.byte 101
+.byte 120
+.byte 116
+.byte 101
+.byte 110
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 102
+.byte 105
+.byte 101
+.byte 108
+.byte 100
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.LC3285:
+.byte 37
+.byte 115
+.byte 37
+.byte 115
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 4
+.LC3204:
+.long 1124597760
+.align 1
+.LC3047:
+.byte 112
+.byte 111
+.byte 105
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 0
+.align 1
+.LC2495:
+.byte 73
+.byte 110
+.byte 99
+.byte 114
+.byte 101
+.byte 97
+.byte 115
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 97
+.byte 114
+.byte 114
+.byte 97
+.byte 121
+.byte 32
+.byte 101
+.byte 108
+.byte 101
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 97
+.byte 115
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 101
+.byte 100
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 100
+.byte 101
+.byte 99
+.byte 114
+.byte 101
+.byte 97
+.byte 115
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 108
+.byte 111
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 10
+.byte 0
+.align 4
+.LC2378:
+.long 1104150528
+.align 4
+.LC2377:
+.long 0
+.long 1077542912
+.align 4
+.LC1678:
+.long 0
+.long 1074003968
+.align 4
+.LC1503:
+.long 0
+.long 1076101120
+.align 4
+.LC1474:
+.long 1092616192
+.align 4
+.LC1299:
+.long 0
+.long 1074266112
+.align 4
+.LC1270:
+.long 1077936128
+.align 4
+.LC1095:
+.long 0
+.long 1075576832
+.align 4
+.LC1066:
+.long 1088421888
+.align 4
+.LC889:
+.long 0
+.long 1075052544
+.align 4
+.LC860:
+.long 1084227584
+.align 4
+.LC855:
+.long 0
+.long 1105199104
+.align 4
+.LC847:
+.long 1325400064
+.align 1
+.LC669:
+.byte 113
+.byte 117
+.byte 101
+.byte 101
+.byte 112
+.byte 0
+.align 1
+.LC654:
+.byte 10
+.byte 0
+.align 1
+.LC653:
+.byte 37
+.byte 100
+.byte 0
+.align 1
+.LC648:
+.byte 32
+.byte 32
+.byte 32
+.byte 107
+.byte 101
+.byte 121
+.byte 61
+.byte 0
+.align 4
+.LC611:
+.long 0
+.long 1073741824
+.align 4
+.LC551:
+.long 0
+.long 1087276160
+.align 4
+.LC550:
+.long 0
+.long 1079984128
+.align 4
+.LC549:
+.long 1123680256
+.align 4
+.LC544:
+.long 1073741824
+.align 1
+.LC440:
+.byte 100
+.byte 111
+.byte 117
+.byte 98
+.byte 108
+.byte 101
+.byte 0
+.align 1
+.LC439:
+.byte 102
+.byte 108
+.byte 111
+.byte 97
+.byte 116
+.byte 0
+.align 1
+.LC438:
+.byte 117
+.byte 110
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 101
+.byte 100
+.byte 0
+.align 1
+.LC437:
+.byte 108
+.byte 111
+.byte 110
+.byte 103
+.byte 0
+.align 1
+.LC436:
+.byte 115
+.byte 104
+.byte 111
+.byte 114
+.byte 116
+.byte 0
+.align 1
+.LC435:
+.byte 105
+.byte 110
+.byte 116
+.byte 0
+.align 1
+.LC434:
+.byte 99
+.byte 104
+.byte 97
+.byte 114
+.byte 0
+.align 4
+.LC428:
+.long 0
+.long 0
+.align 4
+.LC427:
+.long 0
+.long 1072693248
+.align 4
+.LC426:
+.long 0
+.long 1074790400
+.align 4
+.LC425:
+.long 0
+.long 1073741824
+.align 4
+.LC421:
+.long 0
+.align 4
+.LC420:
+.long 1065353216
+.align 1
+.LC398:
+.byte 113
+.byte 117
+.byte 101
+.byte 101
+.byte 112
+.byte 33
+.byte 0
+.align 1
+.LC387:
+.byte 10
+.byte 9
+.byte 8
+.byte 13
+.byte 12
+.byte 92
+.byte 39
+.byte 0
+.align 1
+.LC383:
+.byte 46
+.byte 34
+.byte 46
+.byte 0
+.align 1
+.LC370:
+.byte 46
+.byte 46
+.byte 46
+.byte 0
+.align 4
+.LC340:
+.long 0
+.long 1083410432
+.align 1
+.LC201:
+.byte 32
+.byte 32
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 114
+.byte 101
+.byte 115
+.byte 117
+.byte 108
+.byte 116
+.byte 115
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 110
+.byte 32
+.byte 97
+.byte 115
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 101
+.byte 100
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 108
+.byte 111
+.byte 110
+.byte 103
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC200:
+.byte 68
+.byte 101
+.byte 99
+.byte 105
+.byte 109
+.byte 97
+.byte 108
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 111
+.byte 99
+.byte 116
+.byte 97
+.byte 108
+.byte 47
+.byte 104
+.byte 101
+.byte 120
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 115
+.byte 116
+.byte 97
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 115
+.byte 111
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 109
+.byte 101
+.byte 115
+.byte 32
+.byte 103
+.byte 105
+.byte 118
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.LC27:
+.byte 10
+.byte 70
+.byte 97
+.byte 105
+.byte 108
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC26:
+.byte 10
+.byte 78
+.byte 111
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 115
+.byte 32
+.byte 100
+.byte 101
+.byte 116
+.byte 101
+.byte 99
+.byte 116
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC20:
+.byte 83
+.byte 101
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 37
+.byte 115
+.byte 32
+.byte 114
+.byte 101
+.byte 116
+.byte 117
+.byte 114
+.byte 110
+.byte 101
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.text
+.ident "LCC: 4.1"
diff --git a/lcc/x86/linux/tst/cvt.1bk b/lcc/x86/linux/tst/cvt.1bk
new file mode 100755
index 0000000..74c79f1
--- /dev/null
+++ b/lcc/x86/linux/tst/cvt.1bk
@@ -0,0 +1,11 @@
+1 1 1 1 1 1 1 1 1.000000 1.000000 1.000000
+2 2 2 2 2 2 2 2 2.000000 2.000000 2.000000
+3 3 3 3 3 3 3 3 3.000000 3.000000 3.000000
+4 4 4 4 4 4 4 4 4.000000 4.000000 4.000000
+5 5 5 5 5 5 5 5 5.000000 5.000000 5.000000
+6 6 6 6 6 6 6 6 6.000000 6.000000 6.000000
+7 7 7 7 7 7 7 7 7.000000 7.000000 7.000000
+8 8 8 8 8 8 8 8 8.000000 8.000000 8.000000
+9 9 9 9 9 9 9 9 9.000000 9.000000 9.000000
+10 10 10 10 10 10 10 10 10.000000 10.000000 10.000000
+11 11 11 11 11 11 11 11 11.000000 11.000000 11.000000
diff --git a/lcc/x86/linux/tst/cvt.2bk b/lcc/x86/linux/tst/cvt.2bk
new file mode 100755
index 0000000..b3ab360
--- /dev/null
+++ b/lcc/x86/linux/tst/cvt.2bk
@@ -0,0 +1,2 @@
+tst/cvt.c:32: warning: conversion from `pointer to void function(void)' to `pointer to void' is compiler dependent
+tst/cvt.c:33: warning: conversion from `pointer to void' to `pointer to void function(void)' is compiler dependent
diff --git a/lcc/x86/linux/tst/cvt.sbk b/lcc/x86/linux/tst/cvt.sbk
new file mode 100755
index 0000000..06b427b
--- /dev/null
+++ b/lcc/x86/linux/tst/cvt.sbk
@@ -0,0 +1,792 @@
+.globl print
+.text
+.align 16
+.type print,@function
+print:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+fldl D
+subl $8,%esp
+fstpl (%esp)
+fldl d
+subl $8,%esp
+fstpl (%esp)
+flds f
+subl $8,%esp
+fstpl (%esp)
+pushl L
+pushl I
+movw S,%di
+movzwl %di,%edi
+pushl %edi
+movb C,%bl
+movzbl %bl,%edi
+pushl %edi
+pushl l
+pushl i
+movswl s,%edi
+pushl %edi
+movsbl c,%edi
+pushl %edi
+pushl $.LC2
+call printf
+addl $60,%esp
+.LC1:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf3:
+.size print,.Lf3-print
+.globl main
+.align 16
+.type main,@function
+main:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $296,%esp
+movb $1,c
+movsbl c,%edi
+movl %edi,%esi
+movw %si,s
+movl %edi,i
+movl %edi,l
+movl %edi,%esi
+movl %esi,%ebx
+movb %bl,C
+movl %esi,%ebx
+movw %bx,S
+movl %esi,I
+movl %esi,L
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fstps f
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fstpl -8(%ebp)
+fldl -8(%ebp)
+fstpl d
+fldl -8(%ebp)
+fstpl D
+call print
+movw $2,s
+movswl s,%edi
+movl %edi,%ebx
+movb %bl,c
+movl %edi,i
+movl %edi,l
+movl %edi,%esi
+movl %esi,%ebx
+movb %bl,C
+movl %esi,%ebx
+movw %bx,S
+movl %esi,I
+movl %esi,L
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fstps f
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fstpl -16(%ebp)
+fldl -16(%ebp)
+fstpl d
+fldl -16(%ebp)
+fstpl D
+call print
+movl $3,i
+movl i,%edi
+movl %edi,%ebx
+movb %bl,c
+movl %edi,%esi
+movw %si,s
+movl %edi,l
+movl %edi,%esi
+movl %esi,%ebx
+movb %bl,C
+movl %esi,%ebx
+movw %bx,S
+movl %esi,I
+movl %esi,L
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fstps f
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fstpl -24(%ebp)
+fldl -24(%ebp)
+fstpl d
+fldl -24(%ebp)
+fstpl D
+call print
+movl $4,l
+movl l,%edi
+movl %edi,%ebx
+movb %bl,c
+movl %edi,%esi
+movw %si,s
+movl %edi,i
+movl %edi,%esi
+movl %esi,%ebx
+movb %bl,C
+movl %esi,%ebx
+movw %bx,S
+movl %esi,I
+movl %esi,L
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fstps f
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fstpl -32(%ebp)
+fldl -32(%ebp)
+fstpl d
+fldl -32(%ebp)
+fstpl D
+call print
+movb $5,C
+movb C,%bl
+movzbl %bl,%edi
+movl %edi,%ebx
+movb %bl,c
+movl %edi,%esi
+movw %si,s
+movl %edi,i
+movl %edi,l
+movl %edi,%esi
+movl %esi,%ebx
+movw %bx,S
+movl %esi,I
+movl %esi,L
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fstps f
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fstpl -40(%ebp)
+fldl -40(%ebp)
+fstpl d
+fldl -40(%ebp)
+fstpl D
+call print
+movw $6,S
+movw S,%di
+movzwl %di,%edi
+movl %edi,%ebx
+movb %bl,c
+movl %edi,%esi
+movw %si,s
+movl %edi,i
+movl %edi,l
+movl %edi,%esi
+movl %esi,%ebx
+movb %bl,C
+movl %esi,I
+movl %esi,L
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fstps f
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fstpl -48(%ebp)
+fldl -48(%ebp)
+fstpl d
+fldl -48(%ebp)
+fstpl D
+call print
+movl $7,I
+movl I,%edi
+movl %edi,%ebx
+movb %bl,c
+movl %edi,%ebx
+movw %bx,s
+movl %edi,i
+movl %edi,l
+movl %edi,%ebx
+movb %bl,C
+movl %edi,%esi
+movw %si,S
+movl %edi,L
+fldl .LC5
+movl %edi,%esi
+shrl $1,%esi
+pushl %esi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+andl $1,%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+fstpl -56(%ebp)
+fldl -56(%ebp)
+fstps f
+fldl -56(%ebp)
+fstpl d
+fldl -56(%ebp)
+fstpl D
+call print
+movl $8,L
+movl L,%edi
+movl %edi,%ebx
+movb %bl,c
+movl %edi,%ebx
+movw %bx,s
+movl %edi,i
+movl %edi,l
+movl %edi,%ebx
+movb %bl,C
+movl %edi,%esi
+movw %si,S
+movw S,%si
+movzwl %si,%esi
+movl %esi,I
+fldl .LC5
+movl %edi,%esi
+shrl $1,%esi
+pushl %esi
+fildl (%esp)
+addl $4,%esp
+fmulp %st(1),%st
+andl $1,%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+faddp %st(1),%st
+fstpl -64(%ebp)
+fldl -64(%ebp)
+fstps f
+fldl -64(%ebp)
+fstpl d
+fldl -64(%ebp)
+fstpl D
+call print
+flds .LC6
+fstps f
+flds f
+fstps -84(%ebp)
+flds -84(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,%ebx
+movb %bl,c
+movl %edi,%esi
+movw %si,s
+movl %edi,i
+movl %edi,l
+flds .LC10
+fcomps -84(%ebp)
+fstsw %ax
+sahf
+ja .LC8
+flds -84(%ebp)
+fsubs .LC10
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+leal 0x80000000(%edi),%edi
+movl %edi,-68(%ebp)
+jmp .LC9
+.LC8:
+flds -84(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,-68(%ebp)
+.LC9:
+movl -68(%ebp),%edi
+movl %edi,%ebx
+movb %bl,C
+flds .LC10
+fcomps f
+fstsw %ax
+sahf
+ja .LC12
+flds f
+fsubs .LC10
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+leal 0x80000000(%edi),%edi
+movl %edi,-72(%ebp)
+jmp .LC13
+.LC12:
+flds f
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,-72(%ebp)
+.LC13:
+movl -72(%ebp),%edi
+movw %di,S
+flds .LC10
+fcomps f
+fstsw %ax
+sahf
+ja .LC15
+flds f
+fsubs .LC10
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+leal 0x80000000(%edi),%edi
+movl %edi,-76(%ebp)
+jmp .LC16
+.LC15:
+flds f
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,-76(%ebp)
+.LC16:
+movl -76(%ebp),%edi
+movl %edi,I
+flds .LC10
+fcomps f
+fstsw %ax
+sahf
+ja .LC18
+flds f
+fsubs .LC10
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+leal 0x80000000(%edi),%edi
+movl %edi,-80(%ebp)
+jmp .LC19
+.LC18:
+flds f
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,-80(%ebp)
+.LC19:
+movl -80(%ebp),%edi
+movl %edi,L
+flds f
+fstpl -120(%ebp)
+fldl -120(%ebp)
+fstpl d
+fldl -120(%ebp)
+fstpl D
+call print
+fldl .LC20
+fstpl d
+fldl d
+fstpl -144(%ebp)
+fldl -144(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,%ebx
+movb %bl,c
+movl %edi,%esi
+movw %si,s
+movl %edi,i
+movl %edi,l
+fldl .LC24
+fcompl -144(%ebp)
+fstsw %ax
+sahf
+ja .LC22
+fldl -144(%ebp)
+fsubl .LC24
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+leal 0x80000000(%edi),%edi
+movl %edi,-124(%ebp)
+jmp .LC23
+.LC22:
+fldl -144(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,-124(%ebp)
+.LC23:
+movl -124(%ebp),%edi
+movl %edi,%ebx
+movb %bl,C
+fldl .LC24
+fcompl d
+fstsw %ax
+sahf
+ja .LC26
+fldl d
+fsubl .LC24
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+leal 0x80000000(%edi),%edi
+movl %edi,-128(%ebp)
+jmp .LC27
+.LC26:
+fldl d
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,-128(%ebp)
+.LC27:
+movl -128(%ebp),%edi
+movw %di,S
+fldl .LC24
+fcompl d
+fstsw %ax
+sahf
+ja .LC29
+fldl d
+fsubl .LC24
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+leal 0x80000000(%edi),%edi
+movl %edi,-132(%ebp)
+jmp .LC30
+.LC29:
+fldl d
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,-132(%ebp)
+.LC30:
+movl -132(%ebp),%edi
+movl %edi,I
+fldl .LC24
+fcompl d
+fstsw %ax
+sahf
+ja .LC32
+fldl d
+fsubl .LC24
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+leal 0x80000000(%edi),%edi
+movl %edi,-136(%ebp)
+jmp .LC33
+.LC32:
+fldl d
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,-136(%ebp)
+.LC33:
+movl -136(%ebp),%edi
+movl %edi,L
+fldl d
+fstps f
+fldl d
+fstpl D
+call print
+fldl .LC34
+fstpl D
+fldl D
+fstpl -232(%ebp)
+fldl -232(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,%ebx
+movb %bl,c
+movl %edi,%esi
+movw %si,s
+movl %edi,i
+movl %edi,l
+fldl .LC38
+fcompl -232(%ebp)
+fstsw %ax
+sahf
+ja .LC36
+fldl -232(%ebp)
+fsubl .LC38
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+leal 0x80000000(%edi),%edi
+movl %edi,-212(%ebp)
+jmp .LC37
+.LC36:
+fldl -232(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,-212(%ebp)
+.LC37:
+movl -212(%ebp),%edi
+movl %edi,%ebx
+movb %bl,C
+fldl .LC38
+fcompl D
+fstsw %ax
+sahf
+ja .LC40
+fldl D
+fsubl .LC38
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+leal 0x80000000(%edi),%edi
+movl %edi,-216(%ebp)
+jmp .LC41
+.LC40:
+fldl D
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,-216(%ebp)
+.LC41:
+movl -216(%ebp),%edi
+movw %di,S
+fldl .LC38
+fcompl D
+fstsw %ax
+sahf
+ja .LC43
+fldl D
+fsubl .LC38
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+leal 0x80000000(%edi),%edi
+movl %edi,-220(%ebp)
+jmp .LC44
+.LC43:
+fldl D
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,-220(%ebp)
+.LC44:
+movl -220(%ebp),%edi
+movl %edi,I
+fldl .LC38
+fcompl D
+fstsw %ax
+sahf
+ja .LC46
+fldl D
+fsubl .LC38
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+leal 0x80000000(%edi),%edi
+movl %edi,-224(%ebp)
+jmp .LC47
+.LC46:
+fldl D
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,%edi
+movl %edi,-224(%ebp)
+.LC47:
+movl -224(%ebp),%edi
+movl %edi,L
+fldl D
+fstps f
+fldl D
+fstpl d
+call print
+movl $0,p
+movl $0,p
+movl $0,p
+movl $0,p
+movl P,%edi
+movl %edi,p
+movl $0,P
+movl $0,P
+movl $0,P
+movl $0,P
+movl p,%edi
+movl %edi,P
+movl $0,%eax
+.LC4:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf48:
+.size main,.Lf48-main
+.bss
+.globl P
+.align 4
+.type P,@object
+.size P,4
+.comm P,4
+.globl p
+.align 4
+.type p,@object
+.size p,4
+.comm p,4
+.globl D
+.align 4
+.type D,@object
+.size D,8
+.comm D,8
+.globl d
+.align 4
+.type d,@object
+.size d,8
+.comm d,8
+.globl f
+.align 4
+.type f,@object
+.size f,4
+.comm f,4
+.globl L
+.align 4
+.type L,@object
+.size L,4
+.comm L,4
+.globl I
+.align 4
+.type I,@object
+.size I,4
+.comm I,4
+.globl S
+.align 2
+.type S,@object
+.size S,2
+.comm S,2
+.globl C
+.align 1
+.type C,@object
+.size C,1
+.comm C,1
+.globl l
+.align 4
+.type l,@object
+.size l,4
+.comm l,4
+.globl i
+.align 4
+.type i,@object
+.size i,4
+.comm i,4
+.globl s
+.align 2
+.type s,@object
+.size s,2
+.comm s,2
+.globl c
+.align 1
+.type c,@object
+.size c,1
+.comm c,1
+.data
+.align 4
+.LC38:
+.long 0
+.long 1105199104
+.align 4
+.LC34:
+.long 0
+.long 1076232192
+.align 4
+.LC24:
+.long 0
+.long 1105199104
+.align 4
+.LC20:
+.long 0
+.long 1076101120
+.align 4
+.LC10:
+.long 1325400064
+.align 4
+.LC6:
+.long 1091567616
+.align 4
+.LC5:
+.long 0
+.long 1073741824
+.align 1
+.LC2:
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 108
+.byte 100
+.byte 32
+.byte 37
+.byte 117
+.byte 32
+.byte 37
+.byte 117
+.byte 32
+.byte 37
+.byte 117
+.byte 32
+.byte 37
+.byte 108
+.byte 117
+.byte 32
+.byte 37
+.byte 102
+.byte 32
+.byte 37
+.byte 102
+.byte 32
+.byte 37
+.byte 108
+.byte 102
+.byte 10
+.byte 0
+.text
+.ident "LCC: 4.1"
diff --git a/lcc/x86/linux/tst/fields.1bk b/lcc/x86/linux/tst/fields.1bk
new file mode 100755
index 0000000..f30b13f
--- /dev/null
+++ b/lcc/x86/linux/tst/fields.1bk
@@ -0,0 +1,5 @@
+x = 1 2 3 4 -3 6
+y = 3 8 9
+x = 1 2 3 0 0 6
+y = 2 8 16
+p->a = 0x3, p->b = 0xf
diff --git a/lcc/x86/linux/tst/fields.2bk b/lcc/x86/linux/tst/fields.2bk
new file mode 100755
index 0000000..e689d78
--- /dev/null
+++ b/lcc/x86/linux/tst/fields.2bk
@@ -0,0 +1,4 @@
+tst/fields.c:6: warning: initializer exceeds bit-field width
+tst/fields.c:8: warning: initializer exceeds bit-field width
+tst/fields.c:30: warning: missing return value
+tst/fields.c:34: warning: missing return value
diff --git a/lcc/x86/linux/tst/fields.sbk b/lcc/x86/linux/tst/fields.sbk
new file mode 100755
index 0000000..44607ae
--- /dev/null
+++ b/lcc/x86/linux/tst/fields.sbk
@@ -0,0 +1,321 @@
+.data
+.globl x
+.align 4
+.type x,@object
+.size x,16
+x:
+.long 1
+.byte 2
+.space 3
+.byte 3
+.byte 64
+.space 2
+.byte 80
+.byte 6
+.space 2
+.globl i
+.align 4
+.type i,@object
+.size i,4
+i:
+.long 16
+.globl y
+.align 4
+.type y,@object
+.size y,8
+y:
+.byte 35
+.space 3
+.byte 9
+.byte 0
+.byte 0
+.byte 0
+.globl main
+.text
+.align 16
+.type main,@function
+main:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movsbl x+13,%edi
+pushl %edi
+movl x+12,%edi
+sall $25,%edi
+sarl $29,%edi
+pushl %edi
+movl x+8,%edi
+sall $16,%edi
+sarl $28,%edi
+pushl %edi
+movl x+8,%edi
+sall $20,%edi
+sarl $20,%edi
+pushl %edi
+movsbl x+4,%edi
+pushl %edi
+pushl x
+pushl $.LC4
+call printf
+addl $28,%esp
+pushl y+4
+movl y,%edi
+movl %edi,%esi
+shrl $2,%esi
+andl $15,%esi
+pushl %esi
+andl $3,%edi
+pushl %edi
+pushl $.LC10
+call printf
+addl $16,%esp
+movl x+8,%edi
+andl $0xffff0fff,%edi
+movl i,%esi
+sall $28,%esi
+sarl $28,%esi
+shll $12,%esi
+andl $0xf000,%esi
+orl %esi,%edi
+movl %edi,x+8
+movl x+12,%edi
+andl $0xffffff8f,%edi
+movl %edi,x+12
+movsbl x+13,%edi
+pushl %edi
+movl x+12,%edi
+sall $25,%edi
+sarl $29,%edi
+pushl %edi
+movl x+8,%edi
+sall $16,%edi
+sarl $28,%edi
+pushl %edi
+movl x+8,%edi
+sall $20,%edi
+sarl $20,%edi
+pushl %edi
+movsbl x+4,%edi
+pushl %edi
+pushl x
+pushl $.LC4
+call printf
+addl $28,%esp
+movl y,%edi
+andl $0xfffffffc,%edi
+orl $2,%edi
+movl %edi,y
+movl i,%edi
+movl %edi,y+4
+pushl y+4
+movl y,%edi
+movl %edi,%esi
+shrl $2,%esi
+andl $15,%esi
+pushl %esi
+andl $3,%edi
+pushl %edi
+pushl $.LC10
+call printf
+addl $16,%esp
+pushl $x
+call f2
+addl $4,%esp
+movl $0,%eax
+.LC3:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf21:
+.size main,.Lf21-main
+.globl f1
+.align 16
+.type f1,@function
+f1:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl 20(%ebp),%edi
+andl $0xffffffc3,(,%edi)
+movl 20(%ebp),%edi
+movl (,%edi),%esi
+andl $0xfffffffc,%esi
+movl $0,%ebx
+andl $3,%ebx
+andl $3,%ebx
+orl %ebx,%esi
+movl %esi,(,%edi)
+movl 20(%ebp),%edi
+movl (,%edi),%edi
+andl $60,%edi
+cmpl $0,%edi
+je .LC23
+pushl $.LC25
+call printf
+addl $4,%esp
+.LC23:
+movl 20(%ebp),%edi
+orl $3,(,%edi)
+movl 20(%ebp),%edi
+orl $60,(,%edi)
+movl 20(%ebp),%edi
+movl (,%edi),%edi
+movl %edi,%esi
+shrl $2,%esi
+andl $15,%esi
+pushl %esi
+andl $3,%edi
+pushl %edi
+pushl $.LC26
+call printf
+addl $12,%esp
+movl $0,%eax
+.LC22:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf27:
+.size f1,.Lf27-f1
+.globl f2
+.align 16
+.type f2,@function
+f2:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $4,%esp
+cmpl $0,i
+jne .LC30
+movl $1,-4(%ebp)
+jmp .LC31
+.LC30:
+movl $0,-4(%ebp)
+.LC31:
+movl 20(%ebp),%edi
+movl (,%edi),%esi
+andl $0xfffffffc,%esi
+movl -4(%ebp),%ebx
+andl $3,%ebx
+andl $3,%ebx
+orl %ebx,%esi
+movl %esi,(,%edi)
+movl 20(%ebp),%edi
+pushl %edi
+call f1
+addl $4,%esp
+movl (,%edi),%esi
+andl $0xffffffc3,%esi
+movl $0,%ebx
+andl $15,%ebx
+leal (,%ebx,4),%ebx
+andl $60,%ebx
+orl %ebx,%esi
+movl %esi,(,%edi)
+movl $0,%eax
+.LC28:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf32:
+.size f2,.Lf32-f2
+.data
+.align 1
+.LC26:
+.byte 112
+.byte 45
+.byte 62
+.byte 97
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 120
+.byte 37
+.byte 120
+.byte 44
+.byte 32
+.byte 112
+.byte 45
+.byte 62
+.byte 98
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 120
+.byte 37
+.byte 120
+.byte 10
+.byte 0
+.align 1
+.LC25:
+.byte 112
+.byte 45
+.byte 62
+.byte 98
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 33
+.byte 10
+.byte 0
+.align 1
+.LC10:
+.byte 121
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC4:
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.text
+.ident "LCC: 4.1"
diff --git a/lcc/x86/linux/tst/front.2bk b/lcc/x86/linux/tst/front.2bk
new file mode 100755
index 0000000..841e6a5
--- /dev/null
+++ b/lcc/x86/linux/tst/front.2bk
@@ -0,0 +1,29 @@
+tst/front.c:3: warning: missing return value
+tst/front.c:10: warning: missing return value
+tst/front.c:20: type error in argument 1 to `s'; found `pointer to struct D' expected `pointer to incomplete struct D defined at tst/front.c:14'
+tst/front.c:21: warning: missing return value
+tst/front.c:32: warning: missing return value
+tst/front.c:36: operands of = have illegal types `pointer to int' and `pointer to const int'
+tst/front.c:38: warning: missing return value
+tst/front.c:62: operands of = have illegal types `pointer to char' and `pointer to const void'
+tst/front.c:63: warning: missing return value
+tst/front.c:68: warning: missing return value
+tst/front.c:69: warning: inconsistent linkage for `yy' previously declared at tst/front.c:68
+tst/front.c:69: warning: missing return value
+tst/front.c:71: invalid storage class `static' for `int function goo'
+tst/front.c:71: warning: declaration of `goo' does not match previous declaration at tst/front.c:70
+tst/front.c:71: warning: missing return value
+tst/front.c:74: warning: declaration of `xr' does not match previous declaration at tst/front.c:72
+tst/front.c:74: warning: missing return value
+tst/front.c:81: warning: missing return value
+tst/front.c:82: warning: declaration of `ss2' does not match previous declaration at tst/front.c:81
+tst/front.c:84: warning: inconsistent linkage for `ss5' previously declared at tst/front.c:80
+tst/front.c:92: type error in argument 1 to `gx1'; found `pointer to double' expected `double'
+tst/front.c:92: warning: missing return value
+tst/front.c:95: redeclaration of `hx1' previously declared at tst/front.c:94
+tst/front.c:98: warning: missing return value
+tst/front.c:101: conflicting argument declarations for function `gg1'
+tst/front.c:101: warning: missing return value
+tst/front.c:112: type error in argument 4 to `qsort'; found `pointer to int function(pointer to pointer to char,pointer to pointer to char)' expected `pointer to int function(pointer to const void,pointer to const void)'
+tst/front.c:113: warning: missing return value
+tst/front.c:120: warning: missing return value
diff --git a/lcc/x86/linux/tst/front.sbk b/lcc/x86/linux/tst/front.sbk
new file mode 100755
index 0000000..348b6fe
--- /dev/null
+++ b/lcc/x86/linux/tst/front.sbk
@@ -0,0 +1,530 @@
+.globl main
+.text
+.align 16
+.type main,@function
+main:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+pushl $0
+call exit
+addl $4,%esp
+movl $0,%eax
+.LC1:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf2:
+.size main,.Lf2-main
+.globl nested
+.align 16
+.type nested,@function
+nested:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+cmpl $4,20(%ebp)
+jge .LC7
+cmpl $114,24(%ebp)
+je .LC10
+.LC7:
+cmpl $1,20(%ebp)
+jne .LC9
+movl 24(%ebp),%edi
+cmpl $104,%edi
+je .LC10
+cmpl $105,%edi
+je .LC10
+.LC9:
+cmpl $2,20(%ebp)
+jne .LC4
+movl 24(%ebp),%edi
+cmpl $111,%edi
+je .LC10
+cmpl $121,%edi
+jne .LC4
+.LC10:
+movl 24(%ebp),%edi
+movl %edi,20(%ebp)
+.LC4:
+movl $0,%eax
+.LC3:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf11:
+.size nested,.Lf11-nested
+.globl s
+.align 16
+.type s,@function
+s:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+.LC12:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf13:
+.size s,.Lf13-s
+.data
+.globl Dy
+.align 4
+.type Dy,@object
+.size Dy,8
+Dy:
+.long 0
+.space 4
+.globl Dz
+.align 4
+.type Dz,@object
+.size Dz,8
+Dz:
+.long 1
+.space 4
+.globl Dfunc
+.text
+.align 16
+.type Dfunc,@function
+Dfunc:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf16:
+.size Dfunc,.Lf16-Dfunc
+.globl f
+.align 16
+.type f,@function
+f:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf18:
+.size f,.Lf18-f
+.globl f1
+.align 16
+.type f1,@function
+f1:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf20:
+.size f1,.Lf20-f1
+.globl f2
+.align 16
+.type f2,@function
+f2:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf22:
+.size f2,.Lf22-f2
+.globl g
+.align 16
+.type g,@function
+g:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf24:
+.size g,.Lf24-g
+.globl h
+.align 16
+.type h,@function
+h:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf26:
+.size h,.Lf26-h
+.globl h1
+.align 16
+.type h1,@function
+h1:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf28:
+.size h1,.Lf28-h1
+.globl h2
+.align 16
+.type h2,@function
+h2:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf30:
+.size h2,.Lf30-h2
+.data
+.align 4
+.type yy.32,@object
+.size yy.32,4
+yy.32:
+.long 1
+.globl set1
+.text
+.align 16
+.type set1,@function
+set1:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf33:
+.size set1,.Lf33-set1
+.data
+.align 4
+.type yy.35,@object
+.size yy.35,4
+yy.35:
+.long 2
+.globl set2
+.text
+.align 16
+.type set2,@function
+set2:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf36:
+.size set2,.Lf36-set2
+.align 16
+.type goo,@function
+goo:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf38:
+.size goo,.Lf38-goo
+.globl sss
+.align 16
+.type sss,@function
+sss:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf40:
+.size sss,.Lf40-sss
+.bss
+.align 4
+.type xr.42,@object
+.size xr.42,4
+.lcomm xr.42,4
+.globl rrr
+.text
+.align 16
+.type rrr,@function
+rrr:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf43:
+.size rrr,.Lf43-rrr
+.globl setstatic
+.align 16
+.type setstatic,@function
+setstatic:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf45:
+.size setstatic,.Lf45-setstatic
+.globl gx1
+.align 16
+.type gx1,@function
+gx1:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf47:
+.size gx1,.Lf47-gx1
+.globl ff1
+.align 16
+.type ff1,@function
+ff1:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf49:
+.size ff1,.Lf49-ff1
+.globl gg1
+.align 16
+.type gg1,@function
+gg1:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf51:
+.size gg1,.Lf51-gg1
+.globl hh1
+.align 16
+.type hh1,@function
+hh1:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf53:
+.size hh1,.Lf53-hh1
+.globl cmp
+.align 16
+.type cmp,@function
+cmp:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf55:
+.size cmp,.Lf55-cmp
+.globl sort
+.align 16
+.type sort,@function
+sort:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf57:
+.size sort,.Lf57-sort
+.globl onearg
+.align 16
+.type onearg,@function
+onearg:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf65:
+.size onearg,.Lf65-onearg
+.bss
+.globl ss4
+.align 4
+.type ss4,@object
+.size ss4,4
+.comm ss4,4
+.align 4
+.type ss2,@object
+.size ss2,4
+.lcomm ss2,4
+.align 4
+.type ss5,@object
+.size ss5,4
+.lcomm ss5,4
+.globl ss3
+.align 4
+.type ss3,@object
+.size ss3,4
+.comm ss3,4
+.align 4
+.type ss1,@object
+.size ss1,4
+.lcomm ss1,4
+.align 4
+.type yy,@object
+.size yy,4
+.lcomm yy,4
+.globl z
+.align 4
+.type z,@object
+.size z,4
+.comm z,4
+.globl y
+.align 4
+.type y,@object
+.size y,4
+.comm y,4
+.globl x
+.align 4
+.type x,@object
+.size x,4
+.comm x,4
+.globl b
+.align 4
+.type b,@object
+.size b,4
+.comm b,4
+.globl a
+.align 4
+.type a,@object
+.size a,4
+.comm a,4
+.text
+.ident "LCC: 4.1"
diff --git a/lcc/x86/linux/tst/incr.1bk b/lcc/x86/linux/tst/incr.1bk
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/x86/linux/tst/incr.1bk
diff --git a/lcc/x86/linux/tst/incr.2bk b/lcc/x86/linux/tst/incr.2bk
new file mode 100755
index 0000000..b86c400
--- /dev/null
+++ b/lcc/x86/linux/tst/incr.2bk
@@ -0,0 +1,9 @@
+tst/incr.c:1: warning: missing return value
+tst/incr.c:6: warning: expression with no effect elided
+tst/incr.c:6: warning: expression with no effect elided
+tst/incr.c:11: warning: missing return value
+tst/incr.c:16: warning: expression with no effect elided
+tst/incr.c:16: warning: expression with no effect elided
+tst/incr.c:21: warning: missing return value
+tst/incr.c:30: warning: missing return value
+tst/incr.c:39: warning: missing return value
diff --git a/lcc/x86/linux/tst/incr.sbk b/lcc/x86/linux/tst/incr.sbk
new file mode 100755
index 0000000..1179a8a
--- /dev/null
+++ b/lcc/x86/linux/tst/incr.sbk
@@ -0,0 +1,181 @@
+.globl main
+.text
+.align 16
+.type main,@function
+main:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl $0,%eax
+.LC1:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf2:
+.size main,.Lf2-main
+.globl memchar
+.align 16
+.type memchar,@function
+memchar:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $8,%esp
+movl -8(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-8(%ebp)
+movb (,%edi),%bl
+movb %bl,-1(%ebp)
+movl -8(%ebp),%edi
+leal 1(%edi),%edi
+movl %edi,-8(%ebp)
+movb (,%edi),%bl
+movb %bl,-1(%ebp)
+movl -8(%ebp),%edi
+leal -1(%edi),%esi
+movl %esi,-8(%ebp)
+movb (,%edi),%bl
+movb %bl,-1(%ebp)
+movl -8(%ebp),%edi
+leal -1(%edi),%edi
+movl %edi,-8(%ebp)
+movb (,%edi),%bl
+movb %bl,-1(%ebp)
+movl $0,%eax
+.LC3:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf4:
+.size memchar,.Lf4-memchar
+.globl memint
+.align 16
+.type memint,@function
+memint:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $8,%esp
+movl -8(%ebp),%edi
+leal 4(%edi),%esi
+movl %esi,-8(%ebp)
+movl (,%edi),%edi
+movl %edi,-4(%ebp)
+movl -8(%ebp),%edi
+leal 4(%edi),%edi
+movl %edi,-8(%ebp)
+movl (,%edi),%edi
+movl %edi,-4(%ebp)
+movl -8(%ebp),%edi
+leal -4(%edi),%esi
+movl %esi,-8(%ebp)
+movl (,%edi),%edi
+movl %edi,-4(%ebp)
+movl -8(%ebp),%edi
+leal -4(%edi),%edi
+movl %edi,-8(%ebp)
+movl (,%edi),%edi
+movl %edi,-4(%ebp)
+movl $0,%eax
+.LC5:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf6:
+.size memint,.Lf6-memint
+.globl regchar
+.align 16
+.type regchar,@function
+regchar:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $8,%esp
+movl -8(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-8(%ebp)
+movb (,%edi),%bl
+movb %bl,-1(%ebp)
+movl -8(%ebp),%edi
+leal 1(%edi),%edi
+movl %edi,-8(%ebp)
+movb (,%edi),%bl
+movb %bl,-1(%ebp)
+movl -8(%ebp),%edi
+leal -1(%edi),%esi
+movl %esi,-8(%ebp)
+movb (,%edi),%bl
+movb %bl,-1(%ebp)
+movl -8(%ebp),%edi
+leal -1(%edi),%edi
+movl %edi,-8(%ebp)
+movb (,%edi),%bl
+movb %bl,-1(%ebp)
+movl $0,%eax
+.LC7:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf8:
+.size regchar,.Lf8-regchar
+.globl regint
+.align 16
+.type regint,@function
+regint:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $8,%esp
+movl -8(%ebp),%edi
+leal 4(%edi),%esi
+movl %esi,-8(%ebp)
+movl (,%edi),%edi
+movl %edi,-4(%ebp)
+movl -8(%ebp),%edi
+leal 4(%edi),%edi
+movl %edi,-8(%ebp)
+movl (,%edi),%edi
+movl %edi,-4(%ebp)
+movl -8(%ebp),%edi
+leal -4(%edi),%esi
+movl %esi,-8(%ebp)
+movl (,%edi),%edi
+movl %edi,-4(%ebp)
+movl -8(%ebp),%edi
+leal -4(%edi),%edi
+movl %edi,-8(%ebp)
+movl (,%edi),%edi
+movl %edi,-4(%ebp)
+movl $0,%eax
+.LC9:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf10:
+.size regint,.Lf10-regint
+.ident "LCC: 4.1"
diff --git a/lcc/x86/linux/tst/init.1bk b/lcc/x86/linux/tst/init.1bk
new file mode 100755
index 0000000..042f3bb
--- /dev/null
+++ b/lcc/x86/linux/tst/init.1bk
@@ -0,0 +1,16 @@
+ 1 2 3 4
+ 5 6
+ 7
+if
+for
+else
+while
+1 2 3 if
+4 5 0 for
+6 7 8 else
+9 10 11 while
+1 2 3 if
+4 5 0 for
+6 7 8 else
+9 10 11 while
+0 0 0
diff --git a/lcc/x86/linux/tst/init.2bk b/lcc/x86/linux/tst/init.2bk
new file mode 100755
index 0000000..da08062
--- /dev/null
+++ b/lcc/x86/linux/tst/init.2bk
@@ -0,0 +1,3 @@
+tst/init.c:36: warning: missing return value
+tst/init.c:49: warning: missing return value
+tst/init.c:59: warning: missing return value
diff --git a/lcc/x86/linux/tst/init.sbk b/lcc/x86/linux/tst/init.sbk
new file mode 100755
index 0000000..843e281
--- /dev/null
+++ b/lcc/x86/linux/tst/init.sbk
@@ -0,0 +1,336 @@
+.data
+.globl words
+.align 4
+.type words,@object
+words:
+.long 1
+.long 2
+.long 3
+.byte 105
+.byte 102
+.byte 0
+.space 3
+.space 2
+.long 4
+.long 5
+.space 4
+.byte 102
+.byte 111
+.byte 114
+.space 3
+.space 2
+.long 6
+.long 7
+.long 8
+.byte 101
+.byte 108
+.byte 115
+.byte 101
+.byte 0
+.space 1
+.space 2
+.long 9
+.long 10
+.long 11
+.byte 119
+.byte 104
+.byte 105
+.byte 108
+.byte 101
+.space 1
+.space 2
+.long 0
+.space 8
+.space 8
+.size words,100
+.globl wordlist
+.align 4
+.type wordlist,@object
+.size wordlist,4
+wordlist:
+.long words
+.globl x
+.align 4
+.type x,@object
+x:
+.long 1
+.long 2
+.long 3
+.long 4
+.long 0
+.long 5
+.long 6
+.space 12
+.long 7
+.space 16
+.size x,60
+.globl y
+.align 4
+.type y,@object
+y:
+.long x
+.long x+20
+.long x+40
+.long 0
+.size y,16
+.globl main
+.text
+.align 16
+.type main,@function
+main:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $8,%esp
+movl $0,-8(%ebp)
+jmp .LC8
+.LC5:
+movl $0,-4(%ebp)
+jmp .LC12
+.LC9:
+movl -4(%ebp),%edi
+movl -8(%ebp),%esi
+movl y(,%esi,4),%esi
+pushl (%esi,%edi,4)
+pushl $.LC13
+call printf
+addl $8,%esp
+.LC10:
+incl -4(%ebp)
+.LC12:
+movl -4(%ebp),%edi
+movl -8(%ebp),%esi
+movl y(,%esi,4),%esi
+cmpl $0,(%esi,%edi,4)
+jne .LC9
+pushl $.LC14
+call printf
+addl $4,%esp
+.LC6:
+incl -8(%ebp)
+.LC8:
+movl -8(%ebp),%edi
+movl y(,%edi,4),%edi
+cmpl $0,%edi
+jne .LC5
+call f
+pushl wordlist
+call g
+addl $4,%esp
+movl $0,%eax
+.LC4:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf15:
+.size main,.Lf15-main
+.data
+.align 4
+.type keywords.17,@object
+keywords.17:
+.long .LC18
+.long .LC19
+.long .LC20
+.long .LC21
+.long 0
+.size keywords.17,20
+.globl f
+.text
+.align 16
+.type f,@function
+f:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $4,%esp
+leal keywords.17,%edi
+movl %edi,-4(%ebp)
+jmp .LC25
+.LC22:
+movl -4(%ebp),%edi
+pushl (,%edi)
+pushl $.LC26
+call printf
+addl $8,%esp
+.LC23:
+movl -4(%ebp),%edi
+leal 4(%edi),%edi
+movl %edi,-4(%ebp)
+.LC25:
+movl -4(%ebp),%edi
+movl (,%edi),%edi
+cmpl $0,%edi
+jne .LC22
+movl $0,%eax
+.LC16:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf27:
+.size f,.Lf27-f
+.globl g
+.align 16
+.type g,@function
+g:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $4,%esp
+jmp .LC32
+.LC29:
+movl $0,-4(%ebp)
+jmp .LC36
+.LC33:
+movl -4(%ebp),%edi
+movl 20(%ebp),%esi
+pushl (%esi,%edi,4)
+pushl $.LC37
+call printf
+addl $8,%esp
+.LC34:
+incl -4(%ebp)
+.LC36:
+movl -4(%ebp),%edi
+cmpl $3,%edi
+jb .LC33
+movl 20(%ebp),%edi
+leal 12(%edi),%edi
+pushl %edi
+pushl $.LC26
+call printf
+addl $8,%esp
+.LC30:
+movl 20(%ebp),%edi
+leal 20(%edi),%edi
+movl %edi,20(%ebp)
+.LC32:
+movl 20(%ebp),%edi
+cmpl $0,(,%edi)
+jne .LC29
+call h
+movl $0,%eax
+.LC28:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf38:
+.size g,.Lf38-g
+.globl h
+.align 16
+.type h,@function
+h:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $4,%esp
+movl $0,-4(%ebp)
+jmp .LC43
+.LC40:
+imul $20,-4(%ebp),%edi
+leal words+12(%edi),%esi
+pushl %esi
+pushl words+8(%edi)
+pushl words+4(%edi)
+pushl words(%edi)
+pushl $.LC44
+call printf
+addl $20,%esp
+.LC41:
+incl -4(%ebp)
+.LC43:
+movl -4(%ebp),%edi
+cmpl $5,%edi
+jb .LC40
+movl $0,%eax
+.LC39:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf48:
+.size h,.Lf48-h
+.data
+.align 1
+.LC44:
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.LC37:
+.byte 37
+.byte 100
+.byte 32
+.byte 0
+.align 1
+.LC26:
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.LC21:
+.byte 119
+.byte 104
+.byte 105
+.byte 108
+.byte 101
+.byte 0
+.align 1
+.LC20:
+.byte 101
+.byte 108
+.byte 115
+.byte 101
+.byte 0
+.align 1
+.LC19:
+.byte 102
+.byte 111
+.byte 114
+.byte 0
+.align 1
+.LC18:
+.byte 105
+.byte 102
+.byte 0
+.align 1
+.LC14:
+.byte 10
+.byte 0
+.align 1
+.LC13:
+.byte 32
+.byte 37
+.byte 100
+.byte 0
+.text
+.ident "LCC: 4.1"
diff --git a/lcc/x86/linux/tst/limits.1bk b/lcc/x86/linux/tst/limits.1bk
new file mode 100755
index 0000000..f0c1dc8
--- /dev/null
+++ b/lcc/x86/linux/tst/limits.1bk
@@ -0,0 +1,14 @@
+UCHAR_MAX: 000000ff=255
+USHRT_MAX: 0000ffff=65535
+UINT_MAX: ffffffff=-1
+ULONG_MAX: ffffffff=-1
+CHAR_MAX: 0000007f=127
+SCHAR_MAX: 0000007f=127
+SHRT_MAX: 00007fff=32767
+INT_MAX: 7fffffff=2147483647
+LONG_MAX: 7fffffff=2147483647
+CHAR_MIN: ffffff80=-128
+SCHAR_MIN: ffffff80=-128
+SHRT_MIN: ffff8000=-32768
+INT_MIN: 80000000=-2147483648
+LONG_MIN: 80000000=-2147483648
diff --git a/lcc/x86/linux/tst/limits.2bk b/lcc/x86/linux/tst/limits.2bk
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/x86/linux/tst/limits.2bk
diff --git a/lcc/x86/linux/tst/limits.sbk b/lcc/x86/linux/tst/limits.sbk
new file mode 100755
index 0000000..bed5d18
--- /dev/null
+++ b/lcc/x86/linux/tst/limits.sbk
@@ -0,0 +1,396 @@
+.globl main
+.text
+.align 16
+.type main,@function
+main:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+pushl $255
+pushl $255
+pushl $.LC2
+call printf
+addl $12,%esp
+pushl $65535
+pushl $65535
+pushl $.LC3
+call printf
+addl $12,%esp
+pushl $0xffffffff
+pushl $0xffffffff
+pushl $.LC4
+call printf
+addl $12,%esp
+pushl $0xffffffff
+pushl $0xffffffff
+pushl $.LC5
+call printf
+addl $12,%esp
+pushl $127
+pushl $127
+pushl $.LC6
+call printf
+addl $12,%esp
+pushl $127
+pushl $127
+pushl $.LC7
+call printf
+addl $12,%esp
+pushl $32767
+pushl $32767
+pushl $.LC8
+call printf
+addl $12,%esp
+pushl $2147483647
+pushl $2147483647
+pushl $.LC9
+call printf
+addl $12,%esp
+pushl $2147483647
+pushl $2147483647
+pushl $.LC10
+call printf
+addl $12,%esp
+pushl $-128
+pushl $-128
+pushl $.LC11
+call printf
+addl $12,%esp
+pushl $-128
+pushl $-128
+pushl $.LC12
+call printf
+addl $12,%esp
+pushl $-32768
+pushl $-32768
+pushl $.LC13
+call printf
+addl $12,%esp
+pushl $-2147483648
+pushl $-2147483648
+pushl $.LC14
+call printf
+addl $12,%esp
+pushl $-2147483648
+pushl $-2147483648
+pushl $.LC15
+call printf
+addl $12,%esp
+movl $0,%eax
+.LC1:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf16:
+.size main,.Lf16-main
+.data
+.align 1
+.LC15:
+.byte 76
+.byte 79
+.byte 78
+.byte 71
+.byte 95
+.byte 77
+.byte 73
+.byte 78
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 108
+.byte 120
+.byte 61
+.byte 37
+.byte 108
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC14:
+.byte 73
+.byte 78
+.byte 84
+.byte 95
+.byte 77
+.byte 73
+.byte 78
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC13:
+.byte 83
+.byte 72
+.byte 82
+.byte 84
+.byte 95
+.byte 77
+.byte 73
+.byte 78
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC12:
+.byte 83
+.byte 67
+.byte 72
+.byte 65
+.byte 82
+.byte 95
+.byte 77
+.byte 73
+.byte 78
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC11:
+.byte 67
+.byte 72
+.byte 65
+.byte 82
+.byte 95
+.byte 77
+.byte 73
+.byte 78
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC10:
+.byte 76
+.byte 79
+.byte 78
+.byte 71
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 108
+.byte 120
+.byte 61
+.byte 37
+.byte 108
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC9:
+.byte 73
+.byte 78
+.byte 84
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC8:
+.byte 83
+.byte 72
+.byte 82
+.byte 84
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC7:
+.byte 83
+.byte 67
+.byte 72
+.byte 65
+.byte 82
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC6:
+.byte 67
+.byte 72
+.byte 65
+.byte 82
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC5:
+.byte 85
+.byte 76
+.byte 79
+.byte 78
+.byte 71
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 108
+.byte 120
+.byte 61
+.byte 37
+.byte 108
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC4:
+.byte 85
+.byte 73
+.byte 78
+.byte 84
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC3:
+.byte 85
+.byte 83
+.byte 72
+.byte 82
+.byte 84
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC2:
+.byte 85
+.byte 67
+.byte 72
+.byte 65
+.byte 82
+.byte 95
+.byte 77
+.byte 65
+.byte 88
+.byte 58
+.byte 9
+.byte 37
+.byte 48
+.byte 56
+.byte 120
+.byte 61
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.text
+.ident "LCC: 4.1"
diff --git a/lcc/x86/linux/tst/paranoia.1bk b/lcc/x86/linux/tst/paranoia.1bk
new file mode 100755
index 0000000..da344e6
--- /dev/null
+++ b/lcc/x86/linux/tst/paranoia.1bk
@@ -0,0 +1,183 @@
+Lest this program stop prematurely, i.e. before displaying
+
+ `END OF TEST',
+
+try to persuade the computer NOT to terminate execution when an
+error like Over/Underflow or Division by Zero occurs, but rather
+to persevere with a surrogate value after, perhaps, displaying some
+warning. If persuasion avails naught, don't despair but run this
+program anyway to see how many milestones it passes, and then
+amend it to make further progress.
+
+Answer questions with Y, y, N or n (unless otherwise indicated).
+
+
+Diagnosis resumes after milestone Number 0 Page: 1
+
+Users are invited to help debug and augment this program so it will
+cope with unanticipated and newly uncovered arithmetic pathologies.
+
+Please send suggestions and interesting results to
+ Richard Karpinski
+ Computer Center U-76
+ University of California
+ San Francisco, CA 94143-0704, USA
+
+In doing so, please include the following information:
+ Precision: double;
+ Version: 10 February 1989;
+ Computer:
+
+ Compiler:
+
+ Optimization level:
+
+ Other relevant compiler options:
+
+Diagnosis resumes after milestone Number 1 Page: 2
+
+Running this program should reveal these characteristics:
+ Radix = 1, 2, 4, 8, 10, 16, 100, 256 ...
+ Precision = number of significant digits carried.
+ U2 = Radix/Radix^Precision = One Ulp
+ (OneUlpnit in the Last Place) of 1.000xxx .
+ U1 = 1/Radix^Precision = One Ulp of numbers a little less than 1.0 .
+ Adequacy of guard digits for Mult., Div. and Subt.
+ Whether arithmetic is chopped, correctly rounded, or something else
+ for Mult., Div., Add/Subt. and Sqrt.
+ Whether a Sticky Bit used correctly for rounding.
+ UnderflowThreshold = an underflow threshold.
+ E0 and PseudoZero tell whether underflow is abrupt, gradual, or fuzzy.
+ V = an overflow threshold, roughly.
+ V0 tells, roughly, whether Infinity is represented.
+ Comparisions are checked for consistency with subtraction
+ and for contamination with pseudo-zeros.
+ Sqrt is tested. Y^X is not tested.
+ Extra-precise subexpressions are revealed but NOT YET tested.
+ Decimal-Binary conversion is NOT YET tested for accuracy.
+
+Diagnosis resumes after milestone Number 2 Page: 3
+
+The program attempts to discriminate among
+ FLAWs, like lack of a sticky bit,
+ Serious DEFECTs, like lack of a guard digit, and
+ FAILUREs, like 2+2 == 5 .
+Failures may confound subsequent diagnoses.
+
+The diagnostic capabilities of this program go beyond an earlier
+program called `MACHAR', which can be found at the end of the
+book `Software Manual for the Elementary Functions' (1980) by
+W. J. Cody and W. Waite. Although both programs try to discover
+the Radix, Precision and range (over/underflow thresholds)
+of the arithmetic, this program tries to cope with a wider variety
+of pathologies, and to say how well the arithmetic is implemented.
+
+The program is based upon a conventional radix representation for
+floating-point numbers, but also allows logarithmic encoding
+as used by certain early WANG machines.
+
+BASIC version of this program (C) 1983 by Prof. W. M. Kahan;
+see source comments for more history.
+
+Diagnosis resumes after milestone Number 3 Page: 4
+
+Program is now RUNNING tests on small integers:
+-1, 0, 1/2, 1, 2, 3, 4, 5, 9, 27, 32 & 240 are O.K.
+
+Searching for Radix and Precision.
+Radix = 2.000000 .
+Closest relative separation found is U1 = 1.1102230e-16 .
+
+Recalculating radix and precision
+ confirms closest relative separation U1 .
+Radix confirmed.
+The number of significant digits of the Radix is 53.000000 .
+Some subexpressions appear to be calculated extra
+precisely with about 11 extra B-digits, i.e.
+roughly 3.31133 extra significant decimals.
+That feature is not tested further by this program.
+
+Diagnosis resumes after milestone Number 30 Page: 5
+
+Subtraction appears to be normalized, as it should be.
+Checking for guard digit in *, /, and -.
+ *, /, and - appear to have guard digits, as they should.
+
+Diagnosis resumes after milestone Number 40 Page: 6
+
+Checking rounding on multiply, divide and add/subtract.
+* is neither chopped nor correctly rounded.
+/ is neither chopped nor correctly rounded.
+Addition/Subtraction neither rounds nor chops.
+Sticky bit used incorrectly or not at all.
+FLAW: lack(s) of guard digits or failure(s) to correctly round or chop
+(noted above) count as one flaw in the final tally below.
+
+Does Multiplication commute? Testing on 20 random pairs.
+ No failures found in 20 integer pairs.
+
+Running test of square root(x).
+Testing if sqrt(X * X) == X for 20 Integers X.
+Test for sqrt monotonicity.
+sqrt has passed a test for Monotonicity.
+Testing whether sqrt is rounded or chopped.
+Square root is neither chopped nor correctly rounded.
+Observed errors run from -5.0000000e-01 to 5.0000000e-01 ulps.
+
+Diagnosis resumes after milestone Number 90 Page: 7
+
+Testing powers Z^i for small Integers Z and i.
+... no discrepancis found.
+
+Seeking Underflow thresholds UfThold and E0.
+Smallest strictly positive number found is E0 = 4.94066e-324 .
+Since comparison denies Z = 0, evaluating (Z + Z) / Z should be safe.
+What the machine gets for (Z + Z) / Z is 2.00000000000000000e+00 .
+This is O.K., provided Over/Underflow has NOT just been signaled.
+Underflow is gradual; it incurs Absolute Error =
+(roundoff in UfThold) < E0.
+The Underflow threshold is 2.22507385850720188e-308, below which
+calculation may suffer larger Relative error than merely roundoff.
+Since underflow occurs below the threshold
+UfThold = (2.00000000000000000e+00) ^ (-1.02200000000000000e+03)
+only underflow should afflict the expression
+ (2.00000000000000000e+00) ^ (-1.02200000000000000e+03);
+actually calculating yields: 0.00000000000000000e+00 .
+This computed value is O.K.
+
+Testing X^((X + 1) / (X - 1)) vs. exp(2) = 7.38905609893065218e+00 as X -> 1.
+Accuracy seems adequate.
+Testing powers Z^Q at four nearly extreme values.
+ ... no discrepancies found.
+
+
+Diagnosis resumes after milestone Number 160 Page: 8
+
+Searching for Overflow threshold:
+This may generate an error.
+Can `Z = -Y' overflow?
+Trying it on Y = -Inf .
+Seems O.K.
+Overflow threshold is V = 1.79769313486231571e+308 .
+Overflow saturates at V0 = Inf .
+No Overflow should be signaled for V * 1 = 1.79769313486231571e+308
+ nor for V / 1 = 1.79769313486231571e+308 .
+Any overflow signal separating this * from the one
+above is a DEFECT.
+
+
+Diagnosis resumes after milestone Number 190 Page: 9
+
+
+What message and/or values does Division by Zero produce?
+ Trying to compute 1 / 0 produces ... Inf .
+
+ Trying to compute 0 / 0 produces ... NaN .
+
+Diagnosis resumes after milestone Number 220 Page: 10
+
+
+The number of FLAWs discovered = 1.
+
+The arithmetic diagnosed seems Satisfactory though flawed.
+END OF TEST.
diff --git a/lcc/x86/linux/tst/paranoia.2bk b/lcc/x86/linux/tst/paranoia.2bk
new file mode 100755
index 0000000..f6ddf16
--- /dev/null
+++ b/lcc/x86/linux/tst/paranoia.2bk
@@ -0,0 +1,16 @@
+tst/paranoia.c:1867: warning: missing return value
+tst/paranoia.c:1874: warning: missing return value
+tst/paranoia.c:1884: warning: missing return value
+tst/paranoia.c:1924: warning: missing return value
+tst/paranoia.c:1939: warning: missing return value
+tst/paranoia.c:1956: warning: missing return value
+tst/paranoia.c:1975: warning: missing return value
+tst/paranoia.c:1988: warning: missing return value
+tst/paranoia.c:1995: warning: missing return value
+tst/paranoia.c:2055: warning: missing return value
+tst/paranoia.c:2062: warning: missing return value
+tst/paranoia.c:2070: warning: missing return value
+tst/paranoia.c:2087: warning: missing return value
+tst/paranoia.c:2115: warning: missing return value
+tst/paranoia.c:2144: warning: missing return value
+tst/paranoia.c:2173: warning: missing return value
diff --git a/lcc/x86/linux/tst/paranoia.sbk b/lcc/x86/linux/tst/paranoia.sbk
new file mode 100755
index 0000000..79c571c
--- /dev/null
+++ b/lcc/x86/linux/tst/paranoia.sbk
@@ -0,0 +1,20248 @@
+.data
+.globl Zero
+.align 4
+.type Zero,@object
+.size Zero,8
+Zero:
+.long 0
+.long 0
+.globl Half
+.align 4
+.type Half,@object
+.size Half,8
+Half:
+.long 0
+.long 1071644672
+.globl One
+.align 4
+.type One,@object
+.size One,8
+One:
+.long 0
+.long 1072693248
+.globl Two
+.align 4
+.type Two,@object
+.size Two,8
+Two:
+.long 0
+.long 1073741824
+.globl Three
+.align 4
+.type Three,@object
+.size Three,8
+Three:
+.long 0
+.long 1074266112
+.globl Four
+.align 4
+.type Four,@object
+.size Four,8
+Four:
+.long 0
+.long 1074790400
+.globl Five
+.align 4
+.type Five,@object
+.size Five,8
+Five:
+.long 0
+.long 1075052544
+.globl Eight
+.align 4
+.type Eight,@object
+.size Eight,8
+Eight:
+.long 0
+.long 1075838976
+.globl Nine
+.align 4
+.type Nine,@object
+.size Nine,8
+Nine:
+.long 0
+.long 1075970048
+.globl TwentySeven
+.align 4
+.type TwentySeven,@object
+.size TwentySeven,8
+TwentySeven:
+.long 0
+.long 1077608448
+.globl ThirtyTwo
+.align 4
+.type ThirtyTwo,@object
+.size ThirtyTwo,8
+ThirtyTwo:
+.long 0
+.long 1077936128
+.globl TwoForty
+.align 4
+.type TwoForty,@object
+.size TwoForty,8
+TwoForty:
+.long 0
+.long 1080950784
+.globl MinusOne
+.align 4
+.type MinusOne,@object
+.size MinusOne,8
+MinusOne:
+.long 0
+.long -1074790400
+.globl OneAndHalf
+.align 4
+.type OneAndHalf,@object
+.size OneAndHalf,8
+OneAndHalf:
+.long 0
+.long 1073217536
+.globl NoTrials
+.align 4
+.type NoTrials,@object
+.size NoTrials,4
+NoTrials:
+.long 20
+.globl sigfpe
+.text
+.align 16
+.type sigfpe,@function
+sigfpe:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+incl fpecount
+pushl $.LC3
+call printf
+addl $4,%esp
+pushl $_IO_stdout_
+call fflush
+addl $4,%esp
+movl sigsave,%edi
+cmpl $0,%edi
+je .LC4
+pushl sigsave
+pushl $8
+call signal
+addl $8,%esp
+movl $0,sigsave
+pushl $1
+pushl $ovfl_buf
+call longjmp
+addl $8,%esp
+.LC4:
+call abort
+.LC2:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf6:
+.size sigfpe,.Lf6-sigfpe
+.data
+.align 4
+.type msg.758,@object
+msg.758:
+.long .LC759
+.long .LC760
+.long .LC761
+.long .LC762
+.size msg.758,16
+.globl main
+.text
+.align 16
+.type main,@function
+main:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $1684,%esp
+fldl .LC8
+fstpl Zero
+fldl .LC9
+fstpl One
+fldl One
+fstpl -8(%ebp)
+fldl -8(%ebp)
+faddl -8(%ebp)
+fstpl Two
+fldl Two
+fstpl -16(%ebp)
+fldl -16(%ebp)
+faddl -8(%ebp)
+fstpl Three
+fldl Three
+fstpl -24(%ebp)
+fldl -24(%ebp)
+faddl -8(%ebp)
+fstpl Four
+fldl Four
+fstpl -32(%ebp)
+fldl -32(%ebp)
+faddl -8(%ebp)
+fstpl Five
+fldl -32(%ebp)
+faddl -32(%ebp)
+fstpl Eight
+fldl -24(%ebp)
+fmull -24(%ebp)
+fstpl Nine
+fldl Nine
+fmull -24(%ebp)
+fstpl TwentySeven
+fldl -32(%ebp)
+fmull Eight
+fstpl ThirtyTwo
+fldl -32(%ebp)
+fmull Five
+fmull -24(%ebp)
+fmull -32(%ebp)
+fstpl TwoForty
+fldl -8(%ebp)
+fchs
+fstpl MinusOne
+fldl -8(%ebp)
+fdivl -16(%ebp)
+fstpl Half
+fldl -8(%ebp)
+faddl Half
+fstpl OneAndHalf
+movl $0,ErrCnt
+movl $0,ErrCnt+4
+movl $0,ErrCnt+8
+movl $0,ErrCnt+12
+movl $1,PageNo
+movl $0,Milestone
+pushl $sigfpe
+pushl $8
+call signal
+addl $8,%esp
+call Instructions
+call Pause
+call Heading
+call Pause
+call Characteristics
+call Pause
+call History
+call Pause
+movl $7,Milestone
+pushl $.LC13
+call printf
+addl $4,%esp
+pushl $.LC15
+fldl Zero
+faddl Zero
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC16
+fldl One
+fsubl One
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC16
+fldl Zero
+fcompl One
+fstsw %ax
+sahf
+jae .LC16
+fldl One
+faddl One
+fldl Two
+fcompp
+fstsw %ax
+sahf
+jne .LC16
+movl $1,-36(%ebp)
+jmp .LC17
+.LC16:
+movl $0,-36(%ebp)
+.LC17:
+pushl -36(%ebp)
+pushl $0
+call TstCond
+addl $12,%esp
+fldl Zero
+fchs
+fstpl Z
+fldl .LC8
+fcompl Z
+fstsw %ax
+sahf
+je .LC18
+incl ErrCnt
+pushl $.LC20
+call printf
+addl $4,%esp
+fldl .LC21
+fstpl U1
+fldl .LC9
+fstpl Radix
+call TstPtUf
+.LC18:
+pushl $.LC23
+fldl Two
+faddl One
+fcompl Three
+fstsw %ax
+sahf
+jne .LC24
+fldl Three
+faddl One
+fcompl Four
+fstsw %ax
+sahf
+jne .LC24
+fldl Four
+fldl Two
+fldl Two
+fchs
+fmulp %st(1),%st
+faddp %st(1),%st
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC24
+fldl Four
+fsubl Three
+fsubl One
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC24
+movl $1,-56(%ebp)
+jmp .LC25
+.LC24:
+movl $0,-56(%ebp)
+.LC25:
+pushl -56(%ebp)
+pushl $0
+call TstCond
+addl $12,%esp
+fldl .LC8
+fsubl One
+fcompl MinusOne
+fstsw %ax
+sahf
+jne .LC28
+fldl MinusOne
+faddl One
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC28
+fldl One
+faddl MinusOne
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC28
+fldl One
+subl $8,%esp
+fstpl (%esp)
+call fabs
+addl $8,%esp
+fstpl -132(%ebp)
+fldl MinusOne
+faddl -132(%ebp)
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC28
+fldl MinusOne
+fldl MinusOne
+fmull MinusOne
+faddp %st(1),%st
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC28
+movl $1,-100(%ebp)
+jmp .LC29
+.LC28:
+movl $0,-100(%ebp)
+.LC29:
+pushl $.LC27
+pushl -100(%ebp)
+pushl $0
+call TstCond
+addl $12,%esp
+pushl $.LC31
+fldl Half
+faddl MinusOne
+faddl Half
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC32
+movl $1,-152(%ebp)
+jmp .LC33
+.LC32:
+movl $0,-152(%ebp)
+.LC33:
+pushl -152(%ebp)
+pushl $0
+call TstCond
+addl $12,%esp
+movl $10,Milestone
+pushl $.LC35
+fldl Three
+fmull Three
+fcompl Nine
+fstsw %ax
+sahf
+jne .LC36
+fldl Nine
+fmull Three
+fcompl TwentySeven
+fstsw %ax
+sahf
+jne .LC36
+fldl Four
+faddl Four
+fcompl Eight
+fstsw %ax
+sahf
+jne .LC36
+fldl Eight
+fmull Four
+fcompl ThirtyTwo
+fstsw %ax
+sahf
+jne .LC36
+fldl ThirtyTwo
+fsubl TwentySeven
+fsubl Four
+fsubl One
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC36
+movl $1,-164(%ebp)
+jmp .LC37
+.LC36:
+movl $0,-164(%ebp)
+.LC37:
+pushl -164(%ebp)
+pushl $0
+call TstCond
+addl $12,%esp
+pushl $.LC39
+fldl Four
+faddl One
+fcompl Five
+fstsw %ax
+sahf
+jne .LC40
+fldl Four
+fmull Five
+fmull Three
+fmull Four
+fcompl TwoForty
+fstsw %ax
+sahf
+jne .LC40
+fldl TwoForty
+fdivl Three
+fldl Four
+fmull Four
+fmull Five
+fsubp %st(1),%st
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC40
+fldl TwoForty
+fdivl Four
+fldl Five
+fmull Three
+fmull Four
+fsubp %st(1),%st
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC40
+fldl TwoForty
+fdivl Five
+fldl Four
+fmull Three
+fmull Four
+fsubp %st(1),%st
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC40
+movl $1,-216(%ebp)
+jmp .LC41
+.LC40:
+movl $0,-216(%ebp)
+.LC41:
+pushl -216(%ebp)
+pushl $0
+call TstCond
+addl $12,%esp
+cmpl $0,ErrCnt
+jne .LC42
+pushl $.LC44
+call printf
+addl $4,%esp
+pushl $.LC45
+call printf
+addl $4,%esp
+.LC42:
+pushl $.LC46
+call printf
+addl $4,%esp
+fldl One
+fstpl W
+.LC47:
+fldl W
+fstpl -264(%ebp)
+fldl -264(%ebp)
+faddl -264(%ebp)
+fstpl W
+fldl W
+fstpl -272(%ebp)
+fldl -272(%ebp)
+faddl One
+fstpl Y
+fldl Y
+fsubl -272(%ebp)
+fstpl Z
+fldl Z
+fsubl One
+fstpl Y
+.LC48:
+fldl Y
+subl $8,%esp
+fstpl (%esp)
+call fabs
+addl $8,%esp
+fstpl -264(%ebp)
+fldl MinusOne
+faddl -264(%ebp)
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+ja .LC47
+fldl Zero
+fstpl Precision
+fldl One
+fstpl Y
+.LC50:
+fldl Y
+fstpl -280(%ebp)
+fldl W
+faddl -280(%ebp)
+fstpl Radix
+fldl -280(%ebp)
+faddl -280(%ebp)
+fstpl Y
+fldl Radix
+fsubl W
+fstpl Radix
+.LC51:
+fldl Zero
+fcompl Radix
+fstsw %ax
+sahf
+je .LC50
+fldl Two
+fcompl Radix
+fstsw %ax
+sahf
+jbe .LC53
+fldl One
+fstpl Radix
+.LC53:
+fldl Radix
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC55
+call printf
+addl $12,%esp
+fldl .LC9
+fcompl Radix
+fstsw %ax
+sahf
+je .LC56
+fldl One
+fstpl W
+.LC58:
+fldl Precision
+faddl One
+fstpl Precision
+fldl W
+fmull Radix
+fstpl W
+fldl W
+faddl One
+fstpl Y
+.LC59:
+fldl Y
+fsubl W
+fldl One
+fcompp
+fstsw %ax
+sahf
+je .LC58
+.LC56:
+fldl One
+fdivl W
+fstpl U1
+fldl U1
+fstpl -272(%ebp)
+fldl Radix
+fmull -272(%ebp)
+fstpl U2
+fldl -272(%ebp)
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC61
+call printf
+addl $12,%esp
+pushl $.LC62
+call printf
+addl $4,%esp
+fldl Radix
+fstpl E0
+fldl U1
+fstpl E1
+fldl U2
+fstpl E9
+fldl Precision
+fstpl E3
+fldl Four
+fdivl Three
+fstpl X
+fldl X
+fsubl One
+fstpl Third
+fldl Third
+fstpl -280(%ebp)
+fldl Half
+fsubl -280(%ebp)
+fstpl F6
+fldl F6
+fstpl -288(%ebp)
+fldl -288(%ebp)
+faddl -288(%ebp)
+fstpl X
+fldl X
+fsubl -280(%ebp)
+subl $8,%esp
+fstpl (%esp)
+call fabs
+addl $8,%esp
+fstpl -296(%ebp)
+fldl -296(%ebp)
+fstpl X
+fldl U2
+fcompl X
+fstsw %ax
+sahf
+jbe .LC63
+fldl U2
+fstpl X
+.LC63:
+.LC65:
+fldl X
+fstpl U2
+fldl U2
+fstpl -304(%ebp)
+fldl Half
+fmull -304(%ebp)
+fldl ThirtyTwo
+fmull -304(%ebp)
+fmull -304(%ebp)
+faddp %st(1),%st
+fstpl Y
+fldl One
+faddl Y
+fstpl Y
+fldl Y
+fsubl One
+fstpl X
+.LC66:
+fldl X
+fcompl U2
+fstsw %ax
+sahf
+jae .LC68
+fldl Zero
+fcompl X
+fstsw %ax
+sahf
+jb .LC65
+.LC68:
+fldl Two
+fdivl Three
+fstpl X
+fldl X
+fsubl Half
+fstpl F6
+fldl F6
+fstpl -320(%ebp)
+fldl -320(%ebp)
+faddl -320(%ebp)
+fstpl Third
+fldl Third
+fsubl Half
+fstpl X
+fldl X
+faddl -320(%ebp)
+subl $8,%esp
+fstpl (%esp)
+call fabs
+addl $8,%esp
+fstpl -328(%ebp)
+fldl -328(%ebp)
+fstpl X
+fldl U1
+fcompl X
+fstsw %ax
+sahf
+jbe .LC69
+fldl U1
+fstpl X
+.LC69:
+.LC71:
+fldl X
+fstpl U1
+fldl U1
+fstpl -344(%ebp)
+fldl Half
+fmull -344(%ebp)
+fldl ThirtyTwo
+fmull -344(%ebp)
+fmull -344(%ebp)
+faddp %st(1),%st
+fstpl Y
+fldl Half
+fsubl Y
+fstpl Y
+fldl Half
+faddl Y
+fstpl X
+fldl Half
+fsubl X
+fstpl Y
+fldl Half
+faddl Y
+fstpl X
+.LC72:
+fldl X
+fcompl U1
+fstsw %ax
+sahf
+jae .LC74
+fldl Zero
+fcompl X
+fstsw %ax
+sahf
+jb .LC71
+.LC74:
+fldl E1
+fcompl U1
+fstsw %ax
+sahf
+jne .LC75
+pushl $.LC77
+call printf
+addl $4,%esp
+jmp .LC76
+.LC75:
+fldl U1
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC78
+call printf
+addl $12,%esp
+.LC76:
+fldl One
+fdivl U1
+fstpl W
+fldl Half
+fsubl U1
+faddl Half
+fstpl F9
+fldl U2
+fdivl U1
+faddl .LC79
+subl $8,%esp
+fstpl (%esp)
+call floor
+addl $8,%esp
+fstpl -360(%ebp)
+fldl -360(%ebp)
+fstpl Radix
+fldl E0
+fcompl Radix
+fstsw %ax
+sahf
+jne .LC80
+pushl $.LC82
+call printf
+addl $4,%esp
+jmp .LC81
+.LC80:
+fldl Radix
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC83
+call printf
+addl $12,%esp
+.LC81:
+pushl $.LC85
+fldl Eight
+faddl Eight
+fcompl Radix
+fstsw %ax
+sahf
+jb .LC86
+movl $1,-364(%ebp)
+jmp .LC87
+.LC86:
+movl $0,-364(%ebp)
+.LC87:
+pushl -364(%ebp)
+pushl $2
+call TstCond
+addl $12,%esp
+pushl $.LC89
+fldl Two
+fcompl Radix
+fstsw %ax
+sahf
+je .LC93
+fldl .LC94
+fcompl Radix
+fstsw %ax
+sahf
+je .LC93
+fldl One
+fcompl Radix
+fstsw %ax
+sahf
+jne .LC90
+.LC93:
+movl $1,-376(%ebp)
+jmp .LC91
+.LC90:
+movl $0,-376(%ebp)
+.LC91:
+pushl -376(%ebp)
+pushl $3
+call TstCond
+addl $12,%esp
+movl $20,Milestone
+pushl $.LC96
+fldl F9
+fsubl Half
+fldl Half
+fcompp
+fstsw %ax
+sahf
+jbe .LC97
+movl $1,-388(%ebp)
+jmp .LC98
+.LC97:
+movl $0,-388(%ebp)
+.LC98:
+pushl -388(%ebp)
+pushl $0
+call TstCond
+addl $12,%esp
+fldl F9
+fstpl X
+movl $1,I
+fldl X
+fsubl Half
+fstpl Y
+fldl Y
+fsubl Half
+fstpl Z
+pushl $.LC100
+fldl One
+fcompl X
+fstsw %ax
+sahf
+jne .LC103
+fldl Zero
+fcompl Z
+fstsw %ax
+sahf
+jne .LC101
+.LC103:
+movl $1,-400(%ebp)
+jmp .LC102
+.LC101:
+movl $0,-400(%ebp)
+.LC102:
+pushl -400(%ebp)
+pushl $0
+call TstCond
+addl $12,%esp
+fldl One
+faddl U2
+fstpl X
+movl $0,I
+movl $25,Milestone
+fldl Radix
+fsubl One
+fstpl BMinusU2
+fldl BMinusU2
+fsubl U2
+faddl One
+fstpl BMinusU2
+fldl One
+fcompl Radix
+fstsw %ax
+sahf
+je .LC104
+fldl U1
+subl $8,%esp
+fstpl (%esp)
+call log
+addl $8,%esp
+fstpl -440(%ebp)
+fldl Radix
+subl $8,%esp
+fstpl (%esp)
+call log
+addl $8,%esp
+fstpl -448(%ebp)
+fldl TwoForty
+fchs
+fmull -440(%ebp)
+fdivl -448(%ebp)
+fstpl X
+fldl Half
+faddl X
+subl $8,%esp
+fstpl (%esp)
+call floor
+addl $8,%esp
+fstpl -456(%ebp)
+fldl -456(%ebp)
+fstpl Y
+fldl X
+fsubl Y
+subl $8,%esp
+fstpl (%esp)
+call fabs
+addl $8,%esp
+fstpl -464(%ebp)
+fldl -464(%ebp)
+fmull Four
+fldl One
+fcompp
+fstsw %ax
+sahf
+jbe .LC106
+fldl Y
+fstpl X
+.LC106:
+fldl X
+fdivl TwoForty
+fstpl Precision
+fldl Half
+faddl Precision
+subl $8,%esp
+fstpl (%esp)
+call floor
+addl $8,%esp
+fstpl -472(%ebp)
+fldl -472(%ebp)
+fstpl Y
+fldl Precision
+fsubl Y
+subl $8,%esp
+fstpl (%esp)
+call fabs
+addl $8,%esp
+fstpl -480(%ebp)
+fldl -480(%ebp)
+fmull TwoForty
+fldl Half
+fcompp
+fstsw %ax
+sahf
+jbe .LC108
+fldl Y
+fstpl Precision
+.LC108:
+.LC104:
+fldl Precision
+subl $8,%esp
+fstpl (%esp)
+call floor
+addl $8,%esp
+fstpl -448(%ebp)
+fldl -448(%ebp)
+fcompl Precision
+fstsw %ax
+sahf
+jne .LC112
+fldl One
+fcompl Radix
+fstsw %ax
+sahf
+jne .LC110
+.LC112:
+pushl $.LC113
+call printf
+addl $4,%esp
+pushl $.LC114
+call printf
+addl $4,%esp
+.LC110:
+fldl One
+fcompl Radix
+fstsw %ax
+sahf
+jne .LC115
+pushl $.LC117
+call printf
+addl $4,%esp
+jmp .LC116
+.LC115:
+fldl Precision
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC118
+call printf
+addl $12,%esp
+.LC116:
+pushl $.LC120
+fldl U2
+fmull Nine
+fmull Nine
+fmull TwoForty
+fldl One
+fcompp
+fstsw %ax
+sahf
+jbe .LC121
+movl $1,-452(%ebp)
+jmp .LC122
+.LC121:
+movl $0,-452(%ebp)
+.LC122:
+pushl -452(%ebp)
+pushl $1
+call TstCond
+addl $12,%esp
+movl $30,Milestone
+fldl One
+fdivl Four
+fstpl -492(%ebp)
+fldl Four
+fdivl Three
+fsubl One
+fsubl -492(%ebp)
+fmull Three
+fsubl -492(%ebp)
+subl $8,%esp
+fstpl (%esp)
+call fabs
+addl $8,%esp
+fstpl -500(%ebp)
+fldl -500(%ebp)
+fstpl X
+.LC123:
+fldl X
+fstpl Z2
+fldl Z2
+fstpl -516(%ebp)
+fldl One
+fldl Half
+fmull -516(%ebp)
+fldl ThirtyTwo
+fmull -516(%ebp)
+fmull -516(%ebp)
+faddp %st(1),%st
+faddp %st(1),%st
+fsubl One
+fstpl X
+.LC124:
+fldl X
+fcompl Z2
+fstsw %ax
+sahf
+jae .LC126
+fldl Zero
+fcompl X
+fstsw %ax
+sahf
+jb .LC123
+.LC126:
+fldl Three
+fdivl Four
+fldl Two
+fdivl Three
+fsubp %st(1),%st
+fmull Three
+fldl One
+fdivl Four
+fsubp %st(1),%st
+subl $8,%esp
+fstpl (%esp)
+call fabs
+addl $8,%esp
+fstpl -532(%ebp)
+fldl -532(%ebp)
+fstpl Z
+fldl -532(%ebp)
+fstpl Y
+fldl -532(%ebp)
+fstpl X
+.LC127:
+fldl Z
+fstpl Z1
+fldl One
+fdivl Two
+fstpl -540(%ebp)
+fldl Z1
+fstpl -548(%ebp)
+fldl -540(%ebp)
+fldl -540(%ebp)
+fldl Half
+fmull -548(%ebp)
+fldl ThirtyTwo
+fmull -548(%ebp)
+fmull -548(%ebp)
+faddp %st(1),%st
+fsubp %st(1),%st
+faddl -540(%ebp)
+fsubp %st(1),%st
+faddl -540(%ebp)
+fstpl Z
+.LC128:
+fldl Z
+fcompl Z1
+fstsw %ax
+sahf
+jae .LC130
+fldl Zero
+fcompl Z
+fstsw %ax
+sahf
+jb .LC127
+.LC130:
+.LC131:
+.LC134:
+fldl Y
+fstpl Y1
+fldl Y1
+fstpl -556(%ebp)
+fldl Half
+fldl Half
+fldl Half
+fmull -556(%ebp)
+fldl ThirtyTwo
+fmull -556(%ebp)
+fmull -556(%ebp)
+faddp %st(1),%st
+fsubp %st(1),%st
+faddl Half
+fsubp %st(1),%st
+faddl Half
+fstpl Y
+.LC135:
+fldl Y
+fcompl Y1
+fstsw %ax
+sahf
+jae .LC137
+fldl Zero
+fcompl Y
+fstsw %ax
+sahf
+jb .LC134
+.LC137:
+fldl X
+fstpl X1
+fldl X1
+fstpl -556(%ebp)
+fldl Half
+fmull -556(%ebp)
+fldl ThirtyTwo
+fmull -556(%ebp)
+fmull -556(%ebp)
+faddp %st(1),%st
+fsubl F9
+faddl F9
+fstpl X
+.LC132:
+fldl X
+fcompl X1
+fstsw %ax
+sahf
+jae .LC138
+fldl Zero
+fcompl X
+fstsw %ax
+sahf
+jb .LC131
+.LC138:
+fldl Y1
+fcompl X1
+fstsw %ax
+sahf
+jne .LC141
+fldl Z1
+fcompl X1
+fstsw %ax
+sahf
+je .LC139
+.LC141:
+pushl $.LC142
+pushl $1
+call BadCond
+addl $8,%esp
+fldl Z1
+subl $8,%esp
+fstpl (%esp)
+fldl Y1
+subl $8,%esp
+fstpl (%esp)
+fldl X1
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC143
+call printf
+addl $28,%esp
+pushl $.LC144
+call printf
+addl $4,%esp
+pushl $.LC145
+call printf
+addl $4,%esp
+pushl $.LC146
+call notify
+addl $4,%esp
+fldl U1
+fcompl X1
+fstsw %ax
+sahf
+je .LC150
+fldl U1
+fcompl Y1
+fstsw %ax
+sahf
+je .LC150
+fldl U1
+fcompl Z1
+fstsw %ax
+sahf
+jne .LC140
+.LC150:
+pushl $.LC151
+call printf
+addl $4,%esp
+jmp .LC140
+.LC139:
+fldl U1
+fcompl Z1
+fstsw %ax
+sahf
+jne .LC154
+fldl U2
+fcompl Z2
+fstsw %ax
+sahf
+je .LC152
+.LC154:
+fldl U1
+fcompl Z1
+fstsw %ax
+sahf
+jbe .LC157
+fldl U2
+fcompl Z2
+fstsw %ax
+sahf
+ja .LC155
+.LC157:
+pushl $.LC158
+pushl $0
+call BadCond
+addl $8,%esp
+pushl $.LC159
+call notify
+addl $4,%esp
+fldl Z1
+fsubl U1
+subl $8,%esp
+fstpl (%esp)
+fldl U1
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC160
+call printf
+addl $20,%esp
+fldl Z2
+fsubl U2
+subl $8,%esp
+fstpl (%esp)
+fldl U2
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC161
+call printf
+addl $20,%esp
+jmp .LC156
+.LC155:
+fldl Zero
+fcompl Z1
+fstsw %ax
+sahf
+jae .LC164
+fldl Zero
+fcompl Z2
+fstsw %ax
+sahf
+jb .LC162
+.LC164:
+fldl Radix
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC165
+call printf
+addl $12,%esp
+pushl $.LC166
+call printf
+addl $4,%esp
+fldl Z2
+subl $8,%esp
+fstpl (%esp)
+fldl Z1
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC167
+call printf
+addl $20,%esp
+pushl $.LC168
+call notify
+addl $4,%esp
+.LC162:
+fldl Z2
+fcompl Z1
+fstsw %ax
+sahf
+jne .LC171
+fldl Zero
+fcompl Z1
+fstsw %ax
+sahf
+jae .LC169
+.LC171:
+fldl Z1
+fdivl U1
+fstpl X
+fldl Z2
+fdivl U2
+fstpl Y
+fldl X
+fcompl Y
+fstsw %ax
+sahf
+jae .LC172
+fldl Y
+fstpl X
+.LC172:
+fldl X
+subl $8,%esp
+fstpl (%esp)
+call log
+addl $8,%esp
+fstpl -580(%ebp)
+fldl -580(%ebp)
+fchs
+fstpl Q
+pushl $.LC174
+call printf
+addl $4,%esp
+fldl Radix
+subl $8,%esp
+fstpl (%esp)
+call log
+addl $8,%esp
+fstpl -588(%ebp)
+fldl Q
+fdivl -588(%ebp)
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC175
+call printf
+addl $12,%esp
+fldl .LC94
+subl $8,%esp
+fstpl (%esp)
+call log
+addl $8,%esp
+fstpl -596(%ebp)
+fldl Q
+fdivl -596(%ebp)
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC176
+call printf
+addl $12,%esp
+.LC169:
+pushl $.LC151
+call printf
+addl $4,%esp
+.LC156:
+.LC152:
+.LC140:
+call Pause
+movl $35,Milestone
+fldl Two
+fcompl Radix
+fstsw %ax
+sahf
+ja .LC177
+fldl W
+fldl Radix
+fmull Radix
+fdivp %st(1),%st
+fstpl X
+fldl X
+fstpl -576(%ebp)
+fldl -576(%ebp)
+faddl One
+fstpl Y
+fldl Y
+fsubl -576(%ebp)
+fstpl Z
+fldl Z
+fstpl -584(%ebp)
+fldl -584(%ebp)
+faddl U2
+fstpl T
+fldl T
+fsubl -584(%ebp)
+fstpl X
+pushl $.LC180
+fldl U2
+fcompl X
+fstsw %ax
+sahf
+jne .LC181
+movl $1,-560(%ebp)
+jmp .LC182
+.LC181:
+movl $0,-560(%ebp)
+.LC182:
+pushl -560(%ebp)
+pushl $0
+call TstCond
+addl $12,%esp
+fldl U2
+fcompl X
+fstsw %ax
+sahf
+jne .LC183
+pushl $.LC185
+call printf
+addl $4,%esp
+.LC183:
+.LC177:
+pushl $.LC186
+call printf
+addl $4,%esp
+fldl F9
+fmull One
+fstpl Y
+fldl One
+fmull F9
+fstpl Z
+fldl F9
+fsubl Half
+fstpl X
+fldl X
+fstpl -588(%ebp)
+fldl Y
+fsubl Half
+fsubl -588(%ebp)
+fstpl Y
+fldl Z
+fsubl Half
+fsubl -588(%ebp)
+fstpl Z
+fldl One
+faddl U2
+fstpl X
+fldl X
+fstpl -604(%ebp)
+fldl -604(%ebp)
+fmull Radix
+fstpl T
+fldl Radix
+fmull -604(%ebp)
+fstpl R
+fldl T
+fsubl Radix
+fstpl X
+fldl Radix
+fmull U2
+fstpl -620(%ebp)
+fldl X
+fsubl -620(%ebp)
+fstpl X
+fldl R
+fsubl Radix
+fstpl T
+fldl T
+fsubl -620(%ebp)
+fstpl T
+fldl Radix
+fsubl One
+fstpl -628(%ebp)
+fldl X
+fmull -628(%ebp)
+fstpl X
+fldl T
+fmull -628(%ebp)
+fstpl T
+fldl Zero
+fcompl X
+fstsw %ax
+sahf
+jne .LC187
+fldl Zero
+fcompl Y
+fstsw %ax
+sahf
+jne .LC187
+fldl Zero
+fcompl Z
+fstsw %ax
+sahf
+jne .LC187
+fldl Zero
+fcompl T
+fstsw %ax
+sahf
+jne .LC187
+movl $1,GMult
+jmp .LC188
+.LC187:
+movl $0,GMult
+pushl $.LC189
+pushl $0
+pushl $1
+call TstCond
+addl $12,%esp
+.LC188:
+fldl Radix
+fmull U2
+fstpl Z
+fldl Z
+fstpl -648(%ebp)
+fldl One
+faddl -648(%ebp)
+fstpl X
+fldl X
+fstpl -656(%ebp)
+fldl -656(%ebp)
+faddl -648(%ebp)
+fldl -656(%ebp)
+fmull -656(%ebp)
+fsubp %st(1),%st
+subl $8,%esp
+fstpl (%esp)
+call fabs
+addl $8,%esp
+fstpl -664(%ebp)
+fldl -664(%ebp)
+fsubl U2
+fstpl Y
+fldl One
+fsubl U2
+fstpl X
+fldl X
+fstpl -680(%ebp)
+fldl -680(%ebp)
+fsubl U2
+fldl -680(%ebp)
+fmull -680(%ebp)
+fsubp %st(1),%st
+subl $8,%esp
+fstpl (%esp)
+call fabs
+addl $8,%esp
+fstpl -688(%ebp)
+fldl -688(%ebp)
+fsubl U1
+fstpl Z
+pushl $.LC191
+fldl Zero
+fcompl Y
+fstsw %ax
+sahf
+jb .LC192
+fldl Zero
+fcompl Z
+fstsw %ax
+sahf
+jb .LC192
+movl $1,-640(%ebp)
+jmp .LC193
+.LC192:
+movl $0,-640(%ebp)
+.LC193:
+pushl -640(%ebp)
+pushl $0
+call TstCond
+addl $12,%esp
+fldl One
+fsubl U2
+fstpl Y
+fldl One
+faddl U2
+fstpl X
+fldl One
+fdivl Y
+fstpl Z
+fldl Z
+fsubl X
+fstpl Y
+fldl One
+fdivl Three
+fstpl X
+fldl Three
+fdivl Nine
+fstpl Z
+fldl Z
+fstpl -740(%ebp)
+fldl X
+fsubl -740(%ebp)
+fstpl X
+fldl Nine
+fdivl TwentySeven
+fstpl T
+fldl -740(%ebp)
+fsubl T
+fstpl Z
+pushl $.LC195
+fldl Zero
+fcompl X
+fstsw %ax
+sahf
+jne .LC196
+fldl Zero
+fcompl Y
+fstsw %ax
+sahf
+jne .LC196
+fldl Zero
+fcompl Z
+fstsw %ax
+sahf
+jne .LC196
+movl $1,-700(%ebp)
+jmp .LC197
+.LC196:
+movl $0,-700(%ebp)
+.LC197:
+pushl -700(%ebp)
+pushl $2
+call TstCond
+addl $12,%esp
+fldl F9
+fdivl One
+fstpl Y
+fldl F9
+fsubl Half
+fstpl X
+fldl Y
+fsubl Half
+fsubl X
+fstpl Y
+fldl One
+faddl U2
+fstpl X
+fldl X
+fstpl -780(%ebp)
+fldl -780(%ebp)
+fdivl One
+fstpl T
+fldl T
+fsubl -780(%ebp)
+fstpl X
+fldl Zero
+fcompl X
+fstsw %ax
+sahf
+jne .LC198
+fldl Zero
+fcompl Y
+fstsw %ax
+sahf
+jne .LC198
+fldl Zero
+fcompl Z
+fstsw %ax
+sahf
+jne .LC198
+movl $1,GDiv
+jmp .LC199
+.LC198:
+movl $0,GDiv
+pushl $.LC200
+pushl $0
+pushl $1
+call TstCond
+addl $12,%esp
+.LC199:
+fldl One
+fldl One
+faddl U2
+fdivp %st(1),%st
+fstpl X
+fldl X
+fsubl Half
+fsubl Half
+fstpl Y
+pushl $.LC202
+fldl Zero
+fcompl Y
+fstsw %ax
+sahf
+jbe .LC203
+movl $1,-792(%ebp)
+jmp .LC204
+.LC203:
+movl $0,-792(%ebp)
+.LC204:
+pushl -792(%ebp)
+pushl $1
+call TstCond
+addl $12,%esp
+fldl One
+fsubl U2
+fstpl X
+fldl One
+fldl Radix
+fmull U2
+faddp %st(1),%st
+fstpl Y
+fldl X
+fstpl -844(%ebp)
+fldl -844(%ebp)
+fmull Radix
+fstpl Z
+fldl Y
+fstpl -852(%ebp)
+fldl -852(%ebp)
+fmull Radix
+fstpl T
+fldl Z
+fdivl Radix
+fstpl R
+fldl T
+fdivl Radix
+fstpl StickyBit
+fldl R
+fsubl -844(%ebp)
+fstpl X
+fldl StickyBit
+fsubl -852(%ebp)
+fstpl Y
+pushl $.LC206
+fldl Zero
+fcompl X
+fstsw %ax
+sahf
+jne .LC207
+fldl Zero
+fcompl Y
+fstsw %ax
+sahf
+jne .LC207
+movl $1,-812(%ebp)
+jmp .LC208
+.LC207:
+movl $0,-812(%ebp)
+.LC208:
+pushl -812(%ebp)
+pushl $0
+call TstCond
+addl $12,%esp
+fldl One
+fsubl U1
+fstpl Y
+fldl One
+fsubl F9
+fstpl X
+fldl One
+fsubl Y
+fstpl Y
+fldl Radix
+fsubl U2
+fstpl T
+fldl Radix
+fsubl BMinusU2
+fstpl Z
+fldl Radix
+fsubl T
+fstpl T
+fldl U1
+fcompl X
+fstsw %ax
+sahf
+jne .LC209
+fldl U1
+fcompl Y
+fstsw %ax
+sahf
+jne .LC209
+fldl U2
+fcompl Z
+fstsw %ax
+sahf
+jne .LC209
+fldl U2
+fcompl T
+fstsw %ax
+sahf
+jne .LC209
+movl $1,GAddSub
+jmp .LC210
+.LC209:
+movl $0,GAddSub
+pushl $.LC211
+pushl $0
+pushl $1
+call TstCond
+addl $12,%esp
+.LC210:
+fldl One
+fcompl F9
+fstsw %ax
+sahf
+je .LC212
+fldl F9
+fsubl One
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+ja .LC212
+pushl $.LC214
+pushl $1
+call BadCond
+addl $8,%esp
+pushl $.LC215
+call printf
+addl $4,%esp
+pushl $.LC216
+call printf
+addl $4,%esp
+pushl $.LC217
+call printf
+addl $4,%esp
+.LC212:
+cmpl $1,GMult
+jne .LC218
+cmpl $1,GDiv
+jne .LC218
+cmpl $1,GAddSub
+jne .LC218
+pushl $.LC220
+call printf
+addl $4,%esp
+.LC218:
+movl $40,Milestone
+call Pause
+pushl $.LC221
+call printf
+addl $4,%esp
+movl $0,RMult
+movl $0,RDiv
+movl $0,RAddSub
+fldl Radix
+fdivl Two
+fstpl RadixD2
+fldl Two
+fstpl A1
+movl $0,Done
+.LC222:
+fldl Radix
+fstpl AInvrse
+.LC225:
+fldl AInvrse
+fstpl -924(%ebp)
+fldl -924(%ebp)
+fstpl X
+fldl -924(%ebp)
+fdivl A1
+fstpl AInvrse
+.LC226:
+fldl AInvrse
+subl $8,%esp
+fstpl (%esp)
+call floor
+addl $8,%esp
+fstpl -924(%ebp)
+fldl AInvrse
+fcompl -924(%ebp)
+fstsw %ax
+sahf
+je .LC225
+fldl One
+fcompl X
+fstsw %ax
+sahf
+je .LC231
+fldl Three
+fcompl A1
+fstsw %ax
+sahf
+jae .LC229
+.LC231:
+movl $1,-928(%ebp)
+jmp .LC230
+.LC229:
+movl $0,-928(%ebp)
+.LC230:
+movl -928(%ebp),%edi
+movl %edi,Done
+cmpl $0,Done
+jne .LC232
+fldl Nine
+faddl One
+fstpl A1
+.LC232:
+.LC223:
+cmpl $0,Done
+je .LC222
+fldl One
+fcompl X
+fstsw %ax
+sahf
+jne .LC234
+fldl Radix
+fstpl A1
+.LC234:
+fldl One
+fdivl A1
+fstpl AInvrse
+fldl A1
+fstpl X
+fldl AInvrse
+fstpl Y
+movl $0,Done
+.LC236:
+fldl X
+fmull Y
+fsubl Half
+fstpl Z
+pushl $.LC240
+fldl Half
+fcompl Z
+fstsw %ax
+sahf
+jne .LC241
+movl $1,-928(%ebp)
+jmp .LC242
+.LC241:
+movl $0,-928(%ebp)
+.LC242:
+pushl -928(%ebp)
+pushl $0
+call TstCond
+addl $12,%esp
+fldl Radix
+fcompl X
+fstsw %ax
+sahf
+jne .LC244
+movl $1,-940(%ebp)
+jmp .LC245
+.LC244:
+movl $0,-940(%ebp)
+.LC245:
+movl -940(%ebp),%edi
+movl %edi,Done
+fldl Radix
+fstpl X
+fldl One
+fdivl X
+fstpl Y
+.LC237:
+cmpl $0,Done
+je .LC236
+fldl One
+faddl U2
+fstpl Y2
+fldl One
+fsubl U2
+fstpl Y1
+fldl OneAndHalf
+fsubl U2
+fstpl X
+fldl OneAndHalf
+faddl U2
+fstpl Y
+fldl X
+fstpl -956(%ebp)
+fldl Y2
+fstpl -964(%ebp)
+fldl -956(%ebp)
+fsubl U2
+fmull -964(%ebp)
+fstpl Z
+fldl Y
+fstpl -972(%ebp)
+fldl Y1
+fstpl -980(%ebp)
+fldl -972(%ebp)
+fmull -980(%ebp)
+fstpl T
+fldl Z
+fsubl -956(%ebp)
+fstpl Z
+fldl T
+fsubl -956(%ebp)
+fstpl T
+fldl -956(%ebp)
+fmull -964(%ebp)
+fstpl X
+fldl -972(%ebp)
+faddl U2
+fmull -980(%ebp)
+fstpl Y
+fldl X
+fsubl OneAndHalf
+fstpl X
+fldl Y
+fsubl OneAndHalf
+fstpl Y
+fldl Zero
+fcompl X
+fstsw %ax
+sahf
+jne .LC246
+fldl Zero
+fcompl Y
+fstsw %ax
+sahf
+jne .LC246
+fldl Zero
+fcompl Z
+fstsw %ax
+sahf
+jne .LC246
+fldl Zero
+fcompl T
+fstsw %ax
+sahf
+jb .LC246
+fldl OneAndHalf
+faddl U2
+fstpl -1012(%ebp)
+fldl -1012(%ebp)
+fmull Y2
+fstpl X
+fldl OneAndHalf
+fsubl U2
+fstpl -1028(%ebp)
+fldl -1028(%ebp)
+fsubl U2
+fstpl Y
+fldl -1012(%ebp)
+faddl U2
+fstpl Z
+fldl Y1
+fstpl -1036(%ebp)
+fldl -1028(%ebp)
+fmull -1036(%ebp)
+fstpl T
+fldl Z
+fstpl -1044(%ebp)
+fldl -1044(%ebp)
+faddl U2
+fstpl -1052(%ebp)
+fldl X
+fsubl -1052(%ebp)
+fstpl X
+fldl Y
+fstpl -1060(%ebp)
+fldl -1060(%ebp)
+fmull -1036(%ebp)
+fstpl StickyBit
+fldl -1044(%ebp)
+fmull Y2
+fstpl S
+fldl T
+fsubl -1060(%ebp)
+fstpl T
+fldl U2
+fsubl -1060(%ebp)
+faddl StickyBit
+fstpl Y
+fldl S
+fldl -1052(%ebp)
+faddl U2
+fsubp %st(1),%st
+fstpl Z
+fldl Y2
+faddl U2
+fmull -1036(%ebp)
+fstpl StickyBit
+fldl Y2
+fmull -1036(%ebp)
+fstpl Y1
+fldl StickyBit
+fsubl Y2
+fstpl StickyBit
+fldl Y1
+fsubl Half
+fstpl Y1
+fldl Zero
+fcompl X
+fstsw %ax
+sahf
+jne .LC248
+fldl Zero
+fcompl Y
+fstsw %ax
+sahf
+jne .LC248
+fldl Zero
+fcompl Z
+fstsw %ax
+sahf
+jne .LC248
+fldl Zero
+fcompl T
+fstsw %ax
+sahf
+jne .LC248
+fldl Zero
+fcompl StickyBit
+fstsw %ax
+sahf
+jne .LC248
+fldl Half
+fcompl Y1
+fstsw %ax
+sahf
+jne .LC248
+movl $1,RMult
+pushl $.LC250
+call printf
+addl $4,%esp
+jmp .LC249
+.LC248:
+fldl X
+faddl U2
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC251
+fldl Zero
+fcompl Y
+fstsw %ax
+sahf
+jbe .LC251
+fldl Z
+faddl U2
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC251
+fldl Zero
+fcompl T
+fstsw %ax
+sahf
+jbe .LC251
+fldl StickyBit
+faddl U2
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC251
+fldl Half
+fcompl Y1
+fstsw %ax
+sahf
+jbe .LC251
+movl $2,RMult
+pushl $.LC253
+call printf
+addl $4,%esp
+jmp .LC252
+.LC251:
+pushl $.LC254
+call printf
+addl $4,%esp
+.LC252:
+.LC249:
+cmpl $1,RMult
+jne .LC247
+cmpl $0,GMult
+jne .LC247
+pushl $.LC257
+call notify
+addl $4,%esp
+jmp .LC247
+.LC246:
+pushl $.LC254
+call printf
+addl $4,%esp
+.LC247:
+movl $45,Milestone
+fldl One
+faddl U2
+fstpl Y2
+fldl One
+fsubl U2
+fstpl Y1
+fldl OneAndHalf
+faddl U2
+fstpl -1020(%ebp)
+fldl -1020(%ebp)
+faddl U2
+fstpl Z
+fldl Z
+fstpl -1028(%ebp)
+fldl Y2
+fstpl -1036(%ebp)
+fldl -1028(%ebp)
+fdivl -1036(%ebp)
+fstpl X
+fldl OneAndHalf
+fsubl U2
+fsubl U2
+fstpl T
+fldl T
+fstpl -1044(%ebp)
+fldl Y1
+fstpl -1052(%ebp)
+fldl -1044(%ebp)
+fsubl U2
+fdivl -1052(%ebp)
+fstpl Y
+fldl -1028(%ebp)
+faddl U2
+fdivl -1036(%ebp)
+fstpl Z
+fldl X
+fsubl OneAndHalf
+fstpl X
+fldl Y
+fsubl -1044(%ebp)
+fstpl Y
+fldl -1044(%ebp)
+fdivl -1052(%ebp)
+fstpl T
+fldl Z
+fsubl -1020(%ebp)
+fstpl Z
+fldl U2
+fsubl OneAndHalf
+faddl T
+fstpl T
+fldl Zero
+fcompl X
+fstsw %ax
+sahf
+jb .LC258
+fldl Zero
+fcompl Y
+fstsw %ax
+sahf
+jb .LC258
+fldl Zero
+fcompl Z
+fstsw %ax
+sahf
+jb .LC258
+fldl Zero
+fcompl T
+fstsw %ax
+sahf
+jb .LC258
+fldl Y2
+fstpl -1076(%ebp)
+fldl OneAndHalf
+fdivl -1076(%ebp)
+fstpl X
+fldl OneAndHalf
+fsubl U2
+fstpl Y
+fldl OneAndHalf
+faddl U2
+fstpl Z
+fldl Y
+fstpl -1092(%ebp)
+fldl X
+fsubl -1092(%ebp)
+fstpl X
+fldl Y1
+fstpl -1100(%ebp)
+fldl OneAndHalf
+fdivl -1100(%ebp)
+fstpl T
+fldl -1092(%ebp)
+fdivl -1100(%ebp)
+fstpl Y
+fldl Z
+fstpl -1108(%ebp)
+fldl T
+fldl -1108(%ebp)
+faddl U2
+fsubp %st(1),%st
+fstpl T
+fldl Y
+fsubl -1108(%ebp)
+fstpl Y
+fldl -1108(%ebp)
+fdivl -1076(%ebp)
+fstpl Z
+fldl -1076(%ebp)
+faddl U2
+fdivl -1076(%ebp)
+fstpl Y1
+fldl Z
+fsubl OneAndHalf
+fstpl Z
+fldl Y1
+fsubl -1076(%ebp)
+fstpl Y2
+fldl F9
+fsubl U1
+fdivl F9
+fstpl Y1
+fldl Zero
+fcompl X
+fstsw %ax
+sahf
+jne .LC260
+fldl Zero
+fcompl Y
+fstsw %ax
+sahf
+jne .LC260
+fldl Zero
+fcompl Z
+fstsw %ax
+sahf
+jne .LC260
+fldl Zero
+fcompl T
+fstsw %ax
+sahf
+jne .LC260
+fldl Zero
+fcompl Y2
+fstsw %ax
+sahf
+jne .LC260
+fldl Zero
+fcompl Y2
+fstsw %ax
+sahf
+jne .LC260
+fldl Y1
+fsubl Half
+fldl F9
+fsubl Half
+fcompp
+fstsw %ax
+sahf
+jne .LC260
+movl $1,RDiv
+pushl $.LC262
+call printf
+addl $4,%esp
+cmpl $0,GDiv
+jne .LC261
+pushl $.LC265
+call notify
+addl $4,%esp
+jmp .LC261
+.LC260:
+fldl Zero
+fcompl X
+fstsw %ax
+sahf
+jbe .LC266
+fldl Zero
+fcompl Y
+fstsw %ax
+sahf
+jbe .LC266
+fldl Zero
+fcompl Z
+fstsw %ax
+sahf
+jbe .LC266
+fldl Zero
+fcompl T
+fstsw %ax
+sahf
+jbe .LC266
+fldl Zero
+fcompl Y2
+fstsw %ax
+sahf
+jbe .LC266
+fldl Y1
+fsubl Half
+fldl F9
+fsubl Half
+fcompp
+fstsw %ax
+sahf
+jbe .LC266
+movl $2,RDiv
+pushl $.LC268
+call printf
+addl $4,%esp
+.LC266:
+.LC261:
+.LC258:
+cmpl $0,RDiv
+jne .LC269
+pushl $.LC271
+call printf
+addl $4,%esp
+.LC269:
+fldl One
+fdivl Radix
+fstpl BInvrse
+pushl $.LC273
+fldl BInvrse
+fmull Radix
+fsubl Half
+fldl Half
+fcompp
+fstsw %ax
+sahf
+jne .LC274
+movl $1,-1064(%ebp)
+jmp .LC275
+.LC274:
+movl $0,-1064(%ebp)
+.LC275:
+pushl -1064(%ebp)
+pushl $0
+call TstCond
+addl $12,%esp
+movl $50,Milestone
+pushl $.LC277
+fldl F9
+faddl U1
+fsubl Half
+fldl Half
+fcompp
+fstsw %ax
+sahf
+jne .LC278
+fldl BMinusU2
+faddl U2
+fsubl One
+fldl Radix
+fsubl One
+fcompp
+fstsw %ax
+sahf
+jne .LC278
+movl $1,-1084(%ebp)
+jmp .LC279
+.LC278:
+movl $0,-1084(%ebp)
+.LC279:
+pushl -1084(%ebp)
+pushl $0
+call TstCond
+addl $12,%esp
+fldl One
+fldl U1
+fmull U1
+fsubp %st(1),%st
+fstpl X
+fldl One
+fldl U2
+fldl One
+fsubl U2
+fmulp %st(1),%st
+faddp %st(1),%st
+fstpl Y
+fldl F9
+fsubl Half
+fstpl Z
+fldl X
+fsubl Half
+fsubl Z
+fstpl X
+fldl Y
+fsubl One
+fstpl Y
+fldl Zero
+fcompl X
+fstsw %ax
+sahf
+jne .LC280
+fldl Zero
+fcompl Y
+fstsw %ax
+sahf
+jne .LC280
+movl $2,RAddSub
+pushl $.LC282
+call printf
+addl $4,%esp
+.LC280:
+cmpl $1,GAddSub
+jne .LC283
+fldl Half
+faddl U2
+fmull U2
+fstpl X
+fldl Half
+fsubl U2
+fmull U2
+fstpl Y
+fldl One
+faddl X
+fstpl X
+fldl One
+faddl Y
+fstpl Y
+fldl One
+faddl U2
+fsubl X
+fstpl X
+fldl One
+fsubl Y
+fstpl Y
+fldl Zero
+fcompl X
+fstsw %ax
+sahf
+jne .LC285
+fldl Zero
+fcompl Y
+fstsw %ax
+sahf
+jne .LC285
+fldl Half
+faddl U2
+fmull U1
+fstpl X
+fldl Half
+fsubl U2
+fmull U1
+fstpl Y
+fldl One
+fsubl X
+fstpl X
+fldl One
+fsubl Y
+fstpl Y
+fldl F9
+fsubl X
+fstpl X
+fldl One
+fsubl Y
+fstpl Y
+fldl Zero
+fcompl X
+fstsw %ax
+sahf
+jne .LC287
+fldl Zero
+fcompl Y
+fstsw %ax
+sahf
+jne .LC287
+movl $1,RAddSub
+pushl $.LC289
+call printf
+addl $4,%esp
+cmpl $0,GAddSub
+jne .LC284
+pushl $.LC292
+call notify
+addl $4,%esp
+jmp .LC284
+.LC287:
+pushl $.LC293
+call printf
+addl $4,%esp
+jmp .LC284
+.LC285:
+pushl $.LC293
+call printf
+addl $4,%esp
+jmp .LC284
+.LC283:
+pushl $.LC293
+call printf
+addl $4,%esp
+.LC284:
+fldl One
+fstpl S
+fldl One
+fldl Half
+fldl One
+faddl Half
+fmulp %st(1),%st
+faddp %st(1),%st
+fstpl X
+fldl One
+faddl U2
+fmull Half
+fstpl Y
+fldl X
+fstpl -1164(%ebp)
+fldl Y
+fstpl -1172(%ebp)
+fldl -1164(%ebp)
+fsubl -1172(%ebp)
+fstpl Z
+fldl -1172(%ebp)
+fsubl -1164(%ebp)
+fstpl T
+fldl Z
+faddl T
+fstpl StickyBit
+fldl Zero
+fcompl StickyBit
+fstsw %ax
+sahf
+je .LC294
+fldl Zero
+fstpl S
+pushl $.LC296
+pushl $3
+call BadCond
+addl $8,%esp
+.LC294:
+fldl Zero
+fstpl StickyBit
+cmpl $1,GMult
+jne .LC297
+cmpl $1,GDiv
+jne .LC297
+cmpl $1,GAddSub
+jne .LC297
+cmpl $1,RMult
+jne .LC297
+cmpl $1,RDiv
+jne .LC297
+cmpl $1,RAddSub
+jne .LC297
+fldl RadixD2
+subl $8,%esp
+fstpl (%esp)
+call floor
+addl $8,%esp
+fstpl -1180(%ebp)
+fldl RadixD2
+fcompl -1180(%ebp)
+fstsw %ax
+sahf
+jne .LC297
+pushl $.LC299
+call printf
+addl $4,%esp
+fldl Half
+faddl U1
+fmull U2
+fstpl X
+fldl Half
+fmull U2
+fstpl Y
+fldl One
+faddl Y
+fstpl Z
+fldl One
+faddl X
+fstpl T
+fldl Z
+fsubl One
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jb .LC300
+fldl T
+fsubl One
+fldl U2
+fcompp
+fstsw %ax
+sahf
+ja .LC300
+fldl T
+faddl Y
+fstpl Z
+fldl Z
+fsubl X
+fstpl Y
+fldl Z
+fsubl T
+fldl U2
+fcompp
+fstsw %ax
+sahf
+ja .LC302
+fldl Y
+fsubl T
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC302
+fldl Half
+faddl U1
+fmull U1
+fstpl X
+fldl Half
+fmull U1
+fstpl Y
+fldl One
+fsubl Y
+fstpl Z
+fldl One
+fsubl X
+fstpl T
+fldl Z
+fsubl One
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC304
+fldl T
+fsubl F9
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC304
+fldl Half
+fsubl U1
+fmull U1
+fstpl Z
+fldl F9
+fsubl Z
+fstpl T
+fldl F9
+fsubl Y
+fstpl Q
+fldl T
+fsubl F9
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC306
+fldl F9
+fsubl U1
+fsubl Q
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC306
+fldl One
+faddl U2
+fmull OneAndHalf
+fstpl Z
+fldl OneAndHalf
+faddl U2
+fsubl Z
+faddl U2
+fstpl T
+fldl One
+fldl Half
+fdivl Radix
+faddp %st(1),%st
+fstpl X
+fldl One
+fldl Radix
+fmull U2
+faddp %st(1),%st
+fstpl Y
+fldl X
+fmull Y
+fstpl Z
+fldl Zero
+fcompl T
+fstsw %ax
+sahf
+jne .LC308
+fldl X
+fldl Radix
+fmull U2
+faddp %st(1),%st
+fsubl Z
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC308
+fldl Two
+fcompl Radix
+fstsw %ax
+sahf
+je .LC310
+fldl Two
+faddl U2
+fstpl X
+fldl X
+fdivl Two
+fstpl Y
+fldl Y
+fsubl One
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC311
+fldl S
+fstpl StickyBit
+jmp .LC311
+.LC310:
+fldl S
+fstpl StickyBit
+.LC311:
+.LC308:
+.LC306:
+.LC304:
+.LC302:
+.LC300:
+.LC297:
+fldl One
+fcompl StickyBit
+fstsw %ax
+sahf
+jne .LC314
+pushl $.LC316
+call printf
+addl $4,%esp
+jmp .LC315
+.LC314:
+pushl $.LC317
+call printf
+addl $4,%esp
+.LC315:
+pushl $.LC319
+cmpl $0,GMult
+je .LC320
+cmpl $0,GDiv
+je .LC320
+cmpl $0,GAddSub
+je .LC320
+cmpl $0,RMult
+je .LC320
+cmpl $0,RDiv
+je .LC320
+cmpl $0,RAddSub
+je .LC320
+movl $1,-1184(%ebp)
+jmp .LC321
+.LC320:
+movl $0,-1184(%ebp)
+.LC321:
+pushl -1184(%ebp)
+pushl $3
+call TstCond
+addl $12,%esp
+movl $60,Milestone
+pushl $.LC45
+call printf
+addl $4,%esp
+pushl $.LC322
+call printf
+addl $4,%esp
+pushl NoTrials
+pushl $.LC323
+call printf
+addl $8,%esp
+fldl .LC324
+subl $8,%esp
+fstpl (%esp)
+call sqrt
+addl $8,%esp
+fstpl -1192(%ebp)
+fldl -1192(%ebp)
+fstpl Random9
+fldl Third
+fstpl Random1
+movl $1,I
+.LC325:
+call Random
+fstpl -1200(%ebp)
+fldl -1200(%ebp)
+fstpl X
+call Random
+fstpl -1208(%ebp)
+fldl -1208(%ebp)
+fstpl Y
+fldl Y
+fmull X
+fstpl Z9
+fldl X
+fmull Y
+fstpl Z
+fldl Z
+fsubl Z9
+fstpl Z9
+incl I
+.LC326:
+movl NoTrials,%edi
+cmpl %edi,I
+jg .LC328
+fldl Zero
+fcompl Z9
+fstsw %ax
+sahf
+je .LC325
+.LC328:
+movl NoTrials,%edi
+cmpl %edi,I
+jne .LC329
+fldl One
+fldl Half
+fdivl Three
+faddp %st(1),%st
+fstpl -1208(%ebp)
+fldl -1208(%ebp)
+fstpl Random1
+fldl U2
+faddl U1
+faddl One
+fstpl -1216(%ebp)
+fldl -1216(%ebp)
+fstpl Random2
+fldl Random1
+fstpl -1224(%ebp)
+fldl Random2
+fstpl -1232(%ebp)
+fldl -1224(%ebp)
+fmull -1232(%ebp)
+fstpl Z
+fldl -1232(%ebp)
+fmull -1224(%ebp)
+fstpl Y
+fldl -1208(%ebp)
+fmull -1216(%ebp)
+fstpl -1240(%ebp)
+fldl -1240(%ebp)
+fsubl -1240(%ebp)
+fstpl Z9
+.LC329:
+movl NoTrials,%edi
+cmpl %edi,I
+je .LC331
+fldl Zero
+fcompl Z9
+fstsw %ax
+sahf
+je .LC331
+pushl $.LC333
+pushl $2
+call BadCond
+addl $8,%esp
+jmp .LC332
+.LC331:
+pushl NoTrials
+pushl $.LC334
+call printf
+addl $8,%esp
+.LC332:
+movl $70,Milestone
+pushl $.LC335
+call printf
+addl $4,%esp
+fldl Zero
+subl $8,%esp
+fstpl (%esp)
+call sqrt
+addl $8,%esp
+fstpl -1212(%ebp)
+fldl -1212(%ebp)
+fcompl Zero
+fstsw %ax
+sahf
+jne .LC338
+fldl Zero
+fchs
+fstpl -1220(%ebp)
+fldl -1220(%ebp)
+subl $8,%esp
+fstpl (%esp)
+call sqrt
+addl $8,%esp
+fstpl -1228(%ebp)
+fldl -1228(%ebp)
+fcompl -1220(%ebp)
+fstsw %ax
+sahf
+jne .LC338
+fldl One
+subl $8,%esp
+fstpl (%esp)
+call sqrt
+addl $8,%esp
+fstpl -1244(%ebp)
+fldl -1244(%ebp)
+fcompl One
+fstsw %ax
+sahf
+jne .LC338
+movl $1,-1196(%ebp)
+jmp .LC339
+.LC338:
+movl $0,-1196(%ebp)
+.LC339:
+pushl $.LC337
+pushl -1196(%ebp)
+pushl $0
+call TstCond
+addl $12,%esp
+fldl Zero
+fstpl MinSqEr
+fldl Zero
+fstpl MaxSqEr
+fldl Zero
+fstpl J
+fldl Radix
+fstpl X
+fldl U2
+fstpl OneUlp
+pushl $1
+call SqXMinX
+addl $4,%esp
+fldl BInvrse
+fstpl X
+fldl BInvrse
+fmull U1
+fstpl OneUlp
+pushl $1
+call SqXMinX
+addl $4,%esp
+fldl U1
+fstpl X
+fldl U1
+fmull U1
+fstpl OneUlp
+pushl $1
+call SqXMinX
+addl $4,%esp
+fldl Zero
+fcompl J
+fstsw %ax
+sahf
+je .LC340
+call Pause
+.LC340:
+pushl NoTrials
+pushl $.LC342
+call printf
+addl $8,%esp
+fldl Zero
+fstpl J
+fldl Two
+fstpl X
+fldl Radix
+fstpl Y
+fldl One
+fcompl Radix
+fstsw %ax
+sahf
+je .LC343
+.LC345:
+fldl Y
+fstpl -1284(%ebp)
+fldl -1284(%ebp)
+fstpl X
+fldl Radix
+fmull -1284(%ebp)
+fstpl Y
+.LC346:
+fldl Y
+fsubl X
+fildl NoTrials
+fcompp
+fstsw %ax
+sahf
+ja .LC345
+.LC343:
+fldl X
+fmull U2
+fstpl OneUlp
+movl $1,I
+jmp .LC349
+.LC348:
+fldl X
+faddl One
+fstpl X
+pushl $2
+call SqXMinX
+addl $4,%esp
+fldl Zero
+fcompl J
+fstsw %ax
+sahf
+jae .LC351
+jmp .LC350
+.LC351:
+incl I
+.LC349:
+movl NoTrials,%edi
+cmpl %edi,I
+jle .LC348
+.LC350:
+pushl $.LC353
+call printf
+addl $4,%esp
+movl $-1,I
+fldl BMinusU2
+fstpl X
+fldl Radix
+fstpl Y
+fldl Radix
+fldl Radix
+fmull U2
+faddp %st(1),%st
+fstpl Z
+movl $0,NotMonot
+movl $0,Monot
+jmp .LC355
+.LC354:
+incl I
+fldl X
+subl $8,%esp
+fstpl (%esp)
+call sqrt
+addl $8,%esp
+fstpl -1292(%ebp)
+fldl -1292(%ebp)
+fstpl X
+fldl Y
+subl $8,%esp
+fstpl (%esp)
+call sqrt
+addl $8,%esp
+fstpl -1300(%ebp)
+fldl -1300(%ebp)
+fstpl Q
+fldl Z
+subl $8,%esp
+fstpl (%esp)
+call sqrt
+addl $8,%esp
+fstpl -1308(%ebp)
+fldl -1308(%ebp)
+fstpl Z
+fldl Q
+fcompl X
+fstsw %ax
+sahf
+jb .LC359
+fldl Z
+fcompl Q
+fstsw %ax
+sahf
+jae .LC357
+.LC359:
+movl $1,NotMonot
+jmp .LC358
+.LC357:
+fldl Q
+faddl Half
+subl $8,%esp
+fstpl (%esp)
+call floor
+addl $8,%esp
+fstpl -1324(%ebp)
+fldl -1324(%ebp)
+fstpl Q
+cmpl $0,I
+jg .LC362
+fldl Q
+fmull Q
+fcompl Radix
+fstsw %ax
+sahf
+jne .LC360
+.LC362:
+movl $1,Monot
+jmp .LC361
+.LC360:
+cmpl $0,I
+jle .LC363
+cmpl $1,I
+jle .LC365
+movl $1,Monot
+jmp .LC364
+.LC365:
+fldl Y
+fmull BInvrse
+fstpl Y
+fldl Y
+fstpl -1340(%ebp)
+fldl -1340(%ebp)
+fsubl U1
+fstpl X
+fldl -1340(%ebp)
+faddl U1
+fstpl Z
+jmp .LC364
+.LC363:
+fldl Q
+fstpl Y
+fldl Y
+fstpl -1340(%ebp)
+fldl -1340(%ebp)
+fsubl U2
+fstpl X
+fldl -1340(%ebp)
+faddl U2
+fstpl Z
+.LC364:
+.LC361:
+.LC358:
+.LC355:
+cmpl $0,NotMonot
+jne .LC367
+cmpl $0,Monot
+je .LC354
+.LC367:
+cmpl $0,Monot
+je .LC368
+pushl $.LC370
+call printf
+addl $4,%esp
+jmp .LC369
+.LC368:
+pushl $.LC158
+pushl $2
+call BadCond
+addl $8,%esp
+fldl Y
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC371
+call printf
+addl $12,%esp
+.LC369:
+movl $80,Milestone
+fldl MinSqEr
+faddl Half
+fstpl MinSqEr
+fldl MaxSqEr
+fsubl Half
+fstpl MaxSqEr
+fldl One
+faddl U2
+subl $8,%esp
+fstpl (%esp)
+call sqrt
+addl $8,%esp
+fstpl -1300(%ebp)
+fldl -1300(%ebp)
+fsubl One
+fdivl U2
+fstpl Y
+fldl Y
+fsubl One
+fldl U2
+fdivl Eight
+faddp %st(1),%st
+fstpl SqEr
+fldl MaxSqEr
+fcompl SqEr
+fstsw %ax
+sahf
+jae .LC372
+fldl SqEr
+fstpl MaxSqEr
+.LC372:
+fldl Y
+fldl U2
+fdivl Eight
+faddp %st(1),%st
+fstpl SqEr
+fldl MinSqEr
+fcompl SqEr
+fstsw %ax
+sahf
+jbe .LC374
+fldl SqEr
+fstpl MinSqEr
+.LC374:
+fldl F9
+subl $8,%esp
+fstpl (%esp)
+call sqrt
+addl $8,%esp
+fstpl -1324(%ebp)
+fldl -1324(%ebp)
+fsubl U2
+fldl One
+fsubl U2
+fsubp %st(1),%st
+fdivl U1
+fstpl Y
+fldl Y
+fldl U1
+fdivl Eight
+faddp %st(1),%st
+fstpl SqEr
+fldl MaxSqEr
+fcompl SqEr
+fstsw %ax
+sahf
+jae .LC376
+fldl SqEr
+fstpl MaxSqEr
+.LC376:
+fldl Y
+faddl One
+fldl U1
+fdivl Eight
+faddp %st(1),%st
+fstpl SqEr
+fldl MinSqEr
+fcompl SqEr
+fstsw %ax
+sahf
+jbe .LC378
+fldl SqEr
+fstpl MinSqEr
+.LC378:
+fldl U2
+fstpl OneUlp
+fldl OneUlp
+fstpl X
+movl $1,Indx
+.LC380:
+fldl X
+faddl U1
+faddl X
+faddl F9
+subl $8,%esp
+fstpl (%esp)
+call sqrt
+addl $8,%esp
+fstpl -1356(%ebp)
+fldl -1356(%ebp)
+fstpl Y
+fldl Y
+fsubl U2
+fldl One
+fsubl U2
+faddl X
+fsubp %st(1),%st
+fdivl OneUlp
+fstpl Y
+fldl U1
+fsubl X
+faddl F9
+fmull Half
+fmull X
+fmull X
+fdivl OneUlp
+fstpl Z
+fldl Y
+faddl Half
+faddl Z
+fstpl SqEr
+fldl MinSqEr
+fcompl SqEr
+fstsw %ax
+sahf
+jbe .LC384
+fldl SqEr
+fstpl MinSqEr
+.LC384:
+fldl Y
+fsubl Half
+faddl Z
+fstpl SqEr
+fldl MaxSqEr
+fcompl SqEr
+fstsw %ax
+sahf
+jae .LC386
+fldl SqEr
+fstpl MaxSqEr
+.LC386:
+movl Indx,%edi
+cmpl $1,%edi
+je .LC390
+cmpl $3,%edi
+jne .LC388
+.LC390:
+fldl X
+subl $8,%esp
+fstpl (%esp)
+call Sign
+addl $8,%esp
+fstpl -1396(%ebp)
+fldl OneUlp
+subl $8,%esp
+fstpl (%esp)
+call sqrt
+addl $8,%esp
+fstpl -1404(%ebp)
+fldl Eight
+fldl Nine
+fmull -1404(%ebp)
+fdivp %st(1),%st
+subl $8,%esp
+fstpl (%esp)
+call floor
+addl $8,%esp
+fstpl -1412(%ebp)
+fldl OneUlp
+fmull -1396(%ebp)
+fmull -1412(%ebp)
+fstpl X
+jmp .LC389
+.LC388:
+fldl U1
+fstpl OneUlp
+fldl OneUlp
+fchs
+fstpl X
+.LC389:
+.LC381:
+incl Indx
+cmpl $3,Indx
+jle .LC380
+movl $85,Milestone
+movl $0,SqRWrng
+movl $0,Anomaly
+movl $0,RSqrt
+fldl One
+fcompl Radix
+fstsw %ax
+sahf
+je .LC391
+pushl $.LC393
+call printf
+addl $4,%esp
+fldl Precision
+subl $8,%esp
+fstpl (%esp)
+call floor
+addl $8,%esp
+fstpl -1356(%ebp)
+fldl One
+faddl Precision
+fsubl -1356(%ebp)
+subl $8,%esp
+fstpl (%esp)
+fldl Radix
+subl $8,%esp
+fstpl (%esp)
+call pow
+addl $16,%esp
+fstpl -1364(%ebp)
+fldl Half
+faddl -1364(%ebp)
+subl $8,%esp
+fstpl (%esp)
+call floor
+addl $8,%esp
+fstpl -1372(%ebp)
+fldl -1372(%ebp)
+fstpl D
+fldl D
+fdivl Radix
+fstpl X
+fldl D
+fdivl A1
+fstpl Y
+fldl X
+subl $8,%esp
+fstpl (%esp)
+call floor
+addl $8,%esp
+fstpl -1396(%ebp)
+fldl -1396(%ebp)
+fcompl X
+fstsw %ax
+sahf
+jne .LC396
+fldl Y
+subl $8,%esp
+fstpl (%esp)
+call floor
+addl $8,%esp
+fstpl -1412(%ebp)
+fldl -1412(%ebp)
+fcompl Y
+fstsw %ax
+sahf
+je .LC394
+.LC396:
+movl $1,Anomaly
+jmp .LC395
+.LC394:
+fldl Zero
+fstpl X
+fldl X
+fstpl Z2
+fldl One
+fstpl Y
+fldl Y
+fstpl Y2
+fldl Radix
+fsubl One
+fstpl Z1
+fldl Four
+fmull D
+fstpl FourD
+.LC397:
+fldl Z2
+fcompl Y2
+fstsw %ax
+sahf
+jae .LC400
+fldl Radix
+fstpl Q
+fldl Y
+fstpl Y1
+.LC402:
+fldl Half
+fldl Q
+fdivl Y1
+fsubp %st(1),%st
+subl $8,%esp
+fstpl (%esp)
+call floor
+addl $8,%esp
+fstpl -1436(%ebp)
+fldl Q
+fldl -1436(%ebp)
+fmull Y1
+faddp %st(1),%st
+subl $8,%esp
+fstpl (%esp)
+call fabs
+addl $8,%esp
+fstpl -1444(%ebp)
+fldl -1444(%ebp)
+fstpl X1
+fldl Y1
+fstpl Q
+fldl X1
+fstpl Y1
+.LC403:
+fldl Zero
+fcompl X1
+fstsw %ax
+sahf
+jb .LC402
+fldl One
+fcompl Q
+fstsw %ax
+sahf
+jb .LC405
+fldl Y2
+fstpl Z2
+fldl Y
+fstpl Z
+.LC405:
+.LC400:
+fldl Y
+faddl Two
+fstpl Y
+fldl X
+faddl Eight
+fstpl X
+fldl Y2
+faddl X
+fstpl Y2
+fldl FourD
+fcompl Y2
+fstsw %ax
+sahf
+ja .LC407
+fldl Y2
+fsubl FourD
+fstpl Y2
+.LC407:
+.LC398:
+fldl D
+fcompl Y
+fstsw %ax
+sahf
+ja .LC397
+fldl FourD
+fsubl Z2
+fstpl X8
+fldl X8
+fstpl -1436(%ebp)
+fldl -1436(%ebp)
+fldl Z
+fmull Z
+faddp %st(1),%st
+fdivl FourD
+fstpl Q
+fldl -1436(%ebp)
+fdivl Eight
+fstpl X8
+fldl Q
+fstpl -1452(%ebp)
+fldl -1452(%ebp)
+subl $8,%esp
+fstpl (%esp)
+call floor
+addl $8,%esp
+fstpl -1460(%ebp)
+fldl -1460(%ebp)
+fcompl -1452(%ebp)
+fstsw %ax
+sahf
+je .LC409
+movl $1,Anomaly
+jmp .LC410
+.LC409:
+movl $0,Break
+.LC411:
+fldl Z1
+fmull Z
+fstpl X
+fldl X
+fstpl -1468(%ebp)
+fldl -1468(%ebp)
+fdivl Radix
+subl $8,%esp
+fstpl (%esp)
+call floor
+addl $8,%esp
+fstpl -1476(%ebp)
+fldl -1468(%ebp)
+fldl -1476(%ebp)
+fmull Radix
+fsubp %st(1),%st
+fstpl X
+fldl One
+fcompl X
+fstsw %ax
+sahf
+jne .LC414
+movl $1,Break
+jmp .LC415
+.LC414:
+fldl Z1
+fsubl One
+fstpl Z1
+.LC415:
+.LC412:
+cmpl $0,Break
+jne .LC416
+fldl Zero
+fcompl Z1
+fstsw %ax
+sahf
+jb .LC411
+.LC416:
+fldl Zero
+fcompl Z1
+fstsw %ax
+sahf
+jb .LC417
+cmpl $0,Break
+jne .LC417
+movl $1,Anomaly
+jmp .LC418
+.LC417:
+fldl RadixD2
+fcompl Z1
+fstsw %ax
+sahf
+jae .LC419
+fldl Z1
+fsubl Radix
+fstpl Z1
+.LC419:
+.LC421:
+call NewD
+.LC422:
+fldl U2
+fmull D
+fldl F9
+fcompp
+fstsw %ax
+sahf
+ja .LC421
+fldl D
+fmull Radix
+fsubl D
+fldl W
+fsubl D
+fcompp
+fstsw %ax
+sahf
+je .LC424
+movl $1,Anomaly
+jmp .LC425
+.LC424:
+fldl D
+fstpl Z2
+movl $0,I
+fldl D
+fldl One
+faddl Z
+fmull Half
+faddp %st(1),%st
+fstpl Y
+fldl D
+faddl Z
+faddl Q
+fstpl X
+call SR3750
+fldl D
+fldl One
+fsubl Z
+fmull Half
+faddp %st(1),%st
+faddl D
+fstpl Y
+fldl D
+fsubl Z
+faddl D
+fstpl X
+fldl X
+fstpl -1508(%ebp)
+fldl -1508(%ebp)
+faddl Q
+faddl -1508(%ebp)
+fstpl X
+call SR3750
+call NewD
+fldl D
+fsubl Z2
+fldl W
+fsubl Z2
+fcompp
+fstsw %ax
+sahf
+je .LC426
+movl $1,Anomaly
+jmp .LC427
+.LC426:
+fldl D
+fsubl Z2
+fstpl -1532(%ebp)
+fldl -1532(%ebp)
+fldl Z2
+fldl One
+fsubl Z
+fmull Half
+faddp %st(1),%st
+faddp %st(1),%st
+fstpl Y
+fldl -1532(%ebp)
+fldl Z2
+fsubl Z
+faddl Q
+faddp %st(1),%st
+fstpl X
+call SR3750
+fldl One
+faddl Z
+fmull Half
+fstpl Y
+fldl Q
+fstpl X
+call SR3750
+cmpl $0,I
+jne .LC428
+movl $1,Anomaly
+.LC428:
+.LC427:
+.LC425:
+.LC418:
+.LC410:
+.LC395:
+cmpl $0,I
+je .LC432
+cmpl $0,Anomaly
+je .LC430
+.LC432:
+pushl $.LC433
+pushl $0
+call BadCond
+addl $8,%esp
+fldl W
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC434
+call printf
+addl $12,%esp
+pushl $.LC435
+call printf
+addl $4,%esp
+movl $1,SqRWrng
+.LC430:
+.LC391:
+cmpl $0,Anomaly
+jne .LC436
+fldl Zero
+fcompl MinSqEr
+fstsw %ax
+sahf
+ja .LC438
+fldl Zero
+fcompl MaxSqEr
+fstsw %ax
+sahf
+jb .LC438
+movl $1,RSqrt
+pushl $.LC440
+call printf
+addl $4,%esp
+jmp .LC439
+.LC438:
+fldl MaxSqEr
+faddl U2
+fldl U2
+fsubl Half
+fcompp
+fstsw %ax
+sahf
+jb .LC444
+fldl Half
+fcompl MinSqEr
+fstsw %ax
+sahf
+jb .LC444
+fldl MinSqEr
+faddl Radix
+fldl Half
+fcompp
+fstsw %ax
+sahf
+jbe .LC441
+.LC444:
+movl $1,SqRWrng
+jmp .LC442
+.LC441:
+movl $2,RSqrt
+pushl $.LC445
+call printf
+addl $4,%esp
+.LC442:
+.LC439:
+.LC436:
+cmpl $0,SqRWrng
+je .LC446
+pushl $.LC448
+call printf
+addl $4,%esp
+fldl MinSqEr
+fsubl Half
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC449
+call printf
+addl $12,%esp
+fldl Half
+faddl MaxSqEr
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC450
+call printf
+addl $12,%esp
+pushl $.LC452
+fldl MaxSqEr
+fsubl MinSqEr
+fldl Radix
+fmull Radix
+fcompp
+fstsw %ax
+sahf
+jbe .LC453
+movl $1,-1344(%ebp)
+jmp .LC454
+.LC453:
+movl $0,-1344(%ebp)
+.LC454:
+pushl -1344(%ebp)
+pushl $1
+call TstCond
+addl $12,%esp
+.LC446:
+movl $90,Milestone
+call Pause
+pushl $.LC455
+call printf
+addl $4,%esp
+movl $0,N
+movl $0,I
+fldl Zero
+fchs
+fstpl Z
+movl $3,M
+movl $0,Break
+.LC456:
+fldl One
+fstpl X
+call SR3980
+cmpl $10,I
+jg .LC459
+movl $1023,I
+call SR3980
+.LC459:
+fldl MinusOne
+fcompl Z
+fstsw %ax
+sahf
+jne .LC461
+movl $1,Break
+jmp .LC462
+.LC461:
+fldl MinusOne
+fstpl Z
+call PrintIfNPositive
+movl $0,N
+movl $-4,I
+.LC462:
+.LC457:
+cmpl $0,Break
+je .LC456
+call PrintIfNPositive
+movl N,%edi
+movl %edi,N1
+movl $0,N
+fldl A1
+fstpl Z
+fldl W
+subl $8,%esp
+fstpl (%esp)
+call log
+addl $8,%esp
+fstpl -1348(%ebp)
+fldl A1
+subl $8,%esp
+fstpl (%esp)
+call log
+addl $8,%esp
+fstpl -1356(%ebp)
+fldl Two
+fmull -1348(%ebp)
+fdivl -1356(%ebp)
+subl $8,%esp
+fstpl (%esp)
+call floor
+addl $8,%esp
+fstpl -1364(%ebp)
+fldl -1364(%ebp)
+fistpl M
+movl $0,Break
+.LC463:
+fldl Z
+fstpl X
+movl $1,I
+call SR3980
+fldl AInvrse
+fcompl Z
+fstsw %ax
+sahf
+jne .LC466
+movl $1,Break
+jmp .LC467
+.LC466:
+fldl AInvrse
+fstpl Z
+.LC467:
+.LC464:
+cmpl $0,Break
+je .LC463
+movl $100,Milestone
+movl NoTrials,%edi
+movl %edi,M
+fldl Three
+fstpl Z
+.LC468:
+fldl Z
+fstpl X
+movl $1,I
+call SR3980
+.LC471:
+fldl Z
+faddl Two
+fstpl Z
+.LC472:
+fldl Z
+fdivl Three
+subl $8,%esp
+fstpl (%esp)
+call floor
+addl $8,%esp
+fstpl -1380(%ebp)
+fldl Three
+fmull -1380(%ebp)
+fldl Z
+fcompp
+fstsw %ax
+sahf
+je .LC471
+.LC469:
+fldl Eight
+fmull Three
+fcompl Z
+fstsw %ax
+sahf
+ja .LC468
+cmpl $0,N
+jle .LC474
+pushl $.LC476
+call printf
+addl $4,%esp
+pushl $.LC477
+call printf
+addl $4,%esp
+.LC474:
+call PrintIfNPositive
+movl N1,%edi
+addl %edi,N
+cmpl $0,N
+jne .LC478
+pushl $.LC480
+call printf
+addl $4,%esp
+.LC478:
+cmpl $0,N
+jle .LC481
+call Pause
+jmp .LC482
+.LC481:
+pushl $.LC45
+call printf
+addl $4,%esp
+.LC482:
+movl $110,Milestone
+pushl $.LC483
+call printf
+addl $4,%esp
+fldl U1
+fstpl D
+fldl Precision
+subl $8,%esp
+fstpl (%esp)
+call floor
+addl $8,%esp
+fstpl -1380(%ebp)
+fldl -1380(%ebp)
+fcompl Precision
+fstsw %ax
+sahf
+je .LC484
+fldl BInvrse
+fstpl D
+fldl Precision
+fstpl X
+.LC486:
+fldl D
+fmull BInvrse
+fstpl D
+fldl X
+fsubl One
+fstpl X
+.LC487:
+fldl Zero
+fcompl X
+fstsw %ax
+sahf
+jb .LC486
+.LC484:
+fldl One
+fstpl Y
+fldl D
+fstpl Z
+.LC489:
+fldl Y
+fstpl C
+fldl Z
+fstpl Y
+fldl Y
+fstpl -1388(%ebp)
+fldl -1388(%ebp)
+fmull -1388(%ebp)
+fstpl Z
+.LC490:
+fldl Z
+fcompl Y
+fstsw %ax
+sahf
+jae .LC492
+fldl Z
+faddl Z
+fldl Z
+fcompp
+fstsw %ax
+sahf
+jb .LC489
+.LC492:
+fldl C
+fstpl Y
+fldl Y
+fmull D
+fstpl Z
+.LC493:
+fldl Y
+fstpl C
+fldl Z
+fstpl Y
+fldl Y
+fmull D
+fstpl Z
+.LC494:
+fldl Z
+fcompl Y
+fstsw %ax
+sahf
+jae .LC496
+fldl Z
+faddl Z
+fldl Z
+fcompp
+fstsw %ax
+sahf
+jb .LC493
+.LC496:
+fldl Two
+fcompl Radix
+fstsw %ax
+sahf
+jbe .LC497
+fldl Two
+fstpl HInvrse
+jmp .LC498
+.LC497:
+fldl Radix
+fstpl HInvrse
+.LC498:
+fldl One
+fdivl HInvrse
+fstpl H
+fldl One
+fdivl C
+fstpl CInvrse
+fldl C
+fstpl E0
+fldl E0
+fmull H
+fstpl Z
+.LC499:
+fldl E0
+fstpl Y
+fldl Z
+fstpl E0
+fldl E0
+fmull H
+fstpl Z
+.LC500:
+fldl Z
+fcompl E0
+fstsw %ax
+sahf
+jae .LC502
+fldl Z
+faddl Z
+fldl Z
+fcompp
+fstsw %ax
+sahf
+jb .LC499
+.LC502:
+fldl E0
+fstpl UfThold
+fldl Zero
+fstpl E1
+fldl Zero
+fstpl Q
+fldl U2
+fstpl E9
+fldl One
+faddl E9
+fstpl S
+fldl C
+fmull S
+fstpl D
+fldl C
+fcompl D
+fstsw %ax
+sahf
+jb .LC503
+fldl Radix
+fmull U2
+fstpl E9
+fldl One
+faddl E9
+fstpl S
+fldl C
+fmull S
+fstpl D
+fldl C
+fcompl D
+fstsw %ax
+sahf
+jb .LC504
+pushl $.LC507
+pushl $0
+call BadCond
+addl $8,%esp
+fldl E0
+fstpl Underflow
+fldl Zero
+fstpl Y1
+fldl Z
+fstpl PseudoZero
+call Pause
+jmp .LC504
+.LC503:
+fldl D
+fstpl Underflow
+fldl Underflow
+fmull H
+fstpl PseudoZero
+fldl Zero
+fstpl UfThold
+.LC508:
+fldl Underflow
+fstpl Y1
+fldl PseudoZero
+fstpl Underflow
+fldl E1
+faddl E1
+fldl E1
+fcompp
+fstsw %ax
+sahf
+jb .LC511
+fldl Underflow
+fmull HInvrse
+fstpl Y2
+fldl Y1
+fsubl Y2
+subl $8,%esp
+fstpl (%esp)
+call fabs
+addl $8,%esp
+fstpl -1452(%ebp)
+fldl -1452(%ebp)
+fstpl E1
+fldl Y1
+fstpl Q
+fldl Zero
+fcompl UfThold
+fstsw %ax
+sahf
+jne .LC513
+fldl Y2
+fcompl Y1
+fstsw %ax
+sahf
+je .LC513
+fldl Y1
+fstpl UfThold
+.LC513:
+.LC511:
+fldl PseudoZero
+fmull H
+fstpl PseudoZero
+.LC509:
+fldl PseudoZero
+fcompl Underflow
+fstsw %ax
+sahf
+jae .LC515
+fldl PseudoZero
+faddl PseudoZero
+fldl PseudoZero
+fcompp
+fstsw %ax
+sahf
+jb .LC508
+.LC515:
+.LC504:
+fldl Zero
+fcompl PseudoZero
+fstsw %ax
+sahf
+je .LC516
+pushl $.LC45
+call printf
+addl $4,%esp
+fldl PseudoZero
+fstpl Z
+fldl Zero
+fcompl PseudoZero
+fstsw %ax
+sahf
+jb .LC518
+pushl $.LC520
+pushl $0
+call BadCond
+addl $8,%esp
+pushl $.LC521
+call printf
+addl $4,%esp
+fldl PseudoZero
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC522
+call printf
+addl $12,%esp
+fldl PseudoZero
+fchs
+fstpl X
+fldl Zero
+fcompl X
+fstsw %ax
+sahf
+jb .LC519
+pushl $.LC525
+call printf
+addl $4,%esp
+fldl X
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC526
+call printf
+addl $12,%esp
+jmp .LC519
+.LC518:
+pushl $.LC527
+pushl $3
+call BadCond
+addl $8,%esp
+fldl PseudoZero
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC528
+call printf
+addl $12,%esp
+.LC519:
+call TstPtUf
+.LC516:
+movl $120,Milestone
+fldl CInvrse
+fmull Y
+fldl CInvrse
+fmull Y1
+fcompp
+fstsw %ax
+sahf
+jae .LC529
+fldl H
+fmull S
+fstpl S
+fldl Underflow
+fstpl E0
+.LC529:
+fldl Zero
+fcompl E1
+fstsw %ax
+sahf
+je .LC531
+fldl E0
+fcompl E1
+fstsw %ax
+sahf
+je .LC531
+pushl $.LC158
+pushl $2
+call BadCond
+addl $8,%esp
+fldl E0
+fcompl E1
+fstsw %ax
+sahf
+jbe .LC533
+pushl $.LC535
+call printf
+addl $4,%esp
+pushl $.LC536
+call printf
+addl $4,%esp
+fldl Zero
+fcompl PseudoZero
+fstsw %ax
+sahf
+jne .LC534
+fldl E1
+fstpl E0
+jmp .LC534
+.LC533:
+pushl $.LC539
+call printf
+addl $4,%esp
+pushl $.LC540
+call printf
+addl $4,%esp
+.LC534:
+.LC531:
+fldl E0
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC541
+call printf
+addl $12,%esp
+fldl E0
+fstpl Z
+call TstPtUf
+fldl E0
+fstpl Underflow
+cmpl $1,N
+jne .LC542
+fldl Y
+fstpl Underflow
+.LC542:
+movl $4,I
+fldl Zero
+fcompl E1
+fstsw %ax
+sahf
+jne .LC544
+movl $3,I
+.LC544:
+fldl Zero
+fcompl UfThold
+fstsw %ax
+sahf
+jne .LC546
+sub $2,I
+.LC546:
+movl $1,UfNGrad
+movl I,%edi
+cmpl $1,%edi
+jl .LC548
+cmpl $4,%edi
+jg .LC548
+jmp *.LC571-4(,%edi,4)
+.data
+.align 4
+.LC571:
+.long .LC550
+.long .LC557
+.long .LC562
+.long .LC563
+.text
+.LC550:
+fldl Underflow
+fstpl UfThold
+fldl CInvrse
+fmull Q
+fldl CInvrse
+fmull Y
+fmull S
+fcompp
+fstsw %ax
+sahf
+je .LC551
+fldl Y
+fstpl UfThold
+pushl $.LC553
+pushl $0
+call BadCond
+addl $8,%esp
+fldl UfThold
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC554
+call printf
+addl $12,%esp
+fldl C
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC555
+call printf
+addl $12,%esp
+pushl $.LC556
+call printf
+addl $4,%esp
+.LC551:
+call Pause
+jmp .LC549
+.LC557:
+pushl $.LC558
+pushl $0
+call BadCond
+addl $8,%esp
+pushl $.LC559
+call printf
+addl $4,%esp
+fldl Y2
+subl $8,%esp
+fstpl (%esp)
+fldl Q
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC560
+call printf
+addl $20,%esp
+fldl Q
+fsubl Y2
+subl $8,%esp
+fstpl (%esp)
+call fabs
+addl $8,%esp
+fstpl -1468(%ebp)
+fldl -1468(%ebp)
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC561
+call printf
+addl $12,%esp
+fldl Q
+fstpl UfThold
+jmp .LC549
+.LC562:
+fldl X
+fstpl X
+jmp .LC549
+.LC563:
+fldl UfThold
+fcompl Q
+fstsw %ax
+sahf
+jne .LC564
+fldl E0
+fcompl E1
+fstsw %ax
+sahf
+jne .LC564
+fldl UfThold
+fldl E1
+fdivl E9
+fsubp %st(1),%st
+subl $8,%esp
+fstpl (%esp)
+call fabs
+addl $8,%esp
+fstpl -1492(%ebp)
+fldl E1
+fcompl -1492(%ebp)
+fstsw %ax
+sahf
+jb .LC564
+movl $0,UfNGrad
+pushl $.LC566
+call printf
+addl $4,%esp
+pushl $.LC567
+call printf
+addl $4,%esp
+fldl E0
+fmull CInvrse
+fstpl Y
+fldl Y
+fldl OneAndHalf
+faddl U2
+fmulp %st(1),%st
+fstpl Y
+fldl CInvrse
+fldl One
+faddl U2
+fmulp %st(1),%st
+fstpl X
+fldl Y
+fdivl X
+fstpl Y
+fldl E0
+fcompl Y
+fstsw %ax
+sahf
+jne .LC569
+movl $1,-1496(%ebp)
+jmp .LC570
+.LC569:
+movl $0,-1496(%ebp)
+.LC570:
+movl -1496(%ebp),%edi
+movl %edi,IEEE
+.LC564:
+.LC548:
+.LC549:
+cmpl $0,UfNGrad
+je .LC573
+pushl $.LC45
+call printf
+addl $4,%esp
+leal sigfpe,%edi
+movl %edi,sigsave
+pushl $ovfl_buf
+call __setjmp
+addl $4,%esp
+cmpl $0,%eax
+je .LC575
+pushl $.LC577
+call printf
+addl $4,%esp
+fldl H
+faddl H
+fstpl R
+jmp .LC576
+.LC575:
+fldl Underflow
+fdivl UfThold
+subl $8,%esp
+fstpl (%esp)
+call sqrt
+addl $8,%esp
+fstpl -1460(%ebp)
+fldl -1460(%ebp)
+fstpl R
+.LC576:
+movl $0,sigsave
+fldl H
+fcompl R
+fstsw %ax
+sahf
+jb .LC578
+fldl R
+fmull UfThold
+fstpl Z
+fldl Z
+fldl One
+fldl R
+fmull H
+fldl One
+faddl H
+fmulp %st(1),%st
+faddp %st(1),%st
+fmulp %st(1),%st
+fstpl X
+jmp .LC579
+.LC578:
+fldl UfThold
+fstpl Z
+fldl Z
+fldl One
+fldl H
+fmull H
+fldl One
+faddl H
+fmulp %st(1),%st
+faddp %st(1),%st
+fmulp %st(1),%st
+fstpl X
+.LC579:
+fldl Z
+fcompl X
+fstsw %ax
+sahf
+je .LC580
+fldl X
+fsubl Z
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC580
+pushl $.LC158
+pushl $3
+call BadCond
+addl $8,%esp
+fldl Z
+subl $8,%esp
+fstpl (%esp)
+fldl X
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC582
+call printf
+addl $20,%esp
+fldl X
+fsubl Z
+fstpl Z9
+fldl Z9
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC583
+call printf
+addl $12,%esp
+pushl $.LC584
+call printf
+addl $4,%esp
+pushl $.LC585
+call printf
+addl $4,%esp
+pushl $.LC586
+call printf
+addl $4,%esp
+pushl $.LC587
+call printf
+addl $4,%esp
+pushl $.LC588
+call printf
+addl $4,%esp
+pushl $.LC589
+call printf
+addl $4,%esp
+leal sigfpe,%edi
+movl %edi,sigsave
+pushl $ovfl_buf
+call __setjmp
+addl $4,%esp
+cmpl $0,%eax
+je .LC590
+pushl $.LC592
+call printf
+addl $4,%esp
+jmp .LC591
+.LC590:
+fldl X
+fdivl Z
+fsubl Half
+fsubl Half
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC593
+call printf
+addl $12,%esp
+.LC591:
+movl $0,sigsave
+.LC580:
+.LC573:
+pushl $.LC595
+fldl UfThold
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC594
+call printf
+addl $16,%esp
+pushl $.LC596
+call printf
+addl $4,%esp
+pushl $.LC597
+call printf
+addl $4,%esp
+fldl U1
+fmull U1
+fstpl Y2
+fldl Y2
+fstpl -1468(%ebp)
+fldl -1468(%ebp)
+fmull -1468(%ebp)
+fstpl Y
+fldl Y
+fmull U1
+fstpl Y2
+fldl UfThold
+fcompl Y2
+fstsw %ax
+sahf
+jb .LC598
+fldl E0
+fcompl Y
+fstsw %ax
+sahf
+jae .LC600
+pushl $.LC158
+pushl $2
+call BadCond
+addl $8,%esp
+movl $5,I
+jmp .LC601
+.LC600:
+pushl $.LC158
+pushl $1
+call BadCond
+addl $8,%esp
+movl $4,I
+.LC601:
+pushl I
+pushl $.LC602
+call printf
+addl $8,%esp
+.LC598:
+movl $130,Milestone
+fldl UfThold
+subl $8,%esp
+fstpl (%esp)
+call log
+addl $8,%esp
+fstpl -1476(%ebp)
+fldl HInvrse
+subl $8,%esp
+fstpl (%esp)
+call log
+addl $8,%esp
+fstpl -1484(%ebp)
+fldl Half
+fldl TwoForty
+fmull -1476(%ebp)
+fdivl -1484(%ebp)
+fsubp %st(1),%st
+subl $8,%esp
+fstpl (%esp)
+call floor
+addl $8,%esp
+fstpl -1492(%ebp)
+fldl -1492(%ebp)
+fchs
+fdivl TwoForty
+fstpl Y
+fldl Y
+faddl Y
+fstpl Y2
+pushl $.LC603
+call printf
+addl $4,%esp
+fldl Y
+subl $8,%esp
+fstpl (%esp)
+fldl HInvrse
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC604
+call printf
+addl $20,%esp
+fldl Y
+subl $8,%esp
+fstpl (%esp)
+fldl HInvrse
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC605
+call printf
+addl $20,%esp
+fldl Y2
+subl $8,%esp
+fstpl (%esp)
+fldl HInvrse
+subl $8,%esp
+fstpl (%esp)
+call pow
+addl $16,%esp
+fstpl -1508(%ebp)
+fldl -1508(%ebp)
+fstpl V9
+fldl V9
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC606
+call printf
+addl $12,%esp
+fldl Zero
+fcompl V9
+fstsw %ax
+sahf
+ja .LC609
+fldl Radix
+faddl Radix
+faddl E9
+fmull UfThold
+fcompl V9
+fstsw %ax
+sahf
+jae .LC607
+.LC609:
+pushl $.LC610
+pushl $1
+call BadCond
+addl $8,%esp
+fldl UfThold
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC611
+call printf
+addl $12,%esp
+jmp .LC608
+.LC607:
+fldl UfThold
+fldl One
+faddl E9
+fmulp %st(1),%st
+fcompl V9
+fstsw %ax
+sahf
+jb .LC612
+pushl $.LC614
+call printf
+addl $4,%esp
+jmp .LC613
+.LC612:
+pushl $.LC610
+pushl $2
+call BadCond
+addl $8,%esp
+fldl UfThold
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC611
+call printf
+addl $12,%esp
+.LC613:
+.LC608:
+movl $140,Milestone
+pushl $.LC45
+call printf
+addl $4,%esp
+fldl Zero
+fstpl X
+movl $2,I
+fldl Two
+fmull Three
+fstpl Y
+fldl Zero
+fstpl Q
+movl $0,N
+.LC615:
+fldl X
+fstpl Z
+incl I
+movl I,%edi
+fldl Y
+leal (%edi,%edi),%edi
+pushl %edi
+fildl (%esp)
+addl $4,%esp
+fdivp %st(1),%st
+fstpl Y
+fldl Y
+faddl Q
+fstpl R
+fldl Z
+fstpl -1540(%ebp)
+fldl R
+fstpl -1548(%ebp)
+fldl -1540(%ebp)
+faddl -1548(%ebp)
+fstpl X
+fldl -1540(%ebp)
+fsubl X
+faddl -1548(%ebp)
+fstpl Q
+.LC616:
+fldl Z
+fcompl X
+fstsw %ax
+sahf
+jb .LC615
+fldl OneAndHalf
+fldl One
+fdivl Eight
+faddp %st(1),%st
+fldl X
+fldl OneAndHalf
+fmull ThirtyTwo
+fdivp %st(1),%st
+faddp %st(1),%st
+fstpl Z
+fldl Z
+fstpl -1548(%ebp)
+fldl -1548(%ebp)
+fmull -1548(%ebp)
+fstpl X
+fldl X
+fstpl -1556(%ebp)
+fldl -1556(%ebp)
+fmull -1556(%ebp)
+fstpl Exp2
+fldl F9
+fstpl X
+fldl X
+fsubl U1
+fstpl Y
+fldl Exp2
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC618
+call printf
+addl $12,%esp
+movl $1,I
+.LC619:
+fldl X
+fsubl BInvrse
+fstpl Z
+fldl X
+faddl One
+fldl Z
+fldl One
+fsubl BInvrse
+fsubp %st(1),%st
+fdivp %st(1),%st
+fstpl Z
+fldl Z
+subl $8,%esp
+fstpl (%esp)
+fldl X
+subl $8,%esp
+fstpl (%esp)
+call pow
+addl $16,%esp
+fstpl -1588(%ebp)
+fldl -1588(%ebp)
+fsubl Exp2
+fstpl Q
+fldl Q
+subl $8,%esp
+fstpl (%esp)
+call fabs
+addl $8,%esp
+fstpl -1596(%ebp)
+fldl TwoForty
+fmull U2
+fcompl -1596(%ebp)
+fstsw %ax
+sahf
+jae .LC623
+movl $1,N
+fldl X
+fsubl BInvrse
+fldl One
+fsubl BInvrse
+fsubp %st(1),%st
+fstpl V9
+pushl $.LC625
+pushl $2
+call BadCond
+addl $8,%esp
+fldl Z
+subl $8,%esp
+fstpl (%esp)
+fldl X
+subl $8,%esp
+fstpl (%esp)
+call pow
+addl $16,%esp
+fstpl -1612(%ebp)
+fldl -1612(%ebp)
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC626
+call printf
+addl $12,%esp
+fldl Z
+subl $8,%esp
+fstpl (%esp)
+fldl V9
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC627
+call printf
+addl $20,%esp
+fldl Q
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC628
+call printf
+addl $12,%esp
+pushl $.LC629
+call printf
+addl $4,%esp
+pushl $.LC630
+call printf
+addl $4,%esp
+jmp .LC621
+.LC623:
+fldl Y
+fstpl -1604(%ebp)
+fldl -1604(%ebp)
+fsubl X
+fmull Two
+faddl -1604(%ebp)
+fstpl Z
+fldl -1604(%ebp)
+fstpl X
+fldl Z
+fstpl Y
+fldl X
+fsubl F9
+fstpl -1612(%ebp)
+fldl One
+fldl -1612(%ebp)
+fmull -1612(%ebp)
+faddp %st(1),%st
+fstpl Z
+fldl One
+fcompl Z
+fstsw %ax
+sahf
+jae .LC631
+movl NoTrials,%edi
+cmpl %edi,I
+jge .LC631
+incl I
+jmp .LC619
+.LC631:
+fldl One
+fcompl X
+fstsw %ax
+sahf
+jae .LC633
+cmpl $0,N
+jne .LC621
+pushl $.LC637
+call printf
+addl $4,%esp
+jmp .LC621
+.LC633:
+fldl One
+faddl U2
+fstpl X
+fldl U2
+faddl U2
+fstpl Y
+fldl Y
+faddl X
+fstpl Y
+movl $1,I
+jmp .LC619
+.LC621:
+movl $150,Milestone
+pushl $.LC638
+call printf
+addl $4,%esp
+movl $0,N
+fldl A1
+fstpl Z
+fldl C
+subl $8,%esp
+fstpl (%esp)
+call log
+addl $8,%esp
+fstpl -1564(%ebp)
+fldl A1
+subl $8,%esp
+fstpl (%esp)
+call log
+addl $8,%esp
+fstpl -1572(%ebp)
+fldl Half
+fldl -1564(%ebp)
+fdivl -1572(%ebp)
+fsubp %st(1),%st
+subl $8,%esp
+fstpl (%esp)
+call floor
+addl $8,%esp
+fstpl -1580(%ebp)
+fldl -1580(%ebp)
+fstpl Q
+movl $0,Break
+.LC639:
+fldl CInvrse
+fstpl X
+fldl Q
+subl $8,%esp
+fstpl (%esp)
+fldl Z
+subl $8,%esp
+fstpl (%esp)
+call pow
+addl $16,%esp
+fstpl -1588(%ebp)
+fldl -1588(%ebp)
+fstpl Y
+call IsYeqX
+fldl Q
+fchs
+fstpl Q
+fldl C
+fstpl X
+fldl Q
+subl $8,%esp
+fstpl (%esp)
+fldl Z
+subl $8,%esp
+fstpl (%esp)
+call pow
+addl $16,%esp
+fstpl -1596(%ebp)
+fldl -1596(%ebp)
+fstpl Y
+call IsYeqX
+fldl One
+fcompl Z
+fstsw %ax
+sahf
+jbe .LC642
+movl $1,Break
+jmp .LC643
+.LC642:
+fldl AInvrse
+fstpl Z
+.LC643:
+.LC640:
+cmpl $0,Break
+je .LC639
+call PrintIfNPositive
+cmpl $0,N
+jne .LC644
+pushl $.LC646
+call printf
+addl $4,%esp
+.LC644:
+pushl $.LC45
+call printf
+addl $4,%esp
+movl $160,Milestone
+call Pause
+pushl $.LC647
+call printf
+addl $4,%esp
+pushl $.LC648
+call printf
+addl $4,%esp
+fldl CInvrse
+fchs
+fstpl Y
+fldl HInvrse
+fmull Y
+fstpl V9
+leal sigfpe,%edi
+movl %edi,sigsave
+pushl $ovfl_buf
+call __setjmp
+addl $4,%esp
+cmpl $0,%eax
+je .LC649
+movl $0,I
+fldl Y
+fstpl V9
+jmp .LC651
+.LC649:
+.LC652:
+fldl Y
+fstpl V
+fldl V9
+fstpl Y
+fldl HInvrse
+fmull Y
+fstpl V9
+.LC653:
+fldl Y
+fcompl V9
+fstsw %ax
+sahf
+ja .LC652
+movl $1,I
+.LC651:
+movl $0,sigsave
+fldl V9
+fstpl Z
+pushl $.LC655
+call printf
+addl $4,%esp
+fldl Y
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC656
+call printf
+addl $12,%esp
+fldl Y
+fchs
+fstpl V9
+fldl V9
+fstpl V0
+fldl V
+fsubl Y
+fldl V
+faddl V0
+fcompp
+fstsw %ax
+sahf
+jne .LC657
+pushl $.LC659
+call printf
+addl $4,%esp
+jmp .LC658
+.LC657:
+pushl $.LC660
+call printf
+addl $4,%esp
+pushl $.LC661
+pushl $3
+call BadCond
+addl $8,%esp
+.LC658:
+fldl Y
+fcompl Z
+fstsw %ax
+sahf
+je .LC662
+pushl $.LC158
+pushl $1
+call BadCond
+addl $8,%esp
+fldl Z
+subl $8,%esp
+fstpl (%esp)
+fldl Y
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC664
+call printf
+addl $20,%esp
+.LC662:
+cmpl $0,I
+je .LC665
+fldl V
+fldl HInvrse
+fmull U2
+fsubl HInvrse
+fmulp %st(1),%st
+fstpl Y
+fldl Y
+fldl One
+fsubl HInvrse
+fmull U2
+fmull V
+faddp %st(1),%st
+fstpl Z
+fldl V0
+fcompl Z
+fstsw %ax
+sahf
+jbe .LC667
+fldl Z
+fstpl Y
+.LC667:
+fldl V0
+fcompl Y
+fstsw %ax
+sahf
+jbe .LC669
+fldl Y
+fstpl V
+.LC669:
+fldl V0
+fsubl V
+fldl V0
+fcompp
+fstsw %ax
+sahf
+jbe .LC666
+fldl V0
+fstpl V
+jmp .LC666
+.LC665:
+fldl Y
+fldl HInvrse
+fmull U2
+fsubl HInvrse
+fmulp %st(1),%st
+fstpl V
+fldl V
+fldl One
+fsubl HInvrse
+fmull U2
+fmull Y
+faddp %st(1),%st
+fstpl V
+.LC666:
+fldl V
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC673
+call printf
+addl $12,%esp
+cmpl $0,I
+je .LC674
+fldl V0
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC676
+call printf
+addl $12,%esp
+jmp .LC675
+.LC674:
+pushl $.LC677
+call printf
+addl $4,%esp
+.LC675:
+fldl V
+fmull One
+fstpl V9
+fldl V9
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC678
+call printf
+addl $12,%esp
+fldl V
+fdivl One
+fstpl V9
+fldl V9
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC679
+call printf
+addl $12,%esp
+pushl $.LC680
+call printf
+addl $4,%esp
+pushl $.LC681
+call printf
+addl $4,%esp
+movl $170,Milestone
+fldl V
+fchs
+fldl V
+fcompp
+fstsw %ax
+sahf
+jbe .LC686
+fldl V0
+fchs
+fldl V0
+fcompp
+fstsw %ax
+sahf
+jbe .LC686
+fldl UfThold
+fchs
+fldl V
+fcompp
+fstsw %ax
+sahf
+jbe .LC686
+fldl V
+fcompl UfThold
+fstsw %ax
+sahf
+ja .LC682
+.LC686:
+pushl $.LC687
+pushl $0
+call BadCond
+addl $8,%esp
+fldl UfThold
+subl $8,%esp
+fstpl (%esp)
+fldl V0
+subl $8,%esp
+fstpl (%esp)
+fldl V
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC688
+call printf
+addl $28,%esp
+.LC682:
+movl $175,Milestone
+pushl $.LC45
+call printf
+addl $4,%esp
+movl $1,Indx
+.LC689:
+movl Indx,%edi
+cmpl $1,%edi
+je .LC695
+cmpl $2,%edi
+je .LC696
+cmpl $3,%edi
+je .LC697
+jmp .LC693
+.LC695:
+fldl UfThold
+fstpl Z
+jmp .LC694
+.LC696:
+fldl E0
+fstpl Z
+jmp .LC694
+.LC697:
+fldl PseudoZero
+fstpl Z
+.LC693:
+.LC694:
+fldl Zero
+fcompl Z
+fstsw %ax
+sahf
+je .LC698
+fldl Z
+subl $8,%esp
+fstpl (%esp)
+call sqrt
+addl $8,%esp
+fstpl -1628(%ebp)
+fldl -1628(%ebp)
+fstpl V9
+fldl V9
+fmull V9
+fstpl Y
+fldl Radix
+fmull E9
+fstpl -1660(%ebp)
+fldl Y
+fldl One
+fsubl -1660(%ebp)
+fdivp %st(1),%st
+fldl Z
+fcompp
+fstsw %ax
+sahf
+ja .LC702
+fldl One
+faddl -1660(%ebp)
+fmull Z
+fcompl Y
+fstsw %ax
+sahf
+jae .LC700
+.LC702:
+fldl U1
+fcompl V9
+fstsw %ax
+sahf
+jae .LC703
+pushl $.LC158
+pushl $1
+call BadCond
+addl $8,%esp
+jmp .LC704
+.LC703:
+pushl $.LC158
+pushl $2
+call BadCond
+addl $8,%esp
+.LC704:
+fldl Z
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC705
+call printf
+addl $12,%esp
+fldl Y
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC706
+call printf
+addl $12,%esp
+.LC700:
+.LC698:
+.LC690:
+incl Indx
+cmpl $3,Indx
+jle .LC689
+movl $180,Milestone
+movl $1,Indx
+.LC707:
+cmpl $1,Indx
+jne .LC711
+fldl V
+fstpl Z
+jmp .LC712
+.LC711:
+fldl V0
+fstpl Z
+.LC712:
+fldl Z
+subl $8,%esp
+fstpl (%esp)
+call sqrt
+addl $8,%esp
+fstpl -1628(%ebp)
+fldl -1628(%ebp)
+fstpl V9
+fldl V9
+fstpl -1636(%ebp)
+fldl One
+fldl Radix
+fmull E9
+fsubp %st(1),%st
+fmull -1636(%ebp)
+fstpl X
+fldl -1636(%ebp)
+fmull X
+fstpl V9
+fldl One
+fldl Two
+fmull Radix
+fmull E9
+fsubp %st(1),%st
+fmull Z
+fcompl V9
+fstsw %ax
+sahf
+ja .LC715
+fldl Z
+fcompl V9
+fstsw %ax
+sahf
+jae .LC713
+.LC715:
+fldl V9
+fstpl Y
+fldl W
+fcompl X
+fstsw %ax
+sahf
+jbe .LC716
+pushl $.LC158
+pushl $1
+call BadCond
+addl $8,%esp
+jmp .LC717
+.LC716:
+pushl $.LC158
+pushl $2
+call BadCond
+addl $8,%esp
+.LC717:
+fldl Z
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC718
+call printf
+addl $12,%esp
+fldl Y
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC719
+call printf
+addl $12,%esp
+.LC713:
+.LC708:
+incl Indx
+cmpl $2,Indx
+jle .LC707
+movl $190,Milestone
+call Pause
+fldl UfThold
+fmull V
+fstpl X
+fldl Radix
+fmull Radix
+fstpl Y
+fldl X
+fmull Y
+fldl One
+fcompp
+fstsw %ax
+sahf
+ja .LC722
+fldl Y
+fcompl X
+fstsw %ax
+sahf
+jae .LC720
+.LC722:
+fldl X
+fmull Y
+fldl U1
+fcompp
+fstsw %ax
+sahf
+ja .LC725
+fldl Y
+fdivl U1
+fcompl X
+fstsw %ax
+sahf
+jae .LC723
+.LC725:
+pushl $.LC726
+pushl $2
+call BadCond
+addl $8,%esp
+jmp .LC724
+.LC723:
+pushl $.LC158
+pushl $3
+call BadCond
+addl $8,%esp
+.LC724:
+pushl $.LC728
+fldl X
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC727
+call printf
+addl $16,%esp
+.LC720:
+movl $200,Milestone
+movl $1,Indx
+.LC729:
+fldl F9
+fstpl X
+movl Indx,%edi
+cmpl $2,%edi
+jl .LC733
+cmpl $5,%edi
+jg .LC733
+jmp *.LC739-8(,%edi,4)
+.data
+.align 4
+.LC739:
+.long .LC735
+.long .LC736
+.long .LC737
+.long .LC738
+.text
+.LC735:
+fldl One
+faddl U2
+fstpl X
+jmp .LC734
+.LC736:
+fldl V
+fstpl X
+jmp .LC734
+.LC737:
+fldl UfThold
+fstpl X
+jmp .LC734
+.LC738:
+fldl Radix
+fstpl X
+.LC733:
+.LC734:
+fldl X
+fstpl Y
+leal sigfpe,%edi
+movl %edi,sigsave
+pushl $ovfl_buf
+call __setjmp
+addl $4,%esp
+cmpl $0,%eax
+je .LC741
+fldl X
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC743
+call printf
+addl $12,%esp
+jmp .LC742
+.LC741:
+fldl Y
+fdivl X
+fsubl Half
+fsubl Half
+fstpl V9
+fldl Zero
+fcompl V9
+fstsw %ax
+sahf
+jne .LC744
+jmp .LC730
+.LC744:
+fldl U1
+fchs
+fcompl V9
+fstsw %ax
+sahf
+jne .LC746
+cmpl $5,Indx
+jge .LC746
+pushl $.LC158
+pushl $3
+call BadCond
+addl $8,%esp
+jmp .LC747
+.LC746:
+pushl $.LC158
+pushl $1
+call BadCond
+addl $8,%esp
+.LC747:
+fldl X
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC748
+call printf
+addl $12,%esp
+fldl V9
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC749
+call printf
+addl $12,%esp
+.LC742:
+movl $0,sigsave
+.LC730:
+incl Indx
+cmpl $5,Indx
+jle .LC729
+movl $210,Milestone
+fldl Zero
+fstpl MyZero
+pushl $.LC45
+call printf
+addl $4,%esp
+pushl $.LC750
+call printf
+addl $4,%esp
+leal sigfpe,%edi
+movl %edi,sigsave
+pushl $.LC751
+call printf
+addl $4,%esp
+pushl $ovfl_buf
+call __setjmp
+addl $4,%esp
+cmpl $0,%eax
+jne .LC752
+fldl One
+fdivl MyZero
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC754
+call printf
+addl $12,%esp
+.LC752:
+movl $0,sigsave
+leal sigfpe,%edi
+movl %edi,sigsave
+pushl $.LC755
+call printf
+addl $4,%esp
+pushl $ovfl_buf
+call __setjmp
+addl $4,%esp
+cmpl $0,%eax
+jne .LC756
+fldl Zero
+fdivl MyZero
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC754
+call printf
+addl $12,%esp
+.LC756:
+movl $0,sigsave
+movl $220,Milestone
+call Pause
+pushl $.LC45
+call printf
+addl $4,%esp
+movl $0,-1648(%ebp)
+.LC763:
+movl -1648(%ebp),%edi
+cmpl $0,ErrCnt(,%edi,4)
+je .LC767
+movl -1648(%ebp),%edi
+leal (,%edi,4),%edi
+pushl ErrCnt(%edi)
+pushl msg.758(%edi)
+pushl $.LC769
+call printf
+addl $12,%esp
+.LC767:
+.LC764:
+incl -1648(%ebp)
+cmpl $4,-1648(%ebp)
+jl .LC763
+pushl $.LC45
+call printf
+addl $4,%esp
+movl ErrCnt,%edi
+movl ErrCnt+4,%esi
+leal (%esi,%edi),%edi
+movl ErrCnt+8,%esi
+leal (%esi,%edi),%edi
+movl ErrCnt+12,%esi
+leal (%esi,%edi),%edi
+cmpl $0,%edi
+jle .LC770
+movl ErrCnt,%edi
+movl ErrCnt+4,%esi
+leal (%esi,%edi),%edi
+movl ErrCnt+8,%esi
+leal (%esi,%edi),%edi
+cmpl $0,%edi
+jne .LC775
+cmpl $0,ErrCnt+12
+jle .LC775
+pushl $.LC780
+call printf
+addl $4,%esp
+pushl $.LC781
+call printf
+addl $4,%esp
+.LC775:
+movl ErrCnt,%edi
+movl ErrCnt+4,%esi
+leal (%esi,%edi),%edi
+cmpl $0,%edi
+jne .LC782
+cmpl $0,ErrCnt+8
+jle .LC782
+pushl $.LC786
+call printf
+addl $4,%esp
+pushl $.LC787
+call printf
+addl $4,%esp
+.LC782:
+movl ErrCnt,%edi
+movl ErrCnt+4,%esi
+leal (%esi,%edi),%edi
+cmpl $0,%edi
+jle .LC788
+pushl $.LC791
+call printf
+addl $4,%esp
+pushl $.LC792
+call printf
+addl $4,%esp
+.LC788:
+cmpl $0,ErrCnt
+jle .LC771
+pushl $.LC795
+call printf
+addl $4,%esp
+pushl $.LC796
+call printf
+addl $4,%esp
+jmp .LC771
+.LC770:
+pushl $.LC797
+call printf
+addl $4,%esp
+cmpl $1,RMult
+jne .LC802
+cmpl $1,RDiv
+jne .LC802
+cmpl $1,RAddSub
+jne .LC802
+cmpl $1,RSqrt
+je .LC798
+.LC802:
+pushl $.LC803
+call printf
+addl $4,%esp
+jmp .LC799
+.LC798:
+fldl One
+fcompl StickyBit
+fstsw %ax
+sahf
+ja .LC804
+fldl Radix
+fsubl Two
+fldl Radix
+fsubl Nine
+fsubl One
+fmulp %st(1),%st
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC804
+pushl $.LC806
+call printf
+addl $4,%esp
+pushl $.LC807
+call printf
+addl $4,%esp
+fldl Two
+fcompl Radix
+fstsw %ax
+sahf
+jne .LC808
+fldl Precision
+fldl Four
+fmull Three
+fmull Two
+fsubp %st(1),%st
+fldl Precision
+fsubl TwentySeven
+fsubl TwentySeven
+faddl One
+fmulp %st(1),%st
+fldl Zero
+fcompp
+fstsw %ax
+sahf
+jne .LC808
+pushl $.LC810
+call printf
+addl $4,%esp
+jmp .LC809
+.LC808:
+pushl $.LC811
+call printf
+addl $4,%esp
+.LC809:
+cmpl $0,IEEE
+je .LC812
+pushl $.LC814
+call printf
+addl $4,%esp
+jmp .LC813
+.LC812:
+pushl $.LC815
+call printf
+addl $4,%esp
+pushl $.LC816
+call printf
+addl $4,%esp
+.LC813:
+.LC804:
+pushl $.LC817
+call printf
+addl $4,%esp
+.LC799:
+.LC771:
+cmpl $0,fpecount
+je .LC818
+pushl fpecount
+pushl $.LC820
+call printf
+addl $8,%esp
+.LC818:
+pushl $.LC821
+call printf
+addl $4,%esp
+movl $0,%eax
+.LC7:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf822:
+.size main,.Lf822-main
+.globl Sign
+.align 16
+.type Sign,@function
+Sign:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $8,%esp
+fldl .LC8
+fcompl 20(%ebp)
+fstsw %ax
+sahf
+ja .LC825
+fldl .LC9
+fstpl -8(%ebp)
+jmp .LC826
+.LC825:
+fldl .LC827
+fstpl -8(%ebp)
+.LC826:
+fldl -8(%ebp)
+.LC823:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf828:
+.size Sign,.Lf828-Sign
+.globl Pause
+.align 16
+.type Pause,@function
+Pause:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+pushl Milestone
+pushl $.LC830
+call printf
+addl $8,%esp
+pushl PageNo
+pushl $.LC831
+call printf
+addl $8,%esp
+incl Milestone
+incl PageNo
+movl $0,%eax
+.LC829:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf832:
+.size Pause,.Lf832-Pause
+.globl TstCond
+.align 16
+.type TstCond,@function
+TstCond:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+cmpl $0,24(%ebp)
+jne .LC834
+pushl 28(%ebp)
+pushl 20(%ebp)
+call BadCond
+addl $8,%esp
+pushl $.LC814
+call printf
+addl $4,%esp
+.LC834:
+movl $0,%eax
+.LC833:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf836:
+.size TstCond,.Lf836-TstCond
+.data
+.align 4
+.type msg.838,@object
+msg.838:
+.long .LC839
+.long .LC840
+.long .LC841
+.long .LC842
+.size msg.838,16
+.globl BadCond
+.text
+.align 16
+.type BadCond,@function
+BadCond:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl 20(%ebp),%edi
+leal ErrCnt(,%edi,4),%edi
+incl (,%edi)
+pushl 24(%ebp)
+movl 20(%ebp),%edi
+pushl msg.838(,%edi,4)
+pushl $.LC843
+call printf
+addl $12,%esp
+movl $0,%eax
+.LC837:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf844:
+.size BadCond,.Lf844-BadCond
+.globl Random
+.align 16
+.type Random,@function
+Random:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $48,%esp
+fldl Random1
+faddl Random9
+fstpl -8(%ebp)
+fldl -8(%ebp)
+fmull -8(%ebp)
+fstpl -16(%ebp)
+fldl -16(%ebp)
+fmull -16(%ebp)
+fstpl -16(%ebp)
+fldl -8(%ebp)
+fmull -16(%ebp)
+fstpl -8(%ebp)
+fldl -8(%ebp)
+subl $8,%esp
+fstpl (%esp)
+call floor
+addl $8,%esp
+fstpl -48(%ebp)
+fldl -8(%ebp)
+fsubl -48(%ebp)
+fstpl -16(%ebp)
+fldl -16(%ebp)
+fldl .LC846
+fmull -8(%ebp)
+faddp %st(1),%st
+fstpl Random1
+fldl Random1
+.LC845:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf847:
+.size Random,.Lf847-Random
+.globl SqXMinX
+.align 16
+.type SqXMinX,@function
+SqXMinX:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $40,%esp
+fldl X
+fmull BInvrse
+fstpl -8(%ebp)
+fldl X
+fsubl -8(%ebp)
+fstpl -16(%ebp)
+fldl X
+fmull X
+subl $8,%esp
+fstpl (%esp)
+call sqrt
+addl $8,%esp
+fstpl -32(%ebp)
+fldl -32(%ebp)
+fsubl -8(%ebp)
+fsubl -16(%ebp)
+fdivl OneUlp
+fstpl SqEr
+fldl Zero
+fcompl SqEr
+fstsw %ax
+sahf
+je .LC849
+fldl MinSqEr
+fcompl SqEr
+fstsw %ax
+sahf
+jbe .LC851
+fldl SqEr
+fstpl MinSqEr
+.LC851:
+fldl MaxSqEr
+fcompl SqEr
+fstsw %ax
+sahf
+jae .LC853
+fldl SqEr
+fstpl MaxSqEr
+.LC853:
+fldl J
+faddl .LC9
+fstpl J
+pushl $.LC45
+pushl 20(%ebp)
+call BadCond
+addl $8,%esp
+fldl OneUlp
+fmull SqEr
+subl $8,%esp
+fstpl (%esp)
+fldl X
+subl $8,%esp
+fstpl (%esp)
+fldl X
+fmull X
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC855
+call printf
+addl $28,%esp
+pushl $.LC856
+call printf
+addl $4,%esp
+.LC849:
+movl $0,%eax
+.LC848:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf857:
+.size SqXMinX,.Lf857-SqXMinX
+.globl NewD
+.align 16
+.type NewD,@function
+NewD:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $40,%esp
+fldl Z1
+fmull Q
+fstpl X
+fldl Half
+fldl X
+fdivl Radix
+fsubp %st(1),%st
+subl $8,%esp
+fstpl (%esp)
+call floor
+addl $8,%esp
+fstpl -8(%ebp)
+fldl -8(%ebp)
+fmull Radix
+faddl X
+fstpl X
+fldl X
+fstpl -24(%ebp)
+fldl Z
+fstpl -32(%ebp)
+fldl Q
+fldl -24(%ebp)
+fmull -32(%ebp)
+fsubp %st(1),%st
+fdivl Radix
+fldl -24(%ebp)
+fmull -24(%ebp)
+fldl D
+fdivl Radix
+fmulp %st(1),%st
+faddp %st(1),%st
+fstpl Q
+fldl -32(%ebp)
+fldl Two
+fmull -24(%ebp)
+fmull D
+fsubp %st(1),%st
+fstpl Z
+fldl Zero
+fcompl Z
+fstsw %ax
+sahf
+jb .LC859
+fldl Z
+fchs
+fstpl Z
+fldl Z1
+fchs
+fstpl Z1
+.LC859:
+fldl Radix
+fmull D
+fstpl D
+movl $0,%eax
+.LC858:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf861:
+.size NewD,.Lf861-NewD
+.globl SR3750
+.align 16
+.type SR3750,@function
+SR3750:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $64,%esp
+fldl X
+fsubl Radix
+fldl Z2
+fsubl Radix
+fcompp
+fstsw %ax
+sahf
+ja .LC863
+fldl X
+fsubl Z2
+fldl W
+fsubl Z2
+fcompp
+fstsw %ax
+sahf
+jb .LC863
+incl I
+fldl X
+fmull D
+subl $8,%esp
+fstpl (%esp)
+call sqrt
+addl $8,%esp
+fstpl -32(%ebp)
+fldl -32(%ebp)
+fstpl X2
+fldl X2
+fsubl Z2
+fldl Y
+fsubl Z2
+fsubp %st(1),%st
+fstpl Y2
+fldl X8
+fldl Y
+fsubl Half
+fdivp %st(1),%st
+fstpl X2
+fldl X2
+fstpl -64(%ebp)
+fldl -64(%ebp)
+fldl Half
+fmull -64(%ebp)
+fmull -64(%ebp)
+fsubp %st(1),%st
+fstpl X2
+fldl Y2
+faddl Half
+fldl Half
+fsubl X2
+faddp %st(1),%st
+fstpl SqEr
+fldl MinSqEr
+fcompl SqEr
+fstsw %ax
+sahf
+jbe .LC865
+fldl SqEr
+fstpl MinSqEr
+.LC865:
+fldl Y2
+fsubl X2
+fstpl SqEr
+fldl MaxSqEr
+fcompl SqEr
+fstsw %ax
+sahf
+jae .LC867
+fldl SqEr
+fstpl MaxSqEr
+.LC867:
+.LC863:
+movl $0,%eax
+.LC862:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf869:
+.size SR3750,.Lf869-SR3750
+.globl IsYeqX
+.align 16
+.type IsYeqX,@function
+IsYeqX:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $8,%esp
+fldl X
+fcompl Y
+fstsw %ax
+sahf
+je .LC871
+cmpl $0,N
+jg .LC873
+fldl Zero
+fcompl Z
+fstsw %ax
+sahf
+jne .LC875
+fldl Zero
+fcompl Q
+fstsw %ax
+sahf
+jb .LC875
+pushl $.LC877
+call printf
+addl $4,%esp
+jmp .LC876
+.LC875:
+pushl $.LC878
+pushl $2
+call BadCond
+addl $8,%esp
+.LC876:
+fldl Q
+subl $8,%esp
+fstpl (%esp)
+fldl Z
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC879
+call printf
+addl $20,%esp
+fldl Y
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC880
+call printf
+addl $12,%esp
+fldl X
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC881
+call printf
+addl $12,%esp
+fldl Y
+fsubl X
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC882
+call printf
+addl $12,%esp
+.LC873:
+incl N
+.LC871:
+movl $0,%eax
+.LC870:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf883:
+.size IsYeqX,.Lf883-IsYeqX
+.globl SR3980
+.align 16
+.type SR3980,@function
+SR3980:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $8,%esp
+.LC885:
+fildl I
+fstpl Q
+fldl Q
+subl $8,%esp
+fstpl (%esp)
+fldl Z
+subl $8,%esp
+fstpl (%esp)
+call pow
+addl $16,%esp
+fstpl -8(%ebp)
+fldl -8(%ebp)
+fstpl Y
+call IsYeqX
+movl I,%edi
+leal 1(%edi),%edi
+movl %edi,I
+cmpl M,%edi
+jle .LC888
+jmp .LC887
+.LC888:
+fldl Z
+fmull X
+fstpl X
+.LC886:
+fldl W
+fcompl X
+fstsw %ax
+sahf
+ja .LC885
+.LC887:
+movl $0,%eax
+.LC884:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf890:
+.size SR3980,.Lf890-SR3980
+.globl PrintIfNPositive
+.align 16
+.type PrintIfNPositive,@function
+PrintIfNPositive:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+cmpl $0,N
+jle .LC892
+pushl N
+pushl $.LC894
+call printf
+addl $8,%esp
+.LC892:
+movl $0,%eax
+.LC891:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf895:
+.size PrintIfNPositive,.Lf895-PrintIfNPositive
+.globl TstPtUf
+.align 16
+.type TstPtUf,@function
+TstPtUf:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $48,%esp
+movl $0,N
+fldl Zero
+fcompl Z
+fstsw %ax
+sahf
+je .LC897
+pushl $.LC899
+call printf
+addl $4,%esp
+pushl $.LC900
+call printf
+addl $4,%esp
+leal sigfpe,%edi
+movl %edi,sigsave
+pushl $ovfl_buf
+call __setjmp
+addl $4,%esp
+cmpl $0,%eax
+je .LC901
+jmp .LC903
+.LC901:
+fldl Z
+faddl Z
+fdivl Z
+fstpl Q9
+fldl Q9
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC904
+call printf
+addl $12,%esp
+fldl Q9
+fsubl Two
+subl $8,%esp
+fstpl (%esp)
+call fabs
+addl $8,%esp
+fstpl -16(%ebp)
+fldl Radix
+fmull U2
+fcompl -16(%ebp)
+fstsw %ax
+sahf
+jbe .LC905
+pushl $.LC907
+call printf
+addl $4,%esp
+pushl $.LC908
+call printf
+addl $4,%esp
+jmp .LC906
+.LC905:
+fldl One
+fcompl Q9
+fstsw %ax
+sahf
+ja .LC911
+fldl Two
+fcompl Q9
+fstsw %ax
+sahf
+jae .LC909
+.LC911:
+.LC903:
+movl $1,N
+movl ErrCnt+4,%edi
+leal 1(%edi),%edi
+movl %edi,ErrCnt+4
+pushl $.LC914
+call printf
+addl $4,%esp
+jmp .LC910
+.LC909:
+movl $1,N
+movl ErrCnt+8,%edi
+leal 1(%edi),%edi
+movl %edi,ErrCnt+8
+pushl $.LC917
+call printf
+addl $4,%esp
+.LC910:
+.LC906:
+movl $0,sigsave
+fldl Z
+fmull One
+fstpl V9
+fldl V9
+fstpl Random1
+fldl One
+fmull Z
+fstpl V9
+fldl V9
+fstpl Random2
+fldl Z
+fdivl One
+fstpl V9
+fldl Random1
+fcompl Z
+fstsw %ax
+sahf
+jne .LC918
+fldl Random2
+fcompl Z
+fstsw %ax
+sahf
+jne .LC918
+fldl V9
+fcompl Z
+fstsw %ax
+sahf
+jne .LC918
+cmpl $0,N
+jle .LC919
+call Pause
+jmp .LC919
+.LC918:
+movl $1,N
+pushl $.LC922
+pushl $2
+call BadCond
+addl $8,%esp
+fldl Z
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC923
+call printf
+addl $12,%esp
+fldl Random1
+fcompl Z
+fstsw %ax
+sahf
+je .LC924
+fldl Random1
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC926
+call printf
+addl $12,%esp
+.LC924:
+fldl Random2
+fcompl Z
+fstsw %ax
+sahf
+je .LC927
+fldl Random1
+fcompl Random2
+fstsw %ax
+sahf
+je .LC927
+fldl Random2
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC929
+call printf
+addl $12,%esp
+.LC927:
+fldl V9
+fcompl Z
+fstsw %ax
+sahf
+je .LC930
+fldl V9
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC932
+call printf
+addl $12,%esp
+.LC930:
+fldl Random1
+fcompl Random2
+fstsw %ax
+sahf
+je .LC933
+movl ErrCnt+8,%edi
+leal 1(%edi),%edi
+movl %edi,ErrCnt+8
+pushl $.LC937
+pushl $2
+call BadCond
+addl $8,%esp
+fldl Random2
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC938
+call printf
+addl $12,%esp
+fldl Random1
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC939
+call printf
+addl $12,%esp
+.LC933:
+call Pause
+.LC919:
+.LC897:
+movl $0,%eax
+.LC896:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf940:
+.size TstPtUf,.Lf940-TstPtUf
+.globl notify
+.align 16
+.type notify,@function
+notify:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+pushl 20(%ebp)
+pushl $.LC942
+call printf
+addl $8,%esp
+pushl $.LC943
+call printf
+addl $4,%esp
+movl $0,%eax
+.LC941:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf944:
+.size notify,.Lf944-notify
+.globl msglist
+.align 16
+.type msglist,@function
+msglist:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+jmp .LC947
+.LC946:
+movl 20(%ebp),%edi
+leal 4(%edi),%esi
+movl %esi,20(%ebp)
+pushl (,%edi)
+pushl $.LC949
+call printf
+addl $8,%esp
+.LC947:
+movl 20(%ebp),%edi
+movl (,%edi),%edi
+cmpl $0,%edi
+jne .LC946
+movl $0,%eax
+.LC945:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf950:
+.size msglist,.Lf950-msglist
+.data
+.align 4
+.type instr.952,@object
+instr.952:
+.long .LC953
+.long .LC954
+.long .LC955
+.long .LC956
+.long .LC957
+.long .LC958
+.long .LC959
+.long .LC960
+.long .LC961
+.long 0
+.size instr.952,40
+.globl Instructions
+.text
+.align 16
+.type Instructions,@function
+Instructions:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+pushl $instr.952
+call msglist
+addl $4,%esp
+movl $0,%eax
+.LC951:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf962:
+.size Instructions,.Lf962-Instructions
+.data
+.align 4
+.type head.964,@object
+head.964:
+.long .LC965
+.long .LC966
+.long .LC967
+.long .LC968
+.long .LC969
+.long .LC970
+.long .LC971
+.long .LC972
+.long .LC973
+.long .LC974
+.long .LC975
+.long .LC976
+.long .LC977
+.long .LC978
+.long 0
+.size head.964,60
+.globl Heading
+.text
+.align 16
+.type Heading,@function
+Heading:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+pushl $head.964
+call msglist
+addl $4,%esp
+movl $0,%eax
+.LC963:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf979:
+.size Heading,.Lf979-Heading
+.data
+.align 4
+.type chars.981,@object
+chars.981:
+.long .LC982
+.long .LC983
+.long .LC984
+.long .LC985
+.long .LC986
+.long .LC987
+.long .LC988
+.long .LC989
+.long .LC990
+.long .LC991
+.long .LC992
+.long .LC993
+.long .LC994
+.long .LC995
+.long .LC996
+.long .LC997
+.long .LC998
+.long .LC999
+.long .LC1000
+.long 0
+.size chars.981,80
+.globl Characteristics
+.text
+.align 16
+.type Characteristics,@function
+Characteristics:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+pushl $chars.981
+call msglist
+addl $4,%esp
+movl $0,%eax
+.LC980:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf1001:
+.size Characteristics,.Lf1001-Characteristics
+.data
+.align 4
+.type hist.1003,@object
+hist.1003:
+.long .LC1004
+.long .LC1005
+.long .LC1006
+.long .LC1007
+.long .LC1008
+.long .LC1009
+.long .LC1010
+.long .LC1011
+.long .LC1012
+.long .LC1013
+.long .LC1014
+.long .LC1015
+.long .LC1016
+.long .LC1017
+.long .LC1018
+.long .LC1019
+.long .LC1020
+.long 0
+.size hist.1003,72
+.globl History
+.text
+.align 16
+.type History,@function
+History:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+pushl $hist.1003
+call msglist
+addl $4,%esp
+movl $0,%eax
+.LC1002:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf1021:
+.size History,.Lf1021-History
+.globl pow
+.align 16
+.type pow,@function
+pow:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $96,%esp
+movl $0,-20(%ebp)
+movl $0,-24(%ebp)
+fldl .LC8
+fcompl 28(%ebp)
+fstsw %ax
+sahf
+jne .LC1023
+fldl .LC9
+jmp .LC1022
+.LC1023:
+fldl .LC1028
+fcompl 28(%ebp)
+fstsw %ax
+sahf
+ja .LC1027
+fldl .LC1029
+fcompl 28(%ebp)
+fstsw %ax
+sahf
+jae .LC1025
+.LC1027:
+fldl .LC827
+fcompl 20(%ebp)
+fstsw %ax
+sahf
+je .LC1025
+fldl 20(%ebp)
+subl $8,%esp
+fstpl (%esp)
+call log
+addl $8,%esp
+fstpl -48(%ebp)
+fldl 28(%ebp)
+fmull -48(%ebp)
+subl $8,%esp
+fstpl (%esp)
+call exp
+addl $8,%esp
+fstpl -56(%ebp)
+fldl -56(%ebp)
+jmp .LC1022
+.LC1025:
+fldl .LC8
+fcompl 28(%ebp)
+fstsw %ax
+sahf
+jbe .LC1030
+fldl 28(%ebp)
+fchs
+fstpl 28(%ebp)
+movl $1,-24(%ebp)
+.LC1030:
+leal -32(%ebp),%edi
+pushl %edi
+fldl 28(%ebp)
+subl $8,%esp
+fstpl (%esp)
+call modf
+addl $12,%esp
+fstpl -64(%ebp)
+fldl -64(%ebp)
+fstpl 28(%ebp)
+fldl .LC8
+fcompl 28(%ebp)
+fstsw %ax
+sahf
+je .LC1032
+fldl 20(%ebp)
+subl $8,%esp
+fstpl (%esp)
+call log
+addl $8,%esp
+fstpl -72(%ebp)
+fldl 28(%ebp)
+fmull -72(%ebp)
+subl $8,%esp
+fstpl (%esp)
+call exp
+addl $8,%esp
+fstpl -80(%ebp)
+fldl -80(%ebp)
+fstpl -16(%ebp)
+jmp .LC1033
+.LC1032:
+fldl .LC9
+fstpl -16(%ebp)
+.LC1033:
+leal -8(%ebp),%edi
+pushl %edi
+fldl 20(%ebp)
+subl $8,%esp
+fstpl (%esp)
+call frexp
+addl $12,%esp
+fstpl -88(%ebp)
+fldl -88(%ebp)
+fstpl 20(%ebp)
+fldl -32(%ebp)
+subl $4,%esp
+fistpl 0(%esp)
+popl %eax
+movl %eax,-4(%ebp)
+cmpl $0,%eax
+je .LC1034
+.LC1036:
+movl -4(%ebp),%edi
+andl $1,%edi
+cmpl $0,%edi
+je .LC1040
+fldl -16(%ebp)
+fmull 20(%ebp)
+fstpl -16(%ebp)
+movl -8(%ebp),%edi
+addl %edi,-20(%ebp)
+.LC1040:
+movl -4(%ebp),%edi
+sarl $1,%edi
+movl %edi,-4(%ebp)
+cmpl $0,%edi
+jne .LC1042
+jmp .LC1038
+.LC1042:
+fldl 20(%ebp)
+fmull 20(%ebp)
+fstpl 20(%ebp)
+sall $1,-8(%ebp)
+fldl .LC1046
+fcompl 20(%ebp)
+fstsw %ax
+sahf
+jbe .LC1036
+fldl .LC1047
+fmull 20(%ebp)
+fstpl 20(%ebp)
+decl -8(%ebp)
+jmp .LC1036
+.LC1038:
+.LC1034:
+cmpl $0,-24(%ebp)
+je .LC1048
+fldl .LC9
+fdivl -16(%ebp)
+fstpl -16(%ebp)
+negl -20(%ebp)
+.LC1048:
+pushl -20(%ebp)
+fldl -16(%ebp)
+subl $8,%esp
+fstpl (%esp)
+call ldexp
+addl $12,%esp
+fstpl -96(%ebp)
+fldl -96(%ebp)
+.LC1022:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf1050:
+.size pow,.Lf1050-pow
+.bss
+.globl UfNGrad
+.align 4
+.type UfNGrad,@object
+.size UfNGrad,4
+.comm UfNGrad,4
+.globl SqRWrng
+.align 4
+.type SqRWrng,@object
+.size SqRWrng,4
+.comm SqRWrng,4
+.globl IEEE
+.align 4
+.type IEEE,@object
+.size IEEE,4
+.comm IEEE,4
+.globl Anomaly
+.align 4
+.type Anomaly,@object
+.size Anomaly,4
+.comm Anomaly,4
+.globl Monot
+.align 4
+.type Monot,@object
+.size Monot,4
+.comm Monot,4
+.globl NotMonot
+.align 4
+.type NotMonot,@object
+.size NotMonot,4
+.comm NotMonot,4
+.globl Done
+.align 4
+.type Done,@object
+.size Done,4
+.comm Done,4
+.globl Break
+.align 4
+.type Break,@object
+.size Break,4
+.comm Break,4
+.globl RSqrt
+.align 4
+.type RSqrt,@object
+.size RSqrt,4
+.comm RSqrt,4
+.globl RAddSub
+.align 4
+.type RAddSub,@object
+.size RAddSub,4
+.comm RAddSub,4
+.globl RDiv
+.align 4
+.type RDiv,@object
+.size RDiv,4
+.comm RDiv,4
+.globl RMult
+.align 4
+.type RMult,@object
+.size RMult,4
+.comm RMult,4
+.globl GAddSub
+.align 4
+.type GAddSub,@object
+.size GAddSub,4
+.comm GAddSub,4
+.globl GDiv
+.align 4
+.type GDiv,@object
+.size GDiv,4
+.comm GDiv,4
+.globl GMult
+.align 4
+.type GMult,@object
+.size GMult,4
+.comm GMult,4
+.globl N1
+.align 4
+.type N1,@object
+.size N1,4
+.comm N1,4
+.globl N
+.align 4
+.type N,@object
+.size N,4
+.comm N,4
+.globl M
+.align 4
+.type M,@object
+.size M,4
+.comm M,4
+.globl PageNo
+.align 4
+.type PageNo,@object
+.size PageNo,4
+.comm PageNo,4
+.globl Milestone
+.align 4
+.type Milestone,@object
+.size Milestone,4
+.comm Milestone,4
+.globl fpecount
+.align 4
+.type fpecount,@object
+.size fpecount,4
+.comm fpecount,4
+.globl ErrCnt
+.align 4
+.type ErrCnt,@object
+.size ErrCnt,16
+.comm ErrCnt,16
+.globl Z9
+.align 4
+.type Z9,@object
+.size Z9,8
+.comm Z9,8
+.globl Z2
+.align 4
+.type Z2,@object
+.size Z2,8
+.comm Z2,8
+.globl Z1
+.align 4
+.type Z1,@object
+.size Z1,8
+.comm Z1,8
+.globl PseudoZero
+.align 4
+.type PseudoZero,@object
+.size PseudoZero,8
+.comm PseudoZero,8
+.globl Z
+.align 4
+.type Z,@object
+.size Z,8
+.comm Z,8
+.globl Random2
+.align 4
+.type Random2,@object
+.size Random2,8
+.comm Random2,8
+.globl Y2
+.align 4
+.type Y2,@object
+.size Y2,8
+.comm Y2,8
+.globl Y1
+.align 4
+.type Y1,@object
+.size Y1,8
+.comm Y1,8
+.globl Y
+.align 4
+.type Y,@object
+.size Y,8
+.comm Y,8
+.globl Random1
+.align 4
+.type Random1,@object
+.size Random1,8
+.comm Random1,8
+.globl X8
+.align 4
+.type X8,@object
+.size X8,8
+.comm X8,8
+.globl X2
+.align 4
+.type X2,@object
+.size X2,8
+.comm X2,8
+.globl X1
+.align 4
+.type X1,@object
+.size X1,8
+.comm X1,8
+.globl X
+.align 4
+.type X,@object
+.size X,8
+.comm X,8
+.globl W
+.align 4
+.type W,@object
+.size W,8
+.comm W,8
+.globl V9
+.align 4
+.type V9,@object
+.size V9,8
+.comm V9,8
+.globl V0
+.align 4
+.type V0,@object
+.size V0,8
+.comm V0,8
+.globl V
+.align 4
+.type V,@object
+.size V,8
+.comm V,8
+.globl U2
+.align 4
+.type U2,@object
+.size U2,8
+.comm U2,8
+.globl U1
+.align 4
+.type U1,@object
+.size U1,8
+.comm U1,8
+.globl UfThold
+.align 4
+.type UfThold,@object
+.size UfThold,8
+.comm UfThold,8
+.globl OneUlp
+.align 4
+.type OneUlp,@object
+.size OneUlp,8
+.comm OneUlp,8
+.globl S
+.align 4
+.type S,@object
+.size S,8
+.comm S,8
+.globl Underflow
+.align 4
+.type Underflow,@object
+.size Underflow,8
+.comm Underflow,8
+.globl T
+.align 4
+.type T,@object
+.size T,8
+.comm T,8
+.globl Random9
+.align 4
+.type Random9,@object
+.size Random9,8
+.comm Random9,8
+.globl R
+.align 4
+.type R,@object
+.size R,8
+.comm R,8
+.globl Q9
+.align 4
+.type Q9,@object
+.size Q9,8
+.comm Q9,8
+.globl Q
+.align 4
+.type Q,@object
+.size Q,8
+.comm Q,8
+.globl Precision
+.align 4
+.type Precision,@object
+.size Precision,8
+.comm Precision,8
+.globl MyZero
+.align 4
+.type MyZero,@object
+.size MyZero,8
+.comm MyZero,8
+.globl J
+.align 4
+.type J,@object
+.size J,8
+.comm J,8
+.globl StickyBit
+.align 4
+.type StickyBit,@object
+.size StickyBit,8
+.comm StickyBit,8
+.globl I
+.align 4
+.type I,@object
+.size I,4
+.comm I,4
+.globl HInvrse
+.align 4
+.type HInvrse,@object
+.size HInvrse,8
+.comm HInvrse,8
+.globl H
+.align 4
+.type H,@object
+.size H,8
+.comm H,8
+.globl F9
+.align 4
+.type F9,@object
+.size F9,8
+.comm F9,8
+.globl F6
+.align 4
+.type F6,@object
+.size F6,8
+.comm F6,8
+.globl Third
+.align 4
+.type Third,@object
+.size Third,8
+.comm Third,8
+.globl E9
+.align 4
+.type E9,@object
+.size E9,8
+.comm E9,8
+.globl MaxSqEr
+.align 4
+.type MaxSqEr,@object
+.size MaxSqEr,8
+.comm MaxSqEr,8
+.globl SqEr
+.align 4
+.type SqEr,@object
+.size SqEr,8
+.comm SqEr,8
+.globl MinSqEr
+.align 4
+.type MinSqEr,@object
+.size MinSqEr,8
+.comm MinSqEr,8
+.globl E3
+.align 4
+.type E3,@object
+.size E3,8
+.comm E3,8
+.globl Exp2
+.align 4
+.type Exp2,@object
+.size Exp2,8
+.comm Exp2,8
+.globl E1
+.align 4
+.type E1,@object
+.size E1,8
+.comm E1,8
+.globl E0
+.align 4
+.type E0,@object
+.size E0,8
+.comm E0,8
+.globl FourD
+.align 4
+.type FourD,@object
+.size FourD,8
+.comm FourD,8
+.globl D
+.align 4
+.type D,@object
+.size D,8
+.comm D,8
+.globl CInvrse
+.align 4
+.type CInvrse,@object
+.size CInvrse,8
+.comm CInvrse,8
+.globl C
+.align 4
+.type C,@object
+.size C,8
+.comm C,8
+.globl A1
+.align 4
+.type A1,@object
+.size A1,8
+.comm A1,8
+.globl AInvrse
+.align 4
+.type AInvrse,@object
+.size AInvrse,8
+.comm AInvrse,8
+.globl ch
+.align 1
+.type ch,@object
+.size ch,8
+.comm ch,8
+.globl Indx
+.align 4
+.type Indx,@object
+.size Indx,4
+.comm Indx,4
+.globl BMinusU2
+.align 4
+.type BMinusU2,@object
+.size BMinusU2,8
+.comm BMinusU2,8
+.globl RadixD2
+.align 4
+.type RadixD2,@object
+.size RadixD2,8
+.comm RadixD2,8
+.globl BInvrse
+.align 4
+.type BInvrse,@object
+.size BInvrse,8
+.comm BInvrse,8
+.globl Radix
+.align 4
+.type Radix,@object
+.size Radix,8
+.comm Radix,8
+.globl sigsave
+.align 4
+.type sigsave,@object
+.size sigsave,4
+.comm sigsave,4
+.globl ovfl_buf
+.align 4
+.type ovfl_buf,@object
+.size ovfl_buf,24
+.comm ovfl_buf,24
+.data
+.align 4
+.LC1047:
+.long 0
+.long 1073741824
+.align 4
+.LC1046:
+.long 0
+.long 1071644672
+.align 4
+.LC1029:
+.long 0
+.long 1083256832
+.align 4
+.LC1028:
+.long 0
+.long -1064226816
+.align 1
+.LC1020:
+.byte 115
+.byte 101
+.byte 101
+.byte 32
+.byte 115
+.byte 111
+.byte 117
+.byte 114
+.byte 99
+.byte 101
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 109
+.byte 111
+.byte 114
+.byte 101
+.byte 32
+.byte 104
+.byte 105
+.byte 115
+.byte 116
+.byte 111
+.byte 114
+.byte 121
+.byte 46
+.byte 0
+.align 1
+.LC1019:
+.byte 66
+.byte 65
+.byte 83
+.byte 73
+.byte 67
+.byte 32
+.byte 118
+.byte 101
+.byte 114
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 40
+.byte 67
+.byte 41
+.byte 32
+.byte 49
+.byte 57
+.byte 56
+.byte 51
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 80
+.byte 114
+.byte 111
+.byte 102
+.byte 46
+.byte 32
+.byte 87
+.byte 46
+.byte 32
+.byte 77
+.byte 46
+.byte 32
+.byte 75
+.byte 97
+.byte 104
+.byte 97
+.byte 110
+.byte 59
+.byte 0
+.align 1
+.LC1018:
+.byte 97
+.byte 115
+.byte 32
+.byte 117
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 99
+.byte 101
+.byte 114
+.byte 116
+.byte 97
+.byte 105
+.byte 110
+.byte 32
+.byte 101
+.byte 97
+.byte 114
+.byte 108
+.byte 121
+.byte 32
+.byte 87
+.byte 65
+.byte 78
+.byte 71
+.byte 32
+.byte 109
+.byte 97
+.byte 99
+.byte 104
+.byte 105
+.byte 110
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC1017:
+.byte 102
+.byte 108
+.byte 111
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 45
+.byte 112
+.byte 111
+.byte 105
+.byte 110
+.byte 116
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 115
+.byte 44
+.byte 32
+.byte 98
+.byte 117
+.byte 116
+.byte 32
+.byte 97
+.byte 108
+.byte 115
+.byte 111
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 111
+.byte 119
+.byte 115
+.byte 32
+.byte 108
+.byte 111
+.byte 103
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 105
+.byte 99
+.byte 32
+.byte 101
+.byte 110
+.byte 99
+.byte 111
+.byte 100
+.byte 105
+.byte 110
+.byte 103
+.byte 0
+.align 1
+.LC1016:
+.byte 10
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 98
+.byte 97
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 117
+.byte 112
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 118
+.byte 101
+.byte 110
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 97
+.byte 108
+.byte 32
+.byte 114
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 114
+.byte 101
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 101
+.byte 110
+.byte 116
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 0
+.align 1
+.LC1015:
+.byte 111
+.byte 102
+.byte 32
+.byte 112
+.byte 97
+.byte 116
+.byte 104
+.byte 111
+.byte 108
+.byte 111
+.byte 103
+.byte 105
+.byte 101
+.byte 115
+.byte 44
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 115
+.byte 97
+.byte 121
+.byte 32
+.byte 104
+.byte 111
+.byte 119
+.byte 32
+.byte 119
+.byte 101
+.byte 108
+.byte 108
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 109
+.byte 112
+.byte 108
+.byte 101
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 101
+.byte 100
+.byte 46
+.byte 0
+.align 1
+.LC1014:
+.byte 111
+.byte 102
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 44
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 116
+.byte 114
+.byte 105
+.byte 101
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 111
+.byte 112
+.byte 101
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 97
+.byte 32
+.byte 119
+.byte 105
+.byte 100
+.byte 101
+.byte 114
+.byte 32
+.byte 118
+.byte 97
+.byte 114
+.byte 105
+.byte 101
+.byte 116
+.byte 121
+.byte 0
+.align 1
+.LC1013:
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 44
+.byte 32
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 114
+.byte 97
+.byte 110
+.byte 103
+.byte 101
+.byte 32
+.byte 40
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 47
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 115
+.byte 41
+.byte 0
+.align 1
+.LC1012:
+.byte 87
+.byte 46
+.byte 32
+.byte 74
+.byte 46
+.byte 32
+.byte 67
+.byte 111
+.byte 100
+.byte 121
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 87
+.byte 46
+.byte 32
+.byte 87
+.byte 97
+.byte 105
+.byte 116
+.byte 101
+.byte 46
+.byte 32
+.byte 65
+.byte 108
+.byte 116
+.byte 104
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 32
+.byte 98
+.byte 111
+.byte 116
+.byte 104
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 115
+.byte 32
+.byte 116
+.byte 114
+.byte 121
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 0
+.align 1
+.LC1011:
+.byte 98
+.byte 111
+.byte 111
+.byte 107
+.byte 32
+.byte 32
+.byte 96
+.byte 83
+.byte 111
+.byte 102
+.byte 116
+.byte 119
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 77
+.byte 97
+.byte 110
+.byte 117
+.byte 97
+.byte 108
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 69
+.byte 108
+.byte 101
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 97
+.byte 114
+.byte 121
+.byte 32
+.byte 70
+.byte 117
+.byte 110
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 39
+.byte 32
+.byte 40
+.byte 49
+.byte 57
+.byte 56
+.byte 48
+.byte 41
+.byte 32
+.byte 98
+.byte 121
+.byte 0
+.align 1
+.LC1010:
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 99
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 100
+.byte 32
+.byte 96
+.byte 77
+.byte 65
+.byte 67
+.byte 72
+.byte 65
+.byte 82
+.byte 39
+.byte 44
+.byte 32
+.byte 119
+.byte 104
+.byte 105
+.byte 99
+.byte 104
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 101
+.byte 110
+.byte 100
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 0
+.align 1
+.LC1009:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 99
+.byte 97
+.byte 112
+.byte 97
+.byte 98
+.byte 105
+.byte 108
+.byte 105
+.byte 116
+.byte 105
+.byte 101
+.byte 115
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 103
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 121
+.byte 111
+.byte 110
+.byte 100
+.byte 32
+.byte 97
+.byte 110
+.byte 32
+.byte 101
+.byte 97
+.byte 114
+.byte 108
+.byte 105
+.byte 101
+.byte 114
+.byte 0
+.align 1
+.LC1008:
+.byte 70
+.byte 97
+.byte 105
+.byte 108
+.byte 117
+.byte 114
+.byte 101
+.byte 115
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 115
+.byte 101
+.byte 113
+.byte 117
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC1007:
+.byte 32
+.byte 32
+.byte 32
+.byte 70
+.byte 65
+.byte 73
+.byte 76
+.byte 85
+.byte 82
+.byte 69
+.byte 115
+.byte 44
+.byte 32
+.byte 108
+.byte 105
+.byte 107
+.byte 101
+.byte 32
+.byte 50
+.byte 43
+.byte 50
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 53
+.byte 32
+.byte 46
+.byte 0
+.align 1
+.LC1006:
+.byte 32
+.byte 32
+.byte 32
+.byte 83
+.byte 101
+.byte 114
+.byte 105
+.byte 111
+.byte 117
+.byte 115
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 115
+.byte 44
+.byte 32
+.byte 108
+.byte 105
+.byte 107
+.byte 101
+.byte 32
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 97
+.byte 32
+.byte 103
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 44
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 0
+.align 1
+.LC1005:
+.byte 32
+.byte 32
+.byte 32
+.byte 70
+.byte 76
+.byte 65
+.byte 87
+.byte 115
+.byte 44
+.byte 32
+.byte 108
+.byte 105
+.byte 107
+.byte 101
+.byte 32
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 97
+.byte 32
+.byte 115
+.byte 116
+.byte 105
+.byte 99
+.byte 107
+.byte 121
+.byte 32
+.byte 98
+.byte 105
+.byte 116
+.byte 44
+.byte 0
+.align 1
+.LC1004:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 97
+.byte 116
+.byte 116
+.byte 101
+.byte 109
+.byte 112
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 114
+.byte 105
+.byte 109
+.byte 105
+.byte 110
+.byte 97
+.byte 116
+.byte 101
+.byte 32
+.byte 97
+.byte 109
+.byte 111
+.byte 110
+.byte 103
+.byte 0
+.align 1
+.LC1000:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 68
+.byte 101
+.byte 99
+.byte 105
+.byte 109
+.byte 97
+.byte 108
+.byte 45
+.byte 66
+.byte 105
+.byte 110
+.byte 97
+.byte 114
+.byte 121
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 118
+.byte 101
+.byte 114
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 78
+.byte 79
+.byte 84
+.byte 32
+.byte 89
+.byte 69
+.byte 84
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 97
+.byte 99
+.byte 99
+.byte 117
+.byte 114
+.byte 97
+.byte 99
+.byte 121
+.byte 46
+.byte 0
+.align 1
+.LC999:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 69
+.byte 120
+.byte 116
+.byte 114
+.byte 97
+.byte 45
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 101
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 101
+.byte 120
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 101
+.byte 118
+.byte 101
+.byte 97
+.byte 108
+.byte 101
+.byte 100
+.byte 32
+.byte 98
+.byte 117
+.byte 116
+.byte 32
+.byte 78
+.byte 79
+.byte 84
+.byte 32
+.byte 89
+.byte 69
+.byte 84
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 101
+.byte 100
+.byte 46
+.byte 0
+.align 1
+.LC998:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 83
+.byte 113
+.byte 114
+.byte 116
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 101
+.byte 100
+.byte 46
+.byte 32
+.byte 32
+.byte 89
+.byte 94
+.byte 88
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 101
+.byte 100
+.byte 46
+.byte 0
+.align 1
+.LC997:
+.byte 9
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 116
+.byte 97
+.byte 109
+.byte 105
+.byte 110
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 112
+.byte 115
+.byte 101
+.byte 117
+.byte 100
+.byte 111
+.byte 45
+.byte 122
+.byte 101
+.byte 114
+.byte 111
+.byte 115
+.byte 46
+.byte 0
+.align 1
+.LC996:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 99
+.byte 104
+.byte 101
+.byte 99
+.byte 107
+.byte 101
+.byte 100
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 115
+.byte 105
+.byte 115
+.byte 116
+.byte 101
+.byte 110
+.byte 99
+.byte 121
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 0
+.align 1
+.LC995:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 86
+.byte 48
+.byte 32
+.byte 32
+.byte 116
+.byte 101
+.byte 108
+.byte 108
+.byte 115
+.byte 44
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 108
+.byte 121
+.byte 44
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 32
+.byte 73
+.byte 110
+.byte 102
+.byte 105
+.byte 110
+.byte 105
+.byte 116
+.byte 121
+.byte 32
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 114
+.byte 101
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 101
+.byte 110
+.byte 116
+.byte 101
+.byte 100
+.byte 46
+.byte 0
+.align 1
+.LC994:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 86
+.byte 32
+.byte 61
+.byte 32
+.byte 97
+.byte 110
+.byte 32
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 44
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 108
+.byte 121
+.byte 46
+.byte 0
+.align 1
+.LC993:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 69
+.byte 48
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 80
+.byte 115
+.byte 101
+.byte 117
+.byte 100
+.byte 111
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 116
+.byte 101
+.byte 108
+.byte 108
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 97
+.byte 98
+.byte 114
+.byte 117
+.byte 112
+.byte 116
+.byte 44
+.byte 32
+.byte 103
+.byte 114
+.byte 97
+.byte 100
+.byte 117
+.byte 97
+.byte 108
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 102
+.byte 117
+.byte 122
+.byte 122
+.byte 121
+.byte 46
+.byte 0
+.align 1
+.LC992:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 84
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 61
+.byte 32
+.byte 97
+.byte 110
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 46
+.byte 0
+.align 1
+.LC991:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 87
+.byte 104
+.byte 101
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 97
+.byte 32
+.byte 83
+.byte 116
+.byte 105
+.byte 99
+.byte 107
+.byte 121
+.byte 32
+.byte 66
+.byte 105
+.byte 116
+.byte 32
+.byte 117
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 105
+.byte 110
+.byte 103
+.byte 46
+.byte 0
+.align 1
+.LC990:
+.byte 9
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 46
+.byte 44
+.byte 32
+.byte 68
+.byte 105
+.byte 118
+.byte 46
+.byte 44
+.byte 32
+.byte 65
+.byte 100
+.byte 100
+.byte 47
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 46
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 83
+.byte 113
+.byte 114
+.byte 116
+.byte 46
+.byte 0
+.align 1
+.LC989:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 87
+.byte 104
+.byte 101
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 44
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 100
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 115
+.byte 111
+.byte 109
+.byte 101
+.byte 116
+.byte 104
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 101
+.byte 108
+.byte 115
+.byte 101
+.byte 0
+.align 1
+.LC988:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 65
+.byte 100
+.byte 101
+.byte 113
+.byte 117
+.byte 97
+.byte 99
+.byte 121
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 103
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 46
+.byte 44
+.byte 32
+.byte 68
+.byte 105
+.byte 118
+.byte 46
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 46
+.byte 0
+.align 1
+.LC987:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 85
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 49
+.byte 47
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 94
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 61
+.byte 32
+.byte 79
+.byte 110
+.byte 101
+.byte 32
+.byte 85
+.byte 108
+.byte 112
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 108
+.byte 105
+.byte 116
+.byte 116
+.byte 108
+.byte 101
+.byte 32
+.byte 108
+.byte 101
+.byte 115
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 110
+.byte 32
+.byte 49
+.byte 46
+.byte 48
+.byte 32
+.byte 46
+.byte 0
+.align 1
+.LC986:
+.byte 9
+.byte 40
+.byte 79
+.byte 110
+.byte 101
+.byte 85
+.byte 108
+.byte 112
+.byte 110
+.byte 105
+.byte 116
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 76
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 80
+.byte 108
+.byte 97
+.byte 99
+.byte 101
+.byte 41
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 49
+.byte 46
+.byte 48
+.byte 48
+.byte 48
+.byte 120
+.byte 120
+.byte 120
+.byte 32
+.byte 46
+.byte 0
+.align 1
+.LC985:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 85
+.byte 50
+.byte 32
+.byte 61
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 47
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 94
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 61
+.byte 32
+.byte 79
+.byte 110
+.byte 101
+.byte 32
+.byte 85
+.byte 108
+.byte 112
+.byte 0
+.align 1
+.LC984:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 61
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 105
+.byte 102
+.byte 105
+.byte 99
+.byte 97
+.byte 110
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 99
+.byte 97
+.byte 114
+.byte 114
+.byte 105
+.byte 101
+.byte 100
+.byte 46
+.byte 0
+.align 1
+.LC983:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 49
+.byte 44
+.byte 32
+.byte 50
+.byte 44
+.byte 32
+.byte 52
+.byte 44
+.byte 32
+.byte 56
+.byte 44
+.byte 32
+.byte 49
+.byte 48
+.byte 44
+.byte 32
+.byte 49
+.byte 54
+.byte 44
+.byte 32
+.byte 49
+.byte 48
+.byte 48
+.byte 44
+.byte 32
+.byte 50
+.byte 53
+.byte 54
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 0
+.align 1
+.LC982:
+.byte 82
+.byte 117
+.byte 110
+.byte 110
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 114
+.byte 101
+.byte 118
+.byte 101
+.byte 97
+.byte 108
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 115
+.byte 101
+.byte 32
+.byte 99
+.byte 104
+.byte 97
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 101
+.byte 114
+.byte 105
+.byte 115
+.byte 116
+.byte 105
+.byte 99
+.byte 115
+.byte 58
+.byte 0
+.align 1
+.LC978:
+.byte 9
+.byte 79
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 114
+.byte 101
+.byte 108
+.byte 101
+.byte 118
+.byte 97
+.byte 110
+.byte 116
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 105
+.byte 108
+.byte 101
+.byte 114
+.byte 32
+.byte 111
+.byte 112
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 58
+.byte 0
+.align 1
+.LC977:
+.byte 9
+.byte 79
+.byte 112
+.byte 116
+.byte 105
+.byte 109
+.byte 105
+.byte 122
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 108
+.byte 101
+.byte 118
+.byte 101
+.byte 108
+.byte 58
+.byte 10
+.byte 0
+.align 1
+.LC976:
+.byte 9
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 105
+.byte 108
+.byte 101
+.byte 114
+.byte 58
+.byte 10
+.byte 0
+.align 1
+.LC975:
+.byte 9
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 114
+.byte 58
+.byte 10
+.byte 0
+.align 1
+.LC974:
+.byte 9
+.byte 86
+.byte 101
+.byte 114
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 58
+.byte 9
+.byte 49
+.byte 48
+.byte 32
+.byte 70
+.byte 101
+.byte 98
+.byte 114
+.byte 117
+.byte 97
+.byte 114
+.byte 121
+.byte 32
+.byte 49
+.byte 57
+.byte 56
+.byte 57
+.byte 59
+.byte 0
+.align 1
+.LC973:
+.byte 9
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 58
+.byte 9
+.byte 100
+.byte 111
+.byte 117
+.byte 98
+.byte 108
+.byte 101
+.byte 59
+.byte 0
+.align 1
+.LC972:
+.byte 73
+.byte 110
+.byte 32
+.byte 100
+.byte 111
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 115
+.byte 111
+.byte 44
+.byte 32
+.byte 112
+.byte 108
+.byte 101
+.byte 97
+.byte 115
+.byte 101
+.byte 32
+.byte 105
+.byte 110
+.byte 99
+.byte 108
+.byte 117
+.byte 100
+.byte 101
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 102
+.byte 111
+.byte 108
+.byte 108
+.byte 111
+.byte 119
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 105
+.byte 110
+.byte 102
+.byte 111
+.byte 114
+.byte 109
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 58
+.byte 0
+.align 1
+.LC971:
+.byte 9
+.byte 83
+.byte 97
+.byte 110
+.byte 32
+.byte 70
+.byte 114
+.byte 97
+.byte 110
+.byte 99
+.byte 105
+.byte 115
+.byte 99
+.byte 111
+.byte 44
+.byte 32
+.byte 67
+.byte 65
+.byte 32
+.byte 57
+.byte 52
+.byte 49
+.byte 52
+.byte 51
+.byte 45
+.byte 48
+.byte 55
+.byte 48
+.byte 52
+.byte 44
+.byte 32
+.byte 85
+.byte 83
+.byte 65
+.byte 10
+.byte 0
+.align 1
+.LC970:
+.byte 9
+.byte 85
+.byte 110
+.byte 105
+.byte 118
+.byte 101
+.byte 114
+.byte 115
+.byte 105
+.byte 116
+.byte 121
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 67
+.byte 97
+.byte 108
+.byte 105
+.byte 102
+.byte 111
+.byte 114
+.byte 110
+.byte 105
+.byte 97
+.byte 0
+.align 1
+.LC969:
+.byte 9
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 67
+.byte 101
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 85
+.byte 45
+.byte 55
+.byte 54
+.byte 0
+.align 1
+.LC968:
+.byte 9
+.byte 82
+.byte 105
+.byte 99
+.byte 104
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 75
+.byte 97
+.byte 114
+.byte 112
+.byte 105
+.byte 110
+.byte 115
+.byte 107
+.byte 105
+.byte 0
+.align 1
+.LC967:
+.byte 80
+.byte 108
+.byte 101
+.byte 97
+.byte 115
+.byte 101
+.byte 32
+.byte 115
+.byte 101
+.byte 110
+.byte 100
+.byte 32
+.byte 115
+.byte 117
+.byte 103
+.byte 103
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 105
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 114
+.byte 101
+.byte 115
+.byte 117
+.byte 108
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 0
+.align 1
+.LC966:
+.byte 99
+.byte 111
+.byte 112
+.byte 101
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 117
+.byte 110
+.byte 97
+.byte 110
+.byte 116
+.byte 105
+.byte 99
+.byte 105
+.byte 112
+.byte 97
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 110
+.byte 101
+.byte 119
+.byte 108
+.byte 121
+.byte 32
+.byte 117
+.byte 110
+.byte 99
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 112
+.byte 97
+.byte 116
+.byte 104
+.byte 111
+.byte 108
+.byte 111
+.byte 103
+.byte 105
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC965:
+.byte 85
+.byte 115
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 105
+.byte 110
+.byte 118
+.byte 105
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 104
+.byte 101
+.byte 108
+.byte 112
+.byte 32
+.byte 100
+.byte 101
+.byte 98
+.byte 117
+.byte 103
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 97
+.byte 117
+.byte 103
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 115
+.byte 111
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 119
+.byte 105
+.byte 108
+.byte 108
+.byte 0
+.align 1
+.LC961:
+.byte 65
+.byte 110
+.byte 115
+.byte 119
+.byte 101
+.byte 114
+.byte 32
+.byte 113
+.byte 117
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 89
+.byte 44
+.byte 32
+.byte 121
+.byte 44
+.byte 32
+.byte 78
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 110
+.byte 32
+.byte 40
+.byte 117
+.byte 110
+.byte 108
+.byte 101
+.byte 115
+.byte 115
+.byte 32
+.byte 111
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 119
+.byte 105
+.byte 115
+.byte 101
+.byte 32
+.byte 105
+.byte 110
+.byte 100
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 101
+.byte 100
+.byte 41
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC960:
+.byte 97
+.byte 109
+.byte 101
+.byte 110
+.byte 100
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 109
+.byte 97
+.byte 107
+.byte 101
+.byte 32
+.byte 102
+.byte 117
+.byte 114
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 101
+.byte 115
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC959:
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 97
+.byte 110
+.byte 121
+.byte 119
+.byte 97
+.byte 121
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 115
+.byte 101
+.byte 101
+.byte 32
+.byte 104
+.byte 111
+.byte 119
+.byte 32
+.byte 109
+.byte 97
+.byte 110
+.byte 121
+.byte 32
+.byte 109
+.byte 105
+.byte 108
+.byte 101
+.byte 115
+.byte 116
+.byte 111
+.byte 110
+.byte 101
+.byte 115
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 112
+.byte 97
+.byte 115
+.byte 115
+.byte 101
+.byte 115
+.byte 44
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 110
+.byte 0
+.align 1
+.LC958:
+.byte 119
+.byte 97
+.byte 114
+.byte 110
+.byte 105
+.byte 110
+.byte 103
+.byte 46
+.byte 32
+.byte 32
+.byte 73
+.byte 102
+.byte 32
+.byte 112
+.byte 101
+.byte 114
+.byte 115
+.byte 117
+.byte 97
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 118
+.byte 97
+.byte 105
+.byte 108
+.byte 115
+.byte 32
+.byte 110
+.byte 97
+.byte 117
+.byte 103
+.byte 104
+.byte 116
+.byte 44
+.byte 32
+.byte 100
+.byte 111
+.byte 110
+.byte 39
+.byte 116
+.byte 32
+.byte 100
+.byte 101
+.byte 115
+.byte 112
+.byte 97
+.byte 105
+.byte 114
+.byte 32
+.byte 98
+.byte 117
+.byte 116
+.byte 32
+.byte 114
+.byte 117
+.byte 110
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 0
+.align 1
+.LC957:
+.byte 116
+.byte 111
+.byte 32
+.byte 112
+.byte 101
+.byte 114
+.byte 115
+.byte 101
+.byte 118
+.byte 101
+.byte 114
+.byte 101
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 97
+.byte 32
+.byte 115
+.byte 117
+.byte 114
+.byte 114
+.byte 111
+.byte 103
+.byte 97
+.byte 116
+.byte 101
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 97
+.byte 102
+.byte 116
+.byte 101
+.byte 114
+.byte 44
+.byte 32
+.byte 112
+.byte 101
+.byte 114
+.byte 104
+.byte 97
+.byte 112
+.byte 115
+.byte 44
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 112
+.byte 108
+.byte 97
+.byte 121
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 115
+.byte 111
+.byte 109
+.byte 101
+.byte 0
+.align 1
+.LC956:
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 108
+.byte 105
+.byte 107
+.byte 101
+.byte 32
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 47
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 111
+.byte 99
+.byte 99
+.byte 117
+.byte 114
+.byte 115
+.byte 44
+.byte 32
+.byte 98
+.byte 117
+.byte 116
+.byte 32
+.byte 114
+.byte 97
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 0
+.align 1
+.LC955:
+.byte 116
+.byte 114
+.byte 121
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 112
+.byte 101
+.byte 114
+.byte 115
+.byte 117
+.byte 97
+.byte 100
+.byte 101
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 78
+.byte 79
+.byte 84
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 116
+.byte 101
+.byte 114
+.byte 109
+.byte 105
+.byte 110
+.byte 97
+.byte 116
+.byte 101
+.byte 32
+.byte 101
+.byte 120
+.byte 101
+.byte 99
+.byte 117
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 110
+.byte 32
+.byte 97
+.byte 110
+.byte 0
+.align 1
+.LC954:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 96
+.byte 69
+.byte 78
+.byte 68
+.byte 32
+.byte 79
+.byte 70
+.byte 32
+.byte 84
+.byte 69
+.byte 83
+.byte 84
+.byte 39
+.byte 44
+.byte 10
+.byte 0
+.align 1
+.LC953:
+.byte 76
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 115
+.byte 116
+.byte 111
+.byte 112
+.byte 32
+.byte 112
+.byte 114
+.byte 101
+.byte 109
+.byte 97
+.byte 116
+.byte 117
+.byte 114
+.byte 101
+.byte 108
+.byte 121
+.byte 44
+.byte 32
+.byte 105
+.byte 46
+.byte 101
+.byte 46
+.byte 32
+.byte 98
+.byte 101
+.byte 102
+.byte 111
+.byte 114
+.byte 101
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 112
+.byte 108
+.byte 97
+.byte 121
+.byte 105
+.byte 110
+.byte 103
+.byte 10
+.byte 0
+.align 1
+.LC949:
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.LC943:
+.byte 32
+.byte 32
+.byte 32
+.byte 80
+.byte 76
+.byte 69
+.byte 65
+.byte 83
+.byte 69
+.byte 32
+.byte 78
+.byte 79
+.byte 84
+.byte 73
+.byte 70
+.byte 89
+.byte 32
+.byte 75
+.byte 65
+.byte 82
+.byte 80
+.byte 73
+.byte 78
+.byte 75
+.byte 83
+.byte 73
+.byte 33
+.byte 10
+.byte 0
+.align 1
+.LC942:
+.byte 37
+.byte 115
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 105
+.byte 110
+.byte 99
+.byte 111
+.byte 110
+.byte 115
+.byte 105
+.byte 115
+.byte 116
+.byte 101
+.byte 110
+.byte 116
+.byte 46
+.byte 46
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC939:
+.byte 9
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 90
+.byte 32
+.byte 42
+.byte 32
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.LC938:
+.byte 9
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 49
+.byte 32
+.byte 42
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.LC937:
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 100
+.byte 111
+.byte 101
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 109
+.byte 117
+.byte 116
+.byte 101
+.byte 33
+.byte 10
+.byte 0
+.align 1
+.LC932:
+.byte 90
+.byte 32
+.byte 47
+.byte 32
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.LC929:
+.byte 49
+.byte 32
+.byte 42
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 37
+.byte 103
+.byte 10
+.byte 0
+.align 1
+.LC926:
+.byte 90
+.byte 32
+.byte 42
+.byte 32
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 0
+.align 1
+.LC923:
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 9
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 101
+.byte 115
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 32
+.byte 0
+.align 1
+.LC922:
+.byte 87
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 112
+.byte 114
+.byte 105
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 0
+.align 1
+.LC917:
+.byte 84
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 33
+.byte 10
+.byte 0
+.align 1
+.LC914:
+.byte 84
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 86
+.byte 69
+.byte 82
+.byte 89
+.byte 32
+.byte 83
+.byte 69
+.byte 82
+.byte 73
+.byte 79
+.byte 85
+.byte 83
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 33
+.byte 10
+.byte 0
+.align 1
+.LC908:
+.byte 32
+.byte 104
+.byte 97
+.byte 115
+.byte 32
+.byte 78
+.byte 79
+.byte 84
+.byte 32
+.byte 106
+.byte 117
+.byte 115
+.byte 116
+.byte 32
+.byte 98
+.byte 101
+.byte 101
+.byte 110
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 97
+.byte 108
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC907:
+.byte 84
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 79
+.byte 46
+.byte 75
+.byte 46
+.byte 44
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 118
+.byte 105
+.byte 100
+.byte 101
+.byte 100
+.byte 32
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 47
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 0
+.align 1
+.LC904:
+.byte 87
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 109
+.byte 97
+.byte 99
+.byte 104
+.byte 105
+.byte 110
+.byte 101
+.byte 32
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 40
+.byte 90
+.byte 32
+.byte 43
+.byte 32
+.byte 90
+.byte 41
+.byte 32
+.byte 47
+.byte 32
+.byte 90
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC900:
+.byte 40
+.byte 90
+.byte 32
+.byte 43
+.byte 32
+.byte 90
+.byte 41
+.byte 32
+.byte 47
+.byte 32
+.byte 90
+.byte 32
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 115
+.byte 97
+.byte 102
+.byte 101
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC899:
+.byte 83
+.byte 105
+.byte 110
+.byte 99
+.byte 101
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 100
+.byte 101
+.byte 110
+.byte 105
+.byte 101
+.byte 115
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 101
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 0
+.align 1
+.LC894:
+.byte 83
+.byte 105
+.byte 109
+.byte 105
+.byte 108
+.byte 97
+.byte 114
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 114
+.byte 101
+.byte 112
+.byte 97
+.byte 110
+.byte 99
+.byte 105
+.byte 101
+.byte 115
+.byte 32
+.byte 104
+.byte 97
+.byte 118
+.byte 101
+.byte 32
+.byte 111
+.byte 99
+.byte 99
+.byte 117
+.byte 114
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 116
+.byte 105
+.byte 109
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC882:
+.byte 9
+.byte 9
+.byte 116
+.byte 104
+.byte 101
+.byte 121
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC881:
+.byte 9
+.byte 119
+.byte 104
+.byte 105
+.byte 99
+.byte 104
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 117
+.byte 110
+.byte 101
+.byte 113
+.byte 117
+.byte 97
+.byte 108
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 59
+.byte 10
+.byte 0
+.align 1
+.LC880:
+.byte 9
+.byte 121
+.byte 105
+.byte 101
+.byte 108
+.byte 100
+.byte 101
+.byte 100
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 59
+.byte 10
+.byte 0
+.align 1
+.LC879:
+.byte 9
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 32
+.byte 94
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 10
+.byte 0
+.align 1
+.LC878:
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 10
+.byte 0
+.align 1
+.LC877:
+.byte 87
+.byte 65
+.byte 82
+.byte 78
+.byte 73
+.byte 78
+.byte 71
+.byte 58
+.byte 32
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 10
+.byte 0
+.align 1
+.LC856:
+.byte 9
+.byte 105
+.byte 110
+.byte 115
+.byte 116
+.byte 101
+.byte 97
+.byte 100
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 48
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC855:
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 40
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 32
+.byte 45
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 4
+.LC846:
+.long -1998362383
+.long 1054144693
+.align 1
+.LC843:
+.byte 37
+.byte 115
+.byte 58
+.byte 32
+.byte 32
+.byte 37
+.byte 115
+.byte 0
+.align 1
+.LC842:
+.byte 70
+.byte 76
+.byte 65
+.byte 87
+.byte 0
+.align 1
+.LC841:
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 0
+.align 1
+.LC840:
+.byte 83
+.byte 69
+.byte 82
+.byte 73
+.byte 79
+.byte 85
+.byte 83
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 0
+.align 1
+.LC839:
+.byte 70
+.byte 65
+.byte 73
+.byte 76
+.byte 85
+.byte 82
+.byte 69
+.byte 0
+.align 1
+.LC831:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 80
+.byte 97
+.byte 103
+.byte 101
+.byte 58
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 10
+.byte 0
+.align 1
+.LC830:
+.byte 10
+.byte 68
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 105
+.byte 115
+.byte 32
+.byte 114
+.byte 101
+.byte 115
+.byte 117
+.byte 109
+.byte 101
+.byte 115
+.byte 32
+.byte 97
+.byte 102
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 109
+.byte 105
+.byte 108
+.byte 101
+.byte 115
+.byte 116
+.byte 111
+.byte 110
+.byte 101
+.byte 32
+.byte 78
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 32
+.byte 37
+.byte 100
+.byte 0
+.align 4
+.LC827:
+.long 0
+.long -1074790400
+.align 1
+.LC821:
+.byte 69
+.byte 78
+.byte 68
+.byte 32
+.byte 79
+.byte 70
+.byte 32
+.byte 84
+.byte 69
+.byte 83
+.byte 84
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC820:
+.byte 10
+.byte 65
+.byte 32
+.byte 116
+.byte 111
+.byte 116
+.byte 97
+.byte 108
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 102
+.byte 108
+.byte 111
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 112
+.byte 111
+.byte 105
+.byte 110
+.byte 116
+.byte 32
+.byte 101
+.byte 120
+.byte 99
+.byte 101
+.byte 112
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 119
+.byte 101
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 101
+.byte 103
+.byte 105
+.byte 115
+.byte 116
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC817:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 69
+.byte 120
+.byte 99
+.byte 101
+.byte 108
+.byte 108
+.byte 101
+.byte 110
+.byte 116
+.byte 33
+.byte 10
+.byte 0
+.align 1
+.LC816:
+.byte 32
+.byte 100
+.byte 117
+.byte 114
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 71
+.byte 114
+.byte 97
+.byte 100
+.byte 117
+.byte 97
+.byte 108
+.byte 32
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC815:
+.byte 44
+.byte 10
+.byte 101
+.byte 120
+.byte 99
+.byte 101
+.byte 112
+.byte 116
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 112
+.byte 111
+.byte 115
+.byte 115
+.byte 105
+.byte 98
+.byte 108
+.byte 121
+.byte 32
+.byte 68
+.byte 111
+.byte 117
+.byte 98
+.byte 108
+.byte 101
+.byte 32
+.byte 82
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 105
+.byte 110
+.byte 103
+.byte 0
+.align 1
+.LC814:
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC811:
+.byte 56
+.byte 53
+.byte 52
+.byte 0
+.align 1
+.LC810:
+.byte 55
+.byte 53
+.byte 52
+.byte 0
+.align 1
+.LC807:
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 112
+.byte 111
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 73
+.byte 69
+.byte 69
+.byte 69
+.byte 32
+.byte 115
+.byte 116
+.byte 97
+.byte 110
+.byte 100
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 80
+.byte 0
+.align 1
+.LC806:
+.byte 82
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 111
+.byte 114
+.byte 109
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 0
+.align 1
+.LC803:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 115
+.byte 101
+.byte 101
+.byte 109
+.byte 115
+.byte 32
+.byte 83
+.byte 97
+.byte 116
+.byte 105
+.byte 115
+.byte 102
+.byte 97
+.byte 99
+.byte 116
+.byte 111
+.byte 114
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC797:
+.byte 78
+.byte 111
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 117
+.byte 114
+.byte 101
+.byte 115
+.byte 44
+.byte 32
+.byte 100
+.byte 101
+.byte 102
+.byte 101
+.byte 99
+.byte 116
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 102
+.byte 108
+.byte 97
+.byte 119
+.byte 115
+.byte 32
+.byte 104
+.byte 97
+.byte 118
+.byte 101
+.byte 32
+.byte 98
+.byte 101
+.byte 101
+.byte 110
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC796:
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 39
+.byte 115
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 115
+.byte 101
+.byte 113
+.byte 117
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC795:
+.byte 80
+.byte 111
+.byte 116
+.byte 101
+.byte 110
+.byte 116
+.byte 105
+.byte 97
+.byte 108
+.byte 108
+.byte 121
+.byte 32
+.byte 102
+.byte 97
+.byte 116
+.byte 97
+.byte 108
+.byte 32
+.byte 70
+.byte 65
+.byte 73
+.byte 76
+.byte 85
+.byte 82
+.byte 69
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 104
+.byte 97
+.byte 118
+.byte 101
+.byte 32
+.byte 115
+.byte 112
+.byte 111
+.byte 105
+.byte 108
+.byte 101
+.byte 100
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 0
+.align 1
+.LC792:
+.byte 117
+.byte 110
+.byte 97
+.byte 99
+.byte 99
+.byte 101
+.byte 112
+.byte 116
+.byte 97
+.byte 98
+.byte 108
+.byte 101
+.byte 32
+.byte 83
+.byte 101
+.byte 114
+.byte 105
+.byte 111
+.byte 117
+.byte 115
+.byte 32
+.byte 68
+.byte 101
+.byte 102
+.byte 101
+.byte 99
+.byte 116
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC791:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 104
+.byte 97
+.byte 115
+.byte 32
+.byte 0
+.align 1
+.LC787:
+.byte 100
+.byte 101
+.byte 115
+.byte 112
+.byte 105
+.byte 116
+.byte 101
+.byte 32
+.byte 105
+.byte 110
+.byte 99
+.byte 111
+.byte 110
+.byte 118
+.byte 101
+.byte 110
+.byte 105
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 68
+.byte 101
+.byte 102
+.byte 101
+.byte 99
+.byte 116
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC786:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 65
+.byte 99
+.byte 99
+.byte 101
+.byte 112
+.byte 116
+.byte 97
+.byte 98
+.byte 108
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.LC781:
+.byte 83
+.byte 97
+.byte 116
+.byte 105
+.byte 115
+.byte 102
+.byte 97
+.byte 99
+.byte 116
+.byte 111
+.byte 114
+.byte 121
+.byte 32
+.byte 116
+.byte 104
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 32
+.byte 102
+.byte 108
+.byte 97
+.byte 119
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC780:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 100
+.byte 105
+.byte 97
+.byte 103
+.byte 110
+.byte 111
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 115
+.byte 101
+.byte 101
+.byte 109
+.byte 115
+.byte 32
+.byte 0
+.align 1
+.LC769:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 32
+.byte 37
+.byte 45
+.byte 50
+.byte 57
+.byte 115
+.byte 32
+.byte 37
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC762:
+.byte 70
+.byte 76
+.byte 65
+.byte 87
+.byte 115
+.byte 32
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 61
+.byte 0
+.align 1
+.LC761:
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 115
+.byte 32
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 61
+.byte 0
+.align 1
+.LC760:
+.byte 83
+.byte 69
+.byte 82
+.byte 73
+.byte 79
+.byte 85
+.byte 83
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 115
+.byte 32
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 61
+.byte 0
+.align 1
+.LC759:
+.byte 70
+.byte 65
+.byte 73
+.byte 76
+.byte 85
+.byte 82
+.byte 69
+.byte 115
+.byte 32
+.byte 32
+.byte 101
+.byte 110
+.byte 99
+.byte 111
+.byte 117
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 101
+.byte 100
+.byte 32
+.byte 61
+.byte 0
+.align 1
+.LC755:
+.byte 10
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 84
+.byte 114
+.byte 121
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 32
+.byte 48
+.byte 32
+.byte 47
+.byte 32
+.byte 48
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 100
+.byte 117
+.byte 99
+.byte 101
+.byte 115
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 0
+.align 1
+.LC754:
+.byte 32
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC751:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 84
+.byte 114
+.byte 121
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 32
+.byte 49
+.byte 32
+.byte 47
+.byte 32
+.byte 48
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 100
+.byte 117
+.byte 99
+.byte 101
+.byte 115
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 0
+.align 1
+.LC750:
+.byte 87
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 109
+.byte 101
+.byte 115
+.byte 115
+.byte 97
+.byte 103
+.byte 101
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 47
+.byte 111
+.byte 114
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 115
+.byte 32
+.byte 100
+.byte 111
+.byte 101
+.byte 115
+.byte 32
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 100
+.byte 117
+.byte 99
+.byte 101
+.byte 63
+.byte 10
+.byte 0
+.align 1
+.LC749:
+.byte 32
+.byte 32
+.byte 105
+.byte 110
+.byte 115
+.byte 116
+.byte 101
+.byte 97
+.byte 100
+.byte 44
+.byte 32
+.byte 88
+.byte 32
+.byte 47
+.byte 32
+.byte 88
+.byte 32
+.byte 45
+.byte 32
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 45
+.byte 32
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC748:
+.byte 32
+.byte 32
+.byte 88
+.byte 32
+.byte 47
+.byte 32
+.byte 88
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 49
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 110
+.byte 32
+.byte 88
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.LC743:
+.byte 32
+.byte 32
+.byte 88
+.byte 32
+.byte 47
+.byte 32
+.byte 88
+.byte 32
+.byte 32
+.byte 116
+.byte 114
+.byte 97
+.byte 112
+.byte 115
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 110
+.byte 32
+.byte 88
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 103
+.byte 10
+.byte 0
+.align 1
+.LC728:
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 102
+.byte 97
+.byte 114
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 49
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC727:
+.byte 32
+.byte 117
+.byte 110
+.byte 98
+.byte 97
+.byte 108
+.byte 97
+.byte 110
+.byte 99
+.byte 101
+.byte 100
+.byte 32
+.byte 114
+.byte 97
+.byte 110
+.byte 103
+.byte 101
+.byte 59
+.byte 32
+.byte 85
+.byte 102
+.byte 84
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 42
+.byte 32
+.byte 86
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 9
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.LC726:
+.byte 66
+.byte 97
+.byte 100
+.byte 108
+.byte 121
+.byte 0
+.align 1
+.LC719:
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 102
+.byte 97
+.byte 114
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 40
+.byte 90
+.byte 41
+.byte 32
+.byte 94
+.byte 32
+.byte 50
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC718:
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.LC706:
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 102
+.byte 97
+.byte 114
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 40
+.byte 90
+.byte 41
+.byte 32
+.byte 94
+.byte 32
+.byte 50
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC705:
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 119
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 112
+.byte 114
+.byte 105
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.LC688:
+.byte 43
+.byte 45
+.byte 37
+.byte 103
+.byte 44
+.byte 32
+.byte 43
+.byte 45
+.byte 37
+.byte 103
+.byte 10
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 43
+.byte 45
+.byte 37
+.byte 103
+.byte 32
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 117
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 46
+.byte 0
+.align 1
+.LC687:
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 105
+.byte 110
+.byte 118
+.byte 111
+.byte 108
+.byte 118
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 0
+.align 1
+.LC681:
+.byte 97
+.byte 98
+.byte 111
+.byte 118
+.byte 101
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC680:
+.byte 65
+.byte 110
+.byte 121
+.byte 32
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 97
+.byte 108
+.byte 32
+.byte 115
+.byte 101
+.byte 112
+.byte 97
+.byte 114
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 42
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 111
+.byte 110
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.LC679:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 86
+.byte 32
+.byte 47
+.byte 32
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC678:
+.byte 78
+.byte 111
+.byte 32
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 97
+.byte 108
+.byte 101
+.byte 100
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 86
+.byte 32
+.byte 42
+.byte 32
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.LC677:
+.byte 84
+.byte 104
+.byte 101
+.byte 114
+.byte 101
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 32
+.byte 115
+.byte 97
+.byte 116
+.byte 117
+.byte 114
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 98
+.byte 101
+.byte 99
+.byte 97
+.byte 117
+.byte 115
+.byte 101
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 115
+.byte 121
+.byte 115
+.byte 116
+.byte 101
+.byte 109
+.byte 32
+.byte 116
+.byte 114
+.byte 97
+.byte 112
+.byte 115
+.byte 32
+.byte 111
+.byte 110
+.byte 32
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC676:
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 115
+.byte 97
+.byte 116
+.byte 117
+.byte 114
+.byte 97
+.byte 116
+.byte 101
+.byte 115
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 86
+.byte 48
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC673:
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 86
+.byte 32
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC664:
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 112
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 9
+.byte 115
+.byte 104
+.byte 114
+.byte 105
+.byte 110
+.byte 107
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC661:
+.byte 45
+.byte 40
+.byte 45
+.byte 89
+.byte 41
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 89
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC660:
+.byte 102
+.byte 105
+.byte 110
+.byte 100
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 0
+.align 1
+.LC659:
+.byte 83
+.byte 101
+.byte 101
+.byte 109
+.byte 115
+.byte 32
+.byte 79
+.byte 46
+.byte 75
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC656:
+.byte 84
+.byte 114
+.byte 121
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 111
+.byte 110
+.byte 32
+.byte 89
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC655:
+.byte 67
+.byte 97
+.byte 110
+.byte 32
+.byte 96
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 45
+.byte 89
+.byte 39
+.byte 32
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 63
+.byte 10
+.byte 0
+.align 1
+.LC648:
+.byte 84
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 103
+.byte 101
+.byte 110
+.byte 101
+.byte 114
+.byte 97
+.byte 116
+.byte 101
+.byte 32
+.byte 97
+.byte 110
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC647:
+.byte 83
+.byte 101
+.byte 97
+.byte 114
+.byte 99
+.byte 104
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 79
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 58
+.byte 10
+.byte 0
+.align 1
+.LC646:
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 32
+.byte 110
+.byte 111
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 114
+.byte 101
+.byte 112
+.byte 97
+.byte 110
+.byte 99
+.byte 105
+.byte 101
+.byte 115
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC638:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 112
+.byte 111
+.byte 119
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 90
+.byte 94
+.byte 81
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 114
+.byte 32
+.byte 110
+.byte 101
+.byte 97
+.byte 114
+.byte 108
+.byte 121
+.byte 32
+.byte 101
+.byte 120
+.byte 116
+.byte 114
+.byte 101
+.byte 109
+.byte 101
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC637:
+.byte 65
+.byte 99
+.byte 99
+.byte 117
+.byte 114
+.byte 97
+.byte 99
+.byte 121
+.byte 32
+.byte 115
+.byte 101
+.byte 101
+.byte 109
+.byte 115
+.byte 32
+.byte 97
+.byte 100
+.byte 101
+.byte 113
+.byte 117
+.byte 97
+.byte 116
+.byte 101
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC630:
+.byte 9
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 105
+.byte 110
+.byte 118
+.byte 111
+.byte 108
+.byte 118
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 105
+.byte 110
+.byte 121
+.byte 32
+.byte 105
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 114
+.byte 97
+.byte 116
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC629:
+.byte 9
+.byte 84
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 109
+.byte 117
+.byte 99
+.byte 104
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 115
+.byte 112
+.byte 111
+.byte 105
+.byte 108
+.byte 32
+.byte 102
+.byte 105
+.byte 110
+.byte 97
+.byte 110
+.byte 99
+.byte 105
+.byte 97
+.byte 108
+.byte 10
+.byte 0
+.align 1
+.LC628:
+.byte 9
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC627:
+.byte 9
+.byte 40
+.byte 49
+.byte 32
+.byte 43
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 32
+.byte 94
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 59
+.byte 10
+.byte 0
+.align 1
+.LC626:
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 10
+.byte 0
+.align 1
+.LC625:
+.byte 67
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 101
+.byte 100
+.byte 0
+.align 1
+.LC618:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 88
+.byte 94
+.byte 40
+.byte 40
+.byte 88
+.byte 32
+.byte 43
+.byte 32
+.byte 49
+.byte 41
+.byte 32
+.byte 47
+.byte 32
+.byte 40
+.byte 88
+.byte 32
+.byte 45
+.byte 32
+.byte 49
+.byte 41
+.byte 41
+.byte 32
+.byte 118
+.byte 115
+.byte 46
+.byte 32
+.byte 101
+.byte 120
+.byte 112
+.byte 40
+.byte 50
+.byte 41
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 88
+.byte 32
+.byte 45
+.byte 62
+.byte 32
+.byte 49
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC614:
+.byte 84
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 79
+.byte 46
+.byte 75
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC611:
+.byte 32
+.byte 32
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC610:
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 98
+.byte 101
+.byte 116
+.byte 119
+.byte 101
+.byte 101
+.byte 110
+.byte 32
+.byte 48
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 10
+.byte 0
+.align 1
+.LC606:
+.byte 97
+.byte 99
+.byte 116
+.byte 117
+.byte 97
+.byte 108
+.byte 108
+.byte 121
+.byte 32
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 121
+.byte 105
+.byte 101
+.byte 108
+.byte 100
+.byte 115
+.byte 58
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC605:
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 97
+.byte 102
+.byte 102
+.byte 108
+.byte 105
+.byte 99
+.byte 116
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 101
+.byte 120
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 10
+.byte 9
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 32
+.byte 94
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 59
+.byte 10
+.byte 0
+.align 1
+.LC604:
+.byte 85
+.byte 102
+.byte 84
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 61
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 32
+.byte 94
+.byte 32
+.byte 40
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 41
+.byte 10
+.byte 111
+.byte 110
+.byte 108
+.byte 121
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 0
+.align 1
+.LC603:
+.byte 83
+.byte 105
+.byte 110
+.byte 99
+.byte 101
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 111
+.byte 99
+.byte 99
+.byte 117
+.byte 114
+.byte 115
+.byte 32
+.byte 98
+.byte 101
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC602:
+.byte 82
+.byte 97
+.byte 110
+.byte 103
+.byte 101
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 110
+.byte 97
+.byte 114
+.byte 114
+.byte 111
+.byte 119
+.byte 59
+.byte 32
+.byte 85
+.byte 49
+.byte 94
+.byte 37
+.byte 100
+.byte 32
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC597:
+.byte 109
+.byte 101
+.byte 114
+.byte 101
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 111
+.byte 102
+.byte 102
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC596:
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 115
+.byte 117
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 32
+.byte 108
+.byte 97
+.byte 114
+.byte 103
+.byte 101
+.byte 114
+.byte 32
+.byte 82
+.byte 101
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 110
+.byte 32
+.byte 0
+.align 1
+.LC595:
+.byte 32
+.byte 98
+.byte 101
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 119
+.byte 104
+.byte 105
+.byte 99
+.byte 104
+.byte 0
+.align 1
+.LC594:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.LC593:
+.byte 88
+.byte 32
+.byte 47
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 49
+.byte 32
+.byte 43
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC592:
+.byte 88
+.byte 32
+.byte 47
+.byte 32
+.byte 90
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 115
+.byte 33
+.byte 10
+.byte 0
+.align 1
+.LC589:
+.byte 101
+.byte 110
+.byte 99
+.byte 111
+.byte 117
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 97
+.byte 108
+.byte 116
+.byte 104
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 32
+.byte 97
+.byte 99
+.byte 116
+.byte 117
+.byte 97
+.byte 108
+.byte 108
+.byte 121
+.byte 10
+.byte 0
+.align 1
+.LC588:
+.byte 32
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 32
+.byte 40
+.byte 102
+.byte 40
+.byte 88
+.byte 41
+.byte 32
+.byte 45
+.byte 32
+.byte 102
+.byte 40
+.byte 90
+.byte 41
+.byte 41
+.byte 32
+.byte 47
+.byte 32
+.byte 40
+.byte 88
+.byte 32
+.byte 45
+.byte 32
+.byte 90
+.byte 41
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC587:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 105
+.byte 102
+.byte 32
+.byte 40
+.byte 88
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 90
+.byte 41
+.byte 32
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 32
+.byte 32
+.byte 101
+.byte 108
+.byte 115
+.byte 101
+.byte 0
+.align 1
+.LC586:
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 117
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 110
+.byte 32
+.byte 105
+.byte 110
+.byte 110
+.byte 111
+.byte 99
+.byte 101
+.byte 110
+.byte 116
+.byte 32
+.byte 115
+.byte 116
+.byte 97
+.byte 116
+.byte 101
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 108
+.byte 105
+.byte 107
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.LC585:
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 83
+.byte 69
+.byte 82
+.byte 73
+.byte 79
+.byte 85
+.byte 83
+.byte 32
+.byte 68
+.byte 69
+.byte 70
+.byte 69
+.byte 67
+.byte 84
+.byte 10
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 99
+.byte 97
+.byte 117
+.byte 115
+.byte 101
+.byte 115
+.byte 32
+.byte 0
+.align 1
+.LC584:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 83
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 78
+.byte 79
+.byte 84
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 97
+.byte 108
+.byte 32
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 44
+.byte 32
+.byte 0
+.align 1
+.LC583:
+.byte 121
+.byte 101
+.byte 116
+.byte 32
+.byte 88
+.byte 32
+.byte 45
+.byte 32
+.byte 90
+.byte 32
+.byte 121
+.byte 105
+.byte 101
+.byte 108
+.byte 100
+.byte 115
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC582:
+.byte 88
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 9
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 101
+.byte 113
+.byte 117
+.byte 97
+.byte 108
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 90
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC577:
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 47
+.byte 32
+.byte 85
+.byte 102
+.byte 84
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 101
+.byte 100
+.byte 33
+.byte 10
+.byte 0
+.align 1
+.LC567:
+.byte 40
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 111
+.byte 102
+.byte 102
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 85
+.byte 102
+.byte 84
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 41
+.byte 32
+.byte 60
+.byte 32
+.byte 69
+.byte 48
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC566:
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 103
+.byte 114
+.byte 97
+.byte 100
+.byte 117
+.byte 97
+.byte 108
+.byte 59
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 105
+.byte 110
+.byte 99
+.byte 117
+.byte 114
+.byte 115
+.byte 32
+.byte 65
+.byte 98
+.byte 115
+.byte 111
+.byte 108
+.byte 117
+.byte 116
+.byte 101
+.byte 32
+.byte 69
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 61
+.byte 10
+.byte 0
+.align 1
+.LC561:
+.byte 124
+.byte 81
+.byte 32
+.byte 45
+.byte 32
+.byte 89
+.byte 124
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC560:
+.byte 112
+.byte 114
+.byte 105
+.byte 110
+.byte 116
+.byte 32
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 81
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 89
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC559:
+.byte 81
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 89
+.byte 32
+.byte 119
+.byte 104
+.byte 105
+.byte 108
+.byte 101
+.byte 32
+.byte 100
+.byte 101
+.byte 110
+.byte 121
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 124
+.byte 81
+.byte 32
+.byte 45
+.byte 32
+.byte 89
+.byte 124
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 48
+.byte 59
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 115
+.byte 101
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.LC558:
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 117
+.byte 115
+.byte 101
+.byte 115
+.byte 32
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 44
+.byte 32
+.byte 119
+.byte 104
+.byte 105
+.byte 99
+.byte 104
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 10
+.byte 0
+.align 1
+.LC556:
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 101
+.byte 108
+.byte 115
+.byte 101
+.byte 32
+.byte 109
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 109
+.byte 97
+.byte 110
+.byte 121
+.byte 32
+.byte 108
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 119
+.byte 114
+.byte 111
+.byte 110
+.byte 103
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC555:
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 100
+.byte 111
+.byte 119
+.byte 110
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.LC554:
+.byte 97
+.byte 112
+.byte 112
+.byte 114
+.byte 111
+.byte 97
+.byte 99
+.byte 104
+.byte 32
+.byte 97
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 49
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.LC553:
+.byte 69
+.byte 105
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 97
+.byte 99
+.byte 99
+.byte 117
+.byte 114
+.byte 97
+.byte 99
+.byte 121
+.byte 32
+.byte 100
+.byte 101
+.byte 116
+.byte 101
+.byte 114
+.byte 105
+.byte 111
+.byte 114
+.byte 97
+.byte 116
+.byte 101
+.byte 115
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.LC541:
+.byte 83
+.byte 109
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 115
+.byte 116
+.byte 114
+.byte 105
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 112
+.byte 111
+.byte 115
+.byte 105
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 69
+.byte 48
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC540:
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 110
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 100
+.byte 117
+.byte 99
+.byte 116
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC539:
+.byte 68
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 101
+.byte 110
+.byte 99
+.byte 101
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 115
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 97
+.byte 32
+.byte 104
+.byte 105
+.byte 103
+.byte 104
+.byte 101
+.byte 114
+.byte 0
+.align 1
+.LC536:
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 110
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 101
+.byte 110
+.byte 99
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC535:
+.byte 80
+.byte 114
+.byte 111
+.byte 100
+.byte 117
+.byte 99
+.byte 116
+.byte 115
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 97
+.byte 32
+.byte 104
+.byte 105
+.byte 103
+.byte 104
+.byte 101
+.byte 114
+.byte 0
+.align 1
+.LC528:
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 80
+.byte 115
+.byte 101
+.byte 117
+.byte 100
+.byte 111
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 112
+.byte 114
+.byte 105
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC527:
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 32
+.byte 115
+.byte 116
+.byte 105
+.byte 99
+.byte 107
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 97
+.byte 110
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 100
+.byte 108
+.byte 121
+.byte 32
+.byte 112
+.byte 111
+.byte 115
+.byte 105
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.LC526:
+.byte 112
+.byte 111
+.byte 115
+.byte 105
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 44
+.byte 32
+.byte 105
+.byte 115
+.byte 110
+.byte 39
+.byte 116
+.byte 59
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 112
+.byte 114
+.byte 105
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC525:
+.byte 66
+.byte 117
+.byte 116
+.byte 32
+.byte 45
+.byte 80
+.byte 115
+.byte 101
+.byte 117
+.byte 100
+.byte 111
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 44
+.byte 32
+.byte 119
+.byte 104
+.byte 105
+.byte 99
+.byte 104
+.byte 32
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 98
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.LC522:
+.byte 80
+.byte 115
+.byte 101
+.byte 117
+.byte 100
+.byte 111
+.byte 90
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 112
+.byte 114
+.byte 105
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 97
+.byte 115
+.byte 58
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC521:
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 100
+.byte 108
+.byte 121
+.byte 32
+.byte 110
+.byte 101
+.byte 103
+.byte 97
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.LC520:
+.byte 80
+.byte 111
+.byte 115
+.byte 105
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 101
+.byte 120
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 32
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 97
+.byte 110
+.byte 10
+.byte 0
+.align 1
+.LC507:
+.byte 109
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 109
+.byte 97
+.byte 110
+.byte 121
+.byte 32
+.byte 108
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 119
+.byte 114
+.byte 111
+.byte 110
+.byte 103
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC483:
+.byte 83
+.byte 101
+.byte 101
+.byte 107
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 85
+.byte 110
+.byte 100
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 32
+.byte 116
+.byte 104
+.byte 114
+.byte 101
+.byte 115
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 115
+.byte 32
+.byte 85
+.byte 102
+.byte 84
+.byte 104
+.byte 111
+.byte 108
+.byte 100
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 69
+.byte 48
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC480:
+.byte 46
+.byte 46
+.byte 46
+.byte 32
+.byte 110
+.byte 111
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 99
+.byte 114
+.byte 101
+.byte 112
+.byte 97
+.byte 110
+.byte 99
+.byte 105
+.byte 115
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC477:
+.byte 9
+.byte 105
+.byte 110
+.byte 118
+.byte 111
+.byte 108
+.byte 118
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 105
+.byte 110
+.byte 116
+.byte 101
+.byte 114
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 114
+.byte 97
+.byte 116
+.byte 101
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC476:
+.byte 69
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 115
+.byte 32
+.byte 108
+.byte 105
+.byte 107
+.byte 101
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 105
+.byte 110
+.byte 118
+.byte 97
+.byte 108
+.byte 105
+.byte 100
+.byte 97
+.byte 116
+.byte 101
+.byte 32
+.byte 102
+.byte 105
+.byte 110
+.byte 97
+.byte 110
+.byte 99
+.byte 105
+.byte 97
+.byte 108
+.byte 32
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.LC455:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 112
+.byte 111
+.byte 119
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 90
+.byte 94
+.byte 105
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 115
+.byte 109
+.byte 97
+.byte 108
+.byte 108
+.byte 32
+.byte 73
+.byte 110
+.byte 116
+.byte 101
+.byte 103
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 90
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 105
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC452:
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 32
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 109
+.byte 97
+.byte 110
+.byte 121
+.byte 32
+.byte 108
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 119
+.byte 114
+.byte 111
+.byte 110
+.byte 103
+.byte 0
+.align 1
+.LC450:
+.byte 116
+.byte 111
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 117
+.byte 108
+.byte 112
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC449:
+.byte 79
+.byte 98
+.byte 115
+.byte 101
+.byte 114
+.byte 118
+.byte 101
+.byte 100
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 115
+.byte 32
+.byte 114
+.byte 117
+.byte 110
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 0
+.align 1
+.LC448:
+.byte 83
+.byte 113
+.byte 117
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 111
+.byte 111
+.byte 116
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 101
+.byte 105
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC445:
+.byte 83
+.byte 113
+.byte 117
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 111
+.byte 111
+.byte 116
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC440:
+.byte 83
+.byte 113
+.byte 117
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 111
+.byte 111
+.byte 116
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC435:
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 115
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 115
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC434:
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 94
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.LC433:
+.byte 65
+.byte 110
+.byte 111
+.byte 109
+.byte 97
+.byte 108
+.byte 111
+.byte 117
+.byte 115
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 73
+.byte 110
+.byte 116
+.byte 101
+.byte 103
+.byte 101
+.byte 114
+.byte 32
+.byte 60
+.byte 32
+.byte 0
+.align 1
+.LC393:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 119
+.byte 104
+.byte 101
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 100
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC371:
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 40
+.byte 88
+.byte 41
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 110
+.byte 45
+.byte 109
+.byte 111
+.byte 110
+.byte 111
+.byte 116
+.byte 111
+.byte 110
+.byte 105
+.byte 99
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 88
+.byte 32
+.byte 110
+.byte 101
+.byte 97
+.byte 114
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC370:
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 32
+.byte 104
+.byte 97
+.byte 115
+.byte 32
+.byte 112
+.byte 97
+.byte 115
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 97
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 77
+.byte 111
+.byte 110
+.byte 111
+.byte 116
+.byte 111
+.byte 110
+.byte 105
+.byte 99
+.byte 105
+.byte 116
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC353:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 32
+.byte 109
+.byte 111
+.byte 110
+.byte 111
+.byte 116
+.byte 111
+.byte 110
+.byte 105
+.byte 99
+.byte 105
+.byte 116
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC342:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 105
+.byte 102
+.byte 32
+.byte 115
+.byte 113
+.byte 114
+.byte 116
+.byte 40
+.byte 88
+.byte 32
+.byte 42
+.byte 32
+.byte 88
+.byte 41
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 88
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 73
+.byte 110
+.byte 116
+.byte 101
+.byte 103
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 88
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC337:
+.byte 83
+.byte 113
+.byte 117
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 111
+.byte 111
+.byte 116
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 48
+.byte 46
+.byte 48
+.byte 44
+.byte 32
+.byte 45
+.byte 48
+.byte 46
+.byte 48
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 49
+.byte 46
+.byte 48
+.byte 32
+.byte 119
+.byte 114
+.byte 111
+.byte 110
+.byte 103
+.byte 0
+.align 1
+.LC335:
+.byte 10
+.byte 82
+.byte 117
+.byte 110
+.byte 110
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 115
+.byte 113
+.byte 117
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 114
+.byte 111
+.byte 111
+.byte 116
+.byte 40
+.byte 120
+.byte 41
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC334:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 78
+.byte 111
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 117
+.byte 114
+.byte 101
+.byte 115
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 105
+.byte 110
+.byte 116
+.byte 101
+.byte 103
+.byte 101
+.byte 114
+.byte 32
+.byte 112
+.byte 97
+.byte 105
+.byte 114
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC333:
+.byte 88
+.byte 32
+.byte 42
+.byte 32
+.byte 89
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 89
+.byte 32
+.byte 42
+.byte 32
+.byte 88
+.byte 32
+.byte 116
+.byte 114
+.byte 105
+.byte 97
+.byte 108
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 4
+.LC324:
+.long 0
+.long 1074266112
+.align 1
+.LC323:
+.byte 84
+.byte 101
+.byte 115
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 111
+.byte 110
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 114
+.byte 97
+.byte 110
+.byte 100
+.byte 111
+.byte 109
+.byte 32
+.byte 112
+.byte 97
+.byte 105
+.byte 114
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC322:
+.byte 68
+.byte 111
+.byte 101
+.byte 115
+.byte 32
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 99
+.byte 111
+.byte 109
+.byte 109
+.byte 117
+.byte 116
+.byte 101
+.byte 63
+.byte 32
+.byte 32
+.byte 0
+.align 1
+.LC319:
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 40
+.byte 115
+.byte 41
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 103
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 117
+.byte 114
+.byte 101
+.byte 40
+.byte 115
+.byte 41
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 10
+.byte 40
+.byte 110
+.byte 111
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 97
+.byte 98
+.byte 111
+.byte 118
+.byte 101
+.byte 41
+.byte 32
+.byte 99
+.byte 111
+.byte 117
+.byte 110
+.byte 116
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 111
+.byte 110
+.byte 101
+.byte 32
+.byte 102
+.byte 108
+.byte 97
+.byte 119
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 102
+.byte 105
+.byte 110
+.byte 97
+.byte 108
+.byte 32
+.byte 116
+.byte 97
+.byte 108
+.byte 108
+.byte 121
+.byte 32
+.byte 98
+.byte 101
+.byte 108
+.byte 111
+.byte 119
+.byte 0
+.align 1
+.LC317:
+.byte 83
+.byte 116
+.byte 105
+.byte 99
+.byte 107
+.byte 121
+.byte 32
+.byte 98
+.byte 105
+.byte 116
+.byte 32
+.byte 117
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 105
+.byte 110
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 97
+.byte 116
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC316:
+.byte 83
+.byte 116
+.byte 105
+.byte 99
+.byte 107
+.byte 121
+.byte 32
+.byte 98
+.byte 105
+.byte 116
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 97
+.byte 114
+.byte 101
+.byte 110
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 117
+.byte 115
+.byte 101
+.byte 100
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC299:
+.byte 67
+.byte 104
+.byte 101
+.byte 99
+.byte 107
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 115
+.byte 116
+.byte 105
+.byte 99
+.byte 107
+.byte 121
+.byte 32
+.byte 98
+.byte 105
+.byte 116
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC296:
+.byte 40
+.byte 88
+.byte 32
+.byte 45
+.byte 32
+.byte 89
+.byte 41
+.byte 32
+.byte 43
+.byte 32
+.byte 40
+.byte 89
+.byte 32
+.byte 45
+.byte 32
+.byte 88
+.byte 41
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 110
+.byte 32
+.byte 122
+.byte 101
+.byte 114
+.byte 111
+.byte 33
+.byte 10
+.byte 0
+.align 1
+.LC293:
+.byte 65
+.byte 100
+.byte 100
+.byte 105
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 47
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 110
+.byte 101
+.byte 105
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC292:
+.byte 65
+.byte 100
+.byte 100
+.byte 47
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 0
+.align 1
+.LC289:
+.byte 65
+.byte 100
+.byte 100
+.byte 105
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 47
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC282:
+.byte 65
+.byte 100
+.byte 100
+.byte 47
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC277:
+.byte 73
+.byte 110
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 108
+.byte 101
+.byte 116
+.byte 101
+.byte 32
+.byte 99
+.byte 97
+.byte 114
+.byte 114
+.byte 121
+.byte 45
+.byte 112
+.byte 114
+.byte 111
+.byte 112
+.byte 97
+.byte 103
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 65
+.byte 100
+.byte 100
+.byte 105
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 0
+.align 1
+.LC273:
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 42
+.byte 32
+.byte 40
+.byte 32
+.byte 49
+.byte 32
+.byte 47
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 41
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 49
+.byte 0
+.align 1
+.LC271:
+.byte 47
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 101
+.byte 105
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC268:
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC265:
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 0
+.align 1
+.LC262:
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC257:
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 0
+.align 1
+.LC254:
+.byte 42
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 101
+.byte 105
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 112
+.byte 101
+.byte 100
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC253:
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 99
+.byte 104
+.byte 111
+.byte 112
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC250:
+.byte 77
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 105
+.byte 99
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 99
+.byte 111
+.byte 114
+.byte 114
+.byte 101
+.byte 99
+.byte 116
+.byte 108
+.byte 121
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC240:
+.byte 88
+.byte 32
+.byte 42
+.byte 32
+.byte 40
+.byte 49
+.byte 47
+.byte 88
+.byte 41
+.byte 32
+.byte 100
+.byte 105
+.byte 102
+.byte 102
+.byte 101
+.byte 114
+.byte 115
+.byte 32
+.byte 102
+.byte 114
+.byte 111
+.byte 109
+.byte 32
+.byte 49
+.byte 0
+.align 1
+.LC221:
+.byte 67
+.byte 104
+.byte 101
+.byte 99
+.byte 107
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 111
+.byte 110
+.byte 32
+.byte 109
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 121
+.byte 44
+.byte 32
+.byte 100
+.byte 105
+.byte 118
+.byte 105
+.byte 100
+.byte 101
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 97
+.byte 100
+.byte 100
+.byte 47
+.byte 115
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC220:
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 32
+.byte 42
+.byte 44
+.byte 32
+.byte 47
+.byte 44
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 45
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 104
+.byte 97
+.byte 118
+.byte 101
+.byte 32
+.byte 103
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 44
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 121
+.byte 32
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC217:
+.byte 32
+.byte 32
+.byte 46
+.byte 46
+.byte 46
+.byte 32
+.byte 32
+.byte 105
+.byte 102
+.byte 32
+.byte 40
+.byte 88
+.byte 32
+.byte 61
+.byte 61
+.byte 32
+.byte 49
+.byte 46
+.byte 48
+.byte 41
+.byte 32
+.byte 123
+.byte 46
+.byte 46
+.byte 46
+.byte 46
+.byte 46
+.byte 125
+.byte 32
+.byte 101
+.byte 108
+.byte 115
+.byte 101
+.byte 32
+.byte 123
+.byte 46
+.byte 46
+.byte 46
+.byte 47
+.byte 40
+.byte 88
+.byte 45
+.byte 49
+.byte 46
+.byte 48
+.byte 41
+.byte 46
+.byte 46
+.byte 46
+.byte 125
+.byte 10
+.byte 0
+.align 1
+.LC216:
+.byte 32
+.byte 32
+.byte 115
+.byte 117
+.byte 99
+.byte 104
+.byte 32
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 97
+.byte 117
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 97
+.byte 103
+.byte 97
+.byte 105
+.byte 110
+.byte 115
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 122
+.byte 101
+.byte 114
+.byte 111
+.byte 32
+.byte 97
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.LC215:
+.byte 32
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 121
+.byte 105
+.byte 101
+.byte 108
+.byte 100
+.byte 115
+.byte 32
+.byte 32
+.byte 40
+.byte 49
+.byte 45
+.byte 85
+.byte 49
+.byte 41
+.byte 32
+.byte 45
+.byte 32
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 32
+.byte 44
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 101
+.byte 98
+.byte 121
+.byte 32
+.byte 118
+.byte 105
+.byte 116
+.byte 105
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 10
+.byte 0
+.align 1
+.LC214:
+.byte 99
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 115
+.byte 32
+.byte 32
+.byte 40
+.byte 49
+.byte 45
+.byte 85
+.byte 49
+.byte 41
+.byte 32
+.byte 60
+.byte 32
+.byte 49
+.byte 32
+.byte 32
+.byte 97
+.byte 108
+.byte 116
+.byte 104
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 10
+.byte 0
+.align 1
+.LC211:
+.byte 45
+.byte 32
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 115
+.byte 32
+.byte 71
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 68
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 44
+.byte 32
+.byte 115
+.byte 111
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 99
+.byte 101
+.byte 108
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 111
+.byte 98
+.byte 115
+.byte 99
+.byte 117
+.byte 114
+.byte 101
+.byte 100
+.byte 0
+.align 1
+.LC206:
+.byte 42
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 47
+.byte 111
+.byte 114
+.byte 32
+.byte 47
+.byte 32
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 109
+.byte 97
+.byte 110
+.byte 121
+.byte 32
+.byte 108
+.byte 97
+.byte 115
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 119
+.byte 114
+.byte 111
+.byte 110
+.byte 103
+.byte 0
+.align 1
+.LC202:
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 117
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 49
+.byte 47
+.byte 49
+.byte 46
+.byte 48
+.byte 48
+.byte 48
+.byte 46
+.byte 46
+.byte 49
+.byte 32
+.byte 62
+.byte 61
+.byte 32
+.byte 49
+.byte 0
+.align 1
+.LC200:
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 71
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 68
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 44
+.byte 32
+.byte 115
+.byte 111
+.byte 32
+.byte 88
+.byte 47
+.byte 49
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 88
+.byte 0
+.align 1
+.LC195:
+.byte 68
+.byte 105
+.byte 118
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 71
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 68
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 44
+.byte 32
+.byte 115
+.byte 111
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 32
+.byte 101
+.byte 120
+.byte 99
+.byte 101
+.byte 101
+.byte 100
+.byte 32
+.byte 49
+.byte 32
+.byte 117
+.byte 108
+.byte 112
+.byte 10
+.byte 111
+.byte 114
+.byte 32
+.byte 32
+.byte 49
+.byte 47
+.byte 51
+.byte 32
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 32
+.byte 51
+.byte 47
+.byte 57
+.byte 32
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 32
+.byte 57
+.byte 47
+.byte 50
+.byte 55
+.byte 32
+.byte 109
+.byte 97
+.byte 121
+.byte 32
+.byte 100
+.byte 105
+.byte 115
+.byte 97
+.byte 103
+.byte 114
+.byte 101
+.byte 101
+.byte 0
+.align 1
+.LC191:
+.byte 42
+.byte 32
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 109
+.byte 97
+.byte 110
+.byte 121
+.byte 32
+.byte 102
+.byte 105
+.byte 110
+.byte 97
+.byte 108
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 119
+.byte 114
+.byte 111
+.byte 110
+.byte 103
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC189:
+.byte 42
+.byte 32
+.byte 108
+.byte 97
+.byte 99
+.byte 107
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 71
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 68
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 44
+.byte 32
+.byte 115
+.byte 111
+.byte 32
+.byte 49
+.byte 42
+.byte 88
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 88
+.byte 0
+.align 1
+.LC186:
+.byte 10
+.byte 67
+.byte 104
+.byte 101
+.byte 99
+.byte 107
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 103
+.byte 117
+.byte 97
+.byte 114
+.byte 100
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 32
+.byte 105
+.byte 110
+.byte 32
+.byte 42
+.byte 44
+.byte 32
+.byte 47
+.byte 44
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 45
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC185:
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 109
+.byte 97
+.byte 108
+.byte 105
+.byte 122
+.byte 101
+.byte 100
+.byte 44
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 105
+.byte 116
+.byte 32
+.byte 115
+.byte 104
+.byte 111
+.byte 117
+.byte 108
+.byte 100
+.byte 32
+.byte 98
+.byte 101
+.byte 46
+.byte 0
+.align 1
+.LC180:
+.byte 83
+.byte 117
+.byte 98
+.byte 116
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 110
+.byte 111
+.byte 114
+.byte 109
+.byte 97
+.byte 108
+.byte 105
+.byte 122
+.byte 101
+.byte 100
+.byte 32
+.byte 88
+.byte 61
+.byte 89
+.byte 44
+.byte 88
+.byte 43
+.byte 90
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 89
+.byte 43
+.byte 90
+.byte 33
+.byte 0
+.align 1
+.LC176:
+.byte 114
+.byte 111
+.byte 117
+.byte 103
+.byte 104
+.byte 108
+.byte 121
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 101
+.byte 120
+.byte 116
+.byte 114
+.byte 97
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 105
+.byte 102
+.byte 105
+.byte 99
+.byte 97
+.byte 110
+.byte 116
+.byte 32
+.byte 100
+.byte 101
+.byte 99
+.byte 105
+.byte 109
+.byte 97
+.byte 108
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC175:
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 101
+.byte 108
+.byte 121
+.byte 32
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 32
+.byte 97
+.byte 98
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 37
+.byte 103
+.byte 32
+.byte 101
+.byte 120
+.byte 116
+.byte 114
+.byte 97
+.byte 32
+.byte 66
+.byte 45
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 44
+.byte 32
+.byte 105
+.byte 46
+.byte 101
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC174:
+.byte 83
+.byte 111
+.byte 109
+.byte 101
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 101
+.byte 120
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 32
+.byte 97
+.byte 112
+.byte 112
+.byte 101
+.byte 97
+.byte 114
+.byte 32
+.byte 116
+.byte 111
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 101
+.byte 120
+.byte 116
+.byte 114
+.byte 97
+.byte 10
+.byte 0
+.align 1
+.LC168:
+.byte 111
+.byte 102
+.byte 32
+.byte 97
+.byte 110
+.byte 10
+.byte 101
+.byte 120
+.byte 116
+.byte 114
+.byte 97
+.byte 45
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 0
+.align 1
+.LC167:
+.byte 90
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 90
+.byte 50
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 0
+.align 1
+.LC166:
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 101
+.byte 120
+.byte 97
+.byte 99
+.byte 116
+.byte 32
+.byte 114
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 97
+.byte 108
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 97
+.byte 32
+.byte 114
+.byte 101
+.byte 115
+.byte 117
+.byte 108
+.byte 116
+.byte 10
+.byte 0
+.align 1
+.LC165:
+.byte 66
+.byte 101
+.byte 99
+.byte 97
+.byte 117
+.byte 115
+.byte 101
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 117
+.byte 110
+.byte 117
+.byte 115
+.byte 117
+.byte 97
+.byte 108
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 102
+.byte 0
+.align 1
+.LC161:
+.byte 9
+.byte 85
+.byte 50
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 90
+.byte 50
+.byte 32
+.byte 45
+.byte 32
+.byte 85
+.byte 50
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.LC160:
+.byte 9
+.byte 85
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 90
+.byte 49
+.byte 32
+.byte 45
+.byte 32
+.byte 85
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.LC159:
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 0
+.align 1
+.LC158:
+.byte 0
+.align 1
+.LC151:
+.byte 84
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 102
+.byte 101
+.byte 97
+.byte 116
+.byte 117
+.byte 114
+.byte 101
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 102
+.byte 117
+.byte 114
+.byte 116
+.byte 104
+.byte 101
+.byte 114
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC146:
+.byte 80
+.byte 111
+.byte 115
+.byte 115
+.byte 105
+.byte 98
+.byte 108
+.byte 121
+.byte 32
+.byte 115
+.byte 111
+.byte 109
+.byte 101
+.byte 32
+.byte 112
+.byte 97
+.byte 114
+.byte 116
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 0
+.align 1
+.LC145:
+.byte 98
+.byte 121
+.byte 32
+.byte 101
+.byte 120
+.byte 116
+.byte 114
+.byte 97
+.byte 45
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 101
+.byte 32
+.byte 101
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 101
+.byte 116
+.byte 105
+.byte 99
+.byte 32
+.byte 115
+.byte 117
+.byte 98
+.byte 101
+.byte 120
+.byte 112
+.byte 114
+.byte 101
+.byte 115
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 115
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC144:
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 115
+.byte 121
+.byte 109
+.byte 112
+.byte 116
+.byte 111
+.byte 109
+.byte 115
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 105
+.byte 110
+.byte 99
+.byte 111
+.byte 110
+.byte 115
+.byte 105
+.byte 115
+.byte 116
+.byte 101
+.byte 110
+.byte 99
+.byte 105
+.byte 101
+.byte 115
+.byte 32
+.byte 105
+.byte 110
+.byte 116
+.byte 114
+.byte 111
+.byte 100
+.byte 117
+.byte 99
+.byte 101
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC143:
+.byte 114
+.byte 101
+.byte 115
+.byte 112
+.byte 101
+.byte 99
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 108
+.byte 121
+.byte 32
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 44
+.byte 32
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 44
+.byte 10
+.byte 0
+.align 1
+.LC142:
+.byte 68
+.byte 105
+.byte 115
+.byte 97
+.byte 103
+.byte 114
+.byte 101
+.byte 101
+.byte 109
+.byte 101
+.byte 110
+.byte 116
+.byte 115
+.byte 32
+.byte 97
+.byte 109
+.byte 111
+.byte 110
+.byte 103
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 118
+.byte 97
+.byte 108
+.byte 117
+.byte 101
+.byte 115
+.byte 32
+.byte 88
+.byte 49
+.byte 44
+.byte 32
+.byte 89
+.byte 49
+.byte 44
+.byte 32
+.byte 90
+.byte 49
+.byte 44
+.byte 10
+.byte 0
+.align 1
+.LC120:
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 119
+.byte 111
+.byte 114
+.byte 115
+.byte 101
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 110
+.byte 32
+.byte 53
+.byte 32
+.byte 100
+.byte 101
+.byte 99
+.byte 105
+.byte 109
+.byte 97
+.byte 108
+.byte 32
+.byte 102
+.byte 105
+.byte 103
+.byte 117
+.byte 114
+.byte 101
+.byte 115
+.byte 32
+.byte 32
+.byte 0
+.align 1
+.LC118:
+.byte 84
+.byte 104
+.byte 101
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 105
+.byte 102
+.byte 105
+.byte 99
+.byte 97
+.byte 110
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 116
+.byte 104
+.byte 101
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 37
+.byte 102
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC117:
+.byte 108
+.byte 111
+.byte 103
+.byte 97
+.byte 114
+.byte 105
+.byte 116
+.byte 104
+.byte 109
+.byte 105
+.byte 99
+.byte 32
+.byte 101
+.byte 110
+.byte 99
+.byte 111
+.byte 100
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 104
+.byte 97
+.byte 115
+.byte 32
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 99
+.byte 104
+.byte 97
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 101
+.byte 114
+.byte 105
+.byte 122
+.byte 101
+.byte 100
+.byte 32
+.byte 115
+.byte 111
+.byte 108
+.byte 101
+.byte 108
+.byte 121
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 85
+.byte 49
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC114:
+.byte 111
+.byte 102
+.byte 32
+.byte 115
+.byte 105
+.byte 103
+.byte 110
+.byte 105
+.byte 102
+.byte 105
+.byte 99
+.byte 97
+.byte 110
+.byte 116
+.byte 32
+.byte 100
+.byte 105
+.byte 103
+.byte 105
+.byte 116
+.byte 115
+.byte 32
+.byte 98
+.byte 117
+.byte 116
+.byte 44
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 105
+.byte 116
+.byte 115
+.byte 101
+.byte 108
+.byte 102
+.byte 44
+.byte 32
+.byte 116
+.byte 104
+.byte 105
+.byte 115
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 97
+.byte 32
+.byte 109
+.byte 105
+.byte 110
+.byte 111
+.byte 114
+.byte 32
+.byte 102
+.byte 108
+.byte 97
+.byte 119
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC113:
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 99
+.byte 97
+.byte 110
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 98
+.byte 101
+.byte 32
+.byte 99
+.byte 104
+.byte 97
+.byte 114
+.byte 97
+.byte 99
+.byte 116
+.byte 101
+.byte 114
+.byte 105
+.byte 122
+.byte 101
+.byte 100
+.byte 32
+.byte 98
+.byte 121
+.byte 32
+.byte 97
+.byte 110
+.byte 32
+.byte 73
+.byte 110
+.byte 116
+.byte 101
+.byte 103
+.byte 101
+.byte 114
+.byte 32
+.byte 110
+.byte 117
+.byte 109
+.byte 98
+.byte 101
+.byte 114
+.byte 10
+.byte 0
+.align 1
+.LC100:
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 102
+.byte 117
+.byte 122
+.byte 122
+.byte 121
+.byte 44
+.byte 88
+.byte 61
+.byte 49
+.byte 32
+.byte 98
+.byte 117
+.byte 116
+.byte 32
+.byte 88
+.byte 45
+.byte 49
+.byte 47
+.byte 50
+.byte 45
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 0
+.align 1
+.LC96:
+.byte 40
+.byte 49
+.byte 45
+.byte 85
+.byte 49
+.byte 41
+.byte 45
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 60
+.byte 32
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 70
+.byte 65
+.byte 76
+.byte 83
+.byte 69
+.byte 44
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 103
+.byte 46
+.byte 32
+.byte 102
+.byte 97
+.byte 105
+.byte 108
+.byte 115
+.byte 63
+.byte 0
+.align 4
+.LC94:
+.long 0
+.long 1076101120
+.align 1
+.LC89:
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 103
+.byte 111
+.byte 111
+.byte 100
+.byte 32
+.byte 97
+.byte 115
+.byte 32
+.byte 50
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 49
+.byte 48
+.byte 0
+.align 1
+.LC85:
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 116
+.byte 111
+.byte 111
+.byte 32
+.byte 98
+.byte 105
+.byte 103
+.byte 58
+.byte 32
+.byte 114
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 111
+.byte 102
+.byte 102
+.byte 32
+.byte 112
+.byte 114
+.byte 111
+.byte 98
+.byte 108
+.byte 101
+.byte 109
+.byte 115
+.byte 0
+.align 1
+.LC83:
+.byte 77
+.byte 89
+.byte 83
+.byte 84
+.byte 69
+.byte 82
+.byte 89
+.byte 58
+.byte 32
+.byte 114
+.byte 101
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 101
+.byte 100
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC82:
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 105
+.byte 114
+.byte 109
+.byte 101
+.byte 100
+.byte 46
+.byte 10
+.byte 0
+.align 4
+.LC79:
+.long 1202590843
+.long 1065646817
+.align 1
+.LC78:
+.byte 103
+.byte 101
+.byte 116
+.byte 115
+.byte 32
+.byte 98
+.byte 101
+.byte 116
+.byte 116
+.byte 101
+.byte 114
+.byte 32
+.byte 99
+.byte 108
+.byte 111
+.byte 115
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 114
+.byte 101
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 115
+.byte 101
+.byte 112
+.byte 97
+.byte 114
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 85
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC77:
+.byte 99
+.byte 111
+.byte 110
+.byte 102
+.byte 105
+.byte 114
+.byte 109
+.byte 115
+.byte 32
+.byte 99
+.byte 108
+.byte 111
+.byte 115
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 114
+.byte 101
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 115
+.byte 101
+.byte 112
+.byte 97
+.byte 114
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 85
+.byte 49
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC62:
+.byte 82
+.byte 101
+.byte 99
+.byte 97
+.byte 108
+.byte 99
+.byte 117
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 114
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 112
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 10
+.byte 32
+.byte 0
+.align 1
+.LC61:
+.byte 67
+.byte 108
+.byte 111
+.byte 115
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 114
+.byte 101
+.byte 108
+.byte 97
+.byte 116
+.byte 105
+.byte 118
+.byte 101
+.byte 32
+.byte 115
+.byte 101
+.byte 112
+.byte 97
+.byte 114
+.byte 97
+.byte 116
+.byte 105
+.byte 111
+.byte 110
+.byte 32
+.byte 102
+.byte 111
+.byte 117
+.byte 110
+.byte 100
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 85
+.byte 49
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 46
+.byte 55
+.byte 101
+.byte 32
+.byte 46
+.byte 10
+.byte 10
+.byte 0
+.align 1
+.LC55:
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 102
+.byte 32
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC46:
+.byte 83
+.byte 101
+.byte 97
+.byte 114
+.byte 99
+.byte 104
+.byte 105
+.byte 110
+.byte 103
+.byte 32
+.byte 102
+.byte 111
+.byte 114
+.byte 32
+.byte 82
+.byte 97
+.byte 100
+.byte 105
+.byte 120
+.byte 32
+.byte 97
+.byte 110
+.byte 100
+.byte 32
+.byte 80
+.byte 114
+.byte 101
+.byte 99
+.byte 105
+.byte 115
+.byte 105
+.byte 111
+.byte 110
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC45:
+.byte 10
+.byte 0
+.align 1
+.LC44:
+.byte 45
+.byte 49
+.byte 44
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 49
+.byte 47
+.byte 50
+.byte 44
+.byte 32
+.byte 49
+.byte 44
+.byte 32
+.byte 50
+.byte 44
+.byte 32
+.byte 51
+.byte 44
+.byte 32
+.byte 52
+.byte 44
+.byte 32
+.byte 53
+.byte 44
+.byte 32
+.byte 57
+.byte 44
+.byte 32
+.byte 50
+.byte 55
+.byte 44
+.byte 32
+.byte 51
+.byte 50
+.byte 32
+.byte 38
+.byte 32
+.byte 50
+.byte 52
+.byte 48
+.byte 32
+.byte 97
+.byte 114
+.byte 101
+.byte 32
+.byte 79
+.byte 46
+.byte 75
+.byte 46
+.byte 10
+.byte 0
+.align 1
+.LC39:
+.byte 53
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 52
+.byte 43
+.byte 49
+.byte 44
+.byte 32
+.byte 50
+.byte 52
+.byte 48
+.byte 47
+.byte 51
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 56
+.byte 48
+.byte 44
+.byte 32
+.byte 50
+.byte 52
+.byte 48
+.byte 47
+.byte 52
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 54
+.byte 48
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 50
+.byte 52
+.byte 48
+.byte 47
+.byte 53
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 52
+.byte 56
+.byte 0
+.align 1
+.LC35:
+.byte 57
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 51
+.byte 42
+.byte 51
+.byte 44
+.byte 32
+.byte 50
+.byte 55
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 57
+.byte 42
+.byte 51
+.byte 44
+.byte 32
+.byte 51
+.byte 50
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 56
+.byte 42
+.byte 52
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 51
+.byte 50
+.byte 45
+.byte 50
+.byte 55
+.byte 45
+.byte 52
+.byte 45
+.byte 49
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 0
+.align 1
+.LC31:
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 43
+.byte 32
+.byte 40
+.byte 45
+.byte 49
+.byte 41
+.byte 32
+.byte 43
+.byte 32
+.byte 49
+.byte 47
+.byte 50
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 0
+.align 1
+.LC27:
+.byte 45
+.byte 49
+.byte 43
+.byte 49
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 40
+.byte 45
+.byte 49
+.byte 41
+.byte 43
+.byte 97
+.byte 98
+.byte 115
+.byte 40
+.byte 49
+.byte 41
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 45
+.byte 49
+.byte 43
+.byte 40
+.byte 45
+.byte 49
+.byte 41
+.byte 42
+.byte 40
+.byte 45
+.byte 49
+.byte 41
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 0
+.align 1
+.LC23:
+.byte 51
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 50
+.byte 43
+.byte 49
+.byte 44
+.byte 32
+.byte 52
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 51
+.byte 43
+.byte 49
+.byte 44
+.byte 32
+.byte 52
+.byte 43
+.byte 50
+.byte 42
+.byte 40
+.byte 45
+.byte 50
+.byte 41
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 52
+.byte 45
+.byte 51
+.byte 45
+.byte 49
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 0
+.align 4
+.LC21:
+.long -755914244
+.long 1062232653
+.align 1
+.LC20:
+.byte 67
+.byte 111
+.byte 109
+.byte 112
+.byte 97
+.byte 114
+.byte 105
+.byte 115
+.byte 111
+.byte 110
+.byte 32
+.byte 97
+.byte 108
+.byte 108
+.byte 101
+.byte 103
+.byte 101
+.byte 115
+.byte 32
+.byte 116
+.byte 104
+.byte 97
+.byte 116
+.byte 32
+.byte 45
+.byte 48
+.byte 46
+.byte 48
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 78
+.byte 111
+.byte 110
+.byte 45
+.byte 122
+.byte 101
+.byte 114
+.byte 111
+.byte 33
+.byte 10
+.byte 0
+.align 1
+.LC15:
+.byte 48
+.byte 43
+.byte 48
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 49
+.byte 45
+.byte 49
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 49
+.byte 32
+.byte 60
+.byte 61
+.byte 32
+.byte 48
+.byte 44
+.byte 32
+.byte 111
+.byte 114
+.byte 32
+.byte 49
+.byte 43
+.byte 49
+.byte 32
+.byte 33
+.byte 61
+.byte 32
+.byte 50
+.byte 0
+.align 1
+.LC13:
+.byte 80
+.byte 114
+.byte 111
+.byte 103
+.byte 114
+.byte 97
+.byte 109
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 110
+.byte 111
+.byte 119
+.byte 32
+.byte 82
+.byte 85
+.byte 78
+.byte 78
+.byte 73
+.byte 78
+.byte 71
+.byte 32
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 115
+.byte 32
+.byte 111
+.byte 110
+.byte 32
+.byte 115
+.byte 109
+.byte 97
+.byte 108
+.byte 108
+.byte 32
+.byte 105
+.byte 110
+.byte 116
+.byte 101
+.byte 103
+.byte 101
+.byte 114
+.byte 115
+.byte 58
+.byte 10
+.byte 0
+.align 4
+.LC9:
+.long 0
+.long 1072693248
+.align 4
+.LC8:
+.long 0
+.long 0
+.align 1
+.LC3:
+.byte 10
+.byte 42
+.byte 32
+.byte 42
+.byte 32
+.byte 42
+.byte 32
+.byte 70
+.byte 76
+.byte 79
+.byte 65
+.byte 84
+.byte 73
+.byte 78
+.byte 71
+.byte 45
+.byte 80
+.byte 79
+.byte 73
+.byte 78
+.byte 84
+.byte 32
+.byte 69
+.byte 82
+.byte 82
+.byte 79
+.byte 82
+.byte 32
+.byte 42
+.byte 32
+.byte 42
+.byte 32
+.byte 42
+.byte 10
+.byte 0
+.text
+.ident "LCC: 4.1"
diff --git a/lcc/x86/linux/tst/sort.1bk b/lcc/x86/linux/tst/sort.1bk
new file mode 100755
index 0000000..380d529
--- /dev/null
+++ b/lcc/x86/linux/tst/sort.1bk
@@ -0,0 +1,20 @@
+exchange(1,9)
+exchange(3,7)
+exchange(5,6)
+exchange(0,5)
+exchange(0,3)
+exchange(0,0)
+exchange(1,2)
+exchange(6,6)
+exchange(8,9)
+exchange(7,8)
+-51
+-1
+0
+1
+3
+10
+18
+32
+567
+789
diff --git a/lcc/x86/linux/tst/sort.2bk b/lcc/x86/linux/tst/sort.2bk
new file mode 100755
index 0000000..27488a1
--- /dev/null
+++ b/lcc/x86/linux/tst/sort.2bk
@@ -0,0 +1,5 @@
+tst/sort.c:23: warning: missing return value
+tst/sort.c:30: warning: missing return value
+tst/sort.c:37: warning: missing return value
+tst/sort.c:41: warning: missing return value
+tst/sort.c:65: warning: missing return value
diff --git a/lcc/x86/linux/tst/sort.sbk b/lcc/x86/linux/tst/sort.sbk
new file mode 100755
index 0000000..11dbcdd
--- /dev/null
+++ b/lcc/x86/linux/tst/sort.sbk
@@ -0,0 +1,330 @@
+.data
+.globl in
+.align 4
+.type in,@object
+in:
+.long 10
+.long 32
+.long -1
+.long 567
+.long 3
+.long 18
+.long 1
+.long -51
+.long 789
+.long 0
+.size in,40
+.globl main
+.text
+.align 16
+.type main,@function
+main:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $4,%esp
+pushl $10
+pushl $in
+call sort
+addl $8,%esp
+movl $0,-4(%ebp)
+jmp .LC5
+.LC2:
+movl -4(%ebp),%edi
+pushl in(,%edi,4)
+call putd
+addl $4,%esp
+pushl $10
+call putchar
+addl $4,%esp
+.LC3:
+incl -4(%ebp)
+.LC5:
+movl -4(%ebp),%edi
+cmpl $10,%edi
+jb .LC2
+movl $0,%eax
+.LC1:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf6:
+.size main,.Lf6-main
+.globl putd
+.align 16
+.type putd,@function
+putd:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+cmpl $0,20(%ebp)
+jge .LC8
+pushl $45
+call putchar
+addl $4,%esp
+negl 20(%ebp)
+.LC8:
+movl 20(%ebp),%eax
+movl $10,%ecx
+cdq
+idivl %ecx
+cmpl $0,%eax
+je .LC10
+movl 20(%ebp),%eax
+movl $10,%ecx
+cdq
+idivl %ecx
+pushl %eax
+call putd
+addl $4,%esp
+.LC10:
+movl 20(%ebp),%eax
+movl $10,%ecx
+cdq
+idivl %ecx
+leal 48(%edx),%edi
+pushl %edi
+call putchar
+addl $4,%esp
+movl $0,%eax
+.LC7:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf12:
+.size putd,.Lf12-putd
+.globl sort
+.align 16
+.type sort,@function
+sort:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl 24(%ebp),%edi
+subl $1,%edi
+movl %edi,24(%ebp)
+pushl %edi
+pushl $0
+movl 20(%ebp),%edi
+movl %edi,xx
+pushl %edi
+call quick
+addl $12,%esp
+movl $0,%eax
+.LC13:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf14:
+.size sort,.Lf14-sort
+.globl quick
+.align 16
+.type quick,@function
+quick:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $4,%esp
+movl 28(%ebp),%edi
+cmpl %edi,24(%ebp)
+jl .LC16
+jmp .LC15
+.LC16:
+pushl 28(%ebp)
+pushl 24(%ebp)
+pushl 20(%ebp)
+call partition
+addl $12,%esp
+movl %eax,-4(%ebp)
+movl -4(%ebp),%edi
+subl $1,%edi
+pushl %edi
+pushl 24(%ebp)
+pushl 20(%ebp)
+call quick
+addl $12,%esp
+pushl 28(%ebp)
+movl -4(%ebp),%edi
+leal 1(%edi),%edi
+pushl %edi
+pushl 20(%ebp)
+call quick
+addl $12,%esp
+movl $0,%eax
+.LC15:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf18:
+.size quick,.Lf18-quick
+.globl partition
+.align 16
+.type partition,@function
+partition:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $8,%esp
+incl 28(%ebp)
+movl 24(%ebp),%edi
+movl %edi,-8(%ebp)
+movl -8(%ebp),%edi
+movl 20(%ebp),%esi
+movl (%esi,%edi,4),%edi
+movl %edi,-4(%ebp)
+jmp .LC21
+.LC20:
+incl 24(%ebp)
+jmp .LC24
+.LC23:
+incl 24(%ebp)
+.LC24:
+movl 24(%ebp),%edi
+movl 20(%ebp),%esi
+movl -4(%ebp),%ebx
+cmpl %ebx,(%esi,%edi,4)
+jl .LC23
+decl 28(%ebp)
+jmp .LC27
+.LC26:
+decl 28(%ebp)
+.LC27:
+movl 28(%ebp),%edi
+movl 20(%ebp),%esi
+movl -4(%ebp),%ebx
+cmpl %ebx,(%esi,%edi,4)
+jg .LC26
+movl 28(%ebp),%edi
+cmpl %edi,24(%ebp)
+jge .LC29
+movl 20(%ebp),%edi
+movl 28(%ebp),%esi
+leal (%edi,%esi,4),%esi
+pushl %esi
+movl 24(%ebp),%esi
+leal (%edi,%esi,4),%edi
+pushl %edi
+call exchange
+addl $8,%esp
+.LC29:
+.LC21:
+movl 28(%ebp),%edi
+cmpl %edi,24(%ebp)
+jl .LC20
+movl 20(%ebp),%edi
+movl 28(%ebp),%esi
+leal (%edi,%esi,4),%esi
+pushl %esi
+movl -8(%ebp),%esi
+leal (%edi,%esi,4),%edi
+pushl %edi
+call exchange
+addl $8,%esp
+movl 28(%ebp),%eax
+.LC19:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf31:
+.size partition,.Lf31-partition
+.globl exchange
+.align 16
+.type exchange,@function
+exchange:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $4,%esp
+movl xx,%edi
+movl $4,%esi
+movl 24(%ebp),%ebx
+subl %edi,%ebx
+movl %ebx,%eax
+movl %esi,%ecx
+cdq
+idivl %ecx
+pushl %eax
+movl 20(%ebp),%ebx
+subl %edi,%ebx
+movl %ebx,%eax
+movl %esi,%ecx
+cdq
+idivl %ecx
+pushl %eax
+pushl $.LC33
+call printf
+addl $12,%esp
+movl 20(%ebp),%edi
+movl (,%edi),%esi
+movl %esi,-4(%ebp)
+movl 24(%ebp),%esi
+movl (,%esi),%esi
+movl %esi,(,%edi)
+movl 24(%ebp),%edi
+movl -4(%ebp),%esi
+movl %esi,(,%edi)
+movl $0,%eax
+.LC32:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf34:
+.size exchange,.Lf34-exchange
+.bss
+.globl xx
+.align 4
+.type xx,@object
+.size xx,4
+.comm xx,4
+.data
+.align 1
+.LC33:
+.byte 101
+.byte 120
+.byte 99
+.byte 104
+.byte 97
+.byte 110
+.byte 103
+.byte 101
+.byte 40
+.byte 37
+.byte 100
+.byte 44
+.byte 37
+.byte 100
+.byte 41
+.byte 10
+.byte 0
+.text
+.ident "LCC: 4.1"
diff --git a/lcc/x86/linux/tst/spill.1bk b/lcc/x86/linux/tst/spill.1bk
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/x86/linux/tst/spill.1bk
diff --git a/lcc/x86/linux/tst/spill.2bk b/lcc/x86/linux/tst/spill.2bk
new file mode 100755
index 0000000..f7e3521
--- /dev/null
+++ b/lcc/x86/linux/tst/spill.2bk
@@ -0,0 +1,6 @@
+tst/spill.c:1: warning: missing return value
+tst/spill.c:3: warning: missing return value
+tst/spill.c:5: warning: missing return value
+tst/spill.c:7: warning: missing return value
+tst/spill.c:9: warning: missing return value
+tst/spill.c:17: warning: missing return value
diff --git a/lcc/x86/linux/tst/spill.sbk b/lcc/x86/linux/tst/spill.sbk
new file mode 100755
index 0000000..13799ab
--- /dev/null
+++ b/lcc/x86/linux/tst/spill.sbk
@@ -0,0 +1,282 @@
+.globl main
+.text
+.align 16
+.type main,@function
+main:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl $0,%eax
+.LC1:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf2:
+.size main,.Lf2-main
+.globl f
+.align 16
+.type f,@function
+f:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+call f
+movl %eax,%edi
+call f
+leal (%eax,%edi),%edi
+movl %edi,20(%ebp)
+movl $0,%eax
+.LC3:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf4:
+.size f,.Lf4-f
+.globl f2
+.align 16
+.type f2,@function
+f2:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $4,%esp
+call f
+movl %eax,%edi
+cmpl $0,20(%ebp)
+je .LC7
+call f
+movl %eax,%esi
+movl %esi,-4(%ebp)
+jmp .LC8
+.LC7:
+movl $1,-4(%ebp)
+.LC8:
+movl -4(%ebp),%esi
+leal (%esi,%edi),%edi
+movl %edi,20(%ebp)
+movl $0,%eax
+.LC5:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf9:
+.size f2,.Lf9-f2
+.globl f3
+.align 16
+.type f3,@function
+f3:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $44,%esp
+movl $0,-4(%ebp)
+movl $0,-8(%ebp)
+movl $0,-12(%ebp)
+movl $0,-16(%ebp)
+movl $0,-20(%ebp)
+movl $0,-24(%ebp)
+movl $0,-28(%ebp)
+movl $0,-32(%ebp)
+movl $0,-36(%ebp)
+movl $0,-40(%ebp)
+movl 24(%ebp),%edi
+leal 4(%edi),%esi
+movl %esi,24(%ebp)
+cmpl $0,20(%ebp)
+je .LC12
+call f
+movl %eax,%esi
+movl %esi,-44(%ebp)
+jmp .LC13
+.LC12:
+movl $0,-44(%ebp)
+.LC13:
+movl -44(%ebp),%esi
+movl %esi,(,%edi)
+movl $0,%eax
+.LC10:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf14:
+.size f3,.Lf14-f3
+.globl f4
+.align 16
+.type f4,@function
+f4:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $52,%esp
+movl $0,-4(%ebp)
+movl $0,-8(%ebp)
+movl $0,-12(%ebp)
+movl $0,-16(%ebp)
+movl $0,-20(%ebp)
+movl $0,-24(%ebp)
+movl i,%edi
+leal (,%edi,8),%esi
+fldl a(%esi)
+fstpl -36(%ebp)
+fldl b(%esi)
+fstpl -44(%ebp)
+fldl -36(%ebp)
+faddl -44(%ebp)
+fldl .LC19
+fcompp
+fstsw %ax
+sahf
+je .LC17
+cmpl $0,%edi
+je .LC17
+fldl -36(%ebp)
+fsubl -44(%ebp)
+fldl .LC19
+fcompp
+fstsw %ax
+sahf
+je .LC17
+movl $1,-28(%ebp)
+jmp .LC18
+.LC17:
+movl $0,-28(%ebp)
+.LC18:
+movl -28(%ebp),%edi
+movl %edi,i
+movl $0,%eax
+.LC15:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf20:
+.size f4,.Lf20-f4
+.globl f5
+.align 16
+.type f5,@function
+f5:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl k,%edi
+movl m,%esi
+movl A,%ebx
+movl %edi,%edx
+imull %esi,%edx
+leal (%ebx,%edx,8),%edx
+movl j,%ecx
+movl %ecx,%eax
+imull %esi,%eax
+leal (%ebx,%eax,8),%esi
+movl n,%ebx
+movl B,%eax
+imull %ebx,%edi
+leal (%eax,%edi,8),%edi
+imull %ebx,%ecx
+leal (%eax,%ecx,8),%ebx
+fldl (,%edx)
+fmull (,%esi)
+fldl (,%edi)
+fmull (,%ebx)
+faddp %st(1),%st
+fstpl x
+fldl (,%edx)
+fmull (,%ebx)
+fldl (,%edi)
+fmull (,%esi)
+fsubp %st(1),%st
+fstpl x
+movl $0,%eax
+.LC21:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf22:
+.size f5,.Lf22-f5
+.bss
+.globl x
+.align 4
+.type x,@object
+.size x,8
+.comm x,8
+.globl B
+.align 4
+.type B,@object
+.size B,4
+.comm B,4
+.globl A
+.align 4
+.type A,@object
+.size A,4
+.comm A,4
+.globl n
+.align 4
+.type n,@object
+.size n,4
+.comm n,4
+.globl m
+.align 4
+.type m,@object
+.size m,4
+.comm m,4
+.globl k
+.align 4
+.type k,@object
+.size k,4
+.comm k,4
+.globl j
+.align 4
+.type j,@object
+.size j,4
+.comm j,4
+.globl i
+.align 4
+.type i,@object
+.size i,4
+.comm i,4
+.globl b
+.align 4
+.type b,@object
+.size b,80
+.comm b,80
+.globl a
+.align 4
+.type a,@object
+.size a,80
+.comm a,80
+.data
+.align 4
+.LC19:
+.long 0
+.long 0
+.text
+.ident "LCC: 4.1"
diff --git a/lcc/x86/linux/tst/stdarg.1bk b/lcc/x86/linux/tst/stdarg.1bk
new file mode 100755
index 0000000..097aef7
--- /dev/null
+++ b/lcc/x86/linux/tst/stdarg.1bk
@@ -0,0 +1,6 @@
+test 1
+test 2
+test 3
+test 4
+test 5.000000
+{1 2 3 4} {1 2 3 4} {1 2 3 4} {1 2 3 4} {1 2 3 4} {1 2 3 4}
diff --git a/lcc/x86/linux/tst/stdarg.2bk b/lcc/x86/linux/tst/stdarg.2bk
new file mode 100755
index 0000000..a832cf9
--- /dev/null
+++ b/lcc/x86/linux/tst/stdarg.2bk
@@ -0,0 +1 @@
+tst/stdarg.c:51: warning: missing return value
diff --git a/lcc/x86/linux/tst/stdarg.sbk b/lcc/x86/linux/tst/stdarg.sbk
new file mode 100755
index 0000000..f1001e6
--- /dev/null
+++ b/lcc/x86/linux/tst/stdarg.sbk
@@ -0,0 +1,395 @@
+.data
+.globl x
+.align 4
+.type x,@object
+.size x,16
+x:
+.long 1
+.long 2
+.long 3
+.long 4
+.globl main
+.text
+.align 16
+.type main,@function
+main:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $8,%esp
+pushl $.LC2
+call print
+addl $4,%esp
+pushl $.LC4
+pushl $.LC3
+call print
+addl $8,%esp
+pushl $10
+pushl $3
+pushl $.LC5
+call print
+addl $12,%esp
+pushl $10
+pushl $4
+pushl $.LC8
+pushl $.LC7
+pushl $.LC6
+call print
+addl $20,%esp
+pushl $10
+fldl .LC10
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC8
+pushl $.LC7
+pushl $.LC9
+call print
+addl $24,%esp
+leal x,%edi
+movl %edi,-8(%ebp)
+movl %edi,%esi
+movl %esi,-4(%ebp)
+subl $16,%esp
+movl %esp,%edi
+movl $16,%ecx
+rep
+movsb
+movl -8(%ebp),%edi
+movl %edi,%esi
+subl $16,%esp
+movl %esp,%edi
+movl $16,%ecx
+rep
+movsb
+movl -8(%ebp),%edi
+movl %edi,%esi
+subl $16,%esp
+movl %esp,%edi
+movl $16,%ecx
+rep
+movsb
+movl -8(%ebp),%edi
+movl %edi,%esi
+subl $16,%esp
+movl %esp,%edi
+movl $16,%ecx
+rep
+movsb
+movl -8(%ebp),%edi
+movl %edi,%esi
+subl $16,%esp
+movl %esp,%edi
+movl $16,%ecx
+rep
+movsb
+movl -8(%ebp),%edi
+movl %edi,%esi
+subl $16,%esp
+movl %esp,%edi
+movl $16,%ecx
+rep
+movsb
+pushl $.LC11
+call print
+addl $100,%esp
+movl $0,%eax
+.LC1:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf12:
+.size main,.Lf12-main
+.globl print
+.align 16
+.type print,@function
+print:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $28,%esp
+leal 24(%ebp),%edi
+movl %edi,-4(%ebp)
+jmp .LC19
+.LC16:
+movl 20(%ebp),%edi
+movsbl (,%edi),%edi
+cmpl $37,%edi
+jne .LC20
+movl 20(%ebp),%edi
+leal 1(%edi),%edi
+movl %edi,20(%ebp)
+movsbl (,%edi),%edi
+movl %edi,-8(%ebp)
+movl -8(%ebp),%edi
+cmpl $115,%edi
+je .LC36
+cmpl $115,%edi
+jg .LC41
+.LC40:
+movl -8(%ebp),%edi
+cmpl $98,%edi
+jl .LC22
+cmpl $102,%edi
+jg .LC22
+jmp *.LC42-392(,%edi,4)
+.data
+.align 4
+.LC42:
+.long .LC25
+.long .LC30
+.long .LC32
+.long .LC22
+.long .LC38
+.text
+.LC41:
+cmpl $119,-8(%ebp)
+je .LC34
+jmp .LC22
+.LC25:
+movl -4(%ebp),%edi
+leal 16(%edi),%edi
+movl %edi,-28(%ebp)
+movl %edi,-4(%ebp)
+leal -24(%ebp),%edi
+movl -28(%ebp),%esi
+leal -16(%esi),%esi
+movl $16,%ecx
+rep
+movsb
+pushl -12(%ebp)
+pushl -16(%ebp)
+pushl -20(%ebp)
+pushl -24(%ebp)
+pushl $.LC26
+call printf
+addl $20,%esp
+jmp .LC21
+.LC30:
+movl -4(%ebp),%edi
+leal 4(%edi),%edi
+movl %edi,-4(%ebp)
+movsbl -4(%edi),%edi
+pushl %edi
+pushl $.LC31
+call printf
+addl $8,%esp
+jmp .LC21
+.LC32:
+movl -4(%ebp),%edi
+leal 4(%edi),%edi
+movl %edi,-4(%ebp)
+pushl -4(%edi)
+pushl $.LC33
+call printf
+addl $8,%esp
+jmp .LC21
+.LC34:
+movl -4(%ebp),%edi
+leal 4(%edi),%edi
+movl %edi,-4(%ebp)
+movswl -4(%edi),%edi
+pushl %edi
+pushl $.LC35
+call printf
+addl $8,%esp
+jmp .LC21
+.LC36:
+movl -4(%ebp),%edi
+leal 4(%edi),%edi
+movl %edi,-4(%ebp)
+pushl -4(%edi)
+pushl $.LC37
+call printf
+addl $8,%esp
+jmp .LC21
+.LC38:
+movl -4(%ebp),%edi
+leal 8(%edi),%edi
+movl %edi,-4(%ebp)
+fldl -8(%edi)
+subl $8,%esp
+fstpl (%esp)
+pushl $.LC39
+call printf
+addl $12,%esp
+jmp .LC21
+.LC22:
+movl 20(%ebp),%edi
+movsbl (,%edi),%edi
+pushl %edi
+pushl $.LC31
+call printf
+addl $8,%esp
+jmp .LC21
+.LC20:
+movl 20(%ebp),%edi
+movsbl (,%edi),%edi
+pushl %edi
+pushl $.LC31
+call printf
+addl $8,%esp
+.LC21:
+.LC17:
+incl 20(%ebp)
+.LC19:
+movl 20(%ebp),%edi
+movsbl (,%edi),%edi
+cmpl $0,%edi
+jne .LC16
+movl $0,%eax
+.LC13:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf44:
+.size print,.Lf44-print
+.data
+.align 1
+.LC39:
+.byte 37
+.byte 102
+.byte 0
+.align 1
+.LC37:
+.byte 37
+.byte 115
+.byte 0
+.align 1
+.LC35:
+.byte 37
+.byte 120
+.byte 0
+.align 1
+.LC33:
+.byte 37
+.byte 100
+.byte 0
+.align 1
+.LC31:
+.byte 37
+.byte 99
+.byte 0
+.align 1
+.LC26:
+.byte 123
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 125
+.byte 0
+.align 1
+.LC11:
+.byte 37
+.byte 98
+.byte 32
+.byte 37
+.byte 98
+.byte 32
+.byte 37
+.byte 98
+.byte 32
+.byte 37
+.byte 98
+.byte 32
+.byte 37
+.byte 98
+.byte 32
+.byte 37
+.byte 98
+.byte 10
+.byte 0
+.align 4
+.LC10:
+.long 0
+.long 1075052544
+.align 1
+.LC9:
+.byte 37
+.byte 115
+.byte 37
+.byte 115
+.byte 32
+.byte 37
+.byte 102
+.byte 37
+.byte 99
+.byte 0
+.align 1
+.LC8:
+.byte 115
+.byte 116
+.byte 0
+.align 1
+.LC7:
+.byte 116
+.byte 101
+.byte 0
+.align 1
+.LC6:
+.byte 37
+.byte 115
+.byte 37
+.byte 115
+.byte 32
+.byte 37
+.byte 119
+.byte 37
+.byte 99
+.byte 0
+.align 1
+.LC5:
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 37
+.byte 100
+.byte 37
+.byte 99
+.byte 0
+.align 1
+.LC4:
+.byte 50
+.byte 0
+.align 1
+.LC3:
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.LC2:
+.byte 116
+.byte 101
+.byte 115
+.byte 116
+.byte 32
+.byte 49
+.byte 10
+.byte 0
+.text
+.ident "LCC: 4.1"
diff --git a/lcc/x86/linux/tst/struct.1bk b/lcc/x86/linux/tst/struct.1bk
new file mode 100755
index 0000000..2358779
--- /dev/null
+++ b/lcc/x86/linux/tst/struct.1bk
@@ -0,0 +1,5 @@
+(-1,-1) is not within [10,10; 310,310]
+(1,1) is not within [10,10; 310,310]
+(20,300) is within [10,10; 310,310]
+(500,400) is not within [10,10; 310,310]
+ab
diff --git a/lcc/x86/linux/tst/struct.2bk b/lcc/x86/linux/tst/struct.2bk
new file mode 100755
index 0000000..8a01bb1
--- /dev/null
+++ b/lcc/x86/linux/tst/struct.2bk
@@ -0,0 +1,2 @@
+tst/struct.c:49: warning: missing return value
+tst/struct.c:68: warning: missing return value
diff --git a/lcc/x86/linux/tst/struct.sbk b/lcc/x86/linux/tst/struct.sbk
new file mode 100755
index 0000000..7c5b58b
--- /dev/null
+++ b/lcc/x86/linux/tst/struct.sbk
@@ -0,0 +1,477 @@
+.globl addpoint
+.text
+.align 16
+.type addpoint,@function
+addpoint:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl 32(%ebp),%edi
+addl %edi,24(%ebp)
+movl 36(%ebp),%edi
+addl %edi,28(%ebp)
+movl 20(%ebp),%edi
+leal 24(%ebp),%esi
+movl $8,%ecx
+rep
+movsb
+.LC1:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf5:
+.size addpoint,.Lf5-addpoint
+.globl canonrect
+.align 16
+.type canonrect,@function
+canonrect:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $32,%esp
+movl 32(%ebp),%edi
+cmpl %edi,24(%ebp)
+jge .LC11
+movl 24(%ebp),%edi
+movl %edi,-20(%ebp)
+jmp .LC12
+.LC11:
+movl 32(%ebp),%edi
+movl %edi,-20(%ebp)
+.LC12:
+movl -20(%ebp),%edi
+movl %edi,-16(%ebp)
+movl 36(%ebp),%edi
+cmpl %edi,28(%ebp)
+jge .LC21
+movl 28(%ebp),%edi
+movl %edi,-24(%ebp)
+jmp .LC22
+.LC21:
+movl 36(%ebp),%edi
+movl %edi,-24(%ebp)
+.LC22:
+movl -24(%ebp),%edi
+movl %edi,-12(%ebp)
+movl 32(%ebp),%edi
+cmpl %edi,24(%ebp)
+jle .LC27
+movl 24(%ebp),%edi
+movl %edi,-28(%ebp)
+jmp .LC28
+.LC27:
+movl 32(%ebp),%edi
+movl %edi,-28(%ebp)
+.LC28:
+movl -28(%ebp),%edi
+movl %edi,-8(%ebp)
+movl 36(%ebp),%edi
+cmpl %edi,28(%ebp)
+jle .LC38
+movl 28(%ebp),%edi
+movl %edi,-32(%ebp)
+jmp .LC39
+.LC38:
+movl 36(%ebp),%edi
+movl %edi,-32(%ebp)
+.LC39:
+movl -32(%ebp),%edi
+movl %edi,-4(%ebp)
+movl 20(%ebp),%edi
+leal -16(%ebp),%esi
+movl $16,%ecx
+rep
+movsb
+.LC6:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf40:
+.size canonrect,.Lf40-canonrect
+.globl makepoint
+.align 16
+.type makepoint,@function
+makepoint:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $8,%esp
+movl 24(%ebp),%edi
+movl %edi,-8(%ebp)
+movl 28(%ebp),%edi
+movl %edi,-4(%ebp)
+movl 20(%ebp),%edi
+leal -8(%ebp),%esi
+movl $8,%ecx
+rep
+movsb
+.LC41:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf44:
+.size makepoint,.Lf44-makepoint
+.globl makerect
+.align 16
+.type makerect,@function
+makerect:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $16,%esp
+leal -16(%ebp),%edi
+leal 24(%ebp),%esi
+movl $8,%ecx
+rep
+movsb
+leal -8(%ebp),%edi
+leal 32(%ebp),%esi
+movl $8,%ecx
+rep
+movsb
+leal -16(%ebp),%esi
+subl $16,%esp
+movl %esp,%edi
+movl $16,%ecx
+rep
+movsb
+pushl 20(%ebp)
+call canonrect
+addl $20,%esp
+.LC45:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf48:
+.size makerect,.Lf48-makerect
+.globl ptinrect
+.align 16
+.type ptinrect,@function
+ptinrect:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $4,%esp
+movl 20(%ebp),%edi
+cmpl 28(%ebp),%edi
+jl .LC57
+cmpl 36(%ebp),%edi
+jge .LC57
+movl 32(%ebp),%edi
+cmpl %edi,24(%ebp)
+jl .LC57
+movl 40(%ebp),%edi
+cmpl %edi,24(%ebp)
+jge .LC57
+movl $1,-4(%ebp)
+jmp .LC58
+.LC57:
+movl $0,-4(%ebp)
+.LC58:
+movl -4(%ebp),%eax
+.LC49:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf59:
+.size ptinrect,.Lf59-ptinrect
+.data
+.globl y
+.align 4
+.type y,@object
+.size y,4
+y:
+.byte 97
+.byte 98
+.byte 0
+.space 1
+.globl odd
+.text
+.align 16
+.type odd,@function
+odd:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $4,%esp
+leal -4(%ebp),%edi
+leal 20(%ebp),%esi
+movl $4,%ecx
+rep
+movsb
+leal -4(%ebp),%edi
+pushl %edi
+pushl $.LC61
+call printf
+addl $8,%esp
+movl $0,%eax
+.LC60:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf62:
+.size odd,.Lf62-odd
+.data
+.align 4
+.LC64:
+.long 0
+.long 0
+.align 4
+.LC65:
+.long 320
+.long 320
+.align 4
+.LC66:
+.long -1
+.long -1
+.long 1
+.long 1
+.long 20
+.long 300
+.long 500
+.long 400
+.globl main
+.text
+.align 16
+.type main,@function
+main:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $108,%esp
+leal -68(%ebp),%edi
+leal .LC64,%esi
+movl $8,%ecx
+rep
+movsb
+leal -76(%ebp),%edi
+leal .LC65,%esi
+movl $8,%ecx
+rep
+movsb
+leal -36(%ebp),%edi
+leal .LC66,%esi
+movl $32,%ecx
+rep
+movsb
+pushl $-10
+pushl $-10
+leal -84(%ebp),%edi
+pushl %edi
+call makepoint
+addl $12,%esp
+leal -84(%ebp),%esi
+subl $8,%esp
+movl %esp,%edi
+movl $8,%ecx
+rep
+movsb
+leal -76(%ebp),%esi
+subl $8,%esp
+movl %esp,%edi
+movl $8,%ecx
+rep
+movsb
+leal -92(%ebp),%edi
+pushl %edi
+call addpoint
+addl $20,%esp
+pushl $10
+pushl $10
+leal -100(%ebp),%edi
+pushl %edi
+call makepoint
+addl $12,%esp
+leal -100(%ebp),%esi
+subl $8,%esp
+movl %esp,%edi
+movl $8,%ecx
+rep
+movsb
+leal -68(%ebp),%esi
+subl $8,%esp
+movl %esp,%edi
+movl $8,%ecx
+rep
+movsb
+leal -108(%ebp),%edi
+pushl %edi
+call addpoint
+addl $20,%esp
+leal -108(%ebp),%esi
+subl $8,%esp
+movl %esp,%edi
+movl $8,%ecx
+rep
+movsb
+leal -92(%ebp),%esi
+subl $8,%esp
+movl %esp,%edi
+movl $8,%ecx
+rep
+movsb
+leal -52(%ebp),%edi
+pushl %edi
+call makerect
+addl $20,%esp
+movl $0,-4(%ebp)
+jmp .LC70
+.LC67:
+movl -4(%ebp),%edi
+leal (,%edi,8),%edi
+leal -32(%ebp),%esi
+pushl (%esi,%edi)
+leal -36(%ebp),%esi
+pushl (%esi,%edi)
+leal -60(%ebp),%edi
+pushl %edi
+call makepoint
+addl $12,%esp
+pushl -56(%ebp)
+movl -4(%ebp),%edi
+leal -36(%ebp),%esi
+pushl (%esi,%edi,8)
+pushl $.LC71
+call printf
+addl $12,%esp
+leal -52(%ebp),%esi
+subl $16,%esp
+movl %esp,%edi
+movl $16,%ecx
+rep
+movsb
+leal -60(%ebp),%esi
+subl $8,%esp
+movl %esp,%edi
+movl $8,%ecx
+rep
+movsb
+call ptinrect
+addl $24,%esp
+cmpl $0,%eax
+jne .LC74
+pushl $.LC76
+call printf
+addl $4,%esp
+.LC74:
+pushl -40(%ebp)
+pushl -44(%ebp)
+pushl -48(%ebp)
+pushl -52(%ebp)
+pushl $.LC77
+call printf
+addl $20,%esp
+.LC68:
+incl -4(%ebp)
+.LC70:
+movl -4(%ebp),%edi
+cmpl $4,%edi
+jb .LC67
+leal y,%esi
+subl $4,%esp
+movl %esp,%edi
+movl $4,%ecx
+rep
+movsb
+call odd
+addl $4,%esp
+pushl $0
+call exit
+addl $4,%esp
+movl $0,%eax
+.LC63:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf82:
+.size main,.Lf82-main
+.data
+.align 1
+.LC77:
+.byte 119
+.byte 105
+.byte 116
+.byte 104
+.byte 105
+.byte 110
+.byte 32
+.byte 91
+.byte 37
+.byte 100
+.byte 44
+.byte 37
+.byte 100
+.byte 59
+.byte 32
+.byte 37
+.byte 100
+.byte 44
+.byte 37
+.byte 100
+.byte 93
+.byte 10
+.byte 0
+.align 1
+.LC76:
+.byte 110
+.byte 111
+.byte 116
+.byte 32
+.byte 0
+.align 1
+.LC71:
+.byte 40
+.byte 37
+.byte 100
+.byte 44
+.byte 37
+.byte 100
+.byte 41
+.byte 32
+.byte 105
+.byte 115
+.byte 32
+.byte 0
+.align 1
+.LC61:
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.text
+.ident "LCC: 4.1"
diff --git a/lcc/x86/linux/tst/switch.1bk b/lcc/x86/linux/tst/switch.1bk
new file mode 100755
index 0000000..559e8e3
--- /dev/null
+++ b/lcc/x86/linux/tst/switch.1bk
@@ -0,0 +1,76 @@
+b = 0x8
+f = 0xc
+n = 0xa
+r = 0xd
+t = 0x9
+v = 0xb
+x = 0x78
+f:
+x = 0
+x = 1
+x = 2
+x = 2
+x = 2
+x = 2
+x = 2
+x = 7
+x = 8
+x = 9
+x = 9
+x = 9
+x = 9
+x = 9
+x = 9
+x = 9
+x = 16
+x = 17
+x = 18
+x = 19
+x = 20
+g:
+1 1
+1 2
+2 3
+2 4
+2 5
+3 6
+d 6
+3 7
+d 7
+3 8
+d 8
+d 9
+d 10
+h:
+i = 8
+i = 16
+i = 120
+i = 128
+i = 248
+i = 264
+i = 272
+i = 280
+i = 288
+i = 296
+i = 304
+i = 312
+488 defaults
+x = 0x1000000
+x = 0x2000000
+x = 0x3000000
+x = 0x4000000
+x = 0x5000000
+x = 0x6000000 (default)
+x = 0x7000000 (default)
+0
+1
+2
+3
+4
+5
+0
+1
+2
+3
+4
+5
diff --git a/lcc/x86/linux/tst/switch.2bk b/lcc/x86/linux/tst/switch.2bk
new file mode 100755
index 0000000..76387b3
--- /dev/null
+++ b/lcc/x86/linux/tst/switch.2bk
@@ -0,0 +1,5 @@
+tst/switch.c:55: warning: missing return value
+tst/switch.c:73: warning: missing return value
+tst/switch.c:97: warning: missing return value
+tst/switch.c:112: warning: missing return value
+tst/switch.c:137: warning: missing return value
diff --git a/lcc/x86/linux/tst/switch.sbk b/lcc/x86/linux/tst/switch.sbk
new file mode 100755
index 0000000..c77e6a6
--- /dev/null
+++ b/lcc/x86/linux/tst/switch.sbk
@@ -0,0 +1,899 @@
+.globl main
+.text
+.align 16
+.type main,@function
+main:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $8,%esp
+leal .LC6,%edi
+movl %edi,-4(%ebp)
+jmp .LC5
+.LC2:
+movl -4(%ebp),%edi
+movsbl (,%edi),%edi
+pushl %edi
+call backslash
+addl $4,%esp
+pushl %eax
+movl -4(%ebp),%edi
+movsbl (,%edi),%edi
+pushl %edi
+pushl $.LC7
+call printf
+addl $12,%esp
+.LC3:
+incl -4(%ebp)
+.LC5:
+movl -4(%ebp),%edi
+movsbl (,%edi),%edi
+cmpl $0,%edi
+jne .LC2
+call f
+call g
+call h
+movl $16777216,-8(%ebp)
+jmp .LC11
+.LC8:
+pushl -8(%ebp)
+call big
+addl $4,%esp
+.LC9:
+addl $16777216,-8(%ebp)
+.LC11:
+movl -8(%ebp),%edi
+andl $117440512,%edi
+cmpl $0,%edi
+jne .LC8
+call limit
+movl $0,%eax
+.LC1:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf12:
+.size main,.Lf12-main
+.globl backslash
+.align 16
+.type backslash,@function
+backslash:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl 20(%ebp),%edi
+cmpl $102,%edi
+je .LC17
+cmpl $102,%edi
+jg .LC23
+.LC22:
+cmpl $98,20(%ebp)
+je .LC16
+jmp .LC14
+.LC23:
+movl 20(%ebp),%edi
+cmpl $110,%edi
+je .LC18
+cmpl $110,%edi
+jl .LC14
+.LC24:
+movl 20(%ebp),%edi
+cmpl $114,%edi
+je .LC19
+cmpl $116,%edi
+je .LC20
+cmpl $118,%edi
+je .LC21
+jmp .LC14
+.LC16:
+movl $8,%eax
+jmp .LC13
+.LC17:
+movl $12,%eax
+jmp .LC13
+.LC18:
+movl $10,%eax
+jmp .LC13
+.LC19:
+movl $13,%eax
+jmp .LC13
+.LC20:
+movl $9,%eax
+jmp .LC13
+.LC21:
+movl $11,%eax
+jmp .LC13
+.LC14:
+movl 20(%ebp),%eax
+.LC13:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf25:
+.size backslash,.Lf25-backslash
+.globl f
+.align 16
+.type f,@function
+f:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $12,%esp
+movl $0,-8(%ebp)
+pushl $.LC27
+call printf
+addl $4,%esp
+movl $0,-4(%ebp)
+.LC28:
+movl -4(%ebp),%edi
+movl %edi,-12(%ebp)
+movl -4(%ebp),%edi
+cmpl $1,%edi
+jl .LC32
+cmpl $20,%edi
+jg .LC32
+jmp *.LC44-4(,%edi,4)
+.data
+.align 4
+.LC44:
+.long .LC34
+.long .LC35
+.long .LC32
+.long .LC32
+.long .LC32
+.long .LC32
+.long .LC36
+.long .LC37
+.long .LC38
+.long .LC32
+.long .LC32
+.long .LC32
+.long .LC32
+.long .LC32
+.long .LC32
+.long .LC39
+.long .LC40
+.long .LC41
+.long .LC42
+.long .LC43
+.text
+.LC34:
+movl -4(%ebp),%edi
+movl %edi,-8(%ebp)
+jmp .LC33
+.LC35:
+movl -4(%ebp),%edi
+movl %edi,-8(%ebp)
+jmp .LC33
+.LC36:
+movl -4(%ebp),%edi
+movl %edi,-8(%ebp)
+jmp .LC33
+.LC37:
+movl -4(%ebp),%edi
+movl %edi,-8(%ebp)
+jmp .LC33
+.LC38:
+movl -4(%ebp),%edi
+movl %edi,-8(%ebp)
+jmp .LC33
+.LC39:
+movl -4(%ebp),%edi
+movl %edi,-8(%ebp)
+jmp .LC33
+.LC40:
+movl -4(%ebp),%edi
+movl %edi,-8(%ebp)
+jmp .LC33
+.LC41:
+movl -4(%ebp),%edi
+movl %edi,-8(%ebp)
+jmp .LC33
+.LC42:
+movl -4(%ebp),%edi
+movl %edi,-8(%ebp)
+jmp .LC33
+.LC43:
+movl -4(%ebp),%edi
+movl %edi,-8(%ebp)
+.LC32:
+.LC33:
+pushl -8(%ebp)
+pushl $.LC46
+call printf
+addl $8,%esp
+.LC29:
+incl -4(%ebp)
+cmpl $20,-4(%ebp)
+jle .LC28
+movl $0,%eax
+.LC26:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf47:
+.size f,.Lf47-f
+.globl g
+.align 16
+.type g,@function
+g:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $4,%esp
+pushl $.LC49
+call printf
+addl $4,%esp
+movl $1,-4(%ebp)
+.LC50:
+movl -4(%ebp),%edi
+cmpl $1001,%edi
+jl .LC67
+cmpl $1004,%edi
+jg .LC68
+jmp *.LC69-4004(,%edi,4)
+.data
+.align 4
+.LC69:
+.long .LC63
+.long .LC63
+.long .LC63
+.long .LC63
+.text
+.LC67:
+movl -4(%ebp),%edi
+cmpl $1,%edi
+jl .LC54
+cmpl $8,%edi
+jg .LC54
+jmp *.LC71-4(,%edi,4)
+.data
+.align 4
+.LC71:
+.long .LC56
+.long .LC56
+.long .LC58
+.long .LC58
+.long .LC58
+.long .LC60
+.long .LC60
+.long .LC60
+.text
+.LC68:
+movl -4(%ebp),%edi
+cmpl $3001,%edi
+jl .LC54
+cmpl $3004,%edi
+jg .LC54
+jmp *.LC73-12004(,%edi,4)
+.data
+.align 4
+.LC73:
+.long .LC65
+.long .LC65
+.long .LC65
+.long .LC65
+.text
+.LC56:
+pushl -4(%ebp)
+pushl $.LC57
+call printf
+addl $8,%esp
+jmp .LC55
+.LC58:
+pushl -4(%ebp)
+pushl $.LC59
+call printf
+addl $8,%esp
+jmp .LC55
+.LC60:
+pushl -4(%ebp)
+pushl $.LC61
+call printf
+addl $8,%esp
+.LC54:
+pushl -4(%ebp)
+pushl $.LC62
+call printf
+addl $8,%esp
+jmp .LC55
+.LC63:
+pushl -4(%ebp)
+pushl $.LC64
+call printf
+addl $8,%esp
+jmp .LC55
+.LC65:
+pushl -4(%ebp)
+pushl $.LC66
+call printf
+addl $8,%esp
+.LC55:
+.LC51:
+incl -4(%ebp)
+cmpl $10,-4(%ebp)
+jle .LC50
+movl $0,%eax
+.LC48:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf75:
+.size g,.Lf75-g
+.globl h
+.align 16
+.type h,@function
+h:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $8,%esp
+movl $0,-8(%ebp)
+pushl $.LC77
+call printf
+addl $4,%esp
+movl $1,-4(%ebp)
+.LC78:
+movl -4(%ebp),%edi
+cmpl $264,%edi
+je .LC90
+cmpl $264,%edi
+jg .LC98
+.LC97:
+movl -4(%ebp),%edi
+cmpl $120,%edi
+je .LC88
+cmpl $120,%edi
+jg .LC100
+.LC99:
+movl -4(%ebp),%edi
+cmpl $8,%edi
+je .LC87
+cmpl $8,%edi
+jl .LC82
+.LC101:
+cmpl $16,-4(%ebp)
+je .LC86
+jmp .LC82
+.LC100:
+movl -4(%ebp),%edi
+cmpl $128,%edi
+je .LC84
+cmpl $128,%edi
+jl .LC82
+.LC102:
+cmpl $248,-4(%ebp)
+je .LC91
+jmp .LC82
+.LC98:
+movl -4(%ebp),%edi
+cmpl $288,%edi
+je .LC95
+cmpl $288,%edi
+jg .LC104
+.LC103:
+movl -4(%ebp),%edi
+cmpl $272,%edi
+je .LC92
+cmpl $272,%edi
+jl .LC82
+.LC105:
+cmpl $280,-4(%ebp)
+je .LC89
+jmp .LC82
+.LC104:
+movl -4(%ebp),%edi
+cmpl $304,%edi
+je .LC93
+cmpl $304,%edi
+jg .LC107
+.LC106:
+cmpl $296,-4(%ebp)
+je .LC94
+jmp .LC82
+.LC107:
+cmpl $312,-4(%ebp)
+je .LC96
+jmp .LC82
+.LC82:
+incl -8(%ebp)
+jmp .LC79
+.LC84:
+pushl -4(%ebp)
+pushl $.LC85
+call printf
+addl $8,%esp
+jmp .LC83
+.LC86:
+pushl -4(%ebp)
+pushl $.LC85
+call printf
+addl $8,%esp
+jmp .LC83
+.LC87:
+pushl -4(%ebp)
+pushl $.LC85
+call printf
+addl $8,%esp
+jmp .LC83
+.LC88:
+pushl -4(%ebp)
+pushl $.LC85
+call printf
+addl $8,%esp
+jmp .LC83
+.LC89:
+pushl -4(%ebp)
+pushl $.LC85
+call printf
+addl $8,%esp
+jmp .LC83
+.LC90:
+pushl -4(%ebp)
+pushl $.LC85
+call printf
+addl $8,%esp
+jmp .LC83
+.LC91:
+pushl -4(%ebp)
+pushl $.LC85
+call printf
+addl $8,%esp
+jmp .LC83
+.LC92:
+pushl -4(%ebp)
+pushl $.LC85
+call printf
+addl $8,%esp
+jmp .LC83
+.LC93:
+pushl -4(%ebp)
+pushl $.LC85
+call printf
+addl $8,%esp
+jmp .LC83
+.LC94:
+pushl -4(%ebp)
+pushl $.LC85
+call printf
+addl $8,%esp
+jmp .LC83
+.LC95:
+pushl -4(%ebp)
+pushl $.LC85
+call printf
+addl $8,%esp
+jmp .LC83
+.LC96:
+pushl -4(%ebp)
+pushl $.LC85
+call printf
+addl $8,%esp
+.LC83:
+.LC79:
+incl -4(%ebp)
+cmpl $500,-4(%ebp)
+jle .LC78
+pushl -8(%ebp)
+pushl $.LC108
+call printf
+addl $8,%esp
+movl $0,%eax
+.LC76:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf109:
+.size h,.Lf109-h
+.globl big
+.align 16
+.type big,@function
+big:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $4,%esp
+movl 20(%ebp),%edi
+andl $0x6000000,%edi
+movl %edi,-4(%ebp)
+movl -4(%ebp),%edi
+cmpl $33554432,%edi
+je .LC116
+cmpl $33554432,%edi
+jg .LC120
+.LC119:
+movl -4(%ebp),%edi
+cmpl $-2,%edi
+je .LC114
+cmpl $-1,%edi
+je .LC114
+cmpl $0,%edi
+je .LC114
+jmp .LC111
+.LC120:
+movl -4(%ebp),%edi
+cmpl $67108864,%edi
+je .LC117
+jmp .LC111
+.LC114:
+pushl 20(%ebp)
+pushl $.LC115
+call printf
+addl $8,%esp
+jmp .LC112
+.LC116:
+pushl 20(%ebp)
+pushl $.LC115
+call printf
+addl $8,%esp
+jmp .LC112
+.LC117:
+pushl 20(%ebp)
+pushl $.LC115
+call printf
+addl $8,%esp
+jmp .LC112
+.LC111:
+pushl 20(%ebp)
+pushl $.LC118
+call printf
+addl $8,%esp
+.LC112:
+movl $0,%eax
+.LC110:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf121:
+.size big,.Lf121-big
+.globl limit
+.align 16
+.type limit,@function
+limit:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $4,%esp
+movl $-2147483648,-4(%ebp)
+.LC123:
+movl -4(%ebp),%edi
+movl $-2147483648,%esi
+cmpl $-2147483648,%edi
+jl .LC127
+cmpl $-2147483644,%edi
+jg .LC127
+leal (,%edi,4),%edi
+leal (,%esi,4),%esi
+subl %esi,%edi
+jmp *.LC140(%edi)
+.data
+.align 4
+.LC140:
+.long .LC129
+.long .LC131
+.long .LC133
+.long .LC135
+.long .LC137
+.text
+.LC129:
+pushl $.LC130
+call printf
+addl $4,%esp
+jmp .LC128
+.LC131:
+pushl $.LC132
+call printf
+addl $4,%esp
+jmp .LC128
+.LC133:
+pushl $.LC134
+call printf
+addl $4,%esp
+jmp .LC128
+.LC135:
+pushl $.LC136
+call printf
+addl $4,%esp
+jmp .LC128
+.LC137:
+pushl $.LC138
+call printf
+addl $4,%esp
+jmp .LC128
+.LC127:
+pushl $.LC139
+call printf
+addl $4,%esp
+.LC128:
+.LC124:
+incl -4(%ebp)
+cmpl $-2147483643,-4(%ebp)
+jle .LC123
+movl $2147483647,-4(%ebp)
+.LC141:
+movl -4(%ebp),%edi
+movl $2147483643,%esi
+cmpl $2147483643,%edi
+jl .LC145
+cmpl $2147483647,%edi
+jg .LC145
+leal (,%edi,4),%edi
+leal (,%esi,4),%esi
+subl %esi,%edi
+jmp *.LC152(%edi)
+.data
+.align 4
+.LC152:
+.long .LC151
+.long .LC150
+.long .LC149
+.long .LC148
+.long .LC147
+.text
+.LC147:
+pushl $.LC130
+call printf
+addl $4,%esp
+jmp .LC146
+.LC148:
+pushl $.LC132
+call printf
+addl $4,%esp
+jmp .LC146
+.LC149:
+pushl $.LC134
+call printf
+addl $4,%esp
+jmp .LC146
+.LC150:
+pushl $.LC136
+call printf
+addl $4,%esp
+jmp .LC146
+.LC151:
+pushl $.LC138
+call printf
+addl $4,%esp
+jmp .LC146
+.LC145:
+pushl $.LC139
+call printf
+addl $4,%esp
+.LC146:
+.LC142:
+decl -4(%ebp)
+cmpl $2147483642,-4(%ebp)
+jge .LC141
+movl $0,%eax
+.LC122:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf153:
+.size limit,.Lf153-limit
+.data
+.align 1
+.LC139:
+.byte 53
+.byte 10
+.byte 0
+.align 1
+.LC138:
+.byte 52
+.byte 10
+.byte 0
+.align 1
+.LC136:
+.byte 51
+.byte 10
+.byte 0
+.align 1
+.LC134:
+.byte 50
+.byte 10
+.byte 0
+.align 1
+.LC132:
+.byte 49
+.byte 10
+.byte 0
+.align 1
+.LC130:
+.byte 48
+.byte 10
+.byte 0
+.align 1
+.LC118:
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 120
+.byte 37
+.byte 120
+.byte 32
+.byte 40
+.byte 100
+.byte 101
+.byte 102
+.byte 97
+.byte 117
+.byte 108
+.byte 116
+.byte 41
+.byte 10
+.byte 0
+.align 1
+.LC115:
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 120
+.byte 37
+.byte 120
+.byte 10
+.byte 0
+.align 1
+.LC108:
+.byte 37
+.byte 100
+.byte 32
+.byte 100
+.byte 101
+.byte 102
+.byte 97
+.byte 117
+.byte 108
+.byte 116
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.LC85:
+.byte 105
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC77:
+.byte 104
+.byte 58
+.byte 10
+.byte 0
+.align 1
+.LC66:
+.byte 54
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC64:
+.byte 53
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC62:
+.byte 100
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC61:
+.byte 51
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC59:
+.byte 50
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC57:
+.byte 49
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC49:
+.byte 103
+.byte 58
+.byte 10
+.byte 0
+.align 1
+.LC46:
+.byte 120
+.byte 32
+.byte 61
+.byte 32
+.byte 37
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC27:
+.byte 102
+.byte 58
+.byte 10
+.byte 0
+.align 1
+.LC7:
+.byte 37
+.byte 99
+.byte 32
+.byte 61
+.byte 32
+.byte 48
+.byte 120
+.byte 37
+.byte 120
+.byte 10
+.byte 0
+.align 1
+.LC6:
+.byte 98
+.byte 102
+.byte 110
+.byte 114
+.byte 116
+.byte 118
+.byte 120
+.byte 0
+.text
+.ident "LCC: 4.1"
diff --git a/lcc/x86/linux/tst/wf1.1bk b/lcc/x86/linux/tst/wf1.1bk
new file mode 100755
index 0000000..095e087
--- /dev/null
+++ b/lcc/x86/linux/tst/wf1.1bk
@@ -0,0 +1,74 @@
+5 a
+2 and
+5 buf
+16 c
+8 char
+1 compare
+4 cond
+5 count
+1 d
+1 die
+3 else
+1 entry
+1 eof
+4 err
+1 error
+1 exit
+1 folded
+1 for
+1 free
+1 frequencies
+1 frequency
+1 get
+2 getchar
+3 getword
+14 if
+2 in
+1 index
+1 input
+1 install
+8 int
+1 into
+1 is
+4 isletter
+1 it
+1 itself
+5 left
+1 letter
+7 lookup
+1 main
+2 malloc
+1 message
+2 n
+1 necessary
+12 next
+9 node
+4 of
+1 on
+1 or
+1 otherwise
+2 out
+8 p
+3 print
+2 printf
+16 return
+5 right
+4 root
+25 s
+2 storage
+3 strcmp
+1 strcpy
+1 strlen
+8 struct
+1 structures
+2 subtree
+1 t
+5 tprint
+9 tree
+1 uses
+1 version
+1 wf
+3 while
+21 word
+9 words
+2 z
diff --git a/lcc/x86/linux/tst/wf1.2bk b/lcc/x86/linux/tst/wf1.2bk
new file mode 100755
index 0000000..0e7a8a6
--- /dev/null
+++ b/lcc/x86/linux/tst/wf1.2bk
@@ -0,0 +1,2 @@
+tst/wf1.c:29: warning: missing return value
+tst/wf1.c:87: warning: missing return value
diff --git a/lcc/x86/linux/tst/wf1.sbk b/lcc/x86/linux/tst/wf1.sbk
new file mode 100755
index 0000000..fb237a3
--- /dev/null
+++ b/lcc/x86/linux/tst/wf1.sbk
@@ -0,0 +1,437 @@
+.globl main
+.text
+.align 16
+.type main,@function
+main:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $24,%esp
+movl $0,-24(%ebp)
+movl $0,next
+jmp .LC3
+.LC2:
+leal -24(%ebp),%edi
+pushl %edi
+leal -20(%ebp),%edi
+pushl %edi
+call lookup
+addl $8,%esp
+incl (,%eax)
+.LC3:
+leal -20(%ebp),%edi
+pushl %edi
+call getword
+addl $4,%esp
+cmpl $0,%eax
+jne .LC2
+pushl -24(%ebp)
+call tprint
+addl $4,%esp
+movl $0,%eax
+.LC1:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf5:
+.size main,.Lf5-main
+.globl err
+.align 16
+.type err,@function
+err:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+pushl 20(%ebp)
+pushl $.LC7
+call printf
+addl $8,%esp
+pushl $1
+call exit
+addl $4,%esp
+movl $0,%eax
+.LC6:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf8:
+.size err,.Lf8-err
+.globl getword
+.align 16
+.type getword,@function
+getword:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $8,%esp
+.LC10:
+.LC11:
+call getchar
+movl %eax,%edi
+movl %edi,-4(%ebp)
+cmpl $-1,%edi
+je .LC13
+pushl -4(%ebp)
+call isletter
+addl $4,%esp
+cmpl $0,%eax
+je .LC10
+.LC13:
+movl 20(%ebp),%edi
+movl %edi,-8(%ebp)
+jmp .LC17
+.LC14:
+movl -8(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-8(%ebp)
+movl -4(%ebp),%esi
+movl %esi,%ebx
+movb %bl,(,%edi)
+.LC15:
+call getchar
+movl %eax,-4(%ebp)
+.LC17:
+pushl -4(%ebp)
+call isletter
+addl $4,%esp
+movl %eax,-4(%ebp)
+cmpl $0,%eax
+jne .LC14
+movl -8(%ebp),%edi
+movb $0,(,%edi)
+movl -8(%ebp),%edi
+movl 20(%ebp),%esi
+cmpl %esi,%edi
+jbe .LC18
+movl $1,%eax
+jmp .LC9
+.LC18:
+movl $0,%eax
+.LC9:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf20:
+.size getword,.Lf20-getword
+.globl isletter
+.align 16
+.type isletter,@function
+isletter:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl 20(%ebp),%edi
+cmpl $65,%edi
+jl .LC22
+cmpl $90,%edi
+jg .LC22
+addl $32,20(%ebp)
+.LC22:
+movl 20(%ebp),%edi
+cmpl $97,%edi
+jl .LC24
+cmpl $122,%edi
+jg .LC24
+movl 20(%ebp),%eax
+jmp .LC21
+.LC24:
+movl $0,%eax
+.LC21:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf26:
+.size isletter,.Lf26-isletter
+.globl lookup
+.align 16
+.type lookup,@function
+lookup:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $4,%esp
+movl 24(%ebp),%edi
+movl (,%edi),%edi
+cmpl $0,%edi
+je .LC28
+movl 24(%ebp),%edi
+movl (,%edi),%edi
+pushl 12(%edi)
+pushl 20(%ebp)
+call strcmp
+addl $8,%esp
+movl %eax,-4(%ebp)
+cmpl $0,-4(%ebp)
+jge .LC30
+movl 24(%ebp),%edi
+movl (,%edi),%edi
+leal 4(%edi),%edi
+pushl %edi
+pushl 20(%ebp)
+call lookup
+addl $8,%esp
+movl %eax,%edi
+jmp .LC27
+.LC30:
+cmpl $0,-4(%ebp)
+jle .LC32
+movl 24(%ebp),%edi
+movl (,%edi),%edi
+leal 8(%edi),%edi
+pushl %edi
+pushl 20(%ebp)
+call lookup
+addl $8,%esp
+movl %eax,%edi
+jmp .LC27
+.LC32:
+movl 24(%ebp),%edi
+movl (,%edi),%eax
+jmp .LC27
+.LC28:
+cmpl $2000,next
+jl .LC34
+pushl $.LC36
+call err
+addl $4,%esp
+.LC34:
+movl next,%edi
+sall $4,%edi
+movl $0,words(%edi)
+movl next,%edi
+sall $4,%edi
+movl $0,words+8(%edi)
+movl $0,words+4(%edi)
+pushl 20(%ebp)
+call strlen
+addl $4,%esp
+leal 1(%eax),%edi
+pushl %edi
+call malloc
+addl $4,%esp
+movl next,%esi
+sall $4,%esi
+movl %eax,words+12(%esi)
+movl next,%edi
+sall $4,%edi
+movl words+12(%edi),%edi
+cmpl $0,%edi
+jne .LC40
+pushl $.LC43
+call err
+addl $4,%esp
+.LC40:
+pushl 20(%ebp)
+movl next,%edi
+sall $4,%edi
+pushl words+12(%edi)
+call strcpy
+addl $8,%esp
+movl next,%edi
+leal 1(%edi),%esi
+movl %esi,next
+sall $4,%edi
+leal words(%edi),%edi
+movl 24(%ebp),%esi
+movl %edi,(,%esi)
+movl %edi,%eax
+.LC27:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf45:
+.size lookup,.Lf45-lookup
+.globl tprint
+.align 16
+.type tprint,@function
+tprint:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl 20(%ebp),%edi
+cmpl $0,%edi
+je .LC47
+movl 20(%ebp),%edi
+pushl 4(%edi)
+call tprint
+addl $4,%esp
+movl 20(%ebp),%edi
+pushl 12(%edi)
+pushl (,%edi)
+pushl $.LC49
+call printf
+addl $12,%esp
+movl 20(%ebp),%edi
+pushl 8(%edi)
+call tprint
+addl $4,%esp
+.LC47:
+movl $0,%eax
+.LC46:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf50:
+.size tprint,.Lf50-tprint
+.globl strcmp
+.align 16
+.type strcmp,@function
+strcmp:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+jmp .LC53
+.LC52:
+movl 20(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,20(%ebp)
+movsbl (,%edi),%edi
+cmpl $0,%edi
+jne .LC55
+movl $0,%eax
+jmp .LC51
+.LC55:
+incl 24(%ebp)
+.LC53:
+movl 20(%ebp),%edi
+movsbl (,%edi),%edi
+movl 24(%ebp),%esi
+movsbl (,%esi),%esi
+cmpl %esi,%edi
+je .LC52
+movl 20(%ebp),%edi
+movsbl (,%edi),%edi
+cmpl $0,%edi
+jne .LC57
+movl $-1,%eax
+jmp .LC51
+.LC57:
+movl 24(%ebp),%edi
+movsbl (,%edi),%edi
+cmpl $0,%edi
+jne .LC59
+movl $1,%eax
+jmp .LC51
+.LC59:
+movl 20(%ebp),%edi
+movsbl (,%edi),%edi
+movl 24(%ebp),%esi
+movsbl (,%esi),%esi
+movl %edi,%eax
+subl %esi,%eax
+.LC51:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf61:
+.size strcmp,.Lf61-strcmp
+.bss
+.globl next
+.align 4
+.type next,@object
+.size next,4
+.comm next,4
+.globl words
+.align 4
+.type words,@object
+.size words,32000
+.comm words,32000
+.data
+.align 1
+.LC49:
+.byte 37
+.byte 100
+.byte 9
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.LC43:
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 119
+.byte 111
+.byte 114
+.byte 100
+.byte 32
+.byte 115
+.byte 116
+.byte 111
+.byte 114
+.byte 97
+.byte 103
+.byte 101
+.byte 0
+.align 1
+.LC36:
+.byte 111
+.byte 117
+.byte 116
+.byte 32
+.byte 111
+.byte 102
+.byte 32
+.byte 110
+.byte 111
+.byte 100
+.byte 101
+.byte 32
+.byte 115
+.byte 116
+.byte 111
+.byte 114
+.byte 97
+.byte 103
+.byte 101
+.byte 0
+.align 1
+.LC7:
+.byte 63
+.byte 32
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.text
+.ident "LCC: 4.1"
diff --git a/lcc/x86/linux/tst/yacc.1bk b/lcc/x86/linux/tst/yacc.1bk
new file mode 100755
index 0000000..b08a02f
--- /dev/null
+++ b/lcc/x86/linux/tst/yacc.1bk
@@ -0,0 +1,10 @@
+a
+b
+load
+negate
+push 5
+c
+load
+multiply
+add
+store
diff --git a/lcc/x86/linux/tst/yacc.2bk b/lcc/x86/linux/tst/yacc.2bk
new file mode 100755
index 0000000..a84aa5b
--- /dev/null
+++ b/lcc/x86/linux/tst/yacc.2bk
@@ -0,0 +1,3 @@
+tst/yacc.c:345: warning: missing return value
+tst/yacc.c:349: warning: missing return value
+tst/yacc.c:359: warning: missing return value
diff --git a/lcc/x86/linux/tst/yacc.sbk b/lcc/x86/linux/tst/yacc.sbk
new file mode 100755
index 0000000..a4370b7
--- /dev/null
+++ b/lcc/x86/linux/tst/yacc.sbk
@@ -0,0 +1,2526 @@
+.data
+.globl yyin
+.align 4
+.type yyin,@object
+.size yyin,4
+yyin:
+.long _IO_stdin_
+.globl yyout
+.align 4
+.type yyout,@object
+.size yyout,4
+yyout:
+.long _IO_stdout_
+.globl yylex
+.text
+.align 16
+.type yylex,@function
+yylex:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $4,%esp
+jmp .LC3
+.LC2:
+.LC5:
+movl -4(%ebp),%edi
+cmpl $-1,%edi
+jl .LC6
+cmpl $4,%edi
+jg .LC6
+jmp *.LC17+4(,%edi,4)
+.data
+.align 4
+.LC17:
+.long .LC7
+.long .LC8
+.long .LC11
+.long .LC12
+.long .LC7
+.long .LC14
+.text
+.LC8:
+call yywrap
+cmpl $0,%eax
+je .LC7
+movl $0,%eax
+jmp .LC1
+.LC11:
+movl $257,%eax
+jmp .LC1
+.LC12:
+movl $258,%eax
+jmp .LC1
+.LC14:
+movsbl yytext,%eax
+jmp .LC1
+.LC6:
+pushl -4(%ebp)
+pushl $.LC16
+pushl yyout
+call fprintf
+addl $12,%esp
+.LC7:
+.LC3:
+call yylook
+movl %eax,-4(%ebp)
+cmpl $0,%eax
+jge .LC2
+movl $0,%eax
+.LC1:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf19:
+.size yylex,.Lf19-yylex
+.data
+.globl yyvstop
+.align 4
+.type yyvstop,@object
+yyvstop:
+.long 0
+.long 4
+.long 0
+.long 3
+.long 4
+.long 0
+.long 2
+.long 4
+.long 0
+.long 1
+.long 4
+.long 0
+.long 2
+.long 0
+.long 1
+.long 0
+.long 0
+.size yyvstop,68
+.globl yycrank
+.align 4
+.type yycrank,@object
+yycrank:
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 1
+.byte 3
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 1
+.byte 4
+.space 2
+.byte 1
+.byte 3
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 1
+.byte 5
+.space 2
+.byte 5
+.byte 7
+.space 2
+.byte 5
+.byte 7
+.space 2
+.byte 5
+.byte 7
+.space 2
+.byte 5
+.byte 7
+.space 2
+.byte 5
+.byte 7
+.space 2
+.byte 5
+.byte 7
+.space 2
+.byte 5
+.byte 7
+.space 2
+.byte 5
+.byte 7
+.space 2
+.byte 5
+.byte 7
+.space 2
+.byte 5
+.byte 7
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 1
+.byte 6
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 6
+.byte 8
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.byte 0
+.byte 0
+.space 2
+.size yycrank,580
+.globl yysvec
+.align 4
+.type yysvec,@object
+yysvec:
+.long 0
+.long 0
+.long 0
+.long yycrank-4
+.long 0
+.long 0
+.long yycrank
+.long yysvec+12
+.long 0
+.long yycrank
+.long 0
+.long yyvstop+4
+.long yycrank
+.long 0
+.long yyvstop+12
+.long yycrank+8
+.long 0
+.long yyvstop+24
+.long yycrank+76
+.long 0
+.long yyvstop+36
+.long yycrank
+.long yysvec+60
+.long yyvstop+48
+.long yycrank
+.long yysvec+72
+.long yyvstop+56
+.long 0
+.long 0
+.long 0
+.size yysvec,120
+.globl yytop
+.align 4
+.type yytop,@object
+.size yytop,4
+yytop:
+.long yycrank+564
+.globl yybgin
+.align 4
+.type yybgin,@object
+.size yybgin,4
+yybgin:
+.long yysvec+12
+.globl yymatch
+.align 1
+.type yymatch,@object
+yymatch:
+.byte 0
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 9
+.byte 10
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 9
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 48
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 65
+.byte 1
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 65
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 1
+.byte 0
+.size yymatch,129
+.globl yyextra
+.align 1
+.type yyextra,@object
+yyextra:
+.byte 0
+.byte 0
+.byte 0
+.byte 0
+.byte 0
+.byte 0
+.byte 0
+.byte 0
+.byte 0
+.size yyextra,9
+.globl yylineno
+.align 4
+.type yylineno,@object
+.size yylineno,4
+yylineno:
+.long 1
+.globl yysptr
+.align 4
+.type yysptr,@object
+.size yysptr,4
+yysptr:
+.long yysbuf
+.globl yyprevious
+.align 4
+.type yyprevious,@object
+.size yyprevious,4
+yyprevious:
+.long 10
+.globl yylook
+.text
+.align 16
+.type yylook,@function
+yylook:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $44,%esp
+cmpl $0,yymorfg
+jne .LC35
+leal yytext,%edi
+movl %edi,-16(%ebp)
+jmp .LC36
+.LC35:
+movl $0,yymorfg
+movl yyleng,%edi
+leal yytext(%edi),%edi
+movl %edi,-16(%ebp)
+.LC36:
+.LC37:
+leal yylstate,%edi
+movl %edi,-8(%ebp)
+movl yybgin,%edi
+movl %edi,-4(%ebp)
+movl %edi,yyestate
+cmpl $10,yyprevious
+jne .LC41
+movl -4(%ebp),%edi
+leal 12(%edi),%edi
+movl %edi,-4(%ebp)
+.LC41:
+.LC43:
+movl -4(%ebp),%edi
+movl (,%edi),%edi
+movl %edi,-12(%ebp)
+movl -12(%ebp),%edi
+leal yycrank,%esi
+cmpl %esi,%edi
+jne .LC47
+movl -4(%ebp),%edi
+movl 4(%edi),%edi
+movl %edi,-28(%ebp)
+movl -28(%ebp),%edi
+cmpl $0,%edi
+jne .LC49
+jmp .LC94
+.LC49:
+movl -28(%ebp),%edi
+movl (,%edi),%edi
+leal yycrank,%esi
+cmpl %esi,%edi
+jne .LC51
+jmp .LC94
+.LC51:
+.LC47:
+movl -16(%ebp),%edi
+leal 1(%edi),%esi
+movl %esi,-16(%ebp)
+movl yysptr,%esi
+leal yysbuf,%ebx
+cmpl %ebx,%esi
+jbe .LC61
+movl yysptr,%esi
+leal -1(%esi),%esi
+movl %esi,yysptr
+movsbl (,%esi),%esi
+movl %esi,-40(%ebp)
+jmp .LC62
+.LC61:
+movl yyin,%esi
+movl 4(%esi),%ebx
+movl 8(%esi),%esi
+cmpl %esi,%ebx
+jb .LC63
+pushl yyin
+call __uflow
+addl $4,%esp
+movl %eax,%esi
+movl %esi,-44(%ebp)
+jmp .LC64
+.LC63:
+movl yyin,%esi
+leal 4(%esi),%esi
+movl (,%esi),%ebx
+leal 1(%ebx),%edx
+movl %edx,(,%esi)
+movb (,%ebx),%bl
+movzbl %bl,%esi
+movl %esi,-44(%ebp)
+.LC64:
+movl -44(%ebp),%esi
+movl %esi,-40(%ebp)
+.LC62:
+movl -40(%ebp),%esi
+movl %esi,yytchar
+cmpl $10,%esi
+jne .LC59
+incl yylineno
+movl yytchar,%esi
+movl %esi,-36(%ebp)
+jmp .LC60
+.LC59:
+movl yytchar,%esi
+movl %esi,-36(%ebp)
+.LC60:
+cmpl $-1,-36(%ebp)
+jne .LC57
+movl $0,-32(%ebp)
+jmp .LC58
+.LC57:
+movl yytchar,%esi
+movl %esi,-32(%ebp)
+.LC58:
+movl -32(%ebp),%esi
+movl %esi,-20(%ebp)
+movl %esi,%ebx
+movb %bl,(,%edi)
+.LC65:
+movl -12(%ebp),%edi
+movl %edi,-24(%ebp)
+leal yycrank,%esi
+cmpl %esi,%edi
+jbe .LC66
+movl -20(%ebp),%edi
+movl -24(%ebp),%esi
+leal (%esi,%edi,4),%edi
+movl %edi,-12(%ebp)
+movl -12(%ebp),%edi
+movl %edi,%esi
+movl yytop,%ebx
+cmpl %ebx,%esi
+ja .LC67
+movsbl (,%edi),%edi
+imul $12,%edi,%edi
+leal yysvec(%edi),%edi
+movl -4(%ebp),%esi
+cmpl %esi,%edi
+jne .LC67
+leal yysvec,%edi
+movl -12(%ebp),%esi
+movsbl 1(%esi),%esi
+imul $12,%esi,%esi
+leal yysvec(%esi),%esi
+cmpl %edi,%esi
+jne .LC70
+movl -16(%ebp),%edi
+leal -1(%edi),%edi
+movl %edi,-16(%ebp)
+movsbl (,%edi),%edi
+movl %edi,yytchar
+cmpl $10,yytchar
+jne .LC72
+decl yylineno
+.LC72:
+movl yysptr,%edi
+leal 1(%edi),%esi
+movl %esi,yysptr
+movl yytchar,%esi
+movl %esi,%ebx
+movb %bl,(,%edi)
+jmp .LC94
+.LC70:
+movl -8(%ebp),%edi
+leal 4(%edi),%esi
+movl %esi,-8(%ebp)
+movl -12(%ebp),%esi
+movsbl 1(%esi),%esi
+imul $12,%esi,%esi
+leal yysvec(%esi),%esi
+movl %esi,-4(%ebp)
+movl %esi,(,%edi)
+jmp .LC43
+.LC66:
+movl -12(%ebp),%edi
+leal yycrank,%esi
+cmpl %esi,%edi
+jae .LC75
+leal yycrank,%edi
+movl -12(%ebp),%esi
+subl %esi,%edi
+movl %edi,%eax
+movl $4,%ecx
+cdq
+idivl %ecx
+leal yycrank(,%eax,4),%edi
+movl %edi,-24(%ebp)
+movl %edi,-12(%ebp)
+movl -20(%ebp),%edi
+movl -12(%ebp),%esi
+leal (%esi,%edi,4),%edi
+movl %edi,-12(%ebp)
+movl -12(%ebp),%edi
+movl %edi,%esi
+movl yytop,%ebx
+cmpl %ebx,%esi
+ja .LC77
+movsbl (,%edi),%edi
+imul $12,%edi,%edi
+leal yysvec(%edi),%edi
+movl -4(%ebp),%esi
+cmpl %esi,%edi
+jne .LC77
+leal yysvec,%edi
+movl -12(%ebp),%esi
+movsbl 1(%esi),%esi
+imul $12,%esi,%esi
+leal yysvec(%esi),%esi
+cmpl %edi,%esi
+jne .LC79
+movl -16(%ebp),%edi
+leal -1(%edi),%edi
+movl %edi,-16(%ebp)
+movsbl (,%edi),%edi
+movl %edi,yytchar
+cmpl $10,yytchar
+jne .LC81
+decl yylineno
+.LC81:
+movl yysptr,%edi
+leal 1(%edi),%esi
+movl %esi,yysptr
+movl yytchar,%esi
+movl %esi,%ebx
+movb %bl,(,%edi)
+jmp .LC94
+.LC79:
+movl -8(%ebp),%edi
+leal 4(%edi),%esi
+movl %esi,-8(%ebp)
+movl -12(%ebp),%esi
+movsbl 1(%esi),%esi
+imul $12,%esi,%esi
+leal yysvec(%esi),%esi
+movl %esi,-4(%ebp)
+movl %esi,(,%edi)
+jmp .LC43
+.LC77:
+movl -20(%ebp),%edi
+movsbl yymatch(%edi),%edi
+movl -24(%ebp),%esi
+leal (%esi,%edi,4),%edi
+movl %edi,-12(%ebp)
+movl -12(%ebp),%edi
+movl %edi,%esi
+movl yytop,%ebx
+cmpl %ebx,%esi
+ja .LC83
+movsbl (,%edi),%edi
+imul $12,%edi,%edi
+leal yysvec(%edi),%edi
+movl -4(%ebp),%esi
+cmpl %esi,%edi
+jne .LC83
+leal yysvec,%edi
+movl -12(%ebp),%esi
+movsbl 1(%esi),%esi
+imul $12,%esi,%esi
+leal yysvec(%esi),%esi
+cmpl %edi,%esi
+jne .LC85
+movl -16(%ebp),%edi
+leal -1(%edi),%edi
+movl %edi,-16(%ebp)
+movsbl (,%edi),%edi
+movl %edi,yytchar
+cmpl $10,yytchar
+jne .LC87
+decl yylineno
+.LC87:
+movl yysptr,%edi
+leal 1(%edi),%esi
+movl %esi,yysptr
+movl yytchar,%esi
+movl %esi,%ebx
+movb %bl,(,%edi)
+jmp .LC94
+.LC85:
+movl -8(%ebp),%edi
+leal 4(%edi),%esi
+movl %esi,-8(%ebp)
+movl -12(%ebp),%esi
+movsbl 1(%esi),%esi
+imul $12,%esi,%esi
+leal yysvec(%esi),%esi
+movl %esi,-4(%ebp)
+movl %esi,(,%edi)
+jmp .LC43
+.LC83:
+.LC75:
+.LC67:
+movl -4(%ebp),%edi
+movl 4(%edi),%edi
+movl %edi,-4(%ebp)
+cmpl $0,%edi
+je .LC89
+movl -4(%ebp),%edi
+movl (,%edi),%edi
+movl %edi,-12(%ebp)
+leal yycrank,%esi
+cmpl %esi,%edi
+je .LC89
+jmp .LC65
+.LC89:
+movl -16(%ebp),%edi
+leal -1(%edi),%edi
+movl %edi,-16(%ebp)
+movsbl (,%edi),%edi
+movl %edi,yytchar
+cmpl $10,yytchar
+jne .LC91
+decl yylineno
+.LC91:
+movl yysptr,%edi
+leal 1(%edi),%esi
+movl %esi,yysptr
+movl yytchar,%esi
+movl %esi,%ebx
+movb %bl,(,%edi)
+jmp .LC94
+.LC93:
+movl -16(%ebp),%edi
+leal -1(%edi),%esi
+movl %esi,-16(%ebp)
+movb $0,(,%edi)
+movl -8(%ebp),%edi
+movl (,%edi),%edi
+movl %edi,%esi
+cmpl $0,%esi
+je .LC96
+movl 8(%edi),%edi
+movl %edi,yyfnd
+cmpl $0,%edi
+je .LC96
+movl yyfnd,%edi
+cmpl $0,(,%edi)
+jle .LC96
+movl -8(%ebp),%edi
+movl %edi,yyolsp
+movl yyfnd,%edi
+movl (,%edi),%edi
+movsbl yyextra(%edi),%edi
+cmpl $0,%edi
+je .LC98
+jmp .LC101
+.LC100:
+movl -8(%ebp),%edi
+leal -4(%edi),%edi
+movl %edi,-8(%ebp)
+movl -16(%ebp),%edi
+leal -1(%edi),%esi
+movl %esi,-16(%ebp)
+movsbl (,%edi),%edi
+movl %edi,yytchar
+cmpl $10,yytchar
+jne .LC103
+decl yylineno
+.LC103:
+movl yysptr,%edi
+leal 1(%edi),%esi
+movl %esi,yysptr
+movl yytchar,%esi
+movl %esi,%ebx
+movb %bl,(,%edi)
+.LC101:
+movl yyfnd,%edi
+movl (,%edi),%edi
+negl %edi
+pushl %edi
+movl -8(%ebp),%edi
+movl (,%edi),%edi
+pushl 8(%edi)
+call yyback
+addl $8,%esp
+cmpl $1,%eax
+je .LC105
+movl -8(%ebp),%edi
+leal yylstate,%esi
+cmpl %esi,%edi
+ja .LC100
+.LC105:
+.LC98:
+movl -16(%ebp),%edi
+movsbl (,%edi),%esi
+movl %esi,yyprevious
+movl -8(%ebp),%esi
+movl %esi,yylsp
+leal yytext,%esi
+subl %esi,%edi
+leal 1(%edi),%edi
+movl %edi,yyleng
+movl yyleng,%edi
+movb $0,yytext(%edi)
+movl yyfnd,%edi
+leal 4(%edi),%esi
+movl %esi,yyfnd
+movl (,%edi),%eax
+jmp .LC34
+.LC96:
+movl -16(%ebp),%edi
+movsbl (,%edi),%edi
+movl %edi,yytchar
+cmpl $10,yytchar
+jne .LC106
+decl yylineno
+.LC106:
+movl yysptr,%edi
+leal 1(%edi),%esi
+movl %esi,yysptr
+movl yytchar,%esi
+movl %esi,%ebx
+movb %bl,(,%edi)
+.LC94:
+movl -8(%ebp),%edi
+leal -4(%edi),%esi
+movl %esi,-8(%ebp)
+leal yylstate,%esi
+cmpl %esi,%edi
+ja .LC93
+movsbl yytext,%edi
+cmpl $0,%edi
+jne .LC108
+leal yysbuf,%edi
+movl %edi,yysptr
+movl $0,%eax
+jmp .LC34
+.LC108:
+movl yysptr,%edi
+leal yysbuf,%esi
+cmpl %esi,%edi
+jbe .LC118
+movl yysptr,%edi
+leal -1(%edi),%edi
+movl %edi,yysptr
+movsbl (,%edi),%edi
+movl %edi,-40(%ebp)
+jmp .LC119
+.LC118:
+movl yyin,%edi
+movl 4(%edi),%esi
+movl 8(%edi),%edi
+cmpl %edi,%esi
+jb .LC120
+pushl yyin
+call __uflow
+addl $4,%esp
+movl %eax,%edi
+movl %edi,-44(%ebp)
+jmp .LC121
+.LC120:
+movl yyin,%edi
+leal 4(%edi),%edi
+movl (,%edi),%esi
+leal 1(%esi),%ebx
+movl %ebx,(,%edi)
+movb (,%esi),%bl
+movzbl %bl,%edi
+movl %edi,-44(%ebp)
+.LC121:
+movl -44(%ebp),%edi
+movl %edi,-40(%ebp)
+.LC119:
+movl -40(%ebp),%edi
+movl %edi,yytchar
+cmpl $10,%edi
+jne .LC116
+incl yylineno
+movl yytchar,%edi
+movl %edi,-36(%ebp)
+jmp .LC117
+.LC116:
+movl yytchar,%edi
+movl %edi,-36(%ebp)
+.LC117:
+cmpl $-1,-36(%ebp)
+jne .LC114
+movl $0,-32(%ebp)
+jmp .LC115
+.LC114:
+movl yytchar,%edi
+movl %edi,-32(%ebp)
+.LC115:
+movl -32(%ebp),%edi
+movl %edi,%ebx
+movb %bl,yytext
+movsbl %bl,%edi
+movl %edi,yyprevious
+cmpl $0,yyprevious
+jle .LC122
+movl yyout,%edi
+movl 20(%edi),%esi
+movl 24(%edi),%edi
+cmpl %edi,%esi
+jb .LC125
+movl yyprevious,%edi
+movl %edi,%ebx
+movzbl %bl,%edi
+pushl %edi
+pushl yyout
+call __overflow
+addl $8,%esp
+jmp .LC126
+.LC125:
+movl yyout,%edi
+leal 20(%edi),%edi
+movl (,%edi),%esi
+leal 1(%esi),%ebx
+movl %ebx,(,%edi)
+movl yyprevious,%edi
+movl %edi,%ebx
+movb %bl,(,%esi)
+.LC126:
+.LC122:
+leal yytext,%edi
+movl %edi,-16(%ebp)
+jmp .LC37
+.LC34:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf127:
+.size yylook,.Lf127-yylook
+.globl yyback
+.align 16
+.type yyback,@function
+yyback:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl 20(%ebp),%edi
+cmpl $0,%edi
+jne .LC132
+movl $0,%eax
+jmp .LC128
+.LC131:
+movl 20(%ebp),%edi
+leal 4(%edi),%esi
+movl %esi,20(%ebp)
+movl 24(%ebp),%esi
+cmpl %esi,(,%edi)
+jne .LC134
+movl $1,%eax
+jmp .LC128
+.LC134:
+.LC132:
+movl 20(%ebp),%edi
+cmpl $0,(,%edi)
+jne .LC131
+movl $0,%eax
+.LC128:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf136:
+.size yyback,.Lf136-yyback
+.globl yyinput
+.align 16
+.type yyinput,@function
+yyinput:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $16,%esp
+movl yysptr,%edi
+leal yysbuf,%esi
+cmpl %esi,%edi
+jbe .LC146
+movl yysptr,%edi
+leal -1(%edi),%edi
+movl %edi,yysptr
+movsbl (,%edi),%edi
+movl %edi,-12(%ebp)
+jmp .LC147
+.LC146:
+movl yyin,%edi
+movl 4(%edi),%esi
+movl 8(%edi),%edi
+cmpl %edi,%esi
+jb .LC148
+pushl yyin
+call __uflow
+addl $4,%esp
+movl %eax,%edi
+movl %edi,-16(%ebp)
+jmp .LC149
+.LC148:
+movl yyin,%edi
+leal 4(%edi),%edi
+movl (,%edi),%esi
+leal 1(%esi),%ebx
+movl %ebx,(,%edi)
+movb (,%esi),%bl
+movzbl %bl,%edi
+movl %edi,-16(%ebp)
+.LC149:
+movl -16(%ebp),%edi
+movl %edi,-12(%ebp)
+.LC147:
+movl -12(%ebp),%edi
+movl %edi,yytchar
+cmpl $10,%edi
+jne .LC144
+incl yylineno
+movl yytchar,%edi
+movl %edi,-8(%ebp)
+jmp .LC145
+.LC144:
+movl yytchar,%edi
+movl %edi,-8(%ebp)
+.LC145:
+cmpl $-1,-8(%ebp)
+jne .LC142
+movl $0,-4(%ebp)
+jmp .LC143
+.LC142:
+movl yytchar,%edi
+movl %edi,-4(%ebp)
+.LC143:
+movl -4(%ebp),%eax
+.LC137:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf150:
+.size yyinput,.Lf150-yyinput
+.globl yyoutput
+.align 16
+.type yyoutput,@function
+yyoutput:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl yyout,%edi
+movl 20(%edi),%esi
+movl 24(%edi),%edi
+cmpl %edi,%esi
+jb .LC153
+movl 20(%ebp),%edi
+movl %edi,%ebx
+movzbl %bl,%edi
+pushl %edi
+pushl yyout
+call __overflow
+addl $8,%esp
+jmp .LC154
+.LC153:
+movl yyout,%edi
+leal 20(%edi),%edi
+movl (,%edi),%esi
+leal 1(%esi),%ebx
+movl %ebx,(,%edi)
+movl 20(%ebp),%edi
+movl %edi,%ebx
+movb %bl,(,%esi)
+.LC154:
+movl $0,%eax
+.LC151:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf155:
+.size yyoutput,.Lf155-yyoutput
+.globl yyunput
+.align 16
+.type yyunput,@function
+yyunput:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl 20(%ebp),%edi
+movl %edi,yytchar
+cmpl $10,yytchar
+jne .LC157
+decl yylineno
+.LC157:
+movl yysptr,%edi
+leal 1(%edi),%esi
+movl %esi,yysptr
+movl yytchar,%esi
+movl %esi,%ebx
+movb %bl,(,%edi)
+movl $0,%eax
+.LC156:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf159:
+.size yyunput,.Lf159-yyunput
+.globl main
+.align 16
+.type main,@function
+main:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+call yyparse
+movl $0,%eax
+.LC160:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf161:
+.size main,.Lf161-main
+.globl yyerror
+.align 16
+.type yyerror,@function
+yyerror:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+pushl 20(%ebp)
+pushl $.LC163
+call printf
+addl $8,%esp
+movl $0,%eax
+.LC162:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf164:
+.size yyerror,.Lf164-yyerror
+.data
+.globl yyexca
+.align 2
+.type yyexca,@object
+yyexca:
+.word -1
+.word 1
+.word 0
+.word -1
+.word -2
+.word 0
+.size yyexca,12
+.globl yyact
+.align 2
+.type yyact,@object
+yyact:
+.word 12
+.word 2
+.word 9
+.word 8
+.word 17
+.word 11
+.word 25
+.word 17
+.word 15
+.word 18
+.word 16
+.word 10
+.word 18
+.word 17
+.word 15
+.word 7
+.word 16
+.word 13
+.word 18
+.word 5
+.word 3
+.word 1
+.word 0
+.word 19
+.word 20
+.word 0
+.word 0
+.word 21
+.word 22
+.word 23
+.word 24
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 6
+.word 14
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 0
+.word 4
+.word 6
+.size yyact,498
+.globl yypact
+.align 2
+.type yypact,@object
+yypact:
+.word -1000
+.word -9
+.word -1000
+.word 5
+.word -7
+.word -59
+.word -1000
+.word -1000
+.word -1000
+.word -40
+.word -29
+.word -40
+.word -40
+.word -1000
+.word -1000
+.word -40
+.word -40
+.word -40
+.word -40
+.word -38
+.word -35
+.word -38
+.word -38
+.word -1000
+.word -1000
+.word -1000
+.size yypact,52
+.globl yypgo
+.align 2
+.type yypgo,@object
+yypgo:
+.word 0
+.word 21
+.word 20
+.word 17
+.word 11
+.size yypgo,10
+.globl yyr1
+.align 2
+.type yyr1,@object
+yyr1:
+.word 0
+.word 1
+.word 1
+.word 1
+.word 1
+.word 2
+.word 4
+.word 4
+.word 4
+.word 4
+.word 4
+.word 4
+.word 4
+.word 4
+.word 3
+.size yyr1,30
+.globl yyr2
+.align 2
+.type yyr2,@object
+yyr2:
+.word 0
+.word 0
+.word 2
+.word 3
+.word 3
+.word 3
+.word 3
+.word 3
+.word 3
+.word 3
+.word 2
+.word 3
+.word 1
+.word 1
+.word 1
+.size yyr2,30
+.globl yychk
+.align 2
+.type yychk,@object
+yychk:
+.word -1000
+.word -1
+.word 10
+.word -2
+.word 256
+.word -3
+.word 257
+.word 10
+.word 10
+.word 61
+.word -4
+.word 45
+.word 40
+.word -3
+.word 258
+.word 43
+.word 45
+.word 42
+.word 47
+.word -4
+.word -4
+.word -4
+.word -4
+.word -4
+.word -4
+.word 41
+.size yychk,52
+.globl yydef
+.align 2
+.type yydef,@object
+yydef:
+.word 1
+.word -2
+.word 2
+.word 0
+.word 0
+.word 0
+.word 14
+.word 3
+.word 4
+.word 0
+.word 5
+.word 0
+.word 0
+.word 12
+.word 13
+.word 0
+.word 0
+.word 0
+.word 0
+.word 10
+.word 0
+.word 6
+.word 7
+.word 8
+.word 9
+.word 11
+.size yydef,52
+.globl yychar
+.align 4
+.type yychar,@object
+.size yychar,4
+yychar:
+.long -1
+.globl yynerrs
+.align 4
+.type yynerrs,@object
+.size yynerrs,4
+yynerrs:
+.long 0
+.globl yyerrflag
+.align 2
+.type yyerrflag,@object
+.size yyerrflag,2
+yyerrflag:
+.word 0
+.globl yyparse
+.text
+.align 16
+.type yyparse,@function
+yyparse:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+subl $332,%esp
+movw $0,-6(%ebp)
+movl $-1,yychar
+movl $0,yynerrs
+movw $0,yyerrflag
+leal -328(%ebp),%edi
+movl %edi,-12(%ebp)
+leal yyv-4,%edi
+movl %edi,-20(%ebp)
+.LC168:
+movl -12(%ebp),%edi
+leal 2(%edi),%edi
+movl %edi,-12(%ebp)
+leal -26(%ebp),%esi
+cmpl %esi,%edi
+jbe .LC169
+pushl $.LC172
+call yyerror
+addl $4,%esp
+movl $1,%eax
+jmp .LC165
+.LC169:
+movl -12(%ebp),%edi
+movw -6(%ebp),%si
+movw %si,(,%edi)
+movl -20(%ebp),%edi
+leal 4(%edi),%edi
+movl %edi,-20(%ebp)
+movl -20(%ebp),%edi
+movl yyval,%esi
+movl %esi,(,%edi)
+.LC173:
+movswl -6(%ebp),%edi
+movw yypact(,%edi,2),%di
+movw %di,-14(%ebp)
+movswl -14(%ebp),%edi
+cmpl $-1000,%edi
+jg .LC174
+jmp .LC176
+.LC174:
+cmpl $0,yychar
+jge .LC177
+call yylex
+movl %eax,yychar
+cmpl $0,%eax
+jge .LC179
+movl $0,yychar
+.LC179:
+.LC177:
+movswl -14(%ebp),%edi
+movl yychar,%esi
+leal (%esi,%edi),%edi
+movw %di,-14(%ebp)
+movswl %di,%edi
+cmpl $0,%edi
+jl .LC183
+movswl -14(%ebp),%edi
+cmpl $249,%edi
+jl .LC181
+.LC183:
+jmp .LC176
+.LC181:
+movswl -14(%ebp),%edi
+movw yyact(,%edi,2),%di
+movw %di,-14(%ebp)
+movswl %di,%edi
+movswl yychk(,%edi,2),%edi
+cmpl yychar,%edi
+jne .LC184
+movl $-1,yychar
+movl yylval,%edi
+movl %edi,yyval
+movw -14(%ebp),%di
+movw %di,-6(%ebp)
+movswl yyerrflag,%edi
+cmpl $0,%edi
+jle .LC168
+movswl yyerrflag,%edi
+subl $1,%edi
+movw %di,yyerrflag
+jmp .LC168
+.LC184:
+.LC176:
+movswl -6(%ebp),%edi
+movw yydef(,%edi,2),%di
+movw %di,-14(%ebp)
+movswl %di,%edi
+cmpl $-2,%edi
+jne .LC188
+cmpl $0,yychar
+jge .LC190
+call yylex
+movl %eax,yychar
+cmpl $0,%eax
+jge .LC192
+movl $0,yychar
+.LC192:
+.LC190:
+leal yyexca,%edi
+movl %edi,-24(%ebp)
+jmp .LC197
+.LC194:
+.LC195:
+movl -24(%ebp),%edi
+leal 4(%edi),%edi
+movl %edi,-24(%ebp)
+.LC197:
+movl -24(%ebp),%edi
+movswl (,%edi),%esi
+cmpl $-1,%esi
+jne .LC194
+movswl 2(%edi),%edi
+movswl -6(%ebp),%esi
+cmpl %esi,%edi
+jne .LC194
+jmp .LC199
+.LC198:
+movl -24(%ebp),%edi
+movswl (,%edi),%edi
+cmpl yychar,%edi
+jne .LC201
+jmp .LC200
+.LC201:
+.LC199:
+movl -24(%ebp),%edi
+leal 4(%edi),%edi
+movl %edi,-24(%ebp)
+movswl (,%edi),%edi
+cmpl $0,%edi
+jge .LC198
+.LC200:
+movl -24(%ebp),%edi
+movw 2(%edi),%di
+movw %di,-14(%ebp)
+movswl %di,%edi
+cmpl $0,%edi
+jge .LC203
+movl $0,%eax
+jmp .LC165
+.LC203:
+.LC188:
+movswl -14(%ebp),%edi
+cmpl $0,%edi
+jne .LC205
+movswl yyerrflag,%edi
+movl %edi,-332(%ebp)
+movl -332(%ebp),%edi
+cmpl $0,%edi
+jl .LC207
+cmpl $3,%edi
+jg .LC207
+jmp *.LC223(,%edi,4)
+.data
+.align 4
+.LC223:
+.long .LC210
+.long .LC213
+.long .LC213
+.long .LC220
+.text
+.LC210:
+pushl $.LC211
+call yyerror
+addl $4,%esp
+.LC212:
+incl yynerrs
+.LC213:
+movw $3,yyerrflag
+jmp .LC215
+.LC214:
+movl -12(%ebp),%edi
+movswl (,%edi),%edi
+movswl yypact(,%edi,2),%edi
+leal 256(%edi),%edi
+movw %di,-14(%ebp)
+movswl -14(%ebp),%edi
+cmpl $0,%edi
+jl .LC217
+cmpl $249,%edi
+jge .LC217
+movswl yyact(,%edi,2),%edi
+movswl yychk(,%edi,2),%edi
+cmpl $256,%edi
+jne .LC217
+movswl -14(%ebp),%edi
+movw yyact(,%edi,2),%di
+movw %di,-6(%ebp)
+jmp .LC168
+.LC217:
+movl -12(%ebp),%edi
+movswl (,%edi),%esi
+movw yypact(,%esi,2),%si
+movw %si,-14(%ebp)
+leal -2(%edi),%edi
+movl %edi,-12(%ebp)
+movl -20(%ebp),%edi
+leal -4(%edi),%edi
+movl %edi,-20(%ebp)
+.LC215:
+movl -12(%ebp),%edi
+leal -326(%ebp),%esi
+cmpl %esi,%edi
+jae .LC214
+.LC219:
+movl $1,%eax
+jmp .LC165
+.LC220:
+cmpl $0,yychar
+jne .LC221
+jmp .LC219
+.LC221:
+movl $-1,yychar
+jmp .LC173
+.LC207:
+.LC205:
+movw -14(%ebp),%di
+movswl %di,%esi
+leal (,%esi,2),%esi
+leal yyr2(%esi),%ebx
+movl -12(%ebp),%edx
+movswl (,%ebx),%ecx
+leal (,%ecx,2),%ecx
+subl %ecx,%edx
+movl %edx,-12(%ebp)
+movl -20(%ebp),%edx
+movl %edx,-4(%ebp)
+movswl (,%ebx),%ebx
+leal (,%ebx,4),%ebx
+subl %ebx,%edx
+movl %edx,-20(%ebp)
+movl -20(%ebp),%ebx
+movl 4(%ebx),%ebx
+movl %ebx,yyval
+movw %di,-328(%ebp)
+movw yyr1(%esi),%di
+movw %di,-14(%ebp)
+movswl -14(%ebp),%edi
+movswl yypgo(,%edi,2),%edi
+movl -12(%ebp),%esi
+movswl (,%esi),%esi
+leal (%esi,%edi),%edi
+leal 1(%edi),%edi
+movw %di,-26(%ebp)
+movswl -26(%ebp),%edi
+cmpl $249,%edi
+jge .LC226
+movw yyact(,%edi,2),%di
+movw %di,-6(%ebp)
+movswl %di,%edi
+movswl yychk(,%edi,2),%edi
+movswl -14(%ebp),%esi
+negl %esi
+cmpl %esi,%edi
+je .LC224
+.LC226:
+movswl -14(%ebp),%edi
+movswl yypgo(,%edi,2),%edi
+movw yyact(,%edi,2),%di
+movw %di,-6(%ebp)
+.LC224:
+movswl -328(%ebp),%edi
+movl %edi,-332(%ebp)
+movl -332(%ebp),%edi
+cmpl $4,%edi
+jl .LC168
+cmpl $14,%edi
+jg .LC168
+jmp *.LC248-16(,%edi,4)
+.data
+.align 4
+.LC248:
+.long .LC230
+.long .LC231
+.long .LC233
+.long .LC235
+.long .LC237
+.long .LC239
+.long .LC241
+.long .LC168
+.long .LC243
+.long .LC245
+.long .LC247
+.text
+.LC230:
+movw $0,yyerrflag
+jmp .LC168
+.LC231:
+pushl $.LC232
+call printf
+addl $4,%esp
+jmp .LC168
+.LC233:
+pushl $.LC234
+call printf
+addl $4,%esp
+jmp .LC168
+.LC235:
+pushl $.LC236
+call printf
+addl $4,%esp
+jmp .LC168
+.LC237:
+pushl $.LC238
+call printf
+addl $4,%esp
+jmp .LC168
+.LC239:
+pushl $.LC240
+call printf
+addl $4,%esp
+jmp .LC168
+.LC241:
+pushl $.LC242
+call printf
+addl $4,%esp
+jmp .LC168
+.LC243:
+pushl $.LC244
+call printf
+addl $4,%esp
+jmp .LC168
+.LC245:
+pushl $yytext
+pushl $.LC246
+call printf
+addl $8,%esp
+jmp .LC168
+.LC247:
+pushl $yytext
+pushl $.LC163
+call printf
+addl $8,%esp
+jmp .LC168
+.LC165:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf250:
+.size yyparse,.Lf250-yyparse
+.globl yywrap
+.align 16
+.type yywrap,@function
+yywrap:
+pushl %ebp
+pushl %ebx
+pushl %esi
+pushl %edi
+movl %esp,%ebp
+movl $1,%eax
+.LC251:
+movl %ebp,%esp
+popl %edi
+popl %esi
+popl %ebx
+popl %ebp
+ret
+.Lf252:
+.size yywrap,.Lf252-yywrap
+.bss
+.globl yyv
+.align 4
+.type yyv,@object
+.size yyv,600
+.comm yyv,600
+.globl yyfnd
+.align 4
+.type yyfnd,@object
+.size yyfnd,4
+.comm yyfnd,4
+.globl yyolsp
+.align 4
+.type yyolsp,@object
+.size yyolsp,4
+.comm yyolsp,4
+.globl yylsp
+.align 4
+.type yylsp,@object
+.size yylsp,4
+.comm yylsp,4
+.globl yylstate
+.align 4
+.type yylstate,@object
+.size yylstate,800
+.comm yylstate,800
+.globl yyestate
+.align 4
+.type yyestate,@object
+.size yyestate,4
+.comm yyestate,4
+.globl yytchar
+.align 4
+.type yytchar,@object
+.size yytchar,4
+.comm yytchar,4
+.globl yysbuf
+.align 1
+.type yysbuf,@object
+.size yysbuf,200
+.comm yysbuf,200
+.globl yymorfg
+.align 4
+.type yymorfg,@object
+.size yymorfg,4
+.comm yymorfg,4
+.globl yytext
+.align 1
+.type yytext,@object
+.size yytext,200
+.comm yytext,200
+.globl yyleng
+.align 4
+.type yyleng,@object
+.size yyleng,4
+.comm yyleng,4
+.globl yyval
+.align 4
+.type yyval,@object
+.size yyval,4
+.comm yyval,4
+.globl yylval
+.align 4
+.type yylval,@object
+.size yylval,4
+.comm yylval,4
+.data
+.align 1
+.LC246:
+.byte 112
+.byte 117
+.byte 115
+.byte 104
+.byte 32
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.LC244:
+.byte 108
+.byte 111
+.byte 97
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC242:
+.byte 110
+.byte 101
+.byte 103
+.byte 97
+.byte 116
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.LC240:
+.byte 100
+.byte 105
+.byte 118
+.byte 105
+.byte 100
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.LC238:
+.byte 109
+.byte 117
+.byte 108
+.byte 116
+.byte 105
+.byte 112
+.byte 108
+.byte 121
+.byte 10
+.byte 0
+.align 1
+.LC236:
+.byte 110
+.byte 101
+.byte 103
+.byte 97
+.byte 116
+.byte 101
+.byte 10
+.byte 97
+.byte 100
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC234:
+.byte 97
+.byte 100
+.byte 100
+.byte 10
+.byte 0
+.align 1
+.LC232:
+.byte 115
+.byte 116
+.byte 111
+.byte 114
+.byte 101
+.byte 10
+.byte 0
+.align 1
+.LC211:
+.byte 115
+.byte 121
+.byte 110
+.byte 116
+.byte 97
+.byte 120
+.byte 32
+.byte 101
+.byte 114
+.byte 114
+.byte 111
+.byte 114
+.byte 0
+.align 1
+.LC172:
+.byte 121
+.byte 97
+.byte 99
+.byte 99
+.byte 32
+.byte 115
+.byte 116
+.byte 97
+.byte 99
+.byte 107
+.byte 32
+.byte 111
+.byte 118
+.byte 101
+.byte 114
+.byte 102
+.byte 108
+.byte 111
+.byte 119
+.byte 0
+.align 1
+.LC163:
+.byte 37
+.byte 115
+.byte 10
+.byte 0
+.align 1
+.LC16:
+.byte 98
+.byte 97
+.byte 100
+.byte 32
+.byte 115
+.byte 119
+.byte 105
+.byte 116
+.byte 99
+.byte 104
+.byte 32
+.byte 121
+.byte 121
+.byte 108
+.byte 111
+.byte 111
+.byte 107
+.byte 32
+.byte 37
+.byte 100
+.byte 0
+.text
+.ident "LCC: 4.1"
diff --git a/lcc/x86/win32/tst/8q.1bk b/lcc/x86/win32/tst/8q.1bk
new file mode 100755
index 0000000..c66df8e
--- /dev/null
+++ b/lcc/x86/win32/tst/8q.1bk
@@ -0,0 +1,92 @@
+1 5 8 6 3 7 2 4
+1 6 8 3 7 4 2 5
+1 7 4 6 8 2 5 3
+1 7 5 8 2 4 6 3
+2 4 6 8 3 1 7 5
+2 5 7 1 3 8 6 4
+2 5 7 4 1 8 6 3
+2 6 1 7 4 8 3 5
+2 6 8 3 1 4 7 5
+2 7 3 6 8 5 1 4
+2 7 5 8 1 4 6 3
+2 8 6 1 3 5 7 4
+3 1 7 5 8 2 4 6
+3 5 2 8 1 7 4 6
+3 5 2 8 6 4 7 1
+3 5 7 1 4 2 8 6
+3 5 8 4 1 7 2 6
+3 6 2 5 8 1 7 4
+3 6 2 7 1 4 8 5
+3 6 2 7 5 1 8 4
+3 6 4 1 8 5 7 2
+3 6 4 2 8 5 7 1
+3 6 8 1 4 7 5 2
+3 6 8 1 5 7 2 4
+3 6 8 2 4 1 7 5
+3 7 2 8 5 1 4 6
+3 7 2 8 6 4 1 5
+3 8 4 7 1 6 2 5
+4 1 5 8 2 7 3 6
+4 1 5 8 6 3 7 2
+4 2 5 8 6 1 3 7
+4 2 7 3 6 8 1 5
+4 2 7 3 6 8 5 1
+4 2 7 5 1 8 6 3
+4 2 8 5 7 1 3 6
+4 2 8 6 1 3 5 7
+4 6 1 5 2 8 3 7
+4 6 8 2 7 1 3 5
+4 6 8 3 1 7 5 2
+4 7 1 8 5 2 6 3
+4 7 3 8 2 5 1 6
+4 7 5 2 6 1 3 8
+4 7 5 3 1 6 8 2
+4 8 1 3 6 2 7 5
+4 8 1 5 7 2 6 3
+4 8 5 3 1 7 2 6
+5 1 4 6 8 2 7 3
+5 1 8 4 2 7 3 6
+5 1 8 6 3 7 2 4
+5 2 4 6 8 3 1 7
+5 2 4 7 3 8 6 1
+5 2 6 1 7 4 8 3
+5 2 8 1 4 7 3 6
+5 3 1 6 8 2 4 7
+5 3 1 7 2 8 6 4
+5 3 8 4 7 1 6 2
+5 7 1 3 8 6 4 2
+5 7 1 4 2 8 6 3
+5 7 2 4 8 1 3 6
+5 7 2 6 3 1 4 8
+5 7 2 6 3 1 8 4
+5 7 4 1 3 8 6 2
+5 8 4 1 3 6 2 7
+5 8 4 1 7 2 6 3
+6 1 5 2 8 3 7 4
+6 2 7 1 3 5 8 4
+6 2 7 1 4 8 5 3
+6 3 1 7 5 8 2 4
+6 3 1 8 4 2 7 5
+6 3 1 8 5 2 4 7
+6 3 5 7 1 4 2 8
+6 3 5 8 1 4 2 7
+6 3 7 2 4 8 1 5
+6 3 7 2 8 5 1 4
+6 3 7 4 1 8 2 5
+6 4 1 5 8 2 7 3
+6 4 2 8 5 7 1 3
+6 4 7 1 3 5 2 8
+6 4 7 1 8 2 5 3
+6 8 2 4 1 7 5 3
+7 1 3 8 6 4 2 5
+7 2 4 1 8 5 3 6
+7 2 6 3 1 4 8 5
+7 3 1 6 8 5 2 4
+7 3 8 2 5 1 6 4
+7 4 2 5 8 1 3 6
+7 4 2 8 6 1 3 5
+7 5 3 1 6 8 2 4
+8 2 4 1 7 5 3 6
+8 2 5 3 1 7 4 6
+8 3 1 6 2 5 7 4
+8 4 1 3 6 2 7 5
diff --git a/lcc/x86/win32/tst/8q.2bk b/lcc/x86/win32/tst/8q.2bk
new file mode 100755
index 0000000..fb28350
--- /dev/null
+++ b/lcc/x86/win32/tst/8q.2bk
@@ -0,0 +1,2 @@
+tst/8q.c:30: warning: missing return value
+tst/8q.c:39: warning: missing return value
diff --git a/lcc/x86/win32/tst/8q.sbk b/lcc/x86/win32/tst/8q.sbk
new file mode 100755
index 0000000..85cce1a
--- /dev/null
+++ b/lcc/x86/win32/tst/8q.sbk
@@ -0,0 +1,176 @@
+.486
+.model flat
+extrn __fltused:near
+extrn __ftol:near
+public _main
+_TEXT segment
+_main:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,4
+mov dword ptr (-4)[ebp],0
+L2:
+mov edi,dword ptr (-4)[ebp]
+lea edi,[edi*4]
+mov dword ptr (_down)[edi],1
+mov dword ptr (_up)[edi],1
+L3:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],15
+jl L2
+mov dword ptr (-4)[ebp],0
+L6:
+mov edi,dword ptr (-4)[ebp]
+mov dword ptr (_rows)[edi*4],1
+L7:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],8
+jl L6
+push 0
+call _queens
+add esp,4
+mov eax,0
+L1:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _queens
+_queens:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,4
+mov dword ptr (-4)[ebp],0
+L11:
+mov edi,dword ptr (-4)[ebp]
+cmp dword ptr (_rows)[edi*4],0
+je L15
+mov esi,dword ptr (20)[ebp]
+mov ebx,edi
+sub ebx,esi
+cmp dword ptr (_up+28)[ebx*4],0
+je L15
+lea edi,[esi][edi]
+cmp dword ptr (_down)[edi*4],0
+je L15
+mov edi,dword ptr (-4)[ebp]
+mov esi,dword ptr (20)[ebp]
+lea ebx,[esi][edi]
+mov dword ptr (_down)[ebx*4],0
+mov ebx,edi
+sub ebx,esi
+mov dword ptr (_up+28)[ebx*4],0
+mov dword ptr (_rows)[edi*4],0
+mov edi,dword ptr (20)[ebp]
+mov esi,dword ptr (-4)[ebp]
+mov dword ptr (_x)[edi*4],esi
+cmp dword ptr (20)[ebp],7
+jne L19
+call _print
+add esp,0
+jmp L20
+L19:
+mov edi,dword ptr (20)[ebp]
+lea edi,(1)[edi]
+push edi
+call _queens
+add esp,4
+L20:
+mov edi,dword ptr (-4)[ebp]
+mov esi,dword ptr (20)[ebp]
+lea ebx,[esi][edi]
+mov dword ptr (_down)[ebx*4],1
+mov ebx,edi
+sub ebx,esi
+mov dword ptr (_up+28)[ebx*4],1
+mov dword ptr (_rows)[edi*4],1
+L15:
+L12:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],8
+jl L11
+mov eax,0
+L10:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _print
+_print:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,4
+mov dword ptr (-4)[ebp],0
+L23:
+mov edi,dword ptr (-4)[ebp]
+mov edi,dword ptr (_x)[edi*4]
+lea edi,(49)[edi]
+push edi
+lea edi,(L27)
+push edi
+call _printf
+add esp,8
+L24:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],8
+jl L23
+lea edi,(L28)
+push edi
+call _printf
+add esp,4
+mov eax,0
+L22:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+extrn _printf:near
+_TEXT segment
+_TEXT ends
+_DATA segment
+public _x
+align 4
+_x label byte
+db 32 dup (0)
+public _rows
+align 4
+_rows label byte
+db 32 dup (0)
+public _down
+align 4
+_down label byte
+db 60 dup (0)
+public _up
+align 4
+_up label byte
+db 60 dup (0)
+_DATA ends
+_TEXT segment
+align 1
+L28 label byte
+db 10
+db 0
+align 1
+L27 label byte
+db 37
+db 99
+db 32
+db 0
+_TEXT ends
+end
diff --git a/lcc/x86/win32/tst/array.1bk b/lcc/x86/win32/tst/array.1bk
new file mode 100755
index 0000000..e188568
--- /dev/null
+++ b/lcc/x86/win32/tst/array.1bk
@@ -0,0 +1,4 @@
+ 0 1 2 3 1000 1001 1002 1003 2000 2001 2002 2003
+ 0 1 2 3 1000 1001 1002 1003 2000 2001 2002 2003
+ 0 1 2 3 1000 1001 1002 1003 2000 2001 2002 2003
+ 0 1 2 3 1000 1001 1002 1003 2000 2001 2002 2003
diff --git a/lcc/x86/win32/tst/array.2bk b/lcc/x86/win32/tst/array.2bk
new file mode 100755
index 0000000..0a9b206
--- /dev/null
+++ b/lcc/x86/win32/tst/array.2bk
@@ -0,0 +1,2 @@
+tst/array.c:33: warning: missing return value
+tst/array.c:48: warning: missing return value
diff --git a/lcc/x86/win32/tst/array.sbk b/lcc/x86/win32/tst/array.sbk
new file mode 100755
index 0000000..a89f3c7
--- /dev/null
+++ b/lcc/x86/win32/tst/array.sbk
@@ -0,0 +1,240 @@
+.486
+.model flat
+extrn __fltused:near
+extrn __ftol:near
+public _main
+_TEXT segment
+_main:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,60
+mov dword ptr (-8)[ebp],0
+L2:
+mov dword ptr (-4)[ebp],0
+L6:
+mov edi,dword ptr (-4)[ebp]
+mov esi,dword ptr (-8)[ebp]
+mov ebx,esi
+sal ebx,4
+imul esi,esi,1000
+lea esi,[edi][esi]
+mov dword ptr (_x)[ebx][edi*4],esi
+L7:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],4
+jl L6
+mov edi,dword ptr (-8)[ebp]
+mov esi,edi
+sal esi,4
+lea esi,(_x)[esi]
+mov dword ptr (_y)[edi*4],esi
+L3:
+inc dword ptr (-8)[ebp]
+cmp dword ptr (-8)[ebp],3
+jl L2
+call _f
+add esp,0
+mov dword ptr (-8)[ebp],0
+L10:
+mov edi,dword ptr (-8)[ebp]
+mov esi,edi
+sal esi,4
+lea esi,(-60)[ebp][esi]
+mov dword ptr (-12)[ebp],esi
+mov dword ptr (_y)[edi*4],esi
+mov dword ptr (-4)[ebp],0
+L14:
+mov edi,dword ptr (-4)[ebp]
+lea edi,[edi*4]
+mov esi,dword ptr (-12)[ebp]
+mov ebx,dword ptr (-8)[ebp]
+sal ebx,4
+mov ebx,dword ptr (_x)[ebx][edi]
+mov dword ptr [esi][edi],ebx
+L15:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],4
+jl L14
+L11:
+inc dword ptr (-8)[ebp]
+cmp dword ptr (-8)[ebp],3
+jl L10
+lea edi,(_y)
+push edi
+lea edi,(-60)[ebp]
+push edi
+call _g
+add esp,8
+mov eax,0
+L1:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _f
+_f:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,8
+mov dword ptr (-8)[ebp],0
+L19:
+mov dword ptr (-4)[ebp],0
+L23:
+mov edi,dword ptr (-4)[ebp]
+mov esi,dword ptr (-8)[ebp]
+sal esi,4
+mov edi,dword ptr (_x)[esi][edi*4]
+push edi
+lea edi,(L27)
+push edi
+call _printf
+add esp,8
+L24:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],4
+jl L23
+L20:
+inc dword ptr (-8)[ebp]
+cmp dword ptr (-8)[ebp],3
+jl L19
+lea edi,(L28)
+push edi
+call _printf
+add esp,4
+mov dword ptr (-8)[ebp],0
+L29:
+mov dword ptr (-4)[ebp],0
+L33:
+mov edi,dword ptr (-4)[ebp]
+mov esi,dword ptr (-8)[ebp]
+mov esi,dword ptr (_y)[esi*4]
+mov edi,dword ptr [esi][edi*4]
+push edi
+lea edi,(L27)
+push edi
+call _printf
+add esp,8
+L34:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],4
+jl L33
+L30:
+inc dword ptr (-8)[ebp]
+cmp dword ptr (-8)[ebp],3
+jl L29
+lea edi,(L28)
+push edi
+call _printf
+add esp,4
+mov eax,0
+L18:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _g
+_g:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,8
+mov dword ptr (-8)[ebp],0
+L38:
+mov dword ptr (-4)[ebp],0
+L42:
+mov edi,dword ptr (-4)[ebp]
+mov esi,dword ptr (-8)[ebp]
+sal esi,4
+mov ebx,dword ptr (20)[ebp]
+lea esi,[ebx][esi]
+mov edi,dword ptr [esi][edi*4]
+push edi
+lea edi,(L27)
+push edi
+call _printf
+add esp,8
+L43:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],4
+jl L42
+L39:
+inc dword ptr (-8)[ebp]
+cmp dword ptr (-8)[ebp],3
+jl L38
+lea edi,(L28)
+push edi
+call _printf
+add esp,4
+mov dword ptr (-8)[ebp],0
+L46:
+mov dword ptr (-4)[ebp],0
+L50:
+mov edi,dword ptr (-4)[ebp]
+mov esi,dword ptr (-8)[ebp]
+mov ebx,dword ptr (24)[ebp]
+mov esi,dword ptr [ebx][esi*4]
+mov edi,dword ptr [esi][edi*4]
+push edi
+lea edi,(L27)
+push edi
+call _printf
+add esp,8
+L51:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],4
+jl L50
+L47:
+inc dword ptr (-8)[ebp]
+cmp dword ptr (-8)[ebp],3
+jl L46
+lea edi,(L28)
+push edi
+call _printf
+add esp,4
+mov eax,0
+L37:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+extrn _printf:near
+_TEXT segment
+_TEXT ends
+_DATA segment
+public _y
+align 4
+_y label byte
+db 12 dup (0)
+public _x
+align 4
+_x label byte
+db 48 dup (0)
+_DATA ends
+_TEXT segment
+align 1
+L28 label byte
+db 10
+db 0
+align 1
+L27 label byte
+db 32
+db 37
+db 100
+db 0
+_TEXT ends
+end
diff --git a/lcc/x86/win32/tst/cf.1bk b/lcc/x86/win32/tst/cf.1bk
new file mode 100755
index 0000000..24e21ba
--- /dev/null
+++ b/lcc/x86/win32/tst/cf.1bk
@@ -0,0 +1,51 @@
+char freq
+011 8.1
+012 6.1
+040 11.9
+! 0.2
+" 1.5
+% 0.6
+& 0.4
+' 0.4
+( 2.9
+) 2.9
+* 0.8
++ 1.3
+, 1.3
+- 0.4
+. 0.6
+/ 1.0
+0 2.5
+1 1.9
+2 0.6
+3 0.2
+7 0.4
+8 0.2
+; 3.8
+< 0.8
+= 2.7
+> 0.2
+[ 1.5
+\ 0.8
+] 1.5
+a 3.1
+c 4.4
+e 2.3
+f 6.0
+g 1.3
+h 1.0
+i 5.0
+l 1.0
+m 0.2
+n 3.3
+o 2.1
+p 1.0
+q 0.4
+r 4.2
+s 0.6
+t 3.8
+u 1.2
+v 0.6
+w 0.2
+{ 0.6
+} 0.6
diff --git a/lcc/x86/win32/tst/cf.2bk b/lcc/x86/win32/tst/cf.2bk
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/x86/win32/tst/cf.2bk
diff --git a/lcc/x86/win32/tst/cf.sbk b/lcc/x86/win32/tst/cf.sbk
new file mode 100755
index 0000000..6fd654d
--- /dev/null
+++ b/lcc/x86/win32/tst/cf.sbk
@@ -0,0 +1,185 @@
+.486
+.model flat
+extrn __fltused:near
+extrn __ftol:near
+public _main
+_TEXT segment
+_main:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,24
+cmp dword ptr (20)[ebp],1
+jg L2
+fld dword ptr (L4)
+fstp dword ptr (-16)[ebp]
+jmp L3
+L2:
+mov edi,dword ptr (24)[ebp]
+mov edi,dword ptr (4)[edi]
+push edi
+call _atof
+add esp,4
+fstp dword ptr (-20)[ebp]
+fld dword ptr (-20)[ebp]
+fdiv dword ptr (L5)
+fstp dword ptr (-16)[ebp]
+L3:
+mov dword ptr (-4)[ebp],0
+L6:
+mov edi,dword ptr (-4)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-4)[ebp],esi
+fld dword ptr (L4)
+fstp dword ptr (_f)[edi*4]
+L7:
+cmp dword ptr (-4)[ebp],127
+jle L6
+mov dword ptr (-8)[ebp],0
+jmp L11
+L10:
+mov edi,dword ptr (-12)[ebp]
+lea edi,(_f)[edi*4]
+fld dword ptr [edi]
+fadd dword ptr (L13)
+fstp dword ptr [edi]
+inc dword ptr (-8)[ebp]
+L11:
+call _getchar
+add esp,0
+mov dword ptr (-12)[ebp],eax
+cmp eax,-1
+jne L10
+lea edi,(L14)
+push edi
+call _printf
+add esp,4
+mov dword ptr (-4)[ebp],0
+L15:
+mov edi,dword ptr (-4)[ebp]
+fld dword ptr (_f)[edi*4]
+fstp dword ptr (-24)[ebp]
+fld dword ptr (L4)
+fcomp dword ptr (-24)[ebp]
+fstsw ax
+sahf
+je L19
+fld dword ptr (-24)[ebp]
+mov edi,dword ptr (-8)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fdivp st(1),st
+fld dword ptr (-16)[ebp]
+fcompp
+fstsw ax
+sahf
+ja L19
+cmp dword ptr (-4)[ebp],32
+jg L21
+mov edi,dword ptr (-4)[ebp]
+push edi
+lea edi,(L23)
+push edi
+call _printf
+add esp,8
+jmp L22
+L21:
+mov edi,dword ptr (-4)[ebp]
+push edi
+lea edi,(L24)
+push edi
+call _printf
+add esp,8
+L22:
+fld dword ptr (L5)
+mov edi,dword ptr (-4)[ebp]
+fmul dword ptr (_f)[edi*4]
+mov edi,dword ptr (-8)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fdivp st(1),st
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L25)
+push edi
+call _printf
+add esp,12
+L19:
+L16:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],127
+jle L15
+mov eax,0
+L1:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+extrn _printf:near
+_TEXT segment
+_TEXT ends
+extrn _getchar:near
+_TEXT segment
+_TEXT ends
+extrn _atof:near
+_TEXT segment
+_TEXT ends
+_DATA segment
+public _f
+align 4
+_f label byte
+db 512 dup (0)
+_DATA ends
+_TEXT segment
+align 1
+L25 label byte
+db 9
+db 37
+db 46
+db 49
+db 102
+db 10
+db 0
+align 1
+L24 label byte
+db 37
+db 99
+db 0
+align 1
+L23 label byte
+db 37
+db 48
+db 51
+db 111
+db 0
+align 1
+L14 label byte
+db 99
+db 104
+db 97
+db 114
+db 9
+db 102
+db 114
+db 101
+db 113
+db 10
+db 0
+align 4
+L13 label byte
+dd 03f800000H
+align 4
+L5 label byte
+dd 042c80000H
+align 4
+L4 label byte
+dd 00H
+_TEXT ends
+end
diff --git a/lcc/x86/win32/tst/cq.1bk b/lcc/x86/win32/tst/cq.1bk
new file mode 100755
index 0000000..9ea7979
--- /dev/null
+++ b/lcc/x86/win32/tst/cq.1bk
@@ -0,0 +1,48 @@
+Section s22 returned 0.
+Decimal and octal/hex constants sometimes give
+ different results when assigned to longs.
+Decimal and octal/hex constants sometimes give
+ different results when assigned to longs.
+Section s241 returned 0.
+Section s243 returned 0.
+Section s244 returned 0.
+Section s25 returned 0.
+ 8 bits in chars.
+ 32 bits in ints.
+ 16 bits in shorts.
+ 32 bits in longs.
+ 32 bits in unsigneds.
+ 32 bits in floats.
+ 64 bits in doubles.
+1.192093e-007 is the least number that can be added to 1. (float).
+2.220446e-016 is the least number that can be added to 1. (double).
+Section s26 returned 0.
+Section s4 returned 0.
+Section s61 returned 0.
+Section s626 returned 0.
+Section s71 returned 0.
+Section s72 returned 0.
+Section s757 returned 0.
+Section s7813 returned 0.
+Section s714 returned 0.
+Section s715 returned 0.
+Register count for char is unreliable.
+Register count for pointer is unreliable.
+Register count for int is unreliable.
+Section s81 returned 0.
+Section s84 returned 0.
+char alignment: 1
+short alignment: 2
+int alignment: 4
+long alignment: 4
+unsigned alignment: 4
+float alignment: 4
+double alignment: 4
+Sign extension in fields
+Be especially careful with 1-bit fields!
+Section s85 returned 0.
+Section s86 returned 0.
+Section s88 returned 0.
+Section s9 returned 0.
+
+No errors detected.
diff --git a/lcc/x86/win32/tst/cq.2bk b/lcc/x86/win32/tst/cq.2bk
new file mode 100755
index 0000000..295f5b6
--- /dev/null
+++ b/lcc/x86/win32/tst/cq.2bk
@@ -0,0 +1,25 @@
+tst/cq.c:394: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:394: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:394: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:395: warning: overflow in constant `4294967296'
+tst/cq.c:395: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:395: warning: overflow in constant `040000000000'
+tst/cq.c:395: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:395: warning: overflow in constant `0x100000000'
+tst/cq.c:395: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:396: warning: overflow in constant `68719476735'
+tst/cq.c:396: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:396: warning: overflow in constant `0777777777777'
+tst/cq.c:396: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:396: warning: overflow in constant `0xfffffffff'
+tst/cq.c:396: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:397: warning: overflow in constant `68719476736'
+tst/cq.c:397: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:397: warning: overflow in constant `01000000000000'
+tst/cq.c:397: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:397: warning: overflow in constant `0x1000000000'
+tst/cq.c:397: warning: overflow in converting constant expression from `unsigned long' to `long int'
+tst/cq.c:533: warning: missing return value
+tst/cq.c:1169: warning: missing return value
+tst/cq.c:5294: warning: unreachable code
+tst/cq.c:5303: warning: missing return value
diff --git a/lcc/x86/win32/tst/cq.sbk b/lcc/x86/win32/tst/cq.sbk
new file mode 100755
index 0000000..a9726b9
--- /dev/null
+++ b/lcc/x86/win32/tst/cq.sbk
@@ -0,0 +1,16642 @@
+.486
+.model flat
+extrn __fltused:near
+extrn __ftol:near
+_DATA segment
+align 4
+L2 label byte
+dd _s22
+dd _s241
+dd _s243
+dd _s244
+dd _s25
+dd _s26
+dd _s4
+dd _s61
+dd _s626
+dd _s71
+dd _s72
+dd _s757
+dd _s7813
+dd _s714
+dd _s715
+dd _s81
+dd _s84
+dd _s85
+dd _s86
+dd _s88
+dd _s9
+_DATA ends
+_DATA segment
+align 4
+L3 label byte
+db 68 dup (0)
+align 4
+L4 label byte
+db 4 dup (0)
+public _main
+_DATA ends
+_TEXT segment
+_main:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,4
+mov dword ptr (L3+36),1
+mov dword ptr (L3+40),1
+mov dword ptr (L3+44),1
+mov dword ptr (L3+48),1
+lea edi,(L3)
+mov dword ptr (L4),edi
+mov dword ptr (-4)[ebp],0
+jmp L12
+L9:
+mov edi,dword ptr (L4)
+push edi
+mov edi,dword ptr (-4)[ebp]
+call dword ptr (L2)[edi*4]
+add esp,4
+mov dword ptr (L3+52),eax
+mov edi,dword ptr (L3+56)
+mov esi,dword ptr (L3+52)
+lea edi,[esi][edi]
+mov dword ptr (L3+56),edi
+cmp dword ptr (L3+36),0
+je L17
+mov edi,dword ptr (L3+52)
+push edi
+lea edi,(L3+60)
+push edi
+lea edi,(L20)
+push edi
+call _printf
+add esp,12
+L17:
+L10:
+inc dword ptr (-4)[ebp]
+L12:
+mov edi,dword ptr (-4)[ebp]
+cmp edi,21
+jb L9
+cmp dword ptr (L3+56),0
+jne L23
+lea edi,(L26)
+push edi
+call _printf
+add esp,4
+jmp L24
+L23:
+lea edi,(L27)
+push edi
+call _printf
+add esp,4
+L24:
+mov eax,0
+L1:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 1
+L29 label byte
+db 115
+db 50
+db 50
+db 44
+db 101
+db 114
+db 37
+db 100
+db 10
+db 0
+align 1
+L30 label byte
+db 115
+db 50
+db 50
+db 32
+db 32
+db 32
+db 32
+db 0
+public _s22
+_DATA ends
+_TEXT segment
+_s22:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,32
+mov dword ptr (-12)[ebp],0
+lea edi,(L30)
+mov dword ptr (-4)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+lea edi,(60)[edi]
+mov dword ptr (-8)[ebp],edi
+L31:
+L32:
+mov edi,dword ptr (-8)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-8)[ebp],esi
+mov esi,dword ptr (-4)[ebp]
+lea ebx,(1)[esi]
+mov dword ptr (-4)[ebp],ebx
+mov bl,byte ptr [esi]
+mov byte ptr [edi],bl
+movsx edi,bl
+cmp edi,0
+jne L31
+mov dword ptr (-16)[ebp],1
+mov dword ptr (-24)[ebp],2
+mov dword ptr (-28)[ebp],3
+mov dword ptr (-20)[ebp],4
+mov edi,dword ptr (-16)[ebp]
+mov esi,dword ptr (-24)[ebp]
+lea edi,[esi][edi]
+mov esi,dword ptr (-28)[ebp]
+lea edi,[esi][edi]
+mov esi,dword ptr (-20)[ebp]
+lea edi,[esi][edi]
+cmp edi,10
+je L34
+inc dword ptr (-12)[ebp]
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L36
+push 1
+lea edi,(L29)
+push edi
+call _printf
+add esp,8
+L36:
+L34:
+mov dword ptr (-32)[ebp],2
+mov edi,dword ptr (-16)[ebp]
+cmp dword ptr (-32)[ebp],edi
+jne L38
+add dword ptr (-12)[ebp],4
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L40
+push 4
+lea edi,(L29)
+push edi
+call _printf
+add esp,8
+L40:
+L38:
+mov eax,dword ptr (-12)[ebp]
+L28:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 1
+L43 label byte
+db 115
+db 50
+db 52
+db 49
+db 44
+db 101
+db 114
+db 37
+db 100
+db 10
+db 0
+align 1
+L44 label byte
+db 115
+db 50
+db 52
+db 49
+db 32
+db 32
+db 32
+db 0
+align 4
+L45 label byte
+dd 0
+dd 0
+dd 0
+dd 0
+dd 0
+dd 0
+dd 0
+dd 0
+dd 0
+dd 0
+dd 0
+dd 0
+dd 0
+dd 0
+dd 0
+dd 0
+dd 0
+dd 0
+dd 6
+dd 0
+dd 8
+dd 0
+dd 12
+dd 0
+dd 16
+dd 0
+dd 18
+dd 0
+dd 20
+dd 0
+dd 24
+dd 0
+dd 28
+dd 0
+dd 30
+dd 0
+dd 32
+dd 0
+dd 36
+public _s241
+_DATA ends
+_TEXT segment
+_s241:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,488
+mov dword ptr (-484)[ebp],0
+mov dword ptr (-488)[ebp],0
+lea edi,(L44)
+mov dword ptr (-476)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+lea edi,(60)[edi]
+mov dword ptr (-480)[ebp],edi
+L46:
+L47:
+mov edi,dword ptr (-480)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-480)[ebp],esi
+mov esi,dword ptr (-476)[ebp]
+lea ebx,(1)[esi]
+mov dword ptr (-476)[ebp],ebx
+mov bl,byte ptr [esi]
+mov byte ptr [edi],bl
+movsx edi,bl
+cmp edi,0
+jne L46
+jmp L49
+inc dword ptr (-484)[ebp]
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L51
+push 1
+lea edi,(L43)
+push edi
+call _printf
+add esp,8
+L51:
+L49:
+jmp L53
+add dword ptr (-484)[ebp],2
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L55
+push 2
+lea edi,(L43)
+push edi
+call _printf
+add esp,8
+L55:
+L53:
+jmp L57
+add dword ptr (-484)[ebp],4
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L59
+push 4
+lea edi,(L43)
+push edi
+call _printf
+add esp,8
+L59:
+L57:
+jmp L61
+add dword ptr (-484)[ebp],8
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L63
+push 8
+lea edi,(L43)
+push edi
+call _printf
+add esp,8
+L63:
+L61:
+mov dword ptr (-4)[ebp],0
+L65:
+mov edi,dword ptr (-4)[ebp]
+mov dword ptr (L45)[edi*4],edi
+L66:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],17
+jl L65
+mov dword ptr (-4)[ebp],18
+L69:
+mov edi,dword ptr (-4)[ebp]
+lea edi,(L45)[edi*4]
+mov esi,dword ptr [edi]
+push esi
+call _pow2
+add esp,4
+mov dword ptr [edi],eax
+mov edi,dword ptr (-4)[ebp]
+lea edi,[edi*4]
+mov esi,dword ptr (L45)[edi]
+sub esi,1
+mov dword ptr (L45-4)[edi],esi
+add dword ptr (-4)[ebp],2
+L70:
+cmp dword ptr (-4)[ebp],39
+jl L69
+mov dword ptr (-160)[ebp],0
+mov dword ptr (-316)[ebp],0
+mov dword ptr (-472)[ebp],0
+mov dword ptr (-156)[ebp],1
+mov dword ptr (-312)[ebp],1
+mov dword ptr (-468)[ebp],1
+mov dword ptr (-152)[ebp],2
+mov dword ptr (-308)[ebp],2
+mov dword ptr (-464)[ebp],2
+mov dword ptr (-148)[ebp],3
+mov dword ptr (-304)[ebp],3
+mov dword ptr (-460)[ebp],3
+mov dword ptr (-144)[ebp],4
+mov dword ptr (-300)[ebp],4
+mov dword ptr (-456)[ebp],4
+mov dword ptr (-140)[ebp],5
+mov dword ptr (-296)[ebp],5
+mov dword ptr (-452)[ebp],5
+mov dword ptr (-136)[ebp],6
+mov dword ptr (-292)[ebp],6
+mov dword ptr (-448)[ebp],6
+mov dword ptr (-132)[ebp],7
+mov dword ptr (-288)[ebp],7
+mov dword ptr (-444)[ebp],7
+mov dword ptr (-128)[ebp],8
+mov dword ptr (-284)[ebp],8
+mov dword ptr (-440)[ebp],8
+mov dword ptr (-124)[ebp],9
+mov dword ptr (-280)[ebp],9
+mov dword ptr (-436)[ebp],9
+mov dword ptr (-120)[ebp],10
+mov dword ptr (-276)[ebp],10
+mov dword ptr (-432)[ebp],10
+mov dword ptr (-116)[ebp],11
+mov dword ptr (-272)[ebp],11
+mov dword ptr (-428)[ebp],11
+mov dword ptr (-112)[ebp],12
+mov dword ptr (-268)[ebp],12
+mov dword ptr (-424)[ebp],12
+mov dword ptr (-108)[ebp],13
+mov dword ptr (-264)[ebp],13
+mov dword ptr (-420)[ebp],13
+mov dword ptr (-104)[ebp],14
+mov dword ptr (-260)[ebp],14
+mov dword ptr (-416)[ebp],14
+mov dword ptr (-100)[ebp],15
+mov dword ptr (-256)[ebp],15
+mov dword ptr (-412)[ebp],15
+mov dword ptr (-96)[ebp],16
+mov dword ptr (-252)[ebp],16
+mov dword ptr (-408)[ebp],16
+mov dword ptr (-92)[ebp],63
+mov dword ptr (-248)[ebp],63
+mov dword ptr (-404)[ebp],63
+mov dword ptr (-88)[ebp],64
+mov dword ptr (-244)[ebp],64
+mov dword ptr (-400)[ebp],64
+mov dword ptr (-84)[ebp],255
+mov dword ptr (-240)[ebp],255
+mov dword ptr (-396)[ebp],255
+mov dword ptr (-80)[ebp],256
+mov dword ptr (-236)[ebp],256
+mov dword ptr (-392)[ebp],256
+mov dword ptr (-76)[ebp],4095
+mov dword ptr (-232)[ebp],4095
+mov dword ptr (-388)[ebp],4095
+mov dword ptr (-72)[ebp],4096
+mov dword ptr (-228)[ebp],4096
+mov dword ptr (-384)[ebp],4096
+mov dword ptr (-68)[ebp],65535
+mov dword ptr (-224)[ebp],65535
+mov dword ptr (-380)[ebp],65535
+mov dword ptr (-64)[ebp],65536
+mov dword ptr (-220)[ebp],65536
+mov dword ptr (-376)[ebp],65536
+mov dword ptr (-60)[ebp],262143
+mov dword ptr (-216)[ebp],262143
+mov dword ptr (-372)[ebp],262143
+mov dword ptr (-56)[ebp],262144
+mov dword ptr (-212)[ebp],262144
+mov dword ptr (-368)[ebp],262144
+mov dword ptr (-52)[ebp],1048575
+mov dword ptr (-208)[ebp],1048575
+mov dword ptr (-364)[ebp],1048575
+mov dword ptr (-48)[ebp],1048576
+mov dword ptr (-204)[ebp],1048576
+mov dword ptr (-360)[ebp],1048576
+mov dword ptr (-44)[ebp],16777215
+mov dword ptr (-200)[ebp],16777215
+mov dword ptr (-356)[ebp],16777215
+mov dword ptr (-40)[ebp],16777216
+mov dword ptr (-196)[ebp],16777216
+mov dword ptr (-352)[ebp],16777216
+mov dword ptr (-36)[ebp],268435455
+mov dword ptr (-192)[ebp],268435455
+mov dword ptr (-348)[ebp],268435455
+mov dword ptr (-32)[ebp],268435456
+mov dword ptr (-188)[ebp],268435456
+mov dword ptr (-344)[ebp],268435456
+mov dword ptr (-28)[ebp],1073741823
+mov dword ptr (-184)[ebp],1073741823
+mov dword ptr (-340)[ebp],1073741823
+mov dword ptr (-24)[ebp],1073741824
+mov dword ptr (-180)[ebp],1073741824
+mov dword ptr (-336)[ebp],1073741824
+mov edi,0ffffffffH
+mov dword ptr (-20)[ebp],edi
+mov edi,0ffffffffH
+mov dword ptr (-176)[ebp],edi
+mov edi,0ffffffffH
+mov dword ptr (-332)[ebp],edi
+mov edi,0ffffffffH
+mov dword ptr (-16)[ebp],edi
+mov edi,0ffffffffH
+mov dword ptr (-172)[ebp],edi
+mov edi,0ffffffffH
+mov dword ptr (-328)[ebp],edi
+mov edi,0ffffffffH
+mov dword ptr (-12)[ebp],edi
+mov edi,0ffffffffH
+mov dword ptr (-168)[ebp],edi
+mov edi,0ffffffffH
+mov dword ptr (-324)[ebp],edi
+mov edi,0ffffffffH
+mov dword ptr (-8)[ebp],edi
+mov edi,0ffffffffH
+mov dword ptr (-164)[ebp],edi
+mov edi,0ffffffffH
+mov dword ptr (-320)[ebp],edi
+mov dword ptr (-4)[ebp],0
+L188:
+mov edi,dword ptr (-4)[ebp]
+lea edi,[edi*4]
+mov esi,dword ptr (-160)[ebp][edi]
+cmp dword ptr (L45)[edi],esi
+jne L195
+mov ebx,dword ptr (-316)[ebp][edi]
+cmp esi,ebx
+jne L195
+cmp ebx,dword ptr (-472)[ebp][edi]
+je L192
+L195:
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (40)[edi],0
+je L196
+lea edi,(L198)
+push edi
+call _printf
+add esp,4
+lea edi,(L199)
+push edi
+call _printf
+add esp,4
+L196:
+L192:
+L189:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],39
+jl L188
+cmp dword ptr (-488)[ebp],0
+je L200
+mov dword ptr (-484)[ebp],16
+L200:
+mov eax,dword ptr (-484)[ebp]
+L42:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _pow2
+_pow2:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,4
+mov dword ptr (-4)[ebp],1
+jmp L204
+L203:
+sal dword ptr (-4)[ebp],1
+L204:
+mov edi,dword ptr (20)[ebp]
+mov esi,edi
+sub esi,1
+mov dword ptr (20)[ebp],esi
+cmp edi,0
+jne L203
+mov eax,dword ptr (-4)[ebp]
+L202:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 1
+L207 label byte
+db 115
+db 50
+db 52
+db 51
+db 44
+db 101
+db 114
+db 37
+db 100
+db 10
+db 0
+align 1
+L208 label byte
+db 115
+db 50
+db 52
+db 51
+db 32
+db 32
+db 32
+db 0
+public _s243
+_DATA ends
+_TEXT segment
+_s243:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,268
+mov dword ptr (-268)[ebp],0
+lea edi,(L208)
+mov dword ptr (-260)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+lea edi,(60)[edi]
+mov dword ptr (-264)[ebp],edi
+L209:
+L210:
+mov edi,dword ptr (-264)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-264)[ebp],esi
+mov esi,dword ptr (-260)[ebp]
+lea ebx,(1)[esi]
+mov dword ptr (-260)[ebp],ebx
+mov bl,byte ptr [esi]
+mov byte ptr [edi],bl
+movsx edi,bl
+cmp edi,0
+jne L209
+lea edi,(-256)[ebp]
+push edi
+call _zerofill
+add esp,4
+mov byte ptr (-159)[ebp],1
+mov byte ptr (-191)[ebp],1
+mov byte ptr (-130)[ebp],1
+mov byte ptr (-208)[ebp],1
+mov byte ptr (-158)[ebp],1
+mov byte ptr (-190)[ebp],1
+mov byte ptr (-223)[ebp],1
+mov byte ptr (-207)[ebp],1
+mov byte ptr (-157)[ebp],1
+mov byte ptr (-189)[ebp],1
+mov byte ptr (-222)[ebp],1
+mov byte ptr (-206)[ebp],1
+mov byte ptr (-156)[ebp],1
+mov byte ptr (-188)[ebp],1
+mov byte ptr (-221)[ebp],1
+mov byte ptr (-205)[ebp],1
+mov byte ptr (-155)[ebp],1
+mov byte ptr (-187)[ebp],1
+mov byte ptr (-219)[ebp],1
+mov byte ptr (-204)[ebp],1
+mov byte ptr (-154)[ebp],1
+mov byte ptr (-186)[ebp],1
+mov byte ptr (-218)[ebp],1
+mov byte ptr (-203)[ebp],1
+mov byte ptr (-153)[ebp],1
+mov byte ptr (-185)[ebp],1
+mov byte ptr (-216)[ebp],1
+mov byte ptr (-202)[ebp],1
+mov byte ptr (-152)[ebp],1
+mov byte ptr (-184)[ebp],1
+mov byte ptr (-215)[ebp],1
+mov byte ptr (-201)[ebp],1
+mov byte ptr (-151)[ebp],1
+mov byte ptr (-183)[ebp],1
+mov byte ptr (-161)[ebp],1
+mov byte ptr (-200)[ebp],1
+mov byte ptr (-150)[ebp],1
+mov byte ptr (-182)[ebp],1
+mov byte ptr (-195)[ebp],1
+mov byte ptr (-199)[ebp],1
+mov byte ptr (-149)[ebp],1
+mov byte ptr (-181)[ebp],1
+mov byte ptr (-211)[ebp],1
+mov byte ptr (-148)[ebp],1
+mov byte ptr (-180)[ebp],1
+mov byte ptr (-162)[ebp],1
+mov byte ptr (-147)[ebp],1
+mov byte ptr (-179)[ebp],1
+mov byte ptr (-132)[ebp],1
+mov byte ptr (-246)[ebp],1
+mov byte ptr (-146)[ebp],1
+mov byte ptr (-178)[ebp],1
+mov byte ptr (-247)[ebp],1
+mov byte ptr (-145)[ebp],1
+mov byte ptr (-177)[ebp],1
+mov byte ptr (-133)[ebp],1
+mov byte ptr (-248)[ebp],1
+mov byte ptr (-144)[ebp],1
+mov byte ptr (-176)[ebp],1
+mov byte ptr (-131)[ebp],1
+mov byte ptr (-243)[ebp],1
+mov byte ptr (-143)[ebp],1
+mov byte ptr (-175)[ebp],1
+mov byte ptr (-165)[ebp],1
+mov byte ptr (-244)[ebp],1
+mov byte ptr (-142)[ebp],1
+mov byte ptr (-174)[ebp],1
+mov byte ptr (-163)[ebp],1
+mov byte ptr (-141)[ebp],1
+mov byte ptr (-173)[ebp],1
+mov byte ptr (-213)[ebp],1
+mov byte ptr (-164)[ebp],1
+mov byte ptr (-140)[ebp],1
+mov byte ptr (-172)[ebp],1
+mov byte ptr (-197)[ebp],1
+mov byte ptr (-217)[ebp],1
+mov byte ptr (-139)[ebp],1
+mov byte ptr (-171)[ebp],1
+mov byte ptr (-214)[ebp],1
+mov byte ptr (-138)[ebp],1
+mov byte ptr (-170)[ebp],1
+mov byte ptr (-198)[ebp],1
+mov byte ptr (-256)[ebp],1
+mov byte ptr (-137)[ebp],1
+mov byte ptr (-169)[ebp],1
+mov byte ptr (-196)[ebp],1
+mov byte ptr (-224)[ebp],1
+mov byte ptr (-136)[ebp],1
+mov byte ptr (-168)[ebp],1
+mov byte ptr (-194)[ebp],1
+mov byte ptr (-135)[ebp],1
+mov byte ptr (-167)[ebp],1
+mov byte ptr (-212)[ebp],1
+mov byte ptr (-134)[ebp],1
+mov byte ptr (-166)[ebp],1
+mov byte ptr (-210)[ebp],1
+mov byte ptr (-193)[ebp],1
+mov byte ptr (-209)[ebp],1
+lea edi,(-256)[ebp]
+push edi
+call _sumof
+add esp,4
+cmp eax,98
+je L309
+inc dword ptr (-268)[ebp]
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L311
+push 1
+lea edi,(L207)
+push edi
+call _printf
+add esp,8
+L311:
+L309:
+jmp L313
+add dword ptr (-268)[ebp],8
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L315
+push 8
+lea edi,(L207)
+push edi
+call _printf
+add esp,8
+L315:
+L313:
+mov eax,dword ptr (-268)[ebp]
+L206:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _zerofill
+_zerofill:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,4
+mov dword ptr (-4)[ebp],0
+L318:
+mov edi,dword ptr (20)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (20)[ebp],esi
+mov byte ptr [edi],0
+L319:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],256
+jl L318
+mov eax,0
+L317:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _sumof
+_sumof:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,12
+mov edi,dword ptr (20)[ebp]
+mov dword ptr (-12)[ebp],edi
+mov dword ptr (-4)[ebp],0
+mov dword ptr (-8)[ebp],0
+L323:
+mov edi,dword ptr (-12)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-12)[ebp],esi
+movsx edi,byte ptr [edi]
+add dword ptr (-4)[ebp],edi
+L324:
+inc dword ptr (-8)[ebp]
+cmp dword ptr (-8)[ebp],256
+jl L323
+mov eax,dword ptr (-4)[ebp]
+L322:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 1
+L328 label byte
+db 115
+db 50
+db 52
+db 52
+db 44
+db 101
+db 114
+db 37
+db 100
+db 10
+db 0
+align 1
+L329 label byte
+db 115
+db 50
+db 52
+db 52
+db 32
+db 32
+db 32
+db 0
+public _s244
+_DATA ends
+_TEXT segment
+_s244:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,92
+lea edi,(L329)
+mov dword ptr (-72)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+lea edi,(60)[edi]
+mov dword ptr (-76)[ebp],edi
+L330:
+L331:
+mov edi,dword ptr (-76)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-76)[ebp],esi
+mov esi,dword ptr (-72)[ebp]
+lea ebx,(1)[esi]
+mov dword ptr (-72)[ebp],ebx
+mov bl,byte ptr [esi]
+mov byte ptr [edi],bl
+movsx edi,bl
+cmp edi,0
+jne L330
+mov dword ptr (-84)[ebp],0
+mov dword ptr (-80)[ebp],0
+fld qword ptr (L333)
+fstp qword ptr (-68)[ebp]
+fld qword ptr (L333)
+fstp qword ptr (-60)[ebp]
+fld qword ptr (L333)
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L333)
+fstp qword ptr (-44)[ebp]
+fld qword ptr (L333)
+fstp qword ptr (-36)[ebp]
+fld qword ptr (L333)
+fstp qword ptr (-28)[ebp]
+fld qword ptr (L333)
+fstp qword ptr (-20)[ebp]
+fld qword ptr (L333)
+fstp qword ptr (-12)[ebp]
+mov dword ptr (-80)[ebp],0
+mov dword ptr (-4)[ebp],0
+L341:
+mov edi,dword ptr (-4)[ebp]
+lea edi,[edi*8]
+fld qword ptr (-60)[ebp][edi]
+fcomp qword ptr (-68)[ebp][edi]
+fstsw ax
+sahf
+je L345
+mov dword ptr (-80)[ebp],1
+L345:
+L342:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],7
+jl L341
+cmp dword ptr (-80)[ebp],0
+je L348
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L350
+push 1
+lea edi,(L328)
+push edi
+call _printf
+add esp,8
+L350:
+inc dword ptr (-84)[ebp]
+L348:
+jmp L352
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L354
+push 2
+lea edi,(L328)
+push edi
+call _printf
+add esp,8
+L354:
+add dword ptr (-84)[ebp],2
+L352:
+mov eax,dword ptr (-84)[ebp]
+L327:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 1
+L357 label byte
+db 115
+db 50
+db 53
+db 44
+db 101
+db 114
+db 37
+db 100
+db 10
+db 0
+align 1
+L358 label byte
+db 115
+db 50
+db 53
+db 32
+db 32
+db 32
+db 32
+db 0
+public _s25
+_DATA ends
+_TEXT segment
+_s25:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,28
+lea edi,(L358)
+mov dword ptr (-16)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+lea edi,(60)[edi]
+mov dword ptr (-20)[ebp],edi
+L359:
+L360:
+mov edi,dword ptr (-20)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-20)[ebp],esi
+mov esi,dword ptr (-16)[ebp]
+lea ebx,(1)[esi]
+mov dword ptr (-16)[ebp],ebx
+mov bl,byte ptr [esi]
+mov byte ptr [edi],bl
+movsx edi,bl
+cmp edi,0
+jne L359
+mov dword ptr (-24)[ebp],0
+lea edi,(L362)
+mov dword ptr (-8)[ebp],edi
+mov edi,dword ptr (-8)[ebp]
+movsx esi,byte ptr (1)[edi]
+movsx ebx,byte ptr [edi]
+cmp ebx,esi
+jne L366
+movsx edi,byte ptr (2)[edi]
+cmp esi,edi
+jne L366
+cmp edi,46
+je L363
+L366:
+inc dword ptr (-24)[ebp]
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L367
+push 1
+lea edi,(L357)
+push edi
+call _printf
+add esp,8
+L367:
+L363:
+mov edi,dword ptr (-8)[ebp]
+movsx edi,byte ptr (3)[edi]
+cmp edi,0
+je L369
+add dword ptr (-24)[ebp],4
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L371
+push 4
+lea edi,(L357)
+push edi
+call _printf
+add esp,8
+L371:
+L369:
+movsx edi,byte ptr (L375+1)
+cmp edi,34
+je L373
+add dword ptr (-24)[ebp],8
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L377
+push 8
+lea edi,(L357)
+push edi
+call _printf
+add esp,8
+L377:
+L373:
+lea edi,(L379)
+mov dword ptr (-8)[ebp],edi
+mov edi,dword ptr (-8)[ebp]
+movsx esi,byte ptr [edi]
+cmp esi,10
+jne L387
+movsx esi,byte ptr (1)[edi]
+cmp esi,9
+jne L387
+movsx esi,byte ptr (2)[edi]
+cmp esi,8
+jne L387
+movsx esi,byte ptr (3)[edi]
+cmp esi,13
+jne L387
+movsx esi,byte ptr (4)[edi]
+cmp esi,12
+jne L387
+movsx esi,byte ptr (5)[edi]
+cmp esi,92
+jne L387
+movsx edi,byte ptr (6)[edi]
+cmp edi,39
+je L380
+L387:
+add dword ptr (-24)[ebp],16
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L388
+push 16
+lea edi,(L357)
+push edi
+call _printf
+add esp,8
+L388:
+L380:
+lea edi,(L390)
+mov dword ptr (-12)[ebp],edi
+mov dword ptr (-8)[ebp],edi
+mov dword ptr (-28)[ebp],0
+mov dword ptr (-4)[ebp],0
+jmp L394
+L391:
+mov edi,dword ptr (-4)[ebp]
+mov esi,dword ptr (-8)[ebp]
+movsx esi,byte ptr [esi][edi]
+mov ebx,dword ptr (-12)[ebp]
+movsx edi,byte ptr [ebx][edi]
+cmp esi,edi
+je L395
+mov dword ptr (-28)[ebp],1
+L395:
+L392:
+inc dword ptr (-4)[ebp]
+L394:
+mov edi,dword ptr (-4)[ebp]
+cmp edi,7
+jb L391
+cmp dword ptr (-28)[ebp],0
+je L397
+add dword ptr (-24)[ebp],32
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L399
+push 32
+lea edi,(L357)
+push edi
+call _printf
+add esp,8
+L399:
+L397:
+mov eax,dword ptr (-24)[ebp]
+L356:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 1
+L402 label byte
+db 115
+db 50
+db 54
+db 32
+db 32
+db 32
+db 32
+db 0
+align 1
+L403 label byte
+db 37
+db 51
+db 100
+db 32
+db 98
+db 105
+db 116
+db 115
+db 32
+db 105
+db 110
+db 32
+db 37
+db 115
+db 115
+db 46
+db 10
+db 0
+align 1
+L404 label byte
+db 37
+db 101
+db 32
+db 105
+db 115
+db 32
+db 116
+db 104
+db 101
+db 32
+db 108
+db 101
+db 97
+db 115
+db 116
+db 32
+db 110
+db 117
+db 109
+db 98
+db 101
+db 114
+db 32
+db 116
+db 104
+db 97
+db 116
+db 32
+db 99
+db 97
+db 110
+db 32
+db 98
+db 101
+db 32
+db 97
+db 100
+db 100
+db 101
+db 100
+db 32
+db 116
+db 111
+db 32
+db 49
+db 46
+db 32
+db 40
+db 37
+db 115
+db 41
+db 46
+db 10
+db 0
+public _s26
+_DATA ends
+_TEXT segment
+_s26:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,56
+lea edi,(L402)
+mov dword ptr (-36)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+lea edi,(60)[edi]
+mov dword ptr (-40)[ebp],edi
+L405:
+L406:
+mov edi,dword ptr (-40)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-40)[ebp],esi
+mov esi,dword ptr (-36)[ebp]
+lea ebx,(1)[esi]
+mov dword ptr (-36)[ebp],ebx
+mov bl,byte ptr [esi]
+mov byte ptr [edi],bl
+movsx edi,bl
+cmp edi,0
+jne L405
+mov edi,dword ptr (20)[ebp]
+mov dword ptr [edi],0
+mov byte ptr (-41)[ebp],0
+mov byte ptr (-5)[ebp],1
+jmp L409
+L408:
+movsx edi,byte ptr (-5)[ebp]
+lea edi,[edi*2]
+mov ebx,edi
+mov byte ptr (-5)[ebp],bl
+mov edi,dword ptr (20)[ebp]
+inc dword ptr [edi]
+L409:
+movsx edi,byte ptr (-41)[ebp]
+movsx esi,byte ptr (-5)[ebp]
+cmp edi,esi
+jne L408
+mov edi,dword ptr (20)[ebp]
+mov esi,dword ptr [edi]
+lea esi,[esi*4]
+mov dword ptr (4)[edi],esi
+mov edi,dword ptr (20)[ebp]
+mov esi,dword ptr [edi]
+lea esi,[esi*2]
+mov dword ptr (8)[edi],esi
+mov edi,dword ptr (20)[ebp]
+mov esi,dword ptr [edi]
+lea esi,[esi*4]
+mov dword ptr (12)[edi],esi
+mov edi,dword ptr (20)[ebp]
+mov esi,dword ptr [edi]
+lea esi,[esi*4]
+mov dword ptr (16)[edi],esi
+mov edi,dword ptr (20)[ebp]
+mov esi,dword ptr [edi]
+lea esi,[esi*4]
+mov dword ptr (20)[edi],esi
+mov edi,dword ptr (20)[ebp]
+mov esi,dword ptr [edi]
+lea esi,[esi*8]
+mov dword ptr (24)[edi],esi
+fld dword ptr (L411)
+fstp dword ptr (-16)[ebp]
+fld dword ptr (L411)
+fstp dword ptr (-4)[ebp]
+fld dword ptr (L412)
+fstp dword ptr (-12)[ebp]
+jmp L414
+L413:
+fld dword ptr (-16)[ebp]
+fadd dword ptr (-4)[ebp]
+fstp dword ptr (-12)[ebp]
+fld dword ptr (-4)[ebp]
+fdiv qword ptr (L416)
+fstp dword ptr (-4)[ebp]
+L414:
+fld dword ptr (-16)[ebp]
+fcomp dword ptr (-12)[ebp]
+fstsw ax
+sahf
+jne L413
+mov edi,dword ptr (20)[ebp]
+fld qword ptr (L417)
+fmul dword ptr (-4)[ebp]
+fstp dword ptr (28)[edi]
+fld qword ptr (L418)
+fstp qword ptr (-32)[ebp]
+fld dword ptr (L411)
+fstp dword ptr (-4)[ebp]
+fld qword ptr (L419)
+fstp qword ptr (-24)[ebp]
+jmp L421
+L420:
+fld dword ptr (-4)[ebp]
+fstp qword ptr (-56)[ebp]
+fld qword ptr (-32)[ebp]
+fadd qword ptr (-56)[ebp]
+fstp qword ptr (-24)[ebp]
+fld qword ptr (-56)[ebp]
+fdiv qword ptr (L416)
+fstp dword ptr (-4)[ebp]
+L421:
+fld qword ptr (-32)[ebp]
+fcomp qword ptr (-24)[ebp]
+fstsw ax
+sahf
+jne L420
+mov edi,dword ptr (20)[ebp]
+fld qword ptr (L417)
+fmul dword ptr (-4)[ebp]
+fstp dword ptr (32)[edi]
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (40)[edi],0
+je L423
+lea edi,(L425)
+push edi
+mov edi,dword ptr (20)[ebp]
+mov edi,dword ptr [edi]
+push edi
+lea edi,(L403)
+push edi
+call _printf
+add esp,12
+lea edi,(L426)
+push edi
+mov edi,dword ptr (20)[ebp]
+mov edi,dword ptr (4)[edi]
+push edi
+lea edi,(L403)
+push edi
+call _printf
+add esp,12
+lea edi,(L427)
+push edi
+mov edi,dword ptr (20)[ebp]
+mov edi,dword ptr (8)[edi]
+push edi
+lea edi,(L403)
+push edi
+call _printf
+add esp,12
+lea edi,(L428)
+push edi
+mov edi,dword ptr (20)[ebp]
+mov edi,dword ptr (12)[edi]
+push edi
+lea edi,(L403)
+push edi
+call _printf
+add esp,12
+lea edi,(L429)
+push edi
+mov edi,dword ptr (20)[ebp]
+mov edi,dword ptr (16)[edi]
+push edi
+lea edi,(L403)
+push edi
+call _printf
+add esp,12
+lea edi,(L430)
+push edi
+mov edi,dword ptr (20)[ebp]
+mov edi,dword ptr (20)[edi]
+push edi
+lea edi,(L403)
+push edi
+call _printf
+add esp,12
+lea edi,(L431)
+push edi
+mov edi,dword ptr (20)[ebp]
+mov edi,dword ptr (24)[edi]
+push edi
+lea edi,(L403)
+push edi
+call _printf
+add esp,12
+lea edi,(L430)
+push edi
+mov edi,dword ptr (20)[ebp]
+fld dword ptr (28)[edi]
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L404)
+push edi
+call _printf
+add esp,16
+lea edi,(L431)
+push edi
+mov edi,dword ptr (20)[ebp]
+fld dword ptr (32)[edi]
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L404)
+push edi
+call _printf
+add esp,16
+L423:
+mov eax,0
+L401:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 1
+L433 label byte
+db 115
+db 52
+db 44
+db 101
+db 114
+db 37
+db 100
+db 10
+db 0
+align 1
+L434 label byte
+db 115
+db 52
+db 32
+db 32
+db 32
+db 32
+db 32
+db 0
+public _s4
+_DATA ends
+_TEXT segment
+_s4:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,36
+mov dword ptr (-24)[ebp],0
+lea edi,(L434)
+mov dword ptr (-16)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+lea edi,(60)[edi]
+mov dword ptr (-20)[ebp],edi
+L435:
+L436:
+mov edi,dword ptr (-20)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-20)[ebp],esi
+mov esi,dword ptr (-16)[ebp]
+lea ebx,(1)[esi]
+mov dword ptr (-16)[ebp],ebx
+mov bl,byte ptr [esi]
+mov byte ptr [edi],bl
+movsx edi,bl
+cmp edi,0
+jne L435
+mov dword ptr (-4)[ebp],0
+L438:
+mov edi,dword ptr (-4)[ebp]
+push edi
+call _svtest
+add esp,4
+mov edi,eax
+call _zero
+add esp,0
+cmp edi,eax
+je L442
+mov dword ptr (-24)[ebp],1
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L444
+push 1
+lea edi,(L433)
+push edi
+call _printf
+add esp,8
+L444:
+L442:
+L439:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],3
+jl L438
+call _setev
+add esp,0
+call _testev
+add esp,0
+cmp eax,0
+je L446
+add dword ptr (-24)[ebp],2
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L448
+push 2
+lea edi,(L433)
+push edi
+call _printf
+add esp,8
+L448:
+L446:
+jmp L450
+add dword ptr (-24)[ebp],4
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L452
+push 4
+lea edi,(L433)
+push edi
+call _printf
+add esp,8
+L452:
+L450:
+mov dword ptr (-8)[ebp],0ffffffffH
+mov dword ptr (-12)[ebp],1
+mov dword ptr (-4)[ebp],0
+jmp L457
+L454:
+mov edi,dword ptr (-8)[ebp]
+and dword ptr (-12)[ebp],edi
+shr edi,1
+mov dword ptr (-8)[ebp],edi
+L455:
+inc dword ptr (-4)[ebp]
+L457:
+mov edi,dword ptr (-4)[ebp]
+mov esi,dword ptr (20)[ebp]
+mov esi,dword ptr [esi]
+lea esi,[esi*4]
+cmp edi,esi
+jb L454
+mov edi,dword ptr (-12)[ebp]
+cmp edi,1
+jne L460
+mov edi,dword ptr (-8)[ebp]
+cmp edi,0
+je L458
+L460:
+add dword ptr (-24)[ebp],8
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L461
+push 8
+lea edi,(L433)
+push edi
+call _printf
+add esp,8
+L461:
+L458:
+mov eax,dword ptr (-24)[ebp]
+L432:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 4
+L464 label byte
+db 4 dup (0)
+public _svtest
+_DATA ends
+_TEXT segment
+_svtest:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,4
+mov edi,dword ptr (20)[ebp]
+cmp edi,0
+je L467
+cmp edi,1
+je L468
+cmp edi,2
+je L471
+jmp L465
+L467:
+mov dword ptr (L464),1978
+mov dword ptr (-4)[ebp],0
+jmp L466
+L468:
+cmp dword ptr (L464),1978
+je L469
+mov dword ptr (-4)[ebp],1
+jmp L466
+L469:
+mov dword ptr (L464),1929
+mov dword ptr (-4)[ebp],0
+jmp L466
+L471:
+cmp dword ptr (L464),1929
+je L472
+mov dword ptr (-4)[ebp],1
+jmp L466
+L472:
+mov dword ptr (-4)[ebp],0
+L465:
+L466:
+mov eax,dword ptr (-4)[ebp]
+L463:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 4
+L475 label byte
+db 4 dup (0)
+public _zero
+_DATA ends
+_TEXT segment
+_zero:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,4
+mov dword ptr (L475),2
+mov dword ptr (-4)[ebp],0
+mov eax,dword ptr (-4)[ebp]
+L474:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _testev
+_testev:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+cmp dword ptr (_extvar),1066
+je L477
+mov eax,1
+jmp L476
+L477:
+mov eax,0
+L476:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 1
+L480 label byte
+db 115
+db 54
+db 49
+db 44
+db 101
+db 114
+db 37
+db 100
+db 10
+db 0
+align 1
+L481 label byte
+db 115
+db 54
+db 49
+db 32
+db 32
+db 32
+db 32
+db 0
+align 1
+L482 label byte
+db 65
+db 66
+db 67
+db 68
+db 69
+db 70
+db 71
+db 72
+db 73
+db 74
+db 75
+db 76
+db 77
+db 78
+db 79
+db 80
+db 81
+db 82
+db 83
+db 84
+db 85
+db 86
+db 87
+db 88
+db 89
+db 90
+db 0
+align 1
+L483 label byte
+db 97
+db 98
+db 99
+db 100
+db 101
+db 102
+db 103
+db 104
+db 105
+db 106
+db 107
+db 108
+db 109
+db 110
+db 111
+db 112
+db 113
+db 114
+db 115
+db 116
+db 117
+db 118
+db 119
+db 120
+db 121
+db 122
+db 0
+align 1
+L484 label byte
+db 48
+db 49
+db 50
+db 51
+db 52
+db 53
+db 54
+db 55
+db 56
+db 57
+db 0
+align 1
+L485 label byte
+db 126
+db 33
+db 34
+db 35
+db 37
+db 38
+db 40
+db 41
+db 95
+db 61
+db 45
+db 94
+db 124
+db 123
+db 125
+db 91
+db 93
+db 43
+db 59
+db 42
+db 58
+db 60
+db 62
+db 44
+db 46
+db 63
+db 47
+db 0
+align 1
+L486 label byte
+db 10
+db 9
+db 8
+db 13
+db 12
+db 92
+db 39
+db 0
+align 1
+L487 label byte
+db 32
+db 0
+db 0
+public _s61
+_DATA ends
+_TEXT segment
+_s61:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,60
+lea edi,(L481)
+mov dword ptr (-36)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+lea edi,(60)[edi]
+mov dword ptr (-40)[ebp],edi
+mov dword ptr (-48)[ebp],0
+L488:
+L489:
+mov edi,dword ptr (-40)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-40)[ebp],esi
+mov esi,dword ptr (-36)[ebp]
+lea ebx,(1)[esi]
+mov dword ptr (-36)[ebp],ebx
+mov bl,byte ptr [esi]
+mov byte ptr [edi],bl
+movsx edi,bl
+cmp edi,0
+jne L488
+mov word ptr (-54)[ebp],-19
+movsx edi,word ptr (-54)[ebp]
+mov dword ptr (-60)[ebp],edi
+cmp dword ptr (-60)[ebp],-19
+je L491
+inc dword ptr (-48)[ebp]
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L493
+push 1
+lea edi,(L480)
+push edi
+call _printf
+add esp,8
+L493:
+L491:
+lea edi,(L482)
+mov dword ptr (-28)[ebp],edi
+lea edi,(L483)
+mov dword ptr (-24)[ebp],edi
+lea edi,(L484)
+mov dword ptr (-20)[ebp],edi
+lea edi,(L485)
+mov dword ptr (-16)[ebp],edi
+lea edi,(L486)
+mov dword ptr (-12)[ebp],edi
+lea edi,(L487)
+mov dword ptr (-8)[ebp],edi
+mov dword ptr (-32)[ebp],0
+mov dword ptr (-4)[ebp],0
+jmp L505
+L504:
+mov edi,dword ptr (-4)[ebp]
+lea edi,(-28)[ebp][edi*4]
+mov esi,dword ptr [edi]
+lea ebx,(1)[esi]
+mov dword ptr [edi],ebx
+movsx edi,byte ptr [esi]
+cmp edi,0
+jge L507
+mov dword ptr (-32)[ebp],1
+L507:
+L505:
+mov edi,dword ptr (-4)[ebp]
+mov edi,dword ptr (-28)[ebp][edi*4]
+movsx edi,byte ptr [edi]
+cmp edi,0
+jne L504
+L501:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],6
+jl L505
+cmp dword ptr (-32)[ebp],0
+je L509
+add dword ptr (-48)[ebp],2
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L511
+push 2
+lea edi,(L480)
+push edi
+call _printf
+add esp,8
+L511:
+L509:
+mov dword ptr (-44)[ebp],1048579
+mov edi,dword ptr (-44)[ebp]
+mov esi,edi
+mov word ptr (-50)[ebp],si
+mov ebx,edi
+mov byte ptr (-51)[ebp],bl
+movsx edi,word ptr (-50)[ebp]
+cmp edi,dword ptr (-44)[ebp]
+je L516
+cmp edi,3
+jne L515
+L516:
+movsx edi,byte ptr (-51)[ebp]
+cmp edi,dword ptr (-44)[ebp]
+je L513
+cmp edi,3
+je L513
+L515:
+add dword ptr (-48)[ebp],8
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L517
+push 8
+lea edi,(L480)
+push edi
+call _printf
+add esp,8
+L517:
+L513:
+mov eax,dword ptr (-48)[ebp]
+L479:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 1
+L520 label byte
+db 115
+db 54
+db 50
+db 54
+db 44
+db 101
+db 114
+db 37
+db 100
+db 10
+db 0
+align 1
+L521 label byte
+db 115
+db 54
+db 50
+db 54
+db 32
+db 32
+db 32
+db 0
+public _s626
+_DATA ends
+_TEXT segment
+_s626:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,128
+lea edi,(L521)
+mov dword ptr (-56)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+lea edi,(60)[edi]
+mov dword ptr (-60)[ebp],edi
+mov dword ptr (-104)[ebp],0
+L522:
+L523:
+mov edi,dword ptr (-60)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-60)[ebp],esi
+mov esi,dword ptr (-56)[ebp]
+lea ebx,(1)[esi]
+mov dword ptr (-56)[ebp],ebx
+mov bl,byte ptr [esi]
+mov byte ptr [edi],bl
+movsx edi,bl
+cmp edi,0
+jne L522
+fld dword ptr (L411)
+fstp dword ptr (-36)[ebp]
+mov dword ptr (-64)[ebp],1
+mov dword ptr (-40)[ebp],1
+mov dword ptr (-4)[ebp],0
+jmp L528
+L525:
+fld dword ptr (L529)
+fmul dword ptr (-36)[ebp]
+fstp dword ptr (-36)[ebp]
+mov edi,dword ptr (-40)[ebp]
+lea edi,[edi*2]
+or edi,dword ptr (-64)[ebp]
+mov dword ptr (-40)[ebp],edi
+L526:
+inc dword ptr (-4)[ebp]
+L528:
+mov edi,dword ptr (20)[ebp]
+mov edi,dword ptr (12)[edi]
+sub edi,2
+cmp dword ptr (-4)[ebp],edi
+jl L525
+mov edi,dword ptr (-40)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fstp dword ptr (-112)[ebp]
+fld dword ptr (-36)[ebp]
+fsub dword ptr (-112)[ebp]
+fdiv dword ptr (-36)[ebp]
+fstp dword ptr (-36)[ebp]
+fld qword ptr (L416)
+mov edi,dword ptr (20)[ebp]
+fmul dword ptr (28)[edi]
+fcomp dword ptr (-36)[ebp]
+fstsw ax
+sahf
+jae L530
+add dword ptr (-104)[ebp],2
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L532
+push 2
+lea edi,(L520)
+push edi
+call _printf
+add esp,8
+L532:
+L530:
+mov byte ptr (-73)[ebp],125
+mov word ptr (-76)[ebp],125
+mov dword ptr (-80)[ebp],125
+mov dword ptr (-96)[ebp],15625
+mov dword ptr (-84)[ebp],125
+mov dword ptr (-100)[ebp],15625
+mov dword ptr (-68)[ebp],125
+mov dword ptr (-108)[ebp],15625
+fld dword ptr (L534)
+fstp dword ptr (-72)[ebp]
+fld qword ptr (L535)
+fstp qword ptr (-92)[ebp]
+fld qword ptr (L536)
+fstp qword ptr (-52)[ebp]
+mov dword ptr (-4)[ebp],0
+L537:
+mov edi,dword ptr (-4)[ebp]
+mov byte ptr (-32)[ebp][edi],0
+L538:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],28
+jl L537
+movsx edi,byte ptr (-73)[ebp]
+mov esi,edi
+imul esi,edi
+cmp esi,dword ptr (-96)[ebp]
+je L541
+mov byte ptr (-32)[ebp],1
+L541:
+movsx edi,word ptr (-76)[ebp]
+movsx esi,byte ptr (-73)[ebp]
+imul edi,esi
+cmp edi,dword ptr (-96)[ebp]
+je L543
+mov byte ptr (-31)[ebp],1
+L543:
+movsx edi,word ptr (-76)[ebp]
+mov esi,edi
+imul esi,edi
+cmp esi,dword ptr (-96)[ebp]
+je L546
+mov byte ptr (-30)[ebp],1
+L546:
+mov edi,dword ptr (-80)[ebp]
+movsx esi,byte ptr (-73)[ebp]
+imul edi,esi
+cmp edi,dword ptr (-96)[ebp]
+je L549
+mov byte ptr (-29)[ebp],1
+L549:
+mov edi,dword ptr (-80)[ebp]
+movsx esi,word ptr (-76)[ebp]
+imul edi,esi
+cmp edi,dword ptr (-96)[ebp]
+je L552
+mov byte ptr (-28)[ebp],1
+L552:
+mov edi,dword ptr (-80)[ebp]
+mov esi,edi
+imul esi,edi
+cmp esi,dword ptr (-96)[ebp]
+je L555
+mov byte ptr (-27)[ebp],1
+L555:
+mov eax,dword ptr (-84)[ebp]
+movsx edi,byte ptr (-73)[ebp]
+mul edi
+cmp eax,dword ptr (-100)[ebp]
+je L558
+mov byte ptr (-26)[ebp],1
+L558:
+mov eax,dword ptr (-84)[ebp]
+movsx edi,word ptr (-76)[ebp]
+mul edi
+cmp eax,dword ptr (-100)[ebp]
+je L561
+mov byte ptr (-25)[ebp],1
+L561:
+mov eax,dword ptr (-84)[ebp]
+mov edi,dword ptr (-80)[ebp]
+mul edi
+cmp eax,dword ptr (-100)[ebp]
+je L564
+mov byte ptr (-24)[ebp],1
+L564:
+mov edi,dword ptr (-84)[ebp]
+mov eax,edi
+mul edi
+cmp eax,dword ptr (-100)[ebp]
+je L567
+mov byte ptr (-23)[ebp],1
+L567:
+mov edi,dword ptr (-68)[ebp]
+movsx esi,byte ptr (-73)[ebp]
+imul edi,esi
+cmp edi,dword ptr (-108)[ebp]
+je L570
+mov byte ptr (-22)[ebp],1
+L570:
+mov edi,dword ptr (-68)[ebp]
+movsx esi,word ptr (-76)[ebp]
+imul edi,esi
+cmp edi,dword ptr (-108)[ebp]
+je L573
+mov byte ptr (-21)[ebp],1
+L573:
+mov edi,dword ptr (-68)[ebp]
+mov esi,dword ptr (-80)[ebp]
+imul edi,esi
+cmp edi,dword ptr (-108)[ebp]
+je L576
+mov byte ptr (-20)[ebp],1
+L576:
+mov edi,dword ptr (-68)[ebp]
+mov eax,edi
+mul dword ptr (-84)[ebp]
+cmp eax,dword ptr (-100)[ebp]
+je L579
+mov byte ptr (-19)[ebp],1
+L579:
+mov edi,dword ptr (-68)[ebp]
+mov esi,edi
+imul esi,edi
+cmp esi,dword ptr (-108)[ebp]
+je L582
+mov byte ptr (-18)[ebp],1
+L582:
+fld dword ptr (-72)[ebp]
+movsx edi,byte ptr (-73)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+fld qword ptr (-52)[ebp]
+fcompp
+fstsw ax
+sahf
+je L585
+mov byte ptr (-17)[ebp],1
+L585:
+fld dword ptr (-72)[ebp]
+movsx edi,word ptr (-76)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+fld qword ptr (-52)[ebp]
+fcompp
+fstsw ax
+sahf
+je L588
+mov byte ptr (-16)[ebp],1
+L588:
+fld dword ptr (-72)[ebp]
+mov edi,dword ptr (-80)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+fld qword ptr (-52)[ebp]
+fcompp
+fstsw ax
+sahf
+je L591
+mov byte ptr (-15)[ebp],1
+L591:
+mov edi,dword ptr (-84)[ebp]
+fld dword ptr (-72)[ebp]
+fld qword ptr (L596)
+mov esi,edi
+shr esi,1
+push esi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+and edi,1
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+sub esp,4
+fstp dword ptr 0[esp]
+fld dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+fld qword ptr (-52)[ebp]
+fcompp
+fstsw ax
+sahf
+je L594
+mov byte ptr (-14)[ebp],1
+L594:
+fld dword ptr (-72)[ebp]
+mov edi,dword ptr (-68)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+fld qword ptr (-52)[ebp]
+fcompp
+fstsw ax
+sahf
+je L598
+mov byte ptr (-13)[ebp],1
+L598:
+fld dword ptr (-72)[ebp]
+fmul dword ptr (-72)[ebp]
+fld qword ptr (-52)[ebp]
+fcompp
+fstsw ax
+sahf
+je L601
+mov byte ptr (-12)[ebp],1
+L601:
+fld qword ptr (-92)[ebp]
+movsx edi,byte ptr (-73)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+fld qword ptr (-52)[ebp]
+fcompp
+fstsw ax
+sahf
+je L604
+mov byte ptr (-11)[ebp],1
+L604:
+fld qword ptr (-92)[ebp]
+movsx edi,word ptr (-76)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+fld qword ptr (-52)[ebp]
+fcompp
+fstsw ax
+sahf
+je L607
+mov byte ptr (-10)[ebp],1
+L607:
+fld qword ptr (-92)[ebp]
+fild dword ptr (-80)[ebp]
+fmulp st(1),st
+fld qword ptr (-52)[ebp]
+fcompp
+fstsw ax
+sahf
+je L610
+mov byte ptr (-9)[ebp],1
+L610:
+mov edi,dword ptr (-84)[ebp]
+fld qword ptr (-92)[ebp]
+fld qword ptr (L596)
+mov esi,edi
+shr esi,1
+push esi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+and edi,1
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+fmulp st(1),st
+fld qword ptr (-52)[ebp]
+fcompp
+fstsw ax
+sahf
+je L613
+mov byte ptr (-8)[ebp],1
+L613:
+fld qword ptr (-92)[ebp]
+fild dword ptr (-68)[ebp]
+fmulp st(1),st
+fld qword ptr (-52)[ebp]
+fcompp
+fstsw ax
+sahf
+je L616
+mov byte ptr (-7)[ebp],1
+L616:
+fld qword ptr (-92)[ebp]
+fmul dword ptr (-72)[ebp]
+fld qword ptr (-52)[ebp]
+fcompp
+fstsw ax
+sahf
+je L619
+mov byte ptr (-6)[ebp],1
+L619:
+fld qword ptr (-92)[ebp]
+fmul qword ptr (-92)[ebp]
+fld qword ptr (-52)[ebp]
+fcompp
+fstsw ax
+sahf
+je L622
+mov byte ptr (-5)[ebp],1
+L622:
+mov byte ptr (-41)[ebp],0
+mov dword ptr (-4)[ebp],0
+L625:
+movsx edi,byte ptr (-41)[ebp]
+mov esi,dword ptr (-4)[ebp]
+movsx esi,byte ptr (-32)[ebp][esi]
+lea edi,[esi][edi]
+mov ebx,edi
+mov byte ptr (-41)[ebp],bl
+L626:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],28
+jl L625
+movsx edi,byte ptr (-41)[ebp]
+cmp edi,0
+je L629
+add dword ptr (-104)[ebp],4
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L631
+push 4
+lea edi,(L520)
+push edi
+call _printf
+add esp,8
+lea edi,(L633)
+push edi
+call _printf
+add esp,4
+mov dword ptr (-4)[ebp],0
+L634:
+mov edi,dword ptr (-4)[ebp]
+movsx edi,byte ptr (-32)[ebp][edi]
+push edi
+lea edi,(L638)
+push edi
+call _printf
+add esp,8
+L635:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],28
+jl L634
+lea edi,(L639)
+push edi
+call _printf
+add esp,4
+L631:
+L629:
+mov dword ptr (-68)[ebp],32768
+mov edi,dword ptr (-68)[ebp]
+cmp edi,08000H
+jbe L640
+add dword ptr (-104)[ebp],8
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L642
+push 8
+lea edi,(L520)
+push edi
+call _printf
+add esp,8
+L642:
+L640:
+mov eax,dword ptr (-104)[ebp]
+L519:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 1
+L645 label byte
+db 115
+db 55
+db 49
+db 44
+db 101
+db 114
+db 37
+db 100
+db 10
+db 0
+align 1
+L646 label byte
+db 115
+db 55
+db 49
+db 32
+db 32
+db 32
+db 32
+db 0
+align 1
+L647 label byte
+db 113
+public _s71
+_DATA ends
+_TEXT segment
+_s71:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,68
+lea edi,(L646)
+mov dword ptr (-4)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+lea edi,(60)[edi]
+mov dword ptr (-8)[ebp],edi
+mov dword ptr (-12)[ebp],0
+L648:
+L649:
+mov edi,dword ptr (-8)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-8)[ebp],esi
+mov esi,dword ptr (-4)[ebp]
+lea ebx,(1)[esi]
+mov dword ptr (-4)[ebp],ebx
+mov bl,byte ptr [esi]
+mov byte ptr [edi],bl
+movsx edi,bl
+cmp edi,0
+jne L648
+movsx edi,byte ptr (L653)
+movsx esi,byte ptr (L647)
+cmp edi,esi
+je L651
+inc dword ptr (-12)[ebp]
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L654
+push 1
+lea edi,(L645)
+push edi
+call _printf
+add esp,8
+L654:
+L651:
+jmp L656
+add dword ptr (-12)[ebp],2
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L658
+push 2
+lea edi,(L645)
+push edi
+call _printf
+add esp,8
+L658:
+L656:
+mov dword ptr (-32)[ebp],1942
+cmp dword ptr (-32)[ebp],1942
+jne L666
+mov edi,dword ptr (-32)[ebp]
+cmp dword ptr (-32)[ebp],edi
+je L661
+L666:
+add dword ptr (-12)[ebp],4
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L667
+push 4
+lea edi,(L645)
+push edi
+call _printf
+add esp,8
+L667:
+L661:
+push -5
+call _McCarthy
+add esp,4
+cmp eax,91
+je L669
+add dword ptr (-12)[ebp],8
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L671
+push 8
+lea edi,(L645)
+push edi
+call _printf
+add esp,8
+L671:
+L669:
+mov dword ptr (-56)[ebp],2
+mov dword ptr (-60)[ebp],3
+lea edi,(-60)[ebp]
+mov dword ptr (-64)[ebp],edi
+mov edi,dword ptr (-64)[ebp]
+push edi
+mov edi,dword ptr (-56)[ebp]
+push edi
+call _clobber
+add esp,8
+cmp dword ptr (-56)[ebp],2
+jne L675
+cmp dword ptr (-60)[ebp],2
+je L673
+L675:
+add dword ptr (-12)[ebp],16
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L676
+push 16
+lea edi,(L645)
+push edi
+call _printf
+add esp,8
+L676:
+L673:
+mov edi,dword ptr (20)[ebp]
+fld dword ptr (32)[edi]
+fstp dword ptr (-68)[ebp]
+fld dword ptr (-68)[ebp]
+fcomp dword ptr (-68)[ebp]
+fstsw ax
+sahf
+je L678
+add dword ptr (-12)[ebp],32
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L680
+push 32
+lea edi,(L645)
+push edi
+call _printf
+add esp,8
+L680:
+L678:
+mov eax,dword ptr (-12)[ebp]
+L644:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _McCarthy
+_McCarthy:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+cmp dword ptr (20)[ebp],100
+jle L683
+mov edi,dword ptr (20)[ebp]
+mov eax,edi
+sub eax,10
+jmp L682
+L683:
+mov edi,dword ptr (20)[ebp]
+lea edi,(11)[edi]
+push edi
+call _McCarthy
+add esp,4
+mov edi,eax
+push edi
+call _McCarthy
+add esp,4
+mov edi,eax
+L682:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _clobber
+_clobber:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov dword ptr (20)[ebp],3
+mov edi,dword ptr (24)[ebp]
+mov dword ptr [edi],2
+mov eax,0
+L685:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 1
+L687 label byte
+db 76
+db 111
+db 99
+db 97
+db 108
+db 32
+db 101
+db 114
+db 114
+db 111
+db 114
+db 32
+db 37
+db 100
+db 46
+db 10
+db 0
+align 1
+L688 label byte
+db 115
+db 55
+db 49
+db 52
+db 44
+db 101
+db 114
+db 37
+db 100
+db 10
+db 0
+align 1
+L689 label byte
+db 115
+db 55
+db 49
+db 52
+db 32
+db 32
+db 32
+db 0
+public _s714
+_DATA ends
+_TEXT segment
+_s714:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,248
+lea edi,(L689)
+mov dword ptr (-68)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+lea esi,(60)[edi]
+mov dword ptr (-72)[ebp],esi
+mov dword ptr (-76)[ebp],0
+mov dword ptr (-8)[ebp],0
+mov edi,dword ptr (48)[edi]
+mov dword ptr (-4)[ebp],edi
+L690:
+L691:
+mov edi,dword ptr (-72)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-72)[ebp],esi
+mov esi,dword ptr (-68)[ebp]
+lea ebx,(1)[esi]
+mov dword ptr (-68)[ebp],ebx
+mov bl,byte ptr [esi]
+mov byte ptr [edi],bl
+movsx edi,bl
+cmp edi,0
+jne L690
+mov byte ptr (-9)[ebp],5
+mov byte ptr (-25)[ebp],2
+mov bl,byte ptr (-25)[ebp]
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,2
+je L693
+mov dword ptr (-8)[ebp],1
+cmp dword ptr (-4)[ebp],0
+je L695
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L695:
+L693:
+mov byte ptr (-9)[ebp],5
+mov word ptr (-28)[ebp],2
+movsx edi,word ptr (-28)[ebp]
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,2
+je L697
+mov dword ptr (-8)[ebp],2
+cmp dword ptr (-4)[ebp],0
+je L699
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L699:
+L697:
+mov byte ptr (-9)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov edi,dword ptr (-32)[ebp]
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,2
+je L701
+mov dword ptr (-8)[ebp],3
+cmp dword ptr (-4)[ebp],0
+je L703
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L703:
+L701:
+mov byte ptr (-9)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov edi,dword ptr (-36)[ebp]
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,2
+je L705
+mov dword ptr (-8)[ebp],4
+cmp dword ptr (-4)[ebp],0
+je L707
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L707:
+L705:
+mov byte ptr (-9)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-40)[ebp]
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,2
+je L709
+mov dword ptr (-8)[ebp],5
+cmp dword ptr (-4)[ebp],0
+je L711
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L711:
+L709:
+mov byte ptr (-9)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+fld dword ptr (-56)[ebp]
+call __ftol
+mov ebx,eax
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,2
+je L713
+mov dword ptr (-8)[ebp],6
+cmp dword ptr (-4)[ebp],0
+je L715
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L715:
+L713:
+mov byte ptr (-9)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+fld qword ptr (-64)[ebp]
+call __ftol
+mov ebx,eax
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,2
+je L717
+mov dword ptr (-8)[ebp],7
+cmp dword ptr (-4)[ebp],0
+je L719
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L719:
+L717:
+mov word ptr (-12)[ebp],5
+mov byte ptr (-25)[ebp],2
+movsx edi,byte ptr (-25)[ebp]
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,2
+je L721
+mov dword ptr (-8)[ebp],8
+cmp dword ptr (-4)[ebp],0
+je L723
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L723:
+L721:
+mov word ptr (-12)[ebp],5
+mov word ptr (-28)[ebp],2
+mov di,word ptr (-28)[ebp]
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,2
+je L725
+mov dword ptr (-8)[ebp],9
+cmp dword ptr (-4)[ebp],0
+je L727
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L727:
+L725:
+mov word ptr (-12)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov edi,dword ptr (-32)[ebp]
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,2
+je L729
+mov dword ptr (-8)[ebp],10
+cmp dword ptr (-4)[ebp],0
+je L731
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L731:
+L729:
+mov word ptr (-12)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov edi,dword ptr (-36)[ebp]
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,2
+je L733
+mov dword ptr (-8)[ebp],11
+cmp dword ptr (-4)[ebp],0
+je L735
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L735:
+L733:
+mov word ptr (-12)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-40)[ebp]
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,2
+je L737
+mov dword ptr (-8)[ebp],12
+cmp dword ptr (-4)[ebp],0
+je L739
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L739:
+L737:
+mov word ptr (-12)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+fld dword ptr (-56)[ebp]
+call __ftol
+mov edi,eax
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,2
+je L741
+mov dword ptr (-8)[ebp],13
+cmp dword ptr (-4)[ebp],0
+je L743
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L743:
+L741:
+mov word ptr (-12)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+fld qword ptr (-64)[ebp]
+call __ftol
+mov edi,eax
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,2
+je L745
+mov dword ptr (-8)[ebp],14
+cmp dword ptr (-4)[ebp],0
+je L747
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L747:
+L745:
+mov dword ptr (-16)[ebp],5
+mov byte ptr (-25)[ebp],2
+movsx edi,byte ptr (-25)[ebp]
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],2
+je L749
+mov dword ptr (-8)[ebp],15
+cmp dword ptr (-4)[ebp],0
+je L751
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L751:
+L749:
+mov dword ptr (-16)[ebp],5
+mov word ptr (-28)[ebp],2
+movsx edi,word ptr (-28)[ebp]
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],2
+je L753
+mov dword ptr (-8)[ebp],16
+cmp dword ptr (-4)[ebp],0
+je L755
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L755:
+L753:
+mov dword ptr (-16)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov edi,dword ptr (-32)[ebp]
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],2
+je L757
+mov dword ptr (-8)[ebp],17
+cmp dword ptr (-4)[ebp],0
+je L759
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L759:
+L757:
+mov dword ptr (-16)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov edi,dword ptr (-36)[ebp]
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],2
+je L761
+mov dword ptr (-8)[ebp],18
+cmp dword ptr (-4)[ebp],0
+je L763
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L763:
+L761:
+mov dword ptr (-16)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-40)[ebp]
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],2
+je L765
+mov dword ptr (-8)[ebp],19
+cmp dword ptr (-4)[ebp],0
+je L767
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L767:
+L765:
+mov dword ptr (-16)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+fld dword ptr (-56)[ebp]
+call __ftol
+mov dword ptr (-16)[ebp],eax
+cmp dword ptr (-16)[ebp],2
+je L769
+mov dword ptr (-8)[ebp],20
+cmp dword ptr (-4)[ebp],0
+je L771
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L771:
+L769:
+mov dword ptr (-16)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+fld qword ptr (-64)[ebp]
+call __ftol
+mov dword ptr (-16)[ebp],eax
+cmp dword ptr (-16)[ebp],2
+je L773
+mov dword ptr (-8)[ebp],21
+cmp dword ptr (-4)[ebp],0
+je L775
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L775:
+L773:
+mov dword ptr (-20)[ebp],5
+mov byte ptr (-25)[ebp],2
+movsx edi,byte ptr (-25)[ebp]
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],2
+je L777
+mov dword ptr (-8)[ebp],22
+cmp dword ptr (-4)[ebp],0
+je L779
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L779:
+L777:
+mov dword ptr (-20)[ebp],5
+mov word ptr (-28)[ebp],2
+movsx edi,word ptr (-28)[ebp]
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],2
+je L781
+mov dword ptr (-8)[ebp],23
+cmp dword ptr (-4)[ebp],0
+je L783
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L783:
+L781:
+mov dword ptr (-20)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov edi,dword ptr (-32)[ebp]
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],2
+je L785
+mov dword ptr (-8)[ebp],24
+cmp dword ptr (-4)[ebp],0
+je L787
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L787:
+L785:
+mov dword ptr (-20)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov edi,dword ptr (-36)[ebp]
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],2
+je L789
+mov dword ptr (-8)[ebp],25
+cmp dword ptr (-4)[ebp],0
+je L791
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L791:
+L789:
+mov dword ptr (-20)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-40)[ebp]
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],2
+je L793
+mov dword ptr (-8)[ebp],26
+cmp dword ptr (-4)[ebp],0
+je L795
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L795:
+L793:
+mov dword ptr (-20)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+fld dword ptr (-56)[ebp]
+call __ftol
+mov dword ptr (-20)[ebp],eax
+cmp dword ptr (-20)[ebp],2
+je L797
+mov dword ptr (-8)[ebp],27
+cmp dword ptr (-4)[ebp],0
+je L799
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L799:
+L797:
+mov dword ptr (-20)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+fld qword ptr (-64)[ebp]
+call __ftol
+mov dword ptr (-20)[ebp],eax
+cmp dword ptr (-20)[ebp],2
+je L801
+mov dword ptr (-8)[ebp],28
+cmp dword ptr (-4)[ebp],0
+je L803
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L803:
+L801:
+mov dword ptr (-24)[ebp],5
+mov byte ptr (-25)[ebp],2
+movsx edi,byte ptr (-25)[ebp]
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,2
+je L805
+mov dword ptr (-8)[ebp],29
+cmp dword ptr (-4)[ebp],0
+je L807
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L807:
+L805:
+mov dword ptr (-24)[ebp],5
+mov word ptr (-28)[ebp],2
+movsx edi,word ptr (-28)[ebp]
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,2
+je L809
+mov dword ptr (-8)[ebp],30
+cmp dword ptr (-4)[ebp],0
+je L811
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L811:
+L809:
+mov dword ptr (-24)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov edi,dword ptr (-32)[ebp]
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,2
+je L813
+mov dword ptr (-8)[ebp],31
+cmp dword ptr (-4)[ebp],0
+je L815
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L815:
+L813:
+mov dword ptr (-24)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov edi,dword ptr (-36)[ebp]
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,2
+je L817
+mov dword ptr (-8)[ebp],32
+cmp dword ptr (-4)[ebp],0
+je L819
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L819:
+L817:
+mov dword ptr (-24)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-40)[ebp]
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,2
+je L821
+mov dword ptr (-8)[ebp],33
+cmp dword ptr (-4)[ebp],0
+je L823
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L823:
+L821:
+mov dword ptr (-24)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+fld dword ptr (L828)
+fcomp dword ptr (-56)[ebp]
+fstsw ax
+sahf
+ja L826
+fld dword ptr (-56)[ebp]
+fsub dword ptr (L828)
+call __ftol
+mov edi,eax
+lea edi,(080000000H)[edi]
+mov dword ptr (-80)[ebp],edi
+jmp L827
+L826:
+fld dword ptr (-56)[ebp]
+call __ftol
+mov edi,eax
+mov dword ptr (-80)[ebp],edi
+L827:
+mov edi,dword ptr (-80)[ebp]
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,2
+je L829
+mov dword ptr (-8)[ebp],34
+cmp dword ptr (-4)[ebp],0
+je L831
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L831:
+L829:
+mov dword ptr (-24)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+fld qword ptr (L836)
+fcomp qword ptr (-64)[ebp]
+fstsw ax
+sahf
+ja L834
+fld qword ptr (-64)[ebp]
+fsub qword ptr (L836)
+call __ftol
+mov edi,eax
+lea edi,(080000000H)[edi]
+mov dword ptr (-92)[ebp],edi
+jmp L835
+L834:
+fld qword ptr (-64)[ebp]
+call __ftol
+mov edi,eax
+mov dword ptr (-92)[ebp],edi
+L835:
+mov edi,dword ptr (-92)[ebp]
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,2
+je L837
+mov dword ptr (-8)[ebp],35
+cmp dword ptr (-4)[ebp],0
+je L839
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L839:
+L837:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov byte ptr (-25)[ebp],2
+movsx edi,byte ptr (-25)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L529)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L842
+mov dword ptr (-8)[ebp],36
+cmp dword ptr (-4)[ebp],0
+je L844
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L844:
+L842:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov word ptr (-28)[ebp],2
+movsx edi,word ptr (-28)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L529)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L846
+mov dword ptr (-8)[ebp],37
+cmp dword ptr (-4)[ebp],0
+je L848
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L848:
+L846:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov dword ptr (-32)[ebp],2
+mov edi,dword ptr (-32)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L529)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L850
+mov dword ptr (-8)[ebp],38
+cmp dword ptr (-4)[ebp],0
+je L852
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L852:
+L850:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov dword ptr (-36)[ebp],2
+mov edi,dword ptr (-36)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L529)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L854
+mov dword ptr (-8)[ebp],39
+cmp dword ptr (-4)[ebp],0
+je L856
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L856:
+L854:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-40)[ebp]
+fld qword ptr (L596)
+mov esi,edi
+shr esi,1
+push esi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+and edi,1
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L529)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L858
+mov dword ptr (-8)[ebp],40
+cmp dword ptr (-4)[ebp],0
+je L860
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L860:
+L858:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+fld dword ptr (-56)[ebp]
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L529)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L862
+mov dword ptr (-8)[ebp],41
+cmp dword ptr (-4)[ebp],0
+je L864
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L864:
+L862:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+fld qword ptr (-64)[ebp]
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L529)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L866
+mov dword ptr (-8)[ebp],42
+cmp dword ptr (-4)[ebp],0
+je L868
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L868:
+L866:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov byte ptr (-25)[ebp],2
+movsx edi,byte ptr (-25)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L416)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L871
+mov dword ptr (-8)[ebp],43
+cmp dword ptr (-4)[ebp],0
+je L873
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L873:
+L871:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov word ptr (-28)[ebp],2
+movsx edi,word ptr (-28)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L416)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L875
+mov dword ptr (-8)[ebp],44
+cmp dword ptr (-4)[ebp],0
+je L877
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L877:
+L875:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov dword ptr (-32)[ebp],2
+fild dword ptr (-32)[ebp]
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L416)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L879
+mov dword ptr (-8)[ebp],45
+cmp dword ptr (-4)[ebp],0
+je L881
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L881:
+L879:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov dword ptr (-36)[ebp],2
+fild dword ptr (-36)[ebp]
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L416)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L883
+mov dword ptr (-8)[ebp],46
+cmp dword ptr (-4)[ebp],0
+je L885
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L885:
+L883:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-40)[ebp]
+fld qword ptr (L596)
+mov esi,edi
+shr esi,1
+push esi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+and edi,1
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L416)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L887
+mov dword ptr (-8)[ebp],47
+cmp dword ptr (-4)[ebp],0
+je L889
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L889:
+L887:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+fld dword ptr (-56)[ebp]
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L416)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L891
+mov dword ptr (-8)[ebp],48
+cmp dword ptr (-4)[ebp],0
+je L893
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L893:
+L891:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+fld qword ptr (-64)[ebp]
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L416)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L895
+mov dword ptr (-8)[ebp],49
+cmp dword ptr (-4)[ebp],0
+je L897
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L897:
+L895:
+mov byte ptr (-9)[ebp],5
+mov byte ptr (-25)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+movsx esi,byte ptr (-25)[ebp]
+lea edi,[esi][edi]
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,7
+je L899
+mov dword ptr (-8)[ebp],50
+cmp dword ptr (-4)[ebp],0
+je L901
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L901:
+L899:
+mov byte ptr (-9)[ebp],5
+mov word ptr (-28)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+movsx esi,word ptr (-28)[ebp]
+lea edi,[esi][edi]
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,7
+je L903
+mov dword ptr (-8)[ebp],51
+cmp dword ptr (-4)[ebp],0
+je L905
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L905:
+L903:
+mov byte ptr (-9)[ebp],5
+mov dword ptr (-32)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+mov esi,dword ptr (-32)[ebp]
+lea edi,[esi][edi]
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,7
+je L907
+mov dword ptr (-8)[ebp],52
+cmp dword ptr (-4)[ebp],0
+je L909
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L909:
+L907:
+mov byte ptr (-9)[ebp],5
+mov dword ptr (-36)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+mov esi,dword ptr (-36)[ebp]
+lea edi,[esi][edi]
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,7
+je L911
+mov dword ptr (-8)[ebp],53
+cmp dword ptr (-4)[ebp],0
+je L913
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L913:
+L911:
+mov byte ptr (-9)[ebp],5
+mov dword ptr (-40)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+mov esi,dword ptr (-40)[ebp]
+lea edi,[esi][edi]
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,7
+je L915
+mov dword ptr (-8)[ebp],54
+cmp dword ptr (-4)[ebp],0
+je L917
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L917:
+L915:
+mov byte ptr (-9)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+movsx edi,byte ptr (-9)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fadd dword ptr (-56)[ebp]
+call __ftol
+mov ebx,eax
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,7
+je L919
+mov dword ptr (-8)[ebp],55
+cmp dword ptr (-4)[ebp],0
+je L921
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L921:
+L919:
+mov byte ptr (-9)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+movsx edi,byte ptr (-9)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fadd qword ptr (-64)[ebp]
+call __ftol
+mov ebx,eax
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,7
+je L923
+mov dword ptr (-8)[ebp],56
+cmp dword ptr (-4)[ebp],0
+je L925
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L925:
+L923:
+mov word ptr (-12)[ebp],5
+mov byte ptr (-25)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+movsx esi,byte ptr (-25)[ebp]
+lea edi,[esi][edi]
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,7
+je L927
+mov dword ptr (-8)[ebp],57
+cmp dword ptr (-4)[ebp],0
+je L929
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L929:
+L927:
+mov word ptr (-12)[ebp],5
+mov word ptr (-28)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+movsx esi,word ptr (-28)[ebp]
+lea edi,[esi][edi]
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,7
+je L931
+mov dword ptr (-8)[ebp],58
+cmp dword ptr (-4)[ebp],0
+je L933
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L933:
+L931:
+mov word ptr (-12)[ebp],5
+mov dword ptr (-32)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+mov esi,dword ptr (-32)[ebp]
+lea edi,[esi][edi]
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,7
+je L935
+mov dword ptr (-8)[ebp],59
+cmp dword ptr (-4)[ebp],0
+je L937
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L937:
+L935:
+mov word ptr (-12)[ebp],5
+mov dword ptr (-36)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+mov esi,dword ptr (-36)[ebp]
+lea edi,[esi][edi]
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,7
+je L939
+mov dword ptr (-8)[ebp],60
+cmp dword ptr (-4)[ebp],0
+je L941
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L941:
+L939:
+mov word ptr (-12)[ebp],5
+mov dword ptr (-40)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+mov esi,dword ptr (-40)[ebp]
+lea edi,[esi][edi]
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,7
+je L943
+mov dword ptr (-8)[ebp],61
+cmp dword ptr (-4)[ebp],0
+je L945
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L945:
+L943:
+mov word ptr (-12)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+movsx edi,word ptr (-12)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fadd dword ptr (-56)[ebp]
+call __ftol
+mov edi,eax
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,7
+je L947
+mov dword ptr (-8)[ebp],62
+cmp dword ptr (-4)[ebp],0
+je L949
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L949:
+L947:
+mov word ptr (-12)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+movsx edi,word ptr (-12)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fadd qword ptr (-64)[ebp]
+call __ftol
+mov edi,eax
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,7
+je L951
+mov dword ptr (-8)[ebp],63
+cmp dword ptr (-4)[ebp],0
+je L953
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L953:
+L951:
+mov dword ptr (-16)[ebp],5
+mov byte ptr (-25)[ebp],2
+movsx edi,byte ptr (-25)[ebp]
+add dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],7
+je L955
+mov dword ptr (-8)[ebp],64
+cmp dword ptr (-4)[ebp],0
+je L957
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L957:
+L955:
+mov dword ptr (-16)[ebp],5
+mov word ptr (-28)[ebp],2
+movsx edi,word ptr (-28)[ebp]
+add dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],7
+je L959
+mov dword ptr (-8)[ebp],65
+cmp dword ptr (-4)[ebp],0
+je L961
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L961:
+L959:
+mov dword ptr (-16)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov edi,dword ptr (-32)[ebp]
+add dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],7
+je L963
+mov dword ptr (-8)[ebp],66
+cmp dword ptr (-4)[ebp],0
+je L965
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L965:
+L963:
+mov dword ptr (-16)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov edi,dword ptr (-36)[ebp]
+add dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],7
+je L967
+mov dword ptr (-8)[ebp],67
+cmp dword ptr (-4)[ebp],0
+je L969
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L969:
+L967:
+mov dword ptr (-16)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-16)[ebp]
+mov esi,dword ptr (-40)[ebp]
+lea edi,[esi][edi]
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],7
+je L971
+mov dword ptr (-8)[ebp],68
+cmp dword ptr (-4)[ebp],0
+je L973
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L973:
+L971:
+mov dword ptr (-16)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+mov edi,dword ptr (-16)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fadd dword ptr (-56)[ebp]
+call __ftol
+mov dword ptr (-16)[ebp],eax
+cmp dword ptr (-16)[ebp],7
+je L975
+mov dword ptr (-8)[ebp],69
+cmp dword ptr (-4)[ebp],0
+je L977
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L977:
+L975:
+mov dword ptr (-16)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+fild dword ptr (-16)[ebp]
+fadd qword ptr (-64)[ebp]
+call __ftol
+mov dword ptr (-16)[ebp],eax
+cmp dword ptr (-16)[ebp],7
+je L979
+mov dword ptr (-8)[ebp],70
+cmp dword ptr (-4)[ebp],0
+je L981
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L981:
+L979:
+mov dword ptr (-20)[ebp],5
+mov byte ptr (-25)[ebp],2
+movsx edi,byte ptr (-25)[ebp]
+add dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],7
+je L983
+mov dword ptr (-8)[ebp],71
+cmp dword ptr (-4)[ebp],0
+je L985
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L985:
+L983:
+mov dword ptr (-20)[ebp],5
+mov word ptr (-28)[ebp],2
+movsx edi,word ptr (-28)[ebp]
+add dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],7
+je L987
+mov dword ptr (-8)[ebp],72
+cmp dword ptr (-4)[ebp],0
+je L989
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L989:
+L987:
+mov dword ptr (-20)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov edi,dword ptr (-32)[ebp]
+add dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],7
+je L991
+mov dword ptr (-8)[ebp],73
+cmp dword ptr (-4)[ebp],0
+je L993
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L993:
+L991:
+mov dword ptr (-20)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov edi,dword ptr (-36)[ebp]
+add dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],7
+je L995
+mov dword ptr (-8)[ebp],74
+cmp dword ptr (-4)[ebp],0
+je L997
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L997:
+L995:
+mov dword ptr (-20)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-20)[ebp]
+mov esi,dword ptr (-40)[ebp]
+lea edi,[esi][edi]
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],7
+je L999
+mov dword ptr (-8)[ebp],75
+cmp dword ptr (-4)[ebp],0
+je L1001
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1001:
+L999:
+mov dword ptr (-20)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+mov edi,dword ptr (-20)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fadd dword ptr (-56)[ebp]
+call __ftol
+mov dword ptr (-20)[ebp],eax
+cmp dword ptr (-20)[ebp],7
+je L1003
+mov dword ptr (-8)[ebp],76
+cmp dword ptr (-4)[ebp],0
+je L1005
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1005:
+L1003:
+mov dword ptr (-20)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+fild dword ptr (-20)[ebp]
+fadd qword ptr (-64)[ebp]
+call __ftol
+mov dword ptr (-20)[ebp],eax
+cmp dword ptr (-20)[ebp],7
+je L1007
+mov dword ptr (-8)[ebp],77
+cmp dword ptr (-4)[ebp],0
+je L1009
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1009:
+L1007:
+mov dword ptr (-24)[ebp],5
+mov byte ptr (-25)[ebp],2
+movsx edi,byte ptr (-25)[ebp]
+add dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,7
+je L1011
+mov dword ptr (-8)[ebp],78
+cmp dword ptr (-4)[ebp],0
+je L1013
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1013:
+L1011:
+mov dword ptr (-24)[ebp],5
+mov word ptr (-28)[ebp],2
+movsx edi,word ptr (-28)[ebp]
+add dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,7
+je L1015
+mov dword ptr (-8)[ebp],79
+cmp dword ptr (-4)[ebp],0
+je L1017
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1017:
+L1015:
+mov dword ptr (-24)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov edi,dword ptr (-32)[ebp]
+add dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,7
+je L1019
+mov dword ptr (-8)[ebp],80
+cmp dword ptr (-4)[ebp],0
+je L1021
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1021:
+L1019:
+mov dword ptr (-24)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov edi,dword ptr (-36)[ebp]
+add dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,7
+je L1023
+mov dword ptr (-8)[ebp],81
+cmp dword ptr (-4)[ebp],0
+je L1025
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1025:
+L1023:
+mov dword ptr (-24)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-40)[ebp]
+add dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,7
+je L1027
+mov dword ptr (-8)[ebp],82
+cmp dword ptr (-4)[ebp],0
+je L1029
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1029:
+L1027:
+mov dword ptr (-24)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+mov edi,dword ptr (-24)[ebp]
+fld qword ptr (L596)
+mov esi,edi
+shr esi,1
+push esi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+and edi,1
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+sub esp,4
+fstp dword ptr 0[esp]
+fld dword ptr 0[esp]
+add esp,4
+fadd dword ptr (-56)[ebp]
+fstp dword ptr (-128)[ebp]
+fld dword ptr (L828)
+fcomp dword ptr (-128)[ebp]
+fstsw ax
+sahf
+ja L1032
+fld dword ptr (-128)[ebp]
+fsub dword ptr (L828)
+call __ftol
+mov edi,eax
+lea edi,(080000000H)[edi]
+mov dword ptr (-124)[ebp],edi
+jmp L1033
+L1032:
+fld dword ptr (-128)[ebp]
+call __ftol
+mov edi,eax
+mov dword ptr (-124)[ebp],edi
+L1033:
+mov edi,dword ptr (-124)[ebp]
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,7
+je L1034
+mov dword ptr (-8)[ebp],83
+cmp dword ptr (-4)[ebp],0
+je L1036
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1036:
+L1034:
+mov dword ptr (-24)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+mov edi,dword ptr (-24)[ebp]
+fld qword ptr (L596)
+mov esi,edi
+shr esi,1
+push esi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+and edi,1
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+fadd qword ptr (-64)[ebp]
+fstp qword ptr (-144)[ebp]
+fld qword ptr (L836)
+fcomp qword ptr (-144)[ebp]
+fstsw ax
+sahf
+ja L1039
+fld qword ptr (-144)[ebp]
+fsub qword ptr (L836)
+call __ftol
+mov edi,eax
+lea edi,(080000000H)[edi]
+mov dword ptr (-136)[ebp],edi
+jmp L1040
+L1039:
+fld qword ptr (-144)[ebp]
+call __ftol
+mov edi,eax
+mov dword ptr (-136)[ebp],edi
+L1040:
+mov edi,dword ptr (-136)[ebp]
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,7
+je L1041
+mov dword ptr (-8)[ebp],84
+cmp dword ptr (-4)[ebp],0
+je L1043
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1043:
+L1041:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov byte ptr (-25)[ebp],2
+fld dword ptr (-44)[ebp]
+movsx edi,byte ptr (-25)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L1047)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1045
+mov dword ptr (-8)[ebp],85
+cmp dword ptr (-4)[ebp],0
+je L1048
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1048:
+L1045:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov word ptr (-28)[ebp],2
+fld dword ptr (-44)[ebp]
+movsx edi,word ptr (-28)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L1047)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1050
+mov dword ptr (-8)[ebp],86
+cmp dword ptr (-4)[ebp],0
+je L1052
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1052:
+L1050:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov dword ptr (-32)[ebp],2
+fld dword ptr (-44)[ebp]
+mov edi,dword ptr (-32)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L1047)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1054
+mov dword ptr (-8)[ebp],87
+cmp dword ptr (-4)[ebp],0
+je L1056
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1056:
+L1054:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov dword ptr (-36)[ebp],2
+fld dword ptr (-44)[ebp]
+mov edi,dword ptr (-36)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L1047)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1058
+mov dword ptr (-8)[ebp],88
+cmp dword ptr (-4)[ebp],0
+je L1060
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1060:
+L1058:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-40)[ebp]
+fld dword ptr (-44)[ebp]
+fld qword ptr (L596)
+mov esi,edi
+shr esi,1
+push esi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+and edi,1
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+sub esp,4
+fstp dword ptr 0[esp]
+fld dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L1047)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1062
+mov dword ptr (-8)[ebp],89
+cmp dword ptr (-4)[ebp],0
+je L1064
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1064:
+L1062:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+fld dword ptr (-44)[ebp]
+fadd dword ptr (-56)[ebp]
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L1047)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1066
+mov dword ptr (-8)[ebp],90
+cmp dword ptr (-4)[ebp],0
+je L1068
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1068:
+L1066:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+fld dword ptr (-44)[ebp]
+fadd qword ptr (-64)[ebp]
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L1047)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1070
+mov dword ptr (-8)[ebp],91
+cmp dword ptr (-4)[ebp],0
+je L1072
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1072:
+L1070:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov byte ptr (-25)[ebp],2
+fld qword ptr (-52)[ebp]
+movsx edi,byte ptr (-25)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1076)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1074
+mov dword ptr (-8)[ebp],92
+cmp dword ptr (-4)[ebp],0
+je L1077
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1077:
+L1074:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov word ptr (-28)[ebp],2
+fld qword ptr (-52)[ebp]
+movsx edi,word ptr (-28)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1076)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1079
+mov dword ptr (-8)[ebp],93
+cmp dword ptr (-4)[ebp],0
+je L1081
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1081:
+L1079:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov dword ptr (-32)[ebp],2
+fld qword ptr (-52)[ebp]
+fild dword ptr (-32)[ebp]
+faddp st(1),st
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1076)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1083
+mov dword ptr (-8)[ebp],94
+cmp dword ptr (-4)[ebp],0
+je L1085
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1085:
+L1083:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov dword ptr (-36)[ebp],2
+fld qword ptr (-52)[ebp]
+fild dword ptr (-36)[ebp]
+faddp st(1),st
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1076)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1087
+mov dword ptr (-8)[ebp],95
+cmp dword ptr (-4)[ebp],0
+je L1089
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1089:
+L1087:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-40)[ebp]
+fld qword ptr (-52)[ebp]
+fld qword ptr (L596)
+mov esi,edi
+shr esi,1
+push esi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+and edi,1
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+faddp st(1),st
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1076)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1091
+mov dword ptr (-8)[ebp],96
+cmp dword ptr (-4)[ebp],0
+je L1093
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1093:
+L1091:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+fld qword ptr (-52)[ebp]
+fadd dword ptr (-56)[ebp]
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1076)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1095
+mov dword ptr (-8)[ebp],97
+cmp dword ptr (-4)[ebp],0
+je L1097
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1097:
+L1095:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+fld qword ptr (-52)[ebp]
+fadd qword ptr (-64)[ebp]
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1076)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1099
+mov dword ptr (-8)[ebp],98
+cmp dword ptr (-4)[ebp],0
+je L1101
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1101:
+L1099:
+mov byte ptr (-9)[ebp],5
+mov byte ptr (-25)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+movsx esi,byte ptr (-25)[ebp]
+sub edi,esi
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,3
+je L1103
+mov dword ptr (-8)[ebp],99
+cmp dword ptr (-4)[ebp],0
+je L1105
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1105:
+L1103:
+mov byte ptr (-9)[ebp],5
+mov word ptr (-28)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+movsx esi,word ptr (-28)[ebp]
+sub edi,esi
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,3
+je L1107
+mov dword ptr (-8)[ebp],100
+cmp dword ptr (-4)[ebp],0
+je L1109
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1109:
+L1107:
+mov byte ptr (-9)[ebp],5
+mov dword ptr (-32)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+sub edi,dword ptr (-32)[ebp]
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,3
+je L1111
+mov dword ptr (-8)[ebp],101
+cmp dword ptr (-4)[ebp],0
+je L1113
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1113:
+L1111:
+mov byte ptr (-9)[ebp],5
+mov dword ptr (-36)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+sub edi,dword ptr (-36)[ebp]
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,3
+je L1115
+mov dword ptr (-8)[ebp],102
+cmp dword ptr (-4)[ebp],0
+je L1117
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1117:
+L1115:
+mov byte ptr (-9)[ebp],5
+mov dword ptr (-40)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+sub edi,dword ptr (-40)[ebp]
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,3
+je L1119
+mov dword ptr (-8)[ebp],103
+cmp dword ptr (-4)[ebp],0
+je L1121
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1121:
+L1119:
+mov byte ptr (-9)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+movsx edi,byte ptr (-9)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fsub dword ptr (-56)[ebp]
+call __ftol
+mov ebx,eax
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,3
+je L1123
+mov dword ptr (-8)[ebp],104
+cmp dword ptr (-4)[ebp],0
+je L1125
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1125:
+L1123:
+mov byte ptr (-9)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+movsx edi,byte ptr (-9)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fsub qword ptr (-64)[ebp]
+call __ftol
+mov ebx,eax
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,3
+je L1127
+mov dword ptr (-8)[ebp],105
+cmp dword ptr (-4)[ebp],0
+je L1129
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1129:
+L1127:
+mov word ptr (-12)[ebp],5
+mov byte ptr (-25)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+movsx esi,byte ptr (-25)[ebp]
+sub edi,esi
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,3
+je L1131
+mov dword ptr (-8)[ebp],106
+cmp dword ptr (-4)[ebp],0
+je L1133
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1133:
+L1131:
+mov word ptr (-12)[ebp],5
+mov word ptr (-28)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+movsx esi,word ptr (-28)[ebp]
+sub edi,esi
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,3
+je L1135
+mov dword ptr (-8)[ebp],107
+cmp dword ptr (-4)[ebp],0
+je L1137
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1137:
+L1135:
+mov word ptr (-12)[ebp],5
+mov dword ptr (-32)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+sub edi,dword ptr (-32)[ebp]
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,3
+je L1139
+mov dword ptr (-8)[ebp],108
+cmp dword ptr (-4)[ebp],0
+je L1141
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1141:
+L1139:
+mov word ptr (-12)[ebp],5
+mov dword ptr (-36)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+sub edi,dword ptr (-36)[ebp]
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,3
+je L1143
+mov dword ptr (-8)[ebp],109
+cmp dword ptr (-4)[ebp],0
+je L1145
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1145:
+L1143:
+mov word ptr (-12)[ebp],5
+mov dword ptr (-40)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+sub edi,dword ptr (-40)[ebp]
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,3
+je L1147
+mov dword ptr (-8)[ebp],110
+cmp dword ptr (-4)[ebp],0
+je L1149
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1149:
+L1147:
+mov word ptr (-12)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+movsx edi,word ptr (-12)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fsub dword ptr (-56)[ebp]
+call __ftol
+mov edi,eax
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,3
+je L1151
+mov dword ptr (-8)[ebp],111
+cmp dword ptr (-4)[ebp],0
+je L1153
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1153:
+L1151:
+mov word ptr (-12)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+movsx edi,word ptr (-12)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fsub qword ptr (-64)[ebp]
+call __ftol
+mov edi,eax
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,3
+je L1155
+mov dword ptr (-8)[ebp],112
+cmp dword ptr (-4)[ebp],0
+je L1157
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1157:
+L1155:
+mov dword ptr (-16)[ebp],5
+mov byte ptr (-25)[ebp],2
+movsx edi,byte ptr (-25)[ebp]
+sub dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],3
+je L1159
+mov dword ptr (-8)[ebp],113
+cmp dword ptr (-4)[ebp],0
+je L1161
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1161:
+L1159:
+mov dword ptr (-16)[ebp],5
+mov word ptr (-28)[ebp],2
+movsx edi,word ptr (-28)[ebp]
+sub dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],3
+je L1163
+mov dword ptr (-8)[ebp],114
+cmp dword ptr (-4)[ebp],0
+je L1165
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1165:
+L1163:
+mov dword ptr (-16)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov edi,dword ptr (-32)[ebp]
+sub dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],3
+je L1167
+mov dword ptr (-8)[ebp],115
+cmp dword ptr (-4)[ebp],0
+je L1169
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1169:
+L1167:
+mov dword ptr (-16)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov edi,dword ptr (-36)[ebp]
+sub dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],3
+je L1171
+mov dword ptr (-8)[ebp],116
+cmp dword ptr (-4)[ebp],0
+je L1173
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1173:
+L1171:
+mov dword ptr (-16)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-16)[ebp]
+sub edi,dword ptr (-40)[ebp]
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],3
+je L1175
+mov dword ptr (-8)[ebp],117
+cmp dword ptr (-4)[ebp],0
+je L1177
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1177:
+L1175:
+mov dword ptr (-16)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+mov edi,dword ptr (-16)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fsub dword ptr (-56)[ebp]
+call __ftol
+mov dword ptr (-16)[ebp],eax
+cmp dword ptr (-16)[ebp],3
+je L1179
+mov dword ptr (-8)[ebp],118
+cmp dword ptr (-4)[ebp],0
+je L1181
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1181:
+L1179:
+mov dword ptr (-16)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+fild dword ptr (-16)[ebp]
+fsub qword ptr (-64)[ebp]
+call __ftol
+mov dword ptr (-16)[ebp],eax
+cmp dword ptr (-16)[ebp],3
+je L1183
+mov dword ptr (-8)[ebp],119
+cmp dword ptr (-4)[ebp],0
+je L1185
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1185:
+L1183:
+mov dword ptr (-20)[ebp],5
+mov byte ptr (-25)[ebp],2
+movsx edi,byte ptr (-25)[ebp]
+sub dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],3
+je L1187
+mov dword ptr (-8)[ebp],120
+cmp dword ptr (-4)[ebp],0
+je L1189
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1189:
+L1187:
+mov dword ptr (-20)[ebp],5
+mov word ptr (-28)[ebp],2
+movsx edi,word ptr (-28)[ebp]
+sub dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],3
+je L1191
+mov dword ptr (-8)[ebp],121
+cmp dword ptr (-4)[ebp],0
+je L1193
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1193:
+L1191:
+mov dword ptr (-20)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov edi,dword ptr (-32)[ebp]
+sub dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],3
+je L1195
+mov dword ptr (-8)[ebp],122
+cmp dword ptr (-4)[ebp],0
+je L1197
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1197:
+L1195:
+mov dword ptr (-20)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov edi,dword ptr (-36)[ebp]
+sub dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],3
+je L1199
+mov dword ptr (-8)[ebp],123
+cmp dword ptr (-4)[ebp],0
+je L1201
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1201:
+L1199:
+mov dword ptr (-20)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-20)[ebp]
+sub edi,dword ptr (-40)[ebp]
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],3
+je L1203
+mov dword ptr (-8)[ebp],124
+cmp dword ptr (-4)[ebp],0
+je L1205
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1205:
+L1203:
+mov dword ptr (-20)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+mov edi,dword ptr (-20)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fsub dword ptr (-56)[ebp]
+call __ftol
+mov dword ptr (-20)[ebp],eax
+cmp dword ptr (-20)[ebp],3
+je L1207
+mov dword ptr (-8)[ebp],125
+cmp dword ptr (-4)[ebp],0
+je L1209
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1209:
+L1207:
+mov dword ptr (-20)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+fild dword ptr (-20)[ebp]
+fsub qword ptr (-64)[ebp]
+call __ftol
+mov dword ptr (-20)[ebp],eax
+cmp dword ptr (-20)[ebp],3
+je L1211
+mov dword ptr (-8)[ebp],126
+cmp dword ptr (-4)[ebp],0
+je L1213
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1213:
+L1211:
+mov dword ptr (-24)[ebp],5
+mov byte ptr (-25)[ebp],2
+movsx edi,byte ptr (-25)[ebp]
+sub dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,3
+je L1215
+mov dword ptr (-8)[ebp],127
+cmp dword ptr (-4)[ebp],0
+je L1217
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1217:
+L1215:
+mov dword ptr (-24)[ebp],5
+mov word ptr (-28)[ebp],2
+movsx edi,word ptr (-28)[ebp]
+sub dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,3
+je L1219
+mov dword ptr (-8)[ebp],128
+cmp dword ptr (-4)[ebp],0
+je L1221
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1221:
+L1219:
+mov dword ptr (-24)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov edi,dword ptr (-32)[ebp]
+sub dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,3
+je L1223
+mov dword ptr (-8)[ebp],129
+cmp dword ptr (-4)[ebp],0
+je L1225
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1225:
+L1223:
+mov dword ptr (-24)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov edi,dword ptr (-36)[ebp]
+sub dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,3
+je L1227
+mov dword ptr (-8)[ebp],130
+cmp dword ptr (-4)[ebp],0
+je L1229
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1229:
+L1227:
+mov dword ptr (-24)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-40)[ebp]
+sub dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,3
+je L1231
+mov dword ptr (-8)[ebp],131
+cmp dword ptr (-4)[ebp],0
+je L1233
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1233:
+L1231:
+mov dword ptr (-24)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+mov edi,dword ptr (-24)[ebp]
+fld qword ptr (L596)
+mov esi,edi
+shr esi,1
+push esi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+and edi,1
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+sub esp,4
+fstp dword ptr 0[esp]
+fld dword ptr 0[esp]
+add esp,4
+fsub dword ptr (-56)[ebp]
+fstp dword ptr (-160)[ebp]
+fld dword ptr (L828)
+fcomp dword ptr (-160)[ebp]
+fstsw ax
+sahf
+ja L1236
+fld dword ptr (-160)[ebp]
+fsub dword ptr (L828)
+call __ftol
+mov edi,eax
+lea edi,(080000000H)[edi]
+mov dword ptr (-156)[ebp],edi
+jmp L1237
+L1236:
+fld dword ptr (-160)[ebp]
+call __ftol
+mov edi,eax
+mov dword ptr (-156)[ebp],edi
+L1237:
+mov edi,dword ptr (-156)[ebp]
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,3
+je L1238
+mov dword ptr (-8)[ebp],132
+cmp dword ptr (-4)[ebp],0
+je L1240
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1240:
+L1238:
+mov dword ptr (-24)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+mov edi,dword ptr (-24)[ebp]
+fld qword ptr (L596)
+mov esi,edi
+shr esi,1
+push esi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+and edi,1
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+fsub qword ptr (-64)[ebp]
+fstp qword ptr (-176)[ebp]
+fld qword ptr (L836)
+fcomp qword ptr (-176)[ebp]
+fstsw ax
+sahf
+ja L1243
+fld qword ptr (-176)[ebp]
+fsub qword ptr (L836)
+call __ftol
+mov edi,eax
+lea edi,(080000000H)[edi]
+mov dword ptr (-168)[ebp],edi
+jmp L1244
+L1243:
+fld qword ptr (-176)[ebp]
+call __ftol
+mov edi,eax
+mov dword ptr (-168)[ebp],edi
+L1244:
+mov edi,dword ptr (-168)[ebp]
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,3
+je L1245
+mov dword ptr (-8)[ebp],133
+cmp dword ptr (-4)[ebp],0
+je L1247
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1247:
+L1245:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov byte ptr (-25)[ebp],2
+fld dword ptr (-44)[ebp]
+movsx edi,byte ptr (-25)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fsubp st(1),st
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L1251)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1249
+mov dword ptr (-8)[ebp],134
+cmp dword ptr (-4)[ebp],0
+je L1252
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1252:
+L1249:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov word ptr (-28)[ebp],2
+fld dword ptr (-44)[ebp]
+movsx edi,word ptr (-28)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fsubp st(1),st
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L1251)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1254
+mov dword ptr (-8)[ebp],135
+cmp dword ptr (-4)[ebp],0
+je L1256
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1256:
+L1254:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov dword ptr (-32)[ebp],2
+fld dword ptr (-44)[ebp]
+mov edi,dword ptr (-32)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fsubp st(1),st
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L1251)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1258
+mov dword ptr (-8)[ebp],136
+cmp dword ptr (-4)[ebp],0
+je L1260
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1260:
+L1258:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov dword ptr (-36)[ebp],2
+fld dword ptr (-44)[ebp]
+mov edi,dword ptr (-36)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fsubp st(1),st
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L1251)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1262
+mov dword ptr (-8)[ebp],137
+cmp dword ptr (-4)[ebp],0
+je L1264
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1264:
+L1262:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-40)[ebp]
+fld dword ptr (-44)[ebp]
+fld qword ptr (L596)
+mov esi,edi
+shr esi,1
+push esi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+and edi,1
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+sub esp,4
+fstp dword ptr 0[esp]
+fld dword ptr 0[esp]
+add esp,4
+fsubp st(1),st
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L1251)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1266
+mov dword ptr (-8)[ebp],138
+cmp dword ptr (-4)[ebp],0
+je L1268
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1268:
+L1266:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+fld dword ptr (-44)[ebp]
+fsub dword ptr (-56)[ebp]
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L1251)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1270
+mov dword ptr (-8)[ebp],139
+cmp dword ptr (-4)[ebp],0
+je L1272
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1272:
+L1270:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+fld dword ptr (-44)[ebp]
+fsub qword ptr (-64)[ebp]
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L1251)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1274
+mov dword ptr (-8)[ebp],140
+cmp dword ptr (-4)[ebp],0
+je L1276
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1276:
+L1274:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov byte ptr (-25)[ebp],2
+fld qword ptr (-52)[ebp]
+movsx edi,byte ptr (-25)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fsubp st(1),st
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1280)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1278
+mov dword ptr (-8)[ebp],141
+cmp dword ptr (-4)[ebp],0
+je L1281
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1281:
+L1278:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov word ptr (-28)[ebp],2
+fld qword ptr (-52)[ebp]
+movsx edi,word ptr (-28)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fsubp st(1),st
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1280)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1283
+mov dword ptr (-8)[ebp],142
+cmp dword ptr (-4)[ebp],0
+je L1285
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1285:
+L1283:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov dword ptr (-32)[ebp],2
+fld qword ptr (-52)[ebp]
+fild dword ptr (-32)[ebp]
+fsubp st(1),st
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1280)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1287
+mov dword ptr (-8)[ebp],143
+cmp dword ptr (-4)[ebp],0
+je L1289
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1289:
+L1287:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov dword ptr (-36)[ebp],2
+fld qword ptr (-52)[ebp]
+fild dword ptr (-36)[ebp]
+fsubp st(1),st
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1280)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1291
+mov dword ptr (-8)[ebp],144
+cmp dword ptr (-4)[ebp],0
+je L1293
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1293:
+L1291:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-40)[ebp]
+fld qword ptr (-52)[ebp]
+fld qword ptr (L596)
+mov esi,edi
+shr esi,1
+push esi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+and edi,1
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+fsubp st(1),st
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1280)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1295
+mov dword ptr (-8)[ebp],145
+cmp dword ptr (-4)[ebp],0
+je L1297
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1297:
+L1295:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+fld qword ptr (-52)[ebp]
+fsub dword ptr (-56)[ebp]
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1280)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1299
+mov dword ptr (-8)[ebp],146
+cmp dword ptr (-4)[ebp],0
+je L1301
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1301:
+L1299:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+fld qword ptr (-52)[ebp]
+fsub qword ptr (-64)[ebp]
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1280)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1303
+mov dword ptr (-8)[ebp],147
+cmp dword ptr (-4)[ebp],0
+je L1305
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1305:
+L1303:
+mov byte ptr (-9)[ebp],5
+mov byte ptr (-25)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+movsx esi,byte ptr (-25)[ebp]
+imul edi,esi
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,10
+je L1307
+mov dword ptr (-8)[ebp],148
+cmp dword ptr (-4)[ebp],0
+je L1309
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1309:
+L1307:
+mov byte ptr (-9)[ebp],5
+mov word ptr (-28)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+movsx esi,word ptr (-28)[ebp]
+imul edi,esi
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,10
+je L1311
+mov dword ptr (-8)[ebp],149
+cmp dword ptr (-4)[ebp],0
+je L1313
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1313:
+L1311:
+mov byte ptr (-9)[ebp],5
+mov dword ptr (-32)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+mov esi,dword ptr (-32)[ebp]
+imul edi,esi
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,10
+je L1315
+mov dword ptr (-8)[ebp],150
+cmp dword ptr (-4)[ebp],0
+je L1317
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1317:
+L1315:
+mov byte ptr (-9)[ebp],5
+mov dword ptr (-36)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+mov esi,dword ptr (-36)[ebp]
+imul edi,esi
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,10
+je L1319
+mov dword ptr (-8)[ebp],151
+cmp dword ptr (-4)[ebp],0
+je L1321
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1321:
+L1319:
+mov byte ptr (-9)[ebp],5
+mov dword ptr (-40)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+mov eax,edi
+mul dword ptr (-40)[ebp]
+mov edi,eax
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,10
+je L1323
+mov dword ptr (-8)[ebp],152
+cmp dword ptr (-4)[ebp],0
+je L1325
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1325:
+L1323:
+mov byte ptr (-9)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+movsx edi,byte ptr (-9)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fmul dword ptr (-56)[ebp]
+call __ftol
+mov ebx,eax
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,10
+je L1327
+mov dword ptr (-8)[ebp],153
+cmp dword ptr (-4)[ebp],0
+je L1329
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1329:
+L1327:
+mov byte ptr (-9)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+movsx edi,byte ptr (-9)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fmul qword ptr (-64)[ebp]
+call __ftol
+mov ebx,eax
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,10
+je L1331
+mov dword ptr (-8)[ebp],154
+cmp dword ptr (-4)[ebp],0
+je L1333
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1333:
+L1331:
+mov word ptr (-12)[ebp],5
+mov byte ptr (-25)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+movsx esi,byte ptr (-25)[ebp]
+imul edi,esi
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,10
+je L1335
+mov dword ptr (-8)[ebp],155
+cmp dword ptr (-4)[ebp],0
+je L1337
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1337:
+L1335:
+mov word ptr (-12)[ebp],5
+mov word ptr (-28)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+movsx esi,word ptr (-28)[ebp]
+imul edi,esi
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,10
+je L1339
+mov dword ptr (-8)[ebp],156
+cmp dword ptr (-4)[ebp],0
+je L1341
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1341:
+L1339:
+mov word ptr (-12)[ebp],5
+mov dword ptr (-32)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+mov esi,dword ptr (-32)[ebp]
+imul edi,esi
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,10
+je L1343
+mov dword ptr (-8)[ebp],157
+cmp dword ptr (-4)[ebp],0
+je L1345
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1345:
+L1343:
+mov word ptr (-12)[ebp],5
+mov dword ptr (-36)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+mov esi,dword ptr (-36)[ebp]
+imul edi,esi
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,10
+je L1347
+mov dword ptr (-8)[ebp],158
+cmp dword ptr (-4)[ebp],0
+je L1349
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1349:
+L1347:
+mov word ptr (-12)[ebp],5
+mov dword ptr (-40)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+mov eax,edi
+mul dword ptr (-40)[ebp]
+mov edi,eax
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,10
+je L1351
+mov dword ptr (-8)[ebp],159
+cmp dword ptr (-4)[ebp],0
+je L1353
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1353:
+L1351:
+mov word ptr (-12)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+movsx edi,word ptr (-12)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fmul dword ptr (-56)[ebp]
+call __ftol
+mov edi,eax
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,10
+je L1355
+mov dword ptr (-8)[ebp],160
+cmp dword ptr (-4)[ebp],0
+je L1357
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1357:
+L1355:
+mov word ptr (-12)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+movsx edi,word ptr (-12)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fmul qword ptr (-64)[ebp]
+call __ftol
+mov edi,eax
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,10
+je L1359
+mov dword ptr (-8)[ebp],161
+cmp dword ptr (-4)[ebp],0
+je L1361
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1361:
+L1359:
+mov dword ptr (-16)[ebp],5
+mov byte ptr (-25)[ebp],2
+mov edi,dword ptr (-16)[ebp]
+movsx esi,byte ptr (-25)[ebp]
+imul edi,esi
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],10
+je L1363
+mov dword ptr (-8)[ebp],162
+cmp dword ptr (-4)[ebp],0
+je L1365
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1365:
+L1363:
+mov dword ptr (-16)[ebp],5
+mov word ptr (-28)[ebp],2
+mov edi,dword ptr (-16)[ebp]
+movsx esi,word ptr (-28)[ebp]
+imul edi,esi
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],10
+je L1367
+mov dword ptr (-8)[ebp],163
+cmp dword ptr (-4)[ebp],0
+je L1369
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1369:
+L1367:
+mov dword ptr (-16)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov edi,dword ptr (-16)[ebp]
+mov esi,dword ptr (-32)[ebp]
+imul edi,esi
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],10
+je L1371
+mov dword ptr (-8)[ebp],164
+cmp dword ptr (-4)[ebp],0
+je L1373
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1373:
+L1371:
+mov dword ptr (-16)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov edi,dword ptr (-16)[ebp]
+mov esi,dword ptr (-36)[ebp]
+imul edi,esi
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],10
+je L1375
+mov dword ptr (-8)[ebp],165
+cmp dword ptr (-4)[ebp],0
+je L1377
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1377:
+L1375:
+mov dword ptr (-16)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-16)[ebp]
+mov eax,edi
+mul dword ptr (-40)[ebp]
+mov edi,eax
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],10
+je L1379
+mov dword ptr (-8)[ebp],166
+cmp dword ptr (-4)[ebp],0
+je L1381
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1381:
+L1379:
+mov dword ptr (-16)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+mov edi,dword ptr (-16)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fmul dword ptr (-56)[ebp]
+call __ftol
+mov dword ptr (-16)[ebp],eax
+cmp dword ptr (-16)[ebp],10
+je L1383
+mov dword ptr (-8)[ebp],167
+cmp dword ptr (-4)[ebp],0
+je L1385
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1385:
+L1383:
+mov dword ptr (-16)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+fild dword ptr (-16)[ebp]
+fmul qword ptr (-64)[ebp]
+call __ftol
+mov dword ptr (-16)[ebp],eax
+cmp dword ptr (-16)[ebp],10
+je L1387
+mov dword ptr (-8)[ebp],168
+cmp dword ptr (-4)[ebp],0
+je L1389
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1389:
+L1387:
+mov dword ptr (-20)[ebp],5
+mov byte ptr (-25)[ebp],2
+mov edi,dword ptr (-20)[ebp]
+movsx esi,byte ptr (-25)[ebp]
+imul edi,esi
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],10
+je L1391
+mov dword ptr (-8)[ebp],169
+cmp dword ptr (-4)[ebp],0
+je L1393
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1393:
+L1391:
+mov dword ptr (-20)[ebp],5
+mov word ptr (-28)[ebp],2
+mov edi,dword ptr (-20)[ebp]
+movsx esi,word ptr (-28)[ebp]
+imul edi,esi
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],10
+je L1395
+mov dword ptr (-8)[ebp],170
+cmp dword ptr (-4)[ebp],0
+je L1397
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1397:
+L1395:
+mov dword ptr (-20)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov edi,dword ptr (-20)[ebp]
+mov esi,dword ptr (-32)[ebp]
+imul edi,esi
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],10
+je L1399
+mov dword ptr (-8)[ebp],171
+cmp dword ptr (-4)[ebp],0
+je L1401
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1401:
+L1399:
+mov dword ptr (-20)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov edi,dword ptr (-20)[ebp]
+mov esi,dword ptr (-36)[ebp]
+imul edi,esi
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],10
+je L1403
+mov dword ptr (-8)[ebp],172
+cmp dword ptr (-4)[ebp],0
+je L1405
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1405:
+L1403:
+mov dword ptr (-20)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-20)[ebp]
+mov eax,edi
+mul dword ptr (-40)[ebp]
+mov edi,eax
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],10
+je L1407
+mov dword ptr (-8)[ebp],173
+cmp dword ptr (-4)[ebp],0
+je L1409
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1409:
+L1407:
+mov dword ptr (-20)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+mov edi,dword ptr (-20)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fmul dword ptr (-56)[ebp]
+call __ftol
+mov dword ptr (-20)[ebp],eax
+cmp dword ptr (-20)[ebp],10
+je L1411
+mov dword ptr (-8)[ebp],174
+cmp dword ptr (-4)[ebp],0
+je L1413
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1413:
+L1411:
+mov dword ptr (-20)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+fild dword ptr (-20)[ebp]
+fmul qword ptr (-64)[ebp]
+call __ftol
+mov dword ptr (-20)[ebp],eax
+cmp dword ptr (-20)[ebp],10
+je L1415
+mov dword ptr (-8)[ebp],175
+cmp dword ptr (-4)[ebp],0
+je L1417
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1417:
+L1415:
+mov dword ptr (-24)[ebp],5
+mov byte ptr (-25)[ebp],2
+mov eax,dword ptr (-24)[ebp]
+movsx edi,byte ptr (-25)[ebp]
+mul edi
+mov dword ptr (-24)[ebp],eax
+mov edi,dword ptr (-24)[ebp]
+cmp edi,10
+je L1419
+mov dword ptr (-8)[ebp],176
+cmp dword ptr (-4)[ebp],0
+je L1421
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1421:
+L1419:
+mov dword ptr (-24)[ebp],5
+mov word ptr (-28)[ebp],2
+mov eax,dword ptr (-24)[ebp]
+movsx edi,word ptr (-28)[ebp]
+mul edi
+mov dword ptr (-24)[ebp],eax
+mov edi,dword ptr (-24)[ebp]
+cmp edi,10
+je L1423
+mov dword ptr (-8)[ebp],177
+cmp dword ptr (-4)[ebp],0
+je L1425
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1425:
+L1423:
+mov dword ptr (-24)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov eax,dword ptr (-24)[ebp]
+mov edi,dword ptr (-32)[ebp]
+mul edi
+mov dword ptr (-24)[ebp],eax
+mov edi,dword ptr (-24)[ebp]
+cmp edi,10
+je L1427
+mov dword ptr (-8)[ebp],178
+cmp dword ptr (-4)[ebp],0
+je L1429
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1429:
+L1427:
+mov dword ptr (-24)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov eax,dword ptr (-24)[ebp]
+mov edi,dword ptr (-36)[ebp]
+mul edi
+mov dword ptr (-24)[ebp],eax
+mov edi,dword ptr (-24)[ebp]
+cmp edi,10
+je L1431
+mov dword ptr (-8)[ebp],179
+cmp dword ptr (-4)[ebp],0
+je L1433
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1433:
+L1431:
+mov dword ptr (-24)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov eax,dword ptr (-24)[ebp]
+mul dword ptr (-40)[ebp]
+mov dword ptr (-24)[ebp],eax
+mov edi,dword ptr (-24)[ebp]
+cmp edi,10
+je L1435
+mov dword ptr (-8)[ebp],180
+cmp dword ptr (-4)[ebp],0
+je L1437
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1437:
+L1435:
+mov dword ptr (-24)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+mov edi,dword ptr (-24)[ebp]
+fld qword ptr (L596)
+mov esi,edi
+shr esi,1
+push esi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+and edi,1
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+sub esp,4
+fstp dword ptr 0[esp]
+fld dword ptr 0[esp]
+add esp,4
+fmul dword ptr (-56)[ebp]
+fstp dword ptr (-192)[ebp]
+fld dword ptr (L828)
+fcomp dword ptr (-192)[ebp]
+fstsw ax
+sahf
+ja L1440
+fld dword ptr (-192)[ebp]
+fsub dword ptr (L828)
+call __ftol
+mov edi,eax
+lea edi,(080000000H)[edi]
+mov dword ptr (-188)[ebp],edi
+jmp L1441
+L1440:
+fld dword ptr (-192)[ebp]
+call __ftol
+mov edi,eax
+mov dword ptr (-188)[ebp],edi
+L1441:
+mov edi,dword ptr (-188)[ebp]
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,10
+je L1442
+mov dword ptr (-8)[ebp],181
+cmp dword ptr (-4)[ebp],0
+je L1444
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1444:
+L1442:
+mov dword ptr (-24)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+mov edi,dword ptr (-24)[ebp]
+fld qword ptr (L596)
+mov esi,edi
+shr esi,1
+push esi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+and edi,1
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+fmul qword ptr (-64)[ebp]
+fstp qword ptr (-208)[ebp]
+fld qword ptr (L836)
+fcomp qword ptr (-208)[ebp]
+fstsw ax
+sahf
+ja L1447
+fld qword ptr (-208)[ebp]
+fsub qword ptr (L836)
+call __ftol
+mov edi,eax
+lea edi,(080000000H)[edi]
+mov dword ptr (-200)[ebp],edi
+jmp L1448
+L1447:
+fld qword ptr (-208)[ebp]
+call __ftol
+mov edi,eax
+mov dword ptr (-200)[ebp],edi
+L1448:
+mov edi,dword ptr (-200)[ebp]
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,10
+je L1449
+mov dword ptr (-8)[ebp],182
+cmp dword ptr (-4)[ebp],0
+je L1451
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1451:
+L1449:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov byte ptr (-25)[ebp],2
+fld dword ptr (-44)[ebp]
+movsx edi,byte ptr (-25)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L1455)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1453
+mov dword ptr (-8)[ebp],183
+cmp dword ptr (-4)[ebp],0
+je L1456
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1456:
+L1453:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov word ptr (-28)[ebp],2
+fld dword ptr (-44)[ebp]
+movsx edi,word ptr (-28)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L1455)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1458
+mov dword ptr (-8)[ebp],184
+cmp dword ptr (-4)[ebp],0
+je L1460
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1460:
+L1458:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov dword ptr (-32)[ebp],2
+fld dword ptr (-44)[ebp]
+mov edi,dword ptr (-32)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L1455)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1462
+mov dword ptr (-8)[ebp],185
+cmp dword ptr (-4)[ebp],0
+je L1464
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1464:
+L1462:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov dword ptr (-36)[ebp],2
+fld dword ptr (-44)[ebp]
+mov edi,dword ptr (-36)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L1455)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1466
+mov dword ptr (-8)[ebp],186
+cmp dword ptr (-4)[ebp],0
+je L1468
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1468:
+L1466:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-40)[ebp]
+fld dword ptr (-44)[ebp]
+fld qword ptr (L596)
+mov esi,edi
+shr esi,1
+push esi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+and edi,1
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+sub esp,4
+fstp dword ptr 0[esp]
+fld dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L1455)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1470
+mov dword ptr (-8)[ebp],187
+cmp dword ptr (-4)[ebp],0
+je L1472
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1472:
+L1470:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+fld dword ptr (-44)[ebp]
+fmul dword ptr (-56)[ebp]
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L1455)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1474
+mov dword ptr (-8)[ebp],188
+cmp dword ptr (-4)[ebp],0
+je L1476
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1476:
+L1474:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+fld dword ptr (-44)[ebp]
+fmul qword ptr (-64)[ebp]
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L1455)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1478
+mov dword ptr (-8)[ebp],189
+cmp dword ptr (-4)[ebp],0
+je L1480
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1480:
+L1478:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov byte ptr (-25)[ebp],2
+fld qword ptr (-52)[ebp]
+movsx edi,byte ptr (-25)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1484)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1482
+mov dword ptr (-8)[ebp],190
+cmp dword ptr (-4)[ebp],0
+je L1485
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1485:
+L1482:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov word ptr (-28)[ebp],2
+fld qword ptr (-52)[ebp]
+movsx edi,word ptr (-28)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1484)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1487
+mov dword ptr (-8)[ebp],191
+cmp dword ptr (-4)[ebp],0
+je L1489
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1489:
+L1487:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov dword ptr (-32)[ebp],2
+fld qword ptr (-52)[ebp]
+fild dword ptr (-32)[ebp]
+fmulp st(1),st
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1484)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1491
+mov dword ptr (-8)[ebp],192
+cmp dword ptr (-4)[ebp],0
+je L1493
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1493:
+L1491:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov dword ptr (-36)[ebp],2
+fld qword ptr (-52)[ebp]
+fild dword ptr (-36)[ebp]
+fmulp st(1),st
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1484)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1495
+mov dword ptr (-8)[ebp],193
+cmp dword ptr (-4)[ebp],0
+je L1497
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1497:
+L1495:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-40)[ebp]
+fld qword ptr (-52)[ebp]
+fld qword ptr (L596)
+mov esi,edi
+shr esi,1
+push esi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+and edi,1
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+fmulp st(1),st
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1484)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1499
+mov dword ptr (-8)[ebp],194
+cmp dword ptr (-4)[ebp],0
+je L1501
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1501:
+L1499:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+fld qword ptr (-52)[ebp]
+fmul dword ptr (-56)[ebp]
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1484)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1503
+mov dword ptr (-8)[ebp],195
+cmp dword ptr (-4)[ebp],0
+je L1505
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1505:
+L1503:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+fld qword ptr (-52)[ebp]
+fmul qword ptr (-64)[ebp]
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1484)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1507
+mov dword ptr (-8)[ebp],196
+cmp dword ptr (-4)[ebp],0
+je L1509
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1509:
+L1507:
+mov byte ptr (-9)[ebp],5
+mov byte ptr (-25)[ebp],2
+movsx eax,byte ptr (-9)[ebp]
+movsx edi,byte ptr (-25)[ebp]
+cdq
+idiv edi
+mov ebx,eax
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,2
+je L1511
+mov dword ptr (-8)[ebp],197
+cmp dword ptr (-4)[ebp],0
+je L1513
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1513:
+L1511:
+mov byte ptr (-9)[ebp],5
+mov word ptr (-28)[ebp],2
+movsx eax,byte ptr (-9)[ebp]
+movsx edi,word ptr (-28)[ebp]
+cdq
+idiv edi
+mov ebx,eax
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,2
+je L1515
+mov dword ptr (-8)[ebp],198
+cmp dword ptr (-4)[ebp],0
+je L1517
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1517:
+L1515:
+mov byte ptr (-9)[ebp],5
+mov dword ptr (-32)[ebp],2
+movsx eax,byte ptr (-9)[ebp]
+mov edi,dword ptr (-32)[ebp]
+cdq
+idiv edi
+mov ebx,eax
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,2
+je L1519
+mov dword ptr (-8)[ebp],199
+cmp dword ptr (-4)[ebp],0
+je L1521
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1521:
+L1519:
+mov byte ptr (-9)[ebp],5
+mov dword ptr (-36)[ebp],2
+movsx eax,byte ptr (-9)[ebp]
+mov edi,dword ptr (-36)[ebp]
+cdq
+idiv edi
+mov ebx,eax
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,2
+je L1523
+mov dword ptr (-8)[ebp],200
+cmp dword ptr (-4)[ebp],0
+je L1525
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1525:
+L1523:
+mov byte ptr (-9)[ebp],5
+mov dword ptr (-40)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+mov eax,edi
+mov edi,dword ptr (-40)[ebp]
+xor edx,edx
+div edi
+mov edi,eax
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,2
+je L1527
+mov dword ptr (-8)[ebp],201
+cmp dword ptr (-4)[ebp],0
+je L1529
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1529:
+L1527:
+mov byte ptr (-9)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+movsx edi,byte ptr (-9)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fdiv dword ptr (-56)[ebp]
+call __ftol
+mov ebx,eax
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,2
+je L1531
+mov dword ptr (-8)[ebp],202
+cmp dword ptr (-4)[ebp],0
+je L1533
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1533:
+L1531:
+mov byte ptr (-9)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+movsx edi,byte ptr (-9)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fdiv qword ptr (-64)[ebp]
+call __ftol
+mov ebx,eax
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,2
+je L1535
+mov dword ptr (-8)[ebp],203
+cmp dword ptr (-4)[ebp],0
+je L1537
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1537:
+L1535:
+mov word ptr (-12)[ebp],5
+mov byte ptr (-25)[ebp],2
+movsx eax,word ptr (-12)[ebp]
+movsx edi,byte ptr (-25)[ebp]
+cdq
+idiv edi
+mov edi,eax
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,2
+je L1539
+mov dword ptr (-8)[ebp],204
+cmp dword ptr (-4)[ebp],0
+je L1541
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1541:
+L1539:
+mov word ptr (-12)[ebp],5
+mov word ptr (-28)[ebp],2
+movsx eax,word ptr (-12)[ebp]
+movsx edi,word ptr (-28)[ebp]
+cdq
+idiv edi
+mov edi,eax
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,2
+je L1543
+mov dword ptr (-8)[ebp],205
+cmp dword ptr (-4)[ebp],0
+je L1545
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1545:
+L1543:
+mov word ptr (-12)[ebp],5
+mov dword ptr (-32)[ebp],2
+movsx eax,word ptr (-12)[ebp]
+mov edi,dword ptr (-32)[ebp]
+cdq
+idiv edi
+mov edi,eax
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,2
+je L1547
+mov dword ptr (-8)[ebp],206
+cmp dword ptr (-4)[ebp],0
+je L1549
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1549:
+L1547:
+mov word ptr (-12)[ebp],5
+mov dword ptr (-36)[ebp],2
+movsx eax,word ptr (-12)[ebp]
+mov edi,dword ptr (-36)[ebp]
+cdq
+idiv edi
+mov edi,eax
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,2
+je L1551
+mov dword ptr (-8)[ebp],207
+cmp dword ptr (-4)[ebp],0
+je L1553
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1553:
+L1551:
+mov word ptr (-12)[ebp],5
+mov dword ptr (-40)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+mov eax,edi
+mov edi,dword ptr (-40)[ebp]
+xor edx,edx
+div edi
+mov edi,eax
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,2
+je L1555
+mov dword ptr (-8)[ebp],208
+cmp dword ptr (-4)[ebp],0
+je L1557
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1557:
+L1555:
+mov word ptr (-12)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+movsx edi,word ptr (-12)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fdiv dword ptr (-56)[ebp]
+call __ftol
+mov edi,eax
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,2
+je L1559
+mov dword ptr (-8)[ebp],209
+cmp dword ptr (-4)[ebp],0
+je L1561
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1561:
+L1559:
+mov word ptr (-12)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+movsx edi,word ptr (-12)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fdiv qword ptr (-64)[ebp]
+call __ftol
+mov edi,eax
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,2
+je L1563
+mov dword ptr (-8)[ebp],210
+cmp dword ptr (-4)[ebp],0
+je L1565
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1565:
+L1563:
+mov dword ptr (-16)[ebp],5
+mov byte ptr (-25)[ebp],2
+mov eax,dword ptr (-16)[ebp]
+movsx edi,byte ptr (-25)[ebp]
+cdq
+idiv edi
+mov dword ptr (-16)[ebp],eax
+cmp dword ptr (-16)[ebp],2
+je L1567
+mov dword ptr (-8)[ebp],211
+cmp dword ptr (-4)[ebp],0
+je L1569
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1569:
+L1567:
+mov dword ptr (-16)[ebp],5
+mov word ptr (-28)[ebp],2
+mov eax,dword ptr (-16)[ebp]
+movsx edi,word ptr (-28)[ebp]
+cdq
+idiv edi
+mov dword ptr (-16)[ebp],eax
+cmp dword ptr (-16)[ebp],2
+je L1571
+mov dword ptr (-8)[ebp],212
+cmp dword ptr (-4)[ebp],0
+je L1573
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1573:
+L1571:
+mov dword ptr (-16)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov eax,dword ptr (-16)[ebp]
+mov edi,dword ptr (-32)[ebp]
+cdq
+idiv edi
+mov dword ptr (-16)[ebp],eax
+cmp dword ptr (-16)[ebp],2
+je L1575
+mov dword ptr (-8)[ebp],213
+cmp dword ptr (-4)[ebp],0
+je L1577
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1577:
+L1575:
+mov dword ptr (-16)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov eax,dword ptr (-16)[ebp]
+mov edi,dword ptr (-36)[ebp]
+cdq
+idiv edi
+mov dword ptr (-16)[ebp],eax
+cmp dword ptr (-16)[ebp],2
+je L1579
+mov dword ptr (-8)[ebp],214
+cmp dword ptr (-4)[ebp],0
+je L1581
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1581:
+L1579:
+mov dword ptr (-16)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-16)[ebp]
+mov eax,edi
+mov edi,dword ptr (-40)[ebp]
+xor edx,edx
+div edi
+mov edi,eax
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],2
+je L1583
+mov dword ptr (-8)[ebp],215
+cmp dword ptr (-4)[ebp],0
+je L1585
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1585:
+L1583:
+mov dword ptr (-16)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+mov edi,dword ptr (-16)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fdiv dword ptr (-56)[ebp]
+call __ftol
+mov dword ptr (-16)[ebp],eax
+cmp dword ptr (-16)[ebp],2
+je L1587
+mov dword ptr (-8)[ebp],216
+cmp dword ptr (-4)[ebp],0
+je L1589
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1589:
+L1587:
+mov dword ptr (-16)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+fild dword ptr (-16)[ebp]
+fdiv qword ptr (-64)[ebp]
+call __ftol
+mov dword ptr (-16)[ebp],eax
+cmp dword ptr (-16)[ebp],2
+je L1591
+mov dword ptr (-8)[ebp],217
+cmp dword ptr (-4)[ebp],0
+je L1593
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1593:
+L1591:
+mov dword ptr (-20)[ebp],5
+mov byte ptr (-25)[ebp],2
+mov eax,dword ptr (-20)[ebp]
+movsx edi,byte ptr (-25)[ebp]
+cdq
+idiv edi
+mov dword ptr (-20)[ebp],eax
+cmp dword ptr (-20)[ebp],2
+je L1595
+mov dword ptr (-8)[ebp],218
+cmp dword ptr (-4)[ebp],0
+je L1597
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1597:
+L1595:
+mov dword ptr (-20)[ebp],5
+mov word ptr (-28)[ebp],2
+mov eax,dword ptr (-20)[ebp]
+movsx edi,word ptr (-28)[ebp]
+cdq
+idiv edi
+mov dword ptr (-20)[ebp],eax
+cmp dword ptr (-20)[ebp],2
+je L1599
+mov dword ptr (-8)[ebp],219
+cmp dword ptr (-4)[ebp],0
+je L1601
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1601:
+L1599:
+mov dword ptr (-20)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov eax,dword ptr (-20)[ebp]
+mov edi,dword ptr (-32)[ebp]
+cdq
+idiv edi
+mov dword ptr (-20)[ebp],eax
+cmp dword ptr (-20)[ebp],2
+je L1603
+mov dword ptr (-8)[ebp],220
+cmp dword ptr (-4)[ebp],0
+je L1605
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1605:
+L1603:
+mov dword ptr (-20)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov eax,dword ptr (-20)[ebp]
+mov edi,dword ptr (-36)[ebp]
+cdq
+idiv edi
+mov dword ptr (-20)[ebp],eax
+cmp dword ptr (-20)[ebp],2
+je L1607
+mov dword ptr (-8)[ebp],221
+cmp dword ptr (-4)[ebp],0
+je L1609
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1609:
+L1607:
+mov dword ptr (-20)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-20)[ebp]
+mov eax,edi
+mov edi,dword ptr (-40)[ebp]
+xor edx,edx
+div edi
+mov edi,eax
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],2
+je L1611
+mov dword ptr (-8)[ebp],222
+cmp dword ptr (-4)[ebp],0
+je L1613
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1613:
+L1611:
+mov dword ptr (-20)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+mov edi,dword ptr (-20)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fdiv dword ptr (-56)[ebp]
+call __ftol
+mov dword ptr (-20)[ebp],eax
+cmp dword ptr (-20)[ebp],2
+je L1615
+mov dword ptr (-8)[ebp],223
+cmp dword ptr (-4)[ebp],0
+je L1617
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1617:
+L1615:
+mov dword ptr (-20)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+fild dword ptr (-20)[ebp]
+fdiv qword ptr (-64)[ebp]
+call __ftol
+mov dword ptr (-20)[ebp],eax
+cmp dword ptr (-20)[ebp],2
+je L1619
+mov dword ptr (-8)[ebp],224
+cmp dword ptr (-4)[ebp],0
+je L1621
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1621:
+L1619:
+mov dword ptr (-24)[ebp],5
+mov byte ptr (-25)[ebp],2
+mov eax,dword ptr (-24)[ebp]
+movsx edi,byte ptr (-25)[ebp]
+xor edx,edx
+div edi
+mov dword ptr (-24)[ebp],eax
+mov edi,dword ptr (-24)[ebp]
+cmp edi,2
+je L1623
+mov dword ptr (-8)[ebp],225
+cmp dword ptr (-4)[ebp],0
+je L1625
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1625:
+L1623:
+mov dword ptr (-24)[ebp],5
+mov word ptr (-28)[ebp],2
+mov eax,dword ptr (-24)[ebp]
+movsx edi,word ptr (-28)[ebp]
+xor edx,edx
+div edi
+mov dword ptr (-24)[ebp],eax
+mov edi,dword ptr (-24)[ebp]
+cmp edi,2
+je L1627
+mov dword ptr (-8)[ebp],226
+cmp dword ptr (-4)[ebp],0
+je L1629
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1629:
+L1627:
+mov dword ptr (-24)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov eax,dword ptr (-24)[ebp]
+mov edi,dword ptr (-32)[ebp]
+xor edx,edx
+div edi
+mov dword ptr (-24)[ebp],eax
+mov edi,dword ptr (-24)[ebp]
+cmp edi,2
+je L1631
+mov dword ptr (-8)[ebp],227
+cmp dword ptr (-4)[ebp],0
+je L1633
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1633:
+L1631:
+mov dword ptr (-24)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov eax,dword ptr (-24)[ebp]
+mov edi,dword ptr (-36)[ebp]
+xor edx,edx
+div edi
+mov dword ptr (-24)[ebp],eax
+mov edi,dword ptr (-24)[ebp]
+cmp edi,2
+je L1635
+mov dword ptr (-8)[ebp],228
+cmp dword ptr (-4)[ebp],0
+je L1637
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1637:
+L1635:
+mov dword ptr (-24)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov eax,dword ptr (-24)[ebp]
+mov edi,dword ptr (-40)[ebp]
+xor edx,edx
+div edi
+mov dword ptr (-24)[ebp],eax
+mov edi,dword ptr (-24)[ebp]
+cmp edi,2
+je L1639
+mov dword ptr (-8)[ebp],229
+cmp dword ptr (-4)[ebp],0
+je L1641
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1641:
+L1639:
+mov dword ptr (-24)[ebp],5
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+mov edi,dword ptr (-24)[ebp]
+fld qword ptr (L596)
+mov esi,edi
+shr esi,1
+push esi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+and edi,1
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+sub esp,4
+fstp dword ptr 0[esp]
+fld dword ptr 0[esp]
+add esp,4
+fdiv dword ptr (-56)[ebp]
+fstp dword ptr (-224)[ebp]
+fld dword ptr (L828)
+fcomp dword ptr (-224)[ebp]
+fstsw ax
+sahf
+ja L1644
+fld dword ptr (-224)[ebp]
+fsub dword ptr (L828)
+call __ftol
+mov edi,eax
+lea edi,(080000000H)[edi]
+mov dword ptr (-220)[ebp],edi
+jmp L1645
+L1644:
+fld dword ptr (-224)[ebp]
+call __ftol
+mov edi,eax
+mov dword ptr (-220)[ebp],edi
+L1645:
+mov edi,dword ptr (-220)[ebp]
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,2
+je L1646
+mov dword ptr (-8)[ebp],230
+cmp dword ptr (-4)[ebp],0
+je L1648
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1648:
+L1646:
+mov dword ptr (-24)[ebp],5
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+mov edi,dword ptr (-24)[ebp]
+fld qword ptr (L596)
+mov esi,edi
+shr esi,1
+push esi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+and edi,1
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+fdiv qword ptr (-64)[ebp]
+fstp qword ptr (-240)[ebp]
+fld qword ptr (L836)
+fcomp qword ptr (-240)[ebp]
+fstsw ax
+sahf
+ja L1651
+fld qword ptr (-240)[ebp]
+fsub qword ptr (L836)
+call __ftol
+mov edi,eax
+lea edi,(080000000H)[edi]
+mov dword ptr (-232)[ebp],edi
+jmp L1652
+L1651:
+fld qword ptr (-240)[ebp]
+call __ftol
+mov edi,eax
+mov dword ptr (-232)[ebp],edi
+L1652:
+mov edi,dword ptr (-232)[ebp]
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,2
+je L1653
+mov dword ptr (-8)[ebp],231
+cmp dword ptr (-4)[ebp],0
+je L1655
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1655:
+L1653:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov byte ptr (-25)[ebp],2
+fld dword ptr (-44)[ebp]
+movsx edi,byte ptr (-25)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fdivp st(1),st
+fstp dword ptr (-44)[ebp]
+fld qword ptr (L1659)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1657
+mov dword ptr (-8)[ebp],232
+cmp dword ptr (-4)[ebp],0
+je L1660
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1660:
+L1657:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov word ptr (-28)[ebp],2
+fld dword ptr (-44)[ebp]
+movsx edi,word ptr (-28)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fdivp st(1),st
+fstp dword ptr (-44)[ebp]
+fld qword ptr (L1659)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1662
+mov dword ptr (-8)[ebp],233
+cmp dword ptr (-4)[ebp],0
+je L1664
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1664:
+L1662:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov dword ptr (-32)[ebp],2
+fld dword ptr (-44)[ebp]
+mov edi,dword ptr (-32)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fdivp st(1),st
+fstp dword ptr (-44)[ebp]
+fld qword ptr (L1659)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1666
+mov dword ptr (-8)[ebp],234
+cmp dword ptr (-4)[ebp],0
+je L1668
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1668:
+L1666:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov dword ptr (-36)[ebp],2
+fld dword ptr (-44)[ebp]
+mov edi,dword ptr (-36)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fdivp st(1),st
+fstp dword ptr (-44)[ebp]
+fld qword ptr (L1659)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1670
+mov dword ptr (-8)[ebp],235
+cmp dword ptr (-4)[ebp],0
+je L1672
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1672:
+L1670:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-40)[ebp]
+fld dword ptr (-44)[ebp]
+fld qword ptr (L596)
+mov esi,edi
+shr esi,1
+push esi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+and edi,1
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+sub esp,4
+fstp dword ptr 0[esp]
+fld dword ptr 0[esp]
+add esp,4
+fdivp st(1),st
+fstp dword ptr (-44)[ebp]
+fld qword ptr (L1659)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1674
+mov dword ptr (-8)[ebp],236
+cmp dword ptr (-4)[ebp],0
+je L1676
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1676:
+L1674:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+fld dword ptr (-44)[ebp]
+fdiv dword ptr (-56)[ebp]
+fstp dword ptr (-44)[ebp]
+fld qword ptr (L1659)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1678
+mov dword ptr (-8)[ebp],237
+cmp dword ptr (-4)[ebp],0
+je L1680
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1680:
+L1678:
+fld dword ptr (L841)
+fstp dword ptr (-44)[ebp]
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+fld dword ptr (-44)[ebp]
+fdiv qword ptr (-64)[ebp]
+fstp dword ptr (-44)[ebp]
+fld qword ptr (L1659)
+fcomp dword ptr (-44)[ebp]
+fstsw ax
+sahf
+je L1682
+mov dword ptr (-8)[ebp],238
+cmp dword ptr (-4)[ebp],0
+je L1684
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1684:
+L1682:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov byte ptr (-25)[ebp],2
+fld qword ptr (-52)[ebp]
+movsx edi,byte ptr (-25)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fdivp st(1),st
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1659)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1686
+mov dword ptr (-8)[ebp],239
+cmp dword ptr (-4)[ebp],0
+je L1688
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1688:
+L1686:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov word ptr (-28)[ebp],2
+fld qword ptr (-52)[ebp]
+movsx edi,word ptr (-28)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fdivp st(1),st
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1659)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1690
+mov dword ptr (-8)[ebp],240
+cmp dword ptr (-4)[ebp],0
+je L1692
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1692:
+L1690:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov dword ptr (-32)[ebp],2
+fld qword ptr (-52)[ebp]
+fild dword ptr (-32)[ebp]
+fdivp st(1),st
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1659)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1694
+mov dword ptr (-8)[ebp],241
+cmp dword ptr (-4)[ebp],0
+je L1696
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1696:
+L1694:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov dword ptr (-36)[ebp],2
+fld qword ptr (-52)[ebp]
+fild dword ptr (-36)[ebp]
+fdivp st(1),st
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1659)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1698
+mov dword ptr (-8)[ebp],242
+cmp dword ptr (-4)[ebp],0
+je L1700
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1700:
+L1698:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-40)[ebp]
+fld qword ptr (-52)[ebp]
+fld qword ptr (L596)
+mov esi,edi
+shr esi,1
+push esi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+and edi,1
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+fdivp st(1),st
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1659)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1702
+mov dword ptr (-8)[ebp],243
+cmp dword ptr (-4)[ebp],0
+je L1704
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1704:
+L1702:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+fld dword ptr (L529)
+fstp dword ptr (-56)[ebp]
+fld qword ptr (-52)[ebp]
+fdiv dword ptr (-56)[ebp]
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1659)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1706
+mov dword ptr (-8)[ebp],244
+cmp dword ptr (-4)[ebp],0
+je L1708
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1708:
+L1706:
+fld qword ptr (L870)
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L416)
+fstp qword ptr (-64)[ebp]
+fld qword ptr (-52)[ebp]
+fdiv qword ptr (-64)[ebp]
+fstp qword ptr (-52)[ebp]
+fld qword ptr (L1659)
+fcomp qword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L1710
+mov dword ptr (-8)[ebp],245
+cmp dword ptr (-4)[ebp],0
+je L1712
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1712:
+L1710:
+mov byte ptr (-9)[ebp],5
+mov byte ptr (-25)[ebp],2
+movsx eax,byte ptr (-9)[ebp]
+movsx edi,byte ptr (-25)[ebp]
+cdq
+idiv edi
+mov ebx,edx
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,1
+je L1714
+mov dword ptr (-8)[ebp],246
+cmp dword ptr (-4)[ebp],0
+je L1716
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1716:
+L1714:
+mov byte ptr (-9)[ebp],5
+mov word ptr (-28)[ebp],2
+movsx eax,byte ptr (-9)[ebp]
+movsx edi,word ptr (-28)[ebp]
+cdq
+idiv edi
+mov ebx,edx
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,1
+je L1718
+mov dword ptr (-8)[ebp],247
+cmp dword ptr (-4)[ebp],0
+je L1720
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1720:
+L1718:
+mov byte ptr (-9)[ebp],5
+mov dword ptr (-32)[ebp],2
+movsx eax,byte ptr (-9)[ebp]
+mov edi,dword ptr (-32)[ebp]
+cdq
+idiv edi
+mov ebx,edx
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,1
+je L1722
+mov dword ptr (-8)[ebp],248
+cmp dword ptr (-4)[ebp],0
+je L1724
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1724:
+L1722:
+mov byte ptr (-9)[ebp],5
+mov dword ptr (-36)[ebp],2
+movsx eax,byte ptr (-9)[ebp]
+mov edi,dword ptr (-36)[ebp]
+cdq
+idiv edi
+mov ebx,edx
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,1
+je L1726
+mov dword ptr (-8)[ebp],249
+cmp dword ptr (-4)[ebp],0
+je L1728
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1728:
+L1726:
+mov byte ptr (-9)[ebp],5
+mov dword ptr (-40)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+mov eax,edi
+mov edi,dword ptr (-40)[ebp]
+xor edx,edx
+div edi
+mov edi,edx
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,1
+je L1730
+mov dword ptr (-8)[ebp],250
+cmp dword ptr (-4)[ebp],0
+je L1732
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1732:
+L1730:
+mov word ptr (-12)[ebp],5
+mov byte ptr (-25)[ebp],2
+movsx eax,word ptr (-12)[ebp]
+movsx edi,byte ptr (-25)[ebp]
+cdq
+idiv edi
+mov edi,edx
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,1
+je L1734
+mov dword ptr (-8)[ebp],251
+cmp dword ptr (-4)[ebp],0
+je L1736
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1736:
+L1734:
+mov word ptr (-12)[ebp],5
+mov word ptr (-28)[ebp],2
+movsx eax,word ptr (-12)[ebp]
+movsx edi,word ptr (-28)[ebp]
+cdq
+idiv edi
+mov edi,edx
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,1
+je L1738
+mov dword ptr (-8)[ebp],252
+cmp dword ptr (-4)[ebp],0
+je L1740
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1740:
+L1738:
+mov word ptr (-12)[ebp],5
+mov dword ptr (-32)[ebp],2
+movsx eax,word ptr (-12)[ebp]
+mov edi,dword ptr (-32)[ebp]
+cdq
+idiv edi
+mov edi,edx
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,1
+je L1742
+mov dword ptr (-8)[ebp],253
+cmp dword ptr (-4)[ebp],0
+je L1744
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1744:
+L1742:
+mov word ptr (-12)[ebp],5
+mov dword ptr (-36)[ebp],2
+movsx eax,word ptr (-12)[ebp]
+mov edi,dword ptr (-36)[ebp]
+cdq
+idiv edi
+mov edi,edx
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,1
+je L1746
+mov dword ptr (-8)[ebp],254
+cmp dword ptr (-4)[ebp],0
+je L1748
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1748:
+L1746:
+mov word ptr (-12)[ebp],5
+mov dword ptr (-40)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+mov eax,edi
+mov edi,dword ptr (-40)[ebp]
+xor edx,edx
+div edi
+mov edi,edx
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,1
+je L1750
+mov dword ptr (-8)[ebp],255
+cmp dword ptr (-4)[ebp],0
+je L1752
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1752:
+L1750:
+mov dword ptr (-16)[ebp],5
+mov byte ptr (-25)[ebp],2
+mov eax,dword ptr (-16)[ebp]
+movsx edi,byte ptr (-25)[ebp]
+cdq
+idiv edi
+mov dword ptr (-16)[ebp],edx
+cmp dword ptr (-16)[ebp],1
+je L1754
+mov dword ptr (-8)[ebp],256
+cmp dword ptr (-4)[ebp],0
+je L1756
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1756:
+L1754:
+mov dword ptr (-16)[ebp],5
+mov word ptr (-28)[ebp],2
+mov eax,dword ptr (-16)[ebp]
+movsx edi,word ptr (-28)[ebp]
+cdq
+idiv edi
+mov dword ptr (-16)[ebp],edx
+cmp dword ptr (-16)[ebp],1
+je L1758
+mov dword ptr (-8)[ebp],257
+cmp dword ptr (-4)[ebp],0
+je L1760
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1760:
+L1758:
+mov dword ptr (-16)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov eax,dword ptr (-16)[ebp]
+mov edi,dword ptr (-32)[ebp]
+cdq
+idiv edi
+mov dword ptr (-16)[ebp],edx
+cmp dword ptr (-16)[ebp],1
+je L1762
+mov dword ptr (-8)[ebp],258
+cmp dword ptr (-4)[ebp],0
+je L1764
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1764:
+L1762:
+mov dword ptr (-16)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov eax,dword ptr (-16)[ebp]
+mov edi,dword ptr (-36)[ebp]
+cdq
+idiv edi
+mov dword ptr (-16)[ebp],edx
+cmp dword ptr (-16)[ebp],1
+je L1766
+mov dword ptr (-8)[ebp],259
+cmp dword ptr (-4)[ebp],0
+je L1768
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1768:
+L1766:
+mov dword ptr (-16)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-16)[ebp]
+mov eax,edi
+mov edi,dword ptr (-40)[ebp]
+xor edx,edx
+div edi
+mov edi,edx
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],1
+je L1770
+mov dword ptr (-8)[ebp],260
+cmp dword ptr (-4)[ebp],0
+je L1772
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1772:
+L1770:
+mov dword ptr (-20)[ebp],5
+mov byte ptr (-25)[ebp],2
+mov eax,dword ptr (-20)[ebp]
+movsx edi,byte ptr (-25)[ebp]
+cdq
+idiv edi
+mov dword ptr (-20)[ebp],edx
+cmp dword ptr (-20)[ebp],1
+je L1774
+mov dword ptr (-8)[ebp],261
+cmp dword ptr (-4)[ebp],0
+je L1776
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1776:
+L1774:
+mov dword ptr (-20)[ebp],5
+mov word ptr (-28)[ebp],2
+mov eax,dword ptr (-20)[ebp]
+movsx edi,word ptr (-28)[ebp]
+cdq
+idiv edi
+mov dword ptr (-20)[ebp],edx
+cmp dword ptr (-20)[ebp],1
+je L1778
+mov dword ptr (-8)[ebp],262
+cmp dword ptr (-4)[ebp],0
+je L1780
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1780:
+L1778:
+mov dword ptr (-20)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov eax,dword ptr (-20)[ebp]
+mov edi,dword ptr (-32)[ebp]
+cdq
+idiv edi
+mov dword ptr (-20)[ebp],edx
+cmp dword ptr (-20)[ebp],1
+je L1782
+mov dword ptr (-8)[ebp],263
+cmp dword ptr (-4)[ebp],0
+je L1784
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1784:
+L1782:
+mov dword ptr (-20)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov eax,dword ptr (-20)[ebp]
+mov edi,dword ptr (-36)[ebp]
+cdq
+idiv edi
+mov dword ptr (-20)[ebp],edx
+cmp dword ptr (-20)[ebp],1
+je L1786
+mov dword ptr (-8)[ebp],264
+cmp dword ptr (-4)[ebp],0
+je L1788
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1788:
+L1786:
+mov dword ptr (-20)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-20)[ebp]
+mov eax,edi
+mov edi,dword ptr (-40)[ebp]
+xor edx,edx
+div edi
+mov edi,edx
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],1
+je L1790
+mov dword ptr (-8)[ebp],265
+cmp dword ptr (-4)[ebp],0
+je L1792
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1792:
+L1790:
+mov dword ptr (-24)[ebp],5
+mov byte ptr (-25)[ebp],2
+mov eax,dword ptr (-24)[ebp]
+movsx edi,byte ptr (-25)[ebp]
+xor edx,edx
+div edi
+mov dword ptr (-24)[ebp],edx
+mov edi,dword ptr (-24)[ebp]
+cmp edi,1
+je L1794
+mov dword ptr (-8)[ebp],266
+cmp dword ptr (-4)[ebp],0
+je L1796
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1796:
+L1794:
+mov dword ptr (-24)[ebp],5
+mov word ptr (-28)[ebp],2
+mov eax,dword ptr (-24)[ebp]
+movsx edi,word ptr (-28)[ebp]
+xor edx,edx
+div edi
+mov dword ptr (-24)[ebp],edx
+mov edi,dword ptr (-24)[ebp]
+cmp edi,1
+je L1798
+mov dword ptr (-8)[ebp],267
+cmp dword ptr (-4)[ebp],0
+je L1800
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1800:
+L1798:
+mov dword ptr (-24)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov eax,dword ptr (-24)[ebp]
+mov edi,dword ptr (-32)[ebp]
+xor edx,edx
+div edi
+mov dword ptr (-24)[ebp],edx
+mov edi,dword ptr (-24)[ebp]
+cmp edi,1
+je L1802
+mov dword ptr (-8)[ebp],268
+cmp dword ptr (-4)[ebp],0
+je L1804
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1804:
+L1802:
+mov dword ptr (-24)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov eax,dword ptr (-24)[ebp]
+mov edi,dword ptr (-36)[ebp]
+xor edx,edx
+div edi
+mov dword ptr (-24)[ebp],edx
+mov edi,dword ptr (-24)[ebp]
+cmp edi,1
+je L1806
+mov dword ptr (-8)[ebp],269
+cmp dword ptr (-4)[ebp],0
+je L1808
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1808:
+L1806:
+mov dword ptr (-24)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov eax,dword ptr (-24)[ebp]
+mov edi,dword ptr (-40)[ebp]
+xor edx,edx
+div edi
+mov dword ptr (-24)[ebp],edx
+mov edi,dword ptr (-24)[ebp]
+cmp edi,1
+je L1810
+mov dword ptr (-8)[ebp],270
+cmp dword ptr (-4)[ebp],0
+je L1812
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1812:
+L1810:
+mov byte ptr (-9)[ebp],5
+mov byte ptr (-25)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+movsx esi,byte ptr (-25)[ebp]
+mov ecx,esi
+sar edi,cl
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,1
+je L1814
+mov dword ptr (-8)[ebp],271
+cmp dword ptr (-4)[ebp],0
+je L1816
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1816:
+L1814:
+mov byte ptr (-9)[ebp],5
+mov word ptr (-28)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+movsx esi,word ptr (-28)[ebp]
+mov ecx,esi
+sar edi,cl
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,1
+je L1818
+mov dword ptr (-8)[ebp],272
+cmp dword ptr (-4)[ebp],0
+je L1820
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1820:
+L1818:
+mov byte ptr (-9)[ebp],5
+mov dword ptr (-32)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+mov esi,dword ptr (-32)[ebp]
+mov ecx,esi
+sar edi,cl
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,1
+je L1822
+mov dword ptr (-8)[ebp],273
+cmp dword ptr (-4)[ebp],0
+je L1824
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1824:
+L1822:
+mov byte ptr (-9)[ebp],5
+mov dword ptr (-36)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+mov esi,dword ptr (-36)[ebp]
+mov ecx,esi
+sar edi,cl
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,1
+je L1826
+mov dword ptr (-8)[ebp],274
+cmp dword ptr (-4)[ebp],0
+je L1828
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1828:
+L1826:
+mov byte ptr (-9)[ebp],5
+mov dword ptr (-40)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+mov esi,dword ptr (-40)[ebp]
+mov ecx,esi
+sar edi,cl
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,1
+je L1830
+mov dword ptr (-8)[ebp],275
+cmp dword ptr (-4)[ebp],0
+je L1832
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1832:
+L1830:
+mov word ptr (-12)[ebp],5
+mov byte ptr (-25)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+movsx esi,byte ptr (-25)[ebp]
+mov ecx,esi
+sar edi,cl
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,1
+je L1834
+mov dword ptr (-8)[ebp],276
+cmp dword ptr (-4)[ebp],0
+je L1836
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1836:
+L1834:
+mov word ptr (-12)[ebp],5
+mov word ptr (-28)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+movsx esi,word ptr (-28)[ebp]
+mov ecx,esi
+sar edi,cl
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,1
+je L1838
+mov dword ptr (-8)[ebp],277
+cmp dword ptr (-4)[ebp],0
+je L1840
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1840:
+L1838:
+mov word ptr (-12)[ebp],5
+mov dword ptr (-32)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+mov esi,dword ptr (-32)[ebp]
+mov ecx,esi
+sar edi,cl
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,1
+je L1842
+mov dword ptr (-8)[ebp],278
+cmp dword ptr (-4)[ebp],0
+je L1844
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1844:
+L1842:
+mov word ptr (-12)[ebp],5
+mov dword ptr (-36)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+mov esi,dword ptr (-36)[ebp]
+mov ecx,esi
+sar edi,cl
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,1
+je L1846
+mov dword ptr (-8)[ebp],279
+cmp dword ptr (-4)[ebp],0
+je L1848
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1848:
+L1846:
+mov word ptr (-12)[ebp],5
+mov dword ptr (-40)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+mov esi,dword ptr (-40)[ebp]
+mov ecx,esi
+sar edi,cl
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,1
+je L1850
+mov dword ptr (-8)[ebp],280
+cmp dword ptr (-4)[ebp],0
+je L1852
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1852:
+L1850:
+mov dword ptr (-16)[ebp],5
+mov byte ptr (-25)[ebp],2
+mov edi,dword ptr (-16)[ebp]
+movsx esi,byte ptr (-25)[ebp]
+mov ecx,esi
+sar edi,cl
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],1
+je L1854
+mov dword ptr (-8)[ebp],281
+cmp dword ptr (-4)[ebp],0
+je L1856
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1856:
+L1854:
+mov dword ptr (-16)[ebp],5
+mov word ptr (-28)[ebp],2
+mov edi,dword ptr (-16)[ebp]
+movsx esi,word ptr (-28)[ebp]
+mov ecx,esi
+sar edi,cl
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],1
+je L1858
+mov dword ptr (-8)[ebp],282
+cmp dword ptr (-4)[ebp],0
+je L1860
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1860:
+L1858:
+mov dword ptr (-16)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov edi,dword ptr (-16)[ebp]
+mov esi,dword ptr (-32)[ebp]
+mov ecx,esi
+sar edi,cl
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],1
+je L1862
+mov dword ptr (-8)[ebp],283
+cmp dword ptr (-4)[ebp],0
+je L1864
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1864:
+L1862:
+mov dword ptr (-16)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov edi,dword ptr (-16)[ebp]
+mov esi,dword ptr (-36)[ebp]
+mov ecx,esi
+sar edi,cl
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],1
+je L1866
+mov dword ptr (-8)[ebp],284
+cmp dword ptr (-4)[ebp],0
+je L1868
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1868:
+L1866:
+mov dword ptr (-16)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-16)[ebp]
+mov esi,dword ptr (-40)[ebp]
+mov ecx,esi
+sar edi,cl
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],1
+je L1870
+mov dword ptr (-8)[ebp],285
+cmp dword ptr (-4)[ebp],0
+je L1872
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1872:
+L1870:
+mov dword ptr (-20)[ebp],5
+mov byte ptr (-25)[ebp],2
+mov edi,dword ptr (-20)[ebp]
+movsx esi,byte ptr (-25)[ebp]
+mov ecx,esi
+sar edi,cl
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],1
+je L1874
+mov dword ptr (-8)[ebp],286
+cmp dword ptr (-4)[ebp],0
+je L1876
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1876:
+L1874:
+mov dword ptr (-20)[ebp],5
+mov word ptr (-28)[ebp],2
+mov edi,dword ptr (-20)[ebp]
+movsx esi,word ptr (-28)[ebp]
+mov ecx,esi
+sar edi,cl
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],1
+je L1878
+mov dword ptr (-8)[ebp],287
+cmp dword ptr (-4)[ebp],0
+je L1880
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1880:
+L1878:
+mov dword ptr (-20)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov edi,dword ptr (-20)[ebp]
+mov esi,dword ptr (-32)[ebp]
+mov ecx,esi
+sar edi,cl
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],1
+je L1882
+mov dword ptr (-8)[ebp],288
+cmp dword ptr (-4)[ebp],0
+je L1884
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1884:
+L1882:
+mov dword ptr (-20)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov edi,dword ptr (-20)[ebp]
+mov esi,dword ptr (-36)[ebp]
+mov ecx,esi
+sar edi,cl
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],1
+je L1886
+mov dword ptr (-8)[ebp],289
+cmp dword ptr (-4)[ebp],0
+je L1888
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1888:
+L1886:
+mov dword ptr (-20)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-20)[ebp]
+mov esi,dword ptr (-40)[ebp]
+mov ecx,esi
+sar edi,cl
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],1
+je L1890
+mov dword ptr (-8)[ebp],290
+cmp dword ptr (-4)[ebp],0
+je L1892
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1892:
+L1890:
+mov dword ptr (-24)[ebp],5
+mov byte ptr (-25)[ebp],2
+mov edi,dword ptr (-24)[ebp]
+movsx esi,byte ptr (-25)[ebp]
+mov ecx,esi
+shr edi,cl
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,1
+je L1894
+mov dword ptr (-8)[ebp],291
+cmp dword ptr (-4)[ebp],0
+je L1896
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1896:
+L1894:
+mov dword ptr (-24)[ebp],5
+mov word ptr (-28)[ebp],2
+mov edi,dword ptr (-24)[ebp]
+movsx esi,word ptr (-28)[ebp]
+mov ecx,esi
+shr edi,cl
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,1
+je L1898
+mov dword ptr (-8)[ebp],292
+cmp dword ptr (-4)[ebp],0
+je L1900
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1900:
+L1898:
+mov dword ptr (-24)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov edi,dword ptr (-24)[ebp]
+mov esi,dword ptr (-32)[ebp]
+mov ecx,esi
+shr edi,cl
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,1
+je L1902
+mov dword ptr (-8)[ebp],293
+cmp dword ptr (-4)[ebp],0
+je L1904
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1904:
+L1902:
+mov dword ptr (-24)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov edi,dword ptr (-24)[ebp]
+mov esi,dword ptr (-36)[ebp]
+mov ecx,esi
+shr edi,cl
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,1
+je L1906
+mov dword ptr (-8)[ebp],294
+cmp dword ptr (-4)[ebp],0
+je L1908
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1908:
+L1906:
+mov dword ptr (-24)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-24)[ebp]
+mov esi,dword ptr (-40)[ebp]
+mov ecx,esi
+shr edi,cl
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,1
+je L1910
+mov dword ptr (-8)[ebp],295
+cmp dword ptr (-4)[ebp],0
+je L1912
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1912:
+L1910:
+mov byte ptr (-9)[ebp],5
+mov byte ptr (-25)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+movsx esi,byte ptr (-25)[ebp]
+mov ecx,esi
+sal edi,cl
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,20
+je L1914
+mov dword ptr (-8)[ebp],296
+cmp dword ptr (-4)[ebp],0
+je L1916
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1916:
+L1914:
+mov byte ptr (-9)[ebp],5
+mov word ptr (-28)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+movsx esi,word ptr (-28)[ebp]
+mov ecx,esi
+sal edi,cl
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,20
+je L1918
+mov dword ptr (-8)[ebp],297
+cmp dword ptr (-4)[ebp],0
+je L1920
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1920:
+L1918:
+mov byte ptr (-9)[ebp],5
+mov dword ptr (-32)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+mov esi,dword ptr (-32)[ebp]
+mov ecx,esi
+sal edi,cl
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,20
+je L1922
+mov dword ptr (-8)[ebp],298
+cmp dword ptr (-4)[ebp],0
+je L1924
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1924:
+L1922:
+mov byte ptr (-9)[ebp],5
+mov dword ptr (-36)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+mov esi,dword ptr (-36)[ebp]
+mov ecx,esi
+sal edi,cl
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,20
+je L1926
+mov dword ptr (-8)[ebp],299
+cmp dword ptr (-4)[ebp],0
+je L1928
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1928:
+L1926:
+mov byte ptr (-9)[ebp],5
+mov dword ptr (-40)[ebp],2
+movsx edi,byte ptr (-9)[ebp]
+mov esi,dword ptr (-40)[ebp]
+mov ecx,esi
+sal edi,cl
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,20
+je L1930
+mov dword ptr (-8)[ebp],300
+cmp dword ptr (-4)[ebp],0
+je L1932
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1932:
+L1930:
+mov word ptr (-12)[ebp],5
+mov byte ptr (-25)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+movsx esi,byte ptr (-25)[ebp]
+mov ecx,esi
+sal edi,cl
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,20
+je L1934
+mov dword ptr (-8)[ebp],301
+cmp dword ptr (-4)[ebp],0
+je L1936
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1936:
+L1934:
+mov word ptr (-12)[ebp],5
+mov word ptr (-28)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+movsx esi,word ptr (-28)[ebp]
+mov ecx,esi
+sal edi,cl
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,20
+je L1938
+mov dword ptr (-8)[ebp],302
+cmp dword ptr (-4)[ebp],0
+je L1940
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1940:
+L1938:
+mov word ptr (-12)[ebp],5
+mov dword ptr (-32)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+mov esi,dword ptr (-32)[ebp]
+mov ecx,esi
+sal edi,cl
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,20
+je L1942
+mov dword ptr (-8)[ebp],303
+cmp dword ptr (-4)[ebp],0
+je L1944
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1944:
+L1942:
+mov word ptr (-12)[ebp],5
+mov dword ptr (-36)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+mov esi,dword ptr (-36)[ebp]
+mov ecx,esi
+sal edi,cl
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,20
+je L1946
+mov dword ptr (-8)[ebp],304
+cmp dword ptr (-4)[ebp],0
+je L1948
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1948:
+L1946:
+mov word ptr (-12)[ebp],5
+mov dword ptr (-40)[ebp],2
+movsx edi,word ptr (-12)[ebp]
+mov esi,dword ptr (-40)[ebp]
+mov ecx,esi
+sal edi,cl
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,20
+je L1950
+mov dword ptr (-8)[ebp],305
+cmp dword ptr (-4)[ebp],0
+je L1952
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1952:
+L1950:
+mov dword ptr (-16)[ebp],5
+mov byte ptr (-25)[ebp],2
+mov edi,dword ptr (-16)[ebp]
+movsx esi,byte ptr (-25)[ebp]
+mov ecx,esi
+sal edi,cl
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],20
+je L1954
+mov dword ptr (-8)[ebp],306
+cmp dword ptr (-4)[ebp],0
+je L1956
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1956:
+L1954:
+mov dword ptr (-16)[ebp],5
+mov word ptr (-28)[ebp],2
+mov edi,dword ptr (-16)[ebp]
+movsx esi,word ptr (-28)[ebp]
+mov ecx,esi
+sal edi,cl
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],20
+je L1958
+mov dword ptr (-8)[ebp],307
+cmp dword ptr (-4)[ebp],0
+je L1960
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1960:
+L1958:
+mov dword ptr (-16)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov edi,dword ptr (-16)[ebp]
+mov esi,dword ptr (-32)[ebp]
+mov ecx,esi
+sal edi,cl
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],20
+je L1962
+mov dword ptr (-8)[ebp],308
+cmp dword ptr (-4)[ebp],0
+je L1964
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1964:
+L1962:
+mov dword ptr (-16)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov edi,dword ptr (-16)[ebp]
+mov esi,dword ptr (-36)[ebp]
+mov ecx,esi
+sal edi,cl
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],20
+je L1966
+mov dword ptr (-8)[ebp],309
+cmp dword ptr (-4)[ebp],0
+je L1968
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1968:
+L1966:
+mov dword ptr (-16)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-16)[ebp]
+mov esi,dword ptr (-40)[ebp]
+mov ecx,esi
+sal edi,cl
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],20
+je L1970
+mov dword ptr (-8)[ebp],310
+cmp dword ptr (-4)[ebp],0
+je L1972
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1972:
+L1970:
+mov dword ptr (-20)[ebp],5
+mov byte ptr (-25)[ebp],2
+mov edi,dword ptr (-20)[ebp]
+movsx esi,byte ptr (-25)[ebp]
+mov ecx,esi
+sal edi,cl
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],20
+je L1974
+mov dword ptr (-8)[ebp],311
+cmp dword ptr (-4)[ebp],0
+je L1976
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1976:
+L1974:
+mov dword ptr (-20)[ebp],5
+mov word ptr (-28)[ebp],2
+mov edi,dword ptr (-20)[ebp]
+movsx esi,word ptr (-28)[ebp]
+mov ecx,esi
+sal edi,cl
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],20
+je L1978
+mov dword ptr (-8)[ebp],312
+cmp dword ptr (-4)[ebp],0
+je L1980
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1980:
+L1978:
+mov dword ptr (-20)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov edi,dword ptr (-20)[ebp]
+mov esi,dword ptr (-32)[ebp]
+mov ecx,esi
+sal edi,cl
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],20
+je L1982
+mov dword ptr (-8)[ebp],313
+cmp dword ptr (-4)[ebp],0
+je L1984
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1984:
+L1982:
+mov dword ptr (-20)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov edi,dword ptr (-20)[ebp]
+mov esi,dword ptr (-36)[ebp]
+mov ecx,esi
+sal edi,cl
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],20
+je L1986
+mov dword ptr (-8)[ebp],314
+cmp dword ptr (-4)[ebp],0
+je L1988
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1988:
+L1986:
+mov dword ptr (-20)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-20)[ebp]
+mov esi,dword ptr (-40)[ebp]
+mov ecx,esi
+sal edi,cl
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],20
+je L1990
+mov dword ptr (-8)[ebp],315
+cmp dword ptr (-4)[ebp],0
+je L1992
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1992:
+L1990:
+mov dword ptr (-24)[ebp],5
+mov byte ptr (-25)[ebp],2
+mov edi,dword ptr (-24)[ebp]
+movsx esi,byte ptr (-25)[ebp]
+mov ecx,esi
+shl edi,cl
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,20
+je L1994
+mov dword ptr (-8)[ebp],316
+cmp dword ptr (-4)[ebp],0
+je L1996
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L1996:
+L1994:
+mov dword ptr (-24)[ebp],5
+mov word ptr (-28)[ebp],2
+mov edi,dword ptr (-24)[ebp]
+movsx esi,word ptr (-28)[ebp]
+mov ecx,esi
+shl edi,cl
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,20
+je L1998
+mov dword ptr (-8)[ebp],317
+cmp dword ptr (-4)[ebp],0
+je L2000
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2000:
+L1998:
+mov dword ptr (-24)[ebp],5
+mov dword ptr (-32)[ebp],2
+mov edi,dword ptr (-24)[ebp]
+mov esi,dword ptr (-32)[ebp]
+mov ecx,esi
+shl edi,cl
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,20
+je L2002
+mov dword ptr (-8)[ebp],318
+cmp dword ptr (-4)[ebp],0
+je L2004
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2004:
+L2002:
+mov dword ptr (-24)[ebp],5
+mov dword ptr (-36)[ebp],2
+mov edi,dword ptr (-24)[ebp]
+mov esi,dword ptr (-36)[ebp]
+mov ecx,esi
+shl edi,cl
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,20
+je L2006
+mov dword ptr (-8)[ebp],319
+cmp dword ptr (-4)[ebp],0
+je L2008
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2008:
+L2006:
+mov dword ptr (-24)[ebp],5
+mov dword ptr (-40)[ebp],2
+mov edi,dword ptr (-24)[ebp]
+mov esi,dword ptr (-40)[ebp]
+mov ecx,esi
+shl edi,cl
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,20
+je L2010
+mov dword ptr (-8)[ebp],320
+cmp dword ptr (-4)[ebp],0
+je L2012
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2012:
+L2010:
+mov byte ptr (-9)[ebp],12
+mov byte ptr (-25)[ebp],10
+movsx edi,byte ptr (-9)[ebp]
+movsx esi,byte ptr (-25)[ebp]
+and edi,esi
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,8
+je L2014
+mov dword ptr (-8)[ebp],321
+cmp dword ptr (-4)[ebp],0
+je L2016
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2016:
+L2014:
+mov byte ptr (-9)[ebp],12
+mov word ptr (-28)[ebp],10
+movsx edi,byte ptr (-9)[ebp]
+movsx esi,word ptr (-28)[ebp]
+and edi,esi
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,8
+je L2018
+mov dword ptr (-8)[ebp],322
+cmp dword ptr (-4)[ebp],0
+je L2020
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2020:
+L2018:
+mov byte ptr (-9)[ebp],12
+mov dword ptr (-32)[ebp],10
+movsx edi,byte ptr (-9)[ebp]
+and edi,dword ptr (-32)[ebp]
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,8
+je L2022
+mov dword ptr (-8)[ebp],323
+cmp dword ptr (-4)[ebp],0
+je L2024
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2024:
+L2022:
+mov byte ptr (-9)[ebp],12
+mov dword ptr (-36)[ebp],10
+movsx edi,byte ptr (-9)[ebp]
+and edi,dword ptr (-36)[ebp]
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,8
+je L2026
+mov dword ptr (-8)[ebp],324
+cmp dword ptr (-4)[ebp],0
+je L2028
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2028:
+L2026:
+mov byte ptr (-9)[ebp],12
+mov dword ptr (-40)[ebp],10
+movsx edi,byte ptr (-9)[ebp]
+and edi,dword ptr (-40)[ebp]
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,8
+je L2030
+mov dword ptr (-8)[ebp],325
+cmp dword ptr (-4)[ebp],0
+je L2032
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2032:
+L2030:
+mov word ptr (-12)[ebp],12
+mov byte ptr (-25)[ebp],10
+movsx edi,word ptr (-12)[ebp]
+movsx esi,byte ptr (-25)[ebp]
+and edi,esi
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,8
+je L2034
+mov dword ptr (-8)[ebp],326
+cmp dword ptr (-4)[ebp],0
+je L2036
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2036:
+L2034:
+mov word ptr (-12)[ebp],12
+mov word ptr (-28)[ebp],10
+movsx edi,word ptr (-12)[ebp]
+movsx esi,word ptr (-28)[ebp]
+and edi,esi
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,8
+je L2038
+mov dword ptr (-8)[ebp],327
+cmp dword ptr (-4)[ebp],0
+je L2040
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2040:
+L2038:
+mov word ptr (-12)[ebp],12
+mov dword ptr (-32)[ebp],10
+movsx edi,word ptr (-12)[ebp]
+and edi,dword ptr (-32)[ebp]
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,8
+je L2042
+mov dword ptr (-8)[ebp],328
+cmp dword ptr (-4)[ebp],0
+je L2044
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2044:
+L2042:
+mov word ptr (-12)[ebp],12
+mov dword ptr (-36)[ebp],10
+movsx edi,word ptr (-12)[ebp]
+and edi,dword ptr (-36)[ebp]
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,8
+je L2046
+mov dword ptr (-8)[ebp],329
+cmp dword ptr (-4)[ebp],0
+je L2048
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2048:
+L2046:
+mov word ptr (-12)[ebp],12
+mov dword ptr (-40)[ebp],10
+movsx edi,word ptr (-12)[ebp]
+and edi,dword ptr (-40)[ebp]
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,8
+je L2050
+mov dword ptr (-8)[ebp],330
+cmp dword ptr (-4)[ebp],0
+je L2052
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2052:
+L2050:
+mov dword ptr (-16)[ebp],12
+mov byte ptr (-25)[ebp],10
+movsx edi,byte ptr (-25)[ebp]
+and dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],8
+je L2054
+mov dword ptr (-8)[ebp],331
+cmp dword ptr (-4)[ebp],0
+je L2056
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2056:
+L2054:
+mov dword ptr (-16)[ebp],12
+mov word ptr (-28)[ebp],10
+movsx edi,word ptr (-28)[ebp]
+and dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],8
+je L2058
+mov dword ptr (-8)[ebp],332
+cmp dword ptr (-4)[ebp],0
+je L2060
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2060:
+L2058:
+mov dword ptr (-16)[ebp],12
+mov dword ptr (-32)[ebp],10
+mov edi,dword ptr (-32)[ebp]
+and dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],8
+je L2062
+mov dword ptr (-8)[ebp],333
+cmp dword ptr (-4)[ebp],0
+je L2064
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2064:
+L2062:
+mov dword ptr (-16)[ebp],12
+mov dword ptr (-36)[ebp],10
+mov edi,dword ptr (-36)[ebp]
+and dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],8
+je L2066
+mov dword ptr (-8)[ebp],334
+cmp dword ptr (-4)[ebp],0
+je L2068
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2068:
+L2066:
+mov dword ptr (-16)[ebp],12
+mov dword ptr (-40)[ebp],10
+mov edi,dword ptr (-16)[ebp]
+and edi,dword ptr (-40)[ebp]
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],8
+je L2070
+mov dword ptr (-8)[ebp],335
+cmp dword ptr (-4)[ebp],0
+je L2072
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2072:
+L2070:
+mov dword ptr (-20)[ebp],12
+mov byte ptr (-25)[ebp],10
+movsx edi,byte ptr (-25)[ebp]
+and dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],8
+je L2074
+mov dword ptr (-8)[ebp],336
+cmp dword ptr (-4)[ebp],0
+je L2076
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2076:
+L2074:
+mov dword ptr (-20)[ebp],12
+mov word ptr (-28)[ebp],10
+movsx edi,word ptr (-28)[ebp]
+and dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],8
+je L2078
+mov dword ptr (-8)[ebp],337
+cmp dword ptr (-4)[ebp],0
+je L2080
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2080:
+L2078:
+mov dword ptr (-20)[ebp],12
+mov dword ptr (-32)[ebp],10
+mov edi,dword ptr (-32)[ebp]
+and dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],8
+je L2082
+mov dword ptr (-8)[ebp],338
+cmp dword ptr (-4)[ebp],0
+je L2084
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2084:
+L2082:
+mov dword ptr (-20)[ebp],12
+mov dword ptr (-36)[ebp],10
+mov edi,dword ptr (-36)[ebp]
+and dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],8
+je L2086
+mov dword ptr (-8)[ebp],339
+cmp dword ptr (-4)[ebp],0
+je L2088
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2088:
+L2086:
+mov dword ptr (-20)[ebp],12
+mov dword ptr (-40)[ebp],10
+mov edi,dword ptr (-20)[ebp]
+and edi,dword ptr (-40)[ebp]
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],8
+je L2090
+mov dword ptr (-8)[ebp],340
+cmp dword ptr (-4)[ebp],0
+je L2092
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2092:
+L2090:
+mov dword ptr (-24)[ebp],12
+mov byte ptr (-25)[ebp],10
+movsx edi,byte ptr (-25)[ebp]
+and dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,8
+je L2094
+mov dword ptr (-8)[ebp],341
+cmp dword ptr (-4)[ebp],0
+je L2096
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2096:
+L2094:
+mov dword ptr (-24)[ebp],12
+mov word ptr (-28)[ebp],10
+movsx edi,word ptr (-28)[ebp]
+and dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,8
+je L2098
+mov dword ptr (-8)[ebp],342
+cmp dword ptr (-4)[ebp],0
+je L2100
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2100:
+L2098:
+mov dword ptr (-24)[ebp],12
+mov dword ptr (-32)[ebp],10
+mov edi,dword ptr (-32)[ebp]
+and dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,8
+je L2102
+mov dword ptr (-8)[ebp],343
+cmp dword ptr (-4)[ebp],0
+je L2104
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2104:
+L2102:
+mov dword ptr (-24)[ebp],12
+mov dword ptr (-36)[ebp],10
+mov edi,dword ptr (-36)[ebp]
+and dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,8
+je L2106
+mov dword ptr (-8)[ebp],344
+cmp dword ptr (-4)[ebp],0
+je L2108
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2108:
+L2106:
+mov dword ptr (-24)[ebp],12
+mov dword ptr (-40)[ebp],10
+mov edi,dword ptr (-40)[ebp]
+and dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,8
+je L2110
+mov dword ptr (-8)[ebp],345
+cmp dword ptr (-4)[ebp],0
+je L2112
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2112:
+L2110:
+mov byte ptr (-9)[ebp],12
+mov byte ptr (-25)[ebp],10
+movsx edi,byte ptr (-9)[ebp]
+movsx esi,byte ptr (-25)[ebp]
+xor edi,esi
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,6
+je L2114
+mov dword ptr (-8)[ebp],346
+cmp dword ptr (-4)[ebp],0
+je L2116
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2116:
+L2114:
+mov byte ptr (-9)[ebp],12
+mov word ptr (-28)[ebp],10
+movsx edi,byte ptr (-9)[ebp]
+movsx esi,word ptr (-28)[ebp]
+xor edi,esi
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,6
+je L2118
+mov dword ptr (-8)[ebp],347
+cmp dword ptr (-4)[ebp],0
+je L2120
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2120:
+L2118:
+mov byte ptr (-9)[ebp],12
+mov dword ptr (-32)[ebp],10
+movsx edi,byte ptr (-9)[ebp]
+xor edi,dword ptr (-32)[ebp]
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,6
+je L2122
+mov dword ptr (-8)[ebp],348
+cmp dword ptr (-4)[ebp],0
+je L2124
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2124:
+L2122:
+mov byte ptr (-9)[ebp],12
+mov dword ptr (-36)[ebp],10
+movsx edi,byte ptr (-9)[ebp]
+xor edi,dword ptr (-36)[ebp]
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,6
+je L2126
+mov dword ptr (-8)[ebp],349
+cmp dword ptr (-4)[ebp],0
+je L2128
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2128:
+L2126:
+mov byte ptr (-9)[ebp],12
+mov dword ptr (-40)[ebp],10
+movsx edi,byte ptr (-9)[ebp]
+xor edi,dword ptr (-40)[ebp]
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,6
+je L2130
+mov dword ptr (-8)[ebp],350
+cmp dword ptr (-4)[ebp],0
+je L2132
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2132:
+L2130:
+mov word ptr (-12)[ebp],12
+mov byte ptr (-25)[ebp],10
+movsx edi,word ptr (-12)[ebp]
+movsx esi,byte ptr (-25)[ebp]
+xor edi,esi
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,6
+je L2134
+mov dword ptr (-8)[ebp],351
+cmp dword ptr (-4)[ebp],0
+je L2136
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2136:
+L2134:
+mov word ptr (-12)[ebp],12
+mov word ptr (-28)[ebp],10
+movsx edi,word ptr (-12)[ebp]
+movsx esi,word ptr (-28)[ebp]
+xor edi,esi
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,6
+je L2138
+mov dword ptr (-8)[ebp],352
+cmp dword ptr (-4)[ebp],0
+je L2140
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2140:
+L2138:
+mov word ptr (-12)[ebp],12
+mov dword ptr (-32)[ebp],10
+movsx edi,word ptr (-12)[ebp]
+xor edi,dword ptr (-32)[ebp]
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,6
+je L2142
+mov dword ptr (-8)[ebp],353
+cmp dword ptr (-4)[ebp],0
+je L2144
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2144:
+L2142:
+mov word ptr (-12)[ebp],12
+mov dword ptr (-36)[ebp],10
+movsx edi,word ptr (-12)[ebp]
+xor edi,dword ptr (-36)[ebp]
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,6
+je L2146
+mov dword ptr (-8)[ebp],354
+cmp dword ptr (-4)[ebp],0
+je L2148
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2148:
+L2146:
+mov word ptr (-12)[ebp],12
+mov dword ptr (-40)[ebp],10
+movsx edi,word ptr (-12)[ebp]
+xor edi,dword ptr (-40)[ebp]
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,6
+je L2150
+mov dword ptr (-8)[ebp],355
+cmp dword ptr (-4)[ebp],0
+je L2152
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2152:
+L2150:
+mov dword ptr (-16)[ebp],12
+mov byte ptr (-25)[ebp],10
+movsx edi,byte ptr (-25)[ebp]
+xor dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],6
+je L2154
+mov dword ptr (-8)[ebp],356
+cmp dword ptr (-4)[ebp],0
+je L2156
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2156:
+L2154:
+mov dword ptr (-16)[ebp],12
+mov word ptr (-28)[ebp],10
+movsx edi,word ptr (-28)[ebp]
+xor dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],6
+je L2158
+mov dword ptr (-8)[ebp],357
+cmp dword ptr (-4)[ebp],0
+je L2160
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2160:
+L2158:
+mov dword ptr (-16)[ebp],12
+mov dword ptr (-32)[ebp],10
+mov edi,dword ptr (-32)[ebp]
+xor dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],6
+je L2162
+mov dword ptr (-8)[ebp],358
+cmp dword ptr (-4)[ebp],0
+je L2164
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2164:
+L2162:
+mov dword ptr (-16)[ebp],12
+mov dword ptr (-36)[ebp],10
+mov edi,dword ptr (-36)[ebp]
+xor dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],6
+je L2166
+mov dword ptr (-8)[ebp],359
+cmp dword ptr (-4)[ebp],0
+je L2168
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2168:
+L2166:
+mov dword ptr (-16)[ebp],12
+mov dword ptr (-40)[ebp],10
+mov edi,dword ptr (-16)[ebp]
+xor edi,dword ptr (-40)[ebp]
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],6
+je L2170
+mov dword ptr (-8)[ebp],360
+cmp dword ptr (-4)[ebp],0
+je L2172
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2172:
+L2170:
+mov dword ptr (-20)[ebp],12
+mov byte ptr (-25)[ebp],10
+movsx edi,byte ptr (-25)[ebp]
+xor dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],6
+je L2174
+mov dword ptr (-8)[ebp],361
+cmp dword ptr (-4)[ebp],0
+je L2176
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2176:
+L2174:
+mov dword ptr (-20)[ebp],12
+mov word ptr (-28)[ebp],10
+movsx edi,word ptr (-28)[ebp]
+xor dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],6
+je L2178
+mov dword ptr (-8)[ebp],362
+cmp dword ptr (-4)[ebp],0
+je L2180
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2180:
+L2178:
+mov dword ptr (-20)[ebp],12
+mov dword ptr (-32)[ebp],10
+mov edi,dword ptr (-32)[ebp]
+xor dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],6
+je L2182
+mov dword ptr (-8)[ebp],363
+cmp dword ptr (-4)[ebp],0
+je L2184
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2184:
+L2182:
+mov dword ptr (-20)[ebp],12
+mov dword ptr (-36)[ebp],10
+mov edi,dword ptr (-36)[ebp]
+xor dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],6
+je L2186
+mov dword ptr (-8)[ebp],364
+cmp dword ptr (-4)[ebp],0
+je L2188
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2188:
+L2186:
+mov dword ptr (-20)[ebp],12
+mov dword ptr (-40)[ebp],10
+mov edi,dword ptr (-20)[ebp]
+xor edi,dword ptr (-40)[ebp]
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],6
+je L2190
+mov dword ptr (-8)[ebp],365
+cmp dword ptr (-4)[ebp],0
+je L2192
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2192:
+L2190:
+mov dword ptr (-24)[ebp],12
+mov byte ptr (-25)[ebp],10
+movsx edi,byte ptr (-25)[ebp]
+xor dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,6
+je L2194
+mov dword ptr (-8)[ebp],366
+cmp dword ptr (-4)[ebp],0
+je L2196
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2196:
+L2194:
+mov dword ptr (-24)[ebp],12
+mov word ptr (-28)[ebp],10
+movsx edi,word ptr (-28)[ebp]
+xor dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,6
+je L2198
+mov dword ptr (-8)[ebp],367
+cmp dword ptr (-4)[ebp],0
+je L2200
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2200:
+L2198:
+mov dword ptr (-24)[ebp],12
+mov dword ptr (-32)[ebp],10
+mov edi,dword ptr (-32)[ebp]
+xor dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,6
+je L2202
+mov dword ptr (-8)[ebp],368
+cmp dword ptr (-4)[ebp],0
+je L2204
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2204:
+L2202:
+mov dword ptr (-24)[ebp],12
+mov dword ptr (-36)[ebp],10
+mov edi,dword ptr (-36)[ebp]
+xor dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,6
+je L2206
+mov dword ptr (-8)[ebp],369
+cmp dword ptr (-4)[ebp],0
+je L2208
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2208:
+L2206:
+mov dword ptr (-24)[ebp],12
+mov dword ptr (-40)[ebp],10
+mov edi,dword ptr (-40)[ebp]
+xor dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,6
+je L2210
+mov dword ptr (-8)[ebp],370
+cmp dword ptr (-4)[ebp],0
+je L2212
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2212:
+L2210:
+mov byte ptr (-9)[ebp],12
+mov byte ptr (-25)[ebp],10
+movsx edi,byte ptr (-9)[ebp]
+movsx esi,byte ptr (-25)[ebp]
+or edi,esi
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,14
+je L2214
+mov dword ptr (-8)[ebp],371
+cmp dword ptr (-4)[ebp],0
+je L2216
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2216:
+L2214:
+mov byte ptr (-9)[ebp],12
+mov word ptr (-28)[ebp],10
+movsx edi,byte ptr (-9)[ebp]
+movsx esi,word ptr (-28)[ebp]
+or edi,esi
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,14
+je L2218
+mov dword ptr (-8)[ebp],372
+cmp dword ptr (-4)[ebp],0
+je L2220
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2220:
+L2218:
+mov byte ptr (-9)[ebp],12
+mov dword ptr (-32)[ebp],10
+movsx edi,byte ptr (-9)[ebp]
+or edi,dword ptr (-32)[ebp]
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,14
+je L2222
+mov dword ptr (-8)[ebp],373
+cmp dword ptr (-4)[ebp],0
+je L2224
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2224:
+L2222:
+mov byte ptr (-9)[ebp],12
+mov dword ptr (-36)[ebp],10
+movsx edi,byte ptr (-9)[ebp]
+or edi,dword ptr (-36)[ebp]
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,14
+je L2226
+mov dword ptr (-8)[ebp],374
+cmp dword ptr (-4)[ebp],0
+je L2228
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2228:
+L2226:
+mov byte ptr (-9)[ebp],12
+mov dword ptr (-40)[ebp],10
+movsx edi,byte ptr (-9)[ebp]
+or edi,dword ptr (-40)[ebp]
+mov ebx,edi
+mov byte ptr (-9)[ebp],bl
+movsx edi,byte ptr (-9)[ebp]
+cmp edi,14
+je L2230
+mov dword ptr (-8)[ebp],375
+cmp dword ptr (-4)[ebp],0
+je L2232
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2232:
+L2230:
+mov word ptr (-12)[ebp],12
+mov byte ptr (-25)[ebp],10
+movsx edi,word ptr (-12)[ebp]
+movsx esi,byte ptr (-25)[ebp]
+or edi,esi
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,14
+je L2234
+mov dword ptr (-8)[ebp],376
+cmp dword ptr (-4)[ebp],0
+je L2236
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2236:
+L2234:
+mov word ptr (-12)[ebp],12
+mov word ptr (-28)[ebp],10
+movsx edi,word ptr (-12)[ebp]
+movsx esi,word ptr (-28)[ebp]
+or edi,esi
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,14
+je L2238
+mov dword ptr (-8)[ebp],377
+cmp dword ptr (-4)[ebp],0
+je L2240
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2240:
+L2238:
+mov word ptr (-12)[ebp],12
+mov dword ptr (-32)[ebp],10
+movsx edi,word ptr (-12)[ebp]
+or edi,dword ptr (-32)[ebp]
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,14
+je L2242
+mov dword ptr (-8)[ebp],378
+cmp dword ptr (-4)[ebp],0
+je L2244
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2244:
+L2242:
+mov word ptr (-12)[ebp],12
+mov dword ptr (-36)[ebp],10
+movsx edi,word ptr (-12)[ebp]
+or edi,dword ptr (-36)[ebp]
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,14
+je L2246
+mov dword ptr (-8)[ebp],379
+cmp dword ptr (-4)[ebp],0
+je L2248
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2248:
+L2246:
+mov word ptr (-12)[ebp],12
+mov dword ptr (-40)[ebp],10
+movsx edi,word ptr (-12)[ebp]
+or edi,dword ptr (-40)[ebp]
+mov word ptr (-12)[ebp],di
+movsx edi,word ptr (-12)[ebp]
+cmp edi,14
+je L2250
+mov dword ptr (-8)[ebp],380
+cmp dword ptr (-4)[ebp],0
+je L2252
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2252:
+L2250:
+mov dword ptr (-16)[ebp],12
+mov byte ptr (-25)[ebp],10
+movsx edi,byte ptr (-25)[ebp]
+or dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],14
+je L2254
+mov dword ptr (-8)[ebp],381
+cmp dword ptr (-4)[ebp],0
+je L2256
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2256:
+L2254:
+mov dword ptr (-16)[ebp],12
+mov word ptr (-28)[ebp],10
+movsx edi,word ptr (-28)[ebp]
+or dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],14
+je L2258
+mov dword ptr (-8)[ebp],382
+cmp dword ptr (-4)[ebp],0
+je L2260
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2260:
+L2258:
+mov dword ptr (-16)[ebp],12
+mov dword ptr (-32)[ebp],10
+mov edi,dword ptr (-32)[ebp]
+or dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],14
+je L2262
+mov dword ptr (-8)[ebp],383
+cmp dword ptr (-4)[ebp],0
+je L2264
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2264:
+L2262:
+mov dword ptr (-16)[ebp],12
+mov dword ptr (-36)[ebp],10
+mov edi,dword ptr (-36)[ebp]
+or dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],14
+je L2266
+mov dword ptr (-8)[ebp],384
+cmp dword ptr (-4)[ebp],0
+je L2268
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2268:
+L2266:
+mov dword ptr (-16)[ebp],12
+mov dword ptr (-40)[ebp],10
+mov edi,dword ptr (-16)[ebp]
+or edi,dword ptr (-40)[ebp]
+mov dword ptr (-16)[ebp],edi
+cmp dword ptr (-16)[ebp],14
+je L2270
+mov dword ptr (-8)[ebp],385
+cmp dword ptr (-4)[ebp],0
+je L2272
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2272:
+L2270:
+mov dword ptr (-20)[ebp],12
+mov byte ptr (-25)[ebp],10
+movsx edi,byte ptr (-25)[ebp]
+or dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],14
+je L2274
+mov dword ptr (-8)[ebp],386
+cmp dword ptr (-4)[ebp],0
+je L2276
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2276:
+L2274:
+mov dword ptr (-20)[ebp],12
+mov word ptr (-28)[ebp],10
+movsx edi,word ptr (-28)[ebp]
+or dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],14
+je L2278
+mov dword ptr (-8)[ebp],387
+cmp dword ptr (-4)[ebp],0
+je L2280
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2280:
+L2278:
+mov dword ptr (-20)[ebp],12
+mov dword ptr (-32)[ebp],10
+mov edi,dword ptr (-32)[ebp]
+or dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],14
+je L2282
+mov dword ptr (-8)[ebp],388
+cmp dword ptr (-4)[ebp],0
+je L2284
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2284:
+L2282:
+mov dword ptr (-20)[ebp],12
+mov dword ptr (-36)[ebp],10
+mov edi,dword ptr (-36)[ebp]
+or dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],14
+je L2286
+mov dword ptr (-8)[ebp],389
+cmp dword ptr (-4)[ebp],0
+je L2288
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2288:
+L2286:
+mov dword ptr (-20)[ebp],12
+mov dword ptr (-40)[ebp],10
+mov edi,dword ptr (-20)[ebp]
+or edi,dword ptr (-40)[ebp]
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],14
+je L2290
+mov dword ptr (-8)[ebp],390
+cmp dword ptr (-4)[ebp],0
+je L2292
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2292:
+L2290:
+mov dword ptr (-24)[ebp],12
+mov byte ptr (-25)[ebp],10
+movsx edi,byte ptr (-25)[ebp]
+or dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,14
+je L2294
+mov dword ptr (-8)[ebp],391
+cmp dword ptr (-4)[ebp],0
+je L2296
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2296:
+L2294:
+mov dword ptr (-24)[ebp],12
+mov word ptr (-28)[ebp],10
+movsx edi,word ptr (-28)[ebp]
+or dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,14
+je L2298
+mov dword ptr (-8)[ebp],392
+cmp dword ptr (-4)[ebp],0
+je L2300
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2300:
+L2298:
+mov dword ptr (-24)[ebp],12
+mov dword ptr (-32)[ebp],10
+mov edi,dword ptr (-32)[ebp]
+or dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,14
+je L2302
+mov dword ptr (-8)[ebp],393
+cmp dword ptr (-4)[ebp],0
+je L2304
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2304:
+L2302:
+mov dword ptr (-24)[ebp],12
+mov dword ptr (-36)[ebp],10
+mov edi,dword ptr (-36)[ebp]
+or dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,14
+je L2306
+mov dword ptr (-8)[ebp],394
+cmp dword ptr (-4)[ebp],0
+je L2308
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2308:
+L2306:
+mov dword ptr (-24)[ebp],12
+mov dword ptr (-40)[ebp],10
+mov edi,dword ptr (-40)[ebp]
+or dword ptr (-24)[ebp],edi
+mov edi,dword ptr (-24)[ebp]
+cmp edi,14
+je L2310
+mov dword ptr (-8)[ebp],395
+cmp dword ptr (-4)[ebp],0
+je L2312
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L687)
+push edi
+call _printf
+add esp,8
+L2312:
+L2310:
+cmp dword ptr (-8)[ebp],0
+je L2314
+mov dword ptr (-76)[ebp],1
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L2316
+push 1
+lea edi,(L688)
+push edi
+call _printf
+add esp,8
+L2316:
+L2314:
+mov eax,dword ptr (-76)[ebp]
+L686:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 1
+L2319 label byte
+db 115
+db 55
+db 49
+db 53
+db 44
+db 101
+db 114
+db 37
+db 100
+db 10
+db 0
+align 1
+L2320 label byte
+db 115
+db 55
+db 49
+db 53
+db 32
+db 32
+db 32
+db 0
+public _s715
+_DATA ends
+_TEXT segment
+_s715:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,28
+mov dword ptr (-28)[ebp],0
+mov dword ptr (-20)[ebp],0
+lea edi,(L2320)
+mov dword ptr (-4)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+lea edi,(60)[edi]
+mov dword ptr (-8)[ebp],edi
+mov dword ptr (-16)[ebp],0
+L2321:
+L2322:
+mov edi,dword ptr (-8)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-8)[ebp],esi
+mov esi,dword ptr (-4)[ebp]
+lea ebx,(1)[esi]
+mov dword ptr (-4)[ebp],ebx
+mov bl,byte ptr [esi]
+mov byte ptr [edi],bl
+movsx edi,bl
+cmp edi,0
+jne L2321
+mov dword ptr (-12)[ebp],1
+inc dword ptr (-12)[ebp]
+inc dword ptr (-12)[ebp]
+inc dword ptr (-12)[ebp]
+inc dword ptr (-12)[ebp]
+mov edi,dword ptr (-12)[ebp]
+lea edi,(1)[edi]
+mov dword ptr (-12)[ebp],edi
+cmp edi,6
+je L2324
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L2326
+push 1
+lea edi,(L2319)
+push edi
+call _printf
+add esp,8
+L2326:
+inc dword ptr (-16)[ebp]
+L2324:
+mov edi,dword ptr (-28)[ebp]
+push edi
+mov dword ptr (-24)[ebp],3
+mov edi,dword ptr (-24)[ebp]
+lea edi,(2)[edi]
+push edi
+mov edi,dword ptr (-20)[ebp]
+push edi
+call _s715f
+add esp,12
+cmp eax,5
+je L2328
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L2330
+push 2
+lea edi,(L2319)
+push edi
+call _printf
+add esp,8
+L2330:
+add dword ptr (-16)[ebp],2
+L2328:
+mov eax,dword ptr (-16)[ebp]
+L2318:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _s715f
+_s715f:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov eax,dword ptr (24)[ebp]
+L2332:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 1
+L2334 label byte
+db 115
+db 55
+db 50
+db 44
+db 101
+db 114
+db 37
+db 100
+db 10
+db 0
+align 1
+L2335 label byte
+db 115
+db 55
+db 50
+db 32
+db 32
+db 32
+db 32
+db 0
+public _s72
+_DATA ends
+_TEXT segment
+_s72:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,100
+lea edi,(L2335)
+mov dword ptr (-12)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+lea edi,(60)[edi]
+mov dword ptr (-16)[ebp],edi
+mov dword ptr (-24)[ebp],0
+L2336:
+L2337:
+mov edi,dword ptr (-16)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-16)[ebp],esi
+mov esi,dword ptr (-12)[ebp]
+lea ebx,(1)[esi]
+mov dword ptr (-12)[ebp],ebx
+mov bl,byte ptr [esi]
+mov byte ptr [edi],bl
+movsx edi,bl
+cmp edi,0
+jne L2336
+mov dword ptr (-4)[ebp],2
+cmp dword ptr (-4)[ebp],2
+je L2339
+inc dword ptr (-24)[ebp]
+push 1
+lea edi,(L2334)
+push edi
+call _printf
+add esp,8
+L2339:
+mov edi,dword ptr (-4)[ebp]
+mov esi,edi
+neg esi
+lea edi,[esi][edi]
+cmp edi,0
+je L2341
+add dword ptr (-24)[ebp],2
+push 2
+lea edi,(L2334)
+push edi
+call _printf
+add esp,8
+L2341:
+mov dword ptr (-4)[ebp],0
+mov dword ptr (-8)[ebp],0
+jmp L2346
+L2343:
+mov edi,dword ptr (-4)[ebp]
+lea edi,[edi*2]
+or edi,1
+mov dword ptr (-4)[ebp],edi
+L2344:
+inc dword ptr (-8)[ebp]
+L2346:
+mov edi,dword ptr (20)[ebp]
+mov edi,dword ptr (4)[edi]
+cmp dword ptr (-8)[ebp],edi
+jl L2343
+mov edi,dword ptr (-4)[ebp]
+not edi
+cmp edi,0
+je L2347
+add dword ptr (-24)[ebp],4
+push 4
+lea edi,(L2334)
+push edi
+call _printf
+add esp,8
+L2347:
+mov dword ptr (-4)[ebp],5
+mov edi,dword ptr (-4)[ebp]
+lea edi,(1)[edi]
+mov dword ptr (-4)[ebp],edi
+cmp edi,6
+jne L2354
+mov edi,dword ptr (-4)[ebp]
+sub edi,1
+mov dword ptr (-4)[ebp],edi
+cmp edi,5
+jne L2354
+mov edi,dword ptr (-4)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-4)[ebp],esi
+cmp edi,5
+jne L2354
+mov edi,dword ptr (-4)[ebp]
+mov esi,edi
+sub esi,1
+mov dword ptr (-4)[ebp],esi
+cmp edi,6
+jne L2354
+cmp dword ptr (-4)[ebp],5
+je L2349
+L2354:
+add dword ptr (-24)[ebp],8
+push 8
+lea edi,(L2334)
+push edi
+call _printf
+add esp,8
+L2349:
+mov byte ptr (-29)[ebp],26
+mov dword ptr (-36)[ebp],26
+fld qword ptr (L2355)
+fstp qword ptr (-48)[ebp]
+mov word ptr (-32)[ebp],26
+mov dword ptr (-40)[ebp],26
+mov dword ptr (-28)[ebp],26
+fld dword ptr (L2356)
+fstp dword ptr (-52)[ebp]
+mov dword ptr (-20)[ebp],0
+movsx edi,word ptr (-32)[ebp]
+mov ebx,edi
+movsx edi,bl
+cmp edi,26
+jne L2363
+mov edi,dword ptr (-28)[ebp]
+mov ebx,edi
+movsx edi,bl
+cmp edi,26
+jne L2363
+mov edi,dword ptr (-36)[ebp]
+mov ebx,edi
+movsx edi,bl
+cmp edi,26
+jne L2363
+mov edi,dword ptr (-40)[ebp]
+mov ebx,edi
+movsx edi,bl
+cmp edi,26
+jne L2363
+fld dword ptr (-52)[ebp]
+call __ftol
+mov ebx,eax
+movsx edi,bl
+cmp edi,26
+jne L2363
+fld qword ptr (-48)[ebp]
+call __ftol
+mov ebx,eax
+movsx edi,bl
+cmp edi,26
+je L2357
+L2363:
+inc dword ptr (-20)[ebp]
+L2357:
+movsx edi,byte ptr (-29)[ebp]
+movsx edi,di
+cmp edi,26
+jne L2370
+mov edi,dword ptr (-28)[ebp]
+movsx edi,di
+cmp edi,26
+jne L2370
+mov edi,dword ptr (-36)[ebp]
+movsx edi,di
+cmp edi,26
+jne L2370
+mov edi,dword ptr (-40)[ebp]
+movsx edi,di
+cmp edi,26
+jne L2370
+fld dword ptr (-52)[ebp]
+call __ftol
+mov edi,eax
+movsx edi,di
+cmp edi,26
+jne L2370
+fld qword ptr (-48)[ebp]
+call __ftol
+mov edi,eax
+movsx edi,di
+cmp edi,26
+je L2364
+L2370:
+add dword ptr (-20)[ebp],2
+L2364:
+movsx edi,byte ptr (-29)[ebp]
+cmp edi,26
+jne L2377
+movsx edi,word ptr (-32)[ebp]
+cmp edi,26
+jne L2377
+cmp dword ptr (-36)[ebp],26
+jne L2377
+mov edi,dword ptr (-40)[ebp]
+cmp edi,26
+jne L2377
+fld dword ptr (-52)[ebp]
+call __ftol
+cmp eax,26
+jne L2377
+fld qword ptr (-48)[ebp]
+call __ftol
+cmp eax,26
+je L2371
+L2377:
+add dword ptr (-20)[ebp],4
+L2371:
+movsx edi,byte ptr (-29)[ebp]
+cmp edi,26
+jne L2384
+movsx edi,word ptr (-32)[ebp]
+cmp edi,26
+jne L2384
+cmp dword ptr (-28)[ebp],26
+jne L2384
+mov edi,dword ptr (-40)[ebp]
+cmp edi,26
+jne L2384
+fld dword ptr (-52)[ebp]
+call __ftol
+cmp eax,26
+jne L2384
+fld qword ptr (-48)[ebp]
+call __ftol
+cmp eax,26
+je L2378
+L2384:
+add dword ptr (-20)[ebp],8
+L2378:
+movsx edi,byte ptr (-29)[ebp]
+cmp edi,26
+jne L2393
+movsx edi,word ptr (-32)[ebp]
+cmp edi,26
+jne L2393
+mov edi,dword ptr (-28)[ebp]
+cmp edi,26
+jne L2393
+mov edi,dword ptr (-36)[ebp]
+cmp edi,26
+jne L2393
+fld dword ptr (L828)
+fcomp dword ptr (-52)[ebp]
+fstsw ax
+sahf
+ja L2394
+fld dword ptr (-52)[ebp]
+fsub dword ptr (L828)
+call __ftol
+mov edi,eax
+lea edi,(080000000H)[edi]
+mov dword ptr (-56)[ebp],edi
+jmp L2395
+L2394:
+fld dword ptr (-52)[ebp]
+call __ftol
+mov edi,eax
+mov dword ptr (-56)[ebp],edi
+L2395:
+mov edi,dword ptr (-56)[ebp]
+cmp edi,26
+jne L2393
+fld qword ptr (L836)
+fcomp qword ptr (-48)[ebp]
+fstsw ax
+sahf
+ja L2396
+fld qword ptr (-48)[ebp]
+fsub qword ptr (L836)
+call __ftol
+mov edi,eax
+lea edi,(080000000H)[edi]
+mov dword ptr (-60)[ebp],edi
+jmp L2397
+L2396:
+fld qword ptr (-48)[ebp]
+call __ftol
+mov edi,eax
+mov dword ptr (-60)[ebp],edi
+L2397:
+mov edi,dword ptr (-60)[ebp]
+cmp edi,26
+je L2385
+L2393:
+add dword ptr (-20)[ebp],16
+L2385:
+movsx edi,byte ptr (-29)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fld qword ptr (L2355)
+fcompp
+fstsw ax
+sahf
+jne L2404
+movsx edi,word ptr (-32)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fld qword ptr (L2355)
+fcompp
+fstsw ax
+sahf
+jne L2404
+mov edi,dword ptr (-28)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fld qword ptr (L2355)
+fcompp
+fstsw ax
+sahf
+jne L2404
+mov edi,dword ptr (-36)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fld qword ptr (L2355)
+fcompp
+fstsw ax
+sahf
+jne L2404
+mov edi,dword ptr (-40)[ebp]
+fld qword ptr (L596)
+mov esi,edi
+shr esi,1
+push esi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+and edi,1
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+sub esp,4
+fstp dword ptr 0[esp]
+fld dword ptr 0[esp]
+add esp,4
+fld qword ptr (L2355)
+fcompp
+fstsw ax
+sahf
+jne L2404
+fld qword ptr (-48)[ebp]
+sub esp,4
+fstp dword ptr 0[esp]
+fld dword ptr 0[esp]
+add esp,4
+fld qword ptr (L2355)
+fcompp
+fstsw ax
+sahf
+je L2398
+L2404:
+add dword ptr (-20)[ebp],32
+L2398:
+movsx edi,byte ptr (-29)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fld qword ptr (L2355)
+fcompp
+fstsw ax
+sahf
+jne L2411
+movsx edi,word ptr (-32)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fld qword ptr (L2355)
+fcompp
+fstsw ax
+sahf
+jne L2411
+fild dword ptr (-28)[ebp]
+fld qword ptr (L2355)
+fcompp
+fstsw ax
+sahf
+jne L2411
+fild dword ptr (-36)[ebp]
+fld qword ptr (L2355)
+fcompp
+fstsw ax
+sahf
+jne L2411
+mov edi,dword ptr (-40)[ebp]
+fld qword ptr (L596)
+mov esi,edi
+shr esi,1
+push esi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+and edi,1
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+fld qword ptr (L2355)
+fcompp
+fstsw ax
+sahf
+jne L2411
+fld qword ptr (L2355)
+fcomp dword ptr (-52)[ebp]
+fstsw ax
+sahf
+je L2405
+L2411:
+add dword ptr (-20)[ebp],64
+L2405:
+cmp dword ptr (-20)[ebp],0
+je L2412
+add dword ptr (-24)[ebp],16
+push 16
+lea edi,(L2334)
+push edi
+call _printf
+add esp,8
+L2412:
+mov eax,dword ptr (-24)[ebp]
+L2333:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 1
+L2415 label byte
+db 115
+db 55
+db 53
+db 55
+db 44
+db 101
+db 114
+db 37
+db 100
+db 10
+db 0
+align 1
+L2416 label byte
+db 115
+db 55
+db 53
+db 55
+db 32
+db 32
+db 32
+db 0
+public _s757
+_DATA ends
+_TEXT segment
+_s757:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,148
+lea edi,(L2416)
+mov dword ptr (-112)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+lea edi,(60)[edi]
+mov dword ptr (-116)[ebp],edi
+mov dword ptr (-120)[ebp],0
+L2417:
+L2418:
+mov edi,dword ptr (-116)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-116)[ebp],esi
+mov esi,dword ptr (-112)[ebp]
+lea ebx,(1)[esi]
+mov dword ptr (-112)[ebp],ebx
+mov bl,byte ptr [esi]
+mov byte ptr [edi],bl
+movsx edi,bl
+cmp edi,0
+jne L2417
+mov dword ptr (-124)[ebp],40
+mov edi,dword ptr (-124)[ebp]
+lea esi,[edi*8]
+lea esi,[esi*4]
+cmp esi,1280
+jne L2422
+sar edi,3
+sar edi,2
+cmp edi,1
+je L2420
+L2422:
+inc dword ptr (-120)[ebp]
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L2423
+push 1
+lea edi,(L2415)
+push edi
+call _printf
+add esp,8
+L2423:
+L2420:
+mov dword ptr (-84)[ebp],0
+mov dword ptr (-100)[ebp],0
+jmp L2428
+L2425:
+mov dword ptr (-92)[ebp],1
+mov edi,dword ptr (-92)[ebp]
+mov esi,dword ptr (20)[ebp]
+mov esi,dword ptr (16)[esi]
+sub esi,1
+mov ecx,esi
+shl edi,cl
+mov dword ptr (-96)[ebp],edi
+mov dword ptr (-104)[ebp],0
+mov edi,dword ptr (-104)[ebp]
+not edi
+mov esi,dword ptr (-100)[ebp]
+mov ebx,edi
+mov ecx,esi
+shr ebx,cl
+mov dword ptr (-108)[ebp],ebx
+mov ecx,esi
+shl edi,cl
+mov dword ptr (-104)[ebp],edi
+mov dword ptr (-88)[ebp],0
+jmp L2432
+L2429:
+mov edi,dword ptr (-100)[ebp]
+cmp dword ptr (-88)[ebp],edi
+jge L2440
+mov dword ptr (-132)[ebp],1
+jmp L2441
+L2440:
+mov dword ptr (-132)[ebp],0
+L2441:
+mov edi,dword ptr (-92)[ebp]
+and edi,dword ptr (-104)[ebp]
+cmp edi,0
+jne L2442
+mov dword ptr (-136)[ebp],1
+jmp L2443
+L2442:
+mov dword ptr (-136)[ebp],0
+L2443:
+mov edi,dword ptr (-136)[ebp]
+cmp dword ptr (-132)[ebp],edi
+jne L2439
+mov edi,dword ptr (-100)[ebp]
+cmp dword ptr (-88)[ebp],edi
+jge L2444
+mov dword ptr (-140)[ebp],1
+jmp L2445
+L2444:
+mov dword ptr (-140)[ebp],0
+L2445:
+mov edi,dword ptr (-96)[ebp]
+and edi,dword ptr (-108)[ebp]
+cmp edi,0
+jne L2446
+mov dword ptr (-144)[ebp],1
+jmp L2447
+L2446:
+mov dword ptr (-144)[ebp],0
+L2447:
+mov edi,dword ptr (-144)[ebp]
+cmp dword ptr (-140)[ebp],edi
+je L2433
+L2439:
+mov dword ptr (-84)[ebp],1
+L2433:
+mov edi,dword ptr (-92)[ebp]
+lea edi,[edi*2]
+mov dword ptr (-92)[ebp],edi
+mov edi,dword ptr (-96)[ebp]
+shr edi,1
+mov dword ptr (-96)[ebp],edi
+L2430:
+inc dword ptr (-88)[ebp]
+L2432:
+mov edi,dword ptr (20)[ebp]
+mov edi,dword ptr (16)[edi]
+cmp dword ptr (-88)[ebp],edi
+jl L2429
+L2426:
+inc dword ptr (-100)[ebp]
+L2428:
+mov edi,dword ptr (20)[ebp]
+mov edi,dword ptr (16)[edi]
+cmp dword ptr (-100)[ebp],edi
+jl L2425
+cmp dword ptr (-84)[ebp],0
+je L2448
+add dword ptr (-120)[ebp],2
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L2450
+push 2
+lea edi,(L2415)
+push edi
+call _printf
+add esp,8
+L2450:
+L2448:
+mov dword ptr (-16)[ebp],3
+mov dword ptr (-12)[ebp],2
+mov dword ptr (-8)[ebp],1
+mov edi,dword ptr (-12)[ebp]
+cmp dword ptr (-16)[ebp],edi
+jge L2458
+mov dword ptr (-136)[ebp],1
+jmp L2459
+L2458:
+mov dword ptr (-136)[ebp],0
+L2459:
+mov edi,dword ptr (-8)[ebp]
+cmp dword ptr (-136)[ebp],edi
+jge L2456
+mov dword ptr (-132)[ebp],1
+jmp L2457
+L2456:
+mov dword ptr (-132)[ebp],0
+L2457:
+cmp dword ptr (-132)[ebp],1
+je L2452
+add dword ptr (-120)[ebp],4
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L2460
+push 4
+lea edi,(L2415)
+push edi
+call _printf
+add esp,8
+L2460:
+L2452:
+lea edi,(-76)[ebp]
+lea esi,(-80)[ebp]
+cmp edi,esi
+jne L2462
+add dword ptr (-120)[ebp],8
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L2465
+push 8
+lea edi,(L2415)
+push edi
+call _printf
+add esp,8
+L2465:
+L2462:
+lea edi,(-76)[ebp]
+lea esi,(-80)[ebp]
+cmp edi,esi
+jae L2467
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (40)[edi],0
+je L2470
+lea edi,(L2472)
+push edi
+call _printf
+add esp,4
+L2470:
+L2467:
+mov dword ptr (-84)[ebp],0
+mov dword ptr (-88)[ebp],0
+L2473:
+mov edi,dword ptr (-88)[ebp]
+mov dword ptr (-80)[ebp][edi*4],1
+L2474:
+inc dword ptr (-88)[ebp]
+cmp dword ptr (-88)[ebp],16
+jl L2473
+mov dword ptr (-76)[ebp],0
+mov dword ptr (-64)[ebp],0
+mov dword ptr (-56)[ebp],0
+mov dword ptr (-52)[ebp],0
+mov dword ptr (-44)[ebp],0
+mov dword ptr (-28)[ebp],0
+mov dword ptr (-16)[ebp],0
+L2483:
+mov dword ptr (-12)[ebp],0
+L2487:
+mov dword ptr (-8)[ebp],0
+L2491:
+mov dword ptr (-4)[ebp],0
+L2495:
+mov edi,dword ptr (-12)[ebp]
+cmp dword ptr (-16)[ebp],edi
+jge L2506
+mov dword ptr (-144)[ebp],1
+jmp L2507
+L2506:
+mov dword ptr (-144)[ebp],0
+L2507:
+mov edi,dword ptr (-4)[ebp]
+cmp dword ptr (-8)[ebp],edi
+jge L2508
+mov dword ptr (-148)[ebp],1
+jmp L2509
+L2508:
+mov dword ptr (-148)[ebp],0
+L2509:
+mov edi,dword ptr (-148)[ebp]
+cmp dword ptr (-144)[ebp],edi
+jne L2504
+mov dword ptr (-140)[ebp],1
+jmp L2505
+L2504:
+mov dword ptr (-140)[ebp],0
+L2505:
+mov edi,dword ptr (-16)[ebp]
+mov esi,dword ptr (-12)[ebp]
+lea esi,[esi*4]
+lea edi,[esi][edi*8]
+mov esi,dword ptr (-8)[ebp]
+lea esi,[esi*2]
+lea edi,[esi][edi]
+mov esi,dword ptr (-4)[ebp]
+lea edi,[esi][edi]
+mov edi,dword ptr (-80)[ebp][edi*4]
+cmp dword ptr (-140)[ebp],edi
+je L2499
+mov dword ptr (-84)[ebp],1
+L2499:
+L2496:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],2
+jl L2495
+L2492:
+inc dword ptr (-8)[ebp]
+cmp dword ptr (-8)[ebp],2
+jl L2491
+L2488:
+inc dword ptr (-12)[ebp]
+cmp dword ptr (-12)[ebp],2
+jl L2487
+L2484:
+inc dword ptr (-16)[ebp]
+cmp dword ptr (-16)[ebp],2
+jl L2483
+cmp dword ptr (-84)[ebp],0
+je L2510
+add dword ptr (-120)[ebp],16
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L2512
+push 16
+lea edi,(L2415)
+push edi
+call _printf
+add esp,8
+L2512:
+L2510:
+mov dword ptr (-128)[ebp],0
+mov edi,dword ptr (-128)[ebp]
+cmp edi,0
+je L2514
+add dword ptr (-120)[ebp],32
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L2516
+push 32
+lea edi,(L2415)
+push edi
+call _printf
+add esp,8
+L2516:
+L2514:
+mov eax,dword ptr (-120)[ebp]
+L2414:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 1
+L2519 label byte
+db 76
+db 111
+db 99
+db 97
+db 108
+db 32
+db 101
+db 114
+db 114
+db 111
+db 114
+db 32
+db 37
+db 100
+db 46
+db 10
+db 0
+align 1
+L2520 label byte
+db 115
+db 55
+db 56
+db 49
+db 51
+db 44
+db 101
+db 114
+db 37
+db 100
+db 10
+db 0
+align 1
+L2521 label byte
+db 115
+db 55
+db 56
+db 49
+db 51
+db 32
+db 32
+db 0
+public _s7813
+_DATA ends
+_TEXT segment
+_s7813:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,88
+lea edi,(L2521)
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+lea esi,(60)[edi]
+mov dword ptr (-28)[ebp],esi
+mov dword ptr (-8)[ebp],0
+mov dword ptr (-32)[ebp],0
+mov edi,dword ptr (48)[edi]
+mov dword ptr (-4)[ebp],edi
+L2522:
+L2523:
+mov edi,dword ptr (-28)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-28)[ebp],esi
+mov esi,dword ptr (-24)[ebp]
+lea ebx,(1)[esi]
+mov dword ptr (-24)[ebp],ebx
+mov bl,byte ptr [esi]
+mov byte ptr [edi],bl
+movsx edi,bl
+cmp edi,0
+jne L2522
+jmp L2525
+mov dword ptr (-8)[ebp],1
+cmp dword ptr (-4)[ebp],0
+je L2527
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2527:
+L2525:
+jmp L2529
+mov dword ptr (-8)[ebp],2
+cmp dword ptr (-4)[ebp],0
+je L2531
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2531:
+L2529:
+jmp L2533
+mov dword ptr (-8)[ebp],3
+cmp dword ptr (-4)[ebp],0
+je L2535
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2535:
+L2533:
+jmp L2537
+mov dword ptr (-8)[ebp],4
+cmp dword ptr (-4)[ebp],0
+je L2539
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2539:
+L2537:
+jmp L2541
+mov dword ptr (-8)[ebp],5
+cmp dword ptr (-4)[ebp],0
+je L2543
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2543:
+L2541:
+jmp L2545
+mov dword ptr (-8)[ebp],6
+cmp dword ptr (-4)[ebp],0
+je L2547
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2547:
+L2545:
+jmp L2549
+mov dword ptr (-8)[ebp],7
+cmp dword ptr (-4)[ebp],0
+je L2551
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2551:
+L2549:
+jmp L2553
+mov dword ptr (-8)[ebp],8
+cmp dword ptr (-4)[ebp],0
+je L2555
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2555:
+L2553:
+jmp L2557
+mov dword ptr (-8)[ebp],9
+cmp dword ptr (-4)[ebp],0
+je L2559
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2559:
+L2557:
+jmp L2561
+mov dword ptr (-8)[ebp],10
+cmp dword ptr (-4)[ebp],0
+je L2563
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2563:
+L2561:
+jmp L2565
+mov dword ptr (-8)[ebp],11
+cmp dword ptr (-4)[ebp],0
+je L2567
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2567:
+L2565:
+jmp L2569
+mov dword ptr (-8)[ebp],12
+cmp dword ptr (-4)[ebp],0
+je L2571
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2571:
+L2569:
+jmp L2573
+mov dword ptr (-8)[ebp],13
+cmp dword ptr (-4)[ebp],0
+je L2575
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2575:
+L2573:
+jmp L2577
+mov dword ptr (-8)[ebp],14
+cmp dword ptr (-4)[ebp],0
+je L2579
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2579:
+L2577:
+jmp L2581
+mov dword ptr (-8)[ebp],15
+cmp dword ptr (-4)[ebp],0
+je L2583
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2583:
+L2581:
+jmp L2585
+mov dword ptr (-8)[ebp],16
+cmp dword ptr (-4)[ebp],0
+je L2587
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2587:
+L2585:
+jmp L2589
+mov dword ptr (-8)[ebp],17
+cmp dword ptr (-4)[ebp],0
+je L2591
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2591:
+L2589:
+jmp L2593
+mov dword ptr (-8)[ebp],18
+cmp dword ptr (-4)[ebp],0
+je L2595
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2595:
+L2593:
+jmp L2597
+mov dword ptr (-8)[ebp],16
+cmp dword ptr (-4)[ebp],0
+je L2599
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2599:
+L2597:
+jmp L2601
+mov dword ptr (-8)[ebp],20
+cmp dword ptr (-4)[ebp],0
+je L2603
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2603:
+L2601:
+jmp L2605
+mov dword ptr (-8)[ebp],21
+cmp dword ptr (-4)[ebp],0
+je L2607
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2607:
+L2605:
+jmp L2609
+mov dword ptr (-8)[ebp],22
+cmp dword ptr (-4)[ebp],0
+je L2611
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2611:
+L2609:
+jmp L2613
+mov dword ptr (-8)[ebp],23
+cmp dword ptr (-4)[ebp],0
+je L2615
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2615:
+L2613:
+jmp L2617
+mov dword ptr (-8)[ebp],24
+cmp dword ptr (-4)[ebp],0
+je L2619
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2619:
+L2617:
+jmp L2621
+mov dword ptr (-8)[ebp],25
+cmp dword ptr (-4)[ebp],0
+je L2623
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2623:
+L2621:
+jmp L2625
+mov dword ptr (-8)[ebp],26
+cmp dword ptr (-4)[ebp],0
+je L2627
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2627:
+L2625:
+jmp L2629
+mov dword ptr (-8)[ebp],27
+cmp dword ptr (-4)[ebp],0
+je L2631
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2631:
+L2629:
+jmp L2633
+mov dword ptr (-8)[ebp],28
+cmp dword ptr (-4)[ebp],0
+je L2635
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2635:
+L2633:
+jmp L2637
+mov dword ptr (-8)[ebp],26
+cmp dword ptr (-4)[ebp],0
+je L2639
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2639:
+L2637:
+jmp L2641
+mov dword ptr (-8)[ebp],30
+cmp dword ptr (-4)[ebp],0
+je L2643
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2643:
+L2641:
+jmp L2645
+mov dword ptr (-8)[ebp],31
+cmp dword ptr (-4)[ebp],0
+je L2647
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2647:
+L2645:
+jmp L2649
+mov dword ptr (-8)[ebp],32
+cmp dword ptr (-4)[ebp],0
+je L2651
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2651:
+L2649:
+jmp L2653
+mov dword ptr (-8)[ebp],33
+cmp dword ptr (-4)[ebp],0
+je L2655
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2655:
+L2653:
+jmp L2657
+mov dword ptr (-8)[ebp],34
+cmp dword ptr (-4)[ebp],0
+je L2659
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2659:
+L2657:
+jmp L2661
+mov dword ptr (-8)[ebp],35
+cmp dword ptr (-4)[ebp],0
+je L2663
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2663:
+L2661:
+jmp L2665
+mov dword ptr (-8)[ebp],36
+cmp dword ptr (-4)[ebp],0
+je L2667
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2667:
+L2665:
+jmp L2669
+mov dword ptr (-8)[ebp],37
+cmp dword ptr (-4)[ebp],0
+je L2671
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2671:
+L2669:
+jmp L2673
+mov dword ptr (-8)[ebp],38
+cmp dword ptr (-4)[ebp],0
+je L2675
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2675:
+L2673:
+jmp L2677
+mov dword ptr (-8)[ebp],39
+cmp dword ptr (-4)[ebp],0
+je L2679
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2679:
+L2677:
+jmp L2681
+mov dword ptr (-8)[ebp],40
+cmp dword ptr (-4)[ebp],0
+je L2683
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2683:
+L2681:
+jmp L2685
+mov dword ptr (-8)[ebp],41
+cmp dword ptr (-4)[ebp],0
+je L2687
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2687:
+L2685:
+jmp L2689
+mov dword ptr (-8)[ebp],42
+cmp dword ptr (-4)[ebp],0
+je L2691
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2691:
+L2689:
+jmp L2693
+mov dword ptr (-8)[ebp],43
+cmp dword ptr (-4)[ebp],0
+je L2695
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2695:
+L2693:
+jmp L2697
+mov dword ptr (-8)[ebp],44
+cmp dword ptr (-4)[ebp],0
+je L2699
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2699:
+L2697:
+jmp L2701
+mov dword ptr (-8)[ebp],45
+cmp dword ptr (-4)[ebp],0
+je L2703
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2703:
+L2701:
+jmp L2705
+mov dword ptr (-8)[ebp],46
+cmp dword ptr (-4)[ebp],0
+je L2707
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2707:
+L2705:
+jmp L2709
+mov dword ptr (-8)[ebp],47
+cmp dword ptr (-4)[ebp],0
+je L2711
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2711:
+L2709:
+jmp L2713
+mov dword ptr (-8)[ebp],48
+cmp dword ptr (-4)[ebp],0
+je L2715
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2715:
+L2713:
+jmp L2717
+mov dword ptr (-8)[ebp],49
+cmp dword ptr (-4)[ebp],0
+je L2719
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2719:
+L2717:
+jmp L2721
+mov dword ptr (-8)[ebp],50
+cmp dword ptr (-4)[ebp],0
+je L2723
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2723:
+L2721:
+jmp L2725
+mov dword ptr (-8)[ebp],51
+cmp dword ptr (-4)[ebp],0
+je L2727
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2727:
+L2725:
+jmp L2729
+mov dword ptr (-8)[ebp],52
+cmp dword ptr (-4)[ebp],0
+je L2731
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2731:
+L2729:
+jmp L2733
+mov dword ptr (-8)[ebp],53
+cmp dword ptr (-4)[ebp],0
+je L2735
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2735:
+L2733:
+jmp L2737
+mov dword ptr (-8)[ebp],54
+cmp dword ptr (-4)[ebp],0
+je L2739
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2739:
+L2737:
+jmp L2741
+mov dword ptr (-8)[ebp],55
+cmp dword ptr (-4)[ebp],0
+je L2743
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2743:
+L2741:
+jmp L2745
+mov dword ptr (-8)[ebp],56
+cmp dword ptr (-4)[ebp],0
+je L2747
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2747:
+L2745:
+jmp L2749
+mov dword ptr (-8)[ebp],57
+cmp dword ptr (-4)[ebp],0
+je L2751
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2751:
+L2749:
+jmp L2753
+mov dword ptr (-8)[ebp],58
+cmp dword ptr (-4)[ebp],0
+je L2755
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2755:
+L2753:
+jmp L2757
+mov dword ptr (-8)[ebp],56
+cmp dword ptr (-4)[ebp],0
+je L2759
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2759:
+L2757:
+jmp L2761
+mov dword ptr (-8)[ebp],60
+cmp dword ptr (-4)[ebp],0
+je L2763
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2763:
+L2761:
+jmp L2765
+mov dword ptr (-8)[ebp],61
+cmp dword ptr (-4)[ebp],0
+je L2767
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2767:
+L2765:
+jmp L2769
+mov dword ptr (-8)[ebp],62
+cmp dword ptr (-4)[ebp],0
+je L2771
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2771:
+L2769:
+jmp L2773
+mov dword ptr (-8)[ebp],63
+cmp dword ptr (-4)[ebp],0
+je L2775
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2775:
+L2773:
+jmp L2777
+mov dword ptr (-8)[ebp],64
+cmp dword ptr (-4)[ebp],0
+je L2779
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2779:
+L2777:
+jmp L2781
+mov dword ptr (-8)[ebp],65
+cmp dword ptr (-4)[ebp],0
+je L2783
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2783:
+L2781:
+jmp L2785
+mov dword ptr (-8)[ebp],66
+cmp dword ptr (-4)[ebp],0
+je L2787
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2787:
+L2785:
+jmp L2789
+mov dword ptr (-8)[ebp],67
+cmp dword ptr (-4)[ebp],0
+je L2791
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2791:
+L2789:
+jmp L2793
+mov dword ptr (-8)[ebp],68
+cmp dword ptr (-4)[ebp],0
+je L2795
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2795:
+L2793:
+jmp L2797
+mov dword ptr (-8)[ebp],69
+cmp dword ptr (-4)[ebp],0
+je L2799
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2799:
+L2797:
+jmp L2801
+mov dword ptr (-8)[ebp],70
+cmp dword ptr (-4)[ebp],0
+je L2803
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2803:
+L2801:
+jmp L2805
+mov dword ptr (-8)[ebp],71
+cmp dword ptr (-4)[ebp],0
+je L2807
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2807:
+L2805:
+jmp L2809
+mov dword ptr (-8)[ebp],72
+cmp dword ptr (-4)[ebp],0
+je L2811
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2811:
+L2809:
+jmp L2813
+mov dword ptr (-8)[ebp],73
+cmp dword ptr (-4)[ebp],0
+je L2815
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2815:
+L2813:
+jmp L2817
+mov dword ptr (-8)[ebp],74
+cmp dword ptr (-4)[ebp],0
+je L2819
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2819:
+L2817:
+jmp L2821
+mov dword ptr (-8)[ebp],75
+cmp dword ptr (-4)[ebp],0
+je L2823
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2823:
+L2821:
+cmp dword ptr (-8)[ebp],0
+je L2825
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L2827
+push 1
+lea edi,(L2520)
+push edi
+call _printf
+add esp,8
+L2827:
+inc dword ptr (-32)[ebp]
+L2825:
+mov dword ptr (-8)[ebp],0
+mov dword ptr (-16)[ebp],0
+mov dword ptr (-12)[ebp],0
+mov edi,dword ptr (-12)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-12)[ebp],esi
+cmp edi,0
+je L2830
+mov edi,dword ptr (-16)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-16)[ebp],esi
+cmp edi,0
+je L2830
+mov dword ptr (-44)[ebp],1
+jmp L2831
+L2830:
+mov dword ptr (-44)[ebp],0
+L2831:
+mov edi,dword ptr (-44)[ebp]
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-12)[ebp],1
+je L2832
+mov dword ptr (-8)[ebp],1
+cmp dword ptr (-4)[ebp],0
+je L2834
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2834:
+L2832:
+cmp dword ptr (-16)[ebp],0
+je L2836
+mov dword ptr (-8)[ebp],2
+cmp dword ptr (-4)[ebp],0
+je L2838
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2838:
+L2836:
+cmp dword ptr (-20)[ebp],0
+je L2840
+mov dword ptr (-8)[ebp],3
+cmp dword ptr (-4)[ebp],0
+je L2842
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2842:
+L2840:
+cmp dword ptr (-12)[ebp],0
+je L2845
+mov edi,dword ptr (-16)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-16)[ebp],esi
+cmp edi,0
+je L2845
+mov dword ptr (-48)[ebp],1
+jmp L2846
+L2845:
+mov dword ptr (-48)[ebp],0
+L2846:
+mov edi,dword ptr (-48)[ebp]
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-12)[ebp],1
+je L2847
+mov dword ptr (-8)[ebp],4
+cmp dword ptr (-4)[ebp],0
+je L2849
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2849:
+L2847:
+cmp dword ptr (-16)[ebp],1
+je L2851
+mov dword ptr (-8)[ebp],5
+cmp dword ptr (-4)[ebp],0
+je L2853
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2853:
+L2851:
+cmp dword ptr (-20)[ebp],0
+je L2855
+mov dword ptr (-8)[ebp],6
+cmp dword ptr (-4)[ebp],0
+je L2857
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2857:
+L2855:
+mov edi,dword ptr (-12)[ebp]
+mov esi,edi
+sub esi,1
+mov dword ptr (-12)[ebp],esi
+cmp edi,0
+je L2860
+cmp dword ptr (-16)[ebp],0
+je L2860
+mov dword ptr (-52)[ebp],1
+jmp L2861
+L2860:
+mov dword ptr (-52)[ebp],0
+L2861:
+mov edi,dword ptr (-52)[ebp]
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-12)[ebp],0
+je L2862
+mov dword ptr (-8)[ebp],7
+cmp dword ptr (-4)[ebp],0
+je L2864
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2864:
+L2862:
+cmp dword ptr (-16)[ebp],1
+je L2866
+mov dword ptr (-8)[ebp],8
+cmp dword ptr (-4)[ebp],0
+je L2868
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2868:
+L2866:
+cmp dword ptr (-20)[ebp],1
+je L2870
+mov dword ptr (-8)[ebp],9
+cmp dword ptr (-4)[ebp],0
+je L2872
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2872:
+L2870:
+cmp dword ptr (-12)[ebp],0
+je L2875
+mov edi,dword ptr (-16)[ebp]
+mov esi,edi
+sub esi,1
+mov dword ptr (-16)[ebp],esi
+cmp edi,0
+je L2875
+mov dword ptr (-56)[ebp],1
+jmp L2876
+L2875:
+mov dword ptr (-56)[ebp],0
+L2876:
+mov edi,dword ptr (-56)[ebp]
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-12)[ebp],0
+je L2877
+mov dword ptr (-8)[ebp],10
+cmp dword ptr (-4)[ebp],0
+je L2879
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2879:
+L2877:
+cmp dword ptr (-16)[ebp],1
+je L2881
+mov dword ptr (-8)[ebp],11
+cmp dword ptr (-4)[ebp],0
+je L2883
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2883:
+L2881:
+cmp dword ptr (-20)[ebp],0
+je L2885
+mov dword ptr (-8)[ebp],12
+cmp dword ptr (-4)[ebp],0
+je L2887
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2887:
+L2885:
+cmp dword ptr (-8)[ebp],0
+je L2889
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L2891
+push 2
+lea edi,(L2520)
+push edi
+call _printf
+add esp,8
+L2891:
+add dword ptr (-32)[ebp],2
+L2889:
+mov dword ptr (-8)[ebp],0
+mov dword ptr (-16)[ebp],0
+mov dword ptr (-12)[ebp],0
+mov edi,dword ptr (-12)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-12)[ebp],esi
+cmp edi,0
+jne L2896
+cmp dword ptr (-16)[ebp],0
+je L2894
+L2896:
+mov dword ptr (-60)[ebp],1
+jmp L2895
+L2894:
+mov dword ptr (-60)[ebp],0
+L2895:
+mov edi,dword ptr (-60)[ebp]
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-12)[ebp],1
+je L2897
+mov dword ptr (-8)[ebp],1
+cmp dword ptr (-4)[ebp],0
+je L2899
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2899:
+L2897:
+cmp dword ptr (-16)[ebp],0
+je L2901
+mov dword ptr (-8)[ebp],2
+cmp dword ptr (-4)[ebp],0
+je L2903
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2903:
+L2901:
+cmp dword ptr (-20)[ebp],0
+je L2905
+mov dword ptr (-8)[ebp],3
+cmp dword ptr (-4)[ebp],0
+je L2907
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2907:
+L2905:
+mov edi,dword ptr (-16)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-16)[ebp],esi
+cmp edi,0
+jne L2912
+cmp dword ptr (-12)[ebp],0
+je L2910
+L2912:
+mov dword ptr (-64)[ebp],1
+jmp L2911
+L2910:
+mov dword ptr (-64)[ebp],0
+L2911:
+mov edi,dword ptr (-64)[ebp]
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-12)[ebp],1
+je L2913
+mov dword ptr (-8)[ebp],4
+cmp dword ptr (-4)[ebp],0
+je L2915
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2915:
+L2913:
+cmp dword ptr (-16)[ebp],1
+je L2917
+mov dword ptr (-8)[ebp],5
+cmp dword ptr (-4)[ebp],0
+je L2919
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2919:
+L2917:
+cmp dword ptr (-20)[ebp],1
+je L2921
+mov dword ptr (-8)[ebp],6
+cmp dword ptr (-4)[ebp],0
+je L2923
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2923:
+L2921:
+mov edi,dword ptr (-12)[ebp]
+mov esi,edi
+sub esi,1
+mov dword ptr (-12)[ebp],esi
+cmp edi,0
+jne L2928
+mov edi,dword ptr (-16)[ebp]
+mov esi,edi
+sub esi,1
+mov dword ptr (-16)[ebp],esi
+cmp edi,0
+je L2926
+L2928:
+mov dword ptr (-68)[ebp],1
+jmp L2927
+L2926:
+mov dword ptr (-68)[ebp],0
+L2927:
+mov edi,dword ptr (-68)[ebp]
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-12)[ebp],0
+je L2929
+mov dword ptr (-8)[ebp],7
+cmp dword ptr (-4)[ebp],0
+je L2931
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2931:
+L2929:
+cmp dword ptr (-16)[ebp],1
+je L2933
+mov dword ptr (-8)[ebp],8
+cmp dword ptr (-4)[ebp],0
+je L2935
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2935:
+L2933:
+cmp dword ptr (-20)[ebp],1
+je L2937
+mov dword ptr (-8)[ebp],9
+cmp dword ptr (-4)[ebp],0
+je L2939
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2939:
+L2937:
+cmp dword ptr (-12)[ebp],0
+jne L2944
+mov edi,dword ptr (-16)[ebp]
+mov esi,edi
+sub esi,1
+mov dword ptr (-16)[ebp],esi
+cmp edi,0
+je L2942
+L2944:
+mov dword ptr (-72)[ebp],1
+jmp L2943
+L2942:
+mov dword ptr (-72)[ebp],0
+L2943:
+mov edi,dword ptr (-72)[ebp]
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-12)[ebp],0
+je L2945
+mov dword ptr (-8)[ebp],10
+cmp dword ptr (-4)[ebp],0
+je L2947
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2947:
+L2945:
+cmp dword ptr (-16)[ebp],0
+je L2949
+mov dword ptr (-8)[ebp],11
+cmp dword ptr (-4)[ebp],0
+je L2951
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2951:
+L2949:
+cmp dword ptr (-20)[ebp],1
+je L2953
+mov dword ptr (-8)[ebp],12
+cmp dword ptr (-4)[ebp],0
+je L2955
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L2519)
+push edi
+call _printf
+add esp,8
+L2955:
+L2953:
+cmp dword ptr (-8)[ebp],0
+je L2957
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L2959
+push 4
+lea edi,(L2520)
+push edi
+call _printf
+add esp,8
+L2959:
+add dword ptr (-32)[ebp],4
+L2957:
+mov dword ptr (-16)[ebp],0
+mov dword ptr (-12)[ebp],0
+mov dword ptr (-36)[ebp],0
+mov dword ptr (-40)[ebp],1
+cmp dword ptr (-40)[ebp],0
+je L2963
+mov edi,dword ptr (-36)[ebp]
+mov dword ptr (-76)[ebp],edi
+jmp L2964
+L2963:
+cmp dword ptr (-40)[ebp],0
+je L2965
+mov edi,dword ptr (-12)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-12)[ebp],esi
+mov dword ptr (-80)[ebp],edi
+jmp L2966
+L2965:
+mov edi,dword ptr (-16)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-16)[ebp],esi
+mov dword ptr (-80)[ebp],edi
+L2966:
+mov edi,dword ptr (-80)[ebp]
+mov dword ptr (-76)[ebp],edi
+L2964:
+mov edi,dword ptr (-76)[ebp]
+mov dword ptr (-20)[ebp],edi
+cmp dword ptr (-20)[ebp],0
+jne L2970
+cmp dword ptr (-12)[ebp],0
+jne L2970
+cmp dword ptr (-16)[ebp],0
+je L2967
+L2970:
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L2971
+push 8
+lea edi,(L2520)
+push edi
+call _printf
+add esp,8
+L2971:
+add dword ptr (-32)[ebp],8
+L2967:
+cmp dword ptr (-40)[ebp],0
+je L2978
+mov edi,dword ptr (-36)[ebp]
+mov dword ptr (-84)[ebp],edi
+jmp L2979
+L2978:
+mov dword ptr (-84)[ebp],1
+L2979:
+cmp dword ptr (-84)[ebp],0
+jne L2977
+cmp dword ptr (-36)[ebp],0
+je L2980
+mov dword ptr (-88)[ebp],1
+jmp L2981
+L2980:
+mov edi,dword ptr (-36)[ebp]
+mov dword ptr (-88)[ebp],edi
+L2981:
+cmp dword ptr (-88)[ebp],0
+je L2973
+L2977:
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L2982
+push 16
+lea edi,(L2520)
+push edi
+call _printf
+add esp,8
+L2982:
+add dword ptr (-32)[ebp],16
+L2973:
+mov eax,dword ptr (-32)[ebp]
+L2518:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 1
+L2985 label byte
+db 115
+db 56
+db 49
+db 44
+db 101
+db 114
+db 37
+db 100
+db 10
+db 0
+align 1
+L2986 label byte
+db 115
+db 56
+db 49
+db 32
+db 32
+db 32
+db 32
+db 0
+align 1
+L2987 label byte
+db 82
+db 101
+db 103
+db 105
+db 115
+db 116
+db 101
+db 114
+db 32
+db 99
+db 111
+db 117
+db 110
+db 116
+db 32
+db 102
+db 111
+db 114
+db 32
+db 37
+db 115
+db 32
+db 105
+db 115
+db 32
+db 117
+db 110
+db 114
+db 101
+db 108
+db 105
+db 97
+db 98
+db 108
+db 101
+db 46
+db 10
+db 0
+align 1
+L2988 label byte
+db 37
+db 100
+db 32
+db 114
+db 101
+db 103
+db 105
+db 115
+db 116
+db 101
+db 114
+db 115
+db 32
+db 97
+db 115
+db 115
+db 105
+db 103
+db 110
+db 101
+db 100
+db 32
+db 116
+db 111
+db 32
+db 37
+db 115
+db 32
+db 118
+db 97
+db 114
+db 105
+db 97
+db 98
+db 108
+db 101
+db 115
+db 46
+db 10
+db 0
+public _s81
+_DATA ends
+_TEXT segment
+_s81:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,56
+mov dword ptr (-56)[ebp],0
+mov dword ptr (-44)[ebp],0
+mov dword ptr (-48)[ebp],0
+mov dword ptr (-52)[ebp],0
+lea edi,(L2986)
+mov dword ptr (-36)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+lea edi,(60)[edi]
+mov dword ptr (-40)[ebp],edi
+L2989:
+L2990:
+mov edi,dword ptr (-40)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-40)[ebp],esi
+mov esi,dword ptr (-36)[ebp]
+lea ebx,(1)[esi]
+mov dword ptr (-36)[ebp],ebx
+mov bl,byte ptr [esi]
+mov byte ptr [edi],bl
+movsx edi,bl
+cmp edi,0
+jne L2989
+mov dword ptr (-16)[ebp],1
+mov dword ptr (-20)[ebp],0
+L2992:
+mov edi,dword ptr (-16)[ebp]
+mov ebx,edi
+mov byte ptr (-1)[ebp],bl
+mov byte ptr (-21)[ebp],bl
+lea esi,(-16)[ebp]
+mov dword ptr (-8)[ebp],esi
+lea esi,(-16)[ebp]
+mov dword ptr (-28)[ebp],esi
+mov dword ptr (-12)[ebp],edi
+mov dword ptr (-32)[ebp],edi
+movsx edi,byte ptr (-1)[ebp]
+movsx esi,byte ptr (-21)[ebp]
+cmp edi,esi
+je L2996
+mov dword ptr (-44)[ebp],1
+L2996:
+mov edi,dword ptr (-8)[ebp]
+mov esi,dword ptr (-28)[ebp]
+cmp edi,esi
+je L2998
+mov dword ptr (-48)[ebp],1
+L2998:
+mov edi,dword ptr (-32)[ebp]
+cmp dword ptr (-12)[ebp],edi
+je L3000
+mov dword ptr (-52)[ebp],1
+L3000:
+sal dword ptr (-16)[ebp],1
+L2993:
+inc dword ptr (-20)[ebp]
+cmp dword ptr (-20)[ebp],50
+jl L2992
+cmp dword ptr (-44)[ebp],0
+je L3002
+inc dword ptr (-56)[ebp]
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L3004
+push 1
+lea edi,(L2985)
+push edi
+call _printf
+add esp,8
+L3004:
+L3002:
+cmp dword ptr (-48)[ebp],0
+je L3006
+add dword ptr (-56)[ebp],2
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L3008
+push 2
+lea edi,(L2985)
+push edi
+call _printf
+add esp,8
+L3008:
+L3006:
+cmp dword ptr (-52)[ebp],0
+je L3010
+add dword ptr (-56)[ebp],4
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L3012
+push 4
+lea edi,(L2985)
+push edi
+call _printf
+add esp,8
+L3012:
+L3010:
+call _regc
+add esp,0
+mov dword ptr (-16)[ebp],eax
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (40)[edi],0
+je L3014
+cmp dword ptr (-16)[ebp],0
+jge L3016
+lea edi,(L425)
+push edi
+lea edi,(L2987)
+push edi
+call _printf
+add esp,8
+jmp L3017
+L3016:
+lea edi,(L425)
+push edi
+mov edi,dword ptr (-16)[ebp]
+push edi
+lea edi,(L2988)
+push edi
+call _printf
+add esp,12
+L3017:
+L3014:
+call _regp
+add esp,0
+mov dword ptr (-16)[ebp],eax
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (40)[edi],0
+je L3018
+cmp dword ptr (-16)[ebp],0
+jge L3020
+lea edi,(L3022)
+push edi
+lea edi,(L2987)
+push edi
+call _printf
+add esp,8
+jmp L3021
+L3020:
+lea edi,(L3022)
+push edi
+mov edi,dword ptr (-16)[ebp]
+push edi
+lea edi,(L2988)
+push edi
+call _printf
+add esp,12
+L3021:
+L3018:
+call _regi
+add esp,0
+mov dword ptr (-16)[ebp],eax
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (40)[edi],0
+je L3023
+cmp dword ptr (-16)[ebp],0
+jge L3025
+lea edi,(L426)
+push edi
+lea edi,(L2987)
+push edi
+call _printf
+add esp,8
+jmp L3026
+L3025:
+lea edi,(L426)
+push edi
+mov edi,dword ptr (-16)[ebp]
+push edi
+lea edi,(L2988)
+push edi
+call _printf
+add esp,12
+L3026:
+L3023:
+mov eax,dword ptr (-56)[ebp]
+L2984:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _regc
+_regc:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,148
+mov byte ptr (-138)[ebp],0
+mov byte ptr (-117)[ebp],1
+mov byte ptr (-118)[ebp],2
+mov byte ptr (-119)[ebp],3
+mov byte ptr (-1)[ebp],4
+mov byte ptr (-120)[ebp],5
+mov byte ptr (-2)[ebp],6
+mov byte ptr (-121)[ebp],7
+mov byte ptr (-3)[ebp],8
+mov byte ptr (-122)[ebp],9
+mov byte ptr (-4)[ebp],10
+mov byte ptr (-123)[ebp],11
+mov byte ptr (-5)[ebp],12
+mov byte ptr (-124)[ebp],13
+mov byte ptr (-6)[ebp],14
+mov byte ptr (-125)[ebp],15
+mov byte ptr (-7)[ebp],16
+mov byte ptr (-126)[ebp],17
+mov byte ptr (-8)[ebp],18
+mov byte ptr (-127)[ebp],19
+mov byte ptr (-9)[ebp],20
+mov byte ptr (-128)[ebp],21
+mov byte ptr (-10)[ebp],22
+mov byte ptr (-129)[ebp],23
+mov byte ptr (-11)[ebp],24
+mov byte ptr (-130)[ebp],25
+mov byte ptr (-12)[ebp],26
+mov byte ptr (-131)[ebp],27
+mov byte ptr (-13)[ebp],28
+mov byte ptr (-132)[ebp],29
+mov byte ptr (-14)[ebp],30
+mov byte ptr (-133)[ebp],31
+mov byte ptr (-15)[ebp],32
+mov byte ptr (-134)[ebp],33
+mov byte ptr (-16)[ebp],34
+mov byte ptr (-135)[ebp],35
+mov byte ptr (-136)[ebp],36
+mov byte ptr (-137)[ebp],37
+mov byte ptr (-139)[ebp],38
+lea edi,(-117)[ebp]
+lea esi,(-138)[ebp]
+mov ebx,edi
+sub ebx,esi
+mov esi,ebx
+mov dword ptr (-104)[ebp],esi
+lea esi,(-118)[ebp]
+sub esi,edi
+mov edi,esi
+mov dword ptr (-100)[ebp],edi
+lea edi,(-119)[ebp]
+lea esi,(-118)[ebp]
+sub edi,esi
+mov dword ptr (-96)[ebp],edi
+lea edi,(-120)[ebp]
+lea esi,(-119)[ebp]
+sub edi,esi
+mov dword ptr (-92)[ebp],edi
+lea edi,(-121)[ebp]
+lea esi,(-120)[ebp]
+sub edi,esi
+mov dword ptr (-88)[ebp],edi
+lea edi,(-122)[ebp]
+lea esi,(-121)[ebp]
+sub edi,esi
+mov dword ptr (-84)[ebp],edi
+lea edi,(-123)[ebp]
+lea esi,(-122)[ebp]
+sub edi,esi
+mov dword ptr (-80)[ebp],edi
+lea edi,(-124)[ebp]
+lea esi,(-123)[ebp]
+sub edi,esi
+mov dword ptr (-76)[ebp],edi
+lea edi,(-125)[ebp]
+lea esi,(-124)[ebp]
+sub edi,esi
+mov dword ptr (-72)[ebp],edi
+lea edi,(-126)[ebp]
+lea esi,(-125)[ebp]
+sub edi,esi
+mov dword ptr (-68)[ebp],edi
+lea edi,(-127)[ebp]
+lea esi,(-126)[ebp]
+sub edi,esi
+mov dword ptr (-64)[ebp],edi
+lea edi,(-128)[ebp]
+lea esi,(-127)[ebp]
+sub edi,esi
+mov dword ptr (-60)[ebp],edi
+lea edi,(-129)[ebp]
+lea esi,(-128)[ebp]
+sub edi,esi
+mov dword ptr (-56)[ebp],edi
+lea edi,(-130)[ebp]
+lea esi,(-129)[ebp]
+sub edi,esi
+mov dword ptr (-52)[ebp],edi
+lea edi,(-131)[ebp]
+lea esi,(-130)[ebp]
+sub edi,esi
+mov dword ptr (-48)[ebp],edi
+lea edi,(-132)[ebp]
+lea esi,(-131)[ebp]
+sub edi,esi
+mov dword ptr (-44)[ebp],edi
+lea edi,(-133)[ebp]
+lea esi,(-132)[ebp]
+sub edi,esi
+mov dword ptr (-40)[ebp],edi
+lea edi,(-134)[ebp]
+lea esi,(-133)[ebp]
+sub edi,esi
+mov dword ptr (-36)[ebp],edi
+lea edi,(-135)[ebp]
+lea esi,(-134)[ebp]
+sub edi,esi
+mov dword ptr (-32)[ebp],edi
+lea edi,(-136)[ebp]
+lea esi,(-135)[ebp]
+sub edi,esi
+mov dword ptr (-28)[ebp],edi
+lea edi,(-137)[ebp]
+lea esi,(-136)[ebp]
+sub edi,esi
+mov dword ptr (-24)[ebp],edi
+lea edi,(-139)[ebp]
+lea esi,(-137)[ebp]
+sub edi,esi
+mov dword ptr (-20)[ebp],edi
+mov edi,dword ptr (-104)[ebp]
+mov dword ptr (-116)[ebp],edi
+mov dword ptr (-112)[ebp],1
+mov dword ptr (-108)[ebp],0
+L3049:
+mov edi,dword ptr (-112)[ebp]
+cmp edi,1
+je L3055
+cmp edi,2
+je L3058
+cmp edi,3
+je L3063
+jmp L3053
+L3055:
+mov edi,dword ptr (-108)[ebp]
+mov esi,dword ptr (-116)[ebp]
+cmp dword ptr (-104)[ebp][edi*4],esi
+je L3054
+mov edi,dword ptr (-108)[ebp]
+mov edi,dword ptr (-104)[ebp][edi*4]
+mov dword ptr (-148)[ebp],edi
+mov dword ptr (-112)[ebp],2
+mov dword ptr (-144)[ebp],1
+jmp L3054
+L3058:
+mov edi,dword ptr (-108)[ebp]
+mov esi,dword ptr (-116)[ebp]
+cmp dword ptr (-104)[ebp][edi*4],esi
+jne L3059
+mov dword ptr (-112)[ebp],3
+jmp L3054
+L3059:
+mov edi,dword ptr (-108)[ebp]
+mov esi,dword ptr (-148)[ebp]
+cmp dword ptr (-104)[ebp][edi*4],esi
+jne L3061
+inc dword ptr (-144)[ebp]
+jmp L3054
+L3061:
+mov dword ptr (-112)[ebp],4
+jmp L3054
+L3063:
+mov edi,dword ptr (-108)[ebp]
+mov esi,dword ptr (-116)[ebp]
+cmp dword ptr (-104)[ebp][edi*4],esi
+je L3054
+mov dword ptr (-112)[ebp],4
+L3053:
+L3054:
+L3050:
+inc dword ptr (-108)[ebp]
+cmp dword ptr (-108)[ebp],22
+jl L3049
+cmp dword ptr (-112)[ebp],3
+jne L3066
+mov edi,16
+mov eax,edi
+sub eax,dword ptr (-144)[ebp]
+jmp L3027
+L3066:
+mov eax,-1
+L3027:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _regi
+_regi:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,264
+mov dword ptr (-252)[ebp],0
+mov dword ptr (-168)[ebp],1
+mov dword ptr (-172)[ebp],2
+mov dword ptr (-176)[ebp],3
+mov dword ptr (-4)[ebp],4
+mov dword ptr (-180)[ebp],5
+mov dword ptr (-8)[ebp],6
+mov dword ptr (-184)[ebp],7
+mov dword ptr (-12)[ebp],8
+mov dword ptr (-188)[ebp],9
+mov dword ptr (-16)[ebp],10
+mov dword ptr (-192)[ebp],11
+mov dword ptr (-20)[ebp],12
+mov dword ptr (-196)[ebp],13
+mov dword ptr (-24)[ebp],14
+mov dword ptr (-200)[ebp],15
+mov dword ptr (-28)[ebp],16
+mov dword ptr (-204)[ebp],17
+mov dword ptr (-32)[ebp],18
+mov dword ptr (-208)[ebp],19
+mov dword ptr (-36)[ebp],20
+mov dword ptr (-212)[ebp],21
+mov dword ptr (-40)[ebp],22
+mov dword ptr (-216)[ebp],23
+mov dword ptr (-44)[ebp],24
+mov dword ptr (-220)[ebp],25
+mov dword ptr (-48)[ebp],26
+mov dword ptr (-224)[ebp],27
+mov dword ptr (-52)[ebp],28
+mov dword ptr (-228)[ebp],29
+mov dword ptr (-56)[ebp],30
+mov dword ptr (-232)[ebp],31
+mov dword ptr (-60)[ebp],32
+mov dword ptr (-236)[ebp],33
+mov dword ptr (-64)[ebp],34
+mov dword ptr (-240)[ebp],35
+mov dword ptr (-244)[ebp],36
+mov dword ptr (-248)[ebp],37
+mov dword ptr (-256)[ebp],38
+lea edi,(-168)[ebp]
+mov esi,4
+lea ebx,(-252)[ebp]
+mov edx,edi
+sub edx,ebx
+mov eax,edx
+cdq
+idiv esi
+mov dword ptr (-152)[ebp],eax
+lea ebx,(-172)[ebp]
+sub ebx,edi
+mov eax,ebx
+cdq
+idiv esi
+mov dword ptr (-148)[ebp],eax
+lea edi,(-176)[ebp]
+lea esi,(-172)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-144)[ebp],eax
+lea edi,(-180)[ebp]
+lea esi,(-176)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-140)[ebp],eax
+lea edi,(-184)[ebp]
+lea esi,(-180)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-136)[ebp],eax
+lea edi,(-188)[ebp]
+lea esi,(-184)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-132)[ebp],eax
+lea edi,(-192)[ebp]
+lea esi,(-188)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-128)[ebp],eax
+lea edi,(-196)[ebp]
+lea esi,(-192)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-124)[ebp],eax
+lea edi,(-200)[ebp]
+lea esi,(-196)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-120)[ebp],eax
+lea edi,(-204)[ebp]
+lea esi,(-200)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-116)[ebp],eax
+lea edi,(-208)[ebp]
+lea esi,(-204)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-112)[ebp],eax
+lea edi,(-212)[ebp]
+lea esi,(-208)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-108)[ebp],eax
+lea edi,(-216)[ebp]
+lea esi,(-212)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-104)[ebp],eax
+lea edi,(-220)[ebp]
+lea esi,(-216)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-100)[ebp],eax
+lea edi,(-224)[ebp]
+lea esi,(-220)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-96)[ebp],eax
+lea edi,(-228)[ebp]
+lea esi,(-224)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-92)[ebp],eax
+lea edi,(-232)[ebp]
+lea esi,(-228)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-88)[ebp],eax
+lea edi,(-236)[ebp]
+lea esi,(-232)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-84)[ebp],eax
+lea edi,(-240)[ebp]
+lea esi,(-236)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-80)[ebp],eax
+lea edi,(-244)[ebp]
+lea esi,(-240)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-76)[ebp],eax
+lea edi,(-248)[ebp]
+lea esi,(-244)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-72)[ebp],eax
+lea edi,(-256)[ebp]
+lea esi,(-248)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-68)[ebp],eax
+mov edi,dword ptr (-152)[ebp]
+mov dword ptr (-164)[ebp],edi
+mov dword ptr (-160)[ebp],1
+mov dword ptr (-156)[ebp],0
+L3090:
+mov edi,dword ptr (-160)[ebp]
+cmp edi,1
+je L3096
+cmp edi,2
+je L3099
+cmp edi,3
+je L3104
+jmp L3094
+L3096:
+mov edi,dword ptr (-156)[ebp]
+mov esi,dword ptr (-164)[ebp]
+cmp dword ptr (-152)[ebp][edi*4],esi
+je L3095
+mov edi,dword ptr (-156)[ebp]
+mov edi,dword ptr (-152)[ebp][edi*4]
+mov dword ptr (-264)[ebp],edi
+mov dword ptr (-160)[ebp],2
+mov dword ptr (-260)[ebp],1
+jmp L3095
+L3099:
+mov edi,dword ptr (-156)[ebp]
+mov esi,dword ptr (-164)[ebp]
+cmp dword ptr (-152)[ebp][edi*4],esi
+jne L3100
+mov dword ptr (-160)[ebp],3
+jmp L3095
+L3100:
+mov edi,dword ptr (-156)[ebp]
+mov esi,dword ptr (-264)[ebp]
+cmp dword ptr (-152)[ebp][edi*4],esi
+jne L3102
+inc dword ptr (-260)[ebp]
+jmp L3095
+L3102:
+mov dword ptr (-160)[ebp],4
+jmp L3095
+L3104:
+mov edi,dword ptr (-156)[ebp]
+mov esi,dword ptr (-164)[ebp]
+cmp dword ptr (-152)[ebp][edi*4],esi
+je L3095
+mov dword ptr (-160)[ebp],4
+L3094:
+L3095:
+L3091:
+inc dword ptr (-156)[ebp]
+cmp dword ptr (-156)[ebp],22
+jl L3090
+cmp dword ptr (-160)[ebp],3
+jne L3107
+mov edi,16
+mov eax,edi
+sub eax,dword ptr (-260)[ebp]
+jmp L3068
+L3107:
+mov eax,-1
+L3068:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _regp
+_regp:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,264
+lea edi,(-252)[ebp]
+mov dword ptr (-252)[ebp],edi
+lea edi,(-228)[ebp]
+mov dword ptr (-228)[ebp],edi
+lea edi,(-232)[ebp]
+mov dword ptr (-232)[ebp],edi
+lea edi,(-236)[ebp]
+mov dword ptr (-236)[ebp],edi
+lea edi,(-164)[ebp]
+mov dword ptr (-4)[ebp],edi
+lea edi,(-164)[ebp]
+mov dword ptr (-164)[ebp],edi
+lea edi,(-168)[ebp]
+mov dword ptr (-8)[ebp],edi
+lea edi,(-168)[ebp]
+mov dword ptr (-168)[ebp],edi
+lea edi,(-172)[ebp]
+mov dword ptr (-12)[ebp],edi
+lea edi,(-172)[ebp]
+mov dword ptr (-172)[ebp],edi
+lea edi,(-176)[ebp]
+mov dword ptr (-16)[ebp],edi
+lea edi,(-176)[ebp]
+mov dword ptr (-176)[ebp],edi
+lea edi,(-180)[ebp]
+mov dword ptr (-20)[ebp],edi
+lea edi,(-180)[ebp]
+mov dword ptr (-180)[ebp],edi
+lea edi,(-184)[ebp]
+mov dword ptr (-24)[ebp],edi
+lea edi,(-184)[ebp]
+mov dword ptr (-184)[ebp],edi
+lea edi,(-188)[ebp]
+mov dword ptr (-28)[ebp],edi
+lea edi,(-188)[ebp]
+mov dword ptr (-188)[ebp],edi
+lea edi,(-192)[ebp]
+mov dword ptr (-32)[ebp],edi
+lea edi,(-192)[ebp]
+mov dword ptr (-192)[ebp],edi
+lea edi,(-196)[ebp]
+mov dword ptr (-36)[ebp],edi
+lea edi,(-196)[ebp]
+mov dword ptr (-196)[ebp],edi
+lea edi,(-200)[ebp]
+mov dword ptr (-40)[ebp],edi
+lea edi,(-200)[ebp]
+mov dword ptr (-200)[ebp],edi
+lea edi,(-204)[ebp]
+mov dword ptr (-44)[ebp],edi
+lea edi,(-204)[ebp]
+mov dword ptr (-204)[ebp],edi
+lea edi,(-208)[ebp]
+mov dword ptr (-48)[ebp],edi
+lea edi,(-208)[ebp]
+mov dword ptr (-208)[ebp],edi
+lea edi,(-212)[ebp]
+mov dword ptr (-52)[ebp],edi
+lea edi,(-212)[ebp]
+mov dword ptr (-212)[ebp],edi
+lea edi,(-216)[ebp]
+mov dword ptr (-56)[ebp],edi
+lea edi,(-216)[ebp]
+mov dword ptr (-216)[ebp],edi
+lea edi,(-220)[ebp]
+mov dword ptr (-60)[ebp],edi
+lea edi,(-220)[ebp]
+mov dword ptr (-220)[ebp],edi
+lea edi,(-224)[ebp]
+mov dword ptr (-64)[ebp],edi
+lea edi,(-224)[ebp]
+mov dword ptr (-224)[ebp],edi
+lea edi,(-240)[ebp]
+mov dword ptr (-240)[ebp],edi
+lea edi,(-244)[ebp]
+mov dword ptr (-244)[ebp],edi
+lea edi,(-256)[ebp]
+mov dword ptr (-256)[ebp],edi
+lea edi,(-228)[ebp]
+mov esi,4
+lea ebx,(-252)[ebp]
+mov edx,edi
+sub edx,ebx
+mov eax,edx
+cdq
+idiv esi
+mov dword ptr (-152)[ebp],eax
+lea ebx,(-232)[ebp]
+sub ebx,edi
+mov eax,ebx
+cdq
+idiv esi
+mov dword ptr (-148)[ebp],eax
+lea edi,(-236)[ebp]
+lea esi,(-232)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-144)[ebp],eax
+lea edi,(-164)[ebp]
+lea esi,(-236)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-140)[ebp],eax
+lea edi,(-168)[ebp]
+lea esi,(-164)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-136)[ebp],eax
+lea edi,(-172)[ebp]
+lea esi,(-168)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-132)[ebp],eax
+lea edi,(-176)[ebp]
+lea esi,(-172)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-128)[ebp],eax
+lea edi,(-180)[ebp]
+lea esi,(-176)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-124)[ebp],eax
+lea edi,(-184)[ebp]
+lea esi,(-180)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-120)[ebp],eax
+lea edi,(-188)[ebp]
+lea esi,(-184)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-116)[ebp],eax
+lea edi,(-192)[ebp]
+lea esi,(-188)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-112)[ebp],eax
+lea edi,(-196)[ebp]
+lea esi,(-192)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-108)[ebp],eax
+lea edi,(-200)[ebp]
+lea esi,(-196)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-104)[ebp],eax
+lea edi,(-204)[ebp]
+lea esi,(-200)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-100)[ebp],eax
+lea edi,(-208)[ebp]
+lea esi,(-204)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-96)[ebp],eax
+lea edi,(-212)[ebp]
+lea esi,(-208)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-92)[ebp],eax
+lea edi,(-216)[ebp]
+lea esi,(-212)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-88)[ebp],eax
+lea edi,(-220)[ebp]
+lea esi,(-216)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-84)[ebp],eax
+lea edi,(-224)[ebp]
+lea esi,(-220)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-80)[ebp],eax
+lea edi,(-240)[ebp]
+lea esi,(-224)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-76)[ebp],eax
+lea edi,(-244)[ebp]
+lea esi,(-240)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-72)[ebp],eax
+lea edi,(-256)[ebp]
+lea esi,(-244)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+mov dword ptr (-68)[ebp],eax
+mov edi,dword ptr (-152)[ebp]
+mov dword ptr (-248)[ebp],edi
+mov dword ptr (-160)[ebp],1
+mov dword ptr (-156)[ebp],0
+L3131:
+mov edi,dword ptr (-160)[ebp]
+cmp edi,1
+je L3137
+cmp edi,2
+je L3140
+cmp edi,3
+je L3145
+jmp L3135
+L3137:
+mov edi,dword ptr (-156)[ebp]
+mov esi,dword ptr (-248)[ebp]
+cmp dword ptr (-152)[ebp][edi*4],esi
+je L3136
+mov edi,dword ptr (-156)[ebp]
+mov edi,dword ptr (-152)[ebp][edi*4]
+mov dword ptr (-264)[ebp],edi
+mov dword ptr (-160)[ebp],2
+mov dword ptr (-260)[ebp],1
+jmp L3136
+L3140:
+mov edi,dword ptr (-156)[ebp]
+mov esi,dword ptr (-248)[ebp]
+cmp dword ptr (-152)[ebp][edi*4],esi
+jne L3141
+mov dword ptr (-160)[ebp],3
+jmp L3136
+L3141:
+mov edi,dword ptr (-156)[ebp]
+mov esi,dword ptr (-264)[ebp]
+cmp dword ptr (-152)[ebp][edi*4],esi
+jne L3143
+inc dword ptr (-260)[ebp]
+jmp L3136
+L3143:
+mov dword ptr (-160)[ebp],4
+jmp L3136
+L3145:
+mov edi,dword ptr (-156)[ebp]
+mov esi,dword ptr (-248)[ebp]
+cmp dword ptr (-152)[ebp][edi*4],esi
+je L3136
+mov dword ptr (-160)[ebp],4
+L3135:
+L3136:
+L3132:
+inc dword ptr (-156)[ebp]
+cmp dword ptr (-156)[ebp],22
+jl L3131
+cmp dword ptr (-160)[ebp],3
+jne L3148
+mov edi,16
+mov eax,edi
+sub eax,dword ptr (-260)[ebp]
+jmp L3109
+L3148:
+mov eax,-1
+L3109:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 4
+L3151 label byte
+db 420 dup (0)
+_DATA ends
+_DATA segment
+align 1
+L3152 label byte
+db 115
+db 56
+db 52
+db 44
+db 101
+db 114
+db 37
+db 100
+db 10
+db 0
+align 1
+L3153 label byte
+db 115
+db 56
+db 52
+db 32
+db 32
+db 32
+db 32
+db 0
+public _s84
+_DATA ends
+_TEXT segment
+_s84:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,172
+lea edi,(L3153)
+mov dword ptr (-156)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+lea edi,(60)[edi]
+mov dword ptr (-160)[ebp],edi
+mov dword ptr (-164)[ebp],0
+L3154:
+L3155:
+mov edi,dword ptr (-160)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-160)[ebp],esi
+mov esi,dword ptr (-156)[ebp]
+lea ebx,(1)[esi]
+mov dword ptr (-156)[ebp],ebx
+mov bl,byte ptr [esi]
+mov byte ptr [edi],bl
+movsx edi,bl
+cmp edi,0
+jne L3154
+push 3
+call _fip
+add esp,4
+mov dword ptr (-168)[ebp],eax
+mov edi,dword ptr (-168)[ebp]
+cmp dword ptr [edi],3
+je L3157
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L3159
+push 1
+lea edi,(L3152)
+push edi
+call _printf
+add esp,8
+L3159:
+inc dword ptr (-164)[ebp]
+L3157:
+lea edi,(_glork)
+mov dword ptr (-172)[ebp],edi
+push 4
+call dword ptr (-172)[ebp]
+add esp,4
+cmp eax,4
+je L3161
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L3163
+push 2
+lea edi,(L3152)
+push edi
+call _printf
+add esp,8
+L3163:
+add dword ptr (-164)[ebp],2
+L3161:
+mov dword ptr (-8)[ebp],0
+L3165:
+mov edi,dword ptr (-8)[ebp]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fstp dword ptr (-80)[ebp][edi*4]
+mov edi,dword ptr (-8)[ebp]
+lea edi,[edi*4]
+lea esi,(-80)[ebp][edi]
+mov dword ptr (-148)[ebp][edi],esi
+L3166:
+inc dword ptr (-8)[ebp]
+cmp dword ptr (-8)[ebp],17
+jl L3165
+fld dword ptr (L412)
+fstp dword ptr (-152)[ebp]
+mov dword ptr (-8)[ebp],0
+L3169:
+fld dword ptr (-152)[ebp]
+mov edi,dword ptr (-8)[ebp]
+mov edi,dword ptr (-148)[ebp][edi*4]
+fadd dword ptr [edi]
+fstp dword ptr (-152)[ebp]
+L3170:
+inc dword ptr (-8)[ebp]
+cmp dword ptr (-8)[ebp],17
+jl L3169
+fld dword ptr (L3175)
+fcomp dword ptr (-152)[ebp]
+fstsw ax
+sahf
+je L3173
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L3176
+push 4
+lea edi,(L3152)
+push edi
+call _printf
+add esp,8
+L3176:
+add dword ptr (-164)[ebp],4
+L3173:
+mov dword ptr (-12)[ebp],0
+L3178:
+mov dword ptr (-8)[ebp],0
+L3182:
+mov dword ptr (-4)[ebp],0
+L3186:
+mov edi,dword ptr (-4)[ebp]
+mov esi,dword ptr (-8)[ebp]
+mov ebx,dword ptr (-12)[ebp]
+imul edx,esi,28
+imul ecx,ebx,140
+lea edx,(L3151)[ecx][edx]
+imul ebx,ebx,35
+imul esi,esi,7
+lea esi,[esi][ebx]
+lea esi,[edi][esi]
+mov dword ptr [edx][edi*4],esi
+L3187:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],7
+jl L3186
+L3183:
+inc dword ptr (-8)[ebp]
+cmp dword ptr (-8)[ebp],5
+jl L3182
+L3179:
+inc dword ptr (-12)[ebp]
+cmp dword ptr (-12)[ebp],3
+jl L3178
+mov dword ptr (-12)[ebp],1
+mov dword ptr (-8)[ebp],2
+mov dword ptr (-4)[ebp],3
+push 0
+push 105
+lea edi,(L3151)
+push edi
+call _array
+add esp,12
+mov edi,eax
+push 35
+push 35
+imul esi,dword ptr (-12)[ebp],140
+lea esi,(L3151)[esi]
+push esi
+call _array
+add esp,12
+mov esi,eax
+push 49
+push 7
+imul ebx,dword ptr (-8)[ebp],28
+imul edx,dword ptr (-12)[ebp],140
+lea ebx,(L3151)[edx][ebx]
+push ebx
+call _array
+add esp,12
+lea edi,[esi][edi]
+lea edi,[eax][edi]
+mov esi,dword ptr (-4)[ebp]
+imul ebx,dword ptr (-8)[ebp],28
+imul edx,dword ptr (-12)[ebp],140
+lea ebx,(L3151)[edx][ebx]
+mov esi,dword ptr [ebx][esi*4]
+lea edi,[esi][edi]
+sub edi,52
+cmp edi,0
+je L3190
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L3192
+push 8
+lea edi,(L3152)
+push edi
+call _printf
+add esp,8
+L3192:
+add dword ptr (-164)[ebp],8
+L3190:
+mov eax,dword ptr (-164)[ebp]
+L3150:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _array
+_array:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,4
+mov dword ptr (-4)[ebp],0
+jmp L3198
+L3195:
+mov edi,dword ptr (-4)[ebp]
+mov esi,dword ptr (20)[ebp]
+mov ebx,dword ptr (28)[ebp]
+lea ebx,[ebx][edi]
+cmp dword ptr [esi][edi*4],ebx
+je L3199
+mov eax,1
+jmp L3194
+L3199:
+L3196:
+inc dword ptr (-4)[ebp]
+L3198:
+mov edi,dword ptr (24)[ebp]
+cmp dword ptr (-4)[ebp],edi
+jl L3195
+mov eax,0
+L3194:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 4
+L3202 label byte
+db 4 dup (0)
+public _fip
+_DATA ends
+_TEXT segment
+_fip:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+lea edi,(L3202)
+mov esi,dword ptr (20)[ebp]
+mov dword ptr (L3202),esi
+mov eax,edi
+L3201:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _glork
+_glork:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov eax,dword ptr (20)[ebp]
+L3203:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 1
+L3205 label byte
+db 115
+db 56
+db 53
+db 44
+db 101
+db 114
+db 37
+db 100
+db 10
+db 0
+align 1
+L3206 label byte
+db 115
+db 56
+db 53
+db 32
+db 32
+db 32
+db 32
+db 0
+align 4
+L3214 label byte
+dd L425
+dd L427
+dd L426
+dd L428
+dd L429
+dd L430
+dd L431
+align 1
+L3215 label byte
+db 32
+db 97
+db 108
+db 105
+db 103
+db 110
+db 109
+db 101
+db 110
+db 116
+db 58
+db 32
+db 0
+public _s85
+_DATA ends
+_TEXT segment
+_s85:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,404
+lea edi,(L3206)
+mov dword ptr (-276)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+lea edi,(60)[edi]
+mov dword ptr (-280)[ebp],edi
+mov dword ptr (-320)[ebp],0
+L3219:
+L3220:
+mov edi,dword ptr (-280)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-280)[ebp],esi
+mov esi,dword ptr (-276)[ebp]
+lea ebx,(1)[esi]
+mov dword ptr (-276)[ebp],ebx
+mov bl,byte ptr [esi]
+mov byte ptr [edi],bl
+movsx edi,bl
+cmp edi,0
+jne L3219
+lea edi,(-296)[ebp]
+lea esi,(-316)[ebp]
+sub edi,esi
+cmp edi,0
+jle L3230
+lea edi,(-292)[ebp]
+lea esi,(-296)[ebp]
+sub edi,esi
+cmp edi,0
+jle L3230
+lea edi,(-288)[ebp]
+lea esi,(-292)[ebp]
+sub edi,esi
+cmp edi,0
+jg L3222
+L3230:
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L3231
+push 1
+lea edi,(L3205)
+push edi
+call _printf
+add esp,8
+L3231:
+inc dword ptr (-320)[ebp]
+L3222:
+lea edi,(-355)[ebp]
+lea esi,(-356)[ebp]
+sub edi,esi
+mov dword ptr (-272)[ebp],edi
+lea edi,(-358)[ebp]
+lea esi,(-360)[ebp]
+sub edi,esi
+mov dword ptr (-268)[ebp],edi
+lea edi,(-364)[ebp]
+lea esi,(-368)[ebp]
+sub edi,esi
+mov dword ptr (-264)[ebp],edi
+lea edi,(-372)[ebp]
+lea esi,(-376)[ebp]
+sub edi,esi
+mov dword ptr (-260)[ebp],edi
+lea edi,(-380)[ebp]
+lea esi,(-384)[ebp]
+sub edi,esi
+mov dword ptr (-256)[ebp],edi
+lea edi,(-388)[ebp]
+lea esi,(-392)[ebp]
+sub edi,esi
+mov dword ptr (-252)[ebp],edi
+lea edi,(-400)[ebp]
+lea esi,(-404)[ebp]
+sub edi,esi
+mov dword ptr (-248)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (40)[edi],0
+je L3246
+mov dword ptr (-244)[ebp],0
+L3248:
+mov edi,dword ptr (-244)[ebp]
+lea edi,[edi*4]
+mov esi,dword ptr (-272)[ebp][edi]
+push esi
+lea esi,(L3215)
+push esi
+mov edi,dword ptr (L3214)[edi]
+push edi
+lea edi,(L3252)
+push edi
+call _printf
+add esp,16
+L3249:
+inc dword ptr (-244)[ebp]
+cmp dword ptr (-244)[ebp],7
+jl L3248
+L3246:
+mov edi,dword ptr (-284)[ebp]
+or edi,56
+mov dword ptr (-284)[ebp],edi
+mov edi,dword ptr (-284)[ebp]
+mov esi,edi
+and esi,0fffffffcH
+sal edi,26
+sar edi,29
+sal edi,30
+sar edi,30
+and edi,3
+or esi,edi
+mov dword ptr (-284)[ebp],esi
+mov edi,dword ptr (-284)[ebp]
+mov esi,edi
+and esi,0ffffffc7H
+sal edi,30
+sar edi,30
+sal edi,29
+sar edi,29
+lea edi,[edi*8]
+and edi,56
+or esi,edi
+mov dword ptr (-284)[ebp],esi
+mov edi,dword ptr (-284)[ebp]
+sal edi,26
+sar edi,29
+cmp edi,3
+je L3253
+mov edi,dword ptr (-284)[ebp]
+sal edi,26
+sar edi,29
+cmp edi,-1
+jne L3255
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (40)[edi],0
+je L3256
+lea edi,(L3259)
+push edi
+call _printf
+add esp,4
+jmp L3256
+L3255:
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L3260
+push 2
+lea edi,(L3205)
+push edi
+call _printf
+add esp,8
+L3260:
+add dword ptr (-320)[ebp],2
+L3256:
+L3253:
+mov edi,dword ptr (-284)[ebp]
+or edi,64
+mov dword ptr (-284)[ebp],edi
+mov edi,dword ptr (-284)[ebp]
+sal edi,25
+sar edi,31
+cmp edi,1
+je L3262
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (40)[edi],0
+je L3264
+lea edi,(L3266)
+push edi
+call _printf
+add esp,4
+L3264:
+L3262:
+lea edi,(-240)[ebp]
+mov esi,edi
+sub esi,edi
+cmp esi,0
+jne L3274
+cmp esi,0
+jne L3274
+cmp esi,0
+jne L3274
+cmp esi,0
+jne L3274
+cmp esi,0
+jne L3274
+cmp esi,0
+jne L3274
+cmp esi,0
+je L3267
+L3274:
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L3275
+push 4
+lea edi,(L3205)
+push edi
+call _printf
+add esp,8
+L3275:
+add dword ptr (-320)[ebp],4
+L3267:
+jmp L3277
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L3279
+push 8
+lea edi,(L3205)
+push edi
+call _printf
+add esp,8
+L3279:
+add dword ptr (-320)[ebp],8
+L3277:
+lea edi,(-352)[ebp]
+mov dword ptr (-288)[ebp],edi
+mov byte ptr (-352)[ebp],2
+mov edi,dword ptr (-288)[ebp]
+movsx esi,byte ptr [edi]
+lea esi,(1)[esi]
+mov ebx,esi
+mov byte ptr [edi],bl
+movsx edi,byte ptr (-352)[ebp]
+cmp edi,3
+je L3283
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L3285
+push 16
+lea edi,(L3205)
+push edi
+call _printf
+add esp,8
+L3285:
+add dword ptr (-320)[ebp],16
+L3283:
+mov eax,dword ptr (-320)[ebp]
+L3204:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 1
+L3288 label byte
+db 115
+db 56
+db 54
+db 44
+db 101
+db 114
+db 37
+db 100
+db 10
+db 0
+align 1
+L3289 label byte
+db 115
+db 56
+db 54
+db 32
+db 32
+db 32
+db 32
+db 0
+align 4
+L3290 label byte
+dd 1
+dd 3
+dd 5
+align 4
+L3291 label byte
+dd L3290+8
+_DATA ends
+_DATA segment
+align 4
+L3293 label byte
+db 40 dup (0)
+_DATA ends
+_DATA segment
+align 4
+L3294 label byte
+dd 03f800000H
+dd 040400000H
+dd 040a00000H
+dd 040000000H
+dd 040800000H
+dd 040c00000H
+dd 040400000H
+dd 040a00000H
+dd 040e00000H
+dd 00H
+dd 00H
+dd 00H
+align 4
+L3295 label byte
+dd 03f800000H
+dd 040400000H
+dd 040a00000H
+dd 040000000H
+dd 040800000H
+dd 040c00000H
+dd 040400000H
+dd 040a00000H
+dd 040e00000H
+db 12 dup (0)
+align 4
+L3296 label byte
+dd 03f800000H
+dd 040400000H
+dd 040a00000H
+dd 040000000H
+dd 040800000H
+dd 040c00000H
+dd 040400000H
+dd 040a00000H
+dd 040e00000H
+db 12 dup (0)
+align 4
+L3297 label byte
+dd 03f800000H
+db 8 dup (0)
+dd 040000000H
+db 8 dup (0)
+dd 040400000H
+db 8 dup (0)
+dd 040800000H
+db 8 dup (0)
+public _s86
+_DATA ends
+_TEXT segment
+_s86:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,40
+mov edi,dword ptr (L3291)
+lea edi,(-4)[edi]
+mov dword ptr (-36)[ebp],edi
+call _one
+add esp,0
+mov esi,dword ptr (-36)[ebp]
+lea edi,[esi][eax*4]
+mov dword ptr (-4)[ebp],edi
+lea edi,(L3289)
+mov dword ptr (-24)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+lea edi,(60)[edi]
+mov dword ptr (-28)[ebp],edi
+mov dword ptr (-32)[ebp],0
+L3298:
+L3299:
+mov edi,dword ptr (-28)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-28)[ebp],esi
+mov esi,dword ptr (-24)[ebp]
+lea ebx,(1)[esi]
+mov dword ptr (-24)[ebp],ebx
+mov bl,byte ptr [esi]
+mov byte ptr [edi],bl
+movsx edi,bl
+cmp edi,0
+jne L3298
+mov edi,dword ptr (L3291)
+cmp dword ptr [edi],5
+je L3301
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L3303
+push 1
+lea edi,(L3288)
+push edi
+call _printf
+add esp,8
+L3303:
+inc dword ptr (-32)[ebp]
+L3301:
+mov edi,dword ptr (-36)[ebp]
+cmp dword ptr [edi],3
+je L3305
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L3307
+push 2
+lea edi,(L3288)
+push edi
+call _printf
+add esp,8
+L3307:
+add dword ptr (-32)[ebp],2
+L3305:
+mov edi,dword ptr (-4)[ebp]
+cmp dword ptr [edi],5
+je L3309
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L3311
+push 4
+lea edi,(L3288)
+push edi
+call _printf
+add esp,8
+L3311:
+add dword ptr (-32)[ebp],4
+L3309:
+mov dword ptr (-20)[ebp],0
+mov dword ptr (-8)[ebp],0
+L3313:
+mov edi,dword ptr (-8)[ebp]
+cmp dword ptr (L3293)[edi*4],0
+je L3317
+mov dword ptr (-20)[ebp],1
+L3317:
+L3314:
+inc dword ptr (-8)[ebp]
+cmp dword ptr (-8)[ebp],10
+jl L3313
+cmp dword ptr (-20)[ebp],0
+je L3319
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L3321
+push 8
+lea edi,(L3288)
+push edi
+call _printf
+add esp,8
+L3321:
+add dword ptr (-32)[ebp],8
+L3319:
+mov dword ptr (-20)[ebp],0
+mov dword ptr (-12)[ebp],0
+L3323:
+mov dword ptr (-8)[ebp],0
+L3327:
+imul edi,dword ptr (-12)[ebp],3
+mov esi,dword ptr (-8)[ebp]
+lea edi,[esi][edi]
+mov dword ptr (-16)[ebp],edi
+mov edi,dword ptr (-8)[ebp]
+lea edi,[edi*4]
+imul esi,dword ptr (-12)[ebp],12
+fld dword ptr (L3295)[esi][edi]
+fstp dword ptr (-40)[ebp]
+fld dword ptr (L3296)[esi][edi]
+fcomp dword ptr (-40)[ebp]
+fstsw ax
+sahf
+jne L3333
+mov edi,dword ptr (-16)[ebp]
+fld dword ptr (L3294)[edi*4]
+fcomp dword ptr (-40)[ebp]
+fstsw ax
+sahf
+je L3331
+L3333:
+mov dword ptr (-20)[ebp],1
+L3331:
+L3328:
+inc dword ptr (-8)[ebp]
+cmp dword ptr (-8)[ebp],3
+jl L3327
+L3324:
+inc dword ptr (-12)[ebp]
+cmp dword ptr (-12)[ebp],4
+jl L3323
+cmp dword ptr (-20)[ebp],0
+je L3334
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L3336
+push 16
+lea edi,(L3288)
+push edi
+call _printf
+add esp,8
+L3336:
+add dword ptr (-32)[ebp],16
+L3334:
+mov dword ptr (-20)[ebp],0
+mov dword ptr (-8)[ebp],0
+L3338:
+mov edi,dword ptr (-8)[ebp]
+imul esi,edi,12
+lea edi,(1)[edi]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fcomp dword ptr (L3297)[esi]
+fstsw ax
+sahf
+je L3342
+mov dword ptr (-20)[ebp],1
+L3342:
+L3339:
+inc dword ptr (-8)[ebp]
+cmp dword ptr (-8)[ebp],4
+jl L3338
+cmp dword ptr (-20)[ebp],0
+je L3344
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L3346
+push 32
+lea edi,(L3288)
+push edi
+call _printf
+add esp,8
+L3346:
+add dword ptr (-32)[ebp],32
+L3344:
+mov eax,dword ptr (-32)[ebp]
+L3287:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _one
+_one:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov eax,1
+L3348:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 1
+L3350 label byte
+db 115
+db 56
+db 56
+db 44
+db 101
+db 114
+db 37
+db 100
+db 10
+db 0
+align 1
+L3351 label byte
+db 115
+db 56
+db 56
+db 32
+db 32
+db 32
+db 32
+db 0
+public _s88
+_DATA ends
+_TEXT segment
+_s88:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,44
+lea edi,(L3351)
+mov dword ptr (-4)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+lea edi,(60)[edi]
+mov dword ptr (-8)[ebp],edi
+mov dword ptr (-12)[ebp],0
+L3353:
+L3354:
+mov edi,dword ptr (-8)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-8)[ebp],esi
+mov esi,dword ptr (-4)[ebp]
+lea ebx,(1)[esi]
+mov dword ptr (-4)[ebp],ebx
+mov bl,byte ptr [esi]
+mov byte ptr [edi],bl
+movsx edi,bl
+cmp edi,0
+jne L3353
+jmp L3356
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L3358
+push 1
+lea edi,(L3350)
+push edi
+call _printf
+add esp,8
+L3358:
+inc dword ptr (-12)[ebp]
+L3356:
+lea edi,(-32)[ebp]
+mov dword ptr (_metricp),edi
+mov dword ptr (-32)[ebp],2
+mov edi,dword ptr (_metricp)
+mov dword ptr [edi],3
+cmp dword ptr (-32)[ebp],3
+je L3360
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L3362
+push 2
+lea edi,(L3350)
+push edi
+call _printf
+add esp,8
+L3362:
+add dword ptr (-12)[ebp],2
+L3360:
+fld qword ptr (L419)
+fstp qword ptr (-28)[ebp]
+fld qword ptr (L419)
+fstp qword ptr (-20)[ebp]
+lea edi,(-28)[ebp]
+mov dword ptr (-36)[ebp],edi
+mov edi,dword ptr (-36)[ebp]
+fld qword ptr (L418)
+fstp qword ptr [edi]
+mov edi,dword ptr (-36)[ebp]
+fld qword ptr (L418)
+fstp qword ptr (8)[edi]
+fld qword ptr (-28)[ebp]
+fadd qword ptr (-20)[ebp]
+fld qword ptr (L416)
+fcompp
+fstsw ax
+sahf
+je L3365
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L3368
+push 4
+lea edi,(L3350)
+push edi
+call _printf
+add esp,8
+L3368:
+add dword ptr (-12)[ebp],4
+L3365:
+mov eax,dword ptr (-12)[ebp]
+L3349:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 1
+L3371 label byte
+db 115
+db 57
+db 44
+db 101
+db 114
+db 37
+db 100
+db 10
+db 0
+align 1
+L3372 label byte
+db 115
+db 57
+db 32
+db 32
+db 32
+db 32
+db 32
+db 0
+public _s9
+_DATA ends
+_TEXT segment
+_s9:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,36
+lea edi,(L3372)
+mov dword ptr (-12)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+lea edi,(60)[edi]
+mov dword ptr (-16)[ebp],edi
+mov dword ptr (-20)[ebp],0
+L3373:
+L3374:
+mov edi,dword ptr (-16)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-16)[ebp],esi
+mov esi,dword ptr (-12)[ebp]
+lea ebx,(1)[esi]
+mov dword ptr (-12)[ebp],ebx
+mov bl,byte ptr [esi]
+mov byte ptr [edi],bl
+movsx edi,bl
+cmp edi,0
+jne L3373
+mov dword ptr (-8)[ebp],0
+mov dword ptr (-4)[ebp],0
+L3376:
+mov dword ptr (-24)[ebp],2
+mov dword ptr (-28)[ebp],2
+mov dword ptr (-32)[ebp],3
+mov dword ptr (-36)[ebp],3
+cmp dword ptr (-36)[ebp],3
+jne L3382
+cmp dword ptr (-32)[ebp],3
+je L3380
+L3382:
+mov dword ptr (-8)[ebp],1
+L3380:
+cmp dword ptr (-28)[ebp],2
+jne L3385
+cmp dword ptr (-24)[ebp],2
+je L3383
+L3385:
+mov dword ptr (-8)[ebp],1
+L3383:
+L3377:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],2
+jl L3376
+cmp dword ptr (-8)[ebp],0
+je L3390
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L3388
+push 1
+lea edi,(L3371)
+push edi
+call _printf
+add esp,8
+L3388:
+inc dword ptr (-20)[ebp]
+jmp L3390
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr (44)[edi],0
+je L3391
+push 2
+lea edi,(L3371)
+push edi
+call _printf
+add esp,8
+L3391:
+add dword ptr (-20)[ebp],2
+L3390:
+mov eax,dword ptr (-20)[ebp]
+L3370:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _setev
+_setev:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov dword ptr (_extvar),1066
+mov eax,0
+L3393:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+extrn _printf:near
+_TEXT segment
+_TEXT ends
+_DATA segment
+public _rfs
+align 1
+_rfs label byte
+db 8 dup (0)
+public _crc
+align 4
+_crc label byte
+db 4 dup (0)
+public _rrc
+align 4
+_rrc label byte
+db 4 dup (0)
+public _flgl
+align 4
+_flgl label byte
+db 4 dup (0)
+public _flgd
+align 4
+_flgd label byte
+db 4 dup (0)
+public _flgm
+align 4
+_flgm label byte
+db 4 dup (0)
+public _flgs
+align 4
+_flgs label byte
+db 4 dup (0)
+public _dprec
+align 4
+_dprec label byte
+db 4 dup (0)
+public _fprec
+align 4
+_fprec label byte
+db 4 dup (0)
+public _dbits
+align 4
+_dbits label byte
+db 4 dup (0)
+public _fbits
+align 4
+_fbits label byte
+db 4 dup (0)
+public _ubits
+align 4
+_ubits label byte
+db 4 dup (0)
+public _lbits
+align 4
+_lbits label byte
+db 4 dup (0)
+public _metricp
+align 4
+_metricp label byte
+db 4 dup (0)
+public _extvar
+align 4
+_extvar label byte
+db 4 dup (0)
+_DATA ends
+_TEXT segment
+align 1
+L3266 label byte
+db 66
+db 101
+db 32
+db 101
+db 115
+db 112
+db 101
+db 99
+db 105
+db 97
+db 108
+db 108
+db 121
+db 32
+db 99
+db 97
+db 114
+db 101
+db 102
+db 117
+db 108
+db 32
+db 119
+db 105
+db 116
+db 104
+db 32
+db 49
+db 45
+db 98
+db 105
+db 116
+db 32
+db 102
+db 105
+db 101
+db 108
+db 100
+db 115
+db 33
+db 10
+db 0
+align 1
+L3259 label byte
+db 83
+db 105
+db 103
+db 110
+db 32
+db 101
+db 120
+db 116
+db 101
+db 110
+db 115
+db 105
+db 111
+db 110
+db 32
+db 105
+db 110
+db 32
+db 102
+db 105
+db 101
+db 108
+db 100
+db 115
+db 10
+db 0
+align 1
+L3252 label byte
+db 37
+db 115
+db 37
+db 115
+db 37
+db 100
+db 10
+db 0
+align 4
+L3175 label byte
+dd 043080000H
+align 1
+L3022 label byte
+db 112
+db 111
+db 105
+db 110
+db 116
+db 101
+db 114
+db 0
+align 1
+L2472 label byte
+db 73
+db 110
+db 99
+db 114
+db 101
+db 97
+db 115
+db 105
+db 110
+db 103
+db 32
+db 97
+db 114
+db 114
+db 97
+db 121
+db 32
+db 101
+db 108
+db 101
+db 109
+db 101
+db 110
+db 116
+db 115
+db 32
+db 97
+db 115
+db 115
+db 105
+db 103
+db 110
+db 101
+db 100
+db 32
+db 116
+db 111
+db 32
+db 100
+db 101
+db 99
+db 114
+db 101
+db 97
+db 115
+db 105
+db 110
+db 103
+db 32
+db 108
+db 111
+db 99
+db 97
+db 116
+db 105
+db 111
+db 110
+db 115
+db 10
+db 0
+align 4
+L2356 label byte
+dd 041d00000H
+align 4
+L2355 label byte
+dd 00H
+dd 0403a0000H
+align 4
+L1659 label byte
+dd 00H
+dd 040040000H
+align 4
+L1484 label byte
+dd 00H
+dd 040240000H
+align 4
+L1455 label byte
+dd 041200000H
+align 4
+L1280 label byte
+dd 00H
+dd 040080000H
+align 4
+L1251 label byte
+dd 040400000H
+align 4
+L1076 label byte
+dd 00H
+dd 0401c0000H
+align 4
+L1047 label byte
+dd 040e00000H
+align 4
+L870 label byte
+dd 00H
+dd 040140000H
+align 4
+L841 label byte
+dd 040a00000H
+align 4
+L836 label byte
+dd 00H
+dd 041e00000H
+align 4
+L828 label byte
+dd 04f000000H
+align 1
+L653 label byte
+db 113
+db 117
+db 101
+db 101
+db 112
+db 0
+align 1
+L639 label byte
+db 10
+db 0
+align 1
+L638 label byte
+db 37
+db 100
+db 0
+align 1
+L633 label byte
+db 32
+db 32
+db 32
+db 107
+db 101
+db 121
+db 61
+db 0
+align 4
+L596 label byte
+dd 00H
+dd 040000000H
+align 4
+L536 label byte
+dd 00H
+dd 040ce8480H
+align 4
+L535 label byte
+dd 00H
+dd 0405f4000H
+align 4
+L534 label byte
+dd 042fa0000H
+align 4
+L529 label byte
+dd 040000000H
+align 1
+L431 label byte
+db 100
+db 111
+db 117
+db 98
+db 108
+db 101
+db 0
+align 1
+L430 label byte
+db 102
+db 108
+db 111
+db 97
+db 116
+db 0
+align 1
+L429 label byte
+db 117
+db 110
+db 115
+db 105
+db 103
+db 110
+db 101
+db 100
+db 0
+align 1
+L428 label byte
+db 108
+db 111
+db 110
+db 103
+db 0
+align 1
+L427 label byte
+db 115
+db 104
+db 111
+db 114
+db 116
+db 0
+align 1
+L426 label byte
+db 105
+db 110
+db 116
+db 0
+align 1
+L425 label byte
+db 99
+db 104
+db 97
+db 114
+db 0
+align 4
+L419 label byte
+dd 00H
+dd 00H
+align 4
+L418 label byte
+dd 00H
+dd 03ff00000H
+align 4
+L417 label byte
+dd 00H
+dd 040100000H
+align 4
+L416 label byte
+dd 00H
+dd 040000000H
+align 4
+L412 label byte
+dd 00H
+align 4
+L411 label byte
+dd 03f800000H
+align 1
+L390 label byte
+db 113
+db 117
+db 101
+db 101
+db 112
+db 33
+db 0
+align 1
+L379 label byte
+db 10
+db 9
+db 8
+db 13
+db 12
+db 92
+db 39
+db 0
+align 1
+L375 label byte
+db 46
+db 34
+db 46
+db 0
+align 1
+L362 label byte
+db 46
+db 46
+db 46
+db 0
+align 4
+L333 label byte
+dd 00H
+dd 040938800H
+align 1
+L199 label byte
+db 32
+db 32
+db 32
+db 100
+db 105
+db 102
+db 102
+db 101
+db 114
+db 101
+db 110
+db 116
+db 32
+db 114
+db 101
+db 115
+db 117
+db 108
+db 116
+db 115
+db 32
+db 119
+db 104
+db 101
+db 110
+db 32
+db 97
+db 115
+db 115
+db 105
+db 103
+db 110
+db 101
+db 100
+db 32
+db 116
+db 111
+db 32
+db 108
+db 111
+db 110
+db 103
+db 115
+db 46
+db 10
+db 0
+align 1
+L198 label byte
+db 68
+db 101
+db 99
+db 105
+db 109
+db 97
+db 108
+db 32
+db 97
+db 110
+db 100
+db 32
+db 111
+db 99
+db 116
+db 97
+db 108
+db 47
+db 104
+db 101
+db 120
+db 32
+db 99
+db 111
+db 110
+db 115
+db 116
+db 97
+db 110
+db 116
+db 115
+db 32
+db 115
+db 111
+db 109
+db 101
+db 116
+db 105
+db 109
+db 101
+db 115
+db 32
+db 103
+db 105
+db 118
+db 101
+db 10
+db 0
+align 1
+L27 label byte
+db 10
+db 70
+db 97
+db 105
+db 108
+db 101
+db 100
+db 46
+db 10
+db 0
+align 1
+L26 label byte
+db 10
+db 78
+db 111
+db 32
+db 101
+db 114
+db 114
+db 111
+db 114
+db 115
+db 32
+db 100
+db 101
+db 116
+db 101
+db 99
+db 116
+db 101
+db 100
+db 46
+db 10
+db 0
+align 1
+L20 label byte
+db 83
+db 101
+db 99
+db 116
+db 105
+db 111
+db 110
+db 32
+db 37
+db 115
+db 32
+db 114
+db 101
+db 116
+db 117
+db 114
+db 110
+db 101
+db 100
+db 32
+db 37
+db 100
+db 46
+db 10
+db 0
+_TEXT ends
+end
diff --git a/lcc/x86/win32/tst/cvt.1bk b/lcc/x86/win32/tst/cvt.1bk
new file mode 100755
index 0000000..74c79f1
--- /dev/null
+++ b/lcc/x86/win32/tst/cvt.1bk
@@ -0,0 +1,11 @@
+1 1 1 1 1 1 1 1 1.000000 1.000000 1.000000
+2 2 2 2 2 2 2 2 2.000000 2.000000 2.000000
+3 3 3 3 3 3 3 3 3.000000 3.000000 3.000000
+4 4 4 4 4 4 4 4 4.000000 4.000000 4.000000
+5 5 5 5 5 5 5 5 5.000000 5.000000 5.000000
+6 6 6 6 6 6 6 6 6.000000 6.000000 6.000000
+7 7 7 7 7 7 7 7 7.000000 7.000000 7.000000
+8 8 8 8 8 8 8 8 8.000000 8.000000 8.000000
+9 9 9 9 9 9 9 9 9.000000 9.000000 9.000000
+10 10 10 10 10 10 10 10 10.000000 10.000000 10.000000
+11 11 11 11 11 11 11 11 11.000000 11.000000 11.000000
diff --git a/lcc/x86/win32/tst/cvt.2bk b/lcc/x86/win32/tst/cvt.2bk
new file mode 100755
index 0000000..b3ab360
--- /dev/null
+++ b/lcc/x86/win32/tst/cvt.2bk
@@ -0,0 +1,2 @@
+tst/cvt.c:32: warning: conversion from `pointer to void function(void)' to `pointer to void' is compiler dependent
+tst/cvt.c:33: warning: conversion from `pointer to void' to `pointer to void function(void)' is compiler dependent
diff --git a/lcc/x86/win32/tst/cvt.sbk b/lcc/x86/win32/tst/cvt.sbk
new file mode 100755
index 0000000..341cfaf
--- /dev/null
+++ b/lcc/x86/win32/tst/cvt.sbk
@@ -0,0 +1,742 @@
+.486
+.model flat
+extrn __fltused:near
+extrn __ftol:near
+public _print
+_TEXT segment
+_print:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+fld qword ptr (_D)
+sub esp,8
+fstp qword ptr [esp]
+fld qword ptr (_d)
+sub esp,8
+fstp qword ptr [esp]
+fld dword ptr (_f)
+sub esp,8
+fstp qword ptr [esp]
+mov edi,dword ptr (_L)
+push edi
+mov edi,dword ptr (_I)
+push edi
+mov di,word ptr (_S)
+movzx edi,di
+push edi
+mov bl,byte ptr (_C)
+movzx edi,bl
+push edi
+mov edi,dword ptr (_l)
+push edi
+mov edi,dword ptr (_i)
+push edi
+movsx edi,word ptr (_s)
+push edi
+movsx edi,byte ptr (_c)
+push edi
+lea edi,(L2)
+push edi
+call _printf
+add esp,60
+L1:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _main
+_main:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,296
+mov byte ptr (_c),1
+movsx edi,byte ptr (_c)
+mov esi,edi
+mov word ptr (_s),si
+mov dword ptr (_i),edi
+mov dword ptr (_l),edi
+mov esi,edi
+mov ebx,esi
+mov byte ptr (_C),bl
+mov ebx,esi
+mov word ptr (_S),bx
+mov dword ptr (_I),esi
+mov dword ptr (_L),esi
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fstp dword ptr (_f)
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fstp qword ptr (-8)[ebp]
+fld qword ptr (-8)[ebp]
+fstp qword ptr (_d)
+fld qword ptr (-8)[ebp]
+fstp qword ptr (_D)
+call _print
+add esp,0
+mov word ptr (_s),2
+movsx edi,word ptr (_s)
+mov ebx,edi
+mov byte ptr (_c),bl
+mov dword ptr (_i),edi
+mov dword ptr (_l),edi
+mov esi,edi
+mov ebx,esi
+mov byte ptr (_C),bl
+mov ebx,esi
+mov word ptr (_S),bx
+mov dword ptr (_I),esi
+mov dword ptr (_L),esi
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fstp dword ptr (_f)
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fstp qword ptr (-16)[ebp]
+fld qword ptr (-16)[ebp]
+fstp qword ptr (_d)
+fld qword ptr (-16)[ebp]
+fstp qword ptr (_D)
+call _print
+add esp,0
+mov dword ptr (_i),3
+mov edi,dword ptr (_i)
+mov ebx,edi
+mov byte ptr (_c),bl
+mov esi,edi
+mov word ptr (_s),si
+mov dword ptr (_l),edi
+mov esi,edi
+mov ebx,esi
+mov byte ptr (_C),bl
+mov ebx,esi
+mov word ptr (_S),bx
+mov dword ptr (_I),esi
+mov dword ptr (_L),esi
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fstp dword ptr (_f)
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fstp qword ptr (-24)[ebp]
+fld qword ptr (-24)[ebp]
+fstp qword ptr (_d)
+fld qword ptr (-24)[ebp]
+fstp qword ptr (_D)
+call _print
+add esp,0
+mov dword ptr (_l),4
+mov edi,dword ptr (_l)
+mov ebx,edi
+mov byte ptr (_c),bl
+mov esi,edi
+mov word ptr (_s),si
+mov dword ptr (_i),edi
+mov esi,edi
+mov ebx,esi
+mov byte ptr (_C),bl
+mov ebx,esi
+mov word ptr (_S),bx
+mov dword ptr (_I),esi
+mov dword ptr (_L),esi
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fstp dword ptr (_f)
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fstp qword ptr (-32)[ebp]
+fld qword ptr (-32)[ebp]
+fstp qword ptr (_d)
+fld qword ptr (-32)[ebp]
+fstp qword ptr (_D)
+call _print
+add esp,0
+mov byte ptr (_C),5
+mov bl,byte ptr (_C)
+movzx edi,bl
+mov ebx,edi
+mov byte ptr (_c),bl
+mov esi,edi
+mov word ptr (_s),si
+mov dword ptr (_i),edi
+mov dword ptr (_l),edi
+mov esi,edi
+mov ebx,esi
+mov word ptr (_S),bx
+mov dword ptr (_I),esi
+mov dword ptr (_L),esi
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fstp dword ptr (_f)
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fstp qword ptr (-40)[ebp]
+fld qword ptr (-40)[ebp]
+fstp qword ptr (_d)
+fld qword ptr (-40)[ebp]
+fstp qword ptr (_D)
+call _print
+add esp,0
+mov word ptr (_S),6
+mov di,word ptr (_S)
+movzx edi,di
+mov ebx,edi
+mov byte ptr (_c),bl
+mov esi,edi
+mov word ptr (_s),si
+mov dword ptr (_i),edi
+mov dword ptr (_l),edi
+mov esi,edi
+mov ebx,esi
+mov byte ptr (_C),bl
+mov dword ptr (_I),esi
+mov dword ptr (_L),esi
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fstp dword ptr (_f)
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fstp qword ptr (-48)[ebp]
+fld qword ptr (-48)[ebp]
+fstp qword ptr (_d)
+fld qword ptr (-48)[ebp]
+fstp qword ptr (_D)
+call _print
+add esp,0
+mov dword ptr (_I),7
+mov edi,dword ptr (_I)
+mov ebx,edi
+mov byte ptr (_c),bl
+mov ebx,edi
+mov word ptr (_s),bx
+mov dword ptr (_i),edi
+mov dword ptr (_l),edi
+mov ebx,edi
+mov byte ptr (_C),bl
+mov esi,edi
+mov word ptr (_S),si
+mov dword ptr (_L),edi
+fld qword ptr (L4)
+mov esi,edi
+shr esi,1
+push esi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+and edi,1
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+fstp qword ptr (-56)[ebp]
+fld qword ptr (-56)[ebp]
+fstp dword ptr (_f)
+fld qword ptr (-56)[ebp]
+fstp qword ptr (_d)
+fld qword ptr (-56)[ebp]
+fstp qword ptr (_D)
+call _print
+add esp,0
+mov dword ptr (_L),8
+mov edi,dword ptr (_L)
+mov ebx,edi
+mov byte ptr (_c),bl
+mov ebx,edi
+mov word ptr (_s),bx
+mov dword ptr (_i),edi
+mov dword ptr (_l),edi
+mov ebx,edi
+mov byte ptr (_C),bl
+mov esi,edi
+mov word ptr (_S),si
+mov si,word ptr (_S)
+movzx esi,si
+mov dword ptr (_I),esi
+fld qword ptr (L4)
+mov esi,edi
+shr esi,1
+push esi
+fild dword ptr 0[esp]
+add esp,4
+fmulp st(1),st
+and edi,1
+push edi
+fild dword ptr 0[esp]
+add esp,4
+faddp st(1),st
+fstp qword ptr (-64)[ebp]
+fld qword ptr (-64)[ebp]
+fstp dword ptr (_f)
+fld qword ptr (-64)[ebp]
+fstp qword ptr (_d)
+fld qword ptr (-64)[ebp]
+fstp qword ptr (_D)
+call _print
+add esp,0
+fld dword ptr (L5)
+fstp dword ptr (_f)
+fld dword ptr (_f)
+fstp dword ptr (-84)[ebp]
+fld dword ptr (-84)[ebp]
+call __ftol
+mov edi,eax
+mov ebx,edi
+mov byte ptr (_c),bl
+mov esi,edi
+mov word ptr (_s),si
+mov dword ptr (_i),edi
+mov dword ptr (_l),edi
+fld dword ptr (L9)
+fcomp dword ptr (-84)[ebp]
+fstsw ax
+sahf
+ja L7
+fld dword ptr (-84)[ebp]
+fsub dword ptr (L9)
+call __ftol
+mov edi,eax
+lea edi,(080000000H)[edi]
+mov dword ptr (-68)[ebp],edi
+jmp L8
+L7:
+fld dword ptr (-84)[ebp]
+call __ftol
+mov edi,eax
+mov dword ptr (-68)[ebp],edi
+L8:
+mov edi,dword ptr (-68)[ebp]
+mov ebx,edi
+mov byte ptr (_C),bl
+fld dword ptr (L9)
+fcomp dword ptr (_f)
+fstsw ax
+sahf
+ja L11
+fld dword ptr (_f)
+fsub dword ptr (L9)
+call __ftol
+mov edi,eax
+lea edi,(080000000H)[edi]
+mov dword ptr (-72)[ebp],edi
+jmp L12
+L11:
+fld dword ptr (_f)
+call __ftol
+mov edi,eax
+mov dword ptr (-72)[ebp],edi
+L12:
+mov edi,dword ptr (-72)[ebp]
+mov word ptr (_S),di
+fld dword ptr (L9)
+fcomp dword ptr (_f)
+fstsw ax
+sahf
+ja L14
+fld dword ptr (_f)
+fsub dword ptr (L9)
+call __ftol
+mov edi,eax
+lea edi,(080000000H)[edi]
+mov dword ptr (-76)[ebp],edi
+jmp L15
+L14:
+fld dword ptr (_f)
+call __ftol
+mov edi,eax
+mov dword ptr (-76)[ebp],edi
+L15:
+mov edi,dword ptr (-76)[ebp]
+mov dword ptr (_I),edi
+fld dword ptr (L9)
+fcomp dword ptr (_f)
+fstsw ax
+sahf
+ja L17
+fld dword ptr (_f)
+fsub dword ptr (L9)
+call __ftol
+mov edi,eax
+lea edi,(080000000H)[edi]
+mov dword ptr (-80)[ebp],edi
+jmp L18
+L17:
+fld dword ptr (_f)
+call __ftol
+mov edi,eax
+mov dword ptr (-80)[ebp],edi
+L18:
+mov edi,dword ptr (-80)[ebp]
+mov dword ptr (_L),edi
+fld dword ptr (_f)
+fstp qword ptr (-120)[ebp]
+fld qword ptr (-120)[ebp]
+fstp qword ptr (_d)
+fld qword ptr (-120)[ebp]
+fstp qword ptr (_D)
+call _print
+add esp,0
+fld qword ptr (L19)
+fstp qword ptr (_d)
+fld qword ptr (_d)
+fstp qword ptr (-144)[ebp]
+fld qword ptr (-144)[ebp]
+call __ftol
+mov edi,eax
+mov ebx,edi
+mov byte ptr (_c),bl
+mov esi,edi
+mov word ptr (_s),si
+mov dword ptr (_i),edi
+mov dword ptr (_l),edi
+fld qword ptr (L23)
+fcomp qword ptr (-144)[ebp]
+fstsw ax
+sahf
+ja L21
+fld qword ptr (-144)[ebp]
+fsub qword ptr (L23)
+call __ftol
+mov edi,eax
+lea edi,(080000000H)[edi]
+mov dword ptr (-124)[ebp],edi
+jmp L22
+L21:
+fld qword ptr (-144)[ebp]
+call __ftol
+mov edi,eax
+mov dword ptr (-124)[ebp],edi
+L22:
+mov edi,dword ptr (-124)[ebp]
+mov ebx,edi
+mov byte ptr (_C),bl
+fld qword ptr (L23)
+fcomp qword ptr (_d)
+fstsw ax
+sahf
+ja L25
+fld qword ptr (_d)
+fsub qword ptr (L23)
+call __ftol
+mov edi,eax
+lea edi,(080000000H)[edi]
+mov dword ptr (-128)[ebp],edi
+jmp L26
+L25:
+fld qword ptr (_d)
+call __ftol
+mov edi,eax
+mov dword ptr (-128)[ebp],edi
+L26:
+mov edi,dword ptr (-128)[ebp]
+mov word ptr (_S),di
+fld qword ptr (L23)
+fcomp qword ptr (_d)
+fstsw ax
+sahf
+ja L28
+fld qword ptr (_d)
+fsub qword ptr (L23)
+call __ftol
+mov edi,eax
+lea edi,(080000000H)[edi]
+mov dword ptr (-132)[ebp],edi
+jmp L29
+L28:
+fld qword ptr (_d)
+call __ftol
+mov edi,eax
+mov dword ptr (-132)[ebp],edi
+L29:
+mov edi,dword ptr (-132)[ebp]
+mov dword ptr (_I),edi
+fld qword ptr (L23)
+fcomp qword ptr (_d)
+fstsw ax
+sahf
+ja L31
+fld qword ptr (_d)
+fsub qword ptr (L23)
+call __ftol
+mov edi,eax
+lea edi,(080000000H)[edi]
+mov dword ptr (-136)[ebp],edi
+jmp L32
+L31:
+fld qword ptr (_d)
+call __ftol
+mov edi,eax
+mov dword ptr (-136)[ebp],edi
+L32:
+mov edi,dword ptr (-136)[ebp]
+mov dword ptr (_L),edi
+fld qword ptr (_d)
+fstp dword ptr (_f)
+fld qword ptr (_d)
+fstp qword ptr (_D)
+call _print
+add esp,0
+fld qword ptr (L33)
+fstp qword ptr (_D)
+fld qword ptr (_D)
+fstp qword ptr (-232)[ebp]
+fld qword ptr (-232)[ebp]
+call __ftol
+mov edi,eax
+mov ebx,edi
+mov byte ptr (_c),bl
+mov esi,edi
+mov word ptr (_s),si
+mov dword ptr (_i),edi
+mov dword ptr (_l),edi
+fld qword ptr (L37)
+fcomp qword ptr (-232)[ebp]
+fstsw ax
+sahf
+ja L35
+fld qword ptr (-232)[ebp]
+fsub qword ptr (L37)
+call __ftol
+mov edi,eax
+lea edi,(080000000H)[edi]
+mov dword ptr (-212)[ebp],edi
+jmp L36
+L35:
+fld qword ptr (-232)[ebp]
+call __ftol
+mov edi,eax
+mov dword ptr (-212)[ebp],edi
+L36:
+mov edi,dword ptr (-212)[ebp]
+mov ebx,edi
+mov byte ptr (_C),bl
+fld qword ptr (L37)
+fcomp qword ptr (_D)
+fstsw ax
+sahf
+ja L39
+fld qword ptr (_D)
+fsub qword ptr (L37)
+call __ftol
+mov edi,eax
+lea edi,(080000000H)[edi]
+mov dword ptr (-216)[ebp],edi
+jmp L40
+L39:
+fld qword ptr (_D)
+call __ftol
+mov edi,eax
+mov dword ptr (-216)[ebp],edi
+L40:
+mov edi,dword ptr (-216)[ebp]
+mov word ptr (_S),di
+fld qword ptr (L37)
+fcomp qword ptr (_D)
+fstsw ax
+sahf
+ja L42
+fld qword ptr (_D)
+fsub qword ptr (L37)
+call __ftol
+mov edi,eax
+lea edi,(080000000H)[edi]
+mov dword ptr (-220)[ebp],edi
+jmp L43
+L42:
+fld qword ptr (_D)
+call __ftol
+mov edi,eax
+mov dword ptr (-220)[ebp],edi
+L43:
+mov edi,dword ptr (-220)[ebp]
+mov dword ptr (_I),edi
+fld qword ptr (L37)
+fcomp qword ptr (_D)
+fstsw ax
+sahf
+ja L45
+fld qword ptr (_D)
+fsub qword ptr (L37)
+call __ftol
+mov edi,eax
+lea edi,(080000000H)[edi]
+mov dword ptr (-224)[ebp],edi
+jmp L46
+L45:
+fld qword ptr (_D)
+call __ftol
+mov edi,eax
+mov dword ptr (-224)[ebp],edi
+L46:
+mov edi,dword ptr (-224)[ebp]
+mov dword ptr (_L),edi
+fld qword ptr (_D)
+fstp dword ptr (_f)
+fld qword ptr (_D)
+fstp qword ptr (_d)
+call _print
+add esp,0
+mov dword ptr (_p),0
+mov dword ptr (_p),0
+mov dword ptr (_p),0
+mov dword ptr (_p),0
+mov edi,dword ptr (_P)
+mov dword ptr (_p),edi
+mov dword ptr (_P),0
+mov dword ptr (_P),0
+mov dword ptr (_P),0
+mov dword ptr (_P),0
+mov edi,dword ptr (_p)
+mov dword ptr (_P),edi
+mov eax,0
+L3:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+extrn _printf:near
+_TEXT segment
+_TEXT ends
+_DATA segment
+public _P
+align 4
+_P label byte
+db 4 dup (0)
+public _p
+align 4
+_p label byte
+db 4 dup (0)
+public _D
+align 4
+_D label byte
+db 8 dup (0)
+public _d
+align 4
+_d label byte
+db 8 dup (0)
+public _f
+align 4
+_f label byte
+db 4 dup (0)
+public _L
+align 4
+_L label byte
+db 4 dup (0)
+public _I
+align 4
+_I label byte
+db 4 dup (0)
+public _S
+align 2
+_S label byte
+db 2 dup (0)
+public _C
+align 1
+_C label byte
+db 1 dup (0)
+public _l
+align 4
+_l label byte
+db 4 dup (0)
+public _i
+align 4
+_i label byte
+db 4 dup (0)
+public _s
+align 2
+_s label byte
+db 2 dup (0)
+public _c
+align 1
+_c label byte
+db 1 dup (0)
+_DATA ends
+_TEXT segment
+align 4
+L37 label byte
+dd 00H
+dd 041e00000H
+align 4
+L33 label byte
+dd 00H
+dd 040260000H
+align 4
+L23 label byte
+dd 00H
+dd 041e00000H
+align 4
+L19 label byte
+dd 00H
+dd 040240000H
+align 4
+L9 label byte
+dd 04f000000H
+align 4
+L5 label byte
+dd 041100000H
+align 4
+L4 label byte
+dd 00H
+dd 040000000H
+align 1
+L2 label byte
+db 37
+db 100
+db 32
+db 37
+db 100
+db 32
+db 37
+db 100
+db 32
+db 37
+db 108
+db 100
+db 32
+db 37
+db 117
+db 32
+db 37
+db 117
+db 32
+db 37
+db 117
+db 32
+db 37
+db 108
+db 117
+db 32
+db 37
+db 102
+db 32
+db 37
+db 102
+db 32
+db 37
+db 108
+db 102
+db 10
+db 0
+_TEXT ends
+end
diff --git a/lcc/x86/win32/tst/fields.1bk b/lcc/x86/win32/tst/fields.1bk
new file mode 100755
index 0000000..f30b13f
--- /dev/null
+++ b/lcc/x86/win32/tst/fields.1bk
@@ -0,0 +1,5 @@
+x = 1 2 3 4 -3 6
+y = 3 8 9
+x = 1 2 3 0 0 6
+y = 2 8 16
+p->a = 0x3, p->b = 0xf
diff --git a/lcc/x86/win32/tst/fields.2bk b/lcc/x86/win32/tst/fields.2bk
new file mode 100755
index 0000000..e689d78
--- /dev/null
+++ b/lcc/x86/win32/tst/fields.2bk
@@ -0,0 +1,4 @@
+tst/fields.c:6: warning: initializer exceeds bit-field width
+tst/fields.c:8: warning: initializer exceeds bit-field width
+tst/fields.c:30: warning: missing return value
+tst/fields.c:34: warning: missing return value
diff --git a/lcc/x86/win32/tst/fields.sbk b/lcc/x86/win32/tst/fields.sbk
new file mode 100755
index 0000000..0e5e059
--- /dev/null
+++ b/lcc/x86/win32/tst/fields.sbk
@@ -0,0 +1,323 @@
+.486
+.model flat
+extrn __fltused:near
+extrn __ftol:near
+_DATA segment
+public _x
+align 4
+_x label byte
+dd 1
+db 2
+db 3 dup (0)
+db 03H
+db 040H
+db 2 dup (0)
+db 050H
+db 6
+db 2 dup (0)
+public _i
+align 4
+_i label byte
+dd 16
+public _y
+align 4
+_y label byte
+db 023H
+db 3 dup (0)
+db 09H
+db 00H
+db 00H
+db 00H
+public _main
+_DATA ends
+_TEXT segment
+_main:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+movsx edi,byte ptr (_x+13)
+push edi
+mov edi,dword ptr (_x+12)
+sal edi,25
+sar edi,29
+push edi
+mov edi,dword ptr (_x+8)
+sal edi,16
+sar edi,28
+push edi
+mov edi,dword ptr (_x+8)
+sal edi,20
+sar edi,20
+push edi
+movsx edi,byte ptr (_x+4)
+push edi
+mov edi,dword ptr (_x)
+push edi
+lea edi,(L4)
+push edi
+call _printf
+add esp,28
+mov edi,dword ptr (_y+4)
+push edi
+mov edi,dword ptr (_y)
+mov esi,edi
+shr esi,2
+and esi,15
+push esi
+and edi,3
+push edi
+lea edi,(L10)
+push edi
+call _printf
+add esp,16
+mov edi,dword ptr (_x+8)
+and edi,0ffff0fffH
+mov esi,dword ptr (_i)
+sal esi,28
+sar esi,28
+shl esi,12
+and esi,0f000H
+or edi,esi
+mov dword ptr (_x+8),edi
+mov edi,dword ptr (_x+12)
+and edi,0ffffff8fH
+mov dword ptr (_x+12),edi
+movsx edi,byte ptr (_x+13)
+push edi
+mov edi,dword ptr (_x+12)
+sal edi,25
+sar edi,29
+push edi
+mov edi,dword ptr (_x+8)
+sal edi,16
+sar edi,28
+push edi
+mov edi,dword ptr (_x+8)
+sal edi,20
+sar edi,20
+push edi
+movsx edi,byte ptr (_x+4)
+push edi
+mov edi,dword ptr (_x)
+push edi
+lea edi,(L4)
+push edi
+call _printf
+add esp,28
+mov edi,dword ptr (_y)
+and edi,0fffffffcH
+or edi,2
+mov dword ptr (_y),edi
+mov edi,dword ptr (_i)
+mov dword ptr (_y+4),edi
+mov edi,dword ptr (_y+4)
+push edi
+mov edi,dword ptr (_y)
+mov esi,edi
+shr esi,2
+and esi,15
+push esi
+and edi,3
+push edi
+lea edi,(L10)
+push edi
+call _printf
+add esp,16
+lea edi,(_x)
+push edi
+call _f2
+add esp,4
+mov eax,0
+L3:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _f1
+_f1:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov edi,dword ptr (20)[ebp]
+and dword ptr [edi],0ffffffc3H
+mov edi,dword ptr (20)[ebp]
+mov esi,dword ptr [edi]
+and esi,0fffffffcH
+mov ebx,0
+and ebx,3
+and ebx,3
+or esi,ebx
+mov dword ptr [edi],esi
+mov edi,dword ptr (20)[ebp]
+mov edi,dword ptr [edi]
+and edi,60
+cmp edi,0
+je L22
+lea edi,(L24)
+push edi
+call _printf
+add esp,4
+L22:
+mov edi,dword ptr (20)[ebp]
+or dword ptr [edi],3
+mov edi,dword ptr (20)[ebp]
+or dword ptr [edi],60
+mov edi,dword ptr (20)[ebp]
+mov edi,dword ptr [edi]
+mov esi,edi
+shr esi,2
+and esi,15
+push esi
+and edi,3
+push edi
+lea edi,(L25)
+push edi
+call _printf
+add esp,12
+mov eax,0
+L21:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _f2
+_f2:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,4
+cmp dword ptr (_i),0
+jne L28
+mov dword ptr (-4)[ebp],1
+jmp L29
+L28:
+mov dword ptr (-4)[ebp],0
+L29:
+mov edi,dword ptr (20)[ebp]
+mov esi,dword ptr [edi]
+and esi,0fffffffcH
+mov ebx,dword ptr (-4)[ebp]
+and ebx,3
+and ebx,3
+or esi,ebx
+mov dword ptr [edi],esi
+mov edi,dword ptr (20)[ebp]
+push edi
+call _f1
+add esp,4
+mov esi,dword ptr [edi]
+and esi,0ffffffc3H
+mov ebx,0
+and ebx,15
+lea ebx,[ebx*4]
+and ebx,60
+or esi,ebx
+mov dword ptr [edi],esi
+mov eax,0
+L26:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+extrn _printf:near
+_TEXT segment
+_TEXT ends
+_TEXT segment
+align 1
+L25 label byte
+db 112
+db 45
+db 62
+db 97
+db 32
+db 61
+db 32
+db 48
+db 120
+db 37
+db 120
+db 44
+db 32
+db 112
+db 45
+db 62
+db 98
+db 32
+db 61
+db 32
+db 48
+db 120
+db 37
+db 120
+db 10
+db 0
+align 1
+L24 label byte
+db 112
+db 45
+db 62
+db 98
+db 32
+db 33
+db 61
+db 32
+db 48
+db 33
+db 10
+db 0
+align 1
+L10 label byte
+db 121
+db 32
+db 61
+db 32
+db 37
+db 100
+db 32
+db 37
+db 100
+db 32
+db 37
+db 100
+db 10
+db 0
+align 1
+L4 label byte
+db 120
+db 32
+db 61
+db 32
+db 37
+db 100
+db 32
+db 37
+db 100
+db 32
+db 37
+db 100
+db 32
+db 37
+db 100
+db 32
+db 37
+db 100
+db 32
+db 37
+db 100
+db 10
+db 0
+_TEXT ends
+end
diff --git a/lcc/x86/win32/tst/front.2bk b/lcc/x86/win32/tst/front.2bk
new file mode 100755
index 0000000..841e6a5
--- /dev/null
+++ b/lcc/x86/win32/tst/front.2bk
@@ -0,0 +1,29 @@
+tst/front.c:3: warning: missing return value
+tst/front.c:10: warning: missing return value
+tst/front.c:20: type error in argument 1 to `s'; found `pointer to struct D' expected `pointer to incomplete struct D defined at tst/front.c:14'
+tst/front.c:21: warning: missing return value
+tst/front.c:32: warning: missing return value
+tst/front.c:36: operands of = have illegal types `pointer to int' and `pointer to const int'
+tst/front.c:38: warning: missing return value
+tst/front.c:62: operands of = have illegal types `pointer to char' and `pointer to const void'
+tst/front.c:63: warning: missing return value
+tst/front.c:68: warning: missing return value
+tst/front.c:69: warning: inconsistent linkage for `yy' previously declared at tst/front.c:68
+tst/front.c:69: warning: missing return value
+tst/front.c:71: invalid storage class `static' for `int function goo'
+tst/front.c:71: warning: declaration of `goo' does not match previous declaration at tst/front.c:70
+tst/front.c:71: warning: missing return value
+tst/front.c:74: warning: declaration of `xr' does not match previous declaration at tst/front.c:72
+tst/front.c:74: warning: missing return value
+tst/front.c:81: warning: missing return value
+tst/front.c:82: warning: declaration of `ss2' does not match previous declaration at tst/front.c:81
+tst/front.c:84: warning: inconsistent linkage for `ss5' previously declared at tst/front.c:80
+tst/front.c:92: type error in argument 1 to `gx1'; found `pointer to double' expected `double'
+tst/front.c:92: warning: missing return value
+tst/front.c:95: redeclaration of `hx1' previously declared at tst/front.c:94
+tst/front.c:98: warning: missing return value
+tst/front.c:101: conflicting argument declarations for function `gg1'
+tst/front.c:101: warning: missing return value
+tst/front.c:112: type error in argument 4 to `qsort'; found `pointer to int function(pointer to pointer to char,pointer to pointer to char)' expected `pointer to int function(pointer to const void,pointer to const void)'
+tst/front.c:113: warning: missing return value
+tst/front.c:120: warning: missing return value
diff --git a/lcc/x86/win32/tst/front.sbk b/lcc/x86/win32/tst/front.sbk
new file mode 100755
index 0000000..b3a6945
--- /dev/null
+++ b/lcc/x86/win32/tst/front.sbk
@@ -0,0 +1,436 @@
+.486
+.model flat
+extrn __fltused:near
+extrn __ftol:near
+public _main
+_TEXT segment
+_main:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+push 0
+call _exit
+add esp,4
+mov eax,0
+L1:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _nested
+_nested:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+cmp dword ptr (20)[ebp],4
+jge L6
+cmp dword ptr (24)[ebp],114
+je L9
+L6:
+cmp dword ptr (20)[ebp],1
+jne L8
+mov edi,dword ptr (24)[ebp]
+cmp edi,104
+je L9
+cmp edi,105
+je L9
+L8:
+cmp dword ptr (20)[ebp],2
+jne L3
+mov edi,dword ptr (24)[ebp]
+cmp edi,111
+je L9
+cmp edi,121
+jne L3
+L9:
+mov edi,dword ptr (24)[ebp]
+mov dword ptr (20)[ebp],edi
+L3:
+mov eax,0
+L2:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _s
+_s:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+L10:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+public _Dy
+align 4
+_Dy label byte
+dd 0
+db 4 dup (0)
+public _Dz
+align 4
+_Dz label byte
+dd 1
+db 4 dup (0)
+public _Dfunc
+_DATA ends
+_TEXT segment
+_Dfunc:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _f
+_f:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _f1
+_f1:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _f2
+_f2:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _g
+_g:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _h
+_h:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _h1
+_h1:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _h2
+_h2:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 4
+L21 label byte
+dd 1
+public _set1
+_DATA ends
+_TEXT segment
+_set1:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 4
+L23 label byte
+dd 2
+public _set2
+_DATA ends
+_TEXT segment
+_set2:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_goo:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _sss
+_sss:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 4
+L27 label byte
+db 4 dup (0)
+public _rrr
+_DATA ends
+_TEXT segment
+_rrr:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _setstatic
+_setstatic:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _gx1
+_gx1:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _ff1
+_ff1:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _gg1
+_gg1:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _hh1
+_hh1:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _cmp
+_cmp:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _sort
+_sort:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _onearg
+_onearg:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+extrn _exit:near
+_TEXT segment
+_TEXT ends
+extrn _qsort:near
+_TEXT segment
+_TEXT ends
+extrn _strcmp:near
+_TEXT segment
+_TEXT ends
+_DATA segment
+public _ss4
+align 4
+_ss4 label byte
+db 4 dup (0)
+align 4
+_ss2 label byte
+db 4 dup (0)
+align 4
+_ss5 label byte
+db 4 dup (0)
+public _ss3
+align 4
+_ss3 label byte
+db 4 dup (0)
+align 4
+_ss1 label byte
+db 4 dup (0)
+align 4
+_yy label byte
+db 4 dup (0)
+public _z
+align 4
+_z label byte
+db 4 dup (0)
+public _y
+align 4
+_y label byte
+db 4 dup (0)
+public _x
+align 4
+_x label byte
+db 4 dup (0)
+public _b
+align 4
+_b label byte
+db 4 dup (0)
+public _a
+align 4
+_a label byte
+db 4 dup (0)
+_DATA ends
+end
diff --git a/lcc/x86/win32/tst/incr.1bk b/lcc/x86/win32/tst/incr.1bk
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/x86/win32/tst/incr.1bk
diff --git a/lcc/x86/win32/tst/incr.2bk b/lcc/x86/win32/tst/incr.2bk
new file mode 100755
index 0000000..b86c400
--- /dev/null
+++ b/lcc/x86/win32/tst/incr.2bk
@@ -0,0 +1,9 @@
+tst/incr.c:1: warning: missing return value
+tst/incr.c:6: warning: expression with no effect elided
+tst/incr.c:6: warning: expression with no effect elided
+tst/incr.c:11: warning: missing return value
+tst/incr.c:16: warning: expression with no effect elided
+tst/incr.c:16: warning: expression with no effect elided
+tst/incr.c:21: warning: missing return value
+tst/incr.c:30: warning: missing return value
+tst/incr.c:39: warning: missing return value
diff --git a/lcc/x86/win32/tst/incr.sbk b/lcc/x86/win32/tst/incr.sbk
new file mode 100755
index 0000000..222ce32
--- /dev/null
+++ b/lcc/x86/win32/tst/incr.sbk
@@ -0,0 +1,166 @@
+.486
+.model flat
+extrn __fltused:near
+extrn __ftol:near
+public _main
+_TEXT segment
+_main:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov eax,0
+L1:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _memchar
+_memchar:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,8
+mov edi,dword ptr (-8)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-8)[ebp],esi
+mov bl,byte ptr [edi]
+mov byte ptr (-1)[ebp],bl
+mov edi,dword ptr (-8)[ebp]
+lea edi,(1)[edi]
+mov dword ptr (-8)[ebp],edi
+mov bl,byte ptr [edi]
+mov byte ptr (-1)[ebp],bl
+mov edi,dword ptr (-8)[ebp]
+lea esi,(-1)[edi]
+mov dword ptr (-8)[ebp],esi
+mov bl,byte ptr [edi]
+mov byte ptr (-1)[ebp],bl
+mov edi,dword ptr (-8)[ebp]
+lea edi,(-1)[edi]
+mov dword ptr (-8)[ebp],edi
+mov bl,byte ptr [edi]
+mov byte ptr (-1)[ebp],bl
+mov eax,0
+L2:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _memint
+_memint:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,8
+mov edi,dword ptr (-8)[ebp]
+lea esi,(4)[edi]
+mov dword ptr (-8)[ebp],esi
+mov edi,dword ptr [edi]
+mov dword ptr (-4)[ebp],edi
+mov edi,dword ptr (-8)[ebp]
+lea edi,(4)[edi]
+mov dword ptr (-8)[ebp],edi
+mov edi,dword ptr [edi]
+mov dword ptr (-4)[ebp],edi
+mov edi,dword ptr (-8)[ebp]
+lea esi,(-4)[edi]
+mov dword ptr (-8)[ebp],esi
+mov edi,dword ptr [edi]
+mov dword ptr (-4)[ebp],edi
+mov edi,dword ptr (-8)[ebp]
+lea edi,(-4)[edi]
+mov dword ptr (-8)[ebp],edi
+mov edi,dword ptr [edi]
+mov dword ptr (-4)[ebp],edi
+mov eax,0
+L3:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _regchar
+_regchar:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,8
+mov edi,dword ptr (-8)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-8)[ebp],esi
+mov bl,byte ptr [edi]
+mov byte ptr (-1)[ebp],bl
+mov edi,dword ptr (-8)[ebp]
+lea edi,(1)[edi]
+mov dword ptr (-8)[ebp],edi
+mov bl,byte ptr [edi]
+mov byte ptr (-1)[ebp],bl
+mov edi,dword ptr (-8)[ebp]
+lea esi,(-1)[edi]
+mov dword ptr (-8)[ebp],esi
+mov bl,byte ptr [edi]
+mov byte ptr (-1)[ebp],bl
+mov edi,dword ptr (-8)[ebp]
+lea edi,(-1)[edi]
+mov dword ptr (-8)[ebp],edi
+mov bl,byte ptr [edi]
+mov byte ptr (-1)[ebp],bl
+mov eax,0
+L4:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _regint
+_regint:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,8
+mov edi,dword ptr (-8)[ebp]
+lea esi,(4)[edi]
+mov dword ptr (-8)[ebp],esi
+mov edi,dword ptr [edi]
+mov dword ptr (-4)[ebp],edi
+mov edi,dword ptr (-8)[ebp]
+lea edi,(4)[edi]
+mov dword ptr (-8)[ebp],edi
+mov edi,dword ptr [edi]
+mov dword ptr (-4)[ebp],edi
+mov edi,dword ptr (-8)[ebp]
+lea esi,(-4)[edi]
+mov dword ptr (-8)[ebp],esi
+mov edi,dword ptr [edi]
+mov dword ptr (-4)[ebp],edi
+mov edi,dword ptr (-8)[ebp]
+lea edi,(-4)[edi]
+mov dword ptr (-8)[ebp],edi
+mov edi,dword ptr [edi]
+mov dword ptr (-4)[ebp],edi
+mov eax,0
+L5:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+end
diff --git a/lcc/x86/win32/tst/init.1bk b/lcc/x86/win32/tst/init.1bk
new file mode 100755
index 0000000..042f3bb
--- /dev/null
+++ b/lcc/x86/win32/tst/init.1bk
@@ -0,0 +1,16 @@
+ 1 2 3 4
+ 5 6
+ 7
+if
+for
+else
+while
+1 2 3 if
+4 5 0 for
+6 7 8 else
+9 10 11 while
+1 2 3 if
+4 5 0 for
+6 7 8 else
+9 10 11 while
+0 0 0
diff --git a/lcc/x86/win32/tst/init.2bk b/lcc/x86/win32/tst/init.2bk
new file mode 100755
index 0000000..da08062
--- /dev/null
+++ b/lcc/x86/win32/tst/init.2bk
@@ -0,0 +1,3 @@
+tst/init.c:36: warning: missing return value
+tst/init.c:49: warning: missing return value
+tst/init.c:59: warning: missing return value
diff --git a/lcc/x86/win32/tst/init.sbk b/lcc/x86/win32/tst/init.sbk
new file mode 100755
index 0000000..be83cbd
--- /dev/null
+++ b/lcc/x86/win32/tst/init.sbk
@@ -0,0 +1,336 @@
+.486
+.model flat
+extrn __fltused:near
+extrn __ftol:near
+_DATA segment
+public _words
+align 4
+_words label byte
+dd 1
+dd 2
+dd 3
+db 105
+db 102
+db 0
+db 3 dup (0)
+db 2 dup (0)
+dd 4
+dd 5
+db 4 dup (0)
+db 102
+db 111
+db 114
+db 3 dup (0)
+db 2 dup (0)
+dd 6
+dd 7
+dd 8
+db 101
+db 108
+db 115
+db 101
+db 0
+db 1 dup (0)
+db 2 dup (0)
+dd 9
+dd 10
+dd 11
+db 119
+db 104
+db 105
+db 108
+db 101
+db 1 dup (0)
+db 2 dup (0)
+dd 0
+db 8 dup (0)
+db 8 dup (0)
+public _wordlist
+align 4
+_wordlist label byte
+dd _words
+public _x
+align 4
+_x label byte
+dd 1
+dd 2
+dd 3
+dd 4
+dd 0
+dd 5
+dd 6
+db 12 dup (0)
+dd 7
+db 16 dup (0)
+public _y
+align 4
+_y label byte
+dd _x
+dd _x+20
+dd _x+40
+dd 00H
+public _main
+_DATA ends
+_TEXT segment
+_main:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,8
+mov dword ptr (-8)[ebp],0
+jmp L8
+L5:
+mov dword ptr (-4)[ebp],0
+jmp L12
+L9:
+mov edi,dword ptr (-4)[ebp]
+mov esi,dword ptr (-8)[ebp]
+mov esi,dword ptr (_y)[esi*4]
+mov edi,dword ptr [esi][edi*4]
+push edi
+lea edi,(L13)
+push edi
+call _printf
+add esp,8
+L10:
+inc dword ptr (-4)[ebp]
+L12:
+mov edi,dword ptr (-4)[ebp]
+mov esi,dword ptr (-8)[ebp]
+mov esi,dword ptr (_y)[esi*4]
+cmp dword ptr [esi][edi*4],0
+jne L9
+lea edi,(L14)
+push edi
+call _printf
+add esp,4
+L6:
+inc dword ptr (-8)[ebp]
+L8:
+mov edi,dword ptr (-8)[ebp]
+mov edi,dword ptr (_y)[edi*4]
+cmp edi,0
+jne L5
+call _f
+add esp,0
+mov edi,dword ptr (_wordlist)
+push edi
+call _g
+add esp,4
+mov eax,0
+L4:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 4
+L16 label byte
+dd L17
+dd L18
+dd L19
+dd L20
+dd 00H
+public _f
+_DATA ends
+_TEXT segment
+_f:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,4
+lea edi,(L16)
+mov dword ptr (-4)[ebp],edi
+jmp L24
+L21:
+mov edi,dword ptr (-4)[ebp]
+mov edi,dword ptr [edi]
+push edi
+lea edi,(L25)
+push edi
+call _printf
+add esp,8
+L22:
+mov edi,dword ptr (-4)[ebp]
+lea edi,(4)[edi]
+mov dword ptr (-4)[ebp],edi
+L24:
+mov edi,dword ptr (-4)[ebp]
+mov edi,dword ptr [edi]
+cmp edi,0
+jne L21
+mov eax,0
+L15:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _g
+_g:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,4
+jmp L30
+L27:
+mov dword ptr (-4)[ebp],0
+jmp L34
+L31:
+mov edi,dword ptr (-4)[ebp]
+mov esi,dword ptr (20)[ebp]
+mov edi,dword ptr [esi][edi*4]
+push edi
+lea edi,(L35)
+push edi
+call _printf
+add esp,8
+L32:
+inc dword ptr (-4)[ebp]
+L34:
+mov edi,dword ptr (-4)[ebp]
+cmp edi,3
+jb L31
+mov edi,dword ptr (20)[ebp]
+lea edi,(12)[edi]
+push edi
+lea edi,(L25)
+push edi
+call _printf
+add esp,8
+L28:
+mov edi,dword ptr (20)[ebp]
+lea edi,(20)[edi]
+mov dword ptr (20)[ebp],edi
+L30:
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr [edi],0
+jne L27
+call _h
+add esp,0
+mov eax,0
+L26:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _h
+_h:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,4
+mov dword ptr (-4)[ebp],0
+jmp L40
+L37:
+imul edi,dword ptr (-4)[ebp],20
+lea esi,(_words+12)[edi]
+push esi
+mov esi,dword ptr (_words+8)[edi]
+push esi
+mov esi,dword ptr (_words+4)[edi]
+push esi
+mov edi,dword ptr (_words)[edi]
+push edi
+lea edi,(L41)
+push edi
+call _printf
+add esp,20
+L38:
+inc dword ptr (-4)[ebp]
+L40:
+mov edi,dword ptr (-4)[ebp]
+cmp edi,5
+jb L37
+mov eax,0
+L36:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+extrn _printf:near
+_TEXT segment
+_TEXT ends
+_TEXT segment
+align 1
+L41 label byte
+db 37
+db 100
+db 32
+db 37
+db 100
+db 32
+db 37
+db 100
+db 32
+db 37
+db 115
+db 10
+db 0
+align 1
+L35 label byte
+db 37
+db 100
+db 32
+db 0
+align 1
+L25 label byte
+db 37
+db 115
+db 10
+db 0
+align 1
+L20 label byte
+db 119
+db 104
+db 105
+db 108
+db 101
+db 0
+align 1
+L19 label byte
+db 101
+db 108
+db 115
+db 101
+db 0
+align 1
+L18 label byte
+db 102
+db 111
+db 114
+db 0
+align 1
+L17 label byte
+db 105
+db 102
+db 0
+align 1
+L14 label byte
+db 10
+db 0
+align 1
+L13 label byte
+db 32
+db 37
+db 100
+db 0
+_TEXT ends
+end
diff --git a/lcc/x86/win32/tst/limits.1bk b/lcc/x86/win32/tst/limits.1bk
new file mode 100755
index 0000000..f0c1dc8
--- /dev/null
+++ b/lcc/x86/win32/tst/limits.1bk
@@ -0,0 +1,14 @@
+UCHAR_MAX: 000000ff=255
+USHRT_MAX: 0000ffff=65535
+UINT_MAX: ffffffff=-1
+ULONG_MAX: ffffffff=-1
+CHAR_MAX: 0000007f=127
+SCHAR_MAX: 0000007f=127
+SHRT_MAX: 00007fff=32767
+INT_MAX: 7fffffff=2147483647
+LONG_MAX: 7fffffff=2147483647
+CHAR_MIN: ffffff80=-128
+SCHAR_MIN: ffffff80=-128
+SHRT_MIN: ffff8000=-32768
+INT_MIN: 80000000=-2147483648
+LONG_MIN: 80000000=-2147483648
diff --git a/lcc/x86/win32/tst/limits.2bk b/lcc/x86/win32/tst/limits.2bk
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/x86/win32/tst/limits.2bk
diff --git a/lcc/x86/win32/tst/limits.sbk b/lcc/x86/win32/tst/limits.sbk
new file mode 100755
index 0000000..f041121
--- /dev/null
+++ b/lcc/x86/win32/tst/limits.sbk
@@ -0,0 +1,414 @@
+.486
+.model flat
+extrn __fltused:near
+extrn __ftol:near
+public _main
+_TEXT segment
+_main:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+push 255
+push 255
+lea edi,(L2)
+push edi
+call _printf
+add esp,12
+push 65535
+push 65535
+lea edi,(L3)
+push edi
+call _printf
+add esp,12
+push 0ffffffffH
+push 0ffffffffH
+lea edi,(L4)
+push edi
+call _printf
+add esp,12
+push 0ffffffffH
+push 0ffffffffH
+lea edi,(L5)
+push edi
+call _printf
+add esp,12
+push 127
+push 127
+lea edi,(L6)
+push edi
+call _printf
+add esp,12
+push 127
+push 127
+lea edi,(L7)
+push edi
+call _printf
+add esp,12
+push 32767
+push 32767
+lea edi,(L8)
+push edi
+call _printf
+add esp,12
+push 2147483647
+push 2147483647
+lea edi,(L9)
+push edi
+call _printf
+add esp,12
+push 2147483647
+push 2147483647
+lea edi,(L10)
+push edi
+call _printf
+add esp,12
+push -128
+push -128
+lea edi,(L11)
+push edi
+call _printf
+add esp,12
+push -128
+push -128
+lea edi,(L12)
+push edi
+call _printf
+add esp,12
+push -32768
+push -32768
+lea edi,(L13)
+push edi
+call _printf
+add esp,12
+push -2147483648
+push -2147483648
+lea edi,(L14)
+push edi
+call _printf
+add esp,12
+push -2147483648
+push -2147483648
+lea edi,(L15)
+push edi
+call _printf
+add esp,12
+mov eax,0
+L1:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+extrn _printf:near
+_TEXT segment
+_TEXT ends
+_TEXT segment
+align 1
+L15 label byte
+db 76
+db 79
+db 78
+db 71
+db 95
+db 77
+db 73
+db 78
+db 58
+db 9
+db 37
+db 48
+db 56
+db 108
+db 120
+db 61
+db 37
+db 108
+db 100
+db 10
+db 0
+align 1
+L14 label byte
+db 73
+db 78
+db 84
+db 95
+db 77
+db 73
+db 78
+db 58
+db 9
+db 37
+db 48
+db 56
+db 120
+db 61
+db 37
+db 100
+db 10
+db 0
+align 1
+L13 label byte
+db 83
+db 72
+db 82
+db 84
+db 95
+db 77
+db 73
+db 78
+db 58
+db 9
+db 37
+db 48
+db 56
+db 120
+db 61
+db 37
+db 100
+db 10
+db 0
+align 1
+L12 label byte
+db 83
+db 67
+db 72
+db 65
+db 82
+db 95
+db 77
+db 73
+db 78
+db 58
+db 9
+db 37
+db 48
+db 56
+db 120
+db 61
+db 37
+db 100
+db 10
+db 0
+align 1
+L11 label byte
+db 67
+db 72
+db 65
+db 82
+db 95
+db 77
+db 73
+db 78
+db 58
+db 9
+db 37
+db 48
+db 56
+db 120
+db 61
+db 37
+db 100
+db 10
+db 0
+align 1
+L10 label byte
+db 76
+db 79
+db 78
+db 71
+db 95
+db 77
+db 65
+db 88
+db 58
+db 9
+db 37
+db 48
+db 56
+db 108
+db 120
+db 61
+db 37
+db 108
+db 100
+db 10
+db 0
+align 1
+L9 label byte
+db 73
+db 78
+db 84
+db 95
+db 77
+db 65
+db 88
+db 58
+db 9
+db 37
+db 48
+db 56
+db 120
+db 61
+db 37
+db 100
+db 10
+db 0
+align 1
+L8 label byte
+db 83
+db 72
+db 82
+db 84
+db 95
+db 77
+db 65
+db 88
+db 58
+db 9
+db 37
+db 48
+db 56
+db 120
+db 61
+db 37
+db 100
+db 10
+db 0
+align 1
+L7 label byte
+db 83
+db 67
+db 72
+db 65
+db 82
+db 95
+db 77
+db 65
+db 88
+db 58
+db 9
+db 37
+db 48
+db 56
+db 120
+db 61
+db 37
+db 100
+db 10
+db 0
+align 1
+L6 label byte
+db 67
+db 72
+db 65
+db 82
+db 95
+db 77
+db 65
+db 88
+db 58
+db 9
+db 37
+db 48
+db 56
+db 120
+db 61
+db 37
+db 100
+db 10
+db 0
+align 1
+L5 label byte
+db 85
+db 76
+db 79
+db 78
+db 71
+db 95
+db 77
+db 65
+db 88
+db 58
+db 9
+db 37
+db 48
+db 56
+db 108
+db 120
+db 61
+db 37
+db 108
+db 100
+db 10
+db 0
+align 1
+L4 label byte
+db 85
+db 73
+db 78
+db 84
+db 95
+db 77
+db 65
+db 88
+db 58
+db 9
+db 37
+db 48
+db 56
+db 120
+db 61
+db 37
+db 100
+db 10
+db 0
+align 1
+L3 label byte
+db 85
+db 83
+db 72
+db 82
+db 84
+db 95
+db 77
+db 65
+db 88
+db 58
+db 9
+db 37
+db 48
+db 56
+db 120
+db 61
+db 37
+db 100
+db 10
+db 0
+align 1
+L2 label byte
+db 85
+db 67
+db 72
+db 65
+db 82
+db 95
+db 77
+db 65
+db 88
+db 58
+db 9
+db 37
+db 48
+db 56
+db 120
+db 61
+db 37
+db 100
+db 10
+db 0
+_TEXT ends
+end
diff --git a/lcc/x86/win32/tst/paranoia.1bk b/lcc/x86/win32/tst/paranoia.1bk
new file mode 100755
index 0000000..e25ef14
--- /dev/null
+++ b/lcc/x86/win32/tst/paranoia.1bk
@@ -0,0 +1,179 @@
+Lest this program stop prematurely, i.e. before displaying
+
+ `END OF TEST',
+
+try to persuade the computer NOT to terminate execution when an
+error like Over/Underflow or Division by Zero occurs, but rather
+to persevere with a surrogate value after, perhaps, displaying some
+warning. If persuasion avails naught, don't despair but run this
+program anyway to see how many milestones it passes, and then
+amend it to make further progress.
+
+Answer questions with Y, y, N or n (unless otherwise indicated).
+
+
+Diagnosis resumes after milestone Number 0 Page: 1
+
+Users are invited to help debug and augment this program so it will
+cope with unanticipated and newly uncovered arithmetic pathologies.
+
+Please send suggestions and interesting results to
+ Richard Karpinski
+ Computer Center U-76
+ University of California
+ San Francisco, CA 94143-0704, USA
+
+In doing so, please include the following information:
+ Precision: double;
+ Version: 10 February 1989;
+ Computer:
+
+ Compiler:
+
+ Optimization level:
+
+ Other relevant compiler options:
+
+Diagnosis resumes after milestone Number 1 Page: 2
+
+Running this program should reveal these characteristics:
+ Radix = 1, 2, 4, 8, 10, 16, 100, 256 ...
+ Precision = number of significant digits carried.
+ U2 = Radix/Radix^Precision = One Ulp
+ (OneUlpnit in the Last Place) of 1.000xxx .
+ U1 = 1/Radix^Precision = One Ulp of numbers a little less than 1.0 .
+ Adequacy of guard digits for Mult., Div. and Subt.
+ Whether arithmetic is chopped, correctly rounded, or something else
+ for Mult., Div., Add/Subt. and Sqrt.
+ Whether a Sticky Bit used correctly for rounding.
+ UnderflowThreshold = an underflow threshold.
+ E0 and PseudoZero tell whether underflow is abrupt, gradual, or fuzzy.
+ V = an overflow threshold, roughly.
+ V0 tells, roughly, whether Infinity is represented.
+ Comparisions are checked for consistency with subtraction
+ and for contamination with pseudo-zeros.
+ Sqrt is tested. Y^X is not tested.
+ Extra-precise subexpressions are revealed but NOT YET tested.
+ Decimal-Binary conversion is NOT YET tested for accuracy.
+
+Diagnosis resumes after milestone Number 2 Page: 3
+
+The program attempts to discriminate among
+ FLAWs, like lack of a sticky bit,
+ Serious DEFECTs, like lack of a guard digit, and
+ FAILUREs, like 2+2 == 5 .
+Failures may confound subsequent diagnoses.
+
+The diagnostic capabilities of this program go beyond an earlier
+program called `MACHAR', which can be found at the end of the
+book `Software Manual for the Elementary Functions' (1980) by
+W. J. Cody and W. Waite. Although both programs try to discover
+the Radix, Precision and range (over/underflow thresholds)
+of the arithmetic, this program tries to cope with a wider variety
+of pathologies, and to say how well the arithmetic is implemented.
+
+The program is based upon a conventional radix representation for
+floating-point numbers, but also allows logarithmic encoding
+as used by certain early WANG machines.
+
+BASIC version of this program (C) 1983 by Prof. W. M. Kahan;
+see source comments for more history.
+
+Diagnosis resumes after milestone Number 3 Page: 4
+
+Program is now RUNNING tests on small integers:
+-1, 0, 1/2, 1, 2, 3, 4, 5, 9, 27, 32 & 240 are O.K.
+
+Searching for Radix and Precision.
+Radix = 2.000000 .
+Closest relative separation found is U1 = 1.1102230e-016 .
+
+Recalculating radix and precision
+ confirms closest relative separation U1 .
+Radix confirmed.
+The number of significant digits of the Radix is 53.000000 .
+
+Diagnosis resumes after milestone Number 30 Page: 5
+
+Subtraction appears to be normalized, as it should be.
+Checking for guard digit in *, /, and -.
+ *, /, and - appear to have guard digits, as they should.
+
+Diagnosis resumes after milestone Number 40 Page: 6
+
+Checking rounding on multiply, divide and add/subtract.
+Multiplication appears to round correctly.
+Division appears to round correctly.
+Addition/Subtraction appears to round correctly.
+Checking for sticky bit.
+Sticky bit apparently used correctly.
+
+Does Multiplication commute? Testing on 20 random pairs.
+ No failures found in 20 integer pairs.
+
+Running test of square root(x).
+Testing if sqrt(X * X) == X for 20 Integers X.
+Test for sqrt monotonicity.
+sqrt has passed a test for Monotonicity.
+Testing whether sqrt is rounded or chopped.
+Square root appears to be correctly rounded.
+
+Diagnosis resumes after milestone Number 90 Page: 7
+
+Testing powers Z^i for small Integers Z and i.
+... no discrepancis found.
+
+Seeking Underflow thresholds UfThold and E0.
+Smallest strictly positive number found is E0 = 4.94066e-324 .
+Since comparison denies Z = 0, evaluating (Z + Z) / Z should be safe.
+What the machine gets for (Z + Z) / Z is 2.00000000000000000e+000 .
+This is O.K., provided Over/Underflow has NOT just been signaled.
+Underflow is gradual; it incurs Absolute Error =
+(roundoff in UfThold) < E0.
+The Underflow threshold is 2.22507385850720190e-308, below which
+calculation may suffer larger Relative error than merely roundoff.
+Since underflow occurs below the threshold
+UfThold = (2.00000000000000000e+000) ^ (-1.02200000000000000e+003)
+only underflow should afflict the expression
+ (2.00000000000000000e+000) ^ (-1.02200000000000000e+003);
+actually calculating yields: 0.00000000000000000e+000 .
+This computed value is O.K.
+
+Testing X^((X + 1) / (X - 1)) vs. exp(2) = 7.38905609893065220e+000 as X -> 1.
+Accuracy seems adequate.
+Testing powers Z^Q at four nearly extreme values.
+ ... no discrepancies found.
+
+
+Diagnosis resumes after milestone Number 160 Page: 8
+
+Searching for Overflow threshold:
+This may generate an error.
+Can `Z = -Y' overflow?
+Trying it on Y = -1.#INF0000000000000e+000 .
+Seems O.K.
+Overflow threshold is V = 1.79769313486231570e+308 .
+Overflow saturates at V0 = 1.#INF0000000000000e+000 .
+No Overflow should be signaled for V * 1 = 1.79769313486231570e+308
+ nor for V / 1 = 1.79769313486231570e+308 .
+Any overflow signal separating this * from the one
+above is a DEFECT.
+
+
+Diagnosis resumes after milestone Number 190 Page: 9
+
+
+What message and/or values does Division by Zero produce?
+ Trying to compute 1 / 0 produces ... 1.#INF000e+000 .
+
+ Trying to compute 0 / 0 produces ... -1.#IND000e+000 .
+
+Diagnosis resumes after milestone Number 220 Page: 10
+
+
+
+No failures, defects nor flaws have been discovered.
+Rounding appears to conform to the proposed IEEE standard P754,
+except for possibly Double Rounding during Gradual Underflow.
+The arithmetic diagnosed appears to be Excellent!
+END OF TEST.
diff --git a/lcc/x86/win32/tst/paranoia.2bk b/lcc/x86/win32/tst/paranoia.2bk
new file mode 100755
index 0000000..f6ddf16
--- /dev/null
+++ b/lcc/x86/win32/tst/paranoia.2bk
@@ -0,0 +1,16 @@
+tst/paranoia.c:1867: warning: missing return value
+tst/paranoia.c:1874: warning: missing return value
+tst/paranoia.c:1884: warning: missing return value
+tst/paranoia.c:1924: warning: missing return value
+tst/paranoia.c:1939: warning: missing return value
+tst/paranoia.c:1956: warning: missing return value
+tst/paranoia.c:1975: warning: missing return value
+tst/paranoia.c:1988: warning: missing return value
+tst/paranoia.c:1995: warning: missing return value
+tst/paranoia.c:2055: warning: missing return value
+tst/paranoia.c:2062: warning: missing return value
+tst/paranoia.c:2070: warning: missing return value
+tst/paranoia.c:2087: warning: missing return value
+tst/paranoia.c:2115: warning: missing return value
+tst/paranoia.c:2144: warning: missing return value
+tst/paranoia.c:2173: warning: missing return value
diff --git a/lcc/x86/win32/tst/paranoia.sbk b/lcc/x86/win32/tst/paranoia.sbk
new file mode 100755
index 0000000..bcce8d3
--- /dev/null
+++ b/lcc/x86/win32/tst/paranoia.sbk
@@ -0,0 +1,20480 @@
+.486
+.model flat
+extrn __fltused:near
+extrn __ftol:near
+_DATA segment
+public _Zero
+align 4
+_Zero label byte
+dd 00H
+dd 00H
+public _Half
+align 4
+_Half label byte
+dd 00H
+dd 03fe00000H
+public _One
+align 4
+_One label byte
+dd 00H
+dd 03ff00000H
+public _Two
+align 4
+_Two label byte
+dd 00H
+dd 040000000H
+public _Three
+align 4
+_Three label byte
+dd 00H
+dd 040080000H
+public _Four
+align 4
+_Four label byte
+dd 00H
+dd 040100000H
+public _Five
+align 4
+_Five label byte
+dd 00H
+dd 040140000H
+public _Eight
+align 4
+_Eight label byte
+dd 00H
+dd 040200000H
+public _Nine
+align 4
+_Nine label byte
+dd 00H
+dd 040220000H
+public _TwentySeven
+align 4
+_TwentySeven label byte
+dd 00H
+dd 0403b0000H
+public _ThirtyTwo
+align 4
+_ThirtyTwo label byte
+dd 00H
+dd 040400000H
+public _TwoForty
+align 4
+_TwoForty label byte
+dd 00H
+dd 0406e0000H
+public _MinusOne
+align 4
+_MinusOne label byte
+dd 00H
+dd 0bff00000H
+public _OneAndHalf
+align 4
+_OneAndHalf label byte
+dd 00H
+dd 03ff80000H
+public _NoTrials
+align 4
+_NoTrials label byte
+dd 20
+public _sigfpe
+_DATA ends
+_TEXT segment
+_sigfpe:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+inc dword ptr (_fpecount)
+lea edi,(L2)
+push edi
+call _printf
+add esp,4
+lea edi,(__iob+32)
+push edi
+call _fflush
+add esp,4
+mov edi,dword ptr (_sigsave)
+cmp edi,0
+je L4
+mov edi,dword ptr (_sigsave)
+push edi
+push 8
+call _signal
+add esp,8
+mov dword ptr (_sigsave),0
+push 1
+lea edi,(_ovfl_buf)
+push edi
+call _longjmp
+add esp,8
+L4:
+call _abort
+add esp,0
+L1:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 4
+L757 label byte
+dd L758
+dd L759
+dd L760
+dd L761
+public _main
+_DATA ends
+_TEXT segment
+_main:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,1684
+fld qword ptr (L7)
+fstp qword ptr (_Zero)
+fld qword ptr (L8)
+fstp qword ptr (_One)
+fld qword ptr (_One)
+fstp qword ptr (-8)[ebp]
+fld qword ptr (-8)[ebp]
+fadd qword ptr (-8)[ebp]
+fstp qword ptr (_Two)
+fld qword ptr (_Two)
+fstp qword ptr (-16)[ebp]
+fld qword ptr (-16)[ebp]
+fadd qword ptr (-8)[ebp]
+fstp qword ptr (_Three)
+fld qword ptr (_Three)
+fstp qword ptr (-24)[ebp]
+fld qword ptr (-24)[ebp]
+fadd qword ptr (-8)[ebp]
+fstp qword ptr (_Four)
+fld qword ptr (_Four)
+fstp qword ptr (-32)[ebp]
+fld qword ptr (-32)[ebp]
+fadd qword ptr (-8)[ebp]
+fstp qword ptr (_Five)
+fld qword ptr (-32)[ebp]
+fadd qword ptr (-32)[ebp]
+fstp qword ptr (_Eight)
+fld qword ptr (-24)[ebp]
+fmul qword ptr (-24)[ebp]
+fstp qword ptr (_Nine)
+fld qword ptr (_Nine)
+fmul qword ptr (-24)[ebp]
+fstp qword ptr (_TwentySeven)
+fld qword ptr (-32)[ebp]
+fmul qword ptr (_Eight)
+fstp qword ptr (_ThirtyTwo)
+fld qword ptr (-32)[ebp]
+fmul qword ptr (_Five)
+fmul qword ptr (-24)[ebp]
+fmul qword ptr (-32)[ebp]
+fstp qword ptr (_TwoForty)
+fld qword ptr (-8)[ebp]
+fchs
+fstp qword ptr (_MinusOne)
+fld qword ptr (-8)[ebp]
+fdiv qword ptr (-16)[ebp]
+fstp qword ptr (_Half)
+fld qword ptr (-8)[ebp]
+fadd qword ptr (_Half)
+fstp qword ptr (_OneAndHalf)
+mov dword ptr (_ErrCnt),0
+mov dword ptr (_ErrCnt+4),0
+mov dword ptr (_ErrCnt+8),0
+mov dword ptr (_ErrCnt+12),0
+mov dword ptr (_PageNo),1
+mov dword ptr (_Milestone),0
+lea edi,(_sigfpe)
+push edi
+push 8
+call _signal
+add esp,8
+call _Instructions
+add esp,0
+call _Pause
+add esp,0
+call _Heading
+add esp,0
+call _Pause
+add esp,0
+call _Characteristics
+add esp,0
+call _Pause
+add esp,0
+call _History
+add esp,0
+call _Pause
+add esp,0
+mov dword ptr (_Milestone),7
+lea edi,(L12)
+push edi
+call _printf
+add esp,4
+lea edi,(L14)
+push edi
+fld qword ptr (_Zero)
+fadd qword ptr (_Zero)
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L15
+fld qword ptr (_One)
+fsub qword ptr (_One)
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L15
+fld qword ptr (_Zero)
+fcomp qword ptr (_One)
+fstsw ax
+sahf
+jae L15
+fld qword ptr (_One)
+fadd qword ptr (_One)
+fld qword ptr (_Two)
+fcompp
+fstsw ax
+sahf
+jne L15
+mov dword ptr (-36)[ebp],1
+jmp L16
+L15:
+mov dword ptr (-36)[ebp],0
+L16:
+mov edi,dword ptr (-36)[ebp]
+push edi
+push 0
+call _TstCond
+add esp,12
+fld qword ptr (_Zero)
+fchs
+fstp qword ptr (_Z)
+fld qword ptr (L7)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+je L17
+inc dword ptr (_ErrCnt)
+lea edi,(L19)
+push edi
+call _printf
+add esp,4
+fld qword ptr (L20)
+fstp qword ptr (_U1)
+fld qword ptr (L8)
+fstp qword ptr (_Radix)
+call _TstPtUf
+add esp,0
+L17:
+lea edi,(L22)
+push edi
+fld qword ptr (_Two)
+fadd qword ptr (_One)
+fcomp qword ptr (_Three)
+fstsw ax
+sahf
+jne L23
+fld qword ptr (_Three)
+fadd qword ptr (_One)
+fcomp qword ptr (_Four)
+fstsw ax
+sahf
+jne L23
+fld qword ptr (_Four)
+fld qword ptr (_Two)
+fld qword ptr (_Two)
+fchs
+fmulp st(1),st
+faddp st(1),st
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L23
+fld qword ptr (_Four)
+fsub qword ptr (_Three)
+fsub qword ptr (_One)
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L23
+mov dword ptr (-56)[ebp],1
+jmp L24
+L23:
+mov dword ptr (-56)[ebp],0
+L24:
+mov edi,dword ptr (-56)[ebp]
+push edi
+push 0
+call _TstCond
+add esp,12
+fld qword ptr (L7)
+fsub qword ptr (_One)
+fcomp qword ptr (_MinusOne)
+fstsw ax
+sahf
+jne L27
+fld qword ptr (_MinusOne)
+fadd qword ptr (_One)
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L27
+fld qword ptr (_One)
+fadd qword ptr (_MinusOne)
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L27
+fld qword ptr (_One)
+sub esp,8
+fstp qword ptr [esp]
+call _fabs
+add esp,8
+fstp qword ptr (-132)[ebp]
+fld qword ptr (_MinusOne)
+fadd qword ptr (-132)[ebp]
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L27
+fld qword ptr (_MinusOne)
+fld qword ptr (_MinusOne)
+fmul qword ptr (_MinusOne)
+faddp st(1),st
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L27
+mov dword ptr (-100)[ebp],1
+jmp L28
+L27:
+mov dword ptr (-100)[ebp],0
+L28:
+lea edi,(L26)
+push edi
+mov edi,dword ptr (-100)[ebp]
+push edi
+push 0
+call _TstCond
+add esp,12
+lea edi,(L30)
+push edi
+fld qword ptr (_Half)
+fadd qword ptr (_MinusOne)
+fadd qword ptr (_Half)
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L31
+mov dword ptr (-152)[ebp],1
+jmp L32
+L31:
+mov dword ptr (-152)[ebp],0
+L32:
+mov edi,dword ptr (-152)[ebp]
+push edi
+push 0
+call _TstCond
+add esp,12
+mov dword ptr (_Milestone),10
+lea edi,(L34)
+push edi
+fld qword ptr (_Three)
+fmul qword ptr (_Three)
+fcomp qword ptr (_Nine)
+fstsw ax
+sahf
+jne L35
+fld qword ptr (_Nine)
+fmul qword ptr (_Three)
+fcomp qword ptr (_TwentySeven)
+fstsw ax
+sahf
+jne L35
+fld qword ptr (_Four)
+fadd qword ptr (_Four)
+fcomp qword ptr (_Eight)
+fstsw ax
+sahf
+jne L35
+fld qword ptr (_Eight)
+fmul qword ptr (_Four)
+fcomp qword ptr (_ThirtyTwo)
+fstsw ax
+sahf
+jne L35
+fld qword ptr (_ThirtyTwo)
+fsub qword ptr (_TwentySeven)
+fsub qword ptr (_Four)
+fsub qword ptr (_One)
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L35
+mov dword ptr (-164)[ebp],1
+jmp L36
+L35:
+mov dword ptr (-164)[ebp],0
+L36:
+mov edi,dword ptr (-164)[ebp]
+push edi
+push 0
+call _TstCond
+add esp,12
+lea edi,(L38)
+push edi
+fld qword ptr (_Four)
+fadd qword ptr (_One)
+fcomp qword ptr (_Five)
+fstsw ax
+sahf
+jne L39
+fld qword ptr (_Four)
+fmul qword ptr (_Five)
+fmul qword ptr (_Three)
+fmul qword ptr (_Four)
+fcomp qword ptr (_TwoForty)
+fstsw ax
+sahf
+jne L39
+fld qword ptr (_TwoForty)
+fdiv qword ptr (_Three)
+fld qword ptr (_Four)
+fmul qword ptr (_Four)
+fmul qword ptr (_Five)
+fsubp st(1),st
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L39
+fld qword ptr (_TwoForty)
+fdiv qword ptr (_Four)
+fld qword ptr (_Five)
+fmul qword ptr (_Three)
+fmul qword ptr (_Four)
+fsubp st(1),st
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L39
+fld qword ptr (_TwoForty)
+fdiv qword ptr (_Five)
+fld qword ptr (_Four)
+fmul qword ptr (_Three)
+fmul qword ptr (_Four)
+fsubp st(1),st
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L39
+mov dword ptr (-216)[ebp],1
+jmp L40
+L39:
+mov dword ptr (-216)[ebp],0
+L40:
+mov edi,dword ptr (-216)[ebp]
+push edi
+push 0
+call _TstCond
+add esp,12
+cmp dword ptr (_ErrCnt),0
+jne L41
+lea edi,(L43)
+push edi
+call _printf
+add esp,4
+lea edi,(L44)
+push edi
+call _printf
+add esp,4
+L41:
+lea edi,(L45)
+push edi
+call _printf
+add esp,4
+fld qword ptr (_One)
+fstp qword ptr (_W)
+L46:
+fld qword ptr (_W)
+fstp qword ptr (-264)[ebp]
+fld qword ptr (-264)[ebp]
+fadd qword ptr (-264)[ebp]
+fstp qword ptr (_W)
+fld qword ptr (_W)
+fstp qword ptr (-272)[ebp]
+fld qword ptr (-272)[ebp]
+fadd qword ptr (_One)
+fstp qword ptr (_Y)
+fld qword ptr (_Y)
+fsub qword ptr (-272)[ebp]
+fstp qword ptr (_Z)
+fld qword ptr (_Z)
+fsub qword ptr (_One)
+fstp qword ptr (_Y)
+L47:
+fld qword ptr (_Y)
+sub esp,8
+fstp qword ptr [esp]
+call _fabs
+add esp,8
+fstp qword ptr (-264)[ebp]
+fld qword ptr (_MinusOne)
+fadd qword ptr (-264)[ebp]
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+ja L46
+fld qword ptr (_Zero)
+fstp qword ptr (_Precision)
+fld qword ptr (_One)
+fstp qword ptr (_Y)
+L49:
+fld qword ptr (_Y)
+fstp qword ptr (-280)[ebp]
+fld qword ptr (_W)
+fadd qword ptr (-280)[ebp]
+fstp qword ptr (_Radix)
+fld qword ptr (-280)[ebp]
+fadd qword ptr (-280)[ebp]
+fstp qword ptr (_Y)
+fld qword ptr (_Radix)
+fsub qword ptr (_W)
+fstp qword ptr (_Radix)
+L50:
+fld qword ptr (_Zero)
+fcomp qword ptr (_Radix)
+fstsw ax
+sahf
+je L49
+fld qword ptr (_Two)
+fcomp qword ptr (_Radix)
+fstsw ax
+sahf
+jbe L52
+fld qword ptr (_One)
+fstp qword ptr (_Radix)
+L52:
+fld qword ptr (_Radix)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L54)
+push edi
+call _printf
+add esp,12
+fld qword ptr (L8)
+fcomp qword ptr (_Radix)
+fstsw ax
+sahf
+je L55
+fld qword ptr (_One)
+fstp qword ptr (_W)
+L57:
+fld qword ptr (_Precision)
+fadd qword ptr (_One)
+fstp qword ptr (_Precision)
+fld qword ptr (_W)
+fmul qword ptr (_Radix)
+fstp qword ptr (_W)
+fld qword ptr (_W)
+fadd qword ptr (_One)
+fstp qword ptr (_Y)
+L58:
+fld qword ptr (_Y)
+fsub qword ptr (_W)
+fld qword ptr (_One)
+fcompp
+fstsw ax
+sahf
+je L57
+L55:
+fld qword ptr (_One)
+fdiv qword ptr (_W)
+fstp qword ptr (_U1)
+fld qword ptr (_U1)
+fstp qword ptr (-272)[ebp]
+fld qword ptr (_Radix)
+fmul qword ptr (-272)[ebp]
+fstp qword ptr (_U2)
+fld qword ptr (-272)[ebp]
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L60)
+push edi
+call _printf
+add esp,12
+lea edi,(L61)
+push edi
+call _printf
+add esp,4
+fld qword ptr (_Radix)
+fstp qword ptr (_E0)
+fld qword ptr (_U1)
+fstp qword ptr (_E1)
+fld qword ptr (_U2)
+fstp qword ptr (_E9)
+fld qword ptr (_Precision)
+fstp qword ptr (_E3)
+fld qword ptr (_Four)
+fdiv qword ptr (_Three)
+fstp qword ptr (_X)
+fld qword ptr (_X)
+fsub qword ptr (_One)
+fstp qword ptr (_Third)
+fld qword ptr (_Third)
+fstp qword ptr (-280)[ebp]
+fld qword ptr (_Half)
+fsub qword ptr (-280)[ebp]
+fstp qword ptr (_F6)
+fld qword ptr (_F6)
+fstp qword ptr (-288)[ebp]
+fld qword ptr (-288)[ebp]
+fadd qword ptr (-288)[ebp]
+fstp qword ptr (_X)
+fld qword ptr (_X)
+fsub qword ptr (-280)[ebp]
+sub esp,8
+fstp qword ptr [esp]
+call _fabs
+add esp,8
+fstp qword ptr (-296)[ebp]
+fld qword ptr (-296)[ebp]
+fstp qword ptr (_X)
+fld qword ptr (_U2)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jbe L62
+fld qword ptr (_U2)
+fstp qword ptr (_X)
+L62:
+L64:
+fld qword ptr (_X)
+fstp qword ptr (_U2)
+fld qword ptr (_U2)
+fstp qword ptr (-304)[ebp]
+fld qword ptr (_Half)
+fmul qword ptr (-304)[ebp]
+fld qword ptr (_ThirtyTwo)
+fmul qword ptr (-304)[ebp]
+fmul qword ptr (-304)[ebp]
+faddp st(1),st
+fstp qword ptr (_Y)
+fld qword ptr (_One)
+fadd qword ptr (_Y)
+fstp qword ptr (_Y)
+fld qword ptr (_Y)
+fsub qword ptr (_One)
+fstp qword ptr (_X)
+L65:
+fld qword ptr (_X)
+fcomp qword ptr (_U2)
+fstsw ax
+sahf
+jae L67
+fld qword ptr (_Zero)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jb L64
+L67:
+fld qword ptr (_Two)
+fdiv qword ptr (_Three)
+fstp qword ptr (_X)
+fld qword ptr (_X)
+fsub qword ptr (_Half)
+fstp qword ptr (_F6)
+fld qword ptr (_F6)
+fstp qword ptr (-320)[ebp]
+fld qword ptr (-320)[ebp]
+fadd qword ptr (-320)[ebp]
+fstp qword ptr (_Third)
+fld qword ptr (_Third)
+fsub qword ptr (_Half)
+fstp qword ptr (_X)
+fld qword ptr (_X)
+fadd qword ptr (-320)[ebp]
+sub esp,8
+fstp qword ptr [esp]
+call _fabs
+add esp,8
+fstp qword ptr (-328)[ebp]
+fld qword ptr (-328)[ebp]
+fstp qword ptr (_X)
+fld qword ptr (_U1)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jbe L68
+fld qword ptr (_U1)
+fstp qword ptr (_X)
+L68:
+L70:
+fld qword ptr (_X)
+fstp qword ptr (_U1)
+fld qword ptr (_U1)
+fstp qword ptr (-344)[ebp]
+fld qword ptr (_Half)
+fmul qword ptr (-344)[ebp]
+fld qword ptr (_ThirtyTwo)
+fmul qword ptr (-344)[ebp]
+fmul qword ptr (-344)[ebp]
+faddp st(1),st
+fstp qword ptr (_Y)
+fld qword ptr (_Half)
+fsub qword ptr (_Y)
+fstp qword ptr (_Y)
+fld qword ptr (_Half)
+fadd qword ptr (_Y)
+fstp qword ptr (_X)
+fld qword ptr (_Half)
+fsub qword ptr (_X)
+fstp qword ptr (_Y)
+fld qword ptr (_Half)
+fadd qword ptr (_Y)
+fstp qword ptr (_X)
+L71:
+fld qword ptr (_X)
+fcomp qword ptr (_U1)
+fstsw ax
+sahf
+jae L73
+fld qword ptr (_Zero)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jb L70
+L73:
+fld qword ptr (_E1)
+fcomp qword ptr (_U1)
+fstsw ax
+sahf
+jne L74
+lea edi,(L76)
+push edi
+call _printf
+add esp,4
+jmp L75
+L74:
+fld qword ptr (_U1)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L77)
+push edi
+call _printf
+add esp,12
+L75:
+fld qword ptr (_One)
+fdiv qword ptr (_U1)
+fstp qword ptr (_W)
+fld qword ptr (_Half)
+fsub qword ptr (_U1)
+fadd qword ptr (_Half)
+fstp qword ptr (_F9)
+fld qword ptr (_U2)
+fdiv qword ptr (_U1)
+fadd qword ptr (L78)
+sub esp,8
+fstp qword ptr [esp]
+call _floor
+add esp,8
+fstp qword ptr (-360)[ebp]
+fld qword ptr (-360)[ebp]
+fstp qword ptr (_Radix)
+fld qword ptr (_E0)
+fcomp qword ptr (_Radix)
+fstsw ax
+sahf
+jne L79
+lea edi,(L81)
+push edi
+call _printf
+add esp,4
+jmp L80
+L79:
+fld qword ptr (_Radix)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L82)
+push edi
+call _printf
+add esp,12
+L80:
+lea edi,(L84)
+push edi
+fld qword ptr (_Eight)
+fadd qword ptr (_Eight)
+fcomp qword ptr (_Radix)
+fstsw ax
+sahf
+jb L85
+mov dword ptr (-364)[ebp],1
+jmp L86
+L85:
+mov dword ptr (-364)[ebp],0
+L86:
+mov edi,dword ptr (-364)[ebp]
+push edi
+push 2
+call _TstCond
+add esp,12
+lea edi,(L88)
+push edi
+fld qword ptr (_Two)
+fcomp qword ptr (_Radix)
+fstsw ax
+sahf
+je L92
+fld qword ptr (L93)
+fcomp qword ptr (_Radix)
+fstsw ax
+sahf
+je L92
+fld qword ptr (_One)
+fcomp qword ptr (_Radix)
+fstsw ax
+sahf
+jne L89
+L92:
+mov dword ptr (-376)[ebp],1
+jmp L90
+L89:
+mov dword ptr (-376)[ebp],0
+L90:
+mov edi,dword ptr (-376)[ebp]
+push edi
+push 3
+call _TstCond
+add esp,12
+mov dword ptr (_Milestone),20
+lea edi,(L95)
+push edi
+fld qword ptr (_F9)
+fsub qword ptr (_Half)
+fld qword ptr (_Half)
+fcompp
+fstsw ax
+sahf
+jbe L96
+mov dword ptr (-388)[ebp],1
+jmp L97
+L96:
+mov dword ptr (-388)[ebp],0
+L97:
+mov edi,dword ptr (-388)[ebp]
+push edi
+push 0
+call _TstCond
+add esp,12
+fld qword ptr (_F9)
+fstp qword ptr (_X)
+mov dword ptr (_I),1
+fld qword ptr (_X)
+fsub qword ptr (_Half)
+fstp qword ptr (_Y)
+fld qword ptr (_Y)
+fsub qword ptr (_Half)
+fstp qword ptr (_Z)
+lea edi,(L99)
+push edi
+fld qword ptr (_One)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jne L102
+fld qword ptr (_Zero)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+jne L100
+L102:
+mov dword ptr (-400)[ebp],1
+jmp L101
+L100:
+mov dword ptr (-400)[ebp],0
+L101:
+mov edi,dword ptr (-400)[ebp]
+push edi
+push 0
+call _TstCond
+add esp,12
+fld qword ptr (_One)
+fadd qword ptr (_U2)
+fstp qword ptr (_X)
+mov dword ptr (_I),0
+mov dword ptr (_Milestone),25
+fld qword ptr (_Radix)
+fsub qword ptr (_One)
+fstp qword ptr (_BMinusU2)
+fld qword ptr (_BMinusU2)
+fsub qword ptr (_U2)
+fadd qword ptr (_One)
+fstp qword ptr (_BMinusU2)
+fld qword ptr (_One)
+fcomp qword ptr (_Radix)
+fstsw ax
+sahf
+je L103
+fld qword ptr (_U1)
+sub esp,8
+fstp qword ptr [esp]
+call _log
+add esp,8
+fstp qword ptr (-440)[ebp]
+fld qword ptr (_Radix)
+sub esp,8
+fstp qword ptr [esp]
+call _log
+add esp,8
+fstp qword ptr (-448)[ebp]
+fld qword ptr (_TwoForty)
+fchs
+fmul qword ptr (-440)[ebp]
+fdiv qword ptr (-448)[ebp]
+fstp qword ptr (_X)
+fld qword ptr (_Half)
+fadd qword ptr (_X)
+sub esp,8
+fstp qword ptr [esp]
+call _floor
+add esp,8
+fstp qword ptr (-456)[ebp]
+fld qword ptr (-456)[ebp]
+fstp qword ptr (_Y)
+fld qword ptr (_X)
+fsub qword ptr (_Y)
+sub esp,8
+fstp qword ptr [esp]
+call _fabs
+add esp,8
+fstp qword ptr (-464)[ebp]
+fld qword ptr (-464)[ebp]
+fmul qword ptr (_Four)
+fld qword ptr (_One)
+fcompp
+fstsw ax
+sahf
+jbe L105
+fld qword ptr (_Y)
+fstp qword ptr (_X)
+L105:
+fld qword ptr (_X)
+fdiv qword ptr (_TwoForty)
+fstp qword ptr (_Precision)
+fld qword ptr (_Half)
+fadd qword ptr (_Precision)
+sub esp,8
+fstp qword ptr [esp]
+call _floor
+add esp,8
+fstp qword ptr (-472)[ebp]
+fld qword ptr (-472)[ebp]
+fstp qword ptr (_Y)
+fld qword ptr (_Precision)
+fsub qword ptr (_Y)
+sub esp,8
+fstp qword ptr [esp]
+call _fabs
+add esp,8
+fstp qword ptr (-480)[ebp]
+fld qword ptr (-480)[ebp]
+fmul qword ptr (_TwoForty)
+fld qword ptr (_Half)
+fcompp
+fstsw ax
+sahf
+jbe L107
+fld qword ptr (_Y)
+fstp qword ptr (_Precision)
+L107:
+L103:
+fld qword ptr (_Precision)
+sub esp,8
+fstp qword ptr [esp]
+call _floor
+add esp,8
+fstp qword ptr (-448)[ebp]
+fld qword ptr (-448)[ebp]
+fcomp qword ptr (_Precision)
+fstsw ax
+sahf
+jne L111
+fld qword ptr (_One)
+fcomp qword ptr (_Radix)
+fstsw ax
+sahf
+jne L109
+L111:
+lea edi,(L112)
+push edi
+call _printf
+add esp,4
+lea edi,(L113)
+push edi
+call _printf
+add esp,4
+L109:
+fld qword ptr (_One)
+fcomp qword ptr (_Radix)
+fstsw ax
+sahf
+jne L114
+lea edi,(L116)
+push edi
+call _printf
+add esp,4
+jmp L115
+L114:
+fld qword ptr (_Precision)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L117)
+push edi
+call _printf
+add esp,12
+L115:
+lea edi,(L119)
+push edi
+fld qword ptr (_U2)
+fmul qword ptr (_Nine)
+fmul qword ptr (_Nine)
+fmul qword ptr (_TwoForty)
+fld qword ptr (_One)
+fcompp
+fstsw ax
+sahf
+jbe L120
+mov dword ptr (-452)[ebp],1
+jmp L121
+L120:
+mov dword ptr (-452)[ebp],0
+L121:
+mov edi,dword ptr (-452)[ebp]
+push edi
+push 1
+call _TstCond
+add esp,12
+mov dword ptr (_Milestone),30
+fld qword ptr (_One)
+fdiv qword ptr (_Four)
+fstp qword ptr (-492)[ebp]
+fld qword ptr (_Four)
+fdiv qword ptr (_Three)
+fsub qword ptr (_One)
+fsub qword ptr (-492)[ebp]
+fmul qword ptr (_Three)
+fsub qword ptr (-492)[ebp]
+sub esp,8
+fstp qword ptr [esp]
+call _fabs
+add esp,8
+fstp qword ptr (-500)[ebp]
+fld qword ptr (-500)[ebp]
+fstp qword ptr (_X)
+L122:
+fld qword ptr (_X)
+fstp qword ptr (_Z2)
+fld qword ptr (_Z2)
+fstp qword ptr (-516)[ebp]
+fld qword ptr (_One)
+fld qword ptr (_Half)
+fmul qword ptr (-516)[ebp]
+fld qword ptr (_ThirtyTwo)
+fmul qword ptr (-516)[ebp]
+fmul qword ptr (-516)[ebp]
+faddp st(1),st
+faddp st(1),st
+fsub qword ptr (_One)
+fstp qword ptr (_X)
+L123:
+fld qword ptr (_X)
+fcomp qword ptr (_Z2)
+fstsw ax
+sahf
+jae L125
+fld qword ptr (_Zero)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jb L122
+L125:
+fld qword ptr (_Three)
+fdiv qword ptr (_Four)
+fld qword ptr (_Two)
+fdiv qword ptr (_Three)
+fsubp st(1),st
+fmul qword ptr (_Three)
+fld qword ptr (_One)
+fdiv qword ptr (_Four)
+fsubp st(1),st
+sub esp,8
+fstp qword ptr [esp]
+call _fabs
+add esp,8
+fstp qword ptr (-532)[ebp]
+fld qword ptr (-532)[ebp]
+fstp qword ptr (_Z)
+fld qword ptr (-532)[ebp]
+fstp qword ptr (_Y)
+fld qword ptr (-532)[ebp]
+fstp qword ptr (_X)
+L126:
+fld qword ptr (_Z)
+fstp qword ptr (_Z1)
+fld qword ptr (_One)
+fdiv qword ptr (_Two)
+fstp qword ptr (-540)[ebp]
+fld qword ptr (_Z1)
+fstp qword ptr (-548)[ebp]
+fld qword ptr (-540)[ebp]
+fld qword ptr (-540)[ebp]
+fld qword ptr (_Half)
+fmul qword ptr (-548)[ebp]
+fld qword ptr (_ThirtyTwo)
+fmul qword ptr (-548)[ebp]
+fmul qword ptr (-548)[ebp]
+faddp st(1),st
+fsubp st(1),st
+fadd qword ptr (-540)[ebp]
+fsubp st(1),st
+fadd qword ptr (-540)[ebp]
+fstp qword ptr (_Z)
+L127:
+fld qword ptr (_Z)
+fcomp qword ptr (_Z1)
+fstsw ax
+sahf
+jae L129
+fld qword ptr (_Zero)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+jb L126
+L129:
+L130:
+L133:
+fld qword ptr (_Y)
+fstp qword ptr (_Y1)
+fld qword ptr (_Y1)
+fstp qword ptr (-556)[ebp]
+fld qword ptr (_Half)
+fld qword ptr (_Half)
+fld qword ptr (_Half)
+fmul qword ptr (-556)[ebp]
+fld qword ptr (_ThirtyTwo)
+fmul qword ptr (-556)[ebp]
+fmul qword ptr (-556)[ebp]
+faddp st(1),st
+fsubp st(1),st
+fadd qword ptr (_Half)
+fsubp st(1),st
+fadd qword ptr (_Half)
+fstp qword ptr (_Y)
+L134:
+fld qword ptr (_Y)
+fcomp qword ptr (_Y1)
+fstsw ax
+sahf
+jae L136
+fld qword ptr (_Zero)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+jb L133
+L136:
+fld qword ptr (_X)
+fstp qword ptr (_X1)
+fld qword ptr (_X1)
+fstp qword ptr (-556)[ebp]
+fld qword ptr (_Half)
+fmul qword ptr (-556)[ebp]
+fld qword ptr (_ThirtyTwo)
+fmul qword ptr (-556)[ebp]
+fmul qword ptr (-556)[ebp]
+faddp st(1),st
+fsub qword ptr (_F9)
+fadd qword ptr (_F9)
+fstp qword ptr (_X)
+L131:
+fld qword ptr (_X)
+fcomp qword ptr (_X1)
+fstsw ax
+sahf
+jae L137
+fld qword ptr (_Zero)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jb L130
+L137:
+fld qword ptr (_Y1)
+fcomp qword ptr (_X1)
+fstsw ax
+sahf
+jne L140
+fld qword ptr (_Z1)
+fcomp qword ptr (_X1)
+fstsw ax
+sahf
+je L138
+L140:
+lea edi,(L141)
+push edi
+push 1
+call _BadCond
+add esp,8
+fld qword ptr (_Z1)
+sub esp,8
+fstp qword ptr [esp]
+fld qword ptr (_Y1)
+sub esp,8
+fstp qword ptr [esp]
+fld qword ptr (_X1)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L142)
+push edi
+call _printf
+add esp,28
+lea edi,(L143)
+push edi
+call _printf
+add esp,4
+lea edi,(L144)
+push edi
+call _printf
+add esp,4
+lea edi,(L145)
+push edi
+call _notify
+add esp,4
+fld qword ptr (_U1)
+fcomp qword ptr (_X1)
+fstsw ax
+sahf
+je L149
+fld qword ptr (_U1)
+fcomp qword ptr (_Y1)
+fstsw ax
+sahf
+je L149
+fld qword ptr (_U1)
+fcomp qword ptr (_Z1)
+fstsw ax
+sahf
+jne L139
+L149:
+lea edi,(L150)
+push edi
+call _printf
+add esp,4
+jmp L139
+L138:
+fld qword ptr (_U1)
+fcomp qword ptr (_Z1)
+fstsw ax
+sahf
+jne L153
+fld qword ptr (_U2)
+fcomp qword ptr (_Z2)
+fstsw ax
+sahf
+je L151
+L153:
+fld qword ptr (_U1)
+fcomp qword ptr (_Z1)
+fstsw ax
+sahf
+jbe L156
+fld qword ptr (_U2)
+fcomp qword ptr (_Z2)
+fstsw ax
+sahf
+ja L154
+L156:
+lea edi,(L157)
+push edi
+push 0
+call _BadCond
+add esp,8
+lea edi,(L158)
+push edi
+call _notify
+add esp,4
+fld qword ptr (_Z1)
+fsub qword ptr (_U1)
+sub esp,8
+fstp qword ptr [esp]
+fld qword ptr (_U1)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L159)
+push edi
+call _printf
+add esp,20
+fld qword ptr (_Z2)
+fsub qword ptr (_U2)
+sub esp,8
+fstp qword ptr [esp]
+fld qword ptr (_U2)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L160)
+push edi
+call _printf
+add esp,20
+jmp L155
+L154:
+fld qword ptr (_Zero)
+fcomp qword ptr (_Z1)
+fstsw ax
+sahf
+jae L163
+fld qword ptr (_Zero)
+fcomp qword ptr (_Z2)
+fstsw ax
+sahf
+jb L161
+L163:
+fld qword ptr (_Radix)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L164)
+push edi
+call _printf
+add esp,12
+lea edi,(L165)
+push edi
+call _printf
+add esp,4
+fld qword ptr (_Z2)
+sub esp,8
+fstp qword ptr [esp]
+fld qword ptr (_Z1)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L166)
+push edi
+call _printf
+add esp,20
+lea edi,(L167)
+push edi
+call _notify
+add esp,4
+L161:
+fld qword ptr (_Z2)
+fcomp qword ptr (_Z1)
+fstsw ax
+sahf
+jne L170
+fld qword ptr (_Zero)
+fcomp qword ptr (_Z1)
+fstsw ax
+sahf
+jae L168
+L170:
+fld qword ptr (_Z1)
+fdiv qword ptr (_U1)
+fstp qword ptr (_X)
+fld qword ptr (_Z2)
+fdiv qword ptr (_U2)
+fstp qword ptr (_Y)
+fld qword ptr (_X)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+jae L171
+fld qword ptr (_Y)
+fstp qword ptr (_X)
+L171:
+fld qword ptr (_X)
+sub esp,8
+fstp qword ptr [esp]
+call _log
+add esp,8
+fstp qword ptr (-580)[ebp]
+fld qword ptr (-580)[ebp]
+fchs
+fstp qword ptr (_Q)
+lea edi,(L173)
+push edi
+call _printf
+add esp,4
+fld qword ptr (_Radix)
+sub esp,8
+fstp qword ptr [esp]
+call _log
+add esp,8
+fstp qword ptr (-588)[ebp]
+fld qword ptr (_Q)
+fdiv qword ptr (-588)[ebp]
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L174)
+push edi
+call _printf
+add esp,12
+fld qword ptr (L93)
+sub esp,8
+fstp qword ptr [esp]
+call _log
+add esp,8
+fstp qword ptr (-596)[ebp]
+fld qword ptr (_Q)
+fdiv qword ptr (-596)[ebp]
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L175)
+push edi
+call _printf
+add esp,12
+L168:
+lea edi,(L150)
+push edi
+call _printf
+add esp,4
+L155:
+L151:
+L139:
+call _Pause
+add esp,0
+mov dword ptr (_Milestone),35
+fld qword ptr (_Two)
+fcomp qword ptr (_Radix)
+fstsw ax
+sahf
+ja L176
+fld qword ptr (_W)
+fld qword ptr (_Radix)
+fmul qword ptr (_Radix)
+fdivp st(1),st
+fstp qword ptr (_X)
+fld qword ptr (_X)
+fstp qword ptr (-576)[ebp]
+fld qword ptr (-576)[ebp]
+fadd qword ptr (_One)
+fstp qword ptr (_Y)
+fld qword ptr (_Y)
+fsub qword ptr (-576)[ebp]
+fstp qword ptr (_Z)
+fld qword ptr (_Z)
+fstp qword ptr (-584)[ebp]
+fld qword ptr (-584)[ebp]
+fadd qword ptr (_U2)
+fstp qword ptr (_T)
+fld qword ptr (_T)
+fsub qword ptr (-584)[ebp]
+fstp qword ptr (_X)
+lea edi,(L179)
+push edi
+fld qword ptr (_U2)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jne L180
+mov dword ptr (-560)[ebp],1
+jmp L181
+L180:
+mov dword ptr (-560)[ebp],0
+L181:
+mov edi,dword ptr (-560)[ebp]
+push edi
+push 0
+call _TstCond
+add esp,12
+fld qword ptr (_U2)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jne L182
+lea edi,(L184)
+push edi
+call _printf
+add esp,4
+L182:
+L176:
+lea edi,(L185)
+push edi
+call _printf
+add esp,4
+fld qword ptr (_F9)
+fmul qword ptr (_One)
+fstp qword ptr (_Y)
+fld qword ptr (_One)
+fmul qword ptr (_F9)
+fstp qword ptr (_Z)
+fld qword ptr (_F9)
+fsub qword ptr (_Half)
+fstp qword ptr (_X)
+fld qword ptr (_X)
+fstp qword ptr (-588)[ebp]
+fld qword ptr (_Y)
+fsub qword ptr (_Half)
+fsub qword ptr (-588)[ebp]
+fstp qword ptr (_Y)
+fld qword ptr (_Z)
+fsub qword ptr (_Half)
+fsub qword ptr (-588)[ebp]
+fstp qword ptr (_Z)
+fld qword ptr (_One)
+fadd qword ptr (_U2)
+fstp qword ptr (_X)
+fld qword ptr (_X)
+fstp qword ptr (-604)[ebp]
+fld qword ptr (-604)[ebp]
+fmul qword ptr (_Radix)
+fstp qword ptr (_T)
+fld qword ptr (_Radix)
+fmul qword ptr (-604)[ebp]
+fstp qword ptr (_R)
+fld qword ptr (_T)
+fsub qword ptr (_Radix)
+fstp qword ptr (_X)
+fld qword ptr (_Radix)
+fmul qword ptr (_U2)
+fstp qword ptr (-620)[ebp]
+fld qword ptr (_X)
+fsub qword ptr (-620)[ebp]
+fstp qword ptr (_X)
+fld qword ptr (_R)
+fsub qword ptr (_Radix)
+fstp qword ptr (_T)
+fld qword ptr (_T)
+fsub qword ptr (-620)[ebp]
+fstp qword ptr (_T)
+fld qword ptr (_Radix)
+fsub qword ptr (_One)
+fstp qword ptr (-628)[ebp]
+fld qword ptr (_X)
+fmul qword ptr (-628)[ebp]
+fstp qword ptr (_X)
+fld qword ptr (_T)
+fmul qword ptr (-628)[ebp]
+fstp qword ptr (_T)
+fld qword ptr (_Zero)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jne L186
+fld qword ptr (_Zero)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+jne L186
+fld qword ptr (_Zero)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+jne L186
+fld qword ptr (_Zero)
+fcomp qword ptr (_T)
+fstsw ax
+sahf
+jne L186
+mov dword ptr (_GMult),1
+jmp L187
+L186:
+mov dword ptr (_GMult),0
+lea edi,(L188)
+push edi
+push 0
+push 1
+call _TstCond
+add esp,12
+L187:
+fld qword ptr (_Radix)
+fmul qword ptr (_U2)
+fstp qword ptr (_Z)
+fld qword ptr (_Z)
+fstp qword ptr (-648)[ebp]
+fld qword ptr (_One)
+fadd qword ptr (-648)[ebp]
+fstp qword ptr (_X)
+fld qword ptr (_X)
+fstp qword ptr (-656)[ebp]
+fld qword ptr (-656)[ebp]
+fadd qword ptr (-648)[ebp]
+fld qword ptr (-656)[ebp]
+fmul qword ptr (-656)[ebp]
+fsubp st(1),st
+sub esp,8
+fstp qword ptr [esp]
+call _fabs
+add esp,8
+fstp qword ptr (-664)[ebp]
+fld qword ptr (-664)[ebp]
+fsub qword ptr (_U2)
+fstp qword ptr (_Y)
+fld qword ptr (_One)
+fsub qword ptr (_U2)
+fstp qword ptr (_X)
+fld qword ptr (_X)
+fstp qword ptr (-680)[ebp]
+fld qword ptr (-680)[ebp]
+fsub qword ptr (_U2)
+fld qword ptr (-680)[ebp]
+fmul qword ptr (-680)[ebp]
+fsubp st(1),st
+sub esp,8
+fstp qword ptr [esp]
+call _fabs
+add esp,8
+fstp qword ptr (-688)[ebp]
+fld qword ptr (-688)[ebp]
+fsub qword ptr (_U1)
+fstp qword ptr (_Z)
+lea edi,(L190)
+push edi
+fld qword ptr (_Zero)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+jb L191
+fld qword ptr (_Zero)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+jb L191
+mov dword ptr (-640)[ebp],1
+jmp L192
+L191:
+mov dword ptr (-640)[ebp],0
+L192:
+mov edi,dword ptr (-640)[ebp]
+push edi
+push 0
+call _TstCond
+add esp,12
+fld qword ptr (_One)
+fsub qword ptr (_U2)
+fstp qword ptr (_Y)
+fld qword ptr (_One)
+fadd qword ptr (_U2)
+fstp qword ptr (_X)
+fld qword ptr (_One)
+fdiv qword ptr (_Y)
+fstp qword ptr (_Z)
+fld qword ptr (_Z)
+fsub qword ptr (_X)
+fstp qword ptr (_Y)
+fld qword ptr (_One)
+fdiv qword ptr (_Three)
+fstp qword ptr (_X)
+fld qword ptr (_Three)
+fdiv qword ptr (_Nine)
+fstp qword ptr (_Z)
+fld qword ptr (_Z)
+fstp qword ptr (-740)[ebp]
+fld qword ptr (_X)
+fsub qword ptr (-740)[ebp]
+fstp qword ptr (_X)
+fld qword ptr (_Nine)
+fdiv qword ptr (_TwentySeven)
+fstp qword ptr (_T)
+fld qword ptr (-740)[ebp]
+fsub qword ptr (_T)
+fstp qword ptr (_Z)
+lea edi,(L194)
+push edi
+fld qword ptr (_Zero)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jne L195
+fld qword ptr (_Zero)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+jne L195
+fld qword ptr (_Zero)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+jne L195
+mov dword ptr (-700)[ebp],1
+jmp L196
+L195:
+mov dword ptr (-700)[ebp],0
+L196:
+mov edi,dword ptr (-700)[ebp]
+push edi
+push 2
+call _TstCond
+add esp,12
+fld qword ptr (_F9)
+fdiv qword ptr (_One)
+fstp qword ptr (_Y)
+fld qword ptr (_F9)
+fsub qword ptr (_Half)
+fstp qword ptr (_X)
+fld qword ptr (_Y)
+fsub qword ptr (_Half)
+fsub qword ptr (_X)
+fstp qword ptr (_Y)
+fld qword ptr (_One)
+fadd qword ptr (_U2)
+fstp qword ptr (_X)
+fld qword ptr (_X)
+fstp qword ptr (-780)[ebp]
+fld qword ptr (-780)[ebp]
+fdiv qword ptr (_One)
+fstp qword ptr (_T)
+fld qword ptr (_T)
+fsub qword ptr (-780)[ebp]
+fstp qword ptr (_X)
+fld qword ptr (_Zero)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jne L197
+fld qword ptr (_Zero)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+jne L197
+fld qword ptr (_Zero)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+jne L197
+mov dword ptr (_GDiv),1
+jmp L198
+L197:
+mov dword ptr (_GDiv),0
+lea edi,(L199)
+push edi
+push 0
+push 1
+call _TstCond
+add esp,12
+L198:
+fld qword ptr (_One)
+fld qword ptr (_One)
+fadd qword ptr (_U2)
+fdivp st(1),st
+fstp qword ptr (_X)
+fld qword ptr (_X)
+fsub qword ptr (_Half)
+fsub qword ptr (_Half)
+fstp qword ptr (_Y)
+lea edi,(L201)
+push edi
+fld qword ptr (_Zero)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+jbe L202
+mov dword ptr (-792)[ebp],1
+jmp L203
+L202:
+mov dword ptr (-792)[ebp],0
+L203:
+mov edi,dword ptr (-792)[ebp]
+push edi
+push 1
+call _TstCond
+add esp,12
+fld qword ptr (_One)
+fsub qword ptr (_U2)
+fstp qword ptr (_X)
+fld qword ptr (_One)
+fld qword ptr (_Radix)
+fmul qword ptr (_U2)
+faddp st(1),st
+fstp qword ptr (_Y)
+fld qword ptr (_X)
+fstp qword ptr (-844)[ebp]
+fld qword ptr (-844)[ebp]
+fmul qword ptr (_Radix)
+fstp qword ptr (_Z)
+fld qword ptr (_Y)
+fstp qword ptr (-852)[ebp]
+fld qword ptr (-852)[ebp]
+fmul qword ptr (_Radix)
+fstp qword ptr (_T)
+fld qword ptr (_Z)
+fdiv qword ptr (_Radix)
+fstp qword ptr (_R)
+fld qword ptr (_T)
+fdiv qword ptr (_Radix)
+fstp qword ptr (_StickyBit)
+fld qword ptr (_R)
+fsub qword ptr (-844)[ebp]
+fstp qword ptr (_X)
+fld qword ptr (_StickyBit)
+fsub qword ptr (-852)[ebp]
+fstp qword ptr (_Y)
+lea edi,(L205)
+push edi
+fld qword ptr (_Zero)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jne L206
+fld qword ptr (_Zero)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+jne L206
+mov dword ptr (-812)[ebp],1
+jmp L207
+L206:
+mov dword ptr (-812)[ebp],0
+L207:
+mov edi,dword ptr (-812)[ebp]
+push edi
+push 0
+call _TstCond
+add esp,12
+fld qword ptr (_One)
+fsub qword ptr (_U1)
+fstp qword ptr (_Y)
+fld qword ptr (_One)
+fsub qword ptr (_F9)
+fstp qword ptr (_X)
+fld qword ptr (_One)
+fsub qword ptr (_Y)
+fstp qword ptr (_Y)
+fld qword ptr (_Radix)
+fsub qword ptr (_U2)
+fstp qword ptr (_T)
+fld qword ptr (_Radix)
+fsub qword ptr (_BMinusU2)
+fstp qword ptr (_Z)
+fld qword ptr (_Radix)
+fsub qword ptr (_T)
+fstp qword ptr (_T)
+fld qword ptr (_U1)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jne L208
+fld qword ptr (_U1)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+jne L208
+fld qword ptr (_U2)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+jne L208
+fld qword ptr (_U2)
+fcomp qword ptr (_T)
+fstsw ax
+sahf
+jne L208
+mov dword ptr (_GAddSub),1
+jmp L209
+L208:
+mov dword ptr (_GAddSub),0
+lea edi,(L210)
+push edi
+push 0
+push 1
+call _TstCond
+add esp,12
+L209:
+fld qword ptr (_One)
+fcomp qword ptr (_F9)
+fstsw ax
+sahf
+je L211
+fld qword ptr (_F9)
+fsub qword ptr (_One)
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+ja L211
+lea edi,(L213)
+push edi
+push 1
+call _BadCond
+add esp,8
+lea edi,(L214)
+push edi
+call _printf
+add esp,4
+lea edi,(L215)
+push edi
+call _printf
+add esp,4
+lea edi,(L216)
+push edi
+call _printf
+add esp,4
+L211:
+cmp dword ptr (_GMult),1
+jne L217
+cmp dword ptr (_GDiv),1
+jne L217
+cmp dword ptr (_GAddSub),1
+jne L217
+lea edi,(L219)
+push edi
+call _printf
+add esp,4
+L217:
+mov dword ptr (_Milestone),40
+call _Pause
+add esp,0
+lea edi,(L220)
+push edi
+call _printf
+add esp,4
+mov dword ptr (_RMult),0
+mov dword ptr (_RDiv),0
+mov dword ptr (_RAddSub),0
+fld qword ptr (_Radix)
+fdiv qword ptr (_Two)
+fstp qword ptr (_RadixD2)
+fld qword ptr (_Two)
+fstp qword ptr (_A1)
+mov dword ptr (_Done),0
+L221:
+fld qword ptr (_Radix)
+fstp qword ptr (_AInvrse)
+L224:
+fld qword ptr (_AInvrse)
+fstp qword ptr (-924)[ebp]
+fld qword ptr (-924)[ebp]
+fstp qword ptr (_X)
+fld qword ptr (-924)[ebp]
+fdiv qword ptr (_A1)
+fstp qword ptr (_AInvrse)
+L225:
+fld qword ptr (_AInvrse)
+sub esp,8
+fstp qword ptr [esp]
+call _floor
+add esp,8
+fstp qword ptr (-924)[ebp]
+fld qword ptr (_AInvrse)
+fcomp qword ptr (-924)[ebp]
+fstsw ax
+sahf
+je L224
+fld qword ptr (_One)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+je L230
+fld qword ptr (_Three)
+fcomp qword ptr (_A1)
+fstsw ax
+sahf
+jae L228
+L230:
+mov dword ptr (-928)[ebp],1
+jmp L229
+L228:
+mov dword ptr (-928)[ebp],0
+L229:
+mov edi,dword ptr (-928)[ebp]
+mov dword ptr (_Done),edi
+cmp dword ptr (_Done),0
+jne L231
+fld qword ptr (_Nine)
+fadd qword ptr (_One)
+fstp qword ptr (_A1)
+L231:
+L222:
+cmp dword ptr (_Done),0
+je L221
+fld qword ptr (_One)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jne L233
+fld qword ptr (_Radix)
+fstp qword ptr (_A1)
+L233:
+fld qword ptr (_One)
+fdiv qword ptr (_A1)
+fstp qword ptr (_AInvrse)
+fld qword ptr (_A1)
+fstp qword ptr (_X)
+fld qword ptr (_AInvrse)
+fstp qword ptr (_Y)
+mov dword ptr (_Done),0
+L235:
+fld qword ptr (_X)
+fmul qword ptr (_Y)
+fsub qword ptr (_Half)
+fstp qword ptr (_Z)
+lea edi,(L239)
+push edi
+fld qword ptr (_Half)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+jne L240
+mov dword ptr (-928)[ebp],1
+jmp L241
+L240:
+mov dword ptr (-928)[ebp],0
+L241:
+mov edi,dword ptr (-928)[ebp]
+push edi
+push 0
+call _TstCond
+add esp,12
+fld qword ptr (_Radix)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jne L243
+mov dword ptr (-940)[ebp],1
+jmp L244
+L243:
+mov dword ptr (-940)[ebp],0
+L244:
+mov edi,dword ptr (-940)[ebp]
+mov dword ptr (_Done),edi
+fld qword ptr (_Radix)
+fstp qword ptr (_X)
+fld qword ptr (_One)
+fdiv qword ptr (_X)
+fstp qword ptr (_Y)
+L236:
+cmp dword ptr (_Done),0
+je L235
+fld qword ptr (_One)
+fadd qword ptr (_U2)
+fstp qword ptr (_Y2)
+fld qword ptr (_One)
+fsub qword ptr (_U2)
+fstp qword ptr (_Y1)
+fld qword ptr (_OneAndHalf)
+fsub qword ptr (_U2)
+fstp qword ptr (_X)
+fld qword ptr (_OneAndHalf)
+fadd qword ptr (_U2)
+fstp qword ptr (_Y)
+fld qword ptr (_X)
+fstp qword ptr (-956)[ebp]
+fld qword ptr (_Y2)
+fstp qword ptr (-964)[ebp]
+fld qword ptr (-956)[ebp]
+fsub qword ptr (_U2)
+fmul qword ptr (-964)[ebp]
+fstp qword ptr (_Z)
+fld qword ptr (_Y)
+fstp qword ptr (-972)[ebp]
+fld qword ptr (_Y1)
+fstp qword ptr (-980)[ebp]
+fld qword ptr (-972)[ebp]
+fmul qword ptr (-980)[ebp]
+fstp qword ptr (_T)
+fld qword ptr (_Z)
+fsub qword ptr (-956)[ebp]
+fstp qword ptr (_Z)
+fld qword ptr (_T)
+fsub qword ptr (-956)[ebp]
+fstp qword ptr (_T)
+fld qword ptr (-956)[ebp]
+fmul qword ptr (-964)[ebp]
+fstp qword ptr (_X)
+fld qword ptr (-972)[ebp]
+fadd qword ptr (_U2)
+fmul qword ptr (-980)[ebp]
+fstp qword ptr (_Y)
+fld qword ptr (_X)
+fsub qword ptr (_OneAndHalf)
+fstp qword ptr (_X)
+fld qword ptr (_Y)
+fsub qword ptr (_OneAndHalf)
+fstp qword ptr (_Y)
+fld qword ptr (_Zero)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jne L245
+fld qword ptr (_Zero)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+jne L245
+fld qword ptr (_Zero)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+jne L245
+fld qword ptr (_Zero)
+fcomp qword ptr (_T)
+fstsw ax
+sahf
+jb L245
+fld qword ptr (_OneAndHalf)
+fadd qword ptr (_U2)
+fstp qword ptr (-1012)[ebp]
+fld qword ptr (-1012)[ebp]
+fmul qword ptr (_Y2)
+fstp qword ptr (_X)
+fld qword ptr (_OneAndHalf)
+fsub qword ptr (_U2)
+fstp qword ptr (-1028)[ebp]
+fld qword ptr (-1028)[ebp]
+fsub qword ptr (_U2)
+fstp qword ptr (_Y)
+fld qword ptr (-1012)[ebp]
+fadd qword ptr (_U2)
+fstp qword ptr (_Z)
+fld qword ptr (_Y1)
+fstp qword ptr (-1036)[ebp]
+fld qword ptr (-1028)[ebp]
+fmul qword ptr (-1036)[ebp]
+fstp qword ptr (_T)
+fld qword ptr (_Z)
+fstp qword ptr (-1044)[ebp]
+fld qword ptr (-1044)[ebp]
+fadd qword ptr (_U2)
+fstp qword ptr (-1052)[ebp]
+fld qword ptr (_X)
+fsub qword ptr (-1052)[ebp]
+fstp qword ptr (_X)
+fld qword ptr (_Y)
+fstp qword ptr (-1060)[ebp]
+fld qword ptr (-1060)[ebp]
+fmul qword ptr (-1036)[ebp]
+fstp qword ptr (_StickyBit)
+fld qword ptr (-1044)[ebp]
+fmul qword ptr (_Y2)
+fstp qword ptr (_S)
+fld qword ptr (_T)
+fsub qword ptr (-1060)[ebp]
+fstp qword ptr (_T)
+fld qword ptr (_U2)
+fsub qword ptr (-1060)[ebp]
+fadd qword ptr (_StickyBit)
+fstp qword ptr (_Y)
+fld qword ptr (_S)
+fld qword ptr (-1052)[ebp]
+fadd qword ptr (_U2)
+fsubp st(1),st
+fstp qword ptr (_Z)
+fld qword ptr (_Y2)
+fadd qword ptr (_U2)
+fmul qword ptr (-1036)[ebp]
+fstp qword ptr (_StickyBit)
+fld qword ptr (_Y2)
+fmul qword ptr (-1036)[ebp]
+fstp qword ptr (_Y1)
+fld qword ptr (_StickyBit)
+fsub qword ptr (_Y2)
+fstp qword ptr (_StickyBit)
+fld qword ptr (_Y1)
+fsub qword ptr (_Half)
+fstp qword ptr (_Y1)
+fld qword ptr (_Zero)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jne L247
+fld qword ptr (_Zero)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+jne L247
+fld qword ptr (_Zero)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+jne L247
+fld qword ptr (_Zero)
+fcomp qword ptr (_T)
+fstsw ax
+sahf
+jne L247
+fld qword ptr (_Zero)
+fcomp qword ptr (_StickyBit)
+fstsw ax
+sahf
+jne L247
+fld qword ptr (_Half)
+fcomp qword ptr (_Y1)
+fstsw ax
+sahf
+jne L247
+mov dword ptr (_RMult),1
+lea edi,(L249)
+push edi
+call _printf
+add esp,4
+jmp L248
+L247:
+fld qword ptr (_X)
+fadd qword ptr (_U2)
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L250
+fld qword ptr (_Zero)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+jbe L250
+fld qword ptr (_Z)
+fadd qword ptr (_U2)
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L250
+fld qword ptr (_Zero)
+fcomp qword ptr (_T)
+fstsw ax
+sahf
+jbe L250
+fld qword ptr (_StickyBit)
+fadd qword ptr (_U2)
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L250
+fld qword ptr (_Half)
+fcomp qword ptr (_Y1)
+fstsw ax
+sahf
+jbe L250
+mov dword ptr (_RMult),2
+lea edi,(L252)
+push edi
+call _printf
+add esp,4
+jmp L251
+L250:
+lea edi,(L253)
+push edi
+call _printf
+add esp,4
+L251:
+L248:
+cmp dword ptr (_RMult),1
+jne L246
+cmp dword ptr (_GMult),0
+jne L246
+lea edi,(L256)
+push edi
+call _notify
+add esp,4
+jmp L246
+L245:
+lea edi,(L253)
+push edi
+call _printf
+add esp,4
+L246:
+mov dword ptr (_Milestone),45
+fld qword ptr (_One)
+fadd qword ptr (_U2)
+fstp qword ptr (_Y2)
+fld qword ptr (_One)
+fsub qword ptr (_U2)
+fstp qword ptr (_Y1)
+fld qword ptr (_OneAndHalf)
+fadd qword ptr (_U2)
+fstp qword ptr (-1020)[ebp]
+fld qword ptr (-1020)[ebp]
+fadd qword ptr (_U2)
+fstp qword ptr (_Z)
+fld qword ptr (_Z)
+fstp qword ptr (-1028)[ebp]
+fld qword ptr (_Y2)
+fstp qword ptr (-1036)[ebp]
+fld qword ptr (-1028)[ebp]
+fdiv qword ptr (-1036)[ebp]
+fstp qword ptr (_X)
+fld qword ptr (_OneAndHalf)
+fsub qword ptr (_U2)
+fsub qword ptr (_U2)
+fstp qword ptr (_T)
+fld qword ptr (_T)
+fstp qword ptr (-1044)[ebp]
+fld qword ptr (_Y1)
+fstp qword ptr (-1052)[ebp]
+fld qword ptr (-1044)[ebp]
+fsub qword ptr (_U2)
+fdiv qword ptr (-1052)[ebp]
+fstp qword ptr (_Y)
+fld qword ptr (-1028)[ebp]
+fadd qword ptr (_U2)
+fdiv qword ptr (-1036)[ebp]
+fstp qword ptr (_Z)
+fld qword ptr (_X)
+fsub qword ptr (_OneAndHalf)
+fstp qword ptr (_X)
+fld qword ptr (_Y)
+fsub qword ptr (-1044)[ebp]
+fstp qword ptr (_Y)
+fld qword ptr (-1044)[ebp]
+fdiv qword ptr (-1052)[ebp]
+fstp qword ptr (_T)
+fld qword ptr (_Z)
+fsub qword ptr (-1020)[ebp]
+fstp qword ptr (_Z)
+fld qword ptr (_U2)
+fsub qword ptr (_OneAndHalf)
+fadd qword ptr (_T)
+fstp qword ptr (_T)
+fld qword ptr (_Zero)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jb L257
+fld qword ptr (_Zero)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+jb L257
+fld qword ptr (_Zero)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+jb L257
+fld qword ptr (_Zero)
+fcomp qword ptr (_T)
+fstsw ax
+sahf
+jb L257
+fld qword ptr (_Y2)
+fstp qword ptr (-1076)[ebp]
+fld qword ptr (_OneAndHalf)
+fdiv qword ptr (-1076)[ebp]
+fstp qword ptr (_X)
+fld qword ptr (_OneAndHalf)
+fsub qword ptr (_U2)
+fstp qword ptr (_Y)
+fld qword ptr (_OneAndHalf)
+fadd qword ptr (_U2)
+fstp qword ptr (_Z)
+fld qword ptr (_Y)
+fstp qword ptr (-1092)[ebp]
+fld qword ptr (_X)
+fsub qword ptr (-1092)[ebp]
+fstp qword ptr (_X)
+fld qword ptr (_Y1)
+fstp qword ptr (-1100)[ebp]
+fld qword ptr (_OneAndHalf)
+fdiv qword ptr (-1100)[ebp]
+fstp qword ptr (_T)
+fld qword ptr (-1092)[ebp]
+fdiv qword ptr (-1100)[ebp]
+fstp qword ptr (_Y)
+fld qword ptr (_Z)
+fstp qword ptr (-1108)[ebp]
+fld qword ptr (_T)
+fld qword ptr (-1108)[ebp]
+fadd qword ptr (_U2)
+fsubp st(1),st
+fstp qword ptr (_T)
+fld qword ptr (_Y)
+fsub qword ptr (-1108)[ebp]
+fstp qword ptr (_Y)
+fld qword ptr (-1108)[ebp]
+fdiv qword ptr (-1076)[ebp]
+fstp qword ptr (_Z)
+fld qword ptr (-1076)[ebp]
+fadd qword ptr (_U2)
+fdiv qword ptr (-1076)[ebp]
+fstp qword ptr (_Y1)
+fld qword ptr (_Z)
+fsub qword ptr (_OneAndHalf)
+fstp qword ptr (_Z)
+fld qword ptr (_Y1)
+fsub qword ptr (-1076)[ebp]
+fstp qword ptr (_Y2)
+fld qword ptr (_F9)
+fsub qword ptr (_U1)
+fdiv qword ptr (_F9)
+fstp qword ptr (_Y1)
+fld qword ptr (_Zero)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jne L259
+fld qword ptr (_Zero)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+jne L259
+fld qword ptr (_Zero)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+jne L259
+fld qword ptr (_Zero)
+fcomp qword ptr (_T)
+fstsw ax
+sahf
+jne L259
+fld qword ptr (_Zero)
+fcomp qword ptr (_Y2)
+fstsw ax
+sahf
+jne L259
+fld qword ptr (_Zero)
+fcomp qword ptr (_Y2)
+fstsw ax
+sahf
+jne L259
+fld qword ptr (_Y1)
+fsub qword ptr (_Half)
+fld qword ptr (_F9)
+fsub qword ptr (_Half)
+fcompp
+fstsw ax
+sahf
+jne L259
+mov dword ptr (_RDiv),1
+lea edi,(L261)
+push edi
+call _printf
+add esp,4
+cmp dword ptr (_GDiv),0
+jne L260
+lea edi,(L264)
+push edi
+call _notify
+add esp,4
+jmp L260
+L259:
+fld qword ptr (_Zero)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jbe L265
+fld qword ptr (_Zero)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+jbe L265
+fld qword ptr (_Zero)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+jbe L265
+fld qword ptr (_Zero)
+fcomp qword ptr (_T)
+fstsw ax
+sahf
+jbe L265
+fld qword ptr (_Zero)
+fcomp qword ptr (_Y2)
+fstsw ax
+sahf
+jbe L265
+fld qword ptr (_Y1)
+fsub qword ptr (_Half)
+fld qword ptr (_F9)
+fsub qword ptr (_Half)
+fcompp
+fstsw ax
+sahf
+jbe L265
+mov dword ptr (_RDiv),2
+lea edi,(L267)
+push edi
+call _printf
+add esp,4
+L265:
+L260:
+L257:
+cmp dword ptr (_RDiv),0
+jne L268
+lea edi,(L270)
+push edi
+call _printf
+add esp,4
+L268:
+fld qword ptr (_One)
+fdiv qword ptr (_Radix)
+fstp qword ptr (_BInvrse)
+lea edi,(L272)
+push edi
+fld qword ptr (_BInvrse)
+fmul qword ptr (_Radix)
+fsub qword ptr (_Half)
+fld qword ptr (_Half)
+fcompp
+fstsw ax
+sahf
+jne L273
+mov dword ptr (-1064)[ebp],1
+jmp L274
+L273:
+mov dword ptr (-1064)[ebp],0
+L274:
+mov edi,dword ptr (-1064)[ebp]
+push edi
+push 0
+call _TstCond
+add esp,12
+mov dword ptr (_Milestone),50
+lea edi,(L276)
+push edi
+fld qword ptr (_F9)
+fadd qword ptr (_U1)
+fsub qword ptr (_Half)
+fld qword ptr (_Half)
+fcompp
+fstsw ax
+sahf
+jne L277
+fld qword ptr (_BMinusU2)
+fadd qword ptr (_U2)
+fsub qword ptr (_One)
+fld qword ptr (_Radix)
+fsub qword ptr (_One)
+fcompp
+fstsw ax
+sahf
+jne L277
+mov dword ptr (-1084)[ebp],1
+jmp L278
+L277:
+mov dword ptr (-1084)[ebp],0
+L278:
+mov edi,dword ptr (-1084)[ebp]
+push edi
+push 0
+call _TstCond
+add esp,12
+fld qword ptr (_One)
+fld qword ptr (_U1)
+fmul qword ptr (_U1)
+fsubp st(1),st
+fstp qword ptr (_X)
+fld qword ptr (_One)
+fld qword ptr (_U2)
+fld qword ptr (_One)
+fsub qword ptr (_U2)
+fmulp st(1),st
+faddp st(1),st
+fstp qword ptr (_Y)
+fld qword ptr (_F9)
+fsub qword ptr (_Half)
+fstp qword ptr (_Z)
+fld qword ptr (_X)
+fsub qword ptr (_Half)
+fsub qword ptr (_Z)
+fstp qword ptr (_X)
+fld qword ptr (_Y)
+fsub qword ptr (_One)
+fstp qword ptr (_Y)
+fld qword ptr (_Zero)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jne L279
+fld qword ptr (_Zero)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+jne L279
+mov dword ptr (_RAddSub),2
+lea edi,(L281)
+push edi
+call _printf
+add esp,4
+L279:
+cmp dword ptr (_GAddSub),1
+jne L282
+fld qword ptr (_Half)
+fadd qword ptr (_U2)
+fmul qword ptr (_U2)
+fstp qword ptr (_X)
+fld qword ptr (_Half)
+fsub qword ptr (_U2)
+fmul qword ptr (_U2)
+fstp qword ptr (_Y)
+fld qword ptr (_One)
+fadd qword ptr (_X)
+fstp qword ptr (_X)
+fld qword ptr (_One)
+fadd qword ptr (_Y)
+fstp qword ptr (_Y)
+fld qword ptr (_One)
+fadd qword ptr (_U2)
+fsub qword ptr (_X)
+fstp qword ptr (_X)
+fld qword ptr (_One)
+fsub qword ptr (_Y)
+fstp qword ptr (_Y)
+fld qword ptr (_Zero)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jne L284
+fld qword ptr (_Zero)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+jne L284
+fld qword ptr (_Half)
+fadd qword ptr (_U2)
+fmul qword ptr (_U1)
+fstp qword ptr (_X)
+fld qword ptr (_Half)
+fsub qword ptr (_U2)
+fmul qword ptr (_U1)
+fstp qword ptr (_Y)
+fld qword ptr (_One)
+fsub qword ptr (_X)
+fstp qword ptr (_X)
+fld qword ptr (_One)
+fsub qword ptr (_Y)
+fstp qword ptr (_Y)
+fld qword ptr (_F9)
+fsub qword ptr (_X)
+fstp qword ptr (_X)
+fld qword ptr (_One)
+fsub qword ptr (_Y)
+fstp qword ptr (_Y)
+fld qword ptr (_Zero)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jne L286
+fld qword ptr (_Zero)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+jne L286
+mov dword ptr (_RAddSub),1
+lea edi,(L288)
+push edi
+call _printf
+add esp,4
+cmp dword ptr (_GAddSub),0
+jne L283
+lea edi,(L291)
+push edi
+call _notify
+add esp,4
+jmp L283
+L286:
+lea edi,(L292)
+push edi
+call _printf
+add esp,4
+jmp L283
+L284:
+lea edi,(L292)
+push edi
+call _printf
+add esp,4
+jmp L283
+L282:
+lea edi,(L292)
+push edi
+call _printf
+add esp,4
+L283:
+fld qword ptr (_One)
+fstp qword ptr (_S)
+fld qword ptr (_One)
+fld qword ptr (_Half)
+fld qword ptr (_One)
+fadd qword ptr (_Half)
+fmulp st(1),st
+faddp st(1),st
+fstp qword ptr (_X)
+fld qword ptr (_One)
+fadd qword ptr (_U2)
+fmul qword ptr (_Half)
+fstp qword ptr (_Y)
+fld qword ptr (_X)
+fstp qword ptr (-1164)[ebp]
+fld qword ptr (_Y)
+fstp qword ptr (-1172)[ebp]
+fld qword ptr (-1164)[ebp]
+fsub qword ptr (-1172)[ebp]
+fstp qword ptr (_Z)
+fld qword ptr (-1172)[ebp]
+fsub qword ptr (-1164)[ebp]
+fstp qword ptr (_T)
+fld qword ptr (_Z)
+fadd qword ptr (_T)
+fstp qword ptr (_StickyBit)
+fld qword ptr (_Zero)
+fcomp qword ptr (_StickyBit)
+fstsw ax
+sahf
+je L293
+fld qword ptr (_Zero)
+fstp qword ptr (_S)
+lea edi,(L295)
+push edi
+push 3
+call _BadCond
+add esp,8
+L293:
+fld qword ptr (_Zero)
+fstp qword ptr (_StickyBit)
+cmp dword ptr (_GMult),1
+jne L296
+cmp dword ptr (_GDiv),1
+jne L296
+cmp dword ptr (_GAddSub),1
+jne L296
+cmp dword ptr (_RMult),1
+jne L296
+cmp dword ptr (_RDiv),1
+jne L296
+cmp dword ptr (_RAddSub),1
+jne L296
+fld qword ptr (_RadixD2)
+sub esp,8
+fstp qword ptr [esp]
+call _floor
+add esp,8
+fstp qword ptr (-1180)[ebp]
+fld qword ptr (_RadixD2)
+fcomp qword ptr (-1180)[ebp]
+fstsw ax
+sahf
+jne L296
+lea edi,(L298)
+push edi
+call _printf
+add esp,4
+fld qword ptr (_Half)
+fadd qword ptr (_U1)
+fmul qword ptr (_U2)
+fstp qword ptr (_X)
+fld qword ptr (_Half)
+fmul qword ptr (_U2)
+fstp qword ptr (_Y)
+fld qword ptr (_One)
+fadd qword ptr (_Y)
+fstp qword ptr (_Z)
+fld qword ptr (_One)
+fadd qword ptr (_X)
+fstp qword ptr (_T)
+fld qword ptr (_Z)
+fsub qword ptr (_One)
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jb L299
+fld qword ptr (_T)
+fsub qword ptr (_One)
+fld qword ptr (_U2)
+fcompp
+fstsw ax
+sahf
+ja L299
+fld qword ptr (_T)
+fadd qword ptr (_Y)
+fstp qword ptr (_Z)
+fld qword ptr (_Z)
+fsub qword ptr (_X)
+fstp qword ptr (_Y)
+fld qword ptr (_Z)
+fsub qword ptr (_T)
+fld qword ptr (_U2)
+fcompp
+fstsw ax
+sahf
+ja L301
+fld qword ptr (_Y)
+fsub qword ptr (_T)
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L301
+fld qword ptr (_Half)
+fadd qword ptr (_U1)
+fmul qword ptr (_U1)
+fstp qword ptr (_X)
+fld qword ptr (_Half)
+fmul qword ptr (_U1)
+fstp qword ptr (_Y)
+fld qword ptr (_One)
+fsub qword ptr (_Y)
+fstp qword ptr (_Z)
+fld qword ptr (_One)
+fsub qword ptr (_X)
+fstp qword ptr (_T)
+fld qword ptr (_Z)
+fsub qword ptr (_One)
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L303
+fld qword ptr (_T)
+fsub qword ptr (_F9)
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L303
+fld qword ptr (_Half)
+fsub qword ptr (_U1)
+fmul qword ptr (_U1)
+fstp qword ptr (_Z)
+fld qword ptr (_F9)
+fsub qword ptr (_Z)
+fstp qword ptr (_T)
+fld qword ptr (_F9)
+fsub qword ptr (_Y)
+fstp qword ptr (_Q)
+fld qword ptr (_T)
+fsub qword ptr (_F9)
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L305
+fld qword ptr (_F9)
+fsub qword ptr (_U1)
+fsub qword ptr (_Q)
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L305
+fld qword ptr (_One)
+fadd qword ptr (_U2)
+fmul qword ptr (_OneAndHalf)
+fstp qword ptr (_Z)
+fld qword ptr (_OneAndHalf)
+fadd qword ptr (_U2)
+fsub qword ptr (_Z)
+fadd qword ptr (_U2)
+fstp qword ptr (_T)
+fld qword ptr (_One)
+fld qword ptr (_Half)
+fdiv qword ptr (_Radix)
+faddp st(1),st
+fstp qword ptr (_X)
+fld qword ptr (_One)
+fld qword ptr (_Radix)
+fmul qword ptr (_U2)
+faddp st(1),st
+fstp qword ptr (_Y)
+fld qword ptr (_X)
+fmul qword ptr (_Y)
+fstp qword ptr (_Z)
+fld qword ptr (_Zero)
+fcomp qword ptr (_T)
+fstsw ax
+sahf
+jne L307
+fld qword ptr (_X)
+fld qword ptr (_Radix)
+fmul qword ptr (_U2)
+faddp st(1),st
+fsub qword ptr (_Z)
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L307
+fld qword ptr (_Two)
+fcomp qword ptr (_Radix)
+fstsw ax
+sahf
+je L309
+fld qword ptr (_Two)
+fadd qword ptr (_U2)
+fstp qword ptr (_X)
+fld qword ptr (_X)
+fdiv qword ptr (_Two)
+fstp qword ptr (_Y)
+fld qword ptr (_Y)
+fsub qword ptr (_One)
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L310
+fld qword ptr (_S)
+fstp qword ptr (_StickyBit)
+jmp L310
+L309:
+fld qword ptr (_S)
+fstp qword ptr (_StickyBit)
+L310:
+L307:
+L305:
+L303:
+L301:
+L299:
+L296:
+fld qword ptr (_One)
+fcomp qword ptr (_StickyBit)
+fstsw ax
+sahf
+jne L313
+lea edi,(L315)
+push edi
+call _printf
+add esp,4
+jmp L314
+L313:
+lea edi,(L316)
+push edi
+call _printf
+add esp,4
+L314:
+lea edi,(L318)
+push edi
+cmp dword ptr (_GMult),0
+je L319
+cmp dword ptr (_GDiv),0
+je L319
+cmp dword ptr (_GAddSub),0
+je L319
+cmp dword ptr (_RMult),0
+je L319
+cmp dword ptr (_RDiv),0
+je L319
+cmp dword ptr (_RAddSub),0
+je L319
+mov dword ptr (-1184)[ebp],1
+jmp L320
+L319:
+mov dword ptr (-1184)[ebp],0
+L320:
+mov edi,dword ptr (-1184)[ebp]
+push edi
+push 3
+call _TstCond
+add esp,12
+mov dword ptr (_Milestone),60
+lea edi,(L44)
+push edi
+call _printf
+add esp,4
+lea edi,(L321)
+push edi
+call _printf
+add esp,4
+mov edi,dword ptr (_NoTrials)
+push edi
+lea edi,(L322)
+push edi
+call _printf
+add esp,8
+fld qword ptr (L323)
+sub esp,8
+fstp qword ptr [esp]
+call _sqrt
+add esp,8
+fstp qword ptr (-1192)[ebp]
+fld qword ptr (-1192)[ebp]
+fstp qword ptr (_Random9)
+fld qword ptr (_Third)
+fstp qword ptr (_Random1)
+mov dword ptr (_I),1
+L324:
+call _Random
+add esp,0
+fstp qword ptr (-1200)[ebp]
+fld qword ptr (-1200)[ebp]
+fstp qword ptr (_X)
+call _Random
+add esp,0
+fstp qword ptr (-1208)[ebp]
+fld qword ptr (-1208)[ebp]
+fstp qword ptr (_Y)
+fld qword ptr (_Y)
+fmul qword ptr (_X)
+fstp qword ptr (_Z9)
+fld qword ptr (_X)
+fmul qword ptr (_Y)
+fstp qword ptr (_Z)
+fld qword ptr (_Z)
+fsub qword ptr (_Z9)
+fstp qword ptr (_Z9)
+inc dword ptr (_I)
+L325:
+mov edi,dword ptr (_NoTrials)
+cmp dword ptr (_I),edi
+jg L327
+fld qword ptr (_Zero)
+fcomp qword ptr (_Z9)
+fstsw ax
+sahf
+je L324
+L327:
+mov edi,dword ptr (_NoTrials)
+cmp dword ptr (_I),edi
+jne L328
+fld qword ptr (_One)
+fld qword ptr (_Half)
+fdiv qword ptr (_Three)
+faddp st(1),st
+fstp qword ptr (-1208)[ebp]
+fld qword ptr (-1208)[ebp]
+fstp qword ptr (_Random1)
+fld qword ptr (_U2)
+fadd qword ptr (_U1)
+fadd qword ptr (_One)
+fstp qword ptr (-1216)[ebp]
+fld qword ptr (-1216)[ebp]
+fstp qword ptr (_Random2)
+fld qword ptr (_Random1)
+fstp qword ptr (-1224)[ebp]
+fld qword ptr (_Random2)
+fstp qword ptr (-1232)[ebp]
+fld qword ptr (-1224)[ebp]
+fmul qword ptr (-1232)[ebp]
+fstp qword ptr (_Z)
+fld qword ptr (-1232)[ebp]
+fmul qword ptr (-1224)[ebp]
+fstp qword ptr (_Y)
+fld qword ptr (-1208)[ebp]
+fmul qword ptr (-1216)[ebp]
+fstp qword ptr (-1240)[ebp]
+fld qword ptr (-1240)[ebp]
+fsub qword ptr (-1240)[ebp]
+fstp qword ptr (_Z9)
+L328:
+mov edi,dword ptr (_NoTrials)
+cmp dword ptr (_I),edi
+je L330
+fld qword ptr (_Zero)
+fcomp qword ptr (_Z9)
+fstsw ax
+sahf
+je L330
+lea edi,(L332)
+push edi
+push 2
+call _BadCond
+add esp,8
+jmp L331
+L330:
+mov edi,dword ptr (_NoTrials)
+push edi
+lea edi,(L333)
+push edi
+call _printf
+add esp,8
+L331:
+mov dword ptr (_Milestone),70
+lea edi,(L334)
+push edi
+call _printf
+add esp,4
+fld qword ptr (_Zero)
+sub esp,8
+fstp qword ptr [esp]
+call _sqrt
+add esp,8
+fstp qword ptr (-1212)[ebp]
+fld qword ptr (-1212)[ebp]
+fcomp qword ptr (_Zero)
+fstsw ax
+sahf
+jne L337
+fld qword ptr (_Zero)
+fchs
+fstp qword ptr (-1220)[ebp]
+fld qword ptr (-1220)[ebp]
+sub esp,8
+fstp qword ptr [esp]
+call _sqrt
+add esp,8
+fstp qword ptr (-1228)[ebp]
+fld qword ptr (-1228)[ebp]
+fcomp qword ptr (-1220)[ebp]
+fstsw ax
+sahf
+jne L337
+fld qword ptr (_One)
+sub esp,8
+fstp qword ptr [esp]
+call _sqrt
+add esp,8
+fstp qword ptr (-1244)[ebp]
+fld qword ptr (-1244)[ebp]
+fcomp qword ptr (_One)
+fstsw ax
+sahf
+jne L337
+mov dword ptr (-1196)[ebp],1
+jmp L338
+L337:
+mov dword ptr (-1196)[ebp],0
+L338:
+lea edi,(L336)
+push edi
+mov edi,dword ptr (-1196)[ebp]
+push edi
+push 0
+call _TstCond
+add esp,12
+fld qword ptr (_Zero)
+fstp qword ptr (_MinSqEr)
+fld qword ptr (_Zero)
+fstp qword ptr (_MaxSqEr)
+fld qword ptr (_Zero)
+fstp qword ptr (_J)
+fld qword ptr (_Radix)
+fstp qword ptr (_X)
+fld qword ptr (_U2)
+fstp qword ptr (_OneUlp)
+push 1
+call _SqXMinX
+add esp,4
+fld qword ptr (_BInvrse)
+fstp qword ptr (_X)
+fld qword ptr (_BInvrse)
+fmul qword ptr (_U1)
+fstp qword ptr (_OneUlp)
+push 1
+call _SqXMinX
+add esp,4
+fld qword ptr (_U1)
+fstp qword ptr (_X)
+fld qword ptr (_U1)
+fmul qword ptr (_U1)
+fstp qword ptr (_OneUlp)
+push 1
+call _SqXMinX
+add esp,4
+fld qword ptr (_Zero)
+fcomp qword ptr (_J)
+fstsw ax
+sahf
+je L339
+call _Pause
+add esp,0
+L339:
+mov edi,dword ptr (_NoTrials)
+push edi
+lea edi,(L341)
+push edi
+call _printf
+add esp,8
+fld qword ptr (_Zero)
+fstp qword ptr (_J)
+fld qword ptr (_Two)
+fstp qword ptr (_X)
+fld qword ptr (_Radix)
+fstp qword ptr (_Y)
+fld qword ptr (_One)
+fcomp qword ptr (_Radix)
+fstsw ax
+sahf
+je L342
+L344:
+fld qword ptr (_Y)
+fstp qword ptr (-1284)[ebp]
+fld qword ptr (-1284)[ebp]
+fstp qword ptr (_X)
+fld qword ptr (_Radix)
+fmul qword ptr (-1284)[ebp]
+fstp qword ptr (_Y)
+L345:
+fld qword ptr (_Y)
+fsub qword ptr (_X)
+fild dword ptr (_NoTrials)
+fcompp
+fstsw ax
+sahf
+ja L344
+L342:
+fld qword ptr (_X)
+fmul qword ptr (_U2)
+fstp qword ptr (_OneUlp)
+mov dword ptr (_I),1
+jmp L348
+L347:
+fld qword ptr (_X)
+fadd qword ptr (_One)
+fstp qword ptr (_X)
+push 2
+call _SqXMinX
+add esp,4
+fld qword ptr (_Zero)
+fcomp qword ptr (_J)
+fstsw ax
+sahf
+jae L350
+jmp L349
+L350:
+inc dword ptr (_I)
+L348:
+mov edi,dword ptr (_NoTrials)
+cmp dword ptr (_I),edi
+jle L347
+L349:
+lea edi,(L352)
+push edi
+call _printf
+add esp,4
+mov dword ptr (_I),-1
+fld qword ptr (_BMinusU2)
+fstp qword ptr (_X)
+fld qword ptr (_Radix)
+fstp qword ptr (_Y)
+fld qword ptr (_Radix)
+fld qword ptr (_Radix)
+fmul qword ptr (_U2)
+faddp st(1),st
+fstp qword ptr (_Z)
+mov dword ptr (_NotMonot),0
+mov dword ptr (_Monot),0
+jmp L354
+L353:
+inc dword ptr (_I)
+fld qword ptr (_X)
+sub esp,8
+fstp qword ptr [esp]
+call _sqrt
+add esp,8
+fstp qword ptr (-1292)[ebp]
+fld qword ptr (-1292)[ebp]
+fstp qword ptr (_X)
+fld qword ptr (_Y)
+sub esp,8
+fstp qword ptr [esp]
+call _sqrt
+add esp,8
+fstp qword ptr (-1300)[ebp]
+fld qword ptr (-1300)[ebp]
+fstp qword ptr (_Q)
+fld qword ptr (_Z)
+sub esp,8
+fstp qword ptr [esp]
+call _sqrt
+add esp,8
+fstp qword ptr (-1308)[ebp]
+fld qword ptr (-1308)[ebp]
+fstp qword ptr (_Z)
+fld qword ptr (_Q)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jb L358
+fld qword ptr (_Z)
+fcomp qword ptr (_Q)
+fstsw ax
+sahf
+jae L356
+L358:
+mov dword ptr (_NotMonot),1
+jmp L357
+L356:
+fld qword ptr (_Q)
+fadd qword ptr (_Half)
+sub esp,8
+fstp qword ptr [esp]
+call _floor
+add esp,8
+fstp qword ptr (-1324)[ebp]
+fld qword ptr (-1324)[ebp]
+fstp qword ptr (_Q)
+cmp dword ptr (_I),0
+jg L361
+fld qword ptr (_Q)
+fmul qword ptr (_Q)
+fcomp qword ptr (_Radix)
+fstsw ax
+sahf
+jne L359
+L361:
+mov dword ptr (_Monot),1
+jmp L360
+L359:
+cmp dword ptr (_I),0
+jle L362
+cmp dword ptr (_I),1
+jle L364
+mov dword ptr (_Monot),1
+jmp L363
+L364:
+fld qword ptr (_Y)
+fmul qword ptr (_BInvrse)
+fstp qword ptr (_Y)
+fld qword ptr (_Y)
+fstp qword ptr (-1340)[ebp]
+fld qword ptr (-1340)[ebp]
+fsub qword ptr (_U1)
+fstp qword ptr (_X)
+fld qword ptr (-1340)[ebp]
+fadd qword ptr (_U1)
+fstp qword ptr (_Z)
+jmp L363
+L362:
+fld qword ptr (_Q)
+fstp qword ptr (_Y)
+fld qword ptr (_Y)
+fstp qword ptr (-1340)[ebp]
+fld qword ptr (-1340)[ebp]
+fsub qword ptr (_U2)
+fstp qword ptr (_X)
+fld qword ptr (-1340)[ebp]
+fadd qword ptr (_U2)
+fstp qword ptr (_Z)
+L363:
+L360:
+L357:
+L354:
+cmp dword ptr (_NotMonot),0
+jne L366
+cmp dword ptr (_Monot),0
+je L353
+L366:
+cmp dword ptr (_Monot),0
+je L367
+lea edi,(L369)
+push edi
+call _printf
+add esp,4
+jmp L368
+L367:
+lea edi,(L157)
+push edi
+push 2
+call _BadCond
+add esp,8
+fld qword ptr (_Y)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L370)
+push edi
+call _printf
+add esp,12
+L368:
+mov dword ptr (_Milestone),80
+fld qword ptr (_MinSqEr)
+fadd qword ptr (_Half)
+fstp qword ptr (_MinSqEr)
+fld qword ptr (_MaxSqEr)
+fsub qword ptr (_Half)
+fstp qword ptr (_MaxSqEr)
+fld qword ptr (_One)
+fadd qword ptr (_U2)
+sub esp,8
+fstp qword ptr [esp]
+call _sqrt
+add esp,8
+fstp qword ptr (-1300)[ebp]
+fld qword ptr (-1300)[ebp]
+fsub qword ptr (_One)
+fdiv qword ptr (_U2)
+fstp qword ptr (_Y)
+fld qword ptr (_Y)
+fsub qword ptr (_One)
+fld qword ptr (_U2)
+fdiv qword ptr (_Eight)
+faddp st(1),st
+fstp qword ptr (_SqEr)
+fld qword ptr (_MaxSqEr)
+fcomp qword ptr (_SqEr)
+fstsw ax
+sahf
+jae L371
+fld qword ptr (_SqEr)
+fstp qword ptr (_MaxSqEr)
+L371:
+fld qword ptr (_Y)
+fld qword ptr (_U2)
+fdiv qword ptr (_Eight)
+faddp st(1),st
+fstp qword ptr (_SqEr)
+fld qword ptr (_MinSqEr)
+fcomp qword ptr (_SqEr)
+fstsw ax
+sahf
+jbe L373
+fld qword ptr (_SqEr)
+fstp qword ptr (_MinSqEr)
+L373:
+fld qword ptr (_F9)
+sub esp,8
+fstp qword ptr [esp]
+call _sqrt
+add esp,8
+fstp qword ptr (-1324)[ebp]
+fld qword ptr (-1324)[ebp]
+fsub qword ptr (_U2)
+fld qword ptr (_One)
+fsub qword ptr (_U2)
+fsubp st(1),st
+fdiv qword ptr (_U1)
+fstp qword ptr (_Y)
+fld qword ptr (_Y)
+fld qword ptr (_U1)
+fdiv qword ptr (_Eight)
+faddp st(1),st
+fstp qword ptr (_SqEr)
+fld qword ptr (_MaxSqEr)
+fcomp qword ptr (_SqEr)
+fstsw ax
+sahf
+jae L375
+fld qword ptr (_SqEr)
+fstp qword ptr (_MaxSqEr)
+L375:
+fld qword ptr (_Y)
+fadd qword ptr (_One)
+fld qword ptr (_U1)
+fdiv qword ptr (_Eight)
+faddp st(1),st
+fstp qword ptr (_SqEr)
+fld qword ptr (_MinSqEr)
+fcomp qword ptr (_SqEr)
+fstsw ax
+sahf
+jbe L377
+fld qword ptr (_SqEr)
+fstp qword ptr (_MinSqEr)
+L377:
+fld qword ptr (_U2)
+fstp qword ptr (_OneUlp)
+fld qword ptr (_OneUlp)
+fstp qword ptr (_X)
+mov dword ptr (_Indx),1
+L379:
+fld qword ptr (_X)
+fadd qword ptr (_U1)
+fadd qword ptr (_X)
+fadd qword ptr (_F9)
+sub esp,8
+fstp qword ptr [esp]
+call _sqrt
+add esp,8
+fstp qword ptr (-1356)[ebp]
+fld qword ptr (-1356)[ebp]
+fstp qword ptr (_Y)
+fld qword ptr (_Y)
+fsub qword ptr (_U2)
+fld qword ptr (_One)
+fsub qword ptr (_U2)
+fadd qword ptr (_X)
+fsubp st(1),st
+fdiv qword ptr (_OneUlp)
+fstp qword ptr (_Y)
+fld qword ptr (_U1)
+fsub qword ptr (_X)
+fadd qword ptr (_F9)
+fmul qword ptr (_Half)
+fmul qword ptr (_X)
+fmul qword ptr (_X)
+fdiv qword ptr (_OneUlp)
+fstp qword ptr (_Z)
+fld qword ptr (_Y)
+fadd qword ptr (_Half)
+fadd qword ptr (_Z)
+fstp qword ptr (_SqEr)
+fld qword ptr (_MinSqEr)
+fcomp qword ptr (_SqEr)
+fstsw ax
+sahf
+jbe L383
+fld qword ptr (_SqEr)
+fstp qword ptr (_MinSqEr)
+L383:
+fld qword ptr (_Y)
+fsub qword ptr (_Half)
+fadd qword ptr (_Z)
+fstp qword ptr (_SqEr)
+fld qword ptr (_MaxSqEr)
+fcomp qword ptr (_SqEr)
+fstsw ax
+sahf
+jae L385
+fld qword ptr (_SqEr)
+fstp qword ptr (_MaxSqEr)
+L385:
+mov edi,dword ptr (_Indx)
+cmp edi,1
+je L389
+cmp edi,3
+jne L387
+L389:
+fld qword ptr (_X)
+sub esp,8
+fstp qword ptr [esp]
+call _Sign
+add esp,8
+fstp qword ptr (-1396)[ebp]
+fld qword ptr (_OneUlp)
+sub esp,8
+fstp qword ptr [esp]
+call _sqrt
+add esp,8
+fstp qword ptr (-1404)[ebp]
+fld qword ptr (_Eight)
+fld qword ptr (_Nine)
+fmul qword ptr (-1404)[ebp]
+fdivp st(1),st
+sub esp,8
+fstp qword ptr [esp]
+call _floor
+add esp,8
+fstp qword ptr (-1412)[ebp]
+fld qword ptr (_OneUlp)
+fmul qword ptr (-1396)[ebp]
+fmul qword ptr (-1412)[ebp]
+fstp qword ptr (_X)
+jmp L388
+L387:
+fld qword ptr (_U1)
+fstp qword ptr (_OneUlp)
+fld qword ptr (_OneUlp)
+fchs
+fstp qword ptr (_X)
+L388:
+L380:
+inc dword ptr (_Indx)
+cmp dword ptr (_Indx),3
+jle L379
+mov dword ptr (_Milestone),85
+mov dword ptr (_SqRWrng),0
+mov dword ptr (_Anomaly),0
+mov dword ptr (_RSqrt),0
+fld qword ptr (_One)
+fcomp qword ptr (_Radix)
+fstsw ax
+sahf
+je L390
+lea edi,(L392)
+push edi
+call _printf
+add esp,4
+fld qword ptr (_Precision)
+sub esp,8
+fstp qword ptr [esp]
+call _floor
+add esp,8
+fstp qword ptr (-1356)[ebp]
+fld qword ptr (_One)
+fadd qword ptr (_Precision)
+fsub qword ptr (-1356)[ebp]
+sub esp,8
+fstp qword ptr [esp]
+fld qword ptr (_Radix)
+sub esp,8
+fstp qword ptr [esp]
+call _pow
+add esp,16
+fstp qword ptr (-1364)[ebp]
+fld qword ptr (_Half)
+fadd qword ptr (-1364)[ebp]
+sub esp,8
+fstp qword ptr [esp]
+call _floor
+add esp,8
+fstp qword ptr (-1372)[ebp]
+fld qword ptr (-1372)[ebp]
+fstp qword ptr (_D)
+fld qword ptr (_D)
+fdiv qword ptr (_Radix)
+fstp qword ptr (_X)
+fld qword ptr (_D)
+fdiv qword ptr (_A1)
+fstp qword ptr (_Y)
+fld qword ptr (_X)
+sub esp,8
+fstp qword ptr [esp]
+call _floor
+add esp,8
+fstp qword ptr (-1396)[ebp]
+fld qword ptr (-1396)[ebp]
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jne L395
+fld qword ptr (_Y)
+sub esp,8
+fstp qword ptr [esp]
+call _floor
+add esp,8
+fstp qword ptr (-1412)[ebp]
+fld qword ptr (-1412)[ebp]
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+je L393
+L395:
+mov dword ptr (_Anomaly),1
+jmp L394
+L393:
+fld qword ptr (_Zero)
+fstp qword ptr (_X)
+fld qword ptr (_X)
+fstp qword ptr (_Z2)
+fld qword ptr (_One)
+fstp qword ptr (_Y)
+fld qword ptr (_Y)
+fstp qword ptr (_Y2)
+fld qword ptr (_Radix)
+fsub qword ptr (_One)
+fstp qword ptr (_Z1)
+fld qword ptr (_Four)
+fmul qword ptr (_D)
+fstp qword ptr (_FourD)
+L396:
+fld qword ptr (_Z2)
+fcomp qword ptr (_Y2)
+fstsw ax
+sahf
+jae L399
+fld qword ptr (_Radix)
+fstp qword ptr (_Q)
+fld qword ptr (_Y)
+fstp qword ptr (_Y1)
+L401:
+fld qword ptr (_Half)
+fld qword ptr (_Q)
+fdiv qword ptr (_Y1)
+fsubp st(1),st
+sub esp,8
+fstp qword ptr [esp]
+call _floor
+add esp,8
+fstp qword ptr (-1436)[ebp]
+fld qword ptr (_Q)
+fld qword ptr (-1436)[ebp]
+fmul qword ptr (_Y1)
+faddp st(1),st
+sub esp,8
+fstp qword ptr [esp]
+call _fabs
+add esp,8
+fstp qword ptr (-1444)[ebp]
+fld qword ptr (-1444)[ebp]
+fstp qword ptr (_X1)
+fld qword ptr (_Y1)
+fstp qword ptr (_Q)
+fld qword ptr (_X1)
+fstp qword ptr (_Y1)
+L402:
+fld qword ptr (_Zero)
+fcomp qword ptr (_X1)
+fstsw ax
+sahf
+jb L401
+fld qword ptr (_One)
+fcomp qword ptr (_Q)
+fstsw ax
+sahf
+jb L404
+fld qword ptr (_Y2)
+fstp qword ptr (_Z2)
+fld qword ptr (_Y)
+fstp qword ptr (_Z)
+L404:
+L399:
+fld qword ptr (_Y)
+fadd qword ptr (_Two)
+fstp qword ptr (_Y)
+fld qword ptr (_X)
+fadd qword ptr (_Eight)
+fstp qword ptr (_X)
+fld qword ptr (_Y2)
+fadd qword ptr (_X)
+fstp qword ptr (_Y2)
+fld qword ptr (_FourD)
+fcomp qword ptr (_Y2)
+fstsw ax
+sahf
+ja L406
+fld qword ptr (_Y2)
+fsub qword ptr (_FourD)
+fstp qword ptr (_Y2)
+L406:
+L397:
+fld qword ptr (_D)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+ja L396
+fld qword ptr (_FourD)
+fsub qword ptr (_Z2)
+fstp qword ptr (_X8)
+fld qword ptr (_X8)
+fstp qword ptr (-1436)[ebp]
+fld qword ptr (-1436)[ebp]
+fld qword ptr (_Z)
+fmul qword ptr (_Z)
+faddp st(1),st
+fdiv qword ptr (_FourD)
+fstp qword ptr (_Q)
+fld qword ptr (-1436)[ebp]
+fdiv qword ptr (_Eight)
+fstp qword ptr (_X8)
+fld qword ptr (_Q)
+fstp qword ptr (-1452)[ebp]
+fld qword ptr (-1452)[ebp]
+sub esp,8
+fstp qword ptr [esp]
+call _floor
+add esp,8
+fstp qword ptr (-1460)[ebp]
+fld qword ptr (-1460)[ebp]
+fcomp qword ptr (-1452)[ebp]
+fstsw ax
+sahf
+je L408
+mov dword ptr (_Anomaly),1
+jmp L409
+L408:
+mov dword ptr (_Break),0
+L410:
+fld qword ptr (_Z1)
+fmul qword ptr (_Z)
+fstp qword ptr (_X)
+fld qword ptr (_X)
+fstp qword ptr (-1468)[ebp]
+fld qword ptr (-1468)[ebp]
+fdiv qword ptr (_Radix)
+sub esp,8
+fstp qword ptr [esp]
+call _floor
+add esp,8
+fstp qword ptr (-1476)[ebp]
+fld qword ptr (-1468)[ebp]
+fld qword ptr (-1476)[ebp]
+fmul qword ptr (_Radix)
+fsubp st(1),st
+fstp qword ptr (_X)
+fld qword ptr (_One)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jne L413
+mov dword ptr (_Break),1
+jmp L414
+L413:
+fld qword ptr (_Z1)
+fsub qword ptr (_One)
+fstp qword ptr (_Z1)
+L414:
+L411:
+cmp dword ptr (_Break),0
+jne L415
+fld qword ptr (_Zero)
+fcomp qword ptr (_Z1)
+fstsw ax
+sahf
+jb L410
+L415:
+fld qword ptr (_Zero)
+fcomp qword ptr (_Z1)
+fstsw ax
+sahf
+jb L416
+cmp dword ptr (_Break),0
+jne L416
+mov dword ptr (_Anomaly),1
+jmp L417
+L416:
+fld qword ptr (_RadixD2)
+fcomp qword ptr (_Z1)
+fstsw ax
+sahf
+jae L418
+fld qword ptr (_Z1)
+fsub qword ptr (_Radix)
+fstp qword ptr (_Z1)
+L418:
+L420:
+call _NewD
+add esp,0
+L421:
+fld qword ptr (_U2)
+fmul qword ptr (_D)
+fld qword ptr (_F9)
+fcompp
+fstsw ax
+sahf
+ja L420
+fld qword ptr (_D)
+fmul qword ptr (_Radix)
+fsub qword ptr (_D)
+fld qword ptr (_W)
+fsub qword ptr (_D)
+fcompp
+fstsw ax
+sahf
+je L423
+mov dword ptr (_Anomaly),1
+jmp L424
+L423:
+fld qword ptr (_D)
+fstp qword ptr (_Z2)
+mov dword ptr (_I),0
+fld qword ptr (_D)
+fld qword ptr (_One)
+fadd qword ptr (_Z)
+fmul qword ptr (_Half)
+faddp st(1),st
+fstp qword ptr (_Y)
+fld qword ptr (_D)
+fadd qword ptr (_Z)
+fadd qword ptr (_Q)
+fstp qword ptr (_X)
+call _SR3750
+add esp,0
+fld qword ptr (_D)
+fld qword ptr (_One)
+fsub qword ptr (_Z)
+fmul qword ptr (_Half)
+faddp st(1),st
+fadd qword ptr (_D)
+fstp qword ptr (_Y)
+fld qword ptr (_D)
+fsub qword ptr (_Z)
+fadd qword ptr (_D)
+fstp qword ptr (_X)
+fld qword ptr (_X)
+fstp qword ptr (-1508)[ebp]
+fld qword ptr (-1508)[ebp]
+fadd qword ptr (_Q)
+fadd qword ptr (-1508)[ebp]
+fstp qword ptr (_X)
+call _SR3750
+add esp,0
+call _NewD
+add esp,0
+fld qword ptr (_D)
+fsub qword ptr (_Z2)
+fld qword ptr (_W)
+fsub qword ptr (_Z2)
+fcompp
+fstsw ax
+sahf
+je L425
+mov dword ptr (_Anomaly),1
+jmp L426
+L425:
+fld qword ptr (_D)
+fsub qword ptr (_Z2)
+fstp qword ptr (-1532)[ebp]
+fld qword ptr (-1532)[ebp]
+fld qword ptr (_Z2)
+fld qword ptr (_One)
+fsub qword ptr (_Z)
+fmul qword ptr (_Half)
+faddp st(1),st
+faddp st(1),st
+fstp qword ptr (_Y)
+fld qword ptr (-1532)[ebp]
+fld qword ptr (_Z2)
+fsub qword ptr (_Z)
+fadd qword ptr (_Q)
+faddp st(1),st
+fstp qword ptr (_X)
+call _SR3750
+add esp,0
+fld qword ptr (_One)
+fadd qword ptr (_Z)
+fmul qword ptr (_Half)
+fstp qword ptr (_Y)
+fld qword ptr (_Q)
+fstp qword ptr (_X)
+call _SR3750
+add esp,0
+cmp dword ptr (_I),0
+jne L427
+mov dword ptr (_Anomaly),1
+L427:
+L426:
+L424:
+L417:
+L409:
+L394:
+cmp dword ptr (_I),0
+je L431
+cmp dword ptr (_Anomaly),0
+je L429
+L431:
+lea edi,(L432)
+push edi
+push 0
+call _BadCond
+add esp,8
+fld qword ptr (_W)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L433)
+push edi
+call _printf
+add esp,12
+lea edi,(L434)
+push edi
+call _printf
+add esp,4
+mov dword ptr (_SqRWrng),1
+L429:
+L390:
+cmp dword ptr (_Anomaly),0
+jne L435
+fld qword ptr (_Zero)
+fcomp qword ptr (_MinSqEr)
+fstsw ax
+sahf
+ja L437
+fld qword ptr (_Zero)
+fcomp qword ptr (_MaxSqEr)
+fstsw ax
+sahf
+jb L437
+mov dword ptr (_RSqrt),1
+lea edi,(L439)
+push edi
+call _printf
+add esp,4
+jmp L438
+L437:
+fld qword ptr (_MaxSqEr)
+fadd qword ptr (_U2)
+fld qword ptr (_U2)
+fsub qword ptr (_Half)
+fcompp
+fstsw ax
+sahf
+jb L443
+fld qword ptr (_Half)
+fcomp qword ptr (_MinSqEr)
+fstsw ax
+sahf
+jb L443
+fld qword ptr (_MinSqEr)
+fadd qword ptr (_Radix)
+fld qword ptr (_Half)
+fcompp
+fstsw ax
+sahf
+jbe L440
+L443:
+mov dword ptr (_SqRWrng),1
+jmp L441
+L440:
+mov dword ptr (_RSqrt),2
+lea edi,(L444)
+push edi
+call _printf
+add esp,4
+L441:
+L438:
+L435:
+cmp dword ptr (_SqRWrng),0
+je L445
+lea edi,(L447)
+push edi
+call _printf
+add esp,4
+fld qword ptr (_MinSqEr)
+fsub qword ptr (_Half)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L448)
+push edi
+call _printf
+add esp,12
+fld qword ptr (_Half)
+fadd qword ptr (_MaxSqEr)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L449)
+push edi
+call _printf
+add esp,12
+lea edi,(L451)
+push edi
+fld qword ptr (_MaxSqEr)
+fsub qword ptr (_MinSqEr)
+fld qword ptr (_Radix)
+fmul qword ptr (_Radix)
+fcompp
+fstsw ax
+sahf
+jbe L452
+mov dword ptr (-1344)[ebp],1
+jmp L453
+L452:
+mov dword ptr (-1344)[ebp],0
+L453:
+mov edi,dword ptr (-1344)[ebp]
+push edi
+push 1
+call _TstCond
+add esp,12
+L445:
+mov dword ptr (_Milestone),90
+call _Pause
+add esp,0
+lea edi,(L454)
+push edi
+call _printf
+add esp,4
+mov dword ptr (_N),0
+mov dword ptr (_I),0
+fld qword ptr (_Zero)
+fchs
+fstp qword ptr (_Z)
+mov dword ptr (_M),3
+mov dword ptr (_Break),0
+L455:
+fld qword ptr (_One)
+fstp qword ptr (_X)
+call _SR3980
+add esp,0
+cmp dword ptr (_I),10
+jg L458
+mov dword ptr (_I),1023
+call _SR3980
+add esp,0
+L458:
+fld qword ptr (_MinusOne)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+jne L460
+mov dword ptr (_Break),1
+jmp L461
+L460:
+fld qword ptr (_MinusOne)
+fstp qword ptr (_Z)
+call _PrintIfNPositive
+add esp,0
+mov dword ptr (_N),0
+mov dword ptr (_I),-4
+L461:
+L456:
+cmp dword ptr (_Break),0
+je L455
+call _PrintIfNPositive
+add esp,0
+mov edi,dword ptr (_N)
+mov dword ptr (_N1),edi
+mov dword ptr (_N),0
+fld qword ptr (_A1)
+fstp qword ptr (_Z)
+fld qword ptr (_W)
+sub esp,8
+fstp qword ptr [esp]
+call _log
+add esp,8
+fstp qword ptr (-1348)[ebp]
+fld qword ptr (_A1)
+sub esp,8
+fstp qword ptr [esp]
+call _log
+add esp,8
+fstp qword ptr (-1356)[ebp]
+fld qword ptr (_Two)
+fmul qword ptr (-1348)[ebp]
+fdiv qword ptr (-1356)[ebp]
+sub esp,8
+fstp qword ptr [esp]
+call _floor
+add esp,8
+fstp qword ptr (-1364)[ebp]
+fld qword ptr (-1364)[ebp]
+call __ftol
+mov dword ptr (_M),eax
+mov dword ptr (_Break),0
+L462:
+fld qword ptr (_Z)
+fstp qword ptr (_X)
+mov dword ptr (_I),1
+call _SR3980
+add esp,0
+fld qword ptr (_AInvrse)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+jne L465
+mov dword ptr (_Break),1
+jmp L466
+L465:
+fld qword ptr (_AInvrse)
+fstp qword ptr (_Z)
+L466:
+L463:
+cmp dword ptr (_Break),0
+je L462
+mov dword ptr (_Milestone),100
+mov edi,dword ptr (_NoTrials)
+mov dword ptr (_M),edi
+fld qword ptr (_Three)
+fstp qword ptr (_Z)
+L467:
+fld qword ptr (_Z)
+fstp qword ptr (_X)
+mov dword ptr (_I),1
+call _SR3980
+add esp,0
+L470:
+fld qword ptr (_Z)
+fadd qword ptr (_Two)
+fstp qword ptr (_Z)
+L471:
+fld qword ptr (_Z)
+fdiv qword ptr (_Three)
+sub esp,8
+fstp qword ptr [esp]
+call _floor
+add esp,8
+fstp qword ptr (-1380)[ebp]
+fld qword ptr (_Three)
+fmul qword ptr (-1380)[ebp]
+fld qword ptr (_Z)
+fcompp
+fstsw ax
+sahf
+je L470
+L468:
+fld qword ptr (_Eight)
+fmul qword ptr (_Three)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+ja L467
+cmp dword ptr (_N),0
+jle L473
+lea edi,(L475)
+push edi
+call _printf
+add esp,4
+lea edi,(L476)
+push edi
+call _printf
+add esp,4
+L473:
+call _PrintIfNPositive
+add esp,0
+mov edi,dword ptr (_N1)
+add dword ptr (_N),edi
+cmp dword ptr (_N),0
+jne L477
+lea edi,(L479)
+push edi
+call _printf
+add esp,4
+L477:
+cmp dword ptr (_N),0
+jle L480
+call _Pause
+add esp,0
+jmp L481
+L480:
+lea edi,(L44)
+push edi
+call _printf
+add esp,4
+L481:
+mov dword ptr (_Milestone),110
+lea edi,(L482)
+push edi
+call _printf
+add esp,4
+fld qword ptr (_U1)
+fstp qword ptr (_D)
+fld qword ptr (_Precision)
+sub esp,8
+fstp qword ptr [esp]
+call _floor
+add esp,8
+fstp qword ptr (-1380)[ebp]
+fld qword ptr (-1380)[ebp]
+fcomp qword ptr (_Precision)
+fstsw ax
+sahf
+je L483
+fld qword ptr (_BInvrse)
+fstp qword ptr (_D)
+fld qword ptr (_Precision)
+fstp qword ptr (_X)
+L485:
+fld qword ptr (_D)
+fmul qword ptr (_BInvrse)
+fstp qword ptr (_D)
+fld qword ptr (_X)
+fsub qword ptr (_One)
+fstp qword ptr (_X)
+L486:
+fld qword ptr (_Zero)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jb L485
+L483:
+fld qword ptr (_One)
+fstp qword ptr (_Y)
+fld qword ptr (_D)
+fstp qword ptr (_Z)
+L488:
+fld qword ptr (_Y)
+fstp qword ptr (_C)
+fld qword ptr (_Z)
+fstp qword ptr (_Y)
+fld qword ptr (_Y)
+fstp qword ptr (-1388)[ebp]
+fld qword ptr (-1388)[ebp]
+fmul qword ptr (-1388)[ebp]
+fstp qword ptr (_Z)
+L489:
+fld qword ptr (_Z)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+jae L491
+fld qword ptr (_Z)
+fadd qword ptr (_Z)
+fld qword ptr (_Z)
+fcompp
+fstsw ax
+sahf
+jb L488
+L491:
+fld qword ptr (_C)
+fstp qword ptr (_Y)
+fld qword ptr (_Y)
+fmul qword ptr (_D)
+fstp qword ptr (_Z)
+L492:
+fld qword ptr (_Y)
+fstp qword ptr (_C)
+fld qword ptr (_Z)
+fstp qword ptr (_Y)
+fld qword ptr (_Y)
+fmul qword ptr (_D)
+fstp qword ptr (_Z)
+L493:
+fld qword ptr (_Z)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+jae L495
+fld qword ptr (_Z)
+fadd qword ptr (_Z)
+fld qword ptr (_Z)
+fcompp
+fstsw ax
+sahf
+jb L492
+L495:
+fld qword ptr (_Two)
+fcomp qword ptr (_Radix)
+fstsw ax
+sahf
+jbe L496
+fld qword ptr (_Two)
+fstp qword ptr (_HInvrse)
+jmp L497
+L496:
+fld qword ptr (_Radix)
+fstp qword ptr (_HInvrse)
+L497:
+fld qword ptr (_One)
+fdiv qword ptr (_HInvrse)
+fstp qword ptr (_H)
+fld qword ptr (_One)
+fdiv qword ptr (_C)
+fstp qword ptr (_CInvrse)
+fld qword ptr (_C)
+fstp qword ptr (_E0)
+fld qword ptr (_E0)
+fmul qword ptr (_H)
+fstp qword ptr (_Z)
+L498:
+fld qword ptr (_E0)
+fstp qword ptr (_Y)
+fld qword ptr (_Z)
+fstp qword ptr (_E0)
+fld qword ptr (_E0)
+fmul qword ptr (_H)
+fstp qword ptr (_Z)
+L499:
+fld qword ptr (_Z)
+fcomp qword ptr (_E0)
+fstsw ax
+sahf
+jae L501
+fld qword ptr (_Z)
+fadd qword ptr (_Z)
+fld qword ptr (_Z)
+fcompp
+fstsw ax
+sahf
+jb L498
+L501:
+fld qword ptr (_E0)
+fstp qword ptr (_UfThold)
+fld qword ptr (_Zero)
+fstp qword ptr (_E1)
+fld qword ptr (_Zero)
+fstp qword ptr (_Q)
+fld qword ptr (_U2)
+fstp qword ptr (_E9)
+fld qword ptr (_One)
+fadd qword ptr (_E9)
+fstp qword ptr (_S)
+fld qword ptr (_C)
+fmul qword ptr (_S)
+fstp qword ptr (_D)
+fld qword ptr (_C)
+fcomp qword ptr (_D)
+fstsw ax
+sahf
+jb L502
+fld qword ptr (_Radix)
+fmul qword ptr (_U2)
+fstp qword ptr (_E9)
+fld qword ptr (_One)
+fadd qword ptr (_E9)
+fstp qword ptr (_S)
+fld qword ptr (_C)
+fmul qword ptr (_S)
+fstp qword ptr (_D)
+fld qword ptr (_C)
+fcomp qword ptr (_D)
+fstsw ax
+sahf
+jb L503
+lea edi,(L506)
+push edi
+push 0
+call _BadCond
+add esp,8
+fld qword ptr (_E0)
+fstp qword ptr (_Underflow)
+fld qword ptr (_Zero)
+fstp qword ptr (_Y1)
+fld qword ptr (_Z)
+fstp qword ptr (_PseudoZero)
+call _Pause
+add esp,0
+jmp L503
+L502:
+fld qword ptr (_D)
+fstp qword ptr (_Underflow)
+fld qword ptr (_Underflow)
+fmul qword ptr (_H)
+fstp qword ptr (_PseudoZero)
+fld qword ptr (_Zero)
+fstp qword ptr (_UfThold)
+L507:
+fld qword ptr (_Underflow)
+fstp qword ptr (_Y1)
+fld qword ptr (_PseudoZero)
+fstp qword ptr (_Underflow)
+fld qword ptr (_E1)
+fadd qword ptr (_E1)
+fld qword ptr (_E1)
+fcompp
+fstsw ax
+sahf
+jb L510
+fld qword ptr (_Underflow)
+fmul qword ptr (_HInvrse)
+fstp qword ptr (_Y2)
+fld qword ptr (_Y1)
+fsub qword ptr (_Y2)
+sub esp,8
+fstp qword ptr [esp]
+call _fabs
+add esp,8
+fstp qword ptr (-1452)[ebp]
+fld qword ptr (-1452)[ebp]
+fstp qword ptr (_E1)
+fld qword ptr (_Y1)
+fstp qword ptr (_Q)
+fld qword ptr (_Zero)
+fcomp qword ptr (_UfThold)
+fstsw ax
+sahf
+jne L512
+fld qword ptr (_Y2)
+fcomp qword ptr (_Y1)
+fstsw ax
+sahf
+je L512
+fld qword ptr (_Y1)
+fstp qword ptr (_UfThold)
+L512:
+L510:
+fld qword ptr (_PseudoZero)
+fmul qword ptr (_H)
+fstp qword ptr (_PseudoZero)
+L508:
+fld qword ptr (_PseudoZero)
+fcomp qword ptr (_Underflow)
+fstsw ax
+sahf
+jae L514
+fld qword ptr (_PseudoZero)
+fadd qword ptr (_PseudoZero)
+fld qword ptr (_PseudoZero)
+fcompp
+fstsw ax
+sahf
+jb L507
+L514:
+L503:
+fld qword ptr (_Zero)
+fcomp qword ptr (_PseudoZero)
+fstsw ax
+sahf
+je L515
+lea edi,(L44)
+push edi
+call _printf
+add esp,4
+fld qword ptr (_PseudoZero)
+fstp qword ptr (_Z)
+fld qword ptr (_Zero)
+fcomp qword ptr (_PseudoZero)
+fstsw ax
+sahf
+jb L517
+lea edi,(L519)
+push edi
+push 0
+call _BadCond
+add esp,8
+lea edi,(L520)
+push edi
+call _printf
+add esp,4
+fld qword ptr (_PseudoZero)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L521)
+push edi
+call _printf
+add esp,12
+fld qword ptr (_PseudoZero)
+fchs
+fstp qword ptr (_X)
+fld qword ptr (_Zero)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jb L518
+lea edi,(L524)
+push edi
+call _printf
+add esp,4
+fld qword ptr (_X)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L525)
+push edi
+call _printf
+add esp,12
+jmp L518
+L517:
+lea edi,(L526)
+push edi
+push 3
+call _BadCond
+add esp,8
+fld qword ptr (_PseudoZero)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L527)
+push edi
+call _printf
+add esp,12
+L518:
+call _TstPtUf
+add esp,0
+L515:
+mov dword ptr (_Milestone),120
+fld qword ptr (_CInvrse)
+fmul qword ptr (_Y)
+fld qword ptr (_CInvrse)
+fmul qword ptr (_Y1)
+fcompp
+fstsw ax
+sahf
+jae L528
+fld qword ptr (_H)
+fmul qword ptr (_S)
+fstp qword ptr (_S)
+fld qword ptr (_Underflow)
+fstp qword ptr (_E0)
+L528:
+fld qword ptr (_Zero)
+fcomp qword ptr (_E1)
+fstsw ax
+sahf
+je L530
+fld qword ptr (_E0)
+fcomp qword ptr (_E1)
+fstsw ax
+sahf
+je L530
+lea edi,(L157)
+push edi
+push 2
+call _BadCond
+add esp,8
+fld qword ptr (_E0)
+fcomp qword ptr (_E1)
+fstsw ax
+sahf
+jbe L532
+lea edi,(L534)
+push edi
+call _printf
+add esp,4
+lea edi,(L535)
+push edi
+call _printf
+add esp,4
+fld qword ptr (_Zero)
+fcomp qword ptr (_PseudoZero)
+fstsw ax
+sahf
+jne L533
+fld qword ptr (_E1)
+fstp qword ptr (_E0)
+jmp L533
+L532:
+lea edi,(L538)
+push edi
+call _printf
+add esp,4
+lea edi,(L539)
+push edi
+call _printf
+add esp,4
+L533:
+L530:
+fld qword ptr (_E0)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L540)
+push edi
+call _printf
+add esp,12
+fld qword ptr (_E0)
+fstp qword ptr (_Z)
+call _TstPtUf
+add esp,0
+fld qword ptr (_E0)
+fstp qword ptr (_Underflow)
+cmp dword ptr (_N),1
+jne L541
+fld qword ptr (_Y)
+fstp qword ptr (_Underflow)
+L541:
+mov dword ptr (_I),4
+fld qword ptr (_Zero)
+fcomp qword ptr (_E1)
+fstsw ax
+sahf
+jne L543
+mov dword ptr (_I),3
+L543:
+fld qword ptr (_Zero)
+fcomp qword ptr (_UfThold)
+fstsw ax
+sahf
+jne L545
+sub dword ptr (_I),2
+L545:
+mov dword ptr (_UfNGrad),1
+mov edi,dword ptr (_I)
+cmp edi,1
+jl L547
+cmp edi,4
+jg L547
+jmp dword ptr (L570-4)[edi*4]
+_TEXT ends
+_TEXT segment
+align 4
+L570 label byte
+dd L549
+dd L556
+dd L561
+dd L562
+_TEXT ends
+_TEXT segment
+L549:
+fld qword ptr (_Underflow)
+fstp qword ptr (_UfThold)
+fld qword ptr (_CInvrse)
+fmul qword ptr (_Q)
+fld qword ptr (_CInvrse)
+fmul qword ptr (_Y)
+fmul qword ptr (_S)
+fcompp
+fstsw ax
+sahf
+je L550
+fld qword ptr (_Y)
+fstp qword ptr (_UfThold)
+lea edi,(L552)
+push edi
+push 0
+call _BadCond
+add esp,8
+fld qword ptr (_UfThold)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L553)
+push edi
+call _printf
+add esp,12
+fld qword ptr (_C)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L554)
+push edi
+call _printf
+add esp,12
+lea edi,(L555)
+push edi
+call _printf
+add esp,4
+L550:
+call _Pause
+add esp,0
+jmp L548
+L556:
+lea edi,(L557)
+push edi
+push 0
+call _BadCond
+add esp,8
+lea edi,(L558)
+push edi
+call _printf
+add esp,4
+fld qword ptr (_Y2)
+sub esp,8
+fstp qword ptr [esp]
+fld qword ptr (_Q)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L559)
+push edi
+call _printf
+add esp,20
+fld qword ptr (_Q)
+fsub qword ptr (_Y2)
+sub esp,8
+fstp qword ptr [esp]
+call _fabs
+add esp,8
+fstp qword ptr (-1468)[ebp]
+fld qword ptr (-1468)[ebp]
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L560)
+push edi
+call _printf
+add esp,12
+fld qword ptr (_Q)
+fstp qword ptr (_UfThold)
+jmp L548
+L561:
+fld qword ptr (_X)
+fstp qword ptr (_X)
+jmp L548
+L562:
+fld qword ptr (_UfThold)
+fcomp qword ptr (_Q)
+fstsw ax
+sahf
+jne L563
+fld qword ptr (_E0)
+fcomp qword ptr (_E1)
+fstsw ax
+sahf
+jne L563
+fld qword ptr (_UfThold)
+fld qword ptr (_E1)
+fdiv qword ptr (_E9)
+fsubp st(1),st
+sub esp,8
+fstp qword ptr [esp]
+call _fabs
+add esp,8
+fstp qword ptr (-1492)[ebp]
+fld qword ptr (_E1)
+fcomp qword ptr (-1492)[ebp]
+fstsw ax
+sahf
+jb L563
+mov dword ptr (_UfNGrad),0
+lea edi,(L565)
+push edi
+call _printf
+add esp,4
+lea edi,(L566)
+push edi
+call _printf
+add esp,4
+fld qword ptr (_E0)
+fmul qword ptr (_CInvrse)
+fstp qword ptr (_Y)
+fld qword ptr (_Y)
+fld qword ptr (_OneAndHalf)
+fadd qword ptr (_U2)
+fmulp st(1),st
+fstp qword ptr (_Y)
+fld qword ptr (_CInvrse)
+fld qword ptr (_One)
+fadd qword ptr (_U2)
+fmulp st(1),st
+fstp qword ptr (_X)
+fld qword ptr (_Y)
+fdiv qword ptr (_X)
+fstp qword ptr (_Y)
+fld qword ptr (_E0)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+jne L568
+mov dword ptr (-1496)[ebp],1
+jmp L569
+L568:
+mov dword ptr (-1496)[ebp],0
+L569:
+mov edi,dword ptr (-1496)[ebp]
+mov dword ptr (_IEEE),edi
+L563:
+L547:
+L548:
+cmp dword ptr (_UfNGrad),0
+je L572
+lea edi,(L44)
+push edi
+call _printf
+add esp,4
+lea edi,(_sigfpe)
+mov dword ptr (_sigsave),edi
+lea edi,(_ovfl_buf)
+push edi
+call __setjmp
+add esp,4
+cmp eax,0
+je L574
+lea edi,(L576)
+push edi
+call _printf
+add esp,4
+fld qword ptr (_H)
+fadd qword ptr (_H)
+fstp qword ptr (_R)
+jmp L575
+L574:
+fld qword ptr (_Underflow)
+fdiv qword ptr (_UfThold)
+sub esp,8
+fstp qword ptr [esp]
+call _sqrt
+add esp,8
+fstp qword ptr (-1460)[ebp]
+fld qword ptr (-1460)[ebp]
+fstp qword ptr (_R)
+L575:
+mov dword ptr (_sigsave),0
+fld qword ptr (_H)
+fcomp qword ptr (_R)
+fstsw ax
+sahf
+jb L577
+fld qword ptr (_R)
+fmul qword ptr (_UfThold)
+fstp qword ptr (_Z)
+fld qword ptr (_Z)
+fld qword ptr (_One)
+fld qword ptr (_R)
+fmul qword ptr (_H)
+fld qword ptr (_One)
+fadd qword ptr (_H)
+fmulp st(1),st
+faddp st(1),st
+fmulp st(1),st
+fstp qword ptr (_X)
+jmp L578
+L577:
+fld qword ptr (_UfThold)
+fstp qword ptr (_Z)
+fld qword ptr (_Z)
+fld qword ptr (_One)
+fld qword ptr (_H)
+fmul qword ptr (_H)
+fld qword ptr (_One)
+fadd qword ptr (_H)
+fmulp st(1),st
+faddp st(1),st
+fmulp st(1),st
+fstp qword ptr (_X)
+L578:
+fld qword ptr (_Z)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+je L579
+fld qword ptr (_X)
+fsub qword ptr (_Z)
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L579
+lea edi,(L157)
+push edi
+push 3
+call _BadCond
+add esp,8
+fld qword ptr (_Z)
+sub esp,8
+fstp qword ptr [esp]
+fld qword ptr (_X)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L581)
+push edi
+call _printf
+add esp,20
+fld qword ptr (_X)
+fsub qword ptr (_Z)
+fstp qword ptr (_Z9)
+fld qword ptr (_Z9)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L582)
+push edi
+call _printf
+add esp,12
+lea edi,(L583)
+push edi
+call _printf
+add esp,4
+lea edi,(L584)
+push edi
+call _printf
+add esp,4
+lea edi,(L585)
+push edi
+call _printf
+add esp,4
+lea edi,(L586)
+push edi
+call _printf
+add esp,4
+lea edi,(L587)
+push edi
+call _printf
+add esp,4
+lea edi,(L588)
+push edi
+call _printf
+add esp,4
+lea edi,(_sigfpe)
+mov dword ptr (_sigsave),edi
+lea edi,(_ovfl_buf)
+push edi
+call __setjmp
+add esp,4
+cmp eax,0
+je L589
+lea edi,(L591)
+push edi
+call _printf
+add esp,4
+jmp L590
+L589:
+fld qword ptr (_X)
+fdiv qword ptr (_Z)
+fsub qword ptr (_Half)
+fsub qword ptr (_Half)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L592)
+push edi
+call _printf
+add esp,12
+L590:
+mov dword ptr (_sigsave),0
+L579:
+L572:
+lea edi,(L594)
+push edi
+fld qword ptr (_UfThold)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L593)
+push edi
+call _printf
+add esp,16
+lea edi,(L595)
+push edi
+call _printf
+add esp,4
+lea edi,(L596)
+push edi
+call _printf
+add esp,4
+fld qword ptr (_U1)
+fmul qword ptr (_U1)
+fstp qword ptr (_Y2)
+fld qword ptr (_Y2)
+fstp qword ptr (-1468)[ebp]
+fld qword ptr (-1468)[ebp]
+fmul qword ptr (-1468)[ebp]
+fstp qword ptr (_Y)
+fld qword ptr (_Y)
+fmul qword ptr (_U1)
+fstp qword ptr (_Y2)
+fld qword ptr (_UfThold)
+fcomp qword ptr (_Y2)
+fstsw ax
+sahf
+jb L597
+fld qword ptr (_E0)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+jae L599
+lea edi,(L157)
+push edi
+push 2
+call _BadCond
+add esp,8
+mov dword ptr (_I),5
+jmp L600
+L599:
+lea edi,(L157)
+push edi
+push 1
+call _BadCond
+add esp,8
+mov dword ptr (_I),4
+L600:
+mov edi,dword ptr (_I)
+push edi
+lea edi,(L601)
+push edi
+call _printf
+add esp,8
+L597:
+mov dword ptr (_Milestone),130
+fld qword ptr (_UfThold)
+sub esp,8
+fstp qword ptr [esp]
+call _log
+add esp,8
+fstp qword ptr (-1476)[ebp]
+fld qword ptr (_HInvrse)
+sub esp,8
+fstp qword ptr [esp]
+call _log
+add esp,8
+fstp qword ptr (-1484)[ebp]
+fld qword ptr (_Half)
+fld qword ptr (_TwoForty)
+fmul qword ptr (-1476)[ebp]
+fdiv qword ptr (-1484)[ebp]
+fsubp st(1),st
+sub esp,8
+fstp qword ptr [esp]
+call _floor
+add esp,8
+fstp qword ptr (-1492)[ebp]
+fld qword ptr (-1492)[ebp]
+fchs
+fdiv qword ptr (_TwoForty)
+fstp qword ptr (_Y)
+fld qword ptr (_Y)
+fadd qword ptr (_Y)
+fstp qword ptr (_Y2)
+lea edi,(L602)
+push edi
+call _printf
+add esp,4
+fld qword ptr (_Y)
+sub esp,8
+fstp qword ptr [esp]
+fld qword ptr (_HInvrse)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L603)
+push edi
+call _printf
+add esp,20
+fld qword ptr (_Y)
+sub esp,8
+fstp qword ptr [esp]
+fld qword ptr (_HInvrse)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L604)
+push edi
+call _printf
+add esp,20
+fld qword ptr (_Y2)
+sub esp,8
+fstp qword ptr [esp]
+fld qword ptr (_HInvrse)
+sub esp,8
+fstp qword ptr [esp]
+call _pow
+add esp,16
+fstp qword ptr (-1508)[ebp]
+fld qword ptr (-1508)[ebp]
+fstp qword ptr (_V9)
+fld qword ptr (_V9)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L605)
+push edi
+call _printf
+add esp,12
+fld qword ptr (_Zero)
+fcomp qword ptr (_V9)
+fstsw ax
+sahf
+ja L608
+fld qword ptr (_Radix)
+fadd qword ptr (_Radix)
+fadd qword ptr (_E9)
+fmul qword ptr (_UfThold)
+fcomp qword ptr (_V9)
+fstsw ax
+sahf
+jae L606
+L608:
+lea edi,(L609)
+push edi
+push 1
+call _BadCond
+add esp,8
+fld qword ptr (_UfThold)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L610)
+push edi
+call _printf
+add esp,12
+jmp L607
+L606:
+fld qword ptr (_UfThold)
+fld qword ptr (_One)
+fadd qword ptr (_E9)
+fmulp st(1),st
+fcomp qword ptr (_V9)
+fstsw ax
+sahf
+jb L611
+lea edi,(L613)
+push edi
+call _printf
+add esp,4
+jmp L612
+L611:
+lea edi,(L609)
+push edi
+push 2
+call _BadCond
+add esp,8
+fld qword ptr (_UfThold)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L610)
+push edi
+call _printf
+add esp,12
+L612:
+L607:
+mov dword ptr (_Milestone),140
+lea edi,(L44)
+push edi
+call _printf
+add esp,4
+fld qword ptr (_Zero)
+fstp qword ptr (_X)
+mov dword ptr (_I),2
+fld qword ptr (_Two)
+fmul qword ptr (_Three)
+fstp qword ptr (_Y)
+fld qword ptr (_Zero)
+fstp qword ptr (_Q)
+mov dword ptr (_N),0
+L614:
+fld qword ptr (_X)
+fstp qword ptr (_Z)
+inc dword ptr (_I)
+mov edi,dword ptr (_I)
+fld qword ptr (_Y)
+lea edi,[edi][edi]
+push edi
+fild dword ptr 0[esp]
+add esp,4
+fdivp st(1),st
+fstp qword ptr (_Y)
+fld qword ptr (_Y)
+fadd qword ptr (_Q)
+fstp qword ptr (_R)
+fld qword ptr (_Z)
+fstp qword ptr (-1540)[ebp]
+fld qword ptr (_R)
+fstp qword ptr (-1548)[ebp]
+fld qword ptr (-1540)[ebp]
+fadd qword ptr (-1548)[ebp]
+fstp qword ptr (_X)
+fld qword ptr (-1540)[ebp]
+fsub qword ptr (_X)
+fadd qword ptr (-1548)[ebp]
+fstp qword ptr (_Q)
+L615:
+fld qword ptr (_Z)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jb L614
+fld qword ptr (_OneAndHalf)
+fld qword ptr (_One)
+fdiv qword ptr (_Eight)
+faddp st(1),st
+fld qword ptr (_X)
+fld qword ptr (_OneAndHalf)
+fmul qword ptr (_ThirtyTwo)
+fdivp st(1),st
+faddp st(1),st
+fstp qword ptr (_Z)
+fld qword ptr (_Z)
+fstp qword ptr (-1548)[ebp]
+fld qword ptr (-1548)[ebp]
+fmul qword ptr (-1548)[ebp]
+fstp qword ptr (_X)
+fld qword ptr (_X)
+fstp qword ptr (-1556)[ebp]
+fld qword ptr (-1556)[ebp]
+fmul qword ptr (-1556)[ebp]
+fstp qword ptr (_Exp2)
+fld qword ptr (_F9)
+fstp qword ptr (_X)
+fld qword ptr (_X)
+fsub qword ptr (_U1)
+fstp qword ptr (_Y)
+fld qword ptr (_Exp2)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L617)
+push edi
+call _printf
+add esp,12
+mov dword ptr (_I),1
+L618:
+fld qword ptr (_X)
+fsub qword ptr (_BInvrse)
+fstp qword ptr (_Z)
+fld qword ptr (_X)
+fadd qword ptr (_One)
+fld qword ptr (_Z)
+fld qword ptr (_One)
+fsub qword ptr (_BInvrse)
+fsubp st(1),st
+fdivp st(1),st
+fstp qword ptr (_Z)
+fld qword ptr (_Z)
+sub esp,8
+fstp qword ptr [esp]
+fld qword ptr (_X)
+sub esp,8
+fstp qword ptr [esp]
+call _pow
+add esp,16
+fstp qword ptr (-1588)[ebp]
+fld qword ptr (-1588)[ebp]
+fsub qword ptr (_Exp2)
+fstp qword ptr (_Q)
+fld qword ptr (_Q)
+sub esp,8
+fstp qword ptr [esp]
+call _fabs
+add esp,8
+fstp qword ptr (-1596)[ebp]
+fld qword ptr (_TwoForty)
+fmul qword ptr (_U2)
+fcomp qword ptr (-1596)[ebp]
+fstsw ax
+sahf
+jae L622
+mov dword ptr (_N),1
+fld qword ptr (_X)
+fsub qword ptr (_BInvrse)
+fld qword ptr (_One)
+fsub qword ptr (_BInvrse)
+fsubp st(1),st
+fstp qword ptr (_V9)
+lea edi,(L624)
+push edi
+push 2
+call _BadCond
+add esp,8
+fld qword ptr (_Z)
+sub esp,8
+fstp qword ptr [esp]
+fld qword ptr (_X)
+sub esp,8
+fstp qword ptr [esp]
+call _pow
+add esp,16
+fstp qword ptr (-1612)[ebp]
+fld qword ptr (-1612)[ebp]
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L625)
+push edi
+call _printf
+add esp,12
+fld qword ptr (_Z)
+sub esp,8
+fstp qword ptr [esp]
+fld qword ptr (_V9)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L626)
+push edi
+call _printf
+add esp,20
+fld qword ptr (_Q)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L627)
+push edi
+call _printf
+add esp,12
+lea edi,(L628)
+push edi
+call _printf
+add esp,4
+lea edi,(L629)
+push edi
+call _printf
+add esp,4
+jmp L620
+L622:
+fld qword ptr (_Y)
+fstp qword ptr (-1604)[ebp]
+fld qword ptr (-1604)[ebp]
+fsub qword ptr (_X)
+fmul qword ptr (_Two)
+fadd qword ptr (-1604)[ebp]
+fstp qword ptr (_Z)
+fld qword ptr (-1604)[ebp]
+fstp qword ptr (_X)
+fld qword ptr (_Z)
+fstp qword ptr (_Y)
+fld qword ptr (_X)
+fsub qword ptr (_F9)
+fstp qword ptr (-1612)[ebp]
+fld qword ptr (_One)
+fld qword ptr (-1612)[ebp]
+fmul qword ptr (-1612)[ebp]
+faddp st(1),st
+fstp qword ptr (_Z)
+fld qword ptr (_One)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+jae L630
+mov edi,dword ptr (_NoTrials)
+cmp dword ptr (_I),edi
+jge L630
+inc dword ptr (_I)
+jmp L618
+L630:
+fld qword ptr (_One)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jae L632
+cmp dword ptr (_N),0
+jne L620
+lea edi,(L636)
+push edi
+call _printf
+add esp,4
+jmp L620
+L632:
+fld qword ptr (_One)
+fadd qword ptr (_U2)
+fstp qword ptr (_X)
+fld qword ptr (_U2)
+fadd qword ptr (_U2)
+fstp qword ptr (_Y)
+fld qword ptr (_Y)
+fadd qword ptr (_X)
+fstp qword ptr (_Y)
+mov dword ptr (_I),1
+jmp L618
+L620:
+mov dword ptr (_Milestone),150
+lea edi,(L637)
+push edi
+call _printf
+add esp,4
+mov dword ptr (_N),0
+fld qword ptr (_A1)
+fstp qword ptr (_Z)
+fld qword ptr (_C)
+sub esp,8
+fstp qword ptr [esp]
+call _log
+add esp,8
+fstp qword ptr (-1564)[ebp]
+fld qword ptr (_A1)
+sub esp,8
+fstp qword ptr [esp]
+call _log
+add esp,8
+fstp qword ptr (-1572)[ebp]
+fld qword ptr (_Half)
+fld qword ptr (-1564)[ebp]
+fdiv qword ptr (-1572)[ebp]
+fsubp st(1),st
+sub esp,8
+fstp qword ptr [esp]
+call _floor
+add esp,8
+fstp qword ptr (-1580)[ebp]
+fld qword ptr (-1580)[ebp]
+fstp qword ptr (_Q)
+mov dword ptr (_Break),0
+L638:
+fld qword ptr (_CInvrse)
+fstp qword ptr (_X)
+fld qword ptr (_Q)
+sub esp,8
+fstp qword ptr [esp]
+fld qword ptr (_Z)
+sub esp,8
+fstp qword ptr [esp]
+call _pow
+add esp,16
+fstp qword ptr (-1588)[ebp]
+fld qword ptr (-1588)[ebp]
+fstp qword ptr (_Y)
+call _IsYeqX
+add esp,0
+fld qword ptr (_Q)
+fchs
+fstp qword ptr (_Q)
+fld qword ptr (_C)
+fstp qword ptr (_X)
+fld qword ptr (_Q)
+sub esp,8
+fstp qword ptr [esp]
+fld qword ptr (_Z)
+sub esp,8
+fstp qword ptr [esp]
+call _pow
+add esp,16
+fstp qword ptr (-1596)[ebp]
+fld qword ptr (-1596)[ebp]
+fstp qword ptr (_Y)
+call _IsYeqX
+add esp,0
+fld qword ptr (_One)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+jbe L641
+mov dword ptr (_Break),1
+jmp L642
+L641:
+fld qword ptr (_AInvrse)
+fstp qword ptr (_Z)
+L642:
+L639:
+cmp dword ptr (_Break),0
+je L638
+call _PrintIfNPositive
+add esp,0
+cmp dword ptr (_N),0
+jne L643
+lea edi,(L645)
+push edi
+call _printf
+add esp,4
+L643:
+lea edi,(L44)
+push edi
+call _printf
+add esp,4
+mov dword ptr (_Milestone),160
+call _Pause
+add esp,0
+lea edi,(L646)
+push edi
+call _printf
+add esp,4
+lea edi,(L647)
+push edi
+call _printf
+add esp,4
+fld qword ptr (_CInvrse)
+fchs
+fstp qword ptr (_Y)
+fld qword ptr (_HInvrse)
+fmul qword ptr (_Y)
+fstp qword ptr (_V9)
+lea edi,(_sigfpe)
+mov dword ptr (_sigsave),edi
+lea edi,(_ovfl_buf)
+push edi
+call __setjmp
+add esp,4
+cmp eax,0
+je L648
+mov dword ptr (_I),0
+fld qword ptr (_Y)
+fstp qword ptr (_V9)
+jmp L650
+L648:
+L651:
+fld qword ptr (_Y)
+fstp qword ptr (_V)
+fld qword ptr (_V9)
+fstp qword ptr (_Y)
+fld qword ptr (_HInvrse)
+fmul qword ptr (_Y)
+fstp qword ptr (_V9)
+L652:
+fld qword ptr (_Y)
+fcomp qword ptr (_V9)
+fstsw ax
+sahf
+ja L651
+mov dword ptr (_I),1
+L650:
+mov dword ptr (_sigsave),0
+fld qword ptr (_V9)
+fstp qword ptr (_Z)
+lea edi,(L654)
+push edi
+call _printf
+add esp,4
+fld qword ptr (_Y)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L655)
+push edi
+call _printf
+add esp,12
+fld qword ptr (_Y)
+fchs
+fstp qword ptr (_V9)
+fld qword ptr (_V9)
+fstp qword ptr (_V0)
+fld qword ptr (_V)
+fsub qword ptr (_Y)
+fld qword ptr (_V)
+fadd qword ptr (_V0)
+fcompp
+fstsw ax
+sahf
+jne L656
+lea edi,(L658)
+push edi
+call _printf
+add esp,4
+jmp L657
+L656:
+lea edi,(L659)
+push edi
+call _printf
+add esp,4
+lea edi,(L660)
+push edi
+push 3
+call _BadCond
+add esp,8
+L657:
+fld qword ptr (_Y)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+je L661
+lea edi,(L157)
+push edi
+push 1
+call _BadCond
+add esp,8
+fld qword ptr (_Z)
+sub esp,8
+fstp qword ptr [esp]
+fld qword ptr (_Y)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L663)
+push edi
+call _printf
+add esp,20
+L661:
+cmp dword ptr (_I),0
+je L664
+fld qword ptr (_V)
+fld qword ptr (_HInvrse)
+fmul qword ptr (_U2)
+fsub qword ptr (_HInvrse)
+fmulp st(1),st
+fstp qword ptr (_Y)
+fld qword ptr (_Y)
+fld qword ptr (_One)
+fsub qword ptr (_HInvrse)
+fmul qword ptr (_U2)
+fmul qword ptr (_V)
+faddp st(1),st
+fstp qword ptr (_Z)
+fld qword ptr (_V0)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+jbe L666
+fld qword ptr (_Z)
+fstp qword ptr (_Y)
+L666:
+fld qword ptr (_V0)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+jbe L668
+fld qword ptr (_Y)
+fstp qword ptr (_V)
+L668:
+fld qword ptr (_V0)
+fsub qword ptr (_V)
+fld qword ptr (_V0)
+fcompp
+fstsw ax
+sahf
+jbe L665
+fld qword ptr (_V0)
+fstp qword ptr (_V)
+jmp L665
+L664:
+fld qword ptr (_Y)
+fld qword ptr (_HInvrse)
+fmul qword ptr (_U2)
+fsub qword ptr (_HInvrse)
+fmulp st(1),st
+fstp qword ptr (_V)
+fld qword ptr (_V)
+fld qword ptr (_One)
+fsub qword ptr (_HInvrse)
+fmul qword ptr (_U2)
+fmul qword ptr (_Y)
+faddp st(1),st
+fstp qword ptr (_V)
+L665:
+fld qword ptr (_V)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L672)
+push edi
+call _printf
+add esp,12
+cmp dword ptr (_I),0
+je L673
+fld qword ptr (_V0)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L675)
+push edi
+call _printf
+add esp,12
+jmp L674
+L673:
+lea edi,(L676)
+push edi
+call _printf
+add esp,4
+L674:
+fld qword ptr (_V)
+fmul qword ptr (_One)
+fstp qword ptr (_V9)
+fld qword ptr (_V9)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L677)
+push edi
+call _printf
+add esp,12
+fld qword ptr (_V)
+fdiv qword ptr (_One)
+fstp qword ptr (_V9)
+fld qword ptr (_V9)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L678)
+push edi
+call _printf
+add esp,12
+lea edi,(L679)
+push edi
+call _printf
+add esp,4
+lea edi,(L680)
+push edi
+call _printf
+add esp,4
+mov dword ptr (_Milestone),170
+fld qword ptr (_V)
+fchs
+fld qword ptr (_V)
+fcompp
+fstsw ax
+sahf
+jbe L685
+fld qword ptr (_V0)
+fchs
+fld qword ptr (_V0)
+fcompp
+fstsw ax
+sahf
+jbe L685
+fld qword ptr (_UfThold)
+fchs
+fld qword ptr (_V)
+fcompp
+fstsw ax
+sahf
+jbe L685
+fld qword ptr (_V)
+fcomp qword ptr (_UfThold)
+fstsw ax
+sahf
+ja L681
+L685:
+lea edi,(L686)
+push edi
+push 0
+call _BadCond
+add esp,8
+fld qword ptr (_UfThold)
+sub esp,8
+fstp qword ptr [esp]
+fld qword ptr (_V0)
+sub esp,8
+fstp qword ptr [esp]
+fld qword ptr (_V)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L687)
+push edi
+call _printf
+add esp,28
+L681:
+mov dword ptr (_Milestone),175
+lea edi,(L44)
+push edi
+call _printf
+add esp,4
+mov dword ptr (_Indx),1
+L688:
+mov edi,dword ptr (_Indx)
+cmp edi,1
+je L694
+cmp edi,2
+je L695
+cmp edi,3
+je L696
+jmp L692
+L694:
+fld qword ptr (_UfThold)
+fstp qword ptr (_Z)
+jmp L693
+L695:
+fld qword ptr (_E0)
+fstp qword ptr (_Z)
+jmp L693
+L696:
+fld qword ptr (_PseudoZero)
+fstp qword ptr (_Z)
+L692:
+L693:
+fld qword ptr (_Zero)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+je L697
+fld qword ptr (_Z)
+sub esp,8
+fstp qword ptr [esp]
+call _sqrt
+add esp,8
+fstp qword ptr (-1628)[ebp]
+fld qword ptr (-1628)[ebp]
+fstp qword ptr (_V9)
+fld qword ptr (_V9)
+fmul qword ptr (_V9)
+fstp qword ptr (_Y)
+fld qword ptr (_Radix)
+fmul qword ptr (_E9)
+fstp qword ptr (-1660)[ebp]
+fld qword ptr (_Y)
+fld qword ptr (_One)
+fsub qword ptr (-1660)[ebp]
+fdivp st(1),st
+fld qword ptr (_Z)
+fcompp
+fstsw ax
+sahf
+ja L701
+fld qword ptr (_One)
+fadd qword ptr (-1660)[ebp]
+fmul qword ptr (_Z)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+jae L699
+L701:
+fld qword ptr (_U1)
+fcomp qword ptr (_V9)
+fstsw ax
+sahf
+jae L702
+lea edi,(L157)
+push edi
+push 1
+call _BadCond
+add esp,8
+jmp L703
+L702:
+lea edi,(L157)
+push edi
+push 2
+call _BadCond
+add esp,8
+L703:
+fld qword ptr (_Z)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L704)
+push edi
+call _printf
+add esp,12
+fld qword ptr (_Y)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L705)
+push edi
+call _printf
+add esp,12
+L699:
+L697:
+L689:
+inc dword ptr (_Indx)
+cmp dword ptr (_Indx),3
+jle L688
+mov dword ptr (_Milestone),180
+mov dword ptr (_Indx),1
+L706:
+cmp dword ptr (_Indx),1
+jne L710
+fld qword ptr (_V)
+fstp qword ptr (_Z)
+jmp L711
+L710:
+fld qword ptr (_V0)
+fstp qword ptr (_Z)
+L711:
+fld qword ptr (_Z)
+sub esp,8
+fstp qword ptr [esp]
+call _sqrt
+add esp,8
+fstp qword ptr (-1628)[ebp]
+fld qword ptr (-1628)[ebp]
+fstp qword ptr (_V9)
+fld qword ptr (_V9)
+fstp qword ptr (-1636)[ebp]
+fld qword ptr (_One)
+fld qword ptr (_Radix)
+fmul qword ptr (_E9)
+fsubp st(1),st
+fmul qword ptr (-1636)[ebp]
+fstp qword ptr (_X)
+fld qword ptr (-1636)[ebp]
+fmul qword ptr (_X)
+fstp qword ptr (_V9)
+fld qword ptr (_One)
+fld qword ptr (_Two)
+fmul qword ptr (_Radix)
+fmul qword ptr (_E9)
+fsubp st(1),st
+fmul qword ptr (_Z)
+fcomp qword ptr (_V9)
+fstsw ax
+sahf
+ja L714
+fld qword ptr (_Z)
+fcomp qword ptr (_V9)
+fstsw ax
+sahf
+jae L712
+L714:
+fld qword ptr (_V9)
+fstp qword ptr (_Y)
+fld qword ptr (_W)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jbe L715
+lea edi,(L157)
+push edi
+push 1
+call _BadCond
+add esp,8
+jmp L716
+L715:
+lea edi,(L157)
+push edi
+push 2
+call _BadCond
+add esp,8
+L716:
+fld qword ptr (_Z)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L717)
+push edi
+call _printf
+add esp,12
+fld qword ptr (_Y)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L718)
+push edi
+call _printf
+add esp,12
+L712:
+L707:
+inc dword ptr (_Indx)
+cmp dword ptr (_Indx),2
+jle L706
+mov dword ptr (_Milestone),190
+call _Pause
+add esp,0
+fld qword ptr (_UfThold)
+fmul qword ptr (_V)
+fstp qword ptr (_X)
+fld qword ptr (_Radix)
+fmul qword ptr (_Radix)
+fstp qword ptr (_Y)
+fld qword ptr (_X)
+fmul qword ptr (_Y)
+fld qword ptr (_One)
+fcompp
+fstsw ax
+sahf
+ja L721
+fld qword ptr (_Y)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jae L719
+L721:
+fld qword ptr (_X)
+fmul qword ptr (_Y)
+fld qword ptr (_U1)
+fcompp
+fstsw ax
+sahf
+ja L724
+fld qword ptr (_Y)
+fdiv qword ptr (_U1)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+jae L722
+L724:
+lea edi,(L725)
+push edi
+push 2
+call _BadCond
+add esp,8
+jmp L723
+L722:
+lea edi,(L157)
+push edi
+push 3
+call _BadCond
+add esp,8
+L723:
+lea edi,(L727)
+push edi
+fld qword ptr (_X)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L726)
+push edi
+call _printf
+add esp,16
+L719:
+mov dword ptr (_Milestone),200
+mov dword ptr (_Indx),1
+L728:
+fld qword ptr (_F9)
+fstp qword ptr (_X)
+mov edi,dword ptr (_Indx)
+cmp edi,2
+jl L732
+cmp edi,5
+jg L732
+jmp dword ptr (L738-8)[edi*4]
+_TEXT ends
+_TEXT segment
+align 4
+L738 label byte
+dd L734
+dd L735
+dd L736
+dd L737
+_TEXT ends
+_TEXT segment
+L734:
+fld qword ptr (_One)
+fadd qword ptr (_U2)
+fstp qword ptr (_X)
+jmp L733
+L735:
+fld qword ptr (_V)
+fstp qword ptr (_X)
+jmp L733
+L736:
+fld qword ptr (_UfThold)
+fstp qword ptr (_X)
+jmp L733
+L737:
+fld qword ptr (_Radix)
+fstp qword ptr (_X)
+L732:
+L733:
+fld qword ptr (_X)
+fstp qword ptr (_Y)
+lea edi,(_sigfpe)
+mov dword ptr (_sigsave),edi
+lea edi,(_ovfl_buf)
+push edi
+call __setjmp
+add esp,4
+cmp eax,0
+je L740
+fld qword ptr (_X)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L742)
+push edi
+call _printf
+add esp,12
+jmp L741
+L740:
+fld qword ptr (_Y)
+fdiv qword ptr (_X)
+fsub qword ptr (_Half)
+fsub qword ptr (_Half)
+fstp qword ptr (_V9)
+fld qword ptr (_Zero)
+fcomp qword ptr (_V9)
+fstsw ax
+sahf
+jne L743
+jmp L729
+L743:
+fld qword ptr (_U1)
+fchs
+fcomp qword ptr (_V9)
+fstsw ax
+sahf
+jne L745
+cmp dword ptr (_Indx),5
+jge L745
+lea edi,(L157)
+push edi
+push 3
+call _BadCond
+add esp,8
+jmp L746
+L745:
+lea edi,(L157)
+push edi
+push 1
+call _BadCond
+add esp,8
+L746:
+fld qword ptr (_X)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L747)
+push edi
+call _printf
+add esp,12
+fld qword ptr (_V9)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L748)
+push edi
+call _printf
+add esp,12
+L741:
+mov dword ptr (_sigsave),0
+L729:
+inc dword ptr (_Indx)
+cmp dword ptr (_Indx),5
+jle L728
+mov dword ptr (_Milestone),210
+fld qword ptr (_Zero)
+fstp qword ptr (_MyZero)
+lea edi,(L44)
+push edi
+call _printf
+add esp,4
+lea edi,(L749)
+push edi
+call _printf
+add esp,4
+lea edi,(_sigfpe)
+mov dword ptr (_sigsave),edi
+lea edi,(L750)
+push edi
+call _printf
+add esp,4
+lea edi,(_ovfl_buf)
+push edi
+call __setjmp
+add esp,4
+cmp eax,0
+jne L751
+fld qword ptr (_One)
+fdiv qword ptr (_MyZero)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L753)
+push edi
+call _printf
+add esp,12
+L751:
+mov dword ptr (_sigsave),0
+lea edi,(_sigfpe)
+mov dword ptr (_sigsave),edi
+lea edi,(L754)
+push edi
+call _printf
+add esp,4
+lea edi,(_ovfl_buf)
+push edi
+call __setjmp
+add esp,4
+cmp eax,0
+jne L755
+fld qword ptr (_Zero)
+fdiv qword ptr (_MyZero)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L753)
+push edi
+call _printf
+add esp,12
+L755:
+mov dword ptr (_sigsave),0
+mov dword ptr (_Milestone),220
+call _Pause
+add esp,0
+lea edi,(L44)
+push edi
+call _printf
+add esp,4
+mov dword ptr (-1648)[ebp],0
+L762:
+mov edi,dword ptr (-1648)[ebp]
+cmp dword ptr (_ErrCnt)[edi*4],0
+je L766
+mov edi,dword ptr (-1648)[ebp]
+lea edi,[edi*4]
+mov esi,dword ptr (_ErrCnt)[edi]
+push esi
+mov edi,dword ptr (L757)[edi]
+push edi
+lea edi,(L768)
+push edi
+call _printf
+add esp,12
+L766:
+L763:
+inc dword ptr (-1648)[ebp]
+cmp dword ptr (-1648)[ebp],4
+jl L762
+lea edi,(L44)
+push edi
+call _printf
+add esp,4
+mov edi,dword ptr (_ErrCnt)
+mov esi,dword ptr (_ErrCnt+4)
+lea edi,[esi][edi]
+mov esi,dword ptr (_ErrCnt+8)
+lea edi,[esi][edi]
+mov esi,dword ptr (_ErrCnt+12)
+lea edi,[esi][edi]
+cmp edi,0
+jle L769
+mov edi,dword ptr (_ErrCnt)
+mov esi,dword ptr (_ErrCnt+4)
+lea edi,[esi][edi]
+mov esi,dword ptr (_ErrCnt+8)
+lea edi,[esi][edi]
+cmp edi,0
+jne L774
+cmp dword ptr (_ErrCnt+12),0
+jle L774
+lea edi,(L779)
+push edi
+call _printf
+add esp,4
+lea edi,(L780)
+push edi
+call _printf
+add esp,4
+L774:
+mov edi,dword ptr (_ErrCnt)
+mov esi,dword ptr (_ErrCnt+4)
+lea edi,[esi][edi]
+cmp edi,0
+jne L781
+cmp dword ptr (_ErrCnt+8),0
+jle L781
+lea edi,(L785)
+push edi
+call _printf
+add esp,4
+lea edi,(L786)
+push edi
+call _printf
+add esp,4
+L781:
+mov edi,dword ptr (_ErrCnt)
+mov esi,dword ptr (_ErrCnt+4)
+lea edi,[esi][edi]
+cmp edi,0
+jle L787
+lea edi,(L790)
+push edi
+call _printf
+add esp,4
+lea edi,(L791)
+push edi
+call _printf
+add esp,4
+L787:
+cmp dword ptr (_ErrCnt),0
+jle L770
+lea edi,(L794)
+push edi
+call _printf
+add esp,4
+lea edi,(L795)
+push edi
+call _printf
+add esp,4
+jmp L770
+L769:
+lea edi,(L796)
+push edi
+call _printf
+add esp,4
+cmp dword ptr (_RMult),1
+jne L801
+cmp dword ptr (_RDiv),1
+jne L801
+cmp dword ptr (_RAddSub),1
+jne L801
+cmp dword ptr (_RSqrt),1
+je L797
+L801:
+lea edi,(L802)
+push edi
+call _printf
+add esp,4
+jmp L798
+L797:
+fld qword ptr (_One)
+fcomp qword ptr (_StickyBit)
+fstsw ax
+sahf
+ja L803
+fld qword ptr (_Radix)
+fsub qword ptr (_Two)
+fld qword ptr (_Radix)
+fsub qword ptr (_Nine)
+fsub qword ptr (_One)
+fmulp st(1),st
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L803
+lea edi,(L805)
+push edi
+call _printf
+add esp,4
+lea edi,(L806)
+push edi
+call _printf
+add esp,4
+fld qword ptr (_Two)
+fcomp qword ptr (_Radix)
+fstsw ax
+sahf
+jne L807
+fld qword ptr (_Precision)
+fld qword ptr (_Four)
+fmul qword ptr (_Three)
+fmul qword ptr (_Two)
+fsubp st(1),st
+fld qword ptr (_Precision)
+fsub qword ptr (_TwentySeven)
+fsub qword ptr (_TwentySeven)
+fadd qword ptr (_One)
+fmulp st(1),st
+fld qword ptr (_Zero)
+fcompp
+fstsw ax
+sahf
+jne L807
+lea edi,(L809)
+push edi
+call _printf
+add esp,4
+jmp L808
+L807:
+lea edi,(L810)
+push edi
+call _printf
+add esp,4
+L808:
+cmp dword ptr (_IEEE),0
+je L811
+lea edi,(L813)
+push edi
+call _printf
+add esp,4
+jmp L812
+L811:
+lea edi,(L814)
+push edi
+call _printf
+add esp,4
+lea edi,(L815)
+push edi
+call _printf
+add esp,4
+L812:
+L803:
+lea edi,(L816)
+push edi
+call _printf
+add esp,4
+L798:
+L770:
+cmp dword ptr (_fpecount),0
+je L817
+mov edi,dword ptr (_fpecount)
+push edi
+lea edi,(L819)
+push edi
+call _printf
+add esp,8
+L817:
+lea edi,(L820)
+push edi
+call _printf
+add esp,4
+mov eax,0
+L6:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _Sign
+_Sign:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,8
+fld qword ptr (L7)
+fcomp qword ptr (20)[ebp]
+fstsw ax
+sahf
+ja L823
+fld qword ptr (L8)
+fstp qword ptr (-8)[ebp]
+jmp L824
+L823:
+fld qword ptr (L825)
+fstp qword ptr (-8)[ebp]
+L824:
+fld qword ptr (-8)[ebp]
+L821:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _Pause
+_Pause:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov edi,dword ptr (_Milestone)
+push edi
+lea edi,(L827)
+push edi
+call _printf
+add esp,8
+mov edi,dword ptr (_PageNo)
+push edi
+lea edi,(L828)
+push edi
+call _printf
+add esp,8
+inc dword ptr (_Milestone)
+inc dword ptr (_PageNo)
+mov eax,0
+L826:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _TstCond
+_TstCond:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+cmp dword ptr (24)[ebp],0
+jne L830
+mov edi,dword ptr (28)[ebp]
+push edi
+mov edi,dword ptr (20)[ebp]
+push edi
+call _BadCond
+add esp,8
+lea edi,(L813)
+push edi
+call _printf
+add esp,4
+L830:
+mov eax,0
+L829:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 4
+L833 label byte
+dd L834
+dd L835
+dd L836
+dd L837
+public _BadCond
+_DATA ends
+_TEXT segment
+_BadCond:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov edi,dword ptr (20)[ebp]
+lea edi,(_ErrCnt)[edi*4]
+inc dword ptr [edi]
+mov edi,dword ptr (24)[ebp]
+push edi
+mov edi,dword ptr (20)[ebp]
+mov edi,dword ptr (L833)[edi*4]
+push edi
+lea edi,(L838)
+push edi
+call _printf
+add esp,12
+mov eax,0
+L832:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _Random
+_Random:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,48
+fld qword ptr (_Random1)
+fadd qword ptr (_Random9)
+fstp qword ptr (-8)[ebp]
+fld qword ptr (-8)[ebp]
+fmul qword ptr (-8)[ebp]
+fstp qword ptr (-16)[ebp]
+fld qword ptr (-16)[ebp]
+fmul qword ptr (-16)[ebp]
+fstp qword ptr (-16)[ebp]
+fld qword ptr (-8)[ebp]
+fmul qword ptr (-16)[ebp]
+fstp qword ptr (-8)[ebp]
+fld qword ptr (-8)[ebp]
+sub esp,8
+fstp qword ptr [esp]
+call _floor
+add esp,8
+fstp qword ptr (-48)[ebp]
+fld qword ptr (-8)[ebp]
+fsub qword ptr (-48)[ebp]
+fstp qword ptr (-16)[ebp]
+fld qword ptr (-16)[ebp]
+fld qword ptr (L840)
+fmul qword ptr (-8)[ebp]
+faddp st(1),st
+fstp qword ptr (_Random1)
+fld qword ptr (_Random1)
+L839:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _SqXMinX
+_SqXMinX:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,40
+fld qword ptr (_X)
+fmul qword ptr (_BInvrse)
+fstp qword ptr (-8)[ebp]
+fld qword ptr (_X)
+fsub qword ptr (-8)[ebp]
+fstp qword ptr (-16)[ebp]
+fld qword ptr (_X)
+fmul qword ptr (_X)
+sub esp,8
+fstp qword ptr [esp]
+call _sqrt
+add esp,8
+fstp qword ptr (-32)[ebp]
+fld qword ptr (-32)[ebp]
+fsub qword ptr (-8)[ebp]
+fsub qword ptr (-16)[ebp]
+fdiv qword ptr (_OneUlp)
+fstp qword ptr (_SqEr)
+fld qword ptr (_Zero)
+fcomp qword ptr (_SqEr)
+fstsw ax
+sahf
+je L842
+fld qword ptr (_MinSqEr)
+fcomp qword ptr (_SqEr)
+fstsw ax
+sahf
+jbe L844
+fld qword ptr (_SqEr)
+fstp qword ptr (_MinSqEr)
+L844:
+fld qword ptr (_MaxSqEr)
+fcomp qword ptr (_SqEr)
+fstsw ax
+sahf
+jae L846
+fld qword ptr (_SqEr)
+fstp qword ptr (_MaxSqEr)
+L846:
+fld qword ptr (_J)
+fadd qword ptr (L8)
+fstp qword ptr (_J)
+lea edi,(L44)
+push edi
+mov edi,dword ptr (20)[ebp]
+push edi
+call _BadCond
+add esp,8
+fld qword ptr (_OneUlp)
+fmul qword ptr (_SqEr)
+sub esp,8
+fstp qword ptr [esp]
+fld qword ptr (_X)
+sub esp,8
+fstp qword ptr [esp]
+fld qword ptr (_X)
+fmul qword ptr (_X)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L848)
+push edi
+call _printf
+add esp,28
+lea edi,(L849)
+push edi
+call _printf
+add esp,4
+L842:
+mov eax,0
+L841:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _NewD
+_NewD:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,40
+fld qword ptr (_Z1)
+fmul qword ptr (_Q)
+fstp qword ptr (_X)
+fld qword ptr (_Half)
+fld qword ptr (_X)
+fdiv qword ptr (_Radix)
+fsubp st(1),st
+sub esp,8
+fstp qword ptr [esp]
+call _floor
+add esp,8
+fstp qword ptr (-8)[ebp]
+fld qword ptr (-8)[ebp]
+fmul qword ptr (_Radix)
+fadd qword ptr (_X)
+fstp qword ptr (_X)
+fld qword ptr (_X)
+fstp qword ptr (-24)[ebp]
+fld qword ptr (_Z)
+fstp qword ptr (-32)[ebp]
+fld qword ptr (_Q)
+fld qword ptr (-24)[ebp]
+fmul qword ptr (-32)[ebp]
+fsubp st(1),st
+fdiv qword ptr (_Radix)
+fld qword ptr (-24)[ebp]
+fmul qword ptr (-24)[ebp]
+fld qword ptr (_D)
+fdiv qword ptr (_Radix)
+fmulp st(1),st
+faddp st(1),st
+fstp qword ptr (_Q)
+fld qword ptr (-32)[ebp]
+fld qword ptr (_Two)
+fmul qword ptr (-24)[ebp]
+fmul qword ptr (_D)
+fsubp st(1),st
+fstp qword ptr (_Z)
+fld qword ptr (_Zero)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+jb L851
+fld qword ptr (_Z)
+fchs
+fstp qword ptr (_Z)
+fld qword ptr (_Z1)
+fchs
+fstp qword ptr (_Z1)
+L851:
+fld qword ptr (_Radix)
+fmul qword ptr (_D)
+fstp qword ptr (_D)
+mov eax,0
+L850:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _SR3750
+_SR3750:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,64
+fld qword ptr (_X)
+fsub qword ptr (_Radix)
+fld qword ptr (_Z2)
+fsub qword ptr (_Radix)
+fcompp
+fstsw ax
+sahf
+ja L854
+fld qword ptr (_X)
+fsub qword ptr (_Z2)
+fld qword ptr (_W)
+fsub qword ptr (_Z2)
+fcompp
+fstsw ax
+sahf
+jb L854
+inc dword ptr (_I)
+fld qword ptr (_X)
+fmul qword ptr (_D)
+sub esp,8
+fstp qword ptr [esp]
+call _sqrt
+add esp,8
+fstp qword ptr (-32)[ebp]
+fld qword ptr (-32)[ebp]
+fstp qword ptr (_X2)
+fld qword ptr (_X2)
+fsub qword ptr (_Z2)
+fld qword ptr (_Y)
+fsub qword ptr (_Z2)
+fsubp st(1),st
+fstp qword ptr (_Y2)
+fld qword ptr (_X8)
+fld qword ptr (_Y)
+fsub qword ptr (_Half)
+fdivp st(1),st
+fstp qword ptr (_X2)
+fld qword ptr (_X2)
+fstp qword ptr (-64)[ebp]
+fld qword ptr (-64)[ebp]
+fld qword ptr (_Half)
+fmul qword ptr (-64)[ebp]
+fmul qword ptr (-64)[ebp]
+fsubp st(1),st
+fstp qword ptr (_X2)
+fld qword ptr (_Y2)
+fadd qword ptr (_Half)
+fld qword ptr (_Half)
+fsub qword ptr (_X2)
+faddp st(1),st
+fstp qword ptr (_SqEr)
+fld qword ptr (_MinSqEr)
+fcomp qword ptr (_SqEr)
+fstsw ax
+sahf
+jbe L856
+fld qword ptr (_SqEr)
+fstp qword ptr (_MinSqEr)
+L856:
+fld qword ptr (_Y2)
+fsub qword ptr (_X2)
+fstp qword ptr (_SqEr)
+fld qword ptr (_MaxSqEr)
+fcomp qword ptr (_SqEr)
+fstsw ax
+sahf
+jae L858
+fld qword ptr (_SqEr)
+fstp qword ptr (_MaxSqEr)
+L858:
+L854:
+mov eax,0
+L853:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _IsYeqX
+_IsYeqX:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,8
+fld qword ptr (_X)
+fcomp qword ptr (_Y)
+fstsw ax
+sahf
+je L861
+cmp dword ptr (_N),0
+jg L863
+fld qword ptr (_Zero)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+jne L865
+fld qword ptr (_Zero)
+fcomp qword ptr (_Q)
+fstsw ax
+sahf
+jb L865
+lea edi,(L867)
+push edi
+call _printf
+add esp,4
+jmp L866
+L865:
+lea edi,(L868)
+push edi
+push 2
+call _BadCond
+add esp,8
+L866:
+fld qword ptr (_Q)
+sub esp,8
+fstp qword ptr [esp]
+fld qword ptr (_Z)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L869)
+push edi
+call _printf
+add esp,20
+fld qword ptr (_Y)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L870)
+push edi
+call _printf
+add esp,12
+fld qword ptr (_X)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L871)
+push edi
+call _printf
+add esp,12
+fld qword ptr (_Y)
+fsub qword ptr (_X)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L872)
+push edi
+call _printf
+add esp,12
+L863:
+inc dword ptr (_N)
+L861:
+mov eax,0
+L860:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _SR3980
+_SR3980:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,8
+L874:
+fild dword ptr (_I)
+fstp qword ptr (_Q)
+fld qword ptr (_Q)
+sub esp,8
+fstp qword ptr [esp]
+fld qword ptr (_Z)
+sub esp,8
+fstp qword ptr [esp]
+call _pow
+add esp,16
+fstp qword ptr (-8)[ebp]
+fld qword ptr (-8)[ebp]
+fstp qword ptr (_Y)
+call _IsYeqX
+add esp,0
+mov edi,dword ptr (_I)
+lea edi,(1)[edi]
+mov dword ptr (_I),edi
+cmp edi,dword ptr (_M)
+jle L877
+jmp L876
+L877:
+fld qword ptr (_Z)
+fmul qword ptr (_X)
+fstp qword ptr (_X)
+L875:
+fld qword ptr (_W)
+fcomp qword ptr (_X)
+fstsw ax
+sahf
+ja L874
+L876:
+mov eax,0
+L873:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _PrintIfNPositive
+_PrintIfNPositive:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+cmp dword ptr (_N),0
+jle L880
+mov edi,dword ptr (_N)
+push edi
+lea edi,(L882)
+push edi
+call _printf
+add esp,8
+L880:
+mov eax,0
+L879:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _TstPtUf
+_TstPtUf:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,48
+mov dword ptr (_N),0
+fld qword ptr (_Zero)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+je L884
+lea edi,(L886)
+push edi
+call _printf
+add esp,4
+lea edi,(L887)
+push edi
+call _printf
+add esp,4
+lea edi,(_sigfpe)
+mov dword ptr (_sigsave),edi
+lea edi,(_ovfl_buf)
+push edi
+call __setjmp
+add esp,4
+cmp eax,0
+je L888
+jmp L890
+L888:
+fld qword ptr (_Z)
+fadd qword ptr (_Z)
+fdiv qword ptr (_Z)
+fstp qword ptr (_Q9)
+fld qword ptr (_Q9)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L891)
+push edi
+call _printf
+add esp,12
+fld qword ptr (_Q9)
+fsub qword ptr (_Two)
+sub esp,8
+fstp qword ptr [esp]
+call _fabs
+add esp,8
+fstp qword ptr (-16)[ebp]
+fld qword ptr (_Radix)
+fmul qword ptr (_U2)
+fcomp qword ptr (-16)[ebp]
+fstsw ax
+sahf
+jbe L892
+lea edi,(L894)
+push edi
+call _printf
+add esp,4
+lea edi,(L895)
+push edi
+call _printf
+add esp,4
+jmp L893
+L892:
+fld qword ptr (_One)
+fcomp qword ptr (_Q9)
+fstsw ax
+sahf
+ja L898
+fld qword ptr (_Two)
+fcomp qword ptr (_Q9)
+fstsw ax
+sahf
+jae L896
+L898:
+L890:
+mov dword ptr (_N),1
+mov edi,dword ptr (_ErrCnt+4)
+lea edi,(1)[edi]
+mov dword ptr (_ErrCnt+4),edi
+lea edi,(L901)
+push edi
+call _printf
+add esp,4
+jmp L897
+L896:
+mov dword ptr (_N),1
+mov edi,dword ptr (_ErrCnt+8)
+lea edi,(1)[edi]
+mov dword ptr (_ErrCnt+8),edi
+lea edi,(L904)
+push edi
+call _printf
+add esp,4
+L897:
+L893:
+mov dword ptr (_sigsave),0
+fld qword ptr (_Z)
+fmul qword ptr (_One)
+fstp qword ptr (_V9)
+fld qword ptr (_V9)
+fstp qword ptr (_Random1)
+fld qword ptr (_One)
+fmul qword ptr (_Z)
+fstp qword ptr (_V9)
+fld qword ptr (_V9)
+fstp qword ptr (_Random2)
+fld qword ptr (_Z)
+fdiv qword ptr (_One)
+fstp qword ptr (_V9)
+fld qword ptr (_Random1)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+jne L905
+fld qword ptr (_Random2)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+jne L905
+fld qword ptr (_V9)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+jne L905
+cmp dword ptr (_N),0
+jle L906
+call _Pause
+add esp,0
+jmp L906
+L905:
+mov dword ptr (_N),1
+lea edi,(L909)
+push edi
+push 2
+call _BadCond
+add esp,8
+fld qword ptr (_Z)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L910)
+push edi
+call _printf
+add esp,12
+fld qword ptr (_Random1)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+je L911
+fld qword ptr (_Random1)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L913)
+push edi
+call _printf
+add esp,12
+L911:
+fld qword ptr (_Random2)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+je L914
+fld qword ptr (_Random1)
+fcomp qword ptr (_Random2)
+fstsw ax
+sahf
+je L914
+fld qword ptr (_Random2)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L916)
+push edi
+call _printf
+add esp,12
+L914:
+fld qword ptr (_V9)
+fcomp qword ptr (_Z)
+fstsw ax
+sahf
+je L917
+fld qword ptr (_V9)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L919)
+push edi
+call _printf
+add esp,12
+L917:
+fld qword ptr (_Random1)
+fcomp qword ptr (_Random2)
+fstsw ax
+sahf
+je L920
+mov edi,dword ptr (_ErrCnt+8)
+lea edi,(1)[edi]
+mov dword ptr (_ErrCnt+8),edi
+lea edi,(L924)
+push edi
+push 2
+call _BadCond
+add esp,8
+fld qword ptr (_Random2)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L925)
+push edi
+call _printf
+add esp,12
+fld qword ptr (_Random1)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L926)
+push edi
+call _printf
+add esp,12
+L920:
+call _Pause
+add esp,0
+L906:
+L884:
+mov eax,0
+L883:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _notify
+_notify:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov edi,dword ptr (20)[ebp]
+push edi
+lea edi,(L928)
+push edi
+call _printf
+add esp,8
+lea edi,(L929)
+push edi
+call _printf
+add esp,4
+mov eax,0
+L927:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _msglist
+_msglist:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+jmp L932
+L931:
+mov edi,dword ptr (20)[ebp]
+lea esi,(4)[edi]
+mov dword ptr (20)[ebp],esi
+mov edi,dword ptr [edi]
+push edi
+lea edi,(L934)
+push edi
+call _printf
+add esp,8
+L932:
+mov edi,dword ptr (20)[ebp]
+mov edi,dword ptr [edi]
+cmp edi,0
+jne L931
+mov eax,0
+L930:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 4
+L936 label byte
+dd L937
+dd L938
+dd L939
+dd L940
+dd L941
+dd L942
+dd L943
+dd L944
+dd L945
+dd 00H
+public _Instructions
+_DATA ends
+_TEXT segment
+_Instructions:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+lea edi,(L936)
+push edi
+call _msglist
+add esp,4
+mov eax,0
+L935:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 4
+L947 label byte
+dd L948
+dd L949
+dd L950
+dd L951
+dd L952
+dd L953
+dd L954
+dd L955
+dd L956
+dd L957
+dd L958
+dd L959
+dd L960
+dd L961
+dd 00H
+public _Heading
+_DATA ends
+_TEXT segment
+_Heading:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+lea edi,(L947)
+push edi
+call _msglist
+add esp,4
+mov eax,0
+L946:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 4
+L963 label byte
+dd L964
+dd L965
+dd L966
+dd L967
+dd L968
+dd L969
+dd L970
+dd L971
+dd L972
+dd L973
+dd L974
+dd L975
+dd L976
+dd L977
+dd L978
+dd L979
+dd L980
+dd L981
+dd L982
+dd 00H
+public _Characteristics
+_DATA ends
+_TEXT segment
+_Characteristics:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+lea edi,(L963)
+push edi
+call _msglist
+add esp,4
+mov eax,0
+L962:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+align 4
+L984 label byte
+dd L985
+dd L986
+dd L987
+dd L988
+dd L989
+dd L990
+dd L991
+dd L992
+dd L993
+dd L994
+dd L995
+dd L996
+dd L997
+dd L998
+dd L999
+dd L1000
+dd L1001
+dd 00H
+public _History
+_DATA ends
+_TEXT segment
+_History:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+lea edi,(L984)
+push edi
+call _msglist
+add esp,4
+mov eax,0
+L983:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _pow
+_pow:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,96
+mov dword ptr (-20)[ebp],0
+mov dword ptr (-24)[ebp],0
+fld qword ptr (L7)
+fcomp qword ptr (28)[ebp]
+fstsw ax
+sahf
+jne L1003
+fld qword ptr (L8)
+jmp L1002
+L1003:
+fld qword ptr (L1008)
+fcomp qword ptr (28)[ebp]
+fstsw ax
+sahf
+ja L1007
+fld qword ptr (L1009)
+fcomp qword ptr (28)[ebp]
+fstsw ax
+sahf
+jae L1005
+L1007:
+fld qword ptr (L825)
+fcomp qword ptr (20)[ebp]
+fstsw ax
+sahf
+je L1005
+fld qword ptr (20)[ebp]
+sub esp,8
+fstp qword ptr [esp]
+call _log
+add esp,8
+fstp qword ptr (-48)[ebp]
+fld qword ptr (28)[ebp]
+fmul qword ptr (-48)[ebp]
+sub esp,8
+fstp qword ptr [esp]
+call _exp
+add esp,8
+fstp qword ptr (-56)[ebp]
+fld qword ptr (-56)[ebp]
+jmp L1002
+L1005:
+fld qword ptr (L7)
+fcomp qword ptr (28)[ebp]
+fstsw ax
+sahf
+jbe L1010
+fld qword ptr (28)[ebp]
+fchs
+fstp qword ptr (28)[ebp]
+mov dword ptr (-24)[ebp],1
+L1010:
+lea edi,(-32)[ebp]
+push edi
+fld qword ptr (28)[ebp]
+sub esp,8
+fstp qword ptr [esp]
+call _modf
+add esp,12
+fstp qword ptr (-64)[ebp]
+fld qword ptr (-64)[ebp]
+fstp qword ptr (28)[ebp]
+fld qword ptr (L7)
+fcomp qword ptr (28)[ebp]
+fstsw ax
+sahf
+je L1012
+fld qword ptr (20)[ebp]
+sub esp,8
+fstp qword ptr [esp]
+call _log
+add esp,8
+fstp qword ptr (-72)[ebp]
+fld qword ptr (28)[ebp]
+fmul qword ptr (-72)[ebp]
+sub esp,8
+fstp qword ptr [esp]
+call _exp
+add esp,8
+fstp qword ptr (-80)[ebp]
+fld qword ptr (-80)[ebp]
+fstp qword ptr (-16)[ebp]
+jmp L1013
+L1012:
+fld qword ptr (L8)
+fstp qword ptr (-16)[ebp]
+L1013:
+lea edi,(-8)[ebp]
+push edi
+fld qword ptr (20)[ebp]
+sub esp,8
+fstp qword ptr [esp]
+call _frexp
+add esp,12
+fstp qword ptr (-88)[ebp]
+fld qword ptr (-88)[ebp]
+fstp qword ptr (20)[ebp]
+fld qword ptr (-32)[ebp]
+call __ftol
+mov dword ptr (-4)[ebp],eax
+cmp eax,0
+je L1014
+L1016:
+mov edi,dword ptr (-4)[ebp]
+and edi,1
+cmp edi,0
+je L1020
+fld qword ptr (-16)[ebp]
+fmul qword ptr (20)[ebp]
+fstp qword ptr (-16)[ebp]
+mov edi,dword ptr (-8)[ebp]
+add dword ptr (-20)[ebp],edi
+L1020:
+mov edi,dword ptr (-4)[ebp]
+sar edi,1
+mov dword ptr (-4)[ebp],edi
+cmp edi,0
+jne L1022
+jmp L1018
+L1022:
+fld qword ptr (20)[ebp]
+fmul qword ptr (20)[ebp]
+fstp qword ptr (20)[ebp]
+sal dword ptr (-8)[ebp],1
+fld qword ptr (L1026)
+fcomp qword ptr (20)[ebp]
+fstsw ax
+sahf
+jbe L1016
+fld qword ptr (L1027)
+fmul qword ptr (20)[ebp]
+fstp qword ptr (20)[ebp]
+dec dword ptr (-8)[ebp]
+jmp L1016
+L1018:
+L1014:
+cmp dword ptr (-24)[ebp],0
+je L1028
+fld qword ptr (L8)
+fdiv qword ptr (-16)[ebp]
+fstp qword ptr (-16)[ebp]
+neg dword ptr (-20)[ebp]
+L1028:
+mov edi,dword ptr (-20)[ebp]
+push edi
+fld qword ptr (-16)[ebp]
+sub esp,8
+fstp qword ptr [esp]
+call _ldexp
+add esp,12
+fstp qword ptr (-96)[ebp]
+fld qword ptr (-96)[ebp]
+L1002:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+extrn _modf:near
+_TEXT segment
+_TEXT ends
+extrn _ldexp:near
+_TEXT segment
+_TEXT ends
+extrn _frexp:near
+_TEXT segment
+_TEXT ends
+extrn _exp:near
+_TEXT segment
+_TEXT ends
+extrn _abort:near
+_TEXT segment
+_TEXT ends
+_DATA segment
+public _UfNGrad
+align 4
+_UfNGrad label byte
+db 4 dup (0)
+public _SqRWrng
+align 4
+_SqRWrng label byte
+db 4 dup (0)
+public _IEEE
+align 4
+_IEEE label byte
+db 4 dup (0)
+public _Anomaly
+align 4
+_Anomaly label byte
+db 4 dup (0)
+public _Monot
+align 4
+_Monot label byte
+db 4 dup (0)
+public _NotMonot
+align 4
+_NotMonot label byte
+db 4 dup (0)
+public _Done
+align 4
+_Done label byte
+db 4 dup (0)
+public _Break
+align 4
+_Break label byte
+db 4 dup (0)
+public _RSqrt
+align 4
+_RSqrt label byte
+db 4 dup (0)
+public _RAddSub
+align 4
+_RAddSub label byte
+db 4 dup (0)
+public _RDiv
+align 4
+_RDiv label byte
+db 4 dup (0)
+public _RMult
+align 4
+_RMult label byte
+db 4 dup (0)
+public _GAddSub
+align 4
+_GAddSub label byte
+db 4 dup (0)
+public _GDiv
+align 4
+_GDiv label byte
+db 4 dup (0)
+public _GMult
+align 4
+_GMult label byte
+db 4 dup (0)
+public _N1
+align 4
+_N1 label byte
+db 4 dup (0)
+public _N
+align 4
+_N label byte
+db 4 dup (0)
+public _M
+align 4
+_M label byte
+db 4 dup (0)
+public _PageNo
+align 4
+_PageNo label byte
+db 4 dup (0)
+public _Milestone
+align 4
+_Milestone label byte
+db 4 dup (0)
+public _fpecount
+align 4
+_fpecount label byte
+db 4 dup (0)
+public _ErrCnt
+align 4
+_ErrCnt label byte
+db 16 dup (0)
+public _Z9
+align 4
+_Z9 label byte
+db 8 dup (0)
+public _Z2
+align 4
+_Z2 label byte
+db 8 dup (0)
+public _Z1
+align 4
+_Z1 label byte
+db 8 dup (0)
+public _PseudoZero
+align 4
+_PseudoZero label byte
+db 8 dup (0)
+public _Z
+align 4
+_Z label byte
+db 8 dup (0)
+public _Random2
+align 4
+_Random2 label byte
+db 8 dup (0)
+public _Y2
+align 4
+_Y2 label byte
+db 8 dup (0)
+public _Y1
+align 4
+_Y1 label byte
+db 8 dup (0)
+public _Y
+align 4
+_Y label byte
+db 8 dup (0)
+public _Random1
+align 4
+_Random1 label byte
+db 8 dup (0)
+public _X8
+align 4
+_X8 label byte
+db 8 dup (0)
+public _X2
+align 4
+_X2 label byte
+db 8 dup (0)
+public _X1
+align 4
+_X1 label byte
+db 8 dup (0)
+public _X
+align 4
+_X label byte
+db 8 dup (0)
+public _W
+align 4
+_W label byte
+db 8 dup (0)
+public _V9
+align 4
+_V9 label byte
+db 8 dup (0)
+public _V0
+align 4
+_V0 label byte
+db 8 dup (0)
+public _V
+align 4
+_V label byte
+db 8 dup (0)
+public _U2
+align 4
+_U2 label byte
+db 8 dup (0)
+public _U1
+align 4
+_U1 label byte
+db 8 dup (0)
+public _UfThold
+align 4
+_UfThold label byte
+db 8 dup (0)
+public _OneUlp
+align 4
+_OneUlp label byte
+db 8 dup (0)
+public _S
+align 4
+_S label byte
+db 8 dup (0)
+public _Underflow
+align 4
+_Underflow label byte
+db 8 dup (0)
+public _T
+align 4
+_T label byte
+db 8 dup (0)
+public _Random9
+align 4
+_Random9 label byte
+db 8 dup (0)
+public _R
+align 4
+_R label byte
+db 8 dup (0)
+public _Q9
+align 4
+_Q9 label byte
+db 8 dup (0)
+public _Q
+align 4
+_Q label byte
+db 8 dup (0)
+public _Precision
+align 4
+_Precision label byte
+db 8 dup (0)
+public _MyZero
+align 4
+_MyZero label byte
+db 8 dup (0)
+public _J
+align 4
+_J label byte
+db 8 dup (0)
+public _StickyBit
+align 4
+_StickyBit label byte
+db 8 dup (0)
+public _I
+align 4
+_I label byte
+db 4 dup (0)
+public _HInvrse
+align 4
+_HInvrse label byte
+db 8 dup (0)
+public _H
+align 4
+_H label byte
+db 8 dup (0)
+public _F9
+align 4
+_F9 label byte
+db 8 dup (0)
+public _F6
+align 4
+_F6 label byte
+db 8 dup (0)
+public _Third
+align 4
+_Third label byte
+db 8 dup (0)
+public _E9
+align 4
+_E9 label byte
+db 8 dup (0)
+public _MaxSqEr
+align 4
+_MaxSqEr label byte
+db 8 dup (0)
+public _SqEr
+align 4
+_SqEr label byte
+db 8 dup (0)
+public _MinSqEr
+align 4
+_MinSqEr label byte
+db 8 dup (0)
+public _E3
+align 4
+_E3 label byte
+db 8 dup (0)
+public _Exp2
+align 4
+_Exp2 label byte
+db 8 dup (0)
+public _E1
+align 4
+_E1 label byte
+db 8 dup (0)
+public _E0
+align 4
+_E0 label byte
+db 8 dup (0)
+public _FourD
+align 4
+_FourD label byte
+db 8 dup (0)
+public _D
+align 4
+_D label byte
+db 8 dup (0)
+public _CInvrse
+align 4
+_CInvrse label byte
+db 8 dup (0)
+public _C
+align 4
+_C label byte
+db 8 dup (0)
+public _A1
+align 4
+_A1 label byte
+db 8 dup (0)
+public _AInvrse
+align 4
+_AInvrse label byte
+db 8 dup (0)
+public _ch
+align 1
+_ch label byte
+db 8 dup (0)
+public _Indx
+align 4
+_Indx label byte
+db 4 dup (0)
+public _BMinusU2
+align 4
+_BMinusU2 label byte
+db 8 dup (0)
+public _RadixD2
+align 4
+_RadixD2 label byte
+db 8 dup (0)
+public _BInvrse
+align 4
+_BInvrse label byte
+db 8 dup (0)
+public _Radix
+align 4
+_Radix label byte
+db 8 dup (0)
+public _sigsave
+align 4
+_sigsave label byte
+db 4 dup (0)
+public _ovfl_buf
+align 4
+_ovfl_buf label byte
+db 64 dup (0)
+_DATA ends
+extrn _sqrt:near
+_DATA segment
+_DATA ends
+extrn _log:near
+_DATA segment
+_DATA ends
+extrn _floor:near
+_DATA segment
+_DATA ends
+extrn _fabs:near
+_DATA segment
+_DATA ends
+extrn _longjmp:near
+_DATA segment
+_DATA ends
+extrn __setjmp:near
+_DATA segment
+_DATA ends
+extrn _signal:near
+_DATA segment
+_DATA ends
+extrn _printf:near
+_DATA segment
+_DATA ends
+extrn _fflush:near
+_DATA segment
+_DATA ends
+extrn __iob:near
+_DATA segment
+_DATA ends
+_TEXT segment
+align 4
+L1027 label byte
+dd 00H
+dd 040000000H
+align 4
+L1026 label byte
+dd 00H
+dd 03fe00000H
+align 4
+L1009 label byte
+dd 00H
+dd 040913000H
+align 4
+L1008 label byte
+dd 00H
+dd 0c0913000H
+align 1
+L1001 label byte
+db 115
+db 101
+db 101
+db 32
+db 115
+db 111
+db 117
+db 114
+db 99
+db 101
+db 32
+db 99
+db 111
+db 109
+db 109
+db 101
+db 110
+db 116
+db 115
+db 32
+db 102
+db 111
+db 114
+db 32
+db 109
+db 111
+db 114
+db 101
+db 32
+db 104
+db 105
+db 115
+db 116
+db 111
+db 114
+db 121
+db 46
+db 0
+align 1
+L1000 label byte
+db 66
+db 65
+db 83
+db 73
+db 67
+db 32
+db 118
+db 101
+db 114
+db 115
+db 105
+db 111
+db 110
+db 32
+db 111
+db 102
+db 32
+db 116
+db 104
+db 105
+db 115
+db 32
+db 112
+db 114
+db 111
+db 103
+db 114
+db 97
+db 109
+db 32
+db 40
+db 67
+db 41
+db 32
+db 49
+db 57
+db 56
+db 51
+db 32
+db 98
+db 121
+db 32
+db 80
+db 114
+db 111
+db 102
+db 46
+db 32
+db 87
+db 46
+db 32
+db 77
+db 46
+db 32
+db 75
+db 97
+db 104
+db 97
+db 110
+db 59
+db 0
+align 1
+L999 label byte
+db 97
+db 115
+db 32
+db 117
+db 115
+db 101
+db 100
+db 32
+db 98
+db 121
+db 32
+db 99
+db 101
+db 114
+db 116
+db 97
+db 105
+db 110
+db 32
+db 101
+db 97
+db 114
+db 108
+db 121
+db 32
+db 87
+db 65
+db 78
+db 71
+db 32
+db 109
+db 97
+db 99
+db 104
+db 105
+db 110
+db 101
+db 115
+db 46
+db 10
+db 0
+align 1
+L998 label byte
+db 102
+db 108
+db 111
+db 97
+db 116
+db 105
+db 110
+db 103
+db 45
+db 112
+db 111
+db 105
+db 110
+db 116
+db 32
+db 110
+db 117
+db 109
+db 98
+db 101
+db 114
+db 115
+db 44
+db 32
+db 98
+db 117
+db 116
+db 32
+db 97
+db 108
+db 115
+db 111
+db 32
+db 97
+db 108
+db 108
+db 111
+db 119
+db 115
+db 32
+db 108
+db 111
+db 103
+db 97
+db 114
+db 105
+db 116
+db 104
+db 109
+db 105
+db 99
+db 32
+db 101
+db 110
+db 99
+db 111
+db 100
+db 105
+db 110
+db 103
+db 0
+align 1
+L997 label byte
+db 10
+db 84
+db 104
+db 101
+db 32
+db 112
+db 114
+db 111
+db 103
+db 114
+db 97
+db 109
+db 32
+db 105
+db 115
+db 32
+db 98
+db 97
+db 115
+db 101
+db 100
+db 32
+db 117
+db 112
+db 111
+db 110
+db 32
+db 97
+db 32
+db 99
+db 111
+db 110
+db 118
+db 101
+db 110
+db 116
+db 105
+db 111
+db 110
+db 97
+db 108
+db 32
+db 114
+db 97
+db 100
+db 105
+db 120
+db 32
+db 114
+db 101
+db 112
+db 114
+db 101
+db 115
+db 101
+db 110
+db 116
+db 97
+db 116
+db 105
+db 111
+db 110
+db 32
+db 102
+db 111
+db 114
+db 0
+align 1
+L996 label byte
+db 111
+db 102
+db 32
+db 112
+db 97
+db 116
+db 104
+db 111
+db 108
+db 111
+db 103
+db 105
+db 101
+db 115
+db 44
+db 32
+db 97
+db 110
+db 100
+db 32
+db 116
+db 111
+db 32
+db 115
+db 97
+db 121
+db 32
+db 104
+db 111
+db 119
+db 32
+db 119
+db 101
+db 108
+db 108
+db 32
+db 116
+db 104
+db 101
+db 32
+db 97
+db 114
+db 105
+db 116
+db 104
+db 109
+db 101
+db 116
+db 105
+db 99
+db 32
+db 105
+db 115
+db 32
+db 105
+db 109
+db 112
+db 108
+db 101
+db 109
+db 101
+db 110
+db 116
+db 101
+db 100
+db 46
+db 0
+align 1
+L995 label byte
+db 111
+db 102
+db 32
+db 116
+db 104
+db 101
+db 32
+db 97
+db 114
+db 105
+db 116
+db 104
+db 109
+db 101
+db 116
+db 105
+db 99
+db 44
+db 32
+db 116
+db 104
+db 105
+db 115
+db 32
+db 112
+db 114
+db 111
+db 103
+db 114
+db 97
+db 109
+db 32
+db 116
+db 114
+db 105
+db 101
+db 115
+db 32
+db 116
+db 111
+db 32
+db 99
+db 111
+db 112
+db 101
+db 32
+db 119
+db 105
+db 116
+db 104
+db 32
+db 97
+db 32
+db 119
+db 105
+db 100
+db 101
+db 114
+db 32
+db 118
+db 97
+db 114
+db 105
+db 101
+db 116
+db 121
+db 0
+align 1
+L994 label byte
+db 116
+db 104
+db 101
+db 32
+db 82
+db 97
+db 100
+db 105
+db 120
+db 44
+db 32
+db 80
+db 114
+db 101
+db 99
+db 105
+db 115
+db 105
+db 111
+db 110
+db 32
+db 97
+db 110
+db 100
+db 32
+db 114
+db 97
+db 110
+db 103
+db 101
+db 32
+db 40
+db 111
+db 118
+db 101
+db 114
+db 47
+db 117
+db 110
+db 100
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 32
+db 116
+db 104
+db 114
+db 101
+db 115
+db 104
+db 111
+db 108
+db 100
+db 115
+db 41
+db 0
+align 1
+L993 label byte
+db 87
+db 46
+db 32
+db 74
+db 46
+db 32
+db 67
+db 111
+db 100
+db 121
+db 32
+db 97
+db 110
+db 100
+db 32
+db 87
+db 46
+db 32
+db 87
+db 97
+db 105
+db 116
+db 101
+db 46
+db 32
+db 65
+db 108
+db 116
+db 104
+db 111
+db 117
+db 103
+db 104
+db 32
+db 98
+db 111
+db 116
+db 104
+db 32
+db 112
+db 114
+db 111
+db 103
+db 114
+db 97
+db 109
+db 115
+db 32
+db 116
+db 114
+db 121
+db 32
+db 116
+db 111
+db 32
+db 100
+db 105
+db 115
+db 99
+db 111
+db 118
+db 101
+db 114
+db 0
+align 1
+L992 label byte
+db 98
+db 111
+db 111
+db 107
+db 32
+db 32
+db 96
+db 83
+db 111
+db 102
+db 116
+db 119
+db 97
+db 114
+db 101
+db 32
+db 77
+db 97
+db 110
+db 117
+db 97
+db 108
+db 32
+db 102
+db 111
+db 114
+db 32
+db 116
+db 104
+db 101
+db 32
+db 69
+db 108
+db 101
+db 109
+db 101
+db 110
+db 116
+db 97
+db 114
+db 121
+db 32
+db 70
+db 117
+db 110
+db 99
+db 116
+db 105
+db 111
+db 110
+db 115
+db 39
+db 32
+db 40
+db 49
+db 57
+db 56
+db 48
+db 41
+db 32
+db 98
+db 121
+db 0
+align 1
+L991 label byte
+db 112
+db 114
+db 111
+db 103
+db 114
+db 97
+db 109
+db 32
+db 99
+db 97
+db 108
+db 108
+db 101
+db 100
+db 32
+db 96
+db 77
+db 65
+db 67
+db 72
+db 65
+db 82
+db 39
+db 44
+db 32
+db 119
+db 104
+db 105
+db 99
+db 104
+db 32
+db 99
+db 97
+db 110
+db 32
+db 98
+db 101
+db 32
+db 102
+db 111
+db 117
+db 110
+db 100
+db 32
+db 97
+db 116
+db 32
+db 116
+db 104
+db 101
+db 32
+db 101
+db 110
+db 100
+db 32
+db 111
+db 102
+db 32
+db 116
+db 104
+db 101
+db 0
+align 1
+L990 label byte
+db 84
+db 104
+db 101
+db 32
+db 100
+db 105
+db 97
+db 103
+db 110
+db 111
+db 115
+db 116
+db 105
+db 99
+db 32
+db 99
+db 97
+db 112
+db 97
+db 98
+db 105
+db 108
+db 105
+db 116
+db 105
+db 101
+db 115
+db 32
+db 111
+db 102
+db 32
+db 116
+db 104
+db 105
+db 115
+db 32
+db 112
+db 114
+db 111
+db 103
+db 114
+db 97
+db 109
+db 32
+db 103
+db 111
+db 32
+db 98
+db 101
+db 121
+db 111
+db 110
+db 100
+db 32
+db 97
+db 110
+db 32
+db 101
+db 97
+db 114
+db 108
+db 105
+db 101
+db 114
+db 0
+align 1
+L989 label byte
+db 70
+db 97
+db 105
+db 108
+db 117
+db 114
+db 101
+db 115
+db 32
+db 109
+db 97
+db 121
+db 32
+db 99
+db 111
+db 110
+db 102
+db 111
+db 117
+db 110
+db 100
+db 32
+db 115
+db 117
+db 98
+db 115
+db 101
+db 113
+db 117
+db 101
+db 110
+db 116
+db 32
+db 100
+db 105
+db 97
+db 103
+db 110
+db 111
+db 115
+db 101
+db 115
+db 46
+db 10
+db 0
+align 1
+L988 label byte
+db 32
+db 32
+db 32
+db 70
+db 65
+db 73
+db 76
+db 85
+db 82
+db 69
+db 115
+db 44
+db 32
+db 108
+db 105
+db 107
+db 101
+db 32
+db 50
+db 43
+db 50
+db 32
+db 61
+db 61
+db 32
+db 53
+db 32
+db 46
+db 0
+align 1
+L987 label byte
+db 32
+db 32
+db 32
+db 83
+db 101
+db 114
+db 105
+db 111
+db 117
+db 115
+db 32
+db 68
+db 69
+db 70
+db 69
+db 67
+db 84
+db 115
+db 44
+db 32
+db 108
+db 105
+db 107
+db 101
+db 32
+db 108
+db 97
+db 99
+db 107
+db 32
+db 111
+db 102
+db 32
+db 97
+db 32
+db 103
+db 117
+db 97
+db 114
+db 100
+db 32
+db 100
+db 105
+db 103
+db 105
+db 116
+db 44
+db 32
+db 97
+db 110
+db 100
+db 0
+align 1
+L986 label byte
+db 32
+db 32
+db 32
+db 70
+db 76
+db 65
+db 87
+db 115
+db 44
+db 32
+db 108
+db 105
+db 107
+db 101
+db 32
+db 108
+db 97
+db 99
+db 107
+db 32
+db 111
+db 102
+db 32
+db 97
+db 32
+db 115
+db 116
+db 105
+db 99
+db 107
+db 121
+db 32
+db 98
+db 105
+db 116
+db 44
+db 0
+align 1
+L985 label byte
+db 84
+db 104
+db 101
+db 32
+db 112
+db 114
+db 111
+db 103
+db 114
+db 97
+db 109
+db 32
+db 97
+db 116
+db 116
+db 101
+db 109
+db 112
+db 116
+db 115
+db 32
+db 116
+db 111
+db 32
+db 100
+db 105
+db 115
+db 99
+db 114
+db 105
+db 109
+db 105
+db 110
+db 97
+db 116
+db 101
+db 32
+db 97
+db 109
+db 111
+db 110
+db 103
+db 0
+align 1
+L982 label byte
+db 32
+db 32
+db 32
+db 32
+db 32
+db 68
+db 101
+db 99
+db 105
+db 109
+db 97
+db 108
+db 45
+db 66
+db 105
+db 110
+db 97
+db 114
+db 121
+db 32
+db 99
+db 111
+db 110
+db 118
+db 101
+db 114
+db 115
+db 105
+db 111
+db 110
+db 32
+db 105
+db 115
+db 32
+db 78
+db 79
+db 84
+db 32
+db 89
+db 69
+db 84
+db 32
+db 116
+db 101
+db 115
+db 116
+db 101
+db 100
+db 32
+db 102
+db 111
+db 114
+db 32
+db 97
+db 99
+db 99
+db 117
+db 114
+db 97
+db 99
+db 121
+db 46
+db 0
+align 1
+L981 label byte
+db 32
+db 32
+db 32
+db 32
+db 32
+db 69
+db 120
+db 116
+db 114
+db 97
+db 45
+db 112
+db 114
+db 101
+db 99
+db 105
+db 115
+db 101
+db 32
+db 115
+db 117
+db 98
+db 101
+db 120
+db 112
+db 114
+db 101
+db 115
+db 115
+db 105
+db 111
+db 110
+db 115
+db 32
+db 97
+db 114
+db 101
+db 32
+db 114
+db 101
+db 118
+db 101
+db 97
+db 108
+db 101
+db 100
+db 32
+db 98
+db 117
+db 116
+db 32
+db 78
+db 79
+db 84
+db 32
+db 89
+db 69
+db 84
+db 32
+db 116
+db 101
+db 115
+db 116
+db 101
+db 100
+db 46
+db 0
+align 1
+L980 label byte
+db 32
+db 32
+db 32
+db 32
+db 32
+db 83
+db 113
+db 114
+db 116
+db 32
+db 105
+db 115
+db 32
+db 116
+db 101
+db 115
+db 116
+db 101
+db 100
+db 46
+db 32
+db 32
+db 89
+db 94
+db 88
+db 32
+db 105
+db 115
+db 32
+db 110
+db 111
+db 116
+db 32
+db 116
+db 101
+db 115
+db 116
+db 101
+db 100
+db 46
+db 0
+align 1
+L979 label byte
+db 9
+db 97
+db 110
+db 100
+db 32
+db 102
+db 111
+db 114
+db 32
+db 99
+db 111
+db 110
+db 116
+db 97
+db 109
+db 105
+db 110
+db 97
+db 116
+db 105
+db 111
+db 110
+db 32
+db 119
+db 105
+db 116
+db 104
+db 32
+db 112
+db 115
+db 101
+db 117
+db 100
+db 111
+db 45
+db 122
+db 101
+db 114
+db 111
+db 115
+db 46
+db 0
+align 1
+L978 label byte
+db 32
+db 32
+db 32
+db 32
+db 32
+db 67
+db 111
+db 109
+db 112
+db 97
+db 114
+db 105
+db 115
+db 105
+db 111
+db 110
+db 115
+db 32
+db 97
+db 114
+db 101
+db 32
+db 99
+db 104
+db 101
+db 99
+db 107
+db 101
+db 100
+db 32
+db 102
+db 111
+db 114
+db 32
+db 99
+db 111
+db 110
+db 115
+db 105
+db 115
+db 116
+db 101
+db 110
+db 99
+db 121
+db 32
+db 119
+db 105
+db 116
+db 104
+db 32
+db 115
+db 117
+db 98
+db 116
+db 114
+db 97
+db 99
+db 116
+db 105
+db 111
+db 110
+db 0
+align 1
+L977 label byte
+db 32
+db 32
+db 32
+db 32
+db 32
+db 86
+db 48
+db 32
+db 32
+db 116
+db 101
+db 108
+db 108
+db 115
+db 44
+db 32
+db 114
+db 111
+db 117
+db 103
+db 104
+db 108
+db 121
+db 44
+db 32
+db 119
+db 104
+db 101
+db 116
+db 104
+db 101
+db 114
+db 32
+db 32
+db 73
+db 110
+db 102
+db 105
+db 110
+db 105
+db 116
+db 121
+db 32
+db 32
+db 105
+db 115
+db 32
+db 114
+db 101
+db 112
+db 114
+db 101
+db 115
+db 101
+db 110
+db 116
+db 101
+db 100
+db 46
+db 0
+align 1
+L976 label byte
+db 32
+db 32
+db 32
+db 32
+db 32
+db 86
+db 32
+db 61
+db 32
+db 97
+db 110
+db 32
+db 111
+db 118
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 32
+db 116
+db 104
+db 114
+db 101
+db 115
+db 104
+db 111
+db 108
+db 100
+db 44
+db 32
+db 114
+db 111
+db 117
+db 103
+db 104
+db 108
+db 121
+db 46
+db 0
+align 1
+L975 label byte
+db 32
+db 32
+db 32
+db 32
+db 32
+db 69
+db 48
+db 32
+db 97
+db 110
+db 100
+db 32
+db 80
+db 115
+db 101
+db 117
+db 100
+db 111
+db 90
+db 101
+db 114
+db 111
+db 32
+db 116
+db 101
+db 108
+db 108
+db 32
+db 119
+db 104
+db 101
+db 116
+db 104
+db 101
+db 114
+db 32
+db 117
+db 110
+db 100
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 32
+db 105
+db 115
+db 32
+db 97
+db 98
+db 114
+db 117
+db 112
+db 116
+db 44
+db 32
+db 103
+db 114
+db 97
+db 100
+db 117
+db 97
+db 108
+db 44
+db 32
+db 111
+db 114
+db 32
+db 102
+db 117
+db 122
+db 122
+db 121
+db 46
+db 0
+align 1
+L974 label byte
+db 32
+db 32
+db 32
+db 32
+db 32
+db 85
+db 110
+db 100
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 84
+db 104
+db 114
+db 101
+db 115
+db 104
+db 111
+db 108
+db 100
+db 32
+db 61
+db 32
+db 97
+db 110
+db 32
+db 117
+db 110
+db 100
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 32
+db 116
+db 104
+db 114
+db 101
+db 115
+db 104
+db 111
+db 108
+db 100
+db 46
+db 0
+align 1
+L973 label byte
+db 32
+db 32
+db 32
+db 32
+db 32
+db 87
+db 104
+db 101
+db 116
+db 104
+db 101
+db 114
+db 32
+db 97
+db 32
+db 83
+db 116
+db 105
+db 99
+db 107
+db 121
+db 32
+db 66
+db 105
+db 116
+db 32
+db 117
+db 115
+db 101
+db 100
+db 32
+db 99
+db 111
+db 114
+db 114
+db 101
+db 99
+db 116
+db 108
+db 121
+db 32
+db 102
+db 111
+db 114
+db 32
+db 114
+db 111
+db 117
+db 110
+db 100
+db 105
+db 110
+db 103
+db 46
+db 0
+align 1
+L972 label byte
+db 9
+db 102
+db 111
+db 114
+db 32
+db 77
+db 117
+db 108
+db 116
+db 46
+db 44
+db 32
+db 68
+db 105
+db 118
+db 46
+db 44
+db 32
+db 65
+db 100
+db 100
+db 47
+db 83
+db 117
+db 98
+db 116
+db 46
+db 32
+db 97
+db 110
+db 100
+db 32
+db 83
+db 113
+db 114
+db 116
+db 46
+db 0
+align 1
+L971 label byte
+db 32
+db 32
+db 32
+db 32
+db 32
+db 87
+db 104
+db 101
+db 116
+db 104
+db 101
+db 114
+db 32
+db 97
+db 114
+db 105
+db 116
+db 104
+db 109
+db 101
+db 116
+db 105
+db 99
+db 32
+db 105
+db 115
+db 32
+db 99
+db 104
+db 111
+db 112
+db 112
+db 101
+db 100
+db 44
+db 32
+db 99
+db 111
+db 114
+db 114
+db 101
+db 99
+db 116
+db 108
+db 121
+db 32
+db 114
+db 111
+db 117
+db 110
+db 100
+db 101
+db 100
+db 44
+db 32
+db 111
+db 114
+db 32
+db 115
+db 111
+db 109
+db 101
+db 116
+db 104
+db 105
+db 110
+db 103
+db 32
+db 101
+db 108
+db 115
+db 101
+db 0
+align 1
+L970 label byte
+db 32
+db 32
+db 32
+db 32
+db 32
+db 65
+db 100
+db 101
+db 113
+db 117
+db 97
+db 99
+db 121
+db 32
+db 111
+db 102
+db 32
+db 103
+db 117
+db 97
+db 114
+db 100
+db 32
+db 100
+db 105
+db 103
+db 105
+db 116
+db 115
+db 32
+db 102
+db 111
+db 114
+db 32
+db 77
+db 117
+db 108
+db 116
+db 46
+db 44
+db 32
+db 68
+db 105
+db 118
+db 46
+db 32
+db 97
+db 110
+db 100
+db 32
+db 83
+db 117
+db 98
+db 116
+db 46
+db 0
+align 1
+L969 label byte
+db 32
+db 32
+db 32
+db 32
+db 32
+db 85
+db 49
+db 32
+db 61
+db 32
+db 49
+db 47
+db 82
+db 97
+db 100
+db 105
+db 120
+db 94
+db 80
+db 114
+db 101
+db 99
+db 105
+db 115
+db 105
+db 111
+db 110
+db 32
+db 61
+db 32
+db 79
+db 110
+db 101
+db 32
+db 85
+db 108
+db 112
+db 32
+db 111
+db 102
+db 32
+db 110
+db 117
+db 109
+db 98
+db 101
+db 114
+db 115
+db 32
+db 97
+db 32
+db 108
+db 105
+db 116
+db 116
+db 108
+db 101
+db 32
+db 108
+db 101
+db 115
+db 115
+db 32
+db 116
+db 104
+db 97
+db 110
+db 32
+db 49
+db 46
+db 48
+db 32
+db 46
+db 0
+align 1
+L968 label byte
+db 9
+db 40
+db 79
+db 110
+db 101
+db 85
+db 108
+db 112
+db 110
+db 105
+db 116
+db 32
+db 105
+db 110
+db 32
+db 116
+db 104
+db 101
+db 32
+db 76
+db 97
+db 115
+db 116
+db 32
+db 80
+db 108
+db 97
+db 99
+db 101
+db 41
+db 32
+db 111
+db 102
+db 32
+db 49
+db 46
+db 48
+db 48
+db 48
+db 120
+db 120
+db 120
+db 32
+db 46
+db 0
+align 1
+L967 label byte
+db 32
+db 32
+db 32
+db 32
+db 32
+db 85
+db 50
+db 32
+db 61
+db 32
+db 82
+db 97
+db 100
+db 105
+db 120
+db 47
+db 82
+db 97
+db 100
+db 105
+db 120
+db 94
+db 80
+db 114
+db 101
+db 99
+db 105
+db 115
+db 105
+db 111
+db 110
+db 32
+db 61
+db 32
+db 79
+db 110
+db 101
+db 32
+db 85
+db 108
+db 112
+db 0
+align 1
+L966 label byte
+db 32
+db 32
+db 32
+db 32
+db 32
+db 80
+db 114
+db 101
+db 99
+db 105
+db 115
+db 105
+db 111
+db 110
+db 32
+db 61
+db 32
+db 110
+db 117
+db 109
+db 98
+db 101
+db 114
+db 32
+db 111
+db 102
+db 32
+db 115
+db 105
+db 103
+db 110
+db 105
+db 102
+db 105
+db 99
+db 97
+db 110
+db 116
+db 32
+db 100
+db 105
+db 103
+db 105
+db 116
+db 115
+db 32
+db 99
+db 97
+db 114
+db 114
+db 105
+db 101
+db 100
+db 46
+db 0
+align 1
+L965 label byte
+db 32
+db 32
+db 32
+db 32
+db 32
+db 82
+db 97
+db 100
+db 105
+db 120
+db 32
+db 61
+db 32
+db 49
+db 44
+db 32
+db 50
+db 44
+db 32
+db 52
+db 44
+db 32
+db 56
+db 44
+db 32
+db 49
+db 48
+db 44
+db 32
+db 49
+db 54
+db 44
+db 32
+db 49
+db 48
+db 48
+db 44
+db 32
+db 50
+db 53
+db 54
+db 32
+db 46
+db 46
+db 46
+db 0
+align 1
+L964 label byte
+db 82
+db 117
+db 110
+db 110
+db 105
+db 110
+db 103
+db 32
+db 116
+db 104
+db 105
+db 115
+db 32
+db 112
+db 114
+db 111
+db 103
+db 114
+db 97
+db 109
+db 32
+db 115
+db 104
+db 111
+db 117
+db 108
+db 100
+db 32
+db 114
+db 101
+db 118
+db 101
+db 97
+db 108
+db 32
+db 116
+db 104
+db 101
+db 115
+db 101
+db 32
+db 99
+db 104
+db 97
+db 114
+db 97
+db 99
+db 116
+db 101
+db 114
+db 105
+db 115
+db 116
+db 105
+db 99
+db 115
+db 58
+db 0
+align 1
+L961 label byte
+db 9
+db 79
+db 116
+db 104
+db 101
+db 114
+db 32
+db 114
+db 101
+db 108
+db 101
+db 118
+db 97
+db 110
+db 116
+db 32
+db 99
+db 111
+db 109
+db 112
+db 105
+db 108
+db 101
+db 114
+db 32
+db 111
+db 112
+db 116
+db 105
+db 111
+db 110
+db 115
+db 58
+db 0
+align 1
+L960 label byte
+db 9
+db 79
+db 112
+db 116
+db 105
+db 109
+db 105
+db 122
+db 97
+db 116
+db 105
+db 111
+db 110
+db 32
+db 108
+db 101
+db 118
+db 101
+db 108
+db 58
+db 10
+db 0
+align 1
+L959 label byte
+db 9
+db 67
+db 111
+db 109
+db 112
+db 105
+db 108
+db 101
+db 114
+db 58
+db 10
+db 0
+align 1
+L958 label byte
+db 9
+db 67
+db 111
+db 109
+db 112
+db 117
+db 116
+db 101
+db 114
+db 58
+db 10
+db 0
+align 1
+L957 label byte
+db 9
+db 86
+db 101
+db 114
+db 115
+db 105
+db 111
+db 110
+db 58
+db 9
+db 49
+db 48
+db 32
+db 70
+db 101
+db 98
+db 114
+db 117
+db 97
+db 114
+db 121
+db 32
+db 49
+db 57
+db 56
+db 57
+db 59
+db 0
+align 1
+L956 label byte
+db 9
+db 80
+db 114
+db 101
+db 99
+db 105
+db 115
+db 105
+db 111
+db 110
+db 58
+db 9
+db 100
+db 111
+db 117
+db 98
+db 108
+db 101
+db 59
+db 0
+align 1
+L955 label byte
+db 73
+db 110
+db 32
+db 100
+db 111
+db 105
+db 110
+db 103
+db 32
+db 115
+db 111
+db 44
+db 32
+db 112
+db 108
+db 101
+db 97
+db 115
+db 101
+db 32
+db 105
+db 110
+db 99
+db 108
+db 117
+db 100
+db 101
+db 32
+db 116
+db 104
+db 101
+db 32
+db 102
+db 111
+db 108
+db 108
+db 111
+db 119
+db 105
+db 110
+db 103
+db 32
+db 105
+db 110
+db 102
+db 111
+db 114
+db 109
+db 97
+db 116
+db 105
+db 111
+db 110
+db 58
+db 0
+align 1
+L954 label byte
+db 9
+db 83
+db 97
+db 110
+db 32
+db 70
+db 114
+db 97
+db 110
+db 99
+db 105
+db 115
+db 99
+db 111
+db 44
+db 32
+db 67
+db 65
+db 32
+db 57
+db 52
+db 49
+db 52
+db 51
+db 45
+db 48
+db 55
+db 48
+db 52
+db 44
+db 32
+db 85
+db 83
+db 65
+db 10
+db 0
+align 1
+L953 label byte
+db 9
+db 85
+db 110
+db 105
+db 118
+db 101
+db 114
+db 115
+db 105
+db 116
+db 121
+db 32
+db 111
+db 102
+db 32
+db 67
+db 97
+db 108
+db 105
+db 102
+db 111
+db 114
+db 110
+db 105
+db 97
+db 0
+align 1
+L952 label byte
+db 9
+db 67
+db 111
+db 109
+db 112
+db 117
+db 116
+db 101
+db 114
+db 32
+db 67
+db 101
+db 110
+db 116
+db 101
+db 114
+db 32
+db 85
+db 45
+db 55
+db 54
+db 0
+align 1
+L951 label byte
+db 9
+db 82
+db 105
+db 99
+db 104
+db 97
+db 114
+db 100
+db 32
+db 75
+db 97
+db 114
+db 112
+db 105
+db 110
+db 115
+db 107
+db 105
+db 0
+align 1
+L950 label byte
+db 80
+db 108
+db 101
+db 97
+db 115
+db 101
+db 32
+db 115
+db 101
+db 110
+db 100
+db 32
+db 115
+db 117
+db 103
+db 103
+db 101
+db 115
+db 116
+db 105
+db 111
+db 110
+db 115
+db 32
+db 97
+db 110
+db 100
+db 32
+db 105
+db 110
+db 116
+db 101
+db 114
+db 101
+db 115
+db 116
+db 105
+db 110
+db 103
+db 32
+db 114
+db 101
+db 115
+db 117
+db 108
+db 116
+db 115
+db 32
+db 116
+db 111
+db 0
+align 1
+L949 label byte
+db 99
+db 111
+db 112
+db 101
+db 32
+db 119
+db 105
+db 116
+db 104
+db 32
+db 117
+db 110
+db 97
+db 110
+db 116
+db 105
+db 99
+db 105
+db 112
+db 97
+db 116
+db 101
+db 100
+db 32
+db 97
+db 110
+db 100
+db 32
+db 110
+db 101
+db 119
+db 108
+db 121
+db 32
+db 117
+db 110
+db 99
+db 111
+db 118
+db 101
+db 114
+db 101
+db 100
+db 32
+db 97
+db 114
+db 105
+db 116
+db 104
+db 109
+db 101
+db 116
+db 105
+db 99
+db 32
+db 112
+db 97
+db 116
+db 104
+db 111
+db 108
+db 111
+db 103
+db 105
+db 101
+db 115
+db 46
+db 10
+db 0
+align 1
+L948 label byte
+db 85
+db 115
+db 101
+db 114
+db 115
+db 32
+db 97
+db 114
+db 101
+db 32
+db 105
+db 110
+db 118
+db 105
+db 116
+db 101
+db 100
+db 32
+db 116
+db 111
+db 32
+db 104
+db 101
+db 108
+db 112
+db 32
+db 100
+db 101
+db 98
+db 117
+db 103
+db 32
+db 97
+db 110
+db 100
+db 32
+db 97
+db 117
+db 103
+db 109
+db 101
+db 110
+db 116
+db 32
+db 116
+db 104
+db 105
+db 115
+db 32
+db 112
+db 114
+db 111
+db 103
+db 114
+db 97
+db 109
+db 32
+db 115
+db 111
+db 32
+db 105
+db 116
+db 32
+db 119
+db 105
+db 108
+db 108
+db 0
+align 1
+L945 label byte
+db 65
+db 110
+db 115
+db 119
+db 101
+db 114
+db 32
+db 113
+db 117
+db 101
+db 115
+db 116
+db 105
+db 111
+db 110
+db 115
+db 32
+db 119
+db 105
+db 116
+db 104
+db 32
+db 89
+db 44
+db 32
+db 121
+db 44
+db 32
+db 78
+db 32
+db 111
+db 114
+db 32
+db 110
+db 32
+db 40
+db 117
+db 110
+db 108
+db 101
+db 115
+db 115
+db 32
+db 111
+db 116
+db 104
+db 101
+db 114
+db 119
+db 105
+db 115
+db 101
+db 32
+db 105
+db 110
+db 100
+db 105
+db 99
+db 97
+db 116
+db 101
+db 100
+db 41
+db 46
+db 10
+db 0
+align 1
+L944 label byte
+db 97
+db 109
+db 101
+db 110
+db 100
+db 32
+db 105
+db 116
+db 32
+db 116
+db 111
+db 32
+db 109
+db 97
+db 107
+db 101
+db 32
+db 102
+db 117
+db 114
+db 116
+db 104
+db 101
+db 114
+db 32
+db 112
+db 114
+db 111
+db 103
+db 114
+db 101
+db 115
+db 115
+db 46
+db 10
+db 0
+align 1
+L943 label byte
+db 112
+db 114
+db 111
+db 103
+db 114
+db 97
+db 109
+db 32
+db 97
+db 110
+db 121
+db 119
+db 97
+db 121
+db 32
+db 116
+db 111
+db 32
+db 115
+db 101
+db 101
+db 32
+db 104
+db 111
+db 119
+db 32
+db 109
+db 97
+db 110
+db 121
+db 32
+db 109
+db 105
+db 108
+db 101
+db 115
+db 116
+db 111
+db 110
+db 101
+db 115
+db 32
+db 105
+db 116
+db 32
+db 112
+db 97
+db 115
+db 115
+db 101
+db 115
+db 44
+db 32
+db 97
+db 110
+db 100
+db 32
+db 116
+db 104
+db 101
+db 110
+db 0
+align 1
+L942 label byte
+db 119
+db 97
+db 114
+db 110
+db 105
+db 110
+db 103
+db 46
+db 32
+db 32
+db 73
+db 102
+db 32
+db 112
+db 101
+db 114
+db 115
+db 117
+db 97
+db 115
+db 105
+db 111
+db 110
+db 32
+db 97
+db 118
+db 97
+db 105
+db 108
+db 115
+db 32
+db 110
+db 97
+db 117
+db 103
+db 104
+db 116
+db 44
+db 32
+db 100
+db 111
+db 110
+db 39
+db 116
+db 32
+db 100
+db 101
+db 115
+db 112
+db 97
+db 105
+db 114
+db 32
+db 98
+db 117
+db 116
+db 32
+db 114
+db 117
+db 110
+db 32
+db 116
+db 104
+db 105
+db 115
+db 0
+align 1
+L941 label byte
+db 116
+db 111
+db 32
+db 112
+db 101
+db 114
+db 115
+db 101
+db 118
+db 101
+db 114
+db 101
+db 32
+db 119
+db 105
+db 116
+db 104
+db 32
+db 97
+db 32
+db 115
+db 117
+db 114
+db 114
+db 111
+db 103
+db 97
+db 116
+db 101
+db 32
+db 118
+db 97
+db 108
+db 117
+db 101
+db 32
+db 97
+db 102
+db 116
+db 101
+db 114
+db 44
+db 32
+db 112
+db 101
+db 114
+db 104
+db 97
+db 112
+db 115
+db 44
+db 32
+db 100
+db 105
+db 115
+db 112
+db 108
+db 97
+db 121
+db 105
+db 110
+db 103
+db 32
+db 115
+db 111
+db 109
+db 101
+db 0
+align 1
+L940 label byte
+db 101
+db 114
+db 114
+db 111
+db 114
+db 32
+db 108
+db 105
+db 107
+db 101
+db 32
+db 79
+db 118
+db 101
+db 114
+db 47
+db 85
+db 110
+db 100
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 32
+db 111
+db 114
+db 32
+db 68
+db 105
+db 118
+db 105
+db 115
+db 105
+db 111
+db 110
+db 32
+db 98
+db 121
+db 32
+db 90
+db 101
+db 114
+db 111
+db 32
+db 111
+db 99
+db 99
+db 117
+db 114
+db 115
+db 44
+db 32
+db 98
+db 117
+db 116
+db 32
+db 114
+db 97
+db 116
+db 104
+db 101
+db 114
+db 0
+align 1
+L939 label byte
+db 116
+db 114
+db 121
+db 32
+db 116
+db 111
+db 32
+db 112
+db 101
+db 114
+db 115
+db 117
+db 97
+db 100
+db 101
+db 32
+db 116
+db 104
+db 101
+db 32
+db 99
+db 111
+db 109
+db 112
+db 117
+db 116
+db 101
+db 114
+db 32
+db 78
+db 79
+db 84
+db 32
+db 116
+db 111
+db 32
+db 116
+db 101
+db 114
+db 109
+db 105
+db 110
+db 97
+db 116
+db 101
+db 32
+db 101
+db 120
+db 101
+db 99
+db 117
+db 116
+db 105
+db 111
+db 110
+db 32
+db 119
+db 104
+db 101
+db 110
+db 32
+db 97
+db 110
+db 0
+align 1
+L938 label byte
+db 32
+db 32
+db 32
+db 32
+db 96
+db 69
+db 78
+db 68
+db 32
+db 79
+db 70
+db 32
+db 84
+db 69
+db 83
+db 84
+db 39
+db 44
+db 10
+db 0
+align 1
+L937 label byte
+db 76
+db 101
+db 115
+db 116
+db 32
+db 116
+db 104
+db 105
+db 115
+db 32
+db 112
+db 114
+db 111
+db 103
+db 114
+db 97
+db 109
+db 32
+db 115
+db 116
+db 111
+db 112
+db 32
+db 112
+db 114
+db 101
+db 109
+db 97
+db 116
+db 117
+db 114
+db 101
+db 108
+db 121
+db 44
+db 32
+db 105
+db 46
+db 101
+db 46
+db 32
+db 98
+db 101
+db 102
+db 111
+db 114
+db 101
+db 32
+db 100
+db 105
+db 115
+db 112
+db 108
+db 97
+db 121
+db 105
+db 110
+db 103
+db 10
+db 0
+align 1
+L934 label byte
+db 37
+db 115
+db 10
+db 0
+align 1
+L929 label byte
+db 32
+db 32
+db 32
+db 80
+db 76
+db 69
+db 65
+db 83
+db 69
+db 32
+db 78
+db 79
+db 84
+db 73
+db 70
+db 89
+db 32
+db 75
+db 65
+db 82
+db 80
+db 73
+db 78
+db 75
+db 83
+db 73
+db 33
+db 10
+db 0
+align 1
+L928 label byte
+db 37
+db 115
+db 32
+db 116
+db 101
+db 115
+db 116
+db 32
+db 97
+db 112
+db 112
+db 101
+db 97
+db 114
+db 115
+db 32
+db 116
+db 111
+db 32
+db 98
+db 101
+db 32
+db 105
+db 110
+db 99
+db 111
+db 110
+db 115
+db 105
+db 115
+db 116
+db 101
+db 110
+db 116
+db 46
+db 46
+db 46
+db 10
+db 0
+align 1
+L926 label byte
+db 9
+db 100
+db 105
+db 102
+db 102
+db 101
+db 114
+db 115
+db 32
+db 102
+db 114
+db 111
+db 109
+db 32
+db 90
+db 32
+db 42
+db 32
+db 49
+db 32
+db 61
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 10
+db 0
+align 1
+L925 label byte
+db 9
+db 67
+db 111
+db 109
+db 112
+db 97
+db 114
+db 105
+db 115
+db 111
+db 110
+db 32
+db 97
+db 108
+db 108
+db 101
+db 103
+db 101
+db 115
+db 32
+db 116
+db 104
+db 97
+db 116
+db 32
+db 49
+db 32
+db 42
+db 32
+db 90
+db 32
+db 61
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 10
+db 0
+align 1
+L924 label byte
+db 77
+db 117
+db 108
+db 116
+db 105
+db 112
+db 108
+db 105
+db 99
+db 97
+db 116
+db 105
+db 111
+db 110
+db 32
+db 100
+db 111
+db 101
+db 115
+db 32
+db 110
+db 111
+db 116
+db 32
+db 99
+db 111
+db 109
+db 109
+db 117
+db 116
+db 101
+db 33
+db 10
+db 0
+align 1
+L919 label byte
+db 90
+db 32
+db 47
+db 32
+db 49
+db 32
+db 61
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 10
+db 0
+align 1
+L916 label byte
+db 49
+db 32
+db 42
+db 32
+db 90
+db 32
+db 61
+db 61
+db 32
+db 37
+db 103
+db 10
+db 0
+align 1
+L913 label byte
+db 90
+db 32
+db 42
+db 32
+db 49
+db 32
+db 61
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 32
+db 0
+align 1
+L910 label byte
+db 37
+db 46
+db 49
+db 55
+db 101
+db 10
+db 9
+db 99
+db 111
+db 109
+db 112
+db 97
+db 114
+db 101
+db 115
+db 32
+db 100
+db 105
+db 102
+db 102
+db 101
+db 114
+db 101
+db 110
+db 116
+db 32
+db 102
+db 114
+db 111
+db 109
+db 32
+db 32
+db 0
+align 1
+L909 label byte
+db 87
+db 104
+db 97
+db 116
+db 32
+db 112
+db 114
+db 105
+db 110
+db 116
+db 115
+db 32
+db 97
+db 115
+db 32
+db 90
+db 32
+db 61
+db 32
+db 0
+align 1
+L904 label byte
+db 84
+db 104
+db 105
+db 115
+db 32
+db 105
+db 115
+db 32
+db 97
+db 32
+db 68
+db 69
+db 70
+db 69
+db 67
+db 84
+db 33
+db 10
+db 0
+align 1
+L901 label byte
+db 84
+db 104
+db 105
+db 115
+db 32
+db 105
+db 115
+db 32
+db 97
+db 32
+db 86
+db 69
+db 82
+db 89
+db 32
+db 83
+db 69
+db 82
+db 73
+db 79
+db 85
+db 83
+db 32
+db 68
+db 69
+db 70
+db 69
+db 67
+db 84
+db 33
+db 10
+db 0
+align 1
+L895 label byte
+db 32
+db 104
+db 97
+db 115
+db 32
+db 78
+db 79
+db 84
+db 32
+db 106
+db 117
+db 115
+db 116
+db 32
+db 98
+db 101
+db 101
+db 110
+db 32
+db 115
+db 105
+db 103
+db 110
+db 97
+db 108
+db 101
+db 100
+db 46
+db 10
+db 0
+align 1
+L894 label byte
+db 84
+db 104
+db 105
+db 115
+db 32
+db 105
+db 115
+db 32
+db 79
+db 46
+db 75
+db 46
+db 44
+db 32
+db 112
+db 114
+db 111
+db 118
+db 105
+db 100
+db 101
+db 100
+db 32
+db 79
+db 118
+db 101
+db 114
+db 47
+db 85
+db 110
+db 100
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 0
+align 1
+L891 label byte
+db 87
+db 104
+db 97
+db 116
+db 32
+db 116
+db 104
+db 101
+db 32
+db 109
+db 97
+db 99
+db 104
+db 105
+db 110
+db 101
+db 32
+db 103
+db 101
+db 116
+db 115
+db 32
+db 102
+db 111
+db 114
+db 32
+db 40
+db 90
+db 32
+db 43
+db 32
+db 90
+db 41
+db 32
+db 47
+db 32
+db 90
+db 32
+db 105
+db 115
+db 32
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 32
+db 46
+db 10
+db 0
+align 1
+L887 label byte
+db 40
+db 90
+db 32
+db 43
+db 32
+db 90
+db 41
+db 32
+db 47
+db 32
+db 90
+db 32
+db 115
+db 104
+db 111
+db 117
+db 108
+db 100
+db 32
+db 98
+db 101
+db 32
+db 115
+db 97
+db 102
+db 101
+db 46
+db 10
+db 0
+align 1
+L886 label byte
+db 83
+db 105
+db 110
+db 99
+db 101
+db 32
+db 99
+db 111
+db 109
+db 112
+db 97
+db 114
+db 105
+db 115
+db 111
+db 110
+db 32
+db 100
+db 101
+db 110
+db 105
+db 101
+db 115
+db 32
+db 90
+db 32
+db 61
+db 32
+db 48
+db 44
+db 32
+db 101
+db 118
+db 97
+db 108
+db 117
+db 97
+db 116
+db 105
+db 110
+db 103
+db 32
+db 0
+align 1
+L882 label byte
+db 83
+db 105
+db 109
+db 105
+db 108
+db 97
+db 114
+db 32
+db 100
+db 105
+db 115
+db 99
+db 114
+db 101
+db 112
+db 97
+db 110
+db 99
+db 105
+db 101
+db 115
+db 32
+db 104
+db 97
+db 118
+db 101
+db 32
+db 111
+db 99
+db 99
+db 117
+db 114
+db 114
+db 101
+db 100
+db 32
+db 37
+db 100
+db 32
+db 116
+db 105
+db 109
+db 101
+db 115
+db 46
+db 10
+db 0
+align 1
+L872 label byte
+db 9
+db 9
+db 116
+db 104
+db 101
+db 121
+db 32
+db 100
+db 105
+db 102
+db 102
+db 101
+db 114
+db 32
+db 98
+db 121
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 32
+db 46
+db 10
+db 0
+align 1
+L871 label byte
+db 9
+db 119
+db 104
+db 105
+db 99
+db 104
+db 32
+db 99
+db 111
+db 109
+db 112
+db 97
+db 114
+db 101
+db 100
+db 32
+db 117
+db 110
+db 101
+db 113
+db 117
+db 97
+db 108
+db 32
+db 116
+db 111
+db 32
+db 99
+db 111
+db 114
+db 114
+db 101
+db 99
+db 116
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 32
+db 59
+db 10
+db 0
+align 1
+L870 label byte
+db 9
+db 121
+db 105
+db 101
+db 108
+db 100
+db 101
+db 100
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 59
+db 10
+db 0
+align 1
+L869 label byte
+db 9
+db 40
+db 37
+db 46
+db 49
+db 55
+db 101
+db 41
+db 32
+db 94
+db 32
+db 40
+db 37
+db 46
+db 49
+db 55
+db 101
+db 41
+db 10
+db 0
+align 1
+L868 label byte
+db 99
+db 111
+db 109
+db 112
+db 117
+db 116
+db 105
+db 110
+db 103
+db 10
+db 0
+align 1
+L867 label byte
+db 87
+db 65
+db 82
+db 78
+db 73
+db 78
+db 71
+db 58
+db 32
+db 32
+db 99
+db 111
+db 109
+db 112
+db 117
+db 116
+db 105
+db 110
+db 103
+db 10
+db 0
+align 1
+L849 label byte
+db 9
+db 105
+db 110
+db 115
+db 116
+db 101
+db 97
+db 100
+db 32
+db 111
+db 102
+db 32
+db 99
+db 111
+db 114
+db 114
+db 101
+db 99
+db 116
+db 32
+db 118
+db 97
+db 108
+db 117
+db 101
+db 32
+db 48
+db 32
+db 46
+db 10
+db 0
+align 1
+L848 label byte
+db 115
+db 113
+db 114
+db 116
+db 40
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 41
+db 32
+db 45
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 32
+db 32
+db 61
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 10
+db 0
+align 4
+L840 label byte
+dd 088e368f1H
+dd 03ed4f8b5H
+align 1
+L838 label byte
+db 37
+db 115
+db 58
+db 32
+db 32
+db 37
+db 115
+db 0
+align 1
+L837 label byte
+db 70
+db 76
+db 65
+db 87
+db 0
+align 1
+L836 label byte
+db 68
+db 69
+db 70
+db 69
+db 67
+db 84
+db 0
+align 1
+L835 label byte
+db 83
+db 69
+db 82
+db 73
+db 79
+db 85
+db 83
+db 32
+db 68
+db 69
+db 70
+db 69
+db 67
+db 84
+db 0
+align 1
+L834 label byte
+db 70
+db 65
+db 73
+db 76
+db 85
+db 82
+db 69
+db 0
+align 1
+L828 label byte
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 80
+db 97
+db 103
+db 101
+db 58
+db 32
+db 37
+db 100
+db 10
+db 10
+db 0
+align 1
+L827 label byte
+db 10
+db 68
+db 105
+db 97
+db 103
+db 110
+db 111
+db 115
+db 105
+db 115
+db 32
+db 114
+db 101
+db 115
+db 117
+db 109
+db 101
+db 115
+db 32
+db 97
+db 102
+db 116
+db 101
+db 114
+db 32
+db 109
+db 105
+db 108
+db 101
+db 115
+db 116
+db 111
+db 110
+db 101
+db 32
+db 78
+db 117
+db 109
+db 98
+db 101
+db 114
+db 32
+db 37
+db 100
+db 0
+align 4
+L825 label byte
+dd 00H
+dd 0bff00000H
+align 1
+L820 label byte
+db 69
+db 78
+db 68
+db 32
+db 79
+db 70
+db 32
+db 84
+db 69
+db 83
+db 84
+db 46
+db 10
+db 0
+align 1
+L819 label byte
+db 10
+db 65
+db 32
+db 116
+db 111
+db 116
+db 97
+db 108
+db 32
+db 111
+db 102
+db 32
+db 37
+db 100
+db 32
+db 102
+db 108
+db 111
+db 97
+db 116
+db 105
+db 110
+db 103
+db 32
+db 112
+db 111
+db 105
+db 110
+db 116
+db 32
+db 101
+db 120
+db 99
+db 101
+db 112
+db 116
+db 105
+db 111
+db 110
+db 115
+db 32
+db 119
+db 101
+db 114
+db 101
+db 32
+db 114
+db 101
+db 103
+db 105
+db 115
+db 116
+db 101
+db 114
+db 101
+db 100
+db 46
+db 10
+db 0
+align 1
+L816 label byte
+db 84
+db 104
+db 101
+db 32
+db 97
+db 114
+db 105
+db 116
+db 104
+db 109
+db 101
+db 116
+db 105
+db 99
+db 32
+db 100
+db 105
+db 97
+db 103
+db 110
+db 111
+db 115
+db 101
+db 100
+db 32
+db 97
+db 112
+db 112
+db 101
+db 97
+db 114
+db 115
+db 32
+db 116
+db 111
+db 32
+db 98
+db 101
+db 32
+db 69
+db 120
+db 99
+db 101
+db 108
+db 108
+db 101
+db 110
+db 116
+db 33
+db 10
+db 0
+align 1
+L815 label byte
+db 32
+db 100
+db 117
+db 114
+db 105
+db 110
+db 103
+db 32
+db 71
+db 114
+db 97
+db 100
+db 117
+db 97
+db 108
+db 32
+db 85
+db 110
+db 100
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 46
+db 10
+db 0
+align 1
+L814 label byte
+db 44
+db 10
+db 101
+db 120
+db 99
+db 101
+db 112
+db 116
+db 32
+db 102
+db 111
+db 114
+db 32
+db 112
+db 111
+db 115
+db 115
+db 105
+db 98
+db 108
+db 121
+db 32
+db 68
+db 111
+db 117
+db 98
+db 108
+db 101
+db 32
+db 82
+db 111
+db 117
+db 110
+db 100
+db 105
+db 110
+db 103
+db 0
+align 1
+L813 label byte
+db 46
+db 10
+db 0
+align 1
+L810 label byte
+db 56
+db 53
+db 52
+db 0
+align 1
+L809 label byte
+db 55
+db 53
+db 52
+db 0
+align 1
+L806 label byte
+db 116
+db 104
+db 101
+db 32
+db 112
+db 114
+db 111
+db 112
+db 111
+db 115
+db 101
+db 100
+db 32
+db 73
+db 69
+db 69
+db 69
+db 32
+db 115
+db 116
+db 97
+db 110
+db 100
+db 97
+db 114
+db 100
+db 32
+db 80
+db 0
+align 1
+L805 label byte
+db 82
+db 111
+db 117
+db 110
+db 100
+db 105
+db 110
+db 103
+db 32
+db 97
+db 112
+db 112
+db 101
+db 97
+db 114
+db 115
+db 32
+db 116
+db 111
+db 32
+db 99
+db 111
+db 110
+db 102
+db 111
+db 114
+db 109
+db 32
+db 116
+db 111
+db 32
+db 0
+align 1
+L802 label byte
+db 84
+db 104
+db 101
+db 32
+db 97
+db 114
+db 105
+db 116
+db 104
+db 109
+db 101
+db 116
+db 105
+db 99
+db 32
+db 100
+db 105
+db 97
+db 103
+db 110
+db 111
+db 115
+db 101
+db 100
+db 32
+db 115
+db 101
+db 101
+db 109
+db 115
+db 32
+db 83
+db 97
+db 116
+db 105
+db 115
+db 102
+db 97
+db 99
+db 116
+db 111
+db 114
+db 121
+db 46
+db 10
+db 0
+align 1
+L796 label byte
+db 78
+db 111
+db 32
+db 102
+db 97
+db 105
+db 108
+db 117
+db 114
+db 101
+db 115
+db 44
+db 32
+db 100
+db 101
+db 102
+db 101
+db 99
+db 116
+db 115
+db 32
+db 110
+db 111
+db 114
+db 32
+db 102
+db 108
+db 97
+db 119
+db 115
+db 32
+db 104
+db 97
+db 118
+db 101
+db 32
+db 98
+db 101
+db 101
+db 110
+db 32
+db 100
+db 105
+db 115
+db 99
+db 111
+db 118
+db 101
+db 114
+db 101
+db 100
+db 46
+db 10
+db 0
+align 1
+L795 label byte
+db 32
+db 112
+db 114
+db 111
+db 103
+db 114
+db 97
+db 109
+db 39
+db 115
+db 32
+db 115
+db 117
+db 98
+db 115
+db 101
+db 113
+db 117
+db 101
+db 110
+db 116
+db 32
+db 100
+db 105
+db 97
+db 103
+db 110
+db 111
+db 115
+db 101
+db 115
+db 46
+db 10
+db 0
+align 1
+L794 label byte
+db 80
+db 111
+db 116
+db 101
+db 110
+db 116
+db 105
+db 97
+db 108
+db 108
+db 121
+db 32
+db 102
+db 97
+db 116
+db 97
+db 108
+db 32
+db 70
+db 65
+db 73
+db 76
+db 85
+db 82
+db 69
+db 32
+db 109
+db 97
+db 121
+db 32
+db 104
+db 97
+db 118
+db 101
+db 32
+db 115
+db 112
+db 111
+db 105
+db 108
+db 101
+db 100
+db 32
+db 116
+db 104
+db 105
+db 115
+db 0
+align 1
+L791 label byte
+db 117
+db 110
+db 97
+db 99
+db 99
+db 101
+db 112
+db 116
+db 97
+db 98
+db 108
+db 101
+db 32
+db 83
+db 101
+db 114
+db 105
+db 111
+db 117
+db 115
+db 32
+db 68
+db 101
+db 102
+db 101
+db 99
+db 116
+db 115
+db 46
+db 10
+db 0
+align 1
+L790 label byte
+db 84
+db 104
+db 101
+db 32
+db 97
+db 114
+db 105
+db 116
+db 104
+db 109
+db 101
+db 116
+db 105
+db 99
+db 32
+db 100
+db 105
+db 97
+db 103
+db 110
+db 111
+db 115
+db 101
+db 100
+db 32
+db 104
+db 97
+db 115
+db 32
+db 0
+align 1
+L786 label byte
+db 100
+db 101
+db 115
+db 112
+db 105
+db 116
+db 101
+db 32
+db 105
+db 110
+db 99
+db 111
+db 110
+db 118
+db 101
+db 110
+db 105
+db 101
+db 110
+db 116
+db 32
+db 68
+db 101
+db 102
+db 101
+db 99
+db 116
+db 115
+db 46
+db 10
+db 0
+align 1
+L785 label byte
+db 84
+db 104
+db 101
+db 32
+db 97
+db 114
+db 105
+db 116
+db 104
+db 109
+db 101
+db 116
+db 105
+db 99
+db 32
+db 100
+db 105
+db 97
+db 103
+db 110
+db 111
+db 115
+db 101
+db 100
+db 32
+db 109
+db 97
+db 121
+db 32
+db 98
+db 101
+db 32
+db 65
+db 99
+db 99
+db 101
+db 112
+db 116
+db 97
+db 98
+db 108
+db 101
+db 10
+db 0
+align 1
+L780 label byte
+db 83
+db 97
+db 116
+db 105
+db 115
+db 102
+db 97
+db 99
+db 116
+db 111
+db 114
+db 121
+db 32
+db 116
+db 104
+db 111
+db 117
+db 103
+db 104
+db 32
+db 102
+db 108
+db 97
+db 119
+db 101
+db 100
+db 46
+db 10
+db 0
+align 1
+L779 label byte
+db 84
+db 104
+db 101
+db 32
+db 97
+db 114
+db 105
+db 116
+db 104
+db 109
+db 101
+db 116
+db 105
+db 99
+db 32
+db 100
+db 105
+db 97
+db 103
+db 110
+db 111
+db 115
+db 101
+db 100
+db 32
+db 115
+db 101
+db 101
+db 109
+db 115
+db 32
+db 0
+align 1
+L768 label byte
+db 84
+db 104
+db 101
+db 32
+db 110
+db 117
+db 109
+db 98
+db 101
+db 114
+db 32
+db 111
+db 102
+db 32
+db 32
+db 37
+db 45
+db 50
+db 57
+db 115
+db 32
+db 37
+db 100
+db 46
+db 10
+db 0
+align 1
+L761 label byte
+db 70
+db 76
+db 65
+db 87
+db 115
+db 32
+db 32
+db 100
+db 105
+db 115
+db 99
+db 111
+db 118
+db 101
+db 114
+db 101
+db 100
+db 32
+db 61
+db 0
+align 1
+L760 label byte
+db 68
+db 69
+db 70
+db 69
+db 67
+db 84
+db 115
+db 32
+db 32
+db 100
+db 105
+db 115
+db 99
+db 111
+db 118
+db 101
+db 114
+db 101
+db 100
+db 32
+db 61
+db 0
+align 1
+L759 label byte
+db 83
+db 69
+db 82
+db 73
+db 79
+db 85
+db 83
+db 32
+db 68
+db 69
+db 70
+db 69
+db 67
+db 84
+db 115
+db 32
+db 32
+db 100
+db 105
+db 115
+db 99
+db 111
+db 118
+db 101
+db 114
+db 101
+db 100
+db 32
+db 61
+db 0
+align 1
+L758 label byte
+db 70
+db 65
+db 73
+db 76
+db 85
+db 82
+db 69
+db 115
+db 32
+db 32
+db 101
+db 110
+db 99
+db 111
+db 117
+db 110
+db 116
+db 101
+db 114
+db 101
+db 100
+db 32
+db 61
+db 0
+align 1
+L754 label byte
+db 10
+db 32
+db 32
+db 32
+db 32
+db 84
+db 114
+db 121
+db 105
+db 110
+db 103
+db 32
+db 116
+db 111
+db 32
+db 99
+db 111
+db 109
+db 112
+db 117
+db 116
+db 101
+db 32
+db 48
+db 32
+db 47
+db 32
+db 48
+db 32
+db 112
+db 114
+db 111
+db 100
+db 117
+db 99
+db 101
+db 115
+db 32
+db 46
+db 46
+db 46
+db 0
+align 1
+L753 label byte
+db 32
+db 32
+db 37
+db 46
+db 55
+db 101
+db 32
+db 46
+db 10
+db 0
+align 1
+L750 label byte
+db 32
+db 32
+db 32
+db 32
+db 84
+db 114
+db 121
+db 105
+db 110
+db 103
+db 32
+db 116
+db 111
+db 32
+db 99
+db 111
+db 109
+db 112
+db 117
+db 116
+db 101
+db 32
+db 49
+db 32
+db 47
+db 32
+db 48
+db 32
+db 112
+db 114
+db 111
+db 100
+db 117
+db 99
+db 101
+db 115
+db 32
+db 46
+db 46
+db 46
+db 0
+align 1
+L749 label byte
+db 87
+db 104
+db 97
+db 116
+db 32
+db 109
+db 101
+db 115
+db 115
+db 97
+db 103
+db 101
+db 32
+db 97
+db 110
+db 100
+db 47
+db 111
+db 114
+db 32
+db 118
+db 97
+db 108
+db 117
+db 101
+db 115
+db 32
+db 100
+db 111
+db 101
+db 115
+db 32
+db 68
+db 105
+db 118
+db 105
+db 115
+db 105
+db 111
+db 110
+db 32
+db 98
+db 121
+db 32
+db 90
+db 101
+db 114
+db 111
+db 32
+db 112
+db 114
+db 111
+db 100
+db 117
+db 99
+db 101
+db 63
+db 10
+db 0
+align 1
+L748 label byte
+db 32
+db 32
+db 105
+db 110
+db 115
+db 116
+db 101
+db 97
+db 100
+db 44
+db 32
+db 88
+db 32
+db 47
+db 32
+db 88
+db 32
+db 45
+db 32
+db 49
+db 47
+db 50
+db 32
+db 45
+db 32
+db 49
+db 47
+db 50
+db 32
+db 61
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 32
+db 46
+db 10
+db 0
+align 1
+L747 label byte
+db 32
+db 32
+db 88
+db 32
+db 47
+db 32
+db 88
+db 32
+db 100
+db 105
+db 102
+db 102
+db 101
+db 114
+db 115
+db 32
+db 102
+db 114
+db 111
+db 109
+db 32
+db 49
+db 32
+db 119
+db 104
+db 101
+db 110
+db 32
+db 88
+db 32
+db 61
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 10
+db 0
+align 1
+L742 label byte
+db 32
+db 32
+db 88
+db 32
+db 47
+db 32
+db 88
+db 32
+db 32
+db 116
+db 114
+db 97
+db 112
+db 115
+db 32
+db 119
+db 104
+db 101
+db 110
+db 32
+db 88
+db 32
+db 61
+db 32
+db 37
+db 103
+db 10
+db 0
+align 1
+L727 label byte
+db 105
+db 115
+db 32
+db 116
+db 111
+db 111
+db 32
+db 102
+db 97
+db 114
+db 32
+db 102
+db 114
+db 111
+db 109
+db 32
+db 49
+db 46
+db 10
+db 0
+align 1
+L726 label byte
+db 32
+db 117
+db 110
+db 98
+db 97
+db 108
+db 97
+db 110
+db 99
+db 101
+db 100
+db 32
+db 114
+db 97
+db 110
+db 103
+db 101
+db 59
+db 32
+db 85
+db 102
+db 84
+db 104
+db 111
+db 108
+db 100
+db 32
+db 42
+db 32
+db 86
+db 32
+db 61
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 10
+db 9
+db 37
+db 115
+db 10
+db 0
+align 1
+L725 label byte
+db 66
+db 97
+db 100
+db 108
+db 121
+db 0
+align 1
+L718 label byte
+db 32
+db 105
+db 115
+db 32
+db 116
+db 111
+db 111
+db 32
+db 102
+db 97
+db 114
+db 32
+db 102
+db 114
+db 111
+db 109
+db 32
+db 115
+db 113
+db 114
+db 116
+db 40
+db 90
+db 41
+db 32
+db 94
+db 32
+db 50
+db 32
+db 40
+db 37
+db 46
+db 49
+db 55
+db 101
+db 41
+db 32
+db 46
+db 10
+db 0
+align 1
+L717 label byte
+db 67
+db 111
+db 109
+db 112
+db 97
+db 114
+db 105
+db 115
+db 111
+db 110
+db 32
+db 97
+db 108
+db 108
+db 101
+db 103
+db 101
+db 115
+db 32
+db 116
+db 104
+db 97
+db 116
+db 32
+db 90
+db 32
+db 61
+db 32
+db 37
+db 49
+db 55
+db 101
+db 10
+db 0
+align 1
+L705 label byte
+db 32
+db 105
+db 115
+db 32
+db 116
+db 111
+db 111
+db 32
+db 102
+db 97
+db 114
+db 32
+db 102
+db 114
+db 111
+db 109
+db 32
+db 115
+db 113
+db 114
+db 116
+db 40
+db 90
+db 41
+db 32
+db 94
+db 32
+db 50
+db 32
+db 61
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 32
+db 46
+db 10
+db 0
+align 1
+L704 label byte
+db 67
+db 111
+db 109
+db 112
+db 97
+db 114
+db 105
+db 115
+db 111
+db 110
+db 32
+db 97
+db 108
+db 108
+db 101
+db 103
+db 101
+db 115
+db 32
+db 116
+db 104
+db 97
+db 116
+db 32
+db 119
+db 104
+db 97
+db 116
+db 32
+db 112
+db 114
+db 105
+db 110
+db 116
+db 115
+db 32
+db 97
+db 115
+db 32
+db 90
+db 32
+db 61
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 10
+db 0
+align 1
+L687 label byte
+db 43
+db 45
+db 37
+db 103
+db 44
+db 32
+db 43
+db 45
+db 37
+db 103
+db 10
+db 97
+db 110
+db 100
+db 32
+db 43
+db 45
+db 37
+db 103
+db 32
+db 97
+db 114
+db 101
+db 32
+db 99
+db 111
+db 110
+db 102
+db 117
+db 115
+db 101
+db 100
+db 32
+db 98
+db 121
+db 32
+db 79
+db 118
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 46
+db 0
+align 1
+L686 label byte
+db 67
+db 111
+db 109
+db 112
+db 97
+db 114
+db 105
+db 115
+db 111
+db 110
+db 115
+db 32
+db 105
+db 110
+db 118
+db 111
+db 108
+db 118
+db 105
+db 110
+db 103
+db 32
+db 0
+align 1
+L680 label byte
+db 97
+db 98
+db 111
+db 118
+db 101
+db 32
+db 105
+db 115
+db 32
+db 97
+db 32
+db 68
+db 69
+db 70
+db 69
+db 67
+db 84
+db 46
+db 10
+db 0
+align 1
+L679 label byte
+db 65
+db 110
+db 121
+db 32
+db 111
+db 118
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 32
+db 115
+db 105
+db 103
+db 110
+db 97
+db 108
+db 32
+db 115
+db 101
+db 112
+db 97
+db 114
+db 97
+db 116
+db 105
+db 110
+db 103
+db 32
+db 116
+db 104
+db 105
+db 115
+db 32
+db 42
+db 32
+db 102
+db 114
+db 111
+db 109
+db 32
+db 116
+db 104
+db 101
+db 32
+db 111
+db 110
+db 101
+db 10
+db 0
+align 1
+L678 label byte
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 32
+db 110
+db 111
+db 114
+db 32
+db 102
+db 111
+db 114
+db 32
+db 86
+db 32
+db 47
+db 32
+db 49
+db 32
+db 61
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 32
+db 46
+db 10
+db 0
+align 1
+L677 label byte
+db 78
+db 111
+db 32
+db 79
+db 118
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 32
+db 115
+db 104
+db 111
+db 117
+db 108
+db 100
+db 32
+db 98
+db 101
+db 32
+db 115
+db 105
+db 103
+db 110
+db 97
+db 108
+db 101
+db 100
+db 32
+db 102
+db 111
+db 114
+db 32
+db 86
+db 32
+db 42
+db 32
+db 49
+db 32
+db 61
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 10
+db 0
+align 1
+L676 label byte
+db 84
+db 104
+db 101
+db 114
+db 101
+db 32
+db 105
+db 115
+db 32
+db 110
+db 111
+db 32
+db 115
+db 97
+db 116
+db 117
+db 114
+db 97
+db 116
+db 105
+db 111
+db 110
+db 32
+db 118
+db 97
+db 108
+db 117
+db 101
+db 32
+db 98
+db 101
+db 99
+db 97
+db 117
+db 115
+db 101
+db 32
+db 116
+db 104
+db 101
+db 32
+db 115
+db 121
+db 115
+db 116
+db 101
+db 109
+db 32
+db 116
+db 114
+db 97
+db 112
+db 115
+db 32
+db 111
+db 110
+db 32
+db 111
+db 118
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 46
+db 10
+db 0
+align 1
+L675 label byte
+db 79
+db 118
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 32
+db 115
+db 97
+db 116
+db 117
+db 114
+db 97
+db 116
+db 101
+db 115
+db 32
+db 97
+db 116
+db 32
+db 86
+db 48
+db 32
+db 61
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 32
+db 46
+db 10
+db 0
+align 1
+L672 label byte
+db 79
+db 118
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 32
+db 116
+db 104
+db 114
+db 101
+db 115
+db 104
+db 111
+db 108
+db 100
+db 32
+db 105
+db 115
+db 32
+db 86
+db 32
+db 32
+db 61
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 32
+db 46
+db 10
+db 0
+align 1
+L663 label byte
+db 111
+db 118
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 32
+db 112
+db 97
+db 115
+db 116
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 10
+db 9
+db 115
+db 104
+db 114
+db 105
+db 110
+db 107
+db 115
+db 32
+db 116
+db 111
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 32
+db 46
+db 10
+db 0
+align 1
+L660 label byte
+db 45
+db 40
+db 45
+db 89
+db 41
+db 32
+db 100
+db 105
+db 102
+db 102
+db 101
+db 114
+db 115
+db 32
+db 102
+db 114
+db 111
+db 109
+db 32
+db 89
+db 46
+db 10
+db 0
+align 1
+L659 label byte
+db 102
+db 105
+db 110
+db 100
+db 115
+db 32
+db 97
+db 32
+db 0
+align 1
+L658 label byte
+db 83
+db 101
+db 101
+db 109
+db 115
+db 32
+db 79
+db 46
+db 75
+db 46
+db 10
+db 0
+align 1
+L655 label byte
+db 84
+db 114
+db 121
+db 105
+db 110
+db 103
+db 32
+db 105
+db 116
+db 32
+db 111
+db 110
+db 32
+db 89
+db 32
+db 61
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 32
+db 46
+db 10
+db 0
+align 1
+L654 label byte
+db 67
+db 97
+db 110
+db 32
+db 96
+db 90
+db 32
+db 61
+db 32
+db 45
+db 89
+db 39
+db 32
+db 111
+db 118
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 63
+db 10
+db 0
+align 1
+L647 label byte
+db 84
+db 104
+db 105
+db 115
+db 32
+db 109
+db 97
+db 121
+db 32
+db 103
+db 101
+db 110
+db 101
+db 114
+db 97
+db 116
+db 101
+db 32
+db 97
+db 110
+db 32
+db 101
+db 114
+db 114
+db 111
+db 114
+db 46
+db 10
+db 0
+align 1
+L646 label byte
+db 83
+db 101
+db 97
+db 114
+db 99
+db 104
+db 105
+db 110
+db 103
+db 32
+db 102
+db 111
+db 114
+db 32
+db 79
+db 118
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 32
+db 116
+db 104
+db 114
+db 101
+db 115
+db 104
+db 111
+db 108
+db 100
+db 58
+db 10
+db 0
+align 1
+L645 label byte
+db 32
+db 46
+db 46
+db 46
+db 32
+db 110
+db 111
+db 32
+db 100
+db 105
+db 115
+db 99
+db 114
+db 101
+db 112
+db 97
+db 110
+db 99
+db 105
+db 101
+db 115
+db 32
+db 102
+db 111
+db 117
+db 110
+db 100
+db 46
+db 10
+db 0
+align 1
+L637 label byte
+db 84
+db 101
+db 115
+db 116
+db 105
+db 110
+db 103
+db 32
+db 112
+db 111
+db 119
+db 101
+db 114
+db 115
+db 32
+db 90
+db 94
+db 81
+db 32
+db 97
+db 116
+db 32
+db 102
+db 111
+db 117
+db 114
+db 32
+db 110
+db 101
+db 97
+db 114
+db 108
+db 121
+db 32
+db 101
+db 120
+db 116
+db 114
+db 101
+db 109
+db 101
+db 32
+db 118
+db 97
+db 108
+db 117
+db 101
+db 115
+db 46
+db 10
+db 0
+align 1
+L636 label byte
+db 65
+db 99
+db 99
+db 117
+db 114
+db 97
+db 99
+db 121
+db 32
+db 115
+db 101
+db 101
+db 109
+db 115
+db 32
+db 97
+db 100
+db 101
+db 113
+db 117
+db 97
+db 116
+db 101
+db 46
+db 10
+db 0
+align 1
+L629 label byte
+db 9
+db 99
+db 97
+db 108
+db 99
+db 117
+db 108
+db 97
+db 116
+db 105
+db 111
+db 110
+db 115
+db 32
+db 105
+db 110
+db 118
+db 111
+db 108
+db 118
+db 105
+db 110
+db 103
+db 32
+db 116
+db 105
+db 110
+db 121
+db 32
+db 105
+db 110
+db 116
+db 101
+db 114
+db 101
+db 115
+db 116
+db 32
+db 114
+db 97
+db 116
+db 101
+db 115
+db 46
+db 10
+db 0
+align 1
+L628 label byte
+db 9
+db 84
+db 104
+db 105
+db 115
+db 32
+db 109
+db 117
+db 99
+db 104
+db 32
+db 101
+db 114
+db 114
+db 111
+db 114
+db 32
+db 109
+db 97
+db 121
+db 32
+db 115
+db 112
+db 111
+db 105
+db 108
+db 32
+db 102
+db 105
+db 110
+db 97
+db 110
+db 99
+db 105
+db 97
+db 108
+db 10
+db 0
+align 1
+L627 label byte
+db 9
+db 100
+db 105
+db 102
+db 102
+db 101
+db 114
+db 115
+db 32
+db 102
+db 114
+db 111
+db 109
+db 32
+db 99
+db 111
+db 114
+db 114
+db 101
+db 99
+db 116
+db 32
+db 118
+db 97
+db 108
+db 117
+db 101
+db 32
+db 98
+db 121
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 32
+db 46
+db 10
+db 0
+align 1
+L626 label byte
+db 9
+db 40
+db 49
+db 32
+db 43
+db 32
+db 40
+db 37
+db 46
+db 49
+db 55
+db 101
+db 41
+db 32
+db 94
+db 32
+db 40
+db 37
+db 46
+db 49
+db 55
+db 101
+db 41
+db 59
+db 10
+db 0
+align 1
+L625 label byte
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 32
+db 102
+db 111
+db 114
+db 10
+db 0
+align 1
+L624 label byte
+db 67
+db 97
+db 108
+db 99
+db 117
+db 108
+db 97
+db 116
+db 101
+db 100
+db 0
+align 1
+L617 label byte
+db 84
+db 101
+db 115
+db 116
+db 105
+db 110
+db 103
+db 32
+db 88
+db 94
+db 40
+db 40
+db 88
+db 32
+db 43
+db 32
+db 49
+db 41
+db 32
+db 47
+db 32
+db 40
+db 88
+db 32
+db 45
+db 32
+db 49
+db 41
+db 41
+db 32
+db 118
+db 115
+db 46
+db 32
+db 101
+db 120
+db 112
+db 40
+db 50
+db 41
+db 32
+db 61
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 32
+db 97
+db 115
+db 32
+db 88
+db 32
+db 45
+db 62
+db 32
+db 49
+db 46
+db 10
+db 0
+align 1
+L613 label byte
+db 84
+db 104
+db 105
+db 115
+db 32
+db 99
+db 111
+db 109
+db 112
+db 117
+db 116
+db 101
+db 100
+db 32
+db 118
+db 97
+db 108
+db 117
+db 101
+db 32
+db 105
+db 115
+db 32
+db 79
+db 46
+db 75
+db 46
+db 10
+db 0
+align 1
+L610 label byte
+db 32
+db 32
+db 32
+db 116
+db 104
+db 114
+db 101
+db 115
+db 104
+db 111
+db 108
+db 100
+db 32
+db 61
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 32
+db 46
+db 10
+db 0
+align 1
+L609 label byte
+db 116
+db 104
+db 105
+db 115
+db 32
+db 105
+db 115
+db 32
+db 110
+db 111
+db 116
+db 32
+db 98
+db 101
+db 116
+db 119
+db 101
+db 101
+db 110
+db 32
+db 48
+db 32
+db 97
+db 110
+db 100
+db 32
+db 117
+db 110
+db 100
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 10
+db 0
+align 1
+L605 label byte
+db 97
+db 99
+db 116
+db 117
+db 97
+db 108
+db 108
+db 121
+db 32
+db 99
+db 97
+db 108
+db 99
+db 117
+db 108
+db 97
+db 116
+db 105
+db 110
+db 103
+db 32
+db 121
+db 105
+db 101
+db 108
+db 100
+db 115
+db 58
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 32
+db 46
+db 10
+db 0
+align 1
+L604 label byte
+db 115
+db 104
+db 111
+db 117
+db 108
+db 100
+db 32
+db 97
+db 102
+db 102
+db 108
+db 105
+db 99
+db 116
+db 32
+db 116
+db 104
+db 101
+db 32
+db 101
+db 120
+db 112
+db 114
+db 101
+db 115
+db 115
+db 105
+db 111
+db 110
+db 10
+db 9
+db 40
+db 37
+db 46
+db 49
+db 55
+db 101
+db 41
+db 32
+db 94
+db 32
+db 40
+db 37
+db 46
+db 49
+db 55
+db 101
+db 41
+db 59
+db 10
+db 0
+align 1
+L603 label byte
+db 85
+db 102
+db 84
+db 104
+db 111
+db 108
+db 100
+db 32
+db 61
+db 32
+db 40
+db 37
+db 46
+db 49
+db 55
+db 101
+db 41
+db 32
+db 94
+db 32
+db 40
+db 37
+db 46
+db 49
+db 55
+db 101
+db 41
+db 10
+db 111
+db 110
+db 108
+db 121
+db 32
+db 117
+db 110
+db 100
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 32
+db 0
+align 1
+L602 label byte
+db 83
+db 105
+db 110
+db 99
+db 101
+db 32
+db 117
+db 110
+db 100
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 32
+db 111
+db 99
+db 99
+db 117
+db 114
+db 115
+db 32
+db 98
+db 101
+db 108
+db 111
+db 119
+db 32
+db 116
+db 104
+db 101
+db 32
+db 116
+db 104
+db 114
+db 101
+db 115
+db 104
+db 111
+db 108
+db 100
+db 10
+db 0
+align 1
+L601 label byte
+db 82
+db 97
+db 110
+db 103
+db 101
+db 32
+db 105
+db 115
+db 32
+db 116
+db 111
+db 111
+db 32
+db 110
+db 97
+db 114
+db 114
+db 111
+db 119
+db 59
+db 32
+db 85
+db 49
+db 94
+db 37
+db 100
+db 32
+db 85
+db 110
+db 100
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 115
+db 46
+db 10
+db 0
+align 1
+L596 label byte
+db 109
+db 101
+db 114
+db 101
+db 108
+db 121
+db 32
+db 114
+db 111
+db 117
+db 110
+db 100
+db 111
+db 102
+db 102
+db 46
+db 10
+db 0
+align 1
+L595 label byte
+db 99
+db 97
+db 108
+db 99
+db 117
+db 108
+db 97
+db 116
+db 105
+db 111
+db 110
+db 32
+db 109
+db 97
+db 121
+db 32
+db 115
+db 117
+db 102
+db 102
+db 101
+db 114
+db 32
+db 108
+db 97
+db 114
+db 103
+db 101
+db 114
+db 32
+db 82
+db 101
+db 108
+db 97
+db 116
+db 105
+db 118
+db 101
+db 32
+db 101
+db 114
+db 114
+db 111
+db 114
+db 32
+db 116
+db 104
+db 97
+db 110
+db 32
+db 0
+align 1
+L594 label byte
+db 32
+db 98
+db 101
+db 108
+db 111
+db 119
+db 32
+db 119
+db 104
+db 105
+db 99
+db 104
+db 0
+align 1
+L593 label byte
+db 84
+db 104
+db 101
+db 32
+db 85
+db 110
+db 100
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 32
+db 116
+db 104
+db 114
+db 101
+db 115
+db 104
+db 111
+db 108
+db 100
+db 32
+db 105
+db 115
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 44
+db 32
+db 37
+db 115
+db 10
+db 0
+align 1
+L592 label byte
+db 88
+db 32
+db 47
+db 32
+db 90
+db 32
+db 61
+db 32
+db 49
+db 32
+db 43
+db 32
+db 37
+db 103
+db 32
+db 46
+db 10
+db 0
+align 1
+L591 label byte
+db 88
+db 32
+db 47
+db 32
+db 90
+db 32
+db 102
+db 97
+db 105
+db 108
+db 115
+db 33
+db 10
+db 0
+align 1
+L588 label byte
+db 101
+db 110
+db 99
+db 111
+db 117
+db 110
+db 116
+db 101
+db 114
+db 32
+db 68
+db 105
+db 118
+db 105
+db 115
+db 105
+db 111
+db 110
+db 32
+db 98
+db 121
+db 32
+db 90
+db 101
+db 114
+db 111
+db 32
+db 97
+db 108
+db 116
+db 104
+db 111
+db 117
+db 103
+db 104
+db 32
+db 97
+db 99
+db 116
+db 117
+db 97
+db 108
+db 108
+db 121
+db 10
+db 0
+align 1
+L587 label byte
+db 32
+db 32
+db 46
+db 46
+db 46
+db 32
+db 40
+db 102
+db 40
+db 88
+db 41
+db 32
+db 45
+db 32
+db 102
+db 40
+db 90
+db 41
+db 41
+db 32
+db 47
+db 32
+db 40
+db 88
+db 32
+db 45
+db 32
+db 90
+db 41
+db 32
+db 46
+db 46
+db 46
+db 10
+db 0
+align 1
+L586 label byte
+db 32
+db 32
+db 32
+db 32
+db 105
+db 102
+db 32
+db 40
+db 88
+db 32
+db 61
+db 61
+db 32
+db 90
+db 41
+db 32
+db 32
+db 46
+db 46
+db 46
+db 32
+db 32
+db 101
+db 108
+db 115
+db 101
+db 0
+align 1
+L585 label byte
+db 99
+db 111
+db 110
+db 102
+db 117
+db 115
+db 105
+db 111
+db 110
+db 32
+db 119
+db 104
+db 101
+db 110
+db 32
+db 105
+db 110
+db 110
+db 111
+db 99
+db 101
+db 110
+db 116
+db 32
+db 115
+db 116
+db 97
+db 116
+db 101
+db 109
+db 101
+db 110
+db 116
+db 115
+db 32
+db 108
+db 105
+db 107
+db 101
+db 10
+db 0
+align 1
+L584 label byte
+db 116
+db 104
+db 105
+db 115
+db 32
+db 105
+db 115
+db 32
+db 97
+db 32
+db 83
+db 69
+db 82
+db 73
+db 79
+db 85
+db 83
+db 32
+db 68
+db 69
+db 70
+db 69
+db 67
+db 84
+db 10
+db 116
+db 104
+db 97
+db 116
+db 32
+db 99
+db 97
+db 117
+db 115
+db 101
+db 115
+db 32
+db 0
+align 1
+L583 label byte
+db 32
+db 32
+db 32
+db 32
+db 83
+db 104
+db 111
+db 117
+db 108
+db 100
+db 32
+db 116
+db 104
+db 105
+db 115
+db 32
+db 78
+db 79
+db 84
+db 32
+db 115
+db 105
+db 103
+db 110
+db 97
+db 108
+db 32
+db 85
+db 110
+db 100
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 44
+db 32
+db 0
+align 1
+L582 label byte
+db 121
+db 101
+db 116
+db 32
+db 88
+db 32
+db 45
+db 32
+db 90
+db 32
+db 121
+db 105
+db 101
+db 108
+db 100
+db 115
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 32
+db 46
+db 10
+db 0
+align 1
+L581 label byte
+db 88
+db 32
+db 61
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 10
+db 9
+db 105
+db 115
+db 32
+db 110
+db 111
+db 116
+db 32
+db 101
+db 113
+db 117
+db 97
+db 108
+db 32
+db 116
+db 111
+db 32
+db 90
+db 32
+db 61
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 32
+db 46
+db 10
+db 0
+align 1
+L576 label byte
+db 85
+db 110
+db 100
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 32
+db 47
+db 32
+db 85
+db 102
+db 84
+db 104
+db 111
+db 108
+db 100
+db 32
+db 102
+db 97
+db 105
+db 108
+db 101
+db 100
+db 33
+db 10
+db 0
+align 1
+L566 label byte
+db 40
+db 114
+db 111
+db 117
+db 110
+db 100
+db 111
+db 102
+db 102
+db 32
+db 105
+db 110
+db 32
+db 85
+db 102
+db 84
+db 104
+db 111
+db 108
+db 100
+db 41
+db 32
+db 60
+db 32
+db 69
+db 48
+db 46
+db 10
+db 0
+align 1
+L565 label byte
+db 85
+db 110
+db 100
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 32
+db 105
+db 115
+db 32
+db 103
+db 114
+db 97
+db 100
+db 117
+db 97
+db 108
+db 59
+db 32
+db 105
+db 116
+db 32
+db 105
+db 110
+db 99
+db 117
+db 114
+db 115
+db 32
+db 65
+db 98
+db 115
+db 111
+db 108
+db 117
+db 116
+db 101
+db 32
+db 69
+db 114
+db 114
+db 111
+db 114
+db 32
+db 61
+db 10
+db 0
+align 1
+L560 label byte
+db 124
+db 81
+db 32
+db 45
+db 32
+db 89
+db 124
+db 32
+db 61
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 32
+db 46
+db 10
+db 0
+align 1
+L559 label byte
+db 112
+db 114
+db 105
+db 110
+db 116
+db 32
+db 111
+db 117
+db 116
+db 32
+db 97
+db 115
+db 32
+db 81
+db 32
+db 61
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 44
+db 32
+db 89
+db 32
+db 61
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 32
+db 46
+db 10
+db 0
+align 1
+L558 label byte
+db 81
+db 32
+db 61
+db 61
+db 32
+db 89
+db 32
+db 119
+db 104
+db 105
+db 108
+db 101
+db 32
+db 100
+db 101
+db 110
+db 121
+db 105
+db 110
+db 103
+db 32
+db 116
+db 104
+db 97
+db 116
+db 32
+db 124
+db 81
+db 32
+db 45
+db 32
+db 89
+db 124
+db 32
+db 61
+db 61
+db 32
+db 48
+db 59
+db 32
+db 116
+db 104
+db 101
+db 115
+db 101
+db 32
+db 118
+db 97
+db 108
+db 117
+db 101
+db 115
+db 10
+db 0
+align 1
+L557 label byte
+db 85
+db 110
+db 100
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 32
+db 99
+db 111
+db 110
+db 102
+db 117
+db 115
+db 101
+db 115
+db 32
+db 67
+db 111
+db 109
+db 112
+db 97
+db 114
+db 105
+db 115
+db 111
+db 110
+db 44
+db 32
+db 119
+db 104
+db 105
+db 99
+db 104
+db 32
+db 97
+db 108
+db 108
+db 101
+db 103
+db 101
+db 115
+db 32
+db 116
+db 104
+db 97
+db 116
+db 10
+db 0
+align 1
+L555 label byte
+db 32
+db 111
+db 114
+db 32
+db 101
+db 108
+db 115
+db 101
+db 32
+db 109
+db 117
+db 108
+db 116
+db 105
+db 112
+db 108
+db 105
+db 99
+db 97
+db 116
+db 105
+db 111
+db 110
+db 32
+db 103
+db 101
+db 116
+db 115
+db 32
+db 116
+db 111
+db 111
+db 32
+db 109
+db 97
+db 110
+db 121
+db 32
+db 108
+db 97
+db 115
+db 116
+db 32
+db 100
+db 105
+db 103
+db 105
+db 116
+db 115
+db 32
+db 119
+db 114
+db 111
+db 110
+db 103
+db 46
+db 10
+db 0
+align 1
+L554 label byte
+db 32
+db 99
+db 111
+db 109
+db 105
+db 110
+db 103
+db 32
+db 100
+db 111
+db 119
+db 110
+db 32
+db 102
+db 114
+db 111
+db 109
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 10
+db 0
+align 1
+L553 label byte
+db 97
+db 112
+db 112
+db 114
+db 111
+db 97
+db 99
+db 104
+db 32
+db 97
+db 32
+db 116
+db 104
+db 114
+db 101
+db 115
+db 104
+db 111
+db 108
+db 100
+db 32
+db 61
+db 32
+db 37
+db 46
+db 49
+db 55
+db 101
+db 10
+db 0
+align 1
+L552 label byte
+db 69
+db 105
+db 116
+db 104
+db 101
+db 114
+db 32
+db 97
+db 99
+db 99
+db 117
+db 114
+db 97
+db 99
+db 121
+db 32
+db 100
+db 101
+db 116
+db 101
+db 114
+db 105
+db 111
+db 114
+db 97
+db 116
+db 101
+db 115
+db 32
+db 97
+db 115
+db 32
+db 110
+db 117
+db 109
+db 98
+db 101
+db 114
+db 115
+db 10
+db 0
+align 1
+L540 label byte
+db 83
+db 109
+db 97
+db 108
+db 108
+db 101
+db 115
+db 116
+db 32
+db 115
+db 116
+db 114
+db 105
+db 99
+db 116
+db 108
+db 121
+db 32
+db 112
+db 111
+db 115
+db 105
+db 116
+db 105
+db 118
+db 101
+db 32
+db 110
+db 117
+db 109
+db 98
+db 101
+db 114
+db 32
+db 102
+db 111
+db 117
+db 110
+db 100
+db 32
+db 105
+db 115
+db 32
+db 69
+db 48
+db 32
+db 61
+db 32
+db 37
+db 103
+db 32
+db 46
+db 10
+db 0
+align 1
+L539 label byte
+db 32
+db 116
+db 104
+db 114
+db 101
+db 115
+db 104
+db 111
+db 108
+db 100
+db 32
+db 116
+db 104
+db 97
+db 110
+db 32
+db 112
+db 114
+db 111
+db 100
+db 117
+db 99
+db 116
+db 115
+db 46
+db 10
+db 0
+align 1
+L538 label byte
+db 68
+db 105
+db 102
+db 102
+db 101
+db 114
+db 101
+db 110
+db 99
+db 101
+db 32
+db 117
+db 110
+db 100
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 115
+db 32
+db 97
+db 116
+db 32
+db 97
+db 32
+db 104
+db 105
+db 103
+db 104
+db 101
+db 114
+db 0
+align 1
+L535 label byte
+db 32
+db 116
+db 104
+db 114
+db 101
+db 115
+db 104
+db 111
+db 108
+db 100
+db 32
+db 116
+db 104
+db 97
+db 110
+db 32
+db 100
+db 105
+db 102
+db 102
+db 101
+db 114
+db 101
+db 110
+db 99
+db 101
+db 115
+db 46
+db 10
+db 0
+align 1
+L534 label byte
+db 80
+db 114
+db 111
+db 100
+db 117
+db 99
+db 116
+db 115
+db 32
+db 117
+db 110
+db 100
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 32
+db 97
+db 116
+db 32
+db 97
+db 32
+db 104
+db 105
+db 103
+db 104
+db 101
+db 114
+db 0
+align 1
+L527 label byte
+db 118
+db 97
+db 108
+db 117
+db 101
+db 32
+db 80
+db 115
+db 101
+db 117
+db 100
+db 111
+db 90
+db 101
+db 114
+db 111
+db 32
+db 116
+db 104
+db 97
+db 116
+db 32
+db 112
+db 114
+db 105
+db 110
+db 116
+db 115
+db 32
+db 111
+db 117
+db 116
+db 32
+db 97
+db 115
+db 32
+db 37
+db 103
+db 32
+db 46
+db 10
+db 0
+align 1
+L526 label byte
+db 85
+db 110
+db 100
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 32
+db 99
+db 97
+db 110
+db 32
+db 115
+db 116
+db 105
+db 99
+db 107
+db 32
+db 97
+db 116
+db 32
+db 97
+db 110
+db 32
+db 97
+db 108
+db 108
+db 101
+db 103
+db 101
+db 100
+db 108
+db 121
+db 32
+db 112
+db 111
+db 115
+db 105
+db 116
+db 105
+db 118
+db 101
+db 10
+db 0
+align 1
+L525 label byte
+db 112
+db 111
+db 115
+db 105
+db 116
+db 105
+db 118
+db 101
+db 44
+db 32
+db 105
+db 115
+db 110
+db 39
+db 116
+db 59
+db 32
+db 105
+db 116
+db 32
+db 112
+db 114
+db 105
+db 110
+db 116
+db 115
+db 32
+db 111
+db 117
+db 116
+db 32
+db 97
+db 115
+db 32
+db 32
+db 37
+db 103
+db 32
+db 46
+db 10
+db 0
+align 1
+L524 label byte
+db 66
+db 117
+db 116
+db 32
+db 45
+db 80
+db 115
+db 101
+db 117
+db 100
+db 111
+db 90
+db 101
+db 114
+db 111
+db 44
+db 32
+db 119
+db 104
+db 105
+db 99
+db 104
+db 32
+db 115
+db 104
+db 111
+db 117
+db 108
+db 100
+db 32
+db 98
+db 101
+db 10
+db 0
+align 1
+L521 label byte
+db 80
+db 115
+db 101
+db 117
+db 100
+db 111
+db 90
+db 101
+db 114
+db 111
+db 32
+db 116
+db 104
+db 97
+db 116
+db 32
+db 112
+db 114
+db 105
+db 110
+db 116
+db 115
+db 32
+db 111
+db 117
+db 116
+db 32
+db 97
+db 115
+db 58
+db 32
+db 37
+db 103
+db 32
+db 46
+db 10
+db 0
+align 1
+L520 label byte
+db 97
+db 108
+db 108
+db 101
+db 103
+db 101
+db 100
+db 108
+db 121
+db 32
+db 110
+db 101
+db 103
+db 97
+db 116
+db 105
+db 118
+db 101
+db 32
+db 118
+db 97
+db 108
+db 117
+db 101
+db 10
+db 0
+align 1
+L519 label byte
+db 80
+db 111
+db 115
+db 105
+db 116
+db 105
+db 118
+db 101
+db 32
+db 101
+db 120
+db 112
+db 114
+db 101
+db 115
+db 115
+db 105
+db 111
+db 110
+db 115
+db 32
+db 99
+db 97
+db 110
+db 32
+db 117
+db 110
+db 100
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 32
+db 116
+db 111
+db 32
+db 97
+db 110
+db 10
+db 0
+align 1
+L506 label byte
+db 109
+db 117
+db 108
+db 116
+db 105
+db 112
+db 108
+db 105
+db 99
+db 97
+db 116
+db 105
+db 111
+db 110
+db 32
+db 103
+db 101
+db 116
+db 115
+db 32
+db 116
+db 111
+db 111
+db 32
+db 109
+db 97
+db 110
+db 121
+db 32
+db 108
+db 97
+db 115
+db 116
+db 32
+db 100
+db 105
+db 103
+db 105
+db 116
+db 115
+db 32
+db 119
+db 114
+db 111
+db 110
+db 103
+db 46
+db 10
+db 0
+align 1
+L482 label byte
+db 83
+db 101
+db 101
+db 107
+db 105
+db 110
+db 103
+db 32
+db 85
+db 110
+db 100
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 32
+db 116
+db 104
+db 114
+db 101
+db 115
+db 104
+db 111
+db 108
+db 100
+db 115
+db 32
+db 85
+db 102
+db 84
+db 104
+db 111
+db 108
+db 100
+db 32
+db 97
+db 110
+db 100
+db 32
+db 69
+db 48
+db 46
+db 10
+db 0
+align 1
+L479 label byte
+db 46
+db 46
+db 46
+db 32
+db 110
+db 111
+db 32
+db 100
+db 105
+db 115
+db 99
+db 114
+db 101
+db 112
+db 97
+db 110
+db 99
+db 105
+db 115
+db 32
+db 102
+db 111
+db 117
+db 110
+db 100
+db 46
+db 10
+db 0
+align 1
+L476 label byte
+db 9
+db 105
+db 110
+db 118
+db 111
+db 108
+db 118
+db 105
+db 110
+db 103
+db 32
+db 105
+db 110
+db 116
+db 101
+db 114
+db 101
+db 115
+db 116
+db 32
+db 114
+db 97
+db 116
+db 101
+db 115
+db 46
+db 10
+db 0
+align 1
+L475 label byte
+db 69
+db 114
+db 114
+db 111
+db 114
+db 115
+db 32
+db 108
+db 105
+db 107
+db 101
+db 32
+db 116
+db 104
+db 105
+db 115
+db 32
+db 109
+db 97
+db 121
+db 32
+db 105
+db 110
+db 118
+db 97
+db 108
+db 105
+db 100
+db 97
+db 116
+db 101
+db 32
+db 102
+db 105
+db 110
+db 97
+db 110
+db 99
+db 105
+db 97
+db 108
+db 32
+db 99
+db 97
+db 108
+db 99
+db 117
+db 108
+db 97
+db 116
+db 105
+db 111
+db 110
+db 115
+db 10
+db 0
+align 1
+L454 label byte
+db 84
+db 101
+db 115
+db 116
+db 105
+db 110
+db 103
+db 32
+db 112
+db 111
+db 119
+db 101
+db 114
+db 115
+db 32
+db 90
+db 94
+db 105
+db 32
+db 102
+db 111
+db 114
+db 32
+db 115
+db 109
+db 97
+db 108
+db 108
+db 32
+db 73
+db 110
+db 116
+db 101
+db 103
+db 101
+db 114
+db 115
+db 32
+db 90
+db 32
+db 97
+db 110
+db 100
+db 32
+db 105
+db 46
+db 10
+db 0
+align 1
+L451 label byte
+db 115
+db 113
+db 114
+db 116
+db 32
+db 103
+db 101
+db 116
+db 115
+db 32
+db 116
+db 111
+db 111
+db 32
+db 109
+db 97
+db 110
+db 121
+db 32
+db 108
+db 97
+db 115
+db 116
+db 32
+db 100
+db 105
+db 103
+db 105
+db 116
+db 115
+db 32
+db 119
+db 114
+db 111
+db 110
+db 103
+db 0
+align 1
+L449 label byte
+db 116
+db 111
+db 32
+db 37
+db 46
+db 55
+db 101
+db 32
+db 117
+db 108
+db 112
+db 115
+db 46
+db 10
+db 0
+align 1
+L448 label byte
+db 79
+db 98
+db 115
+db 101
+db 114
+db 118
+db 101
+db 100
+db 32
+db 101
+db 114
+db 114
+db 111
+db 114
+db 115
+db 32
+db 114
+db 117
+db 110
+db 32
+db 102
+db 114
+db 111
+db 109
+db 32
+db 37
+db 46
+db 55
+db 101
+db 32
+db 0
+align 1
+L447 label byte
+db 83
+db 113
+db 117
+db 97
+db 114
+db 101
+db 32
+db 114
+db 111
+db 111
+db 116
+db 32
+db 105
+db 115
+db 32
+db 110
+db 101
+db 105
+db 116
+db 104
+db 101
+db 114
+db 32
+db 99
+db 104
+db 111
+db 112
+db 112
+db 101
+db 100
+db 32
+db 110
+db 111
+db 114
+db 32
+db 99
+db 111
+db 114
+db 114
+db 101
+db 99
+db 116
+db 108
+db 121
+db 32
+db 114
+db 111
+db 117
+db 110
+db 100
+db 101
+db 100
+db 46
+db 10
+db 0
+align 1
+L444 label byte
+db 83
+db 113
+db 117
+db 97
+db 114
+db 101
+db 32
+db 114
+db 111
+db 111
+db 116
+db 32
+db 97
+db 112
+db 112
+db 101
+db 97
+db 114
+db 115
+db 32
+db 116
+db 111
+db 32
+db 98
+db 101
+db 32
+db 99
+db 104
+db 111
+db 112
+db 112
+db 101
+db 100
+db 46
+db 10
+db 0
+align 1
+L439 label byte
+db 83
+db 113
+db 117
+db 97
+db 114
+db 101
+db 32
+db 114
+db 111
+db 111
+db 116
+db 32
+db 97
+db 112
+db 112
+db 101
+db 97
+db 114
+db 115
+db 32
+db 116
+db 111
+db 32
+db 98
+db 101
+db 32
+db 99
+db 111
+db 114
+db 114
+db 101
+db 99
+db 116
+db 108
+db 121
+db 32
+db 114
+db 111
+db 117
+db 110
+db 100
+db 101
+db 100
+db 46
+db 10
+db 0
+align 1
+L434 label byte
+db 32
+db 102
+db 97
+db 105
+db 108
+db 115
+db 32
+db 116
+db 101
+db 115
+db 116
+db 32
+db 119
+db 104
+db 101
+db 116
+db 104
+db 101
+db 114
+db 32
+db 115
+db 113
+db 114
+db 116
+db 32
+db 114
+db 111
+db 117
+db 110
+db 100
+db 115
+db 32
+db 111
+db 114
+db 32
+db 99
+db 104
+db 111
+db 112
+db 115
+db 46
+db 10
+db 0
+align 1
+L433 label byte
+db 82
+db 97
+db 100
+db 105
+db 120
+db 94
+db 80
+db 114
+db 101
+db 99
+db 105
+db 115
+db 105
+db 111
+db 110
+db 32
+db 61
+db 32
+db 37
+db 46
+db 55
+db 101
+db 10
+db 0
+align 1
+L432 label byte
+db 65
+db 110
+db 111
+db 109
+db 97
+db 108
+db 111
+db 117
+db 115
+db 32
+db 97
+db 114
+db 105
+db 116
+db 104
+db 109
+db 101
+db 116
+db 105
+db 99
+db 32
+db 119
+db 105
+db 116
+db 104
+db 32
+db 73
+db 110
+db 116
+db 101
+db 103
+db 101
+db 114
+db 32
+db 60
+db 32
+db 0
+align 1
+L392 label byte
+db 84
+db 101
+db 115
+db 116
+db 105
+db 110
+db 103
+db 32
+db 119
+db 104
+db 101
+db 116
+db 104
+db 101
+db 114
+db 32
+db 115
+db 113
+db 114
+db 116
+db 32
+db 105
+db 115
+db 32
+db 114
+db 111
+db 117
+db 110
+db 100
+db 101
+db 100
+db 32
+db 111
+db 114
+db 32
+db 99
+db 104
+db 111
+db 112
+db 112
+db 101
+db 100
+db 46
+db 10
+db 0
+align 1
+L370 label byte
+db 115
+db 113
+db 114
+db 116
+db 40
+db 88
+db 41
+db 32
+db 105
+db 115
+db 32
+db 110
+db 111
+db 110
+db 45
+db 109
+db 111
+db 110
+db 111
+db 116
+db 111
+db 110
+db 105
+db 99
+db 32
+db 102
+db 111
+db 114
+db 32
+db 88
+db 32
+db 110
+db 101
+db 97
+db 114
+db 32
+db 37
+db 46
+db 55
+db 101
+db 32
+db 46
+db 10
+db 0
+align 1
+L369 label byte
+db 115
+db 113
+db 114
+db 116
+db 32
+db 104
+db 97
+db 115
+db 32
+db 112
+db 97
+db 115
+db 115
+db 101
+db 100
+db 32
+db 97
+db 32
+db 116
+db 101
+db 115
+db 116
+db 32
+db 102
+db 111
+db 114
+db 32
+db 77
+db 111
+db 110
+db 111
+db 116
+db 111
+db 110
+db 105
+db 99
+db 105
+db 116
+db 121
+db 46
+db 10
+db 0
+align 1
+L352 label byte
+db 84
+db 101
+db 115
+db 116
+db 32
+db 102
+db 111
+db 114
+db 32
+db 115
+db 113
+db 114
+db 116
+db 32
+db 109
+db 111
+db 110
+db 111
+db 116
+db 111
+db 110
+db 105
+db 99
+db 105
+db 116
+db 121
+db 46
+db 10
+db 0
+align 1
+L341 label byte
+db 84
+db 101
+db 115
+db 116
+db 105
+db 110
+db 103
+db 32
+db 105
+db 102
+db 32
+db 115
+db 113
+db 114
+db 116
+db 40
+db 88
+db 32
+db 42
+db 32
+db 88
+db 41
+db 32
+db 61
+db 61
+db 32
+db 88
+db 32
+db 102
+db 111
+db 114
+db 32
+db 37
+db 100
+db 32
+db 73
+db 110
+db 116
+db 101
+db 103
+db 101
+db 114
+db 115
+db 32
+db 88
+db 46
+db 10
+db 0
+align 1
+L336 label byte
+db 83
+db 113
+db 117
+db 97
+db 114
+db 101
+db 32
+db 114
+db 111
+db 111
+db 116
+db 32
+db 111
+db 102
+db 32
+db 48
+db 46
+db 48
+db 44
+db 32
+db 45
+db 48
+db 46
+db 48
+db 32
+db 111
+db 114
+db 32
+db 49
+db 46
+db 48
+db 32
+db 119
+db 114
+db 111
+db 110
+db 103
+db 0
+align 1
+L334 label byte
+db 10
+db 82
+db 117
+db 110
+db 110
+db 105
+db 110
+db 103
+db 32
+db 116
+db 101
+db 115
+db 116
+db 32
+db 111
+db 102
+db 32
+db 115
+db 113
+db 117
+db 97
+db 114
+db 101
+db 32
+db 114
+db 111
+db 111
+db 116
+db 40
+db 120
+db 41
+db 46
+db 10
+db 0
+align 1
+L333 label byte
+db 32
+db 32
+db 32
+db 32
+db 32
+db 78
+db 111
+db 32
+db 102
+db 97
+db 105
+db 108
+db 117
+db 114
+db 101
+db 115
+db 32
+db 102
+db 111
+db 117
+db 110
+db 100
+db 32
+db 105
+db 110
+db 32
+db 37
+db 100
+db 32
+db 105
+db 110
+db 116
+db 101
+db 103
+db 101
+db 114
+db 32
+db 112
+db 97
+db 105
+db 114
+db 115
+db 46
+db 10
+db 0
+align 1
+L332 label byte
+db 88
+db 32
+db 42
+db 32
+db 89
+db 32
+db 61
+db 61
+db 32
+db 89
+db 32
+db 42
+db 32
+db 88
+db 32
+db 116
+db 114
+db 105
+db 97
+db 108
+db 32
+db 102
+db 97
+db 105
+db 108
+db 115
+db 46
+db 10
+db 0
+align 4
+L323 label byte
+dd 00H
+dd 040080000H
+align 1
+L322 label byte
+db 84
+db 101
+db 115
+db 116
+db 105
+db 110
+db 103
+db 32
+db 111
+db 110
+db 32
+db 37
+db 100
+db 32
+db 114
+db 97
+db 110
+db 100
+db 111
+db 109
+db 32
+db 112
+db 97
+db 105
+db 114
+db 115
+db 46
+db 10
+db 0
+align 1
+L321 label byte
+db 68
+db 111
+db 101
+db 115
+db 32
+db 77
+db 117
+db 108
+db 116
+db 105
+db 112
+db 108
+db 105
+db 99
+db 97
+db 116
+db 105
+db 111
+db 110
+db 32
+db 99
+db 111
+db 109
+db 109
+db 117
+db 116
+db 101
+db 63
+db 32
+db 32
+db 0
+align 1
+L318 label byte
+db 108
+db 97
+db 99
+db 107
+db 40
+db 115
+db 41
+db 32
+db 111
+db 102
+db 32
+db 103
+db 117
+db 97
+db 114
+db 100
+db 32
+db 100
+db 105
+db 103
+db 105
+db 116
+db 115
+db 32
+db 111
+db 114
+db 32
+db 102
+db 97
+db 105
+db 108
+db 117
+db 114
+db 101
+db 40
+db 115
+db 41
+db 32
+db 116
+db 111
+db 32
+db 99
+db 111
+db 114
+db 114
+db 101
+db 99
+db 116
+db 108
+db 121
+db 32
+db 114
+db 111
+db 117
+db 110
+db 100
+db 32
+db 111
+db 114
+db 32
+db 99
+db 104
+db 111
+db 112
+db 10
+db 40
+db 110
+db 111
+db 116
+db 101
+db 100
+db 32
+db 97
+db 98
+db 111
+db 118
+db 101
+db 41
+db 32
+db 99
+db 111
+db 117
+db 110
+db 116
+db 32
+db 97
+db 115
+db 32
+db 111
+db 110
+db 101
+db 32
+db 102
+db 108
+db 97
+db 119
+db 32
+db 105
+db 110
+db 32
+db 116
+db 104
+db 101
+db 32
+db 102
+db 105
+db 110
+db 97
+db 108
+db 32
+db 116
+db 97
+db 108
+db 108
+db 121
+db 32
+db 98
+db 101
+db 108
+db 111
+db 119
+db 0
+align 1
+L316 label byte
+db 83
+db 116
+db 105
+db 99
+db 107
+db 121
+db 32
+db 98
+db 105
+db 116
+db 32
+db 117
+db 115
+db 101
+db 100
+db 32
+db 105
+db 110
+db 99
+db 111
+db 114
+db 114
+db 101
+db 99
+db 116
+db 108
+db 121
+db 32
+db 111
+db 114
+db 32
+db 110
+db 111
+db 116
+db 32
+db 97
+db 116
+db 32
+db 97
+db 108
+db 108
+db 46
+db 10
+db 0
+align 1
+L315 label byte
+db 83
+db 116
+db 105
+db 99
+db 107
+db 121
+db 32
+db 98
+db 105
+db 116
+db 32
+db 97
+db 112
+db 112
+db 97
+db 114
+db 101
+db 110
+db 116
+db 108
+db 121
+db 32
+db 117
+db 115
+db 101
+db 100
+db 32
+db 99
+db 111
+db 114
+db 114
+db 101
+db 99
+db 116
+db 108
+db 121
+db 46
+db 10
+db 0
+align 1
+L298 label byte
+db 67
+db 104
+db 101
+db 99
+db 107
+db 105
+db 110
+db 103
+db 32
+db 102
+db 111
+db 114
+db 32
+db 115
+db 116
+db 105
+db 99
+db 107
+db 121
+db 32
+db 98
+db 105
+db 116
+db 46
+db 10
+db 0
+align 1
+L295 label byte
+db 40
+db 88
+db 32
+db 45
+db 32
+db 89
+db 41
+db 32
+db 43
+db 32
+db 40
+db 89
+db 32
+db 45
+db 32
+db 88
+db 41
+db 32
+db 105
+db 115
+db 32
+db 110
+db 111
+db 110
+db 32
+db 122
+db 101
+db 114
+db 111
+db 33
+db 10
+db 0
+align 1
+L292 label byte
+db 65
+db 100
+db 100
+db 105
+db 116
+db 105
+db 111
+db 110
+db 47
+db 83
+db 117
+db 98
+db 116
+db 114
+db 97
+db 99
+db 116
+db 105
+db 111
+db 110
+db 32
+db 110
+db 101
+db 105
+db 116
+db 104
+db 101
+db 114
+db 32
+db 114
+db 111
+db 117
+db 110
+db 100
+db 115
+db 32
+db 110
+db 111
+db 114
+db 32
+db 99
+db 104
+db 111
+db 112
+db 115
+db 46
+db 10
+db 0
+align 1
+L291 label byte
+db 65
+db 100
+db 100
+db 47
+db 83
+db 117
+db 98
+db 116
+db 114
+db 97
+db 99
+db 116
+db 0
+align 1
+L288 label byte
+db 65
+db 100
+db 100
+db 105
+db 116
+db 105
+db 111
+db 110
+db 47
+db 83
+db 117
+db 98
+db 116
+db 114
+db 97
+db 99
+db 116
+db 105
+db 111
+db 110
+db 32
+db 97
+db 112
+db 112
+db 101
+db 97
+db 114
+db 115
+db 32
+db 116
+db 111
+db 32
+db 114
+db 111
+db 117
+db 110
+db 100
+db 32
+db 99
+db 111
+db 114
+db 114
+db 101
+db 99
+db 116
+db 108
+db 121
+db 46
+db 10
+db 0
+align 1
+L281 label byte
+db 65
+db 100
+db 100
+db 47
+db 83
+db 117
+db 98
+db 116
+db 114
+db 97
+db 99
+db 116
+db 32
+db 97
+db 112
+db 112
+db 101
+db 97
+db 114
+db 115
+db 32
+db 116
+db 111
+db 32
+db 98
+db 101
+db 32
+db 99
+db 104
+db 111
+db 112
+db 112
+db 101
+db 100
+db 46
+db 10
+db 0
+align 1
+L276 label byte
+db 73
+db 110
+db 99
+db 111
+db 109
+db 112
+db 108
+db 101
+db 116
+db 101
+db 32
+db 99
+db 97
+db 114
+db 114
+db 121
+db 45
+db 112
+db 114
+db 111
+db 112
+db 97
+db 103
+db 97
+db 116
+db 105
+db 111
+db 110
+db 32
+db 105
+db 110
+db 32
+db 65
+db 100
+db 100
+db 105
+db 116
+db 105
+db 111
+db 110
+db 0
+align 1
+L272 label byte
+db 82
+db 97
+db 100
+db 105
+db 120
+db 32
+db 42
+db 32
+db 40
+db 32
+db 49
+db 32
+db 47
+db 32
+db 82
+db 97
+db 100
+db 105
+db 120
+db 32
+db 41
+db 32
+db 100
+db 105
+db 102
+db 102
+db 101
+db 114
+db 115
+db 32
+db 102
+db 114
+db 111
+db 109
+db 32
+db 49
+db 0
+align 1
+L270 label byte
+db 47
+db 32
+db 105
+db 115
+db 32
+db 110
+db 101
+db 105
+db 116
+db 104
+db 101
+db 114
+db 32
+db 99
+db 104
+db 111
+db 112
+db 112
+db 101
+db 100
+db 32
+db 110
+db 111
+db 114
+db 32
+db 99
+db 111
+db 114
+db 114
+db 101
+db 99
+db 116
+db 108
+db 121
+db 32
+db 114
+db 111
+db 117
+db 110
+db 100
+db 101
+db 100
+db 46
+db 10
+db 0
+align 1
+L267 label byte
+db 68
+db 105
+db 118
+db 105
+db 115
+db 105
+db 111
+db 110
+db 32
+db 97
+db 112
+db 112
+db 101
+db 97
+db 114
+db 115
+db 32
+db 116
+db 111
+db 32
+db 99
+db 104
+db 111
+db 112
+db 46
+db 10
+db 0
+align 1
+L264 label byte
+db 68
+db 105
+db 118
+db 105
+db 115
+db 105
+db 111
+db 110
+db 0
+align 1
+L261 label byte
+db 68
+db 105
+db 118
+db 105
+db 115
+db 105
+db 111
+db 110
+db 32
+db 97
+db 112
+db 112
+db 101
+db 97
+db 114
+db 115
+db 32
+db 116
+db 111
+db 32
+db 114
+db 111
+db 117
+db 110
+db 100
+db 32
+db 99
+db 111
+db 114
+db 114
+db 101
+db 99
+db 116
+db 108
+db 121
+db 46
+db 10
+db 0
+align 1
+L256 label byte
+db 77
+db 117
+db 108
+db 116
+db 105
+db 112
+db 108
+db 105
+db 99
+db 97
+db 116
+db 105
+db 111
+db 110
+db 0
+align 1
+L253 label byte
+db 42
+db 32
+db 105
+db 115
+db 32
+db 110
+db 101
+db 105
+db 116
+db 104
+db 101
+db 114
+db 32
+db 99
+db 104
+db 111
+db 112
+db 112
+db 101
+db 100
+db 32
+db 110
+db 111
+db 114
+db 32
+db 99
+db 111
+db 114
+db 114
+db 101
+db 99
+db 116
+db 108
+db 121
+db 32
+db 114
+db 111
+db 117
+db 110
+db 100
+db 101
+db 100
+db 46
+db 10
+db 0
+align 1
+L252 label byte
+db 77
+db 117
+db 108
+db 116
+db 105
+db 112
+db 108
+db 105
+db 99
+db 97
+db 116
+db 105
+db 111
+db 110
+db 32
+db 97
+db 112
+db 112
+db 101
+db 97
+db 114
+db 115
+db 32
+db 116
+db 111
+db 32
+db 99
+db 104
+db 111
+db 112
+db 46
+db 10
+db 0
+align 1
+L249 label byte
+db 77
+db 117
+db 108
+db 116
+db 105
+db 112
+db 108
+db 105
+db 99
+db 97
+db 116
+db 105
+db 111
+db 110
+db 32
+db 97
+db 112
+db 112
+db 101
+db 97
+db 114
+db 115
+db 32
+db 116
+db 111
+db 32
+db 114
+db 111
+db 117
+db 110
+db 100
+db 32
+db 99
+db 111
+db 114
+db 114
+db 101
+db 99
+db 116
+db 108
+db 121
+db 46
+db 10
+db 0
+align 1
+L239 label byte
+db 88
+db 32
+db 42
+db 32
+db 40
+db 49
+db 47
+db 88
+db 41
+db 32
+db 100
+db 105
+db 102
+db 102
+db 101
+db 114
+db 115
+db 32
+db 102
+db 114
+db 111
+db 109
+db 32
+db 49
+db 0
+align 1
+L220 label byte
+db 67
+db 104
+db 101
+db 99
+db 107
+db 105
+db 110
+db 103
+db 32
+db 114
+db 111
+db 117
+db 110
+db 100
+db 105
+db 110
+db 103
+db 32
+db 111
+db 110
+db 32
+db 109
+db 117
+db 108
+db 116
+db 105
+db 112
+db 108
+db 121
+db 44
+db 32
+db 100
+db 105
+db 118
+db 105
+db 100
+db 101
+db 32
+db 97
+db 110
+db 100
+db 32
+db 97
+db 100
+db 100
+db 47
+db 115
+db 117
+db 98
+db 116
+db 114
+db 97
+db 99
+db 116
+db 46
+db 10
+db 0
+align 1
+L219 label byte
+db 32
+db 32
+db 32
+db 32
+db 32
+db 42
+db 44
+db 32
+db 47
+db 44
+db 32
+db 97
+db 110
+db 100
+db 32
+db 45
+db 32
+db 97
+db 112
+db 112
+db 101
+db 97
+db 114
+db 32
+db 116
+db 111
+db 32
+db 104
+db 97
+db 118
+db 101
+db 32
+db 103
+db 117
+db 97
+db 114
+db 100
+db 32
+db 100
+db 105
+db 103
+db 105
+db 116
+db 115
+db 44
+db 32
+db 97
+db 115
+db 32
+db 116
+db 104
+db 101
+db 121
+db 32
+db 115
+db 104
+db 111
+db 117
+db 108
+db 100
+db 46
+db 10
+db 0
+align 1
+L216 label byte
+db 32
+db 32
+db 46
+db 46
+db 46
+db 32
+db 32
+db 105
+db 102
+db 32
+db 40
+db 88
+db 32
+db 61
+db 61
+db 32
+db 49
+db 46
+db 48
+db 41
+db 32
+db 123
+db 46
+db 46
+db 46
+db 46
+db 46
+db 125
+db 32
+db 101
+db 108
+db 115
+db 101
+db 32
+db 123
+db 46
+db 46
+db 46
+db 47
+db 40
+db 88
+db 45
+db 49
+db 46
+db 48
+db 41
+db 46
+db 46
+db 46
+db 125
+db 10
+db 0
+align 1
+L215 label byte
+db 32
+db 32
+db 115
+db 117
+db 99
+db 104
+db 32
+db 112
+db 114
+db 101
+db 99
+db 97
+db 117
+db 116
+db 105
+db 111
+db 110
+db 115
+db 32
+db 97
+db 103
+db 97
+db 105
+db 110
+db 115
+db 116
+db 32
+db 100
+db 105
+db 118
+db 105
+db 115
+db 105
+db 111
+db 110
+db 32
+db 98
+db 121
+db 32
+db 122
+db 101
+db 114
+db 111
+db 32
+db 97
+db 115
+db 10
+db 0
+align 1
+L214 label byte
+db 32
+db 32
+db 115
+db 117
+db 98
+db 116
+db 114
+db 97
+db 99
+db 116
+db 105
+db 111
+db 110
+db 32
+db 121
+db 105
+db 101
+db 108
+db 100
+db 115
+db 32
+db 32
+db 40
+db 49
+db 45
+db 85
+db 49
+db 41
+db 32
+db 45
+db 32
+db 49
+db 32
+db 61
+db 32
+db 48
+db 32
+db 44
+db 32
+db 116
+db 104
+db 101
+db 114
+db 101
+db 98
+db 121
+db 32
+db 118
+db 105
+db 116
+db 105
+db 97
+db 116
+db 105
+db 110
+db 103
+db 10
+db 0
+align 1
+L213 label byte
+db 99
+db 111
+db 109
+db 112
+db 97
+db 114
+db 105
+db 115
+db 111
+db 110
+db 32
+db 97
+db 108
+db 108
+db 101
+db 103
+db 101
+db 115
+db 32
+db 32
+db 40
+db 49
+db 45
+db 85
+db 49
+db 41
+db 32
+db 60
+db 32
+db 49
+db 32
+db 32
+db 97
+db 108
+db 116
+db 104
+db 111
+db 117
+db 103
+db 104
+db 10
+db 0
+align 1
+L210 label byte
+db 45
+db 32
+db 108
+db 97
+db 99
+db 107
+db 115
+db 32
+db 71
+db 117
+db 97
+db 114
+db 100
+db 32
+db 68
+db 105
+db 103
+db 105
+db 116
+db 44
+db 32
+db 115
+db 111
+db 32
+db 99
+db 97
+db 110
+db 99
+db 101
+db 108
+db 108
+db 97
+db 116
+db 105
+db 111
+db 110
+db 32
+db 105
+db 115
+db 32
+db 111
+db 98
+db 115
+db 99
+db 117
+db 114
+db 101
+db 100
+db 0
+align 1
+L205 label byte
+db 42
+db 32
+db 97
+db 110
+db 100
+db 47
+db 111
+db 114
+db 32
+db 47
+db 32
+db 103
+db 101
+db 116
+db 115
+db 32
+db 116
+db 111
+db 111
+db 32
+db 109
+db 97
+db 110
+db 121
+db 32
+db 108
+db 97
+db 115
+db 116
+db 32
+db 100
+db 105
+db 103
+db 105
+db 116
+db 115
+db 32
+db 119
+db 114
+db 111
+db 110
+db 103
+db 0
+align 1
+L201 label byte
+db 67
+db 111
+db 109
+db 112
+db 117
+db 116
+db 101
+db 100
+db 32
+db 118
+db 97
+db 108
+db 117
+db 101
+db 32
+db 111
+db 102
+db 32
+db 49
+db 47
+db 49
+db 46
+db 48
+db 48
+db 48
+db 46
+db 46
+db 49
+db 32
+db 62
+db 61
+db 32
+db 49
+db 0
+align 1
+L199 label byte
+db 68
+db 105
+db 118
+db 105
+db 115
+db 105
+db 111
+db 110
+db 32
+db 108
+db 97
+db 99
+db 107
+db 115
+db 32
+db 97
+db 32
+db 71
+db 117
+db 97
+db 114
+db 100
+db 32
+db 68
+db 105
+db 103
+db 105
+db 116
+db 44
+db 32
+db 115
+db 111
+db 32
+db 88
+db 47
+db 49
+db 32
+db 33
+db 61
+db 32
+db 88
+db 0
+align 1
+L194 label byte
+db 68
+db 105
+db 118
+db 105
+db 115
+db 105
+db 111
+db 110
+db 32
+db 108
+db 97
+db 99
+db 107
+db 115
+db 32
+db 97
+db 32
+db 71
+db 117
+db 97
+db 114
+db 100
+db 32
+db 68
+db 105
+db 103
+db 105
+db 116
+db 44
+db 32
+db 115
+db 111
+db 32
+db 101
+db 114
+db 114
+db 111
+db 114
+db 32
+db 99
+db 97
+db 110
+db 32
+db 101
+db 120
+db 99
+db 101
+db 101
+db 100
+db 32
+db 49
+db 32
+db 117
+db 108
+db 112
+db 10
+db 111
+db 114
+db 32
+db 32
+db 49
+db 47
+db 51
+db 32
+db 32
+db 97
+db 110
+db 100
+db 32
+db 32
+db 51
+db 47
+db 57
+db 32
+db 32
+db 97
+db 110
+db 100
+db 32
+db 32
+db 57
+db 47
+db 50
+db 55
+db 32
+db 109
+db 97
+db 121
+db 32
+db 100
+db 105
+db 115
+db 97
+db 103
+db 114
+db 101
+db 101
+db 0
+align 1
+L190 label byte
+db 42
+db 32
+db 103
+db 101
+db 116
+db 115
+db 32
+db 116
+db 111
+db 111
+db 32
+db 109
+db 97
+db 110
+db 121
+db 32
+db 102
+db 105
+db 110
+db 97
+db 108
+db 32
+db 100
+db 105
+db 103
+db 105
+db 116
+db 115
+db 32
+db 119
+db 114
+db 111
+db 110
+db 103
+db 46
+db 10
+db 0
+align 1
+L188 label byte
+db 42
+db 32
+db 108
+db 97
+db 99
+db 107
+db 115
+db 32
+db 97
+db 32
+db 71
+db 117
+db 97
+db 114
+db 100
+db 32
+db 68
+db 105
+db 103
+db 105
+db 116
+db 44
+db 32
+db 115
+db 111
+db 32
+db 49
+db 42
+db 88
+db 32
+db 33
+db 61
+db 32
+db 88
+db 0
+align 1
+L185 label byte
+db 10
+db 67
+db 104
+db 101
+db 99
+db 107
+db 105
+db 110
+db 103
+db 32
+db 102
+db 111
+db 114
+db 32
+db 103
+db 117
+db 97
+db 114
+db 100
+db 32
+db 100
+db 105
+db 103
+db 105
+db 116
+db 32
+db 105
+db 110
+db 32
+db 42
+db 44
+db 32
+db 47
+db 44
+db 32
+db 97
+db 110
+db 100
+db 32
+db 45
+db 46
+db 10
+db 0
+align 1
+L184 label byte
+db 83
+db 117
+db 98
+db 116
+db 114
+db 97
+db 99
+db 116
+db 105
+db 111
+db 110
+db 32
+db 97
+db 112
+db 112
+db 101
+db 97
+db 114
+db 115
+db 32
+db 116
+db 111
+db 32
+db 98
+db 101
+db 32
+db 110
+db 111
+db 114
+db 109
+db 97
+db 108
+db 105
+db 122
+db 101
+db 100
+db 44
+db 32
+db 97
+db 115
+db 32
+db 105
+db 116
+db 32
+db 115
+db 104
+db 111
+db 117
+db 108
+db 100
+db 32
+db 98
+db 101
+db 46
+db 0
+align 1
+L179 label byte
+db 83
+db 117
+db 98
+db 116
+db 114
+db 97
+db 99
+db 116
+db 105
+db 111
+db 110
+db 32
+db 105
+db 115
+db 32
+db 110
+db 111
+db 116
+db 32
+db 110
+db 111
+db 114
+db 109
+db 97
+db 108
+db 105
+db 122
+db 101
+db 100
+db 32
+db 88
+db 61
+db 89
+db 44
+db 88
+db 43
+db 90
+db 32
+db 33
+db 61
+db 32
+db 89
+db 43
+db 90
+db 33
+db 0
+align 1
+L175 label byte
+db 114
+db 111
+db 117
+db 103
+db 104
+db 108
+db 121
+db 32
+db 37
+db 103
+db 32
+db 101
+db 120
+db 116
+db 114
+db 97
+db 32
+db 115
+db 105
+db 103
+db 110
+db 105
+db 102
+db 105
+db 99
+db 97
+db 110
+db 116
+db 32
+db 100
+db 101
+db 99
+db 105
+db 109
+db 97
+db 108
+db 115
+db 46
+db 10
+db 0
+align 1
+L174 label byte
+db 112
+db 114
+db 101
+db 99
+db 105
+db 115
+db 101
+db 108
+db 121
+db 32
+db 119
+db 105
+db 116
+db 104
+db 32
+db 97
+db 98
+db 111
+db 117
+db 116
+db 32
+db 37
+db 103
+db 32
+db 101
+db 120
+db 116
+db 114
+db 97
+db 32
+db 66
+db 45
+db 100
+db 105
+db 103
+db 105
+db 116
+db 115
+db 44
+db 32
+db 105
+db 46
+db 101
+db 46
+db 10
+db 0
+align 1
+L173 label byte
+db 83
+db 111
+db 109
+db 101
+db 32
+db 115
+db 117
+db 98
+db 101
+db 120
+db 112
+db 114
+db 101
+db 115
+db 115
+db 105
+db 111
+db 110
+db 115
+db 32
+db 97
+db 112
+db 112
+db 101
+db 97
+db 114
+db 32
+db 116
+db 111
+db 32
+db 98
+db 101
+db 32
+db 99
+db 97
+db 108
+db 99
+db 117
+db 108
+db 97
+db 116
+db 101
+db 100
+db 32
+db 101
+db 120
+db 116
+db 114
+db 97
+db 10
+db 0
+align 1
+L167 label byte
+db 111
+db 102
+db 32
+db 97
+db 110
+db 10
+db 101
+db 120
+db 116
+db 114
+db 97
+db 45
+db 112
+db 114
+db 101
+db 99
+db 105
+db 115
+db 105
+db 111
+db 110
+db 0
+align 1
+L166 label byte
+db 90
+db 49
+db 32
+db 61
+db 32
+db 37
+db 46
+db 55
+db 101
+db 44
+db 32
+db 111
+db 114
+db 32
+db 90
+db 50
+db 32
+db 61
+db 32
+db 37
+db 46
+db 55
+db 101
+db 32
+db 0
+align 1
+L165 label byte
+db 44
+db 32
+db 111
+db 114
+db 32
+db 101
+db 120
+db 97
+db 99
+db 116
+db 32
+db 114
+db 97
+db 116
+db 105
+db 111
+db 110
+db 97
+db 108
+db 32
+db 97
+db 114
+db 105
+db 116
+db 104
+db 109
+db 101
+db 116
+db 105
+db 99
+db 32
+db 97
+db 32
+db 114
+db 101
+db 115
+db 117
+db 108
+db 116
+db 10
+db 0
+align 1
+L164 label byte
+db 66
+db 101
+db 99
+db 97
+db 117
+db 115
+db 101
+db 32
+db 111
+db 102
+db 32
+db 117
+db 110
+db 117
+db 115
+db 117
+db 97
+db 108
+db 32
+db 82
+db 97
+db 100
+db 105
+db 120
+db 32
+db 61
+db 32
+db 37
+db 102
+db 0
+align 1
+L160 label byte
+db 9
+db 85
+db 50
+db 32
+db 61
+db 32
+db 37
+db 46
+db 55
+db 101
+db 44
+db 32
+db 90
+db 50
+db 32
+db 45
+db 32
+db 85
+db 50
+db 32
+db 61
+db 32
+db 37
+db 46
+db 55
+db 101
+db 10
+db 0
+align 1
+L159 label byte
+db 9
+db 85
+db 49
+db 32
+db 61
+db 32
+db 37
+db 46
+db 55
+db 101
+db 44
+db 32
+db 90
+db 49
+db 32
+db 45
+db 32
+db 85
+db 49
+db 32
+db 61
+db 32
+db 37
+db 46
+db 55
+db 101
+db 10
+db 0
+align 1
+L158 label byte
+db 80
+db 114
+db 101
+db 99
+db 105
+db 115
+db 105
+db 111
+db 110
+db 0
+align 1
+L157 label byte
+db 0
+align 1
+L150 label byte
+db 84
+db 104
+db 97
+db 116
+db 32
+db 102
+db 101
+db 97
+db 116
+db 117
+db 114
+db 101
+db 32
+db 105
+db 115
+db 32
+db 110
+db 111
+db 116
+db 32
+db 116
+db 101
+db 115
+db 116
+db 101
+db 100
+db 32
+db 102
+db 117
+db 114
+db 116
+db 104
+db 101
+db 114
+db 32
+db 98
+db 121
+db 32
+db 116
+db 104
+db 105
+db 115
+db 32
+db 112
+db 114
+db 111
+db 103
+db 114
+db 97
+db 109
+db 46
+db 10
+db 0
+align 1
+L145 label byte
+db 80
+db 111
+db 115
+db 115
+db 105
+db 98
+db 108
+db 121
+db 32
+db 115
+db 111
+db 109
+db 101
+db 32
+db 112
+db 97
+db 114
+db 116
+db 32
+db 111
+db 102
+db 32
+db 116
+db 104
+db 105
+db 115
+db 0
+align 1
+L144 label byte
+db 98
+db 121
+db 32
+db 101
+db 120
+db 116
+db 114
+db 97
+db 45
+db 112
+db 114
+db 101
+db 99
+db 105
+db 115
+db 101
+db 32
+db 101
+db 118
+db 97
+db 108
+db 117
+db 97
+db 116
+db 105
+db 111
+db 110
+db 32
+db 111
+db 102
+db 32
+db 97
+db 114
+db 105
+db 116
+db 104
+db 109
+db 101
+db 116
+db 105
+db 99
+db 32
+db 115
+db 117
+db 98
+db 101
+db 120
+db 112
+db 114
+db 101
+db 115
+db 115
+db 105
+db 111
+db 110
+db 115
+db 46
+db 10
+db 0
+align 1
+L143 label byte
+db 97
+db 114
+db 101
+db 32
+db 115
+db 121
+db 109
+db 112
+db 116
+db 111
+db 109
+db 115
+db 32
+db 111
+db 102
+db 32
+db 105
+db 110
+db 99
+db 111
+db 110
+db 115
+db 105
+db 115
+db 116
+db 101
+db 110
+db 99
+db 105
+db 101
+db 115
+db 32
+db 105
+db 110
+db 116
+db 114
+db 111
+db 100
+db 117
+db 99
+db 101
+db 100
+db 10
+db 0
+align 1
+L142 label byte
+db 114
+db 101
+db 115
+db 112
+db 101
+db 99
+db 116
+db 105
+db 118
+db 101
+db 108
+db 121
+db 32
+db 32
+db 37
+db 46
+db 55
+db 101
+db 44
+db 32
+db 32
+db 37
+db 46
+db 55
+db 101
+db 44
+db 32
+db 32
+db 37
+db 46
+db 55
+db 101
+db 44
+db 10
+db 0
+align 1
+L141 label byte
+db 68
+db 105
+db 115
+db 97
+db 103
+db 114
+db 101
+db 101
+db 109
+db 101
+db 110
+db 116
+db 115
+db 32
+db 97
+db 109
+db 111
+db 110
+db 103
+db 32
+db 116
+db 104
+db 101
+db 32
+db 118
+db 97
+db 108
+db 117
+db 101
+db 115
+db 32
+db 88
+db 49
+db 44
+db 32
+db 89
+db 49
+db 44
+db 32
+db 90
+db 49
+db 44
+db 10
+db 0
+align 1
+L119 label byte
+db 80
+db 114
+db 101
+db 99
+db 105
+db 115
+db 105
+db 111
+db 110
+db 32
+db 119
+db 111
+db 114
+db 115
+db 101
+db 32
+db 116
+db 104
+db 97
+db 110
+db 32
+db 53
+db 32
+db 100
+db 101
+db 99
+db 105
+db 109
+db 97
+db 108
+db 32
+db 102
+db 105
+db 103
+db 117
+db 114
+db 101
+db 115
+db 32
+db 32
+db 0
+align 1
+L117 label byte
+db 84
+db 104
+db 101
+db 32
+db 110
+db 117
+db 109
+db 98
+db 101
+db 114
+db 32
+db 111
+db 102
+db 32
+db 115
+db 105
+db 103
+db 110
+db 105
+db 102
+db 105
+db 99
+db 97
+db 110
+db 116
+db 32
+db 100
+db 105
+db 103
+db 105
+db 116
+db 115
+db 32
+db 111
+db 102
+db 32
+db 116
+db 104
+db 101
+db 32
+db 82
+db 97
+db 100
+db 105
+db 120
+db 32
+db 105
+db 115
+db 32
+db 37
+db 102
+db 32
+db 46
+db 10
+db 0
+align 1
+L116 label byte
+db 108
+db 111
+db 103
+db 97
+db 114
+db 105
+db 116
+db 104
+db 109
+db 105
+db 99
+db 32
+db 101
+db 110
+db 99
+db 111
+db 100
+db 105
+db 110
+db 103
+db 32
+db 104
+db 97
+db 115
+db 32
+db 112
+db 114
+db 101
+db 99
+db 105
+db 115
+db 105
+db 111
+db 110
+db 32
+db 99
+db 104
+db 97
+db 114
+db 97
+db 99
+db 116
+db 101
+db 114
+db 105
+db 122
+db 101
+db 100
+db 32
+db 115
+db 111
+db 108
+db 101
+db 108
+db 121
+db 32
+db 98
+db 121
+db 32
+db 85
+db 49
+db 46
+db 10
+db 0
+align 1
+L113 label byte
+db 111
+db 102
+db 32
+db 115
+db 105
+db 103
+db 110
+db 105
+db 102
+db 105
+db 99
+db 97
+db 110
+db 116
+db 32
+db 100
+db 105
+db 103
+db 105
+db 116
+db 115
+db 32
+db 98
+db 117
+db 116
+db 44
+db 32
+db 98
+db 121
+db 32
+db 105
+db 116
+db 115
+db 101
+db 108
+db 102
+db 44
+db 32
+db 116
+db 104
+db 105
+db 115
+db 32
+db 105
+db 115
+db 32
+db 97
+db 32
+db 109
+db 105
+db 110
+db 111
+db 114
+db 32
+db 102
+db 108
+db 97
+db 119
+db 46
+db 10
+db 0
+align 1
+L112 label byte
+db 80
+db 114
+db 101
+db 99
+db 105
+db 115
+db 105
+db 111
+db 110
+db 32
+db 99
+db 97
+db 110
+db 110
+db 111
+db 116
+db 32
+db 98
+db 101
+db 32
+db 99
+db 104
+db 97
+db 114
+db 97
+db 99
+db 116
+db 101
+db 114
+db 105
+db 122
+db 101
+db 100
+db 32
+db 98
+db 121
+db 32
+db 97
+db 110
+db 32
+db 73
+db 110
+db 116
+db 101
+db 103
+db 101
+db 114
+db 32
+db 110
+db 117
+db 109
+db 98
+db 101
+db 114
+db 10
+db 0
+align 1
+L99 label byte
+db 67
+db 111
+db 109
+db 112
+db 97
+db 114
+db 105
+db 115
+db 111
+db 110
+db 32
+db 105
+db 115
+db 32
+db 102
+db 117
+db 122
+db 122
+db 121
+db 44
+db 88
+db 61
+db 49
+db 32
+db 98
+db 117
+db 116
+db 32
+db 88
+db 45
+db 49
+db 47
+db 50
+db 45
+db 49
+db 47
+db 50
+db 32
+db 33
+db 61
+db 32
+db 48
+db 0
+align 1
+L95 label byte
+db 40
+db 49
+db 45
+db 85
+db 49
+db 41
+db 45
+db 49
+db 47
+db 50
+db 32
+db 60
+db 32
+db 49
+db 47
+db 50
+db 32
+db 105
+db 115
+db 32
+db 70
+db 65
+db 76
+db 83
+db 69
+db 44
+db 32
+db 112
+db 114
+db 111
+db 103
+db 46
+db 32
+db 102
+db 97
+db 105
+db 108
+db 115
+db 63
+db 0
+align 4
+L93 label byte
+dd 00H
+dd 040240000H
+align 1
+L88 label byte
+db 82
+db 97
+db 100
+db 105
+db 120
+db 32
+db 105
+db 115
+db 32
+db 110
+db 111
+db 116
+db 32
+db 97
+db 115
+db 32
+db 103
+db 111
+db 111
+db 100
+db 32
+db 97
+db 115
+db 32
+db 50
+db 32
+db 111
+db 114
+db 32
+db 49
+db 48
+db 0
+align 1
+L84 label byte
+db 82
+db 97
+db 100
+db 105
+db 120
+db 32
+db 105
+db 115
+db 32
+db 116
+db 111
+db 111
+db 32
+db 98
+db 105
+db 103
+db 58
+db 32
+db 114
+db 111
+db 117
+db 110
+db 100
+db 111
+db 102
+db 102
+db 32
+db 112
+db 114
+db 111
+db 98
+db 108
+db 101
+db 109
+db 115
+db 0
+align 1
+L82 label byte
+db 77
+db 89
+db 83
+db 84
+db 69
+db 82
+db 89
+db 58
+db 32
+db 114
+db 101
+db 99
+db 97
+db 108
+db 99
+db 117
+db 108
+db 97
+db 116
+db 101
+db 100
+db 32
+db 82
+db 97
+db 100
+db 105
+db 120
+db 32
+db 61
+db 32
+db 37
+db 46
+db 55
+db 101
+db 32
+db 46
+db 10
+db 0
+align 1
+L81 label byte
+db 82
+db 97
+db 100
+db 105
+db 120
+db 32
+db 99
+db 111
+db 110
+db 102
+db 105
+db 114
+db 109
+db 101
+db 100
+db 46
+db 10
+db 0
+align 4
+L78 label byte
+dd 047ae147bH
+dd 03f847ae1H
+align 1
+L77 label byte
+db 103
+db 101
+db 116
+db 115
+db 32
+db 98
+db 101
+db 116
+db 116
+db 101
+db 114
+db 32
+db 99
+db 108
+db 111
+db 115
+db 101
+db 115
+db 116
+db 32
+db 114
+db 101
+db 108
+db 97
+db 116
+db 105
+db 118
+db 101
+db 32
+db 115
+db 101
+db 112
+db 97
+db 114
+db 97
+db 116
+db 105
+db 111
+db 110
+db 32
+db 85
+db 49
+db 32
+db 61
+db 32
+db 37
+db 46
+db 55
+db 101
+db 32
+db 46
+db 10
+db 0
+align 1
+L76 label byte
+db 99
+db 111
+db 110
+db 102
+db 105
+db 114
+db 109
+db 115
+db 32
+db 99
+db 108
+db 111
+db 115
+db 101
+db 115
+db 116
+db 32
+db 114
+db 101
+db 108
+db 97
+db 116
+db 105
+db 118
+db 101
+db 32
+db 115
+db 101
+db 112
+db 97
+db 114
+db 97
+db 116
+db 105
+db 111
+db 110
+db 32
+db 85
+db 49
+db 32
+db 46
+db 10
+db 0
+align 1
+L61 label byte
+db 82
+db 101
+db 99
+db 97
+db 108
+db 99
+db 117
+db 108
+db 97
+db 116
+db 105
+db 110
+db 103
+db 32
+db 114
+db 97
+db 100
+db 105
+db 120
+db 32
+db 97
+db 110
+db 100
+db 32
+db 112
+db 114
+db 101
+db 99
+db 105
+db 115
+db 105
+db 111
+db 110
+db 10
+db 32
+db 0
+align 1
+L60 label byte
+db 67
+db 108
+db 111
+db 115
+db 101
+db 115
+db 116
+db 32
+db 114
+db 101
+db 108
+db 97
+db 116
+db 105
+db 118
+db 101
+db 32
+db 115
+db 101
+db 112
+db 97
+db 114
+db 97
+db 116
+db 105
+db 111
+db 110
+db 32
+db 102
+db 111
+db 117
+db 110
+db 100
+db 32
+db 105
+db 115
+db 32
+db 85
+db 49
+db 32
+db 61
+db 32
+db 37
+db 46
+db 55
+db 101
+db 32
+db 46
+db 10
+db 10
+db 0
+align 1
+L54 label byte
+db 82
+db 97
+db 100
+db 105
+db 120
+db 32
+db 61
+db 32
+db 37
+db 102
+db 32
+db 46
+db 10
+db 0
+align 1
+L45 label byte
+db 83
+db 101
+db 97
+db 114
+db 99
+db 104
+db 105
+db 110
+db 103
+db 32
+db 102
+db 111
+db 114
+db 32
+db 82
+db 97
+db 100
+db 105
+db 120
+db 32
+db 97
+db 110
+db 100
+db 32
+db 80
+db 114
+db 101
+db 99
+db 105
+db 115
+db 105
+db 111
+db 110
+db 46
+db 10
+db 0
+align 1
+L44 label byte
+db 10
+db 0
+align 1
+L43 label byte
+db 45
+db 49
+db 44
+db 32
+db 48
+db 44
+db 32
+db 49
+db 47
+db 50
+db 44
+db 32
+db 49
+db 44
+db 32
+db 50
+db 44
+db 32
+db 51
+db 44
+db 32
+db 52
+db 44
+db 32
+db 53
+db 44
+db 32
+db 57
+db 44
+db 32
+db 50
+db 55
+db 44
+db 32
+db 51
+db 50
+db 32
+db 38
+db 32
+db 50
+db 52
+db 48
+db 32
+db 97
+db 114
+db 101
+db 32
+db 79
+db 46
+db 75
+db 46
+db 10
+db 0
+align 1
+L38 label byte
+db 53
+db 32
+db 33
+db 61
+db 32
+db 52
+db 43
+db 49
+db 44
+db 32
+db 50
+db 52
+db 48
+db 47
+db 51
+db 32
+db 33
+db 61
+db 32
+db 56
+db 48
+db 44
+db 32
+db 50
+db 52
+db 48
+db 47
+db 52
+db 32
+db 33
+db 61
+db 32
+db 54
+db 48
+db 44
+db 32
+db 111
+db 114
+db 32
+db 50
+db 52
+db 48
+db 47
+db 53
+db 32
+db 33
+db 61
+db 32
+db 52
+db 56
+db 0
+align 1
+L34 label byte
+db 57
+db 32
+db 33
+db 61
+db 32
+db 51
+db 42
+db 51
+db 44
+db 32
+db 50
+db 55
+db 32
+db 33
+db 61
+db 32
+db 57
+db 42
+db 51
+db 44
+db 32
+db 51
+db 50
+db 32
+db 33
+db 61
+db 32
+db 56
+db 42
+db 52
+db 44
+db 32
+db 111
+db 114
+db 32
+db 51
+db 50
+db 45
+db 50
+db 55
+db 45
+db 52
+db 45
+db 49
+db 32
+db 33
+db 61
+db 32
+db 48
+db 0
+align 1
+L30 label byte
+db 49
+db 47
+db 50
+db 32
+db 43
+db 32
+db 40
+db 45
+db 49
+db 41
+db 32
+db 43
+db 32
+db 49
+db 47
+db 50
+db 32
+db 33
+db 61
+db 32
+db 48
+db 0
+align 1
+L26 label byte
+db 45
+db 49
+db 43
+db 49
+db 32
+db 33
+db 61
+db 32
+db 48
+db 44
+db 32
+db 40
+db 45
+db 49
+db 41
+db 43
+db 97
+db 98
+db 115
+db 40
+db 49
+db 41
+db 32
+db 33
+db 61
+db 32
+db 48
+db 44
+db 32
+db 111
+db 114
+db 32
+db 45
+db 49
+db 43
+db 40
+db 45
+db 49
+db 41
+db 42
+db 40
+db 45
+db 49
+db 41
+db 32
+db 33
+db 61
+db 32
+db 48
+db 0
+align 1
+L22 label byte
+db 51
+db 32
+db 33
+db 61
+db 32
+db 50
+db 43
+db 49
+db 44
+db 32
+db 52
+db 32
+db 33
+db 61
+db 32
+db 51
+db 43
+db 49
+db 44
+db 32
+db 52
+db 43
+db 50
+db 42
+db 40
+db 45
+db 50
+db 41
+db 32
+db 33
+db 61
+db 32
+db 48
+db 44
+db 32
+db 111
+db 114
+db 32
+db 52
+db 45
+db 51
+db 45
+db 49
+db 32
+db 33
+db 61
+db 32
+db 48
+db 0
+align 4
+L20 label byte
+dd 0d2f1a9fcH
+dd 03f50624dH
+align 1
+L19 label byte
+db 67
+db 111
+db 109
+db 112
+db 97
+db 114
+db 105
+db 115
+db 111
+db 110
+db 32
+db 97
+db 108
+db 108
+db 101
+db 103
+db 101
+db 115
+db 32
+db 116
+db 104
+db 97
+db 116
+db 32
+db 45
+db 48
+db 46
+db 48
+db 32
+db 105
+db 115
+db 32
+db 78
+db 111
+db 110
+db 45
+db 122
+db 101
+db 114
+db 111
+db 33
+db 10
+db 0
+align 1
+L14 label byte
+db 48
+db 43
+db 48
+db 32
+db 33
+db 61
+db 32
+db 48
+db 44
+db 32
+db 49
+db 45
+db 49
+db 32
+db 33
+db 61
+db 32
+db 48
+db 44
+db 32
+db 49
+db 32
+db 60
+db 61
+db 32
+db 48
+db 44
+db 32
+db 111
+db 114
+db 32
+db 49
+db 43
+db 49
+db 32
+db 33
+db 61
+db 32
+db 50
+db 0
+align 1
+L12 label byte
+db 80
+db 114
+db 111
+db 103
+db 114
+db 97
+db 109
+db 32
+db 105
+db 115
+db 32
+db 110
+db 111
+db 119
+db 32
+db 82
+db 85
+db 78
+db 78
+db 73
+db 78
+db 71
+db 32
+db 116
+db 101
+db 115
+db 116
+db 115
+db 32
+db 111
+db 110
+db 32
+db 115
+db 109
+db 97
+db 108
+db 108
+db 32
+db 105
+db 110
+db 116
+db 101
+db 103
+db 101
+db 114
+db 115
+db 58
+db 10
+db 0
+align 4
+L8 label byte
+dd 00H
+dd 03ff00000H
+align 4
+L7 label byte
+dd 00H
+dd 00H
+align 1
+L2 label byte
+db 10
+db 42
+db 32
+db 42
+db 32
+db 42
+db 32
+db 70
+db 76
+db 79
+db 65
+db 84
+db 73
+db 78
+db 71
+db 45
+db 80
+db 79
+db 73
+db 78
+db 84
+db 32
+db 69
+db 82
+db 82
+db 79
+db 82
+db 32
+db 42
+db 32
+db 42
+db 32
+db 42
+db 10
+db 0
+_TEXT ends
+end
diff --git a/lcc/x86/win32/tst/sort.1bk b/lcc/x86/win32/tst/sort.1bk
new file mode 100755
index 0000000..380d529
--- /dev/null
+++ b/lcc/x86/win32/tst/sort.1bk
@@ -0,0 +1,20 @@
+exchange(1,9)
+exchange(3,7)
+exchange(5,6)
+exchange(0,5)
+exchange(0,3)
+exchange(0,0)
+exchange(1,2)
+exchange(6,6)
+exchange(8,9)
+exchange(7,8)
+-51
+-1
+0
+1
+3
+10
+18
+32
+567
+789
diff --git a/lcc/x86/win32/tst/sort.2bk b/lcc/x86/win32/tst/sort.2bk
new file mode 100755
index 0000000..27488a1
--- /dev/null
+++ b/lcc/x86/win32/tst/sort.2bk
@@ -0,0 +1,5 @@
+tst/sort.c:23: warning: missing return value
+tst/sort.c:30: warning: missing return value
+tst/sort.c:37: warning: missing return value
+tst/sort.c:41: warning: missing return value
+tst/sort.c:65: warning: missing return value
diff --git a/lcc/x86/win32/tst/sort.sbk b/lcc/x86/win32/tst/sort.sbk
new file mode 100755
index 0000000..cdedc1c
--- /dev/null
+++ b/lcc/x86/win32/tst/sort.sbk
@@ -0,0 +1,324 @@
+.486
+.model flat
+extrn __fltused:near
+extrn __ftol:near
+_DATA segment
+public _in
+align 4
+_in label byte
+dd 10
+dd 32
+dd -1
+dd 567
+dd 3
+dd 18
+dd 1
+dd -51
+dd 789
+dd 0
+public _main
+_DATA ends
+_TEXT segment
+_main:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,4
+push 10
+lea edi,(_in)
+push edi
+call _sort
+add esp,8
+mov dword ptr (-4)[ebp],0
+jmp L5
+L2:
+mov edi,dword ptr (-4)[ebp]
+mov edi,dword ptr (_in)[edi*4]
+push edi
+call _putd
+add esp,4
+push 10
+call _putchar
+add esp,4
+L3:
+inc dword ptr (-4)[ebp]
+L5:
+mov edi,dword ptr (-4)[ebp]
+cmp edi,10
+jb L2
+mov eax,0
+L1:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _putd
+_putd:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+cmp dword ptr (20)[ebp],0
+jge L7
+push 45
+call _putchar
+add esp,4
+neg dword ptr (20)[ebp]
+L7:
+mov eax,dword ptr (20)[ebp]
+mov edi,10
+cdq
+idiv edi
+cmp eax,0
+je L9
+mov eax,dword ptr (20)[ebp]
+mov edi,10
+cdq
+idiv edi
+push eax
+call _putd
+add esp,4
+L9:
+mov eax,dword ptr (20)[ebp]
+mov edi,10
+cdq
+idiv edi
+lea edi,(48)[edx]
+push edi
+call _putchar
+add esp,4
+mov eax,0
+L6:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _sort
+_sort:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov edi,dword ptr (24)[ebp]
+sub edi,1
+mov dword ptr (24)[ebp],edi
+push edi
+push 0
+mov edi,dword ptr (20)[ebp]
+mov dword ptr (_xx),edi
+push edi
+call _quick
+add esp,12
+mov eax,0
+L11:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _quick
+_quick:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,4
+mov edi,dword ptr (28)[ebp]
+cmp dword ptr (24)[ebp],edi
+jl L13
+jmp L12
+L13:
+mov edi,dword ptr (28)[ebp]
+push edi
+mov edi,dword ptr (24)[ebp]
+push edi
+mov edi,dword ptr (20)[ebp]
+push edi
+call _partition
+add esp,12
+mov dword ptr (-4)[ebp],eax
+mov edi,dword ptr (-4)[ebp]
+sub edi,1
+push edi
+mov edi,dword ptr (24)[ebp]
+push edi
+mov edi,dword ptr (20)[ebp]
+push edi
+call _quick
+add esp,12
+mov edi,dword ptr (28)[ebp]
+push edi
+mov edi,dword ptr (-4)[ebp]
+lea edi,(1)[edi]
+push edi
+mov edi,dword ptr (20)[ebp]
+push edi
+call _quick
+add esp,12
+mov eax,0
+L12:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _partition
+_partition:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,8
+inc dword ptr (28)[ebp]
+mov edi,dword ptr (24)[ebp]
+mov dword ptr (-8)[ebp],edi
+mov edi,dword ptr (-8)[ebp]
+mov esi,dword ptr (20)[ebp]
+mov edi,dword ptr [esi][edi*4]
+mov dword ptr (-4)[ebp],edi
+jmp L17
+L16:
+inc dword ptr (24)[ebp]
+jmp L20
+L19:
+inc dword ptr (24)[ebp]
+L20:
+mov edi,dword ptr (24)[ebp]
+mov esi,dword ptr (20)[ebp]
+mov ebx,dword ptr (-4)[ebp]
+cmp dword ptr [esi][edi*4],ebx
+jl L19
+dec dword ptr (28)[ebp]
+jmp L23
+L22:
+dec dword ptr (28)[ebp]
+L23:
+mov edi,dword ptr (28)[ebp]
+mov esi,dword ptr (20)[ebp]
+mov ebx,dword ptr (-4)[ebp]
+cmp dword ptr [esi][edi*4],ebx
+jg L22
+mov edi,dword ptr (28)[ebp]
+cmp dword ptr (24)[ebp],edi
+jge L25
+mov edi,dword ptr (20)[ebp]
+mov esi,dword ptr (28)[ebp]
+lea esi,[edi][esi*4]
+push esi
+mov esi,dword ptr (24)[ebp]
+lea edi,[edi][esi*4]
+push edi
+call _exchange
+add esp,8
+L25:
+L17:
+mov edi,dword ptr (28)[ebp]
+cmp dword ptr (24)[ebp],edi
+jl L16
+mov edi,dword ptr (20)[ebp]
+mov esi,dword ptr (28)[ebp]
+lea esi,[edi][esi*4]
+push esi
+mov esi,dword ptr (-8)[ebp]
+lea edi,[edi][esi*4]
+push edi
+call _exchange
+add esp,8
+mov eax,dword ptr (28)[ebp]
+L15:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _exchange
+_exchange:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,4
+mov edi,dword ptr (_xx)
+mov esi,4
+mov ebx,dword ptr (24)[ebp]
+sub ebx,edi
+mov eax,ebx
+cdq
+idiv esi
+push eax
+mov ebx,dword ptr (20)[ebp]
+sub ebx,edi
+mov eax,ebx
+cdq
+idiv esi
+push eax
+lea edi,(L28)
+push edi
+call _printf
+add esp,12
+mov edi,dword ptr (20)[ebp]
+mov esi,dword ptr [edi]
+mov dword ptr (-4)[ebp],esi
+mov esi,dword ptr (24)[ebp]
+mov esi,dword ptr [esi]
+mov dword ptr [edi],esi
+mov edi,dword ptr (24)[ebp]
+mov esi,dword ptr (-4)[ebp]
+mov dword ptr [edi],esi
+mov eax,0
+L27:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+extrn _printf:near
+_TEXT segment
+_TEXT ends
+extrn _putchar:near
+_TEXT segment
+_TEXT ends
+_DATA segment
+public _xx
+align 4
+_xx label byte
+db 4 dup (0)
+_DATA ends
+_TEXT segment
+align 1
+L28 label byte
+db 101
+db 120
+db 99
+db 104
+db 97
+db 110
+db 103
+db 101
+db 40
+db 37
+db 100
+db 44
+db 37
+db 100
+db 41
+db 10
+db 0
+_TEXT ends
+end
diff --git a/lcc/x86/win32/tst/spill.1bk b/lcc/x86/win32/tst/spill.1bk
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/lcc/x86/win32/tst/spill.1bk
diff --git a/lcc/x86/win32/tst/spill.2bk b/lcc/x86/win32/tst/spill.2bk
new file mode 100755
index 0000000..f7e3521
--- /dev/null
+++ b/lcc/x86/win32/tst/spill.2bk
@@ -0,0 +1,6 @@
+tst/spill.c:1: warning: missing return value
+tst/spill.c:3: warning: missing return value
+tst/spill.c:5: warning: missing return value
+tst/spill.c:7: warning: missing return value
+tst/spill.c:9: warning: missing return value
+tst/spill.c:17: warning: missing return value
diff --git a/lcc/x86/win32/tst/spill.sbk b/lcc/x86/win32/tst/spill.sbk
new file mode 100755
index 0000000..51cf7be
--- /dev/null
+++ b/lcc/x86/win32/tst/spill.sbk
@@ -0,0 +1,259 @@
+.486
+.model flat
+extrn __fltused:near
+extrn __ftol:near
+public _main
+_TEXT segment
+_main:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov eax,0
+L1:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _f
+_f:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+call _f
+add esp,0
+mov edi,eax
+call _f
+add esp,0
+lea edi,[eax][edi]
+mov dword ptr (20)[ebp],edi
+mov eax,0
+L2:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _f2
+_f2:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,4
+call _f
+add esp,0
+mov edi,eax
+cmp dword ptr (20)[ebp],0
+je L5
+call _f
+add esp,0
+mov esi,eax
+mov dword ptr (-4)[ebp],esi
+jmp L6
+L5:
+mov dword ptr (-4)[ebp],1
+L6:
+mov esi,dword ptr (-4)[ebp]
+lea edi,[esi][edi]
+mov dword ptr (20)[ebp],edi
+mov eax,0
+L3:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _f3
+_f3:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,44
+mov dword ptr (-4)[ebp],0
+mov dword ptr (-8)[ebp],0
+mov dword ptr (-12)[ebp],0
+mov dword ptr (-16)[ebp],0
+mov dword ptr (-20)[ebp],0
+mov dword ptr (-24)[ebp],0
+mov dword ptr (-28)[ebp],0
+mov dword ptr (-32)[ebp],0
+mov dword ptr (-36)[ebp],0
+mov dword ptr (-40)[ebp],0
+mov edi,dword ptr (24)[ebp]
+lea esi,(4)[edi]
+mov dword ptr (24)[ebp],esi
+cmp dword ptr (20)[ebp],0
+je L9
+call _f
+add esp,0
+mov esi,eax
+mov dword ptr (-44)[ebp],esi
+jmp L10
+L9:
+mov dword ptr (-44)[ebp],0
+L10:
+mov esi,dword ptr (-44)[ebp]
+mov dword ptr [edi],esi
+mov eax,0
+L7:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _f4
+_f4:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,52
+mov dword ptr (-4)[ebp],0
+mov dword ptr (-8)[ebp],0
+mov dword ptr (-12)[ebp],0
+mov dword ptr (-16)[ebp],0
+mov dword ptr (-20)[ebp],0
+mov dword ptr (-24)[ebp],0
+mov edi,dword ptr (_i)
+lea esi,[edi*8]
+fld qword ptr (_a)[esi]
+fstp qword ptr (-36)[ebp]
+fld qword ptr (_b)[esi]
+fstp qword ptr (-44)[ebp]
+fld qword ptr (-36)[ebp]
+fadd qword ptr (-44)[ebp]
+fld qword ptr (L15)
+fcompp
+fstsw ax
+sahf
+je L13
+cmp edi,0
+je L13
+fld qword ptr (-36)[ebp]
+fsub qword ptr (-44)[ebp]
+fld qword ptr (L15)
+fcompp
+fstsw ax
+sahf
+je L13
+mov dword ptr (-28)[ebp],1
+jmp L14
+L13:
+mov dword ptr (-28)[ebp],0
+L14:
+mov edi,dword ptr (-28)[ebp]
+mov dword ptr (_i),edi
+mov eax,0
+L11:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _f5
+_f5:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov edi,dword ptr (_k)
+mov esi,dword ptr (_m)
+mov ebx,dword ptr (_A)
+mov edx,edi
+imul edx,esi
+lea edx,[ebx][edx*8]
+mov ecx,dword ptr (_j)
+mov eax,ecx
+imul eax,esi
+lea esi,[ebx][eax*8]
+mov ebx,dword ptr (_n)
+mov eax,dword ptr (_B)
+imul edi,ebx
+lea edi,[eax][edi*8]
+imul ecx,ebx
+lea ebx,[eax][ecx*8]
+fld qword ptr [edx]
+fmul qword ptr [esi]
+fld qword ptr [edi]
+fmul qword ptr [ebx]
+faddp st(1),st
+fstp qword ptr (_x)
+fld qword ptr [edx]
+fmul qword ptr [ebx]
+fld qword ptr [edi]
+fmul qword ptr [esi]
+fsubp st(1),st
+fstp qword ptr (_x)
+mov eax,0
+L16:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+public _x
+align 4
+_x label byte
+db 8 dup (0)
+public _B
+align 4
+_B label byte
+db 4 dup (0)
+public _A
+align 4
+_A label byte
+db 4 dup (0)
+public _n
+align 4
+_n label byte
+db 4 dup (0)
+public _m
+align 4
+_m label byte
+db 4 dup (0)
+public _k
+align 4
+_k label byte
+db 4 dup (0)
+public _j
+align 4
+_j label byte
+db 4 dup (0)
+public _i
+align 4
+_i label byte
+db 4 dup (0)
+public _b
+align 4
+_b label byte
+db 80 dup (0)
+public _a
+align 4
+_a label byte
+db 80 dup (0)
+_DATA ends
+_TEXT segment
+align 4
+L15 label byte
+dd 00H
+dd 00H
+_TEXT ends
+end
diff --git a/lcc/x86/win32/tst/stdarg.1bk b/lcc/x86/win32/tst/stdarg.1bk
new file mode 100755
index 0000000..097aef7
--- /dev/null
+++ b/lcc/x86/win32/tst/stdarg.1bk
@@ -0,0 +1,6 @@
+test 1
+test 2
+test 3
+test 4
+test 5.000000
+{1 2 3 4} {1 2 3 4} {1 2 3 4} {1 2 3 4} {1 2 3 4} {1 2 3 4}
diff --git a/lcc/x86/win32/tst/stdarg.2bk b/lcc/x86/win32/tst/stdarg.2bk
new file mode 100755
index 0000000..a832cf9
--- /dev/null
+++ b/lcc/x86/win32/tst/stdarg.2bk
@@ -0,0 +1 @@
+tst/stdarg.c:51: warning: missing return value
diff --git a/lcc/x86/win32/tst/stdarg.sbk b/lcc/x86/win32/tst/stdarg.sbk
new file mode 100755
index 0000000..35c2f66
--- /dev/null
+++ b/lcc/x86/win32/tst/stdarg.sbk
@@ -0,0 +1,415 @@
+.486
+.model flat
+extrn __fltused:near
+extrn __ftol:near
+_DATA segment
+public _x
+align 4
+_x label byte
+dd 1
+dd 2
+dd 3
+dd 4
+public _main
+_DATA ends
+_TEXT segment
+_main:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,8
+lea edi,(L2)
+push edi
+call _print
+add esp,4
+lea edi,(L4)
+push edi
+lea edi,(L3)
+push edi
+call _print
+add esp,8
+push 10
+push 3
+lea edi,(L5)
+push edi
+call _print
+add esp,12
+push 10
+push 4
+lea edi,(L8)
+push edi
+lea edi,(L7)
+push edi
+lea edi,(L6)
+push edi
+call _print
+add esp,20
+push 10
+fld qword ptr (L10)
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L8)
+push edi
+lea edi,(L7)
+push edi
+lea edi,(L9)
+push edi
+call _print
+add esp,24
+lea edi,(_x)
+mov dword ptr (-8)[ebp],edi
+mov esi,edi
+mov dword ptr (-4)[ebp],esi
+sub esp,16
+mov edi,esp
+mov ecx,16
+rep movsb
+mov edi,dword ptr (-8)[ebp]
+mov esi,edi
+sub esp,16
+mov edi,esp
+mov ecx,16
+rep movsb
+mov edi,dword ptr (-8)[ebp]
+mov esi,edi
+sub esp,16
+mov edi,esp
+mov ecx,16
+rep movsb
+mov edi,dword ptr (-8)[ebp]
+mov esi,edi
+sub esp,16
+mov edi,esp
+mov ecx,16
+rep movsb
+mov edi,dword ptr (-8)[ebp]
+mov esi,edi
+sub esp,16
+mov edi,esp
+mov ecx,16
+rep movsb
+mov edi,dword ptr (-8)[ebp]
+mov esi,edi
+sub esp,16
+mov edi,esp
+mov ecx,16
+rep movsb
+lea edi,(L11)
+push edi
+call _print
+add esp,100
+mov eax,0
+L1:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _print
+_print:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,28
+lea edi,(24)[ebp]
+mov dword ptr (-4)[ebp],edi
+jmp L17
+L14:
+mov edi,dword ptr (20)[ebp]
+movsx edi,byte ptr [edi]
+cmp edi,37
+jne L18
+mov edi,dword ptr (20)[ebp]
+lea edi,(1)[edi]
+mov dword ptr (20)[ebp],edi
+movsx edi,byte ptr [edi]
+mov dword ptr (-8)[ebp],edi
+mov edi,dword ptr (-8)[ebp]
+cmp edi,115
+je L34
+cmp edi,115
+jg L39
+L38:
+mov edi,dword ptr (-8)[ebp]
+cmp edi,98
+jl L20
+cmp edi,102
+jg L20
+jmp dword ptr (L40-392)[edi*4]
+_TEXT ends
+_TEXT segment
+align 4
+L40 label byte
+dd L23
+dd L28
+dd L30
+dd L20
+dd L36
+_TEXT ends
+_TEXT segment
+L39:
+cmp dword ptr (-8)[ebp],119
+je L32
+jmp L20
+L23:
+mov edi,dword ptr (-4)[ebp]
+lea edi,(16)[edi]
+mov dword ptr (-28)[ebp],edi
+mov dword ptr (-4)[ebp],edi
+lea edi,(-24)[ebp]
+mov esi,dword ptr (-28)[ebp]
+lea esi,(-16)[esi]
+mov ecx,16
+rep movsb
+mov edi,dword ptr (-12)[ebp]
+push edi
+mov edi,dword ptr (-16)[ebp]
+push edi
+mov edi,dword ptr (-20)[ebp]
+push edi
+mov edi,dword ptr (-24)[ebp]
+push edi
+lea edi,(L24)
+push edi
+call _printf
+add esp,20
+jmp L19
+L28:
+mov edi,dword ptr (-4)[ebp]
+lea edi,(4)[edi]
+mov dword ptr (-4)[ebp],edi
+movsx edi,byte ptr (-4)[edi]
+push edi
+lea edi,(L29)
+push edi
+call _printf
+add esp,8
+jmp L19
+L30:
+mov edi,dword ptr (-4)[ebp]
+lea edi,(4)[edi]
+mov dword ptr (-4)[ebp],edi
+mov edi,dword ptr (-4)[edi]
+push edi
+lea edi,(L31)
+push edi
+call _printf
+add esp,8
+jmp L19
+L32:
+mov edi,dword ptr (-4)[ebp]
+lea edi,(4)[edi]
+mov dword ptr (-4)[ebp],edi
+movsx edi,word ptr (-4)[edi]
+push edi
+lea edi,(L33)
+push edi
+call _printf
+add esp,8
+jmp L19
+L34:
+mov edi,dword ptr (-4)[ebp]
+lea edi,(4)[edi]
+mov dword ptr (-4)[ebp],edi
+mov edi,dword ptr (-4)[edi]
+push edi
+lea edi,(L35)
+push edi
+call _printf
+add esp,8
+jmp L19
+L36:
+mov edi,dword ptr (-4)[ebp]
+lea edi,(8)[edi]
+mov dword ptr (-4)[ebp],edi
+fld qword ptr (-8)[edi]
+sub esp,8
+fstp qword ptr [esp]
+lea edi,(L37)
+push edi
+call _printf
+add esp,12
+jmp L19
+L20:
+mov edi,dword ptr (20)[ebp]
+movsx edi,byte ptr [edi]
+push edi
+lea edi,(L29)
+push edi
+call _printf
+add esp,8
+jmp L19
+L18:
+mov edi,dword ptr (20)[ebp]
+movsx edi,byte ptr [edi]
+push edi
+lea edi,(L29)
+push edi
+call _printf
+add esp,8
+L19:
+L15:
+inc dword ptr (20)[ebp]
+L17:
+mov edi,dword ptr (20)[ebp]
+movsx edi,byte ptr [edi]
+cmp edi,0
+jne L14
+mov dword ptr (-4)[ebp],0
+mov eax,0
+L12:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+extrn _printf:near
+_TEXT segment
+_TEXT ends
+_TEXT segment
+align 1
+L37 label byte
+db 37
+db 102
+db 0
+align 1
+L35 label byte
+db 37
+db 115
+db 0
+align 1
+L33 label byte
+db 37
+db 120
+db 0
+align 1
+L31 label byte
+db 37
+db 100
+db 0
+align 1
+L29 label byte
+db 37
+db 99
+db 0
+align 1
+L24 label byte
+db 123
+db 37
+db 100
+db 32
+db 37
+db 100
+db 32
+db 37
+db 100
+db 32
+db 37
+db 100
+db 125
+db 0
+align 1
+L11 label byte
+db 37
+db 98
+db 32
+db 37
+db 98
+db 32
+db 37
+db 98
+db 32
+db 37
+db 98
+db 32
+db 37
+db 98
+db 32
+db 37
+db 98
+db 10
+db 0
+align 4
+L10 label byte
+dd 00H
+dd 040140000H
+align 1
+L9 label byte
+db 37
+db 115
+db 37
+db 115
+db 32
+db 37
+db 102
+db 37
+db 99
+db 0
+align 1
+L8 label byte
+db 115
+db 116
+db 0
+align 1
+L7 label byte
+db 116
+db 101
+db 0
+align 1
+L6 label byte
+db 37
+db 115
+db 37
+db 115
+db 32
+db 37
+db 119
+db 37
+db 99
+db 0
+align 1
+L5 label byte
+db 116
+db 101
+db 115
+db 116
+db 32
+db 37
+db 100
+db 37
+db 99
+db 0
+align 1
+L4 label byte
+db 50
+db 0
+align 1
+L3 label byte
+db 116
+db 101
+db 115
+db 116
+db 32
+db 37
+db 115
+db 10
+db 0
+align 1
+L2 label byte
+db 116
+db 101
+db 115
+db 116
+db 32
+db 49
+db 10
+db 0
+_TEXT ends
+end
diff --git a/lcc/x86/win32/tst/struct.1bk b/lcc/x86/win32/tst/struct.1bk
new file mode 100755
index 0000000..2358779
--- /dev/null
+++ b/lcc/x86/win32/tst/struct.1bk
@@ -0,0 +1,5 @@
+(-1,-1) is not within [10,10; 310,310]
+(1,1) is not within [10,10; 310,310]
+(20,300) is within [10,10; 310,310]
+(500,400) is not within [10,10; 310,310]
+ab
diff --git a/lcc/x86/win32/tst/struct.2bk b/lcc/x86/win32/tst/struct.2bk
new file mode 100755
index 0000000..8a01bb1
--- /dev/null
+++ b/lcc/x86/win32/tst/struct.2bk
@@ -0,0 +1,2 @@
+tst/struct.c:49: warning: missing return value
+tst/struct.c:68: warning: missing return value
diff --git a/lcc/x86/win32/tst/struct.sbk b/lcc/x86/win32/tst/struct.sbk
new file mode 100755
index 0000000..09775a9
--- /dev/null
+++ b/lcc/x86/win32/tst/struct.sbk
@@ -0,0 +1,453 @@
+.486
+.model flat
+extrn __fltused:near
+extrn __ftol:near
+public _addpoint
+_TEXT segment
+_addpoint:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov edi,dword ptr (32)[ebp]
+add dword ptr (24)[ebp],edi
+mov edi,dword ptr (36)[ebp]
+add dword ptr (28)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+lea esi,(24)[ebp]
+mov ecx,8
+rep movsb
+L1:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _canonrect
+_canonrect:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,32
+mov edi,dword ptr (32)[ebp]
+cmp dword ptr (24)[ebp],edi
+jge L10
+mov edi,dword ptr (24)[ebp]
+mov dword ptr (-20)[ebp],edi
+jmp L11
+L10:
+mov edi,dword ptr (32)[ebp]
+mov dword ptr (-20)[ebp],edi
+L11:
+mov edi,dword ptr (-20)[ebp]
+mov dword ptr (-16)[ebp],edi
+mov edi,dword ptr (36)[ebp]
+cmp dword ptr (28)[ebp],edi
+jge L20
+mov edi,dword ptr (28)[ebp]
+mov dword ptr (-24)[ebp],edi
+jmp L21
+L20:
+mov edi,dword ptr (36)[ebp]
+mov dword ptr (-24)[ebp],edi
+L21:
+mov edi,dword ptr (-24)[ebp]
+mov dword ptr (-12)[ebp],edi
+mov edi,dword ptr (32)[ebp]
+cmp dword ptr (24)[ebp],edi
+jle L26
+mov edi,dword ptr (24)[ebp]
+mov dword ptr (-28)[ebp],edi
+jmp L27
+L26:
+mov edi,dword ptr (32)[ebp]
+mov dword ptr (-28)[ebp],edi
+L27:
+mov edi,dword ptr (-28)[ebp]
+mov dword ptr (-8)[ebp],edi
+mov edi,dword ptr (36)[ebp]
+cmp dword ptr (28)[ebp],edi
+jle L37
+mov edi,dword ptr (28)[ebp]
+mov dword ptr (-32)[ebp],edi
+jmp L38
+L37:
+mov edi,dword ptr (36)[ebp]
+mov dword ptr (-32)[ebp],edi
+L38:
+mov edi,dword ptr (-32)[ebp]
+mov dword ptr (-4)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+lea esi,(-16)[ebp]
+mov ecx,16
+rep movsb
+L5:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _makepoint
+_makepoint:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,8
+mov edi,dword ptr (24)[ebp]
+mov dword ptr (-8)[ebp],edi
+mov edi,dword ptr (28)[ebp]
+mov dword ptr (-4)[ebp],edi
+mov edi,dword ptr (20)[ebp]
+lea esi,(-8)[ebp]
+mov ecx,8
+rep movsb
+L39:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _makerect
+_makerect:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,16
+lea edi,(-16)[ebp]
+lea esi,(24)[ebp]
+mov ecx,8
+rep movsb
+lea edi,(-8)[ebp]
+lea esi,(32)[ebp]
+mov ecx,8
+rep movsb
+lea esi,(-16)[ebp]
+sub esp,16
+mov edi,esp
+mov ecx,16
+rep movsb
+mov edi,dword ptr (20)[ebp]
+push edi
+call _canonrect
+add esp,20
+L42:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _ptinrect
+_ptinrect:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,4
+mov edi,dword ptr (20)[ebp]
+cmp edi,dword ptr (28)[ebp]
+jl L53
+cmp edi,dword ptr (36)[ebp]
+jge L53
+mov edi,dword ptr (32)[ebp]
+cmp dword ptr (24)[ebp],edi
+jl L53
+mov edi,dword ptr (40)[ebp]
+cmp dword ptr (24)[ebp],edi
+jge L53
+mov dword ptr (-4)[ebp],1
+jmp L54
+L53:
+mov dword ptr (-4)[ebp],0
+L54:
+mov eax,dword ptr (-4)[ebp]
+L45:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+public _y
+align 4
+_y label byte
+db 97
+db 98
+db 0
+db 1 dup (0)
+public _odd
+_DATA ends
+_TEXT segment
+_odd:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,4
+lea edi,(-4)[ebp]
+lea esi,(20)[ebp]
+mov ecx,4
+rep movsb
+lea edi,(-4)[ebp]
+push edi
+lea edi,(L56)
+push edi
+call _printf
+add esp,8
+mov eax,0
+L55:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_TEXT segment
+align 4
+L58 label byte
+dd 0
+dd 0
+align 4
+L59 label byte
+dd 320
+dd 320
+align 4
+L60 label byte
+dd -1
+dd -1
+dd 1
+dd 1
+dd 20
+dd 300
+dd 500
+dd 400
+public _main
+_TEXT ends
+_TEXT segment
+_main:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,108
+lea edi,(-68)[ebp]
+lea esi,(L58)
+mov ecx,8
+rep movsb
+lea edi,(-76)[ebp]
+lea esi,(L59)
+mov ecx,8
+rep movsb
+lea edi,(-36)[ebp]
+lea esi,(L60)
+mov ecx,32
+rep movsb
+push -10
+push -10
+lea edi,(-84)[ebp]
+push edi
+call _makepoint
+add esp,12
+lea esi,(-84)[ebp]
+sub esp,8
+mov edi,esp
+mov ecx,8
+rep movsb
+lea esi,(-76)[ebp]
+sub esp,8
+mov edi,esp
+mov ecx,8
+rep movsb
+lea edi,(-92)[ebp]
+push edi
+call _addpoint
+add esp,20
+push 10
+push 10
+lea edi,(-100)[ebp]
+push edi
+call _makepoint
+add esp,12
+lea esi,(-100)[ebp]
+sub esp,8
+mov edi,esp
+mov ecx,8
+rep movsb
+lea esi,(-68)[ebp]
+sub esp,8
+mov edi,esp
+mov ecx,8
+rep movsb
+lea edi,(-108)[ebp]
+push edi
+call _addpoint
+add esp,20
+lea esi,(-108)[ebp]
+sub esp,8
+mov edi,esp
+mov ecx,8
+rep movsb
+lea esi,(-92)[ebp]
+sub esp,8
+mov edi,esp
+mov ecx,8
+rep movsb
+lea edi,(-52)[ebp]
+push edi
+call _makerect
+add esp,20
+mov dword ptr (-4)[ebp],0
+jmp L64
+L61:
+mov edi,dword ptr (-4)[ebp]
+lea edi,[edi*8]
+mov esi,dword ptr (-32)[ebp][edi]
+push esi
+mov edi,dword ptr (-36)[ebp][edi]
+push edi
+lea edi,(-60)[ebp]
+push edi
+call _makepoint
+add esp,12
+mov edi,dword ptr (-56)[ebp]
+push edi
+mov edi,dword ptr (-4)[ebp]
+mov edi,dword ptr (-36)[ebp][edi*8]
+push edi
+lea edi,(L65)
+push edi
+call _printf
+add esp,12
+lea esi,(-52)[ebp]
+sub esp,16
+mov edi,esp
+mov ecx,16
+rep movsb
+lea esi,(-60)[ebp]
+sub esp,8
+mov edi,esp
+mov ecx,8
+rep movsb
+call _ptinrect
+add esp,24
+cmp eax,0
+jne L68
+lea edi,(L70)
+push edi
+call _printf
+add esp,4
+L68:
+mov edi,dword ptr (-40)[ebp]
+push edi
+mov edi,dword ptr (-44)[ebp]
+push edi
+mov edi,dword ptr (-48)[ebp]
+push edi
+mov edi,dword ptr (-52)[ebp]
+push edi
+lea edi,(L71)
+push edi
+call _printf
+add esp,20
+L62:
+inc dword ptr (-4)[ebp]
+L64:
+mov edi,dword ptr (-4)[ebp]
+cmp edi,4
+jb L61
+lea esi,(_y)
+sub esp,4
+mov edi,esp
+mov ecx,4
+rep movsb
+call _odd
+add esp,4
+push 0
+call _exit
+add esp,4
+mov eax,0
+L57:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+extrn _exit:near
+_TEXT segment
+_TEXT ends
+extrn _printf:near
+_TEXT segment
+_TEXT ends
+_TEXT segment
+align 1
+L71 label byte
+db 119
+db 105
+db 116
+db 104
+db 105
+db 110
+db 32
+db 91
+db 37
+db 100
+db 44
+db 37
+db 100
+db 59
+db 32
+db 37
+db 100
+db 44
+db 37
+db 100
+db 93
+db 10
+db 0
+align 1
+L70 label byte
+db 110
+db 111
+db 116
+db 32
+db 0
+align 1
+L65 label byte
+db 40
+db 37
+db 100
+db 44
+db 37
+db 100
+db 41
+db 32
+db 105
+db 115
+db 32
+db 0
+align 1
+L56 label byte
+db 37
+db 115
+db 10
+db 0
+_TEXT ends
+end
diff --git a/lcc/x86/win32/tst/switch.1bk b/lcc/x86/win32/tst/switch.1bk
new file mode 100755
index 0000000..559e8e3
--- /dev/null
+++ b/lcc/x86/win32/tst/switch.1bk
@@ -0,0 +1,76 @@
+b = 0x8
+f = 0xc
+n = 0xa
+r = 0xd
+t = 0x9
+v = 0xb
+x = 0x78
+f:
+x = 0
+x = 1
+x = 2
+x = 2
+x = 2
+x = 2
+x = 2
+x = 7
+x = 8
+x = 9
+x = 9
+x = 9
+x = 9
+x = 9
+x = 9
+x = 9
+x = 16
+x = 17
+x = 18
+x = 19
+x = 20
+g:
+1 1
+1 2
+2 3
+2 4
+2 5
+3 6
+d 6
+3 7
+d 7
+3 8
+d 8
+d 9
+d 10
+h:
+i = 8
+i = 16
+i = 120
+i = 128
+i = 248
+i = 264
+i = 272
+i = 280
+i = 288
+i = 296
+i = 304
+i = 312
+488 defaults
+x = 0x1000000
+x = 0x2000000
+x = 0x3000000
+x = 0x4000000
+x = 0x5000000
+x = 0x6000000 (default)
+x = 0x7000000 (default)
+0
+1
+2
+3
+4
+5
+0
+1
+2
+3
+4
+5
diff --git a/lcc/x86/win32/tst/switch.2bk b/lcc/x86/win32/tst/switch.2bk
new file mode 100755
index 0000000..76387b3
--- /dev/null
+++ b/lcc/x86/win32/tst/switch.2bk
@@ -0,0 +1,5 @@
+tst/switch.c:55: warning: missing return value
+tst/switch.c:73: warning: missing return value
+tst/switch.c:97: warning: missing return value
+tst/switch.c:112: warning: missing return value
+tst/switch.c:137: warning: missing return value
diff --git a/lcc/x86/win32/tst/switch.sbk b/lcc/x86/win32/tst/switch.sbk
new file mode 100755
index 0000000..d81a0ea
--- /dev/null
+++ b/lcc/x86/win32/tst/switch.sbk
@@ -0,0 +1,960 @@
+.486
+.model flat
+extrn __fltused:near
+extrn __ftol:near
+public _main
+_TEXT segment
+_main:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,8
+lea edi,(L6)
+mov dword ptr (-4)[ebp],edi
+jmp L5
+L2:
+mov edi,dword ptr (-4)[ebp]
+movsx edi,byte ptr [edi]
+push edi
+call _backslash
+add esp,4
+push eax
+mov edi,dword ptr (-4)[ebp]
+movsx edi,byte ptr [edi]
+push edi
+lea edi,(L7)
+push edi
+call _printf
+add esp,12
+L3:
+inc dword ptr (-4)[ebp]
+L5:
+mov edi,dword ptr (-4)[ebp]
+movsx edi,byte ptr [edi]
+cmp edi,0
+jne L2
+call _f
+add esp,0
+call _g
+add esp,0
+call _h
+add esp,0
+mov dword ptr (-8)[ebp],16777216
+jmp L11
+L8:
+mov edi,dword ptr (-8)[ebp]
+push edi
+call _big
+add esp,4
+L9:
+add dword ptr (-8)[ebp],16777216
+L11:
+mov edi,dword ptr (-8)[ebp]
+and edi,117440512
+cmp edi,0
+jne L8
+call _limit
+add esp,0
+mov eax,0
+L1:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _backslash
+_backslash:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov edi,dword ptr (20)[ebp]
+cmp edi,102
+je L16
+cmp edi,102
+jg L22
+L21:
+cmp dword ptr (20)[ebp],98
+je L15
+jmp L13
+L22:
+mov edi,dword ptr (20)[ebp]
+cmp edi,110
+je L17
+cmp edi,110
+jl L13
+L23:
+mov edi,dword ptr (20)[ebp]
+cmp edi,114
+je L18
+cmp edi,116
+je L19
+cmp edi,118
+je L20
+jmp L13
+L15:
+mov eax,8
+jmp L12
+L16:
+mov eax,12
+jmp L12
+L17:
+mov eax,10
+jmp L12
+L18:
+mov eax,13
+jmp L12
+L19:
+mov eax,9
+jmp L12
+L20:
+mov eax,11
+jmp L12
+L13:
+mov eax,dword ptr (20)[ebp]
+L12:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _f
+_f:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,12
+mov dword ptr (-8)[ebp],0
+lea edi,(L25)
+push edi
+call _printf
+add esp,4
+mov dword ptr (-4)[ebp],0
+L26:
+mov edi,dword ptr (-4)[ebp]
+mov dword ptr (-12)[ebp],edi
+mov edi,dword ptr (-4)[ebp]
+cmp edi,1
+jl L30
+cmp edi,20
+jg L30
+jmp dword ptr (L42-4)[edi*4]
+_TEXT ends
+_TEXT segment
+align 4
+L42 label byte
+dd L32
+dd L33
+dd L30
+dd L30
+dd L30
+dd L30
+dd L34
+dd L35
+dd L36
+dd L30
+dd L30
+dd L30
+dd L30
+dd L30
+dd L30
+dd L37
+dd L38
+dd L39
+dd L40
+dd L41
+_TEXT ends
+_TEXT segment
+L32:
+mov edi,dword ptr (-4)[ebp]
+mov dword ptr (-8)[ebp],edi
+jmp L31
+L33:
+mov edi,dword ptr (-4)[ebp]
+mov dword ptr (-8)[ebp],edi
+jmp L31
+L34:
+mov edi,dword ptr (-4)[ebp]
+mov dword ptr (-8)[ebp],edi
+jmp L31
+L35:
+mov edi,dword ptr (-4)[ebp]
+mov dword ptr (-8)[ebp],edi
+jmp L31
+L36:
+mov edi,dword ptr (-4)[ebp]
+mov dword ptr (-8)[ebp],edi
+jmp L31
+L37:
+mov edi,dword ptr (-4)[ebp]
+mov dword ptr (-8)[ebp],edi
+jmp L31
+L38:
+mov edi,dword ptr (-4)[ebp]
+mov dword ptr (-8)[ebp],edi
+jmp L31
+L39:
+mov edi,dword ptr (-4)[ebp]
+mov dword ptr (-8)[ebp],edi
+jmp L31
+L40:
+mov edi,dword ptr (-4)[ebp]
+mov dword ptr (-8)[ebp],edi
+jmp L31
+L41:
+mov edi,dword ptr (-4)[ebp]
+mov dword ptr (-8)[ebp],edi
+L30:
+L31:
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L44)
+push edi
+call _printf
+add esp,8
+L27:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],20
+jle L26
+mov eax,0
+L24:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _g
+_g:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,4
+lea edi,(L46)
+push edi
+call _printf
+add esp,4
+mov dword ptr (-4)[ebp],1
+L47:
+mov edi,dword ptr (-4)[ebp]
+cmp edi,1001
+jl L64
+cmp edi,1004
+jg L65
+jmp dword ptr (L66-4004)[edi*4]
+_TEXT ends
+_TEXT segment
+align 4
+L66 label byte
+dd L60
+dd L60
+dd L60
+dd L60
+_TEXT ends
+_TEXT segment
+L64:
+mov edi,dword ptr (-4)[ebp]
+cmp edi,1
+jl L51
+cmp edi,8
+jg L51
+jmp dword ptr (L68-4)[edi*4]
+_TEXT ends
+_TEXT segment
+align 4
+L68 label byte
+dd L53
+dd L53
+dd L55
+dd L55
+dd L55
+dd L57
+dd L57
+dd L57
+_TEXT ends
+_TEXT segment
+L65:
+mov edi,dword ptr (-4)[ebp]
+cmp edi,3001
+jl L51
+cmp edi,3004
+jg L51
+jmp dword ptr (L70-12004)[edi*4]
+_TEXT ends
+_TEXT segment
+align 4
+L70 label byte
+dd L62
+dd L62
+dd L62
+dd L62
+_TEXT ends
+_TEXT segment
+L53:
+mov edi,dword ptr (-4)[ebp]
+push edi
+lea edi,(L54)
+push edi
+call _printf
+add esp,8
+jmp L52
+L55:
+mov edi,dword ptr (-4)[ebp]
+push edi
+lea edi,(L56)
+push edi
+call _printf
+add esp,8
+jmp L52
+L57:
+mov edi,dword ptr (-4)[ebp]
+push edi
+lea edi,(L58)
+push edi
+call _printf
+add esp,8
+L51:
+mov edi,dword ptr (-4)[ebp]
+push edi
+lea edi,(L59)
+push edi
+call _printf
+add esp,8
+jmp L52
+L60:
+mov edi,dword ptr (-4)[ebp]
+push edi
+lea edi,(L61)
+push edi
+call _printf
+add esp,8
+jmp L52
+L62:
+mov edi,dword ptr (-4)[ebp]
+push edi
+lea edi,(L63)
+push edi
+call _printf
+add esp,8
+L52:
+L48:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],10
+jle L47
+mov eax,0
+L45:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _h
+_h:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,8
+mov dword ptr (-8)[ebp],0
+lea edi,(L73)
+push edi
+call _printf
+add esp,4
+mov dword ptr (-4)[ebp],1
+L74:
+mov edi,dword ptr (-4)[ebp]
+cmp edi,264
+je L86
+cmp edi,264
+jg L94
+L93:
+mov edi,dword ptr (-4)[ebp]
+cmp edi,120
+je L84
+cmp edi,120
+jg L96
+L95:
+mov edi,dword ptr (-4)[ebp]
+cmp edi,8
+je L83
+cmp edi,8
+jl L78
+L97:
+cmp dword ptr (-4)[ebp],16
+je L82
+jmp L78
+L96:
+mov edi,dword ptr (-4)[ebp]
+cmp edi,128
+je L80
+cmp edi,128
+jl L78
+L98:
+cmp dword ptr (-4)[ebp],248
+je L87
+jmp L78
+L94:
+mov edi,dword ptr (-4)[ebp]
+cmp edi,288
+je L91
+cmp edi,288
+jg L100
+L99:
+mov edi,dword ptr (-4)[ebp]
+cmp edi,272
+je L88
+cmp edi,272
+jl L78
+L101:
+cmp dword ptr (-4)[ebp],280
+je L85
+jmp L78
+L100:
+mov edi,dword ptr (-4)[ebp]
+cmp edi,304
+je L89
+cmp edi,304
+jg L103
+L102:
+cmp dword ptr (-4)[ebp],296
+je L90
+jmp L78
+L103:
+cmp dword ptr (-4)[ebp],312
+je L92
+jmp L78
+L78:
+inc dword ptr (-8)[ebp]
+jmp L75
+L80:
+mov edi,dword ptr (-4)[ebp]
+push edi
+lea edi,(L81)
+push edi
+call _printf
+add esp,8
+jmp L79
+L82:
+mov edi,dword ptr (-4)[ebp]
+push edi
+lea edi,(L81)
+push edi
+call _printf
+add esp,8
+jmp L79
+L83:
+mov edi,dword ptr (-4)[ebp]
+push edi
+lea edi,(L81)
+push edi
+call _printf
+add esp,8
+jmp L79
+L84:
+mov edi,dword ptr (-4)[ebp]
+push edi
+lea edi,(L81)
+push edi
+call _printf
+add esp,8
+jmp L79
+L85:
+mov edi,dword ptr (-4)[ebp]
+push edi
+lea edi,(L81)
+push edi
+call _printf
+add esp,8
+jmp L79
+L86:
+mov edi,dword ptr (-4)[ebp]
+push edi
+lea edi,(L81)
+push edi
+call _printf
+add esp,8
+jmp L79
+L87:
+mov edi,dword ptr (-4)[ebp]
+push edi
+lea edi,(L81)
+push edi
+call _printf
+add esp,8
+jmp L79
+L88:
+mov edi,dword ptr (-4)[ebp]
+push edi
+lea edi,(L81)
+push edi
+call _printf
+add esp,8
+jmp L79
+L89:
+mov edi,dword ptr (-4)[ebp]
+push edi
+lea edi,(L81)
+push edi
+call _printf
+add esp,8
+jmp L79
+L90:
+mov edi,dword ptr (-4)[ebp]
+push edi
+lea edi,(L81)
+push edi
+call _printf
+add esp,8
+jmp L79
+L91:
+mov edi,dword ptr (-4)[ebp]
+push edi
+lea edi,(L81)
+push edi
+call _printf
+add esp,8
+jmp L79
+L92:
+mov edi,dword ptr (-4)[ebp]
+push edi
+lea edi,(L81)
+push edi
+call _printf
+add esp,8
+L79:
+L75:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],500
+jle L74
+mov edi,dword ptr (-8)[ebp]
+push edi
+lea edi,(L104)
+push edi
+call _printf
+add esp,8
+mov eax,0
+L72:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _big
+_big:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,4
+mov edi,dword ptr (20)[ebp]
+and edi,06000000H
+mov dword ptr (-4)[ebp],edi
+mov edi,dword ptr (-4)[ebp]
+cmp edi,33554432
+je L111
+cmp edi,33554432
+jg L115
+L114:
+mov edi,dword ptr (-4)[ebp]
+cmp edi,-2
+je L109
+cmp edi,-1
+je L109
+cmp edi,0
+je L109
+jmp L106
+L115:
+mov edi,dword ptr (-4)[ebp]
+cmp edi,67108864
+je L112
+jmp L106
+L109:
+mov edi,dword ptr (20)[ebp]
+push edi
+lea edi,(L110)
+push edi
+call _printf
+add esp,8
+jmp L107
+L111:
+mov edi,dword ptr (20)[ebp]
+push edi
+lea edi,(L110)
+push edi
+call _printf
+add esp,8
+jmp L107
+L112:
+mov edi,dword ptr (20)[ebp]
+push edi
+lea edi,(L110)
+push edi
+call _printf
+add esp,8
+jmp L107
+L106:
+mov edi,dword ptr (20)[ebp]
+push edi
+lea edi,(L113)
+push edi
+call _printf
+add esp,8
+L107:
+mov eax,0
+L105:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _limit
+_limit:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,4
+mov dword ptr (-4)[ebp],-2147483648
+L117:
+mov edi,dword ptr (-4)[ebp]
+mov esi,-2147483648
+cmp edi,-2147483648
+jl L121
+cmp edi,-2147483644
+jg L121
+lea edi,[edi*4]
+lea esi,[esi*4]
+sub edi,esi
+jmp dword ptr (L134)[edi]
+_TEXT ends
+_TEXT segment
+align 4
+L134 label byte
+dd L123
+dd L125
+dd L127
+dd L129
+dd L131
+_TEXT ends
+_TEXT segment
+L123:
+lea edi,(L124)
+push edi
+call _printf
+add esp,4
+jmp L122
+L125:
+lea edi,(L126)
+push edi
+call _printf
+add esp,4
+jmp L122
+L127:
+lea edi,(L128)
+push edi
+call _printf
+add esp,4
+jmp L122
+L129:
+lea edi,(L130)
+push edi
+call _printf
+add esp,4
+jmp L122
+L131:
+lea edi,(L132)
+push edi
+call _printf
+add esp,4
+jmp L122
+L121:
+lea edi,(L133)
+push edi
+call _printf
+add esp,4
+L122:
+L118:
+inc dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],-2147483643
+jle L117
+mov dword ptr (-4)[ebp],2147483647
+L135:
+mov edi,dword ptr (-4)[ebp]
+mov esi,2147483643
+cmp edi,2147483643
+jl L139
+cmp edi,2147483647
+jg L139
+lea edi,[edi*4]
+lea esi,[esi*4]
+sub edi,esi
+jmp dword ptr (L146)[edi]
+_TEXT ends
+_TEXT segment
+align 4
+L146 label byte
+dd L145
+dd L144
+dd L143
+dd L142
+dd L141
+_TEXT ends
+_TEXT segment
+L141:
+lea edi,(L124)
+push edi
+call _printf
+add esp,4
+jmp L140
+L142:
+lea edi,(L126)
+push edi
+call _printf
+add esp,4
+jmp L140
+L143:
+lea edi,(L128)
+push edi
+call _printf
+add esp,4
+jmp L140
+L144:
+lea edi,(L130)
+push edi
+call _printf
+add esp,4
+jmp L140
+L145:
+lea edi,(L132)
+push edi
+call _printf
+add esp,4
+jmp L140
+L139:
+lea edi,(L133)
+push edi
+call _printf
+add esp,4
+L140:
+L136:
+dec dword ptr (-4)[ebp]
+cmp dword ptr (-4)[ebp],2147483642
+jge L135
+mov eax,0
+L116:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+extrn _printf:near
+_TEXT segment
+_TEXT ends
+_TEXT segment
+align 1
+L133 label byte
+db 53
+db 10
+db 0
+align 1
+L132 label byte
+db 52
+db 10
+db 0
+align 1
+L130 label byte
+db 51
+db 10
+db 0
+align 1
+L128 label byte
+db 50
+db 10
+db 0
+align 1
+L126 label byte
+db 49
+db 10
+db 0
+align 1
+L124 label byte
+db 48
+db 10
+db 0
+align 1
+L113 label byte
+db 120
+db 32
+db 61
+db 32
+db 48
+db 120
+db 37
+db 120
+db 32
+db 40
+db 100
+db 101
+db 102
+db 97
+db 117
+db 108
+db 116
+db 41
+db 10
+db 0
+align 1
+L110 label byte
+db 120
+db 32
+db 61
+db 32
+db 48
+db 120
+db 37
+db 120
+db 10
+db 0
+align 1
+L104 label byte
+db 37
+db 100
+db 32
+db 100
+db 101
+db 102
+db 97
+db 117
+db 108
+db 116
+db 115
+db 10
+db 0
+align 1
+L81 label byte
+db 105
+db 32
+db 61
+db 32
+db 37
+db 100
+db 10
+db 0
+align 1
+L73 label byte
+db 104
+db 58
+db 10
+db 0
+align 1
+L63 label byte
+db 54
+db 32
+db 37
+db 100
+db 10
+db 0
+align 1
+L61 label byte
+db 53
+db 32
+db 37
+db 100
+db 10
+db 0
+align 1
+L59 label byte
+db 100
+db 32
+db 37
+db 100
+db 10
+db 0
+align 1
+L58 label byte
+db 51
+db 32
+db 37
+db 100
+db 10
+db 0
+align 1
+L56 label byte
+db 50
+db 32
+db 37
+db 100
+db 10
+db 0
+align 1
+L54 label byte
+db 49
+db 32
+db 37
+db 100
+db 10
+db 0
+align 1
+L46 label byte
+db 103
+db 58
+db 10
+db 0
+align 1
+L44 label byte
+db 120
+db 32
+db 61
+db 32
+db 37
+db 100
+db 10
+db 0
+align 1
+L25 label byte
+db 102
+db 58
+db 10
+db 0
+align 1
+L7 label byte
+db 37
+db 99
+db 32
+db 61
+db 32
+db 48
+db 120
+db 37
+db 120
+db 10
+db 0
+align 1
+L6 label byte
+db 98
+db 102
+db 110
+db 114
+db 116
+db 118
+db 120
+db 0
+_TEXT ends
+end
diff --git a/lcc/x86/win32/tst/wf1.1bk b/lcc/x86/win32/tst/wf1.1bk
new file mode 100755
index 0000000..095e087
--- /dev/null
+++ b/lcc/x86/win32/tst/wf1.1bk
@@ -0,0 +1,74 @@
+5 a
+2 and
+5 buf
+16 c
+8 char
+1 compare
+4 cond
+5 count
+1 d
+1 die
+3 else
+1 entry
+1 eof
+4 err
+1 error
+1 exit
+1 folded
+1 for
+1 free
+1 frequencies
+1 frequency
+1 get
+2 getchar
+3 getword
+14 if
+2 in
+1 index
+1 input
+1 install
+8 int
+1 into
+1 is
+4 isletter
+1 it
+1 itself
+5 left
+1 letter
+7 lookup
+1 main
+2 malloc
+1 message
+2 n
+1 necessary
+12 next
+9 node
+4 of
+1 on
+1 or
+1 otherwise
+2 out
+8 p
+3 print
+2 printf
+16 return
+5 right
+4 root
+25 s
+2 storage
+3 strcmp
+1 strcpy
+1 strlen
+8 struct
+1 structures
+2 subtree
+1 t
+5 tprint
+9 tree
+1 uses
+1 version
+1 wf
+3 while
+21 word
+9 words
+2 z
diff --git a/lcc/x86/win32/tst/wf1.2bk b/lcc/x86/win32/tst/wf1.2bk
new file mode 100755
index 0000000..0e7a8a6
--- /dev/null
+++ b/lcc/x86/win32/tst/wf1.2bk
@@ -0,0 +1,2 @@
+tst/wf1.c:29: warning: missing return value
+tst/wf1.c:87: warning: missing return value
diff --git a/lcc/x86/win32/tst/wf1.sbk b/lcc/x86/win32/tst/wf1.sbk
new file mode 100755
index 0000000..df5688a
--- /dev/null
+++ b/lcc/x86/win32/tst/wf1.sbk
@@ -0,0 +1,451 @@
+.486
+.model flat
+extrn __fltused:near
+extrn __ftol:near
+public _main
+_TEXT segment
+_main:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,24
+mov dword ptr (-24)[ebp],0
+mov dword ptr (_next),0
+jmp L3
+L2:
+lea edi,(-24)[ebp]
+push edi
+lea edi,(-20)[ebp]
+push edi
+call _lookup
+add esp,8
+inc dword ptr [eax]
+L3:
+lea edi,(-20)[ebp]
+push edi
+call _getword
+add esp,4
+cmp eax,0
+jne L2
+mov edi,dword ptr (-24)[ebp]
+push edi
+call _tprint
+add esp,4
+mov eax,0
+L1:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _err
+_err:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov edi,dword ptr (20)[ebp]
+push edi
+lea edi,(L6)
+push edi
+call _printf
+add esp,8
+push 1
+call _exit
+add esp,4
+mov eax,0
+L5:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _getword
+_getword:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,8
+L8:
+L9:
+call _getchar
+add esp,0
+mov dword ptr (-4)[ebp],eax
+cmp eax,-1
+je L11
+mov edi,dword ptr (-4)[ebp]
+push edi
+call _isletter
+add esp,4
+cmp eax,0
+je L8
+L11:
+mov edi,dword ptr (20)[ebp]
+mov dword ptr (-8)[ebp],edi
+jmp L15
+L12:
+mov edi,dword ptr (-8)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-8)[ebp],esi
+mov esi,dword ptr (-4)[ebp]
+mov ebx,esi
+mov byte ptr [edi],bl
+L13:
+call _getchar
+add esp,0
+mov dword ptr (-4)[ebp],eax
+L15:
+mov edi,dword ptr (-4)[ebp]
+push edi
+call _isletter
+add esp,4
+mov dword ptr (-4)[ebp],eax
+cmp eax,0
+jne L12
+mov edi,dword ptr (-8)[ebp]
+mov byte ptr [edi],0
+mov edi,dword ptr (-8)[ebp]
+mov esi,dword ptr (20)[ebp]
+cmp edi,esi
+jbe L16
+mov eax,1
+jmp L7
+L16:
+mov eax,0
+L7:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _isletter
+_isletter:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov edi,dword ptr (20)[ebp]
+cmp edi,65
+jl L19
+cmp edi,90
+jg L19
+add dword ptr (20)[ebp],32
+L19:
+mov edi,dword ptr (20)[ebp]
+cmp edi,97
+jl L21
+cmp edi,122
+jg L21
+mov eax,dword ptr (20)[ebp]
+jmp L18
+L21:
+mov eax,0
+L18:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _lookup
+_lookup:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,4
+mov edi,dword ptr (24)[ebp]
+mov edi,dword ptr [edi]
+cmp edi,0
+je L24
+mov edi,dword ptr (24)[ebp]
+mov edi,dword ptr [edi]
+mov edi,dword ptr (12)[edi]
+push edi
+mov edi,dword ptr (20)[ebp]
+push edi
+call _strcmp
+add esp,8
+mov dword ptr (-4)[ebp],eax
+cmp dword ptr (-4)[ebp],0
+jge L26
+mov edi,dword ptr (24)[ebp]
+mov edi,dword ptr [edi]
+lea edi,(4)[edi]
+push edi
+mov edi,dword ptr (20)[ebp]
+push edi
+call _lookup
+add esp,8
+mov edi,eax
+jmp L23
+L26:
+cmp dword ptr (-4)[ebp],0
+jle L28
+mov edi,dword ptr (24)[ebp]
+mov edi,dword ptr [edi]
+lea edi,(8)[edi]
+push edi
+mov edi,dword ptr (20)[ebp]
+push edi
+call _lookup
+add esp,8
+mov edi,eax
+jmp L23
+L28:
+mov edi,dword ptr (24)[ebp]
+mov eax,dword ptr [edi]
+jmp L23
+L24:
+cmp dword ptr (_next),2000
+jl L30
+lea edi,(L32)
+push edi
+call _err
+add esp,4
+L30:
+mov edi,dword ptr (_next)
+sal edi,4
+mov dword ptr (_words)[edi],0
+mov edi,dword ptr (_next)
+sal edi,4
+mov dword ptr (_words+8)[edi],0
+mov dword ptr (_words+4)[edi],0
+mov edi,dword ptr (20)[ebp]
+push edi
+call _strlen
+add esp,4
+lea edi,(1)[eax]
+push edi
+call _malloc
+add esp,4
+mov esi,dword ptr (_next)
+sal esi,4
+mov dword ptr (_words+12)[esi],eax
+mov edi,dword ptr (_next)
+sal edi,4
+mov edi,dword ptr (_words+12)[edi]
+cmp edi,0
+jne L36
+lea edi,(L39)
+push edi
+call _err
+add esp,4
+L36:
+mov edi,dword ptr (20)[ebp]
+push edi
+mov edi,dword ptr (_next)
+sal edi,4
+mov edi,dword ptr (_words+12)[edi]
+push edi
+call _strcpy
+add esp,8
+mov edi,dword ptr (_next)
+lea esi,(1)[edi]
+mov dword ptr (_next),esi
+sal edi,4
+lea edi,(_words)[edi]
+mov esi,dword ptr (24)[ebp]
+mov dword ptr [esi],edi
+mov eax,edi
+L23:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _tprint
+_tprint:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov edi,dword ptr (20)[ebp]
+cmp edi,0
+je L42
+mov edi,dword ptr (20)[ebp]
+mov edi,dword ptr (4)[edi]
+push edi
+call _tprint
+add esp,4
+mov edi,dword ptr (20)[ebp]
+mov esi,dword ptr (12)[edi]
+push esi
+mov edi,dword ptr [edi]
+push edi
+lea edi,(L44)
+push edi
+call _printf
+add esp,12
+mov edi,dword ptr (20)[ebp]
+mov edi,dword ptr (8)[edi]
+push edi
+call _tprint
+add esp,4
+L42:
+mov eax,0
+L41:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _strcmp
+_strcmp:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+jmp L47
+L46:
+mov edi,dword ptr (20)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (20)[ebp],esi
+movsx edi,byte ptr [edi]
+cmp edi,0
+jne L49
+mov eax,0
+jmp L45
+L49:
+inc dword ptr (24)[ebp]
+L47:
+mov edi,dword ptr (20)[ebp]
+movsx edi,byte ptr [edi]
+mov esi,dword ptr (24)[ebp]
+movsx esi,byte ptr [esi]
+cmp edi,esi
+je L46
+mov edi,dword ptr (20)[ebp]
+movsx edi,byte ptr [edi]
+cmp edi,0
+jne L51
+mov eax,-1
+jmp L45
+L51:
+mov edi,dword ptr (24)[ebp]
+movsx edi,byte ptr [edi]
+cmp edi,0
+jne L53
+mov eax,1
+jmp L45
+L53:
+mov edi,dword ptr (20)[ebp]
+movsx edi,byte ptr [edi]
+mov esi,dword ptr (24)[ebp]
+movsx esi,byte ptr [esi]
+mov eax,edi
+sub eax,esi
+L45:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+extrn _strcpy:near
+_TEXT segment
+_TEXT ends
+extrn _strlen:near
+_TEXT segment
+_TEXT ends
+extrn _malloc:near
+_TEXT segment
+_TEXT ends
+extrn _getchar:near
+_TEXT segment
+_TEXT ends
+extrn _exit:near
+_TEXT segment
+_TEXT ends
+extrn _printf:near
+_TEXT segment
+_TEXT ends
+_DATA segment
+public _next
+align 4
+_next label byte
+db 4 dup (0)
+public _words
+align 4
+_words label byte
+db 32000 dup (0)
+_DATA ends
+_TEXT segment
+align 1
+L44 label byte
+db 37
+db 100
+db 9
+db 37
+db 115
+db 10
+db 0
+align 1
+L39 label byte
+db 111
+db 117
+db 116
+db 32
+db 111
+db 102
+db 32
+db 119
+db 111
+db 114
+db 100
+db 32
+db 115
+db 116
+db 111
+db 114
+db 97
+db 103
+db 101
+db 0
+align 1
+L32 label byte
+db 111
+db 117
+db 116
+db 32
+db 111
+db 102
+db 32
+db 110
+db 111
+db 100
+db 101
+db 32
+db 115
+db 116
+db 111
+db 114
+db 97
+db 103
+db 101
+db 0
+align 1
+L6 label byte
+db 63
+db 32
+db 37
+db 115
+db 10
+db 0
+_TEXT ends
+end
diff --git a/lcc/x86/win32/tst/yacc.1bk b/lcc/x86/win32/tst/yacc.1bk
new file mode 100755
index 0000000..b08a02f
--- /dev/null
+++ b/lcc/x86/win32/tst/yacc.1bk
@@ -0,0 +1,10 @@
+a
+b
+load
+negate
+push 5
+c
+load
+multiply
+add
+store
diff --git a/lcc/x86/win32/tst/yacc.2bk b/lcc/x86/win32/tst/yacc.2bk
new file mode 100755
index 0000000..a84aa5b
--- /dev/null
+++ b/lcc/x86/win32/tst/yacc.2bk
@@ -0,0 +1,3 @@
+tst/yacc.c:345: warning: missing return value
+tst/yacc.c:349: warning: missing return value
+tst/yacc.c:359: warning: missing return value
diff --git a/lcc/x86/win32/tst/yacc.sbk b/lcc/x86/win32/tst/yacc.sbk
new file mode 100755
index 0000000..432c9a4
--- /dev/null
+++ b/lcc/x86/win32/tst/yacc.sbk
@@ -0,0 +1,2489 @@
+.486
+.model flat
+extrn __fltused:near
+extrn __ftol:near
+_DATA segment
+public _yyin
+align 4
+_yyin label byte
+dd __iob
+public _yyout
+align 4
+_yyout label byte
+dd __iob+32
+public _yylex
+_DATA ends
+_TEXT segment
+_yylex:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,4
+jmp L4
+L3:
+L6:
+mov edi,dword ptr (-4)[ebp]
+cmp edi,-1
+jl L7
+cmp edi,4
+jg L7
+jmp dword ptr (L18+4)[edi*4]
+_TEXT ends
+_TEXT segment
+align 4
+L18 label byte
+dd L8
+dd L9
+dd L12
+dd L13
+dd L8
+dd L15
+_TEXT ends
+_TEXT segment
+L9:
+call _yywrap
+add esp,0
+cmp eax,0
+je L8
+mov eax,0
+jmp L2
+L12:
+mov eax,257
+jmp L2
+L13:
+mov eax,258
+jmp L2
+L15:
+movsx eax,byte ptr (_yytext)
+jmp L2
+L7:
+mov edi,dword ptr (-4)[ebp]
+push edi
+lea edi,(L17)
+push edi
+mov edi,dword ptr (_yyout)
+push edi
+call _fprintf
+add esp,12
+L8:
+L4:
+call _yylook
+add esp,0
+mov dword ptr (-4)[ebp],eax
+cmp eax,0
+jge L3
+mov eax,0
+L2:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+public _yyvstop
+align 4
+_yyvstop label byte
+dd 0
+dd 4
+dd 0
+dd 3
+dd 4
+dd 0
+dd 2
+dd 4
+dd 0
+dd 1
+dd 4
+dd 0
+dd 2
+dd 0
+dd 1
+dd 0
+dd 0
+public _yycrank
+align 4
+_yycrank label byte
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 1
+db 3
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 1
+db 4
+db 2 dup (0)
+db 1
+db 3
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 1
+db 5
+db 2 dup (0)
+db 5
+db 7
+db 2 dup (0)
+db 5
+db 7
+db 2 dup (0)
+db 5
+db 7
+db 2 dup (0)
+db 5
+db 7
+db 2 dup (0)
+db 5
+db 7
+db 2 dup (0)
+db 5
+db 7
+db 2 dup (0)
+db 5
+db 7
+db 2 dup (0)
+db 5
+db 7
+db 2 dup (0)
+db 5
+db 7
+db 2 dup (0)
+db 5
+db 7
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 1
+db 6
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 6
+db 8
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+db 0
+db 0
+db 2 dup (0)
+public _yysvec
+align 4
+_yysvec label byte
+dd 00H
+dd 00H
+dd 00H
+dd _yycrank-4
+dd 00H
+dd 00H
+dd _yycrank
+dd _yysvec+12
+dd 00H
+dd _yycrank
+dd 00H
+dd _yyvstop+4
+dd _yycrank
+dd 00H
+dd _yyvstop+12
+dd _yycrank+8
+dd 00H
+dd _yyvstop+24
+dd _yycrank+76
+dd 00H
+dd _yyvstop+36
+dd _yycrank
+dd _yysvec+60
+dd _yyvstop+48
+dd _yycrank
+dd _yysvec+72
+dd _yyvstop+56
+dd 00H
+dd 00H
+dd 00H
+public _yytop
+align 4
+_yytop label byte
+dd _yycrank+564
+public _yybgin
+align 4
+_yybgin label byte
+dd _yysvec+12
+public _yymatch
+align 1
+_yymatch label byte
+db 0
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 9
+db 10
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 9
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 48
+db 48
+db 48
+db 48
+db 48
+db 48
+db 48
+db 48
+db 48
+db 48
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 1
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 1
+db 1
+db 1
+db 1
+db 65
+db 1
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 65
+db 1
+db 1
+db 1
+db 1
+db 1
+db 0
+public _yyextra
+align 1
+_yyextra label byte
+db 0
+db 0
+db 0
+db 0
+db 0
+db 0
+db 0
+db 0
+db 0
+public _yylineno
+align 4
+_yylineno label byte
+dd 1
+public _yysptr
+align 4
+_yysptr label byte
+dd _yysbuf
+public _yyprevious
+align 4
+_yyprevious label byte
+dd 10
+public _yylook
+_DATA ends
+_TEXT segment
+_yylook:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,44
+cmp dword ptr (_yymorfg),0
+jne L35
+lea edi,(_yytext)
+mov dword ptr (-16)[ebp],edi
+jmp L36
+L35:
+mov dword ptr (_yymorfg),0
+mov edi,dword ptr (_yyleng)
+lea edi,(_yytext)[edi]
+mov dword ptr (-16)[ebp],edi
+L36:
+L37:
+lea edi,(_yylstate)
+mov dword ptr (-8)[ebp],edi
+mov edi,dword ptr (_yybgin)
+mov dword ptr (-4)[ebp],edi
+mov dword ptr (_yyestate),edi
+cmp dword ptr (_yyprevious),10
+jne L41
+mov edi,dword ptr (-4)[ebp]
+lea edi,(12)[edi]
+mov dword ptr (-4)[ebp],edi
+L41:
+L43:
+mov edi,dword ptr (-4)[ebp]
+mov edi,dword ptr [edi]
+mov dword ptr (-12)[ebp],edi
+mov edi,dword ptr (-12)[ebp]
+lea esi,(_yycrank)
+cmp edi,esi
+jne L47
+mov edi,dword ptr (-4)[ebp]
+mov edi,dword ptr (4)[edi]
+mov dword ptr (-28)[ebp],edi
+mov edi,dword ptr (-28)[ebp]
+cmp edi,0
+jne L49
+jmp L94
+L49:
+mov edi,dword ptr (-28)[ebp]
+mov edi,dword ptr [edi]
+lea esi,(_yycrank)
+cmp edi,esi
+jne L51
+jmp L94
+L51:
+L47:
+mov edi,dword ptr (-16)[ebp]
+lea esi,(1)[edi]
+mov dword ptr (-16)[ebp],esi
+mov esi,dword ptr (_yysptr)
+lea ebx,(_yysbuf)
+cmp esi,ebx
+jbe L61
+mov esi,dword ptr (_yysptr)
+lea esi,(-1)[esi]
+mov dword ptr (_yysptr),esi
+movsx esi,byte ptr [esi]
+mov dword ptr (-40)[ebp],esi
+jmp L62
+L61:
+mov esi,dword ptr (_yyin)
+lea esi,(4)[esi]
+mov ebx,dword ptr [esi]
+sub ebx,1
+mov dword ptr [esi],ebx
+cmp ebx,0
+jl L63
+mov esi,dword ptr (_yyin)
+mov ebx,dword ptr [esi]
+lea edx,(1)[ebx]
+mov dword ptr [esi],edx
+movsx esi,byte ptr [ebx]
+and esi,255
+mov dword ptr (-44)[ebp],esi
+jmp L64
+L63:
+mov esi,dword ptr (_yyin)
+push esi
+call __filbuf
+add esp,4
+mov esi,eax
+mov dword ptr (-44)[ebp],esi
+L64:
+mov esi,dword ptr (-44)[ebp]
+mov dword ptr (-40)[ebp],esi
+L62:
+mov esi,dword ptr (-40)[ebp]
+mov dword ptr (_yytchar),esi
+cmp esi,10
+jne L59
+inc dword ptr (_yylineno)
+mov esi,dword ptr (_yytchar)
+mov dword ptr (-36)[ebp],esi
+jmp L60
+L59:
+mov esi,dword ptr (_yytchar)
+mov dword ptr (-36)[ebp],esi
+L60:
+cmp dword ptr (-36)[ebp],-1
+jne L57
+mov dword ptr (-32)[ebp],0
+jmp L58
+L57:
+mov esi,dword ptr (_yytchar)
+mov dword ptr (-32)[ebp],esi
+L58:
+mov esi,dword ptr (-32)[ebp]
+mov dword ptr (-20)[ebp],esi
+mov ebx,esi
+mov byte ptr [edi],bl
+L65:
+mov edi,dword ptr (-12)[ebp]
+mov dword ptr (-24)[ebp],edi
+lea esi,(_yycrank)
+cmp edi,esi
+jbe L66
+mov edi,dword ptr (-20)[ebp]
+mov esi,dword ptr (-24)[ebp]
+lea edi,[esi][edi*4]
+mov dword ptr (-12)[ebp],edi
+mov edi,dword ptr (-12)[ebp]
+mov esi,edi
+mov ebx,dword ptr (_yytop)
+cmp esi,ebx
+ja L67
+movsx edi,byte ptr [edi]
+imul edi,edi,12
+lea edi,(_yysvec)[edi]
+mov esi,dword ptr (-4)[ebp]
+cmp edi,esi
+jne L67
+lea edi,(_yysvec)
+mov esi,dword ptr (-12)[ebp]
+movsx esi,byte ptr (1)[esi]
+imul esi,esi,12
+lea esi,(_yysvec)[esi]
+cmp esi,edi
+jne L70
+mov edi,dword ptr (-16)[ebp]
+lea edi,(-1)[edi]
+mov dword ptr (-16)[ebp],edi
+movsx edi,byte ptr [edi]
+mov dword ptr (_yytchar),edi
+cmp dword ptr (_yytchar),10
+jne L72
+dec dword ptr (_yylineno)
+L72:
+mov edi,dword ptr (_yysptr)
+lea esi,(1)[edi]
+mov dword ptr (_yysptr),esi
+mov esi,dword ptr (_yytchar)
+mov ebx,esi
+mov byte ptr [edi],bl
+jmp L94
+L70:
+mov edi,dword ptr (-8)[ebp]
+lea esi,(4)[edi]
+mov dword ptr (-8)[ebp],esi
+mov esi,dword ptr (-12)[ebp]
+movsx esi,byte ptr (1)[esi]
+imul esi,esi,12
+lea esi,(_yysvec)[esi]
+mov dword ptr (-4)[ebp],esi
+mov dword ptr [edi],esi
+jmp L43
+L66:
+mov edi,dword ptr (-12)[ebp]
+lea esi,(_yycrank)
+cmp edi,esi
+jae L75
+lea edi,(_yycrank)
+mov esi,dword ptr (-12)[ebp]
+sub edi,esi
+mov eax,edi
+mov edi,4
+cdq
+idiv edi
+lea edi,(_yycrank)[eax*4]
+mov dword ptr (-24)[ebp],edi
+mov dword ptr (-12)[ebp],edi
+mov edi,dword ptr (-20)[ebp]
+mov esi,dword ptr (-12)[ebp]
+lea edi,[esi][edi*4]
+mov dword ptr (-12)[ebp],edi
+mov edi,dword ptr (-12)[ebp]
+mov esi,edi
+mov ebx,dword ptr (_yytop)
+cmp esi,ebx
+ja L77
+movsx edi,byte ptr [edi]
+imul edi,edi,12
+lea edi,(_yysvec)[edi]
+mov esi,dword ptr (-4)[ebp]
+cmp edi,esi
+jne L77
+lea edi,(_yysvec)
+mov esi,dword ptr (-12)[ebp]
+movsx esi,byte ptr (1)[esi]
+imul esi,esi,12
+lea esi,(_yysvec)[esi]
+cmp esi,edi
+jne L79
+mov edi,dword ptr (-16)[ebp]
+lea edi,(-1)[edi]
+mov dword ptr (-16)[ebp],edi
+movsx edi,byte ptr [edi]
+mov dword ptr (_yytchar),edi
+cmp dword ptr (_yytchar),10
+jne L81
+dec dword ptr (_yylineno)
+L81:
+mov edi,dword ptr (_yysptr)
+lea esi,(1)[edi]
+mov dword ptr (_yysptr),esi
+mov esi,dword ptr (_yytchar)
+mov ebx,esi
+mov byte ptr [edi],bl
+jmp L94
+L79:
+mov edi,dword ptr (-8)[ebp]
+lea esi,(4)[edi]
+mov dword ptr (-8)[ebp],esi
+mov esi,dword ptr (-12)[ebp]
+movsx esi,byte ptr (1)[esi]
+imul esi,esi,12
+lea esi,(_yysvec)[esi]
+mov dword ptr (-4)[ebp],esi
+mov dword ptr [edi],esi
+jmp L43
+L77:
+mov edi,dword ptr (-20)[ebp]
+movsx edi,byte ptr (_yymatch)[edi]
+mov esi,dword ptr (-24)[ebp]
+lea edi,[esi][edi*4]
+mov dword ptr (-12)[ebp],edi
+mov edi,dword ptr (-12)[ebp]
+mov esi,edi
+mov ebx,dword ptr (_yytop)
+cmp esi,ebx
+ja L83
+movsx edi,byte ptr [edi]
+imul edi,edi,12
+lea edi,(_yysvec)[edi]
+mov esi,dword ptr (-4)[ebp]
+cmp edi,esi
+jne L83
+lea edi,(_yysvec)
+mov esi,dword ptr (-12)[ebp]
+movsx esi,byte ptr (1)[esi]
+imul esi,esi,12
+lea esi,(_yysvec)[esi]
+cmp esi,edi
+jne L85
+mov edi,dword ptr (-16)[ebp]
+lea edi,(-1)[edi]
+mov dword ptr (-16)[ebp],edi
+movsx edi,byte ptr [edi]
+mov dword ptr (_yytchar),edi
+cmp dword ptr (_yytchar),10
+jne L87
+dec dword ptr (_yylineno)
+L87:
+mov edi,dword ptr (_yysptr)
+lea esi,(1)[edi]
+mov dword ptr (_yysptr),esi
+mov esi,dword ptr (_yytchar)
+mov ebx,esi
+mov byte ptr [edi],bl
+jmp L94
+L85:
+mov edi,dword ptr (-8)[ebp]
+lea esi,(4)[edi]
+mov dword ptr (-8)[ebp],esi
+mov esi,dword ptr (-12)[ebp]
+movsx esi,byte ptr (1)[esi]
+imul esi,esi,12
+lea esi,(_yysvec)[esi]
+mov dword ptr (-4)[ebp],esi
+mov dword ptr [edi],esi
+jmp L43
+L83:
+L75:
+L67:
+mov edi,dword ptr (-4)[ebp]
+mov edi,dword ptr (4)[edi]
+mov dword ptr (-4)[ebp],edi
+cmp edi,0
+je L89
+mov edi,dword ptr (-4)[ebp]
+mov edi,dword ptr [edi]
+mov dword ptr (-12)[ebp],edi
+lea esi,(_yycrank)
+cmp edi,esi
+je L89
+jmp L65
+L89:
+mov edi,dword ptr (-16)[ebp]
+lea edi,(-1)[edi]
+mov dword ptr (-16)[ebp],edi
+movsx edi,byte ptr [edi]
+mov dword ptr (_yytchar),edi
+cmp dword ptr (_yytchar),10
+jne L91
+dec dword ptr (_yylineno)
+L91:
+mov edi,dword ptr (_yysptr)
+lea esi,(1)[edi]
+mov dword ptr (_yysptr),esi
+mov esi,dword ptr (_yytchar)
+mov ebx,esi
+mov byte ptr [edi],bl
+jmp L94
+L93:
+mov edi,dword ptr (-16)[ebp]
+lea esi,(-1)[edi]
+mov dword ptr (-16)[ebp],esi
+mov byte ptr [edi],0
+mov edi,dword ptr (-8)[ebp]
+mov edi,dword ptr [edi]
+mov esi,edi
+cmp esi,0
+je L96
+mov edi,dword ptr (8)[edi]
+mov dword ptr (_yyfnd),edi
+cmp edi,0
+je L96
+mov edi,dword ptr (_yyfnd)
+cmp dword ptr [edi],0
+jle L96
+mov edi,dword ptr (-8)[ebp]
+mov dword ptr (_yyolsp),edi
+mov edi,dword ptr (_yyfnd)
+mov edi,dword ptr [edi]
+movsx edi,byte ptr (_yyextra)[edi]
+cmp edi,0
+je L98
+jmp L101
+L100:
+mov edi,dword ptr (-8)[ebp]
+lea edi,(-4)[edi]
+mov dword ptr (-8)[ebp],edi
+mov edi,dword ptr (-16)[ebp]
+lea esi,(-1)[edi]
+mov dword ptr (-16)[ebp],esi
+movsx edi,byte ptr [edi]
+mov dword ptr (_yytchar),edi
+cmp dword ptr (_yytchar),10
+jne L103
+dec dword ptr (_yylineno)
+L103:
+mov edi,dword ptr (_yysptr)
+lea esi,(1)[edi]
+mov dword ptr (_yysptr),esi
+mov esi,dword ptr (_yytchar)
+mov ebx,esi
+mov byte ptr [edi],bl
+L101:
+mov edi,dword ptr (_yyfnd)
+mov edi,dword ptr [edi]
+neg edi
+push edi
+mov edi,dword ptr (-8)[ebp]
+mov edi,dword ptr [edi]
+mov edi,dword ptr (8)[edi]
+push edi
+call _yyback
+add esp,8
+cmp eax,1
+je L105
+mov edi,dword ptr (-8)[ebp]
+lea esi,(_yylstate)
+cmp edi,esi
+ja L100
+L105:
+L98:
+mov edi,dword ptr (-16)[ebp]
+movsx esi,byte ptr [edi]
+mov dword ptr (_yyprevious),esi
+mov esi,dword ptr (-8)[ebp]
+mov dword ptr (_yylsp),esi
+lea esi,(_yytext)
+sub edi,esi
+lea edi,(1)[edi]
+mov dword ptr (_yyleng),edi
+mov edi,dword ptr (_yyleng)
+mov byte ptr (_yytext)[edi],0
+mov edi,dword ptr (_yyfnd)
+lea esi,(4)[edi]
+mov dword ptr (_yyfnd),esi
+mov eax,dword ptr [edi]
+jmp L34
+L96:
+mov edi,dword ptr (-16)[ebp]
+movsx edi,byte ptr [edi]
+mov dword ptr (_yytchar),edi
+cmp dword ptr (_yytchar),10
+jne L106
+dec dword ptr (_yylineno)
+L106:
+mov edi,dword ptr (_yysptr)
+lea esi,(1)[edi]
+mov dword ptr (_yysptr),esi
+mov esi,dword ptr (_yytchar)
+mov ebx,esi
+mov byte ptr [edi],bl
+L94:
+mov edi,dword ptr (-8)[ebp]
+lea esi,(-4)[edi]
+mov dword ptr (-8)[ebp],esi
+lea esi,(_yylstate)
+cmp edi,esi
+ja L93
+movsx edi,byte ptr (_yytext)
+cmp edi,0
+jne L108
+lea edi,(_yysbuf)
+mov dword ptr (_yysptr),edi
+mov eax,0
+jmp L34
+L108:
+mov edi,dword ptr (_yysptr)
+lea esi,(_yysbuf)
+cmp edi,esi
+jbe L118
+mov edi,dword ptr (_yysptr)
+lea edi,(-1)[edi]
+mov dword ptr (_yysptr),edi
+movsx edi,byte ptr [edi]
+mov dword ptr (-40)[ebp],edi
+jmp L119
+L118:
+mov edi,dword ptr (_yyin)
+lea edi,(4)[edi]
+mov esi,dword ptr [edi]
+sub esi,1
+mov dword ptr [edi],esi
+cmp esi,0
+jl L120
+mov edi,dword ptr (_yyin)
+mov esi,dword ptr [edi]
+lea ebx,(1)[esi]
+mov dword ptr [edi],ebx
+movsx edi,byte ptr [esi]
+and edi,255
+mov dword ptr (-44)[ebp],edi
+jmp L121
+L120:
+mov edi,dword ptr (_yyin)
+push edi
+call __filbuf
+add esp,4
+mov edi,eax
+mov dword ptr (-44)[ebp],edi
+L121:
+mov edi,dword ptr (-44)[ebp]
+mov dword ptr (-40)[ebp],edi
+L119:
+mov edi,dword ptr (-40)[ebp]
+mov dword ptr (_yytchar),edi
+cmp edi,10
+jne L116
+inc dword ptr (_yylineno)
+mov edi,dword ptr (_yytchar)
+mov dword ptr (-36)[ebp],edi
+jmp L117
+L116:
+mov edi,dword ptr (_yytchar)
+mov dword ptr (-36)[ebp],edi
+L117:
+cmp dword ptr (-36)[ebp],-1
+jne L114
+mov dword ptr (-32)[ebp],0
+jmp L115
+L114:
+mov edi,dword ptr (_yytchar)
+mov dword ptr (-32)[ebp],edi
+L115:
+mov edi,dword ptr (-32)[ebp]
+mov ebx,edi
+mov byte ptr (_yytext),bl
+movsx edi,bl
+mov dword ptr (_yyprevious),edi
+cmp dword ptr (_yyprevious),0
+jle L122
+mov edi,dword ptr (_yyout)
+lea edi,(4)[edi]
+mov esi,dword ptr [edi]
+sub esi,1
+mov dword ptr [edi],esi
+cmp esi,0
+jl L125
+mov edi,dword ptr (_yyout)
+mov esi,dword ptr [edi]
+lea ebx,(1)[esi]
+mov dword ptr [edi],ebx
+mov edi,dword ptr (_yyprevious)
+mov ebx,edi
+mov byte ptr [esi],bl
+jmp L126
+L125:
+mov edi,dword ptr (_yyout)
+push edi
+mov edi,dword ptr (_yyprevious)
+push edi
+call __flsbuf
+add esp,8
+L126:
+L122:
+lea edi,(_yytext)
+mov dword ptr (-16)[ebp],edi
+jmp L37
+L34:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _yyback
+_yyback:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov edi,dword ptr (20)[ebp]
+cmp edi,0
+jne L131
+mov eax,0
+jmp L127
+L130:
+mov edi,dword ptr (20)[ebp]
+lea esi,(4)[edi]
+mov dword ptr (20)[ebp],esi
+mov esi,dword ptr (24)[ebp]
+cmp dword ptr [edi],esi
+jne L133
+mov eax,1
+jmp L127
+L133:
+L131:
+mov edi,dword ptr (20)[ebp]
+cmp dword ptr [edi],0
+jne L130
+mov eax,0
+L127:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _yyinput
+_yyinput:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,16
+mov edi,dword ptr (_yysptr)
+lea esi,(_yysbuf)
+cmp edi,esi
+jbe L144
+mov edi,dword ptr (_yysptr)
+lea edi,(-1)[edi]
+mov dword ptr (_yysptr),edi
+movsx edi,byte ptr [edi]
+mov dword ptr (-12)[ebp],edi
+jmp L145
+L144:
+mov edi,dword ptr (_yyin)
+lea edi,(4)[edi]
+mov esi,dword ptr [edi]
+sub esi,1
+mov dword ptr [edi],esi
+cmp esi,0
+jl L146
+mov edi,dword ptr (_yyin)
+mov esi,dword ptr [edi]
+lea ebx,(1)[esi]
+mov dword ptr [edi],ebx
+movsx edi,byte ptr [esi]
+and edi,255
+mov dword ptr (-16)[ebp],edi
+jmp L147
+L146:
+mov edi,dword ptr (_yyin)
+push edi
+call __filbuf
+add esp,4
+mov edi,eax
+mov dword ptr (-16)[ebp],edi
+L147:
+mov edi,dword ptr (-16)[ebp]
+mov dword ptr (-12)[ebp],edi
+L145:
+mov edi,dword ptr (-12)[ebp]
+mov dword ptr (_yytchar),edi
+cmp edi,10
+jne L142
+inc dword ptr (_yylineno)
+mov edi,dword ptr (_yytchar)
+mov dword ptr (-8)[ebp],edi
+jmp L143
+L142:
+mov edi,dword ptr (_yytchar)
+mov dword ptr (-8)[ebp],edi
+L143:
+cmp dword ptr (-8)[ebp],-1
+jne L140
+mov dword ptr (-4)[ebp],0
+jmp L141
+L140:
+mov edi,dword ptr (_yytchar)
+mov dword ptr (-4)[ebp],edi
+L141:
+mov eax,dword ptr (-4)[ebp]
+L135:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _yyoutput
+_yyoutput:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov edi,dword ptr (_yyout)
+lea edi,(4)[edi]
+mov esi,dword ptr [edi]
+sub esi,1
+mov dword ptr [edi],esi
+cmp esi,0
+jl L150
+mov edi,dword ptr (_yyout)
+mov esi,dword ptr [edi]
+lea ebx,(1)[esi]
+mov dword ptr [edi],ebx
+mov edi,dword ptr (20)[ebp]
+mov ebx,edi
+mov byte ptr [esi],bl
+jmp L151
+L150:
+mov edi,dword ptr (_yyout)
+push edi
+mov edi,dword ptr (20)[ebp]
+push edi
+call __flsbuf
+add esp,8
+L151:
+mov eax,0
+L148:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _yyunput
+_yyunput:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov edi,dword ptr (20)[ebp]
+mov dword ptr (_yytchar),edi
+cmp dword ptr (_yytchar),10
+jne L153
+dec dword ptr (_yylineno)
+L153:
+mov edi,dword ptr (_yysptr)
+lea esi,(1)[edi]
+mov dword ptr (_yysptr),esi
+mov esi,dword ptr (_yytchar)
+mov ebx,esi
+mov byte ptr [edi],bl
+mov eax,0
+L152:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _main
+_main:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+call _yyparse
+add esp,0
+mov eax,0
+L155:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _yyerror
+_yyerror:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov edi,dword ptr (20)[ebp]
+push edi
+lea edi,(L157)
+push edi
+call _printf
+add esp,8
+mov eax,0
+L156:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+public _yyexca
+align 2
+_yyexca label byte
+dw -1
+dw 1
+dw 0
+dw -1
+dw -2
+dw 0
+public _yyact
+align 2
+_yyact label byte
+dw 12
+dw 2
+dw 9
+dw 8
+dw 17
+dw 11
+dw 25
+dw 17
+dw 15
+dw 18
+dw 16
+dw 10
+dw 18
+dw 17
+dw 15
+dw 7
+dw 16
+dw 13
+dw 18
+dw 5
+dw 3
+dw 1
+dw 0
+dw 19
+dw 20
+dw 0
+dw 0
+dw 21
+dw 22
+dw 23
+dw 24
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 6
+dw 14
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 0
+dw 4
+dw 6
+public _yypact
+align 2
+_yypact label byte
+dw -1000
+dw -9
+dw -1000
+dw 5
+dw -7
+dw -59
+dw -1000
+dw -1000
+dw -1000
+dw -40
+dw -29
+dw -40
+dw -40
+dw -1000
+dw -1000
+dw -40
+dw -40
+dw -40
+dw -40
+dw -38
+dw -35
+dw -38
+dw -38
+dw -1000
+dw -1000
+dw -1000
+public _yypgo
+align 2
+_yypgo label byte
+dw 0
+dw 21
+dw 20
+dw 17
+dw 11
+public _yyr1
+align 2
+_yyr1 label byte
+dw 0
+dw 1
+dw 1
+dw 1
+dw 1
+dw 2
+dw 4
+dw 4
+dw 4
+dw 4
+dw 4
+dw 4
+dw 4
+dw 4
+dw 3
+public _yyr2
+align 2
+_yyr2 label byte
+dw 0
+dw 0
+dw 2
+dw 3
+dw 3
+dw 3
+dw 3
+dw 3
+dw 3
+dw 3
+dw 2
+dw 3
+dw 1
+dw 1
+dw 1
+public _yychk
+align 2
+_yychk label byte
+dw -1000
+dw -1
+dw 10
+dw -2
+dw 256
+dw -3
+dw 257
+dw 10
+dw 10
+dw 61
+dw -4
+dw 45
+dw 40
+dw -3
+dw 258
+dw 43
+dw 45
+dw 42
+dw 47
+dw -4
+dw -4
+dw -4
+dw -4
+dw -4
+dw -4
+dw 41
+public _yydef
+align 2
+_yydef label byte
+dw 1
+dw -2
+dw 2
+dw 0
+dw 0
+dw 0
+dw 14
+dw 3
+dw 4
+dw 0
+dw 5
+dw 0
+dw 0
+dw 12
+dw 13
+dw 0
+dw 0
+dw 0
+dw 0
+dw 10
+dw 0
+dw 6
+dw 7
+dw 8
+dw 9
+dw 11
+public _yychar
+align 4
+_yychar label byte
+dd -1
+public _yynerrs
+align 4
+_yynerrs label byte
+dd 0
+public _yyerrflag
+align 2
+_yyerrflag label byte
+dw 0
+public _yyparse
+_DATA ends
+_TEXT segment
+_yyparse:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+sub esp,332
+mov word ptr (-6)[ebp],0
+mov dword ptr (_yychar),-1
+mov dword ptr (_yynerrs),0
+mov word ptr (_yyerrflag),0
+lea edi,(-328)[ebp]
+mov dword ptr (-12)[ebp],edi
+lea edi,(_yyv-4)
+mov dword ptr (-20)[ebp],edi
+L161:
+mov edi,dword ptr (-12)[ebp]
+lea edi,(2)[edi]
+mov dword ptr (-12)[ebp],edi
+lea esi,(-26)[ebp]
+cmp edi,esi
+jbe L162
+lea edi,(L165)
+push edi
+call _yyerror
+add esp,4
+mov eax,1
+jmp L158
+L162:
+mov edi,dword ptr (-12)[ebp]
+mov si,word ptr (-6)[ebp]
+mov word ptr [edi],si
+mov edi,dword ptr (-20)[ebp]
+lea edi,(4)[edi]
+mov dword ptr (-20)[ebp],edi
+mov edi,dword ptr (-20)[ebp]
+mov esi,dword ptr (_yyval)
+mov dword ptr [edi],esi
+L166:
+movsx edi,word ptr (-6)[ebp]
+mov di,word ptr (_yypact)[edi*2]
+mov word ptr (-14)[ebp],di
+movsx edi,word ptr (-14)[ebp]
+cmp edi,-1000
+jg L167
+jmp L169
+L167:
+cmp dword ptr (_yychar),0
+jge L170
+call _yylex
+add esp,0
+mov dword ptr (_yychar),eax
+cmp eax,0
+jge L172
+mov dword ptr (_yychar),0
+L172:
+L170:
+movsx edi,word ptr (-14)[ebp]
+mov esi,dword ptr (_yychar)
+lea edi,[esi][edi]
+mov word ptr (-14)[ebp],di
+movsx edi,di
+cmp edi,0
+jl L176
+movsx edi,word ptr (-14)[ebp]
+cmp edi,249
+jl L174
+L176:
+jmp L169
+L174:
+movsx edi,word ptr (-14)[ebp]
+mov di,word ptr (_yyact)[edi*2]
+mov word ptr (-14)[ebp],di
+movsx edi,di
+movsx edi,word ptr (_yychk)[edi*2]
+cmp edi,dword ptr (_yychar)
+jne L177
+mov dword ptr (_yychar),-1
+mov edi,dword ptr (_yylval)
+mov dword ptr (_yyval),edi
+mov di,word ptr (-14)[ebp]
+mov word ptr (-6)[ebp],di
+movsx edi,word ptr (_yyerrflag)
+cmp edi,0
+jle L161
+movsx edi,word ptr (_yyerrflag)
+sub edi,1
+mov word ptr (_yyerrflag),di
+jmp L161
+L177:
+L169:
+movsx edi,word ptr (-6)[ebp]
+mov di,word ptr (_yydef)[edi*2]
+mov word ptr (-14)[ebp],di
+movsx edi,di
+cmp edi,-2
+jne L181
+cmp dword ptr (_yychar),0
+jge L183
+call _yylex
+add esp,0
+mov dword ptr (_yychar),eax
+cmp eax,0
+jge L185
+mov dword ptr (_yychar),0
+L185:
+L183:
+lea edi,(_yyexca)
+mov dword ptr (-24)[ebp],edi
+jmp L190
+L187:
+L188:
+mov edi,dword ptr (-24)[ebp]
+lea edi,(4)[edi]
+mov dword ptr (-24)[ebp],edi
+L190:
+mov edi,dword ptr (-24)[ebp]
+movsx esi,word ptr [edi]
+cmp esi,-1
+jne L187
+movsx edi,word ptr (2)[edi]
+movsx esi,word ptr (-6)[ebp]
+cmp edi,esi
+jne L187
+jmp L192
+L191:
+mov edi,dword ptr (-24)[ebp]
+movsx edi,word ptr [edi]
+cmp edi,dword ptr (_yychar)
+jne L194
+jmp L193
+L194:
+L192:
+mov edi,dword ptr (-24)[ebp]
+lea edi,(4)[edi]
+mov dword ptr (-24)[ebp],edi
+movsx edi,word ptr [edi]
+cmp edi,0
+jge L191
+L193:
+mov edi,dword ptr (-24)[ebp]
+mov di,word ptr (2)[edi]
+mov word ptr (-14)[ebp],di
+movsx edi,di
+cmp edi,0
+jge L196
+mov eax,0
+jmp L158
+L196:
+L181:
+movsx edi,word ptr (-14)[ebp]
+cmp edi,0
+jne L198
+movsx edi,word ptr (_yyerrflag)
+mov dword ptr (-332)[ebp],edi
+mov edi,dword ptr (-332)[ebp]
+cmp edi,0
+jl L200
+cmp edi,3
+jg L200
+jmp dword ptr (L216)[edi*4]
+_TEXT ends
+_TEXT segment
+align 4
+L216 label byte
+dd L203
+dd L206
+dd L206
+dd L213
+_TEXT ends
+_TEXT segment
+L203:
+lea edi,(L204)
+push edi
+call _yyerror
+add esp,4
+L205:
+inc dword ptr (_yynerrs)
+L206:
+mov word ptr (_yyerrflag),3
+jmp L208
+L207:
+mov edi,dword ptr (-12)[ebp]
+movsx edi,word ptr [edi]
+movsx edi,word ptr (_yypact)[edi*2]
+lea edi,(256)[edi]
+mov word ptr (-14)[ebp],di
+movsx edi,word ptr (-14)[ebp]
+cmp edi,0
+jl L210
+cmp edi,249
+jge L210
+movsx edi,word ptr (_yyact)[edi*2]
+movsx edi,word ptr (_yychk)[edi*2]
+cmp edi,256
+jne L210
+movsx edi,word ptr (-14)[ebp]
+mov di,word ptr (_yyact)[edi*2]
+mov word ptr (-6)[ebp],di
+jmp L161
+L210:
+mov edi,dword ptr (-12)[ebp]
+movsx esi,word ptr [edi]
+mov si,word ptr (_yypact)[esi*2]
+mov word ptr (-14)[ebp],si
+lea edi,(-2)[edi]
+mov dword ptr (-12)[ebp],edi
+mov edi,dword ptr (-20)[ebp]
+lea edi,(-4)[edi]
+mov dword ptr (-20)[ebp],edi
+L208:
+mov edi,dword ptr (-12)[ebp]
+lea esi,(-326)[ebp]
+cmp edi,esi
+jae L207
+L212:
+mov eax,1
+jmp L158
+L213:
+cmp dword ptr (_yychar),0
+jne L214
+jmp L212
+L214:
+mov dword ptr (_yychar),-1
+jmp L166
+L200:
+L198:
+mov di,word ptr (-14)[ebp]
+movsx esi,di
+lea esi,[esi*2]
+lea ebx,(_yyr2)[esi]
+mov edx,dword ptr (-12)[ebp]
+movsx ecx,word ptr [ebx]
+lea ecx,[ecx*2]
+sub edx,ecx
+mov dword ptr (-12)[ebp],edx
+mov edx,dword ptr (-20)[ebp]
+mov dword ptr (-4)[ebp],edx
+movsx ebx,word ptr [ebx]
+lea ebx,[ebx*4]
+sub edx,ebx
+mov dword ptr (-20)[ebp],edx
+mov ebx,dword ptr (-20)[ebp]
+mov ebx,dword ptr (4)[ebx]
+mov dword ptr (_yyval),ebx
+mov word ptr (-328)[ebp],di
+mov di,word ptr (_yyr1)[esi]
+mov word ptr (-14)[ebp],di
+movsx edi,word ptr (-14)[ebp]
+movsx edi,word ptr (_yypgo)[edi*2]
+mov esi,dword ptr (-12)[ebp]
+movsx esi,word ptr [esi]
+lea edi,[esi][edi]
+lea edi,(1)[edi]
+mov word ptr (-26)[ebp],di
+movsx edi,word ptr (-26)[ebp]
+cmp edi,249
+jge L219
+mov di,word ptr (_yyact)[edi*2]
+mov word ptr (-6)[ebp],di
+movsx edi,di
+movsx edi,word ptr (_yychk)[edi*2]
+movsx esi,word ptr (-14)[ebp]
+neg esi
+cmp edi,esi
+je L217
+L219:
+movsx edi,word ptr (-14)[ebp]
+movsx edi,word ptr (_yypgo)[edi*2]
+mov di,word ptr (_yyact)[edi*2]
+mov word ptr (-6)[ebp],di
+L217:
+movsx edi,word ptr (-328)[ebp]
+mov dword ptr (-332)[ebp],edi
+mov edi,dword ptr (-332)[ebp]
+cmp edi,4
+jl L161
+cmp edi,14
+jg L161
+jmp dword ptr (L241-16)[edi*4]
+_TEXT ends
+_TEXT segment
+align 4
+L241 label byte
+dd L223
+dd L224
+dd L226
+dd L228
+dd L230
+dd L232
+dd L234
+dd L161
+dd L236
+dd L238
+dd L240
+_TEXT ends
+_TEXT segment
+L223:
+mov word ptr (_yyerrflag),0
+jmp L161
+L224:
+lea edi,(L225)
+push edi
+call _printf
+add esp,4
+jmp L161
+L226:
+lea edi,(L227)
+push edi
+call _printf
+add esp,4
+jmp L161
+L228:
+lea edi,(L229)
+push edi
+call _printf
+add esp,4
+jmp L161
+L230:
+lea edi,(L231)
+push edi
+call _printf
+add esp,4
+jmp L161
+L232:
+lea edi,(L233)
+push edi
+call _printf
+add esp,4
+jmp L161
+L234:
+lea edi,(L235)
+push edi
+call _printf
+add esp,4
+jmp L161
+L236:
+lea edi,(L237)
+push edi
+call _printf
+add esp,4
+jmp L161
+L238:
+lea edi,(_yytext)
+push edi
+lea edi,(L239)
+push edi
+call _printf
+add esp,8
+jmp L161
+L240:
+lea edi,(_yytext)
+push edi
+lea edi,(L157)
+push edi
+call _printf
+add esp,8
+jmp L161
+L158:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+public _yywrap
+_yywrap:
+push ebx
+push esi
+push edi
+push ebp
+mov ebp,esp
+mov eax,1
+L243:
+mov esp,ebp
+pop ebp
+pop edi
+pop esi
+pop ebx
+ret
+_TEXT ends
+_DATA segment
+public _yyv
+align 4
+_yyv label byte
+db 600 dup (0)
+public _yyfnd
+align 4
+_yyfnd label byte
+db 4 dup (0)
+public _yyolsp
+align 4
+_yyolsp label byte
+db 4 dup (0)
+public _yylsp
+align 4
+_yylsp label byte
+db 4 dup (0)
+public _yylstate
+align 4
+_yylstate label byte
+db 800 dup (0)
+public _yyestate
+align 4
+_yyestate label byte
+db 4 dup (0)
+public _yytchar
+align 4
+_yytchar label byte
+db 4 dup (0)
+public _yysbuf
+align 1
+_yysbuf label byte
+db 200 dup (0)
+public _yymorfg
+align 4
+_yymorfg label byte
+db 4 dup (0)
+public _yytext
+align 1
+_yytext label byte
+db 200 dup (0)
+public _yyleng
+align 4
+_yyleng label byte
+db 4 dup (0)
+_DATA ends
+extrn _printf:near
+_DATA segment
+_DATA ends
+extrn _fprintf:near
+_DATA segment
+_DATA ends
+extrn __flsbuf:near
+_DATA segment
+_DATA ends
+extrn __filbuf:near
+_DATA segment
+_DATA ends
+extrn __iob:near
+_DATA segment
+public _yyval
+align 4
+_yyval label byte
+db 4 dup (0)
+public _yylval
+align 4
+_yylval label byte
+db 4 dup (0)
+_DATA ends
+_TEXT segment
+align 1
+L239 label byte
+db 112
+db 117
+db 115
+db 104
+db 32
+db 37
+db 115
+db 10
+db 0
+align 1
+L237 label byte
+db 108
+db 111
+db 97
+db 100
+db 10
+db 0
+align 1
+L235 label byte
+db 110
+db 101
+db 103
+db 97
+db 116
+db 101
+db 10
+db 0
+align 1
+L233 label byte
+db 100
+db 105
+db 118
+db 105
+db 100
+db 101
+db 10
+db 0
+align 1
+L231 label byte
+db 109
+db 117
+db 108
+db 116
+db 105
+db 112
+db 108
+db 121
+db 10
+db 0
+align 1
+L229 label byte
+db 110
+db 101
+db 103
+db 97
+db 116
+db 101
+db 10
+db 97
+db 100
+db 100
+db 10
+db 0
+align 1
+L227 label byte
+db 97
+db 100
+db 100
+db 10
+db 0
+align 1
+L225 label byte
+db 115
+db 116
+db 111
+db 114
+db 101
+db 10
+db 0
+align 1
+L204 label byte
+db 115
+db 121
+db 110
+db 116
+db 97
+db 120
+db 32
+db 101
+db 114
+db 114
+db 111
+db 114
+db 0
+align 1
+L165 label byte
+db 121
+db 97
+db 99
+db 99
+db 32
+db 115
+db 116
+db 97
+db 99
+db 107
+db 32
+db 111
+db 118
+db 101
+db 114
+db 102
+db 108
+db 111
+db 119
+db 0
+align 1
+L157 label byte
+db 37
+db 115
+db 10
+db 0
+align 1
+L17 label byte
+db 98
+db 97
+db 100
+db 32
+db 115
+db 119
+db 105
+db 116
+db 99
+db 104
+db 32
+db 121
+db 121
+db 108
+db 111
+db 111
+db 107
+db 32
+db 37
+db 100
+db 0
+_TEXT ends
+end
diff --git a/libs/cmdlib.h b/libs/cmdlib.h
new file mode 100755
index 0000000..72fba67
--- /dev/null
+++ b/libs/cmdlib.h
@@ -0,0 +1,97 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// start of shared cmdlib stuff
+//
+
+#ifndef __CMDLIB__
+#define __CMDLIB__
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <ctype.h>
+#include <time.h>
+#include <stdarg.h>
+
+#ifndef __BYTEBOOL__
+#define __BYTEBOOL__
+
+#ifndef __cplusplus
+ typedef enum {false, true} boolean;
+#else
+ typedef unsigned char boolean;
+#endif
+
+
+typedef unsigned char byte;
+//typedef unsigned char byte;
+#endif
+
+FILE *SafeOpenWrite (const char *filename);
+FILE *SafeOpenRead (const char *filename);
+void SafeRead (FILE *f, void *buffer, int count);
+void SafeWrite (FILE *f, const void *buffer, int count);
+int LoadFile (const char *filename, void **bufferptr);
+int LoadFileNoCrash (const char *filename, void **bufferptr);
+void SaveFile (const char *filename, void *buffer, int count);
+void DefaultExtension (char *path, char *extension);
+void DefaultPath (char *path, char *basepath);
+void StripFilename (char *path);
+void StripExtension (char *path);
+void ExtractFilePath (const char *path, char *dest);
+void ExtractFileName (const char *path, char *dest);
+void ExtractFileBase (const char *path, char *dest);
+void ExtractFileExtension (const char *path, char *dest);
+short BigShort (short l);
+short LittleShort (short l);
+int BigLong (int l);
+int LittleLong (int l);
+float BigFloat (float l);
+float LittleFloat (float l);
+void *qmalloc (size_t size);
+void* qblockmalloc(size_t nSize);
+
+
+
+// error and printf functions
+typedef void (PFN_ERR)(const char *pFormat, ...);
+typedef void (PFN_PRINTF)(const char *pFormat, ...);
+typedef void (PFN_ERR_NUM)(int nNum, const char *pFormat, ...);
+typedef void (PFN_PRINTF_NUM)(int nNum, const char *pFormat, ...);
+
+void Error(const char *pFormat, ...);
+void Printf(const char *pFormat, ...);
+void ErrorNum(int n, const char *pFormat, ...);
+void PrintfNum(int n, const char *pFormat, ...);
+
+void SetErrorHandler(PFN_ERR pe);
+void SetPrintfHandler(PFN_PRINTF pe);
+void SetErrorHandlerNum(PFN_ERR_NUM pe);
+void SetPrintfHandlerNum(PFN_PRINTF_NUM pe);
+void ConvertDOSToUnixName( char *dst, const char *src );
+char* StrDup(char* pStr);
+char* StrDup(const char* pStr);
+
+
+#endif \ No newline at end of file
diff --git a/libs/cmdlib/cmdlib.cpp b/libs/cmdlib/cmdlib.cpp
new file mode 100755
index 0000000..c1e9d8b
--- /dev/null
+++ b/libs/cmdlib/cmdlib.cpp
@@ -0,0 +1,550 @@
+//
+// start of shared cmdlib stuff
+//
+
+
+#include "cmdlib.h"
+#include "windows.h"
+
+#define PATHSEPERATOR '/'
+
+// rad additions
+// 11.29.99
+PFN_ERR *g_pfnError = NULL;
+PFN_PRINTF *g_pfnPrintf = NULL;
+PFN_ERR_NUM *g_pfnErrorNum = NULL;
+PFN_PRINTF_NUM *g_pfnPrintfNum = NULL;
+
+
+void Error(const char *pFormat, ...)
+{
+ if (g_pfnError)
+ {
+ va_list arg_ptr;
+ va_start(arg_ptr, pFormat);
+ g_pfnError(pFormat, arg_ptr);
+ va_end(arg_ptr);
+ }
+}
+
+void Printf(const char *pFormat, ...)
+{
+ if (g_pfnPrintf)
+ {
+ va_list arg_ptr;
+ va_start(arg_ptr, pFormat);
+ g_pfnPrintf(pFormat, arg_ptr);
+ va_end(arg_ptr);
+ }
+}
+
+void ErrorNum(int nErr, const char *pFormat, ...)
+{
+ if (g_pfnErrorNum)
+ {
+ va_list arg_ptr;
+ va_start(arg_ptr, pFormat);
+ g_pfnErrorNum(nErr, pFormat, arg_ptr);
+ va_end(arg_ptr);
+ }
+}
+
+void PrintfNum(int nErr, const char *pFormat, ...)
+{
+ if (g_pfnPrintfNum)
+ {
+ va_list arg_ptr;
+ va_start(arg_ptr, pFormat);
+ g_pfnPrintfNum(nErr, pFormat, arg_ptr);
+ va_end(arg_ptr);
+ }
+}
+
+
+
+void SetErrorHandler(PFN_ERR pe)
+{
+ g_pfnError = pe;
+}
+
+void SetPrintfHandler(PFN_PRINTF pe)
+{
+ g_pfnPrintf = pe;
+}
+
+void SetErrorHandlerNum(PFN_ERR_NUM pe)
+{
+ g_pfnErrorNum = pe;
+}
+
+void SetPrintfHandler(PFN_PRINTF_NUM pe)
+{
+ g_pfnPrintfNum = pe;
+}
+
+
+
+// rad end
+
+#define MEM_BLOCKSIZE 4096
+void* qblockmalloc(size_t nSize)
+{
+ void *b;
+ // round up to threshold
+ int nAllocSize = nSize % MEM_BLOCKSIZE;
+ if ( nAllocSize > 0)
+ {
+ nSize += MEM_BLOCKSIZE - nAllocSize;
+ }
+ b = malloc(nSize + 1);
+ memset (b, 0, nSize);
+ return b;
+}
+
+void* qmalloc (size_t nSize)
+{
+ void *b;
+ b = malloc(nSize + 1);
+ memset (b, 0, nSize);
+ return b;
+}
+
+/*
+================
+Q_filelength
+================
+*/
+int Q_filelength (FILE *f)
+{
+ int pos;
+ int end;
+
+ pos = ftell (f);
+ fseek (f, 0, SEEK_END);
+ end = ftell (f);
+ fseek (f, pos, SEEK_SET);
+
+ return end;
+}
+
+
+// FIXME: need error handler
+FILE *SafeOpenWrite (const char *filename)
+{
+ FILE *f;
+
+ f = fopen(filename, "wb");
+
+ if (!f)
+ {
+ Error ("Error opening %s: %s",filename,strerror(errno));
+ }
+
+ return f;
+}
+
+FILE *SafeOpenRead (const char *filename)
+{
+ FILE *f;
+
+ f = fopen(filename, "rb");
+
+ if (!f)
+ {
+ Error ("Error opening %s: %s",filename,strerror(errno));
+ }
+
+ return f;
+}
+
+
+void SafeRead (FILE *f, void *buffer, int count)
+{
+ if ( (int)fread (buffer, 1, count, f) != count)
+ Error ("File read failure");
+}
+
+
+void SafeWrite (FILE *f, const void *buffer, int count)
+{
+ if ( (int)fwrite (buffer, 1, count, f) != count)
+ Error ("File read failure");
+}
+
+
+
+/*
+==============
+LoadFile
+==============
+*/
+int LoadFile (const char *filename, void **bufferptr)
+{
+ FILE *f;
+ int length;
+ void *buffer;
+
+ *bufferptr = NULL;
+
+ if (filename == NULL || strlen(filename) == 0)
+ {
+ return -1;
+ }
+
+ f = fopen (filename, "rb");
+ if (!f)
+ {
+ return -1;
+ }
+ length = Q_filelength (f);
+ buffer = qblockmalloc (length+1);
+ ((char *)buffer)[length] = 0;
+ SafeRead (f, buffer, length);
+ fclose (f);
+
+ *bufferptr = buffer;
+ return length;
+}
+
+
+/*
+==============
+LoadFileNoCrash
+
+returns -1 length if not present
+==============
+*/
+int LoadFileNoCrash (const char *filename, void **bufferptr)
+{
+ FILE *f;
+ int length;
+ void *buffer;
+
+ f = fopen (filename, "rb");
+ if (!f)
+ return -1;
+ length = Q_filelength (f);
+ buffer = qmalloc (length+1);
+ ((char *)buffer)[length] = 0;
+ SafeRead (f, buffer, length);
+ fclose (f);
+
+ *bufferptr = buffer;
+ return length;
+}
+
+
+/*
+==============
+SaveFile
+==============
+*/
+void SaveFile (const char *filename, void *buffer, int count)
+{
+ FILE *f;
+
+ f = SafeOpenWrite (filename);
+ SafeWrite (f, buffer, count);
+ fclose (f);
+}
+
+
+
+void DefaultExtension (char *path, char *extension)
+{
+ char *src;
+//
+// if path doesn't have a .EXT, append extension
+// (extension should include the .)
+//
+ src = path + strlen(path) - 1;
+
+ while (*src != PATHSEPERATOR && src != path)
+ {
+ if (*src == '.')
+ return; // it has an extension
+ src--;
+ }
+
+ strcat (path, extension);
+}
+
+
+void DefaultPath (char *path, char *basepath)
+{
+ char temp[128];
+
+ if (path[0] == PATHSEPERATOR)
+ return; // absolute path location
+ strcpy (temp,path);
+ strcpy (path,basepath);
+ strcat (path,temp);
+}
+
+
+void StripFilename (char *path)
+{
+ int length;
+
+ length = strlen(path)-1;
+ while (length > 0 && path[length] != PATHSEPERATOR)
+ length--;
+ path[length] = 0;
+}
+
+void StripExtension (char *path)
+{
+ int length;
+
+ length = strlen(path)-1;
+ while (length > 0 && path[length] != '.')
+ {
+ length--;
+ if (path[length] == '/')
+ return; // no extension
+ }
+ if (length)
+ path[length] = 0;
+}
+
+
+/*
+====================
+Extract file parts
+====================
+*/
+void ExtractFilePath (const char *path, char *dest)
+{
+ const char *src;
+
+ src = path + strlen(path) - 1;
+
+//
+// back up until a \ or the start
+//
+ while (src != path && *(src-1) != PATHSEPERATOR)
+ src--;
+
+ memcpy (dest, path, src-path);
+ dest[src-path] = 0;
+}
+
+void ExtractFileName (const char *path, char *dest)
+{
+ const char *src;
+
+ src = path + strlen(path) - 1;
+
+//
+// back up until a \ or the start
+//
+ while (src != path && *(src-1) != '/'
+ && *(src-1) != '\\' )
+ src--;
+
+ while (*src)
+ {
+ *dest++ = *src++;
+ }
+ *dest = 0;
+}
+
+void ExtractFileBase (const char *path, char *dest)
+{
+ const char *src;
+
+ src = path + strlen(path) - 1;
+
+//
+// back up until a \ or the start
+//
+ while (src != path && *(src-1) != '/'
+ && *(src-1) != '\\' )
+ src--;
+
+ while (*src && *src != '.')
+ {
+ *dest++ = *src++;
+ }
+ *dest = 0;
+}
+
+void ExtractFileExtension (const char *path, char *dest)
+{
+ const char *src;
+
+ src = path + strlen(path) - 1;
+
+//
+// back up until a . or the start
+//
+ while (src != path && *(src-1) != '.')
+ src--;
+ if (src == path)
+ {
+ *dest = 0; // no extension
+ return;
+ }
+
+ strcpy (dest,src);
+}
+
+
+void ConvertDOSToUnixName( char *dst, const char *src )
+{
+ while ( *src )
+ {
+ if ( *src == '\\' )
+ *dst = '/';
+ else
+ *dst = *src;
+ dst++; src++;
+ }
+ *dst = 0;
+}
+
+
+char* StrDup(char* pStr)
+{
+ if (pStr)
+ {
+ return strcpy(new char[strlen(pStr)+1], pStr);
+ }
+ return NULL;
+}
+
+char* StrDup(const char* pStr)
+{
+ if (pStr)
+ {
+ return strcpy(new char[strlen(pStr)+1], pStr);
+ }
+ return NULL;
+}
+
+
+/*
+============================================================================
+
+ BYTE ORDER FUNCTIONS
+
+============================================================================
+*/
+
+#ifdef _SGI_SOURCE
+#define __BIG_ENDIAN__
+#endif
+
+#ifdef __BIG_ENDIAN__
+
+short LittleShort (short l)
+{
+ byte b1,b2;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+
+ return (b1<<8) + b2;
+}
+
+short BigShort (short l)
+{
+ return l;
+}
+
+
+int LittleLong (int l)
+{
+ byte b1,b2,b3,b4;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+ b3 = (l>>16)&255;
+ b4 = (l>>24)&255;
+
+ return ((int)b1<<24) + ((int)b2<<16) + ((int)b3<<8) + b4;
+}
+
+int BigLong (int l)
+{
+ return l;
+}
+
+
+float LittleFloat (float l)
+{
+ union {byte b[4]; float f;} in, out;
+
+ in.f = l;
+ out.b[0] = in.b[3];
+ out.b[1] = in.b[2];
+ out.b[2] = in.b[1];
+ out.b[3] = in.b[0];
+
+ return out.f;
+}
+
+float BigFloat (float l)
+{
+ return l;
+}
+
+
+#else
+
+
+short BigShort (short l)
+{
+ byte b1,b2;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+
+ return (b1<<8) + b2;
+}
+
+short LittleShort (short l)
+{
+ return l;
+}
+
+
+int BigLong (int l)
+{
+ byte b1,b2,b3,b4;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+ b3 = (l>>16)&255;
+ b4 = (l>>24)&255;
+
+ return ((int)b1<<24) + ((int)b2<<16) + ((int)b3<<8) + b4;
+}
+
+int LittleLong (int l)
+{
+ return l;
+}
+
+float BigFloat (float l)
+{
+ union {byte b[4]; float f;} in, out;
+
+ in.f = l;
+ out.b[0] = in.b[3];
+ out.b[1] = in.b[2];
+ out.b[2] = in.b[1];
+ out.b[3] = in.b[0];
+
+ return out.f;
+}
+
+float LittleFloat (float l)
+{
+ return l;
+}
+
+
+
+#endif
+
diff --git a/libs/cmdlib/cmdlib.vcproj b/libs/cmdlib/cmdlib.vcproj
new file mode 100755
index 0000000..f471b07
--- /dev/null
+++ b/libs/cmdlib/cmdlib.vcproj
@@ -0,0 +1,156 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+ ProjectType="Visual C++"
+ Version="7.10"
+ Name="cmdlib"
+ SccProjectName="&quot;$/source/q3radiant&quot;, FEFAAAAA"
+ SccLocalPath="..\..\q3radiant">
+ <Platforms>
+ <Platform
+ Name="Win32"/>
+ </Platforms>
+ <Configurations>
+ <Configuration
+ Name="Release|Win32"
+ OutputDirectory=".\Release"
+ IntermediateDirectory=".\Release"
+ ConfigurationType="4"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ AdditionalIncludeDirectories=".."
+ PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
+ StringPooling="TRUE"
+ RuntimeLibrary="0"
+ EnableFunctionLevelLinking="TRUE"
+ RuntimeTypeInfo="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Release/cmdlib.pch"
+ AssemblerListingLocation=".\Release/"
+ ObjectFile=".\Release/"
+ ProgramDataBaseFileName=".\Release/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ CompileAs="0"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile="..\cmdlib.lib"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCMIDLTool"/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Debug|Win32"
+ OutputDirectory=".\Debug"
+ IntermediateDirectory=".\Debug"
+ ConfigurationType="4"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=".."
+ PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
+ BasicRuntimeChecks="3"
+ RuntimeLibrary="1"
+ RuntimeTypeInfo="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Debug/cmdlib.pch"
+ AssemblerListingLocation=".\Debug/"
+ ObjectFile=".\Debug/"
+ ProgramDataBaseFileName=".\Debug/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"
+ CompileAs="0"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile="..\cmdlibd.lib"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCMIDLTool"/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ </Configurations>
+ <References>
+ </References>
+ <Files>
+ <Filter
+ Name="Source Files"
+ Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat">
+ <File
+ RelativePath="cmdlib.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <Filter
+ Name="Header Files"
+ Filter="h;hpp;hxx;hm;inl">
+ <File
+ RelativePath="..\cmdlib.h">
+ </File>
+ </Filter>
+ </Files>
+ <Globals>
+ </Globals>
+</VisualStudioProject>
diff --git a/libs/jpeg6/README b/libs/jpeg6/README
new file mode 100755
index 0000000..86cc206
--- /dev/null
+++ b/libs/jpeg6/README
@@ -0,0 +1,385 @@
+The Independent JPEG Group's JPEG software
+==========================================
+
+README for release 6b of 27-Mar-1998
+====================================
+
+This distribution contains the sixth public release of the Independent JPEG
+Group's free JPEG software. You are welcome to redistribute this software and
+to use it for any purpose, subject to the conditions under LEGAL ISSUES, below.
+
+Serious users of this software (particularly those incorporating it into
+larger programs) should contact IJG at jpeg-info@uunet.uu.net to be added to
+our electronic mailing list. Mailing list members are notified of updates
+and have a chance to participate in technical discussions, etc.
+
+This software is the work of Tom Lane, Philip Gladstone, Jim Boucher,
+Lee Crocker, Julian Minguillon, Luis Ortiz, George Phillips, Davide Rossi,
+Guido Vollbeding, Ge' Weijers, and other members of the Independent JPEG
+Group.
+
+IJG is not affiliated with the official ISO JPEG standards committee.
+
+
+DOCUMENTATION ROADMAP
+=====================
+
+This file contains the following sections:
+
+OVERVIEW General description of JPEG and the IJG software.
+LEGAL ISSUES Copyright, lack of warranty, terms of distribution.
+REFERENCES Where to learn more about JPEG.
+ARCHIVE LOCATIONS Where to find newer versions of this software.
+RELATED SOFTWARE Other stuff you should get.
+FILE FORMAT WARS Software *not* to get.
+TO DO Plans for future IJG releases.
+
+Other documentation files in the distribution are:
+
+User documentation:
+ install.doc How to configure and install the IJG software.
+ usage.doc Usage instructions for cjpeg, djpeg, jpegtran,
+ rdjpgcom, and wrjpgcom.
+ *.1 Unix-style man pages for programs (same info as usage.doc).
+ wizard.doc Advanced usage instructions for JPEG wizards only.
+ change.log Version-to-version change highlights.
+Programmer and internal documentation:
+ libjpeg.doc How to use the JPEG library in your own programs.
+ example.c Sample code for calling the JPEG library.
+ structure.doc Overview of the JPEG library's internal structure.
+ filelist.doc Road map of IJG files.
+ coderules.doc Coding style rules --- please read if you contribute code.
+
+Please read at least the files install.doc and usage.doc. Useful information
+can also be found in the JPEG FAQ (Frequently Asked Questions) article. See
+ARCHIVE LOCATIONS below to find out where to obtain the FAQ article.
+
+If you want to understand how the JPEG code works, we suggest reading one or
+more of the REFERENCES, then looking at the documentation files (in roughly
+the order listed) before diving into the code.
+
+
+OVERVIEW
+========
+
+This package contains C software to implement JPEG image compression and
+decompression. JPEG (pronounced "jay-peg") is a standardized compression
+method for full-color and gray-scale images. JPEG is intended for compressing
+"real-world" scenes; line drawings, cartoons and other non-realistic images
+are not its strong suit. JPEG is lossy, meaning that the output image is not
+exactly identical to the input image. Hence you must not use JPEG if you
+have to have identical output bits. However, on typical photographic images,
+very good compression levels can be obtained with no visible change, and
+remarkably high compression levels are possible if you can tolerate a
+low-quality image. For more details, see the references, or just experiment
+with various compression settings.
+
+This software implements JPEG baseline, extended-sequential, and progressive
+compression processes. Provision is made for supporting all variants of these
+processes, although some uncommon parameter settings aren't implemented yet.
+For legal reasons, we are not distributing code for the arithmetic-coding
+variants of JPEG; see LEGAL ISSUES. We have made no provision for supporting
+the hierarchical or lossless processes defined in the standard.
+
+We provide a set of library routines for reading and writing JPEG image files,
+plus two sample applications "cjpeg" and "djpeg", which use the library to
+perform conversion between JPEG and some other popular image file formats.
+The library is intended to be reused in other applications.
+
+In order to support file conversion and viewing software, we have included
+considerable functionality beyond the bare JPEG coding/decoding capability;
+for example, the color quantization modules are not strictly part of JPEG
+decoding, but they are essential for output to colormapped file formats or
+colormapped displays. These extra functions can be compiled out of the
+library if not required for a particular application. We have also included
+"jpegtran", a utility for lossless transcoding between different JPEG
+processes, and "rdjpgcom" and "wrjpgcom", two simple applications for
+inserting and extracting textual comments in JFIF files.
+
+The emphasis in designing this software has been on achieving portability and
+flexibility, while also making it fast enough to be useful. In particular,
+the software is not intended to be read as a tutorial on JPEG. (See the
+REFERENCES section for introductory material.) Rather, it is intended to
+be reliable, portable, industrial-strength code. We do not claim to have
+achieved that goal in every aspect of the software, but we strive for it.
+
+We welcome the use of this software as a component of commercial products.
+No royalty is required, but we do ask for an acknowledgement in product
+documentation, as described under LEGAL ISSUES.
+
+
+LEGAL ISSUES
+============
+
+In plain English:
+
+1. We don't promise that this software works. (But if you find any bugs,
+ please let us know!)
+2. You can use this software for whatever you want. You don't have to pay us.
+3. You may not pretend that you wrote this software. If you use it in a
+ program, you must acknowledge somewhere in your documentation that
+ you've used the IJG code.
+
+In legalese:
+
+The authors make NO WARRANTY or representation, either express or implied,
+with respect to this software, its quality, accuracy, merchantability, or
+fitness for a particular purpose. This software is provided "AS IS", and you,
+its user, assume the entire risk as to its quality and accuracy.
+
+This software is copyright (C) 1991-1998, Thomas G. Lane.
+All Rights Reserved except as specified below.
+
+Permission is hereby granted to use, copy, modify, and distribute this
+software (or portions thereof) for any purpose, without fee, subject to these
+conditions:
+(1) If any part of the source code for this software is distributed, then this
+README file must be included, with this copyright and no-warranty notice
+unaltered; and any additions, deletions, or changes to the original files
+must be clearly indicated in accompanying documentation.
+(2) If only executable code is distributed, then the accompanying
+documentation must state that "this software is based in part on the work of
+the Independent JPEG Group".
+(3) Permission for use of this software is granted only if the user accepts
+full responsibility for any undesirable consequences; the authors accept
+NO LIABILITY for damages of any kind.
+
+These conditions apply to any software derived from or based on the IJG code,
+not just to the unmodified library. If you use our work, you ought to
+acknowledge us.
+
+Permission is NOT granted for the use of any IJG author's name or company name
+in advertising or publicity relating to this software or products derived from
+it. This software may be referred to only as "the Independent JPEG Group's
+software".
+
+We specifically permit and encourage the use of this software as the basis of
+commercial products, provided that all warranty or liability claims are
+assumed by the product vendor.
+
+
+ansi2knr.c is included in this distribution by permission of L. Peter Deutsch,
+sole proprietor of its copyright holder, Aladdin Enterprises of Menlo Park, CA.
+ansi2knr.c is NOT covered by the above copyright and conditions, but instead
+by the usual distribution terms of the Free Software Foundation; principally,
+that you must include source code if you redistribute it. (See the file
+ansi2knr.c for full details.) However, since ansi2knr.c is not needed as part
+of any program generated from the IJG code, this does not limit you more than
+the foregoing paragraphs do.
+
+The Unix configuration script "configure" was produced with GNU Autoconf.
+It is copyright by the Free Software Foundation but is freely distributable.
+The same holds for its supporting scripts (config.guess, config.sub,
+ltconfig, ltmain.sh). Another support script, install-sh, is copyright
+by M.I.T. but is also freely distributable.
+
+It appears that the arithmetic coding option of the JPEG spec is covered by
+patents owned by IBM, AT&T, and Mitsubishi. Hence arithmetic coding cannot
+legally be used without obtaining one or more licenses. For this reason,
+support for arithmetic coding has been removed from the free JPEG software.
+(Since arithmetic coding provides only a marginal gain over the unpatented
+Huffman mode, it is unlikely that very many implementations will support it.)
+So far as we are aware, there are no patent restrictions on the remaining
+code.
+
+The IJG distribution formerly included code to read and write GIF files.
+To avoid entanglement with the Unisys LZW patent, GIF reading support has
+been removed altogether, and the GIF writer has been simplified to produce
+"uncompressed GIFs". This technique does not use the LZW algorithm; the
+resulting GIF files are larger than usual, but are readable by all standard
+GIF decoders.
+
+We are required to state that
+ "The Graphics Interchange Format(c) is the Copyright property of
+ CompuServe Incorporated. GIF(sm) is a Service Mark property of
+ CompuServe Incorporated."
+
+
+REFERENCES
+==========
+
+We highly recommend reading one or more of these references before trying to
+understand the innards of the JPEG software.
+
+The best short technical introduction to the JPEG compression algorithm is
+ Wallace, Gregory K. "The JPEG Still Picture Compression Standard",
+ Communications of the ACM, April 1991 (vol. 34 no. 4), pp. 30-44.
+(Adjacent articles in that issue discuss MPEG motion picture compression,
+applications of JPEG, and related topics.) If you don't have the CACM issue
+handy, a PostScript file containing a revised version of Wallace's article is
+available at ftp://ftp.uu.net/graphics/jpeg/wallace.ps.gz. The file (actually
+a preprint for an article that appeared in IEEE Trans. Consumer Electronics)
+omits the sample images that appeared in CACM, but it includes corrections
+and some added material. Note: the Wallace article is copyright ACM and IEEE,
+and it may not be used for commercial purposes.
+
+A somewhat less technical, more leisurely introduction to JPEG can be found in
+"The Data Compression Book" by Mark Nelson and Jean-loup Gailly, published by
+M&T Books (New York), 2nd ed. 1996, ISBN 1-55851-434-1. This book provides
+good explanations and example C code for a multitude of compression methods
+including JPEG. It is an excellent source if you are comfortable reading C
+code but don't know much about data compression in general. The book's JPEG
+sample code is far from industrial-strength, but when you are ready to look
+at a full implementation, you've got one here...
+
+The best full description of JPEG is the textbook "JPEG Still Image Data
+Compression Standard" by William B. Pennebaker and Joan L. Mitchell, published
+by Van Nostrand Reinhold, 1993, ISBN 0-442-01272-1. Price US$59.95, 638 pp.
+The book includes the complete text of the ISO JPEG standards (DIS 10918-1
+and draft DIS 10918-2). This is by far the most complete exposition of JPEG
+in existence, and we highly recommend it.
+
+The JPEG standard itself is not available electronically; you must order a
+paper copy through ISO or ITU. (Unless you feel a need to own a certified
+official copy, we recommend buying the Pennebaker and Mitchell book instead;
+it's much cheaper and includes a great deal of useful explanatory material.)
+In the USA, copies of the standard may be ordered from ANSI Sales at (212)
+642-4900, or from Global Engineering Documents at (800) 854-7179. (ANSI
+doesn't take credit card orders, but Global does.) It's not cheap: as of
+1992, ANSI was charging $95 for Part 1 and $47 for Part 2, plus 7%
+shipping/handling. The standard is divided into two parts, Part 1 being the
+actual specification, while Part 2 covers compliance testing methods. Part 1
+is titled "Digital Compression and Coding of Continuous-tone Still Images,
+Part 1: Requirements and guidelines" and has document numbers ISO/IEC IS
+10918-1, ITU-T T.81. Part 2 is titled "Digital Compression and Coding of
+Continuous-tone Still Images, Part 2: Compliance testing" and has document
+numbers ISO/IEC IS 10918-2, ITU-T T.83.
+
+Some extensions to the original JPEG standard are defined in JPEG Part 3,
+a newer ISO standard numbered ISO/IEC IS 10918-3 and ITU-T T.84. IJG
+currently does not support any Part 3 extensions.
+
+The JPEG standard does not specify all details of an interchangeable file
+format. For the omitted details we follow the "JFIF" conventions, revision
+1.02. A copy of the JFIF spec is available from:
+ Literature Department
+ C-Cube Microsystems, Inc.
+ 1778 McCarthy Blvd.
+ Milpitas, CA 95035
+ phone (408) 944-6300, fax (408) 944-6314
+A PostScript version of this document is available by FTP at
+ftp://ftp.uu.net/graphics/jpeg/jfif.ps.gz. There is also a plain text
+version at ftp://ftp.uu.net/graphics/jpeg/jfif.txt.gz, but it is missing
+the figures.
+
+The TIFF 6.0 file format specification can be obtained by FTP from
+ftp://ftp.sgi.com/graphics/tiff/TIFF6.ps.gz. The JPEG incorporation scheme
+found in the TIFF 6.0 spec of 3-June-92 has a number of serious problems.
+IJG does not recommend use of the TIFF 6.0 design (TIFF Compression tag 6).
+Instead, we recommend the JPEG design proposed by TIFF Technical Note #2
+(Compression tag 7). Copies of this Note can be obtained from ftp.sgi.com or
+from ftp://ftp.uu.net/graphics/jpeg/. It is expected that the next revision
+of the TIFF spec will replace the 6.0 JPEG design with the Note's design.
+Although IJG's own code does not support TIFF/JPEG, the free libtiff library
+uses our library to implement TIFF/JPEG per the Note. libtiff is available
+from ftp://ftp.sgi.com/graphics/tiff/.
+
+
+ARCHIVE LOCATIONS
+=================
+
+The "official" archive site for this software is ftp.uu.net (Internet
+address 192.48.96.9). The most recent released version can always be found
+there in directory graphics/jpeg. This particular version will be archived
+as ftp://ftp.uu.net/graphics/jpeg/jpegsrc.v6b.tar.gz. If you don't have
+direct Internet access, UUNET's archives are also available via UUCP; contact
+help@uunet.uu.net for information on retrieving files that way.
+
+Numerous Internet sites maintain copies of the UUNET files. However, only
+ftp.uu.net is guaranteed to have the latest official version.
+
+You can also obtain this software in DOS-compatible "zip" archive format from
+the SimTel archives (ftp://ftp.simtel.net/pub/simtelnet/msdos/graphics/), or
+on CompuServe in the Graphics Support forum (GO CIS:GRAPHSUP), library 12
+"JPEG Tools". Again, these versions may sometimes lag behind the ftp.uu.net
+release.
+
+The JPEG FAQ (Frequently Asked Questions) article is a useful source of
+general information about JPEG. It is updated constantly and therefore is
+not included in this distribution. The FAQ is posted every two weeks to
+Usenet newsgroups comp.graphics.misc, news.answers, and other groups.
+It is available on the World Wide Web at http://www.faqs.org/faqs/jpeg-faq/
+and other news.answers archive sites, including the official news.answers
+archive at rtfm.mit.edu: ftp://rtfm.mit.edu/pub/usenet/news.answers/jpeg-faq/.
+If you don't have Web or FTP access, send e-mail to mail-server@rtfm.mit.edu
+with body
+ send usenet/news.answers/jpeg-faq/part1
+ send usenet/news.answers/jpeg-faq/part2
+
+
+RELATED SOFTWARE
+================
+
+Numerous viewing and image manipulation programs now support JPEG. (Quite a
+few of them use this library to do so.) The JPEG FAQ described above lists
+some of the more popular free and shareware viewers, and tells where to
+obtain them on Internet.
+
+If you are on a Unix machine, we highly recommend Jef Poskanzer's free
+PBMPLUS software, which provides many useful operations on PPM-format image
+files. In particular, it can convert PPM images to and from a wide range of
+other formats, thus making cjpeg/djpeg considerably more useful. The latest
+version is distributed by the NetPBM group, and is available from numerous
+sites, notably ftp://wuarchive.wustl.edu/graphics/graphics/packages/NetPBM/.
+Unfortunately PBMPLUS/NETPBM is not nearly as portable as the IJG software is;
+you are likely to have difficulty making it work on any non-Unix machine.
+
+A different free JPEG implementation, written by the PVRG group at Stanford,
+is available from ftp://havefun.stanford.edu/pub/jpeg/. This program
+is designed for research and experimentation rather than production use;
+it is slower, harder to use, and less portable than the IJG code, but it
+is easier to read and modify. Also, the PVRG code supports lossless JPEG,
+which we do not. (On the other hand, it doesn't do progressive JPEG.)
+
+
+FILE FORMAT WARS
+================
+
+Some JPEG programs produce files that are not compatible with our library.
+The root of the problem is that the ISO JPEG committee failed to specify a
+concrete file format. Some vendors "filled in the blanks" on their own,
+creating proprietary formats that no one else could read. (For example, none
+of the early commercial JPEG implementations for the Macintosh were able to
+exchange compressed files.)
+
+The file format we have adopted is called JFIF (see REFERENCES). This format
+has been agreed to by a number of major commercial JPEG vendors, and it has
+become the de facto standard. JFIF is a minimal or "low end" representation.
+We recommend the use of TIFF/JPEG (TIFF revision 6.0 as modified by TIFF
+Technical Note #2) for "high end" applications that need to record a lot of
+additional data about an image. TIFF/JPEG is fairly new and not yet widely
+supported, unfortunately.
+
+The upcoming JPEG Part 3 standard defines a file format called SPIFF.
+SPIFF is interoperable with JFIF, in the sense that most JFIF decoders should
+be able to read the most common variant of SPIFF. SPIFF has some technical
+advantages over JFIF, but its major claim to fame is simply that it is an
+official standard rather than an informal one. At this point it is unclear
+whether SPIFF will supersede JFIF or whether JFIF will remain the de-facto
+standard. IJG intends to support SPIFF once the standard is frozen, but we
+have not decided whether it should become our default output format or not.
+(In any case, our decoder will remain capable of reading JFIF indefinitely.)
+
+Various proprietary file formats incorporating JPEG compression also exist.
+We have little or no sympathy for the existence of these formats. Indeed,
+one of the original reasons for developing this free software was to help
+force convergence on common, open format standards for JPEG files. Don't
+use a proprietary file format!
+
+
+TO DO
+=====
+
+The major thrust for v7 will probably be improvement of visual quality.
+The current method for scaling the quantization tables is known not to be
+very good at low Q values. We also intend to investigate block boundary
+smoothing, "poor man's variable quantization", and other means of improving
+quality-vs-file-size performance without sacrificing compatibility.
+
+In future versions, we are considering supporting some of the upcoming JPEG
+Part 3 extensions --- principally, variable quantization and the SPIFF file
+format.
+
+As always, speeding things up is of great interest.
+
+Please send bug reports, offers of help, etc. to jpeg-info@uunet.uu.net.
diff --git a/libs/jpeg6/jchuff.h b/libs/jpeg6/jchuff.h
new file mode 100755
index 0000000..0a81d54
--- /dev/null
+++ b/libs/jpeg6/jchuff.h
@@ -0,0 +1,34 @@
+/*
+ * jchuff.h
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains declarations for Huffman entropy encoding routines
+ * that are shared between the sequential encoder (jchuff.c) and the
+ * progressive encoder (jcphuff.c). No other modules need to see these.
+ */
+
+/* Derived data constructed for each Huffman table */
+
+typedef struct {
+ unsigned int ehufco[256]; /* code for each symbol */
+ char ehufsi[256]; /* length of code for each symbol */
+ /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
+} c_derived_tbl;
+
+/* Short forms of external names for systems with brain-damaged linkers. */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jpeg_make_c_derived_tbl jMkCDerived
+#define jpeg_gen_optimal_table jGenOptTbl
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+/* Expand a Huffman table definition into the derived format */
+EXTERN void jpeg_make_c_derived_tbl JPP((j_compress_ptr cinfo,
+ JHUFF_TBL * htbl, c_derived_tbl ** pdtbl));
+
+/* Generate an optimal table definition given the specified counts */
+EXTERN void jpeg_gen_optimal_table JPP((j_compress_ptr cinfo,
+ JHUFF_TBL * htbl, long freq[]));
diff --git a/libs/jpeg6/jcomapi.cpp b/libs/jpeg6/jcomapi.cpp
new file mode 100755
index 0000000..8f417c0
--- /dev/null
+++ b/libs/jpeg6/jcomapi.cpp
@@ -0,0 +1,94 @@
+/*
+ * jcomapi.c
+ *
+ * Copyright (C) 1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains application interface routines that are used for both
+ * compression and decompression.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/*
+ * Abort processing of a JPEG compression or decompression operation,
+ * but don't destroy the object itself.
+ *
+ * For this, we merely clean up all the nonpermanent memory pools.
+ * Note that temp files (virtual arrays) are not allowed to belong to
+ * the permanent pool, so we will be able to close all temp files here.
+ * Closing a data source or destination, if necessary, is the application's
+ * responsibility.
+ */
+
+GLOBAL void
+jpeg_abort (j_common_ptr cinfo)
+{
+ int pool;
+
+ /* Releasing pools in reverse order might help avoid fragmentation
+ * with some (brain-damaged) malloc libraries.
+ */
+ for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
+ (*cinfo->mem->free_pool) (cinfo, pool);
+ }
+
+ /* Reset overall state for possible reuse of object */
+ cinfo->global_state = (cinfo->is_decompressor ? DSTATE_START : CSTATE_START);
+}
+
+
+/*
+ * Destruction of a JPEG object.
+ *
+ * Everything gets deallocated except the master jpeg_compress_struct itself
+ * and the error manager struct. Both of these are supplied by the application
+ * and must be freed, if necessary, by the application. (Often they are on
+ * the stack and so don't need to be freed anyway.)
+ * Closing a data source or destination, if necessary, is the application's
+ * responsibility.
+ */
+
+GLOBAL void
+jpeg_destroy (j_common_ptr cinfo)
+{
+ /* We need only tell the memory manager to release everything. */
+ /* NB: mem pointer is NULL if memory mgr failed to initialize. */
+ if (cinfo->mem != NULL)
+ (*cinfo->mem->self_destruct) (cinfo);
+ cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
+ cinfo->global_state = 0; /* mark it destroyed */
+}
+
+
+/*
+ * Convenience routines for allocating quantization and Huffman tables.
+ * (Would jutils.c be a more reasonable place to put these?)
+ */
+
+GLOBAL JQUANT_TBL *
+jpeg_alloc_quant_table (j_common_ptr cinfo)
+{
+ JQUANT_TBL *tbl;
+
+ tbl = (JQUANT_TBL *)
+ (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
+ tbl->sent_table = FALSE; /* make sure this is false in any new table */
+ return tbl;
+}
+
+
+GLOBAL JHUFF_TBL *
+jpeg_alloc_huff_table (j_common_ptr cinfo)
+{
+ JHUFF_TBL *tbl;
+
+ tbl = (JHUFF_TBL *)
+ (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
+ tbl->sent_table = FALSE; /* make sure this is false in any new table */
+ return tbl;
+}
diff --git a/libs/jpeg6/jconfig.h b/libs/jpeg6/jconfig.h
new file mode 100755
index 0000000..187ecfc
--- /dev/null
+++ b/libs/jpeg6/jconfig.h
@@ -0,0 +1,41 @@
+/* jconfig.wat --- jconfig.h for Watcom C/C++ on MS-DOS or OS/2. */
+/* see jconfig.doc for explanations */
+
+#define HAVE_PROTOTYPES
+#define HAVE_UNSIGNED_CHAR
+#define HAVE_UNSIGNED_SHORT
+/* #define void char */
+/* #define const */
+#define CHAR_IS_UNSIGNED
+#define HAVE_STDDEF_H
+#define HAVE_STDLIB_H
+#undef NEED_BSD_STRINGS
+#undef NEED_SYS_TYPES_H
+#undef NEED_FAR_POINTERS /* Watcom uses flat 32-bit addressing */
+#undef NEED_SHORT_EXTERNAL_NAMES
+#undef INCOMPLETE_TYPES_BROKEN
+
+#define JDCT_DEFAULT JDCT_FLOAT
+#define JDCT_FASTEST JDCT_FLOAT
+
+#ifdef JPEG_INTERNALS
+
+#undef RIGHT_SHIFT_IS_UNSIGNED
+
+#endif /* JPEG_INTERNALS */
+
+#ifdef JPEG_CJPEG_DJPEG
+
+#define BMP_SUPPORTED /* BMP image file format */
+#define GIF_SUPPORTED /* GIF image file format */
+#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
+#undef RLE_SUPPORTED /* Utah RLE image file format */
+#define TARGA_SUPPORTED /* Targa image file format */
+
+#undef TWO_FILE_COMMANDLINE /* optional */
+#define USE_SETMODE /* Needed to make one-file style work in Watcom */
+#undef NEED_SIGNAL_CATCHER /* Define this if you use jmemname.c */
+#undef DONT_USE_B_MODE
+#undef PROGRESS_REPORT /* optional */
+
+#endif /* JPEG_CJPEG_DJPEG */
diff --git a/libs/jpeg6/jdapimin.cpp b/libs/jpeg6/jdapimin.cpp
new file mode 100755
index 0000000..1bae6a2
--- /dev/null
+++ b/libs/jpeg6/jdapimin.cpp
@@ -0,0 +1,400 @@
+/*
+ * jdapimin.c
+ *
+ * Copyright (C) 1994-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains application interface code for the decompression half
+ * of the JPEG library. These are the "minimum" API routines that may be
+ * needed in either the normal full-decompression case or the
+ * transcoding-only case.
+ *
+ * Most of the routines intended to be called directly by an application
+ * are in this file or in jdapistd.c. But also see jcomapi.c for routines
+ * shared by compression and decompression, and jdtrans.c for the transcoding
+ * case.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/*
+ * Initialization of a JPEG decompression object.
+ * The error manager must already be set up (in case memory manager fails).
+ */
+
+GLOBAL void
+jpeg_create_decompress (j_decompress_ptr cinfo)
+{
+ int i;
+
+ /* For debugging purposes, zero the whole master structure.
+ * But error manager pointer is already there, so save and restore it.
+ */
+ {
+ struct jpeg_error_mgr * err = cinfo->err;
+ i = sizeof(struct jpeg_decompress_struct);
+ i = SIZEOF(struct jpeg_decompress_struct);
+ MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
+ cinfo->err = err;
+ }
+ cinfo->is_decompressor = TRUE;
+
+ /* Initialize a memory manager instance for this object */
+ jinit_memory_mgr((j_common_ptr) cinfo);
+
+ /* Zero out pointers to permanent structures. */
+ cinfo->progress = NULL;
+ cinfo->src = NULL;
+
+ for (i = 0; i < NUM_QUANT_TBLS; i++)
+ cinfo->quant_tbl_ptrs[i] = NULL;
+
+ for (i = 0; i < NUM_HUFF_TBLS; i++) {
+ cinfo->dc_huff_tbl_ptrs[i] = NULL;
+ cinfo->ac_huff_tbl_ptrs[i] = NULL;
+ }
+
+ /* Initialize marker processor so application can override methods
+ * for COM, APPn markers before calling jpeg_read_header.
+ */
+ jinit_marker_reader(cinfo);
+
+ /* And initialize the overall input controller. */
+ jinit_input_controller(cinfo);
+
+ /* OK, I'm ready */
+ cinfo->global_state = DSTATE_START;
+}
+
+
+/*
+ * Destruction of a JPEG decompression object
+ */
+
+GLOBAL void
+jpeg_destroy_decompress (j_decompress_ptr cinfo)
+{
+ jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
+}
+
+
+/*
+ * Abort processing of a JPEG decompression operation,
+ * but don't destroy the object itself.
+ */
+
+GLOBAL void
+jpeg_abort_decompress (j_decompress_ptr cinfo)
+{
+ jpeg_abort((j_common_ptr) cinfo); /* use common routine */
+}
+
+
+/*
+ * Install a special processing method for COM or APPn markers.
+ */
+
+GLOBAL void
+jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
+ jpeg_marker_parser_method routine)
+{
+ if (marker_code == JPEG_COM)
+ cinfo->marker->process_COM = routine;
+ else if (marker_code >= JPEG_APP0 && marker_code <= JPEG_APP0+15)
+ cinfo->marker->process_APPn[marker_code-JPEG_APP0] = routine;
+ else
+ ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
+}
+
+
+/*
+ * Set default decompression parameters.
+ */
+
+LOCAL void
+default_decompress_parms (j_decompress_ptr cinfo)
+{
+ /* Guess the input colorspace, and set output colorspace accordingly. */
+ /* (Wish JPEG committee had provided a real way to specify this...) */
+ /* Note application may override our guesses. */
+ switch (cinfo->num_components) {
+ case 1:
+ cinfo->jpeg_color_space = JCS_GRAYSCALE;
+ cinfo->out_color_space = JCS_GRAYSCALE;
+ break;
+
+ case 3:
+ if (cinfo->saw_JFIF_marker) {
+ cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
+ } else if (cinfo->saw_Adobe_marker) {
+ switch (cinfo->Adobe_transform) {
+ case 0:
+ cinfo->jpeg_color_space = JCS_RGB;
+ break;
+ case 1:
+ cinfo->jpeg_color_space = JCS_YCbCr;
+ break;
+ default:
+ WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
+ cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
+ break;
+ }
+ } else {
+ /* Saw no special markers, try to guess from the component IDs */
+ int cid0 = cinfo->comp_info[0].component_id;
+ int cid1 = cinfo->comp_info[1].component_id;
+ int cid2 = cinfo->comp_info[2].component_id;
+
+ if (cid0 == 1 && cid1 == 2 && cid2 == 3)
+ cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
+ else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
+ cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
+ else {
+ TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
+ cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
+ }
+ }
+ /* Always guess RGB is proper output colorspace. */
+ cinfo->out_color_space = JCS_RGB;
+ break;
+
+ case 4:
+ if (cinfo->saw_Adobe_marker) {
+ switch (cinfo->Adobe_transform) {
+ case 0:
+ cinfo->jpeg_color_space = JCS_CMYK;
+ break;
+ case 2:
+ cinfo->jpeg_color_space = JCS_YCCK;
+ break;
+ default:
+ WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
+ cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
+ break;
+ }
+ } else {
+ /* No special markers, assume straight CMYK. */
+ cinfo->jpeg_color_space = JCS_CMYK;
+ }
+ cinfo->out_color_space = JCS_CMYK;
+ break;
+
+ default:
+ cinfo->jpeg_color_space = JCS_UNKNOWN;
+ cinfo->out_color_space = JCS_UNKNOWN;
+ break;
+ }
+
+ /* Set defaults for other decompression parameters. */
+ cinfo->scale_num = 1; /* 1:1 scaling */
+ cinfo->scale_denom = 1;
+ cinfo->output_gamma = 1.0;
+ cinfo->buffered_image = FALSE;
+ cinfo->raw_data_out = FALSE;
+ cinfo->dct_method = JDCT_DEFAULT;
+ cinfo->do_fancy_upsampling = TRUE;
+ cinfo->do_block_smoothing = TRUE;
+ cinfo->quantize_colors = FALSE;
+ /* We set these in case application only sets quantize_colors. */
+ cinfo->dither_mode = JDITHER_FS;
+#ifdef QUANT_2PASS_SUPPORTED
+ cinfo->two_pass_quantize = TRUE;
+#else
+ cinfo->two_pass_quantize = FALSE;
+#endif
+ cinfo->desired_number_of_colors = 256;
+ cinfo->colormap = NULL;
+ /* Initialize for no mode change in buffered-image mode. */
+ cinfo->enable_1pass_quant = FALSE;
+ cinfo->enable_external_quant = FALSE;
+ cinfo->enable_2pass_quant = FALSE;
+}
+
+
+/*
+ * Decompression startup: read start of JPEG datastream to see what's there.
+ * Need only initialize JPEG object and supply a data source before calling.
+ *
+ * This routine will read as far as the first SOS marker (ie, actual start of
+ * compressed data), and will save all tables and parameters in the JPEG
+ * object. It will also initialize the decompression parameters to default
+ * values, and finally return JPEG_HEADER_OK. On return, the application may
+ * adjust the decompression parameters and then call jpeg_start_decompress.
+ * (Or, if the application only wanted to determine the image parameters,
+ * the data need not be decompressed. In that case, call jpeg_abort or
+ * jpeg_destroy to release any temporary space.)
+ * If an abbreviated (tables only) datastream is presented, the routine will
+ * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
+ * re-use the JPEG object to read the abbreviated image datastream(s).
+ * It is unnecessary (but OK) to call jpeg_abort in this case.
+ * The JPEG_SUSPENDED return code only occurs if the data source module
+ * requests suspension of the decompressor. In this case the application
+ * should load more source data and then re-call jpeg_read_header to resume
+ * processing.
+ * If a non-suspending data source is used and require_image is TRUE, then the
+ * return code need not be inspected since only JPEG_HEADER_OK is possible.
+ *
+ * This routine is now just a front end to jpeg_consume_input, with some
+ * extra error checking.
+ */
+
+GLOBAL int
+jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
+{
+ int retcode;
+
+ if (cinfo->global_state != DSTATE_START &&
+ cinfo->global_state != DSTATE_INHEADER)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+ retcode = jpeg_consume_input(cinfo);
+
+ switch (retcode) {
+ case JPEG_REACHED_SOS:
+ retcode = JPEG_HEADER_OK;
+ break;
+ case JPEG_REACHED_EOI:
+ if (require_image) /* Complain if application wanted an image */
+ ERREXIT(cinfo, JERR_NO_IMAGE);
+ /* Reset to start state; it would be safer to require the application to
+ * call jpeg_abort, but we can't change it now for compatibility reasons.
+ * A side effect is to free any temporary memory (there shouldn't be any).
+ */
+ jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
+ retcode = JPEG_HEADER_TABLES_ONLY;
+ break;
+ case JPEG_SUSPENDED:
+ /* no work */
+ break;
+ }
+
+ return retcode;
+}
+
+
+/*
+ * Consume data in advance of what the decompressor requires.
+ * This can be called at any time once the decompressor object has
+ * been created and a data source has been set up.
+ *
+ * This routine is essentially a state machine that handles a couple
+ * of critical state-transition actions, namely initial setup and
+ * transition from header scanning to ready-for-start_decompress.
+ * All the actual input is done via the input controller's consume_input
+ * method.
+ */
+
+GLOBAL int
+jpeg_consume_input (j_decompress_ptr cinfo)
+{
+ int retcode = JPEG_SUSPENDED;
+
+ /* NB: every possible DSTATE value should be listed in this switch */
+ switch (cinfo->global_state) {
+ case DSTATE_START:
+ /* Start-of-datastream actions: reset appropriate modules */
+ (*cinfo->inputctl->reset_input_controller) (cinfo);
+ /* Initialize application's data source module */
+ (*cinfo->src->init_source) (cinfo);
+ cinfo->global_state = DSTATE_INHEADER;
+ /*FALLTHROUGH*/
+ case DSTATE_INHEADER:
+ retcode = (*cinfo->inputctl->consume_input) (cinfo);
+ if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
+ /* Set up default parameters based on header data */
+ default_decompress_parms(cinfo);
+ /* Set global state: ready for start_decompress */
+ cinfo->global_state = DSTATE_READY;
+ }
+ break;
+ case DSTATE_READY:
+ /* Can't advance past first SOS until start_decompress is called */
+ retcode = JPEG_REACHED_SOS;
+ break;
+ case DSTATE_PRELOAD:
+ case DSTATE_PRESCAN:
+ case DSTATE_SCANNING:
+ case DSTATE_RAW_OK:
+ case DSTATE_BUFIMAGE:
+ case DSTATE_BUFPOST:
+ case DSTATE_STOPPING:
+ retcode = (*cinfo->inputctl->consume_input) (cinfo);
+ break;
+ default:
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ }
+ return retcode;
+}
+
+
+/*
+ * Have we finished reading the input file?
+ */
+
+GLOBAL boolean
+jpeg_input_complete (j_decompress_ptr cinfo)
+{
+ /* Check for valid jpeg object */
+ if (cinfo->global_state < DSTATE_START ||
+ cinfo->global_state > DSTATE_STOPPING)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ return cinfo->inputctl->eoi_reached;
+}
+
+
+/*
+ * Is there more than one scan?
+ */
+
+GLOBAL boolean
+jpeg_has_multiple_scans (j_decompress_ptr cinfo)
+{
+ /* Only valid after jpeg_read_header completes */
+ if (cinfo->global_state < DSTATE_READY ||
+ cinfo->global_state > DSTATE_STOPPING)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ return cinfo->inputctl->has_multiple_scans;
+}
+
+
+/*
+ * Finish JPEG decompression.
+ *
+ * This will normally just verify the file trailer and release temp storage.
+ *
+ * Returns FALSE if suspended. The return value need be inspected only if
+ * a suspending data source is used.
+ */
+
+GLOBAL boolean
+jpeg_finish_decompress (j_decompress_ptr cinfo)
+{
+ if ((cinfo->global_state == DSTATE_SCANNING ||
+ cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
+ /* Terminate final pass of non-buffered mode */
+ if (cinfo->output_scanline < cinfo->output_height)
+ ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
+ (*cinfo->master->finish_output_pass) (cinfo);
+ cinfo->global_state = DSTATE_STOPPING;
+ } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
+ /* Finishing after a buffered-image operation */
+ cinfo->global_state = DSTATE_STOPPING;
+ } else if (cinfo->global_state != DSTATE_STOPPING) {
+ /* STOPPING = repeat call after a suspension, anything else is error */
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ }
+ /* Read until EOI */
+ while (! cinfo->inputctl->eoi_reached) {
+ if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
+ return FALSE; /* Suspend, come back later */
+ }
+ /* Do final cleanup */
+ (*cinfo->src->term_source) (cinfo);
+ /* We can use jpeg_abort to release memory and reset global_state */
+ jpeg_abort((j_common_ptr) cinfo);
+ return TRUE;
+}
diff --git a/libs/jpeg6/jdapistd.cpp b/libs/jpeg6/jdapistd.cpp
new file mode 100755
index 0000000..7781e16
--- /dev/null
+++ b/libs/jpeg6/jdapistd.cpp
@@ -0,0 +1,275 @@
+/*
+ * jdapistd.c
+ *
+ * Copyright (C) 1994-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains application interface code for the decompression half
+ * of the JPEG library. These are the "standard" API routines that are
+ * used in the normal full-decompression case. They are not used by a
+ * transcoding-only application. Note that if an application links in
+ * jpeg_start_decompress, it will end up linking in the entire decompressor.
+ * We thus must separate this file from jdapimin.c to avoid linking the
+ * whole decompression library into a transcoder.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Forward declarations */
+LOCAL boolean output_pass_setup JPP((j_decompress_ptr cinfo));
+
+
+/*
+ * Decompression initialization.
+ * jpeg_read_header must be completed before calling this.
+ *
+ * If a multipass operating mode was selected, this will do all but the
+ * last pass, and thus may take a great deal of time.
+ *
+ * Returns FALSE if suspended. The return value need be inspected only if
+ * a suspending data source is used.
+ */
+
+GLOBAL boolean
+jpeg_start_decompress (j_decompress_ptr cinfo)
+{
+ if (cinfo->global_state == DSTATE_READY) {
+ /* First call: initialize master control, select active modules */
+ jinit_master_decompress(cinfo);
+ if (cinfo->buffered_image) {
+ /* No more work here; expecting jpeg_start_output next */
+ cinfo->global_state = DSTATE_BUFIMAGE;
+ return TRUE;
+ }
+ cinfo->global_state = DSTATE_PRELOAD;
+ }
+ if (cinfo->global_state == DSTATE_PRELOAD) {
+ /* If file has multiple scans, absorb them all into the coef buffer */
+ if (cinfo->inputctl->has_multiple_scans) {
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+ for (;;) {
+ int retcode;
+ /* Call progress monitor hook if present */
+ if (cinfo->progress != NULL)
+ (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+ /* Absorb some more input */
+ retcode = (*cinfo->inputctl->consume_input) (cinfo);
+ if (retcode == JPEG_SUSPENDED)
+ return FALSE;
+ if (retcode == JPEG_REACHED_EOI)
+ break;
+ /* Advance progress counter if appropriate */
+ if (cinfo->progress != NULL &&
+ (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
+ if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
+ /* jdmaster underestimated number of scans; ratchet up one scan */
+ cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
+ }
+ }
+ }
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif /* D_MULTISCAN_FILES_SUPPORTED */
+ }
+ cinfo->output_scan_number = cinfo->input_scan_number;
+ } else if (cinfo->global_state != DSTATE_PRESCAN)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ /* Perform any dummy output passes, and set up for the final pass */
+ return output_pass_setup(cinfo);
+}
+
+
+/*
+ * Set up for an output pass, and perform any dummy pass(es) needed.
+ * Common subroutine for jpeg_start_decompress and jpeg_start_output.
+ * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
+ * Exit: If done, returns TRUE and sets global_state for proper output mode.
+ * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
+ */
+
+LOCAL boolean
+output_pass_setup (j_decompress_ptr cinfo)
+{
+ if (cinfo->global_state != DSTATE_PRESCAN) {
+ /* First call: do pass setup */
+ (*cinfo->master->prepare_for_output_pass) (cinfo);
+ cinfo->output_scanline = 0;
+ cinfo->global_state = DSTATE_PRESCAN;
+ }
+ /* Loop over any required dummy passes */
+ while (cinfo->master->is_dummy_pass) {
+#ifdef QUANT_2PASS_SUPPORTED
+ /* Crank through the dummy pass */
+ while (cinfo->output_scanline < cinfo->output_height) {
+ JDIMENSION last_scanline;
+ /* Call progress monitor hook if present */
+ if (cinfo->progress != NULL) {
+ cinfo->progress->pass_counter = (long) cinfo->output_scanline;
+ cinfo->progress->pass_limit = (long) cinfo->output_height;
+ (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+ }
+ /* Process some data */
+ last_scanline = cinfo->output_scanline;
+ (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
+ &cinfo->output_scanline, (JDIMENSION) 0);
+ if (cinfo->output_scanline == last_scanline)
+ return FALSE; /* No progress made, must suspend */
+ }
+ /* Finish up dummy pass, and set up for another one */
+ (*cinfo->master->finish_output_pass) (cinfo);
+ (*cinfo->master->prepare_for_output_pass) (cinfo);
+ cinfo->output_scanline = 0;
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif /* QUANT_2PASS_SUPPORTED */
+ }
+ /* Ready for application to drive output pass through
+ * jpeg_read_scanlines or jpeg_read_raw_data.
+ */
+ cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
+ return TRUE;
+}
+
+
+/*
+ * Read some scanlines of data from the JPEG decompressor.
+ *
+ * The return value will be the number of lines actually read.
+ * This may be less than the number requested in several cases,
+ * including bottom of image, data source suspension, and operating
+ * modes that emit multiple scanlines at a time.
+ *
+ * Note: we warn about excess calls to jpeg_read_scanlines() since
+ * this likely signals an application programmer error. However,
+ * an oversize buffer (max_lines > scanlines remaining) is not an error.
+ */
+
+GLOBAL JDIMENSION
+jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
+ JDIMENSION max_lines)
+{
+ JDIMENSION row_ctr;
+
+ if (cinfo->global_state != DSTATE_SCANNING)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ if (cinfo->output_scanline >= cinfo->output_height) {
+ WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
+ return 0;
+ }
+
+ /* Call progress monitor hook if present */
+ if (cinfo->progress != NULL) {
+ cinfo->progress->pass_counter = (long) cinfo->output_scanline;
+ cinfo->progress->pass_limit = (long) cinfo->output_height;
+ (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+ }
+
+ /* Process some data */
+ row_ctr = 0;
+ (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
+ cinfo->output_scanline += row_ctr;
+ return row_ctr;
+}
+
+
+/*
+ * Alternate entry point to read raw data.
+ * Processes exactly one iMCU row per call, unless suspended.
+ */
+
+GLOBAL JDIMENSION
+jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
+ JDIMENSION max_lines)
+{
+ JDIMENSION lines_per_iMCU_row;
+
+ if (cinfo->global_state != DSTATE_RAW_OK)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ if (cinfo->output_scanline >= cinfo->output_height) {
+ WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
+ return 0;
+ }
+
+ /* Call progress monitor hook if present */
+ if (cinfo->progress != NULL) {
+ cinfo->progress->pass_counter = (long) cinfo->output_scanline;
+ cinfo->progress->pass_limit = (long) cinfo->output_height;
+ (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+ }
+
+ /* Verify that at least one iMCU row can be returned. */
+ lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
+ if (max_lines < lines_per_iMCU_row)
+ ERREXIT(cinfo, JERR_BUFFER_SIZE);
+
+ /* Decompress directly into user's buffer. */
+ if (! (*cinfo->coef->decompress_data) (cinfo, data))
+ return 0; /* suspension forced, can do nothing more */
+
+ /* OK, we processed one iMCU row. */
+ cinfo->output_scanline += lines_per_iMCU_row;
+ return lines_per_iMCU_row;
+}
+
+
+/* Additional entry points for buffered-image mode. */
+
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+
+/*
+ * Initialize for an output pass in buffered-image mode.
+ */
+
+GLOBAL boolean
+jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
+{
+ if (cinfo->global_state != DSTATE_BUFIMAGE &&
+ cinfo->global_state != DSTATE_PRESCAN)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ /* Limit scan number to valid range */
+ if (scan_number <= 0)
+ scan_number = 1;
+ if (cinfo->inputctl->eoi_reached &&
+ scan_number > cinfo->input_scan_number)
+ scan_number = cinfo->input_scan_number;
+ cinfo->output_scan_number = scan_number;
+ /* Perform any dummy output passes, and set up for the real pass */
+ return output_pass_setup(cinfo);
+}
+
+
+/*
+ * Finish up after an output pass in buffered-image mode.
+ *
+ * Returns FALSE if suspended. The return value need be inspected only if
+ * a suspending data source is used.
+ */
+
+GLOBAL boolean
+jpeg_finish_output (j_decompress_ptr cinfo)
+{
+ if ((cinfo->global_state == DSTATE_SCANNING ||
+ cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
+ /* Terminate this pass. */
+ /* We do not require the whole pass to have been completed. */
+ (*cinfo->master->finish_output_pass) (cinfo);
+ cinfo->global_state = DSTATE_BUFPOST;
+ } else if (cinfo->global_state != DSTATE_BUFPOST) {
+ /* BUFPOST = repeat call after a suspension, anything else is error */
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ }
+ /* Read markers looking for SOS or EOI */
+ while (cinfo->input_scan_number <= cinfo->output_scan_number &&
+ ! cinfo->inputctl->eoi_reached) {
+ if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
+ return FALSE; /* Suspend, come back later */
+ }
+ cinfo->global_state = DSTATE_BUFIMAGE;
+ return TRUE;
+}
+
+#endif /* D_MULTISCAN_FILES_SUPPORTED */
diff --git a/libs/jpeg6/jdatasrc.cpp b/libs/jpeg6/jdatasrc.cpp
new file mode 100755
index 0000000..5c1696d
--- /dev/null
+++ b/libs/jpeg6/jdatasrc.cpp
@@ -0,0 +1,204 @@
+/*
+ * jdatasrc.c
+ *
+ * Copyright (C) 1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains decompression data source routines for the case of
+ * reading JPEG data from a file (or any stdio stream). While these routines
+ * are sufficient for most applications, some will want to use a different
+ * source manager.
+ * IMPORTANT: we assume that fread() will correctly transcribe an array of
+ * JOCTETs from 8-bit-wide elements on external storage. If char is wider
+ * than 8 bits on your machine, you may need to do some tweaking.
+ */
+
+
+/* this is not a core library module, so it doesn't define JPEG_INTERNALS */
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jerror.h"
+
+
+/* Expanded data source object for stdio input */
+
+typedef struct {
+ struct jpeg_source_mgr pub; /* public fields */
+
+ unsigned char *infile; /* source stream */
+ JOCTET * buffer; /* start of buffer */
+ boolean start_of_file; /* have we gotten any data yet? */
+} my_source_mgr;
+
+typedef my_source_mgr * my_src_ptr;
+
+#define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
+
+
+/*
+ * Initialize source --- called by jpeg_read_header
+ * before any data is actually read.
+ */
+
+METHODDEF void
+init_source (j_decompress_ptr cinfo)
+{
+ my_src_ptr src = (my_src_ptr) cinfo->src;
+
+ /* We reset the empty-input-file flag for each image,
+ * but we don't clear the input buffer.
+ * This is correct behavior for reading a series of images from one source.
+ */
+ src->start_of_file = TRUE;
+}
+
+
+/*
+ * Fill the input buffer --- called whenever buffer is emptied.
+ *
+ * In typical applications, this should read fresh data into the buffer
+ * (ignoring the current state of next_input_byte & bytes_in_buffer),
+ * reset the pointer & count to the start of the buffer, and return TRUE
+ * indicating that the buffer has been reloaded. It is not necessary to
+ * fill the buffer entirely, only to obtain at least one more byte.
+ *
+ * There is no such thing as an EOF return. If the end of the file has been
+ * reached, the routine has a choice of ERREXIT() or inserting fake data into
+ * the buffer. In most cases, generating a warning message and inserting a
+ * fake EOI marker is the best course of action --- this will allow the
+ * decompressor to output however much of the image is there. However,
+ * the resulting error message is misleading if the real problem is an empty
+ * input file, so we handle that case specially.
+ *
+ * In applications that need to be able to suspend compression due to input
+ * not being available yet, a FALSE return indicates that no more data can be
+ * obtained right now, but more may be forthcoming later. In this situation,
+ * the decompressor will return to its caller (with an indication of the
+ * number of scanlines it has read, if any). The application should resume
+ * decompression after it has loaded more data into the input buffer. Note
+ * that there are substantial restrictions on the use of suspension --- see
+ * the documentation.
+ *
+ * When suspending, the decompressor will back up to a convenient restart point
+ * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
+ * indicate where the restart point will be if the current call returns FALSE.
+ * Data beyond this point must be rescanned after resumption, so move it to
+ * the front of the buffer rather than discarding it.
+ */
+
+METHODDEF boolean
+fill_input_buffer (j_decompress_ptr cinfo)
+{
+ my_src_ptr src = (my_src_ptr) cinfo->src;
+
+ memcpy( src->buffer, src->infile, INPUT_BUF_SIZE );
+
+ src->infile += INPUT_BUF_SIZE;
+
+ src->pub.next_input_byte = src->buffer;
+ src->pub.bytes_in_buffer = INPUT_BUF_SIZE;
+ src->start_of_file = FALSE;
+
+ return TRUE;
+}
+
+
+/*
+ * Skip data --- used to skip over a potentially large amount of
+ * uninteresting data (such as an APPn marker).
+ *
+ * Writers of suspendable-input applications must note that skip_input_data
+ * is not granted the right to give a suspension return. If the skip extends
+ * beyond the data currently in the buffer, the buffer can be marked empty so
+ * that the next read will cause a fill_input_buffer call that can suspend.
+ * Arranging for additional bytes to be discarded before reloading the input
+ * buffer is the application writer's problem.
+ */
+
+METHODDEF void
+skip_input_data (j_decompress_ptr cinfo, long num_bytes)
+{
+ my_src_ptr src = (my_src_ptr) cinfo->src;
+
+ /* Just a dumb implementation for now. Could use fseek() except
+ * it doesn't work on pipes. Not clear that being smart is worth
+ * any trouble anyway --- large skips are infrequent.
+ */
+ if (num_bytes > 0) {
+ while (num_bytes > (long) src->pub.bytes_in_buffer) {
+ num_bytes -= (long) src->pub.bytes_in_buffer;
+ (void) fill_input_buffer(cinfo);
+ /* note we assume that fill_input_buffer will never return FALSE,
+ * so suspension need not be handled.
+ */
+ }
+ src->pub.next_input_byte += (size_t) num_bytes;
+ src->pub.bytes_in_buffer -= (size_t) num_bytes;
+ }
+}
+
+
+/*
+ * An additional method that can be provided by data source modules is the
+ * resync_to_restart method for error recovery in the presence of RST markers.
+ * For the moment, this source module just uses the default resync method
+ * provided by the JPEG library. That method assumes that no backtracking
+ * is possible.
+ */
+
+
+/*
+ * Terminate source --- called by jpeg_finish_decompress
+ * after all data has been read. Often a no-op.
+ *
+ * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
+ * application must deal with any cleanup that should happen even
+ * for error exit.
+ */
+
+METHODDEF void
+term_source (j_decompress_ptr cinfo)
+{
+ /* no work necessary here */
+}
+
+
+/*
+ * Prepare for input from a stdio stream.
+ * The caller must have already opened the stream, and is responsible
+ * for closing it after finishing decompression.
+ */
+
+GLOBAL void
+jpeg_stdio_src (j_decompress_ptr cinfo, unsigned char *infile)
+{
+ my_src_ptr src;
+
+ /* The source object and input buffer are made permanent so that a series
+ * of JPEG images can be read from the same file by calling jpeg_stdio_src
+ * only before the first one. (If we discarded the buffer at the end of
+ * one image, we'd likely lose the start of the next one.)
+ * This makes it unsafe to use this manager and a different source
+ * manager serially with the same JPEG object. Caveat programmer.
+ */
+ if (cinfo->src == NULL) { /* first time for this JPEG object? */
+ cinfo->src = (struct jpeg_source_mgr *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ SIZEOF(my_source_mgr));
+ src = (my_src_ptr) cinfo->src;
+ src->buffer = (JOCTET *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ INPUT_BUF_SIZE * SIZEOF(JOCTET));
+ }
+
+ src = (my_src_ptr) cinfo->src;
+ src->pub.init_source = init_source;
+ src->pub.fill_input_buffer = fill_input_buffer;
+ src->pub.skip_input_data = skip_input_data;
+ src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
+ src->pub.term_source = term_source;
+ src->infile = infile;
+ src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
+ src->pub.next_input_byte = NULL; /* until buffer loaded */
+}
diff --git a/libs/jpeg6/jdcoefct.cpp b/libs/jpeg6/jdcoefct.cpp
new file mode 100755
index 0000000..2b20c07
--- /dev/null
+++ b/libs/jpeg6/jdcoefct.cpp
@@ -0,0 +1,725 @@
+/*
+ * jdcoefct.c
+ *
+ * Copyright (C) 1994-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the coefficient buffer controller for decompression.
+ * This controller is the top level of the JPEG decompressor proper.
+ * The coefficient buffer lies between entropy decoding and inverse-DCT steps.
+ *
+ * In buffered-image mode, this controller is the interface between
+ * input-oriented processing and output-oriented processing.
+ * Also, the input side (only) is used when reading a file for transcoding.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+/* Block smoothing is only applicable for progressive JPEG, so: */
+#ifndef D_PROGRESSIVE_SUPPORTED
+#undef BLOCK_SMOOTHING_SUPPORTED
+#endif
+
+/* Private buffer controller object */
+
+typedef struct {
+ struct jpeg_d_coef_controller pub; /* public fields */
+
+ /* These variables keep track of the current location of the input side. */
+ /* cinfo->input_iMCU_row is also used for this. */
+ JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
+ int MCU_vert_offset; /* counts MCU rows within iMCU row */
+ int MCU_rows_per_iMCU_row; /* number of such rows needed */
+
+ /* The output side's location is represented by cinfo->output_iMCU_row. */
+
+ /* In single-pass modes, it's sufficient to buffer just one MCU.
+ * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
+ * and let the entropy decoder write into that workspace each time.
+ * (On 80x86, the workspace is FAR even though it's not really very big;
+ * this is to keep the module interfaces unchanged when a large coefficient
+ * buffer is necessary.)
+ * In multi-pass modes, this array points to the current MCU's blocks
+ * within the virtual arrays; it is used only by the input side.
+ */
+ JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
+
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+ /* In multi-pass modes, we need a virtual block array for each component. */
+ jvirt_barray_ptr whole_image[MAX_COMPONENTS];
+#endif
+
+#ifdef BLOCK_SMOOTHING_SUPPORTED
+ /* When doing block smoothing, we latch coefficient Al values here */
+ int * coef_bits_latch;
+#define SAVED_COEFS 6 /* we save coef_bits[0..5] */
+#endif
+} my_coef_controller;
+
+typedef my_coef_controller * my_coef_ptr;
+
+/* Forward declarations */
+METHODDEF int decompress_onepass
+ JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+METHODDEF int decompress_data
+ JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
+#endif
+#ifdef BLOCK_SMOOTHING_SUPPORTED
+LOCAL boolean smoothing_ok JPP((j_decompress_ptr cinfo));
+METHODDEF int decompress_smooth_data
+ JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
+#endif
+
+
+LOCAL void
+start_iMCU_row (j_decompress_ptr cinfo)
+/* Reset within-iMCU-row counters for a new row (input side) */
+{
+ my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+
+ /* In an interleaved scan, an MCU row is the same as an iMCU row.
+ * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
+ * But at the bottom of the image, process only what's left.
+ */
+ if (cinfo->comps_in_scan > 1) {
+ coef->MCU_rows_per_iMCU_row = 1;
+ } else {
+ if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
+ coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
+ else
+ coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
+ }
+
+ coef->MCU_ctr = 0;
+ coef->MCU_vert_offset = 0;
+}
+
+
+/*
+ * Initialize for an input processing pass.
+ */
+
+METHODDEF void
+start_input_pass (j_decompress_ptr cinfo)
+{
+ cinfo->input_iMCU_row = 0;
+ start_iMCU_row(cinfo);
+}
+
+
+/*
+ * Initialize for an output processing pass.
+ */
+
+METHODDEF void
+start_output_pass (j_decompress_ptr cinfo)
+{
+#ifdef BLOCK_SMOOTHING_SUPPORTED
+ my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+
+ /* If multipass, check to see whether to use block smoothing on this pass */
+ if (coef->pub.coef_arrays != NULL) {
+ if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
+ coef->pub.decompress_data = decompress_smooth_data;
+ else
+ coef->pub.decompress_data = decompress_data;
+ }
+#endif
+ cinfo->output_iMCU_row = 0;
+}
+
+
+/*
+ * Decompress and return some data in the single-pass case.
+ * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
+ * Input and output must run in lockstep since we have only a one-MCU buffer.
+ * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
+ *
+ * NB: output_buf contains a plane for each component in image.
+ * For single pass, this is the same as the components in the scan.
+ */
+
+METHODDEF int
+decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
+{
+ my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ int blkn, ci, xindex, yindex, yoffset, useful_width;
+ JSAMPARRAY output_ptr;
+ JDIMENSION start_col, output_col;
+ jpeg_component_info *compptr;
+ inverse_DCT_method_ptr inverse_DCT;
+
+ /* Loop to process as much as one whole iMCU row */
+ for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
+ yoffset++) {
+ for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
+ MCU_col_num++) {
+ /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
+ jzero_far((void FAR *) coef->MCU_buffer[0],
+ (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
+ if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
+ /* Suspension forced; update state counters and exit */
+ coef->MCU_vert_offset = yoffset;
+ coef->MCU_ctr = MCU_col_num;
+ return JPEG_SUSPENDED;
+ }
+ /* Determine where data should go in output_buf and do the IDCT thing.
+ * We skip dummy blocks at the right and bottom edges (but blkn gets
+ * incremented past them!). Note the inner loop relies on having
+ * allocated the MCU_buffer[] blocks sequentially.
+ */
+ blkn = 0; /* index of current DCT block within MCU */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ /* Don't bother to IDCT an uninteresting component. */
+ if (! compptr->component_needed) {
+ blkn += compptr->MCU_blocks;
+ continue;
+ }
+ inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
+ useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
+ : compptr->last_col_width;
+ output_ptr = output_buf[ci] + yoffset * compptr->DCT_scaled_size;
+ start_col = MCU_col_num * compptr->MCU_sample_width;
+ for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
+ if (cinfo->input_iMCU_row < last_iMCU_row ||
+ yoffset+yindex < compptr->last_row_height) {
+ output_col = start_col;
+ for (xindex = 0; xindex < useful_width; xindex++) {
+ (*inverse_DCT) (cinfo, compptr,
+ (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
+ output_ptr, output_col);
+ output_col += compptr->DCT_scaled_size;
+ }
+ }
+ blkn += compptr->MCU_width;
+ output_ptr += compptr->DCT_scaled_size;
+ }
+ }
+ }
+ /* Completed an MCU row, but perhaps not an iMCU row */
+ coef->MCU_ctr = 0;
+ }
+ /* Completed the iMCU row, advance counters for next one */
+ cinfo->output_iMCU_row++;
+ if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
+ start_iMCU_row(cinfo);
+ return JPEG_ROW_COMPLETED;
+ }
+ /* Completed the scan */
+ (*cinfo->inputctl->finish_input_pass) (cinfo);
+ return JPEG_SCAN_COMPLETED;
+}
+
+
+/*
+ * Dummy consume-input routine for single-pass operation.
+ */
+
+METHODDEF int
+dummy_consume_data (j_decompress_ptr cinfo)
+{
+ return JPEG_SUSPENDED; /* Always indicate nothing was done */
+}
+
+
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+
+/*
+ * Consume input data and store it in the full-image coefficient buffer.
+ * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
+ * ie, v_samp_factor block rows for each component in the scan.
+ * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
+ */
+
+METHODDEF int
+consume_data (j_decompress_ptr cinfo)
+{
+ my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ int blkn, ci, xindex, yindex, yoffset;
+ JDIMENSION start_col;
+ JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
+ JBLOCKROW buffer_ptr;
+ jpeg_component_info *compptr;
+
+ /* Align the virtual buffers for the components used in this scan. */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ buffer[ci] = (*cinfo->mem->access_virt_barray)
+ ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
+ cinfo->input_iMCU_row * compptr->v_samp_factor,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ /* Note: entropy decoder expects buffer to be zeroed,
+ * but this is handled automatically by the memory manager
+ * because we requested a pre-zeroed array.
+ */
+ }
+
+ /* Loop to process one whole iMCU row */
+ for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
+ yoffset++) {
+ for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
+ MCU_col_num++) {
+ /* Construct list of pointers to DCT blocks belonging to this MCU */
+ blkn = 0; /* index of current DCT block within MCU */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ start_col = MCU_col_num * compptr->MCU_width;
+ for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
+ buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
+ for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
+ coef->MCU_buffer[blkn++] = buffer_ptr++;
+ }
+ }
+ }
+ /* Try to fetch the MCU. */
+ if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
+ /* Suspension forced; update state counters and exit */
+ coef->MCU_vert_offset = yoffset;
+ coef->MCU_ctr = MCU_col_num;
+ return JPEG_SUSPENDED;
+ }
+ }
+ /* Completed an MCU row, but perhaps not an iMCU row */
+ coef->MCU_ctr = 0;
+ }
+ /* Completed the iMCU row, advance counters for next one */
+ if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
+ start_iMCU_row(cinfo);
+ return JPEG_ROW_COMPLETED;
+ }
+ /* Completed the scan */
+ (*cinfo->inputctl->finish_input_pass) (cinfo);
+ return JPEG_SCAN_COMPLETED;
+}
+
+
+/*
+ * Decompress and return some data in the multi-pass case.
+ * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
+ * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
+ *
+ * NB: output_buf contains a plane for each component in image.
+ */
+
+METHODDEF int
+decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
+{
+ my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ JDIMENSION block_num;
+ int ci, block_row, block_rows;
+ JBLOCKARRAY buffer;
+ JBLOCKROW buffer_ptr;
+ JSAMPARRAY output_ptr;
+ JDIMENSION output_col;
+ jpeg_component_info *compptr;
+ inverse_DCT_method_ptr inverse_DCT;
+
+ /* Force some input to be done if we are getting ahead of the input. */
+ while (cinfo->input_scan_number < cinfo->output_scan_number ||
+ (cinfo->input_scan_number == cinfo->output_scan_number &&
+ cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
+ if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
+ return JPEG_SUSPENDED;
+ }
+
+ /* OK, output from the virtual arrays. */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Don't bother to IDCT an uninteresting component. */
+ if (! compptr->component_needed)
+ continue;
+ /* Align the virtual buffer for this component. */
+ buffer = (*cinfo->mem->access_virt_barray)
+ ((j_common_ptr) cinfo, coef->whole_image[ci],
+ cinfo->output_iMCU_row * compptr->v_samp_factor,
+ (JDIMENSION) compptr->v_samp_factor, FALSE);
+ /* Count non-dummy DCT block rows in this iMCU row. */
+ if (cinfo->output_iMCU_row < last_iMCU_row)
+ block_rows = compptr->v_samp_factor;
+ else {
+ /* NB: can't use last_row_height here; it is input-side-dependent! */
+ block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
+ if (block_rows == 0) block_rows = compptr->v_samp_factor;
+ }
+ inverse_DCT = cinfo->idct->inverse_DCT[ci];
+ output_ptr = output_buf[ci];
+ /* Loop over all DCT blocks to be processed. */
+ for (block_row = 0; block_row < block_rows; block_row++) {
+ buffer_ptr = buffer[block_row];
+ output_col = 0;
+ for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
+ (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
+ output_ptr, output_col);
+ buffer_ptr++;
+ output_col += compptr->DCT_scaled_size;
+ }
+ output_ptr += compptr->DCT_scaled_size;
+ }
+ }
+
+ if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
+ return JPEG_ROW_COMPLETED;
+ return JPEG_SCAN_COMPLETED;
+}
+
+#endif /* D_MULTISCAN_FILES_SUPPORTED */
+
+
+#ifdef BLOCK_SMOOTHING_SUPPORTED
+
+/*
+ * This code applies interblock smoothing as described by section K.8
+ * of the JPEG standard: the first 5 AC coefficients are estimated from
+ * the DC values of a DCT block and its 8 neighboring blocks.
+ * We apply smoothing only for progressive JPEG decoding, and only if
+ * the coefficients it can estimate are not yet known to full precision.
+ */
+
+/*
+ * Determine whether block smoothing is applicable and safe.
+ * We also latch the current states of the coef_bits[] entries for the
+ * AC coefficients; otherwise, if the input side of the decompressor
+ * advances into a new scan, we might think the coefficients are known
+ * more accurately than they really are.
+ */
+
+LOCAL boolean
+smoothing_ok (j_decompress_ptr cinfo)
+{
+ my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+ boolean smoothing_useful = FALSE;
+ int ci, coefi;
+ jpeg_component_info *compptr;
+ JQUANT_TBL * qtable;
+ int * coef_bits;
+ int * coef_bits_latch;
+
+ if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
+ return FALSE;
+
+ /* Allocate latch area if not already done */
+ if (coef->coef_bits_latch == NULL)
+ coef->coef_bits_latch = (int *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ cinfo->num_components *
+ (SAVED_COEFS * SIZEOF(int)));
+ coef_bits_latch = coef->coef_bits_latch;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* All components' quantization values must already be latched. */
+ if ((qtable = compptr->quant_table) == NULL)
+ return FALSE;
+ /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
+ for (coefi = 0; coefi <= 5; coefi++) {
+ if (qtable->quantval[coefi] == 0)
+ return FALSE;
+ }
+ /* DC values must be at least partly known for all components. */
+ coef_bits = cinfo->coef_bits[ci];
+ if (coef_bits[0] < 0)
+ return FALSE;
+ /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
+ for (coefi = 1; coefi <= 5; coefi++) {
+ coef_bits_latch[coefi] = coef_bits[coefi];
+ if (coef_bits[coefi] != 0)
+ smoothing_useful = TRUE;
+ }
+ coef_bits_latch += SAVED_COEFS;
+ }
+
+ return smoothing_useful;
+}
+
+
+/*
+ * Variant of decompress_data for use when doing block smoothing.
+ */
+
+METHODDEF int
+decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
+{
+ my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ JDIMENSION block_num, last_block_column;
+ int ci, block_row, block_rows, access_rows;
+ JBLOCKARRAY buffer;
+ JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
+ JSAMPARRAY output_ptr;
+ JDIMENSION output_col;
+ jpeg_component_info *compptr;
+ inverse_DCT_method_ptr inverse_DCT;
+ boolean first_row, last_row;
+ JBLOCK workspace;
+ int *coef_bits;
+ JQUANT_TBL *quanttbl;
+ INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
+ int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
+ int Al, pred;
+
+ /* Force some input to be done if we are getting ahead of the input. */
+ while (cinfo->input_scan_number <= cinfo->output_scan_number &&
+ ! cinfo->inputctl->eoi_reached) {
+ if (cinfo->input_scan_number == cinfo->output_scan_number) {
+ /* If input is working on current scan, we ordinarily want it to
+ * have completed the current row. But if input scan is DC,
+ * we want it to keep one row ahead so that next block row's DC
+ * values are up to date.
+ */
+ JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
+ if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
+ break;
+ }
+ if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
+ return JPEG_SUSPENDED;
+ }
+
+ /* OK, output from the virtual arrays. */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Don't bother to IDCT an uninteresting component. */
+ if (! compptr->component_needed)
+ continue;
+ /* Count non-dummy DCT block rows in this iMCU row. */
+ if (cinfo->output_iMCU_row < last_iMCU_row) {
+ block_rows = compptr->v_samp_factor;
+ access_rows = block_rows * 2; /* this and next iMCU row */
+ last_row = FALSE;
+ } else {
+ /* NB: can't use last_row_height here; it is input-side-dependent! */
+ block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
+ if (block_rows == 0) block_rows = compptr->v_samp_factor;
+ access_rows = block_rows; /* this iMCU row only */
+ last_row = TRUE;
+ }
+ /* Align the virtual buffer for this component. */
+ if (cinfo->output_iMCU_row > 0) {
+ access_rows += compptr->v_samp_factor; /* prior iMCU row too */
+ buffer = (*cinfo->mem->access_virt_barray)
+ ((j_common_ptr) cinfo, coef->whole_image[ci],
+ (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
+ (JDIMENSION) access_rows, FALSE);
+ buffer += compptr->v_samp_factor; /* point to current iMCU row */
+ first_row = FALSE;
+ } else {
+ buffer = (*cinfo->mem->access_virt_barray)
+ ((j_common_ptr) cinfo, coef->whole_image[ci],
+ (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
+ first_row = TRUE;
+ }
+ /* Fetch component-dependent info */
+ coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
+ quanttbl = compptr->quant_table;
+ Q00 = quanttbl->quantval[0];
+ Q01 = quanttbl->quantval[1];
+ Q10 = quanttbl->quantval[2];
+ Q20 = quanttbl->quantval[3];
+ Q11 = quanttbl->quantval[4];
+ Q02 = quanttbl->quantval[5];
+ inverse_DCT = cinfo->idct->inverse_DCT[ci];
+ output_ptr = output_buf[ci];
+ /* Loop over all DCT blocks to be processed. */
+ for (block_row = 0; block_row < block_rows; block_row++) {
+ buffer_ptr = buffer[block_row];
+ if (first_row && block_row == 0)
+ prev_block_row = buffer_ptr;
+ else
+ prev_block_row = buffer[block_row-1];
+ if (last_row && block_row == block_rows-1)
+ next_block_row = buffer_ptr;
+ else
+ next_block_row = buffer[block_row+1];
+ /* We fetch the surrounding DC values using a sliding-register approach.
+ * Initialize all nine here so as to do the right thing on narrow pics.
+ */
+ DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
+ DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
+ DC7 = DC8 = DC9 = (int) next_block_row[0][0];
+ output_col = 0;
+ last_block_column = compptr->width_in_blocks - 1;
+ for (block_num = 0; block_num <= last_block_column; block_num++) {
+ /* Fetch current DCT block into workspace so we can modify it. */
+ jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
+ /* Update DC values */
+ if (block_num < last_block_column) {
+ DC3 = (int) prev_block_row[1][0];
+ DC6 = (int) buffer_ptr[1][0];
+ DC9 = (int) next_block_row[1][0];
+ }
+ /* Compute coefficient estimates per K.8.
+ * An estimate is applied only if coefficient is still zero,
+ * and is not known to be fully accurate.
+ */
+ /* AC01 */
+ if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
+ num = 36 * Q00 * (DC4 - DC6);
+ if (num >= 0) {
+ pred = (int) (((Q01<<7) + num) / (Q01<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ } else {
+ pred = (int) (((Q01<<7) - num) / (Q01<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ pred = -pred;
+ }
+ workspace[1] = (JCOEF) pred;
+ }
+ /* AC10 */
+ if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
+ num = 36 * Q00 * (DC2 - DC8);
+ if (num >= 0) {
+ pred = (int) (((Q10<<7) + num) / (Q10<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ } else {
+ pred = (int) (((Q10<<7) - num) / (Q10<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ pred = -pred;
+ }
+ workspace[8] = (JCOEF) pred;
+ }
+ /* AC20 */
+ if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
+ num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
+ if (num >= 0) {
+ pred = (int) (((Q20<<7) + num) / (Q20<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ } else {
+ pred = (int) (((Q20<<7) - num) / (Q20<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ pred = -pred;
+ }
+ workspace[16] = (JCOEF) pred;
+ }
+ /* AC11 */
+ if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
+ num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
+ if (num >= 0) {
+ pred = (int) (((Q11<<7) + num) / (Q11<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ } else {
+ pred = (int) (((Q11<<7) - num) / (Q11<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ pred = -pred;
+ }
+ workspace[9] = (JCOEF) pred;
+ }
+ /* AC02 */
+ if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
+ num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
+ if (num >= 0) {
+ pred = (int) (((Q02<<7) + num) / (Q02<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ } else {
+ pred = (int) (((Q02<<7) - num) / (Q02<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ pred = -pred;
+ }
+ workspace[2] = (JCOEF) pred;
+ }
+ /* OK, do the IDCT */
+ (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
+ output_ptr, output_col);
+ /* Advance for next column */
+ DC1 = DC2; DC2 = DC3;
+ DC4 = DC5; DC5 = DC6;
+ DC7 = DC8; DC8 = DC9;
+ buffer_ptr++, prev_block_row++, next_block_row++;
+ output_col += compptr->DCT_scaled_size;
+ }
+ output_ptr += compptr->DCT_scaled_size;
+ }
+ }
+
+ if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
+ return JPEG_ROW_COMPLETED;
+ return JPEG_SCAN_COMPLETED;
+}
+
+#endif /* BLOCK_SMOOTHING_SUPPORTED */
+
+
+/*
+ * Initialize coefficient buffer controller.
+ */
+
+GLOBAL void
+jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
+{
+ my_coef_ptr coef;
+
+ coef = (my_coef_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_coef_controller));
+ cinfo->coef = (struct jpeg_d_coef_controller *) coef;
+ coef->pub.start_input_pass = start_input_pass;
+ coef->pub.start_output_pass = start_output_pass;
+#ifdef BLOCK_SMOOTHING_SUPPORTED
+ coef->coef_bits_latch = NULL;
+#endif
+
+ /* Create the coefficient buffer. */
+ if (need_full_buffer) {
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+ /* Allocate a full-image virtual array for each component, */
+ /* padded to a multiple of samp_factor DCT blocks in each direction. */
+ /* Note we ask for a pre-zeroed array. */
+ int ci, access_rows;
+ jpeg_component_info *compptr;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ access_rows = compptr->v_samp_factor;
+#ifdef BLOCK_SMOOTHING_SUPPORTED
+ /* If block smoothing could be used, need a bigger window */
+ if (cinfo->progressive_mode)
+ access_rows *= 3;
+#endif
+ coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
+ (JDIMENSION) jround_up((long) compptr->width_in_blocks,
+ (long) compptr->h_samp_factor),
+ (JDIMENSION) jround_up((long) compptr->height_in_blocks,
+ (long) compptr->v_samp_factor),
+ (JDIMENSION) access_rows);
+ }
+ coef->pub.consume_data = consume_data;
+ coef->pub.decompress_data = decompress_data;
+ coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else {
+ /* We only need a single-MCU buffer. */
+ JBLOCKROW buffer;
+ int i;
+
+ buffer = (JBLOCKROW)
+ (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
+ for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
+ coef->MCU_buffer[i] = buffer + i;
+ }
+ coef->pub.consume_data = dummy_consume_data;
+ coef->pub.decompress_data = decompress_onepass;
+ coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
+ }
+}
diff --git a/libs/jpeg6/jdcolor.cpp b/libs/jpeg6/jdcolor.cpp
new file mode 100755
index 0000000..d360b53
--- /dev/null
+++ b/libs/jpeg6/jdcolor.cpp
@@ -0,0 +1,367 @@
+/*
+ * jdcolor.c
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains output colorspace conversion routines.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Private subobject */
+
+typedef struct {
+ struct jpeg_color_deconverter pub; /* public fields */
+
+ /* Private state for YCC->RGB conversion */
+ int * Cr_r_tab; /* => table for Cr to R conversion */
+ int * Cb_b_tab; /* => table for Cb to B conversion */
+ INT32 * Cr_g_tab; /* => table for Cr to G conversion */
+ INT32 * Cb_g_tab; /* => table for Cb to G conversion */
+} my_color_deconverter;
+
+typedef my_color_deconverter * my_cconvert_ptr;
+
+
+/**************** YCbCr -> RGB conversion: most common case **************/
+
+/*
+ * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
+ * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
+ * The conversion equations to be implemented are therefore
+ * R = Y + 1.40200 * Cr
+ * G = Y - 0.34414 * Cb - 0.71414 * Cr
+ * B = Y + 1.77200 * Cb
+ * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
+ * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
+ *
+ * To avoid floating-point arithmetic, we represent the fractional constants
+ * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
+ * the products by 2^16, with appropriate rounding, to get the correct answer.
+ * Notice that Y, being an integral input, does not contribute any fraction
+ * so it need not participate in the rounding.
+ *
+ * For even more speed, we avoid doing any multiplications in the inner loop
+ * by precalculating the constants times Cb and Cr for all possible values.
+ * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
+ * for 12-bit samples it is still acceptable. It's not very reasonable for
+ * 16-bit samples, but if you want lossless storage you shouldn't be changing
+ * colorspace anyway.
+ * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
+ * values for the G calculation are left scaled up, since we must add them
+ * together before rounding.
+ */
+
+#define SCALEBITS 16 /* speediest right-shift on some machines */
+#define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
+#define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
+
+
+/*
+ * Initialize tables for YCC->RGB colorspace conversion.
+ */
+
+LOCAL void
+build_ycc_rgb_table (j_decompress_ptr cinfo)
+{
+ my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+ int i;
+ INT32 x;
+ SHIFT_TEMPS
+
+ cconvert->Cr_r_tab = (int *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (MAXJSAMPLE+1) * SIZEOF(int));
+ cconvert->Cb_b_tab = (int *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (MAXJSAMPLE+1) * SIZEOF(int));
+ cconvert->Cr_g_tab = (INT32 *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (MAXJSAMPLE+1) * SIZEOF(INT32));
+ cconvert->Cb_g_tab = (INT32 *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (MAXJSAMPLE+1) * SIZEOF(INT32));
+
+ for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
+ /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
+ /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
+ /* Cr=>R value is nearest int to 1.40200 * x */
+ cconvert->Cr_r_tab[i] = (int)
+ RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
+ /* Cb=>B value is nearest int to 1.77200 * x */
+ cconvert->Cb_b_tab[i] = (int)
+ RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
+ /* Cr=>G value is scaled-up -0.71414 * x */
+ cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
+ /* Cb=>G value is scaled-up -0.34414 * x */
+ /* We also add in ONE_HALF so that need not do it in inner loop */
+ cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
+ }
+}
+
+
+/*
+ * Convert some rows of samples to the output colorspace.
+ *
+ * Note that we change from noninterleaved, one-plane-per-component format
+ * to interleaved-pixel format. The output buffer is therefore three times
+ * as wide as the input buffer.
+ * A starting row offset is provided only for the input buffer. The caller
+ * can easily adjust the passed output_buf value to accommodate any row
+ * offset required on that side.
+ */
+
+METHODDEF void
+ycc_rgb_convert (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION input_row,
+ JSAMPARRAY output_buf, int num_rows)
+{
+ my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+ register int y, cb, cr;
+ register JSAMPROW outptr;
+ register JSAMPROW inptr0, inptr1, inptr2;
+ register JDIMENSION col;
+ JDIMENSION num_cols = cinfo->output_width;
+ /* copy these pointers into registers if possible */
+ register JSAMPLE * range_limit = cinfo->sample_range_limit;
+ register int * Crrtab = cconvert->Cr_r_tab;
+ register int * Cbbtab = cconvert->Cb_b_tab;
+ register INT32 * Crgtab = cconvert->Cr_g_tab;
+ register INT32 * Cbgtab = cconvert->Cb_g_tab;
+ SHIFT_TEMPS
+
+ while (--num_rows >= 0) {
+ inptr0 = input_buf[0][input_row];
+ inptr1 = input_buf[1][input_row];
+ inptr2 = input_buf[2][input_row];
+ input_row++;
+ outptr = *output_buf++;
+ for (col = 0; col < num_cols; col++) {
+ y = GETJSAMPLE(inptr0[col]);
+ cb = GETJSAMPLE(inptr1[col]);
+ cr = GETJSAMPLE(inptr2[col]);
+ /* Range-limiting is essential due to noise introduced by DCT losses. */
+ outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
+ outptr[RGB_GREEN] = range_limit[y +
+ ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
+ SCALEBITS))];
+ outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
+ outptr += RGB_PIXELSIZE;
+ }
+ }
+}
+
+
+/**************** Cases other than YCbCr -> RGB **************/
+
+
+/*
+ * Color conversion for no colorspace change: just copy the data,
+ * converting from separate-planes to interleaved representation.
+ */
+
+METHODDEF void
+null_convert (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION input_row,
+ JSAMPARRAY output_buf, int num_rows)
+{
+ register JSAMPROW inptr, outptr;
+ register JDIMENSION count;
+ register int num_components = cinfo->num_components;
+ JDIMENSION num_cols = cinfo->output_width;
+ int ci;
+
+ while (--num_rows >= 0) {
+ for (ci = 0; ci < num_components; ci++) {
+ inptr = input_buf[ci][input_row];
+ outptr = output_buf[0] + ci;
+ for (count = num_cols; count > 0; count--) {
+ *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
+ outptr += num_components;
+ }
+ }
+ input_row++;
+ output_buf++;
+ }
+}
+
+
+/*
+ * Color conversion for grayscale: just copy the data.
+ * This also works for YCbCr -> grayscale conversion, in which
+ * we just copy the Y (luminance) component and ignore chrominance.
+ */
+
+METHODDEF void
+grayscale_convert (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION input_row,
+ JSAMPARRAY output_buf, int num_rows)
+{
+ jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
+ num_rows, cinfo->output_width);
+}
+
+
+/*
+ * Adobe-style YCCK->CMYK conversion.
+ * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
+ * conversion as above, while passing K (black) unchanged.
+ * We assume build_ycc_rgb_table has been called.
+ */
+
+METHODDEF void
+ycck_cmyk_convert (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION input_row,
+ JSAMPARRAY output_buf, int num_rows)
+{
+ my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+ register int y, cb, cr;
+ register JSAMPROW outptr;
+ register JSAMPROW inptr0, inptr1, inptr2, inptr3;
+ register JDIMENSION col;
+ JDIMENSION num_cols = cinfo->output_width;
+ /* copy these pointers into registers if possible */
+ register JSAMPLE * range_limit = cinfo->sample_range_limit;
+ register int * Crrtab = cconvert->Cr_r_tab;
+ register int * Cbbtab = cconvert->Cb_b_tab;
+ register INT32 * Crgtab = cconvert->Cr_g_tab;
+ register INT32 * Cbgtab = cconvert->Cb_g_tab;
+ SHIFT_TEMPS
+
+ while (--num_rows >= 0) {
+ inptr0 = input_buf[0][input_row];
+ inptr1 = input_buf[1][input_row];
+ inptr2 = input_buf[2][input_row];
+ inptr3 = input_buf[3][input_row];
+ input_row++;
+ outptr = *output_buf++;
+ for (col = 0; col < num_cols; col++) {
+ y = GETJSAMPLE(inptr0[col]);
+ cb = GETJSAMPLE(inptr1[col]);
+ cr = GETJSAMPLE(inptr2[col]);
+ /* Range-limiting is essential due to noise introduced by DCT losses. */
+ outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
+ outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
+ ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
+ SCALEBITS)))];
+ outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
+ /* K passes through unchanged */
+ outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
+ outptr += 4;
+ }
+ }
+}
+
+
+/*
+ * Empty method for start_pass.
+ */
+
+METHODDEF void
+start_pass_dcolor (j_decompress_ptr cinfo)
+{
+ /* no work needed */
+}
+
+
+/*
+ * Module initialization routine for output colorspace conversion.
+ */
+
+GLOBAL void
+jinit_color_deconverter (j_decompress_ptr cinfo)
+{
+ my_cconvert_ptr cconvert;
+ int ci;
+
+ cconvert = (my_cconvert_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_color_deconverter));
+ cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
+ cconvert->pub.start_pass = start_pass_dcolor;
+
+ /* Make sure num_components agrees with jpeg_color_space */
+ switch (cinfo->jpeg_color_space) {
+ case JCS_GRAYSCALE:
+ if (cinfo->num_components != 1)
+ ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+ break;
+
+ case JCS_RGB:
+ case JCS_YCbCr:
+ if (cinfo->num_components != 3)
+ ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+ break;
+
+ case JCS_CMYK:
+ case JCS_YCCK:
+ if (cinfo->num_components != 4)
+ ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+ break;
+
+ default: /* JCS_UNKNOWN can be anything */
+ if (cinfo->num_components < 1)
+ ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+ break;
+ }
+
+ /* Set out_color_components and conversion method based on requested space.
+ * Also clear the component_needed flags for any unused components,
+ * so that earlier pipeline stages can avoid useless computation.
+ */
+
+ switch (cinfo->out_color_space) {
+ case JCS_GRAYSCALE:
+ cinfo->out_color_components = 1;
+ if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
+ cinfo->jpeg_color_space == JCS_YCbCr) {
+ cconvert->pub.color_convert = grayscale_convert;
+ /* For color->grayscale conversion, only the Y (0) component is needed */
+ for (ci = 1; ci < cinfo->num_components; ci++)
+ cinfo->comp_info[ci].component_needed = FALSE;
+ } else
+ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+ break;
+
+ case JCS_RGB:
+ cinfo->out_color_components = RGB_PIXELSIZE;
+ if (cinfo->jpeg_color_space == JCS_YCbCr) {
+ cconvert->pub.color_convert = ycc_rgb_convert;
+ build_ycc_rgb_table(cinfo);
+ } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
+ cconvert->pub.color_convert = null_convert;
+ } else
+ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+ break;
+
+ case JCS_CMYK:
+ cinfo->out_color_components = 4;
+ if (cinfo->jpeg_color_space == JCS_YCCK) {
+ cconvert->pub.color_convert = ycck_cmyk_convert;
+ build_ycc_rgb_table(cinfo);
+ } else if (cinfo->jpeg_color_space == JCS_CMYK) {
+ cconvert->pub.color_convert = null_convert;
+ } else
+ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+ break;
+
+ default:
+ /* Permit null conversion to same output space */
+ if (cinfo->out_color_space == cinfo->jpeg_color_space) {
+ cinfo->out_color_components = cinfo->num_components;
+ cconvert->pub.color_convert = null_convert;
+ } else /* unsupported non-null conversion */
+ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+ break;
+ }
+
+ if (cinfo->quantize_colors)
+ cinfo->output_components = 1; /* single colormapped output component */
+ else
+ cinfo->output_components = cinfo->out_color_components;
+}
diff --git a/libs/jpeg6/jdct.h b/libs/jpeg6/jdct.h
new file mode 100755
index 0000000..1d66d4f
--- /dev/null
+++ b/libs/jpeg6/jdct.h
@@ -0,0 +1,176 @@
+/*
+ * jdct.h
+ *
+ * Copyright (C) 1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This include file contains common declarations for the forward and
+ * inverse DCT modules. These declarations are private to the DCT managers
+ * (jcdctmgr.c, jddctmgr.c) and the individual DCT algorithms.
+ * The individual DCT algorithms are kept in separate files to ease
+ * machine-dependent tuning (e.g., assembly coding).
+ */
+
+
+/*
+ * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
+ * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
+ * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
+ * implementations use an array of type FAST_FLOAT, instead.)
+ * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
+ * The DCT outputs are returned scaled up by a factor of 8; they therefore
+ * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
+ * convention improves accuracy in integer implementations and saves some
+ * work in floating-point ones.
+ * Quantization of the output coefficients is done by jcdctmgr.c.
+ */
+
+#if BITS_IN_JSAMPLE == 8
+typedef int DCTELEM; /* 16 or 32 bits is fine */
+#else
+typedef INT32 DCTELEM; /* must have 32 bits */
+#endif
+
+typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
+typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
+
+
+/*
+ * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
+ * to an output sample array. The routine must dequantize the input data as
+ * well as perform the IDCT; for dequantization, it uses the multiplier table
+ * pointed to by compptr->dct_table. The output data is to be placed into the
+ * sample array starting at a specified column. (Any row offset needed will
+ * be applied to the array pointer before it is passed to the IDCT code.)
+ * Note that the number of samples emitted by the IDCT routine is
+ * DCT_scaled_size * DCT_scaled_size.
+ */
+
+/* typedef inverse_DCT_method_ptr is declared in jpegint.h */
+
+/*
+ * Each IDCT routine has its own ideas about the best dct_table element type.
+ */
+
+typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
+#if BITS_IN_JSAMPLE == 8
+typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
+#define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
+#else
+typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
+#define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
+#endif
+typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
+
+
+/*
+ * Each IDCT routine is responsible for range-limiting its results and
+ * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
+ * be quite far out of range if the input data is corrupt, so a bulletproof
+ * range-limiting step is required. We use a mask-and-table-lookup method
+ * to do the combined operations quickly. See the comments with
+ * prepare_range_limit_table (in jdmaster.c) for more info.
+ */
+
+#define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
+
+#define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
+
+
+/* Short forms of external names for systems with brain-damaged linkers. */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jpeg_fdct_islow jFDislow
+#define jpeg_fdct_ifast jFDifast
+#define jpeg_fdct_float jFDfloat
+#define jpeg_idct_islow jRDislow
+#define jpeg_idct_ifast jRDifast
+#define jpeg_idct_float jRDfloat
+#define jpeg_idct_4x4 jRD4x4
+#define jpeg_idct_2x2 jRD2x2
+#define jpeg_idct_1x1 jRD1x1
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+/* Extern declarations for the forward and inverse DCT routines. */
+
+EXTERN void jpeg_fdct_islow JPP((DCTELEM * data));
+EXTERN void jpeg_fdct_ifast JPP((DCTELEM * data));
+EXTERN void jpeg_fdct_float JPP((FAST_FLOAT * data));
+
+EXTERN void jpeg_idct_islow
+ JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN void jpeg_idct_ifast
+ JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN void jpeg_idct_float
+ JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN void jpeg_idct_4x4
+ JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN void jpeg_idct_2x2
+ JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+EXTERN void jpeg_idct_1x1
+ JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
+
+
+/*
+ * Macros for handling fixed-point arithmetic; these are used by many
+ * but not all of the DCT/IDCT modules.
+ *
+ * All values are expected to be of type INT32.
+ * Fractional constants are scaled left by CONST_BITS bits.
+ * CONST_BITS is defined within each module using these macros,
+ * and may differ from one module to the next.
+ */
+
+#define ONE ((INT32) 1)
+#define CONST_SCALE (ONE << CONST_BITS)
+
+/* Convert a positive real constant to an integer scaled by CONST_SCALE.
+ * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
+ * thus causing a lot of useless floating-point operations at run time.
+ */
+
+#define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
+
+/* Descale and correctly round an INT32 value that's scaled by N bits.
+ * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
+ * the fudge factor is correct for either sign of X.
+ */
+
+#define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
+
+/* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
+ * This macro is used only when the two inputs will actually be no more than
+ * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
+ * full 32x32 multiply. This provides a useful speedup on many machines.
+ * Unfortunately there is no way to specify a 16x16->32 multiply portably
+ * in C, but some C compilers will do the right thing if you provide the
+ * correct combination of casts.
+ */
+
+#ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
+#define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
+#endif
+#ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
+#define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
+#endif
+
+#ifndef MULTIPLY16C16 /* default definition */
+#define MULTIPLY16C16(var,const) ((var) * (const))
+#endif
+
+/* Same except both inputs are variables. */
+
+#ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
+#define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
+#endif
+
+#ifndef MULTIPLY16V16 /* default definition */
+#define MULTIPLY16V16(var1,var2) ((var1) * (var2))
+#endif
diff --git a/libs/jpeg6/jddctmgr.cpp b/libs/jpeg6/jddctmgr.cpp
new file mode 100755
index 0000000..ba01fc6
--- /dev/null
+++ b/libs/jpeg6/jddctmgr.cpp
@@ -0,0 +1,270 @@
+/*
+ * jddctmgr.c
+ *
+ * Copyright (C) 1994-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the inverse-DCT management logic.
+ * This code selects a particular IDCT implementation to be used,
+ * and it performs related housekeeping chores. No code in this file
+ * is executed per IDCT step, only during output pass setup.
+ *
+ * Note that the IDCT routines are responsible for performing coefficient
+ * dequantization as well as the IDCT proper. This module sets up the
+ * dequantization multiplier table needed by the IDCT routine.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jdct.h" /* Private declarations for DCT subsystem */
+
+
+/*
+ * The decompressor input side (jdinput.c) saves away the appropriate
+ * quantization table for each component at the start of the first scan
+ * involving that component. (This is necessary in order to correctly
+ * decode files that reuse Q-table slots.)
+ * When we are ready to make an output pass, the saved Q-table is converted
+ * to a multiplier table that will actually be used by the IDCT routine.
+ * The multiplier table contents are IDCT-method-dependent. To support
+ * application changes in IDCT method between scans, we can remake the
+ * multiplier tables if necessary.
+ * In buffered-image mode, the first output pass may occur before any data
+ * has been seen for some components, and thus before their Q-tables have
+ * been saved away. To handle this case, multiplier tables are preset
+ * to zeroes; the result of the IDCT will be a neutral gray level.
+ */
+
+
+/* Private subobject for this module */
+
+typedef struct {
+ struct jpeg_inverse_dct pub; /* public fields */
+
+ /* This array contains the IDCT method code that each multiplier table
+ * is currently set up for, or -1 if it's not yet set up.
+ * The actual multiplier tables are pointed to by dct_table in the
+ * per-component comp_info structures.
+ */
+ int cur_method[MAX_COMPONENTS];
+} my_idct_controller;
+
+typedef my_idct_controller * my_idct_ptr;
+
+
+/* Allocated multiplier tables: big enough for any supported variant */
+
+typedef union {
+ ISLOW_MULT_TYPE islow_array[DCTSIZE2];
+#ifdef DCT_IFAST_SUPPORTED
+ IFAST_MULT_TYPE ifast_array[DCTSIZE2];
+#endif
+#ifdef DCT_FLOAT_SUPPORTED
+ FLOAT_MULT_TYPE float_array[DCTSIZE2];
+#endif
+} multiplier_table;
+
+
+/* The current scaled-IDCT routines require ISLOW-style multiplier tables,
+ * so be sure to compile that code if either ISLOW or SCALING is requested.
+ */
+#ifdef DCT_ISLOW_SUPPORTED
+#define PROVIDE_ISLOW_TABLES
+#else
+#ifdef IDCT_SCALING_SUPPORTED
+#define PROVIDE_ISLOW_TABLES
+#endif
+#endif
+
+
+/*
+ * Prepare for an output pass.
+ * Here we select the proper IDCT routine for each component and build
+ * a matching multiplier table.
+ */
+
+METHODDEF void
+start_pass (j_decompress_ptr cinfo)
+{
+ my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
+ int ci, i;
+ jpeg_component_info *compptr;
+ int method = 0;
+ inverse_DCT_method_ptr method_ptr = NULL;
+ JQUANT_TBL * qtbl;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Select the proper IDCT routine for this component's scaling */
+ switch (compptr->DCT_scaled_size) {
+#ifdef IDCT_SCALING_SUPPORTED
+ case 1:
+ method_ptr = jpeg_idct_1x1;
+ method = JDCT_ISLOW; /* jidctred uses islow-style table */
+ break;
+ case 2:
+ method_ptr = jpeg_idct_2x2;
+ method = JDCT_ISLOW; /* jidctred uses islow-style table */
+ break;
+ case 4:
+ method_ptr = jpeg_idct_4x4;
+ method = JDCT_ISLOW; /* jidctred uses islow-style table */
+ break;
+#endif
+ case DCTSIZE:
+ switch (cinfo->dct_method) {
+#ifdef DCT_ISLOW_SUPPORTED
+ case JDCT_ISLOW:
+ method_ptr = jpeg_idct_islow;
+ method = JDCT_ISLOW;
+ break;
+#endif
+#ifdef DCT_IFAST_SUPPORTED
+ case JDCT_IFAST:
+ method_ptr = jpeg_idct_ifast;
+ method = JDCT_IFAST;
+ break;
+#endif
+#ifdef DCT_FLOAT_SUPPORTED
+ case JDCT_FLOAT:
+ method_ptr = jpeg_idct_float;
+ method = JDCT_FLOAT;
+ break;
+#endif
+ default:
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+ break;
+ }
+ break;
+ default:
+ ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
+ break;
+ }
+ idct->pub.inverse_DCT[ci] = method_ptr;
+ /* Create multiplier table from quant table.
+ * However, we can skip this if the component is uninteresting
+ * or if we already built the table. Also, if no quant table
+ * has yet been saved for the component, we leave the
+ * multiplier table all-zero; we'll be reading zeroes from the
+ * coefficient controller's buffer anyway.
+ */
+ if (! compptr->component_needed || idct->cur_method[ci] == method)
+ continue;
+ qtbl = compptr->quant_table;
+ if (qtbl == NULL) /* happens if no data yet for component */
+ continue;
+ idct->cur_method[ci] = method;
+ switch (method) {
+#ifdef PROVIDE_ISLOW_TABLES
+ case JDCT_ISLOW:
+ {
+ /* For LL&M IDCT method, multipliers are equal to raw quantization
+ * coefficients, but are stored in natural order as ints.
+ */
+ ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
+ for (i = 0; i < DCTSIZE2; i++) {
+ ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[jpeg_zigzag_order[i]];
+ }
+ }
+ break;
+#endif
+#ifdef DCT_IFAST_SUPPORTED
+ case JDCT_IFAST:
+ {
+ /* For AA&N IDCT method, multipliers are equal to quantization
+ * coefficients scaled by scalefactor[row]*scalefactor[col], where
+ * scalefactor[0] = 1
+ * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
+ * For integer operation, the multiplier table is to be scaled by
+ * IFAST_SCALE_BITS. The multipliers are stored in natural order.
+ */
+ IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
+#define CONST_BITS 14
+ static const INT16 aanscales[DCTSIZE2] = {
+ /* precomputed values scaled up by 14 bits */
+ 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
+ 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
+ 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
+ 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
+ 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
+ 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
+ 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
+ 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
+ };
+ SHIFT_TEMPS
+
+ for (i = 0; i < DCTSIZE2; i++) {
+ ifmtbl[i] = (IFAST_MULT_TYPE)
+ DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[jpeg_zigzag_order[i]],
+ (INT32) aanscales[i]),
+ CONST_BITS-IFAST_SCALE_BITS);
+ }
+ }
+ break;
+#endif
+#ifdef DCT_FLOAT_SUPPORTED
+ case JDCT_FLOAT:
+ {
+ /* For float AA&N IDCT method, multipliers are equal to quantization
+ * coefficients scaled by scalefactor[row]*scalefactor[col], where
+ * scalefactor[0] = 1
+ * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
+ * The multipliers are stored in natural order.
+ */
+ FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
+ int row, col;
+ static const double aanscalefactor[DCTSIZE] = {
+ 1.0, 1.387039845, 1.306562965, 1.175875602,
+ 1.0, 0.785694958, 0.541196100, 0.275899379
+ };
+
+ i = 0;
+ for (row = 0; row < DCTSIZE; row++) {
+ for (col = 0; col < DCTSIZE; col++) {
+ fmtbl[i] = (FLOAT_MULT_TYPE)
+ ((double) qtbl->quantval[jpeg_zigzag_order[i]] *
+ aanscalefactor[row] * aanscalefactor[col]);
+ i++;
+ }
+ }
+ }
+ break;
+#endif
+ default:
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+ break;
+ }
+ }
+}
+
+
+/*
+ * Initialize IDCT manager.
+ */
+
+GLOBAL void
+jinit_inverse_dct (j_decompress_ptr cinfo)
+{
+ my_idct_ptr idct;
+ int ci;
+ jpeg_component_info *compptr;
+
+ idct = (my_idct_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_idct_controller));
+ cinfo->idct = (struct jpeg_inverse_dct *) idct;
+ idct->pub.start_pass = start_pass;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Allocate and pre-zero a multiplier table for each component */
+ compptr->dct_table =
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(multiplier_table));
+ MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
+ /* Mark multiplier table not yet set up for any method */
+ idct->cur_method[ci] = -1;
+ }
+}
diff --git a/libs/jpeg6/jdhuff.cpp b/libs/jpeg6/jdhuff.cpp
new file mode 100755
index 0000000..db42772
--- /dev/null
+++ b/libs/jpeg6/jdhuff.cpp
@@ -0,0 +1,574 @@
+/*
+ * jdhuff.c
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains Huffman entropy decoding routines.
+ *
+ * Much of the complexity here has to do with supporting input suspension.
+ * If the data source module demands suspension, we want to be able to back
+ * up to the start of the current MCU. To do this, we copy state variables
+ * into local working storage, and update them back to the permanent
+ * storage only upon successful completion of an MCU.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jdhuff.h" /* Declarations shared with jdphuff.c */
+
+
+/*
+ * Expanded entropy decoder object for Huffman decoding.
+ *
+ * The savable_state subrecord contains fields that change within an MCU,
+ * but must not be updated permanently until we complete the MCU.
+ */
+
+typedef struct {
+ int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
+} savable_state;
+
+/* This macro is to work around compilers with missing or broken
+ * structure assignment. You'll need to fix this code if you have
+ * such a compiler and you change MAX_COMPS_IN_SCAN.
+ */
+
+#ifndef NO_STRUCT_ASSIGN
+#define ASSIGN_STATE(dest,src) ((dest) = (src))
+#else
+#if MAX_COMPS_IN_SCAN == 4
+#define ASSIGN_STATE(dest,src) \
+ ((dest).last_dc_val[0] = (src).last_dc_val[0], \
+ (dest).last_dc_val[1] = (src).last_dc_val[1], \
+ (dest).last_dc_val[2] = (src).last_dc_val[2], \
+ (dest).last_dc_val[3] = (src).last_dc_val[3])
+#endif
+#endif
+
+
+typedef struct {
+ struct jpeg_entropy_decoder pub; /* public fields */
+
+ /* These fields are loaded into local variables at start of each MCU.
+ * In case of suspension, we exit WITHOUT updating them.
+ */
+ bitread_perm_state bitstate; /* Bit buffer at start of MCU */
+ savable_state saved; /* Other state at start of MCU */
+
+ /* These fields are NOT loaded into local working state. */
+ unsigned int restarts_to_go; /* MCUs left in this restart interval */
+
+ /* Pointers to derived tables (these workspaces have image lifespan) */
+ d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
+ d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
+} huff_entropy_decoder;
+
+typedef huff_entropy_decoder * huff_entropy_ptr;
+
+
+/*
+ * Initialize for a Huffman-compressed scan.
+ */
+
+METHODDEF void
+start_pass_huff_decoder (j_decompress_ptr cinfo)
+{
+ huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
+ int ci, dctbl, actbl;
+ jpeg_component_info * compptr;
+
+ /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
+ * This ought to be an error condition, but we make it a warning because
+ * there are some baseline files out there with all zeroes in these bytes.
+ */
+ if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
+ cinfo->Ah != 0 || cinfo->Al != 0)
+ WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ dctbl = compptr->dc_tbl_no;
+ actbl = compptr->ac_tbl_no;
+ /* Make sure requested tables are present */
+ if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS ||
+ cinfo->dc_huff_tbl_ptrs[dctbl] == NULL)
+ ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
+ if (actbl < 0 || actbl >= NUM_HUFF_TBLS ||
+ cinfo->ac_huff_tbl_ptrs[actbl] == NULL)
+ ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
+ /* Compute derived values for Huffman tables */
+ /* We may do this more than once for a table, but it's not expensive */
+ jpeg_make_d_derived_tbl(cinfo, cinfo->dc_huff_tbl_ptrs[dctbl],
+ & entropy->dc_derived_tbls[dctbl]);
+ jpeg_make_d_derived_tbl(cinfo, cinfo->ac_huff_tbl_ptrs[actbl],
+ & entropy->ac_derived_tbls[actbl]);
+ /* Initialize DC predictions to 0 */
+ entropy->saved.last_dc_val[ci] = 0;
+ }
+
+ /* Initialize bitread state variables */
+ entropy->bitstate.bits_left = 0;
+ entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
+ entropy->bitstate.printed_eod = FALSE;
+
+ /* Initialize restart counter */
+ entropy->restarts_to_go = cinfo->restart_interval;
+}
+
+
+/*
+ * Compute the derived values for a Huffman table.
+ * Note this is also used by jdphuff.c.
+ */
+
+GLOBAL void
+jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, JHUFF_TBL * htbl,
+ d_derived_tbl ** pdtbl)
+{
+ d_derived_tbl *dtbl;
+ int p, i, l, si;
+ int lookbits, ctr;
+ char huffsize[257];
+ unsigned int huffcode[257];
+ unsigned int code;
+
+ /* Allocate a workspace if we haven't already done so. */
+ if (*pdtbl == NULL)
+ *pdtbl = (d_derived_tbl *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(d_derived_tbl));
+ dtbl = *pdtbl;
+ dtbl->pub = htbl; /* fill in back link */
+
+ /* Figure C.1: make table of Huffman code length for each symbol */
+ /* Note that this is in code-length order. */
+
+ p = 0;
+ for (l = 1; l <= 16; l++) {
+ for (i = 1; i <= (int) htbl->bits[l]; i++)
+ huffsize[p++] = (char) l;
+ }
+ huffsize[p] = 0;
+
+ /* Figure C.2: generate the codes themselves */
+ /* Note that this is in code-length order. */
+
+ code = 0;
+ si = huffsize[0];
+ p = 0;
+ while (huffsize[p]) {
+ while (((int) huffsize[p]) == si) {
+ huffcode[p++] = code;
+ code++;
+ }
+ code <<= 1;
+ si++;
+ }
+
+ /* Figure F.15: generate decoding tables for bit-sequential decoding */
+
+ p = 0;
+ for (l = 1; l <= 16; l++) {
+ if (htbl->bits[l]) {
+ dtbl->valptr[l] = p; /* huffval[] index of 1st symbol of code length l */
+ dtbl->mincode[l] = huffcode[p]; /* minimum code of length l */
+ p += htbl->bits[l];
+ dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
+ } else {
+ dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
+ }
+ }
+ dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
+
+ /* Compute lookahead tables to speed up decoding.
+ * First we set all the table entries to 0, indicating "too long";
+ * then we iterate through the Huffman codes that are short enough and
+ * fill in all the entries that correspond to bit sequences starting
+ * with that code.
+ */
+
+ MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
+
+ p = 0;
+ for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
+ for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
+ /* l = current code's length, p = its index in huffcode[] & huffval[]. */
+ /* Generate left-justified code followed by all possible bit sequences */
+ lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
+ for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
+ dtbl->look_nbits[lookbits] = l;
+ dtbl->look_sym[lookbits] = htbl->huffval[p];
+ lookbits++;
+ }
+ }
+ }
+}
+
+
+/*
+ * Out-of-line code for bit fetching (shared with jdphuff.c).
+ * See jdhuff.h for info about usage.
+ * Note: current values of get_buffer and bits_left are passed as parameters,
+ * but are returned in the corresponding fields of the state struct.
+ *
+ * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
+ * of get_buffer to be used. (On machines with wider words, an even larger
+ * buffer could be used.) However, on some machines 32-bit shifts are
+ * quite slow and take time proportional to the number of places shifted.
+ * (This is true with most PC compilers, for instance.) In this case it may
+ * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
+ * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
+ */
+
+#ifdef SLOW_SHIFT_32
+#define MIN_GET_BITS 15 /* minimum allowable value */
+#else
+#define MIN_GET_BITS (BIT_BUF_SIZE-7)
+#endif
+
+
+GLOBAL boolean
+jpeg_fill_bit_buffer (bitread_working_state * state,
+ register bit_buf_type get_buffer, register int bits_left,
+ int nbits)
+/* Load up the bit buffer to a depth of at least nbits */
+{
+ /* Copy heavily used state fields into locals (hopefully registers) */
+ register const JOCTET * next_input_byte = state->next_input_byte;
+ register size_t bytes_in_buffer = state->bytes_in_buffer;
+ register int c;
+
+ /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
+ /* (It is assumed that no request will be for more than that many bits.) */
+
+ while (bits_left < MIN_GET_BITS) {
+ /* Attempt to read a byte */
+ if (state->unread_marker != 0)
+ goto no_more_data; /* can't advance past a marker */
+
+ if (bytes_in_buffer == 0) {
+ if (! (*state->cinfo->src->fill_input_buffer) (state->cinfo))
+ return FALSE;
+ next_input_byte = state->cinfo->src->next_input_byte;
+ bytes_in_buffer = state->cinfo->src->bytes_in_buffer;
+ }
+ bytes_in_buffer--;
+ c = GETJOCTET(*next_input_byte++);
+
+ /* If it's 0xFF, check and discard stuffed zero byte */
+ if (c == 0xFF) {
+ do {
+ if (bytes_in_buffer == 0) {
+ if (! (*state->cinfo->src->fill_input_buffer) (state->cinfo))
+ return FALSE;
+ next_input_byte = state->cinfo->src->next_input_byte;
+ bytes_in_buffer = state->cinfo->src->bytes_in_buffer;
+ }
+ bytes_in_buffer--;
+ c = GETJOCTET(*next_input_byte++);
+ } while (c == 0xFF);
+
+ if (c == 0) {
+ /* Found FF/00, which represents an FF data byte */
+ c = 0xFF;
+ } else {
+ /* Oops, it's actually a marker indicating end of compressed data. */
+ /* Better put it back for use later */
+ state->unread_marker = c;
+
+ no_more_data:
+ /* There should be enough bits still left in the data segment; */
+ /* if so, just break out of the outer while loop. */
+ if (bits_left >= nbits)
+ break;
+ /* Uh-oh. Report corrupted data to user and stuff zeroes into
+ * the data stream, so that we can produce some kind of image.
+ * Note that this code will be repeated for each byte demanded
+ * for the rest of the segment. We use a nonvolatile flag to ensure
+ * that only one warning message appears.
+ */
+ if (! *(state->printed_eod_ptr)) {
+ WARNMS(state->cinfo, JWRN_HIT_MARKER);
+ *(state->printed_eod_ptr) = TRUE;
+ }
+ c = 0; /* insert a zero byte into bit buffer */
+ }
+ }
+
+ /* OK, load c into get_buffer */
+ get_buffer = (get_buffer << 8) | c;
+ bits_left += 8;
+ }
+
+ /* Unload the local registers */
+ state->next_input_byte = next_input_byte;
+ state->bytes_in_buffer = bytes_in_buffer;
+ state->get_buffer = get_buffer;
+ state->bits_left = bits_left;
+
+ return TRUE;
+}
+
+
+/*
+ * Out-of-line code for Huffman code decoding.
+ * See jdhuff.h for info about usage.
+ */
+
+GLOBAL int
+jpeg_huff_decode (bitread_working_state * state,
+ register bit_buf_type get_buffer, register int bits_left,
+ d_derived_tbl * htbl, int min_bits)
+{
+ register int l = min_bits;
+ register INT32 code;
+
+ /* HUFF_DECODE has determined that the code is at least min_bits */
+ /* bits long, so fetch that many bits in one swoop. */
+
+ CHECK_BIT_BUFFER(*state, l, return -1);
+ code = GET_BITS(l);
+
+ /* Collect the rest of the Huffman code one bit at a time. */
+ /* This is per Figure F.16 in the JPEG spec. */
+
+ while (code > htbl->maxcode[l]) {
+ code <<= 1;
+ CHECK_BIT_BUFFER(*state, 1, return -1);
+ code |= GET_BITS(1);
+ l++;
+ }
+
+ /* Unload the local registers */
+ state->get_buffer = get_buffer;
+ state->bits_left = bits_left;
+
+ /* With garbage input we may reach the sentinel value l = 17. */
+
+ if (l > 16) {
+ WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
+ return 0; /* fake a zero as the safest result */
+ }
+
+ return htbl->pub->huffval[ htbl->valptr[l] +
+ ((int) (code - htbl->mincode[l])) ];
+}
+
+
+/*
+ * Figure F.12: extend sign bit.
+ * On some machines, a shift and add will be faster than a table lookup.
+ */
+
+#ifdef AVOID_TABLES
+
+#define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
+
+#else
+
+#define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
+
+static const int extend_test[16] = /* entry n is 2**(n-1) */
+ { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
+ 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
+
+static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
+ { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
+ ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
+ ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
+ ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
+
+#endif /* AVOID_TABLES */
+
+
+/*
+ * Check for a restart marker & resynchronize decoder.
+ * Returns FALSE if must suspend.
+ */
+
+LOCAL boolean
+process_restart (j_decompress_ptr cinfo)
+{
+ huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
+ int ci;
+
+ /* Throw away any unused bits remaining in bit buffer; */
+ /* include any full bytes in next_marker's count of discarded bytes */
+ cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
+ entropy->bitstate.bits_left = 0;
+
+ /* Advance past the RSTn marker */
+ if (! (*cinfo->marker->read_restart_marker) (cinfo))
+ return FALSE;
+
+ /* Re-initialize DC predictions to 0 */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++)
+ entropy->saved.last_dc_val[ci] = 0;
+
+ /* Reset restart counter */
+ entropy->restarts_to_go = cinfo->restart_interval;
+
+ /* Next segment can get another out-of-data warning */
+ entropy->bitstate.printed_eod = FALSE;
+
+ return TRUE;
+}
+
+
+/*
+ * Decode and return one MCU's worth of Huffman-compressed coefficients.
+ * The coefficients are reordered from zigzag order into natural array order,
+ * but are not dequantized.
+ *
+ * The i'th block of the MCU is stored into the block pointed to by
+ * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
+ * (Wholesale zeroing is usually a little faster than retail...)
+ *
+ * Returns FALSE if data source requested suspension. In that case no
+ * changes have been made to permanent state. (Exception: some output
+ * coefficients may already have been assigned. This is harmless for
+ * this module, since we'll just re-assign them on the next call.)
+ */
+
+METHODDEF boolean
+decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
+{
+ huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
+ register int s, k, r;
+ int blkn, ci;
+ JBLOCKROW block;
+ BITREAD_STATE_VARS;
+ savable_state state;
+ d_derived_tbl * dctbl;
+ d_derived_tbl * actbl;
+ jpeg_component_info * compptr;
+
+ /* Process restart marker if needed; may have to suspend */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0)
+ if (! process_restart(cinfo))
+ return FALSE;
+ }
+
+ /* Load up working state */
+ BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
+ ASSIGN_STATE(state, entropy->saved);
+
+ /* Outer loop handles each block in the MCU */
+
+ for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
+ block = MCU_data[blkn];
+ ci = cinfo->MCU_membership[blkn];
+ compptr = cinfo->cur_comp_info[ci];
+ dctbl = entropy->dc_derived_tbls[compptr->dc_tbl_no];
+ actbl = entropy->ac_derived_tbls[compptr->ac_tbl_no];
+
+ /* Decode a single block's worth of coefficients */
+
+ /* Section F.2.2.1: decode the DC coefficient difference */
+ HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
+ if (s) {
+ CHECK_BIT_BUFFER(br_state, s, return FALSE);
+ r = GET_BITS(s);
+ s = HUFF_EXTEND(r, s);
+ }
+
+ /* Shortcut if component's values are not interesting */
+ if (! compptr->component_needed)
+ goto skip_ACs;
+
+ /* Convert DC difference to actual value, update last_dc_val */
+ s += state.last_dc_val[ci];
+ state.last_dc_val[ci] = s;
+ /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
+ (*block)[0] = (JCOEF) s;
+
+ /* Do we need to decode the AC coefficients for this component? */
+ if (compptr->DCT_scaled_size > 1) {
+
+ /* Section F.2.2.2: decode the AC coefficients */
+ /* Since zeroes are skipped, output area must be cleared beforehand */
+ for (k = 1; k < DCTSIZE2; k++) {
+ HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
+
+ r = s >> 4;
+ s &= 15;
+
+ if (s) {
+ k += r;
+ CHECK_BIT_BUFFER(br_state, s, return FALSE);
+ r = GET_BITS(s);
+ s = HUFF_EXTEND(r, s);
+ /* Output coefficient in natural (dezigzagged) order.
+ * Note: the extra entries in jpeg_natural_order[] will save us
+ * if k >= DCTSIZE2, which could happen if the data is corrupted.
+ */
+ (*block)[jpeg_natural_order[k]] = (JCOEF) s;
+ } else {
+ if (r != 15)
+ break;
+ k += 15;
+ }
+ }
+
+ } else {
+skip_ACs:
+
+ /* Section F.2.2.2: decode the AC coefficients */
+ /* In this path we just discard the values */
+ for (k = 1; k < DCTSIZE2; k++) {
+ HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
+
+ r = s >> 4;
+ s &= 15;
+
+ if (s) {
+ k += r;
+ CHECK_BIT_BUFFER(br_state, s, return FALSE);
+ DROP_BITS(s);
+ } else {
+ if (r != 15)
+ break;
+ k += 15;
+ }
+ }
+
+ }
+ }
+
+ /* Completed MCU, so update state */
+ BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
+ ASSIGN_STATE(entropy->saved, state);
+
+ /* Account for restart interval (no-op if not using restarts) */
+ entropy->restarts_to_go--;
+
+ return TRUE;
+}
+
+
+/*
+ * Module initialization routine for Huffman entropy decoding.
+ */
+
+GLOBAL void
+jinit_huff_decoder (j_decompress_ptr cinfo)
+{
+ huff_entropy_ptr entropy;
+ int i;
+
+ entropy = (huff_entropy_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(huff_entropy_decoder));
+ cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
+ entropy->pub.start_pass = start_pass_huff_decoder;
+ entropy->pub.decode_mcu = decode_mcu;
+
+ /* Mark tables unallocated */
+ for (i = 0; i < NUM_HUFF_TBLS; i++) {
+ entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
+ }
+}
diff --git a/libs/jpeg6/jdhuff.h b/libs/jpeg6/jdhuff.h
new file mode 100755
index 0000000..65f3054
--- /dev/null
+++ b/libs/jpeg6/jdhuff.h
@@ -0,0 +1,202 @@
+/*
+ * jdhuff.h
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains declarations for Huffman entropy decoding routines
+ * that are shared between the sequential decoder (jdhuff.c) and the
+ * progressive decoder (jdphuff.c). No other modules need to see these.
+ */
+
+/* Short forms of external names for systems with brain-damaged linkers. */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jpeg_make_d_derived_tbl jMkDDerived
+#define jpeg_fill_bit_buffer jFilBitBuf
+#define jpeg_huff_decode jHufDecode
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+
+/* Derived data constructed for each Huffman table */
+
+#define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
+
+typedef struct {
+ /* Basic tables: (element [0] of each array is unused) */
+ INT32 mincode[17]; /* smallest code of length k */
+ INT32 maxcode[18]; /* largest code of length k (-1 if none) */
+ /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
+ int valptr[17]; /* huffval[] index of 1st symbol of length k */
+
+ /* Link to public Huffman table (needed only in jpeg_huff_decode) */
+ JHUFF_TBL *pub;
+
+ /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
+ * the input data stream. If the next Huffman code is no more
+ * than HUFF_LOOKAHEAD bits long, we can obtain its length and
+ * the corresponding symbol directly from these tables.
+ */
+ int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
+ UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
+} d_derived_tbl;
+
+/* Expand a Huffman table definition into the derived format */
+EXTERN void jpeg_make_d_derived_tbl JPP((j_decompress_ptr cinfo,
+ JHUFF_TBL * htbl, d_derived_tbl ** pdtbl));
+
+
+/*
+ * Fetching the next N bits from the input stream is a time-critical operation
+ * for the Huffman decoders. We implement it with a combination of inline
+ * macros and out-of-line subroutines. Note that N (the number of bits
+ * demanded at one time) never exceeds 15 for JPEG use.
+ *
+ * We read source bytes into get_buffer and dole out bits as needed.
+ * If get_buffer already contains enough bits, they are fetched in-line
+ * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
+ * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
+ * as full as possible (not just to the number of bits needed; this
+ * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
+ * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
+ * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
+ * at least the requested number of bits --- dummy zeroes are inserted if
+ * necessary.
+ */
+
+typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
+#define BIT_BUF_SIZE 32 /* size of buffer in bits */
+
+/* If long is > 32 bits on your machine, and shifting/masking longs is
+ * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
+ * appropriately should be a win. Unfortunately we can't do this with
+ * something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
+ * because not all machines measure sizeof in 8-bit bytes.
+ */
+
+typedef struct { /* Bitreading state saved across MCUs */
+ bit_buf_type get_buffer; /* current bit-extraction buffer */
+ int bits_left; /* # of unused bits in it */
+ boolean printed_eod; /* flag to suppress multiple warning msgs */
+} bitread_perm_state;
+
+typedef struct { /* Bitreading working state within an MCU */
+ /* current data source state */
+ const JOCTET * next_input_byte; /* => next byte to read from source */
+ size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
+ int unread_marker; /* nonzero if we have hit a marker */
+ /* bit input buffer --- note these values are kept in register variables,
+ * not in this struct, inside the inner loops.
+ */
+ bit_buf_type get_buffer; /* current bit-extraction buffer */
+ int bits_left; /* # of unused bits in it */
+ /* pointers needed by jpeg_fill_bit_buffer */
+ j_decompress_ptr cinfo; /* back link to decompress master record */
+ boolean * printed_eod_ptr; /* => flag in permanent state */
+} bitread_working_state;
+
+/* Macros to declare and load/save bitread local variables. */
+#define BITREAD_STATE_VARS \
+ register bit_buf_type get_buffer; \
+ register int bits_left; \
+ bitread_working_state br_state
+
+#define BITREAD_LOAD_STATE(cinfop,permstate) \
+ br_state.cinfo = cinfop; \
+ br_state.next_input_byte = cinfop->src->next_input_byte; \
+ br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
+ br_state.unread_marker = cinfop->unread_marker; \
+ get_buffer = permstate.get_buffer; \
+ bits_left = permstate.bits_left; \
+ br_state.printed_eod_ptr = & permstate.printed_eod
+
+#define BITREAD_SAVE_STATE(cinfop,permstate) \
+ cinfop->src->next_input_byte = br_state.next_input_byte; \
+ cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
+ cinfop->unread_marker = br_state.unread_marker; \
+ permstate.get_buffer = get_buffer; \
+ permstate.bits_left = bits_left
+
+/*
+ * These macros provide the in-line portion of bit fetching.
+ * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
+ * before using GET_BITS, PEEK_BITS, or DROP_BITS.
+ * The variables get_buffer and bits_left are assumed to be locals,
+ * but the state struct might not be (jpeg_huff_decode needs this).
+ * CHECK_BIT_BUFFER(state,n,action);
+ * Ensure there are N bits in get_buffer; if suspend, take action.
+ * val = GET_BITS(n);
+ * Fetch next N bits.
+ * val = PEEK_BITS(n);
+ * Fetch next N bits without removing them from the buffer.
+ * DROP_BITS(n);
+ * Discard next N bits.
+ * The value N should be a simple variable, not an expression, because it
+ * is evaluated multiple times.
+ */
+
+#define CHECK_BIT_BUFFER(state,nbits,action) \
+ { if (bits_left < (nbits)) { \
+ if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
+ { action; } \
+ get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
+
+#define GET_BITS(nbits) \
+ (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
+
+#define PEEK_BITS(nbits) \
+ (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
+
+#define DROP_BITS(nbits) \
+ (bits_left -= (nbits))
+
+/* Load up the bit buffer to a depth of at least nbits */
+EXTERN boolean jpeg_fill_bit_buffer JPP((bitread_working_state * state,
+ register bit_buf_type get_buffer, register int bits_left,
+ int nbits));
+
+
+/*
+ * Code for extracting next Huffman-coded symbol from input bit stream.
+ * Again, this is time-critical and we make the main paths be macros.
+ *
+ * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
+ * without looping. Usually, more than 95% of the Huffman codes will be 8
+ * or fewer bits long. The few overlength codes are handled with a loop,
+ * which need not be inline code.
+ *
+ * Notes about the HUFF_DECODE macro:
+ * 1. Near the end of the data segment, we may fail to get enough bits
+ * for a lookahead. In that case, we do it the hard way.
+ * 2. If the lookahead table contains no entry, the next code must be
+ * more than HUFF_LOOKAHEAD bits long.
+ * 3. jpeg_huff_decode returns -1 if forced to suspend.
+ */
+
+#define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
+{ register int nb, look; \
+ if (bits_left < HUFF_LOOKAHEAD) { \
+ if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
+ get_buffer = state.get_buffer; bits_left = state.bits_left; \
+ if (bits_left < HUFF_LOOKAHEAD) { \
+ nb = 1; goto slowlabel; \
+ } \
+ } \
+ look = PEEK_BITS(HUFF_LOOKAHEAD); \
+ if ((nb = htbl->look_nbits[look]) != 0) { \
+ DROP_BITS(nb); \
+ result = htbl->look_sym[look]; \
+ } else { \
+ nb = HUFF_LOOKAHEAD+1; \
+slowlabel: \
+ if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
+ { failaction; } \
+ get_buffer = state.get_buffer; bits_left = state.bits_left; \
+ } \
+}
+
+/* Out-of-line case for Huffman code fetching */
+EXTERN int jpeg_huff_decode JPP((bitread_working_state * state,
+ register bit_buf_type get_buffer, register int bits_left,
+ d_derived_tbl * htbl, int min_bits));
diff --git a/libs/jpeg6/jdinput.cpp b/libs/jpeg6/jdinput.cpp
new file mode 100755
index 0000000..5b4774f
--- /dev/null
+++ b/libs/jpeg6/jdinput.cpp
@@ -0,0 +1,381 @@
+/*
+ * jdinput.c
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains input control logic for the JPEG decompressor.
+ * These routines are concerned with controlling the decompressor's input
+ * processing (marker reading and coefficient decoding). The actual input
+ * reading is done in jdmarker.c, jdhuff.c, and jdphuff.c.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Private state */
+
+typedef struct {
+ struct jpeg_input_controller pub; /* public fields */
+
+ boolean inheaders; /* TRUE until first SOS is reached */
+} my_input_controller;
+
+typedef my_input_controller * my_inputctl_ptr;
+
+
+/* Forward declarations */
+METHODDEF int consume_markers JPP((j_decompress_ptr cinfo));
+
+
+/*
+ * Routines to calculate various quantities related to the size of the image.
+ */
+
+LOCAL void
+initial_setup (j_decompress_ptr cinfo)
+/* Called once, when first SOS marker is reached */
+{
+ int ci;
+ jpeg_component_info *compptr;
+
+ /* Make sure image isn't bigger than I can handle */
+ if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
+ (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
+ ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
+
+ /* For now, precision must match compiled-in value... */
+ if (cinfo->data_precision != BITS_IN_JSAMPLE)
+ ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
+
+ /* Check that number of components won't exceed internal array sizes */
+ if (cinfo->num_components > MAX_COMPONENTS)
+ ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
+ MAX_COMPONENTS);
+
+ /* Compute maximum sampling factors; check factor validity */
+ cinfo->max_h_samp_factor = 1;
+ cinfo->max_v_samp_factor = 1;
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
+ compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
+ ERREXIT(cinfo, JERR_BAD_SAMPLING);
+ cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
+ compptr->h_samp_factor);
+ cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
+ compptr->v_samp_factor);
+ }
+
+ /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
+ * In the full decompressor, this will be overridden by jdmaster.c;
+ * but in the transcoder, jdmaster.c is not used, so we must do it here.
+ */
+ cinfo->min_DCT_scaled_size = DCTSIZE;
+
+ /* Compute dimensions of components */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ compptr->DCT_scaled_size = DCTSIZE;
+ /* Size in DCT blocks */
+ compptr->width_in_blocks = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
+ (long) (cinfo->max_h_samp_factor * DCTSIZE));
+ compptr->height_in_blocks = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
+ (long) (cinfo->max_v_samp_factor * DCTSIZE));
+ /* downsampled_width and downsampled_height will also be overridden by
+ * jdmaster.c if we are doing full decompression. The transcoder library
+ * doesn't use these values, but the calling application might.
+ */
+ /* Size in samples */
+ compptr->downsampled_width = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
+ (long) cinfo->max_h_samp_factor);
+ compptr->downsampled_height = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
+ (long) cinfo->max_v_samp_factor);
+ /* Mark component needed, until color conversion says otherwise */
+ compptr->component_needed = TRUE;
+ /* Mark no quantization table yet saved for component */
+ compptr->quant_table = NULL;
+ }
+
+ /* Compute number of fully interleaved MCU rows. */
+ cinfo->total_iMCU_rows = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height,
+ (long) (cinfo->max_v_samp_factor*DCTSIZE));
+
+ /* Decide whether file contains multiple scans */
+ if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
+ cinfo->inputctl->has_multiple_scans = TRUE;
+ else
+ cinfo->inputctl->has_multiple_scans = FALSE;
+}
+
+
+LOCAL void
+per_scan_setup (j_decompress_ptr cinfo)
+/* Do computations that are needed before processing a JPEG scan */
+/* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
+{
+ int ci, mcublks, tmp;
+ jpeg_component_info *compptr;
+
+ if (cinfo->comps_in_scan == 1) {
+
+ /* Noninterleaved (single-component) scan */
+ compptr = cinfo->cur_comp_info[0];
+
+ /* Overall image size in MCUs */
+ cinfo->MCUs_per_row = compptr->width_in_blocks;
+ cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
+
+ /* For noninterleaved scan, always one block per MCU */
+ compptr->MCU_width = 1;
+ compptr->MCU_height = 1;
+ compptr->MCU_blocks = 1;
+ compptr->MCU_sample_width = compptr->DCT_scaled_size;
+ compptr->last_col_width = 1;
+ /* For noninterleaved scans, it is convenient to define last_row_height
+ * as the number of block rows present in the last iMCU row.
+ */
+ tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
+ if (tmp == 0) tmp = compptr->v_samp_factor;
+ compptr->last_row_height = tmp;
+
+ /* Prepare array describing MCU composition */
+ cinfo->blocks_in_MCU = 1;
+ cinfo->MCU_membership[0] = 0;
+
+ } else {
+
+ /* Interleaved (multi-component) scan */
+ if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
+ ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
+ MAX_COMPS_IN_SCAN);
+
+ /* Overall image size in MCUs */
+ cinfo->MCUs_per_row = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width,
+ (long) (cinfo->max_h_samp_factor*DCTSIZE));
+ cinfo->MCU_rows_in_scan = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height,
+ (long) (cinfo->max_v_samp_factor*DCTSIZE));
+
+ cinfo->blocks_in_MCU = 0;
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ /* Sampling factors give # of blocks of component in each MCU */
+ compptr->MCU_width = compptr->h_samp_factor;
+ compptr->MCU_height = compptr->v_samp_factor;
+ compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
+ compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
+ /* Figure number of non-dummy blocks in last MCU column & row */
+ tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
+ if (tmp == 0) tmp = compptr->MCU_width;
+ compptr->last_col_width = tmp;
+ tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
+ if (tmp == 0) tmp = compptr->MCU_height;
+ compptr->last_row_height = tmp;
+ /* Prepare array describing MCU composition */
+ mcublks = compptr->MCU_blocks;
+ if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
+ ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
+ while (mcublks-- > 0) {
+ cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
+ }
+ }
+
+ }
+}
+
+
+/*
+ * Save away a copy of the Q-table referenced by each component present
+ * in the current scan, unless already saved during a prior scan.
+ *
+ * In a multiple-scan JPEG file, the encoder could assign different components
+ * the same Q-table slot number, but change table definitions between scans
+ * so that each component uses a different Q-table. (The IJG encoder is not
+ * currently capable of doing this, but other encoders might.) Since we want
+ * to be able to dequantize all the components at the end of the file, this
+ * means that we have to save away the table actually used for each component.
+ * We do this by copying the table at the start of the first scan containing
+ * the component.
+ * The JPEG spec prohibits the encoder from changing the contents of a Q-table
+ * slot between scans of a component using that slot. If the encoder does so
+ * anyway, this decoder will simply use the Q-table values that were current
+ * at the start of the first scan for the component.
+ *
+ * The decompressor output side looks only at the saved quant tables,
+ * not at the current Q-table slots.
+ */
+
+LOCAL void
+latch_quant_tables (j_decompress_ptr cinfo)
+{
+ int ci, qtblno;
+ jpeg_component_info *compptr;
+ JQUANT_TBL * qtbl;
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ /* No work if we already saved Q-table for this component */
+ if (compptr->quant_table != NULL)
+ continue;
+ /* Make sure specified quantization table is present */
+ qtblno = compptr->quant_tbl_no;
+ if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
+ cinfo->quant_tbl_ptrs[qtblno] == NULL)
+ ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
+ /* OK, save away the quantization table */
+ qtbl = (JQUANT_TBL *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(JQUANT_TBL));
+ MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
+ compptr->quant_table = qtbl;
+ }
+}
+
+
+/*
+ * Initialize the input modules to read a scan of compressed data.
+ * The first call to this is done by jdmaster.c after initializing
+ * the entire decompressor (during jpeg_start_decompress).
+ * Subsequent calls come from consume_markers, below.
+ */
+
+METHODDEF void
+start_input_pass (j_decompress_ptr cinfo)
+{
+ per_scan_setup(cinfo);
+ latch_quant_tables(cinfo);
+ (*cinfo->entropy->start_pass) (cinfo);
+ (*cinfo->coef->start_input_pass) (cinfo);
+ cinfo->inputctl->consume_input = cinfo->coef->consume_data;
+}
+
+
+/*
+ * Finish up after inputting a compressed-data scan.
+ * This is called by the coefficient controller after it's read all
+ * the expected data of the scan.
+ */
+
+METHODDEF void
+finish_input_pass (j_decompress_ptr cinfo)
+{
+ cinfo->inputctl->consume_input = consume_markers;
+}
+
+
+/*
+ * Read JPEG markers before, between, or after compressed-data scans.
+ * Change state as necessary when a new scan is reached.
+ * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
+ *
+ * The consume_input method pointer points either here or to the
+ * coefficient controller's consume_data routine, depending on whether
+ * we are reading a compressed data segment or inter-segment markers.
+ */
+
+METHODDEF int
+consume_markers (j_decompress_ptr cinfo)
+{
+ my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
+ int val;
+
+ if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
+ return JPEG_REACHED_EOI;
+
+ val = (*cinfo->marker->read_markers) (cinfo);
+
+ switch (val) {
+ case JPEG_REACHED_SOS: /* Found SOS */
+ if (inputctl->inheaders) { /* 1st SOS */
+ initial_setup(cinfo);
+ inputctl->inheaders = FALSE;
+ /* Note: start_input_pass must be called by jdmaster.c
+ * before any more input can be consumed. jdapi.c is
+ * responsible for enforcing this sequencing.
+ */
+ } else { /* 2nd or later SOS marker */
+ if (! inputctl->pub.has_multiple_scans)
+ ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
+ start_input_pass(cinfo);
+ }
+ break;
+ case JPEG_REACHED_EOI: /* Found EOI */
+ inputctl->pub.eoi_reached = TRUE;
+ if (inputctl->inheaders) { /* Tables-only datastream, apparently */
+ if (cinfo->marker->saw_SOF)
+ ERREXIT(cinfo, JERR_SOF_NO_SOS);
+ } else {
+ /* Prevent infinite loop in coef ctlr's decompress_data routine
+ * if user set output_scan_number larger than number of scans.
+ */
+ if (cinfo->output_scan_number > cinfo->input_scan_number)
+ cinfo->output_scan_number = cinfo->input_scan_number;
+ }
+ break;
+ case JPEG_SUSPENDED:
+ break;
+ }
+
+ return val;
+}
+
+
+/*
+ * Reset state to begin a fresh datastream.
+ */
+
+METHODDEF void
+reset_input_controller (j_decompress_ptr cinfo)
+{
+ my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
+
+ inputctl->pub.consume_input = consume_markers;
+ inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
+ inputctl->pub.eoi_reached = FALSE;
+ inputctl->inheaders = TRUE;
+ /* Reset other modules */
+ (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
+ (*cinfo->marker->reset_marker_reader) (cinfo);
+ /* Reset progression state -- would be cleaner if entropy decoder did this */
+ cinfo->coef_bits = NULL;
+}
+
+
+/*
+ * Initialize the input controller module.
+ * This is called only once, when the decompression object is created.
+ */
+
+GLOBAL void
+jinit_input_controller (j_decompress_ptr cinfo)
+{
+ my_inputctl_ptr inputctl;
+
+ /* Create subobject in permanent pool */
+ inputctl = (my_inputctl_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ SIZEOF(my_input_controller));
+ cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
+ /* Initialize method pointers */
+ inputctl->pub.consume_input = consume_markers;
+ inputctl->pub.reset_input_controller = reset_input_controller;
+ inputctl->pub.start_input_pass = start_input_pass;
+ inputctl->pub.finish_input_pass = finish_input_pass;
+ /* Initialize state: can't use reset_input_controller since we don't
+ * want to try to reset other modules yet.
+ */
+ inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
+ inputctl->pub.eoi_reached = FALSE;
+ inputctl->inheaders = TRUE;
+}
diff --git a/libs/jpeg6/jdmainct.cpp b/libs/jpeg6/jdmainct.cpp
new file mode 100755
index 0000000..c4e0d54
--- /dev/null
+++ b/libs/jpeg6/jdmainct.cpp
@@ -0,0 +1,512 @@
+/*
+ * jdmainct.c
+ *
+ * Copyright (C) 1994-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the main buffer controller for decompression.
+ * The main buffer lies between the JPEG decompressor proper and the
+ * post-processor; it holds downsampled data in the JPEG colorspace.
+ *
+ * Note that this code is bypassed in raw-data mode, since the application
+ * supplies the equivalent of the main buffer in that case.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/*
+ * In the current system design, the main buffer need never be a full-image
+ * buffer; any full-height buffers will be found inside the coefficient or
+ * postprocessing controllers. Nonetheless, the main controller is not
+ * trivial. Its responsibility is to provide context rows for upsampling/
+ * rescaling, and doing this in an efficient fashion is a bit tricky.
+ *
+ * Postprocessor input data is counted in "row groups". A row group
+ * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
+ * sample rows of each component. (We require DCT_scaled_size values to be
+ * chosen such that these numbers are integers. In practice DCT_scaled_size
+ * values will likely be powers of two, so we actually have the stronger
+ * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
+ * Upsampling will typically produce max_v_samp_factor pixel rows from each
+ * row group (times any additional scale factor that the upsampler is
+ * applying).
+ *
+ * The coefficient controller will deliver data to us one iMCU row at a time;
+ * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
+ * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
+ * to one row of MCUs when the image is fully interleaved.) Note that the
+ * number of sample rows varies across components, but the number of row
+ * groups does not. Some garbage sample rows may be included in the last iMCU
+ * row at the bottom of the image.
+ *
+ * Depending on the vertical scaling algorithm used, the upsampler may need
+ * access to the sample row(s) above and below its current input row group.
+ * The upsampler is required to set need_context_rows TRUE at global selection
+ * time if so. When need_context_rows is FALSE, this controller can simply
+ * obtain one iMCU row at a time from the coefficient controller and dole it
+ * out as row groups to the postprocessor.
+ *
+ * When need_context_rows is TRUE, this controller guarantees that the buffer
+ * passed to postprocessing contains at least one row group's worth of samples
+ * above and below the row group(s) being processed. Note that the context
+ * rows "above" the first passed row group appear at negative row offsets in
+ * the passed buffer. At the top and bottom of the image, the required
+ * context rows are manufactured by duplicating the first or last real sample
+ * row; this avoids having special cases in the upsampling inner loops.
+ *
+ * The amount of context is fixed at one row group just because that's a
+ * convenient number for this controller to work with. The existing
+ * upsamplers really only need one sample row of context. An upsampler
+ * supporting arbitrary output rescaling might wish for more than one row
+ * group of context when shrinking the image; tough, we don't handle that.
+ * (This is justified by the assumption that downsizing will be handled mostly
+ * by adjusting the DCT_scaled_size values, so that the actual scale factor at
+ * the upsample step needn't be much less than one.)
+ *
+ * To provide the desired context, we have to retain the last two row groups
+ * of one iMCU row while reading in the next iMCU row. (The last row group
+ * can't be processed until we have another row group for its below-context,
+ * and so we have to save the next-to-last group too for its above-context.)
+ * We could do this most simply by copying data around in our buffer, but
+ * that'd be very slow. We can avoid copying any data by creating a rather
+ * strange pointer structure. Here's how it works. We allocate a workspace
+ * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
+ * of row groups per iMCU row). We create two sets of redundant pointers to
+ * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
+ * pointer lists look like this:
+ * M+1 M-1
+ * master pointer --> 0 master pointer --> 0
+ * 1 1
+ * ... ...
+ * M-3 M-3
+ * M-2 M
+ * M-1 M+1
+ * M M-2
+ * M+1 M-1
+ * 0 0
+ * We read alternate iMCU rows using each master pointer; thus the last two
+ * row groups of the previous iMCU row remain un-overwritten in the workspace.
+ * The pointer lists are set up so that the required context rows appear to
+ * be adjacent to the proper places when we pass the pointer lists to the
+ * upsampler.
+ *
+ * The above pictures describe the normal state of the pointer lists.
+ * At top and bottom of the image, we diddle the pointer lists to duplicate
+ * the first or last sample row as necessary (this is cheaper than copying
+ * sample rows around).
+ *
+ * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
+ * situation each iMCU row provides only one row group so the buffering logic
+ * must be different (eg, we must read two iMCU rows before we can emit the
+ * first row group). For now, we simply do not support providing context
+ * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
+ * be worth providing --- if someone wants a 1/8th-size preview, they probably
+ * want it quick and dirty, so a context-free upsampler is sufficient.
+ */
+
+
+/* Private buffer controller object */
+
+typedef struct {
+ struct jpeg_d_main_controller pub; /* public fields */
+
+ /* Pointer to allocated workspace (M or M+2 row groups). */
+ JSAMPARRAY buffer[MAX_COMPONENTS];
+
+ boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
+ JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
+
+ /* Remaining fields are only used in the context case. */
+
+ /* These are the master pointers to the funny-order pointer lists. */
+ JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
+
+ int whichptr; /* indicates which pointer set is now in use */
+ int context_state; /* process_data state machine status */
+ JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
+ JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
+} my_main_controller;
+
+typedef my_main_controller * my_main_ptr;
+
+/* context_state values: */
+#define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
+#define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
+#define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
+
+
+/* Forward declarations */
+METHODDEF void process_data_simple_main
+ JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
+ JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
+METHODDEF void process_data_context_main
+ JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
+ JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
+#ifdef QUANT_2PASS_SUPPORTED
+METHODDEF void process_data_crank_post
+ JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
+ JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
+#endif
+
+
+LOCAL void
+alloc_funny_pointers (j_decompress_ptr cinfo)
+/* Allocate space for the funny pointer lists.
+ * This is done only once, not once per pass.
+ */
+{
+ my_main_ptr main = (my_main_ptr) cinfo->main;
+ int ci, rgroup;
+ int M = cinfo->min_DCT_scaled_size;
+ jpeg_component_info *compptr;
+ JSAMPARRAY xbuf;
+
+ /* Get top-level space for component array pointers.
+ * We alloc both arrays with one call to save a few cycles.
+ */
+ main->xbuffer[0] = (JSAMPIMAGE)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
+ main->xbuffer[1] = main->xbuffer[0] + cinfo->num_components;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
+ cinfo->min_DCT_scaled_size; /* height of a row group of component */
+ /* Get space for pointer lists --- M+4 row groups in each list.
+ * We alloc both pointer lists with one call to save a few cycles.
+ */
+ xbuf = (JSAMPARRAY)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
+ xbuf += rgroup; /* want one row group at negative offsets */
+ main->xbuffer[0][ci] = xbuf;
+ xbuf += rgroup * (M + 4);
+ main->xbuffer[1][ci] = xbuf;
+ }
+}
+
+
+LOCAL void
+make_funny_pointers (j_decompress_ptr cinfo)
+/* Create the funny pointer lists discussed in the comments above.
+ * The actual workspace is already allocated (in main->buffer),
+ * and the space for the pointer lists is allocated too.
+ * This routine just fills in the curiously ordered lists.
+ * This will be repeated at the beginning of each pass.
+ */
+{
+ my_main_ptr main = (my_main_ptr) cinfo->main;
+ int ci, i, rgroup;
+ int M = cinfo->min_DCT_scaled_size;
+ jpeg_component_info *compptr;
+ JSAMPARRAY buf, xbuf0, xbuf1;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
+ cinfo->min_DCT_scaled_size; /* height of a row group of component */
+ xbuf0 = main->xbuffer[0][ci];
+ xbuf1 = main->xbuffer[1][ci];
+ /* First copy the workspace pointers as-is */
+ buf = main->buffer[ci];
+ for (i = 0; i < rgroup * (M + 2); i++) {
+ xbuf0[i] = xbuf1[i] = buf[i];
+ }
+ /* In the second list, put the last four row groups in swapped order */
+ for (i = 0; i < rgroup * 2; i++) {
+ xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
+ xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
+ }
+ /* The wraparound pointers at top and bottom will be filled later
+ * (see set_wraparound_pointers, below). Initially we want the "above"
+ * pointers to duplicate the first actual data line. This only needs
+ * to happen in xbuffer[0].
+ */
+ for (i = 0; i < rgroup; i++) {
+ xbuf0[i - rgroup] = xbuf0[0];
+ }
+ }
+}
+
+
+LOCAL void
+set_wraparound_pointers (j_decompress_ptr cinfo)
+/* Set up the "wraparound" pointers at top and bottom of the pointer lists.
+ * This changes the pointer list state from top-of-image to the normal state.
+ */
+{
+ my_main_ptr main = (my_main_ptr) cinfo->main;
+ int ci, i, rgroup;
+ int M = cinfo->min_DCT_scaled_size;
+ jpeg_component_info *compptr;
+ JSAMPARRAY xbuf0, xbuf1;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
+ cinfo->min_DCT_scaled_size; /* height of a row group of component */
+ xbuf0 = main->xbuffer[0][ci];
+ xbuf1 = main->xbuffer[1][ci];
+ for (i = 0; i < rgroup; i++) {
+ xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
+ xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
+ xbuf0[rgroup*(M+2) + i] = xbuf0[i];
+ xbuf1[rgroup*(M+2) + i] = xbuf1[i];
+ }
+ }
+}
+
+
+LOCAL void
+set_bottom_pointers (j_decompress_ptr cinfo)
+/* Change the pointer lists to duplicate the last sample row at the bottom
+ * of the image. whichptr indicates which xbuffer holds the final iMCU row.
+ * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
+ */
+{
+ my_main_ptr main = (my_main_ptr) cinfo->main;
+ int ci, i, rgroup, iMCUheight, rows_left;
+ jpeg_component_info *compptr;
+ JSAMPARRAY xbuf;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Count sample rows in one iMCU row and in one row group */
+ iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
+ rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
+ /* Count nondummy sample rows remaining for this component */
+ rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
+ if (rows_left == 0) rows_left = iMCUheight;
+ /* Count nondummy row groups. Should get same answer for each component,
+ * so we need only do it once.
+ */
+ if (ci == 0) {
+ main->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
+ }
+ /* Duplicate the last real sample row rgroup*2 times; this pads out the
+ * last partial rowgroup and ensures at least one full rowgroup of context.
+ */
+ xbuf = main->xbuffer[main->whichptr][ci];
+ for (i = 0; i < rgroup * 2; i++) {
+ xbuf[rows_left + i] = xbuf[rows_left-1];
+ }
+ }
+}
+
+
+/*
+ * Initialize for a processing pass.
+ */
+
+METHODDEF void
+start_pass_main (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
+{
+ my_main_ptr main = (my_main_ptr) cinfo->main;
+
+ switch (pass_mode) {
+ case JBUF_PASS_THRU:
+ if (cinfo->upsample->need_context_rows) {
+ main->pub.process_data = process_data_context_main;
+ make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
+ main->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
+ main->context_state = CTX_PREPARE_FOR_IMCU;
+ main->iMCU_row_ctr = 0;
+ } else {
+ /* Simple case with no context needed */
+ main->pub.process_data = process_data_simple_main;
+ }
+ main->buffer_full = FALSE; /* Mark buffer empty */
+ main->rowgroup_ctr = 0;
+ break;
+#ifdef QUANT_2PASS_SUPPORTED
+ case JBUF_CRANK_DEST:
+ /* For last pass of 2-pass quantization, just crank the postprocessor */
+ main->pub.process_data = process_data_crank_post;
+ break;
+#endif
+ default:
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ break;
+ }
+}
+
+
+/*
+ * Process some data.
+ * This handles the simple case where no context is required.
+ */
+
+METHODDEF void
+process_data_simple_main (j_decompress_ptr cinfo,
+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+{
+ my_main_ptr main = (my_main_ptr) cinfo->main;
+ JDIMENSION rowgroups_avail;
+
+ /* Read input data if we haven't filled the main buffer yet */
+ if (! main->buffer_full) {
+ if (! (*cinfo->coef->decompress_data) (cinfo, main->buffer))
+ return; /* suspension forced, can do nothing more */
+ main->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
+ }
+
+ /* There are always min_DCT_scaled_size row groups in an iMCU row. */
+ rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
+ /* Note: at the bottom of the image, we may pass extra garbage row groups
+ * to the postprocessor. The postprocessor has to check for bottom
+ * of image anyway (at row resolution), so no point in us doing it too.
+ */
+
+ /* Feed the postprocessor */
+ (*cinfo->post->post_process_data) (cinfo, main->buffer,
+ &main->rowgroup_ctr, rowgroups_avail,
+ output_buf, out_row_ctr, out_rows_avail);
+
+ /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
+ if (main->rowgroup_ctr >= rowgroups_avail) {
+ main->buffer_full = FALSE;
+ main->rowgroup_ctr = 0;
+ }
+}
+
+
+/*
+ * Process some data.
+ * This handles the case where context rows must be provided.
+ */
+
+METHODDEF void
+process_data_context_main (j_decompress_ptr cinfo,
+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+{
+ my_main_ptr main = (my_main_ptr) cinfo->main;
+
+ /* Read input data if we haven't filled the main buffer yet */
+ if (! main->buffer_full) {
+ if (! (*cinfo->coef->decompress_data) (cinfo,
+ main->xbuffer[main->whichptr]))
+ return; /* suspension forced, can do nothing more */
+ main->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
+ main->iMCU_row_ctr++; /* count rows received */
+ }
+
+ /* Postprocessor typically will not swallow all the input data it is handed
+ * in one call (due to filling the output buffer first). Must be prepared
+ * to exit and restart. This switch lets us keep track of how far we got.
+ * Note that each case falls through to the next on successful completion.
+ */
+ switch (main->context_state) {
+ case CTX_POSTPONED_ROW:
+ /* Call postprocessor using previously set pointers for postponed row */
+ (*cinfo->post->post_process_data) (cinfo, main->xbuffer[main->whichptr],
+ &main->rowgroup_ctr, main->rowgroups_avail,
+ output_buf, out_row_ctr, out_rows_avail);
+ if (main->rowgroup_ctr < main->rowgroups_avail)
+ return; /* Need to suspend */
+ main->context_state = CTX_PREPARE_FOR_IMCU;
+ if (*out_row_ctr >= out_rows_avail)
+ return; /* Postprocessor exactly filled output buf */
+ /*FALLTHROUGH*/
+ case CTX_PREPARE_FOR_IMCU:
+ /* Prepare to process first M-1 row groups of this iMCU row */
+ main->rowgroup_ctr = 0;
+ main->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
+ /* Check for bottom of image: if so, tweak pointers to "duplicate"
+ * the last sample row, and adjust rowgroups_avail to ignore padding rows.
+ */
+ if (main->iMCU_row_ctr == cinfo->total_iMCU_rows)
+ set_bottom_pointers(cinfo);
+ main->context_state = CTX_PROCESS_IMCU;
+ /*FALLTHROUGH*/
+ case CTX_PROCESS_IMCU:
+ /* Call postprocessor using previously set pointers */
+ (*cinfo->post->post_process_data) (cinfo, main->xbuffer[main->whichptr],
+ &main->rowgroup_ctr, main->rowgroups_avail,
+ output_buf, out_row_ctr, out_rows_avail);
+ if (main->rowgroup_ctr < main->rowgroups_avail)
+ return; /* Need to suspend */
+ /* After the first iMCU, change wraparound pointers to normal state */
+ if (main->iMCU_row_ctr == 1)
+ set_wraparound_pointers(cinfo);
+ /* Prepare to load new iMCU row using other xbuffer list */
+ main->whichptr ^= 1; /* 0=>1 or 1=>0 */
+ main->buffer_full = FALSE;
+ /* Still need to process last row group of this iMCU row, */
+ /* which is saved at index M+1 of the other xbuffer */
+ main->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
+ main->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
+ main->context_state = CTX_POSTPONED_ROW;
+ }
+}
+
+
+/*
+ * Process some data.
+ * Final pass of two-pass quantization: just call the postprocessor.
+ * Source data will be the postprocessor controller's internal buffer.
+ */
+
+#ifdef QUANT_2PASS_SUPPORTED
+
+METHODDEF void
+process_data_crank_post (j_decompress_ptr cinfo,
+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+{
+ (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
+ (JDIMENSION *) NULL, (JDIMENSION) 0,
+ output_buf, out_row_ctr, out_rows_avail);
+}
+
+#endif /* QUANT_2PASS_SUPPORTED */
+
+
+/*
+ * Initialize main buffer controller.
+ */
+
+GLOBAL void
+jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
+{
+ my_main_ptr main;
+ int ci, rgroup, ngroups;
+ jpeg_component_info *compptr;
+
+ main = (my_main_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_main_controller));
+ cinfo->main = (struct jpeg_d_main_controller *) main;
+ main->pub.start_pass = start_pass_main;
+
+ if (need_full_buffer) /* shouldn't happen */
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+
+ /* Allocate the workspace.
+ * ngroups is the number of row groups we need.
+ */
+ if (cinfo->upsample->need_context_rows) {
+ if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
+ ERREXIT(cinfo, JERR_NOTIMPL);
+ alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
+ ngroups = cinfo->min_DCT_scaled_size + 2;
+ } else {
+ ngroups = cinfo->min_DCT_scaled_size;
+ }
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
+ cinfo->min_DCT_scaled_size; /* height of a row group of component */
+ main->buffer[ci] = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ compptr->width_in_blocks * compptr->DCT_scaled_size,
+ (JDIMENSION) (rgroup * ngroups));
+ }
+}
diff --git a/libs/jpeg6/jdmarker.cpp b/libs/jpeg6/jdmarker.cpp
new file mode 100755
index 0000000..6c3c519
--- /dev/null
+++ b/libs/jpeg6/jdmarker.cpp
@@ -0,0 +1,1052 @@
+/*
+ * jdmarker.c
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains routines to decode JPEG datastream markers.
+ * Most of the complexity arises from our desire to support input
+ * suspension: if not all of the data for a marker is available,
+ * we must exit back to the application. On resumption, we reprocess
+ * the marker.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+typedef enum { /* JPEG marker codes */
+ M_SOF0 = 0xc0,
+ M_SOF1 = 0xc1,
+ M_SOF2 = 0xc2,
+ M_SOF3 = 0xc3,
+
+ M_SOF5 = 0xc5,
+ M_SOF6 = 0xc6,
+ M_SOF7 = 0xc7,
+
+ M_JPG = 0xc8,
+ M_SOF9 = 0xc9,
+ M_SOF10 = 0xca,
+ M_SOF11 = 0xcb,
+
+ M_SOF13 = 0xcd,
+ M_SOF14 = 0xce,
+ M_SOF15 = 0xcf,
+
+ M_DHT = 0xc4,
+
+ M_DAC = 0xcc,
+
+ M_RST0 = 0xd0,
+ M_RST1 = 0xd1,
+ M_RST2 = 0xd2,
+ M_RST3 = 0xd3,
+ M_RST4 = 0xd4,
+ M_RST5 = 0xd5,
+ M_RST6 = 0xd6,
+ M_RST7 = 0xd7,
+
+ M_SOI = 0xd8,
+ M_EOI = 0xd9,
+ M_SOS = 0xda,
+ M_DQT = 0xdb,
+ M_DNL = 0xdc,
+ M_DRI = 0xdd,
+ M_DHP = 0xde,
+ M_EXP = 0xdf,
+
+ M_APP0 = 0xe0,
+ M_APP1 = 0xe1,
+ M_APP2 = 0xe2,
+ M_APP3 = 0xe3,
+ M_APP4 = 0xe4,
+ M_APP5 = 0xe5,
+ M_APP6 = 0xe6,
+ M_APP7 = 0xe7,
+ M_APP8 = 0xe8,
+ M_APP9 = 0xe9,
+ M_APP10 = 0xea,
+ M_APP11 = 0xeb,
+ M_APP12 = 0xec,
+ M_APP13 = 0xed,
+ M_APP14 = 0xee,
+ M_APP15 = 0xef,
+
+ M_JPG0 = 0xf0,
+ M_JPG13 = 0xfd,
+ M_COM = 0xfe,
+
+ M_TEM = 0x01,
+
+ M_ERROR = 0x100
+} JPEG_MARKER;
+
+
+/*
+ * Macros for fetching data from the data source module.
+ *
+ * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
+ * the current restart point; we update them only when we have reached a
+ * suitable place to restart if a suspension occurs.
+ */
+
+/* Declare and initialize local copies of input pointer/count */
+#define INPUT_VARS(cinfo) \
+ struct jpeg_source_mgr * datasrc = (cinfo)->src; \
+ const JOCTET * next_input_byte = datasrc->next_input_byte; \
+ size_t bytes_in_buffer = datasrc->bytes_in_buffer
+
+/* Unload the local copies --- do this only at a restart boundary */
+#define INPUT_SYNC(cinfo) \
+ ( datasrc->next_input_byte = next_input_byte, \
+ datasrc->bytes_in_buffer = bytes_in_buffer )
+
+/* Reload the local copies --- seldom used except in MAKE_BYTE_AVAIL */
+#define INPUT_RELOAD(cinfo) \
+ ( next_input_byte = datasrc->next_input_byte, \
+ bytes_in_buffer = datasrc->bytes_in_buffer )
+
+/* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
+ * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
+ * but we must reload the local copies after a successful fill.
+ */
+#define MAKE_BYTE_AVAIL(cinfo,action) \
+ if (bytes_in_buffer == 0) { \
+ if (! (*datasrc->fill_input_buffer) (cinfo)) \
+ { action; } \
+ INPUT_RELOAD(cinfo); \
+ } \
+ bytes_in_buffer--
+
+/* Read a byte into variable V.
+ * If must suspend, take the specified action (typically "return FALSE").
+ */
+#define INPUT_BYTE(cinfo,V,action) \
+ MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
+ V = GETJOCTET(*next_input_byte++); )
+
+/* As above, but read two bytes interpreted as an unsigned 16-bit integer.
+ * V should be declared unsigned int or perhaps INT32.
+ */
+#define INPUT_2BYTES(cinfo,V,action) \
+ MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
+ V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
+ MAKE_BYTE_AVAIL(cinfo,action); \
+ V += GETJOCTET(*next_input_byte++); )
+
+
+/*
+ * Routines to process JPEG markers.
+ *
+ * Entry condition: JPEG marker itself has been read and its code saved
+ * in cinfo->unread_marker; input restart point is just after the marker.
+ *
+ * Exit: if return TRUE, have read and processed any parameters, and have
+ * updated the restart point to point after the parameters.
+ * If return FALSE, was forced to suspend before reaching end of
+ * marker parameters; restart point has not been moved. Same routine
+ * will be called again after application supplies more input data.
+ *
+ * This approach to suspension assumes that all of a marker's parameters can
+ * fit into a single input bufferload. This should hold for "normal"
+ * markers. Some COM/APPn markers might have large parameter segments,
+ * but we use skip_input_data to get past those, and thereby put the problem
+ * on the source manager's shoulders.
+ *
+ * Note that we don't bother to avoid duplicate trace messages if a
+ * suspension occurs within marker parameters. Other side effects
+ * require more care.
+ */
+
+
+LOCAL boolean
+get_soi (j_decompress_ptr cinfo)
+/* Process an SOI marker */
+{
+ int i;
+
+ TRACEMS(cinfo, 1, JTRC_SOI);
+
+ if (cinfo->marker->saw_SOI)
+ ERREXIT(cinfo, JERR_SOI_DUPLICATE);
+
+ /* Reset all parameters that are defined to be reset by SOI */
+
+ for (i = 0; i < NUM_ARITH_TBLS; i++) {
+ cinfo->arith_dc_L[i] = 0;
+ cinfo->arith_dc_U[i] = 1;
+ cinfo->arith_ac_K[i] = 5;
+ }
+ cinfo->restart_interval = 0;
+
+ /* Set initial assumptions for colorspace etc */
+
+ cinfo->jpeg_color_space = JCS_UNKNOWN;
+ cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
+
+ cinfo->saw_JFIF_marker = FALSE;
+ cinfo->density_unit = 0; /* set default JFIF APP0 values */
+ cinfo->X_density = 1;
+ cinfo->Y_density = 1;
+ cinfo->saw_Adobe_marker = FALSE;
+ cinfo->Adobe_transform = 0;
+
+ cinfo->marker->saw_SOI = TRUE;
+
+ return TRUE;
+}
+
+
+LOCAL boolean
+get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
+/* Process a SOFn marker */
+{
+ INT32 length;
+ int c, ci;
+ jpeg_component_info * compptr;
+ INPUT_VARS(cinfo);
+
+ cinfo->progressive_mode = is_prog;
+ cinfo->arith_code = is_arith;
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+
+ INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
+ INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
+ INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
+ INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
+
+ length -= 8;
+
+ TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
+ (int) cinfo->image_width, (int) cinfo->image_height,
+ cinfo->num_components);
+
+ if (cinfo->marker->saw_SOF)
+ ERREXIT(cinfo, JERR_SOF_DUPLICATE);
+
+ /* We don't support files in which the image height is initially specified */
+ /* as 0 and is later redefined by DNL. As long as we have to check that, */
+ /* might as well have a general sanity check. */
+ if (cinfo->image_height <= 0 || cinfo->image_width <= 0
+ || cinfo->num_components <= 0)
+ ERREXIT(cinfo, JERR_EMPTY_IMAGE);
+
+ if (length != (cinfo->num_components * 3))
+ ERREXIT(cinfo, JERR_BAD_LENGTH);
+
+ if (cinfo->comp_info == NULL) /* do only once, even if suspend */
+ cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ cinfo->num_components * SIZEOF(jpeg_component_info));
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ compptr->component_index = ci;
+ INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
+ INPUT_BYTE(cinfo, c, return FALSE);
+ compptr->h_samp_factor = (c >> 4) & 15;
+ compptr->v_samp_factor = (c ) & 15;
+ INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
+
+ TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
+ compptr->component_id, compptr->h_samp_factor,
+ compptr->v_samp_factor, compptr->quant_tbl_no);
+ }
+
+ cinfo->marker->saw_SOF = TRUE;
+
+ INPUT_SYNC(cinfo);
+ return TRUE;
+}
+
+
+LOCAL boolean
+get_sos (j_decompress_ptr cinfo)
+/* Process a SOS marker */
+{
+ INT32 length;
+ int i, ci, n, c, cc;
+ jpeg_component_info * compptr;
+ INPUT_VARS(cinfo);
+
+ if (! cinfo->marker->saw_SOF)
+ ERREXIT(cinfo, JERR_SOS_NO_SOF);
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+
+ INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
+
+ if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
+ ERREXIT(cinfo, JERR_BAD_LENGTH);
+
+ TRACEMS1(cinfo, 1, JTRC_SOS, n);
+
+ cinfo->comps_in_scan = n;
+
+ /* Collect the component-spec parameters */
+
+ for (i = 0; i < n; i++) {
+ INPUT_BYTE(cinfo, cc, return FALSE);
+ INPUT_BYTE(cinfo, c, return FALSE);
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ if (cc == compptr->component_id)
+ goto id_found;
+ }
+
+ ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
+
+ id_found:
+
+ cinfo->cur_comp_info[i] = compptr;
+ compptr->dc_tbl_no = (c >> 4) & 15;
+ compptr->ac_tbl_no = (c ) & 15;
+
+ TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
+ compptr->dc_tbl_no, compptr->ac_tbl_no);
+ }
+
+ /* Collect the additional scan parameters Ss, Se, Ah/Al. */
+ INPUT_BYTE(cinfo, c, return FALSE);
+ cinfo->Ss = c;
+ INPUT_BYTE(cinfo, c, return FALSE);
+ cinfo->Se = c;
+ INPUT_BYTE(cinfo, c, return FALSE);
+ cinfo->Ah = (c >> 4) & 15;
+ cinfo->Al = (c ) & 15;
+
+ TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
+ cinfo->Ah, cinfo->Al);
+
+ /* Prepare to scan data & restart markers */
+ cinfo->marker->next_restart_num = 0;
+
+ /* Count another SOS marker */
+ cinfo->input_scan_number++;
+
+ INPUT_SYNC(cinfo);
+ return TRUE;
+}
+
+
+METHODDEF boolean
+get_app0 (j_decompress_ptr cinfo)
+/* Process an APP0 marker */
+{
+#define JFIF_LEN 14
+ INT32 length;
+ UINT8 b[JFIF_LEN];
+ int buffp;
+ INPUT_VARS(cinfo);
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+ length -= 2;
+
+ /* See if a JFIF APP0 marker is present */
+
+ if (length >= JFIF_LEN) {
+ for (buffp = 0; buffp < JFIF_LEN; buffp++)
+ INPUT_BYTE(cinfo, b[buffp], return FALSE);
+ length -= JFIF_LEN;
+
+ if (b[0]==0x4A && b[1]==0x46 && b[2]==0x49 && b[3]==0x46 && b[4]==0) {
+ /* Found JFIF APP0 marker: check version */
+ /* Major version must be 1, anything else signals an incompatible change.
+ * We used to treat this as an error, but now it's a nonfatal warning,
+ * because some bozo at Hijaak couldn't read the spec.
+ * Minor version should be 0..2, but process anyway if newer.
+ */
+ if (b[5] != 1)
+ WARNMS2(cinfo, JWRN_JFIF_MAJOR, b[5], b[6]);
+ else if (b[6] > 2)
+ TRACEMS2(cinfo, 1, JTRC_JFIF_MINOR, b[5], b[6]);
+ /* Save info */
+ cinfo->saw_JFIF_marker = TRUE;
+ cinfo->density_unit = b[7];
+ cinfo->X_density = (b[8] << 8) + b[9];
+ cinfo->Y_density = (b[10] << 8) + b[11];
+ TRACEMS3(cinfo, 1, JTRC_JFIF,
+ cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
+ if (b[12] | b[13])
+ TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL, b[12], b[13]);
+ if (length != ((INT32) b[12] * (INT32) b[13] * (INT32) 3))
+ TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) length);
+ } else {
+ /* Start of APP0 does not match "JFIF" */
+ TRACEMS1(cinfo, 1, JTRC_APP0, (int) length + JFIF_LEN);
+ }
+ } else {
+ /* Too short to be JFIF marker */
+ TRACEMS1(cinfo, 1, JTRC_APP0, (int) length);
+ }
+
+ INPUT_SYNC(cinfo);
+ if (length > 0) /* skip any remaining data -- could be lots */
+ (*cinfo->src->skip_input_data) (cinfo, (long) length);
+
+ return TRUE;
+}
+
+
+METHODDEF boolean
+get_app14 (j_decompress_ptr cinfo)
+/* Process an APP14 marker */
+{
+#define ADOBE_LEN 12
+ INT32 length;
+ UINT8 b[ADOBE_LEN];
+ int buffp;
+ unsigned int version, flags0, flags1, transform;
+ INPUT_VARS(cinfo);
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+ length -= 2;
+
+ /* See if an Adobe APP14 marker is present */
+
+ if (length >= ADOBE_LEN) {
+ for (buffp = 0; buffp < ADOBE_LEN; buffp++)
+ INPUT_BYTE(cinfo, b[buffp], return FALSE);
+ length -= ADOBE_LEN;
+
+ if (b[0]==0x41 && b[1]==0x64 && b[2]==0x6F && b[3]==0x62 && b[4]==0x65) {
+ /* Found Adobe APP14 marker */
+ version = (b[5] << 8) + b[6];
+ flags0 = (b[7] << 8) + b[8];
+ flags1 = (b[9] << 8) + b[10];
+ transform = b[11];
+ TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
+ cinfo->saw_Adobe_marker = TRUE;
+ cinfo->Adobe_transform = (UINT8) transform;
+ } else {
+ /* Start of APP14 does not match "Adobe" */
+ TRACEMS1(cinfo, 1, JTRC_APP14, (int) length + ADOBE_LEN);
+ }
+ } else {
+ /* Too short to be Adobe marker */
+ TRACEMS1(cinfo, 1, JTRC_APP14, (int) length);
+ }
+
+ INPUT_SYNC(cinfo);
+ if (length > 0) /* skip any remaining data -- could be lots */
+ (*cinfo->src->skip_input_data) (cinfo, (long) length);
+
+ return TRUE;
+}
+
+
+LOCAL boolean
+get_dac (j_decompress_ptr cinfo)
+/* Process a DAC marker */
+{
+ INT32 length;
+ int index, val;
+ INPUT_VARS(cinfo);
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+ length -= 2;
+
+ while (length > 0) {
+ INPUT_BYTE(cinfo, index, return FALSE);
+ INPUT_BYTE(cinfo, val, return FALSE);
+
+ length -= 2;
+
+ TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
+
+ if (index < 0 || index >= (2*NUM_ARITH_TBLS))
+ ERREXIT1(cinfo, JERR_DAC_INDEX, index);
+
+ if (index >= NUM_ARITH_TBLS) { /* define AC table */
+ cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
+ } else { /* define DC table */
+ cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
+ cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
+ if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
+ ERREXIT1(cinfo, JERR_DAC_VALUE, val);
+ }
+ }
+
+ INPUT_SYNC(cinfo);
+ return TRUE;
+}
+
+
+LOCAL boolean
+get_dht (j_decompress_ptr cinfo)
+/* Process a DHT marker */
+{
+ INT32 length;
+ UINT8 bits[17];
+ UINT8 huffval[256];
+ int i, index, count;
+ JHUFF_TBL **htblptr;
+ INPUT_VARS(cinfo);
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+ length -= 2;
+
+ while (length > 0) {
+ INPUT_BYTE(cinfo, index, return FALSE);
+
+ TRACEMS1(cinfo, 1, JTRC_DHT, index);
+
+ bits[0] = 0;
+ count = 0;
+ for (i = 1; i <= 16; i++) {
+ INPUT_BYTE(cinfo, bits[i], return FALSE);
+ count += bits[i];
+ }
+
+ length -= 1 + 16;
+
+ TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
+ bits[1], bits[2], bits[3], bits[4],
+ bits[5], bits[6], bits[7], bits[8]);
+ TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
+ bits[9], bits[10], bits[11], bits[12],
+ bits[13], bits[14], bits[15], bits[16]);
+
+ if (count > 256 || ((INT32) count) > length)
+ ERREXIT(cinfo, JERR_DHT_COUNTS);
+
+ for (i = 0; i < count; i++)
+ INPUT_BYTE(cinfo, huffval[i], return FALSE);
+
+ length -= count;
+
+ if (index & 0x10) { /* AC table definition */
+ index -= 0x10;
+ htblptr = &cinfo->ac_huff_tbl_ptrs[index];
+ } else { /* DC table definition */
+ htblptr = &cinfo->dc_huff_tbl_ptrs[index];
+ }
+
+ if (index < 0 || index >= NUM_HUFF_TBLS)
+ ERREXIT1(cinfo, JERR_DHT_INDEX, index);
+
+ if (*htblptr == NULL)
+ *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
+
+ MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
+ MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
+ }
+
+ INPUT_SYNC(cinfo);
+ return TRUE;
+}
+
+
+LOCAL boolean
+get_dqt (j_decompress_ptr cinfo)
+/* Process a DQT marker */
+{
+ INT32 length;
+ int n, i, prec;
+ unsigned int tmp;
+ JQUANT_TBL *quant_ptr;
+ INPUT_VARS(cinfo);
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+ length -= 2;
+
+ while (length > 0) {
+ INPUT_BYTE(cinfo, n, return FALSE);
+ prec = n >> 4;
+ n &= 0x0F;
+
+ TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
+
+ if (n >= NUM_QUANT_TBLS)
+ ERREXIT1(cinfo, JERR_DQT_INDEX, n);
+
+ if (cinfo->quant_tbl_ptrs[n] == NULL)
+ cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
+ quant_ptr = cinfo->quant_tbl_ptrs[n];
+
+ for (i = 0; i < DCTSIZE2; i++) {
+ if (prec)
+ INPUT_2BYTES(cinfo, tmp, return FALSE);
+ else
+ INPUT_BYTE(cinfo, tmp, return FALSE);
+ quant_ptr->quantval[i] = (UINT16) tmp;
+ }
+
+ for (i = 0; i < DCTSIZE2; i += 8) {
+ TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
+ quant_ptr->quantval[i ], quant_ptr->quantval[i+1],
+ quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
+ quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
+ quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
+ }
+
+ length -= DCTSIZE2+1;
+ if (prec) length -= DCTSIZE2;
+ }
+
+ INPUT_SYNC(cinfo);
+ return TRUE;
+}
+
+
+LOCAL boolean
+get_dri (j_decompress_ptr cinfo)
+/* Process a DRI marker */
+{
+ INT32 length;
+ unsigned int tmp;
+ INPUT_VARS(cinfo);
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+
+ if (length != 4)
+ ERREXIT(cinfo, JERR_BAD_LENGTH);
+
+ INPUT_2BYTES(cinfo, tmp, return FALSE);
+
+ TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
+
+ cinfo->restart_interval = tmp;
+
+ INPUT_SYNC(cinfo);
+ return TRUE;
+}
+
+
+METHODDEF boolean
+skip_variable (j_decompress_ptr cinfo)
+/* Skip over an unknown or uninteresting variable-length marker */
+{
+ INT32 length;
+ INPUT_VARS(cinfo);
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+
+ TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
+
+ INPUT_SYNC(cinfo); /* do before skip_input_data */
+ (*cinfo->src->skip_input_data) (cinfo, (long) length - 2L);
+
+ return TRUE;
+}
+
+
+/*
+ * Find the next JPEG marker, save it in cinfo->unread_marker.
+ * Returns FALSE if had to suspend before reaching a marker;
+ * in that case cinfo->unread_marker is unchanged.
+ *
+ * Note that the result might not be a valid marker code,
+ * but it will never be 0 or FF.
+ */
+
+LOCAL boolean
+next_marker (j_decompress_ptr cinfo)
+{
+ int c;
+ INPUT_VARS(cinfo);
+
+ for (;;) {
+ INPUT_BYTE(cinfo, c, return FALSE);
+ /* Skip any non-FF bytes.
+ * This may look a bit inefficient, but it will not occur in a valid file.
+ * We sync after each discarded byte so that a suspending data source
+ * can discard the byte from its buffer.
+ */
+ while (c != 0xFF) {
+ cinfo->marker->discarded_bytes++;
+ INPUT_SYNC(cinfo);
+ INPUT_BYTE(cinfo, c, return FALSE);
+ }
+ /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
+ * pad bytes, so don't count them in discarded_bytes. We assume there
+ * will not be so many consecutive FF bytes as to overflow a suspending
+ * data source's input buffer.
+ */
+ do {
+ INPUT_BYTE(cinfo, c, return FALSE);
+ } while (c == 0xFF);
+ if (c != 0)
+ break; /* found a valid marker, exit loop */
+ /* Reach here if we found a stuffed-zero data sequence (FF/00).
+ * Discard it and loop back to try again.
+ */
+ cinfo->marker->discarded_bytes += 2;
+ INPUT_SYNC(cinfo);
+ }
+
+ if (cinfo->marker->discarded_bytes != 0) {
+ WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
+ cinfo->marker->discarded_bytes = 0;
+ }
+
+ cinfo->unread_marker = c;
+
+ INPUT_SYNC(cinfo);
+ return TRUE;
+}
+
+
+LOCAL boolean
+first_marker (j_decompress_ptr cinfo)
+/* Like next_marker, but used to obtain the initial SOI marker. */
+/* For this marker, we do not allow preceding garbage or fill; otherwise,
+ * we might well scan an entire input file before realizing it ain't JPEG.
+ * If an application wants to process non-JFIF files, it must seek to the
+ * SOI before calling the JPEG library.
+ */
+{
+ int c, c2;
+ INPUT_VARS(cinfo);
+
+ INPUT_BYTE(cinfo, c, return FALSE);
+ INPUT_BYTE(cinfo, c2, return FALSE);
+ if (c != 0xFF || c2 != (int) M_SOI)
+ ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
+
+ cinfo->unread_marker = c2;
+
+ INPUT_SYNC(cinfo);
+ return TRUE;
+}
+
+
+/*
+ * Read markers until SOS or EOI.
+ *
+ * Returns same codes as are defined for jpeg_consume_input:
+ * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
+ */
+
+METHODDEF int
+read_markers (j_decompress_ptr cinfo)
+{
+ /* Outer loop repeats once for each marker. */
+ for (;;) {
+ /* Collect the marker proper, unless we already did. */
+ /* NB: first_marker() enforces the requirement that SOI appear first. */
+ if (cinfo->unread_marker == 0) {
+ if (! cinfo->marker->saw_SOI) {
+ if (! first_marker(cinfo))
+ return JPEG_SUSPENDED;
+ } else {
+ if (! next_marker(cinfo))
+ return JPEG_SUSPENDED;
+ }
+ }
+ /* At this point cinfo->unread_marker contains the marker code and the
+ * input point is just past the marker proper, but before any parameters.
+ * A suspension will cause us to return with this state still true.
+ */
+ switch (cinfo->unread_marker) {
+ case M_SOI:
+ if (! get_soi(cinfo))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_SOF0: /* Baseline */
+ case M_SOF1: /* Extended sequential, Huffman */
+ if (! get_sof(cinfo, FALSE, FALSE))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_SOF2: /* Progressive, Huffman */
+ if (! get_sof(cinfo, TRUE, FALSE))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_SOF9: /* Extended sequential, arithmetic */
+ if (! get_sof(cinfo, FALSE, TRUE))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_SOF10: /* Progressive, arithmetic */
+ if (! get_sof(cinfo, TRUE, TRUE))
+ return JPEG_SUSPENDED;
+ break;
+
+ /* Currently unsupported SOFn types */
+ case M_SOF3: /* Lossless, Huffman */
+ case M_SOF5: /* Differential sequential, Huffman */
+ case M_SOF6: /* Differential progressive, Huffman */
+ case M_SOF7: /* Differential lossless, Huffman */
+ case M_JPG: /* Reserved for JPEG extensions */
+ case M_SOF11: /* Lossless, arithmetic */
+ case M_SOF13: /* Differential sequential, arithmetic */
+ case M_SOF14: /* Differential progressive, arithmetic */
+ case M_SOF15: /* Differential lossless, arithmetic */
+ ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
+ break;
+
+ case M_SOS:
+ if (! get_sos(cinfo))
+ return JPEG_SUSPENDED;
+ cinfo->unread_marker = 0; /* processed the marker */
+ return JPEG_REACHED_SOS;
+
+ case M_EOI:
+ TRACEMS(cinfo, 1, JTRC_EOI);
+ cinfo->unread_marker = 0; /* processed the marker */
+ return JPEG_REACHED_EOI;
+
+ case M_DAC:
+ if (! get_dac(cinfo))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_DHT:
+ if (! get_dht(cinfo))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_DQT:
+ if (! get_dqt(cinfo))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_DRI:
+ if (! get_dri(cinfo))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_APP0:
+ case M_APP1:
+ case M_APP2:
+ case M_APP3:
+ case M_APP4:
+ case M_APP5:
+ case M_APP6:
+ case M_APP7:
+ case M_APP8:
+ case M_APP9:
+ case M_APP10:
+ case M_APP11:
+ case M_APP12:
+ case M_APP13:
+ case M_APP14:
+ case M_APP15:
+ if (! (*cinfo->marker->process_APPn[cinfo->unread_marker - (int) M_APP0]) (cinfo))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_COM:
+ if (! (*cinfo->marker->process_COM) (cinfo))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_RST0: /* these are all parameterless */
+ case M_RST1:
+ case M_RST2:
+ case M_RST3:
+ case M_RST4:
+ case M_RST5:
+ case M_RST6:
+ case M_RST7:
+ case M_TEM:
+ TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
+ break;
+
+ case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
+ if (! skip_variable(cinfo))
+ return JPEG_SUSPENDED;
+ break;
+
+ default: /* must be DHP, EXP, JPGn, or RESn */
+ /* For now, we treat the reserved markers as fatal errors since they are
+ * likely to be used to signal incompatible JPEG Part 3 extensions.
+ * Once the JPEG 3 version-number marker is well defined, this code
+ * ought to change!
+ */
+ ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
+ break;
+ }
+ /* Successfully processed marker, so reset state variable */
+ cinfo->unread_marker = 0;
+ } /* end loop */
+}
+
+
+/*
+ * Read a restart marker, which is expected to appear next in the datastream;
+ * if the marker is not there, take appropriate recovery action.
+ * Returns FALSE if suspension is required.
+ *
+ * This is called by the entropy decoder after it has read an appropriate
+ * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
+ * has already read a marker from the data source. Under normal conditions
+ * cinfo->unread_marker will be reset to 0 before returning; if not reset,
+ * it holds a marker which the decoder will be unable to read past.
+ */
+
+METHODDEF boolean
+read_restart_marker (j_decompress_ptr cinfo)
+{
+ /* Obtain a marker unless we already did. */
+ /* Note that next_marker will complain if it skips any data. */
+ if (cinfo->unread_marker == 0) {
+ if (! next_marker(cinfo))
+ return FALSE;
+ }
+
+ if (cinfo->unread_marker ==
+ ((int) M_RST0 + cinfo->marker->next_restart_num)) {
+ /* Normal case --- swallow the marker and let entropy decoder continue */
+ TRACEMS1(cinfo, 2, JTRC_RST, cinfo->marker->next_restart_num);
+ cinfo->unread_marker = 0;
+ } else {
+ /* Uh-oh, the restart markers have been messed up. */
+ /* Let the data source manager determine how to resync. */
+ if (! (*cinfo->src->resync_to_restart) (cinfo,
+ cinfo->marker->next_restart_num))
+ return FALSE;
+ }
+
+ /* Update next-restart state */
+ cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
+
+ return TRUE;
+}
+
+
+/*
+ * This is the default resync_to_restart method for data source managers
+ * to use if they don't have any better approach. Some data source managers
+ * may be able to back up, or may have additional knowledge about the data
+ * which permits a more intelligent recovery strategy; such managers would
+ * presumably supply their own resync method.
+ *
+ * read_restart_marker calls resync_to_restart if it finds a marker other than
+ * the restart marker it was expecting. (This code is *not* used unless
+ * a nonzero restart interval has been declared.) cinfo->unread_marker is
+ * the marker code actually found (might be anything, except 0 or FF).
+ * The desired restart marker number (0..7) is passed as a parameter.
+ * This routine is supposed to apply whatever error recovery strategy seems
+ * appropriate in order to position the input stream to the next data segment.
+ * Note that cinfo->unread_marker is treated as a marker appearing before
+ * the current data-source input point; usually it should be reset to zero
+ * before returning.
+ * Returns FALSE if suspension is required.
+ *
+ * This implementation is substantially constrained by wanting to treat the
+ * input as a data stream; this means we can't back up. Therefore, we have
+ * only the following actions to work with:
+ * 1. Simply discard the marker and let the entropy decoder resume at next
+ * byte of file.
+ * 2. Read forward until we find another marker, discarding intervening
+ * data. (In theory we could look ahead within the current bufferload,
+ * without having to discard data if we don't find the desired marker.
+ * This idea is not implemented here, in part because it makes behavior
+ * dependent on buffer size and chance buffer-boundary positions.)
+ * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
+ * This will cause the entropy decoder to process an empty data segment,
+ * inserting dummy zeroes, and then we will reprocess the marker.
+ *
+ * #2 is appropriate if we think the desired marker lies ahead, while #3 is
+ * appropriate if the found marker is a future restart marker (indicating
+ * that we have missed the desired restart marker, probably because it got
+ * corrupted).
+ * We apply #2 or #3 if the found marker is a restart marker no more than
+ * two counts behind or ahead of the expected one. We also apply #2 if the
+ * found marker is not a legal JPEG marker code (it's certainly bogus data).
+ * If the found marker is a restart marker more than 2 counts away, we do #1
+ * (too much risk that the marker is erroneous; with luck we will be able to
+ * resync at some future point).
+ * For any valid non-restart JPEG marker, we apply #3. This keeps us from
+ * overrunning the end of a scan. An implementation limited to single-scan
+ * files might find it better to apply #2 for markers other than EOI, since
+ * any other marker would have to be bogus data in that case.
+ */
+
+GLOBAL boolean
+jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
+{
+ int marker = cinfo->unread_marker;
+ int action = 1;
+
+ /* Always put up a warning. */
+ WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
+
+ /* Outer loop handles repeated decision after scanning forward. */
+ for (;;) {
+ if (marker < (int) M_SOF0)
+ action = 2; /* invalid marker */
+ else if (marker < (int) M_RST0 || marker > (int) M_RST7)
+ action = 3; /* valid non-restart marker */
+ else {
+ if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
+ marker == ((int) M_RST0 + ((desired+2) & 7)))
+ action = 3; /* one of the next two expected restarts */
+ else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
+ marker == ((int) M_RST0 + ((desired-2) & 7)))
+ action = 2; /* a prior restart, so advance */
+ else
+ action = 1; /* desired restart or too far away */
+ }
+ TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
+ switch (action) {
+ case 1:
+ /* Discard marker and let entropy decoder resume processing. */
+ cinfo->unread_marker = 0;
+ return TRUE;
+ case 2:
+ /* Scan to the next marker, and repeat the decision loop. */
+ if (! next_marker(cinfo))
+ return FALSE;
+ marker = cinfo->unread_marker;
+ break;
+ case 3:
+ /* Return without advancing past this marker. */
+ /* Entropy decoder will be forced to process an empty segment. */
+ return TRUE;
+ }
+ } /* end loop */
+}
+
+
+/*
+ * Reset marker processing state to begin a fresh datastream.
+ */
+
+METHODDEF void
+reset_marker_reader (j_decompress_ptr cinfo)
+{
+ cinfo->comp_info = NULL; /* until allocated by get_sof */
+ cinfo->input_scan_number = 0; /* no SOS seen yet */
+ cinfo->unread_marker = 0; /* no pending marker */
+ cinfo->marker->saw_SOI = FALSE; /* set internal state too */
+ cinfo->marker->saw_SOF = FALSE;
+ cinfo->marker->discarded_bytes = 0;
+}
+
+
+/*
+ * Initialize the marker reader module.
+ * This is called only once, when the decompression object is created.
+ */
+
+GLOBAL void
+jinit_marker_reader (j_decompress_ptr cinfo)
+{
+ int i;
+
+ /* Create subobject in permanent pool */
+ cinfo->marker = (struct jpeg_marker_reader *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ SIZEOF(struct jpeg_marker_reader));
+ /* Initialize method pointers */
+ cinfo->marker->reset_marker_reader = reset_marker_reader;
+ cinfo->marker->read_markers = read_markers;
+ cinfo->marker->read_restart_marker = read_restart_marker;
+ cinfo->marker->process_COM = skip_variable;
+ for (i = 0; i < 16; i++)
+ cinfo->marker->process_APPn[i] = skip_variable;
+ cinfo->marker->process_APPn[0] = get_app0;
+ cinfo->marker->process_APPn[14] = get_app14;
+ /* Reset marker processing state */
+ reset_marker_reader(cinfo);
+}
diff --git a/libs/jpeg6/jdmaster.cpp b/libs/jpeg6/jdmaster.cpp
new file mode 100755
index 0000000..64f730f
--- /dev/null
+++ b/libs/jpeg6/jdmaster.cpp
@@ -0,0 +1,557 @@
+/*
+ * jdmaster.c
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains master control logic for the JPEG decompressor.
+ * These routines are concerned with selecting the modules to be executed
+ * and with determining the number of passes and the work to be done in each
+ * pass.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Private state */
+
+typedef struct {
+ struct jpeg_decomp_master pub; /* public fields */
+
+ int pass_number; /* # of passes completed */
+
+ boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
+
+ /* Saved references to initialized quantizer modules,
+ * in case we need to switch modes.
+ */
+ struct jpeg_color_quantizer * quantizer_1pass;
+ struct jpeg_color_quantizer * quantizer_2pass;
+} my_decomp_master;
+
+typedef my_decomp_master * my_master_ptr;
+
+
+/*
+ * Determine whether merged upsample/color conversion should be used.
+ * CRUCIAL: this must match the actual capabilities of jdmerge.c!
+ */
+
+LOCAL boolean
+use_merged_upsample (j_decompress_ptr cinfo)
+{
+#ifdef UPSAMPLE_MERGING_SUPPORTED
+ /* Merging is the equivalent of plain box-filter upsampling */
+ if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
+ return FALSE;
+ /* jdmerge.c only supports YCC=>RGB color conversion */
+ if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
+ cinfo->out_color_space != JCS_RGB ||
+ cinfo->out_color_components != RGB_PIXELSIZE)
+ return FALSE;
+ /* and it only handles 2h1v or 2h2v sampling ratios */
+ if (cinfo->comp_info[0].h_samp_factor != 2 ||
+ cinfo->comp_info[1].h_samp_factor != 1 ||
+ cinfo->comp_info[2].h_samp_factor != 1 ||
+ cinfo->comp_info[0].v_samp_factor > 2 ||
+ cinfo->comp_info[1].v_samp_factor != 1 ||
+ cinfo->comp_info[2].v_samp_factor != 1)
+ return FALSE;
+ /* furthermore, it doesn't work if we've scaled the IDCTs differently */
+ if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
+ cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
+ cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
+ return FALSE;
+ /* ??? also need to test for upsample-time rescaling, when & if supported */
+ return TRUE; /* by golly, it'll work... */
+#else
+ return FALSE;
+#endif
+}
+
+
+/*
+ * Compute output image dimensions and related values.
+ * NOTE: this is exported for possible use by application.
+ * Hence it mustn't do anything that can't be done twice.
+ * Also note that it may be called before the master module is initialized!
+ */
+
+GLOBAL void
+jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
+/* Do computations that are needed before master selection phase */
+{
+#if 0 // JDC: commented out to remove warning
+ int ci;
+ jpeg_component_info *compptr;
+#endif
+
+ /* Prevent application from calling me at wrong times */
+ if (cinfo->global_state != DSTATE_READY)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+#ifdef IDCT_SCALING_SUPPORTED
+
+ /* Compute actual output image dimensions and DCT scaling choices. */
+ if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
+ /* Provide 1/8 scaling */
+ cinfo->output_width = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width, 8L);
+ cinfo->output_height = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height, 8L);
+ cinfo->min_DCT_scaled_size = 1;
+ } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
+ /* Provide 1/4 scaling */
+ cinfo->output_width = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width, 4L);
+ cinfo->output_height = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height, 4L);
+ cinfo->min_DCT_scaled_size = 2;
+ } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
+ /* Provide 1/2 scaling */
+ cinfo->output_width = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width, 2L);
+ cinfo->output_height = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height, 2L);
+ cinfo->min_DCT_scaled_size = 4;
+ } else {
+ /* Provide 1/1 scaling */
+ cinfo->output_width = cinfo->image_width;
+ cinfo->output_height = cinfo->image_height;
+ cinfo->min_DCT_scaled_size = DCTSIZE;
+ }
+ /* In selecting the actual DCT scaling for each component, we try to
+ * scale up the chroma components via IDCT scaling rather than upsampling.
+ * This saves time if the upsampler gets to use 1:1 scaling.
+ * Note this code assumes that the supported DCT scalings are powers of 2.
+ */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ int ssize = cinfo->min_DCT_scaled_size;
+ while (ssize < DCTSIZE &&
+ (compptr->h_samp_factor * ssize * 2 <=
+ cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
+ (compptr->v_samp_factor * ssize * 2 <=
+ cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
+ ssize = ssize * 2;
+ }
+ compptr->DCT_scaled_size = ssize;
+ }
+
+ /* Recompute downsampled dimensions of components;
+ * application needs to know these if using raw downsampled data.
+ */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Size in samples, after IDCT scaling */
+ compptr->downsampled_width = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width *
+ (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
+ (long) (cinfo->max_h_samp_factor * DCTSIZE));
+ compptr->downsampled_height = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height *
+ (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
+ (long) (cinfo->max_v_samp_factor * DCTSIZE));
+ }
+
+#else /* !IDCT_SCALING_SUPPORTED */
+
+ /* Hardwire it to "no scaling" */
+ cinfo->output_width = cinfo->image_width;
+ cinfo->output_height = cinfo->image_height;
+ /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
+ * and has computed unscaled downsampled_width and downsampled_height.
+ */
+
+#endif /* IDCT_SCALING_SUPPORTED */
+
+ /* Report number of components in selected colorspace. */
+ /* Probably this should be in the color conversion module... */
+ switch (cinfo->out_color_space) {
+ case JCS_GRAYSCALE:
+ cinfo->out_color_components = 1;
+ break;
+ case JCS_RGB:
+#if RGB_PIXELSIZE != 3
+ cinfo->out_color_components = RGB_PIXELSIZE;
+ break;
+#endif /* else share code with YCbCr */
+ case JCS_YCbCr:
+ cinfo->out_color_components = 3;
+ break;
+ case JCS_CMYK:
+ case JCS_YCCK:
+ cinfo->out_color_components = 4;
+ break;
+ default: /* else must be same colorspace as in file */
+ cinfo->out_color_components = cinfo->num_components;
+ break;
+ }
+ cinfo->output_components = (cinfo->quantize_colors ? 1 :
+ cinfo->out_color_components);
+
+ /* See if upsampler will want to emit more than one row at a time */
+ if (use_merged_upsample(cinfo))
+ cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
+ else
+ cinfo->rec_outbuf_height = 1;
+}
+
+
+/*
+ * Several decompression processes need to range-limit values to the range
+ * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
+ * due to noise introduced by quantization, roundoff error, etc. These
+ * processes are inner loops and need to be as fast as possible. On most
+ * machines, particularly CPUs with pipelines or instruction prefetch,
+ * a (subscript-check-less) C table lookup
+ * x = sample_range_limit[x];
+ * is faster than explicit tests
+ * if (x < 0) x = 0;
+ * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
+ * These processes all use a common table prepared by the routine below.
+ *
+ * For most steps we can mathematically guarantee that the initial value
+ * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
+ * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
+ * limiting step (just after the IDCT), a wildly out-of-range value is
+ * possible if the input data is corrupt. To avoid any chance of indexing
+ * off the end of memory and getting a bad-pointer trap, we perform the
+ * post-IDCT limiting thus:
+ * x = range_limit[x & MASK];
+ * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
+ * samples. Under normal circumstances this is more than enough range and
+ * a correct output will be generated; with bogus input data the mask will
+ * cause wraparound, and we will safely generate a bogus-but-in-range output.
+ * For the post-IDCT step, we want to convert the data from signed to unsigned
+ * representation by adding CENTERJSAMPLE at the same time that we limit it.
+ * So the post-IDCT limiting table ends up looking like this:
+ * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
+ * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
+ * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
+ * 0,1,...,CENTERJSAMPLE-1
+ * Negative inputs select values from the upper half of the table after
+ * masking.
+ *
+ * We can save some space by overlapping the start of the post-IDCT table
+ * with the simpler range limiting table. The post-IDCT table begins at
+ * sample_range_limit + CENTERJSAMPLE.
+ *
+ * Note that the table is allocated in near data space on PCs; it's small
+ * enough and used often enough to justify this.
+ */
+
+LOCAL void
+prepare_range_limit_table (j_decompress_ptr cinfo)
+/* Allocate and fill in the sample_range_limit table */
+{
+ JSAMPLE * table;
+ int i;
+
+ table = (JSAMPLE *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
+ table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
+ cinfo->sample_range_limit = table;
+ /* First segment of "simple" table: limit[x] = 0 for x < 0 */
+ MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
+ /* Main part of "simple" table: limit[x] = x */
+ for (i = 0; i <= MAXJSAMPLE; i++)
+ table[i] = (JSAMPLE) i;
+ table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
+ /* End of simple table, rest of first half of post-IDCT table */
+ for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
+ table[i] = MAXJSAMPLE;
+ /* Second half of post-IDCT table */
+ MEMZERO(table + (2 * (MAXJSAMPLE+1)),
+ (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
+ MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
+ cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
+}
+
+
+/*
+ * Master selection of decompression modules.
+ * This is done once at jpeg_start_decompress time. We determine
+ * which modules will be used and give them appropriate initialization calls.
+ * We also initialize the decompressor input side to begin consuming data.
+ *
+ * Since jpeg_read_header has finished, we know what is in the SOF
+ * and (first) SOS markers. We also have all the application parameter
+ * settings.
+ */
+
+LOCAL void
+master_selection (j_decompress_ptr cinfo)
+{
+ my_master_ptr master = (my_master_ptr) cinfo->master;
+ boolean use_c_buffer;
+ long samplesperrow;
+ JDIMENSION jd_samplesperrow;
+
+ /* Initialize dimensions and other stuff */
+ jpeg_calc_output_dimensions(cinfo);
+ prepare_range_limit_table(cinfo);
+
+ /* Width of an output scanline must be representable as JDIMENSION. */
+ samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
+ jd_samplesperrow = (JDIMENSION) samplesperrow;
+ if ((long) jd_samplesperrow != samplesperrow)
+ ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
+
+ /* Initialize my private state */
+ master->pass_number = 0;
+ master->using_merged_upsample = use_merged_upsample(cinfo);
+
+ /* Color quantizer selection */
+ master->quantizer_1pass = NULL;
+ master->quantizer_2pass = NULL;
+ /* No mode changes if not using buffered-image mode. */
+ if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
+ cinfo->enable_1pass_quant = FALSE;
+ cinfo->enable_external_quant = FALSE;
+ cinfo->enable_2pass_quant = FALSE;
+ }
+ if (cinfo->quantize_colors) {
+ if (cinfo->raw_data_out)
+ ERREXIT(cinfo, JERR_NOTIMPL);
+ /* 2-pass quantizer only works in 3-component color space. */
+ if (cinfo->out_color_components != 3) {
+ cinfo->enable_1pass_quant = TRUE;
+ cinfo->enable_external_quant = FALSE;
+ cinfo->enable_2pass_quant = FALSE;
+ cinfo->colormap = NULL;
+ } else if (cinfo->colormap != NULL) {
+ cinfo->enable_external_quant = TRUE;
+ } else if (cinfo->two_pass_quantize) {
+ cinfo->enable_2pass_quant = TRUE;
+ } else {
+ cinfo->enable_1pass_quant = TRUE;
+ }
+
+ if (cinfo->enable_1pass_quant) {
+#ifdef QUANT_1PASS_SUPPORTED
+ jinit_1pass_quantizer(cinfo);
+ master->quantizer_1pass = cinfo->cquantize;
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ }
+
+ /* We use the 2-pass code to map to external colormaps. */
+ if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
+#ifdef QUANT_2PASS_SUPPORTED
+ jinit_2pass_quantizer(cinfo);
+ master->quantizer_2pass = cinfo->cquantize;
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ }
+ /* If both quantizers are initialized, the 2-pass one is left active;
+ * this is necessary for starting with quantization to an external map.
+ */
+ }
+
+ /* Post-processing: in particular, color conversion first */
+ if (! cinfo->raw_data_out) {
+ if (master->using_merged_upsample) {
+#ifdef UPSAMPLE_MERGING_SUPPORTED
+ jinit_merged_upsampler(cinfo); /* does color conversion too */
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else {
+ jinit_color_deconverter(cinfo);
+ jinit_upsampler(cinfo);
+ }
+ jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
+ }
+ /* Inverse DCT */
+ jinit_inverse_dct(cinfo);
+ /* Entropy decoding: either Huffman or arithmetic coding. */
+ if (cinfo->arith_code) {
+ ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
+ } else {
+ if (cinfo->progressive_mode) {
+#ifdef D_PROGRESSIVE_SUPPORTED
+ jinit_phuff_decoder(cinfo);
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else
+ jinit_huff_decoder(cinfo);
+ }
+
+ /* Initialize principal buffer controllers. */
+ use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
+ jinit_d_coef_controller(cinfo, use_c_buffer);
+
+ if (! cinfo->raw_data_out)
+ jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
+
+ /* We can now tell the memory manager to allocate virtual arrays. */
+ (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
+
+ /* Initialize input side of decompressor to consume first scan. */
+ (*cinfo->inputctl->start_input_pass) (cinfo);
+
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+ /* If jpeg_start_decompress will read the whole file, initialize
+ * progress monitoring appropriately. The input step is counted
+ * as one pass.
+ */
+ if (cinfo->progress != NULL && ! cinfo->buffered_image &&
+ cinfo->inputctl->has_multiple_scans) {
+ int nscans;
+ /* Estimate number of scans to set pass_limit. */
+ if (cinfo->progressive_mode) {
+ /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
+ nscans = 2 + 3 * cinfo->num_components;
+ } else {
+ /* For a nonprogressive multiscan file, estimate 1 scan per component. */
+ nscans = cinfo->num_components;
+ }
+ cinfo->progress->pass_counter = 0L;
+ cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
+ cinfo->progress->completed_passes = 0;
+ cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
+ /* Count the input pass as done */
+ master->pass_number++;
+ }
+#endif /* D_MULTISCAN_FILES_SUPPORTED */
+}
+
+
+/*
+ * Per-pass setup.
+ * This is called at the beginning of each output pass. We determine which
+ * modules will be active during this pass and give them appropriate
+ * start_pass calls. We also set is_dummy_pass to indicate whether this
+ * is a "real" output pass or a dummy pass for color quantization.
+ * (In the latter case, jdapi.c will crank the pass to completion.)
+ */
+
+METHODDEF void
+prepare_for_output_pass (j_decompress_ptr cinfo)
+{
+ my_master_ptr master = (my_master_ptr) cinfo->master;
+
+ if (master->pub.is_dummy_pass) {
+#ifdef QUANT_2PASS_SUPPORTED
+ /* Final pass of 2-pass quantization */
+ master->pub.is_dummy_pass = FALSE;
+ (*cinfo->cquantize->start_pass) (cinfo, FALSE);
+ (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
+ (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif /* QUANT_2PASS_SUPPORTED */
+ } else {
+ if (cinfo->quantize_colors && cinfo->colormap == NULL) {
+ /* Select new quantization method */
+ if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
+ cinfo->cquantize = master->quantizer_2pass;
+ master->pub.is_dummy_pass = TRUE;
+ } else if (cinfo->enable_1pass_quant) {
+ cinfo->cquantize = master->quantizer_1pass;
+ } else {
+ ERREXIT(cinfo, JERR_MODE_CHANGE);
+ }
+ }
+ (*cinfo->idct->start_pass) (cinfo);
+ (*cinfo->coef->start_output_pass) (cinfo);
+ if (! cinfo->raw_data_out) {
+ if (! master->using_merged_upsample)
+ (*cinfo->cconvert->start_pass) (cinfo);
+ (*cinfo->upsample->start_pass) (cinfo);
+ if (cinfo->quantize_colors)
+ (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
+ (*cinfo->post->start_pass) (cinfo,
+ (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
+ (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
+ }
+ }
+
+ /* Set up progress monitor's pass info if present */
+ if (cinfo->progress != NULL) {
+ cinfo->progress->completed_passes = master->pass_number;
+ cinfo->progress->total_passes = master->pass_number +
+ (master->pub.is_dummy_pass ? 2 : 1);
+ /* In buffered-image mode, we assume one more output pass if EOI not
+ * yet reached, but no more passes if EOI has been reached.
+ */
+ if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
+ cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
+ }
+ }
+}
+
+
+/*
+ * Finish up at end of an output pass.
+ */
+
+METHODDEF void
+finish_output_pass (j_decompress_ptr cinfo)
+{
+ my_master_ptr master = (my_master_ptr) cinfo->master;
+
+ if (cinfo->quantize_colors)
+ (*cinfo->cquantize->finish_pass) (cinfo);
+ master->pass_number++;
+}
+
+
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+
+/*
+ * Switch to a new external colormap between output passes.
+ */
+
+GLOBAL void
+jpeg_new_colormap (j_decompress_ptr cinfo)
+{
+ my_master_ptr master = (my_master_ptr) cinfo->master;
+
+ /* Prevent application from calling me at wrong times */
+ if (cinfo->global_state != DSTATE_BUFIMAGE)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+ if (cinfo->quantize_colors && cinfo->enable_external_quant &&
+ cinfo->colormap != NULL) {
+ /* Select 2-pass quantizer for external colormap use */
+ cinfo->cquantize = master->quantizer_2pass;
+ /* Notify quantizer of colormap change */
+ (*cinfo->cquantize->new_color_map) (cinfo);
+ master->pub.is_dummy_pass = FALSE; /* just in case */
+ } else
+ ERREXIT(cinfo, JERR_MODE_CHANGE);
+}
+
+#endif /* D_MULTISCAN_FILES_SUPPORTED */
+
+
+/*
+ * Initialize master decompression control and select active modules.
+ * This is performed at the start of jpeg_start_decompress.
+ */
+
+GLOBAL void
+jinit_master_decompress (j_decompress_ptr cinfo)
+{
+ my_master_ptr master;
+
+ master = (my_master_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_decomp_master));
+ cinfo->master = (struct jpeg_decomp_master *) master;
+ master->pub.prepare_for_output_pass = prepare_for_output_pass;
+ master->pub.finish_output_pass = finish_output_pass;
+
+ master->pub.is_dummy_pass = FALSE;
+
+ master_selection(cinfo);
+}
diff --git a/libs/jpeg6/jdpostct.cpp b/libs/jpeg6/jdpostct.cpp
new file mode 100755
index 0000000..e3283b0
--- /dev/null
+++ b/libs/jpeg6/jdpostct.cpp
@@ -0,0 +1,290 @@
+/*
+ * jdpostct.c
+ *
+ * Copyright (C) 1994-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the decompression postprocessing controller.
+ * This controller manages the upsampling, color conversion, and color
+ * quantization/reduction steps; specifically, it controls the buffering
+ * between upsample/color conversion and color quantization/reduction.
+ *
+ * If no color quantization/reduction is required, then this module has no
+ * work to do, and it just hands off to the upsample/color conversion code.
+ * An integrated upsample/convert/quantize process would replace this module
+ * entirely.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Private buffer controller object */
+
+typedef struct {
+ struct jpeg_d_post_controller pub; /* public fields */
+
+ /* Color quantization source buffer: this holds output data from
+ * the upsample/color conversion step to be passed to the quantizer.
+ * For two-pass color quantization, we need a full-image buffer;
+ * for one-pass operation, a strip buffer is sufficient.
+ */
+ jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
+ JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
+ JDIMENSION strip_height; /* buffer size in rows */
+ /* for two-pass mode only: */
+ JDIMENSION starting_row; /* row # of first row in current strip */
+ JDIMENSION next_row; /* index of next row to fill/empty in strip */
+} my_post_controller;
+
+typedef my_post_controller * my_post_ptr;
+
+
+/* Forward declarations */
+METHODDEF void post_process_1pass
+ JPP((j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail));
+#ifdef QUANT_2PASS_SUPPORTED
+METHODDEF void post_process_prepass
+ JPP((j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail));
+METHODDEF void post_process_2pass
+ JPP((j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail));
+#endif
+
+
+/*
+ * Initialize for a processing pass.
+ */
+
+METHODDEF void
+start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
+{
+ my_post_ptr post = (my_post_ptr) cinfo->post;
+
+ switch (pass_mode) {
+ case JBUF_PASS_THRU:
+ if (cinfo->quantize_colors) {
+ /* Single-pass processing with color quantization. */
+ post->pub.post_process_data = post_process_1pass;
+ /* We could be doing buffered-image output before starting a 2-pass
+ * color quantization; in that case, jinit_d_post_controller did not
+ * allocate a strip buffer. Use the virtual-array buffer as workspace.
+ */
+ if (post->buffer == NULL) {
+ post->buffer = (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, post->whole_image,
+ (JDIMENSION) 0, post->strip_height, TRUE);
+ }
+ } else {
+ /* For single-pass processing without color quantization,
+ * I have no work to do; just call the upsampler directly.
+ */
+ post->pub.post_process_data = cinfo->upsample->upsample;
+ }
+ break;
+#ifdef QUANT_2PASS_SUPPORTED
+ case JBUF_SAVE_AND_PASS:
+ /* First pass of 2-pass quantization */
+ if (post->whole_image == NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ post->pub.post_process_data = post_process_prepass;
+ break;
+ case JBUF_CRANK_DEST:
+ /* Second pass of 2-pass quantization */
+ if (post->whole_image == NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ post->pub.post_process_data = post_process_2pass;
+ break;
+#endif /* QUANT_2PASS_SUPPORTED */
+ default:
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ break;
+ }
+ post->starting_row = post->next_row = 0;
+}
+
+
+/*
+ * Process some data in the one-pass (strip buffer) case.
+ * This is used for color precision reduction as well as one-pass quantization.
+ */
+
+METHODDEF void
+post_process_1pass (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+{
+ my_post_ptr post = (my_post_ptr) cinfo->post;
+ JDIMENSION num_rows, max_rows;
+
+ /* Fill the buffer, but not more than what we can dump out in one go. */
+ /* Note we rely on the upsampler to detect bottom of image. */
+ max_rows = out_rows_avail - *out_row_ctr;
+ if (max_rows > post->strip_height)
+ max_rows = post->strip_height;
+ num_rows = 0;
+ (*cinfo->upsample->upsample) (cinfo,
+ input_buf, in_row_group_ctr, in_row_groups_avail,
+ post->buffer, &num_rows, max_rows);
+ /* Quantize and emit data. */
+ (*cinfo->cquantize->color_quantize) (cinfo,
+ post->buffer, output_buf + *out_row_ctr, (int) num_rows);
+ *out_row_ctr += num_rows;
+}
+
+
+#ifdef QUANT_2PASS_SUPPORTED
+
+/*
+ * Process some data in the first pass of 2-pass quantization.
+ */
+
+METHODDEF void
+post_process_prepass (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+{
+ my_post_ptr post = (my_post_ptr) cinfo->post;
+ JDIMENSION old_next_row, num_rows;
+
+ /* Reposition virtual buffer if at start of strip. */
+ if (post->next_row == 0) {
+ post->buffer = (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, post->whole_image,
+ post->starting_row, post->strip_height, TRUE);
+ }
+
+ /* Upsample some data (up to a strip height's worth). */
+ old_next_row = post->next_row;
+ (*cinfo->upsample->upsample) (cinfo,
+ input_buf, in_row_group_ctr, in_row_groups_avail,
+ post->buffer, &post->next_row, post->strip_height);
+
+ /* Allow quantizer to scan new data. No data is emitted, */
+ /* but we advance out_row_ctr so outer loop can tell when we're done. */
+ if (post->next_row > old_next_row) {
+ num_rows = post->next_row - old_next_row;
+ (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
+ (JSAMPARRAY) NULL, (int) num_rows);
+ *out_row_ctr += num_rows;
+ }
+
+ /* Advance if we filled the strip. */
+ if (post->next_row >= post->strip_height) {
+ post->starting_row += post->strip_height;
+ post->next_row = 0;
+ }
+}
+
+
+/*
+ * Process some data in the second pass of 2-pass quantization.
+ */
+
+METHODDEF void
+post_process_2pass (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+{
+ my_post_ptr post = (my_post_ptr) cinfo->post;
+ JDIMENSION num_rows, max_rows;
+
+ /* Reposition virtual buffer if at start of strip. */
+ if (post->next_row == 0) {
+ post->buffer = (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, post->whole_image,
+ post->starting_row, post->strip_height, FALSE);
+ }
+
+ /* Determine number of rows to emit. */
+ num_rows = post->strip_height - post->next_row; /* available in strip */
+ max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
+ if (num_rows > max_rows)
+ num_rows = max_rows;
+ /* We have to check bottom of image here, can't depend on upsampler. */
+ max_rows = cinfo->output_height - post->starting_row;
+ if (num_rows > max_rows)
+ num_rows = max_rows;
+
+ /* Quantize and emit data. */
+ (*cinfo->cquantize->color_quantize) (cinfo,
+ post->buffer + post->next_row, output_buf + *out_row_ctr,
+ (int) num_rows);
+ *out_row_ctr += num_rows;
+
+ /* Advance if we filled the strip. */
+ post->next_row += num_rows;
+ if (post->next_row >= post->strip_height) {
+ post->starting_row += post->strip_height;
+ post->next_row = 0;
+ }
+}
+
+#endif /* QUANT_2PASS_SUPPORTED */
+
+
+/*
+ * Initialize postprocessing controller.
+ */
+
+GLOBAL void
+jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
+{
+ my_post_ptr post;
+
+ post = (my_post_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_post_controller));
+ cinfo->post = (struct jpeg_d_post_controller *) post;
+ post->pub.start_pass = start_pass_dpost;
+ post->whole_image = NULL; /* flag for no virtual arrays */
+ post->buffer = NULL; /* flag for no strip buffer */
+
+ /* Create the quantization buffer, if needed */
+ if (cinfo->quantize_colors) {
+ /* The buffer strip height is max_v_samp_factor, which is typically
+ * an efficient number of rows for upsampling to return.
+ * (In the presence of output rescaling, we might want to be smarter?)
+ */
+ post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
+ if (need_full_buffer) {
+ /* Two-pass color quantization: need full-image storage. */
+ /* We round up the number of rows to a multiple of the strip height. */
+#ifdef QUANT_2PASS_SUPPORTED
+ post->whole_image = (*cinfo->mem->request_virt_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+ cinfo->output_width * cinfo->out_color_components,
+ (JDIMENSION) jround_up((long) cinfo->output_height,
+ (long) post->strip_height),
+ post->strip_height);
+#else
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+#endif /* QUANT_2PASS_SUPPORTED */
+ } else {
+ /* One-pass color quantization: just make a strip buffer. */
+ post->buffer = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ cinfo->output_width * cinfo->out_color_components,
+ post->strip_height);
+ }
+ }
+}
diff --git a/libs/jpeg6/jdsample.cpp b/libs/jpeg6/jdsample.cpp
new file mode 100755
index 0000000..bc171f4
--- /dev/null
+++ b/libs/jpeg6/jdsample.cpp
@@ -0,0 +1,478 @@
+/*
+ * jdsample.c
+ *
+ * Copyright (C) 1991-1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains upsampling routines.
+ *
+ * Upsampling input data is counted in "row groups". A row group
+ * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
+ * sample rows of each component. Upsampling will normally produce
+ * max_v_samp_factor pixel rows from each row group (but this could vary
+ * if the upsampler is applying a scale factor of its own).
+ *
+ * An excellent reference for image resampling is
+ * Digital Image Warping, George Wolberg, 1990.
+ * Pub. by IEEE Computer Society Press, Los Alamitos, CA. ISBN 0-8186-8944-7.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Pointer to routine to upsample a single component */
+typedef JMETHOD(void, upsample1_ptr,
+ (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
+
+/* Private subobject */
+
+typedef struct {
+ struct jpeg_upsampler pub; /* public fields */
+
+ /* Color conversion buffer. When using separate upsampling and color
+ * conversion steps, this buffer holds one upsampled row group until it
+ * has been color converted and output.
+ * Note: we do not allocate any storage for component(s) which are full-size,
+ * ie do not need rescaling. The corresponding entry of color_buf[] is
+ * simply set to point to the input data array, thereby avoiding copying.
+ */
+ JSAMPARRAY color_buf[MAX_COMPONENTS];
+
+ /* Per-component upsampling method pointers */
+ upsample1_ptr methods[MAX_COMPONENTS];
+
+ int next_row_out; /* counts rows emitted from color_buf */
+ JDIMENSION rows_to_go; /* counts rows remaining in image */
+
+ /* Height of an input row group for each component. */
+ int rowgroup_height[MAX_COMPONENTS];
+
+ /* These arrays save pixel expansion factors so that int_expand need not
+ * recompute them each time. They are unused for other upsampling methods.
+ */
+ UINT8 h_expand[MAX_COMPONENTS];
+ UINT8 v_expand[MAX_COMPONENTS];
+} my_upsampler;
+
+typedef my_upsampler * my_upsample_ptr;
+
+
+/*
+ * Initialize for an upsampling pass.
+ */
+
+METHODDEF void
+start_pass_upsample (j_decompress_ptr cinfo)
+{
+ my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
+
+ /* Mark the conversion buffer empty */
+ upsample->next_row_out = cinfo->max_v_samp_factor;
+ /* Initialize total-height counter for detecting bottom of image */
+ upsample->rows_to_go = cinfo->output_height;
+}
+
+
+/*
+ * Control routine to do upsampling (and color conversion).
+ *
+ * In this version we upsample each component independently.
+ * We upsample one row group into the conversion buffer, then apply
+ * color conversion a row at a time.
+ */
+
+METHODDEF void
+sep_upsample (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+{
+ my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
+ int ci;
+ jpeg_component_info * compptr;
+ JDIMENSION num_rows;
+
+ /* Fill the conversion buffer, if it's empty */
+ if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Invoke per-component upsample method. Notice we pass a POINTER
+ * to color_buf[ci], so that fullsize_upsample can change it.
+ */
+ (*upsample->methods[ci]) (cinfo, compptr,
+ input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
+ upsample->color_buf + ci);
+ }
+ upsample->next_row_out = 0;
+ }
+
+ /* Color-convert and emit rows */
+
+ /* How many we have in the buffer: */
+ num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
+ /* Not more than the distance to the end of the image. Need this test
+ * in case the image height is not a multiple of max_v_samp_factor:
+ */
+ if (num_rows > upsample->rows_to_go)
+ num_rows = upsample->rows_to_go;
+ /* And not more than what the client can accept: */
+ out_rows_avail -= *out_row_ctr;
+ if (num_rows > out_rows_avail)
+ num_rows = out_rows_avail;
+
+ (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
+ (JDIMENSION) upsample->next_row_out,
+ output_buf + *out_row_ctr,
+ (int) num_rows);
+
+ /* Adjust counts */
+ *out_row_ctr += num_rows;
+ upsample->rows_to_go -= num_rows;
+ upsample->next_row_out += num_rows;
+ /* When the buffer is emptied, declare this input row group consumed */
+ if (upsample->next_row_out >= cinfo->max_v_samp_factor)
+ (*in_row_group_ctr)++;
+}
+
+
+/*
+ * These are the routines invoked by sep_upsample to upsample pixel values
+ * of a single component. One row group is processed per call.
+ */
+
+
+/*
+ * For full-size components, we just make color_buf[ci] point at the
+ * input buffer, and thus avoid copying any data. Note that this is
+ * safe only because sep_upsample doesn't declare the input row group
+ * "consumed" until we are done color converting and emitting it.
+ */
+
+METHODDEF void
+fullsize_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
+{
+ *output_data_ptr = input_data;
+}
+
+
+/*
+ * This is a no-op version used for "uninteresting" components.
+ * These components will not be referenced by color conversion.
+ */
+
+METHODDEF void
+noop_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
+{
+ *output_data_ptr = NULL; /* safety check */
+}
+
+
+/*
+ * This version handles any integral sampling ratios.
+ * This is not used for typical JPEG files, so it need not be fast.
+ * Nor, for that matter, is it particularly accurate: the algorithm is
+ * simple replication of the input pixel onto the corresponding output
+ * pixels. The hi-falutin sampling literature refers to this as a
+ * "box filter". A box filter tends to introduce visible artifacts,
+ * so if you are actually going to use 3:1 or 4:1 sampling ratios
+ * you would be well advised to improve this code.
+ */
+
+METHODDEF void
+int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
+{
+ my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
+ JSAMPARRAY output_data = *output_data_ptr;
+ register JSAMPROW inptr, outptr;
+ register JSAMPLE invalue;
+ register int h;
+ JSAMPROW outend;
+ int h_expand, v_expand;
+ int inrow, outrow;
+
+ h_expand = upsample->h_expand[compptr->component_index];
+ v_expand = upsample->v_expand[compptr->component_index];
+
+ inrow = outrow = 0;
+ while (outrow < cinfo->max_v_samp_factor) {
+ /* Generate one output row with proper horizontal expansion */
+ inptr = input_data[inrow];
+ outptr = output_data[outrow];
+ outend = outptr + cinfo->output_width;
+ while (outptr < outend) {
+ invalue = *inptr++; /* don't need GETJSAMPLE() here */
+ for (h = h_expand; h > 0; h--) {
+ *outptr++ = invalue;
+ }
+ }
+ /* Generate any additional output rows by duplicating the first one */
+ if (v_expand > 1) {
+ jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
+ v_expand-1, cinfo->output_width);
+ }
+ inrow++;
+ outrow += v_expand;
+ }
+}
+
+
+/*
+ * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
+ * It's still a box filter.
+ */
+
+METHODDEF void
+h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
+{
+ JSAMPARRAY output_data = *output_data_ptr;
+ register JSAMPROW inptr, outptr;
+ register JSAMPLE invalue;
+ JSAMPROW outend;
+ int inrow;
+
+ for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
+ inptr = input_data[inrow];
+ outptr = output_data[inrow];
+ outend = outptr + cinfo->output_width;
+ while (outptr < outend) {
+ invalue = *inptr++; /* don't need GETJSAMPLE() here */
+ *outptr++ = invalue;
+ *outptr++ = invalue;
+ }
+ }
+}
+
+
+/*
+ * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
+ * It's still a box filter.
+ */
+
+METHODDEF void
+h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
+{
+ JSAMPARRAY output_data = *output_data_ptr;
+ register JSAMPROW inptr, outptr;
+ register JSAMPLE invalue;
+ JSAMPROW outend;
+ int inrow, outrow;
+
+ inrow = outrow = 0;
+ while (outrow < cinfo->max_v_samp_factor) {
+ inptr = input_data[inrow];
+ outptr = output_data[outrow];
+ outend = outptr + cinfo->output_width;
+ while (outptr < outend) {
+ invalue = *inptr++; /* don't need GETJSAMPLE() here */
+ *outptr++ = invalue;
+ *outptr++ = invalue;
+ }
+ jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
+ 1, cinfo->output_width);
+ inrow++;
+ outrow += 2;
+ }
+}
+
+
+/*
+ * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
+ *
+ * The upsampling algorithm is linear interpolation between pixel centers,
+ * also known as a "triangle filter". This is a good compromise between
+ * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
+ * of the way between input pixel centers.
+ *
+ * A note about the "bias" calculations: when rounding fractional values to
+ * integer, we do not want to always round 0.5 up to the next integer.
+ * If we did that, we'd introduce a noticeable bias towards larger values.
+ * Instead, this code is arranged so that 0.5 will be rounded up or down at
+ * alternate pixel locations (a simple ordered dither pattern).
+ */
+
+METHODDEF void
+h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
+{
+ JSAMPARRAY output_data = *output_data_ptr;
+ register JSAMPROW inptr, outptr;
+ register int invalue;
+ register JDIMENSION colctr;
+ int inrow;
+
+ for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
+ inptr = input_data[inrow];
+ outptr = output_data[inrow];
+ /* Special case for first column */
+ invalue = GETJSAMPLE(*inptr++);
+ *outptr++ = (JSAMPLE) invalue;
+ *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
+
+ for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
+ /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
+ invalue = GETJSAMPLE(*inptr++) * 3;
+ *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
+ *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
+ }
+
+ /* Special case for last column */
+ invalue = GETJSAMPLE(*inptr);
+ *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
+ *outptr++ = (JSAMPLE) invalue;
+ }
+}
+
+
+/*
+ * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
+ * Again a triangle filter; see comments for h2v1 case, above.
+ *
+ * It is OK for us to reference the adjacent input rows because we demanded
+ * context from the main buffer controller (see initialization code).
+ */
+
+METHODDEF void
+h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
+{
+ JSAMPARRAY output_data = *output_data_ptr;
+ register JSAMPROW inptr0, inptr1, outptr;
+#if BITS_IN_JSAMPLE == 8
+ register int thiscolsum, lastcolsum, nextcolsum;
+#else
+ register INT32 thiscolsum, lastcolsum, nextcolsum;
+#endif
+ register JDIMENSION colctr;
+ int inrow, outrow, v;
+
+ inrow = outrow = 0;
+ while (outrow < cinfo->max_v_samp_factor) {
+ for (v = 0; v < 2; v++) {
+ /* inptr0 points to nearest input row, inptr1 points to next nearest */
+ inptr0 = input_data[inrow];
+ if (v == 0) /* next nearest is row above */
+ inptr1 = input_data[inrow-1];
+ else /* next nearest is row below */
+ inptr1 = input_data[inrow+1];
+ outptr = output_data[outrow++];
+
+ /* Special case for first column */
+ thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
+ nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
+ *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
+ *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
+ lastcolsum = thiscolsum; thiscolsum = nextcolsum;
+
+ for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
+ /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
+ /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
+ nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
+ *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
+ *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
+ lastcolsum = thiscolsum; thiscolsum = nextcolsum;
+ }
+
+ /* Special case for last column */
+ *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
+ *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
+ }
+ inrow++;
+ }
+}
+
+
+/*
+ * Module initialization routine for upsampling.
+ */
+
+GLOBAL void
+jinit_upsampler (j_decompress_ptr cinfo)
+{
+ my_upsample_ptr upsample;
+ int ci;
+ jpeg_component_info * compptr;
+ boolean need_buffer, do_fancy;
+ int h_in_group, v_in_group, h_out_group, v_out_group;
+
+ upsample = (my_upsample_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_upsampler));
+ cinfo->upsample = (struct jpeg_upsampler *) upsample;
+ upsample->pub.start_pass = start_pass_upsample;
+ upsample->pub.upsample = sep_upsample;
+ upsample->pub.need_context_rows = FALSE; /* until we find out differently */
+
+ if (cinfo->CCIR601_sampling) /* this isn't supported */
+ ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
+
+ /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
+ * so don't ask for it.
+ */
+ do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
+
+ /* Verify we can handle the sampling factors, select per-component methods,
+ * and create storage as needed.
+ */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Compute size of an "input group" after IDCT scaling. This many samples
+ * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
+ */
+ h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
+ cinfo->min_DCT_scaled_size;
+ v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
+ cinfo->min_DCT_scaled_size;
+ h_out_group = cinfo->max_h_samp_factor;
+ v_out_group = cinfo->max_v_samp_factor;
+ upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
+ need_buffer = TRUE;
+ if (! compptr->component_needed) {
+ /* Don't bother to upsample an uninteresting component. */
+ upsample->methods[ci] = noop_upsample;
+ need_buffer = FALSE;
+ } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
+ /* Fullsize components can be processed without any work. */
+ upsample->methods[ci] = fullsize_upsample;
+ need_buffer = FALSE;
+ } else if (h_in_group * 2 == h_out_group &&
+ v_in_group == v_out_group) {
+ /* Special cases for 2h1v upsampling */
+ if (do_fancy && compptr->downsampled_width > 2)
+ upsample->methods[ci] = h2v1_fancy_upsample;
+ else
+ upsample->methods[ci] = h2v1_upsample;
+ } else if (h_in_group * 2 == h_out_group &&
+ v_in_group * 2 == v_out_group) {
+ /* Special cases for 2h2v upsampling */
+ if (do_fancy && compptr->downsampled_width > 2) {
+ upsample->methods[ci] = h2v2_fancy_upsample;
+ upsample->pub.need_context_rows = TRUE;
+ } else
+ upsample->methods[ci] = h2v2_upsample;
+ } else if ((h_out_group % h_in_group) == 0 &&
+ (v_out_group % v_in_group) == 0) {
+ /* Generic integral-factors upsampling method */
+ upsample->methods[ci] = int_upsample;
+ upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
+ upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
+ } else
+ ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
+ if (need_buffer) {
+ upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) jround_up((long) cinfo->output_width,
+ (long) cinfo->max_h_samp_factor),
+ (JDIMENSION) cinfo->max_v_samp_factor);
+ }
+ }
+}
diff --git a/libs/jpeg6/jdtrans.cpp b/libs/jpeg6/jdtrans.cpp
new file mode 100755
index 0000000..eb873e0
--- /dev/null
+++ b/libs/jpeg6/jdtrans.cpp
@@ -0,0 +1,122 @@
+/*
+ * jdtrans.c
+ *
+ * Copyright (C) 1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains library routines for transcoding decompression,
+ * that is, reading raw DCT coefficient arrays from an input JPEG file.
+ * The routines in jdapimin.c will also be needed by a transcoder.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Forward declarations */
+LOCAL void transdecode_master_selection JPP((j_decompress_ptr cinfo));
+
+
+/*
+ * Read the coefficient arrays from a JPEG file.
+ * jpeg_read_header must be completed before calling this.
+ *
+ * The entire image is read into a set of virtual coefficient-block arrays,
+ * one per component. The return value is a pointer to the array of
+ * virtual-array descriptors. These can be manipulated directly via the
+ * JPEG memory manager, or handed off to jpeg_write_coefficients().
+ * To release the memory occupied by the virtual arrays, call
+ * jpeg_finish_decompress() when done with the data.
+ *
+ * Returns NULL if suspended. This case need be checked only if
+ * a suspending data source is used.
+ */
+
+GLOBAL jvirt_barray_ptr *
+jpeg_read_coefficients (j_decompress_ptr cinfo)
+{
+ if (cinfo->global_state == DSTATE_READY) {
+ /* First call: initialize active modules */
+ transdecode_master_selection(cinfo);
+ cinfo->global_state = DSTATE_RDCOEFS;
+ } else if (cinfo->global_state != DSTATE_RDCOEFS)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ /* Absorb whole file into the coef buffer */
+ for (;;) {
+ int retcode;
+ /* Call progress monitor hook if present */
+ if (cinfo->progress != NULL)
+ (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+ /* Absorb some more input */
+ retcode = (*cinfo->inputctl->consume_input) (cinfo);
+ if (retcode == JPEG_SUSPENDED)
+ return NULL;
+ if (retcode == JPEG_REACHED_EOI)
+ break;
+ /* Advance progress counter if appropriate */
+ if (cinfo->progress != NULL &&
+ (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
+ if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
+ /* startup underestimated number of scans; ratchet up one scan */
+ cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
+ }
+ }
+ }
+ /* Set state so that jpeg_finish_decompress does the right thing */
+ cinfo->global_state = DSTATE_STOPPING;
+ return cinfo->coef->coef_arrays;
+}
+
+
+/*
+ * Master selection of decompression modules for transcoding.
+ * This substitutes for jdmaster.c's initialization of the full decompressor.
+ */
+
+LOCAL void
+transdecode_master_selection (j_decompress_ptr cinfo)
+{
+ /* Entropy decoding: either Huffman or arithmetic coding. */
+ if (cinfo->arith_code) {
+ ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
+ } else {
+ if (cinfo->progressive_mode) {
+#ifdef D_PROGRESSIVE_SUPPORTED
+ jinit_phuff_decoder(cinfo);
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else
+ jinit_huff_decoder(cinfo);
+ }
+
+ /* Always get a full-image coefficient buffer. */
+ jinit_d_coef_controller(cinfo, TRUE);
+
+ /* We can now tell the memory manager to allocate virtual arrays. */
+ (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
+
+ /* Initialize input side of decompressor to consume first scan. */
+ (*cinfo->inputctl->start_input_pass) (cinfo);
+
+ /* Initialize progress monitoring. */
+ if (cinfo->progress != NULL) {
+ int nscans;
+ /* Estimate number of scans to set pass_limit. */
+ if (cinfo->progressive_mode) {
+ /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
+ nscans = 2 + 3 * cinfo->num_components;
+ } else if (cinfo->inputctl->has_multiple_scans) {
+ /* For a nonprogressive multiscan file, estimate 1 scan per component. */
+ nscans = cinfo->num_components;
+ } else {
+ nscans = 1;
+ }
+ cinfo->progress->pass_counter = 0L;
+ cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
+ cinfo->progress->completed_passes = 0;
+ cinfo->progress->total_passes = 1;
+ }
+}
diff --git a/libs/jpeg6/jerror.cpp b/libs/jpeg6/jerror.cpp
new file mode 100755
index 0000000..09027d8
--- /dev/null
+++ b/libs/jpeg6/jerror.cpp
@@ -0,0 +1,231 @@
+/*
+ * jerror.c
+ *
+ * Copyright (C) 1991-1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains simple error-reporting and trace-message routines.
+ * These are suitable for Unix-like systems and others where writing to
+ * stderr is the right thing to do. Many applications will want to replace
+ * some or all of these routines.
+ *
+ * These routines are used by both the compression and decompression code.
+ */
+
+/* this is not a core library module, so it doesn't define JPEG_INTERNALS */
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jversion.h"
+#include "jerror.h"
+
+#ifndef EXIT_FAILURE /* define exit() codes if not provided */
+#define EXIT_FAILURE 1
+#endif
+
+
+/*
+ * Create the message string table.
+ * We do this from the master message list in jerror.h by re-reading
+ * jerror.h with a suitable definition for macro JMESSAGE.
+ * The message table is made an external symbol just in case any applications
+ * want to refer to it directly.
+ */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jpeg_std_message_table jMsgTable
+#endif
+
+#define JMESSAGE(code,string) string ,
+
+const char * const jpeg_std_message_table[] = {
+#include "jerror.h"
+ NULL
+};
+
+
+/*
+ * Error exit handler: must not return to caller.
+ *
+ * Applications may override this if they want to get control back after
+ * an error. Typically one would longjmp somewhere instead of exiting.
+ * The setjmp buffer can be made a private field within an expanded error
+ * handler object. Note that the info needed to generate an error message
+ * is stored in the error object, so you can generate the message now or
+ * later, at your convenience.
+ * You should make sure that the JPEG object is cleaned up (with jpeg_abort
+ * or jpeg_destroy) at some point.
+ */
+
+METHODDEF void
+error_exit (j_common_ptr cinfo)
+{
+ char buffer[JMSG_LENGTH_MAX];
+
+ /* Create the message */
+ (*cinfo->err->format_message) (cinfo, buffer);
+
+ /* Let the memory manager delete any temp files before we die */
+ jpeg_destroy(cinfo);
+
+ // FIXME: need to get this setup with an error handler
+ //Error("%s\n", buffer );
+}
+
+
+/*
+ * Actual output of an error or trace message.
+ * Applications may override this method to send JPEG messages somewhere
+ * other than stderr.
+ */
+
+METHODDEF void
+output_message (j_common_ptr cinfo)
+{
+ char buffer[JMSG_LENGTH_MAX];
+
+ /* Create the message */
+ (*cinfo->err->format_message) (cinfo, buffer);
+
+ /* Send it to stderr, adding a newline */
+ printf("%s\n", buffer);
+}
+
+
+/*
+ * Decide whether to emit a trace or warning message.
+ * msg_level is one of:
+ * -1: recoverable corrupt-data warning, may want to abort.
+ * 0: important advisory messages (always display to user).
+ * 1: first level of tracing detail.
+ * 2,3,...: successively more detailed tracing messages.
+ * An application might override this method if it wanted to abort on warnings
+ * or change the policy about which messages to display.
+ */
+
+METHODDEF void
+emit_message (j_common_ptr cinfo, int msg_level)
+{
+ struct jpeg_error_mgr * err = cinfo->err;
+
+ if (msg_level < 0) {
+ /* It's a warning message. Since corrupt files may generate many warnings,
+ * the policy implemented here is to show only the first warning,
+ * unless trace_level >= 3.
+ */
+ if (err->num_warnings == 0 || err->trace_level >= 3)
+ (*err->output_message) (cinfo);
+ /* Always count warnings in num_warnings. */
+ err->num_warnings++;
+ } else {
+ /* It's a trace message. Show it if trace_level >= msg_level. */
+ if (err->trace_level >= msg_level)
+ (*err->output_message) (cinfo);
+ }
+}
+
+
+/*
+ * Format a message string for the most recent JPEG error or message.
+ * The message is stored into buffer, which should be at least JMSG_LENGTH_MAX
+ * characters. Note that no '\n' character is added to the string.
+ * Few applications should need to override this method.
+ */
+
+METHODDEF void
+format_message (j_common_ptr cinfo, char * buffer)
+{
+ struct jpeg_error_mgr * err = cinfo->err;
+ int msg_code = err->msg_code;
+ const char * msgtext = NULL;
+ const char * msgptr;
+ char ch;
+ boolean isstring;
+
+ /* Look up message string in proper table */
+ if (msg_code > 0 && msg_code <= err->last_jpeg_message) {
+ msgtext = err->jpeg_message_table[msg_code];
+ } else if (err->addon_message_table != NULL &&
+ msg_code >= err->first_addon_message &&
+ msg_code <= err->last_addon_message) {
+ msgtext = err->addon_message_table[msg_code - err->first_addon_message];
+ }
+
+ /* Defend against bogus message number */
+ if (msgtext == NULL) {
+ err->msg_parm.i[0] = msg_code;
+ msgtext = err->jpeg_message_table[0];
+ }
+
+ /* Check for string parameter, as indicated by %s in the message text */
+ isstring = FALSE;
+ msgptr = msgtext;
+ while ((ch = *msgptr++) != '\0') {
+ if (ch == '%') {
+ if (*msgptr == 's') isstring = TRUE;
+ break;
+ }
+ }
+
+ /* Format the message into the passed buffer */
+ if (isstring)
+ sprintf(buffer, msgtext, err->msg_parm.s);
+ else
+ sprintf(buffer, msgtext,
+ err->msg_parm.i[0], err->msg_parm.i[1],
+ err->msg_parm.i[2], err->msg_parm.i[3],
+ err->msg_parm.i[4], err->msg_parm.i[5],
+ err->msg_parm.i[6], err->msg_parm.i[7]);
+}
+
+
+/*
+ * Reset error state variables at start of a new image.
+ * This is called during compression startup to reset trace/error
+ * processing to default state, without losing any application-specific
+ * method pointers. An application might possibly want to override
+ * this method if it has additional error processing state.
+ */
+
+METHODDEF void
+reset_error_mgr (j_common_ptr cinfo)
+{
+ cinfo->err->num_warnings = 0;
+ /* trace_level is not reset since it is an application-supplied parameter */
+ cinfo->err->msg_code = 0; /* may be useful as a flag for "no error" */
+}
+
+
+/*
+ * Fill in the standard error-handling methods in a jpeg_error_mgr object.
+ * Typical call is:
+ * struct jpeg_compress_struct cinfo;
+ * struct jpeg_error_mgr err;
+ *
+ * cinfo.err = jpeg_std_error(&err);
+ * after which the application may override some of the methods.
+ */
+
+GLOBAL struct jpeg_error_mgr *
+jpeg_std_error (struct jpeg_error_mgr * err)
+{
+ err->error_exit = error_exit;
+ err->emit_message = emit_message;
+ err->output_message = output_message;
+ err->format_message = format_message;
+ err->reset_error_mgr = reset_error_mgr;
+
+ err->trace_level = 0; /* default = no tracing */
+ err->num_warnings = 0; /* no warnings emitted yet */
+ err->msg_code = 0; /* may be useful as a flag for "no error" */
+
+ /* Initialize message table pointers */
+ err->jpeg_message_table = jpeg_std_message_table;
+ err->last_jpeg_message = (int) JMSG_LASTMSGCODE - 1;
+
+ err->addon_message_table = NULL;
+ err->first_addon_message = 0; /* for safety */
+ err->last_addon_message = 0;
+
+ return err;
+}
diff --git a/libs/jpeg6/jerror.h b/libs/jpeg6/jerror.h
new file mode 100755
index 0000000..0ffb8b4
--- /dev/null
+++ b/libs/jpeg6/jerror.h
@@ -0,0 +1,273 @@
+/*
+ * jerror.h
+ *
+ * Copyright (C) 1994-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file defines the error and message codes for the JPEG library.
+ * Edit this file to add new codes, or to translate the message strings to
+ * some other language.
+ * A set of error-reporting macros are defined too. Some applications using
+ * the JPEG library may wish to include this file to get the error codes
+ * and/or the macros.
+ */
+
+/*
+ * To define the enum list of message codes, include this file without
+ * defining macro JMESSAGE. To create a message string table, include it
+ * again with a suitable JMESSAGE definition (see jerror.c for an example).
+ */
+#ifndef JMESSAGE
+#ifndef JERROR_H
+/* First time through, define the enum list */
+#define JMAKE_ENUM_LIST
+#else
+/* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
+#define JMESSAGE(code,string)
+#endif /* JERROR_H */
+#endif /* JMESSAGE */
+
+#ifdef JMAKE_ENUM_LIST
+
+typedef enum {
+
+#define JMESSAGE(code,string) code ,
+
+#endif /* JMAKE_ENUM_LIST */
+
+JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
+
+/* For maintenance convenience, list is alphabetical by message code name */
+JMESSAGE(JERR_ARITH_NOTIMPL,
+ "Sorry, there are legal restrictions on arithmetic coding")
+JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
+JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
+JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
+JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
+JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
+JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
+JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
+JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
+JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
+JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
+JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
+JMESSAGE(JERR_BAD_PROGRESSION,
+ "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
+JMESSAGE(JERR_BAD_PROG_SCRIPT,
+ "Invalid progressive parameters at scan script entry %d")
+JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
+JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
+JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
+JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
+JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
+JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
+JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
+JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
+JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
+JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
+JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
+JMESSAGE(JERR_DHT_COUNTS, "Bogus DHT counts")
+JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
+JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
+JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
+JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
+JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
+JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
+JMESSAGE(JERR_FILE_READ, "Input file read error")
+JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
+JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
+JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
+JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
+JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
+JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
+JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
+JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
+ "Cannot transcode due to multiple use of quantization table %d")
+JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
+JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
+JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
+JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
+JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
+JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
+JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
+JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
+JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
+JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
+JMESSAGE(JERR_QUANT_COMPONENTS,
+ "Cannot quantize more than %d color components")
+JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
+JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
+JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
+JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
+JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
+JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
+JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
+JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
+JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
+JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
+JMESSAGE(JERR_TFILE_WRITE,
+ "Write failed on temporary file --- out of disk space?")
+JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
+JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
+JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
+JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
+JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
+JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
+JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
+JMESSAGE(JMSG_VERSION, JVERSION)
+JMESSAGE(JTRC_16BIT_TABLES,
+ "Caution: quantization tables are too coarse for baseline JPEG")
+JMESSAGE(JTRC_ADOBE,
+ "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
+JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
+JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
+JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
+JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
+JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
+JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
+JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
+JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
+JMESSAGE(JTRC_EOI, "End Of Image")
+JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
+JMESSAGE(JTRC_JFIF, "JFIF APP0 marker, density %dx%d %d")
+JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
+ "Warning: thumbnail image size does not match data length %u")
+JMESSAGE(JTRC_JFIF_MINOR, "Unknown JFIF minor revision number %d.%02d")
+JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
+JMESSAGE(JTRC_MISC_MARKER, "Skipping marker 0x%02x, length %u")
+JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
+JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
+JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
+JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
+JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
+JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
+JMESSAGE(JTRC_RST, "RST%d")
+JMESSAGE(JTRC_SMOOTH_NOTIMPL,
+ "Smoothing not supported with nonstandard sampling ratios")
+JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
+JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
+JMESSAGE(JTRC_SOI, "Start of Image")
+JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
+JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
+JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
+JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
+JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
+JMESSAGE(JTRC_UNKNOWN_IDS,
+ "Unrecognized component IDs %d %d %d, assuming YCbCr")
+JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
+JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
+JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
+JMESSAGE(JWRN_BOGUS_PROGRESSION,
+ "Inconsistent progression sequence for component %d coefficient %d")
+JMESSAGE(JWRN_EXTRANEOUS_DATA,
+ "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
+JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
+JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
+JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
+JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
+JMESSAGE(JWRN_MUST_RESYNC,
+ "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
+JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
+JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
+
+#ifdef JMAKE_ENUM_LIST
+
+ JMSG_LASTMSGCODE
+} J_MESSAGE_CODE;
+
+#undef JMAKE_ENUM_LIST
+#endif /* JMAKE_ENUM_LIST */
+
+/* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
+#undef JMESSAGE
+
+
+#ifndef JERROR_H
+#define JERROR_H
+
+/* Macros to simplify using the error and trace message stuff */
+/* The first parameter is either type of cinfo pointer */
+
+/* Fatal errors (print message and exit) */
+#define ERREXIT(cinfo,code) \
+ ((cinfo)->err->msg_code = (code), \
+ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXIT1(cinfo,code,p1) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXIT2(cinfo,code,p1,p2) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (cinfo)->err->msg_parm.i[1] = (p2), \
+ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXIT3(cinfo,code,p1,p2,p3) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (cinfo)->err->msg_parm.i[1] = (p2), \
+ (cinfo)->err->msg_parm.i[2] = (p3), \
+ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (cinfo)->err->msg_parm.i[1] = (p2), \
+ (cinfo)->err->msg_parm.i[2] = (p3), \
+ (cinfo)->err->msg_parm.i[3] = (p4), \
+ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXITS(cinfo,code,str) \
+ ((cinfo)->err->msg_code = (code), \
+ strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
+ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+
+#define MAKESTMT(stuff) do { stuff } while (0)
+
+/* Nonfatal errors (we can keep going, but the data is probably corrupt) */
+#define WARNMS(cinfo,code) \
+ ((cinfo)->err->msg_code = (code), \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
+#define WARNMS1(cinfo,code,p1) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
+#define WARNMS2(cinfo,code,p1,p2) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (cinfo)->err->msg_parm.i[1] = (p2), \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
+
+/* Informational/debugging messages */
+#define TRACEMS(cinfo,lvl,code) \
+ ((cinfo)->err->msg_code = (code), \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
+#define TRACEMS1(cinfo,lvl,code,p1) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
+#define TRACEMS2(cinfo,lvl,code,p1,p2) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (cinfo)->err->msg_parm.i[1] = (p2), \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
+#define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
+ MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
+ _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
+ (cinfo)->err->msg_code = (code); \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
+#define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
+ MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
+ _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
+ (cinfo)->err->msg_code = (code); \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
+#define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
+ MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
+ _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
+ _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
+ (cinfo)->err->msg_code = (code); \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
+#define TRACEMSS(cinfo,lvl,code,str) \
+ ((cinfo)->err->msg_code = (code), \
+ strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
+
+#endif /* JERROR_H */
diff --git a/libs/jpeg6/jfdctflt.cpp b/libs/jpeg6/jfdctflt.cpp
new file mode 100755
index 0000000..1509b88
--- /dev/null
+++ b/libs/jpeg6/jfdctflt.cpp
@@ -0,0 +1,168 @@
+/*
+ * jfdctflt.c
+ *
+ * Copyright (C) 1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains a floating-point implementation of the
+ * forward DCT (Discrete Cosine Transform).
+ *
+ * This implementation should be more accurate than either of the integer
+ * DCT implementations. However, it may not give the same results on all
+ * machines because of differences in roundoff behavior. Speed will depend
+ * on the hardware's floating point capacity.
+ *
+ * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT
+ * on each column. Direct algorithms are also available, but they are
+ * much more complex and seem not to be any faster when reduced to code.
+ *
+ * This implementation is based on Arai, Agui, and Nakajima's algorithm for
+ * scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in
+ * Japanese, but the algorithm is described in the Pennebaker & Mitchell
+ * JPEG textbook (see REFERENCES section in file README). The following code
+ * is based directly on figure 4-8 in P&M.
+ * While an 8-point DCT cannot be done in less than 11 multiplies, it is
+ * possible to arrange the computation so that many of the multiplies are
+ * simple scalings of the final outputs. These multiplies can then be
+ * folded into the multiplications or divisions by the JPEG quantization
+ * table entries. The AA&N method leaves only 5 multiplies and 29 adds
+ * to be done in the DCT itself.
+ * The primary disadvantage of this method is that with a fixed-point
+ * implementation, accuracy is lost due to imprecise representation of the
+ * scaled quantization values. However, that problem does not arise if
+ * we use floating point arithmetic.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jdct.h" /* Private declarations for DCT subsystem */
+
+#ifdef DCT_FLOAT_SUPPORTED
+
+
+/*
+ * This module is specialized to the case DCTSIZE = 8.
+ */
+
+#if DCTSIZE != 8
+ Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
+#endif
+
+
+/*
+ * Perform the forward DCT on one block of samples.
+ */
+
+GLOBAL void
+jpeg_fdct_float (FAST_FLOAT * data)
+{
+ FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
+ FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
+ FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
+ FAST_FLOAT *dataptr;
+ int ctr;
+
+ /* Pass 1: process rows. */
+
+ dataptr = data;
+ for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
+ tmp0 = dataptr[0] + dataptr[7];
+ tmp7 = dataptr[0] - dataptr[7];
+ tmp1 = dataptr[1] + dataptr[6];
+ tmp6 = dataptr[1] - dataptr[6];
+ tmp2 = dataptr[2] + dataptr[5];
+ tmp5 = dataptr[2] - dataptr[5];
+ tmp3 = dataptr[3] + dataptr[4];
+ tmp4 = dataptr[3] - dataptr[4];
+
+ /* Even part */
+
+ tmp10 = tmp0 + tmp3; /* phase 2 */
+ tmp13 = tmp0 - tmp3;
+ tmp11 = tmp1 + tmp2;
+ tmp12 = tmp1 - tmp2;
+
+ dataptr[0] = tmp10 + tmp11; /* phase 3 */
+ dataptr[4] = tmp10 - tmp11;
+
+ z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
+ dataptr[2] = tmp13 + z1; /* phase 5 */
+ dataptr[6] = tmp13 - z1;
+
+ /* Odd part */
+
+ tmp10 = tmp4 + tmp5; /* phase 2 */
+ tmp11 = tmp5 + tmp6;
+ tmp12 = tmp6 + tmp7;
+
+ /* The rotator is modified from fig 4-8 to avoid extra negations. */
+ z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
+ z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
+ z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
+ z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
+
+ z11 = tmp7 + z3; /* phase 5 */
+ z13 = tmp7 - z3;
+
+ dataptr[5] = z13 + z2; /* phase 6 */
+ dataptr[3] = z13 - z2;
+ dataptr[1] = z11 + z4;
+ dataptr[7] = z11 - z4;
+
+ dataptr += DCTSIZE; /* advance pointer to next row */
+ }
+
+ /* Pass 2: process columns. */
+
+ dataptr = data;
+ for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
+ tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
+ tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
+ tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
+ tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
+ tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
+ tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
+ tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
+ tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
+
+ /* Even part */
+
+ tmp10 = tmp0 + tmp3; /* phase 2 */
+ tmp13 = tmp0 - tmp3;
+ tmp11 = tmp1 + tmp2;
+ tmp12 = tmp1 - tmp2;
+
+ dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
+ dataptr[DCTSIZE*4] = tmp10 - tmp11;
+
+ z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
+ dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
+ dataptr[DCTSIZE*6] = tmp13 - z1;
+
+ /* Odd part */
+
+ tmp10 = tmp4 + tmp5; /* phase 2 */
+ tmp11 = tmp5 + tmp6;
+ tmp12 = tmp6 + tmp7;
+
+ /* The rotator is modified from fig 4-8 to avoid extra negations. */
+ z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
+ z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
+ z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
+ z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
+
+ z11 = tmp7 + z3; /* phase 5 */
+ z13 = tmp7 - z3;
+
+ dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
+ dataptr[DCTSIZE*3] = z13 - z2;
+ dataptr[DCTSIZE*1] = z11 + z4;
+ dataptr[DCTSIZE*7] = z11 - z4;
+
+ dataptr++; /* advance pointer to next column */
+ }
+}
+
+#endif /* DCT_FLOAT_SUPPORTED */
diff --git a/libs/jpeg6/jidctflt.cpp b/libs/jpeg6/jidctflt.cpp
new file mode 100755
index 0000000..2e25c44
--- /dev/null
+++ b/libs/jpeg6/jidctflt.cpp
@@ -0,0 +1,241 @@
+/*
+ * jidctflt.c
+ *
+ * Copyright (C) 1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains a floating-point implementation of the
+ * inverse DCT (Discrete Cosine Transform). In the IJG code, this routine
+ * must also perform dequantization of the input coefficients.
+ *
+ * This implementation should be more accurate than either of the integer
+ * IDCT implementations. However, it may not give the same results on all
+ * machines because of differences in roundoff behavior. Speed will depend
+ * on the hardware's floating point capacity.
+ *
+ * A 2-D IDCT can be done by 1-D IDCT on each column followed by 1-D IDCT
+ * on each row (or vice versa, but it's more convenient to emit a row at
+ * a time). Direct algorithms are also available, but they are much more
+ * complex and seem not to be any faster when reduced to code.
+ *
+ * This implementation is based on Arai, Agui, and Nakajima's algorithm for
+ * scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in
+ * Japanese, but the algorithm is described in the Pennebaker & Mitchell
+ * JPEG textbook (see REFERENCES section in file README). The following code
+ * is based directly on figure 4-8 in P&M.
+ * While an 8-point DCT cannot be done in less than 11 multiplies, it is
+ * possible to arrange the computation so that many of the multiplies are
+ * simple scalings of the final outputs. These multiplies can then be
+ * folded into the multiplications or divisions by the JPEG quantization
+ * table entries. The AA&N method leaves only 5 multiplies and 29 adds
+ * to be done in the DCT itself.
+ * The primary disadvantage of this method is that with a fixed-point
+ * implementation, accuracy is lost due to imprecise representation of the
+ * scaled quantization values. However, that problem does not arise if
+ * we use floating point arithmetic.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jdct.h" /* Private declarations for DCT subsystem */
+
+#ifdef DCT_FLOAT_SUPPORTED
+
+
+/*
+ * This module is specialized to the case DCTSIZE = 8.
+ */
+
+#if DCTSIZE != 8
+ Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
+#endif
+
+
+/* Dequantize a coefficient by multiplying it by the multiplier-table
+ * entry; produce a float result.
+ */
+
+#define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
+
+
+/*
+ * Perform dequantization and inverse DCT on one block of coefficients.
+ */
+
+GLOBAL void
+jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block,
+ JSAMPARRAY output_buf, JDIMENSION output_col)
+{
+ FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
+ FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
+ FAST_FLOAT z5, z10, z11, z12, z13;
+ JCOEFPTR inptr;
+ FLOAT_MULT_TYPE * quantptr;
+ FAST_FLOAT * wsptr;
+ JSAMPROW outptr;
+ JSAMPLE *range_limit = IDCT_range_limit(cinfo);
+ int ctr;
+ FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
+ SHIFT_TEMPS
+
+ /* Pass 1: process columns from input, store into work array. */
+
+ inptr = coef_block;
+ quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
+ wsptr = workspace;
+ for (ctr = DCTSIZE; ctr > 0; ctr--) {
+ /* Due to quantization, we will usually find that many of the input
+ * coefficients are zero, especially the AC terms. We can exploit this
+ * by short-circuiting the IDCT calculation for any column in which all
+ * the AC terms are zero. In that case each output is equal to the
+ * DC coefficient (with scale factor as needed).
+ * With typical images and quantization tables, half or more of the
+ * column DCT calculations can be simplified this way.
+ */
+
+ if ((inptr[DCTSIZE*1] | inptr[DCTSIZE*2] | inptr[DCTSIZE*3] |
+ inptr[DCTSIZE*4] | inptr[DCTSIZE*5] | inptr[DCTSIZE*6] |
+ inptr[DCTSIZE*7]) == 0) {
+ /* AC terms all zero */
+ FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
+
+ wsptr[DCTSIZE*0] = dcval;
+ wsptr[DCTSIZE*1] = dcval;
+ wsptr[DCTSIZE*2] = dcval;
+ wsptr[DCTSIZE*3] = dcval;
+ wsptr[DCTSIZE*4] = dcval;
+ wsptr[DCTSIZE*5] = dcval;
+ wsptr[DCTSIZE*6] = dcval;
+ wsptr[DCTSIZE*7] = dcval;
+
+ inptr++; /* advance pointers to next column */
+ quantptr++;
+ wsptr++;
+ continue;
+ }
+
+ /* Even part */
+
+ tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
+ tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
+ tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
+ tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
+
+ tmp10 = tmp0 + tmp2; /* phase 3 */
+ tmp11 = tmp0 - tmp2;
+
+ tmp13 = tmp1 + tmp3; /* phases 5-3 */
+ tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
+
+ tmp0 = tmp10 + tmp13; /* phase 2 */
+ tmp3 = tmp10 - tmp13;
+ tmp1 = tmp11 + tmp12;
+ tmp2 = tmp11 - tmp12;
+
+ /* Odd part */
+
+ tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
+ tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
+ tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
+ tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
+
+ z13 = tmp6 + tmp5; /* phase 6 */
+ z10 = tmp6 - tmp5;
+ z11 = tmp4 + tmp7;
+ z12 = tmp4 - tmp7;
+
+ tmp7 = z11 + z13; /* phase 5 */
+ tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
+
+ z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
+ tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
+ tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
+
+ tmp6 = tmp12 - tmp7; /* phase 2 */
+ tmp5 = tmp11 - tmp6;
+ tmp4 = tmp10 + tmp5;
+
+ wsptr[DCTSIZE*0] = tmp0 + tmp7;
+ wsptr[DCTSIZE*7] = tmp0 - tmp7;
+ wsptr[DCTSIZE*1] = tmp1 + tmp6;
+ wsptr[DCTSIZE*6] = tmp1 - tmp6;
+ wsptr[DCTSIZE*2] = tmp2 + tmp5;
+ wsptr[DCTSIZE*5] = tmp2 - tmp5;
+ wsptr[DCTSIZE*4] = tmp3 + tmp4;
+ wsptr[DCTSIZE*3] = tmp3 - tmp4;
+
+ inptr++; /* advance pointers to next column */
+ quantptr++;
+ wsptr++;
+ }
+
+ /* Pass 2: process rows from work array, store into output array. */
+ /* Note that we must descale the results by a factor of 8 == 2**3. */
+
+ wsptr = workspace;
+ for (ctr = 0; ctr < DCTSIZE; ctr++) {
+ outptr = output_buf[ctr] + output_col;
+ /* Rows of zeroes can be exploited in the same way as we did with columns.
+ * However, the column calculation has created many nonzero AC terms, so
+ * the simplification applies less often (typically 5% to 10% of the time).
+ * And testing floats for zero is relatively expensive, so we don't bother.
+ */
+
+ /* Even part */
+
+ tmp10 = wsptr[0] + wsptr[4];
+ tmp11 = wsptr[0] - wsptr[4];
+
+ tmp13 = wsptr[2] + wsptr[6];
+ tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
+
+ tmp0 = tmp10 + tmp13;
+ tmp3 = tmp10 - tmp13;
+ tmp1 = tmp11 + tmp12;
+ tmp2 = tmp11 - tmp12;
+
+ /* Odd part */
+
+ z13 = wsptr[5] + wsptr[3];
+ z10 = wsptr[5] - wsptr[3];
+ z11 = wsptr[1] + wsptr[7];
+ z12 = wsptr[1] - wsptr[7];
+
+ tmp7 = z11 + z13;
+ tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
+
+ z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
+ tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
+ tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
+
+ tmp6 = tmp12 - tmp7;
+ tmp5 = tmp11 - tmp6;
+ tmp4 = tmp10 + tmp5;
+
+ /* Final output stage: scale down by a factor of 8 and range-limit */
+
+ outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
+ & RANGE_MASK];
+ outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
+ & RANGE_MASK];
+ outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
+ & RANGE_MASK];
+ outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
+ & RANGE_MASK];
+ outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
+ & RANGE_MASK];
+ outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
+ & RANGE_MASK];
+ outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
+ & RANGE_MASK];
+ outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
+ & RANGE_MASK];
+
+ wsptr += DCTSIZE; /* advance pointer to next row */
+ }
+}
+
+#endif /* DCT_FLOAT_SUPPORTED */
diff --git a/libs/jpeg6/jinclude.h b/libs/jpeg6/jinclude.h
new file mode 100755
index 0000000..5ff60fe
--- /dev/null
+++ b/libs/jpeg6/jinclude.h
@@ -0,0 +1,91 @@
+/*
+ * jinclude.h
+ *
+ * Copyright (C) 1991-1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file exists to provide a single place to fix any problems with
+ * including the wrong system include files. (Common problems are taken
+ * care of by the standard jconfig symbols, but on really weird systems
+ * you may have to edit this file.)
+ *
+ * NOTE: this file is NOT intended to be included by applications using the
+ * JPEG library. Most applications need only include jpeglib.h.
+ */
+
+
+/* Include auto-config file to find out which system include files we need. */
+
+#include "jconfig.h" /* auto configuration options */
+#define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
+
+/*
+ * We need the NULL macro and size_t typedef.
+ * On an ANSI-conforming system it is sufficient to include <stddef.h>.
+ * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
+ * pull in <sys/types.h> as well.
+ * Note that the core JPEG library does not require <stdio.h>;
+ * only the default error handler and data source/destination modules do.
+ * But we must pull it in because of the references to FILE in jpeglib.h.
+ * You can remove those references if you want to compile without <stdio.h>.
+ */
+
+#ifdef HAVE_STDDEF_H
+#include <stddef.h>
+#endif
+
+#ifdef HAVE_STDLIB_H
+#include <stdlib.h>
+#endif
+
+#ifdef NEED_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+
+#include <stdio.h>
+
+/*
+ * We need memory copying and zeroing functions, plus strncpy().
+ * ANSI and System V implementations declare these in <string.h>.
+ * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
+ * Some systems may declare memset and memcpy in <memory.h>.
+ *
+ * NOTE: we assume the size parameters to these functions are of type size_t.
+ * Change the casts in these macros if not!
+ */
+
+#ifdef NEED_BSD_STRINGS
+
+#include <strings.h>
+#define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
+#define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
+
+#else /* not BSD, assume ANSI/SysV string lib */
+
+#include <string.h>
+#define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
+#define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
+
+#endif
+
+/*
+ * In ANSI C, and indeed any rational implementation, size_t is also the
+ * type returned by sizeof(). However, it seems there are some irrational
+ * implementations out there, in which sizeof() returns an int even though
+ * size_t is defined as long or unsigned long. To ensure consistent results
+ * we always use this SIZEOF() macro in place of using sizeof() directly.
+ */
+
+#define SIZEOF(object) ((size_t) sizeof(object))
+
+/*
+ * The modules that use fread() and fwrite() always invoke them through
+ * these macros. On some systems you may need to twiddle the argument casts.
+ * CAUTION: argument order is different from underlying functions!
+ */
+
+#define JFREAD(file,buf,sizeofbuf) \
+ ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
+#define JFWRITE(file,buf,sizeofbuf) \
+ ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
diff --git a/libs/jpeg6/jmemmgr.cpp b/libs/jpeg6/jmemmgr.cpp
new file mode 100755
index 0000000..61045f9
--- /dev/null
+++ b/libs/jpeg6/jmemmgr.cpp
@@ -0,0 +1,1115 @@
+/*
+ * jmemmgr.c
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the JPEG system-independent memory management
+ * routines. This code is usable across a wide variety of machines; most
+ * of the system dependencies have been isolated in a separate file.
+ * The major functions provided here are:
+ * * pool-based allocation and freeing of memory;
+ * * policy decisions about how to divide available memory among the
+ * virtual arrays;
+ * * control logic for swapping virtual arrays between main memory and
+ * backing storage.
+ * The separate system-dependent file provides the actual backing-storage
+ * access code, and it contains the policy decision about how much total
+ * main memory to use.
+ * This file is system-dependent in the sense that some of its functions
+ * are unnecessary in some systems. For example, if there is enough virtual
+ * memory so that backing storage will never be used, much of the virtual
+ * array control logic could be removed. (Of course, if you have that much
+ * memory then you shouldn't care about a little bit of unused code...)
+ */
+
+#define JPEG_INTERNALS
+#define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jmemsys.h" /* import the system-dependent declarations */
+
+#ifndef NO_GETENV
+#ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
+extern char * getenv JPP((const char * name));
+#endif
+#endif
+
+
+/*
+ * Some important notes:
+ * The allocation routines provided here must never return NULL.
+ * They should exit to error_exit if unsuccessful.
+ *
+ * It's not a good idea to try to merge the sarray and barray routines,
+ * even though they are textually almost the same, because samples are
+ * usually stored as bytes while coefficients are shorts or ints. Thus,
+ * in machines where byte pointers have a different representation from
+ * word pointers, the resulting machine code could not be the same.
+ */
+
+
+/*
+ * Many machines require storage alignment: longs must start on 4-byte
+ * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
+ * always returns pointers that are multiples of the worst-case alignment
+ * requirement, and we had better do so too.
+ * There isn't any really portable way to determine the worst-case alignment
+ * requirement. This module assumes that the alignment requirement is
+ * multiples of sizeof(ALIGN_TYPE).
+ * By default, we define ALIGN_TYPE as double. This is necessary on some
+ * workstations (where doubles really do need 8-byte alignment) and will work
+ * fine on nearly everything. If your machine has lesser alignment needs,
+ * you can save a few bytes by making ALIGN_TYPE smaller.
+ * The only place I know of where this will NOT work is certain Macintosh
+ * 680x0 compilers that define double as a 10-byte IEEE extended float.
+ * Doing 10-byte alignment is counterproductive because longwords won't be
+ * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
+ * such a compiler.
+ */
+
+#ifndef ALIGN_TYPE /* so can override from jconfig.h */
+#define ALIGN_TYPE double
+#endif
+
+
+/*
+ * We allocate objects from "pools", where each pool is gotten with a single
+ * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
+ * overhead within a pool, except for alignment padding. Each pool has a
+ * header with a link to the next pool of the same class.
+ * Small and large pool headers are identical except that the latter's
+ * link pointer must be FAR on 80x86 machines.
+ * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
+ * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
+ * of the alignment requirement of ALIGN_TYPE.
+ */
+
+typedef union small_pool_struct * small_pool_ptr;
+
+typedef union small_pool_struct {
+ struct {
+ small_pool_ptr next; /* next in list of pools */
+ size_t bytes_used; /* how many bytes already used within pool */
+ size_t bytes_left; /* bytes still available in this pool */
+ } hdr;
+ ALIGN_TYPE dummy; /* included in union to ensure alignment */
+} small_pool_hdr;
+
+typedef union large_pool_struct FAR * large_pool_ptr;
+
+typedef union large_pool_struct {
+ struct {
+ large_pool_ptr next; /* next in list of pools */
+ size_t bytes_used; /* how many bytes already used within pool */
+ size_t bytes_left; /* bytes still available in this pool */
+ } hdr;
+ ALIGN_TYPE dummy; /* included in union to ensure alignment */
+} large_pool_hdr;
+
+
+/*
+ * Here is the full definition of a memory manager object.
+ */
+
+typedef struct {
+ struct jpeg_memory_mgr pub; /* public fields */
+
+ /* Each pool identifier (lifetime class) names a linked list of pools. */
+ small_pool_ptr small_list[JPOOL_NUMPOOLS];
+ large_pool_ptr large_list[JPOOL_NUMPOOLS];
+
+ /* Since we only have one lifetime class of virtual arrays, only one
+ * linked list is necessary (for each datatype). Note that the virtual
+ * array control blocks being linked together are actually stored somewhere
+ * in the small-pool list.
+ */
+ jvirt_sarray_ptr virt_sarray_list;
+ jvirt_barray_ptr virt_barray_list;
+
+ /* This counts total space obtained from jpeg_get_small/large */
+ long total_space_allocated;
+
+ /* alloc_sarray and alloc_barray set this value for use by virtual
+ * array routines.
+ */
+ JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
+} my_memory_mgr;
+
+typedef my_memory_mgr * my_mem_ptr;
+
+
+/*
+ * The control blocks for virtual arrays.
+ * Note that these blocks are allocated in the "small" pool area.
+ * System-dependent info for the associated backing store (if any) is hidden
+ * inside the backing_store_info struct.
+ */
+
+struct jvirt_sarray_control {
+ JSAMPARRAY mem_buffer; /* => the in-memory buffer */
+ JDIMENSION rows_in_array; /* total virtual array height */
+ JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
+ JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
+ JDIMENSION rows_in_mem; /* height of memory buffer */
+ JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
+ JDIMENSION cur_start_row; /* first logical row # in the buffer */
+ JDIMENSION first_undef_row; /* row # of first uninitialized row */
+ boolean pre_zero; /* pre-zero mode requested? */
+ boolean dirty; /* do current buffer contents need written? */
+ boolean b_s_open; /* is backing-store data valid? */
+ jvirt_sarray_ptr next; /* link to next virtual sarray control block */
+ backing_store_info b_s_info; /* System-dependent control info */
+};
+
+struct jvirt_barray_control {
+ JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
+ JDIMENSION rows_in_array; /* total virtual array height */
+ JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
+ JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
+ JDIMENSION rows_in_mem; /* height of memory buffer */
+ JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
+ JDIMENSION cur_start_row; /* first logical row # in the buffer */
+ JDIMENSION first_undef_row; /* row # of first uninitialized row */
+ boolean pre_zero; /* pre-zero mode requested? */
+ boolean dirty; /* do current buffer contents need written? */
+ boolean b_s_open; /* is backing-store data valid? */
+ jvirt_barray_ptr next; /* link to next virtual barray control block */
+ backing_store_info b_s_info; /* System-dependent control info */
+};
+
+
+#ifdef MEM_STATS /* optional extra stuff for statistics */
+
+LOCAL void
+print_mem_stats (j_common_ptr cinfo, int pool_id)
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ small_pool_ptr shdr_ptr;
+ large_pool_ptr lhdr_ptr;
+
+ /* Since this is only a debugging stub, we can cheat a little by using
+ * fprintf directly rather than going through the trace message code.
+ * This is helpful because message parm array can't handle longs.
+ */
+ fprintf(stderr, "Freeing pool %d, total space = %ld\n",
+ pool_id, mem->total_space_allocated);
+
+ for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
+ lhdr_ptr = lhdr_ptr->hdr.next) {
+ fprintf(stderr, " Large chunk used %ld\n",
+ (long) lhdr_ptr->hdr.bytes_used);
+ }
+
+ for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
+ shdr_ptr = shdr_ptr->hdr.next) {
+ fprintf(stderr, " Small chunk used %ld free %ld\n",
+ (long) shdr_ptr->hdr.bytes_used,
+ (long) shdr_ptr->hdr.bytes_left);
+ }
+}
+
+#endif /* MEM_STATS */
+
+
+LOCAL void
+out_of_memory (j_common_ptr cinfo, int which)
+/* Report an out-of-memory error and stop execution */
+/* If we compiled MEM_STATS support, report alloc requests before dying */
+{
+#ifdef MEM_STATS
+ cinfo->err->trace_level = 2; /* force self_destruct to report stats */
+#endif
+ ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
+}
+
+
+/*
+ * Allocation of "small" objects.
+ *
+ * For these, we use pooled storage. When a new pool must be created,
+ * we try to get enough space for the current request plus a "slop" factor,
+ * where the slop will be the amount of leftover space in the new pool.
+ * The speed vs. space tradeoff is largely determined by the slop values.
+ * A different slop value is provided for each pool class (lifetime),
+ * and we also distinguish the first pool of a class from later ones.
+ * NOTE: the values given work fairly well on both 16- and 32-bit-int
+ * machines, but may be too small if longs are 64 bits or more.
+ */
+
+static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
+{
+ 1600, /* first PERMANENT pool */
+ 16000 /* first IMAGE pool */
+};
+
+static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
+{
+ 0, /* additional PERMANENT pools */
+ 5000 /* additional IMAGE pools */
+};
+
+#define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
+
+
+METHODDEF void *
+alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
+/* Allocate a "small" object */
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ small_pool_ptr hdr_ptr, prev_hdr_ptr;
+ char * data_ptr;
+ size_t odd_bytes, min_request, slop;
+
+ /* Check for unsatisfiable request (do now to ensure no overflow below) */
+ if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
+ out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
+
+ /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
+ odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
+ if (odd_bytes > 0)
+ sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
+
+ /* See if space is available in any existing pool */
+ if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
+ ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
+ prev_hdr_ptr = NULL;
+ hdr_ptr = mem->small_list[pool_id];
+ while (hdr_ptr != NULL) {
+ if (hdr_ptr->hdr.bytes_left >= sizeofobject)
+ break; /* found pool with enough space */
+ prev_hdr_ptr = hdr_ptr;
+ hdr_ptr = hdr_ptr->hdr.next;
+ }
+
+ /* Time to make a new pool? */
+ if (hdr_ptr == NULL) {
+ /* min_request is what we need now, slop is what will be leftover */
+ min_request = sizeofobject + SIZEOF(small_pool_hdr);
+ if (prev_hdr_ptr == NULL) /* first pool in class? */
+ slop = first_pool_slop[pool_id];
+ else
+ slop = extra_pool_slop[pool_id];
+ /* Don't ask for more than MAX_ALLOC_CHUNK */
+ if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
+ slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
+ /* Try to get space, if fail reduce slop and try again */
+ for (;;) {
+ hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
+ if (hdr_ptr != NULL)
+ break;
+ slop /= 2;
+ if (slop < MIN_SLOP) /* give up when it gets real small */
+ out_of_memory(cinfo, 2); /* jpeg_get_small failed */
+ }
+ mem->total_space_allocated += min_request + slop;
+ /* Success, initialize the new pool header and add to end of list */
+ hdr_ptr->hdr.next = NULL;
+ hdr_ptr->hdr.bytes_used = 0;
+ hdr_ptr->hdr.bytes_left = sizeofobject + slop;
+ if (prev_hdr_ptr == NULL) /* first pool in class? */
+ mem->small_list[pool_id] = hdr_ptr;
+ else
+ prev_hdr_ptr->hdr.next = hdr_ptr;
+ }
+
+ /* OK, allocate the object from the current pool */
+ data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
+ data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
+ hdr_ptr->hdr.bytes_used += sizeofobject;
+ hdr_ptr->hdr.bytes_left -= sizeofobject;
+
+ return (void *) data_ptr;
+}
+
+
+/*
+ * Allocation of "large" objects.
+ *
+ * The external semantics of these are the same as "small" objects,
+ * except that FAR pointers are used on 80x86. However the pool
+ * management heuristics are quite different. We assume that each
+ * request is large enough that it may as well be passed directly to
+ * jpeg_get_large; the pool management just links everything together
+ * so that we can free it all on demand.
+ * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
+ * structures. The routines that create these structures (see below)
+ * deliberately bunch rows together to ensure a large request size.
+ */
+
+METHODDEF void FAR *
+alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
+/* Allocate a "large" object */
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ large_pool_ptr hdr_ptr;
+ size_t odd_bytes;
+
+ /* Check for unsatisfiable request (do now to ensure no overflow below) */
+ if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
+ out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
+
+ /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
+ odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
+ if (odd_bytes > 0)
+ sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
+
+ /* Always make a new pool */
+ if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
+ ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
+
+ hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
+ SIZEOF(large_pool_hdr));
+ if (hdr_ptr == NULL)
+ out_of_memory(cinfo, 4); /* jpeg_get_large failed */
+ mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
+
+ /* Success, initialize the new pool header and add to list */
+ hdr_ptr->hdr.next = mem->large_list[pool_id];
+ /* We maintain space counts in each pool header for statistical purposes,
+ * even though they are not needed for allocation.
+ */
+ hdr_ptr->hdr.bytes_used = sizeofobject;
+ hdr_ptr->hdr.bytes_left = 0;
+ mem->large_list[pool_id] = hdr_ptr;
+
+ return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
+}
+
+
+/*
+ * Creation of 2-D sample arrays.
+ * The pointers are in near heap, the samples themselves in FAR heap.
+ *
+ * To minimize allocation overhead and to allow I/O of large contiguous
+ * blocks, we allocate the sample rows in groups of as many rows as possible
+ * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
+ * NB: the virtual array control routines, later in this file, know about
+ * this chunking of rows. The rowsperchunk value is left in the mem manager
+ * object so that it can be saved away if this sarray is the workspace for
+ * a virtual array.
+ */
+
+METHODDEF JSAMPARRAY
+alloc_sarray (j_common_ptr cinfo, int pool_id,
+ JDIMENSION samplesperrow, JDIMENSION numrows)
+/* Allocate a 2-D sample array */
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ JSAMPARRAY result;
+ JSAMPROW workspace;
+ JDIMENSION rowsperchunk, currow, i;
+ long ltemp;
+
+ /* Calculate max # of rows allowed in one allocation chunk */
+ ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
+ ((long) samplesperrow * SIZEOF(JSAMPLE));
+ if (ltemp <= 0)
+ ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
+ if (ltemp < (long) numrows)
+ rowsperchunk = (JDIMENSION) ltemp;
+ else
+ rowsperchunk = numrows;
+ mem->last_rowsperchunk = rowsperchunk;
+
+ /* Get space for row pointers (small object) */
+ result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
+ (size_t) (numrows * SIZEOF(JSAMPROW)));
+
+ /* Get the rows themselves (large objects) */
+ currow = 0;
+ while (currow < numrows) {
+ rowsperchunk = MIN(rowsperchunk, numrows - currow);
+ workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
+ (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
+ * SIZEOF(JSAMPLE)));
+ for (i = rowsperchunk; i > 0; i--) {
+ result[currow++] = workspace;
+ workspace += samplesperrow;
+ }
+ }
+
+ return result;
+}
+
+
+/*
+ * Creation of 2-D coefficient-block arrays.
+ * This is essentially the same as the code for sample arrays, above.
+ */
+
+METHODDEF JBLOCKARRAY
+alloc_barray (j_common_ptr cinfo, int pool_id,
+ JDIMENSION blocksperrow, JDIMENSION numrows)
+/* Allocate a 2-D coefficient-block array */
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ JBLOCKARRAY result;
+ JBLOCKROW workspace;
+ JDIMENSION rowsperchunk, currow, i;
+ long ltemp;
+
+ /* Calculate max # of rows allowed in one allocation chunk */
+ ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
+ ((long) blocksperrow * SIZEOF(JBLOCK));
+ if (ltemp <= 0)
+ ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
+ if (ltemp < (long) numrows)
+ rowsperchunk = (JDIMENSION) ltemp;
+ else
+ rowsperchunk = numrows;
+ mem->last_rowsperchunk = rowsperchunk;
+
+ /* Get space for row pointers (small object) */
+ result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
+ (size_t) (numrows * SIZEOF(JBLOCKROW)));
+
+ /* Get the rows themselves (large objects) */
+ currow = 0;
+ while (currow < numrows) {
+ rowsperchunk = MIN(rowsperchunk, numrows - currow);
+ workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
+ (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
+ * SIZEOF(JBLOCK)));
+ for (i = rowsperchunk; i > 0; i--) {
+ result[currow++] = workspace;
+ workspace += blocksperrow;
+ }
+ }
+
+ return result;
+}
+
+
+/*
+ * About virtual array management:
+ *
+ * The above "normal" array routines are only used to allocate strip buffers
+ * (as wide as the image, but just a few rows high). Full-image-sized buffers
+ * are handled as "virtual" arrays. The array is still accessed a strip at a
+ * time, but the memory manager must save the whole array for repeated
+ * accesses. The intended implementation is that there is a strip buffer in
+ * memory (as high as is possible given the desired memory limit), plus a
+ * backing file that holds the rest of the array.
+ *
+ * The request_virt_array routines are told the total size of the image and
+ * the maximum number of rows that will be accessed at once. The in-memory
+ * buffer must be at least as large as the maxaccess value.
+ *
+ * The request routines create control blocks but not the in-memory buffers.
+ * That is postponed until realize_virt_arrays is called. At that time the
+ * total amount of space needed is known (approximately, anyway), so free
+ * memory can be divided up fairly.
+ *
+ * The access_virt_array routines are responsible for making a specific strip
+ * area accessible (after reading or writing the backing file, if necessary).
+ * Note that the access routines are told whether the caller intends to modify
+ * the accessed strip; during a read-only pass this saves having to rewrite
+ * data to disk. The access routines are also responsible for pre-zeroing
+ * any newly accessed rows, if pre-zeroing was requested.
+ *
+ * In current usage, the access requests are usually for nonoverlapping
+ * strips; that is, successive access start_row numbers differ by exactly
+ * num_rows = maxaccess. This means we can get good performance with simple
+ * buffer dump/reload logic, by making the in-memory buffer be a multiple
+ * of the access height; then there will never be accesses across bufferload
+ * boundaries. The code will still work with overlapping access requests,
+ * but it doesn't handle bufferload overlaps very efficiently.
+ */
+
+
+METHODDEF jvirt_sarray_ptr
+request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
+ JDIMENSION samplesperrow, JDIMENSION numrows,
+ JDIMENSION maxaccess)
+/* Request a virtual 2-D sample array */
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ jvirt_sarray_ptr result;
+
+ /* Only IMAGE-lifetime virtual arrays are currently supported */
+ if (pool_id != JPOOL_IMAGE)
+ ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
+
+ /* get control block */
+ result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
+ SIZEOF(struct jvirt_sarray_control));
+
+ result->mem_buffer = NULL; /* marks array not yet realized */
+ result->rows_in_array = numrows;
+ result->samplesperrow = samplesperrow;
+ result->maxaccess = maxaccess;
+ result->pre_zero = pre_zero;
+ result->b_s_open = FALSE; /* no associated backing-store object */
+ result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
+ mem->virt_sarray_list = result;
+
+ return result;
+}
+
+
+METHODDEF jvirt_barray_ptr
+request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
+ JDIMENSION blocksperrow, JDIMENSION numrows,
+ JDIMENSION maxaccess)
+/* Request a virtual 2-D coefficient-block array */
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ jvirt_barray_ptr result;
+
+ /* Only IMAGE-lifetime virtual arrays are currently supported */
+ if (pool_id != JPOOL_IMAGE)
+ ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
+
+ /* get control block */
+ result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
+ SIZEOF(struct jvirt_barray_control));
+
+ result->mem_buffer = NULL; /* marks array not yet realized */
+ result->rows_in_array = numrows;
+ result->blocksperrow = blocksperrow;
+ result->maxaccess = maxaccess;
+ result->pre_zero = pre_zero;
+ result->b_s_open = FALSE; /* no associated backing-store object */
+ result->next = mem->virt_barray_list; /* add to list of virtual arrays */
+ mem->virt_barray_list = result;
+
+ return result;
+}
+
+
+METHODDEF void
+realize_virt_arrays (j_common_ptr cinfo)
+/* Allocate the in-memory buffers for any unrealized virtual arrays */
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ long space_per_minheight, maximum_space, avail_mem;
+ long minheights, max_minheights;
+ jvirt_sarray_ptr sptr;
+ jvirt_barray_ptr bptr;
+
+ /* Compute the minimum space needed (maxaccess rows in each buffer)
+ * and the maximum space needed (full image height in each buffer).
+ * These may be of use to the system-dependent jpeg_mem_available routine.
+ */
+ space_per_minheight = 0;
+ maximum_space = 0;
+ for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
+ if (sptr->mem_buffer == NULL) { /* if not realized yet */
+ space_per_minheight += (long) sptr->maxaccess *
+ (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
+ maximum_space += (long) sptr->rows_in_array *
+ (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
+ }
+ }
+ for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
+ if (bptr->mem_buffer == NULL) { /* if not realized yet */
+ space_per_minheight += (long) bptr->maxaccess *
+ (long) bptr->blocksperrow * SIZEOF(JBLOCK);
+ maximum_space += (long) bptr->rows_in_array *
+ (long) bptr->blocksperrow * SIZEOF(JBLOCK);
+ }
+ }
+
+ if (space_per_minheight <= 0)
+ return; /* no unrealized arrays, no work */
+
+ /* Determine amount of memory to actually use; this is system-dependent. */
+ avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
+ mem->total_space_allocated);
+
+ /* If the maximum space needed is available, make all the buffers full
+ * height; otherwise parcel it out with the same number of minheights
+ * in each buffer.
+ */
+ if (avail_mem >= maximum_space)
+ max_minheights = 1000000000L;
+ else {
+ max_minheights = avail_mem / space_per_minheight;
+ /* If there doesn't seem to be enough space, try to get the minimum
+ * anyway. This allows a "stub" implementation of jpeg_mem_available().
+ */
+ if (max_minheights <= 0)
+ max_minheights = 1;
+ }
+
+ /* Allocate the in-memory buffers and initialize backing store as needed. */
+
+ for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
+ if (sptr->mem_buffer == NULL) { /* if not realized yet */
+ minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
+ if (minheights <= max_minheights) {
+ /* This buffer fits in memory */
+ sptr->rows_in_mem = sptr->rows_in_array;
+ } else {
+ /* It doesn't fit in memory, create backing store. */
+ sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
+ jpeg_open_backing_store(cinfo, & sptr->b_s_info,
+ (long) sptr->rows_in_array *
+ (long) sptr->samplesperrow *
+ (long) SIZEOF(JSAMPLE));
+ sptr->b_s_open = TRUE;
+ }
+ sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
+ sptr->samplesperrow, sptr->rows_in_mem);
+ sptr->rowsperchunk = mem->last_rowsperchunk;
+ sptr->cur_start_row = 0;
+ sptr->first_undef_row = 0;
+ sptr->dirty = FALSE;
+ }
+ }
+
+ for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
+ if (bptr->mem_buffer == NULL) { /* if not realized yet */
+ minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
+ if (minheights <= max_minheights) {
+ /* This buffer fits in memory */
+ bptr->rows_in_mem = bptr->rows_in_array;
+ } else {
+ /* It doesn't fit in memory, create backing store. */
+ bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
+ jpeg_open_backing_store(cinfo, & bptr->b_s_info,
+ (long) bptr->rows_in_array *
+ (long) bptr->blocksperrow *
+ (long) SIZEOF(JBLOCK));
+ bptr->b_s_open = TRUE;
+ }
+ bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
+ bptr->blocksperrow, bptr->rows_in_mem);
+ bptr->rowsperchunk = mem->last_rowsperchunk;
+ bptr->cur_start_row = 0;
+ bptr->first_undef_row = 0;
+ bptr->dirty = FALSE;
+ }
+ }
+}
+
+
+LOCAL void
+do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
+/* Do backing store read or write of a virtual sample array */
+{
+ long bytesperrow, file_offset, byte_count, rows, thisrow, i;
+
+ bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
+ file_offset = ptr->cur_start_row * bytesperrow;
+ /* Loop to read or write each allocation chunk in mem_buffer */
+ for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
+ /* One chunk, but check for short chunk at end of buffer */
+ rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
+ /* Transfer no more than is currently defined */
+ thisrow = (long) ptr->cur_start_row + i;
+ rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
+ /* Transfer no more than fits in file */
+ rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
+ if (rows <= 0) /* this chunk might be past end of file! */
+ break;
+ byte_count = rows * bytesperrow;
+ if (writing)
+ (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
+ (void FAR *) ptr->mem_buffer[i],
+ file_offset, byte_count);
+ else
+ (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
+ (void FAR *) ptr->mem_buffer[i],
+ file_offset, byte_count);
+ file_offset += byte_count;
+ }
+}
+
+
+LOCAL void
+do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
+/* Do backing store read or write of a virtual coefficient-block array */
+{
+ long bytesperrow, file_offset, byte_count, rows, thisrow, i;
+
+ bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
+ file_offset = ptr->cur_start_row * bytesperrow;
+ /* Loop to read or write each allocation chunk in mem_buffer */
+ for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
+ /* One chunk, but check for short chunk at end of buffer */
+ rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
+ /* Transfer no more than is currently defined */
+ thisrow = (long) ptr->cur_start_row + i;
+ rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
+ /* Transfer no more than fits in file */
+ rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
+ if (rows <= 0) /* this chunk might be past end of file! */
+ break;
+ byte_count = rows * bytesperrow;
+ if (writing)
+ (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
+ (void FAR *) ptr->mem_buffer[i],
+ file_offset, byte_count);
+ else
+ (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
+ (void FAR *) ptr->mem_buffer[i],
+ file_offset, byte_count);
+ file_offset += byte_count;
+ }
+}
+
+
+METHODDEF JSAMPARRAY
+access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
+ JDIMENSION start_row, JDIMENSION num_rows,
+ boolean writable)
+/* Access the part of a virtual sample array starting at start_row */
+/* and extending for num_rows rows. writable is true if */
+/* caller intends to modify the accessed area. */
+{
+ JDIMENSION end_row = start_row + num_rows;
+ JDIMENSION undef_row;
+
+ /* debugging check */
+ if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
+ ptr->mem_buffer == NULL)
+ ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
+
+ /* Make the desired part of the virtual array accessible */
+ if (start_row < ptr->cur_start_row ||
+ end_row > ptr->cur_start_row+ptr->rows_in_mem) {
+ if (! ptr->b_s_open)
+ ERREXIT(cinfo, JERR_VIRTUAL_BUG);
+ /* Flush old buffer contents if necessary */
+ if (ptr->dirty) {
+ do_sarray_io(cinfo, ptr, TRUE);
+ ptr->dirty = FALSE;
+ }
+ /* Decide what part of virtual array to access.
+ * Algorithm: if target address > current window, assume forward scan,
+ * load starting at target address. If target address < current window,
+ * assume backward scan, load so that target area is top of window.
+ * Note that when switching from forward write to forward read, will have
+ * start_row = 0, so the limiting case applies and we load from 0 anyway.
+ */
+ if (start_row > ptr->cur_start_row) {
+ ptr->cur_start_row = start_row;
+ } else {
+ /* use long arithmetic here to avoid overflow & unsigned problems */
+ long ltemp;
+
+ ltemp = (long) end_row - (long) ptr->rows_in_mem;
+ if (ltemp < 0)
+ ltemp = 0; /* don't fall off front end of file */
+ ptr->cur_start_row = (JDIMENSION) ltemp;
+ }
+ /* Read in the selected part of the array.
+ * During the initial write pass, we will do no actual read
+ * because the selected part is all undefined.
+ */
+ do_sarray_io(cinfo, ptr, FALSE);
+ }
+ /* Ensure the accessed part of the array is defined; prezero if needed.
+ * To improve locality of access, we only prezero the part of the array
+ * that the caller is about to access, not the entire in-memory array.
+ */
+ if (ptr->first_undef_row < end_row) {
+ if (ptr->first_undef_row < start_row) {
+ if (writable) /* writer skipped over a section of array */
+ ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
+ undef_row = start_row; /* but reader is allowed to read ahead */
+ } else {
+ undef_row = ptr->first_undef_row;
+ }
+ if (writable)
+ ptr->first_undef_row = end_row;
+ if (ptr->pre_zero) {
+ size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
+ undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
+ end_row -= ptr->cur_start_row;
+ while (undef_row < end_row) {
+ jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
+ undef_row++;
+ }
+ } else {
+ if (! writable) /* reader looking at undefined data */
+ ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
+ }
+ }
+ /* Flag the buffer dirty if caller will write in it */
+ if (writable)
+ ptr->dirty = TRUE;
+ /* Return address of proper part of the buffer */
+ return ptr->mem_buffer + (start_row - ptr->cur_start_row);
+}
+
+
+METHODDEF JBLOCKARRAY
+access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
+ JDIMENSION start_row, JDIMENSION num_rows,
+ boolean writable)
+/* Access the part of a virtual block array starting at start_row */
+/* and extending for num_rows rows. writable is true if */
+/* caller intends to modify the accessed area. */
+{
+ JDIMENSION end_row = start_row + num_rows;
+ JDIMENSION undef_row;
+
+ /* debugging check */
+ if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
+ ptr->mem_buffer == NULL)
+ ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
+
+ /* Make the desired part of the virtual array accessible */
+ if (start_row < ptr->cur_start_row ||
+ end_row > ptr->cur_start_row+ptr->rows_in_mem) {
+ if (! ptr->b_s_open)
+ ERREXIT(cinfo, JERR_VIRTUAL_BUG);
+ /* Flush old buffer contents if necessary */
+ if (ptr->dirty) {
+ do_barray_io(cinfo, ptr, TRUE);
+ ptr->dirty = FALSE;
+ }
+ /* Decide what part of virtual array to access.
+ * Algorithm: if target address > current window, assume forward scan,
+ * load starting at target address. If target address < current window,
+ * assume backward scan, load so that target area is top of window.
+ * Note that when switching from forward write to forward read, will have
+ * start_row = 0, so the limiting case applies and we load from 0 anyway.
+ */
+ if (start_row > ptr->cur_start_row) {
+ ptr->cur_start_row = start_row;
+ } else {
+ /* use long arithmetic here to avoid overflow & unsigned problems */
+ long ltemp;
+
+ ltemp = (long) end_row - (long) ptr->rows_in_mem;
+ if (ltemp < 0)
+ ltemp = 0; /* don't fall off front end of file */
+ ptr->cur_start_row = (JDIMENSION) ltemp;
+ }
+ /* Read in the selected part of the array.
+ * During the initial write pass, we will do no actual read
+ * because the selected part is all undefined.
+ */
+ do_barray_io(cinfo, ptr, FALSE);
+ }
+ /* Ensure the accessed part of the array is defined; prezero if needed.
+ * To improve locality of access, we only prezero the part of the array
+ * that the caller is about to access, not the entire in-memory array.
+ */
+ if (ptr->first_undef_row < end_row) {
+ if (ptr->first_undef_row < start_row) {
+ if (writable) /* writer skipped over a section of array */
+ ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
+ undef_row = start_row; /* but reader is allowed to read ahead */
+ } else {
+ undef_row = ptr->first_undef_row;
+ }
+ if (writable)
+ ptr->first_undef_row = end_row;
+ if (ptr->pre_zero) {
+ size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
+ undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
+ end_row -= ptr->cur_start_row;
+ while (undef_row < end_row) {
+ jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
+ undef_row++;
+ }
+ } else {
+ if (! writable) /* reader looking at undefined data */
+ ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
+ }
+ }
+ /* Flag the buffer dirty if caller will write in it */
+ if (writable)
+ ptr->dirty = TRUE;
+ /* Return address of proper part of the buffer */
+ return ptr->mem_buffer + (start_row - ptr->cur_start_row);
+}
+
+
+/*
+ * Release all objects belonging to a specified pool.
+ */
+
+METHODDEF void
+free_pool (j_common_ptr cinfo, int pool_id)
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ small_pool_ptr shdr_ptr;
+ large_pool_ptr lhdr_ptr;
+ size_t space_freed;
+
+ if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
+ ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
+
+#ifdef MEM_STATS
+ if (cinfo->err->trace_level > 1)
+ print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
+#endif
+
+ /* If freeing IMAGE pool, close any virtual arrays first */
+ if (pool_id == JPOOL_IMAGE) {
+ jvirt_sarray_ptr sptr;
+ jvirt_barray_ptr bptr;
+
+ for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
+ if (sptr->b_s_open) { /* there may be no backing store */
+ sptr->b_s_open = FALSE; /* prevent recursive close if error */
+ (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
+ }
+ }
+ mem->virt_sarray_list = NULL;
+ for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
+ if (bptr->b_s_open) { /* there may be no backing store */
+ bptr->b_s_open = FALSE; /* prevent recursive close if error */
+ (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
+ }
+ }
+ mem->virt_barray_list = NULL;
+ }
+
+ /* Release large objects */
+ lhdr_ptr = mem->large_list[pool_id];
+ mem->large_list[pool_id] = NULL;
+
+ while (lhdr_ptr != NULL) {
+ large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
+ space_freed = lhdr_ptr->hdr.bytes_used +
+ lhdr_ptr->hdr.bytes_left +
+ SIZEOF(large_pool_hdr);
+ jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
+ mem->total_space_allocated -= space_freed;
+ lhdr_ptr = next_lhdr_ptr;
+ }
+
+ /* Release small objects */
+ shdr_ptr = mem->small_list[pool_id];
+ mem->small_list[pool_id] = NULL;
+
+ while (shdr_ptr != NULL) {
+ small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
+ space_freed = shdr_ptr->hdr.bytes_used +
+ shdr_ptr->hdr.bytes_left +
+ SIZEOF(small_pool_hdr);
+ jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
+ mem->total_space_allocated -= space_freed;
+ shdr_ptr = next_shdr_ptr;
+ }
+}
+
+
+/*
+ * Close up shop entirely.
+ * Note that this cannot be called unless cinfo->mem is non-NULL.
+ */
+
+METHODDEF void
+self_destruct (j_common_ptr cinfo)
+{
+ int pool;
+
+ /* Close all backing store, release all memory.
+ * Releasing pools in reverse order might help avoid fragmentation
+ * with some (brain-damaged) malloc libraries.
+ */
+ for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
+ free_pool(cinfo, pool);
+ }
+
+ /* Release the memory manager control block too. */
+ jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
+ cinfo->mem = NULL; /* ensures I will be called only once */
+
+ jpeg_mem_term(cinfo); /* system-dependent cleanup */
+}
+
+
+/*
+ * Memory manager initialization.
+ * When this is called, only the error manager pointer is valid in cinfo!
+ */
+
+GLOBAL void
+jinit_memory_mgr (j_common_ptr cinfo)
+{
+ my_mem_ptr mem;
+ long max_to_use;
+ int pool;
+ size_t test_mac;
+
+ cinfo->mem = NULL; /* for safety if init fails */
+
+ /* Check for configuration errors.
+ * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
+ * doesn't reflect any real hardware alignment requirement.
+ * The test is a little tricky: for X>0, X and X-1 have no one-bits
+ * in common if and only if X is a power of 2, ie has only one one-bit.
+ * Some compilers may give an "unreachable code" warning here; ignore it.
+ */
+ if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
+ ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
+ /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
+ * a multiple of SIZEOF(ALIGN_TYPE).
+ * Again, an "unreachable code" warning may be ignored here.
+ * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
+ */
+ test_mac = (size_t) MAX_ALLOC_CHUNK;
+ if ((long) test_mac != MAX_ALLOC_CHUNK ||
+ (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
+ ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
+
+ max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
+
+ /* Attempt to allocate memory manager's control block */
+ mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
+
+ if (mem == NULL) {
+ jpeg_mem_term(cinfo); /* system-dependent cleanup */
+ ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
+ }
+
+ /* OK, fill in the method pointers */
+ mem->pub.alloc_small = alloc_small;
+ mem->pub.alloc_large = alloc_large;
+ mem->pub.alloc_sarray = alloc_sarray;
+ mem->pub.alloc_barray = alloc_barray;
+ mem->pub.request_virt_sarray = request_virt_sarray;
+ mem->pub.request_virt_barray = request_virt_barray;
+ mem->pub.realize_virt_arrays = realize_virt_arrays;
+ mem->pub.access_virt_sarray = access_virt_sarray;
+ mem->pub.access_virt_barray = access_virt_barray;
+ mem->pub.free_pool = free_pool;
+ mem->pub.self_destruct = self_destruct;
+
+ /* Initialize working state */
+ mem->pub.max_memory_to_use = max_to_use;
+
+ for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
+ mem->small_list[pool] = NULL;
+ mem->large_list[pool] = NULL;
+ }
+ mem->virt_sarray_list = NULL;
+ mem->virt_barray_list = NULL;
+
+ mem->total_space_allocated = SIZEOF(my_memory_mgr);
+
+ /* Declare ourselves open for business */
+ cinfo->mem = & mem->pub;
+
+ /* Check for an environment variable JPEGMEM; if found, override the
+ * default max_memory setting from jpeg_mem_init. Note that the
+ * surrounding application may again override this value.
+ * If your system doesn't support getenv(), define NO_GETENV to disable
+ * this feature.
+ */
+#ifndef NO_GETENV
+ { char * memenv;
+
+ if ((memenv = getenv("JPEGMEM")) != NULL) {
+ char ch = 'x';
+
+ if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
+ if (ch == 'm' || ch == 'M')
+ max_to_use *= 1000L;
+ mem->pub.max_memory_to_use = max_to_use * 1000L;
+ }
+ }
+ }
+#endif
+
+}
diff --git a/libs/jpeg6/jmemnobs.cpp b/libs/jpeg6/jmemnobs.cpp
new file mode 100755
index 0000000..e63e5e4
--- /dev/null
+++ b/libs/jpeg6/jmemnobs.cpp
@@ -0,0 +1,103 @@
+/*
+ * jmemnobs.c
+ *
+ * Copyright (C) 1992-1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file provides a really simple implementation of the system-
+ * dependent portion of the JPEG memory manager. This implementation
+ * assumes that no backing-store files are needed: all required space
+ * can be obtained from ri.Malloc().
+ * This is very portable in the sense that it'll compile on almost anything,
+ * but you'd better have lots of main memory (or virtual memory) if you want
+ * to process big images.
+ * Note that the max_memory_to_use option is ignored by this implementation.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jmemsys.h" /* import the system-dependent declarations */
+
+/*
+ * Memory allocation and ri.Freeing are controlled by the regular library
+ * routines ri.Malloc() and ri.Free().
+ */
+
+GLOBAL void *
+jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
+{
+ return (void *) malloc(sizeofobject);
+}
+
+GLOBAL void
+jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
+{
+ free(object);
+}
+
+
+/*
+ * "Large" objects are treated the same as "small" ones.
+ * NB: although we include FAR keywords in the routine declarations,
+ * this file won't actually work in 80x86 small/medium model; at least,
+ * you probably won't be able to process useful-size images in only 64KB.
+ */
+
+GLOBAL void FAR *
+jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
+{
+ return (void FAR *) malloc(sizeofobject);
+}
+
+GLOBAL void
+jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
+{
+ free(object);
+}
+
+
+/*
+ * This routine computes the total memory space available for allocation.
+ * Here we always say, "we got all you want bud!"
+ */
+
+GLOBAL long
+jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
+ long max_bytes_needed, long already_allocated)
+{
+ return max_bytes_needed;
+}
+
+
+/*
+ * Backing store (temporary file) management.
+ * Since jpeg_mem_available always promised the moon,
+ * this should never be called and we can just error out.
+ */
+
+GLOBAL void
+jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info,
+ long total_bytes_needed)
+{
+ ERREXIT(cinfo, JERR_NO_BACKING_STORE);
+}
+
+
+/*
+ * These routines take care of any system-dependent initialization and
+ * cleanup required. Here, there isn't any.
+ */
+
+GLOBAL long
+jpeg_mem_init (j_common_ptr cinfo)
+{
+ return 0; /* just set max_memory_to_use to 0 */
+}
+
+GLOBAL void
+jpeg_mem_term (j_common_ptr cinfo)
+{
+ /* no work */
+}
diff --git a/libs/jpeg6/jmemsys.h b/libs/jpeg6/jmemsys.h
new file mode 100755
index 0000000..0c7d7c1
--- /dev/null
+++ b/libs/jpeg6/jmemsys.h
@@ -0,0 +1,182 @@
+/*
+ * jmemsys.h
+ *
+ * Copyright (C) 1992-1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This include file defines the interface between the system-independent
+ * and system-dependent portions of the JPEG memory manager. No other
+ * modules need include it. (The system-independent portion is jmemmgr.c;
+ * there are several different versions of the system-dependent portion.)
+ *
+ * This file works as-is for the system-dependent memory managers supplied
+ * in the IJG distribution. You may need to modify it if you write a
+ * custom memory manager. If system-dependent changes are needed in
+ * this file, the best method is to #ifdef them based on a configuration
+ * symbol supplied in jconfig.h, as we have done with USE_MSDOS_MEMMGR.
+ */
+
+
+/* Short forms of external names for systems with brain-damaged linkers. */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jpeg_get_small jGetSmall
+#define jpeg_free_small jFreeSmall
+#define jpeg_get_large jGetLarge
+#define jpeg_free_large jFreeLarge
+#define jpeg_mem_available jMemAvail
+#define jpeg_open_backing_store jOpenBackStore
+#define jpeg_mem_init jMemInit
+#define jpeg_mem_term jMemTerm
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+
+/*
+ * These two functions are used to allocate and release small chunks of
+ * memory. (Typically the total amount requested through jpeg_get_small is
+ * no more than 20K or so; this will be requested in chunks of a few K each.)
+ * Behavior should be the same as for the standard library functions malloc
+ * and free; in particular, jpeg_get_small must return NULL on failure.
+ * On most systems, these ARE malloc and free. jpeg_free_small is passed the
+ * size of the object being freed, just in case it's needed.
+ * On an 80x86 machine using small-data memory model, these manage near heap.
+ */
+
+EXTERN void * jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
+EXTERN void jpeg_free_small JPP((j_common_ptr cinfo, void * object,
+ size_t sizeofobject));
+
+/*
+ * These two functions are used to allocate and release large chunks of
+ * memory (up to the total free space designated by jpeg_mem_available).
+ * The interface is the same as above, except that on an 80x86 machine,
+ * far pointers are used. On most other machines these are identical to
+ * the jpeg_get/free_small routines; but we keep them separate anyway,
+ * in case a different allocation strategy is desirable for large chunks.
+ */
+
+EXTERN void FAR * jpeg_get_large JPP((j_common_ptr cinfo,size_t sizeofobject));
+EXTERN void jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
+ size_t sizeofobject));
+
+/*
+ * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
+ * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
+ * matter, but that case should never come into play). This macro is needed
+ * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
+ * On those machines, we expect that jconfig.h will provide a proper value.
+ * On machines with 32-bit flat address spaces, any large constant may be used.
+ *
+ * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
+ * size_t and will be a multiple of sizeof(align_type).
+ */
+
+#ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
+#define MAX_ALLOC_CHUNK 1000000000L
+#endif
+
+/*
+ * This routine computes the total space still available for allocation by
+ * jpeg_get_large. If more space than this is needed, backing store will be
+ * used. NOTE: any memory already allocated must not be counted.
+ *
+ * There is a minimum space requirement, corresponding to the minimum
+ * feasible buffer sizes; jmemmgr.c will request that much space even if
+ * jpeg_mem_available returns zero. The maximum space needed, enough to hold
+ * all working storage in memory, is also passed in case it is useful.
+ * Finally, the total space already allocated is passed. If no better
+ * method is available, cinfo->mem->max_memory_to_use - already_allocated
+ * is often a suitable calculation.
+ *
+ * It is OK for jpeg_mem_available to underestimate the space available
+ * (that'll just lead to more backing-store access than is really necessary).
+ * However, an overestimate will lead to failure. Hence it's wise to subtract
+ * a slop factor from the true available space. 5% should be enough.
+ *
+ * On machines with lots of virtual memory, any large constant may be returned.
+ * Conversely, zero may be returned to always use the minimum amount of memory.
+ */
+
+EXTERN long jpeg_mem_available JPP((j_common_ptr cinfo,
+ long min_bytes_needed,
+ long max_bytes_needed,
+ long already_allocated));
+
+
+/*
+ * This structure holds whatever state is needed to access a single
+ * backing-store object. The read/write/close method pointers are called
+ * by jmemmgr.c to manipulate the backing-store object; all other fields
+ * are private to the system-dependent backing store routines.
+ */
+
+#define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
+
+#ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
+
+typedef unsigned short XMSH; /* type of extended-memory handles */
+typedef unsigned short EMSH; /* type of expanded-memory handles */
+
+typedef union {
+ short file_handle; /* DOS file handle if it's a temp file */
+ XMSH xms_handle; /* handle if it's a chunk of XMS */
+ EMSH ems_handle; /* handle if it's a chunk of EMS */
+} handle_union;
+
+#endif /* USE_MSDOS_MEMMGR */
+
+typedef struct backing_store_struct * backing_store_ptr;
+
+typedef struct backing_store_struct {
+ /* Methods for reading/writing/closing this backing-store object */
+ JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
+ backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count));
+ JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
+ backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count));
+ JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
+ backing_store_ptr info));
+
+ /* Private fields for system-dependent backing-store management */
+#ifdef USE_MSDOS_MEMMGR
+ /* For the MS-DOS manager (jmemdos.c), we need: */
+ handle_union handle; /* reference to backing-store storage object */
+ char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
+#else
+ /* For a typical implementation with temp files, we need: */
+ FILE * temp_file; /* stdio reference to temp file */
+ char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
+#endif
+} backing_store_info;
+
+/*
+ * Initial opening of a backing-store object. This must fill in the
+ * read/write/close pointers in the object. The read/write routines
+ * may take an error exit if the specified maximum file size is exceeded.
+ * (If jpeg_mem_available always returns a large value, this routine can
+ * just take an error exit.)
+ */
+
+EXTERN void jpeg_open_backing_store JPP((j_common_ptr cinfo,
+ backing_store_ptr info,
+ long total_bytes_needed));
+
+
+/*
+ * These routines take care of any system-dependent initialization and
+ * cleanup required. jpeg_mem_init will be called before anything is
+ * allocated (and, therefore, nothing in cinfo is of use except the error
+ * manager pointer). It should return a suitable default value for
+ * max_memory_to_use; this may subsequently be overridden by the surrounding
+ * application. (Note that max_memory_to_use is only important if
+ * jpeg_mem_available chooses to consult it ... no one else will.)
+ * jpeg_mem_term may assume that all requested memory has been freed and that
+ * all opened backing-store objects have been closed.
+ */
+
+EXTERN long jpeg_mem_init JPP((j_common_ptr cinfo));
+EXTERN void jpeg_mem_term JPP((j_common_ptr cinfo));
diff --git a/libs/jpeg6/jmorecfg.h b/libs/jpeg6/jmorecfg.h
new file mode 100755
index 0000000..d451399
--- /dev/null
+++ b/libs/jpeg6/jmorecfg.h
@@ -0,0 +1,346 @@
+/*
+ * jmorecfg.h
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains additional configuration options that customize the
+ * JPEG software for special applications or support machine-dependent
+ * optimizations. Most users will not need to touch this file.
+ */
+
+
+/*
+ * Define BITS_IN_JSAMPLE as either
+ * 8 for 8-bit sample values (the usual setting)
+ * 12 for 12-bit sample values
+ * Only 8 and 12 are legal data precisions for lossy JPEG according to the
+ * JPEG standard, and the IJG code does not support anything else!
+ * We do not support run-time selection of data precision, sorry.
+ */
+
+#define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
+
+
+/*
+ * Maximum number of components (color channels) allowed in JPEG image.
+ * To meet the letter of the JPEG spec, set this to 255. However, darn
+ * few applications need more than 4 channels (maybe 5 for CMYK + alpha
+ * mask). We recommend 10 as a reasonable compromise; use 4 if you are
+ * really short on memory. (Each allowed component costs a hundred or so
+ * bytes of storage, whether actually used in an image or not.)
+ */
+
+#define MAX_COMPONENTS 10 /* maximum number of image components */
+
+
+/*
+ * Basic data types.
+ * You may need to change these if you have a machine with unusual data
+ * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
+ * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
+ * but it had better be at least 16.
+ */
+
+/* Representation of a single sample (pixel element value).
+ * We frequently allocate large arrays of these, so it's important to keep
+ * them small. But if you have memory to burn and access to char or short
+ * arrays is very slow on your hardware, you might want to change these.
+ */
+
+#if BITS_IN_JSAMPLE == 8
+/* JSAMPLE should be the smallest type that will hold the values 0..255.
+ * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
+ */
+
+#ifdef HAVE_UNSIGNED_CHAR
+
+typedef unsigned char JSAMPLE;
+#define GETJSAMPLE(value) ((int) (value))
+
+#else /* not HAVE_UNSIGNED_CHAR */
+
+typedef char JSAMPLE;
+#ifdef CHAR_IS_UNSIGNED
+#define GETJSAMPLE(value) ((int) (value))
+#else
+#define GETJSAMPLE(value) ((int) (value) & 0xFF)
+#endif /* CHAR_IS_UNSIGNED */
+
+#endif /* HAVE_UNSIGNED_CHAR */
+
+#define MAXJSAMPLE 255
+#define CENTERJSAMPLE 128
+
+#endif /* BITS_IN_JSAMPLE == 8 */
+
+
+#if BITS_IN_JSAMPLE == 12
+/* JSAMPLE should be the smallest type that will hold the values 0..4095.
+ * On nearly all machines "short" will do nicely.
+ */
+
+typedef short JSAMPLE;
+#define GETJSAMPLE(value) ((int) (value))
+
+#define MAXJSAMPLE 4095
+#define CENTERJSAMPLE 2048
+
+#endif /* BITS_IN_JSAMPLE == 12 */
+
+
+/* Representation of a DCT frequency coefficient.
+ * This should be a signed value of at least 16 bits; "short" is usually OK.
+ * Again, we allocate large arrays of these, but you can change to int
+ * if you have memory to burn and "short" is really slow.
+ */
+
+typedef short JCOEF;
+
+
+/* Compressed datastreams are represented as arrays of JOCTET.
+ * These must be EXACTLY 8 bits wide, at least once they are written to
+ * external storage. Note that when using the stdio data source/destination
+ * managers, this is also the data type passed to fread/fwrite.
+ */
+
+#ifdef HAVE_UNSIGNED_CHAR
+
+typedef unsigned char JOCTET;
+#define GETJOCTET(value) (value)
+
+#else /* not HAVE_UNSIGNED_CHAR */
+
+typedef char JOCTET;
+#ifdef CHAR_IS_UNSIGNED
+#define GETJOCTET(value) (value)
+#else
+#define GETJOCTET(value) ((value) & 0xFF)
+#endif /* CHAR_IS_UNSIGNED */
+
+#endif /* HAVE_UNSIGNED_CHAR */
+
+
+/* These typedefs are used for various table entries and so forth.
+ * They must be at least as wide as specified; but making them too big
+ * won't cost a huge amount of memory, so we don't provide special
+ * extraction code like we did for JSAMPLE. (In other words, these
+ * typedefs live at a different point on the speed/space tradeoff curve.)
+ */
+
+/* UINT8 must hold at least the values 0..255. */
+
+#ifdef HAVE_UNSIGNED_CHAR
+typedef unsigned char UINT8;
+#else /* not HAVE_UNSIGNED_CHAR */
+#ifdef CHAR_IS_UNSIGNED
+typedef char UINT8;
+#else /* not CHAR_IS_UNSIGNED */
+typedef short UINT8;
+#endif /* CHAR_IS_UNSIGNED */
+#endif /* HAVE_UNSIGNED_CHAR */
+
+/* UINT16 must hold at least the values 0..65535. */
+
+#ifdef HAVE_UNSIGNED_SHORT
+typedef unsigned short UINT16;
+#else /* not HAVE_UNSIGNED_SHORT */
+typedef unsigned int UINT16;
+#endif /* HAVE_UNSIGNED_SHORT */
+
+/* INT16 must hold at least the values -32768..32767. */
+
+#ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
+typedef short INT16;
+#endif
+
+/* INT32 must hold at least signed 32-bit values. */
+
+//#ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
+//typedef long INT32;
+//#endif
+
+/* Datatype used for image dimensions. The JPEG standard only supports
+ * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
+ * "unsigned int" is sufficient on all machines. However, if you need to
+ * handle larger images and you don't mind deviating from the spec, you
+ * can change this datatype.
+ */
+
+typedef unsigned int JDIMENSION;
+
+#define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
+
+
+/* These defines are used in all function definitions and extern declarations.
+ * You could modify them if you need to change function linkage conventions.
+ * Another application is to make all functions global for use with debuggers
+ * or code profilers that require it.
+ */
+
+#define METHODDEF static /* a function called through method pointers */
+#define LOCAL static /* a function used only in its module */
+#define GLOBAL /* a function referenced thru EXTERNs */
+#define EXTERN extern /* a reference to a GLOBAL function */
+
+
+/* Here is the pseudo-keyword for declaring pointers that must be "far"
+ * on 80x86 machines. Most of the specialized coding for 80x86 is handled
+ * by just saying "FAR *" where such a pointer is needed. In a few places
+ * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
+ */
+
+#ifdef NEED_FAR_POINTERS
+#undef FAR
+#define FAR far
+#else
+#undef FAR
+#define FAR
+#endif
+
+
+/*
+ * On a few systems, type boolean and/or its values FALSE, TRUE may appear
+ * in standard header files. Or you may have conflicts with application-
+ * specific header files that you want to include together with these files.
+ * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
+ */
+
+//#ifndef HAVE_BOOLEAN
+//typedef int boolean;
+//#endif
+#ifndef FALSE /* in case these macros already exist */
+#define FALSE 0 /* values of boolean */
+#endif
+#ifndef TRUE
+#define TRUE 1
+#endif
+
+
+/*
+ * The remaining options affect code selection within the JPEG library,
+ * but they don't need to be visible to most applications using the library.
+ * To minimize application namespace pollution, the symbols won't be
+ * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
+ */
+
+#ifdef JPEG_INTERNALS
+#define JPEG_INTERNAL_OPTIONS
+#endif
+
+#ifdef JPEG_INTERNAL_OPTIONS
+
+
+/*
+ * These defines indicate whether to include various optional functions.
+ * Undefining some of these symbols will produce a smaller but less capable
+ * library. Note that you can leave certain source files out of the
+ * compilation/linking process if you've #undef'd the corresponding symbols.
+ * (You may HAVE to do that if your compiler doesn't like null source files.)
+ */
+
+/* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
+
+/* Capability options common to encoder and decoder: */
+
+#undef DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
+#undef DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
+#define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
+
+/* Encoder capability options: */
+
+#undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
+#define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
+#define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
+#define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
+/* Note: if you selected 12-bit data precision, it is dangerous to turn off
+ * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
+ * precision, so jchuff.c normally uses entropy optimization to compute
+ * usable tables for higher precision. If you don't want to do optimization,
+ * you'll have to supply different default Huffman tables.
+ * The exact same statements apply for progressive JPEG: the default tables
+ * don't work for progressive mode. (This may get fixed, however.)
+ */
+#define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
+
+/* Decoder capability options: */
+
+#undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
+#undef D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
+#undef D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
+#undef BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
+#undef IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
+#undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
+#undef UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
+#undef QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
+#undef QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
+
+/* more capability options later, no doubt */
+
+
+/*
+ * Ordering of RGB data in scanlines passed to or from the application.
+ * If your application wants to deal with data in the order B,G,R, just
+ * change these macros. You can also deal with formats such as R,G,B,X
+ * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
+ * the offsets will also change the order in which colormap data is organized.
+ * RESTRICTIONS:
+ * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
+ * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
+ * useful if you are using JPEG color spaces other than YCbCr or grayscale.
+ * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
+ * is not 3 (they don't understand about dummy color components!). So you
+ * can't use color quantization if you change that value.
+ */
+
+#define RGB_RED 0 /* Offset of Red in an RGB scanline element */
+#define RGB_GREEN 1 /* Offset of Green */
+#define RGB_BLUE 2 /* Offset of Blue */
+#define RGB_PIXELSIZE 4 /* JSAMPLEs per RGB scanline element */
+
+
+/* Definitions for speed-related optimizations. */
+
+
+/* If your compiler supports inline functions, define INLINE
+ * as the inline keyword; otherwise define it as empty.
+ */
+
+#ifndef INLINE
+#ifdef __GNUC__ /* for instance, GNU C knows about inline */
+#define INLINE __inline__
+#endif
+#ifndef INLINE
+#define INLINE /* default is to define it as empty */
+#endif
+#endif
+
+
+/* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
+ * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
+ * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
+ */
+
+#ifndef MULTIPLIER
+#define MULTIPLIER int /* type for fastest integer multiply */
+#endif
+
+
+/* FAST_FLOAT should be either float or double, whichever is done faster
+ * by your compiler. (Note that this type is only used in the floating point
+ * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
+ * Typically, float is faster in ANSI C compilers, while double is faster in
+ * pre-ANSI compilers (because they insist on converting to double anyway).
+ * The code below therefore chooses float if we have ANSI-style prototypes.
+ */
+
+#ifndef FAST_FLOAT
+#ifdef HAVE_PROTOTYPES
+#define FAST_FLOAT float
+#else
+#define FAST_FLOAT double
+#endif
+#endif
+
+#endif /* JPEG_INTERNAL_OPTIONS */
diff --git a/libs/jpeg6/jpeg6.vcproj b/libs/jpeg6/jpeg6.vcproj
new file mode 100755
index 0000000..f17e134
--- /dev/null
+++ b/libs/jpeg6/jpeg6.vcproj
@@ -0,0 +1,603 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+ ProjectType="Visual C++"
+ Version="7.10"
+ Name="jpeg6"
+ SccProjectName="&quot;$/source/q3radiant&quot;, FEFAAAAA"
+ SccLocalPath="..\..\q3radiant">
+ <Platforms>
+ <Platform
+ Name="Win32"/>
+ </Platforms>
+ <Configurations>
+ <Configuration
+ Name="Release|Win32"
+ OutputDirectory=".\Release"
+ IntermediateDirectory=".\Release"
+ ConfigurationType="4"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ AdditionalIncludeDirectories=".."
+ PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
+ StringPooling="TRUE"
+ RuntimeLibrary="0"
+ EnableFunctionLevelLinking="TRUE"
+ RuntimeTypeInfo="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Release/jpeg6.pch"
+ AssemblerListingLocation=".\Release/"
+ ObjectFile=".\Release/"
+ ProgramDataBaseFileName=".\Release/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ CompileAs="0"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile="..\jpeg6.lib"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCMIDLTool"/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Debug|Win32"
+ OutputDirectory=".\Debug"
+ IntermediateDirectory=".\Debug"
+ ConfigurationType="4"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=".."
+ PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
+ BasicRuntimeChecks="3"
+ RuntimeLibrary="1"
+ RuntimeTypeInfo="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Debug/jpeg6.pch"
+ AssemblerListingLocation=".\Debug/"
+ ObjectFile=".\Debug/"
+ ProgramDataBaseFileName=".\Debug/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"
+ CompileAs="0"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile="..\jpeg6d.lib"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCMIDLTool"/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ </Configurations>
+ <References>
+ </References>
+ <Files>
+ <Filter
+ Name="Source Files"
+ Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat">
+ <File
+ RelativePath="jcomapi.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="jdapimin.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="jdapistd.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="jdatasrc.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="jdcoefct.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="jdcolor.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="jddctmgr.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="jdhuff.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="jdinput.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="jdmainct.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="jdmarker.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="jdmaster.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="jdpostct.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="jdsample.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="jdtrans.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="jerror.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="jfdctflt.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="jidctflt.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="jmemmgr.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="jmemnobs.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="jpgload.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="jutils.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <Filter
+ Name="Header Files"
+ Filter="h;hpp;hxx;hm;inl">
+ <File
+ RelativePath="jchuff.h">
+ </File>
+ <File
+ RelativePath="jconfig.h">
+ </File>
+ <File
+ RelativePath="jdct.h">
+ </File>
+ <File
+ RelativePath="jdhuff.h">
+ </File>
+ <File
+ RelativePath="jerror.h">
+ </File>
+ <File
+ RelativePath="jinclude.h">
+ </File>
+ <File
+ RelativePath="jmemsys.h">
+ </File>
+ <File
+ RelativePath="jmorecfg.h">
+ </File>
+ <File
+ RelativePath="jpegint.h">
+ </File>
+ <File
+ RelativePath="jversion.h">
+ </File>
+ </Filter>
+ </Files>
+ <Globals>
+ </Globals>
+</VisualStudioProject>
diff --git a/libs/jpeg6/jpegint.h b/libs/jpeg6/jpegint.h
new file mode 100755
index 0000000..b3b6a6d
--- /dev/null
+++ b/libs/jpeg6/jpegint.h
@@ -0,0 +1,388 @@
+/*
+ * jpegint.h
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file provides common declarations for the various JPEG modules.
+ * These declarations are considered internal to the JPEG library; most
+ * applications using the library shouldn't need to include this file.
+ */
+
+
+/* Declarations for both compression & decompression */
+
+typedef enum { /* Operating modes for buffer controllers */
+ JBUF_PASS_THRU, /* Plain stripwise operation */
+ /* Remaining modes require a full-image buffer to have been created */
+ JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
+ JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
+ JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
+} J_BUF_MODE;
+
+/* Values of global_state field (jdapi.c has some dependencies on ordering!) */
+#define CSTATE_START 100 /* after create_compress */
+#define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
+#define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
+#define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
+#define DSTATE_START 200 /* after create_decompress */
+#define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
+#define DSTATE_READY 202 /* found SOS, ready for start_decompress */
+#define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
+#define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
+#define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
+#define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
+#define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
+#define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
+#define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
+#define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
+
+
+/* Declarations for compression modules */
+
+/* Master control module */
+struct jpeg_comp_master {
+ JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
+ JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
+ JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
+
+ /* State variables made visible to other modules */
+ boolean call_pass_startup; /* True if pass_startup must be called */
+ boolean is_last_pass; /* True during last pass */
+};
+
+/* Main buffer control (downsampled-data buffer) */
+struct jpeg_c_main_controller {
+ JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
+ JMETHOD(void, process_data, (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
+ JDIMENSION in_rows_avail));
+};
+
+/* Compression preprocessing (downsampling input buffer control) */
+struct jpeg_c_prep_controller {
+ JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
+ JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf,
+ JDIMENSION *in_row_ctr,
+ JDIMENSION in_rows_avail,
+ JSAMPIMAGE output_buf,
+ JDIMENSION *out_row_group_ctr,
+ JDIMENSION out_row_groups_avail));
+};
+
+/* Coefficient buffer control */
+struct jpeg_c_coef_controller {
+ JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
+ JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
+ JSAMPIMAGE input_buf));
+};
+
+/* Colorspace conversion */
+struct jpeg_color_converter {
+ JMETHOD(void, start_pass, (j_compress_ptr cinfo));
+ JMETHOD(void, color_convert, (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+ JDIMENSION output_row, int num_rows));
+};
+
+/* Downsampling */
+struct jpeg_downsampler {
+ JMETHOD(void, start_pass, (j_compress_ptr cinfo));
+ JMETHOD(void, downsample, (j_compress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION in_row_index,
+ JSAMPIMAGE output_buf,
+ JDIMENSION out_row_group_index));
+
+ boolean need_context_rows; /* TRUE if need rows above & below */
+};
+
+/* Forward DCT (also controls coefficient quantization) */
+struct jpeg_forward_dct {
+ JMETHOD(void, start_pass, (j_compress_ptr cinfo));
+ /* perhaps this should be an array??? */
+ JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
+ jpeg_component_info * compptr,
+ JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
+ JDIMENSION start_row, JDIMENSION start_col,
+ JDIMENSION num_blocks));
+};
+
+/* Entropy encoding */
+struct jpeg_entropy_encoder {
+ JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
+ JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
+ JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
+};
+
+/* Marker writing */
+struct jpeg_marker_writer {
+ /* write_any_marker is exported for use by applications */
+ /* Probably only COM and APPn markers should be written */
+ JMETHOD(void, write_any_marker, (j_compress_ptr cinfo, int marker,
+ const JOCTET *dataptr, unsigned int datalen));
+ JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
+ JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
+ JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
+ JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
+ JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
+};
+
+
+/* Declarations for decompression modules */
+
+/* Master control module */
+struct jpeg_decomp_master {
+ JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
+ JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
+
+ /* State variables made visible to other modules */
+ boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
+};
+
+/* Input control module */
+struct jpeg_input_controller {
+ JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
+ JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
+ JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
+ JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
+
+ /* State variables made visible to other modules */
+ boolean has_multiple_scans; /* True if file has multiple scans */
+ boolean eoi_reached; /* True when EOI has been consumed */
+};
+
+/* Main buffer control (downsampled-data buffer) */
+struct jpeg_d_main_controller {
+ JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
+ JMETHOD(void, process_data, (j_decompress_ptr cinfo,
+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail));
+};
+
+/* Coefficient buffer control */
+struct jpeg_d_coef_controller {
+ JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
+ JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
+ JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
+ JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
+ JSAMPIMAGE output_buf));
+ /* Pointer to array of coefficient virtual arrays, or NULL if none */
+ jvirt_barray_ptr *coef_arrays;
+};
+
+/* Decompression postprocessing (color quantization buffer control) */
+struct jpeg_d_post_controller {
+ JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
+ JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf,
+ JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY output_buf,
+ JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail));
+};
+
+/* Marker reading & parsing */
+struct jpeg_marker_reader {
+ JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
+ /* Read markers until SOS or EOI.
+ * Returns same codes as are defined for jpeg_consume_input:
+ * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
+ */
+ JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
+ /* Read a restart marker --- exported for use by entropy decoder only */
+ jpeg_marker_parser_method read_restart_marker;
+ /* Application-overridable marker processing methods */
+ jpeg_marker_parser_method process_COM;
+ jpeg_marker_parser_method process_APPn[16];
+
+ /* State of marker reader --- nominally internal, but applications
+ * supplying COM or APPn handlers might like to know the state.
+ */
+ boolean saw_SOI; /* found SOI? */
+ boolean saw_SOF; /* found SOF? */
+ int next_restart_num; /* next restart number expected (0-7) */
+ unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
+};
+
+/* Entropy decoding */
+struct jpeg_entropy_decoder {
+ JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
+ JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
+ JBLOCKROW *MCU_data));
+};
+
+/* Inverse DCT (also performs dequantization) */
+typedef JMETHOD(void, inverse_DCT_method_ptr,
+ (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block,
+ JSAMPARRAY output_buf, JDIMENSION output_col));
+
+struct jpeg_inverse_dct {
+ JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
+ /* It is useful to allow each component to have a separate IDCT method. */
+ inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
+};
+
+/* Upsampling (note that upsampler must also call color converter) */
+struct jpeg_upsampler {
+ JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
+ JMETHOD(void, upsample, (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf,
+ JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY output_buf,
+ JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail));
+
+ boolean need_context_rows; /* TRUE if need rows above & below */
+};
+
+/* Colorspace conversion */
+struct jpeg_color_deconverter {
+ JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
+ JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
+ JSAMPIMAGE input_buf, JDIMENSION input_row,
+ JSAMPARRAY output_buf, int num_rows));
+};
+
+/* Color quantization or color precision reduction */
+struct jpeg_color_quantizer {
+ JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
+ JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPARRAY output_buf,
+ int num_rows));
+ JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
+ JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
+};
+
+
+/* Miscellaneous useful macros */
+
+#undef MAX
+#define MAX(a,b) ((a) > (b) ? (a) : (b))
+#undef MIN
+#define MIN(a,b) ((a) < (b) ? (a) : (b))
+
+
+/* We assume that right shift corresponds to signed division by 2 with
+ * rounding towards minus infinity. This is correct for typical "arithmetic
+ * shift" instructions that shift in copies of the sign bit. But some
+ * C compilers implement >> with an unsigned shift. For these machines you
+ * must define RIGHT_SHIFT_IS_UNSIGNED.
+ * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
+ * It is only applied with constant shift counts. SHIFT_TEMPS must be
+ * included in the variables of any routine using RIGHT_SHIFT.
+ */
+
+#ifdef RIGHT_SHIFT_IS_UNSIGNED
+#define SHIFT_TEMPS INT32 shift_temp;
+#define RIGHT_SHIFT(x,shft) \
+ ((shift_temp = (x)) < 0 ? \
+ (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
+ (shift_temp >> (shft)))
+#else
+#define SHIFT_TEMPS
+#define RIGHT_SHIFT(x,shft) ((x) >> (shft))
+#endif
+
+
+/* Short forms of external names for systems with brain-damaged linkers. */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jinit_compress_master jICompress
+#define jinit_c_master_control jICMaster
+#define jinit_c_main_controller jICMainC
+#define jinit_c_prep_controller jICPrepC
+#define jinit_c_coef_controller jICCoefC
+#define jinit_color_converter jICColor
+#define jinit_downsampler jIDownsampler
+#define jinit_forward_dct jIFDCT
+#define jinit_huff_encoder jIHEncoder
+#define jinit_phuff_encoder jIPHEncoder
+#define jinit_marker_writer jIMWriter
+#define jinit_master_decompress jIDMaster
+#define jinit_d_main_controller jIDMainC
+#define jinit_d_coef_controller jIDCoefC
+#define jinit_d_post_controller jIDPostC
+#define jinit_input_controller jIInCtlr
+#define jinit_marker_reader jIMReader
+#define jinit_huff_decoder jIHDecoder
+#define jinit_phuff_decoder jIPHDecoder
+#define jinit_inverse_dct jIIDCT
+#define jinit_upsampler jIUpsampler
+#define jinit_color_deconverter jIDColor
+#define jinit_1pass_quantizer jI1Quant
+#define jinit_2pass_quantizer jI2Quant
+#define jinit_merged_upsampler jIMUpsampler
+#define jinit_memory_mgr jIMemMgr
+#define jdiv_round_up jDivRound
+#define jround_up jRound
+#define jcopy_sample_rows jCopySamples
+#define jcopy_block_row jCopyBlocks
+#define jzero_far jZeroFar
+#define jpeg_zigzag_order jZIGTable
+#define jpeg_natural_order jZAGTable
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+
+/* Compression module initialization routines */
+EXTERN void jinit_compress_master JPP((j_compress_ptr cinfo));
+EXTERN void jinit_c_master_control JPP((j_compress_ptr cinfo,
+ boolean transcode_only));
+EXTERN void jinit_c_main_controller JPP((j_compress_ptr cinfo,
+ boolean need_full_buffer));
+EXTERN void jinit_c_prep_controller JPP((j_compress_ptr cinfo,
+ boolean need_full_buffer));
+EXTERN void jinit_c_coef_controller JPP((j_compress_ptr cinfo,
+ boolean need_full_buffer));
+EXTERN void jinit_color_converter JPP((j_compress_ptr cinfo));
+EXTERN void jinit_downsampler JPP((j_compress_ptr cinfo));
+EXTERN void jinit_forward_dct JPP((j_compress_ptr cinfo));
+EXTERN void jinit_huff_encoder JPP((j_compress_ptr cinfo));
+EXTERN void jinit_phuff_encoder JPP((j_compress_ptr cinfo));
+EXTERN void jinit_marker_writer JPP((j_compress_ptr cinfo));
+/* Decompression module initialization routines */
+EXTERN void jinit_master_decompress JPP((j_decompress_ptr cinfo));
+EXTERN void jinit_d_main_controller JPP((j_decompress_ptr cinfo,
+ boolean need_full_buffer));
+EXTERN void jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
+ boolean need_full_buffer));
+EXTERN void jinit_d_post_controller JPP((j_decompress_ptr cinfo,
+ boolean need_full_buffer));
+EXTERN void jinit_input_controller JPP((j_decompress_ptr cinfo));
+EXTERN void jinit_marker_reader JPP((j_decompress_ptr cinfo));
+EXTERN void jinit_huff_decoder JPP((j_decompress_ptr cinfo));
+EXTERN void jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
+EXTERN void jinit_inverse_dct JPP((j_decompress_ptr cinfo));
+EXTERN void jinit_upsampler JPP((j_decompress_ptr cinfo));
+EXTERN void jinit_color_deconverter JPP((j_decompress_ptr cinfo));
+EXTERN void jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
+EXTERN void jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
+EXTERN void jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
+/* Memory manager initialization */
+EXTERN void jinit_memory_mgr JPP((j_common_ptr cinfo));
+
+/* Utility routines in jutils.c */
+EXTERN long jdiv_round_up JPP((long a, long b));
+EXTERN long jround_up JPP((long a, long b));
+EXTERN void jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
+ JSAMPARRAY output_array, int dest_row,
+ int num_rows, JDIMENSION num_cols));
+EXTERN void jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
+ JDIMENSION num_blocks));
+EXTERN void jzero_far JPP((void FAR * target, size_t bytestozero));
+/* Constant tables in jutils.c */
+extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
+extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
+
+/* Suppress undefined-structure complaints if necessary. */
+
+#ifdef INCOMPLETE_TYPES_BROKEN
+#ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
+struct jvirt_sarray_control { long dummy; };
+struct jvirt_barray_control { long dummy; };
+#endif
+#endif /* INCOMPLETE_TYPES_BROKEN */
diff --git a/libs/jpeg6/jpgload.cpp b/libs/jpeg6/jpgload.cpp
new file mode 100755
index 0000000..1006b99
--- /dev/null
+++ b/libs/jpeg6/jpgload.cpp
@@ -0,0 +1,142 @@
+
+
+#include "jpeglib.h"
+#include <memory.h>
+
+GLOBAL void LoadJPGBuff(unsigned char *fbuffer, unsigned char **pic, int *width, int *height )
+{
+ /* This struct contains the JPEG decompression parameters and pointers to
+ * working space (which is allocated as needed by the JPEG library).
+ */
+ struct jpeg_decompress_struct cinfo;
+ /* We use our private extension JPEG error handler.
+ * Note that this struct must live as long as the main JPEG parameter
+ * struct, to avoid dangling-pointer problems.
+ */
+ /* This struct represents a JPEG error handler. It is declared separately
+ * because applications often want to supply a specialized error handler
+ * (see the second half of this file for an example). But here we just
+ * take the easy way out and use the standard error handler, which will
+ * print a message on stderr and call exit() if compression fails.
+ * Note that this struct must live as long as the main JPEG parameter
+ * struct, to avoid dangling-pointer problems.
+ */
+
+ struct jpeg_error_mgr jerr;
+ /* More stuff */
+ JSAMPARRAY buffer; /* Output row buffer */
+ int row_stride; /* physical row width in output buffer */
+ unsigned char *out;
+ byte *bbuf;
+ int nSize;
+
+ /* Step 1: allocate and initialize JPEG decompression object */
+
+ /* We have to set up the error handler first, in case the initialization
+ * step fails. (Unlikely, but it could happen if you are out of memory.)
+ * This routine fills in the contents of struct jerr, and returns jerr's
+ * address which we place into the link field in cinfo.
+ */
+ cinfo.err = jpeg_std_error(&jerr);
+
+ /* Now we can initialize the JPEG decompression object. */
+ jpeg_create_decompress(&cinfo);
+
+ /* Step 2: specify data source (eg, a file) */
+
+ jpeg_stdio_src(&cinfo, fbuffer);
+
+ /* Step 3: read file parameters with jpeg_read_header() */
+
+ (void) jpeg_read_header(&cinfo, TRUE);
+ /* We can ignore the return value from jpeg_read_header since
+ * (a) suspension is not possible with the stdio data source, and
+ * (b) we passed TRUE to reject a tables-only JPEG file as an error.
+ * See libjpeg.doc for more info.
+ */
+
+ /* Step 4: set parameters for decompression */
+
+ /* In this example, we don't need to change any of the defaults set by
+ * jpeg_read_header(), so we do nothing here.
+ */
+
+ /* Step 5: Start decompressor */
+
+ (void) jpeg_start_decompress(&cinfo);
+ /* We can ignore the return value since suspension is not possible
+ * with the stdio data source.
+ */
+
+ /* We may need to do some setup of our own at this point before reading
+ * the data. After jpeg_start_decompress() we have the correct scaled
+ * output image dimensions available, as well as the output colormap
+ * if we asked for color quantization.
+ * In this example, we need to make an output work buffer of the right size.
+ */
+ /* JSAMPLEs per row in output buffer */
+ row_stride = cinfo.output_width * cinfo.output_components;
+
+ nSize = cinfo.output_width*cinfo.output_height*cinfo.output_components;
+ out = reinterpret_cast<unsigned char*>(malloc(nSize+1));
+ memset(out, 0, nSize+1);
+
+ *pic = out;
+ *width = cinfo.output_width;
+ *height = cinfo.output_height;
+
+ /* Step 6: while (scan lines remain to be read) */
+ /* jpeg_read_scanlines(...); */
+
+ /* Here we use the library's state variable cinfo.output_scanline as the
+ * loop counter, so that we don't have to keep track ourselves.
+ */
+ while (cinfo.output_scanline < cinfo.output_height) {
+ /* jpeg_read_scanlines expects an array of pointers to scanlines.
+ * Here the array is only one element long, but you could ask for
+ * more than one scanline at a time if that's more convenient.
+ */
+ bbuf = ((out+(row_stride*cinfo.output_scanline)));
+ buffer = &bbuf;
+ (void) jpeg_read_scanlines(&cinfo, buffer, 1);
+ }
+
+ // clear all the alphas to 255
+ {
+ int i, j;
+ byte *buf;
+
+ buf = *pic;
+
+ j = cinfo.output_width * cinfo.output_height * 4;
+ for ( i = 3 ; i < j ; i+=4 ) {
+ buf[i] = 255;
+ }
+ }
+
+ /* Step 7: Finish decompression */
+
+ (void) jpeg_finish_decompress(&cinfo);
+ /* We can ignore the return value since suspension is not possible
+ * with the stdio data source.
+ */
+
+ /* Step 8: Release JPEG decompression object */
+
+ /* This is an important step since it will release a good deal of memory. */
+ jpeg_destroy_decompress(&cinfo);
+
+ /* After finish_decompress, we can close the input file.
+ * Here we postpone it until after no more JPEG errors are possible,
+ * so as to simplify the setjmp error logic above. (Actually, I don't
+ * think that jpeg_destroy can do an error exit, but why assume anything...)
+ */
+ //free (fbuffer);
+
+ /* At this point you may want to check to see whether any corrupt-data
+ * warnings occurred (test whether jerr.pub.num_warnings is nonzero).
+ */
+
+ /* And we're done! */
+}
+
diff --git a/libs/jpeg6/jutils.cpp b/libs/jpeg6/jutils.cpp
new file mode 100755
index 0000000..8e8dc13
--- /dev/null
+++ b/libs/jpeg6/jutils.cpp
@@ -0,0 +1,175 @@
+/*
+ * jutils.c
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains tables and miscellaneous utility routines needed
+ * for both compression and decompression.
+ * Note we prefix all global names with "j" to minimize conflicts with
+ * a surrounding application.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/*
+ * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
+ * of a DCT block read in natural order (left to right, top to bottom).
+ */
+
+const int jpeg_zigzag_order[DCTSIZE2] = {
+ 0, 1, 5, 6, 14, 15, 27, 28,
+ 2, 4, 7, 13, 16, 26, 29, 42,
+ 3, 8, 12, 17, 25, 30, 41, 43,
+ 9, 11, 18, 24, 31, 40, 44, 53,
+ 10, 19, 23, 32, 39, 45, 52, 54,
+ 20, 22, 33, 38, 46, 51, 55, 60,
+ 21, 34, 37, 47, 50, 56, 59, 61,
+ 35, 36, 48, 49, 57, 58, 62, 63
+};
+
+/*
+ * jpeg_natural_order[i] is the natural-order position of the i'th element
+ * of zigzag order.
+ *
+ * When reading corrupted data, the Huffman decoders could attempt
+ * to reference an entry beyond the end of this array (if the decoded
+ * zero run length reaches past the end of the block). To prevent
+ * wild stores without adding an inner-loop test, we put some extra
+ * "63"s after the real entries. This will cause the extra coefficient
+ * to be stored in location 63 of the block, not somewhere random.
+ * The worst case would be a run-length of 15, which means we need 16
+ * fake entries.
+ */
+
+const int jpeg_natural_order[DCTSIZE2+16] = {
+ 0, 1, 8, 16, 9, 2, 3, 10,
+ 17, 24, 32, 25, 18, 11, 4, 5,
+ 12, 19, 26, 33, 40, 48, 41, 34,
+ 27, 20, 13, 6, 7, 14, 21, 28,
+ 35, 42, 49, 56, 57, 50, 43, 36,
+ 29, 22, 15, 23, 30, 37, 44, 51,
+ 58, 59, 52, 45, 38, 31, 39, 46,
+ 53, 60, 61, 54, 47, 55, 62, 63,
+ 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
+ 63, 63, 63, 63, 63, 63, 63, 63
+};
+
+
+/*
+ * Arithmetic utilities
+ */
+
+GLOBAL long
+jdiv_round_up (long a, long b)
+/* Compute a/b rounded up to next integer, ie, ceil(a/b) */
+/* Assumes a >= 0, b > 0 */
+{
+ return (a + b - 1L) / b;
+}
+
+
+GLOBAL long
+jround_up (long a, long b)
+/* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
+/* Assumes a >= 0, b > 0 */
+{
+ a += b - 1L;
+ return a - (a % b);
+}
+
+
+/* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
+ * and coefficient-block arrays. This won't work on 80x86 because the arrays
+ * are FAR and we're assuming a small-pointer memory model. However, some
+ * DOS compilers provide far-pointer versions of memcpy() and memset() even
+ * in the small-model libraries. These will be used if USE_FMEM is defined.
+ * Otherwise, the routines below do it the hard way. (The performance cost
+ * is not all that great, because these routines aren't very heavily used.)
+ */
+
+#ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
+#define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
+#define FMEMZERO(target,size) MEMZERO(target,size)
+#else /* 80x86 case, define if we can */
+#ifdef USE_FMEM
+#define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
+#define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
+#endif
+#endif
+
+
+GLOBAL void
+jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
+ JSAMPARRAY output_array, int dest_row,
+ int num_rows, JDIMENSION num_cols)
+/* Copy some rows of samples from one place to another.
+ * num_rows rows are copied from input_array[source_row++]
+ * to output_array[dest_row++]; these areas may overlap for duplication.
+ * The source and destination arrays must be at least as wide as num_cols.
+ */
+{
+ register JSAMPROW inptr, outptr;
+#ifdef FMEMCOPY
+ register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
+#else
+ register JDIMENSION count;
+#endif
+ register int row;
+
+ input_array += source_row;
+ output_array += dest_row;
+
+ for (row = num_rows; row > 0; row--) {
+ inptr = *input_array++;
+ outptr = *output_array++;
+#ifdef FMEMCOPY
+ FMEMCOPY(outptr, inptr, count);
+#else
+ for (count = num_cols; count > 0; count--)
+ *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
+#endif
+ }
+}
+
+
+GLOBAL void
+jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
+ JDIMENSION num_blocks)
+/* Copy a row of coefficient blocks from one place to another. */
+{
+#ifdef FMEMCOPY
+ FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
+#else
+ register JCOEFPTR inptr, outptr;
+ register long count;
+
+ inptr = (JCOEFPTR) input_row;
+ outptr = (JCOEFPTR) output_row;
+ for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
+ *outptr++ = *inptr++;
+ }
+#endif
+}
+
+
+GLOBAL void
+jzero_far (void FAR * target, size_t bytestozero)
+/* Zero out a chunk of FAR memory. */
+/* This might be sample-array data, block-array data, or alloc_large data. */
+{
+#ifdef FMEMZERO
+ FMEMZERO(target, bytestozero);
+#else
+ register char FAR * ptr = (char FAR *) target;
+ register size_t count;
+
+ for (count = bytestozero; count > 0; count--) {
+ *ptr++ = 0;
+ }
+#endif
+}
diff --git a/libs/jpeg6/jversion.h b/libs/jpeg6/jversion.h
new file mode 100755
index 0000000..02083ac
--- /dev/null
+++ b/libs/jpeg6/jversion.h
@@ -0,0 +1,14 @@
+/*
+ * jversion.h
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains software version identification.
+ */
+
+
+#define JVERSION "6 2-Aug-95"
+
+#define JCOPYRIGHT "Copyright (C) 1995, Thomas G. Lane"
diff --git a/libs/jpeglib.h b/libs/jpeglib.h
new file mode 100755
index 0000000..81ca1b4
--- /dev/null
+++ b/libs/jpeglib.h
@@ -0,0 +1,1087 @@
+/*
+ * jpeglib.h
+ *
+ * Copyright (C) 1991-1995, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file defines the application interface for the JPEG library.
+ * Most applications using the library need only include this file,
+ * and perhaps jerror.h if they want to know the exact error codes.
+ */
+
+#ifndef JPEGLIB_H
+#define JPEGLIB_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+
+#ifdef __MACOS__
+
+// JDC: stuff to make mac version compile
+#define boolean qboolean
+#define register
+#define INT32 int
+
+#endif
+
+// rad additions
+// 11.29.99
+
+//#include "cmdlib.h"
+#ifdef _WIN32
+#include "windows.h"
+#include "stdio.h"
+#endif
+
+#ifndef INT32
+#define INT32 int
+#endif
+
+extern void LoadJPGBuff(unsigned char *fbuffer, unsigned char **pic, int *width, int *height );
+// rad end
+
+
+/*
+ * First we include the configuration files that record how this
+ * installation of the JPEG library is set up. jconfig.h can be
+ * generated automatically for many systems. jmorecfg.h contains
+ * manual configuration options that most people need not worry about.
+ */
+
+#ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
+#include "jpeg6/jconfig.h" /* widely used configuration options */
+#endif
+#include "jpeg6/jmorecfg.h" /* seldom changed options */
+
+
+/* Version ID for the JPEG library.
+ * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
+ */
+
+#define JPEG_LIB_VERSION 60 /* Version 6 */
+
+
+/* Various constants determining the sizes of things.
+ * All of these are specified by the JPEG standard, so don't change them
+ * if you want to be compatible.
+ */
+
+#define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
+#define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
+#define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
+#define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
+#define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
+#define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
+#define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
+/* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
+ * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
+ * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
+ * to handle it. We even let you do this from the jconfig.h file. However,
+ * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
+ * sometimes emits noncompliant files doesn't mean you should too.
+ */
+#define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
+#ifndef D_MAX_BLOCKS_IN_MCU
+#define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
+#endif
+
+
+/* This macro is used to declare a "method", that is, a function pointer.
+ * We want to supply prototype parameters if the compiler can cope.
+ * Note that the arglist parameter must be parenthesized!
+ */
+
+#ifdef HAVE_PROTOTYPES
+#define JMETHOD(type,methodname,arglist) type (*methodname) arglist
+#else
+#define JMETHOD(type,methodname,arglist) type (*methodname) ()
+#endif
+
+
+/* Data structures for images (arrays of samples and of DCT coefficients).
+ * On 80x86 machines, the image arrays are too big for near pointers,
+ * but the pointer arrays can fit in near memory.
+ */
+
+typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
+typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
+typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
+
+typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
+typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
+typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
+typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
+
+typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
+
+
+/* Types for JPEG compression parameters and working tables. */
+
+
+/* DCT coefficient quantization tables. */
+
+typedef struct {
+ /* This field directly represents the contents of a JPEG DQT marker.
+ * Note: the values are always given in zigzag order.
+ */
+ UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
+ /* This field is used only during compression. It's initialized FALSE when
+ * the table is created, and set TRUE when it's been output to the file.
+ * You could suppress output of a table by setting this to TRUE.
+ * (See jpeg_suppress_tables for an example.)
+ */
+ boolean sent_table; /* TRUE when table has been output */
+} JQUANT_TBL;
+
+
+/* Huffman coding tables. */
+
+typedef struct {
+ /* These two fields directly represent the contents of a JPEG DHT marker */
+ UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
+ /* length k bits; bits[0] is unused */
+ UINT8 huffval[256]; /* The symbols, in order of incr code length */
+ /* This field is used only during compression. It's initialized FALSE when
+ * the table is created, and set TRUE when it's been output to the file.
+ * You could suppress output of a table by setting this to TRUE.
+ * (See jpeg_suppress_tables for an example.)
+ */
+ boolean sent_table; /* TRUE when table has been output */
+} JHUFF_TBL;
+
+
+/* Basic info about one component (color channel). */
+
+typedef struct {
+ /* These values are fixed over the whole image. */
+ /* For compression, they must be supplied by parameter setup; */
+ /* for decompression, they are read from the SOF marker. */
+ int component_id; /* identifier for this component (0..255) */
+ int component_index; /* its index in SOF or cinfo->comp_info[] */
+ int h_samp_factor; /* horizontal sampling factor (1..4) */
+ int v_samp_factor; /* vertical sampling factor (1..4) */
+ int quant_tbl_no; /* quantization table selector (0..3) */
+ /* These values may vary between scans. */
+ /* For compression, they must be supplied by parameter setup; */
+ /* for decompression, they are read from the SOS marker. */
+ /* The decompressor output side may not use these variables. */
+ int dc_tbl_no; /* DC entropy table selector (0..3) */
+ int ac_tbl_no; /* AC entropy table selector (0..3) */
+
+ /* Remaining fields should be treated as private by applications. */
+
+ /* These values are computed during compression or decompression startup: */
+ /* Component's size in DCT blocks.
+ * Any dummy blocks added to complete an MCU are not counted; therefore
+ * these values do not depend on whether a scan is interleaved or not.
+ */
+ JDIMENSION width_in_blocks;
+ JDIMENSION height_in_blocks;
+ /* Size of a DCT block in samples. Always DCTSIZE for compression.
+ * For decompression this is the size of the output from one DCT block,
+ * reflecting any scaling we choose to apply during the IDCT step.
+ * Values of 1,2,4,8 are likely to be supported. Note that different
+ * components may receive different IDCT scalings.
+ */
+ int DCT_scaled_size;
+ /* The downsampled dimensions are the component's actual, unpadded number
+ * of samples at the main buffer (preprocessing/compression interface), thus
+ * downsampled_width = ceil(image_width * Hi/Hmax)
+ * and similarly for height. For decompression, IDCT scaling is included, so
+ * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
+ */
+ JDIMENSION downsampled_width; /* actual width in samples */
+ JDIMENSION downsampled_height; /* actual height in samples */
+ /* This flag is used only for decompression. In cases where some of the
+ * components will be ignored (eg grayscale output from YCbCr image),
+ * we can skip most computations for the unused components.
+ */
+ boolean component_needed; /* do we need the value of this component? */
+
+ /* These values are computed before starting a scan of the component. */
+ /* The decompressor output side may not use these variables. */
+ int MCU_width; /* number of blocks per MCU, horizontally */
+ int MCU_height; /* number of blocks per MCU, vertically */
+ int MCU_blocks; /* MCU_width * MCU_height */
+ int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
+ int last_col_width; /* # of non-dummy blocks across in last MCU */
+ int last_row_height; /* # of non-dummy blocks down in last MCU */
+
+ /* Saved quantization table for component; NULL if none yet saved.
+ * See jdinput.c comments about the need for this information.
+ * This field is not currently used by the compressor.
+ */
+ JQUANT_TBL * quant_table;
+
+ /* Private per-component storage for DCT or IDCT subsystem. */
+ void * dct_table;
+} jpeg_component_info;
+
+
+/* The script for encoding a multiple-scan file is an array of these: */
+
+typedef struct {
+ int comps_in_scan; /* number of components encoded in this scan */
+ int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
+ int Ss, Se; /* progressive JPEG spectral selection parms */
+ int Ah, Al; /* progressive JPEG successive approx. parms */
+} jpeg_scan_info;
+
+
+/* Known color spaces. */
+
+typedef enum {
+ JCS_UNKNOWN, /* error/unspecified */
+ JCS_GRAYSCALE, /* monochrome */
+ JCS_RGB, /* red/green/blue */
+ JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
+ JCS_CMYK, /* C/M/Y/K */
+ JCS_YCCK /* Y/Cb/Cr/K */
+} J_COLOR_SPACE;
+
+/* DCT/IDCT algorithm options. */
+
+typedef enum {
+ JDCT_ISLOW, /* slow but accurate integer algorithm */
+ JDCT_IFAST, /* faster, less accurate integer method */
+ JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
+} J_DCT_METHOD;
+
+#ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
+#define JDCT_DEFAULT JDCT_ISLOW
+#endif
+#ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
+#define JDCT_FASTEST JDCT_IFAST
+#endif
+
+/* Dithering options for decompression. */
+
+typedef enum {
+ JDITHER_NONE, /* no dithering */
+ JDITHER_ORDERED, /* simple ordered dither */
+ JDITHER_FS /* Floyd-Steinberg error diffusion dither */
+} J_DITHER_MODE;
+
+
+/* Common fields between JPEG compression and decompression master structs. */
+
+#define jpeg_common_fields \
+ struct jpeg_error_mgr * err; /* Error handler module */\
+ struct jpeg_memory_mgr * mem; /* Memory manager module */\
+ struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
+ boolean is_decompressor; /* so common code can tell which is which */\
+ int global_state /* for checking call sequence validity */
+
+/* Routines that are to be used by both halves of the library are declared
+ * to receive a pointer to this structure. There are no actual instances of
+ * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
+ */
+struct jpeg_common_struct {
+ jpeg_common_fields; /* Fields common to both master struct types */
+ /* Additional fields follow in an actual jpeg_compress_struct or
+ * jpeg_decompress_struct. All three structs must agree on these
+ * initial fields! (This would be a lot cleaner in C++.)
+ */
+};
+
+typedef struct jpeg_common_struct * j_common_ptr;
+typedef struct jpeg_compress_struct * j_compress_ptr;
+typedef struct jpeg_decompress_struct * j_decompress_ptr;
+
+
+/* Master record for a compression instance */
+
+struct jpeg_compress_struct {
+ jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
+
+ /* Destination for compressed data */
+ struct jpeg_destination_mgr * dest;
+
+ /* Description of source image --- these fields must be filled in by
+ * outer application before starting compression. in_color_space must
+ * be correct before you can even call jpeg_set_defaults().
+ */
+
+ JDIMENSION image_width; /* input image width */
+ JDIMENSION image_height; /* input image height */
+ int input_components; /* # of color components in input image */
+ J_COLOR_SPACE in_color_space; /* colorspace of input image */
+
+ double input_gamma; /* image gamma of input image */
+
+ /* Compression parameters --- these fields must be set before calling
+ * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
+ * initialize everything to reasonable defaults, then changing anything
+ * the application specifically wants to change. That way you won't get
+ * burnt when new parameters are added. Also note that there are several
+ * helper routines to simplify changing parameters.
+ */
+
+ int data_precision; /* bits of precision in image data */
+
+ int num_components; /* # of color components in JPEG image */
+ J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
+
+ jpeg_component_info * comp_info;
+ /* comp_info[i] describes component that appears i'th in SOF */
+
+ JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
+ /* ptrs to coefficient quantization tables, or NULL if not defined */
+
+ JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
+ JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
+ /* ptrs to Huffman coding tables, or NULL if not defined */
+
+ UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
+ UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
+ UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
+
+ int num_scans; /* # of entries in scan_info array */
+ const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
+ /* The default value of scan_info is NULL, which causes a single-scan
+ * sequential JPEG file to be emitted. To create a multi-scan file,
+ * set num_scans and scan_info to point to an array of scan definitions.
+ */
+
+ boolean raw_data_in; /* TRUE=caller supplies downsampled data */
+ boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
+ boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
+ boolean CCIR601_sampling; /* TRUE=first samples are cosited */
+ int smoothing_factor; /* 1..100, or 0 for no input smoothing */
+ J_DCT_METHOD dct_method; /* DCT algorithm selector */
+
+ /* The restart interval can be specified in absolute MCUs by setting
+ * restart_interval, or in MCU rows by setting restart_in_rows
+ * (in which case the correct restart_interval will be figured
+ * for each scan).
+ */
+ unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
+ int restart_in_rows; /* if > 0, MCU rows per restart interval */
+
+ /* Parameters controlling emission of special markers. */
+
+ boolean write_JFIF_header; /* should a JFIF marker be written? */
+ /* These three values are not used by the JPEG code, merely copied */
+ /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
+ /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
+ /* ratio is defined by X_density/Y_density even when density_unit=0. */
+ UINT8 density_unit; /* JFIF code for pixel size units */
+ UINT16 X_density; /* Horizontal pixel density */
+ UINT16 Y_density; /* Vertical pixel density */
+ boolean write_Adobe_marker; /* should an Adobe marker be written? */
+
+ /* State variable: index of next scanline to be written to
+ * jpeg_write_scanlines(). Application may use this to control its
+ * processing loop, e.g., "while (next_scanline < image_height)".
+ */
+
+ JDIMENSION next_scanline; /* 0 .. image_height-1 */
+
+ /* Remaining fields are known throughout compressor, but generally
+ * should not be touched by a surrounding application.
+ */
+
+ /*
+ * These fields are computed during compression startup
+ */
+ boolean progressive_mode; /* TRUE if scan script uses progressive mode */
+ int max_h_samp_factor; /* largest h_samp_factor */
+ int max_v_samp_factor; /* largest v_samp_factor */
+
+ JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
+ /* The coefficient controller receives data in units of MCU rows as defined
+ * for fully interleaved scans (whether the JPEG file is interleaved or not).
+ * There are v_samp_factor * DCTSIZE sample rows of each component in an
+ * "iMCU" (interleaved MCU) row.
+ */
+
+ /*
+ * These fields are valid during any one scan.
+ * They describe the components and MCUs actually appearing in the scan.
+ */
+ int comps_in_scan; /* # of JPEG components in this scan */
+ jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
+ /* *cur_comp_info[i] describes component that appears i'th in SOS */
+
+ JDIMENSION MCUs_per_row; /* # of MCUs across the image */
+ JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
+
+ int blocks_in_MCU; /* # of DCT blocks per MCU */
+ int MCU_membership[C_MAX_BLOCKS_IN_MCU];
+ /* MCU_membership[i] is index in cur_comp_info of component owning */
+ /* i'th block in an MCU */
+
+ int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
+
+ /*
+ * Links to compression subobjects (methods and private variables of modules)
+ */
+ struct jpeg_comp_master * master;
+ struct jpeg_c_main_controller * main;
+ struct jpeg_c_prep_controller * prep;
+ struct jpeg_c_coef_controller * coef;
+ struct jpeg_marker_writer * marker;
+ struct jpeg_color_converter * cconvert;
+ struct jpeg_downsampler * downsample;
+ struct jpeg_forward_dct * fdct;
+ struct jpeg_entropy_encoder * entropy;
+};
+
+
+/* Master record for a decompression instance */
+
+struct jpeg_decompress_struct {
+ jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
+
+ /* Source of compressed data */
+ struct jpeg_source_mgr * src;
+
+ /* Basic description of image --- filled in by jpeg_read_header(). */
+ /* Application may inspect these values to decide how to process image. */
+
+ JDIMENSION image_width; /* nominal image width (from SOF marker) */
+ JDIMENSION image_height; /* nominal image height */
+ int num_components; /* # of color components in JPEG image */
+ J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
+
+ /* Decompression processing parameters --- these fields must be set before
+ * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
+ * them to default values.
+ */
+
+ J_COLOR_SPACE out_color_space; /* colorspace for output */
+
+ unsigned int scale_num, scale_denom; /* fraction by which to scale image */
+
+ double output_gamma; /* image gamma wanted in output */
+
+ boolean buffered_image; /* TRUE=multiple output passes */
+ boolean raw_data_out; /* TRUE=downsampled data wanted */
+
+ J_DCT_METHOD dct_method; /* IDCT algorithm selector */
+ boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
+ boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
+
+ boolean quantize_colors; /* TRUE=colormapped output wanted */
+ /* the following are ignored if not quantize_colors: */
+ J_DITHER_MODE dither_mode; /* type of color dithering to use */
+ boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
+ int desired_number_of_colors; /* max # colors to use in created colormap */
+ /* these are significant only in buffered-image mode: */
+ boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
+ boolean enable_external_quant;/* enable future use of external colormap */
+ boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
+
+ /* Description of actual output image that will be returned to application.
+ * These fields are computed by jpeg_start_decompress().
+ * You can also use jpeg_calc_output_dimensions() to determine these values
+ * in advance of calling jpeg_start_decompress().
+ */
+
+ JDIMENSION output_width; /* scaled image width */
+ JDIMENSION output_height; /* scaled image height */
+ int out_color_components; /* # of color components in out_color_space */
+ int output_components; /* # of color components returned */
+ /* output_components is 1 (a colormap index) when quantizing colors;
+ * otherwise it equals out_color_components.
+ */
+ int rec_outbuf_height; /* min recommended height of scanline buffer */
+ /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
+ * high, space and time will be wasted due to unnecessary data copying.
+ * Usually rec_outbuf_height will be 1 or 2, at most 4.
+ */
+
+ /* When quantizing colors, the output colormap is described by these fields.
+ * The application can supply a colormap by setting colormap non-NULL before
+ * calling jpeg_start_decompress; otherwise a colormap is created during
+ * jpeg_start_decompress or jpeg_start_output.
+ * The map has out_color_components rows and actual_number_of_colors columns.
+ */
+ int actual_number_of_colors; /* number of entries in use */
+ JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
+
+ /* State variables: these variables indicate the progress of decompression.
+ * The application may examine these but must not modify them.
+ */
+
+ /* Row index of next scanline to be read from jpeg_read_scanlines().
+ * Application may use this to control its processing loop, e.g.,
+ * "while (output_scanline < output_height)".
+ */
+ JDIMENSION output_scanline; /* 0 .. output_height-1 */
+
+ /* Current input scan number and number of iMCU rows completed in scan.
+ * These indicate the progress of the decompressor input side.
+ */
+ int input_scan_number; /* Number of SOS markers seen so far */
+ JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
+
+ /* The "output scan number" is the notional scan being displayed by the
+ * output side. The decompressor will not allow output scan/row number
+ * to get ahead of input scan/row, but it can fall arbitrarily far behind.
+ */
+ int output_scan_number; /* Nominal scan number being displayed */
+ JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
+
+ /* Current progression status. coef_bits[c][i] indicates the precision
+ * with which component c's DCT coefficient i (in zigzag order) is known.
+ * It is -1 when no data has yet been received, otherwise it is the point
+ * transform (shift) value for the most recent scan of the coefficient
+ * (thus, 0 at completion of the progression).
+ * This pointer is NULL when reading a non-progressive file.
+ */
+ int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
+
+ /* Internal JPEG parameters --- the application usually need not look at
+ * these fields. Note that the decompressor output side may not use
+ * any parameters that can change between scans.
+ */
+
+ /* Quantization and Huffman tables are carried forward across input
+ * datastreams when processing abbreviated JPEG datastreams.
+ */
+
+ JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
+ /* ptrs to coefficient quantization tables, or NULL if not defined */
+
+ JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
+ JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
+ /* ptrs to Huffman coding tables, or NULL if not defined */
+
+ /* These parameters are never carried across datastreams, since they
+ * are given in SOF/SOS markers or defined to be reset by SOI.
+ */
+
+ int data_precision; /* bits of precision in image data */
+
+ jpeg_component_info * comp_info;
+ /* comp_info[i] describes component that appears i'th in SOF */
+
+ boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
+ boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
+
+ UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
+ UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
+ UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
+
+ unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
+
+ /* These fields record data obtained from optional markers recognized by
+ * the JPEG library.
+ */
+ boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
+ /* Data copied from JFIF marker: */
+ UINT8 density_unit; /* JFIF code for pixel size units */
+ UINT16 X_density; /* Horizontal pixel density */
+ UINT16 Y_density; /* Vertical pixel density */
+ boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
+ UINT8 Adobe_transform; /* Color transform code from Adobe marker */
+
+ boolean CCIR601_sampling; /* TRUE=first samples are cosited */
+
+ /* Remaining fields are known throughout decompressor, but generally
+ * should not be touched by a surrounding application.
+ */
+
+ /*
+ * These fields are computed during decompression startup
+ */
+ int max_h_samp_factor; /* largest h_samp_factor */
+ int max_v_samp_factor; /* largest v_samp_factor */
+
+ int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
+
+ JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
+ /* The coefficient controller's input and output progress is measured in
+ * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
+ * in fully interleaved JPEG scans, but are used whether the scan is
+ * interleaved or not. We define an iMCU row as v_samp_factor DCT block
+ * rows of each component. Therefore, the IDCT output contains
+ * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
+ */
+
+ JSAMPLE * sample_range_limit; /* table for fast range-limiting */
+
+ /*
+ * These fields are valid during any one scan.
+ * They describe the components and MCUs actually appearing in the scan.
+ * Note that the decompressor output side must not use these fields.
+ */
+ int comps_in_scan; /* # of JPEG components in this scan */
+ jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
+ /* *cur_comp_info[i] describes component that appears i'th in SOS */
+
+ JDIMENSION MCUs_per_row; /* # of MCUs across the image */
+ JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
+
+ int blocks_in_MCU; /* # of DCT blocks per MCU */
+ int MCU_membership[D_MAX_BLOCKS_IN_MCU];
+ /* MCU_membership[i] is index in cur_comp_info of component owning */
+ /* i'th block in an MCU */
+
+ int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
+
+ /* This field is shared between entropy decoder and marker parser.
+ * It is either zero or the code of a JPEG marker that has been
+ * read from the data source, but has not yet been processed.
+ */
+ int unread_marker;
+
+ /*
+ * Links to decompression subobjects (methods, private variables of modules)
+ */
+ struct jpeg_decomp_master * master;
+ struct jpeg_d_main_controller * main;
+ struct jpeg_d_coef_controller * coef;
+ struct jpeg_d_post_controller * post;
+ struct jpeg_input_controller * inputctl;
+ struct jpeg_marker_reader * marker;
+ struct jpeg_entropy_decoder * entropy;
+ struct jpeg_inverse_dct * idct;
+ struct jpeg_upsampler * upsample;
+ struct jpeg_color_deconverter * cconvert;
+ struct jpeg_color_quantizer * cquantize;
+};
+
+
+/* "Object" declarations for JPEG modules that may be supplied or called
+ * directly by the surrounding application.
+ * As with all objects in the JPEG library, these structs only define the
+ * publicly visible methods and state variables of a module. Additional
+ * private fields may exist after the public ones.
+ */
+
+
+/* Error handler object */
+
+struct jpeg_error_mgr {
+ /* Error exit handler: does not return to caller */
+ JMETHOD(void, error_exit, (j_common_ptr cinfo));
+ /* Conditionally emit a trace or warning message */
+ JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
+ /* Routine that actually outputs a trace or error message */
+ JMETHOD(void, output_message, (j_common_ptr cinfo));
+ /* Format a message string for the most recent JPEG error or message */
+ JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
+#define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
+ /* Reset error state variables at start of a new image */
+ JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
+
+ /* The message ID code and any parameters are saved here.
+ * A message can have one string parameter or up to 8 int parameters.
+ */
+ int msg_code;
+#define JMSG_STR_PARM_MAX 80
+ union {
+ int i[8];
+ char s[JMSG_STR_PARM_MAX];
+ } msg_parm;
+
+ /* Standard state variables for error facility */
+
+ int trace_level; /* max msg_level that will be displayed */
+
+ /* For recoverable corrupt-data errors, we emit a warning message,
+ * but keep going unless emit_message chooses to abort. emit_message
+ * should count warnings in num_warnings. The surrounding application
+ * can check for bad data by seeing if num_warnings is nonzero at the
+ * end of processing.
+ */
+ long num_warnings; /* number of corrupt-data warnings */
+
+ /* These fields point to the table(s) of error message strings.
+ * An application can change the table pointer to switch to a different
+ * message list (typically, to change the language in which errors are
+ * reported). Some applications may wish to add additional error codes
+ * that will be handled by the JPEG library error mechanism; the second
+ * table pointer is used for this purpose.
+ *
+ * First table includes all errors generated by JPEG library itself.
+ * Error code 0 is reserved for a "no such error string" message.
+ */
+ const char * const * jpeg_message_table; /* Library errors */
+ int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
+ /* Second table can be added by application (see cjpeg/djpeg for example).
+ * It contains strings numbered first_addon_message..last_addon_message.
+ */
+ const char * const * addon_message_table; /* Non-library errors */
+ int first_addon_message; /* code for first string in addon table */
+ int last_addon_message; /* code for last string in addon table */
+};
+
+
+/* Progress monitor object */
+
+struct jpeg_progress_mgr {
+ JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
+
+ long pass_counter; /* work units completed in this pass */
+ long pass_limit; /* total number of work units in this pass */
+ int completed_passes; /* passes completed so far */
+ int total_passes; /* total number of passes expected */
+};
+
+
+/* Data destination object for compression */
+
+struct jpeg_destination_mgr {
+ JOCTET * next_output_byte; /* => next byte to write in buffer */
+ size_t free_in_buffer; /* # of byte spaces remaining in buffer */
+
+ JMETHOD(void, init_destination, (j_compress_ptr cinfo));
+ JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
+ JMETHOD(void, term_destination, (j_compress_ptr cinfo));
+};
+
+
+/* Data source object for decompression */
+
+struct jpeg_source_mgr {
+ const JOCTET * next_input_byte; /* => next byte to read from buffer */
+ size_t bytes_in_buffer; /* # of bytes remaining in buffer */
+
+ JMETHOD(void, init_source, (j_decompress_ptr cinfo));
+ JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
+ JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
+ JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
+ JMETHOD(void, term_source, (j_decompress_ptr cinfo));
+};
+
+
+/* Memory manager object.
+ * Allocates "small" objects (a few K total), "large" objects (tens of K),
+ * and "really big" objects (virtual arrays with backing store if needed).
+ * The memory manager does not allow individual objects to be freed; rather,
+ * each created object is assigned to a pool, and whole pools can be freed
+ * at once. This is faster and more convenient than remembering exactly what
+ * to free, especially where malloc()/free() are not too speedy.
+ * NB: alloc routines never return NULL. They exit to error_exit if not
+ * successful.
+ */
+
+#define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
+#define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
+#define JPOOL_NUMPOOLS 2
+
+typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
+typedef struct jvirt_barray_control * jvirt_barray_ptr;
+
+
+struct jpeg_memory_mgr {
+ /* Method pointers */
+ JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
+ size_t sizeofobject));
+ JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
+ size_t sizeofobject));
+ JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
+ JDIMENSION samplesperrow,
+ JDIMENSION numrows));
+ JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
+ JDIMENSION blocksperrow,
+ JDIMENSION numrows));
+ JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
+ int pool_id,
+ boolean pre_zero,
+ JDIMENSION samplesperrow,
+ JDIMENSION numrows,
+ JDIMENSION maxaccess));
+ JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
+ int pool_id,
+ boolean pre_zero,
+ JDIMENSION blocksperrow,
+ JDIMENSION numrows,
+ JDIMENSION maxaccess));
+ JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
+ JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
+ jvirt_sarray_ptr ptr,
+ JDIMENSION start_row,
+ JDIMENSION num_rows,
+ boolean writable));
+ JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
+ jvirt_barray_ptr ptr,
+ JDIMENSION start_row,
+ JDIMENSION num_rows,
+ boolean writable));
+ JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
+ JMETHOD(void, self_destruct, (j_common_ptr cinfo));
+
+ /* Limit on memory allocation for this JPEG object. (Note that this is
+ * merely advisory, not a guaranteed maximum; it only affects the space
+ * used for virtual-array buffers.) May be changed by outer application
+ * after creating the JPEG object.
+ */
+ long max_memory_to_use;
+};
+
+
+/* Routine signature for application-supplied marker processing methods.
+ * Need not pass marker code since it is stored in cinfo->unread_marker.
+ */
+typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
+
+
+/* Declarations for routines called by application.
+ * The JPP macro hides prototype parameters from compilers that can't cope.
+ * Note JPP requires double parentheses.
+ */
+
+#ifdef HAVE_PROTOTYPES
+#define JPP(arglist) arglist
+#else
+#define JPP(arglist) ()
+#endif
+
+
+/* Short forms of external names for systems with brain-damaged linkers.
+ * We shorten external names to be unique in the first six letters, which
+ * is good enough for all known systems.
+ * (If your compiler itself needs names to be unique in less than 15
+ * characters, you are out of luck. Get a better compiler.)
+ */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jpeg_std_error jStdError
+#define jpeg_create_compress jCreaCompress
+#define jpeg_create_decompress jCreaDecompress
+#define jpeg_destroy_compress jDestCompress
+#define jpeg_destroy_decompress jDestDecompress
+#define jpeg_stdio_dest jStdDest
+#define jpeg_stdio_src jStdSrc
+#define jpeg_set_defaults jSetDefaults
+#define jpeg_set_colorspace jSetColorspace
+#define jpeg_default_colorspace jDefColorspace
+#define jpeg_set_quality jSetQuality
+#define jpeg_set_linear_quality jSetLQuality
+#define jpeg_add_quant_table jAddQuantTable
+#define jpeg_quality_scaling jQualityScaling
+#define jpeg_simple_progression jSimProgress
+#define jpeg_suppress_tables jSuppressTables
+#define jpeg_alloc_quant_table jAlcQTable
+#define jpeg_alloc_huff_table jAlcHTable
+#define jpeg_start_compress jStrtCompress
+#define jpeg_write_scanlines jWrtScanlines
+#define jpeg_finish_compress jFinCompress
+#define jpeg_write_raw_data jWrtRawData
+#define jpeg_write_marker jWrtMarker
+#define jpeg_write_tables jWrtTables
+#define jpeg_read_header jReadHeader
+#define jpeg_start_decompress jStrtDecompress
+#define jpeg_read_scanlines jReadScanlines
+#define jpeg_finish_decompress jFinDecompress
+#define jpeg_read_raw_data jReadRawData
+#define jpeg_has_multiple_scans jHasMultScn
+#define jpeg_start_output jStrtOutput
+#define jpeg_finish_output jFinOutput
+#define jpeg_input_complete jInComplete
+#define jpeg_new_colormap jNewCMap
+#define jpeg_consume_input jConsumeInput
+#define jpeg_calc_output_dimensions jCalcDimensions
+#define jpeg_set_marker_processor jSetMarker
+#define jpeg_read_coefficients jReadCoefs
+#define jpeg_write_coefficients jWrtCoefs
+#define jpeg_copy_critical_parameters jCopyCrit
+#define jpeg_abort_compress jAbrtCompress
+#define jpeg_abort_decompress jAbrtDecompress
+#define jpeg_abort jAbort
+#define jpeg_destroy jDestroy
+#define jpeg_resync_to_restart jResyncRestart
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+
+/* Default error-management setup */
+EXTERN struct jpeg_error_mgr *jpeg_std_error JPP((struct jpeg_error_mgr *err));
+
+/* Initialization and destruction of JPEG compression objects */
+/* NB: you must set up the error-manager BEFORE calling jpeg_create_xxx */
+EXTERN void jpeg_create_compress JPP((j_compress_ptr cinfo));
+EXTERN void jpeg_create_decompress JPP((j_decompress_ptr cinfo));
+EXTERN void jpeg_destroy_compress JPP((j_compress_ptr cinfo));
+EXTERN void jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
+
+/* Standard data source and destination managers: stdio streams. */
+/* Caller is responsible for opening the file before and closing after. */
+EXTERN void jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
+EXTERN void jpeg_stdio_src JPP((j_decompress_ptr cinfo, unsigned char *infile));
+
+/* Default parameter setup for compression */
+EXTERN void jpeg_set_defaults JPP((j_compress_ptr cinfo));
+/* Compression parameter setup aids */
+EXTERN void jpeg_set_colorspace JPP((j_compress_ptr cinfo,
+ J_COLOR_SPACE colorspace));
+EXTERN void jpeg_default_colorspace JPP((j_compress_ptr cinfo));
+EXTERN void jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
+ boolean force_baseline));
+EXTERN void jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
+ int scale_factor,
+ boolean force_baseline));
+EXTERN void jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
+ const unsigned int *basic_table,
+ int scale_factor,
+ boolean force_baseline));
+EXTERN int jpeg_quality_scaling JPP((int quality));
+EXTERN void jpeg_simple_progression JPP((j_compress_ptr cinfo));
+EXTERN void jpeg_suppress_tables JPP((j_compress_ptr cinfo,
+ boolean suppress));
+EXTERN JQUANT_TBL * jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
+EXTERN JHUFF_TBL * jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
+
+/* Main entry points for compression */
+EXTERN void jpeg_start_compress JPP((j_compress_ptr cinfo,
+ boolean write_all_tables));
+EXTERN JDIMENSION jpeg_write_scanlines JPP((j_compress_ptr cinfo,
+ JSAMPARRAY scanlines,
+ JDIMENSION num_lines));
+EXTERN void jpeg_finish_compress JPP((j_compress_ptr cinfo));
+
+/* Replaces jpeg_write_scanlines when writing raw downsampled data. */
+EXTERN JDIMENSION jpeg_write_raw_data JPP((j_compress_ptr cinfo,
+ JSAMPIMAGE data,
+ JDIMENSION num_lines));
+
+/* Write a special marker. See libjpeg.doc concerning safe usage. */
+EXTERN void jpeg_write_marker JPP((j_compress_ptr cinfo, int marker,
+ const JOCTET *dataptr, unsigned int datalen));
+
+/* Alternate compression function: just write an abbreviated table file */
+EXTERN void jpeg_write_tables JPP((j_compress_ptr cinfo));
+
+/* Decompression startup: read start of JPEG datastream to see what's there */
+EXTERN int jpeg_read_header JPP((j_decompress_ptr cinfo,
+ boolean require_image));
+/* Return value is one of: */
+#define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
+#define JPEG_HEADER_OK 1 /* Found valid image datastream */
+#define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
+/* If you pass require_image = TRUE (normal case), you need not check for
+ * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
+ * JPEG_SUSPENDED is only possible if you use a data source module that can
+ * give a suspension return (the stdio source module doesn't).
+ */
+
+/* Main entry points for decompression */
+EXTERN boolean jpeg_start_decompress JPP((j_decompress_ptr cinfo));
+EXTERN JDIMENSION jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
+ JSAMPARRAY scanlines,
+ JDIMENSION max_lines));
+EXTERN boolean jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
+
+/* Replaces jpeg_read_scanlines when reading raw downsampled data. */
+EXTERN JDIMENSION jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
+ JSAMPIMAGE data,
+ JDIMENSION max_lines));
+
+/* Additional entry points for buffered-image mode. */
+EXTERN boolean jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
+EXTERN boolean jpeg_start_output JPP((j_decompress_ptr cinfo,
+ int scan_number));
+EXTERN boolean jpeg_finish_output JPP((j_decompress_ptr cinfo));
+EXTERN boolean jpeg_input_complete JPP((j_decompress_ptr cinfo));
+EXTERN void jpeg_new_colormap JPP((j_decompress_ptr cinfo));
+EXTERN int jpeg_consume_input JPP((j_decompress_ptr cinfo));
+/* Return value is one of: */
+/* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
+#define JPEG_REACHED_SOS 1 /* Reached start of new scan */
+#define JPEG_REACHED_EOI 2 /* Reached end of image */
+#define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
+#define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
+
+/* Precalculate output dimensions for current decompression parameters. */
+EXTERN void jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
+
+/* Install a special processing method for COM or APPn markers. */
+EXTERN void jpeg_set_marker_processor JPP((j_decompress_ptr cinfo,
+ int marker_code,
+ jpeg_marker_parser_method routine));
+
+/* Read or write raw DCT coefficients --- useful for lossless transcoding. */
+EXTERN jvirt_barray_ptr * jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
+EXTERN void jpeg_write_coefficients JPP((j_compress_ptr cinfo,
+ jvirt_barray_ptr * coef_arrays));
+EXTERN void jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
+ j_compress_ptr dstinfo));
+
+/* If you choose to abort compression or decompression before completing
+ * jpeg_finish_(de)compress, then you need to clean up to release memory,
+ * temporary files, etc. You can just call jpeg_destroy_(de)compress
+ * if you're done with the JPEG object, but if you want to clean it up and
+ * reuse it, call this:
+ */
+EXTERN void jpeg_abort_compress JPP((j_compress_ptr cinfo));
+EXTERN void jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
+
+/* Generic versions of jpeg_abort and jpeg_destroy that work on either
+ * flavor of JPEG object. These may be more convenient in some places.
+ */
+EXTERN void jpeg_abort JPP((j_common_ptr cinfo));
+EXTERN void jpeg_destroy JPP((j_common_ptr cinfo));
+
+/* Default restart-marker-resync procedure for use by data source modules */
+EXTERN boolean jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
+ int desired));
+
+
+/* These marker codes are exported since applications and data source modules
+ * are likely to want to use them.
+ */
+
+#define JPEG_RST0 0xD0 /* RST0 marker code */
+#define JPEG_EOI 0xD9 /* EOI marker code */
+#define JPEG_APP0 0xE0 /* APP0 marker code */
+#define JPEG_COM 0xFE /* COM marker code */
+
+
+/* If we have a brain-damaged compiler that emits warnings (or worse, errors)
+ * for structure definitions that are never filled in, keep it quiet by
+ * supplying dummy definitions for the various substructures.
+ */
+
+#ifdef INCOMPLETE_TYPES_BROKEN
+#ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
+struct jvirt_sarray_control { long dummy; };
+struct jvirt_barray_control { long dummy; };
+struct jpeg_comp_master { long dummy; };
+struct jpeg_c_main_controller { long dummy; };
+struct jpeg_c_prep_controller { long dummy; };
+struct jpeg_c_coef_controller { long dummy; };
+struct jpeg_marker_writer { long dummy; };
+struct jpeg_color_converter { long dummy; };
+struct jpeg_downsampler { long dummy; };
+struct jpeg_forward_dct { long dummy; };
+struct jpeg_entropy_encoder { long dummy; };
+struct jpeg_decomp_master { long dummy; };
+struct jpeg_d_main_controller { long dummy; };
+struct jpeg_d_coef_controller { long dummy; };
+struct jpeg_d_post_controller { long dummy; };
+struct jpeg_input_controller { long dummy; };
+struct jpeg_marker_reader { long dummy; };
+struct jpeg_entropy_decoder { long dummy; };
+struct jpeg_inverse_dct { long dummy; };
+struct jpeg_upsampler { long dummy; };
+struct jpeg_color_deconverter { long dummy; };
+struct jpeg_color_quantizer { long dummy; };
+#endif /* JPEG_INTERNALS */
+#endif /* INCOMPLETE_TYPES_BROKEN */
+
+
+/*
+ * The JPEG library modules define JPEG_INTERNALS before including this file.
+ * The internal structure declarations are read only when that is true.
+ * Applications using the library should not include jpegint.h, but may wish
+ * to include jerror.h.
+ */
+
+#ifdef JPEG_INTERNALS
+#include "jpegint.h" /* fetch private declarations */
+#include "jerror.h" /* fetch error codes too */
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* JPEGLIB_H */
diff --git a/libs/pak/pak.vcproj b/libs/pak/pak.vcproj
new file mode 100755
index 0000000..bf74cae
--- /dev/null
+++ b/libs/pak/pak.vcproj
@@ -0,0 +1,173 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+ ProjectType="Visual C++"
+ Version="7.10"
+ Name="pak"
+ SccProjectName="&quot;$/source/q3radiant&quot;, FEFAAAAA"
+ SccLocalPath="..\..\q3radiant">
+ <Platforms>
+ <Platform
+ Name="Win32"/>
+ </Platforms>
+ <Configurations>
+ <Configuration
+ Name="Debug|Win32"
+ OutputDirectory=".\Debug"
+ IntermediateDirectory=".\Debug"
+ ConfigurationType="4"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=".."
+ PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
+ BasicRuntimeChecks="3"
+ RuntimeLibrary="1"
+ RuntimeTypeInfo="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Debug/pak.pch"
+ AssemblerListingLocation=".\Debug/"
+ ObjectFile=".\Debug/"
+ ProgramDataBaseFileName=".\Debug/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"
+ CompileAs="0"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile="..\pakd.lib"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCMIDLTool"/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Release|Win32"
+ OutputDirectory=".\Release"
+ IntermediateDirectory=".\Release"
+ ConfigurationType="4"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=".."
+ PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
+ RuntimeLibrary="0"
+ RuntimeTypeInfo="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Release/pak.pch"
+ AssemblerListingLocation=".\Release/"
+ ObjectFile=".\Release/"
+ ProgramDataBaseFileName=".\Release/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ CompileAs="0"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile="..\pak.lib"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCMIDLTool"/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ </Configurations>
+ <References>
+ </References>
+ <Files>
+ <Filter
+ Name="Source Files"
+ Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat">
+ <File
+ RelativePath="pakstuff.cpp">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="unzip.cpp">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <Filter
+ Name="Header Files"
+ Filter="h;hpp;hxx;hm;inl">
+ <File
+ RelativePath="..\pakstuff.h">
+ </File>
+ </Filter>
+ </Files>
+ <Globals>
+ </Globals>
+</VisualStudioProject>
diff --git a/libs/pak/pakstuff.cpp b/libs/pak/pakstuff.cpp
new file mode 100755
index 0000000..a4e1dc7
--- /dev/null
+++ b/libs/pak/pakstuff.cpp
@@ -0,0 +1,1209 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include <stdio.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+#include <windows.h>
+#include "io.h"
+#include "pakstuff.h"
+#include "unzip.h"
+//#include "cmdlib.h"
+#include "str.h"
+
+int m_nPAKIndex;
+FILE* pakfile[16];
+struct PACKDirectory pakdir;
+PACKDirPtr pakdirptr = &pakdir;
+UInt16 dirsize;
+boolean pakopen = false;
+int f_type;
+DIRECTORY *paktextures = NULL;
+boolean HavePakColormap;
+UInt32 PakColormapOffset;
+UInt32 PakColormapSize;
+DIRECTORY *dirhead = NULL;
+boolean g_bPK3 = false;
+char g_strBasePath[1024];
+
+struct PK3FileInfo
+{
+ unzFile m_zFile;
+ char *m_pName;
+ unz_s m_zInfo;
+ long m_lSize;
+ ~PK3FileInfo()
+ {
+ delete []m_pName;
+ }
+ bool operator ==(const PK3FileInfo& rhs) const { return strcmp(m_pName, rhs.m_pName) == 0; }
+};
+
+#define __PATHSEPERATOR '/'
+
+#define LOG_PAKFAIL
+
+#ifdef LOG_PAKFAIL
+
+class LogFile
+{
+public:
+ FILE *m_pFile;
+ LogFile(const char* pName)
+ {
+ m_pFile = fopen(pName, "w");
+ }
+ ~LogFile()
+ {
+ if (m_pFile)
+ {
+ fclose(m_pFile);
+ }
+ }
+ void Log(const char *pFormat, ...)
+ {
+ va_list arg_ptr;
+ va_start(arg_ptr, pFormat);
+ fprintf(m_pFile, pFormat, arg_ptr);
+ va_end(arg_ptr);
+ }
+};
+
+LogFile g_LogFile("c:\\paklog.txt");
+#endif
+
+template <class T> class StrPtr : public Str
+{
+protected:
+ T* m_pPtr;
+ StrPtr()
+ {
+ m_pPtr = NULL;
+ }
+
+ StrPtr(const char *pStr, T *p) : Str(pStr)
+ {
+ m_pPtr = p;
+ }
+
+ T* Ptr()
+ {
+ return m_pPtr;
+ }
+
+ T& Ref()
+ {
+ return *m_pPtr;
+ }
+
+
+};
+// PtrList
+// a list of ptrs
+//
+template <class T> class PtrList
+{
+protected:
+ T *m_pPtr;
+ PtrList *m_pNext;
+
+public:
+
+ PtrList()
+ {
+ m_pNext = NULL;
+ m_pPtr = NULL;
+ }
+
+ PtrList(T *ip)
+ {
+ m_pNext = NULL;
+ m_pPtr = ip;
+ }
+
+ ~PtrList()
+ {
+ delete m_pPtr;
+ }
+
+ PtrList* Next()
+ {
+ return m_pNext;
+ }
+
+ void Add(T *ip)
+ {
+ PtrList *pl = this;
+ while (pl && pl->m_pNext)
+ {
+ pl = pl->Next();
+ }
+ pl->m_pNext = new PtrList(ip);
+ }
+
+ void Remove()
+ {
+ PtrList *p = m_pNext;
+ if (p)
+ {
+ while (p->m_pNext != this && p->m_pNext != NULL)
+ {
+ p = p->m_pNext;
+ }
+ if (p->m_pNext == this)
+ {
+ p->m_pNext = m_pNext;
+ }
+ }
+ }
+
+ virtual PtrList* Find(T *ip)
+ {
+ PtrList *p = m_pNext;
+ while (p)
+ {
+ if (*p->m_pPtr == *ip)
+ {
+ return p;
+ }
+ p = p->m_pNext;
+ }
+ return NULL;
+ }
+
+ // remove vp from the list
+ void Remove(T *ip)
+ {
+ PtrList *p = Find(ip);
+ if (p)
+ {
+ p->Remove();
+ }
+ }
+
+ T* Ptr()
+ {
+ return m_pPtr;
+ }
+
+ T& Ref()
+ {
+ return *m_pPtr;
+ }
+
+ void RemoveAll()
+ {
+ PtrList *p = m_pNext;
+ while (p)
+ {
+ PtrList *p2 = p;
+ p = p->m_pNext;
+ delete p2;
+ }
+ }
+};
+
+
+typedef PtrList<unzFile> ZFileList;
+typedef PtrList<Str> StrList;
+typedef PtrList<PK3FileInfo> PK3List;
+
+
+StrList g_PK3TexturePaths;
+PK3List g_PK3Files;
+ZFileList g_zFiles;
+#define WORK_LEN 1024
+#define TEXTURE_PATH "textures"
+#define PATH_SEPERATORS "/\\:\0"
+
+
+char* __StrDup(char* pStr)
+{
+ if (pStr)
+ {
+ return strcpy(new char[strlen(pStr)+1], pStr);
+ }
+ return NULL;
+}
+
+char* __StrDup(const char* pStr)
+{
+ if (pStr)
+ {
+ return strcpy(new char[strlen(pStr)+1], pStr);
+ }
+ return NULL;
+}
+
+#define MEM_BLOCKSIZE 4096
+void* __qblockmalloc(size_t nSize)
+{
+ void *b;
+ // round up to threshold
+ int nAllocSize = nSize % MEM_BLOCKSIZE;
+ if ( nAllocSize > 0)
+ {
+ nSize += MEM_BLOCKSIZE - nAllocSize;
+ }
+ b = malloc(nSize + 1);
+ memset (b, 0, nSize);
+ return b;
+}
+
+void* __qmalloc (size_t nSize)
+{
+ void *b;
+ b = malloc(nSize + 1);
+ memset (b, 0, nSize);
+ return b;
+}
+
+
+/*
+====================
+Extract file parts
+====================
+*/
+void __ExtractFilePath (const char *path, char *dest)
+{
+ const char *src;
+
+ src = path + strlen(path) - 1;
+
+//
+// back up until a \ or the start
+//
+ while (src != path && *(src-1) != __PATHSEPERATOR)
+ src--;
+
+ memcpy (dest, path, src-path);
+ dest[src-path] = 0;
+}
+
+void __ExtractFileName (const char *path, char *dest)
+{
+ const char *src;
+
+ src = path + strlen(path) - 1;
+
+//
+// back up until a \ or the start
+//
+ while (src != path && *(src-1) != '/'
+ && *(src-1) != '\\' )
+ src--;
+
+ while (*src)
+ {
+ *dest++ = *src++;
+ }
+ *dest = 0;
+}
+
+void __ExtractFileBase (const char *path, char *dest)
+{
+ const char *src;
+
+ src = path + strlen(path) - 1;
+
+//
+// back up until a \ or the start
+//
+ while (src != path && *(src-1) != '/'
+ && *(src-1) != '\\' )
+ src--;
+
+ while (*src && *src != '.')
+ {
+ *dest++ = *src++;
+ }
+ *dest = 0;
+}
+
+void __ExtractFileExtension (const char *path, char *dest)
+{
+ const char *src;
+
+ src = path + strlen(path) - 1;
+
+//
+// back up until a . or the start
+//
+ while (src != path && *(src-1) != '.')
+ src--;
+ if (src == path)
+ {
+ *dest = 0; // no extension
+ return;
+ }
+
+ strcpy (dest,src);
+}
+
+
+void __ConvertDOSToUnixName( char *dst, const char *src )
+{
+ while ( *src )
+ {
+ if ( *src == '\\' )
+ *dst = '/';
+ else
+ *dst = *src;
+ dst++; src++;
+ }
+ *dst = 0;
+}
+
+
+
+
+
+void AddSlash(Str& str)
+{
+ int nLen = str.GetLength();
+ if (nLen > 0)
+ {
+ if (str[nLen-1] != '\\' && str[nLen-1] != '/')
+ str += '\\';
+ }
+}
+
+void FindReplace(Str& strContents, const char* pTag, const char* pValue)
+{
+ if (strcmp(pTag, pValue) == 0)
+ return;
+ for (int nPos = strContents.Find(pTag); nPos >= 0; nPos = strContents.Find(pTag))
+ {
+ int nRightLen = strContents.GetLength() - strlen(pTag) - nPos;
+ Str strLeft(strContents.Left(nPos));
+ Str strRight(strContents.Right(nRightLen));
+ strLeft += pValue;
+ strLeft += strRight;
+ strContents = strLeft;
+ }
+}
+
+
+
+
+
+void ProgError(char *errstr, ...)
+{
+ va_list args;
+
+ va_start(args, errstr);
+ printf("\nProgram Error: *** ");
+ vprintf(errstr, args);
+ printf(" ***\n");
+ va_end(args);
+ exit(5);
+}
+
+boolean ReadBytes(FILE *file, void *addr, UInt32 size)
+{
+ while (size > 0x8000)
+ {
+ if (fread(addr, 1, 0x8000, file) != 0x8000)
+ return false;
+ addr = (char *)addr + 0x8000;
+ size -= 0x8000;
+ }
+ if (fread(addr, 1, size, file) != size)
+ return false;
+ return true;
+}
+int ReadMagic(FILE *file)
+{
+ UInt8 buf[4];
+
+ if (ReadBytes(file, buf, 4) == FALSE)
+ return FTYPE_ERROR;
+ if (!strncmp(reinterpret_cast<const char*>(&buf[0]), "IWAD", 4))
+ return FTYPE_IWAD;
+ if (!strncmp(reinterpret_cast<const char*>(&buf[0]), "PWAD", 4))
+ return FTYPE_PWAD;
+ if (!strncmp(reinterpret_cast<const char*>(&buf[0]), "PACK", 4))
+ return FTYPE_PACK;
+ if (!strncmp(reinterpret_cast<const char*>(&buf[0]), "WAD2", 4))
+ return FTYPE_WAD2;
+ if (buf[0] == 0x17 && buf[1] == 0 && buf[2] == 0 && buf[3] == 0)
+ return FTYPE_BSP;
+ if (!strncmp(reinterpret_cast<const char*>(&buf[0]), "IDPO", 4))
+ return FTYPE_MODEL;
+ if (!strncmp(reinterpret_cast<const char*>(&buf[0]), "IDSP", 4))
+ return FTYPE_SPRITE;
+ if (!strncmp(reinterpret_cast<const char*>(&buf[0]), "RIFF", 4))
+ return FTYPE_WAV;
+ if (!strncmp(reinterpret_cast<const char*>(&buf[0]), ".snd", 4))
+ return FTYPE_AU;
+ if (buf[0] == 'P')
+ {
+ if (buf[1] == '1')
+ return FTYPE_PBM_ASC;
+ if (buf[1] == '2')
+ return FTYPE_PGM_ASC;
+ if (buf[1] == '3')
+ return FTYPE_PPM_ASC;
+ if (buf[1] == '4')
+ return FTYPE_PBM_RAW;
+ if (buf[1] == '5')
+ return FTYPE_PGM_RAW;
+ if (buf[1] == '6')
+ return FTYPE_PPM_RAW;
+ }
+ if (buf[0] == 'B' && buf[1] == 'M')
+ return FTYPE_BMP;
+ if (!strncmp(reinterpret_cast<const char*>(&buf[0]), "GIF8", 4))
+ return FTYPE_GIF;
+ if (buf[0] == 0x0a && buf[1] == 0x05 && buf[2] == 0x01 && buf[3] == 0x08)
+ return FTYPE_PCX;
+ return FTYPE_UNKNOWN;
+}
+FILE *OpenFileReadMagic(const char *filename, int *ftype_r)
+{
+ FILE *f;
+
+ *ftype_r = FTYPE_ERROR;
+ if ((f = fopen(filename, "rb")) == NULL)
+ return NULL;
+ *ftype_r = ReadMagic(f);
+ if (*ftype_r == FTYPE_ERROR)
+ {
+ fclose(f);
+ return NULL;
+ }
+ return f;
+}
+boolean WriteBytes(FILE *file, void *addr, UInt32 size)
+{
+ while (size > 0x8000)
+ {
+ if (fwrite(addr, 1, 0x8000, file) != 0x8000)
+ return FALSE;
+ addr = (char *)addr + 0x8000;
+ size -= 0x8000;
+ }
+ if (fwrite(addr, 1, size, file) != size)
+ return FALSE;
+ return TRUE;
+}
+char *ConvertFilePath(char *filename)
+{
+ char *cp;
+
+ if (filename == NULL)
+ ProgError("BUG: cannot convert a NULL pathname");
+ for (cp = filename; *cp; cp++)
+ if (*cp == '/' || *cp == '\\')
+ {
+#ifdef QEU_DOS
+ *cp = '\\';
+#else
+ *cp = '/';
+#endif
+ }
+ return filename;
+}
+
+/*
+ * Read the PACK directory into memory. The optional offset to the
+ * start of the PACK file is given in "offset". The number of files in
+ * the directory is returned in *dirsize_r.
+ */
+PACKDirPtr ReadPACKDirectory(FILE *packfile, UInt32 offset, UInt16 *dirsize_r)
+{
+ PACKDirPtr dir;
+ UInt32 pos, size;
+ UInt16 max, i;
+
+ *dirsize_r = 0;
+ if (packfile == NULL)
+ return NULL;
+ if ((fseek(packfile, offset, SEEK_SET) < 0)
+ || (ReadMagic(packfile) != FTYPE_PACK)
+ || (ReadInt32(packfile, &pos) == FALSE)
+ || (ReadInt32(packfile, &size) == FALSE)
+ || (size == 0L)
+ || (size / sizeof(struct PACKDirectory) > 65535L)
+ || (fseek(packfile, offset + pos, SEEK_SET) < 0))
+ return NULL;
+ dir = (PACKDirPtr)__qmalloc(size);
+ max = (UInt16)(size / sizeof(struct PACKDirectory));
+ for (i = 0; i < max; i++)
+ {
+ if (ReadBytes(packfile, &dir[i], sizeof(struct PACKDirectory)) == FALSE)
+ {
+ free(dir);
+ return NULL;
+ }
+ ConvertFilePath(dir[i].name);
+ dir[i].offset = SwapInt32(dir[i].offset);
+ dir[i].size = SwapInt32(dir[i].size);
+ }
+ *dirsize_r = max;
+ return dir;
+}
+
+/*
+ * Print the contents of the PACK directory in "outf".
+ */
+void DumpPACKDirectory(FILE *outf, PACKDirPtr dir, UInt16 dirsize)
+{
+ UInt16 i;
+ UInt32 sum;
+ char buf[57];
+
+ if (outf == NULL || dir == NULL || dirsize == 0)
+ return;
+ fprintf(outf, "num offset size file name\n");
+ fprintf(outf, " (hex) (dec)\n");
+ sum = 0L;
+ for (i = 0; i < dirsize; i++)
+ {
+ if(!strnicmp(dir[i].name, "textures", 8))
+ {
+ strncpy(buf, dir[i].name, 56);
+ buf[56] = '\0';
+ fprintf(outf, "%3u 0x%08lx %6ld %s\n",
+ i, dir[i].offset, dir[i].size, buf);
+ sum += dir[i].size;
+ }
+ }
+ fprintf(outf, "\nTotal size for %3u entries: %7lu bytes.\n", dirsize, sum);
+ fprintf(outf, "Size of the PACK directory: %7lu bytes.\n",
+ (UInt32)dirsize * (UInt32)sizeof(struct PACKDirectory));
+ fprintf(outf, "Total (header + data + dir): %7lu bytes.\n",
+ 12L + sum + (UInt32)dirsize * (UInt32)sizeof(struct PACKDirectory));
+}
+
+void ClearFileList(FILELIST **list)
+{
+ FILELIST *temp;
+
+ while(*list)
+ {
+ temp = *list;
+ *list = (*list)->next;
+ free(temp);
+ }
+}
+
+void ClearDirList(DIRLIST **list)
+{
+ DIRLIST *temp;
+
+ while(*list)
+ {
+ temp = *list;
+ *list = (*list)->next;
+ free(temp);
+ }
+}
+
+DIRECTORY *FindPakDir(DIRECTORY *dir, char *name)
+{
+ DIRECTORY *currentPtr;
+
+ for(currentPtr = dir; currentPtr; currentPtr = currentPtr->next)
+ {
+ if(!stricmp(name, currentPtr->name))
+ {
+ return currentPtr;
+ }
+ }
+ return NULL;
+}
+
+
+// LoadPK3FileList
+// ---------------
+//
+// This gets passed a file mask which we want to remove as
+// we are only interested in the directory name and any given
+// extension. Only handles explicit filenames or *.something
+//
+boolean LoadPK3FileList(FILELIST **filelist, const char *pattern)
+{
+ char cSearch[WORK_LEN];
+ __ConvertDOSToUnixName( cSearch, pattern );
+ char cPath[WORK_LEN];
+ char cExt[WORK_LEN];
+ char cFile[WORK_LEN];
+ char cWork[WORK_LEN];
+ __ExtractFilePath(pattern, cPath);
+ __ExtractFileName(pattern, cFile);
+ __ExtractFileExtension(pattern, cExt);
+ const char *pCompare = (strnicmp(cFile, "*.", 2) == 0) ? cExt : cFile;
+ strcpy(cWork, cPath);
+ sprintf(cPath, "textures/%s", cWork);
+
+ PK3List *p = g_PK3Files.Next();
+ while (p != NULL)
+ {
+ // qualify the path
+ PK3FileInfo *pKey = p->Ptr();
+ if (strstr(pKey->m_pName, cPath) && strstr(pKey->m_pName, pCompare))
+ {
+ __ExtractFileName(pKey->m_pName, cWork);
+ AddToFileListAlphabetized(filelist, cWork, 0, 0, false);
+ }
+ p = p->Next();
+ }
+ return (*filelist) != NULL;
+}
+
+boolean GetPackFileList(FILELIST **filelist, char *pattern)
+{
+ char *str1, *str2;
+ int i;
+ DIRECTORY *dummy = paktextures;
+ FILELIST *temp;
+
+ if (!pakopen)
+ return false;
+
+ if (g_bPK3)
+ {
+ return LoadPK3FileList(filelist, pattern);
+ }
+
+ str1 = pattern;
+
+ for(i = 0; pattern[i] != '\0'; i++)
+ {
+ if(pattern[i] == '\\')
+ pattern[i] = '/';
+ }
+
+ while(strchr(str1, '/'))
+ {
+ str2 = strchr(str1, '/');
+ *str2++ = '\0';
+ dummy = FindPakDir(dummy, str1);
+ if(!dummy)
+ return false;
+ str1 = str2;
+ }
+ for(temp = dummy->files; temp; temp=temp->next)
+ {
+ AddToFileListAlphabetized(filelist, temp->filename, temp->offset, 0, false);
+ }
+ return true;
+}
+
+boolean GetPackTextureDirs(DIRLIST **dirlist)
+{
+ UInt16 i;
+ char buf[57];
+
+ if (!pakopen)
+ return 1;
+
+ if (g_bPK3)
+ {
+ StrList *pl = g_PK3TexturePaths.Next();
+ while (pl != NULL)
+ {
+ AddToDirListAlphabetized(dirlist, pl->Ref(), 0);
+ pl = pl->Next();
+ }
+ return true;
+ }
+
+ for (i = 0; i < dirsize; i++)
+ {
+ if(!strnicmp(pakdirptr[i].name, "textures", 8))
+ {
+ strncpy(buf, &(pakdirptr[i].name[9]), 46);
+ if(strchr(buf, '\\'))
+ *strchr(buf, '\\') = '\0';
+ else if(strchr(buf, '/'))
+ *strchr(buf, '/') = '\0';
+ else
+ buf[56] = '\0';
+
+ if(strchr(buf, '.'))
+ continue;
+
+ AddToDirListAlphabetized(dirlist, buf, 0);
+ }
+ }
+ return true;
+}
+
+boolean AddToDirListAlphabetized(DIRLIST **list, char *dirname, int from)
+{
+ DIRLIST *currentPtr, *previousPtr, *newPtr;
+
+ strlwr(dirname);
+ for(currentPtr = *list; currentPtr; currentPtr = currentPtr->next)
+ {
+ if(!stricmp(dirname, currentPtr->dirname))
+ {
+ return false;
+ }
+ }
+ previousPtr = NULL;
+ currentPtr = *list;
+
+ if((newPtr = (DIRLIST *)__qmalloc(sizeof(DIRLIST))) == NULL)
+ return false;
+
+ strcpy(newPtr->dirname, dirname);
+ newPtr->from = from;
+
+ while(currentPtr != NULL && stricmp(dirname, currentPtr->dirname) > 0)
+ {
+ previousPtr = currentPtr;
+ currentPtr = currentPtr->next;
+ } //End while
+ if(previousPtr == NULL)
+ {
+ newPtr->next = *list;
+ *list = newPtr;
+ } //End if
+ else
+ {
+ previousPtr->next = newPtr;
+ newPtr->next = currentPtr;
+ } //End else
+ return true;
+}
+
+boolean AddToFileListAlphabetized(FILELIST **list, char *filename, UInt32 offset, UInt32 size, boolean dirs)
+{
+ FILELIST *currentPtr, *previousPtr, *newPtr;
+
+ for(currentPtr = *list; currentPtr; currentPtr = currentPtr->next)
+ {
+ if(!stricmp(filename, currentPtr->filename))
+ {
+ return false;
+ }
+ }
+ previousPtr = NULL;
+ currentPtr = *list;
+
+ if((newPtr = (FILELIST *)__qmalloc(sizeof(FILELIST))) == NULL)
+ return false;
+
+ strcpy(newPtr->filename, filename);
+ newPtr->offset = offset;
+ newPtr->size = size;
+
+ while(currentPtr != NULL && stricmp(filename, currentPtr->filename) > 0)
+ {
+ previousPtr = currentPtr;
+ currentPtr = currentPtr->next;
+ } //End while
+ if(previousPtr == NULL)
+ {
+ newPtr->next = *list;
+ *list = newPtr;
+ } //End if
+ else
+ {
+ previousPtr->next = newPtr;
+ newPtr->next = currentPtr;
+ } //End else
+ return true;
+}
+
+boolean PakLoadFile(const char *filename, void **bufferptr)
+{
+ FILELIST *p = NULL;
+ DIRECTORY *dummy;
+ void *buffer;
+ char *str1, *str2;
+
+ if(!pakopen)
+ return false;
+
+ Str str(filename);
+ __ConvertDOSToUnixName(str, str);
+
+ dummy = paktextures;
+ str1 = str;
+
+ while(strchr(str1, '/'))
+ {
+ str2 = strchr(str1, '/');
+ *str2++ = '\0';
+ dummy = FindPakDir(dummy, str1);
+ if(!dummy)
+ return false;
+ str1 = str2;
+ }
+
+ // FIXME: add error handling routines
+ for(p = dummy->files; p; p = p->next)
+ {
+ if(!stricmp(str1, p->filename))
+ {
+ if (fseek(pakfile[m_nPAKIndex], p->offset, SEEK_SET) < 0)
+ {
+ //Sys_Printf("Unexpected EOF in pakfile\n");
+ return false;
+ }
+ if((buffer = __qmalloc(p->size+5)) == NULL)
+ //Error("Could not allocate memory");
+
+ if(fread(buffer, 1, p->size, pakfile[m_nPAKIndex]) != p->size)
+ {
+ //Sys_Printf("Error reading %s from pak\n", str1);
+ free(buffer);
+ return false;
+ }
+ *bufferptr = buffer;
+ return true;
+ }
+ }
+ return false;
+}
+
+int PakLoadAnyFile(const char *filename, void **bufferptr)
+{
+ char cWork[WORK_LEN];
+ if (g_bPK3)
+ {
+ PK3FileInfo *pInfo;
+ Str strKey;
+ // need to lookup the file without the base/texture path on it
+ Str strBase(g_strBasePath);
+ AddSlash(strBase);
+ __ConvertDOSToUnixName(cWork, strBase);
+ Str strFile(filename);
+ __ConvertDOSToUnixName(strFile, strFile);
+ strFile.MakeLower();
+ strlwr(cWork);
+ FindReplace(strFile, cWork, "");
+
+ PK3FileInfo infoFind;
+ infoFind.m_pName = __StrDup(strFile.GetBuffer());
+ PK3List *pList = g_PK3Files.Find(&infoFind);
+ if (pList)
+ {
+ pInfo = pList->Ptr();
+ memcpy(pInfo->m_zFile, &pInfo->m_zInfo, sizeof(unz_s));
+ if (unzOpenCurrentFile(pInfo->m_zFile) == UNZ_OK)
+ {
+ void *buffer = __qblockmalloc(pInfo->m_lSize+1);
+ int n = unzReadCurrentFile(pInfo->m_zFile , buffer, pInfo->m_lSize);
+ *bufferptr = buffer;
+ unzCloseCurrentFile(pInfo->m_zFile);
+ return n;
+ }
+ }
+#ifdef LOG_PAKFAIL
+ sprintf(cWork, "PAK failed on %s\n", filename);
+ g_LogFile.Log(cWork);
+#endif
+ return -1;
+ }
+
+ for (int i = 0; i < dirsize; i++)
+ {
+ if(!stricmp(filename, pakdirptr[i].name))
+ {
+ if (fseek(pakfile[m_nPAKIndex], pakdirptr[i].offset, SEEK_SET) >= 0)
+ {
+ void *buffer = __qmalloc (pakdirptr[i].size+1);
+ ((char *)buffer)[pakdirptr[i].size] = 0;
+ if (fread(buffer, 1, pakdirptr[i].size, pakfile[m_nPAKIndex]) == pakdirptr[i].size)
+ {
+ *bufferptr = buffer;
+ return pakdirptr[i].size;
+ }
+ }
+ }
+ }
+#ifdef LOG_PAKFAIL
+ sprintf(cWork, "PAK failed on %s\n", filename);
+ g_LogFile.Log(cWork);
+#endif
+ return -1;
+}
+
+
+
+DIRECTORY *AddPakDir(DIRECTORY **dir, char *name)
+{
+ DIRECTORY *currentPtr, *previousPtr, *newPtr;
+
+ for(currentPtr = *dir; currentPtr; currentPtr = currentPtr->next)
+ {
+ if(!stricmp(name, currentPtr->name))
+ {
+ return currentPtr;
+ }
+ }
+ previousPtr = NULL;
+ currentPtr = *dir;
+
+ if((newPtr = (DIRECTORY *)__qmalloc(sizeof(DIRECTORY))) == NULL)
+ return NULL;
+
+ strcpy(newPtr->name, name);
+ newPtr->files = NULL;
+
+ while(currentPtr != NULL && stricmp(name, currentPtr->name) > 0)
+ {
+ previousPtr = currentPtr;
+ currentPtr = currentPtr->next;
+ }
+ if(previousPtr == NULL)
+ {
+ newPtr->next = *dir;
+ *dir = newPtr;
+ }
+ else
+ {
+ previousPtr->next = newPtr;
+ newPtr->next = currentPtr;
+ }
+ return newPtr;
+}
+
+
+// OpenPK3
+// -------
+// Opens a PK3 ( or zip ) file and creates a list of filenames
+// and zip info structures
+//
+boolean OpenPK3(const char *filename)
+{
+ char cFilename[WORK_LEN];
+ char cName[WORK_LEN];
+ char cWork[WORK_LEN];
+ unz_file_info zInfo;
+ unzFile *zFile = new unzFile(unzOpen(filename));
+ g_zFiles.Add(zFile);
+ if (zFile != NULL)
+ {
+ int nStatus = unzGoToFirstFile(*zFile);
+ while (nStatus == UNZ_OK)
+ {
+ cFilename[0] = '\0';
+ unzGetCurrentFileInfo(*zFile, &zInfo, cFilename, WORK_LEN, NULL, 0, NULL, 0);
+ strlwr(cFilename);
+ __ConvertDOSToUnixName( cWork, cFilename);
+ if (strstr(cWork, ".") != NULL)
+ {
+ PK3FileInfo *pInfo = new PK3FileInfo();
+ pInfo->m_pName = __StrDup(cWork);
+ memcpy(&pInfo->m_zInfo, (unz_s*)*zFile, sizeof(unz_s));
+ pInfo->m_lSize = zInfo.uncompressed_size;
+ pInfo->m_zFile = *zFile;
+ g_PK3Files.Add(pInfo);
+ }
+ char *p = strstr(cFilename, TEXTURE_PATH);
+ if (p != NULL)
+ {
+ // FIXME: path differences per os ?
+ // catch solo directory entry
+ if (strlen(p) > strlen(TEXTURE_PATH) + 1)
+ {
+ // skip textures + path seperator
+ p += strlen(TEXTURE_PATH) + 1;
+ int nEnd = strcspn(p, PATH_SEPERATORS);
+ strncpy(cName, p, nEnd);
+ cName[nEnd] = '\0';
+
+ boolean bFound = false;
+ StrList *pl = g_PK3TexturePaths.Next();
+ while (pl != NULL)
+ {
+ if (strcmpi(pl->Ref(), cName) == 0)
+ {
+ // already have this, continue
+ bFound = true;
+ break;
+ }
+ pl = pl->Next();
+ }
+ if (!bFound)
+ {
+ g_PK3TexturePaths.Add(new Str(cName));
+ }
+ }
+ }
+ nStatus = unzGoToNextFile(*zFile);
+ }
+ }
+ return (zFile != NULL);
+}
+
+void closePK3(unzFile zf)
+{
+ unzClose(zf);
+}
+
+void OpenPakFile(const char *filename)
+{
+ int i;
+ char *str1, *str2;
+ DIRECTORY *dummy;
+
+ if(!pakopen)
+ paktextures = NULL;
+
+ HavePakColormap = false;
+
+ Str strTest(filename);
+ strTest.MakeLower();
+ if (strTest.Find("pk3") >= 0 || strTest.Find("zip") >= 0)
+ {
+ pakopen = g_bPK3 = OpenPK3(filename);
+ return;
+ }
+
+
+ if((pakfile[m_nPAKIndex] = OpenFileReadMagic(filename, &f_type)) == NULL)
+ {
+ //FIXME: error routine
+ //Sys_Printf("ERROR: Could not open %s", filename);
+ return;
+ }
+ if(f_type != FTYPE_PACK)
+ {
+ //Sys_Printf("ERROR: %s is not a valid pack file", filename);
+ if(f_type != FTYPE_ERROR)
+ fclose(pakfile[m_nPAKIndex]);
+ return;
+ }
+ pakdirptr = ReadPACKDirectory(pakfile[m_nPAKIndex], 0, &dirsize);
+ if (pakdirptr == NULL)
+ {
+ //Sys_Printf("ERROR: Could not read pack directory", filename);
+ fclose(pakfile[m_nPAKIndex]);
+ return;
+ }
+ if (dirsize == 0)
+ {
+ fclose(pakfile[m_nPAKIndex]);
+ return;
+ }
+ for (i = 0; i < dirsize; i++)
+ {
+ if(!strnicmp("textures/", pakdirptr[i].name, 9))
+ {
+ dummy = paktextures;
+ str1 = pakdirptr[i].name+9;
+ while(strchr(str1, '/'))
+ {
+ str2 = strchr(str1, '/');
+ *str2++ = '\0';
+ dummy = AddPakDir(dummy==paktextures?&paktextures:&dummy, str1);
+ str1 = str2;
+ }
+
+ AddToFileListAlphabetized(&(dummy->files), str1, pakdirptr[i].offset, pakdirptr[i].size, true);
+ }
+ else if(!strnicmp("pics/colormap.pcx", pakdirptr[i].name, 17))
+ {
+ HavePakColormap = true;
+ PakColormapOffset = pakdirptr[i].offset;
+ PakColormapSize = pakdirptr[i].size;
+ }
+ }
+ pakopen = true;
+
+}
+
+void ClearPaKDir(DIRECTORY **dir)
+{
+ DIRECTORY *d1 = *dir, *d2;
+
+ while(d1)
+ {
+ ClearFileList(&(d1->files));
+ d2 = d1;
+ d1 = d1->next;
+ free(d2);
+ }
+}
+
+void CleanUpPakDirs()
+{
+ ClearPaKDir(&paktextures);
+ paktextures = NULL;
+ dirhead = NULL;
+ g_PK3TexturePaths.RemoveAll();
+ g_PK3Files.RemoveAll();
+}
+
+void ClosePakFile(void)
+{
+ if(pakopen)
+ {
+ if (g_bPK3)
+ {
+ ZFileList *p = g_zFiles.Next();
+ while (p != NULL)
+ {
+ unzFile uz = p->Ref();
+ closePK3(uz);
+ p = p->Next();
+ }
+ }
+ else
+ {
+ fclose(pakfile[m_nPAKIndex]);
+ }
+ }
+ pakopen = false;
+ CleanUpPakDirs();
+}
+
+
+void WINAPI InitPakFile(const char * pBasePath, const char *pName)
+{
+ m_nPAKIndex = 0;
+ pakopen = false;
+ paktextures = NULL;
+ strcpy(g_strBasePath, pBasePath);
+ if (pName == NULL)
+ {
+ char cWork[WORK_LEN];
+ Str strPath(pBasePath);
+ AddSlash(strPath);
+ strPath += "*.pk3";
+ bool bGo = true;
+ struct _finddata_t fileinfo;
+ int handle = _findfirst (strPath, &fileinfo);
+ if (handle != -1)
+ {
+ do
+ {
+ sprintf(cWork, "%s\\%s", pBasePath, fileinfo.name);
+ OpenPakFile(cWork);
+ } while (_findnext( handle, &fileinfo ) != -1);
+ _findclose (handle);
+ }
+ }
+ else
+ {
+ OpenPakFile(pName);
+ }
+}
+
diff --git a/libs/pak/unzip.cpp b/libs/pak/unzip.cpp
new file mode 100755
index 0000000..20087da
--- /dev/null
+++ b/libs/pak/unzip.cpp
@@ -0,0 +1,4546 @@
+/*****************************************************************************
+ * name: unzip.c
+ *
+ * desc: IO on .zip files using portions of zlib
+ *
+ * $Archive: /source/code/qcommon/unzip.c $
+ * $Author: ttimo $
+ * $Revision: 1.1.1.3 $
+ * $Modtime: 10/19/99 3:59p $
+ * $Date: 2000/01/11 16:37:27 $
+ *
+ *****************************************************************************/
+
+#include <stdio.h>
+#include <string.h>
+#include <windows.h>
+#include "unzip.h"
+//#include "cmdlib.h"
+
+/* unzip.h -- IO for uncompress .zip files using zlib
+ Version 0.15 beta, Mar 19th, 1998,
+
+ Copyright (C) 1998 Gilles Vollant
+
+ This unzip package allow extract file from .ZIP file, compatible with PKZip 2.04g
+ WinZip, InfoZip tools and compatible.
+ Encryption and multi volume ZipFile (span) are not supported.
+ Old compressions used by old PKZip 1.x are not supported
+
+ THIS IS AN ALPHA VERSION. AT THIS STAGE OF DEVELOPPEMENT, SOMES API OR STRUCTURE
+ CAN CHANGE IN FUTURE VERSION !!
+ I WAIT FEEDBACK at mail info@winimage.com
+ Visit also http://www.winimage.com/zLibDll/unzip.htm for evolution
+
+ Condition of use and distribution are the same than zlib :
+
+ This software is provided 'as-is', without any express or implied
+ warranty. In no event will the authors be held liable for any damages
+ arising from the use of this software.
+
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
+
+
+*/
+/* for more info about .ZIP format, see
+ ftp://ftp.cdrom.com/pub/infozip/doc/appnote-970311-iz.zip
+ PkWare has also a specification at :
+ ftp://ftp.pkware.com/probdesc.zip */
+
+/* zlib.h -- interface of the 'zlib' general purpose compression library
+ version 1.1.3, July 9th, 1998
+
+ Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler
+
+ This software is provided 'as-is', without any express or implied
+ warranty. In no event will the authors be held liable for any damages
+ arising from the use of this software.
+
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
+
+ Jean-loup Gailly Mark Adler
+ jloup@gzip.org madler@alumni.caltech.edu
+
+
+ The data format used by the zlib library is described by RFCs (Request for
+ Comments) 1950 to 1952 in the files ftp://ds.internic.net/rfc/rfc1950.txt
+ (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
+*/
+
+/* zconf.h -- configuration of the zlib compression library
+ * Copyright (C) 1995-1998 Jean-loup Gailly.
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* @(#) $Id: unzip.cpp,v 1.1.1.3 2000/01/11 16:37:27 ttimo Exp $ */
+
+#ifndef _ZCONF_H
+#define _ZCONF_H
+
+/* Maximum value for memLevel in deflateInit2 */
+#ifndef MAX_MEM_LEVEL
+# ifdef MAXSEG_64K
+# define MAX_MEM_LEVEL 8
+# else
+# define MAX_MEM_LEVEL 9
+# endif
+#endif
+
+/* Maximum value for windowBits in deflateInit2 and inflateInit2.
+ * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
+ * created by gzip. (Files created by minigzip can still be extracted by
+ * gzip.)
+ */
+#ifndef MAX_WBITS
+# define MAX_WBITS 15 /* 32K LZ77 window */
+#endif
+
+/* The memory requirements for deflate are (in bytes):
+ (1 << (windowBits+2)) + (1 << (memLevel+9))
+ that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
+ plus a few kilobytes for small objects. For example, if you want to reduce
+ the default memory requirements from 256K to 128K, compile with
+ make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
+ Of course this will generally degrade compression (there's no free lunch).
+
+ The memory requirements for inflate are (in bytes) 1 << windowBits
+ that is, 32K for windowBits=15 (default value) plus a few kilobytes
+ for small objects.
+*/
+
+ /* Type declarations */
+
+#ifndef OF /* function prototypes */
+#define OF(args) args
+#endif
+
+typedef unsigned char Byte; /* 8 bits */
+typedef unsigned int uInt; /* 16 bits or more */
+typedef unsigned long uLong; /* 32 bits or more */
+typedef Byte *voidp;
+
+#ifndef SEEK_SET
+# define SEEK_SET 0 /* Seek from beginning of file. */
+# define SEEK_CUR 1 /* Seek from current position. */
+# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
+#endif
+
+#endif /* _ZCONF_H */
+
+#define ZLIB_VERSION "1.1.3"
+
+/*
+ The 'zlib' compression library provides in-memory compression and
+ decompression functions, including integrity checks of the uncompressed
+ data. This version of the library supports only one compression method
+ (deflation) but other algorithms will be added later and will have the same
+ stream interface.
+
+ Compression can be done in a single step if the buffers are large
+ enough (for example if an input file is mmap'ed), or can be done by
+ repeated calls of the compression function. In the latter case, the
+ application must provide more input and/or consume the output
+ (providing more output space) before each call.
+
+ The library also supports reading and writing files in gzip (.gz) format
+ with an interface similar to that of stdio.
+
+ The library does not install any signal handler. The decoder checks
+ the consistency of the compressed data, so the library should never
+ crash even in case of corrupted input.
+*/
+
+/*
+ The application must update next_in and avail_in when avail_in has
+ dropped to zero. It must update next_out and avail_out when avail_out
+ has dropped to zero. The application must initialize zalloc, zfree and
+ opaque before calling the init function. All other fields are set by the
+ compression library and must not be updated by the application.
+
+ The opaque value provided by the application will be passed as the first
+ parameter for calls of zalloc and zfree. This can be useful for custom
+ memory management. The compression library attaches no meaning to the
+ opaque value.
+
+ zalloc must return Z_NULL if there is not enough memory for the object.
+ If zlib is used in a multi-threaded application, zalloc and zfree must be
+ thread safe.
+
+ On 16-bit systems, the functions zalloc and zfree must be able to allocate
+ exactly 65536 bytes, but will not be required to allocate more than this
+ if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
+ pointers returned by zalloc for objects of exactly 65536 bytes *must*
+ have their offset normalized to zero. The default allocation function
+ provided by this library ensures this (see zutil.c). To reduce memory
+ requirements and avoid any allocation of 64K objects, at the expense of
+ compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
+
+ The fields total_in and total_out can be used for statistics or
+ progress reports. After compression, total_in holds the total size of
+ the uncompressed data and may be saved for use in the decompressor
+ (particularly if the decompressor wants to decompress everything in
+ a single step).
+*/
+
+ /* constants */
+
+#define Z_NO_FLUSH 0
+#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
+#define Z_SYNC_FLUSH 2
+#define Z_FULL_FLUSH 3
+#define Z_FINISH 4
+/* Allowed flush values; see deflate() below for details */
+
+#define Z_OK 0
+#define Z_STREAM_END 1
+#define Z_NEED_DICT 2
+#define Z_ERRNO (-1)
+#define Z_STREAM_ERROR (-2)
+#define Z_DATA_ERROR (-3)
+#define Z_MEM_ERROR (-4)
+#define Z_BUF_ERROR (-5)
+#define Z_VERSION_ERROR (-6)
+/* Return codes for the compression/decompression functions. Negative
+ * values are errors, positive values are used for special but normal events.
+ */
+
+#define Z_NO_COMPRESSION 0
+#define Z_BEST_SPEED 1
+#define Z_BEST_COMPRESSION 9
+#define Z_DEFAULT_COMPRESSION (-1)
+/* compression levels */
+
+#define Z_FILTERED 1
+#define Z_HUFFMAN_ONLY 2
+#define Z_DEFAULT_STRATEGY 0
+/* compression strategy; see deflateInit2() below for details */
+
+#define Z_BINARY 0
+#define Z_ASCII 1
+#define Z_UNKNOWN 2
+/* Possible values of the data_type field */
+
+#define Z_DEFLATED 8
+/* The deflate compression method (the only one supported in this version) */
+
+#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
+
+#define zlib_version zlibVersion()
+/* for compatibility with versions < 1.0.2 */
+
+ /* basic functions */
+
+const char * zlibVersion OF((void));
+/* The application can compare zlibVersion and ZLIB_VERSION for consistency.
+ If the first character differs, the library code actually used is
+ not compatible with the zlib.h header file used by the application.
+ This check is automatically made by deflateInit and inflateInit.
+ */
+
+/*
+int deflateInit OF((z_streamp strm, int level));
+
+ Initializes the internal stream state for compression. The fields
+ zalloc, zfree and opaque must be initialized before by the caller.
+ If zalloc and zfree are set to Z_NULL, deflateInit updates them to
+ use default allocation functions.
+
+ The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
+ 1 gives best speed, 9 gives best compression, 0 gives no compression at
+ all (the input data is simply copied a block at a time).
+ Z_DEFAULT_COMPRESSION requests a default compromise between speed and
+ compression (currently equivalent to level 6).
+
+ deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
+ enough memory, Z_STREAM_ERROR if level is not a valid compression level,
+ Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
+ with the version assumed by the caller (ZLIB_VERSION).
+ msg is set to null if there is no error message. deflateInit does not
+ perform any compression: this will be done by deflate().
+*/
+
+
+int deflate OF((z_streamp strm, int flush));
+/*
+ deflate compresses as much data as possible, and stops when the input
+ buffer becomes empty or the output buffer becomes full. It may introduce some
+ output latency (reading input without producing any output) except when
+ forced to flush.
+
+ The detailed semantics are as follows. deflate performs one or both of the
+ following actions:
+
+ - Compress more input starting at next_in and update next_in and avail_in
+ accordingly. If not all input can be processed (because there is not
+ enough room in the output buffer), next_in and avail_in are updated and
+ processing will resume at this point for the next call of deflate().
+
+ - Provide more output starting at next_out and update next_out and avail_out
+ accordingly. This action is forced if the parameter flush is non zero.
+ Forcing flush frequently degrades the compression ratio, so this parameter
+ should be set only when necessary (in interactive applications).
+ Some output may be provided even if flush is not set.
+
+ Before the call of deflate(), the application should ensure that at least
+ one of the actions is possible, by providing more input and/or consuming
+ more output, and updating avail_in or avail_out accordingly; avail_out
+ should never be zero before the call. The application can consume the
+ compressed output when it wants, for example when the output buffer is full
+ (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
+ and with zero avail_out, it must be called again after making room in the
+ output buffer because there might be more output pending.
+
+ If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
+ flushed to the output buffer and the output is aligned on a byte boundary, so
+ that the decompressor can get all input data available so far. (In particular
+ avail_in is zero after the call if enough output space has been provided
+ before the call.) Flushing may degrade compression for some compression
+ algorithms and so it should be used only when necessary.
+
+ If flush is set to Z_FULL_FLUSH, all output is flushed as with
+ Z_SYNC_FLUSH, and the compression state is reset so that decompression can
+ restart from this point if previous compressed data has been damaged or if
+ random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
+ the compression.
+
+ If deflate returns with avail_out == 0, this function must be called again
+ with the same value of the flush parameter and more output space (updated
+ avail_out), until the flush is complete (deflate returns with non-zero
+ avail_out).
+
+ If the parameter flush is set to Z_FINISH, pending input is processed,
+ pending output is flushed and deflate returns with Z_STREAM_END if there
+ was enough output space; if deflate returns with Z_OK, this function must be
+ called again with Z_FINISH and more output space (updated avail_out) but no
+ more input data, until it returns with Z_STREAM_END or an error. After
+ deflate has returned Z_STREAM_END, the only possible operations on the
+ stream are deflateReset or deflateEnd.
+
+ Z_FINISH can be used immediately after deflateInit if all the compression
+ is to be done in a single step. In this case, avail_out must be at least
+ 0.1% larger than avail_in plus 12 bytes. If deflate does not return
+ Z_STREAM_END, then it must be called again as described above.
+
+ deflate() sets strm->adler to the adler32 checksum of all input read
+ so (that is, total_in bytes).
+
+ deflate() may update data_type if it can make a good guess about
+ the input data type (Z_ASCII or Z_BINARY). In doubt, the data is considered
+ binary. This field is only for information purposes and does not affect
+ the compression algorithm in any manner.
+
+ deflate() returns Z_OK if some progress has been made (more input
+ processed or more output produced), Z_STREAM_END if all input has been
+ consumed and all output has been produced (only when flush is set to
+ Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
+ if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
+ (for example avail_in or avail_out was zero).
+*/
+
+
+int deflateEnd OF((z_streamp strm));
+/*
+ All dynamically allocated data structures for this stream are freed.
+ This function discards any unprocessed input and does not flush any
+ pending output.
+
+ deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
+ stream state was inconsistent, Z_DATA_ERROR if the stream was freed
+ prematurely (some input or output was discarded). In the error case,
+ msg may be set but then points to a static string (which must not be
+ deallocated).
+*/
+
+
+/*
+int inflateInit OF((z_streamp strm));
+
+ Initializes the internal stream state for decompression. The fields
+ next_in, avail_in, zalloc, zfree and opaque must be initialized before by
+ the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
+ value depends on the compression method), inflateInit determines the
+ compression method from the zlib header and allocates all data structures
+ accordingly; otherwise the allocation will be deferred to the first call of
+ inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
+ use default allocation functions.
+
+ inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
+ memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
+ version assumed by the caller. msg is set to null if there is no error
+ message. inflateInit does not perform any decompression apart from reading
+ the zlib header if present: this will be done by inflate(). (So next_in and
+ avail_in may be modified, but next_out and avail_out are unchanged.)
+*/
+
+
+int inflate OF((z_streamp strm, int flush));
+/*
+ inflate decompresses as much data as possible, and stops when the input
+ buffer becomes empty or the output buffer becomes full. It may some
+ introduce some output latency (reading input without producing any output)
+ except when forced to flush.
+
+ The detailed semantics are as follows. inflate performs one or both of the
+ following actions:
+
+ - Decompress more input starting at next_in and update next_in and avail_in
+ accordingly. If not all input can be processed (because there is not
+ enough room in the output buffer), next_in is updated and processing
+ will resume at this point for the next call of inflate().
+
+ - Provide more output starting at next_out and update next_out and avail_out
+ accordingly. inflate() provides as much output as possible, until there
+ is no more input data or no more space in the output buffer (see below
+ about the flush parameter).
+
+ Before the call of inflate(), the application should ensure that at least
+ one of the actions is possible, by providing more input and/or consuming
+ more output, and updating the next_* and avail_* values accordingly.
+ The application can consume the uncompressed output when it wants, for
+ example when the output buffer is full (avail_out == 0), or after each
+ call of inflate(). If inflate returns Z_OK and with zero avail_out, it
+ must be called again after making room in the output buffer because there
+ might be more output pending.
+
+ If the parameter flush is set to Z_SYNC_FLUSH, inflate flushes as much
+ output as possible to the output buffer. The flushing behavior of inflate is
+ not specified for values of the flush parameter other than Z_SYNC_FLUSH
+ and Z_FINISH, but the current implementation actually flushes as much output
+ as possible anyway.
+
+ inflate() should normally be called until it returns Z_STREAM_END or an
+ error. However if all decompression is to be performed in a single step
+ (a single call of inflate), the parameter flush should be set to
+ Z_FINISH. In this case all pending input is processed and all pending
+ output is flushed; avail_out must be large enough to hold all the
+ uncompressed data. (The size of the uncompressed data may have been saved
+ by the compressor for this purpose.) The next operation on this stream must
+ be inflateEnd to deallocate the decompression state. The use of Z_FINISH
+ is never required, but can be used to inform inflate that a faster routine
+ may be used for the single inflate() call.
+
+ If a preset dictionary is needed at this point (see inflateSetDictionary
+ below), inflate sets strm-adler to the adler32 checksum of the
+ dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise
+ it sets strm->adler to the adler32 checksum of all output produced
+ so (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or
+ an error code as described below. At the end of the stream, inflate()
+ checks that its computed adler32 checksum is equal to that saved by the
+ compressor and returns Z_STREAM_END only if the checksum is correct.
+
+ inflate() returns Z_OK if some progress has been made (more input processed
+ or more output produced), Z_STREAM_END if the end of the compressed data has
+ been reached and all uncompressed output has been produced, Z_NEED_DICT if a
+ preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
+ corrupted (input stream not conforming to the zlib format or incorrect
+ adler32 checksum), Z_STREAM_ERROR if the stream structure was inconsistent
+ (for example if next_in or next_out was NULL), Z_MEM_ERROR if there was not
+ enough memory, Z_BUF_ERROR if no progress is possible or if there was not
+ enough room in the output buffer when Z_FINISH is used. In the Z_DATA_ERROR
+ case, the application may then call inflateSync to look for a good
+ compression block.
+*/
+
+
+int inflateEnd OF((z_streamp strm));
+/*
+ All dynamically allocated data structures for this stream are freed.
+ This function discards any unprocessed input and does not flush any
+ pending output.
+
+ inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
+ was inconsistent. In the error case, msg may be set but then points to a
+ static string (which must not be deallocated).
+*/
+
+ /* Advanced functions */
+
+/*
+ The following functions are needed only in some special applications.
+*/
+
+/*
+int deflateInit2 OF((z_streamp strm,
+ int level,
+ int method,
+ int windowBits,
+ int memLevel,
+ int strategy));
+
+ This is another version of deflateInit with more compression options. The
+ fields next_in, zalloc, zfree and opaque must be initialized before by
+ the caller.
+
+ The method parameter is the compression method. It must be Z_DEFLATED in
+ this version of the library.
+
+ The windowBits parameter is the base two logarithm of the window size
+ (the size of the history buffer). It should be in the range 8..15 for this
+ version of the library. Larger values of this parameter result in better
+ compression at the expense of memory usage. The default value is 15 if
+ deflateInit is used instead.
+
+ The memLevel parameter specifies how much memory should be allocated
+ for the internal compression state. memLevel=1 uses minimum memory but
+ is slow and reduces compression ratio; memLevel=9 uses maximum memory
+ for optimal speed. The default value is 8. See zconf.h for total memory
+ usage as a function of windowBits and memLevel.
+
+ The strategy parameter is used to tune the compression algorithm. Use the
+ value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
+ filter (or predictor), or Z_HUFFMAN_ONLY to force Huffman encoding only (no
+ string match). Filtered data consists mostly of small values with a
+ somewhat random distribution. In this case, the compression algorithm is
+ tuned to compress them better. The effect of Z_FILTERED is to force more
+ Huffman coding and less string matching; it is somewhat intermediate
+ between Z_DEFAULT and Z_HUFFMAN_ONLY. The strategy parameter only affects
+ the compression ratio but not the correctness of the compressed output even
+ if it is not set appropriately.
+
+ deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+ memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
+ method). msg is set to null if there is no error message. deflateInit2 does
+ not perform any compression: this will be done by deflate().
+*/
+
+int deflateSetDictionary OF((z_streamp strm,
+ const Byte *dictionary,
+ uInt dictLength));
+/*
+ Initializes the compression dictionary from the given byte sequence
+ without producing any compressed output. This function must be called
+ immediately after deflateInit, deflateInit2 or deflateReset, before any
+ call of deflate. The compressor and decompressor must use exactly the same
+ dictionary (see inflateSetDictionary).
+
+ The dictionary should consist of strings (byte sequences) that are likely
+ to be encountered later in the data to be compressed, with the most commonly
+ used strings preferably put towards the end of the dictionary. Using a
+ dictionary is most useful when the data to be compressed is short and can be
+ predicted with good accuracy; the data can then be compressed better than
+ with the default empty dictionary.
+
+ Depending on the size of the compression data structures selected by
+ deflateInit or deflateInit2, a part of the dictionary may in effect be
+ discarded, for example if the dictionary is larger than the window size in
+ deflate or deflate2. Thus the strings most likely to be useful should be
+ put at the end of the dictionary, not at the front.
+
+ Upon return of this function, strm->adler is set to the Adler32 value
+ of the dictionary; the decompressor may later use this value to determine
+ which dictionary has been used by the compressor. (The Adler32 value
+ applies to the whole dictionary even if only a subset of the dictionary is
+ actually used by the compressor.)
+
+ deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
+ parameter is invalid (such as NULL dictionary) or the stream state is
+ inconsistent (for example if deflate has already been called for this stream
+ or if the compression method is bsort). deflateSetDictionary does not
+ perform any compression: this will be done by deflate().
+*/
+
+int deflateCopy OF((z_streamp dest,
+ z_streamp source));
+/*
+ Sets the destination stream as a complete copy of the source stream.
+
+ This function can be useful when several compression strategies will be
+ tried, for example when there are several ways of pre-processing the input
+ data with a filter. The streams that will be discarded should then be freed
+ by calling deflateEnd. Note that deflateCopy duplicates the internal
+ compression state which can be quite large, so this strategy is slow and
+ can consume lots of memory.
+
+ deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
+ enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
+ (such as zalloc being NULL). msg is left unchanged in both source and
+ destination.
+*/
+
+int deflateReset OF((z_streamp strm));
+/*
+ This function is equivalent to deflateEnd followed by deflateInit,
+ but does not free and reallocate all the internal compression state.
+ The stream will keep the same compression level and any other attributes
+ that may have been set by deflateInit2.
+
+ deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
+ stream state was inconsistent (such as zalloc or state being NULL).
+*/
+
+int deflateParams OF((z_streamp strm,
+ int level,
+ int strategy));
+/*
+ Dynamically update the compression level and compression strategy. The
+ interpretation of level and strategy is as in deflateInit2. This can be
+ used to switch between compression and straight copy of the input data, or
+ to switch to a different kind of input data requiring a different
+ strategy. If the compression level is changed, the input available so far
+ is compressed with the old level (and may be flushed); the new level will
+ take effect only at the next call of deflate().
+
+ Before the call of deflateParams, the stream state must be set as for
+ a call of deflate(), since the currently available input may have to
+ be compressed and flushed. In particular, strm->avail_out must be non-zero.
+
+ deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
+ stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
+ if strm->avail_out was zero.
+*/
+
+/*
+int inflateInit2 OF((z_streamp strm,
+ int windowBits));
+
+ This is another version of inflateInit with an extra parameter. The
+ fields next_in, avail_in, zalloc, zfree and opaque must be initialized
+ before by the caller.
+
+ The windowBits parameter is the base two logarithm of the maximum window
+ size (the size of the history buffer). It should be in the range 8..15 for
+ this version of the library. The default value is 15 if inflateInit is used
+ instead. If a compressed stream with a larger window size is given as
+ input, inflate() will return with the error code Z_DATA_ERROR instead of
+ trying to allocate a larger window.
+
+ inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+ memory, Z_STREAM_ERROR if a parameter is invalid (such as a negative
+ memLevel). msg is set to null if there is no error message. inflateInit2
+ does not perform any decompression apart from reading the zlib header if
+ present: this will be done by inflate(). (So next_in and avail_in may be
+ modified, but next_out and avail_out are unchanged.)
+*/
+
+int inflateSetDictionary OF((z_streamp strm,
+ const Byte *dictionary,
+ uInt dictLength));
+/*
+ Initializes the decompression dictionary from the given uncompressed byte
+ sequence. This function must be called immediately after a call of inflate
+ if this call returned Z_NEED_DICT. The dictionary chosen by the compressor
+ can be determined from the Adler32 value returned by this call of
+ inflate. The compressor and decompressor must use exactly the same
+ dictionary (see deflateSetDictionary).
+
+ inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
+ parameter is invalid (such as NULL dictionary) or the stream state is
+ inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
+ expected one (incorrect Adler32 value). inflateSetDictionary does not
+ perform any decompression: this will be done by subsequent calls of
+ inflate().
+*/
+
+int inflateSync OF((z_streamp strm));
+/*
+ Skips invalid compressed data until a full flush point (see above the
+ description of deflate with Z_FULL_FLUSH) can be found, or until all
+ available input is skipped. No output is provided.
+
+ inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
+ if no more input was provided, Z_DATA_ERROR if no flush point has been found,
+ or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
+ case, the application may save the current current value of total_in which
+ indicates where valid compressed data was found. In the error case, the
+ application may repeatedly call inflateSync, providing more input each time,
+ until success or end of the input data.
+*/
+
+int inflateReset OF((z_streamp strm));
+/*
+ This function is equivalent to inflateEnd followed by inflateInit,
+ but does not free and reallocate all the internal decompression state.
+ The stream will keep attributes that may have been set by inflateInit2.
+
+ inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
+ stream state was inconsistent (such as zalloc or state being NULL).
+*/
+
+
+ /* utility functions */
+
+/*
+ The following utility functions are implemented on top of the
+ basic stream-oriented functions. To simplify the interface, some
+ default options are assumed (compression level and memory usage,
+ standard memory allocation functions). The source code of these
+ utility functions can easily be modified if you need special options.
+*/
+
+int compress OF((Byte *dest, uLong *destLen,
+ const Byte *source, uLong sourceLen));
+/*
+ Compresses the source buffer into the destination buffer. sourceLen is
+ the byte length of the source buffer. Upon entry, destLen is the total
+ size of the destination buffer, which must be at least 0.1% larger than
+ sourceLen plus 12 bytes. Upon exit, destLen is the actual size of the
+ compressed buffer.
+ This function can be used to compress a whole file at once if the
+ input file is mmap'ed.
+ compress returns Z_OK if success, Z_MEM_ERROR if there was not
+ enough memory, Z_BUF_ERROR if there was not enough room in the output
+ buffer.
+*/
+
+int compress2 OF((Byte *dest, uLong *destLen,
+ const Byte *source, uLong sourceLen,
+ int level));
+/*
+ Compresses the source buffer into the destination buffer. The level
+ parameter has the same meaning as in deflateInit. sourceLen is the byte
+ length of the source buffer. Upon entry, destLen is the total size of the
+ destination buffer, which must be at least 0.1% larger than sourceLen plus
+ 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
+
+ compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+ memory, Z_BUF_ERROR if there was not enough room in the output buffer,
+ Z_STREAM_ERROR if the level parameter is invalid.
+*/
+
+int uncompress OF((Byte *dest, uLong *destLen,
+ const Byte *source, uLong sourceLen));
+/*
+ Decompresses the source buffer into the destination buffer. sourceLen is
+ the byte length of the source buffer. Upon entry, destLen is the total
+ size of the destination buffer, which must be large enough to hold the
+ entire uncompressed data. (The size of the uncompressed data must have
+ been saved previously by the compressor and transmitted to the decompressor
+ by some mechanism outside the scope of this compression library.)
+ Upon exit, destLen is the actual size of the compressed buffer.
+ This function can be used to decompress a whole file at once if the
+ input file is mmap'ed.
+
+ uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
+ enough memory, Z_BUF_ERROR if there was not enough room in the output
+ buffer, or Z_DATA_ERROR if the input data was corrupted.
+*/
+
+
+typedef voidp gzFile;
+
+gzFile gzopen OF((const char *path, const char *mode));
+/*
+ Opens a gzip (.gz) file for reading or writing. The mode parameter
+ is as in fopen ("rb" or "wb") but can also include a compression level
+ ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
+ Huffman only compression as in "wb1h". (See the description
+ of deflateInit2 for more information about the strategy parameter.)
+
+ gzopen can be used to read a file which is not in gzip format; in this
+ case gzread will directly read from the file without decompression.
+
+ gzopen returns NULL if the file could not be opened or if there was
+ insufficient memory to allocate the (de)compression state; errno
+ can be checked to distinguish the two cases (if errno is zero, the
+ zlib error is Z_MEM_ERROR). */
+
+gzFile gzdopen OF((int fd, const char *mode));
+/*
+ gzdopen() associates a gzFile with the file descriptor fd. File
+ descriptors are obtained from calls like open, dup, creat, pipe or
+ fileno (in the file has been previously opened with fopen).
+ The mode parameter is as in gzopen.
+ The next call of gzclose on the returned gzFile will also close the
+ file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
+ descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
+ gzdopen returns NULL if there was insufficient memory to allocate
+ the (de)compression state.
+*/
+
+int gzsetparams OF((gzFile file, int level, int strategy));
+/*
+ Dynamically update the compression level or strategy. See the description
+ of deflateInit2 for the meaning of these parameters.
+ gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
+ opened for writing.
+*/
+
+int gzread OF((gzFile file, voidp buf, unsigned len));
+/*
+ Reads the given number of uncompressed bytes from the compressed file.
+ If the input file was not in gzip format, gzread copies the given number
+ of bytes into the buffer.
+ gzread returns the number of uncompressed bytes actually read (0 for
+ end of file, -1 for error). */
+
+int gzwrite OF((gzFile file,
+ const voidp buf, unsigned len));
+/*
+ Writes the given number of uncompressed bytes into the compressed file.
+ gzwrite returns the number of uncompressed bytes actually written
+ (0 in case of error).
+*/
+
+int gzprintf OF((gzFile file, const char *format, ...));
+/*
+ Converts, formats, and writes the args to the compressed file under
+ control of the format string, as in fprintf. gzprintf returns the number of
+ uncompressed bytes actually written (0 in case of error).
+*/
+
+int gzputs OF((gzFile file, const char *s));
+/*
+ Writes the given null-terminated string to the compressed file, excluding
+ the terminating null character.
+ gzputs returns the number of characters written, or -1 in case of error.
+*/
+
+char * gzgets OF((gzFile file, char *buf, int len));
+/*
+ Reads bytes from the compressed file until len-1 characters are read, or
+ a newline character is read and transferred to buf, or an end-of-file
+ condition is encountered. The string is then terminated with a null
+ character.
+ gzgets returns buf, or Z_NULL in case of error.
+*/
+
+int gzputc OF((gzFile file, int c));
+/*
+ Writes c, converted to an unsigned char, into the compressed file.
+ gzputc returns the value that was written, or -1 in case of error.
+*/
+
+int gzgetc OF((gzFile file));
+/*
+ Reads one byte from the compressed file. gzgetc returns this byte
+ or -1 in case of end of file or error.
+*/
+
+int gzflush OF((gzFile file, int flush));
+/*
+ Flushes all pending output into the compressed file. The parameter
+ flush is as in the deflate() function. The return value is the zlib
+ error number (see function gzerror below). gzflush returns Z_OK if
+ the flush parameter is Z_FINISH and all output could be flushed.
+ gzflush should be called only when strictly necessary because it can
+ degrade compression.
+*/
+
+long gzseek OF((gzFile file,
+ long offset, int whence));
+/*
+ Sets the starting position for the next gzread or gzwrite on the
+ given compressed file. The offset represents a number of bytes in the
+ uncompressed data stream. The whence parameter is defined as in lseek(2);
+ the value SEEK_END is not supported.
+ If the file is opened for reading, this function is emulated but can be
+ extremely slow. If the file is opened for writing, only forward seeks are
+ supported; gzseek then compresses a sequence of zeroes up to the new
+ starting position.
+
+ gzseek returns the resulting offset location as measured in bytes from
+ the beginning of the uncompressed stream, or -1 in case of error, in
+ particular if the file is opened for writing and the new starting position
+ would be before the current position.
+*/
+
+int gzrewind OF((gzFile file));
+/*
+ Rewinds the given file. This function is supported only for reading.
+
+ gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
+*/
+
+long gztell OF((gzFile file));
+/*
+ Returns the starting position for the next gzread or gzwrite on the
+ given compressed file. This position represents a number of bytes in the
+ uncompressed data stream.
+
+ gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
+*/
+
+int gzeof OF((gzFile file));
+/*
+ Returns 1 when EOF has previously been detected reading the given
+ input stream, otherwise zero.
+*/
+
+int gzclose OF((gzFile file));
+/*
+ Flushes all pending output if necessary, closes the compressed file
+ and deallocates all the (de)compression state. The return value is the zlib
+ error number (see function gzerror below).
+*/
+
+const char * gzerror OF((gzFile file, int *errnum));
+/*
+ Returns the error message for the last error which occurred on the
+ given compressed file. errnum is set to zlib error number. If an
+ error occurred in the file system and not in the compression library,
+ errnum is set to Z_ERRNO and the application may consult errno
+ to get the exact error code.
+*/
+
+ /* checksum functions */
+
+/*
+ These functions are not related to compression but are exported
+ anyway because they might be useful in applications using the
+ compression library.
+*/
+
+uLong adler32 OF((uLong adler, const Byte *buf, uInt len));
+
+/*
+ Update a running Adler-32 checksum with the bytes buf[0..len-1] and
+ return the updated checksum. If buf is NULL, this function returns
+ the required initial value for the checksum.
+ An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
+ much faster. Usage example:
+
+ uLong adler = adler32(0L, Z_NULL, 0);
+
+ while (read_buffer(buffer, length) != EOF) {
+ adler = adler32(adler, buffer, length);
+ }
+ if (adler != original_adler) error();
+*/
+
+uLong crc32 OF((uLong crc, const Byte *buf, uInt len));
+/*
+ Update a running crc with the bytes buf[0..len-1] and return the updated
+ crc. If buf is NULL, this function returns the required initial value
+ for the crc. Pre- and post-conditioning (one's complement) is performed
+ within this function so it shouldn't be done by the application.
+ Usage example:
+
+ uLong crc = crc32(0L, Z_NULL, 0);
+
+ while (read_buffer(buffer, length) != EOF) {
+ crc = crc32(crc, buffer, length);
+ }
+ if (crc != original_crc) error();
+*/
+
+// private stuff to not include cmdlib.h
+/*
+============================================================================
+
+ BYTE ORDER FUNCTIONS
+
+============================================================================
+*/
+
+#ifdef _SGI_SOURCE
+#define __BIG_ENDIAN__
+#endif
+
+#ifdef __BIG_ENDIAN__
+
+short __LittleShort (short l)
+{
+ byte b1,b2;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+
+ return (b1<<8) + b2;
+}
+
+short __BigShort (short l)
+{
+ return l;
+}
+
+
+int __LittleLong (int l)
+{
+ byte b1,b2,b3,b4;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+ b3 = (l>>16)&255;
+ b4 = (l>>24)&255;
+
+ return ((int)b1<<24) + ((int)b2<<16) + ((int)b3<<8) + b4;
+}
+
+int __BigLong (int l)
+{
+ return l;
+}
+
+
+float __LittleFloat (float l)
+{
+ union {byte b[4]; float f;} in, out;
+
+ in.f = l;
+ out.b[0] = in.b[3];
+ out.b[1] = in.b[2];
+ out.b[2] = in.b[1];
+ out.b[3] = in.b[0];
+
+ return out.f;
+}
+
+float __BigFloat (float l)
+{
+ return l;
+}
+
+
+#else
+
+
+short __BigShort (short l)
+{
+ byte b1,b2;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+
+ return (b1<<8) + b2;
+}
+
+short __LittleShort (short l)
+{
+ return l;
+}
+
+
+int __BigLong (int l)
+{
+ byte b1,b2,b3,b4;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+ b3 = (l>>16)&255;
+ b4 = (l>>24)&255;
+
+ return ((int)b1<<24) + ((int)b2<<16) + ((int)b3<<8) + b4;
+}
+
+int __LittleLong (int l)
+{
+ return l;
+}
+
+float __BigFloat (float l)
+{
+ union {byte b[4]; float f;} in, out;
+
+ in.f = l;
+ out.b[0] = in.b[3];
+ out.b[1] = in.b[2];
+ out.b[2] = in.b[1];
+ out.b[3] = in.b[0];
+
+ return out.f;
+}
+
+float __LittleFloat (float l)
+{
+ return l;
+}
+
+
+
+#endif
+
+
+
+
+ /* various hacks, don't look :) */
+
+/* deflateInit and inflateInit are macros to allow checking the zlib version
+ * and the compiler's view of z_stream:
+ */
+int deflateInit_ OF((z_streamp strm, int level,
+ const char *version, int stream_size));
+int inflateInit_ OF((z_streamp strm,
+ const char *version, int stream_size));
+int deflateInit2_ OF((z_streamp strm, int level, int method,
+ int windowBits, int memLevel,
+ int strategy, const char *version,
+ int stream_size));
+int inflateInit2_ OF((z_streamp strm, int windowBits,
+ const char *version, int stream_size));
+#define deflateInit(strm, level) \
+ deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
+#define inflateInit(strm) \
+ inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
+#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
+ deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
+ (strategy), ZLIB_VERSION, sizeof(z_stream))
+#define inflateInit2(strm, windowBits) \
+ inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
+
+
+const char * zError OF((int err));
+int inflateSyncPoint OF((z_streamp z));
+const uLong * get_crc_table OF((void));
+
+typedef unsigned char uch;
+typedef unsigned short ush;
+typedef unsigned long ulg;
+
+extern const char *z_errmsg[10]; /* indexed by 2-zlib_error */
+/* (size given to avoid silly warnings with Visual C++) */
+
+#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
+
+#define ERR_RETURN(strm,err) \
+ return (strm->msg = (char*)ERR_MSG(err), (err))
+/* To be used only when the state is known to be valid */
+
+ /* common constants */
+
+#ifndef DEF_WBITS
+# define DEF_WBITS MAX_WBITS
+#endif
+/* default windowBits for decompression. MAX_WBITS is for compression only */
+
+#if MAX_MEM_LEVEL >= 8
+# define DEF_MEM_LEVEL 8
+#else
+# define DEF_MEM_LEVEL MAX_MEM_LEVEL
+#endif
+/* default memLevel */
+
+#define STORED_BLOCK 0
+#define STATIC_TREES 1
+#define DYN_TREES 2
+/* The three kinds of block type */
+
+#define MIN_MATCH 3
+#define MAX_MATCH 258
+/* The minimum and maximum match lengths */
+
+#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
+
+ /* target dependencies */
+
+ /* Common defaults */
+
+#ifndef OS_CODE
+# define OS_CODE 0x03 /* assume Unix */
+#endif
+
+#ifndef F_OPEN
+# define F_OPEN(name, mode) fopen((name), (mode))
+#endif
+
+ /* functions */
+
+#ifdef HAVE_STRERROR
+ extern char *strerror OF((int));
+# define zstrerror(errnum) strerror(errnum)
+#else
+# define zstrerror(errnum) ""
+#endif
+
+#define zmemcpy memcpy
+#define zmemcmp memcmp
+#define zmemzero(dest, len) memset(dest, 0, len)
+
+/* Diagnostic functions */
+#ifdef _ZIP_DEBUG_
+ int z_verbose = 0;
+# define Assert(cond,msg) assert(cond);
+ //{if(!(cond)) Sys_Error(msg);}
+# define Trace(x) {if (z_verbose>=0) Sys_Error x ;}
+# define Tracev(x) {if (z_verbose>0) Sys_Error x ;}
+# define Tracevv(x) {if (z_verbose>1) Sys_Error x ;}
+# define Tracec(c,x) {if (z_verbose>0 && (c)) Sys_Error x ;}
+# define Tracecv(c,x) {if (z_verbose>1 && (c)) Sys_Error x ;}
+#else
+# define Assert(cond,msg)
+# define Trace(x)
+# define Tracev(x)
+# define Tracevv(x)
+# define Tracec(c,x)
+# define Tracecv(c,x)
+#endif
+
+
+typedef uLong (*check_func) OF((uLong check, const Byte *buf, uInt len));
+voidp zcalloc OF((voidp opaque, unsigned items, unsigned size));
+void zcfree OF((voidp opaque, voidp ptr));
+
+#define ZALLOC(strm, items, size) \
+ (*((strm)->zalloc))((strm)->opaque, (items), (size))
+#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidp)(addr))
+#define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
+
+
+#if !defined(unix) && !defined(CASESENSITIVITYDEFAULT_YES) && \
+ !defined(CASESENSITIVITYDEFAULT_NO)
+#define CASESENSITIVITYDEFAULT_NO
+#endif
+
+
+#ifndef UNZ_BUFSIZE
+#define UNZ_BUFSIZE (65536)
+#endif
+
+#ifndef UNZ_MAXFILENAMEINZIP
+#define UNZ_MAXFILENAMEINZIP (256)
+#endif
+
+#ifndef ALLOC
+# define ALLOC(size) (malloc(size))
+#endif
+#ifndef TRYFREE
+# define TRYFREE(p) {if (p) free(p);}
+#endif
+
+#define SIZECENTRALDIRITEM (0x2e)
+#define SIZEZIPLOCALHEADER (0x1e)
+
+
+
+/* ===========================================================================
+ Read a byte from a gz_stream; update next_in and avail_in. Return EOF
+ for end of file.
+ IN assertion: the stream s has been sucessfully opened for reading.
+*/
+
+/*
+static int unzlocal_getByte(FILE *fin,int *pi)
+{
+ unsigned char c;
+ int err = fread(&c, 1, 1, fin);
+ if (err==1)
+ {
+ *pi = (int)c;
+ return UNZ_OK;
+ }
+ else
+ {
+ if (ferror(fin))
+ return UNZ_ERRNO;
+ else
+ return UNZ_EOF;
+ }
+}
+*/
+
+/* ===========================================================================
+ Reads a long in LSB order from the given gz_stream. Sets
+*/
+static int unzlocal_getShort (FILE* fin, uLong *pX)
+{
+ short v;
+
+ fread( &v, sizeof(v), 1, fin );
+
+ *pX = __LittleShort( v);
+ return UNZ_OK;
+
+/*
+ uLong x ;
+ int i;
+ int err;
+
+ err = unzlocal_getByte(fin,&i);
+ x = (uLong)i;
+
+ if (err==UNZ_OK)
+ err = unzlocal_getByte(fin,&i);
+ x += ((uLong)i)<<8;
+
+ if (err==UNZ_OK)
+ *pX = x;
+ else
+ *pX = 0;
+ return err;
+*/
+}
+
+static int unzlocal_getLong (FILE *fin, uLong *pX)
+{
+ int v;
+
+ fread( &v, sizeof(v), 1, fin );
+
+ *pX = __LittleLong( v);
+ return UNZ_OK;
+
+/*
+ uLong x ;
+ int i;
+ int err;
+
+ err = unzlocal_getByte(fin,&i);
+ x = (uLong)i;
+
+ if (err==UNZ_OK)
+ err = unzlocal_getByte(fin,&i);
+ x += ((uLong)i)<<8;
+
+ if (err==UNZ_OK)
+ err = unzlocal_getByte(fin,&i);
+ x += ((uLong)i)<<16;
+
+ if (err==UNZ_OK)
+ err = unzlocal_getByte(fin,&i);
+ x += ((uLong)i)<<24;
+
+ if (err==UNZ_OK)
+ *pX = x;
+ else
+ *pX = 0;
+ return err;
+*/
+}
+
+
+/* My own strcmpi / strcasecmp */
+static int strcmpcasenosensitive_internal (const char* fileName1,const char* fileName2)
+{
+ for (;;)
+ {
+ char c1=*(fileName1++);
+ char c2=*(fileName2++);
+ if ((c1>='a') && (c1<='z'))
+ c1 -= 0x20;
+ if ((c2>='a') && (c2<='z'))
+ c2 -= 0x20;
+ if (c1=='\0')
+ return ((c2=='\0') ? 0 : -1);
+ if (c2=='\0')
+ return 1;
+ if (c1<c2)
+ return -1;
+ if (c1>c2)
+ return 1;
+ }
+}
+
+
+#ifdef CASESENSITIVITYDEFAULT_NO
+#define CASESENSITIVITYDEFAULTVALUE 2
+#else
+#define CASESENSITIVITYDEFAULTVALUE 1
+#endif
+
+#ifndef STRCMPCASENOSENTIVEFUNCTION
+#define STRCMPCASENOSENTIVEFUNCTION strcmpcasenosensitive_internal
+#endif
+
+/*
+ Compare two filename (fileName1,fileName2).
+ If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp)
+ If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi
+ or strcasecmp)
+ If iCaseSenisivity = 0, case sensitivity is defaut of your operating system
+ (like 1 on Unix, 2 on Windows)
+
+*/
+extern int unzStringFileNameCompare (const char* fileName1,const char* fileName2,int iCaseSensitivity)
+{
+ if (iCaseSensitivity==0)
+ iCaseSensitivity=CASESENSITIVITYDEFAULTVALUE;
+
+ if (iCaseSensitivity==1)
+ return strcmp(fileName1,fileName2);
+
+ return STRCMPCASENOSENTIVEFUNCTION(fileName1,fileName2);
+}
+
+#define BUFREADCOMMENT (0x400)
+
+/*
+ Locate the Central directory of a zipfile (at the end, just before
+ the global comment)
+*/
+static uLong unzlocal_SearchCentralDir(FILE *fin)
+{
+ unsigned char* buf;
+ uLong uSizeFile;
+ uLong uBackRead;
+ uLong uMaxBack=0xffff; /* maximum size of global comment */
+ uLong uPosFound=0;
+
+ if (fseek(fin,0,SEEK_END) != 0)
+ return 0;
+
+
+ uSizeFile = ftell( fin );
+
+ if (uMaxBack>uSizeFile)
+ uMaxBack = uSizeFile;
+
+ buf = (unsigned char*)malloc(BUFREADCOMMENT+4);
+ if (buf==NULL)
+ return 0;
+
+ uBackRead = 4;
+ while (uBackRead<uMaxBack)
+ {
+ uLong uReadSize,uReadPos ;
+ int i;
+ if (uBackRead+BUFREADCOMMENT>uMaxBack)
+ uBackRead = uMaxBack;
+ else
+ uBackRead+=BUFREADCOMMENT;
+ uReadPos = uSizeFile-uBackRead ;
+
+ uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ?
+ (BUFREADCOMMENT+4) : (uSizeFile-uReadPos);
+ if (fseek(fin,uReadPos,SEEK_SET)!=0)
+ break;
+
+ if (fread(buf,(uInt)uReadSize,1,fin)!=1)
+ break;
+
+ for (i=(int)uReadSize-3; (i--)>0;)
+ if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) &&
+ ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06))
+ {
+ uPosFound = uReadPos+i;
+ break;
+ }
+
+ if (uPosFound!=0)
+ break;
+ }
+ free(buf);
+ return uPosFound;
+}
+
+extern unzFile unzReOpen (const char* path, unzFile file)
+{
+ unz_s *s;
+ FILE * fin;
+
+ fin=fopen(path,"rb");
+ if (fin==NULL)
+ return NULL;
+
+ s=(unz_s*)malloc(sizeof(unz_s));
+ memcpy(s, (unz_s*)file, sizeof(unz_s));
+
+ s->file = fin;
+ return (unzFile)s;
+}
+
+/*
+ Open a Zip file. path contain the full pathname (by example,
+ on a Windows NT computer "c:\\test\\zlib109.zip" or on an Unix computer
+ "zlib/zlib109.zip".
+ If the zipfile cannot be opened (file don't exist or in not valid), the
+ return value is NULL.
+ Else, the return value is a unzFile Handle, usable with other function
+ of this unzip package.
+*/
+extern unzFile unzOpen (const char* path)
+{
+ unz_s us;
+ unz_s *s;
+ uLong central_pos,uL;
+ FILE * fin ;
+
+ uLong number_disk; /* number of the current dist, used for
+ spaning ZIP, unsupported, always 0*/
+ uLong number_disk_with_CD; /* number the the disk with central dir, used
+ for spaning ZIP, unsupported, always 0*/
+ uLong number_entry_CD; /* total number of entries in
+ the central dir
+ (same than number_entry on nospan) */
+
+ int err=UNZ_OK;
+
+ fin=fopen(path,"rb");
+ if (fin==NULL)
+ return NULL;
+
+ central_pos = unzlocal_SearchCentralDir(fin);
+ if (central_pos==0)
+ err=UNZ_ERRNO;
+
+ if (fseek(fin,central_pos,SEEK_SET)!=0)
+ err=UNZ_ERRNO;
+
+ /* the signature, already checked */
+ if (unzlocal_getLong(fin,&uL)!=UNZ_OK)
+ err=UNZ_ERRNO;
+
+ /* number of this disk */
+ if (unzlocal_getShort(fin,&number_disk)!=UNZ_OK)
+ err=UNZ_ERRNO;
+
+ /* number of the disk with the start of the central directory */
+ if (unzlocal_getShort(fin,&number_disk_with_CD)!=UNZ_OK)
+ err=UNZ_ERRNO;
+
+ /* total number of entries in the central dir on this disk */
+ if (unzlocal_getShort(fin,&us.gi.number_entry)!=UNZ_OK)
+ err=UNZ_ERRNO;
+
+ /* total number of entries in the central dir */
+ if (unzlocal_getShort(fin,&number_entry_CD)!=UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if ((number_entry_CD!=us.gi.number_entry) ||
+ (number_disk_with_CD!=0) ||
+ (number_disk!=0))
+ err=UNZ_BADZIPFILE;
+
+ /* size of the central directory */
+ if (unzlocal_getLong(fin,&us.size_central_dir)!=UNZ_OK)
+ err=UNZ_ERRNO;
+
+ /* offset of start of central directory with respect to the
+ starting disk number */
+ if (unzlocal_getLong(fin,&us.offset_central_dir)!=UNZ_OK)
+ err=UNZ_ERRNO;
+
+ /* zipfile comment length */
+ if (unzlocal_getShort(fin,&us.gi.size_comment)!=UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if ((central_pos<us.offset_central_dir+us.size_central_dir) &&
+ (err==UNZ_OK))
+ err=UNZ_BADZIPFILE;
+
+ if (err!=UNZ_OK)
+ {
+ fclose(fin);
+ return NULL;
+ }
+
+ us.file=fin;
+ us.byte_before_the_zipfile = central_pos -
+ (us.offset_central_dir+us.size_central_dir);
+ us.central_pos = central_pos;
+ us.pfile_in_zip_read = NULL;
+
+
+ s=(unz_s*)malloc(sizeof(unz_s));
+ *s=us;
+// unzGoToFirstFile((unzFile)s);
+ return (unzFile)s;
+}
+
+
+/*
+ Close a ZipFile opened with unzipOpen.
+ If there is files inside the .Zip opened with unzipOpenCurrentFile (see later),
+ these files MUST be closed with unzipCloseCurrentFile before call unzipClose.
+ return UNZ_OK if there is no problem. */
+extern int unzClose (unzFile file)
+{
+ unz_s* s;
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+
+ if (s->pfile_in_zip_read!=NULL)
+ unzCloseCurrentFile(file);
+
+ fclose(s->file);
+ free(s);
+ return UNZ_OK;
+}
+
+
+/*
+ Write info about the ZipFile in the *pglobal_info structure.
+ No preparation of the structure is needed
+ return UNZ_OK if there is no problem. */
+extern int unzGetGlobalInfo (unzFile file,unz_global_info *pglobal_info)
+{
+ unz_s* s;
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+ *pglobal_info=s->gi;
+ return UNZ_OK;
+}
+
+
+/*
+ Translate date/time from Dos format to tm_unz (readable more easilty)
+*/
+static void unzlocal_DosDateToTmuDate (uLong ulDosDate, tm_unz* ptm)
+{
+ uLong uDate;
+ uDate = (uLong)(ulDosDate>>16);
+ ptm->tm_mday = (uInt)(uDate&0x1f) ;
+ ptm->tm_mon = (uInt)((((uDate)&0x1E0)/0x20)-1) ;
+ ptm->tm_year = (uInt)(((uDate&0x0FE00)/0x0200)+1980) ;
+
+ ptm->tm_hour = (uInt) ((ulDosDate &0xF800)/0x800);
+ ptm->tm_min = (uInt) ((ulDosDate&0x7E0)/0x20) ;
+ ptm->tm_sec = (uInt) (2*(ulDosDate&0x1f)) ;
+}
+
+/*
+ Get Info about the current file in the zipfile, with internal only info
+*/
+static int unzlocal_GetCurrentFileInfoInternal (unzFile file,
+ unz_file_info *pfile_info,
+ unz_file_info_internal
+ *pfile_info_internal,
+ char *szFileName,
+ uLong fileNameBufferSize,
+ void *extraField,
+ uLong extraFieldBufferSize,
+ char *szComment,
+ uLong commentBufferSize)
+{
+ unz_s* s;
+ unz_file_info file_info;
+ unz_file_info_internal file_info_internal;
+ int err=UNZ_OK;
+ uLong uMagic;
+ long lSeek=0;
+
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+ if (fseek(s->file,s->pos_in_central_dir+s->byte_before_the_zipfile,SEEK_SET)!=0)
+ err=UNZ_ERRNO;
+
+
+ /* we check the magic */
+ if (err==UNZ_OK)
+ if (unzlocal_getLong(s->file,&uMagic) != UNZ_OK)
+ err=UNZ_ERRNO;
+ else if (uMagic!=0x02014b50)
+ err=UNZ_BADZIPFILE;
+
+ if (unzlocal_getShort(s->file,&file_info.version) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getShort(s->file,&file_info.version_needed) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getShort(s->file,&file_info.flag) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getShort(s->file,&file_info.compression_method) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getLong(s->file,&file_info.dosDate) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ unzlocal_DosDateToTmuDate(file_info.dosDate,&file_info.tmu_date);
+
+ if (unzlocal_getLong(s->file,&file_info.crc) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getLong(s->file,&file_info.compressed_size) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getLong(s->file,&file_info.uncompressed_size) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getShort(s->file,&file_info.size_filename) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getShort(s->file,&file_info.size_file_extra) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getShort(s->file,&file_info.size_file_comment) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getShort(s->file,&file_info.disk_num_start) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getShort(s->file,&file_info.internal_fa) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getLong(s->file,&file_info.external_fa) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getLong(s->file,&file_info_internal.offset_curfile) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ lSeek+=file_info.size_filename;
+ if ((err==UNZ_OK) && (szFileName!=NULL))
+ {
+ uLong uSizeRead ;
+ if (file_info.size_filename<fileNameBufferSize)
+ {
+ *(szFileName+file_info.size_filename)='\0';
+ uSizeRead = file_info.size_filename;
+ }
+ else
+ uSizeRead = fileNameBufferSize;
+
+ if ((file_info.size_filename>0) && (fileNameBufferSize>0))
+ if (fread(szFileName,(uInt)uSizeRead,1,s->file)!=1)
+ err=UNZ_ERRNO;
+ lSeek -= uSizeRead;
+ }
+
+
+ if ((err==UNZ_OK) && (extraField!=NULL))
+ {
+ uLong uSizeRead ;
+ if (file_info.size_file_extra<extraFieldBufferSize)
+ uSizeRead = file_info.size_file_extra;
+ else
+ uSizeRead = extraFieldBufferSize;
+
+ if (lSeek!=0)
+ if (fseek(s->file,lSeek,SEEK_CUR)==0)
+ lSeek=0;
+ else
+ err=UNZ_ERRNO;
+ if ((file_info.size_file_extra>0) && (extraFieldBufferSize>0))
+ if (fread(extraField,(uInt)uSizeRead,1,s->file)!=1)
+ err=UNZ_ERRNO;
+ lSeek += file_info.size_file_extra - uSizeRead;
+ }
+ else
+ lSeek+=file_info.size_file_extra;
+
+
+ if ((err==UNZ_OK) && (szComment!=NULL))
+ {
+ uLong uSizeRead ;
+ if (file_info.size_file_comment<commentBufferSize)
+ {
+ *(szComment+file_info.size_file_comment)='\0';
+ uSizeRead = file_info.size_file_comment;
+ }
+ else
+ uSizeRead = commentBufferSize;
+
+ if (lSeek!=0)
+ if (fseek(s->file,lSeek,SEEK_CUR)==0)
+ lSeek=0;
+ else
+ err=UNZ_ERRNO;
+ if ((file_info.size_file_comment>0) && (commentBufferSize>0))
+ if (fread(szComment,(uInt)uSizeRead,1,s->file)!=1)
+ err=UNZ_ERRNO;
+ lSeek+=file_info.size_file_comment - uSizeRead;
+ }
+ else
+ lSeek+=file_info.size_file_comment;
+
+ if ((err==UNZ_OK) && (pfile_info!=NULL))
+ *pfile_info=file_info;
+
+ if ((err==UNZ_OK) && (pfile_info_internal!=NULL))
+ *pfile_info_internal=file_info_internal;
+
+ return err;
+}
+
+
+
+/*
+ Write info about the ZipFile in the *pglobal_info structure.
+ No preparation of the structure is needed
+ return UNZ_OK if there is no problem.
+*/
+extern int unzGetCurrentFileInfo ( unzFile file, unz_file_info *pfile_info,
+ char *szFileName, uLong fileNameBufferSize,
+ void *extraField, uLong extraFieldBufferSize,
+ char *szComment, uLong commentBufferSize)
+{
+ return unzlocal_GetCurrentFileInfoInternal(file,pfile_info,NULL,
+ szFileName,fileNameBufferSize,
+ extraField,extraFieldBufferSize,
+ szComment,commentBufferSize);
+}
+
+/*
+ Set the current file of the zipfile to the first file.
+ return UNZ_OK if there is no problem
+*/
+extern int unzGoToFirstFile (unzFile file)
+{
+ int err=UNZ_OK;
+ unz_s* s;
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+ s->pos_in_central_dir=s->offset_central_dir;
+ s->num_file=0;
+ err=unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info,
+ &s->cur_file_info_internal,
+ NULL,0,NULL,0,NULL,0);
+ s->current_file_ok = (err == UNZ_OK);
+ return err;
+}
+
+
+/*
+ Set the current file of the zipfile to the next file.
+ return UNZ_OK if there is no problem
+ return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest.
+*/
+extern int unzGoToNextFile (unzFile file)
+{
+ unz_s* s;
+ int err;
+
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+ if (!s->current_file_ok)
+ return UNZ_END_OF_LIST_OF_FILE;
+ if (s->num_file+1==s->gi.number_entry)
+ return UNZ_END_OF_LIST_OF_FILE;
+
+ s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename +
+ s->cur_file_info.size_file_extra + s->cur_file_info.size_file_comment ;
+ s->num_file++;
+ err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info,
+ &s->cur_file_info_internal,
+ NULL,0,NULL,0,NULL,0);
+ s->current_file_ok = (err == UNZ_OK);
+ return err;
+}
+
+
+/*
+ Try locate the file szFileName in the zipfile.
+ For the iCaseSensitivity signification, see unzipStringFileNameCompare
+
+ return value :
+ UNZ_OK if the file is found. It becomes the current file.
+ UNZ_END_OF_LIST_OF_FILE if the file is not found
+*/
+extern int unzLocateFile (unzFile file, const char *szFileName, int iCaseSensitivity)
+{
+ unz_s* s;
+ int err;
+
+
+ uLong num_fileSaved;
+ uLong pos_in_central_dirSaved;
+
+
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+
+ if (strlen(szFileName)>=UNZ_MAXFILENAMEINZIP)
+ return UNZ_PARAMERROR;
+
+ s=(unz_s*)file;
+ if (!s->current_file_ok)
+ return UNZ_END_OF_LIST_OF_FILE;
+
+ num_fileSaved = s->num_file;
+ pos_in_central_dirSaved = s->pos_in_central_dir;
+
+ err = unzGoToFirstFile(file);
+
+ while (err == UNZ_OK)
+ {
+ char szCurrentFileName[UNZ_MAXFILENAMEINZIP+1];
+ unzGetCurrentFileInfo(file,NULL,
+ szCurrentFileName,sizeof(szCurrentFileName)-1,
+ NULL,0,NULL,0);
+ if (unzStringFileNameCompare(szCurrentFileName,
+ szFileName,iCaseSensitivity)==0)
+ return UNZ_OK;
+ err = unzGoToNextFile(file);
+ }
+
+ s->num_file = num_fileSaved ;
+ s->pos_in_central_dir = pos_in_central_dirSaved ;
+ return err;
+}
+
+
+/*
+ Read the static header of the current zipfile
+ Check the coherency of the static header and info in the end of central
+ directory about this file
+ store in *piSizeVar the size of extra info in static header
+ (filename and size of extra field data)
+*/
+static int unzlocal_CheckCurrentFileCoherencyHeader (unz_s* s, uInt* piSizeVar,
+ uLong *poffset_local_extrafield,
+ uInt *psize_local_extrafield)
+{
+ uLong uMagic,uData,uFlags;
+ uLong size_filename;
+ uLong size_extra_field;
+ int err=UNZ_OK;
+
+ *piSizeVar = 0;
+ *poffset_local_extrafield = 0;
+ *psize_local_extrafield = 0;
+
+ if (fseek(s->file,s->cur_file_info_internal.offset_curfile +
+ s->byte_before_the_zipfile,SEEK_SET)!=0)
+ return UNZ_ERRNO;
+
+
+ if (err==UNZ_OK)
+ if (unzlocal_getLong(s->file,&uMagic) != UNZ_OK)
+ err=UNZ_ERRNO;
+ else if (uMagic!=0x04034b50)
+ err=UNZ_BADZIPFILE;
+
+ if (unzlocal_getShort(s->file,&uData) != UNZ_OK)
+ err=UNZ_ERRNO;
+/*
+ else if ((err==UNZ_OK) && (uData!=s->cur_file_info.wVersion))
+ err=UNZ_BADZIPFILE;
+*/
+ if (unzlocal_getShort(s->file,&uFlags) != UNZ_OK)
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getShort(s->file,&uData) != UNZ_OK)
+ err=UNZ_ERRNO;
+ else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compression_method))
+ err=UNZ_BADZIPFILE;
+
+ if ((err==UNZ_OK) && (s->cur_file_info.compression_method!=0) &&
+ (s->cur_file_info.compression_method!=Z_DEFLATED))
+ err=UNZ_BADZIPFILE;
+
+ if (unzlocal_getLong(s->file,&uData) != UNZ_OK) /* date/time */
+ err=UNZ_ERRNO;
+
+ if (unzlocal_getLong(s->file,&uData) != UNZ_OK) /* crc */
+ err=UNZ_ERRNO;
+ else if ((err==UNZ_OK) && (uData!=s->cur_file_info.crc) &&
+ ((uFlags & 8)==0))
+ err=UNZ_BADZIPFILE;
+
+ if (unzlocal_getLong(s->file,&uData) != UNZ_OK) /* size compr */
+ err=UNZ_ERRNO;
+ else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compressed_size) &&
+ ((uFlags & 8)==0))
+ err=UNZ_BADZIPFILE;
+
+ if (unzlocal_getLong(s->file,&uData) != UNZ_OK) /* size uncompr */
+ err=UNZ_ERRNO;
+ else if ((err==UNZ_OK) && (uData!=s->cur_file_info.uncompressed_size) &&
+ ((uFlags & 8)==0))
+ err=UNZ_BADZIPFILE;
+
+
+ if (unzlocal_getShort(s->file,&size_filename) != UNZ_OK)
+ err=UNZ_ERRNO;
+ else if ((err==UNZ_OK) && (size_filename!=s->cur_file_info.size_filename))
+ err=UNZ_BADZIPFILE;
+
+ *piSizeVar += (uInt)size_filename;
+
+ if (unzlocal_getShort(s->file,&size_extra_field) != UNZ_OK)
+ err=UNZ_ERRNO;
+ *poffset_local_extrafield= s->cur_file_info_internal.offset_curfile +
+ SIZEZIPLOCALHEADER + size_filename;
+ *psize_local_extrafield = (uInt)size_extra_field;
+
+ *piSizeVar += (uInt)size_extra_field;
+
+ return err;
+}
+
+/*
+ Open for reading data the current file in the zipfile.
+ If there is no error and the file is opened, the return value is UNZ_OK.
+*/
+extern int unzOpenCurrentFile (unzFile file)
+{
+ int err=UNZ_OK;
+ int Store;
+ uInt iSizeVar;
+ unz_s* s;
+ file_in_zip_read_info_s* pfile_in_zip_read_info;
+ uLong offset_local_extrafield; /* offset of the static extra field */
+ uInt size_local_extrafield; /* size of the static extra field */
+
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+ if (!s->current_file_ok)
+ return UNZ_PARAMERROR;
+
+ if (s->pfile_in_zip_read != NULL)
+ unzCloseCurrentFile(file);
+
+ if (unzlocal_CheckCurrentFileCoherencyHeader(s,&iSizeVar,
+ &offset_local_extrafield,&size_local_extrafield)!=UNZ_OK)
+ return UNZ_BADZIPFILE;
+
+ pfile_in_zip_read_info = (file_in_zip_read_info_s*)
+ malloc(sizeof(file_in_zip_read_info_s));
+ if (pfile_in_zip_read_info==NULL)
+ return UNZ_INTERNALERROR;
+
+ pfile_in_zip_read_info->read_buffer=(char*)malloc(UNZ_BUFSIZE);
+ pfile_in_zip_read_info->offset_local_extrafield = offset_local_extrafield;
+ pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield;
+ pfile_in_zip_read_info->pos_local_extrafield=0;
+
+ if (pfile_in_zip_read_info->read_buffer==NULL)
+ {
+ free(pfile_in_zip_read_info);
+ return UNZ_INTERNALERROR;
+ }
+
+ pfile_in_zip_read_info->stream_initialised=0;
+
+ if ((s->cur_file_info.compression_method!=0) &&
+ (s->cur_file_info.compression_method!=Z_DEFLATED))
+ err=UNZ_BADZIPFILE;
+ Store = s->cur_file_info.compression_method==0;
+
+ pfile_in_zip_read_info->crc32_wait=s->cur_file_info.crc;
+ pfile_in_zip_read_info->crc32=0;
+ pfile_in_zip_read_info->compression_method =
+ s->cur_file_info.compression_method;
+ pfile_in_zip_read_info->file=s->file;
+ pfile_in_zip_read_info->byte_before_the_zipfile=s->byte_before_the_zipfile;
+
+ pfile_in_zip_read_info->stream.total_out = 0;
+
+ if (!Store)
+ {
+ pfile_in_zip_read_info->stream.zalloc = (alloc_func)0;
+ pfile_in_zip_read_info->stream.zfree = (free_func)0;
+ pfile_in_zip_read_info->stream.opaque = (voidp)0;
+
+ err=inflateInit2(&pfile_in_zip_read_info->stream, -MAX_WBITS);
+ if (err == Z_OK)
+ pfile_in_zip_read_info->stream_initialised=1;
+ /* windowBits is passed < 0 to tell that there is no zlib header.
+ * Note that in this case inflate *requires* an extra "dummy" byte
+ * after the compressed stream in order to complete decompression and
+ * return Z_STREAM_END.
+ * In unzip, i don't wait absolutely Z_STREAM_END because I known the
+ * size of both compressed and uncompressed data
+ */
+ }
+ pfile_in_zip_read_info->rest_read_compressed =
+ s->cur_file_info.compressed_size ;
+ pfile_in_zip_read_info->rest_read_uncompressed =
+ s->cur_file_info.uncompressed_size ;
+
+
+ pfile_in_zip_read_info->pos_in_zipfile =
+ s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER +
+ iSizeVar;
+
+ pfile_in_zip_read_info->stream.avail_in = (uInt)0;
+
+
+ s->pfile_in_zip_read = pfile_in_zip_read_info;
+ return UNZ_OK;
+}
+
+
+/*
+ Read bytes from the current file.
+ buf contain buffer where data must be copied
+ len the size of buf.
+
+ return the number of byte copied if somes bytes are copied
+ return 0 if the end of file was reached
+ return <0 with error code if there is an error
+ (UNZ_ERRNO for IO error, or zLib error for uncompress error)
+*/
+extern int unzReadCurrentFile (unzFile file, void *buf, unsigned len)
+{
+ int err=UNZ_OK;
+ uInt iRead = 0;
+ unz_s* s;
+ file_in_zip_read_info_s* pfile_in_zip_read_info;
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+ pfile_in_zip_read_info=s->pfile_in_zip_read;
+
+ if (pfile_in_zip_read_info==NULL)
+ return UNZ_PARAMERROR;
+
+
+ if ((pfile_in_zip_read_info->read_buffer == NULL))
+ return UNZ_END_OF_LIST_OF_FILE;
+ if (len==0)
+ return 0;
+
+ pfile_in_zip_read_info->stream.next_out = (Byte*)buf;
+
+ pfile_in_zip_read_info->stream.avail_out = (uInt)len;
+
+ if (len>pfile_in_zip_read_info->rest_read_uncompressed)
+ pfile_in_zip_read_info->stream.avail_out =
+ (uInt)pfile_in_zip_read_info->rest_read_uncompressed;
+
+ while (pfile_in_zip_read_info->stream.avail_out>0)
+ {
+ if ((pfile_in_zip_read_info->stream.avail_in==0) &&
+ (pfile_in_zip_read_info->rest_read_compressed>0))
+ {
+ uInt uReadThis = UNZ_BUFSIZE;
+ if (pfile_in_zip_read_info->rest_read_compressed<uReadThis)
+ uReadThis = (uInt)pfile_in_zip_read_info->rest_read_compressed;
+ if (uReadThis == 0)
+ return UNZ_EOF;
+ if (s->cur_file_info.compressed_size == pfile_in_zip_read_info->rest_read_compressed)
+ if (fseek(pfile_in_zip_read_info->file,
+ pfile_in_zip_read_info->pos_in_zipfile +
+ pfile_in_zip_read_info->byte_before_the_zipfile,SEEK_SET)!=0)
+ return UNZ_ERRNO;
+ if (fread(pfile_in_zip_read_info->read_buffer,uReadThis,1,
+ pfile_in_zip_read_info->file)!=1)
+ return UNZ_ERRNO;
+ pfile_in_zip_read_info->pos_in_zipfile += uReadThis;
+
+ pfile_in_zip_read_info->rest_read_compressed-=uReadThis;
+
+ pfile_in_zip_read_info->stream.next_in =
+ (Byte*)pfile_in_zip_read_info->read_buffer;
+ pfile_in_zip_read_info->stream.avail_in = (uInt)uReadThis;
+ }
+
+ if (pfile_in_zip_read_info->compression_method==0)
+ {
+ uInt uDoCopy,i ;
+ if (pfile_in_zip_read_info->stream.avail_out <
+ pfile_in_zip_read_info->stream.avail_in)
+ uDoCopy = pfile_in_zip_read_info->stream.avail_out ;
+ else
+ uDoCopy = pfile_in_zip_read_info->stream.avail_in ;
+
+ for (i=0;i<uDoCopy;i++)
+ *(pfile_in_zip_read_info->stream.next_out+i) =
+ *(pfile_in_zip_read_info->stream.next_in+i);
+
+ pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32,
+ pfile_in_zip_read_info->stream.next_out,
+ uDoCopy);
+ pfile_in_zip_read_info->rest_read_uncompressed-=uDoCopy;
+ pfile_in_zip_read_info->stream.avail_in -= uDoCopy;
+ pfile_in_zip_read_info->stream.avail_out -= uDoCopy;
+ pfile_in_zip_read_info->stream.next_out += uDoCopy;
+ pfile_in_zip_read_info->stream.next_in += uDoCopy;
+ pfile_in_zip_read_info->stream.total_out += uDoCopy;
+ iRead += uDoCopy;
+ }
+ else
+ {
+ uLong uTotalOutBefore,uTotalOutAfter;
+ const Byte *bufBefore;
+ uLong uOutThis;
+ int flush=Z_SYNC_FLUSH;
+
+ uTotalOutBefore = pfile_in_zip_read_info->stream.total_out;
+ bufBefore = pfile_in_zip_read_info->stream.next_out;
+
+ /*
+ if ((pfile_in_zip_read_info->rest_read_uncompressed ==
+ pfile_in_zip_read_info->stream.avail_out) &&
+ (pfile_in_zip_read_info->rest_read_compressed == 0))
+ flush = Z_FINISH;
+ */
+ err=inflate(&pfile_in_zip_read_info->stream,flush);
+
+ uTotalOutAfter = pfile_in_zip_read_info->stream.total_out;
+ uOutThis = uTotalOutAfter-uTotalOutBefore;
+
+ pfile_in_zip_read_info->crc32 =
+ crc32(pfile_in_zip_read_info->crc32,bufBefore,
+ (uInt)(uOutThis));
+
+ pfile_in_zip_read_info->rest_read_uncompressed -=
+ uOutThis;
+
+ iRead += (uInt)(uTotalOutAfter - uTotalOutBefore);
+
+ if (err==Z_STREAM_END)
+ return (iRead==0) ? UNZ_EOF : iRead;
+ if (err!=Z_OK)
+ break;
+ }
+ }
+
+ if (err==Z_OK)
+ return iRead;
+ return err;
+}
+
+
+/*
+ Give the current position in uncompressed data
+*/
+extern long unztell (unzFile file)
+{
+ unz_s* s;
+ file_in_zip_read_info_s* pfile_in_zip_read_info;
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+ pfile_in_zip_read_info=s->pfile_in_zip_read;
+
+ if (pfile_in_zip_read_info==NULL)
+ return UNZ_PARAMERROR;
+
+ return (long)pfile_in_zip_read_info->stream.total_out;
+}
+
+
+/*
+ return 1 if the end of file was reached, 0 elsewhere
+*/
+extern int unzeof (unzFile file)
+{
+ unz_s* s;
+ file_in_zip_read_info_s* pfile_in_zip_read_info;
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+ pfile_in_zip_read_info=s->pfile_in_zip_read;
+
+ if (pfile_in_zip_read_info==NULL)
+ return UNZ_PARAMERROR;
+
+ if (pfile_in_zip_read_info->rest_read_uncompressed == 0)
+ return 1;
+ else
+ return 0;
+}
+
+
+
+/*
+ Read extra field from the current file (opened by unzOpenCurrentFile)
+ This is the static-header version of the extra field (sometimes, there is
+ more info in the static-header version than in the central-header)
+
+ if buf==NULL, it return the size of the static extra field that can be read
+
+ if buf!=NULL, len is the size of the buffer, the extra header is copied in
+ buf.
+ the return value is the number of bytes copied in buf, or (if <0)
+ the error code
+*/
+extern int unzGetLocalExtrafield (unzFile file,void *buf,unsigned len)
+{
+ unz_s* s;
+ file_in_zip_read_info_s* pfile_in_zip_read_info;
+ uInt read_now;
+ uLong size_to_read;
+
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+ pfile_in_zip_read_info=s->pfile_in_zip_read;
+
+ if (pfile_in_zip_read_info==NULL)
+ return UNZ_PARAMERROR;
+
+ size_to_read = (pfile_in_zip_read_info->size_local_extrafield -
+ pfile_in_zip_read_info->pos_local_extrafield);
+
+ if (buf==NULL)
+ return (int)size_to_read;
+
+ if (len>size_to_read)
+ read_now = (uInt)size_to_read;
+ else
+ read_now = (uInt)len ;
+
+ if (read_now==0)
+ return 0;
+
+ if (fseek(pfile_in_zip_read_info->file,
+ pfile_in_zip_read_info->offset_local_extrafield +
+ pfile_in_zip_read_info->pos_local_extrafield,SEEK_SET)!=0)
+ return UNZ_ERRNO;
+
+ if (fread(buf,(uInt)size_to_read,1,pfile_in_zip_read_info->file)!=1)
+ return UNZ_ERRNO;
+
+ return (int)read_now;
+}
+
+/*
+ Close the file in zip opened with unzipOpenCurrentFile
+ Return UNZ_CRCERROR if all the file was read but the CRC is not good
+*/
+extern int unzCloseCurrentFile (unzFile file)
+{
+ int err=UNZ_OK;
+
+ unz_s* s;
+ file_in_zip_read_info_s* pfile_in_zip_read_info;
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+ pfile_in_zip_read_info=s->pfile_in_zip_read;
+
+ if (pfile_in_zip_read_info==NULL)
+ return UNZ_PARAMERROR;
+
+
+ if (pfile_in_zip_read_info->rest_read_uncompressed == 0)
+ {
+ if (pfile_in_zip_read_info->crc32 != pfile_in_zip_read_info->crc32_wait)
+ err=UNZ_CRCERROR;
+ }
+
+
+ free(pfile_in_zip_read_info->read_buffer);
+ pfile_in_zip_read_info->read_buffer = NULL;
+ if (pfile_in_zip_read_info->stream_initialised)
+ inflateEnd(&pfile_in_zip_read_info->stream);
+
+ pfile_in_zip_read_info->stream_initialised = 0;
+ free(pfile_in_zip_read_info);
+
+ s->pfile_in_zip_read=NULL;
+
+ return err;
+}
+
+
+/*
+ Get the global comment string of the ZipFile, in the szComment buffer.
+ uSizeBuf is the size of the szComment buffer.
+ return the number of byte copied or an error code <0
+*/
+extern int unzGetGlobalComment (unzFile file, char *szComment, uLong uSizeBuf)
+{
+ unz_s* s;
+ uLong uReadThis ;
+ if (file==NULL)
+ return UNZ_PARAMERROR;
+ s=(unz_s*)file;
+
+ uReadThis = uSizeBuf;
+ if (uReadThis>s->gi.size_comment)
+ uReadThis = s->gi.size_comment;
+
+ if (fseek(s->file,s->central_pos+22,SEEK_SET)!=0)
+ return UNZ_ERRNO;
+
+ if (uReadThis>0)
+ {
+ *szComment='\0';
+ if (fread(szComment,(uInt)uReadThis,1,s->file)!=1)
+ return UNZ_ERRNO;
+ }
+
+ if ((szComment != NULL) && (uSizeBuf > s->gi.size_comment))
+ *(szComment+s->gi.size_comment)='\0';
+ return (int)uReadThis;
+}
+
+/* crc32.c -- compute the CRC-32 of a data stream
+ * Copyright (C) 1995-1998 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* @(#) $Id: unzip.cpp,v 1.1.1.3 2000/01/11 16:37:27 ttimo Exp $ */
+
+#ifdef DYNAMIC_CRC_TABLE
+
+static int crc_table_empty = 1;
+static uLong crc_table[256];
+static void make_crc_table OF((void));
+
+/*
+ Generate a table for a byte-wise 32-bit CRC calculation on the polynomial:
+ x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
+
+ Polynomials over GF(2) are represented in binary, one bit per coefficient,
+ with the lowest powers in the most significant bit. Then adding polynomials
+ is just exclusive-or, and multiplying a polynomial by x is a right shift by
+ one. If we call the above polynomial p, and represent a byte as the
+ polynomial q, also with the lowest power in the most significant bit (so the
+ byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
+ where a mod b means the remainder after dividing a by b.
+
+ This calculation is done using the shift-register method of multiplying and
+ taking the remainder. The register is initialized to zero, and for each
+ incoming bit, x^32 is added mod p to the register if the bit is a one (where
+ x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
+ x (which is shifting right by one and adding x^32 mod p if the bit shifted
+ out is a one). We start with the highest power (least significant bit) of
+ q and repeat for all eight bits of q.
+
+ The table is simply the CRC of all possible eight bit values. This is all
+ the information needed to generate CRC's on data a byte at a time for all
+ combinations of CRC register values and incoming bytes.
+*/
+static void make_crc_table()
+{
+ uLong c;
+ int n, k;
+ uLong poly; /* polynomial exclusive-or pattern */
+ /* terms of polynomial defining this crc (except x^32): */
+ static const Byte p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
+
+ /* make exclusive-or pattern from polynomial (0xedb88320L) */
+ poly = 0L;
+ for (n = 0; n < sizeof(p)/sizeof(Byte); n++)
+ poly |= 1L << (31 - p[n]);
+
+ for (n = 0; n < 256; n++)
+ {
+ c = (uLong)n;
+ for (k = 0; k < 8; k++)
+ c = c & 1 ? poly ^ (c >> 1) : c >> 1;
+ crc_table[n] = c;
+ }
+ crc_table_empty = 0;
+}
+#else
+/* ========================================================================
+ * Table of CRC-32's of all single-byte values (made by make_crc_table)
+ */
+static const uLong crc_table[256] = {
+ 0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L,
+ 0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L,
+ 0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L,
+ 0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL,
+ 0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L,
+ 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L,
+ 0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L,
+ 0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL,
+ 0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L,
+ 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL,
+ 0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L,
+ 0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L,
+ 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L,
+ 0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL,
+ 0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL,
+ 0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L,
+ 0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL,
+ 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L,
+ 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L,
+ 0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L,
+ 0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL,
+ 0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L,
+ 0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L,
+ 0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL,
+ 0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L,
+ 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L,
+ 0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L,
+ 0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L,
+ 0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L,
+ 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL,
+ 0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL,
+ 0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L,
+ 0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L,
+ 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL,
+ 0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL,
+ 0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L,
+ 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL,
+ 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L,
+ 0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL,
+ 0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L,
+ 0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL,
+ 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L,
+ 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L,
+ 0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL,
+ 0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L,
+ 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L,
+ 0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L,
+ 0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L,
+ 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L,
+ 0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L,
+ 0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL,
+ 0x2d02ef8dL
+};
+#endif
+
+/* =========================================================================
+ * This function can be used by asm versions of crc32()
+ */
+const uLong * get_crc_table()
+{
+#ifdef DYNAMIC_CRC_TABLE
+ if (crc_table_empty) make_crc_table();
+#endif
+ return (const uLong *)crc_table;
+}
+
+/* ========================================================================= */
+#define DO1(buf) crc = crc_table[((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8);
+#define DO2(buf) DO1(buf); DO1(buf);
+#define DO4(buf) DO2(buf); DO2(buf);
+#define DO8(buf) DO4(buf); DO4(buf);
+
+/* ========================================================================= */
+uLong crc32(uLong crc, const Byte *buf, uInt len)
+{
+ if (buf == Z_NULL) return 0L;
+#ifdef DYNAMIC_CRC_TABLE
+ if (crc_table_empty)
+ make_crc_table();
+#endif
+ crc = crc ^ 0xffffffffL;
+ while (len >= 8)
+ {
+ DO8(buf);
+ len -= 8;
+ }
+ if (len) do {
+ DO1(buf);
+ } while (--len);
+ return crc ^ 0xffffffffL;
+}
+
+/* infblock.h -- header to use infblock.c
+ * Copyright (C) 1995-1998 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+ part of the implementation of the compression library and is
+ subject to change. Applications should only use zlib.h.
+ */
+
+struct inflate_blocks_state;
+typedef struct inflate_blocks_state inflate_blocks_statef;
+
+extern inflate_blocks_statef * inflate_blocks_new OF((
+ z_streamp z,
+ check_func c, /* check function */
+ uInt w)); /* window size */
+
+extern int inflate_blocks OF((
+ inflate_blocks_statef *,
+ z_streamp ,
+ int)); /* initial return code */
+
+extern void inflate_blocks_reset OF((
+ inflate_blocks_statef *,
+ z_streamp ,
+ uLong *)); /* check value on output */
+
+extern int inflate_blocks_free OF((
+ inflate_blocks_statef *,
+ z_streamp));
+
+extern void inflate_set_dictionary OF((
+ inflate_blocks_statef *s,
+ const Byte *d, /* dictionary */
+ uInt n)); /* dictionary length */
+
+extern int inflate_blocks_sync_point OF((
+ inflate_blocks_statef *s));
+
+/* simplify the use of the inflate_huft type with some defines */
+#define exop word.what.Exop
+#define bits word.what.Bits
+
+/* Table for deflate from PKZIP's appnote.txt. */
+static const uInt border[] = { /* Order of the bit length code lengths */
+ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
+
+/* inftrees.h -- header to use inftrees.c
+ * Copyright (C) 1995-1998 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+ part of the implementation of the compression library and is
+ subject to change. Applications should only use zlib.h.
+ */
+
+/* Huffman code lookup table entry--this entry is four bytes for machines
+ that have 16-bit pointers (e.g. PC's in the small or medium model). */
+
+typedef struct inflate_huft_s inflate_huft;
+
+struct inflate_huft_s {
+ union {
+ struct {
+ Byte Exop; /* number of extra bits or operation */
+ Byte Bits; /* number of bits in this code or subcode */
+ } what;
+ uInt pad; /* pad structure to a power of 2 (4 bytes for */
+ } word; /* 16-bit, 8 bytes for 32-bit int's) */
+ uInt base; /* literal, length base, distance base,
+ or table offset */
+};
+
+/* Maximum size of dynamic tree. The maximum found in a long but non-
+ exhaustive search was 1004 huft structures (850 for length/literals
+ and 154 for distances, the latter actually the result of an
+ exhaustive search). The actual maximum is not known, but the
+ value below is more than safe. */
+#define MANY 1440
+
+extern int inflate_trees_bits OF((
+ uInt *, /* 19 code lengths */
+ uInt *, /* bits tree desired/actual depth */
+ inflate_huft * *, /* bits tree result */
+ inflate_huft *, /* space for trees */
+ z_streamp)); /* for messages */
+
+extern int inflate_trees_dynamic OF((
+ uInt, /* number of literal/length codes */
+ uInt, /* number of distance codes */
+ uInt *, /* that many (total) code lengths */
+ uInt *, /* literal desired/actual bit depth */
+ uInt *, /* distance desired/actual bit depth */
+ inflate_huft * *, /* literal/length tree result */
+ inflate_huft * *, /* distance tree result */
+ inflate_huft *, /* space for trees */
+ z_streamp)); /* for messages */
+
+extern int inflate_trees_fixed OF((
+ uInt *, /* literal desired/actual bit depth */
+ uInt *, /* distance desired/actual bit depth */
+ inflate_huft * *, /* literal/length tree result */
+ inflate_huft * *, /* distance tree result */
+ z_streamp)); /* for memory allocation */
+
+
+/* infcodes.h -- header to use infcodes.c
+ * Copyright (C) 1995-1998 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+ part of the implementation of the compression library and is
+ subject to change. Applications should only use zlib.h.
+ */
+
+struct inflate_codes_state;
+typedef struct inflate_codes_state inflate_codes_statef;
+
+extern inflate_codes_statef *inflate_codes_new OF((
+ uInt, uInt,
+ inflate_huft *, inflate_huft *,
+ z_streamp ));
+
+extern int inflate_codes OF((
+ inflate_blocks_statef *,
+ z_streamp ,
+ int));
+
+extern void inflate_codes_free OF((
+ inflate_codes_statef *,
+ z_streamp ));
+
+/* infutil.h -- types and macros common to blocks and codes
+ * Copyright (C) 1995-1998 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+ part of the implementation of the compression library and is
+ subject to change. Applications should only use zlib.h.
+ */
+
+#ifndef _INFUTIL_H
+#define _INFUTIL_H
+
+typedef enum {
+ TYPE, /* get type bits (3, including end bit) */
+ LENS, /* get lengths for stored */
+ STORED, /* processing stored block */
+ TABLE, /* get table lengths */
+ BTREE, /* get bit lengths tree for a dynamic block */
+ DTREE, /* get length, distance trees for a dynamic block */
+ CODES, /* processing fixed or dynamic block */
+ DRY, /* output remaining window bytes */
+ DONE, /* finished last block, done */
+ BAD} /* got a data error--stuck here */
+inflate_block_mode;
+
+/* inflate blocks semi-private state */
+struct inflate_blocks_state {
+
+ /* mode */
+ inflate_block_mode mode; /* current inflate_block mode */
+
+ /* mode dependent information */
+ union {
+ uInt left; /* if STORED, bytes left to copy */
+ struct {
+ uInt table; /* table lengths (14 bits) */
+ uInt index; /* index into blens (or border) */
+ uInt *blens; /* bit lengths of codes */
+ uInt bb; /* bit length tree depth */
+ inflate_huft *tb; /* bit length decoding tree */
+ } trees; /* if DTREE, decoding info for trees */
+ struct {
+ inflate_codes_statef
+ *codes;
+ } decode; /* if CODES, current state */
+ } sub; /* submode */
+ uInt last; /* true if this block is the last block */
+
+ /* mode independent information */
+ uInt bitk; /* bits in bit buffer */
+ uLong bitb; /* bit buffer */
+ inflate_huft *hufts; /* single malloc for tree space */
+ Byte *window; /* sliding window */
+ Byte *end; /* one byte after sliding window */
+ Byte *read; /* window read pointer */
+ Byte *write; /* window write pointer */
+ check_func checkfn; /* check function */
+ uLong check; /* check on output */
+
+};
+
+
+/* defines for inflate input/output */
+/* update pointers and return */
+#define UPDBITS {s->bitb=b;s->bitk=k;}
+#define UPDIN {z->avail_in=n;z->total_in+=p-z->next_in;z->next_in=p;}
+#define UPDOUT {s->write=q;}
+#define UPDATE {UPDBITS UPDIN UPDOUT}
+#define LEAVE {UPDATE return inflate_flush(s,z,r);}
+/* get bytes and bits */
+#define LOADIN {p=z->next_in;n=z->avail_in;b=s->bitb;k=s->bitk;}
+#define NEEDBYTE {if(n)r=Z_OK;else LEAVE}
+#define NEXTBYTE (n--,*p++)
+#define NEEDBITS(j) {while(k<(j)){NEEDBYTE;b|=((uLong)NEXTBYTE)<<k;k+=8;}}
+#define DUMPBITS(j) {b>>=(j);k-=(j);}
+/* output bytes */
+#define WAVAIL (uInt)(q<s->read?s->read-q-1:s->end-q)
+#define LOADOUT {q=s->write;m=(uInt)WAVAIL;}
+#define WRAP {if(q==s->end&&s->read!=s->window){q=s->window;m=(uInt)WAVAIL;}}
+#define FLUSH {UPDOUT r=inflate_flush(s,z,r); LOADOUT}
+#define NEEDOUT {if(m==0){WRAP if(m==0){FLUSH WRAP if(m==0) LEAVE}}r=Z_OK;}
+#define OUTBYTE(a) {*q++=(Byte)(a);m--;}
+/* load static pointers */
+#define LOAD {LOADIN LOADOUT}
+
+/* masks for lower bits (size given to avoid silly warnings with Visual C++) */
+extern uInt inflate_mask[17];
+
+/* copy as much as possible from the sliding window to the output area */
+extern int inflate_flush OF((
+ inflate_blocks_statef *,
+ z_streamp ,
+ int));
+
+#endif
+
+
+/*
+ Notes beyond the 1.93a appnote.txt:
+
+ 1. Distance pointers never point before the beginning of the output
+ stream.
+ 2. Distance pointers can point back across blocks, up to 32k away.
+ 3. There is an implied maximum of 7 bits for the bit length table and
+ 15 bits for the actual data.
+ 4. If only one code exists, then it is encoded using one bit. (Zero
+ would be more efficient, but perhaps a little confusing.) If two
+ codes exist, they are coded using one bit each (0 and 1).
+ 5. There is no way of sending zero distance codes--a dummy must be
+ sent if there are none. (History: a pre 2.0 version of PKZIP would
+ store blocks with no distance codes, but this was discovered to be
+ too harsh a criterion.) Valid only for 1.93a. 2.04c does allow
+ zero distance codes, which is sent as one code of zero bits in
+ length.
+ 6. There are up to 286 literal/length codes. Code 256 represents the
+ end-of-block. Note however that the static length tree defines
+ 288 codes just to fill out the Huffman codes. Codes 286 and 287
+ cannot be used though, since there is no length base or extra bits
+ defined for them. Similarily, there are up to 30 distance codes.
+ However, static trees define 32 codes (all 5 bits) to fill out the
+ Huffman codes, but the last two had better not show up in the data.
+ 7. Unzip can check dynamic Huffman blocks for complete code sets.
+ The exception is that a single code would not be complete (see #4).
+ 8. The five bits following the block type is really the number of
+ literal codes sent minus 257.
+ 9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
+ (1+6+6). Therefore, to output three times the length, you output
+ three codes (1+1+1), whereas to output four times the same length,
+ you only need two codes (1+3). Hmm.
+ 10. In the tree reconstruction algorithm, Code = Code + Increment
+ only if BitLength(i) is not zero. (Pretty obvious.)
+ 11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19)
+ 12. Note: length code 284 can represent 227-258, but length code 285
+ really is 258. The last length deserves its own, short code
+ since it gets used a lot in very redundant files. The length
+ 258 is special since 258 - 3 (the min match length) is 255.
+ 13. The literal/length and distance code bit lengths are read as a
+ single stream of lengths. It is possible (and advantageous) for
+ a repeat code (16, 17, or 18) to go across the boundary between
+ the two sets of lengths.
+ */
+
+
+void inflate_blocks_reset(inflate_blocks_statef *s, z_streamp z, uLong *c)
+{
+ if (c != Z_NULL)
+ *c = s->check;
+ if (s->mode == BTREE || s->mode == DTREE)
+ ZFREE(z, s->sub.trees.blens);
+ if (s->mode == CODES)
+ inflate_codes_free(s->sub.decode.codes, z);
+ s->mode = TYPE;
+ s->bitk = 0;
+ s->bitb = 0;
+ s->read = s->write = s->window;
+ if (s->checkfn != Z_NULL)
+ z->adler = s->check = (*s->checkfn)(0L, (const Byte *)Z_NULL, 0);
+ Tracev(("inflate: blocks reset\n"));
+}
+
+
+inflate_blocks_statef *inflate_blocks_new(z_streamp z, check_func c, uInt w)
+{
+ inflate_blocks_statef *s;
+
+ if ((s = (inflate_blocks_statef *)ZALLOC
+ (z,1,sizeof(struct inflate_blocks_state))) == Z_NULL)
+ return s;
+ if ((s->hufts =
+ (inflate_huft *)ZALLOC(z, sizeof(inflate_huft), MANY)) == Z_NULL)
+ {
+ ZFREE(z, s);
+ return Z_NULL;
+ }
+ if ((s->window = (Byte *)ZALLOC(z, 1, w)) == Z_NULL)
+ {
+ ZFREE(z, s->hufts);
+ ZFREE(z, s);
+ return Z_NULL;
+ }
+ s->end = s->window + w;
+ s->checkfn = c;
+ s->mode = TYPE;
+ Tracev(("inflate: blocks allocated\n"));
+ inflate_blocks_reset(s, z, Z_NULL);
+ return s;
+}
+
+
+int inflate_blocks(inflate_blocks_statef *s, z_streamp z, int r)
+{
+ uInt t; /* temporary storage */
+ uLong b; /* bit buffer */
+ uInt k; /* bits in bit buffer */
+ Byte *p; /* input data pointer */
+ uInt n; /* bytes available there */
+ Byte *q; /* output window write pointer */
+ uInt m; /* bytes to end of window or read pointer */
+
+ /* copy input/output information to locals (UPDATE macro restores) */
+ LOAD
+
+ /* process input based on current state */
+ while (1) switch (s->mode)
+ {
+ case TYPE:
+ NEEDBITS(3)
+ t = (uInt)b & 7;
+ s->last = t & 1;
+ switch (t >> 1)
+ {
+ case 0: /* stored */
+ Tracev(("inflate: stored block%s\n",
+ s->last ? " (last)" : ""));
+ DUMPBITS(3)
+ t = k & 7; /* go to byte boundary */
+ DUMPBITS(t)
+ s->mode = LENS; /* get length of stored block */
+ break;
+ case 1: /* fixed */
+ Tracev(("inflate: fixed codes block%s\n",
+ s->last ? " (last)" : ""));
+ {
+ uInt bl, bd;
+ inflate_huft *tl, *td;
+
+ inflate_trees_fixed(&bl, &bd, &tl, &td, z);
+ s->sub.decode.codes = inflate_codes_new(bl, bd, tl, td, z);
+ if (s->sub.decode.codes == Z_NULL)
+ {
+ r = Z_MEM_ERROR;
+ LEAVE
+ }
+ }
+ DUMPBITS(3)
+ s->mode = CODES;
+ break;
+ case 2: /* dynamic */
+ Tracev(("inflate: dynamic codes block%s\n",
+ s->last ? " (last)" : ""));
+ DUMPBITS(3)
+ s->mode = TABLE;
+ break;
+ case 3: /* illegal */
+ DUMPBITS(3)
+ s->mode = BAD;
+ z->msg = (char*)"invalid block type";
+ r = Z_DATA_ERROR;
+ LEAVE
+ }
+ break;
+ case LENS:
+ NEEDBITS(32)
+ if ((((~b) >> 16) & 0xffff) != (b & 0xffff))
+ {
+ s->mode = BAD;
+ z->msg = (char*)"invalid stored block lengths";
+ r = Z_DATA_ERROR;
+ LEAVE
+ }
+ s->sub.left = (uInt)b & 0xffff;
+ b = k = 0; /* dump bits */
+ Tracev(("inflate: stored length %u\n", s->sub.left));
+ s->mode = s->sub.left ? STORED : (s->last ? DRY : TYPE);
+ break;
+ case STORED:
+ if (n == 0)
+ LEAVE
+ NEEDOUT
+ t = s->sub.left;
+ if (t > n) t = n;
+ if (t > m) t = m;
+ zmemcpy(q, p, t);
+ p += t; n -= t;
+ q += t; m -= t;
+ if ((s->sub.left -= t) != 0)
+ break;
+ Tracev(("inflate: stored end, %lu total out\n",
+ z->total_out + (q >= s->read ? q - s->read :
+ (s->end - s->read) + (q - s->window))));
+ s->mode = s->last ? DRY : TYPE;
+ break;
+ case TABLE:
+ NEEDBITS(14)
+ s->sub.trees.table = t = (uInt)b & 0x3fff;
+#ifndef PKZIP_BUG_WORKAROUND
+ if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29)
+ {
+ s->mode = BAD;
+ z->msg = (char*)"too many length or distance symbols";
+ r = Z_DATA_ERROR;
+ LEAVE
+ }
+#endif
+ t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f);
+ if ((s->sub.trees.blens = (uInt*)ZALLOC(z, t, sizeof(uInt))) == Z_NULL)
+ {
+ r = Z_MEM_ERROR;
+ LEAVE
+ }
+ DUMPBITS(14)
+ s->sub.trees.index = 0;
+ Tracev(("inflate: table sizes ok\n"));
+ s->mode = BTREE;
+ case BTREE:
+ while (s->sub.trees.index < 4 + (s->sub.trees.table >> 10))
+ {
+ NEEDBITS(3)
+ s->sub.trees.blens[border[s->sub.trees.index++]] = (uInt)b & 7;
+ DUMPBITS(3)
+ }
+ while (s->sub.trees.index < 19)
+ s->sub.trees.blens[border[s->sub.trees.index++]] = 0;
+ s->sub.trees.bb = 7;
+ t = inflate_trees_bits(s->sub.trees.blens, &s->sub.trees.bb,
+ &s->sub.trees.tb, s->hufts, z);
+ if (t != Z_OK)
+ {
+ ZFREE(z, s->sub.trees.blens);
+ r = t;
+ if (r == Z_DATA_ERROR)
+ s->mode = BAD;
+ LEAVE
+ }
+ s->sub.trees.index = 0;
+ Tracev(("inflate: bits tree ok\n"));
+ s->mode = DTREE;
+ case DTREE:
+ while (t = s->sub.trees.table,
+ s->sub.trees.index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f))
+ {
+ inflate_huft *h;
+ uInt i, j, c;
+
+ t = s->sub.trees.bb;
+ NEEDBITS(t)
+ h = s->sub.trees.tb + ((uInt)b & inflate_mask[t]);
+ t = h->bits;
+ c = h->base;
+ if (c < 16)
+ {
+ DUMPBITS(t)
+ s->sub.trees.blens[s->sub.trees.index++] = c;
+ }
+ else /* c == 16..18 */
+ {
+ i = c == 18 ? 7 : c - 14;
+ j = c == 18 ? 11 : 3;
+ NEEDBITS(t + i)
+ DUMPBITS(t)
+ j += (uInt)b & inflate_mask[i];
+ DUMPBITS(i)
+ i = s->sub.trees.index;
+ t = s->sub.trees.table;
+ if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) ||
+ (c == 16 && i < 1))
+ {
+ ZFREE(z, s->sub.trees.blens);
+ s->mode = BAD;
+ z->msg = (char*)"invalid bit length repeat";
+ r = Z_DATA_ERROR;
+ LEAVE
+ }
+ c = c == 16 ? s->sub.trees.blens[i - 1] : 0;
+ do {
+ s->sub.trees.blens[i++] = c;
+ } while (--j);
+ s->sub.trees.index = i;
+ }
+ }
+ s->sub.trees.tb = Z_NULL;
+ {
+ uInt bl, bd;
+ inflate_huft *tl, *td;
+ inflate_codes_statef *c;
+
+ bl = 9; /* must be <= 9 for lookahead assumptions */
+ bd = 6; /* must be <= 9 for lookahead assumptions */
+ t = s->sub.trees.table;
+ t = inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f),
+ s->sub.trees.blens, &bl, &bd, &tl, &td,
+ s->hufts, z);
+ ZFREE(z, s->sub.trees.blens);
+ if (t != Z_OK)
+ {
+ if (t == (uInt)Z_DATA_ERROR)
+ s->mode = BAD;
+ r = t;
+ LEAVE
+ }
+ Tracev(("inflate: trees ok\n"));
+ if ((c = inflate_codes_new(bl, bd, tl, td, z)) == Z_NULL)
+ {
+ r = Z_MEM_ERROR;
+ LEAVE
+ }
+ s->sub.decode.codes = c;
+ }
+ s->mode = CODES;
+ case CODES:
+ UPDATE
+ if ((r = inflate_codes(s, z, r)) != Z_STREAM_END)
+ return inflate_flush(s, z, r);
+ r = Z_OK;
+ inflate_codes_free(s->sub.decode.codes, z);
+ LOAD
+ Tracev(("inflate: codes end, %lu total out\n",
+ z->total_out + (q >= s->read ? q - s->read :
+ (s->end - s->read) + (q - s->window))));
+ if (!s->last)
+ {
+ s->mode = TYPE;
+ break;
+ }
+ s->mode = DRY;
+ case DRY:
+ FLUSH
+ if (s->read != s->write)
+ LEAVE
+ s->mode = DONE;
+ case DONE:
+ r = Z_STREAM_END;
+ LEAVE
+ case BAD:
+ r = Z_DATA_ERROR;
+ LEAVE
+ default:
+ r = Z_STREAM_ERROR;
+ LEAVE
+ }
+}
+
+
+int inflate_blocks_free(inflate_blocks_statef *s, z_streamp z)
+{
+ inflate_blocks_reset(s, z, Z_NULL);
+ ZFREE(z, s->window);
+ ZFREE(z, s->hufts);
+ ZFREE(z, s);
+ Tracev(("inflate: blocks freed\n"));
+ return Z_OK;
+}
+
+
+void inflate_set_dictionary(inflate_blocks_statef *s, const Byte *d, uInt n)
+{
+ zmemcpy(s->window, d, n);
+ s->read = s->write = s->window + n;
+}
+
+
+/* Returns true if inflate is currently at the end of a block generated
+ * by Z_SYNC_FLUSH or Z_FULL_FLUSH.
+ * IN assertion: s != Z_NULL
+ */
+int inflate_blocks_sync_point(inflate_blocks_statef *s)
+{
+ return s->mode == LENS;
+}
+
+
+/* And'ing with mask[n] masks the lower n bits */
+uInt inflate_mask[17] = {
+ 0x0000,
+ 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
+ 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
+};
+
+
+/* copy as much as possible from the sliding window to the output area */
+int inflate_flush(inflate_blocks_statef *s, z_streamp z, int r)
+{
+ uInt n;
+ Byte *p;
+ Byte *q;
+
+ /* static copies of source and destination pointers */
+ p = z->next_out;
+ q = s->read;
+
+ /* compute number of bytes to copy as as end of window */
+ n = (uInt)((q <= s->write ? s->write : s->end) - q);
+ if (n > z->avail_out) n = z->avail_out;
+ if (n && r == Z_BUF_ERROR) r = Z_OK;
+
+ /* update counters */
+ z->avail_out -= n;
+ z->total_out += n;
+
+ /* update check information */
+ if (s->checkfn != Z_NULL)
+ z->adler = s->check = (*s->checkfn)(s->check, q, n);
+
+ /* copy as as end of window */
+ zmemcpy(p, q, n);
+ p += n;
+ q += n;
+
+ /* see if more to copy at beginning of window */
+ if (q == s->end)
+ {
+ /* wrap pointers */
+ q = s->window;
+ if (s->write == s->end)
+ s->write = s->window;
+
+ /* compute bytes to copy */
+ n = (uInt)(s->write - q);
+ if (n > z->avail_out) n = z->avail_out;
+ if (n && r == Z_BUF_ERROR) r = Z_OK;
+
+ /* update counters */
+ z->avail_out -= n;
+ z->total_out += n;
+
+ /* update check information */
+ if (s->checkfn != Z_NULL)
+ z->adler = s->check = (*s->checkfn)(s->check, q, n);
+
+ /* copy */
+ zmemcpy(p, q, n);
+ p += n;
+ q += n;
+ }
+
+ /* update pointers */
+ z->next_out = p;
+ s->read = q;
+
+ /* done */
+ return r;
+}
+
+/* inftrees.c -- generate Huffman trees for efficient decoding
+ * Copyright (C) 1995-1998 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+const char inflate_copyright[] =
+ " inflate 1.1.3 Copyright 1995-1998 Mark Adler ";
+/*
+ If you use the zlib library in a product, an acknowledgment is welcome
+ in the documentation of your product. If for some reason you cannot
+ include such an acknowledgment, I would appreciate that you keep this
+ copyright string in the executable of your product.
+ */
+
+/* simplify the use of the inflate_huft type with some defines */
+#define exop word.what.Exop
+#define bits word.what.Bits
+
+
+static int huft_build OF((
+ uInt *, /* code lengths in bits */
+ uInt, /* number of codes */
+ uInt, /* number of "simple" codes */
+ const uInt *, /* list of base values for non-simple codes */
+ const uInt *, /* list of extra bits for non-simple codes */
+ inflate_huft **, /* result: starting table */
+ uInt *, /* maximum lookup bits (returns actual) */
+ inflate_huft *, /* space for trees */
+ uInt *, /* hufts used in space */
+ uInt * )); /* space for values */
+
+/* Tables for deflate from PKZIP's appnote.txt. */
+static const uInt cplens[31] = { /* Copy lengths for literal codes 257..285 */
+ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
+ 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
+ /* see note #13 above about 258 */
+static const uInt cplext[31] = { /* Extra bits for literal codes 257..285 */
+ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
+ 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112}; /* 112==invalid */
+static const uInt cpdist[30] = { /* Copy offsets for distance codes 0..29 */
+ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
+ 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
+ 8193, 12289, 16385, 24577};
+static const uInt cpdext[30] = { /* Extra bits for distance codes */
+ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
+ 7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
+ 12, 12, 13, 13};
+
+/*
+ Huffman code decoding is performed using a multi-level table lookup.
+ The fastest way to decode is to simply build a lookup table whose
+ size is determined by the longest code. However, the time it takes
+ to build this table can also be a factor if the data being decoded
+ is not very long. The most common codes are necessarily the
+ shortest codes, so those codes dominate the decoding time, and hence
+ the speed. The idea is you can have a shorter table that decodes the
+ shorter, more probable codes, and then point to subsidiary tables for
+ the longer codes. The time it costs to decode the longer codes is
+ then traded against the time it takes to make longer tables.
+
+ This results of this trade are in the variables lbits and dbits
+ below. lbits is the number of bits the first level table for literal/
+ length codes can decode in one step, and dbits is the same thing for
+ the distance codes. Subsequent tables are also less than or equal to
+ those sizes. These values may be adjusted either when all of the
+ codes are shorter than that, in which case the longest code length in
+ bits is used, or when the shortest code is *longer* than the requested
+ table size, in which case the length of the shortest code in bits is
+ used.
+
+ There are two different values for the two tables, since they code a
+ different number of possibilities each. The literal/length table
+ codes 286 possible values, or in a flat code, a little over eight
+ bits. The distance table codes 30 possible values, or a little less
+ than five bits, flat. The optimum values for speed end up being
+ about one bit more than those, so lbits is 8+1 and dbits is 5+1.
+ The optimum values may differ though from machine to machine, and
+ possibly even between compilers. Your mileage may vary.
+ */
+
+
+/* If BMAX needs to be larger than 16, then h and x[] should be uLong. */
+#define BMAX 15 /* maximum bit length of any code */
+
+static int huft_build(uInt *b, uInt n, uInt s, const uInt *d, const uInt *e, inflate_huft ** t, uInt *m, inflate_huft *hp, uInt *hn, uInt *v)
+//uInt *b; /* code lengths in bits (all assumed <= BMAX) */
+//uInt n; /* number of codes (assumed <= 288) */
+//uInt s; /* number of simple-valued codes (0..s-1) */
+//const uInt *d; /* list of base values for non-simple codes */
+//const uInt *e; /* list of extra bits for non-simple codes */
+//inflate_huft ** t; /* result: starting table */
+//uInt *m; /* maximum lookup bits, returns actual */
+//inflate_huft *hp; /* space for trees */
+//uInt *hn; /* hufts used in space */
+//uInt *v; /* working area: values in order of bit length */
+/* Given a list of code lengths and a maximum table size, make a set of
+ tables to decode that set of codes. Return Z_OK on success, Z_BUF_ERROR
+ if the given code set is incomplete (the tables are still built in this
+ case), Z_DATA_ERROR if the input is invalid (an over-subscribed set of
+ lengths), or Z_MEM_ERROR if not enough memory. */
+{
+
+ uInt a; /* counter for codes of length k */
+ uInt c[BMAX+1]; /* bit length count table */
+ uInt f; /* i repeats in table every f entries */
+ int g; /* maximum code length */
+ int h; /* table level */
+ register uInt i; /* counter, current code */
+ register uInt j; /* counter */
+ register int k; /* number of bits in current code */
+ int l; /* bits per table (returned in m) */
+ uInt mask; /* (1 << w) - 1, to avoid cc -O bug on HP */
+ register uInt *p; /* pointer into c[], b[], or v[] */
+ inflate_huft *q; /* points to current table */
+ struct inflate_huft_s r; /* table entry for structure assignment */
+ inflate_huft *u[BMAX]; /* table stack */
+ register int w; /* bits before this table == (l * h) */
+ uInt x[BMAX+1]; /* bit offsets, then code stack */
+ uInt *xp; /* pointer into x */
+ int y; /* number of dummy codes added */
+ uInt z; /* number of entries in current table */
+
+
+ /* Generate counts for each bit length */
+ p = c;
+#define C0 *p++ = 0;
+#define C2 C0 C0 C0 C0
+#define C4 C2 C2 C2 C2
+ C4 /* clear c[]--assume BMAX+1 is 16 */
+ p = b; i = n;
+ do {
+ c[*p++]++; /* assume all entries <= BMAX */
+ } while (--i);
+ if (c[0] == n) /* null input--all zero length codes */
+ {
+ *t = (inflate_huft *)Z_NULL;
+ *m = 0;
+ return Z_OK;
+ }
+
+
+ /* Find minimum and maximum length, bound *m by those */
+ l = *m;
+ for (j = 1; j <= BMAX; j++)
+ if (c[j])
+ break;
+ k = j; /* minimum code length */
+ if ((uInt)l < j)
+ l = j;
+ for (i = BMAX; i; i--)
+ if (c[i])
+ break;
+ g = i; /* maximum code length */
+ if ((uInt)l > i)
+ l = i;
+ *m = l;
+
+
+ /* Adjust last length count to fill out codes, if needed */
+ for (y = 1 << j; j < i; j++, y <<= 1)
+ if ((y -= c[j]) < 0)
+ return Z_DATA_ERROR;
+ if ((y -= c[i]) < 0)
+ return Z_DATA_ERROR;
+ c[i] += y;
+
+
+ /* Generate starting offsets into the value table for each length */
+ x[1] = j = 0;
+ p = c + 1; xp = x + 2;
+ while (--i) { /* note that i == g from above */
+ *xp++ = (j += *p++);
+ }
+
+
+ /* Make a table of values in order of bit lengths */
+ p = b; i = 0;
+ do {
+ if ((j = *p++) != 0)
+ v[x[j]++] = i;
+ } while (++i < n);
+ n = x[g]; /* set n to length of v */
+
+
+ /* Generate the Huffman codes and for each, make the table entries */
+ x[0] = i = 0; /* first Huffman code is zero */
+ p = v; /* grab values in bit order */
+ h = -1; /* no tables yet--level -1 */
+ w = -l; /* bits decoded == (l * h) */
+ u[0] = (inflate_huft *)Z_NULL; /* just to keep compilers happy */
+ q = (inflate_huft *)Z_NULL; /* ditto */
+ z = 0; /* ditto */
+
+ /* go through the bit lengths (k already is bits in shortest code) */
+ for (; k <= g; k++)
+ {
+ a = c[k];
+ while (a--)
+ {
+ /* here i is the Huffman code of length k bits for value *p */
+ /* make tables up to required level */
+ while (k > w + l)
+ {
+ h++;
+ w += l; /* previous table always l bits */
+
+ /* compute minimum size table less than or equal to l bits */
+ z = g - w;
+ z = z > (uInt)l ? l : z; /* table size upper limit */
+ if ((f = 1 << (j = k - w)) > a + 1) /* try a k-w bit table */
+ { /* too few codes for k-w bit table */
+ f -= a + 1; /* deduct codes from patterns left */
+ xp = c + k;
+ if (j < z)
+ while (++j < z) /* try smaller tables up to z bits */
+ {
+ if ((f <<= 1) <= *++xp)
+ break; /* enough codes to use up j bits */
+ f -= *xp; /* else deduct codes from patterns */
+ }
+ }
+ z = 1 << j; /* table entries for j-bit table */
+
+ /* allocate new table */
+ if (*hn + z > MANY) /* (note: doesn't matter for fixed) */
+ return Z_MEM_ERROR; /* not enough memory */
+ u[h] = q = hp + *hn;
+ *hn += z;
+
+ /* connect to last table, if there is one */
+ if (h)
+ {
+ x[h] = i; /* save pattern for backing up */
+ r.bits = (Byte)l; /* bits to dump before this table */
+ r.exop = (Byte)j; /* bits in this table */
+ j = i >> (w - l);
+ r.base = (uInt)(q - u[h-1] - j); /* offset to this table */
+ u[h-1][j] = r; /* connect to last table */
+ }
+ else
+ *t = q; /* first table is returned result */
+ }
+
+ /* set up table entry in r */
+ r.bits = (Byte)(k - w);
+ if (p >= v + n)
+ r.exop = 128 + 64; /* out of values--invalid code */
+ else if (*p < s)
+ {
+ r.exop = (Byte)(*p < 256 ? 0 : 32 + 64); /* 256 is end-of-block */
+ r.base = *p++; /* simple code is just the value */
+ }
+ else
+ {
+ r.exop = (Byte)(e[*p - s] + 16 + 64);/* non-simple--look up in lists */
+ r.base = d[*p++ - s];
+ }
+
+ /* fill code-like entries with r */
+ f = 1 << (k - w);
+ for (j = i >> w; j < z; j += f)
+ q[j] = r;
+
+ /* backwards increment the k-bit code i */
+ for (j = 1 << (k - 1); i & j; j >>= 1)
+ i ^= j;
+ i ^= j;
+
+ /* backup over finished tables */
+ mask = (1 << w) - 1; /* needed on HP, cc -O bug */
+ while ((i & mask) != x[h])
+ {
+ h--; /* don't need to update q */
+ w -= l;
+ mask = (1 << w) - 1;
+ }
+ }
+ }
+
+
+ /* Return Z_BUF_ERROR if we were given an incomplete table */
+ return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK;
+}
+
+
+int inflate_trees_bits(uInt *c, uInt *bb, inflate_huft * *tb, inflate_huft *hp, z_streamp z)
+//uInt *c; /* 19 code lengths */
+//uInt *bb; /* bits tree desired/actual depth */
+//inflate_huft * *tb; /* bits tree result */
+//inflate_huft *hp; /* space for trees */
+//z_streamp z; /* for messages */
+{
+ int r;
+ uInt hn = 0; /* hufts used in space */
+ uInt *v; /* work area for huft_build */
+
+ if ((v = (uInt*)ZALLOC(z, 19, sizeof(uInt))) == Z_NULL)
+ return Z_MEM_ERROR;
+ r = huft_build(c, 19, 19, (uInt*)Z_NULL, (uInt*)Z_NULL,
+ tb, bb, hp, &hn, v);
+ if (r == Z_DATA_ERROR)
+ z->msg = (char*)"oversubscribed dynamic bit lengths tree";
+ else if (r == Z_BUF_ERROR || *bb == 0)
+ {
+ z->msg = (char*)"incomplete dynamic bit lengths tree";
+ r = Z_DATA_ERROR;
+ }
+ ZFREE(z, v);
+ return r;
+}
+
+
+int inflate_trees_dynamic(uInt nl, uInt nd, uInt *c, uInt *bl, uInt *bd, inflate_huft * *tl, inflate_huft * *td, inflate_huft *hp, z_streamp z)
+//uInt nl; /* number of literal/length codes */
+//uInt nd; /* number of distance codes */
+//uInt *c; /* that many (total) code lengths */
+//uInt *bl; /* literal desired/actual bit depth */
+//uInt *bd; /* distance desired/actual bit depth */
+//inflate_huft * *tl; /* literal/length tree result */
+//inflate_huft * *td; /* distance tree result */
+//inflate_huft *hp; /* space for trees */
+//z_streamp z; /* for messages */
+{
+ int r;
+ uInt hn = 0; /* hufts used in space */
+ uInt *v; /* work area for huft_build */
+
+ /* allocate work area */
+ if ((v = (uInt*)ZALLOC(z, 288, sizeof(uInt))) == Z_NULL)
+ return Z_MEM_ERROR;
+
+ /* build literal/length tree */
+ r = huft_build(c, nl, 257, cplens, cplext, tl, bl, hp, &hn, v);
+ if (r != Z_OK || *bl == 0)
+ {
+ if (r == Z_DATA_ERROR)
+ z->msg = (char*)"oversubscribed literal/length tree";
+ else if (r != Z_MEM_ERROR)
+ {
+ z->msg = (char*)"incomplete literal/length tree";
+ r = Z_DATA_ERROR;
+ }
+ ZFREE(z, v);
+ return r;
+ }
+
+ /* build distance tree */
+ r = huft_build(c + nl, nd, 0, cpdist, cpdext, td, bd, hp, &hn, v);
+ if (r != Z_OK || (*bd == 0 && nl > 257))
+ {
+ if (r == Z_DATA_ERROR)
+ z->msg = (char*)"oversubscribed distance tree";
+ else if (r == Z_BUF_ERROR) {
+#ifdef PKZIP_BUG_WORKAROUND
+ r = Z_OK;
+ }
+#else
+ z->msg = (char*)"incomplete distance tree";
+ r = Z_DATA_ERROR;
+ }
+ else if (r != Z_MEM_ERROR)
+ {
+ z->msg = (char*)"empty distance tree with lengths";
+ r = Z_DATA_ERROR;
+ }
+ ZFREE(z, v);
+ return r;
+#endif
+ }
+
+ /* done */
+ ZFREE(z, v);
+ return Z_OK;
+}
+
+/* inffixed.h -- table for decoding fixed codes
+ * Generated automatically by the maketree.c program
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+ part of the implementation of the compression library and is
+ subject to change. Applications should only use zlib.h.
+ */
+
+static uInt fixed_bl = 9;
+static uInt fixed_bd = 5;
+static inflate_huft fixed_tl[] = {
+ {{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115},
+ {{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},192},
+ {{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},160},
+ {{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},224},
+ {{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},144},
+ {{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},208},
+ {{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},176},
+ {{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},240},
+ {{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227},
+ {{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},200},
+ {{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},168},
+ {{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},232},
+ {{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},152},
+ {{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},216},
+ {{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},184},
+ {{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},248},
+ {{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163},
+ {{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},196},
+ {{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},164},
+ {{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},228},
+ {{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},148},
+ {{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},212},
+ {{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},180},
+ {{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},244},
+ {{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0},
+ {{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},204},
+ {{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},172},
+ {{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},236},
+ {{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},156},
+ {{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},220},
+ {{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},188},
+ {{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},252},
+ {{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131},
+ {{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},194},
+ {{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},162},
+ {{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},226},
+ {{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},146},
+ {{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},210},
+ {{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},178},
+ {{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},242},
+ {{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258},
+ {{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},202},
+ {{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},170},
+ {{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},234},
+ {{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},154},
+ {{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},218},
+ {{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},186},
+ {{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},250},
+ {{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195},
+ {{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},198},
+ {{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},166},
+ {{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},230},
+ {{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},150},
+ {{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},214},
+ {{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},182},
+ {{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},246},
+ {{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0},
+ {{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},206},
+ {{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},174},
+ {{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},238},
+ {{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},158},
+ {{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},222},
+ {{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},190},
+ {{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},254},
+ {{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115},
+ {{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},193},
+ {{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},161},
+ {{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},225},
+ {{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},145},
+ {{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},209},
+ {{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},177},
+ {{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},241},
+ {{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227},
+ {{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},201},
+ {{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},169},
+ {{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},233},
+ {{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},153},
+ {{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},217},
+ {{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},185},
+ {{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},249},
+ {{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163},
+ {{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},197},
+ {{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},165},
+ {{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},229},
+ {{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},149},
+ {{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},213},
+ {{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},181},
+ {{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},245},
+ {{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0},
+ {{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},205},
+ {{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},173},
+ {{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},237},
+ {{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},157},
+ {{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},221},
+ {{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},189},
+ {{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},253},
+ {{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131},
+ {{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},195},
+ {{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},163},
+ {{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},227},
+ {{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},147},
+ {{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},211},
+ {{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},179},
+ {{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},243},
+ {{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258},
+ {{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},203},
+ {{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},171},
+ {{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},235},
+ {{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},155},
+ {{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},219},
+ {{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},187},
+ {{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},251},
+ {{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195},
+ {{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},199},
+ {{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},167},
+ {{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},231},
+ {{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},151},
+ {{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},215},
+ {{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},183},
+ {{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},247},
+ {{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0},
+ {{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},207},
+ {{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},175},
+ {{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},239},
+ {{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},159},
+ {{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},223},
+ {{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},191},
+ {{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},255}
+ };
+static inflate_huft fixed_td[] = {
+ {{{80,5}},1}, {{{87,5}},257}, {{{83,5}},17}, {{{91,5}},4097},
+ {{{81,5}},5}, {{{89,5}},1025}, {{{85,5}},65}, {{{93,5}},16385},
+ {{{80,5}},3}, {{{88,5}},513}, {{{84,5}},33}, {{{92,5}},8193},
+ {{{82,5}},9}, {{{90,5}},2049}, {{{86,5}},129}, {{{192,5}},24577},
+ {{{80,5}},2}, {{{87,5}},385}, {{{83,5}},25}, {{{91,5}},6145},
+ {{{81,5}},7}, {{{89,5}},1537}, {{{85,5}},97}, {{{93,5}},24577},
+ {{{80,5}},4}, {{{88,5}},769}, {{{84,5}},49}, {{{92,5}},12289},
+ {{{82,5}},13}, {{{90,5}},3073}, {{{86,5}},193}, {{{192,5}},24577}
+ };
+
+int inflate_trees_fixed(uInt *bl, uInt *bd, inflate_huft * *tl, inflate_huft * *td, z_streamp z)
+//uInt *bl; /* literal desired/actual bit depth */
+//uInt *bd; /* distance desired/actual bit depth */
+//inflate_huft * *tl; /* literal/length tree result */
+//inflate_huft * *td; /* distance tree result */
+//z_streamp z; /* for memory allocation */
+{
+ *bl = fixed_bl;
+ *bd = fixed_bd;
+ *tl = fixed_tl;
+ *td = fixed_td;
+ return Z_OK;
+}
+
+/* simplify the use of the inflate_huft type with some defines */
+#define exop word.what.Exop
+#define bits word.what.Bits
+
+/* macros for bit input with no checking and for returning unused bytes */
+#define GRABBITS(j) {while(k<(j)){b|=((uLong)NEXTBYTE)<<k;k+=8;}}
+#define UNGRAB {c=z->avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3;}
+
+/* Called with number of bytes left to write in window at least 258
+ (the maximum string length) and number of input bytes available
+ at least ten. The ten bytes are six bytes for the longest length/
+ distance pair plus four bytes for overloading the bit buffer. */
+
+int inflate_fast(uInt bl, uInt bd, inflate_huft *tl, inflate_huft *td, inflate_blocks_statef *s, z_streamp z)
+{
+ inflate_huft *t; /* temporary pointer */
+ uInt e; /* extra bits or operation */
+ uLong b; /* bit buffer */
+ uInt k; /* bits in bit buffer */
+ Byte *p; /* input data pointer */
+ uInt n; /* bytes available there */
+ Byte *q; /* output window write pointer */
+ uInt m; /* bytes to end of window or read pointer */
+ uInt ml; /* mask for literal/length tree */
+ uInt md; /* mask for distance tree */
+ uInt c; /* bytes to copy */
+ uInt d; /* distance back to copy from */
+ Byte *r; /* copy source pointer */
+
+ /* load input, output, bit values */
+ LOAD
+
+ /* initialize masks */
+ ml = inflate_mask[bl];
+ md = inflate_mask[bd];
+
+ /* do until not enough input or output space for fast loop */
+ do { /* assume called with m >= 258 && n >= 10 */
+ /* get literal/length code */
+ GRABBITS(20) /* max bits for literal/length code */
+ if ((e = (t = tl + ((uInt)b & ml))->exop) == 0)
+ {
+ DUMPBITS(t->bits)
+ Tracevv((t->base >= 0x20 && t->base < 0x7f ?
+ "inflate: * literal '%c'\n" :
+ "inflate: * literal 0x%02x\n", t->base));
+ *q++ = (Byte)t->base;
+ m--;
+ continue;
+ }
+ do {
+ DUMPBITS(t->bits)
+ if (e & 16)
+ {
+ /* get extra bits for length */
+ e &= 15;
+ c = t->base + ((uInt)b & inflate_mask[e]);
+ DUMPBITS(e)
+ Tracevv(("inflate: * length %u\n", c));
+
+ /* decode distance base of block to copy */
+ GRABBITS(15); /* max bits for distance code */
+ e = (t = td + ((uInt)b & md))->exop;
+ do {
+ DUMPBITS(t->bits)
+ if (e & 16)
+ {
+ /* get extra bits to add to distance base */
+ e &= 15;
+ GRABBITS(e) /* get extra bits (up to 13) */
+ d = t->base + ((uInt)b & inflate_mask[e]);
+ DUMPBITS(e)
+ Tracevv(("inflate: * distance %u\n", d));
+
+ /* do the copy */
+ m -= c;
+ if ((uInt)(q - s->window) >= d) /* offset before dest */
+ { /* just copy */
+ r = q - d;
+ *q++ = *r++; c--; /* minimum count is three, */
+ *q++ = *r++; c--; /* so unroll loop a little */
+ }
+ else /* else offset after destination */
+ {
+ e = d - (uInt)(q - s->window); /* bytes from offset to end */
+ r = s->end - e; /* pointer to offset */
+ if (c > e) /* if source crosses, */
+ {
+ c -= e; /* copy to end of window */
+ do {
+ *q++ = *r++;
+ } while (--e);
+ r = s->window; /* copy rest from start of window */
+ }
+ }
+ do { /* copy all or what's left */
+ *q++ = *r++;
+ } while (--c);
+ break;
+ }
+ else if ((e & 64) == 0)
+ {
+ t += t->base;
+ e = (t += ((uInt)b & inflate_mask[e]))->exop;
+ }
+ else
+ {
+ z->msg = (char*)"invalid distance code";
+ UNGRAB
+ UPDATE
+ return Z_DATA_ERROR;
+ }
+ } while (1);
+ break;
+ }
+ if ((e & 64) == 0)
+ {
+ t += t->base;
+ if ((e = (t += ((uInt)b & inflate_mask[e]))->exop) == 0)
+ {
+ DUMPBITS(t->bits)
+ Tracevv((t->base >= 0x20 && t->base < 0x7f ?
+ "inflate: * literal '%c'\n" :
+ "inflate: * literal 0x%02x\n", t->base));
+ *q++ = (Byte)t->base;
+ m--;
+ break;
+ }
+ }
+ else if (e & 32)
+ {
+ Tracevv(("inflate: * end of block\n"));
+ UNGRAB
+ UPDATE
+ return Z_STREAM_END;
+ }
+ else
+ {
+ z->msg = (char*)"invalid literal/length code";
+ UNGRAB
+ UPDATE
+ return Z_DATA_ERROR;
+ }
+ } while (1);
+ } while (m >= 258 && n >= 10);
+
+ /* not enough input or output--restore pointers and return */
+ UNGRAB
+ UPDATE
+ return Z_OK;
+}
+
+/* infcodes.c -- process literals and length/distance pairs
+ * Copyright (C) 1995-1998 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* simplify the use of the inflate_huft type with some defines */
+#define exop word.what.Exop
+#define bits word.what.Bits
+
+typedef enum { /* waiting for "i:"=input, "o:"=output, "x:"=nothing */
+ START, /* x: set up for LEN */
+ LEN, /* i: get length/literal/eob next */
+ LENEXT, /* i: getting length extra (have base) */
+ DIST, /* i: get distance next */
+ DISTEXT, /* i: getting distance extra */
+ COPY, /* o: copying bytes in window, waiting for space */
+ LIT, /* o: got literal, waiting for output space */
+ WASH, /* o: got eob, possibly still output waiting */
+ END, /* x: got eob and all data flushed */
+ BADCODE} /* x: got error */
+inflate_codes_mode;
+
+/* inflate codes private state */
+struct inflate_codes_state {
+
+ /* mode */
+ inflate_codes_mode mode; /* current inflate_codes mode */
+
+ /* mode dependent information */
+ uInt len;
+ union {
+ struct {
+ inflate_huft *tree; /* pointer into tree */
+ uInt need; /* bits needed */
+ } code; /* if LEN or DIST, where in tree */
+ uInt lit; /* if LIT, literal */
+ struct {
+ uInt get; /* bits to get for extra */
+ uInt dist; /* distance back to copy from */
+ } copy; /* if EXT or COPY, where and how much */
+ } sub; /* submode */
+
+ /* mode independent information */
+ Byte lbits; /* ltree bits decoded per branch */
+ Byte dbits; /* dtree bits decoder per branch */
+ inflate_huft *ltree; /* literal/length/eob tree */
+ inflate_huft *dtree; /* distance tree */
+
+};
+
+
+inflate_codes_statef *inflate_codes_new(uInt bl, uInt bd, inflate_huft *tl, inflate_huft *td, z_streamp z)
+{
+ inflate_codes_statef *c;
+
+ if ((c = (inflate_codes_statef *)
+ ZALLOC(z,1,sizeof(struct inflate_codes_state))) != Z_NULL)
+ {
+ c->mode = START;
+ c->lbits = (Byte)bl;
+ c->dbits = (Byte)bd;
+ c->ltree = tl;
+ c->dtree = td;
+ Tracev(("inflate: codes new\n"));
+ }
+ return c;
+}
+
+
+int inflate_codes(inflate_blocks_statef *s, z_streamp z, int r)
+{
+ uInt j; /* temporary storage */
+ inflate_huft *t; /* temporary pointer */
+ uInt e; /* extra bits or operation */
+ uLong b; /* bit buffer */
+ uInt k; /* bits in bit buffer */
+ Byte *p; /* input data pointer */
+ uInt n; /* bytes available there */
+ Byte *q; /* output window write pointer */
+ uInt m; /* bytes to end of window or read pointer */
+ Byte *f; /* pointer to copy strings from */
+ inflate_codes_statef *c = s->sub.decode.codes; /* codes state */
+
+ /* copy input/output information to locals (UPDATE macro restores) */
+ LOAD
+
+ /* process input and output based on current state */
+ while (1) switch (c->mode)
+ { /* waiting for "i:"=input, "o:"=output, "x:"=nothing */
+ case START: /* x: set up for LEN */
+#ifndef SLOW
+ if (m >= 258 && n >= 10)
+ {
+ UPDATE
+ r = inflate_fast(c->lbits, c->dbits, c->ltree, c->dtree, s, z);
+ LOAD
+ if (r != Z_OK)
+ {
+ c->mode = r == Z_STREAM_END ? WASH : BADCODE;
+ break;
+ }
+ }
+#endif /* !SLOW */
+ c->sub.code.need = c->lbits;
+ c->sub.code.tree = c->ltree;
+ c->mode = LEN;
+ case LEN: /* i: get length/literal/eob next */
+ j = c->sub.code.need;
+ NEEDBITS(j)
+ t = c->sub.code.tree + ((uInt)b & inflate_mask[j]);
+ DUMPBITS(t->bits)
+ e = (uInt)(t->exop);
+ if (e == 0) /* literal */
+ {
+ c->sub.lit = t->base;
+ Tracevv((t->base >= 0x20 && t->base < 0x7f ?
+ "inflate: literal '%c'\n" :
+ "inflate: literal 0x%02x\n", t->base));
+ c->mode = LIT;
+ break;
+ }
+ if (e & 16) /* length */
+ {
+ c->sub.copy.get = e & 15;
+ c->len = t->base;
+ c->mode = LENEXT;
+ break;
+ }
+ if ((e & 64) == 0) /* next table */
+ {
+ c->sub.code.need = e;
+ c->sub.code.tree = t + t->base;
+ break;
+ }
+ if (e & 32) /* end of block */
+ {
+ Tracevv(("inflate: end of block\n"));
+ c->mode = WASH;
+ break;
+ }
+ c->mode = BADCODE; /* invalid code */
+ z->msg = (char*)"invalid literal/length code";
+ r = Z_DATA_ERROR;
+ LEAVE
+ case LENEXT: /* i: getting length extra (have base) */
+ j = c->sub.copy.get;
+ NEEDBITS(j)
+ c->len += (uInt)b & inflate_mask[j];
+ DUMPBITS(j)
+ c->sub.code.need = c->dbits;
+ c->sub.code.tree = c->dtree;
+ Tracevv(("inflate: length %u\n", c->len));
+ c->mode = DIST;
+ case DIST: /* i: get distance next */
+ j = c->sub.code.need;
+ NEEDBITS(j)
+ t = c->sub.code.tree + ((uInt)b & inflate_mask[j]);
+ DUMPBITS(t->bits)
+ e = (uInt)(t->exop);
+ if (e & 16) /* distance */
+ {
+ c->sub.copy.get = e & 15;
+ c->sub.copy.dist = t->base;
+ c->mode = DISTEXT;
+ break;
+ }
+ if ((e & 64) == 0) /* next table */
+ {
+ c->sub.code.need = e;
+ c->sub.code.tree = t + t->base;
+ break;
+ }
+ c->mode = BADCODE; /* invalid code */
+ z->msg = (char*)"invalid distance code";
+ r = Z_DATA_ERROR;
+ LEAVE
+ case DISTEXT: /* i: getting distance extra */
+ j = c->sub.copy.get;
+ NEEDBITS(j)
+ c->sub.copy.dist += (uInt)b & inflate_mask[j];
+ DUMPBITS(j)
+ Tracevv(("inflate: distance %u\n", c->sub.copy.dist));
+ c->mode = COPY;
+ case COPY: /* o: copying bytes in window, waiting for space */
+#ifndef __TURBOC__ /* Turbo C bug for following expression */
+ f = (uInt)(q - s->window) < c->sub.copy.dist ?
+ s->end - (c->sub.copy.dist - (q - s->window)) :
+ q - c->sub.copy.dist;
+#else
+ f = q - c->sub.copy.dist;
+ if ((uInt)(q - s->window) < c->sub.copy.dist)
+ f = s->end - (c->sub.copy.dist - (uInt)(q - s->window));
+#endif
+ while (c->len)
+ {
+ NEEDOUT
+ OUTBYTE(*f++)
+ if (f == s->end)
+ f = s->window;
+ c->len--;
+ }
+ c->mode = START;
+ break;
+ case LIT: /* o: got literal, waiting for output space */
+ NEEDOUT
+ OUTBYTE(c->sub.lit)
+ c->mode = START;
+ break;
+ case WASH: /* o: got eob, possibly more output */
+ if (k > 7) /* return unused byte, if any */
+ {
+ Assert(k < 16, "inflate_codes grabbed too many bytes")
+ k -= 8;
+ n++;
+ p--; /* can always return one */
+ }
+ FLUSH
+ if (s->read != s->write)
+ LEAVE
+ c->mode = END;
+ case END:
+ r = Z_STREAM_END;
+ LEAVE
+ case BADCODE: /* x: got error */
+ r = Z_DATA_ERROR;
+ LEAVE
+ default:
+ r = Z_STREAM_ERROR;
+ LEAVE
+ }
+#ifdef NEED_DUMMY_RETURN
+ return Z_STREAM_ERROR; /* Some dumb compilers complain without this */
+#endif
+}
+
+
+void inflate_codes_free(inflate_codes_statef *c, z_streamp z)
+{
+ ZFREE(z, c);
+ Tracev(("inflate: codes free\n"));
+}
+
+/* adler32.c -- compute the Adler-32 checksum of a data stream
+ * Copyright (C) 1995-1998 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+#define BASE 65521L /* largest prime smaller than 65536 */
+#define NMAX 5552
+/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
+
+#undef DO1
+#undef DO2
+#undef DO4
+#undef DO8
+
+#define DO1(buf,i) {s1 += buf[i]; s2 += s1;}
+#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
+#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
+#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
+#define DO16(buf) DO8(buf,0); DO8(buf,8);
+
+/* ========================================================================= */
+uLong adler32(uLong adler, const Byte *buf, uInt len)
+{
+ unsigned long s1 = adler & 0xffff;
+ unsigned long s2 = (adler >> 16) & 0xffff;
+ int k;
+
+ if (buf == Z_NULL) return 1L;
+
+ while (len > 0) {
+ k = len < NMAX ? len : NMAX;
+ len -= k;
+ while (k >= 16) {
+ DO16(buf);
+ buf += 16;
+ k -= 16;
+ }
+ if (k != 0) do {
+ s1 += *buf++;
+ s2 += s1;
+ } while (--k);
+ s1 %= BASE;
+ s2 %= BASE;
+ }
+ return (s2 << 16) | s1;
+}
+
+/* @(#) $Id: unzip.cpp,v 1.1.1.3 2000/01/11 16:37:27 ttimo Exp $ */
+
+/* infblock.h -- header to use infblock.c
+ * Copyright (C) 1995-1998 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+ part of the implementation of the compression library and is
+ subject to change. Applications should only use zlib.h.
+ */
+
+extern inflate_blocks_statef * inflate_blocks_new OF((
+ z_streamp z,
+ check_func c, /* check function */
+ uInt w)); /* window size */
+
+extern int inflate_blocks OF((
+ inflate_blocks_statef *,
+ z_streamp ,
+ int)); /* initial return code */
+
+extern void inflate_blocks_reset OF((
+ inflate_blocks_statef *,
+ z_streamp ,
+ uLong *)); /* check value on output */
+
+extern int inflate_blocks_free OF((
+ inflate_blocks_statef *,
+ z_streamp));
+
+extern void inflate_set_dictionary OF((
+ inflate_blocks_statef *s,
+ const Byte *d, /* dictionary */
+ uInt n)); /* dictionary length */
+
+extern int inflate_blocks_sync_point OF((
+ inflate_blocks_statef *s));
+
+typedef enum {
+ imMETHOD, /* waiting for method byte */
+ imFLAG, /* waiting for flag byte */
+ imDICT4, /* four dictionary check bytes to go */
+ imDICT3, /* three dictionary check bytes to go */
+ imDICT2, /* two dictionary check bytes to go */
+ imDICT1, /* one dictionary check byte to go */
+ imDICT0, /* waiting for inflateSetDictionary */
+ imBLOCKS, /* decompressing blocks */
+ imCHECK4, /* four check bytes to go */
+ imCHECK3, /* three check bytes to go */
+ imCHECK2, /* two check bytes to go */
+ imCHECK1, /* one check byte to go */
+ imDONE, /* finished check, done */
+ imBAD} /* got an error--stay here */
+inflate_mode;
+
+/* inflate private state */
+struct internal_state {
+
+ /* mode */
+ inflate_mode mode; /* current inflate mode */
+
+ /* mode dependent information */
+ union {
+ uInt method; /* if FLAGS, method byte */
+ struct {
+ uLong was; /* computed check value */
+ uLong need; /* stream check value */
+ } check; /* if CHECK, check values to compare */
+ uInt marker; /* if BAD, inflateSync's marker bytes count */
+ } sub; /* submode */
+
+ /* mode independent information */
+ int nowrap; /* flag for no wrapper */
+ uInt wbits; /* log2(window size) (8..15, defaults to 15) */
+ inflate_blocks_statef
+ *blocks; /* current inflate_blocks state */
+
+};
+
+
+int inflateReset(z_streamp z)
+{
+ if (z == Z_NULL || z->state == Z_NULL)
+ return Z_STREAM_ERROR;
+ z->total_in = z->total_out = 0;
+ z->msg = Z_NULL;
+ z->state->mode = z->state->nowrap ? imBLOCKS : imMETHOD;
+ inflate_blocks_reset(z->state->blocks, z, Z_NULL);
+ Tracev(("inflate: reset\n"));
+ return Z_OK;
+}
+
+
+int inflateEnd(z_streamp z)
+{
+ if (z == Z_NULL || z->state == Z_NULL || z->zfree == Z_NULL)
+ return Z_STREAM_ERROR;
+ if (z->state->blocks != Z_NULL)
+ inflate_blocks_free(z->state->blocks, z);
+ ZFREE(z, z->state);
+ z->state = Z_NULL;
+ Tracev(("inflate: end\n"));
+ return Z_OK;
+}
+
+
+
+int inflateInit2_(z_streamp z, int w, const char *version, int stream_size)
+{
+ if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
+ stream_size != sizeof(z_stream))
+ return Z_VERSION_ERROR;
+
+ /* initialize state */
+ if (z == Z_NULL)
+ return Z_STREAM_ERROR;
+ z->msg = Z_NULL;
+ if (z->zalloc == Z_NULL)
+ {
+ z->zalloc = (void *(*)(void *, unsigned, unsigned))zcalloc;
+ z->opaque = (voidp)0;
+ }
+ if (z->zfree == Z_NULL) z->zfree = (void (*)(void *, void *))zcfree;
+ if ((z->state = (struct internal_state *)
+ ZALLOC(z,1,sizeof(struct internal_state))) == Z_NULL)
+ return Z_MEM_ERROR;
+ z->state->blocks = Z_NULL;
+
+ /* handle undocumented nowrap option (no zlib header or check) */
+ z->state->nowrap = 0;
+ if (w < 0)
+ {
+ w = - w;
+ z->state->nowrap = 1;
+ }
+
+ /* set window size */
+ if (w < 8 || w > 15)
+ {
+ inflateEnd(z);
+ return Z_STREAM_ERROR;
+ }
+ z->state->wbits = (uInt)w;
+
+ /* create inflate_blocks state */
+ if ((z->state->blocks =
+ inflate_blocks_new(z, z->state->nowrap ? Z_NULL : adler32, (uInt)1 << w))
+ == Z_NULL)
+ {
+ inflateEnd(z);
+ return Z_MEM_ERROR;
+ }
+ Tracev(("inflate: allocated\n"));
+
+ /* reset state */
+ inflateReset(z);
+ return Z_OK;
+}
+
+
+int inflateInit_(z_streamp z, const char *version, int stream_size)
+{
+ return inflateInit2_(z, DEF_WBITS, version, stream_size);
+}
+
+
+#define iNEEDBYTE {if(z->avail_in==0)return r;r=f;}
+#define iNEXTBYTE (z->avail_in--,z->total_in++,*z->next_in++)
+
+int inflate(z_streamp z, int f)
+{
+ int r;
+ uInt b;
+
+ if (z == Z_NULL || z->state == Z_NULL || z->next_in == Z_NULL)
+ return Z_STREAM_ERROR;
+ f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK;
+ r = Z_BUF_ERROR;
+ while (1) switch (z->state->mode)
+ {
+ case imMETHOD:
+ iNEEDBYTE
+ if (((z->state->sub.method = iNEXTBYTE) & 0xf) != Z_DEFLATED)
+ {
+ z->state->mode = imBAD;
+ z->msg = (char*)"unknown compression method";
+ z->state->sub.marker = 5; /* can't try inflateSync */
+ break;
+ }
+ if ((z->state->sub.method >> 4) + 8 > z->state->wbits)
+ {
+ z->state->mode = imBAD;
+ z->msg = (char*)"invalid window size";
+ z->state->sub.marker = 5; /* can't try inflateSync */
+ break;
+ }
+ z->state->mode = imFLAG;
+ case imFLAG:
+ iNEEDBYTE
+ b = iNEXTBYTE;
+ if (((z->state->sub.method << 8) + b) % 31)
+ {
+ z->state->mode = imBAD;
+ z->msg = (char*)"incorrect header check";
+ z->state->sub.marker = 5; /* can't try inflateSync */
+ break;
+ }
+ Tracev(("inflate: zlib header ok\n"));
+ if (!(b & PRESET_DICT))
+ {
+ z->state->mode = imBLOCKS;
+ break;
+ }
+ z->state->mode = imDICT4;
+ case imDICT4:
+ iNEEDBYTE
+ z->state->sub.check.need = (uLong)iNEXTBYTE << 24;
+ z->state->mode = imDICT3;
+ case imDICT3:
+ iNEEDBYTE
+ z->state->sub.check.need += (uLong)iNEXTBYTE << 16;
+ z->state->mode = imDICT2;
+ case imDICT2:
+ iNEEDBYTE
+ z->state->sub.check.need += (uLong)iNEXTBYTE << 8;
+ z->state->mode = imDICT1;
+ case imDICT1:
+ iNEEDBYTE
+ z->state->sub.check.need += (uLong)iNEXTBYTE;
+ z->adler = z->state->sub.check.need;
+ z->state->mode = imDICT0;
+ return Z_NEED_DICT;
+ case imDICT0:
+ z->state->mode = imBAD;
+ z->msg = (char*)"need dictionary";
+ z->state->sub.marker = 0; /* can try inflateSync */
+ return Z_STREAM_ERROR;
+ case imBLOCKS:
+ r = inflate_blocks(z->state->blocks, z, r);
+ if (r == Z_DATA_ERROR)
+ {
+ z->state->mode = imBAD;
+ z->state->sub.marker = 0; /* can try inflateSync */
+ break;
+ }
+ if (r == Z_OK)
+ r = f;
+ if (r != Z_STREAM_END)
+ return r;
+ r = f;
+ inflate_blocks_reset(z->state->blocks, z, &z->state->sub.check.was);
+ if (z->state->nowrap)
+ {
+ z->state->mode = imDONE;
+ break;
+ }
+ z->state->mode = imCHECK4;
+ case imCHECK4:
+ iNEEDBYTE
+ z->state->sub.check.need = (uLong)iNEXTBYTE << 24;
+ z->state->mode = imCHECK3;
+ case imCHECK3:
+ iNEEDBYTE
+ z->state->sub.check.need += (uLong)iNEXTBYTE << 16;
+ z->state->mode = imCHECK2;
+ case imCHECK2:
+ iNEEDBYTE
+ z->state->sub.check.need += (uLong)iNEXTBYTE << 8;
+ z->state->mode = imCHECK1;
+ case imCHECK1:
+ iNEEDBYTE
+ z->state->sub.check.need += (uLong)iNEXTBYTE;
+
+ if (z->state->sub.check.was != z->state->sub.check.need)
+ {
+ z->state->mode = imBAD;
+ z->msg = (char*)"incorrect data check";
+ z->state->sub.marker = 5; /* can't try inflateSync */
+ break;
+ }
+ Tracev(("inflate: zlib check ok\n"));
+ z->state->mode = imDONE;
+ case imDONE:
+ return Z_STREAM_END;
+ case imBAD:
+ return Z_DATA_ERROR;
+ default:
+ return Z_STREAM_ERROR;
+ }
+#ifdef NEED_DUMMY_RETURN
+ return Z_STREAM_ERROR; /* Some dumb compilers complain without this */
+#endif
+}
+
+
+int inflateSetDictionary(z_streamp z, const Byte *dictionary, uInt dictLength)
+{
+ uInt length = dictLength;
+
+ if (z == Z_NULL || z->state == Z_NULL || z->state->mode != imDICT0)
+ return Z_STREAM_ERROR;
+
+ if (adler32(1L, dictionary, dictLength) != z->adler) return Z_DATA_ERROR;
+ z->adler = 1L;
+
+ if (length >= ((uInt)1<<z->state->wbits))
+ {
+ length = (1<<z->state->wbits)-1;
+ dictionary += dictLength - length;
+ }
+ inflate_set_dictionary(z->state->blocks, dictionary, length);
+ z->state->mode = imBLOCKS;
+ return Z_OK;
+}
+
+
+int inflateSync(z_streamp z)
+{
+ uInt n; /* number of bytes to look at */
+ Byte *p; /* pointer to bytes */
+ uInt m; /* number of marker bytes found in a row */
+ uLong r, w; /* temporaries to save total_in and total_out */
+
+ /* set up */
+ if (z == Z_NULL || z->state == Z_NULL)
+ return Z_STREAM_ERROR;
+ if (z->state->mode != imBAD)
+ {
+ z->state->mode = imBAD;
+ z->state->sub.marker = 0;
+ }
+ if ((n = z->avail_in) == 0)
+ return Z_BUF_ERROR;
+ p = z->next_in;
+ m = z->state->sub.marker;
+
+ /* search */
+ while (n && m < 4)
+ {
+ static const Byte mark[4] = {0, 0, 0xff, 0xff};
+ if (*p == mark[m])
+ m++;
+ else if (*p)
+ m = 0;
+ else
+ m = 4 - m;
+ p++, n--;
+ }
+
+ /* restore */
+ z->total_in += p - z->next_in;
+ z->next_in = p;
+ z->avail_in = n;
+ z->state->sub.marker = m;
+
+ /* return no joy or set up to restart on a new block */
+ if (m != 4)
+ return Z_DATA_ERROR;
+ r = z->total_in; w = z->total_out;
+ inflateReset(z);
+ z->total_in = r; z->total_out = w;
+ z->state->mode = imBLOCKS;
+ return Z_OK;
+}
+
+
+/* Returns true if inflate is currently at the end of a block generated
+ * by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
+ * implementation to provide an additional safety check. PPP uses Z_SYNC_FLUSH
+ * but removes the length bytes of the resulting empty stored block. When
+ * decompressing, PPP checks that at the end of input packet, inflate is
+ * waiting for these length bytes.
+ */
+int inflateSyncPoint(z_streamp z)
+{
+ if (z == Z_NULL || z->state == Z_NULL || z->state->blocks == Z_NULL)
+ return Z_STREAM_ERROR;
+ return inflate_blocks_sync_point(z->state->blocks);
+}
+
+voidp zcalloc (voidp opaque, unsigned items, unsigned size)
+{
+ if (opaque) items += size - size; /* make compiler happy */
+ return (voidp)malloc(items*size);
+}
+
+void zcfree (voidp opaque, voidp ptr)
+{
+ free(ptr);
+ if (opaque) return; /* make compiler happy */
+}
+
diff --git a/libs/pak/unzip.h b/libs/pak/unzip.h
new file mode 100755
index 0000000..d5c165d
--- /dev/null
+++ b/libs/pak/unzip.h
@@ -0,0 +1,300 @@
+
+#if defined(STRICTUNZIP) || defined(STRICTZIPUNZIP)
+/* like the STRICT of WIN32, we define a pointer that cannot be converted
+ from (void*) without cast */
+typedef struct TagunzFile__ { int unused; } unzFile__;
+typedef unzFile__ *unzFile;
+#else
+typedef void* unzFile;
+#endif
+
+
+/* tm_unz contain date/time info */
+typedef struct tm_unz_s
+{
+ unsigned int tm_sec; /* seconds after the minute - [0,59] */
+ unsigned int tm_min; /* minutes after the hour - [0,59] */
+ unsigned int tm_hour; /* hours since midnight - [0,23] */
+ unsigned int tm_mday; /* day of the month - [1,31] */
+ unsigned int tm_mon; /* months since January - [0,11] */
+ unsigned int tm_year; /* years - [1980..2044] */
+} tm_unz;
+
+/* unz_global_info structure contain global data about the ZIPfile
+ These data comes from the end of central dir */
+typedef struct unz_global_info_s
+{
+ unsigned long number_entry; /* total number of entries in the central dir on this disk */
+ unsigned long size_comment; /* size of the global comment of the zipfile */
+} unz_global_info;
+
+
+/* unz_file_info contain information about a file in the zipfile */
+typedef struct unz_file_info_s
+{
+ unsigned long version; /* version made by 2 unsigned chars */
+ unsigned long version_needed; /* version needed to extract 2 unsigned chars */
+ unsigned long flag; /* general purpose bit flag 2 unsigned chars */
+ unsigned long compression_method; /* compression method 2 unsigned chars */
+ unsigned long dosDate; /* last mod file date in Dos fmt 4 unsigned chars */
+ unsigned long crc; /* crc-32 4 unsigned chars */
+ unsigned long compressed_size; /* compressed size 4 unsigned chars */
+ unsigned long uncompressed_size; /* uncompressed size 4 unsigned chars */
+ unsigned long size_filename; /* filename length 2 unsigned chars */
+ unsigned long size_file_extra; /* extra field length 2 unsigned chars */
+ unsigned long size_file_comment; /* file comment length 2 unsigned chars */
+
+ unsigned long disk_num_start; /* disk number start 2 unsigned chars */
+ unsigned long internal_fa; /* internal file attributes 2 unsigned chars */
+ unsigned long external_fa; /* external file attributes 4 unsigned chars */
+
+ tm_unz tmu_date;
+} unz_file_info;
+
+/* unz_file_info_interntal contain internal info about a file in zipfile*/
+typedef struct unz_file_info_internal_s
+{
+ unsigned long offset_curfile;/* relative offset of static header 4 unsigned chars */
+} unz_file_info_internal;
+
+typedef void* (*alloc_func) (void* opaque, unsigned int items, unsigned int size);
+typedef void (*free_func) (void* opaque, void* address);
+
+struct internal_state;
+
+typedef struct z_stream_s {
+ unsigned char *next_in; /* next input unsigned char */
+ unsigned int avail_in; /* number of unsigned chars available at next_in */
+ unsigned long total_in; /* total nb of input unsigned chars read so */
+
+ unsigned char *next_out; /* next output unsigned char should be put there */
+ unsigned int avail_out; /* remaining free space at next_out */
+ unsigned long total_out; /* total nb of unsigned chars output so */
+
+ char *msg; /* last error message, NULL if no error */
+ struct internal_state *state; /* not visible by applications */
+
+ alloc_func zalloc; /* used to allocate the internal state */
+ free_func zfree; /* used to free the internal state */
+ unsigned char* opaque; /* private data object passed to zalloc and zfree */
+
+ int data_type; /* best guess about the data type: ascii or binary */
+ unsigned long adler; /* adler32 value of the uncompressed data */
+ unsigned long reserved; /* reserved for future use */
+} z_stream;
+
+typedef z_stream *z_streamp;
+
+
+/* file_in_zip_read_info_s contain internal information about a file in zipfile,
+ when reading and decompress it */
+typedef struct
+{
+ char *read_buffer; /* internal buffer for compressed data */
+ z_stream stream; /* zLib stream structure for inflate */
+
+ unsigned long pos_in_zipfile; /* position in unsigned char on the zipfile, for fseek*/
+ unsigned long stream_initialised; /* flag set if stream structure is initialised*/
+
+ unsigned long offset_local_extrafield;/* offset of the static extra field */
+ unsigned int size_local_extrafield;/* size of the static extra field */
+ unsigned long pos_local_extrafield; /* position in the static extra field in read*/
+
+ unsigned long crc32; /* crc32 of all data uncompressed */
+ unsigned long crc32_wait; /* crc32 we must obtain after decompress all */
+ unsigned long rest_read_compressed; /* number of unsigned char to be decompressed */
+ unsigned long rest_read_uncompressed;/*number of unsigned char to be obtained after decomp*/
+ FILE* file; /* io structore of the zipfile */
+ unsigned long compression_method; /* compression method (0==store) */
+ unsigned long byte_before_the_zipfile;/* unsigned char before the zipfile, (>0 for sfx)*/
+} file_in_zip_read_info_s;
+
+
+/* unz_s contain internal information about the zipfile
+*/
+typedef struct
+{
+ FILE* file; /* io structore of the zipfile */
+ unz_global_info gi; /* public global information */
+ unsigned long byte_before_the_zipfile;/* unsigned char before the zipfile, (>0 for sfx)*/
+ unsigned long num_file; /* number of the current file in the zipfile*/
+ unsigned long pos_in_central_dir; /* pos of the current file in the central dir*/
+ unsigned long current_file_ok; /* flag about the usability of the current file*/
+ unsigned long central_pos; /* position of the beginning of the central dir*/
+
+ unsigned long size_central_dir; /* size of the central directory */
+ unsigned long offset_central_dir; /* offset of start of central directory with
+ respect to the starting disk number */
+
+ unz_file_info cur_file_info; /* public info about the current file in zip*/
+ unz_file_info_internal cur_file_info_internal; /* private info about it*/
+ file_in_zip_read_info_s* pfile_in_zip_read; /* structure about the current
+ file if we are decompressing it */
+} unz_s;
+
+#define UNZ_OK (0)
+#define UNZ_END_OF_LIST_OF_FILE (-100)
+#define UNZ_ERRNO (Z_ERRNO)
+#define UNZ_EOF (0)
+#define UNZ_PARAMERROR (-102)
+#define UNZ_BADZIPFILE (-103)
+#define UNZ_INTERNALERROR (-104)
+#define UNZ_CRCERROR (-105)
+
+#define UNZ_CASESENSITIVE 1
+#define UNZ_NOTCASESENSITIVE 2
+#define UNZ_OSDEFAULTCASE 0
+
+extern int unzStringFileNameCompare (const char* fileName1, const char* fileName2, int iCaseSensitivity);
+
+/*
+ Compare two filename (fileName1,fileName2).
+ If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp)
+ If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi
+ or strcasecmp)
+ If iCaseSenisivity = 0, case sensitivity is defaut of your operating system
+ (like 1 on Unix, 2 on Windows)
+*/
+
+extern unzFile unzOpen (const char *path);
+extern unzFile unzReOpen (const char* path, unzFile file);
+
+/*
+ Open a Zip file. path contain the full pathname (by example,
+ on a Windows NT computer "c:\\zlib\\zlib111.zip" or on an Unix computer
+ "zlib/zlib111.zip".
+ If the zipfile cannot be opened (file don't exist or in not valid), the
+ return value is NULL.
+ Else, the return value is a unzFile Handle, usable with other function
+ of this unzip package.
+*/
+
+extern int unzClose (unzFile file);
+
+/*
+ Close a ZipFile opened with unzipOpen.
+ If there is files inside the .Zip opened with unzOpenCurrentFile (see later),
+ these files MUST be closed with unzipCloseCurrentFile before call unzipClose.
+ return UNZ_OK if there is no problem. */
+
+extern int unzGetGlobalInfo (unzFile file, unz_global_info *pglobal_info);
+
+/*
+ Write info about the ZipFile in the *pglobal_info structure.
+ No preparation of the structure is needed
+ return UNZ_OK if there is no problem. */
+
+
+extern int unzGetGlobalComment (unzFile file, char *szComment, unsigned long uSizeBuf);
+
+/*
+ Get the global comment string of the ZipFile, in the szComment buffer.
+ uSizeBuf is the size of the szComment buffer.
+ return the number of unsigned char copied or an error code <0
+*/
+
+
+/***************************************************************************/
+/* Unzip package allow you browse the directory of the zipfile */
+
+extern int unzGoToFirstFile (unzFile file);
+
+/*
+ Set the current file of the zipfile to the first file.
+ return UNZ_OK if there is no problem
+*/
+
+extern int unzGoToNextFile (unzFile file);
+
+/*
+ Set the current file of the zipfile to the next file.
+ return UNZ_OK if there is no problem
+ return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest.
+*/
+
+extern int unzLocateFile (unzFile file, const char *szFileName, int iCaseSensitivity);
+
+/*
+ Try locate the file szFileName in the zipfile.
+ For the iCaseSensitivity signification, see unzStringFileNameCompare
+
+ return value :
+ UNZ_OK if the file is found. It becomes the current file.
+ UNZ_END_OF_LIST_OF_FILE if the file is not found
+*/
+
+
+extern int unzGetCurrentFileInfo (unzFile file, unz_file_info *pfile_info, char *szFileName, unsigned long fileNameBufferSize, void *extraField, unsigned long extraFieldBufferSize, char *szComment, unsigned long commentBufferSize);
+
+/*
+ Get Info about the current file
+ if pfile_info!=NULL, the *pfile_info structure will contain somes info about
+ the current file
+ if szFileName!=NULL, the filemane string will be copied in szFileName
+ (fileNameBufferSize is the size of the buffer)
+ if extraField!=NULL, the extra field information will be copied in extraField
+ (extraFieldBufferSize is the size of the buffer).
+ This is the Central-header version of the extra field
+ if szComment!=NULL, the comment string of the file will be copied in szComment
+ (commentBufferSize is the size of the buffer)
+*/
+
+/***************************************************************************/
+/* for reading the content of the current zipfile, you can open it, read data
+ from it, and close it (you can close it before reading all the file)
+ */
+
+extern int unzOpenCurrentFile (unzFile file);
+
+/*
+ Open for reading data the current file in the zipfile.
+ If there is no error, the return value is UNZ_OK.
+*/
+
+extern int unzCloseCurrentFile (unzFile file);
+
+/*
+ Close the file in zip opened with unzOpenCurrentFile
+ Return UNZ_CRCERROR if all the file was read but the CRC is not good
+*/
+
+
+extern int unzReadCurrentFile (unzFile file, void* buf, unsigned len);
+
+/*
+ Read unsigned chars from the current file (opened by unzOpenCurrentFile)
+ buf contain buffer where data must be copied
+ len the size of buf.
+
+ return the number of unsigned char copied if somes unsigned chars are copied
+ return 0 if the end of file was reached
+ return <0 with error code if there is an error
+ (UNZ_ERRNO for IO error, or zLib error for uncompress error)
+*/
+
+extern long unztell(unzFile file);
+
+/*
+ Give the current position in uncompressed data
+*/
+
+extern int unzeof (unzFile file);
+
+/*
+ return 1 if the end of file was reached, 0 elsewhere
+*/
+
+extern int unzGetLocalExtrafield (unzFile file, void* buf, unsigned len);
+
+/*
+ Read extra field from the current file (opened by unzOpenCurrentFile)
+ This is the local-header version of the extra field (sometimes, there is
+ more info in the local-header version than in the central-header)
+
+ if buf==NULL, it return the size of the local extra field
+
+ if buf!=NULL, len is the size of the buffer, the extra header is copied in
+ buf.
+ the return value is the number of unsigned chars copied in buf, or (if <0)
+ the error code
+*/
diff --git a/libs/pakstuff.h b/libs/pakstuff.h
new file mode 100755
index 0000000..2daf64b
--- /dev/null
+++ b/libs/pakstuff.h
@@ -0,0 +1,141 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef _PAKSTUFF_H_
+#define _PAKSTUFF_H_
+
+#include <windows.h>
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+typedef char Int8;
+typedef short Int16;
+typedef long Int32;
+typedef unsigned char UInt8;
+typedef unsigned short UInt16;
+typedef unsigned long UInt32;
+typedef float Float32;
+typedef double Float64;
+#define MAX(a, b) (((a) > (b)) ? (a) : (b))
+#define MIN(a, b) (((a) < (b)) ? (a) : (b))
+#define RANDOM(x) (random() % (x))
+#define RANDOMIZE() srand((int) time(NULL))
+
+#define FTYPE_UNKNOWN 0
+#define FTYPE_IWAD 1 /* .wad "IWAD" */
+#define FTYPE_PWAD 2 /* .wad "PWAD" */
+#define FTYPE_PACK 3 /* .pak "PACK" */
+#define FTYPE_WAD2 4 /* .wad "WAD2" */
+#define FTYPE_BSP 10 /* .bsp (0x17 0x00 0x00 0x00) */
+#define FTYPE_MODEL 11 /* .mdl "IDPO" */
+#define FTYPE_SPRITE 12 /* .spr "IDSP" */
+#define FTYPE_WAV 20 /* .wav "RIFF" */
+#define FTYPE_AU 21 /* .au ".snd" */
+#define FTYPE_VOC 22 /* .voc ? */
+#define FTYPE_PBM_ASC 30 /* .pbm "P1" */
+#define FTYPE_PGM_ASC 31 /* .pgm "P2" */
+#define FTYPE_PPM_ASC 32 /* .ppm "P3" */
+#define FTYPE_PBM_RAW 33 /* .pbm "P4" */
+#define FTYPE_PGM_RAW 34 /* .pgm "P5" */
+#define FTYPE_PPM_RAW 35 /* .ppm "P6" */
+#define FTYPE_BMP 36 /* .bmp "BM" */
+#define FTYPE_GIF 37 /* .gif "GIF8" */
+#define FTYPE_PCX 38 /* .pcx (0x0a 0x05 0x01 0x08) */
+#define FTYPE_ERROR -1
+
+#ifdef FAT_ENDIAN
+Bool ReadInt16 (FILE *file, UInt16 huge *x);
+Bool ReadInt32 (FILE *file, UInt32 huge *x);
+Bool ReadFloat32 (FILE *file, Float32 huge *x);
+Bool WriteInt16 (FILE *file, UInt16 huge *x);
+Bool WriteInt32 (FILE *file, UInt32 huge *x);
+Bool WriteFloat32 (FILE *file, Float32 huge *x);
+UInt16 SwapInt16 (UInt16 x);
+UInt32 SwapInt32 (UInt32 x);
+Float32 SwapFloat32 (Float32 x);
+#else
+#define ReadInt16(f, p) ReadBytes((f), (p), 2L)
+#define ReadInt32(f, p) ReadBytes((f), (p), 4L)
+#define ReadFloat32(f, p) ReadBytes((f), (p), 4L)
+#define WriteInt16(f, p) WriteBytes((f), (p), 2L)
+#define WriteInt32(f, p) WriteBytes((f), (p), 4L)
+#define WriteFloat32(f, p) WriteBytes((f), (p), 4L)
+#define SwapInt16(x) (x)
+#define SwapInt32(x) (x)
+#define SwapFloat32(x) (x)
+#endif /* FAT_ENDIAN */
+
+#define FROMDISK -1
+struct PACKDirectory
+{
+ char name[56]; /* name of file */
+ UInt32 offset; /* offset to start of data */
+ UInt32 size; /* byte size of data */
+};
+typedef struct PACKDirectory *PACKDirPtr;
+
+typedef struct DirListStruct
+{
+ char dirname[1024];
+ int from;
+ struct DirListStruct *next;
+} DIRLIST;
+
+typedef struct FileListStruct
+{
+ char filename[1024];
+ UInt32 offset;
+ UInt32 size;
+ struct FileListStruct *next;
+} FILELIST;
+
+typedef struct DirStruct
+{
+ char name[1024];
+ FILELIST *files;
+ struct DirStruct *next;
+} DIRECTORY;
+
+
+extern int m_nPAKIndex;
+extern FILE* pakfile[16];
+extern boolean pakopen;
+extern DIRECTORY *paktextures;
+
+void ClearFileList (FILELIST **);
+void ClearDirList (DIRLIST **);
+boolean GetPackFileList (FILELIST **, char *);
+boolean GetPackTextureDirs (DIRLIST **);
+boolean AddToDirListAlphabetized (DIRLIST **, char *, int);
+boolean AddToFileListAlphabetized (FILELIST **t, char *, UInt32, UInt32, boolean);
+boolean PakLoadFile (const char *, void **);
+void OpenPakFile (const char *);
+void ClosePakFile (void);
+int PakLoadAnyFile(const char *filename, void **bufferptr);
+void WINAPI InitPakFile(const char * pBasePath, const char *pName);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/libs/str.h b/libs/str.h
new file mode 100755
index 0000000..60ff918
--- /dev/null
+++ b/libs/str.h
@@ -0,0 +1,214 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __STR__
+#define __STR__
+//
+// class Str
+// loose replacement for CString from MFC
+//
+//#include "cmdlib.h"
+#include <string.h>
+
+char* __StrDup(char* pStr);
+char* __StrDup(const char* pStr);
+
+
+
+static char *g_pStrWork = NULL;
+
+class Str
+{
+protected:
+ bool m_bIgnoreCase;
+ char *m_pStr;
+
+public:
+ Str()
+ {
+ m_bIgnoreCase = true;
+ m_pStr = NULL;
+ }
+
+ Str(char *p)
+ {
+ m_bIgnoreCase = true;
+ m_pStr = __StrDup(p);
+ }
+
+ Str(const char *p)
+ {
+ m_bIgnoreCase = true;
+ m_pStr = __StrDup(p);
+ }
+
+ void Deallocate()
+ {
+ delete []m_pStr;
+ m_pStr = NULL;
+ }
+
+ void Allocate(int n)
+ {
+ Deallocate();
+ m_pStr = new char[n];
+ }
+
+ const char* GetBuffer()
+ {
+ return m_pStr;
+ }
+
+ void MakeEmpty()
+ {
+ Deallocate();
+ m_pStr = __StrDup("");
+ }
+
+ ~Str()
+ {
+ Deallocate();
+ delete []g_pStrWork;
+ g_pStrWork = NULL;
+ }
+
+ void MakeLower()
+ {
+ if (m_pStr)
+ {
+ strlwr(m_pStr);
+ }
+ }
+
+ int Find(const char *p)
+ {
+ char *pf = strstr(m_pStr, p);
+ return (pf) ? (pf - m_pStr) : -1;
+ }
+
+ int GetLength()
+ {
+ return (m_pStr) ? strlen(m_pStr) : 0;
+ }
+
+ const char* Left(int n)
+ {
+ delete []g_pStrWork;
+ if (n > 0)
+ {
+ g_pStrWork = new char[n+1];
+ strncpy(g_pStrWork, m_pStr, n);
+ }
+ else
+ {
+ g_pStrWork = "";
+ g_pStrWork = new char[1];
+ g_pStrWork[0] = '\0';
+ }
+ return g_pStrWork;
+ }
+
+ const char* Right(int n)
+ {
+ delete []g_pStrWork;
+ if (n > 0)
+ {
+ g_pStrWork = new char[n+1];
+ int nStart = GetLength() - n;
+ strncpy(g_pStrWork, &m_pStr[nStart], n);
+ g_pStrWork[n] = '\0';
+ }
+ else
+ {
+ g_pStrWork = new char[1];
+ g_pStrWork[0] = '\0';
+ }
+ return g_pStrWork;
+ }
+
+
+ char& operator *() { return *m_pStr; }
+ char& operator *() const { return *const_cast<Str*>(this)->m_pStr; }
+ operator void*() { return m_pStr; }
+ operator char*() { return m_pStr; }
+ operator const char*(){ return reinterpret_cast<const char*>(m_pStr); }
+ operator unsigned char*() { return reinterpret_cast<unsigned char*>(m_pStr); }
+ operator const unsigned char*() { return reinterpret_cast<const unsigned char*>(m_pStr); }
+ Str& operator =(const Str& rhs)
+ {
+ if (&rhs != this)
+ {
+ delete[] m_pStr;
+ m_pStr = __StrDup(rhs.m_pStr);
+ }
+ return *this;
+ }
+
+ Str& operator =(const char* pStr)
+ {
+ if (m_pStr != pStr)
+ {
+ delete[] m_pStr;
+ m_pStr = __StrDup(pStr);
+ }
+ return *this;
+ }
+
+ Str& operator +=(const char *pStr)
+ {
+ if (pStr)
+ {
+ if (m_pStr)
+ {
+ char *p = new char[strlen(m_pStr) + strlen(pStr) + 1];
+ strcpy(p, m_pStr);
+ strcat(p, pStr);
+ delete m_pStr;
+ m_pStr = p;
+ }
+ else
+ {
+ m_pStr = __StrDup(pStr);
+ }
+ }
+ return *this;
+ }
+
+ Str& operator +=(const char c)
+ {
+ return operator+=(&c);
+ }
+
+
+ bool operator ==(const Str& rhs) const { return (m_bIgnoreCase) ? stricmp(m_pStr, rhs.m_pStr) == 0 : strcmp(m_pStr, rhs.m_pStr) == 0; }
+ bool operator ==(char* pStr) const { return (m_bIgnoreCase) ? stricmp(m_pStr, pStr) == 0 : strcmp(m_pStr, pStr) == 0; }
+ bool operator ==(const char* pStr) const { return (m_bIgnoreCase) ? stricmp(m_pStr, pStr) == 0 : strcmp(m_pStr, pStr) == 0; }
+ bool operator !=(Str& rhs) const { return (m_bIgnoreCase) ? stricmp(m_pStr, rhs.m_pStr) != 0 : strcmp(m_pStr, rhs.m_pStr) != 0; }
+ bool operator !=(char* pStr) const { return (m_bIgnoreCase) ? stricmp(m_pStr, pStr) != 0 : strcmp(m_pStr, pStr) != 0; }
+ bool operator !=(const char* pStr) const { return (m_bIgnoreCase) ? stricmp(m_pStr, pStr) != 0 : strcmp(m_pStr, pStr) != 0; }
+ char& operator [](int nIndex) { return m_pStr[nIndex]; }
+ char& operator [](int nIndex) const { return m_pStr[nIndex]; }
+
+};
+
+
+
+#endif \ No newline at end of file
diff --git a/q3asm/Makefile b/q3asm/Makefile
new file mode 100755
index 0000000..b53640a
--- /dev/null
+++ b/q3asm/Makefile
@@ -0,0 +1,13 @@
+# yeah, couldn't do more simple really
+
+CC=gcc
+CFLAGS=-g -Wall
+
+default: q3asm
+
+q3asm: q3asm.c cmdlib.c
+ $(CC) $(CFLAGS) -o $@ $^
+
+clean:
+ rm -f q3asm *~ *.o
+
diff --git a/q3asm/README.Id b/q3asm/README.Id
new file mode 100755
index 0000000..30f44b2
--- /dev/null
+++ b/q3asm/README.Id
@@ -0,0 +1,10 @@
+2002-10-25 Timothee Besset <ttimo@idsoftware.com>
+If you are looking for a faster version of the q3asm tool, try:
+http://www.icculus.org/~phaethon/q3/q3asm-turbo/q3asm-turbo.html
+
+2001-10-31 Timothee Besset <ttimo@idsoftware.com>
+updated from the $/source/q3asm code
+modified for portability and use with >= 1.31 mod source release
+
+the cmdlib.c cmdlib.h mathlib.h qfiles.h have been copied from
+$/source/common
diff --git a/q3asm/cmdlib.c b/q3asm/cmdlib.c
new file mode 100755
index 0000000..630ac57
--- /dev/null
+++ b/q3asm/cmdlib.c
@@ -0,0 +1,1206 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// cmdlib.c
+
+#include "cmdlib.h"
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#ifdef WIN32
+#include <direct.h>
+#include <windows.h>
+#endif
+
+#ifdef __linux
+#include <unistd.h>
+#endif
+
+#ifdef NeXT
+#include <libc.h>
+#endif
+
+#define BASEDIRNAME "quake" // assumed to have a 2 or 3 following
+#define PATHSEPERATOR '/'
+
+// set these before calling CheckParm
+int myargc;
+char **myargv;
+
+char com_token[1024];
+qboolean com_eof;
+
+qboolean archive;
+char archivedir[1024];
+
+
+/*
+===================
+ExpandWildcards
+
+Mimic unix command line expansion
+===================
+*/
+#define MAX_EX_ARGC 1024
+int ex_argc;
+char *ex_argv[MAX_EX_ARGC];
+#ifdef _WIN32
+#include "io.h"
+void ExpandWildcards( int *argc, char ***argv )
+{
+ struct _finddata_t fileinfo;
+ int handle;
+ int i;
+ char filename[1024];
+ char filebase[1024];
+ char *path;
+
+ ex_argc = 0;
+ for (i=0 ; i<*argc ; i++)
+ {
+ path = (*argv)[i];
+ if ( path[0] == '-'
+ || ( !strstr(path, "*") && !strstr(path, "?") ) )
+ {
+ ex_argv[ex_argc++] = path;
+ continue;
+ }
+
+ handle = _findfirst (path, &fileinfo);
+ if (handle == -1)
+ return;
+
+ ExtractFilePath (path, filebase);
+
+ do
+ {
+ sprintf (filename, "%s%s", filebase, fileinfo.name);
+ ex_argv[ex_argc++] = copystring (filename);
+ } while (_findnext( handle, &fileinfo ) != -1);
+
+ _findclose (handle);
+ }
+
+ *argc = ex_argc;
+ *argv = ex_argv;
+}
+#else
+void ExpandWildcards (int *argc, char ***argv)
+{
+}
+#endif
+
+#ifdef WIN_ERROR
+#include <windows.h>
+/*
+=================
+Error
+
+For abnormal program terminations in windowed apps
+=================
+*/
+void Error( const char *error, ... )
+{
+ va_list argptr;
+ char text[1024];
+ char text2[1024];
+ int err;
+
+ err = GetLastError ();
+
+ va_start (argptr,error);
+ vsprintf (text, error,argptr);
+ va_end (argptr);
+
+ sprintf (text2, "%s\nGetLastError() = %i", text, err);
+ MessageBox(NULL, text2, "Error", 0 /* MB_OK */ );
+
+ exit (1);
+}
+
+#else
+/*
+=================
+Error
+
+For abnormal program terminations in console apps
+=================
+*/
+void Error( const char *error, ...)
+{
+ va_list argptr;
+
+ _printf ("\n************ ERROR ************\n");
+
+ va_start (argptr,error);
+ vprintf (error,argptr);
+ va_end (argptr);
+ _printf ("\r\n");
+
+ exit (1);
+}
+#endif
+
+// only printf if in verbose mode
+qboolean verbose = qfalse;
+void qprintf( const char *format, ... ) {
+ va_list argptr;
+
+ if (!verbose)
+ return;
+
+ va_start (argptr,format);
+ vprintf (format,argptr);
+ va_end (argptr);
+
+}
+
+#ifdef WIN32
+HWND hwndOut = NULL;
+qboolean lookedForServer = qfalse;
+UINT wm_BroadcastCommand = -1;
+#endif
+
+void _printf( const char *format, ... ) {
+ va_list argptr;
+ char text[4096];
+#ifdef WIN32
+ ATOM a;
+#endif
+ va_start (argptr,format);
+ vsprintf (text, format, argptr);
+ va_end (argptr);
+
+ printf(text);
+
+#ifdef WIN32
+ if (!lookedForServer) {
+ lookedForServer = qtrue;
+ hwndOut = FindWindow(NULL, "Q3Map Process Server");
+ if (hwndOut) {
+ wm_BroadcastCommand = RegisterWindowMessage( "Q3MPS_BroadcastCommand" );
+ }
+ }
+ if (hwndOut) {
+ a = GlobalAddAtom(text);
+ PostMessage(hwndOut, wm_BroadcastCommand, 0, (LPARAM)a);
+ }
+#endif
+}
+
+
+/*
+
+qdir will hold the path up to the quake directory, including the slash
+
+ f:\quake\
+ /raid/quake/
+
+gamedir will hold qdir + the game directory (id1, id2, etc)
+
+ */
+
+char qdir[1024];
+char gamedir[1024];
+char writedir[1024];
+
+void SetQdirFromPath( const char *path )
+{
+ char temp[1024];
+ const char *c;
+ const char *sep;
+ int len, count;
+
+ if (!(path[0] == '/' || path[0] == '\\' || path[1] == ':'))
+ { // path is partial
+ Q_getwd (temp);
+ strcat (temp, path);
+ path = temp;
+ }
+
+ // search for "quake2" in path
+
+ len = strlen(BASEDIRNAME);
+ for (c=path+strlen(path)-1 ; c != path ; c--)
+ {
+ int i;
+
+ if (!Q_strncasecmp (c, BASEDIRNAME, len))
+ {
+ //
+ //strncpy (qdir, path, c+len+2-path);
+ // the +2 assumes a 2 or 3 following quake which is not the
+ // case with a retail install
+ // so we need to add up how much to the next separator
+ sep = c + len;
+ count = 1;
+ while (*sep && *sep != '/' && *sep != '\\')
+ {
+ sep++;
+ count++;
+ }
+ strncpy (qdir, path, c+len+count-path);
+ qprintf ("qdir: %s\n", qdir);
+ for ( i = 0; i < strlen( qdir ); i++ )
+ {
+ if ( qdir[i] == '\\' )
+ qdir[i] = '/';
+ }
+
+ c += len+count;
+ while (*c)
+ {
+ if (*c == '/' || *c == '\\')
+ {
+ strncpy (gamedir, path, c+1-path);
+
+ for ( i = 0; i < strlen( gamedir ); i++ )
+ {
+ if ( gamedir[i] == '\\' )
+ gamedir[i] = '/';
+ }
+
+ qprintf ("gamedir: %s\n", gamedir);
+
+ if ( !writedir[0] )
+ strcpy( writedir, gamedir );
+ else if ( writedir[strlen( writedir )-1] != '/' )
+ {
+ writedir[strlen( writedir )] = '/';
+ writedir[strlen( writedir )+1] = 0;
+ }
+
+ return;
+ }
+ c++;
+ }
+ Error ("No gamedir in %s", path);
+ return;
+ }
+ }
+ Error ("SetQdirFromPath: no '%s' in %s", BASEDIRNAME, path);
+}
+
+char *ExpandArg (const char *path)
+{
+ static char full[1024];
+
+ if (path[0] != '/' && path[0] != '\\' && path[1] != ':')
+ {
+ Q_getwd (full);
+ strcat (full, path);
+ }
+ else
+ strcpy (full, path);
+ return full;
+}
+
+char *ExpandPath (const char *path)
+{
+ static char full[1024];
+ if (!qdir)
+ Error ("ExpandPath called without qdir set");
+ if (path[0] == '/' || path[0] == '\\' || path[1] == ':') {
+ strcpy( full, path );
+ return full;
+ }
+ sprintf (full, "%s%s", qdir, path);
+ return full;
+}
+
+char *ExpandGamePath (const char *path)
+{
+ static char full[1024];
+ if (!qdir)
+ Error ("ExpandGamePath called without qdir set");
+ if (path[0] == '/' || path[0] == '\\' || path[1] == ':') {
+ strcpy( full, path );
+ return full;
+ }
+ sprintf (full, "%s%s", gamedir, path);
+ return full;
+}
+
+char *ExpandPathAndArchive (const char *path)
+{
+ char *expanded;
+ char archivename[1024];
+
+ expanded = ExpandPath (path);
+
+ if (archive)
+ {
+ sprintf (archivename, "%s/%s", archivedir, path);
+ QCopyFile (expanded, archivename);
+ }
+ return expanded;
+}
+
+
+char *copystring(const char *s)
+{
+ char *b;
+ b = malloc(strlen(s)+1);
+ strcpy (b, s);
+ return b;
+}
+
+
+
+/*
+================
+I_FloatTime
+================
+*/
+double I_FloatTime (void)
+{
+ time_t t;
+
+ time (&t);
+
+ return t;
+#if 0
+// more precise, less portable
+ struct timeval tp;
+ struct timezone tzp;
+ static int secbase;
+
+ gettimeofday(&tp, &tzp);
+
+ if (!secbase)
+ {
+ secbase = tp.tv_sec;
+ return tp.tv_usec/1000000.0;
+ }
+
+ return (tp.tv_sec - secbase) + tp.tv_usec/1000000.0;
+#endif
+}
+
+void Q_getwd (char *out)
+{
+ int i = 0;
+
+#ifdef WIN32
+ _getcwd (out, 256);
+ strcat (out, "\\");
+#else
+ getcwd (out, 256);
+ strcat (out, "/");
+#endif
+
+ while ( out[i] != 0 )
+ {
+ if ( out[i] == '\\' )
+ out[i] = '/';
+ i++;
+ }
+}
+
+
+void Q_mkdir (const char *path)
+{
+#ifdef WIN32
+ if (_mkdir (path) != -1)
+ return;
+#else
+ if (mkdir (path, 0777) != -1)
+ return;
+#endif
+ if (errno != EEXIST)
+ Error ("mkdir %s: %s",path, strerror(errno));
+}
+
+/*
+============
+FileTime
+
+returns -1 if not present
+============
+*/
+int FileTime (const char *path)
+{
+ struct stat buf;
+
+ if (stat (path,&buf) == -1)
+ return -1;
+
+ return buf.st_mtime;
+}
+
+
+
+/*
+==============
+COM_Parse
+
+Parse a token out of a string
+==============
+*/
+char *COM_Parse (char *data)
+{
+ int c;
+ int len;
+
+ len = 0;
+ com_token[0] = 0;
+
+ if (!data)
+ return NULL;
+
+// skip whitespace
+skipwhite:
+ while ( (c = *data) <= ' ')
+ {
+ if (c == 0)
+ {
+ com_eof = qtrue;
+ return NULL; // end of file;
+ }
+ data++;
+ }
+
+// skip // comments
+ if (c=='/' && data[1] == '/')
+ {
+ while (*data && *data != '\n')
+ data++;
+ goto skipwhite;
+ }
+
+
+// handle quoted strings specially
+ if (c == '\"')
+ {
+ data++;
+ do
+ {
+ c = *data++;
+ if (c=='\"')
+ {
+ com_token[len] = 0;
+ return data;
+ }
+ com_token[len] = c;
+ len++;
+ } while (1);
+ }
+
+// parse single characters
+ if (c=='{' || c=='}'|| c==')'|| c=='(' || c=='\'' || c==':')
+ {
+ com_token[len] = c;
+ len++;
+ com_token[len] = 0;
+ return data+1;
+ }
+
+// parse a regular word
+ do
+ {
+ com_token[len] = c;
+ data++;
+ len++;
+ c = *data;
+ if (c=='{' || c=='}'|| c==')'|| c=='(' || c=='\'' || c==':')
+ break;
+ } while (c>32);
+
+ com_token[len] = 0;
+ return data;
+}
+
+
+int Q_strncasecmp (const char *s1, const char *s2, int n)
+{
+ int c1, c2;
+
+ do
+ {
+ c1 = *s1++;
+ c2 = *s2++;
+
+ if (!n--)
+ return 0; // strings are equal until end point
+
+ if (c1 != c2)
+ {
+ if (c1 >= 'a' && c1 <= 'z')
+ c1 -= ('a' - 'A');
+ if (c2 >= 'a' && c2 <= 'z')
+ c2 -= ('a' - 'A');
+ if (c1 != c2)
+ return -1; // strings not equal
+ }
+ } while (c1);
+
+ return 0; // strings are equal
+}
+
+int Q_stricmp (const char *s1, const char *s2)
+{
+ return Q_strncasecmp (s1, s2, 99999);
+}
+
+
+char *strupr (char *start)
+{
+ char *in;
+ in = start;
+ while (*in)
+ {
+ *in = toupper(*in);
+ in++;
+ }
+ return start;
+}
+
+char *strlower (char *start)
+{
+ char *in;
+ in = start;
+ while (*in)
+ {
+ *in = tolower(*in);
+ in++;
+ }
+ return start;
+}
+
+
+/*
+=============================================================================
+
+ MISC FUNCTIONS
+
+=============================================================================
+*/
+
+
+/*
+=================
+CheckParm
+
+Checks for the given parameter in the program's command line arguments
+Returns the argument number (1 to argc-1) or 0 if not present
+=================
+*/
+int CheckParm (const char *check)
+{
+ int i;
+
+ for (i = 1;i<myargc;i++)
+ {
+ if ( !Q_stricmp(check, myargv[i]) )
+ return i;
+ }
+
+ return 0;
+}
+
+
+
+/*
+================
+Q_filelength
+================
+*/
+int Q_filelength (FILE *f)
+{
+ int pos;
+ int end;
+
+ pos = ftell (f);
+ fseek (f, 0, SEEK_END);
+ end = ftell (f);
+ fseek (f, pos, SEEK_SET);
+
+ return end;
+}
+
+
+FILE *SafeOpenWrite (const char *filename)
+{
+ FILE *f;
+
+ f = fopen(filename, "wb");
+
+ if (!f)
+ Error ("Error opening %s: %s",filename,strerror(errno));
+
+ return f;
+}
+
+FILE *SafeOpenRead (const char *filename)
+{
+ FILE *f;
+
+ f = fopen(filename, "rb");
+
+ if (!f)
+ Error ("Error opening %s: %s",filename,strerror(errno));
+
+ return f;
+}
+
+
+void SafeRead (FILE *f, void *buffer, int count)
+{
+ if ( fread (buffer, 1, count, f) != (size_t)count)
+ Error ("File read failure");
+}
+
+
+void SafeWrite (FILE *f, const void *buffer, int count)
+{
+ if (fwrite (buffer, 1, count, f) != (size_t)count)
+ Error ("File write failure");
+}
+
+
+/*
+==============
+FileExists
+==============
+*/
+qboolean FileExists (const char *filename)
+{
+ FILE *f;
+
+ f = fopen (filename, "r");
+ if (!f)
+ return qfalse;
+ fclose (f);
+ return qtrue;
+}
+
+/*
+==============
+LoadFile
+==============
+*/
+int LoadFile( const char *filename, void **bufferptr )
+{
+ FILE *f;
+ int length;
+ void *buffer;
+
+ f = SafeOpenRead (filename);
+ length = Q_filelength (f);
+ buffer = malloc (length+1);
+ ((char *)buffer)[length] = 0;
+ SafeRead (f, buffer, length);
+ fclose (f);
+
+ *bufferptr = buffer;
+ return length;
+}
+
+
+/*
+==============
+LoadFileBlock
+-
+rounds up memory allocation to 4K boundry
+-
+==============
+*/
+int LoadFileBlock( const char *filename, void **bufferptr )
+{
+ FILE *f;
+ int length, nBlock, nAllocSize;
+ void *buffer;
+
+ f = SafeOpenRead (filename);
+ length = Q_filelength (f);
+ nAllocSize = length;
+ nBlock = nAllocSize % MEM_BLOCKSIZE;
+ if ( nBlock > 0) {
+ nAllocSize += MEM_BLOCKSIZE - nBlock;
+ }
+ buffer = malloc (nAllocSize+1);
+ memset(buffer, 0, nAllocSize+1);
+ SafeRead (f, buffer, length);
+ fclose (f);
+
+ *bufferptr = buffer;
+ return length;
+}
+
+
+/*
+==============
+TryLoadFile
+
+Allows failure
+==============
+*/
+int TryLoadFile (const char *filename, void **bufferptr)
+{
+ FILE *f;
+ int length;
+ void *buffer;
+
+ *bufferptr = NULL;
+
+ f = fopen (filename, "rb");
+ if (!f)
+ return -1;
+ length = Q_filelength (f);
+ buffer = malloc (length+1);
+ ((char *)buffer)[length] = 0;
+ SafeRead (f, buffer, length);
+ fclose (f);
+
+ *bufferptr = buffer;
+ return length;
+}
+
+
+/*
+==============
+SaveFile
+==============
+*/
+void SaveFile (const char *filename, const void *buffer, int count)
+{
+ FILE *f;
+
+ f = SafeOpenWrite (filename);
+ SafeWrite (f, buffer, count);
+ fclose (f);
+}
+
+
+
+void DefaultExtension (char *path, const char *extension)
+{
+ char *src;
+//
+// if path doesnt have a .EXT, append extension
+// (extension should include the .)
+//
+ src = path + strlen(path) - 1;
+
+ while (*src != '/' && *src != '\\' && src != path)
+ {
+ if (*src == '.')
+ return; // it has an extension
+ src--;
+ }
+
+ strcat (path, extension);
+}
+
+
+void DefaultPath (char *path, const char *basepath)
+{
+ char temp[128];
+
+ if (path[0] == PATHSEPERATOR)
+ return; // absolute path location
+ strcpy (temp,path);
+ strcpy (path,basepath);
+ strcat (path,temp);
+}
+
+
+void StripFilename (char *path)
+{
+ int length;
+
+ length = strlen(path)-1;
+ while (length > 0 && path[length] != PATHSEPERATOR)
+ length--;
+ path[length] = 0;
+}
+
+void StripExtension (char *path)
+{
+ int length;
+
+ length = strlen(path)-1;
+ while (length > 0 && path[length] != '.')
+ {
+ length--;
+ if (path[length] == '/')
+ return; // no extension
+ }
+ if (length)
+ path[length] = 0;
+}
+
+
+/*
+====================
+Extract file parts
+====================
+*/
+// FIXME: should include the slash, otherwise
+// backing to an empty path will be wrong when appending a slash
+void ExtractFilePath (const char *path, char *dest)
+{
+ const char *src;
+
+ src = path + strlen(path) - 1;
+
+//
+// back up until a \ or the start
+//
+ while (src != path && *(src-1) != '\\' && *(src-1) != '/')
+ src--;
+
+ memcpy (dest, path, src-path);
+ dest[src-path] = 0;
+}
+
+void ExtractFileBase (const char *path, char *dest)
+{
+ const char *src;
+
+ src = path + strlen(path) - 1;
+
+//
+// back up until a \ or the start
+//
+ while (src != path && *(src-1) != PATHSEPERATOR)
+ src--;
+
+ while (*src && *src != '.')
+ {
+ *dest++ = *src++;
+ }
+ *dest = 0;
+}
+
+void ExtractFileExtension (const char *path, char *dest)
+{
+ const char *src;
+
+ src = path + strlen(path) - 1;
+
+//
+// back up until a . or the start
+//
+ while (src != path && *(src-1) != '.')
+ src--;
+ if (src == path)
+ {
+ *dest = 0; // no extension
+ return;
+ }
+
+ strcpy (dest,src);
+}
+
+
+/*
+==============
+ParseNum / ParseHex
+==============
+*/
+int ParseHex (const char *hex)
+{
+ const char *str;
+ int num;
+
+ num = 0;
+ str = hex;
+
+ while (*str)
+ {
+ num <<= 4;
+ if (*str >= '0' && *str <= '9')
+ num += *str-'0';
+ else if (*str >= 'a' && *str <= 'f')
+ num += 10 + *str-'a';
+ else if (*str >= 'A' && *str <= 'F')
+ num += 10 + *str-'A';
+ else
+ Error ("Bad hex number: %s",hex);
+ str++;
+ }
+
+ return num;
+}
+
+
+int ParseNum (const char *str)
+{
+ if (str[0] == '$')
+ return ParseHex (str+1);
+ if (str[0] == '0' && str[1] == 'x')
+ return ParseHex (str+2);
+ return atol (str);
+}
+
+
+
+/*
+============================================================================
+
+ BYTE ORDER FUNCTIONS
+
+============================================================================
+*/
+
+#ifdef _SGI_SOURCE
+#define __BIG_ENDIAN__
+#endif
+
+#ifdef __BIG_ENDIAN__
+
+short LittleShort (short l)
+{
+ byte b1,b2;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+
+ return (b1<<8) + b2;
+}
+
+short BigShort (short l)
+{
+ return l;
+}
+
+
+int LittleLong (int l)
+{
+ byte b1,b2,b3,b4;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+ b3 = (l>>16)&255;
+ b4 = (l>>24)&255;
+
+ return ((int)b1<<24) + ((int)b2<<16) + ((int)b3<<8) + b4;
+}
+
+int BigLong (int l)
+{
+ return l;
+}
+
+
+float LittleFloat (float l)
+{
+ union {byte b[4]; float f;} in, out;
+
+ in.f = l;
+ out.b[0] = in.b[3];
+ out.b[1] = in.b[2];
+ out.b[2] = in.b[1];
+ out.b[3] = in.b[0];
+
+ return out.f;
+}
+
+float BigFloat (float l)
+{
+ return l;
+}
+
+
+#else
+
+
+short BigShort (short l)
+{
+ byte b1,b2;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+
+ return (b1<<8) + b2;
+}
+
+short LittleShort (short l)
+{
+ return l;
+}
+
+
+int BigLong (int l)
+{
+ byte b1,b2,b3,b4;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+ b3 = (l>>16)&255;
+ b4 = (l>>24)&255;
+
+ return ((int)b1<<24) + ((int)b2<<16) + ((int)b3<<8) + b4;
+}
+
+int LittleLong (int l)
+{
+ return l;
+}
+
+float BigFloat (float l)
+{
+ union {byte b[4]; float f;} in, out;
+
+ in.f = l;
+ out.b[0] = in.b[3];
+ out.b[1] = in.b[2];
+ out.b[2] = in.b[1];
+ out.b[3] = in.b[0];
+
+ return out.f;
+}
+
+float LittleFloat (float l)
+{
+ return l;
+}
+
+
+#endif
+
+
+//=======================================================
+
+
+// FIXME: byte swap?
+
+// this is a 16 bit, non-reflected CRC using the polynomial 0x1021
+// and the initial and final xor values shown below... in other words, the
+// CCITT standard CRC used by XMODEM
+
+#define CRC_INIT_VALUE 0xffff
+#define CRC_XOR_VALUE 0x0000
+
+static unsigned short crctable[256] =
+{
+ 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
+ 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
+ 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
+ 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
+ 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
+ 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
+ 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
+ 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
+ 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
+ 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
+ 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
+ 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
+ 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
+ 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
+ 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
+ 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
+ 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
+ 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
+ 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
+ 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
+ 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
+ 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
+ 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
+ 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
+ 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
+ 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
+ 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
+ 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
+ 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
+ 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
+ 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
+ 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0
+};
+
+void CRC_Init(unsigned short *crcvalue)
+{
+ *crcvalue = CRC_INIT_VALUE;
+}
+
+void CRC_ProcessByte(unsigned short *crcvalue, byte data)
+{
+ *crcvalue = (*crcvalue << 8) ^ crctable[(*crcvalue >> 8) ^ data];
+}
+
+unsigned short CRC_Value(unsigned short crcvalue)
+{
+ return crcvalue ^ CRC_XOR_VALUE;
+}
+//=============================================================================
+
+/*
+============
+CreatePath
+============
+*/
+void CreatePath (const char *path)
+{
+ const char *ofs;
+ char c;
+ char dir[1024];
+
+#ifdef _WIN32
+ int olddrive = -1;
+
+ if ( path[1] == ':' )
+ {
+ olddrive = _getdrive();
+ _chdrive( toupper( path[0] ) - 'A' + 1 );
+ }
+#endif
+
+ if (path[1] == ':')
+ path += 2;
+
+ for (ofs = path+1 ; *ofs ; ofs++)
+ {
+ c = *ofs;
+ if (c == '/' || c == '\\')
+ { // create the directory
+ memcpy( dir, path, ofs - path );
+ dir[ ofs - path ] = 0;
+ Q_mkdir( dir );
+ }
+ }
+
+#ifdef _WIN32
+ if ( olddrive != -1 )
+ {
+ _chdrive( olddrive );
+ }
+#endif
+}
+
+
+/*
+============
+QCopyFile
+
+ Used to archive source files
+============
+*/
+void QCopyFile (const char *from, const char *to)
+{
+ void *buffer;
+ int length;
+
+ length = LoadFile (from, &buffer);
+ CreatePath (to);
+ SaveFile (to, buffer, length);
+ free (buffer);
+}
diff --git a/q3asm/cmdlib.h b/q3asm/cmdlib.h
new file mode 100755
index 0000000..b7be51b
--- /dev/null
+++ b/q3asm/cmdlib.h
@@ -0,0 +1,160 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// cmdlib.h
+
+#ifndef __CMDLIB__
+#define __CMDLIB__
+
+#ifdef _WIN32
+#pragma warning(disable : 4244) // MIPS
+#pragma warning(disable : 4136) // X86
+#pragma warning(disable : 4051) // ALPHA
+
+#pragma warning(disable : 4018) // signed/unsigned mismatch
+#pragma warning(disable : 4305) // truncate from double to float
+
+#pragma check_stack(off)
+
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <ctype.h>
+#include <time.h>
+#include <stdarg.h>
+
+#ifdef _WIN32
+
+#pragma intrinsic( memset, memcpy )
+
+#endif
+
+#ifndef __BYTEBOOL__
+#define __BYTEBOOL__
+typedef enum { qfalse, qtrue } qboolean;
+typedef unsigned char byte;
+#endif
+
+#define MAX_OS_PATH 1024
+#define MEM_BLOCKSIZE 4096
+
+// the dec offsetof macro doesnt work very well...
+#define myoffsetof(type,identifier) ((size_t)&((type *)0)->identifier)
+
+
+// set these before calling CheckParm
+extern int myargc;
+extern char **myargv;
+
+char *strupr (char *in);
+char *strlower (char *in);
+int Q_strncasecmp( const char *s1, const char *s2, int n );
+int Q_stricmp( const char *s1, const char *s2 );
+void Q_getwd( char *out );
+
+int Q_filelength (FILE *f);
+int FileTime( const char *path );
+
+void Q_mkdir( const char *path );
+
+extern char qdir[1024];
+extern char gamedir[1024];
+extern char writedir[1024];
+void SetQdirFromPath( const char *path );
+char *ExpandArg( const char *path ); // from cmd line
+char *ExpandPath( const char *path ); // from scripts
+char *ExpandGamePath (const char *path);
+char *ExpandPathAndArchive( const char *path );
+
+
+double I_FloatTime( void );
+
+void Error( const char *error, ... );
+int CheckParm( const char *check );
+
+FILE *SafeOpenWrite( const char *filename );
+FILE *SafeOpenRead( const char *filename );
+void SafeRead (FILE *f, void *buffer, int count);
+void SafeWrite (FILE *f, const void *buffer, int count);
+
+int LoadFile( const char *filename, void **bufferptr );
+int LoadFileBlock( const char *filename, void **bufferptr );
+int TryLoadFile( const char *filename, void **bufferptr );
+void SaveFile( const char *filename, const void *buffer, int count );
+qboolean FileExists( const char *filename );
+
+void DefaultExtension( char *path, const char *extension );
+void DefaultPath( char *path, const char *basepath );
+void StripFilename( char *path );
+void StripExtension( char *path );
+
+void ExtractFilePath( const char *path, char *dest );
+void ExtractFileBase( const char *path, char *dest );
+void ExtractFileExtension( const char *path, char *dest );
+
+int ParseNum (const char *str);
+
+short BigShort (short l);
+short LittleShort (short l);
+int BigLong (int l);
+int LittleLong (int l);
+float BigFloat (float l);
+float LittleFloat (float l);
+
+
+char *COM_Parse (char *data);
+
+extern char com_token[1024];
+extern qboolean com_eof;
+
+char *copystring(const char *s);
+
+
+void CRC_Init(unsigned short *crcvalue);
+void CRC_ProcessByte(unsigned short *crcvalue, byte data);
+unsigned short CRC_Value(unsigned short crcvalue);
+
+void CreatePath( const char *path );
+void QCopyFile( const char *from, const char *to );
+
+extern qboolean archive;
+extern char archivedir[1024];
+
+
+extern qboolean verbose;
+void qprintf( const char *format, ... );
+void _printf( const char *format, ... );
+
+void ExpandWildcards( int *argc, char ***argv );
+
+
+// for compression routines
+typedef struct
+{
+ void *data;
+ int count, width, height;
+} cblock_t;
+
+
+#endif
diff --git a/q3asm/lib.txt b/q3asm/lib.txt
new file mode 100755
index 0000000..7abf270
--- /dev/null
+++ b/q3asm/lib.txt
@@ -0,0 +1,31 @@
+
+strlen
+strcasecmp
+tolower
+strcat
+strncpy
+strcmp
+strcpy
+strchr
+
+vsprintf
+
+memcpy
+memset
+rand
+
+atoi
+atof
+
+abs
+
+floor
+fabs
+tan
+atan
+sqrt
+log
+cos
+sin
+atan2
+
diff --git a/q3asm/mathlib.h b/q3asm/mathlib.h
new file mode 100755
index 0000000..8034808
--- /dev/null
+++ b/q3asm/mathlib.h
@@ -0,0 +1,94 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __MATHLIB__
+#define __MATHLIB__
+
+// mathlib.h
+
+#include <math.h>
+
+#ifdef DOUBLEVEC_T
+typedef double vec_t;
+#else
+typedef float vec_t;
+#endif
+typedef vec_t vec2_t[3];
+typedef vec_t vec3_t[3];
+typedef vec_t vec4_t[4];
+
+#define SIDE_FRONT 0
+#define SIDE_ON 2
+#define SIDE_BACK 1
+#define SIDE_CROSS -2
+
+#define Q_PI 3.14159265358979323846
+#define DEG2RAD( a ) ( ( (a) * Q_PI ) / 180.0F )
+#define RAD2DEG( a ) ( ( (a) * 180.0f ) / Q_PI )
+
+extern vec3_t vec3_origin;
+
+#define EQUAL_EPSILON 0.001
+
+// plane types are used to speed some tests
+// 0-2 are axial planes
+#define PLANE_X 0
+#define PLANE_Y 1
+#define PLANE_Z 2
+#define PLANE_NON_AXIAL 3
+
+qboolean VectorCompare( const vec3_t v1, const vec3_t v2 );
+
+#define DotProduct(x,y) (x[0]*y[0]+x[1]*y[1]+x[2]*y[2])
+#define VectorSubtract(a,b,c) {c[0]=a[0]-b[0];c[1]=a[1]-b[1];c[2]=a[2]-b[2];}
+#define VectorAdd(a,b,c) {c[0]=a[0]+b[0];c[1]=a[1]+b[1];c[2]=a[2]+b[2];}
+#define VectorCopy(a,b) {b[0]=a[0];b[1]=a[1];b[2]=a[2];}
+#define VectorScale(a,b,c) {c[0]=b*a[0];c[1]=b*a[1];c[2]=b*a[2];}
+#define VectorClear(x) {x[0] = x[1] = x[2] = 0;}
+#define VectorNegate(x) {x[0]=-x[0];x[1]=-x[1];x[2]=-x[2];}
+void Vec10Copy( vec_t *in, vec_t *out );
+
+vec_t Q_rint (vec_t in);
+vec_t _DotProduct (vec3_t v1, vec3_t v2);
+void _VectorSubtract (vec3_t va, vec3_t vb, vec3_t out);
+void _VectorAdd (vec3_t va, vec3_t vb, vec3_t out);
+void _VectorCopy (vec3_t in, vec3_t out);
+void _VectorScale (vec3_t v, vec_t scale, vec3_t out);
+
+double VectorLength( const vec3_t v );
+
+void VectorMA( const vec3_t va, double scale, const vec3_t vb, vec3_t vc );
+
+void CrossProduct( const vec3_t v1, const vec3_t v2, vec3_t cross );
+vec_t VectorNormalize( const vec3_t in, vec3_t out );
+vec_t ColorNormalize( const vec3_t in, vec3_t out );
+void VectorInverse (vec3_t v);
+
+void ClearBounds (vec3_t mins, vec3_t maxs);
+void AddPointToBounds( const vec3_t v, vec3_t mins, vec3_t maxs );
+
+qboolean PlaneFromPoints( vec4_t plane, const vec3_t a, const vec3_t b, const vec3_t c );
+
+void NormalToLatLong( const vec3_t normal, byte bytes[2] );
+
+int PlaneTypeForNormal (vec3_t normal);
+
+#endif
diff --git a/q3asm/notes.txt b/q3asm/notes.txt
new file mode 100755
index 0000000..4a016f0
--- /dev/null
+++ b/q3asm/notes.txt
@@ -0,0 +1,16 @@
+
+don't do any paramter conversion (double to float, etc)
+
+
+
+Why?
+
+Security.
+Portability.
+
+It may be more aproachable.
+
+can still use regular dlls for development purposes
+
+lcc
+q3asm
diff --git a/q3asm/ops.txt b/q3asm/ops.txt
new file mode 100755
index 0000000..992e288
--- /dev/null
+++ b/q3asm/ops.txt
@@ -0,0 +1,132 @@
+CNSTF,
+CNSTI,
+CNSTP,
+CNSTU,
+
+ARGB,
+ARGF,
+ARGI,
+ARGP,
+ARGU,
+
+ASGNB,
+ASGNF,
+ASGNI,
+ASGNP,
+ASGNU,
+
+INDIRB,
+INDIRF,
+INDIRI,
+INDIRP,
+INDIRU,
+
+CVFF,
+CVFI,
+
+CVIF,
+CVII,
+CVIU,
+
+CVPU,
+
+CVUI,
+CVUP,
+CVUU,
+
+NEGF,
+NEGI,
+
+CALLB,
+CALLF,
+CALLI,
+CALLP,
+CALLU,
+CALLV,
+
+RETF,
+RETI,
+RETP,
+RETU,
+RETV,
+
+ADDRGP,
+
+ADDRFP,
+
+ADDRLP,
+
+ADDF,
+ADDI,
+ADDP,
+ADDU,
+
+SUBF,
+SUBI,
+SUBP,
+SUBU,
+
+LSHI,
+LSHU,
+
+MODI,
+MODU,
+
+RSHI,
+RSHU,
+
+BANDI,
+BANDU,
+
+BCOMI,
+BCOMU,
+
+BORI,
+BORU,
+
+BXORI,
+BXORU,
+
+DIVF,
+DIVI,
+DIVU,
+
+MULF,
+MULI,
+MULU,
+
+EQF,
+EQI,
+EQU,
+
+GEF,
+GEI,
+GEU,
+
+GTF,
+GTI,
+GTU,
+
+LEF,
+LEI,
+LEU,
+
+LTF,
+LTI,
+LTU,
+
+NEF,
+NEI,
+NEU,
+
+JUMPV,
+
+LABELV,
+
+LOADB,
+LOADF,
+LOADI,
+LOADP,
+LOADU,
+
+
diff --git a/q3asm/opstrings.h b/q3asm/opstrings.h
new file mode 100755
index 0000000..51f2bf3
--- /dev/null
+++ b/q3asm/opstrings.h
@@ -0,0 +1,175 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+{ "BREAK", OP_BREAK },
+
+{ "CNSTF4", OP_CONST },
+{ "CNSTI4", OP_CONST },
+{ "CNSTP4", OP_CONST },
+{ "CNSTU4", OP_CONST },
+
+{ "CNSTI2", OP_CONST },
+{ "CNSTU2", OP_CONST },
+
+{ "CNSTI1", OP_CONST },
+{ "CNSTU1", OP_CONST },
+
+//{ "ARGB", OP_ARG },
+//{ "ARGF", OP_ARG },
+//{ "ARGI", OP_ARG },
+//{ "ARGP", OP_ARG },
+//{ "ARGU", OP_ARG },
+
+{ "ASGNB", OP_BLOCK_COPY },
+{ "ASGNF4", OP_STORE4 },
+{ "ASGNI4", OP_STORE4 },
+{ "ASGNP4", OP_STORE4 },
+{ "ASGNU4", OP_STORE4 },
+
+{ "ASGNI2", OP_STORE2 },
+{ "ASGNU2", OP_STORE2 },
+
+{ "ASGNI1", OP_STORE1 },
+{ "ASGNU1", OP_STORE1 },
+
+{ "INDIRB", OP_IGNORE }, // block copy deals with this
+{ "INDIRF4", OP_LOAD4 },
+{ "INDIRI4", OP_LOAD4 },
+{ "INDIRP4", OP_LOAD4 },
+{ "INDIRU4", OP_LOAD4 },
+
+{ "INDIRI2", OP_LOAD2 },
+{ "INDIRU2", OP_LOAD2 },
+
+{ "INDIRI1", OP_LOAD1 },
+{ "INDIRU1", OP_LOAD1 },
+
+{ "CVFF4", OP_UNDEF },
+{ "CVFI4", OP_CVFI },
+
+{ "CVIF4", OP_CVIF },
+{ "CVII4", OP_SEX8 }, // will be either SEX8 or SEX16
+{ "CVII1", OP_IGNORE },
+{ "CVII2", OP_IGNORE },
+{ "CVIU4", OP_IGNORE },
+
+{ "CVPU4", OP_IGNORE },
+
+{ "CVUI4", OP_IGNORE },
+{ "CVUP4", OP_IGNORE },
+{ "CVUU4", OP_IGNORE },
+
+{ "CVUU1", OP_IGNORE },
+
+{ "NEGF4", OP_NEGF },
+{ "NEGI4", OP_NEGI },
+
+//{ "CALLB", OP_UNDEF },
+//{ "CALLF", OP_UNDEF },
+//{ "CALLI", OP_UNDEF },
+//{ "CALLP", OP_UNDEF },
+//{ "CALLU", OP_UNDEF },
+//{ "CALLV", OP_CALL },
+
+//{ "RETF", OP_UNDEF },
+//{ "RETI", OP_UNDEF },
+//{ "RETP", OP_UNDEF },
+//{ "RETU", OP_UNDEF },
+//{ "RETV", OP_UNDEF },
+
+{ "ADDRGP4", OP_CONST },
+
+//{ "ADDRFP", OP_PARM },
+//{ "ADDRLP", OP_LOCAL },
+
+{ "ADDF4", OP_ADDF },
+{ "ADDI4", OP_ADD },
+{ "ADDP4", OP_ADD },
+{ "ADDP", OP_ADD },
+{ "ADDU4", OP_ADD },
+
+{ "SUBF4", OP_SUBF },
+{ "SUBI4", OP_SUB },
+{ "SUBP4", OP_SUB },
+{ "SUBU4", OP_SUB },
+
+{ "LSHI4", OP_LSH },
+{ "LSHU4", OP_LSH },
+
+{ "MODI4", OP_MODI },
+{ "MODU4", OP_MODU },
+
+{ "RSHI4", OP_RSHI },
+{ "RSHU4", OP_RSHU },
+
+{ "BANDI4", OP_BAND },
+{ "BANDU4", OP_BAND },
+
+{ "BCOMI4", OP_BCOM },
+{ "BCOMU4", OP_BCOM },
+
+{ "BORI4", OP_BOR },
+{ "BORU4", OP_BOR },
+
+{ "BXORI4", OP_BXOR },
+{ "BXORU4", OP_BXOR },
+
+{ "DIVF4", OP_DIVF },
+{ "DIVI4", OP_DIVI },
+{ "DIVU4", OP_DIVU },
+
+{ "MULF4", OP_MULF },
+{ "MULI4", OP_MULI },
+{ "MULU4", OP_MULU },
+
+{ "EQF4", OP_EQF },
+{ "EQI4", OP_EQ },
+{ "EQU4", OP_EQ },
+
+{ "GEF4", OP_GEF },
+{ "GEI4", OP_GEI },
+{ "GEU4", OP_GEU },
+
+{ "GTF4", OP_GTF },
+{ "GTI4", OP_GTI },
+{ "GTU4", OP_GTU },
+
+{ "LEF4", OP_LEF },
+{ "LEI4", OP_LEI },
+{ "LEU4", OP_LEU },
+
+{ "LTF4", OP_LTF },
+{ "LTI4", OP_LTI },
+{ "LTU4", OP_LTU },
+
+{ "NEF4", OP_NEF },
+{ "NEI4", OP_NE },
+{ "NEU4", OP_NE },
+
+{ "JUMPV", OP_JUMP },
+
+{ "LOADB4", OP_UNDEF },
+{ "LOADF4", OP_UNDEF },
+{ "LOADI4", OP_UNDEF },
+{ "LOADP4", OP_UNDEF },
+{ "LOADU4", OP_UNDEF },
+
+
diff --git a/q3asm/q3asm.c b/q3asm/q3asm.c
new file mode 100755
index 0000000..836e427
--- /dev/null
+++ b/q3asm/q3asm.c
@@ -0,0 +1,1047 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "cmdlib.h"
+#include "mathlib.h"
+#include "qfiles.h"
+
+/* MSVC-ism fix. */
+#define atoi(s) strtoul(s,NULL,10)
+
+char outputFilename[MAX_OS_PATH];
+
+// the zero page size is just used for detecting run time faults
+#define ZERO_PAGE_SIZE 0 // 256
+
+typedef enum {
+ OP_UNDEF,
+
+ OP_IGNORE,
+
+ OP_BREAK,
+
+ OP_ENTER,
+ OP_LEAVE,
+ OP_CALL,
+ OP_PUSH,
+ OP_POP,
+
+ OP_CONST,
+ OP_LOCAL,
+
+ OP_JUMP,
+
+ //-------------------
+
+ OP_EQ,
+ OP_NE,
+
+ OP_LTI,
+ OP_LEI,
+ OP_GTI,
+ OP_GEI,
+
+ OP_LTU,
+ OP_LEU,
+ OP_GTU,
+ OP_GEU,
+
+ OP_EQF,
+ OP_NEF,
+
+ OP_LTF,
+ OP_LEF,
+ OP_GTF,
+ OP_GEF,
+
+ //-------------------
+
+ OP_LOAD1,
+ OP_LOAD2,
+ OP_LOAD4,
+ OP_STORE1,
+ OP_STORE2,
+ OP_STORE4, // *(stack[top-1]) = stack[yop
+ OP_ARG,
+ OP_BLOCK_COPY,
+
+ //-------------------
+
+ OP_SEX8,
+ OP_SEX16,
+
+ OP_NEGI,
+ OP_ADD,
+ OP_SUB,
+ OP_DIVI,
+ OP_DIVU,
+ OP_MODI,
+ OP_MODU,
+ OP_MULI,
+ OP_MULU,
+
+ OP_BAND,
+ OP_BOR,
+ OP_BXOR,
+ OP_BCOM,
+
+ OP_LSH,
+ OP_RSHI,
+ OP_RSHU,
+
+ OP_NEGF,
+ OP_ADDF,
+ OP_SUBF,
+ OP_DIVF,
+ OP_MULF,
+
+ OP_CVIF,
+ OP_CVFI
+} opcode_t;
+
+typedef struct {
+ int imageBytes; // after decompression
+ int entryPoint;
+ int stackBase;
+ int stackSize;
+} executableHeader_t;
+
+typedef enum {
+ CODESEG,
+ DATASEG, // initialized 32 bit data, will be byte swapped
+ LITSEG, // strings
+ BSSSEG, // 0 filled
+ NUM_SEGMENTS
+} segmentName_t;
+
+#define MAX_IMAGE 0x400000
+
+typedef struct {
+ byte image[MAX_IMAGE];
+ int imageUsed;
+ int segmentBase; // only valid on second pass
+} segment_t;
+
+typedef struct symbol_s {
+ struct symbol_s *next;
+ int hash;
+ segment_t *segment;
+ char *name;
+ int value;
+} symbol_t;
+
+
+segment_t segment[NUM_SEGMENTS];
+segment_t *currentSegment;
+
+int passNumber;
+
+int numSymbols;
+int errorCount;
+
+symbol_t *symbols;
+symbol_t *lastSymbol;
+
+
+#define MAX_ASM_FILES 256
+int numAsmFiles;
+char *asmFiles[MAX_ASM_FILES];
+char *asmFileNames[MAX_ASM_FILES];
+
+int currentFileIndex;
+char *currentFileName;
+int currentFileLine;
+
+//int stackSize = 16384;
+int stackSize = 0x10000;
+
+// we need to convert arg and ret instructions to
+// stores to the local stack frame, so we need to track the
+// characteristics of the current functions stack frame
+int currentLocals; // bytes of locals needed by this function
+int currentArgs; // bytes of largest argument list called from this function
+int currentArgOffset; // byte offset in currentArgs to store next arg, reset each call
+
+#define MAX_LINE_LENGTH 1024
+char lineBuffer[MAX_LINE_LENGTH];
+int lineParseOffset;
+char token[MAX_LINE_LENGTH];
+
+int instructionCount;
+
+typedef struct {
+ char *name;
+ int opcode;
+} sourceOps_t;
+
+sourceOps_t sourceOps[] = {
+#include "opstrings.h"
+};
+
+#define NUM_SOURCE_OPS ( sizeof( sourceOps ) / sizeof( sourceOps[0] ) )
+
+int opcodesHash[ NUM_SOURCE_OPS ];
+
+
+/*
+=============
+HashString
+=============
+*/
+int HashString( char *s ) {
+ int v = 0;
+
+ while ( *s ) {
+ v += *s;
+ s++;
+ }
+ return v;
+}
+
+
+/*
+============
+CodeError
+============
+*/
+void CodeError( char *fmt, ... ) {
+ va_list argptr;
+
+ errorCount++;
+
+ printf( "%s:%i ", currentFileName, currentFileLine );
+
+ va_start( argptr,fmt );
+ vprintf( fmt,argptr );
+ va_end( argptr );
+}
+
+/*
+============
+EmitByte
+============
+*/
+void EmitByte( segment_t *seg, int v ) {
+ if ( seg->imageUsed >= MAX_IMAGE ) {
+ Error( "MAX_IMAGE" );
+ }
+ seg->image[ seg->imageUsed ] = v;
+ seg->imageUsed++;
+}
+
+/*
+============
+EmitInt
+============
+*/
+void EmitInt( segment_t *seg, int v ) {
+ if ( seg->imageUsed >= MAX_IMAGE - 4) {
+ Error( "MAX_IMAGE" );
+ }
+ seg->image[ seg->imageUsed ] = v & 255;
+ seg->image[ seg->imageUsed + 1 ] = ( v >> 8 ) & 255;
+ seg->image[ seg->imageUsed + 2 ] = ( v >> 16 ) & 255;
+ seg->image[ seg->imageUsed + 3 ] = ( v >> 24 ) & 255;
+ seg->imageUsed += 4;
+}
+
+/*
+============
+DefineSymbol
+
+Symbols can only be defined on pass 0
+============
+*/
+void DefineSymbol( char *sym, int value ) {
+ symbol_t *s, *after;
+ char expanded[MAX_LINE_LENGTH];
+ int hash;
+
+ if ( passNumber == 1 ) {
+ return;
+ }
+
+ // TTimo
+ // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=381
+ // as a security, bail out if vmMain entry point is not first
+ if (!Q_stricmp(sym, "vmMain"))
+ if (value)
+ Error( "vmMain must be the first symbol in the qvm (got offset %d)\n", value );
+
+ // add the file prefix to local symbols to guarantee unique
+ if ( sym[0] == '$' ) {
+ sprintf( expanded, "%s_%i", sym, currentFileIndex );
+ sym = expanded;
+ }
+
+ hash = HashString( sym );
+
+ for ( s = symbols ; s ; s = s->next ) {
+ if ( hash == s->hash && !strcmp( sym, s->name ) ) {
+ CodeError( "Multiple definitions for %s\n", sym );
+ return;
+ }
+ }
+
+ s = malloc( sizeof( *s ) );
+ s->name = copystring( sym );
+ s->hash = hash;
+ s->value = value;
+ s->segment = currentSegment;
+
+ lastSymbol = s; /* for the move-to-lit-segment byteswap hack */
+
+ // insert it in order
+ if ( !symbols || s->value < symbols->value ) {
+ s->next = symbols;
+ symbols = s;
+ return;
+ }
+
+ for ( after = symbols ; after->next && after->next->value < value ; after = after->next ) {
+ }
+ s->next = after->next;
+ after->next = s;
+}
+
+
+/*
+============
+LookupSymbol
+
+Symbols can only be evaluated on pass 1
+============
+*/
+int LookupSymbol( char *sym ) {
+ symbol_t *s;
+ char expanded[MAX_LINE_LENGTH];
+ int hash;
+
+ if ( passNumber == 0 ) {
+ return 0;
+ }
+
+ // add the file prefix to local symbols to guarantee unique
+ if ( sym[0] == '$' ) {
+ sprintf( expanded, "%s_%i", sym, currentFileIndex );
+ sym = expanded;
+ }
+
+ hash = HashString( sym );
+ for ( s = symbols ; s ; s = s->next ) {
+ if ( hash == s->hash && !strcmp( sym, s->name ) ) {
+ return s->segment->segmentBase + s->value;
+ }
+ }
+
+ CodeError( "ERROR: symbol %s undefined\n", sym );
+ passNumber = 0;
+ DefineSymbol( sym, 0 ); // so more errors aren't printed
+ passNumber = 1;
+ return 0;
+}
+
+
+/*
+==============
+ExtractLine
+
+Extracts the next line from the given text block.
+If a full line isn't parsed, returns NULL
+Otherwise returns the updated parse pointer
+===============
+*/
+char *ExtractLine( char *data ) {
+ int i;
+
+ currentFileLine++;
+ lineParseOffset = 0;
+ token[0] = 0;
+
+ if ( data[0] == 0 ) {
+ lineBuffer[0] = 0;
+ return NULL;
+ }
+
+ for ( i = 0 ; i < MAX_LINE_LENGTH ; i++ ) {
+ if ( data[i] == 0 || data[i] == '\n' ) {
+ break;
+ }
+ }
+ if ( i == MAX_LINE_LENGTH ) {
+ CodeError( "MAX_LINE_LENGTH" );
+ return data;
+ }
+ memcpy( lineBuffer, data, i );
+ lineBuffer[i] = 0;
+ data += i;
+ if ( data[0] == '\n' ) {
+ data++;
+ }
+ return data;
+}
+
+
+/*
+==============
+Parse
+
+Parse a token out of linebuffer
+==============
+*/
+qboolean Parse( void ) {
+ int c;
+ int len;
+
+ len = 0;
+ token[0] = 0;
+
+ // skip whitespace
+ while ( lineBuffer[ lineParseOffset ] <= ' ' ) {
+ if ( lineBuffer[ lineParseOffset ] == 0 ) {
+ return qfalse;
+ }
+ lineParseOffset++;
+ }
+
+ // skip ; comments
+ c = lineBuffer[ lineParseOffset ];
+ if ( c == ';' ) {
+ return qfalse;
+ }
+
+
+ // parse a regular word
+ do {
+ token[len] = c;
+ len++;
+ lineParseOffset++;
+ c = lineBuffer[ lineParseOffset ];
+ } while (c>32);
+
+ token[len] = 0;
+ return qtrue;
+}
+
+
+/*
+==============
+ParseValue
+==============
+*/
+int ParseValue( void ) {
+ Parse();
+ return atoi( token );
+}
+
+
+/*
+==============
+ParseExpression
+==============
+*/
+int ParseExpression(void) {
+ int i, j;
+ char sym[MAX_LINE_LENGTH];
+ int v;
+
+ if ( token[0] == '-' ) {
+ i = 1;
+ } else {
+ i = 0;
+ }
+
+ for ( ; i < MAX_LINE_LENGTH ; i++ ) {
+ if ( token[i] == '+' || token[i] == '-' || token[i] == 0 ) {
+ break;
+ }
+ }
+
+ memcpy( sym, token, i );
+ sym[i] = 0;
+
+ if ( ( sym[0] >= '0' && sym[0] <= '9' ) || sym[0] == '-' ) {
+ v = atoi( sym );
+ } else {
+ v = LookupSymbol( sym );
+ }
+
+ // parse add / subtract offsets
+ while ( token[i] != 0 ) {
+ for ( j = i + 1 ; j < MAX_LINE_LENGTH ; j++ ) {
+ if ( token[j] == '+' || token[j] == '-' || token[j] == 0 ) {
+ break;
+ }
+ }
+
+ memcpy( sym, token+i+1, j-i-1 );
+ sym[j-i-1] = 0;
+
+ if ( token[i] == '+' ) {
+ v += atoi( sym );
+ }
+ if ( token[i] == '-' ) {
+ v -= atoi( sym );
+ }
+ i = j;
+ }
+
+ return v;
+}
+
+
+/*
+==============
+HackToSegment
+
+BIG HACK: I want to put all 32 bit values in the data
+segment so they can be byte swapped, and all char data in the lit
+segment, but switch jump tables are emited in the lit segment and
+initialized strng variables are put in the data segment.
+
+I can change segments here, but I also need to fixup the
+label that was just defined
+
+Note that the lit segment is read-write in the VM, so strings
+aren't read only as in some architectures.
+==============
+*/
+void HackToSegment( segmentName_t seg ) {
+ if ( currentSegment == &segment[seg] ) {
+ return;
+ }
+
+ currentSegment = &segment[seg];
+ if ( passNumber == 0 ) {
+ lastSymbol->segment = currentSegment;
+ lastSymbol->value = currentSegment->imageUsed;
+ }
+}
+
+/*
+==============
+AssembleLine
+
+==============
+*/
+void AssembleLine( void ) {
+ int v, v2;
+ int i;
+ int hash;
+
+ Parse();
+ if ( !token[0] ) {
+ return;
+ }
+
+ hash = HashString( token );
+
+ for ( i = 0 ; i < NUM_SOURCE_OPS ; i++ ) {
+ if ( hash == opcodesHash[i] && !strcmp( token, sourceOps[i].name ) ) {
+ int opcode;
+ int expression;
+
+ if ( sourceOps[i].opcode == OP_UNDEF ) {
+ CodeError( "Undefined opcode: %s\n", token );
+ }
+ if ( sourceOps[i].opcode == OP_IGNORE ) {
+ return; // we ignore most conversions
+ }
+
+ // sign extensions need to check next parm
+ opcode = sourceOps[i].opcode;
+ if ( opcode == OP_SEX8 ) {
+ Parse();
+ if ( token[0] == '1' ) {
+ opcode = OP_SEX8;
+ } else if ( token[0] == '2' ) {
+ opcode = OP_SEX16;
+ } else {
+ CodeError( "Bad sign extension: %s\n", token );
+ return;
+ }
+ }
+
+ // check for expression
+ Parse();
+ if ( token[0] && sourceOps[i].opcode != OP_CVIF
+ && sourceOps[i].opcode != OP_CVFI ) {
+ expression = ParseExpression();
+
+ // code like this can generate non-dword block copies:
+ // auto char buf[2] = " ";
+ // we are just going to round up. This might conceivably
+ // be incorrect if other initialized chars follow.
+ if ( opcode == OP_BLOCK_COPY ) {
+ expression = ( expression + 3 ) & ~3;
+ }
+
+ EmitByte( &segment[CODESEG], opcode );
+ EmitInt( &segment[CODESEG], expression );
+ } else {
+ EmitByte( &segment[CODESEG], opcode );
+ }
+
+ instructionCount++;
+ return;
+ }
+ }
+
+ // call instructions reset currentArgOffset
+ if ( !strncmp( token, "CALL", 4 ) ) {
+ EmitByte( &segment[CODESEG], OP_CALL );
+ instructionCount++;
+ currentArgOffset = 0;
+ return;
+ }
+
+ // arg is converted to a reversed store
+ if ( !strncmp( token, "ARG", 3 ) ) {
+ EmitByte( &segment[CODESEG], OP_ARG );
+ instructionCount++;
+ if ( 8 + currentArgOffset >= 256 ) {
+ CodeError( "currentArgOffset >= 256" );
+ return;
+ }
+ EmitByte( &segment[CODESEG], 8 + currentArgOffset );
+ currentArgOffset += 4;
+ return;
+ }
+
+ // ret just leaves something on the op stack
+ if ( !strncmp( token, "RET", 3 ) ) {
+ EmitByte( &segment[CODESEG], OP_LEAVE );
+ instructionCount++;
+ EmitInt( &segment[CODESEG], 8 + currentLocals + currentArgs );
+ return;
+ }
+
+ // pop is needed to discard the return value of
+ // a function
+ if ( !strncmp( token, "pop", 3 ) ) {
+ EmitByte( &segment[CODESEG], OP_POP );
+ instructionCount++;
+ return;
+ }
+
+ // address of a parameter is converted to OP_LOCAL
+ if ( !strncmp( token, "ADDRF", 5 ) ) {
+ instructionCount++;
+ Parse();
+ v = ParseExpression();
+ v = 16 + currentArgs + currentLocals + v;
+ EmitByte( &segment[CODESEG], OP_LOCAL );
+ EmitInt( &segment[CODESEG], v );
+ return;
+ }
+
+ // address of a local is converted to OP_LOCAL
+ if ( !strncmp( token, "ADDRL", 5 ) ) {
+ instructionCount++;
+ Parse();
+ v = ParseExpression();
+ v = 8 + currentArgs + v;
+ EmitByte( &segment[CODESEG], OP_LOCAL );
+ EmitInt( &segment[CODESEG], v );
+ return;
+ }
+
+ if ( !strcmp( token, "proc" ) ) {
+ char name[1024];
+
+ Parse(); // function name
+ strcpy( name, token );
+
+ DefineSymbol( token, instructionCount ); // segment[CODESEG].imageUsed );
+
+ currentLocals = ParseValue(); // locals
+ currentLocals = ( currentLocals + 3 ) & ~3;
+ currentArgs = ParseValue(); // arg marshalling
+ currentArgs = ( currentArgs + 3 ) & ~3;
+
+ if ( 8 + currentLocals + currentArgs >= 32767 ) {
+ CodeError( "Locals > 32k in %s\n", name );
+ }
+
+ instructionCount++;
+ EmitByte( &segment[CODESEG], OP_ENTER );
+ EmitInt( &segment[CODESEG], 8 + currentLocals + currentArgs );
+ return;
+ }
+ if ( !strcmp( token, "endproc" ) ) {
+ Parse(); // skip the function name
+ v = ParseValue(); // locals
+ v2 = ParseValue(); // arg marshalling
+
+ // all functions must leave something on the opstack
+ instructionCount++;
+ EmitByte( &segment[CODESEG], OP_PUSH );
+
+ instructionCount++;
+ EmitByte( &segment[CODESEG], OP_LEAVE );
+ EmitInt( &segment[CODESEG], 8 + currentLocals + currentArgs );
+
+ return;
+ }
+
+
+ if ( !strcmp( token, "address" ) ) {
+ Parse();
+ v = ParseExpression();
+
+ HackToSegment( DATASEG );
+ EmitInt( currentSegment, v );
+ return;
+ }
+ if ( !strcmp( token, "export" ) ) {
+ return;
+ }
+ if ( !strcmp( token, "import" ) ) {
+ return;
+ }
+ if ( !strcmp( token, "code" ) ) {
+ currentSegment = &segment[CODESEG];
+ return;
+ }
+ if ( !strcmp( token, "bss" ) ) {
+ currentSegment = &segment[BSSSEG];
+ return;
+ }
+ if ( !strcmp( token, "data" ) ) {
+ currentSegment = &segment[DATASEG];
+ return;
+ }
+ if ( !strcmp( token, "lit" ) ) {
+ currentSegment = &segment[LITSEG];
+ return;
+ }
+ if ( !strcmp( token, "line" ) ) {
+ return;
+ }
+ if ( !strcmp( token, "file" ) ) {
+ return;
+ }
+
+ if ( !strcmp( token, "equ" ) ) {
+ char name[1024];
+
+ Parse();
+ strcpy( name, token );
+ Parse();
+ DefineSymbol( name, atoi(token) );
+ return;
+ }
+
+ if ( !strcmp( token, "align" ) ) {
+ v = ParseValue();
+ currentSegment->imageUsed = (currentSegment->imageUsed + v - 1 ) & ~( v - 1 );
+ return;
+ }
+
+ if ( !strcmp( token, "skip" ) ) {
+ v = ParseValue();
+ currentSegment->imageUsed += v;
+ return;
+ }
+
+ if ( !strcmp( token, "byte" ) ) {
+ v = ParseValue();
+ v2 = ParseValue();
+
+ if ( v == 1 ) {
+ HackToSegment( LITSEG );
+ } else if ( v == 4 ) {
+ HackToSegment( DATASEG );
+ } else if ( v == 2 ) {
+ CodeError( "16 bit initialized data not supported" );
+ }
+
+ // emit little endien
+ for ( i = 0 ; i < v ; i++ ) {
+ EmitByte( currentSegment, v2 );
+ v2 >>= 8;
+ }
+ return;
+ }
+
+ // code labels are emited as instruction counts, not byte offsets,
+ // because the physical size of the code will change with
+ // different run time compilers and we want to minimize the
+ // size of the required translation table
+ if ( !strncmp( token, "LABEL", 5 ) ) {
+ Parse();
+ if ( currentSegment == &segment[CODESEG] ) {
+ DefineSymbol( token, instructionCount );
+ } else {
+ DefineSymbol( token, currentSegment->imageUsed );
+ }
+ return;
+ }
+
+ CodeError( "Unknown token: %s\n", token );
+}
+
+/*
+==============
+InitTables
+==============
+*/
+void InitTables( void ) {
+ int i;
+
+ for ( i = 0 ; i < NUM_SOURCE_OPS ; i++ ) {
+ opcodesHash[i] = HashString( sourceOps[i].name );
+ }
+}
+
+
+/*
+==============
+WriteMapFile
+==============
+*/
+void WriteMapFile( void ) {
+ FILE *f;
+ symbol_t *s;
+ char imageName[MAX_OS_PATH];
+ int seg;
+
+ strcpy( imageName, outputFilename );
+ StripExtension( imageName );
+ strcat( imageName, ".map" );
+
+ printf( "Writing %s...\n", imageName );
+ f = SafeOpenWrite( imageName );
+ for ( seg = CODESEG ; seg <= BSSSEG ; seg++ ) {
+ for ( s = symbols ; s ; s = s->next ) {
+ if ( s->name[0] == '$' ) {
+ continue; // skip locals
+ }
+ if ( &segment[seg] != s->segment ) {
+ continue;
+ }
+ fprintf( f, "%i %8x %s\n", seg, s->value, s->name );
+ }
+ }
+ fclose( f );
+}
+
+/*
+===============
+WriteVmFile
+===============
+*/
+void WriteVmFile( void ) {
+ char imageName[MAX_OS_PATH];
+ vmHeader_t header;
+ FILE *f;
+
+ printf( "%i total errors\n", errorCount );
+ strcpy( imageName, outputFilename );
+ StripExtension( imageName );
+ strcat( imageName, ".qvm" );
+
+ remove( imageName );
+
+ printf( "code segment: %7i\n", segment[CODESEG].imageUsed );
+ printf( "data segment: %7i\n", segment[DATASEG].imageUsed );
+ printf( "lit segment: %7i\n", segment[LITSEG].imageUsed );
+ printf( "bss segment: %7i\n", segment[BSSSEG].imageUsed );
+ printf( "instruction count: %i\n", instructionCount );
+ if ( errorCount != 0 ) {
+ printf( "Not writing a file due to errors\n" );
+ return;
+ }
+
+ header.vmMagic = VM_MAGIC;
+ header.instructionCount = instructionCount;
+ header.codeOffset = sizeof( header );
+ header.codeLength = segment[CODESEG].imageUsed;
+ header.dataOffset = header.codeOffset + segment[CODESEG].imageUsed;
+ header.dataLength = segment[DATASEG].imageUsed;
+ header.litLength = segment[LITSEG].imageUsed;
+ header.bssLength = segment[BSSSEG].imageUsed;
+
+ printf( "Writing to %s\n", imageName );
+
+ CreatePath( imageName );
+ f = SafeOpenWrite( imageName );
+ SafeWrite( f, &header, sizeof( header ) );
+ SafeWrite( f, &segment[CODESEG].image, segment[CODESEG].imageUsed );
+ SafeWrite( f, &segment[DATASEG].image, segment[DATASEG].imageUsed );
+ SafeWrite( f, &segment[LITSEG].image, segment[LITSEG].imageUsed );
+ fclose( f );
+}
+
+/*
+===============
+Assemble
+===============
+*/
+void Assemble( void ) {
+ int i;
+ char filename[MAX_OS_PATH];
+ char *ptr;
+
+ printf( "outputFilename: %s\n", outputFilename );
+
+ for ( i = 0 ; i < numAsmFiles ; i++ ) {
+ strcpy( filename, asmFileNames[ i ] );
+ DefaultExtension( filename, ".asm" );
+ LoadFile( filename, (void **)&asmFiles[i] );
+ }
+
+ // assemble
+ for ( passNumber = 0 ; passNumber < 2 ; passNumber++ ) {
+ segment[LITSEG].segmentBase = segment[DATASEG].imageUsed;
+ segment[BSSSEG].segmentBase = segment[LITSEG].segmentBase + segment[LITSEG].imageUsed;
+ for ( i = 0 ; i < NUM_SEGMENTS ; i++ ) {
+ segment[i].imageUsed = 0;
+ }
+ segment[DATASEG].imageUsed = 4; // skip the 0 byte, so NULL pointers are fixed up properly
+ instructionCount = 0;
+
+ for ( i = 0 ; i < numAsmFiles ; i++ ) {
+ currentFileIndex = i;
+ currentFileName = asmFileNames[ i ];
+ currentFileLine = 0;
+ printf("pass %i: %s\n", passNumber, currentFileName );
+ ptr = asmFiles[i];
+ while ( ptr ) {
+ ptr = ExtractLine( ptr );
+ AssembleLine();
+ }
+ }
+
+ // align all segment
+ for ( i = 0 ; i < NUM_SEGMENTS ; i++ ) {
+ segment[i].imageUsed = (segment[i].imageUsed + 3) & ~3;
+ }
+ }
+
+ // reserve the stack in bss
+ DefineSymbol( "_stackStart", segment[BSSSEG].imageUsed );
+ segment[BSSSEG].imageUsed += stackSize;
+ DefineSymbol( "_stackEnd", segment[BSSSEG].imageUsed );
+
+ // write the image
+ WriteVmFile();
+
+ // write the map file even if there were errors
+ WriteMapFile();
+}
+
+
+/*
+=============
+ParseOptionFile
+
+=============
+*/
+void ParseOptionFile( const char *filename ) {
+ char expanded[MAX_OS_PATH];
+ char *text, *text_p;
+
+ strcpy( expanded, filename );
+ DefaultExtension( expanded, ".q3asm" );
+ LoadFile( expanded, (void **)&text );
+ if ( !text ) {
+ return;
+ }
+
+ text_p = text;
+
+ while( ( text_p = COM_Parse( text_p ) ) != 0 ) {
+ if ( !strcmp( com_token, "-o" ) ) {
+ // allow output override in option file
+ text_p = COM_Parse( text_p );
+ if ( text_p ) {
+ strcpy( outputFilename, com_token );
+ }
+ continue;
+ }
+
+ asmFileNames[ numAsmFiles ] = copystring( com_token );
+ numAsmFiles++;
+ }
+}
+
+/*
+==============
+main
+==============
+*/
+int main( int argc, char **argv ) {
+ int i;
+ double start, end;
+
+// _chdir( "/quake3/jccode/cgame/lccout" ); // hack for vc profiler
+
+ if ( argc < 2 ) {
+ Error( "usage: q3asm [-o output] <files> or q3asm -f <listfile>\n" );
+ }
+
+ start = I_FloatTime ();
+ InitTables();
+
+ // default filename is "q3asm"
+ strcpy( outputFilename, "q3asm" );
+ numAsmFiles = 0;
+
+ for ( i = 1 ; i < argc ; i++ ) {
+ if ( argv[i][0] != '-' ) {
+ break;
+ }
+ if ( !strcmp( argv[i], "-o" ) ) {
+ if ( i == argc - 1 ) {
+ Error( "-o must preceed a filename" );
+ }
+ strcpy( outputFilename, argv[ i+1 ] );
+ i++;
+ continue;
+ }
+
+ if ( !strcmp( argv[i], "-f" ) ) {
+ if ( i == argc - 1 ) {
+ Error( "-f must preceed a filename" );
+ }
+ ParseOptionFile( argv[ i+1 ] );
+ i++;
+ continue;
+ }
+ Error( "Unknown option: %s", argv[i] );
+ }
+
+ // the rest of the command line args are asm files
+ for ( ; i < argc ; i++ ) {
+ asmFileNames[ numAsmFiles ] = copystring( argv[ i ] );
+ numAsmFiles++;
+ }
+
+ Assemble();
+
+ end = I_FloatTime ();
+ printf ("%5.0f seconds elapsed\n", end-start);
+
+ return 0;
+}
+
diff --git a/q3asm/q3asm.sln b/q3asm/q3asm.sln
new file mode 100755
index 0000000..5f44a09
--- /dev/null
+++ b/q3asm/q3asm.sln
@@ -0,0 +1,28 @@
+Microsoft Visual Studio Solution File, Format Version 8.00
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "q3asm", "q3asm.vcproj", "{E0D6B319-6F95-4ABA-9BE0-5454CAA5C8CD}"
+ ProjectSection(ProjectDependencies) = postProject
+ EndProjectSection
+EndProject
+Global
+ GlobalSection(SourceCodeControl) = preSolution
+ SccNumberOfProjects = 1
+ SccProjectUniqueName0 = q3asm.vcproj
+ SccProjectName0 = \u0022$/source/q3asm\u0022,\u0020YUCAAAAA
+ SccLocalPath0 = .
+ SccProvider0 = MSSCCI:Perforce\u0020SCM
+ EndGlobalSection
+ GlobalSection(SolutionConfiguration) = preSolution
+ Debug = Debug
+ Release = Release
+ EndGlobalSection
+ GlobalSection(ProjectConfiguration) = postSolution
+ {E0D6B319-6F95-4ABA-9BE0-5454CAA5C8CD}.Debug.ActiveCfg = Debug|Win32
+ {E0D6B319-6F95-4ABA-9BE0-5454CAA5C8CD}.Debug.Build.0 = Debug|Win32
+ {E0D6B319-6F95-4ABA-9BE0-5454CAA5C8CD}.Release.ActiveCfg = Release|Win32
+ {E0D6B319-6F95-4ABA-9BE0-5454CAA5C8CD}.Release.Build.0 = Release|Win32
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ EndGlobalSection
+ GlobalSection(ExtensibilityAddIns) = postSolution
+ EndGlobalSection
+EndGlobal
diff --git a/q3asm/q3asm.vcproj b/q3asm/q3asm.vcproj
new file mode 100755
index 0000000..49266b4
--- /dev/null
+++ b/q3asm/q3asm.vcproj
@@ -0,0 +1,195 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+ ProjectType="Visual C++"
+ Version="7.10"
+ Name="q3asm"
+ SccProjectName="&quot;$/source/q3asm&quot;, YUCAAAAA"
+ SccLocalPath=".">
+ <Platforms>
+ <Platform
+ Name="Win32"/>
+ </Platforms>
+ <Configurations>
+ <Configuration
+ Name="Release|Win32"
+ OutputDirectory=".\Release"
+ IntermediateDirectory=".\Release"
+ ConfigurationType="1"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ AdditionalIncludeDirectories="../common"
+ PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
+ StringPooling="TRUE"
+ RuntimeLibrary="4"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Release/q3asm.pch"
+ AssemblerListingLocation=".\Release/"
+ ObjectFile=".\Release/"
+ ProgramDataBaseFileName=".\Release/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ CompileAs="0"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ OutputFile=".\Release/q3asm.exe"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ ProgramDatabaseFile=".\Release/q3asm.pdb"
+ SubSystem="1"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ TypeLibraryName=".\Release/q3asm.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Debug|Win32"
+ OutputDirectory=".\Debug"
+ IntermediateDirectory=".\Debug"
+ ConfigurationType="1"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories="../common"
+ PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
+ BasicRuntimeChecks="3"
+ RuntimeLibrary="5"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Debug/q3asm.pch"
+ AssemblerListingLocation=".\Debug/"
+ ObjectFile=".\Debug/"
+ ProgramDataBaseFileName=".\Debug/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"
+ CompileAs="0"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ OutputFile=".\Debug/q3asm.exe"
+ LinkIncremental="2"
+ SuppressStartupBanner="TRUE"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile=".\Debug/q3asm.pdb"
+ SubSystem="1"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ TypeLibraryName=".\Debug/q3asm.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ </Configurations>
+ <References>
+ </References>
+ <Files>
+ <Filter
+ Name="Source Files"
+ Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat">
+ <File
+ RelativePath="cmdlib.c">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="q3asm.c">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <Filter
+ Name="Header Files"
+ Filter="h;hpp;hxx;hm;inl">
+ <File
+ RelativePath="..\common\cmdlib.h">
+ </File>
+ </Filter>
+ <Filter
+ Name="Resource Files"
+ Filter="ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe">
+ </Filter>
+ </Files>
+ <Globals>
+ </Globals>
+</VisualStudioProject>
diff --git a/q3asm/qfiles.h b/q3asm/qfiles.h
new file mode 100755
index 0000000..9515acf
--- /dev/null
+++ b/q3asm/qfiles.h
@@ -0,0 +1,485 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __QFILES_H__
+#define __QFILES_H__
+
+//
+// qfiles.h: quake file formats
+// This file must be identical in the quake and utils directories
+//
+
+// surface geometry should not exceed these limits
+#define SHADER_MAX_VERTEXES 1000
+#define SHADER_MAX_INDEXES (6*SHADER_MAX_VERTEXES)
+
+
+// the maximum size of game reletive pathnames
+#define MAX_QPATH 64
+
+/*
+========================================================================
+
+QVM files
+
+========================================================================
+*/
+
+#define VM_MAGIC 0x12721444
+typedef struct {
+ int vmMagic;
+
+ int instructionCount;
+
+ int codeOffset;
+ int codeLength;
+
+ int dataOffset;
+ int dataLength;
+ int litLength; // ( dataLength - litLength ) should be byteswapped on load
+ int bssLength; // zero filled memory appended to datalength
+} vmHeader_t;
+
+
+/*
+========================================================================
+
+PCX files are used for 8 bit images
+
+========================================================================
+*/
+
+typedef struct {
+ char manufacturer;
+ char version;
+ char encoding;
+ char bits_per_pixel;
+ unsigned short xmin,ymin,xmax,ymax;
+ unsigned short hres,vres;
+ unsigned char palette[48];
+ char reserved;
+ char color_planes;
+ unsigned short bytes_per_line;
+ unsigned short palette_type;
+ char filler[58];
+ unsigned char data; // unbounded
+} pcx_t;
+
+
+/*
+========================================================================
+
+TGA files are used for 24/32 bit images
+
+========================================================================
+*/
+
+typedef struct _TargaHeader {
+ unsigned char id_length, colormap_type, image_type;
+ unsigned short colormap_index, colormap_length;
+ unsigned char colormap_size;
+ unsigned short x_origin, y_origin, width, height;
+ unsigned char pixel_size, attributes;
+} TargaHeader;
+
+
+
+/*
+========================================================================
+
+.MD3 triangle model file format
+
+========================================================================
+*/
+
+#define MD3_IDENT (('3'<<24)+('P'<<16)+('D'<<8)+'I')
+#define MD3_VERSION 15
+
+// limits
+#define MD3_MAX_LODS 3
+#define MD3_MAX_TRIANGLES 8192 // per surface
+#define MD3_MAX_VERTS 4096 // per surface
+#define MD3_MAX_SHADERS 256 // per surface
+#define MD3_MAX_FRAMES 1024 // per model
+#define MD3_MAX_SURFACES 32 // per model
+#define MD3_MAX_TAGS 16 // per frame
+
+// vertex scales
+#define MD3_XYZ_SCALE (1.0/64)
+
+typedef struct md3Frame_s {
+ vec3_t bounds[2];
+ vec3_t localOrigin;
+ float radius;
+ char name[16];
+} md3Frame_t;
+
+typedef struct md3Tag_s {
+ char name[MAX_QPATH]; // tag name
+ vec3_t origin;
+ vec3_t axis[3];
+} md3Tag_t;
+
+/*
+** md3Surface_t
+**
+** CHUNK SIZE
+** header sizeof( md3Surface_t )
+** shaders sizeof( md3Shader_t ) * numShaders
+** triangles[0] sizeof( md3Triangle_t ) * numTriangles
+** st sizeof( md3St_t ) * numVerts
+** XyzNormals sizeof( md3XyzNormal_t ) * numVerts * numFrames
+*/
+typedef struct {
+ int ident; //
+
+ char name[MAX_QPATH]; // polyset name
+
+ int flags;
+ int numFrames; // all surfaces in a model should have the same
+
+ int numShaders; // all surfaces in a model should have the same
+ int numVerts;
+
+ int numTriangles;
+ int ofsTriangles;
+
+ int ofsShaders; // offset from start of md3Surface_t
+ int ofsSt; // texture coords are common for all frames
+ int ofsXyzNormals; // numVerts * numFrames
+
+ int ofsEnd; // next surface follows
+} md3Surface_t;
+
+typedef struct {
+ char name[MAX_QPATH];
+ int shaderIndex; // for in-game use
+} md3Shader_t;
+
+typedef struct {
+ int indexes[3];
+} md3Triangle_t;
+
+typedef struct {
+ float st[2];
+} md3St_t;
+
+typedef struct {
+ short xyz[3];
+ short normal;
+} md3XyzNormal_t;
+
+typedef struct {
+ int ident;
+ int version;
+
+ char name[MAX_QPATH]; // model name
+
+ int flags;
+
+ int numFrames;
+ int numTags;
+ int numSurfaces;
+
+ int numSkins;
+
+ int ofsFrames; // offset for first frame
+ int ofsTags; // numFrames * numTags
+ int ofsSurfaces; // first surface, others follow
+
+ int ofsEnd; // end of file
+} md3Header_t;
+
+/*
+==============================================================================
+
+MD4 file format
+
+==============================================================================
+*/
+
+#define MD4_IDENT (('4'<<24)+('P'<<16)+('D'<<8)+'I')
+#define MD4_VERSION 1
+#define MD4_MAX_BONES 128
+
+typedef struct {
+ int boneIndex; // these are indexes into the boneReferences,
+ float boneWeight; // not the global per-frame bone list
+ vec3_t offset;
+} md4Weight_t;
+
+typedef struct {
+ vec3_t normal;
+ vec2_t texCoords;
+ int numWeights;
+ md4Weight_t weights[1]; // variable sized
+} md4Vertex_t;
+
+typedef struct {
+ int indexes[3];
+} md4Triangle_t;
+
+typedef struct {
+ int ident;
+
+ char name[MAX_QPATH]; // polyset name
+ char shader[MAX_QPATH];
+ int shaderIndex; // for in-game use
+
+ int ofsHeader; // this will be a negative number
+
+ int numVerts;
+ int ofsVerts;
+
+ int numTriangles;
+ int ofsTriangles;
+
+ // Bone references are a set of ints representing all the bones
+ // present in any vertex weights for this surface. This is
+ // needed because a model may have surfaces that need to be
+ // drawn at different sort times, and we don't want to have
+ // to re-interpolate all the bones for each surface.
+ int numBoneReferences;
+ int ofsBoneReferences;
+
+ int ofsEnd; // next surface follows
+} md4Surface_t;
+
+typedef struct {
+ float matrix[3][4];
+} md4Bone_t;
+
+typedef struct {
+ vec3_t bounds[2]; // bounds of all surfaces of all LOD's for this frame
+ vec3_t localOrigin; // midpoint of bounds, used for sphere cull
+ float radius; // dist from localOrigin to corner
+ char name[16];
+ md4Bone_t bones[1]; // [numBones]
+} md4Frame_t;
+
+typedef struct {
+ int numSurfaces;
+ int ofsSurfaces; // first surface, others follow
+ int ofsEnd; // next lod follows
+} md4LOD_t;
+
+typedef struct {
+ int ident;
+ int version;
+
+ char name[MAX_QPATH]; // model name
+
+ // frames and bones are shared by all levels of detail
+ int numFrames;
+ int numBones;
+ int ofsFrames; // md4Frame_t[numFrames]
+
+ // each level of detail has completely separate sets of surfaces
+ int numLODs;
+ int ofsLODs;
+
+ int ofsEnd; // end of file
+} md4Header_t;
+
+
+/*
+==============================================================================
+
+ .BSP file format
+
+==============================================================================
+*/
+
+
+#define BSP_IDENT (('P'<<24)+('S'<<16)+('B'<<8)+'I')
+ // little-endian "IBSP"
+
+#define BSP_VERSION 46
+
+
+// there shouldn't be any problem with increasing these values at the
+// expense of more memory allocation in the utilities
+#define MAX_MAP_MODELS 0x400
+#define MAX_MAP_BRUSHES 0x8000
+#define MAX_MAP_ENTITIES 0x800
+#define MAX_MAP_ENTSTRING 0x40000
+#define MAX_MAP_SHADERS 0x400
+
+#define MAX_MAP_AREAS 0x100 // MAX_MAP_AREA_BYTES in q_shared must match!
+#define MAX_MAP_FOGS 0x100
+#define MAX_MAP_PLANES 0x20000
+#define MAX_MAP_NODES 0x20000
+#define MAX_MAP_BRUSHSIDES 0x20000
+#define MAX_MAP_LEAFS 0x20000
+#define MAX_MAP_LEAFFACES 0x20000
+#define MAX_MAP_LEAFBRUSHES 0x40000
+#define MAX_MAP_PORTALS 0x20000
+#define MAX_MAP_LIGHTING 0x800000
+#define MAX_MAP_LIGHTGRID 0x800000
+#define MAX_MAP_VISIBILITY 0x200000
+
+#define MAX_MAP_DRAW_SURFS 0x20000
+#define MAX_MAP_DRAW_VERTS 0x80000
+#define MAX_MAP_DRAW_INDEXES 0x80000
+
+
+// key / value pair sizes in the entities lump
+#define MAX_KEY 32
+#define MAX_VALUE 1024
+
+// the editor uses these predefined yaw angles to orient entities up or down
+#define ANGLE_UP -1
+#define ANGLE_DOWN -2
+
+#define LIGHTMAP_WIDTH 128
+#define LIGHTMAP_HEIGHT 128
+
+
+//=============================================================================
+
+
+typedef struct {
+ int fileofs, filelen;
+} lump_t;
+
+#define LUMP_ENTITIES 0
+#define LUMP_SHADERS 1
+#define LUMP_PLANES 2
+#define LUMP_NODES 3
+#define LUMP_LEAFS 4
+#define LUMP_LEAFSURFACES 5
+#define LUMP_LEAFBRUSHES 6
+#define LUMP_MODELS 7
+#define LUMP_BRUSHES 8
+#define LUMP_BRUSHSIDES 9
+#define LUMP_DRAWVERTS 10
+#define LUMP_DRAWINDEXES 11
+#define LUMP_FOGS 12
+#define LUMP_SURFACES 13
+#define LUMP_LIGHTMAPS 14
+#define LUMP_LIGHTGRID 15
+#define LUMP_VISIBILITY 16
+#define HEADER_LUMPS 17
+
+typedef struct {
+ int ident;
+ int version;
+
+ lump_t lumps[HEADER_LUMPS];
+} dheader_t;
+
+typedef struct {
+ float mins[3], maxs[3];
+ int firstSurface, numSurfaces;
+ int firstBrush, numBrushes;
+} dmodel_t;
+
+typedef struct {
+ char shader[MAX_QPATH];
+ int surfaceFlags;
+ int contentFlags;
+} dshader_t;
+
+// planes x^1 is allways the opposite of plane x
+
+typedef struct {
+ float normal[3];
+ float dist;
+} dplane_t;
+
+typedef struct {
+ int planeNum;
+ int children[2]; // negative numbers are -(leafs+1), not nodes
+ int mins[3]; // for frustom culling
+ int maxs[3];
+} dnode_t;
+
+typedef struct {
+ int cluster; // -1 = opaque cluster (do I still store these?)
+ int area;
+
+ int mins[3]; // for frustum culling
+ int maxs[3];
+
+ int firstLeafSurface;
+ int numLeafSurfaces;
+
+ int firstLeafBrush;
+ int numLeafBrushes;
+} dleaf_t;
+
+typedef struct {
+ int planeNum; // positive plane side faces out of the leaf
+ int shaderNum;
+} dbrushside_t;
+
+typedef struct {
+ int firstSide;
+ int numSides;
+ int shaderNum; // the shader that determines the contents flags
+} dbrush_t;
+
+typedef struct {
+ char shader[MAX_QPATH];
+ int brushNum;
+ int visibleSide; // the brush side that ray tests need to clip against (-1 == none)
+} dfog_t;
+
+typedef struct {
+ vec3_t xyz;
+ float st[2];
+ float lightmap[2];
+ vec3_t normal;
+ byte color[4];
+} drawVert_t;
+
+typedef enum {
+ MST_BAD,
+ MST_PLANAR,
+ MST_PATCH,
+ MST_TRIANGLE_SOUP,
+ MST_FLARE
+} mapSurfaceType_t;
+
+typedef struct {
+ int shaderNum;
+ int fogNum;
+ int surfaceType;
+
+ int firstVert;
+ int numVerts;
+
+ int firstIndex;
+ int numIndexes;
+
+ int lightmapNum;
+ int lightmapX, lightmapY;
+ int lightmapWidth, lightmapHeight;
+
+ vec3_t lightmapOrigin;
+ vec3_t lightmapVecs[3]; // for patches, [0] and [1] are lodbounds
+
+ int patchWidth;
+ int patchHeight;
+} dsurface_t;
+
+
+#endif
diff --git a/q3map/brush.c b/q3map/brush.c
new file mode 100755
index 0000000..e373e17
--- /dev/null
+++ b/q3map/brush.c
@@ -0,0 +1,861 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "qbsp.h"
+
+
+int c_active_brushes;
+
+int c_nodes;
+
+// if a brush just barely pokes onto the other side,
+// let it slide by without chopping
+#define PLANESIDE_EPSILON 0.001
+//0.1
+
+
+
+
+/*
+================
+CountBrushList
+================
+*/
+int CountBrushList (bspbrush_t *brushes)
+{
+ int c;
+
+ c = 0;
+ for ( ; brushes ; brushes = brushes->next)
+ c++;
+ return c;
+}
+
+
+/*
+================
+AllocBrush
+================
+*/
+bspbrush_t *AllocBrush (int numsides)
+{
+ bspbrush_t *bb;
+ int c;
+
+ c = (int)&(((bspbrush_t *)0)->sides[numsides]);
+ bb = malloc(c);
+ memset (bb, 0, c);
+ if (numthreads == 1)
+ c_active_brushes++;
+ return bb;
+}
+
+/*
+================
+FreeBrush
+================
+*/
+void FreeBrush (bspbrush_t *brushes)
+{
+ int i;
+
+ for (i=0 ; i<brushes->numsides ; i++)
+ if (brushes->sides[i].winding)
+ FreeWinding(brushes->sides[i].winding);
+ free (brushes);
+ if (numthreads == 1)
+ c_active_brushes--;
+}
+
+
+/*
+================
+FreeBrushList
+================
+*/
+void FreeBrushList (bspbrush_t *brushes)
+{
+ bspbrush_t *next;
+
+ for ( ; brushes ; brushes = next)
+ {
+ next = brushes->next;
+
+ FreeBrush (brushes);
+ }
+}
+
+/*
+==================
+CopyBrush
+
+Duplicates the brush, the sides, and the windings
+==================
+*/
+bspbrush_t *CopyBrush (bspbrush_t *brush)
+{
+ bspbrush_t *newbrush;
+ int size;
+ int i;
+
+ size = (int)&(((bspbrush_t *)0)->sides[brush->numsides]);
+
+ newbrush = AllocBrush (brush->numsides);
+ memcpy (newbrush, brush, size);
+
+ for (i=0 ; i<brush->numsides ; i++)
+ {
+ if (brush->sides[i].winding)
+ newbrush->sides[i].winding = CopyWinding (brush->sides[i].winding);
+ }
+
+ return newbrush;
+}
+
+
+/*
+================
+DrawBrushList
+================
+*/
+void DrawBrushList (bspbrush_t *brush)
+{
+ int i;
+ side_t *s;
+
+ GLS_BeginScene ();
+ for ( ; brush ; brush=brush->next)
+ {
+ for (i=0 ; i<brush->numsides ; i++)
+ {
+ s = &brush->sides[i];
+ if (!s->winding)
+ continue;
+ GLS_Winding (s->winding, 0);
+ }
+ }
+ GLS_EndScene ();
+}
+
+
+
+/*
+================
+WriteBrushList
+================
+*/
+void WriteBrushList (char *name, bspbrush_t *brush, qboolean onlyvis)
+{
+ int i;
+ side_t *s;
+ FILE *f;
+
+ qprintf ("writing %s\n", name);
+ f = SafeOpenWrite (name);
+
+ for ( ; brush ; brush=brush->next)
+ {
+ for (i=0 ; i<brush->numsides ; i++)
+ {
+ s = &brush->sides[i];
+ if (!s->winding)
+ continue;
+ if (onlyvis && !s->visible)
+ continue;
+ OutputWinding (brush->sides[i].winding, f);
+ }
+ }
+
+ fclose (f);
+}
+
+
+/*
+=============
+PrintBrush
+=============
+*/
+void PrintBrush (bspbrush_t *brush)
+{
+ int i;
+
+ _printf ("brush: %p\n", brush);
+ for (i=0;i<brush->numsides ; i++)
+ {
+ pw(brush->sides[i].winding);
+ _printf ("\n");
+ }
+}
+
+/*
+==================
+BoundBrush
+
+Sets the mins/maxs based on the windings
+returns false if the brush doesn't enclose a valid volume
+==================
+*/
+qboolean BoundBrush (bspbrush_t *brush)
+{
+ int i, j;
+ winding_t *w;
+
+ ClearBounds (brush->mins, brush->maxs);
+ for (i=0 ; i<brush->numsides ; i++)
+ {
+ w = brush->sides[i].winding;
+ if (!w)
+ continue;
+ for (j=0 ; j<w->numpoints ; j++)
+ AddPointToBounds (w->p[j], brush->mins, brush->maxs);
+ }
+
+ for (i=0 ; i<3 ; i++) {
+ if (brush->mins[i] < MIN_WORLD_COORD || brush->maxs[i] > MAX_WORLD_COORD
+ || brush->mins[i] >= brush->maxs[i] ) {
+ return qfalse;
+ }
+ }
+
+ return qtrue;
+}
+
+/*
+==================
+CreateBrushWindings
+
+makes basewindigs for sides and mins / maxs for the brush
+returns false if the brush doesn't enclose a valid volume
+==================
+*/
+qboolean CreateBrushWindings (bspbrush_t *brush)
+{
+ int i, j;
+ winding_t *w;
+ side_t *side;
+ plane_t *plane;
+
+ for ( i = 0; i < brush->numsides; i++ )
+ {
+ side = &brush->sides[i];
+ // don't create a winding for a bevel
+ if ( side->bevel ) {
+ continue;
+ }
+ plane = &mapplanes[side->planenum];
+ w = BaseWindingForPlane (plane->normal, plane->dist);
+ for ( j = 0; j < brush->numsides && w; j++ )
+ {
+ if (i == j)
+ continue;
+ if ( brush->sides[j].planenum == ( brush->sides[i].planenum ^ 1 ) )
+ continue; // back side clipaway
+ if (brush->sides[j].bevel)
+ continue;
+ if (brush->sides[j].backSide)
+ continue;
+ plane = &mapplanes[brush->sides[j].planenum^1];
+ ChopWindingInPlace (&w, plane->normal, plane->dist, 0); //CLIP_EPSILON);
+ }
+ // free any existing winding
+ if ( side->winding ) {
+ FreeWinding( side->winding );
+ }
+ side->winding = w;
+ }
+
+ return BoundBrush (brush);
+}
+
+/*
+==================
+BrushFromBounds
+
+Creates a new axial brush
+==================
+*/
+bspbrush_t *BrushFromBounds (vec3_t mins, vec3_t maxs)
+{
+ bspbrush_t *b;
+ int i;
+ vec3_t normal;
+ vec_t dist;
+
+ b = AllocBrush (6);
+ b->numsides = 6;
+ for (i=0 ; i<3 ; i++)
+ {
+ VectorClear (normal);
+ normal[i] = 1;
+ dist = maxs[i];
+ b->sides[i].planenum = FindFloatPlane (normal, dist);
+
+ normal[i] = -1;
+ dist = -mins[i];
+ b->sides[3+i].planenum = FindFloatPlane (normal, dist);
+ }
+
+ CreateBrushWindings (b);
+
+ return b;
+}
+
+/*
+==================
+BrushVolume
+
+==================
+*/
+vec_t BrushVolume (bspbrush_t *brush)
+{
+ int i;
+ winding_t *w;
+ vec3_t corner;
+ vec_t d, area, volume;
+ plane_t *plane;
+
+ if (!brush)
+ return 0;
+
+ // grab the first valid point as the corner
+
+ w = NULL;
+ for (i=0 ; i<brush->numsides ; i++)
+ {
+ w = brush->sides[i].winding;
+ if (w)
+ break;
+ }
+ if (!w)
+ return 0;
+ VectorCopy (w->p[0], corner);
+
+ // make tetrahedrons to all other faces
+
+ volume = 0;
+ for ( ; i<brush->numsides ; i++)
+ {
+ w = brush->sides[i].winding;
+ if (!w)
+ continue;
+ plane = &mapplanes[brush->sides[i].planenum];
+ d = -(DotProduct (corner, plane->normal) - plane->dist);
+ area = WindingArea (w);
+ volume += d*area;
+ }
+
+ volume /= 3;
+ return volume;
+}
+
+
+/*
+==================
+WriteBspBrushMap
+==================
+*/
+void WriteBspBrushMap (char *name, bspbrush_t *list)
+{
+ FILE *f;
+ side_t *s;
+ int i;
+ winding_t *w;
+
+ _printf ("writing %s\n", name);
+ f = fopen (name, "wb");
+ if (!f)
+ Error ("Can't write %s\b", name);
+
+ fprintf (f, "{\n\"classname\" \"worldspawn\"\n");
+
+ for ( ; list ; list=list->next )
+ {
+ fprintf (f, "{\n");
+ for (i=0,s=list->sides ; i<list->numsides ; i++,s++)
+ {
+ w = BaseWindingForPlane (mapplanes[s->planenum].normal, mapplanes[s->planenum].dist);
+
+ fprintf (f,"( %i %i %i ) ", (int)w->p[0][0], (int)w->p[0][1], (int)w->p[0][2]);
+ fprintf (f,"( %i %i %i ) ", (int)w->p[1][0], (int)w->p[1][1], (int)w->p[1][2]);
+ fprintf (f,"( %i %i %i ) ", (int)w->p[2][0], (int)w->p[2][1], (int)w->p[2][2]);
+
+ fprintf (f, "notexture 0 0 0 1 1\n" );
+ FreeWinding (w);
+ }
+ fprintf (f, "}\n");
+ }
+ fprintf (f, "}\n");
+
+ fclose (f);
+
+}
+
+
+//=====================================================================================
+
+/*
+====================
+FilterBrushIntoTree_r
+
+====================
+*/
+int FilterBrushIntoTree_r( bspbrush_t *b, node_t *node ) {
+ bspbrush_t *front, *back;
+ int c;
+
+ if ( !b ) {
+ return 0;
+ }
+
+ // add it to the leaf list
+ if ( node->planenum == PLANENUM_LEAF ) {
+ b->next = node->brushlist;
+ node->brushlist = b;
+
+ // classify the leaf by the structural brush
+ if ( !b->detail ) {
+ if ( b->opaque ) {
+ node->opaque = qtrue;
+ node->areaportal = qfalse;
+ } else if ( b->contents & CONTENTS_AREAPORTAL ) {
+ if ( !node->opaque ) {
+ node->areaportal = qtrue;
+ }
+ }
+ }
+
+ return 1;
+ }
+
+ // split it by the node plane
+ SplitBrush ( b, node->planenum, &front, &back );
+ FreeBrush( b );
+
+ c = 0;
+ c += FilterBrushIntoTree_r( front, node->children[0] );
+ c += FilterBrushIntoTree_r( back, node->children[1] );
+
+ return c;
+}
+
+/*
+=====================
+FilterDetailBrushesIntoTree
+
+Fragment all the detail brushes into the structural leafs
+=====================
+*/
+void FilterDetailBrushesIntoTree( entity_t *e, tree_t *tree ) {
+ bspbrush_t *b, *newb;
+ int r;
+ int c_unique, c_clusters;
+ int i;
+
+ qprintf( "----- FilterDetailBrushesIntoTree -----\n");
+
+ c_unique = 0;
+ c_clusters = 0;
+ for ( b = e->brushes ; b ; b = b->next ) {
+ if ( !b->detail ) {
+ continue;
+ }
+ c_unique++;
+ newb = CopyBrush( b );
+ r = FilterBrushIntoTree_r( newb, tree->headnode );
+ c_clusters += r;
+
+ // mark all sides as visible so drawsurfs are created
+ if ( r ) {
+ for ( i = 0 ; i < b->numsides ; i++ ) {
+ if ( b->sides[i].winding ) {
+ b->sides[i].visible = qtrue;
+ }
+ }
+ }
+ }
+
+ qprintf( "%5i detail brushes\n", c_unique );
+ qprintf( "%5i cluster references\n", c_clusters );
+}
+
+/*
+=====================
+FilterStructuralBrushesIntoTree
+
+Mark the leafs as opaque and areaportals
+=====================
+*/
+void FilterStructuralBrushesIntoTree( entity_t *e, tree_t *tree ) {
+ bspbrush_t *b, *newb;
+ int r;
+ int c_unique, c_clusters;
+ int i;
+
+ qprintf( "----- FilterStructuralBrushesIntoTree -----\n");
+
+ c_unique = 0;
+ c_clusters = 0;
+ for ( b = e->brushes ; b ; b = b->next ) {
+ if ( b->detail ) {
+ continue;
+ }
+ c_unique++;
+ newb = CopyBrush( b );
+ r = FilterBrushIntoTree_r( newb, tree->headnode );
+ c_clusters += r;
+
+ // mark all sides as visible so drawsurfs are created
+ if ( r ) {
+ for ( i = 0 ; i < b->numsides ; i++ ) {
+ if ( b->sides[i].winding ) {
+ b->sides[i].visible = qtrue;
+ }
+ }
+ }
+ }
+
+ qprintf( "%5i structural brushes\n", c_unique );
+ qprintf( "%5i cluster references\n", c_clusters );
+}
+
+
+
+/*
+================
+AllocTree
+================
+*/
+tree_t *AllocTree (void)
+{
+ tree_t *tree;
+
+ tree = malloc(sizeof(*tree));
+ memset (tree, 0, sizeof(*tree));
+ ClearBounds (tree->mins, tree->maxs);
+
+ return tree;
+}
+
+/*
+================
+AllocNode
+================
+*/
+node_t *AllocNode (void)
+{
+ node_t *node;
+
+ node = malloc(sizeof(*node));
+ memset (node, 0, sizeof(*node));
+
+ return node;
+}
+
+
+/*
+================
+WindingIsTiny
+
+Returns true if the winding would be crunched out of
+existance by the vertex snapping.
+================
+*/
+#define EDGE_LENGTH 0.2
+qboolean WindingIsTiny (winding_t *w)
+{
+/*
+ if (WindingArea (w) < 1)
+ return qtrue;
+ return qfalse;
+*/
+ int i, j;
+ vec_t len;
+ vec3_t delta;
+ int edges;
+
+ edges = 0;
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ j = i == w->numpoints - 1 ? 0 : i+1;
+ VectorSubtract (w->p[j], w->p[i], delta);
+ len = VectorLength (delta);
+ if (len > EDGE_LENGTH)
+ {
+ if (++edges == 3)
+ return qfalse;
+ }
+ }
+ return qtrue;
+}
+
+/*
+================
+WindingIsHuge
+
+Returns true if the winding still has one of the points
+from basewinding for plane
+================
+*/
+qboolean WindingIsHuge (winding_t *w)
+{
+ int i, j;
+
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ for (j=0 ; j<3 ; j++)
+ if (w->p[i][j] <= MIN_WORLD_COORD || w->p[i][j] >= MAX_WORLD_COORD)
+ return qtrue;
+ }
+ return qfalse;
+}
+
+//============================================================
+
+/*
+==================
+BrushMostlyOnSide
+
+==================
+*/
+int BrushMostlyOnSide (bspbrush_t *brush, plane_t *plane)
+{
+ int i, j;
+ winding_t *w;
+ vec_t d, max;
+ int side;
+
+ max = 0;
+ side = PSIDE_FRONT;
+ for (i=0 ; i<brush->numsides ; i++)
+ {
+ w = brush->sides[i].winding;
+ if (!w)
+ continue;
+ for (j=0 ; j<w->numpoints ; j++)
+ {
+ d = DotProduct (w->p[j], plane->normal) - plane->dist;
+ if (d > max)
+ {
+ max = d;
+ side = PSIDE_FRONT;
+ }
+ if (-d > max)
+ {
+ max = -d;
+ side = PSIDE_BACK;
+ }
+ }
+ }
+ return side;
+}
+
+/*
+================
+SplitBrush
+
+Generates two new brushes, leaving the original
+unchanged
+================
+*/
+void SplitBrush (bspbrush_t *brush, int planenum,
+ bspbrush_t **front, bspbrush_t **back)
+{
+ bspbrush_t *b[2];
+ int i, j;
+ winding_t *w, *cw[2], *midwinding;
+ plane_t *plane, *plane2;
+ side_t *s, *cs;
+ float d, d_front, d_back;
+
+ *front = *back = NULL;
+ plane = &mapplanes[planenum];
+
+ // check all points
+ d_front = d_back = 0;
+ for (i=0 ; i<brush->numsides ; i++)
+ {
+ w = brush->sides[i].winding;
+ if (!w)
+ continue;
+ for (j=0 ; j<w->numpoints ; j++)
+ {
+ d = DotProduct (w->p[j], plane->normal) - plane->dist;
+ if (d > 0 && d > d_front)
+ d_front = d;
+ if (d < 0 && d < d_back)
+ d_back = d;
+ }
+ }
+ if (d_front < 0.1) // PLANESIDE_EPSILON)
+ { // only on back
+ *back = CopyBrush (brush);
+ return;
+ }
+ if (d_back > -0.1) // PLANESIDE_EPSILON)
+ { // only on front
+ *front = CopyBrush (brush);
+ return;
+ }
+
+ // create a new winding from the split plane
+
+ w = BaseWindingForPlane (plane->normal, plane->dist);
+ for (i=0 ; i<brush->numsides && w ; i++)
+ {
+ if ( brush->sides[i].backSide ) {
+ continue; // fake back-sided polygons never split
+ }
+ plane2 = &mapplanes[brush->sides[i].planenum ^ 1];
+ ChopWindingInPlace (&w, plane2->normal, plane2->dist, 0); // PLANESIDE_EPSILON);
+ }
+
+ if (!w || WindingIsTiny (w) )
+ { // the brush isn't really split
+ int side;
+
+ side = BrushMostlyOnSide (brush, plane);
+ if (side == PSIDE_FRONT)
+ *front = CopyBrush (brush);
+ if (side == PSIDE_BACK)
+ *back = CopyBrush (brush);
+ return;
+ }
+
+ if (WindingIsHuge (w))
+ {
+ qprintf ("WARNING: huge winding\n");
+ }
+
+ midwinding = w;
+
+ // split it for real
+
+ for (i=0 ; i<2 ; i++)
+ {
+ b[i] = AllocBrush (brush->numsides+1);
+ memcpy( b[i], brush, sizeof( bspbrush_t ) - sizeof( brush->sides ) );
+ b[i]->numsides = 0;
+ b[i]->next = NULL;
+ b[i]->original = brush->original;
+ }
+
+ // split all the current windings
+
+ for (i=0 ; i<brush->numsides ; i++)
+ {
+ s = &brush->sides[i];
+ w = s->winding;
+ if (!w)
+ continue;
+ ClipWindingEpsilon (w, plane->normal, plane->dist,
+ 0 /*PLANESIDE_EPSILON*/, &cw[0], &cw[1]);
+ for (j=0 ; j<2 ; j++)
+ {
+ if (!cw[j])
+ continue;
+/*
+ if (WindingIsTiny (cw[j]))
+ {
+ FreeWinding (cw[j]);
+ continue;
+ }
+*/
+ cs = &b[j]->sides[b[j]->numsides];
+ b[j]->numsides++;
+ *cs = *s;
+ cs->winding = cw[j];
+ }
+ }
+
+
+ // see if we have valid polygons on both sides
+
+ for (i=0 ; i<2 ; i++)
+ {
+ BoundBrush (b[i]);
+ for (j=0 ; j<3 ; j++)
+ {
+ if (b[i]->mins[j] < MIN_WORLD_COORD || b[i]->maxs[j] > MAX_WORLD_COORD)
+ {
+ qprintf ("bogus brush after clip\n");
+ break;
+ }
+ }
+
+ if (b[i]->numsides < 3 || j < 3)
+ {
+ FreeBrush (b[i]);
+ b[i] = NULL;
+ }
+ }
+
+ if ( !(b[0] && b[1]) )
+ {
+ if (!b[0] && !b[1])
+ qprintf ("split removed brush\n");
+ else
+ qprintf ("split not on both sides\n");
+ if (b[0])
+ {
+ FreeBrush (b[0]);
+ *front = CopyBrush (brush);
+ }
+ if (b[1])
+ {
+ FreeBrush (b[1]);
+ *back = CopyBrush (brush);
+ }
+ return;
+ }
+
+ // add the midwinding to both sides
+ for (i=0 ; i<2 ; i++)
+ {
+ cs = &b[i]->sides[b[i]->numsides];
+ b[i]->numsides++;
+
+ cs->planenum = planenum^i^1;
+ cs->shaderInfo = NULL;
+ if (i==0)
+ cs->winding = CopyWinding (midwinding);
+ else
+ cs->winding = midwinding;
+ }
+
+{
+ vec_t v1;
+ int i;
+
+ for (i=0 ; i<2 ; i++)
+ {
+ v1 = BrushVolume (b[i]);
+ if (v1 < 1.0)
+ {
+ FreeBrush (b[i]);
+ b[i] = NULL;
+// qprintf ("tiny volume after clip\n");
+ }
+ }
+}
+
+ *front = b[0];
+ *back = b[1];
+}
diff --git a/q3map/brush_primit.c b/q3map/brush_primit.c
new file mode 100755
index 0000000..5ec44cc
--- /dev/null
+++ b/q3map/brush_primit.c
@@ -0,0 +1,52 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "qbsp.h"
+
+
+// global flag
+int g_bBrushPrimit;
+
+// NOTE : ComputeAxisBase here and in editor code must always BE THE SAME !
+// WARNING : special case behaviour of atan2(y,x) <-> atan(y/x) might not be the same everywhere when x == 0
+// rotation by (0,RotY,RotZ) assigns X to normal
+void ComputeAxisBase(vec3_t normal,vec3_t texX,vec3_t texY)
+{
+ vec_t RotY,RotZ;
+ // do some cleaning
+ if (fabs(normal[0])<1e-6)
+ normal[0]=0.0f;
+ if (fabs(normal[1])<1e-6)
+ normal[1]=0.0f;
+ if (fabs(normal[2])<1e-6)
+ normal[2]=0.0f;
+ // compute the two rotations around Y and Z to rotate X to normal
+ RotY=-atan2(normal[2],sqrt(normal[1]*normal[1]+normal[0]*normal[0]));
+ RotZ=atan2(normal[1],normal[0]);
+ // rotate (0,1,0) and (0,0,1) to compute texX and texY
+ texX[0]=-sin(RotZ);
+ texX[1]=cos(RotZ);
+ texX[2]=0;
+ // the texY vector is along -Z ( T texture coorinates axis )
+ texY[0]=-sin(RotY)*cos(RotZ);
+ texY[1]=-sin(RotY)*sin(RotZ);
+ texY[2]=-cos(RotY);
+}
diff --git a/q3map/bsp.c b/q3map/bsp.c
new file mode 100755
index 0000000..12d66aa
--- /dev/null
+++ b/q3map/bsp.c
@@ -0,0 +1,605 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "qbsp.h"
+
+#ifdef _WIN32
+#ifdef _TTIMOBUILD
+#include "pakstuff.h"
+#else
+#include "../libs/pakstuff.h"
+#endif
+extern HWND hwndOut;
+#endif
+
+char source[1024];
+char tempsource[1024];
+char name[1024];
+
+vec_t microvolume = 1.0;
+qboolean glview;
+qboolean nodetail;
+qboolean fulldetail;
+qboolean onlyents;
+qboolean onlytextures;
+qboolean nowater;
+qboolean nofill;
+qboolean noopt;
+qboolean leaktest;
+qboolean verboseentities;
+qboolean noCurveBrushes;
+qboolean fakemap;
+qboolean notjunc;
+qboolean nomerge;
+qboolean nofog;
+qboolean nosubdivide;
+qboolean testExpand;
+qboolean showseams;
+
+char outbase[32];
+
+int entity_num;
+
+/*
+============
+ProcessWorldModel
+
+============
+*/
+void ProcessWorldModel( void ) {
+ entity_t *e;
+ tree_t *tree;
+ bspface_t *faces;
+ qboolean leaked;
+
+ BeginModel();
+
+ e = &entities[0];
+ e->firstDrawSurf = 0;//numMapDrawSurfs;
+
+ // check for patches with adjacent edges that need to LOD together
+ PatchMapDrawSurfs( e );
+
+ // build an initial bsp tree using all of the sides
+ // of all of the structural brushes
+ faces = MakeStructuralBspFaceList ( entities[0].brushes );
+ tree = FaceBSP( faces );
+ MakeTreePortals (tree);
+ FilterStructuralBrushesIntoTree( e, tree );
+
+ // see if the bsp is completely enclosed
+ if ( FloodEntities (tree) ) {
+ // rebuild a better bsp tree using only the
+ // sides that are visible from the inside
+ FillOutside (tree->headnode);
+
+ // chop the sides to the convex hull of
+ // their visible fragments, giving us the smallest
+ // polygons
+ ClipSidesIntoTree( e, tree );
+
+ faces = MakeVisibleBspFaceList( entities[0].brushes );
+ FreeTree (tree);
+ tree = FaceBSP( faces );
+ MakeTreePortals( tree );
+ FilterStructuralBrushesIntoTree( e, tree );
+ leaked = qfalse;
+ } else {
+ _printf ("**********************\n");
+ _printf ("******* leaked *******\n");
+ _printf ("**********************\n");
+ LeakFile (tree);
+ if ( leaktest ) {
+ _printf ("--- MAP LEAKED, ABORTING LEAKTEST ---\n");
+ exit (0);
+ }
+ leaked = qtrue;
+
+ // chop the sides to the convex hull of
+ // their visible fragments, giving us the smallest
+ // polygons
+ ClipSidesIntoTree( e, tree );
+ }
+
+ // save out information for visibility processing
+ NumberClusters( tree );
+ if ( !leaked ) {
+ WritePortalFile( tree );
+ }
+ if ( glview ) {
+ // dump the portals for debugging
+ WriteGLView( tree, source );
+ }
+ FloodAreas (tree);
+
+ // add references to the detail brushes
+ FilterDetailBrushesIntoTree( e, tree );
+
+ // create drawsurfs for triangle models
+ AddTriangleModels( tree );
+
+ // drawsurfs that cross fog boundaries will need to
+ // be split along the bound
+ if ( !nofog ) {
+ FogDrawSurfs(); // may fragment drawsurfs
+ }
+
+ // subdivide each drawsurf as required by shader tesselation
+ if ( !nosubdivide ) {
+ SubdivideDrawSurfs( e, tree );
+ }
+
+ // merge together all common shaders on the same plane and remove
+ // all colinear points, so extra tjunctions won't be generated
+ if ( !nomerge ) {
+ MergeSides( e, tree ); // !@# testing
+ }
+
+ // add in any vertexes required to fix tjunctions
+ if ( !notjunc ) {
+ FixTJunctions( e );
+ }
+
+ // allocate lightmaps for faces and patches
+ AllocateLightmaps( e );
+
+ // add references to the final drawsurfs in the apropriate clusters
+ FilterDrawsurfsIntoTree( e, tree );
+
+ EndModel( tree->headnode );
+
+ FreeTree (tree);
+}
+
+/*
+============
+ProcessSubModel
+
+============
+*/
+void ProcessSubModel( void ) {
+ entity_t *e;
+ tree_t *tree;
+ bspbrush_t *b, *bc;
+ node_t *node;
+
+ BeginModel ();
+
+ e = &entities[entity_num];
+ e->firstDrawSurf = numMapDrawSurfs;
+
+ PatchMapDrawSurfs( e );
+
+ // just put all the brushes in an empty leaf
+ // FIXME: patches?
+ node = AllocNode();
+ node->planenum = PLANENUM_LEAF;
+ for ( b = e->brushes ; b ; b = b->next ) {
+ bc = CopyBrush( b );
+ bc->next = node->brushlist;
+ node->brushlist = bc;
+ }
+
+ tree = AllocTree();
+ tree->headnode = node;
+
+ ClipSidesIntoTree( e, tree );
+
+ // subdivide each drawsurf as required by shader tesselation or fog
+ if ( !nosubdivide ) {
+ SubdivideDrawSurfs( e, tree );
+ }
+
+ // merge together all common shaders on the same plane and remove
+ // all colinear points, so extra tjunctions won't be generated
+ if ( !nomerge ) {
+ MergeSides( e, tree ); // !@# testing
+ }
+
+ // add in any vertexes required to fix tjunctions
+ if ( !notjunc ) {
+ FixTJunctions( e );
+ }
+
+ // allocate lightmaps for faces and patches
+ AllocateLightmaps( e );
+
+ // add references to the final drawsurfs in the apropriate clusters
+ FilterDrawsurfsIntoTree( e, tree );
+
+ EndModel ( node );
+
+ FreeTree( tree );
+}
+
+
+/*
+============
+ProcessModels
+============
+*/
+void ProcessModels (void)
+{
+ qboolean oldVerbose;
+ entity_t *entity;
+
+ oldVerbose = verbose;
+
+ BeginBSPFile ();
+
+ for ( entity_num=0 ; entity_num< num_entities ; entity_num++ ) {
+ entity = &entities[entity_num];
+
+ if ( !entity->brushes && !entity->patches ) {
+ continue;
+ }
+
+ qprintf ("############### model %i ###############\n", nummodels);
+ if (entity_num == 0)
+ ProcessWorldModel ();
+ else
+ ProcessSubModel ();
+
+ if (!verboseentities)
+ verbose = qfalse; // don't bother printing submodels
+ }
+
+ verbose = oldVerbose;
+}
+
+/*
+============
+Bspinfo
+============
+*/
+void Bspinfo( int count, char **fileNames ) {
+ int i;
+ char source[1024];
+ int size;
+ FILE *f;
+
+ if ( count < 1 ) {
+ _printf( "No files to dump info for.\n");
+ return;
+ }
+
+ for ( i = 0 ; i < count ; i++ ) {
+ _printf ("---------------------\n");
+ strcpy (source, fileNames[ i ] );
+ DefaultExtension (source, ".bsp");
+ f = fopen (source, "rb");
+ if (f)
+ {
+ size = Q_filelength (f);
+ fclose (f);
+ }
+ else
+ size = 0;
+ _printf ("%s: %i\n", source, size);
+
+ LoadBSPFile (source);
+ PrintBSPFileSizes ();
+ _printf ("---------------------\n");
+ }
+}
+
+
+/*
+============
+OnlyEnts
+============
+*/
+void OnlyEnts( void ) {
+ char out[1024];
+
+ sprintf (out, "%s.bsp", source);
+ LoadBSPFile (out);
+ num_entities = 0;
+
+ LoadMapFile (name);
+ SetModelNumbers ();
+ SetLightStyles ();
+
+ UnparseEntities ();
+
+ WriteBSPFile (out);
+}
+
+
+/*
+============
+OnlyTextures
+============
+*/
+void OnlyTextures( void ) { // FIXME!!!
+ char out[1024];
+ int i;
+
+ Error( "-onlytextures isn't working now..." );
+
+ sprintf (out, "%s.bsp", source);
+
+ LoadMapFile (name);
+
+ LoadBSPFile (out);
+
+ // replace all the drawsurface shader names
+ for ( i = 0 ; i < numDrawSurfaces ; i++ ) {
+ }
+
+ WriteBSPFile (out);
+}
+
+
+/*
+============
+main
+============
+*/
+int LightMain( int argc, char **argv );
+int VLightMain (int argc, char **argv);
+int VSoundMain (int argc, char **argv);
+int VisMain( int argc, char **argv );
+
+int main (int argc, char **argv) {
+ int i;
+ double start, end;
+ char path[1024];
+
+ _printf ("Q3Map v1.0s (c) 1999 Id Software Inc.\n");
+
+ if ( argc < 2 ) {
+ Error ("usage: q3map [options] mapfile");
+ }
+
+ // check for general program options
+ if (!strcmp(argv[1], "-info")) {
+ Bspinfo( argc - 2, argv + 2 );
+ return 0;
+ }
+ if (!strcmp(argv[1], "-light")) {
+ LightMain( argc - 1, argv + 1 );
+ return 0;
+ }
+ if (!strcmp(argv[1], "-vlight")) {
+ VLightMain( argc - 1, argv + 1 );
+ return 0;
+ }
+ if (!strcmp(argv[1], "-vsound")) {
+ VSoundMain( argc - 1, argv + 1 );
+ return 0;
+ }
+ if (!strcmp(argv[1], "-vis")) {
+ VisMain( argc - 1, argv + 1 );
+ return 0;
+ }
+
+ // do a bsp if nothing else was specified
+
+ _printf ("---- q3map ----\n");
+
+ tempsource[0] = '\0';
+
+ for (i=1 ; i<argc ; i++)
+ {
+ if (!strcmp(argv[i],"-tempname"))
+ {
+ strcpy(tempsource, argv[++i]);
+ }
+ else if (!strcmp(argv[i],"-threads"))
+ {
+ numthreads = atoi (argv[i+1]);
+ i++;
+ }
+ else if (!strcmp(argv[i],"-glview"))
+ {
+ glview = qtrue;
+ }
+ else if (!strcmp(argv[i], "-v"))
+ {
+ _printf ("verbose = true\n");
+ verbose = qtrue;
+ }
+ else if (!strcmp(argv[i], "-draw"))
+ {
+ _printf ("drawflag = true\n");
+ drawflag = qtrue;
+ }
+ else if (!strcmp(argv[i], "-nowater"))
+ {
+ _printf ("nowater = true\n");
+ nowater = qtrue;
+ }
+ else if (!strcmp(argv[i], "-noopt"))
+ {
+ _printf ("noopt = true\n");
+ noopt = qtrue;
+ }
+ else if (!strcmp(argv[i], "-nofill"))
+ {
+ _printf ("nofill = true\n");
+ nofill = qtrue;
+ }
+ else if (!strcmp(argv[i], "-nodetail"))
+ {
+ _printf ("nodetail = true\n");
+ nodetail = qtrue;
+ }
+ else if (!strcmp(argv[i], "-fulldetail"))
+ {
+ _printf ("fulldetail = true\n");
+ fulldetail = qtrue;
+ }
+ else if (!strcmp(argv[i], "-onlyents"))
+ {
+ _printf ("onlyents = true\n");
+ onlyents = qtrue;
+ }
+ else if (!strcmp(argv[i], "-onlytextures"))
+ {
+ _printf ("onlytextures = true\n"); // FIXME: make work again!
+ onlytextures = qtrue;
+ }
+ else if (!strcmp(argv[i], "-micro"))
+ {
+ microvolume = atof(argv[i+1]);
+ _printf ("microvolume = %f\n", microvolume);
+ i++;
+ }
+ else if (!strcmp(argv[i], "-nofog"))
+ {
+ _printf ("nofog = true\n");
+ nofog = qtrue;
+ }
+ else if (!strcmp(argv[i], "-nosubdivide"))
+ {
+ _printf ("nosubdivide = true\n");
+ nosubdivide = qtrue;
+ }
+ else if (!strcmp(argv[i], "-leaktest"))
+ {
+ _printf ("leaktest = true\n");
+ leaktest = qtrue;
+ }
+ else if (!strcmp(argv[i], "-verboseentities"))
+ {
+ _printf ("verboseentities = true\n");
+ verboseentities = qtrue;
+ }
+ else if (!strcmp(argv[i], "-nocurves"))
+ {
+ noCurveBrushes = qtrue;
+ _printf ("no curve brushes\n");
+ }
+ else if (!strcmp(argv[i], "-notjunc"))
+ {
+ notjunc = qtrue;
+ _printf ("no tjunction fixing\n");
+ }
+ else if (!strcmp(argv[i], "-expand"))
+ {
+ testExpand = qtrue;
+ _printf ("Writing expanded.map.\n");
+ }
+ else if (!strcmp(argv[i], "-showseams"))
+ {
+ showseams = qtrue;
+ _printf ("Showing seams on terrain.\n");
+ }
+ else if (!strcmp (argv[i],"-tmpout"))
+ {
+ strcpy (outbase, "/tmp");
+ }
+ else if (!strcmp (argv[i],"-fakemap"))
+ {
+ fakemap = qtrue;
+ _printf( "will generate fakemap.map\n");
+ }
+ else if (!strcmp(argv[i], "-samplesize"))
+ {
+ samplesize = atoi(argv[i+1]);
+ if (samplesize < 1) samplesize = 1;
+ i++;
+ _printf("lightmap sample size is %dx%d units\n", samplesize, samplesize);
+ }
+ else if (argv[i][0] == '-')
+ Error ("Unknown option \"%s\"", argv[i]);
+ else
+ break;
+ }
+
+ if (i != argc - 1)
+ Error ("usage: q3map [options] mapfile");
+
+ start = I_FloatTime ();
+
+ ThreadSetDefault ();
+ //numthreads = 1; // multiple threads aren't helping because of heavy malloc use
+ SetQdirFromPath (argv[i]);
+
+#ifdef _WIN32
+ InitPakFile(gamedir, NULL);
+#endif
+
+ strcpy (source, ExpandArg (argv[i]));
+ StripExtension (source);
+
+ // delete portal and line files
+ sprintf (path, "%s.prt", source);
+ remove (path);
+ sprintf (path, "%s.lin", source);
+ remove (path);
+
+ strcpy (name, ExpandArg (argv[i]));
+ if ( strcmp(name + strlen(name) - 4, ".reg" ) ) {
+ // if we are doing a full map, delete the last saved region map
+ sprintf (path, "%s.reg", source);
+ remove (path);
+
+ DefaultExtension (name, ".map"); // might be .reg
+ }
+
+ //
+ // if onlyents, just grab the entites and resave
+ //
+ if ( onlyents ) {
+ OnlyEnts();
+ return 0;
+ }
+
+ //
+ // if onlytextures, just grab the textures and resave
+ //
+ if ( onlytextures ) {
+ OnlyTextures();
+ return 0;
+ }
+
+ //
+ // start from scratch
+ //
+ LoadShaderInfo();
+
+ // load original file from temp spot in case it was renamed by the editor on the way in
+ if (strlen(tempsource) > 0) {
+ LoadMapFile (tempsource);
+ } else {
+ LoadMapFile (name);
+ }
+
+ SetModelNumbers ();
+ SetLightStyles ();
+
+ ProcessModels ();
+
+ EndBSPFile();
+
+ end = I_FloatTime ();
+ _printf ("%5.0f seconds elapsed\n", end-start);
+
+ // remove temp name if appropriate
+ if (strlen(tempsource) > 0) {
+ remove(tempsource);
+ }
+
+ return 0;
+}
+
diff --git a/q3map/facebsp.c b/q3map/facebsp.c
new file mode 100755
index 0000000..d1b00b4
--- /dev/null
+++ b/q3map/facebsp.c
@@ -0,0 +1,379 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+
+
+int c_faceLeafs;
+
+
+/*
+================
+AllocBspFace
+================
+*/
+bspface_t *AllocBspFace( void ) {
+ bspface_t *f;
+
+ f = malloc(sizeof(*f));
+ memset( f, 0, sizeof(*f) );
+
+ return f;
+}
+
+/*
+================
+FreeBspFace
+================
+*/
+void FreeBspFace( bspface_t *f ) {
+ if ( f->w ) {
+ FreeWinding( f->w );
+ }
+ free( f );
+}
+
+
+/*
+================
+SelectSplitPlaneNum
+================
+*/
+int hintsplit;
+
+#define BLOCK_SIZE 1024
+int SelectSplitPlaneNum( node_t *node, bspface_t *list ) {
+ bspface_t *split;
+ bspface_t *check;
+ bspface_t *bestSplit;
+ int splits, facing, front, back;
+ int side;
+ plane_t *plane;
+ int value, bestValue;
+ int i;
+ vec3_t normal;
+ float dist;
+ int planenum;
+
+ hintsplit = qfalse;
+ // if it is crossing a 1k block boundary, force a split
+ for ( i = 0 ; i < 2 ; i++ ) {
+ dist = BLOCK_SIZE * ( floor( node->mins[i] / BLOCK_SIZE ) + 1 );
+ if ( node->maxs[i] > dist ) {
+ VectorClear( normal );
+ normal[i] = 1;
+ planenum = FindFloatPlane( normal, dist );
+ return planenum;
+ }
+ }
+
+ // pick one of the face planes
+ bestValue = -99999;
+ bestSplit = list;
+
+ for ( split = list ; split ; split = split->next ) {
+ split->checked = qfalse;
+ }
+
+ for ( split = list ; split ; split = split->next ) {
+ if ( split->checked ) {
+ continue;
+ }
+ plane = &mapplanes[ split->planenum ];
+ splits = 0;
+ facing = 0;
+ front = 0;
+ back = 0;
+ for ( check = list ; check ; check = check->next ) {
+ if ( check->planenum == split->planenum ) {
+ facing++;
+ check->checked = qtrue; // won't need to test this plane again
+ continue;
+ }
+ side = WindingOnPlaneSide( check->w, plane->normal, plane->dist );
+ if ( side == SIDE_CROSS ) {
+ splits++;
+ } else if ( side == SIDE_FRONT ) {
+ front++;
+ } else if ( side == SIDE_BACK ) {
+ back++;
+ }
+ }
+ value = 5*facing - 5*splits; // - abs(front-back);
+ if ( plane->type < 3 ) {
+ value+=5; // axial is better
+ }
+ value += split->priority; // prioritize hints higher
+
+ if ( value > bestValue ) {
+ bestValue = value;
+ bestSplit = split;
+ }
+ }
+
+ if ( bestValue == -99999 ) {
+ return -1;
+ }
+
+ if (bestSplit->hint)
+ hintsplit = qtrue;
+
+ return bestSplit->planenum;
+}
+
+int CountFaceList( bspface_t *list ) {
+ int c;
+ c = 0;
+ for ( ; list ; list = list->next ) {
+ c++;
+ }
+ return c;
+}
+
+/*
+================
+BuildFaceTree_r
+================
+*/
+void BuildFaceTree_r( node_t *node, bspface_t *list ) {
+ bspface_t *split;
+ bspface_t *next;
+ int side;
+ plane_t *plane;
+ bspface_t *newFace;
+ bspface_t *childLists[2];
+ winding_t *frontWinding, *backWinding;
+ int i;
+ int splitPlaneNum;
+
+ i = CountFaceList( list );
+
+ splitPlaneNum = SelectSplitPlaneNum( node, list );
+ // if we don't have any more faces, this is a node
+ if ( splitPlaneNum == -1 ) {
+ node->planenum = PLANENUM_LEAF;
+ c_faceLeafs++;
+ return;
+ }
+
+ // partition the list
+ node->planenum = splitPlaneNum;
+ node->hint = hintsplit;
+ plane = &mapplanes[ splitPlaneNum ];
+ childLists[0] = NULL;
+ childLists[1] = NULL;
+ for ( split = list ; split ; split = next ) {
+ next = split->next;
+
+ if ( split->planenum == node->planenum ) {
+ FreeBspFace( split );
+ continue;
+ }
+
+ side = WindingOnPlaneSide( split->w, plane->normal, plane->dist );
+
+ if ( side == SIDE_CROSS ) {
+ ClipWindingEpsilon( split->w, plane->normal, plane->dist, CLIP_EPSILON * 2,
+ &frontWinding, &backWinding );
+ if ( frontWinding ) {
+ newFace = AllocBspFace();
+ newFace->w = frontWinding;
+ newFace->next = childLists[0];
+ newFace->planenum = split->planenum;
+ newFace->priority = split->priority;
+ newFace->hint = split->hint;
+ childLists[0] = newFace;
+ }
+ if ( backWinding ) {
+ newFace = AllocBspFace();
+ newFace->w = backWinding;
+ newFace->next = childLists[1];
+ newFace->planenum = split->planenum;
+ newFace->priority = split->priority;
+ newFace->hint = split->hint;
+ childLists[1] = newFace;
+ }
+ FreeBspFace( split );
+ } else if ( side == SIDE_FRONT ) {
+ split->next = childLists[0];
+ childLists[0] = split;
+ } else if ( side == SIDE_BACK ) {
+ split->next = childLists[1];
+ childLists[1] = split;
+ }
+ }
+
+
+ // recursively process children
+ for ( i = 0 ; i < 2 ; i++ ) {
+ node->children[i] = AllocNode();
+ node->children[i]->parent = node;
+ VectorCopy( node->mins, node->children[i]->mins );
+ VectorCopy( node->maxs, node->children[i]->maxs );
+ }
+
+ for ( i = 0 ; i < 3 ; i++ ) {
+ if ( plane->normal[i] == 1 ) {
+ node->children[0]->mins[i] = plane->dist;
+ node->children[1]->maxs[i] = plane->dist;
+ break;
+ }
+ }
+
+ for ( i = 0 ; i < 2 ; i++ ) {
+ BuildFaceTree_r ( node->children[i], childLists[i]);
+ }
+}
+
+
+/*
+================
+FaceBSP
+
+List will be freed before returning
+================
+*/
+tree_t *FaceBSP( bspface_t *list ) {
+ tree_t *tree;
+ bspface_t *face;
+ int i;
+ int count;
+
+ qprintf( "--- FaceBSP ---\n" );
+
+ tree = AllocTree ();
+
+ count = 0;
+ for ( face = list ; face ; face = face->next ) {
+ count++;
+ for ( i = 0 ; i < face->w->numpoints ; i++ ) {
+ AddPointToBounds( face->w->p[i], tree->mins, tree->maxs);
+ }
+ }
+ qprintf( "%5i faces\n", count );
+
+ tree->headnode = AllocNode();
+ VectorCopy( tree->mins, tree->headnode->mins );
+ VectorCopy( tree->maxs, tree->headnode->maxs );
+ c_faceLeafs = 0;
+
+ BuildFaceTree_r ( tree->headnode, list );
+
+ qprintf( "%5i leafs\n", c_faceLeafs );
+
+ return tree;
+}
+
+
+/*
+=================
+BspFaceForPortal
+=================
+*/
+bspface_t *BspFaceForPortal( portal_t *p ) {
+ bspface_t *f;
+
+ f = AllocBspFace();
+ f->w = CopyWinding( p->winding );
+ f->planenum = p->onnode->planenum & ~1;
+
+ return f;
+}
+
+
+
+/*
+=================
+MakeStructuralBspFaceList
+=================
+*/
+bspface_t *MakeStructuralBspFaceList( bspbrush_t *list ) {
+ bspbrush_t *b;
+ int i;
+ side_t *s;
+ winding_t *w;
+ bspface_t *f, *flist;
+
+ flist = NULL;
+ for ( b = list ; b ; b = b->next ) {
+ if ( b->detail ) {
+ continue;
+ }
+ for ( i = 0 ; i < b->numsides ; i++ ) {
+ s = &b->sides[i];
+ w = s->winding;
+ if ( !w ) {
+ continue;
+ }
+ f = AllocBspFace();
+ f->w = CopyWinding( w );
+ f->planenum = s->planenum & ~1;
+ f->next = flist;
+ if (s->surfaceFlags & SURF_HINT) {
+ //f->priority = HINT_PRIORITY;
+ f->hint = qtrue;
+ }
+ flist = f;
+ }
+ }
+
+ return flist;
+}
+
+/*
+=================
+MakeVisibleBspFaceList
+=================
+*/
+bspface_t *MakeVisibleBspFaceList( bspbrush_t *list ) {
+ bspbrush_t *b;
+ int i;
+ side_t *s;
+ winding_t *w;
+ bspface_t *f, *flist;
+
+ flist = NULL;
+ for ( b = list ; b ; b = b->next ) {
+ if ( b->detail ) {
+ continue;
+ }
+ for ( i = 0 ; i < b->numsides ; i++ ) {
+ s = &b->sides[i];
+ w = s->visibleHull;
+ if ( !w ) {
+ continue;
+ }
+ f = AllocBspFace();
+ f->w = CopyWinding( w );
+ f->planenum = s->planenum & ~1;
+ f->next = flist;
+ if (s->surfaceFlags & SURF_HINT) {
+ //f->priority = HINT_PRIORITY;
+ f->hint = qtrue;
+ }
+ flist = f;
+ }
+ }
+
+ return flist;
+}
+
diff --git a/q3map/fog.c b/q3map/fog.c
new file mode 100755
index 0000000..cf4060a
--- /dev/null
+++ b/q3map/fog.c
@@ -0,0 +1,554 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "qbsp.h"
+
+
+int c_fogFragment;
+int c_fogPatchFragments;
+
+/*
+====================
+DrawSurfToMesh
+====================
+*/
+mesh_t *DrawSurfToMesh( mapDrawSurface_t *ds ) {
+ mesh_t *m;
+
+ m = malloc( sizeof( *m ) );
+ m->width = ds->patchWidth;
+ m->height = ds->patchHeight;
+ m->verts = malloc( sizeof(m->verts[0]) * m->width * m->height );
+ memcpy( m->verts, ds->verts, sizeof(m->verts[0]) * m->width * m->height );
+
+ return m;
+}
+
+
+/*
+====================
+SplitMeshByPlane
+====================
+*/
+void SplitMeshByPlane( mesh_t *in, vec3_t normal, float dist, mesh_t **front, mesh_t **back ) {
+ int w, h, split;
+ float d[MAX_PATCH_SIZE][MAX_PATCH_SIZE];
+ drawVert_t *dv, *v1, *v2;
+ int c_front, c_back, c_on;
+ mesh_t *f, *b;
+ int i;
+ float frac;
+ int frontAprox, backAprox;
+
+ for ( i = 0 ; i < 2 ; i++ ) {
+ dv = in->verts;
+ c_front = 0;
+ c_back = 0;
+ c_on = 0;
+ for ( h = 0 ; h < in->height ; h++ ) {
+ for ( w = 0 ; w < in->width ; w++, dv++ ) {
+ d[h][w] = DotProduct( dv->xyz, normal ) - dist;
+ if ( d[h][w] > ON_EPSILON ) {
+ c_front++;
+ } else if ( d[h][w] < -ON_EPSILON ) {
+ c_back++;
+ } else {
+ c_on++;
+ }
+ }
+ }
+
+ *front = NULL;
+ *back = NULL;
+
+ if ( !c_front ) {
+ *back = in;
+ return;
+ }
+ if ( !c_back ) {
+ *front = in;
+ return;
+ }
+
+ // find a split point
+ split = -1;
+ for ( w = 0 ; w < in->width -1 ; w++ ) {
+ if ( ( d[0][w] < 0 ) != ( d[0][w+1] < 0 ) ) {
+ if ( split == -1 ) {
+ split = w;
+ break;
+ }
+ }
+ }
+
+ if ( split == -1 ) {
+ if ( i == 1 ) {
+ qprintf( "No crossing points in patch\n");
+ *front = in;
+ return;
+ }
+
+ in = TransposeMesh( in );
+ InvertMesh( in );
+ continue;
+ }
+
+ // make sure the split point stays the same for all other rows
+ for ( h = 1 ; h < in->height ; h++ ) {
+ for ( w = 0 ; w < in->width -1 ; w++ ) {
+ if ( ( d[h][w] < 0 ) != ( d[h][w+1] < 0 ) ) {
+ if ( w != split ) {
+ _printf( "multiple crossing points for patch -- can't clip\n");
+ *front = in;
+ return;
+ }
+ }
+ }
+ if ( ( d[h][split] < 0 ) == ( d[h][split+1] < 0 ) ) {
+ _printf( "differing crossing points for patch -- can't clip\n");
+ *front = in;
+ return;
+ }
+ }
+
+ break;
+ }
+
+
+ // create two new meshes
+ f = malloc( sizeof( *f ) );
+ f->width = split + 2;
+ if ( ! (f->width & 1) ) {
+ f->width++;
+ frontAprox = 1;
+ } else {
+ frontAprox = 0;
+ }
+ if ( f->width > MAX_PATCH_SIZE ) {
+ Error( "MAX_PATCH_SIZE after split");
+ }
+ f->height = in->height;
+ f->verts = malloc( sizeof(f->verts[0]) * f->width * f->height );
+
+ b = malloc( sizeof( *b ) );
+ b->width = in->width - split;
+ if ( ! (b->width & 1) ) {
+ b->width++;
+ backAprox = 1;
+ } else {
+ backAprox = 0;
+ }
+ if ( b->width > MAX_PATCH_SIZE ) {
+ Error( "MAX_PATCH_SIZE after split");
+ }
+ b->height = in->height;
+ b->verts = malloc( sizeof(b->verts[0]) * b->width * b->height );
+
+ if ( d[0][0] > 0 ) {
+ *front = f;
+ *back = b;
+ } else {
+ *front = b;
+ *back = f;
+ }
+
+ // distribute the points
+ for ( w = 0 ; w < in->width ; w++ ) {
+ for ( h = 0 ; h < in->height ; h++ ) {
+ if ( w <= split ) {
+ f->verts[ h * f->width + w ] = in->verts[ h * in->width + w ];
+ } else {
+ b->verts[ h * b->width + w - split + backAprox ] = in->verts[ h * in->width + w ];
+ }
+ }
+ }
+
+ // clip the crossing line
+ for ( h = 0 ; h < in->height ; h++ ) {
+ dv = &f->verts[ h * f->width + split + 1 ];
+ v1 = &in->verts[ h * in->width + split ];
+ v2 = &in->verts[ h * in->width + split + 1 ];
+ frac = d[h][split] / ( d[h][split] - d[h][split+1] );
+ for ( i = 0 ; i < 10 ; i++ ) {
+ dv->xyz[i] = v1->xyz[i] + frac * ( v2->xyz[i] - v1->xyz[i] );
+ }
+ dv->xyz[10] = 0;//set all 4 colors to 0
+ if ( frontAprox ) {
+ f->verts[ h * f->width + split + 2 ] = *dv;
+ }
+ b->verts[ h * b->width ] = *dv;
+ if ( backAprox ) {
+ b->verts[ h * b->width + 1 ] = *dv;
+ }
+ }
+
+ /*
+PrintMesh( in );
+_printf("\n");
+PrintMesh( f );
+_printf("\n");
+PrintMesh( b );
+_printf("\n");
+ */
+
+ FreeMesh( in );
+}
+
+
+/*
+====================
+ChopPatchByBrush
+====================
+*/
+qboolean ChopPatchByBrush( mapDrawSurface_t *ds, bspbrush_t *b ) {
+ int i, j;
+ side_t *s;
+ plane_t *plane;
+ mesh_t *outside[MAX_BRUSH_SIDES];
+ int numOutside;
+ mesh_t *m, *front, *back;
+ mapDrawSurface_t *newds;
+
+ m = DrawSurfToMesh( ds );
+ numOutside = 0;
+
+ // only split by the top and bottom planes to avoid
+ // some messy patch clipping issues
+
+ for ( i = 4 ; i <= 5 ; i++ ) {
+ s = &b->sides[ i ];
+ plane = &mapplanes[ s->planenum ];
+
+ SplitMeshByPlane( m, plane->normal, plane->dist, &front, &back );
+
+ if ( !back ) {
+ // nothing actually contained inside
+ for ( j = 0 ; j < numOutside ; j++ ) {
+ FreeMesh( outside[j] );
+ }
+ return qfalse;
+ }
+ m = back;
+
+ if ( front ) {
+ if ( numOutside == MAX_BRUSH_SIDES ) {
+ Error( "MAX_BRUSH_SIDES" );
+ }
+ outside[ numOutside ] = front;
+ numOutside++;
+ }
+ }
+
+ // all of outside fragments become seperate drawsurfs
+ c_fogPatchFragments += numOutside;
+ for ( i = 0 ; i < numOutside ; i++ ) {
+ newds = DrawSurfaceForMesh( outside[ i ] );
+ newds->shaderInfo = ds->shaderInfo;
+ FreeMesh( outside[ i ] );
+ }
+
+ // replace ds with m
+ ds->patchWidth = m->width;
+ ds->patchHeight = m->height;
+ ds->numVerts = m->width * m->height;
+ free( ds->verts );
+ ds->verts = malloc( ds->numVerts * sizeof( *ds->verts ) );
+ memcpy( ds->verts, m->verts, ds->numVerts * sizeof( *ds->verts ) );
+
+ FreeMesh( m );
+
+ return qtrue;
+}
+
+//===============================================================================
+
+/*
+====================
+WindingFromDrawSurf
+====================
+*/
+winding_t *WindingFromDrawSurf( mapDrawSurface_t *ds ) {
+ winding_t *w;
+ int i;
+
+ w = AllocWinding( ds->numVerts );
+ w->numpoints = ds->numVerts;
+ for ( i = 0 ; i < ds->numVerts ; i++ ) {
+ VectorCopy( ds->verts[i].xyz, w->p[i] );
+ }
+ return w;
+}
+
+/*
+====================
+ChopFaceByBrush
+
+There may be a fragment contained in the brush
+====================
+*/
+qboolean ChopFaceByBrush( mapDrawSurface_t *ds, bspbrush_t *b ) {
+ int i, j;
+ side_t *s;
+ plane_t *plane;
+ winding_t *w;
+ winding_t *front, *back;
+ winding_t *outside[MAX_BRUSH_SIDES];
+ int numOutside;
+ mapDrawSurface_t *newds;
+ drawVert_t *dv;
+ shaderInfo_t *si;
+ float mins[2];
+
+ // brush primitive :
+ // axis base
+ vec3_t texX,texY;
+ vec_t x,y;
+
+ w = WindingFromDrawSurf( ds );
+ numOutside = 0;
+
+ for ( i = 0 ; i < b->numsides ; i++ ) {
+ s = &b->sides[ i ];
+ if ( s->backSide ) {
+ continue;
+ }
+ plane = &mapplanes[ s->planenum ];
+
+ // handle coplanar outfacing (don't fog)
+ if ( ds->side->planenum == s->planenum ) {
+ return qfalse;
+ }
+
+ // handle coplanar infacing (keep inside)
+ if ( ( ds->side->planenum ^ 1 ) == s->planenum ) {
+ continue;
+ }
+
+ // general case
+ ClipWindingEpsilon( w, plane->normal, plane->dist, ON_EPSILON,
+ &front, &back );
+ FreeWinding( w );
+ if ( !back ) {
+ // nothing actually contained inside
+ for ( j = 0 ; j < numOutside ; j++ ) {
+ FreeWinding( outside[j] );
+ }
+ return qfalse;
+ }
+ if ( front ) {
+ if ( numOutside == MAX_BRUSH_SIDES ) {
+ Error( "MAX_BRUSH_SIDES" );
+ }
+ outside[ numOutside ] = front;
+ numOutside++;
+ }
+ w = back;
+ }
+
+ // all of outside fragments become seperate drawsurfs
+ // linked to the same side
+ c_fogFragment += numOutside;
+ s = ds->side;
+
+ for ( i = 0 ; i < numOutside ; i++ ) {
+ newds = DrawSurfaceForSide( ds->mapBrush, s, outside[i] );
+ FreeWinding( outside[i] );
+ }
+
+
+ // replace ds->verts with the verts for w
+ ds->numVerts = w->numpoints;
+ free( ds->verts );
+
+ ds->verts = malloc( ds->numVerts * sizeof( *ds->verts ) );
+ memset( ds->verts, 0, ds->numVerts * sizeof( *ds->verts ) );
+
+ si = s->shaderInfo;
+
+ mins[0] = 9999;
+ mins[1] = 9999;
+
+ // compute s/t coordinates from brush primitive texture matrix
+ // compute axis base
+ ComputeAxisBase( mapplanes[s->planenum].normal, texX, texY );
+
+ for ( j = 0 ; j < w->numpoints ; j++ ) {
+ dv = ds->verts + j;
+ VectorCopy( w->p[j], dv->xyz );
+
+ if (g_bBrushPrimit==BPRIMIT_OLDBRUSHES)
+ {
+ // calculate texture s/t
+ dv->st[0] = s->vecs[0][3] + DotProduct( s->vecs[0], dv->xyz );
+ dv->st[1] = s->vecs[1][3] + DotProduct( s->vecs[1], dv->xyz );
+ dv->st[0] /= si->width;
+ dv->st[1] /= si->height;
+ }
+ else
+ {
+ // calculate texture s/t from brush primitive texture matrix
+ x = DotProduct( dv->xyz, texX );
+ y = DotProduct( dv->xyz, texY );
+ dv->st[0]=s->texMat[0][0]*x+s->texMat[0][1]*y+s->texMat[0][2];
+ dv->st[1]=s->texMat[1][0]*x+s->texMat[1][1]*y+s->texMat[1][2];
+ }
+
+ if ( dv->st[0] < mins[0] ) {
+ mins[0] = dv->st[0];
+ }
+ if ( dv->st[1] < mins[1] ) {
+ mins[1] = dv->st[1];
+ }
+
+ // copy normal
+ VectorCopy ( mapplanes[s->planenum].normal, dv->normal );
+ }
+
+ // adjust the texture coordinates to be as close to 0 as possible
+ if ( !si->globalTexture ) {
+ mins[0] = floor( mins[0] );
+ mins[1] = floor( mins[1] );
+ for ( i = 0 ; i < w->numpoints ; i++ ) {
+ dv = ds->verts + i;
+ dv->st[0] -= mins[0];
+ dv->st[1] -= mins[1];
+ }
+ }
+
+ return qtrue;
+}
+
+//===============================================================================
+
+
+/*
+=====================
+FogDrawSurfs
+
+Call after the surface list has been pruned,
+before tjunction fixing
+before lightmap allocation
+=====================
+*/
+void FogDrawSurfs( void ) {
+ int i, j, k;
+ mapDrawSurface_t *ds;
+ bspbrush_t *b;
+ vec3_t mins, maxs;
+ int c_fogged;
+ int numBaseDrawSurfs;
+ dfog_t *fog;
+
+ qprintf("----- FogDrawsurfs -----\n");
+
+ c_fogged = 0;
+ c_fogFragment = 0;
+
+ // find all fog brushes
+ for ( b = entities[0].brushes ; b ; b = b->next ) {
+ if ( !(b->contents & CONTENTS_FOG) ) {
+ continue;
+ }
+
+ if ( numFogs == MAX_MAP_FOGS ) {
+ Error( "MAX_MAP_FOGS" );
+ }
+ fog = &dfogs[numFogs];
+ numFogs++;
+ fog->brushNum = b->outputNumber;
+
+ // find a side with a valid shaderInfo
+ // non-axial fog columns may have bevel planes that need to be skipped
+ for ( i = 0 ; i < b->numsides ; i++ ) {
+ if ( b->sides[i].shaderInfo && (b->sides[i].shaderInfo->contents & CONTENTS_FOG) ) {
+ strcpy( fog->shader, b->sides[i].shaderInfo->shader );
+ break;
+ }
+ }
+ if ( i == b->numsides ) {
+ continue; // shouldn't happen
+ }
+
+ fog->visibleSide = -1;
+
+ // clip each surface into this, but don't clip any of
+ // the resulting fragments to the same brush
+ numBaseDrawSurfs = numMapDrawSurfs;
+ for ( i = 0 ; i < numBaseDrawSurfs ; i++ ) {
+ ds = &mapDrawSurfs[i];
+
+ // bound the drawsurf
+ ClearBounds( mins, maxs );
+ for ( j = 0 ; j < ds->numVerts ; j++ ) {
+ AddPointToBounds( ds->verts[j].xyz, mins, maxs );
+ }
+
+ // check against the fog brush
+ for ( k = 0 ; k < 3 ; k++ ) {
+ if ( mins[k] > b->maxs[k] ) {
+ break;
+ }
+ if ( maxs[k] < b->mins[k] ) {
+ break;
+ }
+ }
+ if ( k < 3 ) {
+ continue; // bboxes don't intersect
+ }
+
+ if ( ds->mapBrush == b ) {
+ int s;
+
+ s = ds->side - b->sides;
+ if ( s <= 6 ) { // not one of the reversed inside faces
+ // this is a visible fog plane
+ if ( fog->visibleSide != -1 ) {
+ _printf( "WARNING: fog brush %i has multiple visible sides\n", b->brushnum );
+ }
+ fog->visibleSide = s;
+ }
+ }
+
+ if ( ds->miscModel ) {
+ // we could write splitting code for trimodels if we wanted to...
+ c_fogged++;
+ ds->fogNum = numFogs - 1;
+ } else if ( ds->patch ) {
+ if ( ChopPatchByBrush( ds, b ) ) {
+ c_fogged++;
+ ds->fogNum = numFogs - 1;
+ }
+ } else {
+ if ( ChopFaceByBrush( ds, b ) ) {
+ c_fogged++;
+ ds->fogNum = numFogs - 1;
+ }
+ }
+ }
+ }
+
+ // split the drawsurfs by the fog brushes
+
+ qprintf( "%5i fogs\n", numFogs );
+ qprintf( "%5i fog polygon fragments\n", c_fogFragment );
+ qprintf( "%5i fog patch fragments\n", c_fogPatchFragments );
+ qprintf( "%5i fogged drawsurfs\n", c_fogged );
+}
diff --git a/q3map/gldraw.c b/q3map/gldraw.c
new file mode 100755
index 0000000..bf2ceba
--- /dev/null
+++ b/q3map/gldraw.c
@@ -0,0 +1,232 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include <windows.h>
+#include <GL/gl.h>
+#include <GL/glu.h>
+#include <GL/glaux.h>
+
+#include "qbsp.h"
+
+// can't use the glvertex3fv functions, because the vec3_t fields
+// could be either floats or doubles, depending on DOUBLEVEC_T
+
+qboolean drawflag;
+vec3_t draw_mins, draw_maxs;
+
+
+#define WIN_SIZE 512
+
+void InitWindow (void)
+{
+ auxInitDisplayMode (AUX_SINGLE | AUX_RGB);
+ auxInitPosition (0, 0, WIN_SIZE, WIN_SIZE);
+ auxInitWindow ("qcsg");
+}
+
+void Draw_ClearWindow (void)
+{
+ static int init;
+ int w, h, g;
+ vec_t mx, my;
+
+ if (!drawflag)
+ return;
+
+ if (!init)
+ {
+ init = qtrue;
+ InitWindow ();
+ }
+
+ glClearColor (1,0.8,0.8,0);
+ glClear (GL_COLOR_BUFFER_BIT);
+
+ w = (draw_maxs[0] - draw_mins[0]);
+ h = (draw_maxs[1] - draw_mins[1]);
+
+ mx = draw_mins[0] + w/2;
+ my = draw_mins[1] + h/2;
+
+ g = w > h ? w : h;
+
+ glLoadIdentity ();
+ gluPerspective (90, 1, 2, 16384);
+ gluLookAt (mx, my, draw_maxs[2] + g/2, mx , my, draw_maxs[2], 0, 1, 0);
+
+ glColor3f (0,0,0);
+// glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
+ glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
+ glDisable (GL_DEPTH_TEST);
+ glEnable (GL_BLEND);
+ glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+
+#if 0
+ glColor4f (1,0,0,0.5);
+ glBegin (GL_POLYGON);
+
+ glVertex3f (0, 500, 0);
+ glVertex3f (0, 900, 0);
+ glVertex3f (0, 900, 100);
+ glVertex3f (0, 500, 100);
+
+ glEnd ();
+#endif
+
+ glFlush ();
+
+}
+
+void Draw_SetRed (void)
+{
+ if (!drawflag)
+ return;
+
+ glColor3f (1,0,0);
+}
+
+void Draw_SetGrey (void)
+{
+ if (!drawflag)
+ return;
+
+ glColor3f (0.5,0.5,0.5);
+}
+
+void Draw_SetBlack (void)
+{
+ if (!drawflag)
+ return;
+
+ glColor3f (0,0,0);
+}
+
+void DrawWinding (winding_t *w)
+{
+ int i;
+
+ if (!drawflag)
+ return;
+
+ glColor4f (0,0,0,0.5);
+ glBegin (GL_LINE_LOOP);
+ for (i=0 ; i<w->numpoints ; i++)
+ glVertex3f (w->p[i][0],w->p[i][1],w->p[i][2] );
+ glEnd ();
+
+ glColor4f (0,1,0,0.3);
+ glBegin (GL_POLYGON);
+ for (i=0 ; i<w->numpoints ; i++)
+ glVertex3f (w->p[i][0],w->p[i][1],w->p[i][2] );
+ glEnd ();
+
+ glFlush ();
+}
+
+void DrawAuxWinding (winding_t *w)
+{
+ int i;
+
+ if (!drawflag)
+ return;
+
+ glColor4f (0,0,0,0.5);
+ glBegin (GL_LINE_LOOP);
+ for (i=0 ; i<w->numpoints ; i++)
+ glVertex3f (w->p[i][0],w->p[i][1],w->p[i][2] );
+ glEnd ();
+
+ glColor4f (1,0,0,0.3);
+ glBegin (GL_POLYGON);
+ for (i=0 ; i<w->numpoints ; i++)
+ glVertex3f (w->p[i][0],w->p[i][1],w->p[i][2] );
+ glEnd ();
+
+ glFlush ();
+}
+
+//============================================================
+
+#define GLSERV_PORT 25001
+
+qboolean wins_init;
+int draw_socket;
+
+void GLS_BeginScene (void)
+{
+ WSADATA winsockdata;
+ WORD wVersionRequested;
+ struct sockaddr_in address;
+ int r;
+
+ if (!wins_init)
+ {
+ wins_init = qtrue;
+
+ wVersionRequested = MAKEWORD(1, 1);
+
+ r = WSAStartup (MAKEWORD(1, 1), &winsockdata);
+
+ if (r)
+ Error ("Winsock initialization failed.");
+
+ }
+
+ // connect a socket to the server
+
+ draw_socket = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
+ if (draw_socket == -1)
+ Error ("draw_socket failed");
+
+ address.sin_family = AF_INET;
+ address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+ address.sin_port = GLSERV_PORT;
+ r = connect (draw_socket, (struct sockaddr *)&address, sizeof(address));
+ if (r == -1)
+ {
+ closesocket (draw_socket);
+ draw_socket = 0;
+ }
+}
+
+void GLS_Winding (winding_t *w, int code)
+{
+ byte buf[1024];
+ int i, j;
+
+ if (!draw_socket)
+ return;
+
+ ((int *)buf)[0] = w->numpoints;
+ ((int *)buf)[1] = code;
+ for (i=0 ; i<w->numpoints ; i++)
+ for (j=0 ; j<3 ; j++)
+ ((float *)buf)[2+i*3+j] = w->p[i][j];
+
+ send (draw_socket, buf, w->numpoints*12+8, 0);
+}
+
+void GLS_EndScene (void)
+{
+ closesocket (draw_socket);
+ draw_socket = 0;
+}
diff --git a/q3map/glfile.c b/q3map/glfile.c
new file mode 100755
index 0000000..8bb10c6
--- /dev/null
+++ b/q3map/glfile.c
@@ -0,0 +1,148 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+
+int c_glfaces;
+
+int PortalVisibleSides (portal_t *p)
+{
+ int fcon, bcon;
+
+ if (!p->onnode)
+ return 0; // outside
+
+ fcon = p->nodes[0]->opaque;
+ bcon = p->nodes[1]->opaque;
+
+ // same contents never create a face
+ if (fcon == bcon)
+ return 0;
+
+ if (!fcon)
+ return 1;
+ if (!bcon)
+ return 2;
+ return 0;
+}
+
+void OutputWinding (winding_t *w, FILE *glview)
+{
+ static int level = 128;
+ vec_t light;
+ int i;
+
+ fprintf (glview, "%i\n", w->numpoints);
+ level+=28;
+ light = (level&255)/255.0;
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ fprintf (glview, "%6.3f %6.3f %6.3f %6.3f %6.3f %6.3f\n",
+ w->p[i][0],
+ w->p[i][1],
+ w->p[i][2],
+ light,
+ light,
+ light);
+ }
+ fprintf (glview, "\n");
+}
+
+/*
+=============
+OutputPortal
+=============
+*/
+void OutputPortal (portal_t *p, FILE *glview)
+{
+ winding_t *w;
+ int sides;
+
+ sides = PortalVisibleSides (p);
+ if (!sides)
+ return;
+
+ c_glfaces++;
+
+ w = p->winding;
+
+ if (sides == 2) // back side
+ w = ReverseWinding (w);
+
+ OutputWinding (w, glview);
+
+ if (sides == 2)
+ FreeWinding(w);
+}
+
+/*
+=============
+WriteGLView_r
+=============
+*/
+void WriteGLView_r (node_t *node, FILE *glview)
+{
+ portal_t *p, *nextp;
+
+ if (node->planenum != PLANENUM_LEAF)
+ {
+ WriteGLView_r (node->children[0], glview);
+ WriteGLView_r (node->children[1], glview);
+ return;
+ }
+
+ // write all the portals
+ for (p=node->portals ; p ; p=nextp)
+ {
+ if (p->nodes[0] == node)
+ {
+ OutputPortal (p, glview);
+ nextp = p->next[0];
+ }
+ else
+ nextp = p->next[1];
+ }
+}
+
+/*
+=============
+WriteGLView
+=============
+*/
+void WriteGLView (tree_t *tree, char *source)
+{
+ char name[1024];
+ FILE *glview;
+
+ c_glfaces = 0;
+ sprintf (name, "%s%s.gl",outbase, source);
+ _printf ("Writing %s\n", name);
+
+ glview = fopen (name, "w");
+ if (!glview)
+ Error ("Couldn't open %s", name);
+ WriteGLView_r (tree->headnode, glview);
+ fclose (glview);
+
+ _printf ("%5i c_glfaces\n", c_glfaces);
+}
+
diff --git a/q3map/leakfile.c b/q3map/leakfile.c
new file mode 100755
index 0000000..101e32d
--- /dev/null
+++ b/q3map/leakfile.c
@@ -0,0 +1,100 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+
+/*
+==============================================================================
+
+LEAF FILE GENERATION
+
+Save out name.line for qe3 to read
+==============================================================================
+*/
+
+
+/*
+=============
+LeakFile
+
+Finds the shortest possible chain of portals
+that leads from the outside leaf to a specifically
+occupied leaf
+=============
+*/
+void LeakFile (tree_t *tree)
+{
+ vec3_t mid;
+ FILE *linefile;
+ char filename[1024];
+ node_t *node;
+ int count;
+
+ if (!tree->outside_node.occupied)
+ return;
+
+ qprintf ("--- LeakFile ---\n");
+
+ //
+ // write the points to the file
+ //
+ sprintf (filename, "%s.lin", source);
+ linefile = fopen (filename, "w");
+ if (!linefile)
+ Error ("Couldn't open %s\n", filename);
+
+ count = 0;
+ node = &tree->outside_node;
+ while (node->occupied > 1)
+ {
+ int next;
+ portal_t *p, *nextportal;
+ node_t *nextnode;
+ int s;
+
+ // find the best portal exit
+ next = node->occupied;
+ for (p=node->portals ; p ; p = p->next[!s])
+ {
+ s = (p->nodes[0] == node);
+ if (p->nodes[s]->occupied
+ && p->nodes[s]->occupied < next)
+ {
+ nextportal = p;
+ nextnode = p->nodes[s];
+ next = nextnode->occupied;
+ }
+ }
+ node = nextnode;
+ WindingCenter (nextportal->winding, mid);
+ fprintf (linefile, "%f %f %f\n", mid[0], mid[1], mid[2]);
+ count++;
+ }
+ // add the occupant center
+ GetVectorForKey (node->occupant, "origin", mid);
+
+ fprintf (linefile, "%f %f %f\n", mid[0], mid[1], mid[2]);
+ qprintf ("%5i point linefile\n", count+1);
+
+ fclose (linefile);
+}
+
diff --git a/q3map/light.c b/q3map/light.c
new file mode 100755
index 0000000..a3d368b
--- /dev/null
+++ b/q3map/light.c
@@ -0,0 +1,2149 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// light.c
+
+#include "light.h"
+#ifdef _WIN32
+#ifdef _TTIMOBUILD
+#include "pakstuff.h"
+#else
+#include "../libs/pakstuff.h"
+#endif
+#endif
+
+
+#define EXTRASCALE 2
+
+typedef struct {
+ float plane[4];
+ vec3_t origin;
+ vec3_t vectors[2];
+ shaderInfo_t *si;
+} filter_t;
+
+#define MAX_FILTERS 1024
+filter_t filters[MAX_FILTERS];
+int numFilters;
+
+extern char source[1024];
+
+qboolean notrace;
+qboolean patchshadows;
+qboolean dump;
+qboolean extra;
+qboolean extraWide;
+qboolean lightmapBorder;
+
+qboolean noSurfaces;
+
+int samplesize = 16; //sample size in units
+int novertexlighting = 0;
+int nogridlighting = 0;
+
+// for run time tweaking of all area sources in the level
+float areaScale = 0.25;
+
+// for run time tweaking of all point sources in the level
+float pointScale = 7500;
+
+qboolean exactPointToPolygon = qtrue;
+
+float formFactorValueScale = 3;
+
+float linearScale = 1.0 / 8000;
+
+light_t *lights;
+int numPointLights;
+int numAreaLights;
+
+FILE *dumpFile;
+
+int c_visible, c_occluded;
+
+//int defaultLightSubdivide = 128; // vary by surface size?
+int defaultLightSubdivide = 999; // vary by surface size?
+
+vec3_t ambientColor;
+
+vec3_t surfaceOrigin[ MAX_MAP_DRAW_SURFS ];
+int entitySurface[ MAX_MAP_DRAW_SURFS ];
+
+// 7,9,11 normalized to avoid being nearly coplanar with common faces
+//vec3_t sunDirection = { 0.441835, 0.56807, 0.694313 };
+//vec3_t sunDirection = { 0.45, 0, 0.9 };
+//vec3_t sunDirection = { 0, 0, 1 };
+
+// these are usually overrided by shader values
+vec3_t sunDirection = { 0.45, 0.3, 0.9 };
+vec3_t sunLight = { 100, 100, 50 };
+
+
+
+typedef struct {
+ dbrush_t *b;
+ vec3_t bounds[2];
+} skyBrush_t;
+
+int numSkyBrushes;
+skyBrush_t skyBrushes[MAX_MAP_BRUSHES];
+
+
+/*
+
+the corners of a patch mesh will always be exactly at lightmap samples.
+The dimensions of the lightmap will be equal to the average length of the control
+mesh in each dimension divided by 2.
+The lightmap sample points should correspond to the chosen subdivision points.
+
+*/
+
+/*
+===============================================================
+
+SURFACE LOADING
+
+===============================================================
+*/
+
+#define MAX_FACE_POINTS 128
+
+/*
+===============
+SubdivideAreaLight
+
+Subdivide area lights that are very large
+A light that is subdivided will never backsplash, avoiding weird pools of light near edges
+===============
+*/
+void SubdivideAreaLight( shaderInfo_t *ls, winding_t *w, vec3_t normal,
+ float areaSubdivide, qboolean backsplash ) {
+ float area, value, intensity;
+ light_t *dl, *dl2;
+ vec3_t mins, maxs;
+ int axis;
+ winding_t *front, *back;
+ vec3_t planeNormal;
+ float planeDist;
+
+ if ( !w ) {
+ return;
+ }
+
+ WindingBounds( w, mins, maxs );
+
+ // check for subdivision
+ for ( axis = 0 ; axis < 3 ; axis++ ) {
+ if ( maxs[axis] - mins[axis] > areaSubdivide ) {
+ VectorClear( planeNormal );
+ planeNormal[axis] = 1;
+ planeDist = ( maxs[axis] + mins[axis] ) * 0.5;
+ ClipWindingEpsilon ( w, planeNormal, planeDist, ON_EPSILON, &front, &back );
+ SubdivideAreaLight( ls, front, normal, areaSubdivide, qfalse );
+ SubdivideAreaLight( ls, back, normal, areaSubdivide, qfalse );
+ FreeWinding( w );
+ return;
+ }
+ }
+
+ // create a light from this
+ area = WindingArea (w);
+ if ( area <= 0 || area > 20000000 ) {
+ return;
+ }
+
+ numAreaLights++;
+ dl = malloc(sizeof(*dl));
+ memset (dl, 0, sizeof(*dl));
+ dl->next = lights;
+ lights = dl;
+ dl->type = emit_area;
+
+ WindingCenter( w, dl->origin );
+ dl->w = w;
+ VectorCopy ( normal, dl->normal);
+ dl->dist = DotProduct( dl->origin, normal );
+
+ value = ls->value;
+ intensity = value * area * areaScale;
+ VectorAdd( dl->origin, dl->normal, dl->origin );
+
+ VectorCopy( ls->color, dl->color );
+
+ dl->photons = intensity;
+
+ // emitColor is irrespective of the area
+ VectorScale( ls->color, value*formFactorValueScale*areaScale, dl->emitColor );
+
+ dl->si = ls;
+
+ if ( ls->contents & CONTENTS_FOG ) {
+ dl->twosided = qtrue;
+ }
+
+ // optionally create a point backsplash light
+ if ( backsplash && ls->backsplashFraction > 0 ) {
+ dl2 = malloc(sizeof(*dl));
+ memset (dl2, 0, sizeof(*dl2));
+ dl2->next = lights;
+ lights = dl2;
+ dl2->type = emit_point;
+
+ VectorMA( dl->origin, ls->backsplashDistance, normal, dl2->origin );
+
+ VectorCopy( ls->color, dl2->color );
+
+ dl2->photons = dl->photons * ls->backsplashFraction;
+ dl2->si = ls;
+ }
+}
+
+
+/*
+===============
+CountLightmaps
+===============
+*/
+void CountLightmaps( void ) {
+ int count;
+ int i;
+ dsurface_t *ds;
+
+ qprintf ("--- CountLightmaps ---\n");
+ count = 0;
+ for ( i = 0 ; i < numDrawSurfaces ; i++ ) {
+ // see if this surface is light emiting
+ ds = &drawSurfaces[i];
+ if ( ds->lightmapNum > count ) {
+ count = ds->lightmapNum;
+ }
+ }
+
+ count++;
+ numLightBytes = count * LIGHTMAP_WIDTH * LIGHTMAP_HEIGHT * 3;
+ if ( numLightBytes > MAX_MAP_LIGHTING ) {
+ Error("MAX_MAP_LIGHTING exceeded");
+ }
+
+ qprintf( "%5i drawSurfaces\n", numDrawSurfaces );
+ qprintf( "%5i lightmaps\n", count );
+}
+
+/*
+===============
+CreateSurfaceLights
+
+This creates area lights
+===============
+*/
+void CreateSurfaceLights( void ) {
+ int i, j, side;
+ dsurface_t *ds;
+ shaderInfo_t *ls;
+ winding_t *w;
+ cFacet_t *f;
+ light_t *dl;
+ vec3_t origin;
+ drawVert_t *dv;
+ int c_lightSurfaces;
+ float lightSubdivide;
+ vec3_t normal;
+
+ qprintf ("--- CreateSurfaceLights ---\n");
+ c_lightSurfaces = 0;
+
+ for ( i = 0 ; i < numDrawSurfaces ; i++ ) {
+ // see if this surface is light emiting
+ ds = &drawSurfaces[i];
+
+ ls = ShaderInfoForShader( dshaders[ ds->shaderNum].shader );
+ if ( ls->value == 0 ) {
+ continue;
+ }
+
+ // determine how much we need to chop up the surface
+ if ( ls->lightSubdivide ) {
+ lightSubdivide = ls->lightSubdivide;
+ } else {
+ lightSubdivide = defaultLightSubdivide;
+ }
+
+ c_lightSurfaces++;
+
+ // an autosprite shader will become
+ // a point light instead of an area light
+ if ( ls->autosprite ) {
+ // autosprite geometry should only have four vertexes
+ if ( surfaceTest[i] ) {
+ // curve or misc_model
+ f = surfaceTest[i]->facets;
+ if ( surfaceTest[i]->numFacets != 1 || f->numBoundaries != 4 ) {
+ _printf( "WARNING: surface at (%i %i %i) has autosprite shader but isn't a quad\n",
+ (int)f->points[0], (int)f->points[1], (int)f->points[2] );
+ }
+ VectorAdd( f->points[0], f->points[1], origin );
+ VectorAdd( f->points[2], origin, origin );
+ VectorAdd( f->points[3], origin, origin );
+ VectorScale( origin, 0.25, origin );
+ } else {
+ // normal polygon
+ dv = &drawVerts[ ds->firstVert ];
+ if ( ds->numVerts != 4 ) {
+ _printf( "WARNING: surface at (%i %i %i) has autosprite shader but %i verts\n",
+ (int)dv->xyz[0], (int)dv->xyz[1], (int)dv->xyz[2] );
+ continue;
+ }
+
+ VectorAdd( dv[0].xyz, dv[1].xyz, origin );
+ VectorAdd( dv[2].xyz, origin, origin );
+ VectorAdd( dv[3].xyz, origin, origin );
+ VectorScale( origin, 0.25, origin );
+ }
+
+
+ numPointLights++;
+ dl = malloc(sizeof(*dl));
+ memset (dl, 0, sizeof(*dl));
+ dl->next = lights;
+ lights = dl;
+
+ VectorCopy( origin, dl->origin );
+ VectorCopy( ls->color, dl->color );
+ dl->photons = ls->value * pointScale;
+ dl->type = emit_point;
+ continue;
+ }
+
+ // possibly create for both sides of the polygon
+ for ( side = 0 ; side <= ls->twoSided ; side++ ) {
+ // create area lights
+ if ( surfaceTest[i] ) {
+ // curve or misc_model
+ for ( j = 0 ; j < surfaceTest[i]->numFacets ; j++ ) {
+ f = surfaceTest[i]->facets + j;
+ w = AllocWinding( f->numBoundaries );
+ w->numpoints = f->numBoundaries;
+ memcpy( w->p, f->points, f->numBoundaries * 12 );
+
+ VectorCopy( f->surface, normal );
+ if ( side ) {
+ winding_t *t;
+
+ t = w;
+ w = ReverseWinding( t );
+ FreeWinding( t );
+ VectorSubtract( vec3_origin, normal, normal );
+ }
+ SubdivideAreaLight( ls, w, normal, lightSubdivide, qtrue );
+ }
+ } else {
+ // normal polygon
+
+ w = AllocWinding( ds->numVerts );
+ w->numpoints = ds->numVerts;
+ for ( j = 0 ; j < ds->numVerts ; j++ ) {
+ VectorCopy( drawVerts[ds->firstVert+j].xyz, w->p[j] );
+ }
+ VectorCopy( ds->lightmapVecs[2], normal );
+ if ( side ) {
+ winding_t *t;
+
+ t = w;
+ w = ReverseWinding( t );
+ FreeWinding( t );
+ VectorSubtract( vec3_origin, normal, normal );
+ }
+ SubdivideAreaLight( ls, w, normal, lightSubdivide, qtrue );
+ }
+ }
+ }
+
+ _printf( "%5i light emitting surfaces\n", c_lightSurfaces );
+}
+
+
+
+/*
+================
+FindSkyBrushes
+================
+*/
+void FindSkyBrushes( void ) {
+ int i, j;
+ dbrush_t *b;
+ skyBrush_t *sb;
+ shaderInfo_t *si;
+ dbrushside_t *s;
+
+ // find the brushes
+ for ( i = 0 ; i < numbrushes ; i++ ) {
+ b = &dbrushes[i];
+ for ( j = 0 ; j < b->numSides ; j++ ) {
+ s = &dbrushsides[ b->firstSide + j ];
+ if ( dshaders[ s->shaderNum ].surfaceFlags & SURF_SKY ) {
+ sb = &skyBrushes[ numSkyBrushes ];
+ sb->b = b;
+ sb->bounds[0][0] = -dplanes[ dbrushsides[ b->firstSide + 0 ].planeNum ].dist - 1;
+ sb->bounds[1][0] = dplanes[ dbrushsides[ b->firstSide + 1 ].planeNum ].dist + 1;
+ sb->bounds[0][1] = -dplanes[ dbrushsides[ b->firstSide + 2 ].planeNum ].dist - 1;
+ sb->bounds[1][1] = dplanes[ dbrushsides[ b->firstSide + 3 ].planeNum ].dist + 1;
+ sb->bounds[0][2] = -dplanes[ dbrushsides[ b->firstSide + 4 ].planeNum ].dist - 1;
+ sb->bounds[1][2] = dplanes[ dbrushsides[ b->firstSide + 5 ].planeNum ].dist + 1;
+ numSkyBrushes++;
+ break;
+ }
+ }
+ }
+
+ // default
+ VectorNormalize( sunDirection, sunDirection );
+
+ // find the sky shader
+ for ( i = 0 ; i < numDrawSurfaces ; i++ ) {
+ si = ShaderInfoForShader( dshaders[ drawSurfaces[i].shaderNum ].shader );
+ if ( si->surfaceFlags & SURF_SKY ) {
+ VectorCopy( si->sunLight, sunLight );
+ VectorCopy( si->sunDirection, sunDirection );
+ break;
+ }
+ }
+}
+
+/*
+=================================================================
+
+ LIGHT SETUP
+
+=================================================================
+*/
+
+/*
+==================
+FindTargetEntity
+==================
+*/
+entity_t *FindTargetEntity( const char *target ) {
+ int i;
+ const char *n;
+
+ for ( i = 0 ; i < num_entities ; i++ ) {
+ n = ValueForKey (&entities[i], "targetname");
+ if ( !strcmp (n, target) ) {
+ return &entities[i];
+ }
+ }
+
+ return NULL;
+}
+
+
+
+/*
+=============
+CreateEntityLights
+=============
+*/
+void CreateEntityLights (void)
+{
+ int i;
+ light_t *dl;
+ entity_t *e, *e2;
+ const char *name;
+ const char *target;
+ vec3_t dest;
+ const char *_color;
+ float intensity;
+ int spawnflags;
+
+ //
+ // entities
+ //
+ for ( i = 0 ; i < num_entities ; i++ ) {
+ e = &entities[i];
+ name = ValueForKey (e, "classname");
+ if (strncmp (name, "light", 5))
+ continue;
+
+ numPointLights++;
+ dl = malloc(sizeof(*dl));
+ memset (dl, 0, sizeof(*dl));
+ dl->next = lights;
+ lights = dl;
+
+ spawnflags = FloatForKey (e, "spawnflags");
+ if ( spawnflags & 1 ) {
+ dl->linearLight = qtrue;
+ }
+
+ GetVectorForKey (e, "origin", dl->origin);
+ dl->style = FloatForKey (e, "_style");
+ if (!dl->style)
+ dl->style = FloatForKey (e, "style");
+ if (dl->style < 0)
+ dl->style = 0;
+
+ intensity = FloatForKey (e, "light");
+ if (!intensity)
+ intensity = FloatForKey (e, "_light");
+ if (!intensity)
+ intensity = 300;
+ _color = ValueForKey (e, "_color");
+ if (_color && _color[0])
+ {
+ sscanf (_color, "%f %f %f", &dl->color[0],&dl->color[1],&dl->color[2]);
+ ColorNormalize (dl->color, dl->color);
+ }
+ else
+ dl->color[0] = dl->color[1] = dl->color[2] = 1.0;
+
+ intensity = intensity * pointScale;
+ dl->photons = intensity;
+
+ dl->type = emit_point;
+
+ // lights with a target will be spotlights
+ target = ValueForKey (e, "target");
+
+ if ( target[0] ) {
+ float radius;
+ float dist;
+
+ e2 = FindTargetEntity (target);
+ if (!e2) {
+ _printf ("WARNING: light at (%i %i %i) has missing target\n",
+ (int)dl->origin[0], (int)dl->origin[1], (int)dl->origin[2]);
+ } else {
+ GetVectorForKey (e2, "origin", dest);
+ VectorSubtract (dest, dl->origin, dl->normal);
+ dist = VectorNormalize (dl->normal, dl->normal);
+ radius = FloatForKey (e, "radius");
+ if ( !radius ) {
+ radius = 64;
+ }
+ if ( !dist ) {
+ dist = 64;
+ }
+ dl->radiusByDist = (radius + 16) / dist;
+ dl->type = emit_spotlight;
+ }
+ }
+ }
+}
+
+//=================================================================
+
+/*
+================
+SetEntityOrigins
+
+Find the offset values for inline models
+================
+*/
+void SetEntityOrigins( void ) {
+ int i, j;
+ entity_t *e;
+ vec3_t origin;
+ const char *key;
+ int modelnum;
+ dmodel_t *dm;
+
+ for ( i=0 ; i < num_entities ; i++ ) {
+ e = &entities[i];
+ key = ValueForKey (e, "model");
+ if ( key[0] != '*' ) {
+ continue;
+ }
+ modelnum = atoi( key + 1 );
+ dm = &dmodels[ modelnum ];
+
+ // set entity surface to true for all surfaces for this model
+ for ( j = 0 ; j < dm->numSurfaces ; j++ ) {
+ entitySurface[ dm->firstSurface + j ] = qtrue;
+ }
+
+ key = ValueForKey (e, "origin");
+ if ( !key[0] ) {
+ continue;
+ }
+ GetVectorForKey ( e, "origin", origin );
+
+ // set origin for all surfaces for this model
+ for ( j = 0 ; j < dm->numSurfaces ; j++ ) {
+ VectorCopy( origin, surfaceOrigin[ dm->firstSurface + j ] );
+ }
+ }
+}
+
+
+/*
+=================================================================
+
+
+=================================================================
+*/
+
+#define MAX_POINTS_ON_WINDINGS 64
+
+/*
+================
+PointToPolygonFormFactor
+================
+*/
+float PointToPolygonFormFactor( const vec3_t point, const vec3_t normal, const winding_t *w ) {
+ vec3_t triVector, triNormal;
+ int i, j;
+ vec3_t dirs[MAX_POINTS_ON_WINDING];
+ float total;
+ float dot, angle, facing;
+
+ for ( i = 0 ; i < w->numpoints ; i++ ) {
+ VectorSubtract( w->p[i], point, dirs[i] );
+ VectorNormalize( dirs[i], dirs[i] );
+ }
+
+ // duplicate first vertex to avoid mod operation
+ VectorCopy( dirs[0], dirs[i] );
+
+ total = 0;
+ for ( i = 0 ; i < w->numpoints ; i++ ) {
+ j = i+1;
+ dot = DotProduct( dirs[i], dirs[j] );
+
+ // roundoff can cause slight creep, which gives an IND from acos
+ if ( dot > 1.0 ) {
+ dot = 1.0;
+ } else if ( dot < -1.0 ) {
+ dot = -1.0;
+ }
+
+ angle = acos( dot );
+ CrossProduct( dirs[i], dirs[j], triVector );
+ if ( VectorNormalize( triVector, triNormal ) < 0.0001 ) {
+ continue;
+ }
+ facing = DotProduct( normal, triNormal );
+ total += facing * angle;
+
+ if ( total > 6.3 || total < -6.3 ) {
+ static qboolean printed;
+
+ if ( !printed ) {
+ printed = qtrue;
+ _printf( "WARNING: bad PointToPolygonFormFactor: %f at %1.1f %1.1f %1.1f from %1.1f %1.1f %1.1f\n", total,
+ w->p[i][0], w->p[i][1], w->p[i][2], point[0], point[1], point[2]);
+ }
+ return 0;
+ }
+
+ }
+
+ total /= 2*3.141592657; // now in the range of 0 to 1 over the entire incoming hemisphere
+
+ return total;
+}
+
+
+/*
+================
+FilterTrace
+
+Returns 0 to 1.0 filter fractions for the given trace
+================
+*/
+void FilterTrace( const vec3_t start, const vec3_t end, vec3_t filter ) {
+ float d1, d2;
+ filter_t *f;
+ int filterNum;
+ vec3_t point;
+ float frac;
+ int i;
+ float s, t;
+ int u, v;
+ int x, y;
+ byte *pixel;
+ float radius;
+ float len;
+ vec3_t total;
+
+ filter[0] = 1.0;
+ filter[1] = 1.0;
+ filter[2] = 1.0;
+
+ for ( filterNum = 0 ; filterNum < numFilters ; filterNum++ ) {
+ f = &filters[ filterNum ];
+
+ // see if the plane is crossed
+ d1 = DotProduct( start, f->plane ) - f->plane[3];
+ d2 = DotProduct( end, f->plane ) - f->plane[3];
+
+ if ( ( d1 < 0 ) == ( d2 < 0 ) ) {
+ continue;
+ }
+
+ // calculate the crossing point
+ frac = d1 / ( d1 - d2 );
+
+ for ( i = 0 ; i < 3 ; i++ ) {
+ point[i] = start[i] + frac * ( end[i] - start[i] );
+ }
+
+ VectorSubtract( point, f->origin, point );
+
+ s = DotProduct( point, f->vectors[0] );
+ t = 1.0 - DotProduct( point, f->vectors[1] );
+ if ( s < 0 || s >= 1.0 || t < 0 || t >= 1.0 ) {
+ continue;
+ }
+
+ // decide the filter size
+ radius = 10 * frac;
+ len = VectorLength( f->vectors[0] );
+ if ( !len ) {
+ continue;
+ }
+ radius = radius * len * f->si->width;
+
+ // look up the filter, taking multiple samples
+ VectorClear( total );
+ for ( u = -1 ; u <= 1 ; u++ ) {
+ for ( v = -1 ; v <=1 ; v++ ) {
+ x = s * f->si->width + u * radius;
+ if ( x < 0 ) {
+ x = 0;
+ }
+ if ( x >= f->si->width ) {
+ x = f->si->width - 1;
+ }
+ y = t * f->si->height + v * radius;
+ if ( y < 0 ) {
+ y = 0;
+ }
+ if ( y >= f->si->height ) {
+ y = f->si->height - 1;
+ }
+
+ pixel = f->si->pixels + ( y * f->si->width + x ) * 4;
+ total[0] += pixel[0];
+ total[1] += pixel[1];
+ total[2] += pixel[2];
+ }
+ }
+
+ filter[0] *= total[0]/(255.0*9);
+ filter[1] *= total[1]/(255.0*9);
+ filter[2] *= total[2]/(255.0*9);
+ }
+
+}
+
+/*
+================
+SunToPoint
+
+Returns an amount of light to add at the point
+================
+*/
+int c_sunHit, c_sunMiss;
+void SunToPoint( const vec3_t origin, traceWork_t *tw, vec3_t addLight ) {
+ int i;
+ trace_t trace;
+ skyBrush_t *b;
+ vec3_t end;
+
+ if ( !numSkyBrushes ) {
+ VectorClear( addLight );
+ return;
+ }
+
+ VectorMA( origin, MAX_WORLD_COORD * 2, sunDirection, end );
+
+ TraceLine( origin, end, &trace, qtrue, tw );
+
+ // see if trace.hit is inside a sky brush
+ for ( i = 0 ; i < numSkyBrushes ; i++) {
+ b = &skyBrushes[ i ];
+
+ // this assumes that sky brushes are axial...
+ if ( trace.hit[0] < b->bounds[0][0]
+ || trace.hit[0] > b->bounds[1][0]
+ || trace.hit[1] < b->bounds[0][1]
+ || trace.hit[1] > b->bounds[1][1]
+ || trace.hit[2] < b->bounds[0][2]
+ || trace.hit[2] > b->bounds[1][2] ) {
+ continue;
+ }
+
+
+ // trace again to get intermediate filters
+ TraceLine( origin, trace.hit, &trace, qtrue, tw );
+
+ // we hit the sky, so add sunlight
+ if ( numthreads == 1 ) {
+ c_sunHit++;
+ }
+ addLight[0] = trace.filter[0] * sunLight[0];
+ addLight[1] = trace.filter[1] * sunLight[1];
+ addLight[2] = trace.filter[2] * sunLight[2];
+
+ return;
+ }
+
+ if ( numthreads == 1 ) {
+ c_sunMiss++;
+ }
+
+ VectorClear( addLight );
+}
+
+/*
+================
+SunToPlane
+================
+*/
+void SunToPlane( const vec3_t origin, const vec3_t normal, vec3_t color, traceWork_t *tw ) {
+ float angle;
+ vec3_t sunColor;
+
+ if ( !numSkyBrushes ) {
+ return;
+ }
+
+ angle = DotProduct( normal, sunDirection );
+ if ( angle <= 0 ) {
+ return; // facing away
+ }
+
+ SunToPoint( origin, tw, sunColor );
+ VectorMA( color, angle, sunColor, color );
+}
+
+/*
+================
+LightingAtSample
+================
+*/
+void LightingAtSample( vec3_t origin, vec3_t normal, vec3_t color,
+ qboolean testOcclusion, qboolean forceSunLight, traceWork_t *tw ) {
+ light_t *light;
+ trace_t trace;
+ float angle;
+ float add;
+ float dist;
+ vec3_t dir;
+
+ VectorCopy( ambientColor, color );
+
+ // trace to all the lights
+ for ( light = lights ; light ; light = light->next ) {
+
+ //MrE: if the light is behind the surface
+ if ( DotProduct(light->origin, normal) - DotProduct(normal, origin) < 0 )
+ continue;
+ // testing exact PTPFF
+ if ( exactPointToPolygon && light->type == emit_area ) {
+ float factor;
+ float d;
+ vec3_t pushedOrigin;
+
+ // see if the point is behind the light
+ d = DotProduct( origin, light->normal ) - light->dist;
+ if ( !light->twosided ) {
+ if ( d < -1 ) {
+ continue; // point is behind light
+ }
+ }
+
+ // test occlusion and find light filters
+ // clip the line, tracing from the surface towards the light
+ if ( !notrace && testOcclusion ) {
+ TraceLine( origin, light->origin, &trace, qfalse, tw );
+
+ // other light rays must not hit anything
+ if ( trace.passSolid ) {
+ continue;
+ }
+ } else {
+ trace.filter[0] = 1.0;
+ trace.filter[1] = 1.0;
+ trace.filter[2] = 1.0;
+ }
+
+ // nudge the point so that it is clearly forward of the light
+ // so that surfaces meeting a light emiter don't get black edges
+ if ( d > -8 && d < 8 ) {
+ VectorMA( origin, (8-d), light->normal, pushedOrigin );
+ } else {
+ VectorCopy( origin, pushedOrigin );
+ }
+
+ // calculate the contribution
+ factor = PointToPolygonFormFactor( pushedOrigin, normal, light->w );
+ if ( factor <= 0 ) {
+ if ( light->twosided ) {
+ factor = -factor;
+ } else {
+ continue;
+ }
+ }
+ color[0] += factor * light->emitColor[0] * trace.filter[0];
+ color[1] += factor * light->emitColor[1] * trace.filter[1];
+ color[2] += factor * light->emitColor[2] * trace.filter[2];
+
+ continue;
+ }
+
+ // calculate the amount of light at this sample
+ if ( light->type == emit_point ) {
+ VectorSubtract( light->origin, origin, dir );
+ dist = VectorNormalize( dir, dir );
+ // clamp the distance to prevent super hot spots
+ if ( dist < 16 ) {
+ dist = 16;
+ }
+ angle = DotProduct( normal, dir );
+ if ( light->linearLight ) {
+ add = angle * light->photons * linearScale - dist;
+ if ( add < 0 ) {
+ add = 0;
+ }
+ } else {
+ add = light->photons / ( dist * dist ) * angle;
+ }
+ } else if ( light->type == emit_spotlight ) {
+ float distByNormal;
+ vec3_t pointAtDist;
+ float radiusAtDist;
+ float sampleRadius;
+ vec3_t distToSample;
+ float coneScale;
+
+ VectorSubtract( light->origin, origin, dir );
+
+ distByNormal = -DotProduct( dir, light->normal );
+ if ( distByNormal < 0 ) {
+ continue;
+ }
+ VectorMA( light->origin, distByNormal, light->normal, pointAtDist );
+ radiusAtDist = light->radiusByDist * distByNormal;
+
+ VectorSubtract( origin, pointAtDist, distToSample );
+ sampleRadius = VectorLength( distToSample );
+
+ if ( sampleRadius >= radiusAtDist ) {
+ continue; // outside the cone
+ }
+ if ( sampleRadius <= radiusAtDist - 32 ) {
+ coneScale = 1.0; // fully inside
+ } else {
+ coneScale = ( radiusAtDist - sampleRadius ) / 32.0;
+ }
+
+ dist = VectorNormalize( dir, dir );
+ // clamp the distance to prevent super hot spots
+ if ( dist < 16 ) {
+ dist = 16;
+ }
+ angle = DotProduct( normal, dir );
+ add = light->photons / ( dist * dist ) * angle * coneScale;
+
+ } else if ( light->type == emit_area ) {
+ VectorSubtract( light->origin, origin, dir );
+ dist = VectorNormalize( dir, dir );
+ // clamp the distance to prevent super hot spots
+ if ( dist < 16 ) {
+ dist = 16;
+ }
+ angle = DotProduct( normal, dir );
+ if ( angle <= 0 ) {
+ continue;
+ }
+ angle *= -DotProduct( light->normal, dir );
+ if ( angle <= 0 ) {
+ continue;
+ }
+
+ if ( light->linearLight ) {
+ add = angle * light->photons * linearScale - dist;
+ if ( add < 0 ) {
+ add = 0;
+ }
+ } else {
+ add = light->photons / ( dist * dist ) * angle;
+ }
+ }
+
+ if ( add <= 1.0 ) {
+ continue;
+ }
+
+ // clip the line, tracing from the surface towards the light
+ if ( !notrace && testOcclusion ) {
+ TraceLine( origin, light->origin, &trace, qfalse, tw );
+
+ // other light rays must not hit anything
+ if ( trace.passSolid ) {
+ continue;
+ }
+ } else {
+ trace.filter[0] = 1;
+ trace.filter[1] = 1;
+ trace.filter[2] = 1;
+ }
+
+ // add the result
+ color[0] += add * light->color[0] * trace.filter[0];
+ color[1] += add * light->color[1] * trace.filter[1];
+ color[2] += add * light->color[2] * trace.filter[2];
+ }
+
+ //
+ // trace directly to the sun
+ //
+ if ( testOcclusion || forceSunLight ) {
+ SunToPlane( origin, normal, color, tw );
+ }
+}
+
+/*
+=============
+PrintOccluded
+
+For debugging
+=============
+*/
+void PrintOccluded( byte occluded[LIGHTMAP_WIDTH*EXTRASCALE][LIGHTMAP_HEIGHT*EXTRASCALE],
+ int width, int height ) {
+ int i, j;
+
+ _printf( "\n" );
+
+ for ( i = 0 ; i < height ; i++ ) {
+ for ( j = 0 ; j < width ; j++ ) {
+ _printf("%i", (int)occluded[j][i] );
+ }
+ _printf( "\n" );
+ }
+}
+
+
+/*
+=============
+VertexLighting
+
+Vertex lighting will completely ignore occlusion, because
+shadows would not be resolvable anyway.
+=============
+*/
+void VertexLighting( dsurface_t *ds, qboolean testOcclusion, qboolean forceSunLight, float scale, traceWork_t *tw ) {
+ int i, j;
+ drawVert_t *dv;
+ vec3_t sample, normal;
+ float max;
+
+ VectorCopy( ds->lightmapVecs[2], normal );
+
+ // generate vertex lighting
+ for ( i = 0 ; i < ds->numVerts ; i++ ) {
+ dv = &drawVerts[ ds->firstVert + i ];
+
+ if ( ds->patchWidth ) {
+ LightingAtSample( dv->xyz, dv->normal, sample, testOcclusion, forceSunLight, tw );
+ }
+ else if (ds->surfaceType == MST_TRIANGLE_SOUP) {
+ LightingAtSample( dv->xyz, dv->normal, sample, testOcclusion, forceSunLight, tw );
+ }
+ else {
+ LightingAtSample( dv->xyz, normal, sample, testOcclusion, forceSunLight, tw );
+ }
+
+ if (scale >= 0)
+ VectorScale(sample, scale, sample);
+ // clamp with color normalization
+ max = sample[0];
+ if ( sample[1] > max ) {
+ max = sample[1];
+ }
+ if ( sample[2] > max ) {
+ max = sample[2];
+ }
+ if ( max > 255 ) {
+ VectorScale( sample, 255/max, sample );
+ }
+
+ // save the sample
+ for ( j = 0 ; j < 3 ; j++ ) {
+ if ( sample[j] > 255 ) {
+ sample[j] = 255;
+ }
+ dv->color[j] = sample[j];
+ }
+
+ // Don't bother writing alpha since it will already be set to 255,
+ // plus we don't want to write over alpha generated by SetTerrainTextures
+ //dv->color[3] = 255;
+ }
+}
+
+
+/*
+=================
+LinearSubdivideMesh
+
+For extra lighting, just midpoint one of the axis.
+The edges are clamped at the original edges.
+=================
+*/
+mesh_t *LinearSubdivideMesh( mesh_t *in ) {
+ int i, j;
+ mesh_t *out;
+ drawVert_t *v1, *v2, *vout;
+
+ out = malloc( sizeof( *out ) );
+
+ out->width = in->width * 2;
+ out->height = in->height;
+ out->verts = malloc( out->width * out->height * sizeof(*out->verts) );
+ for ( j = 0 ; j < in->height ; j++ ) {
+ out->verts[ j * out->width + 0 ] = in->verts[ j * in->width + 0 ];
+ out->verts[ j * out->width + out->width - 1 ] = in->verts[ j * in->width + in->width - 1 ];
+ for ( i = 1 ; i < out->width - 1 ; i+= 2 ) {
+ v1 = in->verts + j * in->width + (i >> 1);
+ v2 = v1 + 1;
+ vout = out->verts + j * out->width + i;
+
+ vout->xyz[0] = 0.75 * v1->xyz[0] + 0.25 * v2->xyz[0];
+ vout->xyz[1] = 0.75 * v1->xyz[1] + 0.25 * v2->xyz[1];
+ vout->xyz[2] = 0.75 * v1->xyz[2] + 0.25 * v2->xyz[2];
+
+ vout->normal[0] = 0.75 * v1->normal[0] + 0.25 * v2->normal[0];
+ vout->normal[1] = 0.75 * v1->normal[1] + 0.25 * v2->normal[1];
+ vout->normal[2] = 0.75 * v1->normal[2] + 0.25 * v2->normal[2];
+
+ VectorNormalize( vout->normal, vout->normal );
+
+ vout++;
+
+ vout->xyz[0] = 0.25 * v1->xyz[0] + 0.75 * v2->xyz[0];
+ vout->xyz[1] = 0.25 * v1->xyz[1] + 0.75 * v2->xyz[1];
+ vout->xyz[2] = 0.25 * v1->xyz[2] + 0.75 * v2->xyz[2];
+
+ vout->normal[0] = 0.25 * v1->normal[0] + 0.75 * v2->normal[0];
+ vout->normal[1] = 0.25 * v1->normal[1] + 0.75 * v2->normal[1];
+ vout->normal[2] = 0.25 * v1->normal[2] + 0.75 * v2->normal[2];
+
+ VectorNormalize( vout->normal, vout->normal );
+
+ }
+ }
+
+ FreeMesh( in );
+
+ return out;
+}
+
+/*
+==============
+ColorToBytes
+==============
+*/
+void ColorToBytes( const float *color, byte *colorBytes ) {
+ float max;
+ vec3_t sample;
+
+ VectorCopy( color, sample );
+
+ // clamp with color normalization
+ max = sample[0];
+ if ( sample[1] > max ) {
+ max = sample[1];
+ }
+ if ( sample[2] > max ) {
+ max = sample[2];
+ }
+ if ( max > 255 ) {
+ VectorScale( sample, 255/max, sample );
+ }
+ colorBytes[ 0 ] = sample[0];
+ colorBytes[ 1 ] = sample[1];
+ colorBytes[ 2 ] = sample[2];
+}
+
+
+
+/*
+=============
+TraceLtm
+=============
+*/
+void TraceLtm( int num ) {
+ dsurface_t *ds;
+ int i, j, k;
+ int x, y;
+ int position, numPositions;
+ vec3_t base, origin, normal;
+ byte occluded[LIGHTMAP_WIDTH*EXTRASCALE][LIGHTMAP_HEIGHT*EXTRASCALE];
+ vec3_t color[LIGHTMAP_WIDTH*EXTRASCALE][LIGHTMAP_HEIGHT*EXTRASCALE];
+ traceWork_t tw;
+ vec3_t average;
+ int count;
+ mesh_t srcMesh, *mesh, *subdivided;
+ shaderInfo_t *si;
+ static float nudge[2][9] = {
+ { 0, -1, 0, 1, -1, 1, -1, 0, 1 },
+ { 0, -1, -1, -1, 0, 0, 1, 1, 1 }
+ };
+ int sampleWidth, sampleHeight, ssize;
+ vec3_t lightmapOrigin, lightmapVecs[2];
+ int widthtable[LIGHTMAP_WIDTH], heighttable[LIGHTMAP_WIDTH];
+
+ ds = &drawSurfaces[num];
+ si = ShaderInfoForShader( dshaders[ ds->shaderNum].shader );
+
+ // vertex-lit triangle model
+ if ( ds->surfaceType == MST_TRIANGLE_SOUP ) {
+ VertexLighting( ds, !si->noVertexShadows, si->forceSunLight, 1.0, &tw );
+ return;
+ }
+
+ if ( ds->lightmapNum == -1 ) {
+ return; // doesn't need lighting at all
+ }
+
+ if (!novertexlighting) {
+ // calculate the vertex lighting for gouraud shade mode
+ VertexLighting( ds, si->vertexShadows, si->forceSunLight, si->vertexScale, &tw );
+ }
+
+ if ( ds->lightmapNum < 0 ) {
+ return; // doesn't need lightmap lighting
+ }
+
+ si = ShaderInfoForShader( dshaders[ ds->shaderNum].shader );
+ ssize = samplesize;
+ if (si->lightmapSampleSize)
+ ssize = si->lightmapSampleSize;
+
+ if (si->patchShadows)
+ tw.patchshadows = qtrue;
+ else
+ tw.patchshadows = patchshadows;
+
+ if ( ds->surfaceType == MST_PATCH ) {
+ srcMesh.width = ds->patchWidth;
+ srcMesh.height = ds->patchHeight;
+ srcMesh.verts = drawVerts + ds->firstVert;
+ mesh = SubdivideMesh( srcMesh, 8, 999 );
+ PutMeshOnCurve( *mesh );
+ MakeMeshNormals( *mesh );
+
+ subdivided = RemoveLinearMeshColumnsRows( mesh );
+ FreeMesh(mesh);
+
+ mesh = SubdivideMeshQuads( subdivided, ssize, LIGHTMAP_WIDTH, widthtable, heighttable);
+ if ( mesh->width != ds->lightmapWidth || mesh->height != ds->lightmapHeight ) {
+ Error( "Mesh lightmap miscount");
+ }
+
+ if ( extra ) {
+ mesh_t *mp;
+
+ // chop it up for more light samples (leaking memory...)
+ mp = mesh;//CopyMesh( mesh );
+ mp = LinearSubdivideMesh( mp );
+ mp = TransposeMesh( mp );
+ mp = LinearSubdivideMesh( mp );
+ mp = TransposeMesh( mp );
+
+ mesh = mp;
+ }
+ } else {
+ VectorCopy( ds->lightmapVecs[2], normal );
+
+ if ( !extra ) {
+ VectorCopy( ds->lightmapOrigin, lightmapOrigin );
+ VectorCopy( ds->lightmapVecs[0], lightmapVecs[0] );
+ VectorCopy( ds->lightmapVecs[1], lightmapVecs[1] );
+ } else {
+ // sample at a closer spacing for antialiasing
+ VectorCopy( ds->lightmapOrigin, lightmapOrigin );
+ VectorScale( ds->lightmapVecs[0], 0.5, lightmapVecs[0] );
+ VectorScale( ds->lightmapVecs[1], 0.5, lightmapVecs[1] );
+ VectorMA( lightmapOrigin, -0.5, lightmapVecs[0], lightmapOrigin );
+ VectorMA( lightmapOrigin, -0.5, lightmapVecs[1], lightmapOrigin );
+ }
+ }
+
+ if ( extra ) {
+ sampleWidth = ds->lightmapWidth * 2;
+ sampleHeight = ds->lightmapHeight * 2;
+ } else {
+ sampleWidth = ds->lightmapWidth;
+ sampleHeight = ds->lightmapHeight;
+ }
+
+ memset ( color, 0, sizeof( color ) );
+
+ // determine which samples are occluded
+ memset ( occluded, 0, sizeof( occluded ) );
+ for ( i = 0 ; i < sampleWidth ; i++ ) {
+ for ( j = 0 ; j < sampleHeight ; j++ ) {
+
+ if ( ds->patchWidth ) {
+ numPositions = 9;
+ VectorCopy( mesh->verts[j*mesh->width+i].normal, normal );
+ // VectorNormalize( normal, normal );
+ // push off of the curve a bit
+ VectorMA( mesh->verts[j*mesh->width+i].xyz, 1, normal, base );
+
+ MakeNormalVectors( normal, lightmapVecs[0], lightmapVecs[1] );
+ } else {
+ numPositions = 9;
+ for ( k = 0 ; k < 3 ; k++ ) {
+ base[k] = lightmapOrigin[k] + normal[k]
+ + i * lightmapVecs[0][k]
+ + j * lightmapVecs[1][k];
+ }
+ }
+ VectorAdd( base, surfaceOrigin[ num ], base );
+
+ // we may need to slightly nudge the sample point
+ // if directly on a wall
+ for ( position = 0 ; position < numPositions ; position++ ) {
+ // calculate lightmap sample position
+ for ( k = 0 ; k < 3 ; k++ ) {
+ origin[k] = base[k] +
+ + ( nudge[0][position]/16 ) * lightmapVecs[0][k]
+ + ( nudge[1][position]/16 ) * lightmapVecs[1][k];
+ }
+
+ if ( notrace ) {
+ break;
+ }
+ if ( !PointInSolid( origin ) ) {
+ break;
+ }
+ }
+
+ // if none of the nudges worked, this sample is occluded
+ if ( position == numPositions ) {
+ occluded[i][j] = qtrue;
+ if ( numthreads == 1 ) {
+ c_occluded++;
+ }
+ continue;
+ }
+
+ if ( numthreads == 1 ) {
+ c_visible++;
+ }
+ occluded[i][j] = qfalse;
+ LightingAtSample( origin, normal, color[i][j], qtrue, qfalse, &tw );
+ }
+ }
+
+ if ( dump ) {
+ PrintOccluded( occluded, sampleWidth, sampleHeight );
+ }
+
+ // calculate average values for occluded samples
+ for ( i = 0 ; i < sampleWidth ; i++ ) {
+ for ( j = 0 ; j < sampleHeight ; j++ ) {
+ if ( !occluded[i][j] ) {
+ continue;
+ }
+ // scan all surrounding samples
+ count = 0;
+ VectorClear( average );
+ for ( x = -1 ; x <= 1; x++ ) {
+ for ( y = -1 ; y <= 1 ; y++ ) {
+ if ( i + x < 0 || i + x >= sampleWidth ) {
+ continue;
+ }
+ if ( j + y < 0 || j + y >= sampleHeight ) {
+ continue;
+ }
+ if ( occluded[i+x][j+y] ) {
+ continue;
+ }
+ count++;
+ VectorAdd( color[i+x][j+y], average, average );
+ }
+ }
+ if ( count ) {
+ VectorScale( average, 1.0/count, color[i][j] );
+ }
+ }
+ }
+
+ // average together the values if we are extra sampling
+ if ( ds->lightmapWidth != sampleWidth ) {
+ for ( i = 0 ; i < ds->lightmapWidth ; i++ ) {
+ for ( j = 0 ; j < ds->lightmapHeight ; j++ ) {
+ for ( k = 0 ; k < 3 ; k++ ) {
+ float value, coverage;
+
+ value = color[i*2][j*2][k] + color[i*2][j*2+1][k] +
+ color[i*2+1][j*2][k] + color[i*2+1][j*2+1][k];
+ coverage = 4;
+ if ( extraWide ) {
+ // wider than box filter
+ if ( i > 0 ) {
+ value += color[i*2-1][j*2][k] + color[i*2-1][j*2+1][k];
+ value += color[i*2-2][j*2][k] + color[i*2-2][j*2+1][k];
+ coverage += 4;
+ }
+ if ( i < ds->lightmapWidth - 1 ) {
+ value += color[i*2+2][j*2][k] + color[i*2+2][j*2+1][k];
+ value += color[i*2+3][j*2][k] + color[i*2+3][j*2+1][k];
+ coverage += 4;
+ }
+ if ( j > 0 ) {
+ value += color[i*2][j*2-1][k] + color[i*2+1][j*2-1][k];
+ value += color[i*2][j*2-2][k] + color[i*2+1][j*2-2][k];
+ coverage += 4;
+ }
+ if ( j < ds->lightmapHeight - 1 ) {
+ value += color[i*2][j*2+2][k] + color[i*2+1][j*2+2][k];
+ value += color[i*2][j*2+3][k] + color[i*2+1][j*2+3][k];
+ coverage += 2;
+ }
+ }
+
+ color[i][j][k] = value / coverage;
+ }
+ }
+ }
+ }
+
+ // optionally create a debugging border around the lightmap
+ if ( lightmapBorder ) {
+ for ( i = 0 ; i < ds->lightmapWidth ; i++ ) {
+ color[i][0][0] = 255;
+ color[i][0][1] = 0;
+ color[i][0][2] = 0;
+
+ color[i][ds->lightmapHeight-1][0] = 255;
+ color[i][ds->lightmapHeight-1][1] = 0;
+ color[i][ds->lightmapHeight-1][2] = 0;
+ }
+ for ( i = 0 ; i < ds->lightmapHeight ; i++ ) {
+ color[0][i][0] = 255;
+ color[0][i][1] = 0;
+ color[0][i][2] = 0;
+
+ color[ds->lightmapWidth-1][i][0] = 255;
+ color[ds->lightmapWidth-1][i][1] = 0;
+ color[ds->lightmapWidth-1][i][2] = 0;
+ }
+ }
+
+ // clamp the colors to bytes and store off
+ for ( i = 0 ; i < ds->lightmapWidth ; i++ ) {
+ for ( j = 0 ; j < ds->lightmapHeight ; j++ ) {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + j)
+ * LIGHTMAP_WIDTH + ds->lightmapX + i;
+
+ ColorToBytes( color[i][j], lightBytes + k*3 );
+ }
+ }
+
+ if (ds->surfaceType == MST_PATCH)
+ {
+ FreeMesh(mesh);
+ }
+}
+
+
+//=============================================================================
+
+vec3_t gridMins;
+vec3_t gridSize = { 64, 64, 128 };
+int gridBounds[3];
+
+
+/*
+========================
+LightContributionToPoint
+========================
+*/
+qboolean LightContributionToPoint( const light_t *light, const vec3_t origin,
+ vec3_t color, traceWork_t *tw ) {
+ trace_t trace;
+ float add;
+
+ add = 0;
+
+ VectorClear( color );
+
+ // testing exact PTPFF
+ if ( exactPointToPolygon && light->type == emit_area ) {
+ float factor;
+ float d;
+ vec3_t normal;
+
+ // see if the point is behind the light
+ d = DotProduct( origin, light->normal ) - light->dist;
+ if ( !light->twosided ) {
+ if ( d < 1 ) {
+ return qfalse; // point is behind light
+ }
+ }
+
+ // test occlusion
+ // clip the line, tracing from the surface towards the light
+ TraceLine( origin, light->origin, &trace, qfalse, tw );
+ if ( trace.passSolid ) {
+ return qfalse;
+ }
+
+ // calculate the contribution
+ VectorSubtract( light->origin, origin, normal );
+ if ( VectorNormalize( normal, normal ) == 0 ) {
+ return qfalse;
+ }
+ factor = PointToPolygonFormFactor( origin, normal, light->w );
+ if ( factor <= 0 ) {
+ if ( light->twosided ) {
+ factor = -factor;
+ } else {
+ return qfalse;
+ }
+ }
+ VectorScale( light->emitColor, factor, color );
+ return qtrue;
+ }
+
+ // calculate the amount of light at this sample
+ if ( light->type == emit_point || light->type == emit_spotlight ) {
+ vec3_t dir;
+ float dist;
+
+ VectorSubtract( light->origin, origin, dir );
+ dist = VectorLength( dir );
+ // clamp the distance to prevent super hot spots
+ if ( dist < 16 ) {
+ dist = 16;
+ }
+ if ( light->linearLight ) {
+ add = light->photons * linearScale - dist;
+ if ( add < 0 ) {
+ add = 0;
+ }
+ } else {
+ add = light->photons / ( dist * dist );
+ }
+ } else {
+ return qfalse;
+ }
+
+ if ( add <= 1.0 ) {
+ return qfalse;
+ }
+
+ // clip the line, tracing from the surface towards the light
+ TraceLine( origin, light->origin, &trace, qfalse, tw );
+
+ // other light rays must not hit anything
+ if ( trace.passSolid ) {
+ return qfalse;
+ }
+
+ // add the result
+ color[0] = add * light->color[0];
+ color[1] = add * light->color[1];
+ color[2] = add * light->color[2];
+
+ return qtrue;
+}
+
+typedef struct {
+ vec3_t dir;
+ vec3_t color;
+} contribution_t;
+
+/*
+=============
+TraceGrid
+
+Grid samples are foe quickly determining the lighting
+of dynamically placed entities in the world
+=============
+*/
+#define MAX_CONTRIBUTIONS 1024
+void TraceGrid( int num ) {
+ int x, y, z;
+ vec3_t origin;
+ light_t *light;
+ vec3_t color;
+ int mod;
+ vec3_t directedColor;
+ vec3_t summedDir;
+ contribution_t contributions[MAX_CONTRIBUTIONS];
+ int numCon;
+ int i;
+ traceWork_t tw;
+ float addSize;
+
+ mod = num;
+ z = mod / ( gridBounds[0] * gridBounds[1] );
+ mod -= z * ( gridBounds[0] * gridBounds[1] );
+
+ y = mod / gridBounds[0];
+ mod -= y * gridBounds[0];
+
+ x = mod;
+
+ origin[0] = gridMins[0] + x * gridSize[0];
+ origin[1] = gridMins[1] + y * gridSize[1];
+ origin[2] = gridMins[2] + z * gridSize[2];
+
+ if ( PointInSolid( origin ) ) {
+ vec3_t baseOrigin;
+ int step;
+
+ VectorCopy( origin, baseOrigin );
+
+ // try to nudge the origin around to find a valid point
+ for ( step = 9 ; step <= 18 ; step += 9 ) {
+ for ( i = 0 ; i < 8 ; i++ ) {
+ VectorCopy( baseOrigin, origin );
+ if ( i & 1 ) {
+ origin[0] += step;
+ } else {
+ origin[0] -= step;
+ }
+ if ( i & 2 ) {
+ origin[1] += step;
+ } else {
+ origin[1] -= step;
+ }
+ if ( i & 4 ) {
+ origin[2] += step;
+ } else {
+ origin[2] -= step;
+ }
+
+ if ( !PointInSolid( origin ) ) {
+ break;
+ }
+ }
+ if ( i != 8 ) {
+ break;
+ }
+ }
+ if ( step > 18 ) {
+ // can't find a valid point at all
+ for ( i = 0 ; i < 8 ; i++ ) {
+ gridData[ num*8 + i ] = 0;
+ }
+ return;
+ }
+ }
+
+ VectorClear( summedDir );
+
+ // trace to all the lights
+
+ // find the major light direction, and divide the
+ // total light between that along the direction and
+ // the remaining in the ambient
+ numCon = 0;
+ for ( light = lights ; light ; light = light->next ) {
+ vec3_t add;
+ vec3_t dir;
+ float addSize;
+
+ if ( !LightContributionToPoint( light, origin, add, &tw ) ) {
+ continue;
+ }
+
+ VectorSubtract( light->origin, origin, dir );
+ VectorNormalize( dir, dir );
+
+ VectorCopy( add, contributions[numCon].color );
+ VectorCopy( dir, contributions[numCon].dir );
+ numCon++;
+
+ addSize = VectorLength( add );
+ VectorMA( summedDir, addSize, dir, summedDir );
+
+ if ( numCon == MAX_CONTRIBUTIONS-1 ) {
+ break;
+ }
+ }
+
+ //
+ // trace directly to the sun
+ //
+ SunToPoint( origin, &tw, color );
+ addSize = VectorLength( color );
+ if ( addSize > 0 ) {
+ VectorCopy( color, contributions[numCon].color );
+ VectorCopy( sunDirection, contributions[numCon].dir );
+ VectorMA( summedDir, addSize, sunDirection, summedDir );
+ numCon++;
+ }
+
+
+ // now that we have identified the primary light direction,
+ // go back and seperate all the light into directed and ambient
+ VectorNormalize( summedDir, summedDir );
+ VectorCopy( ambientColor, color );
+ VectorClear( directedColor );
+
+ for ( i = 0 ; i < numCon ; i++ ) {
+ float d;
+
+ d = DotProduct( contributions[i].dir, summedDir );
+ if ( d < 0 ) {
+ d = 0;
+ }
+
+ VectorMA( directedColor, d, contributions[i].color, directedColor );
+
+ // the ambient light will be at 1/4 the value of directed light
+ d = 0.25 * ( 1.0 - d );
+ VectorMA( color, d, contributions[i].color, color );
+ }
+
+ // now do some fudging to keep the ambient from being too low
+ VectorMA( color, 0.25, directedColor, color );
+
+ //
+ // save the resulting value out
+ //
+ ColorToBytes( color, gridData + num*8 );
+ ColorToBytes( directedColor, gridData + num*8 + 3 );
+
+ VectorNormalize( summedDir, summedDir );
+ NormalToLatLong( summedDir, gridData + num*8 + 6);
+}
+
+
+/*
+=============
+SetupGrid
+=============
+*/
+void SetupGrid( void ) {
+ int i;
+ vec3_t maxs;
+
+ for ( i = 0 ; i < 3 ; i++ ) {
+ gridMins[i] = gridSize[i] * ceil( dmodels[0].mins[i] / gridSize[i] );
+ maxs[i] = gridSize[i] * floor( dmodels[0].maxs[i] / gridSize[i] );
+ gridBounds[i] = (maxs[i] - gridMins[i])/gridSize[i] + 1;
+ }
+
+ numGridPoints = gridBounds[0] * gridBounds[1] * gridBounds[2];
+ if (numGridPoints * 8 >= MAX_MAP_LIGHTGRID)
+ Error("MAX_MAP_LIGHTGRID");
+ qprintf( "%5i gridPoints\n", numGridPoints );
+}
+
+//=============================================================================
+
+/*
+=============
+RemoveLightsInSolid
+=============
+*/
+void RemoveLightsInSolid(void)
+{
+ light_t *light, *prev;
+ int numsolid = 0;
+
+ prev = NULL;
+ for ( light = lights ; light ; ) {
+ if (PointInSolid(light->origin))
+ {
+ if (prev) prev->next = light->next;
+ else lights = light->next;
+ if (light->w)
+ FreeWinding(light->w);
+ free(light);
+ numsolid++;
+ if (prev)
+ light = prev->next;
+ else
+ light = lights;
+ }
+ else
+ {
+ prev = light;
+ light = light->next;
+ }
+ }
+ _printf (" %7i lights in solid\n", numsolid);
+}
+
+/*
+=============
+LightWorld
+=============
+*/
+void LightWorld (void) {
+ float f;
+
+ // determine the number of grid points
+ SetupGrid();
+
+ // find the optional world ambient
+ GetVectorForKey( &entities[0], "_color", ambientColor );
+ f = FloatForKey( &entities[0], "ambient" );
+ VectorScale( ambientColor, f, ambientColor );
+
+ // create lights out of patches and lights
+ qprintf ("--- CreateLights ---\n");
+ CreateEntityLights ();
+ qprintf ("%i point lights\n", numPointLights);
+ qprintf ("%i area lights\n", numAreaLights);
+
+ if (!nogridlighting) {
+ qprintf ("--- TraceGrid ---\n");
+ RunThreadsOnIndividual( numGridPoints, qtrue, TraceGrid );
+ qprintf( "%i x %i x %i = %i grid\n", gridBounds[0], gridBounds[1],
+ gridBounds[2], numGridPoints);
+ }
+
+ qprintf ("--- TraceLtm ---\n");
+ RunThreadsOnIndividual( numDrawSurfaces, qtrue, TraceLtm );
+ qprintf( "%5i visible samples\n", c_visible );
+ qprintf( "%5i occluded samples\n", c_occluded );
+}
+
+/*
+========
+CreateFilters
+
+EXPERIMENTAL, UNUSED
+
+Look for transparent light filter surfaces.
+
+This will only work for flat 3*3 patches that exactly hold one copy of the texture.
+========
+*/
+#define PLANAR_PATCH_EPSILON 0.1
+void CreateFilters( void ) {
+ int i;
+ filter_t *f;
+ dsurface_t *ds;
+ shaderInfo_t *si;
+ drawVert_t *v1, *v2, *v3;
+ vec3_t d1, d2;
+ int vertNum;
+
+ numFilters = 0;
+
+ return;
+
+ for ( i = 0 ; i < numDrawSurfaces ; i++ ) {
+ ds = &drawSurfaces[i];
+ if ( !ds->patchWidth ) {
+ continue;
+ }
+ si = ShaderInfoForShader( dshaders[ ds->shaderNum ].shader );
+/*
+ if ( !(si->surfaceFlags & SURF_LIGHTFILTER) ) {
+ continue;
+ }
+*/
+
+ // we have a filter patch
+ v1 = &drawVerts[ ds->firstVert ];
+
+ if ( ds->patchWidth != 3 || ds->patchHeight != 3 ) {
+ _printf("WARNING: patch at %i %i %i has SURF_LIGHTFILTER but isn't a 3 by 3\n",
+ v1->xyz[0], v1->xyz[1], v1->xyz[2] );
+ continue;
+ }
+
+ if ( numFilters == MAX_FILTERS ) {
+ Error( "MAX_FILTERS" );
+ }
+ f = &filters[ numFilters ];
+ numFilters++;
+
+ v2 = &drawVerts[ ds->firstVert + 2 ];
+ v3 = &drawVerts[ ds->firstVert + 6 ];
+
+ VectorSubtract( v2->xyz, v1->xyz, d1 );
+ VectorSubtract( v3->xyz, v1->xyz, d2 );
+ VectorNormalize( d1, d1 );
+ VectorNormalize( d2, d2 );
+ CrossProduct( d1, d2, f->plane );
+ f->plane[3] = DotProduct( v1->xyz, f->plane );
+
+ // make sure all the control points are on the plane
+ for ( vertNum = 0 ; vertNum < ds->numVerts ; vertNum++ ) {
+ float d;
+
+ d = DotProduct( drawVerts[ ds->firstVert + vertNum ].xyz, f->plane ) - f->plane[3];
+ if ( fabs( d ) > PLANAR_PATCH_EPSILON ) {
+ break;
+ }
+ }
+ if ( vertNum != ds->numVerts ) {
+ numFilters--;
+ _printf("WARNING: patch at %i %i %i has SURF_LIGHTFILTER but isn't flat\n",
+ v1->xyz[0], v1->xyz[1], v1->xyz[2] );
+ continue;
+ }
+ }
+
+ f = &filters[0];
+ numFilters = 1;
+
+ f->plane[0] = 1;
+ f->plane[1] = 0;
+ f->plane[2] = 0;
+ f->plane[3] = 448;
+
+ f->origin[0] = 448;
+ f->origin[1] = 192;
+ f->origin[2] = 0;
+
+ f->vectors[0][0] = 0;
+ f->vectors[0][1] = -1.0 / 128;
+ f->vectors[0][2] = 0;
+
+ f->vectors[1][0] = 0;
+ f->vectors[1][1] = 0;
+ f->vectors[1][2] = 1.0 / 128;
+
+ f->si = ShaderInfoForShader( "textures/hell/blocks11ct" );
+}
+
+/*
+=============
+VertexLightingThread
+=============
+*/
+void VertexLightingThread(int num) {
+ dsurface_t *ds;
+ traceWork_t tw;
+ shaderInfo_t *si;
+
+ ds = &drawSurfaces[num];
+
+ // vertex-lit triangle model
+ if ( ds->surfaceType == MST_TRIANGLE_SOUP ) {
+ return;
+ }
+
+ if (novertexlighting)
+ return;
+
+ if ( ds->lightmapNum == -1 ) {
+ return; // doesn't need lighting at all
+ }
+
+ si = ShaderInfoForShader( dshaders[ ds->shaderNum].shader );
+
+ // calculate the vertex lighting for gouraud shade mode
+ VertexLighting( ds, si->vertexShadows, si->forceSunLight, si->vertexScale, &tw );
+}
+
+/*
+=============
+TriSoupLightingThread
+=============
+*/
+void TriSoupLightingThread(int num) {
+ dsurface_t *ds;
+ traceWork_t tw;
+ shaderInfo_t *si;
+
+ ds = &drawSurfaces[num];
+ si = ShaderInfoForShader( dshaders[ ds->shaderNum].shader );
+
+ // vertex-lit triangle model
+ if ( ds->surfaceType == MST_TRIANGLE_SOUP ) {
+ VertexLighting( ds, !si->noVertexShadows, si->forceSunLight, 1.0, &tw );
+ }
+}
+
+/*
+=============
+GridAndVertexLighting
+=============
+*/
+void GridAndVertexLighting(void) {
+ SetupGrid();
+
+ FindSkyBrushes();
+ CreateFilters();
+ InitTrace();
+ CreateEntityLights ();
+ CreateSurfaceLights();
+
+ if (!nogridlighting) {
+ _printf ("--- TraceGrid ---\n");
+ RunThreadsOnIndividual( numGridPoints, qtrue, TraceGrid );
+ }
+
+ if (!novertexlighting) {
+ _printf ("--- Vertex Lighting ---\n");
+ RunThreadsOnIndividual( numDrawSurfaces, qtrue, VertexLightingThread );
+ }
+
+ _printf("--- Model Lighting ---\n");
+ RunThreadsOnIndividual( numDrawSurfaces, qtrue, TriSoupLightingThread );
+}
+
+/*
+========
+LightMain
+
+========
+*/
+int LightMain (int argc, char **argv) {
+ int i;
+ double start, end;
+ const char *value;
+
+ _printf ("----- Lighting ----\n");
+
+ verbose = qfalse;
+
+ for (i=1 ; i<argc ; i++) {
+ if (!strcmp(argv[i],"-tempname"))
+ {
+ i++;
+ } else if (!strcmp(argv[i],"-v")) {
+ verbose = qtrue;
+ } else if (!strcmp(argv[i],"-threads")) {
+ numthreads = atoi (argv[i+1]);
+ i++;
+ } else if (!strcmp(argv[i],"-area")) {
+ areaScale *= atof(argv[i+1]);
+ _printf ("area light scaling at %f\n", areaScale);
+ i++;
+ } else if (!strcmp(argv[i],"-point")) {
+ pointScale *= atof(argv[i+1]);
+ _printf ("point light scaling at %f\n", pointScale);
+ i++;
+ } else if (!strcmp(argv[i],"-notrace")) {
+ notrace = qtrue;
+ _printf ("No occlusion tracing\n");
+ } else if (!strcmp(argv[i],"-patchshadows")) {
+ patchshadows = qtrue;
+ _printf ("Patch shadow casting enabled\n");
+ } else if (!strcmp(argv[i],"-extra")) {
+ extra = qtrue;
+ _printf ("Extra detail tracing\n");
+ } else if (!strcmp(argv[i],"-extrawide")) {
+ extra = qtrue;
+ extraWide = qtrue;
+ _printf ("Extra wide detail tracing\n");
+ } else if (!strcmp(argv[i], "-samplesize")) {
+ samplesize = atoi(argv[i+1]);
+ if (samplesize < 1) samplesize = 1;
+ i++;
+ _printf("lightmap sample size is %dx%d units\n", samplesize, samplesize);
+ } else if (!strcmp(argv[i], "-novertex")) {
+ novertexlighting = qtrue;
+ _printf("no vertex lighting = true\n");
+ } else if (!strcmp(argv[i], "-nogrid")) {
+ nogridlighting = qtrue;
+ _printf("no grid lighting = true\n");
+ } else if (!strcmp(argv[i],"-border")) {
+ lightmapBorder = qtrue;
+ _printf ("Adding debug border to lightmaps\n");
+ } else if (!strcmp(argv[i],"-nosurf")) {
+ noSurfaces = qtrue;
+ _printf ("Not tracing against surfaces\n" );
+ } else if (!strcmp(argv[i],"-dump")) {
+ dump = qtrue;
+ _printf ("Dumping occlusion maps\n");
+ } else {
+ break;
+ }
+ }
+
+ ThreadSetDefault ();
+
+ if (i != argc - 1) {
+ _printf("usage: q3map -light [-<switch> [-<switch> ...]] <mapname>\n"
+ "\n"
+ "Switches:\n"
+ " v = verbose output\n"
+ " threads <X> = set number of threads to X\n"
+ " area <V> = set the area light scale to V\n"
+ " point <W> = set the point light scale to W\n"
+ " notrace = don't cast any shadows\n"
+ " extra = enable super sampling for anti-aliasing\n"
+ " extrawide = same as extra but smoothen more\n"
+ " nogrid = don't calculate light grid for dynamic model lighting\n"
+ " novertex = don't calculate vertex lighting\n"
+ " samplesize <N> = set the lightmap pixel size to NxN units\n");
+ exit(0);
+ }
+
+ start = I_FloatTime ();
+
+ SetQdirFromPath (argv[i]);
+
+#ifdef _WIN32
+ InitPakFile(gamedir, NULL);
+#endif
+
+ strcpy (source, ExpandArg(argv[i]));
+ StripExtension (source);
+ DefaultExtension (source, ".bsp");
+
+ LoadShaderInfo();
+
+ _printf ("reading %s\n", source);
+
+ LoadBSPFile (source);
+
+ FindSkyBrushes();
+
+ ParseEntities();
+
+ value = ValueForKey( &entities[0], "gridsize" );
+ if (strlen(value)) {
+ sscanf( value, "%f %f %f", &gridSize[0], &gridSize[1], &gridSize[2] );
+ _printf("grid size = {%1.1f, %1.1f, %1.1f}\n", gridSize[0], gridSize[1], gridSize[2]);
+ }
+
+ CreateFilters();
+
+ InitTrace();
+
+ SetEntityOrigins();
+
+ CountLightmaps();
+
+ CreateSurfaceLights();
+
+ LightWorld();
+
+ _printf ("writing %s\n", source);
+ WriteBSPFile (source);
+
+ end = I_FloatTime ();
+ _printf ("%5.0f seconds elapsed\n", end-start);
+
+ return 0;
+}
+
diff --git a/q3map/light.h b/q3map/light.h
new file mode 100755
index 0000000..5faa24a
--- /dev/null
+++ b/q3map/light.h
@@ -0,0 +1,151 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "cmdlib.h"
+#include "mathlib.h"
+#include "bspfile.h"
+#include "polylib.h"
+#include "imagelib.h"
+#include "threads.h"
+#include "scriplib.h"
+
+#include "shaders.h"
+#include "mesh.h"
+
+
+
+typedef enum
+{
+ emit_point,
+ emit_area,
+ emit_spotlight,
+ emit_sun
+} emittype_t;
+
+#define MAX_LIGHT_EDGES 8
+typedef struct light_s
+{
+ struct light_s *next;
+ emittype_t type;
+ struct shaderInfo_s *si;
+
+ vec3_t origin;
+ vec3_t normal; // for surfaces, spotlights, and suns
+ float dist; // plane location along normal
+
+ qboolean linearLight;
+ int photons;
+ int style;
+ vec3_t color;
+ float radiusByDist; // for spotlights
+
+ qboolean twosided; // fog lights both sides
+
+ winding_t *w;
+ vec3_t emitColor; // full out-of-gamut value
+} light_t;
+
+
+extern float lightscale;
+extern float ambient;
+extern float maxlight;
+extern float direct_scale;
+extern float entity_scale;
+
+extern qboolean noSurfaces;
+
+//===============================================================
+
+// light_trace.c
+
+// a facet is a subdivided element of a patch aproximation or model
+typedef struct cFacet_s {
+ float surface[4];
+ int numBoundaries; // either 3 or 4, anything less is degenerate
+ float boundaries[4][4]; // positive is outside the bounds
+
+ vec3_t points[4]; // needed for area light subdivision
+
+ float textureMatrix[2][4]; // compute texture coordinates at point of impact for translucency
+} cFacet_t;
+
+typedef struct {
+ vec3_t mins, maxs;
+ vec3_t origin;
+ float radius;
+
+ qboolean patch;
+
+ int numFacets;
+ cFacet_t *facets;
+
+ shaderInfo_t *shader; // for translucency
+} surfaceTest_t;
+
+
+typedef struct {
+ vec3_t filter; // starts out 1.0, 1.0, 1.0, may be reduced if
+ // transparent surfaces are crossed
+
+ vec3_t hit; // the impact point of a completely opaque surface
+ float hitFraction; // 0 = at start, 1.0 = at end
+ qboolean passSolid;
+} trace_t;
+
+extern surfaceTest_t *surfaceTest[MAX_MAP_DRAW_SURFS];
+
+void InitTrace( void );
+
+// traceWork_t is only a parameter to crutch up poor large local allocations on
+// winNT and macOS. It should be allocated in the worker function, but never
+// looked at.
+typedef struct {
+ vec3_t start, end;
+ int numOpenLeafs;
+ int openLeafNumbers[MAX_MAP_LEAFS];
+ trace_t *trace;
+ int patchshadows;
+} traceWork_t;
+
+void TraceLine( const vec3_t start, const vec3_t stop, trace_t *trace,
+ qboolean testAll, traceWork_t *tw );
+qboolean PointInSolid( vec3_t start );
+
+//===============================================================
+
+//===============================================================
+
+
+typedef struct {
+ int textureNum;
+ int x, y, width, height;
+
+ // for patches
+ qboolean patch;
+ mesh_t mesh;
+
+ // for faces
+ vec3_t origin;
+ vec3_t vecs[3];
+} lightmap_t;
+
+
diff --git a/q3map/light_trace.c b/q3map/light_trace.c
new file mode 100755
index 0000000..f8a51e7
--- /dev/null
+++ b/q3map/light_trace.c
@@ -0,0 +1,944 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "light.h"
+
+
+
+#define CURVE_FACET_ERROR 8
+
+int c_totalTrace;
+int c_cullTrace, c_testTrace;
+int c_testFacets;
+
+surfaceTest_t *surfaceTest[MAX_MAP_DRAW_SURFS];
+
+/*
+=====================
+CM_GenerateBoundaryForPoints
+=====================
+*/
+void CM_GenerateBoundaryForPoints( float boundary[4], float plane[4], vec3_t a, vec3_t b ) {
+ vec3_t d1;
+
+ // amke a perpendicular vector to the edge and the surface
+ VectorSubtract( b, a, d1 );
+ CrossProduct( plane, d1, boundary );
+ VectorNormalize( boundary, boundary );
+ boundary[3] = DotProduct( a, boundary );
+}
+
+/*
+=====================
+TextureMatrixFromPoints
+=====================
+*/
+void TextureMatrixFromPoints( cFacet_t *f, drawVert_t *a, drawVert_t *b, drawVert_t *c ) {
+ int i, j;
+ float t;
+ float m[3][4];
+ float s;
+
+ // This is an incredibly stupid way of solving a three variable equation
+ for ( i = 0 ; i < 2 ; i++ ) {
+
+ m[0][0] = a->xyz[0];
+ m[0][1] = a->xyz[1];
+ m[0][2] = a->xyz[2];
+ m[0][3] = a->st[i];
+
+ m[1][0] = b->xyz[0];
+ m[1][1] = b->xyz[1];
+ m[1][2] = b->xyz[2];
+ m[1][3] = b->st[i];
+
+ m[2][0] = c->xyz[0];
+ m[2][1] = c->xyz[1];
+ m[2][2] = c->xyz[2];
+ m[2][3] = c->st[i];
+
+ if ( fabs(m[1][0]) > fabs(m[0][0]) && fabs(m[1][0]) > fabs(m[2][0]) ) {
+ for ( j = 0 ; j < 4 ; j ++ ) {
+ t = m[0][j];
+ m[0][j] = m[1][j];
+ m[1][j] = t;
+ }
+ } else if ( fabs(m[2][0]) > fabs(m[0][0]) && fabs(m[2][0]) > fabs(m[1][0]) ) {
+ for ( j = 0 ; j < 4 ; j ++ ) {
+ t = m[0][j];
+ m[0][j] = m[2][j];
+ m[2][j] = t;
+ }
+ }
+
+ s = 1.0 / m[0][0];
+ m[0][0] *= s;
+ m[0][1] *= s;
+ m[0][2] *= s;
+ m[0][3] *= s;
+
+ s = m[1][0];
+ m[1][0] -= m[0][0] * s;
+ m[1][1] -= m[0][1] * s;
+ m[1][2] -= m[0][2] * s;
+ m[1][3] -= m[0][3] * s;
+
+ s = m[2][0];
+ m[2][0] -= m[0][0] * s;
+ m[2][1] -= m[0][1] * s;
+ m[2][2] -= m[0][2] * s;
+ m[2][3] -= m[0][3] * s;
+
+ if ( fabs(m[2][1]) > fabs(m[1][1]) ) {
+ for ( j = 0 ; j < 4 ; j ++ ) {
+ t = m[1][j];
+ m[1][j] = m[2][j];
+ m[2][j] = t;
+ }
+ }
+
+ s = 1.0 / m[1][1];
+ m[1][0] *= s;
+ m[1][1] *= s;
+ m[1][2] *= s;
+ m[1][3] *= s;
+
+ s = m[2][1];
+ m[2][0] -= m[1][0] * s;
+ m[2][1] -= m[1][1] * s;
+ m[2][2] -= m[1][2] * s;
+ m[2][3] -= m[1][3] * s;
+
+ s = 1.0 / m[2][2];
+ m[2][0] *= s;
+ m[2][1] *= s;
+ m[2][2] *= s;
+ m[2][3] *= s;
+
+ f->textureMatrix[i][2] = m[2][3];
+ f->textureMatrix[i][1] = m[1][3] - f->textureMatrix[i][2] * m[1][2];
+ f->textureMatrix[i][0] = m[0][3] - f->textureMatrix[i][2] * m[0][2] - f->textureMatrix[i][1] * m[0][1];
+
+ f->textureMatrix[i][3] = 0;
+/*
+ s = fabs( DotProduct( a->xyz, f->textureMatrix[i] ) - a->st[i] );
+ if ( s > 0.01 ) {
+ Error( "Bad textureMatrix" );
+ }
+ s = fabs( DotProduct( b->xyz, f->textureMatrix[i] ) - b->st[i] );
+ if ( s > 0.01 ) {
+ Error( "Bad textureMatrix" );
+ }
+ s = fabs( DotProduct( c->xyz, f->textureMatrix[i] ) - c->st[i] );
+ if ( s > 0.01 ) {
+ Error( "Bad textureMatrix" );
+ }
+*/
+ }
+}
+
+/*
+=====================
+CM_GenerateFacetFor3Points
+=====================
+*/
+qboolean CM_GenerateFacetFor3Points( cFacet_t *f, drawVert_t *a, drawVert_t *b, drawVert_t *c ) {
+ // if we can't generate a valid plane for the points, ignore the facet
+ if ( !PlaneFromPoints( f->surface, a->xyz, b->xyz, c->xyz ) ) {
+ f->numBoundaries = 0;
+ return qfalse;
+ }
+
+ // make boundaries
+ f->numBoundaries = 3;
+
+ CM_GenerateBoundaryForPoints( f->boundaries[0], f->surface, a->xyz, b->xyz );
+ CM_GenerateBoundaryForPoints( f->boundaries[1], f->surface, b->xyz, c->xyz );
+ CM_GenerateBoundaryForPoints( f->boundaries[2], f->surface, c->xyz, a->xyz );
+
+ VectorCopy( a->xyz, f->points[0] );
+ VectorCopy( b->xyz, f->points[1] );
+ VectorCopy( c->xyz, f->points[2] );
+
+ TextureMatrixFromPoints( f, a, b, c );
+
+ return qtrue;
+}
+
+/*
+=====================
+CM_GenerateFacetFor4Points
+
+Attempts to use four points as a planar quad
+=====================
+*/
+#define PLANAR_EPSILON 0.1
+qboolean CM_GenerateFacetFor4Points( cFacet_t *f, drawVert_t *a, drawVert_t *b, drawVert_t *c, drawVert_t *d ) {
+ float dist;
+ int i;
+ vec4_t plane;
+
+ // if we can't generate a valid plane for the points, ignore the facet
+ if ( !PlaneFromPoints( f->surface, a->xyz, b->xyz, c->xyz ) ) {
+ f->numBoundaries = 0;
+ return qfalse;
+ }
+
+ // if the fourth point is also on the plane, we can make a quad facet
+ dist = DotProduct( d->xyz, f->surface ) - f->surface[3];
+ if ( fabs( dist ) > PLANAR_EPSILON ) {
+ f->numBoundaries = 0;
+ return qfalse;
+ }
+
+ // make boundaries
+ f->numBoundaries = 4;
+
+ CM_GenerateBoundaryForPoints( f->boundaries[0], f->surface, a->xyz, b->xyz );
+ CM_GenerateBoundaryForPoints( f->boundaries[1], f->surface, b->xyz, c->xyz );
+ CM_GenerateBoundaryForPoints( f->boundaries[2], f->surface, c->xyz, d->xyz );
+ CM_GenerateBoundaryForPoints( f->boundaries[3], f->surface, d->xyz, a->xyz );
+
+ VectorCopy( a->xyz, f->points[0] );
+ VectorCopy( b->xyz, f->points[1] );
+ VectorCopy( c->xyz, f->points[2] );
+ VectorCopy( d->xyz, f->points[3] );
+
+ for (i = 1; i < 4; i++)
+ {
+ if ( !PlaneFromPoints( plane, f->points[i], f->points[(i+1) % 4], f->points[(i+2) % 4]) ) {
+ f->numBoundaries = 0;
+ return qfalse;
+ }
+
+ if (DotProduct(f->surface, plane) < 0.9) {
+ f->numBoundaries = 0;
+ return qfalse;
+ }
+ }
+
+ TextureMatrixFromPoints( f, a, b, c );
+
+ return qtrue;
+}
+
+
+
+
+/*
+===============
+SphereFromBounds
+===============
+*/
+void SphereFromBounds( vec3_t mins, vec3_t maxs, vec3_t origin, float *radius ) {
+ vec3_t temp;
+
+ VectorAdd( mins, maxs, origin );
+ VectorScale( origin, 0.5, origin );
+ VectorSubtract( maxs, origin, temp );
+ *radius = VectorLength( temp );
+}
+
+
+/*
+====================
+FacetsForTriangleSurface
+====================
+*/
+void FacetsForTriangleSurface( dsurface_t *dsurf, shaderInfo_t *si, surfaceTest_t *test ) {
+ int i;
+ drawVert_t *v1, *v2, *v3, *v4;
+ int count;
+ int i1, i2, i3, i4, i5, i6;
+
+ test->patch = qfalse;
+ test->numFacets = dsurf->numIndexes / 3;
+ test->facets = malloc( sizeof( test->facets[0] ) * test->numFacets );
+ test->shader = si;
+
+ count = 0;
+ for ( i = 0 ; i < test->numFacets ; i++ ) {
+ i1 = drawIndexes[ dsurf->firstIndex + i*3 ];
+ i2 = drawIndexes[ dsurf->firstIndex + i*3 + 1 ];
+ i3 = drawIndexes[ dsurf->firstIndex + i*3 + 2 ];
+
+ v1 = &drawVerts[ dsurf->firstVert + i1 ];
+ v2 = &drawVerts[ dsurf->firstVert + i2 ];
+ v3 = &drawVerts[ dsurf->firstVert + i3 ];
+
+ // try and make a quad out of two triangles
+ if ( i != test->numFacets - 1 ) {
+ i4 = drawIndexes[ dsurf->firstIndex + i*3 + 3 ];
+ i5 = drawIndexes[ dsurf->firstIndex + i*3 + 4 ];
+ i6 = drawIndexes[ dsurf->firstIndex + i*3 + 5 ];
+ if ( i4 == i3 && i5 == i2 ) {
+ v4 = &drawVerts[ dsurf->firstVert + i6 ];
+ if ( CM_GenerateFacetFor4Points( &test->facets[count], v1, v2, v4, v3 ) ) {
+ count++;
+ i++; // skip next tri
+ continue;
+ }
+ }
+ }
+
+ if (CM_GenerateFacetFor3Points( &test->facets[count], v1, v2, v3 ))
+ count++;
+ }
+
+ // we may have turned some pairs into quads
+ test->numFacets = count;
+}
+
+/*
+====================
+FacetsForPatch
+====================
+*/
+void FacetsForPatch( dsurface_t *dsurf, shaderInfo_t *si, surfaceTest_t *test ) {
+ int i, j;
+ drawVert_t *v1, *v2, *v3, *v4;
+ int count;
+ mesh_t srcMesh, *subdivided, *mesh;
+
+ srcMesh.width = dsurf->patchWidth;
+ srcMesh.height = dsurf->patchHeight;
+ srcMesh.verts = &drawVerts[ dsurf->firstVert ];
+
+ //subdivided = SubdivideMesh( mesh, CURVE_FACET_ERROR, 9999 );
+ mesh = SubdivideMesh( srcMesh, 8, 999 );
+ PutMeshOnCurve( *mesh );
+ MakeMeshNormals( *mesh );
+
+ subdivided = RemoveLinearMeshColumnsRows( mesh );
+ FreeMesh(mesh);
+
+ test->patch = qtrue;
+ test->numFacets = ( subdivided->width - 1 ) * ( subdivided->height - 1 ) * 2;
+ test->facets = malloc( sizeof( test->facets[0] ) * test->numFacets );
+ test->shader = si;
+
+ count = 0;
+ for ( i = 0 ; i < subdivided->width - 1 ; i++ ) {
+ for ( j = 0 ; j < subdivided->height - 1 ; j++ ) {
+
+ v1 = subdivided->verts + j * subdivided->width + i;
+ v2 = v1 + 1;
+ v3 = v1 + subdivided->width + 1;
+ v4 = v1 + subdivided->width;
+
+ if ( CM_GenerateFacetFor4Points( &test->facets[count], v1, v4, v3, v2 ) ) {
+ count++;
+ } else {
+ if (CM_GenerateFacetFor3Points( &test->facets[count], v1, v4, v3 ))
+ count++;
+ if (CM_GenerateFacetFor3Points( &test->facets[count], v1, v3, v2 ))
+ count++;
+ }
+ }
+ }
+ test->numFacets = count;
+ FreeMesh(subdivided);
+}
+
+
+/*
+=====================
+InitSurfacesForTesting
+
+Builds structures to speed the ray tracing against surfaces
+=====================
+*/
+void InitSurfacesForTesting( void ) {
+
+ int i, j;
+ dsurface_t *dsurf;
+ surfaceTest_t *test;
+ drawVert_t *dvert;
+ shaderInfo_t *si;
+
+ for ( i = 0 ; i < numDrawSurfaces ; i++ ) {
+ dsurf = &drawSurfaces[ i ];
+ if ( !dsurf->numIndexes && !dsurf->patchWidth ) {
+ continue;
+ }
+
+ // don't make surfaces for transparent objects
+ // because we want light to pass through them
+ si = ShaderInfoForShader( dshaders[ dsurf->shaderNum].shader );
+ if ( (si->contents & CONTENTS_TRANSLUCENT) && !(si->surfaceFlags & SURF_ALPHASHADOW) ) {
+ continue;
+ }
+
+ test = malloc( sizeof( *test ) );
+ surfaceTest[i] = test;
+ ClearBounds( test->mins, test->maxs );
+
+ dvert = &drawVerts[ dsurf->firstVert ];
+ for ( j = 0 ; j < dsurf->numVerts ; j++, dvert++ ) {
+ AddPointToBounds( dvert->xyz, test->mins, test->maxs );
+ }
+
+ SphereFromBounds( test->mins, test->maxs, test->origin, &test->radius );
+
+ if ( dsurf->surfaceType == MST_TRIANGLE_SOUP || dsurf->surfaceType == MST_PLANAR ) {
+ FacetsForTriangleSurface( dsurf, si, test );
+ } else if ( dsurf->surfaceType == MST_PATCH ) {
+ FacetsForPatch( dsurf, si, test );
+ }
+ }
+}
+
+
+/*
+=====================
+GenerateBoundaryForPoints
+=====================
+*/
+void GenerateBoundaryForPoints( float boundary[4], float plane[4], vec3_t a, vec3_t b ) {
+ vec3_t d1;
+
+ // amke a perpendicular vector to the edge and the surface
+ VectorSubtract( b, a, d1 );
+ CrossProduct( plane, d1, boundary );
+ VectorNormalize( boundary, boundary );
+ boundary[3] = DotProduct( a, boundary );
+}
+
+
+/*
+=================
+SetFacetFilter
+
+Given a point on a facet, determine the color filter
+for light passing through
+=================
+*/
+void SetFacetFilter( traceWork_t *tr, shaderInfo_t *shader, cFacet_t *facet, vec3_t point ) {
+ float s, t;
+ int is, it;
+ byte *image;
+ int b;
+
+ // most surfaces are completely opaque
+ if ( !(shader->surfaceFlags & SURF_ALPHASHADOW) ) {
+ VectorClear( tr->trace->filter );
+ return;
+ }
+
+ s = DotProduct( point, facet->textureMatrix[0] ) + facet->textureMatrix[0][3];
+ t = DotProduct( point, facet->textureMatrix[1] ) + facet->textureMatrix[1][3];
+
+ if ( !shader->pixels ) {
+ // assume completely solid
+ VectorClear( point );
+ return;
+ }
+
+ s = s - floor( s );
+ t = t - floor( t );
+
+ is = s * shader->width;
+ it = t * shader->height;
+
+ image = shader->pixels + 4 * ( it * shader->width + is );
+
+ // alpha filter
+ b = image[3];
+
+ // alpha test makes this a binary option
+ b = b < 128 ? 0 : 255;
+
+ tr->trace->filter[0] = tr->trace->filter[0] * (255-b) / 255;
+ tr->trace->filter[1] = tr->trace->filter[1] * (255-b) / 255;
+ tr->trace->filter[2] = tr->trace->filter[2] * (255-b) / 255;
+}
+
+
+/*
+====================
+TraceAgainstFacet
+
+Shader is needed for translucent surfaces
+====================
+*/
+void TraceAgainstFacet( traceWork_t *tr, shaderInfo_t *shader, cFacet_t *facet ) {
+ int j;
+ float d1, d2, d, f;
+ vec3_t point;
+ float dist;
+
+ // ignore degenerate facets
+ if ( facet->numBoundaries < 3 ) {
+ return;
+ }
+
+ dist = facet->surface[3];
+
+ // compare the trace endpoints against the facet plane
+ d1 = DotProduct( tr->start, facet->surface ) - dist;
+ if ( d1 > -1 && d1 < 1 ) {
+ return; // don't self intersect
+ }
+ d2 = DotProduct( tr->end, facet->surface ) - dist;
+ if ( d2 > -1 && d2 < 1 ) {
+ return; // don't self intersect
+ }
+
+ // calculate the intersection fraction
+ f = ( d1 - ON_EPSILON ) / ( d1 - d2 );
+ if ( f <= 0 ) {
+ return;
+ }
+ if ( f >= tr->trace->hitFraction ) {
+ return; // we have hit something earlier
+ }
+
+ // calculate the intersection point
+ for ( j = 0 ; j < 3 ; j++ ) {
+ point[j] = tr->start[j] + f * ( tr->end[j] - tr->start[j] );
+ }
+
+ // check the point against the facet boundaries
+ for ( j = 0 ; j < facet->numBoundaries ; j++ ) {
+ // adjust the plane distance apropriately for mins/maxs
+ dist = facet->boundaries[j][3];
+
+ d = DotProduct( point, facet->boundaries[j] );
+ if ( d > dist + ON_EPSILON ) {
+ break; // outside the bounds
+ }
+ }
+
+ if ( j != facet->numBoundaries ) {
+ return; // we are outside the bounds of the facet
+ }
+
+ // we hit this facet
+
+ // if this is a transparent surface, calculate filter value
+ if ( shader->surfaceFlags & SURF_ALPHASHADOW ) {
+ SetFacetFilter( tr, shader, facet, point );
+ } else {
+ // completely opaque
+ VectorClear( tr->trace->filter );
+ tr->trace->hitFraction = f;
+ }
+
+// VectorCopy( facet->surface, tr->trace->plane.normal );
+// tr->trace->plane.dist = facet->surface[3];
+}
+
+
+/*
+===============================================================
+
+ LINE TRACING
+
+===============================================================
+*/
+
+
+#define TRACE_ON_EPSILON 0.1
+
+typedef struct tnode_s
+{
+ int type;
+ vec3_t normal;
+ float dist;
+ int children[2];
+ int planeNum;
+} tnode_t;
+
+#define MAX_TNODES (MAX_MAP_NODES*4)
+tnode_t *tnodes, *tnode_p;
+
+/*
+==============
+MakeTnode
+
+Converts the disk node structure into the efficient tracing structure
+==============
+*/
+void MakeTnode (int nodenum)
+{
+ tnode_t *t;
+ dplane_t *plane;
+ int i;
+ dnode_t *node;
+ int leafNum;
+
+ t = tnode_p++;
+
+ node = dnodes + nodenum;
+ plane = dplanes + node->planeNum;
+
+ t->planeNum = node->planeNum;
+ t->type = PlaneTypeForNormal( plane->normal );
+ VectorCopy (plane->normal, t->normal);
+ t->dist = plane->dist;
+
+ for (i=0 ; i<2 ; i++)
+ {
+ if (node->children[i] < 0) {
+ leafNum = -node->children[i] - 1;
+ if ( dleafs[leafNum].cluster == -1 ) {
+ // solid
+ t->children[i] = leafNum | ( 1 << 31 ) | ( 1 << 30 );
+ } else {
+ t->children[i] = leafNum | ( 1 << 31 );
+ }
+ } else {
+ t->children[i] = tnode_p - tnodes;
+ MakeTnode (node->children[i]);
+ }
+ }
+
+}
+
+/*
+=============
+InitTrace
+
+Loads the node structure out of a .bsp file to be used for light occlusion
+=============
+*/
+void InitTrace( void ) {
+ // 32 byte align the structs
+ tnodes = malloc( (MAX_TNODES+1) * sizeof(tnode_t));
+ tnodes = (tnode_t *)(((int)tnodes + 31)&~31);
+ tnode_p = tnodes;
+
+ MakeTnode (0);
+
+ InitSurfacesForTesting();
+}
+
+
+/*
+===================
+PointInSolid
+===================
+*/
+qboolean PointInSolid_r( vec3_t start, int node ) {
+ tnode_t *tnode;
+ float front;
+
+ while ( !(node & (1<<31) ) ) {
+ tnode = &tnodes[node];
+ switch (tnode->type) {
+ case PLANE_X:
+ front = start[0] - tnode->dist;
+ break;
+ case PLANE_Y:
+ front = start[1] - tnode->dist;
+ break;
+ case PLANE_Z:
+ front = start[2] - tnode->dist;
+ break;
+ default:
+ front = (start[0]*tnode->normal[0] + start[1]*tnode->normal[1] + start[2]*tnode->normal[2]) - tnode->dist;
+ break;
+ }
+
+ if ( front == 0 ) {
+ // exactly on node, must check both sides
+ return (qboolean) ( PointInSolid_r( start, tnode->children[0] )
+ | PointInSolid_r( start, tnode->children[1] ) );
+ }
+
+ if ( front > 0 ) {
+ node = tnode->children[0];
+ } else {
+ node = tnode->children[1];
+ }
+ }
+
+ if ( node & ( 1 << 30 ) ) {
+ return qtrue;
+ }
+ return qfalse;
+}
+
+/*
+=============
+PointInSolid
+
+=============
+*/
+qboolean PointInSolid( vec3_t start ) {
+ return PointInSolid_r( start, 0 );
+}
+
+
+/*
+=============
+TraceLine_r
+
+Returns qtrue if something is hit and tracing can stop
+=============
+*/
+int TraceLine_r( int node, const vec3_t start, const vec3_t stop, traceWork_t *tw ) {
+ tnode_t *tnode;
+ float front, back;
+ vec3_t mid;
+ float frac;
+ int side;
+ int r;
+
+ if (node & (1<<31)) {
+ if (node & ( 1 << 30 ) ) {
+ VectorCopy (start, tw->trace->hit);
+ tw->trace->passSolid = qtrue;
+ return qtrue;
+ } else {
+ // save the node off for more exact testing
+ if ( tw->numOpenLeafs == MAX_MAP_LEAFS ) {
+ return qfalse;
+ }
+ tw->openLeafNumbers[ tw->numOpenLeafs ] = node & ~(3 << 30);
+ tw->numOpenLeafs++;
+ return qfalse;
+ }
+ }
+
+ tnode = &tnodes[node];
+ switch (tnode->type) {
+ case PLANE_X:
+ front = start[0] - tnode->dist;
+ back = stop[0] - tnode->dist;
+ break;
+ case PLANE_Y:
+ front = start[1] - tnode->dist;
+ back = stop[1] - tnode->dist;
+ break;
+ case PLANE_Z:
+ front = start[2] - tnode->dist;
+ back = stop[2] - tnode->dist;
+ break;
+ default:
+ front = (start[0]*tnode->normal[0] + start[1]*tnode->normal[1] + start[2]*tnode->normal[2]) - tnode->dist;
+ back = (stop[0]*tnode->normal[0] + stop[1]*tnode->normal[1] + stop[2]*tnode->normal[2]) - tnode->dist;
+ break;
+ }
+
+ if (front >= -TRACE_ON_EPSILON && back >= -TRACE_ON_EPSILON) {
+ return TraceLine_r (tnode->children[0], start, stop, tw);
+ }
+
+ if (front < TRACE_ON_EPSILON && back < TRACE_ON_EPSILON) {
+ return TraceLine_r (tnode->children[1], start, stop, tw);
+ }
+
+ side = front < 0;
+
+ frac = front / (front-back);
+
+ mid[0] = start[0] + (stop[0] - start[0])*frac;
+ mid[1] = start[1] + (stop[1] - start[1])*frac;
+ mid[2] = start[2] + (stop[2] - start[2])*frac;
+
+ r = TraceLine_r (tnode->children[side], start, mid, tw);
+
+ if (r) {
+ return r;
+ }
+
+// trace->planeNum = tnode->planeNum;
+ return TraceLine_r (tnode->children[!side], mid, stop, tw);
+}
+
+//==========================================================================================
+
+
+/*
+================
+SphereCull
+================
+*/
+qboolean SphereCull( vec3_t start, vec3_t stop, vec3_t origin, float radius ) {
+ vec3_t v;
+ float d;
+ vec3_t dir;
+ float len;
+ vec3_t on;
+
+ VectorSubtract( stop, start, dir );
+ len = VectorNormalize( dir, dir );
+
+ VectorSubtract( origin, start, v );
+ d = DotProduct( v, dir );
+ if ( d > len + radius ) {
+ return qtrue; // too far ahead
+ }
+ if ( d < -radius ) {
+ return qtrue; // too far behind
+ }
+ VectorMA( start, d, dir, on );
+
+ VectorSubtract( on, origin, v );
+
+ len = VectorLength( v );
+
+ if ( len > radius ) {
+ return qtrue; // too far to the side
+ }
+
+ return qfalse; // must be traced against
+}
+
+/*
+================
+TraceAgainstSurface
+================
+*/
+void TraceAgainstSurface( traceWork_t *tw, surfaceTest_t *surf ) {
+ int i;
+
+ // if surfaces are trans
+ if ( SphereCull( tw->start, tw->end, surf->origin, surf->radius ) ) {
+ if ( numthreads == 1 ) {
+ c_cullTrace++;
+ }
+ return;
+ }
+
+ if ( numthreads == 1 ) {
+ c_testTrace++;
+ c_testFacets += surf->numFacets;
+ }
+
+ /*
+ // MrE: backface culling
+ if (!surf->patch && surf->numFacets) {
+ // if the surface does not cast an alpha shadow
+ if ( !(surf->shader->surfaceFlags & SURF_ALPHASHADOW) ) {
+ vec3_t vec;
+ VectorSubtract(tw->end, tw->start, vec);
+ if (DotProduct(vec, surf->facets->surface) > 0)
+ return;
+ }
+ }
+ */
+
+ // test against each facet
+ for ( i = 0 ; i < surf->numFacets ; i++ ) {
+ TraceAgainstFacet( tw, surf->shader, surf->facets + i );
+ }
+}
+
+/*
+=============
+TraceLine
+
+Follow the trace just through the solid leafs first, and only
+if it passes that, trace against the objects inside the empty leafs
+Returns qtrue if the trace hit any
+
+traceWork_t is only a parameter to crutch up poor large local allocations on
+winNT and macOS. It should be allocated in the worker function, but never
+looked at.
+
+leave testAll false if all you care about is if it hit anything at all.
+if you need to know the exact first point of impact (for a sun trace), set
+testAll to true
+=============
+*/
+extern qboolean patchshadows;
+
+void TraceLine( const vec3_t start, const vec3_t stop, trace_t *trace, qboolean testAll, traceWork_t *tw ) {
+ int r;
+ int i, j;
+ dleaf_t *leaf;
+ float oldHitFrac;
+ surfaceTest_t *test;
+ int surfaceNum;
+ byte surfaceTested[MAX_MAP_DRAW_SURFS/8];
+ ;
+
+ if ( numthreads == 1 ) {
+ c_totalTrace++;
+ }
+
+ // assume all light gets through, unless the ray crosses
+ // a translucent surface
+ trace->filter[0] = 1.0;
+ trace->filter[1] = 1.0;
+ trace->filter[2] = 1.0;
+
+ VectorCopy( start, tw->start );
+ VectorCopy( stop, tw->end );
+ tw->trace = trace;
+
+ tw->numOpenLeafs = 0;
+
+ trace->passSolid = qfalse;
+ trace->hitFraction = 1.0;
+
+ r = TraceLine_r( 0, start, stop, tw );
+
+ // if we hit a solid leaf, stop without testing the leaf
+ // surfaces. Note that the plane and endpoint might not
+ // be the first solid intersection along the ray.
+ if ( r && !testAll ) {
+ return;
+ }
+
+ if ( noSurfaces ) {
+ return;
+ }
+
+ memset( surfaceTested, 0, (numDrawSurfaces+7)/8 );
+ oldHitFrac = trace->hitFraction;
+
+ for ( i = 0 ; i < tw->numOpenLeafs ; i++ ) {
+ leaf = &dleafs[ tw->openLeafNumbers[ i ] ];
+ for ( j = 0 ; j < leaf->numLeafSurfaces ; j++ ) {
+ surfaceNum = dleafsurfaces[ leaf->firstLeafSurface + j ];
+
+ // make sure we don't test the same ray against a surface more than once
+ if ( surfaceTested[ surfaceNum>>3 ] & ( 1 << ( surfaceNum & 7) ) ) {
+ continue;
+ }
+ surfaceTested[ surfaceNum>>3 ] |= ( 1 << ( surfaceNum & 7 ) );
+
+ test = surfaceTest[ surfaceNum ];
+ if ( !test ) {
+ continue;
+ }
+ //
+ if ( !tw->patchshadows && test->patch ) {
+ continue;
+ }
+ TraceAgainstSurface( tw, test );
+ }
+
+ // if the trace is now solid, we can't possibly hit anything closer
+ if ( trace->hitFraction < oldHitFrac ) {
+ trace->passSolid = qtrue;
+ break;
+ }
+ }
+
+ for ( i = 0 ; i < 3 ; i++ ) {
+ trace->hit[i] = start[i] + ( stop[i] - start[i] ) * trace->hitFraction;
+ }
+}
+
diff --git a/q3map/lightmaps.c b/q3map/lightmaps.c
new file mode 100755
index 0000000..95064e5
--- /dev/null
+++ b/q3map/lightmaps.c
@@ -0,0 +1,395 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "qbsp.h"
+
+
+/*
+
+ Lightmap allocation has to be done after all flood filling and
+ visible surface determination.
+
+*/
+
+int numSortShaders;
+mapDrawSurface_t *surfsOnShader[MAX_MAP_SHADERS];
+
+
+int allocated[LIGHTMAP_WIDTH];
+
+int numLightmaps = 1;
+int c_exactLightmap;
+
+
+void PrepareNewLightmap( void ) {
+ memset( allocated, 0, sizeof( allocated ) );
+ numLightmaps++;
+}
+
+/*
+===============
+AllocLMBlock
+
+returns a texture number and the position inside it
+===============
+*/
+qboolean AllocLMBlock (int w, int h, int *x, int *y)
+{
+ int i, j;
+ int best, best2;
+
+ best = LIGHTMAP_HEIGHT;
+
+ for ( i=0 ; i <= LIGHTMAP_WIDTH-w ; i++ ) {
+ best2 = 0;
+
+ for (j=0 ; j<w ; j++) {
+ if (allocated[i+j] >= best) {
+ break;
+ }
+ if (allocated[i+j] > best2) {
+ best2 = allocated[i+j];
+ }
+ }
+ if (j == w) { // this is a valid spot
+ *x = i;
+ *y = best = best2;
+ }
+ }
+
+ if (best + h > LIGHTMAP_HEIGHT) {
+ return qfalse;
+ }
+
+ for (i=0 ; i<w ; i++) {
+ allocated[*x + i] = best + h;
+ }
+
+ return qtrue;
+}
+
+
+/*
+===================
+AllocateLightmapForPatch
+===================
+*/
+//#define LIGHTMAP_PATCHSHIFT
+
+void AllocateLightmapForPatch( mapDrawSurface_t *ds ) {
+ int i, j, k;
+ drawVert_t *verts;
+ int w, h;
+ int x, y;
+ float s, t;
+ mesh_t mesh, *subdividedMesh, *tempMesh, *newmesh;
+ int widthtable[LIGHTMAP_WIDTH], heighttable[LIGHTMAP_HEIGHT], ssize;
+
+ verts = ds->verts;
+
+ mesh.width = ds->patchWidth;
+ mesh.height = ds->patchHeight;
+ mesh.verts = verts;
+ newmesh = SubdivideMesh( mesh, 8, 999 );
+
+ PutMeshOnCurve( *newmesh );
+ tempMesh = RemoveLinearMeshColumnsRows( newmesh );
+ FreeMesh(newmesh);
+
+ ssize = samplesize;
+ if (ds->shaderInfo->lightmapSampleSize)
+ ssize = ds->shaderInfo->lightmapSampleSize;
+
+#ifdef LIGHTMAP_PATCHSHIFT
+ subdividedMesh = SubdivideMeshQuads( tempMesh, ssize, LIGHTMAP_WIDTH-1, widthtable, heighttable);
+#else
+ subdividedMesh = SubdivideMeshQuads( tempMesh, ssize, LIGHTMAP_WIDTH, widthtable, heighttable);
+#endif
+
+ w = subdividedMesh->width;
+ h = subdividedMesh->height;
+
+#ifdef LIGHTMAP_PATCHSHIFT
+ w++;
+ h++;
+#endif
+
+ FreeMesh(subdividedMesh);
+
+ // allocate the lightmap
+ c_exactLightmap += w * h;
+
+ if ( !AllocLMBlock( w, h, &x, &y ) ) {
+ PrepareNewLightmap();
+ if ( !AllocLMBlock( w, h, &x, &y ) ) {
+ Error("Entity %i, brush %i: Lightmap allocation failed",
+ ds->mapBrush->entitynum, ds->mapBrush->brushnum );
+ }
+ }
+
+#ifdef LIGHTMAP_PATCHSHIFT
+ w--;
+ h--;
+#endif
+
+ // set the lightmap texture coordinates in the drawVerts
+ ds->lightmapNum = numLightmaps - 1;
+ ds->lightmapWidth = w;
+ ds->lightmapHeight = h;
+ ds->lightmapX = x;
+ ds->lightmapY = y;
+
+ for ( i = 0 ; i < ds->patchWidth ; i++ ) {
+ for ( k = 0 ; k < w ; k++ ) {
+ if ( originalWidths[k] >= i ) {
+ break;
+ }
+ }
+ if (k >= w)
+ k = w-1;
+ s = x + k;
+ for ( j = 0 ; j < ds->patchHeight ; j++ ) {
+ for ( k = 0 ; k < h ; k++ ) {
+ if ( originalHeights[k] >= j ) {
+ break;
+ }
+ }
+ if (k >= h)
+ k = h-1;
+ t = y + k;
+ verts[i + j * ds->patchWidth].lightmap[0] = ( s + 0.5 ) / LIGHTMAP_WIDTH;
+ verts[i + j * ds->patchWidth].lightmap[1] = ( t + 0.5 ) / LIGHTMAP_HEIGHT;
+ }
+ }
+}
+
+
+/*
+===================
+AllocateLightmapForSurface
+===================
+*/
+//#define LIGHTMAP_BLOCK 16
+void AllocateLightmapForSurface( mapDrawSurface_t *ds ) {
+ vec3_t mins, maxs, size, exactSize, delta;
+ int i;
+ drawVert_t *verts;
+ int w, h;
+ int x, y, ssize;
+ int axis;
+ vec3_t vecs[2];
+ float s, t;
+ vec3_t origin;
+ plane_t *plane;
+ float d;
+ vec3_t planeNormal;
+
+ if ( ds->patch ) {
+ AllocateLightmapForPatch( ds );
+ return;
+ }
+
+ ssize = samplesize;
+ if (ds->shaderInfo->lightmapSampleSize)
+ ssize = ds->shaderInfo->lightmapSampleSize;
+
+ plane = &mapplanes[ ds->side->planenum ];
+
+ // bound the surface
+ ClearBounds( mins, maxs );
+ verts = ds->verts;
+ for ( i = 0 ; i < ds->numVerts ; i++ ) {
+ AddPointToBounds( verts[i].xyz, mins, maxs );
+ }
+
+ // round to the lightmap resolution
+ for ( i = 0 ; i < 3 ; i++ ) {
+ exactSize[i] = maxs[i] - mins[i];
+ mins[i] = ssize * floor( mins[i] / ssize );
+ maxs[i] = ssize * ceil( maxs[i] / ssize );
+ size[i] = (maxs[i] - mins[i]) / ssize + 1;
+ }
+
+ // the two largest axis will be the lightmap size
+ memset( vecs, 0, sizeof( vecs ) );
+
+ planeNormal[0] = fabs( plane->normal[0] );
+ planeNormal[1] = fabs( plane->normal[1] );
+ planeNormal[2] = fabs( plane->normal[2] );
+
+ if ( planeNormal[0] >= planeNormal[1] && planeNormal[0] >= planeNormal[2] ) {
+ w = size[1];
+ h = size[2];
+ axis = 0;
+ vecs[0][1] = 1.0 / ssize;
+ vecs[1][2] = 1.0 / ssize;
+ } else if ( planeNormal[1] >= planeNormal[0] && planeNormal[1] >= planeNormal[2] ) {
+ w = size[0];
+ h = size[2];
+ axis = 1;
+ vecs[0][0] = 1.0 / ssize;
+ vecs[1][2] = 1.0 / ssize;
+ } else {
+ w = size[0];
+ h = size[1];
+ axis = 2;
+ vecs[0][0] = 1.0 / ssize;
+ vecs[1][1] = 1.0 / ssize;
+ }
+
+ if ( !plane->normal[axis] ) {
+ Error( "Chose a 0 valued axis" );
+ }
+
+ if ( w > LIGHTMAP_WIDTH ) {
+ VectorScale ( vecs[0], (float)LIGHTMAP_WIDTH/w, vecs[0] );
+ w = LIGHTMAP_WIDTH;
+ }
+
+ if ( h > LIGHTMAP_HEIGHT ) {
+ VectorScale ( vecs[1], (float)LIGHTMAP_HEIGHT/h, vecs[1] );
+ h = LIGHTMAP_HEIGHT;
+ }
+
+ c_exactLightmap += w * h;
+
+ if ( !AllocLMBlock( w, h, &x, &y ) ) {
+ PrepareNewLightmap();
+ if ( !AllocLMBlock( w, h, &x, &y ) ) {
+ Error("Entity %i, brush %i: Lightmap allocation failed",
+ ds->mapBrush->entitynum, ds->mapBrush->brushnum );
+ }
+ }
+
+ // set the lightmap texture coordinates in the drawVerts
+ ds->lightmapNum = numLightmaps - 1;
+ ds->lightmapWidth = w;
+ ds->lightmapHeight = h;
+ ds->lightmapX = x;
+ ds->lightmapY = y;
+
+ for ( i = 0 ; i < ds->numVerts ; i++ ) {
+ VectorSubtract( verts[i].xyz, mins, delta );
+ s = DotProduct( delta, vecs[0] ) + x + 0.5;
+ t = DotProduct( delta, vecs[1] ) + y + 0.5;
+ verts[i].lightmap[0] = s / LIGHTMAP_WIDTH;
+ verts[i].lightmap[1] = t / LIGHTMAP_HEIGHT;
+ }
+
+ // calculate the world coordinates of the lightmap samples
+
+ // project mins onto plane to get origin
+ d = DotProduct( mins, plane->normal ) - plane->dist;
+ d /= plane->normal[ axis ];
+ VectorCopy( mins, origin );
+ origin[axis] -= d;
+
+ // project stepped lightmap blocks and subtract to get planevecs
+ for ( i = 0 ; i < 2 ; i++ ) {
+ vec3_t normalized;
+ float len;
+
+ len = VectorNormalize( vecs[i], normalized );
+ VectorScale( normalized, (1.0/len), vecs[i] );
+ d = DotProduct( vecs[i], plane->normal );
+ d /= plane->normal[ axis ];
+ vecs[i][axis] -= d;
+ }
+
+ VectorCopy( origin, ds->lightmapOrigin );
+ VectorCopy( vecs[0], ds->lightmapVecs[0] );
+ VectorCopy( vecs[1], ds->lightmapVecs[1] );
+ VectorCopy( plane->normal, ds->lightmapVecs[2] );
+}
+
+/*
+===================
+AllocateLightmaps
+===================
+*/
+void AllocateLightmaps( entity_t *e ) {
+ int i, j;
+ mapDrawSurface_t *ds;
+ shaderInfo_t *si;
+
+ qprintf ("--- AllocateLightmaps ---\n");
+
+
+ // sort all surfaces by shader so common shaders will usually
+ // be in the same lightmap
+ numSortShaders = 0;
+
+ for ( i = e->firstDrawSurf ; i < numMapDrawSurfs ; i++ ) {
+ ds = &mapDrawSurfs[i];
+ if ( !ds->numVerts ) {
+ continue; // leftover from a surface subdivision
+ }
+ if ( ds->miscModel ) {
+ continue;
+ }
+ if ( !ds->patch ) {
+ VectorCopy( mapplanes[ds->side->planenum].normal, ds->lightmapVecs[2] );
+ }
+
+ // search for this shader
+ for ( j = 0 ; j < numSortShaders ; j++ ) {
+ if ( ds->shaderInfo == surfsOnShader[j]->shaderInfo ) {
+ ds->nextOnShader = surfsOnShader[j];
+ surfsOnShader[j] = ds;
+ break;
+ }
+ }
+ if ( j == numSortShaders ) {
+ if ( numSortShaders >= MAX_MAP_SHADERS ) {
+ Error( "MAX_MAP_SHADERS" );
+ }
+ surfsOnShader[j] = ds;
+ numSortShaders++;
+ }
+ }
+ qprintf( "%5i unique shaders\n", numSortShaders );
+
+ // for each shader, allocate lightmaps for each surface
+
+// numLightmaps = 0;
+// PrepareNewLightmap();
+
+ for ( i = 0 ; i < numSortShaders ; i++ ) {
+ si = surfsOnShader[i]->shaderInfo;
+
+ for ( ds = surfsOnShader[i] ; ds ; ds = ds->nextOnShader ) {
+ // some surfaces don't need lightmaps allocated for them
+ if ( si->surfaceFlags & SURF_NOLIGHTMAP ) {
+ ds->lightmapNum = -1;
+ } else if ( si->surfaceFlags & SURF_POINTLIGHT ) {
+ ds->lightmapNum = -3;
+ } else {
+ AllocateLightmapForSurface( ds );
+ }
+ }
+ }
+
+ qprintf( "%7i exact lightmap texels\n", c_exactLightmap );
+ qprintf( "%7i block lightmap texels\n", numLightmaps * LIGHTMAP_WIDTH*LIGHTMAP_HEIGHT );
+}
+
+
+
diff --git a/q3map/lightv.c b/q3map/lightv.c
new file mode 100755
index 0000000..dddecb7
--- /dev/null
+++ b/q3map/lightv.c
@@ -0,0 +1,5748 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+
+#include "cmdlib.h"
+#include "mathlib.h"
+#include "bspfile.h"
+#include "imagelib.h"
+#include "threads.h"
+#include "mutex.h"
+#include "scriplib.h"
+
+#include "shaders.h"
+#include "mesh.h"
+
+#ifdef _WIN32
+//Improve floating-point consistency.
+#pragma optimize( "p", on )
+#endif
+
+#ifdef _WIN32
+#include "../libs/pakstuff.h"
+#endif
+
+#define MAX_CLUSTERS 16384
+#define MAX_PORTALS 32768
+#define MAX_FACETS 65536
+#define MAX_LIGHTS 16384
+
+#define LIGHTMAP_SIZE 128
+
+#define LIGHTMAP_PIXELSHIFT 0.5
+
+//#define LIGHTMAP_PATCHSHIFT
+
+#define PORTALFILE "PRT1"
+
+#define ON_EPSILON 0.1
+
+#define VectorSet(v, x, y, z) v[0] = x;v[1] = y;v[2] = z;
+
+typedef struct
+{
+ vec3_t normal;
+ float dist;
+} plane_t;
+
+#define MAX_POINTS_ON_WINDING 64
+//NOTE: whenever this is overflowed parts of lightmaps might end up not being lit
+#define MAX_POINTS_ON_FIXED_WINDING 48
+
+typedef struct
+{
+ int numpoints;
+ vec3_t points[MAX_POINTS_ON_FIXED_WINDING]; // variable sized
+} winding_t;
+
+typedef struct
+{
+ plane_t plane; // normal pointing into neighbor
+ int leaf; // neighbor
+ winding_t *winding;
+ vec3_t origin; // for fast clip testing
+ float radius;
+} lportal_t;
+
+#define MAX_PORTALS_ON_LEAF 128
+typedef struct lleaf_s
+{
+ int numportals;
+ lportal_t *portals[MAX_PORTALS_ON_LEAF];
+ //
+ int numSurfaces;
+ int firstSurface;
+} lleaf_t;
+
+typedef struct lFacet_s
+{
+ int num;
+ plane_t plane;
+ vec3_t points[4]; //
+ int numpoints;
+ float lightmapCoords[4][2];
+ plane_t boundaries[4]; // negative is outside the bounds
+ float textureMatrix[2][4]; // texture coordinates for translucency
+ float lightmapMatrix[2][4]; // lightmap texture coordinates
+ vec3_t mins;
+ int x, y, width, height;
+} lFacet_t;
+
+typedef struct lsurfaceTest_s
+{
+ vec3_t mins, maxs;
+ vec3_t origin;
+ float radius;
+ qboolean patch; // true if this is a patch
+ qboolean trisoup; // true if this is a triangle soup
+ int numFacets;
+ lFacet_t *facets;
+ mesh_t *detailMesh; // detailed mesh with points for each lmp
+ shaderInfo_t *shader; // for translucency
+ mutex_t *mutex;
+ int numvolumes; // number of volumes casted at this surface
+ //
+ int always_tracelight;
+ int always_vlight;
+} lsurfaceTest_t;
+
+//volume types
+#define VOLUME_NORMAL 0
+#define VOLUME_DIRECTED 1
+
+#define MAX_TRANSLUCENTFACETS 32
+
+typedef struct lightvolume_s
+{
+ int num;
+ int cluster; //cluster this light volume started in
+ plane_t endplane; //end plane
+ plane_t farplane; //original end plane
+ vec3_t points[MAX_POINTS_ON_WINDING]; //end winding points
+ plane_t planes[MAX_POINTS_ON_WINDING]; //volume bounding planes
+ int numplanes; //number of volume bounding planes
+ int type; //light volume type
+ //list with translucent surfaces the volume went through
+ int transFacets[MAX_TRANSLUCENTFACETS];
+ int transSurfaces[MAX_TRANSLUCENTFACETS];
+ int numtransFacets;
+ //clusters already tested
+ byte clusterTested[MAX_CLUSTERS/8];
+ //facets already tested
+ byte facetTested[MAX_FACETS/8];
+ int facetNum; //number of the facet blocking the light in this volume
+ int surfaceNum; //number of the surface blocking the light in this volume
+} lightvolume_t;
+
+//light types
+#define LIGHT_POINTRADIAL 1
+#define LIGHT_POINTSPOT 2
+#define LIGHT_POINTFAKESURFACE 3
+#define LIGHT_SURFACEDIRECTED 4
+#define LIGHT_SURFACERADIAL 5
+#define LIGHT_SURFACESPOT 6
+
+//light distance attenuation types
+#define LDAT_QUADRATIC 0
+#define LDAT_LINEAR 1
+#define LDAT_NOSCALE 2
+
+//light angle attenuation types
+#define LAAT_NORMAL 0
+#define LAAT_QUADRATIC 1
+#define LAAT_DOUBLEQUADRATIC 2
+
+typedef struct vlight_s
+{
+ vec3_t origin; //light origin, for point lights
+ winding_t w; //light winding, for area lights
+ vec4_t plane; //light winding plane
+ vec3_t normal; //direction of the light
+ int type; //light type
+ vec3_t color; //light color
+ qboolean twosided; //radiates light at both sides of the winding
+ int style; //light style (not used)
+ int atten_disttype; //light distance attenuation type
+ int atten_angletype; //light angle attenuation type
+ float atten_distscale; //distance attenuation scale
+ float atten_anglescale; //angle attenuation scale
+ float radiusByDist; //radius by distance for spot lights
+ float photons; //emitted photons
+ float intensity; //intensity
+ vec3_t emitColor; //full out-of-gamut value (not used)
+ struct shaderInfo_s *si; //shader info
+ int insolid; //set when light is in solid
+} vlight_t;
+
+float lightLinearScale = 1.0 / 8000;
+float lightPointScale = 7500;
+float lightAreaScale = 0.25;
+float lightFormFactorValueScale = 3;
+int lightDefaultSubdivide = 999; // vary by surface size?
+vec3_t lightAmbientColor;
+
+int portalclusters, numportals, numfaces;
+lleaf_t *leafs;
+lportal_t *portals;
+int numvlights = 0;
+vlight_t *vlights[MAX_LIGHTS];
+int nostitching = 0;
+int noalphashading = 0;
+int nocolorshading = 0;
+int nobackfaceculling = 0;
+int defaulttracelight = 0;
+int radiosity = 0;
+int radiosity_scale;
+
+int clustersurfaces[MAX_MAP_LEAFFACES];
+int numclustersurfaces = 0;
+lsurfaceTest_t *lsurfaceTest[MAX_MAP_DRAW_SURFS];
+int numfacets;
+float lightmappixelarea[MAX_MAP_LIGHTING/3];
+float *lightFloats;//[MAX_MAP_LIGHTING];
+
+// from polylib.c
+winding_t *AllocWinding (int points);
+void FreeWinding (winding_t *w);
+void WindingCenter (winding_t *w, vec3_t center);
+void WindingBounds (winding_t *w, vec3_t mins, vec3_t maxs);
+vec_t WindingArea (winding_t *w);
+winding_t *BaseWindingForPlane (vec3_t normal, vec_t dist);
+void ClipWindingEpsilon (winding_t *in, vec3_t normal, vec_t dist,
+ vec_t epsilon, winding_t **front, winding_t **back);
+winding_t *ReverseWinding (winding_t *w);
+
+// from light.c
+extern char source[1024];
+extern vec3_t surfaceOrigin[ MAX_MAP_DRAW_SURFS ];
+extern int entitySurface[ MAX_MAP_DRAW_SURFS ];
+extern int samplesize;
+extern int novertexlighting;
+extern int nogridlighting;
+extern qboolean patchshadows;
+extern vec3_t gridSize;
+
+float PointToPolygonFormFactor( const vec3_t point, const vec3_t normal, const winding_t *w );
+void ColorToBytes( const float *color, byte *colorBytes );
+void CountLightmaps( void );
+void GridAndVertexLighting( void );
+void SetEntityOrigins( void );
+
+
+//#define DEBUGNET
+
+#ifdef DEBUGNET
+
+#include "l_net.h"
+
+socket_t *debug_socket;
+
+/*
+=====================
+DebugNet_Setup
+=====================
+*/
+void DebugNet_Setup(void)
+{
+ address_t address;
+ int i;
+
+ Net_Setup();
+ Net_StringToAddress("127.0.0.1:28000", &address);
+ for (i = 0; i < 10; i++)
+ {
+ debug_socket = Net_Connect(&address, 28005 + i);
+ if (debug_socket)
+ break;
+ }
+}
+
+/*
+=====================
+DebugNet_Shutdown
+=====================
+*/
+void DebugNet_Shutdown(void)
+{
+ netmessage_t msg;
+
+ if (debug_socket)
+ {
+ NMSG_Clear(&msg);
+ NMSG_WriteByte(&msg, 1);
+ Net_Send(debug_socket, &msg);
+ Net_Disconnect(debug_socket);
+ }
+ debug_socket = NULL;
+ Net_Shutdown();
+}
+
+/*
+=====================
+DebugNet_RemoveAllPolys
+=====================
+*/
+void DebugNet_RemoveAllPolys(void)
+{
+ netmessage_t msg;
+
+ if (!debug_socket)
+ return;
+ NMSG_Clear(&msg);
+ NMSG_WriteByte(&msg, 2); //remove all debug polys
+ Net_Send(debug_socket, &msg);
+}
+
+/*
+====================
+DebugNet_DrawWinding
+=====================
+*/
+void DebugNet_DrawWinding(winding_t *w, int color)
+{
+ netmessage_t msg;
+ int i;
+
+ if (!debug_socket)
+ return;
+ NMSG_Clear(&msg);
+ NMSG_WriteByte(&msg, 0); //draw a winding
+ NMSG_WriteByte(&msg, w->numpoints); //number of points
+ NMSG_WriteLong(&msg, color); //color
+ for (i = 0; i < w->numpoints; i++)
+ {
+ NMSG_WriteFloat(&msg, w->points[i][0]);
+ NMSG_WriteFloat(&msg, w->points[i][1]);
+ NMSG_WriteFloat(&msg, w->points[i][2]);
+ }
+ Net_Send(debug_socket, &msg);
+}
+
+/*
+=====================
+DebugNet_DrawLine
+=====================
+*/
+void DebugNet_DrawLine(vec3_t p1, vec3_t p2, int color)
+{
+ netmessage_t msg;
+
+ if (!debug_socket)
+ return;
+ NMSG_Clear(&msg);
+ NMSG_WriteByte(&msg, 1); //draw a line
+ NMSG_WriteLong(&msg, color); //color
+ NMSG_WriteFloat(&msg, p1[0]);
+ NMSG_WriteFloat(&msg, p1[1]);
+ NMSG_WriteFloat(&msg, p1[2]);
+ NMSG_WriteFloat(&msg, p2[0]);
+ NMSG_WriteFloat(&msg, p2[1]);
+ NMSG_WriteFloat(&msg, p2[2]);
+ Net_Send(debug_socket, &msg);
+}
+
+/*
+=====================
+DebugNet_DrawMesh
+=====================
+*/
+void DebugNet_DrawMesh(mesh_t *mesh)
+{
+ int i, j;
+ float dot;
+ drawVert_t *v1, *v2, *v3, *v4;
+ winding_t winding;
+ plane_t plane;
+ vec3_t d1, d2;
+
+ for ( i = 0 ; i < mesh->width - 1 ; i++ ) {
+ for ( j = 0 ; j < mesh->height - 1 ; j++ ) {
+
+ v1 = mesh->verts + j * mesh->width + i;
+ v2 = v1 + 1;
+ v3 = v1 + mesh->width + 1;
+ v4 = v1 + mesh->width;
+
+ VectorSubtract( v4->xyz, v1->xyz, d1 );
+ VectorSubtract( v3->xyz, v1->xyz, d2 );
+ CrossProduct( d2, d1, plane.normal );
+ if ( VectorNormalize( plane.normal, plane.normal ) != 0 )
+ {
+ plane.dist = DotProduct( v1->xyz, plane.normal );
+ dot = DotProduct(plane.normal, v2->xyz) - plane.dist;
+ if (fabs(dot) < 0.1)
+ {
+ VectorCopy(v1->xyz, winding.points[0]);
+ VectorCopy(v4->xyz, winding.points[1]);
+ VectorCopy(v3->xyz, winding.points[2]);
+ VectorCopy(v2->xyz, winding.points[3]);
+ winding.numpoints = 4;
+ DebugNet_DrawWinding(&winding, 2);
+ continue;
+ }
+ }
+
+ winding.numpoints = 3;
+ VectorCopy(v1->xyz, winding.points[0]);
+ VectorCopy(v4->xyz, winding.points[1]);
+ VectorCopy(v3->xyz, winding.points[2]);
+ DebugNet_DrawWinding(&winding, 2);
+
+ VectorCopy(v1->xyz, winding.points[0]);
+ VectorCopy(v3->xyz, winding.points[1]);
+ VectorCopy(v2->xyz, winding.points[2]);
+ DebugNet_DrawWinding(&winding, 2);
+ }
+ }
+}
+
+/*
+=====================
+VL_DrawLightVolume
+=====================
+*/
+int VL_ChopWinding (winding_t *in, plane_t *split, float epsilon);
+
+void VL_DrawLightVolume(vlight_t *light, lightvolume_t *volume)
+{
+ winding_t w;
+ int i;
+ vec3_t p2, invlight;
+
+ memcpy(w.points, volume->points, volume->numplanes * sizeof(vec3_t));
+ w.numpoints = volume->numplanes;
+ DebugNet_DrawWinding(&w, 2);
+
+ if (volume->type == VOLUME_DIRECTED)
+ {
+ VectorCopy(light->normal, invlight);
+ VectorInverse(invlight);
+ for (i = 0; i < volume->numplanes; i++)
+ {
+ VectorCopy(volume->points[i], w.points[0]);
+ VectorCopy(volume->points[(i+1) % volume->numplanes], w.points[1]);
+ VectorMA(w.points[1], MAX_WORLD_COORD, invlight, w.points[2]);
+ VectorMA(w.points[0], MAX_WORLD_COORD, invlight, w.points[3]);
+ w.numpoints = 4;
+ DebugNet_DrawWinding(&w, 2);
+ VectorMA(volume->points[i], 8, volume->planes[i].normal, p2);
+ DebugNet_DrawLine(volume->points[i], p2, 3);
+ }
+ }
+ else
+ {
+ //
+ VectorCopy(light->origin, w.points[0]);
+ w.numpoints = 3;
+ for (i = 0; i < volume->numplanes; i++)
+ {
+ VectorCopy(volume->points[i], w.points[1]);
+ VectorCopy(volume->points[(i+1) % volume->numplanes], w.points[2]);
+ VL_ChopWinding(&w, &volume->endplane, 0);
+ DebugNet_DrawWinding(&w, 2);
+ VectorMA(volume->points[i], 8, volume->planes[i].normal, p2);
+ DebugNet_DrawLine(volume->points[i], p2, 3);
+ }
+ }
+}
+
+/*
+=============
+VL_DrawLightmapPixel
+=============
+*/
+void VL_DrawLightmapPixel(int surfaceNum, int x, int y, int color)
+{
+ winding_t w;
+ dsurface_t *ds;
+ mesh_t *mesh;
+
+ ds = &drawSurfaces[surfaceNum];
+
+ if (ds->surfaceType == MST_PATCH)
+ {
+ mesh = lsurfaceTest[surfaceNum]->detailMesh;
+ VectorCopy( mesh->verts[(y-ds->lightmapY)*mesh->width+x-ds->lightmapX].xyz, w.points[0]);
+ VectorCopy( mesh->verts[(y+1-ds->lightmapY)*mesh->width+x-ds->lightmapX].xyz, w.points[1]);
+ VectorCopy( mesh->verts[(y+1-ds->lightmapY)*mesh->width+x+1-ds->lightmapX].xyz, w.points[2]);
+ VectorCopy( mesh->verts[(y-ds->lightmapY)*mesh->width+x+1-ds->lightmapX].xyz, w.points[3]);
+ w.numpoints = 4;
+ }
+ else
+ {
+ VectorMA(ds->lightmapOrigin, (float) x - LIGHTMAP_PIXELSHIFT - ds->lightmapX, ds->lightmapVecs[0], w.points[0]);
+ VectorMA(w.points[0], (float) y - LIGHTMAP_PIXELSHIFT - ds->lightmapY, ds->lightmapVecs[1], w.points[0]);
+ VectorMA(ds->lightmapOrigin, (float) x - LIGHTMAP_PIXELSHIFT - ds->lightmapX, ds->lightmapVecs[0], w.points[1]);
+ VectorMA(w.points[1], (float) y - LIGHTMAP_PIXELSHIFT + 1 - ds->lightmapY, ds->lightmapVecs[1], w.points[1]);
+ VectorMA(ds->lightmapOrigin, (float) x - LIGHTMAP_PIXELSHIFT + 1 - ds->lightmapX, ds->lightmapVecs[0], w.points[2]);
+ VectorMA(w.points[2], (float) y - LIGHTMAP_PIXELSHIFT + 1 - ds->lightmapY, ds->lightmapVecs[1], w.points[2]);
+ VectorMA(ds->lightmapOrigin, (float) x - LIGHTMAP_PIXELSHIFT + 1 - ds->lightmapX, ds->lightmapVecs[0], w.points[3]);
+ VectorMA(w.points[3], (float) y - LIGHTMAP_PIXELSHIFT - ds->lightmapY, ds->lightmapVecs[1], w.points[3]);
+ w.numpoints = 4;
+ }
+ DebugNet_DrawWinding(&w, color);
+}
+
+/*
+============
+VL_DrawPortals
+============
+*/
+void VL_DrawPortals(void)
+{
+ int j;
+ lportal_t *p;
+
+ for (j = 0; j < numportals * 2; j++)
+ {
+ p = portals + j;
+ DebugNet_DrawWinding(p->winding, 1);
+ }
+}
+
+/*
+============
+VL_DrawLeaf
+============
+*/
+void VL_DrawLeaf(int cluster)
+{
+ int i;
+ lleaf_t *leaf;
+ lportal_t *p;
+
+ leaf = &leafs[cluster];
+ for (i = 0; i < leaf->numportals; i++)
+ {
+ p = leaf->portals[i];
+ DebugNet_DrawWinding(p->winding, 1);
+ }
+}
+
+#endif //DEBUGNET
+
+/*
+=============
+VL_SplitWinding
+=============
+*/
+int VL_SplitWinding (winding_t *in, winding_t *back, plane_t *split, float epsilon)
+{
+ vec_t dists[128];
+ int sides[128];
+ int counts[3];
+ vec_t dot;
+ int i, j;
+ vec_t *p1, *p2;
+ vec3_t mid;
+ winding_t out;
+ winding_t *neww;
+
+ counts[0] = counts[1] = counts[2] = 0;
+
+ // determine sides for each point
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ dot = DotProduct (in->points[i], split->normal);
+ dot -= split->dist;
+ dists[i] = dot;
+ if (dot > epsilon)
+ sides[i] = SIDE_FRONT;
+ else if (dot < -epsilon)
+ sides[i] = SIDE_BACK;
+ else
+ {
+ sides[i] = SIDE_ON;
+ }
+ counts[sides[i]]++;
+ }
+
+ if (!counts[SIDE_BACK])
+ {
+ if (!counts[SIDE_FRONT])
+ return SIDE_ON;
+ else
+ return SIDE_FRONT;
+ }
+
+ if (!counts[SIDE_FRONT])
+ {
+ return SIDE_BACK;
+ }
+
+ sides[i] = sides[0];
+ dists[i] = dists[0];
+
+ neww = &out;
+
+ neww->numpoints = 0;
+ back->numpoints = 0;
+
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ p1 = in->points[i];
+
+ if (neww->numpoints >= MAX_POINTS_ON_FIXED_WINDING)
+ {
+ _printf("WARNING: VL_SplitWinding -> MAX_POINTS_ON_FIXED_WINDING overflowed\n");
+ return SIDE_FRONT; // can't chop -- fall back to original
+ }
+ if (back->numpoints >= MAX_POINTS_ON_FIXED_WINDING)
+ {
+ _printf("WARNING: VL_SplitWinding -> MAX_POINTS_ON_FIXED_WINDING overflowed\n");
+ return SIDE_FRONT;
+ }
+
+ if (sides[i] == SIDE_ON)
+ {
+ VectorCopy (p1, neww->points[neww->numpoints]);
+ neww->numpoints++;
+ VectorCopy (p1, back->points[back->numpoints]);
+ back->numpoints++;
+ continue;
+ }
+
+ if (sides[i] == SIDE_FRONT)
+ {
+ VectorCopy (p1, neww->points[neww->numpoints]);
+ neww->numpoints++;
+ }
+ if (sides[i] == SIDE_BACK)
+ {
+ VectorCopy (p1, back->points[back->numpoints]);
+ back->numpoints++;
+ }
+
+ if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i])
+ continue;
+
+ if (neww->numpoints >= MAX_POINTS_ON_FIXED_WINDING)
+ {
+ _printf("WARNING: VL_SplitWinding -> MAX_POINTS_ON_FIXED_WINDING overflowed\n");
+ return SIDE_FRONT; // can't chop -- fall back to original
+ }
+
+ if (back->numpoints >= MAX_POINTS_ON_FIXED_WINDING)
+ {
+ _printf("WARNING: VL_SplitWinding -> MAX_POINTS_ON_FIXED_WINDING overflowed\n");
+ return SIDE_FRONT; // can't chop -- fall back to original
+ }
+
+ // generate a split point
+ p2 = in->points[(i+1)%in->numpoints];
+
+ dot = dists[i] / (dists[i]-dists[i+1]);
+ for (j=0 ; j<3 ; j++)
+ { // avoid round off error when possible
+ if (split->normal[j] == 1)
+ mid[j] = split->dist;
+ else if (split->normal[j] == -1)
+ mid[j] = -split->dist;
+ else
+ mid[j] = p1[j] + dot*(p2[j]-p1[j]);
+ }
+
+ VectorCopy (mid, neww->points[neww->numpoints]);
+ neww->numpoints++;
+ VectorCopy (mid, back->points[back->numpoints]);
+ back->numpoints++;
+ }
+ memcpy(in, &out, sizeof(winding_t));
+
+ return SIDE_CROSS;
+}
+
+/*
+=====================
+VL_LinkSurfaceIntoCluster
+=====================
+*/
+void VL_LinkSurfaceIntoCluster(int cluster, int surfaceNum)
+{
+ lleaf_t *leaf;
+ int i;
+
+ leaf = &leafs[cluster];
+
+ for (i = 0; i < leaf->numSurfaces; i++)
+ {
+ if (clustersurfaces[leaf->firstSurface + i] == surfaceNum)
+ return;
+ }
+ for (i = numclustersurfaces; i > leaf->firstSurface + leaf->numSurfaces; i--)
+ clustersurfaces[i] = clustersurfaces[i-1];
+ for (i = 0; i < portalclusters; i++)
+ {
+ if (i == cluster)
+ continue;
+ if (leafs[i].firstSurface >= leaf->firstSurface + leaf->numSurfaces)
+ leafs[i].firstSurface++;
+ }
+ clustersurfaces[leaf->firstSurface + leaf->numSurfaces] = surfaceNum;
+ leaf->numSurfaces++;
+ numclustersurfaces++;
+ if (numclustersurfaces >= MAX_MAP_LEAFFACES)
+ Error("MAX_MAP_LEAFFACES");
+}
+
+/*
+=====================
+VL_R_LinkSurface
+=====================
+*/
+void VL_R_LinkSurface(int nodenum, int surfaceNum, winding_t *w)
+{
+ int leafnum, cluster, res;
+ dnode_t *node;
+ dplane_t *plane;
+ winding_t back;
+ plane_t split;
+
+ while(nodenum >= 0)
+ {
+ node = &dnodes[nodenum];
+ plane = &dplanes[node->planeNum];
+
+ VectorCopy(plane->normal, split.normal);
+ split.dist = plane->dist;
+ res = VL_SplitWinding (w, &back, &split, 0.1);
+
+ if (res == SIDE_FRONT)
+ {
+ nodenum = node->children[0];
+ }
+ else if (res == SIDE_BACK)
+ {
+ nodenum = node->children[1];
+ }
+ else if (res == SIDE_ON)
+ {
+ memcpy(&back, w, sizeof(winding_t));
+ VL_R_LinkSurface(node->children[1], surfaceNum, &back);
+ nodenum = node->children[0];
+ }
+ else
+ {
+ VL_R_LinkSurface(node->children[1], surfaceNum, &back);
+ nodenum = node->children[0];
+ }
+ }
+ leafnum = -nodenum - 1;
+ cluster = dleafs[leafnum].cluster;
+ if (cluster != -1)
+ {
+ VL_LinkSurfaceIntoCluster(cluster, surfaceNum);
+ }
+}
+
+/*
+=====================
+VL_LinkSurfaces
+
+maybe link each facet seperately instead of the test surfaces?
+=====================
+*/
+void VL_LinkSurfaces(void)
+{
+ int i, j;
+ lsurfaceTest_t *test;
+ lFacet_t *facet;
+ winding_t winding;
+
+ for ( i = 0 ; i < numDrawSurfaces ; i++ )
+ {
+ test = lsurfaceTest[ i ];
+ if (!test)
+ continue;
+ for (j = 0; j < test->numFacets; j++)
+ {
+ facet = &test->facets[j];
+ memcpy(winding.points, facet->points, facet->numpoints * sizeof(vec3_t));
+ winding.numpoints = facet->numpoints;
+ VL_R_LinkSurface(0, i, &winding);
+ }
+ }
+}
+
+/*
+=====================
+VL_TextureMatrixFromPoints
+=====================
+*/
+void VL_TextureMatrixFromPoints( lFacet_t *f, drawVert_t *a, drawVert_t *b, drawVert_t *c ) {
+ int i, j;
+ float t;
+ float m[3][4];
+ float s;
+
+ // This is an incredibly stupid way of solving a three variable equation
+ for ( i = 0 ; i < 2 ; i++ ) {
+
+ m[0][0] = a->xyz[0];
+ m[0][1] = a->xyz[1];
+ m[0][2] = a->xyz[2];
+ m[0][3] = a->st[i];
+
+ m[1][0] = b->xyz[0];
+ m[1][1] = b->xyz[1];
+ m[1][2] = b->xyz[2];
+ m[1][3] = b->st[i];
+
+ m[2][0] = c->xyz[0];
+ m[2][1] = c->xyz[1];
+ m[2][2] = c->xyz[2];
+ m[2][3] = c->st[i];
+
+ if ( fabs(m[1][0]) > fabs(m[0][0]) && fabs(m[1][0]) > fabs(m[2][0]) ) {
+ for ( j = 0 ; j < 4 ; j ++ ) {
+ t = m[0][j];
+ m[0][j] = m[1][j];
+ m[1][j] = t;
+ }
+ } else if ( fabs(m[2][0]) > fabs(m[0][0]) && fabs(m[2][0]) > fabs(m[1][0]) ) {
+ for ( j = 0 ; j < 4 ; j ++ ) {
+ t = m[0][j];
+ m[0][j] = m[2][j];
+ m[2][j] = t;
+ }
+ }
+
+ s = 1.0 / m[0][0];
+ m[0][0] *= s;
+ m[0][1] *= s;
+ m[0][2] *= s;
+ m[0][3] *= s;
+
+ s = m[1][0];
+ m[1][0] -= m[0][0] * s;
+ m[1][1] -= m[0][1] * s;
+ m[1][2] -= m[0][2] * s;
+ m[1][3] -= m[0][3] * s;
+
+ s = m[2][0];
+ m[2][0] -= m[0][0] * s;
+ m[2][1] -= m[0][1] * s;
+ m[2][2] -= m[0][2] * s;
+ m[2][3] -= m[0][3] * s;
+
+ if ( fabs(m[2][1]) > fabs(m[1][1]) ) {
+ for ( j = 0 ; j < 4 ; j ++ ) {
+ t = m[1][j];
+ m[1][j] = m[2][j];
+ m[2][j] = t;
+ }
+ }
+
+ s = 1.0 / m[1][1];
+ m[1][0] *= s;
+ m[1][1] *= s;
+ m[1][2] *= s;
+ m[1][3] *= s;
+
+ s = m[2][1];// / m[1][1];
+ m[2][0] -= m[1][0] * s;
+ m[2][1] -= m[1][1] * s;
+ m[2][2] -= m[1][2] * s;
+ m[2][3] -= m[1][3] * s;
+
+ s = 1.0 / m[2][2];
+ m[2][0] *= s;
+ m[2][1] *= s;
+ m[2][2] *= s;
+ m[2][3] *= s;
+
+ f->textureMatrix[i][2] = m[2][3];
+ f->textureMatrix[i][1] = m[1][3] - f->textureMatrix[i][2] * m[1][2];
+ f->textureMatrix[i][0] = m[0][3] - f->textureMatrix[i][2] * m[0][2] - f->textureMatrix[i][1] * m[0][1];
+
+ f->textureMatrix[i][3] = 0;
+/*
+ s = fabs( DotProduct( a->xyz, f->textureMatrix[i] ) - a->st[i] );
+ if ( s > 0.01 ) {
+ Error( "Bad textureMatrix" );
+ }
+ s = fabs( DotProduct( b->xyz, f->textureMatrix[i] ) - b->st[i] );
+ if ( s > 0.01 ) {
+ Error( "Bad textureMatrix" );
+ }
+ s = fabs( DotProduct( c->xyz, f->textureMatrix[i] ) - c->st[i] );
+ if ( s > 0.01 ) {
+ Error( "Bad textureMatrix" );
+ }
+*/
+ }
+}
+
+/*
+=====================
+VL_LightmapMatrixFromPoints
+=====================
+*/
+void VL_LightmapMatrixFromPoints( dsurface_t *dsurf, shaderInfo_t *si, lFacet_t *f, drawVert_t *a, drawVert_t *b, drawVert_t *c ) {
+ int i, j;
+ float t;
+ float m[3][4], al, bl, cl;
+ float s;
+ int h, w, ssize;
+ vec3_t mins, maxs, delta, size, planeNormal;
+ drawVert_t *verts;
+ static int message;
+
+ // vertex-lit triangle model
+ if ( dsurf->surfaceType == MST_TRIANGLE_SOUP ) {
+ return;
+ }
+
+ if ( dsurf->lightmapNum < 0 ) {
+ return; // doesn't need lighting
+ }
+
+ VectorClear(f->mins);
+ if (dsurf->surfaceType != MST_PATCH)
+ {
+ ssize = samplesize;
+ if (si->lightmapSampleSize)
+ ssize = si->lightmapSampleSize;
+ ClearBounds( mins, maxs );
+ verts = &drawVerts[dsurf->firstVert];
+ for ( i = 0 ; i < dsurf->numVerts ; i++ ) {
+ AddPointToBounds( verts[i].xyz, mins, maxs );
+ }
+ // round to the lightmap resolution
+ for ( i = 0 ; i < 3 ; i++ ) {
+ mins[i] = ssize * floor( mins[i] / ssize );
+ maxs[i] = ssize * ceil( maxs[i] / ssize );
+ f->mins[i] = mins[i];
+ size[i] = (maxs[i] - mins[i]) / ssize + 1;
+ }
+ // the two largest axis will be the lightmap size
+ VectorClear(f->lightmapMatrix[0]);
+ f->lightmapMatrix[0][3] = 0;
+ VectorClear(f->lightmapMatrix[1]);
+ f->lightmapMatrix[1][3] = 0;
+
+ planeNormal[0] = fabs( dsurf->lightmapVecs[2][0] );
+ planeNormal[1] = fabs( dsurf->lightmapVecs[2][1] );
+ planeNormal[2] = fabs( dsurf->lightmapVecs[2][2] );
+
+ if ( planeNormal[0] >= planeNormal[1] && planeNormal[0] >= planeNormal[2] ) {
+ w = size[1];
+ h = size[2];
+ f->lightmapMatrix[0][1] = 1.0 / ssize;
+ f->lightmapMatrix[1][2] = 1.0 / ssize;
+ } else if ( planeNormal[1] >= planeNormal[0] && planeNormal[1] >= planeNormal[2] ) {
+ w = size[0];
+ h = size[2];
+ f->lightmapMatrix[0][0] = 1.0 / ssize;
+ f->lightmapMatrix[1][2] = 1.0 / ssize;
+ } else {
+ w = size[0];
+ h = size[1];
+ f->lightmapMatrix[0][0] = 1.0 / ssize;
+ f->lightmapMatrix[1][1] = 1.0 / ssize;
+ }
+ if ( w > LIGHTMAP_WIDTH ) {
+ VectorScale ( f->lightmapMatrix[0], (float)LIGHTMAP_SIZE/w, f->lightmapMatrix[0] );
+ }
+
+ if ( h > LIGHTMAP_HEIGHT ) {
+ VectorScale ( f->lightmapMatrix[1], (float)LIGHTMAP_SIZE/h, f->lightmapMatrix[1] );
+ }
+ VectorSubtract(a->xyz, f->mins, delta);
+ s = (DotProduct( delta, f->lightmapMatrix[0] ) + dsurf->lightmapX + 0.5) / LIGHTMAP_SIZE;
+ if ( fabs(s - a->lightmap[0]) > 0.01 ) {
+ _printf( "Bad lightmapMatrix" );
+ }
+ t = (DotProduct( delta, f->lightmapMatrix[1] ) + dsurf->lightmapY + 0.5) / LIGHTMAP_SIZE;
+ if ( fabs(t - a->lightmap[1]) > 0.01 ) {
+ _printf( "Bad lightmapMatrix" );
+ }
+ VectorSubtract(b->xyz, f->mins, delta);
+ s = (DotProduct( delta, f->lightmapMatrix[0] ) + dsurf->lightmapX + 0.5) / LIGHTMAP_SIZE;
+ if ( fabs(s - b->lightmap[0]) > 0.01 ) {
+ _printf( "Bad lightmapMatrix" );
+ }
+ t = (DotProduct( delta, f->lightmapMatrix[1] ) + dsurf->lightmapY + 0.5) / LIGHTMAP_SIZE;
+ if ( fabs(t - b->lightmap[1]) > 0.01 ) {
+ _printf( "Bad lightmapMatrix" );
+ }
+ VectorSubtract(c->xyz, f->mins, delta);
+ s = (DotProduct( delta, f->lightmapMatrix[0] ) + dsurf->lightmapX + 0.5) / LIGHTMAP_SIZE;
+ if ( fabs(s - c->lightmap[0]) > 0.01 ) {
+ _printf( "Bad lightmapMatrix" );
+ }
+ t = (DotProduct( delta, f->lightmapMatrix[1] ) + dsurf->lightmapY + 0.5) / LIGHTMAP_SIZE;
+ if ( fabs(t - c->lightmap[1]) > 0.01 ) {
+ _printf( "Bad lightmapMatrix" );
+ }
+ VectorAdd(f->mins, surfaceOrigin[dsurf - drawSurfaces], f->mins);
+ return;
+ }
+ // This is an incredibly stupid way of solving a three variable equation
+ for ( i = 0 ; i < 2 ; i++ ) {
+
+ if (i)
+ al = a->lightmap[i] - ((float) dsurf->lightmapY + 0.5) / LIGHTMAP_SIZE;
+ else
+ al = a->lightmap[i] - ((float) dsurf->lightmapX + 0.5) / LIGHTMAP_SIZE;
+
+ m[0][0] = a->xyz[0] - f->mins[0];
+ m[0][1] = a->xyz[1] - f->mins[1];
+ m[0][2] = a->xyz[2] - f->mins[2];
+ m[0][3] = al;
+
+ if (i)
+ bl = b->lightmap[i] - ((float) dsurf->lightmapY + 0.5) / LIGHTMAP_SIZE;
+ else
+ bl = b->lightmap[i] - ((float) dsurf->lightmapX + 0.5) / LIGHTMAP_SIZE;
+
+ m[1][0] = b->xyz[0] - f->mins[0];
+ m[1][1] = b->xyz[1] - f->mins[1];
+ m[1][2] = b->xyz[2] - f->mins[2];
+ m[1][3] = bl;
+
+ if (i)
+ cl = c->lightmap[i] - ((float) dsurf->lightmapY + 0.5) / LIGHTMAP_SIZE;
+ else
+ cl = c->lightmap[i] - ((float) dsurf->lightmapX + 0.5) / LIGHTMAP_SIZE;
+
+ m[2][0] = c->xyz[0] - f->mins[0];
+ m[2][1] = c->xyz[1] - f->mins[1];
+ m[2][2] = c->xyz[2] - f->mins[2];
+ m[2][3] = cl;
+
+ if ( fabs(m[1][0]) > fabs(m[0][0]) && fabs(m[1][0]) >= fabs(m[2][0]) ) {
+ for ( j = 0 ; j < 4 ; j ++ ) {
+ t = m[0][j];
+ m[0][j] = m[1][j];
+ m[1][j] = t;
+ }
+ } else if ( fabs(m[2][0]) > fabs(m[0][0]) && fabs(m[2][0]) >= fabs(m[1][0]) ) {
+ for ( j = 0 ; j < 4 ; j ++ ) {
+ t = m[0][j];
+ m[0][j] = m[2][j];
+ m[2][j] = t;
+ }
+ }
+
+ if (m[0][0])
+ {
+ s = 1.0 / m[0][0];
+ m[0][0] *= s;
+ m[0][1] *= s;
+ m[0][2] *= s;
+ m[0][3] *= s;
+
+ s = m[1][0];
+ m[1][0] -= m[0][0] * s;
+ m[1][1] -= m[0][1] * s;
+ m[1][2] -= m[0][2] * s;
+ m[1][3] -= m[0][3] * s;
+
+ s = m[2][0];
+ m[2][0] -= m[0][0] * s;
+ m[2][1] -= m[0][1] * s;
+ m[2][2] -= m[0][2] * s;
+ m[2][3] -= m[0][3] * s;
+ }
+
+ if ( fabs(m[2][1]) > fabs(m[1][1]) ) {
+ for ( j = 0 ; j < 4 ; j ++ ) {
+ t = m[1][j];
+ m[1][j] = m[2][j];
+ m[2][j] = t;
+ }
+ }
+
+ if (m[1][1])
+ {
+ s = 1.0 / m[1][1];
+ m[1][0] *= s;
+ m[1][1] *= s;
+ m[1][2] *= s;
+ m[1][3] *= s;
+
+ s = m[2][1];
+ m[2][0] -= m[1][0] * s;
+ m[2][1] -= m[1][1] * s;
+ m[2][2] -= m[1][2] * s;
+ m[2][3] -= m[1][3] * s;
+ }
+
+ if (m[2][2])
+ {
+ s = 1.0 / m[2][2];
+ m[2][0] *= s;
+ m[2][1] *= s;
+ m[2][2] *= s;
+ m[2][3] *= s;
+ }
+
+ f->lightmapMatrix[i][2] = m[2][3];
+ f->lightmapMatrix[i][1] = m[1][3] - f->lightmapMatrix[i][2] * m[1][2];
+ f->lightmapMatrix[i][0] = m[0][3] - f->lightmapMatrix[i][2] * m[0][2] - f->lightmapMatrix[i][1] * m[0][1];
+
+ f->lightmapMatrix[i][3] = 0;
+
+ VectorSubtract(a->xyz, f->mins, delta);
+ s = fabs( DotProduct( delta, f->lightmapMatrix[i] ) - al );
+ if ( s > 0.01 ) {
+ if (!message)
+ _printf( "Bad lightmapMatrix\n" );
+ message = qtrue;
+ }
+ VectorSubtract(b->xyz, f->mins, delta);
+ s = fabs( DotProduct( delta, f->lightmapMatrix[i] ) - bl );
+ if ( s > 0.01 ) {
+ if (!message)
+ _printf( "Bad lightmapMatrix\n" );
+ message = qtrue;
+ }
+ VectorSubtract(c->xyz, f->mins, delta);
+ s = fabs( DotProduct( delta, f->lightmapMatrix[i] ) - cl );
+ if ( s > 0.01 ) {
+ if (!message)
+ _printf( "Bad lightmapMatrix\n" );
+ message = qtrue;
+ }
+ VectorAdd(f->mins, surfaceOrigin[dsurf - drawSurfaces], f->mins);
+ }
+}
+
+/*
+=============
+Plane_Equal
+=============
+*/
+#define NORMAL_EPSILON 0.0001
+#define DIST_EPSILON 0.02
+
+int Plane_Equal(plane_t *a, plane_t *b, int flip)
+{
+ vec3_t normal;
+ float dist;
+
+ if (flip) {
+ normal[0] = - b->normal[0];
+ normal[1] = - b->normal[1];
+ normal[2] = - b->normal[2];
+ dist = - b->dist;
+ }
+ else {
+ normal[0] = b->normal[0];
+ normal[1] = b->normal[1];
+ normal[2] = b->normal[2];
+ dist = b->dist;
+ }
+ if (
+ fabs(a->normal[0] - normal[0]) < NORMAL_EPSILON
+ && fabs(a->normal[1] - normal[1]) < NORMAL_EPSILON
+ && fabs(a->normal[2] - normal[2]) < NORMAL_EPSILON
+ && fabs(a->dist - dist) < DIST_EPSILON )
+ return qtrue;
+ return qfalse;
+}
+
+/*
+=============
+VL_PlaneFromPoints
+=============
+*/
+qboolean VL_PlaneFromPoints( plane_t *plane, const vec3_t a, const vec3_t b, const vec3_t c ) {
+ vec3_t d1, d2;
+
+ VectorSubtract( b, a, d1 );
+ VectorSubtract( c, a, d2 );
+ CrossProduct( d2, d1, plane->normal );
+ if ( VectorNormalize( plane->normal, plane->normal ) == 0 ) {
+ return qfalse;
+ }
+
+ plane->dist = DotProduct( a, plane->normal );
+ return qtrue;
+}
+
+/*
+=====================
+VL_GenerateBoundaryForPoints
+=====================
+*/
+void VL_GenerateBoundaryForPoints( plane_t *boundary, plane_t *plane, vec3_t a, vec3_t b ) {
+ vec3_t d1;
+
+ // make a perpendicular vector to the edge and the surface
+ VectorSubtract( a, b, d1 );
+ CrossProduct( plane->normal, d1, boundary->normal );
+ VectorNormalize( boundary->normal, boundary->normal );
+ boundary->dist = DotProduct( a, boundary->normal );
+}
+
+/*
+=====================
+VL_GenerateFacetFor3Points
+=====================
+*/
+qboolean VL_GenerateFacetFor3Points( dsurface_t *dsurf, shaderInfo_t *si, lFacet_t *f, drawVert_t *a, drawVert_t *b, drawVert_t *c ) {
+ //
+ vec3_t dir;
+ int i;
+
+ // if we can't generate a valid plane for the points, ignore the facet
+ if ( !VL_PlaneFromPoints( &f->plane, a->xyz, b->xyz, c->xyz ) ) {
+ f->numpoints = 0;
+ return qfalse;
+ }
+
+ f->num = numfacets++;
+
+ VectorAdd( a->xyz, surfaceOrigin[dsurf - drawSurfaces], f->points[0] );
+ VectorAdd( b->xyz, surfaceOrigin[dsurf - drawSurfaces], f->points[1] );
+ VectorAdd( c->xyz, surfaceOrigin[dsurf - drawSurfaces], f->points[2] );
+
+ f->lightmapCoords[0][0] = a->lightmap[0];
+ f->lightmapCoords[0][1] = a->lightmap[1];
+ f->lightmapCoords[1][0] = b->lightmap[0];
+ f->lightmapCoords[1][1] = b->lightmap[1];
+ f->lightmapCoords[2][0] = c->lightmap[0];
+ f->lightmapCoords[2][1] = c->lightmap[1];
+
+ VL_GenerateBoundaryForPoints( &f->boundaries[0], &f->plane, f->points[0], f->points[1] );
+ VL_GenerateBoundaryForPoints( &f->boundaries[1], &f->plane, f->points[1], f->points[2] );
+ VL_GenerateBoundaryForPoints( &f->boundaries[2], &f->plane, f->points[2], f->points[0] );
+
+ for (i = 0; i < 3; i++)
+ {
+ VectorSubtract(f->points[(i+1)%3], f->points[i], dir);
+ if (VectorLength(dir) < 0.1)
+ return qfalse;
+ }
+
+ VL_TextureMatrixFromPoints( f, a, b, c );
+ VL_LightmapMatrixFromPoints( dsurf, si, f, a, b, c );
+
+ f->numpoints = 3;
+
+ return qtrue;
+}
+
+/*
+=====================
+VL_GenerateFacetFor4Points
+
+Attempts to use four points as a planar quad
+=====================
+*/
+#define PLANAR_EPSILON 0.1
+qboolean VL_GenerateFacetFor4Points( dsurface_t *dsurf, shaderInfo_t *si, lFacet_t *f, drawVert_t *a, drawVert_t *b, drawVert_t *c, drawVert_t *d ) {
+ float dist;
+ vec3_t dir;
+ int i;
+ plane_t plane;
+
+ // if we can't generate a valid plane for the points, ignore the facet
+ if ( !VL_PlaneFromPoints( &f->plane, a->xyz, b->xyz, c->xyz ) ) {
+ f->numpoints = 0;
+ return qfalse;
+ }
+
+ // if the fourth point is also on the plane, we can make a quad facet
+ dist = DotProduct( d->xyz, f->plane.normal ) - f->plane.dist;
+ if ( fabs( dist ) > PLANAR_EPSILON ) {
+ f->numpoints = 0;
+ return qfalse;
+ }
+
+ VectorAdd( a->xyz, surfaceOrigin[dsurf - drawSurfaces], f->points[0] );
+ VectorAdd( b->xyz, surfaceOrigin[dsurf - drawSurfaces], f->points[1] );
+ VectorAdd( c->xyz, surfaceOrigin[dsurf - drawSurfaces], f->points[2] );
+ VectorAdd( d->xyz, surfaceOrigin[dsurf - drawSurfaces], f->points[3] );
+
+ for (i = 1; i < 4; i++)
+ {
+ if ( !VL_PlaneFromPoints( &plane, f->points[i], f->points[(i+1) % 4], f->points[(i+2) % 4]) ) {
+ f->numpoints = 0;
+ return qfalse;
+ }
+
+ if (!Plane_Equal(&f->plane, &plane, qfalse)) {
+ f->numpoints = 0;
+ return qfalse;
+ }
+ }
+
+ f->lightmapCoords[0][0] = a->lightmap[0];
+ f->lightmapCoords[0][1] = a->lightmap[1];
+ f->lightmapCoords[1][0] = b->lightmap[0];
+ f->lightmapCoords[1][1] = b->lightmap[1];
+ f->lightmapCoords[2][0] = c->lightmap[0];
+ f->lightmapCoords[2][1] = c->lightmap[1];
+ f->lightmapCoords[3][0] = d->lightmap[0];
+ f->lightmapCoords[3][1] = d->lightmap[1];
+
+ VL_GenerateBoundaryForPoints( &f->boundaries[0], &f->plane, f->points[0], f->points[1] );
+ VL_GenerateBoundaryForPoints( &f->boundaries[1], &f->plane, f->points[1], f->points[2] );
+ VL_GenerateBoundaryForPoints( &f->boundaries[2], &f->plane, f->points[2], f->points[3] );
+ VL_GenerateBoundaryForPoints( &f->boundaries[3], &f->plane, f->points[3], f->points[0] );
+
+ for (i = 0; i < 4; i++)
+ {
+ VectorSubtract(f->points[(i+1)%4], f->points[i], dir);
+ if (VectorLength(dir) < 0.1)
+ return qfalse;
+ }
+
+ VL_TextureMatrixFromPoints( f, a, b, c );
+ VL_LightmapMatrixFromPoints( dsurf, si, f, a, b, c );
+
+ f->num = numfacets++;
+ f->numpoints = 4;
+
+ return qtrue;
+}
+
+/*
+===============
+VL_SphereFromBounds
+===============
+*/
+void VL_SphereFromBounds( vec3_t mins, vec3_t maxs, vec3_t origin, float *radius ) {
+ vec3_t temp;
+
+ VectorAdd( mins, maxs, origin );
+ VectorScale( origin, 0.5, origin );
+ VectorSubtract( maxs, origin, temp );
+ *radius = VectorLength( temp );
+}
+
+/*
+====================
+VL_FacetsForTriangleSurface
+====================
+*/
+void VL_FacetsForTriangleSurface( dsurface_t *dsurf, shaderInfo_t *si, lsurfaceTest_t *test ) {
+ int i;
+ drawVert_t *v1, *v2, *v3, *v4;
+ int count;
+ int i1, i2, i3, i4, i5, i6;
+
+ test->patch = qfalse;
+ if (dsurf->surfaceType == MST_TRIANGLE_SOUP)
+ test->trisoup = qtrue;
+ else
+ test->trisoup = qfalse;
+ test->numFacets = dsurf->numIndexes / 3;
+ test->facets = malloc( sizeof( test->facets[0] ) * test->numFacets );
+ test->shader = si;
+
+ count = 0;
+ for ( i = 0 ; i < test->numFacets ; i++ ) {
+ i1 = drawIndexes[ dsurf->firstIndex + i*3 ];
+ i2 = drawIndexes[ dsurf->firstIndex + i*3 + 1 ];
+ i3 = drawIndexes[ dsurf->firstIndex + i*3 + 2 ];
+
+ v1 = &drawVerts[ dsurf->firstVert + i1 ];
+ v2 = &drawVerts[ dsurf->firstVert + i2 ];
+ v3 = &drawVerts[ dsurf->firstVert + i3 ];
+
+ // try and make a quad out of two triangles
+ if ( i != test->numFacets - 1 ) {
+ i4 = drawIndexes[ dsurf->firstIndex + i*3 + 3 ];
+ i5 = drawIndexes[ dsurf->firstIndex + i*3 + 4 ];
+ i6 = drawIndexes[ dsurf->firstIndex + i*3 + 5 ];
+ if ( i4 == i3 && i5 == i2 ) {
+ v4 = &drawVerts[ dsurf->firstVert + i6 ];
+ if ( VL_GenerateFacetFor4Points( dsurf, si, &test->facets[count], v1, v2, v4, v3 ) ) {
+ count++;
+ i++; // skip next tri
+ continue;
+ }
+ }
+ }
+
+ if (VL_GenerateFacetFor3Points( dsurf, si, &test->facets[count], v1, v2, v3 )) {
+ count++;
+ }
+ }
+
+ // we may have turned some pairs into quads
+ test->numFacets = count;
+}
+
+/*
+====================
+VL_FacetsForPatch
+====================
+*/
+void VL_FacetsForPatch( dsurface_t *dsurf, int surfaceNum, shaderInfo_t *si, lsurfaceTest_t *test ) {
+ int i, j, x, y;
+ drawVert_t *v1, *v2, *v3, *v4;
+ int count, ssize;
+ mesh_t mesh;
+ mesh_t *subdivided, *detailmesh, *newmesh;
+ int widthtable[LIGHTMAP_SIZE], heighttable[LIGHTMAP_SIZE];
+
+ mesh.width = dsurf->patchWidth;
+ mesh.height = dsurf->patchHeight;
+ mesh.verts = &drawVerts[ dsurf->firstVert ];
+
+ newmesh = SubdivideMesh( mesh, 8, 999 );
+ PutMeshOnCurve( *newmesh );
+ MakeMeshNormals( *newmesh );
+
+ subdivided = RemoveLinearMeshColumnsRows( newmesh );
+ FreeMesh(newmesh);
+
+ // DebugNet_RemoveAllPolys();
+ // DebugNet_DrawMesh(subdivided);
+
+ ssize = samplesize;
+ if (si->lightmapSampleSize)
+ ssize = si->lightmapSampleSize;
+
+ if ( dsurf->lightmapNum >= 0 ) {
+
+ detailmesh = SubdivideMeshQuads( subdivided, ssize, LIGHTMAP_SIZE, widthtable, heighttable);
+ test->detailMesh = detailmesh;
+
+ // DebugNet_RemoveAllPolys();
+ // DebugNet_DrawMesh(detailmesh);
+
+ if ( detailmesh->width != dsurf->lightmapWidth || detailmesh->height != dsurf->lightmapHeight ) {
+ Error( "Mesh lightmap miscount");
+ }
+ }
+ else {
+ test->detailMesh = NULL;
+ memset(widthtable, 0, sizeof(widthtable));
+ memset(heighttable, 0, sizeof(heighttable));
+ }
+
+ test->patch = qtrue;
+ test->trisoup = qfalse;
+ test->numFacets = ( subdivided->width - 1 ) * ( subdivided->height - 1 ) * 2;
+ test->facets = malloc( sizeof( test->facets[0] ) * test->numFacets );
+ test->shader = si;
+
+ count = 0;
+ x = 0;
+ for ( i = 0 ; i < subdivided->width - 1 ; i++ ) {
+ y = 0;
+ for ( j = 0 ; j < subdivided->height - 1 ; j++ ) {
+
+ v1 = subdivided->verts + j * subdivided->width + i;
+ v2 = v1 + 1;
+ v3 = v1 + subdivided->width + 1;
+ v4 = v1 + subdivided->width;
+
+ if ( VL_GenerateFacetFor4Points( dsurf, si, &test->facets[count], v1, v4, v3, v2 ) ) {
+ test->facets[count].x = x;
+ test->facets[count].y = y;
+ test->facets[count].width = widthtable[i];
+ test->facets[count].height = heighttable[j];
+ count++;
+ } else {
+ if (VL_GenerateFacetFor3Points( dsurf, si, &test->facets[count], v1, v4, v3 )) {
+ test->facets[count].x = x;
+ test->facets[count].y = y;
+ test->facets[count].width = widthtable[i];
+ test->facets[count].height = heighttable[j];
+ count++;
+ }
+ if (VL_GenerateFacetFor3Points( dsurf, si, &test->facets[count], v1, v3, v2 )) {
+ test->facets[count].x = x;
+ test->facets[count].y = y;
+ test->facets[count].width = widthtable[i];
+ test->facets[count].height = heighttable[j];
+ count++;
+ }
+ }
+ y += heighttable[j];
+ }
+ x += widthtable[i];
+ }
+ test->numFacets = count;
+
+ FreeMesh(subdivided);
+}
+
+/*
+=====================
+VL_InitSurfacesForTesting
+=====================
+*/
+void VL_InitSurfacesForTesting( void ) {
+
+ int i, j, k;
+ dsurface_t *dsurf;
+ lsurfaceTest_t *test;
+ shaderInfo_t *si;
+ lFacet_t *facet;
+
+ for ( i = 0 ; i < numDrawSurfaces ; i++ ) {
+ // don't light the entity surfaces with vlight
+ if ( entitySurface[i] )
+ continue;
+ //
+ dsurf = &drawSurfaces[ i ];
+ if ( !dsurf->numIndexes && !dsurf->patchWidth ) {
+ continue;
+ }
+
+ si = ShaderInfoForShader( dshaders[ dsurf->shaderNum].shader );
+ // if the surface is translucent and does not cast an alpha shadow
+ if ( (si->contents & CONTENTS_TRANSLUCENT) && !(si->surfaceFlags & SURF_ALPHASHADOW) ) {
+ // if the surface has no lightmap
+ if ( dsurf->lightmapNum < 0 )
+ continue;
+ }
+
+ test = malloc( sizeof( *test ) );
+ memset(test, 0, sizeof( *test ));
+ test->mutex = MutexAlloc();
+ test->numvolumes = 0;
+ if (si->forceTraceLight)
+ test->always_tracelight = qtrue;
+ else if (si->forceVLight)
+ test->always_vlight = qtrue;
+ lsurfaceTest[i] = test;
+
+ if ( dsurf->surfaceType == MST_TRIANGLE_SOUP || dsurf->surfaceType == MST_PLANAR ) {
+ VL_FacetsForTriangleSurface( dsurf, si, test );
+ } else if ( dsurf->surfaceType == MST_PATCH ) {
+ VL_FacetsForPatch( dsurf, i, si, test );
+ }
+ if (numfacets >= MAX_FACETS)
+ Error("numfacets >= MAX_FACETS (%d)", MAX_FACETS);
+
+ ClearBounds( test->mins, test->maxs );
+ for (j = 0; j < test->numFacets; j++)
+ {
+ facet = &test->facets[j];
+ for ( k = 0 ; k < facet->numpoints; k++) {
+ AddPointToBounds( facet->points[k], test->mins, test->maxs );
+ }
+ }
+ VL_SphereFromBounds( test->mins, test->maxs, test->origin, &test->radius );
+ }
+ _printf("%6d facets\n", numfacets);
+ _printf("linking surfaces...\n");
+ VL_LinkSurfaces();
+}
+
+/*
+=============
+VL_ChopWinding
+=============
+*/
+int VL_ChopWinding (winding_t *in, plane_t *split, float epsilon)
+{
+ vec_t dists[128];
+ int sides[128];
+ int counts[3];
+ vec_t dot;
+ int i, j;
+ vec_t *p1, *p2;
+ vec3_t mid;
+ winding_t out;
+ winding_t *neww;
+
+ counts[0] = counts[1] = counts[2] = 0;
+
+ // determine sides for each point
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ dot = DotProduct (in->points[i], split->normal);
+ dot -= split->dist;
+ dists[i] = dot;
+ if (dot > epsilon)
+ sides[i] = SIDE_FRONT;
+ else if (dot < -epsilon)
+ sides[i] = SIDE_BACK;
+ else
+ {
+ sides[i] = SIDE_ON;
+ }
+ counts[sides[i]]++;
+ }
+
+ if (!counts[SIDE_BACK])
+ {
+ if (!counts[SIDE_FRONT])
+ return SIDE_ON;
+ else
+ return SIDE_FRONT;
+ }
+
+ if (!counts[SIDE_FRONT])
+ {
+ return SIDE_BACK;
+ }
+
+ sides[i] = sides[0];
+ dists[i] = dists[0];
+
+ neww = &out;
+
+ neww->numpoints = 0;
+
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ p1 = in->points[i];
+
+ if (neww->numpoints >= MAX_POINTS_ON_FIXED_WINDING)
+ {
+ _printf("WARNING: VL_ChopWinding -> MAX_POINTS_ON_FIXED_WINDING overflowed\n");
+ return SIDE_FRONT; // can't chop -- fall back to original
+ }
+
+ if (sides[i] == SIDE_ON)
+ {
+ VectorCopy (p1, neww->points[neww->numpoints]);
+ neww->numpoints++;
+ continue;
+ }
+
+ if (sides[i] == SIDE_FRONT)
+ {
+ VectorCopy (p1, neww->points[neww->numpoints]);
+ neww->numpoints++;
+ }
+
+ if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i])
+ continue;
+
+ if (neww->numpoints >= MAX_POINTS_ON_FIXED_WINDING)
+ {
+ _printf("WARNING: VL_ChopWinding -> MAX_POINTS_ON_FIXED_WINDING overflowed\n");
+ return SIDE_FRONT; // can't chop -- fall back to original
+ }
+
+ // generate a split point
+ p2 = in->points[(i+1)%in->numpoints];
+
+ dot = dists[i] / (dists[i]-dists[i+1]);
+ for (j=0 ; j<3 ; j++)
+ { // avoid round off error when possible
+ if (split->normal[j] == 1)
+ mid[j] = split->dist;
+ else if (split->normal[j] == -1)
+ mid[j] = -split->dist;
+ else
+ mid[j] = p1[j] + dot*(p2[j]-p1[j]);
+ }
+
+ VectorCopy (mid, neww->points[neww->numpoints]);
+ neww->numpoints++;
+ }
+ memcpy(in, &out, sizeof(winding_t));
+
+ return SIDE_CROSS;
+}
+
+/*
+=============
+VL_ChopWindingWithBrush
+
+ returns all winding fragments outside the brush
+=============
+*/
+int VL_ChopWindingWithBrush(winding_t *w, dbrush_t *brush, winding_t *outwindings, int maxout)
+{
+ int i, res, numout;
+ winding_t front, back;
+ plane_t plane;
+
+ numout = 0;
+ memcpy(front.points, w->points, w->numpoints * sizeof(vec3_t));
+ front.numpoints = w->numpoints;
+ for (i = 0; i < brush->numSides; i++)
+ {
+ VectorCopy(dplanes[ dbrushsides[ brush->firstSide + i ].planeNum ].normal, plane.normal);
+ VectorInverse(plane.normal);
+ plane.dist = -dplanes[ dbrushsides[ brush->firstSide + i ].planeNum ].dist;
+ res = VL_SplitWinding(&front, &back, &plane, 0.1);
+ if (res == SIDE_BACK || res == SIDE_ON)
+ {
+ memcpy(outwindings[0].points, w->points, w->numpoints * sizeof(vec3_t));
+ outwindings[0].numpoints = w->numpoints;
+ return 1; //did not intersect
+ }
+ if (res != SIDE_FRONT)
+ {
+ if (numout >= maxout)
+ {
+ _printf("WARNING: VL_ChopWindingWithBrush: more than %d windings\n", maxout);
+ return 0;
+ }
+ memcpy(outwindings[numout].points, back.points, back.numpoints * sizeof(vec3_t));
+ outwindings[numout].numpoints = back.numpoints;
+ numout++;
+ }
+ }
+ return numout;
+}
+
+/*
+=============
+VL_WindingAreaOutsideBrushes
+=============
+*/
+float VL_WindingAreaOutsideBrushes(winding_t *w, int *brushnums, int numbrushes)
+{
+ int i, j, numwindings[2], n;
+ winding_t windingsbuf[2][64];
+ dbrush_t *brush;
+ float area;
+
+ memcpy(windingsbuf[0][0].points, w->points, w->numpoints * sizeof(vec3_t));
+ windingsbuf[0][0].numpoints = w->numpoints;
+ numwindings[0] = 1;
+ for (i = 0; i < numbrushes; i++)
+ {
+ brush = &dbrushes[brushnums[i]];
+ if (!(dshaders[brush->shaderNum].contentFlags & (
+ CONTENTS_LAVA
+ | CONTENTS_SLIME
+ | CONTENTS_WATER
+ | CONTENTS_FOG
+ | CONTENTS_AREAPORTAL
+ | CONTENTS_PLAYERCLIP
+ | CONTENTS_MONSTERCLIP
+ | CONTENTS_CLUSTERPORTAL
+ | CONTENTS_DONOTENTER
+ | CONTENTS_BODY
+ | CONTENTS_CORPSE
+ | CONTENTS_TRANSLUCENT
+ | CONTENTS_TRIGGER
+ | CONTENTS_NODROP) ) &&
+ (dshaders[brush->shaderNum].contentFlags & CONTENTS_SOLID) )
+ {
+ numwindings[!(i & 1)] = 0;
+ for (j = 0; j < numwindings[i&1]; j++)
+ {
+ n = VL_ChopWindingWithBrush(&windingsbuf[i&1][j], brush,
+ &windingsbuf[!(i&1)][numwindings[!(i&1)]],
+ 64 - numwindings[!(i&1)]);
+ numwindings[!(i&1)] += n;
+ }
+ if (!numwindings[!(i&1)])
+ return 0;
+ }
+ else
+ {
+ for (j = 0; j < numwindings[i&1]; j++)
+ {
+ windingsbuf[!(i&1)][j] = windingsbuf[i&1][j];
+ }
+ numwindings[!(i&1)] = numwindings[i&1];
+ }
+ }
+ area = 0;
+ for (j = 0; j < numwindings[i&1]; j++)
+ {
+ area += WindingArea(&windingsbuf[i&1][j]);
+ }
+ return area;
+}
+
+/*
+=============
+VL_R_WindingAreaOutsideSolid
+=============
+*/
+float VL_R_WindingAreaOutsideSolid(winding_t *w, vec3_t normal, int nodenum)
+{
+ int leafnum, res;
+ float area;
+ dnode_t *node;
+ dleaf_t *leaf;
+ dplane_t *plane;
+ winding_t back;
+ plane_t split;
+
+ area = 0;
+ while(nodenum >= 0)
+ {
+ node = &dnodes[nodenum];
+ plane = &dplanes[node->planeNum];
+
+ VectorCopy(plane->normal, split.normal);
+ split.dist = plane->dist;
+ res = VL_SplitWinding (w, &back, &split, 0.1);
+
+ if (res == SIDE_FRONT)
+ {
+ nodenum = node->children[0];
+ }
+ else if (res == SIDE_BACK)
+ {
+ nodenum = node->children[1];
+ }
+ else if (res == SIDE_ON)
+ {
+ if (DotProduct(normal, plane->normal) > 0)
+ nodenum = node->children[0];
+ else
+ nodenum = node->children[1];
+ }
+ else
+ {
+ area += VL_R_WindingAreaOutsideSolid(&back, normal, node->children[1]);
+ nodenum = node->children[0];
+ }
+ }
+ leafnum = -nodenum - 1;
+ leaf = &dleafs[leafnum];
+ if (leaf->cluster != -1)
+ {
+ area += VL_WindingAreaOutsideBrushes(w, &dleafbrushes[leaf->firstLeafBrush], leaf->numLeafBrushes);
+ }
+ return area;
+}
+
+/*
+=============
+VL_WindingAreaOutsideSolid
+=============
+*/
+float VL_WindingAreaOutsideSolid(winding_t *w, vec3_t normal)
+{
+ return VL_R_WindingAreaOutsideSolid(w, normal, 0);
+}
+
+/*
+=============
+VL_ChopWindingWithFacet
+=============
+*/
+float VL_ChopWindingWithFacet(winding_t *w, lFacet_t *facet)
+{
+ int i;
+
+ for (i = 0; i < facet->numpoints; i++)
+ {
+ if (VL_ChopWinding(w, &facet->boundaries[i], 0) == SIDE_BACK)
+ return 0;
+ }
+ if (nostitching)
+ return WindingArea(w);
+ else
+ return VL_WindingAreaOutsideSolid(w, facet->plane.normal);
+}
+
+/*
+=============
+VL_CalcVisibleLightmapPixelArea
+
+nice brute force ;)
+=============
+*/
+void VL_CalcVisibleLightmapPixelArea(void)
+{
+ int i, j, x, y, k;
+ dsurface_t *ds;
+ lsurfaceTest_t *test;
+ mesh_t *mesh;
+ winding_t w, tmpw;
+ float area;
+
+ _printf("calculating visible lightmap pixel area...\n");
+ for ( i = 0 ; i < numDrawSurfaces ; i++ )
+ {
+ test = lsurfaceTest[ i ];
+ if (!test)
+ continue;
+ ds = &drawSurfaces[ i ];
+
+ if ( ds->lightmapNum < 0 )
+ continue;
+
+ for (y = 0; y < ds->lightmapHeight; y++)
+ {
+ for (x = 0; x < ds->lightmapWidth; x++)
+ {
+ if (ds->surfaceType == MST_PATCH)
+ {
+ if (y == ds->lightmapHeight-1)
+ continue;
+ if (x == ds->lightmapWidth-1)
+ continue;
+ mesh = lsurfaceTest[i]->detailMesh;
+ VectorCopy( mesh->verts[y*mesh->width+x].xyz, w.points[0]);
+ VectorCopy( mesh->verts[(y+1)*mesh->width+x].xyz, w.points[1]);
+ VectorCopy( mesh->verts[(y+1)*mesh->width+x+1].xyz, w.points[2]);
+ VectorCopy( mesh->verts[y*mesh->width+x+1].xyz, w.points[3]);
+ w.numpoints = 4;
+ if (nostitching)
+ area = WindingArea(&w);
+ else
+ area = VL_WindingAreaOutsideSolid(&w, mesh->verts[y*mesh->width+x].normal);
+ }
+ else
+ {
+ VectorMA(ds->lightmapOrigin, (float) x - LIGHTMAP_PIXELSHIFT, ds->lightmapVecs[0], w.points[0]);
+ VectorMA(w.points[0], (float) y - LIGHTMAP_PIXELSHIFT, ds->lightmapVecs[1], w.points[0]);
+ VectorMA(ds->lightmapOrigin, (float) x - LIGHTMAP_PIXELSHIFT, ds->lightmapVecs[0], w.points[3]);
+ VectorMA(w.points[3], (float) y - LIGHTMAP_PIXELSHIFT + 1, ds->lightmapVecs[1], w.points[3]);
+ VectorMA(ds->lightmapOrigin, (float) x - LIGHTMAP_PIXELSHIFT + 1, ds->lightmapVecs[0], w.points[2]);
+ VectorMA(w.points[2], (float) y - LIGHTMAP_PIXELSHIFT + 1, ds->lightmapVecs[1], w.points[2]);
+ VectorMA(ds->lightmapOrigin, (float) x - LIGHTMAP_PIXELSHIFT + 1, ds->lightmapVecs[0], w.points[1]);
+ VectorMA(w.points[1], (float) y - LIGHTMAP_PIXELSHIFT, ds->lightmapVecs[1], w.points[1]);
+ w.numpoints = 4;
+ area = 0;
+ for (j = 0; j < test->numFacets; j++)
+ {
+ memcpy(&tmpw, &w, sizeof(winding_t));
+ area += VL_ChopWindingWithFacet(&tmpw, &test->facets[j]);
+ }
+ }
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ lightmappixelarea[k] = area;
+ }
+ }
+ }
+}
+
+/*
+=============
+VL_FindAdjacentSurface
+=============
+*/
+int VL_FindAdjacentSurface(int surfaceNum, int facetNum, vec3_t p1, vec3_t p2, int *sNum, int *fNum, int *point)
+{
+ int i, j, k;
+ lsurfaceTest_t *test;
+ lFacet_t *facet;
+ dsurface_t *ds;
+ float *fp1, *fp2;
+ vec3_t dir;
+ plane_t *facetplane;
+ // winding_t w;
+
+ facetplane = &lsurfaceTest[surfaceNum]->facets[facetNum].plane;
+ // DebugNet_RemoveAllPolys();
+ // memcpy(w.points, lsurfaceTest[surfaceNum]->facets[facetNum].points,
+ // lsurfaceTest[surfaceNum]->facets[facetNum].numpoints * sizeof(vec3_t));
+ // w.numpoints = lsurfaceTest[surfaceNum]->facets[facetNum].numpoints;
+ // DebugNet_DrawWinding(&w, 2);
+ for ( i = 0 ; i < numDrawSurfaces ; i++ )
+ {
+ if (i == surfaceNum)
+ continue;
+ test = lsurfaceTest[ i ];
+ if (!test)
+ continue;
+ if (test->trisoup)// || test->patch)
+ continue;
+ ds = &drawSurfaces[i];
+ if ( ds->lightmapNum < 0 )
+ continue;
+ //if this surface is not even near the edge
+ VectorSubtract(p1, test->origin, dir);
+ if (fabs(dir[0]) > test->radius ||
+ fabs(dir[1]) > test->radius ||
+ fabs(dir[1]) > test->radius)
+ {
+ VectorSubtract(p2, test->origin, dir);
+ if (fabs(dir[0]) > test->radius ||
+ fabs(dir[1]) > test->radius ||
+ fabs(dir[1]) > test->radius)
+ {
+ continue;
+ }
+ }
+ //
+ for (j = 0; j < test->numFacets; j++)
+ {
+ facet = &test->facets[j];
+ //
+ //if (!Plane_Equal(&facet->plane, facetplane, qfalse))
+ if (DotProduct(facet->plane.normal, facetplane->normal) < 0.9)
+ {
+ if (!test->trisoup && !test->patch)
+ break;
+ continue;
+ }
+ //
+ for (k = 0; k < facet->numpoints; k++)
+ {
+ fp1 = facet->points[k];
+ if (fabs(p2[0] - fp1[0]) < 0.1 &&
+ fabs(p2[1] - fp1[1]) < 0.1 &&
+ fabs(p2[2] - fp1[2]) < 0.1)
+ {
+ fp2 = facet->points[(k+1) % facet->numpoints];
+ if (fabs(p1[0] - fp2[0]) < 0.1 &&
+ fabs(p1[1] - fp2[1]) < 0.1 &&
+ fabs(p1[2] - fp2[2]) < 0.1)
+ {
+ // memcpy(w.points, facet->points, facet->numpoints * sizeof(vec3_t));
+ // w.numpoints = facet->numpoints;
+ // DebugNet_DrawWinding(&w, 1);
+ *sNum = i;
+ *fNum = j;
+ *point = k;
+ return qtrue;
+ }
+ }
+ /*
+ else if (fabs(p1[0] - fp1[0]) < 0.1 &&
+ fabs(p1[1] - fp1[1]) < 0.1 &&
+ fabs(p1[2] - fp1[2]) < 0.1)
+ {
+ fp2 = facet->points[(k+1) % facet->numpoints];
+ if (fabs(p2[0] - fp2[0]) < 0.1 &&
+ fabs(p2[1] - fp2[1]) < 0.1 &&
+ fabs(p2[2] - fp2[2]) < 0.1)
+ {
+ // memcpy(w.points, facet->points, facet->numpoints * sizeof(vec3_t));
+ // w.numpoints = facet->numpoints;
+ // DebugNet_DrawWinding(&w, 1);
+ *sNum = i;
+ *fNum = j;
+ *point = k;
+ return qtrue;
+ }
+ }
+ //*/
+ }
+ }
+ }
+ return qfalse;
+}
+
+/*
+=============
+VL_SmoothenLightmapEdges
+
+this code is used to smoothen lightmaps across surface edges
+=============
+*/
+void VL_SmoothenLightmapEdges(void)
+{
+ int i, j, k, coords1[2][2];
+ float coords2[2][2];
+ int x1, y1, xinc1, yinc1, k1, k2;
+ float x2, y2, xinc2, yinc2, length;
+ int surfaceNum, facetNum, point;
+ lsurfaceTest_t *test;
+ lFacet_t *facet1, *facet2;
+ dsurface_t *ds1, *ds2;
+ float *p[2], s, t, *color1, *color2;
+ vec3_t dir, cross;
+
+ for ( i = 0 ; i < numDrawSurfaces ; i++ )
+ {
+ test = lsurfaceTest[ i ];
+ if (!test)
+ continue;
+ if (test->trisoup)// || test->patch)
+ continue;
+ ds1 = &drawSurfaces[i];
+ if ( ds1->lightmapNum < 0 )
+ continue;
+ for (j = 0; j < test->numFacets; j++)
+ {
+ facet1 = &test->facets[j];
+ //
+ for (k = 0; k < facet1->numpoints; k++)
+ {
+ p[0] = facet1->points[k];
+ p[1] = facet1->points[(k+1)%facet1->numpoints];
+ //
+ coords1[0][0] = facet1->lightmapCoords[k][0] * LIGHTMAP_SIZE;
+ coords1[0][1] = facet1->lightmapCoords[k][1] * LIGHTMAP_SIZE;
+ coords1[1][0] = facet1->lightmapCoords[(k+1)%facet1->numpoints][0] * LIGHTMAP_SIZE;
+ coords1[1][1] = facet1->lightmapCoords[(k+1)%facet1->numpoints][1] * LIGHTMAP_SIZE;
+ if (coords1[0][0] >= LIGHTMAP_SIZE)
+ coords1[0][0] = LIGHTMAP_SIZE-1;
+ if (coords1[0][1] >= LIGHTMAP_SIZE)
+ coords1[0][1] = LIGHTMAP_SIZE-1;
+ if (coords1[1][0] >= LIGHTMAP_SIZE)
+ coords1[1][0] = LIGHTMAP_SIZE-1;
+ if (coords1[1][1] >= LIGHTMAP_SIZE)
+ coords1[1][1] = LIGHTMAP_SIZE-1;
+ // try one row or column further because on flat faces the lightmap can
+ // extend beyond the edge
+ VectorSubtract(p[1], p[0], dir);
+ VectorNormalize(dir, dir);
+ CrossProduct(dir, facet1->plane.normal, cross);
+ //
+ if (coords1[0][0] - coords1[1][0] == 0)
+ {
+ s = DotProduct( cross, facet1->lightmapMatrix[0] );
+ coords1[0][0] += s < 0 ? 1 : -1;
+ coords1[1][0] += s < 0 ? 1 : -1;
+ if (coords1[0][0] < ds1->lightmapX || coords1[0][0] >= ds1->lightmapX + ds1->lightmapWidth)
+ {
+ coords1[0][0] += s < 0 ? -1 : 1;
+ coords1[1][0] += s < 0 ? -1 : 1;
+ }
+ length = fabs(coords1[1][1] - coords1[0][1]);
+ }
+ else if (coords1[0][1] - coords1[1][1] == 0)
+ {
+ t = DotProduct( cross, facet1->lightmapMatrix[1] );
+ coords1[0][1] += t < 0 ? 1 : -1;
+ coords1[1][1] += t < 0 ? 1 : -1;
+ if (coords1[0][1] < ds1->lightmapY || coords1[0][1] >= ds1->lightmapY + ds1->lightmapHeight)
+ {
+ coords1[0][1] += t < 0 ? -1 : 1;
+ coords1[1][1] += t < 0 ? -1 : 1;
+ }
+ length = fabs(coords1[1][0] - coords1[0][0]);
+ }
+ else
+ {
+ //the edge is not parallell to one of the lightmap axis
+ continue;
+ }
+ //
+ x1 = coords1[0][0];
+ y1 = coords1[0][1];
+ xinc1 = coords1[1][0] - coords1[0][0];
+ if (xinc1 < 0) xinc1 = -1;
+ if (xinc1 > 0) xinc1 = 1;
+ yinc1 = coords1[1][1] - coords1[0][1];
+ if (yinc1 < 0) yinc1 = -1;
+ if (yinc1 > 0) yinc1 = 1;
+ // the edge should be parallell to one of the lightmap axis
+ if (xinc1 != 0 && yinc1 != 0)
+ continue;
+ //
+ if (!VL_FindAdjacentSurface(i, j, p[0], p[1], &surfaceNum, &facetNum, &point))
+ continue;
+ //
+ ds2 = &drawSurfaces[surfaceNum];
+ facet2 = &lsurfaceTest[surfaceNum]->facets[facetNum];
+ coords2[0][0] = facet2->lightmapCoords[(point+1)%facet2->numpoints][0] * LIGHTMAP_SIZE;
+ coords2[0][1] = facet2->lightmapCoords[(point+1)%facet2->numpoints][1] * LIGHTMAP_SIZE;
+ coords2[1][0] = facet2->lightmapCoords[point][0] * LIGHTMAP_SIZE;
+ coords2[1][1] = facet2->lightmapCoords[point][1] * LIGHTMAP_SIZE;
+ if (coords2[0][0] >= LIGHTMAP_SIZE)
+ coords2[0][0] = LIGHTMAP_SIZE-1;
+ if (coords2[0][1] >= LIGHTMAP_SIZE)
+ coords2[0][1] = LIGHTMAP_SIZE-1;
+ if (coords2[1][0] >= LIGHTMAP_SIZE)
+ coords2[1][0] = LIGHTMAP_SIZE-1;
+ if (coords2[1][1] >= LIGHTMAP_SIZE)
+ coords2[1][1] = LIGHTMAP_SIZE-1;
+ //
+ x2 = coords2[0][0];
+ y2 = coords2[0][1];
+ xinc2 = coords2[1][0] - coords2[0][0];
+ if (length)
+ xinc2 = xinc2 / length;
+ yinc2 = coords2[1][1] - coords2[0][1];
+ if (length)
+ yinc2 = yinc2 / length;
+ // the edge should be parallell to one of the lightmap axis
+ if ((int) xinc2 != 0 && (int) yinc2 != 0)
+ continue;
+ //
+ while(1)
+ {
+ k1 = ( ds1->lightmapNum * LIGHTMAP_HEIGHT + y1) * LIGHTMAP_WIDTH + x1;
+ k2 = ( ds2->lightmapNum * LIGHTMAP_HEIGHT + ((int) y2)) * LIGHTMAP_WIDTH + ((int) x2);
+ color1 = lightFloats + k1*3;
+ color2 = lightFloats + k2*3;
+ if (lightmappixelarea[k1] < 0.01)
+ {
+ color1[0] = color2[0];
+ color1[1] = color2[1];
+ color1[2] = color2[2];
+ }
+ else
+ {
+ color1[0] = (float) color2[0] * 0.7 + (float) color1[0] * 0.3;
+ color1[1] = (float) color2[1] * 0.7 + (float) color1[1] * 0.3;
+ color1[2] = (float) color2[2] * 0.7 + (float) color1[2] * 0.3;
+ }
+ //
+ if (x1 == coords1[1][0] &&
+ y1 == coords1[1][1])
+ break;
+ x1 += xinc1;
+ y1 += yinc1;
+ x2 += xinc2;
+ y2 += yinc2;
+ if (x2 < ds2->lightmapX)
+ x2 = ds2->lightmapX;
+ if (x2 >= ds2->lightmapX + ds2->lightmapWidth)
+ x2 = ds2->lightmapX + ds2->lightmapWidth-1;
+ if (y2 < ds2->lightmapY)
+ y2 = ds2->lightmapY;
+ if (y2 >= ds2->lightmapY + ds2->lightmapHeight)
+ y2 = ds2->lightmapY + ds2->lightmapHeight-1;
+ }
+ }
+ }
+ }
+}
+
+/*
+=============
+VL_FixLightmapEdges
+=============
+*/
+void VL_FixLightmapEdges(void)
+{
+ int i, j, x, y, k, foundvalue, height, width, index;
+ int pos, top, bottom;
+ dsurface_t *ds;
+ lsurfaceTest_t *test;
+ float color[3];
+ float *ptr;
+ byte filled[(LIGHTMAP_SIZE+1) * (LIGHTMAP_SIZE+1) / 8];
+ float lightmap_edge_epsilon;
+
+ lightmap_edge_epsilon = 0.1 * samplesize;
+ for ( i = 0 ; i < numDrawSurfaces ; i++ )
+ {
+ test = lsurfaceTest[ i ];
+ if (!test)
+ continue;
+ ds = &drawSurfaces[ i ];
+
+ if ( ds->lightmapNum < 0 )
+ continue;
+ if (ds->surfaceType == MST_PATCH)
+ {
+ height = ds->lightmapHeight - 1;
+ width = ds->lightmapWidth - 1;
+ }
+ else
+ {
+ height = ds->lightmapHeight;
+ width = ds->lightmapWidth;
+ }
+ memset(filled, 0, sizeof(filled));
+// printf("\n");
+ for (x = 0; x < width; x++)
+ {
+ for (y = 0; y < height; y++)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ if (lightmappixelarea[k] > lightmap_edge_epsilon)
+ {
+ index = (ds->lightmapY + y) * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ filled[index >> 3] |= 1 << (index & 7);
+// printf("*");
+ }
+// else
+// printf("_");
+ }
+// printf("\n");
+ }
+ for (y = 0; y < height; y++)
+ {
+ pos = -2;
+ for (x = 0; x < width; x++)
+ {
+ index = (ds->lightmapY + y) * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ if (pos == -2)
+ {
+ if (filled[index >> 3] & (1 << (index & 7)))
+ pos = -1;
+ }
+ else if (pos == -1)
+ {
+ if (!(filled[index >> 3] & (1 << (index & 7))))
+ pos = x - 1;
+ }
+ else
+ {
+ if (filled[index >> 3] & (1 << (index & 7)))
+ {
+ bottom = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + pos;
+ top = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ for (j = 0; j < (x - pos + 1) / 2; j++)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + pos + j + 1;
+ index = (ds->lightmapY + y) * LIGHTMAP_WIDTH + ds->lightmapX + pos + j + 1;
+ filled[index >> 3] |= 1 << (index & 7);
+ (lightFloats + k*3)[0] = (lightFloats + top*3)[0];
+ (lightFloats + k*3)[1] = (lightFloats + top*3)[1];
+ (lightFloats + k*3)[2] = (lightFloats + top*3)[2];
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x - j - 1;
+ index = (ds->lightmapY + y) * LIGHTMAP_WIDTH + ds->lightmapX + x - j - 1;
+ filled[index >> 3] |= 1 << (index & 7);
+ (lightFloats + k*3)[0] = (lightFloats + bottom*3)[0];
+ (lightFloats + k*3)[1] = (lightFloats + bottom*3)[1];
+ (lightFloats + k*3)[2] = (lightFloats + bottom*3)[2];
+ }
+ pos = -1;
+ }
+ }
+ }
+ }
+ for (x = 0; x < width; x++)
+ {
+ pos = -2;
+ for (y = 0; y < height; y++)
+ {
+ index = (ds->lightmapY + y) * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ if (pos == -2)
+ {
+ if (filled[index >> 3] & (1 << (index & 7)))
+ pos = -1;
+ }
+ else if (pos == -1)
+ {
+ if (!(filled[index >> 3] & (1 << (index & 7))))
+ pos = y - 1;
+ }
+ else
+ {
+ if (filled[index >> 3] & (1 << (index & 7)))
+ {
+ bottom = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + pos)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ top = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ for (j = 0; j < (y - pos + 1) / 2; j++)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + pos + j + 1)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ index = (ds->lightmapY + pos + j + 1) * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ filled[index >> 3] |= 1 << (index & 7);
+ (lightFloats + k*3)[0] = (lightFloats + top*3)[0];
+ (lightFloats + k*3)[1] = (lightFloats + top*3)[1];
+ (lightFloats + k*3)[2] = (lightFloats + top*3)[2];
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y - j - 1)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ index = (ds->lightmapY + y - j - 1) * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ filled[index >> 3] |= 1 << (index & 7);
+ (lightFloats + k*3)[0] = (lightFloats + bottom*3)[0];
+ (lightFloats + k*3)[1] = (lightFloats + bottom*3)[1];
+ (lightFloats + k*3)[2] = (lightFloats + bottom*3)[2];
+ }
+ pos = -1;
+ }
+ }
+ }
+ }
+ for (y = 0; y < height; y++)
+ {
+ foundvalue = qfalse;
+ for (x = 0; x < width; x++)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ index = (ds->lightmapY + y) * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ if (foundvalue)
+ {
+ if (filled[index >> 3] & (1 << (index & 7)))
+ {
+ ptr = lightFloats + k*3;
+ color[0] = ptr[0];
+ color[1] = ptr[1];
+ color[2] = ptr[2];
+ }
+ else
+ {
+ ptr = lightFloats + k*3;
+ ptr[0] = color[0];
+ ptr[1] = color[1];
+ ptr[2] = color[2];
+ filled[index >> 3] |= 1 << (index & 7);
+ }
+ }
+ else
+ {
+ if (filled[index >> 3] & (1 << (index & 7)))
+ {
+ ptr = lightFloats + k*3;
+ color[0] = ptr[0];
+ color[1] = ptr[1];
+ color[2] = ptr[2];
+ foundvalue = qtrue;
+ }
+ }
+ }
+ foundvalue = qfalse;
+ for (x = width-1; x >= 0; x--)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ index = (ds->lightmapY + y) * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ if (foundvalue)
+ {
+ if (filled[index >> 3] & (1 << (index & 7)))
+ {
+ ptr = lightFloats + k*3;
+ color[0] = ptr[0];
+ color[1] = ptr[1];
+ color[2] = ptr[2];
+ }
+ else
+ {
+ ptr = lightFloats + k*3;
+ ptr[0] = color[0];
+ ptr[1] = color[1];
+ ptr[2] = color[2];
+ filled[index >> 3] |= 1 << (index & 7);
+ }
+ }
+ else
+ {
+ if (filled[index >> 3] & (1 << (index & 7)))
+ {
+ ptr = lightFloats + k*3;
+ color[0] = ptr[0];
+ color[1] = ptr[1];
+ color[2] = ptr[2];
+ foundvalue = qtrue;
+ }
+ }
+ }
+ }
+ for (x = 0; x < width; x++)
+ {
+ foundvalue = qfalse;
+ for (y = 0; y < height; y++)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ index = (ds->lightmapY + y) * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ if (foundvalue)
+ {
+ if (filled[index >> 3] & (1 << (index & 7)))
+ {
+ ptr = lightFloats + k*3;
+ color[0] = ptr[0];
+ color[1] = ptr[1];
+ color[2] = ptr[2];
+ }
+ else
+ {
+ ptr = lightFloats + k*3;
+ ptr[0] = color[0];
+ ptr[1] = color[1];
+ ptr[2] = color[2];
+ filled[index >> 3] |= 1 << (index & 7);
+ }
+ }
+ else
+ {
+ if (filled[index >> 3] & (1 << (index & 7)))
+ {
+ ptr = lightFloats + k*3;
+ color[0] = ptr[0];
+ color[1] = ptr[1];
+ color[2] = ptr[2];
+ foundvalue = qtrue;
+ }
+ }
+ }
+ foundvalue = qfalse;
+ for (y = height-1; y >= 0; y--)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ index = (ds->lightmapY + y) * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ if (foundvalue)
+ {
+ if (filled[index >> 3] & (1 << (index & 7)))
+ {
+ ptr = lightFloats + k*3;
+ color[0] = ptr[0];
+ color[1] = ptr[1];
+ color[2] = ptr[2];
+ }
+ else
+ {
+ ptr = lightFloats + k*3;
+ ptr[0] = color[0];
+ ptr[1] = color[1];
+ ptr[2] = color[2];
+ filled[index >> 3] |= 1 << (index & 7);
+ }
+ }
+ else
+ {
+ if (filled[index >> 3] & (1 << (index & 7)))
+ {
+ ptr = lightFloats + k*3;
+ color[0] = ptr[0];
+ color[1] = ptr[1];
+ color[2] = ptr[2];
+ foundvalue = qtrue;
+ }
+ }
+ }
+ }
+ if (ds->surfaceType == MST_PATCH)
+ {
+ x = ds->lightmapWidth-1;
+ for (y = 0; y < ds->lightmapHeight; y++)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ ptr = lightFloats + k*3;
+ ptr[0] = (lightFloats + (k-1)*3)[0];
+ ptr[1] = (lightFloats + (k-1)*3)[1];
+ ptr[2] = (lightFloats + (k-1)*3)[2];
+ }
+ y = ds->lightmapHeight-1;
+ for (x = 0; x < ds->lightmapWidth; x++)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ ptr = lightFloats + k*3;
+ ptr[0] = (lightFloats + (k-LIGHTMAP_WIDTH)*3)[0];
+ ptr[1] = (lightFloats + (k-LIGHTMAP_WIDTH)*3)[1];
+ ptr[2] = (lightFloats + (k-LIGHTMAP_WIDTH)*3)[2];
+ }
+ }
+ /*
+ //colored debug edges
+ if (ds->surfaceType == MST_PATCH)
+ {
+ x = ds->lightmapWidth-1;
+ for (y = 0; y < ds->lightmapHeight; y++)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ ptr = lightFloats + k*3;
+ ptr[0] = 255;
+ ptr[1] = 0;
+ ptr[2] = 0;
+ }
+ y = ds->lightmapHeight-1;
+ for (x = 0; x < ds->lightmapWidth; x++)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ ptr = lightFloats + k*3;
+ ptr[0] = 0;
+ ptr[1] = 255;
+ ptr[2] = 0;
+ }
+ }
+ //*/
+ }
+ //
+ VL_SmoothenLightmapEdges();
+}
+
+/*
+=============
+VL_ShiftPatchLightmaps
+=============
+*/
+void VL_ShiftPatchLightmaps(void)
+{
+ int i, j, x, y, k;
+ drawVert_t *verts;
+ dsurface_t *ds;
+ lsurfaceTest_t *test;
+ float *ptr;
+
+ for ( i = 0 ; i < numDrawSurfaces ; i++ )
+ {
+ test = lsurfaceTest[ i ];
+ if (!test)
+ continue;
+ ds = &drawSurfaces[ i ];
+
+ if ( ds->lightmapNum < 0 )
+ continue;
+ if (ds->surfaceType != MST_PATCH)
+ continue;
+ for (x = ds->lightmapWidth; x > 0; x--)
+ {
+ for (y = 0; y <= ds->lightmapHeight; y++)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ ptr = lightFloats + k*3;
+ ptr[0] = (lightFloats + (k-1)*3)[0];
+ ptr[1] = (lightFloats + (k-1)*3)[1];
+ ptr[2] = (lightFloats + (k-1)*3)[2];
+ }
+ }
+ for (y = ds->lightmapHeight; y > 0; y--)
+ {
+ for (x = 0; x <= ds->lightmapWidth; x++)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ ptr = lightFloats + k*3;
+ ptr[0] = (lightFloats + (k-LIGHTMAP_WIDTH)*3)[0];
+ ptr[1] = (lightFloats + (k-LIGHTMAP_WIDTH)*3)[1];
+ ptr[2] = (lightFloats + (k-LIGHTMAP_WIDTH)*3)[2];
+ }
+ }
+ verts = &drawVerts[ ds->firstVert ];
+ for ( j = 0 ; j < ds->patchHeight * ds->patchWidth; j++ )
+ {
+ verts[j].lightmap[0] += 0.5 / LIGHTMAP_WIDTH;
+ verts[j].lightmap[1] += 0.5 / LIGHTMAP_HEIGHT;
+ }
+ ds->lightmapHeight++;
+ ds->lightmapWidth++;
+ }
+}
+
+/*
+=============
+VL_StoreLightmap
+=============
+*/
+void VL_StoreLightmap(void)
+{
+ int i, x, y, k;
+ dsurface_t *ds;
+ lsurfaceTest_t *test;
+ float *src;
+ byte *dst;
+
+ _printf("storing lightmaps...\n");
+ //fix lightmap edges before storing them
+ VL_FixLightmapEdges();
+ //
+#ifdef LIGHTMAP_PATCHSHIFT
+ VL_ShiftPatchLightmaps();
+#endif
+ //
+ for ( i = 0 ; i < numDrawSurfaces ; i++ )
+ {
+ test = lsurfaceTest[ i ];
+ if (!test)
+ continue;
+ ds = &drawSurfaces[ i ];
+
+ if ( ds->lightmapNum < 0 )
+ continue;
+
+ for (y = 0; y < ds->lightmapHeight; y++)
+ {
+ for (x = 0; x < ds->lightmapWidth; x++)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ VectorAdd((lightFloats + k*3), lightAmbientColor, (lightFloats + k*3));
+ src = &lightFloats[k*3];
+ dst = lightBytes + k*3;
+ ColorToBytes(src, dst);
+ }
+ }
+ }
+}
+
+/*
+=============
+PointInLeafnum
+=============
+*/
+int PointInLeafnum(vec3_t point)
+{
+ int nodenum;
+ vec_t dist;
+ dnode_t *node;
+ dplane_t *plane;
+
+ nodenum = 0;
+ while (nodenum >= 0)
+ {
+ node = &dnodes[nodenum];
+ plane = &dplanes[node->planeNum];
+ dist = DotProduct (point, plane->normal) - plane->dist;
+ if (dist > 0)
+ nodenum = node->children[0];
+ else
+ nodenum = node->children[1];
+ }
+
+ return -nodenum - 1;
+}
+
+/*
+=============
+VL_PointInLeafnum_r
+=============
+*/
+int VL_PointInLeafnum_r(vec3_t point, int nodenum)
+{
+ int leafnum;
+ vec_t dist;
+ dnode_t *node;
+ dplane_t *plane;
+
+ while (nodenum >= 0)
+ {
+ node = &dnodes[nodenum];
+ plane = &dplanes[node->planeNum];
+ dist = DotProduct (point, plane->normal) - plane->dist;
+ if (dist > 0.1)
+ {
+ nodenum = node->children[0];
+ }
+ else if (dist < -0.1)
+ {
+ nodenum = node->children[1];
+ }
+ else
+ {
+ leafnum = VL_PointInLeafnum_r(point, node->children[0]);
+ if (dleafs[leafnum].cluster != -1)
+ return leafnum;
+ nodenum = node->children[1];
+ }
+ }
+
+ leafnum = -nodenum - 1;
+ return leafnum;
+}
+
+/*
+=============
+VL_PointInLeafnum
+=============
+*/
+int VL_PointInLeafnum(vec3_t point)
+{
+ return VL_PointInLeafnum_r(point, 0);
+}
+
+/*
+=============
+VL_LightLeafnum
+=============
+*/
+int VL_LightLeafnum(vec3_t point)
+{
+ /*
+ int leafnum;
+ dleaf_t *leaf;
+ float x, y, z;
+ vec3_t test;
+
+ leafnum = VL_PointInLeafnum(point);
+ leaf = &dleafs[leafnum];
+ if (leaf->cluster != -1)
+ return leafnum;
+ for (z = 1; z >= -1; z -= 1)
+ {
+ for (x = 1; x >= -1; x -= 1)
+ {
+ for (y = 1; y >= -1; y -= 1)
+ {
+ VectorCopy(point, test);
+ test[0] += x;
+ test[1] += y;
+ test[2] += z;
+ leafnum = VL_PointInLeafnum(test);
+ leaf = &dleafs[leafnum];
+ if (leaf->cluster != -1)
+ {
+ VectorCopy(test, point);
+ return leafnum;
+ }
+ }
+ }
+ }
+ return leafnum;
+ */
+ return VL_PointInLeafnum(point);
+}
+
+//#define LIGHTPOLYS
+
+#ifdef LIGHTPOLYS
+
+winding_t *lightwindings[MAX_MAP_DRAW_SURFS];
+int numlightwindings;
+
+/*
+=============
+VL_DrawLightWindings
+=============
+*/
+void VL_DrawLightWindings(void)
+{
+ int i;
+ for (i = 0; i < numlightwindings; i++)
+ {
+#ifdef DEBUGNET
+ DebugNet_DrawWinding(lightwindings[i], 1);
+#endif
+ }
+}
+
+/*
+=============
+VL_LightSurfaceWithVolume
+=============
+*/
+void VL_LightSurfaceWithVolume(int surfaceNum, int facetNum, vlight_t *light, lightvolume_t *volume)
+{
+ winding_t *w;
+ lsurfaceTest_t *test;
+ lFacet_t *facet;
+ int i;
+
+ test = lsurfaceTest[ surfaceNum ];
+ facet = &test->facets[ facetNum ];
+
+ //
+ w = (winding_t *) malloc(sizeof(winding_t));
+ memcpy(w->points, facet->points, sizeof(vec3_t) * facet->numpoints);
+ w->numpoints = facet->numpoints;
+
+ for (i = 0; i < volume->numplanes; i++)
+ {
+ //if totally on the back
+ if (VL_ChopWinding(w, &volume->planes[i], 0.01) == SIDE_BACK)
+ return;
+ }
+ lightwindings[numlightwindings] = w;
+ numlightwindings++;
+ if (numlightwindings >= MAX_MAP_DRAW_SURFS)
+ Error("MAX_LIGHTWINDINGS");
+}
+
+#else
+
+/*
+=============
+VL_LightSurfaceWithVolume
+=============
+*/
+/*
+int VL_PointInsideLightVolume(vec3_t point, lightvolume_t *volume)
+{
+ int i;
+ float d;
+
+ for (i = 0; i < volume->numplanes; i++)
+ {
+ d = DotProduct(volume->planes[i].normal, point) - volume->planes[i].dist;
+ if (d < 0) return qfalse;
+ }
+ return qtrue;
+}
+
+void VL_LightSurfaceWithVolume( int surfaceNum, int facetNum, vlight_t *light, lightvolume_t *volume )
+{
+ dsurface_t *ds;
+ int i, j, k;
+ int numPositions;
+ vec3_t base, normal, color;
+ int sampleWidth, sampleHeight;
+ vec3_t lightmapOrigin, lightmapVecs[2], dir;
+ unsigned char *ptr;
+ float add, dist, angle;
+ mesh_t * mesh;
+
+ ds = &drawSurfaces[surfaceNum];
+
+ // vertex-lit triangle model
+ if ( ds->surfaceType == MST_TRIANGLE_SOUP ) {
+ return;
+ }
+
+ if ( ds->lightmapNum < 0 ) {
+ return; // doesn't need lighting
+ }
+
+ if ( ds->surfaceType == MST_PATCH ) {
+ mesh = lsurfaceTest[surfaceNum]->detailMesh;
+ } else {
+ VectorCopy( ds->lightmapVecs[2], normal );
+
+ VectorCopy( ds->lightmapOrigin, lightmapOrigin );
+ VectorCopy( ds->lightmapVecs[0], lightmapVecs[0] );
+ VectorCopy( ds->lightmapVecs[1], lightmapVecs[1] );
+ }
+
+ sampleWidth = ds->lightmapWidth;
+ sampleHeight = ds->lightmapHeight;
+
+ //calculate lightmap
+ for ( i = 0 ; i < sampleWidth; i++ ) {
+ for ( j = 0 ; j < sampleHeight; j++ ) {
+
+ if ( ds->patchWidth ) {
+ numPositions = 9;
+ VectorCopy( mesh->verts[j*mesh->width+i].normal, normal );
+ // VectorNormalize( normal, normal );
+ // push off of the curve a bit
+ VectorMA( mesh->verts[j*mesh->width+i].xyz, 1, normal, base );
+
+// MakeNormalVectors( normal, lightmapVecs[0], lightmapVecs[1] );
+ } else {
+ numPositions = 9;
+ for ( k = 0 ; k < 3 ; k++ ) {
+ base[k] = lightmapOrigin[k] + normal[k]
+ + ((float) i) * lightmapVecs[0][k]
+ + ((float) j) * lightmapVecs[1][k];
+ }
+ }
+ VectorAdd( base, surfaceOrigin[ surfaceNum ], base );
+
+ VectorSubtract(base, light->origin, dir);
+ dist = VectorNormalize(dir, dir);
+ if ( dist < 16 ) {
+ dist = 16;
+ }
+ angle = 1;//DotProduct( normal, dir ); //1;
+ if (angle > 1)
+ angle = 1;
+ if ( light->atten_disttype == LDAT_LINEAR ) {
+ add = angle * light->photons * lightLinearScale - dist;
+ if ( add < 0 ) {
+ add = 0;
+ }
+ } else {
+ add = light->photons / ( dist * dist ) * angle;
+ }
+ if (add <= 1.0)
+ continue;
+
+ if (VL_PointInsideLightVolume(base, volume))
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + j)
+ * LIGHTMAP_WIDTH + ds->lightmapX + i;
+ ptr = lightBytes + k*3;
+ color[0] = (float) ptr[0] + add * light->color[0];
+ color[1] = (float) ptr[1] + add * light->color[1];
+ color[2] = (float) ptr[2] + add * light->color[2];
+ ColorToBytes(color, ptr);
+ }
+ }
+ }
+}
+*/
+
+/*
+=============
+VL_GetFilter
+
+FIXME: don't use a lightmap pixel origin but use the four corner points
+ to map part of a translucent surface onto the lightmap pixel
+=============
+*/
+void VL_GetFilter(vlight_t *light, lightvolume_t *volume, vec3_t lmp, vec3_t filter)
+{
+ lFacet_t *facet;
+ lsurfaceTest_t *test;
+ float d, d1, d2, frac, s, t, ns;
+ int i, j, is, it, b;
+ int x, y, u, v, numsamples, radius, color[4], largest;
+ byte *image;
+ vec3_t point, origin, total;
+
+ VectorSet(filter, 1, 1, 1);
+
+ if (noalphashading)
+ return;
+
+ if (volume->numtransFacets <= 0)
+ return;
+
+ if (light->type == LIGHT_SURFACEDIRECTED)
+ {
+ // project the light map pixel origin onto the area light source plane
+ d = DotProduct(lmp, light->normal) - DotProduct(light->normal, light->w.points[0]);
+ VectorMA(lmp, -d, light->normal, origin);
+ }
+ else
+ {
+ VectorCopy(light->origin, origin);
+ }
+ for (i = 0; i < volume->numtransFacets; i++)
+ {
+ test = lsurfaceTest[ volume->transSurfaces[i] ];
+ facet = &test->facets[ volume->transFacets[i] ];
+ // if this surface does not cast an alpha shadow
+ if ( !(test->shader->surfaceFlags & SURF_ALPHASHADOW) )
+ continue;
+ // if there are no texture pixel available
+ if ( !test->shader->pixels ) {
+ continue;
+ }
+ //
+ d1 = DotProduct( origin, facet->plane.normal) - facet->plane.dist;
+ d2 = DotProduct( lmp, facet->plane.normal ) - facet->plane.dist;
+ // this should never happen because the light volume went through the facet
+ if ( ( d1 < 0 ) == ( d2 < 0 ) ) {
+ continue;
+ }
+ // calculate the crossing point
+ frac = d1 / ( d1 - d2 );
+
+ for ( j = 0 ; j < 3 ; j++ ) {
+ point[j] = origin[j] + frac * ( lmp[j] - origin[j] );
+ }
+
+ s = DotProduct( point, facet->textureMatrix[0] ) + facet->textureMatrix[0][3];
+ t = DotProduct( point, facet->textureMatrix[1] ) + facet->textureMatrix[1][3];
+ if (s < 0)
+ s = 0;
+ if (t < 0)
+ t = 0;
+
+ s = s - floor( s );
+ t = t - floor( t );
+
+ is = s * test->shader->width;
+ it = t * test->shader->height;
+
+ //if old style alpha shading
+ if (nocolorshading) {
+ image = test->shader->pixels + 4 * ( it * test->shader->width + is );
+
+ // alpha filter
+ b = image[3];
+
+ // alpha test makes this a binary option
+ b = b < 128 ? 0 : 255;
+
+ filter[0] = filter[0] * (255-b) / 255;
+ filter[1] = filter[1] * (255-b) / 255;
+ filter[2] = filter[2] * (255-b) / 255;
+ }
+ else {
+ VectorClear(total);
+ numsamples = 0;
+ radius = 2;
+ for ( u = -radius; u <= radius; u++ )
+ {
+ x = is + u;
+ if ( x < 0 || x >= test->shader->width)
+ continue;
+ for ( v = -radius; v <= radius; v++ )
+ {
+ y = it + v;
+ if ( y < 0 || y >= test->shader->height)
+ continue;
+
+ image = test->shader->pixels + 4 * ( y * test->shader->width + x );
+ color[0] = image[0];
+ color[1] = image[1];
+ color[2] = image[2];
+ largest = 0;
+ for (j = 0; j < 3; j++)
+ if (image[j] > largest)
+ largest = image[j];
+ if (largest <= 0 || image[3] == 0) {
+ color[0] = 255;
+ color[1] = 255;
+ color[2] = 255;
+ largest = 255;
+ }
+ total[0] += ((float) color[0]/largest) * (255-image[3]) / 255.0;
+ total[1] += ((float) color[1]/largest) * (255-image[3]) / 255.0;
+ total[2] += ((float) color[2]/largest) * (255-image[3]) / 255.0;
+ numsamples++;
+ }
+ }
+ ns = numsamples;
+ //
+ filter[0] *= total[0] / ns;
+ filter[1] *= total[1] / ns;
+ filter[2] *= total[2] / ns;
+ }
+ }
+}
+
+/*
+=============
+VL_LightSurfaceWithVolume
+=============
+*/
+void VL_LightSurfaceWithVolume( int surfaceNum, int facetNum, vlight_t *light, lightvolume_t *volume )
+{
+ int i;
+ dsurface_t *ds;
+ lFacet_t *facet;
+ lsurfaceTest_t *test;
+ winding_t w;
+ vec3_t base, dir, delta, normal, filter, origin;
+ int min_x[LIGHTMAP_SIZE+2], max_x[LIGHTMAP_SIZE+2];
+ int min_y, max_y, k, x, y, n;
+ float *color, distscale;
+ float d, add, angle, dist, area, insidearea, coords[MAX_POINTS_ON_WINDING+1][2];
+ mesh_t *mesh;
+ byte polygonedges[(LIGHTMAP_SIZE+1) * (LIGHTMAP_SIZE+1) / 8];
+
+
+ ds = &drawSurfaces[surfaceNum];
+
+ // vertex-lit triangle model
+ if ( ds->surfaceType == MST_TRIANGLE_SOUP ) {
+ return;
+ }
+
+ if ( ds->lightmapNum < 0 ) {
+ return; // doesn't need lighting
+ }
+
+ test = lsurfaceTest[ surfaceNum ];
+ facet = &test->facets[ facetNum ];
+
+ if (defaulttracelight && !test->always_vlight)
+ return;
+ if (test->always_tracelight)
+ return;
+
+ memcpy(w.points, facet->points, sizeof(vec3_t) * facet->numpoints);
+ w.numpoints = facet->numpoints;
+
+ for (i = 0; i < volume->numplanes; i++)
+ {
+ //if totally on the back
+ if (VL_ChopWinding(&w, &volume->planes[i], 0.01) == SIDE_BACK)
+ return;
+ }
+
+ // only one thread at a time may write to the lightmap of this surface
+ MutexLock(test->mutex);
+
+ test->numvolumes++;
+
+ if (ds->surfaceType == MST_PATCH)
+ {
+ // FIXME: reduce size and don't mark all as edge
+ min_y = ds->lightmapY + facet->y;
+ max_y = ds->lightmapY + facet->y + facet->height - 1;
+ for (y = min_y; y <= max_y; y++)
+ {
+ min_x[y] = ds->lightmapX + facet->x;
+ max_x[y] = ds->lightmapX + facet->x + facet->width - 1;
+ for (x = min_x[y]; x <= max_x[y]; x++)
+ {
+ n = y * LIGHTMAP_SIZE + x;
+ polygonedges[n >> 3] |= 1 << (n & 7);
+ }
+ }
+ }
+ else
+ {
+ for (i = 0; i < w.numpoints; i++)
+ {
+ float s, t;
+
+ if (i >= MAX_POINTS_ON_WINDING)
+ _printf("coords overflow\n");
+ if (ds->surfaceType != MST_PATCH)
+ {
+ VectorSubtract(w.points[i], facet->mins, delta);
+ s = DotProduct( delta, facet->lightmapMatrix[0] ) + ds->lightmapX + 0.5;
+ t = DotProduct( delta, facet->lightmapMatrix[1] ) + ds->lightmapY + 0.5;
+ if (s >= LIGHTMAP_SIZE)
+ s = LIGHTMAP_SIZE - 0.5;
+ if (s < 0)
+ s = 0;
+ if (t >= LIGHTMAP_SIZE)
+ t = LIGHTMAP_SIZE - 0.5;
+ if (t < 0)
+ t = 0;
+ coords[i][0] = s;
+ coords[i][1] = t;
+ }
+ else
+ {
+ s = DotProduct( w.points[i], facet->lightmapMatrix[0] ) + facet->lightmapMatrix[0][3];
+ t = DotProduct( w.points[i], facet->lightmapMatrix[1] ) + facet->lightmapMatrix[1][3];
+
+ s = s - floor( s );
+ t = t - floor( t );
+
+ coords[i][0] = ds->lightmapX + s * LIGHTMAP_SIZE;// + 0.5;
+ coords[i][1] = ds->lightmapY + t * LIGHTMAP_SIZE;// + 0.5;
+
+ if (coords[i][0] >= LIGHTMAP_SIZE)
+ coords[i][0] -= LIGHTMAP_SIZE;
+ if (coords[i][1] >= LIGHTMAP_SIZE)
+ coords[i][1] -= LIGHTMAP_SIZE;
+ if (coords[i][0] < ds->lightmapX)
+ coords[i][0] = ds->lightmapX;
+ if (coords[i][1] < ds->lightmapY)
+ coords[i][1] = ds->lightmapY;
+ }
+ x = coords[i][0];
+ y = coords[i][1];
+ if (x < ds->lightmapX || x >= LIGHTMAP_SIZE)
+ _printf("VL_LightSurfaceWithVolume: x outside lightmap\n");
+ if (y < ds->lightmapY || y >= LIGHTMAP_SIZE)
+ _printf("VL_LightSurfaceWithVolume: y outside lightmap\n");
+ }
+ coords[i][0] = coords[0][0];
+ coords[i][1] = coords[0][1];
+
+ //
+ min_y = LIGHTMAP_SIZE;
+ max_y = 0;
+ for (i = 0; i < LIGHTMAP_SIZE; i++)
+ {
+ min_x[i] = LIGHTMAP_SIZE;
+ max_x[i] = 0;
+ }
+ memset(polygonedges, 0, sizeof(polygonedges));
+ // scan convert the polygon onto the lightmap
+ // for each edge it marks *every* lightmap pixel the edge goes through
+ // so no brasenham and no scan conversion used for texture mapping but
+ // more something like ray casting
+ // this is necesary because we need all lightmap pixels totally or partly
+ // inside the light volume. these lightmap pixels are only lit for the part
+ // that they are inside the light volume.
+ for (i = 0; i < w.numpoints; i++)
+ {
+ float xf, yf, dx, dy, xstep, ystep, xfrac, yfrac;
+ int xinc, yinc;
+
+ xf = coords[i][0];
+ yf = coords[i][1];
+ dx = coords[i+1][0] - xf;
+ dy = coords[i+1][1] - yf;
+ //
+ x = (int) xf;
+ y = (int) yf;
+ //
+ if (y < min_y)
+ min_y = y;
+ if (y > max_y)
+ max_y = y;
+ //
+ if (fabs(dx) > fabs(dy))
+ {
+ if (dx > 0)
+ {
+ // y fraction at integer x below fractional x
+ yfrac = yf + (floor(xf) - xf) * dy / dx;
+ xinc = 1;
+ }
+ else if (dx < 0)
+ {
+ // y fraction at integer x above fractional x
+ yfrac = yf + (floor(xf) + 1 - xf) * dy / dx;
+ xinc = -1;
+ }
+ else
+ {
+ yfrac = yf;
+ xinc = 0;
+ }
+ // step in y direction per 1 unit in x direction
+ if (dx)
+ ystep = dy / fabs(dx);
+ else
+ ystep = 0;
+ while(1)
+ {
+ if (x < ds->lightmapX || x >= LIGHTMAP_SIZE)
+ _printf("VL_LightSurfaceWithVolume: x outside lightmap\n");
+ if (y < ds->lightmapY || y >= LIGHTMAP_SIZE)
+ _printf("VL_LightSurfaceWithVolume: y outside lightmap\n");
+ //
+ n = y * LIGHTMAP_SIZE + x;
+ polygonedges[n >> 3] |= 1 << (n & 7);
+ if (x < min_x[y])
+ min_x[y] = x;
+ if (x > max_x[y])
+ max_x[y] = x;
+ if (x == (int) coords[i+1][0])
+ break;
+ yfrac += ystep;
+ if (dy > 0)
+ {
+ if (yfrac > (float) y + 1)
+ {
+ y += 1;
+ //
+ n = y * LIGHTMAP_SIZE + x;
+ polygonedges[n >> 3] |= 1 << (n & 7);
+ if (x < min_x[y])
+ min_x[y] = x;
+ if (x > max_x[y])
+ max_x[y] = x;
+ }
+ }
+ else
+ {
+ if (yfrac < (float) y)
+ {
+ y -= 1;
+ //
+ n = y * LIGHTMAP_SIZE + x;
+ polygonedges[n >> 3] |= 1 << (n & 7);
+ if (x < min_x[y])
+ min_x[y] = x;
+ if (x > max_x[y])
+ max_x[y] = x;
+ }
+ }
+ x += xinc;
+ }
+ }
+ else
+ {
+ if (dy > 0)
+ {
+ //x fraction at integer y below fractional y
+ xfrac = xf + (floor(yf) - yf) * dx / dy;
+ yinc = 1;
+ }
+ else if (dy < 0)
+ {
+ //x fraction at integer y above fractional y
+ xfrac = xf + (floor(yf) + 1 - yf) * dx / dy;
+ yinc = -1;
+ }
+ else
+ {
+ xfrac = xf;
+ yinc = 0;
+ }
+ // step in x direction per 1 unit in y direction
+ if (dy)
+ xstep = dx / fabs(dy);
+ else
+ xstep = 0;
+ while(1)
+ {
+ if (x < ds->lightmapX || x >= LIGHTMAP_SIZE)
+ _printf("VL_LightSurfaceWithVolume: x outside lightmap\n");
+ if (y < ds->lightmapY || y >= LIGHTMAP_SIZE)
+ _printf("VL_LightSurfaceWithVolume: y outside lightmap\n");
+ //
+ n = y * LIGHTMAP_SIZE + x;
+ polygonedges[n >> 3] |= 1 << (n & 7);
+ if (x < min_x[y])
+ min_x[y] = x;
+ if (x > max_x[y])
+ max_x[y] = x;
+ if (y == (int) coords[i+1][1])
+ break;
+ xfrac += xstep;
+ if (dx > 0)
+ {
+ if (xfrac > (float) x + 1)
+ {
+ x += 1;
+ //
+ n = y * LIGHTMAP_SIZE + x;
+ polygonedges[n >> 3] |= 1 << (n & 7);
+ if (x < min_x[y])
+ min_x[y] = x;
+ if (x > max_x[y])
+ max_x[y] = x;
+ }
+ }
+ else
+ {
+ if (xfrac < (float) x)
+ {
+ x -= 1;
+ //
+ n = y * LIGHTMAP_SIZE + x;
+ polygonedges[n >> 3] |= 1 << (n & 7);
+ if (x < min_x[y])
+ min_x[y] = x;
+ if (x > max_x[y])
+ max_x[y] = x;
+ }
+ }
+ y += yinc;
+ }
+ }
+ }
+ }
+ // map light onto the lightmap
+ for (y = min_y; y <= max_y; y++)
+ {
+ for (x = min_x[y]; x <= max_x[y]; x++)
+ {
+ if (ds->surfaceType == MST_PATCH)
+ {
+ mesh = test->detailMesh;
+ VectorCopy( mesh->verts[(y-ds->lightmapY)*mesh->width+x-ds->lightmapX].xyz, base);
+ VectorCopy( mesh->verts[(y-ds->lightmapY)*mesh->width+x-ds->lightmapX].normal, normal);
+ //VectorCopy(facet->plane.normal, normal);
+ }
+ else
+ {
+ VectorMA(ds->lightmapOrigin, (float) x - ds->lightmapX, ds->lightmapVecs[0], base);
+ VectorMA(base, (float) y - ds->lightmapY, ds->lightmapVecs[1], base);
+ VectorCopy(facet->plane.normal, normal);
+ }
+ if (light->type == LIGHT_POINTSPOT)
+ {
+ float distByNormal;
+ vec3_t pointAtDist;
+ float radiusAtDist;
+ float sampleRadius;
+ vec3_t distToSample;
+ float coneScale;
+
+ VectorSubtract( light->origin, base, dir );
+
+ distByNormal = -DotProduct( dir, light->normal );
+ if ( distByNormal < 0 ) {
+ continue;
+ }
+ VectorMA( light->origin, distByNormal, light->normal, pointAtDist );
+ radiusAtDist = light->radiusByDist * distByNormal;
+
+ VectorSubtract( base, pointAtDist, distToSample );
+ sampleRadius = VectorLength( distToSample );
+
+ if ( sampleRadius >= radiusAtDist ) {
+ continue; // outside the cone
+ }
+ if ( sampleRadius <= radiusAtDist - 32 ) {
+ coneScale = 1.0; // fully inside
+ } else {
+ coneScale = ( radiusAtDist - sampleRadius ) / 32.0;
+ }
+
+ dist = VectorNormalize( dir, dir );
+ // clamp the distance to prevent super hot spots
+ if ( dist < 16 ) {
+ dist = 16;
+ }
+ angle = DotProduct( normal, dir );
+ if (angle > 1)
+ angle = 1;
+ if (angle > 0) {
+ if ( light->atten_angletype == LAAT_QUADRATIC ) {
+ angle = 1 - angle;
+ angle *= angle;
+ angle = 1 - angle;
+ }
+ else if ( light->atten_angletype == LAAT_DOUBLEQUADRATIC ) {
+ angle = 1 - angle;
+ angle *= angle * angle;
+ angle = 1 - angle;
+ }
+ }
+ if (light->atten_anglescale > 0) {
+ angle /= light->atten_anglescale;
+ if (angle > 1)
+ angle = 1;
+ }
+ if (light->atten_distscale > 0) {
+ distscale = light->atten_distscale;
+ }
+ else {
+ distscale = 1;
+ }
+ //
+ if ( light->atten_disttype == LDAT_NOSCALE ) {
+ add = angle * coneScale;
+ }
+ else if ( light->atten_disttype == LDAT_LINEAR ) {
+ add = angle * light->photons * lightLinearScale * coneScale - dist * distscale;
+ if ( add < 0 ) {
+ add = 0;
+ }
+ }
+ else {
+ add = light->photons / ( dist * dist * distscale) * angle * coneScale;
+ }
+ if (add <= 1.0)
+ continue;
+ }
+ else if (light->type == LIGHT_POINTFAKESURFACE)
+ {
+ // calculate the contribution
+ add = PointToPolygonFormFactor( base, normal, &light->w );
+ if ( add <= 0 ) {
+ if ( light->twosided ) {
+ add = -add;
+ } else {
+ continue;
+ }
+ }
+ }
+ else if (light->type == LIGHT_SURFACEDIRECTED)
+ {
+ //VectorCopy(light->normal, dir);
+ //VectorInverse(dir);
+ // project the light map pixel origin onto the area light source plane
+ d = DotProduct(base, light->normal) - DotProduct(light->normal, light->w.points[0]);
+ VectorMA(base, -d, light->normal, origin);
+ VectorSubtract(origin, base, dir);
+ dist = VectorNormalize(dir, dir);
+ if ( dist < 16 ) {
+ dist = 16;
+ }
+ //
+ angle = DotProduct( normal, dir );
+ if (angle > 1)
+ angle = 1;
+ if (angle > 0) {
+ if ( light->atten_angletype == LAAT_QUADRATIC ) {
+ angle = 1 - angle;
+ angle *= angle;
+ angle = 1 - angle;
+ }
+ else if ( light->atten_angletype == LAAT_DOUBLEQUADRATIC ) {
+ angle = 1 - angle;
+ angle *= angle * angle;
+ angle = 1 - angle;
+ }
+ }
+ if (light->atten_anglescale > 0) {
+ angle /= light->atten_anglescale;
+ if (angle > 1)
+ angle = 1;
+ }
+ if (light->atten_distscale > 0) {
+ distscale = light->atten_distscale;
+ }
+ else {
+ distscale = 1;
+ }
+ if ( light->atten_disttype == LDAT_NOSCALE ) {
+ add = angle;
+ }
+ else if ( light->atten_disttype == LDAT_LINEAR ) {
+ add = angle * light->photons * lightLinearScale - dist * distscale;
+ if ( add < 0 ) {
+ add = 0;
+ }
+ } else { //default quadratic
+ add = light->photons / ( dist * dist * distscale) * angle;
+ }
+ if (add <= 0)
+ continue;
+ }
+ else //normal radial point light
+ {
+ VectorSubtract(light->origin, base, dir);
+ dist = VectorNormalize(dir, dir);
+ if ( dist < 16 ) {
+ dist = 16;
+ }
+ angle = DotProduct( normal, dir );
+ if (angle > 1)
+ angle = 1;
+ if (angle > 0) {
+ if ( light->atten_angletype == LAAT_QUADRATIC ) {
+ angle = 1 - angle;
+ angle *= angle;
+ angle = 1 - angle;
+ }
+ else if ( light->atten_angletype == LAAT_DOUBLEQUADRATIC ) {
+ angle = 1 - angle;
+ angle *= angle * angle;
+ angle = 1 - angle;
+ }
+ }
+ if (light->atten_anglescale > 0) {
+ angle /= light->atten_anglescale;
+ if (angle > 1)
+ angle = 1;
+ }
+ if (light->atten_distscale > 0) {
+ distscale = light->atten_distscale;
+ }
+ else {
+ distscale = 1;
+ }
+ if ( light->atten_disttype == LDAT_NOSCALE ) {
+ add = angle;
+ }
+ else if ( light->atten_disttype == LDAT_LINEAR ) {
+ add = angle * light->photons * lightLinearScale - dist * distscale;
+ if ( add < 0 ) {
+ add = 0;
+ }
+ } else {
+ add = light->photons / ( dist * dist * distscale) * angle;
+ }
+ if (add <= 1.0)
+ continue;
+ }
+ //
+ k = (ds->lightmapNum * LIGHTMAP_HEIGHT + y) * LIGHTMAP_WIDTH + x;
+ //if on one of the edges
+ n = y * LIGHTMAP_SIZE + x;
+ if ((polygonedges[n >> 3] & (1 << (n & 7)) ))
+ {
+ // multiply 'add' by the relative area being lit of the total visible lightmap pixel area
+ //
+ // first create a winding for the lightmap pixel
+ if (ds->surfaceType == MST_PATCH)
+ {
+ mesh = test->detailMesh;
+ if (y-ds->lightmapY >= mesh->height-1)
+ _printf("y outside mesh\n");
+ if (x-ds->lightmapX >= mesh->width-1)
+ _printf("x outside mesh\n");
+ VectorCopy( mesh->verts[(y-ds->lightmapY)*mesh->width+x-ds->lightmapX].xyz, w.points[0]);
+ VectorCopy( mesh->verts[(y+1-ds->lightmapY)*mesh->width+x-ds->lightmapX].xyz, w.points[1]);
+ VectorCopy( mesh->verts[(y+1-ds->lightmapY)*mesh->width+x+1-ds->lightmapX].xyz, w.points[2]);
+ VectorCopy( mesh->verts[(y-ds->lightmapY)*mesh->width+x+1-ds->lightmapX].xyz, w.points[3]);
+ w.numpoints = 4;
+ }
+ else
+ {
+ VectorMA(ds->lightmapOrigin, (float) x - LIGHTMAP_PIXELSHIFT - ds->lightmapX, ds->lightmapVecs[0], w.points[0]);
+ VectorMA(w.points[0], (float) y - LIGHTMAP_PIXELSHIFT - ds->lightmapY, ds->lightmapVecs[1], w.points[0]);
+ VectorMA(ds->lightmapOrigin, (float) x - LIGHTMAP_PIXELSHIFT - ds->lightmapX, ds->lightmapVecs[0], w.points[1]);
+ VectorMA(w.points[1], (float) y - LIGHTMAP_PIXELSHIFT + 1 - ds->lightmapY, ds->lightmapVecs[1], w.points[1]);
+ VectorMA(ds->lightmapOrigin, (float) x - LIGHTMAP_PIXELSHIFT + 1 - ds->lightmapX, ds->lightmapVecs[0], w.points[2]);
+ VectorMA(w.points[2], (float) y - LIGHTMAP_PIXELSHIFT + 1 - ds->lightmapY, ds->lightmapVecs[1], w.points[2]);
+ VectorMA(ds->lightmapOrigin, (float) x - LIGHTMAP_PIXELSHIFT + 1 - ds->lightmapX, ds->lightmapVecs[0], w.points[3]);
+ VectorMA(w.points[3], (float) y - LIGHTMAP_PIXELSHIFT - ds->lightmapY, ds->lightmapVecs[1], w.points[3]);
+ w.numpoints = 4;
+ }
+ //
+ // take the visible area of the lightmap pixel into account
+ //
+ //area = WindingArea(&w);
+ area = lightmappixelarea[k];
+ if (area <= 0)
+ continue;
+ // chop the lightmap pixel winding with the light volume
+ for (i = 0; i < volume->numplanes; i++)
+ {
+ //if totally on the back
+ if (VL_ChopWinding(&w, &volume->planes[i], 0) == SIDE_BACK)
+ break;
+ }
+ // if the lightmap pixel is partly inside the light volume
+ if (i >= volume->numplanes)
+ {
+ insidearea = WindingArea(&w);
+ if (insidearea <= 0)
+ i = 0;
+ add = add * insidearea / area;
+ }
+ else
+ {
+ //DebugNet_DrawWinding(&w, 2);
+ continue; // this shouldn't happen
+ }
+ }
+ // get the light filter from all the translucent surfaces the light volume went through
+ VL_GetFilter(light, volume, base, filter);
+ //
+ color = &lightFloats[k*3];
+ color[0] += add * light->color[0] * filter[0];
+ color[1] += add * light->color[1] * filter[1];
+ color[2] += add * light->color[2] * filter[2];
+ }
+ }
+
+ MutexUnlock(test->mutex);
+}
+
+#endif
+
+/*
+=============
+VL_SplitLightVolume
+=============
+*/
+int VL_SplitLightVolume(lightvolume_t *volume, lightvolume_t *back, plane_t *split, float epsilon)
+{
+ lightvolume_t f, b;
+ vec_t dists[128];
+ int sides[128];
+ int counts[3];
+ vec_t dot;
+ int i, j;
+ vec_t *p1, *p2;
+ vec3_t mid;
+
+ counts[0] = counts[1] = counts[2] = 0;
+
+ // determine sides for each point
+ for (i = 0; i < volume->numplanes; i++)
+ {
+ dot = DotProduct (volume->points[i], split->normal);
+ dot -= split->dist;
+ dists[i] = dot;
+ if (dot > epsilon)
+ sides[i] = SIDE_FRONT;
+ else if (dot < -epsilon)
+ sides[i] = SIDE_BACK;
+ else
+ {
+ sides[i] = SIDE_ON;
+ }
+ counts[sides[i]]++;
+ }
+
+ if (!counts[1])
+ return 0; // completely on front side
+
+ if (!counts[0])
+ return 1; // completely on back side
+
+ sides[i] = sides[0];
+ dists[i] = dists[0];
+
+ f.numplanes = 0;
+ b.numplanes = 0;
+
+ for (i = 0; i < volume->numplanes; i++)
+ {
+ p1 = volume->points[i];
+
+ if (f.numplanes >= MAX_POINTS_ON_FIXED_WINDING)
+ {
+ _printf("WARNING: VL_SplitLightVolume -> MAX_POINTS_ON_FIXED_WINDING overflowed\n");
+ return 0; // can't chop -- fall back to original
+ }
+ if (b.numplanes >= MAX_POINTS_ON_FIXED_WINDING)
+ {
+ _printf("WARNING: VL_SplitLightVolume -> MAX_POINTS_ON_FIXED_WINDING overflowed\n");
+ return 0; // can't chop -- fall back to original
+ }
+
+ if (sides[i] == SIDE_ON)
+ {
+ VectorCopy(p1, f.points[f.numplanes]);
+ VectorCopy(p1, b.points[b.numplanes]);
+ if (sides[i+1] == SIDE_BACK)
+ {
+ f.planes[f.numplanes] = *split;
+ b.planes[b.numplanes] = volume->planes[i];
+ }
+ else if (sides[i+1] == SIDE_FRONT)
+ {
+ f.planes[f.numplanes] = volume->planes[i];
+ b.planes[b.numplanes] = *split;
+ VectorInverse(b.planes[b.numplanes].normal);
+ b.planes[b.numplanes].dist = -b.planes[b.numplanes].dist;
+ }
+ else //this shouldn't happen
+ {
+ f.planes[f.numplanes] = *split;
+ b.planes[b.numplanes] = *split;
+ VectorInverse(b.planes[b.numplanes].normal);
+ b.planes[b.numplanes].dist = -b.planes[b.numplanes].dist;
+ }
+ f.numplanes++;
+ b.numplanes++;
+ continue;
+ }
+
+ if (sides[i] == SIDE_FRONT)
+ {
+ VectorCopy (p1, f.points[f.numplanes]);
+ f.planes[f.numplanes] = volume->planes[i];
+ f.numplanes++;
+ }
+ if (sides[i] == SIDE_BACK)
+ {
+ VectorCopy (p1, b.points[b.numplanes]);
+ b.planes[b.numplanes] = volume->planes[i];
+ b.numplanes++;
+ }
+
+ if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i])
+ continue;
+
+ if (f.numplanes >= MAX_POINTS_ON_FIXED_WINDING)
+ {
+ _printf("WARNING: VL_SplitLightVolume -> MAX_POINTS_ON_FIXED_WINDING overflowed\n");
+ return 0; // can't chop -- fall back to original
+ }
+ if (b.numplanes >= MAX_POINTS_ON_FIXED_WINDING)
+ {
+ _printf("WARNING: VL_SplitLightVolume -> MAX_POINTS_ON_FIXED_WINDING overflowed\n");
+ return 0; // can't chop -- fall back to original
+ }
+
+ // generate a split point
+ p2 = volume->points[(i+1)%volume->numplanes];
+
+ dot = dists[i] / (dists[i]-dists[i+1]);
+ for (j=0 ; j<3 ; j++)
+ { // avoid round off error when possible
+ if (split->normal[j] == 1)
+ mid[j] = split->dist;
+ else if (split->normal[j] == -1)
+ mid[j] = -split->dist;
+ else
+ mid[j] = p1[j] + dot*(p2[j]-p1[j]);
+ }
+
+ VectorCopy (mid, f.points[f.numplanes]);
+ VectorCopy(mid, b.points[b.numplanes]);
+ if (sides[i+1] == SIDE_BACK)
+ {
+ f.planes[f.numplanes] = *split;
+ b.planes[b.numplanes] = volume->planes[i];
+ }
+ else
+ {
+ f.planes[f.numplanes] = volume->planes[i];
+ b.planes[b.numplanes] = *split;
+ VectorInverse(b.planes[b.numplanes].normal);
+ b.planes[b.numplanes].dist = -b.planes[b.numplanes].dist;
+ }
+ f.numplanes++;
+ b.numplanes++;
+ }
+ memcpy(volume->points, f.points, sizeof(vec3_t) * f.numplanes);
+ memcpy(volume->planes, f.planes, sizeof(plane_t) * f.numplanes);
+ volume->numplanes = f.numplanes;
+ memcpy(back->points, b.points, sizeof(vec3_t) * b.numplanes);
+ memcpy(back->planes, b.planes, sizeof(plane_t) * b.numplanes);
+ back->numplanes = b.numplanes;
+
+ return 2;
+}
+
+/*
+=============
+VL_PlaneForEdgeToWinding
+=============
+*/
+void VL_PlaneForEdgeToWinding(vec3_t p1, vec3_t p2, winding_t *w, int windingonfront, plane_t *plane)
+{
+ int i, j;
+ float length, d;
+ vec3_t v1, v2;
+
+ VectorSubtract(p2, p1, v1);
+ for (i = 0; i < w->numpoints; i++)
+ {
+ VectorSubtract (w->points[i], p1, v2);
+
+ plane->normal[0] = v1[1]*v2[2] - v1[2]*v2[1];
+ plane->normal[1] = v1[2]*v2[0] - v1[0]*v2[2];
+ plane->normal[2] = v1[0]*v2[1] - v1[1]*v2[0];
+
+ // if points don't make a valid plane, skip it
+ length = plane->normal[0] * plane->normal[0]
+ + plane->normal[1] * plane->normal[1]
+ + plane->normal[2] * plane->normal[2];
+
+ if (length < ON_EPSILON)
+ continue;
+
+ length = 1/sqrt(length);
+
+ plane->normal[0] *= length;
+ plane->normal[1] *= length;
+ plane->normal[2] *= length;
+
+ plane->dist = DotProduct (w->points[i], plane->normal);
+ //
+ for (j = 0; j < w->numpoints; j++)
+ {
+ if (j == i)
+ continue;
+ d = DotProduct(w->points[j], plane->normal) - plane->dist;
+ if (windingonfront)
+ {
+ if (d < -ON_EPSILON)
+ break;
+ }
+ else
+ {
+ if (d > ON_EPSILON)
+ break;
+ }
+ }
+ if (j >= w->numpoints)
+ return;
+ }
+}
+
+/*
+=============
+VL_R_CastLightAtSurface
+=============
+*/
+void VL_R_FloodLight(vlight_t *light, lightvolume_t *volume, int cluster, int firstportal);
+
+void VL_R_CastLightAtSurface(vlight_t *light, lightvolume_t *volume)
+{
+ lsurfaceTest_t *test;
+ int i, n;
+
+ // light the surface with this volume
+ VL_LightSurfaceWithVolume(volume->surfaceNum, volume->facetNum, light, volume);
+ //
+ test = lsurfaceTest[ volume->surfaceNum ];
+ // if this is not a translucent surface
+ if ( !(test->shader->surfaceFlags & SURF_ALPHASHADOW) && !(test->shader->contents & CONTENTS_TRANSLUCENT))
+ return;
+ //
+ if (volume->numtransFacets >= MAX_TRANSLUCENTFACETS)
+ Error("a light valume went through more than %d translucent facets", MAX_TRANSLUCENTFACETS);
+ //add this translucent surface to the list
+ volume->transSurfaces[volume->numtransFacets] = volume->surfaceNum;
+ volume->transFacets[volume->numtransFacets] = volume->facetNum;
+ volume->numtransFacets++;
+ //clear the tested facets except the translucent ones
+ memset(volume->facetTested, 0, sizeof(volume->facetTested));
+ for (i = 0; i < volume->numtransFacets; i++)
+ {
+ test = lsurfaceTest[ volume->transSurfaces[i] ];
+ n = test->facets[volume->transFacets[i]].num;
+ volume->facetTested[n >> 3] |= 1 << (n & 7);
+ }
+ memset(volume->clusterTested, 0, sizeof(volume->clusterTested));
+ volume->endplane = volume->farplane;
+ volume->surfaceNum = -1;
+ volume->facetNum = 0;
+ VL_R_FloodLight(light, volume, volume->cluster, 0);
+ if (volume->surfaceNum >= 0)
+ {
+ VL_R_CastLightAtSurface(light, volume);
+ }
+}
+
+/*
+=============
+VL_R_SplitLightVolume
+=============
+*/
+int numvolumes = 0;
+
+int VL_R_SplitLightVolume(vlight_t *light, lightvolume_t *volume, plane_t *split, int cluster, int firstportal)
+{
+ lightvolume_t back;
+ int res;
+
+ //
+ res = VL_SplitLightVolume(volume, &back, split, 0.1);
+ // if the volume was split
+ if (res == 2)
+ {
+ memcpy(back.clusterTested, volume->clusterTested, sizeof(back.clusterTested));
+ memcpy(back.facetTested, volume->facetTested, sizeof(back.facetTested));
+ back.num = numvolumes++;
+ back.endplane = volume->endplane;
+ back.surfaceNum = volume->surfaceNum;
+ back.facetNum = volume->facetNum;
+ back.type = volume->type;
+ back.cluster = volume->cluster;
+ back.farplane = volume->farplane;
+ if (volume->numtransFacets > 0)
+ {
+ memcpy(back.transFacets, volume->transFacets, sizeof(back.transFacets));
+ memcpy(back.transSurfaces, volume->transSurfaces, sizeof(back.transSurfaces));
+ }
+ back.numtransFacets = volume->numtransFacets;
+ //
+ // flood the volume at the back of the split plane
+ VL_R_FloodLight(light, &back, cluster, firstportal);
+ // if the back volume hit a surface
+ if (back.surfaceNum >= 0)
+ {
+ VL_R_CastLightAtSurface(light, &back);
+ }
+ }
+ return res;
+}
+
+/*
+=============
+VL_R_FloodLight
+=============
+*/
+void VL_R_FloodLight(vlight_t *light, lightvolume_t *volume, int cluster, int firstportal)
+{
+ int i, j, k, res, surfaceNum, backfaceculled, testculled;
+ float d;
+ winding_t winding, tmpwinding;
+ lleaf_t *leaf;
+ lportal_t *p;
+ lsurfaceTest_t *test;
+ lFacet_t *facet;
+ vec3_t dir1, dir2;
+ plane_t plane;
+
+ // DebugNet_RemoveAllPolys();
+ // VL_DrawLightVolume(light, volume);
+
+ // if the first portal is not zero then we've checked all occluders in this leaf already
+ if (firstportal == 0)
+ {
+ // check all potential occluders in this leaf
+ for (i = 0; i < leafs[cluster].numSurfaces; i++)
+ {
+ surfaceNum = clustersurfaces[leafs[cluster].firstSurface + i];
+ //
+ test = lsurfaceTest[ surfaceNum ];
+ if ( !test )
+ continue;
+ //
+ testculled = qfalse;
+ // use surface as an occluder
+ for (j = 0; j < test->numFacets; j++)
+ {
+ // use each facet as an occluder
+ facet = &test->facets[j];
+ //
+ // memcpy(winding.points, facet->points, sizeof(vec3_t) * facet->numpoints);
+ // winding.numpoints = facet->numpoints;
+ // DebugNet_DrawWinding(&winding, 5);
+ //
+ // if the facet was tested already
+ if ( volume->facetTested[facet->num >> 3] & (1 << (facet->num & 7)) )
+ continue;
+ volume->facetTested[facet->num >> 3] |= 1 << (facet->num & 7);
+ // backface culling for planar surfaces
+ backfaceculled = qfalse;
+ if (!test->patch && !test->trisoup)
+ {
+ if (volume->type == VOLUME_NORMAL)
+ {
+ // facet backface culling
+ d = DotProduct(light->origin, facet->plane.normal) - facet->plane.dist;
+ if (d < 0)
+ {
+ // NOTE: this doesn't work too great because of sometimes very bad tesselation
+ // of surfaces that are supposed to be flat
+ // FIXME: to work around this problem we should make sure that all facets
+ // created from planar surfaces use the lightmapVecs normal vector
+ /*
+ if ( !test->shader->twoSided )
+ {
+ // skip all other facets of this surface as well because they are in the same plane
+ for (k = 0; k < test->numFacets; k++)
+ {
+ facet = &test->facets[k];
+ volume->facetTested[facet->num >> 3] |= 1 << (facet->num & 7);
+ }
+ }*/
+ backfaceculled = qtrue;
+ }
+ }
+ else
+ {
+ // FIXME: if all light source winding points are at the back of the facet
+ // plane then backfaceculled = qtrue
+ }
+ }
+ else // backface culling per facet for patches and triangle soups
+ {
+ if (volume->type == VOLUME_NORMAL)
+ {
+ // facet backface culling
+ d = DotProduct(light->origin, facet->plane.normal) - facet->plane.dist;
+ if (d < 0)
+ backfaceculled = qtrue;
+ }
+ else
+ {
+ // FIXME: if all light source winding points are at the back of the facet
+ // plane then backfaceculled = qtrue
+ }
+ }
+ /* chopping does this already
+ // check if this facet is totally or partly in front of the volume end plane
+ for (k = 0; k < facet->numpoints; k++)
+ {
+ d = DotProduct(volume->endplane.normal, facet->points[k]) - volume->endplane.dist;
+ if (d > ON_EPSILON)
+ break;
+ }
+ // if this facet is outside the light volume
+ if (k >= facet->numpoints)
+ continue;
+ */
+ //
+ if (backfaceculled)
+ {
+ // if the facet is not two sided
+ if ( !nobackfaceculling && !test->shader->twoSided )
+ continue;
+ // flip the winding
+ for (k = 0; k < facet->numpoints; k++)
+ VectorCopy(facet->points[k], winding.points[facet->numpoints - k - 1]);
+ winding.numpoints = facet->numpoints;
+ }
+ else
+ {
+ memcpy(winding.points, facet->points, sizeof(vec3_t) * facet->numpoints);
+ winding.numpoints = facet->numpoints;
+ }
+ //
+ if (!testculled)
+ {
+ testculled = qtrue;
+ // fast check if the surface sphere is totally behind the volume end plane
+ d = DotProduct(volume->endplane.normal, test->origin) - volume->endplane.dist;
+ if (d < -test->radius)
+ {
+ for (k = 0; k < test->numFacets; k++)
+ {
+ facet = &test->facets[k];
+ volume->facetTested[facet->num >> 3] |= 1 << (facet->num & 7);
+ }
+ break;
+ }
+ for (k = 0; k < volume->numplanes; k++)
+ {
+ d = DotProduct(volume->planes[k].normal, test->origin) - volume->planes[k].dist;
+ if (d < - test->radius)
+ {
+ for (k = 0; k < test->numFacets; k++)
+ {
+ facet = &test->facets[k];
+ volume->facetTested[facet->num >> 3] |= 1 << (facet->num & 7);
+ }
+ break;
+ }
+ }
+ if (k < volume->numplanes)
+ break;
+ }
+ //NOTE: we have to chop the facet winding with the volume end plane because
+ // the faces in Q3 are not stitched together nicely
+ res = VL_ChopWinding(&winding, &volume->endplane, 0.01);
+ // if the facet is on or at the back of the volume end plane
+ if (res == SIDE_BACK || res == SIDE_ON)
+ continue;
+ // check if the facet winding is totally or partly inside the light volume
+ memcpy(&tmpwinding, &winding, sizeof(winding_t));
+ for (k = 0; k < volume->numplanes; k++)
+ {
+ res = VL_ChopWinding(&tmpwinding, &volume->planes[k], 0.01);
+ if (res == SIDE_BACK || res == SIDE_ON)
+ break;
+ }
+ // if no part of the light volume is occluded by this facet
+ if (k < volume->numplanes)
+ continue;
+ //
+ for (k = 0; k < winding.numpoints; k++)
+ {
+ if (volume->type == VOLUME_DIRECTED)
+ {
+ VectorSubtract(winding.points[(k+1) % winding.numpoints], winding.points[k], dir1);
+ CrossProduct(light->normal, dir1, plane.normal);
+ VectorNormalize(plane.normal, plane.normal);
+ plane.dist = DotProduct(plane.normal, winding.points[k]);
+ }
+ else
+ {
+ VectorSubtract(winding.points[(k+1) % winding.numpoints], winding.points[k], dir1);
+ VectorSubtract(light->origin, winding.points[k], dir2);
+ CrossProduct(dir1, dir2, plane.normal);
+ VectorNormalize(plane.normal, plane.normal);
+ plane.dist = DotProduct(plane.normal, winding.points[k]);
+ }
+ res = VL_R_SplitLightVolume(light, volume, &plane, cluster, 0);
+ if (res == 1)
+ break; //the facet wasn't really inside the volume
+ }
+ if (k >= winding.numpoints)
+ {
+ volume->endplane = facet->plane;
+ if (backfaceculled)
+ {
+ VectorInverse(volume->endplane.normal);
+ volume->endplane.dist = -volume->endplane.dist;
+ }
+ volume->surfaceNum = surfaceNum;
+ volume->facetNum = j;
+ }
+ }
+ }
+ }
+ // we've tested all occluders in this cluster
+ volume->clusterTested[cluster >> 3] |= 1 << (cluster & 7);
+ // flood light through the portals of the current leaf
+ leaf = &leafs[cluster];
+ for (i = firstportal; i < leaf->numportals; i++)
+ {
+ p = leaf->portals[i];
+ //
+ // memcpy(&winding, p->winding, sizeof(winding_t));
+ // DebugNet_DrawWinding(&winding, 5);
+ // if already flooded into the cluster this portal leads to
+ if ( volume->clusterTested[p->leaf >> 3] & (1 << (p->leaf & 7)) )
+ continue;
+ //
+ if (volume->type == VOLUME_NORMAL)
+ {
+ // portal backface culling
+ d = DotProduct(light->origin, p->plane.normal) - p->plane.dist;
+ if (d > 0) // portal plane normal points into neighbour cluster
+ continue;
+ }
+ else
+ {
+ // FIXME: if all light source winding points are at the back of this portal
+ // plane then there's no need to flood through
+ }
+ // check if this portal is totally or partly in front of the volume end plane
+ // fast check with portal sphere
+ d = DotProduct(volume->endplane.normal, p->origin) - volume->endplane.dist;
+ if (d < -p->radius)
+ continue;
+ for (j = 0; j < p->winding->numpoints; j++)
+ {
+ d = DotProduct(volume->endplane.normal, p->winding->points[j]) - volume->endplane.dist;
+ if (d > -0.01)
+ break;
+ }
+ // if this portal is totally behind the light volume end plane
+ if (j >= p->winding->numpoints)
+ continue;
+ //distance from point light to portal
+ d = DotProduct(p->plane.normal, light->origin) - p->plane.dist;
+ // only check if a point light is Not *on* the portal
+ if (volume->type != VOLUME_NORMAL || fabs(d) > 0.1)
+ {
+ // check if the portal is partly or totally inside the light volume
+ memcpy(&winding, p->winding, sizeof(winding_t));
+ for (j = 0; j < volume->numplanes; j++)
+ {
+ res = VL_ChopWinding(&winding, &volume->planes[j], 0.01);
+ if (res == SIDE_BACK || res == SIDE_ON)
+ break;
+ }
+ // if the light volume does not go through this portal at all
+ if (j < volume->numplanes)
+ continue;
+ }
+ // chop the light volume with the portal
+ for (k = 0; k < p->winding->numpoints; k++)
+ {
+ if (volume->type == VOLUME_DIRECTED)
+ {
+ VectorSubtract(p->winding->points[(k+1) % p->winding->numpoints], p->winding->points[k], dir1);
+ CrossProduct(light->normal, dir1, plane.normal);
+ VectorNormalize(plane.normal, plane.normal);
+ plane.dist = DotProduct(plane.normal, p->winding->points[k]);
+ }
+ else
+ {
+ VectorSubtract(p->winding->points[(k+1) % p->winding->numpoints], p->winding->points[k], dir1);
+ VectorSubtract(light->origin, p->winding->points[k], dir2);
+ CrossProduct(dir1, dir2, plane.normal);
+ VectorNormalize(plane.normal, plane.normal);
+ plane.dist = DotProduct(plane.normal, p->winding->points[k]);
+ }
+ res = VL_R_SplitLightVolume(light, volume, &plane, cluster, i+1);
+ if (res == 1)
+ break; //volume didn't really go through the portal
+ }
+ // if the light volume went through the portal
+ if (k >= p->winding->numpoints)
+ {
+ // flood through the portal
+ VL_R_FloodLight(light, volume, p->leaf, 0);
+ }
+ }
+}
+
+/*
+=============
+VL_R_FloodAreaSpotLight
+=============
+*/
+void VL_FloodAreaSpotLight(vlight_t *light, winding_t *w, int leafnum)
+{
+}
+
+/*
+=============
+VL_R_SubdivideAreaSpotLight
+=============
+*/
+void VL_R_SubdivideAreaSpotLight(vlight_t *light, int nodenum, winding_t *w)
+{
+ int leafnum, res;
+ dnode_t *node;
+ dplane_t *plane;
+ winding_t back;
+ plane_t split;
+
+ while(nodenum >= 0)
+ {
+ node = &dnodes[nodenum];
+ plane = &dplanes[node->planeNum];
+
+ VectorCopy(plane->normal, split.normal);
+ split.dist = plane->dist;
+ res = VL_SplitWinding (w, &back, &split, 0.1);
+
+ if (res == SIDE_FRONT)
+ {
+ nodenum = node->children[0];
+ }
+ else if (res == SIDE_BACK)
+ {
+ nodenum = node->children[1];
+ }
+ else if (res == SIDE_ON)
+ {
+ memcpy(&back, w, sizeof(winding_t));
+ VL_R_SubdivideAreaSpotLight(light, node->children[1], &back);
+ nodenum = node->children[0];
+ }
+ else
+ {
+ VL_R_SubdivideAreaSpotLight(light, node->children[1], &back);
+ nodenum = node->children[0];
+ }
+ }
+ leafnum = -nodenum - 1;
+ if (dleafs[leafnum].cluster != -1)
+ {
+ VL_FloodAreaSpotLight(light, w, leafnum);
+ }
+}
+
+/*
+=============
+VL_R_FloodRadialAreaLight
+=============
+*/
+void VL_FloodRadialAreaLight(vlight_t *light, winding_t *w, int leafnum)
+{
+}
+
+/*
+=============
+VL_R_SubdivideRadialAreaLight
+=============
+*/
+void VL_R_SubdivideRadialAreaLight(vlight_t *light, int nodenum, winding_t *w)
+{
+ int leafnum, res;
+ dnode_t *node;
+ dplane_t *plane;
+ winding_t back;
+ plane_t split;
+
+ while(nodenum >= 0)
+ {
+ node = &dnodes[nodenum];
+ plane = &dplanes[node->planeNum];
+
+ VectorCopy(plane->normal, split.normal);
+ split.dist = plane->dist;
+ res = VL_SplitWinding (w, &back, &split, 0.1);
+
+ if (res == SIDE_FRONT)
+ {
+ nodenum = node->children[0];
+ }
+ else if (res == SIDE_BACK)
+ {
+ nodenum = node->children[1];
+ }
+ else if (res == SIDE_ON)
+ {
+ memcpy(&back, w, sizeof(winding_t));
+ VL_R_SubdivideRadialAreaLight(light, node->children[1], &back);
+ nodenum = node->children[0];
+ }
+ else
+ {
+ VL_R_SubdivideRadialAreaLight(light, node->children[1], &back);
+ nodenum = node->children[0];
+ }
+ }
+ leafnum = -nodenum - 1;
+ if (dleafs[leafnum].cluster != -1)
+ {
+ VL_FloodRadialAreaLight(light, w, leafnum);
+ }
+}
+
+/*
+=============
+VL_R_FloodDirectedLight
+=============
+*/
+void VL_FloodDirectedLight(vlight_t *light, winding_t *w, int leafnum)
+{
+ int i;
+ float dist;
+ lightvolume_t volume;
+ vec3_t dir;
+
+ if (light->atten_disttype == LDAT_NOSCALE)
+ {
+ // light travels without decrease in intensity over distance
+ dist = MAX_WORLD_COORD;
+ }
+ else
+ {
+ if ( light->atten_disttype == LDAT_LINEAR )
+ dist = light->photons * lightLinearScale;
+ else
+ dist = sqrt(light->photons);
+ }
+
+ memset(&volume, 0, sizeof(lightvolume_t));
+ for (i = 0; i < w->numpoints; i++)
+ {
+ VectorMA(w->points[i], dist, light->normal, volume.points[i]);
+ VectorSubtract(w->points[(i+1)%w->numpoints], w->points[i], dir);
+ CrossProduct(light->normal, dir, volume.planes[i].normal);
+ VectorNormalize(volume.planes[i].normal, volume.planes[i].normal);
+ volume.planes[i].dist = DotProduct(volume.planes[i].normal, w->points[i]);
+ }
+ volume.numplanes = w->numpoints;
+ VectorCopy(light->normal, volume.endplane.normal);
+ VectorInverse(volume.endplane.normal);
+ volume.endplane.dist = DotProduct(volume.endplane.normal, volume.points[0]);
+ volume.farplane = volume.endplane;
+ volume.surfaceNum = -1;
+ volume.type = VOLUME_DIRECTED;
+ volume.cluster = dleafs[leafnum].cluster;
+ VL_R_FloodLight(light, &volume, volume.cluster, 0);
+ if (volume.surfaceNum >= 0)
+ {
+ VL_R_CastLightAtSurface(light, &volume);
+ }
+}
+
+/*
+=============
+VL_R_SubdivideDirectedAreaLight
+=============
+*/
+void VL_R_SubdivideDirectedAreaLight(vlight_t *light, int nodenum, winding_t *w)
+{
+ int leafnum, res;
+ dnode_t *node;
+ dplane_t *plane;
+ winding_t back;
+ plane_t split;
+
+ while(nodenum >= 0)
+ {
+ node = &dnodes[nodenum];
+ plane = &dplanes[node->planeNum];
+
+ VectorCopy(plane->normal, split.normal);
+ split.dist = plane->dist;
+ res = VL_SplitWinding (w, &back, &split, 0.1);
+
+ if (res == SIDE_FRONT)
+ {
+ nodenum = node->children[0];
+ }
+ else if (res == SIDE_BACK)
+ {
+ nodenum = node->children[1];
+ }
+ else if (res == SIDE_ON)
+ {
+ memcpy(&back, w, sizeof(winding_t));
+ VL_R_SubdivideDirectedAreaLight(light, node->children[1], &back);
+ nodenum = node->children[0];
+ }
+ else
+ {
+ VL_R_SubdivideDirectedAreaLight(light, node->children[1], &back);
+ nodenum = node->children[0];
+ }
+ }
+ leafnum = -nodenum - 1;
+ if (dleafs[leafnum].cluster != -1)
+ {
+ VL_FloodDirectedLight(light, w, leafnum);
+ }
+}
+
+/*
+=============
+VL_FloodLight
+=============
+*/
+void VL_FloodLight(vlight_t *light)
+{
+ lightvolume_t volume;
+ dleaf_t *leaf;
+ int leafnum, i, j, k, dir[2][4] = {{1, 1, -1, -1}, {1, -1, -1, 1}};
+ float a, step, dist, radius, windingdist;
+ vec3_t vec, r, p, temp;
+ winding_t winding;
+
+ switch(light->type)
+ {
+ case LIGHT_POINTRADIAL:
+ {
+ // source is a point
+ // light radiates in all directions
+ // creates sharp shadows
+ //
+ // create 6 volumes shining in the axis directions
+ // what about: 4 tetrahedrons instead?
+ //
+ if ( light->atten_disttype == LDAT_LINEAR )
+ dist = light->photons * lightLinearScale;
+ else
+ dist = sqrt(light->photons);
+ //always put the winding at a large distance to avoid epsilon issues
+ windingdist = MAX_WORLD_COORD;
+ if (dist > windingdist)
+ windingdist = dist;
+ //
+ leafnum = VL_LightLeafnum(light->origin);
+ leaf = &dleafs[leafnum];
+ if (leaf->cluster == -1)
+ {
+ light->insolid = qtrue;
+ break;
+ }
+ // for each axis
+ for (i = 0; i < 3; i++)
+ {
+ // for both directions on the axis
+ for (j = -1; j <= 1; j += 2)
+ {
+ memset(&volume, 0, sizeof(lightvolume_t));
+ volume.numplanes = 0;
+ for (k = 0; k < 4; k ++)
+ {
+ volume.points[volume.numplanes][i] = light->origin[i] + j * windingdist;
+ volume.points[volume.numplanes][(i+1)%3] = light->origin[(i+1)%3] + dir[0][k] * windingdist;
+ volume.points[volume.numplanes][(i+2)%3] = light->origin[(i+2)%3] + dir[1][k] * windingdist;
+ volume.numplanes++;
+ }
+ if (j >= 0)
+ {
+ VectorCopy(volume.points[0], temp);
+ VectorCopy(volume.points[2], volume.points[0]);
+ VectorCopy(temp, volume.points[2]);
+ }
+ for (k = 0; k < volume.numplanes; k++)
+ {
+ VL_PlaneFromPoints(&volume.planes[k], light->origin, volume.points[(k+1)%volume.numplanes], volume.points[k]);
+ }
+ VectorCopy(light->origin, temp);
+ temp[i] += (float) j * dist;
+ VectorClear(volume.endplane.normal);
+ volume.endplane.normal[i] = -j;
+ volume.endplane.dist = DotProduct(volume.endplane.normal, temp); //DotProduct(volume.endplane.normal, volume.points[0]);
+ volume.farplane = volume.endplane;
+ volume.cluster = leaf->cluster;
+ volume.surfaceNum = -1;
+ volume.type = VOLUME_NORMAL;
+ //
+ memset(volume.facetTested, 0, sizeof(volume.facetTested));
+ memset(volume.clusterTested, 0, sizeof(volume.clusterTested));
+ VL_R_FloodLight(light, &volume, leaf->cluster, 0);
+ if (volume.surfaceNum >= 0)
+ {
+ VL_R_CastLightAtSurface(light, &volume);
+ }
+ }
+ }
+ break;
+ }
+ case LIGHT_POINTSPOT:
+ {
+ // source is a point
+ // light is targetted
+ // creates sharp shadows
+ //
+ // what about using brushes to shape spot lights? that'd be pretty cool
+ //
+ if ( light->atten_disttype == LDAT_LINEAR )
+ dist = light->photons * lightLinearScale;
+ else
+ dist = sqrt(light->photons);
+ dist *= 2;
+ //
+ windingdist = 4096;
+ if (dist > windingdist)
+ windingdist = dist;
+ //take 8 times the cone radius because the spotlight also lights outside the cone
+ radius = 8 * windingdist * light->radiusByDist;
+ //
+ memset(&volume, 0, sizeof(lightvolume_t));
+ leafnum = VL_LightLeafnum(light->origin);
+ leaf = &dleafs[leafnum];
+ if (leaf->cluster == -1)
+ {
+ light->insolid = qtrue;
+ break;
+ }
+ //
+ VectorClear(vec);
+ for (i = 0; i < 3; i++)
+ {
+ if (light->normal[i] > -0.9 && light->normal[i] < 0.9)
+ {
+ vec[i] = 1;
+ break;
+ }
+ }
+ CrossProduct(light->normal, vec, r);
+ VectorScale(r, radius, p);
+ volume.numplanes = 0;
+ step = 45;
+ for (a = step / 2; a < 360 + step / 2; a += step)
+ {
+ RotatePointAroundVector(volume.points[volume.numplanes], light->normal, p, a);
+ VectorAdd(light->origin, volume.points[volume.numplanes], volume.points[volume.numplanes]);
+ VectorMA(volume.points[volume.numplanes], windingdist, light->normal, volume.points[volume.numplanes]);
+ volume.numplanes++;
+ }
+ for (i = 0; i < volume.numplanes; i++)
+ {
+ VL_PlaneFromPoints(&volume.planes[i], light->origin, volume.points[(i+1)%volume.numplanes], volume.points[i]);
+ }
+ VectorMA(light->origin, dist, light->normal, temp);
+ VectorCopy(light->normal, volume.endplane.normal);
+ VectorInverse(volume.endplane.normal);
+ volume.endplane.dist = DotProduct(volume.endplane.normal, temp);//DotProduct(volume.endplane.normal, volume.points[0]);
+ volume.farplane = volume.endplane;
+ volume.cluster = leaf->cluster;
+ volume.surfaceNum = -1;
+ volume.type = VOLUME_NORMAL;
+ //
+ memset(volume.facetTested, 0, sizeof(volume.facetTested));
+ memset(volume.clusterTested, 0, sizeof(volume.clusterTested));
+ VL_R_FloodLight(light, &volume, leaf->cluster, 0);
+ if (volume.surfaceNum >= 0)
+ {
+ VL_R_CastLightAtSurface(light, &volume);
+ }
+ break;
+ }
+ case LIGHT_POINTFAKESURFACE:
+ {
+ float value;
+ int n, axis;
+ vec3_t v, vecs[2];
+
+ if ( light->atten_disttype == LDAT_LINEAR )
+ dist = light->photons * lightLinearScale;
+ else
+ dist = sqrt(light->photons);
+ //always put the winding at a large distance to avoid epsilon issues
+ windingdist = 4096;
+ if (dist > windingdist)
+ windingdist = dist;
+ //
+ VectorMA(light->origin, 0.1, light->normal, light->origin);
+ //
+ leafnum = VL_LightLeafnum(light->origin);
+ leaf = &dleafs[leafnum];
+ if (leaf->cluster == -1)
+ {
+ light->insolid = qtrue;
+ break;
+ }
+ value = 0;
+ for (i = 0; i < 3; i++)
+ {
+ if (fabs(light->normal[i]) > value)
+ {
+ value = fabs(light->normal[i]);
+ axis = i;
+ }
+ }
+ for (i = 0; i < 2; i++)
+ {
+ VectorClear(v);
+ v[(axis + 1 + i) % 3] = 1;
+ CrossProduct(light->normal, v, vecs[i]);
+ }
+ //cast 4 volumes at the front of the surface
+ for (i = -1; i <= 1; i += 2)
+ {
+ for (j = -1; j <= 1; j += 2)
+ {
+ for (n = 0; n < 2; n++)
+ {
+ memset(&volume, 0, sizeof(lightvolume_t));
+ volume.numplanes = 3;
+ VectorMA(light->origin, i * windingdist, vecs[0], volume.points[(i == j) == n]);
+ VectorMA(light->origin, j * windingdist, vecs[1], volume.points[(i != j) == n]);
+ VectorMA(light->origin, windingdist, light->normal, volume.points[2]);
+ for (k = 0; k < volume.numplanes; k++)
+ {
+ VL_PlaneFromPoints(&volume.planes[k], light->origin, volume.points[(k+1)%volume.numplanes], volume.points[k]);
+ }
+ VL_PlaneFromPoints(&volume.endplane, volume.points[0], volume.points[1], volume.points[2]);
+ VectorMA(light->origin, dist, light->normal, temp);
+ volume.endplane.dist = DotProduct(volume.endplane.normal, temp);
+ if (DotProduct(light->origin, volume.endplane.normal) - volume.endplane.dist > 0)
+ break;
+ }
+ volume.farplane = volume.endplane;
+ volume.cluster = leaf->cluster;
+ volume.surfaceNum = -1;
+ volume.type = VOLUME_NORMAL;
+ //
+ memset(volume.facetTested, 0, sizeof(volume.facetTested));
+ memset(volume.clusterTested, 0, sizeof(volume.clusterTested));
+
+ VL_R_FloodLight(light, &volume, leaf->cluster, 0);
+ if (volume.surfaceNum >= 0)
+ {
+ VL_R_CastLightAtSurface(light, &volume);
+ }
+ }
+ }
+ break;
+ }
+ case LIGHT_SURFACEDIRECTED:
+ {
+ // source is an area defined by a winding
+ // the light is unidirectional
+ // creates sharp shadows
+ // for instance sun light or laser light
+ //
+ memcpy(&winding, &light->w, sizeof(winding_t));
+ VL_R_SubdivideDirectedAreaLight(light, 0, &winding);
+ break;
+ }
+ case LIGHT_SURFACERADIAL:
+ {
+ // source is an area defined by a winding
+ // the light radiates in all directions at the front of the winding plane
+ //
+ memcpy(&winding, &light->w, sizeof(winding_t));
+ VL_R_SubdivideRadialAreaLight(light, 0, &winding);
+ break;
+ }
+ case LIGHT_SURFACESPOT:
+ {
+ // source is an area defined by a winding
+ // light is targetted but not unidirectional
+ //
+ memcpy(&winding, &light->w, sizeof(winding_t));
+ VL_R_SubdivideAreaSpotLight(light, 0, &winding);
+ break;
+ }
+ }
+}
+
+/*
+=============
+VL_FloodLightThread
+=============
+*/
+void VL_FloodLightThread(int num)
+{
+ VL_FloodLight(vlights[num]);
+}
+
+/*
+=============
+VL_TestLightLeafs
+=============
+*/
+void VL_TestLightLeafs(void)
+{
+ int leafnum, i;
+ vlight_t *light;
+ dleaf_t *leaf;
+
+ for (i = 0; i < numvlights; i++)
+ {
+ light = vlights[i];
+ if (light->type != LIGHT_POINTRADIAL &&
+ light->type != LIGHT_POINTSPOT)
+ continue;
+ leafnum = VL_LightLeafnum(light->origin);
+ leaf = &dleafs[leafnum];
+ if (leaf->cluster == -1)
+ if (light->type == LIGHT_POINTRADIAL)
+ qprintf("light in solid at %1.1f %1.1f %1.1f\n", light->origin[0], light->origin[1], light->origin[2]);
+ else if (light->type == LIGHT_POINTSPOT)
+ qprintf("spot light in solid at %1.1f %1.1f %1.1f\n", light->origin[0], light->origin[1], light->origin[2]);
+ }
+}
+
+
+/*
+=============
+VL_DoForcedTraceLight
+=============
+*/
+// from light.c
+void TraceLtm( int num );
+
+void VL_DoForcedTraceLight(int num)
+{
+ dsurface_t *ds;
+ shaderInfo_t *si;
+
+ ds = &drawSurfaces[num];
+
+ if ( ds->surfaceType == MST_TRIANGLE_SOUP )
+ return;
+
+ if ( ds->lightmapNum < 0 )
+ return;
+
+ // always light entity surfaces with the old light algorithm
+ if ( !entitySurface[num] )
+ {
+ si = ShaderInfoForShader( dshaders[ ds->shaderNum].shader );
+
+ if (defaulttracelight)
+ {
+ if (si->forceVLight)
+ return;
+ }
+ else
+ {
+ if (!si->forceTraceLight)
+ return;
+ }
+ }
+
+ TraceLtm(num);
+}
+
+/*
+=============
+VL_DoForcedTraceLightSurfaces
+=============
+*/
+void VL_DoForcedTraceLightSurfaces(void)
+{
+ _printf( "forced trace light\n" );
+ RunThreadsOnIndividual( numDrawSurfaces, qtrue, VL_DoForcedTraceLight );
+}
+
+float *oldLightFloats;
+
+/*
+=============
+VL_SurfaceRadiosity
+=============
+*/
+void VL_SurfaceRadiosity( int num ) {
+ dsurface_t *ds;
+ mesh_t *mesh;
+ shaderInfo_t *si;
+ lsurfaceTest_t *test;
+ int x, y, k;
+ vec3_t base, normal;
+ float *color, area;
+ vlight_t vlight;
+
+ ds = &drawSurfaces[num];
+
+ if ( ds->lightmapNum < 0 ) {
+ return; // doesn't have a lightmap
+ }
+
+ // vertex-lit triangle model
+ if ( ds->surfaceType == MST_TRIANGLE_SOUP ) {
+ return;
+ }
+
+ si = ShaderInfoForShader( dshaders[ ds->shaderNum].shader );
+ test = lsurfaceTest[ num ];
+
+ if (!test) {
+ return;
+ }
+
+ for (x = 0; x < ds->lightmapWidth; x++) {
+ for (y = 0; y < ds->lightmapHeight; y++) {
+ //
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ area = lightmappixelarea[k];
+ if (area <= 0)
+ continue;
+ //
+ if (ds->surfaceType == MST_PATCH)
+ {
+ mesh = test->detailMesh;
+ VectorCopy( mesh->verts[y*mesh->width+x].xyz, base);
+ VectorCopy( mesh->verts[y*mesh->width+x].normal, normal);
+ }
+ else
+ {
+ VectorMA(ds->lightmapOrigin, (float) x, ds->lightmapVecs[0], base);
+ VectorMA(base, (float) y, ds->lightmapVecs[1], base);
+ VectorCopy(test->facets[0].plane.normal, normal);
+ }
+ // create ligth from base
+ memset(&vlight, 0, sizeof(vlight_t));
+ color = &oldLightFloats[k*3];
+ // a few units away from the surface
+ VectorMA(base, 5, normal, vlight.origin);
+ ColorNormalize(color, vlight.color);
+ // ok this is crap
+ vlight.photons = VectorLength(color) * 0.05 * lightPointScale / (area * radiosity_scale);
+ // what about using a front facing light only ?
+ vlight.type = LIGHT_POINTRADIAL;
+ // flood the light from this lightmap pixel
+ VL_FloodLight(&vlight);
+ // only one thread at a time may write to the lightmap of this surface
+ MutexLock(test->mutex);
+ // don't light the lightmap pixel itself
+ lightFloats[k*3] = oldLightFloats[k*3];
+ lightFloats[k*3+1] = oldLightFloats[k*3+1];
+ lightFloats[k*3+2] = oldLightFloats[k*3+2];
+ //
+ MutexUnlock(test->mutex);
+ }
+ }
+}
+
+/*
+=============
+VL_Radiosity
+
+this aint working real well but it's fun to play with.
+=============
+*/
+void VL_Radiosity(void) {
+
+ oldLightFloats = lightFloats;
+ lightFloats = (float *) malloc(numLightBytes * sizeof(float));
+ memcpy(lightFloats, oldLightFloats, numLightBytes * sizeof(float));
+ _printf("%7i surfaces\n", numDrawSurfaces);
+ RunThreadsOnIndividual( numDrawSurfaces, qtrue, VL_SurfaceRadiosity );
+ free(oldLightFloats);
+}
+
+/*
+=============
+VL_LightWorld
+=============
+*/
+void VL_LightWorld(void)
+{
+ int i, numcastedvolumes, numvlightsinsolid;
+ float f;
+
+ // find the optional world ambient
+ GetVectorForKey( &entities[0], "_color", lightAmbientColor );
+ f = FloatForKey( &entities[0], "ambient" );
+ VectorScale( lightAmbientColor, f, lightAmbientColor );
+ /*
+ _printf("\r%6d lights out of %d", 0, numvlights);
+ for (i = 0; i < numvlights; i++)
+ {
+ _printf("\r%6d", i);
+ VL_FloodLight(vlights[i]);
+ }
+ _printf("\r%6d lights out of %d\n", i, numvlights);
+ */
+ _printf("%7i lights\n", numvlights);
+ RunThreadsOnIndividual( numvlights, qtrue, VL_FloodLightThread );
+
+ numcastedvolumes = 0;
+ for ( i = 0 ; i < numDrawSurfaces ; i++ ) {
+ if (lsurfaceTest[i])
+ numcastedvolumes += lsurfaceTest[i]->numvolumes;
+ }
+ _printf("%7i light volumes casted\n", numcastedvolumes);
+ numvlightsinsolid = 0;
+ for (i = 0; i < numvlights; i++)
+ {
+ if (vlights[i]->insolid)
+ numvlightsinsolid++;
+ }
+ _printf("%7i lights in solid\n", numvlightsinsolid);
+ //
+ radiosity_scale = 1;
+ for (i = 0; i < radiosity; i++) {
+ VL_Radiosity();
+ radiosity_scale <<= 1;
+ }
+ //
+ VL_StoreLightmap();
+ // redo surfaces with the old light algorithm when needed
+ VL_DoForcedTraceLightSurfaces();
+}
+
+/*
+=============
+VL_CreateEntityLights
+=============
+*/
+entity_t *FindTargetEntity( const char *target );
+
+void VL_CreateEntityLights (void)
+{
+ int i, c_entityLights;
+ vlight_t *dl;
+ entity_t *e, *e2;
+ const char *name;
+ const char *target;
+ vec3_t dest;
+ const char *_color;
+ float intensity;
+ int spawnflags;
+
+ //
+ c_entityLights = 0;
+ _printf("Creating entity lights...\n");
+ //
+ for ( i = 0 ; i < num_entities ; i++ ) {
+ e = &entities[i];
+ name = ValueForKey (e, "classname");
+ if (strncmp (name, "light", 5))
+ continue;
+
+ dl = malloc(sizeof(*dl));
+ memset (dl, 0, sizeof(*dl));
+
+ spawnflags = FloatForKey (e, "spawnflags");
+ if ( spawnflags & 1 ) {
+ dl->atten_disttype = LDAT_LINEAR;
+ }
+ if ( spawnflags & 2 ) {
+ dl->atten_disttype = LDAT_NOSCALE;
+ }
+ if ( spawnflags & 4 ) {
+ dl->atten_angletype = LAAT_QUADRATIC;
+ }
+ if ( spawnflags & 8 ) {
+ dl->atten_angletype = LAAT_DOUBLEQUADRATIC;
+ }
+
+ dl->atten_distscale = FloatForKey(e, "atten_distscale");
+ dl->atten_anglescale = FloatForKey(e, "atten_anglescale");
+
+ GetVectorForKey (e, "origin", dl->origin);
+ dl->style = FloatForKey (e, "_style");
+ if (!dl->style)
+ dl->style = FloatForKey (e, "style");
+ if (dl->style < 0)
+ dl->style = 0;
+
+ intensity = FloatForKey (e, "light");
+ if (!intensity)
+ intensity = FloatForKey (e, "_light");
+ if (!intensity)
+ intensity = 300;
+ _color = ValueForKey (e, "_color");
+ if (_color && _color[0])
+ {
+ sscanf (_color, "%f %f %f", &dl->color[0],&dl->color[1],&dl->color[2]);
+ ColorNormalize (dl->color, dl->color);
+ }
+ else
+ dl->color[0] = dl->color[1] = dl->color[2] = 1.0;
+
+ intensity = intensity * lightPointScale;
+ dl->photons = intensity;
+
+ dl->type = LIGHT_POINTRADIAL;
+
+ // lights with a target will be spotlights
+ target = ValueForKey (e, "target");
+
+ if ( target[0] ) {
+ float radius;
+ float dist;
+
+ e2 = FindTargetEntity (target);
+ if (!e2) {
+ _printf ("WARNING: light at (%i %i %i) has missing target\n",
+ (int)dl->origin[0], (int)dl->origin[1], (int)dl->origin[2]);
+ } else {
+ GetVectorForKey (e2, "origin", dest);
+ VectorSubtract (dest, dl->origin, dl->normal);
+ dist = VectorNormalize (dl->normal, dl->normal);
+ radius = FloatForKey (e, "radius");
+ if ( !radius ) {
+ radius = 64;
+ }
+ if ( !dist ) {
+ dist = 64;
+ }
+ dl->radiusByDist = (radius + 16) / dist;
+ dl->type = LIGHT_POINTSPOT;
+ }
+ }
+ vlights[numvlights++] = dl;
+ c_entityLights++;
+ }
+ _printf("%7i entity lights\n", c_entityLights);
+}
+
+/*
+==================
+VL_SubdivideAreaLight
+==================
+*/
+void VL_SubdivideAreaLight( shaderInfo_t *ls, winding_t *w, vec3_t normal,
+ float areaSubdivide, qboolean backsplash ) {
+ float area, value, intensity;
+ vlight_t *dl, *dl2;
+ vec3_t mins, maxs;
+ int axis;
+ winding_t *front, *back;
+ vec3_t planeNormal;
+ float planeDist;
+
+ if ( !w ) {
+ return;
+ }
+
+ WindingBounds( w, mins, maxs );
+
+ // check for subdivision
+ for ( axis = 0 ; axis < 3 ; axis++ ) {
+ if ( maxs[axis] - mins[axis] > areaSubdivide ) {
+ VectorClear( planeNormal );
+ planeNormal[axis] = 1;
+ planeDist = ( maxs[axis] + mins[axis] ) * 0.5;
+ ClipWindingEpsilon ( w, planeNormal, planeDist, ON_EPSILON, &front, &back );
+ VL_SubdivideAreaLight( ls, front, normal, areaSubdivide, qfalse );
+ VL_SubdivideAreaLight( ls, back, normal, areaSubdivide, qfalse );
+ FreeWinding( w );
+ return;
+ }
+ }
+
+ // create a light from this
+ area = WindingArea (w);
+ if ( area <= 0 || area > 20000000 ) {
+ return;
+ }
+
+ dl = malloc(sizeof(*dl));
+ memset (dl, 0, sizeof(*dl));
+ dl->type = LIGHT_POINTFAKESURFACE;
+
+ WindingCenter( w, dl->origin );
+ memcpy(dl->w.points, w->points, sizeof(vec3_t) * w->numpoints);
+ dl->w.numpoints = w->numpoints;
+ VectorCopy ( normal, dl->normal);
+ VectorCopy ( normal, dl->plane);
+ dl->plane[3] = DotProduct( dl->origin, normal );
+
+ value = ls->value;
+ intensity = value * area * lightAreaScale;
+ VectorAdd( dl->origin, dl->normal, dl->origin );
+
+ VectorCopy( ls->color, dl->color );
+
+ dl->photons = intensity;
+
+ // emitColor is irrespective of the area
+ VectorScale( ls->color, value*lightFormFactorValueScale*lightAreaScale, dl->emitColor );
+ //
+ VectorCopy(dl->emitColor, dl->color);
+
+ dl->si = ls;
+
+ if ( ls->contents & CONTENTS_FOG ) {
+ dl->twosided = qtrue;
+ }
+
+ vlights[numvlights++] = dl;
+
+ // optionally create a point backsplash light
+ if ( backsplash && ls->backsplashFraction > 0 ) {
+
+ dl2 = malloc(sizeof(*dl));
+ memset (dl2, 0, sizeof(*dl2));
+ dl2->type = LIGHT_POINTRADIAL;
+
+ VectorMA( dl->origin, ls->backsplashDistance, normal, dl2->origin );
+
+ VectorCopy( ls->color, dl2->color );
+
+ dl2->photons = dl->photons * ls->backsplashFraction;
+ dl2->si = ls;
+
+ vlights[numvlights++] = dl2;
+ }
+}
+
+/*
+==================
+VL_CreateFakeSurfaceLights
+==================
+*/
+void VL_CreateFakeSurfaceLights( void ) {
+ int i, j, side;
+ dsurface_t *ds;
+ shaderInfo_t *ls;
+ winding_t *w;
+ lFacet_t *f;
+ vlight_t *dl;
+ vec3_t origin;
+ drawVert_t *dv;
+ int c_surfaceLights;
+ float lightSubdivide;
+ vec3_t normal;
+
+
+ c_surfaceLights = 0;
+ _printf ("Creating surface lights...\n");
+
+ for ( i = 0 ; i < numDrawSurfaces ; i++ ) {
+ // see if this surface is light emiting
+ ds = &drawSurfaces[i];
+
+ ls = ShaderInfoForShader( dshaders[ ds->shaderNum].shader );
+ if ( ls->value == 0 ) {
+ continue;
+ }
+
+ // determine how much we need to chop up the surface
+ if ( ls->lightSubdivide ) {
+ lightSubdivide = ls->lightSubdivide;
+ } else {
+ lightSubdivide = lightDefaultSubdivide;
+ }
+
+ c_surfaceLights++;
+
+ // an autosprite shader will become
+ // a point light instead of an area light
+ if ( ls->autosprite ) {
+ // autosprite geometry should only have four vertexes
+ if ( lsurfaceTest[i] ) {
+ // curve or misc_model
+ f = lsurfaceTest[i]->facets;
+ if ( lsurfaceTest[i]->numFacets != 1 || f->numpoints != 4 ) {
+ _printf( "WARNING: surface at (%i %i %i) has autosprite shader but isn't a quad\n",
+ (int)f->points[0], (int)f->points[1], (int)f->points[2] );
+ }
+ VectorAdd( f->points[0], f->points[1], origin );
+ VectorAdd( f->points[2], origin, origin );
+ VectorAdd( f->points[3], origin, origin );
+ VectorScale( origin, 0.25, origin );
+ } else {
+ // normal polygon
+ dv = &drawVerts[ ds->firstVert ];
+ if ( ds->numVerts != 4 ) {
+ _printf( "WARNING: surface at (%i %i %i) has autosprite shader but %i verts\n",
+ (int)dv->xyz[0], (int)dv->xyz[1], (int)dv->xyz[2] );
+ continue;
+ }
+
+ VectorAdd( dv[0].xyz, dv[1].xyz, origin );
+ VectorAdd( dv[2].xyz, origin, origin );
+ VectorAdd( dv[3].xyz, origin, origin );
+ VectorScale( origin, 0.25, origin );
+ }
+
+ dl = malloc(sizeof(*dl));
+ memset (dl, 0, sizeof(*dl));
+ VectorCopy( origin, dl->origin );
+ VectorCopy( ls->color, dl->color );
+ dl->photons = ls->value * lightPointScale;
+ dl->type = LIGHT_POINTRADIAL;
+ vlights[numvlights++] = dl;
+ continue;
+ }
+
+ // possibly create for both sides of the polygon
+ for ( side = 0 ; side <= ls->twoSided ; side++ ) {
+ // create area lights
+ if ( lsurfaceTest[i] ) {
+ // curve or misc_model
+ for ( j = 0 ; j < lsurfaceTest[i]->numFacets ; j++ ) {
+ f = lsurfaceTest[i]->facets + j;
+ w = AllocWinding( f->numpoints );
+ w->numpoints = f->numpoints;
+ memcpy( w->points, f->points, f->numpoints * 12 );
+
+ VectorCopy( f->plane.normal, normal );
+ if ( side ) {
+ winding_t *t;
+
+ t = w;
+ w = ReverseWinding( t );
+ FreeWinding( t );
+ VectorSubtract( vec3_origin, normal, normal );
+ }
+ VL_SubdivideAreaLight( ls, w, normal, lightSubdivide, qtrue );
+ }
+ } else {
+ // normal polygon
+
+ w = AllocWinding( ds->numVerts );
+ w->numpoints = ds->numVerts;
+ for ( j = 0 ; j < ds->numVerts ; j++ ) {
+ VectorCopy( drawVerts[ds->firstVert+j].xyz, w->points[j] );
+ }
+ VectorCopy( ds->lightmapVecs[2], normal );
+ if ( side ) {
+ winding_t *t;
+
+ t = w;
+ w = ReverseWinding( t );
+ FreeWinding( t );
+ VectorSubtract( vec3_origin, normal, normal );
+ }
+ VL_SubdivideAreaLight( ls, w, normal, lightSubdivide, qtrue );
+ }
+ }
+ }
+
+ _printf( "%7i light emitting surfaces\n", c_surfaceLights );
+}
+
+
+/*
+==================
+VL_WindingForBrushSide
+==================
+*/
+winding_t *VL_WindingForBrushSide(dbrush_t *brush, int side, winding_t *w)
+{
+ int i, res;
+ winding_t *tmpw;
+ plane_t plane;
+
+ VectorCopy(dplanes[ dbrushsides[ brush->firstSide + side ].planeNum ].normal, plane.normal);
+ VectorInverse(plane.normal);
+ plane.dist = -dplanes[ dbrushsides[ brush->firstSide + side ].planeNum ].dist;
+ tmpw = BaseWindingForPlane( plane.normal, plane.dist );
+ memcpy(w->points, tmpw->points, sizeof(vec3_t) * tmpw->numpoints);
+ w->numpoints = tmpw->numpoints;
+
+ for (i = 0; i < brush->numSides; i++)
+ {
+ if (i == side)
+ continue;
+ VectorCopy(dplanes[ dbrushsides[ brush->firstSide + i ].planeNum ].normal, plane.normal);
+ VectorInverse(plane.normal);
+ plane.dist = -dplanes[ dbrushsides[ brush->firstSide + i ].planeNum ].dist;
+ res = VL_ChopWinding(w, &plane, 0.1);
+ if (res == SIDE_BACK)
+ return NULL;
+ }
+ return w;
+}
+
+/*
+==================
+VL_CreateSkyLights
+==================
+*/
+void VL_CreateSkyLights(void)
+{
+ int i, j, c_skyLights;
+ dbrush_t *b;
+ shaderInfo_t *si;
+ dbrushside_t *s;
+ vlight_t *dl;
+ vec3_t sunColor, sunDir = { 0.45, 0.3, 0.9 };
+ float d;
+
+ VectorNormalize(sunDir, sunDir);
+ VectorInverse(sunDir);
+
+ c_skyLights = 0;
+ _printf("Creating sky lights...\n");
+ // find the sky shader
+ for ( i = 0 ; i < numDrawSurfaces ; i++ ) {
+ si = ShaderInfoForShader( dshaders[ drawSurfaces[i].shaderNum ].shader );
+ if ( si->surfaceFlags & SURF_SKY ) {
+ VectorCopy( si->sunLight, sunColor );
+ VectorCopy( si->sunDirection, sunDir );
+ VectorInverse(sunDir);
+ break;
+ }
+ }
+
+ // find the brushes
+ for ( i = 0 ; i < numbrushes ; i++ ) {
+ b = &dbrushes[i];
+ for ( j = 0 ; j < b->numSides ; j++ ) {
+ s = &dbrushsides[ b->firstSide + j ];
+ if ( dshaders[ s->shaderNum ].surfaceFlags & SURF_SKY ) {
+ //if this surface doesn't face in the same direction as the sun
+ d = DotProduct(dplanes[ s->planeNum ].normal, sunDir);
+ if (d <= 0)
+ continue;
+ //
+ dl = malloc(sizeof(*dl));
+ memset (dl, 0, sizeof(*dl));
+ VectorCopy(sunColor, dl->color);
+ VectorCopy(sunDir, dl->normal);
+ VectorCopy(dplanes[ s->planeNum ].normal, dl->plane);
+ dl->plane[3] = dplanes[ s->planeNum ].dist;
+ dl->type = LIGHT_SURFACEDIRECTED;
+ dl->atten_disttype = LDAT_NOSCALE;
+ VL_WindingForBrushSide(b, j, &dl->w);
+// DebugNet_DrawWinding(&dl->w, 2);
+ //
+ vlights[numvlights++] = dl;
+ c_skyLights++;
+ }
+ }
+ }
+ _printf("%7i light emitting sky surfaces\n", c_skyLights);
+}
+
+/*
+==================
+VL_SetPortalSphere
+==================
+*/
+void VL_SetPortalSphere (lportal_t *p)
+{
+ int i;
+ vec3_t total, dist;
+ winding_t *w;
+ float r, bestr;
+
+ w = p->winding;
+ VectorCopy (vec3_origin, total);
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ VectorAdd (total, w->points[i], total);
+ }
+
+ for (i=0 ; i<3 ; i++)
+ total[i] /= w->numpoints;
+
+ bestr = 0;
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ VectorSubtract (w->points[i], total, dist);
+ r = VectorLength (dist);
+ if (r > bestr)
+ bestr = r;
+ }
+ VectorCopy (total, p->origin);
+ p->radius = bestr;
+}
+
+/*
+==================
+VL_PlaneFromWinding
+==================
+*/
+void VL_PlaneFromWinding (winding_t *w, plane_t *plane)
+{
+ vec3_t v1, v2;
+
+ //calc plane
+ VectorSubtract (w->points[2], w->points[1], v1);
+ VectorSubtract (w->points[0], w->points[1], v2);
+ CrossProduct (v2, v1, plane->normal);
+ VectorNormalize (plane->normal, plane->normal);
+ plane->dist = DotProduct (w->points[0], plane->normal);
+}
+
+/*
+==================
+VL_AllocWinding
+==================
+*/
+winding_t *VL_AllocWinding (int points)
+{
+ winding_t *w;
+ int size;
+
+ if (points > MAX_POINTS_ON_WINDING)
+ Error ("NewWinding: %i points", points);
+
+ size = (int)((winding_t *)0)->points[points];
+ w = malloc (size);
+ memset (w, 0, size);
+
+ return w;
+}
+
+/*
+============
+VL_LoadPortals
+============
+*/
+void VL_LoadPortals (char *name)
+{
+ int i, j, hint;
+ lportal_t *p;
+ lleaf_t *l;
+ char magic[80];
+ FILE *f;
+ int numpoints;
+ winding_t *w;
+ int leafnums[2];
+ plane_t plane;
+ //
+
+ if (!strcmp(name,"-"))
+ f = stdin;
+ else
+ {
+ f = fopen(name, "r");
+ if (!f)
+ Error ("LoadPortals: couldn't read %s\n",name);
+ }
+
+ if (fscanf (f,"%79s\n%i\n%i\n%i\n",magic, &portalclusters, &numportals, &numfaces) != 4)
+ Error ("LoadPortals: failed to read header");
+ if (strcmp(magic, PORTALFILE))
+ Error ("LoadPortals: not a portal file");
+
+ _printf ("%6i portalclusters\n", portalclusters);
+ _printf ("%6i numportals\n", numportals);
+ _printf ("%6i numfaces\n", numfaces);
+
+ if (portalclusters >= MAX_CLUSTERS)
+ Error ("more than %d clusters in portal file\n", MAX_CLUSTERS);
+
+ // each file portal is split into two memory portals
+ portals = malloc(2*numportals*sizeof(lportal_t));
+ memset (portals, 0, 2*numportals*sizeof(lportal_t));
+
+ leafs = malloc(portalclusters*sizeof(lleaf_t));
+ memset (leafs, 0, portalclusters*sizeof(lleaf_t));
+
+ for (i=0, p=portals ; i<numportals ; i++)
+ {
+ if (fscanf (f, "%i %i %i ", &numpoints, &leafnums[0], &leafnums[1]) != 3)
+ Error ("LoadPortals: reading portal %i", i);
+ if (numpoints > MAX_POINTS_ON_WINDING)
+ Error ("LoadPortals: portal %i has too many points", i);
+ if ( (unsigned)leafnums[0] > portalclusters
+ || (unsigned)leafnums[1] > portalclusters)
+ Error ("LoadPortals: reading portal %i", i);
+ if (fscanf (f, "%i ", &hint) != 1)
+ Error ("LoadPortals: reading hint state");
+
+ w = p->winding = VL_AllocWinding (numpoints);
+ w->numpoints = numpoints;
+
+ for (j=0 ; j<numpoints ; j++)
+ {
+ double v[3];
+ int k;
+
+ // scanf into double, then assign to vec_t
+ // so we don't care what size vec_t is
+ if (fscanf (f, "(%lf %lf %lf ) "
+ , &v[0], &v[1], &v[2]) != 3)
+ Error ("LoadPortals: reading portal %i", i);
+ for (k=0 ; k<3 ; k++)
+ w->points[j][k] = v[k];
+ }
+ fscanf (f, "\n");
+
+ // calc plane
+ VL_PlaneFromWinding (w, &plane);
+
+ // create forward portal
+ l = &leafs[leafnums[0]];
+ if (l->numportals == MAX_PORTALS_ON_LEAF)
+ Error ("Leaf with too many portals");
+ l->portals[l->numportals] = p;
+ l->numportals++;
+
+ p->winding = w;
+ VectorSubtract (vec3_origin, plane.normal, p->plane.normal);
+ p->plane.dist = -plane.dist;
+ p->leaf = leafnums[1];
+ VL_SetPortalSphere (p);
+ p++;
+
+ // create backwards portal
+ l = &leafs[leafnums[1]];
+ if (l->numportals == MAX_PORTALS_ON_LEAF)
+ Error ("Leaf with too many portals");
+ l->portals[l->numportals] = p;
+ l->numportals++;
+
+ p->winding = VL_AllocWinding(w->numpoints);
+ p->winding->numpoints = w->numpoints;
+ for (j=0 ; j<w->numpoints ; j++)
+ {
+ VectorCopy (w->points[w->numpoints-1-j], p->winding->points[j]);
+ }
+
+ p->plane = plane;
+ p->leaf = leafnums[0];
+ VL_SetPortalSphere (p);
+ p++;
+
+ }
+
+ fclose (f);
+}
+
+/*
+============
+VLightMain
+============
+*/
+int VLightMain (int argc, char **argv) {
+ int i;
+ double start, end;
+ const char *value;
+
+ _printf ("----- VLighting ----\n");
+
+ for (i=1 ; i<argc ; i++) {
+ if (!strcmp(argv[i],"-v")) {
+ verbose = qtrue;
+ } else if (!strcmp(argv[i],"-threads")) {
+ numthreads = atoi (argv[i+1]);
+ _printf("num threads = %d\n", numthreads);
+ i++;
+ } else if (!strcmp(argv[i],"-area")) {
+ lightAreaScale *= atof(argv[i+1]);
+ _printf ("area light scaling at %f\n", lightAreaScale);
+ i++;
+ } else if (!strcmp(argv[i],"-point")) {
+ lightPointScale *= atof(argv[i+1]);
+ _printf ("point light scaling at %f\n", lightPointScale);
+ i++;
+ } else if (!strcmp(argv[i], "-samplesize")) {
+ samplesize = atoi(argv[i+1]);
+ if (samplesize < 1) samplesize = 1;
+ i++;
+ _printf("lightmap sample size is %dx%d units\n", samplesize, samplesize);
+ } else if (!strcmp(argv[i], "-novertex")) {
+ novertexlighting = qtrue;
+ _printf("no vertex lighting = true\n");
+ } else if (!strcmp(argv[i], "-nogrid")) {
+ nogridlighting = qtrue;
+ _printf("no grid lighting = true\n");
+ } else if (!strcmp(argv[i], "-nostitching")) {
+ nostitching = qtrue;
+ _printf("no stitching = true\n");
+ } else if (!strcmp(argv[i], "-noalphashading")) {
+ noalphashading = qtrue;
+ _printf("no alpha shading = true\n");
+ } else if (!strcmp(argv[i], "-nocolorshading")) {
+ nocolorshading = qtrue;
+ _printf("old style alpha shading = true\n");
+ } else if (!strcmp(argv[i], "-nobackfaceculling")) {
+ nobackfaceculling = qtrue;
+ _printf("no backface culling = true\n");
+ } else if (!strcmp(argv[i], "-tracelight")) {
+ defaulttracelight = qtrue;
+ _printf("default trace light = true\n");
+ } else if (!strcmp(argv[i], "-radiosity")) {
+ radiosity = atoi(argv[i+1]);
+ _printf("radiosity = %d\n", radiosity);
+ i++;
+ } else {
+ break;
+ }
+ }
+
+ ThreadSetDefault ();
+
+ if (i != argc - 1) {
+ _printf("usage: q3map -vlight [-<switch> [-<switch> ...]] <mapname>\n"
+ "\n"
+ "Switches:\n"
+ " v = verbose output\n"
+ " threads <X> = set number of threads to X\n"
+ " area <V> = set the area light scale to V\n"
+ " point <W> = set the point light scale to W\n"
+ " novertex = don't calculate vertex lighting\n"
+ " nogrid = don't calculate light grid for dynamic model lighting\n"
+ " nostitching = no polygon stitching before lighting\n"
+ " noalphashading = don't use alpha shading\n"
+ " nocolorshading = don't use color alpha shading\n"
+ " tracelight = use old light algorithm by default\n"
+ " samplesize <N> = set the lightmap pixel size to NxN units\n");
+ exit(0);
+ }
+
+ SetQdirFromPath (argv[i]);
+
+#ifdef _WIN32
+ InitPakFile(gamedir, NULL);
+#endif
+
+ strcpy (source, ExpandArg(argv[i]));
+ StripExtension (source);
+ DefaultExtension (source, ".bsp");
+
+ LoadShaderInfo();
+
+ _printf ("reading %s\n", source);
+
+ LoadBSPFile (source);
+ ParseEntities();
+
+ value = ValueForKey( &entities[0], "gridsize" );
+ if (strlen(value)) {
+ sscanf( value, "%f %f %f", &gridSize[0], &gridSize[1], &gridSize[2] );
+ _printf("grid size = {%1.1f, %1.1f, %1.1f}\n", gridSize[0], gridSize[1], gridSize[2]);
+ }
+
+ CountLightmaps();
+
+ StripExtension (source);
+ DefaultExtension (source, ".prt");
+
+ VL_LoadPortals(source);
+
+ // set surfaceOrigin
+ SetEntityOrigins();
+
+ // grid and vertex lighting
+ GridAndVertexLighting();
+
+#ifdef DEBUGNET
+ DebugNet_Setup();
+#endif
+
+ start = clock();
+
+ lightFloats = (float *) malloc(numLightBytes * sizeof(float));
+ memset(lightFloats, 0, numLightBytes * sizeof(float));
+
+ VL_InitSurfacesForTesting();
+
+ VL_CalcVisibleLightmapPixelArea();
+
+ numvlights = 0;
+ VL_CreateEntityLights();
+ VL_CreateFakeSurfaceLights();
+ VL_CreateSkyLights();
+
+ VL_TestLightLeafs();
+
+ VL_LightWorld();
+
+#ifndef LIGHTPOLYS
+ StripExtension (source);
+ DefaultExtension (source, ".bsp");
+ _printf ("writing %s\n", source);
+ WriteBSPFile (source);
+#endif
+
+ end = clock();
+
+ _printf ("%5.2f seconds elapsed\n", (end-start) / CLK_TCK);
+
+#ifdef LIGHTPOLYS
+ VL_DrawLightWindings();
+#endif
+
+#ifdef DEBUGNET
+ DebugNet_Shutdown();
+#endif
+ return 0;
+}
diff --git a/q3map/makefile b/q3map/makefile
new file mode 100755
index 0000000..15c6a0b
--- /dev/null
+++ b/q3map/makefile
@@ -0,0 +1,148 @@
+
+CFLAGS = -c
+LDFLAGS =
+ODIR = /q3/q3map
+
+EXEBASE = q3map
+EXE = $(ODIR)/$(EXEBASE)
+all: $(EXE)
+
+_irix:
+ make "CFLAGS = -c -Ofast=ip27 -OPT:IEEE_arithmetic=3 -I../common -Xcpluscomm " "LDFLAGS = -Ofast=ip27 -OPT:IEEE_arithmetic=3 -g"
+
+_irixdebug:
+ make "CFLAGS = -c -O2 -g -I../common -Xcpluscomm" "LDFLAGS = -g"
+
+_irixinst:
+ make "_irix"
+ make "install"
+
+clean:
+ rm -f $(ODIR)/*.o $(EXE)
+
+install:
+ cp $(EXE) /quake3_bin
+ chmod 0777 /quake3_bin/$(EXEBASE)
+
+installtest:
+ cp $(EXE) /quake3_bin/$(EXEBASE)_test
+ chmod 0777 /quake3_bin/$(EXEBASE)_test
+
+
+FILES = $(ODIR)/fog.o $(ODIR)/brush.o $(ODIR)/tjunction.o $(ODIR)/vis.o $(ODIR)/visflow.o \
+$(ODIR)/light.o $(ODIR)/lightmaps.o $(ODIR)/bspfile.o \
+$(ODIR)/cmdlib.o $(ODIR)/patch.o $(ODIR)/mesh.o $(ODIR)/nodraw.o $(ODIR)/glfile.o \
+$(ODIR)/leakfile.o $(ODIR)/map.o $(ODIR)/mathlib.o $(ODIR)/polylib.o $(ODIR)/aselib.o \
+$(ODIR)/imagelib.o $(ODIR)/portals.o $(ODIR)/prtfile.o $(ODIR)/bsp.o $(ODIR)/surface.o \
+$(ODIR)/scriplib.o $(ODIR)/shaders.o $(ODIR)/threads.o $(ODIR)/tree.o \
+$(ODIR)/writebsp.o $(ODIR)/facebsp.o $(ODIR)/misc_model.o $(ODIR)/light_trace.o
+
+$(EXE) : $(FILES)
+ cc -o $(EXE) $(LDFLAGS) $(FILES) -lm
+
+$(ODIR)/surface.o : surface.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/fog.o : fog.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/brush.o : brush.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/tjunction.o : tjunction.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/lightmaps.o : lightmaps.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/brushbsp.o : brushbsp.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/facebsp.o : facebsp.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/patch.o : patch.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/mesh.o : mesh.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/misc_model.o : misc_model.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/nodraw.o : nodraw.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/glfile.o : glfile.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/leakfile.o : leakfile.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/map.o : map.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/portals.o : portals.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/prtfile.o : prtfile.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/bsp.o : bsp.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/tree.o : tree.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/shaders.o : shaders.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/writebsp.o : writebsp.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/csg.o : csg.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+
+
+$(ODIR)/vis.o : vis.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/visflow.o : visflow.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+
+
+$(ODIR)/light.o : light.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/light_trace.o : light_trace.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+
+$(ODIR)/cmdlib.o : ../common/cmdlib.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/mathlib.o : ../common/mathlib.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/polylib.o : ../common/polylib.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/aselib.o : ../common/aselib.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/imagelib.o : ../common/imagelib.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/scriplib.o : ../common/scriplib.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/threads.o : ../common/threads.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+$(ODIR)/bspfile.o : ../common/bspfile.c
+ cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
+ cc $(CFLAGS) -o $@ /tmp/temp.i
+
+
diff --git a/q3map/map.c b/q3map/map.c
new file mode 100755
index 0000000..e275e34
--- /dev/null
+++ b/q3map/map.c
@@ -0,0 +1,1251 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// map.c
+
+#include "qbsp.h"
+
+
+int entitySourceBrushes; // to track editor brush numbers
+
+int numMapPatches;
+
+// undefine to make plane finding use linear sort
+#define USE_HASHING
+#define PLANE_HASHES 1024
+plane_t *planehash[PLANE_HASHES];
+
+plane_t mapplanes[MAX_MAP_PLANES];
+int nummapplanes;
+
+// as brushes and patches are read in, the shaders are stored out in order
+// here, so -onlytextures can just copy them out over the existing shaders
+// in the drawSurfaces
+char mapIndexedShaders[MAX_MAP_BRUSHSIDES][MAX_QPATH];
+int numMapIndexedShaders;
+
+vec3_t map_mins, map_maxs;
+
+entity_t *mapent;
+
+
+
+int c_boxbevels;
+int c_edgebevels;
+
+int c_areaportals;
+int c_detail;
+int c_structural;
+
+// brushes are parsed into a temporary array of sides,
+// which will have the bevels added and duplicates
+// removed before the final brush is allocated
+bspbrush_t *buildBrush;
+
+
+void TestExpandBrushes (void);
+void SetTerrainTextures( void );
+void ParseTerrain( void );
+
+
+/*
+=============================================================================
+
+PLANE FINDING
+
+=============================================================================
+*/
+
+
+/*
+================
+PlaneEqual
+================
+*/
+#define NORMAL_EPSILON 0.00001
+#define DIST_EPSILON 0.01
+qboolean PlaneEqual (plane_t *p, vec3_t normal, vec_t dist)
+{
+#if 1
+ if (
+ fabs(p->normal[0] - normal[0]) < NORMAL_EPSILON
+ && fabs(p->normal[1] - normal[1]) < NORMAL_EPSILON
+ && fabs(p->normal[2] - normal[2]) < NORMAL_EPSILON
+ && fabs(p->dist - dist) < DIST_EPSILON )
+ return qtrue;
+#else
+ if (p->normal[0] == normal[0]
+ && p->normal[1] == normal[1]
+ && p->normal[2] == normal[2]
+ && p->dist == dist)
+ return qtrue;
+#endif
+ return qfalse;
+}
+
+/*
+================
+AddPlaneToHash
+================
+*/
+void AddPlaneToHash (plane_t *p)
+{
+ int hash;
+
+ hash = (int)fabs(p->dist) / 8;
+ hash &= (PLANE_HASHES-1);
+
+ p->hash_chain = planehash[hash];
+ planehash[hash] = p;
+}
+
+/*
+================
+CreateNewFloatPlane
+================
+*/
+int CreateNewFloatPlane (vec3_t normal, vec_t dist)
+{
+ plane_t *p, temp;
+
+ if (VectorLength(normal) < 0.5)
+ {
+ _printf( "FloatPlane: bad normal\n");
+ return -1;
+ }
+
+ // create a new plane
+ if (nummapplanes+2 > MAX_MAP_PLANES)
+ Error ("MAX_MAP_PLANES");
+
+ p = &mapplanes[nummapplanes];
+ VectorCopy (normal, p->normal);
+ p->dist = dist;
+ p->type = (p+1)->type = PlaneTypeForNormal (p->normal);
+
+ VectorSubtract (vec3_origin, normal, (p+1)->normal);
+ (p+1)->dist = -dist;
+
+ nummapplanes += 2;
+
+ // allways put axial planes facing positive first
+ if (p->type < 3)
+ {
+ if (p->normal[0] < 0 || p->normal[1] < 0 || p->normal[2] < 0)
+ {
+ // flip order
+ temp = *p;
+ *p = *(p+1);
+ *(p+1) = temp;
+
+ AddPlaneToHash (p);
+ AddPlaneToHash (p+1);
+ return nummapplanes - 1;
+ }
+ }
+
+ AddPlaneToHash (p);
+ AddPlaneToHash (p+1);
+ return nummapplanes - 2;
+}
+
+/*
+==============
+SnapVector
+==============
+*/
+void SnapVector (vec3_t normal)
+{
+ int i;
+
+ for (i=0 ; i<3 ; i++)
+ {
+ if ( fabs(normal[i] - 1) < NORMAL_EPSILON )
+ {
+ VectorClear (normal);
+ normal[i] = 1;
+ break;
+ }
+ if ( fabs(normal[i] - -1) < NORMAL_EPSILON )
+ {
+ VectorClear (normal);
+ normal[i] = -1;
+ break;
+ }
+ }
+}
+
+/*
+==============
+SnapPlane
+==============
+*/
+void SnapPlane (vec3_t normal, vec_t *dist)
+{
+ SnapVector (normal);
+
+ if (fabs(*dist-Q_rint(*dist)) < DIST_EPSILON)
+ *dist = Q_rint(*dist);
+}
+
+/*
+=============
+FindFloatPlane
+
+=============
+*/
+#ifndef USE_HASHING
+int FindFloatPlane (vec3_t normal, vec_t dist)
+{
+ int i;
+ plane_t *p;
+
+ SnapPlane (normal, &dist);
+ for (i=0, p=mapplanes ; i<nummapplanes ; i++, p++)
+ {
+ if (PlaneEqual (p, normal, dist))
+ return i;
+ }
+
+ return CreateNewFloatPlane (normal, dist);
+}
+#else
+int FindFloatPlane (vec3_t normal, vec_t dist)
+{
+ int i;
+ plane_t *p;
+ int hash, h;
+
+ SnapPlane (normal, &dist);
+ hash = (int)fabs(dist) / 8;
+ hash &= (PLANE_HASHES-1);
+
+ // search the border bins as well
+ for (i=-1 ; i<=1 ; i++)
+ {
+ h = (hash+i)&(PLANE_HASHES-1);
+ for (p = planehash[h] ; p ; p=p->hash_chain)
+ {
+ if (PlaneEqual (p, normal, dist))
+ return p-mapplanes;
+ }
+ }
+
+ return CreateNewFloatPlane (normal, dist);
+}
+#endif
+
+/*
+================
+MapPlaneFromPoints
+================
+*/
+int MapPlaneFromPoints (vec3_t p0, vec3_t p1, vec3_t p2) {
+ vec3_t t1, t2, normal;
+ vec_t dist;
+
+ VectorSubtract (p0, p1, t1);
+ VectorSubtract (p2, p1, t2);
+ CrossProduct (t1, t2, normal);
+ VectorNormalize (normal, normal);
+
+ dist = DotProduct (p0, normal);
+
+ return FindFloatPlane (normal, dist);
+}
+
+
+//====================================================================
+
+/*
+===========
+SetBrushContents
+
+The contents on all sides of a brush should be the same
+Sets contentsShader, contents, opaque, and detail
+===========
+*/
+void SetBrushContents( bspbrush_t *b ) {
+ int contents, c2;
+ side_t *s;
+ int i;
+ qboolean mixed;
+ int allFlags;
+
+ s = &b->sides[0];
+ contents = s->contents;
+ b->contentShader = s->shaderInfo;
+ mixed = qfalse;
+
+ allFlags = 0;
+
+ for ( i=1 ; i<b->numsides ; i++, s++ ) {
+ s = &b->sides[i];
+
+ if ( !s->shaderInfo ) {
+ continue;
+ }
+
+ c2 = s->contents;
+ if (c2 != contents) {
+ mixed = qtrue;
+ }
+
+ allFlags |= s->surfaceFlags;
+ }
+
+ if ( mixed ) {
+ qprintf ("Entity %i, Brush %i: mixed face contents\n"
+ , b->entitynum, b->brushnum);
+ }
+
+ if ( ( contents & CONTENTS_DETAIL ) && ( contents & CONTENTS_STRUCTURAL ) ) {
+ _printf ("Entity %i, Brush %i: mixed CONTENTS_DETAIL and CONTENTS_STRUCTURAL\n"
+ , num_entities-1, entitySourceBrushes );
+ contents &= ~CONTENTS_DETAIL;
+ }
+
+ // the fulldetail flag will cause detail brushes to be
+ // treated like normal brushes
+ if ( fulldetail ) {
+ contents &= ~CONTENTS_DETAIL;
+ }
+
+ // all translucent brushes that aren't specirically made structural will
+ // be detail
+ if ( ( contents & CONTENTS_TRANSLUCENT ) && !( contents & CONTENTS_STRUCTURAL ) ) {
+ contents |= CONTENTS_DETAIL;
+ }
+
+ if ( contents & CONTENTS_DETAIL ) {
+ c_detail++;
+ b->detail = qtrue;
+ } else {
+ c_structural++;
+ b->detail = qfalse;
+ }
+
+ if ( contents & CONTENTS_TRANSLUCENT ) {
+ b->opaque = qfalse;
+ } else {
+ b->opaque = qtrue;
+ }
+
+ if ( contents & CONTENTS_AREAPORTAL ) {
+ c_areaportals++;
+ }
+
+ b->contents = contents;
+}
+
+
+//============================================================================
+
+/*
+=================
+AddBrushBevels
+
+Adds any additional planes necessary to allow the brush being
+built to be expanded against axial bounding boxes
+=================
+*/
+void AddBrushBevels( void ) {
+ int axis, dir;
+ int i, order;
+ side_t sidetemp;
+ side_t *s;
+ vec3_t normal;
+ float dist;
+
+ //
+ // add the axial planes
+ //
+ order = 0;
+ for (axis=0 ; axis <3 ; axis++)
+ {
+ for (dir=-1 ; dir <= 1 ; dir+=2, order++)
+ {
+ // see if the plane is allready present
+ for ( i=0, s=buildBrush->sides ; i < buildBrush->numsides ; i++,s++ ) {
+ if (mapplanes[s->planenum].normal[axis] == dir)
+ break;
+ }
+
+ if (i == buildBrush->numsides )
+ { // add a new side
+ if ( buildBrush->numsides == MAX_BUILD_SIDES ) {
+ Error( "MAX_BUILD_SIDES" );
+ }
+ memset( s, 0, sizeof( *s ) );
+ buildBrush->numsides++;
+ VectorClear (normal);
+ normal[axis] = dir;
+ if (dir == 1)
+ dist = buildBrush->maxs[axis];
+ else
+ dist = -buildBrush->mins[axis];
+ s->planenum = FindFloatPlane (normal, dist);
+ s->contents = buildBrush->sides[0].contents;
+ s->bevel = qtrue;
+ c_boxbevels++;
+ }
+
+ // if the plane is not in it canonical order, swap it
+ if (i != order)
+ {
+ sidetemp = buildBrush->sides[order];
+ buildBrush->sides[order] = buildBrush->sides[i];
+ buildBrush->sides[i] = sidetemp;
+ }
+ }
+ }
+
+ //
+ // add the edge bevels
+ //
+ if ( buildBrush->numsides == 6 ) {
+ return; // pure axial
+ } else {
+ int j, k, l;
+ float d;
+ winding_t *w, *w2;
+ side_t *s2;
+ vec3_t vec, vec2;
+
+ // test the non-axial plane edges
+ // this code tends to cause some problems...
+ for (i=6 ; i<buildBrush->numsides ; i++)
+ {
+ s = buildBrush->sides + i;
+ w = s->winding;
+ if (!w)
+ continue;
+ for (j=0 ; j<w->numpoints ; j++)
+ {
+ k = (j+1)%w->numpoints;
+ VectorSubtract (w->p[j], w->p[k], vec);
+ if (VectorNormalize (vec, vec) < 0.5)
+ continue;
+ SnapVector (vec);
+ for (k=0 ; k<3 ; k++)
+ if ( vec[k] == -1 || vec[k] == 1)
+ break; // axial
+ if (k != 3)
+ continue; // only test non-axial edges
+
+ // try the six possible slanted axials from this edge
+ for (axis=0 ; axis <3 ; axis++)
+ {
+ for (dir=-1 ; dir <= 1 ; dir+=2)
+ {
+ // construct a plane
+ VectorClear (vec2);
+ vec2[axis] = dir;
+ CrossProduct (vec, vec2, normal);
+ if (VectorNormalize (normal, normal) < 0.5)
+ continue;
+ dist = DotProduct (w->p[j], normal);
+
+ // if all the points on all the sides are
+ // behind this plane, it is a proper edge bevel
+ for (k=0 ; k < buildBrush->numsides ; k++)
+ {
+ // if this plane has allready been used, skip it
+ if (PlaneEqual (&mapplanes[buildBrush->sides[k].planenum]
+ , normal, dist) )
+ break;
+
+ w2 = buildBrush->sides[k].winding;
+ if (!w2)
+ continue;
+ for (l=0 ; l<w2->numpoints ; l++)
+ {
+ d = DotProduct (w2->p[l], normal) - dist;
+ if (d > 0.1)
+ break; // point in front
+ }
+ if (l != w2->numpoints)
+ break;
+ }
+
+ if (k != buildBrush->numsides)
+ continue; // wasn't part of the outer hull
+ // add this plane
+ if ( buildBrush->numsides == MAX_BUILD_SIDES ) {
+ Error( "MAX_BUILD_SIDES" );
+ }
+
+ s2 = &buildBrush->sides[buildBrush->numsides];
+ buildBrush->numsides++;
+ memset( s2, 0, sizeof( *s2 ) );
+
+ s2->planenum = FindFloatPlane (normal, dist);
+ s2->contents = buildBrush->sides[0].contents;
+ s2->bevel = qtrue;
+ c_edgebevels++;
+ }
+ }
+ }
+ }
+ }
+}
+
+/*
+===============
+AddBackSides
+
+fog volumes need to have inside faces created
+===============
+*/
+void AddBackSides( void ) {
+/*
+ bspbrush_t *b;
+ int i, originalSides;
+ side_t *s;
+ side_t *newSide;
+
+ b = buildBrush;
+ originalSides = b->numsides;
+ for ( i = 0 ; i < originalSides ; i++ ) {
+ s = &b->sides[i];
+ if ( !s->shaderInfo ) {
+ continue;
+ }
+ if ( !(s->shaderInfo->contents & CONTENTS_FOG) ) {
+ continue;
+ }
+
+ // duplicate the up-facing side
+ if ( mapplanes[ s->planenum ].normal[2] == 1 ) {
+ newSide = &b->sides[ b->numsides ];
+ b->numsides++;
+
+ *newSide = *s;
+ newSide->backSide = qtrue;
+ newSide->planenum = s->planenum ^ 1; // opposite side
+ }
+ }
+*/
+}
+
+/*
+===============
+FinishBrush
+
+Produces a final brush based on the buildBrush->sides array
+and links it to the current entity
+===============
+*/
+bspbrush_t *FinishBrush( void ) {
+ bspbrush_t *b;
+
+ // liquids may need to have extra sides created for back sides
+ AddBackSides();
+
+ // create windings for sides and bounds for brush
+ if ( !CreateBrushWindings( buildBrush ) ) {
+ // don't keep this brush
+ return NULL;
+ }
+
+ // brushes that will not be visible at all are forced to be detail
+ if ( buildBrush->contents & (CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP) )
+ {
+ buildBrush->detail = qtrue;
+ c_detail++;
+ }
+
+ //
+ // origin brushes are removed, but they set
+ // the rotation origin for the rest of the brushes
+ // in the entity. After the entire entity is parsed,
+ // the planenums and texinfos will be adjusted for
+ // the origin brush
+ //
+ if ( buildBrush->contents & CONTENTS_ORIGIN )
+ {
+ char string[32];
+ vec3_t origin;
+
+ if (num_entities == 1) {
+ _printf ("Entity %i, Brush %i: origin brushes not allowed in world\n"
+ , num_entities - 1, entitySourceBrushes);
+ return NULL;
+ }
+
+ VectorAdd (buildBrush->mins, buildBrush->maxs, origin);
+ VectorScale (origin, 0.5, origin);
+
+ sprintf (string, "%i %i %i", (int)origin[0], (int)origin[1], (int)origin[2]);
+ SetKeyValue (&entities[num_entities - 1], "origin", string);
+
+ VectorCopy (origin, entities[num_entities - 1].origin);
+
+ // don't keep this brush
+ return NULL;
+ }
+
+ if ( buildBrush->contents & CONTENTS_AREAPORTAL ) {
+ if (num_entities != 1) {
+ _printf ("Entity %i, Brush %i: areaportals only allowed in world\n"
+ , num_entities - 1, entitySourceBrushes);
+ return NULL;
+ }
+ }
+
+ AddBrushBevels ();
+
+ // keep it
+ b = CopyBrush( buildBrush );
+
+ b->entitynum = num_entities-1;
+ b->brushnum = entitySourceBrushes;
+
+ b->original = b;
+
+ b->next = mapent->brushes;
+ mapent->brushes = b;
+
+ return b;
+}
+
+//======================================================================
+
+
+/*
+==================
+textureAxisFromPlane
+==================
+*/
+vec3_t baseaxis[18] =
+{
+{0,0,1}, {1,0,0}, {0,-1,0}, // floor
+{0,0,-1}, {1,0,0}, {0,-1,0}, // ceiling
+{1,0,0}, {0,1,0}, {0,0,-1}, // west wall
+{-1,0,0}, {0,1,0}, {0,0,-1}, // east wall
+{0,1,0}, {1,0,0}, {0,0,-1}, // south wall
+{0,-1,0}, {1,0,0}, {0,0,-1} // north wall
+};
+
+void TextureAxisFromPlane(plane_t *pln, vec3_t xv, vec3_t yv)
+{
+ int bestaxis;
+ vec_t dot,best;
+ int i;
+
+ best = 0;
+ bestaxis = 0;
+
+ for (i=0 ; i<6 ; i++)
+ {
+ dot = DotProduct (pln->normal, baseaxis[i*3]);
+ if (dot > best)
+ {
+ best = dot;
+ bestaxis = i;
+ }
+ }
+
+ VectorCopy (baseaxis[bestaxis*3+1], xv);
+ VectorCopy (baseaxis[bestaxis*3+2], yv);
+}
+
+
+
+/*
+=================
+QuakeTextureVecs
+
+Creates world-to-texture mapping vecs for crappy quake plane arrangements
+=================
+*/
+void QuakeTextureVecs( plane_t *plane, vec_t shift[2], vec_t rotate, vec_t scale[2],
+ vec_t mappingVecs[2][4] ) {
+
+ vec3_t vecs[2];
+ int sv, tv;
+ vec_t ang, sinv, cosv;
+ vec_t ns, nt;
+ int i, j;
+
+ TextureAxisFromPlane(plane, vecs[0], vecs[1]);
+
+ if (!scale[0])
+ scale[0] = 1;
+ if (!scale[1])
+ scale[1] = 1;
+
+ // rotate axis
+ if (rotate == 0)
+ { sinv = 0 ; cosv = 1; }
+ else if (rotate == 90)
+ { sinv = 1 ; cosv = 0; }
+ else if (rotate == 180)
+ { sinv = 0 ; cosv = -1; }
+ else if (rotate == 270)
+ { sinv = -1 ; cosv = 0; }
+ else
+ {
+ ang = rotate / 180 * Q_PI;
+ sinv = sin(ang);
+ cosv = cos(ang);
+ }
+
+ if (vecs[0][0])
+ sv = 0;
+ else if (vecs[0][1])
+ sv = 1;
+ else
+ sv = 2;
+
+ if (vecs[1][0])
+ tv = 0;
+ else if (vecs[1][1])
+ tv = 1;
+ else
+ tv = 2;
+
+ for (i=0 ; i<2 ; i++) {
+ ns = cosv * vecs[i][sv] - sinv * vecs[i][tv];
+ nt = sinv * vecs[i][sv] + cosv * vecs[i][tv];
+ vecs[i][sv] = ns;
+ vecs[i][tv] = nt;
+ }
+
+ for (i=0 ; i<2 ; i++)
+ for (j=0 ; j<3 ; j++)
+ mappingVecs[i][j] = vecs[i][j] / scale[i];
+
+ mappingVecs[0][3] = shift[0];
+ mappingVecs[1][3] = shift[1];
+}
+
+//======================================================================
+
+/*
+=================
+ParseRawBrush
+
+Just parses the sides into buildBrush->sides[], nothing else.
+no validation, back plane removal, etc.
+
+Timo - 08/26/99
+added brush epairs parsing ( ignoring actually )
+Timo - 08/04/99
+added exclusive brush primitive parsing
+Timo - 08/08/99
+support for old brush format back in
+NOTE : it would be "cleaner" to have seperate functions to parse between old and new brushes
+=================
+*/
+void ParseRawBrush( ) {
+ side_t *side;
+ vec3_t planepts[3];
+ int planenum;
+ shaderInfo_t *si;
+ // old brushes
+ vec_t shift[2];
+ vec_t rotate;
+ vec_t scale[2];
+ char name[MAX_QPATH];
+ char shader[MAX_QPATH];
+ int flags;
+
+ buildBrush->numsides = 0;
+ buildBrush->detail = qfalse;
+
+ if (g_bBrushPrimit==BPRIMIT_NEWBRUSHES)
+ MatchToken( "{" );
+
+ do
+ {
+ if (!GetToken (qtrue))
+ break;
+ if (!strcmp (token, "}") )
+ break;
+ //Timo : brush primitive : here we may have to jump over brush epairs ( only used in editor )
+ if (g_bBrushPrimit==BPRIMIT_NEWBRUSHES)
+ {
+ do
+ {
+ if (strcmp (token, "(") )
+ GetToken( qfalse );
+ else
+ break;
+ GetToken( qtrue );
+ } while (1);
+ }
+ UnGetToken();
+
+ if ( buildBrush->numsides == MAX_BUILD_SIDES ) {
+ Error( "MAX_BUILD_SIDES" );
+ }
+
+ side = &buildBrush->sides[ buildBrush->numsides ];
+ memset( side, 0, sizeof( *side ) );
+ buildBrush->numsides++;
+
+ // read the three point plane definition
+ Parse1DMatrix( 3, planepts[0] );
+ Parse1DMatrix( 3, planepts[1] );
+ Parse1DMatrix( 3, planepts[2] );
+
+ if (g_bBrushPrimit==BPRIMIT_NEWBRUSHES)
+ // read the texture matrix
+ Parse2DMatrix( 2, 3, (float *)side->texMat );
+
+ // read the texturedef
+ GetToken (qfalse);
+ strcpy (name, token);
+
+ // save the shader name for retexturing
+ if ( numMapIndexedShaders == MAX_MAP_BRUSHSIDES ) {
+ Error( "MAX_MAP_BRUSHSIDES" );
+ }
+ strcpy( mapIndexedShaders[numMapIndexedShaders], name );
+ numMapIndexedShaders++;
+
+ if (g_bBrushPrimit==BPRIMIT_OLDBRUSHES)
+ {
+ GetToken (qfalse);
+ shift[0] = atoi(token);
+ GetToken (qfalse);
+ shift[1] = atoi(token);
+ GetToken (qfalse);
+ rotate = atoi(token);
+ GetToken (qfalse);
+ scale[0] = atof(token);
+ GetToken (qfalse);
+ scale[1] = atof(token);
+ }
+
+ // find default flags and values
+ sprintf( shader, "textures/%s", name );
+ si = ShaderInfoForShader( shader );
+ side->shaderInfo = si;
+ side->surfaceFlags = si->surfaceFlags;
+ side->value = si->value;
+ side->contents = si->contents;
+
+ // allow override of default flags and values
+ // in Q3, the only thing you can override is DETAIL
+ if (TokenAvailable())
+ {
+ GetToken (qfalse);
+// side->contents = atoi(token);
+ flags = atoi(token);
+ if ( flags & CONTENTS_DETAIL ) {
+ side->contents |= CONTENTS_DETAIL;
+ }
+
+ GetToken (qfalse);
+// td.flags = atoi(token);
+
+ GetToken (qfalse);
+// td.value = atoi(token);
+ }
+
+
+ // find the plane number
+ planenum = MapPlaneFromPoints (planepts[0], planepts[1], planepts[2]);
+ side->planenum = planenum;
+
+ if (g_bBrushPrimit==BPRIMIT_OLDBRUSHES)
+ // get the texture mapping for this texturedef / plane combination
+ QuakeTextureVecs( &mapplanes[planenum], shift, rotate, scale, side->vecs );
+
+ } while (1);
+
+ if (g_bBrushPrimit==BPRIMIT_NEWBRUSHES)
+ {
+ UnGetToken();
+ MatchToken( "}" );
+ MatchToken( "}" );
+ }
+}
+
+/*
+=================
+RemoveDuplicateBrushPlanes
+
+Returns false if the brush has a mirrored set of planes,
+meaning it encloses no volume.
+Also removes planes without any normal
+=================
+*/
+qboolean RemoveDuplicateBrushPlanes( bspbrush_t * b ) {
+ int i, j, k;
+ side_t *sides;
+
+ sides = b->sides;
+
+ for ( i = 1 ; i < b->numsides ; i++ ) {
+
+ // check for a degenerate plane
+ if ( sides[i].planenum == -1) {
+ _printf ("Entity %i, Brush %i: degenerate plane\n"
+ , b->entitynum, b->brushnum);
+ // remove it
+ for ( k = i + 1 ; k < b->numsides ; k++ ) {
+ sides[k-1] = sides[k];
+ }
+ b->numsides--;
+ i--;
+ continue;
+ }
+
+ // check for duplication and mirroring
+ for ( j = 0 ; j < i ; j++ ) {
+ if ( sides[i].planenum == sides[j].planenum ) {
+ _printf ("Entity %i, Brush %i: duplicate plane\n"
+ , b->entitynum, b->brushnum);
+ // remove the second duplicate
+ for ( k = i + 1 ; k < b->numsides ; k++ ) {
+ sides[k-1] = sides[k];
+ }
+ b->numsides--;
+ i--;
+ break;
+ }
+
+ if ( sides[i].planenum == (sides[j].planenum ^ 1) ) {
+ // mirror plane, brush is invalid
+ _printf ("Entity %i, Brush %i: mirrored plane\n"
+ , b->entitynum, b->brushnum);
+ return qfalse;
+ }
+ }
+ }
+ return qtrue;
+}
+
+
+/*
+=================
+ParseBrush
+
+ qboolean parameter to true -> parse new brush primitive format ( else use old format )
+=================
+*/
+void ParseBrush (void) {
+ bspbrush_t *b;
+
+ ParseRawBrush();
+
+ buildBrush->portalareas[0] = -1;
+ buildBrush->portalareas[1] = -1;
+ buildBrush->entitynum = num_entities-1;
+ buildBrush->brushnum = entitySourceBrushes;
+
+ // if there are mirrored planes, the entire brush is invalid
+ if ( !RemoveDuplicateBrushPlanes( buildBrush ) ) {
+ return;
+ }
+
+ // get the content for the entire brush
+ SetBrushContents( buildBrush );
+
+ // allow detail brushes to be removed
+ if (nodetail && (buildBrush->contents & CONTENTS_DETAIL) ) {
+ FreeBrush( buildBrush );
+ return;
+ }
+
+ // allow water brushes to be removed
+ if (nowater && (buildBrush->contents & (CONTENTS_LAVA | CONTENTS_SLIME | CONTENTS_WATER)) ) {
+ FreeBrush( buildBrush );
+ return;
+ }
+
+ b = FinishBrush( );
+ if ( !b ) {
+ return;
+ }
+}
+
+
+/*
+================
+MoveBrushesToWorld
+
+Takes all of the brushes from the current entity and
+adds them to the world's brush list.
+
+Used by func_group
+================
+*/
+void MoveBrushesToWorld (entity_t *mapent) {
+ bspbrush_t *b, *next;
+ parseMesh_t *pm;
+
+ // move brushes
+ for ( b = mapent->brushes ; b ; b = next ) {
+ next = b->next;
+
+ b->next = entities[0].brushes;
+ entities[0].brushes = b;
+ }
+ mapent->brushes = NULL;
+
+ // move patches
+ if ( mapent->patches ) {
+
+ for ( pm = mapent->patches ; pm->next ; pm = pm->next ) {
+ }
+
+ pm->next = entities[0].patches;
+ entities[0].patches = mapent->patches;
+
+ mapent->patches = NULL;
+ }
+}
+
+
+/*
+================
+AdjustBrushesForOrigin
+================
+*/
+void AdjustBrushesForOrigin( entity_t *ent ) {
+ bspbrush_t *b;
+ int i;
+ side_t *s;
+ vec_t newdist;
+ parseMesh_t *p;
+
+ for ( b = ent->brushes ; b ; b = b->next ) {
+ for (i=0 ; i<b->numsides ; i++) {
+ s = &b->sides[i];
+ newdist = mapplanes[s->planenum].dist -
+ DotProduct (mapplanes[s->planenum].normal, ent->origin);
+ s->planenum = FindFloatPlane (mapplanes[s->planenum].normal, newdist);
+ }
+ CreateBrushWindings(b);
+ }
+
+ for ( p = ent->patches ; p ; p = p->next ) {
+ for ( i = 0 ; i < p->mesh.width*p->mesh.height ; i++ ) {
+ VectorSubtract( p->mesh.verts[i].xyz, ent->origin, p->mesh.verts[i].xyz );
+ }
+ }
+
+}
+
+/*
+================
+ParseMapEntity
+================
+*/
+qboolean ParseMapEntity (void) {
+ epair_t *e;
+
+ if (!GetToken (qtrue))
+ return qfalse;
+
+ if (strcmp (token, "{") )
+ {
+ Error ("ParseEntity: { not found, found %s on line %d - last entity was at: <%4.2f, %4.2f, %4.2f>...", token, scriptline, entities[num_entities].origin[0], entities[num_entities].origin[1], entities[num_entities].origin[2]);
+ }
+
+ if (num_entities == MAX_MAP_ENTITIES)
+ Error ("num_entities == MAX_MAP_ENTITIES");
+
+ entitySourceBrushes = 0;
+
+ mapent = &entities[num_entities];
+ num_entities++;
+ memset (mapent, 0, sizeof(*mapent));
+
+ do
+ {
+ if (!GetToken (qtrue))
+ Error ("ParseEntity: EOF without closing brace");
+ if (!strcmp (token, "}") )
+ break;
+
+ if (!strcmp (token, "{") ) {
+ // parse a brush or patch
+ if (!GetToken (qtrue))
+ break;
+ if ( !strcmp( token, "patchDef2" ) ) {
+ numMapPatches++;
+ ParsePatch();
+ } else if ( !strcmp( token, "terrainDef" ) ) {
+ ParseTerrain();
+ } else if ( !strcmp( token, "brushDef" ) ) {
+ if (g_bBrushPrimit==BPRIMIT_OLDBRUSHES)
+ Error("old brush format not allowed in new brush format map");
+ g_bBrushPrimit=BPRIMIT_NEWBRUSHES;
+ // parse brush primitive
+ ParseBrush();
+ }
+ else
+ {
+ if (g_bBrushPrimit==BPRIMIT_NEWBRUSHES)
+ Error("new brush format not allowed in old brush format map");
+ g_bBrushPrimit=BPRIMIT_OLDBRUSHES;
+ // parse old brush format
+ UnGetToken();
+ ParseBrush();
+ }
+ entitySourceBrushes++;
+ }
+ else
+ {
+ // parse a key / value pair
+ e = ParseEpair ();
+ e->next = mapent->epairs;
+ mapent->epairs = e;
+ }
+ } while (1);
+
+ GetVectorForKey (mapent, "origin", mapent->origin);
+
+ //
+ // if there was an origin brush, offset all of the planes and texinfo
+ // for all the brushes in the entity
+ if (mapent->origin[0] || mapent->origin[1] || mapent->origin[2]) {
+ AdjustBrushesForOrigin( mapent );
+ }
+
+ // group_info entities are just for editor grouping
+ // ignored
+ // FIXME: leak!
+ if (!strcmp("group_info", ValueForKey (mapent, "classname")))
+ {
+ num_entities--;
+ return qtrue;
+ }
+
+ // group entities are just for editor convenience
+ // toss all brushes into the world entity
+ if (!strcmp ("func_group", ValueForKey (mapent, "classname")))
+ {
+ if ( !strcmp ("1", ValueForKey (mapent, "terrain"))) {
+ SetTerrainTextures();
+ }
+ MoveBrushesToWorld (mapent);
+ num_entities--;
+ return qtrue;
+ }
+
+ return qtrue;
+}
+
+//===================================================================
+
+
+/*
+================
+LoadMapFile
+================
+*/
+void LoadMapFile (char *filename) {
+ bspbrush_t *b;
+
+ qprintf ("--- LoadMapFile ---\n");
+ _printf ("Loading map file %s\n", filename);
+
+ LoadScriptFile (filename);
+
+ num_entities = 0;
+ numMapDrawSurfs = 0;
+ c_detail = 0;
+
+ g_bBrushPrimit = BPRIMIT_UNDEFINED;
+
+ // allocate a very large temporary brush for building
+ // the brushes as they are loaded
+ buildBrush = AllocBrush( MAX_BUILD_SIDES );
+
+ while (ParseMapEntity ())
+ {
+ }
+
+ ClearBounds (map_mins, map_maxs);
+ for ( b = entities[0].brushes ; b ; b=b->next ) {
+ AddPointToBounds( b->mins, map_mins, map_maxs );
+ AddPointToBounds( b->maxs, map_mins, map_maxs );
+ }
+
+ qprintf ("%5i total world brushes\n", CountBrushList( entities[0].brushes ) );
+ qprintf ("%5i detail brushes\n", c_detail );
+ qprintf ("%5i patches\n", numMapPatches);
+ qprintf ("%5i boxbevels\n", c_boxbevels);
+ qprintf ("%5i edgebevels\n", c_edgebevels);
+ qprintf ("%5i entities\n", num_entities);
+ qprintf ("%5i planes\n", nummapplanes);
+ qprintf ("%5i areaportals\n", c_areaportals);
+ qprintf ("size: %5.0f,%5.0f,%5.0f to %5.0f,%5.0f,%5.0f\n", map_mins[0],map_mins[1],map_mins[2],
+ map_maxs[0],map_maxs[1],map_maxs[2]);
+
+ if ( fakemap ) {
+ WriteBspBrushMap ("fakemap.map", entities[0].brushes );
+ }
+
+ if ( testExpand ) {
+ TestExpandBrushes ();
+ }
+}
+
+
+//====================================================================
+
+
+/*
+================
+TestExpandBrushes
+
+Expands all the brush planes and saves a new map out to
+allow visual inspection of the clipping bevels
+================
+*/
+void TestExpandBrushes( void ) {
+ side_t *s;
+ int i, j;
+ bspbrush_t *brush, *list, *copy;
+ vec_t dist;
+ plane_t *plane;
+
+ list = NULL;
+
+ for ( brush = entities[0].brushes ; brush ; brush = brush->next ) {
+ copy = CopyBrush( brush );
+ copy->next = list;
+ list = copy;
+
+ // expand all the planes
+ for ( i=0 ; i<brush->numsides ; i++ ) {
+ s = brush->sides + i;
+ plane = &mapplanes[s->planenum];
+ dist = plane->dist;
+ for (j=0 ; j<3 ; j++) {
+ dist += fabs( 16 * plane->normal[j] );
+ }
+ s->planenum = FindFloatPlane( plane->normal, dist );
+ }
+
+ }
+
+ WriteBspBrushMap ( "expanded.map", entities[0].brushes );
+
+ Error ("can't proceed after expanding brushes");
+}
diff --git a/q3map/mesh.c b/q3map/mesh.c
new file mode 100755
index 0000000..c49c76b
--- /dev/null
+++ b/q3map/mesh.c
@@ -0,0 +1,682 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+
+
+/*
+===============================================================
+
+MESH SUBDIVISION
+
+===============================================================
+*/
+
+
+int originalWidths[MAX_EXPANDED_AXIS];
+int originalHeights[MAX_EXPANDED_AXIS];
+
+int neighbors[8][2] = {
+ {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1}, {-1,-1}, {-1,0}, {-1,1}
+};
+
+/*
+============
+LerpDrawVert
+============
+*/
+void LerpDrawVert( drawVert_t *a, drawVert_t *b, drawVert_t *out ) {
+ out->xyz[0] = 0.5 * (a->xyz[0] + b->xyz[0]);
+ out->xyz[1] = 0.5 * (a->xyz[1] + b->xyz[1]);
+ out->xyz[2] = 0.5 * (a->xyz[2] + b->xyz[2]);
+
+ out->st[0] = 0.5 * (a->st[0] + b->st[0]);
+ out->st[1] = 0.5 * (a->st[1] + b->st[1]);
+
+ out->lightmap[0] = 0.5 * (a->lightmap[0] + b->lightmap[0]);
+ out->lightmap[1] = 0.5 * (a->lightmap[1] + b->lightmap[1]);
+
+ out->color[0] = (a->color[0] + b->color[0]) >> 1;
+ out->color[1] = (a->color[1] + b->color[1]) >> 1;
+ out->color[2] = (a->color[2] + b->color[2]) >> 1;
+ out->color[3] = (a->color[3] + b->color[3]) >> 1;
+}
+
+
+void FreeMesh( mesh_t *m ) {
+ free( m->verts );
+ free( m );
+}
+
+void PrintMesh( mesh_t *m ) {
+ int i, j;
+
+ for ( i = 0 ; i < m->height ; i++ ) {
+ for ( j = 0 ; j < m->width ; j++ ) {
+ _printf("(%5.2f %5.2f %5.2f) "
+ , m->verts[i*m->width+j].xyz[0]
+ , m->verts[i*m->width+j].xyz[1]
+ , m->verts[i*m->width+j].xyz[2] );
+ }
+ _printf("\n");
+ }
+}
+
+
+mesh_t *CopyMesh( mesh_t *mesh ) {
+ mesh_t *out;
+ int size;
+
+ out = malloc( sizeof( *out ) );
+ out->width = mesh->width;
+ out->height = mesh->height;
+
+ size = out->width * out->height * sizeof( *out->verts );
+ out->verts = malloc( size );
+ memcpy( out->verts, mesh->verts, size );
+
+ return out;
+}
+
+
+/*
+=================
+TransposeMesh
+
+Returns a transposed copy of the mesh, freeing the original
+=================
+*/
+mesh_t *TransposeMesh( mesh_t *in ) {
+ int w, h;
+ mesh_t *out;
+
+ out = malloc( sizeof( *out ) );
+ out->width = in->height;
+ out->height = in->width;
+ out->verts = malloc( out->width * out->height * sizeof( drawVert_t ) );
+
+ for ( h = 0 ; h < in->height ; h++ ) {
+ for ( w = 0 ; w < in->width ; w++ ) {
+ out->verts[ w * in->height + h ] = in->verts[ h * in->width + w ];
+ }
+ }
+
+ FreeMesh( in );
+
+ return out;
+}
+
+void InvertMesh( mesh_t *in ) {
+ int w, h;
+ drawVert_t temp;
+
+ for ( h = 0 ; h < in->height ; h++ ) {
+ for ( w = 0 ; w < in->width / 2 ; w++ ) {
+ temp = in->verts[ h * in->width + w ];
+ in->verts[ h * in->width + w ] = in->verts[ h * in->width + in->width - 1 - w ];
+ in->verts[ h * in->width + in->width - 1 - w ] = temp;
+ }
+ }
+}
+
+/*
+=================
+MakeMeshNormals
+
+=================
+*/
+void MakeMeshNormals( mesh_t in ) {
+ int i, j, k, dist;
+ vec3_t normal;
+ vec3_t sum;
+ int count;
+ vec3_t base;
+ vec3_t delta;
+ int x, y;
+ drawVert_t *dv;
+ vec3_t around[8], temp;
+ qboolean good[8];
+ qboolean wrapWidth, wrapHeight;
+ float len;
+
+ wrapWidth = qfalse;
+ for ( i = 0 ; i < in.height ; i++ ) {
+ VectorSubtract( in.verts[i*in.width].xyz,
+ in.verts[i*in.width+in.width-1].xyz, delta );
+ len = VectorLength( delta );
+ if ( len > 1.0 ) {
+ break;
+ }
+ }
+ if ( i == in.height ) {
+ wrapWidth = qtrue;
+ }
+
+ wrapHeight = qfalse;
+ for ( i = 0 ; i < in.width ; i++ ) {
+ VectorSubtract( in.verts[i].xyz,
+ in.verts[i + (in.height-1)*in.width].xyz, delta );
+ len = VectorLength( delta );
+ if ( len > 1.0 ) {
+ break;
+ }
+ }
+ if ( i == in.width) {
+ wrapHeight = qtrue;
+ }
+
+
+ for ( i = 0 ; i < in.width ; i++ ) {
+ for ( j = 0 ; j < in.height ; j++ ) {
+ count = 0;
+ dv = &in.verts[j*in.width+i];
+ VectorCopy( dv->xyz, base );
+ for ( k = 0 ; k < 8 ; k++ ) {
+ VectorClear( around[k] );
+ good[k] = qfalse;
+
+ for ( dist = 1 ; dist <= 3 ; dist++ ) {
+ x = i + neighbors[k][0] * dist;
+ y = j + neighbors[k][1] * dist;
+ if ( wrapWidth ) {
+ if ( x < 0 ) {
+ x = in.width - 1 + x;
+ } else if ( x >= in.width ) {
+ x = 1 + x - in.width;
+ }
+ }
+ if ( wrapHeight ) {
+ if ( y < 0 ) {
+ y = in.height - 1 + y;
+ } else if ( y >= in.height ) {
+ y = 1 + y - in.height;
+ }
+ }
+
+ if ( x < 0 || x >= in.width || y < 0 || y >= in.height ) {
+ break; // edge of patch
+ }
+ VectorSubtract( in.verts[y*in.width+x].xyz, base, temp );
+ if ( VectorNormalize( temp, temp ) == 0 ) {
+ continue; // degenerate edge, get more dist
+ } else {
+ good[k] = qtrue;
+ VectorCopy( temp, around[k] );
+ break; // good edge
+ }
+ }
+ }
+
+ VectorClear( sum );
+ for ( k = 0 ; k < 8 ; k++ ) {
+ if ( !good[k] || !good[(k+1)&7] ) {
+ continue; // didn't get two points
+ }
+ CrossProduct( around[(k+1)&7], around[k], normal );
+ if ( VectorNormalize( normal, normal ) == 0 ) {
+ continue;
+ }
+ VectorAdd( normal, sum, sum );
+ count++;
+ }
+ if ( count == 0 ) {
+//_printf("bad normal\n");
+ count = 1;
+ }
+ VectorNormalize( sum, dv->normal );
+ }
+ }
+}
+
+/*
+=================
+PutMeshOnCurve
+
+Drops the aproximating points onto the curve
+=================
+*/
+void PutMeshOnCurve( mesh_t in ) {
+ int i, j, l;
+ float prev, next;
+
+ // put all the aproximating points on the curve
+ for ( i = 0 ; i < in.width ; i++ ) {
+ for ( j = 1 ; j < in.height ; j += 2 ) {
+ for ( l = 0 ; l < 3 ; l++ ) {
+ prev = ( in.verts[j*in.width+i].xyz[l] + in.verts[(j+1)*in.width+i].xyz[l] ) * 0.5;
+ next = ( in.verts[j*in.width+i].xyz[l] + in.verts[(j-1)*in.width+i].xyz[l] ) * 0.5;
+ in.verts[j*in.width+i].xyz[l] = ( prev + next ) * 0.5;
+ }
+ }
+ }
+
+ for ( j = 0 ; j < in.height ; j++ ) {
+ for ( i = 1 ; i < in.width ; i += 2 ) {
+ for ( l = 0 ; l < 3 ; l++ ) {
+ prev = ( in.verts[j*in.width+i].xyz[l] + in.verts[j*in.width+i+1].xyz[l] ) * 0.5;
+ next = ( in.verts[j*in.width+i].xyz[l] + in.verts[j*in.width+i-1].xyz[l] ) * 0.5;
+ in.verts[j*in.width+i].xyz[l] = ( prev + next ) * 0.5;
+ }
+ }
+ }
+}
+
+
+/*
+=================
+SubdivideMesh
+
+=================
+*/
+mesh_t *SubdivideMesh( mesh_t in, float maxError, float minLength ) {
+ int i, j, k, l;
+ drawVert_t prev, next, mid;
+ vec3_t prevxyz, nextxyz, midxyz;
+ vec3_t delta;
+ float len;
+ mesh_t out;
+ drawVert_t expand[MAX_EXPANDED_AXIS][MAX_EXPANDED_AXIS];
+
+ out.width = in.width;
+ out.height = in.height;
+
+ for ( i = 0 ; i < in.width ; i++ ) {
+ for ( j = 0 ; j < in.height ; j++ ) {
+ expand[j][i] = in.verts[j*in.width+i];
+ }
+ }
+
+ for ( i = 0 ; i < in.height ; i++ ) {
+ originalHeights[i] = i;
+ }
+ for ( i = 0 ; i < in.width ; i++ ) {
+ originalWidths[i] = i;
+ }
+
+ // horizontal subdivisions
+ for ( j = 0 ; j + 2 < out.width ; j += 2 ) {
+ // check subdivided midpoints against control points
+ for ( i = 0 ; i < out.height ; i++ ) {
+ for ( l = 0 ; l < 3 ; l++ ) {
+ prevxyz[l] = expand[i][j+1].xyz[l] - expand[i][j].xyz[l];
+ nextxyz[l] = expand[i][j+2].xyz[l] - expand[i][j+1].xyz[l];
+ midxyz[l] = (expand[i][j].xyz[l] + expand[i][j+1].xyz[l] * 2
+ + expand[i][j+2].xyz[l] ) * 0.25;
+ }
+
+ // if the span length is too long, force a subdivision
+ if ( VectorLength( prevxyz ) > minLength
+ || VectorLength( nextxyz ) > minLength ) {
+ break;
+ }
+
+ // see if this midpoint is off far enough to subdivide
+ VectorSubtract( expand[i][j+1].xyz, midxyz, delta );
+ len = VectorLength( delta );
+ if ( len > maxError ) {
+ break;
+ }
+ }
+
+ if ( out.width + 2 >= MAX_EXPANDED_AXIS ) {
+ break; // can't subdivide any more
+ }
+
+ if ( i == out.height ) {
+ continue; // didn't need subdivision
+ }
+
+ // insert two columns and replace the peak
+ out.width += 2;
+
+ for ( k = out.width - 1 ; k > j + 3 ; k-- ) {
+ originalWidths[k] = originalWidths[k-2];
+ }
+ originalWidths[j+3] = originalWidths[j+1];
+ originalWidths[j+2] = originalWidths[j+1];
+ originalWidths[j+1] = originalWidths[j];
+
+ for ( i = 0 ; i < out.height ; i++ ) {
+ LerpDrawVert( &expand[i][j], &expand[i][j+1], &prev );
+ LerpDrawVert( &expand[i][j+1], &expand[i][j+2], &next );
+ LerpDrawVert( &prev, &next, &mid );
+
+ for ( k = out.width - 1 ; k > j + 3 ; k-- ) {
+ expand[i][k] = expand[i][k-2];
+ }
+ expand[i][j + 1] = prev;
+ expand[i][j + 2] = mid;
+ expand[i][j + 3] = next;
+ }
+
+ // back up and recheck this set again, it may need more subdivision
+ j -= 2;
+
+ }
+
+ // vertical subdivisions
+ for ( j = 0 ; j + 2 < out.height ; j += 2 ) {
+ // check subdivided midpoints against control points
+ for ( i = 0 ; i < out.width ; i++ ) {
+ for ( l = 0 ; l < 3 ; l++ ) {
+ prevxyz[l] = expand[j+1][i].xyz[l] - expand[j][i].xyz[l];
+ nextxyz[l] = expand[j+2][i].xyz[l] - expand[j+1][i].xyz[l];
+ midxyz[l] = (expand[j][i].xyz[l] + expand[j+1][i].xyz[l] * 2
+ + expand[j+2][i].xyz[l] ) * 0.25;
+ }
+
+ // if the span length is too long, force a subdivision
+ if ( VectorLength( prevxyz ) > minLength
+ || VectorLength( nextxyz ) > minLength ) {
+ break;
+ }
+ // see if this midpoint is off far enough to subdivide
+ VectorSubtract( expand[j+1][i].xyz, midxyz, delta );
+ len = VectorLength( delta );
+ if ( len > maxError ) {
+ break;
+ }
+ }
+
+ if ( out.height + 2 >= MAX_EXPANDED_AXIS ) {
+ break; // can't subdivide any more
+ }
+
+ if ( i == out.width ) {
+ continue; // didn't need subdivision
+ }
+
+ // insert two columns and replace the peak
+ out.height += 2;
+
+ for ( k = out.height - 1 ; k > j + 3 ; k-- ) {
+ originalHeights[k] = originalHeights[k-2];
+ }
+ originalHeights[j+3] = originalHeights[j+1];
+ originalHeights[j+2] = originalHeights[j+1];
+ originalHeights[j+1] = originalHeights[j];
+
+ for ( i = 0 ; i < out.width ; i++ ) {
+ LerpDrawVert( &expand[j][i], &expand[j+1][i], &prev );
+ LerpDrawVert( &expand[j+1][i], &expand[j+2][i], &next );
+ LerpDrawVert( &prev, &next, &mid );
+
+ for ( k = out.height - 1 ; k > j + 3 ; k-- ) {
+ expand[k][i] = expand[k-2][i];
+ }
+ expand[j+1][i] = prev;
+ expand[j+2][i] = mid;
+ expand[j+3][i] = next;
+ }
+
+ // back up and recheck this set again, it may need more subdivision
+ j -= 2;
+
+ }
+
+ // collapse the verts
+
+ out.verts = &expand[0][0];
+ for ( i = 1 ; i < out.height ; i++ ) {
+ memmove( &out.verts[i*out.width], expand[i], out.width * sizeof(drawVert_t) );
+ }
+
+ return CopyMesh(&out);
+}
+
+/*
+================
+ProjectPointOntoVector
+================
+*/
+void ProjectPointOntoVector( vec3_t point, vec3_t vStart, vec3_t vEnd, vec3_t vProj )
+{
+ vec3_t pVec, vec;
+
+ VectorSubtract( point, vStart, pVec );
+ VectorSubtract( vEnd, vStart, vec );
+ VectorNormalize( vec, vec );
+ // project onto the directional vector for this segment
+ VectorMA( vStart, DotProduct( pVec, vec ), vec, vProj );
+}
+
+/*
+================
+RemoveLinearMeshColumsRows
+================
+*/
+mesh_t *RemoveLinearMeshColumnsRows( mesh_t *in ) {
+ int i, j, k;
+ float len, maxLength;
+ vec3_t proj, dir;
+ mesh_t out;
+ drawVert_t expand[MAX_EXPANDED_AXIS][MAX_EXPANDED_AXIS];
+
+ out.width = in->width;
+ out.height = in->height;
+
+ for ( i = 0 ; i < in->width ; i++ ) {
+ for ( j = 0 ; j < in->height ; j++ ) {
+ expand[j][i] = in->verts[j*in->width+i];
+ }
+ }
+
+ for ( j = 1 ; j < out.width - 1; j++ ) {
+ maxLength = 0;
+ for ( i = 0 ; i < out.height ; i++ ) {
+ ProjectPointOntoVector(expand[i][j].xyz, expand[i][j-1].xyz, expand[i][j+1].xyz, proj);
+ VectorSubtract(expand[i][j].xyz, proj, dir);
+ len = VectorLength(dir);
+ if (len > maxLength) {
+ maxLength = len;
+ }
+ }
+ if (maxLength < 0.1)
+ {
+ out.width--;
+ for ( i = 0 ; i < out.height ; i++ ) {
+ for (k = j; k < out.width; k++) {
+ expand[i][k] = expand[i][k+1];
+ }
+ }
+ for (k = j; k < out.width; k++) {
+ originalWidths[k] = originalWidths[k+1];
+ }
+ j--;
+ }
+ }
+ for ( j = 1 ; j < out.height - 1; j++ ) {
+ maxLength = 0;
+ for ( i = 0 ; i < out.width ; i++ ) {
+ ProjectPointOntoVector(expand[j][i].xyz, expand[j-1][i].xyz, expand[j+1][i].xyz, proj);
+ VectorSubtract(expand[j][i].xyz, proj, dir);
+ len = VectorLength(dir);
+ if (len > maxLength) {
+ maxLength = len;
+ }
+ }
+ if (maxLength < 0.1)
+ {
+ out.height--;
+ for ( i = 0 ; i < out.width ; i++ ) {
+ for (k = j; k < out.height; k++) {
+ expand[k][i] = expand[k+1][i];
+ }
+ }
+ for (k = j; k < out.height; k++) {
+ originalHeights[k] = originalHeights[k+1];
+ }
+ j--;
+ }
+ }
+ // collapse the verts
+ out.verts = &expand[0][0];
+ for ( i = 1 ; i < out.height ; i++ ) {
+ memmove( &out.verts[i*out.width], expand[i], out.width * sizeof(drawVert_t) );
+ }
+
+ return CopyMesh(&out);
+}
+
+/*
+============
+LerpDrawVertAmount
+============
+*/
+void LerpDrawVertAmount( drawVert_t *a, drawVert_t *b, float amount, drawVert_t *out ) {
+ out->xyz[0] = a->xyz[0] + amount * (b->xyz[0] - a->xyz[0]);
+ out->xyz[1] = a->xyz[1] + amount * (b->xyz[1] - a->xyz[1]);
+ out->xyz[2] = a->xyz[2] + amount * (b->xyz[2] - a->xyz[2]);
+
+ out->st[0] = a->st[0] + amount * (b->st[0] - a->st[0]);
+ out->st[1] = a->st[1] + amount * (b->st[1] - a->st[1]);
+
+ out->lightmap[0] = a->lightmap[0] + amount * (b->lightmap[0] - a->lightmap[0]);
+ out->lightmap[1] = a->lightmap[1] + amount * (b->lightmap[1] - a->lightmap[1]);
+
+ out->color[0] = a->color[0] + amount * (b->color[0] - a->color[0]);
+ out->color[1] = a->color[1] + amount * (b->color[1] - a->color[1]);
+ out->color[2] = a->color[2] + amount * (b->color[2] - a->color[2]);
+ out->color[3] = a->color[3] + amount * (b->color[3] - a->color[3]);
+
+ out->normal[0] = a->normal[0] + amount * (b->normal[0] - a->normal[0]);
+ out->normal[1] = a->normal[1] + amount * (b->normal[1] - a->normal[1]);
+ out->normal[2] = a->normal[2] + amount * (b->normal[2] - a->normal[2]);
+ VectorNormalize(out->normal, out->normal);
+}
+
+/*
+=================
+SubdivideMeshQuads
+=================
+*/
+mesh_t *SubdivideMeshQuads( mesh_t *in, float minLength, int maxsize, int widthtable[], int heighttable[]) {
+ int i, j, k, w, h, maxsubdivisions, subdivisions;
+ vec3_t dir;
+ float length, maxLength, amount;
+ mesh_t out;
+ drawVert_t expand[MAX_EXPANDED_AXIS][MAX_EXPANDED_AXIS];
+
+ out.width = in->width;
+ out.height = in->height;
+
+ for ( i = 0 ; i < in->width ; i++ ) {
+ for ( j = 0 ; j < in->height ; j++ ) {
+ expand[j][i] = in->verts[j*in->width+i];
+ }
+ }
+
+ if (maxsize > MAX_EXPANDED_AXIS)
+ Error("SubdivideMeshQuads: maxsize > MAX_EXPANDED_AXIS");
+
+ // horizontal subdivisions
+
+ maxsubdivisions = (maxsize - in->width) / (in->width - 1);
+
+ for ( w = 0, j = 0 ; w < in->width - 1; w++, j += subdivisions + 1) {
+ maxLength = 0;
+ for ( i = 0 ; i < out.height ; i++ ) {
+ VectorSubtract(expand[i][j+1].xyz, expand[i][j].xyz, dir);
+ length = VectorLength( dir );
+ if (length > maxLength) {
+ maxLength = length;
+ }
+ }
+
+ subdivisions = (int) (maxLength / minLength);
+ if (subdivisions > maxsubdivisions)
+ subdivisions = maxsubdivisions;
+
+ widthtable[w] = subdivisions + 1;
+ if (subdivisions <= 0)
+ continue;
+
+ out.width += subdivisions;
+
+ for ( k = out.width - 1; k >= j + subdivisions; k-- ) {
+ originalWidths[k] = originalWidths[k-subdivisions];
+ }
+ for (k = 1; k <= subdivisions; k++) {
+ originalWidths[j+k] = originalWidths[j];
+ }
+
+ for ( i = 0 ; i < out.height ; i++ ) {
+ for ( k = out.width - 1 ; k > j + subdivisions; k-- ) {
+ expand[i][k] = expand[i][k-subdivisions];
+ }
+ for (k = 1; k <= subdivisions; k++)
+ {
+ amount = (float) k / (subdivisions + 1);
+ LerpDrawVertAmount(&expand[i][j], &expand[i][j+subdivisions+1], amount, &expand[i][j+k]);
+ }
+ }
+ }
+
+ maxsubdivisions = (maxsize - in->height) / (in->height - 1);
+
+ for ( h = 0, j = 0 ; h < in->height - 1; h++, j += subdivisions + 1) {
+ maxLength = 0;
+ for ( i = 0 ; i < out.width ; i++ ) {
+ VectorSubtract(expand[j+1][i].xyz, expand[j][i].xyz, dir);
+ length = VectorLength( dir );
+ if (length > maxLength) {
+ maxLength = length;
+ }
+ }
+
+ subdivisions = (int) (maxLength / minLength);
+ if (subdivisions > maxsubdivisions)
+ subdivisions = maxsubdivisions;
+
+ heighttable[h] = subdivisions + 1;
+ if (subdivisions <= 0)
+ continue;
+
+ out.height += subdivisions;
+
+ for ( k = out.height - 1; k >= j + subdivisions; k-- ) {
+ originalHeights[k] = originalHeights[k-subdivisions];
+ }
+ for (k = 1; k <= subdivisions; k++) {
+ originalHeights[j+k] = originalHeights[j];
+ }
+
+ for ( i = 0 ; i < out.width ; i++ ) {
+ for ( k = out.height - 1 ; k > j + subdivisions; k-- ) {
+ expand[k][i] = expand[k-subdivisions][i];
+ }
+ for (k = 1; k <= subdivisions; k++)
+ {
+ amount = (float) k / (subdivisions + 1);
+ LerpDrawVertAmount(&expand[j][i], &expand[j+subdivisions+1][i], amount, &expand[j+k][i]);
+ }
+ }
+ }
+
+ // collapse the verts
+ out.verts = &expand[0][0];
+ for ( i = 1 ; i < out.height ; i++ ) {
+ memmove( &out.verts[i*out.width], expand[i], out.width * sizeof(drawVert_t) );
+ }
+
+ return CopyMesh(&out);
+}
diff --git a/q3map/mesh.h b/q3map/mesh.h
new file mode 100755
index 0000000..06f5684
--- /dev/null
+++ b/q3map/mesh.h
@@ -0,0 +1,48 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+// mesh.h
+
+
+typedef struct {
+ int width, height;
+ drawVert_t *verts;
+} mesh_t;
+
+#define MAX_EXPANDED_AXIS 128
+
+extern int originalWidths[MAX_EXPANDED_AXIS];
+extern int originalHeights[MAX_EXPANDED_AXIS];
+
+void FreeMesh( mesh_t *m );
+mesh_t *CopyMesh( mesh_t *mesh );
+void PrintMesh( mesh_t *m );
+mesh_t *TransposeMesh( mesh_t *in );
+void InvertMesh( mesh_t *m );
+mesh_t *SubdivideMesh( mesh_t in, float maxError, float minLength );
+mesh_t *SubdivideMeshQuads( mesh_t *in, float minLength, int maxsize, int widthtable[], int heighttable[]);
+mesh_t *RemoveLinearMeshColumnsRows( mesh_t *in );
+void MakeMeshNormals( mesh_t in );
+void PutMeshOnCurve( mesh_t in );
+
+
+void MakeNormalVectors (vec3_t forward, vec3_t right, vec3_t up);
diff --git a/q3map/misc_model.c b/q3map/misc_model.c
new file mode 100755
index 0000000..c83e7e7
--- /dev/null
+++ b/q3map/misc_model.c
@@ -0,0 +1,472 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+#include "aselib.h"
+#ifdef _WIN32
+#ifdef _TTIMOBUILD
+#include "pakstuff.h"
+#else
+#include "../libs/pakstuff.h"
+#endif
+#endif
+
+
+typedef struct {
+ char modelName[1024];
+ md3Header_t *header;
+} loadedModel_t;
+
+int c_triangleModels;
+int c_triangleSurfaces;
+int c_triangleVertexes;
+int c_triangleIndexes;
+
+
+#define MAX_LOADED_MODELS 1024
+loadedModel_t loadedModels[MAX_LOADED_MODELS];
+int numLoadedModels;
+
+/*
+=================
+R_LoadMD3
+=================
+*/
+#define LL(x) x=LittleLong(x)
+md3Header_t *R_LoadMD3( const char *mod_name ) {
+ int i, j;
+ md3Header_t *md3;
+ md3Frame_t *frame;
+ md3Surface_t *surf;
+ md3Triangle_t *tri;
+ md3St_t *st;
+ md3XyzNormal_t *xyz;
+ int version;
+ char filename[1024];
+ int len;
+
+ sprintf( filename, "%s%s", gamedir, mod_name );
+ len = TryLoadFile( filename, (void **)&md3 );
+#ifdef _WIN32
+ if ( len <= 0 ) {
+ len = PakLoadAnyFile(filename, (void **)&md3);
+ }
+#endif
+ if ( len <= 0 ) {
+ return NULL;
+ }
+
+ version = LittleLong (md3->version);
+ if (version != MD3_VERSION) {
+ _printf( "R_LoadMD3: %s has wrong version (%i should be %i)\n",
+ mod_name, version, MD3_VERSION);
+ return NULL;
+ }
+
+ LL(md3->ident);
+ LL(md3->version);
+ LL(md3->numFrames);
+ LL(md3->numTags);
+ LL(md3->numSurfaces);
+ LL(md3->numSkins);
+ LL(md3->ofsFrames);
+ LL(md3->ofsTags);
+ LL(md3->ofsSurfaces);
+ LL(md3->ofsEnd);
+
+ if ( md3->numFrames < 1 ) {
+ _printf( "R_LoadMD3: %s has no frames\n", mod_name );
+ return NULL;
+ }
+
+ // we don't need to swap tags in the renderer, they aren't used
+
+ // swap all the frames
+ frame = (md3Frame_t *) ( (byte *)md3 + md3->ofsFrames );
+ for ( i = 0 ; i < md3->numFrames ; i++, frame++) {
+ frame->radius = LittleFloat( frame->radius );
+ for ( j = 0 ; j < 3 ; j++ ) {
+ frame->bounds[0][j] = LittleFloat( frame->bounds[0][j] );
+ frame->bounds[1][j] = LittleFloat( frame->bounds[1][j] );
+ frame->localOrigin[j] = LittleFloat( frame->localOrigin[j] );
+ }
+ }
+
+ // swap all the surfaces
+ surf = (md3Surface_t *) ( (byte *)md3 + md3->ofsSurfaces );
+ for ( i = 0 ; i < md3->numSurfaces ; i++) {
+
+ LL(surf->ident);
+ LL(surf->flags);
+ LL(surf->numFrames);
+ LL(surf->numShaders);
+ LL(surf->numTriangles);
+ LL(surf->ofsTriangles);
+ LL(surf->numVerts);
+ LL(surf->ofsShaders);
+ LL(surf->ofsSt);
+ LL(surf->ofsXyzNormals);
+ LL(surf->ofsEnd);
+
+ if ( surf->numVerts > SHADER_MAX_VERTEXES ) {
+ Error ("R_LoadMD3: %s has more than %i verts on a surface (%i)",
+ mod_name, SHADER_MAX_VERTEXES, surf->numVerts );
+ }
+ if ( surf->numTriangles*3 > SHADER_MAX_INDEXES ) {
+ Error ("R_LoadMD3: %s has more than %i triangles on a surface (%i)",
+ mod_name, SHADER_MAX_INDEXES / 3, surf->numTriangles );
+ }
+
+ // swap all the triangles
+ tri = (md3Triangle_t *) ( (byte *)surf + surf->ofsTriangles );
+ for ( j = 0 ; j < surf->numTriangles ; j++, tri++ ) {
+ LL(tri->indexes[0]);
+ LL(tri->indexes[1]);
+ LL(tri->indexes[2]);
+ }
+
+ // swap all the ST
+ st = (md3St_t *) ( (byte *)surf + surf->ofsSt );
+ for ( j = 0 ; j < surf->numVerts ; j++, st++ ) {
+ st->st[0] = LittleFloat( st->st[0] );
+ st->st[1] = LittleFloat( st->st[1] );
+ }
+
+ // swap all the XyzNormals
+ xyz = (md3XyzNormal_t *) ( (byte *)surf + surf->ofsXyzNormals );
+ for ( j = 0 ; j < surf->numVerts * surf->numFrames ; j++, xyz++ )
+ {
+ xyz->xyz[0] = LittleShort( xyz->xyz[0] );
+ xyz->xyz[1] = LittleShort( xyz->xyz[1] );
+ xyz->xyz[2] = LittleShort( xyz->xyz[2] );
+
+ xyz->normal = LittleShort( xyz->normal );
+ }
+
+
+ // find the next surface
+ surf = (md3Surface_t *)( (byte *)surf + surf->ofsEnd );
+ }
+
+ return md3;
+}
+
+
+/*
+================
+LoadModel
+================
+*/
+md3Header_t *LoadModel( const char *modelName ) {
+ int i;
+ loadedModel_t *lm;
+
+ // see if we already have it loaded
+ for ( i = 0, lm = loadedModels ; i < numLoadedModels ; i++, lm++ ) {
+ if ( !strcmp( modelName, lm->modelName ) ) {
+ return lm->header;
+ }
+ }
+
+ // load it
+ if ( numLoadedModels == MAX_LOADED_MODELS ) {
+ Error( "MAX_LOADED_MODELS" );
+ }
+ numLoadedModels++;
+
+ strcpy( lm->modelName, modelName );
+
+ lm->header = R_LoadMD3( modelName );
+
+ return lm->header;
+}
+
+/*
+============
+InsertMD3Model
+
+Convert a model entity to raw geometry surfaces and insert it in the tree
+============
+*/
+void InsertMD3Model( const char *modelName, vec3_t origin, float angle, tree_t *tree ) {
+ int i, j;
+ md3Header_t *md3;
+ md3Surface_t *surf;
+ md3Shader_t *shader;
+ md3Triangle_t *tri;
+ md3St_t *st;
+ md3XyzNormal_t *xyz;
+ drawVert_t *outv;
+ float lat, lng;
+ float angleCos, angleSin;
+ mapDrawSurface_t *out;
+ vec3_t temp;
+
+ angle = angle / 180 * Q_PI;
+ angleCos = cos( angle );
+ angleSin = sin( angle );
+
+ // load the model
+ md3 = LoadModel( modelName );
+ if ( !md3 ) {
+ return;
+ }
+
+ // each md3 surface will become a new bsp surface
+
+ c_triangleModels++;
+ c_triangleSurfaces += md3->numSurfaces;
+
+ // expand, translate, and rotate the vertexes
+ // swap all the surfaces
+ surf = (md3Surface_t *) ( (byte *)md3 + md3->ofsSurfaces );
+ for ( i = 0 ; i < md3->numSurfaces ; i++) {
+ // allocate a surface
+ out = AllocDrawSurf();
+ out->miscModel = qtrue;
+
+ shader = (md3Shader_t *) ( (byte *)surf + surf->ofsShaders );
+
+ out->shaderInfo = ShaderInfoForShader( shader->name );
+
+ out->numVerts = surf->numVerts;
+ out->verts = malloc( out->numVerts * sizeof( out->verts[0] ) );
+
+ out->numIndexes = surf->numTriangles * 3;
+ out->indexes = malloc( out->numIndexes * sizeof( out->indexes[0] ) );
+
+ out->lightmapNum = -1;
+ out->fogNum = -1;
+
+ // emit the indexes
+ c_triangleIndexes += surf->numTriangles * 3;
+ tri = (md3Triangle_t *) ( (byte *)surf + surf->ofsTriangles );
+ for ( j = 0 ; j < surf->numTriangles ; j++, tri++ ) {
+ out->indexes[j*3+0] = tri->indexes[0];
+ out->indexes[j*3+1] = tri->indexes[1];
+ out->indexes[j*3+2] = tri->indexes[2];
+ }
+
+ // emit the vertexes
+ st = (md3St_t *) ( (byte *)surf + surf->ofsSt );
+ xyz = (md3XyzNormal_t *) ( (byte *)surf + surf->ofsXyzNormals );
+
+ c_triangleVertexes += surf->numVerts;
+ for ( j = 0 ; j < surf->numVerts ; j++, st++, xyz++ ) {
+ outv = &out->verts[ j ];
+
+ outv->st[0] = st->st[0];
+ outv->st[1] = st->st[1];
+
+ outv->lightmap[0] = 0;
+ outv->lightmap[1] = 0;
+
+ // the colors will be set by the lighting pass
+ outv->color[0] = 255;
+ outv->color[1] = 255;
+ outv->color[2] = 255;
+ outv->color[3] = 255;
+
+ outv->xyz[0] = origin[0] + MD3_XYZ_SCALE * ( xyz->xyz[0] * angleCos - xyz->xyz[1] * angleSin );
+ outv->xyz[1] = origin[1] + MD3_XYZ_SCALE * ( xyz->xyz[0] * angleSin + xyz->xyz[1] * angleCos );
+ outv->xyz[2] = origin[2] + MD3_XYZ_SCALE * ( xyz->xyz[2] );
+
+ // decode the lat/lng normal to a 3 float normal
+ lat = ( xyz->normal >> 8 ) & 0xff;
+ lng = ( xyz->normal & 0xff );
+ lat *= Q_PI/128;
+ lng *= Q_PI/128;
+
+ temp[0] = cos(lat) * sin(lng);
+ temp[1] = sin(lat) * sin(lng);
+ temp[2] = cos(lng);
+
+ // rotate the normal
+ outv->normal[0] = temp[0] * angleCos - temp[1] * angleSin;
+ outv->normal[1] = temp[0] * angleSin + temp[1] * angleCos;
+ outv->normal[2] = temp[2];
+ }
+
+ // find the next surface
+ surf = (md3Surface_t *)( (byte *)surf + surf->ofsEnd );
+ }
+
+}
+
+//==============================================================================
+
+
+/*
+============
+InsertASEModel
+
+Convert a model entity to raw geometry surfaces and insert it in the tree
+============
+*/
+void InsertASEModel( const char *modelName, vec3_t origin, float angle, tree_t *tree ) {
+ int i, j;
+ drawVert_t *outv;
+ float angleCos, angleSin;
+ mapDrawSurface_t *out;
+ int numSurfaces;
+ const char *name;
+ polyset_t *pset;
+ int numFrames;
+ char filename[1024];
+
+ sprintf( filename, "%s%s", gamedir, modelName );
+
+ angle = angle / 180 * Q_PI;
+ angleCos = cos( angle );
+ angleSin = sin( angle );
+
+ // load the model
+ ASE_Load( filename, qfalse, qfalse );
+
+ // each ase surface will become a new bsp surface
+ numSurfaces = ASE_GetNumSurfaces();
+
+ c_triangleModels++;
+ c_triangleSurfaces += numSurfaces;
+
+ // expand, translate, and rotate the vertexes
+ // swap all the surfaces
+ for ( i = 0 ; i < numSurfaces ; i++) {
+ name = ASE_GetSurfaceName( i );
+
+ pset = ASE_GetSurfaceAnimation( i, &numFrames, -1, -1, -1 );
+ if ( !name || !pset ) {
+ continue;
+ }
+
+ // allocate a surface
+ out = AllocDrawSurf();
+ out->miscModel = qtrue;
+
+ out->shaderInfo = ShaderInfoForShader( pset->materialname );
+
+ out->numVerts = 3 * pset->numtriangles;
+ out->verts = malloc( out->numVerts * sizeof( out->verts[0] ) );
+
+ out->numIndexes = 3 * pset->numtriangles;
+ out->indexes = malloc( out->numIndexes * sizeof( out->indexes[0] ) );
+
+ out->lightmapNum = -1;
+ out->fogNum = -1;
+
+ // emit the indexes
+ c_triangleIndexes += out->numIndexes;
+ for ( j = 0 ; j < out->numIndexes ; j++ ) {
+ out->indexes[j] = j;
+ }
+
+ // emit the vertexes
+ c_triangleVertexes += out->numVerts;
+ for ( j = 0 ; j < out->numVerts ; j++ ) {
+ int index;
+ triangle_t *tri;
+
+ index = j % 3;
+ tri = &pset->triangles[ j / 3 ];
+
+ outv = &out->verts[ j ];
+
+ outv->st[0] = tri->texcoords[index][0];
+ outv->st[1] = tri->texcoords[index][1];
+
+ outv->lightmap[0] = 0;
+ outv->lightmap[1] = 0;
+
+ // the colors will be set by the lighting pass
+ outv->color[0] = 255;
+ outv->color[1] = 255;
+ outv->color[2] = 255;
+ outv->color[3] = 255;
+
+ outv->xyz[0] = origin[0] + tri->verts[index][0];
+ outv->xyz[1] = origin[1] + tri->verts[index][1];
+ outv->xyz[2] = origin[2] + tri->verts[index][2];
+
+ // rotate the normal
+ outv->normal[0] = tri->normals[index][0];
+ outv->normal[1] = tri->normals[index][1];
+ outv->normal[2] = tri->normals[index][2];
+ }
+ }
+
+}
+
+
+//==============================================================================
+
+
+
+/*
+=====================
+AddTriangleModels
+=====================
+*/
+void AddTriangleModels( tree_t *tree ) {
+ int entity_num;
+ entity_t *entity;
+
+ qprintf("----- AddTriangleModels -----\n");
+
+ for ( entity_num=1 ; entity_num< num_entities ; entity_num++ ) {
+ entity = &entities[entity_num];
+
+ // convert misc_models into raw geometry
+ if ( !Q_stricmp( "misc_model", ValueForKey( entity, "classname" ) ) ) {
+ const char *model;
+ vec3_t origin;
+ float angle;
+
+ // get the angle for rotation FIXME: support full matrix positioning
+ angle = FloatForKey( entity, "angle" );
+
+ GetVectorForKey( entity, "origin", origin );
+
+ model = ValueForKey( entity, "model" );
+ if ( !model[0] ) {
+ _printf("WARNING: misc_model at %i %i %i without a model key\n", (int)origin[0],
+ (int)origin[1], (int)origin[2] );
+ continue;
+ }
+ if ( strstr( model, ".md3" ) || strstr( model, ".MD3" ) ) {
+ InsertMD3Model( model, origin, angle, tree );
+ continue;
+ }
+ if ( strstr( model, ".ase" ) || strstr( model, ".ASE" ) ) {
+ InsertASEModel( model, origin, angle, tree );
+ continue;
+ }
+ _printf( "Unknown misc_model type: %s\n", model );
+ continue;
+ }
+ }
+
+ qprintf( "%5i triangle models\n", c_triangleModels );
+ qprintf( "%5i triangle surfaces\n", c_triangleSurfaces );
+ qprintf( "%5i triangle vertexes\n", c_triangleVertexes );
+ qprintf( "%5i triangle indexes\n", c_triangleIndexes );
+}
+
diff --git a/q3map/nodraw.c b/q3map/nodraw.c
new file mode 100755
index 0000000..9931f27
--- /dev/null
+++ b/q3map/nodraw.c
@@ -0,0 +1,47 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+
+vec3_t draw_mins, draw_maxs;
+qboolean drawflag;
+
+void Draw_ClearWindow (void)
+{
+}
+
+//============================================================
+
+#define GLSERV_PORT 25001
+
+
+void GLS_BeginScene (void)
+{
+}
+
+void GLS_Winding (winding_t *w, int code)
+{
+}
+
+void GLS_EndScene (void)
+{
+}
diff --git a/q3map/patch.c b/q3map/patch.c
new file mode 100755
index 0000000..5dbd354
--- /dev/null
+++ b/q3map/patch.c
@@ -0,0 +1,286 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "qbsp.h"
+
+
+void PrintCtrl( vec3_t ctrl[9] ) {
+ int i, j;
+
+ for ( i = 0 ; i < 3 ; i++ ) {
+ for ( j = 0 ; j < 3 ; j++ ) {
+ _printf("(%5.2f %5.2f %5.2f) ", ctrl[i*3+j][0], ctrl[i*3+j][1], ctrl[i*3+j][2] );
+ }
+ _printf("\n");
+ }
+}
+
+/*
+================
+DrawSurfaceForMesh
+================
+*/
+mapDrawSurface_t *DrawSurfaceForMesh( mesh_t *m ) {
+ mapDrawSurface_t *ds;
+ int i, j;
+ mesh_t *copy;
+
+ // to make valid normals for patches with degenerate edges,
+ // we need to make a copy of the mesh and put the aproximating
+ // points onto the curve
+ copy = CopyMesh( m );
+ PutMeshOnCurve( *copy );
+ MakeMeshNormals( *copy );
+ for ( j = 0 ; j < m->width ; j++ ) {
+ for ( i = 0 ; i < m->height ; i++ ) {
+ VectorCopy( copy->verts[i*m->width+j].normal, m->verts[i*m->width+j].normal );
+ }
+ }
+ FreeMesh( copy );
+
+ ds = AllocDrawSurf();
+ ds->mapBrush = NULL;
+ ds->side = NULL;
+
+ ds->patch = qtrue;
+ ds->patchWidth = m->width;
+ ds->patchHeight = m->height;
+ ds->numVerts = ds->patchWidth * ds->patchHeight;
+ ds->verts = malloc( ds->numVerts * sizeof( *ds->verts ) );
+ memcpy( ds->verts, m->verts, ds->numVerts * sizeof( *ds->verts ) );
+
+ ds->lightmapNum = -1;
+ ds->fogNum = -1;
+
+ return ds;
+}
+
+/*
+=================
+ParsePatch
+
+Creates a mapDrawSurface_t from the patch text
+=================
+*/
+void ParsePatch( void ) {
+ vec_t info[5];
+ int i, j;
+ parseMesh_t *pm;
+ char texture[MAX_QPATH];
+ char shader[MAX_QPATH];
+ mesh_t m;
+ drawVert_t *verts;
+ epair_t *ep;
+
+ MatchToken( "{" );
+
+ // get texture
+ GetToken (qtrue);
+ strcpy( texture, token );
+
+ // save the shader name for retexturing
+ if ( numMapIndexedShaders == MAX_MAP_BRUSHSIDES ) {
+ Error( "MAX_MAP_BRUSHSIDES" );
+ }
+ strcpy( mapIndexedShaders[numMapIndexedShaders], texture );
+ numMapIndexedShaders++;
+
+
+ Parse1DMatrix( 5, info );
+ m.width = info[0];
+ m.height = info[1];
+ m.verts = verts = malloc( m.width * m.height * sizeof( m.verts[0] ) );
+
+ if ( m.width < 0 || m.width > MAX_PATCH_SIZE
+ || m.height < 0 || m.height > MAX_PATCH_SIZE ) {
+ Error("ParsePatch: bad size");
+ }
+
+ MatchToken( "(" );
+ for ( j = 0 ; j < m.width ; j++ ) {
+ MatchToken( "(" );
+ for ( i = 0 ; i < m.height ; i++ ) {
+ Parse1DMatrix( 5, verts[i*m.width+j].xyz );
+ }
+ MatchToken( ")" );
+ }
+ MatchToken( ")" );
+
+ // if brush primitives format, we may have some epairs to ignore here
+ GetToken(qtrue);
+ if (g_bBrushPrimit!=BPRIMIT_OLDBRUSHES && strcmp(token,"}"))
+ {
+ // NOTE: we leak that!
+ ep = ParseEpair();
+ }
+ else
+ UnGetToken();
+
+ MatchToken( "}" );
+ MatchToken( "}" );
+
+ if ( noCurveBrushes ) {
+ return;
+ }
+
+ // find default flags and values
+ pm = malloc( sizeof( *pm ) );
+ memset( pm, 0, sizeof( *pm ) );
+
+ sprintf( shader, "textures/%s", texture );
+ pm->shaderInfo = ShaderInfoForShader( shader );
+ pm->mesh = m;
+
+ // link to the entity
+ pm->next = mapent->patches;
+ mapent->patches = pm;
+}
+
+
+void GrowGroup_r( int patchNum, int patchCount, const byte *bordering, byte *group ) {
+ int i;
+ const byte *row;
+
+ if ( group[patchNum] ) {
+ return;
+ }
+ group[patchNum] = 1;
+ row = bordering + patchNum * patchCount;
+ for ( i = 0 ; i < patchCount ; i++ ) {
+ if ( row[i] ) {
+ GrowGroup_r( i, patchCount, bordering, group );
+ }
+ }
+}
+
+
+/*
+=====================
+PatchMapDrawSurfs
+
+Any patches that share an edge need to choose their
+level of detail as a unit, otherwise the edges would
+pull apart.
+=====================
+*/
+void PatchMapDrawSurfs( entity_t *e ) {
+ parseMesh_t *pm;
+ parseMesh_t *check, *scan;
+ mapDrawSurface_t *ds;
+ int patchCount, groupCount;
+ int i, j, k, l, c1, c2;
+ drawVert_t *v1, *v2;
+ vec3_t bounds[2];
+ byte *bordering;
+ parseMesh_t *meshes[MAX_MAP_DRAW_SURFS];
+ qboolean grouped[MAX_MAP_DRAW_SURFS];
+ byte group[MAX_MAP_DRAW_SURFS];
+
+ qprintf( "----- PatchMapDrawSurfs -----\n" );
+
+ patchCount = 0;
+ for ( pm = e->patches ; pm ; pm = pm->next ) {
+ meshes[patchCount] = pm;
+ patchCount++;
+ }
+
+ if ( !patchCount ) {
+ return;
+ }
+ bordering = malloc( patchCount * patchCount );
+ memset( bordering, 0, patchCount * patchCount );
+
+ // build the bordering matrix
+ for ( k = 0 ; k < patchCount ; k++ ) {
+ bordering[k*patchCount+k] = 1;
+
+ for ( l = k+1 ; l < patchCount ; l++ ) {
+ check = meshes[k];
+ scan = meshes[l];
+ c1 = scan->mesh.width * scan->mesh.height;
+ v1 = scan->mesh.verts;
+
+ for ( i = 0 ; i < c1 ; i++, v1++ ) {
+ c2 = check->mesh.width * check->mesh.height;
+ v2 = check->mesh.verts;
+ for ( j = 0 ; j < c2 ; j++, v2++ ) {
+ if ( fabs( v1->xyz[0] - v2->xyz[0] ) < 1.0
+ && fabs( v1->xyz[1] - v2->xyz[1] ) < 1.0
+ && fabs( v1->xyz[2] - v2->xyz[2] ) < 1.0 ) {
+ break;
+ }
+ }
+ if ( j != c2 ) {
+ break;
+ }
+ }
+ if ( i != c1 ) {
+ // we have a connection
+ bordering[k*patchCount+l] =
+ bordering[l*patchCount+k] = 1;
+ } else {
+ // no connection
+ bordering[k*patchCount+l] =
+ bordering[l*patchCount+k] = 0;
+ }
+
+ }
+ }
+
+ // build groups
+ memset( grouped, 0, sizeof(grouped) );
+ groupCount = 0;
+ for ( i = 0 ; i < patchCount ; i++ ) {
+ if ( !grouped[i] ) {
+ groupCount++;
+ }
+
+ // recursively find all patches that belong in the same group
+ memset( group, 0, patchCount );
+ GrowGroup_r( i, patchCount, bordering, group );
+
+ // bound them
+ ClearBounds( bounds[0], bounds[1] );
+ for ( j = 0 ; j < patchCount ; j++ ) {
+ if ( group[j] ) {
+ grouped[j] = qtrue;
+ scan = meshes[j];
+ c1 = scan->mesh.width * scan->mesh.height;
+ v1 = scan->mesh.verts;
+ for ( k = 0 ; k < c1 ; k++, v1++ ) {
+ AddPointToBounds( v1->xyz, bounds[0], bounds[1] );
+ }
+ }
+ }
+
+ // create drawsurf
+ scan = meshes[i];
+ scan->grouped = qtrue;
+ ds = DrawSurfaceForMesh( &scan->mesh );
+ ds->shaderInfo = scan->shaderInfo;
+ VectorCopy( bounds[0], ds->lightmapVecs[0] );
+ VectorCopy( bounds[1], ds->lightmapVecs[1] );
+ }
+
+ qprintf( "%5i patches\n", patchCount );
+ qprintf( "%5i patch LOD groups\n", groupCount );
+}
+
diff --git a/q3map/portals.c b/q3map/portals.c
new file mode 100755
index 0000000..dee708f
--- /dev/null
+++ b/q3map/portals.c
@@ -0,0 +1,843 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+
+
+int c_active_portals;
+int c_peak_portals;
+int c_boundary;
+int c_boundary_sides;
+
+/*
+===========
+AllocPortal
+===========
+*/
+portal_t *AllocPortal (void)
+{
+ portal_t *p;
+
+ if (numthreads == 1)
+ c_active_portals++;
+ if (c_active_portals > c_peak_portals)
+ c_peak_portals = c_active_portals;
+
+ p = malloc (sizeof(portal_t));
+ memset (p, 0, sizeof(portal_t));
+
+ return p;
+}
+
+void FreePortal (portal_t *p)
+{
+ if (p->winding)
+ FreeWinding (p->winding);
+ if (numthreads == 1)
+ c_active_portals--;
+ free (p);
+}
+
+//==============================================================
+
+/*
+=============
+Portal_Passable
+
+Returns true if the portal has non-opaque leafs on both sides
+=============
+*/
+qboolean Portal_Passable(portal_t *p) {
+ if (!p->onnode) {
+ return qfalse; // to global outsideleaf
+ }
+
+ if (p->nodes[0]->planenum != PLANENUM_LEAF
+ || p->nodes[1]->planenum != PLANENUM_LEAF) {
+ Error ("Portal_EntityFlood: not a leaf");
+ }
+
+ if ( !p->nodes[0]->opaque && !p->nodes[1]->opaque ) {
+ return qtrue;
+ }
+
+ return qfalse;
+}
+
+
+//=============================================================================
+
+int c_tinyportals;
+
+/*
+=============
+AddPortalToNodes
+=============
+*/
+void AddPortalToNodes (portal_t *p, node_t *front, node_t *back)
+{
+ if (p->nodes[0] || p->nodes[1])
+ Error ("AddPortalToNode: allready included");
+
+ p->nodes[0] = front;
+ p->next[0] = front->portals;
+ front->portals = p;
+
+ p->nodes[1] = back;
+ p->next[1] = back->portals;
+ back->portals = p;
+}
+
+
+/*
+=============
+RemovePortalFromNode
+=============
+*/
+void RemovePortalFromNode (portal_t *portal, node_t *l)
+{
+ portal_t **pp, *t;
+
+// remove reference to the current portal
+ pp = &l->portals;
+ while (1)
+ {
+ t = *pp;
+ if (!t)
+ Error ("RemovePortalFromNode: portal not in leaf");
+
+ if ( t == portal )
+ break;
+
+ if (t->nodes[0] == l)
+ pp = &t->next[0];
+ else if (t->nodes[1] == l)
+ pp = &t->next[1];
+ else
+ Error ("RemovePortalFromNode: portal not bounding leaf");
+ }
+
+ if (portal->nodes[0] == l)
+ {
+ *pp = portal->next[0];
+ portal->nodes[0] = NULL;
+ }
+ else if (portal->nodes[1] == l)
+ {
+ *pp = portal->next[1];
+ portal->nodes[1] = NULL;
+ }
+}
+
+//============================================================================
+
+void PrintPortal (portal_t *p)
+{
+ int i;
+ winding_t *w;
+
+ w = p->winding;
+ for (i=0 ; i<w->numpoints ; i++)
+ _printf ("(%5.0f,%5.0f,%5.0f)\n",w->p[i][0]
+ , w->p[i][1], w->p[i][2]);
+}
+
+/*
+================
+MakeHeadnodePortals
+
+The created portals will face the global outside_node
+================
+*/
+#define SIDESPACE 8
+void MakeHeadnodePortals (tree_t *tree)
+{
+ vec3_t bounds[2];
+ int i, j, n;
+ portal_t *p, *portals[6];
+ plane_t bplanes[6], *pl;
+ node_t *node;
+
+ node = tree->headnode;
+
+// pad with some space so there will never be null volume leafs
+ for (i=0 ; i<3 ; i++)
+ {
+ bounds[0][i] = tree->mins[i] - SIDESPACE;
+ bounds[1][i] = tree->maxs[i] + SIDESPACE;
+ if ( bounds[0][i] >= bounds[1][i] ) {
+ Error( "Backwards tree volume" );
+ }
+ }
+
+ tree->outside_node.planenum = PLANENUM_LEAF;
+ tree->outside_node.brushlist = NULL;
+ tree->outside_node.portals = NULL;
+ tree->outside_node.opaque = qfalse;
+
+ for (i=0 ; i<3 ; i++)
+ for (j=0 ; j<2 ; j++)
+ {
+ n = j*3 + i;
+
+ p = AllocPortal ();
+ portals[n] = p;
+
+ pl = &bplanes[n];
+ memset (pl, 0, sizeof(*pl));
+ if (j)
+ {
+ pl->normal[i] = -1;
+ pl->dist = -bounds[j][i];
+ }
+ else
+ {
+ pl->normal[i] = 1;
+ pl->dist = bounds[j][i];
+ }
+ p->plane = *pl;
+ p->winding = BaseWindingForPlane (pl->normal, pl->dist);
+ AddPortalToNodes (p, node, &tree->outside_node);
+ }
+
+// clip the basewindings by all the other planes
+ for (i=0 ; i<6 ; i++)
+ {
+ for (j=0 ; j<6 ; j++)
+ {
+ if (j == i)
+ continue;
+ ChopWindingInPlace (&portals[i]->winding, bplanes[j].normal, bplanes[j].dist, ON_EPSILON);
+ }
+ }
+}
+
+//===================================================
+
+
+/*
+================
+BaseWindingForNode
+================
+*/
+#define BASE_WINDING_EPSILON 0.001
+#define SPLIT_WINDING_EPSILON 0.001
+
+winding_t *BaseWindingForNode (node_t *node)
+{
+ winding_t *w;
+ node_t *n;
+ plane_t *plane;
+ vec3_t normal;
+ vec_t dist;
+
+ w = BaseWindingForPlane (mapplanes[node->planenum].normal
+ , mapplanes[node->planenum].dist);
+
+ // clip by all the parents
+ for (n=node->parent ; n && w ; )
+ {
+ plane = &mapplanes[n->planenum];
+
+ if (n->children[0] == node)
+ { // take front
+ ChopWindingInPlace (&w, plane->normal, plane->dist, BASE_WINDING_EPSILON);
+ }
+ else
+ { // take back
+ VectorSubtract (vec3_origin, plane->normal, normal);
+ dist = -plane->dist;
+ ChopWindingInPlace (&w, normal, dist, BASE_WINDING_EPSILON);
+ }
+ node = n;
+ n = n->parent;
+ }
+
+ return w;
+}
+
+//============================================================
+
+/*
+==================
+MakeNodePortal
+
+create the new portal by taking the full plane winding for the cutting plane
+and clipping it by all of parents of this node
+==================
+*/
+void MakeNodePortal (node_t *node)
+{
+ portal_t *new_portal, *p;
+ winding_t *w;
+ vec3_t normal;
+ float dist;
+ int side;
+
+ w = BaseWindingForNode (node);
+
+ // clip the portal by all the other portals in the node
+ for (p = node->portals ; p && w; p = p->next[side])
+ {
+ if (p->nodes[0] == node)
+ {
+ side = 0;
+ VectorCopy (p->plane.normal, normal);
+ dist = p->plane.dist;
+ }
+ else if (p->nodes[1] == node)
+ {
+ side = 1;
+ VectorSubtract (vec3_origin, p->plane.normal, normal);
+ dist = -p->plane.dist;
+ }
+ else
+ Error ("CutNodePortals_r: mislinked portal");
+
+ ChopWindingInPlace (&w, normal, dist, CLIP_EPSILON);
+ }
+
+ if (!w)
+ {
+ return;
+ }
+
+ if (WindingIsTiny (w))
+ {
+ c_tinyportals++;
+ FreeWinding (w);
+ return;
+ }
+
+ new_portal = AllocPortal ();
+ new_portal->plane = mapplanes[node->planenum];
+ new_portal->onnode = node;
+ new_portal->winding = w;
+ new_portal->hint = node->hint;
+ AddPortalToNodes (new_portal, node->children[0], node->children[1]);
+}
+
+
+/*
+==============
+SplitNodePortals
+
+Move or split the portals that bound node so that the node's
+children have portals instead of node.
+==============
+*/
+void SplitNodePortals (node_t *node)
+{
+ portal_t *p, *next_portal, *new_portal;
+ node_t *f, *b, *other_node;
+ int side;
+ plane_t *plane;
+ winding_t *frontwinding, *backwinding;
+
+ plane = &mapplanes[node->planenum];
+ f = node->children[0];
+ b = node->children[1];
+
+ for (p = node->portals ; p ; p = next_portal)
+ {
+ if (p->nodes[0] == node)
+ side = 0;
+ else if (p->nodes[1] == node)
+ side = 1;
+ else
+ Error ("SplitNodePortals: mislinked portal");
+ next_portal = p->next[side];
+
+ other_node = p->nodes[!side];
+ RemovePortalFromNode (p, p->nodes[0]);
+ RemovePortalFromNode (p, p->nodes[1]);
+
+//
+// cut the portal into two portals, one on each side of the cut plane
+//
+ ClipWindingEpsilon (p->winding, plane->normal, plane->dist,
+ SPLIT_WINDING_EPSILON, &frontwinding, &backwinding);
+
+ if (frontwinding && WindingIsTiny(frontwinding))
+ {
+ if (!f->tinyportals)
+ VectorCopy(frontwinding->p[0], f->referencepoint);
+ f->tinyportals++;
+ if (!other_node->tinyportals)
+ VectorCopy(frontwinding->p[0], other_node->referencepoint);
+ other_node->tinyportals++;
+
+ FreeWinding (frontwinding);
+ frontwinding = NULL;
+ c_tinyportals++;
+ }
+
+ if (backwinding && WindingIsTiny(backwinding))
+ {
+ if (!b->tinyportals)
+ VectorCopy(backwinding->p[0], b->referencepoint);
+ b->tinyportals++;
+ if (!other_node->tinyportals)
+ VectorCopy(backwinding->p[0], other_node->referencepoint);
+ other_node->tinyportals++;
+
+ FreeWinding (backwinding);
+ backwinding = NULL;
+ c_tinyportals++;
+ }
+
+ if (!frontwinding && !backwinding)
+ { // tiny windings on both sides
+ continue;
+ }
+
+ if (!frontwinding)
+ {
+ FreeWinding (backwinding);
+ if (side == 0)
+ AddPortalToNodes (p, b, other_node);
+ else
+ AddPortalToNodes (p, other_node, b);
+ continue;
+ }
+ if (!backwinding)
+ {
+ FreeWinding (frontwinding);
+ if (side == 0)
+ AddPortalToNodes (p, f, other_node);
+ else
+ AddPortalToNodes (p, other_node, f);
+ continue;
+ }
+
+ // the winding is split
+ new_portal = AllocPortal ();
+ *new_portal = *p;
+ new_portal->winding = backwinding;
+ FreeWinding (p->winding);
+ p->winding = frontwinding;
+
+ if (side == 0)
+ {
+ AddPortalToNodes (p, f, other_node);
+ AddPortalToNodes (new_portal, b, other_node);
+ }
+ else
+ {
+ AddPortalToNodes (p, other_node, f);
+ AddPortalToNodes (new_portal, other_node, b);
+ }
+ }
+
+ node->portals = NULL;
+}
+
+
+/*
+================
+CalcNodeBounds
+================
+*/
+void CalcNodeBounds (node_t *node)
+{
+ portal_t *p;
+ int s;
+ int i;
+
+ // calc mins/maxs for both leafs and nodes
+ ClearBounds (node->mins, node->maxs);
+ for (p = node->portals ; p ; p = p->next[s])
+ {
+ s = (p->nodes[1] == node);
+ for (i=0 ; i<p->winding->numpoints ; i++)
+ AddPointToBounds (p->winding->p[i], node->mins, node->maxs);
+ }
+}
+
+/*
+==================
+MakeTreePortals_r
+==================
+*/
+void MakeTreePortals_r (node_t *node)
+{
+ int i;
+
+ CalcNodeBounds (node);
+ if (node->mins[0] >= node->maxs[0])
+ {
+ _printf ("WARNING: node without a volume\n");
+ _printf("node has %d tiny portals\n", node->tinyportals);
+ _printf("node reference point %1.2f %1.2f %1.2f\n", node->referencepoint[0],
+ node->referencepoint[1],
+ node->referencepoint[2]);
+ }
+
+ for (i=0 ; i<3 ; i++)
+ {
+ if (node->mins[i] < MIN_WORLD_COORD || node->maxs[i] > MAX_WORLD_COORD)
+ {
+ _printf ("WARNING: node with unbounded volume\n");
+ break;
+ }
+ }
+ if (node->planenum == PLANENUM_LEAF)
+ return;
+
+ MakeNodePortal (node);
+ SplitNodePortals (node);
+
+ MakeTreePortals_r (node->children[0]);
+ MakeTreePortals_r (node->children[1]);
+}
+
+/*
+==================
+MakeTreePortals
+==================
+*/
+void MakeTreePortals (tree_t *tree)
+{
+ qprintf( "----- MakeTreePortals -----\n");
+ MakeHeadnodePortals (tree);
+ MakeTreePortals_r (tree->headnode);
+ qprintf("%6d tiny portals\n", c_tinyportals);
+}
+
+/*
+=========================================================
+
+FLOOD ENTITIES
+
+=========================================================
+*/
+
+int c_floodedleafs;
+
+/*
+=============
+FloodPortals_r
+=============
+*/
+void FloodPortals_r (node_t *node, int dist) {
+ portal_t *p;
+ int s;
+
+ if ( node->occupied ) {
+ return;
+ }
+
+ if ( node->opaque ) {
+ return;
+ }
+
+ c_floodedleafs++;
+ node->occupied = dist;
+
+ for (p=node->portals ; p ; p = p->next[s]) {
+ s = (p->nodes[1] == node);
+ FloodPortals_r (p->nodes[!s], dist+1);
+ }
+}
+
+/*
+=============
+PlaceOccupant
+=============
+*/
+qboolean PlaceOccupant (node_t *headnode, vec3_t origin, entity_t *occupant)
+{
+ node_t *node;
+ vec_t d;
+ plane_t *plane;
+
+ // find the leaf to start in
+ node = headnode;
+ while (node->planenum != PLANENUM_LEAF)
+ {
+ plane = &mapplanes[node->planenum];
+ d = DotProduct (origin, plane->normal) - plane->dist;
+ if (d >= 0)
+ node = node->children[0];
+ else
+ node = node->children[1];
+ }
+
+ if ( node->opaque )
+ return qfalse;
+ node->occupant = occupant;
+
+ FloodPortals_r (node, 1);
+
+ return qtrue;
+}
+
+/*
+=============
+FloodEntities
+
+Marks all nodes that can be reached by entites
+=============
+*/
+qboolean FloodEntities( tree_t *tree ) {
+ int i;
+ vec3_t origin;
+ const char *cl;
+ qboolean inside;
+ node_t *headnode;
+
+ headnode = tree->headnode;
+ qprintf ("--- FloodEntities ---\n");
+ inside = qfalse;
+ tree->outside_node.occupied = 0;
+
+ c_floodedleafs = 0;
+ for (i=1 ; i<num_entities ; i++)
+ {
+ GetVectorForKey (&entities[i], "origin", origin);
+ if (VectorCompare(origin, vec3_origin))
+ continue;
+
+ cl = ValueForKey (&entities[i], "classname");
+
+ origin[2] += 1; // so objects on floor are ok
+
+ if (PlaceOccupant (headnode, origin, &entities[i]))
+ inside = qtrue;
+ }
+
+ qprintf("%5i flooded leafs\n", c_floodedleafs );
+
+ if (!inside)
+ {
+ qprintf ("no entities in open -- no filling\n");
+ }
+ else if (tree->outside_node.occupied)
+ {
+ qprintf ("entity reached from outside -- no filling\n");
+ }
+
+ return (qboolean)(inside && !tree->outside_node.occupied);
+}
+
+/*
+=========================================================
+
+FLOOD AREAS
+
+=========================================================
+*/
+
+int c_areas;
+
+/*
+=============
+FloodAreas_r
+=============
+*/
+void FloodAreas_r (node_t *node)
+{
+ portal_t *p;
+ int s;
+ bspbrush_t *b;
+
+ if ( node->areaportal ) {
+ //
+ if ( node->area == -1 ) {
+ node->area = c_areas;
+ }
+ // this node is part of an area portal brush
+ b = node->brushlist->original;
+
+ // if the current area has allready touched this
+ // portal, we are done
+ if (b->portalareas[0] == c_areas || b->portalareas[1] == c_areas)
+ return;
+
+ // note the current area as bounding the portal
+ if (b->portalareas[1] != -1)
+ {
+ _printf ("WARNING: areaportal brush %i touches > 2 areas\n", b->brushnum );
+ return;
+ }
+ if (b->portalareas[0] != -1) {
+ b->portalareas[1] = c_areas;
+ } else {
+ b->portalareas[0] = c_areas;
+ }
+
+ return;
+ }
+
+ if (node->area != -1) {
+ return; // allready got it
+ }
+ if ( node->cluster == -1 ) {
+ return;
+ }
+
+ node->area = c_areas;
+
+ for (p=node->portals ; p ; p = p->next[s])
+ {
+ s = (p->nodes[1] == node);
+
+ if ( !Portal_Passable(p) )
+ continue;
+
+ FloodAreas_r (p->nodes[!s]);
+ }
+}
+
+
+/*
+=============
+FindAreas_r
+
+Just decend the tree, and for each node that hasn't had an
+area set, flood fill out from there
+=============
+*/
+void FindAreas_r (node_t *node)
+{
+ if (node->planenum != PLANENUM_LEAF)
+ {
+ FindAreas_r (node->children[0]);
+ FindAreas_r (node->children[1]);
+ return;
+ }
+
+ if (node->opaque)
+ return;
+
+ if (node->areaportal)
+ return;
+
+ if (node->area != -1)
+ return; // allready got it
+
+ FloodAreas_r (node);
+ c_areas++;
+}
+
+/*
+=============
+CheckAreas_r
+=============
+*/
+void CheckAreas_r (node_t *node)
+{
+ bspbrush_t *b;
+
+ if (node->planenum != PLANENUM_LEAF)
+ {
+ CheckAreas_r (node->children[0]);
+ CheckAreas_r (node->children[1]);
+ return;
+ }
+
+ if (node->opaque)
+ return;
+
+ if (node->cluster != -1)
+ if (node->area == -1)
+ _printf("WARNING: cluster %d has area set to -1\n", node->cluster);
+ if (node->areaportal)
+ {
+ b = node->brushlist->original;
+
+ // check if the areaportal touches two areas
+ if (b->portalareas[0] == -1 || b->portalareas[1] == -1)
+ _printf ("WARNING: areaportal brush %i doesn't touch two areas\n", b->brushnum);
+ }
+}
+
+/*
+=============
+FloodAreas
+
+Mark each leaf with an area, bounded by CONTENTS_AREAPORTAL
+=============
+*/
+void FloodAreas (tree_t *tree)
+{
+ qprintf ("--- FloodAreas ---\n");
+ FindAreas_r( tree->headnode );
+
+ // check for areaportal brushes that don't touch two areas
+ CheckAreas_r( tree->headnode );
+
+ qprintf ("%5i areas\n", c_areas);
+}
+
+//======================================================
+
+int c_outside;
+int c_inside;
+int c_solid;
+
+void FillOutside_r (node_t *node)
+{
+ if (node->planenum != PLANENUM_LEAF)
+ {
+ FillOutside_r (node->children[0]);
+ FillOutside_r (node->children[1]);
+ return;
+ }
+
+ // anything not reachable by an entity
+ // can be filled away
+ if (!node->occupied) {
+ if ( !node->opaque ) {
+ c_outside++;
+ node->opaque = qtrue;
+ } else {
+ c_solid++;
+ }
+ } else {
+ c_inside++;
+ }
+
+}
+
+/*
+=============
+FillOutside
+
+Fill all nodes that can't be reached by entities
+=============
+*/
+void FillOutside (node_t *headnode)
+{
+ c_outside = 0;
+ c_inside = 0;
+ c_solid = 0;
+ qprintf ("--- FillOutside ---\n");
+ FillOutside_r (headnode);
+ qprintf ("%5i solid leafs\n", c_solid);
+ qprintf ("%5i leafs filled\n", c_outside);
+ qprintf ("%5i inside leafs\n", c_inside);
+}
+
+
+//==============================================================
+
diff --git a/q3map/prtfile.c b/q3map/prtfile.c
new file mode 100755
index 0000000..902ae05
--- /dev/null
+++ b/q3map/prtfile.c
@@ -0,0 +1,272 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+
+/*
+==============================================================================
+
+PORTAL FILE GENERATION
+
+Save out name.prt for qvis to read
+==============================================================================
+*/
+
+
+#define PORTALFILE "PRT1"
+
+FILE *pf;
+int num_visclusters; // clusters the player can be in
+int num_visportals;
+int num_solidfaces;
+
+void WriteFloat (FILE *f, vec_t v)
+{
+ if ( fabs(v - Q_rint(v)) < 0.001 )
+ fprintf (f,"%i ",(int)Q_rint(v));
+ else
+ fprintf (f,"%f ",v);
+}
+
+/*
+=================
+WritePortalFile_r
+=================
+*/
+void WritePortalFile_r (node_t *node)
+{
+ int i, s;
+ portal_t *p;
+ winding_t *w;
+ vec3_t normal;
+ vec_t dist;
+
+ // decision node
+ if (node->planenum != PLANENUM_LEAF) {
+ WritePortalFile_r (node->children[0]);
+ WritePortalFile_r (node->children[1]);
+ return;
+ }
+
+ if (node->opaque) {
+ return;
+ }
+
+ for (p = node->portals ; p ; p=p->next[s])
+ {
+ w = p->winding;
+ s = (p->nodes[1] == node);
+ if (w && p->nodes[0] == node)
+ {
+ if (!Portal_Passable(p))
+ continue;
+ // write out to the file
+
+ // sometimes planes get turned around when they are very near
+ // the changeover point between different axis. interpret the
+ // plane the same way vis will, and flip the side orders if needed
+ // FIXME: is this still relevent?
+ WindingPlane (w, normal, &dist);
+ if ( DotProduct (p->plane.normal, normal) < 0.99 )
+ { // backwards...
+ fprintf (pf,"%i %i %i ",w->numpoints, p->nodes[1]->cluster, p->nodes[0]->cluster);
+ }
+ else
+ fprintf (pf,"%i %i %i ",w->numpoints, p->nodes[0]->cluster, p->nodes[1]->cluster);
+ if (p->hint)
+ fprintf (pf, "1 ");
+ else
+ fprintf (pf, "0 ");
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ fprintf (pf,"(");
+ WriteFloat (pf, w->p[i][0]);
+ WriteFloat (pf, w->p[i][1]);
+ WriteFloat (pf, w->p[i][2]);
+ fprintf (pf,") ");
+ }
+ fprintf (pf,"\n");
+ }
+ }
+
+}
+
+/*
+=================
+WriteFaceFile_r
+=================
+*/
+void WriteFaceFile_r (node_t *node)
+{
+ int i, s;
+ portal_t *p;
+ winding_t *w;
+
+ // decision node
+ if (node->planenum != PLANENUM_LEAF) {
+ WriteFaceFile_r (node->children[0]);
+ WriteFaceFile_r (node->children[1]);
+ return;
+ }
+
+ if (node->opaque) {
+ return;
+ }
+
+ for (p = node->portals ; p ; p=p->next[s])
+ {
+ w = p->winding;
+ s = (p->nodes[1] == node);
+ if (w)
+ {
+ if (Portal_Passable(p))
+ continue;
+ // write out to the file
+
+ if (p->nodes[0] == node)
+ {
+ fprintf (pf,"%i %i ",w->numpoints, p->nodes[0]->cluster);
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ fprintf (pf,"(");
+ WriteFloat (pf, w->p[i][0]);
+ WriteFloat (pf, w->p[i][1]);
+ WriteFloat (pf, w->p[i][2]);
+ fprintf (pf,") ");
+ }
+ fprintf (pf,"\n");
+ }
+ else
+ {
+ fprintf (pf,"%i %i ",w->numpoints, p->nodes[1]->cluster);
+ for (i = w->numpoints-1; i >= 0; i--)
+ {
+ fprintf (pf,"(");
+ WriteFloat (pf, w->p[i][0]);
+ WriteFloat (pf, w->p[i][1]);
+ WriteFloat (pf, w->p[i][2]);
+ fprintf (pf,") ");
+ }
+ fprintf (pf,"\n");
+ }
+ }
+ }
+}
+
+/*
+================
+NumberLeafs_r
+================
+*/
+void NumberLeafs_r (node_t *node)
+{
+ portal_t *p;
+
+ if ( node->planenum != PLANENUM_LEAF ) {
+ // decision node
+ node->cluster = -99;
+ NumberLeafs_r (node->children[0]);
+ NumberLeafs_r (node->children[1]);
+ return;
+ }
+
+ node->area = -1;
+
+ if ( node->opaque ) {
+ // solid block, viewpoint never inside
+ node->cluster = -1;
+ return;
+ }
+
+ node->cluster = num_visclusters;
+ num_visclusters++;
+
+ // count the portals
+ for (p = node->portals ; p ; )
+ {
+ if (p->nodes[0] == node) // only write out from first leaf
+ {
+ if (Portal_Passable(p))
+ num_visportals++;
+ else
+ num_solidfaces++;
+ p = p->next[0];
+ }
+ else
+ {
+ if (!Portal_Passable(p))
+ num_solidfaces++;
+ p = p->next[1];
+ }
+ }
+}
+
+
+/*
+================
+NumberClusters
+================
+*/
+void NumberClusters(tree_t *tree) {
+ num_visclusters = 0;
+ num_visportals = 0;
+ num_solidfaces = 0;
+
+ qprintf ("--- NumberClusters ---\n");
+
+ // set the cluster field in every leaf and count the total number of portals
+ NumberLeafs_r (tree->headnode);
+
+ qprintf ("%5i visclusters\n", num_visclusters);
+ qprintf ("%5i visportals\n", num_visportals);
+ qprintf ("%5i solidfaces\n", num_solidfaces);
+}
+
+/*
+================
+WritePortalFile
+================
+*/
+void WritePortalFile (tree_t *tree)
+{
+ char filename[1024];
+
+ qprintf ("--- WritePortalFile ---\n");
+
+ // write the file
+ sprintf (filename, "%s.prt", source);
+ _printf ("writing %s\n", filename);
+ pf = fopen (filename, "w");
+ if (!pf)
+ Error ("Error opening %s", filename);
+
+ fprintf (pf, "%s\n", PORTALFILE);
+ fprintf (pf, "%i\n", num_visclusters);
+ fprintf (pf, "%i\n", num_visportals);
+ fprintf (pf, "%i\n", num_solidfaces);
+
+ WritePortalFile_r(tree->headnode);
+ WriteFaceFile_r(tree->headnode);
+
+ fclose (pf);
+}
+
diff --git a/q3map/q3map.sln b/q3map/q3map.sln
new file mode 100755
index 0000000..6e4bb3c
--- /dev/null
+++ b/q3map/q3map.sln
@@ -0,0 +1,56 @@
+Microsoft Visual Studio Solution File, Format Version 8.00
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "jpeg6", "..\libs\jpeg6\jpeg6.vcproj", "{A862AD26-94DD-4618-A814-F6AACA0B2FE3}"
+ ProjectSection(ProjectDependencies) = postProject
+ EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pak", "..\libs\pak\pak.vcproj", "{F2ACC9D7-D628-4624-864F-87FE58787625}"
+ ProjectSection(ProjectDependencies) = postProject
+ EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "q3map", "q3map.vcproj", "{F1162C55-66E7-4486-B1F3-071CFAA78332}"
+ ProjectSection(ProjectDependencies) = postProject
+ {F2ACC9D7-D628-4624-864F-87FE58787625} = {F2ACC9D7-D628-4624-864F-87FE58787625}
+ {A862AD26-94DD-4618-A814-F6AACA0B2FE3} = {A862AD26-94DD-4618-A814-F6AACA0B2FE3}
+ EndProjectSection
+EndProject
+Global
+ GlobalSection(SourceCodeControl) = preSolution
+ SccNumberOfProjects = 3
+ SccProjectUniqueName0 = ..\\libs\\jpeg6\\jpeg6.vcproj
+ SccProjectName0 = \u0022$/source/q3radiant\u0022,\u0020FEFAAAAA
+ SccLocalPath0 = ..\\q3radiant
+ SccProvider0 = MSSCCI:Perforce\u0020SCM
+ SccProjectFilePathRelativizedFromConnection0 = ..\\libs\\jpeg6\\
+ SccProjectUniqueName1 = ..\\libs\\pak\\pak.vcproj
+ SccProjectName1 = \u0022$/source/q3radiant\u0022,\u0020FEFAAAAA
+ SccLocalPath1 = ..\\q3radiant
+ SccProvider1 = MSSCCI:Perforce\u0020SCM
+ SccProjectFilePathRelativizedFromConnection1 = ..\\libs\\pak\\
+ SccProjectUniqueName2 = q3map.vcproj
+ SccProjectName2 = \u0022$/source/q3map\u0022,\u0020PADAAAAA
+ SccLocalPath2 = .
+ SccProvider2 = MSSCCI:Perforce\u0020SCM
+ EndGlobalSection
+ GlobalSection(SolutionConfiguration) = preSolution
+ Debug = Debug
+ Release = Release
+ EndGlobalSection
+ GlobalSection(ProjectConfiguration) = postSolution
+ {A862AD26-94DD-4618-A814-F6AACA0B2FE3}.Debug.ActiveCfg = Debug|Win32
+ {A862AD26-94DD-4618-A814-F6AACA0B2FE3}.Debug.Build.0 = Debug|Win32
+ {A862AD26-94DD-4618-A814-F6AACA0B2FE3}.Release.ActiveCfg = Release|Win32
+ {A862AD26-94DD-4618-A814-F6AACA0B2FE3}.Release.Build.0 = Release|Win32
+ {F2ACC9D7-D628-4624-864F-87FE58787625}.Debug.ActiveCfg = Debug|Win32
+ {F2ACC9D7-D628-4624-864F-87FE58787625}.Debug.Build.0 = Debug|Win32
+ {F2ACC9D7-D628-4624-864F-87FE58787625}.Release.ActiveCfg = Release|Win32
+ {F2ACC9D7-D628-4624-864F-87FE58787625}.Release.Build.0 = Release|Win32
+ {F1162C55-66E7-4486-B1F3-071CFAA78332}.Debug.ActiveCfg = Debug|Win32
+ {F1162C55-66E7-4486-B1F3-071CFAA78332}.Debug.Build.0 = Debug|Win32
+ {F1162C55-66E7-4486-B1F3-071CFAA78332}.Release.ActiveCfg = Release|Win32
+ {F1162C55-66E7-4486-B1F3-071CFAA78332}.Release.Build.0 = Release|Win32
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ EndGlobalSection
+ GlobalSection(ExtensibilityAddIns) = postSolution
+ EndGlobalSection
+EndGlobal
diff --git a/q3map/q3map.vcproj b/q3map/q3map.vcproj
new file mode 100755
index 0000000..64ad4f8
--- /dev/null
+++ b/q3map/q3map.vcproj
@@ -0,0 +1,1606 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+ ProjectType="Visual C++"
+ Version="7.10"
+ Name="q3map"
+ SccProjectName="&quot;$/source/q3map&quot;, PADAAAAA"
+ SccLocalPath=".">
+ <Platforms>
+ <Platform
+ Name="Win32"/>
+ </Platforms>
+ <Configurations>
+ <Configuration
+ Name="Debug|Win32"
+ OutputDirectory=".\Debug"
+ IntermediateDirectory=".\Debug"
+ ConfigurationType="1"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories="../common,c:\quake3\common,c:\quake3\libs"
+ PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
+ RuntimeLibrary="1"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Debug/q3map.pch"
+ AssemblerListingLocation=".\Debug/"
+ ObjectFile=".\Debug/"
+ ProgramDataBaseFileName=".\Debug/"
+ BrowseInformation="1"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"
+ CompileAs="0"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="glaux.lib glu32.lib wsock32.lib opengl32.lib odbc32.lib odbccp32.lib ..\libs\pakd.lib ..\libs\jpeg6d.lib"
+ OutputFile=".\Debug/q3map.exe"
+ LinkIncremental="2"
+ SuppressStartupBanner="TRUE"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile=".\Debug/q3map.pdb"
+ SubSystem="1"
+ StackReserveSize="4194304"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ TypeLibraryName=".\Debug/q3map.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Release|Win32"
+ OutputDirectory=".\Release"
+ IntermediateDirectory=".\Release"
+ ConfigurationType="1"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ AdditionalIncludeDirectories="../common,c:\quake3\common,c:\quake3\libs"
+ PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
+ StringPooling="TRUE"
+ RuntimeLibrary="0"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Release/q3map.pch"
+ AssemblerListingLocation=".\Release/"
+ ObjectFile=".\Release/"
+ ProgramDataBaseFileName=".\Release/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="3"
+ CompileAs="0"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="glaux.lib glu32.lib wsock32.lib opengl32.lib odbc32.lib odbccp32.lib ..\libs\pak.lib ..\libs\jpeg6.lib"
+ OutputFile=".\Release/q3map.exe"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile=".\Release/q3map.pdb"
+ SubSystem="1"
+ StackReserveSize="4194304"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ TypeLibraryName=".\Release/q3map.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="DebugTTimo|Win32"
+ OutputDirectory=".\q3map___Win32_DebugTTimo"
+ IntermediateDirectory=".\q3map___Win32_DebugTTimo"
+ ConfigurationType="1"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories="../common,../../Libs,c:\quake3\common,c:\quake3\libs"
+ PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_TTIMOBUILD"
+ RuntimeLibrary="1"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\q3map___Win32_DebugTTimo/q3map.pch"
+ AssemblerListingLocation=".\q3map___Win32_DebugTTimo/"
+ ObjectFile=".\q3map___Win32_DebugTTimo/"
+ ProgramDataBaseFileName=".\q3map___Win32_DebugTTimo/"
+ BrowseInformation="1"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"
+ CompileAs="0"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="glaux.lib glu32.lib wsock32.lib opengl32.lib odbc32.lib odbccp32.lib pakd.lib jpeg6d.lib"
+ OutputFile=".\q3map___Win32_DebugTTimo/q3map.exe"
+ LinkIncremental="2"
+ SuppressStartupBanner="TRUE"
+ AdditionalLibraryDirectories="../../Libs"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile=".\q3map___Win32_DebugTTimo/q3map.pdb"
+ SubSystem="1"
+ StackReserveSize="4194304"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ TypeLibraryName=".\q3map___Win32_DebugTTimo/q3map.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="ReleaseTTimo|Win32"
+ OutputDirectory=".\q3map___Win32_ReleaseTTimo"
+ IntermediateDirectory=".\q3map___Win32_ReleaseTTimo"
+ ConfigurationType="1"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ AdditionalIncludeDirectories="../common,../../Libs,c:\quake3\common,c:\quake3\libs"
+ PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;_TTIMOBUILD"
+ StringPooling="TRUE"
+ RuntimeLibrary="0"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\q3map___Win32_ReleaseTTimo/q3map.pch"
+ AssemblerListingLocation=".\q3map___Win32_ReleaseTTimo/"
+ ObjectFile=".\q3map___Win32_ReleaseTTimo/"
+ ProgramDataBaseFileName=".\q3map___Win32_ReleaseTTimo/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="3"
+ CompileAs="0"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="glaux.lib glu32.lib wsock32.lib opengl32.lib odbc32.lib odbccp32.lib pak.lib jpeg6.lib"
+ OutputFile=".\q3map___Win32_ReleaseTTimo/q3map.exe"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ AdditionalLibraryDirectories="../../Libs"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile=".\q3map___Win32_ReleaseTTimo/q3map.pdb"
+ SubSystem="1"
+ StackReserveSize="4194304"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ TypeLibraryName=".\q3map___Win32_ReleaseTTimo/q3map.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ </Configurations>
+ <References>
+ </References>
+ <Files>
+ <File
+ RelativePath="..\common\aselib.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="brush.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="brush_primit.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="bsp.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\common\bspfile.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\common\cmdlib.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="facebsp.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="fog.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="gldraw.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="glfile.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\common\imagelib.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="leakfile.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="light.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="light_trace.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="lightmaps.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="lightv.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="map.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\common\mathlib.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="mesh.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="misc_model.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\common\mutex.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="patch.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\common\polylib.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="portals.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="prtfile.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\common\scriplib.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="shaders.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="soundv.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="surface.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="terrain.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\common\threads.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tjunction.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="tree.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="vis.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="visflow.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="writebsp.c">
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ </File>
+ </Files>
+ <Globals>
+ </Globals>
+</VisualStudioProject>
diff --git a/q3map/qbsp.h b/q3map/qbsp.h
new file mode 100755
index 0000000..0890713
--- /dev/null
+++ b/q3map/qbsp.h
@@ -0,0 +1,455 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "cmdlib.h"
+#include "mathlib.h"
+#include "scriplib.h"
+#include "polylib.h"
+#include "imagelib.h"
+#include "threads.h"
+#include "bspfile.h"
+#include "shaders.h"
+#include "mesh.h"
+
+
+#define MAX_PATCH_SIZE 32
+
+#define CLIP_EPSILON 0.1
+#define PLANENUM_LEAF -1
+
+#define HINT_PRIORITY 1000
+
+typedef struct parseMesh_s {
+ struct parseMesh_s *next;
+ mesh_t mesh;
+ shaderInfo_t *shaderInfo;
+
+ qboolean grouped; // used during shared edge grouping
+ struct parseMesh_s *groupChain;
+} parseMesh_t;
+
+typedef struct bspface_s {
+ struct bspface_s *next;
+ int planenum;
+ int priority; // added to value calculation
+ qboolean checked;
+ qboolean hint;
+ winding_t *w;
+} bspface_t;
+
+typedef struct plane_s {
+ vec3_t normal;
+ vec_t dist;
+ int type;
+ struct plane_s *hash_chain;
+} plane_t;
+
+typedef struct side_s {
+ int planenum;
+
+ float texMat[2][3]; // brush primitive texture matrix
+ // for old brush coordinates mode
+ float vecs[2][4]; // texture coordinate mapping
+
+ winding_t *winding;
+ winding_t *visibleHull; // convex hull of all visible fragments
+
+ struct shaderInfo_s *shaderInfo;
+
+ int contents; // from shaderInfo
+ int surfaceFlags; // from shaderInfo
+ int value; // from shaderInfo
+
+ qboolean visible; // choose visble planes first
+ qboolean bevel; // don't ever use for bsp splitting, and don't bother
+ // making windings for it
+ qboolean backSide; // generated side for a q3map_backShader
+} side_t;
+
+
+#define MAX_BRUSH_SIDES 1024
+
+typedef struct bspbrush_s {
+ struct bspbrush_s *next;
+
+ int entitynum; // editor numbering
+ int brushnum; // editor numbering
+
+ struct shaderInfo_s *contentShader;
+
+ int contents;
+ qboolean detail;
+ qboolean opaque;
+ int outputNumber; // set when the brush is written to the file list
+
+ int portalareas[2];
+
+ struct bspbrush_s *original; // chopped up brushes will reference the originals
+
+ vec3_t mins, maxs;
+ int numsides;
+ side_t sides[6]; // variably sized
+} bspbrush_t;
+
+
+
+typedef struct drawsurf_s {
+ shaderInfo_t *shaderInfo;
+
+ bspbrush_t *mapBrush; // not valid for patches
+ side_t *side; // not valid for patches
+
+ struct drawsurf_s *nextOnShader; // when sorting by shader for lightmaps
+
+ int fogNum; // set by FogDrawSurfs
+
+ int lightmapNum; // -1 = no lightmap
+ int lightmapX, lightmapY;
+ int lightmapWidth, lightmapHeight;
+
+ int numVerts;
+ drawVert_t *verts;
+
+ int numIndexes;
+ int *indexes;
+
+ // for faces only
+ int planeNum;
+
+ vec3_t lightmapOrigin; // also used for flares
+ vec3_t lightmapVecs[3]; // also used for flares
+
+ // for patches only
+ qboolean patch;
+ int patchWidth;
+ int patchHeight;
+
+ // for misc_models only
+ qboolean miscModel;
+
+ qboolean flareSurface;
+} mapDrawSurface_t;
+
+typedef struct drawSurfRef_s {
+ struct drawSurfRef_s *nextRef;
+ int outputNumber;
+} drawSurfRef_t;
+
+typedef struct node_s {
+ // both leafs and nodes
+ int planenum; // -1 = leaf node
+ struct node_s *parent;
+ vec3_t mins, maxs; // valid after portalization
+ bspbrush_t *volume; // one for each leaf/node
+
+ // nodes only
+ side_t *side; // the side that created the node
+ struct node_s *children[2];
+ qboolean hint;
+ int tinyportals;
+ vec3_t referencepoint;
+
+ // leafs only
+ qboolean opaque; // view can never be inside
+ qboolean areaportal;
+ int cluster; // for portalfile writing
+ int area; // for areaportals
+ bspbrush_t *brushlist; // fragments of all brushes in this leaf
+ drawSurfRef_t *drawSurfReferences; // references to patches pushed down
+
+ int occupied; // 1 or greater can reach entity
+ entity_t *occupant; // for leak file testing
+
+ struct portal_s *portals; // also on nodes during construction
+} node_t;
+
+typedef struct portal_s {
+ plane_t plane;
+ node_t *onnode; // NULL = outside box
+ node_t *nodes[2]; // [0] = front side of plane
+ struct portal_s *next[2];
+ winding_t *winding;
+
+ qboolean sidefound; // false if ->side hasn't been checked
+ qboolean hint;
+ side_t *side; // NULL = non-visible
+} portal_t;
+
+typedef struct {
+ node_t *headnode;
+ node_t outside_node;
+ vec3_t mins, maxs;
+} tree_t;
+
+extern int entity_num;
+
+
+extern qboolean noprune;
+extern qboolean nodetail;
+extern qboolean fulldetail;
+extern qboolean nowater;
+extern qboolean noCurveBrushes;
+extern qboolean fakemap;
+extern qboolean coplanar;
+extern qboolean nofog;
+extern qboolean testExpand;
+extern qboolean showseams;
+
+extern vec_t microvolume;
+
+extern char outbase[32];
+extern char source[1024];
+
+extern int samplesize; //sample size in units
+extern int novertexlighting;
+extern int nogridlighting;
+
+//=============================================================================
+
+// brush.c
+
+int CountBrushList (bspbrush_t *brushes);
+bspbrush_t *AllocBrush (int numsides);
+void FreeBrush (bspbrush_t *brushes);
+void FreeBrushList (bspbrush_t *brushes);
+bspbrush_t *CopyBrush (bspbrush_t *brush);
+void DrawBrushList (bspbrush_t *brush);
+void WriteBrushList (char *name, bspbrush_t *brush, qboolean onlyvis);
+void PrintBrush (bspbrush_t *brush);
+qboolean BoundBrush (bspbrush_t *brush);
+qboolean CreateBrushWindings (bspbrush_t *brush);
+bspbrush_t *BrushFromBounds (vec3_t mins, vec3_t maxs);
+vec_t BrushVolume (bspbrush_t *brush);
+void WriteBspBrushMap (char *name, bspbrush_t *list);
+
+void FilterDetailBrushesIntoTree( entity_t *e, tree_t *tree );
+void FilterStructuralBrushesIntoTree( entity_t *e, tree_t *tree );
+
+//=============================================================================
+
+// map.c
+
+extern int entitySourceBrushes;
+
+// mapplanes[ num^1 ] will always be the mirror or mapplanes[ num ]
+// nummapplanes will always be even
+extern plane_t mapplanes[MAX_MAP_PLANES];
+extern int nummapplanes;
+
+extern vec3_t map_mins, map_maxs;
+
+extern char mapIndexedShaders[MAX_MAP_BRUSHSIDES][MAX_QPATH];
+extern int numMapIndexedShaders;
+
+extern entity_t *mapent;
+
+#define MAX_BUILD_SIDES 300
+extern bspbrush_t *buildBrush;
+
+
+void LoadMapFile (char *filename);
+int FindFloatPlane (vec3_t normal, vec_t dist);
+int PlaneTypeForNormal (vec3_t normal);
+bspbrush_t *FinishBrush( void );
+mapDrawSurface_t *AllocDrawSurf( void );
+mapDrawSurface_t *DrawSurfaceForSide( bspbrush_t *b, side_t *s, winding_t *w );
+
+//=============================================================================
+
+//=============================================================================
+
+// draw.c
+
+extern vec3_t draw_mins, draw_maxs;
+extern qboolean drawflag;
+
+void Draw_ClearWindow (void);
+void DrawWinding (winding_t *w);
+
+void GLS_BeginScene (void);
+void GLS_Winding (winding_t *w, int code);
+void GLS_EndScene (void);
+
+//=============================================================================
+
+// csg
+
+bspbrush_t *MakeBspBrushList ( bspbrush_t *brushes, vec3_t clipmins, vec3_t clipmaxs);
+
+//=============================================================================
+
+// brushbsp
+
+#define PSIDE_FRONT 1
+#define PSIDE_BACK 2
+#define PSIDE_BOTH (PSIDE_FRONT|PSIDE_BACK)
+#define PSIDE_FACING 4
+
+int BoxOnPlaneSide (vec3_t mins, vec3_t maxs, plane_t *plane);
+qboolean WindingIsTiny (winding_t *w);
+
+void SplitBrush (bspbrush_t *brush, int planenum,
+ bspbrush_t **front, bspbrush_t **back);
+
+tree_t *AllocTree (void);
+node_t *AllocNode (void);
+
+tree_t *BrushBSP (bspbrush_t *brushlist, vec3_t mins, vec3_t maxs);
+
+//=============================================================================
+
+// portals.c
+
+void MakeHeadnodePortals (tree_t *tree);
+void MakeNodePortal (node_t *node);
+void SplitNodePortals (node_t *node);
+
+qboolean Portal_Passable(portal_t *p);
+
+qboolean FloodEntities (tree_t *tree);
+void FillOutside (node_t *headnode);
+void FloodAreas (tree_t *tree);
+bspface_t *VisibleFaces(entity_t *e, tree_t *tree);
+void FreePortal (portal_t *p);
+
+void MakeTreePortals (tree_t *tree);
+
+//=============================================================================
+
+// glfile.c
+
+void OutputWinding( winding_t *w, FILE *glview );
+void WriteGLView( tree_t *tree, char *source );
+
+//=============================================================================
+
+// leakfile.c
+
+void LeakFile( tree_t *tree );
+
+//=============================================================================
+
+// prtfile.c
+
+void NumberClusters( tree_t *tree );
+void WritePortalFile( tree_t *tree );
+
+//=============================================================================
+
+// writebsp.c
+
+void SetModelNumbers (void);
+void SetLightStyles (void);
+
+int EmitShader( const char *shader );
+
+void BeginBSPFile (void);
+void EndBSPFile (void);
+
+void BeginModel (void);
+void EndModel( node_t *headnode );
+
+
+//=============================================================================
+
+// tree.c
+
+void FreeTree (tree_t *tree);
+void FreeTree_r (node_t *node);
+void PrintTree_r (node_t *node, int depth);
+void FreeTreePortals_r (node_t *node);
+
+//=============================================================================
+
+// patch.c
+
+extern int numMapPatches;
+
+mapDrawSurface_t *DrawSurfaceForMesh( mesh_t *m );
+void ParsePatch( void );
+mesh_t *SubdivideMesh( mesh_t in, float maxError, float minLength );
+void PatchMapDrawSurfs( entity_t *e );
+
+//=============================================================================
+
+// lightmap.c
+
+void AllocateLightmaps( entity_t *e );
+
+//=============================================================================
+
+// tjunction.c
+
+void FixTJunctions( entity_t *e );
+
+
+//=============================================================================
+
+// fog.c
+
+void FogDrawSurfs( void );
+winding_t *WindingFromDrawSurf( mapDrawSurface_t *ds );
+
+//=============================================================================
+
+// facebsp.c
+
+bspface_t *BspFaceForPortal( portal_t *p );
+bspface_t *MakeStructuralBspFaceList( bspbrush_t *list );
+bspface_t *MakeVisibleBspFaceList( bspbrush_t *list );
+tree_t *FaceBSP( bspface_t *list );
+
+//=============================================================================
+
+// misc_model.c
+
+extern int c_triangleModels;
+extern int c_triangleSurfaces;
+extern int c_triangleVertexes;
+extern int c_triangleIndexes;
+
+void AddTriangleModels( tree_t *tree );
+
+//=============================================================================
+
+// surface.c
+
+extern mapDrawSurface_t mapDrawSurfs[MAX_MAP_DRAW_SURFS];
+extern int numMapDrawSurfs;
+
+mapDrawSurface_t *AllocDrawSurf( void );
+void MergeSides( entity_t *e, tree_t *tree );
+void SubdivideDrawSurfs( entity_t *e, tree_t *tree );
+void MakeDrawSurfaces( bspbrush_t *b );
+void ClipSidesIntoTree( entity_t *e, tree_t *tree );
+void FilterDrawsurfsIntoTree( entity_t *e, tree_t *tree );
+
+//==============================================================================
+
+// brush_primit.c
+
+#define BPRIMIT_UNDEFINED 0
+#define BPRIMIT_OLDBRUSHES 1
+#define BPRIMIT_NEWBRUSHES 2
+extern int g_bBrushPrimit;
+
+void ComputeAxisBase( vec3_t normal, vec3_t texX, vec3_t texY);
diff --git a/q3map/shaders.c b/q3map/shaders.c
new file mode 100755
index 0000000..1efc513
--- /dev/null
+++ b/q3map/shaders.c
@@ -0,0 +1,608 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include <string.h>
+#include <math.h>
+#include "cmdlib.h"
+#include "mathlib.h"
+#include "imagelib.h"
+#include "scriplib.h"
+
+#ifdef _TTIMOBUILD
+#include "../common/qfiles.h"
+#include "../common/surfaceflags.h"
+#else
+#include "../code/qcommon/qfiles.h"
+#include "../code/game/surfaceflags.h"
+#endif
+
+#include "shaders.h"
+#ifdef _WIN32
+
+#ifdef _TTIMOBUILD
+#include "pakstuff.h"
+#include "jpeglib.h"
+#else
+#include "../libs/pakstuff.h"
+#include "../libs/jpeglib.h"
+#endif
+
+#endif
+
+
+// 5% backsplash by default
+#define DEFAULT_BACKSPLASH_FRACTION 0.05
+#define DEFAULT_BACKSPLASH_DISTANCE 24
+
+
+#define MAX_SURFACE_INFO 4096
+
+shaderInfo_t defaultInfo;
+shaderInfo_t shaderInfo[MAX_SURFACE_INFO];
+int numShaderInfo;
+
+
+typedef struct {
+ char *name;
+ int clearSolid, surfaceFlags, contents;
+} infoParm_t;
+
+infoParm_t infoParms[] = {
+ // server relevant contents
+ {"water", 1, 0, CONTENTS_WATER },
+ {"slime", 1, 0, CONTENTS_SLIME }, // mildly damaging
+ {"lava", 1, 0, CONTENTS_LAVA }, // very damaging
+ {"playerclip", 1, 0, CONTENTS_PLAYERCLIP },
+ {"monsterclip", 1, 0, CONTENTS_MONSTERCLIP },
+ {"nodrop", 1, 0, CONTENTS_NODROP }, // don't drop items or leave bodies (death fog, lava, etc)
+ {"nonsolid", 1, SURF_NONSOLID, 0}, // clears the solid flag
+
+ // utility relevant attributes
+ {"origin", 1, 0, CONTENTS_ORIGIN }, // center of rotating brushes
+ {"trans", 0, 0, CONTENTS_TRANSLUCENT }, // don't eat contained surfaces
+ {"detail", 0, 0, CONTENTS_DETAIL }, // don't include in structural bsp
+ {"structural", 0, 0, CONTENTS_STRUCTURAL }, // force into structural bsp even if trnas
+ {"areaportal", 1, 0, CONTENTS_AREAPORTAL }, // divides areas
+ {"clusterportal",1, 0, CONTENTS_CLUSTERPORTAL },// for bots
+ {"donotenter", 1, 0, CONTENTS_DONOTENTER }, // for bots
+ {"botclip", 1, 0, CONTENTS_BOTCLIP }, // for bots
+ {"nobotclip", 0, 0, CONTENTS_NOBOTCLIP }, // don't use for bot clipping
+
+ {"fog", 1, 0, CONTENTS_FOG}, // carves surfaces entering
+ {"sky", 0, SURF_SKY, 0 }, // emit light from an environment map
+ {"lightfilter", 0, SURF_LIGHTFILTER, 0 }, // filter light going through it
+ {"alphashadow", 0, SURF_ALPHASHADOW, 0 }, // test light on a per-pixel basis
+ {"hint", 0, SURF_HINT, 0 }, // use as a primary splitter
+
+ // server attributes
+ {"slick", 0, SURF_SLICK, 0 },
+ {"noimpact", 0, SURF_NOIMPACT, 0 }, // don't make impact explosions or marks
+ {"nomarks", 0, SURF_NOMARKS, 0 }, // don't make impact marks, but still explode
+ {"ladder", 0, SURF_LADDER, 0 },
+ {"nodamage", 0, SURF_NODAMAGE, 0 },
+ {"metalsteps", 0, SURF_METALSTEPS,0 },
+ {"flesh", 0, SURF_FLESH, 0 },
+ {"nosteps", 0, SURF_NOSTEPS, 0 },
+
+ // drawsurf attributes
+ {"nodraw", 0, SURF_NODRAW, 0 }, // don't generate a drawsurface (or a lightmap)
+ {"pointlight", 0, SURF_POINTLIGHT, 0 }, // sample lighting at vertexes
+ {"nolightmap", 0, SURF_NOLIGHTMAP,0 }, // don't generate a lightmap
+ {"nodlight", 0, SURF_NODLIGHT, 0 }, // don't ever add dynamic lights
+ {"dust", 0, SURF_DUST, 0} // leave dust trail when walking on this surface
+};
+
+
+/*
+===============
+LoadShaderImage
+===============
+*/
+
+byte* LoadImageFile(char *filename, qboolean *bTGA)
+{
+ byte *buffer = NULL;
+ int nLen = 0;
+ *bTGA = qtrue;
+ if (FileExists(filename))
+ {
+ LoadFileBlock(filename, &buffer);
+ }
+#ifdef _WIN32
+ else
+ {
+ PakLoadAnyFile(filename, &buffer);
+ }
+#endif
+ if ( buffer == NULL)
+ {
+ nLen = strlen(filename);
+ filename[nLen-3] = 'j';
+ filename[nLen-2] = 'p';
+ filename[nLen-1] = 'g';
+ if (FileExists(filename))
+ {
+ LoadFileBlock(filename, &buffer);
+ }
+#ifdef _WIN32
+ else
+ {
+ PakLoadAnyFile(filename, &buffer);
+ }
+#endif
+ if ( buffer )
+ {
+ *bTGA = qfalse;
+ }
+ }
+ return buffer;
+}
+
+/*
+===============
+LoadShaderImage
+===============
+*/
+static void LoadShaderImage( shaderInfo_t *si ) {
+ char filename[1024];
+ int i, count;
+ float color[4];
+ byte *buffer;
+ qboolean bTGA = qtrue;
+
+ // look for the lightimage if it is specified
+ if ( si->lightimage[0] ) {
+ sprintf( filename, "%s%s", gamedir, si->lightimage );
+ DefaultExtension( filename, ".tga" );
+ buffer = LoadImageFile(filename, &bTGA);
+ if ( buffer != NULL) {
+ goto loadTga;
+ }
+ }
+
+ // look for the editorimage if it is specified
+ if ( si->editorimage[0] ) {
+ sprintf( filename, "%s%s", gamedir, si->editorimage );
+ DefaultExtension( filename, ".tga" );
+ buffer = LoadImageFile(filename, &bTGA);
+ if ( buffer != NULL) {
+ goto loadTga;
+ }
+ }
+
+ // just try the shader name with a .tga
+ // on unix, we have case sensitivity problems...
+ sprintf( filename, "%s%s.tga", gamedir, si->shader );
+ buffer = LoadImageFile(filename, &bTGA);
+ if ( buffer != NULL) {
+ goto loadTga;
+ }
+
+ sprintf( filename, "%s%s.TGA", gamedir, si->shader );
+ buffer = LoadImageFile(filename, &bTGA);
+ if ( buffer != NULL) {
+ goto loadTga;
+ }
+
+ // couldn't load anything
+ _printf("WARNING: Couldn't find image for shader %s\n", si->shader );
+
+ si->color[0] = 1;
+ si->color[1] = 1;
+ si->color[2] = 1;
+ si->width = 64;
+ si->height = 64;
+ si->pixels = malloc( si->width * si->height * 4 );
+ memset ( si->pixels, 255, si->width * si->height * 4 );
+ return;
+
+ // load the image to get dimensions and color
+loadTga:
+ if ( bTGA) {
+ LoadTGABuffer( buffer, &si->pixels, &si->width, &si->height );
+ }
+ else {
+#ifdef _WIN32
+ LoadJPGBuff(buffer, &si->pixels, &si->width, &si->height );
+#endif
+ }
+
+ free(buffer);
+
+ count = si->width * si->height;
+
+ VectorClear( color );
+ color[ 3 ] = 0;
+ for ( i = 0 ; i < count ; i++ ) {
+ color[0] += si->pixels[ i * 4 + 0 ];
+ color[1] += si->pixels[ i * 4 + 1 ];
+ color[2] += si->pixels[ i * 4 + 2 ];
+ color[3] += si->pixels[ i * 4 + 3 ];
+ }
+ ColorNormalize( color, si->color );
+ VectorScale( color, 1.0/count, si->averageColor );
+}
+
+/*
+===============
+AllocShaderInfo
+===============
+*/
+static shaderInfo_t *AllocShaderInfo( void ) {
+ shaderInfo_t *si;
+
+ if ( numShaderInfo == MAX_SURFACE_INFO ) {
+ Error( "MAX_SURFACE_INFO" );
+ }
+ si = &shaderInfo[ numShaderInfo ];
+ numShaderInfo++;
+
+ // set defaults
+
+ si->contents = CONTENTS_SOLID;
+
+ si->backsplashFraction = DEFAULT_BACKSPLASH_FRACTION;
+ si->backsplashDistance = DEFAULT_BACKSPLASH_DISTANCE;
+
+ si->lightmapSampleSize = 0;
+ si->forceTraceLight = qfalse;
+ si->forceVLight = qfalse;
+ si->patchShadows = qfalse;
+ si->vertexShadows = qfalse;
+ si->noVertexShadows = qfalse;
+ si->forceSunLight = qfalse;
+ si->vertexScale = 1.0;
+ si->notjunc = qfalse;
+
+ return si;
+}
+
+/*
+===============
+ShaderInfoForShader
+===============
+*/
+shaderInfo_t *ShaderInfoForShader( const char *shaderName ) {
+ int i;
+ shaderInfo_t *si;
+ char shader[MAX_QPATH];
+
+ // strip off extension
+ strcpy( shader, shaderName );
+ StripExtension( shader );
+
+ // search for it
+ for ( i = 0 ; i < numShaderInfo ; i++ ) {
+ si = &shaderInfo[ i ];
+ if ( !Q_stricmp( shader, si->shader ) ) {
+ if ( !si->width ) {
+ LoadShaderImage( si );
+ }
+ return si;
+ }
+ }
+
+ si = AllocShaderInfo();
+ strcpy( si->shader, shader );
+
+ LoadShaderImage( si );
+
+ return si;
+}
+
+/*
+===============
+ParseShaderFile
+===============
+*/
+static void ParseShaderFile( const char *filename ) {
+ int i;
+ int numInfoParms = sizeof(infoParms) / sizeof(infoParms[0]);
+ shaderInfo_t *si;
+
+// qprintf( "shaderFile: %s\n", filename );
+ LoadScriptFile( filename );
+ while ( 1 ) {
+ if ( !GetToken( qtrue ) ) {
+ break;
+ }
+
+ si = AllocShaderInfo();
+ strcpy( si->shader, token );
+ MatchToken( "{" );
+ while ( 1 ) {
+ if ( !GetToken( qtrue ) ) {
+ break;
+ }
+ if ( !strcmp( token, "}" ) ) {
+ break;
+ }
+
+ // skip internal braced sections
+ if ( !strcmp( token, "{" ) ) {
+ si->hasPasses = qtrue;
+ while ( 1 ) {
+ if ( !GetToken( qtrue ) ) {
+ break;
+ }
+ if ( !strcmp( token, "}" ) ) {
+ break;
+ }
+ }
+ continue;
+ }
+
+ if ( !Q_stricmp( token, "surfaceparm" ) ) {
+ GetToken( qfalse );
+ for ( i = 0 ; i < numInfoParms ; i++ ) {
+ if ( !Q_stricmp( token, infoParms[i].name ) ) {
+ si->surfaceFlags |= infoParms[i].surfaceFlags;
+ si->contents |= infoParms[i].contents;
+ if ( infoParms[i].clearSolid ) {
+ si->contents &= ~CONTENTS_SOLID;
+ }
+ break;
+ }
+ }
+ if ( i == numInfoParms ) {
+ // we will silently ignore all tokens beginning with qer,
+ // which are QuakeEdRadient parameters
+ if ( Q_strncasecmp( token, "qer", 3 ) ) {
+ _printf( "Unknown surfaceparm: \"%s\"\n", token );
+ }
+ }
+ continue;
+ }
+
+
+ // qer_editorimage <image>
+ if ( !Q_stricmp( token, "qer_editorimage" ) ) {
+ GetToken( qfalse );
+ strcpy( si->editorimage, token );
+ DefaultExtension( si->editorimage, ".tga" );
+ continue;
+ }
+
+ // q3map_lightimage <image>
+ if ( !Q_stricmp( token, "q3map_lightimage" ) ) {
+ GetToken( qfalse );
+ strcpy( si->lightimage, token );
+ DefaultExtension( si->lightimage, ".tga" );
+ continue;
+ }
+
+ // q3map_surfacelight <value>
+ if ( !Q_stricmp( token, "q3map_surfacelight" ) ) {
+ GetToken( qfalse );
+ si->value = atoi( token );
+ continue;
+ }
+
+ // q3map_lightsubdivide <value>
+ if ( !Q_stricmp( token, "q3map_lightsubdivide" ) ) {
+ GetToken( qfalse );
+ si->lightSubdivide = atoi( token );
+ continue;
+ }
+
+ // q3map_lightmapsamplesize <value>
+ if ( !Q_stricmp( token, "q3map_lightmapsamplesize" ) ) {
+ GetToken( qfalse );
+ si->lightmapSampleSize = atoi( token );
+ continue;
+ }
+
+ // q3map_tracelight
+ if ( !Q_stricmp( token, "q3map_tracelight" ) ) {
+ si->forceTraceLight = qtrue;
+ continue;
+ }
+
+ // q3map_vlight
+ if ( !Q_stricmp( token, "q3map_vlight" ) ) {
+ si->forceVLight = qtrue;
+ continue;
+ }
+
+ // q3map_patchshadows
+ if ( !Q_stricmp( token, "q3map_patchshadows" ) ) {
+ si->patchShadows = qtrue;
+ continue;
+ }
+
+ // q3map_vertexshadows
+ if ( !Q_stricmp( token, "q3map_vertexshadows" ) ) {
+ si->vertexShadows = qtrue;
+ continue;
+ }
+
+ // q3map_novertexshadows
+ if ( !Q_stricmp( token, "q3map_novertexshadows" ) ) {
+ si->noVertexShadows = qtrue;
+ continue;
+ }
+
+ // q3map_forcesunlight
+ if ( !Q_stricmp( token, "q3map_forcesunlight" ) ) {
+ si->forceSunLight = qtrue;
+ continue;
+ }
+
+ // q3map_vertexscale
+ if ( !Q_stricmp( token, "q3map_vertexscale" ) ) {
+ GetToken( qfalse );
+ si->vertexScale = atof(token);
+ continue;
+ }
+
+ // q3map_notjunc
+ if ( !Q_stricmp( token, "q3map_notjunc" ) ) {
+ si->notjunc = qtrue;
+ continue;
+ }
+
+ // q3map_globaltexture
+ if ( !Q_stricmp( token, "q3map_globaltexture" ) ) {
+ si->globalTexture = qtrue;
+ continue;
+ }
+
+ // q3map_backsplash <percent> <distance>
+ if ( !Q_stricmp( token, "q3map_backsplash" ) ) {
+ GetToken( qfalse );
+ si->backsplashFraction = atof( token ) * 0.01;
+ GetToken( qfalse );
+ si->backsplashDistance = atof( token );
+ continue;
+ }
+
+ // q3map_backshader <shader>
+ if ( !Q_stricmp( token, "q3map_backshader" ) ) {
+ GetToken( qfalse );
+ strcpy( si->backShader, token );
+ continue;
+ }
+
+ // q3map_flare <shader>
+ if ( !Q_stricmp( token, "q3map_flare" ) ) {
+ GetToken( qfalse );
+ strcpy( si->flareShader, token );
+ continue;
+ }
+
+ // light <value>
+ // old style flare specification
+ if ( !Q_stricmp( token, "light" ) ) {
+ GetToken( qfalse );
+ strcpy( si->flareShader, "flareshader" );
+ continue;
+ }
+
+ // q3map_sun <red> <green> <blue> <intensity> <degrees> <elivation>
+ // color will be normalized, so it doesn't matter what range you use
+ // intensity falls off with angle but not distance 100 is a fairly bright sun
+ // degree of 0 = from the east, 90 = north, etc. altitude of 0 = sunrise/set, 90 = noon
+ if ( !Q_stricmp( token, "q3map_sun" ) ) {
+ float a, b;
+
+ GetToken( qfalse );
+ si->sunLight[0] = atof( token );
+ GetToken( qfalse );
+ si->sunLight[1] = atof( token );
+ GetToken( qfalse );
+ si->sunLight[2] = atof( token );
+
+ VectorNormalize( si->sunLight, si->sunLight);
+
+ GetToken( qfalse );
+ a = atof( token );
+ VectorScale( si->sunLight, a, si->sunLight);
+
+ GetToken( qfalse );
+ a = atof( token );
+ a = a / 180 * Q_PI;
+
+ GetToken( qfalse );
+ b = atof( token );
+ b = b / 180 * Q_PI;
+
+ si->sunDirection[0] = cos( a ) * cos( b );
+ si->sunDirection[1] = sin( a ) * cos( b );
+ si->sunDirection[2] = sin( b );
+
+ si->surfaceFlags |= SURF_SKY;
+ continue;
+ }
+
+ // tesssize is used to force liquid surfaces to subdivide
+ if ( !Q_stricmp( token, "tesssize" ) ) {
+ GetToken( qfalse );
+ si->subdivisions = atof( token );
+ continue;
+ }
+
+ // cull none will set twoSided
+ if ( !Q_stricmp( token, "cull" ) ) {
+ GetToken( qfalse );
+ if ( !Q_stricmp( token, "none" ) ) {
+ si->twoSided = qtrue;
+ }
+ continue;
+ }
+
+
+ // deformVertexes autosprite[2]
+ // we catch this so autosprited surfaces become point
+ // lights instead of area lights
+ if ( !Q_stricmp( token, "deformVertexes" ) ) {
+ GetToken( qfalse );
+ if ( !Q_strncasecmp( token, "autosprite", 10 ) ) {
+ si->autosprite = qtrue;
+ si->contents = CONTENTS_DETAIL;
+ }
+ continue;
+ }
+
+
+ // ignore all other tokens on the line
+
+ while ( TokenAvailable() ) {
+ GetToken( qfalse );
+ }
+ }
+ }
+}
+
+/*
+===============
+LoadShaderInfo
+===============
+*/
+#define MAX_SHADER_FILES 64
+void LoadShaderInfo( void ) {
+ char filename[1024];
+ int i;
+ char *shaderFiles[MAX_SHADER_FILES];
+ int numShaderFiles;
+
+ sprintf( filename, "%sscripts/shaderlist.txt", gamedir );
+ LoadScriptFile( filename );
+
+ numShaderFiles = 0;
+ while ( 1 ) {
+ if ( !GetToken( qtrue ) ) {
+ break;
+ }
+ shaderFiles[numShaderFiles] = malloc(MAX_OS_PATH);
+ strcpy( shaderFiles[ numShaderFiles ], token );
+ numShaderFiles++;
+ }
+
+ for ( i = 0 ; i < numShaderFiles ; i++ ) {
+ sprintf( filename, "%sscripts/%s.shader", gamedir, shaderFiles[i] );
+ ParseShaderFile( filename );
+ free(shaderFiles[i]);
+ }
+
+ qprintf( "%5i shaderInfo\n", numShaderInfo);
+}
+
diff --git a/q3map/shaders.h b/q3map/shaders.h
new file mode 100755
index 0000000..fc187c6
--- /dev/null
+++ b/q3map/shaders.h
@@ -0,0 +1,71 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+
+typedef struct shaderInfo_s {
+ char shader[MAX_QPATH];
+ int surfaceFlags;
+ int contents;
+ int value;
+
+ char backShader[MAX_QPATH]; // for surfaces that generate different front and back passes
+ char flareShader[MAX_QPATH]; // for light flares
+
+ float subdivisions; // from a "tesssize xxx"
+ float backsplashFraction; // floating point value, usually 0.05
+ float backsplashDistance; // default 16
+ float lightSubdivide; // default 120
+ int lightmapSampleSize; // lightmap sample size
+
+ qboolean hasPasses; // false if the shader doesn't define any rendering passes
+
+ qboolean globalTexture; // don't normalize texture repeats
+
+ qboolean twoSided; // cull none
+ qboolean autosprite; // autosprite shaders will become point lights
+ // instead of area lights
+ qboolean lightFilter; // light rays that cross surfaces of this type
+ // should test against the filter image
+ qboolean forceTraceLight; // always use -light for this surface
+ qboolean forceVLight; // always use -vlight for this surface
+ qboolean patchShadows; // have patches casting shadows when using -light for this surface
+ qboolean vertexShadows; // shadows will be casted at this surface even when vertex lit
+ qboolean noVertexShadows; // no shadows will be casted at this surface in vertex lighting
+ qboolean forceSunLight; // force sun light at this surface even tho we might not calculate shadows in vertex lighting
+ qboolean notjunc; // don't use this surface for tjunction fixing
+ float vertexScale; // vertex light scale
+
+ char editorimage[MAX_QPATH]; // use this image to generate texture coordinates
+ char lightimage[MAX_QPATH]; // use this image to generate color / averageColor
+ vec3_t color; // colorNormalized
+ vec3_t averageColor;
+
+ int width, height;
+ byte *pixels;
+
+ vec3_t sunLight;
+ vec3_t sunDirection;
+} shaderInfo_t;
+
+void LoadShaderInfo( void );
+shaderInfo_t *ShaderInfoForShader( const char *shader );
+
diff --git a/q3map/soundv.c b/q3map/soundv.c
new file mode 100755
index 0000000..1883c52
--- /dev/null
+++ b/q3map/soundv.c
@@ -0,0 +1,5742 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+/*****************************************************************************
+ * name: soundv.c
+ *****************************************************************************/
+
+#include "cmdlib.h"
+#include "mathlib.h"
+#include "bspfile.h"
+#include "imagelib.h"
+#include "threads.h"
+#include "mutex.h"
+#include "scriplib.h"
+
+#include "shaders.h"
+#include "mesh.h"
+
+#ifdef _WIN32
+//Improve floating-point consistency.
+#pragma optimize( "p", on )
+#endif
+
+#ifdef _WIN32
+#include "../libs/pakstuff.h"
+#endif
+
+#define MAX_CLUSTERS 16384
+#define MAX_PORTALS 32768
+#define MAX_FACETS 65536
+#define MAX_LIGHTS 16384
+
+#define LIGHTMAP_SIZE 128
+
+#define LIGHTMAP_PIXELSHIFT 0.5
+
+//#define LIGHTMAP_PATCHSHIFT
+
+#define PORTALFILE "PRT1"
+
+#define ON_EPSILON 0.1
+
+#define VectorSet(v, x, y, z) v[0] = x;v[1] = y;v[2] = z;
+
+typedef struct
+{
+ vec3_t normal;
+ float dist;
+} plane_t;
+
+#define MAX_POINTS_ON_WINDING 64
+//NOTE: whenever this is overflowed parts of lightmaps might end up not being lit
+#define MAX_POINTS_ON_FIXED_WINDING 48
+
+typedef struct
+{
+ int numpoints;
+ vec3_t points[MAX_POINTS_ON_FIXED_WINDING]; // variable sized
+} winding_t;
+
+typedef struct
+{
+ plane_t plane; // normal pointing into neighbor
+ int leaf; // neighbor
+ winding_t *winding;
+ vec3_t origin; // for fast clip testing
+ float radius;
+} lportal_t;
+
+#define MAX_PORTALS_ON_LEAF 128
+typedef struct lleaf_s
+{
+ int numportals;
+ lportal_t *portals[MAX_PORTALS_ON_LEAF];
+ //
+ int numSurfaces;
+ int firstSurface;
+} lleaf_t;
+
+typedef struct lFacet_s
+{
+ int num;
+ plane_t plane;
+ vec3_t points[4]; //
+ int numpoints;
+ float lightmapCoords[4][2];
+ plane_t boundaries[4]; // negative is outside the bounds
+ float textureMatrix[2][4]; // texture coordinates for translucency
+ float lightmapMatrix[2][4]; // lightmap texture coordinates
+ vec3_t mins;
+ int x, y, width, height;
+} lFacet_t;
+
+typedef struct lsurfaceTest_s
+{
+ vec3_t mins, maxs;
+ vec3_t origin;
+ float radius;
+ qboolean patch; // true if this is a patch
+ qboolean trisoup; // true if this is a triangle soup
+ int numFacets;
+ lFacet_t *facets;
+ mesh_t *detailMesh; // detailed mesh with points for each lmp
+ shaderInfo_t *shader; // for translucency
+ mutex_t *mutex;
+ int numvolumes; // number of volumes casted at this surface
+ //
+ int always_tracelight;
+ int always_vsound;
+} lsurfaceTest_t;
+
+//volume types
+#define VOLUME_NORMAL 0
+#define VOLUME_DIRECTED 1
+
+#define MAX_TRANSLUCENTFACETS 32
+
+typedef struct lightvolume_s
+{
+ int num;
+ int cluster; //cluster this light volume started in
+ plane_t endplane; //end plane
+ plane_t farplane; //original end plane
+ vec3_t points[MAX_POINTS_ON_WINDING]; //end winding points
+ plane_t planes[MAX_POINTS_ON_WINDING]; //volume bounding planes
+ int numplanes; //number of volume bounding planes
+ int type; //light volume type
+ //list with translucent surfaces the volume went through
+ int transFacets[MAX_TRANSLUCENTFACETS];
+ int transSurfaces[MAX_TRANSLUCENTFACETS];
+ int numtransFacets;
+ //clusters already tested
+ byte clusterTested[MAX_CLUSTERS/8];
+ //facets already tested
+ byte facetTested[MAX_FACETS/8];
+ int facetNum; //number of the facet blocking the light in this volume
+ int surfaceNum; //number of the surface blocking the light in this volume
+} lightvolume_t;
+
+//light types
+#define LIGHT_POINTRADIAL 1
+#define LIGHT_POINTSPOT 2
+#define LIGHT_POINTFAKESURFACE 3
+#define LIGHT_SURFACEDIRECTED 4
+#define LIGHT_SURFACERADIAL 5
+#define LIGHT_SURFACESPOT 6
+
+//light distance attenuation types
+#define LDAT_QUADRATIC 0
+#define LDAT_LINEAR 1
+#define LDAT_NOSCALE 2
+
+//light angle attenuation types
+#define LAAT_NORMAL 0
+#define LAAT_QUADRATIC 1
+#define LAAT_DOUBLEQUADRATIC 2
+
+typedef struct vsound_s
+{
+ vec3_t origin; //light origin, for point lights
+ winding_t w; //light winding, for area lights
+ vec4_t plane; //light winding plane
+ vec3_t normal; //direction of the light
+ int type; //light type
+ vec3_t color; //light color
+ qboolean twosided; //radiates light at both sides of the winding
+ int style; //light style (not used)
+ int atten_disttype; //light distance attenuation type
+ int atten_angletype; //light angle attenuation type
+ float atten_distscale; //distance attenuation scale
+ float atten_anglescale; //angle attenuation scale
+ float radiusByDist; //radius by distance for spot lights
+ float photons; //emitted photons
+ float intensity; //intensity
+ vec3_t emitColor; //full out-of-gamut value (not used)
+ struct shaderInfo_s *si; //shader info
+ int insolid; //set when light is in solid
+} vsound_t;
+
+static float lightLinearScale = 1.0 / 8000;
+static float lightPointScale = 7500;
+static float lightAreaScale = 0.25;
+static float lightFormFactorValueScale = 3;
+static int lightDefaultSubdivide = 999; // vary by surface size?
+static vec3_t lightAmbientColor;
+
+static int portalclusters, numportals, numfaces;
+static lleaf_t *leafs;
+static lportal_t *portals;
+static int numvsounds = 0;
+static vsound_t *vsounds[MAX_LIGHTS];
+static int nostitching = 0;
+static int noalphashading = 0;
+static int nocolorshading = 0;
+static int nobackfaceculling = 0;
+static int defaulttracelight = 0;
+static int radiosity = 0;
+static int radiosity_scale;
+
+static int clustersurfaces[MAX_MAP_LEAFFACES];
+static int numclustersurfaces = 0;
+static lsurfaceTest_t *lsurfaceTest[MAX_MAP_DRAW_SURFS];
+static int numfacets;
+static float lightmappixelarea[MAX_MAP_LIGHTING/3];
+static float *lightFloats;//[MAX_MAP_LIGHTING];
+
+// from polylib.c
+winding_t *AllocWinding (int points);
+void FreeWinding (winding_t *w);
+void WindingCenter (winding_t *w, vec3_t center);
+void WindingBounds (winding_t *w, vec3_t mins, vec3_t maxs);
+vec_t WindingArea (winding_t *w);
+winding_t *BaseWindingForPlane (vec3_t normal, vec_t dist);
+void ClipWindingEpsilon (winding_t *in, vec3_t normal, vec_t dist,
+ vec_t epsilon, winding_t **front, winding_t **back);
+winding_t *ReverseWinding (winding_t *w);
+
+// from light.c
+extern char source[1024];
+extern vec3_t surfaceOrigin[ MAX_MAP_DRAW_SURFS ];
+extern int entitySurface[ MAX_MAP_DRAW_SURFS ];
+extern int samplesize;
+extern qboolean patchshadows;
+extern vec3_t gridSize;
+
+float PointToPolygonFormFactor( const vec3_t point, const vec3_t normal, const winding_t *w );
+void ColorToBytes( const float *color, byte *colorBytes );
+void CountLightmaps( void );
+void GridAndVertexLighting( void );
+void SetEntityOrigins( void );
+
+
+//#define DEBUGNET
+
+#ifdef DEBUGNET
+
+#include "l_net.h"
+
+socket_t *debug_socket;
+
+/*
+=====================
+DebugNet_Setup
+=====================
+*/
+void DebugNet_Setup(void)
+{
+ address_t address;
+ int i;
+
+ Net_Setup();
+ Net_StringToAddress("127.0.0.1:28000", &address);
+ for (i = 0; i < 10; i++)
+ {
+ debug_socket = Net_Connect(&address, 28005 + i);
+ if (debug_socket)
+ break;
+ }
+}
+
+/*
+=====================
+DebugNet_Shutdown
+=====================
+*/
+void DebugNet_Shutdown(void)
+{
+ netmessage_t msg;
+
+ if (debug_socket)
+ {
+ NMSG_Clear(&msg);
+ NMSG_WriteByte(&msg, 1);
+ Net_Send(debug_socket, &msg);
+ Net_Disconnect(debug_socket);
+ }
+ debug_socket = NULL;
+ Net_Shutdown();
+}
+
+/*
+=====================
+DebugNet_RemoveAllPolys
+=====================
+*/
+void DebugNet_RemoveAllPolys(void)
+{
+ netmessage_t msg;
+
+ if (!debug_socket)
+ return;
+ NMSG_Clear(&msg);
+ NMSG_WriteByte(&msg, 2); //remove all debug polys
+ Net_Send(debug_socket, &msg);
+}
+
+/*
+====================
+DebugNet_DrawWinding
+=====================
+*/
+void DebugNet_DrawWinding(winding_t *w, int color)
+{
+ netmessage_t msg;
+ int i;
+
+ if (!debug_socket)
+ return;
+ NMSG_Clear(&msg);
+ NMSG_WriteByte(&msg, 0); //draw a winding
+ NMSG_WriteByte(&msg, w->numpoints); //number of points
+ NMSG_WriteLong(&msg, color); //color
+ for (i = 0; i < w->numpoints; i++)
+ {
+ NMSG_WriteFloat(&msg, w->points[i][0]);
+ NMSG_WriteFloat(&msg, w->points[i][1]);
+ NMSG_WriteFloat(&msg, w->points[i][2]);
+ }
+ Net_Send(debug_socket, &msg);
+}
+
+/*
+=====================
+DebugNet_DrawLine
+=====================
+*/
+void DebugNet_DrawLine(vec3_t p1, vec3_t p2, int color)
+{
+ netmessage_t msg;
+
+ if (!debug_socket)
+ return;
+ NMSG_Clear(&msg);
+ NMSG_WriteByte(&msg, 1); //draw a line
+ NMSG_WriteLong(&msg, color); //color
+ NMSG_WriteFloat(&msg, p1[0]);
+ NMSG_WriteFloat(&msg, p1[1]);
+ NMSG_WriteFloat(&msg, p1[2]);
+ NMSG_WriteFloat(&msg, p2[0]);
+ NMSG_WriteFloat(&msg, p2[1]);
+ NMSG_WriteFloat(&msg, p2[2]);
+ Net_Send(debug_socket, &msg);
+}
+
+/*
+=====================
+DebugNet_DrawMesh
+=====================
+*/
+void DebugNet_DrawMesh(mesh_t *mesh)
+{
+ int i, j;
+ float dot;
+ drawVert_t *v1, *v2, *v3, *v4;
+ winding_t winding;
+ plane_t plane;
+ vec3_t d1, d2;
+
+ for ( i = 0 ; i < mesh->width - 1 ; i++ ) {
+ for ( j = 0 ; j < mesh->height - 1 ; j++ ) {
+
+ v1 = mesh->verts + j * mesh->width + i;
+ v2 = v1 + 1;
+ v3 = v1 + mesh->width + 1;
+ v4 = v1 + mesh->width;
+
+ VectorSubtract( v4->xyz, v1->xyz, d1 );
+ VectorSubtract( v3->xyz, v1->xyz, d2 );
+ CrossProduct( d2, d1, plane.normal );
+ if ( VectorNormalize( plane.normal, plane.normal ) != 0 )
+ {
+ plane.dist = DotProduct( v1->xyz, plane.normal );
+ dot = DotProduct(plane.normal, v2->xyz) - plane.dist;
+ if (fabs(dot) < 0.1)
+ {
+ VectorCopy(v1->xyz, winding.points[0]);
+ VectorCopy(v4->xyz, winding.points[1]);
+ VectorCopy(v3->xyz, winding.points[2]);
+ VectorCopy(v2->xyz, winding.points[3]);
+ winding.numpoints = 4;
+ DebugNet_DrawWinding(&winding, 2);
+ continue;
+ }
+ }
+
+ winding.numpoints = 3;
+ VectorCopy(v1->xyz, winding.points[0]);
+ VectorCopy(v4->xyz, winding.points[1]);
+ VectorCopy(v3->xyz, winding.points[2]);
+ DebugNet_DrawWinding(&winding, 2);
+
+ VectorCopy(v1->xyz, winding.points[0]);
+ VectorCopy(v3->xyz, winding.points[1]);
+ VectorCopy(v2->xyz, winding.points[2]);
+ DebugNet_DrawWinding(&winding, 2);
+ }
+ }
+}
+
+/*
+=====================
+VS_DrawLightVolume
+=====================
+*/
+int VS_ChopWinding (winding_t *in, plane_t *split, float epsilon);
+
+void VS_DrawLightVolume(vsound_t *light, lightvolume_t *volume)
+{
+ winding_t w;
+ int i;
+ vec3_t p2, invsound;
+
+ memcpy(w.points, volume->points, volume->numplanes * sizeof(vec3_t));
+ w.numpoints = volume->numplanes;
+ DebugNet_DrawWinding(&w, 2);
+
+ if (volume->type == VOLUME_DIRECTED)
+ {
+ VectorCopy(light->normal, invsound);
+ VectorInverse(invsound);
+ for (i = 0; i < volume->numplanes; i++)
+ {
+ VectorCopy(volume->points[i], w.points[0]);
+ VectorCopy(volume->points[(i+1) % volume->numplanes], w.points[1]);
+ VectorMA(w.points[1], MAX_WORLD_COORD, invsound, w.points[2]);
+ VectorMA(w.points[0], MAX_WORLD_COORD, invsound, w.points[3]);
+ w.numpoints = 4;
+ DebugNet_DrawWinding(&w, 2);
+ VectorMA(volume->points[i], 8, volume->planes[i].normal, p2);
+ DebugNet_DrawLine(volume->points[i], p2, 3);
+ }
+ }
+ else
+ {
+ //
+ VectorCopy(light->origin, w.points[0]);
+ w.numpoints = 3;
+ for (i = 0; i < volume->numplanes; i++)
+ {
+ VectorCopy(volume->points[i], w.points[1]);
+ VectorCopy(volume->points[(i+1) % volume->numplanes], w.points[2]);
+ VS_ChopWinding(&w, &volume->endplane, 0);
+ DebugNet_DrawWinding(&w, 2);
+ VectorMA(volume->points[i], 8, volume->planes[i].normal, p2);
+ DebugNet_DrawLine(volume->points[i], p2, 3);
+ }
+ }
+}
+
+/*
+=============
+VS_DrawLightmapPixel
+=============
+*/
+void VS_DrawLightmapPixel(int surfaceNum, int x, int y, int color)
+{
+ winding_t w;
+ dsurface_t *ds;
+ mesh_t *mesh;
+
+ ds = &drawSurfaces[surfaceNum];
+
+ if (ds->surfaceType == MST_PATCH)
+ {
+ mesh = lsurfaceTest[surfaceNum]->detailMesh;
+ VectorCopy( mesh->verts[(y-ds->lightmapY)*mesh->width+x-ds->lightmapX].xyz, w.points[0]);
+ VectorCopy( mesh->verts[(y+1-ds->lightmapY)*mesh->width+x-ds->lightmapX].xyz, w.points[1]);
+ VectorCopy( mesh->verts[(y+1-ds->lightmapY)*mesh->width+x+1-ds->lightmapX].xyz, w.points[2]);
+ VectorCopy( mesh->verts[(y-ds->lightmapY)*mesh->width+x+1-ds->lightmapX].xyz, w.points[3]);
+ w.numpoints = 4;
+ }
+ else
+ {
+ VectorMA(ds->lightmapOrigin, (float) x - LIGHTMAP_PIXELSHIFT - ds->lightmapX, ds->lightmapVecs[0], w.points[0]);
+ VectorMA(w.points[0], (float) y - LIGHTMAP_PIXELSHIFT - ds->lightmapY, ds->lightmapVecs[1], w.points[0]);
+ VectorMA(ds->lightmapOrigin, (float) x - LIGHTMAP_PIXELSHIFT - ds->lightmapX, ds->lightmapVecs[0], w.points[1]);
+ VectorMA(w.points[1], (float) y - LIGHTMAP_PIXELSHIFT + 1 - ds->lightmapY, ds->lightmapVecs[1], w.points[1]);
+ VectorMA(ds->lightmapOrigin, (float) x - LIGHTMAP_PIXELSHIFT + 1 - ds->lightmapX, ds->lightmapVecs[0], w.points[2]);
+ VectorMA(w.points[2], (float) y - LIGHTMAP_PIXELSHIFT + 1 - ds->lightmapY, ds->lightmapVecs[1], w.points[2]);
+ VectorMA(ds->lightmapOrigin, (float) x - LIGHTMAP_PIXELSHIFT + 1 - ds->lightmapX, ds->lightmapVecs[0], w.points[3]);
+ VectorMA(w.points[3], (float) y - LIGHTMAP_PIXELSHIFT - ds->lightmapY, ds->lightmapVecs[1], w.points[3]);
+ w.numpoints = 4;
+ }
+ DebugNet_DrawWinding(&w, color);
+}
+
+/*
+============
+VS_DrawPortals
+============
+*/
+void VS_DrawPortals(void)
+{
+ int j;
+ lportal_t *p;
+
+ for (j = 0; j < numportals * 2; j++)
+ {
+ p = portals + j;
+ DebugNet_DrawWinding(p->winding, 1);
+ }
+}
+
+/*
+============
+VS_DrawLeaf
+============
+*/
+void VS_DrawLeaf(int cluster)
+{
+ int i;
+ lleaf_t *leaf;
+ lportal_t *p;
+
+ leaf = &leafs[cluster];
+ for (i = 0; i < leaf->numportals; i++)
+ {
+ p = leaf->portals[i];
+ DebugNet_DrawWinding(p->winding, 1);
+ }
+}
+
+#endif //DEBUGNET
+
+/*
+=============
+VS_SplitWinding
+=============
+*/
+int VS_SplitWinding (winding_t *in, winding_t *back, plane_t *split, float epsilon)
+{
+ vec_t dists[128];
+ int sides[128];
+ int counts[3];
+ vec_t dot;
+ int i, j;
+ vec_t *p1, *p2;
+ vec3_t mid;
+ winding_t out;
+ winding_t *neww;
+
+ counts[0] = counts[1] = counts[2] = 0;
+
+ // determine sides for each point
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ dot = DotProduct (in->points[i], split->normal);
+ dot -= split->dist;
+ dists[i] = dot;
+ if (dot > epsilon)
+ sides[i] = SIDE_FRONT;
+ else if (dot < -epsilon)
+ sides[i] = SIDE_BACK;
+ else
+ {
+ sides[i] = SIDE_ON;
+ }
+ counts[sides[i]]++;
+ }
+
+ if (!counts[SIDE_BACK])
+ {
+ if (!counts[SIDE_FRONT])
+ return SIDE_ON;
+ else
+ return SIDE_FRONT;
+ }
+
+ if (!counts[SIDE_FRONT])
+ {
+ return SIDE_BACK;
+ }
+
+ sides[i] = sides[0];
+ dists[i] = dists[0];
+
+ neww = &out;
+
+ neww->numpoints = 0;
+ back->numpoints = 0;
+
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ p1 = in->points[i];
+
+ if (neww->numpoints >= MAX_POINTS_ON_FIXED_WINDING)
+ {
+ _printf("WARNING: VS_SplitWinding -> MAX_POINTS_ON_FIXED_WINDING overflowed\n");
+ return SIDE_FRONT; // can't chop -- fall back to original
+ }
+ if (back->numpoints >= MAX_POINTS_ON_FIXED_WINDING)
+ {
+ _printf("WARNING: VS_SplitWinding -> MAX_POINTS_ON_FIXED_WINDING overflowed\n");
+ return SIDE_FRONT;
+ }
+
+ if (sides[i] == SIDE_ON)
+ {
+ VectorCopy (p1, neww->points[neww->numpoints]);
+ neww->numpoints++;
+ VectorCopy (p1, back->points[back->numpoints]);
+ back->numpoints++;
+ continue;
+ }
+
+ if (sides[i] == SIDE_FRONT)
+ {
+ VectorCopy (p1, neww->points[neww->numpoints]);
+ neww->numpoints++;
+ }
+ if (sides[i] == SIDE_BACK)
+ {
+ VectorCopy (p1, back->points[back->numpoints]);
+ back->numpoints++;
+ }
+
+ if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i])
+ continue;
+
+ if (neww->numpoints >= MAX_POINTS_ON_FIXED_WINDING)
+ {
+ _printf("WARNING: VS_SplitWinding -> MAX_POINTS_ON_FIXED_WINDING overflowed\n");
+ return SIDE_FRONT; // can't chop -- fall back to original
+ }
+
+ if (back->numpoints >= MAX_POINTS_ON_FIXED_WINDING)
+ {
+ _printf("WARNING: VS_SplitWinding -> MAX_POINTS_ON_FIXED_WINDING overflowed\n");
+ return SIDE_FRONT; // can't chop -- fall back to original
+ }
+
+ // generate a split point
+ p2 = in->points[(i+1)%in->numpoints];
+
+ dot = dists[i] / (dists[i]-dists[i+1]);
+ for (j=0 ; j<3 ; j++)
+ { // avoid round off error when possible
+ if (split->normal[j] == 1)
+ mid[j] = split->dist;
+ else if (split->normal[j] == -1)
+ mid[j] = -split->dist;
+ else
+ mid[j] = p1[j] + dot*(p2[j]-p1[j]);
+ }
+
+ VectorCopy (mid, neww->points[neww->numpoints]);
+ neww->numpoints++;
+ VectorCopy (mid, back->points[back->numpoints]);
+ back->numpoints++;
+ }
+ memcpy(in, &out, sizeof(winding_t));
+
+ return SIDE_CROSS;
+}
+
+/*
+=====================
+VS_LinkSurfaceIntoCluster
+=====================
+*/
+void VS_LinkSurfaceIntoCluster(int cluster, int surfaceNum)
+{
+ lleaf_t *leaf;
+ int i;
+
+ leaf = &leafs[cluster];
+
+ for (i = 0; i < leaf->numSurfaces; i++)
+ {
+ if (clustersurfaces[leaf->firstSurface + i] == surfaceNum)
+ return;
+ }
+ for (i = numclustersurfaces; i > leaf->firstSurface + leaf->numSurfaces; i--)
+ clustersurfaces[i] = clustersurfaces[i-1];
+ for (i = 0; i < portalclusters; i++)
+ {
+ if (i == cluster)
+ continue;
+ if (leafs[i].firstSurface >= leaf->firstSurface + leaf->numSurfaces)
+ leafs[i].firstSurface++;
+ }
+ clustersurfaces[leaf->firstSurface + leaf->numSurfaces] = surfaceNum;
+ leaf->numSurfaces++;
+ numclustersurfaces++;
+ if (numclustersurfaces >= MAX_MAP_LEAFFACES)
+ Error("MAX_MAP_LEAFFACES");
+}
+
+/*
+=====================
+VS_R_LinkSurface
+=====================
+*/
+void VS_R_LinkSurface(int nodenum, int surfaceNum, winding_t *w)
+{
+ int leafnum, cluster, res;
+ dnode_t *node;
+ dplane_t *plane;
+ winding_t back;
+ plane_t split;
+
+ while(nodenum >= 0)
+ {
+ node = &dnodes[nodenum];
+ plane = &dplanes[node->planeNum];
+
+ VectorCopy(plane->normal, split.normal);
+ split.dist = plane->dist;
+ res = VS_SplitWinding (w, &back, &split, 0.1);
+
+ if (res == SIDE_FRONT)
+ {
+ nodenum = node->children[0];
+ }
+ else if (res == SIDE_BACK)
+ {
+ nodenum = node->children[1];
+ }
+ else if (res == SIDE_ON)
+ {
+ memcpy(&back, w, sizeof(winding_t));
+ VS_R_LinkSurface(node->children[1], surfaceNum, &back);
+ nodenum = node->children[0];
+ }
+ else
+ {
+ VS_R_LinkSurface(node->children[1], surfaceNum, &back);
+ nodenum = node->children[0];
+ }
+ }
+ leafnum = -nodenum - 1;
+ cluster = dleafs[leafnum].cluster;
+ if (cluster != -1)
+ {
+ VS_LinkSurfaceIntoCluster(cluster, surfaceNum);
+ }
+}
+
+/*
+=====================
+VS_LinkSurfaces
+
+maybe link each facet seperately instead of the test surfaces?
+=====================
+*/
+void VS_LinkSurfaces(void)
+{
+ int i, j;
+ lsurfaceTest_t *test;
+ lFacet_t *facet;
+ winding_t winding;
+
+ for ( i = 0 ; i < numDrawSurfaces ; i++ )
+ {
+ test = lsurfaceTest[ i ];
+ if (!test)
+ continue;
+ for (j = 0; j < test->numFacets; j++)
+ {
+ facet = &test->facets[j];
+ memcpy(winding.points, facet->points, facet->numpoints * sizeof(vec3_t));
+ winding.numpoints = facet->numpoints;
+ VS_R_LinkSurface(0, i, &winding);
+ }
+ }
+}
+
+/*
+=====================
+VS_TextureMatrixFromPoints
+=====================
+*/
+void VS_TextureMatrixFromPoints( lFacet_t *f, drawVert_t *a, drawVert_t *b, drawVert_t *c ) {
+ int i, j;
+ float t;
+ float m[3][4];
+ float s;
+
+ // This is an incredibly stupid way of solving a three variable equation
+ for ( i = 0 ; i < 2 ; i++ ) {
+
+ m[0][0] = a->xyz[0];
+ m[0][1] = a->xyz[1];
+ m[0][2] = a->xyz[2];
+ m[0][3] = a->st[i];
+
+ m[1][0] = b->xyz[0];
+ m[1][1] = b->xyz[1];
+ m[1][2] = b->xyz[2];
+ m[1][3] = b->st[i];
+
+ m[2][0] = c->xyz[0];
+ m[2][1] = c->xyz[1];
+ m[2][2] = c->xyz[2];
+ m[2][3] = c->st[i];
+
+ if ( fabs(m[1][0]) > fabs(m[0][0]) && fabs(m[1][0]) > fabs(m[2][0]) ) {
+ for ( j = 0 ; j < 4 ; j ++ ) {
+ t = m[0][j];
+ m[0][j] = m[1][j];
+ m[1][j] = t;
+ }
+ } else if ( fabs(m[2][0]) > fabs(m[0][0]) && fabs(m[2][0]) > fabs(m[1][0]) ) {
+ for ( j = 0 ; j < 4 ; j ++ ) {
+ t = m[0][j];
+ m[0][j] = m[2][j];
+ m[2][j] = t;
+ }
+ }
+
+ s = 1.0 / m[0][0];
+ m[0][0] *= s;
+ m[0][1] *= s;
+ m[0][2] *= s;
+ m[0][3] *= s;
+
+ s = m[1][0];
+ m[1][0] -= m[0][0] * s;
+ m[1][1] -= m[0][1] * s;
+ m[1][2] -= m[0][2] * s;
+ m[1][3] -= m[0][3] * s;
+
+ s = m[2][0];
+ m[2][0] -= m[0][0] * s;
+ m[2][1] -= m[0][1] * s;
+ m[2][2] -= m[0][2] * s;
+ m[2][3] -= m[0][3] * s;
+
+ if ( fabs(m[2][1]) > fabs(m[1][1]) ) {
+ for ( j = 0 ; j < 4 ; j ++ ) {
+ t = m[1][j];
+ m[1][j] = m[2][j];
+ m[2][j] = t;
+ }
+ }
+
+ s = 1.0 / m[1][1];
+ m[1][0] *= s;
+ m[1][1] *= s;
+ m[1][2] *= s;
+ m[1][3] *= s;
+
+ s = m[2][1];// / m[1][1];
+ m[2][0] -= m[1][0] * s;
+ m[2][1] -= m[1][1] * s;
+ m[2][2] -= m[1][2] * s;
+ m[2][3] -= m[1][3] * s;
+
+ s = 1.0 / m[2][2];
+ m[2][0] *= s;
+ m[2][1] *= s;
+ m[2][2] *= s;
+ m[2][3] *= s;
+
+ f->textureMatrix[i][2] = m[2][3];
+ f->textureMatrix[i][1] = m[1][3] - f->textureMatrix[i][2] * m[1][2];
+ f->textureMatrix[i][0] = m[0][3] - f->textureMatrix[i][2] * m[0][2] - f->textureMatrix[i][1] * m[0][1];
+
+ f->textureMatrix[i][3] = 0;
+/*
+ s = fabs( DotProduct( a->xyz, f->textureMatrix[i] ) - a->st[i] );
+ if ( s > 0.01 ) {
+ Error( "Bad textureMatrix" );
+ }
+ s = fabs( DotProduct( b->xyz, f->textureMatrix[i] ) - b->st[i] );
+ if ( s > 0.01 ) {
+ Error( "Bad textureMatrix" );
+ }
+ s = fabs( DotProduct( c->xyz, f->textureMatrix[i] ) - c->st[i] );
+ if ( s > 0.01 ) {
+ Error( "Bad textureMatrix" );
+ }
+*/
+ }
+}
+
+/*
+=====================
+VS_LightmapMatrixFromPoints
+=====================
+*/
+void VS_LightmapMatrixFromPoints( dsurface_t *dsurf, shaderInfo_t *si, lFacet_t *f, drawVert_t *a, drawVert_t *b, drawVert_t *c ) {
+ int i, j;
+ float t;
+ float m[3][4], al, bl, cl;
+ float s;
+ int h, w, ssize;
+ vec3_t mins, maxs, delta, size, planeNormal;
+ drawVert_t *verts;
+ static int message;
+
+ // vertex-lit triangle model
+ if ( dsurf->surfaceType == MST_TRIANGLE_SOUP ) {
+ return;
+ }
+
+ if ( dsurf->lightmapNum < 0 ) {
+ return; // doesn't need lighting
+ }
+
+ VectorClear(f->mins);
+ if (dsurf->surfaceType != MST_PATCH)
+ {
+ ssize = samplesize;
+ if (si->lightmapSampleSize)
+ ssize = si->lightmapSampleSize;
+ ClearBounds( mins, maxs );
+ verts = &drawVerts[dsurf->firstVert];
+ for ( i = 0 ; i < dsurf->numVerts ; i++ ) {
+ AddPointToBounds( verts[i].xyz, mins, maxs );
+ }
+ // round to the lightmap resolution
+ for ( i = 0 ; i < 3 ; i++ ) {
+ mins[i] = ssize * floor( mins[i] / ssize );
+ maxs[i] = ssize * ceil( maxs[i] / ssize );
+ f->mins[i] = mins[i];
+ size[i] = (maxs[i] - mins[i]) / ssize + 1;
+ }
+ // the two largest axis will be the lightmap size
+ VectorClear(f->lightmapMatrix[0]);
+ f->lightmapMatrix[0][3] = 0;
+ VectorClear(f->lightmapMatrix[1]);
+ f->lightmapMatrix[1][3] = 0;
+
+ planeNormal[0] = fabs( dsurf->lightmapVecs[2][0] );
+ planeNormal[1] = fabs( dsurf->lightmapVecs[2][1] );
+ planeNormal[2] = fabs( dsurf->lightmapVecs[2][2] );
+
+ if ( planeNormal[0] >= planeNormal[1] && planeNormal[0] >= planeNormal[2] ) {
+ w = size[1];
+ h = size[2];
+ f->lightmapMatrix[0][1] = 1.0 / ssize;
+ f->lightmapMatrix[1][2] = 1.0 / ssize;
+ } else if ( planeNormal[1] >= planeNormal[0] && planeNormal[1] >= planeNormal[2] ) {
+ w = size[0];
+ h = size[2];
+ f->lightmapMatrix[0][0] = 1.0 / ssize;
+ f->lightmapMatrix[1][2] = 1.0 / ssize;
+ } else {
+ w = size[0];
+ h = size[1];
+ f->lightmapMatrix[0][0] = 1.0 / ssize;
+ f->lightmapMatrix[1][1] = 1.0 / ssize;
+ }
+ if ( w > LIGHTMAP_WIDTH ) {
+ VectorScale ( f->lightmapMatrix[0], (float)LIGHTMAP_SIZE/w, f->lightmapMatrix[0] );
+ }
+
+ if ( h > LIGHTMAP_HEIGHT ) {
+ VectorScale ( f->lightmapMatrix[1], (float)LIGHTMAP_SIZE/h, f->lightmapMatrix[1] );
+ }
+ VectorSubtract(a->xyz, f->mins, delta);
+ s = (DotProduct( delta, f->lightmapMatrix[0] ) + dsurf->lightmapX + 0.5) / LIGHTMAP_SIZE;
+ if ( fabs(s - a->lightmap[0]) > 0.01 ) {
+ _printf( "Bad lightmapMatrix" );
+ }
+ t = (DotProduct( delta, f->lightmapMatrix[1] ) + dsurf->lightmapY + 0.5) / LIGHTMAP_SIZE;
+ if ( fabs(t - a->lightmap[1]) > 0.01 ) {
+ _printf( "Bad lightmapMatrix" );
+ }
+ VectorSubtract(b->xyz, f->mins, delta);
+ s = (DotProduct( delta, f->lightmapMatrix[0] ) + dsurf->lightmapX + 0.5) / LIGHTMAP_SIZE;
+ if ( fabs(s - b->lightmap[0]) > 0.01 ) {
+ _printf( "Bad lightmapMatrix" );
+ }
+ t = (DotProduct( delta, f->lightmapMatrix[1] ) + dsurf->lightmapY + 0.5) / LIGHTMAP_SIZE;
+ if ( fabs(t - b->lightmap[1]) > 0.01 ) {
+ _printf( "Bad lightmapMatrix" );
+ }
+ VectorSubtract(c->xyz, f->mins, delta);
+ s = (DotProduct( delta, f->lightmapMatrix[0] ) + dsurf->lightmapX + 0.5) / LIGHTMAP_SIZE;
+ if ( fabs(s - c->lightmap[0]) > 0.01 ) {
+ _printf( "Bad lightmapMatrix" );
+ }
+ t = (DotProduct( delta, f->lightmapMatrix[1] ) + dsurf->lightmapY + 0.5) / LIGHTMAP_SIZE;
+ if ( fabs(t - c->lightmap[1]) > 0.01 ) {
+ _printf( "Bad lightmapMatrix" );
+ }
+ VectorAdd(f->mins, surfaceOrigin[dsurf - drawSurfaces], f->mins);
+ return;
+ }
+ // This is an incredibly stupid way of solving a three variable equation
+ for ( i = 0 ; i < 2 ; i++ ) {
+
+ if (i)
+ al = a->lightmap[i] - ((float) dsurf->lightmapY + 0.5) / LIGHTMAP_SIZE;
+ else
+ al = a->lightmap[i] - ((float) dsurf->lightmapX + 0.5) / LIGHTMAP_SIZE;
+
+ m[0][0] = a->xyz[0] - f->mins[0];
+ m[0][1] = a->xyz[1] - f->mins[1];
+ m[0][2] = a->xyz[2] - f->mins[2];
+ m[0][3] = al;
+
+ if (i)
+ bl = b->lightmap[i] - ((float) dsurf->lightmapY + 0.5) / LIGHTMAP_SIZE;
+ else
+ bl = b->lightmap[i] - ((float) dsurf->lightmapX + 0.5) / LIGHTMAP_SIZE;
+
+ m[1][0] = b->xyz[0] - f->mins[0];
+ m[1][1] = b->xyz[1] - f->mins[1];
+ m[1][2] = b->xyz[2] - f->mins[2];
+ m[1][3] = bl;
+
+ if (i)
+ cl = c->lightmap[i] - ((float) dsurf->lightmapY + 0.5) / LIGHTMAP_SIZE;
+ else
+ cl = c->lightmap[i] - ((float) dsurf->lightmapX + 0.5) / LIGHTMAP_SIZE;
+
+ m[2][0] = c->xyz[0] - f->mins[0];
+ m[2][1] = c->xyz[1] - f->mins[1];
+ m[2][2] = c->xyz[2] - f->mins[2];
+ m[2][3] = cl;
+
+ if ( fabs(m[1][0]) > fabs(m[0][0]) && fabs(m[1][0]) >= fabs(m[2][0]) ) {
+ for ( j = 0 ; j < 4 ; j ++ ) {
+ t = m[0][j];
+ m[0][j] = m[1][j];
+ m[1][j] = t;
+ }
+ } else if ( fabs(m[2][0]) > fabs(m[0][0]) && fabs(m[2][0]) >= fabs(m[1][0]) ) {
+ for ( j = 0 ; j < 4 ; j ++ ) {
+ t = m[0][j];
+ m[0][j] = m[2][j];
+ m[2][j] = t;
+ }
+ }
+
+ if (m[0][0])
+ {
+ s = 1.0 / m[0][0];
+ m[0][0] *= s;
+ m[0][1] *= s;
+ m[0][2] *= s;
+ m[0][3] *= s;
+
+ s = m[1][0];
+ m[1][0] -= m[0][0] * s;
+ m[1][1] -= m[0][1] * s;
+ m[1][2] -= m[0][2] * s;
+ m[1][3] -= m[0][3] * s;
+
+ s = m[2][0];
+ m[2][0] -= m[0][0] * s;
+ m[2][1] -= m[0][1] * s;
+ m[2][2] -= m[0][2] * s;
+ m[2][3] -= m[0][3] * s;
+ }
+
+ if ( fabs(m[2][1]) > fabs(m[1][1]) ) {
+ for ( j = 0 ; j < 4 ; j ++ ) {
+ t = m[1][j];
+ m[1][j] = m[2][j];
+ m[2][j] = t;
+ }
+ }
+
+ if (m[1][1])
+ {
+ s = 1.0 / m[1][1];
+ m[1][0] *= s;
+ m[1][1] *= s;
+ m[1][2] *= s;
+ m[1][3] *= s;
+
+ s = m[2][1];
+ m[2][0] -= m[1][0] * s;
+ m[2][1] -= m[1][1] * s;
+ m[2][2] -= m[1][2] * s;
+ m[2][3] -= m[1][3] * s;
+ }
+
+ if (m[2][2])
+ {
+ s = 1.0 / m[2][2];
+ m[2][0] *= s;
+ m[2][1] *= s;
+ m[2][2] *= s;
+ m[2][3] *= s;
+ }
+
+ f->lightmapMatrix[i][2] = m[2][3];
+ f->lightmapMatrix[i][1] = m[1][3] - f->lightmapMatrix[i][2] * m[1][2];
+ f->lightmapMatrix[i][0] = m[0][3] - f->lightmapMatrix[i][2] * m[0][2] - f->lightmapMatrix[i][1] * m[0][1];
+
+ f->lightmapMatrix[i][3] = 0;
+
+ VectorSubtract(a->xyz, f->mins, delta);
+ s = fabs( DotProduct( delta, f->lightmapMatrix[i] ) - al );
+ if ( s > 0.01 ) {
+ if (!message)
+ _printf( "Bad lightmapMatrix\n" );
+ message = qtrue;
+ }
+ VectorSubtract(b->xyz, f->mins, delta);
+ s = fabs( DotProduct( delta, f->lightmapMatrix[i] ) - bl );
+ if ( s > 0.01 ) {
+ if (!message)
+ _printf( "Bad lightmapMatrix\n" );
+ message = qtrue;
+ }
+ VectorSubtract(c->xyz, f->mins, delta);
+ s = fabs( DotProduct( delta, f->lightmapMatrix[i] ) - cl );
+ if ( s > 0.01 ) {
+ if (!message)
+ _printf( "Bad lightmapMatrix\n" );
+ message = qtrue;
+ }
+ VectorAdd(f->mins, surfaceOrigin[dsurf - drawSurfaces], f->mins);
+ }
+}
+
+/*
+=============
+Plane_Equal
+=============
+*/
+#define NORMAL_EPSILON 0.0001
+#define DIST_EPSILON 0.02
+
+static int Plane_Equal(plane_t *a, plane_t *b, int flip)
+{
+ vec3_t normal;
+ float dist;
+
+ if (flip) {
+ normal[0] = - b->normal[0];
+ normal[1] = - b->normal[1];
+ normal[2] = - b->normal[2];
+ dist = - b->dist;
+ }
+ else {
+ normal[0] = b->normal[0];
+ normal[1] = b->normal[1];
+ normal[2] = b->normal[2];
+ dist = b->dist;
+ }
+ if (
+ fabs(a->normal[0] - normal[0]) < NORMAL_EPSILON
+ && fabs(a->normal[1] - normal[1]) < NORMAL_EPSILON
+ && fabs(a->normal[2] - normal[2]) < NORMAL_EPSILON
+ && fabs(a->dist - dist) < DIST_EPSILON )
+ return qtrue;
+ return qfalse;
+}
+
+/*
+=============
+VS_PlaneFromPoints
+=============
+*/
+qboolean VS_PlaneFromPoints( plane_t *plane, const vec3_t a, const vec3_t b, const vec3_t c ) {
+ vec3_t d1, d2;
+
+ VectorSubtract( b, a, d1 );
+ VectorSubtract( c, a, d2 );
+ CrossProduct( d2, d1, plane->normal );
+ if ( VectorNormalize( plane->normal, plane->normal ) == 0 ) {
+ return qfalse;
+ }
+
+ plane->dist = DotProduct( a, plane->normal );
+ return qtrue;
+}
+
+/*
+=====================
+VS_GenerateBoundaryForPoints
+=====================
+*/
+void VS_GenerateBoundaryForPoints( plane_t *boundary, plane_t *plane, vec3_t a, vec3_t b ) {
+ vec3_t d1;
+
+ // make a perpendicular vector to the edge and the surface
+ VectorSubtract( a, b, d1 );
+ CrossProduct( plane->normal, d1, boundary->normal );
+ VectorNormalize( boundary->normal, boundary->normal );
+ boundary->dist = DotProduct( a, boundary->normal );
+}
+
+/*
+=====================
+VS_GenerateFacetFor3Points
+=====================
+*/
+qboolean VS_GenerateFacetFor3Points( dsurface_t *dsurf, shaderInfo_t *si, lFacet_t *f, drawVert_t *a, drawVert_t *b, drawVert_t *c ) {
+ //
+ vec3_t dir;
+ int i;
+
+ // if we can't generate a valid plane for the points, ignore the facet
+ if ( !VS_PlaneFromPoints( &f->plane, a->xyz, b->xyz, c->xyz ) ) {
+ f->numpoints = 0;
+ return qfalse;
+ }
+
+ f->num = numfacets++;
+
+ VectorAdd( a->xyz, surfaceOrigin[dsurf - drawSurfaces], f->points[0] );
+ VectorAdd( b->xyz, surfaceOrigin[dsurf - drawSurfaces], f->points[1] );
+ VectorAdd( c->xyz, surfaceOrigin[dsurf - drawSurfaces], f->points[2] );
+
+ f->lightmapCoords[0][0] = a->lightmap[0];
+ f->lightmapCoords[0][1] = a->lightmap[1];
+ f->lightmapCoords[1][0] = b->lightmap[0];
+ f->lightmapCoords[1][1] = b->lightmap[1];
+ f->lightmapCoords[2][0] = c->lightmap[0];
+ f->lightmapCoords[2][1] = c->lightmap[1];
+
+ VS_GenerateBoundaryForPoints( &f->boundaries[0], &f->plane, f->points[0], f->points[1] );
+ VS_GenerateBoundaryForPoints( &f->boundaries[1], &f->plane, f->points[1], f->points[2] );
+ VS_GenerateBoundaryForPoints( &f->boundaries[2], &f->plane, f->points[2], f->points[0] );
+
+ for (i = 0; i < 3; i++)
+ {
+ VectorSubtract(f->points[(i+1)%3], f->points[i], dir);
+ if (VectorLength(dir) < 0.1)
+ return qfalse;
+ }
+
+ VS_TextureMatrixFromPoints( f, a, b, c );
+ VS_LightmapMatrixFromPoints( dsurf, si, f, a, b, c );
+
+ f->numpoints = 3;
+
+ return qtrue;
+}
+
+/*
+=====================
+VS_GenerateFacetFor4Points
+
+Attempts to use four points as a planar quad
+=====================
+*/
+#define PLANAR_EPSILON 0.1
+qboolean VS_GenerateFacetFor4Points( dsurface_t *dsurf, shaderInfo_t *si, lFacet_t *f, drawVert_t *a, drawVert_t *b, drawVert_t *c, drawVert_t *d ) {
+ float dist;
+ vec3_t dir;
+ int i;
+ plane_t plane;
+
+ // if we can't generate a valid plane for the points, ignore the facet
+ if ( !VS_PlaneFromPoints( &f->plane, a->xyz, b->xyz, c->xyz ) ) {
+ f->numpoints = 0;
+ return qfalse;
+ }
+
+ // if the fourth point is also on the plane, we can make a quad facet
+ dist = DotProduct( d->xyz, f->plane.normal ) - f->plane.dist;
+ if ( fabs( dist ) > PLANAR_EPSILON ) {
+ f->numpoints = 0;
+ return qfalse;
+ }
+
+ VectorAdd( a->xyz, surfaceOrigin[dsurf - drawSurfaces], f->points[0] );
+ VectorAdd( b->xyz, surfaceOrigin[dsurf - drawSurfaces], f->points[1] );
+ VectorAdd( c->xyz, surfaceOrigin[dsurf - drawSurfaces], f->points[2] );
+ VectorAdd( d->xyz, surfaceOrigin[dsurf - drawSurfaces], f->points[3] );
+
+ for (i = 1; i < 4; i++)
+ {
+ if ( !VS_PlaneFromPoints( &plane, f->points[i], f->points[(i+1) % 4], f->points[(i+2) % 4]) ) {
+ f->numpoints = 0;
+ return qfalse;
+ }
+
+ if (!Plane_Equal(&f->plane, &plane, qfalse)) {
+ f->numpoints = 0;
+ return qfalse;
+ }
+ }
+
+ f->lightmapCoords[0][0] = a->lightmap[0];
+ f->lightmapCoords[0][1] = a->lightmap[1];
+ f->lightmapCoords[1][0] = b->lightmap[0];
+ f->lightmapCoords[1][1] = b->lightmap[1];
+ f->lightmapCoords[2][0] = c->lightmap[0];
+ f->lightmapCoords[2][1] = c->lightmap[1];
+ f->lightmapCoords[3][0] = d->lightmap[0];
+ f->lightmapCoords[3][1] = d->lightmap[1];
+
+ VS_GenerateBoundaryForPoints( &f->boundaries[0], &f->plane, f->points[0], f->points[1] );
+ VS_GenerateBoundaryForPoints( &f->boundaries[1], &f->plane, f->points[1], f->points[2] );
+ VS_GenerateBoundaryForPoints( &f->boundaries[2], &f->plane, f->points[2], f->points[3] );
+ VS_GenerateBoundaryForPoints( &f->boundaries[3], &f->plane, f->points[3], f->points[0] );
+
+ for (i = 0; i < 4; i++)
+ {
+ VectorSubtract(f->points[(i+1)%4], f->points[i], dir);
+ if (VectorLength(dir) < 0.1)
+ return qfalse;
+ }
+
+ VS_TextureMatrixFromPoints( f, a, b, c );
+ VS_LightmapMatrixFromPoints( dsurf, si, f, a, b, c );
+
+ f->num = numfacets++;
+ f->numpoints = 4;
+
+ return qtrue;
+}
+
+/*
+===============
+VS_SphereFromBounds
+===============
+*/
+void VS_SphereFromBounds( vec3_t mins, vec3_t maxs, vec3_t origin, float *radius ) {
+ vec3_t temp;
+
+ VectorAdd( mins, maxs, origin );
+ VectorScale( origin, 0.5, origin );
+ VectorSubtract( maxs, origin, temp );
+ *radius = VectorLength( temp );
+}
+
+/*
+====================
+VS_FacetsForTriangleSurface
+====================
+*/
+void VS_FacetsForTriangleSurface( dsurface_t *dsurf, shaderInfo_t *si, lsurfaceTest_t *test ) {
+ int i;
+ drawVert_t *v1, *v2, *v3, *v4;
+ int count;
+ int i1, i2, i3, i4, i5, i6;
+
+ test->patch = qfalse;
+ if (dsurf->surfaceType == MST_TRIANGLE_SOUP)
+ test->trisoup = qtrue;
+ else
+ test->trisoup = qfalse;
+ test->numFacets = dsurf->numIndexes / 3;
+ test->facets = malloc( sizeof( test->facets[0] ) * test->numFacets );
+ test->shader = si;
+
+ count = 0;
+ for ( i = 0 ; i < test->numFacets ; i++ ) {
+ i1 = drawIndexes[ dsurf->firstIndex + i*3 ];
+ i2 = drawIndexes[ dsurf->firstIndex + i*3 + 1 ];
+ i3 = drawIndexes[ dsurf->firstIndex + i*3 + 2 ];
+
+ v1 = &drawVerts[ dsurf->firstVert + i1 ];
+ v2 = &drawVerts[ dsurf->firstVert + i2 ];
+ v3 = &drawVerts[ dsurf->firstVert + i3 ];
+
+ // try and make a quad out of two triangles
+ if ( i != test->numFacets - 1 ) {
+ i4 = drawIndexes[ dsurf->firstIndex + i*3 + 3 ];
+ i5 = drawIndexes[ dsurf->firstIndex + i*3 + 4 ];
+ i6 = drawIndexes[ dsurf->firstIndex + i*3 + 5 ];
+ if ( i4 == i3 && i5 == i2 ) {
+ v4 = &drawVerts[ dsurf->firstVert + i6 ];
+ if ( VS_GenerateFacetFor4Points( dsurf, si, &test->facets[count], v1, v2, v4, v3 ) ) {
+ count++;
+ i++; // skip next tri
+ continue;
+ }
+ }
+ }
+
+ if (VS_GenerateFacetFor3Points( dsurf, si, &test->facets[count], v1, v2, v3 )) {
+ count++;
+ }
+ }
+
+ // we may have turned some pairs into quads
+ test->numFacets = count;
+}
+
+/*
+====================
+VS_FacetsForPatch
+====================
+*/
+void VS_FacetsForPatch( dsurface_t *dsurf, int surfaceNum, shaderInfo_t *si, lsurfaceTest_t *test ) {
+ int i, j, x, y;
+ drawVert_t *v1, *v2, *v3, *v4;
+ int count, ssize;
+ mesh_t mesh;
+ mesh_t *subdivided, *detailmesh, *newmesh;
+ int widthtable[LIGHTMAP_SIZE], heighttable[LIGHTMAP_SIZE];
+
+ mesh.width = dsurf->patchWidth;
+ mesh.height = dsurf->patchHeight;
+ mesh.verts = &drawVerts[ dsurf->firstVert ];
+
+ newmesh = SubdivideMesh( mesh, 8, 999 );
+ PutMeshOnCurve( *newmesh );
+ MakeMeshNormals( *newmesh );
+
+ subdivided = RemoveLinearMeshColumnsRows( newmesh );
+ FreeMesh(newmesh);
+
+ // DebugNet_RemoveAllPolys();
+ // DebugNet_DrawMesh(subdivided);
+
+ ssize = samplesize;
+ if (si->lightmapSampleSize)
+ ssize = si->lightmapSampleSize;
+
+ if ( dsurf->lightmapNum >= 0 ) {
+
+ detailmesh = SubdivideMeshQuads( subdivided, ssize, LIGHTMAP_SIZE, widthtable, heighttable);
+ test->detailMesh = detailmesh;
+
+ // DebugNet_RemoveAllPolys();
+ // DebugNet_DrawMesh(detailmesh);
+
+ if ( detailmesh->width != dsurf->lightmapWidth || detailmesh->height != dsurf->lightmapHeight ) {
+ Error( "Mesh lightmap miscount");
+ }
+ }
+ else {
+ test->detailMesh = NULL;
+ memset(widthtable, 0, sizeof(widthtable));
+ memset(heighttable, 0, sizeof(heighttable));
+ }
+
+ test->patch = qtrue;
+ test->trisoup = qfalse;
+ test->numFacets = ( subdivided->width - 1 ) * ( subdivided->height - 1 ) * 2;
+ test->facets = malloc( sizeof( test->facets[0] ) * test->numFacets );
+ test->shader = si;
+
+ count = 0;
+ x = 0;
+ for ( i = 0 ; i < subdivided->width - 1 ; i++ ) {
+ y = 0;
+ for ( j = 0 ; j < subdivided->height - 1 ; j++ ) {
+
+ v1 = subdivided->verts + j * subdivided->width + i;
+ v2 = v1 + 1;
+ v3 = v1 + subdivided->width + 1;
+ v4 = v1 + subdivided->width;
+
+ if ( VS_GenerateFacetFor4Points( dsurf, si, &test->facets[count], v1, v4, v3, v2 ) ) {
+ test->facets[count].x = x;
+ test->facets[count].y = y;
+ test->facets[count].width = widthtable[i];
+ test->facets[count].height = heighttable[j];
+ count++;
+ } else {
+ if (VS_GenerateFacetFor3Points( dsurf, si, &test->facets[count], v1, v4, v3 )) {
+ test->facets[count].x = x;
+ test->facets[count].y = y;
+ test->facets[count].width = widthtable[i];
+ test->facets[count].height = heighttable[j];
+ count++;
+ }
+ if (VS_GenerateFacetFor3Points( dsurf, si, &test->facets[count], v1, v3, v2 )) {
+ test->facets[count].x = x;
+ test->facets[count].y = y;
+ test->facets[count].width = widthtable[i];
+ test->facets[count].height = heighttable[j];
+ count++;
+ }
+ }
+ y += heighttable[j];
+ }
+ x += widthtable[i];
+ }
+ test->numFacets = count;
+
+ FreeMesh(subdivided);
+}
+
+/*
+=====================
+VS_InitSurfacesForTesting
+=====================
+*/
+void VS_InitSurfacesForTesting( void ) {
+
+ int i, j, k;
+ dsurface_t *dsurf;
+ lsurfaceTest_t *test;
+ shaderInfo_t *si;
+ lFacet_t *facet;
+
+ for ( i = 0 ; i < numDrawSurfaces ; i++ ) {
+ // don't light the entity surfaces with vsound
+ if ( entitySurface[i] )
+ continue;
+ //
+ dsurf = &drawSurfaces[ i ];
+ if ( !dsurf->numIndexes && !dsurf->patchWidth ) {
+ continue;
+ }
+
+ si = ShaderInfoForShader( dshaders[ dsurf->shaderNum].shader );
+ // if the surface is translucent and does not cast an alpha shadow
+ if ( (si->contents & CONTENTS_TRANSLUCENT) && !(si->surfaceFlags & SURF_ALPHASHADOW) ) {
+ // if the surface has no lightmap
+ if ( dsurf->lightmapNum < 0 )
+ continue;
+ }
+
+ test = malloc( sizeof( *test ) );
+ memset(test, 0, sizeof( *test ));
+ test->mutex = MutexAlloc();
+ test->numvolumes = 0;
+ if (si->forceTraceLight)
+ test->always_tracelight = qtrue;
+ else if (si->forceVLight)
+ test->always_vsound = qtrue;
+ lsurfaceTest[i] = test;
+
+ if ( dsurf->surfaceType == MST_TRIANGLE_SOUP || dsurf->surfaceType == MST_PLANAR ) {
+ VS_FacetsForTriangleSurface( dsurf, si, test );
+ } else if ( dsurf->surfaceType == MST_PATCH ) {
+ VS_FacetsForPatch( dsurf, i, si, test );
+ }
+ if (numfacets >= MAX_FACETS)
+ Error("numfacets >= MAX_FACETS (%d)", MAX_FACETS);
+
+ ClearBounds( test->mins, test->maxs );
+ for (j = 0; j < test->numFacets; j++)
+ {
+ facet = &test->facets[j];
+ for ( k = 0 ; k < facet->numpoints; k++) {
+ AddPointToBounds( facet->points[k], test->mins, test->maxs );
+ }
+ }
+ VS_SphereFromBounds( test->mins, test->maxs, test->origin, &test->radius );
+ }
+ _printf("%6d facets\n", numfacets);
+ _printf("linking surfaces...\n");
+ VS_LinkSurfaces();
+}
+
+/*
+=============
+VS_ChopWinding
+=============
+*/
+int VS_ChopWinding (winding_t *in, plane_t *split, float epsilon)
+{
+ vec_t dists[128];
+ int sides[128];
+ int counts[3];
+ vec_t dot;
+ int i, j;
+ vec_t *p1, *p2;
+ vec3_t mid;
+ winding_t out;
+ winding_t *neww;
+
+ counts[0] = counts[1] = counts[2] = 0;
+
+ // determine sides for each point
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ dot = DotProduct (in->points[i], split->normal);
+ dot -= split->dist;
+ dists[i] = dot;
+ if (dot > epsilon)
+ sides[i] = SIDE_FRONT;
+ else if (dot < -epsilon)
+ sides[i] = SIDE_BACK;
+ else
+ {
+ sides[i] = SIDE_ON;
+ }
+ counts[sides[i]]++;
+ }
+
+ if (!counts[SIDE_BACK])
+ {
+ if (!counts[SIDE_FRONT])
+ return SIDE_ON;
+ else
+ return SIDE_FRONT;
+ }
+
+ if (!counts[SIDE_FRONT])
+ {
+ return SIDE_BACK;
+ }
+
+ sides[i] = sides[0];
+ dists[i] = dists[0];
+
+ neww = &out;
+
+ neww->numpoints = 0;
+
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ p1 = in->points[i];
+
+ if (neww->numpoints >= MAX_POINTS_ON_FIXED_WINDING)
+ {
+ _printf("WARNING: VS_ChopWinding -> MAX_POINTS_ON_FIXED_WINDING overflowed\n");
+ return SIDE_FRONT; // can't chop -- fall back to original
+ }
+
+ if (sides[i] == SIDE_ON)
+ {
+ VectorCopy (p1, neww->points[neww->numpoints]);
+ neww->numpoints++;
+ continue;
+ }
+
+ if (sides[i] == SIDE_FRONT)
+ {
+ VectorCopy (p1, neww->points[neww->numpoints]);
+ neww->numpoints++;
+ }
+
+ if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i])
+ continue;
+
+ if (neww->numpoints >= MAX_POINTS_ON_FIXED_WINDING)
+ {
+ _printf("WARNING: VS_ChopWinding -> MAX_POINTS_ON_FIXED_WINDING overflowed\n");
+ return SIDE_FRONT; // can't chop -- fall back to original
+ }
+
+ // generate a split point
+ p2 = in->points[(i+1)%in->numpoints];
+
+ dot = dists[i] / (dists[i]-dists[i+1]);
+ for (j=0 ; j<3 ; j++)
+ { // avoid round off error when possible
+ if (split->normal[j] == 1)
+ mid[j] = split->dist;
+ else if (split->normal[j] == -1)
+ mid[j] = -split->dist;
+ else
+ mid[j] = p1[j] + dot*(p2[j]-p1[j]);
+ }
+
+ VectorCopy (mid, neww->points[neww->numpoints]);
+ neww->numpoints++;
+ }
+ memcpy(in, &out, sizeof(winding_t));
+
+ return SIDE_CROSS;
+}
+
+/*
+=============
+VS_ChopWindingWithBrush
+
+ returns all winding fragments outside the brush
+=============
+*/
+int VS_ChopWindingWithBrush(winding_t *w, dbrush_t *brush, winding_t *outwindings, int maxout)
+{
+ int i, res, numout;
+ winding_t front, back;
+ plane_t plane;
+
+ numout = 0;
+ memcpy(front.points, w->points, w->numpoints * sizeof(vec3_t));
+ front.numpoints = w->numpoints;
+ for (i = 0; i < brush->numSides; i++)
+ {
+ VectorCopy(dplanes[ dbrushsides[ brush->firstSide + i ].planeNum ].normal, plane.normal);
+ VectorInverse(plane.normal);
+ plane.dist = -dplanes[ dbrushsides[ brush->firstSide + i ].planeNum ].dist;
+ res = VS_SplitWinding(&front, &back, &plane, 0.1);
+ if (res == SIDE_BACK || res == SIDE_ON)
+ {
+ memcpy(outwindings[0].points, w->points, w->numpoints * sizeof(vec3_t));
+ outwindings[0].numpoints = w->numpoints;
+ return 1; //did not intersect
+ }
+ if (res != SIDE_FRONT)
+ {
+ if (numout >= maxout)
+ {
+ _printf("WARNING: VS_ChopWindingWithBrush: more than %d windings\n", maxout);
+ return 0;
+ }
+ memcpy(outwindings[numout].points, back.points, back.numpoints * sizeof(vec3_t));
+ outwindings[numout].numpoints = back.numpoints;
+ numout++;
+ }
+ }
+ return numout;
+}
+
+/*
+=============
+VS_WindingAreaOutsideBrushes
+=============
+*/
+float VS_WindingAreaOutsideBrushes(winding_t *w, int *brushnums, int numbrushes)
+{
+ int i, j, numwindings[2], n;
+ winding_t windingsbuf[2][64];
+ dbrush_t *brush;
+ float area;
+
+ memcpy(windingsbuf[0][0].points, w->points, w->numpoints * sizeof(vec3_t));
+ windingsbuf[0][0].numpoints = w->numpoints;
+ numwindings[0] = 1;
+ for (i = 0; i < numbrushes; i++)
+ {
+ brush = &dbrushes[brushnums[i]];
+ if (!(dshaders[brush->shaderNum].contentFlags & (
+ CONTENTS_LAVA
+ | CONTENTS_SLIME
+ | CONTENTS_WATER
+ | CONTENTS_FOG
+ | CONTENTS_AREAPORTAL
+ | CONTENTS_PLAYERCLIP
+ | CONTENTS_MONSTERCLIP
+ | CONTENTS_CLUSTERPORTAL
+ | CONTENTS_DONOTENTER
+ | CONTENTS_BODY
+ | CONTENTS_CORPSE
+ | CONTENTS_TRANSLUCENT
+ | CONTENTS_TRIGGER
+ | CONTENTS_NODROP) ) &&
+ (dshaders[brush->shaderNum].contentFlags & CONTENTS_SOLID) )
+ {
+ numwindings[!(i & 1)] = 0;
+ for (j = 0; j < numwindings[i&1]; j++)
+ {
+ n = VS_ChopWindingWithBrush(&windingsbuf[i&1][j], brush,
+ &windingsbuf[!(i&1)][numwindings[!(i&1)]],
+ 64 - numwindings[!(i&1)]);
+ numwindings[!(i&1)] += n;
+ }
+ if (!numwindings[!(i&1)])
+ return 0;
+ }
+ else
+ {
+ for (j = 0; j < numwindings[i&1]; j++)
+ {
+ windingsbuf[!(i&1)][j] = windingsbuf[i&1][j];
+ }
+ numwindings[!(i&1)] = numwindings[i&1];
+ }
+ }
+ area = 0;
+ for (j = 0; j < numwindings[i&1]; j++)
+ {
+ area += WindingArea(&windingsbuf[i&1][j]);
+ }
+ return area;
+}
+
+/*
+=============
+VS_R_WindingAreaOutsideSolid
+=============
+*/
+float VS_R_WindingAreaOutsideSolid(winding_t *w, vec3_t normal, int nodenum)
+{
+ int leafnum, res;
+ float area;
+ dnode_t *node;
+ dleaf_t *leaf;
+ dplane_t *plane;
+ winding_t back;
+ plane_t split;
+
+ area = 0;
+ while(nodenum >= 0)
+ {
+ node = &dnodes[nodenum];
+ plane = &dplanes[node->planeNum];
+
+ VectorCopy(plane->normal, split.normal);
+ split.dist = plane->dist;
+ res = VS_SplitWinding (w, &back, &split, 0.1);
+
+ if (res == SIDE_FRONT)
+ {
+ nodenum = node->children[0];
+ }
+ else if (res == SIDE_BACK)
+ {
+ nodenum = node->children[1];
+ }
+ else if (res == SIDE_ON)
+ {
+ if (DotProduct(normal, plane->normal) > 0)
+ nodenum = node->children[0];
+ else
+ nodenum = node->children[1];
+ }
+ else
+ {
+ area += VS_R_WindingAreaOutsideSolid(&back, normal, node->children[1]);
+ nodenum = node->children[0];
+ }
+ }
+ leafnum = -nodenum - 1;
+ leaf = &dleafs[leafnum];
+ if (leaf->cluster != -1)
+ {
+ area += VS_WindingAreaOutsideBrushes(w, &dleafbrushes[leaf->firstLeafBrush], leaf->numLeafBrushes);
+ }
+ return area;
+}
+
+/*
+=============
+VS_WindingAreaOutsideSolid
+=============
+*/
+float VS_WindingAreaOutsideSolid(winding_t *w, vec3_t normal)
+{
+ return VS_R_WindingAreaOutsideSolid(w, normal, 0);
+}
+
+/*
+=============
+VS_ChopWindingWithFacet
+=============
+*/
+float VS_ChopWindingWithFacet(winding_t *w, lFacet_t *facet)
+{
+ int i;
+
+ for (i = 0; i < facet->numpoints; i++)
+ {
+ if (VS_ChopWinding(w, &facet->boundaries[i], 0) == SIDE_BACK)
+ return 0;
+ }
+ if (nostitching)
+ return WindingArea(w);
+ else
+ return VS_WindingAreaOutsideSolid(w, facet->plane.normal);
+}
+
+/*
+=============
+VS_CalcVisibleLightmapPixelArea
+
+nice brute force ;)
+=============
+*/
+void VS_CalcVisibleLightmapPixelArea(void)
+{
+ int i, j, x, y, k;
+ dsurface_t *ds;
+ lsurfaceTest_t *test;
+ mesh_t *mesh;
+ winding_t w, tmpw;
+ float area;
+
+ _printf("calculating visible lightmap pixel area...\n");
+ for ( i = 0 ; i < numDrawSurfaces ; i++ )
+ {
+ test = lsurfaceTest[ i ];
+ if (!test)
+ continue;
+ ds = &drawSurfaces[ i ];
+
+ if ( ds->lightmapNum < 0 )
+ continue;
+
+ for (y = 0; y < ds->lightmapHeight; y++)
+ {
+ for (x = 0; x < ds->lightmapWidth; x++)
+ {
+ if (ds->surfaceType == MST_PATCH)
+ {
+ if (y == ds->lightmapHeight-1)
+ continue;
+ if (x == ds->lightmapWidth-1)
+ continue;
+ mesh = lsurfaceTest[i]->detailMesh;
+ VectorCopy( mesh->verts[y*mesh->width+x].xyz, w.points[0]);
+ VectorCopy( mesh->verts[(y+1)*mesh->width+x].xyz, w.points[1]);
+ VectorCopy( mesh->verts[(y+1)*mesh->width+x+1].xyz, w.points[2]);
+ VectorCopy( mesh->verts[y*mesh->width+x+1].xyz, w.points[3]);
+ w.numpoints = 4;
+ if (nostitching)
+ area = WindingArea(&w);
+ else
+ area = VS_WindingAreaOutsideSolid(&w, mesh->verts[y*mesh->width+x].normal);
+ }
+ else
+ {
+ VectorMA(ds->lightmapOrigin, (float) x - LIGHTMAP_PIXELSHIFT, ds->lightmapVecs[0], w.points[0]);
+ VectorMA(w.points[0], (float) y - LIGHTMAP_PIXELSHIFT, ds->lightmapVecs[1], w.points[0]);
+ VectorMA(ds->lightmapOrigin, (float) x - LIGHTMAP_PIXELSHIFT, ds->lightmapVecs[0], w.points[3]);
+ VectorMA(w.points[3], (float) y - LIGHTMAP_PIXELSHIFT + 1, ds->lightmapVecs[1], w.points[3]);
+ VectorMA(ds->lightmapOrigin, (float) x - LIGHTMAP_PIXELSHIFT + 1, ds->lightmapVecs[0], w.points[2]);
+ VectorMA(w.points[2], (float) y - LIGHTMAP_PIXELSHIFT + 1, ds->lightmapVecs[1], w.points[2]);
+ VectorMA(ds->lightmapOrigin, (float) x - LIGHTMAP_PIXELSHIFT + 1, ds->lightmapVecs[0], w.points[1]);
+ VectorMA(w.points[1], (float) y - LIGHTMAP_PIXELSHIFT, ds->lightmapVecs[1], w.points[1]);
+ w.numpoints = 4;
+ area = 0;
+ for (j = 0; j < test->numFacets; j++)
+ {
+ memcpy(&tmpw, &w, sizeof(winding_t));
+ area += VS_ChopWindingWithFacet(&tmpw, &test->facets[j]);
+ }
+ }
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ lightmappixelarea[k] = area;
+ }
+ }
+ }
+}
+
+/*
+=============
+VS_FindAdjacentSurface
+=============
+*/
+int VS_FindAdjacentSurface(int surfaceNum, int facetNum, vec3_t p1, vec3_t p2, int *sNum, int *fNum, int *point)
+{
+ int i, j, k;
+ lsurfaceTest_t *test;
+ lFacet_t *facet;
+ dsurface_t *ds;
+ float *fp1, *fp2;
+ vec3_t dir;
+ plane_t *facetplane;
+ // winding_t w;
+
+ facetplane = &lsurfaceTest[surfaceNum]->facets[facetNum].plane;
+ // DebugNet_RemoveAllPolys();
+ // memcpy(w.points, lsurfaceTest[surfaceNum]->facets[facetNum].points,
+ // lsurfaceTest[surfaceNum]->facets[facetNum].numpoints * sizeof(vec3_t));
+ // w.numpoints = lsurfaceTest[surfaceNum]->facets[facetNum].numpoints;
+ // DebugNet_DrawWinding(&w, 2);
+ for ( i = 0 ; i < numDrawSurfaces ; i++ )
+ {
+ if (i == surfaceNum)
+ continue;
+ test = lsurfaceTest[ i ];
+ if (!test)
+ continue;
+ if (test->trisoup)// || test->patch)
+ continue;
+ ds = &drawSurfaces[i];
+ if ( ds->lightmapNum < 0 )
+ continue;
+ //if this surface is not even near the edge
+ VectorSubtract(p1, test->origin, dir);
+ if (fabs(dir[0]) > test->radius ||
+ fabs(dir[1]) > test->radius ||
+ fabs(dir[1]) > test->radius)
+ {
+ VectorSubtract(p2, test->origin, dir);
+ if (fabs(dir[0]) > test->radius ||
+ fabs(dir[1]) > test->radius ||
+ fabs(dir[1]) > test->radius)
+ {
+ continue;
+ }
+ }
+ //
+ for (j = 0; j < test->numFacets; j++)
+ {
+ facet = &test->facets[j];
+ //
+ //if (!Plane_Equal(&facet->plane, facetplane, qfalse))
+ if (DotProduct(facet->plane.normal, facetplane->normal) < 0.9)
+ {
+ if (!test->trisoup && !test->patch)
+ break;
+ continue;
+ }
+ //
+ for (k = 0; k < facet->numpoints; k++)
+ {
+ fp1 = facet->points[k];
+ if (fabs(p2[0] - fp1[0]) < 0.1 &&
+ fabs(p2[1] - fp1[1]) < 0.1 &&
+ fabs(p2[2] - fp1[2]) < 0.1)
+ {
+ fp2 = facet->points[(k+1) % facet->numpoints];
+ if (fabs(p1[0] - fp2[0]) < 0.1 &&
+ fabs(p1[1] - fp2[1]) < 0.1 &&
+ fabs(p1[2] - fp2[2]) < 0.1)
+ {
+ // memcpy(w.points, facet->points, facet->numpoints * sizeof(vec3_t));
+ // w.numpoints = facet->numpoints;
+ // DebugNet_DrawWinding(&w, 1);
+ *sNum = i;
+ *fNum = j;
+ *point = k;
+ return qtrue;
+ }
+ }
+ /*
+ else if (fabs(p1[0] - fp1[0]) < 0.1 &&
+ fabs(p1[1] - fp1[1]) < 0.1 &&
+ fabs(p1[2] - fp1[2]) < 0.1)
+ {
+ fp2 = facet->points[(k+1) % facet->numpoints];
+ if (fabs(p2[0] - fp2[0]) < 0.1 &&
+ fabs(p2[1] - fp2[1]) < 0.1 &&
+ fabs(p2[2] - fp2[2]) < 0.1)
+ {
+ // memcpy(w.points, facet->points, facet->numpoints * sizeof(vec3_t));
+ // w.numpoints = facet->numpoints;
+ // DebugNet_DrawWinding(&w, 1);
+ *sNum = i;
+ *fNum = j;
+ *point = k;
+ return qtrue;
+ }
+ }
+ //*/
+ }
+ }
+ }
+ return qfalse;
+}
+
+/*
+=============
+VS_SmoothenLightmapEdges
+
+this code is used to smoothen lightmaps across surface edges
+=============
+*/
+void VS_SmoothenLightmapEdges(void)
+{
+ int i, j, k, coords1[2][2];
+ float coords2[2][2];
+ int x1, y1, xinc1, yinc1, k1, k2;
+ float x2, y2, xinc2, yinc2, length;
+ int surfaceNum, facetNum, point;
+ lsurfaceTest_t *test;
+ lFacet_t *facet1, *facet2;
+ dsurface_t *ds1, *ds2;
+ float *p[2], s, t, *color1, *color2;
+ vec3_t dir, cross;
+
+ for ( i = 0 ; i < numDrawSurfaces ; i++ )
+ {
+ test = lsurfaceTest[ i ];
+ if (!test)
+ continue;
+ if (test->trisoup)// || test->patch)
+ continue;
+ ds1 = &drawSurfaces[i];
+ if ( ds1->lightmapNum < 0 )
+ continue;
+ for (j = 0; j < test->numFacets; j++)
+ {
+ facet1 = &test->facets[j];
+ //
+ for (k = 0; k < facet1->numpoints; k++)
+ {
+ p[0] = facet1->points[k];
+ p[1] = facet1->points[(k+1)%facet1->numpoints];
+ //
+ coords1[0][0] = facet1->lightmapCoords[k][0] * LIGHTMAP_SIZE;
+ coords1[0][1] = facet1->lightmapCoords[k][1] * LIGHTMAP_SIZE;
+ coords1[1][0] = facet1->lightmapCoords[(k+1)%facet1->numpoints][0] * LIGHTMAP_SIZE;
+ coords1[1][1] = facet1->lightmapCoords[(k+1)%facet1->numpoints][1] * LIGHTMAP_SIZE;
+ if (coords1[0][0] >= LIGHTMAP_SIZE)
+ coords1[0][0] = LIGHTMAP_SIZE-1;
+ if (coords1[0][1] >= LIGHTMAP_SIZE)
+ coords1[0][1] = LIGHTMAP_SIZE-1;
+ if (coords1[1][0] >= LIGHTMAP_SIZE)
+ coords1[1][0] = LIGHTMAP_SIZE-1;
+ if (coords1[1][1] >= LIGHTMAP_SIZE)
+ coords1[1][1] = LIGHTMAP_SIZE-1;
+ // try one row or column further because on flat faces the lightmap can
+ // extend beyond the edge
+ VectorSubtract(p[1], p[0], dir);
+ VectorNormalize(dir, dir);
+ CrossProduct(dir, facet1->plane.normal, cross);
+ //
+ if (coords1[0][0] - coords1[1][0] == 0)
+ {
+ s = DotProduct( cross, facet1->lightmapMatrix[0] );
+ coords1[0][0] += s < 0 ? 1 : -1;
+ coords1[1][0] += s < 0 ? 1 : -1;
+ if (coords1[0][0] < ds1->lightmapX || coords1[0][0] >= ds1->lightmapX + ds1->lightmapWidth)
+ {
+ coords1[0][0] += s < 0 ? -1 : 1;
+ coords1[1][0] += s < 0 ? -1 : 1;
+ }
+ length = fabs(coords1[1][1] - coords1[0][1]);
+ }
+ else if (coords1[0][1] - coords1[1][1] == 0)
+ {
+ t = DotProduct( cross, facet1->lightmapMatrix[1] );
+ coords1[0][1] += t < 0 ? 1 : -1;
+ coords1[1][1] += t < 0 ? 1 : -1;
+ if (coords1[0][1] < ds1->lightmapY || coords1[0][1] >= ds1->lightmapY + ds1->lightmapHeight)
+ {
+ coords1[0][1] += t < 0 ? -1 : 1;
+ coords1[1][1] += t < 0 ? -1 : 1;
+ }
+ length = fabs(coords1[1][0] - coords1[0][0]);
+ }
+ else
+ {
+ //the edge is not parallell to one of the lightmap axis
+ continue;
+ }
+ //
+ x1 = coords1[0][0];
+ y1 = coords1[0][1];
+ xinc1 = coords1[1][0] - coords1[0][0];
+ if (xinc1 < 0) xinc1 = -1;
+ if (xinc1 > 0) xinc1 = 1;
+ yinc1 = coords1[1][1] - coords1[0][1];
+ if (yinc1 < 0) yinc1 = -1;
+ if (yinc1 > 0) yinc1 = 1;
+ // the edge should be parallell to one of the lightmap axis
+ if (xinc1 != 0 && yinc1 != 0)
+ continue;
+ //
+ if (!VS_FindAdjacentSurface(i, j, p[0], p[1], &surfaceNum, &facetNum, &point))
+ continue;
+ //
+ ds2 = &drawSurfaces[surfaceNum];
+ facet2 = &lsurfaceTest[surfaceNum]->facets[facetNum];
+ coords2[0][0] = facet2->lightmapCoords[(point+1)%facet2->numpoints][0] * LIGHTMAP_SIZE;
+ coords2[0][1] = facet2->lightmapCoords[(point+1)%facet2->numpoints][1] * LIGHTMAP_SIZE;
+ coords2[1][0] = facet2->lightmapCoords[point][0] * LIGHTMAP_SIZE;
+ coords2[1][1] = facet2->lightmapCoords[point][1] * LIGHTMAP_SIZE;
+ if (coords2[0][0] >= LIGHTMAP_SIZE)
+ coords2[0][0] = LIGHTMAP_SIZE-1;
+ if (coords2[0][1] >= LIGHTMAP_SIZE)
+ coords2[0][1] = LIGHTMAP_SIZE-1;
+ if (coords2[1][0] >= LIGHTMAP_SIZE)
+ coords2[1][0] = LIGHTMAP_SIZE-1;
+ if (coords2[1][1] >= LIGHTMAP_SIZE)
+ coords2[1][1] = LIGHTMAP_SIZE-1;
+ //
+ x2 = coords2[0][0];
+ y2 = coords2[0][1];
+ xinc2 = coords2[1][0] - coords2[0][0];
+ if (length)
+ xinc2 = xinc2 / length;
+ yinc2 = coords2[1][1] - coords2[0][1];
+ if (length)
+ yinc2 = yinc2 / length;
+ // the edge should be parallell to one of the lightmap axis
+ if ((int) xinc2 != 0 && (int) yinc2 != 0)
+ continue;
+ //
+ while(1)
+ {
+ k1 = ( ds1->lightmapNum * LIGHTMAP_HEIGHT + y1) * LIGHTMAP_WIDTH + x1;
+ k2 = ( ds2->lightmapNum * LIGHTMAP_HEIGHT + ((int) y2)) * LIGHTMAP_WIDTH + ((int) x2);
+ color1 = lightFloats + k1*3;
+ color2 = lightFloats + k2*3;
+ if (lightmappixelarea[k1] < 0.01)
+ {
+ color1[0] = color2[0];
+ color1[1] = color2[1];
+ color1[2] = color2[2];
+ }
+ else
+ {
+ color1[0] = (float) color2[0] * 0.7 + (float) color1[0] * 0.3;
+ color1[1] = (float) color2[1] * 0.7 + (float) color1[1] * 0.3;
+ color1[2] = (float) color2[2] * 0.7 + (float) color1[2] * 0.3;
+ }
+ //
+ if (x1 == coords1[1][0] &&
+ y1 == coords1[1][1])
+ break;
+ x1 += xinc1;
+ y1 += yinc1;
+ x2 += xinc2;
+ y2 += yinc2;
+ if (x2 < ds2->lightmapX)
+ x2 = ds2->lightmapX;
+ if (x2 >= ds2->lightmapX + ds2->lightmapWidth)
+ x2 = ds2->lightmapX + ds2->lightmapWidth-1;
+ if (y2 < ds2->lightmapY)
+ y2 = ds2->lightmapY;
+ if (y2 >= ds2->lightmapY + ds2->lightmapHeight)
+ y2 = ds2->lightmapY + ds2->lightmapHeight-1;
+ }
+ }
+ }
+ }
+}
+
+/*
+=============
+VS_FixLightmapEdges
+=============
+*/
+void VS_FixLightmapEdges(void)
+{
+ int i, j, x, y, k, foundvalue, height, width, index;
+ int pos, top, bottom;
+ dsurface_t *ds;
+ lsurfaceTest_t *test;
+ float color[3];
+ float *ptr;
+ byte filled[(LIGHTMAP_SIZE+1) * (LIGHTMAP_SIZE+1) / 8];
+ float lightmap_edge_epsilon;
+
+ lightmap_edge_epsilon = 0.1 * samplesize;
+ for ( i = 0 ; i < numDrawSurfaces ; i++ )
+ {
+ test = lsurfaceTest[ i ];
+ if (!test)
+ continue;
+ ds = &drawSurfaces[ i ];
+
+ if ( ds->lightmapNum < 0 )
+ continue;
+ if (ds->surfaceType == MST_PATCH)
+ {
+ height = ds->lightmapHeight - 1;
+ width = ds->lightmapWidth - 1;
+ }
+ else
+ {
+ height = ds->lightmapHeight;
+ width = ds->lightmapWidth;
+ }
+ memset(filled, 0, sizeof(filled));
+// printf("\n");
+ for (x = 0; x < width; x++)
+ {
+ for (y = 0; y < height; y++)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ if (lightmappixelarea[k] > lightmap_edge_epsilon)
+ {
+ index = (ds->lightmapY + y) * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ filled[index >> 3] |= 1 << (index & 7);
+// printf("*");
+ }
+// else
+// printf("_");
+ }
+// printf("\n");
+ }
+ for (y = 0; y < height; y++)
+ {
+ pos = -2;
+ for (x = 0; x < width; x++)
+ {
+ index = (ds->lightmapY + y) * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ if (pos == -2)
+ {
+ if (filled[index >> 3] & (1 << (index & 7)))
+ pos = -1;
+ }
+ else if (pos == -1)
+ {
+ if (!(filled[index >> 3] & (1 << (index & 7))))
+ pos = x - 1;
+ }
+ else
+ {
+ if (filled[index >> 3] & (1 << (index & 7)))
+ {
+ bottom = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + pos;
+ top = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ for (j = 0; j < (x - pos + 1) / 2; j++)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + pos + j + 1;
+ index = (ds->lightmapY + y) * LIGHTMAP_WIDTH + ds->lightmapX + pos + j + 1;
+ filled[index >> 3] |= 1 << (index & 7);
+ (lightFloats + k*3)[0] = (lightFloats + top*3)[0];
+ (lightFloats + k*3)[1] = (lightFloats + top*3)[1];
+ (lightFloats + k*3)[2] = (lightFloats + top*3)[2];
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x - j - 1;
+ index = (ds->lightmapY + y) * LIGHTMAP_WIDTH + ds->lightmapX + x - j - 1;
+ filled[index >> 3] |= 1 << (index & 7);
+ (lightFloats + k*3)[0] = (lightFloats + bottom*3)[0];
+ (lightFloats + k*3)[1] = (lightFloats + bottom*3)[1];
+ (lightFloats + k*3)[2] = (lightFloats + bottom*3)[2];
+ }
+ pos = -1;
+ }
+ }
+ }
+ }
+ for (x = 0; x < width; x++)
+ {
+ pos = -2;
+ for (y = 0; y < height; y++)
+ {
+ index = (ds->lightmapY + y) * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ if (pos == -2)
+ {
+ if (filled[index >> 3] & (1 << (index & 7)))
+ pos = -1;
+ }
+ else if (pos == -1)
+ {
+ if (!(filled[index >> 3] & (1 << (index & 7))))
+ pos = y - 1;
+ }
+ else
+ {
+ if (filled[index >> 3] & (1 << (index & 7)))
+ {
+ bottom = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + pos)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ top = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ for (j = 0; j < (y - pos + 1) / 2; j++)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + pos + j + 1)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ index = (ds->lightmapY + pos + j + 1) * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ filled[index >> 3] |= 1 << (index & 7);
+ (lightFloats + k*3)[0] = (lightFloats + top*3)[0];
+ (lightFloats + k*3)[1] = (lightFloats + top*3)[1];
+ (lightFloats + k*3)[2] = (lightFloats + top*3)[2];
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y - j - 1)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ index = (ds->lightmapY + y - j - 1) * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ filled[index >> 3] |= 1 << (index & 7);
+ (lightFloats + k*3)[0] = (lightFloats + bottom*3)[0];
+ (lightFloats + k*3)[1] = (lightFloats + bottom*3)[1];
+ (lightFloats + k*3)[2] = (lightFloats + bottom*3)[2];
+ }
+ pos = -1;
+ }
+ }
+ }
+ }
+ for (y = 0; y < height; y++)
+ {
+ foundvalue = qfalse;
+ for (x = 0; x < width; x++)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ index = (ds->lightmapY + y) * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ if (foundvalue)
+ {
+ if (filled[index >> 3] & (1 << (index & 7)))
+ {
+ ptr = lightFloats + k*3;
+ color[0] = ptr[0];
+ color[1] = ptr[1];
+ color[2] = ptr[2];
+ }
+ else
+ {
+ ptr = lightFloats + k*3;
+ ptr[0] = color[0];
+ ptr[1] = color[1];
+ ptr[2] = color[2];
+ filled[index >> 3] |= 1 << (index & 7);
+ }
+ }
+ else
+ {
+ if (filled[index >> 3] & (1 << (index & 7)))
+ {
+ ptr = lightFloats + k*3;
+ color[0] = ptr[0];
+ color[1] = ptr[1];
+ color[2] = ptr[2];
+ foundvalue = qtrue;
+ }
+ }
+ }
+ foundvalue = qfalse;
+ for (x = width-1; x >= 0; x--)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ index = (ds->lightmapY + y) * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ if (foundvalue)
+ {
+ if (filled[index >> 3] & (1 << (index & 7)))
+ {
+ ptr = lightFloats + k*3;
+ color[0] = ptr[0];
+ color[1] = ptr[1];
+ color[2] = ptr[2];
+ }
+ else
+ {
+ ptr = lightFloats + k*3;
+ ptr[0] = color[0];
+ ptr[1] = color[1];
+ ptr[2] = color[2];
+ filled[index >> 3] |= 1 << (index & 7);
+ }
+ }
+ else
+ {
+ if (filled[index >> 3] & (1 << (index & 7)))
+ {
+ ptr = lightFloats + k*3;
+ color[0] = ptr[0];
+ color[1] = ptr[1];
+ color[2] = ptr[2];
+ foundvalue = qtrue;
+ }
+ }
+ }
+ }
+ for (x = 0; x < width; x++)
+ {
+ foundvalue = qfalse;
+ for (y = 0; y < height; y++)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ index = (ds->lightmapY + y) * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ if (foundvalue)
+ {
+ if (filled[index >> 3] & (1 << (index & 7)))
+ {
+ ptr = lightFloats + k*3;
+ color[0] = ptr[0];
+ color[1] = ptr[1];
+ color[2] = ptr[2];
+ }
+ else
+ {
+ ptr = lightFloats + k*3;
+ ptr[0] = color[0];
+ ptr[1] = color[1];
+ ptr[2] = color[2];
+ filled[index >> 3] |= 1 << (index & 7);
+ }
+ }
+ else
+ {
+ if (filled[index >> 3] & (1 << (index & 7)))
+ {
+ ptr = lightFloats + k*3;
+ color[0] = ptr[0];
+ color[1] = ptr[1];
+ color[2] = ptr[2];
+ foundvalue = qtrue;
+ }
+ }
+ }
+ foundvalue = qfalse;
+ for (y = height-1; y >= 0; y--)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ index = (ds->lightmapY + y) * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ if (foundvalue)
+ {
+ if (filled[index >> 3] & (1 << (index & 7)))
+ {
+ ptr = lightFloats + k*3;
+ color[0] = ptr[0];
+ color[1] = ptr[1];
+ color[2] = ptr[2];
+ }
+ else
+ {
+ ptr = lightFloats + k*3;
+ ptr[0] = color[0];
+ ptr[1] = color[1];
+ ptr[2] = color[2];
+ filled[index >> 3] |= 1 << (index & 7);
+ }
+ }
+ else
+ {
+ if (filled[index >> 3] & (1 << (index & 7)))
+ {
+ ptr = lightFloats + k*3;
+ color[0] = ptr[0];
+ color[1] = ptr[1];
+ color[2] = ptr[2];
+ foundvalue = qtrue;
+ }
+ }
+ }
+ }
+ if (ds->surfaceType == MST_PATCH)
+ {
+ x = ds->lightmapWidth-1;
+ for (y = 0; y < ds->lightmapHeight; y++)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ ptr = lightFloats + k*3;
+ ptr[0] = (lightFloats + (k-1)*3)[0];
+ ptr[1] = (lightFloats + (k-1)*3)[1];
+ ptr[2] = (lightFloats + (k-1)*3)[2];
+ }
+ y = ds->lightmapHeight-1;
+ for (x = 0; x < ds->lightmapWidth; x++)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ ptr = lightFloats + k*3;
+ ptr[0] = (lightFloats + (k-LIGHTMAP_WIDTH)*3)[0];
+ ptr[1] = (lightFloats + (k-LIGHTMAP_WIDTH)*3)[1];
+ ptr[2] = (lightFloats + (k-LIGHTMAP_WIDTH)*3)[2];
+ }
+ }
+ /*
+ //colored debug edges
+ if (ds->surfaceType == MST_PATCH)
+ {
+ x = ds->lightmapWidth-1;
+ for (y = 0; y < ds->lightmapHeight; y++)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ ptr = lightFloats + k*3;
+ ptr[0] = 255;
+ ptr[1] = 0;
+ ptr[2] = 0;
+ }
+ y = ds->lightmapHeight-1;
+ for (x = 0; x < ds->lightmapWidth; x++)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ ptr = lightFloats + k*3;
+ ptr[0] = 0;
+ ptr[1] = 255;
+ ptr[2] = 0;
+ }
+ }
+ //*/
+ }
+ //
+ VS_SmoothenLightmapEdges();
+}
+
+/*
+=============
+VS_ShiftPatchLightmaps
+=============
+*/
+void VS_ShiftPatchLightmaps(void)
+{
+ int i, j, x, y, k;
+ drawVert_t *verts;
+ dsurface_t *ds;
+ lsurfaceTest_t *test;
+ float *ptr;
+
+ for ( i = 0 ; i < numDrawSurfaces ; i++ )
+ {
+ test = lsurfaceTest[ i ];
+ if (!test)
+ continue;
+ ds = &drawSurfaces[ i ];
+
+ if ( ds->lightmapNum < 0 )
+ continue;
+ if (ds->surfaceType != MST_PATCH)
+ continue;
+ for (x = ds->lightmapWidth; x > 0; x--)
+ {
+ for (y = 0; y <= ds->lightmapHeight; y++)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ ptr = lightFloats + k*3;
+ ptr[0] = (lightFloats + (k-1)*3)[0];
+ ptr[1] = (lightFloats + (k-1)*3)[1];
+ ptr[2] = (lightFloats + (k-1)*3)[2];
+ }
+ }
+ for (y = ds->lightmapHeight; y > 0; y--)
+ {
+ for (x = 0; x <= ds->lightmapWidth; x++)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ ptr = lightFloats + k*3;
+ ptr[0] = (lightFloats + (k-LIGHTMAP_WIDTH)*3)[0];
+ ptr[1] = (lightFloats + (k-LIGHTMAP_WIDTH)*3)[1];
+ ptr[2] = (lightFloats + (k-LIGHTMAP_WIDTH)*3)[2];
+ }
+ }
+ verts = &drawVerts[ ds->firstVert ];
+ for ( j = 0 ; j < ds->patchHeight * ds->patchWidth; j++ )
+ {
+ verts[j].lightmap[0] += 0.5 / LIGHTMAP_WIDTH;
+ verts[j].lightmap[1] += 0.5 / LIGHTMAP_HEIGHT;
+ }
+ ds->lightmapHeight++;
+ ds->lightmapWidth++;
+ }
+}
+
+/*
+=============
+VS_StoreLightmap
+=============
+*/
+void VS_StoreLightmap(void)
+{
+ int i, x, y, k;
+ dsurface_t *ds;
+ lsurfaceTest_t *test;
+ float *src;
+ byte *dst;
+
+ _printf("storing lightmaps...\n");
+ //fix lightmap edges before storing them
+ VS_FixLightmapEdges();
+ //
+#ifdef LIGHTMAP_PATCHSHIFT
+ VS_ShiftPatchLightmaps();
+#endif
+ //
+ for ( i = 0 ; i < numDrawSurfaces ; i++ )
+ {
+ test = lsurfaceTest[ i ];
+ if (!test)
+ continue;
+ ds = &drawSurfaces[ i ];
+
+ if ( ds->lightmapNum < 0 )
+ continue;
+
+ for (y = 0; y < ds->lightmapHeight; y++)
+ {
+ for (x = 0; x < ds->lightmapWidth; x++)
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ VectorAdd((lightFloats + k*3), lightAmbientColor, (lightFloats + k*3));
+ src = &lightFloats[k*3];
+ dst = lightBytes + k*3;
+ ColorToBytes(src, dst);
+ }
+ }
+ }
+}
+
+/*
+=============
+PointInLeafnum
+=============
+*/
+static int PointInLeafnum(vec3_t point)
+{
+ int nodenum;
+ vec_t dist;
+ dnode_t *node;
+ dplane_t *plane;
+
+ nodenum = 0;
+ while (nodenum >= 0)
+ {
+ node = &dnodes[nodenum];
+ plane = &dplanes[node->planeNum];
+ dist = DotProduct (point, plane->normal) - plane->dist;
+ if (dist > 0)
+ nodenum = node->children[0];
+ else
+ nodenum = node->children[1];
+ }
+
+ return -nodenum - 1;
+}
+
+/*
+=============
+VS_PointInLeafnum_r
+=============
+*/
+int VS_PointInLeafnum_r(vec3_t point, int nodenum)
+{
+ int leafnum;
+ vec_t dist;
+ dnode_t *node;
+ dplane_t *plane;
+
+ while (nodenum >= 0)
+ {
+ node = &dnodes[nodenum];
+ plane = &dplanes[node->planeNum];
+ dist = DotProduct (point, plane->normal) - plane->dist;
+ if (dist > 0.1)
+ {
+ nodenum = node->children[0];
+ }
+ else if (dist < -0.1)
+ {
+ nodenum = node->children[1];
+ }
+ else
+ {
+ leafnum = VS_PointInLeafnum_r(point, node->children[0]);
+ if (dleafs[leafnum].cluster != -1)
+ return leafnum;
+ nodenum = node->children[1];
+ }
+ }
+
+ leafnum = -nodenum - 1;
+ return leafnum;
+}
+
+/*
+=============
+VS_PointInLeafnum
+=============
+*/
+int VS_PointInLeafnum(vec3_t point)
+{
+ return VS_PointInLeafnum_r(point, 0);
+}
+
+/*
+=============
+VS_LightLeafnum
+=============
+*/
+int VS_LightLeafnum(vec3_t point)
+{
+ /*
+ int leafnum;
+ dleaf_t *leaf;
+ float x, y, z;
+ vec3_t test;
+
+ leafnum = VS_PointInLeafnum(point);
+ leaf = &dleafs[leafnum];
+ if (leaf->cluster != -1)
+ return leafnum;
+ for (z = 1; z >= -1; z -= 1)
+ {
+ for (x = 1; x >= -1; x -= 1)
+ {
+ for (y = 1; y >= -1; y -= 1)
+ {
+ VectorCopy(point, test);
+ test[0] += x;
+ test[1] += y;
+ test[2] += z;
+ leafnum = VS_PointInLeafnum(test);
+ leaf = &dleafs[leafnum];
+ if (leaf->cluster != -1)
+ {
+ VectorCopy(test, point);
+ return leafnum;
+ }
+ }
+ }
+ }
+ return leafnum;
+ */
+ return VS_PointInLeafnum(point);
+}
+
+//#define LIGHTPOLYS
+
+#ifdef LIGHTPOLYS
+
+winding_t *lightwindings[MAX_MAP_DRAW_SURFS];
+int numlightwindings;
+
+/*
+=============
+VS_DrawLightWindings
+=============
+*/
+void VS_DrawLightWindings(void)
+{
+ int i;
+ for (i = 0; i < numlightwindings; i++)
+ {
+#ifdef DEBUGNET
+ DebugNet_DrawWinding(lightwindings[i], 1);
+#endif
+ }
+}
+
+/*
+=============
+VS_LightSurfaceWithVolume
+=============
+*/
+void VS_LightSurfaceWithVolume(int surfaceNum, int facetNum, vsound_t *light, lightvolume_t *volume)
+{
+ winding_t *w;
+ lsurfaceTest_t *test;
+ lFacet_t *facet;
+ int i;
+
+ test = lsurfaceTest[ surfaceNum ];
+ facet = &test->facets[ facetNum ];
+
+ //
+ w = (winding_t *) malloc(sizeof(winding_t));
+ memcpy(w->points, facet->points, sizeof(vec3_t) * facet->numpoints);
+ w->numpoints = facet->numpoints;
+
+ for (i = 0; i < volume->numplanes; i++)
+ {
+ //if totally on the back
+ if (VS_ChopWinding(w, &volume->planes[i], 0.01) == SIDE_BACK)
+ return;
+ }
+ lightwindings[numlightwindings] = w;
+ numlightwindings++;
+ if (numlightwindings >= MAX_MAP_DRAW_SURFS)
+ Error("MAX_LIGHTWINDINGS");
+}
+
+#else
+
+/*
+=============
+VS_LightSurfaceWithVolume
+=============
+*/
+/*
+int VS_PointInsideLightVolume(vec3_t point, lightvolume_t *volume)
+{
+ int i;
+ float d;
+
+ for (i = 0; i < volume->numplanes; i++)
+ {
+ d = DotProduct(volume->planes[i].normal, point) - volume->planes[i].dist;
+ if (d < 0) return qfalse;
+ }
+ return qtrue;
+}
+
+void VS_LightSurfaceWithVolume( int surfaceNum, int facetNum, vsound_t *light, lightvolume_t *volume )
+{
+ dsurface_t *ds;
+ int i, j, k;
+ int numPositions;
+ vec3_t base, normal, color;
+ int sampleWidth, sampleHeight;
+ vec3_t lightmapOrigin, lightmapVecs[2], dir;
+ unsigned char *ptr;
+ float add, dist, angle;
+ mesh_t * mesh;
+
+ ds = &drawSurfaces[surfaceNum];
+
+ // vertex-lit triangle model
+ if ( ds->surfaceType == MST_TRIANGLE_SOUP ) {
+ return;
+ }
+
+ if ( ds->lightmapNum < 0 ) {
+ return; // doesn't need lighting
+ }
+
+ if ( ds->surfaceType == MST_PATCH ) {
+ mesh = lsurfaceTest[surfaceNum]->detailMesh;
+ } else {
+ VectorCopy( ds->lightmapVecs[2], normal );
+
+ VectorCopy( ds->lightmapOrigin, lightmapOrigin );
+ VectorCopy( ds->lightmapVecs[0], lightmapVecs[0] );
+ VectorCopy( ds->lightmapVecs[1], lightmapVecs[1] );
+ }
+
+ sampleWidth = ds->lightmapWidth;
+ sampleHeight = ds->lightmapHeight;
+
+ //calculate lightmap
+ for ( i = 0 ; i < sampleWidth; i++ ) {
+ for ( j = 0 ; j < sampleHeight; j++ ) {
+
+ if ( ds->patchWidth ) {
+ numPositions = 9;
+ VectorCopy( mesh->verts[j*mesh->width+i].normal, normal );
+ // VectorNormalize( normal, normal );
+ // push off of the curve a bit
+ VectorMA( mesh->verts[j*mesh->width+i].xyz, 1, normal, base );
+
+// MakeNormalVectors( normal, lightmapVecs[0], lightmapVecs[1] );
+ } else {
+ numPositions = 9;
+ for ( k = 0 ; k < 3 ; k++ ) {
+ base[k] = lightmapOrigin[k] + normal[k]
+ + ((float) i) * lightmapVecs[0][k]
+ + ((float) j) * lightmapVecs[1][k];
+ }
+ }
+ VectorAdd( base, surfaceOrigin[ surfaceNum ], base );
+
+ VectorSubtract(base, light->origin, dir);
+ dist = VectorNormalize(dir, dir);
+ if ( dist < 16 ) {
+ dist = 16;
+ }
+ angle = 1;//DotProduct( normal, dir ); //1;
+ if (angle > 1)
+ angle = 1;
+ if ( light->atten_disttype == LDAT_LINEAR ) {
+ add = angle * light->photons * lightLinearScale - dist;
+ if ( add < 0 ) {
+ add = 0;
+ }
+ } else {
+ add = light->photons / ( dist * dist ) * angle;
+ }
+ if (add <= 1.0)
+ continue;
+
+ if (VS_PointInsideLightVolume(base, volume))
+ {
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + j)
+ * LIGHTMAP_WIDTH + ds->lightmapX + i;
+ ptr = lightBytes + k*3;
+ color[0] = (float) ptr[0] + add * light->color[0];
+ color[1] = (float) ptr[1] + add * light->color[1];
+ color[2] = (float) ptr[2] + add * light->color[2];
+ ColorToBytes(color, ptr);
+ }
+ }
+ }
+}
+*/
+
+/*
+=============
+VS_GetFilter
+
+FIXME: don't use a lightmap pixel origin but use the four corner points
+ to map part of a translucent surface onto the lightmap pixel
+=============
+*/
+void VS_GetFilter(vsound_t *light, lightvolume_t *volume, vec3_t lmp, vec3_t filter)
+{
+ lFacet_t *facet;
+ lsurfaceTest_t *test;
+ float d, d1, d2, frac, s, t, ns;
+ int i, j, is, it, b;
+ int x, y, u, v, numsamples, radius, color[4], largest;
+ byte *image;
+ vec3_t point, origin, total;
+
+ VectorSet(filter, 1, 1, 1);
+
+ if (noalphashading)
+ return;
+
+ if (volume->numtransFacets <= 0)
+ return;
+
+ if (light->type == LIGHT_SURFACEDIRECTED)
+ {
+ // project the light map pixel origin onto the area light source plane
+ d = DotProduct(lmp, light->normal) - DotProduct(light->normal, light->w.points[0]);
+ VectorMA(lmp, -d, light->normal, origin);
+ }
+ else
+ {
+ VectorCopy(light->origin, origin);
+ }
+ for (i = 0; i < volume->numtransFacets; i++)
+ {
+ test = lsurfaceTest[ volume->transSurfaces[i] ];
+ facet = &test->facets[ volume->transFacets[i] ];
+ // if this surface does not cast an alpha shadow
+ if ( !(test->shader->surfaceFlags & SURF_ALPHASHADOW) )
+ continue;
+ // if there are no texture pixel available
+ if ( !test->shader->pixels ) {
+ continue;
+ }
+ //
+ d1 = DotProduct( origin, facet->plane.normal) - facet->plane.dist;
+ d2 = DotProduct( lmp, facet->plane.normal ) - facet->plane.dist;
+ // this should never happen because the light volume went through the facet
+ if ( ( d1 < 0 ) == ( d2 < 0 ) ) {
+ continue;
+ }
+ // calculate the crossing point
+ frac = d1 / ( d1 - d2 );
+
+ for ( j = 0 ; j < 3 ; j++ ) {
+ point[j] = origin[j] + frac * ( lmp[j] - origin[j] );
+ }
+
+ s = DotProduct( point, facet->textureMatrix[0] ) + facet->textureMatrix[0][3];
+ t = DotProduct( point, facet->textureMatrix[1] ) + facet->textureMatrix[1][3];
+ if (s < 0)
+ s = 0;
+ if (t < 0)
+ t = 0;
+
+ s = s - floor( s );
+ t = t - floor( t );
+
+ is = s * test->shader->width;
+ it = t * test->shader->height;
+
+ //if old style alpha shading
+ if (nocolorshading) {
+ image = test->shader->pixels + 4 * ( it * test->shader->width + is );
+
+ // alpha filter
+ b = image[3];
+
+ // alpha test makes this a binary option
+ b = b < 128 ? 0 : 255;
+
+ filter[0] = filter[0] * (255-b) / 255;
+ filter[1] = filter[1] * (255-b) / 255;
+ filter[2] = filter[2] * (255-b) / 255;
+ }
+ else {
+ VectorClear(total);
+ numsamples = 0;
+ radius = 2;
+ for ( u = -radius; u <= radius; u++ )
+ {
+ x = is + u;
+ if ( x < 0 || x >= test->shader->width)
+ continue;
+ for ( v = -radius; v <= radius; v++ )
+ {
+ y = it + v;
+ if ( y < 0 || y >= test->shader->height)
+ continue;
+
+ image = test->shader->pixels + 4 * ( y * test->shader->width + x );
+ color[0] = image[0];
+ color[1] = image[1];
+ color[2] = image[2];
+ largest = 0;
+ for (j = 0; j < 3; j++)
+ if (image[j] > largest)
+ largest = image[j];
+ if (largest <= 0 || image[3] == 0) {
+ color[0] = 255;
+ color[1] = 255;
+ color[2] = 255;
+ largest = 255;
+ }
+ total[0] += ((float) color[0]/largest) * (255-image[3]) / 255.0;
+ total[1] += ((float) color[1]/largest) * (255-image[3]) / 255.0;
+ total[2] += ((float) color[2]/largest) * (255-image[3]) / 255.0;
+ numsamples++;
+ }
+ }
+ ns = numsamples;
+ //
+ filter[0] *= total[0] / ns;
+ filter[1] *= total[1] / ns;
+ filter[2] *= total[2] / ns;
+ }
+ }
+}
+
+/*
+=============
+VS_LightSurfaceWithVolume
+=============
+*/
+void VS_LightSurfaceWithVolume( int surfaceNum, int facetNum, vsound_t *light, lightvolume_t *volume )
+{
+ int i;
+ dsurface_t *ds;
+ lFacet_t *facet;
+ lsurfaceTest_t *test;
+ winding_t w;
+ vec3_t base, dir, delta, normal, filter, origin;
+ int min_x[LIGHTMAP_SIZE+2], max_x[LIGHTMAP_SIZE+2];
+ int min_y, max_y, k, x, y, n;
+ float *color, distscale;
+ float d, add, angle, dist, area, insidearea, coords[MAX_POINTS_ON_WINDING+1][2];
+ mesh_t *mesh;
+ byte polygonedges[(LIGHTMAP_SIZE+1) * (LIGHTMAP_SIZE+1) / 8];
+
+
+ ds = &drawSurfaces[surfaceNum];
+
+ // vertex-lit triangle model
+ if ( ds->surfaceType == MST_TRIANGLE_SOUP ) {
+ return;
+ }
+
+ if ( ds->lightmapNum < 0 ) {
+ return; // doesn't need lighting
+ }
+
+ test = lsurfaceTest[ surfaceNum ];
+ facet = &test->facets[ facetNum ];
+
+ if (defaulttracelight && !test->always_vsound)
+ return;
+ if (test->always_tracelight)
+ return;
+
+ memcpy(w.points, facet->points, sizeof(vec3_t) * facet->numpoints);
+ w.numpoints = facet->numpoints;
+
+ for (i = 0; i < volume->numplanes; i++)
+ {
+ //if totally on the back
+ if (VS_ChopWinding(&w, &volume->planes[i], 0.01) == SIDE_BACK)
+ return;
+ }
+
+ // only one thread at a time may write to the lightmap of this surface
+ MutexLock(test->mutex);
+
+ test->numvolumes++;
+
+ if (ds->surfaceType == MST_PATCH)
+ {
+ // FIXME: reduce size and don't mark all as edge
+ min_y = ds->lightmapY + facet->y;
+ max_y = ds->lightmapY + facet->y + facet->height - 1;
+ for (y = min_y; y <= max_y; y++)
+ {
+ min_x[y] = ds->lightmapX + facet->x;
+ max_x[y] = ds->lightmapX + facet->x + facet->width - 1;
+ for (x = min_x[y]; x <= max_x[y]; x++)
+ {
+ n = y * LIGHTMAP_SIZE + x;
+ polygonedges[n >> 3] |= 1 << (n & 7);
+ }
+ }
+ }
+ else
+ {
+ for (i = 0; i < w.numpoints; i++)
+ {
+ float s, t;
+
+ if (i >= MAX_POINTS_ON_WINDING)
+ _printf("coords overflow\n");
+ if (ds->surfaceType != MST_PATCH)
+ {
+ VectorSubtract(w.points[i], facet->mins, delta);
+ s = DotProduct( delta, facet->lightmapMatrix[0] ) + ds->lightmapX + 0.5;
+ t = DotProduct( delta, facet->lightmapMatrix[1] ) + ds->lightmapY + 0.5;
+ if (s >= LIGHTMAP_SIZE)
+ s = LIGHTMAP_SIZE - 0.5;
+ if (s < 0)
+ s = 0;
+ if (t >= LIGHTMAP_SIZE)
+ t = LIGHTMAP_SIZE - 0.5;
+ if (t < 0)
+ t = 0;
+ coords[i][0] = s;
+ coords[i][1] = t;
+ }
+ else
+ {
+ s = DotProduct( w.points[i], facet->lightmapMatrix[0] ) + facet->lightmapMatrix[0][3];
+ t = DotProduct( w.points[i], facet->lightmapMatrix[1] ) + facet->lightmapMatrix[1][3];
+
+ s = s - floor( s );
+ t = t - floor( t );
+
+ coords[i][0] = ds->lightmapX + s * LIGHTMAP_SIZE;// + 0.5;
+ coords[i][1] = ds->lightmapY + t * LIGHTMAP_SIZE;// + 0.5;
+
+ if (coords[i][0] >= LIGHTMAP_SIZE)
+ coords[i][0] -= LIGHTMAP_SIZE;
+ if (coords[i][1] >= LIGHTMAP_SIZE)
+ coords[i][1] -= LIGHTMAP_SIZE;
+ if (coords[i][0] < ds->lightmapX)
+ coords[i][0] = ds->lightmapX;
+ if (coords[i][1] < ds->lightmapY)
+ coords[i][1] = ds->lightmapY;
+ }
+ x = coords[i][0];
+ y = coords[i][1];
+ if (x < ds->lightmapX || x >= LIGHTMAP_SIZE)
+ _printf("VS_LightSurfaceWithVolume: x outside lightmap\n");
+ if (y < ds->lightmapY || y >= LIGHTMAP_SIZE)
+ _printf("VS_LightSurfaceWithVolume: y outside lightmap\n");
+ }
+ coords[i][0] = coords[0][0];
+ coords[i][1] = coords[0][1];
+
+ //
+ min_y = LIGHTMAP_SIZE;
+ max_y = 0;
+ for (i = 0; i < LIGHTMAP_SIZE; i++)
+ {
+ min_x[i] = LIGHTMAP_SIZE;
+ max_x[i] = 0;
+ }
+ memset(polygonedges, 0, sizeof(polygonedges));
+ // scan convert the polygon onto the lightmap
+ // for each edge it marks *every* lightmap pixel the edge goes through
+ // so no brasenham and no scan conversion used for texture mapping but
+ // more something like ray casting
+ // this is necesary because we need all lightmap pixels totally or partly
+ // inside the light volume. these lightmap pixels are only lit for the part
+ // that they are inside the light volume.
+ for (i = 0; i < w.numpoints; i++)
+ {
+ float xf, yf, dx, dy, xstep, ystep, xfrac, yfrac;
+ int xinc, yinc;
+
+ xf = coords[i][0];
+ yf = coords[i][1];
+ dx = coords[i+1][0] - xf;
+ dy = coords[i+1][1] - yf;
+ //
+ x = (int) xf;
+ y = (int) yf;
+ //
+ if (y < min_y)
+ min_y = y;
+ if (y > max_y)
+ max_y = y;
+ //
+ if (fabs(dx) > fabs(dy))
+ {
+ if (dx > 0)
+ {
+ // y fraction at integer x below fractional x
+ yfrac = yf + (floor(xf) - xf) * dy / dx;
+ xinc = 1;
+ }
+ else if (dx < 0)
+ {
+ // y fraction at integer x above fractional x
+ yfrac = yf + (floor(xf) + 1 - xf) * dy / dx;
+ xinc = -1;
+ }
+ else
+ {
+ yfrac = yf;
+ xinc = 0;
+ }
+ // step in y direction per 1 unit in x direction
+ if (dx)
+ ystep = dy / fabs(dx);
+ else
+ ystep = 0;
+ while(1)
+ {
+ if (x < ds->lightmapX || x >= LIGHTMAP_SIZE)
+ _printf("VS_LightSurfaceWithVolume: x outside lightmap\n");
+ if (y < ds->lightmapY || y >= LIGHTMAP_SIZE)
+ _printf("VS_LightSurfaceWithVolume: y outside lightmap\n");
+ //
+ n = y * LIGHTMAP_SIZE + x;
+ polygonedges[n >> 3] |= 1 << (n & 7);
+ if (x < min_x[y])
+ min_x[y] = x;
+ if (x > max_x[y])
+ max_x[y] = x;
+ if (x == (int) coords[i+1][0])
+ break;
+ yfrac += ystep;
+ if (dy > 0)
+ {
+ if (yfrac > (float) y + 1)
+ {
+ y += 1;
+ //
+ n = y * LIGHTMAP_SIZE + x;
+ polygonedges[n >> 3] |= 1 << (n & 7);
+ if (x < min_x[y])
+ min_x[y] = x;
+ if (x > max_x[y])
+ max_x[y] = x;
+ }
+ }
+ else
+ {
+ if (yfrac < (float) y)
+ {
+ y -= 1;
+ //
+ n = y * LIGHTMAP_SIZE + x;
+ polygonedges[n >> 3] |= 1 << (n & 7);
+ if (x < min_x[y])
+ min_x[y] = x;
+ if (x > max_x[y])
+ max_x[y] = x;
+ }
+ }
+ x += xinc;
+ }
+ }
+ else
+ {
+ if (dy > 0)
+ {
+ //x fraction at integer y below fractional y
+ xfrac = xf + (floor(yf) - yf) * dx / dy;
+ yinc = 1;
+ }
+ else if (dy < 0)
+ {
+ //x fraction at integer y above fractional y
+ xfrac = xf + (floor(yf) + 1 - yf) * dx / dy;
+ yinc = -1;
+ }
+ else
+ {
+ xfrac = xf;
+ yinc = 0;
+ }
+ // step in x direction per 1 unit in y direction
+ if (dy)
+ xstep = dx / fabs(dy);
+ else
+ xstep = 0;
+ while(1)
+ {
+ if (x < ds->lightmapX || x >= LIGHTMAP_SIZE)
+ _printf("VS_LightSurfaceWithVolume: x outside lightmap\n");
+ if (y < ds->lightmapY || y >= LIGHTMAP_SIZE)
+ _printf("VS_LightSurfaceWithVolume: y outside lightmap\n");
+ //
+ n = y * LIGHTMAP_SIZE + x;
+ polygonedges[n >> 3] |= 1 << (n & 7);
+ if (x < min_x[y])
+ min_x[y] = x;
+ if (x > max_x[y])
+ max_x[y] = x;
+ if (y == (int) coords[i+1][1])
+ break;
+ xfrac += xstep;
+ if (dx > 0)
+ {
+ if (xfrac > (float) x + 1)
+ {
+ x += 1;
+ //
+ n = y * LIGHTMAP_SIZE + x;
+ polygonedges[n >> 3] |= 1 << (n & 7);
+ if (x < min_x[y])
+ min_x[y] = x;
+ if (x > max_x[y])
+ max_x[y] = x;
+ }
+ }
+ else
+ {
+ if (xfrac < (float) x)
+ {
+ x -= 1;
+ //
+ n = y * LIGHTMAP_SIZE + x;
+ polygonedges[n >> 3] |= 1 << (n & 7);
+ if (x < min_x[y])
+ min_x[y] = x;
+ if (x > max_x[y])
+ max_x[y] = x;
+ }
+ }
+ y += yinc;
+ }
+ }
+ }
+ }
+ // map light onto the lightmap
+ for (y = min_y; y <= max_y; y++)
+ {
+ for (x = min_x[y]; x <= max_x[y]; x++)
+ {
+ if (ds->surfaceType == MST_PATCH)
+ {
+ mesh = test->detailMesh;
+ VectorCopy( mesh->verts[(y-ds->lightmapY)*mesh->width+x-ds->lightmapX].xyz, base);
+ VectorCopy( mesh->verts[(y-ds->lightmapY)*mesh->width+x-ds->lightmapX].normal, normal);
+ //VectorCopy(facet->plane.normal, normal);
+ }
+ else
+ {
+ VectorMA(ds->lightmapOrigin, (float) x - ds->lightmapX, ds->lightmapVecs[0], base);
+ VectorMA(base, (float) y - ds->lightmapY, ds->lightmapVecs[1], base);
+ VectorCopy(facet->plane.normal, normal);
+ }
+ if (light->type == LIGHT_POINTSPOT)
+ {
+ float distByNormal;
+ vec3_t pointAtDist;
+ float radiusAtDist;
+ float sampleRadius;
+ vec3_t distToSample;
+ float coneScale;
+
+ VectorSubtract( light->origin, base, dir );
+
+ distByNormal = -DotProduct( dir, light->normal );
+ if ( distByNormal < 0 ) {
+ continue;
+ }
+ VectorMA( light->origin, distByNormal, light->normal, pointAtDist );
+ radiusAtDist = light->radiusByDist * distByNormal;
+
+ VectorSubtract( base, pointAtDist, distToSample );
+ sampleRadius = VectorLength( distToSample );
+
+ if ( sampleRadius >= radiusAtDist ) {
+ continue; // outside the cone
+ }
+ if ( sampleRadius <= radiusAtDist - 32 ) {
+ coneScale = 1.0; // fully inside
+ } else {
+ coneScale = ( radiusAtDist - sampleRadius ) / 32.0;
+ }
+
+ dist = VectorNormalize( dir, dir );
+ // clamp the distance to prevent super hot spots
+ if ( dist < 16 ) {
+ dist = 16;
+ }
+ angle = DotProduct( normal, dir );
+ if (angle > 1)
+ angle = 1;
+ if (angle > 0) {
+ if ( light->atten_angletype == LAAT_QUADRATIC ) {
+ angle = 1 - angle;
+ angle *= angle;
+ angle = 1 - angle;
+ }
+ else if ( light->atten_angletype == LAAT_DOUBLEQUADRATIC ) {
+ angle = 1 - angle;
+ angle *= angle * angle;
+ angle = 1 - angle;
+ }
+ }
+ if (light->atten_anglescale > 0) {
+ angle /= light->atten_anglescale;
+ if (angle > 1)
+ angle = 1;
+ }
+ if (light->atten_distscale > 0) {
+ distscale = light->atten_distscale;
+ }
+ else {
+ distscale = 1;
+ }
+ //
+ if ( light->atten_disttype == LDAT_NOSCALE ) {
+ add = angle * coneScale;
+ }
+ else if ( light->atten_disttype == LDAT_LINEAR ) {
+ add = angle * light->photons * lightLinearScale * coneScale - dist * distscale;
+ if ( add < 0 ) {
+ add = 0;
+ }
+ }
+ else {
+ add = light->photons / ( dist * dist * distscale) * angle * coneScale;
+ }
+ if (add <= 1.0)
+ continue;
+ }
+ else if (light->type == LIGHT_POINTFAKESURFACE)
+ {
+ // calculate the contribution
+ add = PointToPolygonFormFactor( base, normal, &light->w );
+ if ( add <= 0 ) {
+ if ( light->twosided ) {
+ add = -add;
+ } else {
+ continue;
+ }
+ }
+ }
+ else if (light->type == LIGHT_SURFACEDIRECTED)
+ {
+ //VectorCopy(light->normal, dir);
+ //VectorInverse(dir);
+ // project the light map pixel origin onto the area light source plane
+ d = DotProduct(base, light->normal) - DotProduct(light->normal, light->w.points[0]);
+ VectorMA(base, -d, light->normal, origin);
+ VectorSubtract(origin, base, dir);
+ dist = VectorNormalize(dir, dir);
+ if ( dist < 16 ) {
+ dist = 16;
+ }
+ //
+ angle = DotProduct( normal, dir );
+ if (angle > 1)
+ angle = 1;
+ if (angle > 0) {
+ if ( light->atten_angletype == LAAT_QUADRATIC ) {
+ angle = 1 - angle;
+ angle *= angle;
+ angle = 1 - angle;
+ }
+ else if ( light->atten_angletype == LAAT_DOUBLEQUADRATIC ) {
+ angle = 1 - angle;
+ angle *= angle * angle;
+ angle = 1 - angle;
+ }
+ }
+ if (light->atten_anglescale > 0) {
+ angle /= light->atten_anglescale;
+ if (angle > 1)
+ angle = 1;
+ }
+ if (light->atten_distscale > 0) {
+ distscale = light->atten_distscale;
+ }
+ else {
+ distscale = 1;
+ }
+ if ( light->atten_disttype == LDAT_NOSCALE ) {
+ add = angle;
+ }
+ else if ( light->atten_disttype == LDAT_LINEAR ) {
+ add = angle * light->photons * lightLinearScale - dist * distscale;
+ if ( add < 0 ) {
+ add = 0;
+ }
+ } else { //default quadratic
+ add = light->photons / ( dist * dist * distscale) * angle;
+ }
+ if (add <= 0)
+ continue;
+ }
+ else //normal radial point light
+ {
+ VectorSubtract(light->origin, base, dir);
+ dist = VectorNormalize(dir, dir);
+ if ( dist < 16 ) {
+ dist = 16;
+ }
+ angle = DotProduct( normal, dir );
+ if (angle > 1)
+ angle = 1;
+ if (angle > 0) {
+ if ( light->atten_angletype == LAAT_QUADRATIC ) {
+ angle = 1 - angle;
+ angle *= angle;
+ angle = 1 - angle;
+ }
+ else if ( light->atten_angletype == LAAT_DOUBLEQUADRATIC ) {
+ angle = 1 - angle;
+ angle *= angle * angle;
+ angle = 1 - angle;
+ }
+ }
+ if (light->atten_anglescale > 0) {
+ angle /= light->atten_anglescale;
+ if (angle > 1)
+ angle = 1;
+ }
+ if (light->atten_distscale > 0) {
+ distscale = light->atten_distscale;
+ }
+ else {
+ distscale = 1;
+ }
+ if ( light->atten_disttype == LDAT_NOSCALE ) {
+ add = angle;
+ }
+ else if ( light->atten_disttype == LDAT_LINEAR ) {
+ add = angle * light->photons * lightLinearScale - dist * distscale;
+ if ( add < 0 ) {
+ add = 0;
+ }
+ } else {
+ add = light->photons / ( dist * dist * distscale) * angle;
+ }
+ if (add <= 1.0)
+ continue;
+ }
+ //
+ k = (ds->lightmapNum * LIGHTMAP_HEIGHT + y) * LIGHTMAP_WIDTH + x;
+ //if on one of the edges
+ n = y * LIGHTMAP_SIZE + x;
+ if ((polygonedges[n >> 3] & (1 << (n & 7)) ))
+ {
+ // multiply 'add' by the relative area being lit of the total visible lightmap pixel area
+ //
+ // first create a winding for the lightmap pixel
+ if (ds->surfaceType == MST_PATCH)
+ {
+ mesh = test->detailMesh;
+ if (y-ds->lightmapY >= mesh->height-1)
+ _printf("y outside mesh\n");
+ if (x-ds->lightmapX >= mesh->width-1)
+ _printf("x outside mesh\n");
+ VectorCopy( mesh->verts[(y-ds->lightmapY)*mesh->width+x-ds->lightmapX].xyz, w.points[0]);
+ VectorCopy( mesh->verts[(y+1-ds->lightmapY)*mesh->width+x-ds->lightmapX].xyz, w.points[1]);
+ VectorCopy( mesh->verts[(y+1-ds->lightmapY)*mesh->width+x+1-ds->lightmapX].xyz, w.points[2]);
+ VectorCopy( mesh->verts[(y-ds->lightmapY)*mesh->width+x+1-ds->lightmapX].xyz, w.points[3]);
+ w.numpoints = 4;
+ }
+ else
+ {
+ VectorMA(ds->lightmapOrigin, (float) x - LIGHTMAP_PIXELSHIFT - ds->lightmapX, ds->lightmapVecs[0], w.points[0]);
+ VectorMA(w.points[0], (float) y - LIGHTMAP_PIXELSHIFT - ds->lightmapY, ds->lightmapVecs[1], w.points[0]);
+ VectorMA(ds->lightmapOrigin, (float) x - LIGHTMAP_PIXELSHIFT - ds->lightmapX, ds->lightmapVecs[0], w.points[1]);
+ VectorMA(w.points[1], (float) y - LIGHTMAP_PIXELSHIFT + 1 - ds->lightmapY, ds->lightmapVecs[1], w.points[1]);
+ VectorMA(ds->lightmapOrigin, (float) x - LIGHTMAP_PIXELSHIFT + 1 - ds->lightmapX, ds->lightmapVecs[0], w.points[2]);
+ VectorMA(w.points[2], (float) y - LIGHTMAP_PIXELSHIFT + 1 - ds->lightmapY, ds->lightmapVecs[1], w.points[2]);
+ VectorMA(ds->lightmapOrigin, (float) x - LIGHTMAP_PIXELSHIFT + 1 - ds->lightmapX, ds->lightmapVecs[0], w.points[3]);
+ VectorMA(w.points[3], (float) y - LIGHTMAP_PIXELSHIFT - ds->lightmapY, ds->lightmapVecs[1], w.points[3]);
+ w.numpoints = 4;
+ }
+ //
+ // take the visible area of the lightmap pixel into account
+ //
+ //area = WindingArea(&w);
+ area = lightmappixelarea[k];
+ if (area <= 0)
+ continue;
+ // chop the lightmap pixel winding with the light volume
+ for (i = 0; i < volume->numplanes; i++)
+ {
+ //if totally on the back
+ if (VS_ChopWinding(&w, &volume->planes[i], 0) == SIDE_BACK)
+ break;
+ }
+ // if the lightmap pixel is partly inside the light volume
+ if (i >= volume->numplanes)
+ {
+ insidearea = WindingArea(&w);
+ if (insidearea <= 0)
+ i = 0;
+ add = add * insidearea / area;
+ }
+ else
+ {
+ //DebugNet_DrawWinding(&w, 2);
+ continue; // this shouldn't happen
+ }
+ }
+ // get the light filter from all the translucent surfaces the light volume went through
+ VS_GetFilter(light, volume, base, filter);
+ //
+ color = &lightFloats[k*3];
+ color[0] += add * light->color[0] * filter[0];
+ color[1] += add * light->color[1] * filter[1];
+ color[2] += add * light->color[2] * filter[2];
+ }
+ }
+
+ MutexUnlock(test->mutex);
+}
+
+#endif
+
+/*
+=============
+VS_SplitLightVolume
+=============
+*/
+int VS_SplitLightVolume(lightvolume_t *volume, lightvolume_t *back, plane_t *split, float epsilon)
+{
+ lightvolume_t f, b;
+ vec_t dists[128];
+ int sides[128];
+ int counts[3];
+ vec_t dot;
+ int i, j;
+ vec_t *p1, *p2;
+ vec3_t mid;
+
+ counts[0] = counts[1] = counts[2] = 0;
+
+ // determine sides for each point
+ for (i = 0; i < volume->numplanes; i++)
+ {
+ dot = DotProduct (volume->points[i], split->normal);
+ dot -= split->dist;
+ dists[i] = dot;
+ if (dot > epsilon)
+ sides[i] = SIDE_FRONT;
+ else if (dot < -epsilon)
+ sides[i] = SIDE_BACK;
+ else
+ {
+ sides[i] = SIDE_ON;
+ }
+ counts[sides[i]]++;
+ }
+
+ if (!counts[1])
+ return 0; // completely on front side
+
+ if (!counts[0])
+ return 1; // completely on back side
+
+ sides[i] = sides[0];
+ dists[i] = dists[0];
+
+ f.numplanes = 0;
+ b.numplanes = 0;
+
+ for (i = 0; i < volume->numplanes; i++)
+ {
+ p1 = volume->points[i];
+
+ if (f.numplanes >= MAX_POINTS_ON_FIXED_WINDING)
+ {
+ _printf("WARNING: VS_SplitLightVolume -> MAX_POINTS_ON_FIXED_WINDING overflowed\n");
+ return 0; // can't chop -- fall back to original
+ }
+ if (b.numplanes >= MAX_POINTS_ON_FIXED_WINDING)
+ {
+ _printf("WARNING: VS_SplitLightVolume -> MAX_POINTS_ON_FIXED_WINDING overflowed\n");
+ return 0; // can't chop -- fall back to original
+ }
+
+ if (sides[i] == SIDE_ON)
+ {
+ VectorCopy(p1, f.points[f.numplanes]);
+ VectorCopy(p1, b.points[b.numplanes]);
+ if (sides[i+1] == SIDE_BACK)
+ {
+ f.planes[f.numplanes] = *split;
+ b.planes[b.numplanes] = volume->planes[i];
+ }
+ else if (sides[i+1] == SIDE_FRONT)
+ {
+ f.planes[f.numplanes] = volume->planes[i];
+ b.planes[b.numplanes] = *split;
+ VectorInverse(b.planes[b.numplanes].normal);
+ b.planes[b.numplanes].dist = -b.planes[b.numplanes].dist;
+ }
+ else //this shouldn't happen
+ {
+ f.planes[f.numplanes] = *split;
+ b.planes[b.numplanes] = *split;
+ VectorInverse(b.planes[b.numplanes].normal);
+ b.planes[b.numplanes].dist = -b.planes[b.numplanes].dist;
+ }
+ f.numplanes++;
+ b.numplanes++;
+ continue;
+ }
+
+ if (sides[i] == SIDE_FRONT)
+ {
+ VectorCopy (p1, f.points[f.numplanes]);
+ f.planes[f.numplanes] = volume->planes[i];
+ f.numplanes++;
+ }
+ if (sides[i] == SIDE_BACK)
+ {
+ VectorCopy (p1, b.points[b.numplanes]);
+ b.planes[b.numplanes] = volume->planes[i];
+ b.numplanes++;
+ }
+
+ if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i])
+ continue;
+
+ if (f.numplanes >= MAX_POINTS_ON_FIXED_WINDING)
+ {
+ _printf("WARNING: VS_SplitLightVolume -> MAX_POINTS_ON_FIXED_WINDING overflowed\n");
+ return 0; // can't chop -- fall back to original
+ }
+ if (b.numplanes >= MAX_POINTS_ON_FIXED_WINDING)
+ {
+ _printf("WARNING: VS_SplitLightVolume -> MAX_POINTS_ON_FIXED_WINDING overflowed\n");
+ return 0; // can't chop -- fall back to original
+ }
+
+ // generate a split point
+ p2 = volume->points[(i+1)%volume->numplanes];
+
+ dot = dists[i] / (dists[i]-dists[i+1]);
+ for (j=0 ; j<3 ; j++)
+ { // avoid round off error when possible
+ if (split->normal[j] == 1)
+ mid[j] = split->dist;
+ else if (split->normal[j] == -1)
+ mid[j] = -split->dist;
+ else
+ mid[j] = p1[j] + dot*(p2[j]-p1[j]);
+ }
+
+ VectorCopy (mid, f.points[f.numplanes]);
+ VectorCopy(mid, b.points[b.numplanes]);
+ if (sides[i+1] == SIDE_BACK)
+ {
+ f.planes[f.numplanes] = *split;
+ b.planes[b.numplanes] = volume->planes[i];
+ }
+ else
+ {
+ f.planes[f.numplanes] = volume->planes[i];
+ b.planes[b.numplanes] = *split;
+ VectorInverse(b.planes[b.numplanes].normal);
+ b.planes[b.numplanes].dist = -b.planes[b.numplanes].dist;
+ }
+ f.numplanes++;
+ b.numplanes++;
+ }
+ memcpy(volume->points, f.points, sizeof(vec3_t) * f.numplanes);
+ memcpy(volume->planes, f.planes, sizeof(plane_t) * f.numplanes);
+ volume->numplanes = f.numplanes;
+ memcpy(back->points, b.points, sizeof(vec3_t) * b.numplanes);
+ memcpy(back->planes, b.planes, sizeof(plane_t) * b.numplanes);
+ back->numplanes = b.numplanes;
+
+ return 2;
+}
+
+/*
+=============
+VS_PlaneForEdgeToWinding
+=============
+*/
+void VS_PlaneForEdgeToWinding(vec3_t p1, vec3_t p2, winding_t *w, int windingonfront, plane_t *plane)
+{
+ int i, j;
+ float length, d;
+ vec3_t v1, v2;
+
+ VectorSubtract(p2, p1, v1);
+ for (i = 0; i < w->numpoints; i++)
+ {
+ VectorSubtract (w->points[i], p1, v2);
+
+ plane->normal[0] = v1[1]*v2[2] - v1[2]*v2[1];
+ plane->normal[1] = v1[2]*v2[0] - v1[0]*v2[2];
+ plane->normal[2] = v1[0]*v2[1] - v1[1]*v2[0];
+
+ // if points don't make a valid plane, skip it
+ length = plane->normal[0] * plane->normal[0]
+ + plane->normal[1] * plane->normal[1]
+ + plane->normal[2] * plane->normal[2];
+
+ if (length < ON_EPSILON)
+ continue;
+
+ length = 1/sqrt(length);
+
+ plane->normal[0] *= length;
+ plane->normal[1] *= length;
+ plane->normal[2] *= length;
+
+ plane->dist = DotProduct (w->points[i], plane->normal);
+ //
+ for (j = 0; j < w->numpoints; j++)
+ {
+ if (j == i)
+ continue;
+ d = DotProduct(w->points[j], plane->normal) - plane->dist;
+ if (windingonfront)
+ {
+ if (d < -ON_EPSILON)
+ break;
+ }
+ else
+ {
+ if (d > ON_EPSILON)
+ break;
+ }
+ }
+ if (j >= w->numpoints)
+ return;
+ }
+}
+
+/*
+=============
+VS_R_CastLightAtSurface
+=============
+*/
+void VS_R_FloodLight(vsound_t *light, lightvolume_t *volume, int cluster, int firstportal);
+
+void VS_R_CastLightAtSurface(vsound_t *light, lightvolume_t *volume)
+{
+ lsurfaceTest_t *test;
+ int i, n;
+
+ // light the surface with this volume
+ VS_LightSurfaceWithVolume(volume->surfaceNum, volume->facetNum, light, volume);
+ //
+ test = lsurfaceTest[ volume->surfaceNum ];
+ // if this is not a translucent surface
+ if ( !(test->shader->surfaceFlags & SURF_ALPHASHADOW) && !(test->shader->contents & CONTENTS_TRANSLUCENT))
+ return;
+ //
+ if (volume->numtransFacets >= MAX_TRANSLUCENTFACETS)
+ Error("a light valume went through more than %d translucent facets", MAX_TRANSLUCENTFACETS);
+ //add this translucent surface to the list
+ volume->transSurfaces[volume->numtransFacets] = volume->surfaceNum;
+ volume->transFacets[volume->numtransFacets] = volume->facetNum;
+ volume->numtransFacets++;
+ //clear the tested facets except the translucent ones
+ memset(volume->facetTested, 0, sizeof(volume->facetTested));
+ for (i = 0; i < volume->numtransFacets; i++)
+ {
+ test = lsurfaceTest[ volume->transSurfaces[i] ];
+ n = test->facets[volume->transFacets[i]].num;
+ volume->facetTested[n >> 3] |= 1 << (n & 7);
+ }
+ memset(volume->clusterTested, 0, sizeof(volume->clusterTested));
+ volume->endplane = volume->farplane;
+ volume->surfaceNum = -1;
+ volume->facetNum = 0;
+ VS_R_FloodLight(light, volume, volume->cluster, 0);
+ if (volume->surfaceNum >= 0)
+ {
+ VS_R_CastLightAtSurface(light, volume);
+ }
+}
+
+/*
+=============
+VS_R_SplitLightVolume
+=============
+*/
+static int numvolumes = 0;
+
+int VS_R_SplitLightVolume(vsound_t *light, lightvolume_t *volume, plane_t *split, int cluster, int firstportal)
+{
+ lightvolume_t back;
+ int res;
+
+ //
+ res = VS_SplitLightVolume(volume, &back, split, 0.1);
+ // if the volume was split
+ if (res == 2)
+ {
+ memcpy(back.clusterTested, volume->clusterTested, sizeof(back.clusterTested));
+ memcpy(back.facetTested, volume->facetTested, sizeof(back.facetTested));
+ back.num = numvolumes++;
+ back.endplane = volume->endplane;
+ back.surfaceNum = volume->surfaceNum;
+ back.facetNum = volume->facetNum;
+ back.type = volume->type;
+ back.cluster = volume->cluster;
+ back.farplane = volume->farplane;
+ if (volume->numtransFacets > 0)
+ {
+ memcpy(back.transFacets, volume->transFacets, sizeof(back.transFacets));
+ memcpy(back.transSurfaces, volume->transSurfaces, sizeof(back.transSurfaces));
+ }
+ back.numtransFacets = volume->numtransFacets;
+ //
+ // flood the volume at the back of the split plane
+ VS_R_FloodLight(light, &back, cluster, firstportal);
+ // if the back volume hit a surface
+ if (back.surfaceNum >= 0)
+ {
+ VS_R_CastLightAtSurface(light, &back);
+ }
+ }
+ return res;
+}
+
+/*
+=============
+VS_R_FloodLight
+=============
+*/
+void VS_R_FloodLight(vsound_t *light, lightvolume_t *volume, int cluster, int firstportal)
+{
+ int i, j, k, res, surfaceNum, backfaceculled, testculled;
+ float d;
+ winding_t winding, tmpwinding;
+ lleaf_t *leaf;
+ lportal_t *p;
+ lsurfaceTest_t *test;
+ lFacet_t *facet;
+ vec3_t dir1, dir2;
+ plane_t plane;
+
+ // DebugNet_RemoveAllPolys();
+ // VS_DrawLightVolume(light, volume);
+
+ // if the first portal is not zero then we've checked all occluders in this leaf already
+ if (firstportal == 0)
+ {
+ // check all potential occluders in this leaf
+ for (i = 0; i < leafs[cluster].numSurfaces; i++)
+ {
+ surfaceNum = clustersurfaces[leafs[cluster].firstSurface + i];
+ //
+ test = lsurfaceTest[ surfaceNum ];
+ if ( !test )
+ continue;
+ //
+ testculled = qfalse;
+ // use surface as an occluder
+ for (j = 0; j < test->numFacets; j++)
+ {
+ // use each facet as an occluder
+ facet = &test->facets[j];
+ //
+ // memcpy(winding.points, facet->points, sizeof(vec3_t) * facet->numpoints);
+ // winding.numpoints = facet->numpoints;
+ // DebugNet_DrawWinding(&winding, 5);
+ //
+ // if the facet was tested already
+ if ( volume->facetTested[facet->num >> 3] & (1 << (facet->num & 7)) )
+ continue;
+ volume->facetTested[facet->num >> 3] |= 1 << (facet->num & 7);
+ // backface culling for planar surfaces
+ backfaceculled = qfalse;
+ if (!test->patch && !test->trisoup)
+ {
+ if (volume->type == VOLUME_NORMAL)
+ {
+ // facet backface culling
+ d = DotProduct(light->origin, facet->plane.normal) - facet->plane.dist;
+ if (d < 0)
+ {
+ // NOTE: this doesn't work too great because of sometimes very bad tesselation
+ // of surfaces that are supposed to be flat
+ // FIXME: to work around this problem we should make sure that all facets
+ // created from planar surfaces use the lightmapVecs normal vector
+ /*
+ if ( !test->shader->twoSided )
+ {
+ // skip all other facets of this surface as well because they are in the same plane
+ for (k = 0; k < test->numFacets; k++)
+ {
+ facet = &test->facets[k];
+ volume->facetTested[facet->num >> 3] |= 1 << (facet->num & 7);
+ }
+ }*/
+ backfaceculled = qtrue;
+ }
+ }
+ else
+ {
+ // FIXME: if all light source winding points are at the back of the facet
+ // plane then backfaceculled = qtrue
+ }
+ }
+ else // backface culling per facet for patches and triangle soups
+ {
+ if (volume->type == VOLUME_NORMAL)
+ {
+ // facet backface culling
+ d = DotProduct(light->origin, facet->plane.normal) - facet->plane.dist;
+ if (d < 0)
+ backfaceculled = qtrue;
+ }
+ else
+ {
+ // FIXME: if all light source winding points are at the back of the facet
+ // plane then backfaceculled = qtrue
+ }
+ }
+ /* chopping does this already
+ // check if this facet is totally or partly in front of the volume end plane
+ for (k = 0; k < facet->numpoints; k++)
+ {
+ d = DotProduct(volume->endplane.normal, facet->points[k]) - volume->endplane.dist;
+ if (d > ON_EPSILON)
+ break;
+ }
+ // if this facet is outside the light volume
+ if (k >= facet->numpoints)
+ continue;
+ */
+ //
+ if (backfaceculled)
+ {
+ // if the facet is not two sided
+ if ( !nobackfaceculling && !test->shader->twoSided )
+ continue;
+ // flip the winding
+ for (k = 0; k < facet->numpoints; k++)
+ VectorCopy(facet->points[k], winding.points[facet->numpoints - k - 1]);
+ winding.numpoints = facet->numpoints;
+ }
+ else
+ {
+ memcpy(winding.points, facet->points, sizeof(vec3_t) * facet->numpoints);
+ winding.numpoints = facet->numpoints;
+ }
+ //
+ if (!testculled)
+ {
+ testculled = qtrue;
+ // fast check if the surface sphere is totally behind the volume end plane
+ d = DotProduct(volume->endplane.normal, test->origin) - volume->endplane.dist;
+ if (d < -test->radius)
+ {
+ for (k = 0; k < test->numFacets; k++)
+ {
+ facet = &test->facets[k];
+ volume->facetTested[facet->num >> 3] |= 1 << (facet->num & 7);
+ }
+ break;
+ }
+ for (k = 0; k < volume->numplanes; k++)
+ {
+ d = DotProduct(volume->planes[k].normal, test->origin) - volume->planes[k].dist;
+ if (d < - test->radius)
+ {
+ for (k = 0; k < test->numFacets; k++)
+ {
+ facet = &test->facets[k];
+ volume->facetTested[facet->num >> 3] |= 1 << (facet->num & 7);
+ }
+ break;
+ }
+ }
+ if (k < volume->numplanes)
+ break;
+ }
+ //NOTE: we have to chop the facet winding with the volume end plane because
+ // the faces in Q3 are not stitched together nicely
+ res = VS_ChopWinding(&winding, &volume->endplane, 0.01);
+ // if the facet is on or at the back of the volume end plane
+ if (res == SIDE_BACK || res == SIDE_ON)
+ continue;
+ // check if the facet winding is totally or partly inside the light volume
+ memcpy(&tmpwinding, &winding, sizeof(winding_t));
+ for (k = 0; k < volume->numplanes; k++)
+ {
+ res = VS_ChopWinding(&tmpwinding, &volume->planes[k], 0.01);
+ if (res == SIDE_BACK || res == SIDE_ON)
+ break;
+ }
+ // if no part of the light volume is occluded by this facet
+ if (k < volume->numplanes)
+ continue;
+ //
+ for (k = 0; k < winding.numpoints; k++)
+ {
+ if (volume->type == VOLUME_DIRECTED)
+ {
+ VectorSubtract(winding.points[(k+1) % winding.numpoints], winding.points[k], dir1);
+ CrossProduct(light->normal, dir1, plane.normal);
+ VectorNormalize(plane.normal, plane.normal);
+ plane.dist = DotProduct(plane.normal, winding.points[k]);
+ }
+ else
+ {
+ VectorSubtract(winding.points[(k+1) % winding.numpoints], winding.points[k], dir1);
+ VectorSubtract(light->origin, winding.points[k], dir2);
+ CrossProduct(dir1, dir2, plane.normal);
+ VectorNormalize(plane.normal, plane.normal);
+ plane.dist = DotProduct(plane.normal, winding.points[k]);
+ }
+ res = VS_R_SplitLightVolume(light, volume, &plane, cluster, 0);
+ if (res == 1)
+ break; //the facet wasn't really inside the volume
+ }
+ if (k >= winding.numpoints)
+ {
+ volume->endplane = facet->plane;
+ if (backfaceculled)
+ {
+ VectorInverse(volume->endplane.normal);
+ volume->endplane.dist = -volume->endplane.dist;
+ }
+ volume->surfaceNum = surfaceNum;
+ volume->facetNum = j;
+ }
+ }
+ }
+ }
+ // we've tested all occluders in this cluster
+ volume->clusterTested[cluster >> 3] |= 1 << (cluster & 7);
+ // flood light through the portals of the current leaf
+ leaf = &leafs[cluster];
+ for (i = firstportal; i < leaf->numportals; i++)
+ {
+ p = leaf->portals[i];
+ //
+ // memcpy(&winding, p->winding, sizeof(winding_t));
+ // DebugNet_DrawWinding(&winding, 5);
+ // if already flooded into the cluster this portal leads to
+ if ( volume->clusterTested[p->leaf >> 3] & (1 << (p->leaf & 7)) )
+ continue;
+ //
+ if (volume->type == VOLUME_NORMAL)
+ {
+ // portal backface culling
+ d = DotProduct(light->origin, p->plane.normal) - p->plane.dist;
+ if (d > 0) // portal plane normal points into neighbour cluster
+ continue;
+ }
+ else
+ {
+ // FIXME: if all light source winding points are at the back of this portal
+ // plane then there's no need to flood through
+ }
+ // check if this portal is totally or partly in front of the volume end plane
+ // fast check with portal sphere
+ d = DotProduct(volume->endplane.normal, p->origin) - volume->endplane.dist;
+ if (d < -p->radius)
+ continue;
+ for (j = 0; j < p->winding->numpoints; j++)
+ {
+ d = DotProduct(volume->endplane.normal, p->winding->points[j]) - volume->endplane.dist;
+ if (d > -0.01)
+ break;
+ }
+ // if this portal is totally behind the light volume end plane
+ if (j >= p->winding->numpoints)
+ continue;
+ //distance from point light to portal
+ d = DotProduct(p->plane.normal, light->origin) - p->plane.dist;
+ // only check if a point light is Not *on* the portal
+ if (volume->type != VOLUME_NORMAL || fabs(d) > 0.1)
+ {
+ // check if the portal is partly or totally inside the light volume
+ memcpy(&winding, p->winding, sizeof(winding_t));
+ for (j = 0; j < volume->numplanes; j++)
+ {
+ res = VS_ChopWinding(&winding, &volume->planes[j], 0.01);
+ if (res == SIDE_BACK || res == SIDE_ON)
+ break;
+ }
+ // if the light volume does not go through this portal at all
+ if (j < volume->numplanes)
+ continue;
+ }
+ // chop the light volume with the portal
+ for (k = 0; k < p->winding->numpoints; k++)
+ {
+ if (volume->type == VOLUME_DIRECTED)
+ {
+ VectorSubtract(p->winding->points[(k+1) % p->winding->numpoints], p->winding->points[k], dir1);
+ CrossProduct(light->normal, dir1, plane.normal);
+ VectorNormalize(plane.normal, plane.normal);
+ plane.dist = DotProduct(plane.normal, p->winding->points[k]);
+ }
+ else
+ {
+ VectorSubtract(p->winding->points[(k+1) % p->winding->numpoints], p->winding->points[k], dir1);
+ VectorSubtract(light->origin, p->winding->points[k], dir2);
+ CrossProduct(dir1, dir2, plane.normal);
+ VectorNormalize(plane.normal, plane.normal);
+ plane.dist = DotProduct(plane.normal, p->winding->points[k]);
+ }
+ res = VS_R_SplitLightVolume(light, volume, &plane, cluster, i+1);
+ if (res == 1)
+ break; //volume didn't really go through the portal
+ }
+ // if the light volume went through the portal
+ if (k >= p->winding->numpoints)
+ {
+ // flood through the portal
+ VS_R_FloodLight(light, volume, p->leaf, 0);
+ }
+ }
+}
+
+/*
+=============
+VS_R_FloodAreaSpotLight
+=============
+*/
+void VS_FloodAreaSpotLight(vsound_t *light, winding_t *w, int leafnum)
+{
+}
+
+/*
+=============
+VS_R_SubdivideAreaSpotLight
+=============
+*/
+void VS_R_SubdivideAreaSpotLight(vsound_t *light, int nodenum, winding_t *w)
+{
+ int leafnum, res;
+ dnode_t *node;
+ dplane_t *plane;
+ winding_t back;
+ plane_t split;
+
+ while(nodenum >= 0)
+ {
+ node = &dnodes[nodenum];
+ plane = &dplanes[node->planeNum];
+
+ VectorCopy(plane->normal, split.normal);
+ split.dist = plane->dist;
+ res = VS_SplitWinding (w, &back, &split, 0.1);
+
+ if (res == SIDE_FRONT)
+ {
+ nodenum = node->children[0];
+ }
+ else if (res == SIDE_BACK)
+ {
+ nodenum = node->children[1];
+ }
+ else if (res == SIDE_ON)
+ {
+ memcpy(&back, w, sizeof(winding_t));
+ VS_R_SubdivideAreaSpotLight(light, node->children[1], &back);
+ nodenum = node->children[0];
+ }
+ else
+ {
+ VS_R_SubdivideAreaSpotLight(light, node->children[1], &back);
+ nodenum = node->children[0];
+ }
+ }
+ leafnum = -nodenum - 1;
+ if (dleafs[leafnum].cluster != -1)
+ {
+ VS_FloodAreaSpotLight(light, w, leafnum);
+ }
+}
+
+/*
+=============
+VS_R_FloodRadialAreaLight
+=============
+*/
+void VS_FloodRadialAreaLight(vsound_t *light, winding_t *w, int leafnum)
+{
+}
+
+/*
+=============
+VS_R_SubdivideRadialAreaLight
+=============
+*/
+void VS_R_SubdivideRadialAreaLight(vsound_t *light, int nodenum, winding_t *w)
+{
+ int leafnum, res;
+ dnode_t *node;
+ dplane_t *plane;
+ winding_t back;
+ plane_t split;
+
+ while(nodenum >= 0)
+ {
+ node = &dnodes[nodenum];
+ plane = &dplanes[node->planeNum];
+
+ VectorCopy(plane->normal, split.normal);
+ split.dist = plane->dist;
+ res = VS_SplitWinding (w, &back, &split, 0.1);
+
+ if (res == SIDE_FRONT)
+ {
+ nodenum = node->children[0];
+ }
+ else if (res == SIDE_BACK)
+ {
+ nodenum = node->children[1];
+ }
+ else if (res == SIDE_ON)
+ {
+ memcpy(&back, w, sizeof(winding_t));
+ VS_R_SubdivideRadialAreaLight(light, node->children[1], &back);
+ nodenum = node->children[0];
+ }
+ else
+ {
+ VS_R_SubdivideRadialAreaLight(light, node->children[1], &back);
+ nodenum = node->children[0];
+ }
+ }
+ leafnum = -nodenum - 1;
+ if (dleafs[leafnum].cluster != -1)
+ {
+ VS_FloodRadialAreaLight(light, w, leafnum);
+ }
+}
+
+/*
+=============
+VS_R_FloodDirectedLight
+=============
+*/
+void VS_FloodDirectedLight(vsound_t *light, winding_t *w, int leafnum)
+{
+ int i;
+ float dist;
+ lightvolume_t volume;
+ vec3_t dir;
+
+ if (light->atten_disttype == LDAT_NOSCALE)
+ {
+ // light travels without decrease in intensity over distance
+ dist = MAX_WORLD_COORD;
+ }
+ else
+ {
+ if ( light->atten_disttype == LDAT_LINEAR )
+ dist = light->photons * lightLinearScale;
+ else
+ dist = sqrt(light->photons);
+ }
+
+ memset(&volume, 0, sizeof(lightvolume_t));
+ for (i = 0; i < w->numpoints; i++)
+ {
+ VectorMA(w->points[i], dist, light->normal, volume.points[i]);
+ VectorSubtract(w->points[(i+1)%w->numpoints], w->points[i], dir);
+ CrossProduct(light->normal, dir, volume.planes[i].normal);
+ VectorNormalize(volume.planes[i].normal, volume.planes[i].normal);
+ volume.planes[i].dist = DotProduct(volume.planes[i].normal, w->points[i]);
+ }
+ volume.numplanes = w->numpoints;
+ VectorCopy(light->normal, volume.endplane.normal);
+ VectorInverse(volume.endplane.normal);
+ volume.endplane.dist = DotProduct(volume.endplane.normal, volume.points[0]);
+ volume.farplane = volume.endplane;
+ volume.surfaceNum = -1;
+ volume.type = VOLUME_DIRECTED;
+ volume.cluster = dleafs[leafnum].cluster;
+ VS_R_FloodLight(light, &volume, volume.cluster, 0);
+ if (volume.surfaceNum >= 0)
+ {
+ VS_R_CastLightAtSurface(light, &volume);
+ }
+}
+
+/*
+=============
+VS_R_SubdivideDirectedAreaLight
+=============
+*/
+void VS_R_SubdivideDirectedAreaLight(vsound_t *light, int nodenum, winding_t *w)
+{
+ int leafnum, res;
+ dnode_t *node;
+ dplane_t *plane;
+ winding_t back;
+ plane_t split;
+
+ while(nodenum >= 0)
+ {
+ node = &dnodes[nodenum];
+ plane = &dplanes[node->planeNum];
+
+ VectorCopy(plane->normal, split.normal);
+ split.dist = plane->dist;
+ res = VS_SplitWinding (w, &back, &split, 0.1);
+
+ if (res == SIDE_FRONT)
+ {
+ nodenum = node->children[0];
+ }
+ else if (res == SIDE_BACK)
+ {
+ nodenum = node->children[1];
+ }
+ else if (res == SIDE_ON)
+ {
+ memcpy(&back, w, sizeof(winding_t));
+ VS_R_SubdivideDirectedAreaLight(light, node->children[1], &back);
+ nodenum = node->children[0];
+ }
+ else
+ {
+ VS_R_SubdivideDirectedAreaLight(light, node->children[1], &back);
+ nodenum = node->children[0];
+ }
+ }
+ leafnum = -nodenum - 1;
+ if (dleafs[leafnum].cluster != -1)
+ {
+ VS_FloodDirectedLight(light, w, leafnum);
+ }
+}
+
+/*
+=============
+VS_FloodLight
+=============
+*/
+void VS_FloodLight(vsound_t *light)
+{
+ lightvolume_t volume;
+ dleaf_t *leaf;
+ int leafnum, i, j, k, dir[2][4] = {{1, 1, -1, -1}, {1, -1, -1, 1}};
+ float a, step, dist, radius, windingdist;
+ vec3_t vec, r, p, temp;
+ winding_t winding;
+
+ switch(light->type)
+ {
+ case LIGHT_POINTRADIAL:
+ {
+ // source is a point
+ // light radiates in all directions
+ // creates sharp shadows
+ //
+ // create 6 volumes shining in the axis directions
+ // what about: 4 tetrahedrons instead?
+ //
+ if ( light->atten_disttype == LDAT_LINEAR )
+ dist = light->photons * lightLinearScale;
+ else
+ dist = sqrt(light->photons);
+ //always put the winding at a large distance to avoid epsilon issues
+ windingdist = MAX_WORLD_COORD;
+ if (dist > windingdist)
+ windingdist = dist;
+ //
+ leafnum = VS_LightLeafnum(light->origin);
+ leaf = &dleafs[leafnum];
+ if (leaf->cluster == -1)
+ {
+ light->insolid = qtrue;
+ break;
+ }
+ // for each axis
+ for (i = 0; i < 3; i++)
+ {
+ // for both directions on the axis
+ for (j = -1; j <= 1; j += 2)
+ {
+ memset(&volume, 0, sizeof(lightvolume_t));
+ volume.numplanes = 0;
+ for (k = 0; k < 4; k ++)
+ {
+ volume.points[volume.numplanes][i] = light->origin[i] + j * windingdist;
+ volume.points[volume.numplanes][(i+1)%3] = light->origin[(i+1)%3] + dir[0][k] * windingdist;
+ volume.points[volume.numplanes][(i+2)%3] = light->origin[(i+2)%3] + dir[1][k] * windingdist;
+ volume.numplanes++;
+ }
+ if (j >= 0)
+ {
+ VectorCopy(volume.points[0], temp);
+ VectorCopy(volume.points[2], volume.points[0]);
+ VectorCopy(temp, volume.points[2]);
+ }
+ for (k = 0; k < volume.numplanes; k++)
+ {
+ VS_PlaneFromPoints(&volume.planes[k], light->origin, volume.points[(k+1)%volume.numplanes], volume.points[k]);
+ }
+ VectorCopy(light->origin, temp);
+ temp[i] += (float) j * dist;
+ VectorClear(volume.endplane.normal);
+ volume.endplane.normal[i] = -j;
+ volume.endplane.dist = DotProduct(volume.endplane.normal, temp); //DotProduct(volume.endplane.normal, volume.points[0]);
+ volume.farplane = volume.endplane;
+ volume.cluster = leaf->cluster;
+ volume.surfaceNum = -1;
+ volume.type = VOLUME_NORMAL;
+ //
+ memset(volume.facetTested, 0, sizeof(volume.facetTested));
+ memset(volume.clusterTested, 0, sizeof(volume.clusterTested));
+ VS_R_FloodLight(light, &volume, leaf->cluster, 0);
+ if (volume.surfaceNum >= 0)
+ {
+ VS_R_CastLightAtSurface(light, &volume);
+ }
+ }
+ }
+ break;
+ }
+ case LIGHT_POINTSPOT:
+ {
+ // source is a point
+ // light is targetted
+ // creates sharp shadows
+ //
+ // what about using brushes to shape spot lights? that'd be pretty cool
+ //
+ if ( light->atten_disttype == LDAT_LINEAR )
+ dist = light->photons * lightLinearScale;
+ else
+ dist = sqrt(light->photons);
+ dist *= 2;
+ //
+ windingdist = 4096;
+ if (dist > windingdist)
+ windingdist = dist;
+ //take 8 times the cone radius because the spotlight also lights outside the cone
+ radius = 8 * windingdist * light->radiusByDist;
+ //
+ memset(&volume, 0, sizeof(lightvolume_t));
+ leafnum = VS_LightLeafnum(light->origin);
+ leaf = &dleafs[leafnum];
+ if (leaf->cluster == -1)
+ {
+ light->insolid = qtrue;
+ break;
+ }
+ //
+ VectorClear(vec);
+ for (i = 0; i < 3; i++)
+ {
+ if (light->normal[i] > -0.9 && light->normal[i] < 0.9)
+ {
+ vec[i] = 1;
+ break;
+ }
+ }
+ CrossProduct(light->normal, vec, r);
+ VectorScale(r, radius, p);
+ volume.numplanes = 0;
+ step = 45;
+ for (a = step / 2; a < 360 + step / 2; a += step)
+ {
+ RotatePointAroundVector(volume.points[volume.numplanes], light->normal, p, a);
+ VectorAdd(light->origin, volume.points[volume.numplanes], volume.points[volume.numplanes]);
+ VectorMA(volume.points[volume.numplanes], windingdist, light->normal, volume.points[volume.numplanes]);
+ volume.numplanes++;
+ }
+ for (i = 0; i < volume.numplanes; i++)
+ {
+ VS_PlaneFromPoints(&volume.planes[i], light->origin, volume.points[(i+1)%volume.numplanes], volume.points[i]);
+ }
+ VectorMA(light->origin, dist, light->normal, temp);
+ VectorCopy(light->normal, volume.endplane.normal);
+ VectorInverse(volume.endplane.normal);
+ volume.endplane.dist = DotProduct(volume.endplane.normal, temp);//DotProduct(volume.endplane.normal, volume.points[0]);
+ volume.farplane = volume.endplane;
+ volume.cluster = leaf->cluster;
+ volume.surfaceNum = -1;
+ volume.type = VOLUME_NORMAL;
+ //
+ memset(volume.facetTested, 0, sizeof(volume.facetTested));
+ memset(volume.clusterTested, 0, sizeof(volume.clusterTested));
+ VS_R_FloodLight(light, &volume, leaf->cluster, 0);
+ if (volume.surfaceNum >= 0)
+ {
+ VS_R_CastLightAtSurface(light, &volume);
+ }
+ break;
+ }
+ case LIGHT_POINTFAKESURFACE:
+ {
+ float value;
+ int n, axis;
+ vec3_t v, vecs[2];
+
+ if ( light->atten_disttype == LDAT_LINEAR )
+ dist = light->photons * lightLinearScale;
+ else
+ dist = sqrt(light->photons);
+ //always put the winding at a large distance to avoid epsilon issues
+ windingdist = 4096;
+ if (dist > windingdist)
+ windingdist = dist;
+ //
+ VectorMA(light->origin, 0.1, light->normal, light->origin);
+ //
+ leafnum = VS_LightLeafnum(light->origin);
+ leaf = &dleafs[leafnum];
+ if (leaf->cluster == -1)
+ {
+ light->insolid = qtrue;
+ break;
+ }
+ value = 0;
+ for (i = 0; i < 3; i++)
+ {
+ if (fabs(light->normal[i]) > value)
+ {
+ value = fabs(light->normal[i]);
+ axis = i;
+ }
+ }
+ for (i = 0; i < 2; i++)
+ {
+ VectorClear(v);
+ v[(axis + 1 + i) % 3] = 1;
+ CrossProduct(light->normal, v, vecs[i]);
+ }
+ //cast 4 volumes at the front of the surface
+ for (i = -1; i <= 1; i += 2)
+ {
+ for (j = -1; j <= 1; j += 2)
+ {
+ for (n = 0; n < 2; n++)
+ {
+ memset(&volume, 0, sizeof(lightvolume_t));
+ volume.numplanes = 3;
+ VectorMA(light->origin, i * windingdist, vecs[0], volume.points[(i == j) == n]);
+ VectorMA(light->origin, j * windingdist, vecs[1], volume.points[(i != j) == n]);
+ VectorMA(light->origin, windingdist, light->normal, volume.points[2]);
+ for (k = 0; k < volume.numplanes; k++)
+ {
+ VS_PlaneFromPoints(&volume.planes[k], light->origin, volume.points[(k+1)%volume.numplanes], volume.points[k]);
+ }
+ VS_PlaneFromPoints(&volume.endplane, volume.points[0], volume.points[1], volume.points[2]);
+ VectorMA(light->origin, dist, light->normal, temp);
+ volume.endplane.dist = DotProduct(volume.endplane.normal, temp);
+ if (DotProduct(light->origin, volume.endplane.normal) - volume.endplane.dist > 0)
+ break;
+ }
+ volume.farplane = volume.endplane;
+ volume.cluster = leaf->cluster;
+ volume.surfaceNum = -1;
+ volume.type = VOLUME_NORMAL;
+ //
+ memset(volume.facetTested, 0, sizeof(volume.facetTested));
+ memset(volume.clusterTested, 0, sizeof(volume.clusterTested));
+
+ VS_R_FloodLight(light, &volume, leaf->cluster, 0);
+ if (volume.surfaceNum >= 0)
+ {
+ VS_R_CastLightAtSurface(light, &volume);
+ }
+ }
+ }
+ break;
+ }
+ case LIGHT_SURFACEDIRECTED:
+ {
+ // source is an area defined by a winding
+ // the light is unidirectional
+ // creates sharp shadows
+ // for instance sun light or laser light
+ //
+ memcpy(&winding, &light->w, sizeof(winding_t));
+ VS_R_SubdivideDirectedAreaLight(light, 0, &winding);
+ break;
+ }
+ case LIGHT_SURFACERADIAL:
+ {
+ // source is an area defined by a winding
+ // the light radiates in all directions at the front of the winding plane
+ //
+ memcpy(&winding, &light->w, sizeof(winding_t));
+ VS_R_SubdivideRadialAreaLight(light, 0, &winding);
+ break;
+ }
+ case LIGHT_SURFACESPOT:
+ {
+ // source is an area defined by a winding
+ // light is targetted but not unidirectional
+ //
+ memcpy(&winding, &light->w, sizeof(winding_t));
+ VS_R_SubdivideAreaSpotLight(light, 0, &winding);
+ break;
+ }
+ }
+}
+
+/*
+=============
+VS_FloodLightThread
+=============
+*/
+void VS_FloodLightThread(int num)
+{
+ VS_FloodLight(vsounds[num]);
+}
+
+/*
+=============
+VS_TestLightLeafs
+=============
+*/
+void VS_TestLightLeafs(void)
+{
+ int leafnum, i;
+ vsound_t *light;
+ dleaf_t *leaf;
+
+ for (i = 0; i < numvsounds; i++)
+ {
+ light = vsounds[i];
+ if (light->type != LIGHT_POINTRADIAL &&
+ light->type != LIGHT_POINTSPOT)
+ continue;
+ leafnum = VS_LightLeafnum(light->origin);
+ leaf = &dleafs[leafnum];
+ if (leaf->cluster == -1)
+ if (light->type == LIGHT_POINTRADIAL)
+ qprintf("light in solid at %1.1f %1.1f %1.1f\n", light->origin[0], light->origin[1], light->origin[2]);
+ else if (light->type == LIGHT_POINTSPOT)
+ qprintf("spot light in solid at %1.1f %1.1f %1.1f\n", light->origin[0], light->origin[1], light->origin[2]);
+ }
+}
+
+
+/*
+=============
+VS_DoForcedTraceLight
+=============
+*/
+// from light.c
+void TraceLtm( int num );
+
+void VS_DoForcedTraceLight(int num)
+{
+ dsurface_t *ds;
+ shaderInfo_t *si;
+
+ ds = &drawSurfaces[num];
+
+ if ( ds->surfaceType == MST_TRIANGLE_SOUP )
+ return;
+
+ if ( ds->lightmapNum < 0 )
+ return;
+
+ // always light entity surfaces with the old light algorithm
+ if ( !entitySurface[num] )
+ {
+ si = ShaderInfoForShader( dshaders[ ds->shaderNum].shader );
+
+ if (defaulttracelight)
+ {
+ if (si->forceVLight)
+ return;
+ }
+ else
+ {
+ if (!si->forceTraceLight)
+ return;
+ }
+ }
+
+ TraceLtm(num);
+}
+
+/*
+=============
+VS_DoForcedTraceLightSurfaces
+=============
+*/
+void VS_DoForcedTraceLightSurfaces(void)
+{
+ _printf( "forced trace light\n" );
+ RunThreadsOnIndividual( numDrawSurfaces, qtrue, VS_DoForcedTraceLight );
+}
+
+float *oldLightFloats;
+
+/*
+=============
+VS_SurfaceRadiosity
+=============
+*/
+void VS_SurfaceRadiosity( int num ) {
+ dsurface_t *ds;
+ mesh_t *mesh;
+ shaderInfo_t *si;
+ lsurfaceTest_t *test;
+ int x, y, k;
+ vec3_t base, normal;
+ float *color, area;
+ vsound_t vsound;
+
+ ds = &drawSurfaces[num];
+
+ if ( ds->lightmapNum < 0 ) {
+ return; // doesn't have a lightmap
+ }
+
+ // vertex-lit triangle model
+ if ( ds->surfaceType == MST_TRIANGLE_SOUP ) {
+ return;
+ }
+
+ si = ShaderInfoForShader( dshaders[ ds->shaderNum].shader );
+ test = lsurfaceTest[ num ];
+
+ if (!test) {
+ return;
+ }
+
+ for (x = 0; x < ds->lightmapWidth; x++) {
+ for (y = 0; y < ds->lightmapHeight; y++) {
+ //
+ k = ( ds->lightmapNum * LIGHTMAP_HEIGHT + ds->lightmapY + y)
+ * LIGHTMAP_WIDTH + ds->lightmapX + x;
+ area = lightmappixelarea[k];
+ if (area <= 0)
+ continue;
+ //
+ if (ds->surfaceType == MST_PATCH)
+ {
+ mesh = test->detailMesh;
+ VectorCopy( mesh->verts[y*mesh->width+x].xyz, base);
+ VectorCopy( mesh->verts[y*mesh->width+x].normal, normal);
+ }
+ else
+ {
+ VectorMA(ds->lightmapOrigin, (float) x, ds->lightmapVecs[0], base);
+ VectorMA(base, (float) y, ds->lightmapVecs[1], base);
+ VectorCopy(test->facets[0].plane.normal, normal);
+ }
+ // create ligth from base
+ memset(&vsound, 0, sizeof(vsound_t));
+ color = &oldLightFloats[k*3];
+ // a few units away from the surface
+ VectorMA(base, 5, normal, vsound.origin);
+ ColorNormalize(color, vsound.color);
+ // ok this is crap
+ vsound.photons = VectorLength(color) * 0.05 * lightPointScale / (area * radiosity_scale);
+ // what about using a front facing light only ?
+ vsound.type = LIGHT_POINTRADIAL;
+ // flood the light from this lightmap pixel
+ VS_FloodLight(&vsound);
+ // only one thread at a time may write to the lightmap of this surface
+ MutexLock(test->mutex);
+ // don't light the lightmap pixel itself
+ lightFloats[k*3] = oldLightFloats[k*3];
+ lightFloats[k*3+1] = oldLightFloats[k*3+1];
+ lightFloats[k*3+2] = oldLightFloats[k*3+2];
+ //
+ MutexUnlock(test->mutex);
+ }
+ }
+}
+
+/*
+=============
+VS_Radiosity
+
+this aint working real well but it's fun to play with.
+=============
+*/
+void VS_Radiosity(void) {
+
+ oldLightFloats = lightFloats;
+ lightFloats = (float *) malloc(numLightBytes * sizeof(float));
+ memcpy(lightFloats, oldLightFloats, numLightBytes * sizeof(float));
+ _printf("%7i surfaces\n", numDrawSurfaces);
+ RunThreadsOnIndividual( numDrawSurfaces, qtrue, VS_SurfaceRadiosity );
+ free(oldLightFloats);
+}
+
+/*
+=============
+VS_LightWorld
+=============
+*/
+void VS_LightWorld(void)
+{
+ int i, numcastedvolumes, numvsoundsinsolid;
+ float f;
+
+ // find the optional world ambient
+ GetVectorForKey( &entities[0], "_color", lightAmbientColor );
+ f = FloatForKey( &entities[0], "ambient" );
+ VectorScale( lightAmbientColor, f, lightAmbientColor );
+ /*
+ _printf("\r%6d lights out of %d", 0, numvsounds);
+ for (i = 0; i < numvsounds; i++)
+ {
+ _printf("\r%6d", i);
+ VS_FloodLight(vsounds[i]);
+ }
+ _printf("\r%6d lights out of %d\n", i, numvsounds);
+ */
+ _printf("%7i lights\n", numvsounds);
+ RunThreadsOnIndividual( numvsounds, qtrue, VS_FloodLightThread );
+
+ numcastedvolumes = 0;
+ for ( i = 0 ; i < numDrawSurfaces ; i++ ) {
+ if (lsurfaceTest[i])
+ numcastedvolumes += lsurfaceTest[i]->numvolumes;
+ }
+ _printf("%7i light volumes casted\n", numcastedvolumes);
+ numvsoundsinsolid = 0;
+ for (i = 0; i < numvsounds; i++)
+ {
+ if (vsounds[i]->insolid)
+ numvsoundsinsolid++;
+ }
+ _printf("%7i lights in solid\n", numvsoundsinsolid);
+ //
+ radiosity_scale = 1;
+ for (i = 0; i < radiosity; i++) {
+ VS_Radiosity();
+ radiosity_scale <<= 1;
+ }
+ //
+ VS_StoreLightmap();
+ // redo surfaces with the old light algorithm when needed
+ VS_DoForcedTraceLightSurfaces();
+}
+
+/*
+=============
+VS_CreateEntitySpeakers
+=============
+*/
+entity_t *FindTargetEntity( const char *target );
+
+void VS_CreateEntitySpeakers (void)
+{
+ int i, c_entityLights;
+ vsound_t *dl;
+ entity_t *e, *e2;
+ const char *name;
+ const char *target;
+ vec3_t dest;
+ const char *_color;
+ float intensity;
+ int spawnflags;
+
+ //
+ c_entityLights = 0;
+ _printf("Creating entity lights...\n");
+ //
+ for ( i = 0 ; i < num_entities ; i++ ) {
+ e = &entities[i];
+ name = ValueForKey (e, "classname");
+ if (strncmp (name, "speaker", 7))
+ continue;
+
+ dl = malloc(sizeof(*dl));
+ memset (dl, 0, sizeof(*dl));
+
+ spawnflags = FloatForKey (e, "spawnflags");
+ if ( spawnflags & 1 ) {
+ dl->atten_disttype = LDAT_LINEAR;
+ }
+ if ( spawnflags & 2 ) {
+ dl->atten_disttype = LDAT_NOSCALE;
+ }
+ if ( spawnflags & 4 ) {
+ dl->atten_angletype = LAAT_QUADRATIC;
+ }
+ if ( spawnflags & 8 ) {
+ dl->atten_angletype = LAAT_DOUBLEQUADRATIC;
+ }
+
+ dl->atten_distscale = FloatForKey(e, "atten_distscale");
+ dl->atten_anglescale = FloatForKey(e, "atten_anglescale");
+
+ GetVectorForKey (e, "origin", dl->origin);
+ dl->style = FloatForKey (e, "_style");
+ if (!dl->style)
+ dl->style = FloatForKey (e, "style");
+ if (dl->style < 0)
+ dl->style = 0;
+
+ intensity = FloatForKey (e, "light");
+ if (!intensity)
+ intensity = FloatForKey (e, "_light");
+ if (!intensity)
+ intensity = 300;
+ _color = ValueForKey (e, "_color");
+ if (_color && _color[0])
+ {
+ sscanf (_color, "%f %f %f", &dl->color[0],&dl->color[1],&dl->color[2]);
+ ColorNormalize (dl->color, dl->color);
+ }
+ else
+ dl->color[0] = dl->color[1] = dl->color[2] = 1.0;
+
+ intensity = intensity * lightPointScale;
+ dl->photons = intensity;
+
+ dl->type = LIGHT_POINTRADIAL;
+
+ // lights with a target will be spotlights
+ target = ValueForKey (e, "target");
+
+ if ( target[0] ) {
+ float radius;
+ float dist;
+
+ e2 = FindTargetEntity (target);
+ if (!e2) {
+ _printf ("WARNING: light at (%i %i %i) has missing target\n",
+ (int)dl->origin[0], (int)dl->origin[1], (int)dl->origin[2]);
+ } else {
+ GetVectorForKey (e2, "origin", dest);
+ VectorSubtract (dest, dl->origin, dl->normal);
+ dist = VectorNormalize (dl->normal, dl->normal);
+ radius = FloatForKey (e, "radius");
+ if ( !radius ) {
+ radius = 64;
+ }
+ if ( !dist ) {
+ dist = 64;
+ }
+ dl->radiusByDist = (radius + 16) / dist;
+ dl->type = LIGHT_POINTSPOT;
+ }
+ }
+ vsounds[numvsounds++] = dl;
+ c_entityLights++;
+ }
+ _printf("%7i entity lights\n", c_entityLights);
+}
+
+/*
+==================
+VS_SubdivideAreaLight
+==================
+*/
+void VS_SubdivideAreaLight( shaderInfo_t *ls, winding_t *w, vec3_t normal,
+ float areaSubdivide, qboolean backsplash ) {
+ float area, value, intensity;
+ vsound_t *dl, *dl2;
+ vec3_t mins, maxs;
+ int axis;
+ winding_t *front, *back;
+ vec3_t planeNormal;
+ float planeDist;
+
+ if ( !w ) {
+ return;
+ }
+
+ WindingBounds( w, mins, maxs );
+
+ // check for subdivision
+ for ( axis = 0 ; axis < 3 ; axis++ ) {
+ if ( maxs[axis] - mins[axis] > areaSubdivide ) {
+ VectorClear( planeNormal );
+ planeNormal[axis] = 1;
+ planeDist = ( maxs[axis] + mins[axis] ) * 0.5;
+ ClipWindingEpsilon ( w, planeNormal, planeDist, ON_EPSILON, &front, &back );
+ VS_SubdivideAreaLight( ls, front, normal, areaSubdivide, qfalse );
+ VS_SubdivideAreaLight( ls, back, normal, areaSubdivide, qfalse );
+ FreeWinding( w );
+ return;
+ }
+ }
+
+ // create a light from this
+ area = WindingArea (w);
+ if ( area <= 0 || area > 20000000 ) {
+ return;
+ }
+
+ dl = malloc(sizeof(*dl));
+ memset (dl, 0, sizeof(*dl));
+ dl->type = LIGHT_POINTFAKESURFACE;
+
+ WindingCenter( w, dl->origin );
+ memcpy(dl->w.points, w->points, sizeof(vec3_t) * w->numpoints);
+ dl->w.numpoints = w->numpoints;
+ VectorCopy ( normal, dl->normal);
+ VectorCopy ( normal, dl->plane);
+ dl->plane[3] = DotProduct( dl->origin, normal );
+
+ value = ls->value;
+ intensity = value * area * lightAreaScale;
+ VectorAdd( dl->origin, dl->normal, dl->origin );
+
+ VectorCopy( ls->color, dl->color );
+
+ dl->photons = intensity;
+
+ // emitColor is irrespective of the area
+ VectorScale( ls->color, value*lightFormFactorValueScale*lightAreaScale, dl->emitColor );
+ //
+ VectorCopy(dl->emitColor, dl->color);
+
+ dl->si = ls;
+
+ if ( ls->contents & CONTENTS_FOG ) {
+ dl->twosided = qtrue;
+ }
+
+ vsounds[numvsounds++] = dl;
+
+ // optionally create a point backsplash light
+ if ( backsplash && ls->backsplashFraction > 0 ) {
+
+ dl2 = malloc(sizeof(*dl));
+ memset (dl2, 0, sizeof(*dl2));
+ dl2->type = LIGHT_POINTRADIAL;
+
+ VectorMA( dl->origin, ls->backsplashDistance, normal, dl2->origin );
+
+ VectorCopy( ls->color, dl2->color );
+
+ dl2->photons = dl->photons * ls->backsplashFraction;
+ dl2->si = ls;
+
+ vsounds[numvsounds++] = dl2;
+ }
+}
+
+/*
+==================
+VS_CreateFakeSurfaceLights
+==================
+*/
+void VS_CreateFakeSurfaceLights( void ) {
+ int i, j, side;
+ dsurface_t *ds;
+ shaderInfo_t *ls;
+ winding_t *w;
+ lFacet_t *f;
+ vsound_t *dl;
+ vec3_t origin;
+ drawVert_t *dv;
+ int c_surfaceLights;
+ float lightSubdivide;
+ vec3_t normal;
+
+
+ c_surfaceLights = 0;
+ _printf ("Creating surface lights...\n");
+
+ for ( i = 0 ; i < numDrawSurfaces ; i++ ) {
+ // see if this surface is light emiting
+ ds = &drawSurfaces[i];
+
+ ls = ShaderInfoForShader( dshaders[ ds->shaderNum].shader );
+ if ( ls->value == 0 ) {
+ continue;
+ }
+
+ // determine how much we need to chop up the surface
+ if ( ls->lightSubdivide ) {
+ lightSubdivide = ls->lightSubdivide;
+ } else {
+ lightSubdivide = lightDefaultSubdivide;
+ }
+
+ c_surfaceLights++;
+
+ // an autosprite shader will become
+ // a point light instead of an area light
+ if ( ls->autosprite ) {
+ // autosprite geometry should only have four vertexes
+ if ( lsurfaceTest[i] ) {
+ // curve or misc_model
+ f = lsurfaceTest[i]->facets;
+ if ( lsurfaceTest[i]->numFacets != 1 || f->numpoints != 4 ) {
+ _printf( "WARNING: surface at (%i %i %i) has autosprite shader but isn't a quad\n",
+ (int)f->points[0], (int)f->points[1], (int)f->points[2] );
+ }
+ VectorAdd( f->points[0], f->points[1], origin );
+ VectorAdd( f->points[2], origin, origin );
+ VectorAdd( f->points[3], origin, origin );
+ VectorScale( origin, 0.25, origin );
+ } else {
+ // normal polygon
+ dv = &drawVerts[ ds->firstVert ];
+ if ( ds->numVerts != 4 ) {
+ _printf( "WARNING: surface at (%i %i %i) has autosprite shader but %i verts\n",
+ (int)dv->xyz[0], (int)dv->xyz[1], (int)dv->xyz[2] );
+ continue;
+ }
+
+ VectorAdd( dv[0].xyz, dv[1].xyz, origin );
+ VectorAdd( dv[2].xyz, origin, origin );
+ VectorAdd( dv[3].xyz, origin, origin );
+ VectorScale( origin, 0.25, origin );
+ }
+
+ dl = malloc(sizeof(*dl));
+ memset (dl, 0, sizeof(*dl));
+ VectorCopy( origin, dl->origin );
+ VectorCopy( ls->color, dl->color );
+ dl->photons = ls->value * lightPointScale;
+ dl->type = LIGHT_POINTRADIAL;
+ vsounds[numvsounds++] = dl;
+ continue;
+ }
+
+ // possibly create for both sides of the polygon
+ for ( side = 0 ; side <= ls->twoSided ; side++ ) {
+ // create area lights
+ if ( lsurfaceTest[i] ) {
+ // curve or misc_model
+ for ( j = 0 ; j < lsurfaceTest[i]->numFacets ; j++ ) {
+ f = lsurfaceTest[i]->facets + j;
+ w = AllocWinding( f->numpoints );
+ w->numpoints = f->numpoints;
+ memcpy( w->points, f->points, f->numpoints * 12 );
+
+ VectorCopy( f->plane.normal, normal );
+ if ( side ) {
+ winding_t *t;
+
+ t = w;
+ w = ReverseWinding( t );
+ FreeWinding( t );
+ VectorSubtract( vec3_origin, normal, normal );
+ }
+ VS_SubdivideAreaLight( ls, w, normal, lightSubdivide, qtrue );
+ }
+ } else {
+ // normal polygon
+
+ w = AllocWinding( ds->numVerts );
+ w->numpoints = ds->numVerts;
+ for ( j = 0 ; j < ds->numVerts ; j++ ) {
+ VectorCopy( drawVerts[ds->firstVert+j].xyz, w->points[j] );
+ }
+ VectorCopy( ds->lightmapVecs[2], normal );
+ if ( side ) {
+ winding_t *t;
+
+ t = w;
+ w = ReverseWinding( t );
+ FreeWinding( t );
+ VectorSubtract( vec3_origin, normal, normal );
+ }
+ VS_SubdivideAreaLight( ls, w, normal, lightSubdivide, qtrue );
+ }
+ }
+ }
+
+ _printf( "%7i light emitting surfaces\n", c_surfaceLights );
+}
+
+
+/*
+==================
+VS_WindingForBrushSide
+==================
+*/
+winding_t *VS_WindingForBrushSide(dbrush_t *brush, int side, winding_t *w)
+{
+ int i, res;
+ winding_t *tmpw;
+ plane_t plane;
+
+ VectorCopy(dplanes[ dbrushsides[ brush->firstSide + side ].planeNum ].normal, plane.normal);
+ VectorInverse(plane.normal);
+ plane.dist = -dplanes[ dbrushsides[ brush->firstSide + side ].planeNum ].dist;
+ tmpw = BaseWindingForPlane( plane.normal, plane.dist );
+ memcpy(w->points, tmpw->points, sizeof(vec3_t) * tmpw->numpoints);
+ w->numpoints = tmpw->numpoints;
+
+ for (i = 0; i < brush->numSides; i++)
+ {
+ if (i == side)
+ continue;
+ VectorCopy(dplanes[ dbrushsides[ brush->firstSide + i ].planeNum ].normal, plane.normal);
+ VectorInverse(plane.normal);
+ plane.dist = -dplanes[ dbrushsides[ brush->firstSide + i ].planeNum ].dist;
+ res = VS_ChopWinding(w, &plane, 0.1);
+ if (res == SIDE_BACK)
+ return NULL;
+ }
+ return w;
+}
+
+/*
+==================
+VS_CreateSkyLights
+==================
+*/
+void VS_CreateSkyLights(void)
+{
+ int i, j, c_skyLights;
+ dbrush_t *b;
+ shaderInfo_t *si;
+ dbrushside_t *s;
+ vsound_t *dl;
+ vec3_t sunColor, sunDir = { 0.45, 0.3, 0.9 };
+ float d;
+
+ VectorNormalize(sunDir, sunDir);
+ VectorInverse(sunDir);
+
+ c_skyLights = 0;
+ _printf("Creating sky lights...\n");
+ // find the sky shader
+ for ( i = 0 ; i < numDrawSurfaces ; i++ ) {
+ si = ShaderInfoForShader( dshaders[ drawSurfaces[i].shaderNum ].shader );
+ if ( si->surfaceFlags & SURF_SKY ) {
+ VectorCopy( si->sunLight, sunColor );
+ VectorCopy( si->sunDirection, sunDir );
+ VectorInverse(sunDir);
+ break;
+ }
+ }
+
+ // find the brushes
+ for ( i = 0 ; i < numbrushes ; i++ ) {
+ b = &dbrushes[i];
+ for ( j = 0 ; j < b->numSides ; j++ ) {
+ s = &dbrushsides[ b->firstSide + j ];
+ if ( dshaders[ s->shaderNum ].surfaceFlags & SURF_SKY ) {
+ //if this surface doesn't face in the same direction as the sun
+ d = DotProduct(dplanes[ s->planeNum ].normal, sunDir);
+ if (d <= 0)
+ continue;
+ //
+ dl = malloc(sizeof(*dl));
+ memset (dl, 0, sizeof(*dl));
+ VectorCopy(sunColor, dl->color);
+ VectorCopy(sunDir, dl->normal);
+ VectorCopy(dplanes[ s->planeNum ].normal, dl->plane);
+ dl->plane[3] = dplanes[ s->planeNum ].dist;
+ dl->type = LIGHT_SURFACEDIRECTED;
+ dl->atten_disttype = LDAT_NOSCALE;
+ VS_WindingForBrushSide(b, j, &dl->w);
+// DebugNet_DrawWinding(&dl->w, 2);
+ //
+ vsounds[numvsounds++] = dl;
+ c_skyLights++;
+ }
+ }
+ }
+ _printf("%7i light emitting sky surfaces\n", c_skyLights);
+}
+
+/*
+==================
+VS_SetPortalSphere
+==================
+*/
+void VS_SetPortalSphere (lportal_t *p)
+{
+ int i;
+ vec3_t total, dist;
+ winding_t *w;
+ float r, bestr;
+
+ w = p->winding;
+ VectorCopy (vec3_origin, total);
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ VectorAdd (total, w->points[i], total);
+ }
+
+ for (i=0 ; i<3 ; i++)
+ total[i] /= w->numpoints;
+
+ bestr = 0;
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ VectorSubtract (w->points[i], total, dist);
+ r = VectorLength (dist);
+ if (r > bestr)
+ bestr = r;
+ }
+ VectorCopy (total, p->origin);
+ p->radius = bestr;
+}
+
+/*
+==================
+VS_PlaneFromWinding
+==================
+*/
+void VS_PlaneFromWinding (winding_t *w, plane_t *plane)
+{
+ vec3_t v1, v2;
+
+ //calc plane
+ VectorSubtract (w->points[2], w->points[1], v1);
+ VectorSubtract (w->points[0], w->points[1], v2);
+ CrossProduct (v2, v1, plane->normal);
+ VectorNormalize (plane->normal, plane->normal);
+ plane->dist = DotProduct (w->points[0], plane->normal);
+}
+
+/*
+==================
+VS_AllocWinding
+==================
+*/
+winding_t *VS_AllocWinding (int points)
+{
+ winding_t *w;
+ int size;
+
+ if (points > MAX_POINTS_ON_WINDING)
+ Error ("NewWinding: %i points", points);
+
+ size = (int)((winding_t *)0)->points[points];
+ w = malloc (size);
+ memset (w, 0, size);
+
+ return w;
+}
+
+/*
+============
+VS_LoadPortals
+============
+*/
+void VS_LoadPortals (char *name)
+{
+ int i, j, hint;
+ lportal_t *p;
+ lleaf_t *l;
+ char magic[80];
+ FILE *f;
+ int numpoints;
+ winding_t *w;
+ int leafnums[2];
+ plane_t plane;
+ //
+
+ if (!strcmp(name,"-"))
+ f = stdin;
+ else
+ {
+ f = fopen(name, "r");
+ if (!f)
+ Error ("LoadPortals: couldn't read %s\n",name);
+ }
+
+ if (fscanf (f,"%79s\n%i\n%i\n%i\n",magic, &portalclusters, &numportals, &numfaces) != 4)
+ Error ("LoadPortals: failed to read header");
+ if (strcmp(magic, PORTALFILE))
+ Error ("LoadPortals: not a portal file");
+
+ _printf ("%6i portalclusters\n", portalclusters);
+ _printf ("%6i numportals\n", numportals);
+ _printf ("%6i numfaces\n", numfaces);
+
+ if (portalclusters >= MAX_CLUSTERS)
+ Error ("more than %d clusters in portal file\n", MAX_CLUSTERS);
+
+ // each file portal is split into two memory portals
+ portals = malloc(2*numportals*sizeof(lportal_t));
+ memset (portals, 0, 2*numportals*sizeof(lportal_t));
+
+ leafs = malloc(portalclusters*sizeof(lleaf_t));
+ memset (leafs, 0, portalclusters*sizeof(lleaf_t));
+
+ for (i=0, p=portals ; i<numportals ; i++)
+ {
+ if (fscanf (f, "%i %i %i ", &numpoints, &leafnums[0], &leafnums[1]) != 3)
+ Error ("LoadPortals: reading portal %i", i);
+ if (numpoints > MAX_POINTS_ON_WINDING)
+ Error ("LoadPortals: portal %i has too many points", i);
+ if ( (unsigned)leafnums[0] > portalclusters
+ || (unsigned)leafnums[1] > portalclusters)
+ Error ("LoadPortals: reading portal %i", i);
+ if (fscanf (f, "%i ", &hint) != 1)
+ Error ("LoadPortals: reading hint state");
+
+ w = p->winding = VS_AllocWinding (numpoints);
+ w->numpoints = numpoints;
+
+ for (j=0 ; j<numpoints ; j++)
+ {
+ double v[3];
+ int k;
+
+ // scanf into double, then assign to vec_t
+ // so we don't care what size vec_t is
+ if (fscanf (f, "(%lf %lf %lf ) "
+ , &v[0], &v[1], &v[2]) != 3)
+ Error ("LoadPortals: reading portal %i", i);
+ for (k=0 ; k<3 ; k++)
+ w->points[j][k] = v[k];
+ }
+ fscanf (f, "\n");
+
+ // calc plane
+ VS_PlaneFromWinding (w, &plane);
+
+ // create forward portal
+ l = &leafs[leafnums[0]];
+ if (l->numportals == MAX_PORTALS_ON_LEAF)
+ Error ("Leaf with too many portals");
+ l->portals[l->numportals] = p;
+ l->numportals++;
+
+ p->winding = w;
+ VectorSubtract (vec3_origin, plane.normal, p->plane.normal);
+ p->plane.dist = -plane.dist;
+ p->leaf = leafnums[1];
+ VS_SetPortalSphere (p);
+ p++;
+
+ // create backwards portal
+ l = &leafs[leafnums[1]];
+ if (l->numportals == MAX_PORTALS_ON_LEAF)
+ Error ("Leaf with too many portals");
+ l->portals[l->numportals] = p;
+ l->numportals++;
+
+ p->winding = VS_AllocWinding(w->numpoints);
+ p->winding->numpoints = w->numpoints;
+ for (j=0 ; j<w->numpoints ; j++)
+ {
+ VectorCopy (w->points[w->numpoints-1-j], p->winding->points[j]);
+ }
+
+ p->plane = plane;
+ p->leaf = leafnums[0];
+ VS_SetPortalSphere (p);
+ p++;
+
+ }
+
+ fclose (f);
+}
+
+/*
+============
+VLightMain
+============
+*/
+int VSoundMain (int argc, char **argv) {
+ int i;
+ double start, end;
+ const char *value;
+
+ _printf ("----- VLighting ----\n");
+
+ for (i=1 ; i<argc ; i++) {
+ if (!strcmp(argv[i],"-v")) {
+ verbose = qtrue;
+ } else if (!strcmp(argv[i],"-threads")) {
+ numthreads = atoi (argv[i+1]);
+ _printf("num threads = %d\n", numthreads);
+ i++;
+ } else if (!strcmp(argv[i],"-area")) {
+ lightAreaScale *= atof(argv[i+1]);
+ _printf ("area light scaling at %f\n", lightAreaScale);
+ i++;
+ } else if (!strcmp(argv[i],"-point")) {
+ lightPointScale *= atof(argv[i+1]);
+ _printf ("point light scaling at %f\n", lightPointScale);
+ i++;
+ } else if (!strcmp(argv[i], "-samplesize")) {
+ samplesize = atoi(argv[i+1]);
+ if (samplesize < 1) samplesize = 1;
+ i++;
+ _printf("lightmap sample size is %dx%d units\n", samplesize, samplesize);
+ } else if (!strcmp(argv[i], "-nostitching")) {
+ nostitching = qtrue;
+ _printf("no stitching = true\n");
+ } else if (!strcmp(argv[i], "-noalphashading")) {
+ noalphashading = qtrue;
+ _printf("no alpha shading = true\n");
+ } else if (!strcmp(argv[i], "-nocolorshading")) {
+ nocolorshading = qtrue;
+ _printf("old style alpha shading = true\n");
+ } else if (!strcmp(argv[i], "-nobackfaceculling")) {
+ nobackfaceculling = qtrue;
+ _printf("no backface culling = true\n");
+ } else if (!strcmp(argv[i], "-tracelight")) {
+ defaulttracelight = qtrue;
+ _printf("default trace light = true\n");
+ } else if (!strcmp(argv[i], "-radiosity")) {
+ radiosity = atoi(argv[i+1]);
+ _printf("radiosity = %d\n", radiosity);
+ i++;
+ } else {
+ break;
+ }
+ }
+
+ ThreadSetDefault ();
+
+ if (i != argc - 1) {
+ _printf("usage: q3map -vsound [-<switch> [-<switch> ...]] <mapname>\n"
+ "\n"
+ "Switches:\n"
+ " v = verbose output\n"
+ " threads <X> = set number of threads to X\n"
+ " area <V> = set the area light scale to V\n"
+ " point <W> = set the point light scale to W\n"
+ " novertex = don't calculate vertex lighting\n"
+ " nogrid = don't calculate light grid for dynamic model lighting\n"
+ " nostitching = no polygon stitching before lighting\n"
+ " noalphashading = don't use alpha shading\n"
+ " nocolorshading = don't use color alpha shading\n"
+ " tracelight = use old light algorithm by default\n"
+ " samplesize <N> = set the lightmap pixel size to NxN units\n");
+ exit(0);
+ }
+
+ SetQdirFromPath (argv[i]);
+
+#ifdef _WIN32
+ InitPakFile(gamedir, NULL);
+#endif
+
+ strcpy (source, ExpandArg(argv[i]));
+ StripExtension (source);
+ DefaultExtension (source, ".bsp");
+
+ LoadShaderInfo();
+
+ _printf ("reading %s\n", source);
+
+ LoadBSPFile (source);
+ ParseEntities();
+
+ value = ValueForKey( &entities[0], "gridsize" );
+ if (strlen(value)) {
+ sscanf( value, "%f %f %f", &gridSize[0], &gridSize[1], &gridSize[2] );
+ _printf("grid size = {%1.1f, %1.1f, %1.1f}\n", gridSize[0], gridSize[1], gridSize[2]);
+ }
+
+ CountLightmaps();
+
+ StripExtension (source);
+ DefaultExtension (source, ".prt");
+
+ VS_LoadPortals(source);
+
+ // set surfaceOrigin
+ SetEntityOrigins();
+
+ // grid and vertex lighting
+ GridAndVertexLighting();
+
+#ifdef DEBUGNET
+ DebugNet_Setup();
+#endif
+
+ start = clock();
+
+ lightFloats = (float *) malloc(numLightBytes * sizeof(float));
+ memset(lightFloats, 0, numLightBytes * sizeof(float));
+
+ VS_InitSurfacesForTesting();
+
+ VS_CalcVisibleLightmapPixelArea();
+
+ numvsounds = 0;
+ VS_CreateEntitySpeakers();
+ VS_CreateFakeSurfaceLights();
+ VS_CreateSkyLights();
+
+ VS_TestLightLeafs();
+
+ VS_LightWorld();
+
+#ifndef LIGHTPOLYS
+ StripExtension (source);
+ DefaultExtension (source, ".bsp");
+ _printf ("writing %s\n", source);
+ WriteBSPFile (source);
+#endif
+
+ end = clock();
+
+ _printf ("%5.2f seconds elapsed\n", (end-start) / CLK_TCK);
+
+#ifdef LIGHTPOLYS
+ VS_DrawLightWindings();
+#endif
+
+#ifdef DEBUGNET
+ DebugNet_Shutdown();
+#endif
+ return 0;
+}
diff --git a/q3map/surface.c b/q3map/surface.c
new file mode 100755
index 0000000..462449d
--- /dev/null
+++ b/q3map/surface.c
@@ -0,0 +1,1158 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "qbsp.h"
+
+
+mapDrawSurface_t mapDrawSurfs[MAX_MAP_DRAW_SURFS];
+int numMapDrawSurfs;
+
+/*
+=============================================================================
+
+DRAWSURF CONSTRUCTION
+
+=============================================================================
+*/
+
+/*
+=================
+AllocDrawSurf
+=================
+*/
+mapDrawSurface_t *AllocDrawSurf( void ) {
+ mapDrawSurface_t *ds;
+
+ if ( numMapDrawSurfs >= MAX_MAP_DRAW_SURFS ) {
+ Error( "MAX_MAP_DRAW_SURFS");
+ }
+ ds = &mapDrawSurfs[ numMapDrawSurfs ];
+ numMapDrawSurfs++;
+
+ return ds;
+}
+
+/*
+=================
+DrawSurfaceForSide
+=================
+*/
+#define SNAP_FLOAT_TO_INT 8
+#define SNAP_INT_TO_FLOAT (1.0/SNAP_FLOAT_TO_INT)
+
+mapDrawSurface_t *DrawSurfaceForSide( bspbrush_t *b, side_t *s, winding_t *w ) {
+ mapDrawSurface_t *ds;
+ int i, j;
+ shaderInfo_t *si;
+ drawVert_t *dv;
+ float mins[2], maxs[2];
+
+ // brush primitive :
+ // axis base
+ vec3_t texX,texY;
+ vec_t x,y;
+
+ if ( w->numpoints > 64 ) {
+ Error( "DrawSurfaceForSide: w->numpoints = %i", w->numpoints );
+ }
+
+ si = s->shaderInfo;
+
+ ds = AllocDrawSurf();
+
+ ds->shaderInfo = si;
+ ds->mapBrush = b;
+ ds->side = s;
+ ds->fogNum = -1;
+ ds->numVerts = w->numpoints;
+ ds->verts = malloc( ds->numVerts * sizeof( *ds->verts ) );
+ memset( ds->verts, 0, ds->numVerts * sizeof( *ds->verts ) );
+
+ mins[0] = mins[1] = 99999;
+ maxs[0] = maxs[1] = -99999;
+
+ // compute s/t coordinates from brush primitive texture matrix
+ // compute axis base
+ ComputeAxisBase( mapplanes[s->planenum].normal, texX, texY );
+
+ for ( j = 0 ; j < w->numpoints ; j++ ) {
+ dv = ds->verts + j;
+
+ // round the xyz to a given precision
+ for ( i = 0 ; i < 3 ; i++ ) {
+ dv->xyz[i] = SNAP_INT_TO_FLOAT * floor( w->p[j][i] * SNAP_FLOAT_TO_INT + 0.5 );
+ }
+
+ if (g_bBrushPrimit==BPRIMIT_OLDBRUSHES)
+ {
+ // calculate texture s/t
+ dv->st[0] = s->vecs[0][3] + DotProduct( s->vecs[0], dv->xyz );
+ dv->st[1] = s->vecs[1][3] + DotProduct( s->vecs[1], dv->xyz );
+ dv->st[0] /= si->width;
+ dv->st[1] /= si->height;
+ }
+ else
+ {
+ // calculate texture s/t from brush primitive texture matrix
+ x = DotProduct( dv->xyz, texX );
+ y = DotProduct( dv->xyz, texY );
+ dv->st[0]=s->texMat[0][0]*x+s->texMat[0][1]*y+s->texMat[0][2];
+ dv->st[1]=s->texMat[1][0]*x+s->texMat[1][1]*y+s->texMat[1][2];
+ }
+
+ for ( i = 0 ; i < 2 ; i++ ) {
+ if ( dv->st[i] < mins[i] ) {
+ mins[i] = dv->st[i];
+ }
+ if ( dv->st[i] > maxs[i] ) {
+ maxs[i] = dv->st[i];
+ }
+ }
+
+ // copy normal
+ VectorCopy ( mapplanes[s->planenum].normal, dv->normal );
+ }
+
+ // adjust the texture coordinates to be as close to 0 as possible
+ if ( !si->globalTexture ) {
+ mins[0] = floor( mins[0] );
+ mins[1] = floor( mins[1] );
+ for ( i = 0 ; i < w->numpoints ; i++ ) {
+ dv = ds->verts + i;
+ dv->st[0] -= mins[0];
+ dv->st[1] -= mins[1];
+ }
+ }
+
+ return ds;
+}
+
+
+//=========================================================================
+
+
+
+
+typedef struct {
+ int planenum;
+ shaderInfo_t *shaderInfo;
+ int count;
+} sideRef_t;
+
+#define MAX_SIDE_REFS MAX_MAP_PLANES
+
+sideRef_t sideRefs[MAX_SIDE_REFS];
+int numSideRefs;
+
+void AddSideRef( side_t *side ) {
+ int i;
+
+ for ( i = 0 ; i < numSideRefs ; i++ ) {
+ if ( side->planenum == sideRefs[i].planenum
+ && side->shaderInfo == sideRefs[i].shaderInfo ) {
+ sideRefs[i].count++;
+ return;
+ }
+ }
+
+ if ( numSideRefs == MAX_SIDE_REFS ) {
+ Error( "MAX_SIDE_REFS" );
+ }
+
+ sideRefs[i].planenum = side->planenum;
+ sideRefs[i].shaderInfo = side->shaderInfo;
+ sideRefs[i].count++;
+ numSideRefs++;
+}
+
+
+/*
+=====================
+MergeSides
+
+=====================
+*/
+void MergeSides( entity_t *e, tree_t *tree ) {
+ int i;
+
+ qprintf( "----- MergeSides -----\n");
+
+ for ( i = e->firstDrawSurf ; i < numMapDrawSurfs ; i++ ) {
+// AddSideRef( side );
+ }
+
+ qprintf( "%5i siderefs\n", numSideRefs );
+}
+
+//=====================================================================
+
+/*
+===================
+SubdivideDrawSurf
+===================
+*/
+void SubdivideDrawSurf( mapDrawSurface_t *ds, winding_t *w, float subdivisions ) {
+ int i;
+ int axis;
+ vec3_t bounds[2];
+ const float epsilon = 0.1;
+ int subFloor, subCeil;
+ winding_t *frontWinding, *backWinding;
+ mapDrawSurface_t *newds;
+
+ if ( !w ) {
+ return;
+ }
+ if ( w->numpoints < 3 ) {
+ Error( "SubdivideDrawSurf: Bad w->numpoints" );
+ }
+
+ ClearBounds( bounds[0], bounds[1] );
+ for ( i = 0 ; i < w->numpoints ; i++ ) {
+ AddPointToBounds( w->p[i], bounds[0], bounds[1] );
+ }
+
+ for ( axis = 0 ; axis < 3 ; axis++ ) {
+ vec3_t planePoint = { 0, 0, 0 };
+ vec3_t planeNormal = { 0, 0, 0 };
+ float d;
+
+ subFloor = floor( bounds[0][axis] / subdivisions ) * subdivisions;
+ subCeil = ceil( bounds[1][axis] / subdivisions ) * subdivisions;
+
+ planePoint[axis] = subFloor + subdivisions;
+ planeNormal[axis] = -1;
+
+ d = DotProduct( planePoint, planeNormal );
+
+ // subdivide if necessary
+ if ( subCeil - subFloor > subdivisions ) {
+ // gotta clip polygon into two polygons
+ ClipWindingEpsilon( w, planeNormal, d, epsilon, &frontWinding, &backWinding );
+
+ // the clip may not produce two polygons if it was epsilon close
+ if ( !frontWinding ) {
+ w = backWinding;
+ } else if ( !backWinding ) {
+ w = frontWinding;
+ } else {
+ SubdivideDrawSurf( ds, frontWinding, subdivisions );
+ SubdivideDrawSurf( ds, backWinding, subdivisions );
+
+ return;
+ }
+ }
+ }
+
+ // emit this polygon
+ newds = DrawSurfaceForSide( ds->mapBrush, ds->side, w );
+ newds->fogNum = ds->fogNum;
+}
+
+
+/*
+=====================
+SubdivideDrawSurfs
+
+Chop up surfaces that have subdivision attributes
+=====================
+*/
+void SubdivideDrawSurfs( entity_t *e, tree_t *tree ) {
+ int i;
+ mapDrawSurface_t *ds;
+ int numBaseDrawSurfs;
+ winding_t *w;
+ float subdivision;
+ shaderInfo_t *si;
+
+ qprintf( "----- SubdivideDrawSurfs -----\n");
+ numBaseDrawSurfs = numMapDrawSurfs;
+ for ( i = e->firstDrawSurf ; i < numBaseDrawSurfs ; i++ ) {
+ ds = &mapDrawSurfs[i];
+
+ // only subdivide brush sides, not patches or misc_models
+ if ( !ds->side ) {
+ continue;
+ }
+
+ // check subdivision for shader
+ si = ds->side->shaderInfo;
+ if ( !si ) {
+ continue;
+ }
+
+ if (ds->shaderInfo->autosprite || si->autosprite) {
+ continue;
+ }
+
+ subdivision = si->subdivisions;
+ if ( !subdivision ) {
+ continue;
+ }
+
+ w = WindingFromDrawSurf( ds );
+ ds->numVerts = 0; // remove this reference
+ SubdivideDrawSurf( ds, w, subdivision );
+ }
+
+}
+
+
+//===================================================================================
+
+/*
+====================
+ClipSideIntoTree_r
+
+Adds non-opaque leaf fragments to the convex hull
+====================
+*/
+void ClipSideIntoTree_r( winding_t *w, side_t *side, node_t *node ) {
+ plane_t *plane;
+ winding_t *front, *back;
+
+ if ( !w ) {
+ return;
+ }
+
+ if ( node->planenum != PLANENUM_LEAF ) {
+ if ( side->planenum == node->planenum ) {
+ ClipSideIntoTree_r( w, side, node->children[0] );
+ return;
+ }
+ if ( side->planenum == ( node->planenum ^ 1) ) {
+ ClipSideIntoTree_r( w, side, node->children[1] );
+ return;
+ }
+
+ plane = &mapplanes[ node->planenum ];
+ ClipWindingEpsilon ( w, plane->normal, plane->dist,
+ ON_EPSILON, &front, &back );
+ FreeWinding( w );
+
+ ClipSideIntoTree_r( front, side, node->children[0] );
+ ClipSideIntoTree_r( back, side, node->children[1] );
+
+ return;
+ }
+
+ // if opaque leaf, don't add
+ if ( !node->opaque ) {
+ AddWindingToConvexHull( w, &side->visibleHull, mapplanes[ side->planenum ].normal );
+ }
+
+ FreeWinding( w );
+ return;
+}
+
+
+/*
+=====================
+ClipSidesIntoTree
+
+Creates side->visibleHull for all visible sides
+
+The drawsurf for a side will consist of the convex hull of
+all points in non-opaque clusters, which allows overlaps
+to be trimmed off automatically.
+=====================
+*/
+void ClipSidesIntoTree( entity_t *e, tree_t *tree ) {
+ bspbrush_t *b;
+ int i;
+ winding_t *w;
+ side_t *side, *newSide;
+ shaderInfo_t *si;
+
+ qprintf( "----- ClipSidesIntoTree -----\n");
+
+ for ( b = e->brushes ; b ; b = b->next ) {
+ for ( i = 0 ; i < b->numsides ; i++ ) {
+ side = &b->sides[i];
+ if ( !side->winding) {
+ continue;
+ }
+ w = CopyWinding( side->winding );
+ side->visibleHull = NULL;
+ ClipSideIntoTree_r( w, side, tree->headnode );
+
+ w = side->visibleHull;
+ if ( !w ) {
+ continue;
+ }
+ si = side->shaderInfo;
+ if ( !si ) {
+ continue;
+ }
+ // don't create faces for non-visible sides
+ if ( si->surfaceFlags & SURF_NODRAW ) {
+ continue;
+ }
+
+ // always use the original quad winding for auto sprites
+ if ( side->shaderInfo->autosprite ) {
+ w = side->winding;
+ }
+ //
+ if ( side->bevel ) {
+ Error( "monkey tried to create draw surface for brush bevel" );
+ }
+ // save this winding as a visible surface
+ DrawSurfaceForSide( b, side, w );
+
+ // make a back side for it if needed
+ if ( !(si->contents & CONTENTS_FOG) ) {
+ continue;
+ }
+
+ // duplicate the up-facing side
+ w = ReverseWinding( w );
+
+ newSide = malloc( sizeof( *side ) );
+ *newSide = *side;
+ newSide->visibleHull = w;
+ newSide->planenum ^= 1;
+
+ // save this winding as a visible surface
+ DrawSurfaceForSide( b, newSide, w );
+
+ }
+ }
+}
+
+/*
+===================================================================================
+
+ FILTER REFERENCES DOWN THE TREE
+
+===================================================================================
+*/
+
+/*
+====================
+FilterDrawSurfIntoTree
+
+Place a reference to the given drawsurf in every leaf it contacts
+We assume that the point mesh aproximation to the curve will get a
+reference into all the leafs we need.
+====================
+*/
+int FilterMapDrawSurfIntoTree( vec3_t point, mapDrawSurface_t *ds, node_t *node ) {
+ drawSurfRef_t *dsr;
+ float d;
+ plane_t *plane;
+ int c;
+
+ if ( node->planenum != PLANENUM_LEAF ) {
+ plane = &mapplanes[ node->planenum ];
+ d = DotProduct( point, plane->normal ) - plane->dist;
+ c = 0;
+ if ( d >= -ON_EPSILON ) {
+ c += FilterMapDrawSurfIntoTree( point, ds, node->children[0] );
+ }
+ if ( d <= ON_EPSILON ) {
+ c += FilterMapDrawSurfIntoTree( point, ds, node->children[1] );
+ }
+ return c;
+ }
+
+ // if opaque leaf, don't add
+ if ( node->opaque ) {
+ return 0;
+ }
+
+ // add the drawsurf if it hasn't been already
+ for ( dsr = node->drawSurfReferences ; dsr ; dsr = dsr->nextRef ) {
+ if ( dsr->outputNumber == numDrawSurfaces ) {
+ return 0; // already referenced
+ }
+ }
+
+ dsr = malloc( sizeof( *dsr ) );
+ dsr->outputNumber = numDrawSurfaces;
+ dsr->nextRef = node->drawSurfReferences;
+ node->drawSurfReferences = dsr;
+ return 1;
+}
+
+/*
+====================
+FilterDrawSurfIntoTree_r
+
+Place a reference to the given drawsurf in every leaf it is in
+====================
+*/
+int FilterMapDrawSurfIntoTree_r( winding_t *w, mapDrawSurface_t *ds, node_t *node ) {
+ drawSurfRef_t *dsr;
+ plane_t *plane;
+ int total;
+ winding_t *front, *back;
+
+ if ( node->planenum != PLANENUM_LEAF ) {
+ plane = &mapplanes[ node->planenum ];
+ ClipWindingEpsilon ( w, plane->normal, plane->dist,
+ ON_EPSILON, &front, &back );
+
+ total = 0;
+ if ( front ) {
+ total += FilterMapDrawSurfIntoTree_r( front, ds, node->children[0] );
+ }
+ if ( back ) {
+ total += FilterMapDrawSurfIntoTree_r( back, ds, node->children[1] );
+ }
+
+ FreeWinding( w );
+ return total;
+ }
+
+ // if opaque leaf, don't add
+ if ( node->opaque ) {
+ return 0;
+ }
+
+ // add the drawsurf if it hasn't been already
+ for ( dsr = node->drawSurfReferences ; dsr ; dsr = dsr->nextRef ) {
+ if ( dsr->outputNumber == numDrawSurfaces ) {
+ return 0; // already referenced
+ }
+ }
+
+ dsr = malloc( sizeof( *dsr ) );
+ dsr->outputNumber = numDrawSurfaces;
+ dsr->nextRef = node->drawSurfReferences;
+ node->drawSurfReferences = dsr;
+ return 1;
+}
+
+/*
+====================
+FilterSideIntoTree_r
+
+Place a reference to the given drawsurf in every leaf it contacts
+====================
+*/
+int FilterSideIntoTree_r( winding_t *w, side_t *side, mapDrawSurface_t *ds, node_t *node ) {
+ drawSurfRef_t *dsr;
+ plane_t *plane;
+ winding_t *front, *back;
+ int total;
+
+ if ( !w ) {
+ return 0;
+ }
+
+ if ( node->planenum != PLANENUM_LEAF ) {
+ if ( side->planenum == node->planenum ) {
+ return FilterSideIntoTree_r( w, side, ds, node->children[0] );
+ }
+ if ( side->planenum == ( node->planenum ^ 1) ) {
+ return FilterSideIntoTree_r( w, side, ds, node->children[1] );
+ }
+
+ plane = &mapplanes[ node->planenum ];
+ ClipWindingEpsilon ( w, plane->normal, plane->dist,
+ ON_EPSILON, &front, &back );
+
+ total = FilterSideIntoTree_r( front, side, ds, node->children[0] );
+ total += FilterSideIntoTree_r( back, side, ds, node->children[1] );
+
+ FreeWinding( w );
+ return total;
+ }
+
+ // if opaque leaf, don't add
+ if ( node->opaque ) {
+ return 0;
+ }
+
+ dsr = malloc( sizeof( *dsr ) );
+ dsr->outputNumber = numDrawSurfaces;
+ dsr->nextRef = node->drawSurfReferences;
+ node->drawSurfReferences = dsr;
+
+ FreeWinding( w );
+ return 1;
+}
+
+
+/*
+=====================
+FilterFaceIntoTree
+=====================
+*/
+int FilterFaceIntoTree( mapDrawSurface_t *ds, tree_t *tree ) {
+ int l;
+ winding_t *w;
+
+ w = WindingFromDrawSurf( ds );
+ l = FilterSideIntoTree_r( w, ds->side, ds, tree->headnode );
+
+ return l;
+}
+
+
+
+/*
+=====================
+FilterPatchSurfIntoTree
+=====================
+*/
+#define SUBDIVISION_LIMIT 8.0
+int FilterPatchSurfIntoTree( mapDrawSurface_t *ds, tree_t *tree ) {
+ int i, j;
+ int l;
+ mesh_t baseMesh, *subdividedMesh;
+ winding_t *w;
+
+ baseMesh.width = ds->patchWidth;
+ baseMesh.height = ds->patchHeight;
+ baseMesh.verts = ds->verts;
+ subdividedMesh = SubdivideMesh( baseMesh, SUBDIVISION_LIMIT, 32 );
+
+ l = 0;
+ for (i = 0; i < subdividedMesh->width-1; i++) {
+ for (j = 0; j < subdividedMesh->height-1; j++) {
+ w = AllocWinding(3);
+ VectorCopy(subdividedMesh->verts[j * subdividedMesh->width + i].xyz, w->p[0]);
+ VectorCopy(subdividedMesh->verts[j * subdividedMesh->width + i + 1].xyz, w->p[1]);
+ VectorCopy(subdividedMesh->verts[(j+1) * subdividedMesh->width + i].xyz, w->p[2]);
+ w->numpoints = 3;
+ l += FilterMapDrawSurfIntoTree_r( w, ds, tree->headnode );
+ w = AllocWinding(3);
+ VectorCopy(subdividedMesh->verts[j * subdividedMesh->width + i + 1].xyz, w->p[0]);
+ VectorCopy(subdividedMesh->verts[(j+1) * subdividedMesh->width + i + 1].xyz, w->p[1]);
+ VectorCopy(subdividedMesh->verts[(j+1) * subdividedMesh->width + i].xyz, w->p[2]);
+ w->numpoints = 3;
+ l += FilterMapDrawSurfIntoTree_r( w, ds, tree->headnode );
+ }
+ }
+
+ // also use the old point filtering into the tree
+ for ( i = 0 ; i < subdividedMesh->width * subdividedMesh->height ; i++ ) {
+ l += FilterMapDrawSurfIntoTree( subdividedMesh->verts[i].xyz, ds, tree->headnode );
+ }
+
+ free(subdividedMesh);
+
+ return l;
+}
+
+
+/*
+=====================
+FilterMiscModelSurfIntoTree
+=====================
+*/
+int FilterMiscModelSurfIntoTree( mapDrawSurface_t *ds, tree_t *tree ) {
+ int i;
+ int l;
+ winding_t *w;
+
+ l = 0;
+ for (i = 0; i < ds->numIndexes-2; i++) {
+ w = AllocWinding(3);
+ VectorCopy(ds->verts[ds->indexes[i]].xyz, w->p[0]);
+ VectorCopy(ds->verts[ds->indexes[i+1]].xyz, w->p[1]);
+ VectorCopy(ds->verts[ds->indexes[i+2]].xyz, w->p[2]);
+ w->numpoints = 3;
+ l += FilterMapDrawSurfIntoTree_r( w, ds, tree->headnode );
+ }
+
+ // also use the old point filtering into the tree
+ for ( i = 0 ; i < ds->numVerts ; i++ ) {
+ l += FilterMapDrawSurfIntoTree( ds->verts[i].xyz, ds, tree->headnode );
+ }
+
+ return l;
+}
+
+/*
+=====================
+FilterFlareSurfIntoTree
+=====================
+*/
+int FilterFlareSurfIntoTree( mapDrawSurface_t *ds, tree_t *tree ) {
+ return FilterMapDrawSurfIntoTree( ds->lightmapOrigin, ds, tree->headnode );
+}
+
+
+//======================================================================
+
+int c_stripSurfaces, c_fanSurfaces;
+
+/*
+==================
+IsTriangleDegenerate
+
+Returns qtrue if all three points are collinear or backwards
+===================
+*/
+#define COLINEAR_AREA 10
+static qboolean IsTriangleDegenerate( drawVert_t *points, int a, int b, int c ) {
+ vec3_t v1, v2, v3;
+ float d;
+
+ VectorSubtract( points[b].xyz, points[a].xyz, v1 );
+ VectorSubtract( points[c].xyz, points[a].xyz, v2 );
+ CrossProduct( v1, v2, v3 );
+ d = VectorLength( v3 );
+
+ // assume all very small or backwards triangles will cause problems
+ if ( d < COLINEAR_AREA ) {
+ return qtrue;
+ }
+
+ return qfalse;
+}
+
+/*
+===============
+SurfaceAsTriFan
+
+The surface can't be represented as a single tristrip without
+leaving a degenerate triangle (and therefore a crack), so add
+a point in the middle and create (points-1) triangles in fan order
+===============
+*/
+static void SurfaceAsTriFan( dsurface_t *ds ) {
+ int i;
+ int colorSum[4];
+ drawVert_t *mid, *v;
+
+ // create a new point in the center of the face
+ if ( numDrawVerts == MAX_MAP_DRAW_VERTS ) {
+ Error( "MAX_MAP_DRAW_VERTS" );
+ }
+ mid = &drawVerts[ numDrawVerts ];
+ numDrawVerts++;
+
+ colorSum[0] = colorSum[1] = colorSum[2] = colorSum[3] = 0;
+
+ v = drawVerts + ds->firstVert;
+ for (i = 0 ; i < ds->numVerts ; i++, v++ ) {
+ VectorAdd( mid->xyz, v->xyz, mid->xyz );
+ mid->st[0] += v->st[0];
+ mid->st[1] += v->st[1];
+ mid->lightmap[0] += v->lightmap[0];
+ mid->lightmap[1] += v->lightmap[1];
+
+ colorSum[0] += v->color[0];
+ colorSum[1] += v->color[1];
+ colorSum[2] += v->color[2];
+ colorSum[3] += v->color[3];
+ }
+
+ mid->xyz[0] /= ds->numVerts;
+ mid->xyz[1] /= ds->numVerts;
+ mid->xyz[2] /= ds->numVerts;
+
+ mid->st[0] /= ds->numVerts;
+ mid->st[1] /= ds->numVerts;
+
+ mid->lightmap[0] /= ds->numVerts;
+ mid->lightmap[1] /= ds->numVerts;
+
+ mid->color[0] = colorSum[0] / ds->numVerts;
+ mid->color[1] = colorSum[1] / ds->numVerts;
+ mid->color[2] = colorSum[2] / ds->numVerts;
+ mid->color[3] = colorSum[3] / ds->numVerts;
+
+ VectorCopy((drawVerts+ds->firstVert)->normal, mid->normal );
+
+ // fill in indices in trifan order
+ if ( numDrawIndexes + ds->numVerts*3 > MAX_MAP_DRAW_INDEXES ) {
+ Error( "MAX_MAP_DRAWINDEXES" );
+ }
+ ds->firstIndex = numDrawIndexes;
+ ds->numIndexes = ds->numVerts*3;
+
+ //FIXME
+ // should be: for ( i = 0 ; i < ds->numVerts ; i++ ) {
+ // set a break point and test this in a map
+ //for ( i = 0 ; i < ds->numVerts*3 ; i++ ) {
+ for ( i = 0 ; i < ds->numVerts ; i++ ) {
+ drawIndexes[numDrawIndexes++] = ds->numVerts;
+ drawIndexes[numDrawIndexes++] = i;
+ drawIndexes[numDrawIndexes++] = (i+1) % ds->numVerts;
+ }
+
+ ds->numVerts++;
+}
+
+
+/*
+================
+SurfaceAsTristrip
+
+Try to create indices that make (points-2) triangles in tristrip order
+================
+*/
+#define MAX_INDICES 1024
+static void SurfaceAsTristrip( dsurface_t *ds ) {
+ int i;
+ int rotate;
+ int numIndices;
+ int ni;
+ int a, b, c;
+ int indices[MAX_INDICES];
+
+ // determine the triangle strip order
+ numIndices = ( ds->numVerts - 2 ) * 3;
+ if ( numIndices > MAX_INDICES ) {
+ Error( "MAX_INDICES exceeded for surface" );
+ }
+
+ // try all possible orderings of the points looking
+ // for a strip order that isn't degenerate
+ for ( rotate = 0 ; rotate < ds->numVerts ; rotate++ ) {
+ for ( ni = 0, i = 0 ; i < ds->numVerts - 2 - i ; i++ ) {
+ a = ( ds->numVerts - 1 - i + rotate ) % ds->numVerts;
+ b = ( i + rotate ) % ds->numVerts;
+ c = ( ds->numVerts - 2 - i + rotate ) % ds->numVerts;
+
+ if ( IsTriangleDegenerate( drawVerts + ds->firstVert, a, b, c ) ) {
+ break;
+ }
+ indices[ni++] = a;
+ indices[ni++] = b;
+ indices[ni++] = c;
+
+ if ( i + 1 != ds->numVerts - 1 - i ) {
+ a = ( ds->numVerts - 2 - i + rotate ) % ds->numVerts;
+ b = ( i + rotate ) % ds->numVerts;
+ c = ( i + 1 + rotate ) % ds->numVerts;
+
+ if ( IsTriangleDegenerate( drawVerts + ds->firstVert, a, b, c ) ) {
+ break;
+ }
+ indices[ni++] = a;
+ indices[ni++] = b;
+ indices[ni++] = c;
+ }
+ }
+ if ( ni == numIndices ) {
+ break; // got it done without degenerate triangles
+ }
+ }
+
+ // if any triangle in the strip is degenerate,
+ // render from a centered fan point instead
+ if ( ni < numIndices ) {
+ c_fanSurfaces++;
+ SurfaceAsTriFan( ds );
+ return;
+ }
+
+ // a normal tristrip
+ c_stripSurfaces++;
+
+ if ( numDrawIndexes + ni > MAX_MAP_DRAW_INDEXES ) {
+ Error( "MAX_MAP_DRAW_INDEXES" );
+ }
+ ds->firstIndex = numDrawIndexes;
+ ds->numIndexes = ni;
+
+ memcpy( drawIndexes + numDrawIndexes, indices, ni * sizeof(int) );
+ numDrawIndexes += ni;
+}
+
+/*
+===============
+EmitPlanarSurf
+===============
+*/
+void EmitPlanarSurf( mapDrawSurface_t *ds ) {
+ int j;
+ dsurface_t *out;
+ drawVert_t *outv;
+
+ if ( numDrawSurfaces == MAX_MAP_DRAW_SURFS ) {
+ Error( "MAX_MAP_DRAW_SURFS" );
+ }
+ out = &drawSurfaces[ numDrawSurfaces ];
+ numDrawSurfaces++;
+
+ out->surfaceType = MST_PLANAR;
+ out->shaderNum = EmitShader( ds->shaderInfo->shader );
+ out->firstVert = numDrawVerts;
+ out->numVerts = ds->numVerts;
+ out->fogNum = ds->fogNum;
+ out->lightmapNum = ds->lightmapNum;
+ out->lightmapX = ds->lightmapX;
+ out->lightmapY = ds->lightmapY;
+ out->lightmapWidth = ds->lightmapWidth;
+ out->lightmapHeight = ds->lightmapHeight;
+
+ VectorCopy( ds->lightmapOrigin, out->lightmapOrigin );
+ VectorCopy( ds->lightmapVecs[0], out->lightmapVecs[0] );
+ VectorCopy( ds->lightmapVecs[1], out->lightmapVecs[1] );
+ VectorCopy( ds->lightmapVecs[2], out->lightmapVecs[2] );
+
+ for ( j = 0 ; j < ds->numVerts ; j++ ) {
+ if ( numDrawVerts == MAX_MAP_DRAW_VERTS ) {
+ Error( "MAX_MAP_DRAW_VERTS" );
+ }
+ outv = &drawVerts[ numDrawVerts ];
+ numDrawVerts++;
+ memcpy( outv, &ds->verts[ j ], sizeof( *outv ) );
+ outv->color[0] = 255;
+ outv->color[1] = 255;
+ outv->color[2] = 255;
+ outv->color[3] = 255;
+ }
+
+ // create the indexes
+ SurfaceAsTristrip( out );
+}
+
+
+/*
+===============
+EmitPatchSurf
+===============
+*/
+void EmitPatchSurf( mapDrawSurface_t *ds ) {
+ int j;
+ dsurface_t *out;
+ drawVert_t *outv;
+
+ if ( numDrawSurfaces == MAX_MAP_DRAW_SURFS ) {
+ Error( "MAX_MAP_DRAW_SURFS" );
+ }
+ out = &drawSurfaces[ numDrawSurfaces ];
+ numDrawSurfaces++;
+
+ out->surfaceType = MST_PATCH;
+ out->shaderNum = EmitShader( ds->shaderInfo->shader );
+ out->firstVert = numDrawVerts;
+ out->numVerts = ds->numVerts;
+ out->firstIndex = numDrawIndexes;
+ out->numIndexes = ds->numIndexes;
+ out->patchWidth = ds->patchWidth;
+ out->patchHeight = ds->patchHeight;
+ out->fogNum = ds->fogNum;
+ out->lightmapNum = ds->lightmapNum;
+ out->lightmapX = ds->lightmapX;
+ out->lightmapY = ds->lightmapY;
+ out->lightmapWidth = ds->lightmapWidth;
+ out->lightmapHeight = ds->lightmapHeight;
+
+ VectorCopy( ds->lightmapOrigin, out->lightmapOrigin );
+ VectorCopy( ds->lightmapVecs[0], out->lightmapVecs[0] );
+ VectorCopy( ds->lightmapVecs[1], out->lightmapVecs[1] );
+ VectorCopy( ds->lightmapVecs[2], out->lightmapVecs[2] );
+
+ for ( j = 0 ; j < ds->numVerts ; j++ ) {
+ if ( numDrawVerts == MAX_MAP_DRAW_VERTS ) {
+ Error( "MAX_MAP_DRAW_VERTS" );
+ }
+ outv = &drawVerts[ numDrawVerts ];
+ numDrawVerts++;
+ memcpy( outv, &ds->verts[ j ], sizeof( *outv ) );
+ outv->color[0] = 255;
+ outv->color[1] = 255;
+ outv->color[2] = 255;
+ outv->color[3] = 255;
+ }
+
+ for ( j = 0 ; j < ds->numIndexes ; j++ ) {
+ if ( numDrawIndexes == MAX_MAP_DRAW_INDEXES ) {
+ Error( "MAX_MAP_DRAW_INDEXES" );
+ }
+ drawIndexes[ numDrawIndexes ] = ds->indexes[ j ];
+ numDrawIndexes++;
+ }
+}
+
+/*
+===============
+EmitFlareSurf
+===============
+*/
+void EmitFlareSurf( mapDrawSurface_t *ds ) {
+ dsurface_t *out;
+
+ if ( numDrawSurfaces == MAX_MAP_DRAW_SURFS ) {
+ Error( "MAX_MAP_DRAW_SURFS" );
+ }
+ out = &drawSurfaces[ numDrawSurfaces ];
+ numDrawSurfaces++;
+
+ out->surfaceType = MST_FLARE;
+ out->shaderNum = EmitShader( ds->shaderInfo->shader );
+ out->fogNum = ds->fogNum;
+
+ VectorCopy( ds->lightmapOrigin, out->lightmapOrigin );
+ VectorCopy( ds->lightmapVecs[0], out->lightmapVecs[0] ); // color
+ VectorCopy( ds->lightmapVecs[2], out->lightmapVecs[2] );
+}
+
+
+/*
+===============
+EmitModelSurf
+===============
+*/
+void EmitModelSurf( mapDrawSurface_t *ds ) {
+ int j;
+ dsurface_t *out;
+ drawVert_t *outv;
+
+ if ( numDrawSurfaces == MAX_MAP_DRAW_SURFS ) {
+ Error( "MAX_MAP_DRAW_SURFS" );
+ }
+ out = &drawSurfaces[ numDrawSurfaces ];
+ numDrawSurfaces++;
+
+ out->surfaceType = MST_TRIANGLE_SOUP;
+ out->shaderNum = EmitShader( ds->shaderInfo->shader );
+ out->firstVert = numDrawVerts;
+ out->numVerts = ds->numVerts;
+ out->firstIndex = numDrawIndexes;
+ out->numIndexes = ds->numIndexes;
+ out->patchWidth = ds->patchWidth;
+ out->patchHeight = ds->patchHeight;
+ out->fogNum = ds->fogNum;
+ out->lightmapNum = ds->lightmapNum;
+ out->lightmapX = ds->lightmapX;
+ out->lightmapY = ds->lightmapY;
+ out->lightmapWidth = ds->lightmapWidth;
+ out->lightmapHeight = ds->lightmapHeight;
+
+ VectorCopy( ds->lightmapOrigin, out->lightmapOrigin );
+ VectorCopy( ds->lightmapVecs[0], out->lightmapVecs[0] );
+ VectorCopy( ds->lightmapVecs[1], out->lightmapVecs[1] );
+ VectorCopy( ds->lightmapVecs[2], out->lightmapVecs[2] );
+
+ for ( j = 0 ; j < ds->numVerts ; j++ ) {
+ if ( numDrawVerts == MAX_MAP_DRAW_VERTS ) {
+ Error( "MAX_MAP_DRAW_VERTS" );
+ }
+ outv = &drawVerts[ numDrawVerts ];
+ numDrawVerts++;
+ memcpy( outv, &ds->verts[ j ], sizeof( *outv ) );
+ outv->color[0] = 255;
+ outv->color[1] = 255;
+ outv->color[2] = 255;
+ }
+
+ for ( j = 0 ; j < ds->numIndexes ; j++ ) {
+ if ( numDrawIndexes == MAX_MAP_DRAW_INDEXES ) {
+ Error( "MAX_MAP_DRAW_INDEXES" );
+ }
+ drawIndexes[ numDrawIndexes ] = ds->indexes[ j ];
+ numDrawIndexes++;
+ }
+}
+
+//======================================================================
+
+/*
+==================
+CreateFlareSurface
+
+Light flares from surface lights become
+==================
+*/
+void CreateFlareSurface( mapDrawSurface_t *faceDs ) {
+ mapDrawSurface_t *ds;
+ int i;
+
+ ds = AllocDrawSurf();
+
+ if ( faceDs->shaderInfo->flareShader[0] ) {
+ ds->shaderInfo = ShaderInfoForShader( faceDs->shaderInfo->flareShader );
+ } else {
+ ds->shaderInfo = ShaderInfoForShader( "flareshader" );
+ }
+ ds->flareSurface = qtrue;
+ VectorCopy( faceDs->lightmapVecs[2], ds->lightmapVecs[2] );
+
+ // find midpoint
+ VectorClear( ds->lightmapOrigin );
+ for ( i = 0 ; i < faceDs->numVerts ; i++ ) {
+ VectorAdd( ds->lightmapOrigin, faceDs->verts[i].xyz, ds->lightmapOrigin );
+ }
+ VectorScale( ds->lightmapOrigin, 1.0/faceDs->numVerts, ds->lightmapOrigin );
+
+ VectorMA( ds->lightmapOrigin, 2, ds->lightmapVecs[2], ds->lightmapOrigin );
+
+ VectorCopy( faceDs->shaderInfo->color, ds->lightmapVecs[0] );
+
+ // FIXME: fog
+}
+
+/*
+=====================
+FilterDrawsurfsIntoTree
+
+Upon completion, all drawsurfs that actually generate a reference
+will have been emited to the bspfile arrays, and the references
+will have valid final indexes
+=====================
+*/
+void FilterDrawsurfsIntoTree( entity_t *e, tree_t *tree ) {
+ int i;
+ mapDrawSurface_t *ds;
+ int refs;
+ int c_surfs, c_refs;
+
+ qprintf( "----- FilterDrawsurfsIntoTree -----\n");
+
+ c_surfs = 0;
+ c_refs = 0;
+ for ( i = e->firstDrawSurf ; i < numMapDrawSurfs ; i++ ) {
+ ds = &mapDrawSurfs[i];
+
+ if ( !ds->numVerts && !ds->flareSurface ) {
+ continue;
+ }
+ if ( ds->miscModel ) {
+ refs = FilterMiscModelSurfIntoTree( ds, tree );
+ EmitModelSurf( ds );
+ } else if ( ds->patch ) {
+ refs = FilterPatchSurfIntoTree( ds, tree );
+ EmitPatchSurf( ds );
+ } else if ( ds->flareSurface ) {
+ refs = FilterFlareSurfIntoTree( ds, tree );
+ EmitFlareSurf( ds );
+ } else {
+ refs = FilterFaceIntoTree( ds, tree );
+// if ( ds->shaderInfo->value >= 1000 ) { // ds->shaderInfo->flareShader[0] ) {
+ if ( ds->shaderInfo->flareShader[0] ) {
+ CreateFlareSurface( ds );
+ }
+ EmitPlanarSurf( ds );
+ }
+ if ( refs > 0 ) {
+ c_surfs++;
+ c_refs += refs;
+ }
+ }
+ qprintf( "%5i emited drawsurfs\n", c_surfs );
+ qprintf( "%5i references\n", c_refs );
+ qprintf( "%5i stripfaces\n", c_stripSurfaces );
+ qprintf( "%5i fanfaces\n", c_fanSurfaces );
+}
+
+
+
diff --git a/q3map/terrain.c b/q3map/terrain.c
new file mode 100755
index 0000000..9446737
--- /dev/null
+++ b/q3map/terrain.c
@@ -0,0 +1,1255 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "qbsp.h"
+#include <assert.h>
+
+#define SURF_WIDTH 2048
+#define SURF_HEIGHT 2048
+
+#define GROW_VERTS 512
+#define GROW_INDICES 512
+#define GROW_SURFACES 128
+
+#define VectorSet(v, x, y, z) v[0] = x;v[1] = y;v[2] = z;
+
+void QuakeTextureVecs( plane_t *plane, vec_t shift[2], vec_t rotate, vec_t scale[2], vec_t mappingVecs[2][4] );
+
+typedef struct {
+ shaderInfo_t *shader;
+ int x, y;
+
+ int maxVerts;
+ int numVerts;
+ drawVert_t *verts;
+
+ int maxIndexes;
+ int numIndexes;
+ int *indexes;
+} terrainSurf_t;
+
+static terrainSurf_t *surfaces = NULL;
+static terrainSurf_t *lastSurface = NULL;
+static int numsurfaces = 0;
+static int maxsurfaces = 0;
+
+/*
+================
+ShaderForLayer
+================
+*/
+shaderInfo_t *ShaderForLayer( int minlayer, int maxlayer, const char *shadername ) {
+ char shader[ MAX_QPATH ];
+
+ if ( minlayer == maxlayer ) {
+ sprintf( shader, "textures/%s_%d", shadername, maxlayer );
+ } else {
+ sprintf( shader, "textures/%s_%dto%d", shadername, minlayer, maxlayer );
+ }
+
+ return ShaderInfoForShader( shader );
+}
+
+/*
+================
+CompareVert
+================
+*/
+qboolean CompareVert( drawVert_t *v1, drawVert_t *v2, qboolean checkst ) {
+ int i;
+
+ for( i = 0; i < 3; i++ ) {
+ if ( floor( v1->xyz[ i ] + 0.1 ) != floor( v2->xyz[ i ] + 0.1 ) ) {
+ return qfalse;
+ }
+ if ( checkst && ( ( v1->st[ 0 ] != v2->st[ 0 ] ) || ( v1->st[ 1 ] != v2->st[ 1 ] ) ) ) {
+ return qfalse;
+ }
+ }
+
+ return qtrue;
+}
+
+/*
+================
+LoadAlphaMap
+================
+*/
+byte *LoadAlphaMap( int *num_layers, int *alphawidth, int *alphaheight ) {
+ int *alphamap32;
+ byte *alphamap;
+ const char *alphamapname;
+ char ext[ 128 ];
+ int width;
+ int height;
+ int layers;
+ int size;
+ int i;
+
+ assert( alphawidth );
+ assert( alphaheight );
+ assert( num_layers );
+
+ layers = atoi( ValueForKey( mapent, "layers" ) );
+ if ( layers < 1 ) {
+ Error ("SetTerrainTextures: invalid value for 'layers' (%d)", layers );
+ }
+
+ alphamapname = ValueForKey( mapent, "alphamap" );
+ if ( !alphamapname[ 0 ] ) {
+ Error ("LoadAlphaMap: No alphamap specified on terrain" );
+ }
+
+ ExtractFileExtension( alphamapname, ext);
+ if ( !Q_stricmp( ext, "tga" ) ) {
+ Load32BitImage( ExpandGamePath( alphamapname ), &alphamap32, &width, &height );
+
+ size = width * height;
+ alphamap = malloc( size );
+ for( i = 0; i < size; i++ ) {
+ alphamap[ i ] = ( ( alphamap32[ i ] & 0xff ) * layers ) / 256;
+ if ( alphamap[ i ] >= layers ) {
+ alphamap[ i ] = layers - 1;
+ }
+ }
+ } else {
+ Load256Image( ExpandGamePath( alphamapname ), &alphamap, NULL, &width, &height );
+ size = width * height;
+ for( i = 0; i < size; i++ ) {
+ if ( alphamap[ i ] >= layers ) {
+ alphamap[ i ] = layers - 1;
+ }
+ }
+ }
+
+ if ( ( width < 2 ) || ( height < 2 ) ) {
+ Error ("LoadAlphaMap: alphamap width/height must be at least 2x2." );
+ }
+
+ *num_layers = layers;
+ *alphawidth = width;
+ *alphaheight = height;
+
+ return alphamap;
+}
+
+/*
+================
+CalcTerrainSize
+================
+*/
+void CalcTerrainSize( vec3_t mins, vec3_t maxs, vec3_t size ) {
+ bspbrush_t *brush;
+ int i;
+ const char *key;
+
+ // calculate the size of the terrain
+ ClearBounds( mins, maxs );
+ for( brush = mapent->brushes; brush != NULL; brush = brush->next ) {
+ AddPointToBounds( brush->mins, mins, maxs );
+ AddPointToBounds( brush->maxs, mins, maxs );
+ }
+
+ key = ValueForKey( mapent, "min" );
+ if ( key[ 0 ] ) {
+ GetVectorForKey( mapent, "min", mins );
+ }
+
+ key = ValueForKey( mapent, "max" );
+ if ( key[ 0 ] ) {
+ GetVectorForKey( mapent, "max", maxs );
+ }
+
+ for( i = 0; i < 3; i++ ) {
+ mins[ i ] = floor( mins[ i ] + 0.1 );
+ maxs[ i ] = floor( maxs[ i ] + 0.1 );
+ }
+
+ VectorSubtract( maxs, mins, size );
+
+ if ( ( size[ 0 ] <= 0 ) || ( size[ 1 ] <= 0 ) ) {
+ Error ("CalcTerrainSize: Invalid terrain size: %fx%f", size[ 0 ], size[ 1 ] );
+ }
+}
+
+/*
+==================
+IsTriangleDegenerate
+
+Returns qtrue if all three points are collinear or backwards
+===================
+*/
+#define COLINEAR_AREA 10
+static qboolean IsTriangleDegenerate( drawVert_t *points, int a, int b, int c ) {
+ vec3_t v1, v2, v3;
+ float d;
+
+ VectorSubtract( points[b].xyz, points[a].xyz, v1 );
+ VectorSubtract( points[c].xyz, points[a].xyz, v2 );
+ CrossProduct( v1, v2, v3 );
+ d = VectorLength( v3 );
+
+ // assume all very small or backwards triangles will cause problems
+ if ( d < COLINEAR_AREA ) {
+ return qtrue;
+ }
+
+ return qfalse;
+}
+
+/*
+===============
+SideAsTriFan
+
+The surface can't be represented as a single tristrip without
+leaving a degenerate triangle (and therefore a crack), so add
+a point in the middle and create (points-1) triangles in fan order
+===============
+*/
+static void SideAsTriFan( terrainSurf_t *surf, int *index, int num ) {
+ int i;
+ int colorSum[4];
+ drawVert_t *mid, *v;
+
+ // make sure we have enough space for a new vert
+ if ( surf->numVerts >= surf->maxVerts ) {
+ surf->maxVerts += GROW_VERTS;
+ surf->verts = realloc( surf->verts, surf->maxVerts * sizeof( *surf->verts ) );
+ }
+
+ // create a new point in the center of the face
+ mid = &surf->verts[ surf->numVerts ];
+ surf->numVerts++;
+
+ colorSum[0] = colorSum[1] = colorSum[2] = colorSum[3] = 0;
+
+ for (i = 0 ; i < num; i++ ) {
+ v = &surf->verts[ index[ i ] ];
+ VectorAdd( mid->xyz, v->xyz, mid->xyz );
+ mid->st[0] += v->st[0];
+ mid->st[1] += v->st[1];
+ mid->lightmap[0] += v->lightmap[0];
+ mid->lightmap[1] += v->lightmap[1];
+
+ colorSum[0] += v->color[0];
+ colorSum[1] += v->color[1];
+ colorSum[2] += v->color[2];
+ colorSum[3] += v->color[3];
+ }
+
+ mid->xyz[0] /= num;
+ mid->xyz[1] /= num;
+ mid->xyz[2] /= num;
+
+ mid->st[0] /= num;
+ mid->st[1] /= num;
+
+ mid->lightmap[0] /= num;
+ mid->lightmap[1] /= num;
+
+ mid->color[0] = colorSum[0] / num;
+ mid->color[1] = colorSum[1] / num;
+ mid->color[2] = colorSum[2] / num;
+ mid->color[3] = colorSum[3] / num;
+
+ // fill in indices in trifan order
+ if ( surf->numIndexes + num * 3 > surf->maxIndexes ) {
+ surf->maxIndexes = surf->numIndexes + num * 3;
+ surf->indexes = realloc( surf->indexes, surf->maxIndexes * sizeof( *surf->indexes ) );
+ }
+
+
+ for ( i = 0 ; i < num; i++ ) {
+ surf->indexes[ surf->numIndexes++ ] = surf->numVerts - 1;
+ surf->indexes[ surf->numIndexes++ ] = index[ i ];
+ surf->indexes[ surf->numIndexes++ ] = index[ (i+1) % ( surf->numVerts - 1 ) ];
+ }
+}
+/*
+================
+SideAsTristrip
+
+Try to create indices that make (points-2) triangles in tristrip order
+================
+*/
+#define MAX_INDICES 1024
+static void SideAsTristrip( terrainSurf_t *surf, int *index, int num ) {
+ int i;
+ int rotate;
+ int numIndices;
+ int ni;
+ int a, b, c;
+ int indices[ MAX_INDICES ];
+
+ // determine the triangle strip order
+ numIndices = ( num - 2 ) * 3;
+ if ( numIndices > MAX_INDICES ) {
+ Error( "MAX_INDICES exceeded for surface" );
+ }
+
+ // try all possible orderings of the points looking
+ // for a strip order that isn't degenerate
+ for ( rotate = 0 ; rotate < num; rotate++ ) {
+ for ( ni = 0, i = 0 ; i < num - 2 - i ; i++ ) {
+ a = index[ ( num - 1 - i + rotate ) % num ];
+ b = index[ ( i + rotate ) % num ];
+ c = index[ ( num - 2 - i + rotate ) % num ];
+
+ if ( IsTriangleDegenerate( surf->verts, a, b, c ) ) {
+ break;
+ }
+ indices[ni++] = a;
+ indices[ni++] = b;
+ indices[ni++] = c;
+
+ if ( i + 1 != num - 1 - i ) {
+ a = index[ ( num - 2 - i + rotate ) % num ];
+ b = index[ ( i + rotate ) % num ];
+ c = index[ ( i + 1 + rotate ) % num ];
+
+ if ( IsTriangleDegenerate( surf->verts, a, b, c ) ) {
+ break;
+ }
+ indices[ni++] = a;
+ indices[ni++] = b;
+ indices[ni++] = c;
+ }
+ }
+ if ( ni == numIndices ) {
+ break; // got it done without degenerate triangles
+ }
+ }
+
+ // if any triangle in the strip is degenerate,
+ // render from a centered fan point instead
+ if ( ni < numIndices ) {
+ SideAsTriFan( surf, index, num );
+ return;
+ }
+
+ // a normal tristrip
+ if ( surf->numIndexes + ni > surf->maxIndexes ) {
+ surf->maxIndexes = surf->numIndexes + ni;
+ surf->indexes = realloc( surf->indexes, surf->maxIndexes * sizeof( *surf->indexes ) );
+ }
+
+ memcpy( surf->indexes + surf->numIndexes, indices, ni * sizeof( *surf->indexes ) );
+ surf->numIndexes += ni;
+}
+
+/*
+================
+CreateTerrainSurface
+================
+*/
+void CreateTerrainSurface( terrainSurf_t *surf, shaderInfo_t *shader ) {
+ int i, j, k;
+ drawVert_t *out;
+ drawVert_t *in;
+ mapDrawSurface_t *newsurf;
+
+ newsurf = AllocDrawSurf();
+
+ newsurf->miscModel = qtrue;
+ newsurf->shaderInfo = shader;
+ newsurf->lightmapNum = -1;
+ newsurf->fogNum = -1;
+ newsurf->numIndexes = surf->numIndexes;
+ newsurf->numVerts = surf->numVerts;
+
+ // copy the indices
+ newsurf->indexes = malloc( surf->numIndexes * sizeof( *newsurf->indexes ) );
+ memcpy( newsurf->indexes, surf->indexes, surf->numIndexes * sizeof( *newsurf->indexes ) );
+
+ // allocate the vertices
+ newsurf->verts = malloc( surf->numVerts * sizeof( *newsurf->verts ) );
+ memset( newsurf->verts, 0, surf->numVerts * sizeof( *newsurf->verts ) );
+
+ // calculate the surface verts
+ out = newsurf->verts;
+ for( i = 0; i < newsurf->numVerts; i++, out++ ) {
+ VectorCopy( surf->verts[ i ].xyz, out->xyz );
+
+ // set the texture coordinates
+ out->st[ 0 ] = surf->verts[ i ].st[ 0 ];
+ out->st[ 1 ] = surf->verts[ i ].st[ 1 ];
+
+ // the colors will be set by the lighting pass
+ out->color[0] = 255;
+ out->color[1] = 255;
+ out->color[2] = 255;
+ out->color[3] = surf->verts[ i ].color[ 3 ];
+
+ // calculate the vertex normal
+ VectorClear( out->normal );
+ for( j = 0; j < numsurfaces; j++ ) {
+ in = surfaces[ j ].verts;
+ for( k = 0; k < surfaces[ j ].numVerts; k++, in++ ) {
+ if ( CompareVert( out, in, qfalse ) ) {
+ VectorAdd( out->normal, in->normal, out->normal );
+ }
+ }
+ }
+
+ VectorNormalize( out->normal, out->normal );
+ }
+}
+
+/*
+================
+EmitTerrainVerts
+================
+*/
+void EmitTerrainVerts( side_t *side, terrainSurf_t *surf, int maxlayer, int alpha[ MAX_POINTS_ON_WINDING ], qboolean projecttexture ) {
+ int i;
+ int j;
+ drawVert_t *vert;
+ int *indices;
+ int numindices;
+ int maxindices;
+ int xyplane;
+ vec3_t xynorm = { 0, 0, 1 };
+ vec_t shift[ 2 ] = { 0, 0 };
+ vec_t scale[ 2 ] = { 0.5, 0.5 };
+ float vecs[ 2 ][ 4 ];
+ static int numtimes = 0;
+
+ numtimes++;
+
+ if ( !surf->verts ) {
+ surf->numVerts = 0;
+ surf->maxVerts = GROW_VERTS;
+ surf->verts = malloc( surf->maxVerts * sizeof( *surf->verts ) );
+
+ surf->numIndexes = 0;
+ surf->maxIndexes = GROW_INDICES;
+ surf->indexes = malloc( surf->maxIndexes * sizeof( *surf->indexes ) );
+ }
+
+ // calculate the texture coordinate vectors
+ xyplane = FindFloatPlane( xynorm, 0 );
+ QuakeTextureVecs( &mapplanes[ xyplane ], shift, 0, scale, vecs );
+
+ // emit the vertexes
+ numindices = 0;
+ maxindices = surf->maxIndexes;
+ indices = malloc ( maxindices * sizeof( *indices ) );
+
+ for ( i = 0; i < side->winding->numpoints; i++ ) {
+ vert = &surf->verts[ surf->numVerts ];
+
+ // set the final alpha value--0 for texture 1, 255 for texture 2
+ if ( alpha[ i ] < maxlayer ) {
+ vert->color[3] = 0;
+ } else {
+ vert->color[3] = 255;
+ }
+
+ vert->xyz[ 0 ] = floor( side->winding->p[ i ][ 0 ] + 0.1f );
+ vert->xyz[ 1 ] = floor( side->winding->p[ i ][ 1 ] + 0.1f );
+ vert->xyz[ 2 ] = floor( side->winding->p[ i ][ 2 ] + 0.1f );
+
+ // set the texture coordinates
+ if ( projecttexture ) {
+ vert->st[0] = ( vecs[0][3] + DotProduct( vecs[ 0 ], vert->xyz ) ) / surf->shader->width;
+ vert->st[1] = ( vecs[1][3] + DotProduct( vecs[ 1 ], vert->xyz ) ) / surf->shader->height;
+ } else {
+ vert->st[0] = ( side->vecs[0][3] + DotProduct( side->vecs[ 0 ], vert->xyz ) ) / surf->shader->width;
+ vert->st[1] = ( side->vecs[1][3] + DotProduct( side->vecs[ 1 ], vert->xyz ) ) / surf->shader->height;
+ }
+
+ VectorCopy( mapplanes[ side->planenum ].normal, vert->normal );
+
+ for( j = 0; j < surf->numVerts; j++ ) {
+ if ( CompareVert( vert, &surf->verts[ j ], qtrue ) ) {
+ break;
+ }
+ }
+
+ if ( numindices >= maxindices ) {
+ maxindices += GROW_INDICES;
+ indices = realloc( indices, maxindices * sizeof( *indices ) );
+ }
+
+ if ( j != surf->numVerts ) {
+ indices[ numindices++ ] = j;
+ } else {
+ indices[ numindices++ ] = surf->numVerts;
+ surf->numVerts++;
+ if ( surf->numVerts >= surf->maxVerts ) {
+ surf->maxVerts += GROW_VERTS;
+ surf->verts = realloc( surf->verts, surf->maxVerts * sizeof( *surf->verts ) );
+ }
+ }
+ }
+
+ SideAsTristrip( surf, indices, numindices );
+
+ free( indices );
+}
+
+/*
+================
+SurfaceForShader
+================
+*/
+terrainSurf_t *SurfaceForShader( shaderInfo_t *shader, int x, int y ) {
+ int i;
+
+ if ( lastSurface && ( lastSurface->shader == shader ) && ( lastSurface->x == x ) && ( lastSurface->y == y ) ) {
+ return lastSurface;
+ }
+
+ lastSurface = surfaces;
+ for( i = 0; i < numsurfaces; i++, lastSurface++ ) {
+ if ( ( lastSurface->shader == shader ) && ( lastSurface->x == x ) && ( lastSurface->y == y ) ) {
+ return lastSurface;
+ }
+ }
+
+ if ( numsurfaces >= maxsurfaces ) {
+ maxsurfaces += GROW_SURFACES;
+ surfaces = realloc( surfaces, maxsurfaces * sizeof( *surfaces ) );
+ memset( surfaces + numsurfaces + 1, 0, ( maxsurfaces - numsurfaces - 1 ) * sizeof( *surfaces ) );
+ }
+
+ lastSurface= &surfaces[ numsurfaces++ ];
+ lastSurface->shader = shader;
+ lastSurface->x = x;
+ lastSurface->y = y;
+
+ return lastSurface;
+}
+
+/*
+================
+SetTerrainTextures
+================
+*/
+void SetTerrainTextures( void ) {
+ int i;
+ int x, y;
+ int layer;
+ int minlayer, maxlayer;
+ float s, t;
+ float min_s, min_t;
+ int alpha[ MAX_POINTS_ON_WINDING ];
+ shaderInfo_t *si, *terrainShader;
+ bspbrush_t *brush;
+ side_t *side;
+ const char *shadername;
+ vec3_t mins, maxs;
+ vec3_t size;
+ int surfwidth, surfheight, surfsize;
+ terrainSurf_t *surf;
+ byte *alphamap;
+ int alphawidth, alphaheight;
+ int num_layers;
+ extern qboolean onlyents;
+
+ if ( onlyents ) {
+ return;
+ }
+
+ shadername = ValueForKey( mapent, "shader" );
+ if ( !shadername[ 0 ] ) {
+ Error ("SetTerrainTextures: shader not specified" );
+ }
+
+ alphamap = LoadAlphaMap( &num_layers, &alphawidth, &alphaheight );
+
+ mapent->firstDrawSurf = numMapDrawSurfs;
+
+ // calculate the size of the terrain
+ CalcTerrainSize( mins, maxs, size );
+
+ surfwidth = ( size[ 0 ] + SURF_WIDTH - 1 ) / SURF_WIDTH;
+ surfheight = ( size[ 1 ] + SURF_HEIGHT - 1 ) / SURF_HEIGHT;
+ surfsize = surfwidth * surfheight;
+
+ lastSurface = NULL;
+ numsurfaces = 0;
+ maxsurfaces = 0;
+ for( i = num_layers; i > 0; i-- ) {
+ maxsurfaces += i * surfsize;
+ }
+ surfaces = malloc( maxsurfaces * sizeof( *surfaces ) );
+ memset( surfaces, 0, maxsurfaces * sizeof( *surfaces ) );
+
+ terrainShader = ShaderInfoForShader( "textures/common/terrain" );
+
+ for( brush = mapent->brushes; brush != NULL; brush = brush->next ) {
+ // only create surfaces for sides marked as terrain
+ for( side = brush->sides; side < &brush->sides[ brush->numsides ]; side++ ) {
+ if ( !side->shaderInfo ) {
+ continue;
+ }
+
+ if ( ( ( side->surfaceFlags | side->shaderInfo->surfaceFlags ) & SURF_NODRAW ) && !strstr( side->shaderInfo->shader, "terrain" ) ) {
+ continue;
+ }
+
+ minlayer = num_layers;
+ maxlayer = 0;
+
+ // project each point of the winding onto the alphamap to determine which
+ // textures to blend
+ min_s = 1.0;
+ min_t = 1.0;
+ for( i = 0; i < side->winding->numpoints; i++ ) {
+ s = floor( side->winding->p[ i ][ 0 ] + 0.1f - mins[ 0 ] ) / size[ 0 ];
+ t = floor( side->winding->p[ i ][ 1 ] + 0.1f - mins[ 0 ] ) / size[ 1 ];
+
+ if ( s < 0 ) {
+ s = 0;
+ }
+
+ if ( t < 0 ) {
+ t = 0;
+ }
+
+ if ( s >= 1.0 ) {
+ s = 1.0;
+ }
+
+ if ( t >= 1.0 ) {
+ t = 1.0;
+ }
+
+ if ( s < min_s ) {
+ min_s = s;
+ }
+
+ if ( t < min_t ) {
+ min_t = t;
+ }
+
+ x = ( alphawidth - 1 ) * s;
+ y = ( alphaheight - 1 ) * t;
+
+ layer = alphamap[ x + y * alphawidth ];
+ if ( layer < minlayer ) {
+ minlayer = layer;
+ }
+
+ if ( layer > maxlayer ) {
+ maxlayer = layer;
+ }
+
+ alpha[ i ] = layer;
+ }
+
+ x = min_s * surfwidth;
+ if ( x >= surfwidth ) {
+ x = surfwidth - 1;
+ }
+
+ y = min_t * surfheight;
+ if ( y >= surfheight ) {
+ y = surfheight - 1;
+ }
+
+ if ( strstr( side->shaderInfo->shader, "terrain" ) ) {
+ si = ShaderForLayer( minlayer, maxlayer, shadername );
+ if ( showseams ) {
+ for( i = 0; i < side->winding->numpoints; i++ ) {
+ if ( ( alpha[ i ] != minlayer ) && ( alpha[ i ] != maxlayer ) ) {
+ si = ShaderInfoForShader( "textures/common/white" );
+ break;
+ }
+ }
+ }
+ surf = SurfaceForShader( si, x, y );
+ EmitTerrainVerts( side, surf, maxlayer, alpha, qtrue );
+ } else {
+ si = side->shaderInfo;
+ side->shaderInfo = terrainShader;
+ surf = SurfaceForShader( si, x, y );
+ EmitTerrainVerts( side, surf, maxlayer, alpha, qfalse );
+ }
+ }
+ }
+
+ // create the final surfaces
+ for( surf = surfaces, i = 0; i < numsurfaces; i++, surf++ ) {
+ if ( surf->numVerts ) {
+ CreateTerrainSurface( surf, surf->shader );
+ }
+ }
+
+ //
+ // clean up any allocated memory
+ //
+ for( surf = surfaces, i = 0; i < numsurfaces; i++, surf++ ) {
+ if ( surf->verts ) {
+ free( surf->verts );
+ free( surf->indexes );
+ }
+ }
+ free( alphamap );
+ free( surfaces );
+
+ surfaces = NULL;
+ lastSurface = NULL;
+ numsurfaces = 0;
+ maxsurfaces = 0;
+}
+
+/*****************************************************************************
+
+ New terrain code
+
+******************************************************************************/
+
+typedef struct terrainFace_s {
+ shaderInfo_t *shaderInfo;
+ //texdef_t texdef;
+
+ float vecs[ 2 ][ 4 ]; // texture coordinate mapping
+} terrainFace_t;
+
+typedef struct terrainVert_s {
+ vec3_t xyz;
+ terrainFace_t tri;
+} terrainVert_t;
+
+typedef struct terrainMesh_s {
+ float scale_x;
+ float scale_y;
+ vec3_t origin;
+
+ int width, height;
+ terrainVert_t *map;
+} terrainMesh_t;
+
+terrainVert_t *Terrain_GetVert( terrainMesh_t *pm, int x, int y ) {
+ return &pm->map[ x + y * pm->width ];
+}
+
+void Terrain_GetTriangles( terrainMesh_t *pm, int x, int y, terrainVert_t **verts ) {
+ if ( ( x + y ) & 1 ) {
+ // first tri
+ verts[ 0 ] = Terrain_GetVert( pm, x, y );
+ verts[ 1 ] = Terrain_GetVert( pm, x, y + 1 );
+ verts[ 2 ] = Terrain_GetVert( pm, x + 1, y + 1 );
+
+ // second tri
+ verts[ 3 ] = verts[ 2 ];
+ verts[ 4 ] = Terrain_GetVert( pm, x + 1, y );
+ verts[ 5 ] = verts[ 0 ];
+ } else {
+ // first tri
+ verts[ 0 ] = Terrain_GetVert( pm, x, y );
+ verts[ 1 ] = Terrain_GetVert( pm, x, y + 1 );
+ verts[ 2 ] = Terrain_GetVert( pm, x + 1, y );
+
+ // second tri
+ verts[ 3 ] = verts[ 2 ];
+ verts[ 4 ] = verts[ 1 ];
+ verts[ 5 ] = Terrain_GetVert( pm, x + 1, y + 1 );
+ }
+}
+
+/*
+================
+EmitTerrainVerts2
+================
+*/
+void EmitTerrainVerts2( terrainSurf_t *surf, terrainVert_t **verts, int alpha[ 3 ] ) {
+ int i;
+ int j;
+ drawVert_t *vert;
+ int *indices;
+ int numindices;
+ int maxindices;
+ int xyplane;
+ vec3_t xynorm = { 0, 0, 1 };
+ vec_t shift[ 2 ] = { 0, 0 };
+ vec_t scale[ 2 ] = { 0.5, 0.5 };
+ float vecs[ 2 ][ 4 ];
+ vec4_t plane;
+
+ if ( !surf->verts ) {
+ surf->numVerts = 0;
+ surf->maxVerts = GROW_VERTS;
+ surf->verts = malloc( surf->maxVerts * sizeof( *surf->verts ) );
+
+ surf->numIndexes = 0;
+ surf->maxIndexes = GROW_INDICES;
+ surf->indexes = malloc( surf->maxIndexes * sizeof( *surf->indexes ) );
+ }
+
+ // calculate the texture coordinate vectors
+ xyplane = FindFloatPlane( xynorm, 0 );
+ QuakeTextureVecs( &mapplanes[ xyplane ], shift, 0, scale, vecs );
+
+ // emit the vertexes
+ numindices = 0;
+ maxindices = surf->maxIndexes;
+ assert( maxindices >= 0 );
+ indices = malloc ( maxindices * sizeof( *indices ) );
+
+ PlaneFromPoints( plane, verts[ 0 ]->xyz, verts[ 1 ]->xyz, verts[ 2 ]->xyz );
+
+ for ( i = 0; i < 3; i++ ) {
+ vert = &surf->verts[ surf->numVerts ];
+
+ if ( alpha[ i ] ) {
+ vert->color[3] = 255;
+ } else {
+ vert->color[3] = 0;
+ }
+
+ vert->xyz[ 0 ] = floor( verts[ i ]->xyz[ 0 ] + 0.1f );
+ vert->xyz[ 1 ] = floor( verts[ i ]->xyz[ 1 ] + 0.1f );
+ vert->xyz[ 2 ] = floor( verts[ i ]->xyz[ 2 ] + 0.1f );
+
+ // set the texture coordinates
+ vert->st[0] = ( vecs[0][3] + DotProduct( vecs[ 0 ], vert->xyz ) ) / surf->shader->width;
+ vert->st[1] = ( vecs[1][3] + DotProduct( vecs[ 1 ], vert->xyz ) ) / surf->shader->height;
+
+ VectorCopy( plane, vert->normal );
+
+ for( j = 0; j < surf->numVerts; j++ ) {
+ if ( CompareVert( vert, &surf->verts[ j ], qtrue ) ) {
+ break;
+ }
+ }
+
+ if ( numindices >= maxindices ) {
+ maxindices += GROW_INDICES;
+ indices = realloc( indices, maxindices * sizeof( *indices ) );
+ }
+
+ if ( j != surf->numVerts ) {
+ indices[ numindices++ ] = j;
+ } else {
+ indices[ numindices++ ] = surf->numVerts;
+ surf->numVerts++;
+ if ( surf->numVerts >= surf->maxVerts ) {
+ surf->maxVerts += GROW_VERTS;
+ surf->verts = realloc( surf->verts, surf->maxVerts * sizeof( *surf->verts ) );
+ }
+ }
+ }
+
+ SideAsTristrip( surf, indices, numindices );
+
+ free( indices );
+}
+
+int MapPlaneFromPoints( vec3_t p0, vec3_t p1, vec3_t p2 );
+void QuakeTextureVecs( plane_t *plane, vec_t shift[2], vec_t rotate, vec_t scale[2], vec_t mappingVecs[2][4] );
+qboolean RemoveDuplicateBrushPlanes( bspbrush_t *b );
+void SetBrushContents( bspbrush_t *b );
+
+void AddBrushSide( vec3_t v1, vec3_t v2, vec3_t v3, shaderInfo_t *terrainShader ) {
+ side_t *side;
+ int planenum;
+
+ side = &buildBrush->sides[ buildBrush->numsides ];
+ memset( side, 0, sizeof( *side ) );
+ buildBrush->numsides++;
+
+ side->shaderInfo = terrainShader;
+
+ // find the plane number
+ planenum = MapPlaneFromPoints( v1, v2, v3 );
+ side->planenum = planenum;
+}
+
+void MakeBrushFromTriangle( vec3_t v1, vec3_t v2, vec3_t v3, shaderInfo_t *terrainShader ) {
+ bspbrush_t *b;
+ vec3_t d1;
+ vec3_t d2;
+ vec3_t d3;
+
+ VectorSet( d1, v1[ 0 ], v1[ 1 ], MIN_WORLD_COORD + 10 ); //FIXME
+ VectorSet( d2, v2[ 0 ], v2[ 1 ], MIN_WORLD_COORD + 10 );
+ VectorSet( d3, v3[ 0 ], v3[ 1 ], MIN_WORLD_COORD + 10 );
+
+ buildBrush->numsides = 0;
+ buildBrush->detail = qfalse;
+
+ AddBrushSide( v1, v2, v3, terrainShader );
+ AddBrushSide( v1, d1, v2, terrainShader );
+ AddBrushSide( v2, d2, v3, terrainShader );
+ AddBrushSide( v3, d3, v1, terrainShader );
+ AddBrushSide( d3, d2, d1, terrainShader );
+
+ buildBrush->portalareas[0] = -1;
+ buildBrush->portalareas[1] = -1;
+ buildBrush->entitynum = num_entities-1;
+ buildBrush->brushnum = entitySourceBrushes;
+
+ // if there are mirrored planes, the entire brush is invalid
+ if ( !RemoveDuplicateBrushPlanes( buildBrush ) ) {
+ return;
+ }
+
+ // get the content for the entire brush
+ SetBrushContents( buildBrush );
+ buildBrush->contents |= CONTENTS_DETAIL;
+
+ b = FinishBrush();
+ if ( !b ) {
+ return;
+ }
+}
+
+void MakeTerrainIntoBrushes( terrainMesh_t *tm ) {
+ int index[ 6 ];
+ int y;
+ int x;
+ terrainVert_t *verts;
+ shaderInfo_t *terrainShader;
+
+ terrainShader = ShaderInfoForShader( "textures/common/terrain" );
+
+ verts = tm->map;
+ for( y = 0; y < tm->height - 1; y++ ) {
+ for( x = 0; x < tm->width - 1; x++ ) {
+ if ( ( x + y ) & 1 ) {
+ // first tri
+ index[ 0 ] = x + y * tm->width;
+ index[ 1 ] = x + ( y + 1 ) * tm->width;
+ index[ 2 ] = ( x + 1 ) + ( y + 1 ) * tm->width;
+ index[ 3 ] = ( x + 1 ) + ( y + 1 ) * tm->width;
+ index[ 4 ] = ( x + 1 ) + y * tm->width;
+ index[ 5 ] = x + y * tm->width;
+ } else {
+ // first tri
+ index[ 0 ] = x + y * tm->width;
+ index[ 1 ] = x + ( y + 1 ) * tm->width;
+ index[ 2 ] = ( x + 1 ) + y * tm->width;
+ index[ 3 ] = ( x + 1 ) + y * tm->width;
+ index[ 4 ] = x + ( y + 1 ) * tm->width;
+ index[ 5 ] = ( x + 1 ) + ( y + 1 ) * tm->width;
+ }
+
+ MakeBrushFromTriangle( verts[ index[ 0 ] ].xyz, verts[ index[ 1 ] ].xyz, verts[ index[ 2 ] ].xyz, terrainShader );
+ MakeBrushFromTriangle( verts[ index[ 3 ] ].xyz, verts[ index[ 4 ] ].xyz, verts[ index[ 5 ] ].xyz, terrainShader );
+ }
+ }
+}
+
+void Terrain_ParseFace( terrainFace_t *face ) {
+ shaderInfo_t *si;
+ vec_t shift[ 2 ];
+ vec_t rotate;
+ vec_t scale[ 2 ];
+ char name[ MAX_QPATH ];
+ char shader[ MAX_QPATH ];
+ plane_t p;
+
+ // read the texturedef
+ GetToken( qfalse );
+ strcpy( name, token );
+
+ GetToken( qfalse );
+ shift[ 0 ] = atof(token);
+ GetToken( qfalse );
+ shift[ 1 ] = atof( token );
+ GetToken( qfalse );
+ rotate = atof( token );
+ GetToken( qfalse );
+ scale[ 0 ] = atof( token );
+ GetToken( qfalse );
+ scale[ 1 ] = atof( token );
+
+ // find default flags and values
+ sprintf( shader, "textures/%s", name );
+ si = ShaderInfoForShader( shader );
+ face->shaderInfo = si;
+ //face->texdef = si->texdef;
+
+ // skip over old contents
+ GetToken( qfalse );
+
+ // skip over old flags
+ GetToken( qfalse );
+
+ // skip over old value
+ GetToken( qfalse );
+
+ //Surface_Parse( &face->texdef );
+ //Surface_BuildTexdef( &face->texdef );
+
+ // make a fake horizontal plane
+ VectorSet( p.normal, 0, 0, 1 );
+ p.dist = 0;
+ p.type = PlaneTypeForNormal( p.normal );
+
+ QuakeTextureVecs( &p, shift, rotate, scale, face->vecs );
+}
+
+#define MAX_TERRAIN_TEXTURES 128
+static int numtextures = 0;;
+static shaderInfo_t *textures[ MAX_TERRAIN_TEXTURES ];
+
+void Terrain_AddTexture( shaderInfo_t *texture ) {
+ int i;
+
+ if ( !texture ) {
+ return;
+ }
+
+ for( i = 0; i < numtextures; i++ ) {
+ if ( textures[ i ] == texture ) {
+ return;
+ }
+ }
+
+ if ( numtextures >= MAX_TERRAIN_TEXTURES ) {
+ Error( "Too many textures on terrain" );
+ return;
+ }
+
+ textures[ numtextures++ ] = texture;
+}
+
+int LayerForShader( shaderInfo_t *shader ) {
+ int i;
+ int l;
+
+ l = strlen( shader->shader );
+ for( i = l - 1; i >= 0; i-- ) {
+ if ( shader->shader[ i ] == '_' ) {
+ return atoi( &shader->shader[ i + 1 ] );
+ break;
+ }
+ }
+
+ return 0;
+}
+
+/*
+=================
+ParseTerrain
+
+Creates a mapDrawSurface_t from the terrain text
+=================
+*/
+
+void ParseTerrain( void ) {
+ int i, j;
+ int x, y;
+ int x1, y1;
+ terrainMesh_t t;
+ int index;
+ terrainVert_t *verts[ 6 ];
+ int num_layers;
+ int layer, minlayer, maxlayer;
+ int alpha[ 6 ];
+ shaderInfo_t *si, *terrainShader;
+ int surfwidth, surfheight, surfsize;
+ terrainSurf_t *surf;
+ char shadername[ MAX_QPATH ];
+
+ mapent->firstDrawSurf = numMapDrawSurfs;
+
+ memset( &t, 0, sizeof( t ) );
+
+ MatchToken( "{" );
+
+ // get width
+ GetToken( qtrue );
+ t.width = atoi( token );
+
+ // get height
+ GetToken( qfalse );
+ t.height = atoi( token );
+
+ // get scale_x
+ GetToken( qfalse );
+ t.scale_x = atof( token );
+
+ // get scale_y
+ GetToken( qfalse );
+ t.scale_y = atof( token );
+
+ // get origin
+ GetToken( qtrue );
+ t.origin[ 0 ] = atof( token );
+ GetToken( qfalse );
+ t.origin[ 1 ] = atof( token );
+ GetToken( qfalse );
+ t.origin[ 2 ] = atof( token );
+
+ t.map = malloc( t.width * t.height * sizeof( t.map[ 0 ] ) );
+
+ if ( t.width <= 0 || t.height <= 0 ) {
+ Error( "ParseTerrain: bad size" );
+ }
+
+ numtextures = 0;
+ index = 0;
+ for ( i = 0; i < t.height; i++ ) {
+ for( j = 0; j < t.width; j++, index++ ) {
+ // get height
+ GetToken( qtrue );
+ t.map[ index ].xyz[ 0 ] = t.origin[ 0 ] + t.scale_x * ( float )j;
+ t.map[ index ].xyz[ 1 ] = t.origin[ 1 ] + t.scale_y * ( float )i;
+ t.map[ index ].xyz[ 2 ] = t.origin[ 2 ] + atof( token );
+
+ Terrain_ParseFace( &t.map[ index ].tri );
+ Terrain_AddTexture( t.map[ index ].tri.shaderInfo );
+ }
+ }
+
+ MatchToken( "}" );
+ MatchToken( "}" );
+
+ MakeTerrainIntoBrushes( &t );
+
+ surfwidth = ( ( t.scale_x * t.width ) + SURF_WIDTH - 1 ) / SURF_WIDTH;
+ surfheight = ( ( t.scale_y * t.height ) + SURF_HEIGHT - 1 ) / SURF_HEIGHT;
+ surfsize = surfwidth * surfheight;
+
+ //FIXME
+ num_layers = 0;
+ for( i = 0; i < numtextures; i++ ) {
+ layer = LayerForShader( textures[ i ] ) + 1;
+ if ( layer > num_layers ) {
+ num_layers = layer;
+ }
+ }
+ num_layers = 4;
+
+ memset( alpha, 0, sizeof( alpha ) );
+
+ lastSurface = NULL;
+ numsurfaces = 0;
+ maxsurfaces = 0;
+ for( i = num_layers; i > 0; i-- ) {
+ maxsurfaces += i * surfsize;
+ }
+
+ surfaces = malloc( maxsurfaces * sizeof( *surfaces ) );
+ memset( surfaces, 0, maxsurfaces * sizeof( *surfaces ) );
+
+ terrainShader = ShaderInfoForShader( "textures/common/terrain" );
+
+ // get the shadername
+ if ( Q_strncasecmp( textures[ 0 ]->shader, "textures/", 9 ) == 0 ) {
+ strcpy( shadername, &textures[ 0 ]->shader[ 9 ] );
+ } else {
+ strcpy( shadername, textures[ 0 ]->shader );
+ }
+ j = strlen( shadername );
+ for( i = j - 1; i >= 0; i-- ) {
+ if ( shadername[ i ] == '_' ) {
+ shadername[ i ] = 0;
+ break;
+ }
+ }
+
+ for( y = 0; y < t.height - 1; y++ ) {
+ for( x = 0; x < t.width - 1; x++ ) {
+ Terrain_GetTriangles( &t, x, y, verts );
+
+ x1 = ( ( float )x / ( float )( t.width - 1 ) ) * surfwidth;
+ if ( x1 >= surfwidth ) {
+ x1 = surfwidth - 1;
+ }
+
+ y1 = ( ( float )y / ( float )( t.height - 1 ) ) * surfheight;
+ if ( y1 >= surfheight ) {
+ y1 = surfheight - 1;
+ }
+
+ maxlayer = minlayer = LayerForShader( verts[ 0 ]->tri.shaderInfo );
+ for( i = 0; i < 3; i++ ) {
+ layer = LayerForShader( verts[ i ]->tri.shaderInfo );
+ if ( layer < minlayer ) {
+ minlayer = layer;
+ }
+ if ( layer > maxlayer ) {
+ maxlayer = layer;
+ }
+ }
+
+ for( i = 0; i < 3; i++ ) {
+ layer = LayerForShader( verts[ i ]->tri.shaderInfo );
+ if ( layer > minlayer ) {
+ alpha[ i ] = 1.0f;
+ } else {
+ alpha[ i ] = 0.0f;
+ }
+ }
+
+ si = ShaderForLayer( minlayer, maxlayer, shadername );
+ surf = SurfaceForShader( si, x1, y1 );
+ EmitTerrainVerts2( surf, &verts[ 0 ], &alpha[ 0 ] );
+
+ // second triangle
+ maxlayer = minlayer = LayerForShader( verts[ 3 ]->tri.shaderInfo );
+ for( i = 3; i < 6; i++ ) {
+ layer = LayerForShader( verts[ i ]->tri.shaderInfo );
+ if ( layer < minlayer ) {
+ minlayer = layer;
+ }
+ if ( layer > maxlayer ) {
+ maxlayer = layer;
+ }
+ }
+
+ for( i = 3; i < 6; i++ ) {
+ layer = LayerForShader( verts[ i ]->tri.shaderInfo );
+ if ( layer > minlayer ) {
+ alpha[ i ] = 1.0f;
+ } else {
+ alpha[ i ] = 0.0f;
+ }
+ }
+
+ si = ShaderForLayer( minlayer, maxlayer, shadername );
+ surf = SurfaceForShader( si, x1, y1 );
+ EmitTerrainVerts2( surf, &verts[ 3 ], &alpha[ 3 ] );
+ }
+ }
+
+ // create the final surfaces
+ for( surf = surfaces, i = 0; i < numsurfaces; i++, surf++ ) {
+ if ( surf->numVerts ) {
+ CreateTerrainSurface( surf, surf->shader );
+ }
+ }
+
+ //
+ // clean up any allocated memory
+ //
+ for( surf = surfaces, i = 0; i < numsurfaces; i++, surf++ ) {
+ if ( surf->verts ) {
+ free( surf->verts );
+ free( surf->indexes );
+ }
+ }
+ free( surfaces );
+
+ surfaces = NULL;
+ lastSurface = NULL;
+ numsurfaces = 0;
+ maxsurfaces = 0;
+
+ free( t.map );
+}
+
diff --git a/q3map/tjunction.c b/q3map/tjunction.c
new file mode 100755
index 0000000..9d41dc2
--- /dev/null
+++ b/q3map/tjunction.c
@@ -0,0 +1,551 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "qbsp.h"
+
+typedef struct edgePoint_s {
+ float intercept;
+ vec3_t xyz;
+ struct edgePoint_s *prev, *next;
+} edgePoint_t;
+
+typedef struct edgeLine_s {
+ vec3_t normal1;
+ float dist1;
+
+ vec3_t normal2;
+ float dist2;
+
+ vec3_t origin;
+ vec3_t dir;
+
+ edgePoint_t chain; // unused element of doubly linked list
+} edgeLine_t;
+
+typedef struct {
+ float length;
+ drawVert_t *dv[2];
+} originalEdge_t;
+
+#define MAX_ORIGINAL_EDGES 0x10000
+originalEdge_t originalEdges[MAX_ORIGINAL_EDGES];
+int numOriginalEdges;
+
+
+#define MAX_EDGE_LINES 0x10000
+edgeLine_t edgeLines[MAX_EDGE_LINES];
+int numEdgeLines;
+
+int c_degenerateEdges;
+int c_addedVerts;
+int c_totalVerts;
+
+int c_natural, c_rotate, c_cant;
+
+// these should be whatever epsilon we actually expect,
+// plus SNAP_INT_TO_FLOAT
+#define LINE_POSITION_EPSILON 0.25
+#define POINT_ON_LINE_EPSILON 0.25
+
+/*
+====================
+InsertPointOnEdge
+====================
+*/
+void InsertPointOnEdge( vec3_t v, edgeLine_t *e ) {
+ vec3_t delta;
+ float d;
+ edgePoint_t *p, *scan;
+
+ VectorSubtract( v, e->origin, delta );
+ d = DotProduct( delta, e->dir );
+
+ p = malloc( sizeof(edgePoint_t) );
+ p->intercept = d;
+ VectorCopy( v, p->xyz );
+
+ if ( e->chain.next == &e->chain ) {
+ e->chain.next = e->chain.prev = p;
+ p->next = p->prev = &e->chain;
+ return;
+ }
+
+ scan = e->chain.next;
+ for ( ; scan != &e->chain ; scan = scan->next ) {
+ d = p->intercept - scan->intercept;
+ if ( d > -LINE_POSITION_EPSILON && d < LINE_POSITION_EPSILON ) {
+ free( p );
+ return; // the point is already set
+ }
+
+ if ( p->intercept < scan->intercept ) {
+ // insert here
+ p->prev = scan->prev;
+ p->next = scan;
+ scan->prev->next = p;
+ scan->prev = p;
+ return;
+ }
+ }
+
+ // add at the end
+ p->prev = scan->prev;
+ p->next = scan;
+ scan->prev->next = p;
+ scan->prev = p;
+}
+
+
+/*
+====================
+AddEdge
+====================
+*/
+int AddEdge( vec3_t v1, vec3_t v2, qboolean createNonAxial ) {
+ int i;
+ edgeLine_t *e;
+ float d;
+ vec3_t dir;
+
+ VectorSubtract( v2, v1, dir );
+ d = VectorNormalize( dir, dir );
+ if ( d < 0.1 ) {
+ // if we added a 0 length vector, it would make degenerate planes
+ c_degenerateEdges++;
+ return -1;
+ }
+
+ if ( !createNonAxial ) {
+ if ( fabs( dir[0] + dir[1] + dir[2] ) != 1.0 ) {
+ if ( numOriginalEdges == MAX_ORIGINAL_EDGES ) {
+ Error( "MAX_ORIGINAL_EDGES" );
+ }
+ originalEdges[ numOriginalEdges ].dv[0] = (drawVert_t *)v1;
+ originalEdges[ numOriginalEdges ].dv[1] = (drawVert_t *)v2;
+ originalEdges[ numOriginalEdges ].length = d;
+ numOriginalEdges++;
+ return -1;
+ }
+ }
+
+ for ( i = 0 ; i < numEdgeLines ; i++ ) {
+ e = &edgeLines[i];
+
+ d = DotProduct( v1, e->normal1 ) - e->dist1;
+ if ( d < -POINT_ON_LINE_EPSILON || d > POINT_ON_LINE_EPSILON ) {
+ continue;
+ }
+ d = DotProduct( v1, e->normal2 ) - e->dist2;
+ if ( d < -POINT_ON_LINE_EPSILON || d > POINT_ON_LINE_EPSILON ) {
+ continue;
+ }
+
+ d = DotProduct( v2, e->normal1 ) - e->dist1;
+ if ( d < -POINT_ON_LINE_EPSILON || d > POINT_ON_LINE_EPSILON ) {
+ continue;
+ }
+ d = DotProduct( v2, e->normal2 ) - e->dist2;
+ if ( d < -POINT_ON_LINE_EPSILON || d > POINT_ON_LINE_EPSILON ) {
+ continue;
+ }
+
+ // this is the edge
+ InsertPointOnEdge( v1, e );
+ InsertPointOnEdge( v2, e );
+ return i;
+ }
+
+ // create a new edge
+ if ( numEdgeLines >= MAX_EDGE_LINES ) {
+ Error( "MAX_EDGE_LINES" );
+ }
+
+ e = &edgeLines[ numEdgeLines ];
+ numEdgeLines++;
+
+ e->chain.next = e->chain.prev = &e->chain;
+
+ VectorCopy( v1, e->origin );
+ VectorCopy( dir, e->dir );
+
+ MakeNormalVectors( e->dir, e->normal1, e->normal2 );
+ e->dist1 = DotProduct( e->origin, e->normal1 );
+ e->dist2 = DotProduct( e->origin, e->normal2 );
+
+ InsertPointOnEdge( v1, e );
+ InsertPointOnEdge( v2, e );
+
+ return numEdgeLines - 1;
+}
+
+/*
+====================
+AddSurfaceEdges
+====================
+*/
+void AddSurfaceEdges( mapDrawSurface_t *ds ) {
+ int i;
+
+ for ( i = 0 ; i < ds->numVerts ; i++ ) {
+ // save the edge number in the lightmap field
+ // so we don't need to look it up again
+ ds->verts[i].lightmap[0] =
+ AddEdge( ds->verts[i].xyz, ds->verts[(i+1) % ds->numVerts].xyz, qfalse );
+ }
+}
+
+/*
+================
+ColinearEdge
+================
+*/
+qboolean ColinearEdge( vec3_t v1, vec3_t v2, vec3_t v3 ) {
+ vec3_t midpoint, dir, offset, on;
+ float d;
+
+ VectorSubtract( v2, v1, midpoint );
+ VectorSubtract( v3, v1, dir );
+ d = VectorNormalize( dir, dir );
+ if ( d == 0 ) {
+ return qfalse; // degenerate
+ }
+
+ d = DotProduct( midpoint, dir );
+ VectorScale( dir, d, on );
+ VectorSubtract( midpoint, on, offset );
+ d = VectorLength ( offset );
+
+ if ( d < 0.1 ) {
+ return qtrue;
+ }
+
+ return qfalse;
+}
+
+/*
+====================
+AddPatchEdges
+
+Add colinear border edges, which will fix some classes of patch to
+brush tjunctions
+====================
+*/
+void AddPatchEdges( mapDrawSurface_t *ds ) {
+ int i;
+ float *v1, *v2, *v3;
+
+ for ( i = 0 ; i < ds->patchWidth - 2; i+=2 ) {
+ v1 = ds->verts[ i ].xyz;
+ v2 = ds->verts[ i + 1 ].xyz;
+ v3 = ds->verts[ i + 2 ].xyz;
+
+ // if v2 is the midpoint of v1 to v3, add an edge from v1 to v3
+ if ( ColinearEdge( v1, v2, v3 ) ) {
+ AddEdge( v1, v3, qfalse );
+ }
+
+ v1 = ds->verts[ ( ds->patchHeight - 1 ) * ds->patchWidth + i ].xyz;
+ v2 = ds->verts[ ( ds->patchHeight - 1 ) * ds->patchWidth + i + 1 ].xyz;
+ v3 = ds->verts[ ( ds->patchHeight - 1 ) * ds->patchWidth + i + 2 ].xyz;
+
+ // if v2 is on the v1 to v3 line, add an edge from v1 to v3
+ if ( ColinearEdge( v1, v2, v3 ) ) {
+ AddEdge( v1, v3, qfalse );
+ }
+ }
+
+ for ( i = 0 ; i < ds->patchHeight - 2 ; i+=2 ) {
+ v1 = ds->verts[ i * ds->patchWidth ].xyz;
+ v2 = ds->verts[ ( i + 1 ) * ds->patchWidth ].xyz;
+ v3 = ds->verts[ ( i + 2 ) * ds->patchWidth ].xyz;
+
+ // if v2 is the midpoint of v1 to v3, add an edge from v1 to v3
+ if ( ColinearEdge( v1, v2, v3 ) ) {
+ AddEdge( v1, v3, qfalse );
+ }
+
+ v1 = ds->verts[ ( ds->patchWidth - 1 ) + i * ds->patchWidth ].xyz;
+ v2 = ds->verts[ ( ds->patchWidth - 1 ) + ( i + 1 ) * ds->patchWidth ].xyz;
+ v3 = ds->verts[ ( ds->patchWidth - 1 ) + ( i + 2 ) * ds->patchWidth ].xyz;
+
+ // if v2 is the midpoint of v1 to v3, add an edge from v1 to v3
+ if ( ColinearEdge( v1, v2, v3 ) ) {
+ AddEdge( v1, v3, qfalse );
+ }
+ }
+
+
+}
+
+
+/*
+====================
+FixSurfaceJunctions
+====================
+*/
+#define MAX_SURFACE_VERTS 256
+void FixSurfaceJunctions( mapDrawSurface_t *ds ) {
+ int i, j, k;
+ edgeLine_t *e;
+ edgePoint_t *p;
+ int originalVerts;
+ int counts[MAX_SURFACE_VERTS];
+ int originals[MAX_SURFACE_VERTS];
+ int firstVert[MAX_SURFACE_VERTS];
+ drawVert_t verts[MAX_SURFACE_VERTS], *v1, *v2;
+ int numVerts;
+ float start, end, frac;
+ vec3_t delta;
+
+ originalVerts = ds->numVerts;
+
+ numVerts = 0;
+ for ( i = 0 ; i < ds->numVerts ; i++ ) {
+ counts[i] = 0;
+ firstVert[i] = numVerts;
+
+ // copy first vert
+ if ( numVerts == MAX_SURFACE_VERTS ) {
+ Error( "MAX_SURFACE_VERTS" );
+ }
+ verts[numVerts] = ds->verts[i];
+ originals[numVerts] = i;
+ numVerts++;
+
+ // check to see if there are any t junctions before the next vert
+ v1 = &ds->verts[i];
+ v2 = &ds->verts[ (i+1) % ds->numVerts ];
+
+ j = (int)ds->verts[i].lightmap[0];
+ if ( j == -1 ) {
+ continue; // degenerate edge
+ }
+ e = &edgeLines[ j ];
+
+ VectorSubtract( v1->xyz, e->origin, delta );
+ start = DotProduct( delta, e->dir );
+
+ VectorSubtract( v2->xyz, e->origin, delta );
+ end = DotProduct( delta, e->dir );
+
+
+ if ( start < end ) {
+ p = e->chain.next;
+ } else {
+ p = e->chain.prev;
+ }
+
+ for ( ; p != &e->chain ; ) {
+ if ( start < end ) {
+ if ( p->intercept > end - ON_EPSILON ) {
+ break;
+ }
+ } else {
+ if ( p->intercept < end + ON_EPSILON ) {
+ break;
+ }
+ }
+
+ if (
+ ( start < end && p->intercept > start + ON_EPSILON ) ||
+ ( start > end && p->intercept < start - ON_EPSILON ) ) {
+ // insert this point
+ if ( numVerts == MAX_SURFACE_VERTS ) {
+ Error( "MAX_SURFACE_VERTS" );
+ }
+
+ // take the exact intercept point
+ VectorCopy( p->xyz, verts[ numVerts ].xyz );
+
+ // copy the normal
+ VectorCopy( v1->normal, verts[ numVerts ].normal );
+
+ // interpolate the texture coordinates
+ frac = ( p->intercept - start ) / ( end - start );
+ for ( j = 0 ; j < 2 ; j++ ) {
+ verts[ numVerts ].st[j] = v1->st[j] +
+ frac * ( v2->st[j] - v1->st[j] );
+ }
+ originals[numVerts] = i;
+ numVerts++;
+ counts[i]++;
+ }
+
+ if ( start < end ) {
+ p = p->next;
+ } else {
+ p = p->prev;
+ }
+ }
+ }
+
+ c_addedVerts += numVerts - ds->numVerts;
+ c_totalVerts += numVerts;
+
+
+ // FIXME: check to see if the entire surface degenerated
+ // after snapping
+
+ // rotate the points so that the initial vertex is between
+ // two non-subdivided edges
+ for ( i = 0 ; i < numVerts ; i++ ) {
+ if ( originals[ (i+1) % numVerts ] == originals[ i ] ) {
+ continue;
+ }
+ j = (i + numVerts - 1 ) % numVerts;
+ k = (i + numVerts - 2 ) % numVerts;
+ if ( originals[ j ] == originals[ k ] ) {
+ continue;
+ }
+ break;
+ }
+
+ if ( i == 0 ) {
+ // fine the way it is
+ c_natural++;
+
+ ds->numVerts = numVerts;
+ ds->verts = malloc( numVerts * sizeof( *ds->verts ) );
+ memcpy( ds->verts, verts, numVerts * sizeof( *ds->verts ) );
+
+ return;
+ }
+ if ( i == numVerts ) {
+ // create a vertex in the middle to start the fan
+ c_cant++;
+
+/*
+ memset ( &verts[numVerts], 0, sizeof( verts[numVerts] ) );
+ for ( i = 0 ; i < numVerts ; i++ ) {
+ for ( j = 0 ; j < 10 ; j++ ) {
+ verts[numVerts].xyz[j] += verts[i].xyz[j];
+ }
+ }
+ for ( j = 0 ; j < 10 ; j++ ) {
+ verts[numVerts].xyz[j] /= numVerts;
+ }
+
+ i = numVerts;
+ numVerts++;
+*/
+ } else {
+ // just rotate the vertexes
+ c_rotate++;
+
+ }
+
+ ds->numVerts = numVerts;
+ ds->verts = malloc( numVerts * sizeof( *ds->verts ) );
+
+ for ( j = 0 ; j < ds->numVerts ; j++ ) {
+ ds->verts[j] = verts[ ( j + i ) % ds->numVerts ];
+ }
+}
+
+/*
+================
+EdgeCompare
+================
+*/
+int EdgeCompare( const void *elem1, const void *elem2 ) {
+ float d1, d2;
+
+ d1 = ((originalEdge_t *)elem1)->length;
+ d2 = ((originalEdge_t *)elem2)->length;
+
+ if ( d1 < d2 ) {
+ return -1;
+ }
+ if ( d2 > d1 ) {
+ return 1;
+ }
+ return 0;
+}
+
+
+/*
+================
+FixTJunctions
+
+Call after the surface list has been pruned, but before lightmap allocation
+================
+*/
+void FixTJunctions( entity_t *ent ) {
+ int i;
+ mapDrawSurface_t *ds;
+ int axialEdgeLines;
+ originalEdge_t *e;
+
+ qprintf("----- FixTJunctions -----\n");
+
+ numEdgeLines = 0;
+ numOriginalEdges = 0;
+
+ // add all the edges
+ // this actually creates axial edges, but it
+ // only creates originalEdge_t structures
+ // for non-axial edges
+ for ( i = ent->firstDrawSurf ; i < numMapDrawSurfs ; i++ ) {
+ ds = &mapDrawSurfs[i];
+ if ( ds->patch ) {
+ AddPatchEdges( ds );
+ } else if ( ds->shaderInfo->autosprite || ds->shaderInfo->notjunc || ds->miscModel ) {
+ // miscModels don't add tjunctions
+ } else {
+ AddSurfaceEdges( ds );
+ }
+ }
+
+ axialEdgeLines = numEdgeLines;
+
+ // sort the non-axial edges by length
+ qsort( originalEdges, numOriginalEdges, sizeof(originalEdges[0]), EdgeCompare );
+
+ // add the non-axial edges, longest first
+ // this gives the most accurate edge description
+ for ( i = 0 ; i < numOriginalEdges ; i++ ) {
+ e = &originalEdges[i];
+ e->dv[0]->lightmap[0] = AddEdge( e->dv[0]->xyz, e->dv[1]->xyz, qtrue );
+ }
+
+ qprintf( "%6i axial edge lines\n", axialEdgeLines );
+ qprintf( "%6i non-axial edge lines\n", numEdgeLines - axialEdgeLines );
+ qprintf( "%6i degenerate edges\n", c_degenerateEdges );
+
+ // insert any needed vertexes
+ for ( i = ent->firstDrawSurf ; i < numMapDrawSurfs ; i++ ) {
+ ds = &mapDrawSurfs[i];
+ if ( ds->patch ) {
+ continue;
+ }
+ if ( ds->shaderInfo->autosprite || ds->shaderInfo->notjunc || ds->miscModel ) {
+ continue;
+ }
+
+ FixSurfaceJunctions( ds );
+ }
+
+ qprintf( "%6i verts added for tjunctions\n", c_addedVerts );
+ qprintf( "%6i total verts\n", c_totalVerts );
+ qprintf( "%6i naturally ordered\n", c_natural );
+ qprintf( "%6i rotated orders\n", c_rotate );
+ qprintf( "%6i can't order\n", c_cant );
+}
diff --git a/q3map/tree.c b/q3map/tree.c
new file mode 100755
index 0000000..4addea6
--- /dev/null
+++ b/q3map/tree.c
@@ -0,0 +1,146 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "qbsp.h"
+
+
+extern int c_nodes;
+
+void RemovePortalFromNode (portal_t *portal, node_t *l);
+
+node_t *NodeForPoint (node_t *node, vec3_t origin)
+{
+ plane_t *plane;
+ vec_t d;
+
+ while (node->planenum != PLANENUM_LEAF)
+ {
+ plane = &mapplanes[node->planenum];
+ d = DotProduct (origin, plane->normal) - plane->dist;
+ if (d >= 0)
+ node = node->children[0];
+ else
+ node = node->children[1];
+ }
+
+ return node;
+}
+
+
+
+/*
+=============
+FreeTreePortals_r
+=============
+*/
+void FreeTreePortals_r (node_t *node)
+{
+ portal_t *p, *nextp;
+ int s;
+
+ // free children
+ if (node->planenum != PLANENUM_LEAF)
+ {
+ FreeTreePortals_r (node->children[0]);
+ FreeTreePortals_r (node->children[1]);
+ }
+
+ // free portals
+ for (p=node->portals ; p ; p=nextp)
+ {
+ s = (p->nodes[1] == node);
+ nextp = p->next[s];
+
+ RemovePortalFromNode (p, p->nodes[!s]);
+ FreePortal (p);
+ }
+ node->portals = NULL;
+}
+
+/*
+=============
+FreeTree_r
+=============
+*/
+void FreeTree_r (node_t *node)
+{
+ // free children
+ if (node->planenum != PLANENUM_LEAF)
+ {
+ FreeTree_r (node->children[0]);
+ FreeTree_r (node->children[1]);
+ }
+
+ // free bspbrushes
+ FreeBrushList (node->brushlist);
+
+ // free the node
+ if (node->volume)
+ FreeBrush (node->volume);
+
+ if (numthreads == 1)
+ c_nodes--;
+ free (node);
+}
+
+
+/*
+=============
+FreeTree
+=============
+*/
+void FreeTree (tree_t *tree)
+{
+ FreeTreePortals_r (tree->headnode);
+ FreeTree_r (tree->headnode);
+ free (tree);
+}
+
+//===============================================================
+
+void PrintTree_r (node_t *node, int depth)
+{
+ int i;
+ plane_t *plane;
+ bspbrush_t *bb;
+
+ for (i=0 ; i<depth ; i++)
+ _printf (" ");
+ if (node->planenum == PLANENUM_LEAF)
+ {
+ if (!node->brushlist)
+ _printf ("NULL\n");
+ else
+ {
+ for (bb=node->brushlist ; bb ; bb=bb->next)
+ _printf ("%i ", bb->original->brushnum);
+ _printf ("\n");
+ }
+ return;
+ }
+
+ plane = &mapplanes[node->planenum];
+ _printf ("#%i (%5.2f %5.2f %5.2f):%5.2f\n", node->planenum,
+ plane->normal[0], plane->normal[1], plane->normal[2],
+ plane->dist);
+ PrintTree_r (node->children[0], depth+1);
+ PrintTree_r (node->children[1], depth+1);
+}
diff --git a/q3map/vis.c b/q3map/vis.c
new file mode 100755
index 0000000..6baab38
--- /dev/null
+++ b/q3map/vis.c
@@ -0,0 +1,1197 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// vis.c
+
+#include "vis.h"
+#include "threads.h"
+#include "stdlib.h"
+#ifdef _WIN32
+#include "../libs/pakstuff.h"
+#endif
+
+
+#define VIS_HEADER_SIZE 8
+
+extern char outbase[32];
+
+int numportals;
+int portalclusters;
+int numfaces;
+
+char inbase[32];
+
+vportal_t *portals;
+leaf_t *leafs;
+
+vportal_t *faces;
+leaf_t *faceleafs;
+
+int c_portaltest, c_portalpass, c_portalcheck;
+
+int leafbytes; // (portalclusters+63)>>3
+int leaflongs;
+
+int portalbytes, portallongs;
+
+qboolean fastvis;
+qboolean noPassageVis;
+qboolean passageVisOnly;
+qboolean mergevis;
+qboolean nosort;
+qboolean saveprt;
+
+int testlevel = 2;
+
+int totalvis;
+
+vportal_t *sorted_portals[MAX_MAP_PORTALS*2];
+
+void PassageMemory(void);
+
+
+//=============================================================================
+
+void PlaneFromWinding (winding_t *w, plane_t *plane)
+{
+ vec3_t v1, v2;
+
+// calc plane
+ VectorSubtract (w->points[2], w->points[1], v1);
+ VectorSubtract (w->points[0], w->points[1], v2);
+ CrossProduct (v2, v1, plane->normal);
+ VectorNormalize (plane->normal, plane->normal);
+ plane->dist = DotProduct (w->points[0], plane->normal);
+}
+
+
+/*
+==================
+NewWinding
+==================
+*/
+winding_t *NewWinding (int points)
+{
+ winding_t *w;
+ int size;
+
+ if (points > MAX_POINTS_ON_WINDING)
+ Error ("NewWinding: %i points", points);
+
+ size = (int)((winding_t *)0)->points[points];
+ w = malloc (size);
+ memset (w, 0, size);
+
+ return w;
+}
+
+
+
+void prl(leaf_t *l)
+{
+ int i;
+ vportal_t *p;
+ plane_t pl;
+
+ for (i=0 ; i<l->numportals ; i++)
+ {
+ p = l->portals[i];
+ pl = p->plane;
+ _printf ("portal %4i to leaf %4i : %7.1f : (%4.1f, %4.1f, %4.1f)\n",(int)(p-portals),p->leaf,pl.dist, pl.normal[0], pl.normal[1], pl.normal[2]);
+ }
+}
+
+
+//=============================================================================
+
+/*
+=============
+SortPortals
+
+Sorts the portals from the least complex, so the later ones can reuse
+the earlier information.
+=============
+*/
+int PComp (const void *a, const void *b)
+{
+ if ( (*(vportal_t **)a)->nummightsee == (*(vportal_t **)b)->nummightsee)
+ return 0;
+ if ( (*(vportal_t **)a)->nummightsee < (*(vportal_t **)b)->nummightsee)
+ return -1;
+ return 1;
+}
+void SortPortals (void)
+{
+ int i;
+
+ for (i=0 ; i<numportals*2 ; i++)
+ sorted_portals[i] = &portals[i];
+
+ if (nosort)
+ return;
+ qsort (sorted_portals, numportals*2, sizeof(sorted_portals[0]), PComp);
+}
+
+
+/*
+==============
+LeafVectorFromPortalVector
+==============
+*/
+int LeafVectorFromPortalVector (byte *portalbits, byte *leafbits)
+{
+ int i, j, leafnum;
+ vportal_t *p;
+ int c_leafs;
+
+
+ for (i=0 ; i<numportals*2 ; i++)
+ {
+ if (portalbits[i>>3] & (1<<(i&7)) )
+ {
+ p = portals+i;
+ leafbits[p->leaf>>3] |= (1<<(p->leaf&7));
+ }
+ }
+
+ for (j = 0; j < portalclusters; j++)
+ {
+ leafnum = j;
+ while (leafs[leafnum].merged >= 0)
+ leafnum = leafs[leafnum].merged;
+ //if the merged leaf is visible then the original leaf is visible
+ if (leafbits[leafnum>>3] & (1<<(leafnum&7)))
+ {
+ leafbits[j>>3] |= (1<<(j&7));
+ }
+ }
+
+ c_leafs = CountBits (leafbits, portalclusters);
+
+ return c_leafs;
+}
+
+
+/*
+===============
+ClusterMerge
+
+Merges the portal visibility for a leaf
+===============
+*/
+void ClusterMerge (int leafnum)
+{
+ leaf_t *leaf;
+ byte portalvector[MAX_PORTALS/8];
+ byte uncompressed[MAX_MAP_LEAFS/8];
+ int i, j;
+ int numvis, mergedleafnum;
+ vportal_t *p;
+ int pnum;
+
+ // OR together all the portalvis bits
+
+ mergedleafnum = leafnum;
+ while(leafs[mergedleafnum].merged >= 0)
+ mergedleafnum = leafs[mergedleafnum].merged;
+
+ memset (portalvector, 0, portalbytes);
+ leaf = &leafs[mergedleafnum];
+ for (i = 0; i < leaf->numportals; i++)
+ {
+ p = leaf->portals[i];
+ if (p->removed)
+ continue;
+
+ if (p->status != stat_done)
+ Error ("portal not done");
+ for (j=0 ; j<portallongs ; j++)
+ ((long *)portalvector)[j] |= ((long *)p->portalvis)[j];
+ pnum = p - portals;
+ portalvector[pnum>>3] |= 1<<(pnum&7);
+ }
+
+ memset (uncompressed, 0, leafbytes);
+
+ uncompressed[mergedleafnum>>3] |= (1<<(mergedleafnum&7));
+ // convert portal bits to leaf bits
+ numvis = LeafVectorFromPortalVector (portalvector, uncompressed);
+
+// if (uncompressed[leafnum>>3] & (1<<(leafnum&7)))
+// _printf ("WARNING: Leaf portals saw into leaf\n");
+
+// uncompressed[leafnum>>3] |= (1<<(leafnum&7));
+
+ numvis++; // count the leaf itself
+
+ totalvis += numvis;
+
+ qprintf ("cluster %4i : %4i visible\n", leafnum, numvis);
+
+ memcpy (visBytes + VIS_HEADER_SIZE + leafnum*leafbytes, uncompressed, leafbytes);
+}
+
+/*
+==================
+CalcPortalVis
+==================
+*/
+void CalcPortalVis (void)
+{
+#ifdef MREDEBUG
+ _printf("%6d portals out of %d", 0, numportals*2);
+ //get rid of the counter
+ RunThreadsOnIndividual (numportals*2, qfalse, PortalFlow);
+#else
+ RunThreadsOnIndividual (numportals*2, qtrue, PortalFlow);
+#endif
+
+}
+
+/*
+==================
+CalcPassageVis
+==================
+*/
+void CalcPassageVis(void)
+{
+ PassageMemory();
+
+#ifdef MREDEBUG
+ _printf("%6d portals out of %d", 0, numportals*2);
+ RunThreadsOnIndividual (numportals*2, qfalse, CreatePassages);
+ _printf("\n");
+ _printf("%6d portals out of %d", 0, numportals*2);
+ RunThreadsOnIndividual (numportals*2, qfalse, PassageFlow);
+ _printf("\n");
+#else
+ RunThreadsOnIndividual (numportals*2, qtrue, CreatePassages);
+ RunThreadsOnIndividual (numportals*2, qtrue, PassageFlow);
+#endif
+}
+
+/*
+==================
+CalcPassagePortalVis
+==================
+*/
+void CalcPassagePortalVis(void)
+{
+ PassageMemory();
+
+#ifdef MREDEBUG
+ _printf("%6d portals out of %d", 0, numportals*2);
+ RunThreadsOnIndividual (numportals*2, qfalse, CreatePassages);
+ _printf("\n");
+ _printf("%6d portals out of %d", 0, numportals*2);
+ RunThreadsOnIndividual (numportals*2, qfalse, PassagePortalFlow);
+ _printf("\n");
+#else
+ RunThreadsOnIndividual (numportals*2, qtrue, CreatePassages);
+ RunThreadsOnIndividual (numportals*2, qtrue, PassagePortalFlow);
+#endif
+}
+
+/*
+==================
+CalcFastVis
+==================
+*/
+void CalcFastVis(void)
+{
+ int i;
+
+ // fastvis just uses mightsee for a very loose bound
+ for (i=0 ; i<numportals*2 ; i++)
+ {
+ portals[i].portalvis = portals[i].portalflood;
+ portals[i].status = stat_done;
+ }
+}
+
+/*
+==================
+CalcVis
+==================
+*/
+void CalcVis (void)
+{
+ int i;
+
+ RunThreadsOnIndividual (numportals*2, qtrue, BasePortalVis);
+
+// RunThreadsOnIndividual (numportals*2, qtrue, BetterPortalVis);
+
+ SortPortals ();
+
+ if (fastvis) {
+ CalcFastVis();
+ }
+ else if ( noPassageVis ) {
+ CalcPortalVis();
+ }
+ else if ( passageVisOnly ) {
+ CalcPassageVis();
+ }
+ else {
+ CalcPassagePortalVis();
+ }
+ //
+ // assemble the leaf vis lists by oring and compressing the portal lists
+ //
+ _printf("creating leaf vis...\n");
+ for (i=0 ; i<portalclusters ; i++)
+ ClusterMerge (i);
+
+ _printf( "Total visible clusters: %i\n", totalvis );
+ _printf( "Average clusters visible: %i\n", totalvis / portalclusters );
+}
+
+/*
+==================
+SetPortalSphere
+==================
+*/
+void SetPortalSphere (vportal_t *p)
+{
+ int i;
+ vec3_t total, dist;
+ winding_t *w;
+ float r, bestr;
+
+ w = p->winding;
+ VectorCopy (vec3_origin, total);
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ VectorAdd (total, w->points[i], total);
+ }
+
+ for (i=0 ; i<3 ; i++)
+ total[i] /= w->numpoints;
+
+ bestr = 0;
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ VectorSubtract (w->points[i], total, dist);
+ r = VectorLength (dist);
+ if (r > bestr)
+ bestr = r;
+ }
+ VectorCopy (total, p->origin);
+ p->radius = bestr;
+}
+
+/*
+=============
+Winding_PlanesConcave
+=============
+*/
+#define WCONVEX_EPSILON 0.2
+
+int Winding_PlanesConcave(winding_t *w1, winding_t *w2,
+ vec3_t normal1, vec3_t normal2,
+ float dist1, float dist2)
+{
+ int i;
+
+ if (!w1 || !w2) return qfalse;
+
+ // check if one of the points of winding 1 is at the front of the plane of winding 2
+ for (i = 0; i < w1->numpoints; i++)
+ {
+ if (DotProduct(normal2, w1->points[i]) - dist2 > WCONVEX_EPSILON) return qtrue;
+ }
+ // check if one of the points of winding 2 is at the front of the plane of winding 1
+ for (i = 0; i < w2->numpoints; i++)
+ {
+ if (DotProduct(normal1, w2->points[i]) - dist1 > WCONVEX_EPSILON) return qtrue;
+ }
+
+ return qfalse;
+}
+
+/*
+============
+TryMergeLeaves
+============
+*/
+int TryMergeLeaves(int l1num, int l2num)
+{
+ int i, j, k, n, numportals;
+ plane_t plane1, plane2;
+ leaf_t *l1, *l2;
+ vportal_t *p1, *p2;
+ vportal_t *portals[MAX_PORTALS_ON_LEAF];
+
+ for (k = 0; k < 2; k++)
+ {
+ if (k) l1 = &leafs[l1num];
+ else l1 = &faceleafs[l1num];
+ for (i = 0; i < l1->numportals; i++)
+ {
+ p1 = l1->portals[i];
+ if (p1->leaf == l2num) continue;
+ for (n = 0; n < 2; n++)
+ {
+ if (n) l2 = &leafs[l2num];
+ else l2 = &faceleafs[l2num];
+ for (j = 0; j < l2->numportals; j++)
+ {
+ p2 = l2->portals[j];
+ if (p2->leaf == l1num) continue;
+ //
+ plane1 = p1->plane;
+ plane2 = p2->plane;
+ if (Winding_PlanesConcave(p1->winding, p2->winding, plane1.normal, plane2.normal, plane1.dist, plane2.dist))
+ return qfalse;
+ }
+ }
+ }
+ }
+ for (k = 0; k < 2; k++)
+ {
+ if (k)
+ {
+ l1 = &leafs[l1num];
+ l2 = &leafs[l2num];
+ }
+ else
+ {
+ l1 = &faceleafs[l1num];
+ l2 = &faceleafs[l2num];
+ }
+ numportals = 0;
+ //the leaves can be merged now
+ for (i = 0; i < l1->numportals; i++)
+ {
+ p1 = l1->portals[i];
+ if (p1->leaf == l2num)
+ {
+ p1->removed = qtrue;
+ continue;
+ }
+ portals[numportals++] = p1;
+ }
+ for (j = 0; j < l2->numportals; j++)
+ {
+ p2 = l2->portals[j];
+ if (p2->leaf == l1num)
+ {
+ p2->removed = qtrue;
+ continue;
+ }
+ portals[numportals++] = p2;
+ }
+ for (i = 0; i < numportals; i++)
+ {
+ l2->portals[i] = portals[i];
+ }
+ l2->numportals = numportals;
+ l1->merged = l2num;
+ }
+ return qtrue;
+}
+
+/*
+============
+UpdatePortals
+============
+*/
+void UpdatePortals(void)
+{
+ int i;
+ vportal_t *p;
+
+ for (i = 0; i < numportals * 2; i++)
+ {
+ p = &portals[i];
+ if (p->removed)
+ continue;
+ while(leafs[p->leaf].merged >= 0)
+ p->leaf = leafs[p->leaf].merged;
+ }
+}
+
+/*
+============
+MergeLeaves
+
+try to merge leaves but don't merge through hint splitters
+============
+*/
+void MergeLeaves(void)
+{
+ int i, j, nummerges, totalnummerges;
+ leaf_t *leaf;
+ vportal_t *p;
+
+ totalnummerges = 0;
+ do
+ {
+ nummerges = 0;
+ for (i = 0; i < portalclusters; i++)
+ {
+ leaf = &leafs[i];
+ //if this leaf is merged already
+ if (leaf->merged >= 0)
+ continue;
+ //
+ for (j = 0; j < leaf->numportals; j++)
+ {
+ p = leaf->portals[j];
+ //
+ if (p->removed)
+ continue;
+ //never merge through hint portals
+ if (p->hint)
+ continue;
+ if (TryMergeLeaves(i, p->leaf))
+ {
+ UpdatePortals();
+ nummerges++;
+ break;
+ }
+ }
+ }
+ totalnummerges += nummerges;
+ } while (nummerges);
+ _printf("%6d leaves merged\n", totalnummerges);
+}
+
+/*
+============
+TryMergeWinding
+============
+*/
+#define CONTINUOUS_EPSILON 0.005
+
+winding_t *TryMergeWinding (winding_t *f1, winding_t *f2, vec3_t planenormal)
+{
+ vec_t *p1, *p2, *p3, *p4, *back;
+ winding_t *newf;
+ int i, j, k, l;
+ vec3_t normal, delta;
+ vec_t dot;
+ qboolean keep1, keep2;
+
+
+ //
+ // find a common edge
+ //
+ p1 = p2 = NULL; // stop compiler warning
+ j = 0; //
+
+ for (i = 0; i < f1->numpoints; i++)
+ {
+ p1 = f1->points[i];
+ p2 = f1->points[(i+1) % f1->numpoints];
+ for (j = 0; j < f2->numpoints; j++)
+ {
+ p3 = f2->points[j];
+ p4 = f2->points[(j+1) % f2->numpoints];
+ for (k = 0; k < 3; k++)
+ {
+ if (fabs(p1[k] - p4[k]) > 0.1)//EQUAL_EPSILON) //ME
+ break;
+ if (fabs(p2[k] - p3[k]) > 0.1)//EQUAL_EPSILON) //ME
+ break;
+ } //end for
+ if (k==3)
+ break;
+ } //end for
+ if (j < f2->numpoints)
+ break;
+ } //end for
+
+ if (i == f1->numpoints)
+ return NULL; // no matching edges
+
+ //
+ // check slope of connected lines
+ // if the slopes are colinear, the point can be removed
+ //
+ back = f1->points[(i+f1->numpoints-1)%f1->numpoints];
+ VectorSubtract (p1, back, delta);
+ CrossProduct (planenormal, delta, normal);
+ VectorNormalize (normal, normal);
+
+ back = f2->points[(j+2)%f2->numpoints];
+ VectorSubtract (back, p1, delta);
+ dot = DotProduct (delta, normal);
+ if (dot > CONTINUOUS_EPSILON)
+ return NULL; // not a convex polygon
+ keep1 = (qboolean)(dot < -CONTINUOUS_EPSILON);
+
+ back = f1->points[(i+2)%f1->numpoints];
+ VectorSubtract (back, p2, delta);
+ CrossProduct (planenormal, delta, normal);
+ VectorNormalize (normal, normal);
+
+ back = f2->points[(j+f2->numpoints-1)%f2->numpoints];
+ VectorSubtract (back, p2, delta);
+ dot = DotProduct (delta, normal);
+ if (dot > CONTINUOUS_EPSILON)
+ return NULL; // not a convex polygon
+ keep2 = (qboolean)(dot < -CONTINUOUS_EPSILON);
+
+ //
+ // build the new polygon
+ //
+ newf = NewWinding (f1->numpoints + f2->numpoints);
+
+ // copy first polygon
+ for (k=(i+1)%f1->numpoints ; k != i ; k=(k+1)%f1->numpoints)
+ {
+ if (k==(i+1)%f1->numpoints && !keep2)
+ continue;
+
+ VectorCopy (f1->points[k], newf->points[newf->numpoints]);
+ newf->numpoints++;
+ }
+
+ // copy second polygon
+ for (l= (j+1)%f2->numpoints ; l != j ; l=(l+1)%f2->numpoints)
+ {
+ if (l==(j+1)%f2->numpoints && !keep1)
+ continue;
+ VectorCopy (f2->points[l], newf->points[newf->numpoints]);
+ newf->numpoints++;
+ }
+
+ return newf;
+}
+
+/*
+============
+MergeLeafPortals
+============
+*/
+void MergeLeafPortals(void)
+{
+ int i, j, k, nummerges, hintsmerged;
+ leaf_t *leaf;
+ vportal_t *p1, *p2;
+ winding_t *w;
+
+ nummerges = 0;
+ hintsmerged = 0;
+ for (i = 0; i < portalclusters; i++)
+ {
+ leaf = &leafs[i];
+ if (leaf->merged >= 0) continue;
+ for (j = 0; j < leaf->numportals; j++)
+ {
+ p1 = leaf->portals[j];
+ if (p1->removed)
+ continue;
+ for (k = j+1; k < leaf->numportals; k++)
+ {
+ p2 = leaf->portals[k];
+ if (p2->removed)
+ continue;
+ if (p1->leaf == p2->leaf)
+ {
+ w = TryMergeWinding(p1->winding, p2->winding, p1->plane.normal);
+ if (w)
+ {
+ FreeWinding(p1->winding);
+ p1->winding = w;
+ if (p1->hint && p2->hint)
+ hintsmerged++;
+ p1->hint |= p2->hint;
+ SetPortalSphere(p1);
+ p2->removed = qtrue;
+ nummerges++;
+ i--;
+ break;
+ }
+ }
+ }
+ if (k < leaf->numportals)
+ break;
+ }
+ }
+ _printf("%6d portals merged\n", nummerges);
+ _printf("%6d hint portals merged\n", hintsmerged);
+}
+
+
+/*
+============
+WritePortals
+============
+*/
+int CountActivePortals(void)
+{
+ int num, hints, j;
+ vportal_t *p;
+
+ num = 0;
+ hints = 0;
+ for (j = 0; j < numportals * 2; j++)
+ {
+ p = portals + j;
+ if (p->removed)
+ continue;
+ if (p->hint)
+ hints++;
+ num++;
+ }
+ _printf("%6d active portals\n", num);
+ _printf("%6d hint portals\n", hints);
+ return num;
+}
+
+/*
+============
+WritePortals
+============
+*/
+void WriteFloat (FILE *f, vec_t v);
+
+void WritePortals(char *filename)
+{
+ int i, j, num;
+ FILE *pf;
+ vportal_t *p;
+ winding_t *w;
+
+ // write the file
+ pf = fopen (filename, "w");
+ if (!pf)
+ Error ("Error opening %s", filename);
+
+ num = 0;
+ for (j = 0; j < numportals * 2; j++)
+ {
+ p = portals + j;
+ if (p->removed)
+ continue;
+// if (!p->hint)
+// continue;
+ num++;
+ }
+
+ fprintf (pf, "%s\n", PORTALFILE);
+ fprintf (pf, "%i\n", 0);
+ fprintf (pf, "%i\n", num);// + numfaces);
+ fprintf (pf, "%i\n", 0);
+
+ for (j = 0; j < numportals * 2; j++)
+ {
+ p = portals + j;
+ if (p->removed)
+ continue;
+// if (!p->hint)
+// continue;
+ w = p->winding;
+ fprintf (pf,"%i %i %i ",w->numpoints, 0, 0);
+ fprintf (pf, "%d ", p->hint);
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ fprintf (pf,"(");
+ WriteFloat (pf, w->points[i][0]);
+ WriteFloat (pf, w->points[i][1]);
+ WriteFloat (pf, w->points[i][2]);
+ fprintf (pf,") ");
+ }
+ fprintf (pf,"\n");
+ }
+
+ /*
+ for (j = 0; j < numfaces; j++)
+ {
+ p = faces + j;
+ w = p->winding;
+ fprintf (pf,"%i %i %i ",w->numpoints, 0, 0);
+ fprintf (pf, "0 ");
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ fprintf (pf,"(");
+ WriteFloat (pf, w->points[i][0]);
+ WriteFloat (pf, w->points[i][1]);
+ WriteFloat (pf, w->points[i][2]);
+ fprintf (pf,") ");
+ }
+ fprintf (pf,"\n");
+ }*/
+
+ fclose (pf);
+}
+
+/*
+============
+LoadPortals
+============
+*/
+void LoadPortals (char *name)
+{
+ int i, j, hint;
+ vportal_t *p;
+ leaf_t *l;
+ char magic[80];
+ FILE *f;
+ int numpoints;
+ winding_t *w;
+ int leafnums[2];
+ plane_t plane;
+
+ if (!strcmp(name,"-"))
+ f = stdin;
+ else
+ {
+ f = fopen(name, "r");
+ if (!f)
+ Error ("LoadPortals: couldn't read %s\n",name);
+ }
+
+ if (fscanf (f,"%79s\n%i\n%i\n%i\n",magic, &portalclusters, &numportals, &numfaces) != 4)
+ Error ("LoadPortals: failed to read header");
+ if (strcmp(magic,PORTALFILE))
+ Error ("LoadPortals: not a portal file");
+
+ _printf ("%6i portalclusters\n", portalclusters);
+ _printf ("%6i numportals\n", numportals);
+ _printf ("%6i numfaces\n", numfaces);
+
+ // these counts should take advantage of 64 bit systems automatically
+ leafbytes = ((portalclusters+63)&~63)>>3;
+ leaflongs = leafbytes/sizeof(long);
+
+ portalbytes = ((numportals*2+63)&~63)>>3;
+ portallongs = portalbytes/sizeof(long);
+
+ // each file portal is split into two memory portals
+ portals = malloc(2*numportals*sizeof(vportal_t));
+ memset (portals, 0, 2*numportals*sizeof(vportal_t));
+
+ leafs = malloc(portalclusters*sizeof(leaf_t));
+ memset (leafs, 0, portalclusters*sizeof(leaf_t));
+
+ for (i = 0; i < portalclusters; i++)
+ leafs[i].merged = -1;
+
+ numVisBytes = VIS_HEADER_SIZE + portalclusters*leafbytes;
+
+ ((int *)visBytes)[0] = portalclusters;
+ ((int *)visBytes)[1] = leafbytes;
+
+ for (i=0, p=portals ; i<numportals ; i++)
+ {
+ if (fscanf (f, "%i %i %i ", &numpoints, &leafnums[0], &leafnums[1]) != 3)
+ Error ("LoadPortals: reading portal %i", i);
+ if (numpoints > MAX_POINTS_ON_WINDING)
+ Error ("LoadPortals: portal %i has too many points", i);
+ if ( (unsigned)leafnums[0] > portalclusters
+ || (unsigned)leafnums[1] > portalclusters)
+ Error ("LoadPortals: reading portal %i", i);
+ if (fscanf (f, "%i ", &hint) != 1)
+ Error ("LoadPortals: reading hint state");
+
+ w = p->winding = NewWinding (numpoints);
+ w->numpoints = numpoints;
+
+ for (j=0 ; j<numpoints ; j++)
+ {
+ double v[3];
+ int k;
+
+ // scanf into double, then assign to vec_t
+ // so we don't care what size vec_t is
+ if (fscanf (f, "(%lf %lf %lf ) "
+ , &v[0], &v[1], &v[2]) != 3)
+ Error ("LoadPortals: reading portal %i", i);
+ for (k=0 ; k<3 ; k++)
+ w->points[j][k] = v[k];
+ }
+ fscanf (f, "\n");
+
+ // calc plane
+ PlaneFromWinding (w, &plane);
+
+ // create forward portal
+ l = &leafs[leafnums[0]];
+ if (l->numportals == MAX_PORTALS_ON_LEAF)
+ Error ("Leaf with too many portals");
+ l->portals[l->numportals] = p;
+ l->numportals++;
+
+ p->num = i+1;
+ p->hint = hint;
+ p->winding = w;
+ VectorSubtract (vec3_origin, plane.normal, p->plane.normal);
+ p->plane.dist = -plane.dist;
+ p->leaf = leafnums[1];
+ SetPortalSphere (p);
+ p++;
+
+ // create backwards portal
+ l = &leafs[leafnums[1]];
+ if (l->numportals == MAX_PORTALS_ON_LEAF)
+ Error ("Leaf with too many portals");
+ l->portals[l->numportals] = p;
+ l->numportals++;
+
+ p->num = i+1;
+ p->hint = hint;
+ p->winding = NewWinding(w->numpoints);
+ p->winding->numpoints = w->numpoints;
+ for (j=0 ; j<w->numpoints ; j++)
+ {
+ VectorCopy (w->points[w->numpoints-1-j], p->winding->points[j]);
+ }
+
+ p->plane = plane;
+ p->leaf = leafnums[0];
+ SetPortalSphere (p);
+ p++;
+
+ }
+
+ faces = malloc(2*numfaces*sizeof(vportal_t));
+ memset (faces, 0, 2*numfaces*sizeof(vportal_t));
+
+ faceleafs = malloc(portalclusters*sizeof(leaf_t));
+ memset(faceleafs, 0, portalclusters*sizeof(leaf_t));
+
+ for (i = 0, p = faces; i < numfaces; i++)
+ {
+ if (fscanf (f, "%i %i ", &numpoints, &leafnums[0]) != 2)
+ Error ("LoadPortals: reading portal %i", i);
+
+ w = p->winding = NewWinding (numpoints);
+ w->numpoints = numpoints;
+
+ for (j=0 ; j<numpoints ; j++)
+ {
+ double v[3];
+ int k;
+
+ // scanf into double, then assign to vec_t
+ // so we don't care what size vec_t is
+ if (fscanf (f, "(%lf %lf %lf ) "
+ , &v[0], &v[1], &v[2]) != 3)
+ Error ("LoadPortals: reading portal %i", i);
+ for (k=0 ; k<3 ; k++)
+ w->points[j][k] = v[k];
+ }
+ fscanf (f, "\n");
+
+ // calc plane
+ PlaneFromWinding (w, &plane);
+
+ l = &faceleafs[leafnums[0]];
+ l->merged = -1;
+ if (l->numportals == MAX_PORTALS_ON_LEAF)
+ Error ("Leaf with too many faces");
+ l->portals[l->numportals] = p;
+ l->numportals++;
+
+ p->num = i+1;
+ p->winding = w;
+ // normal pointing out of the leaf
+ VectorSubtract (vec3_origin, plane.normal, p->plane.normal);
+ p->plane.dist = -plane.dist;
+ p->leaf = -1;
+ SetPortalSphere (p);
+ p++;
+ }
+
+ fclose (f);
+}
+
+
+/*
+================
+CalcPHS
+
+Calculate the PHS (Potentially Hearable Set)
+by ORing together all the PVS visible from a leaf
+================
+*/
+void CalcPHS (void)
+{
+ int i, j, k, l, index;
+ int bitbyte;
+ long *dest, *src;
+ byte *scan;
+ int count;
+ byte uncompressed[MAX_MAP_LEAFS/8];
+
+ _printf ("Building PHS...\n");
+
+ count = 0;
+ for (i=0 ; i<portalclusters ; i++)
+ {
+ scan = visBytes + i*leafbytes;
+ memcpy (uncompressed, scan, leafbytes);
+ for (j=0 ; j<leafbytes ; j++)
+ {
+ bitbyte = scan[j];
+ if (!bitbyte)
+ continue;
+ for (k=0 ; k<8 ; k++)
+ {
+ if (! (bitbyte & (1<<k)) )
+ continue;
+ // OR this pvs row into the phs
+ index = ((j<<3)+k);
+ if (index >= portalclusters)
+ Error ("Bad bit in PVS"); // pad bits should be 0
+ src = (long *)(visBytes + index*leafbytes);
+ dest = (long *)uncompressed;
+ for (l=0 ; l<leaflongs ; l++)
+ ((long *)uncompressed)[l] |= src[l];
+ }
+ }
+ for (j=0 ; j<portalclusters ; j++)
+ if (uncompressed[j>>3] & (1<<(j&7)) )
+ count++;
+
+ // FIXME: copy it off
+ }
+
+ _printf ("Average clusters hearable: %i\n", count/portalclusters);
+}
+
+/*
+===========
+VisMain
+===========
+*/
+int VisMain (int argc, char **argv)
+{
+ char portalfile[1024];
+ char name[1024];
+ int i;
+ double start, end;
+
+ _printf ("---- vis ----\n");
+
+ verbose = qfalse;
+ for (i=1 ; i<argc ; i++) {
+ if (!strcmp(argv[i],"-threads")) {
+ numthreads = atoi (argv[i+1]);
+ i++;
+ } else if (!strcmp(argv[i],"-threads")) {
+ numthreads = atoi (argv[i+1]);
+ i++;
+ } else if (!strcmp(argv[i], "-fast")) {
+ _printf ("fastvis = true\n");
+ fastvis = qtrue;
+ } else if (!strcmp(argv[i], "-merge")) {
+ _printf ("merge = true\n");
+ mergevis = qtrue;
+ } else if (!strcmp(argv[i], "-nopassage")) {
+ _printf ("nopassage = true\n");
+ noPassageVis = qtrue;
+ } else if (!strcmp(argv[i], "-passageOnly")) {
+ _printf("passageOnly = true\n");
+ passageVisOnly = qtrue;
+ } else if (!strcmp(argv[i], "-level")) {
+ testlevel = atoi(argv[i+1]);
+ _printf ("testlevel = %i\n", testlevel);
+ i++;
+ } else if (!strcmp(argv[i], "-v")) {
+ _printf ("verbose = true\n");
+ verbose = qtrue;
+ } else if (!strcmp (argv[i],"-nosort")) {
+ _printf ("nosort = true\n");
+ nosort = qtrue;
+ } else if (!strcmp (argv[i],"-saveprt")) {
+ _printf ("saveprt = true\n");
+ saveprt = qtrue;
+ } else if (!strcmp (argv[i],"-tmpin")) {
+ strcpy (inbase, "/tmp");
+ } else if (!strcmp (argv[i],"-tmpout")) {
+ strcpy (outbase, "/tmp");
+ } else if (argv[i][0] == '-') {
+ Error ("Unknown option \"%s\"", argv[i]);
+ } else {
+ break;
+ }
+ }
+
+ if (i != argc - 1)
+ Error ("usage: vis [-threads #] [-level 0-4] [-fast] [-v] bspfile");
+
+#ifdef MREDEBUG
+ start = clock();
+#else
+ start = I_FloatTime ();
+#endif
+
+ ThreadSetDefault ();
+
+ SetQdirFromPath (argv[i]);
+
+#ifdef _WIN32
+ InitPakFile(gamedir, NULL);
+#endif
+
+ // load the bsp
+ sprintf (name, "%s%s", inbase, ExpandArg(argv[i]));
+ StripExtension (name);
+ strcat (name, ".bsp");
+ _printf ("reading %s\n", name);
+ LoadBSPFile (name);
+
+ // load the portal file
+ sprintf (portalfile, "%s%s", inbase, ExpandArg(argv[i]));
+ StripExtension (portalfile);
+ strcat (portalfile, ".prt");
+ _printf ("reading %s\n", portalfile);
+ LoadPortals (portalfile);
+
+ if (mergevis)
+ {
+ MergeLeaves();
+ MergeLeafPortals();
+ }
+
+ CountActivePortals();
+// WritePortals("maps/hints.prs");
+
+ _printf ("visdatasize:%i\n", numVisBytes);
+
+ CalcVis ();
+
+// CalcPHS ();
+
+ // delete the prt file
+ if ( !saveprt ) {
+ remove( portalfile );
+ }
+
+ // write the bsp file
+ _printf ("writing %s\n", name);
+ WriteBSPFile (name);
+
+#ifdef MREDEBUG
+ end = clock();
+ _printf ("%5.2f seconds elapsed\n", (end-start) / CLK_TCK);
+#else
+ end = I_FloatTime ();
+ _printf ("%5.2f seconds elapsed\n", end-start);
+#endif
+ return 0;
+}
+
diff --git a/q3map/vis.h b/q3map/vis.h
new file mode 100755
index 0000000..e607184
--- /dev/null
+++ b/q3map/vis.h
@@ -0,0 +1,162 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// vis.h
+
+#include "cmdlib.h"
+#include "mathlib.h"
+#include "bspfile.h"
+
+#define MAX_PORTALS 32768
+
+#define PORTALFILE "PRT1"
+
+#define ON_EPSILON 0.1
+
+//#define MREDEBUG
+
+// seperator caching helps a bit
+#define SEPERATORCACHE
+
+// can't have more seperators than the max number of points on a winding
+#define MAX_SEPERATORS 64
+
+typedef struct
+{
+ vec3_t normal;
+ float dist;
+} plane_t;
+
+#define MAX_POINTS_ON_WINDING 64
+#define MAX_POINTS_ON_FIXED_WINDING 12
+
+typedef struct
+{
+ int numpoints;
+ vec3_t points[MAX_POINTS_ON_FIXED_WINDING]; // variable sized
+} winding_t;
+
+winding_t *NewWinding (int points);
+void FreeWinding (winding_t *w);
+winding_t *CopyWinding (winding_t *w);
+
+
+typedef struct passage_s
+{
+ struct passage_s *next;
+ byte cansee[1]; //all portals that can be seen through this passage
+} passage_t;
+
+typedef enum {stat_none, stat_working, stat_done} vstatus_t;
+typedef struct
+{
+ int num;
+ qboolean hint; // true if this portal was created from a hint splitter
+ qboolean removed;
+ plane_t plane; // normal pointing into neighbor
+ int leaf; // neighbor
+
+ vec3_t origin; // for fast clip testing
+ float radius;
+
+ winding_t *winding;
+ vstatus_t status;
+ byte *portalfront; // [portals], preliminary
+ byte *portalflood; // [portals], intermediate
+ byte *portalvis; // [portals], final
+
+ int nummightsee; // bit count on portalflood for sort
+ passage_t *passages; // there are just as many passages as there
+ // are portals in the leaf this portal leads to
+} vportal_t;
+
+#define MAX_PORTALS_ON_LEAF 128
+typedef struct leaf_s
+{
+ int numportals;
+ int merged;
+ vportal_t *portals[MAX_PORTALS_ON_LEAF];
+} leaf_t;
+
+
+typedef struct pstack_s
+{
+ byte mightsee[MAX_PORTALS/8]; // bit string
+ struct pstack_s *next;
+ leaf_t *leaf;
+ vportal_t *portal; // portal exiting
+ winding_t *source;
+ winding_t *pass;
+
+ winding_t windings[3]; // source, pass, temp in any order
+ int freewindings[3];
+
+ plane_t portalplane;
+ int depth;
+#ifdef SEPERATORCACHE
+ plane_t seperators[2][MAX_SEPERATORS];
+ int numseperators[2];
+#endif
+} pstack_t;
+
+typedef struct
+{
+ vportal_t *base;
+ int c_chains;
+ pstack_t pstack_head;
+} threaddata_t;
+
+
+
+extern int numportals;
+extern int portalclusters;
+
+extern vportal_t *portals;
+extern leaf_t *leafs;
+
+extern int c_portaltest, c_portalpass, c_portalcheck;
+extern int c_portalskip, c_leafskip;
+extern int c_vistest, c_mighttest;
+extern int c_chains;
+
+extern byte *vismap, *vismap_p, *vismap_end; // past visfile
+
+extern int testlevel;
+
+extern byte *uncompressed;
+
+extern int leafbytes, leaflongs;
+extern int portalbytes, portallongs;
+
+
+void LeafFlow (int leafnum);
+
+
+void BasePortalVis(int portalnum);
+void BetterPortalVis(int portalnum);
+void PortalFlow(int portalnum);
+void PassagePortalFlow(int portalnum);
+void CreatePassages(int portalnum);
+void PassageFlow(int portalnum);
+
+extern vportal_t *sorted_portals[MAX_MAP_PORTALS*2];
+
+int CountBits (byte *bits, int numbits);
diff --git a/q3map/visflow.c b/q3map/visflow.c
new file mode 100755
index 0000000..c62a33b
--- /dev/null
+++ b/q3map/visflow.c
@@ -0,0 +1,1657 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "vis.h"
+
+/*
+
+ each portal will have a list of all possible to see from first portal
+
+ if (!thread->portalmightsee[portalnum])
+
+ portal mightsee
+
+ for p2 = all other portals in leaf
+ get sperating planes
+ for all portals that might be seen by p2
+ mark as unseen if not present in seperating plane
+ flood fill a new mightsee
+ save as passagemightsee
+
+
+ void CalcMightSee (leaf_t *leaf,
+*/
+
+int CountBits (byte *bits, int numbits)
+{
+ int i;
+ int c;
+
+ c = 0;
+ for (i=0 ; i<numbits ; i++)
+ if (bits[i>>3] & (1<<(i&7)) )
+ c++;
+
+ return c;
+}
+
+int c_fullskip;
+int c_portalskip, c_leafskip;
+int c_vistest, c_mighttest;
+
+int c_chop, c_nochop;
+
+int active;
+
+void CheckStack (leaf_t *leaf, threaddata_t *thread)
+{
+ pstack_t *p, *p2;
+
+ for (p=thread->pstack_head.next ; p ; p=p->next)
+ {
+// _printf ("=");
+ if (p->leaf == leaf)
+ Error ("CheckStack: leaf recursion");
+ for (p2=thread->pstack_head.next ; p2 != p ; p2=p2->next)
+ if (p2->leaf == p->leaf)
+ Error ("CheckStack: late leaf recursion");
+ }
+// _printf ("\n");
+}
+
+
+winding_t *AllocStackWinding (pstack_t *stack)
+{
+ int i;
+
+ for (i=0 ; i<3 ; i++)
+ {
+ if (stack->freewindings[i])
+ {
+ stack->freewindings[i] = 0;
+ return &stack->windings[i];
+ }
+ }
+
+ Error ("AllocStackWinding: failed");
+
+ return NULL;
+}
+
+void FreeStackWinding (winding_t *w, pstack_t *stack)
+{
+ int i;
+
+ i = w - stack->windings;
+
+ if (i<0 || i>2)
+ return; // not from local
+
+ if (stack->freewindings[i])
+ Error ("FreeStackWinding: allready free");
+ stack->freewindings[i] = 1;
+}
+
+/*
+==============
+VisChopWinding
+
+==============
+*/
+winding_t *VisChopWinding (winding_t *in, pstack_t *stack, plane_t *split)
+{
+ vec_t dists[128];
+ int sides[128];
+ int counts[3];
+ vec_t dot;
+ int i, j;
+ vec_t *p1, *p2;
+ vec3_t mid;
+ winding_t *neww;
+
+ counts[0] = counts[1] = counts[2] = 0;
+
+ // determine sides for each point
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ dot = DotProduct (in->points[i], split->normal);
+ dot -= split->dist;
+ dists[i] = dot;
+ if (dot > ON_EPSILON)
+ sides[i] = SIDE_FRONT;
+ else if (dot < -ON_EPSILON)
+ sides[i] = SIDE_BACK;
+ else
+ {
+ sides[i] = SIDE_ON;
+ }
+ counts[sides[i]]++;
+ }
+
+ if (!counts[1])
+ return in; // completely on front side
+
+ if (!counts[0])
+ {
+ FreeStackWinding (in, stack);
+ return NULL;
+ }
+
+ sides[i] = sides[0];
+ dists[i] = dists[0];
+
+ neww = AllocStackWinding (stack);
+
+ neww->numpoints = 0;
+
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ p1 = in->points[i];
+
+ if (neww->numpoints == MAX_POINTS_ON_FIXED_WINDING)
+ {
+ FreeStackWinding (neww, stack);
+ return in; // can't chop -- fall back to original
+ }
+
+ if (sides[i] == SIDE_ON)
+ {
+ VectorCopy (p1, neww->points[neww->numpoints]);
+ neww->numpoints++;
+ continue;
+ }
+
+ if (sides[i] == SIDE_FRONT)
+ {
+ VectorCopy (p1, neww->points[neww->numpoints]);
+ neww->numpoints++;
+ }
+
+ if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i])
+ continue;
+
+ if (neww->numpoints == MAX_POINTS_ON_FIXED_WINDING)
+ {
+ FreeStackWinding (neww, stack);
+ return in; // can't chop -- fall back to original
+ }
+
+ // generate a split point
+ p2 = in->points[(i+1)%in->numpoints];
+
+ dot = dists[i] / (dists[i]-dists[i+1]);
+ for (j=0 ; j<3 ; j++)
+ { // avoid round off error when possible
+ if (split->normal[j] == 1)
+ mid[j] = split->dist;
+ else if (split->normal[j] == -1)
+ mid[j] = -split->dist;
+ else
+ mid[j] = p1[j] + dot*(p2[j]-p1[j]);
+ }
+
+ VectorCopy (mid, neww->points[neww->numpoints]);
+ neww->numpoints++;
+ }
+
+ // free the original winding
+ FreeStackWinding (in, stack);
+
+ return neww;
+}
+
+/*
+==============
+ClipToSeperators
+
+Source, pass, and target are an ordering of portals.
+
+Generates seperating planes canidates by taking two points from source and one
+point from pass, and clips target by them.
+
+If target is totally clipped away, that portal can not be seen through.
+
+Normal clip keeps target on the same side as pass, which is correct if the
+order goes source, pass, target. If the order goes pass, source, target then
+flipclip should be set.
+==============
+*/
+winding_t *ClipToSeperators (winding_t *source, winding_t *pass, winding_t *target, qboolean flipclip, pstack_t *stack)
+{
+ int i, j, k, l;
+ plane_t plane;
+ vec3_t v1, v2;
+ float d;
+ vec_t length;
+ int counts[3];
+ qboolean fliptest;
+
+ // check all combinations
+ for (i=0 ; i<source->numpoints ; i++)
+ {
+ l = (i+1)%source->numpoints;
+ VectorSubtract (source->points[l] , source->points[i], v1);
+
+ // find a vertex of pass that makes a plane that puts all of the
+ // vertexes of pass on the front side and all of the vertexes of
+ // source on the back side
+ for (j=0 ; j<pass->numpoints ; j++)
+ {
+ VectorSubtract (pass->points[j], source->points[i], v2);
+
+ plane.normal[0] = v1[1]*v2[2] - v1[2]*v2[1];
+ plane.normal[1] = v1[2]*v2[0] - v1[0]*v2[2];
+ plane.normal[2] = v1[0]*v2[1] - v1[1]*v2[0];
+
+ // if points don't make a valid plane, skip it
+
+ length = plane.normal[0] * plane.normal[0]
+ + plane.normal[1] * plane.normal[1]
+ + plane.normal[2] * plane.normal[2];
+
+ if (length < ON_EPSILON)
+ continue;
+
+ length = 1/sqrt(length);
+
+ plane.normal[0] *= length;
+ plane.normal[1] *= length;
+ plane.normal[2] *= length;
+
+ plane.dist = DotProduct (pass->points[j], plane.normal);
+
+ //
+ // find out which side of the generated seperating plane has the
+ // source portal
+ //
+#if 1
+ fliptest = qfalse;
+ for (k=0 ; k<source->numpoints ; k++)
+ {
+ if (k == i || k == l)
+ continue;
+ d = DotProduct (source->points[k], plane.normal) - plane.dist;
+ if (d < -ON_EPSILON)
+ { // source is on the negative side, so we want all
+ // pass and target on the positive side
+ fliptest = qfalse;
+ break;
+ }
+ else if (d > ON_EPSILON)
+ { // source is on the positive side, so we want all
+ // pass and target on the negative side
+ fliptest = qtrue;
+ break;
+ }
+ }
+ if (k == source->numpoints)
+ continue; // planar with source portal
+#else
+ fliptest = flipclip;
+#endif
+ //
+ // flip the normal if the source portal is backwards
+ //
+ if (fliptest)
+ {
+ VectorSubtract (vec3_origin, plane.normal, plane.normal);
+ plane.dist = -plane.dist;
+ }
+#if 1
+ //
+ // if all of the pass portal points are now on the positive side,
+ // this is the seperating plane
+ //
+ counts[0] = counts[1] = counts[2] = 0;
+ for (k=0 ; k<pass->numpoints ; k++)
+ {
+ if (k==j)
+ continue;
+ d = DotProduct (pass->points[k], plane.normal) - plane.dist;
+ if (d < -ON_EPSILON)
+ break;
+ else if (d > ON_EPSILON)
+ counts[0]++;
+ else
+ counts[2]++;
+ }
+ if (k != pass->numpoints)
+ continue; // points on negative side, not a seperating plane
+
+ if (!counts[0])
+ continue; // planar with seperating plane
+#else
+ k = (j+1)%pass->numpoints;
+ d = DotProduct (pass->points[k], plane.normal) - plane.dist;
+ if (d < -ON_EPSILON)
+ continue;
+ k = (j+pass->numpoints-1)%pass->numpoints;
+ d = DotProduct (pass->points[k], plane.normal) - plane.dist;
+ if (d < -ON_EPSILON)
+ continue;
+#endif
+ //
+ // flip the normal if we want the back side
+ //
+ if (flipclip)
+ {
+ VectorSubtract (vec3_origin, plane.normal, plane.normal);
+ plane.dist = -plane.dist;
+ }
+
+#ifdef SEPERATORCACHE
+ stack->seperators[flipclip][stack->numseperators[flipclip]] = plane;
+ if (++stack->numseperators[flipclip] >= MAX_SEPERATORS)
+ Error("MAX_SEPERATORS");
+#endif
+ //MrE: fast check first
+ d = DotProduct (stack->portal->origin, plane.normal) - plane.dist;
+ //if completely at the back of the seperator plane
+ if (d < -stack->portal->radius)
+ return NULL;
+ //if completely on the front of the seperator plane
+ if (d > stack->portal->radius)
+ break;
+
+ //
+ // clip target by the seperating plane
+ //
+ target = VisChopWinding (target, stack, &plane);
+ if (!target)
+ return NULL; // target is not visible
+
+ break; // optimization by Antony Suter
+ }
+ }
+
+ return target;
+}
+
+/*
+==================
+RecursiveLeafFlow
+
+Flood fill through the leafs
+If src_portal is NULL, this is the originating leaf
+==================
+*/
+void RecursiveLeafFlow (int leafnum, threaddata_t *thread, pstack_t *prevstack)
+{
+ pstack_t stack;
+ vportal_t *p;
+ plane_t backplane;
+ leaf_t *leaf;
+ int i, j, n;
+ long *test, *might, *prevmight, *vis, more;
+ int pnum;
+
+ thread->c_chains++;
+
+ leaf = &leafs[leafnum];
+// CheckStack (leaf, thread);
+
+ prevstack->next = &stack;
+
+ stack.next = NULL;
+ stack.leaf = leaf;
+ stack.portal = NULL;
+ stack.depth = prevstack->depth + 1;
+
+#ifdef SEPERATORCACHE
+ stack.numseperators[0] = 0;
+ stack.numseperators[1] = 0;
+#endif
+
+ might = (long *)stack.mightsee;
+ vis = (long *)thread->base->portalvis;
+
+ // check all portals for flowing into other leafs
+ for (i = 0; i < leaf->numportals; i++)
+ {
+ p = leaf->portals[i];
+ if (p->removed)
+ continue;
+ pnum = p - portals;
+
+ /* MrE: portal trace debug code
+ {
+ int portaltrace[] = {13, 16, 17, 37};
+ pstack_t *s;
+
+ s = &thread->pstack_head;
+ for (j = 0; s->next && j < sizeof(portaltrace)/sizeof(int) - 1; j++, s = s->next)
+ {
+ if (s->portal->num != portaltrace[j])
+ break;
+ }
+ if (j >= sizeof(portaltrace)/sizeof(int) - 1)
+ {
+ if (p->num == portaltrace[j])
+ n = 0; //traced through all the portals
+ }
+ }
+ */
+
+ if ( ! (prevstack->mightsee[pnum >> 3] & (1<<(pnum&7)) ) )
+ {
+ continue; // can't possibly see it
+ }
+
+ // if the portal can't see anything we haven't allready seen, skip it
+ if (p->status == stat_done)
+ {
+ test = (long *)p->portalvis;
+ }
+ else
+ {
+ test = (long *)p->portalflood;
+ }
+
+ more = 0;
+ prevmight = (long *)prevstack->mightsee;
+ for (j=0 ; j<portallongs ; j++)
+ {
+ might[j] = prevmight[j] & test[j];
+ more |= (might[j] & ~vis[j]);
+ }
+
+ if (!more &&
+ (thread->base->portalvis[pnum>>3] & (1<<(pnum&7))) )
+ { // can't see anything new
+ continue;
+ }
+
+ // get plane of portal, point normal into the neighbor leaf
+ stack.portalplane = p->plane;
+ VectorSubtract (vec3_origin, p->plane.normal, backplane.normal);
+ backplane.dist = -p->plane.dist;
+
+// c_portalcheck++;
+
+ stack.portal = p;
+ stack.next = NULL;
+ stack.freewindings[0] = 1;
+ stack.freewindings[1] = 1;
+ stack.freewindings[2] = 1;
+
+#if 1
+ {
+ float d;
+
+ d = DotProduct (p->origin, thread->pstack_head.portalplane.normal);
+ d -= thread->pstack_head.portalplane.dist;
+ if (d < -p->radius)
+ {
+ continue;
+ }
+ else if (d > p->radius)
+ {
+ stack.pass = p->winding;
+ }
+ else
+ {
+ stack.pass = VisChopWinding (p->winding, &stack, &thread->pstack_head.portalplane);
+ if (!stack.pass)
+ continue;
+ }
+ }
+#else
+ stack.pass = VisChopWinding (p->winding, &stack, &thread->pstack_head.portalplane);
+ if (!stack.pass)
+ continue;
+#endif
+
+
+#if 1
+ {
+ float d;
+
+ d = DotProduct (thread->base->origin, p->plane.normal);
+ d -= p->plane.dist;
+ //MrE: vis-bug fix
+ //if (d > p->radius)
+ if (d > thread->base->radius)
+ {
+ continue;
+ }
+ //MrE: vis-bug fix
+ //if (d < -p->radius)
+ else if (d < -thread->base->radius)
+ {
+ stack.source = prevstack->source;
+ }
+ else
+ {
+ stack.source = VisChopWinding (prevstack->source, &stack, &backplane);
+ //FIXME: shouldn't we create a new source origin and radius for fast checks?
+ if (!stack.source)
+ continue;
+ }
+ }
+#else
+ stack.source = VisChopWinding (prevstack->source, &stack, &backplane);
+ if (!stack.source)
+ continue;
+#endif
+
+ if (!prevstack->pass)
+ { // the second leaf can only be blocked if coplanar
+
+ // mark the portal as visible
+ thread->base->portalvis[pnum>>3] |= (1<<(pnum&7));
+
+ RecursiveLeafFlow (p->leaf, thread, &stack);
+ continue;
+ }
+
+#ifdef SEPERATORCACHE
+ if (stack.numseperators[0])
+ {
+ for (n = 0; n < stack.numseperators[0]; n++)
+ {
+ stack.pass = VisChopWinding (stack.pass, &stack, &stack.seperators[0][n]);
+ if (!stack.pass)
+ break; // target is not visible
+ }
+ if (n < stack.numseperators[0])
+ continue;
+ }
+ else
+ {
+ stack.pass = ClipToSeperators (prevstack->source, prevstack->pass, stack.pass, qfalse, &stack);
+ }
+#else
+ stack.pass = ClipToSeperators (stack.source, prevstack->pass, stack.pass, qfalse, &stack);
+#endif
+ if (!stack.pass)
+ continue;
+
+#ifdef SEPERATORCACHE
+ if (stack.numseperators[1])
+ {
+ for (n = 0; n < stack.numseperators[1]; n++)
+ {
+ stack.pass = VisChopWinding (stack.pass, &stack, &stack.seperators[1][n]);
+ if (!stack.pass)
+ break; // target is not visible
+ }
+ }
+ else
+ {
+ stack.pass = ClipToSeperators (prevstack->pass, prevstack->source, stack.pass, qtrue, &stack);
+ }
+#else
+ stack.pass = ClipToSeperators (prevstack->pass, stack.source, stack.pass, qtrue, &stack);
+#endif
+ if (!stack.pass)
+ continue;
+
+ // mark the portal as visible
+ thread->base->portalvis[pnum>>3] |= (1<<(pnum&7));
+
+ // flow through it for real
+ RecursiveLeafFlow (p->leaf, thread, &stack);
+ //
+ stack.next = NULL;
+ }
+}
+
+/*
+===============
+PortalFlow
+
+generates the portalvis bit vector
+===============
+*/
+void PortalFlow (int portalnum)
+{
+ threaddata_t data;
+ int i;
+ vportal_t *p;
+ int c_might, c_can;
+
+#ifdef MREDEBUG
+ _printf("\r%6d", portalnum);
+#endif
+
+ p = sorted_portals[portalnum];
+
+ if (p->removed)
+ {
+ p->status = stat_done;
+ return;
+ }
+
+ p->status = stat_working;
+
+ c_might = CountBits (p->portalflood, numportals*2);
+
+ memset (&data, 0, sizeof(data));
+ data.base = p;
+
+ data.pstack_head.portal = p;
+ data.pstack_head.source = p->winding;
+ data.pstack_head.portalplane = p->plane;
+ data.pstack_head.depth = 0;
+ for (i=0 ; i<portallongs ; i++)
+ ((long *)data.pstack_head.mightsee)[i] = ((long *)p->portalflood)[i];
+
+ RecursiveLeafFlow (p->leaf, &data, &data.pstack_head);
+
+ p->status = stat_done;
+
+ c_can = CountBits (p->portalvis, numportals*2);
+
+ qprintf ("portal:%4i mightsee:%4i cansee:%4i (%i chains)\n",
+ (int)(p - portals), c_might, c_can, data.c_chains);
+}
+
+/*
+==================
+RecursivePassageFlow
+==================
+*/
+void RecursivePassageFlow (vportal_t *portal, threaddata_t *thread, pstack_t *prevstack)
+{
+ pstack_t stack;
+ vportal_t *p;
+ leaf_t *leaf;
+ passage_t *passage, *nextpassage;
+ int i, j;
+ long *might, *vis, *prevmight, *cansee, *portalvis, more;
+ int pnum;
+
+ leaf = &leafs[portal->leaf];
+
+ prevstack->next = &stack;
+
+ stack.next = NULL;
+ stack.depth = prevstack->depth + 1;
+
+ vis = (long *)thread->base->portalvis;
+
+ passage = portal->passages;
+ nextpassage = passage;
+ // check all portals for flowing into other leafs
+ for (i = 0; i < leaf->numportals; i++, passage = nextpassage)
+ {
+ p = leaf->portals[i];
+ if ( p->removed ) {
+ continue;
+ }
+ nextpassage = passage->next;
+ pnum = p - portals;
+
+ if ( ! (prevstack->mightsee[pnum >> 3] & (1<<(pnum&7)) ) ) {
+ continue; // can't possibly see it
+ }
+
+ // mark the portal as visible
+ thread->base->portalvis[pnum>>3] |= (1<<(pnum&7));
+
+ prevmight = (long *)prevstack->mightsee;
+ cansee = (long *)passage->cansee;
+ might = (long *)stack.mightsee;
+ memcpy(might, prevmight, portalbytes);
+ if (p->status == stat_done)
+ portalvis = (long *) p->portalvis;
+ else
+ portalvis = (long *) p->portalflood;
+ more = 0;
+ for (j = 0; j < portallongs; j++)
+ {
+ if (*might)
+ {
+ *might &= *cansee++ & *portalvis++;
+ more |= (*might & ~vis[j]);
+ }
+ else
+ {
+ cansee++;
+ portalvis++;
+ }
+ might++;
+ }
+
+ if ( !more ) {
+ // can't see anything new
+ continue;
+ }
+
+ // flow through it for real
+ RecursivePassageFlow(p, thread, &stack);
+
+ stack.next = NULL;
+ }
+}
+
+/*
+===============
+PassageFlow
+===============
+*/
+void PassageFlow (int portalnum)
+{
+ threaddata_t data;
+ int i;
+ vportal_t *p;
+// int c_might, c_can;
+
+#ifdef MREDEBUG
+ _printf("\r%6d", portalnum);
+#endif
+
+ p = sorted_portals[portalnum];
+
+ if (p->removed)
+ {
+ p->status = stat_done;
+ return;
+ }
+
+ p->status = stat_working;
+
+// c_might = CountBits (p->portalflood, numportals*2);
+
+ memset (&data, 0, sizeof(data));
+ data.base = p;
+
+ data.pstack_head.portal = p;
+ data.pstack_head.source = p->winding;
+ data.pstack_head.portalplane = p->plane;
+ data.pstack_head.depth = 0;
+ for (i=0 ; i<portallongs ; i++)
+ ((long *)data.pstack_head.mightsee)[i] = ((long *)p->portalflood)[i];
+
+ RecursivePassageFlow (p, &data, &data.pstack_head);
+
+ p->status = stat_done;
+
+ /*
+ c_can = CountBits (p->portalvis, numportals*2);
+
+ qprintf ("portal:%4i mightsee:%4i cansee:%4i (%i chains)\n",
+ (int)(p - portals), c_might, c_can, data.c_chains);
+ */
+}
+
+/*
+==================
+RecursivePassagePortalFlow
+==================
+*/
+void RecursivePassagePortalFlow (vportal_t *portal, threaddata_t *thread, pstack_t *prevstack)
+{
+ pstack_t stack;
+ vportal_t *p;
+ leaf_t *leaf;
+ plane_t backplane;
+ passage_t *passage, *nextpassage;
+ int i, j, n;
+ long *might, *vis, *prevmight, *cansee, *portalvis, more;
+ int pnum;
+
+// thread->c_chains++;
+
+ leaf = &leafs[portal->leaf];
+// CheckStack (leaf, thread);
+
+ prevstack->next = &stack;
+
+ stack.next = NULL;
+ stack.leaf = leaf;
+ stack.portal = NULL;
+ stack.depth = prevstack->depth + 1;
+
+#ifdef SEPERATORCACHE
+ stack.numseperators[0] = 0;
+ stack.numseperators[1] = 0;
+#endif
+
+ vis = (long *)thread->base->portalvis;
+
+ passage = portal->passages;
+ nextpassage = passage;
+ // check all portals for flowing into other leafs
+ for (i = 0; i < leaf->numportals; i++, passage = nextpassage)
+ {
+ p = leaf->portals[i];
+ if (p->removed)
+ continue;
+ nextpassage = passage->next;
+ pnum = p - portals;
+
+ if ( ! (prevstack->mightsee[pnum >> 3] & (1<<(pnum&7)) ) )
+ continue; // can't possibly see it
+
+ prevmight = (long *)prevstack->mightsee;
+ cansee = (long *)passage->cansee;
+ might = (long *)stack.mightsee;
+ memcpy(might, prevmight, portalbytes);
+ if (p->status == stat_done)
+ portalvis = (long *) p->portalvis;
+ else
+ portalvis = (long *) p->portalflood;
+ more = 0;
+ for (j = 0; j < portallongs; j++)
+ {
+ if (*might)
+ {
+ *might &= *cansee++ & *portalvis++;
+ more |= (*might & ~vis[j]);
+ }
+ else
+ {
+ cansee++;
+ portalvis++;
+ }
+ might++;
+ }
+
+ if (!more && (thread->base->portalvis[pnum>>3] & (1<<(pnum&7))) )
+ { // can't see anything new
+ continue;
+ }
+
+ // get plane of portal, point normal into the neighbor leaf
+ stack.portalplane = p->plane;
+ VectorSubtract (vec3_origin, p->plane.normal, backplane.normal);
+ backplane.dist = -p->plane.dist;
+
+// c_portalcheck++;
+
+ stack.portal = p;
+ stack.next = NULL;
+ stack.freewindings[0] = 1;
+ stack.freewindings[1] = 1;
+ stack.freewindings[2] = 1;
+
+#if 1
+ {
+ float d;
+
+ d = DotProduct (p->origin, thread->pstack_head.portalplane.normal);
+ d -= thread->pstack_head.portalplane.dist;
+ if (d < -p->radius)
+ {
+ continue;
+ }
+ else if (d > p->radius)
+ {
+ stack.pass = p->winding;
+ }
+ else
+ {
+ stack.pass = VisChopWinding (p->winding, &stack, &thread->pstack_head.portalplane);
+ if (!stack.pass)
+ continue;
+ }
+ }
+#else
+ stack.pass = VisChopWinding (p->winding, &stack, &thread->pstack_head.portalplane);
+ if (!stack.pass)
+ continue;
+#endif
+
+
+#if 1
+ {
+ float d;
+
+ d = DotProduct (thread->base->origin, p->plane.normal);
+ d -= p->plane.dist;
+ //MrE: vis-bug fix
+ //if (d > p->radius)
+ if (d > thread->base->radius)
+ {
+ continue;
+ }
+ //MrE: vis-bug fix
+ //if (d < -p->radius)
+ else if (d < -thread->base->radius)
+ {
+ stack.source = prevstack->source;
+ }
+ else
+ {
+ stack.source = VisChopWinding (prevstack->source, &stack, &backplane);
+ //FIXME: shouldn't we create a new source origin and radius for fast checks?
+ if (!stack.source)
+ continue;
+ }
+ }
+#else
+ stack.source = VisChopWinding (prevstack->source, &stack, &backplane);
+ if (!stack.source)
+ continue;
+#endif
+
+ if (!prevstack->pass)
+ { // the second leaf can only be blocked if coplanar
+
+ // mark the portal as visible
+ thread->base->portalvis[pnum>>3] |= (1<<(pnum&7));
+
+ RecursivePassagePortalFlow (p, thread, &stack);
+ continue;
+ }
+
+#ifdef SEPERATORCACHE
+ if (stack.numseperators[0])
+ {
+ for (n = 0; n < stack.numseperators[0]; n++)
+ {
+ stack.pass = VisChopWinding (stack.pass, &stack, &stack.seperators[0][n]);
+ if (!stack.pass)
+ break; // target is not visible
+ }
+ if (n < stack.numseperators[0])
+ continue;
+ }
+ else
+ {
+ stack.pass = ClipToSeperators (prevstack->source, prevstack->pass, stack.pass, qfalse, &stack);
+ }
+#else
+ stack.pass = ClipToSeperators (stack.source, prevstack->pass, stack.pass, qfalse, &stack);
+#endif
+ if (!stack.pass)
+ continue;
+
+#ifdef SEPERATORCACHE
+ if (stack.numseperators[1])
+ {
+ for (n = 0; n < stack.numseperators[1]; n++)
+ {
+ stack.pass = VisChopWinding (stack.pass, &stack, &stack.seperators[1][n]);
+ if (!stack.pass)
+ break; // target is not visible
+ }
+ }
+ else
+ {
+ stack.pass = ClipToSeperators (prevstack->pass, prevstack->source, stack.pass, qtrue, &stack);
+ }
+#else
+ stack.pass = ClipToSeperators (prevstack->pass, stack.source, stack.pass, qtrue, &stack);
+#endif
+ if (!stack.pass)
+ continue;
+
+ // mark the portal as visible
+ thread->base->portalvis[pnum>>3] |= (1<<(pnum&7));
+
+ // flow through it for real
+ RecursivePassagePortalFlow(p, thread, &stack);
+ //
+ stack.next = NULL;
+ }
+}
+
+/*
+===============
+PassagePortalFlow
+===============
+*/
+void PassagePortalFlow (int portalnum)
+{
+ threaddata_t data;
+ int i;
+ vportal_t *p;
+// int c_might, c_can;
+
+#ifdef MREDEBUG
+ _printf("\r%6d", portalnum);
+#endif
+
+ p = sorted_portals[portalnum];
+
+ if (p->removed)
+ {
+ p->status = stat_done;
+ return;
+ }
+
+ p->status = stat_working;
+
+// c_might = CountBits (p->portalflood, numportals*2);
+
+ memset (&data, 0, sizeof(data));
+ data.base = p;
+
+ data.pstack_head.portal = p;
+ data.pstack_head.source = p->winding;
+ data.pstack_head.portalplane = p->plane;
+ data.pstack_head.depth = 0;
+ for (i=0 ; i<portallongs ; i++)
+ ((long *)data.pstack_head.mightsee)[i] = ((long *)p->portalflood)[i];
+
+ RecursivePassagePortalFlow (p, &data, &data.pstack_head);
+
+ p->status = stat_done;
+
+ /*
+ c_can = CountBits (p->portalvis, numportals*2);
+
+ qprintf ("portal:%4i mightsee:%4i cansee:%4i (%i chains)\n",
+ (int)(p - portals), c_might, c_can, data.c_chains);
+ */
+}
+
+winding_t *PassageChopWinding (winding_t *in, winding_t *out, plane_t *split)
+{
+ vec_t dists[128];
+ int sides[128];
+ int counts[3];
+ vec_t dot;
+ int i, j;
+ vec_t *p1, *p2;
+ vec3_t mid;
+ winding_t *neww;
+
+ counts[0] = counts[1] = counts[2] = 0;
+
+ // determine sides for each point
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ dot = DotProduct (in->points[i], split->normal);
+ dot -= split->dist;
+ dists[i] = dot;
+ if (dot > ON_EPSILON)
+ sides[i] = SIDE_FRONT;
+ else if (dot < -ON_EPSILON)
+ sides[i] = SIDE_BACK;
+ else
+ {
+ sides[i] = SIDE_ON;
+ }
+ counts[sides[i]]++;
+ }
+
+ if (!counts[1])
+ return in; // completely on front side
+
+ if (!counts[0])
+ {
+ return NULL;
+ }
+
+ sides[i] = sides[0];
+ dists[i] = dists[0];
+
+ neww = out;
+
+ neww->numpoints = 0;
+
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ p1 = in->points[i];
+
+ if (neww->numpoints == MAX_POINTS_ON_FIXED_WINDING)
+ {
+ return in; // can't chop -- fall back to original
+ }
+
+ if (sides[i] == SIDE_ON)
+ {
+ VectorCopy (p1, neww->points[neww->numpoints]);
+ neww->numpoints++;
+ continue;
+ }
+
+ if (sides[i] == SIDE_FRONT)
+ {
+ VectorCopy (p1, neww->points[neww->numpoints]);
+ neww->numpoints++;
+ }
+
+ if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i])
+ continue;
+
+ if (neww->numpoints == MAX_POINTS_ON_FIXED_WINDING)
+ {
+ return in; // can't chop -- fall back to original
+ }
+
+ // generate a split point
+ p2 = in->points[(i+1)%in->numpoints];
+
+ dot = dists[i] / (dists[i]-dists[i+1]);
+ for (j=0 ; j<3 ; j++)
+ { // avoid round off error when possible
+ if (split->normal[j] == 1)
+ mid[j] = split->dist;
+ else if (split->normal[j] == -1)
+ mid[j] = -split->dist;
+ else
+ mid[j] = p1[j] + dot*(p2[j]-p1[j]);
+ }
+
+ VectorCopy (mid, neww->points[neww->numpoints]);
+ neww->numpoints++;
+ }
+
+ return neww;
+}
+
+/*
+===============
+AddSeperators
+===============
+*/
+int AddSeperators (winding_t *source, winding_t *pass, qboolean flipclip, plane_t *seperators, int maxseperators)
+{
+ int i, j, k, l;
+ plane_t plane;
+ vec3_t v1, v2;
+ float d;
+ vec_t length;
+ int counts[3], numseperators;
+ qboolean fliptest;
+
+ numseperators = 0;
+ // check all combinations
+ for (i=0 ; i<source->numpoints ; i++)
+ {
+ l = (i+1)%source->numpoints;
+ VectorSubtract (source->points[l] , source->points[i], v1);
+
+ // find a vertex of pass that makes a plane that puts all of the
+ // vertexes of pass on the front side and all of the vertexes of
+ // source on the back side
+ for (j=0 ; j<pass->numpoints ; j++)
+ {
+ VectorSubtract (pass->points[j], source->points[i], v2);
+
+ plane.normal[0] = v1[1]*v2[2] - v1[2]*v2[1];
+ plane.normal[1] = v1[2]*v2[0] - v1[0]*v2[2];
+ plane.normal[2] = v1[0]*v2[1] - v1[1]*v2[0];
+
+ // if points don't make a valid plane, skip it
+
+ length = plane.normal[0] * plane.normal[0]
+ + plane.normal[1] * plane.normal[1]
+ + plane.normal[2] * plane.normal[2];
+
+ if (length < ON_EPSILON)
+ continue;
+
+ length = 1/sqrt(length);
+
+ plane.normal[0] *= length;
+ plane.normal[1] *= length;
+ plane.normal[2] *= length;
+
+ plane.dist = DotProduct (pass->points[j], plane.normal);
+
+ //
+ // find out which side of the generated seperating plane has the
+ // source portal
+ //
+#if 1
+ fliptest = qfalse;
+ for (k=0 ; k<source->numpoints ; k++)
+ {
+ if (k == i || k == l)
+ continue;
+ d = DotProduct (source->points[k], plane.normal) - plane.dist;
+ if (d < -ON_EPSILON)
+ { // source is on the negative side, so we want all
+ // pass and target on the positive side
+ fliptest = qfalse;
+ break;
+ }
+ else if (d > ON_EPSILON)
+ { // source is on the positive side, so we want all
+ // pass and target on the negative side
+ fliptest = qtrue;
+ break;
+ }
+ }
+ if (k == source->numpoints)
+ continue; // planar with source portal
+#else
+ fliptest = flipclip;
+#endif
+ //
+ // flip the normal if the source portal is backwards
+ //
+ if (fliptest)
+ {
+ VectorSubtract (vec3_origin, plane.normal, plane.normal);
+ plane.dist = -plane.dist;
+ }
+#if 1
+ //
+ // if all of the pass portal points are now on the positive side,
+ // this is the seperating plane
+ //
+ counts[0] = counts[1] = counts[2] = 0;
+ for (k=0 ; k<pass->numpoints ; k++)
+ {
+ if (k==j)
+ continue;
+ d = DotProduct (pass->points[k], plane.normal) - plane.dist;
+ if (d < -ON_EPSILON)
+ break;
+ else if (d > ON_EPSILON)
+ counts[0]++;
+ else
+ counts[2]++;
+ }
+ if (k != pass->numpoints)
+ continue; // points on negative side, not a seperating plane
+
+ if (!counts[0])
+ continue; // planar with seperating plane
+#else
+ k = (j+1)%pass->numpoints;
+ d = DotProduct (pass->points[k], plane.normal) - plane.dist;
+ if (d < -ON_EPSILON)
+ continue;
+ k = (j+pass->numpoints-1)%pass->numpoints;
+ d = DotProduct (pass->points[k], plane.normal) - plane.dist;
+ if (d < -ON_EPSILON)
+ continue;
+#endif
+ //
+ // flip the normal if we want the back side
+ //
+ if (flipclip)
+ {
+ VectorSubtract (vec3_origin, plane.normal, plane.normal);
+ plane.dist = -plane.dist;
+ }
+
+ if (numseperators >= maxseperators)
+ Error("max seperators");
+ seperators[numseperators] = plane;
+ numseperators++;
+ break;
+ }
+ }
+ return numseperators;
+}
+
+/*
+===============
+CreatePassages
+
+MrE: create passages from one portal to all the portals in the leaf the portal leads to
+ every passage has a cansee bit string with all the portals that can be
+ seen through the passage
+===============
+*/
+void CreatePassages(int portalnum)
+{
+ int i, j, k, n, numseperators, numsee;
+ float d;
+ vportal_t *portal, *p, *target;
+ leaf_t *leaf;
+ passage_t *passage, *lastpassage;
+ plane_t seperators[MAX_SEPERATORS*2];
+ winding_t *w;
+ winding_t in, out, *res;
+
+#ifdef MREDEBUG
+ _printf("\r%6d", portalnum);
+#endif
+
+ portal = sorted_portals[portalnum];
+
+ if (portal->removed)
+ {
+ portal->status = stat_done;
+ return;
+ }
+
+ lastpassage = NULL;
+ leaf = &leafs[portal->leaf];
+ for (i = 0; i < leaf->numportals; i++)
+ {
+ target = leaf->portals[i];
+ if (target->removed)
+ continue;
+
+ passage = (passage_t *) malloc(sizeof(passage_t) + portalbytes);
+ memset(passage, 0, sizeof(passage_t) + portalbytes);
+ numseperators = AddSeperators(portal->winding, target->winding, qfalse, seperators, MAX_SEPERATORS*2);
+ numseperators += AddSeperators(target->winding, portal->winding, qtrue, &seperators[numseperators], MAX_SEPERATORS*2-numseperators);
+
+ passage->next = NULL;
+ if (lastpassage)
+ lastpassage->next = passage;
+ else
+ portal->passages = passage;
+ lastpassage = passage;
+
+ numsee = 0;
+ //create the passage->cansee
+ for (j = 0; j < numportals * 2; j++)
+ {
+ p = &portals[j];
+ if (p->removed)
+ continue;
+ if ( ! (target->portalflood[j >> 3] & (1<<(j&7)) ) )
+ continue;
+ if ( ! (portal->portalflood[j >> 3] & (1<<(j&7)) ) )
+ continue;
+ for (k = 0; k < numseperators; k++)
+ {
+ //
+ d = DotProduct (p->origin, seperators[k].normal) - seperators[k].dist;
+ //if completely at the back of the seperator plane
+ if (d < -p->radius + ON_EPSILON)
+ break;
+ w = p->winding;
+ for (n = 0; n < w->numpoints; n++)
+ {
+ d = DotProduct (w->points[n], seperators[k].normal) - seperators[k].dist;
+ //if at the front of the seperator
+ if (d > ON_EPSILON)
+ break;
+ }
+ //if no points are at the front of the seperator
+ if (n >= w->numpoints)
+ break;
+ }
+ if (k < numseperators)
+ continue;
+ memcpy(&in, p->winding, sizeof(winding_t));
+ for (k = 0; k < numseperators; k++)
+ {
+ res = PassageChopWinding(&in, &out, &seperators[k]);
+ if (res == &out)
+ memcpy(&in, &out, sizeof(winding_t));
+ if (res == NULL)
+ break;
+ }
+ if (k < numseperators)
+ continue;
+ passage->cansee[j >> 3] |= (1<<(j&7));
+ numsee++;
+ }
+ }
+}
+
+void PassageMemory(void)
+{
+ int i, j, totalmem, totalportals;
+ vportal_t *portal, *target;
+ leaf_t *leaf;
+
+ totalmem = 0;
+ totalportals = 0;
+ for (i = 0; i < numportals; i++)
+ {
+ portal = sorted_portals[i];
+ if (portal->removed)
+ continue;
+ leaf = &leafs[portal->leaf];
+ for (j = 0; j < leaf->numportals; j++)
+ {
+ target = leaf->portals[j];
+ if (target->removed)
+ continue;
+ totalmem += sizeof(passage_t) + portalbytes;
+ totalportals++;
+ }
+ }
+ _printf("%7i average number of passages per leaf\n", totalportals / numportals);
+ _printf("%7i MB required passage memory\n", totalmem >> 10 >> 10);
+}
+
+/*
+===============================================================================
+
+This is a rough first-order aproximation that is used to trivially reject some
+of the final calculations.
+
+
+Calculates portalfront and portalflood bit vectors
+
+thinking about:
+
+typedef struct passage_s
+{
+ struct passage_s *next;
+ struct portal_s *to;
+ stryct sep_s *seperators;
+ byte *mightsee;
+} passage_t;
+
+typedef struct portal_s
+{
+ struct passage_s *passages;
+ int leaf; // leaf portal faces into
+} portal_s;
+
+leaf = portal->leaf
+clear
+for all portals
+
+
+calc portal visibility
+ clear bit vector
+ for all passages
+ passage visibility
+
+
+for a portal to be visible to a passage, it must be on the front of
+all seperating planes, and both portals must be behind the new portal
+
+===============================================================================
+*/
+
+int c_flood, c_vis;
+
+
+/*
+==================
+SimpleFlood
+
+==================
+*/
+void SimpleFlood (vportal_t *srcportal, int leafnum)
+{
+ int i;
+ leaf_t *leaf;
+ vportal_t *p;
+ int pnum;
+
+ leaf = &leafs[leafnum];
+
+ for (i=0 ; i<leaf->numportals ; i++)
+ {
+ p = leaf->portals[i];
+ if (p->removed)
+ continue;
+ pnum = p - portals;
+ if ( ! (srcportal->portalfront[pnum>>3] & (1<<(pnum&7)) ) )
+ continue;
+
+ if (srcportal->portalflood[pnum>>3] & (1<<(pnum&7)) )
+ continue;
+
+ srcportal->portalflood[pnum>>3] |= (1<<(pnum&7));
+
+ SimpleFlood (srcportal, p->leaf);
+ }
+}
+
+/*
+==============
+BasePortalVis
+==============
+*/
+void BasePortalVis (int portalnum)
+{
+ int j, k;
+ vportal_t *tp, *p;
+ float d;
+ winding_t *w;
+
+ p = portals+portalnum;
+
+ if (p->removed)
+ return;
+
+ p->portalfront = malloc (portalbytes);
+ memset (p->portalfront, 0, portalbytes);
+
+ p->portalflood = malloc (portalbytes);
+ memset (p->portalflood, 0, portalbytes);
+
+ p->portalvis = malloc (portalbytes);
+ memset (p->portalvis, 0, portalbytes);
+
+ for (j=0, tp = portals ; j<numportals*2 ; j++, tp++)
+ {
+ if (j == portalnum)
+ continue;
+ if (tp->removed)
+ continue;
+ /*
+ if (farplanedist >= 0)
+ {
+ vec3_t dir;
+ VectorSubtract(p->origin, tp->origin, dir);
+ if (VectorLength(dir) > farplanedist - p->radius - tp->radius)
+ continue;
+ }
+ */
+ w = tp->winding;
+ for (k=0 ; k<w->numpoints ; k++)
+ {
+ d = DotProduct (w->points[k], p->plane.normal)
+ - p->plane.dist;
+ if (d > ON_EPSILON)
+ break;
+ }
+ if (k == w->numpoints)
+ continue; // no points on front
+
+ w = p->winding;
+ for (k=0 ; k<w->numpoints ; k++)
+ {
+ d = DotProduct (w->points[k], tp->plane.normal)
+ - tp->plane.dist;
+ if (d < -ON_EPSILON)
+ break;
+ }
+ if (k == w->numpoints)
+ continue; // no points on front
+
+ p->portalfront[j>>3] |= (1<<(j&7));
+ }
+
+ SimpleFlood (p, p->leaf);
+
+ p->nummightsee = CountBits (p->portalflood, numportals*2);
+// _printf ("portal %i: %i mightsee\n", portalnum, p->nummightsee);
+ c_flood += p->nummightsee;
+}
+
+
+
+
+
+/*
+===============================================================================
+
+This is a second order aproximation
+
+Calculates portalvis bit vector
+
+WAAAAAAY too slow.
+
+===============================================================================
+*/
+
+/*
+==================
+RecursiveLeafBitFlow
+
+==================
+*/
+void RecursiveLeafBitFlow (int leafnum, byte *mightsee, byte *cansee)
+{
+ vportal_t *p;
+ leaf_t *leaf;
+ int i, j;
+ long more;
+ int pnum;
+ byte newmight[MAX_PORTALS/8];
+
+ leaf = &leafs[leafnum];
+
+ // check all portals for flowing into other leafs
+ for (i=0 ; i<leaf->numportals ; i++)
+ {
+ p = leaf->portals[i];
+ if (p->removed)
+ continue;
+ pnum = p - portals;
+
+ // if some previous portal can't see it, skip
+ if (! (mightsee[pnum>>3] & (1<<(pnum&7)) ) )
+ continue;
+
+ // if this portal can see some portals we mightsee, recurse
+ more = 0;
+ for (j=0 ; j<portallongs ; j++)
+ {
+ ((long *)newmight)[j] = ((long *)mightsee)[j]
+ & ((long *)p->portalflood)[j];
+ more |= ((long *)newmight)[j] & ~((long *)cansee)[j];
+ }
+
+ if (!more)
+ continue; // can't see anything new
+
+ cansee[pnum>>3] |= (1<<(pnum&7));
+
+ RecursiveLeafBitFlow (p->leaf, newmight, cansee);
+ }
+}
+
+/*
+==============
+BetterPortalVis
+==============
+*/
+void BetterPortalVis (int portalnum)
+{
+ vportal_t *p;
+
+ p = portals+portalnum;
+
+ if (p->removed)
+ return;
+
+ RecursiveLeafBitFlow (p->leaf, p->portalflood, p->portalvis);
+
+ // build leaf vis information
+ p->nummightsee = CountBits (p->portalvis, numportals*2);
+ c_vis += p->nummightsee;
+}
+
+
diff --git a/q3map/writebsp.c b/q3map/writebsp.c
new file mode 100755
index 0000000..7a56d88
--- /dev/null
+++ b/q3map/writebsp.c
@@ -0,0 +1,418 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "qbsp.h"
+
+/*
+============
+EmitShader
+============
+*/
+int EmitShader( const char *shader ) {
+ int i;
+ shaderInfo_t *si;
+
+ if ( !shader ) {
+ shader = "noshader";
+ }
+
+ for ( i = 0 ; i < numShaders ; i++ ) {
+ if ( !Q_stricmp( shader, dshaders[i].shader ) ) {
+ return i;
+ }
+ }
+
+ if ( i == MAX_MAP_SHADERS ) {
+ Error( "MAX_MAP_SHADERS" );
+ }
+ numShaders++;
+ strcpy( dshaders[i].shader, shader );
+
+ si = ShaderInfoForShader( shader );
+ dshaders[i].surfaceFlags = si->surfaceFlags;
+ dshaders[i].contentFlags = si->contents;
+
+ return i;
+}
+
+
+/*
+============
+EmitPlanes
+
+There is no oportunity to discard planes, because all of the original
+brushes will be saved in the map.
+============
+*/
+void EmitPlanes (void)
+{
+ int i;
+ dplane_t *dp;
+ plane_t *mp;
+
+ mp = mapplanes;
+ for (i=0 ; i<nummapplanes ; i++, mp++)
+ {
+ dp = &dplanes[numplanes];
+ VectorCopy ( mp->normal, dp->normal);
+ dp->dist = mp->dist;
+ numplanes++;
+ }
+}
+
+
+
+/*
+==================
+EmitLeaf
+==================
+*/
+void EmitLeaf (node_t *node)
+{
+ dleaf_t *leaf_p;
+ bspbrush_t *b;
+ drawSurfRef_t *dsr;
+
+ // emit a leaf
+ if (numleafs >= MAX_MAP_LEAFS)
+ Error ("MAX_MAP_LEAFS");
+
+ leaf_p = &dleafs[numleafs];
+ numleafs++;
+
+ leaf_p->cluster = node->cluster;
+ leaf_p->area = node->area;
+
+ //
+ // write bounding box info
+ //
+ VectorCopy (node->mins, leaf_p->mins);
+ VectorCopy (node->maxs, leaf_p->maxs);
+
+ //
+ // write the leafbrushes
+ //
+ leaf_p->firstLeafBrush = numleafbrushes;
+ for ( b = node->brushlist ; b ; b = b->next ) {
+ if ( numleafbrushes >= MAX_MAP_LEAFBRUSHES ) {
+ Error( "MAX_MAP_LEAFBRUSHES" );
+ }
+ dleafbrushes[numleafbrushes] = b->original->outputNumber;
+ numleafbrushes++;
+ }
+ leaf_p->numLeafBrushes = numleafbrushes - leaf_p->firstLeafBrush;
+
+ //
+ // write the surfaces visible in this leaf
+ //
+ if ( node->opaque ) {
+ return; // no leaffaces in solids
+ }
+
+ // add the drawSurfRef_t drawsurfs
+ leaf_p->firstLeafSurface = numleafsurfaces;
+ for ( dsr = node->drawSurfReferences ; dsr ; dsr = dsr->nextRef ) {
+ if ( numleafsurfaces >= MAX_MAP_LEAFFACES)
+ Error ("MAX_MAP_LEAFFACES");
+ dleafsurfaces[numleafsurfaces] = dsr->outputNumber;
+ numleafsurfaces++;
+ }
+
+
+ leaf_p->numLeafSurfaces = numleafsurfaces - leaf_p->firstLeafSurface;
+}
+
+
+/*
+============
+EmitDrawNode_r
+============
+*/
+int EmitDrawNode_r (node_t *node)
+{
+ dnode_t *n;
+ int i;
+
+ if (node->planenum == PLANENUM_LEAF)
+ {
+ EmitLeaf (node);
+ return -numleafs;
+ }
+
+ // emit a node
+ if (numnodes == MAX_MAP_NODES)
+ Error ("MAX_MAP_NODES");
+ n = &dnodes[numnodes];
+ numnodes++;
+
+ VectorCopy (node->mins, n->mins);
+ VectorCopy (node->maxs, n->maxs);
+
+ if (node->planenum & 1)
+ Error ("WriteDrawNodes_r: odd planenum");
+ n->planeNum = node->planenum;
+
+ //
+ // recursively output the other nodes
+ //
+ for (i=0 ; i<2 ; i++)
+ {
+ if (node->children[i]->planenum == PLANENUM_LEAF)
+ {
+ n->children[i] = -(numleafs + 1);
+ EmitLeaf (node->children[i]);
+ }
+ else
+ {
+ n->children[i] = numnodes;
+ EmitDrawNode_r (node->children[i]);
+ }
+ }
+
+ return n - dnodes;
+}
+
+//=========================================================
+
+
+
+/*
+============
+SetModelNumbers
+============
+*/
+void SetModelNumbers (void)
+{
+ int i;
+ int models;
+ char value[10];
+
+ models = 1;
+ for ( i=1 ; i<num_entities ; i++ ) {
+ if ( entities[i].brushes || entities[i].patches ) {
+ sprintf ( value, "*%i", models );
+ models++;
+ SetKeyValue (&entities[i], "model", value);
+ }
+ }
+
+}
+
+/*
+============
+SetLightStyles
+============
+*/
+#define MAX_SWITCHED_LIGHTS 32
+void SetLightStyles (void)
+{
+ int stylenum;
+ const char *t;
+ entity_t *e;
+ int i, j;
+ char value[10];
+ char lighttargets[MAX_SWITCHED_LIGHTS][64];
+
+
+ // any light that is controlled (has a targetname)
+ // must have a unique style number generated for it
+
+ stylenum = 0;
+ for (i=1 ; i<num_entities ; i++)
+ {
+ e = &entities[i];
+
+ t = ValueForKey (e, "classname");
+ if (Q_strncasecmp (t, "light", 5))
+ continue;
+ t = ValueForKey (e, "targetname");
+ if (!t[0])
+ continue;
+
+ // find this targetname
+ for (j=0 ; j<stylenum ; j++)
+ if (!strcmp (lighttargets[j], t))
+ break;
+ if (j == stylenum)
+ {
+ if (stylenum == MAX_SWITCHED_LIGHTS)
+ Error ("stylenum == MAX_SWITCHED_LIGHTS");
+ strcpy (lighttargets[j], t);
+ stylenum++;
+ }
+ sprintf (value, "%i", 32 + j);
+ SetKeyValue (e, "style", value);
+ }
+
+}
+
+//===========================================================
+
+/*
+==================
+BeginBSPFile
+==================
+*/
+void BeginBSPFile( void ) {
+ // these values may actually be initialized
+ // if the file existed when loaded, so clear them explicitly
+ nummodels = 0;
+ numnodes = 0;
+ numbrushsides = 0;
+ numleafsurfaces = 0;
+ numleafbrushes = 0;
+
+ // leave leaf 0 as an error, because leafs are referenced as
+ // negative number nodes
+ numleafs = 1;
+}
+
+
+/*
+============
+EndBSPFile
+============
+*/
+void EndBSPFile( void ) {
+ char path[1024];
+
+ EmitPlanes ();
+ UnparseEntities ();
+
+ // write the map
+ sprintf (path, "%s.bsp", source);
+ _printf ("Writing %s\n", path);
+ WriteBSPFile (path);
+}
+
+
+//===========================================================
+
+/*
+============
+EmitBrushes
+============
+*/
+void EmitBrushes ( bspbrush_t *brushes ) {
+ int j;
+ dbrush_t *db;
+ bspbrush_t *b;
+ dbrushside_t *cp;
+
+ for ( b = brushes ; b ; b = b->next ) {
+ if ( numbrushes == MAX_MAP_BRUSHES ) {
+ Error( "MAX_MAP_BRUSHES" );
+ }
+ b->outputNumber = numbrushes;
+ db = &dbrushes[numbrushes];
+ numbrushes++;
+
+ db->shaderNum = EmitShader( b->contentShader->shader );
+ db->firstSide = numbrushsides;
+
+ // don't emit any generated backSide sides
+ db->numSides = 0;
+ for ( j=0 ; j<b->numsides ; j++ ) {
+ if ( b->sides[j].backSide ) {
+ continue;
+ }
+ if ( numbrushsides == MAX_MAP_BRUSHSIDES ) {
+ Error( "MAX_MAP_BRUSHSIDES ");
+ }
+ cp = &dbrushsides[numbrushsides];
+ db->numSides++;
+ numbrushsides++;
+ cp->planeNum = b->sides[j].planenum;
+ cp->shaderNum = EmitShader( b->sides[j].shaderInfo->shader );
+ }
+ }
+
+}
+
+
+/*
+==================
+BeginModel
+==================
+*/
+void BeginModel( void ) {
+ dmodel_t *mod;
+ bspbrush_t *b;
+ entity_t *e;
+ vec3_t mins, maxs;
+ parseMesh_t *p;
+ int i;
+
+ if ( nummodels == MAX_MAP_MODELS ) {
+ Error( "MAX_MAP_MODELS" );
+ }
+ mod = &dmodels[nummodels];
+
+ //
+ // bound the brushes
+ //
+ e = &entities[entity_num];
+
+ ClearBounds (mins, maxs);
+ for ( b = e->brushes ; b ; b = b->next ) {
+ if ( !b->numsides ) {
+ continue; // not a real brush (origin brush, etc)
+ }
+ AddPointToBounds (b->mins, mins, maxs);
+ AddPointToBounds (b->maxs, mins, maxs);
+ }
+
+ for ( p = e->patches ; p ; p = p->next ) {
+ for ( i = 0 ; i < p->mesh.width * p->mesh.height ; i++ ) {
+ AddPointToBounds( p->mesh.verts[i].xyz, mins, maxs );
+ }
+ }
+
+ VectorCopy (mins, mod->mins);
+ VectorCopy (maxs, mod->maxs);
+
+ mod->firstSurface = numDrawSurfaces;
+ mod->firstBrush = numbrushes;
+
+ EmitBrushes( e->brushes );
+}
+
+
+
+
+/*
+==================
+EndModel
+==================
+*/
+void EndModel( node_t *headnode ) {
+ dmodel_t *mod;
+
+ qprintf ("--- EndModel ---\n");
+
+ mod = &dmodels[nummodels];
+ EmitDrawNode_r (headnode);
+ mod->numSurfaces = numDrawSurfaces - mod->firstSurface;
+ mod->numBrushes = numbrushes - mod->firstBrush;
+
+ nummodels++;
+}
+
diff --git a/q3radiant/BMP.H b/q3radiant/BMP.H
new file mode 100755
index 0000000..367d652
--- /dev/null
+++ b/q3radiant/BMP.H
@@ -0,0 +1,101 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef _BMP_H
+#define _BMP_H
+
+#define xBI_NONE 0
+#define xBI_RGB 0
+#define xBI_RLE4 2
+#define xBI_RLE8 1
+
+#define BMP_SIGNATURE_WORD 0x4d42
+
+#pragma pack(1)
+
+
+
+typedef struct {
+ unsigned short bfType; // signature - 'BM'
+ unsigned long bfSize; // file size in bytes
+ unsigned short bfReserved1; // 0
+ unsigned short bfReserved2; // 0
+ unsigned long bfOffBits; // offset to bitmap
+} bmphd_t;
+
+
+
+typedef struct {
+ unsigned long biSize; // size of this struct
+ long biWidth; // bmap width in pixels
+ long biHeight; // bmap height in pixels
+ unsigned short biPlanes; // num planes - always 1
+ unsigned short biBitCount; // bits perpixel
+ unsigned long biCompression; // compression flag
+ unsigned long biSizeImage; // image size in bytes
+ long biXPelsPerMeter; // horz resolution
+ long biYPelsPerMeter; // vert resolution
+ unsigned long biClrUsed; // 0 -> color table size
+ unsigned long biClrImportant; // important color count
+} binfo_t;
+
+
+typedef struct {
+ unsigned char blue;
+ unsigned char green;
+ unsigned char red;
+ unsigned char reserved;
+} drgb_t;
+
+
+// quake expects its palette to be bgr
+// this is totally backwards but what can you do
+typedef struct {
+ unsigned char r;
+ unsigned char g;
+ unsigned char b;
+} rgb_t;
+
+
+typedef struct {
+ unsigned char b;
+ unsigned char g;
+ unsigned char r;
+} bgr_t;
+
+
+typedef struct {
+ int bpp; // bits per pixel
+ int width;
+ int height;
+ unsigned char *data;
+ rgb_t *palette;
+} bitmap_t;
+
+
+void LoadBMP(char *filename, bitmap_t *bit);
+void FreeBMP(bitmap_t *bitmap);
+void WriteBMP(char *filename, bitmap_t *bit);
+void NewBMP(int width, int height, int bpp, bitmap_t *bit);
+
+
+
+#endif
diff --git a/q3radiant/BRUSH.H b/q3radiant/BRUSH.H
new file mode 100755
index 0000000..13f17b6
--- /dev/null
+++ b/q3radiant/BRUSH.H
@@ -0,0 +1,124 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+// brush.h
+
+// all types moved to qertypes.h
+//--typedef struct
+//--{
+//-- int numpoints;
+//-- int maxpoints;
+//-- float points[8][5]; // variable sized
+//--} winding_t;
+
+
+// the normals on planes point OUT of the brush
+//--#define MAXPOINTS 16
+//--typedef struct face_s
+//--{
+//-- struct face_s *next;
+//-- vec3_t planepts[3];
+//-- texdef_t texdef;
+//-- plane_t plane;
+//--
+//-- winding_t *face_winding;
+//--
+//-- vec3_t d_color;
+//-- qtexture_t *d_texture;
+//--
+//--} face_t;
+//--
+//--typedef struct {
+//-- vec3_t xyz;
+//-- float sideST[2];
+//-- float capST[2];
+//--} curveVertex_t;
+//--
+//--typedef struct {
+//-- curveVertex_t v[2];
+//--} sideVertex_t;
+//--
+//--typedef struct brush_s
+//--{
+//-- struct brush_s *prev, *next; // links in active/selected
+//-- struct brush_s *oprev, *onext; // links in entity
+//-- struct entity_s *owner;
+//-- vec3_t mins, maxs;
+//-- face_t *brush_faces;
+//--
+//-- qboolean bModelFailed;
+//-- //
+//-- // curve brush extensions
+//-- // all are derived from brush_faces
+//-- qboolean curveBrush;
+//-- qboolean patchBrush;
+//-- int nPatchID;
+//--} brush_t;
+
+void Brush_AddToList (brush_t *b, brush_t *list);
+void Brush_Build(brush_t *b, bool bSnap = true, bool bMarkMap = true, bool bConvert = false);
+void Brush_BuildWindings( brush_t *b, bool bSnap = true );
+brush_t* Brush_Clone (brush_t *b);
+brush_t* Brush_FullClone(brush_t *b);
+brush_t* Brush_Create (vec3_t mins, vec3_t maxs, texdef_t *texdef);
+void Brush_Draw( brush_t *b );
+void Brush_DrawXY(brush_t *b, int nViewType);
+// set bRemoveNode to false to avoid trying to delete the item in group view tree control
+void Brush_Free (brush_t *b, bool bRemoveNode = true);
+int Brush_MemorySize(brush_t *b);
+void Brush_MakeSided (int sides);
+void Brush_MakeSidedCone (int sides);
+void Brush_Move (brush_t *b, const vec3_t move, bool bSnap = true);
+int Brush_MoveVertex(brush_t *b, vec3_t vertex, vec3_t delta, vec3_t end, bool bSnap = true);
+void Brush_ResetFaceOriginals(brush_t *b);
+brush_t* Brush_Parse (void);
+face_t* Brush_Ray (vec3_t origin, vec3_t dir, brush_t *b, float *dist);
+void Brush_RemoveFromList (brush_t *b);
+void Brush_SplitBrushByFace (brush_t *in, face_t *f, brush_t **front, brush_t **back);
+void Brush_SelectFaceForDragging (brush_t *b, face_t *f, qboolean shear);
+void Brush_SetTexture (brush_t *b, texdef_t *texdef, brushprimit_texdef_t *brushprimit_texdef, bool bFitScale = false, IPluginTexdef* pPlugTexdef=NULL );
+void Brush_SideSelect (brush_t *b, vec3_t origin, vec3_t dir, qboolean shear);
+void Brush_SnapToGrid(brush_t *pb);
+void Brush_Rotate(brush_t *b, vec3_t vAngle, vec3_t vOrigin, bool bBuild = true);
+void Brush_MakeSidedSphere(int sides);
+void Brush_Write (brush_t *b, FILE *f);
+void Brush_Write (brush_t *b, CMemFile* pMemFile);
+void Brush_RemoveEmptyFaces ( brush_t *b );
+winding_t* Brush_MakeFaceWinding (brush_t *b, face_t *face);
+
+int AddPlanept (float *f);
+float SetShadeForPlane (plane_t *p);
+
+face_t* Face_Alloc( void );
+void Face_Free( face_t *f );
+face_t* Face_Clone (face_t *f);
+void Face_MakePlane (face_t *f);
+void Face_Draw( face_t *face );
+void Face_TextureVectors (face_t *f, float STfromXYZ[2][4]);
+void SetFaceTexdef (brush_t *b, face_t *f, texdef_t *texdef, brushprimit_texdef_t *brushprimit_texdef, bool bFitScale = false, IPluginTexdef* pPlugTexdef = NULL );
+
+void Face_FitTexture( face_t * face, int nHeight, int nWidth );
+void Brush_FitTexture( brush_t *b, int nHeight, int nWidth );
+void Brush_SetEpair(brush_t *b, const char *pKey, const char *pValue);
+const char* Brush_GetKeyValue(brush_t *b, const char *pKey);
+brush_t *Brush_Alloc();
+const char* Brush_Name(brush_t *b);
diff --git a/q3radiant/BSInput.cpp b/q3radiant/BSInput.cpp
new file mode 100755
index 0000000..8d7cef5
--- /dev/null
+++ b/q3radiant/BSInput.cpp
@@ -0,0 +1,115 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// BSInput.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "BSInput.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CBSInput dialog
+
+
+CBSInput::CBSInput(CWnd* pParent /*=NULL*/)
+ : CDialog(CBSInput::IDD, pParent)
+{
+ //{{AFX_DATA_INIT(CBSInput)
+ m_fField1 = 0.0f;
+ m_fField2 = 0.0f;
+ m_fField3 = 0.0f;
+ m_fField4 = 0.0f;
+ m_fField5 = 0.0f;
+ m_strField1 = _T("");
+ m_strField2 = _T("");
+ m_strField3 = _T("");
+ m_strField4 = _T("");
+ m_strField5 = _T("");
+ //}}AFX_DATA_INIT
+}
+
+
+void CBSInput::DoDataExchange(CDataExchange* pDX)
+{
+ CDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CBSInput)
+ DDX_Text(pDX, IDC_EDIT_FIELD1, m_fField1);
+ DDX_Text(pDX, IDC_EDIT_FIELD2, m_fField2);
+ DDX_Text(pDX, IDC_EDIT_FIELD3, m_fField3);
+ DDX_Text(pDX, IDC_EDIT_FIELD4, m_fField4);
+ DDX_Text(pDX, IDC_EDIT_FIELD5, m_fField5);
+ DDX_Text(pDX, IDC_STATIC_FIELD1, m_strField1);
+ DDX_Text(pDX, IDC_STATIC_FIELD2, m_strField2);
+ DDX_Text(pDX, IDC_STATIC_FIELD3, m_strField3);
+ DDX_Text(pDX, IDC_STATIC_FIELD4, m_strField4);
+ DDX_Text(pDX, IDC_STATIC_FIELD5, m_strField5);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CBSInput, CDialog)
+ //{{AFX_MSG_MAP(CBSInput)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CBSInput message handlers
+
+BOOL CBSInput::OnInitDialog()
+{
+ CDialog::OnInitDialog();
+
+ if (m_strField1.GetLength() == 0)
+ {
+ GetDlgItem(IDC_EDIT_FIELD1)->ShowWindow(SW_HIDE);
+ GetDlgItem(IDC_STATIC_FIELD1)->ShowWindow(SW_HIDE);
+ }
+ if (m_strField2.GetLength() == 0)
+ {
+ GetDlgItem(IDC_EDIT_FIELD2)->ShowWindow(SW_HIDE);
+ GetDlgItem(IDC_STATIC_FIELD2)->ShowWindow(SW_HIDE);
+ }
+ if (m_strField3.GetLength() == 0)
+ {
+ GetDlgItem(IDC_EDIT_FIELD3)->ShowWindow(SW_HIDE);
+ GetDlgItem(IDC_STATIC_FIELD3)->ShowWindow(SW_HIDE);
+ }
+ if (m_strField4.GetLength() == 0)
+ {
+ GetDlgItem(IDC_EDIT_FIELD4)->ShowWindow(SW_HIDE);
+ GetDlgItem(IDC_STATIC_FIELD4)->ShowWindow(SW_HIDE);
+ }
+ if (m_strField5.GetLength() == 0)
+ {
+ GetDlgItem(IDC_EDIT_FIELD5)->ShowWindow(SW_HIDE);
+ GetDlgItem(IDC_STATIC_FIELD5)->ShowWindow(SW_HIDE);
+ }
+
+ return TRUE; // return TRUE unless you set the focus to a control
+ // EXCEPTION: OCX Property Pages should return FALSE
+}
diff --git a/q3radiant/BSInput.h b/q3radiant/BSInput.h
new file mode 100755
index 0000000..02b2057
--- /dev/null
+++ b/q3radiant/BSInput.h
@@ -0,0 +1,76 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_BSINPUT_H__81DF2A32_A552_11D1_B58E_00AA00A410FC__INCLUDED_)
+#define AFX_BSINPUT_H__81DF2A32_A552_11D1_B58E_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// BSInput.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CBSInput dialog
+
+class CBSInput : public CDialog
+{
+// Construction
+public:
+ CBSInput(CWnd* pParent = NULL); // standard constructor
+
+// Dialog Data
+ //{{AFX_DATA(CBSInput)
+ enum { IDD = IDD_DIALOG_INPUT };
+ float m_fField1;
+ float m_fField2;
+ float m_fField3;
+ float m_fField4;
+ float m_fField5;
+ CString m_strField1;
+ CString m_strField2;
+ CString m_strField3;
+ CString m_strField4;
+ CString m_strField5;
+ //}}AFX_DATA
+
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CBSInput)
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+
+ // Generated message map functions
+ //{{AFX_MSG(CBSInput)
+ virtual BOOL OnInitDialog();
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_BSINPUT_H__81DF2A32_A552_11D1_B58E_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/BSPFILE.H b/q3radiant/BSPFILE.H
new file mode 100755
index 0000000..93c9db0
--- /dev/null
+++ b/q3radiant/BSPFILE.H
@@ -0,0 +1,379 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+
+// upper design bounds
+// leaffaces, leafbrushes, planes, and verts are still bounded by
+// 16 bit short limits
+#define MAX_MAP_MODELS 1024
+#define MAX_MAP_BRUSHES 8192
+#define MAX_MAP_ENTITIES 2048
+#define MAX_MAP_PATHS 2048
+#define MAX_MAP_ENTSTRING 0x20000
+#define MAX_MAP_TEXTURES 1024
+#define MAX_MAP_TEXINFO 8192
+
+#define MAX_MAP_PLANES 65536
+#define MAX_MAP_NODES 65536
+#define MAX_MAP_BRUSHSIDES 65536
+#define MAX_MAP_LEAFS 65536
+#define MAX_MAP_VERTS 65536
+#define MAX_MAP_FACES 65536
+#define MAX_MAP_LEAFFACES 65536
+#define MAX_MAP_LEAFBRUSHES 65536
+#define MAX_MAP_PORTALS 65536
+#define MAX_MAP_EDGES 128000
+#define MAX_MAP_SURFEDGES 256000
+#define MAX_MAP_MIPTEX 0x200000
+#define MAX_MAP_LIGHTING 0x200000
+#define MAX_MAP_VISIBILITY 0x100000
+
+// key / value pair sizes
+
+#define MAX_KEY 32
+#define MAX_VALUE 1024
+
+//=============================================================================
+
+#define BSPVERSION 34
+
+typedef struct
+{
+ int fileofs, filelen;
+} lump_t;
+
+#define LUMP_ENTITIES 0
+#define LUMP_PLANES 1
+#define LUMP_TEXTURES 2
+#define LUMP_VERTEXES 3
+#define LUMP_VISIBILITY 4
+#define LUMP_NODES 5
+#define LUMP_TEXINFO 6
+#define LUMP_FACES 7
+#define LUMP_LIGHTING 8
+#define LUMP_LEAFS 9
+#define LUMP_LEAFFACES 10
+#define LUMP_LEAFBRUSHES 11
+#define LUMP_EDGES 12
+#define LUMP_SURFEDGES 13
+#define LUMP_MODELS 14
+#define LUMP_PATHS 15
+#define LUMP_BRUSHES 16
+#define LUMP_BRUSHSIDES 17
+#define LUMP_POP 18
+
+#define HEADER_LUMPS 18
+
+typedef struct
+{
+ int version;
+ lump_t lumps[HEADER_LUMPS];
+} dheader_t;
+
+typedef struct
+{
+ float mins[3], maxs[3];
+ float origin[3]; // for sounds or lights
+ int headnode;
+ int visleafs; // not including the solid leaf 0
+ int firstface, numfaces;
+} dmodel_t;
+
+typedef struct
+{
+ int nummiptex;
+ int dataofs[4]; // [nummiptex]
+} dmiptexlump_t;
+
+#define MIPLEVELS 4
+typedef struct miptex_s
+{
+ char name[16];
+ unsigned width, height;
+ unsigned offsets[MIPLEVELS]; // four mip maps stored
+ int flags;
+ int value;
+} miptex_t;
+
+
+typedef struct
+{
+ float point[3];
+} dvertex_t;
+
+
+// 0-2 are axial planes
+#define PLANE_X 0
+#define PLANE_Y 1
+#define PLANE_Z 2
+
+// 3-5 are non-axial planes snapped to the nearest
+#define PLANE_ANYX 3
+#define PLANE_ANYY 4
+#define PLANE_ANYZ 5
+
+// planes (x&~1) and (x&~1)+1 are allways opposites
+
+typedef struct
+{
+ float normal[3];
+ float dist;
+ int type; // PLANE_X - PLANE_ANYZ ?remove? trivial to regenerate
+} dplane_t;
+
+
+// contents flags are seperate bits
+// a given brush can contribute multiple content bits
+// multiple brushes can be in a single leaf
+
+// lower bits are stronger, and will eat weaker brushes completely
+#define CONTENTS_SOLID 1 // an eye is never valid in a solid
+#define CONTENTS_WINDOW 2 // translucent, but not watery
+#define CONTENTS_LAVA 8
+#define CONTENTS_SLIME 16
+#define CONTENTS_WATER 32
+#define CONTENTS_THINWATER 64 // translucent faces
+
+#define LAST_VISIBLE_CONTENTS 64
+
+// remaining contents are non-visible, and don't eat brushes
+#define CONTENTS_MONSTER 128
+#define CONTENTS_PLAYERCLIP 256
+#define CONTENTS_MONSTERCLIP 512
+
+
+// currents can be added to any other contents, and may be mixed
+#define CONTENTS_CURRENT_0 1024
+#define CONTENTS_CURRENT_90 2048
+#define CONTENTS_CURRENT_180 4096
+#define CONTENTS_CURRENT_270 8192
+#define CONTENTS_CURRENT_UP 16384
+#define CONTENTS_CURRENT_DOWN 32768
+
+#define CONTENTS_ORIGIN 65536 // removed before processing
+
+
+
+// !!! if this is changed, it must be changed in asm_i386.h too !!!
+typedef struct
+{
+ int planenum;
+ int children[2]; // negative numbers are -(leafs+1), not nodes
+ short mins[3]; // for frustom culling
+ short maxs[3];
+ unsigned short firstface;
+ unsigned short numfaces; // counting both sides
+} dnode_t;
+
+typedef struct texinfo_s
+{
+ float vecs[2][4]; // [s/t][xyz offset]
+ int miptex;
+ int flags; // miptex flags + overrides
+ int value; // light emition, etc
+} texinfo_t;
+
+#define TEX_SPECIAL 1 // sky or slime, no lightmap or 256 subdivision
+#define SURF_LIGHT 2
+
+#define SURF_WATER 4
+#define SURF_SLIME 8
+#define SURF_LAVA 16
+#define SURF_WINDOW 32
+
+#define SURF_SKY 64
+#define SURF_MIRROR 128
+
+#define SURF_SLIPPERY 256
+
+// note that edge 0 is never used, because negative edge nums are used for
+// counterclockwise use of the edge in a face
+typedef struct
+{
+ unsigned short v[2]; // vertex numbers
+} dedge_t;
+
+#define MAXLIGHTMAPS 4
+typedef struct
+{
+ unsigned short planenum;
+ short side;
+
+ int firstedge; // we must support > 64k edges
+ short numedges;
+ short texinfo;
+
+// lighting info
+ byte styles[MAXLIGHTMAPS];
+ int lightofs; // start of [numstyles*surfsize] samples
+} dface_t;
+
+typedef struct
+{
+ int contents; // OR of all brushes
+ int visofs; // -1 = no visibility info
+
+ short mins[3]; // for frustum culling
+ short maxs[3];
+
+ unsigned short firstleafface;
+ unsigned short numleaffaces;
+
+ unsigned short firstleafbrush;
+ unsigned short numleafbrushes;
+} dleaf_t;
+
+
+typedef struct
+{
+ unsigned short planenum; // facing out of the leaf
+ short texinfo;
+} dbrushside_t;
+
+typedef struct
+{
+ int firstside;
+ int numsides;
+ int contents;
+} dbrush_t;
+
+typedef struct
+{
+ float origin[3];
+ float angles[3];
+ int next, prev;
+ int flags;
+ float speed;
+} dpath_t;
+
+//============================================================================
+
+#ifndef QUAKE_GAME
+
+#define ANGLE_UP -1
+#define ANGLE_DOWN -2
+
+
+// the utilities get to be lazy and just use large static arrays
+
+extern int nummodels;
+extern dmodel_t dmodels[MAX_MAP_MODELS];
+
+extern int visdatasize;
+extern byte dvisdata[MAX_MAP_VISIBILITY];
+
+extern int lightdatasize;
+extern byte dlightdata[MAX_MAP_LIGHTING];
+
+extern int texdatasize;
+extern byte dtexdata[MAX_MAP_MIPTEX]; // (dmiptexlump_t)
+
+extern int entdatasize;
+extern char dentdata[MAX_MAP_ENTSTRING];
+
+extern int numleafs;
+extern dleaf_t dleafs[MAX_MAP_LEAFS];
+
+extern int numplanes;
+extern dplane_t dplanes[MAX_MAP_PLANES];
+
+extern int numvertexes;
+extern dvertex_t dvertexes[MAX_MAP_VERTS];
+
+extern int numnodes;
+extern dnode_t dnodes[MAX_MAP_NODES];
+
+extern int numtexinfo;
+extern texinfo_t texinfo[MAX_MAP_TEXINFO];
+
+extern int numfaces;
+extern dface_t dfaces[MAX_MAP_FACES];
+
+extern int numedges;
+extern dedge_t dedges[MAX_MAP_EDGES];
+
+extern int numleaffaces;
+extern unsigned short dleaffaces[MAX_MAP_LEAFFACES];
+
+extern int numleafbrushes;
+extern unsigned short dleafbrushes[MAX_MAP_LEAFBRUSHES];
+
+extern int numsurfedges;
+extern int dsurfedges[MAX_MAP_SURFEDGES];
+
+extern int numpaths;
+extern dpath_t dpaths[MAX_MAP_PATHS];
+
+extern int numbrushes;
+extern dbrush_t dbrushes[MAX_MAP_BRUSHES];
+
+extern int numbrushsides;
+extern dbrushside_t dbrushsides[MAX_MAP_BRUSHSIDES];
+
+
+void DecompressVis (byte *in, byte *decompressed);
+int CompressVis (byte *vis, byte *dest);
+
+void LoadBSPFile (char *filename);
+void WriteBSPFile (char *filename);
+void PrintBSPFileSizes (void);
+
+//===============
+
+
+typedef struct epair_s
+{
+ struct epair_s *next;
+ char *key;
+ char *value;
+} epair_t;
+
+typedef struct
+{
+ vec3_t origin;
+ int firstbrush;
+ int numbrushes;
+ epair_t *epairs;
+} entity_t;
+
+extern int num_entities;
+extern entity_t entities[MAX_MAP_ENTITIES];
+
+void ParseEntities (void);
+void UnparseEntities (void);
+
+void SetKeyValue (entity_t *ent, char *key, char *value);
+char *ValueForKey (entity_t *ent, char *key);
+// will return "" if not present
+
+vec_t FloatForKey (entity_t *ent, char *key);
+void GetVectorForKey (entity_t *ent, char *key, vec3_t vec);
+
+epair_t *ParseEpair (void);
+
+void PrintEntity (entity_t *ent);
+
+extern int r_leaftovis[MAX_MAP_LEAFS];
+extern int r_vistoleaf[MAX_MAP_LEAFS];
+extern int r_numvisleafs;
+
+#endif
diff --git a/q3radiant/Bmp.cpp b/q3radiant/Bmp.cpp
new file mode 100755
index 0000000..adda9a9
--- /dev/null
+++ b/q3radiant/Bmp.cpp
@@ -0,0 +1,417 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "stdafx.h"
+#include <stdio.h>
+#include <malloc.h>
+#include <string.h>
+
+#include "bmp.h"
+
+
+void Error(char *fmt, ...);
+
+
+static int GetColorCount(int nbits)
+{
+ int ncolors = 0;
+
+ if (nbits < 24)
+ {
+ ncolors = 1 << nbits;
+ }
+
+ return(ncolors);
+}
+
+
+static void BMPLineNone(FILE *f, char *sline, int pixbytes, int width)
+{
+ int nbytes, i, k, j;
+
+ switch (pixbytes)
+ {
+ case 1 :
+ nbytes = (width + 3) / 4;
+ nbytes *= 4;
+
+ fread(sline, width, 1, f);
+ nbytes -= width;
+
+ while (nbytes-- > 0) fgetc(f);
+ return;
+
+ case 3 :
+ nbytes = ((width * 3) + 3) / 4;
+ nbytes *= 4;
+
+ fread(sline, width, 3, f);
+ nbytes -= width * 3;
+
+ while (nbytes-- > 0) fgetc(f);
+
+ // reorder bgr to rgb
+ for (i = 0, j = 0; i < width; i++, j += 3)
+ {
+ k = sline[j];
+ sline[j] = sline[j+2];
+ sline[j+2] = k;
+ }
+
+ return;
+ }
+
+ Error("BMPLineNone failed.");
+}
+
+
+static void BMPLineRLE8(FILE *f, char *sline, int pixbytes, int width)
+{
+ Error("RLE8 not yet supported.");
+}
+
+
+static void BMPLineRLE4(FILE *f, char *sline, int pixbytes, int width)
+{
+ Error("RLE4 not yet supported.");
+}
+
+
+static void BMPLine(FILE *f, char *scanline, int pixbytes, int width, int rle)
+{
+ switch (rle)
+ {
+ case xBI_NONE : BMPLineNone(f, scanline, pixbytes, width); return;
+ case xBI_RLE8 : BMPLineRLE8(f, scanline, pixbytes, width); return;
+ case xBI_RLE4 : BMPLineRLE4(f, scanline, pixbytes, width); return;
+ }
+
+ Error("Unknown compression type.");
+}
+
+
+
+static void PrintHeader(binfo_t *b)
+{
+ printf("biSize : %ld\n", b->biSize);
+ printf("biWidth : %ld\n", b->biWidth);
+ printf("biHeight : %ld\n", b->biHeight);
+ printf("biPlanes : %d\n", b->biPlanes);
+ printf("biBitCount : %d\n", b->biBitCount);
+ printf("biCompression : %ld\n", b->biCompression);
+ printf("biSizeImage : %ld\n", b->biSizeImage);
+ printf("biXPelsPerMeter: %ld\n", b->biXPelsPerMeter);
+ printf("biYPelsPerMeter: %ld\n", b->biYPelsPerMeter);
+ printf("biClrUsed : %ld\n", b->biClrUsed);
+ printf("biClrImportant : %ld\n", b->biClrImportant);
+}
+
+
+void LoadBMP(char *filename, bitmap_t *bit)
+{
+ FILE *f;
+ bmphd_t bhd;
+ binfo_t info;
+ int pxlsize = 1;
+ int rowbytes, i, pixbytes;
+ char *scanline;
+
+ // open file
+ if ((f = fopen(filename, "rb")) == NULL)
+ {
+ Error("Unable to open %s.", filename);
+ }
+
+ // read in bitmap header
+ if (fread(&bhd, sizeof(bhd), 1, f) != 1)
+ {
+ fclose(f);
+ Error("Unable to read in bitmap header.");
+ }
+
+ // make sure we have a valid bitmap file
+ if (bhd.bfType != BMP_SIGNATURE_WORD)
+ {
+ fclose(f);
+ Error("Invalid BMP file: %s", filename);
+ }
+
+ // load in info header
+ if (fread(&info, sizeof(info), 1, f) != 1)
+ {
+ fclose(f);
+ Error("Unable to read bitmap info header.");
+ }
+
+ // make sure this is an info type of bitmap
+ if (info.biSize != sizeof(binfo_t))
+ {
+ fclose(f);
+ Error("We only support the info bitmap type.");
+ }
+
+ // PrintHeader(&info);
+
+ bit->bpp = info.biBitCount;
+ bit->width = info.biWidth;
+ bit->height = info.biHeight;
+ bit->data = NULL;
+ bit->palette = NULL;
+
+ //currently we only read in 8 and 24 bit bmp files
+ if (info.biBitCount == 8) pixbytes = 1;
+ else if (info.biBitCount == 24) pixbytes = 3;
+ else
+ {
+ Error("BPP %d not supported.", info.biBitCount);
+ }
+
+ // if this is an eight bit image load palette
+ if (pixbytes == 1)
+ {
+ drgb_t q;
+
+ bit->palette = reinterpret_cast<rgb_t*>(malloc(sizeof(rgb_t) * 256));
+
+ for (i = 0; i < 256; i++)
+ {
+ if (fread(&q, sizeof(drgb_t), 1, f) != 1)
+ {
+ fclose(f); free(bit->palette);
+ Error("Unable to read palette.");
+ }
+
+ bit->palette[i].r = q.red;
+ bit->palette[i].g = q.green;
+ bit->palette[i].b = q.blue;
+ }
+ }
+
+ // position to start of bitmap
+ fseek(f, bhd.bfOffBits, SEEK_SET);
+
+ // create scanline to read data into
+ rowbytes = ((info.biWidth * pixbytes) + 3) / 4;
+ rowbytes *= 4;
+
+ scanline = reinterpret_cast<char*>(malloc(rowbytes));
+
+ // alloc space for new bitmap
+ bit->data = reinterpret_cast<unsigned char*>(malloc(info.biWidth * pixbytes * info.biHeight));
+
+ // read in image
+ for (i = 0; i < info.biHeight; i++)
+ {
+ BMPLine(f, scanline, pixbytes, info.biWidth, info.biCompression);
+
+ // store line
+ memcpy(&bit->data[info.biWidth * pixbytes * (info.biHeight - i - 1)], scanline, info.biWidth * pixbytes);
+ }
+
+ free(scanline);
+ fclose(f);
+}
+
+
+
+static void BMPEncodeLine(FILE *f, unsigned char *data, int npxls, int pixbytes)
+{
+ int nbytes, i, j, k;
+
+ switch (pixbytes)
+ {
+ case 1 :
+ nbytes = (npxls + 3) / 4;
+ nbytes *= 4;
+
+ fwrite(data, npxls, 1, f);
+ nbytes -= npxls;
+
+ while (nbytes-- > 0) fputc(0, f);
+ return;
+
+ case 3 :
+ // reorder rgb to bgr
+ for (i = 0, j = 0; i < npxls; i++, j+= 3)
+ {
+ k = data[j];
+ data[j] = data[j + 2];
+ data[j + 2] = k;
+ }
+
+ nbytes = ((npxls * 3) + 3) / 4;
+ nbytes *= 4;
+
+ fwrite(data, npxls, 3, f);
+ nbytes -= npxls * 3;
+
+ while (nbytes-- > 0) fputc(0, f);
+ return;
+ }
+
+ Error("BMPEncodeLine Failed.");
+}
+
+
+
+void WriteBMP(char *filename, bitmap_t *bit)
+{
+ FILE *f;
+ bmphd_t header;
+ binfo_t info;
+ drgb_t q; // palette that gets written
+ long bmofs;
+ int w, h, i;
+ int pixbytes;
+
+ if (bit->bpp == 8) pixbytes = 1;
+ else if (bit->bpp == 24) pixbytes = 3;
+
+ else
+ {
+ Error("BPP %d not supported.", bit->bpp);
+ }
+
+
+ if ((f = fopen(filename, "wb")) == NULL)
+ {
+ Error("Unable to open %s.", filename);
+ }
+
+ // write out an empty header as a place holder
+ if (fwrite(&header, sizeof(header), 1, f) != 1)
+ {
+ Error("Unable to fwrite.");
+ }
+
+ // init and write info header
+ info.biSize = sizeof(binfo_t);
+ info.biWidth = bit->width;
+ info.biHeight = bit->height;
+ info.biPlanes = 1;
+ info.biBitCount = bit->bpp;
+ info.biCompression = xBI_NONE;
+ info.biSizeImage = bit->width * bit->height;
+ info.biXPelsPerMeter = 0;
+ info.biYPelsPerMeter = 0;
+ info.biClrUsed = 256;
+ info.biClrImportant = 256;
+
+ if (fwrite(&info, sizeof(binfo_t), 1, f) != 1)
+ {
+ Error("fwrite failed.");
+ }
+
+ // write out palette if we need to
+ if (bit->bpp == 8)
+ {
+ for (i = 0; i < 256; i++)
+ {
+ q.red = bit->palette[i].r;
+ q.green = bit->palette[i].g;
+ q.blue = bit->palette[i].b;
+
+ fwrite(&q, sizeof(q), 1, f);
+ }
+ }
+
+ // save offset to start of bitmap
+ bmofs = ftell(f);
+
+ // output bitmap
+ w = bit->width;
+ h = bit->height;
+
+ for (i = h - 1; i >= 0; i--)
+ {
+ BMPEncodeLine(f, &bit->data[w * pixbytes * i], w, pixbytes);
+ }
+
+ // update and rewrite file header
+ header.bfType = BMP_SIGNATURE_WORD;
+ header.bfSize = ftell(f);
+ header.bfOffBits = bmofs;
+
+ fseek(f, 0L, SEEK_SET);
+ fwrite(&header, sizeof(header), 1, f);
+
+ fclose(f);
+}
+
+
+void NewBMP(int width, int height, int bpp, bitmap_t *bit)
+{
+ int pixbytes;
+
+ if (bpp == 8) pixbytes = 1;
+ else if (bpp == 24) pixbytes = 3;
+
+ else
+ {
+ Error("NewBMP: 8 or 24 bit only.");
+ }
+
+ bit->bpp = bpp;
+ bit->width = width;
+ bit->height = height;
+
+ bit->data = reinterpret_cast<unsigned char*>(malloc(width * height * pixbytes));
+
+ if (bit->data == NULL)
+ {
+ Error("NewBMP: malloc failed.");
+ }
+
+ // see if we need to create a palette
+ if (pixbytes == 1)
+ {
+ bit->palette = (rgb_t *) malloc(768);
+
+ if (bit->palette == NULL)
+ {
+ Error("NewBMP: unable to malloc palette.");
+ }
+ }
+ else
+ {
+ bit->palette = NULL;
+ }
+}
+
+
+
+void FreeBMP(bitmap_t *bitmap)
+{
+ if (bitmap->palette)
+ {
+ free(bitmap->palette);
+ bitmap->palette = NULL;
+ }
+
+ if (bitmap->data)
+ {
+ free(bitmap->data);
+ bitmap->data = NULL;
+ }
+}
+
+
diff --git a/q3radiant/Brush.cpp b/q3radiant/Brush.cpp
new file mode 100755
index 0000000..e7f0168
--- /dev/null
+++ b/q3radiant/Brush.cpp
@@ -0,0 +1,4595 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+
+#include "stdafx.h"
+#include <assert.h>
+#include "qe3.h"
+#include "winding.h"
+
+
+// globals
+
+int g_nBrushId = 0;
+
+const char* Brush_Name(brush_t *b)
+{
+ static char cBuff[1024];
+ b->numberId = g_nBrushId++;
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ sprintf(cBuff, "Brush %i", b->numberId);
+ Brush_SetEpair(b, "Name", cBuff);
+ }
+ return cBuff;
+}
+
+brush_t *Brush_Alloc()
+{
+ brush_t *b = (brush_t*)qmalloc(sizeof(brush_t));
+ return b;
+}
+
+
+
+
+void PrintWinding (winding_t *w)
+{
+ int i;
+
+ printf ("-------------\n");
+ for (i=0 ; i<w->numpoints ; i++)
+ printf ("(%5.2f, %5.2f, %5.2f)\n", w->points[i][0]
+ , w->points[i][1], w->points[i][2]);
+}
+
+void PrintPlane (plane_t *p)
+{
+ printf ("(%5.2f, %5.2f, %5.2f) : %5.2f\n", p->normal[0], p->normal[1],
+ p->normal[2], p->dist);
+}
+
+void PrintVector (vec3_t v)
+{
+ printf ("(%5.2f, %5.2f, %5.2f)\n", v[0], v[1], v[2]);
+}
+
+
+/*
+=============================================================================
+
+ TEXTURE COORDINATES
+
+=============================================================================
+*/
+
+
+/*
+==================
+textureAxisFromPlane
+==================
+*/
+vec3_t baseaxis[18] =
+{
+{0,0,1}, {1,0,0}, {0,-1,0}, // floor
+{0,0,-1}, {1,0,0}, {0,-1,0}, // ceiling
+{1,0,0}, {0,1,0}, {0,0,-1}, // west wall
+{-1,0,0}, {0,1,0}, {0,0,-1}, // east wall
+{0,1,0}, {1,0,0}, {0,0,-1}, // south wall
+{0,-1,0}, {1,0,0}, {0,0,-1} // north wall
+};
+
+void TextureAxisFromPlane(plane_t *pln, vec3_t xv, vec3_t yv)
+{
+ int bestaxis;
+ float dot,best;
+ int i;
+
+ best = 0;
+ bestaxis = 0;
+
+ for (i=0 ; i<6 ; i++)
+ {
+ dot = DotProduct (pln->normal, baseaxis[i*3]);
+ if (dot > best)
+ {
+ best = dot;
+ bestaxis = i;
+ }
+ }
+
+ VectorCopy (baseaxis[bestaxis*3+1], xv);
+ VectorCopy (baseaxis[bestaxis*3+2], yv);
+}
+
+
+
+float lightaxis[3] = {0.6, 0.8, 1.0};
+/*
+================
+SetShadeForPlane
+
+Light different planes differently to
+improve recognition
+================
+*/
+float SetShadeForPlane (plane_t *p)
+{
+ int i;
+ float f;
+
+ // axial plane
+ for (i=0 ; i<3 ; i++)
+ if (fabs(p->normal[i]) > 0.9)
+ {
+ f = lightaxis[i];
+ return f;
+ }
+
+ // between two axial planes
+ for (i=0 ; i<3 ; i++)
+ if (fabs(p->normal[i]) < 0.1)
+ {
+ f = (lightaxis[(i+1)%3] + lightaxis[(i+2)%3])/2;
+ return f;
+ }
+
+ // other
+ f= (lightaxis[0] + lightaxis[1] + lightaxis[2]) / 3;
+ return f;
+}
+
+vec3_t vecs[2];
+float shift[2];
+
+/*
+================
+Face_Alloc
+================
+*/
+face_t *Face_Alloc( void )
+{
+ face_t *f = (face_t*)qmalloc( sizeof( *f ) );
+
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ f->pData = static_cast<void *>( g_SurfaceTable.m_pfnTexdefAlloc( f ) );
+
+ return f;
+}
+
+/*
+================
+Face_Free
+================
+*/
+void Face_Free( face_t *f )
+{
+ assert( f != 0 );
+
+ if ( f->face_winding )
+ {
+ free( f->face_winding );
+ f->face_winding = 0;
+ }
+
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+#ifdef _DEBUG
+ if ( !f->pData )
+ {
+ Sys_Printf("WARNING: unexpected IPluginTexdef is NULL in Face_Free\n");
+ }
+ else
+#endif
+ GETPLUGINTEXDEF(f)->DecRef();
+ }
+
+ f->texdef.~texdef_t();;
+
+ free( f );
+}
+
+/*
+================
+Face_Clone
+================
+*/
+face_t *Face_Clone (face_t *f)
+{
+ face_t *n;
+
+ n = Face_Alloc();
+ n->texdef = f->texdef;
+
+ memcpy (n->planepts, f->planepts, sizeof(n->planepts));
+
+ // all other fields are derived, and will be set by Brush_Build
+ return n;
+}
+
+/*
+================
+Face_FullClone
+
+makes an exact copy of the face
+================
+*/
+face_t *Face_FullClone (face_t *f)
+{
+ face_t *n;
+
+ n = Face_Alloc();
+ n->texdef = f->texdef;
+ memcpy(n->planepts, f->planepts, sizeof(n->planepts));
+ memcpy(&n->plane, &f->plane, sizeof(plane_t));
+ if (f->face_winding)
+ n->face_winding = Winding_Clone(f->face_winding);
+ else
+ n->face_winding = NULL;
+ n->d_texture = Texture_ForName( n->texdef.name );
+ return n;
+}
+
+/*
+================
+Clamp
+================
+*/
+void Clamp(float& f, int nClamp)
+{
+ float fFrac = f - static_cast<int>(f);
+ f = static_cast<int>(f) % nClamp;
+ f += fFrac;
+}
+
+/*
+================
+Face_MoveTexture
+================
+*/
+void Face_MoveTexture(face_t *f, vec3_t delta)
+{
+ vec3_t vX, vY;
+/*
+#ifdef _DEBUG
+ if (g_PrefsDlg.m_bBrushPrimitMode)
+ Sys_Printf("Warning : Face_MoveTexture not done in brush primitive mode\n");
+#endif
+*/
+ if (g_qeglobals.m_bBrushPrimitMode)
+ Face_MoveTexture_BrushPrimit( f, delta );
+ else
+ {
+ TextureAxisFromPlane(&f->plane, vX, vY);
+
+ vec3_t vDP, vShift;
+ vDP[0] = DotProduct(delta, vX);
+ vDP[1] = DotProduct(delta, vY);
+
+ double fAngle = f->texdef.rotate / 180 * Q_PI;
+ double c = cos(fAngle);
+ double s = sin(fAngle);
+
+ vShift[0] = vDP[0] * c - vDP[1] * s;
+ vShift[1] = vDP[0] * s + vDP[1] * c;
+
+ if (!f->texdef.scale[0])
+ f->texdef.scale[0] = 1;
+ if (!f->texdef.scale[1])
+ f->texdef.scale[1] = 1;
+
+ f->texdef.shift[0] -= vShift[0] / f->texdef.scale[0];
+ f->texdef.shift[1] -= vShift[1] / f->texdef.scale[1];
+
+ // clamp the shifts
+ Clamp(f->texdef.shift[0], f->d_texture->width);
+ Clamp(f->texdef.shift[1], f->d_texture->height);
+ }
+}
+
+/*
+================
+Face_SetColor
+================
+*/
+void Face_SetColor (brush_t *b, face_t *f, float fCurveColor)
+{
+ float shade;
+ qtexture_t *q;
+
+ q = f->d_texture;
+
+ // set shading for face
+ shade = SetShadeForPlane (&f->plane);
+ if (g_pParentWnd->GetCamera()->Camera().draw_mode == cd_texture && !b->owner->eclass->fixedsize)
+ {
+ //if (b->curveBrush)
+ // shade = fCurveColor;
+ f->d_color[0] =
+ f->d_color[1] =
+ f->d_color[2] = shade;
+ }
+ else
+ {
+ f->d_color[0] = shade*q->color[0];
+ f->d_color[1] = shade*q->color[1];
+ f->d_color[2] = shade*q->color[2];
+ }
+}
+
+/*
+================
+Face_TextureVectors
+TTimo: NOTE: this is never to get called while in brush primitives mode
+================
+*/
+void Face_TextureVectors (face_t *f, float STfromXYZ[2][4])
+{
+ vec3_t pvecs[2];
+ int sv, tv;
+ float ang, sinv, cosv;
+ float ns, nt;
+ int i,j;
+ qtexture_t *q;
+ texdef_t *td;
+
+#ifdef _DEBUG
+ //++timo when playing with patches, this sometimes get called and the Warning is displayed
+ // find some way out ..
+ if (g_qeglobals.m_bBrushPrimitMode && !g_qeglobals.bNeedConvert)
+ Sys_Printf("Warning : illegal call of Face_TextureVectors in brush primitive mode\n");
+#endif
+
+ td = &f->texdef;
+ q = f->d_texture;
+
+ memset (STfromXYZ, 0, 8*sizeof(float));
+
+ if (!td->scale[0])
+ td->scale[0] = (g_PrefsDlg.m_bHiColorTextures) ? 0.5 : 1;
+ if (!td->scale[1])
+ td->scale[1] = (g_PrefsDlg.m_bHiColorTextures) ? 0.5 : 1;
+
+ // get natural texture axis
+ TextureAxisFromPlane(&f->plane, pvecs[0], pvecs[1]);
+
+ // rotate axis
+ if (td->rotate == 0)
+ { sinv = 0 ; cosv = 1; }
+ else if (td->rotate == 90)
+ { sinv = 1 ; cosv = 0; }
+ else if (td->rotate == 180)
+ { sinv = 0 ; cosv = -1; }
+ else if (td->rotate == 270)
+ { sinv = -1 ; cosv = 0; }
+ else
+ {
+ ang = td->rotate / 180 * Q_PI;
+ sinv = sin(ang);
+ cosv = cos(ang);
+ }
+
+ if (pvecs[0][0])
+ sv = 0;
+ else if (pvecs[0][1])
+ sv = 1;
+ else
+ sv = 2;
+
+ if (pvecs[1][0])
+ tv = 0;
+ else if (pvecs[1][1])
+ tv = 1;
+ else
+ tv = 2;
+
+ for (i=0 ; i<2 ; i++) {
+ ns = cosv * pvecs[i][sv] - sinv * pvecs[i][tv];
+ nt = sinv * pvecs[i][sv] + cosv * pvecs[i][tv];
+ STfromXYZ[i][sv] = ns;
+ STfromXYZ[i][tv] = nt;
+ }
+
+ // scale
+ for (i=0 ; i<2 ; i++)
+ for (j=0 ; j<3 ; j++)
+ STfromXYZ[i][j] = STfromXYZ[i][j] / td->scale[i];
+
+ // shift
+ STfromXYZ[0][3] = td->shift[0];
+ STfromXYZ[1][3] = td->shift[1];
+
+ for (j=0 ; j<4 ; j++) {
+ STfromXYZ[0][j] /= q->width;
+ STfromXYZ[1][j] /= q->height;
+ }
+}
+
+/*
+================
+Face_MakePlane
+================
+*/
+void Face_MakePlane (face_t *f)
+{
+ int j;
+ vec3_t t1, t2, t3;
+
+ // convert to a vector / dist plane
+ for (j=0 ; j<3 ; j++)
+ {
+ t1[j] = f->planepts[0][j] - f->planepts[1][j];
+ t2[j] = f->planepts[2][j] - f->planepts[1][j];
+ t3[j] = f->planepts[1][j];
+ }
+
+ CrossProduct(t1,t2, f->plane.normal);
+ if (VectorCompare (f->plane.normal, vec3_origin))
+ printf ("WARNING: brush plane with no normal\n");
+ VectorNormalize (f->plane.normal);
+ f->plane.dist = DotProduct (t3, f->plane.normal);
+}
+
+/*
+================
+EmitTextureCoordinates
+================
+*/
+void EmitTextureCoordinates ( float *xyzst, qtexture_t *q, face_t *f)
+{
+ float STfromXYZ[2][4];
+
+ Face_TextureVectors (f, STfromXYZ);
+ xyzst[3] = DotProduct (xyzst, STfromXYZ[0]) + STfromXYZ[0][3];
+ xyzst[4] = DotProduct (xyzst, STfromXYZ[1]) + STfromXYZ[1][3];
+}
+
+//==========================================================================
+
+/*
+================
+Brush_MakeFacePlanes
+================
+*/
+void Brush_MakeFacePlanes (brush_t *b)
+{
+ face_t *f;
+
+ for (f=b->brush_faces ; f ; f=f->next)
+ {
+ Face_MakePlane (f);
+ }
+}
+
+/*
+================
+DrawBrushEntityName
+================
+*/
+void DrawBrushEntityName (brush_t *b)
+{
+ char *name;
+ //float a, s, c;
+ //vec3_t mid;
+ //int i;
+
+ if (!b->owner)
+ return; // during contruction
+
+ if (b->owner == world_entity)
+ return;
+
+ if (b != b->owner->brushes.onext)
+ return; // not key brush
+
+// MERGEME
+#if 0
+ if (!(g_qeglobals.d_savedinfo.exclude & EXCLUDE_ANGLES))
+ {
+ // draw the angle pointer
+ a = FloatForKey (b->owner, "angle");
+ if (a)
+ {
+ s = sin (a/180*Q_PI);
+ c = cos (a/180*Q_PI);
+ for (i=0 ; i<3 ; i++)
+ mid[i] = (b->mins[i] + b->maxs[i])*0.5;
+
+ qglBegin (GL_LINE_STRIP);
+ qglVertex3fv (mid);
+ mid[0] += c*8;
+ mid[1] += s*8;
+ mid[2] += s*8;
+ qglVertex3fv (mid);
+ mid[0] -= c*4;
+ mid[1] -= s*4;
+ mid[2] -= s*4;
+ mid[0] -= s*4;
+ mid[1] += c*4;
+ mid[2] += c*4;
+ qglVertex3fv (mid);
+ mid[0] += c*4;
+ mid[1] += s*4;
+ mid[2] += s*4;
+ mid[0] += s*4;
+ mid[1] -= c*4;
+ mid[2] -= c*4;
+ qglVertex3fv (mid);
+ mid[0] -= c*4;
+ mid[1] -= s*4;
+ mid[2] -= s*4;
+ mid[0] += s*4;
+ mid[1] -= c*4;
+ mid[2] -= c*4;
+ qglVertex3fv (mid);
+ qglEnd ();
+ }
+ }
+#endif
+
+ if (g_qeglobals.d_savedinfo.show_names)
+ {
+ name = ValueForKey (b->owner, "classname");
+ qglRasterPos3f (b->mins[0]+4, b->mins[1]+4, b->mins[2]+4);
+ qglCallLists (strlen(name), GL_UNSIGNED_BYTE, name);
+ }
+}
+
+/*
+=================
+Brush_MakeFaceWinding
+
+returns the visible polygon on a face
+=================
+*/
+winding_t *Brush_MakeFaceWinding (brush_t *b, face_t *face)
+{
+ winding_t *w;
+ face_t *clip;
+ plane_t plane;
+ qboolean past;
+
+ // get a poly that covers an effectively infinite area
+ w = Winding_BaseForPlane (&face->plane);
+
+ // chop the poly by all of the other faces
+ past = false;
+ for (clip = b->brush_faces ; clip && w ; clip=clip->next)
+ {
+ if (clip == face)
+ {
+ past = true;
+ continue;
+ }
+ if (DotProduct (face->plane.normal, clip->plane.normal) > 0.999
+ && fabs(face->plane.dist - clip->plane.dist) < 0.01 )
+ { // identical plane, use the later one
+ if (past)
+ {
+ free (w);
+ return NULL;
+ }
+ continue;
+ }
+
+ // flip the plane, because we want to keep the back side
+ VectorSubtract (vec3_origin,clip->plane.normal, plane.normal);
+ plane.dist = -clip->plane.dist;
+
+ w = Winding_Clip (w, &plane, false);
+ if (!w)
+ return w;
+ }
+
+ if (w->numpoints < 3)
+ {
+ free(w);
+ w = NULL;
+ }
+
+ if (!w)
+ printf ("unused plane\n");
+
+ return w;
+}
+
+/*
+=================
+Brush_SnapPlanepts
+=================
+*/
+void Brush_SnapPlanepts (brush_t *b)
+{
+ int i, j;
+ face_t *f;
+
+ if (g_PrefsDlg.m_bNoClamp)
+ return;
+
+ for (f=b->brush_faces ; f; f=f->next)
+ for (i=0 ; i<3 ; i++)
+ for (j=0 ; j<3 ; j++)
+ f->planepts[i][j] = floor (f->planepts[i][j] + 0.5);
+}
+
+/*
+** Brush_Build
+**
+** Builds a brush rendering data and also sets the min/max bounds
+*/
+// TTimo
+// added a bConvert flag to convert between old and new brush texture formats
+// TTimo
+// brush grouping: update the group treeview if necessary
+void Brush_Build( brush_t *b, bool bSnap, bool bMarkMap, bool bConvert )
+{
+ bool bLocalConvert;
+
+#ifdef _DEBUG
+ if (!g_qeglobals.m_bBrushPrimitMode && bConvert)
+ Sys_Printf("Warning : conversion from brush primitive to old brush format not implemented\n");
+#endif
+
+ // if bConvert is set and g_qeglobals.bNeedConvert is not, that just means we need convert for this brush only
+ if (bConvert && !g_qeglobals.bNeedConvert)
+ {
+ bLocalConvert = true;
+ g_qeglobals.bNeedConvert = true;
+ }
+
+ /*
+ ** build the windings and generate the bounding box
+ */
+ Brush_BuildWindings(b, bSnap);
+
+ Patch_BuildPoints (b);
+
+ /*
+ ** move the points and edges if in select mode
+ */
+ if (g_qeglobals.d_select_mode == sel_vertex || g_qeglobals.d_select_mode == sel_edge)
+ SetupVertexSelection ();
+
+ if (b->itemOwner == NULL)
+ Group_AddToProperGroup(b);
+
+ if (bMarkMap)
+ {
+ Sys_MarkMapModified();
+ }
+
+ if (bLocalConvert)
+ g_qeglobals.bNeedConvert = false;
+}
+
+/*
+==============
+Brush_SplitBrushByFace
+
+The incoming brush is NOT freed.
+The incoming face is NOT left referenced.
+==============
+*/
+void Brush_SplitBrushByFace (brush_t *in, face_t *f, brush_t **front, brush_t **back)
+{
+ brush_t *b;
+ face_t *nf;
+ vec3_t temp;
+
+ b = Brush_Clone (in);
+ nf = Face_Clone (f);
+
+ nf->texdef = b->brush_faces->texdef;
+ nf->next = b->brush_faces;
+ b->brush_faces = nf;
+
+ Brush_Build( b );
+ Brush_RemoveEmptyFaces ( b );
+ if ( !b->brush_faces )
+ { // completely clipped away
+ Brush_Free (b);
+ *back = NULL;
+ }
+ else
+ {
+ Entity_LinkBrush (in->owner, b);
+ *back = b;
+ }
+
+ b = Brush_Clone (in);
+ nf = Face_Clone (f);
+ // swap the plane winding
+ VectorCopy (nf->planepts[0], temp);
+ VectorCopy (nf->planepts[1], nf->planepts[0]);
+ VectorCopy (temp, nf->planepts[1]);
+
+ nf->texdef = b->brush_faces->texdef;
+ nf->next = b->brush_faces;
+ b->brush_faces = nf;
+
+ Brush_Build( b );
+ Brush_RemoveEmptyFaces ( b );
+ if ( !b->brush_faces )
+ { // completely clipped away
+ Brush_Free (b);
+ *front = NULL;
+ }
+ else
+ {
+ Entity_LinkBrush (in->owner, b);
+ *front = b;
+ }
+}
+
+/*
+=================
+Brush_BestSplitFace
+
+returns the best face to split the brush with.
+return NULL if the brush is convex
+=================
+*/
+face_t *Brush_BestSplitFace(brush_t *b)
+{
+ face_t *face, *f, *bestface;
+ winding_t *front, *back;
+ int splits, tinywindings, value, bestvalue;
+
+ bestvalue = 999999;
+ bestface = NULL;
+ for (face = b->brush_faces; face; face = face->next)
+ {
+ splits = 0;
+ tinywindings = 0;
+ for (f = b->brush_faces; f; f = f->next)
+ {
+ if (f == face) continue;
+ //
+ Winding_SplitEpsilon(f->face_winding, face->plane.normal, face->plane.dist, 0.1, &front, &back);
+
+ if (!front)
+ {
+ Winding_Free(back);
+ }
+ else if (!back)
+ {
+ Winding_Free(front);
+ }
+ else
+ {
+ splits++;
+ if (Winding_IsTiny(front)) tinywindings++;
+ if (Winding_IsTiny(back)) tinywindings++;
+ }
+ }
+ if (splits)
+ {
+ value = splits + 50 * tinywindings;
+ if (value < bestvalue)
+ {
+ bestvalue = value;
+ bestface = face;
+ }
+ }
+ }
+ return bestface;
+}
+
+/*
+=================
+Brush_MakeConvexBrushes
+
+MrE FIXME: this doesn't work because the old
+ Brush_SplitBrushByFace is used
+Turns the brush into a minimal number of convex brushes.
+If the input brush is convex then it will be returned.
+Otherwise the input brush will be freed.
+NOTE: the input brush should have windings for the faces.
+=================
+*/
+brush_t *Brush_MakeConvexBrushes(brush_t *b)
+{
+ brush_t *front, *back, *end;
+ face_t *face;
+
+ b->next = NULL;
+ face = Brush_BestSplitFace(b);
+ if (!face) return b;
+ Brush_SplitBrushByFace(b, face, &front, &back);
+ //this should never happen
+ if (!front && !back) return b;
+ Brush_Free(b);
+ if (!front)
+ return Brush_MakeConvexBrushes(back);
+ b = Brush_MakeConvexBrushes(front);
+ if (back)
+ {
+ for (end = b; end->next; end = end->next);
+ end->next = Brush_MakeConvexBrushes(back);
+ }
+ return b;
+}
+
+/*
+=================
+Brush_Convex
+=================
+*/
+int Brush_Convex(brush_t *b)
+{
+ face_t *face1, *face2;
+
+ for (face1 = b->brush_faces; face1; face1 = face1->next)
+ {
+ if (!face1->face_winding) continue;
+ for (face2 = b->brush_faces; face2; face2 = face2->next)
+ {
+ if (face1 == face2) continue;
+ if (!face2->face_winding) continue;
+ if (Winding_PlanesConcave(face1->face_winding, face2->face_winding,
+ face1->plane.normal, face2->plane.normal,
+ face1->plane.dist, face2->plane.dist))
+ {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+/*
+=================
+Brush_MoveVertexes_old1
+
+- The input brush must have face windings.
+- The input brush must be a brush with faces that do not intersect.
+- The input brush does not have to be convex.
+- The vertex will not be moved if the movement either causes the
+ brush to have faces that intersect or causes the brush to be
+ flipped inside out.
+ (For instance a tetrahedron can easily be flipped inside out
+ without having faces that intersect.)
+- The created brush does not have to be convex.
+- Returns true if the vertex movement is performed.
+=================
+*/
+
+#define MAX_MOVE_FACES 64
+#define INTERSECT_EPSILON 0.1
+#define POINT_EPSILON 0.3
+
+int Brush_MoveVertex_old1(brush_t *b, vec3_t vertex, vec3_t delta, vec3_t end, bool bSnap)
+{
+ face_t *f, *face, *newface, *lastface, *nextface;
+ face_t *movefaces[MAX_MOVE_FACES];
+ int movefacepoints[MAX_MOVE_FACES];
+ winding_t *w, tmpw;
+ int i, j, k, nummovefaces, result;
+ float dot;
+
+ result = false;
+ //
+ tmpw.numpoints = 3;
+ tmpw.maxpoints = 3;
+ VectorAdd(vertex, delta, end);
+ //snap or not?
+ if (bSnap)
+ for (i = 0; i < 3; i++)
+ end[i] = floor(end[i] / g_qeglobals.d_gridsize + 0.5) * g_qeglobals.d_gridsize;
+ //chop off triangles from all brush faces that use the to be moved vertex
+ //store pointers to these chopped off triangles in movefaces[]
+ nummovefaces = 0;
+ for (face = b->brush_faces; face; face = face->next)
+ {
+ w = face->face_winding;
+ if (!w) continue;
+ for (i = 0; i < w->numpoints; i++)
+ {
+ if (Point_Equal(w->points[i], vertex, POINT_EPSILON))
+ {
+ if (face->face_winding->numpoints <= 3)
+ {
+ movefacepoints[nummovefaces] = i;
+ movefaces[nummovefaces++] = face;
+ break;
+ }
+ dot = DotProduct(end, face->plane.normal) - face->plane.dist;
+ //if the end point is in front of the face plane
+ if (dot > 0.1)
+ {
+ //fanout triangle subdivision
+ for (k = i; k < i + w->numpoints-3; k++)
+ {
+ VectorCopy(w->points[i], tmpw.points[0]);
+ VectorCopy(w->points[(k+1) % w->numpoints], tmpw.points[1]);
+ VectorCopy(w->points[(k+2) % w->numpoints], tmpw.points[2]);
+ //
+ newface = Face_Clone(face);
+ //get the original
+ for (f = face; f->original; f = f->original) ;
+ newface->original = f;
+ //store the new winding
+ if (newface->face_winding) Winding_Free(newface->face_winding);
+ newface->face_winding = Winding_Clone(&tmpw);
+ //get the texture
+ newface->d_texture = Texture_ForName( newface->texdef.name );
+ //add the face to the brush
+ newface->next = b->brush_faces;
+ b->brush_faces = newface;
+ //add this new triangle to the move faces
+ movefacepoints[nummovefaces] = 0;
+ movefaces[nummovefaces++] = newface;
+ }
+ //give the original face a new winding
+ VectorCopy(w->points[(i-2+w->numpoints) % w->numpoints], tmpw.points[0]);
+ VectorCopy(w->points[(i-1+w->numpoints) % w->numpoints], tmpw.points[1]);
+ VectorCopy(w->points[i], tmpw.points[2]);
+ Winding_Free(face->face_winding);
+ face->face_winding = Winding_Clone(&tmpw);
+ //add the original face to the move faces
+ movefacepoints[nummovefaces] = 2;
+ movefaces[nummovefaces++] = face;
+ }
+ else
+ {
+ //chop a triangle off the face
+ VectorCopy(w->points[(i-1+w->numpoints) % w->numpoints], tmpw.points[0]);
+ VectorCopy(w->points[i], tmpw.points[1]);
+ VectorCopy(w->points[(i+1) % w->numpoints], tmpw.points[2]);
+ //remove the point from the face winding
+ Winding_RemovePoint(w, i);
+ //get texture crap right
+ Face_SetColor(b, face, 1.0);
+ for (j = 0; j < w->numpoints; j++)
+ EmitTextureCoordinates(w->points[j], face->d_texture, face);
+ //make a triangle face
+ newface = Face_Clone(face);
+ //get the original
+ for (f = face; f->original; f = f->original) ;
+ newface->original = f;
+ //store the new winding
+ if (newface->face_winding) Winding_Free(newface->face_winding);
+ newface->face_winding = Winding_Clone(&tmpw);
+ //get the texture
+ newface->d_texture = Texture_ForName( newface->texdef.name );
+ //add the face to the brush
+ newface->next = b->brush_faces;
+ b->brush_faces = newface;
+ //
+ movefacepoints[nummovefaces] = 1;
+ movefaces[nummovefaces++] = newface;
+ }
+ break;
+ }
+ }
+ }
+ //now movefaces contains pointers to triangle faces that
+ //contain the to be moved vertex
+
+ //check if the move is valid
+ int l;
+ vec3_t p1, p2;
+ winding_t *w2;
+ plane_t plane;
+
+ face = NULL;
+ VectorCopy(vertex, tmpw.points[1]);
+ VectorCopy(end, tmpw.points[2]);
+ for (face = b->brush_faces; face; face = face->next)
+ {
+ for (i = 0; i < nummovefaces; i++)
+ {
+ if (face == movefaces[i])
+ break;
+ }
+ if (i < nummovefaces)
+ continue;
+ //the delta vector may not intersect with any of the not move faces
+ if (Winding_VectorIntersect(face->face_winding, &face->plane, vertex, end, INTERSECT_EPSILON))
+ break;
+ //if the end point of the to be moved vertex is near this not move face
+ if (abs(DotProduct(face->plane.normal, end) - face->plane.dist) < 0.5)
+ {
+ //the end point may not be inside or very close to the not move face winding
+ if (Winding_PointInside(face->face_winding, &face->plane, end, 0.5))
+ break;
+ }
+ for (i = 0; i < nummovefaces; i++)
+ {
+ w = movefaces[i]->face_winding;
+ j = movefacepoints[i];
+ for (k = -1; k <= 1; k += 2)
+ {
+ //check if the new edge will not intersect with the not move face
+ VectorCopy(w->points[(j + k + w->numpoints) % w->numpoints], tmpw.points[0]);
+ if (Winding_VectorIntersect(face->face_winding, &face->plane, tmpw.points[0], end, INTERSECT_EPSILON))
+ {
+ //ok the new edge instersects with the not move face
+ //we can't perform the vertex movement
+ //break;
+ }
+ //check if the not move face intersects the "movement winding"
+ Winding_Plane(&tmpw, plane.normal, &plane.dist);
+ w2 = face->face_winding;
+ for (l = 0; l < w2->numpoints; l++)
+ {
+ VectorCopy(w2->points[l], p1);
+ if (Point_Equal(p1, tmpw.points[0], POINT_EPSILON)) continue;
+ VectorCopy(w2->points[(l+1) % w2->numpoints], p2);
+ if (Point_Equal(p2, tmpw.points[0], POINT_EPSILON)) continue;
+ if (Winding_VectorIntersect(&tmpw, &plane, p1, p2, INTERSECT_EPSILON))
+ break;
+ }
+ if (l < w2->numpoints)
+ {
+ //ok this not move face intersects the "movement winding"
+ //we can't perform the vertex movement
+ break;
+ }
+ }
+ if (k <= 1) break;
+ }
+ if (i < nummovefaces)
+ break;
+ }
+ if (!face)
+ {
+ //ok the move was valid
+ //now move all the vertexes of the movefaces
+ for (i = 0; i < nummovefaces; i++)
+ {
+ VectorCopy(end, movefaces[i]->face_winding->points[movefacepoints[i]]);
+ //create new face plane
+ for (j = 0; j < 3; j++)
+ {
+ VectorCopy(movefaces[i]->face_winding->points[j], movefaces[i]->planepts[j]);
+ }
+ Face_MakePlane(movefaces[i]);
+ }
+ result = true;
+ }
+ //get texture crap right
+ for (i = 0; i < nummovefaces; i++)
+ {
+ Face_SetColor(b, movefaces[i], 1.0);
+ for (j = 0; j < movefaces[i]->face_winding->numpoints; j++)
+ EmitTextureCoordinates(movefaces[i]->face_winding->points[j], movefaces[i]->d_texture, movefaces[i]);
+ }
+
+ //now try to merge faces with their original faces
+ lastface = NULL;
+ for (face = b->brush_faces; face; face = nextface)
+ {
+ nextface = face->next;
+ if (!face->original)
+ {
+ lastface = face;
+ continue;
+ }
+ if (!Plane_Equal(&face->plane, &face->original->plane, false))
+ {
+ lastface = face;
+ continue;
+ }
+ w = Winding_TryMerge(face->face_winding, face->original->face_winding, face->plane.normal, true);
+ if (!w)
+ {
+ lastface = face;
+ continue;
+ }
+ Winding_Free(face->original->face_winding);
+ face->original->face_winding = w;
+ //get texture crap right
+ Face_SetColor(b, face->original, 1.0);
+ for (j = 0; j < face->original->face_winding->numpoints; j++)
+ EmitTextureCoordinates(face->original->face_winding->points[j], face->original->d_texture, face->original);
+ //remove the face that was merged with the original
+ if (lastface) lastface->next = face->next;
+ else b->brush_faces = face->next;
+ Face_Free(face);
+ }
+ return result;
+}
+
+/*
+=================
+Brush_MoveVertexes_old2
+
+- The input brush must be convex
+- The input brush must have face windings.
+- The output brush will be convex.
+- Returns true if the vertex movement is performed.
+=================
+*/
+
+#define MAX_MOVE_FACES 64
+#define INTERSECT_EPSILON 0.1
+#define POINT_EPSILON 0.3
+
+int Brush_MoveVertex_old2(brush_t *b, vec3_t vertex, vec3_t delta, vec3_t end, bool bSnap)
+{
+ face_t *f, *face, *newface, *lastface, *nextface;
+ face_t *movefaces[MAX_MOVE_FACES];
+ int movefacepoints[MAX_MOVE_FACES];
+ winding_t *w, tmpw;
+ int i, j, k, nummovefaces, result;
+ float dot;
+
+ result = true;
+ //
+ tmpw.numpoints = 3;
+ tmpw.maxpoints = 3;
+ VectorAdd(vertex, delta, end);
+ //snap or not?
+ if (bSnap)
+ for (i = 0; i < 3; i++)
+ end[i] = floor(end[i] / g_qeglobals.d_gridsize + 0.5) * g_qeglobals.d_gridsize;
+ //chop off triangles from all brush faces that use the to be moved vertex
+ //store pointers to these chopped off triangles in movefaces[]
+ nummovefaces = 0;
+ for (face = b->brush_faces; face; face = face->next)
+ {
+ w = face->face_winding;
+ if (!w) continue;
+ for (i = 0; i < w->numpoints; i++)
+ {
+ if (Point_Equal(w->points[i], vertex, POINT_EPSILON))
+ {
+ if (face->face_winding->numpoints <= 3)
+ {
+ movefacepoints[nummovefaces] = i;
+ movefaces[nummovefaces++] = face;
+ break;
+ }
+ dot = DotProduct(end, face->plane.normal) - face->plane.dist;
+ //if the end point is in front of the face plane
+ if (dot > 0.1)
+ {
+ //fanout triangle subdivision
+ for (k = i; k < i + w->numpoints-3; k++)
+ {
+ VectorCopy(w->points[i], tmpw.points[0]);
+ VectorCopy(w->points[(k+1) % w->numpoints], tmpw.points[1]);
+ VectorCopy(w->points[(k+2) % w->numpoints], tmpw.points[2]);
+ //
+ newface = Face_Clone(face);
+ //get the original
+ for (f = face; f->original; f = f->original) ;
+ newface->original = f;
+ //store the new winding
+ if (newface->face_winding) Winding_Free(newface->face_winding);
+ newface->face_winding = Winding_Clone(&tmpw);
+ //get the texture
+ newface->d_texture = Texture_ForName( newface->texdef.name );
+ //add the face to the brush
+ newface->next = b->brush_faces;
+ b->brush_faces = newface;
+ //add this new triangle to the move faces
+ movefacepoints[nummovefaces] = 0;
+ movefaces[nummovefaces++] = newface;
+ }
+ //give the original face a new winding
+ VectorCopy(w->points[(i-2+w->numpoints) % w->numpoints], tmpw.points[0]);
+ VectorCopy(w->points[(i-1+w->numpoints) % w->numpoints], tmpw.points[1]);
+ VectorCopy(w->points[i], tmpw.points[2]);
+ Winding_Free(face->face_winding);
+ face->face_winding = Winding_Clone(&tmpw);
+ //add the original face to the move faces
+ movefacepoints[nummovefaces] = 2;
+ movefaces[nummovefaces++] = face;
+ }
+ else
+ {
+ //chop a triangle off the face
+ VectorCopy(w->points[(i-1+w->numpoints) % w->numpoints], tmpw.points[0]);
+ VectorCopy(w->points[i], tmpw.points[1]);
+ VectorCopy(w->points[(i+1) % w->numpoints], tmpw.points[2]);
+ //remove the point from the face winding
+ Winding_RemovePoint(w, i);
+ //get texture crap right
+ Face_SetColor(b, face, 1.0);
+ for (j = 0; j < w->numpoints; j++)
+ EmitTextureCoordinates(w->points[j], face->d_texture, face);
+ //make a triangle face
+ newface = Face_Clone(face);
+ //get the original
+ for (f = face; f->original; f = f->original) ;
+ newface->original = f;
+ //store the new winding
+ if (newface->face_winding) Winding_Free(newface->face_winding);
+ newface->face_winding = Winding_Clone(&tmpw);
+ //get the texture
+ newface->d_texture = Texture_ForName( newface->texdef.name );
+ //add the face to the brush
+ newface->next = b->brush_faces;
+ b->brush_faces = newface;
+ //
+ movefacepoints[nummovefaces] = 1;
+ movefaces[nummovefaces++] = newface;
+ }
+ break;
+ }
+ }
+ }
+ //now movefaces contains pointers to triangle faces that
+ //contain the to be moved vertex
+
+ //move the vertex
+ for (i = 0; i < nummovefaces; i++)
+ {
+ //move vertex to end position
+ VectorCopy(end, movefaces[i]->face_winding->points[movefacepoints[i]]);
+ //create new face plane
+ for (j = 0; j < 3; j++)
+ {
+ VectorCopy(movefaces[i]->face_winding->points[j], movefaces[i]->planepts[j]);
+ }
+ Face_MakePlane(movefaces[i]);
+ }
+ //if the brush is no longer convex
+ if (!Brush_Convex(b))
+ {
+ for (i = 0; i < nummovefaces; i++)
+ {
+ //move the vertex back to the initial position
+ VectorCopy(vertex, movefaces[i]->face_winding->points[movefacepoints[i]]);
+ //create new face plane
+ for (j = 0; j < 3; j++)
+ {
+ VectorCopy(movefaces[i]->face_winding->points[j], movefaces[i]->planepts[j]);
+ }
+ Face_MakePlane(movefaces[i]);
+ }
+ result = false;
+ }
+ //get texture crap right
+ for (i = 0; i < nummovefaces; i++)
+ {
+ Face_SetColor(b, movefaces[i], 1.0);
+ for (j = 0; j < movefaces[i]->face_winding->numpoints; j++)
+ EmitTextureCoordinates(movefaces[i]->face_winding->points[j], movefaces[i]->d_texture, movefaces[i]);
+ }
+
+ //now try to merge faces with their original faces
+ lastface = NULL;
+ for (face = b->brush_faces; face; face = nextface)
+ {
+ nextface = face->next;
+ if (!face->original)
+ {
+ lastface = face;
+ continue;
+ }
+ if (!Plane_Equal(&face->plane, &face->original->plane, false))
+ {
+ lastface = face;
+ continue;
+ }
+ w = Winding_TryMerge(face->face_winding, face->original->face_winding, face->plane.normal, true);
+ if (!w)
+ {
+ lastface = face;
+ continue;
+ }
+ Winding_Free(face->original->face_winding);
+ face->original->face_winding = w;
+ //get texture crap right
+ Face_SetColor(b, face->original, 1.0);
+ for (j = 0; j < face->original->face_winding->numpoints; j++)
+ EmitTextureCoordinates(face->original->face_winding->points[j], face->original->d_texture, face->original);
+ //remove the face that was merged with the original
+ if (lastface) lastface->next = face->next;
+ else b->brush_faces = face->next;
+ Face_Free(face);
+ }
+ return result;
+}
+
+/*
+=================
+Brush_MoveVertexes
+
+- The input brush must be convex
+- The input brush must have face windings.
+- The output brush will be convex.
+- Returns true if the WHOLE vertex movement is performed.
+=================
+*/
+
+#define MAX_MOVE_FACES 64
+
+int Brush_MoveVertex(brush_t *b, vec3_t vertex, vec3_t delta, vec3_t end, bool bSnap)
+{
+ face_t *f, *face, *newface, *lastface, *nextface;
+ face_t *movefaces[MAX_MOVE_FACES];
+ int movefacepoints[MAX_MOVE_FACES];
+ winding_t *w, tmpw;
+ vec3_t start, mid;
+ plane_t plane;
+ int i, j, k, nummovefaces, result, done;
+ float dot, front, back, frac, smallestfrac;
+
+ result = true;
+ //
+ tmpw.numpoints = 3;
+ tmpw.maxpoints = 3;
+ VectorCopy(vertex, start);
+ VectorAdd(vertex, delta, end);
+ //snap or not?
+ if (bSnap)
+ for (i = 0; i < 3; i++)
+ end[i] = floor(end[i] / g_qeglobals.d_gridsize + 0.5) * g_qeglobals.d_gridsize;
+ //
+ VectorCopy(end, mid);
+ //if the start and end are the same
+ if (Point_Equal(start, end, 0.3)) return false;
+ //the end point may not be the same as another vertex
+ for (face = b->brush_faces; face; face = face->next)
+ {
+ w = face->face_winding;
+ if (!w) continue;
+ for (i = 0; i < w->numpoints; i++)
+ {
+ if (Point_Equal(w->points[i], end, 0.3))
+ {
+ VectorCopy(vertex, end);
+ return false;
+ }
+ }
+ }
+ //
+ done = false;
+ while(!done)
+ {
+ //chop off triangles from all brush faces that use the to be moved vertex
+ //store pointers to these chopped off triangles in movefaces[]
+ nummovefaces = 0;
+ for (face = b->brush_faces; face; face = face->next)
+ {
+ w = face->face_winding;
+ if (!w) continue;
+ for (i = 0; i < w->numpoints; i++)
+ {
+ if (Point_Equal(w->points[i], start, 0.2))
+ {
+ if (face->face_winding->numpoints <= 3)
+ {
+ movefacepoints[nummovefaces] = i;
+ movefaces[nummovefaces++] = face;
+ break;
+ }
+ dot = DotProduct(end, face->plane.normal) - face->plane.dist;
+ //if the end point is in front of the face plane
+ if (dot > 0.1)
+ {
+ //fanout triangle subdivision
+ for (k = i; k < i + w->numpoints-3; k++)
+ {
+ VectorCopy(w->points[i], tmpw.points[0]);
+ VectorCopy(w->points[(k+1) % w->numpoints], tmpw.points[1]);
+ VectorCopy(w->points[(k+2) % w->numpoints], tmpw.points[2]);
+ //
+ newface = Face_Clone(face);
+ //get the original
+ for (f = face; f->original; f = f->original) ;
+ newface->original = f;
+ //store the new winding
+ if (newface->face_winding) Winding_Free(newface->face_winding);
+ newface->face_winding = Winding_Clone(&tmpw);
+ //get the texture
+ newface->d_texture = Texture_ForName( newface->texdef.name );
+ //add the face to the brush
+ newface->next = b->brush_faces;
+ b->brush_faces = newface;
+ //add this new triangle to the move faces
+ movefacepoints[nummovefaces] = 0;
+ movefaces[nummovefaces++] = newface;
+ }
+ //give the original face a new winding
+ VectorCopy(w->points[(i-2+w->numpoints) % w->numpoints], tmpw.points[0]);
+ VectorCopy(w->points[(i-1+w->numpoints) % w->numpoints], tmpw.points[1]);
+ VectorCopy(w->points[i], tmpw.points[2]);
+ Winding_Free(face->face_winding);
+ face->face_winding = Winding_Clone(&tmpw);
+ //add the original face to the move faces
+ movefacepoints[nummovefaces] = 2;
+ movefaces[nummovefaces++] = face;
+ }
+ else
+ {
+ //chop a triangle off the face
+ VectorCopy(w->points[(i-1+w->numpoints) % w->numpoints], tmpw.points[0]);
+ VectorCopy(w->points[i], tmpw.points[1]);
+ VectorCopy(w->points[(i+1) % w->numpoints], tmpw.points[2]);
+ //remove the point from the face winding
+ Winding_RemovePoint(w, i);
+ //get texture crap right
+ Face_SetColor(b, face, 1.0);
+ for (j = 0; j < w->numpoints; j++)
+ EmitTextureCoordinates(w->points[j], face->d_texture, face);
+ //make a triangle face
+ newface = Face_Clone(face);
+ //get the original
+ for (f = face; f->original; f = f->original) ;
+ newface->original = f;
+ //store the new winding
+ if (newface->face_winding) Winding_Free(newface->face_winding);
+ newface->face_winding = Winding_Clone(&tmpw);
+ //get the texture
+ newface->d_texture = Texture_ForName( newface->texdef.name );
+ //add the face to the brush
+ newface->next = b->brush_faces;
+ b->brush_faces = newface;
+ //
+ movefacepoints[nummovefaces] = 1;
+ movefaces[nummovefaces++] = newface;
+ }
+ break;
+ }
+ }
+ }
+ //now movefaces contains pointers to triangle faces that
+ //contain the to be moved vertex
+ //
+ done = true;
+ VectorCopy(end, mid);
+ smallestfrac = 1;
+ for (face = b->brush_faces; face; face = face->next)
+ {
+ //check if there is a move face that has this face as the original
+ for (i = 0; i < nummovefaces; i++)
+ {
+ if (movefaces[i]->original == face) break;
+ }
+ if (i >= nummovefaces) continue;
+ //check if the original is not a move face itself
+ for (j = 0; j < nummovefaces; j++)
+ {
+ if (face == movefaces[j]) break;
+ }
+ //if the original is not a move face itself
+ if (j >= nummovefaces)
+ {
+ memcpy(&plane, &movefaces[i]->original->plane, sizeof(plane_t));
+ }
+ else
+ {
+ k = movefacepoints[j];
+ w = movefaces[j]->face_winding;
+ VectorCopy(w->points[(k+1)%w->numpoints], tmpw.points[0]);
+ VectorCopy(w->points[(k+2)%w->numpoints], tmpw.points[1]);
+ //
+ k = movefacepoints[i];
+ w = movefaces[i]->face_winding;
+ VectorCopy(w->points[(k+1)%w->numpoints], tmpw.points[2]);
+ if (!Plane_FromPoints(tmpw.points[0], tmpw.points[1], tmpw.points[2], &plane))
+ {
+ VectorCopy(w->points[(k+2)%w->numpoints], tmpw.points[2]);
+ if (!Plane_FromPoints(tmpw.points[0], tmpw.points[1], tmpw.points[2], &plane))
+ //this should never happen otherwise the face merge did a crappy job a previous pass
+ continue;
+ }
+ }
+ //now we've got the plane to check agains
+ front = DotProduct(start, plane.normal) - plane.dist;
+ back = DotProduct(end, plane.normal) - plane.dist;
+ //if the whole move is at one side of the plane
+ if (front < 0.01 && back < 0.01) continue;
+ if (front > -0.01 && back > -0.01) continue;
+ //if there's no movement orthogonal to this plane at all
+ if (fabs(front-back) < 0.001) continue;
+ //ok first only move till the plane is hit
+ frac = front/(front-back);
+ if (frac < smallestfrac)
+ {
+ mid[0] = start[0] + (end[0] - start[0]) * frac;
+ mid[1] = start[1] + (end[1] - start[1]) * frac;
+ mid[2] = start[2] + (end[2] - start[2]) * frac;
+ smallestfrac = frac;
+ }
+ //
+ done = false;
+ }
+
+ //move the vertex
+ for (i = 0; i < nummovefaces; i++)
+ {
+ //move vertex to end position
+ VectorCopy(mid, movefaces[i]->face_winding->points[movefacepoints[i]]);
+ //create new face plane
+ for (j = 0; j < 3; j++)
+ {
+ VectorCopy(movefaces[i]->face_winding->points[j], movefaces[i]->planepts[j]);
+ }
+ Face_MakePlane(movefaces[i]);
+ if (VectorLength(movefaces[i]->plane.normal) < 0.1)
+ result = false;
+ }
+ //if the brush is no longer convex
+ if (!result || !Brush_Convex(b))
+ {
+ for (i = 0; i < nummovefaces; i++)
+ {
+ //move the vertex back to the initial position
+ VectorCopy(start, movefaces[i]->face_winding->points[movefacepoints[i]]);
+ //create new face plane
+ for (j = 0; j < 3; j++)
+ {
+ VectorCopy(movefaces[i]->face_winding->points[j], movefaces[i]->planepts[j]);
+ }
+ Face_MakePlane(movefaces[i]);
+ }
+ result = false;
+ VectorCopy(start, end);
+ done = true;
+ }
+ else
+ {
+ VectorCopy(mid, start);
+ }
+ //get texture crap right
+ for (i = 0; i < nummovefaces; i++)
+ {
+ Face_SetColor(b, movefaces[i], 1.0);
+ for (j = 0; j < movefaces[i]->face_winding->numpoints; j++)
+ EmitTextureCoordinates(movefaces[i]->face_winding->points[j], movefaces[i]->d_texture, movefaces[i]);
+ }
+
+ //now try to merge faces with their original faces
+ lastface = NULL;
+ for (face = b->brush_faces; face; face = nextface)
+ {
+ nextface = face->next;
+ if (!face->original)
+ {
+ lastface = face;
+ continue;
+ }
+ if (!Plane_Equal(&face->plane, &face->original->plane, false))
+ {
+ lastface = face;
+ continue;
+ }
+ w = Winding_TryMerge(face->face_winding, face->original->face_winding, face->plane.normal, true);
+ if (!w)
+ {
+ lastface = face;
+ continue;
+ }
+ Winding_Free(face->original->face_winding);
+ face->original->face_winding = w;
+ //get texture crap right
+ Face_SetColor(b, face->original, 1.0);
+ for (j = 0; j < face->original->face_winding->numpoints; j++)
+ EmitTextureCoordinates(face->original->face_winding->points[j], face->original->d_texture, face->original);
+ //remove the face that was merged with the original
+ if (lastface) lastface->next = face->next;
+ else b->brush_faces = face->next;
+ Face_Free(face);
+ }
+ }
+ return result;
+}
+
+/*
+=================
+Brush_InsertVertexBetween
+=================
+*/
+int Brush_InsertVertexBetween(brush_t *b, vec3_t p1, vec3_t p2)
+{
+ face_t *face;
+ winding_t *w, *neww;
+ vec3_t point;
+ int i, insert;
+
+ if (Point_Equal(p1, p2, 0.4))
+ return false;
+ VectorAdd(p1, p2, point);
+ VectorScale(point, 0.5, point);
+ insert = false;
+ //the end point may not be the same as another vertex
+ for (face = b->brush_faces; face; face = face->next)
+ {
+ w = face->face_winding;
+ if (!w) continue;
+ neww = NULL;
+ for (i = 0; i < w->numpoints; i++)
+ {
+ if (!Point_Equal(w->points[i], p1, 0.1))
+ continue;
+ if (Point_Equal(w->points[(i+1) % w->numpoints], p2, 0.1))
+ {
+ neww = Winding_InsertPoint(w, point, (i+1) % w->numpoints);
+ break;
+ }
+ else if (Point_Equal(w->points[(i-1+w->numpoints) % w->numpoints], p2, 0.3))
+ {
+ neww = Winding_InsertPoint(w, point, i);
+ break;
+ }
+ }
+ if (neww)
+ {
+ Winding_Free(face->face_winding);
+ face->face_winding = neww;
+ insert = true;
+ }
+ }
+ return insert;
+}
+
+
+/*
+=================
+Brush_ResetFaceOriginals
+=================
+*/
+void Brush_ResetFaceOriginals(brush_t *b)
+{
+ face_t *face;
+
+ for (face = b->brush_faces; face; face = face->next)
+ {
+ face->original = NULL;
+ }
+}
+
+/*
+=================
+Brush_Parse
+
+The brush is NOT linked to any list
+=================
+*/
+//++timo FIXME: when using old brush primitives, the test loop for "Brush" and "patchDef2" "patchDef3" is ran
+// before each face parsing. It works, but it's a performance hit
+brush_t *Brush_Parse (void)
+{
+ brush_t *b;
+ face_t *f;
+ int i,j;
+
+ g_qeglobals.d_parsed_brushes++;
+ b = Brush_Alloc();
+
+ do
+ {
+ if (!GetToken (true))
+ break;
+ if (!strcmp (token, "}") )
+ break;
+
+ // handle "Brush" primitive
+ if (strcmpi(token, "brushDef") == 0)
+ {
+ // Timo parsing new brush format
+ g_qeglobals.bPrimitBrushes=true;
+ // check the map is not mixing the two kinds of brushes
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ if (g_qeglobals.bOldBrushes)
+ Sys_Printf("Warning : old brushes and brush primitive in the same file are not allowed ( Brush_Parse )\n");
+ }
+ //++Timo write new brush primitive -> old conversion code for Q3->Q2 conversions ?
+ else
+ Sys_Printf("Warning : conversion code from brush primitive not done ( Brush_Parse )\n");
+
+ BrushPrimit_Parse(b);
+ if (b == NULL)
+ {
+ Warning ("parsing brush primitive");
+ return NULL;
+ }
+ else
+ {
+ continue;
+ }
+ }
+ if ( strcmpi( token, "terrainDef" ) == 0 )
+ {
+ free (b);
+
+ b = Terrain_Parse();
+ if (b == NULL)
+ {
+ Warning ("parsing terrain/brush");
+ return NULL;
+ }
+ else
+ {
+ continue;
+ }
+ }
+ if (strcmpi(token, "patchDef2") == 0 || strcmpi(token, "patchDef3") == 0)
+ {
+ free (b);
+
+ // double string compare but will go away soon
+ b = Patch_Parse(strcmpi(token, "patchDef2") == 0);
+ if (b == NULL)
+ {
+ Warning ("parsing patch/brush");
+ return NULL;
+ }
+ else
+ {
+ continue;
+ }
+ // handle inline patch
+ }
+ else
+ {
+ // Timo parsing old brush format
+ g_qeglobals.bOldBrushes=true;
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ // check the map is not mixing the two kinds of brushes
+ if (g_qeglobals.bPrimitBrushes)
+ Sys_Printf("Warning : old brushes and brush primitive in the same file are not allowed ( Brush_Parse )\n");
+ // set the "need" conversion flag
+ g_qeglobals.bNeedConvert=true;
+ }
+
+ f = Face_Alloc();
+
+ // add the brush to the end of the chain, so
+ // loading and saving a map doesn't reverse the order
+
+ f->next = NULL;
+ if (!b->brush_faces)
+ {
+ b->brush_faces = f;
+ }
+ else
+ {
+ face_t *scan;
+ for (scan=b->brush_faces ; scan->next ; scan=scan->next)
+ ;
+ scan->next = f;
+ }
+
+ // read the three point plane definition
+ for (i=0 ; i<3 ; i++)
+ {
+ if (i != 0)
+ GetToken (true);
+ if (strcmp (token, "(") )
+ {
+ Warning ("parsing brush");
+ return NULL;
+ }
+
+ for (j=0 ; j<3 ; j++)
+ {
+ GetToken (false);
+ f->planepts[i][j] = atof(token);
+ }
+
+ GetToken (false);
+ if (strcmp (token, ")") )
+ {
+ Warning ("parsing brush");
+ return NULL;
+ }
+ }
+ }
+
+ // Timo
+ // if we have a surface plugin, we'll call the plugin parsing
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+ GETPLUGINTEXDEF(f)->ParseTexdef();
+ }
+ else
+ {
+
+ // read the texturedef
+ GetToken (false);
+ f->texdef.SetName(token);
+ if (token[0] == '(')
+ {
+ int i = 32;
+ }
+ GetToken (false);
+ f->texdef.shift[0] = atoi(token);
+ GetToken (false);
+ f->texdef.shift[1] = atoi(token);
+ GetToken (false);
+ f->texdef.rotate = atoi(token);
+ GetToken (false);
+ f->texdef.scale[0] = atof(token);
+ GetToken (false);
+ f->texdef.scale[1] = atof(token);
+
+ // the flags and value field aren't necessarily present
+ f->d_texture = Texture_ForName( f->texdef.name );
+ f->texdef.flags = f->d_texture->flags;
+ f->texdef.value = f->d_texture->value;
+ f->texdef.contents = f->d_texture->contents;
+
+ if (TokenAvailable ())
+ {
+ GetToken (false);
+ f->texdef.contents = atoi(token);
+ GetToken (false);
+ f->texdef.flags = atoi(token);
+ GetToken (false);
+ f->texdef.value = atoi(token);
+ }
+
+ }
+ } while (1);
+
+ return b;
+}
+
+/*
+=================
+QERApp_MapPrintf_FILE
+callback for surface properties plugin
+must fit a PFN_QERAPP_MAPPRINTF ( see isurfaceplugin.h )
+=================
+*/
+// carefully initialize !
+FILE * g_File;
+void WINAPI QERApp_MapPrintf_FILE( char *text, ... )
+{
+ va_list argptr;
+ char buf[32768];
+
+ va_start (argptr,text);
+ vsprintf (buf, text,argptr);
+ va_end (argptr);
+
+ fprintf( g_File, buf );
+}
+
+
+/*
+==============
+Brush_SetEpair
+sets an epair for the given brush
+==============
+*/
+void Brush_SetEpair(brush_t *b, const char *pKey, const char *pValue)
+{
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ if (b->patchBrush)
+ {
+ Patch_SetEpair(b->pPatch, pKey, pValue);
+ }
+ else if (b->terrainBrush)
+ {
+ Terrain_SetEpair(b->pTerrain, pKey, pValue);
+ }
+ else
+ {
+ SetKeyValue(b->epairs, pKey, pValue);
+ }
+ }
+ else
+ {
+ Sys_Printf("Can only set key/values in Brush primitive mode\n");
+ }
+}
+
+/*
+=================
+Brush_GetKeyValue
+=================
+*/
+const char* Brush_GetKeyValue(brush_t *b, const char *pKey)
+{
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ if (b->patchBrush)
+ {
+ return Patch_GetKeyValue(b->pPatch, pKey);
+ }
+ else if (b->terrainBrush)
+ {
+ return Terrain_GetKeyValue(b->pTerrain, pKey);
+ }
+ else
+ {
+ return ValueForKey(b->epairs, pKey);
+ }
+ }
+ else
+ {
+ Sys_Printf("Can only set brush/patch key/values in Brush primitive mode\n");
+ }
+ return "";
+}
+
+/*
+=================
+Brush_Write
+save all brushes as Brush primitive format
+=================
+*/
+void Brush_Write (brush_t *b, FILE *f)
+{
+ epair_t *ep;
+ face_t *fa;
+ char *pname;
+ int i;
+
+ if (b->patchBrush)
+ {
+ Patch_Write(b->pPatch, f);
+ return;
+ }
+ if ( b->pTerrain )
+ {
+ Terrain_Write(b->pTerrain, f);
+ return;
+ }
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ // save brush primitive format
+ fprintf (f, "{\nbrushDef\n{\n");
+ // brush epairs
+ if (b->epairs)
+ for (ep = b->epairs ; ep ; ep=ep->next)
+ fprintf (f, "\"%s\" \"%s\"\n", ep->key, ep->value);
+ for (fa=b->brush_faces ; fa ; fa=fa->next)
+ {
+ // save planepts
+ for (i=0 ; i<3 ; i++)
+ {
+ fprintf(f, "( ");
+ for (int j = 0; j < 3; j++)
+ if (fa->planepts[i][j] == static_cast<int>(fa->planepts[i][j]))
+ fprintf(f, "%i ", static_cast<int>(fa->planepts[i][j]));
+ else
+ fprintf(f, "%f ", fa->planepts[i][j]);
+ fprintf(f, ") ");
+ }
+ // save texture coordinates
+ fprintf(f,"( ( ");
+ for (i=0 ; i<3 ; i++)
+ if (fa->brushprimit_texdef.coords[0][i] == static_cast<int>(fa->brushprimit_texdef.coords[0][i]))
+ fprintf(f,"%i ",static_cast<int>(fa->brushprimit_texdef.coords[0][i]));
+ else
+ fprintf(f,"%f ",fa->brushprimit_texdef.coords[0][i]);
+ fprintf(f,") ( ");
+ for (i=0 ; i<3 ; i++)
+ if (fa->brushprimit_texdef.coords[1][i] == static_cast<int>(fa->brushprimit_texdef.coords[1][i]))
+ fprintf(f,"%i ",static_cast<int>(fa->brushprimit_texdef.coords[1][i]));
+ else
+ fprintf(f,"%f ",fa->brushprimit_texdef.coords[1][i]);
+ fprintf(f,") ) ");
+ // save texture attribs
+ //++timo surface properties plugin not implemented for brush primitives
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ Sys_Printf("WARNING: surface properties plugin not supported with brush primitives (yet)\n");
+
+ char *pName = strlen(fa->texdef.name) > 0 ? fa->texdef.name : "unnamed";
+ fprintf(f, "%s ", pName );
+ fprintf(f, "%i %i %i\n", fa->texdef.contents, fa->texdef.flags, fa->texdef.value);
+ }
+ fprintf (f, "}\n}\n");
+ }
+ else
+ {
+ fprintf (f, "{\n");
+ for (fa=b->brush_faces ; fa ; fa=fa->next)
+ {
+ for (i=0 ; i<3 ; i++)
+ {
+ fprintf(f, "( ");
+ for (int j = 0; j < 3; j++)
+ {
+ if (fa->planepts[i][j] == static_cast<int>(fa->planepts[i][j]))
+ fprintf(f, "%i ", static_cast<int>(fa->planepts[i][j]));
+ else
+ fprintf(f, "%f ", fa->planepts[i][j]);
+ }
+ fprintf(f, ") ");
+ }
+
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+ g_File = f;
+#ifdef _DEBUG
+ if (!fa->pData)
+ Sys_Printf("ERROR: unexpected IPluginTexdef* is NULL in Brush_Write\n");
+ else
+#endif
+ GETPLUGINTEXDEF(fa)->WriteTexdef( QERApp_MapPrintf_FILE );
+ }
+ else
+ {
+ pname = fa->texdef.name;
+ if (pname[0] == 0)
+ pname = "unnamed";
+
+ fprintf (f, "%s %i %i %i ", pname,
+ (int)fa->texdef.shift[0], (int)fa->texdef.shift[1],
+ (int)fa->texdef.rotate);
+
+ if (fa->texdef.scale[0] == (int)fa->texdef.scale[0])
+ fprintf (f, "%i ", (int)fa->texdef.scale[0]);
+ else
+ fprintf (f, "%f ", (float)fa->texdef.scale[0]);
+ if (fa->texdef.scale[1] == (int)fa->texdef.scale[1])
+ fprintf (f, "%i", (int)fa->texdef.scale[1]);
+ else
+ fprintf (f, "%f", (float)fa->texdef.scale[1]);
+
+ fprintf (f, " %i %i %i", fa->texdef.contents, fa->texdef.flags, fa->texdef.value);
+ }
+ fprintf (f, "\n");
+ }
+ fprintf (f, "}\n");
+ }
+}
+
+/*
+=================
+QERApp_MapPrintf_MEMFILE
+callback for surface properties plugin
+must fit a PFN_QERAPP_MAPPRINTF ( see isurfaceplugin.h )
+=================
+*/
+// carefully initialize !
+CMemFile * g_pMemFile;
+void WINAPI QERApp_MapPrintf_MEMFILE( char *text, ... )
+{
+ va_list argptr;
+ char buf[32768];
+
+ va_start (argptr,text);
+ vsprintf (buf, text,argptr);
+ va_end (argptr);
+
+ MemFile_fprintf( g_pMemFile, buf );
+}
+
+/*
+=================
+Brush_Write to a CMemFile*
+save all brushes as Brush primitive format
+=================
+*/
+void Brush_Write (brush_t *b, CMemFile *pMemFile)
+{
+ epair_t *ep;
+ face_t *fa;
+ char *pname;
+ int i;
+
+ if (b->patchBrush)
+ {
+ Patch_Write(b->pPatch, pMemFile);
+ return;
+ }
+ if (b->terrainBrush)
+ {
+ Terrain_Write(b->pTerrain, pMemFile);
+ return;
+ }
+ //++timo NOTE: it's not very difficult to add since the surface properties plugin
+ // writes throught a printf-style function prototype
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+ Sys_Printf("WARNING: Brush_Write to a CMemFile and Surface Properties plugin not done\n");
+ }
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ // brush primitive format
+ MemFile_fprintf (pMemFile, "{\nBrushDef\n{\n");
+ // brush epairs
+ if (b->epairs)
+ for( ep = b->epairs ; ep ; ep=ep->next )
+ MemFile_fprintf (pMemFile, "\"%s\" \"%s\"\n", ep->key, ep->value );
+ for (fa=b->brush_faces ; fa ; fa=fa->next)
+ {
+ // save planepts
+ for (i=0 ; i<3 ; i++)
+ {
+ MemFile_fprintf(pMemFile, "( ");
+ for (int j = 0; j < 3; j++)
+ if (fa->planepts[i][j] == static_cast<int>(fa->planepts[i][j]))
+ MemFile_fprintf(pMemFile, "%i ", static_cast<int>(fa->planepts[i][j]));
+ else
+ MemFile_fprintf(pMemFile, "%f ", fa->planepts[i][j]);
+ MemFile_fprintf(pMemFile, ") ");
+ }
+ // save texture coordinates
+ MemFile_fprintf(pMemFile,"( ( ");
+ for (i=0 ; i<3 ; i++)
+ if (fa->brushprimit_texdef.coords[0][i] == static_cast<int>(fa->brushprimit_texdef.coords[0][i]))
+ MemFile_fprintf(pMemFile,"%i ",static_cast<int>(fa->brushprimit_texdef.coords[0][i]));
+ else
+ MemFile_fprintf(pMemFile,"%f ",fa->brushprimit_texdef.coords[0][i]);
+ MemFile_fprintf(pMemFile,") ( ");
+ for (i=0 ; i<3 ; i++)
+ if (fa->brushprimit_texdef.coords[1][i] == static_cast<int>(fa->brushprimit_texdef.coords[1][i]))
+ MemFile_fprintf(pMemFile,"%i ",static_cast<int>(fa->brushprimit_texdef.coords[1][i]));
+ else
+ MemFile_fprintf(pMemFile,"%f ",fa->brushprimit_texdef.coords[1][i]);
+ MemFile_fprintf(pMemFile,") ) ");
+ // save texture attribs
+ char *pName = strlen(fa->texdef.name) > 0 ? fa->texdef.name : "unnamed";
+ MemFile_fprintf(pMemFile, "%s ", pName);
+ MemFile_fprintf(pMemFile, "%i %i %i\n", fa->texdef.contents, fa->texdef.flags, fa->texdef.value);
+ }
+ MemFile_fprintf (pMemFile, "}\n}\n");
+ }
+ else
+ {
+ // old brushes format
+ // also handle surface properties plugin
+ MemFile_fprintf (pMemFile, "{\n");
+ for (fa=b->brush_faces ; fa ; fa=fa->next)
+ {
+ for (i=0 ; i<3 ; i++)
+ {
+ MemFile_fprintf(pMemFile, "( ");
+ for (int j = 0; j < 3; j++)
+ {
+ if (fa->planepts[i][j] == static_cast<int>(fa->planepts[i][j]))
+ MemFile_fprintf(pMemFile, "%i ", static_cast<int>(fa->planepts[i][j]));
+ else
+ MemFile_fprintf(pMemFile, "%f ", fa->planepts[i][j]);
+ }
+ MemFile_fprintf(pMemFile, ") ");
+ }
+
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+ g_pMemFile = pMemFile;
+#ifdef _DEBUG
+ if (!fa->pData)
+ Sys_Printf("ERROR: unexpected IPluginTexdef* is NULL in Brush_Write\n");
+ else
+#endif
+ GETPLUGINTEXDEF(fa)->WriteTexdef( QERApp_MapPrintf_MEMFILE );
+ }
+ else
+ {
+ pname = fa->texdef.name;
+ if (pname[0] == 0)
+ pname = "unnamed";
+
+ MemFile_fprintf (pMemFile, "%s %i %i %i ", pname,
+ (int)fa->texdef.shift[0], (int)fa->texdef.shift[1],
+ (int)fa->texdef.rotate);
+
+ if (fa->texdef.scale[0] == (int)fa->texdef.scale[0])
+ MemFile_fprintf (pMemFile, "%i ", (int)fa->texdef.scale[0]);
+ else
+ MemFile_fprintf (pMemFile, "%f ", (float)fa->texdef.scale[0]);
+ if (fa->texdef.scale[1] == (int)fa->texdef.scale[1])
+ MemFile_fprintf (pMemFile, "%i", (int)fa->texdef.scale[1]);
+ else
+ MemFile_fprintf (pMemFile, "%f", (float)fa->texdef.scale[1]);
+
+ MemFile_fprintf (pMemFile, " %i %i %i", fa->texdef.contents, fa->texdef.flags, fa->texdef.value);
+ }
+ MemFile_fprintf (pMemFile, "\n");
+ }
+ MemFile_fprintf (pMemFile, "}\n");
+ }
+
+
+}
+
+
+/*
+=============
+Brush_Create
+
+Create non-textured blocks for entities
+The brush is NOT linked to any list
+=============
+*/
+brush_t *Brush_Create (vec3_t mins, vec3_t maxs, texdef_t *texdef)
+{
+ int i, j;
+ vec3_t pts[4][2];
+ face_t *f;
+ brush_t *b;
+
+ // brush primitive mode : convert texdef to brushprimit_texdef ?
+ // most of the time texdef is empty
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ // check texdef is empty .. if there are cases it's not we need to write some conversion code
+ if (texdef->shift[0]!=0 || texdef->shift[1]!=0 || texdef->scale[0]!=0 || texdef->scale[1]!=0 || texdef->rotate!=0)
+ Sys_Printf("Warning : non-zero texdef detected in Brush_Create .. need brush primitive conversion\n");
+ }
+
+ for (i=0 ; i<3 ; i++)
+ {
+ if (maxs[i] < mins[i])
+ Error ("Brush_InitSolid: backwards");
+ }
+
+ b = Brush_Alloc();
+
+ pts[0][0][0] = mins[0];
+ pts[0][0][1] = mins[1];
+
+ pts[1][0][0] = mins[0];
+ pts[1][0][1] = maxs[1];
+
+ pts[2][0][0] = maxs[0];
+ pts[2][0][1] = maxs[1];
+
+ pts[3][0][0] = maxs[0];
+ pts[3][0][1] = mins[1];
+
+ for (i=0 ; i<4 ; i++)
+ {
+ pts[i][0][2] = mins[2];
+ pts[i][1][0] = pts[i][0][0];
+ pts[i][1][1] = pts[i][0][1];
+ pts[i][1][2] = maxs[2];
+ }
+
+ for (i=0 ; i<4 ; i++)
+ {
+ f = Face_Alloc();
+ f->texdef = *texdef;
+ f->texdef.flags &= ~SURF_KEEP;
+ f->texdef.contents &= ~CONTENTS_KEEP;
+ f->next = b->brush_faces;
+ b->brush_faces = f;
+ j = (i+1)%4;
+
+ VectorCopy (pts[j][1], f->planepts[0]);
+ VectorCopy (pts[i][1], f->planepts[1]);
+ VectorCopy (pts[i][0], f->planepts[2]);
+ }
+
+ f = Face_Alloc();
+ f->texdef = *texdef;
+ f->texdef.flags &= ~SURF_KEEP;
+ f->texdef.contents &= ~CONTENTS_KEEP;
+ f->next = b->brush_faces;
+ b->brush_faces = f;
+
+ VectorCopy (pts[0][1], f->planepts[0]);
+ VectorCopy (pts[1][1], f->planepts[1]);
+ VectorCopy (pts[2][1], f->planepts[2]);
+
+ f = Face_Alloc();
+ f->texdef = *texdef;
+ f->texdef.flags &= ~SURF_KEEP;
+ f->texdef.contents &= ~CONTENTS_KEEP;
+ f->next = b->brush_faces;
+ b->brush_faces = f;
+
+ VectorCopy (pts[2][0], f->planepts[0]);
+ VectorCopy (pts[1][0], f->planepts[1]);
+ VectorCopy (pts[0][0], f->planepts[2]);
+
+ return b;
+}
+
+/*
+=============
+Brush_CreatePyramid
+
+Create non-textured pyramid for light entities
+The brush is NOT linked to any list
+=============
+*/
+brush_t *Brush_CreatePyramid (vec3_t mins, vec3_t maxs, texdef_t *texdef)
+{
+ //++timo handle new brush primitive ? return here ??
+ return Brush_Create(mins, maxs, texdef);
+
+ for (int i=0 ; i<3 ; i++)
+ if (maxs[i] < mins[i])
+ Error ("Brush_InitSolid: backwards");
+
+ brush_t* b = Brush_Alloc();
+
+ vec3_t corners[4];
+
+ float fMid = Q_rint(mins[2] + (Q_rint((maxs[2] - mins[2]) / 2)));
+
+ corners[0][0] = mins[0];
+ corners[0][1] = mins[1];
+ corners[0][2] = fMid;
+
+ corners[1][0] = mins[0];
+ corners[1][1] = maxs[1];
+ corners[1][2] = fMid;
+
+ corners[2][0] = maxs[0];
+ corners[2][1] = maxs[1];
+ corners[2][2] = fMid;
+
+ corners[3][0] = maxs[0];
+ corners[3][1] = mins[1];
+ corners[3][2] = fMid;
+
+ vec3_t top, bottom;
+
+ top[0] = Q_rint(mins[0] + ((maxs[0] - mins[0]) / 2));
+ top[1] = Q_rint(mins[1] + ((maxs[1] - mins[1]) / 2));
+ top[2] = Q_rint(maxs[2]);
+
+ VectorCopy(top, bottom);
+ bottom[2] = mins[2];
+
+ // sides
+ for (i = 0; i < 4; i++)
+ {
+ face_t* f = Face_Alloc();
+ f->texdef = *texdef;
+ f->texdef.flags &= ~SURF_KEEP;
+ f->texdef.contents &= ~CONTENTS_KEEP;
+ f->next = b->brush_faces;
+ b->brush_faces = f;
+ int j = (i+1)%4;
+
+ VectorCopy (top, f->planepts[0]);
+ VectorCopy (corners[i], f->planepts[1]);
+ VectorCopy(corners[j], f->planepts[2]);
+
+ f = Face_Alloc();
+ f->texdef = *texdef;
+ f->texdef.flags &= ~SURF_KEEP;
+ f->texdef.contents &= ~CONTENTS_KEEP;
+ f->next = b->brush_faces;
+ b->brush_faces = f;
+
+ VectorCopy (bottom, f->planepts[2]);
+ VectorCopy (corners[i], f->planepts[1]);
+ VectorCopy(corners[j], f->planepts[0]);
+ }
+
+ return b;
+}
+
+
+
+
+/*
+=============
+Brush_MakeSided
+
+Makes the current brush have the given number of 2d sides
+=============
+*/
+void Brush_MakeSided (int sides)
+{
+ int i, axis;
+ vec3_t mins, maxs;
+ brush_t *b;
+ texdef_t *texdef;
+ face_t *f;
+ vec3_t mid;
+ float width;
+ float sv, cv;
+
+ if (sides < 3)
+ {
+ Sys_Status ("Bad sides number", 0);
+ return;
+ }
+
+ if (sides >= MAX_POINTS_ON_WINDING-4)
+ {
+ Sys_Printf("too many sides.\n");
+ return;
+ }
+
+ if (!QE_SingleBrush ())
+ {
+ Sys_Status ("Must have a single brush selected", 0 );
+ return;
+ }
+
+ b = selected_brushes.next;
+ VectorCopy (b->mins, mins);
+ VectorCopy (b->maxs, maxs);
+ texdef = &g_qeglobals.d_texturewin.texdef;
+
+ Brush_Free (b);
+
+ if (g_pParentWnd->ActiveXY())
+ {
+ switch(g_pParentWnd->ActiveXY()->GetViewType())
+ {
+ case XY: axis = 2; break;
+ case XZ: axis = 1; break;
+ case YZ: axis = 0; break;
+ }
+ }
+ else
+ {
+ axis = 2;
+ }
+
+ // find center of brush
+ width = 8;
+ for (i = 0; i < 3; i++)
+ {
+ mid[i] = (maxs[i] + mins[i]) * 0.5;
+ if (i == axis) continue;
+ if ((maxs[i] - mins[i]) * 0.5 > width)
+ width = (maxs[i] - mins[i]) * 0.5;
+ }
+
+ b = Brush_Alloc();
+
+ // create top face
+ f = Face_Alloc();
+ f->texdef = *texdef;
+ f->next = b->brush_faces;
+ b->brush_faces = f;
+
+ f->planepts[2][(axis+1)%3] = mins[(axis+1)%3]; f->planepts[2][(axis+2)%3] = mins[(axis+2)%3]; f->planepts[2][axis] = maxs[axis];
+ f->planepts[1][(axis+1)%3] = maxs[(axis+1)%3]; f->planepts[1][(axis+2)%3] = mins[(axis+2)%3]; f->planepts[1][axis] = maxs[axis];
+ f->planepts[0][(axis+1)%3] = maxs[(axis+1)%3]; f->planepts[0][(axis+2)%3] = maxs[(axis+2)%3]; f->planepts[0][axis] = maxs[axis];
+
+ // create bottom face
+ f = Face_Alloc();
+ f->texdef = *texdef;
+ f->next = b->brush_faces;
+ b->brush_faces = f;
+
+ f->planepts[0][(axis+1)%3] = mins[(axis+1)%3]; f->planepts[0][(axis+2)%3] = mins[(axis+2)%3]; f->planepts[0][axis] = mins[axis];
+ f->planepts[1][(axis+1)%3] = maxs[(axis+1)%3]; f->planepts[1][(axis+2)%3] = mins[(axis+2)%3]; f->planepts[1][axis] = mins[axis];
+ f->planepts[2][(axis+1)%3] = maxs[(axis+1)%3]; f->planepts[2][(axis+2)%3] = maxs[(axis+2)%3]; f->planepts[2][axis] = mins[axis];
+
+ for (i=0 ; i<sides ; i++)
+ {
+ f = Face_Alloc();
+ f->texdef = *texdef;
+ f->next = b->brush_faces;
+ b->brush_faces = f;
+
+ sv = sin (i*3.14159265*2/sides);
+ cv = cos (i*3.14159265*2/sides);
+
+ f->planepts[0][(axis+1)%3] = floor(mid[(axis+1)%3]+width*cv+0.5);
+ f->planepts[0][(axis+2)%3] = floor(mid[(axis+2)%3]+width*sv+0.5);
+ f->planepts[0][axis] = mins[axis];
+
+ f->planepts[1][(axis+1)%3] = f->planepts[0][(axis+1)%3];
+ f->planepts[1][(axis+2)%3] = f->planepts[0][(axis+2)%3];
+ f->planepts[1][axis] = maxs[axis];
+
+ f->planepts[2][(axis+1)%3] = floor(f->planepts[0][(axis+1)%3] - width*sv + 0.5);
+ f->planepts[2][(axis+2)%3] = floor(f->planepts[0][(axis+2)%3] + width*cv + 0.5);
+ f->planepts[2][axis] = maxs[axis];
+ }
+
+ Brush_AddToList (b, &selected_brushes);
+
+ Entity_LinkBrush (world_entity, b);
+
+ Brush_Build( b );
+
+ Sys_UpdateWindows (W_ALL);
+}
+
+
+
+/*
+=============
+Brush_Free
+
+Frees the brush with all of its faces and display list.
+Unlinks the brush from whichever chain it is in.
+Decrements the owner entity's brushcount.
+Removes owner entity if this was the last brush
+unless owner is the world.
+Removes from groups
+=============
+*/
+void Brush_Free (brush_t *b, bool bRemoveNode)
+{
+ face_t *f, *next;
+ epair_t *ep, *enext;
+
+ // remove from group
+ if (bRemoveNode)
+ Group_RemoveBrush(b);
+
+ // free the patch if it's there
+ if (b->patchBrush)
+ {
+ Patch_Delete(b->pPatch);
+ }
+
+ if( b->terrainBrush )
+ {
+ Terrain_Delete( b->pTerrain );
+ }
+
+ // free faces
+ for (f=b->brush_faces ; f ; f=next)
+ {
+ next = f->next;
+ Face_Free( f );
+ }
+
+ //Timo : free brush epairs
+ for (ep = b->epairs ; ep ; ep=enext )
+ {
+ enext = ep->next;
+ free (ep->key);
+ free (ep->value);
+ free (ep);
+ }
+
+ // unlink from active/selected list
+ if (b->next)
+ Brush_RemoveFromList (b);
+
+ // unlink from entity list
+ if (b->onext)
+ Entity_UnlinkBrush (b);
+
+ free (b);
+}
+
+/*
+=============
+Face_MemorySize
+=============
+*/
+int Face_MemorySize(face_t *f )
+{
+ int size = 0;
+
+ if (f->face_winding)
+ {
+ size += _msize(f->face_winding);
+ }
+ //f->texdef.~texdef_t();;
+ size += _msize(f);
+ return size;
+}
+
+/*
+=============
+Brush_MemorySize
+=============
+*/
+int Brush_MemorySize(brush_t *b)
+{
+ face_t *f;
+ epair_t *ep;
+ int size = 0;
+
+ //
+ if (b->patchBrush)
+ {
+ size += Patch_MemorySize(b->pPatch);
+ }
+ if (b->terrainBrush)
+ {
+ size += Terrain_MemorySize(b->pTerrain);
+ }
+ //
+ for (f = b->brush_faces; f; f = f->next)
+ {
+ size += Face_MemorySize(f);
+ }
+ //
+ for (ep = b->epairs; ep; ep = ep->next )
+ {
+ size += _msize(ep->key);
+ size += _msize(ep->value);
+ size += _msize(ep);
+ }
+ size += _msize(b);
+ return size;
+}
+
+
+/*
+============
+Brush_Clone
+
+Does NOT add the new brush to any lists
+============
+*/
+brush_t *Brush_Clone (brush_t *b)
+{
+ brush_t *n = NULL;
+ face_t *f, *nf;
+
+ if (b->patchBrush)
+ {
+ patchMesh_t *p = Patch_Duplicate(b->pPatch);
+ Brush_RemoveFromList(p->pSymbiot);
+ Entity_UnlinkBrush(p->pSymbiot);
+ n = p->pSymbiot;
+ }
+ else if (b->terrainBrush)
+ {
+ terrainMesh_t *p = Terrain_Duplicate(b->pTerrain);
+ Brush_RemoveFromList(p->pSymbiot);
+ Entity_UnlinkBrush(p->pSymbiot);
+ n = p->pSymbiot;
+ }
+ else
+ {
+ n = Brush_Alloc();
+ n->numberId = g_nBrushId++;
+ n->owner = b->owner;
+ for (f=b->brush_faces ; f ; f=f->next)
+ {
+ nf = Face_Clone( f );
+ nf->next = n->brush_faces;
+ n->brush_faces = nf;
+ }
+ }
+
+ return n;
+}
+
+
+
+/*
+============
+Brush_Clone
+
+Does NOT add the new brush to any lists
+============
+*/
+brush_t *Brush_FullClone(brush_t *b)
+{
+ brush_t *n = NULL;
+ face_t *f, *nf, *f2, *nf2;
+ int j;
+
+ if (b->patchBrush)
+ {
+ patchMesh_t *p = Patch_Duplicate(b->pPatch);
+ Brush_RemoveFromList(p->pSymbiot);
+ Entity_UnlinkBrush(p->pSymbiot);
+ n = p->pSymbiot;
+ n->owner = b->owner;
+ Brush_Build(n);
+ }
+ else if (b->terrainBrush)
+ {
+ terrainMesh_t *p = Terrain_Duplicate(b->pTerrain);
+ Brush_RemoveFromList(p->pSymbiot);
+ Entity_UnlinkBrush(p->pSymbiot);
+ n = p->pSymbiot;
+ n->owner = b->owner;
+ Brush_Build(n);
+ }
+ else
+ {
+ n = Brush_Alloc();
+ n->numberId = g_nBrushId++;
+ n->owner = b->owner;
+ VectorCopy(b->mins, n->mins);
+ VectorCopy(b->maxs, n->maxs);
+ //
+ for (f = b->brush_faces; f; f = f->next)
+ {
+ if (f->original) continue;
+ nf = Face_FullClone(f);
+ nf->next = n->brush_faces;
+ n->brush_faces = nf;
+ //copy all faces that have the original set to this face
+ for (f2 = b->brush_faces; f2; f2 = f2->next)
+ {
+ if (f2->original == f)
+ {
+ nf2 = Face_FullClone(f2);
+ nf2->next = n->brush_faces;
+ n->brush_faces = nf2;
+ //set original
+ nf2->original = nf;
+ }
+ }
+ }
+ for (nf = n->brush_faces; nf; nf = nf->next)
+ {
+ Face_SetColor(n, nf, 1.0);
+ if (nf->face_winding)
+ {
+ if (g_qeglobals.m_bBrushPrimitMode)
+ EmitBrushPrimitTextureCoordinates(nf,nf->face_winding);
+ else
+ {
+ for (j = 0; j < nf->face_winding->numpoints; j++)
+ EmitTextureCoordinates(nf->face_winding->points[j], nf->d_texture, nf);
+ }
+ }
+ }
+ }
+ return n;
+}
+
+/*
+==============
+Brush_Ray
+
+Itersects a ray with a brush
+Returns the face hit and the distance along the ray the intersection occured at
+Returns NULL and 0 if not hit at all
+==============
+*/
+face_t *Brush_Ray (vec3_t origin, vec3_t dir, brush_t *b, float *dist)
+{
+ face_t *f, *firstface;
+ vec3_t p1, p2;
+ float frac, d1, d2;
+ int i;
+
+ VectorCopy (origin, p1);
+ for (i=0 ; i<3 ; i++)
+ p2[i] = p1[i] + dir[i]*16384;
+
+ for (f=b->brush_faces ; f ; f=f->next)
+ {
+ d1 = DotProduct (p1, f->plane.normal) - f->plane.dist;
+ d2 = DotProduct (p2, f->plane.normal) - f->plane.dist;
+ if (d1 >= 0 && d2 >= 0)
+ {
+ *dist = 0;
+ return NULL; // ray is on front side of face
+ }
+ if (d1 <=0 && d2 <= 0)
+ continue;
+ // clip the ray to the plane
+ frac = d1 / (d1 - d2);
+ if (d1 > 0)
+ {
+ firstface = f;
+ for (i=0 ; i<3 ; i++)
+ p1[i] = p1[i] + frac *(p2[i] - p1[i]);
+ }
+ else
+ {
+ for (i=0 ; i<3 ; i++)
+ p2[i] = p1[i] + frac *(p2[i] - p1[i]);
+ }
+ }
+
+ // find distance p1 is along dir
+ VectorSubtract (p1, origin, p1);
+ d1 = DotProduct (p1, dir);
+
+ *dist = d1;
+
+ return firstface;
+}
+
+//PGM
+face_t *Brush_Point (vec3_t origin, brush_t *b)
+{
+ face_t *f;
+ float d1;
+
+ for (f=b->brush_faces ; f ; f=f->next)
+ {
+ d1 = DotProduct (origin, f->plane.normal) - f->plane.dist;
+ if (d1 > 0)
+ {
+ return NULL; // point is on front side of face
+ }
+ }
+
+ return b->brush_faces;
+}
+//PGM
+
+
+void Brush_AddToList (brush_t *b, brush_t *list)
+{
+ if (b->next || b->prev)
+ Error ("Brush_AddToList: allready linked");
+
+ if (list == &selected_brushes || list == &active_brushes)
+ {
+ if (b->patchBrush && list == &selected_brushes)
+ {
+ Patch_Select(b->pPatch);
+ }
+ if (b->terrainBrush && list == &selected_brushes) {
+ Terrain_Select(b->pTerrain);
+ }
+ }
+ b->next = list->next;
+ list->next->prev = b;
+ list->next = b;
+ b->prev = list;
+
+ // TTimo messaging
+ DispatchRadiantMsg( RADIANT_SELECTION );
+}
+
+void Brush_RemoveFromList (brush_t *b)
+{
+ if (!b->next || !b->prev)
+ Error ("Brush_RemoveFromList: not linked");
+
+ if (b->patchBrush)
+ {
+ Patch_Deselect(b->pPatch);
+ //Patch_Deselect(b->nPatchID);
+ }
+ if (b->terrainBrush)
+ {
+ Terrain_Deselect(b->pTerrain);
+ }
+
+ b->next->prev = b->prev;
+ b->prev->next = b->next;
+ b->next = b->prev = NULL;
+}
+
+/*
+===============
+SetFaceTexdef
+
+Doesn't set the curve flags
+
+NOTE : ( TTimo )
+ never trust f->d_texture here, f->texdef and f->d_texture are out of sync when called by Brush_SetTexture
+ use Texture_ForName() to find the right shader
+ FIXME : send the right shader ( qtexture_t * ) in the parameters ?
+
+TTimo: surface plugin, added an IPluginTexdef* parameter
+ if not NULL, get ->Copy() of it into the face ( and remember to hook )
+ if NULL, ask for a default
+===============
+*/
+void SetFaceTexdef (brush_t *b, face_t *f, texdef_t *texdef, brushprimit_texdef_t *brushprimit_texdef, bool bFitScale, IPluginTexdef* pPlugTexdef) {
+ int oldFlags;
+ int oldContents;
+ face_t *tf;
+
+ oldFlags = f->texdef.flags;
+ oldContents = f->texdef.contents;
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ f->texdef = *texdef;
+ ConvertTexMatWithQTexture( brushprimit_texdef, NULL, &f->brushprimit_texdef, Texture_ForName( f->texdef.name ) );
+ }
+ else
+ if (bFitScale)
+ {
+ f->texdef = *texdef;
+ // fit the scaling of the texture on the actual plane
+ vec3_t p1,p2,p3; // absolute coordinates
+ // compute absolute coordinates
+ ComputeAbsolute(f,p1,p2,p3);
+ // compute the scale
+ vec3_t vx,vy;
+ VectorSubtract(p2,p1,vx);
+ VectorNormalize(vx);
+ VectorSubtract(p3,p1,vy);
+ VectorNormalize(vy);
+ // assign scale
+ VectorScale(vx,texdef->scale[0],vx);
+ VectorScale(vy,texdef->scale[1],vy);
+ VectorAdd(p1,vx,p2);
+ VectorAdd(p1,vy,p3);
+ // compute back shift scale rot
+ AbsoluteToLocal(f->plane,f,p1,p2,p3);
+ }
+ else
+ f->texdef = *texdef;
+ f->texdef.flags = (f->texdef.flags & ~SURF_KEEP) | (oldFlags & SURF_KEEP);
+ f->texdef.contents = (f->texdef.contents & ~CONTENTS_KEEP) | (oldContents & CONTENTS_KEEP);
+
+ // surface plugin
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+#ifdef _DEBUG
+ if (!f->pData)
+ Sys_Printf("ERROR: unexpected IPluginTexdef* is NULL in SetFaceTexdef\n");
+ else
+#endif
+ GETPLUGINTEXDEF(f)->DecRef();
+ IPluginTexdef *pTexdef = NULL;
+ if ( pPlugTexdef )
+ {
+ pTexdef = pPlugTexdef->Copy();
+ pTexdef->Hook( f );
+ }
+ else
+ pTexdef = g_SurfaceTable.m_pfnTexdefAlloc( f );
+ f->pData = pTexdef;
+ }
+
+ // if this is a curve face, set all other curve faces to the same texdef
+ if (f->texdef.flags & SURF_CURVE)
+ {
+ for (tf = b->brush_faces ; tf ; tf = tf->next)
+ {
+ if (tf->texdef.flags & SURF_CURVE)
+ tf->texdef = f->texdef;
+ }
+ }
+}
+
+
+void Brush_SetTexture (brush_t *b, texdef_t *texdef, brushprimit_texdef_t *brushprimit_texdef, bool bFitScale, IPluginTexdef* pTexdef)
+{
+ for (face_t* f = b->brush_faces ; f ; f = f->next)
+ {
+ SetFaceTexdef (b, f, texdef, brushprimit_texdef, bFitScale, pTexdef);
+ }
+ Brush_Build( b );
+ if (b->patchBrush)
+ {
+ //++timo clean
+// Sys_Printf("WARNING: Brush_SetTexture needs surface plugin code for patches\n");
+ Patch_SetTexture(b->pPatch, texdef, pTexdef );
+ }
+ if (b->terrainBrush)
+ {
+ Terrain_SetTexture(b->pTerrain, texdef);
+ }
+
+}
+
+
+qboolean ClipLineToFace (vec3_t p1, vec3_t p2, face_t *f)
+{
+ float d1, d2, fr;
+ int i;
+ float *v;
+
+ d1 = DotProduct (p1, f->plane.normal) - f->plane.dist;
+ d2 = DotProduct (p2, f->plane.normal) - f->plane.dist;
+
+ if (d1 >= 0 && d2 >= 0)
+ return false; // totally outside
+ if (d1 <= 0 && d2 <= 0)
+ return true; // totally inside
+
+ fr = d1 / (d1 - d2);
+
+ if (d1 > 0)
+ v = p1;
+ else
+ v = p2;
+
+ for (i=0 ; i<3 ; i++)
+ v[i] = p1[i] + fr*(p2[i] - p1[i]);
+
+ return true;
+}
+
+
+int AddPlanept (float *f)
+{
+ int i;
+
+ for (i=0 ; i<g_qeglobals.d_num_move_points ; i++)
+ if (g_qeglobals.d_move_points[i] == f)
+ return 0;
+ g_qeglobals.d_move_points[g_qeglobals.d_num_move_points++] = f;
+ return 1;
+}
+
+/*
+==============
+Brush_SelectFaceForDragging
+
+Adds the faces planepts to move_points, and
+rotates and adds the planepts of adjacent face if shear is set
+==============
+*/
+void Brush_SelectFaceForDragging (brush_t *b, face_t *f, qboolean shear)
+{
+ int i;
+ face_t *f2;
+ winding_t *w;
+ float d;
+ brush_t *b2;
+ int c;
+
+ if (b->owner->eclass->fixedsize)
+ return;
+
+ c = 0;
+ for (i=0 ; i<3 ; i++)
+ c += AddPlanept (f->planepts[i]);
+ if (c == 0)
+ return; // allready completely added
+
+ // select all points on this plane in all brushes the selection
+ for (b2=selected_brushes.next ; b2 != &selected_brushes ; b2 = b2->next)
+ {
+ if (b2 == b)
+ continue;
+ for (f2=b2->brush_faces ; f2 ; f2=f2->next)
+ {
+ for (i=0 ; i<3 ; i++)
+ if (fabs(DotProduct(f2->planepts[i], f->plane.normal)
+ -f->plane.dist) > ON_EPSILON)
+ break;
+ if (i==3)
+ { // move this face as well
+ Brush_SelectFaceForDragging (b2, f2, shear);
+ break;
+ }
+ }
+ }
+
+
+ // if shearing, take all the planes adjacent to
+ // selected faces and rotate their points so the
+ // edge clipped by a selcted face has two of the points
+ if (!shear)
+ return;
+
+ for (f2=b->brush_faces ; f2 ; f2=f2->next)
+ {
+ if (f2 == f)
+ continue;
+ w = Brush_MakeFaceWinding (b, f2);
+ if (!w)
+ continue;
+
+ // any points on f will become new control points
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ d = DotProduct (w->points[i], f->plane.normal)
+ - f->plane.dist;
+ if (d > -ON_EPSILON && d < ON_EPSILON)
+ break;
+ }
+
+ //
+ // if none of the points were on the plane,
+ // leave it alone
+ //
+ if (i != w->numpoints)
+ {
+ if (i == 0)
+ { // see if the first clockwise point was the
+ // last point on the winding
+ d = DotProduct (w->points[w->numpoints-1]
+ , f->plane.normal) - f->plane.dist;
+ if (d > -ON_EPSILON && d < ON_EPSILON)
+ i = w->numpoints - 1;
+ }
+
+ AddPlanept (f2->planepts[0]);
+
+ VectorCopy (w->points[i], f2->planepts[0]);
+ if (++i == w->numpoints)
+ i = 0;
+
+ // see if the next point is also on the plane
+ d = DotProduct (w->points[i]
+ , f->plane.normal) - f->plane.dist;
+ if (d > -ON_EPSILON && d < ON_EPSILON)
+ AddPlanept (f2->planepts[1]);
+
+ VectorCopy (w->points[i], f2->planepts[1]);
+ if (++i == w->numpoints)
+ i = 0;
+
+ // the third point is never on the plane
+
+ VectorCopy (w->points[i], f2->planepts[2]);
+ }
+
+ free(w);
+ }
+}
+
+/*
+==============
+Brush_SideSelect
+
+The mouse click did not hit the brush, so grab one or more side
+planes for dragging
+==============
+*/
+void Brush_SideSelect (brush_t *b, vec3_t origin, vec3_t dir
+ , qboolean shear)
+{
+ face_t *f, *f2;
+ vec3_t p1, p2;
+
+ //if (b->patchBrush)
+ // return;
+ //Patch_SideSelect(b->nPatchID, origin, dir);
+ for (f=b->brush_faces ; f ; f=f->next)
+ {
+ VectorCopy (origin, p1);
+ VectorMA (origin, 16384, dir, p2);
+
+ for (f2=b->brush_faces ; f2 ; f2=f2->next)
+ {
+ if (f2 == f)
+ continue;
+ ClipLineToFace (p1, p2, f2);
+ }
+
+ if (f2)
+ continue;
+
+ if (VectorCompare (p1, origin))
+ continue;
+ if (ClipLineToFace (p1, p2, f))
+ continue;
+
+ Brush_SelectFaceForDragging (b, f, shear);
+ }
+
+
+}
+
+void Brush_BuildWindings( brush_t *b, bool bSnap )
+{
+ winding_t *w;
+ face_t *face;
+ vec_t v;
+
+ if (bSnap)
+ Brush_SnapPlanepts( b );
+
+ // clear the mins/maxs bounds
+ b->mins[0] = b->mins[1] = b->mins[2] = 99999;
+ b->maxs[0] = b->maxs[1] = b->maxs[2] = -99999;
+
+ Brush_MakeFacePlanes (b);
+
+ face = b->brush_faces;
+
+ float fCurveColor = 1.0;
+
+ for ( ; face ; face=face->next)
+ {
+ int i, j;
+ free(face->face_winding);
+ w = face->face_winding = Brush_MakeFaceWinding (b, face);
+ face->d_texture = Texture_ForName( face->texdef.name );
+
+ if (!w)
+ continue;
+
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ // add to bounding box
+ for (j=0 ; j<3 ; j++)
+ {
+ v = w->points[i][j];
+ if (v > b->maxs[j])
+ b->maxs[j] = v;
+ if (v < b->mins[j])
+ b->mins[j] = v;
+ }
+ }
+ // setup s and t vectors, and set color
+ //if (!g_PrefsDlg.m_bGLLighting)
+ //{
+ Face_SetColor (b, face, fCurveColor);
+ //}
+
+ fCurveColor -= .10;
+ if (fCurveColor <= 0)
+ fCurveColor = 1.0;
+
+ // computing ST coordinates for the windings
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ if (g_qeglobals.bNeedConvert)
+ {
+ // we have parsed old brushes format and need conversion
+ // convert old brush texture representation to new format
+ FaceToBrushPrimitFace(face);
+#ifdef _DEBUG
+ // use old texture coordinates code to check against
+ for (i=0 ; i<w->numpoints ; i++)
+ EmitTextureCoordinates( w->points[i], face->d_texture, face);
+#endif
+ }
+ // use new texture representation to compute texture coordinates
+ // in debug mode we will check against old code and warn if there are differences
+ EmitBrushPrimitTextureCoordinates(face,w);
+ }
+ else
+ {
+ for (i=0 ; i<w->numpoints ; i++)
+ EmitTextureCoordinates( w->points[i], face->d_texture, face);
+ }
+ }
+}
+
+/*
+==================
+Brush_RemoveEmptyFaces
+
+Frees any overconstraining faces
+==================
+*/
+void Brush_RemoveEmptyFaces ( brush_t *b )
+{
+ face_t *f, *next;
+
+ f = b->brush_faces;
+ b->brush_faces = NULL;
+
+ for ( ; f ; f=next)
+ {
+ next = f->next;
+ if (!f->face_winding)
+ Face_Free (f);
+ else
+ {
+ f->next = b->brush_faces;
+ b->brush_faces = f;
+ }
+
+ }
+}
+
+void Brush_SnapToGrid(brush_t *pb)
+{
+ for (face_t *f = pb->brush_faces ; f; f = f->next)
+ {
+ for (int i = 0 ;i < 3 ;i++)
+ {
+ for (int j = 0 ;j < 3 ; j++)
+ {
+ f->planepts[i][j] = floor (f->planepts[i][j] / g_qeglobals.d_gridsize + 0.5) * g_qeglobals.d_gridsize;
+ }
+ }
+ }
+ Brush_Build(pb);
+}
+
+void Brush_Rotate(brush_t *b, vec3_t vAngle, vec3_t vOrigin, bool bBuild)
+{
+ for (face_t* f=b->brush_faces ; f ; f=f->next)
+ {
+ for (int i=0 ; i<3 ; i++)
+ {
+ VectorRotate(f->planepts[i], vAngle, vOrigin, f->planepts[i]);
+ }
+ }
+ if (bBuild)
+ {
+ Brush_Build(b, false, false);
+ }
+}
+
+void Brush_Center(brush_t *b, vec3_t vNewCenter)
+{
+ vec3_t vMid;
+ // get center of the brush
+ for (int j = 0; j < 3; j++)
+ {
+ vMid[j] = b->mins[j] + abs((b->maxs[j] - b->mins[j]) * 0.5);
+ }
+ // calc distance between centers
+ VectorSubtract(vNewCenter, vMid, vMid);
+ Brush_Move(b, vMid, true);
+
+}
+
+// only designed for fixed size entity brushes
+void Brush_Resize(brush_t *b, vec3_t vMin, vec3_t vMax)
+{
+ brush_t *b2 = Brush_Create(vMin, vMax, &b->brush_faces->texdef);
+
+ face_t *next;
+ for (face_t *f=b->brush_faces ; f ; f=next)
+ {
+ next = f->next;
+ Face_Free( f );
+ }
+
+ b->brush_faces = b2->brush_faces;
+
+ // unlink from active/selected list
+ if (b2->next)
+ Brush_RemoveFromList (b2);
+ free(b2);
+ Brush_Build(b, true);
+}
+
+
+eclass_t* HasModel(brush_t *b)
+{
+ vec3_t vMin, vMax;
+ vMin[0] = vMin[1] = vMin[2] = 9999;
+ vMax[0] = vMax[1] = vMax[2] = -9999;
+
+ if (b->owner->md3Class != NULL)
+ {
+ return b->owner->md3Class;
+ }
+
+ if (Eclass_hasModel(b->owner->eclass, vMin, vMax))
+ {
+ return b->owner->eclass;
+ }
+
+ eclass_t *e = NULL;
+ // FIXME: entity needs to track whether a cache hit failed and not ask again
+ if (b->owner->eclass->nShowFlags & ECLASS_MISCMODEL)
+ {
+ char *pModel = ValueForKey(b->owner, "model");
+ if (pModel != NULL && strlen(pModel) > 0)
+ {
+ e = GetCachedModel(b->owner, pModel, vMin, vMax);
+ if (e != NULL)
+ {
+ // we need to scale the brush to the proper size based on the model load
+ // recreate brush just like in load/save
+
+ VectorAdd (vMin, b->owner->origin, vMin);
+ VectorAdd (vMax, b->owner->origin, vMax);
+
+ Brush_Resize(b, vMin, vMax);
+
+/*
+ //
+ vec3_t vTemp, vTemp2;
+ VectorSubtract(b->maxs, b->mins, vTemp);
+ VectorSubtract(vMax, vMin, vTemp2);
+ for (int i = 0; i < 3; i++)
+ {
+ if (vTemp[i] != 0)
+ {
+ vTemp2[i] /= vTemp[i];
+ }
+ }
+ vec3_t vMid, vMid2;
+ vMid[0] = vMid[1] = vMid[2] = 0.0;
+ vMid2[0] = vMid2[1] = vMid2[2] = 0.0;
+
+ for (int j = 0; j < 3; j++)
+ {
+ vMid2[j] = b->mins[j] + abs((b->maxs[j] - b->mins[j]) * 0.5);
+ }
+
+ //VectorSubtract(vMid2, vMid, vMid2);
+
+ for (face_t* f=b->brush_faces ; f ; f=f->next)
+ {
+ for (int i=0 ; i<3 ; i++)
+ {
+
+ // scale
+ VectorSubtract(f->planepts[i], vMid2, f->planepts[i]);
+ f->planepts[i][0] *= vTemp2[0];
+ f->planepts[i][1] *= vTemp2[1];
+ f->planepts[i][2] *= vTemp2[2];
+ VectorAdd(f->planepts[i], vMid2, f->planepts[i]);
+ }
+ }
+
+ //Brush_Center(b, b->owner->origin);
+
+ //Brush_SnapToGrid(b);
+/*
+ float a = FloatForKey (b->owner, "angle");
+ if (a)
+ {
+ vec3_t vAngle;
+ vAngle[0] = vAngle[1] = 0;
+ vAngle[2] = a;
+ Brush_Rotate(b, vAngle, b->owner->origin);
+ }
+ else
+ {
+ Brush_Build(b, true);
+*/
+// }
+
+ b->bModelFailed = false;
+ }
+ else
+ {
+ b->bModelFailed = true;
+ }
+ }
+ }
+ return e;
+}
+
+static bool g_bInPaintedModel = false;
+static bool g_bDoIt = false;
+bool PaintedModel(brush_t *b, bool bOkToTexture)
+{
+ if (g_bInPaintedModel)
+ {
+ return true;
+ }
+
+ if (g_PrefsDlg.m_nEntityShowState == ENTITY_BOX || b->bModelFailed)
+ {
+ return false;
+ }
+ else if (!IsBrushSelected(b) && (g_PrefsDlg.m_nEntityShowState & ENTITY_SELECTED_ONLY))
+ {
+ return false;
+ }
+
+ g_bInPaintedModel = true;
+ bool bReturn = false;
+
+ eclass_t *pEclass = HasModel(b);
+
+ if (pEclass)
+ {
+ qglPushAttrib(GL_ALL_ATTRIB_BITS);
+ entitymodel *model = pEclass->model;
+
+
+ float a = FloatForKey (b->owner, "angle");
+ while (model != NULL)
+ {
+ if (bOkToTexture == false || g_PrefsDlg.m_nEntityShowState & ENTITY_WIREFRAME || model->nTextureBind == -1) // skinned
+ {
+ qglDisable( GL_CULL_FACE );
+ qglPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
+ qglDisable(GL_TEXTURE_2D);
+ qglColor3fv(pEclass->color);
+ }
+ else
+ {
+ qglColor3f(1, 1, 1);
+ qglEnable(GL_TEXTURE_2D);
+ qglBindTexture( GL_TEXTURE_2D, model->nTextureBind );
+ }
+ vec3_t v;
+
+ int i,j;
+ VectorAdd(b->maxs, b->mins, v);
+ VectorScale(v, 0.5, v);
+ VectorCopy(b->owner->origin, v);
+
+
+ //for (i = 0; i < 3; i++)
+ //{
+ // v[i] -= (pEclass->mins[i] - b->mins[i]);
+ //}
+
+ //if (model->nModelPosition)
+ //{
+ //v[2] = b->mins[2] - (pEclass->mins[2]);
+ //}
+
+ float s, c;
+ if (a)
+ {
+ s = sin (a/180*Q_PI);
+ c = cos (a/180*Q_PI);
+ }
+
+ vec3_t vSin;
+ vec3_t vCos;
+ VectorClear(vSin);
+ VectorClear(vCos);
+ for ( j = 0; j < 3; j++)
+ {
+ if (b->owner->vRotation[j])
+ {
+ vSin[j] = sin(b->owner->vRotation[j]/180*Q_PI);
+ vCos[j] = cos(b->owner->vRotation[j]/180*Q_PI);
+ }
+ }
+
+
+ qglBegin (GL_TRIANGLES);
+
+ vec5_t vTest[3];
+ for (i = 0; i < model->nTriCount; i++)
+ {
+ for (j = 0; j < 3; j++)
+ {
+#if 1
+ float x = model->pTriList[i].v[j][0] + v[0];
+ float y = model->pTriList[i].v[j][1] + v[1];
+ if (a)
+ {
+ float x2 = (((x - v[0]) * c) - ((y - v[1]) * s)) + v[0];
+ float y2 = (((x - v[0]) * s) + ((y - v[1]) * c)) + v[1];
+ x = x2;
+ y = y2;
+ }
+ //qglTexCoord2f (pEclass->pTriList[i].st[j][0] / pEclass->nSkinWidth, pEclass->pTriList[i].st[j][1] / pEclass->nSkinHeight);
+ qglTexCoord2f (model->pTriList[i].st[j][0], model->pTriList[i].st[j][1]);
+ qglVertex3f(x, y, model->pTriList[i].v[j][2] + v[2]);
+#else
+ float x = model->pTriList[i].v[j][0] + v[0];
+ float y = model->pTriList[i].v[j][1] + v[1];
+ float z = model->pTriList[i].v[j][2] + v[2];
+
+ if (b->owner->vRotation[0])
+ {
+ float y2 = (((y - v[1]) * vCos[0]) - ((z - v[2]) * vSin[0])) + v[1];
+ float z2 = (((y - v[1]) * vSin[0]) + ((z - v[2]) * vCos[0])) + v[2];
+ y = y2;
+ z = z2;
+ }
+ if (b->owner->vRotation[1])
+ {
+ float z2 = (((z - v[2]) * vCos[1]) - ((x - v[0]) * vSin[1])) + v[2];
+ float x2 = (((z - v[2]) * vSin[1]) + ((x - v[0]) * vCos[1])) + v[0];
+ x = x2;
+ z = z2;
+ }
+ if (b->owner->vRotation[2])
+ {
+ float x2 = (((x - v[0]) * vCos[2]) - ((y - v[1]) * vSin[2])) + v[0];
+ float y2 = (((x - v[0]) * vSin[2]) + ((y - v[1]) * vCos[2])) + v[1];
+ x = x2;
+ y = y2;
+ }
+ qglTexCoord2f (model->pTriList[i].st[j][0], model->pTriList[i].st[j][1]);
+ qglVertex3f(x, y, z);
+#endif
+ if (g_bDoIt)
+ {
+ vTest[j][0] = x;
+ vTest[j][1] = y;
+ vTest[j][2] = model->pTriList[i].v[j][2] + v[2];
+ vTest[j][3] = model->pTriList[i].st[j][0];
+ vTest[j][4] = model->pTriList[i].st[j][1];
+ }
+
+ }
+ if (g_bDoIt)
+ {
+ Patch_FromTriangle(vTest[0], vTest[1], vTest[2]);
+ }
+ }
+ qglEnd();
+ if (g_PrefsDlg.m_nEntityShowState & ENTITY_WIREFRAME) // skinned
+ {
+ qglEnable(GL_CULL_FACE );
+ qglEnable(GL_TEXTURE_2D);
+ qglPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
+ }
+ else
+ {
+ qglDisable(GL_TEXTURE_2D);
+ }
+ model = model->pNext;
+ }
+
+ if (g_bDoIt)
+ {
+ g_bDoIt = false;
+ }
+
+ vec3_t vColor;
+ VectorScale(pEclass->color, 0.50, vColor);
+
+ vec3_t vCenter, vMin, vMax;
+ VectorCopy(b->owner->origin, vCenter);
+
+ qglColor3fv(vColor);
+ qglPointSize(4);
+
+ qglBegin(GL_POINTS);
+ qglVertex3fv(b->owner->origin);
+ qglEnd();
+
+ qglBegin(GL_LINES);
+ vCenter[0] -= 8;
+ qglVertex3fv(vCenter);
+ vCenter[0] += 16;
+ qglVertex3fv(vCenter);
+ vCenter[0] -= 8;
+ vCenter[1] -= 8;
+ qglVertex3fv(vCenter);
+ vCenter[1] += 16;
+ qglVertex3fv(vCenter);
+ vCenter[1] -= 8;
+ vCenter[2] -= 8;
+ qglVertex3fv(vCenter);
+ vCenter[2] += 16;
+ qglVertex3fv(vCenter);
+ vCenter[2] -= 8;
+ qglEnd();
+
+ VectorCopy(vCenter, vMin);
+ VectorCopy(vCenter, vMax);
+ vMin[0] -= 4;
+ vMin[1] -= 4;
+ vMin[2] -= 4;
+ vMax[0] += 4;
+ vMax[1] += 4;
+ vMax[2] += 4;
+
+ qglBegin(GL_LINE_LOOP);
+ qglVertex3f(vMin[0],vMin[1],vMin[2]);
+ qglVertex3f(vMax[0],vMin[1],vMin[2]);
+ qglVertex3f(vMax[0],vMax[1],vMin[2]);
+ qglVertex3f(vMin[0],vMax[1],vMin[2]);
+ qglEnd();
+
+ qglBegin(GL_LINE_LOOP);
+ qglVertex3f(vMin[0],vMin[1],vMax[2]);
+ qglVertex3f(vMax[0],vMin[1],vMax[2]);
+ qglVertex3f(vMax[0],vMax[1],vMax[2]);
+ qglVertex3f(vMin[0],vMax[1],vMax[2]);
+ qglEnd();
+
+ qglBegin(GL_LINES);
+ qglVertex3f(vMin[0],vMin[1],vMin[2]);
+ qglVertex3f(vMin[0],vMin[1],vMax[2]);
+ qglVertex3f(vMin[0],vMax[1],vMax[2]);
+ qglVertex3f(vMin[0],vMax[1],vMin[2]);
+ qglVertex3f(vMax[0],vMin[1],vMin[2]);
+ qglVertex3f(vMax[0],vMin[1],vMax[2]);
+ qglVertex3f(vMax[0],vMax[1],vMax[2]);
+ qglVertex3f(vMax[0],vMax[1],vMin[2]);
+ qglEnd();
+
+
+ if (g_PrefsDlg.m_nEntityShowState & ENTITY_BOXED)
+ {
+ qglColor3fv(pEclass->color);
+
+ vec3_t mins, maxs;
+ VectorCopy(b->mins, mins);
+ VectorCopy(b->maxs, maxs);
+/*
+ if (a)
+ {
+ vec3_t vAngle;
+ vAngle[0] = vAngle[1] = 0;
+ vAngle[2] = a;
+ VectorRotate(mins, vAngle, b->owner->origin, mins);
+ VectorRotate(maxs, vAngle, b->owner->origin, maxs);
+ }
+*/
+ qglBegin(GL_LINE_LOOP);
+ qglVertex3f(mins[0],mins[1],mins[2]);
+ qglVertex3f(maxs[0],mins[1],mins[2]);
+ qglVertex3f(maxs[0],maxs[1],mins[2]);
+ qglVertex3f(mins[0],maxs[1],mins[2]);
+ qglEnd();
+
+ qglBegin(GL_LINE_LOOP);
+ qglVertex3f(mins[0],mins[1],maxs[2]);
+ qglVertex3f(maxs[0],mins[1],maxs[2]);
+ qglVertex3f(maxs[0],maxs[1],maxs[2]);
+ qglVertex3f(mins[0],maxs[1],maxs[2]);
+ qglEnd();
+
+ qglBegin(GL_LINES);
+ qglVertex3f(mins[0],mins[1],mins[2]);
+ qglVertex3f(mins[0],mins[1],maxs[2]);
+ qglVertex3f(mins[0],maxs[1],maxs[2]);
+ qglVertex3f(mins[0],maxs[1],mins[2]);
+ qglVertex3f(maxs[0],mins[1],mins[2]);
+ qglVertex3f(maxs[0],mins[1],maxs[2]);
+ qglVertex3f(maxs[0],maxs[1],maxs[2]);
+ qglVertex3f(maxs[0],maxs[1],mins[2]);
+ qglEnd();
+ }
+ qglPopAttrib();
+ bReturn = true;
+ }
+ else
+ {
+ b->bModelFailed = true;
+ }
+
+ g_bInPaintedModel = false;
+ return bReturn;
+}
+/*
+//++timo moved out to mahlib.h
+//++timo remove
+void AngleVectors (vec3_t angles, vec3_t forward, vec3_t right, vec3_t up)
+{
+ float angle;
+ static float sr, sp, sy, cr, cp, cy;
+ // static to help MS compiler fp bugs
+
+ angle = angles[YAW] * Q_PI / 180;
+ sy = sin(angle);
+ cy = cos(angle);
+ angle = angles[PITCH] * Q_PI / 180;
+ sp = sin(angle);
+ cp = cos(angle);
+ angle = angles[ROLL] * Q_PI / 180;
+ sr = sin(angle);
+ cr = cos(angle);
+
+ if (forward)
+ {
+ forward[0] = cp*cy;
+ forward[1] = cp*sy;
+ forward[2] = -sp;
+ }
+ if (right)
+ {
+ right[0] = (-1*sr*sp*cy+-1*cr*-sy);
+ right[1] = (-1*sr*sp*sy+-1*cr*cy);
+ right[2] = -1*sr*cp;
+ }
+ if (up)
+ {
+ up[0] = (cr*sp*cy+-sr*-sy);
+ up[1] = (cr*sp*sy+-sr*cy);
+ up[2] = cr*cp;
+ }
+}
+*/
+void FacingVectors (entity_t *e, vec3_t forward, vec3_t right, vec3_t up)
+{
+ int angleVal;
+ vec3_t angles;
+
+ angleVal = IntForKey(e, "angle");
+ if (angleVal == -1) // up
+ {
+ VectorSet(angles, 270, 0, 0);
+ }
+ else if(angleVal == -2) // down
+ {
+ VectorSet(angles, 90, 0, 0);
+ }
+ else
+ {
+ VectorSet(angles, 0, angleVal, 0);
+ }
+
+ AngleVectors(angles, forward, right, up);
+}
+
+void Brush_DrawFacingAngle (brush_t *b, entity_t *e)
+{
+ vec3_t forward, right, up;
+ vec3_t endpoint, tip1, tip2;
+ vec3_t start;
+ float dist;
+
+ VectorAdd(e->brushes.onext->mins, e->brushes.onext->maxs, start);
+ VectorScale(start, 0.5, start);
+ dist = (b->maxs[0] - start[0]) * 2.5;
+
+ FacingVectors (e, forward, right, up);
+ VectorMA (start, dist, forward, endpoint);
+
+ dist = (b->maxs[0] - start[0]) * 0.5;
+ VectorMA (endpoint, -dist, forward, tip1);
+ VectorMA (tip1, -dist, up, tip1);
+ VectorMA (tip1, 2*dist, up, tip2);
+
+ qglColor4f (1, 1, 1, 1);
+ qglLineWidth (4);
+ qglBegin (GL_LINES);
+ qglVertex3fv (start);
+ qglVertex3fv (endpoint);
+ qglVertex3fv (endpoint);
+ qglVertex3fv (tip1);
+ qglVertex3fv (endpoint);
+ qglVertex3fv (tip2);
+ qglEnd ();
+ qglLineWidth (1);
+}
+
+void DrawLight(brush_t *b)
+{
+ vec3_t vTriColor;
+ bool bTriPaint = false;
+
+ vTriColor[0] = vTriColor[2] = 1.0;
+ vTriColor[1] = 1.0;
+ bTriPaint = true;
+ CString strColor = ValueForKey(b->owner, "_color");
+ if (strColor.GetLength() > 0)
+ {
+ float fR, fG, fB;
+ int n = sscanf(strColor,"%f %f %f", &fR, &fG, &fB);
+ if (n == 3)
+ {
+ vTriColor[0] = fR;
+ vTriColor[1] = fG;
+ vTriColor[2] = fB;
+ }
+ }
+ qglColor3f(vTriColor[0], vTriColor[1], vTriColor[2]);
+
+ vec3_t vCorners[4];
+ float fMid = b->mins[2] + (b->maxs[2] - b->mins[2]) / 2;
+
+ vCorners[0][0] = b->mins[0];
+ vCorners[0][1] = b->mins[1];
+ vCorners[0][2] = fMid;
+
+ vCorners[1][0] = b->mins[0];
+ vCorners[1][1] = b->maxs[1];
+ vCorners[1][2] = fMid;
+
+ vCorners[2][0] = b->maxs[0];
+ vCorners[2][1] = b->maxs[1];
+ vCorners[2][2] = fMid;
+
+ vCorners[3][0] = b->maxs[0];
+ vCorners[3][1] = b->mins[1];
+ vCorners[3][2] = fMid;
+
+ vec3_t vTop, vBottom;
+
+ vTop[0] = b->mins[0] + ((b->maxs[0] - b->mins[0]) / 2);
+ vTop[1] = b->mins[1] + ((b->maxs[1] - b->mins[1]) / 2);
+ vTop[2] = b->maxs[2];
+
+ VectorCopy(vTop, vBottom);
+ vBottom[2] = b->mins[2];
+
+ vec3_t vSave;
+ VectorCopy(vTriColor, vSave);
+
+ qglBegin(GL_TRIANGLE_FAN);
+ qglVertex3fv(vTop);
+ for (int i = 0; i <= 3; i++)
+ {
+ vTriColor[0] *= 0.95;
+ vTriColor[1] *= 0.95;
+ vTriColor[2] *= 0.95;
+ qglColor3f(vTriColor[0], vTriColor[1], vTriColor[2]);
+ qglVertex3fv(vCorners[i]);
+ }
+ qglVertex3fv(vCorners[0]);
+ qglEnd();
+
+ VectorCopy(vSave, vTriColor);
+ vTriColor[0] *= 0.95;
+ vTriColor[1] *= 0.95;
+ vTriColor[2] *= 0.95;
+
+ qglBegin(GL_TRIANGLE_FAN);
+ qglVertex3fv(vBottom);
+ qglVertex3fv(vCorners[0]);
+ for (i = 3; i >= 0; i--)
+ {
+ vTriColor[0] *= 0.95;
+ vTriColor[1] *= 0.95;
+ vTriColor[2] *= 0.95;
+ qglColor3f(vTriColor[0], vTriColor[1], vTriColor[2]);
+ qglVertex3fv(vCorners[i]);
+ }
+ qglEnd();
+
+ // check for DOOM lights
+ CString str = ValueForKey(b->owner, "light_right");
+ if (str.GetLength() > 0) {
+ vec3_t vRight, vUp, vTarget, vTemp;
+ GetVectorForKey (b->owner, "light_right", vRight);
+ GetVectorForKey (b->owner, "light_up", vUp);
+ GetVectorForKey (b->owner, "light_target", vTarget);
+
+ qglColor3f(0, 1, 0);
+ qglBegin(GL_LINE_LOOP);
+ VectorAdd(vTarget, b->owner->origin, vTemp);
+ VectorAdd(vTemp, vRight, vTemp);
+ VectorAdd(vTemp, vUp, vTemp);
+ qglVertex3fv(b->owner->origin);
+ qglVertex3fv(vTemp);
+ VectorAdd(vTarget, b->owner->origin, vTemp);
+ VectorAdd(vTemp, vUp, vTemp);
+ VectorSubtract(vTemp, vRight, vTemp);
+ qglVertex3fv(b->owner->origin);
+ qglVertex3fv(vTemp);
+ VectorAdd(vTarget, b->owner->origin, vTemp);
+ VectorAdd(vTemp, vRight, vTemp);
+ VectorSubtract(vTemp, vUp, vTemp);
+ qglVertex3fv(b->owner->origin);
+ qglVertex3fv(vTemp);
+ VectorAdd(vTarget, b->owner->origin, vTemp);
+ VectorSubtract(vTemp, vUp, vTemp);
+ VectorSubtract(vTemp, vRight, vTemp);
+ qglVertex3fv(b->owner->origin);
+ qglVertex3fv(vTemp);
+ qglEnd();
+
+ }
+
+}
+
+void Brush_Draw( brush_t *b )
+{
+ face_t *face;
+ int i, order;
+ qtexture_t *prev = 0;
+ winding_t *w;
+
+ if ( b->owner && ( b->owner->eclass->nShowFlags & ECLASS_PLUGINENTITY ) )
+ {
+ b->owner->pPlugEnt->CamRender();
+ return;
+ }
+
+ // (TTimo) NOTE: added by build 173, I check after pPlugEnt so it doesn't interfere ?
+ if (b->hiddenBrush)
+ {
+ return;
+ }
+
+ if (b->patchBrush)
+ {
+ //Patch_DrawCam(b->nPatchID);
+ Patch_DrawCam(b->pPatch);
+ //if (!g_bPatchShowBounds)
+ return;
+ }
+
+ if (b->terrainBrush)
+ {
+ Terrain_DrawCam(b->pTerrain);
+ return;
+ }
+
+ int nDrawMode = g_pParentWnd->GetCamera()->Camera().draw_mode;
+
+ if (b->owner->eclass->fixedsize)
+ {
+
+ if (!(g_qeglobals.d_savedinfo.exclude & EXCLUDE_ANGLES) && (b->owner->eclass->nShowFlags & ECLASS_ANGLE))
+ {
+ Brush_DrawFacingAngle(b, b->owner);
+ }
+
+ if (g_PrefsDlg.m_bNewLightDraw && (b->owner->eclass->nShowFlags & ECLASS_LIGHT))
+ {
+ DrawLight(b);
+ return;
+ }
+ if (nDrawMode == cd_texture || nDrawMode == cd_light)
+ qglDisable (GL_TEXTURE_2D);
+
+ // if we are wireframing models
+ bool bp = (b->bModelFailed) ? false : PaintedModel(b, true);
+
+ if (nDrawMode == cd_texture || nDrawMode == cd_light)
+ qglEnable (GL_TEXTURE_2D);
+
+ if (bp)
+ return;
+ }
+
+ // guarantee the texture will be set first
+ prev = NULL;
+ for (face = b->brush_faces,order = 0 ; face ; face=face->next, order++)
+ {
+ w = face->face_winding;
+ if (!w)
+ {
+ continue; // freed face
+ }
+
+ if (g_qeglobals.d_savedinfo.exclude & EXCLUDE_CAULK)
+ {
+ if (strstr(face->texdef.name, "caulk"))
+ {
+ continue;
+ }
+ }
+
+#if 0
+ if (b->alphaBrush)
+ {
+ if (!(face->texdef.flags & SURF_ALPHA))
+ continue;
+ //--qglPushAttrib(GL_ALL_ATTRIB_BITS);
+ qglDisable(GL_CULL_FACE);
+ //--qglTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
+ //--qglBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ //--qglDisable(GL_DEPTH_TEST);
+ //--qglBlendFunc (GL_SRC_ALPHA, GL_DST_ALPHA);
+ //--qglEnable (GL_BLEND);
+ }
+#endif
+
+ if ((nDrawMode == cd_texture || nDrawMode == cd_light) && face->d_texture != prev)
+ {
+ // set the texture for this face
+ prev = face->d_texture;
+ qglBindTexture( GL_TEXTURE_2D, face->d_texture->texture_number );
+ }
+
+
+
+ if (!b->patchBrush)
+ {
+ if (face->texdef.flags & SURF_TRANS33)
+ qglColor4f ( face->d_color[0], face->d_color[1], face->d_color[2], 0.33 );
+ else if ( face->texdef.flags & SURF_TRANS66)
+ qglColor4f ( face->d_color[0], face->d_color[1], face->d_color[2], 0.66 );
+ else
+ qglColor3fv( face->d_color );
+ }
+ else
+ {
+ qglColor4f ( face->d_color[0], face->d_color[1], face->d_color[2], 0.13 );
+ }
+
+ // shader drawing stuff
+ if (face->d_texture->bFromShader)
+ {
+ // setup shader drawing
+ qglColor4f ( face->d_color[0], face->d_color[1], face->d_color[2], face->d_texture->fTrans );
+
+ }
+
+ // draw the polygon
+
+ //if (nDrawMode == cd_light)
+ //{
+ if (g_PrefsDlg.m_bGLLighting)
+ {
+ qglNormal3fv(face->plane.normal);
+ }
+ //}
+
+ qglBegin(GL_POLYGON);
+ //if (nDrawMode == cd_light)
+
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ if (nDrawMode == cd_texture || nDrawMode == cd_light)
+ qglTexCoord2fv( &w->points[i][3] );
+ qglVertex3fv(w->points[i]);
+ }
+ qglEnd();
+ }
+
+#if 0
+ if (b->alphaBrush)
+ {
+ //--qglPopAttrib();
+ qglEnable(GL_CULL_FACE);
+ //--qglDisable (GL_BLEND);
+ //--qglTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
+ }
+#endif
+
+ if (b->owner->eclass->fixedsize && (nDrawMode == cd_texture || nDrawMode == cd_light))
+ qglEnable (GL_TEXTURE_2D);
+
+ qglBindTexture( GL_TEXTURE_2D, 0 );
+}
+
+
+
+void Face_Draw( face_t *f )
+{
+ int i;
+
+ if ( f->face_winding == 0 )
+ return;
+ qglBegin( GL_POLYGON );
+ for ( i = 0 ; i < f->face_winding->numpoints; i++)
+ qglVertex3fv( f->face_winding->points[i] );
+ qglEnd();
+}
+
+void Brush_DrawXY(brush_t *b, int nViewType)
+{
+ face_t *face;
+ int order;
+ winding_t *w;
+ int i;
+
+ if (b->hiddenBrush)
+ {
+ return;
+ }
+
+ if (b->patchBrush)
+ {
+ //Patch_DrawXY(b->nPatchID);
+ Patch_DrawXY(b->pPatch);
+ if (!g_bPatchShowBounds)
+ return;
+ }
+
+ if (b->terrainBrush)
+ {
+ Terrain_DrawXY(b->pTerrain, b->owner);
+ }
+
+
+ if (b->owner->eclass->fixedsize)
+ {
+ if (g_PrefsDlg.m_bNewLightDraw && (b->owner->eclass->nShowFlags & ECLASS_LIGHT))
+ {
+ vec3_t vCorners[4];
+ float fMid = b->mins[2] + (b->maxs[2] - b->mins[2]) / 2;
+
+ vCorners[0][0] = b->mins[0];
+ vCorners[0][1] = b->mins[1];
+ vCorners[0][2] = fMid;
+
+ vCorners[1][0] = b->mins[0];
+ vCorners[1][1] = b->maxs[1];
+ vCorners[1][2] = fMid;
+
+ vCorners[2][0] = b->maxs[0];
+ vCorners[2][1] = b->maxs[1];
+ vCorners[2][2] = fMid;
+
+ vCorners[3][0] = b->maxs[0];
+ vCorners[3][1] = b->mins[1];
+ vCorners[3][2] = fMid;
+
+ vec3_t vTop, vBottom;
+
+ vTop[0] = b->mins[0] + ((b->maxs[0] - b->mins[0]) / 2);
+ vTop[1] = b->mins[1] + ((b->maxs[1] - b->mins[1]) / 2);
+ vTop[2] = b->maxs[2];
+
+ VectorCopy(vTop, vBottom);
+ vBottom[2] = b->mins[2];
+
+ qglPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
+ qglBegin(GL_TRIANGLE_FAN);
+ qglVertex3fv(vTop);
+ qglVertex3fv(vCorners[0]);
+ qglVertex3fv(vCorners[1]);
+ qglVertex3fv(vCorners[2]);
+ qglVertex3fv(vCorners[3]);
+ qglVertex3fv(vCorners[0]);
+ qglEnd();
+ qglBegin(GL_TRIANGLE_FAN);
+ qglVertex3fv(vBottom);
+ qglVertex3fv(vCorners[0]);
+ qglVertex3fv(vCorners[3]);
+ qglVertex3fv(vCorners[2]);
+ qglVertex3fv(vCorners[1]);
+ qglVertex3fv(vCorners[0]);
+ qglEnd();
+ DrawBrushEntityName (b);
+ return;
+ }
+ else if (b->owner->eclass->nShowFlags & ECLASS_MISCMODEL)
+ {
+ if (PaintedModel(b, false))
+ return;
+ }
+ }
+
+ for (face = b->brush_faces,order = 0 ; face ; face=face->next, order++)
+ {
+ // only draw polygons facing in a direction we care about
+ if (nViewType == XY)
+ {
+ if (face->plane.normal[2] <= 0)
+ continue;
+ }
+ else
+ {
+ if (nViewType == XZ)
+ {
+ if (face->plane.normal[1] <= 0)
+ continue;
+ }
+ else
+ {
+ if (face->plane.normal[0] <= 0)
+ continue;
+ }
+ }
+
+ w = face->face_winding;
+ if (!w)
+ continue;
+
+ //if (b->alphaBrush && !(face->texdef.flags & SURF_ALPHA))
+ // continue;
+
+ // draw the polygon
+ qglBegin(GL_LINE_LOOP);
+ for (i=0 ; i<w->numpoints ; i++)
+ qglVertex3fv(w->points[i]);
+ qglEnd();
+ }
+
+ DrawBrushEntityName (b);
+
+}
+
+/*
+============
+Brush_Move
+============
+*/
+void Brush_Move (brush_t *b, const vec3_t move, bool bSnap)
+{
+ int i;
+ face_t *f;
+
+ for (f=b->brush_faces ; f ; f=f->next)
+ {
+ vec3_t vTemp;
+ VectorCopy(move, vTemp);
+
+ if (g_PrefsDlg.m_bTextureLock)
+ Face_MoveTexture(f, vTemp);
+
+ for (i=0 ; i<3 ; i++)
+ VectorAdd (f->planepts[i], move, f->planepts[i]);
+ }
+ Brush_Build( b, bSnap );
+
+
+ if (b->patchBrush)
+ {
+ //Patch_Move(b->nPatchID, move);
+ Patch_Move(b->pPatch, move);
+ }
+
+ if (b->terrainBrush)
+ {
+ Terrain_Move(b->pTerrain, move);
+ }
+
+
+ // PGM - keep the origin vector up to date on fixed size entities.
+ if(b->owner->eclass->fixedsize)
+ {
+ VectorAdd(b->owner->origin, move, b->owner->origin);
+ //VectorAdd(b->maxs, b->mins, b->owner->origin);
+ //VectorScale(b->owner->origin, 0.5, b->owner->origin);
+ }
+}
+
+
+
+void Brush_Print(brush_t* b)
+{
+ int nFace = 0;
+ for (face_t* f = b->brush_faces ; f ; f=f->next)
+ {
+ Sys_Printf("Face %i\n", nFace++);
+ Sys_Printf("%f %f %f\n", f->planepts[0][0], f->planepts[0][1], f->planepts[0][2]);
+ Sys_Printf("%f %f %f\n", f->planepts[1][0], f->planepts[1][1], f->planepts[1][2]);
+ Sys_Printf("%f %f %f\n", f->planepts[2][0], f->planepts[2][1], f->planepts[2][2]);
+ }
+ }
+
+
+
+/*
+=============
+Brush_MakeSided
+
+Makes the current brushhave the given number of 2d sides and turns it into a cone
+=============
+*/
+void Brush_MakeSidedCone(int sides)
+{
+ int i;
+ vec3_t mins, maxs;
+ brush_t *b;
+ texdef_t *texdef;
+ face_t *f;
+ vec3_t mid;
+ float width;
+ float sv, cv;
+
+ if (sides < 3)
+ {
+ Sys_Status ("Bad sides number", 0);
+ return;
+ }
+
+ if (!QE_SingleBrush ())
+ {
+ Sys_Status ("Must have a single brush selected", 0 );
+ return;
+ }
+
+ b = selected_brushes.next;
+ VectorCopy (b->mins, mins);
+ VectorCopy (b->maxs, maxs);
+ texdef = &g_qeglobals.d_texturewin.texdef;
+
+ Brush_Free (b);
+
+ // find center of brush
+ width = 8;
+ for (i=0 ; i<2 ; i++)
+ {
+ mid[i] = (maxs[i] + mins[i])*0.5;
+ if (maxs[i] - mins[i] > width)
+ width = maxs[i] - mins[i];
+ }
+ width /= 2;
+
+ b = Brush_Alloc();
+
+ // create bottom face
+ f = Face_Alloc();
+ f->texdef = *texdef;
+ f->next = b->brush_faces;
+ b->brush_faces = f;
+
+ f->planepts[0][0] = mins[0];f->planepts[0][1] = mins[1];f->planepts[0][2] = mins[2];
+ f->planepts[1][0] = maxs[0];f->planepts[1][1] = mins[1];f->planepts[1][2] = mins[2];
+ f->planepts[2][0] = maxs[0];f->planepts[2][1] = maxs[1];f->planepts[2][2] = mins[2];
+
+ for (i=0 ; i<sides ; i++)
+ {
+ f = Face_Alloc();
+ f->texdef = *texdef;
+ f->next = b->brush_faces;
+ b->brush_faces = f;
+
+ sv = sin (i*3.14159265*2/sides);
+ cv = cos (i*3.14159265*2/sides);
+
+
+ f->planepts[0][0] = floor(mid[0]+width*cv+0.5);
+ f->planepts[0][1] = floor(mid[1]+width*sv+0.5);
+ f->planepts[0][2] = mins[2];
+
+ f->planepts[1][0] = mid[0];
+ f->planepts[1][1] = mid[1];
+ f->planepts[1][2] = maxs[2];
+
+ f->planepts[2][0] = floor(f->planepts[0][0] - width * sv + 0.5);
+ f->planepts[2][1] = floor(f->planepts[0][1] + width * cv + 0.5);
+ f->planepts[2][2] = maxs[2];
+
+ }
+
+ Brush_AddToList (b, &selected_brushes);
+
+ Entity_LinkBrush (world_entity, b);
+
+ Brush_Build( b );
+
+ Sys_UpdateWindows (W_ALL);
+}
+
+/*
+=============
+Brush_MakeSided
+
+Makes the current brushhave the given number of 2d sides and turns it into a sphere
+=============
+
+*/
+void Brush_MakeSidedSphere(int sides)
+{
+ int i,j;
+ vec3_t mins, maxs;
+ brush_t *b;
+ texdef_t *texdef;
+ face_t *f;
+ vec3_t mid;
+
+ if (sides < 4)
+ {
+ Sys_Status ("Bad sides number", 0);
+ return;
+ }
+
+ if (!QE_SingleBrush ())
+ {
+ Sys_Status ("Must have a single brush selected", 0 );
+ return;
+ }
+
+ b = selected_brushes.next;
+ VectorCopy (b->mins, mins);
+ VectorCopy (b->maxs, maxs);
+ texdef = &g_qeglobals.d_texturewin.texdef;
+
+ Brush_Free (b);
+
+ // find center of brush
+ float radius = 8;
+ for (i=0 ; i<2 ; i++)
+ {
+ mid[i] = (maxs[i] + mins[i])*0.5;
+ if (maxs[i] - mins[i] > radius)
+ radius = maxs[i] - mins[i];
+ }
+ radius /= 2;
+
+ b = Brush_Alloc();
+
+ float dt = float(2 * Q_PI / sides);
+ float dp = float(Q_PI / sides);
+ float t,p;
+ for(i=0; i <= sides-1; i++)
+ {
+ for(j=0;j <= sides-2; j++)
+ {
+ t = i * dt;
+ p = float(j * dp - Q_PI / 2);
+
+ f = Face_Alloc();
+ f->texdef = *texdef;
+ f->next = b->brush_faces;
+ b->brush_faces = f;
+
+ VectorPolar(f->planepts[0], radius, t, p);
+ VectorPolar(f->planepts[1], radius, t, p + dp);
+ VectorPolar(f->planepts[2], radius, t + dt, p + dp);
+
+ for (int k = 0; k < 3; k++)
+ VectorAdd(f->planepts[k], mid, f->planepts[k]);
+ }
+ }
+
+ p = float((sides - 1) * dp - Q_PI / 2);
+ for(i = 0; i <= sides-1; i++)
+ {
+ t = i * dt;
+
+ f = Face_Alloc();
+ f->texdef = *texdef;
+ f->next = b->brush_faces;
+ b->brush_faces = f;
+
+ VectorPolar(f->planepts[0], radius, t, p);
+ VectorPolar(f->planepts[1], radius, t + dt, p + dp);
+ VectorPolar(f->planepts[2], radius, t + dt, p);
+
+ for (int k = 0; k < 3; k++)
+ VectorAdd(f->planepts[k], mid, f->planepts[k]);
+ }
+
+ Brush_AddToList (b, &selected_brushes);
+
+ Entity_LinkBrush (world_entity, b);
+
+ Brush_Build( b );
+
+ Sys_UpdateWindows (W_ALL);
+}
+
+void Face_FitTexture( face_t * face, int nHeight, int nWidth )
+{
+ winding_t *w;
+ vec3_t mins,maxs;
+ int i;
+ float width, height, temp;
+ float rot_width, rot_height;
+ float cosv,sinv,ang;
+ float min_t, min_s, max_t, max_s;
+ float s,t;
+ vec3_t vecs[2];
+ vec3_t coords[4];
+ texdef_t *td;
+
+ if (nHeight < 1)
+ {
+ nHeight = 1;
+ }
+ if (nWidth < 1)
+ {
+ nWidth = 1;
+ }
+
+ ClearBounds (mins, maxs);
+
+ td = &face->texdef;
+ w = face->face_winding;
+ if (!w)
+ {
+ return;
+ }
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ AddPointToBounds( w->points[i], mins, maxs );
+ }
+ //
+ // get the current angle
+ //
+ ang = td->rotate / 180 * Q_PI;
+ sinv = sin(ang);
+ cosv = cos(ang);
+
+ // get natural texture axis
+ TextureAxisFromPlane(&face->plane, vecs[0], vecs[1]);
+
+ min_s = DotProduct( mins, vecs[0] );
+ min_t = DotProduct( mins, vecs[1] );
+ max_s = DotProduct( maxs, vecs[0] );
+ max_t = DotProduct( maxs, vecs[1] );
+ width = max_s - min_s;
+ height = max_t - min_t;
+ coords[0][0] = min_s;
+ coords[0][1] = min_t;
+ coords[1][0] = max_s;
+ coords[1][1] = min_t;
+ coords[2][0] = min_s;
+ coords[2][1] = max_t;
+ coords[3][0] = max_s;
+ coords[3][1] = max_t;
+ min_s = min_t = 99999;
+ max_s = max_t = -99999;
+ for (i=0; i<4; i++)
+ {
+ s = cosv * coords[i][0] - sinv * coords[i][1];
+ t = sinv * coords[i][0] + cosv * coords[i][1];
+ if (i&1)
+ {
+ if (s > max_s)
+ {
+ max_s = s;
+ }
+ }
+ else
+ {
+ if (s < min_s)
+ {
+ min_s = s;
+ }
+ if (i<2)
+ {
+ if (t < min_t)
+ {
+ min_t = t;
+ }
+ }
+ else
+ {
+ if (t > max_t)
+ {
+ max_t = t;
+ }
+ }
+ }
+ }
+ rot_width = (max_s - min_s);
+ rot_height = (max_t - min_t);
+ td->scale[0] = -(rot_width/((float)(face->d_texture->width*nWidth)));
+ td->scale[1] = -(rot_height/((float)(face->d_texture->height*nHeight)));
+
+ td->shift[0] = min_s/td->scale[0];
+ temp = (int)(td->shift[0] / (face->d_texture->width*nWidth));
+ temp = (temp+1)*face->d_texture->width*nWidth;
+ td->shift[0] = (int)(temp - td->shift[0])%(face->d_texture->width*nWidth);
+
+ td->shift[1] = min_t/td->scale[1];
+ temp = (int)(td->shift[1] / (face->d_texture->height*nHeight));
+ temp = (temp+1)*(face->d_texture->height*nHeight);
+ td->shift[1] = (int)(temp - td->shift[1])%(face->d_texture->height*nHeight);
+}
+
+void Brush_FitTexture( brush_t *b, int nHeight, int nWidth )
+{
+ face_t *face;
+
+ for (face = b->brush_faces ; face ; face=face->next)
+ {
+ Face_FitTexture( face, nHeight, nWidth );
+ }
+}
+
+
diff --git a/q3radiant/BrushScript.cpp b/q3radiant/BrushScript.cpp
new file mode 100755
index 0000000..6a0614a
--- /dev/null
+++ b/q3radiant/BrushScript.cpp
@@ -0,0 +1,672 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// BrushScript stuff
+//
+#include "stdafx.h"
+#include "qe3.h"
+#include "BSInput.h"
+#include "DialogInfo.h"
+
+
+//
+struct SVariableDef
+{
+ CString m_strName;
+ CString m_strInput;
+ float m_fValue;
+};
+
+struct SVecVariableDef
+{
+ CString m_strName;
+ CString m_strInput;
+ vec3_t m_vValue;
+};
+
+
+
+const int MAX_VARIABLES = 64;
+
+brush_t* g_pHold1 = NULL;
+brush_t* g_pHold2 = NULL;
+brush_t* g_pHold3 = NULL;
+bool g_bRotateAroundSelection;
+int g_nVariableCount;
+int g_nVecVariableCount;
+int g_nLoopCounter;
+float g_fDefault = 9999.9;
+vec3_t g_vDefault;
+bool g_bStartLoop;
+char* g_pLooper;
+bool g_bKeepGoing;
+
+SVariableDef g_Variables[MAX_VARIABLES];
+SVecVariableDef g_VecVariables[MAX_VARIABLES];
+
+void InitForScriptRun()
+{
+ g_pHold1 = NULL;
+ g_pHold2 = NULL;
+ g_pHold3 = NULL;
+ g_bRotateAroundSelection = true;
+ g_nVariableCount = 0;
+ g_nVecVariableCount = 0;
+ g_nLoopCounter = 0;
+ g_bStartLoop = false;
+ g_pLooper = NULL;
+ g_bKeepGoing = true;
+}
+
+void AddVariable(const char* pName, float fValue, const char* pInput = NULL)
+{
+ if (g_nVariableCount < MAX_VARIABLES)
+ {
+ g_Variables[g_nVariableCount].m_strName = pName;
+ g_Variables[g_nVariableCount].m_strName.MakeLower();
+ g_Variables[g_nVariableCount].m_fValue = fValue;
+ if (pInput)
+ g_Variables[g_nVariableCount].m_strInput = pInput;
+ g_nVariableCount++;
+ }
+ else
+ g_pParentWnd->MessageBox("Maximum script variable limit reached!");
+}
+
+float VariableValue(const char* pName)
+{
+ CString strName = pName;
+ strName.MakeLower();
+ for (int n = 0; n < g_nVariableCount; n++)
+ {
+ if (strName == g_Variables[n].m_strName)
+ return g_Variables[n].m_fValue;
+ }
+ //strName.Format("Reference to non-existant varirable %s", pName);
+ //g_pParentWnd->MessageBox(strName);
+ return g_fDefault;
+}
+
+void SetVariableValue(const char* pName, float fValue)
+{
+ CString strName = pName;
+ strName.MakeLower();
+ for (int n = 0; n < g_nVariableCount; n++)
+ {
+ if (strName == g_Variables[n].m_strName)
+ g_Variables[n].m_fValue = fValue;
+ }
+}
+
+
+
+void AddVectorVariable(const char* pName, const char* pInput = NULL)
+{
+ if (g_nVecVariableCount < MAX_VARIABLES)
+ {
+ g_VecVariables[g_nVecVariableCount].m_strName = pName;
+ g_VecVariables[g_nVecVariableCount].m_strName.MakeLower();
+ if (pInput)
+ g_VecVariables[g_nVariableCount].m_strInput = pInput;
+ g_nVecVariableCount++;
+ }
+ else
+ g_pParentWnd->MessageBox("Maximum script variable limit reached!");
+}
+
+void VectorVariableValue(const char* pName, vec3_t& v)
+{
+ CString strName = pName;
+ strName.MakeLower();
+ for (int n = 0; n < g_nVecVariableCount; n++)
+ {
+ if (strName == g_VecVariables[n].m_strName)
+ {
+ VectorCopy(g_VecVariables[n].m_vValue, v);
+ return;
+ }
+ }
+ strName.Format("Reference to non-existant variable %s", pName);
+ g_pParentWnd->MessageBox(strName);
+}
+
+void SetVectorVariableValue(const char* pName, vec3_t v)
+{
+ CString strName = pName;
+ strName.MakeLower();
+ for (int n = 0; n < g_nVecVariableCount; n++)
+ {
+ if (strName == g_VecVariables[n].m_strName)
+ VectorCopy(v, g_VecVariables[n].m_vValue);
+ }
+}
+
+
+
+
+
+// commands
+//
+// _CopySelected(nHoldPos)
+// copies selected brush to hold spot 1, 2 or 3
+//
+// _MoveSelected(x, y, z)
+// moves selected brush by coords provided
+//
+// _RotateSelected(x, y, z)
+// rotates selected brush by coords provided
+//
+// _MoveHold(nHoldPos, x, y, z)
+// moves brush in hold pos by coords provided
+//
+// _RotateHold(nHoldPos, x, y, z)
+// rotates brush in hold pos by coords provided
+//
+// _CopyToMap(nHoldPos)
+// copies hold brush to map
+//
+// _CopyAndSelect(nHoldPos)
+// copies hold brush to map and selects it
+//
+// _Input(VarName1, ... VarNamennn)
+// inputs a list of values from the user
+//
+
+typedef void (PFNScript)(char*&);
+
+
+struct SBrushScript
+{
+ const char* m_pName;
+ PFNScript* m_pProc;
+};
+
+
+const char* GetParam(char*& pBuffer)
+{
+ static CString strParam;
+ bool bStringMode = false;
+
+ while (*pBuffer != NULL && isspace(*pBuffer)) // skip and whitespace
+ pBuffer++;
+
+ if (*pBuffer == '(') // if it's an opening paren, skip it
+ pBuffer++;
+
+ if (*pBuffer == '\"') // string ?
+ {
+ pBuffer++;
+ bStringMode = true;
+ }
+
+ strParam = "";
+
+ if (bStringMode)
+ {
+ while (*pBuffer != NULL && *pBuffer != '\"')
+ strParam += *pBuffer++;
+ }
+ else
+ {
+ while (*pBuffer != NULL && *pBuffer != ' ' && *pBuffer != ')' && *pBuffer != ',')
+ strParam += *pBuffer++;
+ }
+
+ if (*pBuffer != NULL) // skip last char
+ pBuffer++;
+
+ if (strParam.GetLength() > 0)
+ {
+ if (strParam.GetAt(0) == '$') // ? variable name
+ {
+ float f = VariableValue(strParam);
+ if (f != g_fDefault)
+ strParam.Format("%f", f);
+ }
+ }
+
+ return strParam;
+}
+
+brush_t* CopyBrush(brush_t* p)
+{
+ brush_t* pCopy = Brush_Clone(p);
+ //Brush_AddToList (pCopy, &active_brushes);
+ //Entity_LinkBrush (world_entity, pCopy);
+ Brush_Build(pCopy, false);
+ return pCopy;
+}
+
+
+void CopySelected(char*& pBuffer)
+{
+ // expects one param
+ CString strParam = GetParam(pBuffer);
+ int n = atoi(strParam);
+
+ brush_t* pCopy = NULL;
+ if (selected_brushes.next != &selected_brushes &&
+ selected_brushes.next->next == &selected_brushes)
+ pCopy = selected_brushes.next;
+
+ if (pCopy)
+ {
+ if (n == 1)
+ {
+ //if (g_pHold1)
+ //Brush_Free(g_pHold1);
+ g_pHold1 = CopyBrush(pCopy);
+ }
+ else if (n == 2)
+ {
+ //if (g_pHold2)
+ //Brush_Free(g_pHold2);
+ g_pHold2 = CopyBrush(pCopy);
+ }
+ else
+ {
+ //if (g_pHold3)
+ //Brush_Free(g_pHold3);
+ g_pHold3 = CopyBrush(pCopy);
+ }
+ }
+}
+
+void MoveSelected(char*& pBuffer)
+{
+ vec3_t v;
+ CString strParam = GetParam(pBuffer);
+ v[0] = atof(strParam);
+ strParam = GetParam(pBuffer);
+ v[1] = atof(strParam);
+ strParam = GetParam(pBuffer);
+ v[2] = atof(strParam);
+ Select_Move(v, false);
+ Sys_UpdateWindows(W_ALL);
+}
+
+void RotateSelected(char*& pBuffer)
+{
+ vec3_t v;
+
+ if (g_bRotateAroundSelection)
+ {
+ Select_GetTrueMid(v);
+ VectorCopy(v, g_pParentWnd->ActiveXY()->RotateOrigin());
+ }
+
+ CString strParam = GetParam(pBuffer);
+ v[0] = atof(strParam);
+ strParam = GetParam(pBuffer);
+ v[1] = atof(strParam);
+ strParam = GetParam(pBuffer);
+ v[2] = atof(strParam);
+ for (int i = 0; i < 3; i++)
+ if (v[i] != 0.0)
+ Select_RotateAxis(i, v[i], false , true);
+ Sys_UpdateWindows(W_ALL);
+}
+
+void MoveHold(char*& pBuffer)
+{
+ CString strParam = GetParam(pBuffer);
+ brush_t* pBrush = NULL;
+ int nHold = atoi(strParam);
+ if (nHold == 1)
+ pBrush = g_pHold1;
+ else if (nHold == 2)
+ pBrush = g_pHold2;
+ else
+ pBrush = g_pHold3;
+
+ if (pBrush)
+ {
+ vec3_t v;
+ strParam = GetParam(pBuffer);
+ v[0] = atof(strParam);
+ strParam = GetParam(pBuffer);
+ v[1] = atof(strParam);
+ strParam = GetParam(pBuffer);
+ v[2] = atof(strParam);
+ Brush_Move (pBrush, v, false);
+ }
+}
+
+void RotateHold(char*& pBuffer)
+{
+ CString strParam = GetParam(pBuffer);
+ brush_t* pBrush = NULL;
+ int nHold = atoi(strParam);
+ if (nHold == 1)
+ pBrush = g_pHold1;
+ else if (nHold == 2)
+ pBrush = g_pHold2;
+ else
+ pBrush = g_pHold3;
+
+ if (pBrush)
+ {
+ vec3_t v;
+ strParam = GetParam(pBuffer);
+ v[0] = atof(strParam);
+ strParam = GetParam(pBuffer);
+ v[1] = atof(strParam);
+ strParam = GetParam(pBuffer);
+ v[2] = atof(strParam);
+ for (int i = 0; i < 3; i++)
+ if (v[i] != 0.0)
+ Select_RotateAxis(i, v[i]);
+ }
+}
+
+void CopyToMap(char*& pBuffer)
+{
+ CString strParam = GetParam(pBuffer);
+ brush_t* pBrush = NULL;
+ int nHold = atoi(strParam);
+ if (nHold == 1)
+ pBrush = g_pHold1;
+ else if (nHold == 2)
+ pBrush = g_pHold2;
+ else
+ pBrush = g_pHold3;
+
+ if (pBrush)
+ {
+ Brush_AddToList(pBrush, &active_brushes);
+ Entity_LinkBrush (world_entity, pBrush);
+ Brush_Build(pBrush, false);
+ Sys_UpdateWindows(W_ALL);
+ }
+}
+
+void CopyAndSelect(char*& pBuffer)
+{
+ CString strParam = GetParam(pBuffer);
+ brush_t* pBrush = NULL;
+ int nHold = atoi(strParam);
+ if (nHold == 1)
+ pBrush = g_pHold1;
+ else if (nHold == 2)
+ pBrush = g_pHold2;
+ else
+ pBrush = g_pHold3;
+
+ if (pBrush)
+ {
+ Select_Deselect();
+ Brush_AddToList(pBrush, &active_brushes);
+ Entity_LinkBrush (world_entity, pBrush);
+ Brush_Build(pBrush, false);
+ Select_Brush(pBrush);
+ Sys_UpdateWindows(W_ALL);
+ }
+}
+
+void Input(char*& pBuffer)
+{
+ CBSInput dlg;
+ bool bGo = false;
+ for (int n = 0; n < g_nVariableCount; n++)
+ {
+ if (g_Variables[n].m_strInput.GetLength() > 0)
+ {
+ bGo = true;
+ if (n < 5)
+ {
+ switch (n)
+ {
+ case 0 : dlg.m_strField1 = g_Variables[n].m_strInput; break;
+ case 1 : dlg.m_strField2 = g_Variables[n].m_strInput; break;
+ case 2 : dlg.m_strField3 = g_Variables[n].m_strInput; break;
+ case 3 : dlg.m_strField4 = g_Variables[n].m_strInput; break;
+ case 4 : dlg.m_strField5 = g_Variables[n].m_strInput; break;
+ }
+ }
+ }
+ }
+ if (bGo)
+ {
+ if (dlg.DoModal() == IDOK)
+ {
+ for (int n = 0; n < g_nVariableCount; n++)
+ {
+ if (g_Variables[n].m_strInput.GetLength() > 0)
+ {
+ if (n < 5)
+ {
+ switch (n)
+ {
+ case 0 : g_Variables[n].m_fValue = dlg.m_fField1; break;
+ case 1 : g_Variables[n].m_fValue = dlg.m_fField2; break;
+ case 2 : g_Variables[n].m_fValue = dlg.m_fField3; break;
+ case 3 : g_Variables[n].m_fValue = dlg.m_fField4; break;
+ case 4 : g_Variables[n].m_fValue = dlg.m_fField5; break;
+ }
+ }
+ }
+ }
+ }
+ else g_bKeepGoing = false;
+ }
+}
+
+bool g_bWaiting;
+void _3DPointDone(bool b, int n)
+{
+ g_bWaiting = false;
+}
+
+void _3DPointInput(char*& pBuffer)
+{
+ CString strParam = GetParam(pBuffer);
+ CString strParam2 = GetParam(pBuffer);
+ ShowInfoDialog(strParam2);
+ AddVectorVariable(strParam, strParam2);
+ g_bWaiting = true;
+ AcquirePath(2, &_3DPointDone);
+ while (g_bWaiting)
+ {
+ MSG msg;
+ if (::PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ))
+ {
+ TranslateMessage(&msg);
+ DispatchMessage(&msg);
+ }
+ }
+ HideInfoDialog();
+ SetVectorVariableValue(strParam, g_PathPoints[0]);
+}
+
+void SetRotateOrigin(char*& pBuffer)
+{
+ vec3_t v;
+ CString strParam = GetParam(pBuffer);
+ VectorVariableValue(strParam, v);
+ VectorCopy(v, g_pParentWnd->ActiveXY()->RotateOrigin());
+ g_bRotateAroundSelection = false;
+}
+
+void InputVar(char*& pBuffer)
+{
+ CString strParam = GetParam(pBuffer);
+ CString strParam2 = GetParam(pBuffer);
+ AddVariable(strParam, 0.0, strParam2);
+}
+
+void LoopCount(char*& pBuffer)
+{
+ CString strParam = GetParam(pBuffer);
+ g_nLoopCounter = atoi(strParam);
+ if (g_nLoopCounter == 0)
+ g_nLoopCounter = VariableValue(strParam);
+ if (g_nLoopCounter > 0)
+ g_pLooper = pBuffer;
+}
+
+void LoopRun(char*& pBuffer)
+{
+ if (g_bStartLoop == true)
+ {
+ g_nLoopCounter--;
+ if (g_nLoopCounter == 0)
+ {
+ g_bStartLoop = false;
+ GetParam(pBuffer);
+ }
+ else
+ pBuffer = g_pLooper;
+ }
+ else
+ {
+ if (g_pLooper && g_nLoopCounter > 0)
+ {
+ g_bStartLoop = true;
+ pBuffer = g_pLooper;
+ }
+ else
+ {
+ GetParam(pBuffer);
+ }
+ }
+}
+
+
+void ConfirmMessage(char*& pBuffer)
+{
+ CString strParam = GetParam(pBuffer);
+ if (g_pParentWnd->MessageBox(strParam, "Script Info", MB_OKCANCEL) == IDCANCEL)
+ g_bKeepGoing = false;
+}
+
+void Spherize(char*& pBuffer)
+{
+ g_bScreenUpdates = false;
+ for (int n = 0; n < 120; n += 36)
+ {
+ for (int i = 0; i < 360; i += 36)
+ {
+ Select_RotateAxis(0, i, false , true);
+ CSG_Subtract();
+ }
+ Select_RotateAxis(2, n, false , true);
+ }
+ g_bScreenUpdates = true;
+}
+
+void RunIt(char*& pBuffer);
+SBrushScript g_ScriptCmds[] =
+{
+ {"_CopySelected", &CopySelected},
+ {"_MoveSelected", &MoveSelected},
+ {"_RotateSelected", &RotateSelected},
+ {"_MoveHold", &MoveHold},
+ {"_RotateHold", &RotateHold},
+ {"_CopyToMap", &CopyToMap},
+ {"_CopyAndSelect", &CopyAndSelect},
+ {"_Input", &Input},
+ {"_3DPointInput", &_3DPointInput},
+ {"_SetRotateOrigin", &SetRotateOrigin},
+ {"_InputVar", &InputVar},
+ {"_LoopCount", &LoopCount},
+ {"_LoopRun", &LoopRun},
+ {"_ConfirmMessage", &ConfirmMessage},
+ {"_Spherize", &Spherize},
+ {"_RunScript", RunIt}
+};
+
+const int g_nScriptCmdCount = sizeof(g_ScriptCmds) / sizeof(SBrushScript);
+
+void RunScript(char* pBuffer)
+{
+ g_pHold1 = NULL;
+ g_pHold2 = NULL;
+ g_pHold3 = NULL;
+
+ while (g_bKeepGoing && pBuffer && *pBuffer)
+ {
+ while (*pBuffer != NULL && *pBuffer != '_')
+ pBuffer++;
+
+ char* pTemp = pBuffer;
+ int nLen = 0;
+ while (*pTemp != NULL && *pTemp != '(')
+ {
+ pTemp++;
+ nLen++;
+ }
+ if (*pBuffer != NULL)
+ {
+ bool bFound = false;
+ for (int i = 0; i < g_nScriptCmdCount; i++)
+ {
+ //if (strnicmp(g_ScriptCmds[i].m_pName, pBuffer, strlen(g_ScriptCmds[i].m_pName)) == 0)
+ if (strnicmp(g_ScriptCmds[i].m_pName, pBuffer, nLen) == 0)
+ {
+ pBuffer += strlen(g_ScriptCmds[i].m_pName);
+ g_ScriptCmds[i].m_pProc(pBuffer);
+ if (g_bStartLoop)
+ {
+ }
+ bFound = true;
+ break;
+ }
+ }
+ if (!bFound)
+ pBuffer++;
+ }
+ }
+}
+
+
+void RunScriptByName(char* pBuffer, bool bInit)
+{
+ if (bInit)
+ InitForScriptRun();
+ char* pScript = new char[4096];
+ CString strINI = g_strAppPath;
+ strINI += "\\scripts.ini";
+ GetPrivateProfileSection(pBuffer, pScript, 16384, strINI);
+ CString strScript;
+ char* pWorkScript = pScript;
+ while (*pWorkScript != NULL)
+ {
+ strScript += pWorkScript;
+ pWorkScript += strlen(pWorkScript) + 1;
+ }
+ RunScript(strScript.GetBuffer(0));
+}
+
+
+void RunIt(char*& pBuffer)
+{
+ brush_t* p1 = g_pHold1;
+ brush_t* p2 = g_pHold2;
+ brush_t* p3 = g_pHold3;
+
+ CString strParam = GetParam(pBuffer);
+ RunScriptByName(strParam.GetBuffer(0), false);
+
+ g_pHold3 = p3;
+ g_pHold2 = p2;
+ g_pHold1 = p1;
+}
+
diff --git a/q3radiant/CAMERA.H b/q3radiant/CAMERA.H
new file mode 100755
index 0000000..a1fbfa1
--- /dev/null
+++ b/q3radiant/CAMERA.H
@@ -0,0 +1,51 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+// window system independent camera view code
+
+typedef enum
+{
+ cd_wire,
+ cd_solid,
+ cd_texture,
+ cd_light,
+ cd_blend
+} camera_draw_mode;
+
+typedef struct
+{
+ int width, height;
+
+ qboolean timing;
+
+ vec3_t origin;
+ vec3_t angles;
+
+ camera_draw_mode draw_mode;
+
+ vec3_t color; // background
+
+ vec3_t forward, right, up; // move matrix
+
+ vec3_t vup, vpn, vright; // view matrix
+} camera_t;
+
diff --git a/q3radiant/CSG.CPP b/q3radiant/CSG.CPP
new file mode 100755
index 0000000..eef0b14
--- /dev/null
+++ b/q3radiant/CSG.CPP
@@ -0,0 +1,686 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "stdafx.h"
+#include "qe3.h"
+#include "winding.h"
+
+
+/*
+=============
+CSG_MakeHollow
+=============
+*/
+
+void Brush_Scale(brush_t* b)
+{
+ for (face_t* f = b->brush_faces ; f ; f=f->next)
+ {
+ for (int i=0 ; i<3 ; i++)
+ {
+ VectorScale (f->planepts[i], g_qeglobals.d_gridsize, f->planepts[i]);
+ }
+ }
+}
+
+void CSG_MakeHollow (void)
+{
+ brush_t *b, *front, *back, *next;
+ face_t *f;
+ face_t split;
+ vec3_t move;
+ int i;
+
+ for (b = selected_brushes.next ; b != &selected_brushes ; b=next)
+ {
+ next = b->next;
+
+ if (b->owner->eclass->fixedsize || b->patchBrush || b->terrainBrush || b->hiddenBrush)
+ continue;
+
+ for (f = b->brush_faces ; f ; f=f->next)
+ {
+ split = *f;
+ VectorScale (f->plane.normal, g_qeglobals.d_gridsize, move);
+ for (i=0 ; i<3 ; i++)
+ VectorSubtract (split.planepts[i], move, split.planepts[i]);
+
+ Brush_SplitBrushByFace (b, &split, &front, &back);
+ if (back)
+ Brush_Free (back);
+ if (front)
+ Brush_AddToList (front, &selected_brushes);
+ }
+ Brush_Free (b);
+ }
+ Sys_UpdateWindows (W_ALL);
+}
+
+/*
+=============
+Brush_Merge
+
+ Returns a new brush that is created by merging brush1 and brush2.
+ May return NULL if brush1 and brush2 do not create a convex brush when merged.
+ The input brushes brush1 and brush2 stay intact.
+
+ if onlyshape is true then the merge is allowed based on the shape only
+ otherwise the texture/shader references of faces in the same plane have to
+ be the same as well.
+=============
+*/
+brush_t *Brush_Merge(brush_t *brush1, brush_t *brush2, int onlyshape)
+{
+ int i, shared;
+ brush_t *newbrush;
+ face_t *face1, *face2, *newface, *f;
+
+ // check for bounding box overlapp
+ for (i = 0; i < 3; i++)
+ {
+ if (brush1->mins[i] > brush2->maxs[i] + ON_EPSILON
+ || brush1->maxs[i] < brush2->mins[i] - ON_EPSILON)
+ {
+ // never merge if the brushes overlap
+ return NULL;
+ }
+ }
+ //
+ shared = 0;
+ // check if the new brush would be convex... flipped planes make a brush non-convex
+ for (face1 = brush1->brush_faces; face1; face1 = face1->next)
+ {
+ // don't check the faces of brush 1 and 2 touching each other
+ for (face2 = brush2->brush_faces; face2; face2 = face2->next)
+ {
+ if (Plane_Equal(&face1->plane, &face2->plane, true))
+ {
+ shared++;
+ // there may only be ONE shared side
+ if (shared > 1)
+ return NULL;
+ break;
+ }
+ }
+ // if this face plane is shared
+ if (face2) continue;
+ //
+ for (face2 = brush2->brush_faces; face2; face2 = face2->next)
+ {
+ // don't check the faces of brush 1 and 2 touching each other
+ for (f = brush1->brush_faces; f; f = f->next)
+ {
+ if (Plane_Equal(&face2->plane, &f->plane, true)) break;
+ }
+ if (f)
+ continue;
+ //
+ if (Plane_Equal(&face1->plane, &face2->plane, false))
+ {
+ //if the texture/shader references should be the same but are not
+ if (!onlyshape && stricmp(face1->texdef.name, face2->texdef.name) != 0) return NULL;
+ continue;
+ }
+ //
+ if (Winding_PlanesConcave(face1->face_winding, face2->face_winding,
+ face1->plane.normal, face2->plane.normal,
+ face1->plane.dist, face2->plane.dist))
+ {
+ return NULL;
+ } //end if
+ } //end for
+ } //end for
+ //
+ newbrush = Brush_Alloc();
+ //
+ for (face1 = brush1->brush_faces; face1; face1 = face1->next)
+ {
+ // don't add the faces of brush 1 and 2 touching each other
+ for (face2 = brush2->brush_faces; face2; face2 = face2->next)
+ {
+ if (Plane_Equal(&face1->plane, &face2->plane, true))
+ break;
+ }
+ if (face2)
+ continue;
+ // don't add faces with the same plane twice
+ for (f = newbrush->brush_faces; f; f = f->next)
+ {
+ if (Plane_Equal(&face1->plane, &f->plane, false))
+ break;
+ if (Plane_Equal(&face1->plane, &f->plane, true))
+ break;
+ }
+ if (f)
+ continue;
+ //
+ newface = Face_Alloc();
+ newface->texdef = face1->texdef;
+ VectorCopy(face1->planepts[0], newface->planepts[0]);
+ VectorCopy(face1->planepts[1], newface->planepts[1]);
+ VectorCopy(face1->planepts[2], newface->planepts[2]);
+ newface->plane = face1->plane;
+ newface->next = newbrush->brush_faces;
+ newbrush->brush_faces = newface;
+ }
+ //
+ for (face2 = brush2->brush_faces; face2; face2 = face2->next)
+ {
+ // don't add the faces of brush 1 and 2 touching each other
+ for (face1 = brush1->brush_faces; face1; face1 = face1->next)
+ {
+ if (Plane_Equal(&face2->plane, &face1->plane, true))
+ break;
+ }
+ if (face1)
+ continue;
+ // don't add faces with the same plane twice
+ for (f = newbrush->brush_faces; f; f = f->next)
+ {
+ if (Plane_Equal(&face2->plane, &f->plane, false))
+ break;
+ if (Plane_Equal(&face2->plane, &f->plane, true))
+ break;
+ }
+ if (f)
+ continue;
+ //
+ newface = Face_Alloc();
+ newface->texdef = face2->texdef;
+ VectorCopy(face2->planepts[0], newface->planepts[0]);
+ VectorCopy(face2->planepts[1], newface->planepts[1]);
+ VectorCopy(face2->planepts[2], newface->planepts[2]);
+ newface->plane = face2->plane;
+ newface->next = newbrush->brush_faces;
+ newbrush->brush_faces = newface;
+ }
+ // link the new brush to an entity
+ Entity_LinkBrush (brush1->owner, newbrush);
+ // build windings for the faces
+ Brush_BuildWindings( newbrush, false);
+ return newbrush;
+}
+
+/*
+=============
+Brush_MergeListPairs
+
+ Returns a list with merged brushes.
+ Tries to merge brushes pair wise.
+ The input list is destroyed.
+ Input and output should be a single linked list using .next
+=============
+*/
+brush_t *Brush_MergeListPairs(brush_t *brushlist, int onlyshape)
+{
+ int nummerges, merged;
+ brush_t *b1, *b2, *tail, *newbrush, *newbrushlist;
+ brush_t *lastb2;
+
+ if (!brushlist) return NULL;
+
+ nummerges = 0;
+ do
+ {
+ for (tail = brushlist; tail; tail = tail->next)
+ {
+ if (!tail->next) break;
+ }
+ merged = 0;
+ newbrushlist = NULL;
+ for (b1 = brushlist; b1; b1 = brushlist)
+ {
+ lastb2 = b1;
+ for (b2 = b1->next; b2; b2 = b2->next)
+ {
+ newbrush = Brush_Merge(b1, b2, onlyshape);
+ if (newbrush)
+ {
+ tail->next = newbrush;
+ lastb2->next = b2->next;
+ brushlist = brushlist->next;
+ b1->next = b1->prev = NULL;
+ b2->next = b2->prev = NULL;
+ Brush_Free(b1);
+ Brush_Free(b2);
+ for (tail = brushlist; tail; tail = tail->next)
+ {
+ if (!tail->next) break;
+ } //end for
+ merged++;
+ nummerges++;
+ break;
+ }
+ lastb2 = b2;
+ }
+ //if b1 can't be merged with any of the other brushes
+ if (!b2)
+ {
+ brushlist = brushlist->next;
+ //keep b1
+ b1->next = newbrushlist;
+ newbrushlist = b1;
+ }
+ }
+ brushlist = newbrushlist;
+ } while(merged);
+ return newbrushlist;
+}
+
+/*
+=============
+Brush_MergeList
+
+ Tries to merge all brushes in the list into one new brush.
+ The input brush list stays intact.
+ Returns NULL if no merged brush can be created.
+ To create a new brush the brushes in the list may not overlap and
+ the outer faces of the brushes together should make a new convex brush.
+
+ if onlyshape is true then the merge is allowed based on the shape only
+ otherwise the texture/shader references of faces in the same plane have to
+ be the same as well.
+=============
+*/
+brush_t *Brush_MergeList(brush_t *brushlist, int onlyshape)
+{
+ brush_t *brush1, *brush2, *brush3, *newbrush;
+ face_t *face1, *face2, *face3, *newface, *f;
+
+ if (!brushlist) return NULL;
+ for (brush1 = brushlist; brush1; brush1 = brush1->next)
+ {
+ // check if the new brush would be convex... flipped planes make a brush concave
+ for (face1 = brush1->brush_faces; face1; face1 = face1->next)
+ {
+ // don't check face1 if it touches another brush
+ for (brush2 = brushlist; brush2; brush2 = brush2->next)
+ {
+ if (brush2 == brush1) continue;
+ for (face2 = brush2->brush_faces; face2; face2 = face2->next)
+ {
+ if (Plane_Equal(&face1->plane, &face2->plane, true))
+ {
+ break;
+ }
+ }
+ if (face2) break;
+ }
+ // if face1 touches another brush
+ if (brush2) continue;
+ //
+ for (brush2 = brush1->next; brush2; brush2 = brush2->next)
+ {
+ // don't check the faces of brush 2 touching another brush
+ for (face2 = brush2->brush_faces; face2; face2 = face2->next)
+ {
+ for (brush3 = brushlist; brush3; brush3 = brush3->next)
+ {
+ if (brush3 == brush2) continue;
+ for (face3 = brush3->brush_faces; face3; face3 = face3->next)
+ {
+ if (Plane_Equal(&face2->plane, &face3->plane, true)) break;
+ }
+ if (face3) break;
+ }
+ // if face2 touches another brush
+ if (brush3) continue;
+ //
+ if (Plane_Equal(&face1->plane, &face2->plane, false))
+ {
+ //if the texture/shader references should be the same but are not
+ if (!onlyshape && stricmp(face1->texdef.name, face2->texdef.name) != 0) return NULL;
+ continue;
+ }
+ //
+ if (Winding_PlanesConcave(face1->face_winding, face2->face_winding,
+ face1->plane.normal, face2->plane.normal,
+ face1->plane.dist, face2->plane.dist))
+ {
+ return NULL;
+ }
+ }
+ }
+ }
+ }
+ //
+ newbrush = Brush_Alloc();
+ //
+ for (brush1 = brushlist; brush1; brush1 = brush1->next)
+ {
+ for (face1 = brush1->brush_faces; face1; face1 = face1->next)
+ {
+ // don't add face1 to the new brush if it touches another brush
+ for (brush2 = brushlist; brush2; brush2 = brush2->next)
+ {
+ if (brush2 == brush1) continue;
+ for (face2 = brush2->brush_faces; face2; face2 = face2->next)
+ {
+ if (Plane_Equal(&face1->plane, &face2->plane, true))
+ {
+ break;
+ }
+ }
+ if (face2) break;
+ }
+ if (brush2) continue;
+ // don't add faces with the same plane twice
+ for (f = newbrush->brush_faces; f; f = f->next)
+ {
+ if (Plane_Equal(&face1->plane, &f->plane, false))
+ break;
+ if (Plane_Equal(&face1->plane, &f->plane, true))
+ break;
+ }
+ if (f)
+ continue;
+ //
+ newface = Face_Alloc();
+ newface->texdef = face1->texdef;
+ VectorCopy(face1->planepts[0], newface->planepts[0]);
+ VectorCopy(face1->planepts[1], newface->planepts[1]);
+ VectorCopy(face1->planepts[2], newface->planepts[2]);
+ newface->plane = face1->plane;
+ newface->next = newbrush->brush_faces;
+ newbrush->brush_faces = newface;
+ }
+ }
+ // link the new brush to an entity
+ Entity_LinkBrush (brushlist->owner, newbrush);
+ // build windings for the faces
+ Brush_BuildWindings( newbrush, false);
+ return newbrush;
+}
+
+/*
+=============
+Brush_Subtract
+
+ Returns a list of brushes that remain after B is subtracted from A.
+ May by empty if A is contained inside B.
+ The originals are undisturbed.
+=============
+*/
+brush_t *Brush_Subtract(brush_t *a, brush_t *b)
+{
+ // a - b = out (list)
+ brush_t *front, *back;
+ brush_t *in, *out, *next;
+ face_t *f;
+
+ in = a;
+ out = NULL;
+ for (f = b->brush_faces; f && in; f = f->next)
+ {
+ Brush_SplitBrushByFace(in, f, &front, &back);
+ if (in != a) Brush_Free(in);
+ if (front)
+ { // add to list
+ front->next = out;
+ out = front;
+ }
+ in = back;
+ }
+ //NOTE: in != a just in case brush b has no faces
+ if (in && in != a)
+ {
+ Brush_Free(in);
+ }
+ else
+ { //didn't really intersect
+ for (b = out; b; b = next)
+ {
+ next = b->next;
+ b->next = b->prev = NULL;
+ Brush_Free(b);
+ }
+ return a;
+ }
+ return out;
+}
+
+/*
+=============
+CSG_Subtract
+=============
+*/
+void CSG_Subtract (void)
+{
+ brush_t *b, *s, *fragments, *nextfragment, *frag, *next, *snext;
+ brush_t fragmentlist;
+ int i, numfragments, numbrushes;
+
+ Sys_Printf ("Subtracting...\n");
+
+ if (selected_brushes.next == &selected_brushes)
+ {
+ Sys_Printf("No brushes selected.\n");
+ return;
+ }
+
+ fragmentlist.next = &fragmentlist;
+ fragmentlist.prev = &fragmentlist;
+
+ numfragments = 0;
+ numbrushes = 0;
+ for (b = selected_brushes.next ; b != &selected_brushes ; b=next)
+ {
+ next = b->next;
+
+ if (b->owner->eclass->fixedsize)
+ continue; // can't use texture from a fixed entity, so don't subtract
+
+ // chop all fragments further up
+ for (s = fragmentlist.next; s != &fragmentlist; s = snext)
+ {
+ snext = s->next;
+
+ for (i=0 ; i<3 ; i++)
+ if (b->mins[i] >= s->maxs[i] - ON_EPSILON
+ || b->maxs[i] <= s->mins[i] + ON_EPSILON)
+ break;
+ if (i != 3)
+ continue; // definately don't touch
+ fragments = Brush_Subtract(s, b);
+ // if the brushes did not really intersect
+ if (fragments == s)
+ continue;
+ // try to merge fragments
+ fragments = Brush_MergeListPairs(fragments, true);
+ // add the fragments to the list
+ for (frag = fragments; frag; frag = nextfragment)
+ {
+ nextfragment = frag->next;
+ frag->next = NULL;
+ frag->owner = s->owner;
+ Brush_AddToList(frag, &fragmentlist);
+ }
+ // free the original brush
+ Brush_Free(s);
+ }
+
+ // chop any active brushes up
+ for (s = active_brushes.next; s != &active_brushes; s = snext)
+ {
+ snext = s->next;
+
+ if (s->owner->eclass->fixedsize || s->patchBrush || s->terrainBrush || s->hiddenBrush)
+ continue;
+
+ //face_t *pFace = s->brush_faces;
+ if (s->brush_faces->d_texture->bFromShader && (s->brush_faces->d_texture->nShaderFlags & QER_NOCARVE))
+ {
+ continue;
+ }
+
+ for (i=0 ; i<3 ; i++)
+ if (b->mins[i] >= s->maxs[i] - ON_EPSILON
+ || b->maxs[i] <= s->mins[i] + ON_EPSILON)
+ break;
+ if (i != 3)
+ continue; // definately don't touch
+
+ fragments = Brush_Subtract(s, b);
+ // if the brushes did not really intersect
+ if (fragments == s)
+ continue;
+ //
+ Undo_AddBrush(s);
+ // one extra brush chopped up
+ numbrushes++;
+ // try to merge fragments
+ fragments = Brush_MergeListPairs(fragments, true);
+ // add the fragments to the list
+ for (frag = fragments; frag; frag = nextfragment)
+ {
+ nextfragment = frag->next;
+ frag->next = NULL;
+ frag->owner = s->owner;
+ Brush_AddToList(frag, &fragmentlist);
+ }
+ // free the original brush
+ Brush_Free(s);
+ }
+ }
+
+ // move all fragments to the active brush list
+ for (frag = fragmentlist.next; frag != &fragmentlist; frag = nextfragment)
+ {
+ nextfragment = frag->next;
+ numfragments++;
+ Brush_RemoveFromList(frag);
+ Brush_AddToList(frag, &active_brushes);
+ Undo_EndBrush(frag);
+ }
+
+ if (numfragments == 0)
+ {
+ Sys_Printf("Selected brush%s did not intersect with any other brushes.\n",
+ (selected_brushes.next->next == &selected_brushes) ? "":"es");
+ return;
+ }
+ Sys_Printf("done. (created %d fragment%s out of %d brush%s)\n", numfragments, (numfragments == 1)?"":"s",
+ numbrushes, (numbrushes == 1)?"":"es");
+ Sys_UpdateWindows(W_ALL);
+}
+
+/*
+=============
+CSG_Merge
+=============
+*/
+void CSG_Merge(void)
+{
+ brush_t *b, *next, *newlist, *newbrush;
+ struct entity_s *owner;
+
+ Sys_Printf ("Merging...\n");
+
+ if (selected_brushes.next == &selected_brushes)
+ {
+ Sys_Printf("No brushes selected.\n");
+ return;
+ }
+
+ if (selected_brushes.next->next == &selected_brushes)
+ {
+ Sys_Printf("At least two brushes have to be selected.\n");
+ return;
+ }
+
+ owner = selected_brushes.next->owner;
+
+ for (b = selected_brushes.next; b != &selected_brushes; b = next)
+ {
+ next = b->next;
+
+ if (b->owner->eclass->fixedsize)
+ {
+ // can't use texture from a fixed entity, so don't subtract
+ Sys_Printf("Cannot add fixed size entities.\n");
+ return;
+ }
+
+ if (b->patchBrush)
+ {
+ Sys_Printf("Cannot add patches.\n");
+ return;
+ }
+ if (b->terrainBrush)
+ {
+ Sys_Printf("Cannot add terrains.\n");
+ return;
+ }
+
+ if (b->brush_faces->d_texture->bFromShader && (b->brush_faces->d_texture->nShaderFlags & QER_NOCARVE))
+ {
+ Sys_Printf("Cannot add brushes using shaders that don't allows CSG operations.\n");
+ return;
+ }
+
+ if (b->owner != owner)
+ {
+ Sys_Printf("Cannot add brushes from different entities.\n");
+ return;
+ }
+
+ }
+
+ newlist = NULL;
+ for (b = selected_brushes.next; b != &selected_brushes; b = next)
+ {
+ next = b->next;
+
+ Brush_RemoveFromList(b);
+ b->next = newlist;
+ b->prev = NULL;
+ newlist = b;
+ }
+
+ newbrush = Brush_MergeList(newlist, true);
+ // if the new brush would not be convex
+ if (!newbrush)
+ {
+ // add the brushes back into the selection
+ for (b = newlist; b; b = next)
+ {
+ next = b->next;
+ b->next = NULL;
+ b->prev = NULL;
+ Brush_AddToList(b, &selected_brushes);
+ }
+ Sys_Printf("Cannot add a set of brushes with a concave hull.\n");
+ return;
+ }
+ // free the original brushes
+ for (b = newlist; b; b = next)
+ {
+ next = b->next;
+ b->next = NULL;
+ b->prev = NULL;
+ Brush_Free(b);
+ }
+ Brush_AddToList(newbrush, &selected_brushes);
+
+ Sys_Printf ("done.\n");
+ Sys_UpdateWindows (W_ALL);
+}
diff --git a/q3radiant/CamWnd.cpp b/q3radiant/CamWnd.cpp
new file mode 100755
index 0000000..0ea352d
--- /dev/null
+++ b/q3radiant/CamWnd.cpp
@@ -0,0 +1,1165 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// CamWnd.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "XYWnd.h"
+#include "CamWnd.h"
+#include "qe3.h"
+#include "splines/splines.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+extern void DrawPathLines();
+
+int g_nAngleSpeed = 300;
+int g_nMoveSpeed = 400;
+
+
+/////////////////////////////////////////////////////////////////////////////
+// CCamWnd
+IMPLEMENT_DYNCREATE(CCamWnd, CWnd);
+
+CCamWnd::CCamWnd()
+{
+ m_pXYFriend = NULL;
+ m_nNumTransBrushes = 0;
+ memset(&m_Camera, 0, sizeof(camera_t));
+ m_pSide_select = NULL;
+ m_bClipMode = false;
+ Cam_Init();
+}
+
+CCamWnd::~CCamWnd()
+{
+}
+
+
+BEGIN_MESSAGE_MAP(CCamWnd, CWnd)
+ //{{AFX_MSG_MAP(CCamWnd)
+ ON_WM_KEYDOWN()
+ ON_WM_PAINT()
+ ON_WM_DESTROY()
+ ON_WM_CLOSE()
+ ON_WM_MOUSEMOVE()
+ ON_WM_LBUTTONDOWN()
+ ON_WM_LBUTTONUP()
+ ON_WM_MBUTTONDOWN()
+ ON_WM_MBUTTONUP()
+ ON_WM_RBUTTONDOWN()
+ ON_WM_RBUTTONUP()
+ ON_WM_CREATE()
+ ON_WM_SIZE()
+ ON_WM_NCCALCSIZE()
+ ON_WM_KILLFOCUS()
+ ON_WM_SETFOCUS()
+ ON_WM_KEYUP()
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+
+LONG WINAPI CamWndProc (
+ HWND hWnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam)
+{
+ RECT rect;
+
+ GetClientRect(hWnd, &rect);
+
+ switch (uMsg)
+ {
+ case WM_KILLFOCUS:
+ case WM_SETFOCUS:
+ SendMessage( hWnd, WM_NCACTIVATE, uMsg == WM_SETFOCUS, 0 );
+ return 0;
+
+ case WM_NCCALCSIZE:// don't let windows copy pixels
+ DefWindowProc (hWnd, uMsg, wParam, lParam);
+ return WVR_REDRAW;
+
+ }
+
+ return DefWindowProc( hWnd, uMsg, wParam, lParam );
+}
+
+
+/////////////////////////////////////////////////////////////////////////////
+// CCamWnd message handlers
+
+BOOL CCamWnd::PreCreateWindow(CREATESTRUCT& cs)
+{
+ WNDCLASS wc;
+ HINSTANCE hInstance = AfxGetInstanceHandle();
+ if (::GetClassInfo(hInstance, CAMERA_WINDOW_CLASS, &wc) == FALSE)
+ {
+ // Register a new class
+ memset (&wc, 0, sizeof(wc));
+ wc.style = CS_NOCLOSE | CS_OWNDC;
+ wc.lpszClassName = CAMERA_WINDOW_CLASS;
+ wc.hCursor = LoadCursor (NULL,IDC_ARROW);
+ wc.lpfnWndProc = CamWndProc;
+ if (AfxRegisterClass(&wc) == FALSE)
+ Error ("CCamWnd RegisterClass: failed");
+ }
+
+ cs.lpszClass = CAMERA_WINDOW_CLASS;
+ cs.lpszName = "CAM";
+ if (cs.style != QE3_CHILDSTYLE)
+ cs.style = QE3_SPLITTER_STYLE;
+
+ BOOL bResult = CWnd::PreCreateWindow(cs);
+
+ // See if the class already exists and if not then we need
+ // to register our new window class.
+ return bResult;
+
+}
+
+
+void CCamWnd::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
+{
+ g_pParentWnd->HandleKey(nChar, nRepCnt, nFlags);
+}
+
+
+brush_t* g_pSplitList = NULL;
+
+void CCamWnd::OnPaint()
+{
+ CPaintDC dc(this); // device context for painting
+ bool bPaint = true;
+ if (!qwglMakeCurrent( dc.m_hDC, g_qeglobals.d_hglrcBase ))
+ {
+ Sys_Printf("ERROR: wglMakeCurrent failed..\n ");
+ Sys_Printf("Please restart Q3Radiant if the camera view is not working\n");
+ }
+ else
+ {
+ QE_CheckOpenGLForErrors();
+ g_pSplitList = NULL;
+ if (g_bClipMode)
+ {
+ if (g_Clip1.Set() && g_Clip2.Set())
+ {
+ g_pSplitList = ( (g_pParentWnd->ActiveXY()->GetViewType() == XZ) ? !g_bSwitch : g_bSwitch) ? &g_brBackSplits : &g_brFrontSplits;
+ }
+ }
+ Cam_Draw ();
+ QE_CheckOpenGLForErrors();
+ qwglSwapBuffers(dc.m_hDC);
+ }
+}
+
+
+void CCamWnd::SetXYFriend(CXYWnd * pWnd)
+{
+ m_pXYFriend = pWnd;
+}
+
+void CCamWnd::OnDestroy()
+{
+ QEW_StopGL(GetSafeHwnd(), g_qeglobals.d_hglrcBase, g_qeglobals.d_hdcBase );
+ CWnd::OnDestroy();
+}
+
+void CCamWnd::OnClose()
+{
+ CWnd::OnClose();
+}
+
+extern void Select_ShiftTexture(int x, int y);
+extern void Select_RotateTexture(int amt);
+extern void Select_ScaleTexture(int x, int y);
+void CCamWnd::OnMouseMove(UINT nFlags, CPoint point)
+{
+ CRect r;
+ GetClientRect(r);
+ if (GetCapture() == this && (GetKeyState(VK_MENU) & 0x8000) && !((GetKeyState(VK_SHIFT) & 0x8000) || (GetKeyState(VK_CONTROL) & 0x8000)))
+ {
+ if (GetKeyState(VK_CONTROL) & 0x8000)
+ Select_RotateTexture(point.y - m_ptLastCursor.y);
+ else
+ if (GetKeyState(VK_SHIFT) & 0x8000)
+ Select_ScaleTexture(point.x - m_ptLastCursor.x, m_ptLastCursor.y - point.y);
+ else
+ Select_ShiftTexture(point.x - m_ptLastCursor.x, m_ptLastCursor.y - point.y);
+ }
+ else
+ {
+ Cam_MouseMoved(point.x, r.bottom - 1 - point.y, nFlags);
+ }
+ m_ptLastCursor = point;
+}
+
+void CCamWnd::OnLButtonDown(UINT nFlags, CPoint point)
+{
+ m_ptLastCursor = point;
+ OriginalMouseDown(nFlags, point);
+}
+
+void CCamWnd::OnLButtonUp(UINT nFlags, CPoint point)
+{
+ OriginalMouseUp(nFlags, point);
+}
+
+void CCamWnd::OnMButtonDown(UINT nFlags, CPoint point)
+{
+ OriginalMouseDown(nFlags, point);
+}
+
+void CCamWnd::OnMButtonUp(UINT nFlags, CPoint point)
+{
+ OriginalMouseUp(nFlags, point);
+}
+
+void CCamWnd::OnRButtonDown(UINT nFlags, CPoint point)
+{
+ OriginalMouseDown(nFlags, point);
+}
+
+void CCamWnd::OnRButtonUp(UINT nFlags, CPoint point)
+{
+ OriginalMouseUp(nFlags, point);
+}
+
+int CCamWnd::OnCreate(LPCREATESTRUCT lpCreateStruct)
+{
+ if (CWnd::OnCreate(lpCreateStruct) == -1)
+ return -1;
+
+ g_qeglobals.d_hdcBase = GetDC()->m_hDC;
+ QEW_SetupPixelFormat(g_qeglobals.d_hdcBase, true);
+
+ if ((g_qeglobals.d_hglrcBase = qwglCreateContext(g_qeglobals.d_hdcBase)) == 0)
+ Error("wglCreateContext failed");
+
+ if (!qwglMakeCurrent(g_qeglobals.d_hdcBase, g_qeglobals.d_hglrcBase))
+ Error ("wglMakeCurrent failed");
+
+
+ //
+ // create GL font
+ //
+ HFONT hfont = ::CreateFont(
+ 12, // logical height of font
+ 6, // logical average character width
+ 0, // angle of escapement
+ 0, // base-line orientation angle
+ 0, // font weight
+ 0, // italic attribute flag
+ 0, // underline attribute flag
+ 0, // strikeout attribute flag
+ 0, // character set identifier
+ 0, // output precision
+ 0, // clipping precision
+ 0, // output quality
+ 0, // pitch and family
+ "system font" // pointer to typeface name string
+ );
+
+ if (!hfont)
+ Error( "couldn't create font" );
+
+ ::SelectObject(g_qeglobals.d_hdcBase, hfont);
+
+ if ((g_qeglobals.d_font_list = qglGenLists (256)) == 0)
+ Error( "couldn't create font dlists" );
+
+ // create the bitmap display lists
+ // we're making images of glyphs 0 thru 255
+
+ if (g_PrefsDlg.m_bBuggyICD)
+ {
+ if ( !qwglUseFontBitmaps (g_qeglobals.d_hdcBase, 1, 255, g_qeglobals.d_font_list-1) )
+ Error( "wglUseFontBitmaps faileD" );
+ }
+ else
+ {
+ if ( !qwglUseFontBitmaps (g_qeglobals.d_hdcBase, 1, 255, g_qeglobals.d_font_list) )
+ Error( "wglUseFontBitmaps faileD" );
+ }
+
+ // indicate start of glyph display lists
+ qglListBase (g_qeglobals.d_font_list);
+
+ // report OpenGL information
+ Sys_Printf ("GL_VENDOR: %s\n", qglGetString (GL_VENDOR));
+ Sys_Printf ("GL_RENDERER: %s\n", qglGetString (GL_RENDERER));
+ Sys_Printf ("GL_VERSION: %s\n", qglGetString (GL_VERSION));
+ Sys_Printf ("GL_EXTENSIONS: %s\n", qglGetString (GL_EXTENSIONS));
+
+ g_qeglobals.d_hwndCamera = GetSafeHwnd();
+
+ return 0;
+}
+
+void CCamWnd::OriginalMouseUp(UINT nFlags, CPoint point)
+{
+ CRect r;
+ GetClientRect(r);
+ Cam_MouseUp(point.x, r.bottom - 1 - point.y, nFlags);
+ if (!(nFlags & (MK_LBUTTON|MK_RBUTTON|MK_MBUTTON)))
+ ReleaseCapture ();
+}
+
+void CCamWnd::OriginalMouseDown(UINT nFlags, CPoint point)
+{
+ //if (GetTopWindow()->GetSafeHwnd() != GetSafeHwnd())
+ // BringWindowToTop();
+ CRect r;
+ GetClientRect(r);
+ SetFocus();
+ SetCapture();
+ //if (!(GetKeyState(VK_MENU) & 0x8000))
+ Cam_MouseDown (point.x, r.bottom - 1 - point.y, nFlags);
+}
+
+void CCamWnd::Cam_Init()
+{
+ //m_Camera.draw_mode = cd_texture;
+ m_Camera.timing = false;
+ m_Camera.origin[0] = 0;
+ m_Camera.origin[1] = 20;
+ m_Camera.origin[2] = 46;
+ m_Camera.color[0] = 0.3;
+ m_Camera.color[1] = 0.3;
+ m_Camera.color[2] = 0.3;
+}
+
+void CCamWnd::Cam_BuildMatrix()
+{
+ float xa, ya;
+ float matrix[4][4];
+ int i;
+
+ xa = m_Camera.angles[0]/180*Q_PI;
+ ya = m_Camera.angles[1]/180*Q_PI;
+
+ // the movement matrix is kept 2d
+
+ m_Camera.forward[0] = cos(ya);
+ m_Camera.forward[1] = sin(ya);
+ m_Camera.right[0] = m_Camera.forward[1];
+ m_Camera.right[1] = -m_Camera.forward[0];
+
+ qglGetFloatv (GL_PROJECTION_MATRIX, &matrix[0][0]);
+
+ for (i=0 ; i<3 ; i++)
+ {
+ m_Camera.vright[i] = matrix[i][0];
+ m_Camera.vup[i] = matrix[i][1];
+ m_Camera.vpn[i] = matrix[i][2];
+ }
+
+ VectorNormalize (m_Camera.vright);
+ VectorNormalize (m_Camera.vup);
+ VectorNormalize (m_Camera.vpn);
+}
+
+
+
+void CCamWnd::Cam_ChangeFloor (qboolean up)
+{
+ brush_t *b;
+ float d, bestd, current;
+ vec3_t start, dir;
+
+ start[0] = m_Camera.origin[0];
+ start[1] = m_Camera.origin[1];
+ start[2] = 8192;
+ dir[0] = dir[1] = 0;
+ dir[2] = -1;
+
+ current = 8192 - (m_Camera.origin[2] - 48);
+ if (up)
+ bestd = 0;
+ else
+ bestd = 16384;
+
+ for (b=active_brushes.next ; b != &active_brushes ; b=b->next)
+ {
+ if ( b->pTerrain && !Terrain_Ray( start, dir, b, &d ) )
+ continue;
+ if ( !b->pTerrain && !Brush_Ray (start, dir, b, &d) )
+ continue;
+ if (up && d < current && d > bestd)
+ bestd = d;
+ if (!up && d > current && d < bestd)
+ bestd = d;
+ }
+
+ if (bestd == 0 || bestd == 16384)
+ return;
+
+ m_Camera.origin[2] += current - bestd;
+ Sys_UpdateWindows (W_CAMERA|W_Z_OVERLAY);
+}
+
+
+void CCamWnd::Cam_PositionDrag()
+{
+ int x, y;
+ Sys_GetCursorPos (&x, &y);
+ if (x != m_ptCursor.x || y != m_ptCursor.y)
+ {
+ x -= m_ptCursor.x;
+ VectorMA (m_Camera.origin, x, m_Camera.vright, m_Camera.origin);
+ y -= m_ptCursor.y;
+ m_Camera.origin[2] -= y;
+ SetCursorPos(m_ptCursor.x, m_ptCursor.y);
+ Sys_UpdateWindows (W_CAMERA | W_XY_OVERLAY);
+ }
+}
+
+
+void CCamWnd::Cam_MouseControl (float dtime)
+{
+ int xl, xh;
+ int yl, yh;
+ float xf, yf;
+ if (g_PrefsDlg.m_nMouseButtons == 2)
+ {
+ if (m_nCambuttonstate != (MK_RBUTTON | MK_SHIFT))
+ return;
+ }
+ else
+ {
+ if (m_nCambuttonstate != MK_RBUTTON)
+ return;
+ }
+
+ xf = (float)(m_ptButton.x - m_Camera.width/2) / (m_Camera.width/2);
+ yf = (float)(m_ptButton.y - m_Camera.height/2) / (m_Camera.height/2);
+
+
+ xl = m_Camera.width/3;
+ xh = xl*2;
+ yl = m_Camera.height/3;
+ yh = yl*2;
+
+ //Sys_Printf("xf-%f yf-%f xl-%i xh-i% yl-i% yh-i%\n",xf,yf,xl,xh,yl,yh);
+#if 0
+ // strafe
+ if (buttony < yl && (buttonx < xl || buttonx > xh))
+ VectorMA (camera.origin, xf*dtime*g_nMoveSpeed, camera.right, camera.origin);
+ else
+#endif
+ {
+ xf *= 1.0 - fabs(yf);
+ if (xf < 0)
+ {
+ xf += 0.1;
+ if (xf > 0)
+ xf = 0;
+ }
+ else
+ {
+ xf -= 0.1;
+ if (xf < 0)
+ xf = 0;
+ }
+
+ VectorMA (m_Camera.origin, yf*dtime*g_nMoveSpeed, m_Camera.forward, m_Camera.origin);
+ m_Camera.angles[YAW] += xf*-dtime*g_nAngleSpeed;
+ }
+
+#if 0
+ if (g_PrefsDlg.m_bQE4Painting)
+ {
+ MSG msg;
+ if (::PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ))
+ {
+ TranslateMessage(&msg);
+ DispatchMessage(&msg);
+ }
+ }
+#endif
+
+ int nUpdate = (g_PrefsDlg.m_bCamXYUpdate) ? (W_CAMERA | W_XY) : (W_CAMERA);
+ Sys_UpdateWindows (nUpdate);
+ g_pParentWnd->PostMessage(WM_TIMER, 0, 0);
+
+}
+
+
+
+void CCamWnd::Cam_MouseDown(int x, int y, int buttons)
+{
+ vec3_t dir;
+ float f, r, u;
+ int i;
+
+ //
+ // calc ray direction
+ //
+ u = (float)(y - m_Camera.height/2) / (m_Camera.width/2);
+ r = (float)(x - m_Camera.width/2) / (m_Camera.width/2);
+ f = 1;
+
+ for (i=0 ; i<3 ; i++)
+ dir[i] = m_Camera.vpn[i] * f + m_Camera.vright[i] * r + m_Camera.vup[i] * u;
+ VectorNormalize (dir);
+
+ GetCursorPos(&m_ptCursor);
+
+ m_nCambuttonstate = buttons;
+ m_ptButton.x = x;
+ m_ptButton.y = y;
+
+ // LBUTTON = manipulate selection
+ // shift-LBUTTON = select
+ // middle button = grab texture
+ // ctrl-middle button = set entire brush to texture
+ // ctrl-shift-middle button = set single face to texture
+ int nMouseButton = g_PrefsDlg.m_nMouseButtons == 2 ? MK_RBUTTON : MK_MBUTTON;
+ if ((buttons == MK_LBUTTON)
+ || (buttons == (MK_LBUTTON | MK_SHIFT))
+ || (buttons == (MK_LBUTTON | MK_CONTROL))
+ || (buttons == (MK_LBUTTON | MK_CONTROL | MK_SHIFT))
+ || (buttons == nMouseButton)
+ || (buttons == (nMouseButton|MK_SHIFT))
+ || (buttons == (nMouseButton|MK_CONTROL))
+ || (buttons == (nMouseButton|MK_SHIFT|MK_CONTROL)))
+ {
+
+ if (g_PrefsDlg.m_nMouseButtons == 2 && (buttons == (MK_RBUTTON | MK_SHIFT)))
+ Cam_MouseControl (0.1);
+ else
+ {
+ // something global needs to track which window is responsible for stuff
+ Patch_SetView(W_CAMERA);
+ Drag_Begin (x, y, buttons, m_Camera.vright, m_Camera.vup, m_Camera.origin, dir);
+ }
+ return;
+ }
+
+ if (buttons == MK_RBUTTON)
+ {
+ Cam_MouseControl (0.1);
+ return;
+ }
+}
+
+
+void CCamWnd::Cam_MouseUp (int x, int y, int buttons)
+{
+ m_nCambuttonstate = 0;
+ Drag_MouseUp (buttons);
+}
+
+
+void CCamWnd::Cam_MouseMoved (int x, int y, int buttons)
+{
+ m_nCambuttonstate = buttons;
+ if (!buttons) {
+ if ( ( g_qeglobals.d_select_mode == sel_terrainpoint ) || ( g_qeglobals.d_select_mode == sel_terraintexture ) ) {
+ vec3_t dir;
+ float f, r, u;
+ int i;
+
+ //
+ // calc ray direction
+ //
+ u = (float)(y - m_Camera.height/2) / (m_Camera.width/2);
+ r = (float)(x - m_Camera.width/2) / (m_Camera.width/2);
+ f = 1;
+
+ for (i=0 ; i<3 ; i++)
+ dir[i] = m_Camera.vpn[i] * f + m_Camera.vright[i] * r + m_Camera.vup[i] * u;
+ VectorNormalize (dir);
+
+ m_ptButton.x = x;
+ m_ptButton.y = y;
+
+ Terrain_SelectPointByRay( m_Camera.origin, dir, buttons );
+
+ Sys_UpdateWindows(W_CAMERA);
+ }
+
+ return;
+ }
+ m_ptButton.x = x;
+ m_ptButton.y = y;
+
+ if (buttons == (MK_RBUTTON|MK_CONTROL) )
+ {
+ Cam_PositionDrag ();
+ Sys_UpdateWindows (W_XY|W_CAMERA|W_Z);
+ return;
+ }
+
+ GetCursorPos(&m_ptCursor);
+
+ if (buttons & (MK_LBUTTON | MK_MBUTTON) )
+ {
+ Drag_MouseMoved (x, y, buttons);
+ Sys_UpdateWindows (W_XY|W_CAMERA|W_Z);
+ }
+}
+
+
+void CCamWnd::InitCull()
+{
+ int i;
+
+ VectorSubtract (m_Camera.vpn, m_Camera.vright, m_vCull1);
+ VectorAdd (m_Camera.vpn, m_Camera.vright, m_vCull2);
+
+ for (i=0 ; i<3 ; i++)
+ {
+ if (m_vCull1[i] > 0)
+ m_nCullv1[i] = 3+i;
+ else
+ m_nCullv1[i] = i;
+ if (m_vCull2[i] > 0)
+ m_nCullv2[i] = 3+i;
+ else
+ m_nCullv2[i] = i;
+ }
+}
+
+qboolean CCamWnd::CullBrush (brush_t *b)
+{
+ int i;
+ vec3_t point;
+ float d;
+
+ if (g_PrefsDlg.m_bCubicClipping)
+ {
+ float fLevel = g_PrefsDlg.m_nCubicScale * 64;
+
+ point[0] = m_Camera.origin[0] - fLevel;
+ point[1] = m_Camera.origin[1] - fLevel;
+ point[2] = m_Camera.origin[2] - fLevel;
+
+ for (i=0; i<3; i++)
+ if (b->mins[i] < point[i] && b->maxs[i] < point[i])
+ return true;
+
+ point[0] = m_Camera.origin[0] + fLevel;
+ point[1] = m_Camera.origin[1] + fLevel;
+ point[2] = m_Camera.origin[2] + fLevel;
+
+ for (i=0; i<3; i++)
+ if (b->mins[i] > point[i] && b->maxs[i] > point[i])
+ return true;
+ }
+
+
+ for (i=0 ; i<3 ; i++)
+ point[i] = b->mins[m_nCullv1[i]] - m_Camera.origin[i];
+
+ d = DotProduct (point, m_vCull1);
+ if (d < -1)
+ return true;
+
+ for (i=0 ; i<3 ; i++)
+ point[i] = b->mins[m_nCullv2[i]] - m_Camera.origin[i];
+
+ d = DotProduct (point, m_vCull2);
+ if (d < -1)
+ return true;
+
+ return false;
+}
+
+#if 0
+void CCamWnd::DrawLightRadius(brush_t* pBrush)
+{
+ // if lighting
+ int nRadius = Brush_LightRadius(pBrush);
+ if (nRadius > 0)
+ {
+ Brush_SetLightColor(pBrush);
+ qglEnable (GL_BLEND);
+ qglPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
+ qglBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ qglDisable (GL_TEXTURE_2D);
+
+ qglEnable(GL_TEXTURE_2D);
+ qglDisable(GL_BLEND);
+ qglPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
+ }
+}
+#endif
+
+/*
+==============
+Cam_Draw
+==============
+*/
+
+void CCamWnd::Cam_Draw()
+{
+ brush_t *brush;
+ face_t *face;
+ float screenaspect;
+ float yfov;
+ double start, end;
+ int i;
+
+ /*
+ FILE *f = fopen("g:/nardo/raduffy/editorhack.dat", "w");
+ if (f != NULL) {
+ fwrite(&m_Camera.origin[0], sizeof(float), 1, f);
+ fwrite(&m_Camera.origin[1], sizeof(float), 1, f);
+ fwrite(&m_Camera.origin[2], sizeof(float), 1, f);
+ fwrite(&m_Camera.angles[PITCH], sizeof(float), 1, f);
+ fwrite(&m_Camera.angles[YAW], sizeof(float), 1, f);
+ fclose(f);
+ }
+ */
+
+ if (!active_brushes.next)
+ return; // not valid yet
+
+ if (m_Camera.timing)
+ start = Sys_DoubleTime ();
+
+ //
+ // clear
+ //
+ QE_CheckOpenGLForErrors();
+
+ qglViewport(0, 0, m_Camera.width, m_Camera.height);
+ qglScissor(0, 0, m_Camera.width, m_Camera.height);
+ qglClearColor (g_qeglobals.d_savedinfo.colors[COLOR_CAMERABACK][0],
+ g_qeglobals.d_savedinfo.colors[COLOR_CAMERABACK][1],
+ g_qeglobals.d_savedinfo.colors[COLOR_CAMERABACK][2], 0);
+ qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+
+ //
+ // set up viewpoint
+ //
+ vec5_t lightPos;
+
+ if (g_PrefsDlg.m_bGLLighting)
+ {
+ qglEnable(GL_LIGHTING);
+ //qglEnable(GL_LIGHT0);
+
+ lightPos[0] = lightPos[1] = lightPos[2] = 3.5;
+ lightPos[3] = 1.0;
+ qglLightModelfv(GL_LIGHT_MODEL_AMBIENT, lightPos);
+ //qglLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
+ //lightPos[0] = lightPos[1] = lightPos[2] = 3.5;
+ //qglLightfv(GL_LIGHT0, GL_AMBIENT, lightPos);
+ }
+ else
+ {
+ qglDisable(GL_LIGHTING);
+ }
+
+ qglMatrixMode(GL_PROJECTION);
+ qglLoadIdentity ();
+
+ screenaspect = (float)m_Camera.width / m_Camera.height;
+ yfov = 2*atan((float)m_Camera.height / m_Camera.width)*180/Q_PI;
+ qgluPerspective (yfov, screenaspect, 2, 8192);
+
+ qglRotatef (-90, 1, 0, 0); // put Z going up
+ qglRotatef (90, 0, 0, 1); // put Z going up
+ qglRotatef (m_Camera.angles[0], 0, 1, 0);
+ qglRotatef (-m_Camera.angles[1], 0, 0, 1);
+ qglTranslatef (-m_Camera.origin[0], -m_Camera.origin[1], -m_Camera.origin[2]);
+
+ Cam_BuildMatrix ();
+
+
+ //if (m_Camera.draw_mode == cd_light)
+ //{
+// if (g_PrefsDlg.m_bGLLighting)
+// {
+// VectorCopy(m_Camera.origin, lightPos);
+// lightPos[3] = 1;
+// qglLightfv(GL_LIGHT0, GL_POSITION, lightPos);
+// }
+ //}
+
+ InitCull ();
+
+ //
+ // draw stuff
+ //
+ GLfloat lAmbient[] = {1.0, 1.0, 1.0, 1.0};
+
+ switch (m_Camera.draw_mode)
+ {
+ case cd_wire:
+ qglPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
+ qglDisable(GL_TEXTURE_2D);
+ qglDisable(GL_TEXTURE_1D);
+ qglDisable(GL_BLEND);
+ qglDisable(GL_DEPTH_TEST);
+ qglColor3f(1.0, 1.0, 1.0);
+ // qglEnable (GL_LINE_SMOOTH);
+ break;
+
+ case cd_solid:
+ qglCullFace(GL_FRONT);
+ qglEnable(GL_CULL_FACE);
+ qglShadeModel (GL_FLAT);
+ qglPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
+ qglDisable(GL_TEXTURE_2D);
+ qglDisable(GL_BLEND);
+ qglEnable(GL_DEPTH_TEST);
+ qglDepthFunc (GL_LEQUAL);
+ break;
+
+ case cd_texture:
+ qglCullFace(GL_FRONT);
+ qglEnable(GL_CULL_FACE);
+ qglShadeModel (GL_FLAT);
+ qglPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
+ qglEnable(GL_TEXTURE_2D);
+ qglTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
+ qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+ qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
+ qglDisable(GL_BLEND);
+ qglEnable(GL_DEPTH_TEST);
+ qglDepthFunc (GL_LEQUAL);
+ break;
+
+ case cd_blend:
+ qglCullFace(GL_FRONT);
+ qglEnable(GL_CULL_FACE);
+ qglShadeModel (GL_FLAT);
+ qglPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
+ qglEnable(GL_TEXTURE_2D);
+ qglTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
+ qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+ qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
+ qglDisable(GL_DEPTH_TEST);
+ qglEnable (GL_BLEND);
+ qglBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ break;
+ }
+
+ qglMatrixMode(GL_TEXTURE);
+
+ m_nNumTransBrushes = 0;
+
+ for (brush = active_brushes.next ; brush != &active_brushes ; brush=brush->next)
+ {
+ //DrawLightRadius(brush);
+
+ if (CullBrush (brush))
+ continue;
+
+ if (FilterBrush (brush))
+ continue;
+
+ if ((brush->brush_faces->texdef.flags & (SURF_TRANS33 | SURF_TRANS66)) || (brush->brush_faces->d_texture->bFromShader && brush->brush_faces->d_texture->fTrans != 1.0))
+ {
+ m_TransBrushes [ m_nNumTransBrushes++ ] = brush;
+ }
+ else
+ {
+ //-- if (brush->patchBrush)
+ //-- m_TransBrushes [ m_nNumTransBrushes++ ] = brush;
+ //-- else
+ Brush_Draw(brush);
+ }
+
+
+ }
+
+ if (g_PrefsDlg.m_bGLLighting)
+ {
+ qglDisable (GL_LIGHTING);
+ }
+
+ //
+ //qglDepthMask ( 0 ); // Don't write to depth buffer
+ qglEnable ( GL_BLEND );
+ qglBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ for ( i = 0; i < m_nNumTransBrushes; i++ )
+ Brush_Draw (m_TransBrushes[i]);
+
+ //qglDepthMask ( 1 ); // Ok, write now
+
+ qglMatrixMode(GL_PROJECTION);
+
+ //
+ // now draw selected brushes
+ //
+
+ if (g_PrefsDlg.m_bGLLighting)
+ {
+ qglEnable (GL_LIGHTING);
+ }
+
+ qglTranslatef (g_qeglobals.d_select_translate[0], g_qeglobals.d_select_translate[1], g_qeglobals.d_select_translate[2]);
+ qglMatrixMode(GL_TEXTURE);
+
+ brush_t* pList = (g_bClipMode && g_pSplitList) ? g_pSplitList : &selected_brushes;
+ // draw normally
+ for (brush = pList->next ; brush != pList ; brush=brush->next)
+ {
+ //DrawLightRadius(brush);
+ //if (brush->patchBrush && g_qeglobals.d_select_mode == sel_curvepoint)
+ // continue;
+
+ Brush_Draw(brush);
+ }
+
+ // blend on top
+ qglMatrixMode(GL_PROJECTION);
+
+
+ qglDisable (GL_LIGHTING);
+ qglColor4f(1.0, 0.0, 0.0, 0.3);
+ qglEnable (GL_BLEND);
+ qglPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
+ qglBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ qglDisable (GL_TEXTURE_2D);
+ for (brush = pList->next ; brush != pList ; brush=brush->next)
+ {
+ if ( (brush->patchBrush && g_qeglobals.d_select_mode == sel_curvepoint) ||
+ (brush->terrainBrush && g_qeglobals.d_select_mode == sel_terrainpoint) )
+ continue;
+
+ for (face=brush->brush_faces ; face ; face=face->next)
+ Face_Draw( face );
+ }
+
+
+ int nCount = g_ptrSelectedFaces.GetSize();
+ if (nCount > 0)
+ {
+ for (int i = 0; i < nCount; i++)
+ {
+ face_t *selFace = reinterpret_cast<face_t*>(g_ptrSelectedFaces.GetAt(i));
+ Face_Draw(selFace);
+ }
+ }
+
+ // non-zbuffered outline
+
+ qglDisable (GL_BLEND);
+ qglDisable (GL_DEPTH_TEST);
+ qglPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
+ qglColor3f (1, 1, 1);
+ for (brush = pList->next ; brush != pList ; brush=brush->next)
+ {
+ if (g_qeglobals.dontDrawSelectedOutlines || (brush->patchBrush && g_qeglobals.d_select_mode == sel_curvepoint) ||
+ (brush->terrainBrush && g_qeglobals.d_select_mode == sel_terrainpoint))
+ continue;
+
+ for (face=brush->brush_faces ; face ; face=face->next)
+ Face_Draw( face );
+ }
+
+
+ // edge / vertex flags
+
+ if (g_qeglobals.d_select_mode == sel_vertex)
+ {
+ qglPointSize (4);
+ qglColor3f (0,1,0);
+ qglBegin (GL_POINTS);
+ for (i=0 ; i<g_qeglobals.d_numpoints ; i++)
+ qglVertex3fv (g_qeglobals.d_points[i]);
+ qglEnd ();
+ qglPointSize (1);
+ }
+ else if (g_qeglobals.d_select_mode == sel_edge)
+ {
+ float *v1, *v2;
+
+ qglPointSize (4);
+ qglColor3f (0,0,1);
+ qglBegin (GL_POINTS);
+ for (i=0 ; i<g_qeglobals.d_numedges ; i++)
+ {
+ v1 = g_qeglobals.d_points[g_qeglobals.d_edges[i].p1];
+ v2 = g_qeglobals.d_points[g_qeglobals.d_edges[i].p2];
+ qglVertex3f ( (v1[0]+v2[0])*0.5,(v1[1]+v2[1])*0.5,(v1[2]+v2[2])*0.5);
+ }
+ qglEnd ();
+ qglPointSize (1);
+ }
+
+
+ g_splineList->draw(static_cast<qboolean>(g_qeglobals.d_select_mode == sel_addpoint || g_qeglobals.d_select_mode == sel_editpoint));
+ if (g_qeglobals.selectObject && (g_qeglobals.d_select_mode == sel_addpoint || g_qeglobals.d_select_mode == sel_editpoint)) {
+ g_qeglobals.selectObject->drawSelection();
+ }
+
+ //
+ // draw pointfile
+ //
+
+ qglEnable(GL_DEPTH_TEST);
+
+
+ DrawPathLines ();
+
+
+
+ if (g_qeglobals.d_pointfile_display_list)
+ {
+ Pointfile_Draw();
+ // glCallList (g_qeglobals.d_pointfile_display_list);
+ }
+
+ // bind back to the default texture so that we don't have problems
+ // elsewhere using/modifying texture maps between contexts
+ qglBindTexture( GL_TEXTURE_2D, 0 );
+
+#if 0
+ // area selection hack
+ if (g_qeglobals.d_select_mode == sel_area)
+ {
+ qglEnable (GL_BLEND);
+ qglBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ qglColor4f(0.0, 0.0, 1.0, 0.25);
+ qglPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
+ qglRectfv(g_qeglobals.d_vAreaTL, g_qeglobals.d_vAreaBR);
+ qglDisable (GL_BLEND);
+ }
+#endif
+
+ qglFinish();
+ QE_CheckOpenGLForErrors();
+ // Sys_EndWait();
+ if (m_Camera.timing)
+ {
+ end = Sys_DoubleTime ();
+ Sys_Printf ("Camera: %i ms\n", (int)(1000*(end-start)));
+ }
+}
+
+
+void CCamWnd::OnSize(UINT nType, int cx, int cy)
+{
+ CWnd::OnSize(nType, cx, cy);
+ CRect rect;
+ GetClientRect(rect);
+ m_Camera.width = rect.right;
+ m_Camera.height = rect.bottom;
+ InvalidateRect(NULL, false);
+}
+
+void CCamWnd::BenchMark()
+{
+ PAINTSTRUCT ps;
+ CRect rct;
+ GetWindowRect(rct);
+ long lStyle = ::GetWindowLong(GetSafeHwnd(), GWL_STYLE);
+ ::SetWindowLong(GetSafeHwnd(), GWL_STYLE, QE3_CHILDSTYLE);
+ CWnd* pParent = GetParent();
+ SetParent(g_pParentWnd);
+ MoveWindow(CRect(30, 30, 400, 400), TRUE);
+
+ BeginPaint(&ps);
+ if (!qwglMakeCurrent(ps.hdc, g_qeglobals.d_hglrcBase))
+ Error ("wglMakeCurrent failed in Benchmark");
+
+ qglDrawBuffer (GL_FRONT);
+ double dStart = Sys_DoubleTime ();
+ for (int i=0 ; i < 100 ; i++)
+ {
+ m_Camera.angles[YAW] = i*4;
+ Cam_Draw();
+ }
+ qwglSwapBuffers(ps.hdc);
+ qglDrawBuffer (GL_BACK);
+ double dEnd = Sys_DoubleTime ();
+ EndPaint(&ps);
+ Sys_Printf ("%5.2f seconds\n", dEnd - dStart);
+ ::SetWindowLong(GetSafeHwnd(), GWL_STYLE, lStyle);
+ SetParent(pParent);
+ MoveWindow(rct, TRUE);
+}
+
+void CCamWnd::ReInitGL()
+{
+
+ qwglMakeCurrent(0,0);
+ QEW_SetupPixelFormat(GetDC()->m_hDC, true);
+ if (!qwglMakeCurrent(g_qeglobals.d_hdcBase, g_qeglobals.d_hglrcBase))
+ Error ("wglMakeCurrent failed");
+
+ return;
+
+ long lStyle = ::GetWindowLong(GetSafeHwnd(), GWL_STYLE);
+ int nID = ::GetWindowLong(GetSafeHwnd(), GWL_ID);
+ CWnd* pParent = GetParent();
+ CRect rctClient;
+ GetClientRect(rctClient);
+ DestroyWindow();
+ Create(CAMERA_WINDOW_CLASS, "", lStyle, rctClient, pParent, nID);
+}
+
+void CCamWnd::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags)
+{
+ g_pParentWnd->HandleKey(nChar, nRepCnt, nFlags, false);
+}
+
+// Timo
+// brush primitive texture shifting, using camera view to select translations :
+void CCamWnd::ShiftTexture_BrushPrimit(face_t *f, int x, int y)
+{
+ vec3_t texS,texT;
+ vec3_t viewX,viewY;
+ int XS,XT,YS,YT;
+ int outS,outT;
+#ifdef _DEBUG
+ if (!g_qeglobals.m_bBrushPrimitMode)
+ {
+ Sys_Printf("Warning : unexpected call to CCamWnd::ShiftTexture_BrushPrimit with brush primitive mode disbaled\n");
+ return;
+ }
+#endif
+ // compute face axis base
+ ComputeAxisBase( f->plane.normal, texS, texT );
+ // compute camera view vectors
+ VectorCopy( m_Camera.vup, viewY );
+ VectorCopy( m_Camera.vright, viewX );
+ // compute best vectors
+ ComputeBest2DVector( viewX, texS, texT, XS, XT );
+ ComputeBest2DVector( viewY, texS, texT, YS, YT );
+ // check this is not a degenerate case
+ if ( ( XS == YS ) && ( XT == YT ) )
+ {
+#ifdef _DEBUG
+ Sys_Printf("Warning : degenerate best vectors axis base in CCamWnd::ShiftTexture_BrushPrimit\n");
+#endif
+ // forget it
+ Select_ShiftTexture_BrushPrimit( f, x, y );
+ return;
+ }
+ // compute best fitted translation in face axis base
+ outS = XS*x + YS*y;
+ outT = XT*x + YT*y;
+ // call actual texture shifting code
+ Select_ShiftTexture_BrushPrimit( f, outS, outT );
+}
diff --git a/q3radiant/CamWnd.h b/q3radiant/CamWnd.h
new file mode 100755
index 0000000..8f0a283
--- /dev/null
+++ b/q3radiant/CamWnd.h
@@ -0,0 +1,120 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_CAMWND_H__44B4BA03_781B_11D1_B53C_00AA00A410FC__INCLUDED_)
+#define AFX_CAMWND_H__44B4BA03_781B_11D1_B53C_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// CamWnd.h : header file
+//
+/////////////////////////////////////////////////////////////////////////////
+// CCamWnd window
+class CXYWnd;
+
+class CCamWnd : public CWnd
+{
+ DECLARE_DYNCREATE(CCamWnd);
+// Construction
+public:
+ CCamWnd();
+
+// Attributes
+public:
+
+// Operations
+public:
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CCamWnd)
+ protected:
+ virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
+ //}}AFX_VIRTUAL
+
+// Implementation
+public:
+ void ShiftTexture_BrushPrimit(face_t *f, int x, int y);
+ void ReInitGL();
+ void BenchMark();
+ CXYWnd* m_pXYFriend;
+ void SetXYFriend(CXYWnd* pWnd);
+ virtual ~CCamWnd();
+ camera_t& Camera(){return m_Camera;};
+ void Cam_MouseControl(float dtime);
+ void Cam_ChangeFloor(qboolean up);
+
+protected:
+ void Cam_Init();
+ void Cam_BuildMatrix();
+ void Cam_PositionDrag();
+ void Cam_MouseDown(int x, int y, int buttons);
+ void Cam_MouseUp (int x, int y, int buttons);
+ void Cam_MouseMoved (int x, int y, int buttons);
+ void InitCull();
+ qboolean CullBrush (brush_t *b);
+ void Cam_Draw();
+
+
+ brush_t* m_TransBrushes[MAX_MAP_BRUSHES];
+ int m_nNumTransBrushes;
+ camera_t m_Camera;
+ int m_nCambuttonstate;
+ CPoint m_ptButton;
+ CPoint m_ptCursor;
+ CPoint m_ptLastCursor;
+ face_t* m_pSide_select;
+ vec3_t m_vCull1;
+ vec3_t m_vCull2;
+ int m_nCullv1[3];
+ int m_nCullv2[3];
+ bool m_bClipMode;
+
+ // Generated message map functions
+protected:
+ void OriginalMouseDown(UINT nFlags, CPoint point);
+ void OriginalMouseUp(UINT nFlags, CPoint point);
+ //{{AFX_MSG(CCamWnd)
+ afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
+ afx_msg void OnPaint();
+ afx_msg void OnDestroy();
+ afx_msg void OnClose();
+ afx_msg void OnMouseMove(UINT nFlags, CPoint point);
+ afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
+ afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
+ afx_msg void OnMButtonDown(UINT nFlags, CPoint point);
+ afx_msg void OnMButtonUp(UINT nFlags, CPoint point);
+ afx_msg void OnRButtonDown(UINT nFlags, CPoint point);
+ afx_msg void OnRButtonUp(UINT nFlags, CPoint point);
+ afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
+ afx_msg void OnSize(UINT nType, int cx, int cy);
+ afx_msg void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags);
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+/////////////////////////////////////////////////////////////////////////////
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_CAMWND_H__44B4BA03_781B_11D1_B53C_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/CapDialog.cpp b/q3radiant/CapDialog.cpp
new file mode 100755
index 0000000..c4194c7
--- /dev/null
+++ b/q3radiant/CapDialog.cpp
@@ -0,0 +1,64 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// CapDialog.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "CapDialog.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CCapDialog dialog
+
+
+CCapDialog::CCapDialog(CWnd* pParent /*=NULL*/)
+ : CDialog(CCapDialog::IDD, pParent)
+{
+ //{{AFX_DATA_INIT(CCapDialog)
+ m_nCap = 0;
+ //}}AFX_DATA_INIT
+}
+
+
+void CCapDialog::DoDataExchange(CDataExchange* pDX)
+{
+ CDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CCapDialog)
+ DDX_Radio(pDX, IDC_RADIO_CAP, m_nCap);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CCapDialog, CDialog)
+ //{{AFX_MSG_MAP(CCapDialog)
+ // NOTE: the ClassWizard will add message map macros here
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CCapDialog message handlers
diff --git a/q3radiant/CapDialog.h b/q3radiant/CapDialog.h
new file mode 100755
index 0000000..df81dcb
--- /dev/null
+++ b/q3radiant/CapDialog.h
@@ -0,0 +1,69 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_CAPDIALOG_H__10637162_2BD2_11D2_B030_00AA00A410FC__INCLUDED_)
+#define AFX_CAPDIALOG_H__10637162_2BD2_11D2_B030_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// CapDialog.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CCapDialog dialog
+
+class CCapDialog : public CDialog
+{
+// Construction
+public:
+ static enum {BEVEL = 0, ENDCAP, IBEVEL, IENDCAP};
+ CCapDialog(CWnd* pParent = NULL); // standard constructor
+
+ int getCapType() {return m_nCap;};
+// Dialog Data
+ //{{AFX_DATA(CCapDialog)
+ enum { IDD = IDD_DIALOG_CAP };
+ int m_nCap;
+ //}}AFX_DATA
+
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CCapDialog)
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+
+ // Generated message map functions
+ //{{AFX_MSG(CCapDialog)
+ // NOTE: the ClassWizard will add member functions here
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_CAPDIALOG_H__10637162_2BD2_11D2_B030_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/CharBuffer.h b/q3radiant/CharBuffer.h
new file mode 100755
index 0000000..ab86627
--- /dev/null
+++ b/q3radiant/CharBuffer.h
@@ -0,0 +1,109 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __CHARBUFFER_HPP
+#define __CHARBUFFER_HPP
+
+class CCharBuffer
+{
+ char* m_pCharBuffer;
+ unsigned m_uSize;
+
+ public:
+ CCharBuffer();
+
+ CCharBuffer(unsigned uSize);
+
+ CCharBuffer(const char* pString);
+
+ CCharBuffer(const CCharBuffer& rhs);
+
+ ~CCharBuffer();
+
+ char* Allocate(uint uSize);
+
+ void DeAllocate();
+
+ size_t StringLength()
+ { return strlen(m_pCharBuffer); }
+
+ void StripTrailing(char c, int nLen);
+
+ char& operator *()
+ { return *m_pCharBuffer; }
+
+ char& operator *() const
+ { return *const_cast<CCharBuffer*>(this)->m_pCharBuffer; }
+
+ operator void*()
+ { return m_pCharBuffer; }
+
+ operator char*()
+ { return m_pCharBuffer; }
+
+ operator const char*()
+ { return reinterpret_cast<const char*>(m_pCharBuffer); }
+
+ operator unsigned char*()
+ { return reinterpret_cast<unsigned char*>(m_pCharBuffer); }
+
+ operator const unsigned char*()
+ { return reinterpret_cast<const unsigned char*>(m_pCharBuffer); }
+
+ unsigned SizeOf()
+ { return m_uSize; }
+
+ CCharBuffer& operator =(const CCharBuffer& rhs);
+
+ CCharBuffer& operator =(const char* pString);
+
+ bool operator ==(const CCharBuffer& rhs) const
+ { return strcmp(m_pCharBuffer, rhs.m_pCharBuffer) == 0; }
+
+ bool operator ==(char* pString) const
+ { return strcmp(m_pCharBuffer, pString) == 0; }
+
+ bool operator ==(const char* pString) const
+ { return strcmp(m_pCharBuffer, pString) == 0; }
+
+ bool operator !=(CCharBuffer& rhs) const
+ { return strcmp(m_pCharBuffer, rhs.m_pCharBuffer) != 0; }
+
+ bool operator !=(char* pString) const
+ { return strcmp(m_pCharBuffer, pString) != 0; }
+
+ bool operator !=(const char* pString) const
+ { return strcmp(m_pCharBuffer, pString) != 0; }
+
+ char& operator [](int nIndex)
+ { return m_pCharBuffer[nIndex]; }
+
+ char& operator [](int nIndex) const
+ { return m_pCharBuffer[nIndex]; }
+
+ char* Fill(char FillChar)
+ { memset(m_pCharBuffer, FillChar, m_uSize-1); return m_pCharBuffer; }
+};
+//
+//-----------------------------------------------------------------------------
+#endif // __CCHARBUFFER_HPP
+//-----------------------------------------------------------------------------
+//
diff --git a/q3radiant/ChildFrm.cpp b/q3radiant/ChildFrm.cpp
new file mode 100755
index 0000000..b2e477f
--- /dev/null
+++ b/q3radiant/ChildFrm.cpp
@@ -0,0 +1,86 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// ChildFrm.cpp : implementation of the CChildFrame class
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+
+#include "ChildFrm.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CChildFrame
+
+IMPLEMENT_DYNCREATE(CChildFrame, CMDIChildWnd)
+
+BEGIN_MESSAGE_MAP(CChildFrame, CMDIChildWnd)
+ //{{AFX_MSG_MAP(CChildFrame)
+ // NOTE - the ClassWizard will add and remove mapping macros here.
+ // DO NOT EDIT what you see in these blocks of generated code !
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CChildFrame construction/destruction
+
+CChildFrame::CChildFrame()
+{
+ // TODO: add member initialization code here
+
+}
+
+CChildFrame::~CChildFrame()
+{
+}
+
+BOOL CChildFrame::PreCreateWindow(CREATESTRUCT& cs)
+{
+ // TODO: Modify the Window class or styles here by modifying
+ // the CREATESTRUCT cs
+
+ return CMDIChildWnd::PreCreateWindow(cs);
+}
+
+/////////////////////////////////////////////////////////////////////////////
+// CChildFrame diagnostics
+
+#ifdef _DEBUG
+void CChildFrame::AssertValid() const
+{
+ CMDIChildWnd::AssertValid();
+}
+
+void CChildFrame::Dump(CDumpContext& dc) const
+{
+ CMDIChildWnd::Dump(dc);
+}
+
+#endif //_DEBUG
+
+/////////////////////////////////////////////////////////////////////////////
+// CChildFrame message handlers
diff --git a/q3radiant/ChildFrm.h b/q3radiant/ChildFrm.h
new file mode 100755
index 0000000..1de2584
--- /dev/null
+++ b/q3radiant/ChildFrm.h
@@ -0,0 +1,73 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// ChildFrm.h : interface of the CChildFrame class
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#if !defined(AFX_CHILDFRM_H__330BBF0C_731C_11D1_B539_00AA00A410FC__INCLUDED_)
+#define AFX_CHILDFRM_H__330BBF0C_731C_11D1_B539_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+
+class CChildFrame : public CMDIChildWnd
+{
+ DECLARE_DYNCREATE(CChildFrame)
+public:
+ CChildFrame();
+
+// Attributes
+public:
+
+// Operations
+public:
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CChildFrame)
+ virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
+ //}}AFX_VIRTUAL
+
+// Implementation
+public:
+ virtual ~CChildFrame();
+#ifdef _DEBUG
+ virtual void AssertValid() const;
+ virtual void Dump(CDumpContext& dc) const;
+#endif
+
+// Generated message map functions
+protected:
+ //{{AFX_MSG(CChildFrame)
+ // NOTE - the ClassWizard will add and remove member functions here.
+ // DO NOT EDIT what you see in these blocks of generated code!
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+/////////////////////////////////////////////////////////////////////////////
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_CHILDFRM_H__330BBF0C_731C_11D1_B539_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/CommandsDlg.cpp b/q3radiant/CommandsDlg.cpp
new file mode 100755
index 0000000..761ea43
--- /dev/null
+++ b/q3radiant/CommandsDlg.cpp
@@ -0,0 +1,109 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// CommandsDlg.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "CommandsDlg.h"
+#include "MainFrm.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CCommandsDlg dialog
+
+
+CCommandsDlg::CCommandsDlg(CWnd* pParent /*=NULL*/)
+ : CDialog(CCommandsDlg::IDD, pParent)
+{
+ //{{AFX_DATA_INIT(CCommandsDlg)
+ // NOTE: the ClassWizard will add member initialization here
+ //}}AFX_DATA_INIT
+}
+
+
+void CCommandsDlg::DoDataExchange(CDataExchange* pDX)
+{
+ CDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CCommandsDlg)
+ DDX_Control(pDX, IDC_LIST_COMMANDS, m_lstCommands);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CCommandsDlg, CDialog)
+ //{{AFX_MSG_MAP(CCommandsDlg)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CCommandsDlg message handlers
+
+BOOL CCommandsDlg::OnInitDialog()
+{
+ CDialog::OnInitDialog();
+ m_lstCommands.SetTabStops(96);
+ int nCount = g_nCommandCount;
+
+ CFile fileout;
+ fileout.Open("c:/commandlist.txt", CFile::modeCreate | CFile::modeWrite);
+ for (int n = 0; n < nCount; n++)
+ {
+ CString strLine;
+ char c = g_Commands[n].m_nKey;
+ CString strKeys = c;
+ for (int k = 0; k < g_nKeyCount; k++)
+ {
+ if (g_Keys[k].m_nVKKey == g_Commands[n].m_nKey)
+ {
+ strKeys = g_Keys[k].m_strName;
+ break;
+ }
+ }
+ CString strMod("");
+ if (g_Commands[n].m_nModifiers & RAD_SHIFT)
+ strMod = "Shift";
+ if (g_Commands[n].m_nModifiers & RAD_ALT)
+ strMod += (strMod.GetLength() > 0) ? " + Alt" : "Alt";
+ if (g_Commands[n].m_nModifiers & RAD_CONTROL)
+ strMod += (strMod.GetLength() > 0) ? " + Control" : "Control";
+ if (strMod.GetLength() > 0)
+ {
+ strMod += " + ";
+ }
+ strLine.Format("%s \t%s%s", g_Commands[n].m_strCommand, strMod, strKeys);
+ m_lstCommands.AddString(strLine);
+
+ strLine.Format("%s \t\t\t%s%s", g_Commands[n].m_strCommand, strMod, strKeys);
+
+ fileout.Write(strLine, strLine.GetLength());
+ fileout.Write("\r\n", 2);
+ }
+ fileout.Close();
+ return TRUE; // return TRUE unless you set the focus to a control
+ // EXCEPTION: OCX Property Pages should return FALSE
+}
diff --git a/q3radiant/CommandsDlg.h b/q3radiant/CommandsDlg.h
new file mode 100755
index 0000000..7347e84
--- /dev/null
+++ b/q3radiant/CommandsDlg.h
@@ -0,0 +1,67 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_COMMANDSDLG_H__C80F6E42_8531_11D1_B548_00AA00A410FC__INCLUDED_)
+#define AFX_COMMANDSDLG_H__C80F6E42_8531_11D1_B548_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// CommandsDlg.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CCommandsDlg dialog
+
+class CCommandsDlg : public CDialog
+{
+// Construction
+public:
+ CCommandsDlg(CWnd* pParent = NULL); // standard constructor
+
+// Dialog Data
+ //{{AFX_DATA(CCommandsDlg)
+ enum { IDD = IDD_DLG_COMMANDLIST };
+ CListBox m_lstCommands;
+ //}}AFX_DATA
+
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CCommandsDlg)
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+
+ // Generated message map functions
+ //{{AFX_MSG(CCommandsDlg)
+ virtual BOOL OnInitDialog();
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_COMMANDSDLG_H__C80F6E42_8531_11D1_B548_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/DRAG.CPP b/q3radiant/DRAG.CPP
new file mode 100755
index 0000000..d6a0928
--- /dev/null
+++ b/q3radiant/DRAG.CPP
@@ -0,0 +1,828 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "stdafx.h"
+#include "qe3.h"
+
+/*
+
+ drag either multiple brushes, or select plane points from
+ a single brush.
+
+*/
+
+qboolean drag_ok;
+vec3_t drag_xvec;
+vec3_t drag_yvec;
+
+static int buttonstate;
+int pressx, pressy;
+static vec3_t pressdelta;
+static vec3_t vPressStart;
+static int buttonx, buttony;
+
+
+//int num_move_points;
+//float *move_points[1024];
+
+int lastx, lasty;
+
+qboolean drag_first;
+
+
+void AxializeVector (vec3_t v)
+{
+ vec3_t a;
+ float o;
+ int i;
+
+ if (!v[0] && !v[1])
+ return;
+ if (!v[1] && !v[2])
+ return;
+ if (!v[0] && !v[2])
+ return;
+
+ for (i=0 ; i<3 ; i++)
+ a[i] = fabs(v[i]);
+ if (a[0] > a[1] && a[0] > a[2])
+ i = 0;
+ else if (a[1] > a[0] && a[1] > a[2])
+ i = 1;
+ else
+ i = 2;
+
+ o = v[i];
+ VectorCopy (vec3_origin, v);
+ if (o<0)
+ v[i] = -1;
+ else
+ v[i] = 1;
+
+}
+
+
+/*
+===========
+Drag_Setup
+===========
+*/
+void Drag_Setup (int x, int y, int buttons,
+ vec3_t xaxis, vec3_t yaxis,
+ vec3_t origin, vec3_t dir)
+{
+ trace_t t;
+ face_t *f;
+
+ drag_first = true;
+
+ VectorCopy (vec3_origin, pressdelta);
+ pressx = x;
+ pressy = y;
+
+ VectorCopy (xaxis, drag_xvec);
+ AxializeVector (drag_xvec);
+ VectorCopy (yaxis, drag_yvec);
+ AxializeVector (drag_yvec);
+
+ if (g_qeglobals.d_select_mode == sel_addpoint) {
+ if (g_qeglobals.selectObject) {
+ g_qeglobals.selectObject->addPoint(origin[0], origin[1], origin[2]);
+ } else {
+ clearSelection();
+ }
+ return;
+ }
+
+ if (g_qeglobals.d_select_mode == sel_editpoint) {
+
+ if (g_qeglobals.selectObject) {
+ if (g_qeglobals.selectObject->selectPointByRay(origin[0], origin[1], origin[2], dir[0], dir[1], dir[2], !(buttons == MK_SHIFT)) >= 0) {
+ drag_ok = true;
+ }
+ return;
+ } else {
+ clearSelection();
+ }
+ Sys_UpdateWindows(W_ALL);
+ Undo_Start("drag object point");
+
+ return;
+ }
+
+
+ extern void SelectCurvePointByRay (vec3_t org, vec3_t dir, int buttons);
+ if (g_qeglobals.d_select_mode == sel_curvepoint)
+ {
+ //if ((buttons == MK_LBUTTON))
+ // g_qeglobals.d_num_move_points = 0;
+
+ SelectCurvePointByRay (origin, dir, buttons);
+
+ if (g_qeglobals.d_num_move_points || g_qeglobals.d_select_mode == sel_area)
+ {
+ drag_ok = true;
+ }
+
+ Sys_UpdateWindows(W_ALL);
+
+ Undo_Start("drag curve point");
+ Undo_AddBrushList(&selected_brushes);
+
+ return;
+ }
+ else if (g_qeglobals.d_select_mode == sel_terrainpoint)
+ {
+ Terrain_SelectPointByRay( origin, dir, buttons );
+
+ if (g_qeglobals.d_numterrapoints || g_qeglobals.d_select_mode == sel_area)
+ {
+ drag_ok = true;
+ }
+
+ Sys_UpdateWindows(W_ALL);
+
+ Undo_Start("drag terrain point");
+ Undo_AddBrushList(&selected_brushes);
+ return;
+ }
+ else if (g_qeglobals.d_select_mode == sel_terraintexture)
+ {
+ Terrain_SelectPointByRay( origin, dir, buttons );
+
+ if (g_qeglobals.d_numterrapoints || g_qeglobals.d_select_mode == sel_area)
+ {
+ drag_ok = true;
+ }
+
+ Sys_UpdateWindows(W_ALL);
+
+ Undo_Start("drag terrain point");
+ Undo_AddBrushList(&selected_brushes);
+ return;
+ }
+ else
+ {
+ g_qeglobals.d_num_move_points = 0;
+ }
+
+ if (selected_brushes.next == &selected_brushes)
+ {
+ //in this case a new brush is created when the dragging
+ //takes place in the XYWnd, An useless undo is created
+ //when the dragging takes place in the CamWnd
+ Undo_Start("create brush");
+
+ Sys_Status("No selection to drag\n", 0);
+ return;
+ }
+
+
+ if (g_qeglobals.d_select_mode == sel_vertex)
+ {
+ SelectVertexByRay (origin, dir);
+ if (g_qeglobals.d_num_move_points)
+ {
+ drag_ok = true;
+ Undo_Start("drag vertex");
+ Undo_AddBrushList(&selected_brushes);
+ return;
+ }
+ }
+
+ if (g_qeglobals.d_select_mode == sel_edge)
+ {
+ SelectEdgeByRay (origin, dir);
+ if (g_qeglobals.d_num_move_points)
+ {
+ drag_ok = true;
+ Undo_Start("drag edge");
+ Undo_AddBrushList(&selected_brushes);
+ return;
+ }
+ }
+
+
+ //
+ // check for direct hit first
+ //
+ t = Test_Ray (origin, dir, true);
+ if (t.selected)
+ {
+ drag_ok = true;
+
+ Undo_Start("drag selection");
+ Undo_AddBrushList(&selected_brushes);
+
+ if (buttons == (MK_LBUTTON|MK_CONTROL) )
+ {
+ Sys_Printf ("Shear dragging face\n");
+ Brush_SelectFaceForDragging (t.brush, t.face, true);
+ }
+ else if (buttons == (MK_LBUTTON|MK_CONTROL|MK_SHIFT) )
+ {
+ Sys_Printf ("Sticky dragging brush\n");
+ for (f=t.brush->brush_faces ; f ; f=f->next)
+ Brush_SelectFaceForDragging (t.brush, f, false);
+ }
+ else
+ Sys_Printf ("Dragging entire selection\n");
+
+ return;
+ }
+
+ if (g_qeglobals.d_select_mode == sel_vertex || g_qeglobals.d_select_mode == sel_edge)
+ return;
+
+ //
+ // check for side hit
+ //
+ // multiple brushes selected?
+ if (selected_brushes.next->next != &selected_brushes)
+ {
+ // yes, special handling
+ bool bOK = (g_PrefsDlg.m_bALTEdge) ? (static_cast<bool>(::GetAsyncKeyState(VK_MENU))) : true;
+ if (bOK)
+ {
+ for (brush_t* pBrush = selected_brushes.next ; pBrush != &selected_brushes ; pBrush = pBrush->next)
+ {
+ if (buttons & MK_CONTROL)
+ Brush_SideSelect (pBrush, origin, dir, true);
+ else
+ Brush_SideSelect (pBrush, origin, dir, false);
+ }
+ }
+ else
+ {
+ Sys_Printf ("press ALT to drag multiple edges\n");
+ return;
+ }
+ }
+ else
+ {
+ // single select.. trying to drag fixed entities handle themselves and just move
+ if (buttons & MK_CONTROL)
+ Brush_SideSelect (selected_brushes.next, origin, dir, true);
+ else
+ Brush_SideSelect (selected_brushes.next, origin, dir, false);
+ }
+
+ Sys_Printf ("Side stretch\n");
+ drag_ok = true;
+
+ Undo_Start("side stretch");
+ Undo_AddBrushList(&selected_brushes);
+}
+
+entity_t *peLink;
+
+void UpdateTarget(vec3_t origin, vec3_t dir)
+{
+ trace_t t;
+ entity_t *pe;
+ int i;
+ char sz[128];
+
+ t = Test_Ray (origin, dir, 0);
+
+ if (!t.brush)
+ return;
+
+ pe = t.brush->owner;
+
+ if (pe == NULL)
+ return;
+
+ // is this the first?
+ if (peLink != NULL)
+ {
+
+ // Get the target id from out current target
+ // if there is no id, make one
+
+ i = IntForKey(pe, "target");
+ if (i <= 0)
+ {
+ i = GetUniqueTargetId(1);
+ sprintf(sz, "%d", i);
+
+ SetKeyValue(pe, "target", sz);
+ }
+
+ // set the target # into our src
+
+ sprintf(sz, "%d", i);
+ SetKeyValue(peLink, "targetname", sz);
+
+ Sys_UpdateWindows(W_ENTITY);
+
+ }
+
+ // promote the target to the src
+
+ peLink = pe;
+
+}
+
+/*
+===========
+Drag_Begin
+//++timo test three button mouse and three button emulation here ?
+===========
+*/
+void Drag_Begin (int x, int y, int buttons,
+ vec3_t xaxis, vec3_t yaxis,
+ vec3_t origin, vec3_t dir)
+{
+ trace_t t;
+ bool altdown;
+
+ drag_ok = false;
+ VectorCopy (vec3_origin, pressdelta);
+ VectorCopy (vec3_origin, vPressStart);
+ drag_first = true;
+ peLink = NULL;
+
+ altdown = static_cast<bool>(::GetAsyncKeyState(VK_MENU));
+
+ // shift-LBUTTON = select entire brush
+ if (buttons == (MK_LBUTTON | MK_SHIFT) && g_qeglobals.d_select_mode != sel_curvepoint &&
+ g_qeglobals.d_select_mode != sel_terrainpoint && g_qeglobals.d_select_mode != sel_terraintexture)
+ {
+ int nFlag = altdown ? SF_CYCLE : 0;
+ if (dir[0] == 0 || dir[1] == 0 || dir[2] == 0) // extremely low chance of this happening from camera
+ Select_Ray (origin, dir, nFlag | SF_ENTITIES_FIRST); // hack for XY
+ else
+ Select_Ray (origin, dir, nFlag);
+ return;
+ }
+
+ // ctrl-alt-LBUTTON = multiple brush select without selecting whole entities
+ if (buttons == (MK_LBUTTON | MK_CONTROL) && altdown && g_qeglobals.d_select_mode != sel_curvepoint &&
+ g_qeglobals.d_select_mode != sel_terrainpoint && g_qeglobals.d_select_mode != sel_terraintexture)
+ {
+ if (dir[0] == 0 || dir[1] == 0 || dir[2] == 0) // extremely low chance of this happening from camera
+ Select_Ray (origin, dir, SF_ENTITIES_FIRST); // hack for XY
+ else
+ Select_Ray (origin, dir, 0);
+ return;
+ }
+
+ // ctrl-shift-LBUTTON = select single face
+ if (buttons == (MK_LBUTTON | MK_CONTROL | MK_SHIFT) && g_qeglobals.d_select_mode != sel_curvepoint &&
+ g_qeglobals.d_select_mode != sel_terrainpoint && g_qeglobals.d_select_mode != sel_terraintexture)
+ {
+ Select_Deselect (!static_cast<bool>(::GetAsyncKeyState(VK_MENU)));
+ Select_Ray (origin, dir, SF_SINGLEFACE);
+ return;
+ }
+
+
+ // LBUTTON + all other modifiers = manipulate selection
+ if (buttons & MK_LBUTTON)
+ {
+ //
+ Drag_Setup (x, y, buttons, xaxis, yaxis, origin, dir);
+ return;
+ }
+
+ int nMouseButton = g_PrefsDlg.m_nMouseButtons == 2 ? MK_RBUTTON : MK_MBUTTON;
+ // middle button = grab texture
+ if (buttons == nMouseButton)
+ {
+ t = Test_Ray (origin, dir, false);
+ if (t.face)
+ {
+ g_qeglobals.d_new_brush_bottom_z = t.brush->mins[2];
+ g_qeglobals.d_new_brush_top_z = t.brush->maxs[2];
+ // use a local brushprimit_texdef fitted to a default 2x2 texture
+ brushprimit_texdef_t bp_local;
+ ConvertTexMatWithQTexture( &t.face->brushprimit_texdef, t.face->d_texture, &bp_local, NULL );
+ Texture_SetTexture ( &t.face->texdef, &bp_local, false, GETPLUGINTEXDEF(t.face));
+ UpdateSurfaceDialog();
+ UpdatePatchInspector();
+ }
+ else
+ Sys_Printf ("Did not select a texture\n");
+ return;
+ }
+
+ // ctrl-middle button = set entire brush to texture
+ if (buttons == (nMouseButton|MK_CONTROL) )
+ {
+ t = Test_Ray (origin, dir, false);
+ if (t.brush)
+ {
+ if (t.brush->brush_faces->texdef.name[0] == '(')
+ Sys_Printf ("Can't change an entity texture\n");
+ else
+ {
+ Brush_SetTexture (t.brush, &g_qeglobals.d_texturewin.texdef, &g_qeglobals.d_texturewin.brushprimit_texdef, false, static_cast<IPluginTexdef *>( g_qeglobals.d_texturewin.pTexdef ) );
+ Sys_UpdateWindows (W_ALL);
+ }
+ }
+ else
+ Sys_Printf ("Didn't hit a btrush\n");
+ return;
+ }
+
+ // ctrl-shift-middle button = set single face to texture
+ if (buttons == (nMouseButton|MK_SHIFT|MK_CONTROL) )
+ {
+ t = Test_Ray (origin, dir, false);
+ if (t.brush)
+ {
+ if (t.brush->brush_faces->texdef.name[0] == '(')
+ Sys_Printf ("Can't change an entity texture\n");
+ else
+ {
+ SetFaceTexdef (t.brush, t.face, &g_qeglobals.d_texturewin.texdef, &g_qeglobals.d_texturewin.brushprimit_texdef);
+ Brush_Build( t.brush );
+ Sys_UpdateWindows (W_ALL);
+ }
+ }
+ else
+ Sys_Printf ("Didn't hit a btrush\n");
+ return;
+ }
+
+ if (buttons == (nMouseButton | MK_SHIFT))
+ {
+ Sys_Printf("Set brush face texture info\n");
+ t = Test_Ray (origin, dir, false);
+ if (t.brush)
+ {
+ if (t.brush->brush_faces->texdef.name[0] == '(')
+ {
+ if (t.brush->owner->eclass->nShowFlags & ECLASS_LIGHT)
+ {
+ CString strBuff;
+ qtexture_t* pTex = Texture_ForName(g_qeglobals.d_texturewin.texdef.name);
+ if (pTex)
+ {
+ vec3_t vColor;
+ VectorCopy(pTex->color, vColor);
+
+ float fLargest = 0.0f;
+ for (int i = 0; i < 3; i++)
+ {
+ if (vColor[i] > fLargest)
+ fLargest = vColor[i];
+ }
+
+ if (fLargest == 0.0f)
+ {
+ vColor[0] = vColor[1] = vColor[2] = 1.0f;
+ }
+ else
+ {
+ float fScale = 1.0f / fLargest;
+ for (int i = 0; i < 3; i++)
+ {
+ vColor[i] *= fScale;
+ }
+ }
+ strBuff.Format("%f %f %f",pTex->color[0], pTex->color[1], pTex->color[2]);
+ SetKeyValue(t.brush->owner, "_color", strBuff.GetBuffer(0));
+ Sys_UpdateWindows (W_ALL);
+ }
+ }
+ else
+ {
+ Sys_Printf ("Can't select an entity brush face\n");
+ }
+ }
+ else
+ {
+ //strcpy(t.face->texdef.name,g_qeglobals.d_texturewin.texdef.name);
+ t.face->texdef.SetName(g_qeglobals.d_texturewin.texdef.name);
+ Brush_Build(t.brush);
+ Sys_UpdateWindows (W_ALL);
+ }
+ }
+ else
+ Sys_Printf ("Didn't hit a brush\n");
+ return;
+ }
+
+}
+
+
+//
+//===========
+//MoveSelection
+//===========
+//
+void MoveSelection (vec3_t move)
+{
+ int i, success;
+ brush_t *b;
+ CString strStatus;
+ vec3_t vTemp, vTemp2, end;
+
+ if (!move[0] && !move[1] && !move[2])
+ return;
+
+ move[0] = (g_nScaleHow & SCALE_X) ? 0 : move[0];
+ move[1] = (g_nScaleHow & SCALE_Y) ? 0 : move[1];
+ move[2] = (g_nScaleHow & SCALE_Z) ? 0 : move[2];
+
+ if (g_pParentWnd->ActiveXY()->RotateMode() || g_bPatchBendMode)
+ {
+ float fDeg = -move[2];
+ float fAdj = move[2];
+ int nAxis = 0;
+ if (g_pParentWnd->ActiveXY()->GetViewType() == XY)
+ {
+ fDeg = -move[1];
+ fAdj = move[1];
+ nAxis = 2;
+ }
+ else
+ if (g_pParentWnd->ActiveXY()->GetViewType() == XZ)
+ {
+ fDeg = move[2];
+ fAdj = move[2];
+ nAxis = 1;
+ }
+ else
+ nAxis = 0;
+
+ g_pParentWnd->ActiveXY()->Rotation()[nAxis] += fAdj;
+ strStatus.Format("%s x:: %.1f y:: %.1f z:: %.1f", (g_bPatchBendMode) ? "Bend angle" : "Rotation", g_pParentWnd->ActiveXY()->Rotation()[0], g_pParentWnd->ActiveXY()->Rotation()[1], g_pParentWnd->ActiveXY()->Rotation()[2]);
+ g_pParentWnd->SetStatusText(2, strStatus);
+
+ if (g_bPatchBendMode)
+ {
+ Patch_SelectBendNormal();
+ Select_RotateAxis(nAxis, fDeg*2, false, true);
+ Patch_SelectBendAxis();
+ Select_RotateAxis(nAxis, fDeg, false, true);
+ }
+ else
+ {
+ Select_RotateAxis(nAxis, fDeg, false, true);
+ }
+ return;
+ }
+
+ if (g_pParentWnd->ActiveXY()->ScaleMode())
+ {
+ vec3_t v;
+ v[0] = v[1] = v[2] = 1.0;
+ if (move[1] > 0)
+ {
+ v[0] = 1.1;
+ v[1] = 1.1;
+ v[2] = 1.1;
+ }
+ else
+ if (move[1] < 0)
+ {
+ v[0] = 0.9;
+ v[1] = 0.9;
+ v[2] = 0.9;
+ }
+
+ Select_Scale((g_nScaleHow & SCALE_X) ? 1.0 : v[0],
+ (g_nScaleHow & SCALE_Y) ? 1.0 : v[1],
+ (g_nScaleHow & SCALE_Z) ? 1.0 : v[2]);
+ Sys_UpdateWindows (W_ALL);
+ return;
+ }
+
+
+ vec3_t vDistance;
+ VectorSubtract(pressdelta, vPressStart, vDistance);
+ strStatus.Format("Distance x: %.1f y: %.1f z: %.1f", vDistance[0], vDistance[1], vDistance[2]);
+ g_pParentWnd->SetStatusText(3, strStatus);
+
+ //
+ // dragging only a part of the selection
+ //
+ //point object selection
+ if (g_qeglobals.d_select_mode == sel_editpoint) {
+ if (g_qeglobals.selectObject) {
+ g_qeglobals.selectObject->updateSelection(move[0], move[1], move[2]);
+ }
+ return;
+ }
+
+
+ // this is fairly crappy way to deal with curvepoint and area selection
+ // but it touches the smallest amount of code this way
+ //
+ if (g_qeglobals.d_num_move_points || g_qeglobals.d_numterrapoints || g_qeglobals.d_select_mode == sel_area)
+ {
+ //area selection
+ if (g_qeglobals.d_select_mode == sel_area)
+ {
+ VectorAdd(g_qeglobals.d_vAreaBR, move, g_qeglobals.d_vAreaBR);
+ return;
+ }
+ //curve point selection
+ if (g_qeglobals.d_select_mode == sel_curvepoint)
+ {
+ Patch_UpdateSelected(move);
+ return;
+ }
+ //terrain point selection
+ if ( ( g_qeglobals.d_select_mode == sel_terrainpoint ) || ( g_qeglobals.d_select_mode == sel_terraintexture ) )
+ {
+ Terrain_UpdateSelected(move);
+ return;
+ }
+
+ //vertex selection
+ if (g_qeglobals.d_select_mode == sel_vertex)
+ {
+ success = true;
+ for (b = selected_brushes.next; b != &selected_brushes; b = b->next)
+ {
+ success &= Brush_MoveVertex(b, g_qeglobals.d_move_points[0], move, end, true);
+ }
+ if (success)
+ VectorCopy(end, g_qeglobals.d_move_points[0]);
+ return;
+ }
+ //all other selection types
+ for (i=0 ; i<g_qeglobals.d_num_move_points ; i++)
+ VectorAdd (g_qeglobals.d_move_points[i], move, g_qeglobals.d_move_points[i]);
+ //VectorScale(move, .5, move);
+ //for (i=0 ; i<g_qeglobals.d_num_move_points2 ; i++)
+ // VectorAdd (g_qeglobals.d_move_points2[i], move, g_qeglobals.d_move_points2[i]);
+ for (b = selected_brushes.next; b != &selected_brushes; b = b->next)
+ {
+ VectorCopy(b->maxs, vTemp);
+ VectorSubtract(vTemp, b->mins, vTemp);
+ Brush_Build( b );
+ for (i=0 ; i<3 ; i++)
+ if (b->mins[i] > b->maxs[i]
+ || b->maxs[i] - b->mins[i] > MAX_BRUSH_SIZE)
+ break; // dragged backwards or fucked up
+ if (i != 3)
+ break;
+ if (b->patchBrush)
+ {
+ VectorCopy(b->maxs, vTemp2);
+ VectorSubtract(vTemp2, b->mins, vTemp2);
+ VectorSubtract(vTemp2, vTemp, vTemp2);
+ //if (!Patch_DragScale(b->nPatchID, vTemp2, move))
+ if (!Patch_DragScale(b->pPatch, vTemp2, move))
+ {
+ b = NULL;
+ break;
+ }
+ }
+
+ if (b->terrainBrush)
+ {
+ VectorCopy(b->maxs, vTemp2);
+ VectorSubtract(vTemp2, b->mins, vTemp2);
+ VectorSubtract(vTemp2, vTemp, vTemp2);
+ if (!Terrain_DragScale(b->pTerrain, vTemp2, move))
+ {
+ b = NULL;
+ break;
+ }
+ }
+ }
+ // if any of the brushes were crushed out of existance
+ // calcel the entire move
+ if (b != &selected_brushes)
+ {
+ Sys_Printf ("Brush dragged backwards, move canceled\n");
+ for (i=0 ; i<g_qeglobals.d_num_move_points ; i++)
+ VectorSubtract (g_qeglobals.d_move_points[i], move, g_qeglobals.d_move_points[i]);
+
+ for (b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ Brush_Build( b );
+ }
+
+ }
+ else
+ {
+ // reset face originals from vertex edit mode
+ // this is dirty, but unfortunately necessary because Brush_Build
+ // can remove windings
+ for (b = selected_brushes.next; b != &selected_brushes; b = b->next)
+ {
+ Brush_ResetFaceOriginals(b);
+ }
+ //
+ // if there are lots of brushes selected, just translate instead
+ // of rebuilding the brushes
+ //
+ if (drag_yvec[2] == 0 && selected_brushes.next->next != &selected_brushes)
+ {
+ Select_Move (move);
+ //VectorAdd (g_qeglobals.d_select_translate, move, g_qeglobals.d_select_translate);
+ }
+ else
+ {
+ Select_Move (move);
+ }
+ }
+}
+
+/*
+===========
+Drag_MouseMoved
+===========
+*/
+void Drag_MouseMoved (int x, int y, int buttons)
+{
+ vec3_t move, delta;
+ int i;
+
+ if (!buttons)
+ {
+ drag_ok = false;
+ return;
+ }
+ if (!drag_ok)
+ return;
+
+ // clear along one axis
+ if (buttons & MK_SHIFT)
+ {
+ drag_first = false;
+ if (abs(x-pressx) > abs(y-pressy))
+ y = pressy;
+ else
+ x = pressx;
+ }
+
+
+ for (i=0 ; i<3 ; i++)
+ {
+ move[i] = drag_xvec[i]*(x - pressx) + drag_yvec[i]*(y - pressy);
+ if (!g_PrefsDlg.m_bNoClamp)
+ {
+ move[i] = floor(move[i]/g_qeglobals.d_gridsize+0.5)*g_qeglobals.d_gridsize;
+ }
+ }
+
+ VectorSubtract (move, pressdelta, delta);
+ VectorCopy (move, pressdelta);
+
+ MoveSelection (delta);
+
+}
+
+/*
+===========
+Drag_MouseUp
+===========
+*/
+void Drag_MouseUp (int nButtons)
+{
+ Sys_Status ("drag completed.", 0);
+
+ if (g_qeglobals.d_select_mode == sel_area)
+ {
+ if ( OnlyTerrainSelected() )
+ {
+ Terrain_SelectAreaPoints();
+ g_qeglobals.d_select_mode = sel_terrainpoint;
+ Sys_UpdateWindows (W_ALL);
+ }
+ else
+ {
+ Patch_SelectAreaPoints();
+ g_qeglobals.d_select_mode = sel_curvepoint;
+ Sys_UpdateWindows (W_ALL);
+ }
+ }
+
+ if (g_qeglobals.d_select_translate[0] || g_qeglobals.d_select_translate[1] || g_qeglobals.d_select_translate[2])
+ {
+ Select_Move (g_qeglobals.d_select_translate);
+ VectorCopy (vec3_origin, g_qeglobals.d_select_translate);
+ Sys_UpdateWindows (W_CAMERA);
+ }
+
+ g_pParentWnd->SetStatusText(3, "");
+
+ //
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
diff --git a/q3radiant/DialogInfo.cpp b/q3radiant/DialogInfo.cpp
new file mode 100755
index 0000000..3015997
--- /dev/null
+++ b/q3radiant/DialogInfo.cpp
@@ -0,0 +1,94 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// DialogInfo.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "DialogInfo.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CDialogInfo dialog
+CDialogInfo g_dlgInfo;
+
+void ShowInfoDialog(const char* pText)
+{
+ if (g_dlgInfo.GetSafeHwnd())
+ {
+ g_dlgInfo.m_wndInfo.SetWindowText(pText);
+ g_dlgInfo.ShowWindow(SW_SHOW);
+ }
+ else
+ {
+ g_dlgInfo.Create(IDD_DLG_INFORMATION);
+ g_dlgInfo.m_wndInfo.SetWindowText(pText);
+ g_dlgInfo.ShowWindow(SW_SHOW);
+ }
+ g_pParentWnd->SetFocus();
+}
+
+void HideInfoDialog()
+{
+ if (g_dlgInfo.GetSafeHwnd())
+ g_dlgInfo.ShowWindow(SW_HIDE);
+}
+
+
+CDialogInfo::CDialogInfo(CWnd* pParent /*=NULL*/)
+ : CDialog(CDialogInfo::IDD, pParent)
+{
+ //{{AFX_DATA_INIT(CDialogInfo)
+ //}}AFX_DATA_INIT
+}
+
+
+void CDialogInfo::DoDataExchange(CDataExchange* pDX)
+{
+ CDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CDialogInfo)
+ DDX_Control(pDX, IDC_EDIT1, m_wndInfo);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CDialogInfo, CDialog)
+ //{{AFX_MSG_MAP(CDialogInfo)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CDialogInfo message handlers
+
+BOOL CDialogInfo::OnInitDialog()
+{
+ CDialog::OnInitDialog();
+ // TODO: Add extra initialization here
+
+ return TRUE; // return TRUE unless you set the focus to a control
+ // EXCEPTION: OCX Property Pages should return FALSE
+}
diff --git a/q3radiant/DialogInfo.h b/q3radiant/DialogInfo.h
new file mode 100755
index 0000000..f0faafc
--- /dev/null
+++ b/q3radiant/DialogInfo.h
@@ -0,0 +1,69 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_DIALOGINFO_H__81DF2A33_A552_11D1_B58E_00AA00A410FC__INCLUDED_)
+#define AFX_DIALOGINFO_H__81DF2A33_A552_11D1_B58E_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// DialogInfo.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CDialogInfo dialog
+void HideInfoDialog();
+void ShowInfoDialog(const char* pText);
+
+class CDialogInfo : public CDialog
+{
+// Construction
+public:
+ CDialogInfo(CWnd* pParent = NULL); // standard constructor
+
+// Dialog Data
+ //{{AFX_DATA(CDialogInfo)
+ enum { IDD = IDD_DLG_INFORMATION };
+ CEdit m_wndInfo;
+ //}}AFX_DATA
+
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CDialogInfo)
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+
+ // Generated message map functions
+ //{{AFX_MSG(CDialogInfo)
+ virtual BOOL OnInitDialog();
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_DIALOGINFO_H__81DF2A33_A552_11D1_B58E_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/DialogTextures.cpp b/q3radiant/DialogTextures.cpp
new file mode 100755
index 0000000..f91766b
--- /dev/null
+++ b/q3radiant/DialogTextures.cpp
@@ -0,0 +1,89 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// DialogTextures.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "DialogTextures.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CDialogTextures dialog
+
+
+CDialogTextures::CDialogTextures(CWnd* pParent /*=NULL*/)
+ : CDialog(CDialogTextures::IDD, pParent)
+{
+ //{{AFX_DATA_INIT(CDialogTextures)
+ // NOTE: the ClassWizard will add member initialization here
+ //}}AFX_DATA_INIT
+}
+
+
+void CDialogTextures::DoDataExchange(CDataExchange* pDX)
+{
+ CDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CDialogTextures)
+ DDX_Control(pDX, IDC_LIST_TEXTURES, m_wndList);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CDialogTextures, CDialog)
+ //{{AFX_MSG_MAP(CDialogTextures)
+ ON_LBN_DBLCLK(IDC_LIST_TEXTURES, OnDblclkListTextures)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CDialogTextures message handlers
+
+void CDialogTextures::OnOK()
+{
+ m_nSelection = m_wndList.GetCurSel();
+ CDialog::OnOK();
+}
+
+void CDialogTextures::OnDblclkListTextures()
+{
+ OnOK();
+}
+
+BOOL CDialogTextures::OnInitDialog()
+{
+ CDialog::OnInitDialog();
+ CStringArray sa;
+ FillTextureMenu(&sa);
+ m_nSelection = -1;
+ for (int i = 0; i < sa.GetSize(); i ++)
+ {
+ m_wndList.AddString(sa.GetAt(i));
+ }
+ return TRUE; // return TRUE unless you set the focus to a control
+ // EXCEPTION: OCX Property Pages should return FALSE
+}
diff --git a/q3radiant/DialogTextures.h b/q3radiant/DialogTextures.h
new file mode 100755
index 0000000..368b088
--- /dev/null
+++ b/q3radiant/DialogTextures.h
@@ -0,0 +1,69 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_DIALOGTEXTURES_H__F3F3F984_E47E_11D1_B61B_00AA00A410FC__INCLUDED_)
+#define AFX_DIALOGTEXTURES_H__F3F3F984_E47E_11D1_B61B_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// DialogTextures.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CDialogTextures dialog
+
+class CDialogTextures : public CDialog
+{
+// Construction
+public:
+ CDialogTextures(CWnd* pParent = NULL); // standard constructor
+
+// Dialog Data
+ //{{AFX_DATA(CDialogTextures)
+ enum { IDD = IDD_DIALOG_TEXTURELIST };
+ CListBox m_wndList;
+ //}}AFX_DATA
+ int m_nSelection;
+
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CDialogTextures)
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+ // Generated message map functions
+ //{{AFX_MSG(CDialogTextures)
+ virtual void OnOK();
+ afx_msg void OnDblclkListTextures();
+ virtual BOOL OnInitDialog();
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_DIALOGTEXTURES_H__F3F3F984_E47E_11D1_B61B_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/DialogThick.cpp b/q3radiant/DialogThick.cpp
new file mode 100755
index 0000000..8b5eb33
--- /dev/null
+++ b/q3radiant/DialogThick.cpp
@@ -0,0 +1,66 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// DialogThick.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "DialogThick.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CDialogThick dialog
+
+
+CDialogThick::CDialogThick(CWnd* pParent /*=NULL*/)
+ : CDialog(CDialogThick::IDD, pParent)
+{
+ //{{AFX_DATA_INIT(CDialogThick)
+ m_bSeams = TRUE;
+ m_nAmount = 8;
+ //}}AFX_DATA_INIT
+}
+
+
+void CDialogThick::DoDataExchange(CDataExchange* pDX)
+{
+ CDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CDialogThick)
+ DDX_Check(pDX, IDC_CHECK_SEAMS, m_bSeams);
+ DDX_Text(pDX, IDC_EDIT_AMOUNT, m_nAmount);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CDialogThick, CDialog)
+ //{{AFX_MSG_MAP(CDialogThick)
+ // NOTE: the ClassWizard will add message map macros here
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CDialogThick message handlers
diff --git a/q3radiant/DialogThick.h b/q3radiant/DialogThick.h
new file mode 100755
index 0000000..303dfe2
--- /dev/null
+++ b/q3radiant/DialogThick.h
@@ -0,0 +1,68 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_DIALOGTHICK_H__59F46602_553D_11D2_B082_00AA00A410FC__INCLUDED_)
+#define AFX_DIALOGTHICK_H__59F46602_553D_11D2_B082_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// DialogThick.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CDialogThick dialog
+
+class CDialogThick : public CDialog
+{
+// Construction
+public:
+ CDialogThick(CWnd* pParent = NULL); // standard constructor
+
+// Dialog Data
+ //{{AFX_DATA(CDialogThick)
+ enum { IDD = IDD_DIALOG_THICKEN };
+ BOOL m_bSeams;
+ int m_nAmount;
+ //}}AFX_DATA
+
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CDialogThick)
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+
+ // Generated message map functions
+ //{{AFX_MSG(CDialogThick)
+ // NOTE: the ClassWizard will add member functions here
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_DIALOGTHICK_H__59F46602_553D_11D2_B082_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/DlgEvent.cpp b/q3radiant/DlgEvent.cpp
new file mode 100755
index 0000000..2af1629
--- /dev/null
+++ b/q3radiant/DlgEvent.cpp
@@ -0,0 +1,65 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// DlgEvent.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "DlgEvent.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CDlgEvent dialog
+
+
+CDlgEvent::CDlgEvent(CWnd* pParent /*=NULL*/)
+ : CDialog(CDlgEvent::IDD, pParent)
+{
+ //{{AFX_DATA_INIT(CDlgEvent)
+ m_strParm = _T("");
+ m_event = 0;
+ //}}AFX_DATA_INIT
+}
+
+
+void CDlgEvent::DoDataExchange(CDataExchange* pDX)
+{
+ CDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CDlgEvent)
+ DDX_Text(pDX, IDC_EDIT_PARAM, m_strParm);
+ DDX_Radio(pDX, IDC_RADIO_EVENT, m_event);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CDlgEvent, CDialog)
+ //{{AFX_MSG_MAP(CDlgEvent)
+ // NOTE: the ClassWizard will add message map macros here
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CDlgEvent message handlers
diff --git a/q3radiant/DlgEvent.h b/q3radiant/DlgEvent.h
new file mode 100755
index 0000000..f99235a
--- /dev/null
+++ b/q3radiant/DlgEvent.h
@@ -0,0 +1,69 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_DLGEVENT_H__B12EEBE1_FB71_407B_9075_50F63B168567__INCLUDED_)
+#define AFX_DLGEVENT_H__B12EEBE1_FB71_407B_9075_50F63B168567__INCLUDED_
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+// DlgEvent.h : header file
+//
+
+#include "splines/splines.h"
+/////////////////////////////////////////////////////////////////////////////
+// CDlgEvent dialog
+
+class CDlgEvent : public CDialog
+{
+// Construction
+public:
+ CDlgEvent(CWnd* pParent = NULL); // standard constructor
+
+// Dialog Data
+ //{{AFX_DATA(CDlgEvent)
+ enum { IDD = IDD_DLG_CAMERAEVENT };
+ CString m_strParm;
+ int m_event;
+ //}}AFX_DATA
+
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CDlgEvent)
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+
+ // Generated message map functions
+ //{{AFX_MSG(CDlgEvent)
+ // NOTE: the ClassWizard will add member functions here
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_DLGEVENT_H__B12EEBE1_FB71_407B_9075_50F63B168567__INCLUDED_)
diff --git a/q3radiant/ECLASS.CPP b/q3radiant/ECLASS.CPP
new file mode 100755
index 0000000..0e3f46a
--- /dev/null
+++ b/q3radiant/ECLASS.CPP
@@ -0,0 +1,932 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "stdafx.h"
+#include "qe3.h"
+#include "io.h"
+#include "pakstuff.h"
+//#include "qertypes.h"
+
+eclass_t *eclass = NULL;
+eclass_t *eclass_bad = NULL;
+char eclass_directory[1024];
+
+// md3 cache for misc_models
+eclass_t *g_md3Cache = NULL;
+
+/*
+
+the classname, color triple, and bounding box are parsed out of comments
+A ? size means take the exact brush size.
+
+/*QUAKED <classname> (0 0 0) ?
+/*QUAKED <classname> (0 0 0) (-8 -8 -8) (8 8 8)
+
+Flag names can follow the size description:
+
+/*QUAKED func_door (0 .5 .8) ? START_OPEN STONE_SOUND DOOR_DONT_LINK GOLD_KEY SILVER_KEY
+
+*/
+
+void CleanEntityList(eclass_t *&pList)
+{
+ while (pList)
+ {
+ eclass_t* pTemp = pList->next;
+
+ entitymodel *model = pList->model;
+ while (model != NULL)
+ {
+ delete []model->pTriList;
+ model = model->pNext;
+ }
+
+ if (pList->modelpath)
+ free(pList->modelpath);
+ if (pList->skinpath) // PGM
+ free(pList->skinpath); // PGM
+
+ free(pList->name);
+ free(pList->comments);
+ free(pList);
+ pList = pTemp;
+ }
+
+ pList = NULL;
+
+}
+
+
+void CleanUpEntities()
+{
+ CleanEntityList(eclass);
+ CleanEntityList(g_md3Cache);
+/*
+ while (eclass)
+ {
+ eclass_t* pTemp = eclass->next;
+ delete []eclass->pTriList;
+
+ if (eclass->modelpath)
+ free(eclass->modelpath);
+ if (eclass->skinpath) // PGM
+ free(eclass->skinpath); // PGM
+
+ free(eclass->name);
+ free(eclass->comments);
+ free(eclass);
+ eclass = pTemp;
+ }
+
+ eclass = NULL;
+*/
+ if (eclass_bad)
+ {
+ free(eclass_bad->name);
+ free(eclass_bad->comments);
+ free(eclass_bad);
+ eclass_bad = NULL;
+ }
+}
+
+void ExtendBounds(vec3_t v, vec3_t &vMin, vec3_t &vMax)
+{
+ for (int i = 0 ;i < 3 ;i++)
+ {
+ vec_t f = v[i];
+
+ if (f < vMin[i])
+ {
+ vMin[i] = f;
+ }
+
+ if (f > vMax[i])
+ {
+ vMax[i] = f;
+ }
+ }
+}
+
+
+
+// FIXME: this code is a TOTAL clusterfuck
+//
+void LoadModel(const char *pLocation, eclass_t *e, vec3_t &vMin, vec3_t &vMax, entitymodel *&pModel, const char *pSkin)
+{
+ // this assumes a path only and uses tris.md2
+ // for the model and skin.pcx for the skin
+ char cPath[1024];
+ char cSkin[1024];
+ char cFullLocation[1024];
+ //struct _finddata_t fileinfo;
+
+ vMin[0] = vMin[1] = vMin[2] = 99999;
+ vMax[0] = vMax[1] = vMax[2] = -99999;
+
+ bool bMD3 = false;
+ bool bASE = false;
+
+ strcpy( cFullLocation, pLocation );
+
+ if (strstr(pLocation, ".md3"))
+ {
+ bMD3 = true;
+ }
+ else if (strstr(pLocation, ".md2") != NULL)
+ {
+ sprintf( cFullLocation, "%stris.md2", pLocation);
+ }
+ else if (strstr(pLocation, ".ase") != NULL)
+ {
+ bASE = true;
+ }
+
+ sprintf( cPath, "%s/%s", ValueForKey(g_qeglobals.d_project_entity, "basepath"), cFullLocation);
+
+ Sys_Printf("Loading model %s...", cPath);
+ unsigned char* p = NULL;
+ bool bOpen = (LoadFile(cPath, reinterpret_cast<void**>(&p)) > 0);
+ if (!bOpen)
+ {
+ Sys_Printf(" failed. Trying PAK file...");
+// sprintf (cPath, "%stris.md2", pLocation);
+ strcpy (cPath, cFullLocation);
+ bOpen = (PakLoadAnyFile(cPath, reinterpret_cast<void**>(&p)) > 0);
+ }
+
+ if (bOpen)
+ {
+ Sys_Printf(" successful.\n");
+
+ if (bASE)
+ {
+/*
+ free(p);
+ CString strOut;
+ ::GetTempPath(1024, strOut.GetBuffer(1024));
+ strOut.ReleaseBuffer();
+ AddSlash(strOut);
+ strOut += "Temp.ase";
+ CopyFile(cPath, strOut, false);
+ CString strIn = strOut;
+ FindReplace(strOut, ".ase", ".md3");
+ strcpy(cPath, strIn);
+ strcpy(cSkin, strOut);
+ Q3Data_ProduceTempMD3(ValueForKey(g_qeglobals.d_project_entity, "basepath"), cPath, cSkin);
+ CString strModel = cPath;
+ if (LoadFile(strOut.GetBuffer(0), reinterpret_cast<void**>(&p)) == 0)
+ {
+ Sys_Printf(" Conversion from ASE failed.\n");
+ return;
+ }
+ bMD3 = true;
+*/
+ }
+
+ if (bMD3)
+ {
+ md3Header_t header;
+ md3Surface_t *pSurface;
+ header = *(md3Header_t *)p;
+ if (pSkin != NULL)
+ {
+ strcpy(cSkin, pSkin);
+ }
+ else
+ {
+ cSkin[0] = '\0';
+ }
+ int n = header.numFrames;
+ pSurface = (md3Surface_t *) (p + header.ofsSurfaces);
+ for (int z = 0; z < header.numSurfaces; z++ )
+ {
+ int nTris = pSurface->numTriangles;
+
+ //unsigned char* pTris = reinterpret_cast<unsigned char*>(pSurface);
+ //pTris += pSurface->ofsTriangles;
+
+ if (nTris > 0)
+ {
+ int nStart = 0;
+ if (pModel->pTriList == NULL)
+ {
+ pModel->nModelPosition = 0;
+ pModel->pTriList = new trimodel[nTris];
+ pModel->nTriCount = nTris;
+ }
+ else
+ {
+ // already have one so we need to reallocate
+ int nNewCount = pModel->nTriCount + nTris;
+ trimodel* pNewModels = new trimodel[nNewCount];
+ for (int i = 0; i < pModel->nTriCount; i++)
+ {
+ memcpy(&pNewModels[i], &pModel->pTriList[i], sizeof(trimodel));
+ }
+ nStart = pModel->nTriCount;
+ pModel->nTriCount = nNewCount;
+ //nTris = nNewCount;
+ delete [] pModel->pTriList;
+ pModel->pTriList = pNewModels;
+ }
+
+ md3Triangle_t *pTris = reinterpret_cast<md3Triangle_t*>((reinterpret_cast<unsigned char*>(pSurface) + pSurface->ofsTriangles));
+ md3XyzNormal_t *pXyz = reinterpret_cast<md3XyzNormal_t*>((reinterpret_cast<unsigned char*>(pSurface) + pSurface->ofsXyzNormals));
+ if (e->nFrame < pSurface->numFrames)
+ {
+ pXyz += (e->nFrame * pSurface->numVerts);
+ }
+
+ md3St_t *pST = reinterpret_cast<md3St_t*>((reinterpret_cast<unsigned char*>(pSurface) + pSurface->ofsSt));
+
+ for (int i = 0; i < nTris; i++)
+ {
+ for (int k = 0; k < 3; k ++)
+ {
+ for (int j = 0; j < 3; j++)
+ {
+ //e->pTriList[i].v[k][j] = (f->verts[tri.index_xyz[k]].v[j] * f->scale[j] + f->translate[j]);
+ pModel->pTriList[nStart].v[k][j] = pXyz[pTris[i].indexes[k]].xyz[j] * MD3_XYZ_SCALE;
+ }
+ pModel->pTriList[nStart].st[k][0] = pST[pTris[i].indexes[k]].st[0];
+ pModel->pTriList[nStart].st[k][1] = pST[pTris[i].indexes[k]].st[1];
+ ExtendBounds (pModel->pTriList[nStart].v[k], vMin, vMax);
+ }
+ nStart++;
+ }
+
+ }
+
+ md3Shader_t *pShader = reinterpret_cast<md3Shader_t*>((reinterpret_cast<unsigned char*>(pSurface) + pSurface->ofsShaders));
+ sprintf (cPath, "%s/%s", ValueForKey(g_qeglobals.d_project_entity, "basepath"), pShader->name);
+ strlwr(cPath);
+ pModel->nTextureBind = Texture_LoadSkin(cPath, &pModel->nSkinWidth, &pModel->nSkinHeight);
+ if (pModel->nTextureBind == -1)
+ {
+ Sys_Printf("Model skin load failed on texture %s\n", cPath);
+ }
+ pSurface = (md3Surface_t *) ((( char * ) pSurface) + pSurface->ofsEnd);
+ pModel->pNext = reinterpret_cast<entitymodel_t*>(qmalloc(sizeof(entitymodel_t)));
+ pModel = pModel->pNext;
+ }
+ }
+ else
+ {
+
+ dmdl_t model;
+ daliasframe_t *f;
+ unsigned char* pTris = p;
+ dstvert_t *pST = NULL;
+ int nTris = 0;
+
+ // grab model params
+ memcpy(&model, p, sizeof(dmdl_t));
+ f = (daliasframe_t*)(p + model.ofs_frames);
+ pTris += model.ofs_tris;
+ pST = reinterpret_cast<dstvert_t*>(p + model.ofs_st);
+ nTris = model.num_tris;
+
+ if(pSkin)
+ {
+ strcpy (cSkin, pSkin);
+ if ((cSkin[strlen(cSkin)-1] == '\\') || (cSkin[strlen(cSkin)-1] == '/'))
+ strcat(cSkin, "skin.pcx\0");
+ }
+ else
+ {
+ strcpy(cSkin, (char *)(p + model.ofs_skins));
+ }
+
+ sprintf (cPath, "%s/%s", ValueForKey(g_qeglobals.d_project_entity, "basepath"), cSkin);
+ strlwr(cPath);
+ pModel->nTextureBind = Texture_LoadSkin(cPath, &pModel->nSkinWidth, &pModel->nSkinHeight);
+ if (pModel->nTextureBind == -1)
+ {
+ Sys_Printf("Model skin load failed on texture %s\n", cPath);
+ }
+ int nStart = 0;
+ if (pModel->pTriList == NULL)
+ {
+ pModel->nModelPosition = 0;
+ pModel->pTriList = new trimodel[nTris];
+ pModel->nTriCount = nTris;
+ }
+ else
+ {
+ // already have one so we need to reallocate
+ int nNewCount = pModel->nTriCount + nTris;
+ trimodel* pNewModels = new trimodel[nNewCount];
+ for (int i = 0; i < pModel->nTriCount; i++)
+ {
+ memcpy(&pNewModels[i], &pModel->pTriList[i], sizeof(trimodel));
+ }
+ nStart = pModel->nTriCount;
+ pModel->nTriCount = nNewCount;
+ nTris = nNewCount;
+ delete [] pModel->pTriList;
+ pModel->pTriList = pNewModels;
+ }
+
+ for (int i = nStart; i < nTris; i++)
+ {
+ dtriangle_t tri;
+ memcpy(&tri, pTris, sizeof(dtriangle_t));
+ for (int k = 0; k < 3; k ++)
+ {
+ for (int j = 0; j < 3; j++)
+ {
+ pModel->pTriList[i].v[k][j] = (f->verts[tri.index_xyz[k]].v[j] * f->scale[j] + f->translate[j]);
+ }
+
+ pModel->pTriList[i].st[k][0] = pST[tri.index_st[k]].s / pModel->nSkinWidth;
+ pModel->pTriList[i].st[k][1] = pST[tri.index_st[k]].t / pModel->nSkinHeight;;
+ ExtendBounds (pModel->pTriList[i].v[k], vMin, vMax);
+ }
+ pTris += sizeof(dtriangle_t);
+ }
+ }
+ free(p);
+ }
+ else
+ {
+ Sys_Printf(" failed.\n");
+ }
+
+#if 0
+ if (pModel->pTriList != NULL && pModel->nTriCount > 0 && !bMD3)
+ {
+ if(fabs(vMin[2]) < ((vMax[2]-vMin[2]) / 10.0)) // > 90% above 0 point.
+ pModel->nModelPosition = 1;
+// sprintf (cPath, "%s/%sskin.pcx", ValueForKey(g_qeglobals.d_project_entity, "basepath"), pLocation);
+ sprintf (cPath, "%s/%s", ValueForKey(g_qeglobals.d_project_entity, "basepath"), cSkin);
+ pModel->nTextureBind = Texture_LoadSkin(cPath, &pModel->nSkinWidth, &pModel->nSkinHeight);
+ if (pModel->nTextureBind == -1)
+ {
+// sprintf (cPath, "%sskin.pcx", pLocation);
+ strcpy (cPath, cSkin);
+ pModel->nTextureBind = Texture_LoadSkin(cPath, &pModel->nSkinWidth, &pModel->nSkinHeight);
+ }
+ }
+#endif
+
+}
+
+void setSpecialLoad(eclass_t *e, const char* pWhat, char*& p)
+{
+ CString str = e->comments;
+ int n = str.Find(pWhat);
+ if (n >= 0)
+ {
+ char* pText = e->comments + n + strlen(pWhat);
+ if (*pText == '\"')
+ pText++;
+
+ str = "";
+ while (*pText != '\"' && *pText != '\0')
+ {
+ str += *pText;
+ pText++;
+ }
+ if (str.GetLength() > 0)
+ {
+ p = strdup(str);
+ //--LoadModel(str, e);
+ }
+ }
+}
+
+char *debugname;
+
+eclass_t *Eclass_InitFromText (char *text)
+{
+ char *t;
+ int len;
+ int r, i;
+ char parms[256], *p;
+ eclass_t *e;
+ char color[128];
+
+ e = (eclass_t*)qmalloc(sizeof(*e));
+ memset (e, 0, sizeof(*e));
+
+ text += strlen("/*QUAKED ");
+
+// grab the name
+ text = COM_Parse (text);
+ e->name = (char*)qmalloc (strlen(com_token)+1);
+ strcpy (e->name, com_token);
+ debugname = e->name;
+
+// grab the color, reformat as texture name
+ r = sscanf (text," (%f %f %f)", &e->color[0], &e->color[1], &e->color[2]);
+ if (r != 3)
+ return e;
+ sprintf (color, "(%f %f %f)", e->color[0], e->color[1], e->color[2]);
+ //strcpy (e->texdef.name, color);
+ e->texdef.SetName(color);
+
+ while (*text != ')')
+ {
+ if (!*text)
+ return e;
+ text++;
+ }
+ text++;
+
+// get the size
+ text = COM_Parse (text);
+ if (com_token[0] == '(')
+ { // parse the size as two vectors
+ e->fixedsize = true;
+ r = sscanf (text,"%f %f %f) (%f %f %f)", &e->mins[0], &e->mins[1], &e->mins[2],
+ &e->maxs[0], &e->maxs[1], &e->maxs[2]);
+ if (r != 6)
+ return e;
+
+ for (i=0 ; i<2 ; i++)
+ {
+ while (*text != ')')
+ {
+ if (!*text)
+ return e;
+ text++;
+ }
+ text++;
+ }
+ }
+ else
+ { // use the brushes
+ }
+
+// get the flags
+
+
+// copy to the first /n
+ p = parms;
+ while (*text && *text != '\n')
+ *p++ = *text++;
+ *p = 0;
+ text++;
+
+// any remaining words are parm flags
+ p = parms;
+ for (i=0 ; i<8 ; i++)
+ {
+ p = COM_Parse (p);
+ if (!p)
+ break;
+ strcpy (e->flagnames[i], com_token);
+ }
+
+// find the length until close comment
+ for (t=text ; t[0] && !(t[0]=='*' && t[1]=='/') ; t++)
+ ;
+
+// copy the comment block out
+ len = t-text;
+ e->comments = (char*)qmalloc (len+1);
+ memcpy (e->comments, text, len);
+#if 0
+ for (i=0 ; i<len ; i++)
+ if (text[i] == '\n')
+ e->comments[i] = '\r';
+ else
+ e->comments[i] = text[i];
+#endif
+ e->comments[len] = 0;
+
+ setSpecialLoad(e, "model=", e->modelpath);
+ setSpecialLoad(e, "skin=", e->skinpath);
+ char *pFrame = NULL;
+ setSpecialLoad(e, "frame=", pFrame);
+ if (pFrame != NULL)
+ {
+ e->nFrame = atoi(pFrame);
+ }
+
+ if(!e->skinpath)
+ setSpecialLoad(e, "texture=", e->skinpath);
+
+ // setup show flags
+ e->nShowFlags = 0;
+ if (strcmpi(e->name, "light") == 0)
+ {
+ e->nShowFlags |= ECLASS_LIGHT;
+ }
+
+ if ( (strnicmp(e->name, "info_player", strlen("info_player")) == 0)
+ ||(strnicmp(e->name, "path_corner", strlen("path_corner")) == 0)
+ ||(strnicmp(e->name, "team_ctf", strlen("team_ctf")) == 0) )
+ {
+ e->nShowFlags |= ECLASS_ANGLE;
+ }
+ if (strcmpi(e->name, "path") == 0)
+ {
+ e->nShowFlags |= ECLASS_PATH;
+ }
+ if (strcmpi(e->name, "misc_model") == 0)
+ {
+ e->nShowFlags |= ECLASS_MISCMODEL;
+ }
+
+
+ return e;
+}
+
+qboolean Eclass_hasModel(eclass_t *e, vec3_t &vMin, vec3_t &vMax)
+{
+ if (e->modelpath != NULL)
+ {
+ if (e->model == NULL)
+ {
+ e->model = reinterpret_cast<entitymodel_t*>(qmalloc(sizeof(entitymodel_t)));
+ }
+ char *pModelBuff = strdup(e->modelpath);
+ char *pSkinBuff = NULL;
+ if (e->skinpath)
+ {
+ pSkinBuff = strdup(e->skinpath);
+ }
+
+ CStringList Models;
+ CStringList Skins;
+ char* pToken = strtok(pModelBuff, ";\0");
+ while (pToken != NULL)
+ {
+ Models.AddTail(pToken);
+ pToken = strtok(NULL, ";\0");
+ }
+
+ if (pSkinBuff != NULL)
+ {
+ pToken = strtok(pSkinBuff, ";\0");
+ while (pToken != NULL)
+ {
+ Skins.AddTail(pToken);
+ pToken = strtok(NULL, ";\0");
+ }
+ }
+
+ entitymodel *model = e->model;
+ for (int i = 0; i < Models.GetCount(); i++)
+ {
+ char *pSkin = NULL;
+ if (i < Skins.GetCount())
+ {
+ pSkin = Skins.GetAt(Skins.FindIndex(i)).GetBuffer(0);
+ }
+ LoadModel(Models.GetAt(Models.FindIndex(i)), e, vMin, vMax, model, pSkin);
+ model->pNext = reinterpret_cast<entitymodel_t*>(qmalloc(sizeof(entitymodel_t)));
+ model = model->pNext;
+ }
+
+ // at this poitn vMin and vMax contain the min max of the model
+ // which needs to be centered at origin 0, 0, 0
+
+ VectorSnap(vMin);
+ VectorSnap(vMax);
+
+ if (vMax[0] - vMin[0] < 2)
+ {
+ vMin[0] -= 1;
+ vMax[0] += 1;
+ }
+
+ if (vMin[1] - vMax[1] < 2)
+ {
+ vMin[1] -= 1;
+ vMax[1] += 1;
+ }
+
+ if (vMax[2] - vMin[2] < 2)
+ {
+ vMax[2] -= 1;
+ vMax[2] += 1;
+ }
+
+ vec3_t vTemp;
+ VectorAdd(vMin, vMax, vTemp);
+ VectorScale(vTemp, 0.5, vTemp);
+ model = e->model;
+ while (model != NULL)
+ {
+ for (i = 0; i < model->nTriCount; i++)
+ {
+ for (int j = 0; j < 3; j++)
+ {
+ ;//VectorSubtract(model->pTriList[i].v[j], vTemp, model->pTriList[i].v[j]);
+ }
+ }
+ model = model->pNext;
+ }
+
+ free(pModelBuff);
+ free(e->modelpath);
+ e->modelpath = NULL;
+
+ if(e->skinpath)
+ {
+ free(e->skinpath);
+ e->skinpath = NULL;
+ free(pSkinBuff);
+ }
+
+ }
+ return (e->model != NULL && e->model->nTriCount > 0);
+}
+
+
+void EClass_InsertSortedList(eclass_t *&pList, eclass_t *e)
+{
+ eclass_t *s;
+
+ if (!pList)
+ {
+ pList = e;
+ return;
+ }
+
+
+ s = pList;
+ if (stricmp (e->name, s->name) < 0)
+ {
+ e->next = s;
+ pList = e;
+ return;
+ }
+
+ do
+ {
+ if (!s->next || stricmp (e->name, s->next->name) < 0)
+ {
+ e->next = s->next;
+ s->next = e;
+ return;
+ }
+ s=s->next;
+ } while (1);
+}
+
+/*
+=================
+Eclass_InsertAlphabetized
+=================
+*/
+void Eclass_InsertAlphabetized (eclass_t *e)
+{
+#if 1
+ EClass_InsertSortedList(eclass, e);
+#else
+ eclass_t *s;
+
+ if (!eclass)
+ {
+ eclass = e;
+ return;
+ }
+
+
+ s = eclass;
+ if (stricmp (e->name, s->name) < 0)
+ {
+ e->next = s;
+ eclass = e;
+ return;
+ }
+
+ do
+ {
+ if (!s->next || stricmp (e->name, s->next->name) < 0)
+ {
+ e->next = s->next;
+ s->next = e;
+ return;
+ }
+ s=s->next;
+ } while (1);
+#endif
+}
+
+
+/*
+=================
+Eclass_ScanFile
+=================
+*/
+
+qboolean parsing_single = false;
+qboolean eclass_found;
+eclass_t *eclass_e;
+//#ifdef BUILD_LIST
+extern bool g_bBuildList;
+CString strDefFile;
+//#endif
+void Eclass_ScanFile (char *filename)
+{
+ int size;
+ char *data;
+ eclass_t *e;
+ int i;
+ char temp[1024];
+
+ QE_ConvertDOSToUnixName( temp, filename );
+
+ Sys_Printf ("ScanFile: %s\n", temp);
+
+ // BUG
+ size = LoadFile (filename, (void**)&data);
+ eclass_found = false;
+ for (i=0 ; i<size ; i++)
+ if (!strncmp(data+i, "/*QUAKED",8))
+ {
+
+ //#ifdef BUILD_LIST
+ if (g_bBuildList)
+ {
+ CString strDef = "";
+ int j = i;
+ while (1)
+ {
+ strDef += *(data+j);
+ if (*(data+j) == '/' && *(data+j-1) == '*')
+ break;
+ j++;
+ }
+ strDef += "\r\n\r\n\r\n";
+ strDefFile += strDef;
+ }
+ //#endif
+ e = Eclass_InitFromText (data+i);
+ if (e)
+ Eclass_InsertAlphabetized (e);
+ else
+ printf ("Error parsing: %s in %s\n",debugname, filename);
+
+ // single ?
+ eclass_e = e;
+ eclass_found = true;
+ if ( parsing_single )
+ break;
+ }
+
+ free (data);
+}
+
+
+
+void Eclass_InitForSourceDirectory (char *path)
+{
+ struct _finddata_t fileinfo;
+ int handle;
+ char filename[1024];
+ char filebase[1024];
+ char temp[1024];
+ char *s;
+
+ QE_ConvertDOSToUnixName( temp, path );
+
+ Sys_Printf ("Eclass_InitForSourceDirectory: %s\n", temp );
+
+ strcpy (filebase, path);
+ s = filebase + strlen(filebase)-1;
+ while (*s != '\\' && *s != '/' && s!=filebase)
+ s--;
+ *s = 0;
+
+ CleanUpEntities();
+ eclass = NULL;
+//#ifdef BUILD_LIST
+ if (g_bBuildList)
+ strDefFile = "";
+//#endif
+ handle = _findfirst (path, &fileinfo);
+ if (handle != -1)
+ {
+ do
+ {
+ sprintf (filename, "%s\\%s", filebase, fileinfo.name);
+ Eclass_ScanFile (filename);
+ } while (_findnext( handle, &fileinfo ) != -1);
+
+ _findclose (handle);
+ }
+
+//#ifdef BUILD_LIST
+ if (g_bBuildList)
+ {
+ CFile file;
+ if (file.Open("c:\\entities.def", CFile::modeCreate | CFile::modeWrite))
+ {
+ file.Write(strDefFile.GetBuffer(0), strDefFile.GetLength());
+ file.Close();
+ }
+ }
+//#endif
+
+ eclass_bad = Eclass_InitFromText ("/*QUAKED UNKNOWN_CLASS (0 0.5 0) ?");
+}
+
+eclass_t *Eclass_ForName (char *name, qboolean has_brushes)
+{
+ eclass_t *e;
+ char init[1024];
+
+#ifdef _DEBUG
+ // grouping stuff, not an eclass
+ if (strcmp(name, "group_info")==0)
+ Sys_Printf("WARNING: unexpected group_info entity in Eclass_ForName\n");
+#endif
+
+ if (!name)
+ return eclass_bad;
+
+ for (e=eclass ; e ; e=e->next)
+ if (!strcmp (name, e->name))
+ return e;
+
+ // create a new class for it
+ if (has_brushes)
+ {
+ sprintf (init, "/*QUAKED %s (0 0.5 0) ?\nNot found in source.\n", name);
+ e = Eclass_InitFromText (init);
+ }
+ else
+ {
+ sprintf (init, "/*QUAKED %s (0 0.5 0) (-8 -8 -8) (8 8 8)\nNot found in source.\n", name);
+ e = Eclass_InitFromText (init);
+ }
+
+ Eclass_InsertAlphabetized (e);
+
+ return e;
+}
+
+
+eclass_t* GetCachedModel(entity_t *pEntity, const char *pName, vec3_t &vMin, vec3_t &vMax)
+{
+
+ eclass_t *e = NULL;
+ if (pName == NULL || strlen(pName) == 0)
+ {
+ return NULL;
+ }
+
+ for (e = g_md3Cache; e ; e = e->next)
+ {
+ if (!strcmp (pName, e->name))
+ {
+ pEntity->md3Class = e;
+ VectorCopy(e->mins, vMin);
+ VectorCopy(e->maxs, vMax);
+ return e;
+ }
+ }
+
+ e = (eclass_t*)qmalloc(sizeof(*e));
+ memset (e, 0, sizeof(*e));
+ e->name = strdup(pName);
+ e->modelpath = strdup(pName);
+ e->skinpath = strdup(pName);
+ char *p = strstr(e->skinpath, ".md3");
+ if (p != NULL)
+ {
+ p++;
+ strncpy(p, "tga", 3);
+ }
+ else
+ {
+ free(e->skinpath);
+ e->skinpath = NULL;
+ }
+
+ e->color[0] = e->color[2] = 0.85;
+
+ if (Eclass_hasModel(e, vMin, vMax))
+ {
+ EClass_InsertSortedList(g_md3Cache, e);
+ VectorCopy(vMin, e->mins);
+ VectorCopy(vMax, e->maxs);
+ pEntity->md3Class = e;
+ return e;
+ }
+
+ return NULL;
+}
diff --git a/q3radiant/ENTITY.CPP b/q3radiant/ENTITY.CPP
new file mode 100755
index 0000000..d4353b5
--- /dev/null
+++ b/q3radiant/ENTITY.CPP
@@ -0,0 +1,933 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "stdafx.h"
+#include "qe3.h"
+
+//
+int g_entityId = 1;
+
+char *ValueForKey ( epair_t *&e, const char *key)
+{
+ epair_t *ep;
+ for (ep=e ; ep ; ep=ep->next)
+ {
+ if (!strcmp (ep->key, key) )
+ {
+ return ep->value;
+ }
+ }
+ return "";
+}
+
+
+char *ValueForKey (entity_t *ent, const char *key)
+{
+ return ValueForKey(ent->epairs, key);
+}
+
+void TrackMD3Angles(entity_t *e, const char *key, const char *value)
+{
+ if (strcmpi(key, "angle") != 0)
+ {
+ return;
+ }
+
+ if (e->eclass->fixedsize && e->eclass->nShowFlags & ECLASS_MISCMODEL)
+ {
+ float a = FloatForKey (e, "angle");
+ float b = atof(value);
+ if (a != b)
+ {
+ vec3_t vAngle;
+ vAngle[0] = vAngle[1] = 0;
+ vAngle[2] = -a;
+ Brush_Rotate(e->brushes.onext, vAngle, e->origin, true);
+ vAngle[2] = b;
+ Brush_Rotate(e->brushes.onext, vAngle, e->origin, true);
+ }
+ }
+}
+
+void SetKeyValue (epair_t *&e, const char *key, const char *value)
+{
+ epair_t *ep;
+ for (ep=e ; ep ; ep=ep->next)
+ {
+ if (!strcmp (ep->key, key) )
+ {
+ free (ep->value);
+ ep->value = (char*)qmalloc(strlen(value)+1);
+ strcpy (ep->value, value);
+ return;
+ }
+ }
+ ep = (epair_t*)qmalloc (sizeof(*ep));
+ ep->next = e;
+ e = ep;
+ ep->key = (char*)qmalloc(strlen(key)+1);
+ strcpy (ep->key, key);
+ ep->value = (char*)qmalloc(strlen(value)+1);
+ strcpy (ep->value, value);
+
+}
+
+
+void SetKeyValue (entity_t *ent, const char *key, const char *value)
+{
+
+ if (ent == NULL)
+ return;
+
+ if (!key || !key[0])
+ return;
+
+ TrackMD3Angles(ent, key, value);
+
+ SetKeyValue(ent->epairs, key, value);
+
+}
+
+void DeleteKey (epair_t *&e, const char *key)
+{
+ epair_t **ep, *next;
+
+ ep = &e;
+ while (*ep)
+ {
+ next = *ep;
+ if ( !strcmp (next->key, key) )
+ {
+ *ep = next->next;
+ free(next->key);
+ free(next->value);
+ free(next);
+ return;
+ }
+ ep = &next->next;
+ }
+}
+
+
+void DeleteKey (entity_t *ent, const char *key)
+{
+ DeleteKey(ent->epairs, key);
+}
+
+
+
+
+float FloatForKey (entity_t *ent, const char *key)
+{
+ char *k;
+
+ k = ValueForKey (ent, key);
+ return atof(k);
+}
+
+int IntForKey (entity_t *ent, const char *key)
+{
+ char *k;
+
+ k = ValueForKey (ent, key);
+ return atoi(k);
+}
+
+void GetVectorForKey (entity_t *ent, const char *key, vec3_t vec)
+{
+ char *k;
+
+ k = ValueForKey (ent, key);
+ sscanf (k, "%f %f %f", &vec[0], &vec[1], &vec[2]);
+}
+
+/*
+===============
+Entity_FreeEpairs
+
+Frees the entity epairs.
+===============
+*/
+void Entity_FreeEpairs(entity_t *e)
+{
+ epair_t *ep, *next;
+
+ for (ep = e->epairs; ep; ep = next)
+ {
+ next = ep->next;
+ free (ep->key);
+ free (ep->value);
+ free (ep);
+ }
+ e->epairs = NULL;
+}
+
+/*
+===========
+Entity_AddToList
+===========
+*/
+void Entity_AddToList(entity_t *e, entity_t *list)
+{
+ if (e->next || e->prev)
+ Error ("Entity_AddToList: allready linked");
+ e->next = list->next;
+ list->next->prev = e;
+ list->next = e;
+ e->prev = list;
+}
+
+/*
+===========
+Entity_RemoveFromList
+===========
+*/
+void Entity_RemoveFromList (entity_t *e)
+{
+ if (!e->next || !e->prev)
+ Error ("Entity_RemoveFromList: not linked");
+ e->next->prev = e->prev;
+ e->prev->next = e->next;
+ e->next = e->prev = NULL;
+}
+
+
+
+/*
+===============
+Entity_Free
+
+Frees the entity and any brushes is has.
+The entity is removed from the global entities list.
+===============
+*/
+void Entity_Free (entity_t *e)
+{
+ // do we have a plugin entity ?
+ if ( e->pPlugEnt )
+ {
+ e->pPlugEnt->DecRef();
+ e->pPlugEnt = NULL;
+ }
+
+ while (e->brushes.onext != &e->brushes)
+ Brush_Free (e->brushes.onext);
+
+ if (e->next)
+ {
+ e->next->prev = e->prev;
+ e->prev->next = e->next;
+ }
+
+ Entity_FreeEpairs(e);
+
+ free (e);
+}
+
+/*
+=================
+Entity_MemorySize
+=================
+*/
+int Entity_MemorySize(entity_t *e)
+{
+ epair_t *ep;
+ int size = 0;
+
+ for (ep = e->epairs; ep; ep = ep->next)
+ {
+ size += _msize(ep->key);
+ size += _msize(ep->value);
+ size += _msize(ep);
+ }
+ size += _msize(e);
+ return size;
+}
+
+/*
+=================
+ParseEpair
+=================
+*/
+epair_t *ParseEpair (void)
+{
+ epair_t *e;
+
+ e = (epair_t*)qmalloc (sizeof(*e));
+
+ e->key = (char*)qmalloc(strlen(token)+1);
+ strcpy (e->key, token);
+
+ GetToken (false);
+ e->value = (char*)qmalloc(strlen(token)+1);
+ strcpy (e->value, token);
+
+ return e;
+}
+
+/*
+================
+Entity_Parse
+
+If onlypairs is set, the classname info will not
+be looked up, and the entity will not be added
+to the global list. Used for parsing the project.
+================
+*/
+entity_t *Entity_Parse (qboolean onlypairs, brush_t* pList)
+{
+ entity_t *ent;
+ eclass_t *e;
+ brush_t *b;
+ vec3_t mins, maxs;
+ epair_t *ep;
+ qboolean has_brushes;
+
+ if (!GetToken (true))
+ return NULL;
+
+ if (strcmp (token, "{") )
+ Error ("ParseEntity: { not found");
+
+ ent = (entity_t*)qmalloc (sizeof(*ent));
+ ent->entityId = g_entityId++;
+ ent->brushes.onext = ent->brushes.oprev = &ent->brushes;
+
+ int n = 0;
+ do
+ {
+ if (!GetToken (true))
+ {
+ Warning ("ParseEntity: EOF without closing brace");
+ return NULL;
+ }
+ if (!strcmp (token, "}") )
+ break;
+ if (!strcmp (token, "{") )
+ {
+ b = Brush_Parse ();
+ if (b != NULL)
+ {
+ b->owner = ent;
+ // add to the end of the entity chain
+ b->onext = &ent->brushes;
+ b->oprev = ent->brushes.oprev;
+ ent->brushes.oprev->onext = b;
+ ent->brushes.oprev = b;
+ }
+ else
+ {
+ break;
+ }
+ }
+ else
+ {
+ ep = ParseEpair ();
+ ep->next = ent->epairs;
+ ent->epairs = ep;
+ }
+ } while (1);
+
+ // group info entity?
+ if (strcmp(ValueForKey (ent, "classname"), "group_info") == 0)
+ return ent;
+
+ if (onlypairs)
+ return ent;
+
+ if (ent->brushes.onext == &ent->brushes)
+ has_brushes = false;
+ else
+ has_brushes = true;
+
+ GetVectorForKey (ent, "origin", ent->origin);
+
+ e = Eclass_ForName (ValueForKey (ent, "classname"), has_brushes);
+ ent->eclass = e;
+ if ( e->nShowFlags & ECLASS_PLUGINENTITY )
+ {
+ // locate the plugin
+ CPlugIn * pPlug = g_pParentWnd->GetPlugInMgr().PluginForModule( e->hPlug );
+ if (pPlug)
+ {
+ // create the plugin entity
+ IPluginEntity* pPlugEnt = pPlug->CreatePluginEntity( ent );
+ if (pPlugEnt)
+ {
+ ent->pPlugEnt = pPlugEnt;
+ // the brush is used to select and move
+ pPlugEnt->GetBounds( mins, maxs );
+ }
+ else
+ {
+ // give it a default bounding box
+ SetKeyValue (ent, "model", "");
+ mins[0] = -4; mins[1] = -4; mins[2] = -4;
+ maxs[0] = 4; maxs[1] = 4; maxs[2] = 4;
+ VectorAdd( mins, ent->origin, mins );
+ VectorAdd( maxs, ent->origin, maxs );
+ }
+ b = Brush_Create (mins, maxs, &ent->eclass->texdef);
+ Entity_LinkBrush (ent, b);
+ Brush_Build( b, true );
+ }
+ else
+ Sys_Printf("WARNING: plugin lookup failed for plugin entities\n");
+ }
+ else if (e->fixedsize)
+ { // fixed size entity
+ if (ent->brushes.onext != &ent->brushes)
+ {
+ printf ("Warning: Fixed size entity with brushes\n");
+#if 0
+ while (ent->brushes.onext != &ent->brushes)
+ { // FIXME: this will free the entity and crash!
+ Brush_Free (b);
+ }
+#endif
+ ent->brushes.next = ent->brushes.prev = &ent->brushes;
+ }
+
+ // create a custom brush
+ VectorAdd (e->mins, ent->origin, mins);
+ VectorAdd (e->maxs, ent->origin, maxs);
+
+ float a = 0;
+ if (e->nShowFlags & ECLASS_MISCMODEL)
+ {
+ char* p = ValueForKey(ent, "model");
+ if (p != NULL && strlen(p) > 0)
+ {
+ vec3_t vMin, vMax;
+ a = FloatForKey (ent, "angle");
+ if (GetCachedModel(ent, p, vMin, vMax))
+ {
+ // create a custom brush
+ VectorAdd (ent->md3Class->mins, ent->origin, mins);
+ VectorAdd (ent->md3Class->maxs, ent->origin, maxs);
+ }
+ }
+ }
+
+ b = Brush_Create (mins, maxs, &e->texdef);
+
+ if (a)
+ {
+ vec3_t vAngle;
+ vAngle[0] = vAngle[1] = 0;
+ vAngle[2] = a;
+ Brush_Rotate(b, vAngle, ent->origin, false);
+ }
+
+
+ b->owner = ent;
+
+ b->onext = ent->brushes.onext;
+ b->oprev = &ent->brushes;
+ ent->brushes.onext->oprev = b;
+ ent->brushes.onext = b;
+ }
+ else
+ { // brush entity
+ if (ent->brushes.next == &ent->brushes)
+ printf ("Warning: Brush entity with no brushes\n");
+ }
+
+ // add all the brushes to the main list
+ if (pList)
+ {
+ for (b=ent->brushes.onext ; b != &ent->brushes ; b=b->onext)
+ {
+ b->next = pList->next;
+ pList->next->prev = b;
+ b->prev = pList;
+ pList->next = b;
+ }
+ }
+
+ return ent;
+}
+
+void VectorMidpoint(vec3_t va, vec3_t vb, vec3_t& out)
+{
+ for (int i = 0; i < 3; i++)
+ out[i] = va[i] + ((vb[i] - va[i]) / 2);
+}
+
+
+/*
+============
+Entity_Write
+============
+*/
+void Entity_Write (entity_t *e, FILE *f, qboolean use_region)
+{
+ epair_t *ep;
+ brush_t *b;
+ vec3_t origin;
+ char text[128];
+ int count;
+
+ // if none of the entities brushes are in the region,
+ // don't write the entity at all
+ if (use_region)
+ {
+ // in region mode, save the camera position as playerstart
+ if ( !strcmp(ValueForKey (e, "classname"), "info_player_start") )
+ {
+ fprintf (f, "{\n");
+ fprintf (f, "\"classname\" \"info_player_start\"\n");
+ fprintf (f, "\"origin\" \"%i %i %i\"\n", (int)g_pParentWnd->GetCamera()->Camera().origin[0],
+ (int)g_pParentWnd->GetCamera()->Camera().origin[1], (int)g_pParentWnd->GetCamera()->Camera().origin[2]);
+ fprintf (f, "\"angle\" \"%i\"\n", (int)g_pParentWnd->GetCamera()->Camera().angles[YAW]);
+ fprintf (f, "}\n");
+ return;
+ }
+
+ for (b=e->brushes.onext ; b != &e->brushes ; b=b->onext)
+ if (!Map_IsBrushFiltered(b))
+ break; // got one
+
+ if (b == &e->brushes)
+ return; // nothing visible
+ }
+
+ if ( e->eclass->nShowFlags & ECLASS_PLUGINENTITY )
+ {
+ // NOTE: the whole brush placement / origin stuff is a mess
+ VectorCopy( e->origin, origin );
+ sprintf (text, "%i %i %i", (int)origin[0], (int)origin[1], (int)origin[2]);
+ SetKeyValue (e, "origin", text);
+ }
+ // if fixedsize, calculate a new origin based on the current
+ // brush position
+ else if (e->eclass->fixedsize)
+ {
+ if (e->eclass->nShowFlags & ECLASS_MISCMODEL && e->md3Class != NULL)
+ {
+ VectorCopy(e->origin, origin);
+ //VectorSubtract (e->brushes.onext->mins, e->md3Class->mins, origin);
+ }
+ else
+ {
+ VectorSubtract (e->brushes.onext->mins, e->eclass->mins, origin);
+ }
+ sprintf (text, "%i %i %i", (int)origin[0], (int)origin[1], (int)origin[2]);
+ SetKeyValue (e, "origin", text);
+ }
+
+ fprintf (f, "{\n");
+ for (ep = e->epairs ; ep ; ep=ep->next)
+ fprintf (f, "\"%s\" \"%s\"\n", ep->key, ep->value);
+
+ if (!e->eclass->fixedsize)
+ {
+ count = 0;
+ for (b=e->brushes.onext ; b != &e->brushes ; b=b->onext)
+ {
+ if (!use_region || !Map_IsBrushFiltered (b))
+ {
+ fprintf (f, "// brush %i\n", count);
+ count++;
+ Brush_Write (b, f);
+ }
+ }
+ }
+ fprintf (f, "}\n");
+}
+
+
+
+qboolean IsBrushSelected(brush_t* bSel)
+{
+ for (brush_t* b = selected_brushes.next ;b != NULL && b != &selected_brushes; b = b->next)
+ {
+ if (b == bSel)
+ return true;
+ }
+ return false;
+}
+
+//
+//============
+//Entity_WriteSelected
+//============
+//
+void Entity_WriteSelected(entity_t *e, FILE *f)
+{
+ epair_t *ep;
+ brush_t *b;
+ vec3_t origin;
+ char text[128];
+ int count;
+
+ for (b=e->brushes.onext ; b != &e->brushes ; b=b->onext)
+ if (IsBrushSelected(b))
+ break; // got one
+
+ if (b == &e->brushes)
+ return; // nothing selected
+
+ // if fixedsize, calculate a new origin based on the current
+ // brush position
+ if (e->eclass->fixedsize)
+ {
+ if (e->eclass->nShowFlags & ECLASS_MISCMODEL && e->md3Class != NULL)
+ {
+ VectorCopy(e->origin, origin);
+ //VectorSubtract (e->brushes.onext->mins, e->md3Class->mins, origin);
+ }
+ else
+ {
+ VectorSubtract (e->brushes.onext->mins, e->eclass->mins, origin);
+ }
+ sprintf (text, "%i %i %i", (int)origin[0], (int)origin[1], (int)origin[2]);
+ SetKeyValue (e, "origin", text);
+ }
+
+ fprintf (f, "{\n");
+ for (ep = e->epairs ; ep ; ep=ep->next)
+ fprintf (f, "\"%s\" \"%s\"\n", ep->key, ep->value);
+
+ if (!e->eclass->fixedsize)
+ {
+ count = 0;
+ for (b=e->brushes.onext ; b != &e->brushes ; b=b->onext)
+ {
+ if (IsBrushSelected(b))
+ {
+ fprintf (f, "// brush %i\n", count);
+ count++;
+ Brush_Write (b, f);
+ }
+ }
+ }
+ fprintf (f, "}\n");
+}
+
+
+//
+//============
+//Entity_WriteSelected to a CMemFile
+//============
+//
+void Entity_WriteSelected(entity_t *e, CMemFile* pMemFile)
+{
+ epair_t *ep;
+ brush_t *b;
+ vec3_t origin;
+ char text[128];
+ int count;
+
+ for (b=e->brushes.onext ; b != &e->brushes ; b=b->onext)
+ if (IsBrushSelected(b))
+ break; // got one
+
+ if (b == &e->brushes)
+ return; // nothing selected
+
+ // if fixedsize, calculate a new origin based on the current
+ // brush position
+ if (e->eclass->fixedsize)
+ {
+ if (e->eclass->nShowFlags & ECLASS_MISCMODEL && e->md3Class != NULL)
+ {
+ //VectorSubtract (e->brushes.onext->mins, e->md3Class->mins, origin);
+ VectorCopy(e->origin, origin);
+ }
+ else
+ {
+ VectorSubtract (e->brushes.onext->mins, e->eclass->mins, origin);
+ }
+ sprintf (text, "%i %i %i", (int)origin[0], (int)origin[1], (int)origin[2]);
+ SetKeyValue (e, "origin", text);
+ }
+
+ MemFile_fprintf(pMemFile, "{\n");
+ for (ep = e->epairs ; ep ; ep=ep->next)
+ MemFile_fprintf(pMemFile, "\"%s\" \"%s\"\n", ep->key, ep->value);
+
+ if (!e->eclass->fixedsize)
+ {
+ count = 0;
+ for (b=e->brushes.onext ; b != &e->brushes ; b=b->onext)
+ {
+ if (IsBrushSelected(b))
+ {
+ MemFile_fprintf(pMemFile, "// brush %i\n", count);
+ count++;
+ Brush_Write (b, pMemFile);
+ }
+ }
+ }
+ MemFile_fprintf(pMemFile, "}\n");
+}
+
+
+
+
+/*
+============
+Entity_Create
+
+Creates a new entity out of the selected_brushes list.
+If the entity class is fixed size, the brushes are only
+used to find a midpoint. Otherwise, the brushes have
+their ownership transfered to the new entity.
+============
+*/
+entity_t *Entity_Create (eclass_t *c)
+{
+ entity_t *e;
+ brush_t *b;
+ vec3_t mins, maxs;
+ int i;
+
+ // check to make sure the brushes are ok
+
+ for (b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ {
+ if (b->owner != world_entity)
+ {
+ Sys_Printf ("Entity NOT created, brushes not all from world\n");
+ Sys_Beep ();
+ return NULL;
+ }
+ }
+
+ // create it
+
+ e = (entity_t*)qmalloc(sizeof(*e));
+ e->entityId = g_entityId++;
+ e->brushes.onext = e->brushes.oprev = &e->brushes;
+ e->eclass = c;
+ SetKeyValue (e, "classname", c->name);
+
+ // add the entity to the entity list
+ Entity_AddToList(e, &entities);
+
+ // plugin entity ?
+ if (c->nShowFlags & ECLASS_PLUGINENTITY)
+ {
+ // locate the plugin
+ CPlugIn * pPlug = g_pParentWnd->GetPlugInMgr().PluginForModule( c->hPlug );
+ if (pPlug)
+ {
+ //
+ // just use the selection for positioning
+ //
+ b = selected_brushes.next;
+ for (i=0 ; i<3 ; i++)
+ e->origin[i] = b->mins[i] - c->mins[i];
+
+ // create the plugin entity
+ IPluginEntity* pPlugEnt = pPlug->CreatePluginEntity( e );
+
+ if (pPlugEnt)
+ {
+ e->pPlugEnt = pPlugEnt;
+ // the brush is used to select and move
+ pPlugEnt->GetBounds( mins, maxs );
+ b = Brush_Create (mins, maxs, &c->texdef);
+
+ Entity_LinkBrush (e, b);
+
+ // delete the current selection
+ Select_Delete ();
+
+ // select the new brush
+ b->next = b->prev = &selected_brushes;
+ selected_brushes.next = selected_brushes.prev = b;
+
+ Brush_Build( b );
+ }
+ }
+ else
+ {
+ Sys_Printf( "WARNING: plugin lookup failed while creating a plugin entitiy in Entity_Create\n" );
+ return NULL;
+ }
+ }
+ else if (c->fixedsize)
+ {
+ //
+ // just use the selection for positioning
+ //
+ b = selected_brushes.next;
+ for (i=0 ; i<3 ; i++)
+ e->origin[i] = b->mins[i] - c->mins[i];
+
+ // create a custom brush
+ VectorAdd (c->mins, e->origin, mins);
+ VectorAdd (c->maxs, e->origin, maxs);
+
+ b = Brush_Create (mins, maxs, &c->texdef);
+
+ Entity_LinkBrush (e, b);
+
+ // delete the current selection
+ Select_Delete ();
+
+ // select the new brush
+ b->next = b->prev = &selected_brushes;
+ selected_brushes.next = selected_brushes.prev = b;
+
+ Brush_Build( b );
+ }
+ else
+ {
+ //
+ // change the selected brushes over to the new entity
+ //
+ for (b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ {
+ Entity_UnlinkBrush (b);
+ Entity_LinkBrush (e, b);
+ Brush_Build( b ); // so the key brush gets a name
+ }
+ }
+
+ Sys_UpdateWindows (W_ALL);
+ return e;
+}
+
+
+/*
+===========
+Entity_LinkBrush
+===========
+*/
+void Entity_LinkBrush (entity_t *e, brush_t *b)
+{
+ if (b->oprev || b->onext)
+ Error ("Entity_LinkBrush: Allready linked");
+ b->owner = e;
+
+ b->onext = e->brushes.onext;
+ b->oprev = &e->brushes;
+ e->brushes.onext->oprev = b;
+ e->brushes.onext = b;
+}
+
+/*
+===========
+Entity_UnlinkBrush
+===========
+*/
+void Entity_UnlinkBrush (brush_t *b)
+{
+ //if (!b->owner || !b->onext || !b->oprev)
+ if (!b->onext || !b->oprev)
+ Error ("Entity_UnlinkBrush: Not currently linked");
+ b->onext->oprev = b->oprev;
+ b->oprev->onext = b->onext;
+ b->onext = b->oprev = NULL;
+ b->owner = NULL;
+}
+
+
+/*
+===========
+Entity_Clone
+===========
+*/
+entity_t *Entity_Clone (entity_t *e)
+{
+ entity_t *n;
+ epair_t *ep, *np;
+
+ n = (entity_t*)qmalloc(sizeof(*n));
+ n->entityId = g_entityId++;
+ n->brushes.onext = n->brushes.oprev = &n->brushes;
+ n->eclass = e->eclass;
+
+ // add the entity to the entity list
+ Entity_AddToList(n, &entities);
+
+ for (ep = e->epairs ; ep ; ep=ep->next)
+ {
+ np = (epair_t*)qmalloc(sizeof(*np));
+ np->key = copystring(ep->key);
+ np->value = copystring(ep->value);
+ np->next = n->epairs;
+ n->epairs = np;
+ }
+ return n;
+}
+
+int GetUniqueTargetId(int iHint)
+{
+ int iMin, iMax, i;
+ BOOL fFound;
+ entity_t *pe;
+
+ fFound = FALSE;
+ pe = entities.next;
+ iMin = 0;
+ iMax = 0;
+
+ for (; pe != NULL && pe != &entities ; pe = pe->next)
+ {
+ i = IntForKey(pe, "target");
+ if (i)
+ {
+ iMin = min(i, iMin);
+ iMax = max(i, iMax);
+ if (i == iHint)
+ fFound = TRUE;
+ }
+ }
+
+ if (fFound)
+ return iMax + 1;
+ else
+ return iHint;
+}
+
+entity_t *FindEntity(char *pszKey, char *pszValue)
+{
+ entity_t *pe;
+
+ pe = entities.next;
+
+ for (; pe != NULL && pe != &entities ; pe = pe->next)
+ {
+ if (!strcmp(ValueForKey(pe, pszKey), pszValue))
+ return pe;
+ }
+
+ return NULL;
+}
+
+entity_t *FindEntityInt(char *pszKey, int iValue)
+{
+ entity_t *pe;
+
+ pe = entities.next;
+
+ for (; pe != NULL && pe != &entities ; pe = pe->next)
+ {
+ if (IntForKey(pe, pszKey) == iValue)
+ return pe;
+ }
+
+ return NULL;
+}
diff --git a/q3radiant/ENTITY.H b/q3radiant/ENTITY.H
new file mode 100755
index 0000000..df929c0
--- /dev/null
+++ b/q3radiant/ENTITY.H
@@ -0,0 +1,76 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+ // entity.h
+
+ void Eclass_InitForSourceDirectory (char *path);
+ eclass_t *Eclass_ForName (char *name, qboolean has_brushes);
+
+ // forward declare this one
+ class IPluginEntity;
+
+ typedef struct entity_s
+ {
+ struct entity_s *prev, *next;
+ brush_t brushes; // head/tail of list
+ int undoId, redoId, entityId; // used for undo/redo
+ vec3_t origin;
+ eclass_t *eclass;
+ epair_t *epairs;
+ eclass_t *md3Class;
+ IPluginEntity *pPlugEnt;
+ vec3_t vRotation; // valid for misc_models only
+ vec3_t vScale; // valid for misc_models only
+ } entity_t;
+
+ char *ValueForKey (entity_t *ent, const char *key);
+ void SetKeyValue (entity_t *ent, const char *key, const char *value);
+ void SetKeyValue (epair_t *&e, const char *key, const char *value);
+ void DeleteKey (entity_t *ent, const char *key);
+ void DeleteKey (epair_t *&e, const char *key);
+ float FloatForKey (entity_t *ent, const char *key);
+ int IntForKey (entity_t *ent, const char *key);
+ void GetVectorForKey (entity_t *ent, const char *key, vec3_t vec);
+
+ void Entity_Free (entity_t *e);
+ void Entity_FreeEpairs(entity_t *e);
+ int Entity_MemorySize(entity_t *e);
+ entity_t *Entity_Parse (qboolean onlypairs, brush_t* pList = NULL);
+ void Entity_Write (entity_t *e, FILE *f, qboolean use_region);
+ void Entity_WriteSelected(entity_t *e, FILE *f);
+ void Entity_WriteSelected(entity_t *e, CMemFile*);
+ entity_t *Entity_Create (eclass_t *c);
+ entity_t *Entity_Clone (entity_t *e);
+ void Entity_AddToList(entity_t *e, entity_t *list);
+ void Entity_RemoveFromList(entity_t *e);
+
+ void Entity_LinkBrush (entity_t *e, brush_t *b);
+ void Entity_UnlinkBrush (brush_t *b);
+ entity_t *FindEntity(char *pszKey, char *pszValue);
+ entity_t *FindEntityInt(char *pszKey, int iValue);
+
+ int GetUniqueTargetId(int iHint);
+ qboolean Eclass_hasModel(eclass_t *e, vec3_t &vMin, vec3_t &vMax);
+ eclass_t* GetCachedModel(entity_t *pEntity, const char *pName, vec3_t &vMin, vec3_t &vMax);
+
+ //Timo : used for parsing epairs in brush primitive
+ epair_t* ParseEpair(void);
+ char *ValueForKey ( epair_t *&e, const char *key);
diff --git a/q3radiant/ENTITYW.H b/q3radiant/ENTITYW.H
new file mode 100755
index 0000000..7aad9da
--- /dev/null
+++ b/q3radiant/ENTITYW.H
@@ -0,0 +1,68 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// entity.h
+
+#define DlgXBorder 5
+#define DlgYBorder 5
+
+
+#define EntList 0
+#define EntComment 1
+#define EntCheck1 2
+#define EntCheck2 3
+#define EntCheck3 4
+#define EntCheck4 5
+#define EntCheck5 6
+#define EntCheck6 7
+#define EntCheck7 8
+#define EntCheck8 9
+#define EntCheck9 10
+#define EntCheck10 11
+#define EntCheck11 12
+#define EntCheck12 13
+#define EntProps 14
+#define EntDir0 15
+#define EntDir45 16
+#define EntDir90 17
+#define EntDir135 18
+#define EntDir180 19
+#define EntDir225 20
+#define EntDir270 21
+#define EntDir315 22
+#define EntDirUp 23
+#define EntDirDown 24
+#define EntDelProp 25
+#define EntKeyLabel 26
+#define EntKeyField 27
+#define EntValueLabel 28
+#define EntValueField 29
+#define EntColor 30
+#define EntAssignSounds 31
+#define EntAssignModels 32
+#define EntTab 33
+
+#define EntLast 34
+
+extern HWND hwndEnt[EntLast];
+
+extern int rgIds[EntLast];
+
diff --git a/q3radiant/EPAIRS.H b/q3radiant/EPAIRS.H
new file mode 100755
index 0000000..378cd31
--- /dev/null
+++ b/q3radiant/EPAIRS.H
@@ -0,0 +1,1402 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef EPAIRS_H_
+#define EPAIRS_H_
+
+typedef struct
+{
+ char *key;
+ char *value;
+} userEpair_t;
+
+userEpair_t eclassStr[] =
+{
+ //////////////////////////////
+ // Worldspawn
+ //////////////////////////////
+ {"classname", "worldspawn"},
+ {"color", "0 0 0"},
+ {"rem", "Only used for the world entity."},
+ {"rem", "cdtrack - number of CD track to play when level starts"},
+ {"rem", "fog_value - level of fog for this map"},
+
+ //////////////////////////////
+ // Light
+ //////////////////////////////
+ {"classname", "light"},
+ {"size", "-8 -8 -8 8 8 8"},
+ {"color", "0 1 0"},
+ {"flag", "START_OFF"},
+
+ {"rem", "style - number of style to use, 0-63"},
+ {"rem", "nelnosmama - string to define lightstyle"},
+
+ //////////////////////////////
+ // light_walltorch
+ //////////////////////////////
+ {"classname", "light_walltorch"},
+ {"size", "-8 -8 -8 8 8 8"},
+ {"color", "0 1 0"},
+ {"flag", "START_ON"},
+
+ {"rem", "style - number of style to use, 0-63"},
+ {"rem", "nelnosmama - string to define lightstyle"},
+
+ //////////////////////////////
+ // light_spot
+ //////////////////////////////
+ {"classname", "light_spot"},
+ {"size", "-8 -8 -8 8 8 8"},
+ {"color", "0 1 0"},
+ {"flag", "START_ON"},
+
+ {"rem", "Used to make a spotlight. If it is targeted at another entity,"},
+ {"rem", "the spotlight will point directly at it, otherwise it will point"},
+ {"rem", "in the direction of its 'angle' field"},
+ {"rem", ""},
+ {"rem", "style - number of style to use, 0-63"},
+ {"rem", "nelnosmama - string to define lightstyle"},
+
+ //////////////////////////////
+ // light_strobe
+ //////////////////////////////
+ {"classname", "light_strobe"},
+ {"size", "-8 -8 -8 8 8 8"},
+ {"color", "0 1 0"},
+
+ {"flag", "START_ON"},
+ {"rem", "style - number of style to use, 0-63"},
+ {"rem", "nelnosmama - string to define lightstyle"},
+
+ //////////////////////////////
+ // effect_fog
+ //////////////////////////////
+ {"classname", "effect_fog"},
+ {"color", "0 1 0"},
+ {"rem", "Duh, fog."},
+ {"rem", ""},
+
+ //////////////////////////////
+ // effect_snow
+ //////////////////////////////
+ {"classname", "effect_snow"},
+ {"color", "1 1 1"},
+ {"height", "10"},
+ {"rem", "Snow!"},
+ {"rem", "Do you realize the entire street value of this mountain?"},
+
+ //////////////////////////////
+ // effect_rain
+ //////////////////////////////
+ {"classname", "effect_rain"},
+ {"height", "10"},
+ {"color", "0 0.5 0.8"},
+ {"rem", "Rain!"},
+ {"rem", "Yellow rain?"},
+
+ //////////////////////////////
+ // func_door
+ //////////////////////////////
+ {"classname", "func_door"},
+ {"color", "0 0.5 0.8"},
+ {"health", "0"},
+ {"speed", "100"},
+ {"wait", "3"},
+ {"lip", "8"},
+ {"dmg", "2"},
+ {"angle", "0 0 0"},
+ {"message", "you suck"},
+ {"targetname", ""},
+ {"flag", "START_OPEN"},
+ {"flag", "REVERSE"},
+ {"flag", "DOOR_DONT_LINK"},
+ {"flag", "TOGGLE"},
+ {"flag", "AUTO_OPEN"},
+ {"flag", "USE_TO_CLOSE"},
+
+ {"rem", "Doors that touch are linked together to operate as one."},
+ {"rem", " "},
+ {"rem", "message - printed when the door is touched if it is a trigger door and it hasn't been fired yet"},
+ {"rem", "angle - determines the opening direction"},
+ {"rem", "targetname - if set, no touch field will be spawned and a remote button or trigger field activates the door."},
+ {"rem", "health - if set, door must be shot open"},
+ {"rem", "speed - movement speed (100 default)"},
+ {"rem", "wait - time to wait before returning (3 default, -1 = never return)"},
+ {"rem", "lip - amount of door visible remaining at end of move (8 default)"},
+ {"rem", "dmg - damage to inflict when blocked (2 default)"},
+ {"rem", "sound_opening - name of the sound to play during opening, ie. doors/creek.wav"},
+ {"rem", "sound_open_finish - name of the sound to play when opening completes, ie. doors/slam.wav"},
+ {"rem", "sound_closing - name of the sound to play when closing starts, ie. doors/creek.wav"},
+ {"rem", "sound_close_finish - name of the sound to play when closing completes, ie. doors/slam.wav"},
+ {"rem", " "},
+ {"rem", "Spawnflags:"},
+ {"rem", "TOGGLE causes the door to wait in both the start and end states for a"},
+ {"rem", "trigger event."},
+ {"rem", " "},
+ {"rem", "START_OPEN causes the door to move to its destination when spawned, and"},
+ {"rem", "operate in reverse. It is used to temporarily or permanently close off an"},
+ {"rem", "area when triggered (not usefull for touch or takedamage doors)."},
+ {"rem", "AUTO_OPEN will spawn a trigger field around the door that can open it without"},
+ {"rem", "its being used."},
+ {"rem", "DOOR_DONT_LINK will stop a door from being automatically linked to other doors"},
+ {"rem", "that it touches."},
+
+ //////////////////////////////
+ // func_plat
+ //////////////////////////////
+ {"classname", "func_plat"},
+ {"color", "0 0.5 0.8"},
+ {"flag", "PLAT_START_UP"},
+ {"flag", ""},
+ {"flag", ""},
+ {"flag", "PLAT_TOGGLE"},
+
+ {"rem", "Plats should be drawn in the up position to spawn correctly"},
+ {"rem", " "},
+ {"rem", "message - printed when the door is touched if it is a trigger door and it hasn't been fired yet"},
+ {"rem", "angle - determines the opening direction"},
+ {"rem", "targetname - if set, no touch field will be spawned and a remote button or trigger field activates the door."},
+ {"rem", "health - if set, door must be shot open"},
+ {"rem", "speed - movement speed (100 default)"},
+ {"rem", "wait - time to wait before returning (3 default, -1 = never return)"},
+ {"rem", "height - number of units to move the platform up from spawn position. If height is"},
+ {"rem", "not specified, then the movement distance is determined based on the vertical size of the platform."},
+ {"rem", "dmg - damage to inflict when blocked (2 default)"},
+ {"rem", "sound_up - name of the sound to play when going up, ie. doors/creek.wav"},
+ {"rem", "sound_top - name of the sound to play when plat hits top, ie. doors/slam.wav"},
+ {"rem", "sound_down - name of the sound to play when going down, ie. doors/creek.wav"},
+ {"rem", "sound_bottom - name of the sound to play when plat hits bottom, ie. doors/slam.wav"},
+ {"rem", " "},
+ {"rem", "Spawnflags:"},
+ {"rem", "PLAT_START_UP starts the platform in the up (drawn) position"},
+ {"rem", "(height added to drawn position)"},
+ {"rem", "TOGGLE causes the platform to wait in both the start and end states for a"},
+ {"rem", "trigger event."},
+
+ //////////////////////////////
+ // func_door_rotate
+ //////////////////////////////
+ {"classname", "func_door_rotate"},
+ {"distance", "90.0"},
+ {"color", "0 0.5 0.8"},
+ {"message", "they suck"},
+ {"flag", "START_OPEN"},
+ {"flag", "REVERSE"},
+ {"flag", "DOOR_DONT_LINK"},
+ {"flag", "TOGGLE"},
+ {"flag", "X_AXIS"},
+ {"flag", "Y_AXIS"},
+ {"flag", "AUTO_OPEN"},
+ {"flag", "USE_TO_CLOSE"},
+// {"flag", "X_AXIS"},
+// {"flag", "Y_AXIS"},
+
+ {"rem", "if two doors touch, they are assumed to be connected and operate as a unit."},
+ {"rem", " "},
+ {"rem", "TOGGLE causes the door to wait in both the start and end states for a"},
+ {"rem", "trigger event."},
+ {"rem", " "},
+ {"rem", "START_OPEN causes the door to move to its destination when spawned, and"},
+ {"rem", "operate in reverse. It is used to temporarily or permanently close off an"},
+ {"rem", "area when triggered (not usefull for touch or takedamage doors)."},
+ {"rem", " "},
+ {"rem", "Key doors are allways wait -1."},
+ {"rem", " "},
+ {"rem", "You need to have an origin brush as part of this entity. The center of"},
+ {"rem", "that brush will be"},
+ {"rem", "the point around which it is rotated. It will rotate around the Z axis by"},
+ {"rem", "default. You can"},
+ {"rem", "check either the X_AXIS or Y_AXIS box to change that."},
+ {"rem", " "},
+ {"rem", "'distance' is how many degrees the door will be rotated."},
+ {"rem", "'speed' determines how fast the door moves; default value is 100."},
+ {"rem", " "},
+ {"rem", "REVERSE will cause the door to rotate in the opposite direction."},
+ {"rem", " "},
+ {"rem", "'message' is printed when the door is touched if it is a trigger door and"},
+ {"rem", " it hasn't been fired yet."},
+ {"rem", "'targetname' if set, no touch field will be spawned and a remote button or"},
+ {"rem", " trigger field activates the door."},
+ {"rem", "'health' if set, door must be shot open"},
+ {"rem", "'wait' wait before returning (3 default, -1 = never return)"},
+ {"rem", "'dmg' damage to inflict when blocked (2 default)"},
+ {"rem", "sound_opening - name of the sound to play during opening, ie. doors/creek.wav"},
+ {"rem", "sound_open_finish - name of the sound to play when opening completes, ie. doors/slam.wav"},
+ {"rem", "sound_closing - name of the sound to play when closing starts, ie. doors/creek.wav"},
+ {"rem", "sound_close_finish - name of the sound to play when closing completes, ie. doors/slam.wav"},
+ {"rem", "AUTO_OPEN will spawn a trigger field around the door that can open it without"},
+ {"rem", "its being used."},
+ {"rem", "DOOR_DONT_LINK will stop a door from being automatically linked to other doors"},
+ {"rem", "that it touches."},
+
+ //////////////////////////////
+ // func_rotate
+ //////////////////////////////
+ {"classname", "func_rotate"},
+ {"color", "0.0 0.5 0.8"},
+ {"flag", "START_ON"},
+ {"flag", "REVERSE"},
+ {"flag", "X_AXIS"},
+ {"flag", "Y_AXIS"},
+
+ {"rem", "You need to have an origin brush as part of this entity."},
+ {"rem", "The center of that brush will be"},
+ {"rem", "the point around which it is rotated. It will rotate around the Z axis by"},
+ {"rem", "default. You can"},
+ {"rem", "check either the X_AXIS or Y_AXIS box to change that."},
+ {"rem", " "},
+ {"rem", "'speed' determines how fast it moves; default value is 100."},
+ {"rem", "'dmg' damage to inflict when blocked (2 default)"},
+ {"rem", " "},
+ {"rem", "REVERSE will cause the it to rotate in the opposite direction."},
+
+ //////////////////////////////
+ // trigger_multiple
+ //////////////////////////////
+ {"classname", "trigger_multiple"},
+ {"color", "0.5 0.5 0.5"},
+ {"health", "0"},
+ {"delay", "0"},
+ {"wait", "0.2"},
+ {"sound", ""},
+ {"targetname", ""},
+ {"target", ""},
+ {"killtarget", ""},
+ {"message", ""},
+ {"flag", "NOTOUCH"},
+
+ {"rem", "a repeatable trigger, targetted at the entity with the name"},
+ {"rem", "targetname."},
+ {"rem", ""},
+ {"rem", "health - if set the trigger must be killed to activate"},
+ {"rem", "delay - time to wait after activation before firing target"},
+ {"rem", "wait - time to wait between retriggering (default = 0.2 seconds)"},
+ {"rem", ""},
+ {"rem", "Spawnflags:"},
+ {"rem", "NOTOUCH - if set the trigger is only fired by other entities and"},
+ {"rem", "not by touching."},
+
+ //////////////////////////////
+ // trigger_console
+ //////////////////////////////
+ {"classname", "trigger_console"},
+ {"color", "0.5 0.5 0.5"},
+ {"wait", "0.2"},
+ {"command", ""},
+ {"rem", ""},
+ {"rem", "command - the command to send to the console when triggered"},
+
+ //////////////////////////////
+ // trigger_once
+ //////////////////////////////
+ {"classname", "trigger_once"},
+ {"color", "0.5 0.5 0.5"},
+ {"angle", "0 0 0"},
+ {"health", "0"},
+ {"delay", "0"},
+ {"sound", ""},
+ {"targetname", ""},
+ {"killtarget", ""},
+ {"message", ""},
+ {"flag", "NOTOUCH"},
+
+ {"rem", "triggers once, then removes itself"},
+ {"rem", " "},
+ {"rem", "health - if set the trigger must be killed to activate"},
+ {"rem", "delay - time to wait after activation before firing target"},
+ {"rem", "wait - time to wait between retriggering (default = 0.2 seconds)"},
+ {"rem", "sound - name of sound to play upon firing"},
+ {"rem", " "},
+ {"rem", "Spawnflags:"},
+ {"rem", "NOTOUCH - if set the trigger is only fired by other entities and"},
+ {"rem", "not by touching."},
+
+ //////////////////////////////
+ // trigger_relay
+ //////////////////////////////
+ {"classname", "trigger_relay"},
+ {"color", "0.5 0.5 0.5"},
+ {"delay", "0"},
+ {"sound", ""},
+ {"targetname", ""},
+ {"killtarget", ""},
+ {"message", ""},
+
+ {"rem", "sound - name of sound to play upon firing"},
+
+ //////////////////////////////
+ // trigger_teleport
+ //////////////////////////////
+ {"classname", "trigger_teleport"},
+ {"color", "0.5 0.5 0.5"},
+ {"sound", ""},
+ {"targetname", ""},
+ {"killtarget", ""},
+ {"message", ""},
+ {"flag", "PLAYER_ONLY"},
+ {"flag", "NO_FLASH"},
+ {"flag", "NO_ANGLE_ADJUST"},
+
+ {"rem", "sound - name of sound to play upon firing, if not specified, then no"},
+ {"rem", "sound will be played"},
+ {"rem", "fog_value - sets fog_value to this when a teleporter is used"},
+ {"rem", ""},
+ {"rem", "Spawnflags:"},
+ {"rem", "PLAYER_ONLY - will only teleport players (NOT bots)"},
+ {"rem", "NO_FLASH - no spawn fog will be generated when an object teleports"},
+ {"rem", "NO_ANGLE_ADJUST - the object's angle will not be adjusted when it is"},
+ {"rem", "teleported."},
+
+ //////////////////////////////
+ // info_teleport_destination
+ //////////////////////////////
+ {"classname", "info_teleport_destination"},
+ {"color", "0.5 0.5 0.5"},
+ {"size", "-8.0 -8.0 -8.0 8.0 8.0 8.0"},
+
+ //////////////////////////////
+ // trigger_warp
+ //////////////////////////////
+ {"classname", "trigger_warp"},
+ {"color", "0.5 0.5 0.5"},
+ {"sound", ""},
+ {"targetname", ""},
+ {"killtarget", ""},
+ {"message", ""},
+ {"flag", "PLAYER_ONLY"},
+ {"flag", "NO_FLASH"},
+ {"flag", "NO_ANGLE_ADJUST"},
+
+ {"rem", "sound - name of sound to play upon firing, if not specified, then no"},
+ {"rem", "sound will be played"},
+ {"rem", "fog_value - sets fog_value to this when a warp is used"},
+ {"rem", "speed - speed from this path point to the next"},
+ {"rem", ""},
+ {"rem", "Spawnflags:"},
+ {"rem", "PLAYER_ONLY - will only teleport players (NOT bots)"},
+ {"rem", "NO_FLASH - no spawn fog will be generated when an object teleports"},
+ {"rem", "NO_ANGLE_ADJUST - the object's angle will not be adjusted when it is"},
+ {"rem", "teleported."},
+
+ //////////////////////////////
+ // tele_cylinder
+ //////////////////////////////
+
+ {"classname", "warp_cylinder"},
+ {"color", "0.5 0.5 0.5"},
+ {"color", "1 0 1"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"rem", "Location player starts in deathmatch"},
+
+ //////////////////////////////
+ // info_warp_destination
+ //////////////////////////////
+ {"classname", "info_warp_destination"},
+ {"color", "0.5 0.5 0.5"},
+ {"size", "-8.0 -8.0 -8.0 8.0 8.0 8.0"},
+
+ {"rem", "target - next target to warp to"},
+ {"rem", "speed - speed from this path point to the next"},
+
+ //////////////////////////////
+ // trigger_onlyregistered
+ //////////////////////////////
+ {"classname", "trigger_onlyregistered"},
+ {"color", "0.5 0.5 0.5"},
+ {"sound", ""},
+ {"wait", "2.0"},
+ {"message", ""},
+
+ {"rem", "sound - name of sound to play upon firing"},
+ {"rem", "wait - the number of seconds between triggerings and"},
+ {"rem", "the length of time the message will be displayed"},
+
+ //////////////////////////////
+ // trigger_hurt
+ //////////////////////////////
+ {"classname", "trigger_hurt"},
+ {"color", "0.5 0.5 0.5"},
+ {"sound", ""},
+ {"dmg", "2.0"},
+ {"wait", "2.0"},
+ {"message", ""},
+
+ {"rem", "sound - name of sound to play upon firing"},
+ {"rem", "dmg - the amount of damage the trigger will do to an object"},
+ {"rem", "wait - the number of seconds between triggerings and"},
+
+ //////////////////////////////
+ // trigger_push
+ //////////////////////////////
+ {"classname", "trigger_push"},
+ {"color", "0.5 0.5 0.5"},
+ {"sound", ""},
+ {"message", ""},
+ {"speed", "1000.0"},
+ {"flag", "PUSH_ONCE"},
+ {"rem", "speed - the velocity to give the object"},
+ {"rem", "speed - the velocity to give the object"},
+
+ //////////////////////////////
+ // trigger_counter
+ //////////////////////////////
+ {"classname", "trigger_counter"},
+ {"color", "0.5 0.5 0.5"},
+ {"sound", ""},
+ {"flag", "NO_MESSAGE"},
+
+ {"rem", "sound - name of sound to play upon firing"},
+ {"rem", "message - message to display upon last triggering"},
+ {"rem", "when NO_MESSAGE is set, no messages are displayed upon triggering"},
+
+ //////////////////////////////
+ // trigger_changelevel
+ //////////////////////////////
+ {"classname", "trigger_changelevel"},
+ {"color", "0.5 0.5 0.5"},
+ {"sound", ""},
+ {"map", ""},
+ {"flag", "NO_INTERMISSION"},
+
+ {"rem", "sound - name of sound to play upon firing"},
+ {"rem", "message - message to display upon last triggering"},
+
+ //////////////////////////////
+ // func_wall
+ //////////////////////////////
+ {"classname", "func_wall"},
+ {"color", "0 0.5 0.8"},
+ {"health", "0"},
+ {"message", ""},
+ {"targetname", ""},
+ {"target", ""},
+ {"killtarget", ""},
+
+ {"rem", "targetname - the name of this wall if it is a target"},
+ {"rem", "target - the next entity to trigger when this one is triggered"},
+ {"rem", "killtarget - the targetname of the entity to remove when triggered"},
+
+ //////////////////////////////
+ // func_button
+ //////////////////////////////
+ {"classname", "func_button"},
+ {"color", "0 0.5 0.8"},
+ {"health", "0"},
+ {"targetname", ""},
+ {"target", ""},
+ {"killtarget", ""},
+ {"speed", ""},
+ {"wait", ""},
+ {"angle", ""},
+ {"lip", ""},
+ {"flag", "PUSH_TOUCH"},
+
+ {"rem", "targetname - the name of this wall if it is a target"},
+ {"rem", "target - the next entity to trigger when this one is triggered"},
+ {"rem", "killtarget - the targetname of the entity to remove when triggered"},
+ {"rem", "sound_use - the sound to play when the button is used (defaults to none)"},
+ {"rem", "sound_return - the sound to play when the button returns (defaults to none)"},
+ {"rem", "speed - rate of travel when button moves"},
+ {"rem", "wait - seconds to wait befor returning to useable (-1 = never return)"},
+ {"rem", "angle - direction of travel"},
+ {"rem", "lip - amount of button left sticking out after being pushed (default 4)"},
+ {"rem", "health - when > 0 the button must be killed in order to fire"},
+ {"rem", "PUSH_TOUCH will allow the button to be pushed by running into it, Quake style"},
+
+ //////////////////////////////
+ // func_multi_button
+ //////////////////////////////
+ {"classname", "func_multi_button"},
+ {"color", "0 0.5 0.8"},
+ {"health", "0"},
+ {"targetname", ""},
+ {"target", ""},
+ {"killtarget", ""},
+ {"speed", ""},
+ {"wait", ""},
+ {"angle", ""},
+ {"lip", ""},
+ {"flag", "PUSH_TOUCH"},
+ {"flag", "CYCLE"},
+
+ {"rem", "targetname - the name of this wall if it is a target"},
+ {"rem", "target - the next entity to trigger when this one is triggered"},
+ {"rem", "killtarget - the targetname of the entity to remove when triggered"},
+ {"rem", "sound_use - the sound to play when the button is used (defaults to none)"},
+ {"rem", "sound_return - the sound to play when the button returns (defaults to none)"},
+ {"rem", "speed - rate of travel when button moves"},
+ {"rem", "wait - seconds to wait befor returning to useable (-1 = never return)"},
+ {"rem", "angle - direction of travel"},
+ {"rem", "health - when > 0 the button must be killed in order to fire"},
+ {"rem", "distance - distance button travels on each push"},
+ {"rem", "count - number of positions this button has"},
+ {"rem", "PUSH_TOUCH will allow the button to be pushed by running into it, Quake style"},
+ {"rem", "CYCLE - button will not return to top from last position, but will go back through all positions"},
+
+ //////////////////////////////
+ // func_train
+ //////////////////////////////
+ {"classname", "func_train"},
+ {"distance", "90.0"},
+ {"color", "0 0.5 0.8"},
+ {"rem", "targetname - the name of this train"},
+ {"rem", "target - the path_corner that the train will spawn at"},
+ {"rem", "killtarget - the targetname of the entity to remove when triggered"},
+
+ //////////////////////////////
+ // func_train
+ //////////////////////////////
+ {"classname", "func_train2"},
+ {"distance", "90.0"},
+ {"color", "0 0.5 0.8"},
+ {"rem", "targetname - the name of this train"},
+ {"rem", "target - the path_corner that the train will spawn at"},
+ {"rem", "killtarget - the targetname of the entity to remove when triggered"},
+
+ //////////////////////////////
+ // path_corner_train
+ //////////////////////////////
+ {"classname", "path_corner_train"},
+ {"distance", "90.0"},
+ {"color", "0.5 0.3 0"},
+ {"size", "-8 -8 -8 8 8 8"},
+ {"flag", "X_AXIS"},
+ {"flag", "Y_AXIS"},
+ {"flag", "Z_AXIS"},
+ {"flag", "TRIGWAIT"},
+ {"rem", "killtarget - the targetname of the entity to remove when this"},
+ {"rem", "path_corner is reached"},
+ {"rem", "speed - rate of travel from this path_corner to the next"},
+ {"rem", "wait - seconds to wait after the actions on this path_corner are complete"},
+ {"rem", "sound - sound to play at this path corner"},
+ {"rem", "x_distance - distance in degrees to rotate around x axis"},
+ {"rem", "y_distance - distance in degrees to rotate around y axis"},
+ {"rem", "z_distance - distance in degrees to rotate around z axis"},
+ {"rem", "x_speed - speed to rotate along x axis in degrees per second"},
+ {"rem", "y_speed - speed to rotate along y axis in degrees per second"},
+ {"rem", "z_speed - speed to rotate along z axis in degrees per second"},
+ {"rem", "health - if health is set, the train will wait at this path corner"},
+ {"rem", "until it is killed."},
+ {"rem", "Spawnflags:"},
+ {"rem", "X_AXIS - when checked train will rotate continually around "},
+ {"rem", "x axis at x_speed degrees per second"},
+ {"rem", "Y_AXIS - when checked train will rotate continually around "},
+ {"rem", "y axis at y_speed degrees per second"},
+ {"rem", "Z_AXIS - when checked train will rotate continually around "},
+ {"rem", "z axis at z_speed degrees per second"},
+ {"rem", "TRIGWAIT - wait here until triggered"},
+
+ //////////////////////////////
+ // info_player_start
+ //////////////////////////////
+ {"classname", "info_player_start"},
+ {"color", "1 0 0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"rem", "Location player starts in single play."},
+
+ //////////////////////////////
+ // info_mikiko_start
+ //////////////////////////////
+ {"classname", "info_mikiko_start"},
+ {"color", "1 0 0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"rem", "Location Mikiko starts in single play."},
+
+ //////////////////////////////
+ // info_superfly_start
+ //////////////////////////////
+ {"classname", "info_superfly_start"},
+ {"color", "1 0 0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"rem", "Location Superfly starts in single play."},
+
+ //////////////////////////////
+ // info_null
+ //////////////////////////////
+ {"classname", "info_null"},
+ {"color", "1 0 0"},
+ {"size", "-8 -8 -8 8 8 8"},
+ {"rem", "You can point anything to this as a target"},
+
+ //////////////////////////////
+ // info_player_deathmatch
+ //////////////////////////////
+ {"classname", "info_player_deathmatch"},
+ {"color", "1 0 1"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"rem", "Location player starts in deathmatch"},
+
+ //////////////////////////////
+ // info_player_coop
+ //////////////////////////////
+ {"classname", "info_player_coop"},
+ {"color", "1 0 1"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"rem", "Location player starts in coop"},
+
+ //////////////////////////////
+ // func_door_secret
+ //////////////////////////////
+ {"classname", "func_door_secret"},
+ {"color", "0 0.5 0.8"},
+ {"health", "0"},
+ {"speed", "100"},
+ {"wait", "3"},
+ {"lip", "8"},
+ {"dmg", "2"},
+ {"angle", "0 0 0"},
+ {"message", "we all suck"},
+ {"targetname", ""},
+ {"flag", "OPEN_ONCE"},
+ {"flag", "1ST_LEFT"},
+ {"flag", "1ST_DOWN"},
+ {"flag", "NO_SHOOT"},
+ {"flag", "YES_SHOOT"},
+
+ {"rem", "message - printed when the door is touched if it is a trigger door and it hasn't been fired yet"},
+ {"rem", "angle - determines the opening direction"},
+ {"rem", "targetname - if set, no touch field will be spawned and a remote button or trigger field activates the door."},
+ {"rem", "health - if set, door must be shot open"},
+ {"rem", "speed - movement speed (100 default)"},
+ {"rem", "wait - time to wait before returning (3 default, -1 = never return)"},
+ {"rem", "dmg - damage to inflict when blocked (2 default)"},
+ {"rem", "sound_opening - name of the sound to play during opening, ie. doors/creek.wav"},
+ {"rem", "sound_open_finish - name of the sound to play when opening completes, ie. doors/slam.wav"},
+ {"rem", "sound_closing - name of the sound to play when closing starts, ie. doors/creek.wav"},
+ {"rem", "sound_close_finish - name of the sound to play when closing completes, ie. doors/slam.wav"},
+ {"rem", " "},
+ {"rem", "Spawnflags:"},
+ {"rem", "SECRET_OPEN_ONCE - door stays open (imagine that...)"},
+ {"rem", "SECRET_1ST_LEFT - first move is left of move direction"},
+ {"rem", "SECRET_1ST_DOWN - first move is down from move direction"},
+ {"rem", "SECRET_NO_SHOOT - only opened by a trigger"},
+ {"rem", "SECRET_YES_SHOOT - shootable even if targeted"},
+
+ //////////////////////////////
+ // func_wall_explode
+ //////////////////////////////
+ {"classname", "func_wall_explode"},
+ {"color", "0 0.5 0.8"},
+ {"health", "0"},
+ {"message", ""},
+ {"targetname", ""},
+ {"target", ""},
+ {"killtarget", ""},
+ {"model_1", ""},
+ {"model_2", ""},
+ {"model_3", ""},
+ {"flag", "ROCK_CHUNKS"},
+ {"flag", "WOOD_CHUNKS"},
+ {"flag", "EXTRA_CHUNKS"},
+ {"flag", "EXTRA_VELOCITY"},
+ {"flag", "NO_CHUNKS"},
+ {"flag", "NO_SOUND"},
+
+ {"rem", "targetname - the name of this wall if it is a target"},
+ {"rem", "target - the next entity to trigger when this one is triggered"},
+ {"rem", "killtarget - the targetname of the entity to remove when triggered"},
+ {"rem", "health - ummm... this would be the health of the wall, if it is 0 then"},
+ {"rem", "the wall can only be exploded by targetting it"},
+ {"rem", "message - this prints out when wall go boom"},
+ {"rem", "model_1 - the specific pathname of the first model to throw when killed"},
+ {"rem", "if model_1 is set then spawnflags ROCK_CHUNKS and WOOD_CHUNKS are overridden"},
+ {"rem", "model_2 - the pathname of the second model"},
+ {"rem", "model_3 - I wouldn't bet on it, but this is probably the name of the 3rd model"},
+ {"rem", " "},
+ {"rem", "Spawnflags:"},
+ {"rem", "ROCK_CHUNKS - makes rock chunk wall-gibs fly"},
+ {"rem", "WOOD_CHUNKS - makes wood chunk wall-gibs fly"},
+ {"rem", "EXTRA_CHUNKS - makes up to 3 chunks per explosion, instead of just one"},
+ {"rem", "EXTRA_VELOCITY - gives chunks a higher velocity (good for underwater)"},
+ {"rem", "NO_CHUNKS - um, no chunks"},
+ {"rem", "NO_SOUND - no sound, use when lots of func walls are activated simultaneously to keep the"},
+ {"rem", "Quake engine from choking with too many sounds at once."},
+
+ //////////////////////////////
+ // func_anim
+ //////////////////////////////
+ {"classname", "func_anim"},
+ {"color", "0.0 1.0 0.1"},
+ {"flag", "VISIBLE"},
+ {"rem", "Spawnflags:"},
+ {"rem", "VISIBLE - start visible"},
+
+ //////////////////////////////
+ // func_floater
+ //////////////////////////////
+ {"classname", "func_floater"},
+ {"color", "0 0.5 0.8"},
+ {"size", "-16 -16 -16 16 16 16"},
+ {"model", ""},
+
+ {"rem", "model - pathname to model (ie. models/floater.mdl)"},
+ {"rem", "velocity_cap - maximum up/down velocity"},
+ {"rem", "dissipate - how fast velocity degrades to velocity_cap (default = 0.99)"},
+ {"rem", "object_mass - mass of object (mass / volume = density)"},
+ {"rem", "object_volume - volume of object (mass / volume = density)"},
+
+ //////////////////////////////
+ // func_debris
+ //////////////////////////////
+
+ {"classname", "func_debris"},
+ {"color", "0 0.5 0.8"},
+ {"target", ""},
+ {"flag", "GO_TO_ACTIVATOR"},
+ {"flag", "NO_ROTATE"},
+ {"flag", "MOMENTUM_DAMAGE"},
+ {"flag", "NO_ROTATION_ADJUST"},
+ {"flag", "DROP_ONLY"},
+ {"flag", "QUARTER_SIZE"},
+
+ {"rem", "target - debris will fly towards targeted entity"},
+ {"rem", "fly_sound - sound to play while the entity flies through the air"},
+ {"rem", "hit_sound - sound to play when the entity hits something"},
+ {"rem", "damage - amount of damage to do when hitting another object"},
+ {"rem", "if MOMENTUM_DAMAGE is selected, then damage will be based on the"},
+ {"rem", "speed of the debris when it impacts the object and damage becomes"},
+ {"rem", "the divisor, so if speed at impact = 300 and damge = 3, then damage done"},
+ {"rem", "while 300 / 3 = 100 points. If damage is not set, then momentum damage"},
+ {"rem", "will be the default with a damage divisor of 3."},
+ {"rem", "Spawnflags:"},
+ {"rem", "GO_TO_ACTIVATOR - debris will fly at whoever activated it"},
+ {"rem", "NO_ROTATE - don't give this debris any random rotation"},
+ {"rem", "MOMENTUM_DAMAGE - damage based on velocity"},
+ {"rem", "DROP_ONLY - no upward velocity, debris just falls"},
+ {"rem", "QUARTER_SIZE - shrink bounding box by 1/4"},
+ {"rem", "Notes:"},
+ {"rem", "A func debris entity must have an origin brush contained in it,"},
+ {"rem", "otherwise it will rotate around the center of the level, not"},
+ {"rem", "its own center. That is bad."},
+
+ //////////////////////////////
+ // func_debris_visible
+ //////////////////////////////
+
+ {"classname", "func_debris_visible"},
+ {"color", "0 0.5 0.8"},
+ {"target", ""},
+ {"flag", "GO_TO_ACTIVATOR"},
+ {"flag", "NO_ROTATE"},
+ {"flag", "MOMENTUM_DAMAGE"},
+ {"flag", "NO_ROTATION_ADJUST"},
+ {"flag", "DROP_ONLY"},
+ {"flag", "QUARTER_SIZE"},
+
+ {"rem", "SAME AS FUNC_DEBRIS EXCEPT DEBRIS IS VISIBLE BEFORE TARGETTING"},
+ {"rem", "target - debris will fly towards targeted entity"},
+ {"rem", "fly_sound - sound to play while the entity flies through the air"},
+ {"rem", "hit_sound - sound to play when the entity hits something"},
+ {"rem", "damage - amount of damage to do when hitting another object"},
+ {"rem", "if MOMENTUM_DAMAGE is selected, then damage will be based on the"},
+ {"rem", "speed of the debris when it impacts the object and damage becomes"},
+ {"rem", "the divisor, so if speed at impact = 300 and damge = 3, then damage done"},
+ {"rem", "while 300 / 3 = 100 points. If damage is not set, then momentum damage"},
+ {"rem", "will be the default with a damage divisor of 3."},
+ {"rem", "Spawnflags:"},
+ {"rem", "GO_TO_ACTIVATOR - debris will fly at whoever activated it"},
+ {"rem", "NO_ROTATE - don't give this debris any random rotation"},
+ {"rem", "MOMENTUM_DAMAGE - damage based on velocity"},
+ {"rem", "DROP_ONLY - no upward velocity, debris just falls"},
+ {"rem", "QUARTER_SIZE - shrink bounding box by 1/4"},
+ {"rem", "Notes:"},
+ {"rem", "A func debris entity must have an origin brush contained in it,"},
+ {"rem", "otherwise it will rotate around the center of the level, not"},
+ {"rem", "its own center. That is bad."},
+
+ //////////////////////////////
+ // func_particlefield
+ //////////////////////////////
+ {"classname", "func_particlefield"},
+ {"color", "0 0.5 0.8"},
+ {"flag", "USE_COUNT"},
+ {"rem", "count - number of times to trigger before activated"},
+ {"rem", "color - color of particles use:"},
+ {"rem", "black, blue, green, cyan, red, "},
+ {"rem", "purple, brown, ltgray, dkgray, "},
+ {"rem", "ltblue, ltgreen, ltcyan, ltpurple,"},
+ {"rem", "yellow, white"},
+
+ //////////////////////////////
+ // func_monitor
+ //////////////////////////////
+ {"classname", "func_monitor"},
+ {"color", "0 0.5 0.8"},
+ {"rem", "target - the info_camera that the view will be from"},
+ {"rem", "fov - the field of view when looking through this camera"},
+
+ //////////////////////////////
+ // info_camera
+ //////////////////////////////
+ {"classname", "info_camera"},
+ {"color", "1 0 0"},
+ {"size", "-8 -8 -8 8 8 8"},
+
+ //////////////////////////////
+ // misc_lavaball_drop
+ //////////////////////////////
+ {"classname", "misc_lavaball_drop"},
+ {"size", "-8 -8 -8 8 8 8"},
+ {"color", "1.0 0.5 0.0"},
+
+ //////////////////////////////
+ // misc_lavaball_toss
+ //////////////////////////////
+ {"classname", "misc_lavaball_toss"},
+ {"size", "-8 -8 -8 8 8 8"},
+ {"color", "1.0 0.5 0.0"},
+
+ {"rem", "target = can be triggered"},
+ {"rem", "mintime = minimum time between tosses (default = 4.0 seconds)"},
+ {"rem", "maxtime = maximum time between tosses (default = 12.0 seconds)"},
+ {"rem", "damage = damage to do when an hitting something"},
+ {"rem", "upmin = minimum upward velocity (default = 200)"},
+ {"rem", "upmax = maximum upward velocity (default = 800)"},
+
+ //////////////////////////////
+ // sound_ambient
+ //////////////////////////////
+
+ {"classname", "sound_ambient"},
+ {"size", "-8 -8 -8 8 8 8"},
+ {"color", "1 0 1"},
+
+ {"rem", "sound - path to ambient sound (ie. ambience/sound.wav."},
+ {"rem", "fade - distance multiplier to make sounds fade in further away from source."},
+ {"rem", "1.0 is normal, 2.0 is twice as far."},
+ {"rem", "volume - 0 through 255. 255 is max."},
+
+ //////////////////////////////
+ // sound_ambient
+ //////////////////////////////
+
+ {"classname", "trigger_fog_value"},
+ {"color", "0 1 0"},
+
+ {"rem", "fog_value - the value for fog density 0 - 4. 0 is off, ie. r_drawfog 0"},
+
+ //////////////////////////////
+ // node_node
+ //////////////////////////////
+
+ {"classname", "node_node"},
+ {"color", "0.5 0.5 1"},
+ {"size", "-8 -8 -8 8 8 8"},
+ {"flag", "NODE_DOOR"},
+
+ {"rem", "number - the number of this node"},
+ {"rem", "link - the number of the node linked to (can be up to four link fields)"},
+
+ //////////////////////////////////////////////////////////////////////////////////////////////////////
+ //
+ // Monsters
+ //
+ //////////////////////////////////////////////////////////////////////////////////////////////////////
+
+ ////////////////////////////////////////
+ // Episode 1 monsters
+ ////////////////////////////////////////
+
+ {"classname", "monster_froginator"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A light and refreshing monster."},
+ {"rem", "One day I will read the spec and know what this"},
+ {"rem", "monster does."},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_crox"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A realistic representation of your mother"},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_slaughterskeet"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A big thing with a big beak."},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_thunderskeet"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A big thing with a big beak."},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_venomvermin"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A big thing with a big beak."},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_tentaclor"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A big thing with a big beak."},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_sludgeminion"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"flag", "PATHFOLLOW"},
+ {"rem", "A big thing with a big beak."},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_prisoner"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "gib him."},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "func_prisoner_respawn"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"rem", "time - seconds until a new prisoner is spawned"},
+
+ {"classname", "monster_inmater"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-32 -32 -24 32 32 64"},
+ {"flag", "WANDER"},
+ {"flag", "PATHFOLLOW"},
+ {"rem", "A big thing with a big beak."},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+ {"rem", "PATH_FOLLOW - begin following a monster path"},
+
+ {"classname", "monster_squid"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A big thing with a big beak."},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_trackattack"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"rem", "Track turrets need to have a target"},
+ {"rem", "which is the path_corner_track at which"},
+ {"rem", "they will start."},
+ {"rem", "Spawn about 16 units below the track to"},
+
+ {"classname", "monster_trackdaddy"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"rem", "Track turrets need to have a target"},
+ {"rem", "which is the path_corner_track at which"},
+ {"rem", "they will start."},
+
+ {"classname", "monster_lasergat"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"rem", "Track turrets need to have a target"},
+ {"rem", "which is the path_corner_track at which"},
+ {"rem", "they will start."},
+
+ {"classname", "monster_psyclaw"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A big dog without a head and a"},
+ {"rem", "brain for a back. Cool, eh?"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_labworker"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "Lab worker. Your momma."},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_battleboar"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A motorized, cybernetic pig, of course."},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ //////////////////////////////
+ // path_corner_track
+ //
+ // path corners for tracked turrets only!
+ //////////////////////////////
+
+ {"classname", "path_corner_track"},
+ {"distance", "90.0"},
+ {"color", "0.5 0.3 0"},
+ {"size", "-8 -8 -8 8 8 8"},
+
+ ////////////////////////////////////////
+ // Episode 2 monsters
+ ////////////////////////////////////////
+
+ {"classname", "monster_skeleton"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "Where's he at? Ahh! He's in me!"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_spider"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-32 -32 -24 32 32 32"},
+ {"flag", "WANDER"},
+ {"rem", "Dumbass."},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_tarantula"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "Dumbass."},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_griffon"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A big thing with a big beak."},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_harpy"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A big thing with a big beak."},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_centurion"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A big thing with a big beak."},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_siren"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A big thing with a big beak."},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_ferryman"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A big thing with a big beak."},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_satyr"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-32 -32 -24 32 32 64"},
+ {"flag", "WANDER"},
+ {"rem", "This thing will beat you down."},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_column"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-32 -32 -24 32 32 64"},
+ {"flag", "WANDER"},
+ {"rem", "Look at the tits on that statue!!"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ ////////////////////////////////////////
+ // Episode 3 monsters
+ ////////////////////////////////////////
+
+ {"classname", "monster_plague_rat"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"rem", "I broke you!"},
+ {"flag", "WANDER"},
+ {"rem", "I broke you!"},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_rotworm"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "I beat the dictionary out of your filthy mouth!"},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_buboid"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "Dumbass."},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_priest"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A big thing with a big beak."},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_doombat"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A big thing with a big beak."},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_lycanthir"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A big thing with a big beak."},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_fletcher"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A big thing with a big beak."},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_dwarf"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A big thing with a big beak."},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_dragonegg"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A big thing with a big beak."},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_babydragon"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A big thing with a big beak."},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ ////////////////////////////////////////
+ // Episode 4 monsters
+ ////////////////////////////////////////
+
+ {"classname", "monster_gang1"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "Less than half a fucking man."},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_gang2"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "You're fucking dumb! Suck it down."},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_blackprisoner"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A big thing with a big beak."},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_whiteprisoner"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A big thing with a big beak."},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_femgang"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A big thing with a big beak."},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_rocketdude"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A big thing with a big beak."},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_chaingang"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "A big thing with a big beak."},
+ {"rem", "radius - wander radius"},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monster_labmonkey"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 32"},
+ {"flag", "WANDER"},
+ {"rem", "Lab monkey. This thing will crack your skull."},
+ {"rem", "Spawnflags:"},
+ {"rem", "WANDER - monster will wander around"},
+
+ {"classname", "monkey_message"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-8 -8 -8 8 8 8"},
+ {"rem", "Target this from the monkey switch to display current monkey state."},
+
+ //////////////////////////////////////////////////////////////////
+ // monster AI markers
+ //////////////////////////////////////////////////////////////////
+
+ {"classname", "monster_path_corner"},
+ {"distance", "90.0"},
+ {"color", "0.5 0.3 0"},
+ {"size", "-8 -8 -8 8 8 8"},
+ {"rem", "A path corner for a monster to travel along"},
+ {"rem" "target1 - target4: "},
+ {"rem", "Can have up to 4 targets for the monster"},
+ {"rem", "to travel to. If there is more than one target"},
+ {"rem", "the monster will randomly choose the next target"},
+ {"rem", "from those available."},
+ {"rem", "action1 - action4: "},
+ {"rem", "Use the action field to make a monster perform a"},
+ {"rem", "specific action at the path corner. For example"},
+ {"rem", "'action scoop' will make a sludge minion scoop"},
+ {"rem", "sludge at that path corner (other monsters will"},
+ {"rem", "ignore the scoop command. You can have multiple"},
+ {"rem", "actions on a path corner, for instance:"},
+ {"rem", " action1 scoop"},
+ {"rem", " action2 interrogate"},
+ {"rem", "Sludge minions reaching this path corner will scoop"},
+ {"rem", "while Inmaters will search out nearest prisoner"},
+
+
+ //////////////////////////////////////////////////////////////////
+ // decorations
+ //////////////////////////////////////////////////////////////////
+
+ {"classname", "deco_e1"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 0"},
+ {"flag", "DECO_EXPLODE"},
+ {"flag", "DECO_NO_EXPLODE"},
+ {"flag", "DECO_PUSHABLE"},
+ {"rem", "model - choose model # -- see list."},
+
+ {"classname", "deco_e2"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 0"},
+ {"flag", "DECO_EXPLODE"},
+ {"flag", "DECO_NO_EXPLODE"},
+ {"flag", "DECO_PUSHABLE"},
+ {"rem", "model - choose model # -- see list."},
+
+ {"classname", "deco_e3"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 0"},
+ {"flag", "DECO_EXPLODE"},
+ {"flag", "DECO_NO_EXPLODE"},
+ {"flag", "DECO_PUSHABLE"},
+ {"rem", "model - choose model # -- see list."},
+
+ {"classname", "deco_e4"},
+ {"color", "1.0 0.0 0.0"},
+ {"size", "-16 -16 -24 16 16 0"},
+ {"flag", "DECO_EXPLODE"},
+ {"flag", "DECO_NO_EXPLODE"},
+ {"flag", "DECO_PUSHABLE"},
+ {"rem", "model - choose model # -- see list."},
+
+ {NULL, NULL},
+};
+
+#endif \ No newline at end of file
diff --git a/q3radiant/EditWnd.cpp b/q3radiant/EditWnd.cpp
new file mode 100755
index 0000000..e2dbd34
--- /dev/null
+++ b/q3radiant/EditWnd.cpp
@@ -0,0 +1,61 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// EditWnd.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "EditWnd.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CEditWnd
+IMPLEMENT_DYNCREATE(CEditWnd, CWnd);
+
+CEditWnd::CEditWnd()
+{
+}
+
+CEditWnd::~CEditWnd()
+{
+}
+
+
+BEGIN_MESSAGE_MAP(CEditWnd, CEdit)
+ //{{AFX_MSG_MAP(CEditWnd)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CEditWnd message handlers
+
+BOOL CEditWnd::PreCreateWindow(CREATESTRUCT& cs)
+{
+ cs.style = WS_CHILD | WS_VSCROLL | ES_AUTOHSCROLL | ES_MULTILINE | WS_VISIBLE;
+ cs.lpszClass = "EDIT";
+ return CEdit::PreCreateWindow(cs);
+}
diff --git a/q3radiant/EditWnd.h b/q3radiant/EditWnd.h
new file mode 100755
index 0000000..02f6532
--- /dev/null
+++ b/q3radiant/EditWnd.h
@@ -0,0 +1,71 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_EDITWND_H__279AAE22_78C5_11D1_B53C_00AA00A410FC__INCLUDED_)
+#define AFX_EDITWND_H__279AAE22_78C5_11D1_B53C_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// EditWnd.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CEditWnd window
+
+class CEditWnd : public CEdit
+{
+ DECLARE_DYNCREATE(CEditWnd);
+// Construction
+public:
+ CEditWnd();
+
+// Attributes
+public:
+
+// Operations
+public:
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CEditWnd)
+ protected:
+ virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
+ //}}AFX_VIRTUAL
+
+// Implementation
+public:
+ virtual ~CEditWnd();
+
+ // Generated message map functions
+protected:
+ //{{AFX_MSG(CEditWnd)
+ //}}AFX_MSG
+
+ DECLARE_MESSAGE_MAP()
+};
+
+/////////////////////////////////////////////////////////////////////////////
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_EDITWND_H__279AAE22_78C5_11D1_B53C_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/EntityListDlg.cpp b/q3radiant/EntityListDlg.cpp
new file mode 100755
index 0000000..a2c2e66
--- /dev/null
+++ b/q3radiant/EntityListDlg.cpp
@@ -0,0 +1,152 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// EntityListDlg.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "EntityListDlg.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CEntityListDlg dialog
+
+
+CEntityListDlg::CEntityListDlg(CWnd* pParent /*=NULL*/)
+ : CDialog(CEntityListDlg::IDD, pParent)
+{
+ //{{AFX_DATA_INIT(CEntityListDlg)
+ //}}AFX_DATA_INIT
+}
+
+
+void CEntityListDlg::DoDataExchange(CDataExchange* pDX)
+{
+ CDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CEntityListDlg)
+ DDX_Control(pDX, IDC_LIST_ENTITY, m_lstEntity);
+ DDX_Control(pDX, IDC_TREE_ENTITY, m_treeEntity);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CEntityListDlg, CDialog)
+ //{{AFX_MSG_MAP(CEntityListDlg)
+ ON_BN_CLICKED(IDSELECT, OnSelect)
+ ON_NOTIFY(TVN_SELCHANGED, IDC_TREE_ENTITY, OnSelchangedTreeEntity)
+ ON_NOTIFY(NM_DBLCLK, IDC_TREE_ENTITY, OnDblclkTreeEntity)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CEntityListDlg message handlers
+
+void CEntityListDlg::OnSelect()
+{
+ HTREEITEM hItem = m_treeEntity.GetSelectedItem();
+ if (hItem)
+ {
+ entity_t* pEntity = reinterpret_cast<entity_t*>(m_treeEntity.GetItemData(hItem));
+ if (pEntity)
+ {
+ Select_Deselect();
+ Select_Brush (pEntity->brushes.onext);
+ }
+ }
+ Sys_UpdateWindows(W_ALL);
+}
+
+BOOL CEntityListDlg::OnInitDialog()
+{
+ CDialog::OnInitDialog();
+
+ CMapStringToPtr mapEntity;
+
+ HTREEITEM hParent = m_treeEntity.InsertItem(world_entity->eclass->name);
+ HTREEITEM hChild = m_treeEntity.InsertItem(world_entity->eclass->name, hParent);
+ m_treeEntity.SetItemData(hChild, reinterpret_cast<DWORD>(world_entity));
+
+ for (entity_t* pEntity=entities.next ; pEntity != &entities ; pEntity=pEntity->next)
+ {
+ hParent = NULL;
+ if (mapEntity.Lookup(pEntity->eclass->name, reinterpret_cast<void*&>(hParent)) == FALSE)
+ {
+ hParent = m_treeEntity.InsertItem(pEntity->eclass->name);
+ mapEntity.SetAt(pEntity->eclass->name, reinterpret_cast<void*>(hParent));
+ }
+ hChild = m_treeEntity.InsertItem(pEntity->eclass->name, hParent);
+ m_treeEntity.SetItemData(hChild, reinterpret_cast<DWORD>(pEntity));
+ }
+
+ CRect rct;
+ m_lstEntity.GetClientRect(rct);
+ m_lstEntity.InsertColumn(0, "Key", LVCFMT_LEFT, rct.Width() / 2);
+ m_lstEntity.InsertColumn(1, "Value", LVCFMT_LEFT, rct.Width() / 2);
+ m_lstEntity.DeleteColumn(2);
+ UpdateData(FALSE);
+
+ return TRUE; // return TRUE unless you set the focus to a control
+ // EXCEPTION: OCX Property Pages should return FALSE
+}
+
+void CEntityListDlg::OnSelchangedTreeEntity(NMHDR* pNMHDR, LRESULT* pResult)
+{
+ NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
+ HTREEITEM hItem = m_treeEntity.GetSelectedItem();
+ m_lstEntity.DeleteAllItems();
+ if (hItem)
+ {
+ CString strList;
+ entity_t* pEntity = reinterpret_cast<entity_t*>(m_treeEntity.GetItemData(hItem));
+ if (pEntity)
+ {
+ for (epair_t* pEpair = pEntity->epairs ; pEpair ; pEpair = pEpair->next)
+ {
+ if (strlen(pEpair->key) > 8)
+ strList.Format("%s\t%s", pEpair->key, pEpair->value);
+ else
+ strList.Format("%s\t\t%s", pEpair->key, pEpair->value);
+ int nParent = m_lstEntity.InsertItem(0, pEpair->key);
+ m_lstEntity.SetItem(nParent, 1, LVIF_TEXT, pEpair->value, 0, 0, 0, reinterpret_cast<DWORD>(pEntity));
+
+ }
+ }
+ }
+ *pResult = 0;
+}
+
+void CEntityListDlg::OnDblclkListInfo()
+{
+ // TODO: Add your control notification handler code here
+
+}
+
+void CEntityListDlg::OnDblclkTreeEntity(NMHDR* pNMHDR, LRESULT* pResult)
+{
+ OnSelect();
+ *pResult = 0;
+}
diff --git a/q3radiant/EntityListDlg.h b/q3radiant/EntityListDlg.h
new file mode 100755
index 0000000..53c3534
--- /dev/null
+++ b/q3radiant/EntityListDlg.h
@@ -0,0 +1,72 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_ENTITYLISTDLG_H__C241B9A3_819F_11D1_B548_00AA00A410FC__INCLUDED_)
+#define AFX_ENTITYLISTDLG_H__C241B9A3_819F_11D1_B548_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// EntityListDlg.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CEntityListDlg dialog
+
+class CEntityListDlg : public CDialog
+{
+// Construction
+public:
+ CEntityListDlg(CWnd* pParent = NULL); // standard constructor
+
+// Dialog Data
+ //{{AFX_DATA(CEntityListDlg)
+ enum { IDD = IDD_DLG_ENTITYLIST };
+ CListCtrl m_lstEntity;
+ CTreeCtrl m_treeEntity;
+ //}}AFX_DATA
+
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CEntityListDlg)
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+
+ // Generated message map functions
+ //{{AFX_MSG(CEntityListDlg)
+ afx_msg void OnSelect();
+ virtual BOOL OnInitDialog();
+ afx_msg void OnSelchangedTreeEntity(NMHDR* pNMHDR, LRESULT* pResult);
+ afx_msg void OnDblclkListInfo();
+ afx_msg void OnDblclkTreeEntity(NMHDR* pNMHDR, LRESULT* pResult);
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_ENTITYLISTDLG_H__C241B9A3_819F_11D1_B548_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/EpairsWrapper.h b/q3radiant/EpairsWrapper.h
new file mode 100755
index 0000000..3de691f
--- /dev/null
+++ b/q3radiant/EpairsWrapper.h
@@ -0,0 +1,63 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//-----------------------------------------------------------------------------
+//
+// $LogFile$
+// $Revision: 1.1.1.4 $
+// $Author: ttimo $
+// $Date: 2000/01/18 00:17:10 $
+// $Log: EpairsWrapper.h,v $
+// Revision 1.1.1.4 2000/01/18 00:17:10 ttimo
+// merging in for RC
+//
+// Revision 1.3 2000/01/17 23:53:41 TBesset
+// ready for merge in sourceforge (RC candidate)
+//
+// Revision 1.1.1.3 1999/12/29 18:31:25 TBesset
+// Q3Radiant public version
+//
+// DESCRIPTION:
+// virtual class to allow plugin operations on entities epairs
+// this is the internal header for our implementation
+
+#ifndef _EPAIRSWRAPPER_H_
+#define _EPAIRSWRAPPER_H_
+
+class CEpairsWrapper : public IEpair
+{
+public:
+ int refCount;
+ entity_t *m_pEnt;
+ virtual void IncRef() { refCount++; }
+ virtual void DecRef() { refCount--; if (refCount <= 0) delete this; }
+ CEpairsWrapper() { refCount = 0; }
+ CEpairsWrapper( entity_t* ep ) { refCount = 0; m_pEnt = ep; }
+ virtual ~CEpairsWrapper() { }
+ virtual void GetVectorForKey( char* key, vec3_t vec );
+ virtual float FloatForKey( char *key );
+ virtual char* ValueForKey( char *key );
+ virtual void SetKeyValue( char *key, char *value );
+ virtual void GetEntityOrigin( vec3_t vec );
+ virtual void CalculateRotatedBounds( vec3_t mins, vec3_t maxs );
+};
+
+#endif \ No newline at end of file
diff --git a/q3radiant/FNMATCH.CPP b/q3radiant/FNMATCH.CPP
new file mode 100755
index 0000000..f7679d5
--- /dev/null
+++ b/q3radiant/FNMATCH.CPP
@@ -0,0 +1,87 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "stdafx.h"
+#include <stdlib.h>
+
+#define Reg1 register
+int match(char *mask, char *name)
+{
+ Reg1 unsigned char *m = (unsigned char *)mask, *n = (unsigned char *)name;
+ char *ma = mask, *na = name;
+ int wild = 0, q = 0;
+
+ while (1)
+ {
+ if (*m == '*')
+ {
+ while (*m == '*')
+ m++;
+ wild = 1;
+ ma = (char *)m;
+ na = (char *)n;
+ }
+
+ if (!*m)
+ {
+ if (!*n)
+ return 0;
+ for (m--; (m > (unsigned char *)mask) && (*m == '?'); m--)
+ ;
+ if ((*m == '*') && (m > (unsigned char *)mask) &&
+ (m[-1] != '\\'))
+ return 0;
+ if (!wild)
+ return 1;
+ m = (unsigned char *)ma;
+ n = (unsigned char *)++na;
+ }
+ else if (!*n)
+ {
+ while(*m == '*')
+ m++;
+ return (*m != 0);
+ }
+ if ((*m == '\\') && ((m[1] == '*') || (m[1] == '?')))
+ {
+ m++;
+ q = 1;
+ }
+ else
+ q = 0;
+
+ if ((tolower(*m) != tolower(*n)) && ((*m != '?') || q))
+ {
+ if (!wild)
+ return 1;
+ m = (unsigned char *)ma;
+ n = (unsigned char *)++na;
+ }
+ else
+ {
+ if (*m)
+ m++;
+ if (*n)
+ n++;
+ }
+ }
+}
+
diff --git a/q3radiant/FNMATCH.H b/q3radiant/FNMATCH.H
new file mode 100755
index 0000000..b194e2f
--- /dev/null
+++ b/q3radiant/FNMATCH.H
@@ -0,0 +1,27 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef _FNMATCH_H
+#define _FNMATCH_H
+
+int match(char *mask, char *name);
+
+#endif /* fnmatch.h */
diff --git a/q3radiant/FindTextureDlg.cpp b/q3radiant/FindTextureDlg.cpp
new file mode 100755
index 0000000..030abde
--- /dev/null
+++ b/q3radiant/FindTextureDlg.cpp
@@ -0,0 +1,175 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// FindTextureDlg.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "FindTextureDlg.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CFindTextureDlg dialog
+
+CFindTextureDlg g_TexFindDlg;
+CFindTextureDlg& g_dlgFind = g_TexFindDlg;
+static bool g_bFindActive = true;
+
+void CFindTextureDlg::updateTextures(const char *p)
+{
+ if (isOpen())
+ {
+ if (g_bFindActive)
+ {
+ setFindStr(p);
+ }
+ else
+ {
+ setReplaceStr(p);
+ }
+ }
+}
+
+CFindTextureDlg::CFindTextureDlg(CWnd* pParent /*=NULL*/)
+ : CDialog(CFindTextureDlg::IDD, pParent)
+{
+ //{{AFX_DATA_INIT(CFindTextureDlg)
+ m_bSelectedOnly = FALSE;
+ m_strFind = _T("");
+ m_strReplace = _T("");
+ m_bForce = FALSE;
+ m_bLive = TRUE;
+ //}}AFX_DATA_INIT
+}
+
+
+void CFindTextureDlg::DoDataExchange(CDataExchange* pDX)
+{
+ CDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CFindTextureDlg)
+ DDX_Check(pDX, IDC_CHECK_SELECTED, m_bSelectedOnly);
+ DDX_Text(pDX, IDC_EDIT_FIND, m_strFind);
+ DDX_Text(pDX, IDC_EDIT_REPLACE, m_strReplace);
+ DDX_Check(pDX, IDC_CHECK_FORCE, m_bForce);
+ DDX_Check(pDX, IDC_CHECK_LIVE, m_bLive);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CFindTextureDlg, CDialog)
+ //{{AFX_MSG_MAP(CFindTextureDlg)
+ ON_BN_CLICKED(ID_BTN_APPLY, OnBtnApply)
+ ON_EN_SETFOCUS(IDC_EDIT_FIND, OnSetfocusEditFind)
+ ON_EN_SETFOCUS(IDC_EDIT_REPLACE, OnSetfocusEditReplace)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+void CFindTextureDlg::OnBtnApply()
+{
+ UpdateData(TRUE);
+ CRect rct;
+ GetWindowRect(rct);
+ SaveRegistryInfo("Radiant::TextureFindWindow", &rct, sizeof(rct));
+ FindReplaceTextures(m_strFind, m_strReplace, m_bSelectedOnly, m_bForce);
+}
+
+void CFindTextureDlg::OnOK()
+{
+ UpdateData(TRUE);
+ CRect rct;
+ GetWindowRect(rct);
+ SaveRegistryInfo("Radiant::TextureFindWindow", &rct, sizeof(rct));
+ FindReplaceTextures(m_strFind, m_strReplace, m_bSelectedOnly, m_bForce);
+ CDialog::OnOK();
+}
+
+void CFindTextureDlg::show()
+{
+ if (g_dlgFind.GetSafeHwnd() == NULL || IsWindow(g_dlgFind.GetSafeHwnd()) == FALSE)
+ {
+ g_dlgFind.Create(IDD_DIALOG_FINDREPLACE);
+ g_dlgFind.ShowWindow(SW_SHOW);
+ }
+ else
+ {
+ g_dlgFind.ShowWindow(SW_SHOW);
+ }
+ CRect rct;
+ LONG lSize = sizeof(rct);
+ if (LoadRegistryInfo("Radiant::TextureFindWindow", &rct, &lSize))
+ g_dlgFind.SetWindowPos(NULL, rct.left, rct.top, 0,0, SWP_NOSIZE | SWP_SHOWWINDOW);
+}
+
+
+bool CFindTextureDlg::isOpen()
+{
+ return (g_dlgFind.GetSafeHwnd() == NULL || ::IsWindowVisible(g_dlgFind.GetSafeHwnd()) == FALSE) ? false : true;
+}
+
+void CFindTextureDlg::setFindStr(const char * p)
+{
+ g_dlgFind.UpdateData(TRUE);
+ if (g_dlgFind.m_bLive)
+ {
+ g_dlgFind.m_strFind = p;
+ g_dlgFind.UpdateData(FALSE);
+ }
+}
+
+void CFindTextureDlg::setReplaceStr(const char * p)
+{
+ g_dlgFind.UpdateData(TRUE);
+ if (g_dlgFind.m_bLive)
+ {
+ g_dlgFind.m_strReplace = p;
+ g_dlgFind.UpdateData(FALSE);
+ }
+}
+
+
+void CFindTextureDlg::OnCancel()
+{
+ CRect rct;
+ GetWindowRect(rct);
+ SaveRegistryInfo("Radiant::TextureFindWindow", &rct, sizeof(rct));
+ CDialog::OnCancel();
+}
+
+BOOL CFindTextureDlg::DestroyWindow()
+{
+ return CDialog::DestroyWindow();
+}
+
+void CFindTextureDlg::OnSetfocusEditFind()
+{
+ g_bFindActive = true;
+}
+
+void CFindTextureDlg::OnSetfocusEditReplace()
+{
+ g_bFindActive = false;
+}
diff --git a/q3radiant/FindTextureDlg.h b/q3radiant/FindTextureDlg.h
new file mode 100755
index 0000000..c69c95d
--- /dev/null
+++ b/q3radiant/FindTextureDlg.h
@@ -0,0 +1,83 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_FINDTEXTUREDLG_H__34B75D32_9F3A_11D1_B570_00AA00A410FC__INCLUDED_)
+#define AFX_FINDTEXTUREDLG_H__34B75D32_9F3A_11D1_B570_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// FindTextureDlg.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CFindTextureDlg dialog
+
+class CFindTextureDlg : public CDialog
+{
+// Construction
+public:
+ static void setReplaceStr(const char* p);
+ static void setFindStr(const char* p);
+ static bool isOpen();
+ static void show();
+ static void updateTextures(const char* p);
+ CFindTextureDlg(CWnd* pParent = NULL); // standard constructor
+
+// Dialog Data
+ //{{AFX_DATA(CFindTextureDlg)
+ enum { IDD = IDD_DIALOG_FINDREPLACE };
+ BOOL m_bSelectedOnly;
+ CString m_strFind;
+ CString m_strReplace;
+ BOOL m_bForce;
+ BOOL m_bLive;
+ //}}AFX_DATA
+
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CFindTextureDlg)
+ public:
+ virtual BOOL DestroyWindow();
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+
+ // Generated message map functions
+ //{{AFX_MSG(CFindTextureDlg)
+ afx_msg void OnBtnApply();
+ virtual void OnOK();
+ virtual void OnCancel();
+ afx_msg void OnSetfocusEditFind();
+ afx_msg void OnSetfocusEditReplace();
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_FINDTEXTUREDLG_H__34B75D32_9F3A_11D1_B570_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/GLINGR.H b/q3radiant/GLINGR.H
new file mode 100755
index 0000000..5ce0294
--- /dev/null
+++ b/q3radiant/GLINGR.H
@@ -0,0 +1,97 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// This .h file contains constants, typedefs, etc. for Intergraph
+// extensions to OpenGL. These extensions are:
+//
+// Multiple Palette Extension
+// Texture Object Extension
+
+#define GL_INGR_multiple_palette 1
+#define GL_EXT_texture_object 1
+
+
+// New constants and typedefs for the Multiple Palette Extension
+#define GL_PALETTE_INGR 0x80c0
+#define GL_MAX_PALETTES_INGR 0x80c1
+#define GL_MAX_PALETTE_ENTRIES_INGR 0x80c2
+#define GL_CURRENT_PALETTE_INGR 0x80c3
+#define GL_PALETTE_WRITEMASK_INGR 0x80c4
+#define GL_CURRENT_RASTER_PALETTE_INGR 0x80c5
+#define GL_PALETTE_CLEAR_VALUE_INGR 0x80c6
+
+// Function prototypes for the Multiple Palette Extension routines
+typedef void (APIENTRY *PALETTEFUNCPTR)(GLuint);
+typedef void (APIENTRY *PALETTEMASKFUNCPTR)(GLboolean);
+typedef void (APIENTRY *WGLLOADPALETTEFUNCPTR)(GLuint, GLsizei, GLuint *);
+typedef void (APIENTRY *CLEARPALETTEFUNCPTR)(GLuint);
+
+
+// New Constants and typedefs for the Texture Object Extension
+#define GL_TEXTURE_PRIORITY_EXT 0x8066
+#define GL_TEXTURE_RESIDENT_EXT 0x8067
+#define GL_TEXTURE_1D_BINDING_EXT 0x8068
+#define GL_TEXTURE_2D_BINDING_EXT 0x8069
+
+// Function prototypes for the Texture Object Extension routines
+typedef GLboolean (APIENTRY *ARETEXRESFUNCPTR)(GLsizei, const GLuint *,
+ const GLboolean *);
+typedef void (APIENTRY *BINDTEXFUNCPTR)(GLenum, GLuint);
+typedef void (APIENTRY *DELTEXFUNCPTR)(GLsizei, const GLuint *);
+typedef void (APIENTRY *GENTEXFUNCPTR)(GLsizei, GLuint *);
+typedef GLboolean (APIENTRY *ISTEXFUNCPTR)(GLuint);
+typedef void (APIENTRY *PRIORTEXFUNCPTR)(GLsizei, const GLuint *,
+ const GLclampf *);
+
+
+/* OpenGL ExtEscape escape function constants */
+#ifndef OPENGL_GETINFO
+#define OPENGL_GETINFO 4353 /* for OpenGL ExtEscape */
+#endif
+
+// OPENGL_GETINFO ExtEscape sub-escape numbers. They are defined by
+// Microsoft.
+
+#ifndef OPENGL_GETINFO_DRVNAME
+
+#define OPENGL_GETINFO_DRVNAME 0
+
+
+// Input structure for OPENGL_GETINFO ExtEscape.
+
+typedef struct _OPENGLGETINFO
+{
+ ULONG ulSubEsc;
+} OPENGLGETINFO, *POPENGLGETINFO;
+
+
+// Output structure for OPENGL_GETINFO_DRVNAME ExtEscape.
+
+typedef struct _GLDRVNAMERET
+{
+ ULONG ulVersion; // must be 1 for this version
+ ULONG ulDriverVersion; // driver specific version number
+ WCHAR awch[MAX_PATH+1];
+} GLDRVNAMERET, *PGLDRVNAMERET;
+
+#endif
+
+
diff --git a/q3radiant/GLInterface.cpp b/q3radiant/GLInterface.cpp
new file mode 100755
index 0000000..71c6ff3
--- /dev/null
+++ b/q3radiant/GLInterface.cpp
@@ -0,0 +1,93 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//-----------------------------------------------------------------------------
+//
+// $LogFile$
+// $Revision: 1.1.1.4.2.1 $
+// $Author: ttimo $
+// $Date: 2000/02/04 22:59:34 $
+// $log$
+// Revision 1.1.1.3 1999/12/29 18:31:26 TBesset
+// Q3Radiant public version
+//
+// Revision 1.2 1999/11/22 17:46:45 Timo & Christine
+// merged EARadiant into the main tree
+// bug fixes for Q3Plugin / EAPlugin
+// export for Robert
+//
+// Revision 1.1.4.1 1999/11/03 20:37:59 Timo & Christine
+// MEAN plugin for Q3Radiant, alpha version
+//
+// Revision 1.1.2.1 1999/10/27 08:34:26 Timo & Christine
+// preview version of the texture tools plugin is ready
+// ( TexTool.dll plugin is in Q3Plugin module )
+// plugins can draw in their own window using Radiant's qgl bindings
+//
+//
+// DESCRIPTION:
+// Quick interface hack for selected face interface
+// this one really needs more work, but I'm in a hurry with TexTool
+
+#include "stdafx.h"
+
+// stores objects that want to be hooked into drawing in the XY window
+//++timo TODO: add support for camera view, Z view ... (texture view?)
+CPtrArray l_GLWindows;
+
+int WINAPI QERApp_ISelectedFace_GetTextureNumber()
+{
+ if (g_ptrSelectedFaces.GetSize() > 0)
+ {
+ face_t *selFace = reinterpret_cast<face_t*>(g_ptrSelectedFaces.GetAt(0));
+ return selFace->d_texture->texture_number;
+ }
+ //++timo hu ? find the appropriate gl bind number
+ return 0;
+}
+
+void WINAPI QERApp_HookXYGLWindow(IGLWindow* pGLW)
+{
+ l_GLWindows.Add( pGLW );
+ pGLW->IncRef();
+}
+
+void WINAPI QERApp_UnHookGLWindow(IGLWindow* pGLW)
+{
+ for( int i = 0; i < l_GLWindows.GetSize(); i++ )
+ {
+ if (l_GLWindows.GetAt(i) == pGLW)
+ {
+ l_GLWindows.RemoveAt(i);
+ pGLW->DecRef();
+ return;
+ }
+ }
+#ifdef _DEBUG
+ Sys_Printf("ERROR: IGLWindow* not found in QERApp_UnHookGLWindow\n");
+#endif
+}
+
+void DrawPluginEntities( VIEWTYPE vt )
+{
+ for(int i = 0; i<l_GLWindows.GetSize(); i++ )
+ static_cast<IGLWindow*>(l_GLWindows.GetAt(i))->Draw( vt );
+} \ No newline at end of file
diff --git a/q3radiant/GLW_WIN.H b/q3radiant/GLW_WIN.H
new file mode 100755
index 0000000..d8b1c89
--- /dev/null
+++ b/q3radiant/GLW_WIN.H
@@ -0,0 +1,49 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef _WIN32
+# error You should not be including this file on this platform
+#endif
+
+#ifndef __GLW_WIN_H__
+#define __GLW_WIN_H__
+
+typedef struct
+{
+ HINSTANCE hInstance;
+ void *wndproc;
+
+ HDC hDC; // handle to device context
+ HWND hWnd; // handle to window
+ HGLRC hGLRC; // handle to GL rendering context
+
+ HINSTANCE hinstOpenGL; // HINSTANCE for the OpenGL library
+
+ qboolean minidriver;
+ qboolean allowdisplaydepthchange;
+ qboolean mcd_accelerated;
+
+ FILE *log_fp;
+} glwstate_t;
+
+extern glwstate_t glw_state;
+
+#endif
diff --git a/q3radiant/GroupBar.cpp b/q3radiant/GroupBar.cpp
new file mode 100755
index 0000000..09d01c6
--- /dev/null
+++ b/q3radiant/GroupBar.cpp
@@ -0,0 +1,84 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// GroupBar.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "GroupBar.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CGroupBar dialog
+
+
+CGroupBar::CGroupBar(CWnd* pParent /*=NULL*/)
+ : CDialogBar()
+{
+ //{{AFX_DATA_INIT(CGroupBar)
+ // NOTE: the ClassWizard will add member initialization here
+ //}}AFX_DATA_INIT
+}
+
+
+void CGroupBar::DoDataExchange(CDataExchange* pDX)
+{
+ CDialogBar::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CGroupBar)
+ DDX_Control(pDX, IDC_COMBO_GROUPS, m_wndGroupList);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CGroupBar, CDialogBar)
+ //{{AFX_MSG_MAP(CGroupBar)
+ ON_BN_CLICKED(IDC_BTN_ADDGROUP, OnBtnAddgroup)
+ ON_BN_CLICKED(IDC_BTN_LISTGROUPS, OnBtnListgroups)
+ ON_BN_CLICKED(IDC_BTN_REMOVEGROUP, OnBtnRemovegroup)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CGroupBar message handlers
+
+void CGroupBar::OnBtnAddgroup()
+{
+ // TODO: Add your control notification handler code here
+
+}
+
+void CGroupBar::OnBtnListgroups()
+{
+ // TODO: Add your control notification handler code here
+
+}
+
+void CGroupBar::OnBtnRemovegroup()
+{
+ // TODO: Add your control notification handler code here
+
+}
diff --git a/q3radiant/GroupBar.h b/q3radiant/GroupBar.h
new file mode 100755
index 0000000..8db20f8
--- /dev/null
+++ b/q3radiant/GroupBar.h
@@ -0,0 +1,69 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_GROUPBAR_H__926379A9_F46B_4E81_AD23_71BDDF55BDB3__INCLUDED_)
+#define AFX_GROUPBAR_H__926379A9_F46B_4E81_AD23_71BDDF55BDB3__INCLUDED_
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+// GroupBar.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CGroupBar dialog
+
+class CGroupBar : public CDialogBar
+{
+// Construction
+public:
+ CGroupBar(CWnd* pParent = NULL); // standard constructor
+
+// Dialog Data
+ //{{AFX_DATA(CGroupBar)
+ enum { IDD = IDD_GROUPBAR };
+ CComboBox m_wndGroupList;
+ //}}AFX_DATA
+
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CGroupBar)
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+
+ // Generated message map functions
+ //{{AFX_MSG(CGroupBar)
+ afx_msg void OnBtnAddgroup();
+ afx_msg void OnBtnListgroups();
+ afx_msg void OnBtnRemovegroup();
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_GROUPBAR_H__926379A9_F46B_4E81_AD23_71BDDF55BDB3__INCLUDED_)
diff --git a/q3radiant/GroupDlg.cpp b/q3radiant/GroupDlg.cpp
new file mode 100755
index 0000000..f0d4826
--- /dev/null
+++ b/q3radiant/GroupDlg.cpp
@@ -0,0 +1,655 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// GroupDlg.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "GroupDlg.h"
+#include "NameDlg.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+#define IMG_PATCH 0
+#define IMG_BRUSH 1
+#define IMG_GROUP 2
+#define IMG_ENTITY 3
+#define IMG_ENTITYGROUP 4
+#define IMG_MODEL 5
+#define IMG_SCRIPT 6
+
+// misc group support
+#define MAX_GROUPS 4096
+#define GROUP_DELIMETER '@'
+#define GROUPNAME "QER_Group_%i"
+
+CGroupDlg g_wndGroup;
+CGroupDlg *g_pGroupDlg = &g_wndGroup;
+
+// group_t are loaded / saved through "group_info" entities
+// they hold epairs for group settings and additionnal access info (tree nodes)
+group_t *g_pGroups = NULL;
+
+void Group_Add(entity_t *e)
+{
+ group_t *g = (group_t*)qmalloc(sizeof(group_t));
+ g->epairs = e->epairs;
+ g->next = NULL;
+ e->epairs = NULL;
+ // create a new group node
+ HTREEITEM hItem = g_wndGroup.m_wndTree.GetSelectedItem();
+ TVINSERTSTRUCT tvInsert;
+ memset(&tvInsert, 0, sizeof(TVINSERTSTRUCT));
+ tvInsert.item.iImage = IMG_GROUP;
+ tvInsert.item.iSelectedImage = tvInsert.item.iImage;
+ //++timo wasat?
+ // tvInsert.hParent = (hItem) ? hItem : m_hWorld;
+ tvInsert.hParent = g_wndGroup.m_hWorld;
+ tvInsert.hInsertAfter = NULL;
+ tvInsert.item.mask = TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE;
+ char *pipo = ValueForKey(e->epairs, "group");
+ tvInsert.item.pszText = _T(ValueForKey(g->epairs, "group"));
+ g->itemOwner = g_wndGroup.m_wndTree.InsertItem(&tvInsert);
+ g->next = g_pGroups;
+ g_pGroups = g;
+}
+
+group_t* Group_Alloc(char *name)
+{
+ group_t *g = (group_t*)qmalloc(sizeof(group_t));
+ SetKeyValue( g->epairs, "group", name );
+ return g;
+}
+
+group_t* Group_ForName(const char * name)
+{
+ group_t *g = g_pGroups;
+ while (g != NULL)
+ {
+ if (strcmp( ValueForKey(g->epairs,"group"), name ) == 0)
+ break;
+ g = g->next;
+ }
+ return g;
+}
+
+void Group_AddToItem(brush_t *b, HTREEITEM item)
+{
+ char cBuff[1024];
+ int nImage = IMG_BRUSH;
+ if (!g_qeglobals.m_bBrushPrimitMode)
+ {
+ return;
+ }
+ const char *pName = NULL;
+ const char *pNamed = Brush_GetKeyValue(b, "name");
+
+ if (!b->owner || (b->owner == world_entity))
+ {
+ if (b->patchBrush)
+ {
+ pName = "Generic Patch";
+ nImage = IMG_PATCH;
+ }
+ else
+ {
+ pName = "Generic Brush";
+ nImage = IMG_BRUSH;
+ }
+ }
+ else
+ {
+ pName = b->owner->eclass->name;
+ if (b->owner->eclass->fixedsize)
+ {
+ nImage = IMG_ENTITY;
+ }
+ else
+ {
+ nImage = IMG_ENTITYGROUP;
+ }
+ }
+
+ strcpy(cBuff, pName);
+
+ TVINSERTSTRUCT tvInsert;
+ memset(&tvInsert, 0, sizeof(TVINSERTSTRUCT));
+ tvInsert.item.iImage = (b->patchBrush) ? IMG_PATCH : IMG_BRUSH;
+ tvInsert.item.iSelectedImage = tvInsert.item.iImage;
+ tvInsert.hParent = item;
+ tvInsert.hInsertAfter = NULL;
+ tvInsert.item.mask = TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE;
+ tvInsert.item.pszText = cBuff;
+ HTREEITEM itemNew = g_pGroupDlg->m_wndTree.InsertItem(&tvInsert);
+ g_pGroupDlg->m_wndTree.SetItemData(itemNew, reinterpret_cast<DWORD>(b));
+ b->itemOwner = itemNew;
+ g_pGroupDlg->m_wndTree.RedrawWindow();
+
+}
+
+void Group_RemoveBrush(brush_t *b)
+{
+ if (!g_qeglobals.m_bBrushPrimitMode)
+ {
+ return;
+ }
+ if (b->itemOwner)
+ {
+ g_pGroupDlg->m_wndTree.DeleteItem(b->itemOwner);
+ b->itemOwner = NULL;
+ g_pGroupDlg->m_wndTree.RedrawWindow();
+ }
+ DeleteKey(b->epairs, "group");
+}
+
+void Group_AddToWorld(brush_t *b)
+{
+ if (!g_qeglobals.m_bBrushPrimitMode)
+ {
+ return;
+ }
+ HTREEITEM itemParent = g_pGroupDlg->m_wndTree.GetRootItem();
+ Group_AddToItem(b, itemParent);
+}
+
+void Group_AddToProperGroup(brush_t *b)
+{
+ if (!g_qeglobals.m_bBrushPrimitMode)
+ {
+ return;
+ }
+ // NOTE: we do a local copy of the "group" key because it gets erased by Group_RemoveBrush
+ const char *pGroup = Brush_GetKeyValue(b, "group");
+ // remove the entry in the tree if there's one
+ if (b->itemOwner)
+ {
+ g_pGroupDlg->m_wndTree.DeleteItem(b->itemOwner);
+ b->itemOwner = NULL;
+ g_pGroupDlg->m_wndTree.RedrawWindow();
+ }
+
+ if (*pGroup != 0)
+ {
+ // find the item
+ group_t *g = Group_ForName(pGroup);
+ if (g)
+ Group_AddToItem(b, g->itemOwner);
+#ifdef _DEBUG
+ else
+ Sys_Printf("WARNING: unexpected Group_ForName not found in Group_AddToProperGroup\n");
+#endif
+ }
+ else
+ {
+ Group_AddToWorld(b);
+ }
+}
+
+void Group_AddToSelected(brush_t *b)
+{
+ if (!g_qeglobals.m_bBrushPrimitMode)
+ {
+ return;
+ }
+ HTREEITEM hItem = g_pGroupDlg->m_wndTree.GetSelectedItem();
+ if (hItem == NULL)
+ {
+ hItem = g_pGroupDlg->m_wndTree.GetRootItem();
+ }
+ Group_AddToItem(b, hItem);
+}
+
+void Group_Save(FILE *f)
+{
+ group_t *g = g_pGroups;
+ while (g)
+ {
+ fprintf(f,"{\n\"classname\" \"group_info\"\n\"group\" \"%s\"\n}\n", ValueForKey( g->epairs, "group" ));
+ g = g->next;
+ }
+}
+
+void Group_Init()
+{
+ if (!g_qeglobals.m_bBrushPrimitMode)
+ {
+ return;
+ }
+ // start by cleaning everything
+ // clean the groups
+ //++timo FIXME: we leak, delete the groups on the way (I don't have time to do it now)
+#ifdef _DEBUG
+ Sys_Printf("TODO: fix leak in Group_Init\n");
+#endif
+ group_t *g = g_pGroups;
+ while (g)
+ {
+ epair_t *ep,*enext;
+ for (ep = g->epairs ; ep ; ep=enext )
+ {
+ enext = ep->next;
+ free (ep->key);
+ free (ep->value);
+ free (ep);
+ }
+ g = g->next;
+ }
+ g_pGroups = NULL;
+ g_wndGroup.m_wndTree.DeleteAllItems();
+ TVINSERTSTRUCT tvInsert;
+ memset(&tvInsert, 0, sizeof(TVINSERTSTRUCT));
+ tvInsert.hParent = NULL;
+ tvInsert.hInsertAfter = NULL;
+ tvInsert.item.mask = TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE;
+ tvInsert.item.pszText = _T("World");
+ tvInsert.item.iImage = IMG_GROUP;
+ tvInsert.item.iSelectedImage = IMG_GROUP;
+ HTREEITEM hWorld = g_wndGroup.m_wndTree.InsertItem(&tvInsert);
+ // walk through all the brushes, remove the itemOwner key and add them back where they belong
+ brush_t *b;
+ for (b = active_brushes.next; b != &active_brushes; b = b->next)
+ {
+ b->itemOwner = NULL;
+ Group_AddToProperGroup(b);
+ }
+ for (b = selected_brushes.next ; b != &selected_brushes ; b = b->next)
+ {
+ b->itemOwner = NULL;
+ Group_AddToProperGroup(b);
+ }
+}
+
+// scan through world_entity for groups in this map?
+// we use GROUPNAME "QER_group_%i" to look for existing groups and their naming
+//++timo FIXME: is this actually needed for anything?
+void Group_GetListFromWorld(CStringArray *pArray)
+{
+ if (!g_qeglobals.m_bBrushPrimitMode)
+ {
+ return;
+ }
+
+ if (world_entity == NULL)
+ {
+ return;
+ }
+
+ pArray->RemoveAll();
+ char cBuff[1024];
+ for (int i =0; i < MAX_GROUPS; i++)
+ {
+ sprintf(cBuff, GROUPNAME, i);
+ char *pGroup = ValueForKey(world_entity, cBuff);
+ if (pGroup && strlen(pGroup) > 0)
+ {
+ pArray->Add(pGroup);
+ }
+ else
+ {
+ break;
+ }
+ }
+}
+
+void Group_RemoveListFromWorld()
+{
+ if (!g_qeglobals.m_bBrushPrimitMode)
+ {
+ return;
+ }
+ CStringArray array;
+ Group_GetListFromWorld(&array);
+ int nCount = array.GetSize();
+ for (int i = 0; i < nCount; i++)
+ {
+ DeleteKey(world_entity, array.GetAt(i));
+ }
+}
+
+/*
+void Group_SetListToWorld(CStringArray *pArray)
+{
+ if (!g_qeglobals.m_bBrushPrimitMode)
+ {
+ return;
+ }
+ char cBuff[1024];
+ Group_RemoveListFromWorld();
+ int nCount = pArray->GetSize();
+ for (int i = 0; i < nCount; i++)
+ {
+ sprintf(cBuff, GROUPNAME, i);
+ SetKeyValue(world_entity, cBuff, pArray->GetAt(i));
+ }
+}
+*/
+
+int CountChar(const char *p, char c)
+{
+ int nCount = 0;
+ int nLen = strlen(p)-1;
+ while (nLen-- >= 0)
+ {
+ if (p[nLen] == c)
+ {
+ nCount++;
+ }
+ }
+ return nCount;
+}
+
+/*
+// this is not very efficient but should get the job done
+// as our trees should never be too big
+void Group_BuildTree(CTreeCtrl *pTree)
+{
+ if (!g_qeglobals.m_bBrushPrimitMode)
+ {
+ return;
+ }
+ CStringArray array;
+ int i;
+ CString strTemp;
+ CString strRight;
+
+ //++timo WARNING: this is very dangerous! delete all tree items, without checking the brushes
+ pTree->DeleteAllItems();
+ TVINSERTSTRUCT tvInsert;
+ memset(&tvInsert, 0, sizeof(TVINSERTSTRUCT));
+ tvInsert.hParent = NULL;
+ tvInsert.hInsertAfter = NULL;
+ tvInsert.item.mask = TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE;
+ tvInsert.item.pszText = _T("World");
+ tvInsert.item.iImage = IMG_GROUP;
+ tvInsert.item.iSelectedImage = IMG_GROUP;
+ HTREEITEM hWorld = pTree->InsertItem(&tvInsert);
+
+ Group_GetListFromWorld(&array);
+
+ // groups use @ to delimit levels, the number of @ signs
+ // start with ROOT item
+ // nothing is a peer with world, it is ancestor to everything
+ // expects things in order so first entry should be a 2nd level item
+ HTREEITEM itemParent = pTree->GetRootItem();
+ HTREEITEM itemLast = itemParent;
+ int nCount = array.GetSize();
+ int nLastLevel = 1;
+ for (i = 0; i < nCount; i++)
+ {
+ strTemp = array.GetAt(i);
+ int nLevel = CountChar(strTemp, GROUP_DELIMETER);
+ if (nLevel < nLastLevel)
+ {
+ int nLevelsUp = nLastLevel - nLevel;
+ while (nLevelsUp-- > 0)
+ {
+ itemParent = pTree->GetParentItem(itemParent);
+ }
+ }
+ else if (nLevel > nLastLevel)
+ {
+ itemParent = itemLast;
+ }
+ nLastLevel = nLevel;
+ char *pLast = strrchr(strTemp, GROUP_DELIMETER);
+ pLast++;
+ itemLast = pTree->InsertItem(pLast, itemParent);
+ }
+}
+*/
+
+void DecomposeSiblingList(const char *p, CStringArray *pArray, CTreeCtrl *pTree, HTREEITEM itemChild)
+{
+ CString str = p;
+ str += GROUP_DELIMETER;
+ while (itemChild)
+ {
+ CString strAdd = str;
+ strAdd += pTree->GetItemText(itemChild);
+ // do not want to add brushes or things, just groups
+ if (pTree->GetItemData(itemChild) == 0)
+ {
+ pArray->Add(strAdd);
+ }
+ if (pTree->ItemHasChildren(itemChild))
+ {
+ HTREEITEM itemOffspring = pTree->GetChildItem(itemChild);
+ DecomposeSiblingList(strAdd, pArray, pTree, itemOffspring);
+ }
+ itemChild = pTree->GetNextSiblingItem(itemChild);
+ }
+}
+
+/*
+void Group_DecomposeTree(CTreeCtrl *pTree)
+{
+ if (!g_qeglobals.m_bBrushPrimitMode)
+ {
+ return;
+ }
+ CStringArray array;
+ HTREEITEM itemParent = pTree->GetRootItem();
+ if (pTree->ItemHasChildren(itemParent))
+ {
+ HTREEITEM itemChild = pTree->GetChildItem(itemParent);
+ DecomposeSiblingList(pTree->GetItemText(itemParent), &array, pTree, itemChild);
+ }
+ Group_SetListToWorld(&array);
+}
+*/
+
+/////////////////////////////////////////////////////////////////////////////
+// CGroupDlg dialog
+
+
+CGroupDlg::CGroupDlg(CWnd* pParent /*=NULL*/)
+ : CDialog(CGroupDlg::IDD, pParent)
+{
+ //{{AFX_DATA_INIT(CGroupDlg)
+ // NOTE: the ClassWizard will add member initialization here
+ //}}AFX_DATA_INIT
+}
+
+
+void CGroupDlg::DoDataExchange(CDataExchange* pDX)
+{
+ CDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CGroupDlg)
+ DDX_Control(pDX, IDC_TREE_GROUP, m_wndTree);
+ DDX_Control(pDX, IDC_BTN_EDIT, m_wndEdit);
+ DDX_Control(pDX, IDC_BTN_DEL, m_wndDel);
+ DDX_Control(pDX, IDC_BTN_ADD, m_wndAdd);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CGroupDlg, CDialog)
+ //{{AFX_MSG_MAP(CGroupDlg)
+ ON_WM_SIZE()
+ ON_BN_CLICKED(IDC_BTN_ADD, OnBtnAdd)
+ ON_BN_CLICKED(IDC_BTN_DEL, OnBtnDel)
+ ON_BN_CLICKED(IDC_BTN_EDIT, OnBtnEdit)
+ ON_NOTIFY(NM_RCLICK, IDC_TREE_GROUP, OnRclickTreeGroup)
+ ON_NOTIFY(TVN_ENDLABELEDIT, IDC_TREE_GROUP, OnEndlabeleditTreeGroup)
+ ON_NOTIFY(NM_CLICK, IDC_TREE_GROUP, OnClickTreeGroup)
+ ON_NOTIFY(TVN_SETDISPINFO, IDC_TREE_GROUP, OnSetdispinfoTreeGroup)
+ ON_NOTIFY(TVN_BEGINDRAG, IDC_TREE_GROUP, OnBegindragTreeGroup)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CGroupDlg message handlers
+
+void CGroupDlg::OnSize(UINT nType, int cx, int cy)
+{
+ CDialog::OnSize(nType, cx, cy);
+ CRect rct;
+ GetClientRect(rct);
+
+ if ( m_wndAdd.GetSafeHwnd())
+ {
+ //all borders at 4, spacing at 6
+ CRect rctButton;
+ m_wndAdd.GetWindowRect(rctButton);
+ int nWidth = rctButton.Width();
+ int nHeight = rctButton.Height();
+
+ int nTop = rct.Height() - nHeight - 4;
+
+ m_wndAdd.SetWindowPos(NULL, 4, nTop, 0, 0, SWP_NOSIZE);
+ m_wndEdit.SetWindowPos(NULL, 8 + nWidth , nTop, 0, 0, SWP_NOSIZE);
+ m_wndDel.SetWindowPos(NULL, 12 + (nWidth * 2), nTop, 0, 0, SWP_NOSIZE);
+ rct.bottom = nTop;
+ m_wndTree.SetWindowPos(NULL, rct.left + 4, rct.top + 4, rct.Width() - 8, rct.Height() - 8, SWP_SHOWWINDOW);
+ }
+}
+
+BOOL CGroupDlg::OnInitDialog()
+{
+ CDialog::OnInitDialog();
+ m_imgList.Create(IDB_BITMAP_GROUPS, 16, 0, ILC_COLOR);
+ m_wndTree.SetImageList(&m_imgList, TVSIL_NORMAL);
+ InitGroups();
+ return TRUE; // return TRUE unless you set the focus to a control
+ // EXCEPTION: OCX Property Pages should return FALSE
+}
+
+void CGroupDlg::InitGroups()
+{
+ Group_Init();
+}
+
+// add a new group, put all selected brushes into the group
+void CGroupDlg::OnBtnAdd()
+{
+ CNameDlg dlg("New Group", this);
+ if (dlg.DoModal() == IDOK)
+ {
+ // create a new group node
+ HTREEITEM hItem = m_wndTree.GetSelectedItem();
+ TVINSERTSTRUCT tvInsert;
+ memset(&tvInsert, 0, sizeof(TVINSERTSTRUCT));
+ tvInsert.item.iImage = IMG_GROUP;
+ tvInsert.item.iSelectedImage = tvInsert.item.iImage;
+ //++timo wasat?
+ // tvInsert.hParent = (hItem) ? hItem : m_hWorld;
+ tvInsert.hParent = m_hWorld;
+ tvInsert.hInsertAfter = NULL;
+ tvInsert.item.mask = TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE;
+ tvInsert.item.pszText = _T(dlg.m_strName.GetBuffer(0));
+ // create a new group
+ group_t *g = Group_Alloc( dlg.m_strName.GetBuffer(0) );
+ g->itemOwner = m_wndTree.InsertItem(&tvInsert);
+ g->next = g_pGroups;
+ g_pGroups = g;
+ // now add the selected brushes
+ // NOTE: it would be much faster to give the group_t for adding
+ // but Select_AddToGroup is the standard way for all other cases
+ Select_AddToGroup( dlg.m_strName.GetBuffer(0) );
+ }
+}
+
+void CGroupDlg::OnBtnDel()
+{
+}
+
+void CGroupDlg::OnBtnEdit()
+{
+}
+
+BOOL CGroupDlg::OnChildNotify(UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pLResult)
+{
+ return CDialog::OnChildNotify(message, wParam, lParam, pLResult);
+}
+
+BOOL CGroupDlg::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult)
+{
+ return CDialog::OnNotify(wParam, lParam, pResult);
+}
+
+void CGroupDlg::OnRclickTreeGroup(NMHDR* pNMHDR, LRESULT* pResult)
+{
+ // TODO: Add your control notification handler code here
+
+ *pResult = 0;
+}
+
+void CGroupDlg::OnEndlabeleditTreeGroup(NMHDR* pNMHDR, LRESULT* pResult)
+{
+ TV_DISPINFO* pTVDispInfo = (TV_DISPINFO*)pNMHDR;
+ const char *pText = pTVDispInfo->item.pszText;
+ if (pText && strlen(pText) > 0)
+ {
+ HTREEITEM item = pTVDispInfo->item.hItem;
+ if (m_wndTree.GetRootItem() != item)
+ {
+ m_wndTree.SetItemText(item, pText);
+ if (pTVDispInfo->item.iImage != IMG_GROUP)
+ {
+ // if it is an entity
+ }
+ }
+ else
+ {
+ Sys_Printf("Cannot rename the world\n");
+ }
+ }
+ m_wndTree.RedrawWindow();
+ *pResult = 0;
+}
+
+void CGroupDlg::OnClickTreeGroup(NMHDR* pNMHDR, LRESULT* pResult)
+{
+ // TODO: Add your control notification handler code here
+
+ *pResult = 0;
+}
+
+void CGroupDlg::OnSetdispinfoTreeGroup(NMHDR* pNMHDR, LRESULT* pResult)
+{
+ TV_DISPINFO* pTVDispInfo = (TV_DISPINFO*)pNMHDR;
+ // TODO: Add your control notification handler code here
+
+ *pResult = 0;
+}
+
+void CGroupDlg::OnCancel()
+{
+ TreeView_EndEditLabelNow(m_wndTree.GetSafeHwnd(), TRUE);
+}
+
+void CGroupDlg::OnOK()
+{
+ TreeView_EndEditLabelNow(m_wndTree.GetSafeHwnd(), FALSE);
+}
+
+void CGroupDlg::OnBegindragTreeGroup(NMHDR* pNMHDR, LRESULT* pResult)
+{
+ NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
+ // TODO: Add your control notification handler code here
+
+ *pResult = 0;
+}
diff --git a/q3radiant/GroupDlg.h b/q3radiant/GroupDlg.h
new file mode 100755
index 0000000..55672a0
--- /dev/null
+++ b/q3radiant/GroupDlg.h
@@ -0,0 +1,90 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_GROUPDLG_H__92368487_9E05_454E_A66F_23A9A94A753B__INCLUDED_)
+#define AFX_GROUPDLG_H__92368487_9E05_454E_A66F_23A9A94A753B__INCLUDED_
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+// GroupDlg.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CGroupDlg dialog
+
+class CGroupDlg : public CDialog
+{
+ CImageList m_imgList;
+// Construction
+public:
+ virtual void OnOK();
+ virtual void OnCancel();
+ void InitGroups();
+ CGroupDlg(CWnd* pParent = NULL); // standard constructor
+
+ HTREEITEM m_hWorld;
+
+// Dialog Data
+ //{{AFX_DATA(CGroupDlg)
+ enum { IDD = IDD_DLG_GROUP };
+ CTreeCtrl m_wndTree;
+ CButton m_wndEdit;
+ CButton m_wndDel;
+ CButton m_wndAdd;
+ //}}AFX_DATA
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CGroupDlg)
+ public:
+ virtual BOOL OnChildNotify(UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pLResult);
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ virtual BOOL OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult);
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+
+ // Generated message map functions
+ //{{AFX_MSG(CGroupDlg)
+ afx_msg void OnSize(UINT nType, int cx, int cy);
+ virtual BOOL OnInitDialog();
+ afx_msg void OnBtnAdd();
+ afx_msg void OnBtnDel();
+ afx_msg void OnBtnEdit();
+ afx_msg void OnRclickTreeGroup(NMHDR* pNMHDR, LRESULT* pResult);
+ afx_msg void OnEndlabeleditTreeGroup(NMHDR* pNMHDR, LRESULT* pResult);
+ afx_msg void OnClickTreeGroup(NMHDR* pNMHDR, LRESULT* pResult);
+ afx_msg void OnSetdispinfoTreeGroup(NMHDR* pNMHDR, LRESULT* pResult);
+ afx_msg void OnBegindragTreeGroup(NMHDR* pNMHDR, LRESULT* pResult);
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
+
+extern CGroupDlg *g_pGroupDlg;
+
+
+#endif // !defined(AFX_GROUPDLG_H__92368487_9E05_454E_A66F_23A9A94A753B__INCLUDED_)
diff --git a/q3radiant/IBSPFrontend.h b/q3radiant/IBSPFrontend.h
new file mode 100755
index 0000000..7aa4e01
--- /dev/null
+++ b/q3radiant/IBSPFrontend.h
@@ -0,0 +1,101 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//-----------------------------------------------------------------------------
+//
+// $LogFile$
+// $Revision: 1.3 $
+// $Author: ttimo $
+// $Date: 2000/01/18 00:43:59 $
+// $Log: IBSPFrontend.h,v $
+// Revision 1.3 2000/01/18 00:43:59 ttimo
+// RC
+//
+// Revision 1.2 2000/01/13 00:46:41 ttimo
+// Merged in patches in / out
+//
+// Revision 1.1.1.1.2.1 2000/01/13 00:15:41 ttimo
+// beta of patches in / out - tested with GenSurf
+//
+// Revision 1.1.1.1 2000/01/07 17:17:27 ttimo
+// initial import of Q3Radiant module
+//
+// Revision 1.2 2000/01/07 16:40:09 TBesset
+// merged from BSP frontend
+//
+// Revision 1.1.2.4 2000/01/07 00:16:26 TBesset
+// frontend ready for public version
+//
+// Revision 1.1.2.3 2000/01/04 00:26:58 TBesset
+// added a LoadPointFile in BSP frontend
+//
+// Revision 1.1.2.2 1999/12/31 19:43:20 TBesset
+// no message
+//
+// Revision 1.1.2.1 1999/12/29 16:49:39 TBesset
+// adding IBSPFrontend to the repository
+//
+//
+// DESCRIPTION:
+// interface for BSP frontends plugins
+//
+
+// DONE: - change BSP menu to Q3Build menu ?
+// DONE: - detect when Q3Build dies ?
+// DELAYED: - hotkeys !
+// SUCCESS: - try again getting feedback from Q3Build
+
+#ifndef __IBSPFRONTEND_H_
+#define __IBSPFRONTEND_H_
+
+// define a GUID for this interface so plugins can access and reference it
+// {8ED6A480-BA5E-11d3-A3E3-0004AC96D4C3}
+static const GUID QERPlugBSPFrontendTable_GUID =
+{ 0x8ed6a480, 0xba5e, 0x11d3, { 0xa3, 0xe3, 0x0, 0x4, 0xac, 0x96, 0xd4, 0xc3 } };
+
+// ask the plugin about the items to show up in the BSP menu
+typedef char * (WINAPI* PFN_GETBSPMENU) ();
+// dispatch a BSP menu command
+typedef void (WINAPI* PFN_DISPATCHBSPCOMMAND) (char *);
+
+struct _QERPlugBSPFrontendTable
+{
+ int m_nSize;
+ PFN_GETBSPMENU m_pfnGetBSPMenu;
+ PFN_DISPATCHBSPCOMMAND m_pfnDispatchBSPCommand;
+};
+
+// interface provided by Radiant to the plugin
+// {A2CCF366-BA60-11d3-A3E3-0004AC96D4C3}
+static const GUID QERAppBSPFrontendTable_GUID =
+{ 0xa2ccf366, 0xba60, 0x11d3, { 0xa3, 0xe3, 0x0, 0x4, 0xac, 0x96, 0xd4, 0xc3 } };
+
+typedef char * (WINAPI* PFN_GETMAPNAME) ();
+typedef void (WINAPI* PFN_LOADPOINTFILE) ();
+
+struct _QERAppBSPFrontendTable
+{
+ int m_nSize;
+ PFN_GETMAPNAME m_pfnGetMapName;
+ PFN_LOADPOINTFILE m_pfnLoadPointFile;
+};
+
+#endif \ No newline at end of file
diff --git a/q3radiant/ICON1.ICO b/q3radiant/ICON1.ICO
new file mode 100755
index 0000000..d24956b
--- /dev/null
+++ b/q3radiant/ICON1.ICO
Binary files differ
diff --git a/q3radiant/IEpairs.cpp b/q3radiant/IEpairs.cpp
new file mode 100755
index 0000000..626e8cd
--- /dev/null
+++ b/q3radiant/IEpairs.cpp
@@ -0,0 +1,185 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//-----------------------------------------------------------------------------
+//
+// $LogFile$
+// $Revision: 1.1.1.4 $
+// $Author: ttimo $
+// $Date: 2000/01/18 00:17:12 $
+// $Log: IEpairs.cpp,v $
+// Revision 1.1.1.4 2000/01/18 00:17:12 ttimo
+// merging in for RC
+//
+// Revision 1.3 2000/01/17 23:53:41 TBesset
+// ready for merge in sourceforge (RC candidate)
+//
+// Revision 1.2 2000/01/07 16:40:10 TBesset
+// merged from BSP frontend
+// Revision 1.1.1.3 1999/12/29 18:31:26 TBesset
+// Q3Radiant public version
+//
+//
+// Revision 1.2 1999/11/22 17:46:45 Timo & Christine
+// merged EARadiant into the main tree
+// bug fixes for Q3Plugin / EAPlugin
+// export for Robert
+//
+// Revision 1.1.2.1 1999/11/03 20:37:59 Timo & Christine
+// MEAN plugin for Q3Radiant, alpha version
+//
+//
+// DESCRIPTION:
+// virtual class to allow plugin operations on entities epairs
+//
+
+#include "stdafx.h"
+
+void CEpairsWrapper::GetVectorForKey( char* key, vec3_t vec )
+{
+ ::GetVectorForKey( m_pEnt, key, vec );
+}
+
+float CEpairsWrapper::FloatForKey( char *key )
+{
+ return ::FloatForKey( m_pEnt, key );
+}
+
+char* CEpairsWrapper::ValueForKey( char *key )
+{
+ return ::ValueForKey( m_pEnt, key );
+}
+
+void CEpairsWrapper::SetKeyValue( char *key, char *value )
+{
+ ::SetKeyValue( m_pEnt, key, value );
+}
+
+void CEpairsWrapper::GetEntityOrigin( vec3_t vec )
+{
+ VectorCopy( m_pEnt->origin, vec );
+}
+
+// taken from Ritual's version of Q3Radiant ( Entity_CalculateRotatedBounds )
+void CEpairsWrapper::CalculateRotatedBounds( vec3_t mins, vec3_t maxs )
+{
+ entity_t *ent = m_pEnt;
+ int i;
+ float angle;
+ vec3_t angles;
+ vec3_t forward,right,up;
+ vec3_t rotmins, rotmaxs;
+ float trans[3][3];
+ qboolean changed;
+ char tempangles[ 128 ];
+
+ memset( angles, 0, sizeof(vec3_t) );
+ ::GetVectorForKey (ent, "angles", angles);
+
+ changed = false;
+ while ( angles[0] < 0 )
+ {
+ changed = true;
+ angles[0] += 360;
+ }
+ while ( angles[0] > 359 )
+ {
+ changed = true;
+ angles[0] -= 360;
+ }
+ while ( angles[1] < 0 )
+ {
+ changed = true;
+ angles[1] += 360;
+ }
+ while ( angles[1] > 359 )
+ {
+ changed = true;
+ angles[1] -= 360;
+ }
+ while ( angles[2] < 0 )
+ {
+ changed = true;
+ angles[2] += 360;
+ }
+ while ( angles[2] > 359 )
+ {
+ changed = true;
+ angles[2] -= 360;
+ }
+
+ if ( changed )
+ {
+ sprintf( tempangles, "%d %d %d", (int)angles[0], (int)angles[1], (int)angles[2] );
+ ::SetKeyValue ( ent, "angles", tempangles );
+ }
+
+
+ angle = ::FloatForKey (ent, "angle");
+ if ( fabs(angle) > 2 )
+ {
+ angles[1] = angle;
+ }
+ else if (angle == -1)
+ {
+ angles[0] = -90;
+ }
+ else if (angle == -2)
+ {
+ angles[0] = 90;
+ }
+ ::AngleVectors( angles, forward, right, up );
+ for (i=0 ; i<3 ; i++)
+ {
+ trans[i][0] = forward[i];
+ trans[i][1] = -right[i];
+ trans[i][2] = up[i];
+ }
+ ClearBounds( rotmins, rotmaxs );
+ for ( i = 0; i < 8; i++ )
+ {
+ int j;
+ vec3_t tmp, rottemp;
+
+ if ( i & 1 )
+ tmp[0] = mins[0];
+ else
+ tmp[0] = maxs[0];
+
+ if ( i & 2 )
+ tmp[1] = mins[1];
+ else
+ tmp[1] = maxs[1];
+
+ if ( i & 4 )
+ tmp[2] = mins[2];
+ else
+ tmp[2] = maxs[2];
+
+ for (j=0; j<3 ; j++)
+ {
+ rottemp[j] = DotProduct( tmp, trans[j] );
+ }
+ AddPointToBounds( rottemp, rotmins, rotmaxs );
+ }
+ VectorCopy( rotmins, mins );
+ VectorCopy( rotmaxs, maxs );
+}
diff --git a/q3radiant/IEpairs.h b/q3radiant/IEpairs.h
new file mode 100755
index 0000000..c7ceb09
--- /dev/null
+++ b/q3radiant/IEpairs.h
@@ -0,0 +1,83 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//-----------------------------------------------------------------------------
+//
+// $LogFile$
+// $Revision: 1.1.1.4 $
+// $Author: ttimo $
+// $Date: 2000/01/18 00:17:12 $
+// $Log: IEpairs.h,v $
+// Revision 1.1.1.4 2000/01/18 00:17:12 ttimo
+// merging in for RC
+//
+// Revision 1.3 2000/01/17 23:53:42 TBesset
+// ready for merge in sourceforge (RC candidate)
+//
+// Revision 1.2 2000/01/07 16:40:10 TBesset
+// merged from BSP frontend
+//
+// Revision 1.1.1.3 1999/12/29 18:31:26 TBesset
+// Q3Radiant public version
+//
+// Revision 1.1.1.1.2.1 1999/12/29 21:39:35 TBesset
+// updated to update3 from Robert
+//
+// Revision 1.1.1.3 1999/12/29 18:31:26 TBesset
+// Q3Radiant public version
+//
+// Revision 1.1.1.3 1999/12/29 18:31:26 TBesset
+// Q3Radiant public version
+//
+//
+// Revision 1.2 1999/11/22 17:46:45 Timo & Christine
+// merged EARadiant into the main tree
+// bug fixes for Q3Plugin / EAPlugin
+// export for Robert
+//
+// Revision 1.1.2.1 1999/11/03 20:37:59 Timo & Christine
+// MEAN plugin for Q3Radiant, alpha version
+//
+//
+// DESCRIPTION:
+// virtual class to allow plugin operations on entities epairs
+//
+
+#ifndef _IEPAIRS_H_
+#define _IEPAIRS_H_
+
+class IEpair
+{
+public:
+ // Increment the number of references to this object
+ virtual void IncRef () = 0;
+ // Decrement the reference count
+ virtual void DecRef () = 0;
+ virtual void GetVectorForKey( char* key, vec3_t vec ) = 0;
+ virtual float FloatForKey( char *key ) = 0;
+ virtual char* ValueForKey( char *key ) = 0;
+ virtual void SetKeyValue( char *key, char *value ) = 0;
+ virtual void GetEntityOrigin( vec3_t vec ) = 0;
+ // compute the rotated bounds of the BBox based on "angle" and "angles" keys
+ virtual void CalculateRotatedBounds( vec3_t mins, vec3_t maxs ) = 0;
+};
+
+#endif \ No newline at end of file
diff --git a/q3radiant/IMessaging.h b/q3radiant/IMessaging.h
new file mode 100755
index 0000000..549ad51
--- /dev/null
+++ b/q3radiant/IMessaging.h
@@ -0,0 +1,119 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//-----------------------------------------------------------------------------
+//
+// $LogFile$
+// $Revision: 1.1.2.1 $
+// $Author: ttimo $
+// $Date: 2000/02/04 22:59:34 $
+// $Log: IMessaging.h,v $
+// Revision 1.1.2.1 2000/02/04 22:59:34 ttimo
+// messaging API preview
+//
+//
+// DESCRIPTION:
+// interface for all-purpose messaging in Radiant
+
+#ifndef __IMESSAGING_H_
+#define __IMESSAGING_H_
+
+// this one can be hooked in the GL window procs for customizing GUI through plugins
+class IWindowListener
+{
+public:
+ // Increment the number of references to this object
+ virtual void IncRef () = 0;
+ // Decrement the reference count
+ virtual void DecRef () = 0;
+ // since Radiant is MFC we don't use a WNDPROC, we wrap the MFC handlers
+ // the handler is called first, if returns false Radiant continues processing
+ //++timo maybe add more later ? OnKeyUp and OnKeyDown for instance
+ //++timo TODO: add handlers everywhere
+ virtual bool OnLButtonDown(UINT nFlags, int x, int y) = 0;
+ virtual bool OnMButtonDown(UINT nFlags, int x, int y) = 0;
+ virtual bool OnRButtonDown(UINT nFlags, int x, int y) = 0;
+ virtual bool OnLButtonUp(UINT nFlags, int x, int y) = 0;
+ virtual bool OnMButtonUp(UINT nFlags, int x, int y) = 0;
+ virtual bool OnRButtonUp(UINT nFlags, int x, int y) = 0;
+ virtual bool OnMouseMove(UINT nFlags, int x, int y) = 0;
+};
+
+// various Radiant messages --------
+// this one holds the total number of supported messages (this is used to allocate structs)
+#define RADIANT_MSGCOUNT 3
+// they start with a 0, can be indexed in an array
+// something was selected / deselected
+#define RADIANT_SELECTION 0
+// a brush face was selected / deselected
+#define RADIANT_SFACE 1
+// current texture / shader changed
+#define RADIANT_TEXTURE 2
+
+// this one can be used to listen for Radiant-specific events
+class IListener
+{
+public:
+ // Increment the number of references to this object
+ virtual void IncRef () = 0;
+ // Decrement the reference count
+ virtual void DecRef () = 0;
+ // message is one of the RADIANT_* consts
+ virtual void DispatchRadiantMsg( int Msg ) = 0;
+};
+
+// this one is provided by Radiant, it's a wrapper for some usefull functions
+class IXYWndWrapper
+{
+public:
+ virtual void SnapToGrid( int x1, int y1, vec3_t pt ) = 0;
+};
+
+// define a GUID for this interface so plugins can access and reference it
+// {41FD005C-D36B-11d3-A3E9-0004AC96D4C3}
+static const GUID QERMessaging_GUID =
+{ 0x41fd005c, 0xd36b, 0x11d3, { 0xa3, 0xe9, 0x0, 0x4, 0xac, 0x96, 0xd4, 0xc3 } };
+
+// will hook the given IWindowListener to the XY window and increment the ref count
+//++timo TODO: add hooking in the CAM view and Z view
+typedef void (WINAPI* PFN_QERAPP_HOOKWINDOW) (IWindowListener *);
+// will unhook the given IWindowListener
+typedef void (WINAPI* PFN_QERAPP_UNHOOKWINDOW) (IWindowListener *);
+// to retrieve the IXYWndWrapper
+typedef IXYWndWrapper* (WINAPI* PFN_QERAPP_GETXYWNDWRAPPER) ();
+
+// will hook a given listener into Radiant listening for the given message and increment ref count
+// call several times to listen for several messages
+typedef void (WINAPI* PFN_QERAPP_HOOKLISTENER) (IListener *, int Msg);
+// will unhook the listener and return the number of messages the given listener was removed from
+typedef int (WINAPI* PFN_QERAPP_UNHOOKLISTENER)(IListener *);
+
+struct _QERMessagingTable
+{
+ int m_nSize;
+ PFN_QERAPP_HOOKWINDOW m_pfnHookWindow;
+ PFN_QERAPP_UNHOOKWINDOW m_pfnUnHookWindow;
+ PFN_QERAPP_GETXYWNDWRAPPER m_pfnGetXYWndWrapper;
+ PFN_QERAPP_HOOKLISTENER m_pfnHookListener;
+ PFN_QERAPP_UNHOOKLISTENER m_pfnUnHookListener;
+};
+
+#endif \ No newline at end of file
diff --git a/q3radiant/IPluginEntities.h b/q3radiant/IPluginEntities.h
new file mode 100755
index 0000000..bf2c818
--- /dev/null
+++ b/q3radiant/IPluginEntities.h
@@ -0,0 +1,105 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//-----------------------------------------------------------------------------
+//
+// $LogFile$
+// $Revision: 1.1.1.4 $
+// $Author: ttimo $
+// $Date: 2000/01/18 00:17:12 $
+// $Log: IPluginEntities.h,v $
+// Revision 1.1.1.4 2000/01/18 00:17:12 ttimo
+// merging in for RC
+//
+// Revision 1.3 2000/01/17 23:53:42 TBesset
+// ready for merge in sourceforge (RC candidate)
+//
+// Revision 1.2 2000/01/07 16:40:10 TBesset
+// merged from BSP frontend
+//
+// Revision 1.1.1.3 1999/12/29 18:31:27 TBesset
+// Q3Radiant public version
+//
+// Revision 1.1.1.1.2.1 1999/12/29 21:39:35 TBesset
+// updated to update3 from Robert
+//
+// Revision 1.1.1.3 1999/12/29 18:31:27 TBesset
+// Q3Radiant public version
+// Revision 1.1.1.3 1999/12/29 18:31:27 TBesset
+// Q3Radiant public version
+//
+// Revision 1.2 1999/11/22 17:46:45 Timo & Christine
+// merged EARadiant into the main tree
+// bug fixes for Q3Plugin / EAPlugin
+// export for Robert
+//
+// Revision 1.1.2.1 1999/11/03 20:37:59 Timo & Christine
+// MEAN plugin for Q3Radiant, alpha version
+//
+//
+// DESCRIPTION:
+// _QERPluginEntitiesTable is used by plugins for various plugin entities commands
+// _QERPlugEntitiesFactory is a set of commands Radiant uses to instanciate plugin entities
+// next are basics for plugin entities ( interfaces )
+
+#ifndef __IPLUGINENTITIES_H_
+#define __IPLUGINENTITIES_H_
+
+// define a GUID for this interface so plugins can access and reference it
+// {9613F500-8C7C-11d3-8EF3-C9EB56B6B7BE}
+static const GUID QERPluginEntitiesTable_GUID =
+{ 0x9613f500, 0x8c7c, 0x11d3, { 0x8e, 0xf3, 0xc9, 0xeb, 0x56, 0xb6, 0xb7, 0xbe } };
+
+typedef int (WINAPI* PFN_ECLASSSCANDIR) ( char*, HMODULE );
+
+struct _QERPluginEntitiesTable
+{
+ int m_nSize;
+ PFN_ECLASSSCANDIR m_pfnEClassScanDir;
+};
+
+// plugin entities
+class IPluginEntity
+{
+public:
+ // Increment the number of references to this object
+ virtual void IncRef () = 0;
+ // Decrement the reference count
+ virtual void DecRef () = 0;
+ // getting bounds of the brush used to select/move the object
+ virtual void GetBounds( vec3_t mins, vec3_t maxs ) = 0;
+ // rendering the object in the camera view
+ virtual void CamRender() = 0;
+};
+
+// {DBC6B300-8E4B-11d3-8EF3-BA5E57D56399}
+static const GUID QERPlugEntitiesFactory_GUID =
+{ 0xdbc6b300, 0x8e4b, 0x11d3, { 0x8e, 0xf3, 0xba, 0x5e, 0x57, 0xd5, 0x63, 0x99 } };
+
+typedef IPluginEntity * (WINAPI* PFN_CREATEENTITY) ( eclass_t *, IEpair * );
+
+struct _QERPlugEntitiesFactory
+{
+ int m_nSize;
+ PFN_CREATEENTITY m_pfnCreateEntity;
+};
+
+#endif \ No newline at end of file
diff --git a/q3radiant/ISelectedFace.h b/q3radiant/ISelectedFace.h
new file mode 100755
index 0000000..e4c5481
--- /dev/null
+++ b/q3radiant/ISelectedFace.h
@@ -0,0 +1,113 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//-----------------------------------------------------------------------------
+//
+// $LogFile$
+// $Revision: 1.1.1.4.2.1 $
+// $Author: ttimo $
+// $Date: 2000/02/10 03:00:20 $
+// $Log: ISelectedFace.h,v $
+// Revision 1.1.1.4.2.1 2000/02/10 03:00:20 ttimo
+// adding IShaders.h
+//
+// Revision 1.1.1.4 2000/01/18 00:17:12 ttimo
+// merging in for RC
+//
+// Revision 1.3 2000/01/17 23:53:42 TBesset
+// ready for merge in sourceforge (RC candidate)
+//
+// Revision 1.2 2000/01/07 16:40:10 TBesset
+// merged from BSP frontend
+//
+// Revision 1.1.1.3 1999/12/29 18:31:27 TBesset
+// Q3Radiant public version
+//
+// Revision 1.1.1.1.2.1 1999/12/29 21:39:35 TBesset
+// updated to update3 from Robert
+//
+// Revision 1.1.1.3 1999/12/29 18:31:27 TBesset
+// Q3Radiant public version
+// Revision 1.1.1.3 1999/12/29 18:31:27 TBesset
+// Q3Radiant public version
+//
+// Revision 1.2 1999/11/22 17:46:45 Timo & Christine
+// merged EARadiant into the main tree
+// bug fixes for Q3Plugin / EAPlugin
+// export for Robert
+//
+// Revision 1.1.4.3 1999/11/15 22:39:40 Timo & Christine
+// bug fixing / additional features after update 173 from Robert
+//
+// Revision 1.1.4.2 1999/11/14 16:26:10 Timo & Christine
+// first beta of the ritualmap surface plugin
+//
+// Revision 1.1.4.1 1999/11/03 20:37:59 Timo & Christine
+// MEAN plugin for Q3Radiant, alpha version
+//
+// Revision 1.1.2.1 1999/10/27 08:34:26 Timo & Christine
+// preview version of the texture tools plugin is ready
+// ( TexTool.dll plugin is in Q3Plugin module )
+// plugins can draw in their own window using Radiant's qgl bindings
+//
+//
+// DESCRIPTION:
+// Quick interface hack for selected face interface
+// this one really needs more work, but I'm in a hurry with TexTool
+
+#ifndef __ISELECTEDFACE_H_
+#define __ISELECTEDFACE_H_
+
+// define a GUID for this interface so plugins can access and reference it
+// {5416A2A0-8633-11d3-8EF3-88B61F3A3B12}
+static const GUID QERSelectedFaceTable_GUID =
+{ 0x5416a2a0, 0x8633, 0x11d3, { 0x8e, 0xf3, 0x88, 0xb6, 0x1f, 0x3a, 0x3b, 0x12 } };
+
+//++timo TODO: this interface needs some cleanup with the new texture / shaders interface
+
+// retrieve the texture number to bind to
+typedef int (WINAPI* PFN_GETTEXTURENUMBER) ();
+// winding_t is assumed to have MAX_POINTS_ON_WINDING allocated
+typedef int (WINAPI* PFN_GETFACEINFO) (_QERFaceData*, winding_t* );
+// tell editor to update the selected face data
+typedef int (WINAPI* PFN_SETFACEINFO) (_QERFaceData*);
+// retrieving some texture information
+typedef void (WINAPI* PFN_GETTEXTURESIZE) ( int Size[2] );
+// loading the qtexture_t from the texture name
+typedef qtexture_t* (WINAPI* PFN_TEXTUREFORNAME) ( const char *name );
+// straight func pointer to Select_SetTexture
+// last parameter must be casted to an IPluginTexdef
+typedef void (WINAPI* PFN_SELECT_SETTEXTURE) (texdef_t *texdef, brushprimit_texdef_t *brushprimit_texdef, bool bFitScale, void* pPlugTexdef );
+
+// NOTE: some things in there are not really related to the selected face
+// having some stuff moved into a textures-dedicated part ?
+struct _QERSelectedFaceTable
+{
+ int m_nSize;
+ PFN_GETTEXTURENUMBER m_pfnGetTextureNumber;
+ PFN_GETFACEINFO m_pfnGetFaceInfo;
+ PFN_SETFACEINFO m_pfnSetFaceInfo;
+ PFN_GETTEXTURESIZE m_pfnGetTextureSize;
+ PFN_TEXTUREFORNAME m_pfnTextureForName;
+ PFN_SELECT_SETTEXTURE m_pfnSelect_SetTexture;
+};
+
+#endif \ No newline at end of file
diff --git a/q3radiant/IShaders.cpp b/q3radiant/IShaders.cpp
new file mode 100755
index 0000000..b68f2d4
--- /dev/null
+++ b/q3radiant/IShaders.cpp
@@ -0,0 +1,86 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//-----------------------------------------------------------------------------
+//
+// $LogFile$
+// $Revision: 1.1.2.2 $
+// $Author: ttimo $
+// $Date: 2000/02/24 22:24:45 $
+// $Log: IShaders.cpp,v $
+// Revision 1.1.2.2 2000/02/24 22:24:45 ttimo
+// RC2
+//
+// Revision 1.1.2.1 2000/02/11 03:52:30 ttimo
+// working on the IShader interface
+//
+//
+// DESCRIPTION:
+// implementation of the shaders / textures interface
+//
+
+#include "stdafx.h"
+
+//++timo NOTE: this whole part is evolving on a seperate branch on SourceForge
+// will eventually turn into a major rewrite of the shader / texture code
+
+// this is a modified version of Texture_ForName
+qtexture_t* WINAPI QERApp_TryTextureForName(const char* name)
+{
+ qtexture_t *q;
+ char filename[1024];
+ for (q=g_qeglobals.d_qtextures ; q ; q=q->next)
+ {
+ if (!strcmp(name, q->filename))
+ return q;
+ }
+ // try loading from file .. this is a copy of the worst part of Texture_ForName
+ char cWork[1024];
+ sprintf (filename, "%s/%s.tga", ValueForKey (g_qeglobals.d_project_entity, "texturepath"), name);
+ QE_ConvertDOSToUnixName( cWork, filename );
+ strcpy(filename, cWork);
+ unsigned char* pPixels = NULL;
+ int nWidth;
+ int nHeight;
+ LoadImage(filename, &pPixels, &nWidth, &nHeight);
+ if (pPixels == NULL)
+ {
+ // try jpg
+ // blatant assumption of .tga should be fine since we sprintf'd it above
+ int nLen = strlen(filename);
+ filename[nLen-3] = 'j';
+ filename[nLen-2] = 'p';
+ filename[nLen-1] = 'g';
+ LoadImage(filename, &pPixels, &nWidth, &nHeight);
+ }
+ if (pPixels)
+ {
+ q = Texture_LoadTGATexture(pPixels, nWidth, nHeight, NULL, 0, 0, 0);
+ //++timo storing the filename .. will be removed by shader code cleanup
+ // this is dirty, and we sure miss some places were we should fill the filename info
+ strcpy( q->filename, name );
+ SetNameShaderInfo(q, filename, name);
+ Sys_Printf ("done.\n", name);
+ free(pPixels);
+ return q;
+ }
+ return NULL;
+}
diff --git a/q3radiant/IShaders.h b/q3radiant/IShaders.h
new file mode 100755
index 0000000..9bd0cf2
--- /dev/null
+++ b/q3radiant/IShaders.h
@@ -0,0 +1,79 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//-----------------------------------------------------------------------------
+//
+// $LogFile$
+// $Revision: 1.1.2.3 $
+// $Author: ttimo $
+// $Date: 2000/02/24 22:24:45 $
+// $Log: IShaders.h,v $
+// Revision 1.1.2.3 2000/02/24 22:24:45 ttimo
+// RC2
+//
+// Revision 1.1.2.2 2000/02/11 03:52:30 ttimo
+// working on the IShader interface
+//
+// Revision 1.1.2.1 2000/02/10 03:00:20 ttimo
+// adding IShaders.h
+//
+//
+// DESCRIPTION:
+// a set of functions to manipulate textures in Radiant
+//
+
+#ifndef __ISHADERS_H_
+#define __ISHADERS_H_
+
+// define a GUID for this interface so plugins can access and reference it
+// {D42F798A-DF57-11d3-A3EE-0004AC96D4C3}
+static const GUID QERShadersTable_GUID =
+{ 0xd42f798a, 0xdf57, 0x11d3, { 0xa3, 0xee, 0x0, 0x4, 0xac, 0x96, 0xd4, 0xc3 } };
+
+//++timo NOTE: global strategy, when there's try before it means .. if the thing can't be found / loaded it will not
+// create a default one
+
+//++timo TODO: duplicate _QERFuncTable_1::m_pfnHasShader here?
+//++timo FIXME: change the names to fit the changes we wanna do in the Radiant shader / textures code
+//++timo NOTE: for Curry, this shader loading thingy is only provided so that we can update the Radiant texture window?
+// don't use yet .. will not implement yet
+// get a shader, load it if needed
+// returns NULL if shader doesn't exist
+//++timo will reload the shader if already loaded? .. no, don't do that yet ..
+//++timo I'm not happy with the name?
+typedef qtexture_t* (WINAPI* PFN_TRYSHADERFORNAME) (const char* name);
+// load a texture
+// will not try loading a shader, will look for the actual image file ..
+// returns NULL on file not found
+// NOTE: don't put the .tga or .jpg filetype extension
+// if returns NULL, it means the texture needs loading, use _QERSelectedFaceTable::m_pfnTextureForName
+//++timo NOTE: all of this is hacks and workarounds, the shader code rewrite is supposed to solve all issues
+typedef qtexture_t* (WINAPI* PFN_TRYTEXTUREFORNAME) (const char* filename);
+
+struct _QERShadersTable
+{
+ int m_nSize;
+ // currently disabled
+// PFN_TRYLOADSHADER m_pfnTryLoadShader;
+ PFN_TRYTEXTUREFORNAME m_pfnTryTextureForName;
+};
+
+#endif \ No newline at end of file
diff --git a/q3radiant/LBMLIB.CPP b/q3radiant/LBMLIB.CPP
new file mode 100755
index 0000000..5d52307
--- /dev/null
+++ b/q3radiant/LBMLIB.CPP
@@ -0,0 +1,1329 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// lbmlib.c
+
+#include "stdafx.h"
+#include "cmdlib.h"
+#include "lbmlib.h"
+#include "bmp.h"
+#include "pakstuff.h"
+#include "jpeglib.h"
+
+
+/*
+============================================================================
+
+ LBM STUFF
+
+============================================================================
+*/
+
+
+typedef unsigned char UBYTE;
+//conflicts with windows typedef short WORD;
+typedef unsigned short UWORD;
+typedef long LONG;
+
+typedef enum
+{
+ ms_none,
+ ms_mask,
+ ms_transcolor,
+ ms_lasso
+} mask_t;
+
+typedef enum
+{
+ cm_none,
+ cm_rle1
+} compress_t;
+
+typedef struct
+{
+ UWORD w,h;
+ short x,y;
+ UBYTE nPlanes;
+ UBYTE masking;
+ UBYTE compression;
+ UBYTE pad1;
+ UWORD transparentColor;
+ UBYTE xAspect,yAspect;
+ short pageWidth,pageHeight;
+} bmhd_t;
+
+extern bmhd_t bmhd; // will be in native byte order
+
+
+
+#define FORMID ('F'+('O'<<8)+((int)'R'<<16)+((int)'M'<<24))
+#define ILBMID ('I'+('L'<<8)+((int)'B'<<16)+((int)'M'<<24))
+#define PBMID ('P'+('B'<<8)+((int)'M'<<16)+((int)' '<<24))
+#define BMHDID ('B'+('M'<<8)+((int)'H'<<16)+((int)'D'<<24))
+#define BODYID ('B'+('O'<<8)+((int)'D'<<16)+((int)'Y'<<24))
+#define CMAPID ('C'+('M'<<8)+((int)'A'<<16)+((int)'P'<<24))
+
+
+bmhd_t bmhd;
+
+int Align (int l)
+{
+ if (l&1)
+ return l+1;
+ return l;
+}
+
+
+
+/*
+================
+LBMRLEdecompress
+
+Source must be evenly aligned!
+================
+*/
+byte *LBMRLEDecompress (byte *source,byte *unpacked, int bpwidth)
+{
+ int count;
+ byte b,rept;
+
+ count = 0;
+
+ do
+ {
+ rept = *source++;
+
+ if (rept > 0x80)
+ {
+ rept = (rept^0xff)+2;
+ b = *source++;
+ memset(unpacked,b,rept);
+ unpacked += rept;
+ }
+ else if (rept < 0x80)
+ {
+ rept++;
+ memcpy(unpacked,source,rept);
+ unpacked += rept;
+ source += rept;
+ }
+ else
+ rept = 0; // rept of 0x80 is NOP
+
+ count += rept;
+
+ } while (count<bpwidth);
+
+ if (count>bpwidth)
+ Error ("Decompression exceeded width!\n");
+
+
+ return source;
+}
+
+
+/*
+=================
+LoadLBM
+=================
+*/
+void LoadLBM (char *filename, byte **picture, byte **palette)
+{
+ byte *LBMbuffer, *picbuffer, *cmapbuffer;
+ int y;
+ byte *LBM_P, *LBMEND_P;
+ byte *pic_p;
+ byte *body_p;
+
+ int formtype,formlength;
+ int chunktype,chunklength;
+
+// qiet compiler warnings
+ picbuffer = NULL;
+ cmapbuffer = NULL;
+
+//
+// load the LBM
+//
+ LoadFile (filename, (void **)&LBMbuffer);
+
+ if (LBMbuffer == NULL)
+ {
+ return;
+ }
+//
+// parse the LBM header
+//
+ LBM_P = LBMbuffer;
+ if ( *(int *)LBMbuffer != LittleLong(FORMID) )
+ Error ("No FORM ID at start of file!\n");
+
+ LBM_P += 4;
+ formlength = BigLong( *(int *)LBM_P );
+ LBM_P += 4;
+ LBMEND_P = LBM_P + Align(formlength);
+
+ formtype = LittleLong(*(int *)LBM_P);
+
+ if (formtype != ILBMID && formtype != PBMID)
+ Error ("Unrecognized form type: %c%c%c%c\n", formtype&0xff
+ ,(formtype>>8)&0xff,(formtype>>16)&0xff,(formtype>>24)&0xff);
+
+ LBM_P += 4;
+
+//
+// parse chunks
+//
+
+ while (LBM_P < LBMEND_P)
+ {
+ chunktype = LBM_P[0] + (LBM_P[1]<<8) + (LBM_P[2]<<16) + (LBM_P[3]<<24);
+ LBM_P += 4;
+ chunklength = LBM_P[3] + (LBM_P[2]<<8) + (LBM_P[1]<<16) + (LBM_P[0]<<24);
+ LBM_P += 4;
+
+ switch ( chunktype )
+ {
+ case BMHDID:
+ memcpy (&bmhd,LBM_P,sizeof(bmhd));
+ bmhd.w = BigShort(bmhd.w);
+ bmhd.h = BigShort(bmhd.h);
+ bmhd.x = BigShort(bmhd.x);
+ bmhd.y = BigShort(bmhd.y);
+ bmhd.pageWidth = BigShort(bmhd.pageWidth);
+ bmhd.pageHeight = BigShort(bmhd.pageHeight);
+ break;
+
+ case CMAPID:
+ cmapbuffer = (unsigned char*)malloc (768);
+ memset (cmapbuffer, 0, 768);
+ memcpy (cmapbuffer, LBM_P, chunklength);
+ break;
+
+ case BODYID:
+ body_p = LBM_P;
+
+ pic_p = picbuffer = (unsigned char*)malloc (bmhd.w*bmhd.h);
+ if (formtype == PBMID)
+ {
+ //
+ // unpack PBM
+ //
+ for (y=0 ; y<bmhd.h ; y++, pic_p += bmhd.w)
+ {
+ if (bmhd.compression == cm_rle1)
+ body_p = LBMRLEDecompress ((byte *)body_p
+ , pic_p , bmhd.w);
+ else if (bmhd.compression == cm_none)
+ {
+ memcpy (pic_p,body_p,bmhd.w);
+ body_p += Align(bmhd.w);
+ }
+ }
+
+ }
+ else
+ {
+ //
+ // unpack ILBM
+ //
+ Error ("%s is an interlaced LBM, not packed", filename);
+ }
+ break;
+ }
+
+ LBM_P += Align(chunklength);
+ }
+
+ free (LBMbuffer);
+
+ *picture = picbuffer;
+
+ if (palette)
+ *palette = cmapbuffer;
+}
+
+
+/*
+============================================================================
+
+ WRITE LBM
+
+============================================================================
+*/
+
+/*
+==============
+WriteLBMfile
+==============
+*/
+void WriteLBMfile (char *filename, byte *data,
+ int width, int height, byte *palette)
+{
+ byte *lbm, *lbmptr;
+ int *formlength, *bmhdlength, *cmaplength, *bodylength;
+ int length;
+ bmhd_t basebmhd;
+
+ lbm = lbmptr = (unsigned char*)malloc (width*height+1000);
+
+//
+// start FORM
+//
+ *lbmptr++ = 'F';
+ *lbmptr++ = 'O';
+ *lbmptr++ = 'R';
+ *lbmptr++ = 'M';
+
+ formlength = (int*)lbmptr;
+ lbmptr+=4; // leave space for length
+
+ *lbmptr++ = 'P';
+ *lbmptr++ = 'B';
+ *lbmptr++ = 'M';
+ *lbmptr++ = ' ';
+
+//
+// write BMHD
+//
+ *lbmptr++ = 'B';
+ *lbmptr++ = 'M';
+ *lbmptr++ = 'H';
+ *lbmptr++ = 'D';
+
+ bmhdlength = (int *)lbmptr;
+ lbmptr+=4; // leave space for length
+
+ memset (&basebmhd,0,sizeof(basebmhd));
+ basebmhd.w = BigShort((short)width);
+ basebmhd.h = BigShort((short)height);
+ basebmhd.nPlanes = 8;
+ basebmhd.xAspect = 5;
+ basebmhd.yAspect = 6;
+ basebmhd.pageWidth = BigShort((short)width);
+ basebmhd.pageHeight = BigShort((short)height);
+
+ memcpy (lbmptr,&basebmhd,sizeof(basebmhd));
+ lbmptr += sizeof(basebmhd);
+
+ length = lbmptr-(byte *)bmhdlength-4;
+ *bmhdlength = BigLong(length);
+ if (length&1)
+ *lbmptr++ = 0; // pad chunk to even offset
+
+//
+// write CMAP
+//
+ *lbmptr++ = 'C';
+ *lbmptr++ = 'M';
+ *lbmptr++ = 'A';
+ *lbmptr++ = 'P';
+
+ cmaplength = (int *)lbmptr;
+ lbmptr+=4; // leave space for length
+
+ memcpy (lbmptr,palette,768);
+ lbmptr += 768;
+
+ length = lbmptr-(byte *)cmaplength-4;
+ *cmaplength = BigLong(length);
+ if (length&1)
+ *lbmptr++ = 0; // pad chunk to even offset
+
+//
+// write BODY
+//
+ *lbmptr++ = 'B';
+ *lbmptr++ = 'O';
+ *lbmptr++ = 'D';
+ *lbmptr++ = 'Y';
+
+ bodylength = (int *)lbmptr;
+ lbmptr+=4; // leave space for length
+
+ memcpy (lbmptr,data,width*height);
+ lbmptr += width*height;
+
+ length = lbmptr-(byte *)bodylength-4;
+ *bodylength = BigLong(length);
+ if (length&1)
+ *lbmptr++ = 0; // pad chunk to even offset
+
+//
+// done
+//
+ length = lbmptr-(byte *)formlength-4;
+ *formlength = BigLong(length);
+ if (length&1)
+ *lbmptr++ = 0; // pad chunk to even offset
+
+//
+// write output file
+//
+ SaveFile (filename, lbm, lbmptr-lbm);
+ free (lbm);
+}
+
+/*
+============================================================================
+
+LOAD PCX
+
+============================================================================
+*/
+typedef struct
+{
+ char manufacturer;
+ char version;
+ char encoding;
+ char bits_per_pixel;
+ unsigned short xmin,ymin,xmax,ymax;
+ unsigned short hres,vres;
+ unsigned char palette[48];
+ char reserved;
+ char color_planes;
+ unsigned short bytes_per_line;
+ unsigned short palette_type;
+ char filler[58];
+ unsigned char data; // unbounded
+} pcx_t;
+
+/*
+==============
+LoadPCX
+==============
+*/
+void LoadPCX (char *filename, byte **pic, byte **palette, int *width, int *height)
+{
+ byte *raw = 0;
+ pcx_t *pcx;
+ int x, y;
+ int len;
+ int dataByte, runLength;
+ byte *out, *pix;
+
+ if (pic)
+ *pic = NULL;
+ if (palette)
+ *palette = NULL;
+ if (width)
+ *width = 0;
+ if (height)
+ *height = 0;
+
+ //
+ // load the file
+ //
+ len = LoadFile (filename, (void **)&raw);
+ if (len == -1)
+ return;
+
+ //
+ // parse the PCX file
+ //
+ pcx = (pcx_t *)raw;
+ raw = &pcx->data;
+
+ pcx->xmin = LittleShort(pcx->xmin);
+ pcx->ymin = LittleShort(pcx->ymin);
+ pcx->xmax = LittleShort(pcx->xmax);
+ pcx->ymax = LittleShort(pcx->ymax);
+ pcx->hres = LittleShort(pcx->hres);
+ pcx->vres = LittleShort(pcx->vres);
+ pcx->bytes_per_line = LittleShort(pcx->bytes_per_line);
+ pcx->palette_type = LittleShort(pcx->palette_type);
+
+ if (pcx->manufacturer != 0x0a
+ || pcx->version != 5
+ || pcx->encoding != 1
+ || pcx->bits_per_pixel != 8
+ || pcx->xmax >= 640
+ || pcx->ymax >= 480)
+ Error ("Bad pcx file %s", filename);
+
+ if (palette)
+ {
+ *palette = (unsigned char*)malloc(768);
+ memcpy (*palette, (byte *)pcx + len - 768, 768);
+ }
+
+ if (width)
+ *width = pcx->xmax+1;
+ if (height)
+ *height = pcx->ymax+1;
+
+ if (!pic)
+ {
+ free(pcx);
+ return;
+ }
+
+ out = (unsigned char*)malloc ( (pcx->ymax+1) * (pcx->xmax+1) );
+ if (!out)
+ Error ("Skin_Cache: couldn't allocate");
+
+ *pic = out;
+
+ pix = out;
+
+ for (y=0 ; y<=pcx->ymax ; y++, pix += pcx->xmax+1)
+ {
+ for (x=0 ; x<=pcx->xmax ; )
+ {
+ dataByte = *raw++;
+
+ if((dataByte & 0xC0) == 0xC0)
+ {
+ runLength = dataByte & 0x3F;
+ dataByte = *raw++;
+ }
+ else
+ runLength = 1;
+
+ while(runLength-- > 0)
+ pix[x++] = dataByte;
+ }
+
+ }
+
+ if ( raw - (byte *)pcx > len)
+ Error ("PCX file %s was malformed", filename);
+
+ free (pcx);
+}
+/*
+==============
+WritePCXfile
+==============
+*/
+void WritePCXfile (char *filename, byte *data,
+ int width, int height, byte *palette)
+{
+ int i, j, length;
+ pcx_t *pcx;
+ byte *pack;
+
+ pcx = (pcx_t*)malloc (width*height*2+1000);
+ memset (pcx, 0, sizeof(*pcx));
+
+ pcx->manufacturer = 0x0a; // PCX id
+ pcx->version = 5; // 256 color
+ pcx->encoding = 1; // uncompressed
+ pcx->bits_per_pixel = 8; // 256 color
+ pcx->xmin = 0;
+ pcx->ymin = 0;
+ pcx->xmax = LittleShort((short)(width-1));
+ pcx->ymax = LittleShort((short)(height-1));
+ pcx->hres = LittleShort((short)width);
+ pcx->vres = LittleShort((short)height);
+ pcx->color_planes = 1; // chunky image
+ pcx->bytes_per_line = LittleShort((short)width);
+ pcx->palette_type = LittleShort(2); // not a grey scale
+
+ // pack the image
+ pack = &pcx->data;
+
+ for (i=0 ; i<height ; i++)
+ {
+ for (j=0 ; j<width ; j++)
+ {
+ if ( (*data & 0xc0) != 0xc0)
+ *pack++ = *data++;
+ else
+ {
+ *pack++ = 0xc1;
+ *pack++ = *data++;
+ }
+ }
+ }
+
+ // write the palette
+ *pack++ = 0x0c; // palette ID byte
+ for (i=0 ; i<768 ; i++)
+ *pack++ = *palette++;
+
+// write output file
+ length = pack - (byte *)pcx;
+ SaveFile (filename, pcx, length);
+
+ free (pcx);
+}
+
+/*
+============================================================================
+
+LOAD IMAGE
+
+============================================================================
+*/
+
+/*
+==============
+Load256Image
+
+Will load either an lbm or pcx, depending on extension.
+Any of the return pointers can be NULL if you don't want them.
+==============
+*/
+void Load256Image (char *name, byte **pixels, byte **palette,
+ int *width, int *height)
+{
+ char ext[128];
+ bitmap_t bmp;
+
+ ExtractFileExtension (name, ext);
+ if (stricmp(ext, "lbm"))
+ {
+ LoadLBM (name, pixels, palette);
+ if (width)
+ *width = bmhd.w;
+ if (height)
+ *height = bmhd.h;
+ }
+ else if (stricmp (ext, "pcx"))
+ {
+ LoadPCX (name, pixels, palette, width, height);
+ }
+ else if (stricmp (ext, "bmp"))
+ {
+ LoadBMP (name, &bmp);
+ if (bmp.palette)
+ {
+ *palette = (unsigned char*)malloc (768);
+ memcpy (*palette, bmp.palette, 768);
+ }
+ FreeBMP (&bmp);
+ }
+ else
+ Error ("%s doesn't have a known image extension", name);
+}
+
+
+/*
+==============
+Save256Image
+
+Will save either an lbm or pcx, depending on extension.
+==============
+*/
+void Save256Image (char *name, byte *pixels, byte *palette,
+ int width, int height)
+{
+ char ext[128];
+
+ ExtractFileExtension (name, ext);
+ if (!strcmp (ext, "lbm"))
+ {
+ WriteLBMfile (name, pixels, width, height, palette);
+ }
+ else if (!stricmp (ext, "pcx"))
+ {
+ WritePCXfile (name, pixels, width, height, palette);
+ }
+ else
+ Error ("%s doesn't have a known image extension", name);
+}
+
+
+
+/*
+============================================================================
+
+TARGA IMAGE
+
+============================================================================
+*/
+typedef struct _TargaHeader {
+ unsigned char id_length, colormap_type, image_type;
+ unsigned short colormap_index, colormap_length;
+ unsigned char colormap_size;
+ unsigned short x_origin, y_origin, width, height;
+ unsigned char pixel_size, attributes;
+} TargaHeader;
+
+int fgetLittleShort (FILE *f)
+{
+ byte b1, b2;
+
+ b1 = fgetc(f);
+ b2 = fgetc(f);
+
+ return (short)(b1 + b2*256);
+}
+
+int getLittleShort (byte*& p)
+{
+ byte b1, b2;
+ b1 = *p++;
+ b2 = *p++;
+ return (short)(b1 + b2*256);
+}
+
+int getLittleLong (byte*& p)
+{
+ byte b1, b2, b3, b4;
+
+ b1 = *p++;
+ b2 = *p++;
+ b3 = *p++;
+ b4 = *p++;
+ return b1 + (b2<<8) + (b3<<16) + (b4<<24);
+}
+
+char getc(byte*& p)
+{
+ return *p++;
+}
+
+/*
+=========================================================
+
+BMP LOADING
+
+=========================================================
+*/
+typedef struct
+{
+ char id[2];
+ unsigned long fileSize;
+ unsigned long reserved0;
+ unsigned long bitmapDataOffset;
+ unsigned long bitmapHeaderSize;
+ unsigned long width;
+ unsigned long height;
+ unsigned short planes;
+ unsigned short bitsPerPixel;
+ unsigned long compression;
+ unsigned long bitmapDataSize;
+ unsigned long hRes;
+ unsigned long vRes;
+ unsigned long colors;
+ unsigned long importantColors;
+ unsigned char palette[256][4];
+} BMPHeader_t;
+
+static void LoadBMP( const char *name, byte **pic, int *width, int *height )
+{
+ int columns, rows, numPixels;
+ byte *pixbuf;
+ int row, column;
+ byte *buf_p;
+ byte *buffer;
+ unsigned int length;
+ BMPHeader_t bmpHeader;
+ byte *bmpRGBA;
+
+ *pic = NULL;
+
+ //
+ // load the file
+ //
+ length = LoadFile( ( char * ) name, (void **)&buffer);
+ if (length == -1)
+ {
+ length = PakLoadAnyFile( (char*)name, (void**)&buffer);
+ if (length == -1)
+ {
+ return;
+ }
+ }
+
+ buf_p = buffer;
+
+ bmpHeader.id[0] = *buf_p++;
+ bmpHeader.id[1] = *buf_p++;
+ bmpHeader.fileSize = LittleLong( * ( long * ) buf_p );
+ buf_p += 4;
+ bmpHeader.reserved0 = LittleLong( * ( long * ) buf_p );
+ buf_p += 4;
+ bmpHeader.bitmapDataOffset = LittleLong( * ( long * ) buf_p );
+ buf_p += 4;
+ bmpHeader.bitmapHeaderSize = LittleLong( * ( long * ) buf_p );
+ buf_p += 4;
+ bmpHeader.width = LittleLong( * ( long * ) buf_p );
+ buf_p += 4;
+ bmpHeader.height = LittleLong( * ( long * ) buf_p );
+ buf_p += 4;
+ bmpHeader.planes = LittleShort( * ( short * ) buf_p );
+ buf_p += 2;
+ bmpHeader.bitsPerPixel = LittleShort( * ( short * ) buf_p );
+ buf_p += 2;
+ bmpHeader.compression = LittleLong( * ( long * ) buf_p );
+ buf_p += 4;
+ bmpHeader.bitmapDataSize = LittleLong( * ( long * ) buf_p );
+ buf_p += 4;
+ bmpHeader.hRes = LittleLong( * ( long * ) buf_p );
+ buf_p += 4;
+ bmpHeader.vRes = LittleLong( * ( long * ) buf_p );
+ buf_p += 4;
+ bmpHeader.colors = LittleLong( * ( long * ) buf_p );
+ buf_p += 4;
+ bmpHeader.importantColors = LittleLong( * ( long * ) buf_p );
+ buf_p += 4;
+
+ memcpy( bmpHeader.palette, buf_p, sizeof( bmpHeader.palette ) );
+
+ if ( bmpHeader.bitsPerPixel == 8 )
+ buf_p += 1024;
+
+ if ( bmpHeader.id[0] != 'B' && bmpHeader.id[1] != 'M' )
+ {
+ Sys_Printf("LoadBMP: only Windows-style BMP files supported (%s)\n", name );
+ }
+ if ( bmpHeader.fileSize != length )
+ {
+ Sys_Printf("LoadBMP: header size does not match file size (%d vs. %d) (%s)\n", bmpHeader.fileSize, length, name );
+ }
+ if ( bmpHeader.compression != 0 )
+ {
+ Sys_Printf("LoadBMP: only uncompressed BMP files supported (%s)\n", name );
+ }
+ if ( bmpHeader.bitsPerPixel < 8 )
+ {
+ Sys_Printf("LoadBMP: monochrome and 4-bit BMP files not supported (%s)\n", name );
+ }
+
+ columns = bmpHeader.width;
+ rows = bmpHeader.height;
+ if ( rows < 0 )
+ rows = -rows;
+ numPixels = columns * rows;
+
+ if ( width )
+ *width = columns;
+ if ( height )
+ *height = rows;
+
+ bmpRGBA = reinterpret_cast<unsigned char*>(malloc( numPixels * 4 ));
+ *pic = bmpRGBA;
+
+
+ for ( row = rows-1; row >= 0; row-- )
+ {
+ pixbuf = bmpRGBA + row*columns*4;
+
+ for ( column = 0; column < columns; column++ )
+ {
+ unsigned char red, green, blue, alpha;
+ int palIndex;
+ unsigned short shortPixel;
+
+ switch ( bmpHeader.bitsPerPixel )
+ {
+ case 8:
+ palIndex = *buf_p++;
+ *pixbuf++ = bmpHeader.palette[palIndex][2];
+ *pixbuf++ = bmpHeader.palette[palIndex][1];
+ *pixbuf++ = bmpHeader.palette[palIndex][0];
+ *pixbuf++ = 0xff;
+ break;
+ case 16:
+ shortPixel = * ( unsigned short * ) pixbuf;
+ pixbuf += 2;
+ *pixbuf++ = ( shortPixel & ( 31 << 10 ) ) >> 7;
+ *pixbuf++ = ( shortPixel & ( 31 << 5 ) ) >> 2;
+ *pixbuf++ = ( shortPixel & ( 31 ) ) << 3;
+ *pixbuf++ = 0xff;
+ break;
+
+ case 24:
+ blue = *buf_p++;
+ green = *buf_p++;
+ red = *buf_p++;
+ *pixbuf++ = red;
+ *pixbuf++ = green;
+ *pixbuf++ = blue;
+ *pixbuf++ = 255;
+ break;
+ case 32:
+ blue = *buf_p++;
+ green = *buf_p++;
+ red = *buf_p++;
+ alpha = *buf_p++;
+ *pixbuf++ = red;
+ *pixbuf++ = green;
+ *pixbuf++ = blue;
+ *pixbuf++ = alpha;
+ break;
+ default:
+ Sys_Printf("LoadBMP: illegal pixel_size '%d' in file '%s'\n", bmpHeader.bitsPerPixel, name );
+ break;
+ }
+ }
+ }
+
+ free( buffer );
+
+}
+
+
+/*
+=================================================================
+
+PCX LOADING
+
+=================================================================
+*/
+
+
+/*
+==============
+LoadPCX
+==============
+*/
+static void LoadPCX ( const char *filename, byte **pic, byte **palette, int *width, int *height)
+{
+ byte *raw;
+ pcx_t *pcx;
+ int x, y;
+ int len;
+ int dataByte, runLength;
+ byte *out, *pix;
+ int xmax, ymax;
+
+ *pic = NULL;
+ *palette = NULL;
+
+ //
+ // load the file
+ //
+ len = LoadFile( ( char * ) filename, (void **)&raw);
+ if (len == -1)
+ {
+ len = PakLoadAnyFile( (char*)filename, (void**)&raw);
+ if (len == -1)
+ {
+ return;
+ }
+ }
+
+ //
+ // parse the PCX file
+ //
+ pcx = (pcx_t *)raw;
+ raw = &pcx->data;
+
+ xmax = LittleShort(pcx->xmax);
+ ymax = LittleShort(pcx->ymax);
+
+ if (pcx->manufacturer != 0x0a
+ || pcx->version != 5
+ || pcx->encoding != 1
+ || pcx->bits_per_pixel != 8
+ || xmax >= 1024
+ || ymax >= 1024)
+ {
+ Sys_Printf ("Bad pcx file %s (%i x %i) (%i x %i)\n", filename, xmax+1, ymax+1, pcx->xmax, pcx->ymax);
+ return;
+ }
+
+ out = reinterpret_cast<unsigned char*>(malloc ( (ymax+1) * (xmax+1) ));
+
+ *pic = out;
+
+ pix = out;
+
+ if (palette)
+ {
+ *palette = reinterpret_cast<unsigned char*>(malloc(768));
+ memcpy (*palette, (byte *)pcx + len - 768, 768);
+ }
+
+ if (width)
+ *width = xmax+1;
+ if (height)
+ *height = ymax+1;
+// FIXME: use bytes_per_line here?
+
+ for (y=0 ; y<=ymax ; y++, pix += xmax+1)
+ {
+ for (x=0 ; x<=xmax ; )
+ {
+ dataByte = *raw++;
+
+ if((dataByte & 0xC0) == 0xC0)
+ {
+ runLength = dataByte & 0x3F;
+ dataByte = *raw++;
+ }
+ else
+ runLength = 1;
+
+ while(runLength-- > 0)
+ pix[x++] = dataByte;
+ }
+
+ }
+
+ if ( raw - (byte *)pcx > len)
+ {
+ Sys_Printf ("PCX file %s was malformed", filename);
+ free (*pic);
+ *pic = NULL;
+ }
+
+ free(pcx);
+}
+
+
+/*
+==============
+LoadPCX32
+==============
+*/
+static void LoadPCX32 ( const char *filename, byte **pic, int *width, int *height) {
+ byte *palette;
+ byte *pic8;
+ int i, c, p;
+ byte *pic32;
+
+ LoadPCX (filename, &pic8, &palette, width, height);
+ if (!pic8) {
+ *pic = NULL;
+ return;
+ }
+
+ c = (*width) * (*height);
+ pic32 = *pic = reinterpret_cast<unsigned char*>(malloc(4 * c ));
+ for (i = 0 ; i < c ; i++) {
+ p = pic8[i];
+ pic32[0] = palette[p*3];
+ pic32[1] = palette[p*3 + 1];
+ pic32[2] = palette[p*3 + 2];
+ pic32[3] = 255;
+ pic32 += 4;
+ }
+
+ free (pic8);
+ free (palette);
+}
+
+/*
+=========================================================
+
+TARGA LOADING
+
+=========================================================
+*/
+
+/*
+=============
+LoadTGA
+=============
+*/
+void LoadTGA ( const char *name, byte **pic, int *width, int *height)
+{
+ int columns, rows, numPixels;
+ byte *pixbuf;
+ int row, column;
+ byte *buf_p;
+ byte *buffer;
+ TargaHeader targa_header;
+ byte *targa_rgba;
+
+ *pic = NULL;
+
+ //
+ // load the file
+ //
+ int nLen = LoadFile ( ( char * ) name, (void **)&buffer);
+ if (nLen == -1)
+ {
+ nLen = PakLoadAnyFile((char*)name, (void**)&buffer);
+ if (nLen == -1)
+ {
+ return;
+ }
+ }
+
+ buf_p = buffer;
+
+ targa_header.id_length = *buf_p++;
+ targa_header.colormap_type = *buf_p++;
+ targa_header.image_type = *buf_p++;
+
+ targa_header.colormap_index = LittleShort ( *(short *)buf_p );
+ buf_p += 2;
+ targa_header.colormap_length = LittleShort ( *(short *)buf_p );
+ buf_p += 2;
+ targa_header.colormap_size = *buf_p++;
+ targa_header.x_origin = LittleShort ( *(short *)buf_p );
+ buf_p += 2;
+ targa_header.y_origin = LittleShort ( *(short *)buf_p );
+ buf_p += 2;
+ targa_header.width = LittleShort ( *(short *)buf_p );
+ buf_p += 2;
+ targa_header.height = LittleShort ( *(short *)buf_p );
+ buf_p += 2;
+ targa_header.pixel_size = *buf_p++;
+ targa_header.attributes = *buf_p++;
+
+ //++timo debug
+ if (targa_header.pixel_size == 32)
+ Sys_Printf("%s is 32bit\n", name);
+ bool bAlphaOK = false;
+
+ if (targa_header.image_type!=2
+ && targa_header.image_type!=10
+ && targa_header.image_type != 3 )
+ {
+ Sys_Printf("LoadTGA: Only type 2 (RGB), 3 (gray), and 10 (RGB) TGA images supported\n");
+ }
+
+ if ( targa_header.colormap_type != 0 )
+ {
+ Sys_Printf("LoadTGA: colormaps not supported\n" );
+ }
+
+ if ( ( targa_header.pixel_size != 32 && targa_header.pixel_size != 24 ) && targa_header.image_type != 3 )
+ {
+ Sys_Printf("LoadTGA: Only 32 or 24 bit images supported (no colormaps)\n");
+ }
+
+ columns = targa_header.width;
+ rows = targa_header.height;
+ numPixels = columns * rows;
+
+ if (width)
+ *width = columns;
+ if (height)
+ *height = rows;
+
+ targa_rgba = reinterpret_cast<unsigned char*>(malloc (numPixels*4));
+ *pic = targa_rgba;
+
+ if (targa_header.id_length != 0)
+ buf_p += targa_header.id_length; // skip TARGA image comment
+
+ if ( targa_header.image_type==2 || targa_header.image_type == 3 )
+ {
+ // Uncompressed RGB or gray scale image
+ for(row=rows-1; row>=0; row--)
+ {
+ pixbuf = targa_rgba + row*columns*4;
+ for(column=0; column<columns; column++)
+ {
+ unsigned char red,green,blue,alphabyte;
+ switch (targa_header.pixel_size)
+ {
+
+ case 8:
+ blue = *buf_p++;
+ green = blue;
+ red = blue;
+ *pixbuf++ = red;
+ *pixbuf++ = green;
+ *pixbuf++ = blue;
+ *pixbuf++ = 255;
+ break;
+
+ case 24:
+ blue = *buf_p++;
+ green = *buf_p++;
+ red = *buf_p++;
+ *pixbuf++ = red;
+ *pixbuf++ = green;
+ *pixbuf++ = blue;
+ *pixbuf++ = 255;
+ break;
+ case 32:
+ blue = *buf_p++;
+ green = *buf_p++;
+ red = *buf_p++;
+ alphabyte = *buf_p++;
+ //++timo debug: detect if the whole alpha channel is 0
+ if (alphabyte != 0)
+ bAlphaOK = true;
+ *pixbuf++ = red;
+ *pixbuf++ = green;
+ *pixbuf++ = blue;
+ *pixbuf++ = alphabyte;
+ break;
+ default:
+ Sys_Printf("LoadTGA: illegal pixel_size '%d' in file '%s'\n", targa_header.pixel_size, name );
+ break;
+ }
+ }
+ }
+
+ //++timo debug
+ if (bAlphaOK)
+ Sys_Printf("alpha channel OK");
+ else
+ Sys_Printf("empty alpha channel!");
+ }
+ else if (targa_header.image_type==10) { // Runlength encoded RGB images
+
+ //++timo debug
+ Sys_Printf("runlength encode RGB image");
+
+ unsigned char red,green,blue,alphabyte,packetHeader,packetSize,j;
+
+ red = 0;
+ green = 0;
+ blue = 0;
+ alphabyte = 0xff;
+
+ for(row=rows-1; row>=0; row--) {
+ pixbuf = targa_rgba + row*columns*4;
+ for(column=0; column<columns; ) {
+ packetHeader= *buf_p++;
+ packetSize = 1 + (packetHeader & 0x7f);
+ if (packetHeader & 0x80) { // run-length packet
+ switch (targa_header.pixel_size) {
+ case 24:
+ blue = *buf_p++;
+ green = *buf_p++;
+ red = *buf_p++;
+ alphabyte = 255;
+ break;
+ case 32:
+ blue = *buf_p++;
+ green = *buf_p++;
+ red = *buf_p++;
+ alphabyte = *buf_p++;
+ break;
+ default:
+ Sys_Printf("LoadTGA: illegal pixel_size '%d' in file '%s'\n", targa_header.pixel_size, name );
+ break;
+ }
+
+ for(j=0;j<packetSize;j++) {
+ *pixbuf++=red;
+ *pixbuf++=green;
+ *pixbuf++=blue;
+ *pixbuf++=alphabyte;
+ column++;
+ if (column==columns) { // run spans across rows
+ column=0;
+ if (row>0)
+ row--;
+ else
+ goto breakOut;
+ pixbuf = targa_rgba + row*columns*4;
+ }
+ }
+ }
+ else { // non run-length packet
+ for(j=0;j<packetSize;j++) {
+ switch (targa_header.pixel_size) {
+ case 24:
+ blue = *buf_p++;
+ green = *buf_p++;
+ red = *buf_p++;
+ *pixbuf++ = red;
+ *pixbuf++ = green;
+ *pixbuf++ = blue;
+ *pixbuf++ = 255;
+ break;
+ case 32:
+ blue = *buf_p++;
+ green = *buf_p++;
+ red = *buf_p++;
+ alphabyte = *buf_p++;
+ *pixbuf++ = red;
+ *pixbuf++ = green;
+ *pixbuf++ = blue;
+ *pixbuf++ = alphabyte;
+ break;
+ default:
+ Sys_Printf("LoadTGA: illegal pixel_size '%d' in file '%s'\n", targa_header.pixel_size, name );
+ break;
+ }
+ column++;
+ if (column==columns) { // pixel packet run spans across rows
+ column=0;
+ if (row>0)
+ row--;
+ else
+ goto breakOut;
+ pixbuf = targa_rgba + row*columns*4;
+ }
+ }
+ }
+ }
+ breakOut:;
+ }
+ }
+
+ free(buffer);
+}
+
+
+
+
+void LoadJPG( const char *filename, unsigned char **pic, int *width, int *height )
+{
+ byte *fbuffer = NULL;
+ int nLen = LoadFile( ( char * ) filename, (void **)&fbuffer);
+ if (nLen == -1)
+ {
+ nLen = PakLoadAnyFile((char*)filename, (void**)&fbuffer);
+ if (nLen == -1)
+ {
+ return;
+ }
+ }
+ LoadJPGBuff(fbuffer, pic, width, height);
+ free(fbuffer);
+}
+
+//===================================================================
+
+/*
+=================
+LoadImage
+
+Loads any of the supported image types into a cannonical
+32 bit format.
+=================
+*/
+void LoadImage( const char *name, byte **pic, int *width, int *height )
+{
+ int len;
+ *pic = NULL;
+ *width = 0;
+ *height = 0;
+
+ len = strlen(name);
+ if (len<5)
+ {
+ return;
+ }
+
+ if ( !stricmp( name+len-4, ".tga" ) )
+ {
+ LoadTGA( name, pic, width, height );
+ }
+ else if ( !stricmp(name+len-4, ".pcx") )
+ {
+ LoadPCX32( name, pic, width, height );
+ }
+ else if ( !stricmp( name+len-4, ".bmp" ) )
+ {
+ LoadBMP( name, pic, width, height );
+ }
+ else if ( !stricmp( name+len-4, ".jpg" ) )
+ {
+ LoadJPG( name, pic, width, height );
+ }
+}
+
diff --git a/q3radiant/LBMLIB.H b/q3radiant/LBMLIB.H
new file mode 100755
index 0000000..16b747f
--- /dev/null
+++ b/q3radiant/LBMLIB.H
@@ -0,0 +1,40 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// piclib.h
+
+
+void LoadLBM (char *filename, byte **picture, byte **palette);
+void WriteLBMfile (char *filename, byte *data, int width, int height
+ , byte *palette);
+void LoadPCX (char *filename, byte **picture, byte **palette, int *width, int *height);
+void WritePCXfile (char *filename, byte *data, int width, int height
+ , byte *palette);
+
+// loads / saves either lbm or pcx, depending on extension
+void Load256Image (char *name, byte **pixels, byte **palette,
+ int *width, int *height);
+void Save256Image (char *name, byte *pixels, byte *palette,
+ int width, int height);
+
+
+void LoadTGA (char *filename, byte **pixels, int *width, int *height);
+void LoadImage( const char *name, byte **pic, int *width, int *height );
diff --git a/q3radiant/LstToolBar.cpp b/q3radiant/LstToolBar.cpp
new file mode 100755
index 0000000..3c9e352
--- /dev/null
+++ b/q3radiant/LstToolBar.cpp
@@ -0,0 +1,59 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// LstToolBar.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "LstToolBar.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CLstToolBar
+
+CLstToolBar::CLstToolBar()
+{
+}
+
+CLstToolBar::~CLstToolBar()
+{
+}
+
+
+BEGIN_MESSAGE_MAP(CLstToolBar, CToolBar)
+ //{{AFX_MSG_MAP(CLstToolBar)
+ ON_WM_PARENTNOTIFY()
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CLstToolBar message handlers
+
+void CLstToolBar::OnParentNotify(UINT message, LPARAM lParam)
+{
+ CToolBar::OnParentNotify(message, lParam);
+}
diff --git a/q3radiant/LstToolBar.h b/q3radiant/LstToolBar.h
new file mode 100755
index 0000000..acfb9a2
--- /dev/null
+++ b/q3radiant/LstToolBar.h
@@ -0,0 +1,69 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_LSTTOOLBAR_H__279AAE23_78C5_11D1_B53C_00AA00A410FC__INCLUDED_)
+#define AFX_LSTTOOLBAR_H__279AAE23_78C5_11D1_B53C_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// LstToolBar.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CLstToolBar window
+
+class CLstToolBar : public CToolBar
+{
+// Construction
+public:
+ CLstToolBar();
+
+// Attributes
+public:
+
+// Operations
+public:
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CLstToolBar)
+ //}}AFX_VIRTUAL
+
+// Implementation
+public:
+ virtual ~CLstToolBar();
+
+ // Generated message map functions
+protected:
+ //{{AFX_MSG(CLstToolBar)
+ afx_msg void OnParentNotify(UINT message, LPARAM lParam);
+ //}}AFX_MSG
+
+ DECLARE_MESSAGE_MAP()
+};
+
+/////////////////////////////////////////////////////////////////////////////
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_LSTTOOLBAR_H__279AAE23_78C5_11D1_B53C_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/MAP.CPP b/q3radiant/MAP.CPP
new file mode 100755
index 0000000..8207c54
--- /dev/null
+++ b/q3radiant/MAP.CPP
@@ -0,0 +1,1062 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// map.c
+
+#include "stdafx.h"
+#include "qe3.h"
+#include "PrefsDlg.h"
+
+qboolean modified; // for quit confirmation (0 = clean, 1 = unsaved,
+ // 2 = autosaved, but not regular saved)
+
+char currentmap[1024];
+
+
+brush_t active_brushes; // brushes currently being displayed
+brush_t selected_brushes; // highlighted
+
+face_t *selected_face;
+brush_t *selected_face_brush;
+
+brush_t filtered_brushes; // brushes that have been filtered or regioned
+
+entity_t entities; // head/tail of doubly linked list
+
+entity_t *world_entity = NULL; // "classname" "worldspawn" !
+
+void AddRegionBrushes (void);
+void RemoveRegionBrushes (void);
+
+
+void DupLists()
+{
+ DWORD dw = GetTickCount();
+
+}
+
+/*
+=============================================================
+
+ Cross map selection saving
+
+ this could fuck up if you have only part of a complex entity selected...
+=============================================================
+*/
+
+brush_t between_brushes;
+entity_t between_entities;
+
+bool g_bRestoreBetween = false;
+
+void Map_SaveBetween (void)
+{
+
+ if (g_pParentWnd->ActiveXY())
+ {
+ g_bRestoreBetween = true;
+ g_pParentWnd->ActiveXY()->Copy();
+ }
+ return;
+
+#if 0
+
+ brush_t *b;
+ entity_t *e, *e2;
+
+ between_brushes.next = selected_brushes.next;
+ between_brushes.prev = selected_brushes.prev;
+ between_brushes.next->prev = &between_brushes;
+ between_brushes.prev->next = &between_brushes;
+
+ between_entities.next = between_entities.prev = &between_entities;
+ selected_brushes.next = selected_brushes.prev = &selected_brushes;
+
+ for (b=between_brushes.next ; b != &between_brushes ; b=b->next)
+ {
+ e = b->owner;
+ if (e == world_entity)
+ b->owner = NULL;
+ else
+ {
+ for (e2=between_entities.next ; e2 != &between_entities ; e2=e2->next)
+ if (e2 == e)
+ goto next; // allready got the entity
+ // move the entity over
+ e->prev->next = e->next;
+ e->next->prev = e->prev;
+ e->next = between_entities.next;
+ e->prev = &between_entities;
+ e->next->prev = e;
+ e->prev->next = e;
+ }
+next: ;
+ }
+#endif
+}
+
+void Map_RestoreBetween (void)
+{
+ if (g_pParentWnd->ActiveXY() && g_bRestoreBetween)
+ g_pParentWnd->ActiveXY()->Paste();
+ return;
+
+#if 0
+ entity_t *head, *tail;
+ brush_t *b;
+
+ if (!between_brushes.next)
+ return;
+
+ for (b=between_brushes.next ; b != &between_brushes ; b=b->next)
+ {
+ if (!b->owner)
+ {
+ b->owner = world_entity;
+ b->onext = world_entity->brushes.onext;
+ b->oprev = &world_entity->brushes;
+ b->onext->oprev = b;
+ b->oprev->onext = b;
+ }
+ }
+
+ selected_brushes.next = between_brushes.next;
+ selected_brushes.prev = between_brushes.prev;
+ selected_brushes.next->prev = &selected_brushes;
+ selected_brushes.prev->next = &selected_brushes;
+
+ head = between_entities.next;
+ tail = between_entities.prev;
+
+ if (head != tail)
+ {
+ entities.prev->next = head;
+ head->prev = entities.prev;
+ tail->next = &entities;
+ entities.prev = tail;
+ }
+
+ between_brushes.next = NULL;
+ between_entities.next = NULL;
+#endif
+}
+
+//============================================================================
+
+bool CheckForTinyBrush(brush_t* b, int n, float fSize)
+{
+ bool bTiny = false;
+ for (int i=0 ; i<3 ; i++)
+ {
+ if (b->maxs[i] - b->mins[i] < fSize)
+ bTiny = true;
+ }
+ if (bTiny)
+ Sys_Printf("Possible problem brush (too small) #%i ", n);
+ return bTiny;
+}
+
+void Map_BuildBrushData(void)
+{
+ brush_t *b, *next;
+
+ if (active_brushes.next == NULL)
+ return;
+
+ Sys_BeginWait (); // this could take a while
+
+ int n = 0;
+ for (b=active_brushes.next ; b != NULL && b != &active_brushes ; b=next)
+ {
+ next = b->next;
+ Brush_Build( b, true, false, false );
+ if (!b->brush_faces || (g_PrefsDlg.m_bCleanTiny && CheckForTinyBrush(b, n++, g_PrefsDlg.m_fTinySize)))
+ {
+ Brush_Free (b);
+ Sys_Printf ("Removed degenerate brush\n");
+ }
+ }
+ Sys_EndWait();
+}
+
+entity_t *Map_FindClass (char *cname)
+{
+ entity_t *ent;
+
+ for (ent = entities.next ; ent != &entities ; ent=ent->next)
+ {
+ if (!strcmp(cname, ValueForKey (ent, "classname")))
+ return ent;
+ }
+ return NULL;
+}
+
+/*
+================
+Map_Free
+================
+*/
+void Map_Free (void)
+{
+ g_bRestoreBetween = false;
+ if (selected_brushes.next &&
+ (selected_brushes.next != &selected_brushes) )
+ {
+ if (MessageBox(g_qeglobals.d_hwndMain, "Copy selection?", "", MB_YESNO) == IDYES)
+ Map_SaveBetween ();
+ }
+
+ Texture_ClearInuse ();
+ Pointfile_Clear ();
+ strcpy (currentmap, "unnamed.map");
+ Sys_SetTitle (currentmap);
+ g_qeglobals.d_num_entities = 0;
+ g_qeglobals.d_numterrapoints = 0;
+
+ if (!active_brushes.next)
+ { // first map
+ active_brushes.prev = active_brushes.next = &active_brushes;
+ selected_brushes.prev = selected_brushes.next = &selected_brushes;
+ filtered_brushes.prev = filtered_brushes.next = &filtered_brushes;
+
+ entities.prev = entities.next = &entities;
+ }
+ else
+ {
+ while (active_brushes.next != &active_brushes)
+ Brush_Free (active_brushes.next);
+ while (selected_brushes.next != &selected_brushes)
+ Brush_Free (selected_brushes.next);
+ while (filtered_brushes.next != &filtered_brushes)
+ Brush_Free (filtered_brushes.next);
+
+ while (entities.next != &entities)
+ Entity_Free (entities.next);
+ }
+
+ if (world_entity)
+ Entity_Free(world_entity);
+ world_entity = NULL;
+}
+
+entity_t *AngledEntity()
+{
+ entity_t *ent = Map_FindClass ("info_player_start");
+ if (!ent)
+ {
+ ent = Map_FindClass ("info_player_deathmatch");
+ }
+ if (!ent)
+ {
+ ent = Map_FindClass ("info_player_deathmatch");
+ }
+ if (!ent)
+ {
+ ent = Map_FindClass ("team_CTF_redplayer");
+ }
+ if (!ent)
+ {
+ ent = Map_FindClass ("team_CTF_blueplayer");
+ }
+ if (!ent)
+ {
+ ent = Map_FindClass ("team_CTF_redspawn");
+ }
+ if (!ent)
+ {
+ ent = Map_FindClass ("team_CTF_bluespawn");
+ }
+ return ent;
+}
+
+
+
+/*
+================
+Map_LoadFile
+================
+*/
+void Map_LoadFile (char *filename)
+{
+ char *buf;
+ entity_t *ent;
+ char temp[1024];
+
+ Sys_BeginWait ();
+ Select_Deselect();
+ //SetInspectorMode(W_CONSOLE);
+
+ QE_ConvertDOSToUnixName( temp, filename );
+ Sys_Printf ("Map_LoadFile: %s\n", temp );
+
+ Map_Free ();
+ //++timo FIXME: maybe even easier to have Group_Init called from Map_Free?
+ Group_Init();
+
+ g_qeglobals.d_parsed_brushes = 0;
+ strcpy (currentmap, filename);
+
+ if (LoadFile (filename, (void **)&buf) != -1)
+ {
+
+ StartTokenParsing (buf);
+ g_qeglobals.d_num_entities = 0;
+
+ // Timo
+ // will be used in Entity_Parse to detect if a conversion between brush formats is needed
+ g_qeglobals.bNeedConvert = false;
+ g_qeglobals.bOldBrushes = false;
+ g_qeglobals.bPrimitBrushes = false;
+
+ while (1)
+ {
+ ent = Entity_Parse (false, &active_brushes);
+ if (!ent)
+ break;
+ if (!strcmp(ValueForKey (ent, "classname"), "worldspawn"))
+ {
+ if (world_entity)
+ Sys_Printf ("WARNING: multiple worldspawn\n");
+ world_entity = ent;
+ }
+ else if (!strcmp(ValueForKey (ent, "classname"), "group_info"))
+ {
+ // it's a group thing!
+ Group_Add(ent);
+ Entity_Free(ent);
+ }
+ else
+ {
+ // add the entity to the end of the entity list
+ ent->next = &entities;
+ ent->prev = entities.prev;
+ entities.prev->next = ent;
+ entities.prev = ent;
+ g_qeglobals.d_num_entities++;
+ }
+ }
+ }
+
+ free (buf);
+
+ if (!world_entity)
+ {
+ Sys_Printf ("No worldspawn in map.\n");
+ Map_New ();
+ return;
+ }
+
+ Sys_Printf ("--- LoadMapFile ---\n");
+ Sys_Printf ("%s\n", temp );
+
+ Sys_Printf ("%5i brushes\n", g_qeglobals.d_parsed_brushes );
+ Sys_Printf ("%5i entities\n", g_qeglobals.d_num_entities);
+
+ Map_RestoreBetween ();
+
+ Sys_Printf ("Map_BuildAllDisplayLists\n");
+ Map_BuildBrushData();
+
+ // reset the "need conversion" flag
+ // conversion to the good format done in Map_BuildBrushData
+ g_qeglobals.bNeedConvert=false;
+
+ //
+ // move the view to a start position
+ //
+ ent = AngledEntity();
+
+ g_pParentWnd->GetCamera()->Camera().angles[PITCH] = 0;
+ if (ent)
+ {
+ GetVectorForKey (ent, "origin", g_pParentWnd->GetCamera()->Camera().origin);
+ GetVectorForKey (ent, "origin", g_pParentWnd->GetXYWnd()->GetOrigin());
+ g_pParentWnd->GetCamera()->Camera().angles[YAW] = FloatForKey (ent, "angle");
+ }
+ else
+ {
+ g_pParentWnd->GetCamera()->Camera().angles[YAW] = 0;
+ VectorCopy (vec3_origin, g_pParentWnd->GetCamera()->Camera().origin);
+ VectorCopy (vec3_origin, g_pParentWnd->GetXYWnd()->GetOrigin());
+ }
+
+ Map_RegionOff ();
+
+
+ modified = false;
+ Sys_SetTitle (temp);
+
+ Texture_ShowInuse ();
+
+ Sys_EndWait();
+ Sys_UpdateWindows (W_ALL);
+
+}
+
+/*
+===========
+Map_SaveFile
+===========
+*/
+void Map_SaveFile (char *filename, qboolean use_region )
+{
+ entity_t *e, *next;
+ FILE *f;
+ char temp[1024];
+ int count;
+
+ if (filename == NULL || strlen(filename) == 0)
+ {
+ CFileDialog dlgSave(FALSE, "map", NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, "Map Files (*.map)|*.map||", AfxGetMainWnd());
+ if (dlgSave.DoModal() == IDOK)
+ filename = strdup(dlgSave.m_ofn.lpstrFile);
+ else
+ return;
+ }
+
+ Pointfile_Clear ();
+ QE_ConvertDOSToUnixName( temp, filename );
+
+ if (!use_region)
+ {
+ char backup[1024];
+
+ // rename current to .bak
+ strcpy (backup, filename);
+ StripExtension (backup);
+ strcat (backup, ".bak");
+ _unlink (backup);
+ rename (filename, backup);
+ }
+
+ Sys_Printf ("Map_SaveFile: %s\n", filename);
+
+ f = fopen(filename, "w");
+
+ if (!f)
+ {
+ Sys_Printf ("ERROR!!!! Couldn't open %s\n", filename);
+ return;
+ }
+
+ if (use_region)
+ {
+ AddRegionBrushes ();
+ }
+
+ // write world entity first
+ Entity_Write (world_entity, f, use_region);
+
+ // then write all other ents
+ count = 1;
+ for (e=entities.next ; e != &entities ; e=next)
+ {
+ next = e->next;
+ if (e->brushes.onext == &e->brushes)
+ {
+ Entity_Free (e); // no brushes left, so remove it
+ }
+ else
+ {
+ fprintf (f, "// entity %i\n", count);
+ count++;
+ Entity_Write (e, f, use_region);
+ }
+ }
+
+ // save the group info stuff
+ Group_Save(f);
+
+ fclose (f);
+
+ if (use_region)
+ RemoveRegionBrushes ();
+
+ Sys_Printf ("Saved.\n");
+ modified = false;
+
+ if ( !strstr( temp, "autosave" ) )
+ Sys_SetTitle (temp);
+
+ if (!use_region)
+ {
+ time_t timer;
+ FILE *f;
+
+ time (&timer);
+ MessageBeep (MB_ICONEXCLAMATION);
+ f = fopen ("c:/tstamps.log", "a");
+ if (f)
+ {
+ fprintf (f, "%s", filename);
+ //fprintf (f, "%4i : %35s : %s", g_qeglobals.d_workcount, filename, ctime(&timer));
+ fclose (f);
+ g_qeglobals.d_workcount = 0;
+ }
+ fclose (f);
+ Sys_Status ("Saved.\n", 0);
+ }
+
+ //Curve_WriteFile (filename); //.trinity
+ //Patch_WriteFile (filename);
+}
+
+/*
+===========
+Map_New
+===========
+*/
+void Map_New (void)
+{
+ Sys_Printf ("Map_New\n");
+ Map_Free ();
+
+ Patch_Cleanup();
+
+ world_entity = (entity_s*)qmalloc(sizeof(*world_entity));
+ world_entity->brushes.onext =
+ world_entity->brushes.oprev = &world_entity->brushes;
+ SetKeyValue (world_entity, "classname", "worldspawn");
+ world_entity->eclass = Eclass_ForName ("worldspawn", true);
+
+ g_pParentWnd->GetCamera()->Camera().angles[YAW] = 0;
+ g_pParentWnd->GetCamera()->Camera().angles[PITCH] = 0;
+ VectorCopy (vec3_origin, g_pParentWnd->GetCamera()->Camera().origin);
+ g_pParentWnd->GetCamera()->Camera().origin[2] = 48;
+ VectorCopy (vec3_origin, g_pParentWnd->GetXYWnd()->GetOrigin());
+
+ Map_RestoreBetween ();
+
+ Group_Init();
+
+ Sys_UpdateWindows (W_ALL);
+ modified = false;
+}
+
+/*
+===========================================================
+
+ REGION
+
+===========================================================
+*/
+
+qboolean region_active;
+vec3_t region_mins = {MIN_WORLD_COORD, MIN_WORLD_COORD, MIN_WORLD_COORD};
+vec3_t region_maxs = {MAX_WORLD_COORD, MAX_WORLD_COORD, MAX_WORLD_COORD};
+
+brush_t *region_sides[4];
+/*
+===========
+AddRegionBrushes
+
+a regioned map will have temp walls put up at the region boundary
+===========
+*/
+void AddRegionBrushes (void)
+{
+ vec3_t mins, maxs;
+ int i;
+ texdef_t td;
+
+ if (!region_active)
+ return;
+
+ memset (&td, 0, sizeof(td));
+ //strcpy (td.name, "REGION");
+ td.SetName("REGION");
+
+ mins[0] = region_mins[0] - 16;
+ maxs[0] = region_mins[0] + 1;
+ mins[1] = region_mins[1] - 16;
+ maxs[1] = region_maxs[1] + 16;
+ mins[2] = MIN_WORLD_COORD;
+ maxs[2] = MAX_WORLD_COORD;
+ region_sides[0] = Brush_Create (mins, maxs, &td);
+
+ mins[0] = region_maxs[0] - 1;
+ maxs[0] = region_maxs[0] + 16;
+ region_sides[1] = Brush_Create (mins, maxs, &td);
+
+ mins[0] = region_mins[0] - 16;
+ maxs[0] = region_maxs[0] + 16;
+ mins[1] = region_mins[1] - 16;
+ maxs[1] = region_mins[1] + 1;
+ region_sides[2] = Brush_Create (mins, maxs, &td);
+
+ mins[1] = region_maxs[1] - 1;
+ maxs[1] = region_maxs[1] + 16;
+ region_sides[3] = Brush_Create (mins, maxs, &td);
+
+ for (i=0 ; i<4 ; i++)
+ {
+ Brush_AddToList (region_sides[i], &selected_brushes);
+ Entity_LinkBrush (world_entity, region_sides[i]);
+ Brush_Build( region_sides[i] );
+ }
+}
+
+void RemoveRegionBrushes (void)
+{
+ int i;
+
+ if (!region_active)
+ return;
+ for (i=0 ; i<4 ; i++)
+ Brush_Free (region_sides[i]);
+}
+
+
+qboolean Map_IsBrushFiltered (brush_t *b)
+{
+ int i;
+
+ for (i=0 ; i<3 ; i++)
+ {
+ if (b->mins[i] > region_maxs[i])
+ return true;
+ if (b->maxs[i] < region_mins[i])
+ return true;
+ }
+ return false;
+}
+
+/*
+===========
+Map_RegionOff
+
+Other filtering options may still be on
+===========
+*/
+void Map_RegionOff (void)
+{
+ brush_t *b, *next;
+ int i;
+
+ region_active = false;
+ for (i=0 ; i<3 ; i++)
+ {
+ region_maxs[i] = MAX_WORLD_COORD;//4096;
+ region_mins[i] = MIN_WORLD_COORD;//-4096;
+ }
+
+ for (b=filtered_brushes.next ; b != &filtered_brushes ; b=next)
+ {
+ next = b->next;
+ if (Map_IsBrushFiltered (b))
+ continue; // still filtered
+ Brush_RemoveFromList (b);
+ if (active_brushes.next == NULL || active_brushes.prev == NULL)
+ {
+ active_brushes.next = &active_brushes;
+ active_brushes.prev = &active_brushes;
+ }
+ Brush_AddToList (b, &active_brushes);
+ }
+
+ Sys_UpdateWindows (W_ALL);
+}
+
+void Map_ApplyRegion (void)
+{
+ brush_t *b, *next;
+
+ region_active = true;
+ for (b=active_brushes.next ; b != &active_brushes ; b=next)
+ {
+ next = b->next;
+ if (!Map_IsBrushFiltered (b))
+ continue; // still filtered
+ Brush_RemoveFromList (b);
+ Brush_AddToList (b, &filtered_brushes);
+ }
+
+ Sys_UpdateWindows (W_ALL);
+}
+
+
+/*
+========================
+Map_RegionSelectedBrushes
+========================
+*/
+void Map_RegionSelectedBrushes (void)
+{
+ Map_RegionOff ();
+
+ if (selected_brushes.next == &selected_brushes) // nothing selected
+ {
+ Sys_Printf("Tried to region with no selection...\n");
+ return;
+ }
+ region_active = true;
+ Select_GetBounds (region_mins, region_maxs);
+
+ // move the entire active_brushes list to filtered_brushes
+ filtered_brushes.next = active_brushes.next;
+ filtered_brushes.prev = active_brushes.prev;
+ filtered_brushes.next->prev = &filtered_brushes;
+ filtered_brushes.prev->next = &filtered_brushes;
+
+ // move the entire selected_brushes list to active_brushes
+ active_brushes.next = selected_brushes.next;
+ active_brushes.prev = selected_brushes.prev;
+ active_brushes.next->prev = &active_brushes;
+ active_brushes.prev->next = &active_brushes;
+
+ // clear selected_brushes
+ selected_brushes.next = selected_brushes.prev = &selected_brushes;
+
+ Sys_UpdateWindows (W_ALL);
+}
+
+
+/*
+===========
+Map_RegionXY
+===========
+*/
+void Map_RegionXY (void)
+{
+ Map_RegionOff ();
+
+ region_mins[0] = g_pParentWnd->GetXYWnd()->GetOrigin()[0] - 0.5 * g_pParentWnd->GetXYWnd()->Width() / g_pParentWnd->GetXYWnd()->Scale();
+ region_maxs[0] = g_pParentWnd->GetXYWnd()->GetOrigin()[0] + 0.5 * g_pParentWnd->GetXYWnd()->Width() / g_pParentWnd->GetXYWnd()->Scale();
+ region_mins[1] = g_pParentWnd->GetXYWnd()->GetOrigin()[1] - 0.5 * g_pParentWnd->GetXYWnd()->Height() / g_pParentWnd->GetXYWnd()->Scale();
+ region_maxs[1] = g_pParentWnd->GetXYWnd()->GetOrigin()[1] + 0.5 * g_pParentWnd->GetXYWnd()->Height() / g_pParentWnd->GetXYWnd()->Scale();
+ region_mins[2] = -MIN_WORLD_COORD;
+ region_maxs[2] = MAX_WORLD_COORD;
+ Map_ApplyRegion ();
+}
+
+/*
+===========
+Map_RegionTallBrush
+===========
+*/
+void Map_RegionTallBrush (void)
+{
+ brush_t *b;
+
+ if (!QE_SingleBrush ())
+ return;
+
+ b = selected_brushes.next;
+
+ Map_RegionOff ();
+
+ VectorCopy (b->mins, region_mins);
+ VectorCopy (b->maxs, region_maxs);
+ region_mins[2] = MIN_WORLD_COORD;
+ region_maxs[2] = MAX_WORLD_COORD;
+
+
+ Select_Delete ();
+ Map_ApplyRegion ();
+}
+/*
+===========
+Map_RegionBrush
+===========
+*/
+void Map_RegionBrush (void)
+{
+ brush_t *b;
+
+ if (!QE_SingleBrush ())
+ return;
+
+ b = selected_brushes.next;
+
+ Map_RegionOff ();
+
+ VectorCopy (b->mins, region_mins);
+ VectorCopy (b->maxs, region_maxs);
+
+ Select_Delete ();
+ Map_ApplyRegion ();
+}
+
+
+
+void UniqueTargetName(CString& rStr)
+{
+ // make a unique target value
+ int maxtarg = 0;
+ for (entity_t* e=entities.next ; e != &entities ; e=e->next)
+ {
+ char* tn = ValueForKey (e, "targetname");
+ if (tn && tn[0])
+ {
+ int targetnum = atoi(tn+1);
+ if (targetnum > maxtarg)
+ maxtarg = targetnum;
+ }
+ else
+ {
+ tn = ValueForKey (e, "target");
+ if (tn && tn[0])
+ {
+ int targetnum = atoi(tn+1);
+ if (targetnum > maxtarg)
+ maxtarg = targetnum;
+ }
+ }
+ }
+ rStr.Format("t%i", maxtarg+1);
+}
+
+//
+//================
+//Map_ImportFile
+// Timo 09/01/99 : called by CXYWnd::Paste & Map_ImportFile
+// if Map_ImportFile ( prefab ), the buffer may contain brushes in old format ( conversion needed )
+//================
+//
+void Map_ImportBuffer (char* buf)
+{
+ entity_t* ent;
+ brush_t* b = NULL;
+ CPtrArray ptrs;
+
+ Select_Deselect();
+
+ Undo_Start("import buffer");
+
+ g_qeglobals.d_parsed_brushes = 0;
+ if (buf)
+ {
+ CMapStringToString mapStr;
+ StartTokenParsing (buf);
+ g_qeglobals.d_num_entities = 0;
+
+ // Timo
+ // will be used in Entity_Parse to detect if a conversion between brush formats is needed
+ g_qeglobals.bNeedConvert = false;
+ g_qeglobals.bOldBrushes = false;
+ g_qeglobals.bPrimitBrushes = false;
+
+ while (1)
+ {
+
+ // use the selected brushes list as it's handy
+ //ent = Entity_Parse (false, &selected_brushes);
+ ent = Entity_Parse (false, &active_brushes);
+ if (!ent)
+ break;
+ //end entity for undo
+ Undo_EndEntity(ent);
+ //end brushes for undo
+ for(b = ent->brushes.onext; b && b != &ent->brushes; b = b->onext)
+ {
+ Undo_EndBrush(b);
+ }
+
+ if (!strcmp(ValueForKey (ent, "classname"), "worldspawn"))
+ {
+ // world brushes need to be added to the current world entity
+
+ b=ent->brushes.onext;
+ while (b && b != &ent->brushes)
+ {
+ brush_t* bNext = b->onext;
+ Entity_UnlinkBrush(b);
+ Entity_LinkBrush(world_entity, b);
+ ptrs.Add(b);
+ b = bNext;
+ }
+ }
+ else
+ {
+ // the following bit remaps conflicting target/targetname key/value pairs
+ CString str = ValueForKey(ent, "target");
+ CString strKey;
+ CString strTarget("");
+ if (str.GetLength() > 0)
+ {
+ if (FindEntity("target", str.GetBuffer(0)))
+ {
+ if (!mapStr.Lookup(str, strKey))
+ {
+ UniqueTargetName(strKey);
+ mapStr.SetAt(str, strKey);
+ }
+ strTarget = strKey;
+ SetKeyValue(ent, "target", strTarget.GetBuffer(0));
+ }
+ }
+ str = ValueForKey(ent, "targetname");
+ if (str.GetLength() > 0)
+ {
+ if (FindEntity("targetname", str.GetBuffer(0)))
+ {
+ if (!mapStr.Lookup(str, strKey))
+ {
+ UniqueTargetName(strKey);
+ mapStr.SetAt(str, strKey);
+ }
+ SetKeyValue(ent, "targetname", strKey.GetBuffer(0));
+ }
+ }
+ //if (strTarget.GetLength() > 0)
+ // SetKeyValue(ent, "target", strTarget.GetBuffer(0));
+
+ // add the entity to the end of the entity list
+ ent->next = &entities;
+ ent->prev = entities.prev;
+ entities.prev->next = ent;
+ entities.prev = ent;
+ g_qeglobals.d_num_entities++;
+
+ for (b=ent->brushes.onext ; b != &ent->brushes ; b=b->onext)
+ {
+ ptrs.Add(b);
+ }
+ }
+ }
+ }
+
+ //::ShowWindow(g_qeglobals.d_hwndEntity, FALSE);
+ //::LockWindowUpdate(g_qeglobals.d_hwndEntity);
+ g_bScreenUpdates = false;
+ for (int i = 0; i < ptrs.GetSize(); i++)
+ {
+ Brush_Build(reinterpret_cast<brush_t*>(ptrs[i]), true, false);
+ Select_Brush(reinterpret_cast<brush_t*>(ptrs[i]), true, false);
+ }
+ //::LockWindowUpdate(NULL);
+ g_bScreenUpdates = true;
+
+ ptrs.RemoveAll();
+
+ // reset the "need conversion" flag
+ // conversion to the good format done in Map_BuildBrushData
+ g_qeglobals.bNeedConvert=false;
+
+ Sys_UpdateWindows (W_ALL);
+ //Sys_MarkMapModified();
+ modified = true;
+
+ Undo_End();
+
+}
+
+
+//
+//================
+//Map_ImportFile
+//================
+//
+void Map_ImportFile (char *filename)
+{
+ char* buf;
+ char temp[1024];
+ Sys_BeginWait ();
+ QE_ConvertDOSToUnixName( temp, filename );
+ if (LoadFile (filename, (void **)&buf) != -1)
+ {
+ Map_ImportBuffer(buf);
+ free(buf);
+ Map_BuildBrushData();
+ }
+ Sys_UpdateWindows (W_ALL);
+ modified = true;
+ Sys_EndWait();
+}
+
+//
+//===========
+//Map_SaveSelected
+//===========
+//
+// Saves selected world brushes and whole entities with partial/full selections
+//
+void Map_SaveSelected(char* pFilename)
+{
+ entity_t *e, *next;
+ FILE *f;
+ char temp[1024];
+ int count;
+
+ QE_ConvertDOSToUnixName(temp, pFilename);
+ f = fopen(pFilename, "w");
+
+ if (!f)
+ {
+ Sys_Printf ("ERROR!!!! Couldn't open %s\n", pFilename);
+ return;
+ }
+
+ // write world entity first
+ Entity_WriteSelected(world_entity, f);
+
+ // then write all other ents
+ count = 1;
+ for (e=entities.next ; e != &entities ; e=next)
+ {
+ fprintf (f, "// entity %i\n", count);
+ count++;
+ Entity_WriteSelected(e, f);
+ next = e->next;
+ }
+ fclose (f);
+}
+
+
+//
+//===========
+//Map_SaveSelected
+//===========
+//
+// Saves selected world brushes and whole entities with partial/full selections
+//
+void Map_SaveSelected(CMemFile* pMemFile, CMemFile* pPatchFile)
+{
+ entity_t *e, *next;
+ int count;
+ CString strTemp;
+
+ // write world entity first
+ Entity_WriteSelected(world_entity, pMemFile);
+
+ // then write all other ents
+ count = 1;
+ for (e=entities.next ; e != &entities ; e=next)
+ {
+ MemFile_fprintf(pMemFile, "// entity %i\n", count);
+ count++;
+ Entity_WriteSelected(e, pMemFile);
+ next = e->next;
+ }
+
+ //if (pPatchFile)
+ // Patch_WriteFile(pPatchFile);
+}
+
+
+void MemFile_fprintf(CMemFile* pMemFile, const char* pText, ...)
+{
+ char Buffer[4096];
+ va_list args;
+ va_start (args,pText);
+ vsprintf(Buffer, pText, args);
+ pMemFile->Write(Buffer, strlen(Buffer));
+} \ No newline at end of file
diff --git a/q3radiant/MAP.H b/q3radiant/MAP.H
new file mode 100755
index 0000000..8c1c070
--- /dev/null
+++ b/q3radiant/MAP.H
@@ -0,0 +1,59 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// map.h -- the state of the current world that all views are displaying
+
+extern char currentmap[1024];
+
+// head/tail of doubly linked lists
+extern brush_t active_brushes; // brushes currently being displayed
+extern brush_t selected_brushes; // highlighted
+
+
+extern CPtrArray& g_ptrSelectedFaces;
+extern CPtrArray& g_ptrSelectedFaceBrushes;
+//extern face_t *selected_face;
+//extern brush_t *selected_face_brush;
+extern brush_t filtered_brushes; // brushes that have been filtered or regioned
+
+extern entity_t entities;
+extern entity_t *world_entity; // the world entity is NOT included in
+ // the entities chain
+
+extern qboolean modified; // for quit confirmations
+
+extern vec3_t region_mins, region_maxs;
+extern qboolean region_active;
+
+void Map_LoadFile (char *filename);
+void Map_SaveFile (char *filename, qboolean use_region);
+void Map_New (void);
+void Map_BuildBrushData(void);
+
+void Map_RegionOff (void);
+void Map_RegionXY (void);
+void Map_RegionTallBrush (void);
+void Map_RegionBrush (void);
+void Map_RegionSelectedBrushes (void);
+qboolean Map_IsBrushFiltered (brush_t *b);
+
+void Map_SaveSelected(CMemFile* pMemFile, CMemFile* pPatchFile = NULL);
+void Map_ImportBuffer (char* buf);
diff --git a/q3radiant/MATHLIB.CPP b/q3radiant/MATHLIB.CPP
new file mode 100755
index 0000000..d112578
--- /dev/null
+++ b/q3radiant/MATHLIB.CPP
@@ -0,0 +1,311 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// mathlib.c -- math primitives
+
+#include "stdafx.h"
+#include "cmdlib.h"
+#include "mathlib.h"
+
+vec3_t vec3_origin = {0.0f,0.0f,0.0f};
+
+
+float VectorLength(vec3_t v)
+{
+ int i;
+ float length;
+
+ length = 0.0f;
+ for (i=0 ; i< 3 ; i++)
+ length += v[i]*v[i];
+ length = (float)sqrt (length);
+
+ return length;
+}
+
+qboolean VectorCompare (vec3_t v1, vec3_t v2)
+{
+ int i;
+
+ for (i=0 ; i<3 ; i++)
+ if (fabs(v1[i]-v2[i]) > EQUAL_EPSILON)
+ return false;
+
+ return true;
+}
+
+vec_t Q_rint (vec_t in)
+{
+ if (g_PrefsDlg.m_bNoClamp)
+ return in;
+ else
+ return (float)floor (in + 0.5);
+}
+
+void VectorMA (vec3_t va, float scale, vec3_t vb, vec3_t vc)
+{
+ vc[0] = va[0] + scale*vb[0];
+ vc[1] = va[1] + scale*vb[1];
+ vc[2] = va[2] + scale*vb[2];
+}
+
+void CrossProduct (vec3_t v1, vec3_t v2, vec3_t cross)
+{
+ cross[0] = v1[1]*v2[2] - v1[2]*v2[1];
+ cross[1] = v1[2]*v2[0] - v1[0]*v2[2];
+ cross[2] = v1[0]*v2[1] - v1[1]*v2[0];
+}
+
+vec_t _DotProduct (vec3_t v1, vec3_t v2)
+{
+ return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2];
+}
+
+void _VectorSubtract (vec3_t va, vec3_t vb, vec3_t out)
+{
+ out[0] = va[0]-vb[0];
+ out[1] = va[1]-vb[1];
+ out[2] = va[2]-vb[2];
+}
+
+void _VectorAdd (vec3_t va, vec3_t vb, vec3_t out)
+{
+ out[0] = va[0]+vb[0];
+ out[1] = va[1]+vb[1];
+ out[2] = va[2]+vb[2];
+}
+
+void _VectorCopy (vec3_t in, vec3_t out)
+{
+ out[0] = in[0];
+ out[1] = in[1];
+ out[2] = in[2];
+}
+
+vec_t VectorNormalize (vec3_t v)
+{
+ int i;
+ float length;
+
+ length = 0.0f;
+ for (i=0 ; i< 3 ; i++)
+ length += v[i]*v[i];
+ length = (float)sqrt (length);
+ if (length == 0)
+ return (vec_t)0;
+
+ for (i=0 ; i< 3 ; i++)
+ v[i] /= length;
+
+ return length;
+}
+
+void VectorInverse (vec3_t v)
+{
+ v[0] = -v[0];
+ v[1] = -v[1];
+ v[2] = -v[2];
+}
+
+void VectorScale (vec3_t v, vec_t scale, vec3_t out)
+{
+ out[0] = v[0] * scale;
+ out[1] = v[1] * scale;
+ out[2] = v[2] * scale;
+}
+
+
+void VectorRotate (vec3_t vIn, vec3_t vRotation, vec3_t out)
+{
+ vec3_t vWork, va;
+ VectorCopy(vIn, va);
+ VectorCopy(va, vWork);
+ int nIndex[3][2];
+ nIndex[0][0] = 1; nIndex[0][1] = 2;
+ nIndex[1][0] = 2; nIndex[1][1] = 0;
+ nIndex[2][0] = 0; nIndex[2][1] = 1;
+
+ for (int i = 0; i < 3; i++)
+ {
+ if (vRotation[i] != 0)
+ {
+ double dAngle = vRotation[i] * Q_PI / 180.0;
+ double c = cos(dAngle);
+ double s = sin(dAngle);
+ vWork[nIndex[i][0]] = va[nIndex[i][0]] * c - va[nIndex[i][1]] * s;
+ vWork[nIndex[i][1]] = va[nIndex[i][0]] * s + va[nIndex[i][1]] * c;
+ }
+ VectorCopy(vWork, va);
+ }
+ VectorCopy(vWork, out);
+}
+
+void VectorRotate (vec3_t vIn, vec3_t vRotation, vec3_t vOrigin, vec3_t out)
+{
+ vec3_t vTemp, vTemp2;
+ VectorSubtract(vIn, vOrigin, vTemp);
+ VectorRotate(vTemp, vRotation, vTemp2);
+ VectorAdd(vTemp2, vOrigin, out);
+}
+
+void VectorPolar(vec3_t v, float radius, float theta, float phi)
+{
+ v[0]=float(radius * cos(theta) * cos(phi));
+ v[1]=float(radius * sin(theta) * cos(phi));
+ v[2]=float(radius * sin(phi));
+}
+
+void VectorSnap(vec3_t v)
+{
+ for (int i = 0; i < 3; i++)
+ {
+ v[i] = floor (v[i] + 0.5);
+ }
+}
+
+
+void _Vector5Add (vec5_t va, vec5_t vb, vec5_t out)
+{
+ out[0] = va[0]+vb[0];
+ out[1] = va[1]+vb[1];
+ out[2] = va[2]+vb[2];
+ out[3] = va[3]+vb[3];
+ out[4] = va[4]+vb[4];
+}
+
+void _Vector5Scale (vec5_t v, vec_t scale, vec5_t out)
+{
+ out[0] = v[0] * scale;
+ out[1] = v[1] * scale;
+ out[2] = v[2] * scale;
+ out[3] = v[3] * scale;
+ out[4] = v[4] * scale;
+}
+
+void _Vector53Copy (vec5_t in, vec3_t out)
+{
+ out[0] = in[0];
+ out[1] = in[1];
+ out[2] = in[2];
+}
+
+// NOTE: added these from Ritual's Q3Radiant
+void ClearBounds (vec3_t mins, vec3_t maxs)
+{
+ mins[0] = mins[1] = mins[2] = 99999;
+ maxs[0] = maxs[1] = maxs[2] = -99999;
+}
+
+void AddPointToBounds (vec3_t v, vec3_t mins, vec3_t maxs)
+{
+ int i;
+ vec_t val;
+
+ for (i=0 ; i<3 ; i++)
+ {
+ val = v[i];
+ if (val < mins[i])
+ mins[i] = val;
+ if (val > maxs[i])
+ maxs[i] = val;
+ }
+}
+
+#define PITCH 0 // up / down
+#define YAW 1 // left / right
+#define ROLL 2 // fall over
+#ifndef M_PI
+#define M_PI 3.14159265358979323846 // matches value in gcc v2 math.h
+#endif
+
+void AngleVectors (vec3_t angles, vec3_t forward, vec3_t right, vec3_t up)
+{
+ float angle;
+ static float sr, sp, sy, cr, cp, cy;
+ // static to help MS compiler fp bugs
+
+ angle = angles[YAW] * (M_PI*2 / 360);
+ sy = sin(angle);
+ cy = cos(angle);
+ angle = angles[PITCH] * (M_PI*2 / 360);
+ sp = sin(angle);
+ cp = cos(angle);
+ angle = angles[ROLL] * (M_PI*2 / 360);
+ sr = sin(angle);
+ cr = cos(angle);
+
+ if (forward)
+ {
+ forward[0] = cp*cy;
+ forward[1] = cp*sy;
+ forward[2] = -sp;
+ }
+ if (right)
+ {
+ right[0] = -sr*sp*cy+cr*sy;
+ right[1] = -sr*sp*sy-cr*cy;
+ right[2] = -sr*cp;
+ }
+ if (up)
+ {
+ up[0] = cr*sp*cy+sr*sy;
+ up[1] = cr*sp*sy-sr*cy;
+ up[2] = cr*cp;
+ }
+}
+
+void VectorToAngles( vec3_t vec, vec3_t angles )
+{
+ float forward;
+ float yaw, pitch;
+
+ if ( ( vec[ 0 ] == 0 ) && ( vec[ 1 ] == 0 ) )
+ {
+ yaw = 0;
+ if ( vec[ 2 ] > 0 )
+ {
+ pitch = 90;
+ }
+ else
+ {
+ pitch = 270;
+ }
+ }
+ else
+ {
+ yaw = atan2( vec[ 1 ], vec[ 0 ] ) * 180 / M_PI;
+ if ( yaw < 0 )
+ {
+ yaw += 360;
+ }
+
+ forward = ( float )sqrt( vec[ 0 ] * vec[ 0 ] + vec[ 1 ] * vec[ 1 ] );
+ pitch = atan2( vec[ 2 ], forward ) * 180 / M_PI;
+ if ( pitch < 0 )
+ {
+ pitch += 360;
+ }
+ }
+
+ angles[ 0 ] = pitch;
+ angles[ 1 ] = yaw;
+ angles[ 2 ] = 0;
+}
diff --git a/q3radiant/MATHLIB.H b/q3radiant/MATHLIB.H
new file mode 100755
index 0000000..6119be8
--- /dev/null
+++ b/q3radiant/MATHLIB.H
@@ -0,0 +1,86 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __MATHLIB__
+#define __MATHLIB__
+
+// mathlib.h
+
+#include <math.h>
+
+typedef float vec_t;
+typedef vec_t vec3_t[3];
+typedef vec_t vec5_t[5];
+
+#define SIDE_FRONT 0
+#define SIDE_ON 2
+#define SIDE_BACK 1
+#define SIDE_CROSS -2
+
+#define Q_PI 3.14159265358979323846
+
+extern vec3_t vec3_origin;
+
+#define EQUAL_EPSILON 0.001
+
+qboolean VectorCompare (vec3_t v1, vec3_t v2);
+
+#define DotProduct(x,y) (x[0]*y[0]+x[1]*y[1]+x[2]*y[2])
+#define VectorSubtract(a,b,c) {c[0]=a[0]-b[0];c[1]=a[1]-b[1];c[2]=a[2]-b[2];}
+#define VectorAdd(a,b,c) {c[0]=a[0]+b[0];c[1]=a[1]+b[1];c[2]=a[2]+b[2];}
+#define VectorCopy(a,b) {b[0]=a[0];b[1]=a[1];b[2]=a[2];}
+#define VectorSet(v, a, b, c) {v[0]=a;v[1]=b;v[2]=c;}
+
+vec_t Q_rint (vec_t in);
+vec_t _DotProduct (vec3_t v1, vec3_t v2);
+void _VectorSubtract (vec3_t va, vec3_t vb, vec3_t out);
+void _VectorAdd (vec3_t va, vec3_t vb, vec3_t out);
+void _VectorCopy (vec3_t in, vec3_t out);
+
+float VectorLength(vec3_t v);
+
+void VectorMA (vec3_t va, float scale, vec3_t vb, vec3_t vc);
+
+void CrossProduct (vec3_t v1, vec3_t v2, vec3_t cross);
+vec_t VectorNormalize (vec3_t v);
+void VectorInverse (vec3_t v);
+void VectorScale (vec3_t v, vec_t scale, vec3_t out);
+void VectorPolar(vec3_t v, float radius, float theta, float phi);
+void VectorSnap(vec3_t v);
+
+void _Vector53Copy (vec5_t in, vec3_t out);
+void _Vector5Scale (vec5_t v, vec_t scale, vec5_t out);
+void _Vector5Add (vec5_t va, vec5_t vb, vec5_t out);
+
+// NOTE: added these from Ritual's Q3Radiant
+void ClearBounds (vec3_t mins, vec3_t maxs);
+void AddPointToBounds (vec3_t v, vec3_t mins, vec3_t maxs);
+
+void AngleVectors (vec3_t angles, vec3_t forward, vec3_t right, vec3_t up);
+void VectorToAngles( vec3_t vec, vec3_t angles );
+#define VectorClear(x) {x[0] = x[1] = x[2] = 0;}
+
+#define ZERO_EPSILON 1.0E-6
+#define RAD2DEG( a ) ( ( (a) * 180.0f ) / Q_PI )
+#define DEG2RAD( a ) ( ( (a) * Q_PI ) / 180.0f )
+
+
+#endif
diff --git a/q3radiant/MRU.CPP b/q3radiant/MRU.CPP
new file mode 100755
index 0000000..d675362
--- /dev/null
+++ b/q3radiant/MRU.CPP
@@ -0,0 +1,671 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//*************************************************************
+// File name: mru.c
+//
+// Description:
+//
+// Routines for MRU support
+//
+// Development Team:
+//
+// Gilles Vollant (100144.2636@compuserve.com)
+//
+//*************************************************************
+
+#include "stdafx.h"
+#include <windows.h>
+#include <windowsx.h>
+#include <string.h>
+
+#include "mru.h"
+// CreateMruMenu : MRUMENU constructor
+// wNbLruShowInit : nb of item showed in menu
+// wNbLruMenuInit : nb of item stored in memory
+// wMaxSizeLruItemInit : size max. of filename
+
+
+//*************************************************************
+//
+// CreateMruMenu()
+//
+// Purpose:
+//
+// Allocate and Initialize an MRU and return a pointer on it
+//
+//
+// Parameters:
+//
+// WORD wNbLruShowInit - Maximum number of item displayed on menu
+// WORD wNbLruMenuInit - Maximum number of item stored in memory
+// WORD wMaxSizeLruItemInit - Maximum size of an item (ie size of pathname)
+// WORD wIdMruInit - ID of the first item in the menu (default:IDMRU)
+//
+//
+// Return: (LPMRUMENU)
+//
+// Pointer on a MRUMENU structure, used by other function
+//
+//
+// Comments:
+// wNbLruShowInit <= wNbLruMenuInit
+//
+//
+// History: Date Author Comment
+// 09/24/94 G. Vollant Created
+//
+//*************************************************************
+
+LPMRUMENU CreateMruMenu (WORD wNbLruShowInit,
+ WORD wNbLruMenuInit,WORD wMaxSizeLruItemInit,WORD wIdMruInit)
+{
+LPMRUMENU lpMruMenu;
+ lpMruMenu = (LPMRUMENU)GlobalAllocPtr(GHND,sizeof(MRUMENU));
+
+ lpMruMenu->wNbItemFill = 0;
+ lpMruMenu->wNbLruMenu = wNbLruMenuInit;
+ lpMruMenu->wNbLruShow = wNbLruShowInit;
+ lpMruMenu->wIdMru = wIdMruInit;
+ lpMruMenu->wMaxSizeLruItem = wMaxSizeLruItemInit;
+ lpMruMenu->lpMRU = (LPSTR)GlobalAllocPtr(GHND,
+ lpMruMenu->wNbLruMenu*(UINT)lpMruMenu->wMaxSizeLruItem);
+ if (lpMruMenu->lpMRU == NULL)
+ {
+ GlobalFreePtr(lpMruMenu);
+ lpMruMenu = NULL;
+ }
+ return lpMruMenu;
+}
+
+//*************************************************************
+//
+// CreateMruMenuDefault()
+//
+// Purpose:
+//
+// Allocate and Initialize an MRU and return a pointer on it
+// Use default parameter
+//
+//
+// Parameters:
+//
+//
+// Return: (LPMRUMENU)
+//
+// Pointer on a MRUMENU structure, used by other function
+//
+//
+// Comments:
+//
+//
+// History: Date Author Comment
+// 09/24/94 G. Vollant Created
+//
+//*************************************************************
+
+LPMRUMENU CreateMruMenuDefault()
+{
+ return CreateMruMenu (NBMRUMENUSHOW,NBMRUMENU,MAXSIZEMRUITEM,IDMRU);
+}
+
+
+//*************************************************************
+//
+// DeleteMruMenu()
+//
+// Purpose:
+// Destructor :
+// Clean and free a MRUMENU structure
+//
+// Parameters:
+//
+// LPMRUMENU lpMruMenu - pointer on MRUMENU, allocated
+// by CreateMruMenu() or CreateMruMenuDefault()
+//
+//
+// Return: void
+//
+//
+// Comments:
+//
+//
+// History: Date Author Comment
+// 09/24/94 G. Vollant Created
+//
+//*************************************************************
+void DeleteMruMenu(LPMRUMENU lpMruMenu)
+{
+ GlobalFreePtr(lpMruMenu->lpMRU);
+ GlobalFreePtr(lpMruMenu);
+}
+
+//*************************************************************
+//
+// SetNbLruShow()
+//
+// Purpose:
+// Change the maximum number of item displayed on menu
+//
+// Parameters:
+// LPMRUMENU lpMruMenu - pointer on MRUMENU
+// WORD wNbLruShowInit - Maximum number of item displayed on menu
+//
+//
+// Return: void
+//
+//
+// Comments:
+//
+//
+// History: Date Author Comment
+// 09/24/94 G. Vollant Created
+//
+//*************************************************************
+void SetNbLruShow (LPMRUMENU lpMruMenu,WORD wNbLruShowInit)
+{
+ lpMruMenu->wNbLruShow = min(wNbLruShowInit,lpMruMenu->wNbLruMenu);
+}
+
+//*************************************************************
+//
+// SetMenuItem()
+//
+// Purpose:
+// Set the filename of an item
+//
+// Parameters:
+// LPMRUMENU lpMruMenu - pointer on MRUMENU
+// WORD wItem - Number of Item to set, zero based
+// LPSTR lpItem - String, contain the filename of the item
+//
+//
+// Return: (BOOL)
+// TRUE - Function run successfully
+// FALSE - Function don't run successfully
+//
+//
+// Comments:
+// used when load .INI or reg database
+//
+// History: Date Author Comment
+// 09/24/94 G. Vollant Created
+//
+//*************************************************************
+BOOL SetMenuItem (LPMRUMENU lpMruMenu,WORD wItem,LPSTR lpItem)
+{
+ if (wItem >= NBMRUMENU)
+ return FALSE;
+ _fstrncpy((lpMruMenu->lpMRU) +
+ ((lpMruMenu->wMaxSizeLruItem) * (UINT)wItem),
+ lpItem,lpMruMenu->wMaxSizeLruItem-1);
+ lpMruMenu->wNbItemFill = max(lpMruMenu->wNbItemFill,wItem+1);
+ return TRUE;
+}
+
+//*************************************************************
+//
+// GetMenuItem()
+//
+// Purpose:
+// Get the filename of an item
+//
+// Parameters:
+// LPMRUMENU lpMruMenu - pointer on MRUMENU
+// WORD wItem - Number of Item to set, zero based
+// BOOL fIDMBased - TRUE : wItem is based on ID menu item
+// FALSE : wItem is zero-based
+// LPSTR lpItem - String where the filename of the item will be
+// stored by GetMenuItem()
+// UINT uiSize - Size of the lpItem buffer
+//
+//
+// Return: (BOOL)
+// TRUE - Function run successfully
+// FALSE - Function don't run successfully
+//
+//
+// Comments:
+// Used for saving in .INI or reg database, or when user select
+// an MRU in File menu
+//
+// History: Date Author Comment
+// 09/24/94 G. Vollant Created
+//
+//*************************************************************
+BOOL GetMenuItem (LPMRUMENU lpMruMenu,WORD wItem,
+ BOOL fIDMBased,LPSTR lpItem,UINT uiSize)
+{
+ if (fIDMBased)
+ wItem -= (lpMruMenu->wIdMru + 1);
+ if (wItem >= lpMruMenu->wNbItemFill)
+ return FALSE;
+ _fstrncpy(lpItem,(lpMruMenu->lpMRU) +
+ ((lpMruMenu->wMaxSizeLruItem) * (UINT)(wItem)),uiSize);
+ *(lpItem+uiSize-1) = '\0';
+ return TRUE;
+}
+
+//*************************************************************
+//
+// AddNewItem()
+//
+// Purpose:
+// Add an item at the begin of the list
+//
+// Parameters:
+// LPMRUMENU lpMruMenu - pointer on MRUMENU
+// LPSTR lpItem - String contain the filename to add
+//
+// Return: (BOOL)
+// TRUE - Function run successfully
+// FALSE - Function don't run successfully
+//
+//
+// Comments:
+// Used when used open a file (using File Open common
+// dialog, Drag and drop or MRU)
+//
+// History: Date Author Comment
+// 09/24/94 G. Vollant Created
+//
+//*************************************************************
+void AddNewItem (LPMRUMENU lpMruMenu,LPSTR lpItem)
+{
+WORD i,j;
+ for (i=0;i<lpMruMenu->wNbItemFill;i++)
+ if (lstrcmpi(lpItem,(lpMruMenu->lpMRU) +
+ ((lpMruMenu->wMaxSizeLruItem) * (UINT)i)) == 0)
+ {
+ // Shift the other items
+ for (j=i;j>0;j--)
+ lstrcpy((lpMruMenu->lpMRU) + (lpMruMenu->wMaxSizeLruItem * (UINT)j),
+ (lpMruMenu->lpMRU) + (lpMruMenu->wMaxSizeLruItem * (UINT)(j-1)));
+ _fstrncpy(lpMruMenu->lpMRU,lpItem,lpMruMenu->wMaxSizeLruItem-1);
+ return ;
+ }
+ lpMruMenu->wNbItemFill = min(lpMruMenu->wNbItemFill+1,lpMruMenu->wNbLruMenu);
+ for (i=lpMruMenu->wNbItemFill-1;i>0;i--)
+ lstrcpy(lpMruMenu->lpMRU + (lpMruMenu->wMaxSizeLruItem * (UINT)i),
+ lpMruMenu->lpMRU + (lpMruMenu->wMaxSizeLruItem * (UINT)(i-1)));
+ _fstrncpy(lpMruMenu->lpMRU,lpItem,lpMruMenu->wMaxSizeLruItem-1);
+}
+
+//*************************************************************
+//
+// DelMenuItem()
+//
+// Purpose:
+// Delete an item
+//
+// Parameters:
+// LPMRUMENU lpMruMenu - pointer on MRUMENU
+// WORD wItem - Number of Item to set, zero based
+// BOOL fIDMBased - TRUE : wItem is based on ID menu item
+// FALSE : wItem is zero-based
+//
+// Return: (BOOL)
+// TRUE - Function run successfully
+// FALSE - Function don't run successfully
+//
+//
+// Comments:
+// Used when used open a file, using MRU, and when an error
+// occured (by example, when file was deleted)
+//
+// History: Date Author Comment
+// 09/24/94 G. Vollant Created
+//
+//*************************************************************
+BOOL DelMenuItem(LPMRUMENU lpMruMenu,WORD wItem,BOOL fIDMBased)
+{
+WORD i;
+ if (fIDMBased)
+ wItem -= (lpMruMenu->wIdMru + 1);
+ if (lpMruMenu->wNbItemFill <= wItem)
+ return FALSE;
+ lpMruMenu->wNbItemFill--;
+ for (i=wItem;i<lpMruMenu->wNbItemFill;i++)
+ lstrcpy(lpMruMenu->lpMRU + (lpMruMenu->wMaxSizeLruItem * (UINT)i),
+ lpMruMenu->lpMRU + (lpMruMenu->wMaxSizeLruItem * (UINT)(i+1)));
+ return TRUE;
+}
+
+//*************************************************************
+//
+// PlaceMenuMRUItem()
+//
+// Purpose:
+// Add MRU at the end of a menu
+//
+// Parameters:
+// LPMRUMENU lpMruMenu - pointer on MRUMENU
+// HMENU hMenu - Handle of menu where MRU must be added
+// UINT uiItem - Item of menu entry where MRU must be added
+//
+// Return: void
+//
+//
+// Comments:
+// Used MRU is modified, for refresh the File menu
+//
+// History: Date Author Comment
+// 09/24/94 G. Vollant Created
+//
+//*************************************************************
+void PlaceMenuMRUItem(LPMRUMENU lpMruMenu,HMENU hMenu,UINT uiItem)
+{
+int i;
+WORD wNbShow;
+ if (hMenu == NULL)
+ return;
+ // remove old MRU in menu
+ for (i=0;i<=(int)(lpMruMenu->wNbLruMenu);i++)
+ RemoveMenu(hMenu,i+lpMruMenu->wIdMru,MF_BYCOMMAND);
+
+ if (lpMruMenu->wNbItemFill == 0)
+ return;
+
+ // If they are item, insert a separator before the files
+ InsertMenu(hMenu,uiItem,MF_SEPARATOR,lpMruMenu->wIdMru,NULL);
+
+ wNbShow = min(lpMruMenu->wNbItemFill,lpMruMenu->wNbLruShow);
+ for (i=(int)wNbShow-1;i>=0;i--)
+ {
+ LPSTR lpTxt;
+ if (lpTxt = (LPSTR)GlobalAllocPtr(GHND,lpMruMenu->wMaxSizeLruItem + 20))
+ {
+ wsprintf(lpTxt,"&%lu %s",
+ (DWORD)(i+1),lpMruMenu->lpMRU + (lpMruMenu->wMaxSizeLruItem*(UINT)i));
+ InsertMenu(hMenu,(((WORD)i)!=(wNbShow-1)) ? (lpMruMenu->wIdMru+i+2) : lpMruMenu->wIdMru,
+ MF_STRING,lpMruMenu->wIdMru+i+1,lpTxt);
+ GlobalFreePtr(lpTxt);
+ }
+ }
+
+}
+
+///////////////////////////////////////////
+
+
+
+//*************************************************************
+//
+// SaveMruInIni()
+//
+// Purpose:
+// Save MRU in a private .INI
+//
+// Parameters:
+// LPMRUMENU lpMruMenu - pointer on MRUMENU
+// LPSTR lpszSection - Points to a null-terminated string containing
+// the name of the section
+// LPSTR lpszFile - Points to a null-terminated string that names
+// the initialization file.
+//
+// Return: (BOOL)
+// TRUE - Function run successfully
+// FALSE - Function don't run successfully
+//
+//
+// Comments:
+// See WritePrivateProfileString API for more info on lpszSection and lpszFile
+//
+// History: Date Author Comment
+// 09/24/94 G. Vollant Created
+//
+//*************************************************************
+BOOL SaveMruInIni(LPMRUMENU lpMruMenu,LPSTR lpszSection,LPSTR lpszFile)
+{
+LPSTR lpTxt;
+WORD i;
+
+ lpTxt = (LPSTR)GlobalAllocPtr(GHND,lpMruMenu->wMaxSizeLruItem + 20);
+ if (lpTxt == NULL)
+ return FALSE;
+
+ for (i=0;i<lpMruMenu->wNbLruMenu;i++)
+ {
+ char szEntry[16];
+ wsprintf(szEntry,"File%lu",(DWORD)i+1);
+ if (!GetMenuItem(lpMruMenu,i,FALSE,lpTxt,lpMruMenu->wMaxSizeLruItem + 10))
+ *lpTxt = '\0';
+ WritePrivateProfileString(lpszSection,szEntry,lpTxt,lpszFile);
+ }
+ GlobalFreePtr(lpTxt);
+ WritePrivateProfileString(NULL,NULL,NULL,lpszFile); // flush cache
+ return TRUE;
+}
+
+
+//*************************************************************
+//
+// LoadMruInIni()
+//
+// Purpose:
+// Load MRU from a private .INI
+//
+// Parameters:
+// LPMRUMENU lpMruMenu - pointer on MRUMENU
+// LPSTR lpszSection - Points to a null-terminated string containing
+// the name of the section
+// LPSTR lpszFile - Points to a null-terminated string that names
+// the initialization file.
+//
+// Return: (BOOL)
+// TRUE - Function run successfully
+// FALSE - Function don't run successfully
+//
+//
+// Comments:
+// See GetPrivateProfileString API for more info on lpszSection and lpszFile
+//
+// History: Date Author Comment
+// 09/24/94 G. Vollant Created
+//
+//*************************************************************
+BOOL LoadMruInIni(LPMRUMENU lpMruMenu,LPSTR lpszSection,LPSTR lpszFile)
+{
+LPSTR lpTxt;
+WORD i;
+ lpTxt = (LPSTR)GlobalAllocPtr(GHND,lpMruMenu->wMaxSizeLruItem + 20);
+ if (lpTxt == NULL)
+ return FALSE;
+
+ for (i=0;i<lpMruMenu->wNbLruMenu;i++)
+ {
+ char szEntry[16];
+
+ wsprintf(szEntry,"File%lu",(DWORD)i+1);
+ GetPrivateProfileString(lpszSection,szEntry,"",lpTxt,
+ lpMruMenu->wMaxSizeLruItem + 10,lpszFile);
+ if (*lpTxt == '\0')
+ break;
+ SetMenuItem(lpMruMenu,i,lpTxt);
+ }
+ GlobalFreePtr(lpTxt);
+ return TRUE;
+}
+
+#ifdef WIN32
+
+BOOL IsWin395OrHigher(void)
+{
+ WORD wVer;
+
+ wVer = LOWORD(GetVersion());
+ wVer = (((WORD)LOBYTE(wVer)) << 8) | (WORD)HIBYTE(wVer);
+
+ return (wVer >= 0x035F); // 5F = 95 dec
+}
+
+
+//*************************************************************
+//
+// SaveMruInReg()
+//
+// Purpose:
+// Save MRU in the registry
+//
+// Parameters:
+// LPMRUMENU lpMruMenu - pointer on MRUMENU
+// LPSTR lpszKey - Points to a null-terminated string
+// specifying the name of a key that
+// this function opens or creates.
+//
+// Return: (BOOL)
+// TRUE - Function run successfully
+// FALSE - Function don't run successfully
+//
+//
+// Comments:
+// Win32 function designed for Windows NT and Windows 95
+// See RegCreateKeyEx API for more info on lpszKey
+//
+// History: Date Author Comment
+// 09/24/94 G. Vollant Created
+//
+//*************************************************************
+BOOL SaveMruInReg(LPMRUMENU lpMruMenu,LPSTR lpszKey)
+{
+LPSTR lpTxt;
+WORD i;
+HKEY hCurKey;
+DWORD dwDisp;
+
+ lpTxt = (LPSTR)GlobalAllocPtr(GHND,lpMruMenu->wMaxSizeLruItem + 20);
+ if (lpTxt == NULL)
+ return FALSE;
+
+ RegCreateKeyEx(HKEY_CURRENT_USER,lpszKey,0,NULL,
+ REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS,NULL,&hCurKey,&dwDisp);
+
+ for (i=0;i<lpMruMenu->wNbLruMenu;i++)
+ {
+ char szEntry[16];
+ wsprintf(szEntry,"File%lu",(DWORD)i+1);
+ if (!GetMenuItem(lpMruMenu,i,FALSE,lpTxt,lpMruMenu->wMaxSizeLruItem + 10))
+ *lpTxt = '\0';
+ RegSetValueEx(hCurKey,szEntry,0,REG_SZ,(unsigned char*)lpTxt,lstrlen(lpTxt));
+ }
+ RegCloseKey(hCurKey);
+ GlobalFreePtr(lpTxt);
+ return TRUE;
+}
+
+//*************************************************************
+//
+// LoadMruInReg()
+//
+// Purpose:
+// Load MRU from the registry
+//
+// Parameters:
+// LPMRUMENU lpMruMenu - pointer on MRUMENU
+// LPSTR lpszKey - Points to a null-terminated string
+// specifying the name of a key that
+// this function opens or creates.
+//
+// Return: (BOOL)
+// TRUE - Function run successfully
+// FALSE - Function don't run successfully
+//
+//
+// Comments:
+// Win32 function designed for Windows NT and Windows 95
+// See RegOpenKeyEx API for more info on lpszKey
+//
+// History: Date Author Comment
+// 09/24/94 G. Vollant Created
+//
+//*************************************************************
+BOOL LoadMruInReg(LPMRUMENU lpMruMenu,LPSTR lpszKey)
+{
+LPSTR lpTxt;
+WORD i;
+HKEY hCurKey;
+DWORD dwType;
+ lpTxt = (LPSTR)GlobalAllocPtr(GHND,lpMruMenu->wMaxSizeLruItem + 20);
+ if (lpTxt == NULL)
+ return FALSE;
+
+ RegOpenKeyEx(HKEY_CURRENT_USER,lpszKey,0,KEY_READ,&hCurKey);
+
+
+ for (i=0;i<lpMruMenu->wNbLruMenu;i++)
+ {
+ char szEntry[16];
+ DWORD dwSizeBuf;
+ wsprintf(szEntry,"File%lu",(DWORD)i+1);
+ *lpTxt = '\0';
+ dwSizeBuf = lpMruMenu->wMaxSizeLruItem + 10;
+ RegQueryValueEx(hCurKey,szEntry,NULL,&dwType,(LPBYTE)lpTxt,&dwSizeBuf);
+ *(lpTxt+dwSizeBuf)='\0';
+ if (*lpTxt == '\0')
+ break;
+ SetMenuItem(lpMruMenu,i,lpTxt);
+ }
+ RegCloseKey(hCurKey);
+ GlobalFreePtr(lpTxt);
+ return TRUE;
+}
+
+
+//*************************************************************
+//
+// GetWin32Kind()
+//
+// Purpose:
+// Get the Win32 platform
+//
+// Parameters:
+//
+// Return: (WIN32KIND)
+// WINNT - Run under Windows NT
+// WIN32S - Run under Windows 3.1x + Win32s
+// WIN95ORGREATHER - Run under Windows 95
+//
+//
+// Comments:
+// Win32 function designed for Windows NT and Windows 95
+// See RegOpenKeyEx API for more info on lpszKey
+//
+// History: Date Author Comment
+// 09/24/94 G. Vollant Created
+//
+//*************************************************************
+WIN32KIND GetWin32Kind()
+{
+BOOL IsWin395OrHigher(void);
+
+ WORD wVer;
+
+ if ((GetVersion() & 0x80000000) == 0)
+ return WINNT;
+ wVer = LOWORD(GetVersion());
+ wVer = (((WORD)LOBYTE(wVer)) << 8) | (WORD)HIBYTE(wVer);
+
+ if (wVer >= 0x035F)
+ return WIN95ORGREATHER;
+ else
+ return WIN32S;
+}
+#endif
diff --git a/q3radiant/MRU.H b/q3radiant/MRU.H
new file mode 100755
index 0000000..e508ac7
--- /dev/null
+++ b/q3radiant/MRU.H
@@ -0,0 +1,100 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//*************************************************************
+// File name: mru.h
+//
+// Description:
+//
+// Header for MRU support
+//
+// Development Team:
+//
+// Gilles Vollant (100144.2636@compuserve.com)
+//
+//*************************************************************
+
+#ifndef __MRU_H__
+#define __MRU_H__
+
+#define NBMRUMENUSHOW 6 // Default number of MRU showed in the menu File
+#define NBMRUMENU 9 // Default number of MRU stored
+#define IDMRU 8000 // Default First ID of MRU
+#ifdef OFS_MAXPATHNAME
+#define MAXSIZEMRUITEM OFS_MAXPATHNAME
+#else
+#define MAXSIZEMRUITEM 128 // Default max size of an entry
+#endif
+
+typedef struct
+{
+WORD wNbItemFill;
+WORD wNbLruShow;
+WORD wNbLruMenu;
+WORD wMaxSizeLruItem;
+WORD wIdMru;
+LPSTR lpMRU;
+} MRUMENU;
+
+typedef MRUMENU FAR * LPMRUMENU;
+
+#ifdef __cplusplus
+LPMRUMENU CreateMruMenu (WORD wNbLruShowInit=NBMRUMENUSHOW,
+ WORD wNbLruMenuInit=NBMRUMENU,
+ WORD wMaxSizeLruItemInit=MAXSIZEMRUITEM,
+ WORD wIdMruInit=IDMRU);
+#else
+LPMRUMENU CreateMruMenu (WORD wNbLruShowInit,
+ WORD wNbLruMenuInit,
+ WORD wMaxSizeLruItemInit,
+ WORD wIdMruInit);
+#endif
+
+LPMRUMENU CreateMruMenuDefault();
+void DeleteMruMenu (LPMRUMENU lpMruMenu);
+
+void SetNbLruShow (LPMRUMENU lpMruMenu,WORD wNbLruShowInit);
+BOOL SetMenuItem (LPMRUMENU lpMruMenu,WORD wItem,
+ LPSTR lpItem);
+BOOL GetMenuItem (LPMRUMENU lpMruMenu,WORD wItem,
+ BOOL fIDMBased,LPSTR lpItem,UINT uiSize);
+BOOL DelMenuItem (LPMRUMENU lpMruMenu,WORD wItem,BOOL fIDMBased);
+void AddNewItem (LPMRUMENU lpMruMenu,LPSTR lpItem);
+void PlaceMenuMRUItem(LPMRUMENU lpMruMenu,HMENU hMenu,UINT uiItem);
+
+BOOL SaveMruInIni (LPMRUMENU lpMruMenu,LPSTR lpszSection,LPSTR lpszFile);
+BOOL LoadMruInIni (LPMRUMENU lpMruMenu,LPSTR lpszSection,LPSTR lpszFile);
+#ifdef WIN32
+BOOL SaveMruInReg (LPMRUMENU lpMruMenu,LPSTR lpszKey);
+BOOL LoadMruInReg (LPMRUMENU lpMruMenu,LPSTR lpszKey);
+
+typedef enum
+{
+WIN32S,
+WINNT,
+WIN95ORGREATHER
+} WIN32KIND;
+WIN32KIND GetWin32Kind();
+#endif
+
+
+//////////////////////////////////////////////////////////////
+#endif
diff --git a/q3radiant/MainFrm.cpp b/q3radiant/MainFrm.cpp
new file mode 100755
index 0000000..b148f4f
--- /dev/null
+++ b/q3radiant/MainFrm.cpp
@@ -0,0 +1,5224 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// MainFrm.cpp : implementation of the CMainFrame class
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "qe3.h"
+#include "ZWnd.h"
+#include "CamWnd.h"
+#include "TexWnd.h"
+#include "EditWnd.h"
+#include "entityw.h"
+#include "PrefsDlg.h"
+#include "MapInfo.h"
+#include "MainFrm.h"
+#include "RotateDlg.h"
+#include "EntityListDlg.h"
+#include "ScriptDlg.h"
+#include "NewProjDlg.h"
+#include "CommandsDlg.h"
+#include "ScaleDialog.h"
+#include "FindTextureDlg.h"
+#include "SurfaceDlg.h"
+#include "shlobj.h"
+#include "DialogTextures.h"
+#include "PatchDensityDlg.h"
+#include "DialogThick.h"
+#include "PatchDialog.h"
+#include "Undo.h"
+#include "NameDlg.h"
+#include "../libs/pakstuff.h"
+#include "splines/splines.h"
+#include "dlgcamera.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+
+// globals
+CString g_strAppPath; // holds the full path of the executable
+CEdit* g_pEdit = NULL; // used originally to make qe4 work with mfc.. still used
+CMainFrame* g_pParentWnd = NULL; // used to precast to CMainFrame
+CPrefsDlg g_Preferences; // global prefs instance
+CPrefsDlg& g_PrefsDlg = g_Preferences; // reference used throughout
+int g_nUpdateBits = 0; // window update flags
+bool g_bScreenUpdates = true; // whether window painting is active, used in a few places
+ // to disable updates for speed reasons
+ // both of the above should be made members of CMainFrame
+
+//bool g_bSnapToGrid = true; // early use, no longer in use, clamping pref will be used
+CString g_strProject; // holds the active project filename
+
+
+/////////////////////////////////////////////////////////////////////////////
+// CMainFrame
+
+// command mapping stuff
+//
+// m_strCommand is the command string
+// m_nKey is the windows VK_??? equivelant
+// m_nModifiers are key states as follows
+// bit
+// 0 - shift
+// 1 - alt
+// 2 - control
+// 4 - press only
+//
+#define SPEED_MOVE 32
+#define SPEED_TURN 22.5
+
+
+SCommandInfo g_Commands[] =
+{
+ {"ToggleOutlineDraw", 'J', 0x00, ID_SELECTION_NOOUTLINE},
+ {"CSGMerge", 'U', 0x04, ID_SELECTION_CSGMERGE},
+ {"CSGSubtract", 'U', 0x01, ID_SELECTION_CSGSUBTRACT},
+ {"ViewGroups", 'G', 0x00, ID_VIEW_GROUPS},
+ {"HideSelected", 'H', 0x00, ID_VIEW_HIDESHOW_HIDESELECTED},
+ {"ShowHidden", 'H', 0x01, ID_VIEW_HIDESHOW_SHOWHIDDEN},
+ {"BendMode", 'B', 0x00, ID_PATCH_BEND},
+ {"FitFace", 'B', 0x04, ID_FITFACE},
+ {"FitBrush", 'B', 0x01, ID_FITBRUSH},
+ {"FreezePatchVertices", 'F', 0x00, ID_CURVE_FREEZE},
+ {"UnFreezePatchVertices", 'F', 0x04, ID_CURVE_UNFREEZE},
+ {"UnFreezeAllPatchVertices", 'F', 0x05, ID_CURVE_UNFREEZEALL},
+ {"ViewTextures", 'T', 0, ID_VIEW_TEXTURE},
+ {"ThickenPatch", 'T', 0x04, ID_CURVE_THICKEN},
+ {"MakeOverlayPatch", 'Y', 0, ID_CURVE_OVERLAY_SET},
+ {"ClearPatchOverlays", 'Y', 0x02, ID_CURVE_OVERLAY_CLEAR},
+ {"SurfaceInspector", 'S', 0, ID_TEXTURES_INSPECTOR},
+ {"PatchInspector", 'S', 0x01, ID_PATCH_INSPECTOR},
+ {"ToggleShowPatches", 'P', 0x05, ID_CURVE_CYCLECAP},
+ {"ToggleShowPatches", 'P', 0x04, ID_VIEW_SHOWCURVES},
+ {"RedisperseRows", 'E', 0x04, ID_CURVE_REDISPERSE_ROWS},
+ {"RedisperseCols", 'E', 0x05, ID_CURVE_REDISPERSE_COLS},
+ {"InvertCurveTextureX", 'I', 0x05, ID_CURVE_NEGATIVETEXTUREY},
+ {"InvertCurveTextureY", 'I', 0x01, ID_CURVE_NEGATIVETEXTUREX},
+ {"InvertCurve", 'I', 0x04, ID_CURVE_NEGATIVE},
+ {"IncPatchColumn", VK_ADD, 0x05, ID_CURVE_INSERTCOLUMN},
+ {"IncPatchRow", VK_ADD, 0x04, ID_CURVE_INSERTROW},
+ {"DecPatchColumn", VK_SUBTRACT, 0x05, ID_CURVE_DELETECOLUMN},
+ {"DecPatchRow", VK_SUBTRACT, 0x04, ID_CURVE_DELETEROW},
+ {"Patch TAB", VK_TAB, 0x00, ID_PATCH_TAB},
+ {"Patch TAB", VK_TAB, 0x01, ID_PATCH_TAB},
+ {"SelectNudgeDown", VK_DOWN, 0x02, ID_SELECTION_SELECT_NUDGEDOWN},
+ {"EntityColor",'K', 0, ID_MISC_SELECTENTITYCOLOR},
+ {"CameraForward", VK_UP, 0, ID_CAMERA_FORWARD},
+ {"CameraBack", VK_DOWN, 0, ID_CAMERA_BACK},
+ {"CameraLeft", VK_LEFT, 0, ID_CAMERA_LEFT},
+ {"CameraRight", VK_RIGHT, 0, ID_CAMERA_RIGHT},
+ {"CameraUp", 'D', 0, ID_CAMERA_UP},
+ {"CameraDown", 'C', 0, ID_CAMERA_DOWN},
+ {"CameraAngleUp", 'A', 0, ID_CAMERA_ANGLEUP},
+ {"CameraAngleDown", 'Z', 0, ID_CAMERA_ANGLEDOWN},
+ {"CameraStrafeRight", VK_PERIOD, 0, ID_CAMERA_STRAFERIGHT},
+ {"CameraStrafeLeft", VK_COMMA, 0, ID_CAMERA_STRAFELEFT},
+ {"ToggleGrid", '0', 0, ID_GRID_TOGGLE},
+ {"SetGrid1", '1', 0, ID_GRID_1},
+ {"SetGrid2", '2', 0, ID_GRID_2},
+ {"SetGrid4", '3', 0, ID_GRID_4},
+ {"SetGrid8", '4', 0, ID_GRID_8},
+ {"SetGrid16", '5', 0, ID_GRID_16},
+ {"SetGrid32", '6', 0, ID_GRID_32},
+ {"SetGrid64", '7', 0, ID_GRID_64},
+ {"DragEdges", 'E', 0, ID_SELECTION_DRAGEDGES},
+ {"DragVertices", 'V', 0, ID_SELECTION_DRAGVERTECIES},
+ {"ViewEntityInfo", 'N', 0, ID_VIEW_ENTITY},
+ {"ViewConsole", 'O', 0, ID_VIEW_CONSOLE},
+ {"CloneSelection", VK_SPACE, 0, ID_SELECTION_CLONE},
+ {"DeleteSelection", VK_BACK, 0, ID_SELECTION_DELETE},
+ {"UnSelectSelection", VK_ESCAPE, 0, ID_SELECTION_DESELECT},
+ {"CenterView", VK_END, 0, ID_VIEW_CENTER},
+ {"ZoomOut", VK_INSERT, 0, ID_VIEW_ZOOMOUT},
+ {"ZoomIn", VK_DELETE, 0, ID_VIEW_ZOOMIN},
+ {"UpFloor", VK_PRIOR, 0, ID_VIEW_UPFLOOR},
+ {"DownFloor", VK_NEXT, 0, ID_VIEW_DOWNFLOOR},
+ {"ToggleClipper", 'X', 0, ID_VIEW_CLIPPER},
+ {"ToggleCrosshairs", 'X', 0x01, ID_VIEW_CROSSHAIR},
+ {"TogTexLock", 'T', 0x01, ID_TOGGLE_LOCK},
+ {"TogTexRotLock", 'R', 0x01, ID_TOGGLE_ROTATELOCK},
+ {"ToggleRealtime", 'R', 0x04, ID_VIEW_CAMERAUPDATE},
+ {"RaiseLowerTerrain", 'T', 0x06, ID_TERRAIN_RAISELOWERTERRAIN},
+ {"EntityList", 'L', 0, ID_EDIT_ENTITYINFO},
+ {"Preferences", 'P', 0, ID_PREFS},
+ {"ToggleCamera", 'C', 0x05, ID_TOGGLECAMERA},
+ {"ToggleConsole", 'O', 0, ID_TOGGLECONSOLE},
+ {"ToggleView", 'V', 0x05, ID_TOGGLEVIEW},
+ {"ToggleZ", 'Z', 0x05, ID_TOGGLEZ},
+ {"ConnectSelection", 'K', 0x04, ID_SELECTION_CONNECT},
+ {"Brush3Sided", '3', 0x04, ID_BRUSH_3SIDED},
+ {"Brush4Sided", '4', 0x04, ID_BRUSH_4SIDED},
+ {"Brush5Sided", '5', 0x04, ID_BRUSH_5SIDED},
+ {"Brush6Sided", '6', 0x04, ID_BRUSH_6SIDED},
+ {"Brush7Sided", '7', 0x04, ID_BRUSH_7SIDED},
+ {"Brush8Sided", '8', 0x04, ID_BRUSH_8SIDED},
+ {"Brush9Sided", '9', 0x04, ID_BRUSH_9SIDED},
+ {"ShowDetail", 'D', 0x04, ID_VIEW_SHOWDETAIL},
+ {"MakeDetail", 'M', 0x05, ID_CURVE_MATRIX_TRANSPOSE},
+ {"MakeDetail", 'M', 0x04, ID_SELECTION_MAKE_DETAIL},
+ {"MapInfo", 'M', 0, ID_EDIT_MAPINFO},
+ {"NextLeakSpot", 'K', 0x05, ID_MISC_NEXTLEAKSPOT},
+ {"PrevLeakSpot", 'L', 0x05, ID_MISC_PREVIOUSLEAKSPOT},
+ {"FileOpen", 'O', 0x04, ID_FILE_OPEN},
+ {"FileSave", 'S', 0x04, ID_FILE_SAVE},
+ {"Exit", 'X', 0x04, ID_FILE_EXIT},
+ {"NextView", VK_TAB, 0x04, ID_VIEW_NEXTVIEW},
+ {"ClipSelected", VK_RETURN, 0x00, ID_CLIP_SELECTED},
+ {"SplitSelected", VK_RETURN, 0x01, ID_SPLIT_SELECTED},
+ {"FlipClip", VK_RETURN, 0x04, ID_FLIP_CLIP},
+ {"MouseRotate", 'R', 0x00, ID_SELECT_MOUSEROTATE},
+ {"Copy", 'C', 0x04, ID_EDIT_COPYBRUSH},
+ {"Paste", 'V', 0x04, ID_EDIT_PASTEBRUSH},
+ {"Undo", 'Z', 0x04, ID_EDIT_UNDO},
+ {"Redo", 'Y', 0x04, ID_EDIT_REDO},
+ {"ZZoomOut", VK_INSERT, 0x04, ID_VIEW_ZZOOMOUT},
+ {"ZZoomIn", VK_DELETE, 0x04, ID_VIEW_ZZOOMIN},
+ {"TexDecrement", VK_SUBTRACT, 0x01, ID_SELECTION_TEXTURE_DEC},
+ {"TexIncrement", VK_ADD, 0x01, ID_SELECTION_TEXTURE_INC},
+ {"TextureFit", '5', 0x01, ID_SELECTION_TEXTURE_FIT},
+ {"TexRotateClock", VK_NEXT, 0x01, ID_SELECTION_TEXTURE_ROTATECLOCK},
+ {"TexRotateCounter", VK_PRIOR, 0x01, ID_SELECTION_TEXTURE_ROTATECOUNTER},
+ {"TexScaleUp", VK_UP, 0x04, ID_SELECTION_TEXTURE_SCALEUP},
+ {"TexScaleDown", VK_DOWN, 0x04, ID_SELECTION_TEXTURE_SCALEDOWN},
+ {"TexShiftLeft", VK_LEFT, 0x01, ID_SELECTION_TEXTURE_SHIFTLEFT},
+ {"TexShiftRight", VK_RIGHT, 0x01, ID_SELECTION_TEXTURE_SHIFTRIGHT},
+ {"TexShiftUp", VK_UP, 0x01, ID_SELECTION_TEXTURE_SHIFTUP},
+ {"TexShiftDown", VK_DOWN, 0x01, ID_SELECTION_TEXTURE_SHIFTDOWN},
+ {"GridDown", 219, 0x00, ID_GRID_PREV},
+ {"GridUp", 221, 0x00, ID_GRID_NEXT},
+ {"TexScaleLeft", VK_LEFT, 0x04, ID_SELECTION_TEXTURE_SCALELEFT},
+ {"TexScaleRight", VK_RIGHT, 0x04, ID_SELECTION_TEXTURE_SCALERIGHT},
+ {"CubicClipZoomOut", 219, 0x04, ID_VIEW_CUBEOUT},
+ {"CubicClipZoomIn", 221, 0x04, ID_VIEW_CUBEIN},
+ {"ToggleCubicClip", 220, 0x04, ID_VIEW_CUBICCLIPPING},
+// {"ToggleCubicClip", '\\', 0x04, ID_VIEW_CUBICCLIPPING},
+ {"MoveSelectionDOWN", VK_SUBTRACT, 0x00, ID_SELECTION_MOVEDOWN},
+ {"MoveSelectionUP", VK_ADD, 0x00, ID_SELECTION_MOVEUP},
+ {"DumpSelectedBrush", 'D', 0x01, ID_SELECTION_PRINT},
+ {"ToggleSizePaint", 'Q', 0x08, ID_SELECTION_TOGGLESIZEPAINT},
+ {"SelectNudgeLeft", VK_LEFT, 0x02, ID_SELECTION_SELECT_NUDGELEFT},
+ {"SelectNudgeRight", VK_RIGHT, 0x02, ID_SELECTION_SELECT_NUDGERIGHT},
+ {"SelectNudgeUp", VK_UP, 0x02, ID_SELECTION_SELECT_NUDGEUP},
+ {"CycleCapTexturePatch", 'N', 0x05, ID_CURVE_CYCLECAP},
+ {"NaturalizePatch", 'N', 0x04, ID_PATCH_NATURALIZE},
+ {"SnapPatchToGrid", 'G', 0x04, ID_SELECT_SNAPTOGRID},
+ {"ShowAllTextures", 'A', 0x04, ID_TEXTURES_SHOWALL},
+ {"SelectAllOfType", 'A', 0x01, ID_SELECT_ALL},
+ {"CapCurrentCurve", 'C', 0x01, ID_CURVE_CAP},
+ {"MakeStructural", 'S', 0x05, ID_SELECTION_MAKE_STRUCTURAL}
+ //{"ForceCameraWalk", 'Q', 0x08, ID_CAMERA_ACTIVE}
+};
+
+int g_nCommandCount = sizeof(g_Commands) / sizeof(SCommandInfo);
+
+SKeyInfo g_Keys[] =
+{
+ {"Space", VK_SPACE},
+ {"Backspace", VK_BACK},
+ {"Escape", VK_ESCAPE},
+ {"End", VK_END},
+ {"Insert", VK_INSERT},
+ {"Delete", VK_DELETE},
+ {"PageUp", VK_PRIOR},
+ {"PageDown", VK_NEXT},
+ {"Up", VK_UP},
+ {"Down", VK_DOWN},
+ {"Left", VK_LEFT},
+ {"Right", VK_RIGHT},
+ {"F1", VK_F1},
+ {"F2", VK_F2},
+ {"F3", VK_F3},
+ {"F4", VK_F4},
+ {"F5", VK_F5},
+ {"F6", VK_F6},
+ {"F7", VK_F7},
+ {"F8", VK_F8},
+ {"F9", VK_F9},
+ {"F10", VK_F10},
+ {"F11", VK_F11},
+ {"F12", VK_F12},
+ {"Tab", VK_TAB},
+ {"Return", VK_RETURN},
+ {"Comma", VK_COMMA},
+ {"Period", VK_PERIOD},
+ {"Plus", VK_ADD},
+ {"Multiply", VK_MULTIPLY},
+ {"Subtract", VK_SUBTRACT},
+ {"NumPad0", VK_NUMPAD0},
+ {"NumPad1", VK_NUMPAD1},
+ {"NumPad2", VK_NUMPAD2},
+ {"NumPad3", VK_NUMPAD3},
+ {"NumPad4", VK_NUMPAD4},
+ {"NumPad5", VK_NUMPAD5},
+ {"NumPad6", VK_NUMPAD6},
+ {"NumPad7", VK_NUMPAD7},
+ {"NumPad8", VK_NUMPAD8},
+ {"NumPad9", VK_NUMPAD9},
+ {"[", 219},
+ {"]", 221},
+ {"\\", 220}
+};
+
+int g_nKeyCount = sizeof(g_Keys) / sizeof(SKeyInfo);
+
+const int CMD_TEXTUREWAD_END = CMD_TEXTUREWAD + 127;
+const int CMD_BSPCOMMAND_END = CMD_BSPCOMMAND + 127;
+const int IDMRU_END = IDMRU+9;
+
+const int g_msgBSPDone = RegisterWindowMessage("_BSPDone");
+const int g_msgBSPStatus = RegisterWindowMessage("_BSPStatus");
+
+IMPLEMENT_DYNAMIC(CMainFrame, CFrameWnd)
+
+BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
+ //{{AFX_MSG_MAP(CMainFrame)
+ ON_WM_PARENTNOTIFY()
+ ON_WM_CREATE()
+ ON_WM_TIMER()
+ ON_WM_DESTROY()
+ ON_WM_CLOSE()
+ ON_WM_KEYDOWN()
+ ON_WM_SIZE()
+ ON_COMMAND(ID_VIEW_CAMERATOGGLE, ToggleCamera)
+ ON_COMMAND(ID_FILE_CLOSE, OnFileClose)
+ ON_COMMAND(ID_FILE_EXIT, OnFileExit)
+ ON_COMMAND(ID_FILE_LOADPROJECT, OnFileLoadproject)
+ ON_COMMAND(ID_FILE_NEW, OnFileNew)
+ ON_COMMAND(ID_FILE_OPEN, OnFileOpen)
+ ON_COMMAND(ID_FILE_POINTFILE, OnFilePointfile)
+ ON_COMMAND(ID_FILE_PRINT, OnFilePrint)
+ ON_COMMAND(ID_FILE_PRINT_PREVIEW, OnFilePrintPreview)
+ ON_COMMAND(ID_FILE_SAVE, OnFileSave)
+ ON_COMMAND(ID_FILE_SAVEAS, OnFileSaveas)
+ ON_COMMAND(ID_VIEW_100, OnView100)
+ ON_COMMAND(ID_VIEW_CENTER, OnViewCenter)
+ ON_COMMAND(ID_VIEW_CONSOLE, OnViewConsole)
+ ON_COMMAND(ID_VIEW_DOWNFLOOR, OnViewDownfloor)
+ ON_COMMAND(ID_VIEW_ENTITY, OnViewEntity)
+ ON_COMMAND(ID_VIEW_FRONT, OnViewFront)
+ ON_COMMAND(ID_VIEW_SHOWBLOCKS, OnViewShowblocks)
+ ON_COMMAND(ID_VIEW_SHOWCLIP, OnViewShowclip)
+ ON_COMMAND(ID_VIEW_SHOWCOORDINATES, OnViewShowcoordinates)
+ ON_COMMAND(ID_VIEW_SHOWDETAIL, OnViewShowdetail)
+ ON_COMMAND(ID_VIEW_SHOWENT, OnViewShowent)
+ ON_COMMAND(ID_VIEW_SHOWLIGHTS, OnViewShowlights)
+ ON_COMMAND(ID_VIEW_SHOWNAMES, OnViewShownames)
+ ON_COMMAND(ID_VIEW_SHOWPATH, OnViewShowpath)
+ ON_COMMAND(ID_VIEW_SHOWWATER, OnViewShowwater)
+ ON_COMMAND(ID_VIEW_SHOWWORLD, OnViewShowworld)
+ ON_COMMAND(ID_VIEW_TEXTURE, OnViewTexture)
+ ON_COMMAND(ID_VIEW_UPFLOOR, OnViewUpfloor)
+ ON_COMMAND(ID_VIEW_XY, OnViewXy)
+ ON_COMMAND(ID_VIEW_Z100, OnViewZ100)
+ ON_COMMAND(ID_VIEW_ZOOMIN, OnViewZoomin)
+ ON_COMMAND(ID_VIEW_ZOOMOUT, OnViewZoomout)
+ ON_COMMAND(ID_VIEW_ZZOOMIN, OnViewZzoomin)
+ ON_COMMAND(ID_VIEW_ZZOOMOUT, OnViewZzoomout)
+ ON_COMMAND(ID_VIEW_SIDE, OnViewSide)
+ ON_COMMAND(ID_TEXTURES_SHOWINUSE, OnTexturesShowinuse)
+ ON_COMMAND(ID_TEXTURES_INSPECTOR, OnTexturesInspector)
+ ON_COMMAND(ID_MISC_BENCHMARK, OnMiscBenchmark)
+ ON_COMMAND(ID_MISC_FINDBRUSH, OnMiscFindbrush)
+ ON_COMMAND(ID_MISC_GAMMA, OnMiscGamma)
+ ON_COMMAND(ID_MISC_NEXTLEAKSPOT, OnMiscNextleakspot)
+ ON_COMMAND(ID_MISC_PREVIOUSLEAKSPOT, OnMiscPreviousleakspot)
+ ON_COMMAND(ID_MISC_PRINTXY, OnMiscPrintxy)
+ ON_COMMAND(ID_MISC_SELECTENTITYCOLOR, OnMiscSelectentitycolor)
+ ON_COMMAND(ID_TEXTUREBK, OnTexturebk)
+ ON_COMMAND(ID_COLORS_MAJOR, OnColorsMajor)
+ ON_COMMAND(ID_COLORS_MINOR, OnColorsMinor)
+ ON_COMMAND(ID_COLORS_XYBK, OnColorsXybk)
+ ON_COMMAND(ID_BRUSH_3SIDED, OnBrush3sided)
+ ON_COMMAND(ID_BRUSH_4SIDED, OnBrush4sided)
+ ON_COMMAND(ID_BRUSH_5SIDED, OnBrush5sided)
+ ON_COMMAND(ID_BRUSH_6SIDED, OnBrush6sided)
+ ON_COMMAND(ID_BRUSH_7SIDED, OnBrush7sided)
+ ON_COMMAND(ID_BRUSH_8SIDED, OnBrush8sided)
+ ON_COMMAND(ID_BRUSH_9SIDED, OnBrush9sided)
+ ON_COMMAND(ID_BRUSH_ARBITRARYSIDED, OnBrushArbitrarysided)
+ ON_COMMAND(ID_BRUSH_FLIPX, OnBrushFlipx)
+ ON_COMMAND(ID_BRUSH_FLIPY, OnBrushFlipy)
+ ON_COMMAND(ID_BRUSH_FLIPZ, OnBrushFlipz)
+ ON_COMMAND(ID_BRUSH_ROTATEX, OnBrushRotatex)
+ ON_COMMAND(ID_BRUSH_ROTATEY, OnBrushRotatey)
+ ON_COMMAND(ID_BRUSH_ROTATEZ, OnBrushRotatez)
+ ON_COMMAND(ID_REGION_OFF, OnRegionOff)
+ ON_COMMAND(ID_REGION_SETBRUSH, OnRegionSetbrush)
+ ON_COMMAND(ID_REGION_SETSELECTION, OnRegionSetselection)
+ ON_COMMAND(ID_REGION_SETTALLBRUSH, OnRegionSettallbrush)
+ ON_COMMAND(ID_REGION_SETXY, OnRegionSetxy)
+ ON_COMMAND(ID_SELECTION_ARBITRARYROTATION, OnSelectionArbitraryrotation)
+ ON_COMMAND(ID_SELECTION_CLONE, OnSelectionClone)
+ ON_COMMAND(ID_SELECTION_CONNECT, OnSelectionConnect)
+ ON_COMMAND(ID_SELECTION_CSGSUBTRACT, OnSelectionCsgsubtract)
+ ON_COMMAND(ID_SELECTION_CSGMERGE, OnSelectionCsgmerge)
+ ON_COMMAND(ID_SELECTION_NOOUTLINE, OnSelectionNoOutline)
+ ON_COMMAND(ID_SELECTION_DELETE, OnSelectionDelete)
+ ON_COMMAND(ID_SELECTION_DESELECT, OnSelectionDeselect)
+ ON_COMMAND(ID_SELECTION_DRAGEDGES, OnSelectionDragedges)
+ ON_COMMAND(ID_SELECTION_DRAGVERTECIES, OnSelectionDragvertecies)
+ ON_COMMAND(ID_SELECTION_MAKE_DETAIL, OnSelectionMakeDetail)
+ ON_COMMAND(ID_SELECTION_MAKE_STRUCTURAL, OnSelectionMakeStructural)
+ ON_COMMAND(ID_SELECTION_MAKEHOLLOW, OnSelectionMakehollow)
+ ON_COMMAND(ID_SELECTION_SELECTCOMPLETETALL, OnSelectionSelectcompletetall)
+ ON_COMMAND(ID_SELECTION_SELECTINSIDE, OnSelectionSelectinside)
+ ON_COMMAND(ID_SELECTION_SELECTPARTIALTALL, OnSelectionSelectpartialtall)
+ ON_COMMAND(ID_SELECTION_SELECTTOUCHING, OnSelectionSelecttouching)
+ ON_COMMAND(ID_SELECTION_UNGROUPENTITY, OnSelectionUngroupentity)
+ ON_COMMAND(ID_TEXTURES_POPUP, OnTexturesPopup)
+ ON_COMMAND(ID_SPLINES_POPUP, OnSplinesPopup)
+ ON_COMMAND(ID_POPUP_SELECTION, OnPopupSelection)
+ ON_COMMAND(ID_VIEW_CHANGE, OnViewChange)
+ ON_COMMAND(ID_VIEW_CAMERAUPDATE, OnViewCameraupdate)
+ ON_COMMAND(ID_TERRAIN_RAISELOWERTERRAIN, OnRaiseLowerTerrain)
+ ON_UPDATE_COMMAND_UI(ID_VIEW_CAMERAUPDATE, OnUpdateViewCameraupdate)
+ ON_WM_SIZING()
+ ON_COMMAND(ID_HELP_ABOUT, OnHelpAbout)
+ ON_COMMAND(ID_VIEW_CLIPPER, OnViewClipper)
+ ON_COMMAND(ID_CAMERA_ANGLEDOWN, OnCameraAngledown)
+ ON_COMMAND(ID_CAMERA_ANGLEUP, OnCameraAngleup)
+ ON_COMMAND(ID_CAMERA_BACK, OnCameraBack)
+ ON_COMMAND(ID_CAMERA_DOWN, OnCameraDown)
+ ON_COMMAND(ID_CAMERA_FORWARD, OnCameraForward)
+ ON_COMMAND(ID_CAMERA_LEFT, OnCameraLeft)
+ ON_COMMAND(ID_CAMERA_RIGHT, OnCameraRight)
+ ON_COMMAND(ID_CAMERA_STRAFELEFT, OnCameraStrafeleft)
+ ON_COMMAND(ID_CAMERA_STRAFERIGHT, OnCameraStraferight)
+ ON_COMMAND(ID_CAMERA_UP, OnCameraUp)
+ ON_COMMAND(ID_GRID_TOGGLE, OnGridToggle)
+ ON_COMMAND(ID_PREFS, OnPrefs)
+ ON_COMMAND(ID_TOGGLECAMERA, OnTogglecamera)
+ ON_COMMAND(ID_TOGGLECONSOLE, OnToggleconsole)
+ ON_COMMAND(ID_TOGGLEVIEW, OnToggleview)
+ ON_COMMAND(ID_TOGGLEZ, OnTogglez)
+ ON_COMMAND(ID_TOGGLE_LOCK, OnToggleLock)
+ ON_COMMAND(ID_EDIT_MAPINFO, OnEditMapinfo)
+ ON_COMMAND(ID_EDIT_ENTITYINFO, OnEditEntityinfo)
+ ON_COMMAND(ID_BRUSH_SCRIPTS, OnBrushScripts)
+ ON_COMMAND(ID_VIEW_NEXTVIEW, OnViewNextview)
+ ON_COMMAND(ID_HELP_COMMANDLIST, OnHelpCommandlist)
+ ON_COMMAND(ID_FILE_NEWPROJECT, OnFileNewproject)
+ ON_COMMAND(ID_FLIP_CLIP, OnFlipClip)
+ ON_COMMAND(ID_CLIP_SELECTED, OnClipSelected)
+ ON_COMMAND(ID_SPLIT_SELECTED, OnSplitSelected)
+ ON_COMMAND(ID_TOGGLEVIEW_XZ, OnToggleviewXz)
+ ON_COMMAND(ID_TOGGLEVIEW_YZ, OnToggleviewYz)
+ ON_COMMAND(ID_COLORS_BRUSH, OnColorsBrush)
+ ON_COMMAND(ID_COLORS_CLIPPER, OnColorsClipper)
+ ON_COMMAND(ID_COLORS_GRIDTEXT, OnColorsGridtext)
+ ON_COMMAND(ID_COLORS_SELECTEDBRUSH, OnColorsSelectedbrush)
+ ON_COMMAND(ID_COLORS_GRIDBLOCK, OnColorsGridblock)
+ ON_COMMAND(ID_COLORS_VIEWNAME, OnColorsViewname)
+ ON_COMMAND(ID_COLOR_SETORIGINAL, OnColorSetoriginal)
+ ON_COMMAND(ID_COLOR_SETQER, OnColorSetqer)
+ ON_COMMAND(ID_COLOR_SETBLACK, OnColorSetblack)
+ ON_COMMAND(ID_SNAPTOGRID, OnSnaptogrid)
+ ON_COMMAND(ID_SELECT_SCALE, OnSelectScale)
+ ON_COMMAND(ID_SELECT_MOUSEROTATE, OnSelectMouserotate)
+ ON_COMMAND(ID_EDIT_COPYBRUSH, OnEditCopybrush)
+ ON_COMMAND(ID_EDIT_PASTEBRUSH, OnEditPastebrush)
+ ON_COMMAND(ID_EDIT_UNDO, OnEditUndo)
+ ON_COMMAND(ID_EDIT_REDO, OnEditRedo)
+ ON_UPDATE_COMMAND_UI(ID_EDIT_UNDO, OnUpdateEditUndo)
+ ON_UPDATE_COMMAND_UI(ID_EDIT_REDO, OnUpdateEditRedo)
+ ON_COMMAND(ID_SELECTION_INVERT, OnSelectionInvert)
+ ON_COMMAND(ID_SELECTION_TEXTURE_DEC, OnSelectionTextureDec)
+ ON_COMMAND(ID_SELECTION_TEXTURE_FIT, OnSelectionTextureFit)
+ ON_COMMAND(ID_SELECTION_TEXTURE_INC, OnSelectionTextureInc)
+ ON_COMMAND(ID_SELECTION_TEXTURE_ROTATECLOCK, OnSelectionTextureRotateclock)
+ ON_COMMAND(ID_SELECTION_TEXTURE_ROTATECOUNTER, OnSelectionTextureRotatecounter)
+ ON_COMMAND(ID_SELECTION_TEXTURE_SCALEDOWN, OnSelectionTextureScaledown)
+ ON_COMMAND(ID_SELECTION_TEXTURE_SCALEUP, OnSelectionTextureScaleup)
+ ON_COMMAND(ID_SELECTION_TEXTURE_SHIFTDOWN, OnSelectionTextureShiftdown)
+ ON_COMMAND(ID_SELECTION_TEXTURE_SHIFTLEFT, OnSelectionTextureShiftleft)
+ ON_COMMAND(ID_SELECTION_TEXTURE_SHIFTRIGHT, OnSelectionTextureShiftright)
+ ON_COMMAND(ID_SELECTION_TEXTURE_SHIFTUP, OnSelectionTextureShiftup)
+ ON_COMMAND(ID_GRID_NEXT, OnGridNext)
+ ON_COMMAND(ID_GRID_PREV, OnGridPrev)
+ ON_COMMAND(ID_SELECTION_TEXTURE_SCALELEFT, OnSelectionTextureScaleLeft)
+ ON_COMMAND(ID_SELECTION_TEXTURE_SCALERIGHT, OnSelectionTextureScaleRight)
+ ON_COMMAND(ID_TEXTURE_REPLACEALL, OnTextureReplaceall)
+ ON_COMMAND(ID_SCALELOCKX, OnScalelockx)
+ ON_COMMAND(ID_SCALELOCKY, OnScalelocky)
+ ON_COMMAND(ID_SCALELOCKZ, OnScalelockz)
+ ON_COMMAND(ID_SELECT_MOUSESCALE, OnSelectMousescale)
+ ON_COMMAND(ID_VIEW_CUBICCLIPPING, OnViewCubicclipping)
+ ON_COMMAND(ID_FILE_IMPORT, OnFileImport)
+ ON_COMMAND(ID_FILE_PROJECTSETTINGS, OnFileProjectsettings)
+ ON_UPDATE_COMMAND_UI(ID_FILE_IMPORT, OnUpdateFileImport)
+ ON_COMMAND(ID_VIEW_CUBEIN, OnViewCubein)
+ ON_COMMAND(ID_VIEW_CUBEOUT, OnViewCubeout)
+ ON_COMMAND(ID_FILE_SAVEREGION, OnFileSaveregion)
+ ON_UPDATE_COMMAND_UI(ID_FILE_SAVEREGION, OnUpdateFileSaveregion)
+ ON_COMMAND(ID_SELECTION_MOVEDOWN, OnSelectionMovedown)
+ ON_COMMAND(ID_SELECTION_MOVEUP, OnSelectionMoveup)
+ ON_COMMAND(ID_TOOLBAR_MAIN, OnToolbarMain)
+ ON_COMMAND(ID_TOOLBAR_TEXTURE, OnToolbarTexture)
+ ON_COMMAND(ID_SELECTION_PRINT, OnSelectionPrint)
+ ON_COMMAND(ID_SELECTION_TOGGLESIZEPAINT, OnSelectionTogglesizepaint)
+ ON_COMMAND(ID_BRUSH_MAKECONE, OnBrushMakecone)
+ ON_COMMAND(ID_TEXTURES_LOAD, OnTexturesLoad)
+ ON_COMMAND(ID_TOGGLE_ROTATELOCK, OnToggleRotatelock)
+ ON_COMMAND(ID_CURVE_BEVEL, OnCurveBevel)
+ ON_COMMAND(ID_CURVE_CYLINDER, OnCurveCylinder)
+ ON_COMMAND(ID_CURVE_EIGHTHSPHERE, OnCurveEighthsphere)
+ ON_COMMAND(ID_CURVE_ENDCAP, OnCurveEndcap)
+ ON_COMMAND(ID_CURVE_HEMISPHERE, OnCurveHemisphere)
+ ON_COMMAND(ID_CURVE_INVERTCURVE, OnCurveInvertcurve)
+ ON_COMMAND(ID_CURVE_QUARTER, OnCurveQuarter)
+ ON_COMMAND(ID_CURVE_SPHERE, OnCurveSphere)
+ ON_COMMAND(ID_FILE_IMPORTMAP, OnFileImportmap)
+ ON_COMMAND(ID_FILE_EXPORTMAP, OnFileExportmap)
+ ON_COMMAND(ID_EDIT_LOADPREFAB, OnEditLoadprefab)
+ ON_COMMAND(ID_VIEW_SHOWCURVES, OnViewShowcurves)
+ ON_COMMAND(ID_SELECTION_SELECT_NUDGEDOWN, OnSelectionSelectNudgedown)
+ ON_COMMAND(ID_SELECTION_SELECT_NUDGELEFT, OnSelectionSelectNudgeleft)
+ ON_COMMAND(ID_SELECTION_SELECT_NUDGERIGHT, OnSelectionSelectNudgeright)
+ ON_COMMAND(ID_SELECTION_SELECT_NUDGEUP, OnSelectionSelectNudgeup)
+ ON_WM_SYSKEYDOWN()
+ ON_COMMAND(ID_TEXTURES_LOADLIST, OnTexturesLoadlist)
+ ON_COMMAND(ID_DONTSELECTCURVE, OnDontselectcurve)
+ ON_COMMAND(ID_CONVERTCURVES, OnConvertcurves)
+ ON_COMMAND(ID_DYNAMIC_LIGHTING, OnDynamicLighting)
+ ON_COMMAND(ID_CURVE_SIMPLEPATCHMESH, OnCurveSimplepatchmesh)
+ ON_COMMAND(ID_PATCH_SHOWBOUNDINGBOX, OnPatchToggleBox)
+ ON_COMMAND(ID_PATCH_WIREFRAME, OnPatchWireframe)
+ ON_COMMAND(ID_CURVE_PATCHCONE, OnCurvePatchcone)
+ ON_COMMAND(ID_CURVE_PATCHTUBE, OnCurvePatchtube)
+ ON_COMMAND(ID_PATCH_WELD, OnPatchWeld)
+ ON_COMMAND(ID_CURVE_PATCHBEVEL, OnCurvePatchbevel)
+ ON_COMMAND(ID_CURVE_PATCHENDCAP, OnCurvePatchendcap)
+ ON_COMMAND(ID_CURVE_PATCHINVERTEDBEVEL, OnCurvePatchinvertedbevel)
+ ON_COMMAND(ID_CURVE_PATCHINVERTEDENDCAP, OnCurvePatchinvertedendcap)
+ ON_COMMAND(ID_PATCH_DRILLDOWN, OnPatchDrilldown)
+ ON_COMMAND(ID_CURVE_INSERTCOLUMN, OnCurveInsertcolumn)
+ ON_COMMAND(ID_CURVE_INSERTROW, OnCurveInsertrow)
+ ON_COMMAND(ID_CURVE_DELETECOLUMN, OnCurveDeletecolumn)
+ ON_COMMAND(ID_CURVE_DELETEROW, OnCurveDeleterow)
+ ON_COMMAND(ID_CURVE_INSERT_ADDCOLUMN, OnCurveInsertAddcolumn)
+ ON_COMMAND(ID_CURVE_INSERT_ADDROW, OnCurveInsertAddrow)
+ ON_COMMAND(ID_CURVE_INSERT_INSERTCOLUMN, OnCurveInsertInsertcolumn)
+ ON_COMMAND(ID_CURVE_INSERT_INSERTROW, OnCurveInsertInsertrow)
+ ON_COMMAND(ID_CURVE_NEGATIVE, OnCurveNegative)
+ ON_COMMAND(ID_CURVE_NEGATIVETEXTUREX, OnCurveNegativeTextureX)
+ ON_COMMAND(ID_CURVE_NEGATIVETEXTUREY, OnCurveNegativeTextureY)
+ ON_COMMAND(ID_CURVE_DELETE_FIRSTCOLUMN, OnCurveDeleteFirstcolumn)
+ ON_COMMAND(ID_CURVE_DELETE_FIRSTROW, OnCurveDeleteFirstrow)
+ ON_COMMAND(ID_CURVE_DELETE_LASTCOLUMN, OnCurveDeleteLastcolumn)
+ ON_COMMAND(ID_CURVE_DELETE_LASTROW, OnCurveDeleteLastrow)
+ ON_COMMAND(ID_PATCH_BEND, OnPatchBend)
+ ON_COMMAND(ID_PATCH_INSDEL, OnPatchInsdel)
+ ON_COMMAND(ID_PATCH_ENTER, OnPatchEnter)
+ ON_COMMAND(ID_PATCH_TAB, OnPatchTab)
+ ON_COMMAND(ID_CURVE_PATCHDENSETUBE, OnCurvePatchdensetube)
+ ON_COMMAND(ID_CURVE_PATCHVERYDENSETUBE, OnCurvePatchverydensetube)
+ ON_COMMAND(ID_CURVE_CAP, OnCurveCap)
+ ON_COMMAND(ID_CURVE_CAP_INVERTEDBEVEL, OnCurveCapInvertedbevel)
+ ON_COMMAND(ID_CURVE_CAP_INVERTEDENDCAP, OnCurveCapInvertedendcap)
+ ON_COMMAND(ID_CURVE_REDISPERSE_COLS, OnCurveRedisperseCols)
+ ON_COMMAND(ID_CURVE_REDISPERSE_ROWS, OnCurveRedisperseRows)
+ ON_COMMAND(ID_PATCH_NATURALIZE, OnPatchNaturalize)
+ ON_COMMAND(ID_SELECT_SNAPTOGRID, OnSnapToGrid)
+ ON_COMMAND(ID_CURVE_PATCHSQUARE, OnCurvePatchsquare)
+ ON_COMMAND(ID_TERRAIN_CREATETERRAINFROMBRUSH, OnTerrainCreateFromBrush)
+ ON_COMMAND(ID_TEXTURES_TEXTUREWINDOWSCALE_10, OnTexturesTexturewindowscale10)
+ ON_COMMAND(ID_TEXTURES_TEXTUREWINDOWSCALE_100, OnTexturesTexturewindowscale100)
+ ON_COMMAND(ID_TEXTURES_TEXTUREWINDOWSCALE_200, OnTexturesTexturewindowscale200)
+ ON_COMMAND(ID_TEXTURES_TEXTUREWINDOWSCALE_25, OnTexturesTexturewindowscale25)
+ ON_COMMAND(ID_TEXTURES_TEXTUREWINDOWSCALE_50, OnTexturesTexturewindowscale50)
+ ON_COMMAND(ID_TEXTURES_FLUSH, OnTexturesFlush)
+ ON_COMMAND(ID_CURVE_OVERLAY_CLEAR, OnCurveOverlayClear)
+ ON_COMMAND(ID_CURVE_OVERLAY_SET, OnCurveOverlaySet)
+ ON_COMMAND(ID_CURVE_THICKEN, OnCurveThicken)
+ ON_COMMAND(ID_CURVE_CYCLECAP, OnCurveCyclecap)
+ ON_COMMAND(ID_CURVE_MATRIX_TRANSPOSE, OnCurveMatrixTranspose)
+ ON_COMMAND(ID_TEXTURES_RELOADSHADERS, OnTexturesReloadshaders)
+ ON_COMMAND(ID_SHOW_ENTITIES, OnShowEntities)
+ ON_COMMAND(ID_VIEW_ENTITIESAS_BOUNDINGBOX, OnViewEntitiesasBoundingbox)
+ ON_COMMAND(ID_VIEW_ENTITIESAS_SELECTEDSKINNED, OnViewEntitiesasSelectedskinned)
+ ON_COMMAND(ID_VIEW_ENTITIESAS_SELECTEDWIREFRAME, OnViewEntitiesasSelectedwireframe)
+ ON_COMMAND(ID_VIEW_ENTITIESAS_SKINNED, OnViewEntitiesasSkinned)
+ ON_COMMAND(ID_VIEW_ENTITIESAS_SKINNEDANDBOXED, OnViewEntitiesasSkinnedandboxed)
+ ON_COMMAND(ID_VIEW_ENTITIESAS_WIREFRAME, OnViewEntitiesasWireframe)
+ ON_COMMAND(ID_PLUGINS_REFRESH, OnPluginsRefresh)
+ ON_COMMAND(ID_VIEW_SHOWHINT, OnViewShowhint)
+ ON_UPDATE_COMMAND_UI(ID_TEXTURES_SHOWINUSE, OnUpdateTexturesShowinuse)
+ ON_COMMAND(ID_TEXTURES_SHOWALL, OnTexturesShowall)
+ ON_COMMAND(ID_PATCH_INSPECTOR, OnPatchInspector)
+ ON_COMMAND(ID_VIEW_OPENGLLIGHTING, OnViewOpengllighting)
+ ON_COMMAND(ID_SELECT_ALL, OnSelectAll)
+ ON_COMMAND(ID_VIEW_SHOWCAULK, OnViewShowcaulk)
+ ON_COMMAND(ID_CURVE_FREEZE, OnCurveFreeze)
+ ON_COMMAND(ID_CURVE_UNFREEZE, OnCurveUnFreeze)
+ ON_COMMAND(ID_CURVE_UNFREEZEALL, OnCurveUnFreezeAll)
+ ON_COMMAND(ID_SELECT_RESELECT, OnSelectReselect)
+ ON_COMMAND(ID_VIEW_SHOWANGLES, OnViewShowangles)
+ ON_COMMAND(ID_EDIT_SAVEPREFAB, OnEditSaveprefab)
+ ON_COMMAND(ID_CURVE_MOREENDCAPSBEVELS_SQUAREBEVEL, OnCurveMoreendcapsbevelsSquarebevel)
+ ON_COMMAND(ID_CURVE_MOREENDCAPSBEVELS_SQUAREENDCAP, OnCurveMoreendcapsbevelsSquareendcap)
+ ON_COMMAND(ID_BRUSH_PRIMITIVES_SPHERE, OnBrushPrimitivesSphere)
+ ON_COMMAND(ID_VIEW_CROSSHAIR, OnViewCrosshair)
+ ON_COMMAND(ID_VIEW_HIDESHOW_HIDESELECTED, OnViewHideshowHideselected)
+ ON_COMMAND(ID_VIEW_HIDESHOW_SHOWHIDDEN, OnViewHideshowShowhidden)
+ ON_COMMAND(ID_TEXTURES_SHADERS_SHOW, OnTexturesShadersShow)
+ ON_COMMAND(ID_TEXTURES_FLUSH_UNUSED, OnTexturesFlushUnused)
+ ON_COMMAND(ID_VIEW_GROUPS, OnViewGroups)
+ ON_COMMAND(ID_DROP_GROUP_ADDTO_WORLD, OnDropGroupAddtoWorld)
+ ON_COMMAND(ID_DROP_GROUP_NAME, OnDropGroupName)
+ ON_COMMAND(ID_DROP_GROUP_NEWGROUP, OnDropGroupNewgroup)
+ ON_COMMAND(ID_DROP_GROUP_REMOVE, OnDropGroupRemove)
+ ON_COMMAND(ID_SPLINES_MODE, OnSplinesMode)
+ ON_COMMAND(ID_SPLINES_LOAD, OnSplinesLoad)
+ ON_COMMAND(ID_SPLINES_SAVE, OnSplinesSave)
+ ON_COMMAND(ID_SPLINES_EDIT, OnSplinesEdit)
+ ON_COMMAND(ID_SPLINE_TEST, OnSplineTest)
+ ON_COMMAND(ID_POPUP_NEWCAMERA_INTERPOLATED, OnPopupNewcameraInterpolated)
+ ON_COMMAND(ID_POPUP_NEWCAMERA_SPLINE, OnPopupNewcameraSpline)
+ ON_COMMAND(ID_POPUP_NEWCAMERA_FIXED, OnPopupNewcameraFixed)
+ //}}AFX_MSG_MAP
+ ON_COMMAND_RANGE(CMD_TEXTUREWAD, CMD_TEXTUREWAD_END, OnTextureWad)
+ ON_COMMAND_RANGE(CMD_BSPCOMMAND, CMD_BSPCOMMAND_END, OnBspCommand)
+ ON_COMMAND_RANGE(IDMRU, IDMRU_END, OnMru)
+ ON_COMMAND_RANGE(ID_VIEW_NEAREST, ID_TEXTURES_FLATSHADE, OnViewNearest)
+ ON_COMMAND_RANGE(ID_GRID_1, ID_GRID_64, OnGrid1)
+ ON_COMMAND_RANGE(ID_PLUGIN_START, ID_PLUGIN_END, OnPlugIn)
+ ON_REGISTERED_MESSAGE(g_msgBSPDone, OnBSPDone)
+ ON_REGISTERED_MESSAGE(g_msgBSPStatus, OnBSPStatus)
+ ON_MESSAGE(WM_DISPLAYCHANGE, OnDisplayChange)
+
+END_MESSAGE_MAP()
+
+static UINT indicators[] =
+{
+ ID_SEPARATOR, // status line indicator
+ ID_SEPARATOR, // status line indicator
+ ID_SEPARATOR, // status line indicator
+ ID_SEPARATOR, // status line indicator
+ ID_SEPARATOR, // status line indicator
+ ID_SEPARATOR, // status line indicator
+};
+
+LRESULT CMainFrame::OnDisplayChange(UINT wParam, long lParam)
+{
+ int n = wParam;
+ return 0;
+}
+
+
+LRESULT CMainFrame::OnBSPStatus(UINT wParam, long lParam)
+{
+ return 0;
+}
+
+LRESULT CMainFrame::OnBSPDone(UINT wParam, long lParam)
+{
+ DLLBuildDone();
+ return 0;
+}
+
+
+/////////////////////////////////////////////////////////////////////////////
+// CMainFrame construction/destruction
+
+CMainFrame::CMainFrame()
+{
+ m_bDoLoop = false;
+ m_bSplittersOK = false;
+ g_pParentWnd = this;
+ m_pXYWnd = NULL;
+ m_pCamWnd = NULL;
+ m_pTexWnd = NULL;
+ m_pZWnd = NULL;
+ m_pEditWnd = NULL;
+ m_pYZWnd = NULL;
+ m_pXZWnd = NULL;
+ m_pActiveXY = NULL;
+ m_bCamPreview = true;
+}
+
+CMainFrame::~CMainFrame()
+{
+}
+
+void HandlePopup(CWnd* pWindow, unsigned int uId)
+{
+ // Get the current position of the mouse
+ CPoint ptMouse;
+ GetCursorPos(&ptMouse);
+
+ // Load up a menu that has the options we are looking for in it
+ CMenu mnuPopup;
+ VERIFY(mnuPopup.LoadMenu(uId));
+ mnuPopup.GetSubMenu(0)->TrackPopupMenu(TPM_LEFTALIGN | TPM_LEFTBUTTON |
+ TPM_RIGHTBUTTON, ptMouse.x, ptMouse.y,pWindow);
+ mnuPopup.DestroyMenu();
+
+ // Set focus back to window
+ pWindow->SetFocus();
+}
+
+
+void CMainFrame::OnParentNotify(UINT message, LPARAM lParam)
+{
+}
+
+void CMainFrame::SetButtonMenuStates()
+{
+ CMenu* pMenu = GetMenu();
+ if (pMenu)
+ {
+ // by default all of these are checked because that's how they're defined in the menu editor
+ if ( !g_qeglobals.d_savedinfo.show_names )
+ pMenu->CheckMenuItem(ID_VIEW_SHOWNAMES, MF_BYCOMMAND | MF_UNCHECKED);
+ if ( !g_qeglobals.d_savedinfo.show_coordinates )
+ pMenu->CheckMenuItem(ID_VIEW_SHOWCOORDINATES, MF_BYCOMMAND | MF_UNCHECKED );
+
+ if ( g_qeglobals.d_savedinfo.exclude & EXCLUDE_LIGHTS )
+ pMenu->CheckMenuItem(ID_VIEW_SHOWLIGHTS, MF_BYCOMMAND | MF_UNCHECKED );
+ if ( g_qeglobals.d_savedinfo.exclude & EXCLUDE_ENT )
+ pMenu->CheckMenuItem(ID_VIEW_ENTITY, MF_BYCOMMAND | MF_UNCHECKED );
+ if ( g_qeglobals.d_savedinfo.exclude & EXCLUDE_PATHS )
+ pMenu->CheckMenuItem(ID_VIEW_SHOWPATH, MF_BYCOMMAND | MF_UNCHECKED );
+ if ( g_qeglobals.d_savedinfo.exclude & EXCLUDE_WATER )
+ pMenu->CheckMenuItem(ID_VIEW_SHOWWATER, MF_BYCOMMAND | MF_UNCHECKED );
+ if ( g_qeglobals.d_savedinfo.exclude & EXCLUDE_WORLD )
+ pMenu->CheckMenuItem(ID_VIEW_SHOWWORLD, MF_BYCOMMAND | MF_UNCHECKED );
+ if ( g_qeglobals.d_savedinfo.exclude & EXCLUDE_CLIP )
+ pMenu->CheckMenuItem(ID_VIEW_SHOWCLIP, MF_BYCOMMAND | MF_UNCHECKED );
+ if ( g_qeglobals.d_savedinfo.exclude & EXCLUDE_HINT )
+ pMenu->CheckMenuItem(ID_VIEW_SHOWHINT, MF_BYCOMMAND | MF_UNCHECKED );
+ if ( g_qeglobals.d_savedinfo.exclude & EXCLUDE_CAULK )
+ pMenu->CheckMenuItem(ID_VIEW_SHOWCAULK, MF_BYCOMMAND | MF_UNCHECKED );
+ if ( g_qeglobals.d_savedinfo.exclude & EXCLUDE_ANGLES )
+ pMenu->CheckMenuItem(ID_VIEW_SHOWANGLES, MF_BYCOMMAND | MF_UNCHECKED );
+
+
+ pMenu->CheckMenuItem(ID_TOGGLE_LOCK, MF_BYCOMMAND | (g_PrefsDlg.m_bTextureLock) ? MF_CHECKED : MF_UNCHECKED);
+ pMenu->CheckMenuItem(ID_TOGGLE_ROTATELOCK, MF_BYCOMMAND | (g_PrefsDlg.m_bRotateLock) ? MF_CHECKED : MF_UNCHECKED);
+ pMenu->CheckMenuItem(ID_VIEW_CUBICCLIPPING, MF_BYCOMMAND | (g_PrefsDlg.m_bCubicClipping) ? MF_CHECKED : MF_UNCHECKED);
+ pMenu->CheckMenuItem (ID_VIEW_OPENGLLIGHTING, MF_BYCOMMAND | (g_PrefsDlg.m_bGLLighting) ? MF_CHECKED : MF_UNCHECKED );
+ pMenu->CheckMenuItem (ID_SNAPTOGRID, MF_BYCOMMAND | (!g_PrefsDlg.m_bNoClamp) ? MF_CHECKED : MF_UNCHECKED );
+ if (m_wndToolBar.GetSafeHwnd())
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_VIEW_CUBICCLIPPING, (g_PrefsDlg.m_bCubicClipping) ? TRUE : FALSE);
+
+ int n = g_PrefsDlg.m_nTextureScale;
+ int id;
+ switch (n)
+ {
+ case 10 : id = ID_TEXTURES_TEXTUREWINDOWSCALE_10; break;
+ case 25 : id = ID_TEXTURES_TEXTUREWINDOWSCALE_25; break;
+ case 50 : id = ID_TEXTURES_TEXTUREWINDOWSCALE_50; break;
+ case 200 : id = ID_TEXTURES_TEXTUREWINDOWSCALE_200; break;
+ default : id = ID_TEXTURES_TEXTUREWINDOWSCALE_100; break;
+ }
+ CheckTextureScale(id);
+
+
+ }
+ if (g_qeglobals.d_project_entity)
+ {
+ FillTextureMenu(); // redundant but i'll clean it up later.. yeah right..
+ FillBSPMenu();
+ LoadMruInReg(g_qeglobals.d_lpMruMenu,"Software\\id\\QuakeEd4\\MRU");
+ PlaceMenuMRUItem(g_qeglobals.d_lpMruMenu,::GetSubMenu(::GetMenu(GetSafeHwnd()),0), ID_FILE_EXIT);
+ }
+}
+
+void CMainFrame::ShowMenuItemKeyBindings(CMenu *pMenu)
+{
+ int i, j;
+ char key[1024], *ptr;
+ MENUITEMINFO MenuItemInfo;
+
+ //return;
+ for (i = 0; i < g_nCommandCount; i++)
+ {
+ memset(&MenuItemInfo, 0, sizeof(MENUITEMINFO));
+ MenuItemInfo.cbSize = sizeof(MENUITEMINFO);
+ MenuItemInfo.fMask = MIIM_TYPE;
+ MenuItemInfo.dwTypeData = key;
+ MenuItemInfo.cch = sizeof(key);
+ if (!pMenu->GetMenuItemInfo(g_Commands[i].m_nCommand, &MenuItemInfo))
+ continue;
+ if (MenuItemInfo.fType != MFT_STRING)
+ continue;
+ ptr = strchr(key, '\t');
+ if (ptr) *ptr = '\0';
+ strcat(key, "\t");
+ if (g_Commands[i].m_nModifiers) // are there modifiers present?
+ {
+ if (g_Commands[i].m_nModifiers & RAD_SHIFT)
+ strcat(key, "Shift-");
+ if (g_Commands[i].m_nModifiers & RAD_ALT)
+ strcat(key, "Alt-");
+ if (g_Commands[i].m_nModifiers & RAD_CONTROL)
+ strcat(key, "Ctrl-");
+ }
+ for (j = 0; j < g_nKeyCount; j++)
+ {
+ if (g_Commands[i].m_nKey == g_Keys[j].m_nVKKey)
+ {
+ strcat(key, g_Keys[j].m_strName);
+ break;
+ }
+ }
+ if (j >= g_nKeyCount)
+ {
+ sprintf(&key[strlen(key)], "%c", g_Commands[i].m_nKey);
+ }
+ memset(&MenuItemInfo, 0, sizeof(MENUITEMINFO));
+ MenuItemInfo.cbSize = sizeof(MENUITEMINFO);
+ MenuItemInfo.fMask = MIIM_TYPE;
+ MenuItemInfo.fType = MFT_STRING;
+ MenuItemInfo.dwTypeData = key;
+ MenuItemInfo.cch = strlen(key);
+ SetMenuItemInfo(pMenu->m_hMenu, g_Commands[i].m_nCommand, FALSE, &MenuItemInfo);
+ }
+}
+
+int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
+{
+
+ //Init3Dfx();
+
+ char* pBuffer = g_strAppPath.GetBufferSetLength(_MAX_PATH + 1);
+ int nResult = ::GetModuleFileName(NULL, pBuffer, _MAX_PATH);
+ ASSERT(nResult != 0);
+ pBuffer[g_strAppPath.ReverseFind('\\') + 1] = '\0';
+ g_strAppPath.ReleaseBuffer();
+
+ InitCommonControls ();
+ g_qeglobals.d_hInstance = AfxGetInstanceHandle();
+ MFCCreate(AfxGetInstanceHandle());
+
+ //g_PrefsDlg.LoadPrefs();
+
+ if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
+ return -1;
+
+ UINT nStyle;
+ UINT nID = (g_PrefsDlg.m_bWideToolbar) ? IDR_TOOLBAR_ADVANCED : IDR_TOOLBAR1;
+
+ if (!m_wndToolBar.Create(this) ||
+ !m_wndToolBar.LoadToolBar(nID))
+ {
+ TRACE0("Failed to create toolbar\n");
+ return -1; // fail to create
+ }
+
+ if (!m_wndStatusBar.Create(this) ||
+ !m_wndStatusBar.SetIndicators(indicators,
+ sizeof(indicators)/sizeof(UINT)))
+ {
+ TRACE0("Failed to create status bar\n");
+ return -1; // fail to create
+ }
+
+#if 0
+ if (!m_wndScaleBar.Create(this) ||
+ !m_wndScaleBar.LoadToolBar(IDR_TOOLBAR_SCALELOCK))
+ {
+ TRACE0("Failed to create scaling toolbar\n");
+ return -1; // fail to create
+ }
+#endif
+
+ // TODO: Remove this if you don't want tool tips or a resizeable toolbar
+ m_wndToolBar.SetBarStyle(m_wndToolBar.GetBarStyle() |
+ CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC);
+
+ // TODO: Delete these three lines if you don't want the toolbar to
+ // be dockable
+ m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
+ EnableDocking(CBRS_ALIGN_ANY);
+ DockControlBar(&m_wndToolBar);
+
+ //m_wndScaleBar.SetBarStyle(m_wndScaleBar.GetBarStyle() | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC);
+ //m_wndScaleBar.EnableDocking(CBRS_ALIGN_ANY);
+ //m_wndScaleBar.ShowWindow(SW_HIDE);
+
+ int nImage;
+ int nIndex = m_wndToolBar.CommandToIndex(ID_VIEW_CAMERATOGGLE);
+ if (nIndex >= 0)
+ {
+ m_wndToolBar.GetButtonInfo(nIndex, nID, nStyle, nImage);
+ m_wndToolBar.SetButtonInfo(nIndex, nID, TBBS_CHECKBOX, nImage);
+ m_wndToolBar.GetToolBarCtrl().CheckButton(nID);
+ }
+ m_bCamPreview = true;
+
+ nIndex = m_wndToolBar.CommandToIndex(ID_VIEW_CUBICCLIPPING);
+ if (nIndex >= 0)
+ {
+ m_wndToolBar.GetButtonInfo(nIndex, nID, nStyle, nImage);
+ m_wndToolBar.SetButtonInfo(nIndex, nID, TBBS_CHECKBOX, nImage);
+ }
+ nIndex = m_wndToolBar.CommandToIndex(ID_VIEW_ENTITY);
+ if (nIndex >= 0)
+ {
+ m_wndToolBar.GetButtonInfo(nIndex, nID, nStyle, nImage);
+ m_wndToolBar.SetButtonInfo(nIndex, nID, TBBS_CHECKBOX, nImage);
+ }
+ nIndex = m_wndToolBar.CommandToIndex(ID_VIEW_CLIPPER);
+ if (nIndex >= 0)
+ {
+ m_wndToolBar.GetButtonInfo(nIndex, nID, nStyle, nImage);
+ m_wndToolBar.SetButtonInfo(nIndex, nID, TBBS_CHECKBOX, nImage);
+ }
+ nIndex = m_wndToolBar.CommandToIndex(ID_SELECT_MOUSEROTATE);
+ if (nIndex >= 0)
+ {
+ m_wndToolBar.GetButtonInfo(nIndex, nID, nStyle, nImage);
+ m_wndToolBar.SetButtonInfo(nIndex, nID, TBBS_CHECKBOX, nImage);
+ }
+
+ nIndex = m_wndToolBar.CommandToIndex(ID_SELECT_MOUSESCALE);
+ if (nIndex >= 0)
+ {
+ m_wndToolBar.GetButtonInfo(nIndex, nID, nStyle, nImage);
+ m_wndToolBar.SetButtonInfo(nIndex, nID, TBBS_CHECKBOX, nImage);
+ }
+
+ nIndex = m_wndToolBar.CommandToIndex(ID_SCALELOCKX);
+ if (nIndex >= 0)
+ {
+ m_wndToolBar.GetButtonInfo(nIndex, nID, nStyle, nImage);
+ m_wndToolBar.SetButtonInfo(nIndex, nID, TBBS_CHECKBOX, nImage);
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_SCALELOCKX, FALSE);
+ }
+
+ nIndex = m_wndToolBar.CommandToIndex(ID_SCALELOCKY);
+ if (nIndex >= 0)
+ {
+ m_wndToolBar.GetButtonInfo(nIndex, nID, nStyle, nImage);
+ m_wndToolBar.SetButtonInfo(nIndex, nID, TBBS_CHECKBOX, nImage);
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_SCALELOCKY, FALSE);
+ }
+
+ nIndex = m_wndToolBar.CommandToIndex(ID_SCALELOCKZ);
+ if (nIndex >= 0)
+ {
+ m_wndToolBar.GetButtonInfo(nIndex, nID, nStyle, nImage);
+ m_wndToolBar.SetButtonInfo(nIndex, nID, TBBS_CHECKBOX, nImage);
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_SCALELOCKZ, FALSE);
+ }
+
+#ifdef QUAKE3
+ nIndex = m_wndToolBar.CommandToIndex(ID_DONTSELECTCURVE);
+ if (nIndex >= 0)
+ {
+ m_wndToolBar.GetButtonInfo(nIndex, nID, nStyle, nImage);
+ m_wndToolBar.SetButtonInfo(nIndex, nID, TBBS_CHECKBOX, nImage);
+ }
+ nIndex = m_wndToolBar.CommandToIndex(ID_PATCH_SHOWBOUNDINGBOX);
+ if (nIndex >= 0)
+ {
+ m_wndToolBar.GetButtonInfo(nIndex, nID, nStyle, nImage);
+ m_wndToolBar.SetButtonInfo(nIndex, nID, TBBS_CHECKBOX, nImage);
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_PATCH_SHOWBOUNDINGBOX, TRUE);
+ }
+ nIndex = m_wndToolBar.CommandToIndex(ID_PATCH_WELD);
+ if (nIndex >= 0)
+ {
+ m_wndToolBar.GetButtonInfo(nIndex, nID, nStyle, nImage);
+ m_wndToolBar.SetButtonInfo(nIndex, nID, TBBS_CHECKBOX, nImage);
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_PATCH_WELD, TRUE);
+ }
+ nIndex = m_wndToolBar.CommandToIndex(ID_PATCH_DRILLDOWN);
+ if (nIndex >= 0)
+ {
+ m_wndToolBar.GetButtonInfo(nIndex, nID, nStyle, nImage);
+ m_wndToolBar.SetButtonInfo(nIndex, nID, TBBS_CHECKBOX, nImage);
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_PATCH_DRILLDOWN, TRUE);
+ }
+ nIndex = m_wndToolBar.CommandToIndex(ID_PATCH_BEND);
+ if (nIndex >= 0)
+ {
+ m_wndToolBar.GetButtonInfo(nIndex, nID, nStyle, nImage);
+ m_wndToolBar.SetButtonInfo(nIndex, nID, TBBS_CHECKBOX, nImage);
+ }
+ nIndex = m_wndToolBar.CommandToIndex(ID_PATCH_INSDEL);
+ if (nIndex >= 0)
+ {
+ m_wndToolBar.GetButtonInfo(nIndex, nID, nStyle, nImage);
+ m_wndToolBar.SetButtonInfo(nIndex, nID, TBBS_CHECKBOX, nImage);
+ }
+#else
+ m_wndToolBar.GetToolBarCtrl().HideButton(ID_DONTSELECTCURVE);
+ m_wndToolBar.GetToolBarCtrl().HideButton(ID_PATCH_SHOWBOUNDINGBOX);
+ m_wndToolBar.GetToolBarCtrl().HideButton(ID_PATCH_WELD);
+ m_wndToolBar.GetToolBarCtrl().HideButton(ID_PATCH_WIREFRAME);
+#endif
+ g_nScaleHow = 0;
+
+
+#ifdef QUAKE3
+ g_pParentWnd->GetMenu()->DestroyMenu();
+ CMenu* pMenu = new CMenu();
+ pMenu->LoadMenu(IDR_MENU_QUAKE3);
+ g_pParentWnd->SetMenu(pMenu);
+#else
+ CMenu* pMenu = GetMenu();
+#endif
+
+ m_wndTextureBar.Create(this, IDD_TEXTUREBAR, CBRS_BOTTOM, 7433);
+ m_wndTextureBar.EnableDocking(CBRS_ALIGN_ANY);
+ DockControlBar(&m_wndTextureBar);
+
+ g_qeglobals.d_lpMruMenu = CreateMruMenuDefault();
+
+ m_bAutoMenuEnable = FALSE;
+
+ LoadCommandMap();
+
+ ShowMenuItemKeyBindings(pMenu);
+
+ CFont* pFont = new CFont();
+ pFont->CreatePointFont(g_PrefsDlg.m_nStatusSize * 10, "Arial");
+ m_wndStatusBar.SetFont(pFont);
+
+ OnPluginsRefresh();
+
+ if (g_PrefsDlg.m_bRunBefore == FALSE)
+ {
+ g_PrefsDlg.m_bRunBefore = TRUE;
+ g_PrefsDlg.SavePrefs();
+/*
+ if (MessageBox("Would you like QERadiant to build and load a default project? If this is the first time you have run QERadiant or you are not familiar with editing QE4 project files directly, this is HIGHLY recommended", "Create a default project?", MB_YESNO) == IDYES)
+ {
+ OnFileNewproject();
+ }
+*/
+ }
+ else
+ {
+ // hack that keeps SGI OpenGL from crashing on texture load with no map
+#if 0
+ if (g_PrefsDlg.m_bSGIOpenGL)
+ {
+ vec3_t vMin, vMax;
+ vMin[0] = vMin[1] = vMin[2] = 0;
+ vMax[0] = vMax[1] = vMax[2] = 8;
+ brush_t* pBrush = Brush_Create(vMin, vMax, &g_qeglobals.d_texturewin.texdef);
+ Entity_LinkBrush (world_entity, pBrush);
+ Brush_Build(pBrush);
+ Brush_AddToList (pBrush, &active_brushes);
+ Select_Brush(pBrush);
+ Sys_UpdateWindows(W_ALL);
+ PostMessage(WM_COMMAND, ID_SELECTION_DELETE, 0);
+ }
+#endif
+ // load plugins before the first Map_LoadFile
+ // required for model plugins
+ if (g_PrefsDlg.m_bLoadLastMap && g_PrefsDlg.m_strLastMap.GetLength() > 0)
+ Map_LoadFile(g_PrefsDlg.m_strLastMap.GetBuffer(0));
+ }
+
+ SetGridStatus();
+ SetTexValStatus();
+ SetButtonMenuStates();
+ LoadBarState("RadiantToolBars2");
+ if (!g_PrefsDlg.m_bTextureBar)
+ ShowControlBar(&m_wndTextureBar, FALSE, TRUE);
+ else
+ ShowControlBar(&m_wndTextureBar, TRUE, TRUE);
+
+ ShowControlBar(&m_wndToolBar, (m_wndToolBar.GetStyle() & WS_VISIBLE), TRUE);
+
+ SetActiveXY(m_pXYWnd);
+ m_pXYWnd->SetFocus();
+
+ PostMessage(WM_KEYDOWN, 'O', NULL);
+
+ return 0;
+}
+
+void CMainFrame::LoadCommandMap()
+{
+ CString strINI;
+ char* pBuff = new char[1024];
+ if (g_PrefsDlg.m_strUserPath.GetLength() > 0)
+ strINI = g_PrefsDlg.m_strUserPath;
+ else
+ {
+ strINI = g_strAppPath;
+ strINI += "\\radiant.ini";
+ }
+
+ for (int i = 0; i < g_nCommandCount; i++)
+ {
+ int nLen = GetPrivateProfileString("Commands", g_Commands[i].m_strCommand, "", pBuff, 1024, strINI);
+ if (nLen > 0)
+ {
+ CString strBuff = pBuff;
+ strBuff.TrimLeft();
+ strBuff.TrimRight();
+ int nSpecial = strBuff.Find("+alt");
+ g_Commands[i].m_nModifiers = 0;
+ if (nSpecial >= 0)
+ {
+ g_Commands[i].m_nModifiers |= RAD_ALT;
+ FindReplace(strBuff, "+alt", "");
+ }
+ nSpecial = strBuff.Find("+ctrl");
+ if (nSpecial >= 0)
+ {
+ g_Commands[i].m_nModifiers |= RAD_CONTROL;
+ FindReplace(strBuff, "+ctrl", "");
+ }
+ nSpecial = strBuff.Find("+shift");
+ if (nSpecial >= 0)
+ {
+ g_Commands[i].m_nModifiers |= RAD_SHIFT;
+ FindReplace(strBuff, "+shift", "");
+ }
+ strBuff.TrimLeft();
+ strBuff.TrimRight();
+ strBuff.MakeUpper();
+ if (nLen == 1) // most often case.. deal with first
+ {
+ g_Commands[i].m_nKey = __toascii(strBuff.GetAt(0));
+ }
+ else // special key
+ {
+ for (int j = 0; j < g_nKeyCount; j++)
+ {
+ if (strBuff.CompareNoCase(g_Keys[j].m_strName) == 0)
+ {
+ g_Commands[i].m_nKey = g_Keys[j].m_nVKKey;
+ break;
+ }
+ }
+ }
+ }
+ }
+ delete []pBuff;
+}
+
+BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
+{
+ // TODO: Modify the Window class or styles here by modifying
+ // the CREATESTRUCT cs
+ return CFrameWnd::PreCreateWindow(cs);
+}
+
+/////////////////////////////////////////////////////////////////////////////
+// CMainFrame diagnostics
+
+#ifdef _DEBUG
+void CMainFrame::AssertValid() const
+{
+ CFrameWnd::AssertValid();
+}
+
+void CMainFrame::Dump(CDumpContext& dc) const
+{
+ CFrameWnd::Dump(dc);
+}
+
+#endif //_DEBUG
+
+/////////////////////////////////////////////////////////////////////////////
+// CMainFrame message handlers
+void CMainFrame::CreateQEChildren()
+{
+ // the project file can be specified on the command line,
+ // or implicitly found in the scripts directory
+ bool bProjectLoaded = false;
+ if (AfxGetApp()->m_lpCmdLine && strlen(AfxGetApp()->m_lpCmdLine))
+ {
+ ParseCommandLine (AfxGetApp()->m_lpCmdLine);
+ bProjectLoaded = QE_LoadProject(argv[1]);
+ }
+ else
+ {
+ if (g_PrefsDlg.m_bLoadLast && g_PrefsDlg.m_strLastProject.GetLength() > 0)
+ {
+ bProjectLoaded = QE_LoadProject(g_PrefsDlg.m_strLastProject.GetBuffer(0));
+ }
+ if (!bProjectLoaded)
+ {
+ CString str = g_strAppPath;
+ AddSlash(str);
+ str += "../baseq3/scripts/quake.qe4";
+ char cWork[1024];
+ char *pFile = NULL;
+ GetFullPathName(str, 1024, cWork, &pFile);
+ bProjectLoaded = QE_LoadProject(cWork);
+ }
+ if (!bProjectLoaded)
+ {
+ bProjectLoaded = QE_LoadProject("scripts/quake.qe4");
+ }
+ }
+
+ if (!bProjectLoaded)
+ {
+#if 0
+ // let's try the default project directory..
+ char* pBuff = new char[1024];
+ ::GetCurrentDirectory(1024, pBuff);
+ CString strDefProj = g_strAppPath;
+ AddSlash(strDefProj);
+ strDefProj += "defproj";
+ if (::SetCurrentDirectory(strDefProj))
+ {
+ bProjectLoaded = QE_LoadProject("scripts/quake.qe4");
+ if (bProjectLoaded)
+ {
+ // setup auto load stuff for the default map
+ g_PrefsDlg.m_bLoadLast = TRUE;
+ AddSlash(strDefProj);
+ strDefProj += "maps\\defproj.map";
+ g_PrefsDlg.m_strLastMap = strDefProj;
+ g_PrefsDlg.SavePrefs();
+ }
+ }
+ else
+ {
+ ::SetCurrentDirectory(pBuff);
+ }
+ delete []pBuff;
+#endif
+
+ if (!bProjectLoaded)
+ {
+ Sys_Printf ("Using default.qe4. You may experience problems. See the readme.txt\n");
+ CString strProj = g_strAppPath;
+ strProj += "\\default.qe4";
+ bProjectLoaded = QE_LoadProject(strProj.GetBuffer(0));
+
+ if (!bProjectLoaded)
+ {
+ CFileDialog dlgFile(true, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, "Q3Radiant Project files (*.qe4, *.prj)|*.qe4|*.prj||", this);
+ if (dlgFile.DoModal() == IDOK)
+ bProjectLoaded = QE_LoadProject(dlgFile.GetPathName().GetBuffer(0));
+ }
+ }
+ }
+
+ if (!bProjectLoaded)
+ Error("Unable to load project file. It was unavailable in the scripts path and the default could not be found");
+
+
+ if (g_PrefsDlg.m_bPAK == TRUE)
+ {
+ // FIXME: pay attention to Q3 pref
+ //InitPakFile(ValueForKey(g_qeglobals.d_project_entity, "basepath"), g_PrefsDlg.m_strPAKFile);
+ InitPakFile(ValueForKey(g_qeglobals.d_project_entity, "basepath"), NULL);
+ }
+
+ QE_Init ();
+
+ Sys_Printf ("Entering message loop\n");
+
+ m_bDoLoop = true;
+ SetTimer(QE_TIMER0, 1000, NULL);
+
+}
+
+BOOL CMainFrame::OnCommand(WPARAM wParam, LPARAM lParam)
+{
+ return CFrameWnd::OnCommand(wParam, lParam);
+}
+
+LRESULT CMainFrame::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam)
+{
+ RoutineProcessing();
+ return CFrameWnd::DefWindowProc(message, wParam, lParam);
+}
+
+
+void CMainFrame::RoutineProcessing()
+{
+ if (m_bDoLoop)
+ {
+ double time = 0.0;
+ double oldtime = 0.0;
+ double delta= 0.0;
+
+ CheckBspProcess ();
+ time = Sys_DoubleTime ();
+ delta = time - oldtime;
+ oldtime = time;
+ if (delta > 0.2)
+ delta = 0.2;
+
+ // run time dependant behavior
+ if (m_pCamWnd)
+ m_pCamWnd->Cam_MouseControl(delta);
+
+ if (g_PrefsDlg.m_bQE4Painting && g_nUpdateBits)
+ {
+ int nBits = g_nUpdateBits; // this is done to keep this routine from being
+ g_nUpdateBits = 0; // re-entered due to the paint process.. only
+ UpdateWindows(nBits); // happens in rare cases but causes a stack overflow
+ }
+
+ }
+}
+
+LRESULT CMainFrame::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
+{
+ return CFrameWnd::WindowProc(message, wParam, lParam);
+}
+
+bool MouseDown()
+{
+ if (::GetAsyncKeyState(VK_LBUTTON))
+ return true;
+ if (::GetAsyncKeyState(VK_RBUTTON))
+ return true;
+ if (::GetAsyncKeyState(VK_MBUTTON))
+ return true;
+ return false;
+}
+
+
+void CMainFrame::OnTimer(UINT nIDEvent)
+{
+ if (!MouseDown())
+ {
+ QE_CountBrushesAndUpdateStatusBar();
+ QE_CheckAutoSave();
+ }
+}
+struct SplitInfo
+{
+ int m_nMin;
+ int m_nCur;
+};
+
+bool LoadWindowPlacement(HWND hwnd, const char* pName)
+{
+ WINDOWPLACEMENT wp;
+ wp.length = sizeof(WINDOWPLACEMENT);
+ LONG lSize = sizeof(wp);
+ if (LoadRegistryInfo(pName, &wp, &lSize))
+ {
+ ::SetWindowPlacement(hwnd, &wp);
+ return true;
+ }
+ return false;
+}
+
+void SaveWindowPlacement(HWND hwnd, const char* pName)
+{
+ WINDOWPLACEMENT wp;
+ wp.length = sizeof(WINDOWPLACEMENT);
+ if (::GetWindowPlacement(hwnd, &wp))
+ {
+ SaveRegistryInfo(pName, &wp, sizeof(wp));
+ }
+}
+
+
+void CMainFrame::OnDestroy()
+{
+ KillTimer(QE_TIMER0);
+
+ SaveBarState("RadiantToolBars2");
+
+ // FIXME
+ // original mru stuff needs replaced with mfc stuff
+ SaveMruInReg(g_qeglobals.d_lpMruMenu,"Software\\id\\QuakeEd4\\MRU");
+
+ DeleteMruMenu(g_qeglobals.d_lpMruMenu);
+
+ SaveWindowPlacement(GetSafeHwnd(), "Radiant::MainWindowPlace");
+ //SaveWindowState(GetSafeHwnd(), "Radiant::MainWindow");
+ //if (m_nCurrentStyle == QR_QE4)
+ //SaveWindowPlacement(g_qeglobals.d_hwndEntity, "EntityWindowPlace");
+
+ if (m_nCurrentStyle == 0 || m_nCurrentStyle == 3)
+ {
+ SaveWindowState(m_wndSplit.GetSafeHwnd(), "Radiant::Split");
+ SaveWindowState(m_wndSplit2.GetSafeHwnd(), "Radiant::Split2");
+ SaveWindowState(m_wndSplit3.GetSafeHwnd(), "Radiant::Split3");
+
+ SplitInfo spinfo;
+ m_wndSplit.GetRowInfo(0, spinfo.m_nCur, spinfo.m_nMin);
+ SaveRegistryInfo("Radiant::Split::Row_0", &spinfo, sizeof(spinfo));
+ m_wndSplit.GetRowInfo(1, spinfo.m_nCur, spinfo.m_nMin);
+ SaveRegistryInfo("Radiant::Split::Row_1", &spinfo, sizeof(spinfo));
+
+ m_wndSplit2.GetColumnInfo(0, spinfo.m_nCur, spinfo.m_nMin);
+ SaveRegistryInfo("Radiant::Split2::Col_0", &spinfo, sizeof(spinfo));
+ m_wndSplit2.GetColumnInfo(1, spinfo.m_nCur, spinfo.m_nMin);
+ SaveRegistryInfo("Radiant::Split2::Col_1", &spinfo, sizeof(spinfo));
+ m_wndSplit2.GetColumnInfo(2, spinfo.m_nCur, spinfo.m_nMin);
+ SaveRegistryInfo("Radiant::Split2::Col_2", &spinfo, sizeof(spinfo));
+
+ m_wndSplit3.GetRowInfo(0, spinfo.m_nCur, spinfo.m_nMin);
+ SaveRegistryInfo("Radiant::Split3::Row_0", &spinfo, sizeof(spinfo));
+ m_wndSplit3.GetRowInfo(1, spinfo.m_nCur, spinfo.m_nMin);
+ SaveRegistryInfo("Radiant::Split3::Row_1", &spinfo, sizeof(spinfo));
+ }
+ else
+ {
+ SaveWindowPlacement(m_pXYWnd->GetSafeHwnd(), "xywindow");
+ SaveWindowPlacement(m_pXZWnd->GetSafeHwnd(), "xzwindow");
+ SaveWindowPlacement(m_pYZWnd->GetSafeHwnd(), "yzwindow");
+ SaveWindowPlacement(m_pCamWnd->GetSafeHwnd(), "camerawindow");
+ SaveWindowPlacement(m_pZWnd->GetSafeHwnd(), "zwindow");
+ SaveWindowState(m_pTexWnd->GetSafeHwnd(), "texwindow");
+ SaveWindowState(m_pEditWnd->GetSafeHwnd(), "editwindow");
+ }
+
+ if (m_pXYWnd->GetSafeHwnd())
+ m_pXYWnd->SendMessage(WM_DESTROY, 0, 0);
+ delete m_pXYWnd; m_pXYWnd = NULL;
+
+ if (m_pYZWnd->GetSafeHwnd())
+ m_pYZWnd->SendMessage(WM_DESTROY, 0, 0);
+ delete m_pYZWnd; m_pYZWnd = NULL;
+
+ if (m_pXZWnd->GetSafeHwnd())
+ m_pXZWnd->SendMessage(WM_DESTROY, 0, 0);
+ delete m_pXZWnd; m_pXZWnd = NULL;
+
+ if (m_pZWnd->GetSafeHwnd())
+ m_pZWnd->SendMessage(WM_DESTROY, 0, 0);
+ delete m_pZWnd; m_pZWnd = NULL;
+
+ if (m_pTexWnd->GetSafeHwnd())
+ m_pTexWnd->SendMessage(WM_DESTROY, 0, 0);
+ delete m_pTexWnd; m_pTexWnd = NULL;
+
+ if (m_pEditWnd->GetSafeHwnd())
+ m_pEditWnd->SendMessage(WM_DESTROY, 0, 0);
+ delete m_pEditWnd; m_pEditWnd = NULL;
+
+ if (m_pCamWnd->GetSafeHwnd())
+ m_pCamWnd->SendMessage(WM_DESTROY, 0, 0);
+ delete m_pCamWnd;m_pCamWnd = NULL;
+
+ SaveRegistryInfo("SavedInfo", &g_qeglobals.d_savedinfo, sizeof(g_qeglobals.d_savedinfo));
+
+ if (strcmpi(currentmap, "unnamed.map") != 0)
+ {
+ g_PrefsDlg.m_strLastMap = currentmap;
+ g_PrefsDlg.SavePrefs();
+ }
+ CleanUpEntities();
+
+ while (active_brushes.next != &active_brushes)
+ Brush_Free (active_brushes.next, false);
+ while (selected_brushes.next != &selected_brushes)
+ Brush_Free (selected_brushes.next, false);
+ while (filtered_brushes.next != &filtered_brushes)
+ Brush_Free (filtered_brushes.next, false);
+
+ while (entities.next != &entities)
+ Entity_Free (entities.next);
+
+ epair_t* pEPair = g_qeglobals.d_project_entity->epairs;
+ while (pEPair)
+ {
+ epair_t* pNextEPair = pEPair->next;
+ free (pEPair->key);
+ free (pEPair->value);
+ free (pEPair);
+ pEPair = pNextEPair;
+ }
+
+ entity_t* pEntity = g_qeglobals.d_project_entity->next;
+ while (pEntity != NULL && pEntity != g_qeglobals.d_project_entity)
+ {
+ entity_t* pNextEntity = pEntity->next;
+ Entity_Free(pEntity);
+ pEntity = pNextEntity;
+ }
+
+ Texture_Cleanup();
+
+ if (world_entity)
+ Entity_Free(world_entity);
+
+ if (notexture)
+ {
+ // Timo
+ // Surface properties plugin
+#ifdef _DEBUG
+ if ( !notexture->pData )
+ Sys_Printf("WARNING: found a qtexture_t* with no IPluginQTexture\n");
+#endif
+ if ( notexture->pData )
+ GETPLUGINTEXDEF(notexture)->DecRef();
+
+ free(notexture);
+ }
+
+ //if (current_texture)
+ // free(current_texture);
+ ClosePakFile();
+
+ FreeShaders();
+
+ CFrameWnd::OnDestroy();
+}
+
+void CMainFrame::OnClose()
+{
+ if (ConfirmModified())
+ {
+ CFrameWnd::OnClose();
+ }
+}
+
+void CMainFrame::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags)
+{
+ // run through our list to see if we have a handler for nChar
+ //
+ for (int i = 0; i < g_nCommandCount; i++)
+ {
+ if (g_Commands[i].m_nKey == nChar) // find a match?
+ {
+ bool bGo = true;
+ if (g_Commands[i].m_nModifiers & RAD_PRESS)
+ {
+ int nModifiers = g_Commands[i].m_nModifiers & ~RAD_PRESS;
+ if (nModifiers) // are there modifiers present?
+ {
+ if (nModifiers & RAD_ALT)
+ if (!(GetKeyState(VK_MENU) & 0x8000))
+ bGo = false;
+ if (nModifiers & RAD_CONTROL)
+ if (!(GetKeyState(VK_CONTROL) & 0x8000))
+ bGo = false;
+ if (nModifiers & RAD_SHIFT)
+ if (!(GetKeyState(VK_SHIFT) & 0x8000))
+ bGo = false;
+ }
+ else // no modifiers make sure none of those keys are pressed
+ {
+ if (GetKeyState(VK_MENU) & 0x8000)
+ bGo = false;
+ if (GetKeyState(VK_CONTROL) & 0x8000)
+ bGo = false;
+ if (GetKeyState(VK_SHIFT) & 0x8000)
+ bGo = false;
+ }
+ if (bGo)
+ {
+ SendMessage(WM_COMMAND, g_Commands[i].m_nCommand, 0);
+ break;
+ }
+ }
+ }
+ }
+}
+
+bool CamOK(unsigned int nKey)
+{
+ if (nKey == VK_UP || nKey == VK_LEFT || nKey == VK_RIGHT || nKey == VK_DOWN)
+ {
+ if (::GetAsyncKeyState(nKey))
+ return true;
+ else
+ return false;
+ }
+ return true;
+}
+
+
+void CMainFrame::OnSysKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
+{
+ //OnKeyDown(nChar, nRepCnt, nFlags);
+ if (nChar == VK_DOWN)
+ {
+ OnKeyDown(nChar, nRepCnt, nFlags);
+ }
+ CFrameWnd::OnSysKeyDown(nChar, nRepCnt, nFlags);
+}
+
+void CMainFrame::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
+{
+ for (int i = 0; i < g_nCommandCount; i++)
+ {
+ if (g_Commands[i].m_nKey == nChar) // find a match?
+ {
+ // check modifiers
+ unsigned int nState = 0;
+ if (GetKeyState(VK_MENU) & 0x8000)
+ nState |= RAD_ALT;
+ if (GetKeyState(VK_CONTROL) & 0x8000)
+ nState |= RAD_CONTROL;
+ if (GetKeyState(VK_SHIFT) & 0x8000)
+ nState |= RAD_SHIFT;
+ if ((g_Commands[i].m_nModifiers & 0x7) == nState)
+ {
+ SendMessage(WM_COMMAND, g_Commands[i].m_nCommand, 0);
+ break;
+ }
+ }
+ }
+ CFrameWnd::OnKeyDown(nChar, nRepCnt, nFlags);
+}
+
+BOOL CMainFrame::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext)
+{
+ g_qeglobals.d_hwndMain = GetSafeHwnd();
+ g_qeglobals.d_hwndStatus = GetMessageBar()->GetSafeHwnd();
+
+/*
+ if (g_PrefsDlg.m_bRunBefore == FALSE)
+ {
+ MessageBox("In the following dialog, please make sure the Quake2 .exe information is correct.\nQERadiant will NOT run correctly without this information");
+ g_PrefsDlg.DoModal();
+ }
+*/
+
+ m_nCurrentStyle = g_PrefsDlg.m_nView;
+
+ CreateEntityWindow(AfxGetInstanceHandle());
+
+ g_pGroupDlg->Create( IDD_DLG_GROUP, this);
+ g_qeglobals.d_hwndGroup = g_pGroupDlg->GetSafeHwnd();
+ ::SetParent(g_qeglobals.d_hwndGroup, g_qeglobals.d_hwndEntity);
+ g_pGroupDlg->ShowWindow(SW_SHOW);
+
+ if (!LoadWindowPlacement(GetSafeHwnd(), "Radiant::MainWindowPlace"))
+ {
+ LoadWindowState(GetSafeHwnd(), "Radiant::MainWindow");
+ }
+
+ //if (m_nCurrentStyle == QR_QE4)
+ // LoadWindowPlacement(g_qeglobals.d_hwndEntity, "EntityWindowPlace");
+
+ CRect rect(5,25, 100, 100);
+ CRect rctParent;
+ GetClientRect(rctParent);
+
+ if (g_PrefsDlg.m_nView == 0 || g_PrefsDlg.m_nView == 3)
+ {
+ m_wndSplit.CreateStatic(this, 2, 1);
+ m_wndSplit2.CreateStatic(&m_wndSplit, 1, 3);
+ m_wndSplit3.CreateStatic(&m_wndSplit2, 2,1);
+
+ m_wndSplit.CreateView(1,0,RUNTIME_CLASS(CEditWnd), CSize(25, 100), pContext);
+ g_pEdit = dynamic_cast<CEdit*>(m_wndSplit.GetPane(1,0));
+ if (g_pEdit)
+ g_qeglobals.d_hwndEdit = g_pEdit->GetSafeHwnd();
+
+ m_wndSplit3.CreateView(0,0,RUNTIME_CLASS(CCamWnd), CSize(25, 100), pContext);
+ m_pCamWnd = dynamic_cast<CCamWnd*>(m_wndSplit3.GetPane(0,0));
+
+ m_wndSplit2.CreateView(0,1,RUNTIME_CLASS(CXYWnd), CSize(25, 100), pContext);
+ m_pXYWnd = dynamic_cast<CXYWnd*>(m_wndSplit2.GetPane(0,1));
+ m_pXYWnd->SetViewType(XY);
+
+ m_pCamWnd->SetXYFriend(m_pXYWnd);
+
+ m_wndSplit2.CreateView(0,2,RUNTIME_CLASS(CZWnd), CSize(25, 100), pContext);
+ m_pZWnd = dynamic_cast<CZWnd*>(m_wndSplit2.GetPane(0,2));
+
+ m_wndSplit3.CreateView(1,0,RUNTIME_CLASS(CTexWnd), CSize(25, 100), pContext);
+ m_pTexWnd = dynamic_cast<CTexWnd*>(m_wndSplit3.GetPane(1,0));
+
+ CreateQEChildren();
+
+ if (g_PrefsDlg.m_nView == 0)
+ {
+ // the following bit switches the left and right views
+ CWnd* pRight = m_wndSplit2.GetPane(0,2);
+ long lRightID = ::GetWindowLong(pRight->GetSafeHwnd(), GWL_ID);
+ long lLeftID = ::GetWindowLong(m_wndSplit3.GetSafeHwnd(), GWL_ID);
+ ::SetWindowLong(pRight->GetSafeHwnd(), GWL_ID, lLeftID);
+ ::SetWindowLong(m_wndSplit3.GetSafeHwnd(), GWL_ID, lRightID);
+ }
+
+ m_wndSplit.SetRowInfo(0, rctParent.Height() * .85, 50);
+ m_wndSplit.SetRowInfo(1, rctParent.Height() * .15, 5);
+
+ float fLeft = (g_PrefsDlg.m_nView == 0) ? .05 : .25;
+ float fRight = (g_PrefsDlg.m_nView == 0) ? .25 : .05;
+ int nMin1 = (g_PrefsDlg.m_nView == 0) ? 10 : 25;
+ int nMin2 = (nMin1 == 10) ? 25 : 10;
+
+ m_wndSplit2.SetColumnInfo(0, rctParent.Width() * fLeft, nMin1);
+ m_wndSplit2.SetColumnInfo(1, rctParent.Width() * .70, 100);
+ m_wndSplit2.SetColumnInfo(2, rctParent.Width() * fRight, nMin2);
+
+ m_wndSplit3.SetRowInfo(1, (rctParent.Height() * .85) * .40, 15);
+ m_wndSplit3.SetRowInfo(0, (rctParent.Height() * .85) * .60, 15);
+
+ LoadWindowState(m_wndSplit.GetSafeHwnd(), "Radiant::Split");
+ LoadWindowState(m_wndSplit2.GetSafeHwnd(), "Radiant::Split2");
+ LoadWindowState(m_wndSplit3.GetSafeHwnd(), "Radiant::Split3");
+ ::ShowWindow(g_qeglobals.d_hwndEntity, SW_HIDE);
+
+ SplitInfo spinfo;
+ long lSize = sizeof(spinfo);
+ if (LoadRegistryInfo("Radiant::Split::Row_0", &spinfo, &lSize))
+ m_wndSplit.SetRowInfo(0, spinfo.m_nCur, spinfo.m_nMin);
+ if (LoadRegistryInfo("Radiant::Split::Row_1", &spinfo, &lSize))
+ m_wndSplit.SetRowInfo(1, spinfo.m_nCur, spinfo.m_nMin);
+
+ if (LoadRegistryInfo("Radiant::Split2::Col_0", &spinfo, &lSize))
+ m_wndSplit2.SetColumnInfo(0, spinfo.m_nCur, spinfo.m_nMin);
+ if (LoadRegistryInfo("Radiant::Split2::Col_1", &spinfo, &lSize))
+ m_wndSplit2.SetColumnInfo(1, spinfo.m_nCur, spinfo.m_nMin);
+ if (LoadRegistryInfo("Radiant::Split2::Col_2", &spinfo, &lSize))
+ m_wndSplit2.SetColumnInfo(2, spinfo.m_nCur, spinfo.m_nMin);
+
+ if (LoadRegistryInfo("Radiant::Split3::Row_0", &spinfo, &lSize))
+ m_wndSplit3.SetRowInfo(0, spinfo.m_nCur, spinfo.m_nMin);
+ if (LoadRegistryInfo("Radiant::Split3::Row_1", &spinfo, &lSize))
+ m_wndSplit3.SetRowInfo(1, spinfo.m_nCur, spinfo.m_nMin);
+
+ m_wndSplit.RecalcLayout();
+ m_wndSplit2.RecalcLayout();
+ m_wndSplit3.RecalcLayout();
+ }
+ else if (g_PrefsDlg.m_nView == 1)
+ {
+ m_pCamWnd = new CCamWnd();
+ m_pCamWnd->Create(CAMERA_WINDOW_CLASS, "", QE3_CHILDSTYLE, rect, this, 1234);
+
+ m_pZWnd = new CZWnd();
+ m_pZWnd->Create(Z_WINDOW_CLASS, "", QE3_CHILDSTYLE, rect, this, 1238);
+
+ m_pXYWnd = new CXYWnd();
+ m_pXYWnd->Create(XY_WINDOW_CLASS, "", QE3_CHILDSTYLE, rect, this, 1235);
+ m_pXYWnd->SetViewType(XY);
+
+ m_pXZWnd = new CXYWnd();
+ m_pXZWnd->Create(XY_WINDOW_CLASS, "", QE3_CHILDSTYLE, rect, this, 1236);
+ m_pXZWnd->SetViewType(XZ);
+
+ m_pYZWnd = new CXYWnd();
+ m_pYZWnd->Create(XY_WINDOW_CLASS, "", QE3_CHILDSTYLE, rect, this, 1237);
+ m_pYZWnd->SetViewType(YZ);
+
+ m_pCamWnd->SetXYFriend(m_pXYWnd);
+
+ m_pTexWnd = new CTexWnd();
+ m_pTexWnd->Create(TEXTURE_WINDOW_CLASS, "", QE3_SPLITTER_STYLE, rect, this, 1239);
+ ::SetParent(m_pTexWnd->GetSafeHwnd(), g_qeglobals.d_hwndEntity);
+
+ CRect rctWork;
+ // XY and Z windows are 2 pixels off of the height and one down from top so one pixel spacing vertically
+ // Z window takes up 10% of right edge
+ // XY window takes up 60% of middle
+ // TEX and CAM windows take up 30% of left
+#if 0
+ int xTex = 1;
+ int xXY = 1 + xTex + ((float)rctParent.Width()) * .30;
+ int xZ = 1 + xXY + ((float)rctParent.Width()) * .60;
+ int yXY = 1;
+ int yTex = 1 + ((float)rctParent.Height()) * .45;
+ m_pXYWnd->SetWindowPos(NULL, xXY, yXY, ((float)rctParent.Width()) * .60, rctParent.Height() - 2, SWP_SHOWWINDOW);
+ m_pXZWnd->SetWindowPos(NULL, xXY, yXY, ((float)rctParent.Width()) * .60, rctParent.Height() - 2, SWP_SHOWWINDOW);
+ m_pYZWnd->SetWindowPos(NULL, xXY, yXY, ((float)rctParent.Width()) * .60, rctParent.Height() - 2, SWP_SHOWWINDOW);
+ m_pCamWnd->SetWindowPos(NULL, xTex, yXY, ((float)rctParent.Width()) *.30, ((float)rctParent.Height()) * .45, SWP_SHOWWINDOW);
+ m_pTexWnd->SetWindowPos(NULL, xTex, yTex, ((float)rctParent.Width()) *.30, ((float)rctParent.Height()) * .45, SWP_SHOWWINDOW);
+#endif
+
+ LoadWindowPlacement(m_pXYWnd->GetSafeHwnd(), "xywindow");
+ LoadWindowPlacement(m_pXZWnd->GetSafeHwnd(), "xzwindow");
+ LoadWindowPlacement(m_pYZWnd->GetSafeHwnd(), "yzwindow");
+ LoadWindowPlacement(m_pCamWnd->GetSafeHwnd(), "camerawindow");
+ LoadWindowPlacement(m_pZWnd->GetSafeHwnd(), "zwindow");
+
+ if (!g_PrefsDlg.m_bXZVis)
+ m_pXZWnd->ShowWindow(SW_HIDE);
+ if (!g_PrefsDlg.m_bYZVis)
+ m_pYZWnd->ShowWindow(SW_HIDE);
+ if (!g_PrefsDlg.m_bZVis)
+ m_pZWnd->ShowWindow(SW_HIDE);
+
+ CreateQEChildren();
+ }
+ else // 4 way
+ {
+ m_wndSplit.CreateStatic(this, 2, 2);
+
+ m_wndSplit.CreateView(0,0,RUNTIME_CLASS(CCamWnd), CSize(25, 100), pContext);
+ m_pCamWnd = dynamic_cast<CCamWnd*>(m_wndSplit.GetPane(0,0));
+
+ m_wndSplit.CreateView(0,1,RUNTIME_CLASS(CXYWnd), CSize(25, 100), pContext);
+ m_pXYWnd = dynamic_cast<CXYWnd*>(m_wndSplit.GetPane(0,1));
+ m_pXYWnd->SetViewType(XY);
+
+ m_wndSplit.CreateView(1,0,RUNTIME_CLASS(CXYWnd), CSize(25, 100), pContext);
+ m_pYZWnd = dynamic_cast<CXYWnd*>(m_wndSplit.GetPane(1,0));
+ m_pYZWnd->SetViewType(YZ);
+
+ m_wndSplit.CreateView(1,1,RUNTIME_CLASS(CXYWnd), CSize(25, 100), pContext);
+ m_pXZWnd = dynamic_cast<CXYWnd*>(m_wndSplit.GetPane(1,1));
+ m_pXZWnd->SetViewType(XZ);
+
+ m_pCamWnd->SetXYFriend(m_pXYWnd);
+
+ m_pTexWnd = new CTexWnd();
+ m_pTexWnd->Create(TEXTURE_WINDOW_CLASS, "", QE3_SPLITTER_STYLE, rect, this, 1237);
+ ::SetParent(m_pTexWnd->GetSafeHwnd(), g_qeglobals.d_hwndEntity);
+
+ m_pZWnd = new CZWnd();
+ m_pZWnd->Create(Z_WINDOW_CLASS, "", QE3_CHILDSTYLE, rect, this, 1236);
+ m_pZWnd->ShowWindow(SW_HIDE);
+
+
+ //m_pEditWnd = new CRADEditWnd();
+ //m_pEditWnd->Create(NULL, "Console", QE3_STYLE, rect, this, 1238);
+ //g_pEdit = m_pEditWnd->GetEditWnd();
+ //if (g_pEdit)
+ // g_qeglobals.d_hwndEdit = g_pEdit->GetSafeHwnd();
+
+ LoadWindowState(m_pTexWnd->GetSafeHwnd(), "texwindow");
+ LoadWindowState(m_pEditWnd->GetSafeHwnd(), "editwindow");
+ ::ShowWindow(g_qeglobals.d_hwndEntity, SW_HIDE);
+
+ CreateQEChildren();
+
+ CRect rctParent;
+ GetClientRect(rctParent);
+
+ m_wndSplit.SetRowInfo(0, rctParent.Height() * .5, 50);
+ m_wndSplit.SetRowInfo(1, rctParent.Height() * .5, 50);
+
+ m_wndSplit.SetColumnInfo(0, rctParent.Width() * .5, 50);
+ m_wndSplit.SetColumnInfo(1, rctParent.Width() * .5, 50);
+
+ LoadWindowState(m_wndSplit.GetSafeHwnd(), "Radiant::SplitSPLIT");
+
+ m_wndSplit.RecalcLayout();
+ }
+
+ if (g_pEdit)
+ g_pEdit->SendMessage(WM_SETFONT, (WPARAM)::GetStockObject(DEFAULT_GUI_FONT), (LPARAM)TRUE);
+
+
+ if (m_pXYWnd)
+ m_pXYWnd->SetActive(true);
+ m_bSplittersOK = true;
+ Texture_SetMode(g_qeglobals.d_savedinfo.iTexMenu);
+
+ return TRUE;
+}
+
+CRect g_rctOld(0,0,0,0);
+void CMainFrame::OnSize(UINT nType, int cx, int cy)
+{
+ CFrameWnd::OnSize(nType, cx, cy);
+
+ CRect rctParent;
+ GetClientRect(rctParent);
+
+ UINT nID;
+ UINT nStyle;
+ int nWidth;
+ if (m_wndStatusBar.GetSafeHwnd())
+ {
+ m_wndStatusBar.GetPaneInfo(0, nID, nStyle, nWidth);
+ m_wndStatusBar.SetPaneInfo(0, nID, nStyle, rctParent.Width() * .19);
+ m_wndStatusBar.GetPaneInfo(1, nID, nStyle, nWidth);
+ m_wndStatusBar.SetPaneInfo(1, nID, nStyle, rctParent.Width() * .19);
+ m_wndStatusBar.GetPaneInfo(2, nID, nStyle, nWidth);
+ m_wndStatusBar.SetPaneInfo(2, nID, nStyle, rctParent.Width() * .19);
+ m_wndStatusBar.GetPaneInfo(3, nID, nStyle, nWidth);
+ m_wndStatusBar.SetPaneInfo(3, nID, nStyle, rctParent.Width() * .19);
+ m_wndStatusBar.GetPaneInfo(4, nID, nStyle, nWidth);
+ m_wndStatusBar.SetPaneInfo(4, nID, nStyle, rctParent.Width() * .13);
+ m_wndStatusBar.GetPaneInfo(5, nID, nStyle, nWidth);
+ m_wndStatusBar.SetPaneInfo(5, nID, nStyle, rctParent.Width() * .01);
+ }
+
+ if (nType == SIZE_RESTORED && m_bSplittersOK && g_rctOld.Width() > 0)
+ {
+ if (m_nCurrentStyle == 0 || m_nCurrentStyle == 3)
+ {
+ SplitInfo spinfo;
+ m_wndSplit.GetRowInfo(0, spinfo.m_nCur, spinfo.m_nMin);
+ float fpc1 = (float)spinfo.m_nCur / g_rctOld.Height();
+ m_wndSplit.GetRowInfo(1, spinfo.m_nCur, spinfo.m_nMin);
+ float fpc2 = (float)spinfo.m_nCur / g_rctOld.Height();
+ m_wndSplit2.GetColumnInfo(0, spinfo.m_nCur, spinfo.m_nMin);
+ float fpc3 = (float)spinfo.m_nCur / g_rctOld.Width();
+ m_wndSplit2.GetColumnInfo(1, spinfo.m_nCur, spinfo.m_nMin);
+ float fpc4 = (float)spinfo.m_nCur / g_rctOld.Width();
+ m_wndSplit2.GetColumnInfo(2, spinfo.m_nCur, spinfo.m_nMin);
+ float fpc5 = (float)spinfo.m_nCur / g_rctOld.Width();
+ m_wndSplit3.GetRowInfo(0, spinfo.m_nCur, spinfo.m_nMin);
+ float fpc6 = (float)spinfo.m_nCur / g_rctOld.Height();
+ m_wndSplit3.GetRowInfo(1, spinfo.m_nCur, spinfo.m_nMin);
+ float fpc7 = (float)spinfo.m_nCur / g_rctOld.Height();
+
+ m_wndSplit.SetRowInfo(0, rctParent.Height() * fpc1, 100);
+ m_wndSplit.SetRowInfo(1, rctParent.Height() * fpc2, 25);
+
+ int nMin1 = (m_nCurrentStyle == 0) ? 10 : 25;
+ int nMin2 = (nMin1 == 10) ? 25 : 10;
+
+ m_wndSplit2.SetColumnInfo(0, rctParent.Width() * fpc3, nMin1);
+ m_wndSplit2.SetColumnInfo(1, rctParent.Width() * fpc4, 100);
+ m_wndSplit2.SetColumnInfo(2, rctParent.Width() * fpc5, nMin2);
+
+ m_wndSplit3.SetRowInfo(0, rctParent.Height() * fpc6, 50);
+ m_wndSplit3.SetRowInfo(1, rctParent.Height() * fpc7, 50);
+
+ m_wndSplit.RecalcLayout();
+ m_wndSplit2.RecalcLayout();
+ m_wndSplit3.RecalcLayout();
+ }
+ }
+
+
+}
+
+
+void OpenDialog (void);
+void SaveAsDialog (bool bRegion);
+void Select_Ungroup (void);
+
+void CMainFrame::ToggleCamera()
+{
+ if (m_bCamPreview)
+ m_bCamPreview = false;
+ else
+ m_bCamPreview = true;
+}
+
+void CMainFrame::OnFileClose()
+{
+
+}
+
+void CMainFrame::OnFileExit()
+{
+ PostMessage (WM_CLOSE, 0, 0L);
+}
+
+void CMainFrame::OnFileLoadproject()
+{
+ if (ConfirmModified())
+ ProjectDialog ();
+}
+
+void CMainFrame::OnFileNew()
+{
+ if (ConfirmModified())
+ Map_New ();
+}
+
+void CMainFrame::OnFileOpen()
+{
+ if (ConfirmModified())
+ OpenDialog ();
+}
+
+void CMainFrame::OnFilePointfile()
+{
+ if (g_qeglobals.d_pointfile_display_list)
+ Pointfile_Clear ();
+ else
+ Pointfile_Check ();
+}
+
+void CMainFrame::OnFilePrint()
+{
+
+}
+
+void CMainFrame::OnFilePrintPreview()
+{
+
+}
+
+void CMainFrame::OnFileSave()
+{
+ if (!strcmp(currentmap, "unnamed.map"))
+ {
+ SaveAsDialog (false);
+ }
+ else
+ {
+ Map_SaveFile (currentmap, false);
+ }
+}
+
+void CMainFrame::OnFileSaveas()
+{
+ SaveAsDialog(false);
+}
+
+void CMainFrame::OnView100()
+{
+ if (m_pXYWnd)
+ m_pXYWnd->SetScale(1);
+ if (m_pXZWnd)
+ m_pXZWnd->SetScale(1);
+ if (m_pYZWnd)
+ m_pYZWnd->SetScale(1);
+ Sys_UpdateWindows (W_XY|W_XY_OVERLAY);
+}
+
+void CMainFrame::OnViewCenter()
+{
+ m_pCamWnd->Camera().angles[ROLL] = m_pCamWnd->Camera().angles[PITCH] = 0;
+ m_pCamWnd->Camera().angles[YAW] = 22.5 *
+ floor( (m_pCamWnd->Camera().angles[YAW]+11)/22.5 );
+ Sys_UpdateWindows (W_CAMERA | W_XY_OVERLAY);
+}
+
+void CMainFrame::OnViewConsole()
+{
+ if (m_nCurrentStyle > 0 && m_nCurrentStyle < 3) // QE4 style
+ {
+ if (inspector_mode == W_CONSOLE && m_nCurrentStyle != QR_QE4) // are we in console mode already?
+ {
+ if (::IsWindowVisible(g_qeglobals.d_hwndEntity))
+ ::ShowWindow(g_qeglobals.d_hwndEntity, SW_HIDE);
+ else
+ ::ShowWindow(g_qeglobals.d_hwndEntity, SW_NORMAL);
+ }
+ else
+ {
+ ::ShowWindow(g_qeglobals.d_hwndEntity, SW_NORMAL);
+ SetInspectorMode(W_CONSOLE);
+ }
+ }
+}
+
+void CMainFrame::OnViewDownfloor()
+{
+ m_pCamWnd->Cam_ChangeFloor (false);
+}
+
+void CMainFrame::OnViewEntity()
+{
+ if (m_nCurrentStyle == 0 || m_nCurrentStyle == 3)
+ {
+ if (::IsWindowVisible(g_qeglobals.d_hwndEntity) && inspector_mode == W_ENTITY)
+ ::ShowWindow(g_qeglobals.d_hwndEntity, SW_HIDE);
+ else
+ {
+ ::ShowWindow(g_qeglobals.d_hwndEntity, SW_NORMAL);
+ SetInspectorMode(W_ENTITY);
+ }
+ }
+ else
+ {
+ if (inspector_mode == W_ENTITY && m_nCurrentStyle != QR_QE4)
+ {
+ if (::IsWindowVisible(g_qeglobals.d_hwndEntity))
+ ::ShowWindow(g_qeglobals.d_hwndEntity, SW_HIDE);
+ else
+ ::ShowWindow(g_qeglobals.d_hwndEntity, SW_NORMAL);
+ }
+ else
+ {
+ ::ShowWindow(g_qeglobals.d_hwndEntity, SW_NORMAL);
+ SetInspectorMode(W_ENTITY);
+ }
+ }
+}
+
+void CMainFrame::OnViewFront()
+{
+ if (m_nCurrentStyle != 2)
+ {
+ m_pXYWnd->SetViewType(YZ);
+ m_pXYWnd->PositionView();
+ }
+ Sys_UpdateWindows (W_XY);
+}
+
+void CMainFrame::OnMru(unsigned int nID)
+{
+ DoMru(GetSafeHwnd(),nID);
+}
+
+void CMainFrame::OnViewNearest(unsigned int nID)
+{
+ Texture_SetMode(nID);
+}
+
+void CMainFrame::OnTextureWad(unsigned int nID)
+{
+ Sys_BeginWait ();
+ Texture_ShowDirectory (nID);
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnBspCommand(unsigned int nID)
+{
+ if (g_PrefsDlg.m_bSnapShots && stricmp(currentmap, "unnamed.map") != 0)
+ Map_Snapshot();
+
+ if (g_qeglobals.bBSPFrontendPlugin)
+ {
+ CString foo = g_BSPFrontendCommands.GetAt(nID-CMD_BSPCOMMAND);
+ g_BSPFrontendTable.m_pfnDispatchBSPCommand( foo.GetBuffer(0) );
+ }
+ else
+ {
+ RunBsp (bsp_commands[LOWORD(nID-CMD_BSPCOMMAND)]);
+ }
+}
+
+
+
+void CMainFrame::OnViewShowblocks()
+{
+ g_qeglobals.show_blocks ^= 1;
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWBLOCKS, MF_BYCOMMAND | (g_qeglobals.show_blocks ? MF_CHECKED : MF_UNCHECKED) );
+ Sys_UpdateWindows (W_XY);
+}
+
+void CMainFrame::OnViewShowclip()
+{
+ if ( ( g_qeglobals.d_savedinfo.exclude ^= EXCLUDE_CLIP ) & EXCLUDE_CLIP )
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWCLIP, MF_BYCOMMAND | MF_UNCHECKED );
+ else
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWCLIP, MF_BYCOMMAND | MF_CHECKED );
+ Sys_UpdateWindows (W_XY|W_CAMERA);
+}
+
+void CMainFrame::OnViewShowcoordinates()
+{
+ g_qeglobals.d_savedinfo.show_coordinates ^= 1;
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWCOORDINATES, MF_BYCOMMAND | (g_qeglobals.d_savedinfo.show_coordinates ? MF_CHECKED : MF_UNCHECKED) );
+ Sys_UpdateWindows (W_XY);
+}
+
+void CMainFrame::OnViewShowdetail()
+{
+ if ( ( g_qeglobals.d_savedinfo.exclude ^= EXCLUDE_DETAIL ) & EXCLUDE_DETAIL )
+ {
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWDETAIL, MF_BYCOMMAND | MF_UNCHECKED );
+ ::SetWindowText (g_qeglobals.d_hwndCamera, "Camera View (DETAIL EXCLUDED)");
+ }
+ else
+ {
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWDETAIL, MF_BYCOMMAND | MF_CHECKED );
+ ::SetWindowText (g_qeglobals.d_hwndCamera, "Camera View");
+ }
+ Sys_UpdateWindows (W_XY|W_CAMERA);
+}
+
+void CMainFrame::OnViewShowent()
+{
+ if ( ( g_qeglobals.d_savedinfo.exclude ^= EXCLUDE_ENT ) & EXCLUDE_ENT )
+ CheckMenuItem( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWENT, MF_BYCOMMAND | MF_UNCHECKED);
+ else
+ CheckMenuItem( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWENT, MF_BYCOMMAND | MF_CHECKED);
+ Sys_UpdateWindows (W_XY|W_CAMERA);
+}
+
+void CMainFrame::OnViewShowlights()
+{
+ if ( ( g_qeglobals.d_savedinfo.exclude ^= EXCLUDE_LIGHTS ) & EXCLUDE_LIGHTS )
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWLIGHTS, MF_BYCOMMAND | MF_UNCHECKED );
+ else
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWLIGHTS, MF_BYCOMMAND | MF_CHECKED );
+ Sys_UpdateWindows (W_XY|W_CAMERA);
+}
+
+void CMainFrame::OnViewShownames()
+{
+ g_qeglobals.d_savedinfo.show_names = !g_qeglobals.d_savedinfo.show_names;
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWNAMES, MF_BYCOMMAND | (g_qeglobals.d_savedinfo.show_names ? MF_CHECKED : MF_UNCHECKED) );
+ Map_BuildBrushData();
+ Sys_UpdateWindows (W_XY);
+}
+
+void CMainFrame::OnViewShowpath()
+{
+ if ( ( g_qeglobals.d_savedinfo.exclude ^= EXCLUDE_PATHS ) & EXCLUDE_PATHS )
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWPATH, MF_BYCOMMAND | MF_UNCHECKED );
+ else
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWPATH, MF_BYCOMMAND | MF_CHECKED );
+ Sys_UpdateWindows (W_XY|W_CAMERA);
+}
+
+void CMainFrame::OnViewShowwater()
+{
+ if ( ( g_qeglobals.d_savedinfo.exclude ^= EXCLUDE_WATER ) & EXCLUDE_WATER )
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWWATER, MF_BYCOMMAND | MF_UNCHECKED );
+ else
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWWATER, MF_BYCOMMAND | MF_CHECKED );
+ Sys_UpdateWindows (W_XY|W_CAMERA);
+}
+
+void CMainFrame::OnViewShowworld()
+{
+ if ( ( g_qeglobals.d_savedinfo.exclude ^= EXCLUDE_WORLD ) & EXCLUDE_WORLD )
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWWORLD, MF_BYCOMMAND | MF_UNCHECKED );
+ else
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWWORLD, MF_BYCOMMAND | MF_CHECKED );
+ Sys_UpdateWindows (W_XY|W_CAMERA);
+}
+
+void CMainFrame::OnViewTexture()
+{
+ if (m_nCurrentStyle > 0 && m_nCurrentStyle < 3) // QE4 style
+ {
+ if (inspector_mode == W_TEXTURE && m_nCurrentStyle != QR_QE4) // are we in console mode already?
+ {
+ if (::IsWindowVisible(g_qeglobals.d_hwndEntity))
+ ::ShowWindow(g_qeglobals.d_hwndEntity, SW_HIDE);
+ else
+ ::ShowWindow(g_qeglobals.d_hwndEntity, SW_SHOW);
+ }
+ else
+ {
+ ::ShowWindow(g_qeglobals.d_hwndEntity, SW_SHOW);
+ SetInspectorMode(W_TEXTURE);
+ }
+ }
+}
+
+void CMainFrame::OnViewUpfloor()
+{
+ m_pCamWnd->Cam_ChangeFloor (true);
+}
+
+void CMainFrame::OnViewXy()
+{
+ if (m_nCurrentStyle != 2)
+ {
+ m_pXYWnd->SetViewType(XY);
+ m_pXYWnd->PositionView();
+ }
+ Sys_UpdateWindows (W_XY);
+}
+
+void CMainFrame::OnViewZ100()
+{
+ z.scale = 1;
+ Sys_UpdateWindows (W_Z|W_Z_OVERLAY);
+}
+
+void CMainFrame::OnViewZoomin()
+{
+ if (m_pXYWnd && m_pXYWnd->Active())
+ {
+ m_pXYWnd->SetScale(m_pXYWnd->Scale() * 5.0 / 4);
+ if (m_pXYWnd->Scale() > 20)
+ m_pXYWnd->SetScale(20);
+ }
+
+ if (m_pXZWnd && m_pXZWnd->Active())
+ {
+ m_pXZWnd->SetScale(m_pXZWnd->Scale() * 5.0 / 4);
+ if (m_pXZWnd->Scale() > 20)
+ m_pXZWnd->SetScale(20);
+ }
+
+ if (m_pYZWnd && m_pYZWnd->Active())
+ {
+ m_pYZWnd->SetScale(m_pYZWnd->Scale() * 5.0 / 4);
+ if (m_pYZWnd->Scale() > 20)
+ m_pYZWnd->SetScale(20);
+ }
+
+
+ Sys_UpdateWindows (W_XY|W_XY_OVERLAY);
+}
+
+void CMainFrame::OnViewZoomout()
+{
+
+ if (m_pXYWnd && m_pXYWnd->Active())
+ {
+ m_pXYWnd->SetScale(m_pXYWnd->Scale() * 4.0 / 5);
+ if (m_pXYWnd->Scale() < 0.1 / 32)
+ m_pXYWnd->SetScale(0.1 /32);
+ }
+
+ if (m_pXZWnd && m_pXZWnd->Active())
+ {
+ m_pXZWnd->SetScale(m_pXZWnd->Scale() * 4.0 / 5);
+ if (m_pXZWnd->Scale() < 0.1 / 32)
+ m_pXZWnd->SetScale(0.1 / 32);
+ }
+
+ if (m_pYZWnd && m_pYZWnd->Active())
+ {
+ m_pYZWnd->SetScale(m_pYZWnd->Scale() * 4.0 / 5);
+ if (m_pYZWnd->Scale() < 0.1 / 32)
+ m_pYZWnd->SetScale(0.1 / 32);
+ }
+ Sys_UpdateWindows (W_XY|W_XY_OVERLAY);
+}
+
+void CMainFrame::OnViewZzoomin()
+{
+ z.scale *= 5.0/4;
+ if (z.scale > 4)
+ z.scale = 4;
+ Sys_UpdateWindows (W_Z|W_Z_OVERLAY);
+}
+
+void CMainFrame::OnViewZzoomout()
+{
+ z.scale *= 4.0/5;
+ if (z.scale < 0.125)
+ z.scale = 0.125;
+ Sys_UpdateWindows (W_Z|W_Z_OVERLAY);
+}
+
+void CMainFrame::OnViewSide()
+{
+ if (m_nCurrentStyle != 2)
+ {
+ m_pXYWnd->SetViewType(XZ);
+ m_pXYWnd->PositionView();
+ }
+ Sys_UpdateWindows (W_XY);
+}
+
+void CMainFrame::OnGrid1(unsigned int nID)
+{
+ HMENU hMenu = ::GetMenu(GetSafeHwnd());
+
+ CheckMenuItem(hMenu, ID_GRID_1, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_GRID_2, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_GRID_4, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_GRID_8, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_GRID_16, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_GRID_32, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_GRID_64, MF_BYCOMMAND | MF_UNCHECKED);
+
+ switch (nID)
+ {
+ case ID_GRID_1: g_qeglobals.d_gridsize = 0; break;
+ case ID_GRID_2: g_qeglobals.d_gridsize = 1; break;
+ case ID_GRID_4: g_qeglobals.d_gridsize = 2; break;
+ case ID_GRID_8: g_qeglobals.d_gridsize = 3; break;
+ case ID_GRID_16: g_qeglobals.d_gridsize = 4; break;
+ case ID_GRID_32: g_qeglobals.d_gridsize = 5; break;
+ case ID_GRID_64: g_qeglobals.d_gridsize = 6; break;
+ }
+ g_qeglobals.d_gridsize = 1 << g_qeglobals.d_gridsize;
+
+ if (g_PrefsDlg.m_bSnapTToGrid)
+ g_qeglobals.d_savedinfo.m_nTextureTweak = g_qeglobals.d_gridsize;
+
+ SetGridStatus();
+ CheckMenuItem(hMenu, nID, MF_BYCOMMAND | MF_CHECKED);
+ Sys_UpdateWindows (W_XY|W_Z);
+
+}
+
+void CMainFrame::OnTexturesShowinuse()
+{
+ Sys_BeginWait ();
+ Texture_ShowInuse ();
+ if (m_pTexWnd)
+ {
+ m_pTexWnd->RedrawWindow();
+ }
+}
+
+//from TexWnd.cpp
+extern qboolean texture_showinuse;
+void CMainFrame::OnUpdateTexturesShowinuse(CCmdUI* pCmdUI)
+{
+ pCmdUI->SetCheck(texture_showinuse);
+}
+
+void CMainFrame::OnTexturesInspector()
+{
+ DoSurface ();
+}
+
+void CMainFrame::OnMiscBenchmark()
+{
+ m_pCamWnd->BenchMark();
+}
+
+void CMainFrame::OnMiscFindbrush()
+{
+ DoFind();
+}
+
+void CMainFrame::OnMiscGamma()
+{
+ float fSave = g_qeglobals.d_savedinfo.fGamma;
+ DoGamma();
+ if (fSave != g_qeglobals.d_savedinfo.fGamma)
+ {
+ MessageBox("You must restart Q3Radiant for Gamma settings to take place");
+ }
+}
+
+void CMainFrame::OnMiscNextleakspot()
+{
+ Pointfile_Next();
+}
+
+void CMainFrame::OnMiscPreviousleakspot()
+{
+ Pointfile_Prev();
+}
+
+void CMainFrame::OnMiscPrintxy()
+{
+ WXY_Print();
+}
+
+void CMainFrame::OnMiscSelectentitycolor()
+{
+ if (edit_entity)
+ {
+ CString strColor = ValueForKey(edit_entity, "_color");
+ if (strColor.GetLength() > 0)
+ {
+ float fR, fG, fB;
+ int n = sscanf(strColor,"%f %f %f", &fR, &fG, &fB);
+ if (n == 3)
+ {
+ g_qeglobals.d_savedinfo.colors[COLOR_ENTITY][0] = fR;
+ g_qeglobals.d_savedinfo.colors[COLOR_ENTITY][1] = fG;
+ g_qeglobals.d_savedinfo.colors[COLOR_ENTITY][2] = fB;
+ }
+ }
+
+ if (inspector_mode == W_ENTITY && (DoColor(COLOR_ENTITY)))
+ {
+ char buffer[100];
+ sprintf(buffer, "%f %f %f", g_qeglobals.d_savedinfo.colors[COLOR_ENTITY][0],
+ g_qeglobals.d_savedinfo.colors[COLOR_ENTITY][1],
+ g_qeglobals.d_savedinfo.colors[COLOR_ENTITY][2]);
+
+ ::SetWindowText( hwndEnt[EntValueField], buffer );
+ ::SetWindowText( hwndEnt[EntKeyField], "_color" );
+ AddProp();
+//DK - SOF change to get color to entity quickly
+ //--::SetWindowText( hwndEnt[EntValueField], buffer );
+//-- ::SetWindowText( hwndEnt[EntKeyField], "color" );
+//-- AddProp();
+ }
+ Sys_UpdateWindows( W_ALL );
+ }
+}
+
+void CMainFrame::OnTexturebk()
+{
+ DoColor(COLOR_TEXTUREBACK);
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnColorsMajor()
+{
+ DoColor(COLOR_GRIDMAJOR);
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnColorsMinor()
+{
+ DoColor(COLOR_GRIDMINOR);
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnColorsXybk()
+{
+ DoColor(COLOR_GRIDBACK);
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnBrush3sided()
+{
+ Undo_Start("3 sided");
+ Undo_AddBrushList(&selected_brushes);
+ Brush_MakeSided(3);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnBrush4sided()
+{
+ Undo_Start("4 sided");
+ Undo_AddBrushList(&selected_brushes);
+ Brush_MakeSided(4);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnBrush5sided()
+{
+ Undo_Start("5 sided");
+ Undo_AddBrushList(&selected_brushes);
+ Brush_MakeSided(5);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnBrush6sided()
+{
+ Undo_Start("6 sided");
+ Undo_AddBrushList(&selected_brushes);
+ Brush_MakeSided(6);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnBrush7sided()
+{
+ Undo_Start("7 sided");
+ Undo_AddBrushList(&selected_brushes);
+ Brush_MakeSided(7);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnBrush8sided()
+{
+ Undo_Start("8 sided");
+ Undo_AddBrushList(&selected_brushes);
+ Brush_MakeSided(8);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnBrush9sided()
+{
+ Undo_Start("9 sided");
+ Undo_AddBrushList(&selected_brushes);
+ Brush_MakeSided(9);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnBrushArbitrarysided()
+{
+ Undo_Start("arbitrary sided");
+ Undo_AddBrushList(&selected_brushes);
+ DoSides();
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnBrushFlipx()
+{
+ Undo_Start("flip X");
+ Undo_AddBrushList(&selected_brushes);
+
+ Select_FlipAxis (0);
+ for (brush_t *b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ {
+ if(b->owner->eclass->fixedsize)
+ {
+ char buf[16];
+ float a = FloatForKey(b->owner, "angle");
+ a = div( ( 180 - a ) , 180 ).rem;
+ SetKeyValue(b->owner, "angle", itoa(a, buf, 10));
+ Brush_Build(b);
+ }
+ }
+
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnBrushFlipy()
+{
+ Undo_Start("flip Y");
+ Undo_AddBrushList(&selected_brushes);
+
+ Select_FlipAxis (1);
+ for (brush_t *b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ {
+ if(b->owner->eclass->fixedsize)
+ {
+ float a = FloatForKey(b->owner, "angle");
+ if (a == 0 || a == 180 || a == 360)
+ continue;
+ if ( a == 90 || a == 270)
+ {
+ a += 180;
+ }
+ else if (a > 270)
+ a += 90;
+ else if (a > 180)
+ a -= 90;
+ else if (a > 90)
+ a += 90;
+ else
+ a -= 90;
+ a = (int)a % 360;
+ char buf[16];
+ SetKeyValue(b->owner, "angle", itoa(a, buf, 10));
+ Brush_Build(b);
+ }
+ }
+
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnBrushFlipz()
+{
+ Undo_Start("flip Z");
+ Undo_AddBrushList(&selected_brushes);
+ Select_FlipAxis (2);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnBrushRotatex()
+{
+ Undo_Start("rotate X");
+ Undo_AddBrushList(&selected_brushes);
+ Select_RotateAxis (0, 90);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnBrushRotatey()
+{
+ Undo_Start("rotate Y");
+ Undo_AddBrushList(&selected_brushes);
+ Select_RotateAxis (1, 90);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnBrushRotatez()
+{
+ Undo_Start("rotate Z");
+ Undo_AddBrushList(&selected_brushes);
+ Select_RotateAxis (2, 90);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnRegionOff()
+{
+ Map_RegionOff ();
+}
+
+void CMainFrame::OnRegionSetbrush()
+{
+ Map_RegionBrush ();
+}
+
+void CMainFrame::OnRegionSetselection()
+{
+ Map_RegionSelectedBrushes ();
+}
+
+void CMainFrame::OnRegionSettallbrush()
+{
+ Map_RegionTallBrush ();
+}
+
+void CMainFrame::OnRegionSetxy()
+{
+ Map_RegionXY ();
+}
+
+void CMainFrame::OnSelectionArbitraryrotation()
+{
+ //if (ActiveXY())
+ // ActiveXY()->UndoCopy();
+ Undo_Start("arbitrary rotation");
+ Undo_AddBrushList(&selected_brushes);
+
+ CRotateDlg dlg;
+ dlg.DoModal();
+ //DoRotate ();
+
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnSelectionClone()
+{
+ //if (ActiveXY())
+ // ActiveXY()->UndoCopy();
+ Select_Clone();
+}
+
+void CMainFrame::OnSelectionConnect()
+{
+ ConnectEntities();
+}
+
+void CMainFrame::OnSelectionMakehollow()
+{
+ //if (ActiveXY())
+ // ActiveXY()->UndoCopy();
+ Undo_Start("hollow");
+ Undo_AddBrushList(&selected_brushes);
+ CSG_MakeHollow ();
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnSelectionCsgsubtract()
+{
+ //if (ActiveXY())
+ // ActiveXY()->UndoCopy();
+ Undo_Start("CSG subtract");
+ CSG_Subtract();
+ Undo_End();
+}
+
+void CMainFrame::OnSelectionCsgmerge()
+{
+ //if (ActiveXY())
+ // ActiveXY()->UndoCopy();
+ Undo_Start("CSG merge");
+ Undo_AddBrushList(&selected_brushes);
+ CSG_Merge();
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnSelectionNoOutline()
+{
+ g_qeglobals.dontDrawSelectedOutlines ^= 1;
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CMainFrame::OnSelectionDelete()
+{
+ brush_t *brush;
+ //if (ActiveXY())
+ // ActiveXY()->UndoCopy();
+ Undo_Start("delete");
+ Undo_AddBrushList(&selected_brushes);
+ //add all deleted entities to the undo
+ for (brush = selected_brushes.next; brush != &selected_brushes; brush = brush->next)
+ {
+ Undo_AddEntity(brush->owner);
+ }
+ // NOTE: Select_Delete does NOT delete entities
+ Select_Delete();
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnSelectionDeselect()
+{
+ if (!ByeByeSurfaceDialog())
+ {
+ if (g_bClipMode)
+ OnViewClipper();
+ else if (g_bRotateMode)
+ OnSelectMouserotate();
+ else if (g_bScaleMode)
+ OnSelectMousescale();
+ else if (g_bPathMode)
+ {
+ if (ActiveXY())
+ ActiveXY()->KillPathMode();
+ }
+ else
+ {
+ if (g_qeglobals.d_select_mode == sel_curvepoint && g_qeglobals.d_num_move_points > 0)
+ {
+ g_qeglobals.d_num_move_points = 0;
+ Sys_UpdateWindows(W_ALL);
+ }
+ else if ( g_qeglobals.d_select_mode == sel_terrainpoint && g_qeglobals.d_numterrapoints > 0 )
+ {
+ g_qeglobals.d_numterrapoints = 0;
+ Sys_UpdateWindows( W_ALL );
+ }
+ else
+ {
+ Select_Deselect ();
+ SetStatusText(2, " ");
+ }
+ }
+ }
+}
+
+void CMainFrame::OnSelectionDragedges()
+{
+ if (g_qeglobals.d_select_mode == sel_edge)
+ {
+ clearSelection();
+ Sys_UpdateWindows (W_ALL);
+ }
+ else
+ {
+ SetupVertexSelection ();
+ if (g_qeglobals.d_numpoints)
+ g_qeglobals.d_select_mode = sel_edge;
+ Sys_UpdateWindows (W_ALL);
+ }
+}
+
+void CMainFrame::OnSelectionDragvertecies()
+{
+ if (g_qeglobals.d_select_mode == sel_vertex || g_qeglobals.d_select_mode == sel_curvepoint ||
+ g_qeglobals.d_select_mode == sel_terrainpoint )
+ {
+ clearSelection();
+ Sys_UpdateWindows (W_ALL);
+ }
+ else
+ {
+ //--if (QE_SingleBrush() && selected_brushes.next->patchBrush)
+ if ( OnlyTerrainSelected() )
+ {
+ //Terrain_Edit();
+ }
+ else if (OnlyPatchesSelected())
+ {
+ Patch_EditPatch();
+ }
+ else if ( !AnyPatchesSelected() && !AnyTerrainSelected() )
+ {
+ SetupVertexSelection ();
+ if (g_qeglobals.d_numpoints)
+ g_qeglobals.d_select_mode = sel_vertex;
+ }
+ Sys_UpdateWindows (W_ALL);
+ }
+}
+
+void CMainFrame::OnRaiseLowerTerrain()
+{
+ //if ( !OnlyTerrainSelected() || ( g_qeglobals.d_select_mode == sel_terrainpoint ) )
+ //if ( ( g_qeglobals.d_select_mode == sel_terrainpoint ) || ( g_qeglobals.d_select_mode == sel_terraintexture ) )
+ if ( g_qeglobals.d_select_mode == sel_terrainpoint ) {
+ clearSelection();
+ Sys_UpdateWindows (W_ALL);
+ }
+ else if ( g_qeglobals.d_select_mode == sel_terraintexture ) {
+ clearSelection();
+ g_qeglobals.d_select_mode = sel_terrainpoint;
+ Sys_UpdateWindows (W_ALL);
+ }
+ else
+ {
+ //g_qeglobals.d_select_mode = sel_terrainpoint;
+ clearSelection();
+ g_qeglobals.d_select_mode = sel_terraintexture;
+ Sys_UpdateWindows (W_ALL);
+// Terrain_Edit();
+ }
+}
+
+void CMainFrame::OnSelectionMakeDetail()
+{
+ Undo_Start("make detail");
+ Undo_AddBrushList(&selected_brushes);
+ Select_MakeDetail ();
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnSelectionMakeStructural()
+{
+ Undo_Start("make structural");
+ Undo_AddBrushList(&selected_brushes);
+ Select_MakeStructural ();
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnSelectionSelectcompletetall()
+{
+ if (ActiveXY())
+ ActiveXY()->UndoCopy();
+ Select_CompleteTall ();
+}
+
+void CMainFrame::OnSelectionSelectinside()
+{
+ Select_Inside ();
+}
+
+void CMainFrame::OnSelectionSelectpartialtall()
+{
+ Select_PartialTall();
+}
+
+void CMainFrame::OnSelectionSelecttouching()
+{
+ Select_Touching();
+}
+
+void CMainFrame::OnSelectionUngroupentity()
+{
+ Select_Ungroup();
+}
+
+void CMainFrame::OnTexturesPopup()
+{
+ HandlePopup(this, IDR_POPUP_TEXTURE);
+}
+
+void CMainFrame::OnSplinesPopup()
+{
+ HandlePopup(this, IDR_POPUP_SPLINE);
+}
+
+void CMainFrame::OnPopupSelection()
+{
+ HandlePopup(this, IDR_POPUP_SELECTION);
+}
+
+void CMainFrame::OnViewChange()
+{
+ OnViewNextview();
+ //HandlePopup(this, IDR_POPUP_VIEW);
+}
+
+void CMainFrame::OnViewCameraupdate()
+{
+ Sys_UpdateWindows(W_CAMERA);
+}
+
+void CMainFrame::OnUpdateViewCameraupdate(CCmdUI* pCmdUI)
+{
+ pCmdUI->Enable(m_bCamPreview == false);
+}
+
+void CMainFrame::OnSizing(UINT fwSide, LPRECT pRect)
+{
+ CFrameWnd::OnSizing(fwSide, pRect);
+ GetClientRect(g_rctOld);
+}
+
+void CMainFrame::OnHelpAbout()
+{
+ DoAbout();
+}
+
+void CMainFrame::OnViewClipper()
+{
+ if (ActiveXY())
+ {
+ if (ActiveXY()->ClipMode())
+ {
+ ActiveXY()->SetClipMode(false);
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_VIEW_CLIPPER, FALSE);
+ }
+ else
+ {
+ if (ActiveXY()->RotateMode())
+ OnSelectMouserotate();
+ ActiveXY()->SetClipMode(true);
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_VIEW_CLIPPER);
+ }
+ }
+}
+
+void CMainFrame::OnCameraAngledown()
+{
+ m_pCamWnd->Camera().angles[0] -= SPEED_TURN;
+ if (m_pCamWnd->Camera().angles[0] < -85)
+ m_pCamWnd->Camera().angles[0] = -85;
+ Sys_UpdateWindows (W_CAMERA|W_XY_OVERLAY);
+}
+
+void CMainFrame::OnCameraAngleup()
+{
+ m_pCamWnd->Camera().angles[0] += SPEED_TURN;
+ if (m_pCamWnd->Camera().angles[0] > 85)
+ m_pCamWnd->Camera().angles[0] = 85;
+ Sys_UpdateWindows (W_CAMERA|W_XY_OVERLAY);
+}
+
+void CMainFrame::OnCameraBack()
+{
+ VectorMA (m_pCamWnd->Camera().origin, -SPEED_MOVE, m_pCamWnd->Camera().forward, m_pCamWnd->Camera().origin);
+ int nUpdate = (g_PrefsDlg.m_bCamXYUpdate) ? (W_CAMERA | W_XY) : (W_CAMERA);
+ Sys_UpdateWindows (nUpdate);
+}
+
+void CMainFrame::OnCameraDown()
+{
+ m_pCamWnd->Camera().origin[2] -= SPEED_MOVE;
+ int nUpdate = (g_PrefsDlg.m_bCamXYUpdate) ? (W_CAMERA | W_XY) : (W_CAMERA);
+ Sys_UpdateWindows (nUpdate);
+}
+
+void CMainFrame::OnCameraForward()
+{
+ VectorMA (m_pCamWnd->Camera().origin, SPEED_MOVE, m_pCamWnd->Camera().forward, m_pCamWnd->Camera().origin);
+ int nUpdate = (g_PrefsDlg.m_bCamXYUpdate) ? (W_CAMERA | W_XY) : (W_CAMERA);
+ Sys_UpdateWindows (nUpdate);
+}
+
+void CMainFrame::OnCameraLeft()
+{
+ m_pCamWnd->Camera().angles[1] += SPEED_TURN;
+ int nUpdate = (g_PrefsDlg.m_bCamXYUpdate) ? (W_CAMERA | W_XY) : (W_CAMERA);
+ Sys_UpdateWindows (nUpdate);
+}
+
+void CMainFrame::OnCameraRight()
+{
+ m_pCamWnd->Camera().angles[1] -= SPEED_TURN;
+ int nUpdate = (g_PrefsDlg.m_bCamXYUpdate) ? (W_CAMERA | W_XY) : (W_CAMERA);
+ Sys_UpdateWindows (nUpdate);
+}
+
+void CMainFrame::OnCameraStrafeleft()
+{
+ VectorMA (m_pCamWnd->Camera().origin, -SPEED_MOVE, m_pCamWnd->Camera().right, m_pCamWnd->Camera().origin);
+ int nUpdate = (g_PrefsDlg.m_bCamXYUpdate) ? (W_CAMERA | W_XY) : (W_CAMERA);
+ Sys_UpdateWindows (nUpdate);
+}
+
+void CMainFrame::OnCameraStraferight()
+{
+ VectorMA (m_pCamWnd->Camera().origin, SPEED_MOVE, m_pCamWnd->Camera().right, m_pCamWnd->Camera().origin);
+ int nUpdate = (g_PrefsDlg.m_bCamXYUpdate) ? (W_CAMERA | W_XY) : (W_CAMERA);
+ Sys_UpdateWindows (nUpdate);
+}
+
+void CMainFrame::OnCameraUp()
+{
+ m_pCamWnd->Camera().origin[2] += SPEED_MOVE;
+ int nUpdate = (g_PrefsDlg.m_bCamXYUpdate) ? (W_CAMERA | W_XY) : (W_CAMERA);
+ Sys_UpdateWindows (nUpdate);
+}
+
+void CMainFrame::OnGridToggle()
+{
+ g_qeglobals.d_showgrid = !g_qeglobals.d_showgrid;
+ Sys_UpdateWindows (W_XY|W_Z);
+}
+
+void CMainFrame::OnPrefs()
+{
+ int nView = g_PrefsDlg.m_nView;
+ BOOL bToolbar = g_PrefsDlg.m_bWideToolbar;
+ BOOL bTextureBar = g_PrefsDlg.m_bTextureBar;
+ BOOL bSGIOpenGL = g_PrefsDlg.m_bSGIOpenGL;
+ BOOL bBuggyICD = g_PrefsDlg.m_bBuggyICD;
+ int nShader = g_PrefsDlg.m_nShader;
+ g_PrefsDlg.LoadPrefs();
+ if (g_PrefsDlg.DoModal() == IDOK)
+ {
+ if (g_PrefsDlg.m_nView != nView || g_PrefsDlg.m_bWideToolbar != bToolbar
+ || g_PrefsDlg.m_bSGIOpenGL != bSGIOpenGL || g_PrefsDlg.m_bBuggyICD != bBuggyICD || nShader != g_PrefsDlg.m_nShader)
+ MessageBox("You need to restart Q3Radiant for the view changes to take place.");
+ if (m_pTexWnd)
+ m_pTexWnd->UpdatePrefs();
+ if (bTextureBar != g_PrefsDlg.m_bTextureBar)
+ {
+ if (bTextureBar) // was turned on
+ ShowControlBar(&m_wndTextureBar, TRUE, TRUE);
+ else // was turned off
+ ShowControlBar(&m_wndTextureBar, FALSE, TRUE);
+ m_wndTextureBar.Invalidate();
+ }
+ CMenu* pMenu = GetMenu();
+ if (pMenu)
+ pMenu->CheckMenuItem(ID_SNAPTOGRID, MF_BYCOMMAND | (!g_PrefsDlg.m_bNoClamp) ? MF_CHECKED : MF_UNCHECKED);
+ }
+}
+
+// 0 = radiant styel
+// 1 = qe4 style
+void CMainFrame::SetWindowStyle(int nStyle)
+{
+}
+
+void CMainFrame::OnTogglecamera()
+{
+ if (m_nCurrentStyle > 0 && m_nCurrentStyle < 3) // QE4 style
+ {
+ if (m_pCamWnd && m_pCamWnd->GetSafeHwnd())
+ {
+ if (m_pCamWnd->IsWindowVisible())
+ m_pCamWnd->ShowWindow(SW_HIDE);
+ else
+ m_pCamWnd->ShowWindow(SW_SHOW);
+ }
+ }
+}
+
+void CMainFrame::OnToggleconsole()
+{
+ if (m_nCurrentStyle > 0 && m_nCurrentStyle < 3) // QE4 style
+ {
+ if (m_pEditWnd && m_pEditWnd->GetSafeHwnd())
+ {
+ if (m_pEditWnd->IsWindowVisible())
+ m_pEditWnd->ShowWindow(SW_HIDE);
+ else
+ m_pEditWnd->ShowWindow(SW_SHOW);
+ }
+ }
+}
+
+void CMainFrame::OnToggleview()
+{
+ if (m_nCurrentStyle == 1) // QE4 style
+ {
+ if (m_pXYWnd && m_pXYWnd->GetSafeHwnd())
+ {
+ if (m_pXYWnd->IsWindowVisible())
+ m_pXYWnd->ShowWindow(SW_HIDE);
+ else
+ m_pXYWnd->ShowWindow(SW_SHOW);
+ }
+ }
+}
+
+void CMainFrame::OnTogglez()
+{
+ if (m_nCurrentStyle == 1 || m_nCurrentStyle == 2) // QE4 style
+ {
+ if (m_pZWnd && m_pZWnd->GetSafeHwnd())
+ {
+ if (m_pZWnd->IsWindowVisible())
+ m_pZWnd->ShowWindow(SW_HIDE);
+ else
+ m_pZWnd->ShowWindow(SW_SHOW);
+ }
+ }
+ else
+ {
+ Undo_Redo();
+ }
+}
+
+void CMainFrame::OnToggleLock()
+{
+ g_PrefsDlg.m_bTextureLock = !g_PrefsDlg.m_bTextureLock;
+ CMenu* pMenu = GetMenu();
+ if (pMenu)
+ pMenu->CheckMenuItem(ID_TOGGLE_LOCK, MF_BYCOMMAND | (g_PrefsDlg.m_bTextureLock) ? MF_CHECKED : MF_UNCHECKED);
+ g_PrefsDlg.SavePrefs();
+ SetGridStatus();
+}
+
+void CMainFrame::OnEditMapinfo()
+{
+ CMapInfo dlg;
+ dlg.DoModal();
+}
+
+void CMainFrame::OnEditEntityinfo()
+{
+ CEntityListDlg dlg;
+ dlg.DoModal();
+}
+
+
+
+void CMainFrame::OnBrushScripts()
+{
+ CScriptDlg dlg;
+ dlg.DoModal();
+}
+
+void CMainFrame::OnViewNextview()
+{
+ if (m_nCurrentStyle != 2)
+ {
+ if (m_pXYWnd->GetViewType() == XY)
+ m_pXYWnd->SetViewType(XZ);
+ else
+ if (m_pXYWnd->GetViewType() == XZ)
+ m_pXYWnd->SetViewType(YZ);
+ else
+ m_pXYWnd->SetViewType(XY);
+ m_pXYWnd->PositionView();
+ Sys_UpdateWindows (W_XY);
+ }
+}
+
+void CMainFrame::OnHelpCommandlist()
+{
+ CCommandsDlg dlg;
+ dlg.DoModal();
+#if 0
+ if (g_b3Dfx)
+ {
+ C3DFXCamWnd* pWnd = new C3DFXCamWnd();
+ CRect rect(50,50,400, 400);
+ pWnd->Create(_3DFXCAMERA_WINDOW_CLASS, "", QE3_CHILDSTYLE, rect, this, 1234);
+ pWnd->ShowWindow(SW_SHOW);
+ }
+#endif
+}
+
+void CMainFrame::OnFileNewproject()
+{
+ CNewProjDlg dlg;
+ if (dlg.DoModal() == IDOK && dlg.m_strName.GetLength() > 0)
+ {
+ CString strQ2;
+ CString strQ2File;
+ ExtractPath_and_Filename(g_PrefsDlg.m_strQuake2, strQ2, strQ2File);
+
+
+ AddSlash(strQ2);
+ strQ2 += dlg.m_strName;
+ CString strProjToLoad;
+ CString strMapToLoad;
+ bool bGood = true;
+ if (::CreateDirectory(strQ2, NULL))
+ {
+ CString strDir = strQ2;
+ strDir += "\\maps";
+ if (::CreateDirectory(strDir, NULL))
+ {
+ CString strSource = g_strAppPath;
+ AddSlash(strSource);
+ strSource += "projmap.dat";
+ CString strDest = strDir;
+ AddSlash(strDest);
+ CString strName;
+ strName.Format("%s.map", dlg.m_strName);
+ strDest += strName;
+ strMapToLoad = strDest;
+ if (!::CopyFile(strSource, strDest, FALSE))
+ bGood = false;
+ }
+ else bGood = false;
+
+ strDir = strQ2;
+ strDir += "\\pics";
+ if (::CreateDirectory(strDir, NULL))
+ {
+ CString strSource = g_strAppPath;
+ AddSlash(strSource);
+ strSource += "colormap.pcx";
+ CString strDest = strDir;
+ AddSlash(strDest);
+ strDest += "colormap.pcx";
+ if (!::CopyFile(strSource, strDest, FALSE))
+ bGood = false;
+ }
+ else bGood = false;
+
+ strDir = strQ2;
+ strDir += "\\scripts";
+ if (::CreateDirectory(strDir, NULL))
+ {
+ CString strSource = g_strAppPath;
+ AddSlash(strSource);
+ strSource += "projqe4.dat";
+ CString strDest = strDir;
+ AddSlash(strDest);
+ strDest += "quake.qe4";
+ if (!::CopyFile(strSource, strDest, FALSE))
+ bGood = false;
+ else
+ strProjToLoad = strDest;
+ }
+ else bGood = false;
+ if (bGood && strProjToLoad.GetLength() > 0)
+ {
+ if (QE_LoadProject(strProjToLoad.GetBuffer(0)))
+ {
+ if (strMapToLoad.GetLength() > 0)
+ Map_LoadFile(strMapToLoad.GetBuffer(0));
+ }
+ }
+ }
+ else
+ {
+ CString strMsg;
+ strMsg.Format("Unable to create directory %s", strQ2);
+ MessageBox(strMsg);
+ }
+
+ }
+}
+
+void CMainFrame::UpdateStatusText()
+{
+ for (int n = 0; n < 6; n++)
+ {
+ if (m_strStatus[n].GetLength() >= 0 && m_wndStatusBar.GetSafeHwnd())
+ m_wndStatusBar.SetPaneText(n, m_strStatus[n]);
+ }
+}
+
+void CMainFrame::SetStatusText(int nPane, const char * pText)
+{
+ if (pText && nPane <= 5 && nPane > 0)
+ {
+ m_strStatus[nPane] = pText;
+ UpdateStatusText();
+ }
+}
+
+void CMainFrame::UpdateWindows(int nBits)
+{
+
+ if (!g_bScreenUpdates)
+ return;
+
+ if (nBits & (W_XY | W_XY_OVERLAY))
+ {
+ if (m_pXYWnd)
+ m_pXYWnd->RedrawWindow(NULL, NULL, RDW_INVALIDATE | RDW_UPDATENOW);
+ if (m_pXZWnd)
+ m_pXZWnd->RedrawWindow(NULL, NULL, RDW_INVALIDATE | RDW_UPDATENOW);
+ if (m_pYZWnd)
+ m_pYZWnd->RedrawWindow(NULL, NULL, RDW_INVALIDATE | RDW_UPDATENOW);
+ }
+
+ if (nBits & W_CAMERA || ((nBits & W_CAMERA_IFON) && m_bCamPreview))
+ {
+ if (m_pCamWnd)
+ {
+ m_pCamWnd->RedrawWindow(NULL, NULL, RDW_INVALIDATE | RDW_UPDATENOW);
+ }
+ }
+
+ if (nBits & (W_Z | W_Z_OVERLAY))
+ {
+ if (m_pZWnd)
+ m_pZWnd->RedrawWindow(NULL, NULL, RDW_INVALIDATE | RDW_UPDATENOW);
+ }
+
+ if (nBits & W_TEXTURE)
+ {
+ if (m_pTexWnd)
+ m_pTexWnd->RedrawWindow(NULL, NULL, RDW_INVALIDATE | RDW_UPDATENOW);
+ }
+}
+
+void WINAPI Sys_UpdateWindows (int nBits)
+{
+ if (g_PrefsDlg.m_bQE4Painting)
+ g_nUpdateBits |= nBits;
+ else
+ g_pParentWnd->UpdateWindows(nBits);
+}
+
+
+
+void CMainFrame::OnFlipClip()
+{
+ if (m_pActiveXY)
+ m_pActiveXY->FlipClip();
+}
+
+void CMainFrame::OnClipSelected()
+{
+ if (m_pActiveXY && m_pActiveXY->ClipMode())
+ {
+ Undo_Start("clip selected");
+ Undo_AddBrushList(&selected_brushes);
+ m_pActiveXY->Clip();
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+ }
+ else
+ {
+ if (g_bPatchBendMode)
+ Patch_BendHandleENTER();
+ else if (g_bPatchBendMode)
+ Patch_InsDelHandleENTER();
+ }
+}
+
+void CMainFrame::OnSplitSelected()
+{
+ if (m_pActiveXY)
+ {
+ Undo_Start("split selected");
+ Undo_AddBrushList(&selected_brushes);
+ m_pActiveXY->SplitClip();
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+ }
+}
+
+CXYWnd* CMainFrame::ActiveXY()
+{
+ return m_pActiveXY;
+}
+
+
+void CMainFrame::OnToggleviewXz()
+{
+ if (m_nCurrentStyle == 1) // QE4 style
+ {
+ if (m_pXZWnd && m_pXZWnd->GetSafeHwnd())
+ {
+ // get windowplacement doesn't actually save this so we will here
+ g_PrefsDlg.m_bXZVis = m_pXZWnd->IsWindowVisible();
+ if (g_PrefsDlg.m_bXZVis)
+ m_pXZWnd->ShowWindow(SW_HIDE);
+ else
+ m_pXZWnd->ShowWindow(SW_SHOW);
+ g_PrefsDlg.m_bXZVis ^= 1;
+ g_PrefsDlg.SavePrefs();
+ }
+ }
+}
+
+void CMainFrame::OnToggleviewYz()
+{
+ if (m_nCurrentStyle == 1) // QE4 style
+ {
+ if (m_pYZWnd && m_pYZWnd->GetSafeHwnd())
+ {
+ g_PrefsDlg.m_bYZVis = m_pYZWnd->IsWindowVisible();
+ if (g_PrefsDlg.m_bYZVis)
+ m_pYZWnd->ShowWindow(SW_HIDE);
+ else
+ m_pYZWnd->ShowWindow(SW_SHOW);
+ g_PrefsDlg.m_bYZVis ^= 1;
+ g_PrefsDlg.SavePrefs();
+ }
+ }
+}
+
+void CMainFrame::OnColorsBrush()
+{
+ DoColor(COLOR_BRUSHES);
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnColorsClipper()
+{
+ DoColor(COLOR_CLIPPER);
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnColorsGridtext()
+{
+ DoColor(COLOR_GRIDTEXT);
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnColorsSelectedbrush()
+{
+ DoColor(COLOR_SELBRUSHES);
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnColorsGridblock()
+{
+ DoColor(COLOR_GRIDBLOCK);
+ Sys_UpdateWindows (W_ALL);
+}
+
+
+
+void CMainFrame::OnColorsViewname()
+{
+ DoColor(COLOR_VIEWNAME);
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnColorSetoriginal()
+{
+ for (int i=0 ; i<3 ; i++)
+ {
+ g_qeglobals.d_savedinfo.colors[COLOR_TEXTUREBACK][i] = 0.25;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDBACK][i] = 1.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDMINOR][i] = 0.75;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDMAJOR][i] = 0.5;
+ g_qeglobals.d_savedinfo.colors[COLOR_CAMERABACK][i] = 0.25;
+ }
+
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDBLOCK][0] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDBLOCK][1] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDBLOCK][2] = 1.0;
+
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDTEXT][0] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDTEXT][1] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDTEXT][2] = 0.0;
+
+ g_qeglobals.d_savedinfo.colors[COLOR_SELBRUSHES][0] = 1.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_SELBRUSHES][1] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_SELBRUSHES][2] = 0.0;
+
+ g_qeglobals.d_savedinfo.colors[COLOR_CLIPPER][0] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_CLIPPER][1] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_CLIPPER][2] = 1.0;
+
+ g_qeglobals.d_savedinfo.colors[COLOR_BRUSHES][0] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_BRUSHES][1] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_BRUSHES][2] = 0.0;
+
+ g_qeglobals.d_savedinfo.colors[COLOR_VIEWNAME][0] = 0.5;
+ g_qeglobals.d_savedinfo.colors[COLOR_VIEWNAME][1] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_VIEWNAME][2] = 0.75;
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnColorSetqer()
+{
+ for (int i=0 ; i<3 ; i++)
+ {
+ g_qeglobals.d_savedinfo.colors[COLOR_TEXTUREBACK][i] = 0.25;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDBACK][i] = 1.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDMINOR][i] = 1.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDMAJOR][i] = 0.5;
+ g_qeglobals.d_savedinfo.colors[COLOR_CAMERABACK][i] = 0.25;
+ }
+
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDBLOCK][0] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDBLOCK][1] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDBLOCK][2] = 1.0;
+
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDTEXT][0] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDTEXT][1] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDTEXT][2] = 0.0;
+
+ g_qeglobals.d_savedinfo.colors[COLOR_SELBRUSHES][0] = 1.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_SELBRUSHES][1] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_SELBRUSHES][2] = 0.0;
+
+ g_qeglobals.d_savedinfo.colors[COLOR_CLIPPER][0] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_CLIPPER][1] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_CLIPPER][2] = 1.0;
+
+ g_qeglobals.d_savedinfo.colors[COLOR_BRUSHES][0] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_BRUSHES][1] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_BRUSHES][2] = 0.0;
+
+ g_qeglobals.d_savedinfo.colors[COLOR_VIEWNAME][0] = 0.5;
+ g_qeglobals.d_savedinfo.colors[COLOR_VIEWNAME][1] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_VIEWNAME][2] = 0.75;
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnColorSetblack()
+{
+ for (int i=0 ; i<3 ; i++)
+ {
+ g_qeglobals.d_savedinfo.colors[COLOR_TEXTUREBACK][i] = 0.25;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDBACK][i] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDMINOR][i] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_CAMERABACK][i] = 0.25;
+ }
+
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDMAJOR][0] = 0.3;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDMAJOR][1] = 0.5;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDMAJOR][2] = 0.5;
+
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDBLOCK][0] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDBLOCK][1] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDBLOCK][2] = 1.0;
+
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDTEXT][0] = 1.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDTEXT][1] = 1.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDTEXT][2] = 1.0;
+
+ g_qeglobals.d_savedinfo.colors[COLOR_SELBRUSHES][0] = 1.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_SELBRUSHES][1] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_SELBRUSHES][2] = 0.0;
+
+ g_qeglobals.d_savedinfo.colors[COLOR_CLIPPER][0] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_CLIPPER][1] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_CLIPPER][2] = 1.0;
+
+ g_qeglobals.d_savedinfo.colors[COLOR_BRUSHES][0] = 1.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_BRUSHES][1] = 1.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_BRUSHES][2] = 1.0;
+
+ g_qeglobals.d_savedinfo.colors[COLOR_VIEWNAME][0] = 0.7;
+ g_qeglobals.d_savedinfo.colors[COLOR_VIEWNAME][1] = 0.7;
+ g_qeglobals.d_savedinfo.colors[COLOR_VIEWNAME][2] = 0.0;
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnSnaptogrid()
+{
+ g_PrefsDlg.m_bNoClamp ^= 1;
+ g_PrefsDlg.SavePrefs();
+ CMenu* pMenu = GetMenu();
+ if (pMenu)
+ pMenu->CheckMenuItem(ID_SNAPTOGRID, MF_BYCOMMAND | (!g_PrefsDlg.m_bNoClamp) ? MF_CHECKED : MF_UNCHECKED);
+}
+
+
+void CMainFrame::OnSelectScale()
+{
+ //if (ActiveXY())
+ // ActiveXY()->UndoCopy();
+ Undo_Start("scale");
+ Undo_AddBrushList(&selected_brushes);
+
+ CScaleDialog dlg;
+ if (dlg.DoModal() == IDOK)
+ {
+ if (dlg.m_fX > 0 && dlg.m_fY > 0 && dlg.m_fZ > 0)
+ {
+ Select_Scale(dlg.m_fX, dlg.m_fY, dlg.m_fZ);
+ Sys_UpdateWindows (W_ALL);
+ }
+ else
+ Sys_Printf("Warning.. Tried to scale by a zero value.");
+ }
+
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnSelectMouserotate()
+{
+ if (ActiveXY())
+ {
+ if (ActiveXY()->ClipMode())
+ OnViewClipper();
+ if (ActiveXY()->RotateMode())
+ {
+ // SetRotateMode(false) always works
+ ActiveXY()->SetRotateMode(false);
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_SELECT_MOUSEROTATE, FALSE);
+ Map_BuildBrushData();
+ }
+ else
+ {
+ // may not work if no brush selected, see return value
+ if (ActiveXY()->SetRotateMode(true))
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_SELECT_MOUSEROTATE, TRUE);
+ else
+ // if MFC called, we need to set back to FALSE ourselves
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_SELECT_MOUSEROTATE, FALSE);
+ }
+
+ }
+}
+
+void CMainFrame::OnEditCopybrush()
+{
+ if (ActiveXY())
+ ActiveXY()->Copy();
+}
+
+void CMainFrame::OnEditPastebrush()
+{
+ if (ActiveXY())
+ ActiveXY()->Paste();
+}
+
+void CMainFrame::OnEditUndo()
+{
+// if (ActiveXY())
+// ActiveXY()->Undo();
+ Undo_Undo();
+}
+
+void CMainFrame::OnEditRedo()
+{
+ Undo_Redo();
+}
+
+void CMainFrame::OnUpdateEditUndo(CCmdUI* pCmdUI)
+{
+ /*
+ BOOL bEnable = false;
+ if (ActiveXY())
+ bEnable = ActiveXY()->UndoAvailable();
+ pCmdUI->Enable(bEnable);
+ */
+ pCmdUI->Enable(Undo_UndoAvailable());
+}
+
+void CMainFrame::OnUpdateEditRedo(CCmdUI* pCmdUI)
+{
+ pCmdUI->Enable(Undo_RedoAvailable());
+}
+
+void CMainFrame::OnSelectionTextureDec()
+{
+ g_qeglobals.d_savedinfo.m_nTextureTweak--;
+ if (g_qeglobals.d_savedinfo.m_nTextureTweak == 0)
+ g_qeglobals.d_savedinfo.m_nTextureTweak--;
+ SetTexValStatus();
+}
+
+void CMainFrame::OnSelectionTextureFit()
+{
+ // TODO: Add your command handler code here
+
+}
+
+void CMainFrame::OnSelectionTextureInc()
+{
+ g_qeglobals.d_savedinfo.m_nTextureTweak++;
+ if (g_qeglobals.d_savedinfo.m_nTextureTweak == 0)
+ g_qeglobals.d_savedinfo.m_nTextureTweak++;
+ SetTexValStatus();
+}
+
+void CMainFrame::OnSelectionTextureRotateclock()
+{
+ Select_RotateTexture(abs(g_PrefsDlg.m_nRotation));
+}
+
+void CMainFrame::OnSelectionTextureRotatecounter()
+{
+ Select_RotateTexture(-abs(g_PrefsDlg.m_nRotation));
+}
+
+void CMainFrame::OnSelectionTextureScaledown()
+{
+ Select_ScaleTexture(0, -abs(g_qeglobals.d_savedinfo.m_nTextureTweak));
+}
+
+void CMainFrame::OnSelectionTextureScaleup()
+{
+ Select_ScaleTexture(0, abs(g_qeglobals.d_savedinfo.m_nTextureTweak));
+}
+
+void CMainFrame::OnSelectionTextureScaleLeft()
+{
+ Select_ScaleTexture(-abs(g_qeglobals.d_savedinfo.m_nTextureTweak),0);
+}
+
+void CMainFrame::OnSelectionTextureScaleRight()
+{
+ Select_ScaleTexture(abs(g_qeglobals.d_savedinfo.m_nTextureTweak),0);
+}
+
+void CMainFrame::OnSelectionTextureShiftdown()
+{
+ Select_ShiftTexture(0, -abs(g_qeglobals.d_savedinfo.m_nTextureTweak));
+}
+
+void CMainFrame::OnSelectionTextureShiftleft()
+{
+ Select_ShiftTexture(-abs(g_qeglobals.d_savedinfo.m_nTextureTweak), 0);
+}
+
+void CMainFrame::OnSelectionTextureShiftright()
+{
+ Select_ShiftTexture(abs(g_qeglobals.d_savedinfo.m_nTextureTweak), 0);
+}
+
+void CMainFrame::OnSelectionTextureShiftup()
+{
+ Select_ShiftTexture(0, abs(g_qeglobals.d_savedinfo.m_nTextureTweak));
+}
+
+void CMainFrame::OnGridNext()
+{
+ if (g_qeglobals.d_gridsize < 64)
+ {
+ g_qeglobals.d_gridsize = g_qeglobals.d_gridsize << 1;
+ Sys_UpdateWindows(W_XY | W_Z);
+ SetGridStatus();
+
+ HMENU hMenu = ::GetMenu(GetSafeHwnd());
+ CheckMenuItem(hMenu, ID_GRID_1, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_GRID_2, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_GRID_4, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_GRID_8, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_GRID_16, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_GRID_32, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_GRID_64, MF_BYCOMMAND | MF_UNCHECKED);
+
+ int nID;
+ switch (g_qeglobals.d_gridsize)
+ {
+ case 1: nID = ID_GRID_1; break;
+ case 2: nID = ID_GRID_2; break;
+ case 4: nID = ID_GRID_4; break;
+ case 8: nID = ID_GRID_8; break;
+ case 16: nID = ID_GRID_16; break;
+ case 32: nID = ID_GRID_32; break;
+ case 64: nID = ID_GRID_64; break;
+ }
+ CheckMenuItem(hMenu, nID, MF_BYCOMMAND | MF_CHECKED);
+ }
+}
+
+void CMainFrame::OnGridPrev()
+{
+ if (g_qeglobals.d_gridsize > 1)
+ {
+ g_qeglobals.d_gridsize = g_qeglobals.d_gridsize >> 1;
+ Sys_UpdateWindows(W_XY | W_Z);
+ SetGridStatus();
+ HMENU hMenu = ::GetMenu(GetSafeHwnd());
+ CheckMenuItem(hMenu, ID_GRID_1, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_GRID_2, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_GRID_4, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_GRID_8, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_GRID_16, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_GRID_32, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_GRID_64, MF_BYCOMMAND | MF_UNCHECKED);
+
+ int nID;
+ switch (g_qeglobals.d_gridsize)
+ {
+ case 1: nID = ID_GRID_1; break;
+ case 2: nID = ID_GRID_2; break;
+ case 4: nID = ID_GRID_4; break;
+ case 8: nID = ID_GRID_8; break;
+ case 16: nID = ID_GRID_16; break;
+ case 32: nID = ID_GRID_32; break;
+ case 64: nID = ID_GRID_64; break;
+ }
+ CheckMenuItem(hMenu, nID, MF_BYCOMMAND | MF_CHECKED);
+ }
+}
+
+void CMainFrame::SetGridStatus()
+{
+ CString strStatus;
+ char c1;
+ char c2;
+ c1 = (g_PrefsDlg.m_bTextureLock) ? 'M' : ' ';
+ c2 = (g_PrefsDlg.m_bRotateLock) ? 'R' : ' ';
+ strStatus.Format("G:%i T:%i R:%i C:%i L:%c%c", g_qeglobals.d_gridsize, g_qeglobals.d_savedinfo.m_nTextureTweak, g_PrefsDlg.m_nRotation, g_PrefsDlg.m_nCubicScale, c1, c2);
+ SetStatusText(4, strStatus);
+}
+
+void CMainFrame::SetTexValStatus()
+{
+ //CString strStatus;
+ //strStatus.Format("T: %i C: %i", g_nTextureTweak, g_nCubicScale);
+ //SetStatusText(5, strStatus.GetBuffer(0));
+ SetGridStatus();
+}
+
+void CMainFrame::OnTextureReplaceall()
+{
+ CFindTextureDlg::show();
+}
+
+
+void CMainFrame::OnScalelockx()
+{
+ if (g_nScaleHow & SCALE_X)
+ {
+ g_nScaleHow ^= SCALE_X;
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_SCALELOCKX, FALSE);
+ }
+ else
+ {
+ g_nScaleHow |= SCALE_X;
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_SCALELOCKX);
+ }
+}
+
+void CMainFrame::OnScalelocky()
+{
+ if (g_nScaleHow & SCALE_Y)
+ {
+ g_nScaleHow ^= SCALE_Y;
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_SCALELOCKY, FALSE);
+ }
+ else
+ {
+ g_nScaleHow |= SCALE_Y;
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_SCALELOCKY);
+ }
+}
+
+void CMainFrame::OnScalelockz()
+{
+ if (g_nScaleHow & SCALE_Z)
+ {
+ g_nScaleHow ^= SCALE_Z;
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_SCALELOCKZ, FALSE);
+ }
+ else
+ {
+ g_nScaleHow |= SCALE_Z;
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_SCALELOCKZ);
+ }
+}
+
+void CMainFrame::OnSelectMousescale()
+{
+ if (ActiveXY())
+ {
+ if (ActiveXY()->ClipMode())
+ OnViewClipper();
+ if (ActiveXY()->RotateMode())
+ {
+ // SetRotateMode(false) always works
+ ActiveXY()->SetRotateMode(false);
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_SELECT_MOUSESCALE, FALSE);
+ }
+ if (ActiveXY()->ScaleMode())
+ {
+ ActiveXY()->SetScaleMode(false);
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_SELECT_MOUSESCALE, FALSE);
+ }
+ else
+ {
+ ActiveXY()->SetScaleMode(true);
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_SELECT_MOUSESCALE);
+ }
+ }
+}
+
+void CMainFrame::OnFileImport()
+{
+}
+
+void CMainFrame::OnFileProjectsettings()
+{
+ DoProjectSettings();
+}
+
+void CMainFrame::OnUpdateFileImport(CCmdUI* pCmdUI)
+{
+ pCmdUI->Enable(FALSE);
+}
+
+void CMainFrame::OnViewCubein()
+{
+ g_PrefsDlg.m_nCubicScale--;
+ if (g_PrefsDlg.m_nCubicScale < 1)
+ g_PrefsDlg.m_nCubicScale = 1;
+ g_PrefsDlg.SavePrefs();
+ Sys_UpdateWindows(W_CAMERA);
+ SetTexValStatus();
+}
+
+void CMainFrame::OnViewCubeout()
+{
+ g_PrefsDlg.m_nCubicScale++;
+ if (g_PrefsDlg.m_nCubicScale > 22)
+ g_PrefsDlg.m_nCubicScale = 22;
+ g_PrefsDlg.SavePrefs();
+ Sys_UpdateWindows(W_CAMERA);
+ SetTexValStatus();
+}
+
+void CMainFrame::OnViewCubicclipping()
+{
+ g_PrefsDlg.m_bCubicClipping ^= 1;
+ CMenu* pMenu = GetMenu();
+ if (pMenu)
+ pMenu->CheckMenuItem(ID_VIEW_CUBICCLIPPING, MF_BYCOMMAND | (g_PrefsDlg.m_bCubicClipping) ? MF_CHECKED : MF_UNCHECKED);
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_VIEW_CUBICCLIPPING, (g_PrefsDlg.m_bCubicClipping) ? TRUE : FALSE);
+ g_PrefsDlg.SavePrefs();
+ Map_BuildBrushData ();
+ Sys_UpdateWindows(W_CAMERA);
+}
+
+
+void CMainFrame::OnFileSaveregion()
+{
+ SaveAsDialog (true);
+}
+
+void CMainFrame::OnUpdateFileSaveregion(CCmdUI* pCmdUI)
+{
+ pCmdUI->Enable(static_cast<BOOL>(region_active));
+}
+
+void CMainFrame::OnSelectionMovedown()
+{
+ Undo_Start("move up");
+ Undo_AddBrushList(&selected_brushes);
+
+ vec3_t vAmt;
+ vAmt[0] = vAmt[1] = 0.0;
+ vAmt[2] = -g_qeglobals.d_gridsize;
+ Select_Move (vAmt);
+ Sys_UpdateWindows(W_CAMERA | W_XY | W_Z);
+
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnSelectionMoveup()
+{
+ vec3_t vAmt;
+ vAmt[0] = vAmt[1] = 0.0;
+ vAmt[2] = g_qeglobals.d_gridsize;
+ Select_Move (vAmt);
+ Sys_UpdateWindows(W_CAMERA | W_XY | W_Z);
+}
+
+void CMainFrame::OnToolbarMain()
+{
+
+}
+
+void CMainFrame::OnToolbarTexture()
+{
+
+}
+
+void CMainFrame::OnSelectionPrint()
+{
+ for (brush_t* b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ Brush_Print(b);
+}
+
+void CMainFrame::UpdateTextureBar()
+{
+ if (m_wndTextureBar.GetSafeHwnd())
+ m_wndTextureBar.GetSurfaceAttributes();
+}
+
+bool g_bTABDown = false;
+bool g_bOriginalFlag;
+void CMainFrame::OnSelectionTogglesizepaint()
+{
+ if (::GetAsyncKeyState('Q'))
+ {
+ if (!g_bTABDown)
+ {
+ g_bTABDown = true;
+ g_bOriginalFlag = g_PrefsDlg.m_bSizePaint;
+ g_PrefsDlg.m_bSizePaint = !g_bOriginalFlag;
+ Sys_UpdateWindows(W_XY);
+ return;
+ }
+ }
+ else
+ {
+ g_bTABDown = false;
+ g_PrefsDlg.m_bSizePaint = g_bOriginalFlag;
+ Sys_UpdateWindows(W_XY);
+ return;
+ }
+}
+
+void CMainFrame::OnBrushMakecone()
+{
+ Undo_Start("make cone");
+ Undo_AddBrushList(&selected_brushes);
+ DoSides(true);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+
+void CMainFrame::OnTexturesLoad()
+{
+ BROWSEINFO bi;
+ CString strPath;
+ char* p = strPath.GetBuffer(MAX_PATH+1);
+ bi.hwndOwner = GetSafeHwnd();
+ bi.pidlRoot = NULL;
+ bi.pszDisplayName = p;
+ bi.lpszTitle = "Load textures from path";
+ bi.ulFlags = 0;
+ bi.lpfn = NULL;
+ bi.lParam = NULL;
+ bi.iImage = 0;
+ LPITEMIDLIST pidlBrowse;
+ pidlBrowse = SHBrowseForFolder(&bi);
+ if (pidlBrowse)
+ {
+ SHGetPathFromIDList(pidlBrowse, p);
+ strPath.ReleaseBuffer();
+ AddSlash(strPath);
+ Texture_ShowDirectory(strPath.GetBuffer(0));
+ }
+}
+
+void CMainFrame::OnToggleRotatelock()
+{
+ g_PrefsDlg.m_bRotateLock ^= 1;
+ CMenu* pMenu = GetMenu();
+ if (pMenu)
+ pMenu->CheckMenuItem(ID_TOGGLE_ROTATELOCK, MF_BYCOMMAND | (g_PrefsDlg.m_bRotateLock) ? MF_CHECKED : MF_UNCHECKED);
+ g_PrefsDlg.SavePrefs();
+ SetGridStatus();
+}
+
+
+void CMainFrame::OnCurveBevel()
+{
+ //Curve_MakeCurvedBrush (false, false, false, false, false, true, true);
+}
+
+void CMainFrame::OnCurveCylinder()
+{
+ //Curve_MakeCurvedBrush (false, false, false, true, true, true, true);
+}
+
+void CMainFrame::OnCurveEighthsphere()
+{
+ //Curve_MakeCurvedBrush (false, true, false, true, true, false, false);
+}
+
+void CMainFrame::OnCurveEndcap()
+{
+ //Curve_MakeCurvedBrush (false, false, false, false, true, true, true);
+}
+
+void CMainFrame::OnCurveHemisphere()
+{
+ //Curve_MakeCurvedBrush (false, true, false, true, true, true, true);
+}
+
+void CMainFrame::OnCurveInvertcurve()
+{
+ //Curve_Invert ();
+}
+
+void CMainFrame::OnCurveQuarter()
+{
+ //Curve_MakeCurvedBrush (false, true, false, true, true, true, false);
+}
+
+void CMainFrame::OnCurveSphere()
+{
+ //Curve_MakeCurvedBrush (false, true, true, true, true, true, true);
+}
+
+void CMainFrame::OnFileImportmap()
+{
+ CFileDialog dlgFile(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, "Map files (*.map)|*.map||", this);
+ if (dlgFile.DoModal() == IDOK)
+ {
+ Map_ImportFile(dlgFile.GetPathName().GetBuffer(0));
+ }
+}
+
+void CMainFrame::OnFileExportmap()
+{
+ CFileDialog dlgFile(FALSE, "map", NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, "Map files (*.map)|*.map||", this);
+ if (dlgFile.DoModal() == IDOK)
+ {
+ Map_SaveSelected(dlgFile.GetPathName().GetBuffer(0));
+ }
+}
+
+void CMainFrame::OnViewShowcurves()
+{
+ if ( ( g_qeglobals.d_savedinfo.exclude ^= EXCLUDE_CURVES ) & EXCLUDE_CURVES )
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWCURVES, MF_BYCOMMAND | MF_UNCHECKED );
+ else
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWCURVES, MF_BYCOMMAND | MF_CHECKED );
+ Sys_UpdateWindows (W_XY|W_CAMERA);
+}
+
+void CMainFrame::OnSelectionSelectNudgedown()
+{
+ NudgeSelection(3, g_qeglobals.d_savedinfo.m_nTextureTweak);
+}
+
+void CMainFrame::OnSelectionSelectNudgeleft()
+{
+ NudgeSelection(0, g_qeglobals.d_savedinfo.m_nTextureTweak);
+}
+
+void CMainFrame::OnSelectionSelectNudgeright()
+{
+ NudgeSelection(2, g_qeglobals.d_savedinfo.m_nTextureTweak);
+}
+
+void CMainFrame::OnSelectionSelectNudgeup()
+{
+ NudgeSelection(1, g_qeglobals.d_savedinfo.m_nTextureTweak);
+}
+
+void CMainFrame::NudgeSelection(int nDirection, int nAmount)
+{
+ if (ActiveXY()->RotateMode())
+ {
+ int nAxis = 0;
+ if (ActiveXY()->GetViewType() == XY)
+ {
+ nAxis = 2;
+ }
+ else
+ if (g_pParentWnd->ActiveXY()->GetViewType() == XZ)
+ {
+ nAxis = 1;
+ nAmount = -nAmount;
+ }
+
+ if (nDirection == 2 || nDirection == 3)
+ {
+ nAmount = -nAmount;
+ }
+
+ float fDeg = -nAmount;
+ float fAdj = nAmount;
+
+ g_pParentWnd->ActiveXY()->Rotation()[nAxis] += fAdj;
+ CString strStatus;
+ strStatus.Format("Rotation x:: %.1f y:: %.1f z:: %.1f", g_pParentWnd->ActiveXY()->Rotation()[0], g_pParentWnd->ActiveXY()->Rotation()[1], g_pParentWnd->ActiveXY()->Rotation()[2]);
+ g_pParentWnd->SetStatusText(2, strStatus);
+ Select_RotateAxis(nAxis, fDeg, false, true);
+ Sys_UpdateWindows (W_ALL);
+ }
+ else
+ if (ActiveXY()->ScaleMode())
+ {
+ if (nDirection == 0 || nDirection == 3)
+ {
+ nAmount = -nAmount;
+ }
+ vec3_t v;
+ v[0] = v[1] = v[2] = 1.0;
+ if (nAmount > 0)
+ {
+ v[0] = 1.1;
+ v[1] = 1.1;
+ v[2] = 1.1;
+ }
+ else
+ {
+ v[0] = 0.9;
+ v[1] = 0.9;
+ v[2] = 0.9;
+ }
+
+ Select_Scale((g_nScaleHow & SCALE_X) ? v[0] : 1.0,
+ (g_nScaleHow & SCALE_Y) ? v[1] : 1.0,
+ (g_nScaleHow & SCALE_Z) ? v[2] : 1.0);
+ Sys_UpdateWindows (W_ALL);
+ }
+ else
+ {
+ // 0 - left, 1 - up, 2 - right, 3 - down
+ int nDim;
+ if (nDirection == 0)
+ {
+ nDim = ActiveXY()->GetViewType() == YZ ? 1 : 0;
+ nAmount = -nAmount;
+ }
+ else if (nDirection == 1)
+ {
+ nDim = ActiveXY()->GetViewType() == XY ? 1 : 2;
+ }
+ else if (nDirection == 2)
+ {
+ nDim = ActiveXY()->GetViewType() == YZ ? 1 : 0;
+ }
+ else
+ {
+ nDim = ActiveXY()->GetViewType() == XY ? 1 : 2;
+ nAmount = -nAmount;
+ }
+ Nudge(nDim, nAmount);
+ }
+}
+
+
+BOOL CMainFrame::PreTranslateMessage(MSG* pMsg)
+{
+ return CFrameWnd::PreTranslateMessage(pMsg);
+}
+
+void CMainFrame::Nudge(int nDim, float fNudge)
+{
+ vec3_t vMove;
+ vMove[0] = vMove[1] = vMove[2] = 0;
+ vMove[nDim] = fNudge;
+ Select_Move(vMove, true);
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnTexturesLoadlist()
+{
+ CDialogTextures dlg;
+ if (dlg.DoModal() == IDOK && dlg.m_nSelection >= 0)
+ {
+ Texture_ShowDirectory(dlg.m_nSelection + CMD_TEXTUREWAD);
+ }
+}
+
+void CMainFrame::OnDontselectcurve()
+{
+ g_PrefsDlg.m_bSelectCurves ^= 1;
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_DONTSELECTCURVE, (g_PrefsDlg.m_bSelectCurves) ? FALSE : TRUE);
+}
+
+void CMainFrame::OnConvertcurves()
+{
+#if 0
+ Select_Deselect();
+ for (brush_t* pb = active_brushes.next ; pb != &active_brushes ; pb = pb->next)
+ {
+ if (pb->curveBrush)
+ {
+ for (face_t* f = pb->brush_faces ; f ; f=f->next)
+ {
+ if (f->texdef.contents & CONTENTS_LADDER)
+ {
+ f->texdef.contents &= ~CONTENTS_LADDER;
+ f->texdef.contents |= CONTENTS_NEGATIVE_CURVE;
+ }
+ }
+ }
+ }
+ Map_BuildBrushData();
+#endif
+
+}
+
+void CMainFrame::OnDynamicLighting()
+{
+ CCamWnd* pCam = new CCamWnd();
+ CRect rect(100, 100, 300, 300);
+ pCam->Create(CAMERA_WINDOW_CLASS, "", WS_OVERLAPPEDWINDOW, rect, GetDesktopWindow(), 12345);
+ pCam->ShowWindow(SW_SHOW);
+}
+
+
+void CMainFrame::OnCurveSimplepatchmesh()
+{
+ Undo_Start("make simpe patch mesh");
+ Undo_AddBrushList(&selected_brushes);
+
+ CPatchDensityDlg dlg;
+ dlg.DoModal();
+
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+
+void CMainFrame::OnPatchToggleBox()
+{
+ g_bPatchShowBounds ^= 1;
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_PATCH_SHOWBOUNDINGBOX, (g_bPatchShowBounds) ? TRUE : FALSE);
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CMainFrame::OnPatchWireframe()
+{
+ g_bPatchWireFrame ^= 1;
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_PATCH_WIREFRAME, (g_bPatchWireFrame) ? TRUE : FALSE);
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CMainFrame::OnCurvePatchcone()
+{
+ Undo_Start("make curve cone");
+ Undo_AddBrushList(&selected_brushes);
+ Patch_BrushToMesh(true);
+ Sys_UpdateWindows (W_ALL);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnCurvePatchtube()
+{
+ Undo_Start("make curve cylinder");
+ Undo_AddBrushList(&selected_brushes);
+ Patch_BrushToMesh(false);
+ Sys_UpdateWindows (W_ALL);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnPatchWeld()
+{
+ g_bPatchWeld ^= 1;
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_PATCH_WELD, (g_bPatchWeld) ? TRUE : FALSE);
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CMainFrame::OnCurvePatchbevel()
+{
+ Undo_Start("make bevel");
+ Undo_AddBrushList(&selected_brushes);
+ Patch_BrushToMesh(false, true, false);
+ Sys_UpdateWindows (W_ALL);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnCurvePatchendcap()
+{
+ Undo_Start("make end cap");
+ Undo_AddBrushList(&selected_brushes);
+ Patch_BrushToMesh(false, false, true);
+ Sys_UpdateWindows (W_ALL);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnCurvePatchinvertedbevel()
+{
+ //Patch_BrushToMesh(false, true, false, true);
+ //Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnCurvePatchinvertedendcap()
+{
+ //Patch_BrushToMesh(false, false, true, true);
+ //Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnPatchDrilldown()
+{
+ g_bPatchDrillDown ^= 1;
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_PATCH_DRILLDOWN, (g_bPatchDrillDown) ? TRUE : FALSE);
+ Sys_UpdateWindows(W_ALL);
+}
+
+
+void CMainFrame::OnCurveInsertcolumn()
+{
+ Undo_Start("insert colum");
+ Undo_AddBrushList(&selected_brushes);
+ //Patch_AdjustSelectedRowCols(0, 2);
+ Patch_AdjustSelected(true, true, true);
+ Sys_UpdateWindows(W_ALL);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnCurveInsertrow()
+{
+ Undo_Start("insert row");
+ Undo_AddBrushList(&selected_brushes);
+ //Patch_AdjustSelectedRowCols(2, 0);
+ Patch_AdjustSelected(true, false, true);
+ Sys_UpdateWindows(W_ALL);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnCurveDeletecolumn()
+{
+ Undo_Start("delete column");
+ Undo_AddBrushList(&selected_brushes);
+ Patch_AdjustSelected(false, true, true);
+ Sys_UpdateWindows(W_ALL);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnCurveDeleterow()
+{
+ Undo_Start("delete row");
+ Undo_AddBrushList(&selected_brushes);
+ Patch_AdjustSelected(false, false, true);
+ Sys_UpdateWindows(W_ALL);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnCurveInsertAddcolumn()
+{
+ Undo_Start("add (2) columns");
+ Undo_AddBrushList(&selected_brushes);
+ Patch_AdjustSelected(true, true, true);
+ Sys_UpdateWindows(W_ALL);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnCurveInsertAddrow()
+{
+ Undo_Start("add (2) rows");
+ Undo_AddBrushList(&selected_brushes);
+ Patch_AdjustSelected(true, false, true);
+ Sys_UpdateWindows(W_ALL);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnCurveInsertInsertcolumn()
+{
+ Undo_Start("insert (2) columns");
+ Undo_AddBrushList(&selected_brushes);
+ Patch_AdjustSelected(true, true, false);
+ Sys_UpdateWindows(W_ALL);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnCurveInsertInsertrow()
+{
+ Undo_Start("insert (2) rows");
+ Undo_AddBrushList(&selected_brushes);
+ Patch_AdjustSelected(true, false, false);
+ Sys_UpdateWindows(W_ALL);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnCurveNegative()
+{
+ Patch_ToggleInverted();
+ //Sys_UpdateWindows(W_ALL);
+}
+
+void CMainFrame::OnCurveNegativeTextureX()
+{
+ Patch_InvertTexture(false);
+ //Sys_UpdateWindows(W_ALL);
+}
+
+void CMainFrame::OnCurveNegativeTextureY()
+{
+ Patch_InvertTexture(true);
+ //Sys_UpdateWindows(W_ALL);
+}
+
+
+void CMainFrame::OnCurveDeleteFirstcolumn()
+{
+ Undo_Start("delete first (2) columns");
+ Undo_AddBrushList(&selected_brushes);
+ Patch_AdjustSelected(false, true, true);
+ Sys_UpdateWindows(W_ALL);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnCurveDeleteFirstrow()
+{
+ Undo_Start("delete first (2) rows");
+ Undo_AddBrushList(&selected_brushes);
+ Patch_AdjustSelected(false, false, true);
+ Sys_UpdateWindows(W_ALL);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnCurveDeleteLastcolumn()
+{
+ Undo_Start("delete last (2) columns");
+ Undo_AddBrushList(&selected_brushes);
+ Patch_AdjustSelected(false, true, false);
+ Sys_UpdateWindows(W_ALL);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnCurveDeleteLastrow()
+{
+ Undo_Start("delete last (2) rows");
+ Undo_AddBrushList(&selected_brushes);
+ Patch_AdjustSelected(false, false, false);
+ Sys_UpdateWindows(W_ALL);
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnPatchBend()
+{
+ Patch_BendToggle();
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_PATCH_BEND, (g_bPatchBendMode) ? TRUE : FALSE);
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CMainFrame::OnPatchInsdel()
+{
+ Patch_InsDelToggle();
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_PATCH_INSDEL, (g_bPatchInsertMode) ? TRUE : FALSE);
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CMainFrame::OnPatchEnter()
+{
+
+}
+
+void CMainFrame::OnPatchTab()
+{
+ if (g_bPatchBendMode)
+ Patch_BendHandleTAB();
+ else if (g_bPatchInsertMode)
+ Patch_InsDelHandleTAB();
+ else
+ {
+ // check to see if the selected brush is part of a func group
+ // if it is, deselect everything and reselect the next brush
+ // in the group
+ brush_t *b = selected_brushes.next;
+ entity_t * e;
+ if (b != &selected_brushes)
+ {
+ if (strcmpi(b->owner->eclass->name, "worldspawn") != 0)
+ {
+ e = b->owner;
+ Select_Deselect();
+ for (brush_t * b2 = e->brushes.onext ; b2 != &e->brushes ; b2 = b2->onext)
+ {
+ if (b == b2)
+ {
+ b2 = b2->onext;
+ break;
+ }
+ }
+ if (b2 == &e->brushes)
+ b2 = b2->onext;
+
+ Select_Brush(b2, false);
+ Sys_UpdateWindows(W_ALL);
+ }
+ }
+ }
+}
+
+void CMainFrame::UpdatePatchToolbarButtons()
+{
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_PATCH_BEND, (g_bPatchBendMode) ? TRUE : FALSE);
+ m_wndToolBar.GetToolBarCtrl().CheckButton(ID_PATCH_INSDEL, (g_bPatchInsertMode) ? TRUE : FALSE);
+}
+
+void CMainFrame::OnCurvePatchdensetube()
+{
+ Undo_Start("dense cylinder");
+ Undo_AddBrushList(&selected_brushes);
+
+ Patch_BrushToMesh(false);
+ OnCurveInsertAddrow();
+ OnCurveInsertInsertrow();
+ Sys_UpdateWindows (W_ALL);
+
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnCurvePatchverydensetube()
+{
+ Undo_Start("very dense cylinder");
+ Undo_AddBrushList(&selected_brushes);
+
+ Patch_BrushToMesh(false);
+ OnCurveInsertAddrow();
+ OnCurveInsertInsertrow();
+ OnCurveInsertAddrow();
+ OnCurveInsertInsertrow();
+ Sys_UpdateWindows (W_ALL);
+
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnCurveCap()
+{
+ Patch_CapCurrent();
+ Sys_UpdateWindows (W_ALL);
+}
+
+
+void CMainFrame::OnCurveCapInvertedbevel()
+{
+ Patch_CapCurrent(true);
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnCurveCapInvertedendcap()
+{
+ Patch_CapCurrent(false, true);
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnCurveRedisperseCols()
+{
+ Patch_DisperseColumns();
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnCurveRedisperseRows()
+{
+ Patch_DisperseRows();
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnPatchNaturalize()
+{
+ Patch_NaturalizeSelected();
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnSnapToGrid()
+{
+ Select_SnapToGrid();
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnCurvePatchsquare()
+{
+ Undo_Start("square cylinder");
+ Undo_AddBrushList(&selected_brushes);
+
+ Patch_BrushToMesh(false, false, false, true);
+ Sys_UpdateWindows (W_ALL);
+
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnTerrainCreateFromBrush()
+{
+ Terrain_BrushToMesh();
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::CheckTextureScale(int id)
+{
+ CMenu* pMenu = GetMenu();
+ if (pMenu)
+ {
+ pMenu->CheckMenuItem(ID_TEXTURES_TEXTUREWINDOWSCALE_10, MF_BYCOMMAND | MF_UNCHECKED);
+ pMenu->CheckMenuItem(ID_TEXTURES_TEXTUREWINDOWSCALE_25, MF_BYCOMMAND | MF_UNCHECKED);
+ pMenu->CheckMenuItem(ID_TEXTURES_TEXTUREWINDOWSCALE_50, MF_BYCOMMAND | MF_UNCHECKED);
+ pMenu->CheckMenuItem(ID_TEXTURES_TEXTUREWINDOWSCALE_100, MF_BYCOMMAND | MF_UNCHECKED);
+ pMenu->CheckMenuItem(ID_TEXTURES_TEXTUREWINDOWSCALE_200, MF_BYCOMMAND | MF_UNCHECKED);
+ pMenu->CheckMenuItem(id, MF_BYCOMMAND | MF_CHECKED);
+ }
+ g_PrefsDlg.SavePrefs();
+ Texture_ResetPosition();
+ Sys_UpdateWindows(W_TEXTURE);
+}
+
+void CMainFrame::OnTexturesTexturewindowscale10()
+{
+ g_PrefsDlg.m_nTextureScale = 10;
+ CheckTextureScale(ID_TEXTURES_TEXTUREWINDOWSCALE_10);
+}
+
+void CMainFrame::OnTexturesTexturewindowscale100()
+{
+ g_PrefsDlg.m_nTextureScale = 100;
+ CheckTextureScale(ID_TEXTURES_TEXTUREWINDOWSCALE_100);
+}
+
+void CMainFrame::OnTexturesTexturewindowscale200()
+{
+ g_PrefsDlg.m_nTextureScale = 200;
+ CheckTextureScale(ID_TEXTURES_TEXTUREWINDOWSCALE_200);
+}
+
+void CMainFrame::OnTexturesTexturewindowscale25()
+{
+ g_PrefsDlg.m_nTextureScale = 25;
+ CheckTextureScale(ID_TEXTURES_TEXTUREWINDOWSCALE_25);
+}
+
+void CMainFrame::OnTexturesTexturewindowscale50()
+{
+ g_PrefsDlg.m_nTextureScale = 50;
+ CheckTextureScale(ID_TEXTURES_TEXTUREWINDOWSCALE_50);
+}
+
+
+
+void CMainFrame::OnTexturesFlush()
+{
+ Texture_Flush();
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CMainFrame::OnCurveOverlayClear()
+{
+ Patch_ClearOverlays();
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CMainFrame::OnCurveOverlaySet()
+{
+ Patch_SetOverlays();
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CMainFrame::OnCurveThicken()
+{
+ Undo_Start("curve thicken");
+ Undo_AddBrushList(&selected_brushes);
+
+ CDialogThick dlg;
+ if (dlg.DoModal() == IDOK)
+ {
+ Patch_Thicken(dlg.m_nAmount, dlg.m_bSeams);
+ Sys_UpdateWindows(W_ALL);
+ }
+
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnCurveCyclecap()
+{
+ Patch_NaturalizeSelected(true, true);
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnCurveMatrixTranspose()
+{
+ Patch_Transpose();
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnTexturesReloadshaders()
+{
+ CWaitCursor wait;
+ ReloadShaders();
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::SetEntityCheck()
+{
+ CMenu* pMenu = GetMenu();
+ if (pMenu)
+ {
+ pMenu->CheckMenuItem(ID_VIEW_ENTITIESAS_BOUNDINGBOX, MF_BYCOMMAND | (g_PrefsDlg.m_nEntityShowState == ENTITY_BOX) ? MF_CHECKED : MF_UNCHECKED);
+ pMenu->CheckMenuItem(ID_VIEW_ENTITIESAS_WIREFRAME, MF_BYCOMMAND | (g_PrefsDlg.m_nEntityShowState == ENTITY_WIRE) ? MF_CHECKED : MF_UNCHECKED);
+ pMenu->CheckMenuItem(ID_VIEW_ENTITIESAS_SELECTEDWIREFRAME, MF_BYCOMMAND | (g_PrefsDlg.m_nEntityShowState == ENTITY_SELECTED) ? MF_CHECKED : MF_UNCHECKED);
+ pMenu->CheckMenuItem(ID_VIEW_ENTITIESAS_SELECTEDSKINNED, MF_BYCOMMAND | (g_PrefsDlg.m_nEntityShowState == ENTITY_SELECTED_SKIN) ? MF_CHECKED : MF_UNCHECKED);
+ pMenu->CheckMenuItem(ID_VIEW_ENTITIESAS_SKINNED, MF_BYCOMMAND | (g_PrefsDlg.m_nEntityShowState == ENTITY_SKINNED) ? MF_CHECKED : MF_UNCHECKED);
+ pMenu->CheckMenuItem(ID_VIEW_ENTITIESAS_SKINNEDANDBOXED, MF_BYCOMMAND | (g_PrefsDlg.m_nEntityShowState == ENTITY_SKINNED_BOXED) ? MF_CHECKED : MF_UNCHECKED);
+ }
+}
+
+
+void CMainFrame::OnShowEntities()
+{
+ HandlePopup(this, IDR_POPUP_ENTITY);
+}
+
+void CMainFrame::OnViewEntitiesasBoundingbox()
+{
+ g_PrefsDlg.m_nEntityShowState = ENTITY_BOX;
+ SetEntityCheck();
+ g_PrefsDlg.SavePrefs();
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnViewEntitiesasSelectedskinned()
+{
+ g_PrefsDlg.m_nEntityShowState = ENTITY_SELECTED_SKIN;
+ SetEntityCheck();
+ g_PrefsDlg.SavePrefs();
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnViewEntitiesasSelectedwireframe()
+{
+ g_PrefsDlg.m_nEntityShowState = ENTITY_SELECTED;
+ SetEntityCheck();
+ g_PrefsDlg.SavePrefs();
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnViewEntitiesasSkinned()
+{
+ g_PrefsDlg.m_nEntityShowState = ENTITY_SKINNED;
+ SetEntityCheck();
+ g_PrefsDlg.SavePrefs();
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnViewEntitiesasSkinnedandboxed()
+{
+ g_PrefsDlg.m_nEntityShowState = ENTITY_SKINNED_BOXED;
+ SetEntityCheck();
+ g_PrefsDlg.SavePrefs();
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnViewEntitiesasWireframe()
+{
+ g_PrefsDlg.m_nEntityShowState = ENTITY_WIRE;
+ SetEntityCheck();
+ g_PrefsDlg.SavePrefs();
+ Sys_UpdateWindows (W_ALL);
+}
+
+
+
+
+
+
+
+void CMainFrame::OnPluginsRefresh()
+{
+ CleanPlugInMenu();
+ CString str(g_strAppPath);
+ AddSlash(str);
+ str += "plugins\\";
+ m_PlugInMgr.Init(str);
+}
+
+void CMainFrame::CleanPlugInMenu()
+{
+ m_nNextPlugInID = ID_PLUGIN_START;
+ CMenu* pMenu = GetMenu();
+ //--pMenu->RemoveMenu(MENU_PLUGIN, MF_BYPOSITION);
+ //--pMenu->InsertMenu(MENU_PLUGIN, MF_BYPOSITION, 0, "Plugins");
+ //--DrawMenuBar();
+ CMenu* pSub = pMenu->GetSubMenu(MENU_PLUGIN);
+ if (pSub)
+ {
+ int n = pSub->GetMenuItemCount();
+ for (int i = n; i > 1 ; i--)
+ {
+ pSub->RemoveMenu(i, MF_BYPOSITION);
+ }
+ }
+}
+
+void CMainFrame::AddPlugInMenuItem(CPlugIn* pPlugIn)
+{
+ const char *menuText; //PGM
+ CMenu* pMenu = GetMenu();
+ CMenu* pSub = pMenu->GetSubMenu(MENU_PLUGIN);
+ if (pSub)
+ {
+ CMenu* pChild = new CMenu();
+ pChild->CreateMenu();
+ int nCount = pPlugIn->getCommandCount();
+ if (nCount > 0)
+ {
+ while (nCount > 0)
+ {
+ menuText = pPlugIn->getCommand(--nCount);
+ if (menuText != NULL && strlen(menuText) > 0)
+ {
+ if(!strcmp(menuText, "-"))
+ pChild->AppendMenu(MF_SEPARATOR, NULL);
+ else
+ pChild->AppendMenu(MF_STRING, m_nNextPlugInID, menuText);
+ pPlugIn->addMenuID(m_nNextPlugInID++);
+ }
+ }
+ pSub->AppendMenu(MF_POPUP, reinterpret_cast<unsigned int>(pChild->GetSafeHmenu()), pPlugIn->getMenuName());
+ }
+ }
+}
+
+void CMainFrame::OnPlugIn(unsigned int nID)
+{
+ CMenu* pMenu = GetMenu();
+ CString str;
+ pMenu->GetMenuString(nID, str, MF_BYCOMMAND);
+ m_PlugInMgr.Dispatch(nID, str);
+}
+
+void CMainFrame::OnViewShowhint()
+{
+ if ( ( g_qeglobals.d_savedinfo.exclude ^= EXCLUDE_HINT ) & EXCLUDE_HINT )
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWHINT, MF_BYCOMMAND | MF_UNCHECKED );
+ else
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWHINT, MF_BYCOMMAND | MF_CHECKED );
+ Sys_UpdateWindows (W_XY|W_CAMERA);
+}
+
+void CMainFrame::OnTexturesShowall()
+{
+ Texture_ShowAll();
+}
+
+void CMainFrame::OnPatchInspector()
+{
+ DoPatchInspector();
+}
+
+void CMainFrame::OnViewOpengllighting()
+{
+ g_PrefsDlg.m_bGLLighting ^= 1;
+ g_PrefsDlg.SavePrefs();
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_OPENGLLIGHTING, MF_BYCOMMAND | (g_PrefsDlg.m_bGLLighting) ? MF_CHECKED : MF_UNCHECKED );
+ Sys_UpdateWindows (W_XY|W_CAMERA);
+}
+
+void CMainFrame::OnSelectAll()
+{
+ Select_AllOfType();
+}
+
+void CMainFrame::OnViewShowcaulk()
+{
+ if ( ( g_qeglobals.d_savedinfo.exclude ^= EXCLUDE_CAULK ) & EXCLUDE_CAULK )
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWCAULK, MF_BYCOMMAND | MF_UNCHECKED );
+ else
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWCAULK, MF_BYCOMMAND | MF_CHECKED );
+ Sys_UpdateWindows (W_XY|W_CAMERA);
+
+}
+
+void CMainFrame::OnCurveFreeze()
+{
+ Patch_Freeze();
+}
+
+void CMainFrame::OnCurveUnFreeze()
+{
+ Patch_UnFreeze(false);
+}
+
+void CMainFrame::OnCurveUnFreezeAll()
+{
+ Patch_UnFreeze(true);
+}
+
+void CMainFrame::OnSelectReselect()
+{
+ Select_Reselect();
+}
+
+void CMainFrame::OnViewShowangles()
+{
+ if ( ( g_qeglobals.d_savedinfo.exclude ^= EXCLUDE_ANGLES ) & EXCLUDE_ANGLES )
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWANGLES, MF_BYCOMMAND | MF_UNCHECKED );
+ else
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_VIEW_SHOWANGLES, MF_BYCOMMAND | MF_CHECKED );
+ Sys_UpdateWindows (W_XY|W_CAMERA);
+}
+
+void CMainFrame::OnEditSaveprefab()
+{
+ CFileDialog dlgFile(FALSE, "pfb", NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, "Prefab files (*.pfb)|*.pfb||", this);
+ char CurPath[1024];
+ if (g_PrefsDlg.m_strPrefabPath.GetLength() > 0)
+ {
+ strcpy(CurPath, g_PrefsDlg.m_strPrefabPath);
+ }
+ else
+ {
+ ::GetCurrentDirectory(1024, CurPath);
+ }
+ dlgFile.m_ofn.lpstrInitialDir = CurPath;
+ if (dlgFile.DoModal() == IDOK)
+ {
+ Map_SaveSelected(dlgFile.GetPathName().GetBuffer(0));
+ }
+}
+
+
+void CMainFrame::OnEditLoadprefab()
+{
+ CFileDialog dlgFile(TRUE, "pfb", NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, "Prefab files (*.pfb)|*.pfb||", this);
+ char CurPath[1024];
+ if (g_PrefsDlg.m_strPrefabPath.GetLength() > 0)
+ {
+ strcpy(CurPath, g_PrefsDlg.m_strPrefabPath);
+ }
+ else
+ {
+ ::GetCurrentDirectory(1024, CurPath);
+ }
+ dlgFile.m_ofn.lpstrInitialDir = CurPath;
+ if (dlgFile.DoModal() == IDOK)
+ {
+ Map_ImportFile(dlgFile.GetPathName().GetBuffer(0));
+ }
+}
+
+void CMainFrame::OnCurveMoreendcapsbevelsSquarebevel()
+{
+ Undo_Start("square bevel");
+ Undo_AddBrushList(&selected_brushes);
+
+ Patch_BrushToMesh(false, true, false, true);
+ Sys_UpdateWindows (W_ALL);
+
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnCurveMoreendcapsbevelsSquareendcap()
+{
+ Undo_Start("square endcap");
+ Undo_AddBrushList(&selected_brushes);
+
+ Patch_BrushToMesh(false, false, true, true);
+ Sys_UpdateWindows (W_ALL);
+
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+void CMainFrame::OnBrushPrimitivesSphere()
+{
+ Undo_Start("make sphere");
+ Undo_AddBrushList(&selected_brushes);
+
+ DoSides(false, true);
+
+ Undo_EndBrushList(&selected_brushes);
+ Undo_End();
+}
+
+extern bool g_bCrossHairs;
+void CMainFrame::OnViewCrosshair()
+{
+ g_bCrossHairs ^= 1;
+ Sys_UpdateWindows (W_XY);
+}
+
+void CMainFrame::OnViewHideshowHideselected()
+{
+ Select_Hide();
+ Select_Deselect();
+}
+
+void CMainFrame::OnViewHideshowShowhidden()
+{
+ Select_ShowAllHidden();
+}
+
+void CMainFrame::OnTexturesShadersShow()
+{
+ g_PrefsDlg.m_bShowShaders ^= 1;
+ CheckMenuItem ( ::GetMenu(g_qeglobals.d_hwndMain), ID_TEXTURES_SHADERS_SHOW, MF_BYCOMMAND | ((g_PrefsDlg.m_bShowShaders) ? MF_CHECKED : MF_UNCHECKED ));
+ Sys_UpdateWindows(W_TEXTURE);
+
+}
+
+void CMainFrame::OnTexturesFlushUnused()
+{
+ Texture_FlushUnused();
+ Sys_UpdateWindows(W_TEXTURE);
+}
+
+void CMainFrame::OnSelectionInvert()
+{
+ Select_Invert();
+ Sys_UpdateWindows(W_XY | W_Z | W_CAMERA);
+}
+
+
+void CMainFrame::OnViewGroups()
+{
+ if (m_nCurrentStyle == 0 || m_nCurrentStyle == 3)
+ {
+ if (::IsWindowVisible(g_qeglobals.d_hwndEntity) && inspector_mode == W_GROUP)
+ ::ShowWindow(g_qeglobals.d_hwndEntity, SW_HIDE);
+ else
+ {
+ ::ShowWindow(g_qeglobals.d_hwndEntity, SW_NORMAL);
+ SetInspectorMode(W_GROUP);
+ }
+ }
+ else
+ {
+ if (inspector_mode == W_GROUP && m_nCurrentStyle != QR_QE4)
+ {
+ if (::IsWindowVisible(g_qeglobals.d_hwndEntity))
+ ::ShowWindow(g_qeglobals.d_hwndEntity, SW_HIDE);
+ else
+ ::ShowWindow(g_qeglobals.d_hwndEntity, SW_NORMAL);
+ }
+ else
+ {
+ ::ShowWindow(g_qeglobals.d_hwndEntity, SW_NORMAL);
+ SetInspectorMode(W_GROUP);
+ }
+ }
+}
+
+void CMainFrame::OnDropGroupAddtoWorld()
+{
+ Select_AddToGroup("World");
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnDropGroupName()
+{
+ CNameDlg dlg("Name Selection", this);
+ if (dlg.DoModal() == IDOK)
+ {
+ Select_Name(dlg.m_strName);
+ Sys_UpdateWindows (W_ALL);
+ }
+}
+
+void CMainFrame::OnDropGroupNewgroup()
+{
+
+}
+
+void CMainFrame::OnDropGroupRemove()
+{
+ Select_AddToGroup("World");
+ Sys_UpdateWindows (W_ALL);
+}
+
+void CMainFrame::OnSplinesMode()
+{
+ g_qeglobals.d_select_mode = sel_addpoint;
+ g_qeglobals.selectObject = g_splineList->getPositionObj();
+ g_splineList->clear();
+ g_splineList->startEdit(true);
+ showCameraInspector();
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CMainFrame::OnSplinesLoad()
+{
+ g_splineList->load("maps/test.camera");
+ g_splineList->buildCamera();
+}
+
+void CMainFrame::OnSplinesSave()
+{
+ g_splineList->save("maps/test.camera");
+}
+
+void CMainFrame::OnSplinesEdit()
+{
+ showCameraInspector();
+ Sys_UpdateWindows(W_ALL);
+}
+
+extern void testCamSpeed();
+void CMainFrame::OnSplineTest()
+{
+ long start = GetTickCount();
+ g_splineList->startCamera(start);
+ float cycle = g_splineList->getTotalTime();
+ long msecs = cycle * 1000;
+ long current = start;
+ vec3_t lookat;
+ VectorClear(lookat);
+ vec3_t dir;
+ while (current < start + msecs) {
+ float fov;
+ g_splineList->getCameraInfo(current, &g_pParentWnd->GetCamera()->Camera().origin[0], &dir[0], &fov);
+ g_pParentWnd->GetCamera()->Camera().angles[1] = atan2 (dir[1], dir[0])*180/3.14159;
+ g_pParentWnd->GetCamera()->Camera().angles[0] = asin (dir[2])*180/3.14159;
+ g_pParentWnd->UpdateWindows(W_XY | W_CAMERA);
+ current = GetTickCount();
+ }
+ g_splineList->setRunning(false);
+}
+
+void CMainFrame::OnSplinesTarget()
+{
+}
+
+void CMainFrame::OnSplinesTargetPoints()
+{
+}
+
+void CMainFrame::OnSplinesCameraPoints()
+{
+}
+
+void CMainFrame::OnPopupNewcameraInterpolated()
+{
+ g_qeglobals.d_select_mode = sel_addpoint;
+ g_qeglobals.selectObject = g_splineList->startNewCamera(idCameraPosition::INTERPOLATED);
+ OnSplinesEdit();
+}
+
+void CMainFrame::OnPopupNewcameraSpline()
+{
+ g_qeglobals.d_select_mode = sel_addpoint;
+ g_qeglobals.selectObject = g_splineList->startNewCamera(idCameraPosition::SPLINE);
+ OnSplinesEdit();
+}
+
+void CMainFrame::OnPopupNewcameraFixed()
+{
+ g_qeglobals.d_select_mode = sel_addpoint;
+ g_qeglobals.selectObject = g_splineList->startNewCamera(idCameraPosition::FIXED);
+ OnSplinesEdit();
+}
diff --git a/q3radiant/MainFrm.h b/q3radiant/MainFrm.h
new file mode 100755
index 0000000..35e46a8
--- /dev/null
+++ b/q3radiant/MainFrm.h
@@ -0,0 +1,504 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// MainFrm.h : interface of the CMainFrame class
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#if !defined(AFX_MAINFRM_H__330BBF0A_731C_11D1_B539_00AA00A410FC__INCLUDED_)
+#define AFX_MAINFRM_H__330BBF0A_731C_11D1_B539_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+
+#include "LstToolBar.h"
+#include "XYWnd.h"
+#include "TexWnd.h"
+#include "ZWnd.h"
+#include "CamWnd.h"
+#include "RADEditWnd.h"
+#include "TextureBar.h"
+#include "PlugInManager.h"
+#include "PlugIn.h"
+#include "groupdlg.h"
+
+
+const int RAD_SHIFT = 0x01;
+const int RAD_ALT = 0x02;
+const int RAD_CONTROL = 0x04;
+const int RAD_PRESS = 0x08;
+
+struct SCommandInfo
+{
+ char* m_strCommand;
+ unsigned int m_nKey;
+ unsigned int m_nModifiers;
+ unsigned int m_nCommand;
+};
+
+struct SKeyInfo
+{
+ char* m_strName;
+ unsigned int m_nVKKey;
+};
+
+
+
+
+class CMainFrame : public CFrameWnd
+{
+ DECLARE_DYNAMIC(CMainFrame)
+public:
+ CMainFrame();
+ void HandleKey(UINT nChar, UINT nRepCnt, UINT nFlags, bool bDown = true)
+ {
+ if (bDown)
+ OnKeyDown(nChar, nRepCnt, nFlags);
+ else
+ OnKeyUp(nChar, nRepCnt, nFlags);
+ };
+
+// Attributes
+public:
+
+// Operations
+public:
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CMainFrame)
+ public:
+ virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
+ virtual BOOL PreTranslateMessage(MSG* pMsg);
+ protected:
+ virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam);
+ virtual LRESULT DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam);
+ virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam);
+ virtual BOOL OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext);
+ //}}AFX_VIRTUAL
+
+// Implementation
+public:
+ void UpdatePatchToolbarButtons();
+ void NudgeSelection(int nDirection, int nAmount);
+ void UpdateTextureBar();
+ void SetButtonMenuStates();
+ void SetTexValStatus();
+ void SetGridStatus();
+ void RoutineProcessing();
+ CXYWnd* ActiveXY();
+ void UpdateWindows(int nBits);
+ void SetStatusText(int nPane, const char* pText);
+ void UpdateStatusText();
+ void SetWindowStyle(int nStyle);
+ virtual ~CMainFrame();
+ CXYWnd* GetXYWnd() {return m_pXYWnd;};
+ CXYWnd* GetXZWnd() {return m_pXZWnd;};
+ CXYWnd* GetYZWnd() {return m_pYZWnd;};
+ CCamWnd* GetCamera() {return m_pCamWnd;};
+ CTexWnd* GetTexWnd() {return m_pTexWnd;};
+ void SetActiveXY(CXYWnd* p)
+ {
+ if (m_pActiveXY)
+ m_pActiveXY->SetActive(false);
+
+ m_pActiveXY = p;
+
+ if (m_pActiveXY)
+ m_pActiveXY->SetActive(true);
+
+ };
+ int CurrentStyle() { return m_nCurrentStyle; };
+#ifdef _DEBUG
+ virtual void AssertValid() const;
+ virtual void Dump(CDumpContext& dc) const;
+#endif
+
+protected: // control bar embedded members
+ CStatusBar m_wndStatusBar;
+ CLstToolBar m_wndToolBar;
+ CLstToolBar m_wndScaleBar;
+ CDialogBar m_wndHelpBar;
+ CTextureBar m_wndTextureBar;
+ CSplitterWnd m_wndSplit;
+ CSplitterWnd m_wndSplit2;
+ CSplitterWnd m_wndSplit3;
+ CXYWnd* m_pXYWnd;
+ CXYWnd* m_pYZWnd;
+ CXYWnd* m_pXZWnd;
+ CCamWnd* m_pCamWnd;
+ CTexWnd* m_pTexWnd;
+ CZWnd* m_pZWnd;
+ CRADEditWnd* m_pEditWnd;
+ int m_nCurrentStyle;
+ CString m_strStatus[15];
+ CXYWnd* m_pActiveXY;
+ bool m_bCamPreview;
+ CPlugInManager m_PlugInMgr;
+ int m_nNextPlugInID;
+
+// Generated message map functions
+protected:
+ bool m_bDoLoop;
+ bool m_bSplittersOK;
+ void CreateQEChildren();
+ void LoadCommandMap();
+ void ShowMenuItemKeyBindings(CMenu *pMenu);
+ void SetEntityCheck();
+ afx_msg LRESULT OnBSPStatus(UINT wParam, long lParam);
+ afx_msg LRESULT OnBSPDone(UINT wParam, long lParam);
+public:
+ void Nudge(int nDim, float fNudge);
+
+ CPlugInManager &GetPlugInMgr() {return m_PlugInMgr;};
+ void AddPlugInMenuItem(CPlugIn* pPlugIn);
+ void CleanPlugInMenu();
+
+ // these are public so i can easily reflect messages
+ // from child windows..
+ //{{AFX_MSG(CMainFrame)
+ afx_msg void OnParentNotify(UINT message, LPARAM lParam);
+ afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
+ afx_msg void OnTimer(UINT nIDEvent);
+ afx_msg void OnDestroy();
+ afx_msg void OnClose();
+ afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
+ afx_msg void OnSize(UINT nType, int cx, int cy);
+ afx_msg void ToggleCamera();
+ afx_msg void OnFileClose();
+ afx_msg void OnFileExit();
+ afx_msg void OnFileLoadproject();
+ afx_msg void OnFileNew();
+ afx_msg void OnFileOpen();
+ afx_msg void OnFilePointfile();
+ afx_msg void OnFilePrint();
+ afx_msg void OnFilePrintPreview();
+ afx_msg void OnFileSave();
+ afx_msg void OnFileSaveas();
+ afx_msg void OnView100();
+ afx_msg void OnViewCenter();
+ afx_msg void OnViewConsole();
+ afx_msg void OnViewDownfloor();
+ afx_msg void OnViewEntity();
+ afx_msg void OnViewFront();
+ afx_msg void OnViewShowblocks();
+ afx_msg void OnViewShowclip();
+ afx_msg void OnViewShowcoordinates();
+ afx_msg void OnViewShowdetail();
+ afx_msg void OnViewShowent();
+ afx_msg void OnViewShowlights();
+ afx_msg void OnViewShownames();
+ afx_msg void OnViewShowpath();
+ afx_msg void OnViewShowwater();
+ afx_msg void OnViewShowworld();
+ afx_msg void OnViewTexture();
+ afx_msg void OnViewUpfloor();
+ afx_msg void OnViewXy();
+ afx_msg void OnViewZ100();
+ afx_msg void OnViewZoomin();
+ afx_msg void OnViewZoomout();
+ afx_msg void OnViewZzoomin();
+ afx_msg void OnViewZzoomout();
+ afx_msg void OnViewSide();
+ afx_msg void OnTexturesShowinuse();
+ afx_msg void OnTexturesInspector();
+ afx_msg void OnMiscBenchmark();
+ afx_msg void OnMiscFindbrush();
+ afx_msg void OnMiscGamma();
+ afx_msg void OnMiscNextleakspot();
+ afx_msg void OnMiscPreviousleakspot();
+ afx_msg void OnMiscPrintxy();
+ afx_msg void OnMiscSelectentitycolor();
+ afx_msg void OnTexturebk();
+ afx_msg void OnColorsMajor();
+ afx_msg void OnColorsMinor();
+ afx_msg void OnColorsXybk();
+ afx_msg void OnBrush3sided();
+ afx_msg void OnBrush4sided();
+ afx_msg void OnBrush5sided();
+ afx_msg void OnBrush6sided();
+ afx_msg void OnBrush7sided();
+ afx_msg void OnBrush8sided();
+ afx_msg void OnBrush9sided();
+ afx_msg void OnBrushArbitrarysided();
+ afx_msg void OnBrushFlipx();
+ afx_msg void OnBrushFlipy();
+ afx_msg void OnBrushFlipz();
+ afx_msg void OnBrushRotatex();
+ afx_msg void OnBrushRotatey();
+ afx_msg void OnBrushRotatez();
+ afx_msg void OnRegionOff();
+ afx_msg void OnRegionSetbrush();
+ afx_msg void OnRegionSetselection();
+ afx_msg void OnRegionSettallbrush();
+ afx_msg void OnRegionSetxy();
+ afx_msg void OnSelectionArbitraryrotation();
+ afx_msg void OnSelectionClone();
+ afx_msg void OnSelectionConnect();
+ afx_msg void OnSelectionCsgsubtract();
+ afx_msg void OnSelectionCsgmerge();
+ afx_msg void OnSelectionNoOutline();
+ afx_msg void OnSelectionDelete();
+ afx_msg void OnSelectionDeselect();
+ afx_msg void OnSelectionDragedges();
+ afx_msg void OnSelectionDragvertecies();
+ afx_msg void OnRaiseLowerTerrain();
+ afx_msg void OnSelectionMakeDetail();
+ afx_msg void OnSelectionMakeStructural();
+ afx_msg void OnSelectionMakehollow();
+ afx_msg void OnSelectionSelectcompletetall();
+ afx_msg void OnSelectionSelectinside();
+ afx_msg void OnSelectionSelectpartialtall();
+ afx_msg void OnSelectionSelecttouching();
+ afx_msg void OnSelectionUngroupentity();
+ afx_msg void OnTexturesPopup();
+ afx_msg void OnSplinesPopup();
+ afx_msg void OnPopupSelection();
+ afx_msg void OnViewChange();
+ afx_msg void OnViewCameraupdate();
+ afx_msg void OnUpdateViewCameraupdate(CCmdUI* pCmdUI);
+ afx_msg void OnSizing(UINT fwSide, LPRECT pRect);
+ afx_msg void OnHelpAbout();
+ afx_msg void OnViewClipper();
+ afx_msg void OnCameraAngledown();
+ afx_msg void OnCameraAngleup();
+ afx_msg void OnCameraBack();
+ afx_msg void OnCameraDown();
+ afx_msg void OnCameraForward();
+ afx_msg void OnCameraLeft();
+ afx_msg void OnCameraRight();
+ afx_msg void OnCameraStrafeleft();
+ afx_msg void OnCameraStraferight();
+ afx_msg void OnCameraUp();
+ afx_msg void OnGridToggle();
+ afx_msg void OnPrefs();
+ afx_msg void OnTogglecamera();
+ afx_msg void OnToggleconsole();
+ afx_msg void OnToggleview();
+ afx_msg void OnTogglez();
+ afx_msg void OnToggleLock();
+ afx_msg void OnEditMapinfo();
+ afx_msg void OnEditEntityinfo();
+ afx_msg void OnBrushScripts();
+ afx_msg void OnViewNextview();
+ afx_msg void OnHelpCommandlist();
+ afx_msg void OnFileNewproject();
+ afx_msg void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags);
+ afx_msg void OnFlipClip();
+ afx_msg void OnClipSelected();
+ afx_msg void OnSplitSelected();
+ afx_msg void OnToggleviewXz();
+ afx_msg void OnToggleviewYz();
+ afx_msg void OnColorsBrush();
+ afx_msg void OnColorsClipper();
+ afx_msg void OnColorsGridtext();
+ afx_msg void OnColorsSelectedbrush();
+ afx_msg void OnColorsGridblock();
+ afx_msg void OnColorsViewname();
+ afx_msg void OnColorSetoriginal();
+ afx_msg void OnColorSetqer();
+ afx_msg void OnColorSetblack();
+ afx_msg void OnSnaptogrid();
+ afx_msg void OnSelectScale();
+ afx_msg void OnSelectMouserotate();
+ afx_msg void OnEditCopybrush();
+ afx_msg void OnEditPastebrush();
+ afx_msg void OnEditUndo();
+ afx_msg void OnEditRedo();
+ afx_msg void OnUpdateEditUndo(CCmdUI* pCmdUI);
+ afx_msg void OnUpdateEditRedo(CCmdUI* pCmdUI);
+ afx_msg void OnSelectionInvert();
+ afx_msg void OnSelectionTextureDec();
+ afx_msg void OnSelectionTextureFit();
+ afx_msg void OnSelectionTextureInc();
+ afx_msg void OnSelectionTextureRotateclock();
+ afx_msg void OnSelectionTextureRotatecounter();
+ afx_msg void OnSelectionTextureScaledown();
+ afx_msg void OnSelectionTextureScaleup();
+ afx_msg void OnSelectionTextureShiftdown();
+ afx_msg void OnSelectionTextureShiftleft();
+ afx_msg void OnSelectionTextureShiftright();
+ afx_msg void OnSelectionTextureShiftup();
+ afx_msg void OnGridNext();
+ afx_msg void OnGridPrev();
+ afx_msg void OnSelectionTextureScaleLeft();
+ afx_msg void OnSelectionTextureScaleRight();
+ afx_msg void OnTextureReplaceall();
+ afx_msg void OnScalelockx();
+ afx_msg void OnScalelocky();
+ afx_msg void OnScalelockz();
+ afx_msg void OnSelectMousescale();
+ afx_msg void OnViewCubicclipping();
+ afx_msg void OnFileImport();
+ afx_msg void OnFileProjectsettings();
+ afx_msg void OnUpdateFileImport(CCmdUI* pCmdUI);
+ afx_msg void OnViewCubein();
+ afx_msg void OnViewCubeout();
+ afx_msg void OnFileSaveregion();
+ afx_msg void OnUpdateFileSaveregion(CCmdUI* pCmdUI);
+ afx_msg void OnSelectionMovedown();
+ afx_msg void OnSelectionMoveup();
+ afx_msg void OnToolbarMain();
+ afx_msg void OnToolbarTexture();
+ afx_msg void OnSelectionPrint();
+ afx_msg void OnSelectionTogglesizepaint();
+ afx_msg void OnBrushMakecone();
+ afx_msg void OnTexturesLoad();
+ afx_msg void OnToggleRotatelock();
+ afx_msg void OnCurveBevel();
+ afx_msg void OnCurveCylinder();
+ afx_msg void OnCurveEighthsphere();
+ afx_msg void OnCurveEndcap();
+ afx_msg void OnCurveHemisphere();
+ afx_msg void OnCurveInvertcurve();
+ afx_msg void OnCurveQuarter();
+ afx_msg void OnCurveSphere();
+ afx_msg void OnFileImportmap();
+ afx_msg void OnFileExportmap();
+ afx_msg void OnEditLoadprefab();
+ afx_msg void OnViewShowcurves();
+ afx_msg void OnSelectionSelectNudgedown();
+ afx_msg void OnSelectionSelectNudgeleft();
+ afx_msg void OnSelectionSelectNudgeright();
+ afx_msg void OnSelectionSelectNudgeup();
+ afx_msg void OnSysKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
+ afx_msg void OnTexturesLoadlist();
+ afx_msg void OnDontselectcurve();
+ afx_msg void OnConvertcurves();
+ afx_msg void OnDynamicLighting();
+ afx_msg void OnCurveSimplepatchmesh();
+ afx_msg void OnPatchToggleBox();
+ afx_msg void OnPatchWireframe();
+ afx_msg void OnCurvePatchcone();
+ afx_msg void OnCurvePatchtube();
+ afx_msg void OnPatchWeld();
+ afx_msg void OnCurvePatchbevel();
+ afx_msg void OnCurvePatchendcap();
+ afx_msg void OnCurvePatchinvertedbevel();
+ afx_msg void OnCurvePatchinvertedendcap();
+ afx_msg void OnPatchDrilldown();
+ afx_msg void OnCurveInsertcolumn();
+ afx_msg void OnCurveInsertrow();
+ afx_msg void OnCurveDeletecolumn();
+ afx_msg void OnCurveDeleterow();
+ afx_msg void OnCurveInsertAddcolumn();
+ afx_msg void OnCurveInsertAddrow();
+ afx_msg void OnCurveInsertInsertcolumn();
+ afx_msg void OnCurveInsertInsertrow();
+ afx_msg void OnCurveNegative();
+ afx_msg void OnCurveNegativeTextureX();
+ afx_msg void OnCurveNegativeTextureY();
+ afx_msg void OnCurveDeleteFirstcolumn();
+ afx_msg void OnCurveDeleteFirstrow();
+ afx_msg void OnCurveDeleteLastcolumn();
+ afx_msg void OnCurveDeleteLastrow();
+ afx_msg void OnPatchBend();
+ afx_msg void OnPatchInsdel();
+ afx_msg void OnPatchEnter();
+ afx_msg void OnPatchTab();
+ afx_msg void OnCurvePatchdensetube();
+ afx_msg void OnCurvePatchverydensetube();
+ afx_msg void OnCurveCap();
+ afx_msg void OnCurveCapInvertedbevel();
+ afx_msg void OnCurveCapInvertedendcap();
+ afx_msg void OnCurveRedisperseCols();
+ afx_msg void OnCurveRedisperseRows();
+ afx_msg void OnPatchNaturalize();
+ afx_msg void OnSnapToGrid();
+ afx_msg void OnCurvePatchsquare();
+ afx_msg void OnTerrainCreateFromBrush();
+ afx_msg void OnTexturesTexturewindowscale10();
+ afx_msg void OnTexturesTexturewindowscale100();
+ afx_msg void OnTexturesTexturewindowscale200();
+ afx_msg void OnTexturesTexturewindowscale25();
+ afx_msg void OnTexturesTexturewindowscale50();
+ afx_msg void OnTexturesFlush();
+ afx_msg void OnCurveOverlayClear();
+ afx_msg void OnCurveOverlaySet();
+ afx_msg void OnCurveThicken();
+ afx_msg void OnCurveCyclecap();
+ afx_msg void OnCurveMatrixTranspose();
+ afx_msg void OnTexturesReloadshaders();
+ afx_msg void OnShowEntities();
+ afx_msg void OnViewEntitiesasBoundingbox();
+ afx_msg void OnViewEntitiesasSelectedskinned();
+ afx_msg void OnViewEntitiesasSelectedwireframe();
+ afx_msg void OnViewEntitiesasSkinned();
+ afx_msg void OnViewEntitiesasSkinnedandboxed();
+ afx_msg void OnViewEntitiesasWireframe();
+ afx_msg void OnPluginsRefresh();
+ afx_msg void OnViewShowhint();
+ afx_msg void OnUpdateTexturesShowinuse(CCmdUI* pCmdUI);
+ afx_msg void OnTexturesShowall();
+ afx_msg void OnPatchInspector();
+ afx_msg void OnViewOpengllighting();
+ afx_msg void OnSelectAll();
+ afx_msg void OnViewShowcaulk();
+ afx_msg void OnCurveFreeze();
+ afx_msg void OnCurveUnFreeze();
+ afx_msg void OnCurveUnFreezeAll();
+ afx_msg void OnSelectReselect();
+ afx_msg void OnViewShowangles();
+ afx_msg void OnEditSaveprefab();
+ afx_msg void OnCurveMoreendcapsbevelsSquarebevel();
+ afx_msg void OnCurveMoreendcapsbevelsSquareendcap();
+ afx_msg void OnBrushPrimitivesSphere();
+ afx_msg void OnViewCrosshair();
+ afx_msg void OnViewHideshowHideselected();
+ afx_msg void OnViewHideshowShowhidden();
+ afx_msg void OnTexturesShadersShow();
+ afx_msg void OnTexturesFlushUnused();
+ afx_msg void OnViewGroups();
+ afx_msg void OnDropGroupAddtoWorld();
+ afx_msg void OnDropGroupName();
+ afx_msg void OnDropGroupNewgroup();
+ afx_msg void OnDropGroupRemove();
+ afx_msg void OnSplinesMode();
+ afx_msg void OnSplinesLoad();
+ afx_msg void OnSplinesSave();
+ afx_msg void OnSplinesEdit();
+ afx_msg void OnSplineTest();
+ afx_msg void OnSplinesTarget();
+ afx_msg void OnSplinesTargetPoints();
+ afx_msg void OnSplinesCameraPoints();
+ afx_msg void OnPopupNewcameraInterpolated();
+ afx_msg void OnPopupNewcameraSpline();
+ afx_msg void OnPopupNewcameraFixed();
+ //}}AFX_MSG
+ afx_msg void OnMru(unsigned int nID);
+ afx_msg void OnViewNearest(unsigned int nID);
+ afx_msg void OnTextureWad(unsigned int nID);
+ afx_msg void OnBspCommand(unsigned int nID);
+ afx_msg void OnGrid1(unsigned int nID);
+ afx_msg LRESULT OnDisplayChange(WPARAM wp, LPARAM lp);
+ void CheckTextureScale(int id);
+ afx_msg void OnPlugIn(unsigned int nID);
+
+ DECLARE_MESSAGE_MAP()
+};
+
+/////////////////////////////////////////////////////////////////////////////
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_MAINFRM_H__330BBF0A_731C_11D1_B539_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/MapInfo.cpp b/q3radiant/MapInfo.cpp
new file mode 100755
index 0000000..8373b7b
--- /dev/null
+++ b/q3radiant/MapInfo.cpp
@@ -0,0 +1,114 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// MapInfo.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "MapInfo.h"
+#include "qe3.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CMapInfo dialog
+
+
+CMapInfo::CMapInfo(CWnd* pParent /*=NULL*/)
+ : CDialog(CMapInfo::IDD, pParent)
+{
+ //{{AFX_DATA_INIT(CMapInfo)
+ m_nNet = 0;
+ m_nTotalBrushes = 0;
+ m_nTotalEntities = 0;
+ //}}AFX_DATA_INIT
+}
+
+
+void CMapInfo::DoDataExchange(CDataExchange* pDX)
+{
+ CDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CMapInfo)
+ DDX_Control(pDX, IDC_LIST_ENTITIES, m_lstEntity);
+ DDX_Text(pDX, IDC_EDIT_NET, m_nNet);
+ DDX_Text(pDX, IDC_EDIT_TOTALBRUSHES, m_nTotalBrushes);
+ DDX_Text(pDX, IDC_EDIT_TOTALENTITIES, m_nTotalEntities);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CMapInfo, CDialog)
+ //{{AFX_MSG_MAP(CMapInfo)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CMapInfo message handlers
+
+BOOL CMapInfo::OnInitDialog()
+{
+ CDialog::OnInitDialog();
+
+ m_nTotalBrushes = 0;
+ m_nTotalEntities = 0;
+ m_nNet = 0;
+ for (brush_t* pBrush=active_brushes.next ; pBrush != &active_brushes ; pBrush=pBrush->next)
+ {
+ m_nTotalBrushes++;
+ if (pBrush->owner == world_entity)
+ m_nNet++;
+ }
+
+
+ CMapStringToPtr mapEntity;
+
+ int nValue = 0;
+ for (entity_t* pEntity=entities.next ; pEntity != &entities ; pEntity=pEntity->next)
+ {
+ m_nTotalEntities++;
+ nValue = 0;
+ mapEntity.Lookup(pEntity->eclass->name, reinterpret_cast<void*&>(nValue));
+ nValue++ ;
+ mapEntity.SetAt(pEntity->eclass->name, reinterpret_cast<void*>(nValue));
+ }
+
+ m_lstEntity.ResetContent();
+ m_lstEntity.SetTabStops(96);
+ CString strKey;
+ POSITION pos = mapEntity.GetStartPosition();
+ while (pos)
+ {
+ mapEntity.GetNextAssoc(pos, strKey, reinterpret_cast<void*&>(nValue));
+ CString strList;
+ strList.Format("%s\t%i", strKey, nValue);
+ m_lstEntity.AddString(strList);
+ }
+
+ UpdateData(FALSE);
+
+ return TRUE; // return TRUE unless you set the focus to a control
+ // EXCEPTION: OCX Property Pages should return FALSE
+}
diff --git a/q3radiant/MapInfo.h b/q3radiant/MapInfo.h
new file mode 100755
index 0000000..28db33a
--- /dev/null
+++ b/q3radiant/MapInfo.h
@@ -0,0 +1,70 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_MAPINFO_H__C241B9A2_819F_11D1_B548_00AA00A410FC__INCLUDED_)
+#define AFX_MAPINFO_H__C241B9A2_819F_11D1_B548_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// MapInfo.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CMapInfo dialog
+
+class CMapInfo : public CDialog
+{
+// Construction
+public:
+ CMapInfo(CWnd* pParent = NULL); // standard constructor
+
+// Dialog Data
+ //{{AFX_DATA(CMapInfo)
+ enum { IDD = IDD_DLG_MAPINFO };
+ CListBox m_lstEntity;
+ int m_nNet;
+ int m_nTotalBrushes;
+ int m_nTotalEntities;
+ //}}AFX_DATA
+
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CMapInfo)
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+
+ // Generated message map functions
+ //{{AFX_MSG(CMapInfo)
+ virtual BOOL OnInitDialog();
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_MAPINFO_H__C241B9A2_819F_11D1_B548_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/Messaging.cpp b/q3radiant/Messaging.cpp
new file mode 100755
index 0000000..e744b84
--- /dev/null
+++ b/q3radiant/Messaging.cpp
@@ -0,0 +1,137 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//-----------------------------------------------------------------------------
+//
+// $LogFile$
+// $Revision: 1.1.2.1 $
+// $Author: ttimo $
+// $Date: 2000/02/04 22:59:34 $
+// $Log: Messaging.cpp,v $
+// Revision 1.1.2.1 2000/02/04 22:59:34 ttimo
+// messaging API preview
+//
+//
+// DESCRIPTION:
+// implementation of IMessaging specific interface
+//
+
+#include "stdafx.h"
+
+CPtrArray l_Listeners[RADIANT_MSGCOUNT];
+CPtrArray l_WindowListeners;
+CXYWndWrapper l_XYWndWrapper;
+
+void WINAPI QERApp_HookWindow(IWindowListener* pListen)
+{
+ l_WindowListeners.Add( pListen );
+ pListen->IncRef();
+}
+
+void WINAPI QERApp_UnHookWindow(IWindowListener* pListen)
+{
+ for ( int i = 0; i < l_WindowListeners.GetSize(); i++ )
+ {
+ if (l_WindowListeners.GetAt(i) == pListen)
+ {
+ l_WindowListeners.RemoveAt(i);
+ pListen->DecRef();
+ return;
+ }
+ }
+#ifdef _DEBUG
+ Sys_Printf("WARNING: IWindowListener not found in QERApp_UnHookWindow\n");
+#endif
+}
+
+void DispatchOnMouseMove(UINT nFlags, int x, int y)
+{
+ for( int i = 0; i < l_WindowListeners.GetSize(); i++ )
+ static_cast<IWindowListener*>(l_WindowListeners.GetAt(i))->OnMouseMove( nFlags, x, y );
+}
+
+bool DispatchOnLButtonDown(UINT nFlags, int x, int y)
+{
+ for( int i = 0; i < l_WindowListeners.GetSize(); i++ )
+ if (static_cast<IWindowListener*>(l_WindowListeners.GetAt(i))->OnLButtonDown( nFlags, x, y ))
+ return true;
+ return false;
+}
+
+bool DispatchOnLButtonUp(UINT nFlags, int x, int y)
+{
+ for( int i = 0; i < l_WindowListeners.GetSize(); i++ )
+ if (static_cast<IWindowListener*>(l_WindowListeners.GetAt(i))->OnLButtonUp( nFlags, x, y ))
+ return true;
+ return false;
+}
+
+void WINAPI QERApp_HookListener(IListener* pListen, int Msg)
+{
+#ifdef _DEBUG
+ if (Msg >= RADIANT_MSGCOUNT)
+ {
+ Sys_Printf("ERROR: bad index in QERApp_HookListener\n");
+ return;
+ }
+#endif
+ l_Listeners[Msg].Add( pListen );
+ pListen->IncRef();
+}
+
+int WINAPI QERApp_UnHookListener(IListener* pListen)
+{
+ int count = 0;
+ for( int i = 0; i<RADIANT_MSGCOUNT; i++ )
+ for( int j = 0; j<l_Listeners[i].GetSize(); j++ )
+ if (l_Listeners[i].GetAt(j) == pListen)
+ {
+ l_Listeners[i].RemoveAt(j);
+ pListen->DecRef();
+ count++;
+ }
+ return count;
+}
+
+void DispatchRadiantMsg( int Msg )
+{
+#ifdef _DEBUG
+ if (Msg >= RADIANT_MSGCOUNT)
+ {
+ Sys_Printf("ERROR: bad index in DispatchRadiantMsg\n");
+ return;
+ }
+#endif
+ for(int i = 0; i<l_Listeners[Msg].GetSize(); i++)
+ static_cast<IListener *>(l_Listeners[Msg].GetAt(i))->DispatchRadiantMsg(Msg);
+}
+
+void CXYWndWrapper::SnapToGrid( int x1, int y1, vec3_t pt )
+{
+ CRect rctZ;
+ g_pParentWnd->ActiveXY()->GetClientRect( rctZ );
+ g_pParentWnd->ActiveXY()->SnapToPoint( x1, rctZ.Height() - 1 - y1, pt );
+}
+
+IXYWndWrapper* WINAPI QERApp_GetXYWndWrapper()
+{
+ return &l_XYWndWrapper;
+}
diff --git a/q3radiant/Messaging.h b/q3radiant/Messaging.h
new file mode 100755
index 0000000..dfea880
--- /dev/null
+++ b/q3radiant/Messaging.h
@@ -0,0 +1,46 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//-----------------------------------------------------------------------------
+//
+// $LogFile$
+// $Revision: 1.1.2.1 $
+// $Author: ttimo $
+// $Date: 2000/02/04 22:59:34 $
+// $Log: Messaging.h,v $
+// Revision 1.1.2.1 2000/02/04 22:59:34 ttimo
+// messaging API preview
+//
+//
+// DESCRIPTION:
+// headers for internal classes used in Messaging.cpp
+//
+
+#ifndef __MESSAGING_H_
+#define __MESSAGING_H_
+
+class CXYWndWrapper : public IXYWndWrapper
+{
+public:
+ void SnapToGrid( int x1, int y1, vec3_t pt );
+};
+
+#endif \ No newline at end of file
diff --git a/q3radiant/NameDlg.cpp b/q3radiant/NameDlg.cpp
new file mode 100755
index 0000000..14027c5
--- /dev/null
+++ b/q3radiant/NameDlg.cpp
@@ -0,0 +1,79 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// NameDlg.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "NameDlg.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CNameDlg dialog
+
+
+CNameDlg::CNameDlg(const char *pName, CWnd* pParent /*=NULL*/)
+ : CDialog(CNameDlg::IDD, pParent)
+{
+ //{{AFX_DATA_INIT(CNameDlg)
+ m_strName = _T("");
+ //}}AFX_DATA_INIT
+ m_strCaption = pName;
+}
+
+
+void CNameDlg::DoDataExchange(CDataExchange* pDX)
+{
+ CDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CNameDlg)
+ DDX_Text(pDX, IDC_EDIT_NAME, m_strName);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CNameDlg, CDialog)
+ //{{AFX_MSG_MAP(CNameDlg)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CNameDlg message handlers
+
+void CNameDlg::OnOK()
+{
+ CDialog::OnOK();
+}
+
+BOOL CNameDlg::OnInitDialog()
+{
+ CDialog::OnInitDialog();
+
+ SetWindowText(m_strCaption);
+
+ return TRUE; // return TRUE unless you set the focus to a control
+ // EXCEPTION: OCX Property Pages should return FALSE
+}
diff --git a/q3radiant/NameDlg.h b/q3radiant/NameDlg.h
new file mode 100755
index 0000000..6dd75ba
--- /dev/null
+++ b/q3radiant/NameDlg.h
@@ -0,0 +1,69 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_NAMEDLG_H__624F3290_976A_48A9_AE89_50CD1E6E2F9A__INCLUDED_)
+#define AFX_NAMEDLG_H__624F3290_976A_48A9_AE89_50CD1E6E2F9A__INCLUDED_
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+// NameDlg.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CNameDlg dialog
+
+class CNameDlg : public CDialog
+{
+ CString m_strCaption;
+// Construction
+public:
+ CNameDlg(const char *pName, CWnd* pParent = NULL); // standard constructor
+
+// Dialog Data
+ //{{AFX_DATA(CNameDlg)
+ enum { IDD = IDD_NEWNAME };
+ CString m_strName;
+ //}}AFX_DATA
+
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CNameDlg)
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+
+ // Generated message map functions
+ //{{AFX_MSG(CNameDlg)
+ virtual void OnOK();
+ virtual BOOL OnInitDialog();
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_NAMEDLG_H__624F3290_976A_48A9_AE89_50CD1E6E2F9A__INCLUDED_)
diff --git a/q3radiant/NewProjDlg.cpp b/q3radiant/NewProjDlg.cpp
new file mode 100755
index 0000000..4a9c1b5
--- /dev/null
+++ b/q3radiant/NewProjDlg.cpp
@@ -0,0 +1,64 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// NewProjDlg.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "NewProjDlg.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CNewProjDlg dialog
+
+
+CNewProjDlg::CNewProjDlg(CWnd* pParent /*=NULL*/)
+ : CDialog(CNewProjDlg::IDD, pParent)
+{
+ //{{AFX_DATA_INIT(CNewProjDlg)
+ m_strName = _T("");
+ //}}AFX_DATA_INIT
+}
+
+
+void CNewProjDlg::DoDataExchange(CDataExchange* pDX)
+{
+ CDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CNewProjDlg)
+ DDX_Text(pDX, IDC_EDIT_NAME, m_strName);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CNewProjDlg, CDialog)
+ //{{AFX_MSG_MAP(CNewProjDlg)
+ // NOTE: the ClassWizard will add message map macros here
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CNewProjDlg message handlers
diff --git a/q3radiant/NewProjDlg.h b/q3radiant/NewProjDlg.h
new file mode 100755
index 0000000..6d6c302
--- /dev/null
+++ b/q3radiant/NewProjDlg.h
@@ -0,0 +1,67 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_NEWPROJDLG_H__1E2527A2_8447_11D1_B548_00AA00A410FC__INCLUDED_)
+#define AFX_NEWPROJDLG_H__1E2527A2_8447_11D1_B548_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// NewProjDlg.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CNewProjDlg dialog
+
+class CNewProjDlg : public CDialog
+{
+// Construction
+public:
+ CNewProjDlg(CWnd* pParent = NULL); // standard constructor
+
+// Dialog Data
+ //{{AFX_DATA(CNewProjDlg)
+ enum { IDD = IDD_DLG_NEWPROJECT };
+ CString m_strName;
+ //}}AFX_DATA
+
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CNewProjDlg)
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+
+ // Generated message map functions
+ //{{AFX_MSG(CNewProjDlg)
+ // NOTE: the ClassWizard will add member functions here
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_NEWPROJDLG_H__1E2527A2_8447_11D1_B548_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/PARSE.CPP b/q3radiant/PARSE.CPP
new file mode 100755
index 0000000..6a2b340
--- /dev/null
+++ b/q3radiant/PARSE.CPP
@@ -0,0 +1,148 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "stdafx.h"
+#include "qe3.h"
+
+char token[MAXTOKEN];
+qboolean unget;
+char *script_p;
+int scriptline;
+
+void StartTokenParsing (char *data)
+{
+ scriptline = 1;
+ script_p = data;
+ unget = false;
+}
+
+qboolean WINAPI GetToken (qboolean crossline)
+{
+ char *token_p;
+
+ if (unget) // is a token allready waiting?
+ {
+ unget = false;
+ return true;
+ }
+
+//
+// skip space
+//
+skipspace:
+ while (*script_p <= 32)
+ {
+ if (!*script_p)
+ {
+ if (!crossline)
+ Sys_Printf("Warning: Line %i is incomplete [01]\n",scriptline);
+ return false;
+ }
+ if (*script_p++ == '\n')
+ {
+ if (!crossline)
+ Sys_Printf("Warning: Line %i is incomplete [02]\n",scriptline);
+ scriptline++;
+ }
+ }
+
+ if (script_p[0] == '/' && script_p[1] == '/') // comment field
+ {
+ if (!crossline)
+ Sys_Printf("Warning: Line %i is incomplete [03]\n",scriptline);
+ while (*script_p++ != '\n')
+ if (!*script_p)
+ {
+ if (!crossline)
+ Sys_Printf("Warning: Line %i is incomplete [04]\n",scriptline);
+ return false;
+ }
+ goto skipspace;
+ }
+
+//
+// copy token
+//
+ token_p = token;
+
+ if (*script_p == '"')
+ {
+ script_p++;
+ //if (*script_p == '"') // handle double quotes i suspect they are put in by other editors cccasionally
+ // script_p++;
+ while ( *script_p != '"' )
+ {
+ if (!*script_p)
+ Error ("EOF inside quoted token");
+ *token_p++ = *script_p++;
+ if (token_p == &token[MAXTOKEN])
+ Error ("Token too large on line %i",scriptline);
+ }
+ script_p++;
+ //if (*script_p == '"') // handle double quotes i suspect they are put in by other editors cccasionally
+ // script_p++;
+ }
+ else while ( *script_p > 32 )
+ {
+ *token_p++ = *script_p++;
+ if (token_p == &token[MAXTOKEN])
+ Error ("Token too large on line %i",scriptline);
+ }
+
+ *token_p = 0;
+
+ return true;
+}
+
+void WINAPI UngetToken (void)
+{
+ unget = true;
+}
+
+
+/*
+==============
+TokenAvailable
+
+Returns true if there is another token on the line
+==============
+*/
+qboolean TokenAvailable (void)
+{
+ char *search_p;
+
+ search_p = script_p;
+
+ while ( *search_p <= 32)
+ {
+ if (*search_p == '\n')
+ return false;
+ if (*search_p == 0)
+ return false;
+ search_p++;
+ }
+
+ if (*search_p == ';')
+ return false;
+
+ return true;
+}
+
diff --git a/q3radiant/PARSE.H b/q3radiant/PARSE.H
new file mode 100755
index 0000000..60e1c7b
--- /dev/null
+++ b/q3radiant/PARSE.H
@@ -0,0 +1,34 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// parse.h -- text file parsing routines
+
+#define MAXTOKEN 1024
+
+extern char token[MAXTOKEN];
+extern int scriptline;
+
+// NOTE: added WINAPI call syntax to export these for plugins in _QERScripLibTable
+void StartTokenParsing (char *data);
+qboolean WINAPI GetToken (qboolean crossline);
+void WINAPI UngetToken (void);
+qboolean TokenAvailable (void);
+
diff --git a/q3radiant/PMESH.CPP b/q3radiant/PMESH.CPP
new file mode 100755
index 0000000..3f69152
--- /dev/null
+++ b/q3radiant/PMESH.CPP
@@ -0,0 +1,5136 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+// Preliminary patch stuff
+//
+//
+
+#include "stdafx.h"
+#include "qe3.h"
+#include "DialogInfo.h"
+#include "CapDialog.h"
+
+// externs
+extern void MemFile_fprintf(CMemFile* pMemFile, const char* pText, ...);
+extern face_t *Face_Alloc( void );
+void _Write3DMatrix (FILE *f, int y, int x, int z, float *m);
+void _Write3DMatrix (CMemFile *f, int y, int x, int z, float *m);
+
+
+
+#define CBLOCK_SUBDIVISIONS 6
+
+
+patchMesh_t* MakeNewPatch()
+{
+ patchMesh_t *pm = reinterpret_cast<patchMesh_t*>(qmalloc(sizeof(patchMesh_t)));
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+ pm->pData = static_cast<void *>( g_SurfaceTable.m_pfnPatchAlloc( pm ) );
+ }
+ return pm;
+}
+
+// FIXME: this needs to be dynamic
+//#define MAX_PATCH_MESHES 4096
+//patchMesh_t patchMeshes[MAX_PATCH_MESHES];
+//int numPatchMeshes = 0;
+
+// used for a save spot
+patchMesh_t patchSave;
+
+// Tracks the selected patch for point manipulation/update. FIXME: Need to revert back to a generalized
+// brush approach
+//--int g_nSelectedPatch = -1;
+
+// HACK: for tracking which view generated the click
+// as we dont want to deselect a point on a same point
+// click if it is from a different view
+int g_nPatchClickedView = -1;
+bool g_bSameView = false;
+
+
+// globals
+bool g_bPatchShowBounds = true;
+bool g_bPatchWireFrame = false;
+bool g_bPatchWeld = true;
+bool g_bPatchDrillDown = true;
+bool g_bPatchInsertMode = false;
+bool g_bPatchBendMode = false;
+int g_nPatchBendState = -1;
+int g_nPatchInsertState = -1;
+int g_nBendOriginIndex = 0;
+vec3_t g_vBendOrigin;
+
+bool g_bPatchAxisOnRow = true;
+int g_nPatchAxisIndex = 0;
+bool g_bPatchLowerEdge = true;
+
+// BEND states
+enum
+{
+ BEND_SELECT_ROTATION = 0,
+ BEND_SELECT_ORIGIN,
+ BEND_SELECT_EDGE,
+ BEND_BENDIT,
+ BEND_STATE_COUNT
+};
+
+const char *g_pBendStateMsg[] =
+{
+ "Use TAB to cycle through available bend axis. Press ENTER when the desired one is highlighted.",
+ "Use TAB to cycle through available rotation axis. This will LOCK around that point. You may also use Shift + Middle Click to select an arbitrary point. Press ENTER when the desired one is highlighted",
+ "Use TAB to choose which side to bend. Press ENTER when the desired one is highlighted.",
+ "Use the MOUSE to bend the patch. It uses the same ui rules as Free Rotation. Press ENTER to accept the bend, press ESC to abandon it and exit Bend mode",
+ ""
+};
+
+// INSERT states
+enum
+{
+ INSERT_SELECT_EDGE = 0,
+ INSERT_STATE_COUNT
+};
+
+const char* g_pInsertStateMsg[] =
+{
+ "Use TAB to cycle through available rows/columns for insertion/deletion. Press INS to insert at the highlight, DEL to remove the pair"
+};
+
+
+float *g_InversePoints[1024];
+
+const float fFullBright = 1.0;
+const float fLowerLimit = .50;
+const float fDec = .05;
+void _SetColor(face_t* f, float fColor[3])
+{
+ return;
+ fColor[0] = f->d_color[0];
+ fColor[1] = f->d_color[1];
+ fColor[2] = f->d_color[2];
+ qglColor3fv(fColor);
+}
+
+
+void _DecColor(float fColor[3])
+{
+ return;
+ fColor[0] -= fDec;
+ fColor[1] -= fDec ;
+ fColor[2] -= fDec;
+ for (int i = 0; i < 3; i++)
+ {
+ if (fColor[i] <= fLowerLimit)
+ {
+ fColor[0] = fFullBright;
+ fColor[1] = fFullBright;
+ fColor[2] = fFullBright;
+ break;
+ }
+ }
+ qglColor3fv(fColor);
+}
+
+vec_t __VectorNormalize (vec3_t in, vec3_t out)
+{
+ vec_t length, ilength;
+
+ length = sqrt (in[0]*in[0] + in[1]*in[1] + in[2]*in[2]);
+ if (length == 0)
+ {
+ VectorClear (out);
+ return 0;
+ }
+
+ ilength = 1.0/length;
+ out[0] = in[0]*ilength;
+ out[1] = in[1]*ilength;
+ out[2] = in[2]*ilength;
+
+ return length;
+}
+
+
+void Patch_SetType(patchMesh_t *p, int nType)
+{
+ p->type = (p->type & PATCH_STYLEMASK) | nType;
+}
+
+void Patch_SetStyle(patchMesh_t *p, int nStyle)
+{
+ p->type = (p->type & PATCH_TYPEMASK) | nStyle;
+}
+
+/*
+==================
+Patch_MemorySize
+==================
+*/
+int Patch_MemorySize(patchMesh_t *p)
+{
+ return _msize(p);
+}
+
+
+
+/*
+===============
+InterpolateInteriorPoints
+===============
+*/
+void InterpolateInteriorPoints( patchMesh_t *p )
+{
+ int i, j, k;
+ int next, prev;
+
+ for ( i = 0 ; i < p->width ; i += 2 )
+ {
+
+ next = ( i == p->width - 1 ) ? 1 : ( i + 1 ) % p->width;
+ prev = ( i == 0 ) ? p->width - 2 : i - 1;
+
+#if 0
+ if ( i == 0 )
+ {
+ next = ( i + 1 ) % p->width;
+ prev = p->width - 2; // joined wrap case
+ }
+ else if ( i == p->width - 1 )
+ {
+ next = 1;
+ prev = i - 1;
+ }
+ else
+ {
+ next = ( i + 1 ) % p->width;
+ prev = i - 1;
+ }
+#endif
+
+ for ( j = 0 ; j < p->height ; j++ )
+ {
+ for ( k = 0 ; k < 3 ; k++ )
+ {
+ p->ctrl[i][j].xyz[k] = ( p->ctrl[next][j].xyz[k] + p->ctrl[prev][j].xyz[k] ) * 0.5;
+ }
+ }
+ }
+}
+
+/*
+=================
+MakeMeshNormals
+
+=================
+*/
+int neighbors[8][2] = {
+ {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1}, {-1,-1}, {-1,0}, {-1,1}
+};
+
+void Patch_MeshNormals(patchMesh_t *in )
+{
+ int i, j, k, dist;
+ vec3_t normal;
+ vec3_t sum;
+ int count;
+ vec3_t base;
+ vec3_t delta;
+ int x, y;
+ drawVert_t *dv;
+ vec3_t around[8], temp;
+ qboolean good[8];
+ qboolean wrapWidth, wrapHeight;
+ float len;
+
+ wrapWidth = false;
+ for ( i = 0 ; i < in->height ; i++ )
+ {
+
+ VectorSubtract( in->ctrl[0][i].xyz,
+ in->ctrl[in->width-1][i].xyz, delta );
+ len = VectorLength( delta );
+ if ( len > 1.0 )
+ {
+ break;
+ }
+ }
+ if ( i == in->height )
+ {
+ wrapWidth = true;
+ }
+
+ wrapHeight = false;
+ for ( i = 0 ; i < in->width ; i++ )
+ {
+ VectorSubtract( in->ctrl[i][0].xyz,
+ in->ctrl[i][in->height-1].xyz, delta );
+ len = VectorLength( delta );
+ if ( len > 1.0 )
+ {
+ break;
+ }
+ }
+ if ( i == in->width)
+ {
+ wrapHeight = true;
+ }
+
+
+ for ( i = 0 ; i < in->width ; i++ )
+ {
+ for ( j = 0 ; j < in->height ; j++ )
+ {
+ count = 0;
+ //--dv = reinterpret_cast<drawVert_t*>(in.ctrl[j*in.width+i]);
+ dv = &in->ctrl[i][j];
+ VectorCopy( dv->xyz, base );
+ for ( k = 0 ; k < 8 ; k++ )
+ {
+ VectorClear( around[k] );
+ good[k] = false;
+
+ for ( dist = 1 ; dist <= 3 ; dist++ )
+ {
+ x = i + neighbors[k][0] * dist;
+ y = j + neighbors[k][1] * dist;
+ if ( wrapWidth )
+ {
+ if ( x < 0 )
+ {
+ x = in->width - 1 + x;
+ }
+ else if ( x >= in->width )
+ {
+ x = 1 + x - in->width;
+ }
+ }
+ if ( wrapHeight )
+ {
+ if ( y < 0 )
+ {
+ y = in->height - 1 + y;
+ }
+ else if ( y >= in->height )
+ {
+ y = 1 + y - in->height;
+ }
+ }
+
+ if ( x < 0 || x >= in->width || y < 0 || y >= in->height )
+ {
+ break; // edge of patch
+ }
+ //--VectorSubtract( in.ctrl[y*in.width+x]->xyz, base, temp );
+ VectorSubtract( in->ctrl[x][y].xyz, base, temp );
+ if ( __VectorNormalize( temp, temp ) == 0 )
+ {
+ continue; // degenerate edge, get more dist
+ }
+ else
+ {
+ good[k] = true;
+ VectorCopy( temp, around[k] );
+ break; // good edge
+ }
+ }
+ }
+
+ VectorClear( sum );
+ for ( k = 0 ; k < 8 ; k++ )
+ {
+ if ( !good[k] || !good[(k+1)&7] )
+ {
+ continue; // didn't get two points
+ }
+ CrossProduct( around[(k+1)&7], around[k], normal );
+ if ( __VectorNormalize( normal, normal ) == 0 )
+ {
+ continue;
+ }
+ VectorAdd( normal, sum, sum );
+ count++;
+ }
+ if ( count == 0 )
+ {
+ //printf("bad normal\n");
+ count = 1;
+ //continue;
+ }
+ __VectorNormalize( sum, dv->normal );
+ }
+ }
+}
+
+
+
+
+/*
+==================
+Patch_CalcBounds
+==================
+*/
+void Patch_CalcBounds(patchMesh_t *p, vec3_t& vMin, vec3_t& vMax)
+{
+ vMin[0] = vMin[1] = vMin[2] = 99999;
+ vMax[0] = vMax[1] = vMax[2] = -99999;
+
+ p->bDirty = true;
+ for (int w = 0; w < p->width; w++)
+ {
+ for (int h = 0; h < p->height; h++)
+ {
+ for (int j = 0; j < 3; j++)
+ {
+ float f = p->ctrl[w][h].xyz[j];
+ if (f < vMin[j])
+ vMin[j] = f;
+ if (f > vMax[j])
+ vMax[j] = f;
+ }
+ }
+ }
+}
+
+/*
+==================
+Brush_RebuildBrush
+==================
+*/
+void Brush_RebuildBrush(brush_t *b, vec3_t vMins, vec3_t vMaxs)
+{
+ //
+ // Total hack job
+ // Rebuilds a brush
+ int i, j;
+ face_t *f, *next;
+ vec3_t pts[4][2];
+ texdef_t texdef;
+ // free faces
+
+ for (j = 0; j < 3; j++)
+ {
+ if ((int)vMins[j] == (int)vMaxs[j])
+ {
+ vMins[j] -= 4;
+ vMaxs[j] += 4;
+ }
+ }
+
+
+ for (f=b->brush_faces ; f ; f=next)
+ {
+ next = f->next;
+ if (f)
+ texdef = f->texdef;
+ Face_Free( f );
+ }
+
+ b->brush_faces = NULL;
+
+ // left the last face so we can use its texdef
+
+ for (i=0 ; i<3 ; i++)
+ if (vMaxs[i] < vMins[i])
+ Error ("Brush_RebuildBrush: backwards");
+
+ pts[0][0][0] = vMins[0];
+ pts[0][0][1] = vMins[1];
+
+ pts[1][0][0] = vMins[0];
+ pts[1][0][1] = vMaxs[1];
+
+ pts[2][0][0] = vMaxs[0];
+ pts[2][0][1] = vMaxs[1];
+
+ pts[3][0][0] = vMaxs[0];
+ pts[3][0][1] = vMins[1];
+
+ for (i=0 ; i<4 ; i++)
+ {
+ pts[i][0][2] = vMins[2];
+ pts[i][1][0] = pts[i][0][0];
+ pts[i][1][1] = pts[i][0][1];
+ pts[i][1][2] = vMaxs[2];
+ }
+
+ for (i=0 ; i<4 ; i++)
+ {
+ f = Face_Alloc();
+ f->texdef = texdef;
+ f->texdef.flags &= ~SURF_KEEP;
+ f->texdef.contents &= ~CONTENTS_KEEP;
+ if ( b->patchBrush )
+ {
+ f->texdef.flags |= SURF_PATCH;
+ }
+ f->next = b->brush_faces;
+ b->brush_faces = f;
+ j = (i+1)%4;
+
+ VectorCopy (pts[j][1], f->planepts[0]);
+ VectorCopy (pts[i][1], f->planepts[1]);
+ VectorCopy (pts[i][0], f->planepts[2]);
+ }
+
+ f = Face_Alloc();
+ f->texdef = texdef;
+ f->texdef.flags &= ~SURF_KEEP;
+ f->texdef.contents &= ~CONTENTS_KEEP;
+ if ( b->patchBrush )
+ {
+ f->texdef.flags |= SURF_PATCH;
+ }
+ f->next = b->brush_faces;
+ b->brush_faces = f;
+
+ VectorCopy (pts[0][1], f->planepts[0]);
+ VectorCopy (pts[1][1], f->planepts[1]);
+ VectorCopy (pts[2][1], f->planepts[2]);
+
+ f = Face_Alloc();
+ f->texdef = texdef;
+ f->texdef.flags &= ~SURF_KEEP;
+ f->texdef.contents &= ~CONTENTS_KEEP;
+ if ( b->patchBrush )
+ {
+ f->texdef.flags |= SURF_PATCH;
+ }
+ f->next = b->brush_faces;
+ b->brush_faces = f;
+
+ VectorCopy (pts[2][0], f->planepts[0]);
+ VectorCopy (pts[1][0], f->planepts[1]);
+ VectorCopy (pts[0][0], f->planepts[2]);
+
+ Brush_Build(b);
+}
+
+void WINAPI Patch_Rebuild(patchMesh_t *p)
+{
+ vec3_t vMin, vMax;
+ Patch_CalcBounds(p, vMin, vMax);
+ Brush_RebuildBrush(p->pSymbiot, vMin, vMax);
+ p->bDirty = true;
+}
+
+/*
+==================
+AddBrushForPatch
+==================
+ adds a patch brush and ties it to this patch id
+*/
+brush_t* AddBrushForPatch(patchMesh_t *pm, bool bLinkToWorld )
+{
+ // find the farthest points in x,y,z
+ vec3_t vMin, vMax;
+ Patch_CalcBounds(pm, vMin, vMax);
+
+ for (int j = 0; j < 3; j++)
+ {
+ if (vMin[j] == vMax[j])
+ {
+ vMin[j] -= 4;
+ vMax[j] += 4;
+ }
+ }
+
+ brush_t *b = Brush_Create(vMin, vMax, &g_qeglobals.d_texturewin.texdef);
+ face_t *f;
+ for (f=b->brush_faces ; f ; f=f->next)
+ {
+ f->texdef.flags |= SURF_PATCH;
+ }
+
+ // FIXME: this entire type of linkage needs to be fixed
+ b->pPatch = pm;
+ pm->pSymbiot = b;
+ pm->bSelected = false;
+ pm->bOverlay = false;
+ pm->bDirty = true;
+ pm->nListID = -1;
+
+ if (bLinkToWorld)
+ {
+ Brush_AddToList (b, &active_brushes);
+ Entity_LinkBrush (world_entity, b);
+ Brush_Build(b);
+ }
+
+ return b;
+}
+
+void Patch_SetPointIntensities(int n)
+{
+#if 0
+ patchMesh_t *p = patchMeshes[n];
+ for (int i = 0; i < p->width; i++)
+ {
+ for (int j = 0; j < p->height; j++)
+ {
+
+ }
+ }
+#endif
+}
+
+// very approximate widths and heights
+
+/*
+==================
+Patch_Width
+==================
+*/
+float Patch_Width(patchMesh_t *p)
+{
+ float f = 0;
+ for (int i = 0; i < p->width-1; i++)
+ {
+ vec3_t vTemp;
+ VectorSubtract(p->ctrl[i][0].xyz, p->ctrl[i+1][0].xyz, vTemp);
+ f += VectorLength(vTemp);
+ }
+ return f;
+}
+
+float Patch_WidthDistanceTo(patchMesh_t *p, int j)
+{
+ float f = 0;
+ for (int i = 0; i < j; i++)
+ {
+ vec3_t vTemp;
+ VectorSubtract(p->ctrl[i][0].xyz, p->ctrl[i+1][0].xyz, vTemp);
+ f += VectorLength(vTemp);
+ }
+ return f;
+}
+
+
+
+/*
+==================
+Patch_Height
+==================
+*/
+float Patch_Height(patchMesh_t *p)
+{
+ float f = 0;
+ for (int i = 0; i < p->height-1; i++)
+ {
+ vec3_t vTemp;
+ VectorSubtract(p->ctrl[0][i].xyz, p->ctrl[0][i+1].xyz, vTemp);
+ f += VectorLength(vTemp);
+ }
+ return f;
+}
+
+float Patch_HeightDistanceTo(patchMesh_t *p, int j)
+{
+ float f = 0;
+ for (int i = 0; i < j; i++)
+ {
+ vec3_t vTemp;
+ VectorSubtract(p->ctrl[0][i].xyz, p->ctrl[0][i+1].xyz, vTemp);
+ f += VectorLength(vTemp);
+ }
+ return f;
+}
+
+
+
+/*
+==================
+Patch_Naturalize
+==================
+texture = TotalTexture * LengthToThisControlPoint / TotalControlPointLength
+
+dist( this control point to first control point ) / dist ( last control pt to first)
+*/
+void Patch_Naturalize(patchMesh_t *p)
+{
+ int nWidth = (g_PrefsDlg.m_bHiColorTextures == TRUE) ? p->d_texture->width * 0.5 : p->d_texture->width;
+ int nHeight = (g_PrefsDlg.m_bHiColorTextures == TRUE) ? p->d_texture->height * 0.5 : p->d_texture->height;
+ float fPWidth = Patch_Width(p);
+ float fPHeight = Patch_Height(p);
+ float xAccum = 0;
+ for ( int i = 0 ; i < p->width ; i++ )
+ {
+ float yAccum = 0;
+ for ( int j = 0 ; j < p->height ; j++ )
+ {
+ p->ctrl[i][j].st[0] = (fPWidth / nWidth) * xAccum / fPWidth;
+ p->ctrl[i][j].st[1] = (fPHeight / nHeight) * yAccum / fPHeight;
+ yAccum = Patch_HeightDistanceTo(p,j+1);
+ //p->ctrl[i][j][3] = (fPWidth / nWidth) * (float)i / (p->width - 1);
+ //p->ctrl[i][j][4] = (fPHeight/ nHeight) * (float)j / (p->height - 1);
+ }
+ xAccum = Patch_WidthDistanceTo(p,i+1);
+ }
+ p->bDirty = true;
+}
+
+/*
+ if (bIBevel)
+ {
+ VectorCopy(p->ctrl[1][0], p->ctrl[1][1]);
+ }
+
+ if (bIEndcap)
+ {
+ VectorCopy(p->ctrl[3][0], p->ctrl[4][1]);
+ VectorCopy(p->ctrl[2][0], p->ctrl[3][1]);
+ VectorCopy(p->ctrl[2][0], p->ctrl[2][1]);
+ VectorCopy(p->ctrl[2][0], p->ctrl[1][1]);
+ VectorCopy(p->ctrl[1][0], p->ctrl[0][1]);
+ VectorCopy(p->ctrl[1][0], p->ctrl[0][2]);
+ VectorCopy(p->ctrl[1][0], p->ctrl[1][2]);
+ VectorCopy(p->ctrl[2][0], p->ctrl[2][2]);
+ VectorCopy(p->ctrl[3][0], p->ctrl[3][2]);
+ VectorCopy(p->ctrl[3][0], p->ctrl[4][2]);
+ }
+*/
+
+int Index3By[][2] =
+{
+ {0,0},
+ {1,0},
+ {2,0},
+ {2,1},
+ {2,2},
+ {1,2},
+ {0,2},
+ {0,1},
+ {0,0},
+ {0,0},
+ {0,0},
+ {0,0},
+ {0,0},
+ {0,0},
+ {0,0}
+};
+
+int Index5By[][2] =
+{
+ {0,0},
+ {1,0},
+ {2,0},
+ {3,0},
+ {4,0},
+ {4,1},
+ {4,2},
+ {4,3},
+ {4,4},
+ {3,4},
+ {2,4},
+ {1,4},
+ {0,4},
+ {0,3},
+ {0,2},
+ {0,1}
+};
+
+
+
+int Interior3By[][2] =
+{
+ {1,1}
+};
+
+int Interior5By[][2] =
+{
+ {1,1},
+ {2,1},
+ {3,1},
+ {1,2},
+ {2,2},
+ {3,2},
+ {1,3},
+ {2,3},
+ {3,3}
+};
+
+int Interior3ByCount = sizeof(Interior3By) / sizeof(int[2]);
+int Interior5ByCount = sizeof(Interior5By) / sizeof(int[2]);
+
+face_t* Patch_GetAxisFace(patchMesh_t *p)
+{
+ face_t *f = NULL;
+ vec3_t vTemp;
+ brush_t *b = p->pSymbiot;
+
+ for (f = b->brush_faces ; f ; f = f->next)
+ {
+ VectorSubtract(f->face_winding->points[1], f->face_winding->points[0], vTemp);
+ int nScore = 0;
+
+ // default edge faces on caps are 8 high so
+ // as soon as we hit one that is bigger it should be on the right axis
+ for (int j = 0; j < 3; j++)
+ {
+ if (vTemp[j] > 8)
+ nScore++;
+ }
+
+ if (nScore > 0)
+ break;
+ }
+
+ if (f == NULL)
+ f = b->brush_faces;
+ return f;
+}
+
+int g_nFaceCycle = 0;
+
+face_t* nextFace(patchMesh_t *p)
+{
+ brush_t *b = p->pSymbiot;
+ face_t *f = NULL;
+ int n = 0;
+ for (f = b->brush_faces ; f && n <= g_nFaceCycle; f = f->next)
+ {
+ n++;
+ }
+ g_nFaceCycle++;
+ if (g_nFaceCycle > 5)
+ {
+ g_nFaceCycle =0;
+ f = b->brush_faces;
+ }
+
+ return f;
+}
+
+
+extern void EmitTextureCoordinates ( float *xyzst, qtexture_t *q, face_t *f);
+void Patch_CapTexture(patchMesh_t *p, bool bFaceCycle = false)
+{
+ Patch_MeshNormals(p);
+ face_t *f = (bFaceCycle) ? nextFace(p) : Patch_GetAxisFace(p);
+ vec3_t vSave;
+ VectorCopy(f->plane.normal, vSave);
+
+ float fRotate = f->texdef.rotate;
+ f->texdef.rotate = 0;
+ float fScale[2];
+ fScale[0] = f->texdef.scale[0];
+ fScale[1] = f->texdef.scale[1];
+ f->texdef.scale[0] = 0.5;
+ f->texdef.scale[1] = 0.5;
+ float fShift[2];
+ fShift[0] = f->texdef.shift[0];
+ fShift[1] = f->texdef.shift[1];
+ f->texdef.shift[0] = 0;
+ f->texdef.shift[1] = 0;
+
+ for (int i = 0; i < p->width; i++)
+ {
+ for (int j = 0; j < p->height; j++)
+ {
+ if (!bFaceCycle)
+ {
+ VectorCopy(p->ctrl[i][j].normal, f->plane.normal);
+ }
+ EmitTextureCoordinates( p->ctrl[i][j].xyz, f->d_texture, f);
+ }
+ }
+ VectorCopy(vSave, f->plane.normal);
+ f->texdef.rotate = fRotate;
+ f->texdef.scale[0] = fScale[0];
+ f->texdef.scale[1] = fScale[1];
+ f->texdef.shift[0] = fShift[0];
+ f->texdef.shift[1] = fShift[1];
+ p->bDirty = true;
+}
+
+void FillPatch(patchMesh_t *p, vec3_t v)
+{
+ for (int i = 0; i < p->width; i++)
+ {
+ for (int j = 0; j < p->height; j++)
+ {
+ VectorCopy(v, p->ctrl[i][j].xyz);
+ }
+ }
+}
+
+brush_t* Cap(patchMesh_t *pParent, bool bByColumn, bool bFirst)
+{
+ brush_t *b;
+ patchMesh_t *p;
+ vec3_t vMin, vMax;
+ int i, j;
+
+ bool bSmall = true;
+ // make a generic patch
+ if (pParent->width <= 9)
+ {
+ b = Patch_GenericMesh(3, 3, 2, false);
+ }
+ else
+ {
+ b = Patch_GenericMesh(5, 5, 2, false);
+ bSmall = false;
+ }
+
+ if (!b)
+ {
+ Sys_Printf("Unable to cap. You may need to ungroup the patch.\n");
+ return NULL;
+ }
+
+ p = b->pPatch;
+ p->type |= PATCH_CAP;
+
+ vMin[0] = vMin[1] = vMin[2] = 9999;
+ vMax[0] = vMax[1] = vMax[2] = -9999;
+
+ // we seam the column edge, FIXME: this might need to be able to seem either edge
+ //
+ int nSize = (bByColumn) ? pParent->width : pParent->height;
+ int nIndex = (bFirst) ? 0 : (bByColumn) ? pParent->height-1 : pParent->width-1;
+
+ FillPatch(p, pParent->ctrl[0][nIndex].xyz);
+
+ for (i = 0; i < nSize; i++)
+ {
+ if (bByColumn)
+ {
+ if (bSmall)
+ {
+ VectorCopy(pParent->ctrl[i][nIndex].xyz, p->ctrl[Index3By[i][0]][Index3By[i][1]].xyz);
+ }
+ else
+ {
+ VectorCopy(pParent->ctrl[i][nIndex].xyz, p->ctrl[Index5By[i][0]][Index5By[i][1]].xyz);
+ }
+ }
+ else
+ {
+ if (bSmall)
+ {
+ VectorCopy(pParent->ctrl[nIndex][i].xyz, p->ctrl[Index3By[i][0]][Index3By[i][1]].xyz);
+ }
+ else
+ {
+ VectorCopy(pParent->ctrl[nIndex][i].xyz, p->ctrl[Index5By[i][0]][Index5By[i][1]].xyz);
+ }
+ }
+
+ for (j = 0; j < 3; j++)
+ {
+ float f = (bSmall) ? p->ctrl[Index3By[i][0]][Index3By[i][1]].xyz[j] : p->ctrl[Index5By[i][0]][Index5By[i][1]].xyz[j];
+ if (f < vMin[j])
+ vMin[j] = f;
+ if (f > vMax[j])
+ vMax[j] = f;
+ }
+ }
+
+ vec3_t vTemp;
+ for (j = 0; j < 3; j++)
+ {
+ vTemp[j] = vMin[j] + abs((vMax[j] - vMin[j]) * 0.5);
+ }
+
+ int nCount = (bSmall) ? Interior3ByCount : Interior5ByCount;
+ for (j = 0; j < nCount; j++)
+ {
+ if (bSmall)
+ {
+ VectorCopy(vTemp, p->ctrl[Interior3By[j][0]][Interior3By[j][1]].xyz);
+ }
+ else
+ {
+ VectorCopy(vTemp, p->ctrl[Interior5By[j][0]][Interior5By[j][1]].xyz);
+ }
+ }
+
+ if (bFirst)
+ {
+ drawVert_t vertTemp;
+ for (i = 0; i < p->width; i++)
+ {
+ for (j = 0; j < p->height / 2; j++)
+ {
+ memcpy(&vertTemp, &p->ctrl[i][p->height - 1- j], sizeof (drawVert_t));
+ memcpy(&p->ctrl[i][p->height - 1 - j], &p->ctrl[i][j], sizeof(drawVert_t));
+ memcpy(&p->ctrl[i][j], &vertTemp, sizeof(drawVert_t));
+ }
+ }
+ }
+
+ Patch_Rebuild(p);
+ Patch_CapTexture(p);
+ return p->pSymbiot;
+}
+
+brush_t* CapSpecial(patchMesh_t *pParent, int nType, bool bFirst)
+{
+ brush_t *b;
+ patchMesh_t *p;
+ vec3_t vMin, vMax, vTemp;
+ int i, j;
+
+ if (nType == CCapDialog::IENDCAP)
+ b = Patch_GenericMesh(5, 3, 2, false);
+ else
+ b = Patch_GenericMesh(3, 3, 2, false);
+
+ if (!b)
+ {
+ Sys_Printf("Unable to cap. Make sure you ungroup before re-capping.");
+ return NULL;
+ }
+
+ p = b->pPatch;
+ p->type |= PATCH_CAP;
+
+ vMin[0] = vMin[1] = vMin[2] = 9999;
+ vMax[0] = vMax[1] = vMax[2] = -9999;
+
+ int nSize = pParent->width;
+ int nIndex = (bFirst) ? 0 : pParent->height-1;
+
+ // parent bounds are used for some things
+ Patch_CalcBounds(pParent, vMin, vMax);
+
+ for (j = 0; j < 3; j++)
+ {
+ vTemp[j] = vMin[j] + abs((vMax[j] - vMin[j]) * 0.5);
+ }
+
+ if (nType == CCapDialog::IBEVEL)
+ {
+ VectorCopy(pParent->ctrl[0][nIndex].xyz, p->ctrl[0][0].xyz);
+ VectorCopy(pParent->ctrl[2][nIndex].xyz, p->ctrl[0][2].xyz);
+ VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[0][1].xyz);
+ VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[2][2].xyz);
+ VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[1][0].xyz);
+ VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[1][1].xyz);
+ VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[1][2].xyz);
+ VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[2][0].xyz);
+ VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[2][1].xyz);
+ }
+ else if (nType == CCapDialog::BEVEL)
+ {
+ vec3_t p1, p2, p3, p4, temp, dir;
+
+ VectorCopy(pParent->ctrl[0][nIndex].xyz, p3);
+ VectorCopy(pParent->ctrl[1][nIndex].xyz, p1);
+ VectorCopy(pParent->ctrl[2][nIndex].xyz, p2);
+
+ VectorSubtract(p3, p2, dir);
+ VectorNormalize(dir);
+ VectorSubtract(p1, p2, temp);
+ vec_t dist = _DotProduct(temp, dir);
+
+ VectorScale(dir, dist, temp);
+
+ VectorAdd(p2, temp, temp);
+
+ VectorSubtract(temp, p1, temp);
+ VectorScale(temp, 2, temp);
+ VectorAdd(p1, temp, p4);
+
+ VectorCopy(p4, p->ctrl[0][0].xyz);
+ VectorCopy(p4, p->ctrl[1][0].xyz);
+ VectorCopy(p4, p->ctrl[0][1].xyz);
+ VectorCopy(p4, p->ctrl[1][1].xyz);
+ VectorCopy(p4, p->ctrl[0][2].xyz);
+ VectorCopy(p4, p->ctrl[1][2].xyz);
+ VectorCopy(p3, p->ctrl[2][0].xyz);
+ VectorCopy(p1, p->ctrl[2][1].xyz);
+ VectorCopy(p2, p->ctrl[2][2].xyz);
+
+ }
+ else if (nType == CCapDialog::ENDCAP)
+ {
+ VectorAdd(pParent->ctrl[4][nIndex].xyz, pParent->ctrl[0][nIndex].xyz, vTemp);
+ VectorScale(vTemp, 0.5, vTemp);
+ VectorCopy(pParent->ctrl[0][nIndex].xyz, p->ctrl[0][0].xyz);
+ VectorCopy(vTemp, p->ctrl[1][0].xyz);
+ VectorCopy(pParent->ctrl[4][nIndex].xyz, p->ctrl[2][0].xyz);
+
+ VectorCopy(pParent->ctrl[2][nIndex].xyz, p->ctrl[0][2].xyz);
+ VectorCopy(pParent->ctrl[2][nIndex].xyz, p->ctrl[1][2].xyz);
+ VectorCopy(pParent->ctrl[2][nIndex].xyz, p->ctrl[2][2].xyz);
+ VectorCopy(pParent->ctrl[2][nIndex].xyz, p->ctrl[1][1].xyz);
+
+ VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[0][1].xyz);
+ VectorCopy(pParent->ctrl[3][nIndex].xyz, p->ctrl[2][1].xyz);
+ }
+ else
+ {
+ VectorCopy(pParent->ctrl[0][nIndex].xyz, p->ctrl[0][0].xyz);
+ VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[1][0].xyz);
+ VectorCopy(pParent->ctrl[2][nIndex].xyz, p->ctrl[2][0].xyz);
+ VectorCopy(pParent->ctrl[3][nIndex].xyz, p->ctrl[3][0].xyz);
+ VectorCopy(pParent->ctrl[4][nIndex].xyz, p->ctrl[4][0].xyz);
+
+ VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[0][1].xyz);
+ VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[1][1].xyz);
+ VectorCopy(pParent->ctrl[2][nIndex].xyz, p->ctrl[2][1].xyz);
+ VectorCopy(pParent->ctrl[3][nIndex].xyz, p->ctrl[3][1].xyz);
+ VectorCopy(pParent->ctrl[3][nIndex].xyz, p->ctrl[4][1].xyz);
+
+ VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[0][2].xyz);
+ VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[1][2].xyz);
+ VectorCopy(pParent->ctrl[2][nIndex].xyz, p->ctrl[2][2].xyz);
+ VectorCopy(pParent->ctrl[3][nIndex].xyz, p->ctrl[3][2].xyz);
+ VectorCopy(pParent->ctrl[3][nIndex].xyz, p->ctrl[4][2].xyz);
+ }
+
+
+ bool bEndCap = (nType == CCapDialog::ENDCAP || nType == CCapDialog::IENDCAP);
+ if ((!bFirst && !bEndCap) || (bFirst && bEndCap))
+ {
+ drawVert_t vertTemp;
+ for (i = 0; i < p->width; i++)
+ {
+ for (j = 0; j < p->height / 2; j++)
+ {
+ memcpy(&vertTemp, &p->ctrl[i][p->height - 1- j], sizeof (drawVert_t));
+ memcpy(&p->ctrl[i][p->height - 1 - j], &p->ctrl[i][j], sizeof(drawVert_t));
+ memcpy(&p->ctrl[i][j], &vertTemp, sizeof(drawVert_t));
+ }
+ }
+ }
+
+ //--Patch_CalcBounds(p, vMin, vMax);
+ //--Brush_RebuildBrush(p->pSymbiot, vMin, vMax);
+ Patch_Rebuild(p);
+ Patch_CapTexture(p);
+ return p->pSymbiot;
+}
+
+
+void Patch_CapCurrent(bool bInvertedBevel, bool bInvertedEndcap)
+{
+ patchMesh_t *pParent = NULL;
+ brush_t *b[4];
+ brush_t *pCap = NULL;
+ b[0] = b[1] = b[2] = b[3] = NULL;
+ int nIndex = 0;
+
+ if (!QE_SingleBrush())
+ {
+ Sys_Printf("Cannot cap multiple selection. Please select a single patch.\n");
+ return;
+ }
+
+
+ for (brush_t *pb = selected_brushes.next ; pb != NULL && pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ pParent = pb->pPatch;
+ // decide which if any ends we are going to cap
+ // if any of these compares hit, it is a closed patch and as such
+ // the generic capping will work.. if we do not find a closed edge
+ // then we need to ask which kind of cap to add
+ if (VectorCompare(pParent->ctrl[0][0].xyz, pParent->ctrl[pParent->width-1][0].xyz))
+ {
+ pCap = Cap(pParent, true, false);
+ if (pCap != NULL)
+ {
+ b[nIndex++] = pCap;
+ }
+ }
+ if (VectorCompare(pParent->ctrl[0][pParent->height-1].xyz, pParent->ctrl[pParent->width-1][pParent->height-1].xyz))
+ {
+ pCap = Cap(pParent, true, true);
+ if (pCap != NULL)
+ {
+ b[nIndex++] = pCap;
+ }
+ }
+ if (VectorCompare(pParent->ctrl[0][0].xyz, pParent->ctrl[0][pParent->height-1].xyz))
+ {
+ pCap = Cap(pParent, false, false);
+ if (pCap != NULL)
+ {
+ b[nIndex++] = pCap;
+ }
+ }
+ if (VectorCompare(pParent->ctrl[pParent->width-1][0].xyz, pParent->ctrl[pParent->width-1][pParent->height-1].xyz))
+ {
+ pCap = Cap(pParent, false, true);
+ if (pCap != NULL)
+ {
+ b[nIndex++] = pCap;
+ }
+ }
+ }
+ }
+
+ if (pParent)
+ {
+ // if we did not cap anything with the above tests
+ if (nIndex == 0)
+ {
+ CCapDialog dlg;
+ if (dlg.DoModal() == IDOK)
+ {
+ b[nIndex++] = CapSpecial(pParent, dlg.getCapType(), false);
+ b[nIndex++] = CapSpecial(pParent, dlg.getCapType(), true);
+ }
+ }
+
+ if (nIndex > 0)
+ {
+ while (nIndex > 0)
+ {
+ nIndex--;
+ if (b[nIndex])
+ {
+ Select_Brush(b[nIndex]);
+ }
+ }
+ eclass_t *pecNew = Eclass_ForName("func_group", false);
+ if (pecNew)
+ {
+ entity_t *e = Entity_Create(pecNew);
+ SetKeyValue(e, "type", "patchCapped");
+ }
+ }
+ }
+}
+
+
+//FIXME: Table drive all this crap
+//
+void GenerateEndCaps(brush_t *brushParent, bool bBevel, bool bEndcap, bool bInverted)
+{
+ brush_t *b, *b2;
+ patchMesh_t *p, *p2, *pParent;
+ vec3_t vTemp, vMin, vMax;
+ int i, j;
+
+ pParent = brushParent->pPatch;
+
+ Patch_CalcBounds(pParent, vMin, vMax);
+ // basically generate two endcaps, place them, and link the three brushes with a func_group
+
+ if (pParent->width > 9)
+ b = Patch_GenericMesh(5, 3, 2, false);
+ else
+ b = Patch_GenericMesh(3, 3, 2, false);
+ p = b->pPatch;
+
+ vMin[0] = vMin[1] = vMin[2] = 9999;
+ vMax[0] = vMax[1] = vMax[2] = -9999;
+
+ for (i = 0; i < pParent->width; i++)
+ {
+ VectorCopy(pParent->ctrl[i][0].xyz, p->ctrl[Index3By[i][0]][Index3By[i][1]].xyz);
+ for (j = 0; j < 3; j++)
+ {
+ if (pParent->ctrl[i][0].xyz[j] < vMin[j])
+ vMin[j] = pParent->ctrl[i][0].xyz[j];
+ if (pParent->ctrl[i][0].xyz[j] > vMax[j])
+ vMax[j] = pParent->ctrl[i][0].xyz[j];
+ }
+ }
+
+ for (j = 0; j < 3; j++)
+ {
+ vTemp[j] = vMin[j] + abs((vMax[j] - vMin[j]) * 0.5);
+ }
+
+ for (i = 0; i < Interior3ByCount; i++)
+ {
+ VectorCopy(vTemp, p->ctrl[Interior3By[i][0]][Interior3By[i][1]].xyz);
+ }
+
+ Patch_CalcBounds(p, vMin, vMax);
+ Brush_RebuildBrush(p->pSymbiot, vMin, vMax);
+ Select_Brush(p->pSymbiot);
+ return;
+
+ bool bCreated = false;
+
+ if (bInverted)
+ {
+ if (bBevel)
+ {
+ b = Patch_GenericMesh(3, 3, 2, false);
+ p = b->pPatch;
+ VectorCopy(p->ctrl[2][2].xyz, p->ctrl[1][2].xyz);
+ VectorCopy(p->ctrl[2][2].xyz, p->ctrl[2][1].xyz);
+ VectorCopy(p->ctrl[2][2].xyz, p->ctrl[0][1].xyz);
+ VectorCopy(p->ctrl[2][2].xyz, p->ctrl[1][0].xyz);
+ VectorCopy(p->ctrl[2][2].xyz, p->ctrl[1][1].xyz);
+ VectorCopy(p->ctrl[2][0].xyz, p->ctrl[0][0].xyz);
+
+ b2 = Patch_GenericMesh(3, 3, 2, false);
+ p2 = b2->pPatch;
+ VectorCopy(p2->ctrl[2][2].xyz, p2->ctrl[1][2].xyz);
+ VectorCopy(p2->ctrl[2][2].xyz, p2->ctrl[2][1].xyz);
+ VectorCopy(p2->ctrl[2][2].xyz, p2->ctrl[0][1].xyz);
+ VectorCopy(p2->ctrl[2][2].xyz, p2->ctrl[1][0].xyz);
+ VectorCopy(p2->ctrl[2][2].xyz, p2->ctrl[1][1].xyz);
+ VectorCopy(p2->ctrl[2][0].xyz, p2->ctrl[0][0].xyz);
+
+
+ bCreated = true;
+
+ }
+ else if (bEndcap)
+ {
+ b = Patch_GenericMesh(5, 5, 2, false);
+ p = b->pPatch;
+ VectorCopy(p->ctrl[4][4].xyz, p->ctrl[4][3].xyz);
+ VectorCopy(p->ctrl[0][4].xyz, p->ctrl[1][4].xyz);
+ VectorCopy(p->ctrl[0][4].xyz, p->ctrl[2][4].xyz);
+ VectorCopy(p->ctrl[0][4].xyz, p->ctrl[3][4].xyz);
+
+ VectorCopy(p->ctrl[4][0].xyz, p->ctrl[4][1].xyz);
+ VectorCopy(p->ctrl[0][0].xyz, p->ctrl[1][0].xyz);
+ VectorCopy(p->ctrl[0][0].xyz, p->ctrl[2][0].xyz);
+ VectorCopy(p->ctrl[0][0].xyz, p->ctrl[3][0].xyz);
+
+ for (i = 1; i < 4; i++)
+ {
+ for (j = 0; j < 4; j++)
+ {
+ VectorCopy(p->ctrl[4][i].xyz, p->ctrl[j][i].xyz);
+ }
+ }
+
+
+ b2 = Patch_GenericMesh(5, 5, 2, false);
+ p2 = b2->pPatch;
+ VectorCopy(p2->ctrl[4][4].xyz, p2->ctrl[4][3].xyz);
+ VectorCopy(p2->ctrl[0][4].xyz, p2->ctrl[1][4].xyz);
+ VectorCopy(p2->ctrl[0][4].xyz, p2->ctrl[2][4].xyz);
+ VectorCopy(p2->ctrl[0][4].xyz, p2->ctrl[3][4].xyz);
+
+ VectorCopy(p2->ctrl[4][0].xyz, p2->ctrl[4][1].xyz);
+ VectorCopy(p2->ctrl[0][0].xyz, p2->ctrl[1][0].xyz);
+ VectorCopy(p2->ctrl[0][0].xyz, p2->ctrl[2][0].xyz);
+ VectorCopy(p2->ctrl[0][0].xyz, p2->ctrl[3][0].xyz);
+
+ for (i = 1; i < 4; i++)
+ {
+ for (j = 0; j < 4; j++)
+ {
+ VectorCopy(p2->ctrl[4][i].xyz, p2->ctrl[j][i].xyz);
+ }
+ }
+
+
+ bCreated = true;
+ }
+ }
+ else
+ {
+ if (bBevel)
+ {
+ b = Patch_GenericMesh(3, 3, 2, false);
+ p = b->pPatch;
+ VectorCopy(p->ctrl[2][0].xyz, p->ctrl[2][1].xyz);
+ VectorCopy(p->ctrl[0][0].xyz, p->ctrl[1][0].xyz);
+ VectorCopy(p->ctrl[0][0].xyz, p->ctrl[2][0].xyz);
+
+ b2 = Patch_GenericMesh(3, 3, 2, false);
+ p2 = b2->pPatch;
+ VectorCopy(p2->ctrl[2][0].xyz, p2->ctrl[2][1].xyz);
+ VectorCopy(p2->ctrl[0][0].xyz, p2->ctrl[1][0].xyz);
+ VectorCopy(p2->ctrl[0][0].xyz, p2->ctrl[2][0].xyz);
+ bCreated = true;
+ }
+ else if (bEndcap)
+ {
+ b = Patch_GenericMesh(5, 5, 2, false);
+ p = b->pPatch;
+ VectorCopy(p->ctrl[0][0].xyz, p->ctrl[1][0].xyz);
+ VectorCopy(p->ctrl[0][0].xyz, p->ctrl[2][0].xyz);
+ VectorCopy(p->ctrl[0][0].xyz, p->ctrl[3][0].xyz);
+ VectorCopy(p->ctrl[4][0].xyz, p->ctrl[4][1].xyz);
+ VectorCopy(p->ctrl[0][0].xyz, p->ctrl[4][0].xyz);
+
+ VectorCopy(p->ctrl[0][4].xyz, p->ctrl[1][4].xyz);
+ VectorCopy(p->ctrl[0][4].xyz, p->ctrl[2][4].xyz);
+ VectorCopy(p->ctrl[0][4].xyz, p->ctrl[3][4].xyz);
+ VectorCopy(p->ctrl[4][4].xyz, p->ctrl[4][3].xyz);
+ VectorCopy(p->ctrl[0][4].xyz, p->ctrl[4][4].xyz);
+
+ b2 = Patch_GenericMesh(5, 5, 2, false);
+ p2 = b2->pPatch;
+ VectorCopy(p2->ctrl[0][0].xyz, p2->ctrl[1][0].xyz);
+ VectorCopy(p2->ctrl[0][0].xyz, p2->ctrl[2][0].xyz);
+ VectorCopy(p2->ctrl[0][0].xyz, p2->ctrl[3][0].xyz);
+ VectorCopy(p2->ctrl[4][0].xyz, p2->ctrl[4][1].xyz);
+ VectorCopy(p2->ctrl[0][0].xyz, p2->ctrl[4][0].xyz);
+
+ VectorCopy(p2->ctrl[0][4].xyz, p2->ctrl[1][4].xyz);
+ VectorCopy(p2->ctrl[0][4].xyz, p2->ctrl[2][4].xyz);
+ VectorCopy(p2->ctrl[0][4].xyz, p2->ctrl[3][4].xyz);
+ VectorCopy(p2->ctrl[4][4].xyz, p2->ctrl[4][3].xyz);
+ VectorCopy(p2->ctrl[0][4].xyz, p2->ctrl[4][4].xyz);
+ bCreated = true;
+ }
+ else
+ {
+ b = Patch_GenericMesh(3, 3, 2, false);
+ p = b->pPatch;
+
+ VectorCopy(p->ctrl[0][1].xyz, vTemp);
+ VectorCopy(p->ctrl[0][2].xyz, p->ctrl[0][1].xyz)
+ VectorCopy(p->ctrl[1][2].xyz, p->ctrl[0][2].xyz)
+ VectorCopy(p->ctrl[2][2].xyz, p->ctrl[1][2].xyz)
+ VectorCopy(p->ctrl[2][1].xyz, p->ctrl[2][2].xyz)
+ VectorCopy(p->ctrl[2][0].xyz, p->ctrl[2][1].xyz)
+ VectorCopy(p->ctrl[1][0].xyz, p->ctrl[2][0].xyz)
+ VectorCopy(p->ctrl[0][0].xyz, p->ctrl[1][0].xyz)
+ VectorCopy(vTemp, p->ctrl[0][0].xyz)
+
+ b2 = Patch_GenericMesh(3, 3, 2, false);
+ p2 = b2->pPatch;
+ VectorCopy(p2->ctrl[0][1].xyz, vTemp);
+ VectorCopy(p2->ctrl[0][2].xyz, p2->ctrl[0][1].xyz)
+ VectorCopy(p2->ctrl[1][2].xyz, p2->ctrl[0][2].xyz)
+ VectorCopy(p2->ctrl[2][2].xyz, p2->ctrl[1][2].xyz)
+ VectorCopy(p2->ctrl[2][1].xyz, p2->ctrl[2][2].xyz)
+ VectorCopy(p2->ctrl[2][0].xyz, p2->ctrl[2][1].xyz)
+ VectorCopy(p2->ctrl[1][0].xyz, p2->ctrl[2][0].xyz)
+ VectorCopy(p2->ctrl[0][0].xyz, p2->ctrl[1][0].xyz)
+ VectorCopy(vTemp, p2->ctrl[0][0].xyz)
+ bCreated = true;
+ }
+ }
+
+ if (bCreated)
+ {
+ drawVert_t vertTemp;
+ for (i = 0; i < p->width; i++)
+ {
+ for (j = 0; j < p->height; j++)
+ {
+ p->ctrl[i][j].xyz[2] = vMin[2];
+ p2->ctrl[i][j].xyz[2] = vMax[2];
+ }
+
+ for (j = 0; j < p->height / 2; j++)
+ {
+ memcpy(&vertTemp, &p->ctrl[i][p->height - 1- j], sizeof (drawVert_t));
+ memcpy(&p->ctrl[i][p->height - 1 - j], &p->ctrl[i][j], sizeof(drawVert_t));
+ memcpy(&p->ctrl[i][j], &vertTemp, sizeof(drawVert_t));
+ }
+
+ }
+ //Select_Delete();
+
+ Patch_CalcBounds(p, vMin, vMax);
+ Brush_RebuildBrush(p->pSymbiot, vMin, vMax);
+ Patch_CalcBounds(p2, vMin, vMax);
+ Brush_RebuildBrush(p2->pSymbiot, vMin, vMax);
+ Select_Brush(p->pSymbiot);
+ Select_Brush(p2->pSymbiot);
+ }
+ else
+ {
+ Select_Delete();
+ }
+ //Select_Brush(brushParent);
+
+}
+
+
+/*
+===============
+BrushToPatchMesh
+===============
+*/
+void Patch_BrushToMesh(bool bCone, bool bBevel, bool bEndcap, bool bSquare, int nHeight)
+{
+ brush_t *b;
+ patchMesh_t *p;
+ int i,j;
+
+ if (!QE_SingleBrush())
+ return;
+
+ b = selected_brushes.next;
+
+ p = MakeNewPatch();
+
+ p->d_texture = b->brush_faces->d_texture;
+
+ p->height = nHeight;
+
+ p->type = PATCH_CYLINDER;
+ if (bBevel & !bSquare)
+ {
+ p->type = PATCH_BEVEL;
+ p->width = 3;
+ int nStep = (b->maxs[2] - b->mins[2]) / (p->height-1);
+ int nStart = b->mins[2];
+ for (i = 0; i < p->height; i++)
+ {
+ p->ctrl[0][i].xyz[0] = b->mins[0];
+ p->ctrl[0][i].xyz[1] = b->mins[1];
+ p->ctrl[0][i].xyz[2] = nStart;
+
+ p->ctrl[1][i].xyz[0] = b->maxs[0];
+ p->ctrl[1][i].xyz[1] = b->mins[1];
+ p->ctrl[1][i].xyz[2] = nStart;
+
+ p->ctrl[2][i].xyz[0] = b->maxs[0];
+ p->ctrl[2][i].xyz[1] = b->maxs[1];
+ p->ctrl[2][i].xyz[2] = nStart;
+ nStart += nStep;
+ }
+ }
+ else if (bEndcap & !bSquare)
+ {
+ p->type = PATCH_ENDCAP;
+ p->width = 5;
+ int nStep = (b->maxs[2] - b->mins[2]) / (p->height-1);
+ int nStart = b->mins[2];
+ for (i = 0; i < p->height; i++)
+ {
+ p->ctrl[0][i].xyz[0] = b->mins[0];
+ p->ctrl[0][i].xyz[1] = b->mins[1];
+ p->ctrl[0][i].xyz[2] = nStart;
+
+ p->ctrl[1][i].xyz[0] = b->mins[0];
+ p->ctrl[1][i].xyz[1] = b->maxs[1];
+ p->ctrl[1][i].xyz[2] = nStart;
+
+ p->ctrl[2][i].xyz[0] = b->mins[0] + ((b->maxs[0] - b->mins[0]) * 0.5);
+ p->ctrl[2][i].xyz[1] = b->maxs[1];
+ p->ctrl[2][i].xyz[2] = nStart;
+
+ p->ctrl[3][i].xyz[0] = b->maxs[0];
+ p->ctrl[3][i].xyz[1] = b->maxs[1];
+ p->ctrl[3][i].xyz[2] = nStart;
+
+ p->ctrl[4][i].xyz[0] = b->maxs[0];
+ p->ctrl[4][i].xyz[1] = b->mins[1];
+ p->ctrl[4][i].xyz[2] = nStart;
+ nStart += nStep;
+ }
+ }
+ else
+ {
+ p->width = 9;
+ p->ctrl[1][0].xyz[0] = b->mins[0];
+ p->ctrl[1][0].xyz[1] = b->mins[1];
+
+ p->ctrl[3][0].xyz[0] = b->maxs[0];
+ p->ctrl[3][0].xyz[1] = b->mins[1];
+
+ p->ctrl[5][0].xyz[0] = b->maxs[0];
+ p->ctrl[5][0].xyz[1] = b->maxs[1];
+
+ p->ctrl[7][0].xyz[0] = b->mins[0];
+ p->ctrl[7][0].xyz[1] = b->maxs[1];
+
+ for ( i = 1 ; i < p->width - 1 ; i += 2 )
+ {
+
+ p->ctrl[i][0].xyz[2] = b->mins[2];
+
+ VectorCopy( p->ctrl[i][0].xyz, p->ctrl[i][2].xyz );
+
+ p->ctrl[i][2].xyz[2] = b->maxs[2];
+
+ p->ctrl[i][1].xyz[0] = ( p->ctrl[i][0].xyz[0] + p->ctrl[i][2].xyz[0] ) * 0.5;
+ p->ctrl[i][1].xyz[1] = ( p->ctrl[i][0].xyz[1] + p->ctrl[i][2].xyz[1] ) * 0.5;
+ p->ctrl[i][1].xyz[2] = ( p->ctrl[i][0].xyz[2] + p->ctrl[i][2].xyz[2] ) * 0.5;
+ }
+ InterpolateInteriorPoints( p );
+
+ if (bSquare)
+ {
+ if (bBevel || bEndcap)
+ {
+ if (bBevel)
+ {
+ for (i = 0; i < p->height; i++)
+ {
+ VectorCopy(p->ctrl[1][i].xyz, p->ctrl[2][i].xyz);
+ VectorCopy(p->ctrl[7][i].xyz, p->ctrl[6][i].xyz);
+ }
+ }
+ else
+ {
+ for (i = 0; i < p->height; i++)
+ {
+ VectorCopy(p->ctrl[5][i].xyz, p->ctrl[4][i].xyz);
+ VectorCopy(p->ctrl[1][i].xyz, p->ctrl[2][i].xyz);
+ VectorCopy(p->ctrl[7][i].xyz, p->ctrl[6][i].xyz);
+ VectorCopy(p->ctrl[8][i].xyz, p->ctrl[7][i].xyz);
+ }
+ }
+ }
+ else
+ {
+ for (i = 0; i < p->width-1; i ++)
+ {
+ for (j = 0; j < p->height; j++)
+ {
+ VectorCopy(p->ctrl[i+1][j].xyz, p->ctrl[i][j].xyz);
+ }
+ }
+ for (j = 0; j < p->height; j++)
+ {
+ VectorCopy(p->ctrl[0][j].xyz, p->ctrl[8][j].xyz);
+ }
+ }
+ }
+ }
+
+
+ Patch_Naturalize(p);
+
+ if (bCone)
+ {
+ p->type = PATCH_CONE;
+ float xc = (b->maxs[0] + b->mins[0]) * 0.5;
+ float yc = (b->maxs[1] + b->mins[1]) * 0.5;
+
+ for ( i = 0 ; i < p->width ; i ++)
+ {
+ p->ctrl[i][2].xyz[0] = xc;
+ p->ctrl[i][2].xyz[1] = yc;
+ }
+ }
+/*
+ if (bEndcap || bBevel)
+ {
+ if (bInverted)
+ {
+ for ( i = 0 ; i < p->height ; i ++)
+ {
+ if (bBevel)
+ {
+ VectorCopy(p->ctrl[7][i], p->ctrl[0][i]);
+ VectorCopy(p->ctrl[7][i], p->ctrl[8][i]);
+ VectorCopy(p->ctrl[3][i], p->ctrl[2][i]);
+ VectorCopy(p->ctrl[5][i], p->ctrl[1][i]);
+ VectorCopy(p->ctrl[5][i], p->ctrl[4][i]);
+ VectorCopy(p->ctrl[5][i], p->ctrl[6][i]);
+ }
+ else
+ {
+ VectorCopy(p->ctrl[4][i], p->ctrl[8][i]);
+ VectorCopy(p->ctrl[1][i], p->ctrl[0][i]);
+ VectorCopy(p->ctrl[1][i], p->ctrl[10][i]);
+ VectorCopy(p->ctrl[3][i], p->ctrl[2][i]);
+ VectorCopy(p->ctrl[5][i], p->ctrl[4][i]);
+ VectorCopy(p->ctrl[7][i], p->ctrl[6][i]);
+ VectorCopy(p->ctrl[5][i], p->ctrl[7][i]);
+ VectorCopy(p->ctrl[3][i], p->ctrl[9][i]);
+ }
+ }
+ }
+ else
+ {
+ for ( i = 0 ; i < p->height ; i ++)
+ {
+ VectorCopy(p->ctrl[1][i], p->ctrl[2][i]);
+ VectorCopy(p->ctrl[7][i], p->ctrl[6][i]);
+ if (bBevel)
+ {
+ VectorCopy(p->ctrl[5][i], p->ctrl[4][i]);
+ }
+ }
+ }
+ }
+*/
+
+ b = AddBrushForPatch(p);
+
+
+#if 1
+ Select_Delete();
+ Select_Brush(b);
+#else
+ if (!bCone)
+ {
+ Select_Delete();
+ Select_Brush(b);
+ GenerateEndCaps(b, bBevel, bEndcap, bInverted);
+ eclass_t *pecNew = Eclass_ForName("func_group", false);
+ if (pecNew)
+ {
+ Entity_Create(pecNew);
+ }
+ }
+ else
+ {
+ Select_Delete();
+ Select_Brush(b);
+ }
+#endif
+
+}
+
+/*
+==================
+Patch_GenericMesh
+==================
+*/
+brush_t* Patch_GenericMesh(int nWidth, int nHeight, int nOrientation, bool bDeleteSource, bool bOverride)
+{
+ int i,j;
+
+ if (nHeight < 3 || nHeight > 15 || nWidth < 3 || nWidth > 15)
+ {
+ Sys_Printf("Invalid patch width or height.\n");
+ return NULL;
+ }
+
+ if (! bOverride && !QE_SingleBrush())
+ {
+ Sys_Printf("Cannot generate a patch from multiple selections.\n");
+ return NULL;
+ }
+
+
+
+ patchMesh_t* p = MakeNewPatch();
+ p->d_texture = Texture_ForName(g_qeglobals.d_texturewin.texdef.name);
+
+ p->width = nWidth;
+ p->height = nHeight;
+ p->type = PATCH_GENERIC;
+
+ int nFirst = 0;
+ int nSecond = 1;
+ if (nOrientation == 0)
+ {
+ nFirst = 1;
+ nSecond = 2;
+ }
+ else if (nOrientation == 1)
+ {
+ nSecond = 2;
+ }
+
+ brush_t *b = selected_brushes.next;
+
+ int xStep = b->mins[nFirst];
+ float xAdj = abs((b->maxs[nFirst] - b->mins[nFirst]) / (nWidth - 1));
+ float yAdj = abs((b->maxs[nSecond] - b->mins[nSecond]) / (nHeight - 1));
+
+ for (i = 0; i < nWidth; i++)
+ {
+ int yStep = b->mins[nSecond];
+ for (j = 0; j < nHeight; j++)
+ {
+ p->ctrl[i][j].xyz[nFirst] = xStep;
+ p->ctrl[i][j].xyz[nSecond] = yStep;
+ p->ctrl[i][j].xyz[nOrientation] = 0;
+ yStep += yAdj;
+ }
+ xStep += xAdj;
+ }
+
+ Patch_Naturalize(p);
+
+ b = AddBrushForPatch(p);
+ if (bDeleteSource)
+ {
+ Select_Delete();
+ Select_Brush(b);
+ }
+
+ return b;
+ //g_qeglobals.d_select_mode = sel_curvepoint;
+}
+
+/*
+==================
+PointInMoveList
+==================
+*/
+int PointInMoveList(float *pf)
+{
+ for (int i = 0; i < g_qeglobals.d_num_move_points; i++)
+ {
+ if (pf == &g_qeglobals.d_move_points[i][0])
+ return i;
+ }
+ return -1;
+}
+
+/*
+==================
+PointValueInMoveList
+==================
+*/
+int PointValueInMoveList(vec3_t v)
+{
+ for (int i = 0; i < g_qeglobals.d_num_move_points; i++)
+ {
+ if (VectorCompare(v, g_qeglobals.d_move_points[i]))
+ return i;
+ }
+ return -1;
+}
+
+
+/*
+==================
+RemovePointFromMoveList
+==================
+*/
+void RemovePointFromMoveList(vec3_t v)
+{
+ int n;
+ while ( (n = PointValueInMoveList(v)) >= 0)
+ {
+ for (int i = n; i < g_qeglobals.d_num_move_points-1; i++)
+ {
+ g_qeglobals.d_move_points[i] = g_qeglobals.d_move_points[i+1];
+ }
+ g_qeglobals.d_num_move_points--;
+ }
+}
+
+/*
+==================
+ColumnSelected
+==================
+*/
+bool ColumnSelected(patchMesh_t* p, int nCol)
+{
+ for (int i = 0; i < p->height; i++)
+ {
+ if (PointInMoveList(p->ctrl[nCol][i].xyz) == -1)
+ return false;
+ }
+ return true;
+}
+
+/*
+==================
+AddPoint
+==================
+*/
+void AddPoint(patchMesh_t* p, vec3_t v, bool bWeldOrDrill = true)
+{
+ int nDim1 = (g_pParentWnd->ActiveXY()->GetViewType() == YZ) ? 1 : 0;
+ int nDim2 = (g_pParentWnd->ActiveXY()->GetViewType() == XY) ? 1 : 2;
+ g_qeglobals.d_move_points[g_qeglobals.d_num_move_points++] = v;
+ if ((g_bPatchWeld || g_bPatchDrillDown) && bWeldOrDrill)
+ {
+ for ( int i = 0 ; i < p->width ; i++ )
+ {
+ for ( int j = 0 ; j < p->height ; j++ )
+ {
+ if (g_bPatchWeld)
+ {
+ if ( VectorCompare(v, p->ctrl[i][j].xyz)
+ && PointInMoveList(p->ctrl[i][j].xyz) == -1)
+ {
+ g_qeglobals.d_move_points[g_qeglobals.d_num_move_points++] = p->ctrl[i][j].xyz;
+ continue;
+ }
+ }
+ if (g_bPatchDrillDown && g_nPatchClickedView != W_CAMERA)
+ {
+ if ( (fabs(v[nDim1] - p->ctrl[i][j].xyz[nDim1]) <= EQUAL_EPSILON)
+ &&(fabs(v[nDim2] - p->ctrl[i][j].xyz[nDim2]) <= EQUAL_EPSILON))
+ {
+ if (PointInMoveList(p->ctrl[i][j].xyz) == -1)
+ {
+ g_qeglobals.d_move_points[g_qeglobals.d_num_move_points++] = p->ctrl[i][j].xyz;
+ continue;
+ }
+ }
+#if 0
+ int l = 0;
+ for ( int k = 0; k < 2; k++ )
+ {
+ if (fabs(v[k] - p->ctrl[i][j].xyz[k]) > EQUAL_EPSILON)
+ continue;
+ l++;
+ }
+ if (l >= 2 && PointInMoveList(p->ctrl[i][j].xyz) == -1)
+ {
+ g_qeglobals.d_move_points[g_qeglobals.d_num_move_points++] = p->ctrl[i][j].xyz;
+ continue;
+ }
+#endif
+ }
+ }
+ }
+ }
+#if 0
+ if (g_qeglobals.d_num_move_points == 1)
+ {
+ // single point selected
+ // FIXME: the two loops can probably be reduced to one
+ for ( int i = 0 ; i < p->width ; i++ )
+ {
+ for ( int j = 0 ; j < p->height ; j++ )
+ {
+ int n = PointInMoveList(v);
+ if (n >= 0)
+ {
+ if (((i & 0x01) && (j & 0x01)) == 0)
+ {
+ // put any sibling fixed points
+ // into the inverse list
+ int p1, p2, p3, p4;
+ p1 = i + 2;
+ p2 = i - 2;
+ p3 = j + 2;
+ p4 = j - 2;
+ if (p1 < p->width)
+ {
+
+ }
+ if (p2 >= 0)
+ {
+ }
+ if (p3 < p->height)
+ {
+ }
+ if (p4 >= 0)
+ {
+ }
+ }
+ }
+ }
+ }
+ }
+#endif
+}
+
+/*
+==================
+SelectRow
+==================
+*/
+void SelectRow(patchMesh_t* p, int nRow, bool bMulti)
+{
+ if (!bMulti)
+ g_qeglobals.d_num_move_points = 0;
+ for (int i = 0; i < p->width; i++)
+ {
+ AddPoint(p, p->ctrl[i][nRow].xyz, false);
+ }
+ //Sys_Printf("Selected Row %d\n", nRow);
+}
+
+/*
+==================
+SelectColumn
+==================
+*/
+void SelectColumn(patchMesh_t* p, int nCol, bool bMulti)
+{
+ if (!bMulti)
+ g_qeglobals.d_num_move_points = 0;
+ for (int i = 0; i < p->height; i++)
+ {
+ AddPoint(p, p->ctrl[nCol][i].xyz, false);
+ }
+ //Sys_Printf("Selected Col %d\n", nCol);
+}
+
+
+/*
+==================
+AddPatchMovePoint
+==================
+*/
+void AddPatchMovePoint(vec3_t v, bool bMulti, bool bFull)
+{
+ if (!g_bSameView && !bMulti && !bFull)
+ {
+ g_bSameView = true;
+ return;
+ }
+
+ for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ patchMesh_t* p = pb->pPatch;
+ for ( int i = 0 ; i < p->width ; i++ )
+ {
+ for ( int j = 0 ; j < p->height ; j++ )
+ {
+ if (VectorCompare(v, p->ctrl[i][j].xyz))
+ {
+ if (PointInMoveList(p->ctrl[i][j].xyz) == -1)
+ {
+ if (bFull) // if we want the full row/col this is on
+ {
+ SelectColumn(p, i, bMulti);
+ }
+ else
+ {
+ if (!bMulti)
+ g_qeglobals.d_num_move_points = 0;
+ AddPoint(p, p->ctrl[i][j].xyz);
+ //Sys_Printf("Selected col:row %d:%d\n", i, j);
+ }
+ //--if (!bMulti)
+ return;
+ }
+ else
+ {
+ if (bFull)
+ {
+ if (ColumnSelected(p, i))
+ {
+ SelectRow(p, j, bMulti);
+ }
+ else
+ {
+ SelectColumn(p, i, bMulti);
+ }
+ return;
+ }
+ if (g_bSameView)
+ {
+ RemovePointFromMoveList(v);
+ return;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+/*
+==================
+Patch_UpdateSelected
+==================
+*/
+void Patch_UpdateSelected(vec3_t vMove)
+{
+ int i, j;
+ for (i=0 ; i < g_qeglobals.d_num_move_points ; i++)
+ {
+ VectorAdd (g_qeglobals.d_move_points[i], vMove, g_qeglobals.d_move_points[i]);
+ if (g_qeglobals.d_num_move_points == 1)
+ {
+ }
+ }
+
+ //--patchMesh_t* p = &patchMeshes[g_nSelectedPatch];
+ for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ patchMesh_t* p = pb->pPatch;
+
+
+ g_qeglobals.d_numpoints = 0;
+ for (i = 0 ; i < p->width ; i++ )
+ {
+ for ( j = 0 ; j < p->height ; j++ )
+ {
+ VectorCopy (p->ctrl[i][j].xyz, g_qeglobals.d_points[g_qeglobals.d_numpoints]);
+ if (g_qeglobals.d_numpoints < MAX_POINTS-1)
+ {
+ g_qeglobals.d_numpoints++;
+ }
+ }
+ }
+
+ vec3_t vMin, vMax;
+ Patch_CalcBounds(p, vMin, vMax);
+ Brush_RebuildBrush(p->pSymbiot, vMin, vMax);
+ }
+ }
+ //Brush_Free(p->pSymbiot);
+ //Select_Brush(AddBrushForPatch(g_nSelectedPatch));
+}
+
+
+
+/*
+===============
+SampleSinglePatch
+===============
+*/
+void SampleSinglePatch (float ctrl[3][3][5], float u, float v, float out[5]) {
+ float vCtrl[3][5];
+ int vPoint;
+ int axis;
+
+ // find the control points for the v coordinate
+ for (vPoint = 0 ; vPoint < 3 ; vPoint++)
+ {
+ for (axis = 0 ; axis < 5 ; axis++)
+ {
+ float a, b, c;
+ float qA, qB, qC;
+
+ a = ctrl[0][vPoint][axis];
+ b = ctrl[1][vPoint][axis];
+ c = ctrl[2][vPoint][axis];
+ qA = a - 2 * b + c;
+ qB = 2 * b - 2 * a;
+ qC = a;
+
+ vCtrl[vPoint][axis] = qA * u * u + qB * u + qC;
+ }
+ }
+
+ // interpolate the v value
+ for (axis = 0 ; axis < 5 ; axis++)
+ {
+ float a, b, c;
+ float qA, qB, qC;
+
+ a = vCtrl[0][axis];
+ b = vCtrl[1][axis];
+ c = vCtrl[2][axis];
+ qA = a - 2 * b + c;
+ qB = 2 * b - 2 * a;
+ qC = a;
+
+ out[axis] = qA * v * v + qB * v + qC;
+ }
+}
+
+/*
+===================
+DrawSinglePatch
+===================
+*/
+void DrawSinglePatch (float ctrl[3][3][5], bool bPoints)
+{
+ int i, j;
+ float u, v;
+ float verts[CBLOCK_SUBDIVISIONS+1][CBLOCK_SUBDIVISIONS+1][5];
+
+ for (i = 0 ; i <= CBLOCK_SUBDIVISIONS ; i++)
+ {
+ for (j = 0 ; j <= CBLOCK_SUBDIVISIONS ; j++)
+ {
+ u = (float)i / CBLOCK_SUBDIVISIONS;
+ v = (float)j / CBLOCK_SUBDIVISIONS;
+ SampleSinglePatch (ctrl, u, v, verts[i][j]);
+ }
+ }
+ // at this point we have
+
+ int nCount = -1;
+ for (i = 0 ; i < CBLOCK_SUBDIVISIONS ; i++)
+ {
+ qglBegin (GL_QUAD_STRIP);
+
+ for (j = 0 ; j <= CBLOCK_SUBDIVISIONS ; j++)
+ {
+ qglTexCoord2fv( verts[i+1][j] + 3 );
+ qglVertex3fv( verts[i+1][j] );
+/*
+ if (nCount >= 0)
+ {
+ VectorCopy(verts[i+1][j], vNormals[nCount]);
+ }
+ nCount++;
+ if (nCount == 3)
+ {
+ VectorSubtract(vNormals[0], vNormals[1], vNormals[0]);
+ VectorSubtract(vNormals[1], vNormals[2], vNormals[1]);
+ CrossProduct(vNormals[0], vNormals[1], vNormals[2]);
+ //VectorNormalize(vNormals[2]);
+ qglNormal3fv(vNormals[2]);
+ nCount = -1;
+ }
+*/
+ qglTexCoord2fv( verts[i][j] + 3 );
+ qglVertex3fv( verts[i][j] );
+/*
+ VectorCopy(verts[i][j], vNormals[nCount]);
+ nCount++;
+ if (nCount == 3)
+ {
+ VectorSubtract(vNormals[0], vNormals[1], vNormals[0]);
+ VectorSubtract(vNormals[1], vNormals[2], vNormals[1]);
+ CrossProduct(vNormals[0], vNormals[1], vNormals[2]);
+ //VectorNormalize(vNormals[2]);
+ qglNormal3fv(vNormals[2]);
+ nCount = -1;
+ }
+*/
+ }
+ qglEnd ();
+ }
+
+}
+
+/*
+=================
+DrawPatchMesh
+=================
+*/
+//FIXME: this routine needs to be reorganized.. should be about 1/4 the size and complexity
+void DrawPatchMesh( patchMesh_t *pm, bool bPoints, bool bShade = false ) {
+ int i, j, k, l;
+ float ctrl[3][3][5];
+
+ bool bOverlay = pm->bOverlay;
+ int nDrawMode = g_pParentWnd->GetCamera()->Camera().draw_mode;
+
+ //--float fColor[3];
+ //--if (bShade)
+ //--{
+ //-- face_t *f = pm->pSymbiot->brush_faces;
+ //-- _SetColor(f, fColor);
+ //--}
+ if (g_PrefsDlg.m_bDisplayLists)
+ {
+ if (pm->bDirty || pm->nListID <= 0)
+ {
+ if (pm->nListID <= 0)
+ pm->nListID = qglGenLists(1);
+ if (pm->nListID > 0)
+ {
+ qglNewList(pm->nListID, GL_COMPILE_AND_EXECUTE);
+ }
+
+
+
+ if (pm->type != PATCH_TRIANGLE)
+ {
+ //vec3_t *vMeshData = new vec3_t[pm->width * pm->height];
+
+ // wasteful
+ if (g_PrefsDlg.m_bGLLighting)
+ {
+ Patch_MeshNormals(pm);
+ for (i = 0; i < pm->width; i++)
+ {
+ for (j = 0; j < pm->height; j++)
+ {
+ //VectorCopy(pm->ctrl[i][j].xyz, vMeshData[(j * pm->width) + i]);
+ qglNormal3fv(pm->ctrl[i][j].normal);
+ }
+ }
+ }
+
+ for ( i = 0 ; i + 2 < pm->width ; i += 2 )
+ {
+ for ( j = 0 ; j + 2 < pm->height ; j += 2 )
+ {
+
+ for ( k = 0 ; k < 3 ; k++ )
+ {
+ vec3_t vAvg;
+ vAvg[0] = vAvg[1] = vAvg[2] = 0;
+ for ( l = 0 ; l < 3 ; l++ )
+ {
+ ctrl[k][l][0] = pm->ctrl[ i + k ][ j + l ].xyz[ 0 ];
+ ctrl[k][l][1] = pm->ctrl[ i + k ][ j + l ].xyz[ 1 ];
+ ctrl[k][l][2] = pm->ctrl[ i + k ][ j + l ].xyz[ 2 ];
+ ctrl[k][l][3] = pm->ctrl[ i + k ][ j + l ].xyz[ 3 ];
+ ctrl[k][l][4] = pm->ctrl[ i + k ][ j + l ].xyz[ 4 ];
+
+ if (g_PrefsDlg.m_bGLLighting)
+ {
+ qglNormal3fv(pm->ctrl[i+k][j+l].normal);
+ }
+ }
+
+ }
+
+//-- if (g_pParentWnd->GetCamera()->Camera().draw_mode == cd_texture)
+//-- {
+//-- VectorCopy(pm->ctrl[i][j].normal, plane.normal);
+//-- float shade = SetShadeForPlane(&plane);
+//-- qtexture_t *q = pm->d_texture;
+//-- vec3_t vColor;
+//--
+//-- vColor[0] = shade;// * q->color[0];
+//-- vColor[1] = shade;// * q->color[1];
+//-- vColor[2] = shade;// * q->color[2];
+//-- qglColor3fv(vColor);
+//-- }
+
+
+//-- if (g_PrefsDlg.m_bGLLighting)
+//-- {
+//-- //qglNormal3fv(pm->ctrl[i][j].normal);
+//-- }
+ DrawSinglePatch( ctrl, bPoints );
+ }
+ }
+
+ // we have an array of clean control points
+ //
+ /*
+ qglMap2f(GL_MAP2_NORMAL, 0, 1, 3, 3, 0, 1, 9, 3, (float*)&vMeshData);
+ for (i = 0; i < pm->width; i++)
+ {
+ for (j = 0; j < pm->height; j++)
+ {
+ qglEvalPoint2(i, j);
+ }
+ }
+
+ delete []vMeshData;
+ */
+ }
+ else
+ {
+ qglBegin (GL_TRIANGLES);
+ qglTexCoord2fv( pm->ctrl[0][0].st);
+ qglVertex3fv( pm->ctrl[0][0].xyz);
+ qglTexCoord2fv( pm->ctrl[2][0].st);
+ qglVertex3fv( pm->ctrl[2][0].xyz);
+ qglTexCoord2fv( pm->ctrl[2][2].st);
+ qglVertex3fv( pm->ctrl[2][2].xyz);
+ qglEnd();
+ }
+
+ if (pm->nListID > 0)
+ {
+ qglEndList();
+ pm->bDirty = false;
+ }
+ }
+ else
+ {
+ qglCallList(pm->nListID);
+ }
+ }
+ else
+ {
+ for ( i = 0 ; i + 2 < pm->width ; i += 2 )
+ {
+ for ( j = 0 ; j + 2 < pm->height ; j += 2 )
+ {
+ for ( k = 0 ; k < 3 ; k++ )
+ {
+ for ( l = 0 ; l < 3 ; l++ )
+ {
+ ctrl[k][l][0] = pm->ctrl[ i + k ][ j + l ].xyz[ 0 ];
+ ctrl[k][l][1] = pm->ctrl[ i + k ][ j + l ].xyz[ 1 ];
+ ctrl[k][l][2] = pm->ctrl[ i + k ][ j + l ].xyz[ 2 ];
+ ctrl[k][l][3] = pm->ctrl[ i + k ][ j + l ].xyz[ 3 ];
+ ctrl[k][l][4] = pm->ctrl[ i + k ][ j + l ].xyz[ 4 ];
+ }
+ }
+ //--if (bShade)
+ //--{
+ //-- _DecColor(fColor);
+ //--}
+ DrawSinglePatch( ctrl, bPoints );
+ }
+ }
+ }
+
+ vec3_t* pSelectedPoints[256];
+ int nIndex = 0;
+
+ qglPushAttrib(GL_CURRENT_BIT);
+ //--qglDisable(GL_BLEND);
+ //--qglDisable (GL_DEPTH_TEST);
+ //qglDisable (GL_TEXTURE_2D);
+
+ bool bDisabledLighting = qglIsEnabled(GL_LIGHTING);
+ if (bDisabledLighting)
+ {
+ qglDisable(GL_LIGHTING);
+ }
+
+
+ // FIXME: this bend painting code needs to be rolled up significantly as it is a cluster fuck right now
+ if (bPoints && (g_qeglobals.d_select_mode == sel_curvepoint || g_qeglobals.d_select_mode == sel_area || g_bPatchBendMode || g_bPatchInsertMode))
+ {
+ bOverlay = false;
+
+ // bending or inserting
+ if (g_bPatchBendMode || g_bPatchInsertMode)
+ {
+ qglPointSize(6);
+ if (g_bPatchAxisOnRow)
+ {
+ qglColor3f(1, 0, 1);
+ qglBegin(GL_POINTS);
+ for (i = 0; i < pm->width; i++)
+ {
+ qglVertex3fv(reinterpret_cast<float(*)>(&pm->ctrl[i][g_nPatchAxisIndex].xyz));
+ }
+ qglEnd();
+
+ // could do all of this in one loop but it was pretty messy
+ if (g_bPatchInsertMode)
+ {
+ qglColor3f(0, 0, 1);
+ qglBegin(GL_POINTS);
+ for (i = 0; i < pm->width; i++)
+ {
+ qglVertex3fv(reinterpret_cast<float(*)>(&pm->ctrl[i][g_nPatchAxisIndex].xyz));
+ qglVertex3fv(reinterpret_cast<float(*)>(&pm->ctrl[i][g_nPatchAxisIndex+1].xyz));
+ }
+ qglEnd();
+ }
+ else
+ {
+ if (g_nPatchBendState == BEND_SELECT_EDGE || g_nPatchBendState == BEND_BENDIT || g_nPatchBendState == BEND_SELECT_ORIGIN)
+ {
+ qglColor3f(0, 0, 1);
+ qglBegin(GL_POINTS);
+ if (g_nPatchBendState == BEND_SELECT_ORIGIN)
+ {
+ qglVertex3fv(g_vBendOrigin);
+ }
+ else
+ {
+ for (i = 0; i < pm->width; i++)
+ {
+ if (g_bPatchLowerEdge)
+ {
+ for (j = 0; j < g_nPatchAxisIndex; j++)
+ qglVertex3fv(reinterpret_cast<float(*)>(&pm->ctrl[i][j].xyz));
+ }
+ else
+ {
+ for (j = pm->height-1; j > g_nPatchAxisIndex; j--)
+ qglVertex3fv(reinterpret_cast<float(*)>(&pm->ctrl[i][j].xyz));
+ }
+ }
+ }
+ qglEnd();
+ }
+ }
+ }
+ else
+ {
+ qglColor3f(1, 0, 1);
+ qglBegin(GL_POINTS);
+ for (i = 0; i < pm->height; i++)
+ {
+ qglVertex3fv(reinterpret_cast<float(*)>(&pm->ctrl[g_nPatchAxisIndex][i].xyz));
+ }
+ qglEnd();
+
+ // could do all of this in one loop but it was pretty messy
+ if (g_bPatchInsertMode)
+ {
+ qglColor3f(0, 0, 1);
+ qglBegin(GL_POINTS);
+ for (i = 0; i < pm->height; i++)
+ {
+ qglVertex3fv(reinterpret_cast<float(*)>(&pm->ctrl[g_nPatchAxisIndex][i].xyz));
+ qglVertex3fv(reinterpret_cast<float(*)>(&pm->ctrl[g_nPatchAxisIndex+1][i].xyz));
+ }
+ qglEnd();
+ }
+ else
+ {
+ if (g_nPatchBendState == BEND_SELECT_EDGE || g_nPatchBendState == BEND_BENDIT || g_nPatchBendState == BEND_SELECT_ORIGIN)
+ {
+ qglColor3f(0, 0, 1);
+ qglBegin(GL_POINTS);
+ for (i = 0; i < pm->height; i++)
+ {
+ if (g_nPatchBendState == BEND_SELECT_ORIGIN)
+ {
+ qglVertex3fv(reinterpret_cast<float(*)>(&pm->ctrl[g_nBendOriginIndex][i].xyz));
+ }
+ else
+ {
+ if (g_bPatchLowerEdge)
+ {
+ for (j = 0; j < g_nPatchAxisIndex; j++)
+ qglVertex3fv(reinterpret_cast<float(*)>(&pm->ctrl[j][i].xyz));
+ }
+ else
+ {
+ for (j = pm->width-1; j > g_nPatchAxisIndex; j--)
+ qglVertex3fv(reinterpret_cast<float(*)>(&pm->ctrl[j][i].xyz));
+ }
+ }
+ }
+ qglEnd();
+ }
+ }
+ }
+ }
+ else // just painting the grid for selection
+ {
+ qglPointSize(6);
+ for ( i = 0 ; i < pm->width ; i++ )
+ {
+ for ( j = 0 ; j < pm->height ; j++ )
+ {
+ qglBegin(GL_POINTS);
+ // FIXME: need to not do loop lookups inside here
+ int n = PointValueInMoveList(pm->ctrl[i][j].xyz);
+ if (n >= 0)
+ {
+ pSelectedPoints[nIndex++] = reinterpret_cast<float(*)[3]>(&pm->ctrl[i][j].xyz);
+ }
+
+ if (i & 0x01 || j & 0x01)
+ qglColor3f(1, 0, 1);
+ else
+ qglColor3f(0, 1, 0);
+ qglVertex3fv(pm->ctrl[i][j].xyz);
+ qglEnd();
+ }
+ }
+ }
+ if (nIndex > 0)
+ {
+ qglBegin(GL_POINTS);
+ qglColor3f(0, 0, 1);
+ while (nIndex-- > 0)
+ {
+ qglVertex3fv(*pSelectedPoints[nIndex]);
+ }
+ qglEnd();
+ }
+ }
+
+ if (bOverlay)
+ {
+ qglPointSize(6);
+ qglColor3f(0.5, 0.5, 0.5);
+ for ( i = 0 ; i < pm->width ; i++ )
+ {
+ qglBegin(GL_POINTS);
+ for ( j = 0 ; j < pm->height ; j++ )
+ {
+ if (i & 0x01 || j & 0x01)
+ qglColor3f(0.5, 0, 0.5);
+ else
+ qglColor3f(0, 0.5, 0);
+ qglVertex3fv(pm->ctrl[i][j].xyz);
+ }
+ qglEnd();
+ }
+ }
+ //--qglEnable (GL_TEXTURE_2D);
+ //--qglEnable (GL_DEPTH_TEST);
+
+ if (bDisabledLighting)
+ {
+ qglEnable(GL_LIGHTING);
+ }
+
+ qglPopAttrib();
+
+}
+
+/*
+==================
+Patch_DrawXY
+==================
+*/
+void Patch_DrawXY(patchMesh_t *pm)
+{
+ qglPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
+ if (pm->bSelected)
+ {
+ qglColor3fv(g_qeglobals.d_savedinfo.colors[COLOR_SELBRUSHES]);
+ //qglDisable (GL_LINE_STIPPLE);
+ //qglLineWidth (1);
+ }
+ else
+ qglColor3fv(g_qeglobals.d_savedinfo.colors[COLOR_BRUSHES]);
+
+ DrawPatchMesh( pm , pm->bSelected );
+ qglPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
+ if (pm->bSelected)
+ {
+ //qglLineWidth (2);
+ //qglEnable (GL_LINE_STIPPLE);
+ }
+}
+
+/*
+==================
+Patch_DrawCam
+==================
+*/
+void Patch_DrawCam(patchMesh_t *pm)
+{
+ qglColor3f (1,1,1);
+ qglPushAttrib(GL_ALL_ATTRIB_BITS);
+
+ if (g_bPatchWireFrame)
+ {
+ qglDisable( GL_CULL_FACE );
+ qglPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
+ qglDisable(GL_TEXTURE_2D);
+ if (g_PrefsDlg.m_bGLLighting)
+ {
+ qglDisable(GL_LIGHTING);
+ }
+ DrawPatchMesh( pm , pm->bSelected, true );
+ if (g_PrefsDlg.m_bGLLighting)
+ {
+ qglEnable(GL_LIGHTING);
+ }
+ qglEnable( GL_CULL_FACE );
+ }
+ else
+ {
+ if (g_PrefsDlg.m_bGLLighting)
+ {
+ //qglEnable(GL_NORMALIZE);
+ }
+ qglEnable( GL_CULL_FACE );
+ qglCullFace(GL_FRONT);
+ qglBindTexture (GL_TEXTURE_2D, pm->d_texture->texture_number);
+
+ if (pm->d_texture->bFromShader && pm->d_texture->fTrans < 1.0)
+ {
+ //qglEnable ( GL_BLEND );
+ //qglBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ qglColor4f(pm->d_texture->color[0], pm->d_texture->color[1], pm->d_texture->color[2], pm->d_texture->fTrans);
+ }
+ DrawPatchMesh( pm , pm->bSelected, true );
+
+ qglCullFace(GL_BACK);
+ //qglDisable(GL_TEXTURE_2D);
+ qglPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
+
+ qglDisable ( GL_BLEND );
+ DrawPatchMesh( pm , pm->bSelected, true );
+ }
+
+#if 0 // this paints normal indicators on the ctrl points
+ //--qglDisable (GL_DEPTH_TEST);
+ qglDisable (GL_TEXTURE_2D);
+ qglColor3f (1,1,1);
+
+ for (int i = 0; i < pm->width; i++)
+ {
+ for (int j = 0; j < pm->height; j++)
+ {
+ vec3_t temp;
+ qglBegin (GL_LINES);
+ qglVertex3fv (pm->ctrl[i][j].xyz);
+ VectorMA (pm->ctrl[i][j].xyz, 8, pm->ctrl[i][j].normal, temp);
+ qglVertex3fv (temp);
+ qglEnd ();
+ }
+ }
+ qglEnable (GL_TEXTURE_2D);
+ //--qglEnable (GL_DEPTH_TEST);
+#endif
+
+
+ qglPopAttrib();
+}
+
+
+
+
+void ConvexHullForSection( float section[2][4][7] ) {
+}
+
+void BrushesForSection( float section[2][4][7] ) {
+}
+
+//
+//================
+//Patch_BuildPoints
+//================
+void Patch_BuildPoints (brush_t *b)
+{
+ face_t *f;
+ b->patchBrush = false;
+ for (f=b->brush_faces ; f ; f=f->next)
+ {
+ if (f->texdef.flags & SURF_PATCH)
+ {
+ b->patchBrush = true;
+ //vec3_t vMin, vMax;
+ //Patch_CalcBounds(&patchMeshes[b->nPatchID], vMin, vMax);
+ //VectorCopy(vMin, b->mins);
+ //VectorCopy(vMax, b->maxs);
+ break;
+ }
+ }
+}
+
+
+
+//
+//===============
+//Patch_WriteFile
+//===============
+//
+#if 0
+void Patch_WriteFile (char *name)
+{
+ char patchName[1024];
+ time_t ltime;
+ strcpy(patchName, name);
+ StripExtension (patchName);
+ strcat (patchName, ".patch");
+
+ FILE *file = fopen(patchName, "w");
+ if (file)
+ {
+ time(&ltime);
+ fprintf (file, "// %s saved on %s\n", name, ctime(&ltime) );
+
+ for (int i = 0; i < numPatchMeshes; i++)
+ {
+ fprintf(file, "{\n");
+ fprintf(file, " %s\n", patchMeshes[i].d_texture->name);
+ fprintf(file, " ( %i %i %i ) \n", patchMeshes[i].width, patchMeshes[i].height, patchMeshes[i].negative);
+ for (int w = 0; w < patchMeshes[i].width; w++)
+ {
+ for (int h = 0; h < patchMeshes[i].height; h++)
+ {
+ fprintf(file, " ( ");
+ for (int k = 0; k < 5; k++)
+ {
+ float f = patchMeshes[i].ctrl[w][h][k];
+ if (f == int(f))
+ fprintf(file, "%i ", (int)f);
+ else
+ fprintf(file, "%f ", f);
+ }
+ fprintf(file, ")\n");
+ }
+ }
+ fprintf(file, "}\n");
+ }
+ fclose(file);
+ }
+}
+#endif
+
+/*
+==================
+Patch_Move
+==================
+*/
+void Patch_Move(patchMesh_t *pm, const vec3_t vMove, bool bRebuild)
+{
+ pm->bDirty = true;
+ for (int w = 0; w < pm->width; w++)
+ {
+ for (int h = 0; h < pm->height; h++)
+ {
+ VectorAdd(pm->ctrl[w][h].xyz, vMove, pm->ctrl[w][h].xyz);
+ }
+ }
+ if (bRebuild)
+ {
+ vec3_t vMin, vMax;
+ Patch_CalcBounds(pm, vMin, vMax);
+ //Brush_RebuildBrush(patchMeshes[n].pSymbiot, vMin, vMax);
+ }
+ UpdatePatchInspector();
+
+}
+
+/*
+==================
+Patch_ApplyMatrix
+==================
+*/
+void Patch_ApplyMatrix(patchMesh_t *p, const vec3_t vOrigin, const vec3_t vMatrix[3], bool bSnap)
+{
+ vec3_t vTemp;
+
+ for (int w = 0; w < p->width; w++)
+ {
+ for (int h = 0; h < p->height; h++)
+ {
+ if ( (g_qeglobals.d_select_mode == sel_curvepoint || g_bPatchBendMode)
+ && PointInMoveList(p->ctrl[w][h].xyz) == -1)
+ continue;
+ VectorSubtract (p->ctrl[w][h].xyz, vOrigin, vTemp);
+ for (int j = 0; j < 3; j++)
+ {
+ p->ctrl[w][h].xyz[j] = DotProduct(vTemp, vMatrix[j]) + vOrigin[j];
+ if (bSnap)
+ {
+ p->ctrl[w][h].xyz[j] = floor(p->ctrl[w][h].xyz[j] + 0.5);
+ }
+ }
+ }
+ }
+ vec3_t vMin, vMax;
+ Patch_CalcBounds(p, vMin, vMax);
+ Brush_RebuildBrush(p->pSymbiot, vMin, vMax);
+}
+
+/*
+==================
+Patch_EditPatch
+==================
+*/
+void Patch_EditPatch()
+{
+ //--patchMesh_t* p = &patchMeshes[n];
+ g_qeglobals.d_numpoints = 0;
+ g_qeglobals.d_num_move_points = 0;
+
+ for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ patchMesh_t* p = pb->pPatch;
+ for ( int i = 0 ; i < p->width ; i++ )
+ {
+ for ( int j = 0 ; j < p->height ; j++ )
+ {
+ VectorCopy (p->ctrl[i][j].xyz, g_qeglobals.d_points[g_qeglobals.d_numpoints]);
+ if (g_qeglobals.d_numpoints < MAX_POINTS-1)
+ {
+ g_qeglobals.d_numpoints++;
+ }
+ }
+ }
+ }
+ }
+ g_qeglobals.d_select_mode = sel_curvepoint;
+ //--g_nSelectedPatch = n;
+}
+
+
+
+/*
+==================
+Patch_Deselect
+==================
+*/
+//FIXME: need all sorts of asserts throughout a lot of this crap
+void Patch_Deselect()
+{
+ //--g_nSelectedPatch = -1;
+ clearSelection();
+
+ for (brush_t *b = selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ {
+ if (b->patchBrush)
+ {
+ b->pPatch->bSelected = false;
+ }
+ }
+
+ //for (int i = 0; i < numPatchMeshes; i++)
+ // patchMeshes[i].bSelected = false;
+
+ if (g_bPatchBendMode)
+ Patch_BendToggle();
+ if (g_bPatchInsertMode)
+ Patch_InsDelToggle();
+}
+
+
+/*
+==================
+Patch_Select
+==================
+*/
+void Patch_Select(patchMesh_t *p)
+{
+ // maintained for point manip.. which i need to fix as this
+ // is pf error prone
+ //--g_nSelectedPatch = n;
+ p->bSelected = true;
+}
+
+
+/*
+==================
+Patch_Deselect
+==================
+*/
+void Patch_Deselect(patchMesh_t *p)
+{
+ p->bSelected = false;
+}
+
+
+/*
+==================
+Patch_Delete
+==================
+*/
+void Patch_Delete(patchMesh_t *p)
+{
+ p->pSymbiot->pPatch = NULL;
+ p->pSymbiot->patchBrush = false;
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+#ifdef _DEBUG
+ if (!p->pData)
+ Sys_Printf("WARNING: unexpected IPluginTexdef* is NULL in Patch_Delete\n");
+ else
+#endif
+ {
+ GETPLUGINTEXDEF(p)->DecRef();
+ p->pData = NULL;
+ }
+ }
+ free(p);
+ p = NULL;
+
+ // bump the array down
+ //for (int i = n; i < numPatchMeshes; i++)
+ //{
+ // patchMeshes[i].pSymbiot->nPatchID--;
+ // patchMeshes[i] = patchMeshes[i+1];
+ //}
+ //numPatchMeshes--;
+ UpdatePatchInspector();
+}
+
+
+/*
+==================
+Patch_Scale
+==================
+*/
+void Patch_Scale(patchMesh_t *p, const vec3_t vOrigin, const vec3_t vAmt, bool bRebuild)
+{
+
+ for (int w = 0; w < p->width; w++)
+ {
+ for (int h = 0; h < p->height; h++)
+ {
+ if (g_qeglobals.d_select_mode == sel_curvepoint && PointInMoveList(p->ctrl[w][h].xyz) == -1)
+ continue;
+ for (int i=0 ; i<3 ; i++)
+ {
+ p->ctrl[w][h].xyz[i] -= vOrigin[i];
+ p->ctrl[w][h].xyz[i] *= vAmt[i];
+ p->ctrl[w][h].xyz[i] += vOrigin[i];
+ }
+ }
+ }
+ if (bRebuild)
+ {
+ vec3_t vMin, vMax;
+ Patch_CalcBounds(p, vMin, vMax);
+ Brush_RebuildBrush(p->pSymbiot, vMin, vMax);
+ }
+ UpdatePatchInspector();
+}
+
+
+/*
+==================
+Patch_Cleanup
+==================
+*/
+void Patch_Cleanup()
+{
+ //--g_nSelectedPatch = -1;
+ //numPatchMeshes = 0;
+}
+
+
+
+/*
+==================
+Patch_SetView
+==================
+*/
+void Patch_SetView(int n)
+{
+ g_bSameView = (n == g_nPatchClickedView);
+ g_nPatchClickedView = n;
+}
+
+
+/*
+==================
+Patch_SetTexture
+==================
+*/
+// FIXME: need array validation throughout
+void Patch_SetTexture(patchMesh_t *p, texdef_t *tex_def, IPluginTexdef* pPlugTexdef)
+{
+ p->d_texture = Texture_ForName(tex_def->name);
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+#ifdef _DEBUG
+ if (!p->pData)
+ Sys_Printf("WARNING: unexpected p->pData is NULL in Patch_SetTexture\n");
+ else
+#endif
+ GETPLUGINTEXDEF(p)->DecRef();
+ if (pPlugTexdef)
+ {
+ p->pData = pPlugTexdef->Copy();
+ GETPLUGINTEXDEF(p)->Hook(p);
+ }
+ else
+ {
+ g_SurfaceTable.m_pfnPatchAlloc( p );
+ GETPLUGINTEXDEF(p)->SetDefaultTexdef();
+ }
+ }
+ UpdatePatchInspector();
+}
+
+
+/*
+==================
+Patch_DragScale
+==================
+*/
+bool Patch_DragScale(patchMesh_t *p, vec3_t vAmt, vec3_t vMove)
+{
+ vec3_t vMin, vMax, vScale, vTemp, vMid;
+ int i;
+
+ Patch_CalcBounds(p, vMin, vMax);
+
+ VectorSubtract(vMax, vMin, vTemp);
+
+ // if we are scaling in the same dimension the patch has no depth
+ for (i = 0; i < 3; i ++)
+ {
+ if (vTemp[i] == 0 && vMove[i] != 0)
+ {
+ //Patch_Move(n, vMove, true);
+ return false;
+ }
+ }
+
+ for (i=0 ; i<3 ; i++)
+ vMid[i] = (vMin[i] + ((vMax[i] - vMin[i]) / 2));
+
+ for (i = 0; i < 3; i++)
+ {
+ if (vAmt[i] != 0)
+ {
+ vScale[i] = 1.0 + vAmt[i] / vTemp[i];
+ }
+ else
+ {
+ vScale[i] = 1.0;
+ }
+ }
+
+ Patch_Scale(p, vMid, vScale, false);
+
+ VectorSubtract(vMax, vMin, vTemp);
+
+ Patch_CalcBounds(p, vMin, vMax);
+
+ VectorSubtract(vMax, vMin, vMid);
+
+ VectorSubtract(vMid, vTemp, vTemp);
+
+ VectorScale(vTemp, 0.5, vTemp);
+
+ // abs of both should always be equal
+ if (!VectorCompare(vMove, vAmt))
+ {
+ for (i = 0; i < 3; i++)
+ {
+ if (vMove[i] != vAmt[i])
+ vTemp[i] = -(vTemp[i]);
+ }
+ }
+
+ Patch_Move(p, vTemp);
+ return true;
+}
+
+
+/*
+==================
+Patch_AddRow
+==================
+*/
+void Patch_AddRow(patchMesh_t *p)
+{
+ vec3_t vMin, vMax, vTemp;
+ int i, j;
+
+
+ if (p->height+2 < MAX_PATCH_HEIGHT)
+ {
+ Patch_CalcBounds(p, vMin, vMax);
+ VectorSubtract(vMax, vMin, vTemp);
+ for (i = 0; i < 3; i++)
+ {
+ vTemp[i] /= p->height + 2;
+ }
+
+ for (j = 0; j < p->width; j++)
+ {
+ VectorCopy(p->ctrl[j][p->height].xyz, p->ctrl[j][p->height+1].xyz);
+ VectorCopy(p->ctrl[j][p->height].xyz, p->ctrl[j][p->height+2].xyz);
+ p->height += 2;
+ i = 1;
+ while (i < p->height)
+ {
+ VectorAdd(p->ctrl[j][i].xyz, vTemp, p->ctrl[j][i].xyz);
+ i++;
+ }
+ }
+
+ Patch_CalcBounds(p, vMin, vMax);
+ Brush_RebuildBrush(p->pSymbiot, vMin, vMax);
+ }
+ UpdatePatchInspector();
+}
+
+/*
+==================
+Patch_InsertColumn
+==================
+*/
+void Patch_InsertColumn(patchMesh_t *p, bool bAdd)
+{
+ int h, w, i, j;
+ vec3_t vTemp;
+
+ if (p->width + 2 >= MAX_PATCH_WIDTH)
+ return;
+
+ if (bAdd) // add column?
+ {
+ for (h = 0; h < p->height; h++)
+ {
+ j = p->width-1;
+ VectorSubtract(p->ctrl[j][h].xyz, p->ctrl[j-1][h].xyz, vTemp);
+ for (i = 0; i < 3; i++)
+ vTemp[i] /= 3;
+
+ memcpy(&p->ctrl[j+2][h],&p->ctrl[j][h], sizeof(drawVert_t));
+ memcpy(&p->ctrl[j][h],&p->ctrl[j-1][h], sizeof(drawVert_t));
+
+ VectorAdd(p->ctrl[j][h].xyz, vTemp, p->ctrl[j][h].xyz);
+ memcpy(&p->ctrl[j+1][h], &p->ctrl[j][h], sizeof(drawVert_t));
+ VectorAdd(p->ctrl[j+1][h].xyz, vTemp, p->ctrl[j+1][h].xyz);
+ }
+ }
+ else
+ {
+ for (h = 0; h < p->height; h++)
+ {
+ w = p->width-1;
+ while (w >= 0)
+ {
+ memcpy(&p->ctrl[w+2][h],&p->ctrl[w][h], sizeof(drawVert_t));
+ w--;
+ }
+ VectorSubtract(p->ctrl[1][h].xyz, p->ctrl[0][h].xyz, vTemp);
+ for (i = 0; i < 3; i++)
+ vTemp[i] /= 3;
+ VectorCopy(p->ctrl[0][h].xyz, p->ctrl[1][h].xyz);
+ VectorAdd(p->ctrl[1][h].xyz, vTemp, p->ctrl[1][h].xyz);
+ VectorCopy(p->ctrl[1][h].xyz, p->ctrl[2][h].xyz);
+ VectorAdd(p->ctrl[2][h].xyz, vTemp, p->ctrl[2][h].xyz);
+ }
+ }
+ p->width += 2;
+ UpdatePatchInspector();
+}
+
+
+/*
+==================
+Patch_InsertRow
+==================
+*/
+void Patch_InsertRow(patchMesh_t *p, bool bAdd)
+{
+ int h, w, i, j;
+ vec3_t vTemp;
+
+ if (p->height + 2 >= MAX_PATCH_HEIGHT)
+ return;
+
+ if (bAdd) // add column?
+ {
+ for (w = 0; w < p->width; w++)
+ {
+ j = p->height-1;
+ VectorSubtract(p->ctrl[w][j].xyz, p->ctrl[w][j-1].xyz, vTemp);
+ for (i = 0; i < 3; i++)
+ vTemp[i] /= 3;
+
+ memcpy(&p->ctrl[w][j+2],&p->ctrl[w][j], sizeof(drawVert_t));
+ memcpy(&p->ctrl[w][j],&p->ctrl[w][j-1], sizeof(drawVert_t));
+
+ VectorAdd(p->ctrl[w][j].xyz, vTemp, p->ctrl[w][j].xyz);
+ memcpy(&p->ctrl[w][j+1], &p->ctrl[w][j], sizeof(drawVert_t));
+ VectorAdd(p->ctrl[w][j+1].xyz, vTemp, p->ctrl[w][j+1].xyz);
+ }
+ }
+ else
+ {
+ for (w = 0; w < p->width; w++)
+ {
+ h = p->height-1;
+ while (h >= 0)
+ {
+ memcpy(&p->ctrl[w][h+2],&p->ctrl[w][h], sizeof(drawVert_t));
+ h--;
+ }
+ VectorSubtract(p->ctrl[w][1].xyz, p->ctrl[w][0].xyz, vTemp);
+ for (i = 0; i < 3; i++)
+ vTemp[i] /= 3;
+ VectorCopy(p->ctrl[w][0].xyz, p->ctrl[w][1].xyz);
+ VectorAdd(p->ctrl[w][1].xyz, vTemp, p->ctrl[w][1].xyz);
+ VectorCopy(p->ctrl[w][1].xyz, p->ctrl[w][2].xyz);
+ VectorAdd(p->ctrl[w][2].xyz, vTemp, p->ctrl[w][2].xyz);
+ }
+ }
+ p->height += 2;
+ UpdatePatchInspector();
+}
+
+
+/*
+==================
+Patch_RemoveRow
+==================
+*/
+void Patch_RemoveRow(patchMesh_t *p, bool bFirst)
+{
+
+ if (p->height <= MIN_PATCH_HEIGHT)
+ return;
+
+ p->height -= 2;
+
+ if (bFirst)
+ {
+ for (int w = 0; w < p->width; w++)
+ {
+ for (int h = 0; h < p->height; h++)
+ {
+ memcpy(&p->ctrl[w][h], &p->ctrl[w][h+2], sizeof(drawVert_t));
+ }
+ }
+ }
+ UpdatePatchInspector();
+}
+
+
+/*
+==================
+Patch_RemoveColumn
+==================
+*/
+void Patch_RemoveColumn(patchMesh_t *p, bool bFirst)
+{
+
+ if (p->width <= MIN_PATCH_WIDTH)
+ return;
+
+ p->width -= 2;
+
+ if (bFirst)
+ {
+ for (int h = 0; h < p->height; h++)
+ {
+ for (int w = 0; w < p->width; w++)
+ {
+ memcpy(&p->ctrl[w][h], &p->ctrl[w+2][h], sizeof(drawVert_t));
+ }
+ }
+ }
+ UpdatePatchInspector();
+}
+
+
+/*
+==================
+Patch_AdjustColumns
+==================
+*/
+void Patch_AdjustColumns(patchMesh_t *p, int nCols)
+{
+ vec3_t vTemp, vTemp2;
+ int i, w, h;
+
+ if (nCols & 0x01 || p->width + nCols < 3 || p->width + nCols > MAX_PATCH_WIDTH)
+ return;
+
+ // add in column adjustment
+ p->width += nCols;
+
+ for (h = 0; h < p->height; h++)
+ {
+ // for each column, we need to evenly disperse p->width number
+ // of points across the old bounds
+
+ // calc total distance to interpolate
+ VectorSubtract(p->ctrl[p->width - 1 - nCols][h].xyz, p->ctrl[0][h].xyz, vTemp);
+
+ // amount per cycle
+ for (i = 0; i < 3; i ++)
+ {
+ vTemp2[i] = vTemp[i] / (p->width - 1);
+ }
+
+ // move along
+ for (w = 0; w < p->width-1; w++)
+ {
+ VectorAdd(p->ctrl[w][h].xyz, vTemp2, p->ctrl[w+1][h].xyz);
+ }
+
+ }
+ for ( w = 0 ; w < p->width ; w++ )
+ {
+ for ( h = 0 ; h < p->height ; h++ )
+ {
+ p->ctrl[w][h].st[0] = 4 * (float)w / (p->width - 1);
+ p->ctrl[w][h].st[1] = 4 * (float)h / (p->height - 1);
+ }
+ }
+ UpdatePatchInspector();
+}
+
+
+/*
+==================
+Patch_AdjustRows
+==================
+*/
+void Patch_AdjustRows(patchMesh_t *p, int nRows)
+{
+ vec3_t vTemp, vTemp2;
+ int i, w, h;
+
+ if (nRows & 0x01 || p->height + nRows < 3 || p->height + nRows > MAX_PATCH_HEIGHT)
+ return;
+
+ // add in column adjustment
+ p->height += nRows;
+
+ for (w = 0; w < p->width; w++)
+ {
+ // for each row, we need to evenly disperse p->height number
+ // of points across the old bounds
+
+ // calc total distance to interpolate
+ VectorSubtract(p->ctrl[w][p->height - 1 - nRows].xyz, p->ctrl[w][0].xyz, vTemp);
+
+ //vTemp[0] = vTemp[1] = vTemp[2] = 0;
+ //for (h = 0; h < p->height - nRows; h ++)
+ //{
+ // VectorAdd(vTemp, p->ctrl[w][h], vTemp);
+ //}
+
+ // amount per cycle
+ for (i = 0; i < 3; i ++)
+ {
+ vTemp2[i] = vTemp[i] / (p->height - 1);
+ }
+
+ // move along
+ for (h = 0; h < p->height-1; h++)
+ {
+ VectorAdd(p->ctrl[w][h].xyz, vTemp2, p->ctrl[w][h+1].xyz);
+ }
+
+ }
+ for ( w = 0 ; w < p->width ; w++ )
+ {
+ for ( h = 0 ; h < p->height ; h++ )
+ {
+ p->ctrl[w][h].st[0] = 4 * (float)w / (p->width - 1);
+ p->ctrl[w][h].st[1] = 4 * (float)h / (p->height - 1);
+ }
+ }
+ UpdatePatchInspector();
+}
+
+
+void Patch_DisperseRows()
+{
+ vec3_t vTemp, vTemp2;
+ int i, w, h;
+
+
+ for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ patchMesh_t *p = pb->pPatch;
+ Patch_Rebuild(p);
+ for (w = 0; w < p->width; w++)
+ {
+ // for each row, we need to evenly disperse p->height number
+ // of points across the old bounds
+
+ // calc total distance to interpolate
+ VectorSubtract(p->ctrl[w][p->height - 1].xyz, p->ctrl[w][0].xyz, vTemp);
+
+ //vTemp[0] = vTemp[1] = vTemp[2] = 0;
+ //for (h = 0; h < p->height - nRows; h ++)
+ //{
+ // VectorAdd(vTemp, p->ctrl[w][h], vTemp);
+ //}
+
+ // amount per cycle
+ for (i = 0; i < 3; i ++)
+ {
+ vTemp2[i] = vTemp[i] / (p->height - 1);
+ }
+
+ // move along
+ for (h = 0; h < p->height-1; h++)
+ {
+ VectorAdd(p->ctrl[w][h].xyz, vTemp2, p->ctrl[w][h+1].xyz);
+ }
+ Patch_Naturalize(p);
+
+ }
+ }
+ }
+ UpdatePatchInspector();
+
+}
+
+/*
+==================
+Patch_AdjustColumns
+==================
+*/
+void Patch_DisperseColumns()
+{
+ vec3_t vTemp, vTemp2;
+ int i, w, h;
+
+ for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ patchMesh_t *p = pb->pPatch;
+ Patch_Rebuild(p);
+
+ for (h = 0; h < p->height; h++)
+ {
+ // for each column, we need to evenly disperse p->width number
+ // of points across the old bounds
+
+ // calc total distance to interpolate
+ VectorSubtract(p->ctrl[p->width - 1][h].xyz, p->ctrl[0][h].xyz, vTemp);
+
+ // amount per cycle
+ for (i = 0; i < 3; i ++)
+ {
+ vTemp2[i] = vTemp[i] / (p->width - 1);
+ }
+
+ // move along
+ for (w = 0; w < p->width-1; w++)
+ {
+ VectorAdd(p->ctrl[w][h].xyz, vTemp2, p->ctrl[w+1][h].xyz);
+ }
+
+ }
+ Patch_Naturalize(p);
+ }
+ }
+ UpdatePatchInspector();
+}
+
+
+
+/*
+==================
+Patch_AdjustSelected
+==================
+*/
+void Patch_AdjustSelected(bool bInsert, bool bColumn, bool bFlag)
+{
+ bool bUpdate = false;
+ for (brush_t* pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ if (bInsert)
+ {
+ if (bColumn)
+ {
+ Patch_InsertColumn(pb->pPatch, bFlag);
+ }
+ else
+ {
+ Patch_InsertRow(pb->pPatch, bFlag);
+ }
+ }
+ else
+ {
+ if (bColumn)
+ {
+ Patch_RemoveColumn(pb->pPatch, bFlag);
+ }
+ else
+ {
+ Patch_RemoveRow(pb->pPatch, bFlag);
+ }
+ }
+ bUpdate = true;
+ vec3_t vMin, vMax;
+ patchMesh_t *p = pb->pPatch;
+ Patch_CalcBounds(p, vMin, vMax);
+ Brush_RebuildBrush(p->pSymbiot, vMin, vMax);
+ }
+ }
+ if (bUpdate)
+ {
+ Sys_UpdateWindows(W_ALL);
+ }
+}
+
+
+/*
+==================
+Patch_AdjustSelectedRowCols
+==================
+*/
+void Patch_AdjustSelectedRowCols(int nRows, int nCols)
+{
+ for (brush_t* pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ Patch_InsertColumn(pb->pPatch, false);
+ if (nRows != 0)
+ {
+ Patch_AdjustRows(pb->pPatch, nRows);
+ }
+
+ if (nCols != 0)
+ {
+ Patch_AdjustColumns(pb->pPatch, nCols);
+ }
+ }
+ }
+ UpdatePatchInspector();
+}
+
+
+
+void Parse1DMatrix(int x, float* p)
+{
+ GetToken(true); // (
+ for (int i = 0; i < x; i++)
+ {
+ GetToken(false);
+ p[i] = atof(token);
+ }
+ GetToken(true); // )
+}
+
+void Parse2DMatrix(int y, int x, float* p)
+{
+ GetToken(true); // (
+ for (int i = 0; i < y; i++)
+ {
+ Parse1DMatrix(x, p + i*x);
+ }
+ GetToken(true); // )
+}
+
+void Parse3DMatrix(int z, int y, int x, float* p)
+{
+ GetToken(true); // (
+ for (int i = 0; i < z; i++)
+ {
+ Parse2DMatrix(y, x, p + i*(x*MAX_PATCH_HEIGHT));
+ }
+ GetToken(true); // )
+}
+
+// parses a patch
+brush_t* Patch_Parse(bool bOld)
+{
+ //--if (bOld)
+ //--{
+ //-- return Patch_ParseOld();
+ //--}
+
+ GetToken(true);
+
+ if (strcmp(token, "{"))
+ return NULL;
+
+ patchMesh_t *pm = MakeNewPatch();
+
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+ GETPLUGINTEXDEF(pm)->ParsePatchTexdef();
+ }
+ else
+ {
+ // texture def
+ GetToken(true);
+
+ // band-aid
+ if (strcmp(token, "("))
+ {
+ pm->d_texture = Texture_ForName(token);
+ GetToken(true);
+ }
+ else
+ {
+ pm->d_texture = notexture;
+ Sys_Printf("Warning: Patch read with no texture, using notexture... \n");
+ }
+
+ if (strcmp(token, "("))
+ return NULL;
+
+ // width, height, flags (currently only negative)
+ GetToken(false);
+ pm->width = atoi(token);
+
+ GetToken(false);
+ pm->height = atoi(token);
+
+ GetToken(false);
+ pm->contents = atoi(token);
+
+ GetToken(false);
+ pm->flags = atoi(token);
+
+ GetToken(false);
+ pm->value = atoi(token);
+
+ if (!bOld)
+ {
+ GetToken(false);
+ pm->type = atoi(token);
+ }
+
+ GetToken(false);
+ if (strcmp(token, ")"))
+ return NULL;
+
+ }
+
+
+
+ float ctrl[MAX_PATCH_WIDTH][MAX_PATCH_HEIGHT][5];
+ Parse3DMatrix(pm->width, pm->height, 5, reinterpret_cast<float*>(&ctrl));
+
+ int w, h;
+
+ for (w = 0; w < pm->width; w++)
+ {
+ for (h = 0; h < pm->height; h++)
+ {
+ pm->ctrl[w][h].xyz[0] = ctrl[w][h][0];
+ pm->ctrl[w][h].xyz[1] = ctrl[w][h][1];
+ pm->ctrl[w][h].xyz[2] = ctrl[w][h][2];
+ pm->ctrl[w][h].st[0] = ctrl[w][h][3];
+ pm->ctrl[w][h].st[1] = ctrl[w][h][4];
+ }
+ }
+
+ GetToken(true);
+
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ // we are in brush primit mode, but maybe it's a classic patch that needs converting, test "}"
+ if (strcmp(token, "}") && strcmp (token, "(") )
+ {
+ epair_t *ep = ParseEpair();
+ ep->next = pm->epairs;
+ pm->epairs = ep;
+ GetToken(true);
+ }
+ }
+
+ if (strcmp(token, "}"))
+ return NULL;
+
+ brush_t *b = AddBrushForPatch(pm, false);
+
+ return b;
+}
+
+
+/*
+==================
+Patch_Write
+==================
+*/
+void Patch_Write (patchMesh_t *p, CMemFile *file)
+{
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+ Sys_Printf("WARNING: Patch_Write to a CMemFile and Surface Properties plugin not done\n");
+ }
+ //--MemFile_fprintf(file, " {\n patchDef3\n {\n");
+ MemFile_fprintf(file, " {\n patchDef2\n {\n");
+
+ MemFile_fprintf(file, " %s\n",p->d_texture->name);
+ //--MemFile_fprintf(file, " ( %i %i %i %i %i %i ) \n", p->width, p->height, p->contents, p->flags, p->value, p->type);
+ MemFile_fprintf(file, " ( %i %i %i %i %i ) \n", p->width, p->height, p->contents, p->flags, p->value);
+
+
+ float ctrl[MAX_PATCH_WIDTH][MAX_PATCH_HEIGHT][5];
+
+ int w, h;
+ for (w = 0; w < p->width; w++)
+ {
+ for (h = 0; h < p->height; h++)
+ {
+ ctrl[w][h][0] = p->ctrl[w][h].xyz[0];
+ ctrl[w][h][1] = p->ctrl[w][h].xyz[1];
+ ctrl[w][h][2] = p->ctrl[w][h].xyz[2];
+ ctrl[w][h][3] = p->ctrl[w][h].st[0];
+ ctrl[w][h][4] = p->ctrl[w][h].st[1];
+ }
+ }
+
+ _Write3DMatrix(file, p->width, p->height, 5, reinterpret_cast<float*>(&ctrl));
+
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ if (p->epairs)
+ {
+ for (epair_t *ep = p->epairs ; ep ; ep=ep->next)
+ {
+ MemFile_fprintf (file, "\"%s\" \"%s\"\n", ep->key, ep->value);
+ }
+ }
+ }
+
+ MemFile_fprintf(file, " }\n }\n");
+}
+
+void Patch_Write (patchMesh_t *p, FILE *file)
+{
+ fprintf(file, " {\n patchDef2\n {\n");
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+#ifdef _DEBUG
+ if ( !p->pData )
+ Sys_Printf("ERROR: no IPluginTexdef in patch\n");
+#endif
+ g_File = file;
+ GETPLUGINTEXDEF(p)->WritePatchTexdef( QERApp_MapPrintf_FILE );
+ }
+ else
+ {
+ fprintf(file, " %s\n",p->d_texture->name);
+ fprintf(file, " ( %i %i %i %i %i ) \n", p->width, p->height, p->contents, p->flags, p->value);
+ }
+
+ float ctrl[MAX_PATCH_WIDTH][MAX_PATCH_HEIGHT][5];
+
+ int w, h;
+ for (w = 0; w < p->width; w++)
+ {
+ for (h = 0; h < p->height; h++)
+ {
+ ctrl[w][h][0] = p->ctrl[w][h].xyz[0];
+ ctrl[w][h][1] = p->ctrl[w][h].xyz[1];
+ ctrl[w][h][2] = p->ctrl[w][h].xyz[2];
+ ctrl[w][h][3] = p->ctrl[w][h].st[0];
+ ctrl[w][h][4] = p->ctrl[w][h].st[1];
+ }
+ }
+
+ _Write3DMatrix(file, p->width, p->height, 5, reinterpret_cast<float*>(&ctrl));
+
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ if (p->epairs)
+ {
+ for (epair_t *ep = p->epairs ; ep ; ep=ep->next)
+ {
+ fprintf (file, "\"%s\" \"%s\"\n", ep->key, ep->value);
+ }
+ }
+ }
+
+ fprintf(file, " }\n }\n");
+}
+
+
+/*
+==================
+Patch_RotateTexture
+==================
+*/
+void Patch_RotateTexture(patchMesh_t *p, float fAngle)
+{
+ vec3_t vMin, vMax;
+ Patch_CalcBounds(p, vMin, vMax);
+ p->bDirty = true;
+ for (int w = 0; w < p->width; w++)
+ {
+ for (int h = 0; h < p->height; h++)
+ {
+ if (g_qeglobals.d_select_mode == sel_curvepoint && PointInMoveList(p->ctrl[w][h].xyz) == -1)
+ continue;
+
+ float x = p->ctrl[w][h].st[0];
+ float y = p->ctrl[w][h].st[1];
+ p->ctrl[w][h].st[0] = x * cos(fAngle * Q_PI / 180) - y * sin(fAngle * Q_PI / 180);
+ p->ctrl[w][h].st[1] = y * cos(fAngle * Q_PI / 180) + x * sin(fAngle * Q_PI / 180);
+ }
+ }
+}
+
+
+/*
+==================
+Patch_ScaleTexture
+==================
+*/
+void Patch_ScaleTexture(patchMesh_t *p, float fx, float fy, bool bFixup)
+{
+ // FIXME:
+ // this hack turns scales into 1.1 or 0.9
+ if (bFixup)
+ {
+ fx = (fx == 0) ? 1.0 : (fx > 0) ? 0.9 : 1.10;
+ fy = (fy == 0) ? 1.0 : (fy > 0) ? 0.9 : 1.10;
+ }
+ else
+ {
+ if (fx == 0)
+ fx = 1.0;
+ if (fy == 0)
+ fy = 1.0;
+ }
+
+ for (int w = 0; w < p->width; w++)
+ {
+ for (int h = 0; h < p->height; h++)
+ {
+ if (g_qeglobals.d_select_mode == sel_curvepoint && PointInMoveList(p->ctrl[w][h].xyz) == -1)
+ continue;
+
+ p->ctrl[w][h].st[0] *= fx;
+ p->ctrl[w][h].st[1] *= fy;
+ }
+ }
+ p->bDirty = true;
+}
+
+
+/*
+==================
+Patch_ShiftTexture
+==================
+*/
+void Patch_ShiftTexture(patchMesh_t *p, float fx, float fy)
+{
+ //if (fx)
+ // fx = (fx > 0) ? 0.1 : -0.1;
+ //if (fy)
+ // fy = (fy > 0) ? 0.1 : -0.1;
+
+ fx = (abs(fx) >= 1) ? fx / 10 : fx;
+ fy = (abs(fy) >= 1) ? fy / 10 : fy;
+
+ for (int w = 0; w < p->width; w++)
+ {
+ for (int h = 0; h < p->height; h++)
+ {
+ if (g_qeglobals.d_select_mode == sel_curvepoint && PointInMoveList(p->ctrl[w][h].xyz) == -1)
+ continue;
+
+ p->ctrl[w][h].st[0] += fx;
+ p->ctrl[w][h].st[1] += fy;
+ }
+ }
+ p->bDirty = true;
+}
+
+void patchInvert(patchMesh_t *p)
+{
+ drawVert_t vertTemp;
+ p->bDirty = true;
+ for ( int i = 0 ; i < p->width ; i++ )
+ {
+ for (int j = 0; j < p->height / 2; j++)
+ {
+ memcpy(&vertTemp, &p->ctrl[i][p->height - 1- j], sizeof (drawVert_t));
+ memcpy(&p->ctrl[i][p->height - 1 - j], &p->ctrl[i][j], sizeof(drawVert_t));
+ memcpy(&p->ctrl[i][j], &vertTemp, sizeof(drawVert_t));
+ }
+ }
+}
+
+/*
+==================
+Patch_ToggleInverted
+==================
+*/
+void Patch_ToggleInverted()
+{
+ bool bUpdate = false;
+
+ for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ bUpdate = true;
+ patchInvert(pb->pPatch);
+ }
+ }
+
+ if (bUpdate)
+ {
+ Sys_UpdateWindows(W_ALL);
+ }
+ UpdatePatchInspector();
+}
+
+/*
+==================
+Patch_ToggleInverted
+==================
+*/
+void Patch_InvertTexture(bool bY)
+{
+ bool bUpdate = false;
+
+ float fTemp[2];
+ for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ bUpdate = true;
+ patchMesh_t *p = pb->pPatch;
+ p->bDirty = true;
+ if (bY)
+ {
+ for ( int i = 0 ; i < p->height ; i++ )
+ {
+ for (int j = 0; j < p->width / 2; j++)
+ {
+ memcpy(fTemp, &p->ctrl[p->width - 1- j][i].st[0], sizeof (float[2]));
+ memcpy(&p->ctrl[p->width - 1- j][i].st[0], &p->ctrl[j][i].st[0], sizeof(float[2]));
+ memcpy(&p->ctrl[j][i].st[0], fTemp, sizeof(float[2]));
+ }
+ }
+ }
+ else
+ {
+ for ( int i = 0 ; i < p->width ; i++ )
+ {
+ for (int j = 0; j < p->height / 2; j++)
+ {
+ memcpy(fTemp, &p->ctrl[i][p->height - 1- j].st[0], sizeof (float[2]));
+ memcpy(&p->ctrl[i][p->height - 1 - j].st[0], &p->ctrl[i][j].st[0], sizeof(float[2]));
+ memcpy(&p->ctrl[i][j].st[0], fTemp, sizeof(float[2]));
+ }
+ }
+ }
+ }
+ }
+
+ if (bUpdate)
+ {
+ Sys_UpdateWindows(W_ALL);
+ }
+ UpdatePatchInspector();
+}
+
+
+
+
+/*
+==================
+Patch_Save
+==================
+ Saves patch ctrl info (originally to deal with a
+ cancel in the surface dialog
+*/
+void Patch_Save(patchMesh_t *p)
+{
+ patchSave.width = p->width;
+ patchSave.height = p->height;
+ memcpy(patchSave.ctrl, p->ctrl, sizeof(p->ctrl));
+}
+
+
+/*
+==================
+Patch_Restore
+==================
+*/
+void Patch_Restore(patchMesh_t *p)
+{
+ p->width = patchSave.width;
+ p->height = patchSave.height;
+ memcpy(p->ctrl, patchSave.ctrl, sizeof(p->ctrl));
+}
+
+void Patch_ResetTexturing(float fx, float fy)
+{
+ for (brush_t* pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ patchMesh_t *p = pb->pPatch;
+ p->bDirty = true;
+ for ( int i = 0 ; i < p->width ; i++ )
+ {
+ for ( int j = 0 ; j < p->height ; j++ )
+ {
+ p->ctrl[i][j].st[0] = fx * (float)i / (p->width - 1);
+ p->ctrl[i][j].st[1] = fy * (float)j / (p->height - 1);
+ }
+ }
+ }
+ }
+}
+
+
+void Patch_FitTexturing()
+{
+ for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ patchMesh_t *p = pb->pPatch;
+ p->bDirty = true;
+ for ( int i = 0 ; i < p->width ; i++ )
+ {
+ for ( int j = 0 ; j < p->height ; j++ )
+ {
+ p->ctrl[i][j].st[0] = 1 * (float)i / (p->width - 1);
+ p->ctrl[i][j].st[1] = 1 * (float)j / (p->height - 1);
+ }
+ }
+ }
+ }
+}
+
+
+void Patch_SetTextureInfo(texdef_t *pt)
+{
+ for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ if (pt->rotate)
+ Patch_RotateTexture(pb->pPatch, pt->rotate);
+
+ if (pt->shift[0] || pt->shift[1])
+ Patch_ShiftTexture(pb->pPatch, pt->shift[0], pt->shift[1]);
+
+ if (pt->scale[0] || pt->scale[1])
+ Patch_ScaleTexture(pb->pPatch, pt->scale[0], pt->scale[1], false);
+
+ patchMesh_t *p = pb->pPatch;
+ p->contents = pt->contents;
+ p->flags = pt->flags;
+ p->value = pt->value;
+ }
+ }
+}
+
+bool WINAPI OnlyPatchesSelected()
+{
+ if (g_ptrSelectedFaces.GetSize() > 0 || selected_brushes.next == &selected_brushes)
+ return false;
+ for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (!pb->patchBrush)
+ {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool WINAPI AnyPatchesSelected()
+{
+ if (g_ptrSelectedFaces.GetSize() > 0 || selected_brushes.next == &selected_brushes)
+ return false;
+ for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ return true;
+ }
+ }
+ return false;
+}
+
+patchMesh_t* SinglePatchSelected()
+{
+ if (selected_brushes.next->patchBrush)
+ {
+ return selected_brushes.next->pPatch;
+ }
+ return NULL;
+}
+
+void Patch_BendToggle()
+{
+ if (g_bPatchBendMode)
+ {
+ g_bPatchBendMode = false;
+ HideInfoDialog();
+ g_pParentWnd->UpdatePatchToolbarButtons() ;
+ return;
+ }
+
+ brush_t* b = selected_brushes.next;
+
+ if (!QE_SingleBrush() || !b->patchBrush)
+ {
+ Sys_Printf("Must bend a single patch");
+ return;
+ }
+
+ Patch_Save(b->pPatch);
+ g_bPatchBendMode = true;
+ g_nPatchBendState = BEND_SELECT_ROTATION;
+ g_bPatchAxisOnRow = true;
+ g_nPatchAxisIndex = 1;
+ ShowInfoDialog(g_pBendStateMsg[BEND_SELECT_ROTATION]);
+}
+
+void Patch_BendHandleTAB()
+{
+ if (!g_bPatchBendMode)
+ {
+ return;
+ }
+
+ brush_t* b = selected_brushes.next;
+ if (!QE_SingleBrush() || !b->patchBrush)
+ {
+ Patch_BendToggle();
+ Sys_Printf("No patch to bend!");
+ return;
+ }
+
+ patchMesh_t *p = b->pPatch;
+
+ bool bShift = (GetKeyState(VK_SHIFT) & 0x8000);
+
+ if (g_nPatchBendState == BEND_SELECT_ROTATION)
+ {
+ // only able to deal with odd numbered rows/cols
+ g_nPatchAxisIndex += (bShift) ? -2 : 2;
+ if (g_bPatchAxisOnRow)
+ {
+ if ((bShift) ? g_nPatchAxisIndex <= 0 : g_nPatchAxisIndex >= p->height)
+ {
+ g_bPatchAxisOnRow = false;
+ g_nPatchAxisIndex = (bShift) ? p->width-1 : 1;
+ }
+ }
+ else
+ {
+ if ((bShift) ? g_nPatchAxisIndex <= 0 : g_nPatchAxisIndex >= p->width)
+ {
+ g_bPatchAxisOnRow = true;
+ g_nPatchAxisIndex = (bShift) ? p->height-1 : 1;
+ }
+ }
+ }
+ else
+ if (g_nPatchBendState == BEND_SELECT_ORIGIN)
+ {
+ g_nBendOriginIndex += (bShift) ? -1 : 1;
+ if (g_bPatchAxisOnRow)
+ {
+ if (bShift)
+ {
+ if (g_nBendOriginIndex < 0)
+ g_nBendOriginIndex = p->width-1;
+ }
+ else
+ {
+ if (g_nBendOriginIndex > p->width-1)
+ g_nBendOriginIndex = 0;
+ }
+ VectorCopy(p->ctrl[g_nBendOriginIndex][g_nPatchAxisIndex].xyz, g_vBendOrigin);
+ }
+ else
+ {
+ if (bShift)
+ {
+ if (g_nBendOriginIndex < 0)
+ g_nBendOriginIndex = p->height-1;
+ }
+ else
+ {
+ if (g_nBendOriginIndex > p->height-1)
+ g_nBendOriginIndex = 0;
+ }
+ VectorCopy(p->ctrl[g_nPatchAxisIndex][g_nBendOriginIndex].xyz, g_vBendOrigin);
+ }
+ }
+ else
+ if (g_nPatchBendState == BEND_SELECT_EDGE)
+ {
+ g_bPatchLowerEdge ^= 1;
+ }
+ Sys_UpdateWindows(W_ALL);
+}
+
+void Patch_BendHandleENTER()
+{
+ if (!g_bPatchBendMode)
+ {
+ return;
+ }
+
+ if (g_nPatchBendState < BEND_BENDIT)
+ {
+ g_nPatchBendState++;
+ ShowInfoDialog(g_pBendStateMsg[g_nPatchBendState]);
+ if (g_nPatchBendState == BEND_SELECT_ORIGIN)
+ {
+ g_vBendOrigin[0] = g_vBendOrigin[1] = g_vBendOrigin[2] = 0;
+ g_nBendOriginIndex = 0;
+ Patch_BendHandleTAB();
+ }
+ else
+ if (g_nPatchBendState == BEND_SELECT_EDGE)
+ {
+ g_bPatchLowerEdge = true;
+ }
+ else
+ if (g_nPatchBendState == BEND_BENDIT)
+ {
+ // basically we go into rotation mode, set the axis to the center of the
+ }
+ }
+ else
+ {
+ // done
+ Patch_BendToggle();
+ }
+ Sys_UpdateWindows(W_ALL);
+
+}
+
+
+void Patch_BendHandleESC()
+{
+ if (!g_bPatchBendMode)
+ {
+ return;
+ }
+ Patch_BendToggle();
+ brush_t* b = selected_brushes.next;
+ if (QE_SingleBrush() && b->patchBrush)
+ {
+ Patch_Restore(b->pPatch);
+ }
+ Sys_UpdateWindows(W_ALL);
+}
+
+void Patch_SetBendRotateOrigin(patchMesh_t *p)
+{
+#if 1
+ int nType = g_pParentWnd->ActiveXY()->GetViewType();
+ int nDim3 = (nType == XY) ? 2 : (nType == YZ) ? 0 : 1;
+
+ g_vBendOrigin[nDim3] = 0;
+ VectorCopy(g_vBendOrigin, g_pParentWnd->ActiveXY()->RotateOrigin());
+ return;
+#else
+ int nDim1 = (g_pParentWnd->ActiveXY()->GetViewType() == YZ) ? 1 : 0;
+ int nDim2 = (g_pParentWnd->ActiveXY()->GetViewType() == XY) ? 1 : 2;
+
+ float fxLo, fyLo, fxHi, fyHi;
+ fxLo = fyLo = 9999;
+ fxHi = fyHi = -9999;
+
+ if (g_bPatchAxisOnRow)
+ {
+ for (int i = 0; i < p->width; i++)
+ {
+ if (p->ctrl[i][g_nPatchAxisIndex].xyz[nDim1] < fxLo)
+ fxLo = p->ctrl[i][g_nPatchAxisIndex].xyz[nDim1];
+
+ if (p->ctrl[i][g_nPatchAxisIndex].xyz[nDim1] > fxHi)
+ fxHi = p->ctrl[i][g_nPatchAxisIndex].xyz[nDim1];
+
+ if (p->ctrl[i][g_nPatchAxisIndex].xyz[nDim2] < fyLo)
+ fyLo = p->ctrl[i][g_nPatchAxisIndex].xyz[nDim2];
+
+ if (p->ctrl[i][g_nPatchAxisIndex].xyz[nDim2] > fyHi)
+ fyHi = p->ctrl[i][g_nPatchAxisIndex].xyz[nDim2];
+ }
+ }
+ else
+ {
+ for (int i = 0; i < p->height; i++)
+ {
+ if (p->ctrl[g_nPatchAxisIndex][i].xyz[nDim1] < fxLo)
+ fxLo = p->ctrl[g_nPatchAxisIndex][i].xyz[nDim1];
+
+ if (p->ctrl[g_nPatchAxisIndex][i].xyz[nDim1] > fxHi)
+ fxHi = p->ctrl[g_nPatchAxisIndex][i].xyz[nDim1];
+
+ if (p->ctrl[g_nPatchAxisIndex][i].xyz[nDim2] < fyLo)
+ fyLo = p->ctrl[g_nPatchAxisIndex][i].xyz[nDim2];
+
+ if (p->ctrl[g_nPatchAxisIndex][i].xyz[nDim2] > fyHi)
+ fyHi = p->ctrl[g_nPatchAxisIndex][i].xyz[nDim2];
+ }
+ }
+
+ g_pParentWnd->ActiveXY()->RotateOrigin()[0] = g_pParentWnd->ActiveXY()->RotateOrigin()[1] = g_pParentWnd->ActiveXY()->RotateOrigin()[2] = 0.0;
+ g_pParentWnd->ActiveXY()->RotateOrigin()[nDim1] = (fxLo + fxHi) * 0.5;
+ g_pParentWnd->ActiveXY()->RotateOrigin()[nDim2] = (fyLo + fyHi) * 0.5;
+#endif
+}
+
+// also sets the rotational origin
+void Patch_SelectBendAxis()
+{
+ brush_t* b = selected_brushes.next;
+ if (!QE_SingleBrush() || !b->patchBrush)
+ {
+ // should not ever happen
+ Patch_BendToggle();
+ return;
+ }
+
+ patchMesh_t *p = b->pPatch;
+ if (g_bPatchAxisOnRow)
+ {
+ SelectRow(p, g_nPatchAxisIndex, false);
+ }
+ else
+ {
+ SelectColumn(p, g_nPatchAxisIndex, false);
+ }
+
+ //FIXME: this only needs to be set once...
+ Patch_SetBendRotateOrigin(p);
+
+}
+
+void Patch_SelectBendNormal()
+{
+ brush_t* b = selected_brushes.next;
+ if (!QE_SingleBrush() || !b->patchBrush)
+ {
+ // should not ever happen
+ Patch_BendToggle();
+ return;
+ }
+
+ patchMesh_t *p = b->pPatch;
+
+ g_qeglobals.d_num_move_points = 0;
+ if (g_bPatchAxisOnRow)
+ {
+ if (g_bPatchLowerEdge)
+ {
+ for (int j = 0; j < g_nPatchAxisIndex; j++)
+ SelectRow(p, j, true);
+ }
+ else
+ {
+ for (int j = p->height-1; j > g_nPatchAxisIndex; j--)
+ SelectRow(p, j, true);
+ }
+ }
+ else
+ {
+ if (g_bPatchLowerEdge)
+ {
+ for (int j = 0; j < g_nPatchAxisIndex; j++)
+ SelectColumn(p, j, true);
+ }
+ else
+ {
+ for (int j = p->width-1; j > g_nPatchAxisIndex; j--)
+ SelectColumn(p, j, true);
+ }
+ }
+ Patch_SetBendRotateOrigin(p);
+}
+
+
+
+void Patch_InsDelToggle()
+{
+ if (g_bPatchInsertMode)
+ {
+ g_bPatchInsertMode = false;
+ HideInfoDialog();
+ g_pParentWnd->UpdatePatchToolbarButtons() ;
+ return;
+ }
+
+ brush_t* b = selected_brushes.next;
+
+ if (!QE_SingleBrush() || !b->patchBrush)
+ {
+ Sys_Printf("Must work with a single patch");
+ return;
+ }
+
+ Patch_Save(b->pPatch);
+ g_bPatchInsertMode = true;
+ g_nPatchInsertState = INSERT_SELECT_EDGE;
+ g_bPatchAxisOnRow = true;
+ g_nPatchAxisIndex = 0;
+ ShowInfoDialog(g_pInsertStateMsg[INSERT_SELECT_EDGE]);
+
+}
+
+void Patch_InsDelESC()
+{
+ if (!g_bPatchInsertMode)
+ {
+ return;
+ }
+ Patch_InsDelToggle();
+ Sys_UpdateWindows(W_ALL);
+}
+
+
+void Patch_InsDelHandleENTER()
+{
+}
+
+void Patch_InsDelHandleTAB()
+{
+ if (!g_bPatchInsertMode)
+ {
+ Patch_InsDelToggle();
+ return;
+ }
+
+ brush_t* b = selected_brushes.next;
+ if (!QE_SingleBrush() || !b->patchBrush)
+ {
+ Patch_BendToggle();
+ Sys_Printf("No patch to bend!");
+ return;
+ }
+
+ patchMesh_t *p = b->pPatch;
+
+ // only able to deal with odd numbered rows/cols
+ g_nPatchAxisIndex += 2;
+ if (g_bPatchAxisOnRow)
+ {
+ if (g_nPatchAxisIndex >= p->height-1)
+ {
+ g_bPatchAxisOnRow = false;
+ g_nPatchAxisIndex = 0;
+ }
+ }
+ else
+ {
+ if (g_nPatchAxisIndex >= p->width-1)
+ {
+ g_bPatchAxisOnRow = true;
+ g_nPatchAxisIndex = 0;
+ }
+ }
+ Sys_UpdateWindows(W_ALL);
+}
+
+
+void _Write1DMatrix (FILE *f, int x, float *m) {
+ int i;
+
+ fprintf (f, "( ");
+ for (i = 0 ; i < x ; i++) {
+ if (m[i] == (int)m[i] ) {
+ fprintf (f, "%i ", (int)m[i]);
+ } else {
+ fprintf (f, "%f ", m[i]);
+ }
+ }
+ fprintf (f, ")");
+}
+
+void _Write2DMatrix (FILE *f, int y, int x, float *m) {
+ int i;
+
+ fprintf (f, "( ");
+ for (i = 0 ; i < y ; i++) {
+ _Write1DMatrix (f, x, m + i*x);
+ fprintf (f, " ");
+ }
+ fprintf (f, ")\n");
+}
+
+
+void _Write3DMatrix (FILE *f, int z, int y, int x, float *m) {
+ int i;
+
+ fprintf (f, "(\n");
+ for (i = 0 ; i < z ; i++) {
+ _Write2DMatrix (f, y, x, m + i*(x*MAX_PATCH_HEIGHT) );
+ }
+ fprintf (f, ")\n");
+}
+
+void _Write1DMatrix (CMemFile *f, int x, float *m) {
+ int i;
+
+ MemFile_fprintf (f, "( ");
+ for (i = 0 ; i < x ; i++) {
+ if (m[i] == (int)m[i] ) {
+ MemFile_fprintf (f, "%i ", (int)m[i]);
+ } else {
+ MemFile_fprintf (f, "%f ", m[i]);
+ }
+ }
+ MemFile_fprintf (f, ")");
+}
+
+void _Write2DMatrix (CMemFile *f, int y, int x, float *m) {
+ int i;
+
+ MemFile_fprintf (f, "( ");
+ for (i = 0 ; i < y ; i++) {
+ _Write1DMatrix (f, x, m + i*x);
+ MemFile_fprintf (f, " ");
+ }
+ MemFile_fprintf (f, ")\n");
+}
+
+
+void _Write3DMatrix (CMemFile *f, int z, int y, int x, float *m) {
+ int i;
+
+ MemFile_fprintf (f, "(\n");
+ for (i = 0 ; i < z ; i++) {
+ _Write2DMatrix (f, y, x, m + i*(x*MAX_PATCH_HEIGHT) );
+ }
+ MemFile_fprintf (f, ")\n");
+}
+
+
+void Patch_NaturalizeSelected(bool bCap, bool bCycleCap)
+{
+ for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ if (bCap)
+ Patch_CapTexture(pb->pPatch, bCycleCap);
+ else
+ Patch_Naturalize(pb->pPatch);
+ }
+ }
+}
+
+bool within(vec3_t vTest, vec3_t vTL, vec3_t vBR)
+{
+ int nDim1 = (g_pParentWnd->ActiveXY()->GetViewType() == YZ) ? 1 : 0;
+ int nDim2 = (g_pParentWnd->ActiveXY()->GetViewType() == XY) ? 1 : 2;
+ if ((vTest[nDim1] > vTL[nDim1] && vTest[nDim1] < vBR[nDim1]) ||
+ (vTest[nDim1] < vTL[nDim1] && vTest[nDim1] > vBR[nDim1]))
+ {
+ if ((vTest[nDim2] > vTL[nDim2] && vTest[nDim2] < vBR[nDim2]) ||
+ (vTest[nDim2] < vTL[nDim2] && vTest[nDim2] > vBR[nDim2]))
+ return true;
+ }
+ return false;
+}
+
+
+void Patch_SelectAreaPoints()
+{
+ g_qeglobals.d_num_move_points = 0;
+ g_nPatchClickedView = -1;
+
+ for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ patchMesh_t *p = pb->pPatch;
+ for (int i = 0; i < p->width; i++)
+ {
+ for (int j = 0; j < p->height; j++)
+ {
+ if (within(p->ctrl[i][j].xyz, g_qeglobals.d_vAreaTL, g_qeglobals.d_vAreaBR))
+ {
+ g_qeglobals.d_move_points[g_qeglobals.d_num_move_points++] = p->ctrl[i][j].xyz;
+ }
+ }
+ }
+ }
+ }
+}
+
+const char* Patch_GetTextureName()
+{
+ brush_t* b = selected_brushes.next;
+ if (b->patchBrush)
+ {
+ patchMesh_t *p = b->pPatch;
+ if (p->d_texture->name)
+ return p->d_texture->name;
+ }
+ return "";
+}
+
+patchMesh_t* Patch_Duplicate(patchMesh_t *pFrom)
+{
+ patchMesh_t* p = MakeNewPatch();
+ memcpy(p, pFrom , sizeof(patchMesh_t));
+ p->bSelected = false;
+ p->bDirty = true;
+ p->bOverlay = false;
+ p->nListID = -1;
+ // surface plugin
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+#ifdef _DEBUG
+ if (!pFrom->pData)
+ Sys_Printf("WARNING: unexpected pFrom->pData is NULL in Patch_Duplicate\n");
+ else
+#endif
+ p->pData = GETPLUGINTEXDEF(pFrom)->Copy();
+ }
+ AddBrushForPatch(p);
+ return p;
+}
+
+
+void Patch_Thicken(int nAmount, bool bSeam)
+{
+ int i, j, h, w;
+ brush_t *b;
+ patchMesh_t *pSeam;
+ vec3_t vMin, vMax;
+ CPtrArray brushes;
+
+ nAmount = -nAmount;
+
+
+ if (!QE_SingleBrush())
+ {
+ Sys_Printf("Cannot thicken multiple patches. Please select a single patch.\n");
+ return;
+ }
+
+ for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ patchMesh_t *p = pb->pPatch;
+ Patch_MeshNormals(p);
+ patchMesh_t *pNew = Patch_Duplicate(p);
+ for (i = 0; i < p->width; i++)
+ {
+ for (j = 0; j < p->height; j++)
+ {
+ VectorMA (p->ctrl[i][j].xyz, nAmount, p->ctrl[i][j].normal, pNew->ctrl[i][j].xyz);
+ }
+ }
+
+ Patch_Rebuild(pNew);
+ pNew->type |= PATCH_THICK;
+ brushes.Add(pNew->pSymbiot);
+
+ if (bSeam)
+ {
+
+ // FIXME: this should detect if any edges of the patch are closed and act appropriately
+ //
+ if (!(p->type & PATCH_CYLINDER))
+ {
+ b = Patch_GenericMesh(3, p->height, 2, false, true);
+ pSeam = b->pPatch;
+ pSeam->type |= PATCH_SEAM;
+ for (i = 0; i < p->height; i++)
+ {
+ VectorCopy(p->ctrl[0][i].xyz, pSeam->ctrl[0][i].xyz);
+ VectorCopy(pNew->ctrl[0][i].xyz, pSeam->ctrl[2][i].xyz);
+ VectorAdd(pSeam->ctrl[0][i].xyz, pSeam->ctrl[2][i].xyz, pSeam->ctrl[1][i].xyz);
+ VectorScale(pSeam->ctrl[1][i].xyz, 0.5, pSeam->ctrl[1][i].xyz);
+ }
+
+
+ Patch_CalcBounds(pSeam, vMin, vMax);
+ Brush_RebuildBrush(pSeam->pSymbiot, vMin, vMax);
+ //--Patch_CapTexture(pSeam);
+ Patch_Naturalize(pSeam);
+ patchInvert(pSeam);
+ brushes.Add(b);
+
+ w = p->width - 1;
+ b = Patch_GenericMesh(3, p->height, 2, false, true);
+ pSeam = b->pPatch;
+ pSeam->type |= PATCH_SEAM;
+ for (i = 0; i < p->height; i++)
+ {
+ VectorCopy(p->ctrl[w][i].xyz, pSeam->ctrl[0][i].xyz);
+ VectorCopy(pNew->ctrl[w][i].xyz, pSeam->ctrl[2][i].xyz);
+ VectorAdd(pSeam->ctrl[0][i].xyz, pSeam->ctrl[2][i].xyz, pSeam->ctrl[1][i].xyz);
+ VectorScale(pSeam->ctrl[1][i].xyz, 0.5, pSeam->ctrl[1][i].xyz);
+ }
+ Patch_CalcBounds(pSeam, vMin, vMax);
+ Brush_RebuildBrush(pSeam->pSymbiot, vMin, vMax);
+ //--Patch_CapTexture(pSeam);
+ Patch_Naturalize(pSeam);
+ brushes.Add(b);
+ }
+
+ //--{
+ // otherwise we will add one per end
+ b = Patch_GenericMesh(p->width, 3, 2, false, true);
+ pSeam = b->pPatch;
+ pSeam->type |= PATCH_SEAM;
+ for (i = 0; i < p->width; i++)
+ {
+ VectorCopy(p->ctrl[i][0].xyz, pSeam->ctrl[i][0].xyz);
+ VectorCopy(pNew->ctrl[i][0].xyz, pSeam->ctrl[i][2].xyz);
+ VectorAdd(pSeam->ctrl[i][0].xyz, pSeam->ctrl[i][2].xyz, pSeam->ctrl[i][1].xyz);
+ VectorScale(pSeam->ctrl[i][1].xyz, 0.5, pSeam->ctrl[i][1].xyz);
+ }
+
+
+ Patch_CalcBounds(pSeam, vMin, vMax);
+ Brush_RebuildBrush(pSeam->pSymbiot, vMin, vMax);
+ //--Patch_CapTexture(pSeam);
+ Patch_Naturalize(pSeam);
+ patchInvert(pSeam);
+ brushes.Add(b);
+
+ h = p->height - 1;
+ b = Patch_GenericMesh(p->width, 3, 2, false, true);
+ pSeam = b->pPatch;
+ pSeam->type |= PATCH_SEAM;
+ for (i = 0; i < p->width; i++)
+ {
+ VectorCopy(p->ctrl[i][h].xyz, pSeam->ctrl[i][0].xyz);
+ VectorCopy(pNew->ctrl[i][h].xyz, pSeam->ctrl[i][2].xyz);
+ VectorAdd(pSeam->ctrl[i][0].xyz, pSeam->ctrl[i][2].xyz, pSeam->ctrl[i][1].xyz);
+ VectorScale(pSeam->ctrl[i][1].xyz, 0.5, pSeam->ctrl[i][1].xyz);
+ }
+ Patch_CalcBounds(pSeam, vMin, vMax);
+ Brush_RebuildBrush(pSeam->pSymbiot, vMin, vMax);
+ //--Patch_CapTexture(pSeam);
+ Patch_Naturalize(pSeam);
+ brushes.Add(b);
+
+ eclass_t *pecNew = Eclass_ForName("func_group", false);
+ if (pecNew)
+ {
+ entity_t *e = Entity_Create(pecNew);
+ SetKeyValue(e, "type", "patchThick");
+ }
+
+
+ //--}
+ }
+ patchInvert(pNew);
+ }
+ }
+
+ for (i = 0; i < brushes.GetSize(); i++)
+ {
+ Select_Brush(reinterpret_cast<brush_t*>(brushes.GetAt(i)));
+ }
+
+ UpdatePatchInspector();
+}
+
+
+/*
+lets get another list together as far as necessities..
+
+*snapping stuff to the grid (i will only snap movements by the mouse to the grid.. snapping the rotational bend stuff will fubar everything)
+
+capping bevels/endcaps
+
+hot keys
+
+texture fix for caps
+
+clear clipboard
+
+*region fix
+
+*surface dialog
+
+*/
+
+void Patch_SetOverlays()
+{
+ for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ pb->pPatch->bOverlay = true;
+ }
+ }
+}
+
+
+
+void Patch_ClearOverlays()
+{
+ brush_t *pb;
+ for (pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ pb->pPatch->bOverlay = false;
+ }
+ }
+
+ for (pb = active_brushes.next ; pb != &active_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ pb->pPatch->bOverlay = false;
+ }
+ }
+
+}
+
+// freezes selected vertices
+void Patch_Freeze()
+{
+ brush_t *pb;
+ for (pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ pb->pPatch->bOverlay = false;
+ }
+ }
+
+ for (pb = active_brushes.next ; pb != &active_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ pb->pPatch->bOverlay = false;
+ }
+ }
+
+}
+
+void Patch_UnFreeze(bool bAll)
+{
+}
+
+
+
+void Patch_Transpose()
+{
+ int i, j, w;
+ drawVert_t dv;
+ for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ patchMesh_t *p = pb->pPatch;
+
+ if ( p->width > p->height )
+ {
+ for ( i = 0 ; i < p->height ; i++ )
+ {
+ for ( j = i + 1 ; j < p->width ; j++ )
+ {
+ if ( j < p->height )
+ {
+ // swap the value
+ memcpy(&dv,&p->ctrl[j][i],sizeof(drawVert_t));
+ memcpy(&p->ctrl[j][i],&p->ctrl[i][j], sizeof(drawVert_t));
+ memcpy(&p->ctrl[i][j],&dv, sizeof(drawVert_t));
+ }
+ else
+ {
+ // just copy
+ memcpy(&p->ctrl[j][i],&p->ctrl[i][j], sizeof(drawVert_t));
+ }
+ }
+ }
+ }
+ else
+ {
+ for ( i = 0 ; i < p->width ; i++ )
+ {
+ for ( j = i + 1 ; j < p->height ; j++ )
+ {
+ if ( j < p->width )
+ {
+ // swap the value
+ memcpy(&dv,&p->ctrl[i][j], sizeof(drawVert_t));
+ memcpy(&p->ctrl[i][j],&p->ctrl[j][i], sizeof(drawVert_t));
+ memcpy(&p->ctrl[j][i],&dv, sizeof(drawVert_t));
+ }
+ else
+ {
+ // just copy
+ memcpy(&p->ctrl[i][j],&p->ctrl[j][i], sizeof(drawVert_t));
+ }
+ }
+ }
+ }
+
+ w = p->width;
+ p->width = p->height;
+ p->height = w;
+ patchInvert(p);
+ Patch_Rebuild(p);
+ }
+ }
+}
+
+
+
+void Select_SnapToGrid()
+{
+ int i,j, k;
+ for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ patchMesh_t *p = pb->pPatch;
+#if 0
+ float ctrl[MAX_PATCH_WIDTH][MAX_PATCH_HEIGHT][5];
+ memcpy(ctrl, p->ctrl, sizeof(p->ctrl));
+ i = p->width;
+ p->width = p->height;
+ p->height = i;
+ for (i = 0; i < p->width; i++)
+ {
+ int l = p->height-1;
+ for (j = 0; j < p->height; j++)
+ {
+ for (k = 0; k < 5; k++)
+ {
+ p->ctrl[i][l][k] = ctrl[j][i][k];
+ }
+ l--;
+ }
+ }
+#else
+ for (i = 0; i < p->width; i++)
+ {
+ for (j = 0; j < p->height; j++)
+ {
+ for (k = 0; k < 3; k++)
+ {
+ p->ctrl[i][j].xyz[k] = floor(p->ctrl[i][j].xyz[k] / g_qeglobals.d_gridsize + 0.5) * g_qeglobals.d_gridsize;
+ }
+ }
+ }
+#endif
+ vec3_t vMin, vMax;
+ Patch_CalcBounds(p, vMin, vMax);
+ Brush_RebuildBrush(p->pSymbiot, vMin, vMax);
+ }
+ else
+ {
+ Brush_SnapToGrid(pb);
+ }
+ }
+}
+
+
+void Patch_FindReplaceTexture(brush_t *pb, const char *pFind, const char *pReplace, bool bForce)
+{
+ if (pb->patchBrush)
+ {
+ patchMesh_t *p = pb->pPatch;
+ if (bForce || strcmpi(p->d_texture->name, pFind) == 0)
+ {
+ p->d_texture = Texture_ForName(pReplace);
+ //strcpy(p->d_texture->name, pReplace);
+ }
+ }
+}
+
+void Patch_ReplaceQTexture(brush_t *pb, qtexture_t *pOld, qtexture_t *pNew)
+{
+ if (pb->patchBrush)
+ {
+ patchMesh_t *p = pb->pPatch;
+ if (p->d_texture == pOld)
+ {
+ p->d_texture = pNew;
+ }
+ }
+}
+
+void Patch_Clone(patchMesh_t *p, brush_t *pNewOwner)
+{
+}
+
+void Patch_FromTriangle(vec5_t vx, vec5_t vy, vec5_t vz)
+{
+ patchMesh_t* p = MakeNewPatch();
+ p->d_texture = Texture_ForName(g_qeglobals.d_texturewin.texdef.name);
+ p->width = 3;
+ p->height = 3;
+ p->type = PATCH_TRIANGLE;
+
+ // 0 0 goes to x
+ // 0 1 goes to x
+ // 0 2 goes to x
+
+ // 1 0 goes to mid of x and z
+ // 1 1 goes to mid of x y and z
+ // 1 2 goes to mid of x and y
+
+ // 2 0 goes to z
+ // 2 1 goes to mid of y and z
+ // 2 2 goes to y
+
+ vec5_t vMidXZ;
+ vec5_t vMidXY;
+ vec5_t vMidYZ;
+
+
+ for (int j = 0; j < 3; j++)
+ {
+ _Vector5Add(vx, vz, vMidXZ);
+ _Vector5Scale(vMidXZ, 0.5, vMidXZ);
+ //vMidXZ[j] = vx[j] + abs((vx[j] - vz[j]) * 0.5);
+ }
+
+ for (j = 0; j < 3; j++)
+ {
+ _Vector5Add(vx, vy, vMidXY);
+ _Vector5Scale(vMidXY, 0.5, vMidXY);
+ //vMidXY[j] = vx[j] + abs((vx[j] - vy[j]) * 0.5);
+ }
+
+ for (j = 0; j < 3; j++)
+ {
+ _Vector5Add(vy, vz, vMidYZ);
+ _Vector5Scale(vMidYZ, 0.5, vMidYZ);
+ //vMidYZ[j] = vy[j] + abs((vy[j] - vz[j]) * 0.5);
+ }
+
+ _Vector53Copy(vx, p->ctrl[0][0].xyz);
+ _Vector53Copy(vx, p->ctrl[0][1].xyz);
+ _Vector53Copy(vx, p->ctrl[0][2].xyz);
+ p->ctrl[0][0].st[0] = vx[3];
+ p->ctrl[0][0].st[1] = vx[4];
+ p->ctrl[0][1].st[0] = vx[3];
+ p->ctrl[0][1].st[1] = vx[4];
+ p->ctrl[0][2].st[0] = vx[3];
+ p->ctrl[0][2].st[1] = vx[4];
+
+ _Vector53Copy(vMidXY, p->ctrl[1][0].xyz);
+ _Vector53Copy(vx, p->ctrl[1][1].xyz);
+ _Vector53Copy(vMidXZ, p->ctrl[1][2].xyz);
+ p->ctrl[1][0].st[0] = vMidXY[3];
+ p->ctrl[1][0].st[1] = vMidXY[4];
+ p->ctrl[1][1].st[0] = vx[3];
+ p->ctrl[1][1].st[1] = vx[4];
+ p->ctrl[1][2].st[0] = vMidXZ[3];
+ p->ctrl[1][2].st[1] = vMidXZ[4];
+
+ _Vector53Copy(vy, p->ctrl[2][0].xyz);
+ _Vector53Copy(vMidYZ, p->ctrl[2][1].xyz);
+ _Vector53Copy(vz, p->ctrl[2][2].xyz);
+ p->ctrl[2][0].st[0] = vy[3];
+ p->ctrl[2][0].st[1] = vy[4];
+ p->ctrl[2][1].st[0] = vMidYZ[3];
+ p->ctrl[2][1].st[1] = vMidYZ[4];
+ p->ctrl[2][2].st[0] = vz[3];
+ p->ctrl[2][2].st[1] = vz[4];
+
+
+ //Patch_Naturalize(p);
+
+ brush_t *b = AddBrushForPatch(p);
+
+}
+
+
+/*
+==============
+Patch_SetEpair
+sets an epair for the given patch
+==============
+*/
+void Patch_SetEpair(patchMesh_t *p, const char *pKey, const char *pValue)
+{
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ SetKeyValue(p->epairs, pKey, pValue);
+ }
+}
+
+/*
+=================
+Patch_GetKeyValue
+=================
+*/
+const char* Patch_GetKeyValue(patchMesh_t *p, const char *pKey)
+{
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ return ValueForKey(p->epairs, pKey);
+ }
+ return "";
+}
+
+
+//Real nitpicky, but could you make CTRL-S save the current map with the current name? (ie: File/Save)
+/*
+Feature addition.
+When reading in textures, please check for the presence of a file called "textures.link" or something, which contains one line such as;
+
+g:\quake3\baseq3\textures\common
+
+ So that, when I'm reading in, lets say, my \eerie directory, it goes through and adds my textures to the palette, along with everything in common.
+
+ Don't forget to add "Finer texture alignment" to the list. I'd like to be able to move in 0.1 increments using the Shift-Arrow Keys.
+
+ No. Sometimes textures are drawn the wrong way on patches. We'd like the ability to flip a texture. Like the way X/Y scale -1 used to worked.
+
+ 1) Easier way of deleting rows, columns
+2) Fine tuning of textures on patches (X/Y shifts other than with the surface dialog)
+2) Patch matrix transposition
+
+ 1) Actually, bump texture flipping on patches to the top of the list of things to do.
+2) When you select a patch, and hit S, it should read in the selected patch texture. Should not work if you multiselect patches and hit S
+3) Brandon has a wierd anomoly. He fine-tunes a patch with caps. It looks fine when the patch is selected, but as soon as he escapes out, it reverts to it's pre-tuned state. When he selects the patch again, it looks tuned
+
+
+*1) Flipping textures on patches
+*2) When you select a patch, and hit S, it should read in the selected patch texture. Should not work if you multiselect patches and hit S
+3) Easier way of deleting rows columns
+*4) Thick Curves
+5) Patch matrix transposition
+6) Inverted cylinder capping
+*7) bugs
+*8) curve speed
+
+ Have a new feature request. "Compute Bounding Box" for mapobjects (md3 files). This would be used for misc_mapobject (essentially, drop in 3DS Max models into our maps)
+
+ Ok, Feature Request. Load and draw MD3's in the Camera view with proper bounding boxes. This should be off misc_model
+
+ Feature Addition: View/Hide Hint Brushes -- This should be a specific case.
+*/
diff --git a/q3radiant/PMESH.H b/q3radiant/PMESH.H
new file mode 100755
index 0000000..3d49eae
--- /dev/null
+++ b/q3radiant/PMESH.H
@@ -0,0 +1,21 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
diff --git a/q3radiant/POINTS.CPP b/q3radiant/POINTS.CPP
new file mode 100755
index 0000000..db443a7
--- /dev/null
+++ b/q3radiant/POINTS.CPP
@@ -0,0 +1,156 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "stdafx.h"
+
+#include "qe3.h"
+
+
+#define MAX_POINTFILE 8192
+static vec3_t s_pointvecs[MAX_POINTFILE];
+static int s_num_points, s_check_point;
+
+void Pointfile_Delete (void)
+{
+ char name[1024];
+
+ strcpy (name, currentmap);
+ StripExtension (name);
+ strcat (name, ".lin");
+
+ remove(name);
+}
+
+// advance camera to next point
+void Pointfile_Next (void)
+{
+ vec3_t dir;
+
+ if (s_check_point >= s_num_points-2)
+ {
+ Sys_Status ("End of pointfile", 0);
+ return;
+ }
+ s_check_point++;
+ VectorCopy (s_pointvecs[s_check_point], g_pParentWnd->GetCamera()->Camera().origin);
+ VectorCopy (s_pointvecs[s_check_point], g_pParentWnd->GetXYWnd()->GetOrigin());
+ VectorSubtract (s_pointvecs[s_check_point+1], g_pParentWnd->GetCamera()->Camera().origin, dir);
+ VectorNormalize (dir);
+ g_pParentWnd->GetCamera()->Camera().angles[1] = atan2 (dir[1], dir[0])*180/3.14159;
+ g_pParentWnd->GetCamera()->Camera().angles[0] = asin (dir[2])*180/3.14159;
+
+ Sys_UpdateWindows (W_ALL);
+}
+
+// advance camera to previous point
+void Pointfile_Prev (void)
+{
+ vec3_t dir;
+
+ if ( s_check_point == 0)
+ {
+ Sys_Status ("Start of pointfile", 0);
+ return;
+ }
+ s_check_point--;
+ VectorCopy (s_pointvecs[s_check_point], g_pParentWnd->GetCamera()->Camera().origin);
+ VectorCopy (s_pointvecs[s_check_point], g_pParentWnd->GetXYWnd()->GetOrigin());
+ VectorSubtract (s_pointvecs[s_check_point+1], g_pParentWnd->GetCamera()->Camera().origin, dir);
+ VectorNormalize (dir);
+ g_pParentWnd->GetCamera()->Camera().angles[1] = atan2 (dir[1], dir[0])*180/3.14159;
+ g_pParentWnd->GetCamera()->Camera().angles[0] = asin (dir[2])*180/3.14159;
+
+ Sys_UpdateWindows (W_ALL);
+}
+
+void WINAPI Pointfile_Check (void)
+{
+ char name[1024];
+ FILE *f;
+ vec3_t v;
+
+ strcpy (name, currentmap);
+ StripExtension (name);
+ strcat (name, ".lin");
+
+ f = fopen (name, "r");
+ if (!f)
+ return;
+
+ Sys_Printf ("Reading pointfile %s\n", name);
+
+ if (!g_qeglobals.d_pointfile_display_list)
+ g_qeglobals.d_pointfile_display_list = qglGenLists(1);
+
+ s_num_points = 0;
+ qglNewList (g_qeglobals.d_pointfile_display_list, GL_COMPILE);
+ qglColor3f (1, 0, 0);
+ qglDisable(GL_TEXTURE_2D);
+ qglDisable(GL_TEXTURE_1D);
+ qglLineWidth (4);
+ qglBegin(GL_LINE_STRIP);
+ do
+ {
+ if (fscanf (f, "%f %f %f\n", &v[0], &v[1], &v[2]) != 3)
+ break;
+ if (s_num_points < MAX_POINTFILE)
+ {
+ VectorCopy (v, s_pointvecs[s_num_points]);
+ s_num_points++;
+ }
+ qglVertex3fv (v);
+ } while (1);
+ qglEnd();
+ qglLineWidth (1);
+ qglEndList ();
+
+ s_check_point = 0;
+ fclose (f);
+ //Pointfile_Next ();
+}
+
+void Pointfile_Draw( void )
+{
+ int i;
+
+ qglColor3f( 1.0F, 0.0F, 0.0F );
+ qglDisable(GL_TEXTURE_2D);
+ qglDisable(GL_TEXTURE_1D);
+ qglLineWidth (4);
+ qglBegin(GL_LINE_STRIP);
+ for ( i = 0; i < s_num_points; i++ )
+ {
+ qglVertex3fv( s_pointvecs[i] );
+ }
+ qglEnd();
+ qglLineWidth( 1 );
+}
+
+void Pointfile_Clear (void)
+{
+ if (!g_qeglobals.d_pointfile_display_list)
+ return;
+
+ qglDeleteLists (g_qeglobals.d_pointfile_display_list, 1);
+ g_qeglobals.d_pointfile_display_list = 0;
+ Sys_UpdateWindows (W_ALL);
+}
+
diff --git a/q3radiant/PatchDensityDlg.cpp b/q3radiant/PatchDensityDlg.cpp
new file mode 100755
index 0000000..3fda571
--- /dev/null
+++ b/q3radiant/PatchDensityDlg.cpp
@@ -0,0 +1,89 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// PatchDensityDlg.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "PatchDensityDlg.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CPatchDensityDlg dialog
+
+
+CPatchDensityDlg::CPatchDensityDlg(CWnd* pParent /*=NULL*/)
+ : CDialog(CPatchDensityDlg::IDD, pParent)
+{
+ //{{AFX_DATA_INIT(CPatchDensityDlg)
+ //}}AFX_DATA_INIT
+}
+
+
+void CPatchDensityDlg::DoDataExchange(CDataExchange* pDX)
+{
+ CDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CPatchDensityDlg)
+ DDX_Control(pDX, IDC_COMBO_WIDTH, m_wndWidth);
+ DDX_Control(pDX, IDC_COMBO_HEIGHT, m_wndHeight);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CPatchDensityDlg, CDialog)
+ //{{AFX_MSG_MAP(CPatchDensityDlg)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CPatchDensityDlg message handlers
+
+int g_nXLat[] = {3,5,7,9,11,13,15};
+
+void CPatchDensityDlg::OnOK()
+{
+ int nWidth = m_wndWidth.GetCurSel();
+ int nHeight = m_wndHeight.GetCurSel();
+
+ if (nWidth >= 0 && nWidth <= 6 && nHeight >= 0 && nHeight <= 6)
+ {
+ Patch_GenericMesh(g_nXLat[nWidth], g_nXLat[nHeight], g_pParentWnd->ActiveXY()->GetViewType());
+ Sys_UpdateWindows(W_ALL);
+ }
+
+ CDialog::OnOK();
+}
+
+BOOL CPatchDensityDlg::OnInitDialog()
+{
+ CDialog::OnInitDialog();
+
+ m_wndWidth.SetCurSel(0);
+ m_wndHeight.SetCurSel(0);
+ return TRUE; // return TRUE unless you set the focus to a control
+ // EXCEPTION: OCX Property Pages should return FALSE
+}
diff --git a/q3radiant/PatchDensityDlg.h b/q3radiant/PatchDensityDlg.h
new file mode 100755
index 0000000..9297e16
--- /dev/null
+++ b/q3radiant/PatchDensityDlg.h
@@ -0,0 +1,69 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_PATCHDENSITYDLG_H__509162A1_1023_11D2_AFFB_00AA00A410FC__INCLUDED_)
+#define AFX_PATCHDENSITYDLG_H__509162A1_1023_11D2_AFFB_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// PatchDensityDlg.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CPatchDensityDlg dialog
+
+class CPatchDensityDlg : public CDialog
+{
+// Construction
+public:
+ CPatchDensityDlg(CWnd* pParent = NULL); // standard constructor
+
+// Dialog Data
+ //{{AFX_DATA(CPatchDensityDlg)
+ enum { IDD = IDD_DIALOG_NEWPATCH };
+ CComboBox m_wndWidth;
+ CComboBox m_wndHeight;
+ //}}AFX_DATA
+
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CPatchDensityDlg)
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+
+ // Generated message map functions
+ //{{AFX_MSG(CPatchDensityDlg)
+ virtual void OnOK();
+ virtual BOOL OnInitDialog();
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_PATCHDENSITYDLG_H__509162A1_1023_11D2_AFFB_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/PatchDialog.cpp b/q3radiant/PatchDialog.cpp
new file mode 100755
index 0000000..316e145
--- /dev/null
+++ b/q3radiant/PatchDialog.cpp
@@ -0,0 +1,354 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// PatchDialog.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "PatchDialog.h"
+#include "TextureLayout.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CPatchDialog dialog
+
+CPatchDialog g_PatchDialog;
+
+CPatchDialog::CPatchDialog(CWnd* pParent /*=NULL*/)
+ : CDialog(CPatchDialog::IDD, pParent)
+{
+ //{{AFX_DATA_INIT(CPatchDialog)
+ m_strName = _T("");
+ m_fS = 0.0f;
+ m_fT = 0.0f;
+ m_fX = 0.0f;
+ m_fY = 0.0f;
+ m_fZ = 0.0f;
+ m_fHScale = 0.05f;
+ m_fHShift = 0.05f;
+ m_fRotate = 45;
+ m_fVScale = 0.05f;
+ m_fVShift = 0.05f;
+ //}}AFX_DATA_INIT
+ m_Patch = NULL;
+}
+
+
+void CPatchDialog::DoDataExchange(CDataExchange* pDX)
+{
+ CDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CPatchDialog)
+ DDX_Control(pDX, IDC_SPIN_VSHIFT, m_wndVShift);
+ DDX_Control(pDX, IDC_SPIN_VSCALE, m_wndVScale);
+ DDX_Control(pDX, IDC_SPIN_ROTATE, m_wndRotate);
+ DDX_Control(pDX, IDC_SPIN_HSHIFT, m_wndHShift);
+ DDX_Control(pDX, IDC_SPIN_HSCALE, m_wndHScale);
+ DDX_Control(pDX, IDC_COMBO_TYPE, m_wndType);
+ DDX_Control(pDX, IDC_COMBO_ROW, m_wndRows);
+ DDX_Control(pDX, IDC_COMBO_COL, m_wndCols);
+ DDX_Text(pDX, IDC_EDIT_NAME, m_strName);
+ DDX_Text(pDX, IDC_EDIT_S, m_fS);
+ DDX_Text(pDX, IDC_EDIT_T, m_fT);
+ DDX_Text(pDX, IDC_EDIT_X, m_fX);
+ DDX_Text(pDX, IDC_EDIT_Y, m_fY);
+ DDX_Text(pDX, IDC_EDIT_Z, m_fZ);
+ DDX_Text(pDX, IDC_HSCALE, m_fHScale);
+ DDX_Text(pDX, IDC_HSHIFT, m_fHShift);
+ DDX_Text(pDX, IDC_ROTATE, m_fRotate);
+ DDX_Text(pDX, IDC_VSCALE, m_fVScale);
+ DDX_Text(pDX, IDC_VSHIFT, m_fVShift);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CPatchDialog, CDialog)
+ //{{AFX_MSG_MAP(CPatchDialog)
+ ON_BN_CLICKED(IDC_BTN_PATCHDETAILS, OnBtnPatchdetails)
+ ON_BN_CLICKED(IDC_BTN_PATCHFIT, OnBtnPatchfit)
+ ON_BN_CLICKED(IDC_BTN_PATCHNATURAL, OnBtnPatchnatural)
+ ON_BN_CLICKED(IDC_BTN_PATCHRESET, OnBtnPatchreset)
+ ON_CBN_SELCHANGE(IDC_COMBO_COL, OnSelchangeComboCol)
+ ON_CBN_SELCHANGE(IDC_COMBO_ROW, OnSelchangeComboRow)
+ ON_CBN_SELCHANGE(IDC_COMBO_TYPE, OnSelchangeComboType)
+ ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN_HSCALE, OnDeltaposSpin)
+ ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN_ROTATE, OnDeltaposSpin)
+ ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN_VSCALE, OnDeltaposSpin)
+ ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN_VSHIFT, OnDeltaposSpin)
+ ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN_HSHIFT, OnDeltaposSpin)
+ ON_WM_DESTROY()
+ ON_BN_CLICKED(ID_APPLY, OnApply)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CPatchDialog message handlers
+
+void CPatchDialog::OnBtnPatchdetails()
+{
+ Patch_NaturalizeSelected(true);
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CPatchDialog::OnBtnPatchfit()
+{
+ Patch_FitTexturing();
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CPatchDialog::OnBtnPatchnatural()
+{
+ Patch_NaturalizeSelected();
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CPatchDialog::OnBtnPatchreset()
+{
+ CTextureLayout dlg;
+ if (dlg.DoModal() == IDOK)
+ {
+ Patch_ResetTexturing(dlg.m_fX, dlg.m_fY);
+ }
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CPatchDialog::OnSelchangeComboCol()
+{
+ UpdateRowColInfo();
+}
+
+void CPatchDialog::OnSelchangeComboRow()
+{
+ UpdateRowColInfo();
+}
+
+void CPatchDialog::OnSelchangeComboType()
+{
+ // TODO: Add your control notification handler code here
+
+}
+
+void CPatchDialog::OnOK()
+{
+ m_Patch = NULL;
+
+ CDialog::OnOK();
+}
+
+void CPatchDialog::OnDeltaposSpin(NMHDR* pNMHDR, LRESULT* pResult)
+{
+ NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
+ UpdateSpinners((pNMUpDown->iDelta > 0), pNMUpDown->hdr.idFrom);
+ *pResult = 0;
+}
+
+BOOL CPatchDialog::OnInitDialog()
+{
+ CDialog::OnInitDialog();
+
+ m_wndHScale.SetRange(0, 1000);
+ m_wndVScale.SetRange(0, 1000);
+ m_wndHShift.SetRange(0, 1000);
+ m_wndVShift.SetRange(0, 1000);
+ m_wndRotate.SetRange(0, 1000);
+
+ GetPatchInfo();
+
+ // TODO: Add extra initialization here
+
+ return TRUE; // return TRUE unless you set the focus to a control
+ // EXCEPTION: OCX Property Pages should return FALSE
+}
+
+
+
+void CPatchDialog::GetPatchInfo()
+{
+ m_Patch = SinglePatchSelected();
+ if (m_Patch != NULL)
+ {
+ CString str;
+ int i;
+ m_wndRows.ResetContent();
+ for (i = 0; i < m_Patch->height; i++)
+ {
+ str.Format("%i", i);
+ m_wndRows.AddString(str);
+ }
+ m_wndRows.SetCurSel(0);
+ m_wndCols.ResetContent();
+ for (i = 0; i < m_Patch->width; i++)
+ {
+ str.Format("%i", i);
+ m_wndCols.AddString(str);
+ }
+ m_wndCols.SetCurSel(0);
+ }
+ UpdateRowColInfo();
+}
+
+void CPatchDialog::SetPatchInfo()
+{
+
+}
+
+void DoPatchInspector()
+{
+ if (g_PatchDialog.GetSafeHwnd() == NULL)
+ {
+ g_PatchDialog.Create(IDD_DIALOG_PATCH);
+ CRect rct;
+ LONG lSize = sizeof(rct);
+ if (LoadRegistryInfo("Radiant::PatchWindow", &rct, &lSize))
+ {
+ g_PatchDialog.SetWindowPos(NULL, rct.left, rct.top, 0,0, SWP_NOSIZE);
+ }
+ }
+ g_PatchDialog.ShowWindow(SW_SHOW);
+ g_PatchDialog.GetPatchInfo();
+}
+
+void UpdatePatchInspector()
+{
+ if (g_PatchDialog.GetSafeHwnd() != NULL)
+ {
+ g_PatchDialog.UpdateInfo();
+ }
+
+}
+
+void CPatchDialog::OnDestroy()
+{
+ if (GetSafeHwnd())
+ {
+ CRect rct;
+ GetWindowRect(rct);
+ SaveRegistryInfo("Radiant::PatchWindow", &rct, sizeof(rct));
+ }
+ CDialog::OnDestroy();
+}
+
+void CPatchDialog::UpdateRowColInfo()
+{
+ m_fX = m_fY = m_fZ = m_fS = m_fT = 0.0;
+
+ if (m_Patch != NULL)
+ {
+ int r = m_wndRows.GetCurSel();
+ int c = m_wndCols.GetCurSel();
+ if (r >= 0 && r < m_Patch->height && c >= 0 && c < m_Patch->width)
+ {
+ m_fX = m_Patch->ctrl[c][r].xyz[0];
+ m_fY = m_Patch->ctrl[c][r].xyz[1];
+ m_fZ = m_Patch->ctrl[c][r].xyz[2];
+ m_fS = m_Patch->ctrl[c][r].st[0];
+ m_fT = m_Patch->ctrl[c][r].st[1];
+ }
+ }
+ UpdateData(FALSE);
+}
+
+void CPatchDialog::UpdateInfo()
+{
+ GetPatchInfo();
+}
+
+void CPatchDialog::OnApply()
+{
+ UpdateData(TRUE);
+ if (m_Patch != NULL)
+ {
+ int r = m_wndRows.GetCurSel();
+ int c = m_wndCols.GetCurSel();
+ if (r >= 0 && r < m_Patch->height && c >= 0 && c < m_Patch->width)
+ {
+ m_Patch->ctrl[c][r].xyz[0] = m_fX;
+ m_Patch->ctrl[c][r].xyz[1] = m_fY;
+ m_Patch->ctrl[c][r].xyz[2] = m_fZ;
+ m_Patch->ctrl[c][r].st[0] = m_fS;
+ m_Patch->ctrl[c][r].st[1] = m_fT;
+ m_Patch->bDirty = true;
+ Sys_UpdateWindows(W_ALL);
+ }
+ }
+}
+
+void CPatchDialog::UpdateSpinners(bool bUp, int nID)
+{
+ texdef_t td;
+
+ td.rotate = 0.0;
+ td.scale[0] = td.scale[1] = 0.0;
+ td.shift[0] = td.shift[1] = 0.0;
+ td.contents = 0;
+ td.flags = 0;
+ td.value = 0;
+
+
+ UpdateData(TRUE);
+
+ if (nID == IDC_SPIN_ROTATE)
+ {
+ if (bUp)
+ td.rotate = m_fRotate;
+ else
+ td.rotate = -m_fRotate;
+ }
+ else if (nID == IDC_SPIN_HSCALE)
+ {
+ if (bUp)
+ td.scale[0] = 1 - m_fHScale;
+ else
+ td.scale[0] = 1 + m_fHScale;
+ }
+ else if (nID == IDC_SPIN_VSCALE)
+ {
+ if (bUp)
+ td.scale[1] = 1 - m_fVScale;
+ else
+ td.scale[1] = 1 + m_fVScale;
+ }
+
+ else if (nID == IDC_SPIN_HSHIFT)
+ {
+ if (bUp)
+ td.shift[0] = m_fHShift;
+ else
+ td.shift[0] = -m_fHShift;
+ }
+ else if (nID == IDC_SPIN_VSHIFT)
+ {
+ if (bUp)
+ td.shift[1] = m_fVShift;
+ else
+ td.shift[1] = -m_fVShift;
+ }
+
+ Patch_SetTextureInfo(&td);
+ Sys_UpdateWindows(W_CAMERA);
+}
+
+
diff --git a/q3radiant/PatchDialog.h b/q3radiant/PatchDialog.h
new file mode 100755
index 0000000..572acc9
--- /dev/null
+++ b/q3radiant/PatchDialog.h
@@ -0,0 +1,102 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_PATCHDIALOG_H__DE62DFB4_E9EC_11D2_A509_0020AFEB881A__INCLUDED_)
+#define AFX_PATCHDIALOG_H__DE62DFB4_E9EC_11D2_A509_0020AFEB881A__INCLUDED_
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+// PatchDialog.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CPatchDialog dialog
+
+class CPatchDialog : public CDialog
+{
+ patchMesh_t *m_Patch;
+// Construction
+public:
+ void UpdateInfo();
+ void SetPatchInfo();
+ void GetPatchInfo();
+ CPatchDialog(CWnd* pParent = NULL); // standard constructor
+ void UpdateSpinners(bool bUp, int nID);
+
+// Dialog Data
+ //{{AFX_DATA(CPatchDialog)
+ enum { IDD = IDD_DIALOG_PATCH };
+ CSpinButtonCtrl m_wndVShift;
+ CSpinButtonCtrl m_wndVScale;
+ CSpinButtonCtrl m_wndRotate;
+ CSpinButtonCtrl m_wndHShift;
+ CSpinButtonCtrl m_wndHScale;
+ CComboBox m_wndType;
+ CComboBox m_wndRows;
+ CComboBox m_wndCols;
+ CString m_strName;
+ float m_fS;
+ float m_fT;
+ float m_fX;
+ float m_fY;
+ float m_fZ;
+ float m_fHScale;
+ float m_fHShift;
+ float m_fRotate;
+ float m_fVScale;
+ float m_fVShift;
+ //}}AFX_DATA
+
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CPatchDialog)
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+ void UpdateRowColInfo();
+
+ // Generated message map functions
+ //{{AFX_MSG(CPatchDialog)
+ afx_msg void OnBtnPatchdetails();
+ afx_msg void OnBtnPatchfit();
+ afx_msg void OnBtnPatchnatural();
+ afx_msg void OnBtnPatchreset();
+ afx_msg void OnSelchangeComboCol();
+ afx_msg void OnSelchangeComboRow();
+ afx_msg void OnSelchangeComboType();
+ virtual void OnOK();
+ afx_msg void OnDeltaposSpin(NMHDR* pNMHDR, LRESULT* pResult);
+ virtual BOOL OnInitDialog();
+ afx_msg void OnDestroy();
+ afx_msg void OnApply();
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_PATCHDIALOG_H__DE62DFB4_E9EC_11D2_A509_0020AFEB881A__INCLUDED_)
diff --git a/q3radiant/PlugIn.cpp b/q3radiant/PlugIn.cpp
new file mode 100755
index 0000000..7c19044
--- /dev/null
+++ b/q3radiant/PlugIn.cpp
@@ -0,0 +1,297 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// PlugIn.cpp: implementation of the CPlugIn class.
+//
+//////////////////////////////////////////////////////////////////////
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "PlugIn.h"
+
+#ifdef _DEBUG
+#undef THIS_FILE
+static char THIS_FILE[]=__FILE__;
+#define new DEBUG_NEW
+#endif
+
+//////////////////////////////////////////////////////////////////////
+// Construction/Destruction
+//////////////////////////////////////////////////////////////////////
+
+CPlugIn::CPlugIn()
+{
+ m_hDLL = NULL;
+ m_pQERPlugEntitiesFactory = NULL;
+}
+
+CPlugIn::~CPlugIn()
+{
+ if (m_pQERPlugEntitiesFactory)
+ delete m_pQERPlugEntitiesFactory;
+ if (m_hDLL != NULL)
+ free();
+}
+
+bool CPlugIn::load(const char *p)
+{
+ m_hDLL = ::LoadLibrary(p);
+ if (m_hDLL != NULL)
+ {
+ m_pfnInit = reinterpret_cast<PFN_QERPLUG_INIT>(::GetProcAddress(m_hDLL, QERPLUG_INIT));
+ if (m_pfnInit != NULL)
+ {
+ m_strVersion = (*m_pfnInit)(AfxGetApp()->m_hInstance, g_pParentWnd->GetSafeHwnd());
+ Sys_Printf("Loaded plugin > %s\n", m_strVersion);
+
+ m_pfnGetName = reinterpret_cast<PFN_QERPLUG_GETNAME>(::GetProcAddress(m_hDLL, QERPLUG_GETNAME));
+ if (m_pfnGetName != NULL)
+ {
+ m_strName = (*m_pfnGetName)();
+ }
+
+ m_pfnGetCommandList = reinterpret_cast<PFN_QERPLUG_GETCOMMANDLIST>(::GetProcAddress(m_hDLL, QERPLUG_GETCOMMANDLIST));
+ if (m_pfnGetCommandList)
+ {
+ CString str = (*m_pfnGetCommandList)();
+ char cTemp[1024];
+ strcpy(cTemp, str);
+ char* token = strtok(cTemp, ",;");
+ if (token && *token == ' ')
+ {
+ while (*token == ' ')
+ token++;
+ }
+ while (token != NULL)
+ {
+ m_CommandStrings.Add(token);
+ token = strtok(NULL, ",;");
+ }
+ }
+
+ m_pfnDispatch = reinterpret_cast<PFN_QERPLUG_DISPATCH>(::GetProcAddress(m_hDLL, QERPLUG_DISPATCH));
+ m_pfnGetFuncTable = reinterpret_cast<PFN_QERPLUG_GETFUNCTABLE>(::GetProcAddress(m_hDLL, QERPLUG_GETFUNCTABLE));
+
+ m_pfnGetTextureInfo = reinterpret_cast<PFN_QERPLUG_GETTEXTUREINFO>(::GetProcAddress(m_hDLL, QERPLUG_GETTEXTUREINFO));
+ m_pfnLoadTexture = reinterpret_cast<PFN_QERPLUG_LOADTEXTURE>(::GetProcAddress(m_hDLL, QERPLUG_LOADTEXTURE));
+
+ m_pfnGetSurfaceFlags = reinterpret_cast<PFN_QERPLUG_GETSURFACEFLAGS>(::GetProcAddress(m_hDLL, QERPLUG_GETSURFACEFLAGS));
+
+ m_pfnRegisterPluginEntities = reinterpret_cast<PFN_QERPLUG_REGISTERPLUGINENTITIES>(::GetProcAddress(m_hDLL, QERPLUG_REGISTERPLUGINENTITIES));
+
+ m_pfnInitSurfaceProperties = reinterpret_cast<PFN_QERPLUG_INITSURFACEPROPERTIES>(::GetProcAddress(m_hDLL, QERPLUG_INITSURFACEPROPERTIES));
+
+ m_pfnRequestInterface = reinterpret_cast<PFN_QERPLUG_REQUESTINTERFACE>(::GetProcAddress(m_hDLL, QERPLUG_REQUESTINTERFACE));
+
+ return (m_pfnDispatch != NULL && m_pfnGetFuncTable != NULL);
+ //--return true;
+ }
+ Sys_Printf("FAILED to Load plugin > %s\n", p);
+ }
+ LPVOID lpMsgBuf;
+ FormatMessage(
+ FORMAT_MESSAGE_ALLOCATE_BUFFER |
+ FORMAT_MESSAGE_FROM_SYSTEM |
+ FORMAT_MESSAGE_IGNORE_INSERTS,
+ NULL,
+ GetLastError(),
+ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
+ (LPTSTR) &lpMsgBuf,
+ 0,
+ NULL
+ );
+ Sys_Printf("LoadLibrary failed on %s: GetLastError: %s\n", p, lpMsgBuf );
+ // Free the buffer.
+ LocalFree( lpMsgBuf );
+ free();
+ return false;
+}
+
+_QERTextureInfo* CPlugIn::getTextureInfo()
+{
+ if (m_pfnGetTextureInfo != NULL)
+ {
+ return reinterpret_cast<_QERTextureInfo*>((*m_pfnGetTextureInfo)());
+ }
+ return NULL;
+}
+
+void CPlugIn::loadTexture(LPCSTR pFilename)
+{
+ if (m_pfnLoadTexture != NULL)
+ {
+ (*m_pfnLoadTexture)(pFilename);
+ }
+}
+
+LPVOID CPlugIn::getSurfaceFlags()
+{
+ if (m_pfnGetSurfaceFlags != NULL)
+ {
+ return reinterpret_cast<LPVOID>((*m_pfnGetSurfaceFlags)());
+ }
+ return NULL;
+}
+
+void CPlugIn::free()
+{
+ if (m_hDLL != NULL)
+ ::FreeLibrary(m_hDLL);
+ m_hDLL = NULL;
+}
+
+const char* CPlugIn::getVersionStr()
+{
+ return m_pfnGetName();
+}
+
+const char* CPlugIn::getMenuName()
+{
+ return m_strName;
+}
+
+int CPlugIn::getCommandCount()
+{
+ return m_CommandStrings.GetSize();
+}
+
+const char* CPlugIn::getCommand(int n)
+{
+ return m_CommandStrings.GetAt(n);
+}
+
+void CPlugIn::dispatchCommand(const char* p, vec3_t vMin, vec3_t vMax, BOOL bSingleBrush)
+{
+ if (m_pfnDispatch)
+ {
+ (*m_pfnDispatch)(p, vMin, vMax, bSingleBrush);
+ }
+}
+
+void CPlugIn::addMenuID(int n)
+{
+ m_CommandIDs.Add(n);
+}
+
+bool CPlugIn::ownsCommandID(int n)
+{
+ for (int i = 0; i < m_CommandIDs.GetSize(); i++)
+ {
+ if (m_CommandIDs.GetAt(i) == n)
+ return true;
+ }
+ return false;
+}
+
+void* CPlugIn::getFuncTable()
+{
+ if (m_pfnGetFuncTable)
+ {
+ return (*m_pfnGetFuncTable)();
+ }
+ return NULL;
+}
+
+void CPlugIn::RegisterPluginEntities()
+{
+ // if we found the QERPlug_RegisterPluginEntities export, it means this plugin provides his own entities
+ if (m_pfnRegisterPluginEntities)
+ {
+ // resquest a _QERPlugEntitiesFactory
+ if (m_pfnRequestInterface)
+ {
+ m_pQERPlugEntitiesFactory = new _QERPlugEntitiesFactory;
+ m_pQERPlugEntitiesFactory->m_nSize = sizeof(_QERPlugEntitiesFactory);
+ if (m_pfnRequestInterface( QERPlugEntitiesFactory_GUID, m_pQERPlugEntitiesFactory ))
+ {
+ // create an IEpair interface for the project settings
+ CEpairsWrapper *pProjectEp = new CEpairsWrapper( g_qeglobals.d_project_entity );
+ m_pfnRegisterPluginEntities( pProjectEp );
+ }
+ else
+ Sys_Printf( "WARNING: failed to request QERPlugEntitiesFactory from plugin %s\n", m_strName.GetBuffer(0) );
+ }
+ else
+ Sys_Printf( "WARNING: QERPlug_RequestInterface not found in %s\n", m_strName.GetBuffer(0) );
+ }
+}
+
+void CPlugIn::InitBSPFrontendPlugin()
+{
+ if (m_pfnRequestInterface)
+ {
+ // request a _QERPlugBSPFrontendTable
+ g_BSPFrontendTable.m_nSize = sizeof( _QERPlugBSPFrontendTable );
+ if ( m_pfnRequestInterface( QERPlugBSPFrontendTable_GUID, &g_BSPFrontendTable ) )
+ {
+ g_qeglobals.bBSPFrontendPlugin = true;
+ }
+ }
+}
+
+void CPlugIn::InitSurfacePlugin()
+{
+ // if we found the QERPlug_InitSurfaceProperties export, it means this plugin does surface properties
+ if (m_pfnInitSurfaceProperties)
+ {
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+ Sys_Printf( "WARNING: conflict for surface properties plugins. %s ignored.\n", m_strName );
+ return;
+ }
+ if (m_pfnRequestInterface)
+ {
+ // call the plugin surface properties init
+ m_pfnInitSurfaceProperties();
+ // request filling of the global _QERPlugSurfaceTable
+ g_SurfaceTable.m_nSize = sizeof( g_SurfaceTable );
+ if ( m_pfnRequestInterface( QERPlugSurfaceTable_GUID, &g_SurfaceTable ) )
+ {
+ // update the global so we know we have a surface properties plugin
+ g_qeglobals.bSurfacePropertiesPlugin = true;
+ }
+ else
+ Sys_Printf( "WARNING: _QERPlugSurfaceTable interface request failed for surface plugin\n" );
+ }
+ else
+ Sys_Printf("WARNING: QERPlug_RequestInterface export not found in surface properties plugin.\n");
+ }
+}
+
+// create a plugin entity
+// e is the entity being created
+// e->eclass is the plugin eclass info
+// e->epairs will be accessed by the plugin entity through a IEpair interface
+IPluginEntity * CPlugIn::CreatePluginEntity(entity_t *e)
+{
+ if (m_pQERPlugEntitiesFactory)
+ {
+ // create an IEpair interface for e->epairs
+ CEpairsWrapper *pEp = new CEpairsWrapper( e );
+ IPluginEntity *pEnt = m_pQERPlugEntitiesFactory->m_pfnCreateEntity( e->eclass, pEp );
+ if ( pEnt )
+ return pEnt;
+ delete pEp;
+ return NULL;
+ }
+ Sys_Printf("WARNING: unexpected m_pQERPlugEntitiesFactory is NULL in CPlugin::CreatePluginEntity\n");
+ return NULL;
+}
diff --git a/q3radiant/PlugIn.h b/q3radiant/PlugIn.h
new file mode 100755
index 0000000..d534ae3
--- /dev/null
+++ b/q3radiant/PlugIn.h
@@ -0,0 +1,82 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// PlugIn.h: interface for the CPlugIn class.
+//
+//////////////////////////////////////////////////////////////////////
+
+#if !defined(AFX_PLUGIN_H__B501A832_5755_11D2_B084_00AA00A410FC__INCLUDED_)
+#define AFX_PLUGIN_H__B501A832_5755_11D2_B084_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+
+class CPlugIn : public CObject
+{
+private:
+ HMODULE m_hDLL;
+ PFN_QERPLUG_INIT m_pfnInit;
+ PFN_QERPLUG_GETNAME m_pfnGetName;
+ PFN_QERPLUG_GETCOMMANDLIST m_pfnGetCommandList;
+ PFN_QERPLUG_DISPATCH m_pfnDispatch;
+ PFN_QERPLUG_GETFUNCTABLE m_pfnGetFuncTable;
+ PFN_QERPLUG_GETTEXTUREINFO m_pfnGetTextureInfo;
+ PFN_QERPLUG_LOADTEXTURE m_pfnLoadTexture;
+ PFN_QERPLUG_GETSURFACEFLAGS m_pfnGetSurfaceFlags;
+ PFN_QERPLUG_REGISTERPLUGINENTITIES m_pfnRegisterPluginEntities;
+ PFN_QERPLUG_INITSURFACEPROPERTIES m_pfnInitSurfaceProperties;
+ PFN_QERPLUG_REQUESTINTERFACE m_pfnRequestInterface;
+ CWordArray m_CommandIDs;
+ CStringArray m_CommandStrings;
+ CString m_strName;
+ CString m_strVersion;
+
+ // for plugins that provide plugin entities
+ _QERPlugEntitiesFactory* m_pQERPlugEntitiesFactory;
+
+public:
+ void InitBSPFrontendPlugin();
+ IPluginEntity * CreatePluginEntity( entity_t * );
+ HMODULE GetDLLModule() { return m_hDLL; }
+ void InitSurfacePlugin();
+ void RegisterPluginEntities();
+ void* getFuncTable();
+ bool ownsCommandID(int n);
+ void addMenuID(int n);
+ CPlugIn();
+ virtual ~CPlugIn();
+ bool load(const char *p);
+ void free();
+ const char* getVersionStr();
+ const char* getMenuName();
+ int getCommandCount();
+ const char* getCommand(int n);
+ void dispatchCommand(const char* p, vec3_t vMin, vec3_t vMax, BOOL bSingleBrush);
+
+ _QERTextureInfo *getTextureInfo();
+ void loadTexture(LPCSTR pFilename);
+
+ LPVOID getSurfaceFlags();
+
+};
+
+#endif // !defined(AFX_PLUGIN_H__B501A832_5755_11D2_B084_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/PlugInManager.cpp b/q3radiant/PlugInManager.cpp
new file mode 100755
index 0000000..1a9e76a
--- /dev/null
+++ b/q3radiant/PlugInManager.cpp
@@ -0,0 +1,1665 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// PlugInManager.cpp: implementation of the CPlugInManager class.
+//
+//////////////////////////////////////////////////////////////////////
+
+#include "stdafx.h"
+#include "io.h"
+#include "Radiant.h"
+#include "PlugInManager.h"
+#include "PlugIn.h"
+#include "DialogInfo.h"
+#include "pakstuff.h"
+
+#ifdef _DEBUG
+#undef THIS_FILE
+static char THIS_FILE[]=__FILE__;
+#define new DEBUG_NEW
+#endif
+
+//////////////////////////////////////////////////////////////////////
+// Construction/Destruction
+//////////////////////////////////////////////////////////////////////
+
+CPlugInManager::CPlugInManager()
+{
+ m_pTexturePlug = NULL;
+ m_pSurfaceListPlug = NULL;
+ PatchesMode = EActivePatches;
+}
+
+CPlugInManager::~CPlugInManager()
+{
+ Cleanup();
+}
+
+void CPlugInManager::Init(const char * pPath)
+{
+ Cleanup();
+
+ // set some globals
+ g_qeglobals.bSurfacePropertiesPlugin = false;
+ g_qeglobals.bBSPFrontendPlugin = false;
+
+ CString strPath(pPath);
+ strPath += "*.dll";
+
+ bool bGo = true;
+
+ struct _finddata_t fileinfo;
+ int handle = _findfirst (strPath, &fileinfo);
+ if (handle != -1)
+ {
+ do
+ {
+ strPath.Format("%s\\%s", pPath, fileinfo.name);
+ CPlugIn *pPlug = new CPlugIn();
+ if (pPlug->load(strPath))
+ {
+ if(FillFuncTable(pPlug)) // PGM
+ {
+ m_PlugIns.Add(pPlug);
+
+ pPlug->RegisterPluginEntities();
+
+ // if this thing handles surface properties
+ pPlug->InitSurfacePlugin();
+
+ // will test and init if it's a BSP frontend
+ pPlug->InitBSPFrontendPlugin();
+
+ g_pParentWnd->AddPlugInMenuItem(pPlug);
+
+ // if this thing handles textures
+ if (pPlug->getTextureInfo() != NULL)
+ {
+ this->m_pTexturePlug = pPlug;
+
+ // if this is a wad style texture extension, have it load everything now
+ if (pPlug->getTextureInfo()->m_bWadStyle)
+ {
+ CString strPath = ValueForKey(g_qeglobals.d_project_entity, "texturepath");
+ pPlug->loadTexture(strPath);
+ }
+ }
+
+ if (pPlug->getSurfaceFlags() != NULL)
+ {
+ this->m_pSurfaceListPlug = pPlug;
+ }
+ }
+ else
+ {
+ delete pPlug; // PGM
+ }
+ }
+ else
+ {
+ delete pPlug;
+ }
+ } while (_findnext( handle, &fileinfo ) != -1);
+ _findclose (handle);
+ }
+
+}
+
+void CPlugInManager::Cleanup()
+{
+ int i;
+ for (i = 0; i < m_PlugIns.GetSize(); i++)
+ {
+ CPlugIn *plug = reinterpret_cast<CPlugIn*>(m_PlugIns.GetAt(i));
+ plug->free();
+ delete plug;
+ }
+ m_PlugIns.RemoveAll();
+
+ for (i = 0; i < m_BrushHandles.GetSize(); i++)
+ {
+ brush_t *pb = reinterpret_cast<brush_t*>(m_BrushHandles.GetAt(i));
+ Brush_Free(pb);
+ }
+ m_BrushHandles.RemoveAll();
+
+ for (i = 0; i < m_EntityHandles.GetSize(); i++)
+ {
+ entity_t *pe = reinterpret_cast<entity_t*>(m_EntityHandles.GetAt(i));
+ Entity_Free(pe);
+ }
+ m_EntityHandles.RemoveAll();
+
+ // patches
+ // these are linked into the map
+ m_PatchesHandles.RemoveAll();
+ // these patches were allocated by Radiant on plugin request
+ // if the list is not empty, it means either the plugin asked for allocation and never commited them to the map
+ // in which case we are supposed to delete them
+ // or it commited them but never called m_pfnReleasePatchHandles, in case the patches may have already been
+ // erased and we are trying a second time, therefore crashing ..
+ //++timo FIXME: for now I leave a leak warning, we'd need a table to keep track of commited patches
+#ifdef _DEBUG
+ if (m_PluginPatches.GetSize() != 0)
+ Sys_Printf("WARNING: m_PluginPatches.GetSize() != 0 in CPlugInManager::Cleanup, possible leak\n");
+#endif
+/* for (i = 0; i < m_PluginPatches.GetSize(); i++)
+ {
+ patchMesh_t *pMesh = reinterpret_cast<patchMesh_t*>(m_PluginPatches.GetAt(i));
+ if (pMesh->pSymbiot)
+ delete pMesh;
+ }
+ m_PluginPatches.RemoveAll(); */
+}
+
+void CPlugInManager::Dispatch(int n, const char * p)
+{
+ for (int i = 0; i < m_PlugIns.GetSize(); i++)
+ {
+ CPlugIn *plug = reinterpret_cast<CPlugIn*>(m_PlugIns.GetAt(i));
+ if (plug->ownsCommandID(n))
+ {
+ vec3_t vMin, vMax;
+ if (selected_brushes.next == &selected_brushes)
+ {
+ vMin[0] = vMin[1] = vMin[2] = 0;
+ VectorCopy(vMin, vMax);
+ }
+ else
+ {
+ Select_GetBounds (vMin, vMax);
+ }
+ plug->dispatchCommand(p, vMin, vMax, QE_SingleBrush(true)); // PGM -- added quiet
+ break;
+ }
+ }
+}
+
+// creates a dummy brush in the active brushes list
+// FIXME : is this one really USED ?
+void WINAPI QERApp_CreateBrush(vec3_t vMin, vec3_t vMax)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+
+ brush_t* pBrush = Brush_Create(vMin, vMax, &g_qeglobals.d_texturewin.texdef);
+ Entity_LinkBrush (world_entity, pBrush);
+ Brush_Build(pBrush);
+ Brush_AddToList (pBrush, &active_brushes);
+ Select_Brush(pBrush);
+ Sys_UpdateWindows(W_ALL);
+}
+
+LPVOID CPlugInManager::CreateBrushHandle()
+{
+ brush_t *pb = Brush_Alloc();
+ pb->numberId = g_nBrushId++;
+ m_BrushHandles.Add(pb);
+ return (LPVOID)pb;
+}
+
+void CPlugInManager::DeleteBrushHandle(void * vp)
+{
+ CPtrArray* pHandles[3];
+ pHandles[0] = &m_SelectedBrushHandles;
+ pHandles[1] = &m_ActiveBrushHandles;
+ pHandles[2] = &m_BrushHandles;
+
+ for (int j = 0; j < 3; j++)
+ {
+ for (int i = 0; i < pHandles[j]->GetSize(); i++)
+ {
+ brush_t *pb = reinterpret_cast<brush_t*>(pHandles[j]->GetAt(i));
+ if (pb == reinterpret_cast<brush_t*>(vp))
+ {
+ if (j == 2)
+ {
+ // only remove it from the list if it is work area
+ // this allows the selected and active list indexes to remain constant
+ // throughout a session (i.e. between an allocate and release)
+ pHandles[j]->RemoveAt(i);
+ }
+ Brush_Free(pb);
+ Sys_MarkMapModified(); // PGM
+ return;
+ }
+ }
+ }
+}
+
+void CPlugInManager::CommitBrushHandleToMap(void * vp)
+{
+ g_bScreenUpdates = false;
+ for (int i = 0; i < m_BrushHandles.GetSize(); i++)
+ {
+ brush_t *pb = reinterpret_cast<brush_t*>(m_BrushHandles.GetAt(i));
+ if (pb == reinterpret_cast<brush_t*>(vp))
+ {
+ m_BrushHandles.RemoveAt(i);
+ Entity_LinkBrush (world_entity, pb);
+ Brush_Build(pb);
+ Brush_AddToList (pb, &active_brushes);
+ Select_Brush(pb);
+ }
+ }
+ g_bScreenUpdates = true;
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CPlugInManager::AddFaceToBrushHandle(void * vp, vec3_t v1, vec3_t v2, vec3_t v3)
+{
+ brush_t *bp = FindBrushHandle(vp);
+ if (bp != NULL)
+ {
+ face_t *f = Face_Alloc();
+ f->texdef = g_qeglobals.d_texturewin.texdef;
+ f->texdef.flags &= ~SURF_KEEP;
+ f->texdef.contents &= ~CONTENTS_KEEP;
+ f->next = bp->brush_faces;
+ bp->brush_faces = f;
+ VectorCopy (v1, f->planepts[0]);
+ VectorCopy (v2, f->planepts[1]);
+ VectorCopy (v3, f->planepts[2]);
+ }
+}
+
+brush_t* CPlugInManager::FindBrushHandle(void * vp)
+{
+ CPtrArray* pHandles[4];
+ pHandles[0] = &m_SelectedBrushHandles;
+ pHandles[1] = &m_ActiveBrushHandles;
+ pHandles[2] = &m_BrushHandles;
+ pHandles[3] = &m_EntityBrushHandles;
+
+ for (int j = 0; j < 4; j++)
+ {
+ for (int i = 0; i < pHandles[j]->GetSize(); i++)
+ {
+ brush_t *pb = reinterpret_cast<brush_t*>(pHandles[j]->GetAt(i));
+ if (pb == reinterpret_cast<brush_t*>(vp))
+ {
+ return pb;
+ }
+ }
+ }
+ return NULL;
+}
+
+patchMesh_t* CPlugInManager::FindPatchHandle(int index)
+{
+ switch (PatchesMode)
+ {
+ case EActivePatches:
+ case ESelectedPatches:
+ if ( index < m_PatchesHandles.GetSize() )
+ {
+ brush_t *pb = reinterpret_cast<brush_t *>(m_PatchesHandles.GetAt(index));
+ return pb->pPatch;
+ }
+#ifdef _DEBUG
+ Sys_Printf("WARNING: out of bounds in CPlugInManager::FindPatchHandle\n");
+#endif
+ break;
+ case EAllocatedPatches:
+ if ( index < m_PluginPatches.GetSize() )
+ {
+ patchMesh_t *pPatch = reinterpret_cast<patchMesh_t *>(m_PluginPatches.GetAt(index));
+ return pPatch;
+ }
+#ifdef _DEBUG
+ Sys_Printf("WARNING: out of bounds in CPlugInManager::FindPatchHandle\n");
+#endif
+ break;
+ }
+ return NULL;
+}
+
+LPVOID WINAPI QERApp_CreateBrushHandle()
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ return g_pParentWnd->GetPlugInMgr().CreateBrushHandle();
+}
+
+void WINAPI QERApp_DeleteBrushHandle(LPVOID vp)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ g_pParentWnd->GetPlugInMgr().DeleteBrushHandle(vp);
+}
+
+void WINAPI QERApp_CommitBrushHandleToMap(LPVOID vp)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ g_pParentWnd->GetPlugInMgr().CommitBrushHandleToMap(vp);
+}
+
+void WINAPI QERApp_AddFace(LPVOID vp, vec3_t v1, vec3_t v2, vec3_t v3)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ g_pParentWnd->GetPlugInMgr().AddFaceToBrushHandle(vp, v1, v2, v3);
+}
+
+void WINAPI QERApp_DeleteSelection()
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ Select_Delete();
+}
+
+void WINAPI QERApp_SysMsg(LPCSTR pMsg)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ CString str = pMsg;
+ Sys_Printf(str.GetBuffer(0));
+}
+
+// NOTE: called only in case of plugin error. We can try a plugin refresh instead of a straight crash ?
+void WINAPI QERApp_ErrorMsg(LPCSTR pMsg)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ CString str = pMsg;
+ Error(str.GetBuffer(0));
+}
+
+void WINAPI QERApp_InfoMsg(LPCSTR pMsg)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ ShowInfoDialog(pMsg);
+}
+
+void WINAPI QERApp_HideInfoMsg()
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ HideInfoDialog();
+}
+
+//=====
+//PGM
+void WINAPI QERApp_PositionView(vec3_t v1, vec3_t v2)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ g_pParentWnd->ActiveXY()->SetOrigin(v1);
+ // FIXME - implement this!
+ Sys_UpdateWindows(W_ALL);
+}
+//PGM
+//=====
+
+//FIXME: this AcquirePath stuff is pretty much a mess and needs cleaned up
+bool g_bPlugWait = false;
+bool g_bPlugOK = false;
+int g_nPlugCount = 0;
+
+void _PlugDone(bool b, int n)
+{
+ g_bPlugWait = false;
+ g_bPlugOK = b;
+ g_nPlugCount = n;
+}
+
+void WINAPI QERApp_GetPoints(int nMax, _QERPointData *pData, LPCSTR pMsg)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ ShowInfoDialog(pMsg);
+ g_bPlugWait = true;
+ g_bPlugOK = false;
+ g_nPlugCount = 0;
+// g_nPlugCount=nMax-1;
+ AcquirePath(nMax, &_PlugDone);
+ while (g_bPlugWait)
+ {
+ MSG msg;
+ if (::PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ))
+ {
+ TranslateMessage(&msg);
+ DispatchMessage(&msg);
+ }
+ }
+ HideInfoDialog();
+
+ pData->m_nCount = 0;
+ pData->m_pVectors = NULL;
+
+ if (g_bPlugOK && g_nPlugCount > 0)
+ {
+ pData->m_nCount = g_nPlugCount;
+ pData->m_pVectors = reinterpret_cast<vec3_t*>(qmalloc(g_nPlugCount * sizeof(vec3_t)));
+ vec3_t *pOut = pData->m_pVectors;
+ for (int i = 0; i < g_nPlugCount; i++)
+ {
+ memcpy(pOut, &g_PathPoints[i],sizeof(vec3_t));
+ pOut++;
+ }
+ }
+}
+
+void WINAPI QERApp_AddFaceData(LPVOID pv, _QERFaceData *pData)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+
+ brush_t* pBrush = g_pParentWnd->GetPlugInMgr().FindBrushHandle(pv);
+ if (pBrush != NULL)
+ {
+ face_t *f = Face_Alloc();
+ f->texdef = g_qeglobals.d_texturewin.texdef;
+ f->texdef.flags = pData->m_nFlags;
+ f->texdef.contents = pData->m_nContents;
+ f->texdef.value = pData->m_nValue;
+ f->texdef.rotate = pData->m_fRotate;
+ f->texdef.shift[0] = pData->m_fShift[0];
+ f->texdef.shift[1] = pData->m_fShift[1];
+ f->texdef.scale[0] = pData->m_fScale[0];
+ f->texdef.scale[1] = pData->m_fScale[1];
+ //strcpy(f->texdef.name, pData->m_TextureName);
+ f->texdef.SetName(pData->m_TextureName);
+ f->next = pBrush->brush_faces;
+ pBrush->brush_faces = f;
+ VectorCopy (pData->m_v1, f->planepts[0]);
+ VectorCopy (pData->m_v2, f->planepts[1]);
+ VectorCopy (pData->m_v3, f->planepts[2]);
+ Sys_MarkMapModified(); // PGM
+ }
+}
+
+int WINAPI QERApp_GetFaceCount(LPVOID pv)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ int n = 0;
+ brush_t *pBrush = g_pParentWnd->GetPlugInMgr().FindBrushHandle(pv);
+ if (pBrush != NULL)
+ {
+ for (face_t *f = pBrush->brush_faces ; f; f = f->next)
+ {
+ n++;
+ }
+ }
+ return n;
+}
+
+_QERFaceData* WINAPI QERApp_GetFaceData(LPVOID pv, int nFaceIndex)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ static _QERFaceData face;
+ int n = 0;
+ brush_t *pBrush = g_pParentWnd->GetPlugInMgr().FindBrushHandle(pv);
+
+ if (pBrush != NULL)
+ {
+ for (face_t *f = pBrush->brush_faces ; f; f = f->next)
+ {
+
+#ifdef _DEBUG
+ if (!pBrush->brush_faces)
+ {
+ Sys_Printf( "Warning : pBrush->brush_faces is NULL in QERApp_GetFaceData\n" );
+ return NULL;
+ }
+#endif
+
+ if (n == nFaceIndex)
+ {
+ face.m_nContents = f->texdef.contents;
+ face.m_nFlags = f->texdef.flags;
+ face.m_fRotate = f->texdef.rotate;
+ face.m_fScale[0] = f->texdef.scale[0];
+ face.m_fScale[1] = f->texdef.scale[1];
+ face.m_fShift[0] = f->texdef.shift[0];
+ face.m_fShift[1] = f->texdef.shift[1];
+ face.m_nValue = f->texdef.value;
+ strcpy(face.m_TextureName, f->texdef.name);
+ VectorCopy(f->planepts[0], face.m_v1);
+ VectorCopy(f->planepts[1], face.m_v2);
+ VectorCopy(f->planepts[2], face.m_v3);
+ return &face;
+ }
+ n++;
+ }
+ }
+ return NULL;
+}
+
+void WINAPI QERApp_SetFaceData(LPVOID pv, int nFaceIndex, _QERFaceData *pData)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ int n = 0;
+ brush_t *pBrush = g_pParentWnd->GetPlugInMgr().FindBrushHandle(pv);
+
+ if (pBrush != NULL)
+ {
+ for (face_t *f = pBrush->brush_faces ; f; f = f->next)
+ {
+ if (n == nFaceIndex)
+ {
+ f->texdef.flags = pData->m_nFlags;
+ f->texdef.contents = pData->m_nContents;
+ f->texdef.value = pData->m_nValue;
+ f->texdef.rotate = pData->m_fRotate;
+ f->texdef.shift[0] = pData->m_fShift[0];
+ f->texdef.shift[1] = pData->m_fShift[1];
+ f->texdef.scale[0] = pData->m_fScale[0];
+ f->texdef.scale[1] = pData->m_fScale[1];
+ //strcpy(f->texdef.name, pData->m_TextureName);
+ f->texdef.SetName(pData->m_TextureName);
+ VectorCopy(pData->m_v1, f->planepts[0]);
+ VectorCopy(pData->m_v2, f->planepts[1]);
+ VectorCopy(pData->m_v3, f->planepts[2]);
+ Sys_MarkMapModified(); // PGM
+ return; // PGM
+ }
+ n++;
+ }
+ }
+}
+
+void WINAPI QERApp_DeleteFace(LPVOID pv, int nFaceIndex)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ int n = 0;
+ brush_t *pBrush = g_pParentWnd->GetPlugInMgr().FindBrushHandle(pv);
+ if (pBrush != NULL)
+ {
+ face_t *pPrev = pBrush->brush_faces;
+ for (face_t *f = pBrush->brush_faces; f; f = f->next)
+ {
+ if (n == nFaceIndex)
+ {
+ pPrev->next = f->next;
+ Face_Free (f);
+ Sys_MarkMapModified(); // PGM
+ return;
+ }
+ n++;
+ pPrev = f;
+ }
+ }
+}
+
+//==========
+//PGM
+void WINAPI QERApp_BuildBrush (LPVOID pv)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ brush_t *pBrush = g_pParentWnd->GetPlugInMgr().FindBrushHandle(pv);
+ if (pBrush != NULL)
+ {
+ Brush_Build(pBrush);
+ Sys_UpdateWindows(W_ALL);
+ }
+}
+
+//Timo : another version with bConvert flag
+//++timo since 1.7 is not compatible with earlier plugin versions, remove this one and update QERApp_BuildBrush
+void WINAPI QERApp_BuildBrush2 (LPVOID pv, int bConvert)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ brush_t *pBrush = g_pParentWnd->GetPlugInMgr().FindBrushHandle(pv);
+ if (pBrush != NULL)
+ {
+ Brush_Build( pBrush, true, true, bConvert );
+ Sys_UpdateWindows(W_ALL);
+ }
+}
+
+void WINAPI QERApp_SelectBrush (LPVOID pv)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ brush_t *pBrush = g_pParentWnd->GetPlugInMgr().FindBrushHandle(pv);
+ if (pBrush != NULL)
+ {
+ Select_Brush(pBrush, false);
+ Sys_UpdateWindows(W_ALL);
+ }
+
+}
+
+void WINAPI QERApp_DeselectBrush (LPVOID pv)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ // FIXME - implement this!
+}
+
+void WINAPI QERApp_ResetPlugins()
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ g_pParentWnd->OnPluginsRefresh();
+}
+
+void WINAPI QERApp_DeselectAllBrushes ()
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ Select_Deselect();
+ Sys_UpdateWindows(W_ALL);
+}
+//PGM
+//==========
+
+void WINAPI QERApp_TextureBrush(LPVOID pv, LPCSTR pName)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ brush_t *pBrush = g_pParentWnd->GetPlugInMgr().FindBrushHandle(pv);
+ if (pBrush != NULL)
+ {
+ for (face_t *f = pBrush->brush_faces ; f; f = f->next)
+ {
+ //strcpy(f->texdef.name, pName);
+ f->texdef.SetName(pName);
+ }
+ Sys_MarkMapModified(); // PGM
+ }
+}
+
+int WINAPI QERApp_SelectedBrushCount()
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ int n = 0;
+ for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ n++;
+ }
+ return n;
+}
+
+int WINAPI QERApp_ActiveBrushCount()
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ int n = 0;
+ for (brush_t *pb = active_brushes.next ; pb != &active_brushes ; pb = pb->next)
+ {
+ n++;
+ }
+ return n;
+}
+
+int WINAPI QERApp_AllocateSelectedBrushHandles()
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ int n = 0;
+ for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ n++;
+ g_pParentWnd->GetPlugInMgr().GetSelectedHandles().Add(pb);
+ }
+ return n;
+}
+
+int WINAPI QERApp_AllocateActiveBrushHandles()
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ int n = 0;
+ for (brush_t *pb = active_brushes.next ; pb != &active_brushes ; pb = pb->next)
+ {
+ n++;
+ g_pParentWnd->GetPlugInMgr().GetActiveHandles().Add(pb);
+ }
+ return n;
+}
+
+void WINAPI QERApp_ReleaseSelectedBrushHandles()
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ g_pParentWnd->GetPlugInMgr().GetSelectedHandles().RemoveAll();
+ Sys_UpdateWindows(W_ALL);
+}
+
+void WINAPI QERApp_ReleaseActiveBrushHandles()
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ g_pParentWnd->GetPlugInMgr().GetActiveHandles().RemoveAll();
+ Sys_UpdateWindows(W_ALL);
+}
+
+LPVOID WINAPI QERApp_GetActiveBrushHandle(int nIndex)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ if (nIndex < g_pParentWnd->GetPlugInMgr().GetActiveHandles().GetSize())
+ {
+ return reinterpret_cast<LPVOID>(g_pParentWnd->GetPlugInMgr().GetActiveHandles().GetAt(nIndex));
+ }
+ return NULL;
+}
+
+LPVOID WINAPI QERApp_GetSelectedBrushHandle(int nIndex)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ if (nIndex < g_pParentWnd->GetPlugInMgr().GetSelectedHandles().GetSize())
+ {
+ return reinterpret_cast<LPVOID>(g_pParentWnd->GetPlugInMgr().GetSelectedHandles().GetAt(nIndex));
+ }
+ return NULL;
+}
+
+int WINAPI QERApp_TextureCount()
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ Texture_StartPos ();
+ int x, y;
+ int n = 0;
+ while (1)
+ {
+ qtexture_t *q = Texture_NextPos (&x, &y);
+ if (!q)
+ break;
+ n++;
+ }
+ return n;
+}
+
+LPCSTR WINAPI QERApp_GetTexture(int nIndex)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ static char name[QER_MAX_NAMELEN];
+ Texture_StartPos ();
+ int x, y;
+ int n = 0;
+ while (1)
+ {
+ qtexture_t *q = Texture_NextPos (&x, &y);
+ if (!q)
+ break;
+ if (n == nIndex)
+ {
+ strcpy(name, q->name);
+ return name;
+ }
+ n++;
+ }
+ return NULL;
+}
+
+LPCSTR WINAPI QERApp_GetCurrentTexture()
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ return g_qeglobals.d_texturewin.texdef.name;
+}
+
+void WINAPI QERApp_SetCurrentTexture(LPCSTR strName)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ //++timo hu ?? tex is not initialized ?? can be any value ..
+ texdef_t tex;
+ //++timo added a brushprimit_texdef ..
+ // smthg to be done here
+ brushprimit_texdef_t brushprimit_tex;
+ //strcpy(tex.name, strName);
+ tex.SetName(strName);
+ Texture_SetTexture(&tex,&brushprimit_tex);
+}
+
+int WINAPI QERApp_GetEClassCount()
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ int n = 0;
+ for (eclass_t *e = eclass ; e ; e = e->next)
+ {
+ n++;
+ }
+ return n;
+}
+
+LPCSTR WINAPI QERApp_GetEClass(int nIndex)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ int n = 0;
+ for (eclass_t *e = eclass ; e ; e = e->next)
+ {
+ if (n == nIndex)
+ {
+ return e->name;
+ }
+ }
+ return NULL;
+}
+
+void WINAPI QERApp_LoadTextureRGBA(LPVOID vp)
+{
+ Texture_LoadFromPlugIn(vp);
+}
+
+// v1.70 code
+// world_entity holds the worldspawn and is indexed as 0
+// other entities are in the entities doubly linked list
+// QERApp_GetEntityCount counts the entities like in any C array: [0..length-1]
+int WINAPI QERApp_GetEntityCount()
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ int n = 1;
+ for (entity_t *pe = entities.next ; pe != &entities ; pe = pe->next)
+ {
+ n++;
+ }
+ return n;
+}
+
+// We don't store entities in CPtrArray, we need to walk the list
+LPVOID WINAPI QERApp_GetEntityHandle(int nIndex)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ if (nIndex==0)
+ // looks for the worldspawn
+ return static_cast<LPVOID>(world_entity);
+ entity_t *pe = &entities;
+ int n = 0;
+ while ( n < nIndex )
+ {
+ pe = pe->next;
+ n++;
+ }
+ return static_cast<LPVOID>(pe);
+}
+
+epair_t** WINAPI QERApp_GetEntityKeyValList(LPVOID vp)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ entity_t *pe = static_cast<entity_t *>(vp);
+ return &pe->epairs;
+}
+
+epair_t* WINAPI QERApp_AllocateEpair( char *key, char *val )
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ epair_t *e = (epair_t*)qmalloc (sizeof(*e));
+ e->key = (char*)qmalloc(strlen(key)+1);
+ strcpy (e->key, key);
+ e->value = (char*)qmalloc(strlen(val)+1);
+ strcpy (e->value, val);
+ return e;
+}
+
+void WINAPI QERApp_SetEntityKeyValList(LPVOID vp, epair_t* ep)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ entity_t *pe = static_cast<entity_t *>(vp);
+ if (pe->epairs)
+ Sys_Printf( "Warning : pe->epairs != NULL in QERApp_SetEntityKeyValList, will not set\n" );
+ else
+ pe->epairs = ep;
+}
+
+int WINAPI QERApp_AllocateEntityBrushHandles(LPVOID vp)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ entity_t *pe = static_cast<entity_t *>(vp);
+ int n = 0;
+ if (!pe->brushes.onext)
+ return 0;
+ g_pParentWnd->GetPlugInMgr().GetEntityBrushHandles().RemoveAll();
+ for (brush_t *pb = pe->brushes.onext ; pb != &pe->brushes ; pb=pb->onext)
+ {
+ n++;
+ g_pParentWnd->GetPlugInMgr().GetEntityBrushHandles().Add(pb);
+ }
+ return n;
+}
+
+void WINAPI QERApp_ReleaseEntityBrushHandles()
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ g_pParentWnd->GetPlugInMgr().GetEntityBrushHandles().RemoveAll();
+}
+
+LPVOID WINAPI QERApp_GetEntityBrushHandle(int nIndex)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ if (nIndex < g_pParentWnd->GetPlugInMgr().GetEntityBrushHandles().GetSize())
+ return g_pParentWnd->GetPlugInMgr().GetEntityBrushHandles().GetAt(nIndex);
+ return NULL;
+}
+
+LPVOID WINAPI QERApp_CreateEntityHandle()
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ entity_t *pe = reinterpret_cast<entity_t*>(qmalloc(sizeof(entity_t)));
+ pe->brushes.onext = pe->brushes.oprev = &pe->brushes;
+ g_pParentWnd->GetPlugInMgr().GetEntityHandles().Add(static_cast<LPVOID>(pe));
+ return static_cast<LPVOID>(pe);
+}
+
+// the vpBrush needs to be in m_BrushHandles
+//++timo we don't have allocation nor storage for vpEntity, no checks for this one
+void WINAPI QERApp_CommitBrushHandleToEntity(LPVOID vpBrush, LPVOID vpEntity)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ g_pParentWnd->GetPlugInMgr().CommitBrushHandleToEntity(vpBrush, vpEntity);
+ return;
+}
+
+char* WINAPI QERApp_ReadProjectKey(char* key)
+{
+ return ValueForKey(g_qeglobals.d_project_entity, key);
+}
+
+int WINAPI QERApp_ScanFileForEClass(char *filename )
+{
+ // set single class parsing
+ parsing_single = true;
+ Eclass_ScanFile(filename);
+ if (eclass_found)
+ {
+ eclass_e->nShowFlags |= ECLASS_PLUGINENTITY;
+ return 1;
+ }
+ return 0;
+}
+
+// the vpBrush needs to be in m_BrushHandles
+//++timo add a debug check to see if we found the brush handle
+// NOTE : seems there's no way to check vpEntity is valid .. this is dangerous
+// links the brush to its entity, everything else is done when commiting the entity to the map
+void CPlugInManager::CommitBrushHandleToEntity(LPVOID vpBrush, LPVOID vpEntity)
+{
+ brush_t* pb;
+ entity_t* pe;
+ for (int i=0 ; i < m_BrushHandles.GetSize() ; i++)
+ {
+ if (vpBrush == m_BrushHandles.GetAt(i))
+ {
+ m_BrushHandles.RemoveAt(i);
+ pb = reinterpret_cast<brush_t*>(vpBrush);
+ pe = reinterpret_cast<entity_t *>(vpEntity);
+ Entity_LinkBrush (pe, pb);
+ }
+ }
+ Sys_UpdateWindows(W_ALL);
+}
+
+// the vpEntity must be in m_EntityHandles
+void WINAPI QERApp_CommitEntityHandleToMap(LPVOID vpEntity)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ g_pParentWnd->GetPlugInMgr().CommitEntityHandleToMap(vpEntity);
+ return;
+}
+
+int WINAPI QERApp_LoadFile( const char *pLocation, void ** buffer )
+{
+ char cPath[1024];
+ sprintf( cPath, "%s/%s", ValueForKey(g_qeglobals.d_project_entity, "basepath"), pLocation);
+ int nSize = LoadFile( cPath, buffer);
+ if (nSize == -1)
+ {
+ nSize = PakLoadAnyFile(cPath, buffer);
+ }
+ return nSize;
+}
+
+char * WINAPI QERApp_ExpandReletivePath (char *p)
+{
+ return ExpandReletivePath(p);
+}
+
+// NOTE: this is a simplified version
+int WINAPI QERApp_HasShader( const char *pName )
+{
+ CShaderInfo *pInfo = hasShader( pName );
+ if (pInfo)
+ return 1;
+ return 0;
+}
+
+qtexture_t* WINAPI QERApp_Texture_ForName (const char *name)
+{
+ // if the texture is not loaded yet, this call will get it loaded
+ // but: when we assign a GL bind number, we need to be in the g_qeglobals.d_hdcBase , g_qeglobals.d_hglrcBase GL context
+ // the plugin may set the GL context to whatever he likes, but then load would fail
+ // NOTE: is context switching time-consuming? then maybe the plugin could handle the context switch and only add a
+ // sanity check in debug mode here
+ // read current context
+ HDC pluginHDC = qwglGetCurrentDC();
+ HGLRC pluginHGLRC = qwglGetCurrentContext();
+ qwglMakeCurrent( g_qeglobals.d_hdcBase, g_qeglobals.d_hglrcBase );
+ qtexture_t* qtex = Texture_ForName( name );
+ return qtex;
+ qwglMakeCurrent( pluginHDC, pluginHGLRC );
+}
+
+void WINAPI QERApp_RadiantFree( void * buf )
+{
+ free( buf );
+}
+
+char* WINAPI QERApp_Token()
+{
+ return token;
+}
+
+char* WINAPI QERApp_GetMapName()
+{
+ return currentmap;
+}
+
+void CPlugInManager::CommitEntityHandleToMap(LPVOID vpEntity)
+{
+ entity_t *pe;
+ eclass_t *e;
+ brush_t *b;
+ vec3_t mins,maxs;
+ bool has_brushes;
+ for (int i=0 ; i < m_EntityHandles.GetSize() ; i++ )
+ {
+ if (vpEntity == m_EntityHandles.GetAt(i))
+ {
+ m_EntityHandles.RemoveAt(i);
+ pe = reinterpret_cast<entity_t*>(vpEntity);
+ // fill additional fields
+ // straight copy from Entity_Parse
+ // entity_t::origin
+ GetVectorForKey (pe, "origin", pe->origin);
+ // entity_t::eclass
+ if (pe->brushes.onext == &pe->brushes)
+ has_brushes = false;
+ else
+ has_brushes = true;
+ e = Eclass_ForName (ValueForKey (pe, "classname"), has_brushes);
+ pe->eclass = e;
+ // fixedsize
+ if (e->fixedsize)
+ {
+ if (pe->brushes.onext != &pe->brushes)
+ {
+ Sys_Printf("Warning : Fixed size entity with brushes in CPlugInManager::CommitEntityHandleToMap\n");
+ }
+ // create a custom brush
+ VectorAdd(e->mins, pe->origin, mins);
+ VectorAdd(e->maxs, pe->origin, maxs);
+ float a = 0;
+ if (e->nShowFlags & ECLASS_MISCMODEL)
+ {
+ char* p = ValueForKey(pe, "model");
+ if (p != NULL && strlen(p) > 0)
+ {
+ vec3_t vMin, vMax;
+ a = FloatForKey (pe, "angle");
+ if (GetCachedModel(pe, p, vMin, vMax))
+ {
+ // create a custom brush
+ VectorAdd (pe->md3Class->mins, pe->origin, mins);
+ VectorAdd (pe->md3Class->maxs, pe->origin, maxs);
+ }
+ }
+ }
+
+ b = Brush_Create (mins, maxs, &e->texdef);
+
+ if (a)
+ {
+ vec3_t vAngle;
+ vAngle[0] = vAngle[1] = 0;
+ vAngle[2] = a;
+ Brush_Rotate(b, vAngle, pe->origin, false);
+ }
+
+ b->owner = pe;
+
+ b->onext = pe->brushes.onext;
+ b->oprev = &pe->brushes;
+ pe->brushes.onext->oprev = b;
+ pe->brushes.onext = b;
+ }
+ else
+ { // brush entity
+ if (pe->brushes.next == &pe->brushes)
+ Sys_Printf ("Warning: Brush entity with no brushes in CPlugInManager::CommitEntityHandleToMap\n");
+ }
+
+ // add brushes to the active brushes list
+ // and build them along the way
+ for (b=pe->brushes.onext ; b != &pe->brushes ; b=b->onext)
+ {
+ // convert between old brushes and brush primitive
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ // we only filled the shift scale rot fields, needs conversion
+ Brush_Build( b, true, true, true );
+ }
+ else
+ {
+ // we are using old brushes
+ Brush_Build( b );
+ }
+ b->next = active_brushes.next;
+ active_brushes.next->prev = b;
+ b->prev = &active_brushes;
+ active_brushes.next = b;
+ }
+
+ // handle worldspawn entities
+ // if worldspawn has no brushes, use the new one
+ if (!strcmp(ValueForKey (pe, "classname"), "worldspawn"))
+ {
+ if ( world_entity && ( world_entity->brushes.onext != &world_entity->brushes ) )
+ {
+ // worldspawn already has brushes
+ Sys_Printf ("Commiting worldspawn as func_group\n");
+ SetKeyValue(pe, "classname", "func_group");
+ // add the entity to the end of the entity list
+ pe->next = &entities;
+ pe->prev = entities.prev;
+ entities.prev->next = pe;
+ entities.prev = pe;
+ g_qeglobals.d_num_entities++;
+ }
+ else
+ {
+ // there's a worldspawn with no brushes, we assume the map is empty
+ if ( world_entity )
+ {
+ Entity_Free( world_entity );
+ world_entity = pe;
+ }
+ else
+ Sys_Printf("Warning : unexpected world_entity == NULL in CommitEntityHandleToMap\n");
+ }
+ }
+ else
+ {
+ // add the entity to the end of the entity list
+ pe->next = &entities;
+ pe->prev = entities.prev;
+ entities.prev->next = pe;
+ entities.prev = pe;
+ g_qeglobals.d_num_entities++;
+ }
+ }
+ }
+}
+
+void WINAPI QERApp_SetScreenUpdate(int bScreenUpdates)
+{
+ g_bScreenUpdates = bScreenUpdates;
+}
+
+texturewin_t* WINAPI QERApp_QeglobalsTexturewin()
+{
+ return &g_qeglobals.d_texturewin;
+}
+
+_QERTextureInfo* CPlugInManager::GetTextureInfo()
+{
+ if (m_pTexturePlug != NULL)
+ {
+ return m_pTexturePlug->getTextureInfo();
+ }
+ else
+ {
+ return NULL;
+ }
+}
+
+LPVOID CPlugInManager::GetSurfaceFlags()
+{
+ if (m_pSurfaceListPlug != NULL)
+ {
+ return m_pSurfaceListPlug->getSurfaceFlags();
+ }
+ else
+ {
+ return NULL;
+ }
+}
+
+void CPlugInManager::LoadTexture(const char *pFilename)
+{
+ if (m_pTexturePlug != NULL)
+ {
+ m_pTexturePlug->loadTexture(pFilename);
+ }
+}
+
+patchMesh_t* WINAPI QERApp_GetSelectedPatch( )
+{
+ for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ return pb->pPatch;
+ }
+ }
+#ifdef _DEBUG
+ Sys_Printf("WARNING: QERApp_GetSelectedPatchTexdef called with no patch selected\n");
+#endif
+ return NULL;
+}
+
+char* WINAPI QERApp_GetGamePath()
+{
+ return g_PrefsDlg.m_strQuake2.GetBuffer(0);
+}
+
+char* WINAPI QERApp_GetQERPath()
+{
+ return g_strAppPath.GetBuffer(0);
+}
+
+// patches in/out -----------------------------------
+int WINAPI QERApp_AllocateActivePatchHandles()
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ return g_pParentWnd->GetPlugInMgr().AllocateActivePatchHandles();
+}
+
+int CPlugInManager::AllocateActivePatchHandles()
+{
+ int n = 0;
+ for (brush_t *pb = active_brushes.next ; pb != &active_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ n++;
+ m_PatchesHandles.Add(pb);
+ }
+ }
+ return n;
+}
+
+int WINAPI QERApp_AllocateSelectedPatchHandles()
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ return g_pParentWnd->GetPlugInMgr().AllocateSelectedPatchHandles();
+}
+
+int CPlugInManager::AllocateSelectedPatchHandles()
+{
+ int n = 0;
+ for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ n++;
+ m_PatchesHandles.Add(pb);
+ }
+ }
+ return n;
+}
+
+void WINAPI QERApp_ReleasePatchHandles()
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ g_pParentWnd->GetPlugInMgr().ReleasePatchesHandles();
+}
+
+patchMesh_t* WINAPI QERApp_GetPatchData(int index)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ static patchMesh_t patch;
+ patchMesh_t *pPatch = g_pParentWnd->GetPlugInMgr().FindPatchHandle(index);
+ if (pPatch)
+ {
+ memcpy( &patch, pPatch, sizeof(patchMesh_t) );
+ return &patch;
+ }
+ return NULL;
+}
+
+void WINAPI QERApp_DeletePatch(int index)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ patchMesh_t *pPatch = g_pParentWnd->GetPlugInMgr().FindPatchHandle(index);
+ if (pPatch)
+ {
+ brush_t *pb = pPatch->pSymbiot;
+ Patch_Delete( pPatch );
+ if (pb)
+ Brush_Free( pb );
+ }
+#ifdef _DEBUG
+ Sys_Printf("Warning: QERApp_DeletePatch: FindPatchHandle failed\n");
+#endif
+}
+
+int WINAPI QERApp_CreatePatchHandle()
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ return g_pParentWnd->GetPlugInMgr().CreatePatchHandle();
+}
+
+int CPlugInManager::CreatePatchHandle()
+{
+ // NOTE: we can't call the AddBrushForPatch until we have filled the patchMesh_t structure
+ patchMesh_t *pPatch = MakeNewPatch();
+ m_PluginPatches.Add( pPatch );
+ // change mode
+ PatchesMode = EAllocatedPatches;
+ return m_PluginPatches.GetSize()-1;
+}
+
+void WINAPI QERApp_CommitPatchHandleToMap(int index, patchMesh_t *pMesh, char *texName)
+{
+ AFX_MANAGE_STATE(AfxGetStaticModuleState());
+ g_pParentWnd->GetPlugInMgr().CommitPatchHandleToMap(index, pMesh, texName);
+}
+
+void CPlugInManager::CommitPatchHandleToMap(int index, patchMesh_t *pMesh, char *texName)
+{
+ if (PatchesMode==EAllocatedPatches)
+ {
+ patchMesh_t *pPatch = reinterpret_cast<patchMesh_t *>( m_PluginPatches.GetAt(index) );
+ memcpy( pPatch, pMesh, sizeof( patchMesh_t ) );
+ // patch texturing, if none given use current texture
+ if (texName)
+ pPatch->d_texture = Texture_ForName(texName);
+ if ( !pPatch->d_texture )
+ {
+ pPatch->d_texture = Texture_ForName(g_qeglobals.d_texturewin.texdef.name);
+ // checking .. just in case
+ if (!pPatch->d_texture)
+ {
+#ifdef _DEBUG
+ Sys_Printf("WARNING: failed to set patch to current texture in CPlugInManager::CommitPatchHandleToMap\n");
+#endif
+ pPatch->d_texture = notexture;
+ }
+ }
+ g_bScreenUpdates = false;
+ // the bLinkToWorld flag in AddBrushForPatch takes care of Brush_AddToList Entity_linkBrush and Brush_Build
+ brush_t *pb = AddBrushForPatch( pPatch, true );
+ Select_Brush( pb );
+ g_bScreenUpdates = true;
+ Sys_UpdateWindows(W_ALL);
+ }
+ else
+ {
+ brush_t *pBrush = reinterpret_cast<brush_t *>( m_PatchesHandles.GetAt(index) );
+ patchMesh_t *pPatch = pBrush->pPatch;
+ pPatch->width = pMesh->width;
+ pPatch->height = pMesh->height;
+ pPatch->contents = pMesh->contents;
+ pPatch->flags = pMesh->flags;
+ pPatch->value = pMesh->value;
+ pPatch->type = pMesh->type;
+ memcpy( pPatch->ctrl, pMesh->ctrl, sizeof(drawVert_t)*MAX_PATCH_HEIGHT*MAX_PATCH_WIDTH );
+ pPatch->bDirty = true;
+ }
+}
+
+// this gets called when the plugin needs specific services, for example the OpenGL drawing interface
+//++timo plugins should be able to dynamically register their own interfaces in there
+int WINAPI QERApp_RequestInterface( REFGUID refGUID, LPVOID pInterface )
+{
+ if (IsEqualGUID( refGUID, QERQglTable_GUID ))
+ {
+ _QERQglTable *pQglTable = static_cast<_QERQglTable *>(pInterface);
+ if ( pQglTable->m_nSize != sizeof(_QERQglTable) )
+ {
+ Sys_Printf("wrong m_nSize in plugin-requested _QERQglTable interface\n");
+ return 0;
+ }
+ pQglTable->m_pfn_qglAlphaFunc = qglAlphaFunc;
+ pQglTable->m_pfn_qglBegin = qglBegin;
+ pQglTable->m_pfn_qglBindTexture = qglBindTexture;
+ pQglTable->m_pfn_qglBlendFunc = qglBlendFunc;
+ pQglTable->m_pfn_qglCallList = qglCallList;
+ pQglTable->m_pfn_qglCallLists = qglCallLists;
+ pQglTable->m_pfn_qglClear = qglClear;
+ pQglTable->m_pfn_qglClearColor = qglClearColor;
+ pQglTable->m_pfn_qglClearDepth = qglClearDepth;
+ pQglTable->m_pfn_qglColor3f = qglColor3f;
+ pQglTable->m_pfn_qglColor4f = qglColor4f;
+ pQglTable->m_pfn_qglCullFace = qglCullFace;
+ pQglTable->m_pfn_qglDisable = qglDisable;
+ pQglTable->m_pfn_qglDeleteLists = qglDeleteLists;
+ pQglTable->m_pfn_qglEnable = qglEnable;
+ pQglTable->m_pfn_qglEnd = qglEnd;
+ pQglTable->m_pfn_qglEndList = qglEndList;
+ pQglTable->m_pfn_qglGenLists = qglGenLists;
+ pQglTable->m_pfn_qglListBase = qglListBase;
+ pQglTable->m_pfn_qglLoadIdentity = qglLoadIdentity;
+ pQglTable->m_pfn_qglMatrixMode = qglMatrixMode;
+ pQglTable->m_pfn_qglNewList = qglNewList;
+ pQglTable->m_pfn_qglNormal3f = qglNormal3f;
+ pQglTable->m_pfn_qglOrtho = qglOrtho;
+ pQglTable->m_pfn_qglPointSize = qglPointSize;
+ pQglTable->m_pfn_qglPolygonMode = qglPolygonMode;
+ pQglTable->m_pfn_qglPopMatrix = qglPopMatrix;
+ pQglTable->m_pfn_qglPushMatrix = qglPushMatrix;
+ pQglTable->m_pfn_qglRotated = qglRotated;
+ pQglTable->m_pfn_qglRotatef = qglRotatef;
+ pQglTable->m_pfn_qglScalef = qglScalef;
+ pQglTable->m_pfn_qglTexCoord2f = qglTexCoord2f;
+ pQglTable->m_pfn_qglTexEnvf = qglTexEnvf;
+ pQglTable->m_pfn_qglTexGenf = qglTexGenf;
+ pQglTable->m_pfn_qglTexParameterf = qglTexParameterf;
+ pQglTable->m_pfn_qglTranslated = qglTranslated;
+ pQglTable->m_pfn_qglTranslatef = qglTranslatef;
+ pQglTable->m_pfn_qglVertex2f = qglVertex2f;
+ pQglTable->m_pfn_qglVertex3f = qglVertex3f;
+ pQglTable->m_pfn_qglViewport = qglViewport;
+ pQglTable->m_pfn_QE_CheckOpenGLForErrors = &QE_CheckOpenGLForErrors;
+ pQglTable->m_pfn_QEW_SetupPixelFormat = &QEW_SetupPixelFormat;
+ pQglTable->m_pfn_qwglCreateContext = qwglCreateContext;
+ pQglTable->m_pfn_qwglDeleteContext = qwglDeleteContext;
+ pQglTable->m_pfn_qwglMakeCurrent = qwglMakeCurrent;
+ pQglTable->m_pfn_qwglShareLists = qwglShareLists;
+ pQglTable->m_pfn_qwglSwapBuffers = qwglSwapBuffers;
+ pQglTable->m_pfn_qwglUseFontBitmaps = qwglUseFontBitmaps;
+ pQglTable->m_pfnGetQeglobalsHGLRC = &QERApp_GetQeglobalsHGLRC;
+ pQglTable->m_pfn_qgluPerspective = qgluPerspective;
+ pQglTable->m_pfn_qgluLookAt = qgluLookAt;
+ pQglTable->m_pfnHookXYGLWindow = QERApp_HookXYGLWindow;
+ pQglTable->m_pfnUnHookGLWindow = QERApp_UnHookGLWindow;
+
+ return 1;
+ }
+ else if (IsEqualGUID( refGUID, QERSelectedFaceTable_GUID ))
+ {
+ _QERSelectedFaceTable *pSelectedFaceTable = static_cast<_QERSelectedFaceTable *>(pInterface);
+ if ( pSelectedFaceTable->m_nSize != sizeof(_QERSelectedFaceTable) )
+ {
+ Sys_Printf("wrong m_nSize in plugin-requested _QERSelectedFaceTable interface\n");
+ return 0;
+ }
+ pSelectedFaceTable->m_pfnGetTextureNumber = &QERApp_ISelectedFace_GetTextureNumber;
+ pSelectedFaceTable->m_pfnGetFaceInfo = &QERApp_GetFaceInfo;
+ pSelectedFaceTable->m_pfnSetFaceInfo = &QERApp_SetFaceInfo;
+ pSelectedFaceTable->m_pfnGetTextureSize = &QERApp_GetTextureSize;
+ pSelectedFaceTable->m_pfnTextureForName = &QERApp_Texture_ForName;
+ pSelectedFaceTable->m_pfnSelect_SetTexture = &Select_SetTexture;
+ return 1;
+ }
+ else if (IsEqualGUID( refGUID, QERPluginEntitiesTable_GUID ))
+ {
+ _QERPluginEntitiesTable *pPluginEntitiesTable = static_cast<_QERPluginEntitiesTable *>(pInterface);
+ if ( pPluginEntitiesTable->m_nSize != sizeof(_QERPluginEntitiesTable) )
+ {
+ Sys_Printf("wrong m_nSize in plugin-requested _QERPluginEntitiesTable interface\n");
+ return 0;
+ }
+ pPluginEntitiesTable->m_pfnEClassScanDir = &QERApp_EClassScanDir;
+ return 1;
+ }
+ else if (IsEqualGUID( refGUID, QERScripLibTable_GUID ))
+ {
+ _QERScripLibTable *pScripLibTable = static_cast<_QERScripLibTable *>(pInterface);
+ if ( pScripLibTable->m_nSize != sizeof( _QERScripLibTable ) )
+ {
+ Sys_Printf("wrong m_nSize in plugin-requested _QERScripLibTable\n");
+ return 0;
+ }
+ pScripLibTable->m_pfnGetToken = &GetToken;
+ pScripLibTable->m_pfnToken = &QERApp_Token;
+ pScripLibTable->m_pfnUnGetToken = &UngetToken;
+ return 1;
+ }
+ else if (IsEqualGUID( refGUID, QERAppSurfaceTable_GUID ))
+ {
+ _QERAppSurfaceTable *pSurfaceTable = static_cast<_QERAppSurfaceTable *>(pInterface);
+ if ( pSurfaceTable->m_nSize != sizeof( _QERAppSurfaceTable ) )
+ {
+ Sys_Printf("wrong m_nSize in plugin-requested _QERAppSurfaceTable\n");
+ return 0;
+ }
+ pSurfaceTable->m_pfnAnyPatchesSelected = &AnyPatchesSelected;
+ pSurfaceTable->m_pfnOnlyPatchesSelected = &OnlyPatchesSelected;
+ pSurfaceTable->m_pfnQeglobalsTexturewin = &QERApp_QeglobalsTexturewin;
+ pSurfaceTable->m_pfnGetSelectedPatch = &QERApp_GetSelectedPatch;
+ pSurfaceTable->m_pfnPatchRebuild = &Patch_Rebuild;
+ pSurfaceTable->m_pfnGetTwoSelectedPatch = &QERApp_GetTwoSelectedPatch;
+ return 1;
+ }
+ else if (IsEqualGUID( refGUID, QERAppBSPFrontendTable_GUID ))
+ {
+ _QERAppBSPFrontendTable *pBSPFrontendTable = static_cast<_QERAppBSPFrontendTable *>(pInterface);
+ if ( pBSPFrontendTable->m_nSize != sizeof( _QERAppBSPFrontendTable ) )
+ {
+ Sys_Printf("wrong m_nSize in plugin-requested _QERAppBSPFrontendTable\n");
+ return 0;
+ }
+ pBSPFrontendTable->m_pfnGetMapName = &QERApp_GetMapName;
+ pBSPFrontendTable->m_pfnLoadPointFile = &Pointfile_Check;
+ return 1;
+ }
+ else if (IsEqualGUID( refGUID, QERMessaging_GUID ))
+ {
+ _QERMessagingTable *pMessagingTable = static_cast<_QERMessagingTable *>(pInterface);
+ if ( pMessagingTable->m_nSize != sizeof( _QERMessagingTable ) )
+ {
+ Sys_Printf("wrong m_nSize in plugin-requested _QERMessagingTable\n");
+ return 0;
+ }
+ pMessagingTable->m_pfnHookWindow = QERApp_HookWindow;
+ pMessagingTable->m_pfnUnHookWindow = QERApp_UnHookWindow;
+ pMessagingTable->m_pfnGetXYWndWrapper = QERApp_GetXYWndWrapper;
+ pMessagingTable->m_pfnHookListener = QERApp_HookListener;
+ pMessagingTable->m_pfnUnHookListener = QERApp_UnHookListener;
+ return 1;
+ }
+ else if (IsEqualGUID( refGUID, QERShadersTable_GUID ))
+ {
+ _QERShadersTable *pShadersTable = static_cast<_QERShadersTable *>(pInterface);
+ if ( pShadersTable->m_nSize != sizeof( _QERShadersTable ) )
+ {
+ Sys_Printf("wring m_nSize in plugin-requested _QERShadersTable\n");
+ return 0;
+ }
+ pShadersTable->m_pfnTryTextureForName = QERApp_TryTextureForName;
+ return 1;
+ }
+ return 0;
+}
+
+int CPlugInManager::FillFuncTable(CPlugIn *pPlug)
+{
+ _QERFuncTable_1 *pTable = reinterpret_cast<_QERFuncTable_1*>(pPlug->getFuncTable());
+ if (pTable != NULL)
+ {
+ if (pTable->m_fVersion != QER_PLUG_VERSION)
+ {
+ Sys_Printf("Radiant plugin manager was built with version %.2f, Plugin %s is version %.2f\n", QER_PLUG_VERSION, pPlug->getVersionStr() , pTable->m_fVersion);
+ }
+ if (pTable->m_fVersion >= QER_PLUG_VERSION_1)
+ {
+ pTable->m_pfnCreateBrush = &QERApp_CreateBrush;
+ pTable->m_pfnCreateBrushHandle = &QERApp_CreateBrushHandle;
+ pTable->m_pfnDeleteBrushHandle = &QERApp_DeleteBrushHandle;
+ pTable->m_pfnCommitBrushHandle = &QERApp_CommitBrushHandleToMap;
+ pTable->m_pfnAddFace = &QERApp_AddFace;
+ pTable->m_pfnAddFaceData = &QERApp_AddFaceData;
+ pTable->m_pfnGetFaceData = &QERApp_GetFaceData;
+ pTable->m_pfnGetFaceCount = &QERApp_GetFaceCount;
+ pTable->m_pfnSetFaceData = &QERApp_SetFaceData;
+ pTable->m_pfnDeleteFace = &QERApp_DeleteFace;
+ pTable->m_pfnTextureBrush = &QERApp_TextureBrush;
+ pTable->m_pfnBuildBrush = &QERApp_BuildBrush; // PGM
+ pTable->m_pfnSelectBrush = &QERApp_SelectBrush; // PGM
+ pTable->m_pfnDeselectBrush = &QERApp_DeselectBrush; // PGM
+ pTable->m_pfnDeselectAllBrushes = &QERApp_DeselectAllBrushes; // PGM
+ pTable->m_pfnDeleteSelection = &QERApp_DeleteSelection;
+ pTable->m_pfnGetPoints = &QERApp_GetPoints;
+ pTable->m_pfnSysMsg = &QERApp_SysMsg;
+ pTable->m_pfnInfoMsg = &QERApp_InfoMsg;
+ pTable->m_pfnHideInfoMsg = &QERApp_HideInfoMsg;
+ pTable->m_pfnPositionView = &QERApp_PositionView; // PGM
+ pTable->m_pfnSelectedBrushCount = &QERApp_SelectedBrushCount;
+ pTable->m_pfnAllocateSelectedBrushHandles = &QERApp_AllocateSelectedBrushHandles;
+ pTable->m_pfnReleaseSelectedBrushHandles = &QERApp_ReleaseSelectedBrushHandles;
+ pTable->m_pfnGetSelectedBrushHandle = &QERApp_GetSelectedBrushHandle;
+ pTable->m_pfnActiveBrushCount = &QERApp_ActiveBrushCount;
+ pTable->m_pfnAllocateActiveBrushHandles = &QERApp_AllocateActiveBrushHandles;
+ pTable->m_pfnReleaseActiveBrushHandles = &QERApp_ReleaseActiveBrushHandles;
+ pTable->m_pfnGetActiveBrushHandle = &QERApp_GetActiveBrushHandle;
+ pTable->m_pfnTextureCount = &QERApp_TextureCount;
+ pTable->m_pfnGetTexture = &QERApp_GetTexture;
+ pTable->m_pfnGetCurrentTexture = &QERApp_GetCurrentTexture;
+ pTable->m_pfnSetCurrentTexture = &QERApp_SetCurrentTexture;
+ pTable->m_pfnGetEClassCount = &QERApp_GetEClassCount;
+ pTable->m_pfnGetEClass = &QERApp_GetEClass;
+ pTable->m_pfnResetPlugins = &QERApp_ResetPlugins;
+ }
+ // end of v1.00
+ if (pTable->m_fVersion >= 1.5f)
+ {
+ // v1.50 starts
+ pTable->m_pfnLoadTextureRGBA = &QERApp_LoadTextureRGBA;
+ // end of v1.50
+ }
+ if (pTable->m_fVersion >= 1.7f)
+ {
+ pTable->m_pfnGetEntityCount = &QERApp_GetEntityCount;
+ pTable->m_pfnGetEntityHandle = &QERApp_GetEntityHandle;
+ pTable->m_pfnGetEntityKeyValList = &QERApp_GetEntityKeyValList;
+ pTable->m_pfnAllocateEpair = &QERApp_AllocateEpair;
+ pTable->m_pfnSetEntityKeyValList = &QERApp_SetEntityKeyValList;
+ pTable->m_pfnAllocateEntityBrushHandles = &QERApp_AllocateEntityBrushHandles;
+ pTable->m_pfnReleaseEntityBrushHandles = &QERApp_ReleaseEntityBrushHandles;
+ pTable->m_pfnGetEntityBrushHandle = &QERApp_GetEntityBrushHandle;
+ pTable->m_pfnCreateEntityHandle = &QERApp_CreateEntityHandle;
+ pTable->m_pfnCommitBrushHandleToEntity = &QERApp_CommitBrushHandleToEntity;
+ pTable->m_pfnCommitEntityHandleToMap = &QERApp_CommitEntityHandleToMap;
+ pTable->m_pfnSetScreenUpdate = &QERApp_SetScreenUpdate;
+ pTable->m_pfnSysUpdateWindows = &Sys_UpdateWindows;
+ pTable->m_pfnBuildBrush2 = &QERApp_BuildBrush2;
+ pTable->m_pfnReadProjectKey = &QERApp_ReadProjectKey;
+ pTable->m_pfnScanFileForEClass = &QERApp_ScanFileForEClass;
+ pTable->m_pfnRequestInterface = &QERApp_RequestInterface;
+ pTable->m_pfnErrorMsg = &QERApp_ErrorMsg;
+ pTable->m_pfnLoadFile = &QERApp_LoadFile;
+ pTable->m_pfnExpandReletivePath = &QERApp_ExpandReletivePath;
+ pTable->m_pfnQE_ConvertDOSToUnixName = &QE_ConvertDOSToUnixName;
+ pTable->m_pfnHasShader = &QERApp_HasShader;
+ pTable->m_pfnTexture_LoadSkin = &Texture_LoadSkin;
+ pTable->m_pfnRadiantFree = &QERApp_RadiantFree;
+ pTable->m_pfnGetGamePath = &QERApp_GetGamePath;
+ pTable->m_pfnGetQERPath = &QERApp_GetQERPath;
+ // patches
+ pTable->m_pfnAllocateActivePatchHandles = &QERApp_AllocateActivePatchHandles;
+ pTable->m_pfnAllocateSelectedPatchHandles = &QERApp_AllocateSelectedPatchHandles;
+ pTable->m_pfnReleasePatchHandles = &QERApp_ReleasePatchHandles;
+ pTable->m_pfnGetPatchData = &QERApp_GetPatchData;
+ pTable->m_pfnDeletePatch = &QERApp_DeletePatch;
+ pTable->m_pfnCreatePatchHandle = &QERApp_CreatePatchHandle;
+ pTable->m_pfnCommitPatchHandleToMap = &QERApp_CommitPatchHandleToMap;
+ }
+ return true;
+ }
+ else
+ {
+ Sys_Printf("Unable to load %s because the function tables are not the same size\n", pPlug->getVersionStr());
+ }
+ return false;
+}
+
+CPlugIn * CPlugInManager::PluginForModule(HMODULE hPlug)
+{
+ int i;
+ for( i=0; i!=m_PlugIns.GetSize(); i++ )
+ {
+ if ( reinterpret_cast<CPlugIn *>(m_PlugIns[i])->GetDLLModule() == hPlug )
+ return reinterpret_cast<CPlugIn *>(m_PlugIns[i]);
+ }
+ return NULL;
+}
+
diff --git a/q3radiant/PlugInManager.h b/q3radiant/PlugInManager.h
new file mode 100755
index 0000000..1b77e94
--- /dev/null
+++ b/q3radiant/PlugInManager.h
@@ -0,0 +1,100 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// PlugInManager.h: interface for the CPlugInManager class.
+//
+//////////////////////////////////////////////////////////////////////
+
+#if !defined(AFX_PLUGINMANAGER_H__CFB18412_55FE_11D2_B082_00AA00A410FC__INCLUDED_)
+#define AFX_PLUGINMANAGER_H__CFB18412_55FE_11D2_B082_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+
+#include "plugin.h"
+
+class CPlugInManager
+{
+private:
+ CObArray m_PlugIns;
+ CPtrArray m_BrushHandles;
+ CPtrArray m_SelectedBrushHandles;
+ CPtrArray m_ActiveBrushHandles;
+
+ CPlugIn *m_pTexturePlug;
+ CPlugIn *m_pSurfaceListPlug;
+
+ // v1.70
+ // brushes of the current entity ( see m_SelectedBrushHandles and m_ActiveBrushHandles )
+ CPtrArray m_EntityBrushHandles;
+ // allocated entities, not commited yet ( see m_BrushHandles )
+ CPtrArray m_EntityHandles;
+
+ // tells in which array to look when given a patch index
+ enum EPatchesMode { EActivePatches, ESelectedPatches, EAllocatedPatches } PatchesMode;
+ // patches handles (brush_t*)
+ CPtrArray m_PatchesHandles;
+ // plugin-allocated patches, not commited yet (patchMesh_t*)
+ CPtrArray m_PluginPatches;
+
+public:
+ CPlugIn * PluginForModule( HMODULE hPlug );
+ CPtrArray& GetActiveHandles() {return m_ActiveBrushHandles; };
+ CPtrArray& GetSelectedHandles() {return m_SelectedBrushHandles; };
+ CPtrArray& GetPluginPatches() {return m_PluginPatches; };
+ brush_t* FindBrushHandle(void *vp);
+ patchMesh_t* FindPatchHandle(int index);
+ int CreatePatchHandle();
+ int AllocateActivePatchHandles();
+ int AllocateSelectedPatchHandles();
+ void CommitPatchHandleToMap(int index, patchMesh_t *pMesh, char *texName);
+ void ReleasePatchesHandles() { m_PatchesHandles.RemoveAll(); m_PluginPatches.RemoveAll(); }
+ void AddFaceToBrushHandle(void *vp, vec3_t v1, vec3_t v2, vec3_t v3);
+ void CommitBrushHandleToMap(void *vp);
+ void DeleteBrushHandle(LPVOID vp);
+ LPVOID CreateBrushHandle();
+ void Dispatch(int n, const char *p);
+ void Cleanup();
+ void Init(const char* pPath);
+ CPlugInManager();
+ virtual ~CPlugInManager();
+
+ // the texture manager front ends the single load
+ // addins (texture, model, map formats.. etc.)
+ _QERTextureInfo* GetTextureInfo();
+ void LoadTexture(const char *pFilename);
+
+ LPVOID GetSurfaceFlags();
+
+ // v1.70
+ CPtrArray& GetEntityBrushHandles() {return m_EntityBrushHandles; };
+ CPtrArray& GetEntityHandles() {return m_EntityHandles; };
+ // the vpBrush needs to be in m_BrushHandles
+ void CommitBrushHandleToEntity( LPVOID vpBrush, LPVOID vpEntity );
+ // the vpEntity needs to be in m_EntityHandles
+ void CommitEntityHandleToMap( LPVOID vpEntity );
+
+protected:
+ int FillFuncTable(CPlugIn *pPlug); // PGM
+};
+
+#endif // !defined(AFX_PLUGINMANAGER_H__CFB18412_55FE_11D2_B082_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/PluginEntities.cpp b/q3radiant/PluginEntities.cpp
new file mode 100755
index 0000000..fb2d972
--- /dev/null
+++ b/q3radiant/PluginEntities.cpp
@@ -0,0 +1,101 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//-----------------------------------------------------------------------------
+//
+// $LogFile$
+// $Revision: 1.1.1.4 $
+// $Author: ttimo $
+// $Date: 2000/01/18 00:17:34 $
+// $Log: PluginEntities.cpp,v $
+// Revision 1.1.1.4 2000/01/18 00:17:34 ttimo
+// merging in for RC
+//
+// Revision 1.3 2000/01/17 23:53:42 TBesset
+// ready for merge in sourceforge (RC candidate)
+//
+// Revision 1.2 2000/01/07 16:40:11 TBesset
+// merged from BSP frontend
+//
+// Revision 1.1.1.3 1999/12/29 18:31:34 TBesset
+// Q3Radiant public version
+//
+// Revision 1.1.1.1.2.1 1999/12/29 21:39:38 TBesset
+// updated to update3 from Robert
+//
+// Revision 1.1.1.3 1999/12/29 18:31:34 TBesset
+// Q3Radiant public version
+// Revision 1.1.1.3 1999/12/29 18:31:34 TBesset
+// Q3Radiant public version
+//
+// Revision 1.2 1999/11/22 17:46:46 Timo & Christine
+// merged EARadiant into the main tree
+// bug fixes for Q3Plugin / EAPlugin
+// export for Robert
+//
+// Revision 1.1.2.1 1999/11/03 20:38:01 Timo & Christine
+// MEAN plugin for Q3Radiant, alpha version
+//
+//
+// DESCRIPTION:
+// implementation of IPluginEntities specific interface
+//
+
+#include "stdafx.h"
+#include "io.h"
+
+// is Eclass_InitForModelDirectory
+int WINAPI QERApp_EClassScanDir( char *path, HMODULE hPlug )
+{
+ struct _finddata_t fileinfo;
+ int handle;
+ char temp[ _MAX_PATH ];
+ char filebase[ _MAX_PATH ];
+ char filename[ _MAX_PATH ];
+ char *s;
+ eclass_t *e;
+ QE_ConvertDOSToUnixName( temp, path );
+ strcpy (filebase, path);
+ s = filebase + strlen(filebase)-1;
+ while (*s != '\\' && *s != '/' && s!=filebase)
+ s--;
+ *s = 0;
+ handle = _findfirst (path, &fileinfo);
+ if (handle != -1)
+ {
+ do
+ {
+ sprintf (filename, "%s\\%s", filebase, fileinfo.name);
+ Eclass_ScanFile (filename);
+
+ if (eclass_found)
+ {
+ e = eclass_e;
+ e->modelpath = strdup( fileinfo.name );
+ e->nShowFlags |= ECLASS_PLUGINENTITY;
+ e->hPlug = hPlug;
+ }
+ } while (_findnext( handle, &fileinfo ) != -1);
+
+ _findclose (handle);
+ }
+ return 0;
+}
diff --git a/q3radiant/PrefsDlg.cpp b/q3radiant/PrefsDlg.cpp
new file mode 100755
index 0000000..df67f1f
--- /dev/null
+++ b/q3radiant/PrefsDlg.cpp
@@ -0,0 +1,578 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// PrefsDlg.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "PrefsDlg.h"
+#include "shlobj.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+#define PREF_SECTION "Prefs"
+#define INTERNAL_SECTION "Internals"
+#define MOUSE_KEY "MouseButtons"
+#define WINDOW_KEY "QE4StyleWindows"
+#define LAYOUT_KEY "WindowLayout"
+#define Q2_KEY "Quake2Dir"
+#define RUNQ2_KEY "RunQuake2Run"
+#define TLOCK_KEY "TextureLock"
+#define RLOCK_KEY "RotateLock"
+#define LOADLAST_KEY "LoadLast"
+#define LOADLASTMAP_KEY "LoadLastMap"
+#define LASTPROJ_KEY "LastProject"
+#define LASTMAP_KEY "LastMap"
+#define RUN_KEY "RunBefore"
+#define _3DFX_KEY "Use3Dfx"
+#define FACE_KEY "NewFaceGrab"
+#define BSP_KEY "InternalBSP"
+#define RCLICK_KEY "NewRightClick"
+#define VERTEX_KEY "NewVertex"
+#define AUTOSAVE_KEY "Autosave"
+#define AUTOSAVETIME_KEY "AutosaveMinutes"
+#define PAK_KEY "UsePAK"
+#define NEWAPPLY_KEY "ApplyDismissesSurface"
+#define HACK_KEY "Gatewayescapehack"
+#define TEXTURE_KEY "NewTextureWindowStuff"
+#define TINYBRUSH_KEY "CleanTinyBrushes"
+#define TINYSIZE_KEY "CleanTinyBrusheSize"
+#define SNAPSHOT_KEY "Snapshots"
+#define PAKFILE_KEY "PAKFile"
+#define STATUS_KEY "StatusPointSize"
+#define MOVESPEED_KEY "MoveSpeed"
+#define ANGLESPEED_KEY "AngleSpeed"
+#define SETGAME_KEY "UseSetGame"
+#define CAMXYUPDATE_KEY "CamXYUpdate"
+#define LIGHTDRAW_KEY "NewLightStyle"
+#define WHATGAME_KEY "WhichGame"
+#define CUBICCLIP_KEY "CubicClipping"
+#define CUBICSCALE_KEY "CubicScale"
+#define ALTEDGE_KEY "ALTEdgeDrag"
+#define TEXTUREBAR_KEY "UseTextureBar"
+#define FACECOLORS_KEY "FaceColors"
+#define QE4PAINT_KEY "QE4Paint"
+#define SNAPT_KEY "SnapT"
+#define XZVIS_KEY "XZVIS"
+#define YZVIS_KEY "YZVIS"
+#define ZVIS_KEY "ZVIS"
+#define SIZEPAINT_KEY "SizePainting"
+#define DLLENTITIES_KEY "DLLEntities"
+#define WIDETOOLBAR_KEY "WideToolBar"
+#define NOCLAMP_KEY "NoClamp"
+#define PREFAB_KEY "PrefabPath"
+#define USERINI_KEY "UserINIPath"
+#define ROTATION_KEY "Rotation"
+#define SGIOPENGL_KEY "SGIOpenGL"
+#define BUGGYICD_KEY "BuggyICD"
+#define HICOLOR_KEY "HiColorTextures"
+#define CHASEMOUSE_KEY "ChaseMouse"
+#define ENTITYSHOW_KEY "EntityShow"
+#define TEXTURESCALE_KEY "TextureScale"
+#define TEXTURESCROLLBAR_KEY "TextureScrollbar"
+#define DISPLAYLISTS_KEY "UseDisplayLists"
+#define NORMALIZECOLORS_KEY "NormalizeColors"
+#define SHADERS_KEY "UseShaders"
+#define SWITCHCLIP_KEY "SwitchClipKey"
+#define SELWHOLEENTS_KEY "SelectWholeEntitiesKey"
+#define TEXTURESUBSET_KEY "UseTextureSubsetLoading"
+#define TEXTUREQUALITY_KEY "TextureQuality"
+#define SHOWSHADERS_KEY "ShowShaders"
+#define SHADERTEST_KEY "ShaderTest"
+#define GLLIGHTING_KEY "UseGLLighting"
+#define LOADSHADERS_KEY "LoadShaders"
+#define NOSTIPPLE_KEY "NoStipple"
+#define UNDOLEVELS_KEY "UndoLevels"
+
+#define MOUSE_DEF 1
+#define WINDOW_DEF 0
+#define Q2_DEF "c:\\quake2\\quake2.exe"
+#define Q3_DEF "c:\\Program Files\\Quake III Arena\\quake3.exe"
+#define PAKFILE_DEF "c:\\quake2\\baseq2\\pak0.pak"
+#define RUNQ2_DEF 0
+#define TLOCK_DEF 1
+#define LOADLAST_DEF 1
+#define RUN_DEF 0
+
+/////////////////////////////////////////////////////////////////////////////
+// CPrefsDlg dialog
+
+
+CPrefsDlg::CPrefsDlg(CWnd* pParent /*=NULL*/)
+ : CDialog(CPrefsDlg::IDD, pParent)
+{
+ //{{AFX_DATA_INIT(CPrefsDlg)
+ m_strQuake2 = _T("c:\\quake3\\");
+ m_nMouse = 1;
+ m_nView = 0;
+ m_bLoadLast = FALSE;
+ m_bFace = FALSE;
+ m_bInternalBSP = FALSE;
+ m_bRightClick = FALSE;
+ m_bRunQuake = FALSE;
+ m_bSetGame = FALSE;
+ m_bVertex = FALSE;
+ m_bAutoSave = TRUE;
+ m_bNewApplyHandling = FALSE;
+ m_strAutoSave = _T("5");
+ m_bPAK = FALSE;
+ m_bLoadLastMap = FALSE;
+ m_bTextureWindow = FALSE;
+ m_bSnapShots = FALSE;
+ m_fTinySize = 0.5;
+ m_bCleanTiny = FALSE;
+ m_strPAKFile = _T("c:\\quake2\\baseq2\\pak0.pak");
+ m_nStatusSize = 10;
+ m_bCamXYUpdate = FALSE;
+ m_bNewLightDraw = FALSE;
+ m_strPrefabPath = _T("");
+ m_nWhatGame = 0;
+ m_strWhatGame = _T("Quake3");
+ m_bALTEdge = FALSE;
+ m_bTextureBar = FALSE;
+ m_bFaceColors = FALSE;
+ m_bQE4Painting = TRUE;
+ m_bSnapTToGrid = FALSE;
+ m_bXZVis = FALSE;
+ m_bYZVis = FALSE;
+ m_bZVis = FALSE;
+ m_bSizePaint = FALSE;
+ m_bDLLEntities = FALSE;
+ m_bWideToolbar = TRUE;
+ m_bNoClamp = FALSE;
+ m_strUserPath = _T("");
+ m_nRotation = 0;
+ m_bSGIOpenGL = FALSE;
+ m_bBuggyICD = FALSE;
+ m_bHiColorTextures = TRUE;
+ m_bChaseMouse = FALSE;
+ m_bTextureScrollbar = TRUE;
+ m_bDisplayLists = TRUE;
+ m_bShowShaders = FALSE;
+ m_nShader = -1;
+ m_bNoStipple = FALSE;
+ //}}AFX_DATA_INIT
+ //LoadPrefs();
+ m_bSelectCurves = TRUE;
+ m_bSelectTerrain = TRUE;
+ m_nEntityShowState = 0;
+ m_nTextureScale = 2;
+ m_bSwitchClip = FALSE;
+ m_bSelectWholeEntities = TRUE;
+ m_nTextureQuality = 3;
+ m_bShowShaders = TRUE;
+ m_bGLLighting = FALSE;
+ m_nShader = 0;
+ m_nUndoLevels = 64;
+}
+
+
+
+
+void CPrefsDlg::DoDataExchange(CDataExchange* pDX)
+{
+ CDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CPrefsDlg)
+ DDX_Control(pDX, IDC_SPIN_UNDO, m_wndUndoSpin);
+ DDX_Control(pDX, IDC_SPIN_POINTSIZE, m_wndFontSpin);
+ DDX_Control(pDX, IDC_SLIDER_TEXTUREQUALITY, m_wndTexturequality);
+ DDX_Control(pDX, IDC_COMBO_WHATGAME, m_wndWhatGame);
+ DDX_Control(pDX, IDC_SLIDER_CAMSPEED, m_wndCamSpeed);
+ DDX_Control(pDX, IDC_SPIN_AUTOSAVE, m_wndSpin);
+ DDX_Text(pDX, IDC_EDIT_QUAKE2, m_strQuake2);
+ DDX_Radio(pDX, IDC_RADIO_MOUSE, m_nMouse);
+ DDX_Radio(pDX, IDC_RADIO_VIEWTYPE, m_nView);
+ DDX_Check(pDX, IDC_CHECK_LOADLAST, m_bLoadLast);
+ DDX_Check(pDX, IDC_CHECK_FACE, m_bFace);
+ DDX_Check(pDX, IDC_CHECK_INTERNALBSP, m_bInternalBSP);
+ DDX_Check(pDX, IDC_CHECK_RIGHTCLICK, m_bRightClick);
+ DDX_Check(pDX, IDC_CHECK_RUNQUAKE, m_bRunQuake);
+ DDX_Check(pDX, IDC_CHECK_SETGAME, m_bSetGame);
+ DDX_Check(pDX, IDC_CHECK_VERTEX, m_bVertex);
+ DDX_Check(pDX, IDC_CHECK_AUTOSAVE, m_bAutoSave);
+ DDX_Text(pDX, IDC_EDIT_AUTOSAVE, m_strAutoSave);
+ DDX_Check(pDX, IDC_CHECK_PAK, m_bPAK);
+ DDX_Check(pDX, IDC_CHECK_LOADLASTMAP, m_bLoadLastMap);
+ DDX_Check(pDX, IDC_CHECK_TEXTUREWINDOW, m_bTextureWindow);
+ DDX_Check(pDX, IDC_CHECK_SNAPSHOTS, m_bSnapShots);
+ DDX_Text(pDX, IDC_EDIT_PAKFILE, m_strPAKFile);
+ DDX_Text(pDX, IDC_EDIT_STATUSPOINTSIZE, m_nStatusSize);
+ DDV_MinMaxInt(pDX, m_nStatusSize, 2, 14);
+ DDX_Check(pDX, IDC_CHECK_CAMXYUPDATE, m_bCamXYUpdate);
+ DDX_Check(pDX, IDC_CHECK_LIGHTDRAW, m_bNewLightDraw);
+ DDX_Text(pDX, IDC_EDIT_PREFABPATH, m_strPrefabPath);
+ DDX_CBString(pDX, IDC_COMBO_WHATGAME, m_strWhatGame);
+ DDX_Check(pDX, IDC_CHECK_ALTDRAG, m_bALTEdge);
+ DDX_Check(pDX, IDC_CHECK_TEXTURETOOLBAR, m_bTextureBar);
+ DDX_Check(pDX, IDC_CHECK_FACECOLOR, m_bFaceColors);
+ DDX_Check(pDX, IDC_CHECK_QE4PAINTING, m_bQE4Painting);
+ DDX_Check(pDX, IDC_CHECK_SNAPT, m_bSnapTToGrid);
+ DDX_Check(pDX, IDC_CHECK_SIZEPAINT, m_bSizePaint);
+ DDX_Check(pDX, IDC_CHECK_DLLENTITIES, m_bDLLEntities);
+ DDX_Check(pDX, IDC_CHECK_WIDETOOLBAR, m_bWideToolbar);
+ DDX_Check(pDX, IDC_CHECK_NOCLAMP, m_bNoClamp);
+ DDX_Text(pDX, IDC_EDIT_USERPATH, m_strUserPath);
+ DDX_Text(pDX, IDC_EDIT_ROTATION, m_nRotation);
+ DDX_Check(pDX, IDC_CHECK_SGIOPENGL, m_bSGIOpenGL);
+ DDX_Check(pDX, IDC_CHECK_BUGGYICD, m_bBuggyICD);
+ DDX_Check(pDX, IDC_CHECK_HICOLOR, m_bHiColorTextures);
+ DDX_Check(pDX, IDC_CHECK_MOUSECHASE, m_bChaseMouse);
+ DDX_Check(pDX, IDC_CHECK_TEXTURESCROLLBAR, m_bTextureScrollbar);
+ DDX_Check(pDX, IDC_CHECK_DISPLAYLISTS, m_bDisplayLists);
+ DDX_CBIndex(pDX, IDC_COMBO_SHADERS, m_nShader);
+ DDX_Check(pDX, IDC_CHECK_NOSTIPPLE, m_bNoStipple);
+ DDX_Text(pDX, IDC_EDIT_UNDOLEVELS, m_nUndoLevels);
+ DDV_MinMaxInt(pDX, m_nUndoLevels, 1, 64);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CPrefsDlg, CDialog)
+ //{{AFX_MSG_MAP(CPrefsDlg)
+ ON_BN_CLICKED(IDC_BTN_BROWSE, OnBtnBrowse)
+ ON_BN_CLICKED(IDC_BTN_BROWSEPAK, OnBtnBrowsepak)
+ ON_BN_CLICKED(IDC_BTN_BROWSEPREFAB, OnBtnBrowseprefab)
+ ON_BN_CLICKED(IDC_BTN_BROWSEUSERINI, OnBtnBrowseuserini)
+ ON_CBN_SELCHANGE(IDC_COMBO_WHATGAME, OnSelchangeComboWhatgame)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CPrefsDlg message handlers
+
+void CPrefsDlg::OnBtnBrowse()
+{
+ UpdateData(TRUE);
+ CFileDialog dlg(true, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, "Executables (*.exe)|*.exe||", this);
+ if (dlg.DoModal() == IDOK)
+ {
+ m_strQuake2 = dlg.GetPathName();
+ UpdateData(FALSE);
+ }
+}
+
+BOOL CPrefsDlg::OnInitDialog()
+{
+ CDialog::OnInitDialog();
+ m_wndSpin.SetRange(1,60);
+ m_wndCamSpeed.SetRange(10, 800);
+ m_wndCamSpeed.SetPos(m_nMoveSpeed);
+
+ this->m_wndTexturequality.SetRange(0, 3);
+ this->m_wndTexturequality.SetPos(m_nTextureQuality);
+
+ m_wndFontSpin.SetRange(4,24);
+ m_wndUndoSpin.SetRange(1,64);
+
+ m_wndWhatGame.AddString("Quake2");
+ m_wndWhatGame.AddString("Quake3");
+
+ GetDlgItem(IDC_CHECK_HICOLOR)->EnableWindow(TRUE);
+ GetDlgItem(IDC_CHECK_NOCLAMP)->EnableWindow(TRUE);
+
+ //GetDlgItem(IDC_CHECK_NOCLAMP)->EnableWindow(FALSE);
+
+ m_wndWhatGame.SelectString(-1,m_strWhatGame);
+ if (strstr(m_strWhatGame, "Quake3") != NULL)
+ {
+ GetDlgItem(IDC_EDIT_PAKFILE)->EnableWindow(FALSE);
+ GetDlgItem(IDC_BTN_BROWSEPAK)->EnableWindow(FALSE);
+ GetDlgItem(IDC_CHECK_INTERNALBSP)->EnableWindow(FALSE);
+ }
+ else
+ {
+ GetDlgItem(IDC_EDIT_PAKFILE)->EnableWindow(TRUE);
+ GetDlgItem(IDC_BTN_BROWSEPAK)->EnableWindow(TRUE);
+ GetDlgItem(IDC_CHECK_INTERNALBSP)->EnableWindow(TRUE);
+ }
+
+ return TRUE; // return TRUE unless you set the focus to a control
+ // EXCEPTION: OCX Property Pages should return FALSE
+}
+
+void CPrefsDlg::OnOK()
+{
+ m_nMoveSpeed = m_wndCamSpeed.GetPos();
+ m_nAngleSpeed = (float)m_nMoveSpeed * 0.50;
+ this->m_nTextureQuality = m_wndTexturequality.GetPos();
+ SavePrefs();
+
+ if (g_pParentWnd)
+ g_pParentWnd->SetGridStatus();
+ Sys_UpdateWindows(W_ALL);
+ Undo_SetMaxSize(m_nUndoLevels);
+ CDialog::OnOK();
+}
+
+void CPrefsDlg::LoadPrefs()
+{
+ CString strBuff;
+ CString strPrefab = g_strAppPath;
+ AddSlash(strPrefab);
+ strPrefab += "Prefabs\\";
+
+ m_nMouse = AfxGetApp()->GetProfileInt(PREF_SECTION, MOUSE_KEY, MOUSE_DEF);
+ if (m_nMouse == 0)
+ m_nMouseButtons = 2;
+ else
+ m_nMouseButtons = 3;
+
+ m_nView = AfxGetApp()->GetProfileInt(PREF_SECTION, WINDOW_KEY, WINDOW_DEF);
+ m_strQuake2 = AfxGetApp()->GetProfileString(PREF_SECTION, Q2_KEY, Q2_DEF);
+ m_bRunQuake = AfxGetApp()->GetProfileInt(PREF_SECTION, RUNQ2_KEY, RUNQ2_DEF);
+ m_bTextureLock = AfxGetApp()->GetProfileInt(PREF_SECTION, TLOCK_KEY, TLOCK_DEF);
+ m_bRotateLock = AfxGetApp()->GetProfileInt(PREF_SECTION, RLOCK_KEY, TLOCK_DEF);
+ m_strLastProject = AfxGetApp()->GetProfileString(PREF_SECTION, LASTPROJ_KEY, "");
+ m_strLastMap = AfxGetApp()->GetProfileString(PREF_SECTION, LASTMAP_KEY, "");
+ m_bLoadLast = AfxGetApp()->GetProfileInt(PREF_SECTION, LOADLAST_KEY, LOADLAST_DEF);
+ m_bRunBefore = AfxGetApp()->GetProfileInt(INTERNAL_SECTION, RUN_KEY, RUN_DEF);
+ //m_b3Dfx = AfxGetApp()->GetProfileInt(PREF_SECTION, _3DFX_KEY, 0);
+ m_bFace = AfxGetApp()->GetProfileInt(PREF_SECTION, FACE_KEY, 1);
+ m_bInternalBSP = AfxGetApp()->GetProfileInt(PREF_SECTION, BSP_KEY, 0);
+ m_bRightClick = AfxGetApp()->GetProfileInt(PREF_SECTION, RCLICK_KEY, 1);
+ m_bVertex = AfxGetApp()->GetProfileInt(PREF_SECTION, VERTEX_KEY, 1);
+ m_bAutoSave = AfxGetApp()->GetProfileInt(PREF_SECTION, AUTOSAVE_KEY, 1);
+ m_bPAK = AfxGetApp()->GetProfileInt(PREF_SECTION, PAK_KEY, 1);
+ m_bNewApplyHandling = AfxGetApp()->GetProfileInt(PREF_SECTION, NEWAPPLY_KEY, 0);
+ m_bLoadLastMap = AfxGetApp()->GetProfileInt(PREF_SECTION, LOADLASTMAP_KEY, 0);
+ m_bGatewayHack = AfxGetApp()->GetProfileInt(PREF_SECTION, HACK_KEY, 0);
+ m_bTextureWindow = AfxGetApp()->GetProfileInt(PREF_SECTION, TEXTURE_KEY, 0);
+ m_bCleanTiny = AfxGetApp()->GetProfileInt(PREF_SECTION, TINYBRUSH_KEY, 0);
+ strBuff = AfxGetApp()->GetProfileString(PREF_SECTION, TINYSIZE_KEY, "0.5");
+ m_fTinySize = atof(strBuff);
+ m_nAutoSave = AfxGetApp()->GetProfileInt(PREF_SECTION, AUTOSAVETIME_KEY, 5);
+ m_strAutoSave.Format("%i", m_nAutoSave);
+ m_bSnapShots = AfxGetApp()->GetProfileInt(PREF_SECTION, SNAPSHOT_KEY, 0);
+ m_strPAKFile = AfxGetApp()->GetProfileString(PREF_SECTION, PAKFILE_KEY, PAKFILE_DEF);
+ m_nStatusSize = AfxGetApp()->GetProfileInt(PREF_SECTION, STATUS_KEY, 10);
+ m_nMoveSpeed = AfxGetApp()->GetProfileInt(PREF_SECTION, MOVESPEED_KEY, 400);
+ m_nAngleSpeed = AfxGetApp()->GetProfileInt(PREF_SECTION, ANGLESPEED_KEY, 300);
+ m_bSetGame = AfxGetApp()->GetProfileInt(PREF_SECTION, SETGAME_KEY, 0);
+ m_bCamXYUpdate = AfxGetApp()->GetProfileInt(PREF_SECTION, CAMXYUPDATE_KEY, 1);
+ m_bNewLightDraw = AfxGetApp()->GetProfileInt(PREF_SECTION, LIGHTDRAW_KEY, 1);
+ m_bCubicClipping = AfxGetApp()->GetProfileInt(PREF_SECTION, CUBICCLIP_KEY, 1);
+ m_nCubicScale = AfxGetApp()->GetProfileInt(PREF_SECTION, CUBICSCALE_KEY, 13);
+ m_bALTEdge = AfxGetApp()->GetProfileInt(PREF_SECTION, ALTEDGE_KEY, 0);
+ m_bTextureBar = AfxGetApp()->GetProfileInt(PREF_SECTION, TEXTUREBAR_KEY, 0);
+ m_strWhatGame = AfxGetApp()->GetProfileString(PREF_SECTION, WHATGAME_KEY, "Quake3");
+ m_bFaceColors = AfxGetApp()->GetProfileInt(PREF_SECTION, FACECOLORS_KEY, 0);
+ m_bQE4Painting = AfxGetApp()->GetProfileInt(PREF_SECTION, QE4PAINT_KEY, 1);
+ m_bSnapTToGrid = AfxGetApp()->GetProfileInt(PREF_SECTION, SNAPT_KEY, 0);
+ m_bXZVis = AfxGetApp()->GetProfileInt(PREF_SECTION, XZVIS_KEY, 0);
+ m_bYZVis = AfxGetApp()->GetProfileInt(PREF_SECTION, YZVIS_KEY, 0);
+ m_bZVis = AfxGetApp()->GetProfileInt(PREF_SECTION, ZVIS_KEY, 1);
+ m_bSizePaint = AfxGetApp()->GetProfileInt(PREF_SECTION, SIZEPAINT_KEY, 0);
+ m_bDLLEntities = AfxGetApp()->GetProfileInt(PREF_SECTION, DLLENTITIES_KEY, 0);
+ m_bWideToolbar = AfxGetApp()->GetProfileInt(PREF_SECTION, WIDETOOLBAR_KEY, 1);
+ m_bNoClamp = AfxGetApp()->GetProfileInt(PREF_SECTION, NOCLAMP_KEY, 0);
+ m_strPrefabPath = AfxGetApp()->GetProfileString(PREF_SECTION, PREFAB_KEY, strPrefab);
+ m_strUserPath = AfxGetApp()->GetProfileString(PREF_SECTION, USERINI_KEY, "");
+ m_nRotation = AfxGetApp()->GetProfileInt(PREF_SECTION, ROTATION_KEY, 45);
+ m_bSGIOpenGL = AfxGetApp()->GetProfileInt(PREF_SECTION, SGIOPENGL_KEY, 0);
+ m_bBuggyICD = AfxGetApp()->GetProfileInt(PREF_SECTION, BUGGYICD_KEY, 0);
+ m_bHiColorTextures = AfxGetApp()->GetProfileInt(PREF_SECTION, HICOLOR_KEY, 1);
+ m_bChaseMouse = AfxGetApp()->GetProfileInt(PREF_SECTION, CHASEMOUSE_KEY, 1);
+ m_nEntityShowState = AfxGetApp()->GetProfileInt(PREF_SECTION, ENTITYSHOW_KEY, 0);
+ m_nTextureScale = AfxGetApp()->GetProfileInt(PREF_SECTION, TEXTURESCALE_KEY, 50);
+ m_bTextureScrollbar = AfxGetApp()->GetProfileInt(PREF_SECTION, TEXTURESCROLLBAR_KEY, TRUE);
+ m_bDisplayLists = AfxGetApp()->GetProfileInt(PREF_SECTION, DISPLAYLISTS_KEY, TRUE);
+ m_bSwitchClip = AfxGetApp()->GetProfileInt(PREF_SECTION, SWITCHCLIP_KEY, TRUE);
+ m_bSelectWholeEntities = AfxGetApp()->GetProfileInt(PREF_SECTION, SELWHOLEENTS_KEY, TRUE);
+ m_nTextureQuality = AfxGetApp()->GetProfileInt(PREF_SECTION, TEXTUREQUALITY_KEY, 6);
+ m_bShowShaders = AfxGetApp()->GetProfileInt(PREF_SECTION, SHOWSHADERS_KEY, TRUE);
+ m_bGLLighting = AfxGetApp()->GetProfileInt(PREF_SECTION, GLLIGHTING_KEY, FALSE);
+ m_nShader = AfxGetApp()->GetProfileInt(PREF_SECTION, LOADSHADERS_KEY, 0);
+ m_bNoStipple = AfxGetApp()->GetProfileInt(PREF_SECTION, NOSTIPPLE_KEY, 0);
+ m_nUndoLevels = AfxGetApp()->GetProfileInt(PREF_SECTION, UNDOLEVELS_KEY, 0);
+
+ if (m_bRunBefore == FALSE)
+ {
+ SetGamePrefs();
+ }
+}
+
+
+void CPrefsDlg::SavePrefs()
+{
+ if (GetSafeHwnd())
+ UpdateData(TRUE);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, MOUSE_KEY, m_nMouse);
+ if (m_nMouse == 0)
+ m_nMouseButtons = 2;
+ else
+ m_nMouseButtons = 3;
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, WINDOW_KEY, m_nView);
+ AfxGetApp()->WriteProfileString(PREF_SECTION, Q2_KEY, m_strQuake2);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, RUNQ2_KEY, m_bRunQuake);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, TLOCK_KEY, m_bTextureLock);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, RLOCK_KEY, m_bRotateLock);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, LOADLAST_KEY, m_bLoadLast);
+ AfxGetApp()->WriteProfileString(PREF_SECTION, LASTPROJ_KEY, m_strLastProject);
+ AfxGetApp()->WriteProfileString(PREF_SECTION, LASTMAP_KEY, m_strLastMap);
+ AfxGetApp()->WriteProfileInt(INTERNAL_SECTION, RUN_KEY, m_bRunBefore);
+ //AfxGetApp()->WriteProfileInt(PREF_SECTION, _3DFX_KEY, m_b3Dfx);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, FACE_KEY, m_bFace);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, BSP_KEY, m_bInternalBSP);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, RCLICK_KEY, m_bRightClick);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, VERTEX_KEY, m_bVertex);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, AUTOSAVE_KEY, m_bAutoSave);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, PAK_KEY, m_bPAK);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, LOADLASTMAP_KEY, m_bLoadLastMap);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, TEXTURE_KEY, m_bTextureWindow);
+ m_nAutoSave = atoi(m_strAutoSave);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, AUTOSAVETIME_KEY, m_nAutoSave);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, SNAPSHOT_KEY, m_bSnapShots);
+ AfxGetApp()->WriteProfileString(PREF_SECTION, PAKFILE_KEY, m_strPAKFile);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, STATUS_KEY, m_nStatusSize);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, SETGAME_KEY, m_bSetGame);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, CAMXYUPDATE_KEY, m_bCamXYUpdate);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, LIGHTDRAW_KEY, m_bNewLightDraw);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, MOVESPEED_KEY, m_nMoveSpeed);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, ANGLESPEED_KEY, m_nAngleSpeed);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, CUBICCLIP_KEY, m_bCubicClipping);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, CUBICSCALE_KEY, m_nCubicScale);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, ALTEDGE_KEY, m_bALTEdge);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, TEXTUREBAR_KEY, m_bTextureBar);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, FACECOLORS_KEY, m_bFaceColors);
+ AfxGetApp()->WriteProfileString(PREF_SECTION, WHATGAME_KEY, m_strWhatGame);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, QE4PAINT_KEY, m_bQE4Painting);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, SNAPT_KEY, m_bSnapTToGrid);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, XZVIS_KEY, m_bXZVis);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, YZVIS_KEY, m_bYZVis);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, ZVIS_KEY, m_bZVis);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, SIZEPAINT_KEY, m_bSizePaint);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, DLLENTITIES_KEY, m_bDLLEntities);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, WIDETOOLBAR_KEY, m_bWideToolbar);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, NOCLAMP_KEY, m_bNoClamp);
+ AfxGetApp()->WriteProfileString(PREF_SECTION, PREFAB_KEY, m_strPrefabPath);
+ AfxGetApp()->WriteProfileString(PREF_SECTION, USERINI_KEY, m_strUserPath);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, ROTATION_KEY, m_nRotation);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, SGIOPENGL_KEY, m_bSGIOpenGL);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, BUGGYICD_KEY, m_bBuggyICD);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, HICOLOR_KEY, m_bHiColorTextures);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, CHASEMOUSE_KEY, m_bChaseMouse);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, ENTITYSHOW_KEY, m_nEntityShowState);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, TEXTURESCALE_KEY, m_nTextureScale);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, TEXTURESCROLLBAR_KEY, m_bTextureScrollbar);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, DISPLAYLISTS_KEY, m_bDisplayLists);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, SWITCHCLIP_KEY, m_bSwitchClip);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, SELWHOLEENTS_KEY, m_bSelectWholeEntities);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, TEXTUREQUALITY_KEY, m_nTextureQuality);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, SHOWSHADERS_KEY, m_bShowShaders);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, GLLIGHTING_KEY, m_bGLLighting);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, LOADSHADERS_KEY, m_nShader);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, NOSTIPPLE_KEY, m_bNoStipple);
+ AfxGetApp()->WriteProfileInt(PREF_SECTION, UNDOLEVELS_KEY, m_nUndoLevels);
+}
+
+
+
+void CPrefsDlg::OnBtnBrowsepak()
+{
+ UpdateData(TRUE);
+ CFileDialog dlg(true, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, "PAK files (*.pak)|*.pak||", this);
+ if (dlg.DoModal() == IDOK)
+ {
+ m_strPAKFile = dlg.GetPathName();
+ UpdateData(FALSE);
+ }
+}
+
+void CPrefsDlg::OnBtnBrowseprefab()
+{
+ UpdateData(TRUE);
+ BROWSEINFO bi;
+ CString strPath;
+ char* p = strPath.GetBuffer(MAX_PATH+1);
+ bi.hwndOwner = GetSafeHwnd();
+ bi.pidlRoot = NULL;
+ bi.pszDisplayName = p;
+ bi.lpszTitle = "Load textures from path";
+ bi.ulFlags = 0;
+ bi.lpfn = NULL;
+ bi.lParam = NULL;
+ bi.iImage = 0;
+ LPITEMIDLIST pidlBrowse;
+ pidlBrowse = SHBrowseForFolder(&bi);
+ if (pidlBrowse)
+ {
+ SHGetPathFromIDList(pidlBrowse, p);
+ strPath.ReleaseBuffer();
+ AddSlash(strPath);
+ m_strPrefabPath = strPath;
+ UpdateData(FALSE);
+ }
+}
+
+void CPrefsDlg::OnBtnBrowseuserini()
+{
+ UpdateData(TRUE);
+ CFileDialog dlg(true, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, "INI files (*.ini)|*.ini||", this);
+ if (dlg.DoModal() == IDOK)
+ {
+ m_strUserPath = dlg.GetPathName();
+ UpdateData(FALSE);
+ }
+}
+
+void CPrefsDlg::OnSelchangeComboWhatgame()
+{
+ int n = m_wndWhatGame.GetCurSel();
+ if (n >= 0)
+ {
+ m_wndWhatGame.GetLBText(n, m_strWhatGame);
+ }
+ SetGamePrefs();
+}
+
+void CPrefsDlg::SetGamePrefs()
+{
+ if (strstr(m_strWhatGame, "Quake3") != NULL)
+ {
+ m_bHiColorTextures = TRUE;
+ m_bWideToolbar = TRUE;
+ m_strPAKFile = "PK3 files are loaded from the baseq3 path";
+ m_bInternalBSP = FALSE;
+ if (GetSafeHwnd())
+ {
+ GetDlgItem(IDC_EDIT_PAKFILE)->EnableWindow(FALSE);
+ GetDlgItem(IDC_BTN_BROWSEPAK)->EnableWindow(FALSE);
+ GetDlgItem(IDC_CHECK_INTERNALBSP)->EnableWindow(FALSE);
+ }
+ }
+ else
+ {
+ m_bHiColorTextures = FALSE;
+ m_bWideToolbar = FALSE;
+ m_strPAKFile = PAKFILE_DEF;
+ if (GetSafeHwnd())
+ {
+ GetDlgItem(IDC_EDIT_PAKFILE)->EnableWindow(TRUE);
+ GetDlgItem(IDC_BTN_BROWSEPAK)->EnableWindow(TRUE);
+ GetDlgItem(IDC_CHECK_INTERNALBSP)->EnableWindow(TRUE);
+ }
+ }
+ SavePrefs();
+}
diff --git a/q3radiant/PrefsDlg.h b/q3radiant/PrefsDlg.h
new file mode 100755
index 0000000..892fab9
--- /dev/null
+++ b/q3radiant/PrefsDlg.h
@@ -0,0 +1,161 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_PREFSDLG_H__DC829122_812D_11D1_B548_00AA00A410FC__INCLUDED_)
+#define AFX_PREFSDLG_H__DC829122_812D_11D1_B548_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// PrefsDlg.h : header file
+//
+
+#include "resource.h"
+
+/////////////////////////////////////////////////////////////////////////////
+// CPrefsDlg dialog
+
+#define MAX_TEXTURE_QUALITY 3
+
+class CPrefsDlg : public CDialog
+{
+// Construction
+public:
+ // these mirror what goes in the combo box
+ enum {SHADER_NONE = 0, SHADER_COMMON, SHADER_ALL};
+ void LoadPrefs();
+ void SavePrefs();
+ void SetGamePrefs();
+ CPrefsDlg(CWnd* pParent = NULL); // standard constructor
+
+// Dialog Data
+ //{{AFX_DATA(CPrefsDlg)
+ enum { IDD = IDD_DLG_PREFS };
+ CSpinButtonCtrl m_wndUndoSpin;
+ CSpinButtonCtrl m_wndFontSpin;
+ CSliderCtrl m_wndTexturequality;
+ CComboBox m_wndWhatGame;
+ CSliderCtrl m_wndCamSpeed;
+ CSpinButtonCtrl m_wndSpin;
+ CString m_strQuake2;
+ int m_nMouse;
+ int m_nView;
+ BOOL m_bTextureLock;
+ BOOL m_bLoadLast;
+ BOOL m_bRunBefore;
+ CString m_strLastProject;
+ CString m_strLastMap;
+ BOOL m_bFace;
+ BOOL m_bInternalBSP;
+ BOOL m_bRightClick;
+ BOOL m_bRunQuake;
+ BOOL m_bSetGame;
+ BOOL m_bVertex;
+ BOOL m_bAutoSave;
+ BOOL m_bNewApplyHandling;
+ CString m_strAutoSave;
+ BOOL m_bPAK;
+ BOOL m_bLoadLastMap;
+ BOOL m_bGatewayHack;
+ BOOL m_bTextureWindow;
+ BOOL m_bSnapShots;
+ float m_fTinySize;
+ BOOL m_bCleanTiny;
+ CString m_strPAKFile;
+ int m_nStatusSize;
+ BOOL m_bCamXYUpdate;
+ BOOL m_bNewLightDraw;
+ CString m_strPrefabPath;
+ int m_nWhatGame;
+ CString m_strWhatGame;
+ BOOL m_bALTEdge;
+ BOOL m_bTextureBar;
+ BOOL m_bFaceColors;
+ BOOL m_bQE4Painting;
+ BOOL m_bSnapTToGrid;
+ BOOL m_bXZVis;
+ BOOL m_bYZVis;
+ BOOL m_bZVis;
+ BOOL m_bSizePaint;
+ BOOL m_bDLLEntities;
+ BOOL m_bRotateLock;
+ BOOL m_bWideToolbar;
+ BOOL m_bNoClamp;
+ CString m_strUserPath;
+ int m_nRotation;
+ BOOL m_bSGIOpenGL;
+ BOOL m_bBuggyICD;
+ BOOL m_bHiColorTextures;
+ BOOL m_bChaseMouse;
+ BOOL m_bTextureScrollbar;
+ BOOL m_bDisplayLists;
+ BOOL m_bShowShaders;
+ int m_nShader;
+ BOOL m_bNoStipple;
+ int m_nUndoLevels;
+ //}}AFX_DATA
+ int m_nMouseButtons;
+ int m_nAngleSpeed;
+ int m_nMoveSpeed;
+ int m_nAutoSave;
+ bool m_bCubicClipping;
+ int m_nCubicScale;
+ BOOL m_bSelectCurves;
+ BOOL m_bSelectTerrain;
+ int m_nEntityShowState;
+ int m_nTextureScale;
+ BOOL m_bNormalizeColors;
+ BOOL m_bSwitchClip;
+ BOOL m_bSelectWholeEntities;
+ int m_nTextureQuality;
+ BOOL m_bGLLighting;
+
+ // brush primitive mode
+ //++timo moved into g_qeglobals
+// BOOL m_bBrushPrimitMode;
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CPrefsDlg)
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+
+ // Generated message map functions
+ //{{AFX_MSG(CPrefsDlg)
+ afx_msg void OnBtnBrowse();
+ virtual BOOL OnInitDialog();
+ virtual void OnOK();
+ afx_msg void OnBtnBrowsepak();
+ afx_msg void OnBtnBrowseprefab();
+ afx_msg void OnBtnBrowseuserini();
+ afx_msg void OnSelchangeComboWhatgame();
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_PREFSDLG_H__DC829122_812D_11D1_B548_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/QE3.CPP b/q3radiant/QE3.CPP
new file mode 100755
index 0000000..691977d
--- /dev/null
+++ b/q3radiant/QE3.CPP
@@ -0,0 +1,751 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "stdafx.h"
+#include "qe3.h"
+#include "PrefsDlg.h"
+#include <direct.h>
+#include <sys\stat.h>
+
+QEGlobals_t g_qeglobals;
+
+void WINAPI QE_CheckOpenGLForErrors(void)
+{
+ CString strMsg;
+ int i = qglGetError();
+ if (i != GL_NO_ERROR)
+ {
+ if (i == GL_OUT_OF_MEMORY)
+ {
+ //strMsg.Format("OpenGL out of memory error %s\nDo you wish to save before exiting?", qgluErrorString((GLenum)i));
+ if (MessageBox(g_qeglobals.d_hwndMain, strMsg, "Q3Radiant Error", MB_YESNO) == IDYES)
+ {
+ Map_SaveFile(NULL, false);
+ }
+ exit(1);
+ }
+ else
+ {
+ //strMsg.Format("Warning: OpenGL Error %s\n ", qgluErrorString((GLenum)i));
+ Sys_Printf (strMsg.GetBuffer(0));
+ }
+ }
+}
+
+
+char *ExpandReletivePath (char *p)
+{
+ static char temp[1024];
+ char *base;
+
+ if (!p || !p[0])
+ return NULL;
+ if (p[0] == '/' || p[0] == '\\')
+ return p;
+
+ base = ValueForKey(g_qeglobals.d_project_entity, "basepath");
+ sprintf (temp, "%s/%s", base, p);
+ return temp;
+}
+
+char *copystring (char *s)
+{
+ char *b;
+ b = (char*)malloc(strlen(s)+1);
+ strcpy (b,s);
+ return b;
+}
+
+
+bool DoesFileExist(const char* pBuff, long& lSize)
+{
+ CFile file;
+ if (file.Open(pBuff, CFile::modeRead | CFile::shareDenyNone))
+ {
+ lSize += file.GetLength();
+ file.Close();
+ return true;
+ }
+ return false;
+}
+
+
+void Map_Snapshot()
+{
+ CString strMsg;
+ // we need to do the following
+ // 1. make sure the snapshot directory exists (create it if it doesn't)
+ // 2. find out what the lastest save is based on number
+ // 3. inc that and save the map
+ CString strOrgPath, strOrgFile;
+ ExtractPath_and_Filename(currentmap, strOrgPath, strOrgFile);
+ AddSlash(strOrgPath);
+ strOrgPath += "snapshots";
+ bool bGo = true;
+ struct _stat Stat;
+ if (_stat(strOrgPath, &Stat) == -1)
+ {
+ bGo = (_mkdir(strOrgPath) != -1);
+ }
+ AddSlash(strOrgPath);
+ if (bGo)
+ {
+ int nCount = 0;
+ long lSize = 0;
+ CString strNewPath = strOrgPath;
+ strNewPath += strOrgFile;
+ CString strFile;
+ while (bGo)
+ {
+ strFile.Format("%s.%i", strNewPath, nCount);
+ bGo = DoesFileExist(strFile, lSize);
+ nCount++;
+ }
+ // strFile has the next available slot
+ Map_SaveFile(strFile.GetBuffer(0), false);
+ Sys_SetTitle (currentmap);
+ if (lSize > 12 * 1024 * 1024) // total size of saves > 4 mb
+ {
+ Sys_Printf("The snapshot files in the [%s] directory total more than 4 megabytes. You might consider cleaning the directory up.", strOrgPath);
+ }
+ }
+ else
+ {
+ strMsg.Format("Snapshot save failed.. unabled to create directory\n%s", strOrgPath);
+ g_pParentWnd->MessageBox(strMsg);
+ }
+}
+/*
+===============
+QE_CheckAutoSave
+
+If five minutes have passed since making a change
+and the map hasn't been saved, save it out.
+===============
+*/
+
+
+void QE_CheckAutoSave( void )
+{
+ static clock_t s_start;
+ clock_t now;
+
+ now = clock();
+
+ if ( modified != 1 || !s_start)
+ {
+ s_start = now;
+ return;
+ }
+
+ if ( now - s_start > ( CLOCKS_PER_SEC * 60 * g_PrefsDlg.m_nAutoSave))
+ {
+
+ if (g_PrefsDlg.m_bAutoSave)
+ {
+ CString strMsg = g_PrefsDlg.m_bSnapShots ? "Autosaving snapshot..." : "Autosaving...";
+ Sys_Printf(strMsg.GetBuffer(0));
+ Sys_Printf("\n");
+ Sys_Status (strMsg.GetBuffer(0),0);
+
+ // only snapshot if not working on a default map
+ if (g_PrefsDlg.m_bSnapShots && stricmp(currentmap, "unnamed.map") != 0)
+ {
+ Map_Snapshot();
+ }
+ else
+ {
+ Map_SaveFile (ValueForKey(g_qeglobals.d_project_entity, "autosave"), false);
+ }
+
+ Sys_Status ("Autosaving...Saved.", 0 );
+ modified = 2;
+ }
+ else
+ {
+ Sys_Printf ("Autosave skipped...\n");
+ Sys_Status ("Autosave skipped...", 0 );
+ }
+ s_start = now;
+ }
+}
+
+
+int BuildShortPathName(const char* pPath, char* pBuffer, int nBufferLen)
+{
+ char *pFile = NULL;
+ int nResult = GetFullPathName(pPath, nBufferLen, pBuffer, &pFile);
+ nResult = GetShortPathName(pPath, pBuffer, nBufferLen);
+ if (nResult == 0)
+ strcpy(pBuffer, pPath); // Use long filename
+ return nResult;
+}
+
+
+
+const char *g_pPathFixups[]=
+{
+ "basepath",
+ "remotebasepath",
+ "entitypath",
+ "texturepath",
+ "autosave",
+ "mapspath"
+};
+
+const int g_nPathFixupCount = sizeof(g_pPathFixups) / sizeof(const char*);
+
+/*
+===========
+QE_LoadProject
+===========
+*/
+qboolean QE_LoadProject (char *projectfile)
+{
+ char *data;
+
+ Sys_Printf ("QE_LoadProject (%s)\n", projectfile);
+
+ if ( LoadFileNoCrash (projectfile, (void **)&data) == -1)
+ return false;
+
+ g_strProject = projectfile;
+
+ CString strData = data;
+ free(data);
+
+ CString strQ2Path = g_PrefsDlg.m_strQuake2;
+ CString strQ2File;
+ ExtractPath_and_Filename(g_PrefsDlg.m_strQuake2, strQ2Path, strQ2File);
+ AddSlash(strQ2Path);
+
+
+ char* pBuff = new char[1024];
+
+ BuildShortPathName(strQ2Path, pBuff, 1024);
+ FindReplace(strData, "__Q2PATH", pBuff);
+ BuildShortPathName(g_strAppPath, pBuff, 1024);
+ FindReplace(strData, "__QERPATH", pBuff);
+
+ char* pFile;
+ if (GetFullPathName(projectfile, 1024, pBuff, &pFile))
+ {
+ g_PrefsDlg.m_strLastProject = pBuff;
+ BuildShortPathName(g_PrefsDlg.m_strLastProject, pBuff, 1024);
+ g_PrefsDlg.m_strLastProject = pBuff;
+ g_PrefsDlg.SavePrefs();
+
+ ExtractPath_and_Filename(pBuff, strQ2Path, strQ2File);
+ int nLen = strQ2Path.GetLength();
+ if (nLen > 0)
+ {
+ if (strQ2Path[nLen - 1] == '\\')
+ strQ2Path.SetAt(nLen-1,'\0');
+ char* pBuffer = strQ2Path.GetBufferSetLength(_MAX_PATH + 1);
+ int n = strQ2Path.ReverseFind('\\');
+ if (n >=0 )
+ pBuffer[n + 1] = '\0';
+ strQ2Path.ReleaseBuffer();
+ FindReplace(strData, "__QEPROJPATH", strQ2Path);
+ }
+ }
+
+
+ StartTokenParsing (strData.GetBuffer(0));
+ g_qeglobals.d_project_entity = Entity_Parse (true);
+ if (!g_qeglobals.d_project_entity)
+ Error ("Couldn't parse %s", projectfile);
+
+ for (int i = 0; i < g_nPathFixupCount; i++)
+ {
+ char *pPath = ValueForKey (g_qeglobals.d_project_entity, g_pPathFixups[i]);
+ if (pPath[0] != '\\' && pPath[0] != '/')
+ {
+ if (GetFullPathName(pPath, 1024, pBuff, &pFile))
+ {
+ SetKeyValue(g_qeglobals.d_project_entity, g_pPathFixups[i], pBuff);
+ }
+ }
+ }
+
+ delete []pBuff;
+
+ // set here some default project settings you need
+ if ( strlen( ValueForKey( g_qeglobals.d_project_entity, "brush_primit" ) ) == 0 )
+ {
+ SetKeyValue( g_qeglobals.d_project_entity, "brush_primit", "0" );
+ }
+
+ g_qeglobals.m_bBrushPrimitMode = IntForKey( g_qeglobals.d_project_entity, "brush_primit" );
+
+
+ Eclass_InitForSourceDirectory (ValueForKey (g_qeglobals.d_project_entity, "entitypath"));
+ FillClassList(); // list in entity window
+
+ Map_New();
+
+
+ FillTextureMenu();
+ FillBSPMenu();
+
+ return true;
+}
+
+/*
+===========
+QE_SaveProject
+===========
+*/
+//extern char *bsp_commands[256];
+
+qboolean QE_SaveProject (const char* pProjectFile)
+{
+ //char filename[1024];
+ FILE *fp;
+ epair_t *ep;
+
+ //sprintf (filename, "%s\\%s.prj", g_projectdir, g_username);
+
+ if (!(fp = fopen (pProjectFile, "w+")))
+ Error ("Could not open project file!");
+
+ fprintf (fp, "{\n");
+ for (ep = g_qeglobals.d_project_entity->epairs; ep; ep=ep->next)
+ fprintf (fp, "\"%s\" \"%s\"\n", ep->key, ep->value);
+ fprintf (fp, "}\n");
+
+ fclose (fp);
+
+ return TRUE;
+}
+
+
+
+/*
+===========
+QE_KeyDown
+===========
+*/
+#define SPEED_MOVE 32
+#define SPEED_TURN 22.5
+
+
+/*
+===============
+ConnectEntities
+
+Sets target / targetname on the two entities selected
+from the first selected to the secon
+===============
+*/
+void ConnectEntities (void)
+{
+ entity_t *e1, *e2, *e;
+ char *target, *tn;
+ int maxtarg, targetnum;
+ char newtarg[32];
+
+ if (g_qeglobals.d_select_count != 2)
+ {
+ Sys_Status ("Must have two brushes selected.", 0);
+ Sys_Beep ();
+ return;
+ }
+
+ e1 = g_qeglobals.d_select_order[0]->owner;
+ e2 = g_qeglobals.d_select_order[1]->owner;
+
+ if (e1 == world_entity || e2 == world_entity)
+ {
+ Sys_Status ("Can't connect to the world.", 0);
+ Sys_Beep ();
+ return;
+ }
+
+ if (e1 == e2)
+ {
+ Sys_Status ("Brushes are from same entity.", 0);
+ Sys_Beep ();
+ return;
+ }
+
+ target = ValueForKey (e1, "target");
+ if (target && target[0])
+ strcpy (newtarg, target);
+ else
+ {
+ target = ValueForKey (e2, "targetname");
+ if (target && target[0])
+ strcpy (newtarg, target);
+ else
+ {
+ // make a unique target value
+ maxtarg = 0;
+ for (e=entities.next ; e != &entities ; e=e->next)
+ {
+ tn = ValueForKey (e, "targetname");
+ if (tn && tn[0])
+ {
+ targetnum = atoi(tn+1);
+ if (targetnum > maxtarg)
+ maxtarg = targetnum;
+ }
+ }
+ sprintf (newtarg, "t%i", maxtarg+1);
+ }
+ }
+
+ SetKeyValue (e1, "target", newtarg);
+ SetKeyValue (e2, "targetname", newtarg);
+ Sys_UpdateWindows (W_XY | W_CAMERA);
+
+ Select_Deselect();
+ Select_Brush (g_qeglobals.d_select_order[1]);
+}
+
+qboolean QE_SingleBrush (bool bQuiet)
+{
+ if ( (selected_brushes.next == &selected_brushes)
+ || (selected_brushes.next->next != &selected_brushes) )
+ {
+ if (!bQuiet)
+ {
+ Sys_Printf ("Error: you must have a single brush selected\n");
+ }
+ return false;
+ }
+ if (selected_brushes.next->owner->eclass->fixedsize)
+ {
+ if (!bQuiet)
+ {
+ Sys_Printf ("Error: you cannot manipulate fixed size entities\n");
+ }
+ return false;
+ }
+
+ return true;
+}
+
+void QE_Init (void)
+{
+ /*
+ ** initialize variables
+ */
+ g_qeglobals.d_gridsize = 8;
+ g_qeglobals.d_showgrid = true;
+
+ /*
+ ** other stuff
+ */
+ Texture_Init (true);
+ //Cam_Init ();
+ //XY_Init ();
+ Z_Init ();
+ Terrain_Init();
+}
+
+void WINAPI QE_ConvertDOSToUnixName( char *dst, const char *src )
+{
+ while ( *src )
+ {
+ if ( *src == '\\' )
+ *dst = '/';
+ else
+ *dst = *src;
+ dst++; src++;
+ }
+ *dst = 0;
+}
+
+int g_numbrushes, g_numentities;
+
+void QE_CountBrushesAndUpdateStatusBar( void )
+{
+ static int s_lastbrushcount, s_lastentitycount;
+ static qboolean s_didonce;
+
+ //entity_t *e;
+ brush_t *b, *next;
+
+ g_numbrushes = 0;
+ g_numentities = 0;
+
+ if ( active_brushes.next != NULL )
+ {
+ for ( b = active_brushes.next ; b != NULL && b != &active_brushes ; b=next)
+ {
+ next = b->next;
+ if (b->brush_faces )
+ {
+ if ( !b->owner->eclass->fixedsize)
+ g_numbrushes++;
+ else
+ g_numentities++;
+ }
+ }
+ }
+/*
+ if ( entities.next != NULL )
+ {
+ for ( e = entities.next ; e != &entities && g_numentities != MAX_MAP_ENTITIES ; e = e->next)
+ {
+ g_numentities++;
+ }
+ }
+*/
+ if ( ( ( g_numbrushes != s_lastbrushcount ) || ( g_numentities != s_lastentitycount ) ) || ( !s_didonce ) )
+ {
+ Sys_UpdateStatusBar();
+
+ s_lastbrushcount = g_numbrushes;
+ s_lastentitycount = g_numentities;
+ s_didonce = true;
+ }
+}
+
+char com_token[1024];
+qboolean com_eof;
+
+/*
+================
+I_FloatTime
+================
+*/
+double I_FloatTime (void)
+{
+ time_t t;
+
+ time (&t);
+
+ return t;
+#if 0
+// more precise, less portable
+ struct timeval tp;
+ struct timezone tzp;
+ static int secbase;
+
+ gettimeofday(&tp, &tzp);
+
+ if (!secbase)
+ {
+ secbase = tp.tv_sec;
+ return tp.tv_usec/1000000.0;
+ }
+
+ return (tp.tv_sec - secbase) + tp.tv_usec/1000000.0;
+#endif
+}
+
+
+/*
+==============
+COM_Parse
+
+Parse a token out of a string
+==============
+*/
+char *COM_Parse (char *data)
+{
+ int c;
+ int len;
+
+ len = 0;
+ com_token[0] = 0;
+
+ if (!data)
+ return NULL;
+
+// skip whitespace
+skipwhite:
+ while ( (c = *data) <= ' ')
+ {
+ if (c == 0)
+ {
+ com_eof = true;
+ return NULL; // end of file;
+ }
+ data++;
+ }
+
+// skip // comments
+ if (c=='/' && data[1] == '/')
+ {
+ while (*data && *data != '\n')
+ data++;
+ goto skipwhite;
+ }
+
+
+// handle quoted strings specially
+ if (c == '\"')
+ {
+ data++;
+ do
+ {
+ c = *data++;
+ if (c=='\"')
+ {
+ com_token[len] = 0;
+ return data;
+ }
+ com_token[len] = c;
+ len++;
+ } while (1);
+ }
+
+// parse single characters
+ if (c=='{' || c=='}'|| c==')'|| c=='(' || c=='\'' || c==':')
+ {
+ com_token[len] = c;
+ len++;
+ com_token[len] = 0;
+ return data+1;
+ }
+
+// parse a regular word
+ do
+ {
+ com_token[len] = c;
+ data++;
+ len++;
+ c = *data;
+ if (c=='{' || c=='}'|| c==')'|| c=='(' || c=='\'' || c==':')
+ break;
+ } while (c>32);
+
+ com_token[len] = 0;
+ return data;
+}
+
+
+
+/*
+=============================================================================
+
+ MISC FUNCTIONS
+
+=============================================================================
+*/
+
+
+int argc;
+char *argv[MAX_NUM_ARGVS];
+
+/*
+============
+ParseCommandLine
+============
+*/
+void ParseCommandLine (char *lpCmdLine)
+{
+ argc = 1;
+ argv[0] = "programname";
+
+ while (*lpCmdLine && (argc < MAX_NUM_ARGVS))
+ {
+ while (*lpCmdLine && ((*lpCmdLine <= 32) || (*lpCmdLine > 126)))
+ lpCmdLine++;
+
+ if (*lpCmdLine)
+ {
+ argv[argc] = lpCmdLine;
+ argc++;
+
+ while (*lpCmdLine && ((*lpCmdLine > 32) && (*lpCmdLine <= 126)))
+ lpCmdLine++;
+
+ if (*lpCmdLine)
+ {
+ *lpCmdLine = 0;
+ lpCmdLine++;
+ }
+
+ }
+ }
+}
+
+
+
+/*
+=================
+CheckParm
+
+Checks for the given parameter in the program's command line arguments
+Returns the argument number (1 to argc-1) or 0 if not present
+=================
+*/
+int CheckParm (char *check)
+{
+ int i;
+
+ for (i = 1;i<argc;i++)
+ {
+ if ( stricmp(check, argv[i]) )
+ return i;
+ }
+
+ return 0;
+}
+
+
+
+
+/*
+==============
+ParseNum / ParseHex
+==============
+*/
+int ParseHex (char *hex)
+{
+ char *str;
+ int num;
+
+ num = 0;
+ str = hex;
+
+ while (*str)
+ {
+ num <<= 4;
+ if (*str >= '0' && *str <= '9')
+ num += *str-'0';
+ else if (*str >= 'a' && *str <= 'f')
+ num += 10 + *str-'a';
+ else if (*str >= 'A' && *str <= 'F')
+ num += 10 + *str-'A';
+ else
+ Error ("Bad hex number: %s",hex);
+ str++;
+ }
+
+ return num;
+}
+
+
+int ParseNum (char *str)
+{
+ if (str[0] == '$')
+ return ParseHex (str+1);
+ if (str[0] == '0' && str[1] == 'x')
+ return ParseHex (str+2);
+ return atol (str);
+}
+
+
diff --git a/q3radiant/QE3.H b/q3radiant/QE3.H
new file mode 100755
index 0000000..8b78119
--- /dev/null
+++ b/q3radiant/QE3.H
@@ -0,0 +1,669 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __QE3_H__
+#define __QE3_H__
+
+// disable data conversion warnings for gl
+#pragma warning(disable : 4244) // MIPS
+#pragma warning(disable : 4136) // X86
+#pragma warning(disable : 4051) // ALPHA
+
+#include <windows.h>
+
+extern "C"
+{
+#include "qgl.h"
+}
+
+#include <math.h>
+#include <stdlib.h>
+#include <malloc.h>
+
+// this define to use HTREEITEM and MFC stuff in the headers
+#define QERTYPES_USE_MFC
+#include "qertypes.h"
+#include "../libs/cmdlib.h"
+#include "mathlib.h"
+#include "parse.h"
+#include "lbmlib.h"
+
+#include <commctrl.h>
+#include "afxres.h"
+#include "resource.h"
+
+#include "qedefs.h"
+
+#include "qfiles.h"
+
+#include "textures.h"
+#include "brush.h"
+#include "entity.h"
+#include "map.h"
+#include "select.h"
+#include "splines/splines.h"
+
+#include "camera.h"
+#include "xy.h"
+#include "z.h"
+#include "mru.h"
+
+#include "undo.h"
+
+#include "terrain.h"
+
+// the dec offsetof macro doesn't work very well...
+#define myoffsetof(type,identifier) ((size_t)&((type *)0)->identifier)
+
+
+// set these before calling CheckParm
+extern int myargc;
+extern char **myargv;
+
+double I_FloatTime (void);
+
+void Error (char *error, ...);
+void Warning (char *error, ...);
+int CheckParm (char *check);
+void ParseCommandLine (char *lpCmdLine);
+
+
+int ParseNum (char *str);
+
+
+char *COM_Parse (char *data);
+
+extern char com_token[1024];
+extern qboolean com_eof;
+
+#define MAX_NUM_ARGVS 32
+extern int argc;
+extern char *argv[MAX_NUM_ARGVS];
+
+
+typedef struct
+{
+ int p1, p2;
+ face_t *f1, *f2;
+} pedge_t;
+
+typedef struct
+{
+ int iSize;
+ int iTexMenu; // nearest, linear, etc
+ float fGamma; // gamma for textures
+ char szProject[256]; // last project loaded
+ vec3_t colors[COLOR_LAST];
+ qboolean show_names;
+ qboolean show_coordinates;
+ int exclude;
+ int m_nTextureTweak;
+} SavedInfo_t;
+
+//
+// system functions
+//
+// TTimo NOTE: WINAPI funcs can be accessed by plugins
+void Sys_UpdateStatusBar( void );
+void WINAPI Sys_UpdateWindows (int bits);
+void Sys_Beep (void);
+void Sys_ClearPrintf (void);
+void Sys_Printf (char *text, ...);
+double Sys_DoubleTime (void);
+void Sys_GetCursorPos (int *x, int *y);
+void Sys_SetCursorPos (int x, int y);
+void Sys_SetTitle (char *text);
+void Sys_BeginWait (void);
+void Sys_EndWait (void);
+void Sys_Status(const char *psz, int part);
+
+/*
+** most of the QE globals are stored in this structure
+*/
+typedef struct
+{
+ qboolean d_showgrid;
+ int d_gridsize;
+
+ int d_num_entities;
+
+ entity_t *d_project_entity;
+
+ float d_new_brush_bottom_z,
+ d_new_brush_top_z;
+
+ HINSTANCE d_hInstance;
+
+ HGLRC d_hglrcBase;
+ HDC d_hdcBase;
+
+ HWND d_hwndMain;
+ HWND d_hwndCamera;
+ HWND d_hwndEdit;
+ HWND d_hwndEntity;
+ HWND d_hwndTexture;
+ HWND d_hwndXY;
+ HWND d_hwndZ;
+ HWND d_hwndStatus;
+ HWND d_hwndGroup;
+ HWND d_hwndMedia;
+
+ vec3_t d_points[MAX_POINTS];
+ int d_numpoints;
+ pedge_t d_edges[MAX_EDGES];
+ int d_numedges;
+
+ // terrain variables
+ float d_terrainBrushSize;
+ terrainnoise_t d_terrainNoiseType;
+ terrainfalloff_t d_terrainFalloff;
+ terrainbrush_t d_terrainBrush;
+ int d_terrainWidth;
+ int d_terrainHeight;
+
+ terrainVert_t *d_terrapoints[MAX_TERRA_POINTS];
+ int d_numterrapoints;
+
+
+ int d_num_move_points;
+ float *d_move_points[4096];
+
+ qtexture_t *d_qtextures;
+
+ texturewin_t d_texturewin;
+
+ int d_pointfile_display_list;
+
+ xy_t d_xyOld;
+
+ LPMRUMENU d_lpMruMenu;
+
+ SavedInfo_t d_savedinfo;
+
+ int d_workcount;
+
+ // connect entities uses the last two brushes selected
+ int d_select_count;
+ brush_t *d_select_order[2];
+ vec3_t d_select_translate; // for dragging w/o making new display lists
+ select_t d_select_mode;
+ idPointListInterface *selectObject; //
+
+ int d_font_list;
+
+ int d_parsed_brushes;
+
+ qboolean show_blocks;
+
+ // Timo
+ // tells if we are internally using brush primitive (texture coordinates and map format)
+ // this is a shortcut for IntForKey( g_qeglobals.d_project_entity, "brush_primit" )
+ // NOTE: must keep the two ones in sync
+ BOOL m_bBrushPrimitMode;
+
+ // used while importing brush data from file or memory buffer
+ // tells if conversion between map format and internal preferences ( m_bBrushPrimitMode ) is needed
+ qboolean bNeedConvert;
+ qboolean bOldBrushes;
+ qboolean bPrimitBrushes;
+
+ vec3_t d_vAreaTL;
+ vec3_t d_vAreaBR;
+
+ // tells if we are using .INI files for prefs instead of registry
+ qboolean use_ini;
+ // even in .INI mode we use the registry for all void* prefs
+ char use_ini_registry[64];
+
+ //Timo
+ // tells we have surface properties plugin
+ qboolean bSurfacePropertiesPlugin;
+ // tells we are using a BSP frontend plugin
+ qboolean bBSPFrontendPlugin;
+
+ qboolean dontDrawSelectedOutlines;
+
+} QEGlobals_t;
+
+//void *qmalloc (size_t size);
+char *copystring (char *s);
+char *ExpandReletivePath (char *p);
+
+void Pointfile_Delete (void);
+void WINAPI Pointfile_Check (void);
+void Pointfile_Next (void);
+void Pointfile_Prev (void);
+void Pointfile_Clear (void);
+void Pointfile_Draw( void );
+void Pointfile_Load( void );
+
+//
+// drag.c
+//
+void Drag_Begin (int x, int y, int buttons,
+ vec3_t xaxis, vec3_t yaxis,
+ vec3_t origin, vec3_t dir);
+void Drag_MouseMoved (int x, int y, int buttons);
+void Drag_MouseUp (int nButtons = 0);
+
+//
+// csg.c
+//
+void CSG_MakeHollow (void);
+void CSG_Subtract (void);
+void CSG_Merge (void);
+
+//
+// vertsel.c
+//
+
+void SetupVertexSelection (void);
+void SelectEdgeByRay (vec3_t org, vec3_t dir);
+void SelectVertexByRay (vec3_t org, vec3_t dir);
+
+void ConnectEntities (void);
+
+extern int update_bits;
+
+extern int screen_width;
+extern int screen_height;
+
+extern HANDLE bsp_process;
+extern HANDLE g_hBSPOutput;
+extern HANDLE g_hBSPInput;
+
+
+char *TranslateString (char *buf);
+
+void ProjectDialog (void);
+
+void FillTextureMenu (CStringArray* pArray = NULL);
+void FillBSPMenu (void);
+
+BOOL CALLBACK Win_Dialog (
+ HWND hwndDlg, // handle to dialog box
+ UINT uMsg, // message
+ WPARAM wParam, // first message parameter
+ LPARAM lParam // second message parameter
+);
+
+
+//
+// win_cam.c
+//
+void WCam_Create (HINSTANCE hInstance);
+
+
+//
+// win_xy.c
+//
+void WXY_Create (HINSTANCE hInstance);
+
+//
+// win_z.c
+//
+void WZ_Create (HINSTANCE hInstance);
+
+//
+// win_ent.c
+//
+
+
+//
+// win_main.c
+//
+void Main_Create (HINSTANCE hInstance);
+extern BOOL SaveWindowState(HWND hWnd, const char *pszName);
+extern BOOL LoadWindowState(HWND hWnd, const char *pszName);
+
+extern BOOL SaveRegistryInfo(const char *pszName, void *pvBuf, long lSize);
+extern BOOL LoadRegistryInfo(const char *pszName, void *pvBuf, long *plSize);
+
+//
+// entityw.c
+//
+BOOL CreateEntityWindow(HINSTANCE hInstance);
+void FillClassList (void);
+BOOL UpdateEntitySel(eclass_t *pec);
+void SetInspectorMode(int iType);
+int DrawTexControls(HWND hWnd);
+void SetSpawnFlags(void);
+void GetSpawnFlags(void);
+void SetKeyValuePairs(bool bClearMD3 = false);
+extern void BuildGammaTable(float g);
+BOOL GetSelectAllCriteria(CString &strKey, CString &strVal);
+
+
+// win_dlg.c
+
+void DoGamma(void);
+void DoFind(void);
+void DoRotate(void);
+void DoSides(bool bCone = false, bool bSphere = false, bool bTorus = false);
+void DoAbout(void);
+void DoSurface();
+
+/*
+** QE function declarations
+*/
+void QE_CheckAutoSave( void );
+void WINAPI QE_ConvertDOSToUnixName( char *dst, const char *src );
+void QE_CountBrushesAndUpdateStatusBar( void );
+void WINAPI QE_CheckOpenGLForErrors(void);
+void QE_ExpandBspString (char *bspaction, char *out, char *mapname, bool useTemps);
+void QE_Init (void);
+qboolean QE_KeyDown (int key, int nFlags = 0);
+qboolean QE_LoadProject (char *projectfile);
+qboolean QE_SingleBrush (bool bQuiet = false);
+
+
+// sys stuff
+void Sys_MarkMapModified (void);
+
+/*
+** QE Win32 function declarations
+*/
+int WINAPI QEW_SetupPixelFormat(HDC hDC, qboolean zbuffer );
+void QEW_StopGL( HWND hWnd, HGLRC hGLRC, HDC hDC );
+
+/*
+** extern declarations
+*/
+extern QEGlobals_t g_qeglobals;
+
+//++timo clean (moved into qertypes.h)
+//enum VIEWTYPE {YZ, XZ, XY};
+qboolean IsBrushSelected(brush_t* bSel);
+
+// curve brushes
+
+void Curve_MakeCurvedBrush (qboolean negative, qboolean top, qboolean bottom,
+ qboolean s1, qboolean s2, qboolean s3, qboolean s4);
+
+void Curve_Invert (void);
+
+void Curve_AddFakePlanes( brush_t *B );
+void Curve_StripFakePlanes( brush_t *B );
+void Curve_BuildPoints (brush_t *b);
+void Curve_XYDraw (brush_t *b);
+void Curve_CameraDraw (brush_t *b);
+
+void Curve_WriteFile (char *name);
+
+
+// patch stuff
+
+extern bool g_bSameView;
+extern int g_nPatchClickedView;
+bool within(vec3_t vTest, vec3_t vTL, vec3_t vBR);
+
+void Brush_RebuildBrush(brush_t *b, vec3_t vMins, vec3_t vMaxs );
+patchMesh_t* MakeNewPatch();
+brush_t* AddBrushForPatch(patchMesh_t *pm, bool bLinkToWorld = true);
+brush_t* Patch_GenericMesh(int nWidth, int nHeight, int nOrientation = 2, bool bDeleteSource = true, bool bOverride = false);
+void Patch_ReadFile (char *name);
+void Patch_WriteFile (char *name);
+void Patch_BuildPoints (brush_t *b);
+void Patch_Move(patchMesh_t *p, const vec3_t vMove, bool bRebuild = false);
+//++timo had to add a default value for bSnap (see Patch_ApplyMatrix call from Select_ApplyMatrix in select.cpp)
+void Patch_ApplyMatrix(patchMesh_t *p, const vec3_t vOrigin, const vec3_t vMatrix[3], bool bSnap = false);
+void Patch_EditPatch();
+void Patch_Deselect();
+void Patch_Deselect(patchMesh_t *p);
+void Patch_Delete(patchMesh_t *p);
+int Patch_MemorySize(patchMesh_t *p);
+void Patch_Select(patchMesh_t *p);
+void Patch_Scale(patchMesh_t *p, const vec3_t vOrigin, const vec3_t vAmt, bool bRebuilt = true);
+void Patch_Cleanup();
+void Patch_SetView(int n);
+void Patch_SetTexture(patchMesh_t *p, texdef_t *tex_def, IPluginTexdef* pPlugTexdef = NULL);
+void Patch_BrushToMesh(bool bCone = false, bool bBevel = false, bool bEndcap = false, bool bSquare = false, int nHeight = 3);
+bool Patch_DragScale(patchMesh_t *p, vec3_t vAmt, vec3_t vMove);
+void Patch_ReadBuffer(char* pBuff, bool bSelect = false);
+void Patch_WriteFile (CMemFile* pMemFile);
+void Patch_UpdateSelected(vec3_t vMove);
+void Patch_AddRow(patchMesh_t *p);
+brush_t* Patch_Parse(bool bOld);
+void Patch_Write (patchMesh_t *p, FILE *f);
+void Patch_Write (patchMesh_t *p, CMemFile *file);
+void Patch_AdjustColumns(patchMesh_t *p, int nCols);
+void Patch_AdjustRows(patchMesh_t *p, int nRows);
+void Patch_AdjustSelected(bool bInsert, bool bColumn, bool bFlag);
+patchMesh_t* Patch_Duplicate(patchMesh_t *pFrom);
+void Patch_RotateTexture(patchMesh_t *p, float fAngle);
+void Patch_ScaleTexture(patchMesh_t *p, float fx, float fy, bool bFixup = true);
+void Patch_ShiftTexture(patchMesh_t *p, float fx, float fy);
+void Patch_DrawCam(patchMesh_t *p);
+void Patch_DrawXY(patchMesh_t *p);
+void Patch_InsertColumn(patchMesh_t *p, bool bAdd);
+void Patch_InsertRow(patchMesh_t *p, bool bAdd);
+void Patch_RemoveRow(patchMesh_t *p, bool bFirst);
+void Patch_RemoveColumn(patchMesh_t *p, bool bFirst);
+void Patch_ToggleInverted();
+void Patch_Restore(patchMesh_t *p);
+void Patch_Save(patchMesh_t *p);
+void Patch_SetTextureInfo(texdef_t* pt);
+void Patch_NaturalTexturing();
+void Patch_ResetTexturing(float fx, float fy);
+void Patch_FitTexturing();
+void Patch_BendToggle();
+void Patch_StartInsDel();
+void Patch_BendHandleTAB();
+void Patch_BendHandleENTER();
+void Patch_SelectBendNormal();
+void Patch_SelectBendAxis();
+bool WINAPI OnlyPatchesSelected();
+bool WINAPI AnyPatchesSelected();
+patchMesh_t* SinglePatchSelected();
+void Patch_CapCurrent(bool bInvertedBevel = false, bool bInvertedEndcap = false);
+void Patch_DisperseRows();
+void Patch_DisperseColumns();
+void Patch_NaturalizeSelected(bool bCap = false, bool bCycleCap = false);
+void Patch_SelectAreaPoints();
+void Patch_InvertTexture(bool bY);
+void Patch_InsDelToggle();
+void Patch_InsDelHandleTAB();
+void Patch_InsDelHandleENTER();
+void Patch_SetOverlays();
+void Patch_ClearOverlays();
+void Patch_Thicken(int nAmount, bool bSeam);
+void Patch_Transpose();
+void Patch_Freeze();
+void Patch_UnFreeze(bool bAll);
+const char* Patch_GetTextureName();
+void Patch_FindReplaceTexture(brush_t *pb, const char *pFind, const char *pReplace, bool bForce);
+void Patch_ReplaceQTexture(brush_t *pb, qtexture_t *pOld, qtexture_t *pNew);
+void Select_SnapToGrid();
+extern bool g_bPatchShowBounds;
+extern bool g_bPatchWireFrame;
+extern bool g_bPatchWeld;
+extern bool g_bPatchDrillDown;
+extern bool g_bPatchInsertMode;
+extern bool g_bPatchBendMode;
+extern vec3_t g_vBendOrigin;
+void Patch_FromTriangle(vec5_t vx, vec5_t vy, vec5_t vz);
+const char* Patch_GetKeyValue(patchMesh_t *p, const char *pKey);
+void Patch_SetEpair(patchMesh_t *p, const char *pKey, const char *pValue);
+
+
+
+// group stuff
+// group_t are loaded / saved through "group_info" entities
+// they hold epairs for group settings and additionnal access info (tree nodes)
+typedef struct group_s
+{
+ struct group_s *next;
+ epair_t *epairs;
+ HTREEITEM itemOwner;
+} group_t;
+
+// NOTES: grouping only enabled in brush primitives mode
+// grouping works by naming brushes and setting display properties
+// the group hierarchy is not related with the map hierarchy (entity list, brushes etc.)
+// brushes with no group are under the "world" node (default for all brushes)
+// void Group_GetListFromWorld(CStringArray *pArray);
+void Group_RemoveListFromWorld();
+// void Group_SetListToWorld(CStringArray *pArray);
+// void Group_BuildTree(CTreeCtrl *pTree);
+// void Group_DecomposeTree(CTreeCtrl *pTree);
+// save group_t as "classname" "group_info" things
+void Group_Save(FILE *f);
+// clean the brushes ownerItem, clean the treeview and rebuild everything
+// is usually called when loading a new map, but may be called anytime
+void Group_Init();
+void Group_Add(entity_t *e);
+
+// remove a brush from it's current group, will erase the "group" epair if any, and delete the tree control node
+void Group_RemoveBrush(brush_t *b);
+void Group_AddToWorld(brush_t *b);
+// will remove brush of it's current group if any, and will add it wherever needed according to it's "group" key
+void Group_AddToProperGroup(brush_t *b);
+void Group_AddToSelected(brush_t *b);
+// allocate a new group, set name
+group_t* Group_Alloc(const char *name);
+// we use entities to store information about the groups
+// these entities are not linked into the world, and they have no brushes
+// only loaded / saved in map file
+group_t* Group_ForName(const char *name);
+
+// Timo
+// new brush primitive stuff
+void ComputeAxisBase(vec3_t normal,vec3_t texS,vec3_t texT );
+void FaceToBrushPrimitFace(face_t *f);
+void EmitBrushPrimitTextureCoordinates(face_t *, winding_t *);
+// EmitTextureCoordinates, is old code used for brush to brush primitive conversion
+void EmitTextureCoordinates ( float *xyzst, qtexture_t *q, face_t *f);
+void BrushPrimit_Parse(brush_t *);
+// compute a fake shift scale rot representation from the texture matrix
+void TexMatToFakeTexCoords( vec_t texMat[2][3], float shift[2], float *rot, float scale[2] );
+void FakeTexCoordsToTexMat( float shift[2], float rot, float scale[2], vec_t texMat[2][3] );
+void ConvertTexMatWithQTexture( brushprimit_texdef_t *texMat1, qtexture_t *qtex1, brushprimit_texdef_t *texMat2, qtexture_t *qtex2 );
+// texture locking
+void Face_MoveTexture_BrushPrimit(face_t *f, vec3_t delta);
+void Select_ShiftTexture_BrushPrimit( face_t *f, int x, int y );
+void RotateFaceTexture_BrushPrimit(face_t *f, int nAxis, float fDeg, vec3_t vOrigin );
+// used in CCamWnd::ShiftTexture_BrushPrimit
+void ComputeBest2DVector( vec3_t v, vec3_t X, vec3_t Y, int &x, int &y );
+
+
+//
+// eclass.cpp
+//
+extern qboolean parsing_single;
+extern qboolean eclass_found;
+extern eclass_t *eclass_e;
+void Eclass_ScanFile( char *filename );
+
+// for interfaces, we require main plugin header included
+#include "qerplugin.h"
+
+//
+// SurfaceDlg.cpp and surface properties plugin
+//
+//++timo some patch in/out stuff is in there, needs to be moved out in a dedicated interface
+void WINAPI Patch_Rebuild(patchMesh_t *p);
+#include "isurfaceplugin.h"
+extern _QERPlugSurfaceTable g_SurfaceTable;
+
+//
+// OpenGL interface
+//
+#include "igl.h"
+HGLRC WINAPI QERApp_GetQeglobalsHGLRC();
+void WINAPI QERApp_HookXYGLWindow(IGLWindow* pGLW);
+void WINAPI QERApp_UnHookGLWindow(IGLWindow* pGLW);
+void DrawPluginEntities( VIEWTYPE vt );
+
+//
+// ISelectedFace interface
+//
+#include "ISelectedFace.h"
+int WINAPI QERApp_ISelectedFace_GetTextureNumber();
+int WINAPI QERApp_GetFaceInfo(_QERFaceData *pFaceData, winding_t *pWinding);
+int WINAPI QERApp_SetFaceInfo(_QERFaceData *pFaceData);
+void WINAPI QERApp_GetTextureSize( int Size[2] );
+
+//
+// IEpairs interface
+//
+#include "IEpairs.h"
+#include "EpairsWrapper.h"
+
+//
+// IPluginEntities interface
+//
+#include "IPluginEntities.h"
+int WINAPI QERApp_EClassScanDir( char *dir, HMODULE plugID );
+
+//
+// ShaderInfo.cpp
+//
+#include "ShaderInfo.h"
+
+//
+// TexWnd.cpp
+//
+CShaderInfo* hasShader(const char *pName);
+
+//
+// IScripLib interface
+// GetToken, UnGetToken, etc.
+#include "IScriplib.h"
+extern FILE *g_File;
+void WINAPI QERApp_MapPrintf_FILE( char *text, ... );
+
+//
+// ISurfacePlugin interface
+//
+void WINAPI QERApp_GetTwoSelectedPatch( patchMesh_t **p1, patchMesh_t **p2 );
+
+//
+// IBSPFrontend interface
+//
+#include "IBSPFrontend.h"
+extern _QERPlugBSPFrontendTable g_BSPFrontendTable;
+extern CStringArray g_BSPFrontendCommands;
+
+//
+// IMessaging interface
+#include "IMessaging.h"
+#include "Messaging.h"
+void WINAPI QERApp_HookWindow(IWindowListener* pListen);
+void WINAPI QERApp_UnHookWindow(IWindowListener* pListen);
+IXYWndWrapper* WINAPI QERApp_GetXYWndWrapper();
+void WINAPI QERApp_HookListener(IListener* pListen, int Msg);
+int WINAPI QERApp_UnHookListener(IListener* pListen);
+void DispatchRadiantMsg( int Msg );
+// dispatch for IWindowListener entities
+void DispatchOnMouseMove(UINT nFlags, int x, int y);
+bool DispatchOnLButtonDown(UINT nFlags, int x, int y);
+bool DispatchOnLButtonUp(UINT nFlags, int x, int y);
+
+//
+// IShaders interface
+CShaderInfo* SetNameShaderInfo(qtexture_t* q, const char* pPath, const char* pName);
+qtexture_t* Texture_LoadTGATexture (unsigned char* pPixels, int nWidth, int nHeight, char* pPath, int nFlags, int nContents, int nValue );
+#include "IShaders.h"
+qtexture_t* WINAPI QERApp_TryTextureForName(const char* name);
+
+
+
+#endif
diff --git a/q3radiant/QEDEFS.H b/q3radiant/QEDEFS.H
new file mode 100755
index 0000000..355787d
--- /dev/null
+++ b/q3radiant/QEDEFS.H
@@ -0,0 +1,164 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __QEDEFS_H__
+#define __QEDEFS_H__
+
+#define QE_VERSION 0x0501
+
+#define QE3_STYLE (WS_OVERLAPPED | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_THICKFRAME | WS_CAPTION | WS_SYSMENU | WS_CHILD)
+#define QE3_STYLE2 (WS_OVERLAPPED | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_MINIMIZEBOX | WS_THICKFRAME | WS_CAPTION | WS_SYSMENU)
+#define QE3_CHILDSTYLE (WS_OVERLAPPED | WS_MINIMIZEBOX | WS_THICKFRAME | WS_CAPTION | WS_VISIBLE | WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_MAXIMIZEBOX)
+
+#define QE3_SPLITTER_STYLE (WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS)
+
+
+
+#define QE_AUTOSAVE_INTERVAL 5 // number of minutes between autosaves
+
+#define _3DFXCAMERA_WINDOW_CLASS "Q3DFXCamera"
+#define CAMERA_WINDOW_CLASS "QCamera"
+#define XY_WINDOW_CLASS "QXY"
+#define Z_WINDOW_CLASS "QZ"
+#define ENT_WINDOW_CLASS "QENT"
+#define TEXTURE_WINDOW_CLASS "QTEX"
+
+#define ZWIN_WIDTH 40
+#define CWIN_SIZE (0.4)
+
+#define MAX_EDGES 512
+//#define MAX_POINTS 1024
+#define MAX_POINTS 2048
+
+#define MAX_TERRA_POINTS 4096
+
+#define CMD_TEXTUREWAD 60000
+#define CMD_BSPCOMMAND 61000
+
+#define PITCH 0
+#define YAW 1
+#define ROLL 2
+
+#define QE_TIMER0 1
+
+#define PLANE_X 0
+#define PLANE_Y 1
+#define PLANE_Z 2
+#define PLANE_ANYX 3
+#define PLANE_ANYY 4
+#define PLANE_ANYZ 5
+
+#define ON_EPSILON 0.01
+
+#define KEY_FORWARD 1
+#define KEY_BACK 2
+#define KEY_TURNLEFT 4
+#define KEY_TURNRIGHT 8
+#define KEY_LEFT 16
+#define KEY_RIGHT 32
+#define KEY_LOOKUP 64
+#define KEY_LOOKDOWN 128
+#define KEY_UP 256
+#define KEY_DOWN 512
+
+// xy.c
+#define EXCLUDE_LIGHTS 0x01
+#define EXCLUDE_ENT 0x02
+#define EXCLUDE_PATHS 0x04
+#define EXCLUDE_WATER 0x08
+#define EXCLUDE_WORLD 0x10
+#define EXCLUDE_CLIP 0x20
+#define EXCLUDE_DETAIL 0x40
+#define EXCLUDE_CURVES 0x80
+#define INCLUDE_EASY 0x100
+#define INCLUDE_NORMAL 0x200
+#define INCLUDE_HARD 0x400
+#define INCLUDE_DEATHMATCH 0x800
+#define EXCLUDE_HINT 0x1000
+#define EXCLUDE_CAULK 0x2000
+#define EXCLUDE_ANGLES 0x4000
+#define EXCLUDE_TERRAIN 0x8000
+
+
+//
+// menu indexes for modifying menus
+//
+#define MENU_VIEW 2
+#define MENU_BSP 4
+#define MENU_TEXTURE 6
+#define MENU_PLUGIN 11
+
+
+// odd things not in windows header...
+#define VK_COMMA 188
+#define VK_PERIOD 190
+
+/*
+** window bits
+*/
+//++timo moved to qertypes.h
+// clean
+/*
+#define W_CAMERA 0x0001
+#define W_XY 0x0002
+#define W_XY_OVERLAY 0x0004
+#define W_Z 0x0008
+#define W_TEXTURE 0x0010
+#define W_Z_OVERLAY 0x0020
+#define W_CONSOLE 0x0040
+#define W_ENTITY 0x0080
+#define W_CAMERA_IFON 0x0100
+#define W_XZ 0x0200 //--| only used for patch vertex manip stuff
+#define W_YZ 0x0400 //--|
+#define W_ALL 0xFFFFFFFF
+*/
+
+#define COLOR_TEXTUREBACK 0
+#define COLOR_GRIDBACK 1
+#define COLOR_GRIDMINOR 2
+#define COLOR_GRIDMAJOR 3
+#define COLOR_CAMERABACK 4
+#define COLOR_ENTITY 5
+#define COLOR_GRIDBLOCK 6
+#define COLOR_GRIDTEXT 7
+#define COLOR_BRUSHES 8
+#define COLOR_SELBRUSHES 9
+#define COLOR_CLIPPER 10
+#define COLOR_VIEWNAME 11
+#define COLOR_LAST 12
+
+// classes
+#define ENTITY_WIREFRAME 0x00001
+#define ENTITY_SKIN_MODEL 0x00010
+#define ENTITY_SELECTED_ONLY 0x00100
+#define ENTITY_BOXED 0x01000
+
+// menu settings
+#define ENTITY_BOX 0x01000
+#define ENTITY_WIRE 0x00001
+#define ENTITY_SELECTED 0x00101
+#define ENTITY_SKINNED 0x00010
+#define ENTITY_SKINNED_BOXED 0x01010
+#define ENTITY_SELECTED_SKIN 0x00110
+
+
+
+#endif
diff --git a/q3radiant/QERTYPES.H b/q3radiant/QERTYPES.H
new file mode 100755
index 0000000..eeb99c1
--- /dev/null
+++ b/q3radiant/QERTYPES.H
@@ -0,0 +1,454 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// qertypes.h
+//
+// common types
+// merged from brush.h, etc. for plugin support
+//
+#ifndef _QERTYPE_H
+#define _QERTYPE_H
+
+#ifndef __BYTEBOOL__
+#define __BYTEBOOL__
+typedef boolean qboolean;
+//typedef unsigned char byte;
+#endif
+
+#define MAXPOINTS 16
+
+typedef float vec_t;
+typedef vec_t vec2_t[2];
+typedef vec_t vec3_t[3];
+
+#include "splines/math_vector.h"
+
+#ifndef M_PI
+#define M_PI 3.14159265358979323846 // matches value in gcc v2 math.h
+#endif
+
+class texdef_t
+{
+public:
+ texdef_t()
+ {
+ name = new char[1];
+ name[0] = '\0';
+ }
+ ~texdef_t()
+ {
+ delete []name;
+ name = NULL;
+ }
+
+ const char *Name( void )
+ {
+ if ( name ) {
+ return name;
+ }
+
+ return "";
+ }
+
+ void SetName(const char *p)
+ {
+ if (name)
+ {
+ delete []name;
+ }
+ if (p)
+ {
+ name = strcpy(new char[strlen(p)+1], p);
+ }
+ else
+ {
+ name = new char[1];
+ name[0] = '\0';
+ }
+ }
+
+ texdef_t& operator =(const texdef_t& rhs)
+ {
+ if (&rhs != this)
+ {
+ SetName(rhs.name);
+ shift[0] = rhs.shift[0];
+ shift[1] = rhs.shift[1];
+ rotate = rhs.rotate;
+ scale[0] = rhs.scale[0];
+ scale[1] = rhs.scale[1];
+ contents = rhs.contents;
+ flags = rhs.flags;
+ value = rhs.value;
+ }
+ return *this;
+ }
+ //char name[128];
+ char *name;
+ float shift[2];
+ float rotate;
+ float scale[2];
+ int contents;
+ int flags;
+ int value;
+};
+
+// Timo
+// new brush primitive texdef
+typedef struct brushprimit_texdef_s
+{
+ vec_t coords[2][3];
+} brushprimit_texdef_t;
+
+class texturewin_t
+{
+public:
+ texturewin_t()
+ {
+ }
+ ~texturewin_t()
+ {
+ }
+ int width, height;
+ int originy;
+ // add brushprimit_texdef_t for brush primitive coordinates storage
+ brushprimit_texdef_t brushprimit_texdef;
+ int m_nTotalHeight;
+ // surface plugin, must be casted to a IPluginTexdef*
+ void* pTexdef;
+ texdef_t texdef;
+};
+
+#define QER_TRANS 0x00000001
+#define QER_NOCARVE 0x00000002
+
+typedef struct qtexture_s
+{
+ struct qtexture_s *next;
+ char name[64]; // includes partial directory and extension
+ int width, height;
+ int contents;
+ int flags;
+ int value;
+ int texture_number; // gl bind number
+
+ // name of the .shader file
+ char shadername[1024]; // old shader stuff
+ qboolean bFromShader; // created from a shader
+ float fTrans; // amount of transparency
+ int nShaderFlags; // qer_ shader flags
+ vec3_t color; // for flat shade mode
+ qboolean inuse; // true = is present on the level
+
+ // cast this one to an IPluginQTexture if you are using it
+ // NOTE: casting can be done with a GETPLUGINQTEXTURE defined in isurfaceplugin.h
+ // TODO: if the __ISURFACEPLUGIN_H_ header is used, use a union { void *pData; IPluginQTexture *pPluginQTexture } kind of thing ?
+ void *pData;
+
+ //++timo FIXME: this is the actual filename of the texture
+ // this will be removed after shader code cleanup
+ char filename[64];
+
+} qtexture_t;
+
+// NOTE: don't trust this definition!
+// you should read float points[..][5]
+// see NewWinding definition
+#define MAX_POINTS_ON_WINDING 64
+typedef struct
+{
+ int numpoints;
+ int maxpoints;
+ float points[8][5]; // variable sized
+} winding_t;
+
+typedef struct
+{
+ vec3_t normal;
+ double dist;
+ int type;
+} plane_t;
+
+//++timo texdef and brushprimit_texdef are static
+// TODO : do dynamic ?
+typedef struct face_s
+{
+ struct face_s *next;
+ struct face_s *original; //used for vertex movement
+ vec3_t planepts[3];
+ texdef_t texdef;
+ plane_t plane;
+
+ winding_t *face_winding;
+
+ vec3_t d_color;
+ qtexture_t *d_texture;
+
+ // Timo new brush primit texdef
+ brushprimit_texdef_t brushprimit_texdef;
+
+ // cast this one to an IPluginTexdef if you are using it
+ // NOTE: casting can be done with a GETPLUGINTEXDEF defined in isurfaceplugin.h
+ // TODO: if the __ISURFACEPLUGIN_H_ header is used, use a union { void *pData; IPluginTexdef *pPluginTexdef } kind of thing ?
+ void *pData;
+} face_t;
+
+typedef struct {
+ vec3_t xyz;
+ float sideST[2];
+ float capST[2];
+} curveVertex_t;
+
+typedef struct {
+ curveVertex_t v[2];
+} sideVertex_t;
+
+
+#define MIN_PATCH_WIDTH 3
+#define MIN_PATCH_HEIGHT 3
+
+#define MAX_PATCH_WIDTH 16
+#define MAX_PATCH_HEIGHT 16
+
+// patch type info
+// type in lower 16 bits, flags in upper
+// endcaps directly follow this patch in the list
+
+// types
+#define PATCH_GENERIC 0x00000000 // generic flat patch
+#define PATCH_CYLINDER 0x00000001 // cylinder
+#define PATCH_BEVEL 0x00000002 // bevel
+#define PATCH_ENDCAP 0x00000004 // endcap
+#define PATCH_HEMISPHERE 0x00000008 // hemisphere
+#define PATCH_CONE 0x00000010 // cone
+#define PATCH_TRIANGLE 0x00000020 // simple tri, assumes 3x3 patch
+
+// behaviour styles
+#define PATCH_CAP 0x00001000 // flat patch applied as a cap
+#define PATCH_SEAM 0x00002000 // flat patch applied as a seam
+#define PATCH_THICK 0x00004000 // patch applied as a thick portion
+
+// styles
+#define PATCH_BEZIER 0x00000000 // default bezier
+#define PATCH_BSPLINE 0x10000000 // bspline
+
+#define PATCH_TYPEMASK 0x00000fff //
+#define PATCH_BTYPEMASK 0x0000f000 //
+#define PATCH_STYLEMASK 0xffff0000 //
+
+typedef struct {
+ vec3_t xyz;
+ float st[2];
+ float lightmap[2];
+ vec3_t normal;
+} drawVert_t;
+
+// used in brush primitive AND entities
+typedef struct epair_s
+{
+ struct epair_s *next;
+ char *key;
+ char *value;
+} epair_t;
+
+struct brush_s;
+typedef struct brush_s brush_t;
+
+typedef struct {
+ int width, height; // in control points, not patches
+ int contents, flags, value, type;
+ qtexture_t *d_texture;
+ drawVert_t ctrl[MAX_PATCH_WIDTH][MAX_PATCH_HEIGHT];
+ brush_t *pSymbiot;
+ qboolean bSelected;
+ qboolean bOverlay;
+ qboolean bDirty;
+ int nListID;
+ epair_t *epairs;
+ // cast this one to an IPluginTexdef if you are using it
+ // NOTE: casting can be done with a GETPLUGINTEXDEF defined in isurfaceplugin.h
+ // TODO: if the __ISURFACEPLUGIN_H_ header is used, use a union { void *pData; IPluginTexdef *pPluginTexdef } kind of thing ?
+ void *pData;
+} patchMesh_t;
+
+typedef struct {
+ int index;
+ qtexture_t *texture;
+ texdef_t texdef;
+} terrainFace_t;
+
+typedef struct {
+ float height;
+ float scale;
+ terrainFace_t tri;
+ vec4_t rgba;
+ vec3_t normal;
+ vec3_t xyz;
+} terrainVert_t;
+
+#define MAX_TERRAIN_TEXTURES 128
+typedef struct {
+ int width, height;
+
+ vec3_t mins, maxs;
+ vec3_t origin;
+ float scale_x;
+ float scale_y;
+
+ int numtextures;
+ qtexture_t *textures[ MAX_TERRAIN_TEXTURES ];
+
+ terrainVert_t *heightmap; // width * height
+
+ epair_t *epairs;
+
+ brush_s *pSymbiot;
+ bool bSelected;
+ bool bDirty;
+ int nListID;
+} terrainMesh_t;
+
+typedef struct brush_s
+{
+ struct brush_s *prev, *next; // links in active/selected
+ struct brush_s *oprev, *onext; // links in entity
+ struct entity_s *owner;
+ vec3_t mins, maxs;
+ face_t *brush_faces;
+
+ qboolean bModelFailed;
+ //
+ // curve brush extensions
+ // all are derived from brush_faces
+ qboolean patchBrush;
+ qboolean hiddenBrush;
+ qboolean terrainBrush;
+
+ //int nPatchID;
+
+ patchMesh_t *pPatch;
+ terrainMesh_t *pTerrain;
+
+ struct entity_s *pUndoOwner;
+
+ int undoId; //undo ID
+ int redoId; //redo ID
+ int ownerId; //entityId of the owner entity for undo
+
+ // TTimo: HTREEITEM is MFC, some plugins really don't like it
+#ifdef QERTYPES_USE_MFC
+ int numberId; // brush number
+ HTREEITEM itemOwner; // owner for grouping
+#else
+ int numberId;
+ DWORD itemOwner;
+#endif
+
+ // brush primitive only
+ epair_t *epairs;
+
+} brush_t;
+
+
+#define MAX_FLAGS 8
+
+
+typedef struct trimodel_t
+{
+ vec3_t v[3];
+ float st[3][2];
+} trimodel;
+
+typedef struct entitymodel_t
+{
+ struct entitymodel_t *pNext;
+ int nTriCount;
+ trimodel *pTriList;
+ int nTextureBind;
+ int nSkinWidth;
+ int nSkinHeight;
+ int nModelPosition;
+} entitymodel;
+
+
+// eclass show flags
+
+#define ECLASS_LIGHT 0x00000001
+#define ECLASS_ANGLE 0x00000002
+#define ECLASS_PATH 0x00000004
+#define ECLASS_MISCMODEL 0x00000008
+#define ECLASS_PLUGINENTITY 0x00000010
+
+typedef struct eclass_s
+{
+ struct eclass_s *next;
+ char *name;
+ qboolean fixedsize;
+ qboolean unknown; // wasn't found in source
+ vec3_t mins, maxs;
+ vec3_t color;
+ texdef_t texdef;
+ char *comments;
+ char flagnames[MAX_FLAGS][32];
+
+/*
+ int nTriCount;
+ trimodel *pTriList;
+ int nTextureBind;
+ int nSkinWidth, nSkinHeight;
+*/
+ entitymodel *model;
+ char *modelpath;
+ char *skinpath;
+ int nFrame;
+ unsigned int nShowFlags;
+
+ HMODULE hPlug;
+} eclass_t;
+
+extern eclass_t *eclass;
+
+/*
+** window bits
+*/
+#define W_CAMERA 0x0001
+#define W_XY 0x0002
+#define W_XY_OVERLAY 0x0004
+#define W_Z 0x0008
+#define W_TEXTURE 0x0010
+#define W_Z_OVERLAY 0x0020
+#define W_CONSOLE 0x0040
+#define W_ENTITY 0x0080
+#define W_CAMERA_IFON 0x0100
+#define W_XZ 0x0200 //--| only used for patch vertex manip stuff
+#define W_YZ 0x0400 //--|
+#define W_GROUP 0x0800
+#define W_MEDIA 0x1000
+#define W_ALL 0xFFFFFFFF
+
+// used in some Drawing routines
+enum VIEWTYPE {YZ, XZ, XY};
+
+enum terrainnoise_t { NOISE_NONE, NOISE_PLUS, NOISE_PLUSMINUS };
+enum terrainbrush_t { TERRAIN_BRUSH_CIRCLE, TERRAIN_BRUSH_SQUARE };
+enum terrainfalloff_t { TERRAIN_FALLOFF_LINEAR, TERRAIN_FALLOFF_CURVED };
+
+#endif \ No newline at end of file
diff --git a/q3radiant/QFILES.H b/q3radiant/QFILES.H
new file mode 100755
index 0000000..5043d93
--- /dev/null
+++ b/q3radiant/QFILES.H
@@ -0,0 +1,481 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+//
+// qfiles.h: quake file formats
+// This file must be identical in the quake and utils directories
+//
+
+/*
+========================================================================
+
+.MD2 triangle model file format
+
+========================================================================
+*/
+
+#define IDALIASHEADER (('2'<<24)+('P'<<16)+('D'<<8)+'I')
+#define ALIAS_VERSION 8
+
+#define MAX_TRIANGLES 4096
+#define MAX_VERTS 2048
+#define MAX_FRAMES 512
+#define MAX_MD2SKINS 32
+#define MAX_SKINNAME 64
+
+typedef struct
+{
+ short s;
+ short t;
+} dstvert_t;
+
+typedef struct
+{
+ short index_xyz[3];
+ short index_st[3];
+} dtriangle_t;
+
+typedef struct
+{
+ byte v[3]; // scaled byte to fit in frame mins/maxs
+ byte lightnormalindex;
+} dtrivertx_t;
+
+typedef struct
+{
+ float scale[3]; // multiply byte verts by this
+ float translate[3]; // then add this
+ char name[16]; // frame name from grabbing
+ dtrivertx_t verts[1]; // variable sized
+} daliasframe_t;
+
+
+// the glcmd format:
+// a positive integer starts a tristrip command, followed by that many
+// vertex structures.
+// a negative integer starts a trifan command, followed by -x vertexes
+// a zero indicates the end of the command list.
+// a vertex consists of a floating point s, a floating point t,
+// and an integer vertex index.
+
+
+typedef struct
+{
+ int ident;
+ int version;
+
+ int skinwidth;
+ int skinheight;
+ int framesize; // byte size of each frame
+
+ int num_skins;
+ int num_xyz;
+ int num_st; // greater than num_xyz for seams
+ int num_tris;
+ int num_glcmds; // dwords in strip/fan command list
+ int num_frames;
+
+ int ofs_skins; // each skin is a MAX_SKINNAME string
+ int ofs_st; // byte offset from start for stverts
+ int ofs_tris; // offset for dtriangles
+ int ofs_frames; // offset for first frame
+ int ofs_glcmds;
+ int ofs_end; // end of file
+
+} dmdl_t;
+
+#define MD3_IDENT (('3'<<24)+('P'<<16)+('D'<<8)+'I')
+#define MAX_QPATH 64 // max length of a quake game pathname
+#define MD3_XYZ_SCALE (1.0/64)
+
+typedef struct {
+ int ident;
+ int version;
+
+ char name[MAX_QPATH]; // model name
+
+ int flags;
+
+ int numFrames;
+ int numTags;
+ int numSurfaces;
+
+ int numSkins;
+
+ int ofsFrames; // offset for first frame
+ int ofsTags; // numFrames * numTags
+ int ofsSurfaces; // first surface, others follow
+
+ int ofsEnd; // end of file
+} md3Header_t;
+
+typedef struct {
+ int ident; //
+
+ char name[MAX_QPATH]; // polyset name
+
+ int flags;
+ int numFrames; // all surfaces in a model should have the same
+
+ int numShaders; // all surfaces in a model should have the same
+ int numVerts;
+
+ int numTriangles;
+ int ofsTriangles;
+
+ int ofsShaders; // offset from start of md3Surface_t
+ int ofsSt; // texture coords are common for all frames
+ int ofsXyzNormals; // numVerts * numFrames
+
+ int ofsEnd; // next surface follows
+
+} md3Surface_t;
+
+typedef struct {
+ char name[MAX_QPATH];
+ int shaderIndex; // for in-game use
+} md3Shader_t;
+
+typedef struct {
+ int indexes[3];
+} md3Triangle_t;
+
+typedef struct {
+ float st[2];
+} md3St_t;
+
+typedef struct {
+ short xyz[3];
+ short normal;
+} md3XyzNormal_t;
+
+
+typedef struct
+{
+ float st[2];
+ int nVertIndex;
+} glst_t;
+
+typedef struct
+{
+ int nCount;
+ int ObjectIndex;
+ glst_t GlSt;
+} gl_t;
+
+/*
+========================================================================
+
+.SP2 sprite file format
+
+========================================================================
+*/
+
+#define IDSPRITEHEADER (('2'<<24)+('S'<<16)+('D'<<8)+'I')
+ // little-endian "IDS2"
+#define SPRITE_VERSION 2
+
+typedef struct
+{
+ int width, height;
+ int origin_x, origin_y; // raster coordinates inside pic
+ char name[MAX_SKINNAME]; // name of pcx file
+} dsprframe_t;
+
+typedef struct {
+ int ident;
+ int version;
+ int numframes;
+ dsprframe_t frames[1]; // variable sized
+} dsprite_t;
+
+/*
+==============================================================================
+
+ .WAL texture file format
+
+==============================================================================
+*/
+
+
+#define MIPLEVELS 4
+typedef struct miptex_s
+{
+ char name[32];
+ unsigned width, height;
+ unsigned offsets[MIPLEVELS]; // four mip maps stored
+ char animname[32]; // next frame in animation chain
+ int flags;
+ int contents;
+ int value;
+} miptex_t;
+
+
+
+/*
+==============================================================================
+
+ .BSP file format
+
+==============================================================================
+*/
+
+#define IDBSPHEADER (('P'<<24)+('S'<<16)+('B'<<8)+'I')
+ // little-endian "IBSP"
+
+#define BSPVERSION 36
+
+
+// upper design bounds
+// leaffaces, leafbrushes, planes, and verts are still bounded by
+// 16 bit short limits
+#define MAX_MAP_MODELS 1024
+#define MAX_MAP_BRUSHES 8192
+#define MAX_MAP_ENTITIES 2048
+#define MAX_MAP_ENTSTRING 0x20000
+#define MAX_MAP_TEXINFO 8192
+
+#define MAX_MAP_PLANES 65536
+#define MAX_MAP_NODES 65536
+#define MAX_MAP_BRUSHSIDES 65536
+#define MAX_MAP_LEAFS 65536
+#define MAX_MAP_VERTS 65536
+#define MAX_MAP_FACES 65536
+#define MAX_MAP_LEAFFACES 65536
+#define MAX_MAP_LEAFBRUSHES 65536
+#define MAX_MAP_PORTALS 65536
+#define MAX_MAP_EDGES 128000
+#define MAX_MAP_SURFEDGES 256000
+#define MAX_MAP_LIGHTING 0x200000
+#define MAX_MAP_VISIBILITY 0x100000
+
+#define MAX_WORLD_COORD ( 128*1024 )
+#define MIN_WORLD_COORD ( -128*1024 )
+#define WORLD_SIZE ( MAX_WORLD_COORD - MIN_WORLD_COORD )
+
+#define MAX_BRUSH_SIZE ( WORLD_SIZE )
+
+// key / value pair sizes
+
+#define MAX_KEY 32
+#define MAX_VALUE 1024
+
+//=============================================================================
+
+typedef struct
+{
+ int fileofs, filelen;
+} lump_t;
+
+#define LUMP_ENTITIES 0
+#define LUMP_PLANES 1
+#define LUMP_VERTEXES 2
+#define LUMP_VISIBILITY 3
+#define LUMP_NODES 4
+#define LUMP_TEXINFO 5
+#define LUMP_FACES 6
+#define LUMP_LIGHTING 7
+#define LUMP_LEAFS 8
+#define LUMP_LEAFFACES 9
+#define LUMP_LEAFBRUSHES 10
+#define LUMP_EDGES 11
+#define LUMP_SURFEDGES 12
+#define LUMP_MODELS 13
+#define LUMP_BRUSHES 14
+#define LUMP_BRUSHSIDES 15
+#define LUMP_POP 16
+
+#define HEADER_LUMPS 17
+
+typedef struct
+{
+ int ident;
+ int version;
+ lump_t lumps[HEADER_LUMPS];
+} dheader_t;
+
+typedef struct
+{
+ float mins[3], maxs[3];
+ float origin[3]; // for sounds or lights
+ int headnode;
+ int firstface, numfaces; // submodels just draw faces
+ // without walking the bsp tree
+} dmodel_t;
+
+
+typedef struct
+{
+ float point[3];
+} dvertex_t;
+
+
+// 0-2 are axial planes
+#define PLANE_X 0
+#define PLANE_Y 1
+#define PLANE_Z 2
+
+// 3-5 are non-axial planes snapped to the nearest
+#define PLANE_ANYX 3
+#define PLANE_ANYY 4
+#define PLANE_ANYZ 5
+
+// planes (x&~1) and (x&~1)+1 are allways opposites
+
+typedef struct
+{
+ float normal[3];
+ float dist;
+ int type; // PLANE_X - PLANE_ANYZ ?remove? trivial to regenerate
+} dplane_t;
+
+
+// contents flags are seperate bits
+// a given brush can contribute multiple content bits
+// multiple brushes can be in a single leaf
+
+// lower bits are stronger, and will eat weaker brushes completely
+#define CONTENTS_SOLID 1 // an eye is never valid in a solid
+#define CONTENTS_WINDOW 2 // translucent, but not watery
+#define CONTENTS_AUX 4
+#define CONTENTS_LAVA 8
+#define CONTENTS_SLIME 16
+#define CONTENTS_WATER 32
+#define CONTENTS_MIST 64
+#define LAST_VISIBLE_CONTENTS 64
+
+// remaining contents are non-visible, and don't eat brushes
+#define CONTENTS_PLAYERCLIP 0x10000
+#define CONTENTS_MONSTERCLIP 0x20000
+
+// currents can be added to any other contents, and may be mixed
+#define CONTENTS_CURRENT_0 0x40000
+#define CONTENTS_CURRENT_90 0x80000
+#define CONTENTS_CURRENT_180 0x100000
+#define CONTENTS_CURRENT_270 0x200000
+#define CONTENTS_CURRENT_UP 0x400000
+#define CONTENTS_CURRENT_DOWN 0x800000
+
+#define CONTENTS_ORIGIN 0x1000000 // removed before bsping an entity
+
+#define CONTENTS_MONSTER 0x2000000 // should never be on a brush, only in game
+#define CONTENTS_DEADMONSTER 0x4000000 // corpse
+#define CONTENTS_DETAIL 0x8000000 // brushes to be added after vis leafs
+#define CONTENTS_TRANSLUCENT 0x10000000 // auto set if any surface has trans
+#define CONTENTS_LADDER 0x20000000 // ladder
+#define CONTENTS_NEGATIVE_CURVE 0x40000000 // reverse inside / outside
+
+#define CONTENTS_KEEP (CONTENTS_DETAIL | CONTENTS_NEGATIVE_CURVE)
+
+
+typedef struct
+{
+ int planenum;
+ int children[2]; // negative numbers are -(leafs+1), not nodes
+ short mins[3]; // for frustom culling
+ short maxs[3];
+ unsigned short firstface;
+ unsigned short numfaces; // counting both sides
+} dnode_t;
+
+
+typedef struct texinfo_s
+{
+ float vecs[2][4]; // [s/t][xyz offset]
+ int flags; // miptex flags + overrides
+ int value; // light emission, etc
+ char texture[32]; // texture name (textures/*.wal)
+ int nexttexinfo; // for animations, -1 = end of chain
+} texinfo_t;
+
+
+#define SURF_LIGHT 0x1 // value will hold the light strength
+
+#define SURF_SLICK 0x2 // effects game physics
+
+#define SURF_SKY 0x4 // don't draw, but add to skybox
+#define SURF_WARP 0x8 // turbulent water warp
+#define SURF_TRANS33 0x10
+#define SURF_TRANS66 0x20
+#define SURF_FLOWING 0x40 // scroll towards angle
+#define SURF_NODRAW 0x80 // don't bother referencing the texture
+
+#define SURF_PATCH 0x20000000
+#define SURF_CURVE_FAKE 0x40000000
+#define SURF_CURVE 0x80000000
+#define SURF_KEEP (SURF_CURVE | SURF_CURVE_FAKE | SURF_PATCH)
+
+// note that edge 0 is never used, because negative edge nums are used for
+// counterclockwise use of the edge in a face
+typedef struct
+{
+ unsigned short v[2]; // vertex numbers
+} dedge_t;
+
+#define MAXLIGHTMAPS 4
+typedef struct
+{
+ unsigned short planenum;
+ short side;
+
+ int firstedge; // we must support > 64k edges
+ short numedges;
+ short texinfo;
+
+// lighting info
+ byte styles[MAXLIGHTMAPS];
+ int lightofs; // start of [numstyles*surfsize] samples
+} dface_t;
+
+typedef struct
+{
+ int contents; // OR of all brushes (not needed?)
+
+ int pvsofs; // -1 = no info
+ int phsofs; // -1 = no info
+
+ short mins[3]; // for frustum culling
+ short maxs[3];
+
+ unsigned short firstleafface;
+ unsigned short numleaffaces;
+
+ unsigned short firstleafbrush;
+ unsigned short numleafbrushes;
+} dleaf_t;
+
+typedef struct
+{
+ unsigned short planenum; // facing out of the leaf
+ short texinfo;
+} dbrushside_t;
+
+typedef struct
+{
+ int firstside;
+ int numsides;
+ int contents;
+} dbrush_t;
+
+#define ANGLE_UP -1
+#define ANGLE_DOWN -2
+
diff --git a/q3radiant/QGL.H b/q3radiant/QGL.H
new file mode 100755
index 0000000..c16de65
--- /dev/null
+++ b/q3radiant/QGL.H
@@ -0,0 +1,456 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+/*
+** QGL.H
+*/
+
+#ifndef __QGL_H__
+#define __QGL_H__
+
+#ifdef _WIN32
+# include <windows.h>
+#endif
+
+#include <gl/gl.h>
+#include <gl/glu.h>
+
+int QGL_Init( const char *dllname, const char* pGluName );
+void QGL_Shutdown();
+
+#ifndef APIENTRY
+# define APIENTRY
+#endif
+
+extern void ( APIENTRY * qglAccum )(GLenum op, GLfloat value);
+extern void ( APIENTRY * qglAlphaFunc )(GLenum func, GLclampf ref);
+extern GLboolean ( APIENTRY * qglAreTexturesResident )(GLsizei n, const GLuint *textures, GLboolean *residences);
+extern void ( APIENTRY * qglArrayElement )(GLint i);
+extern void ( APIENTRY * qglBegin )(GLenum mode);
+extern void ( APIENTRY * qglBindTexture )(GLenum target, GLuint texture);
+extern void ( APIENTRY * qglBitmap )(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap);
+extern void ( APIENTRY * qglBlendFunc )(GLenum sfactor, GLenum dfactor);
+extern void ( APIENTRY * qglCallList )(GLuint list);
+extern void ( APIENTRY * qglCallLists )(GLsizei n, GLenum type, const GLvoid *lists);
+extern void ( APIENTRY * qglClear )(GLbitfield mask);
+extern void ( APIENTRY * qglClearAccum )(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+extern void ( APIENTRY * qglClearColor )(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+extern void ( APIENTRY * qglClearDepth )(GLclampd depth);
+extern void ( APIENTRY * qglClearIndex )(GLfloat c);
+extern void ( APIENTRY * qglClearStencil )(GLint s);
+extern void ( APIENTRY * qglClipPlane )(GLenum plane, const GLdouble *equation);
+extern void ( APIENTRY * qglColor3b )(GLbyte red, GLbyte green, GLbyte blue);
+extern void ( APIENTRY * qglColor3bv )(const GLbyte *v);
+extern void ( APIENTRY * qglColor3d )(GLdouble red, GLdouble green, GLdouble blue);
+extern void ( APIENTRY * qglColor3dv )(const GLdouble *v);
+extern void ( APIENTRY * qglColor3f )(GLfloat red, GLfloat green, GLfloat blue);
+extern void ( APIENTRY * qglColor3fv )(const GLfloat *v);
+extern void ( APIENTRY * qglColor3i )(GLint red, GLint green, GLint blue);
+extern void ( APIENTRY * qglColor3iv )(const GLint *v);
+extern void ( APIENTRY * qglColor3s )(GLshort red, GLshort green, GLshort blue);
+extern void ( APIENTRY * qglColor3sv )(const GLshort *v);
+extern void ( APIENTRY * qglColor3ub )(GLubyte red, GLubyte green, GLubyte blue);
+extern void ( APIENTRY * qglColor3ubv )(const GLubyte *v);
+extern void ( APIENTRY * qglColor3ui )(GLuint red, GLuint green, GLuint blue);
+extern void ( APIENTRY * qglColor3uiv )(const GLuint *v);
+extern void ( APIENTRY * qglColor3us )(GLushort red, GLushort green, GLushort blue);
+extern void ( APIENTRY * qglColor3usv )(const GLushort *v);
+extern void ( APIENTRY * qglColor4b )(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha);
+extern void ( APIENTRY * qglColor4bv )(const GLbyte *v);
+extern void ( APIENTRY * qglColor4d )(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha);
+extern void ( APIENTRY * qglColor4dv )(const GLdouble *v);
+extern void ( APIENTRY * qglColor4f )(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+extern void ( APIENTRY * qglColor4fv )(const GLfloat *v);
+extern void ( APIENTRY * qglColor4i )(GLint red, GLint green, GLint blue, GLint alpha);
+extern void ( APIENTRY * qglColor4iv )(const GLint *v);
+extern void ( APIENTRY * qglColor4s )(GLshort red, GLshort green, GLshort blue, GLshort alpha);
+extern void ( APIENTRY * qglColor4sv )(const GLshort *v);
+extern void ( APIENTRY * qglColor4ub )(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha);
+extern void ( APIENTRY * qglColor4ubv )(const GLubyte *v);
+extern void ( APIENTRY * qglColor4ui )(GLuint red, GLuint green, GLuint blue, GLuint alpha);
+extern void ( APIENTRY * qglColor4uiv )(const GLuint *v);
+extern void ( APIENTRY * qglColor4us )(GLushort red, GLushort green, GLushort blue, GLushort alpha);
+extern void ( APIENTRY * qglColor4usv )(const GLushort *v);
+extern void ( APIENTRY * qglColorMask )(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
+extern void ( APIENTRY * qglColorMaterial )(GLenum face, GLenum mode);
+extern void ( APIENTRY * qglColorPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+extern void ( APIENTRY * qglCopyPixels )(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type);
+extern void ( APIENTRY * qglCopyTexImage1D )(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLint border);
+extern void ( APIENTRY * qglCopyTexImage2D )(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+extern void ( APIENTRY * qglCopyTexSubImage1D )(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
+extern void ( APIENTRY * qglCopyTexSubImage2D )(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+extern void ( APIENTRY * qglCullFace )(GLenum mode);
+extern void ( APIENTRY * qglDeleteLists )(GLuint list, GLsizei range);
+extern void ( APIENTRY * qglDeleteTextures )(GLsizei n, const GLuint *textures);
+extern void ( APIENTRY * qglDepthFunc )(GLenum func);
+extern void ( APIENTRY * qglDepthMask )(GLboolean flag);
+extern void ( APIENTRY * qglDepthRange )(GLclampd zNear, GLclampd zFar);
+extern void ( APIENTRY * qglDisable )(GLenum cap);
+extern void ( APIENTRY * qglDisableClientState )(GLenum array);
+extern void ( APIENTRY * qglDrawArrays )(GLenum mode, GLint first, GLsizei count);
+extern void ( APIENTRY * qglDrawBuffer )(GLenum mode);
+extern void ( APIENTRY * qglDrawElements )(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices);
+extern void ( APIENTRY * qglDrawPixels )(GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+extern void ( APIENTRY * qglEdgeFlag )(GLboolean flag);
+extern void ( APIENTRY * qglEdgeFlagPointer )(GLsizei stride, const GLvoid *pointer);
+extern void ( APIENTRY * qglEdgeFlagv )(const GLboolean *flag);
+extern void ( APIENTRY * qglEnable )(GLenum cap);
+extern void ( APIENTRY * qglEnableClientState )(GLenum array);
+extern void ( APIENTRY * qglEnd )(void);
+extern void ( APIENTRY * qglEndList )(void);
+extern void ( APIENTRY * qglEvalCoord1d )(GLdouble u);
+extern void ( APIENTRY * qglEvalCoord1dv )(const GLdouble *u);
+extern void ( APIENTRY * qglEvalCoord1f )(GLfloat u);
+extern void ( APIENTRY * qglEvalCoord1fv )(const GLfloat *u);
+extern void ( APIENTRY * qglEvalCoord2d )(GLdouble u, GLdouble v);
+extern void ( APIENTRY * qglEvalCoord2dv )(const GLdouble *u);
+extern void ( APIENTRY * qglEvalCoord2f )(GLfloat u, GLfloat v);
+extern void ( APIENTRY * qglEvalCoord2fv )(const GLfloat *u);
+extern void ( APIENTRY * qglEvalMesh1 )(GLenum mode, GLint i1, GLint i2);
+extern void ( APIENTRY * qglEvalMesh2 )(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2);
+extern void ( APIENTRY * qglEvalPoint1 )(GLint i);
+extern void ( APIENTRY * qglEvalPoint2 )(GLint i, GLint j);
+extern void ( APIENTRY * qglFeedbackBuffer )(GLsizei size, GLenum type, GLfloat *buffer);
+extern void ( APIENTRY * qglFinish )(void);
+extern void ( APIENTRY * qglFlush )(void);
+extern void ( APIENTRY * qglFogf )(GLenum pname, GLfloat param);
+extern void ( APIENTRY * qglFogfv )(GLenum pname, const GLfloat *params);
+extern void ( APIENTRY * qglFogi )(GLenum pname, GLint param);
+extern void ( APIENTRY * qglFogiv )(GLenum pname, const GLint *params);
+extern void ( APIENTRY * qglFrontFace )(GLenum mode);
+extern void ( APIENTRY * qglFrustum )(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+extern GLuint ( APIENTRY * qglGenLists )(GLsizei range);
+extern void ( APIENTRY * qglGenTextures )(GLsizei n, GLuint *textures);
+extern void ( APIENTRY * qglGetBooleanv )(GLenum pname, GLboolean *params);
+extern void ( APIENTRY * qglGetClipPlane )(GLenum plane, GLdouble *equation);
+extern void ( APIENTRY * qglGetDoublev )(GLenum pname, GLdouble *params);
+extern GLenum ( APIENTRY * qglGetError )(void);
+extern void ( APIENTRY * qglGetFloatv )(GLenum pname, GLfloat *params);
+extern void ( APIENTRY * qglGetIntegerv )(GLenum pname, GLint *params);
+extern void ( APIENTRY * qglGetLightfv )(GLenum light, GLenum pname, GLfloat *params);
+extern void ( APIENTRY * qglGetLightiv )(GLenum light, GLenum pname, GLint *params);
+extern void ( APIENTRY * qglGetMapdv )(GLenum target, GLenum query, GLdouble *v);
+extern void ( APIENTRY * qglGetMapfv )(GLenum target, GLenum query, GLfloat *v);
+extern void ( APIENTRY * qglGetMapiv )(GLenum target, GLenum query, GLint *v);
+extern void ( APIENTRY * qglGetMaterialfv )(GLenum face, GLenum pname, GLfloat *params);
+extern void ( APIENTRY * qglGetMaterialiv )(GLenum face, GLenum pname, GLint *params);
+extern void ( APIENTRY * qglGetPixelMapfv )(GLenum map, GLfloat *values);
+extern void ( APIENTRY * qglGetPixelMapuiv )(GLenum map, GLuint *values);
+extern void ( APIENTRY * qglGetPixelMapusv )(GLenum map, GLushort *values);
+extern void ( APIENTRY * qglGetPointerv )(GLenum pname, GLvoid* *params);
+extern void ( APIENTRY * qglGetPolygonStipple )(GLubyte *mask);
+extern const GLubyte * ( APIENTRY * qglGetString )(GLenum name);
+extern void ( APIENTRY * qglGetTexEnvfv )(GLenum target, GLenum pname, GLfloat *params);
+extern void ( APIENTRY * qglGetTexEnviv )(GLenum target, GLenum pname, GLint *params);
+extern void ( APIENTRY * qglGetTexGendv )(GLenum coord, GLenum pname, GLdouble *params);
+extern void ( APIENTRY * qglGetTexGenfv )(GLenum coord, GLenum pname, GLfloat *params);
+extern void ( APIENTRY * qglGetTexGeniv )(GLenum coord, GLenum pname, GLint *params);
+extern void ( APIENTRY * qglGetTexImage )(GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels);
+extern void ( APIENTRY * qglGetTexLevelParameterfv )(GLenum target, GLint level, GLenum pname, GLfloat *params);
+extern void ( APIENTRY * qglGetTexLevelParameteriv )(GLenum target, GLint level, GLenum pname, GLint *params);
+extern void ( APIENTRY * qglGetTexParameterfv )(GLenum target, GLenum pname, GLfloat *params);
+extern void ( APIENTRY * qglGetTexParameteriv )(GLenum target, GLenum pname, GLint *params);
+extern void ( APIENTRY * qglHint )(GLenum target, GLenum mode);
+extern void ( APIENTRY * qglIndexMask )(GLuint mask);
+extern void ( APIENTRY * qglIndexPointer )(GLenum type, GLsizei stride, const GLvoid *pointer);
+extern void ( APIENTRY * qglIndexd )(GLdouble c);
+extern void ( APIENTRY * qglIndexdv )(const GLdouble *c);
+extern void ( APIENTRY * qglIndexf )(GLfloat c);
+extern void ( APIENTRY * qglIndexfv )(const GLfloat *c);
+extern void ( APIENTRY * qglIndexi )(GLint c);
+extern void ( APIENTRY * qglIndexiv )(const GLint *c);
+extern void ( APIENTRY * qglIndexs )(GLshort c);
+extern void ( APIENTRY * qglIndexsv )(const GLshort *c);
+extern void ( APIENTRY * qglIndexub )(GLubyte c);
+extern void ( APIENTRY * qglIndexubv )(const GLubyte *c);
+extern void ( APIENTRY * qglInitNames )(void);
+extern void ( APIENTRY * qglInterleavedArrays )(GLenum format, GLsizei stride, const GLvoid *pointer);
+extern GLboolean ( APIENTRY * qglIsEnabled )(GLenum cap);
+extern GLboolean ( APIENTRY * qglIsList )(GLuint list);
+extern GLboolean ( APIENTRY * qglIsTexture )(GLuint texture);
+extern void ( APIENTRY * qglLightModelf )(GLenum pname, GLfloat param);
+extern void ( APIENTRY * qglLightModelfv )(GLenum pname, const GLfloat *params);
+extern void ( APIENTRY * qglLightModeli )(GLenum pname, GLint param);
+extern void ( APIENTRY * qglLightModeliv )(GLenum pname, const GLint *params);
+extern void ( APIENTRY * qglLightf )(GLenum light, GLenum pname, GLfloat param);
+extern void ( APIENTRY * qglLightfv )(GLenum light, GLenum pname, const GLfloat *params);
+extern void ( APIENTRY * qglLighti )(GLenum light, GLenum pname, GLint param);
+extern void ( APIENTRY * qglLightiv )(GLenum light, GLenum pname, const GLint *params);
+extern void ( APIENTRY * qglLineStipple )(GLint factor, GLushort pattern);
+extern void ( APIENTRY * qglLineWidth )(GLfloat width);
+extern void ( APIENTRY * qglListBase )(GLuint base);
+extern void ( APIENTRY * qglLoadIdentity )(void);
+extern void ( APIENTRY * qglLoadMatrixd )(const GLdouble *m);
+extern void ( APIENTRY * qglLoadMatrixf )(const GLfloat *m);
+extern void ( APIENTRY * qglLoadName )(GLuint name);
+extern void ( APIENTRY * qglLogicOp )(GLenum opcode);
+extern void ( APIENTRY * qglMap1d )(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points);
+extern void ( APIENTRY * qglMap1f )(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points);
+extern void ( APIENTRY * qglMap2d )(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points);
+extern void ( APIENTRY * qglMap2f )(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points);
+extern void ( APIENTRY * qglMapGrid1d )(GLint un, GLdouble u1, GLdouble u2);
+extern void ( APIENTRY * qglMapGrid1f )(GLint un, GLfloat u1, GLfloat u2);
+extern void ( APIENTRY * qglMapGrid2d )(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2);
+extern void ( APIENTRY * qglMapGrid2f )(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2);
+extern void ( APIENTRY * qglMaterialf )(GLenum face, GLenum pname, GLfloat param);
+extern void ( APIENTRY * qglMaterialfv )(GLenum face, GLenum pname, const GLfloat *params);
+extern void ( APIENTRY * qglMateriali )(GLenum face, GLenum pname, GLint param);
+extern void ( APIENTRY * qglMaterialiv )(GLenum face, GLenum pname, const GLint *params);
+extern void ( APIENTRY * qglMatrixMode )(GLenum mode);
+extern void ( APIENTRY * qglMultMatrixd )(const GLdouble *m);
+extern void ( APIENTRY * qglMultMatrixf )(const GLfloat *m);
+extern void ( APIENTRY * qglNewList )(GLuint list, GLenum mode);
+extern void ( APIENTRY * qglNormal3b )(GLbyte nx, GLbyte ny, GLbyte nz);
+extern void ( APIENTRY * qglNormal3bv )(const GLbyte *v);
+extern void ( APIENTRY * qglNormal3d )(GLdouble nx, GLdouble ny, GLdouble nz);
+extern void ( APIENTRY * qglNormal3dv )(const GLdouble *v);
+extern void ( APIENTRY * qglNormal3f )(GLfloat nx, GLfloat ny, GLfloat nz);
+extern void ( APIENTRY * qglNormal3fv )(const GLfloat *v);
+extern void ( APIENTRY * qglNormal3i )(GLint nx, GLint ny, GLint nz);
+extern void ( APIENTRY * qglNormal3iv )(const GLint *v);
+extern void ( APIENTRY * qglNormal3s )(GLshort nx, GLshort ny, GLshort nz);
+extern void ( APIENTRY * qglNormal3sv )(const GLshort *v);
+extern void ( APIENTRY * qglNormalPointer )(GLenum type, GLsizei stride, const GLvoid *pointer);
+extern void ( APIENTRY * qglOrtho )(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+extern void ( APIENTRY * qglPassThrough )(GLfloat token);
+extern void ( APIENTRY * qglPixelMapfv )(GLenum map, GLsizei mapsize, const GLfloat *values);
+extern void ( APIENTRY * qglPixelMapuiv )(GLenum map, GLsizei mapsize, const GLuint *values);
+extern void ( APIENTRY * qglPixelMapusv )(GLenum map, GLsizei mapsize, const GLushort *values);
+extern void ( APIENTRY * qglPixelStoref )(GLenum pname, GLfloat param);
+extern void ( APIENTRY * qglPixelStorei )(GLenum pname, GLint param);
+extern void ( APIENTRY * qglPixelTransferf )(GLenum pname, GLfloat param);
+extern void ( APIENTRY * qglPixelTransferi )(GLenum pname, GLint param);
+extern void ( APIENTRY * qglPixelZoom )(GLfloat xfactor, GLfloat yfactor);
+extern void ( APIENTRY * qglPointSize )(GLfloat size);
+extern void ( APIENTRY * qglPolygonMode )(GLenum face, GLenum mode);
+extern void ( APIENTRY * qglPolygonOffset )(GLfloat factor, GLfloat units);
+extern void ( APIENTRY * qglPolygonStipple )(const GLubyte *mask);
+extern void ( APIENTRY * qglPopAttrib )(void);
+extern void ( APIENTRY * qglPopClientAttrib )(void);
+extern void ( APIENTRY * qglPopMatrix )(void);
+extern void ( APIENTRY * qglPopName )(void);
+extern void ( APIENTRY * qglPrioritizeTextures )(GLsizei n, const GLuint *textures, const GLclampf *priorities);
+extern void ( APIENTRY * qglPushAttrib )(GLbitfield mask);
+extern void ( APIENTRY * qglPushClientAttrib )(GLbitfield mask);
+extern void ( APIENTRY * qglPushMatrix )(void);
+extern void ( APIENTRY * qglPushName )(GLuint name);
+extern void ( APIENTRY * qglRasterPos2d )(GLdouble x, GLdouble y);
+extern void ( APIENTRY * qglRasterPos2dv )(const GLdouble *v);
+extern void ( APIENTRY * qglRasterPos2f )(GLfloat x, GLfloat y);
+extern void ( APIENTRY * qglRasterPos2fv )(const GLfloat *v);
+extern void ( APIENTRY * qglRasterPos2i )(GLint x, GLint y);
+extern void ( APIENTRY * qglRasterPos2iv )(const GLint *v);
+extern void ( APIENTRY * qglRasterPos2s )(GLshort x, GLshort y);
+extern void ( APIENTRY * qglRasterPos2sv )(const GLshort *v);
+extern void ( APIENTRY * qglRasterPos3d )(GLdouble x, GLdouble y, GLdouble z);
+extern void ( APIENTRY * qglRasterPos3dv )(const GLdouble *v);
+extern void ( APIENTRY * qglRasterPos3f )(GLfloat x, GLfloat y, GLfloat z);
+extern void ( APIENTRY * qglRasterPos3fv )(const GLfloat *v);
+extern void ( APIENTRY * qglRasterPos3i )(GLint x, GLint y, GLint z);
+extern void ( APIENTRY * qglRasterPos3iv )(const GLint *v);
+extern void ( APIENTRY * qglRasterPos3s )(GLshort x, GLshort y, GLshort z);
+extern void ( APIENTRY * qglRasterPos3sv )(const GLshort *v);
+extern void ( APIENTRY * qglRasterPos4d )(GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+extern void ( APIENTRY * qglRasterPos4dv )(const GLdouble *v);
+extern void ( APIENTRY * qglRasterPos4f )(GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+extern void ( APIENTRY * qglRasterPos4fv )(const GLfloat *v);
+extern void ( APIENTRY * qglRasterPos4i )(GLint x, GLint y, GLint z, GLint w);
+extern void ( APIENTRY * qglRasterPos4iv )(const GLint *v);
+extern void ( APIENTRY * qglRasterPos4s )(GLshort x, GLshort y, GLshort z, GLshort w);
+extern void ( APIENTRY * qglRasterPos4sv )(const GLshort *v);
+extern void ( APIENTRY * qglReadBuffer )(GLenum mode);
+extern void ( APIENTRY * qglReadPixels )(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels);
+extern void ( APIENTRY * qglRectd )(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2);
+extern void ( APIENTRY * qglRectdv )(const GLdouble *v1, const GLdouble *v2);
+extern void ( APIENTRY * qglRectf )(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2);
+extern void ( APIENTRY * qglRectfv )(const GLfloat *v1, const GLfloat *v2);
+extern void ( APIENTRY * qglRecti )(GLint x1, GLint y1, GLint x2, GLint y2);
+extern void ( APIENTRY * qglRectiv )(const GLint *v1, const GLint *v2);
+extern void ( APIENTRY * qglRects )(GLshort x1, GLshort y1, GLshort x2, GLshort y2);
+extern void ( APIENTRY * qglRectsv )(const GLshort *v1, const GLshort *v2);
+extern GLint ( APIENTRY * qglRenderMode )(GLenum mode);
+extern void ( APIENTRY * qglRotated )(GLdouble angle, GLdouble x, GLdouble y, GLdouble z);
+extern void ( APIENTRY * qglRotatef )(GLfloat angle, GLfloat x, GLfloat y, GLfloat z);
+extern void ( APIENTRY * qglScaled )(GLdouble x, GLdouble y, GLdouble z);
+extern void ( APIENTRY * qglScalef )(GLfloat x, GLfloat y, GLfloat z);
+extern void ( APIENTRY * qglScissor )(GLint x, GLint y, GLsizei width, GLsizei height);
+extern void ( APIENTRY * qglSelectBuffer )(GLsizei size, GLuint *buffer);
+extern void ( APIENTRY * qglShadeModel )(GLenum mode);
+extern void ( APIENTRY * qglStencilFunc )(GLenum func, GLint ref, GLuint mask);
+extern void ( APIENTRY * qglStencilMask )(GLuint mask);
+extern void ( APIENTRY * qglStencilOp )(GLenum fail, GLenum zfail, GLenum zpass);
+extern void ( APIENTRY * qglTexCoord1d )(GLdouble s);
+extern void ( APIENTRY * qglTexCoord1dv )(const GLdouble *v);
+extern void ( APIENTRY * qglTexCoord1f )(GLfloat s);
+extern void ( APIENTRY * qglTexCoord1fv )(const GLfloat *v);
+extern void ( APIENTRY * qglTexCoord1i )(GLint s);
+extern void ( APIENTRY * qglTexCoord1iv )(const GLint *v);
+extern void ( APIENTRY * qglTexCoord1s )(GLshort s);
+extern void ( APIENTRY * qglTexCoord1sv )(const GLshort *v);
+extern void ( APIENTRY * qglTexCoord2d )(GLdouble s, GLdouble t);
+extern void ( APIENTRY * qglTexCoord2dv )(const GLdouble *v);
+extern void ( APIENTRY * qglTexCoord2f )(GLfloat s, GLfloat t);
+extern void ( APIENTRY * qglTexCoord2fv )(const GLfloat *v);
+extern void ( APIENTRY * qglTexCoord2i )(GLint s, GLint t);
+extern void ( APIENTRY * qglTexCoord2iv )(const GLint *v);
+extern void ( APIENTRY * qglTexCoord2s )(GLshort s, GLshort t);
+extern void ( APIENTRY * qglTexCoord2sv )(const GLshort *v);
+extern void ( APIENTRY * qglTexCoord3d )(GLdouble s, GLdouble t, GLdouble r);
+extern void ( APIENTRY * qglTexCoord3dv )(const GLdouble *v);
+extern void ( APIENTRY * qglTexCoord3f )(GLfloat s, GLfloat t, GLfloat r);
+extern void ( APIENTRY * qglTexCoord3fv )(const GLfloat *v);
+extern void ( APIENTRY * qglTexCoord3i )(GLint s, GLint t, GLint r);
+extern void ( APIENTRY * qglTexCoord3iv )(const GLint *v);
+extern void ( APIENTRY * qglTexCoord3s )(GLshort s, GLshort t, GLshort r);
+extern void ( APIENTRY * qglTexCoord3sv )(const GLshort *v);
+extern void ( APIENTRY * qglTexCoord4d )(GLdouble s, GLdouble t, GLdouble r, GLdouble q);
+extern void ( APIENTRY * qglTexCoord4dv )(const GLdouble *v);
+extern void ( APIENTRY * qglTexCoord4f )(GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+extern void ( APIENTRY * qglTexCoord4fv )(const GLfloat *v);
+extern void ( APIENTRY * qglTexCoord4i )(GLint s, GLint t, GLint r, GLint q);
+extern void ( APIENTRY * qglTexCoord4iv )(const GLint *v);
+extern void ( APIENTRY * qglTexCoord4s )(GLshort s, GLshort t, GLshort r, GLshort q);
+extern void ( APIENTRY * qglTexCoord4sv )(const GLshort *v);
+extern void ( APIENTRY * qglTexCoordPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+extern void ( APIENTRY * qglTexEnvf )(GLenum target, GLenum pname, GLfloat param);
+extern void ( APIENTRY * qglTexEnvfv )(GLenum target, GLenum pname, const GLfloat *params);
+extern void ( APIENTRY * qglTexEnvi )(GLenum target, GLenum pname, GLint param);
+extern void ( APIENTRY * qglTexEnviv )(GLenum target, GLenum pname, const GLint *params);
+extern void ( APIENTRY * qglTexGend )(GLenum coord, GLenum pname, GLdouble param);
+extern void ( APIENTRY * qglTexGendv )(GLenum coord, GLenum pname, const GLdouble *params);
+extern void ( APIENTRY * qglTexGenf )(GLenum coord, GLenum pname, GLfloat param);
+extern void ( APIENTRY * qglTexGenfv )(GLenum coord, GLenum pname, const GLfloat *params);
+extern void ( APIENTRY * qglTexGeni )(GLenum coord, GLenum pname, GLint param);
+extern void ( APIENTRY * qglTexGeniv )(GLenum coord, GLenum pname, const GLint *params);
+extern void ( APIENTRY * qglTexImage1D )(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+extern void ( APIENTRY * qglTexImage2D )(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+extern void ( APIENTRY * qglTexParameterf )(GLenum target, GLenum pname, GLfloat param);
+extern void ( APIENTRY * qglTexParameterfv )(GLenum target, GLenum pname, const GLfloat *params);
+extern void ( APIENTRY * qglTexParameteri )(GLenum target, GLenum pname, GLint param);
+extern void ( APIENTRY * qglTexParameteriv )(GLenum target, GLenum pname, const GLint *params);
+extern void ( APIENTRY * qglTexSubImage1D )(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels);
+extern void ( APIENTRY * qglTexSubImage2D )(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+extern void ( APIENTRY * qglTranslated )(GLdouble x, GLdouble y, GLdouble z);
+extern void ( APIENTRY * qglTranslatef )(GLfloat x, GLfloat y, GLfloat z);
+extern void ( APIENTRY * qglVertex2d )(GLdouble x, GLdouble y);
+extern void ( APIENTRY * qglVertex2dv )(const GLdouble *v);
+extern void ( APIENTRY * qglVertex2f )(GLfloat x, GLfloat y);
+extern void ( APIENTRY * qglVertex2fv )(const GLfloat *v);
+extern void ( APIENTRY * qglVertex2i )(GLint x, GLint y);
+extern void ( APIENTRY * qglVertex2iv )(const GLint *v);
+extern void ( APIENTRY * qglVertex2s )(GLshort x, GLshort y);
+extern void ( APIENTRY * qglVertex2sv )(const GLshort *v);
+extern void ( APIENTRY * qglVertex3d )(GLdouble x, GLdouble y, GLdouble z);
+extern void ( APIENTRY * qglVertex3dv )(const GLdouble *v);
+extern void ( APIENTRY * qglVertex3f )(GLfloat x, GLfloat y, GLfloat z);
+extern void ( APIENTRY * qglVertex3fv )(const GLfloat *v);
+extern void ( APIENTRY * qglVertex3i )(GLint x, GLint y, GLint z);
+extern void ( APIENTRY * qglVertex3iv )(const GLint *v);
+extern void ( APIENTRY * qglVertex3s )(GLshort x, GLshort y, GLshort z);
+extern void ( APIENTRY * qglVertex3sv )(const GLshort *v);
+extern void ( APIENTRY * qglVertex4d )(GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+extern void ( APIENTRY * qglVertex4dv )(const GLdouble *v);
+extern void ( APIENTRY * qglVertex4f )(GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+extern void ( APIENTRY * qglVertex4fv )(const GLfloat *v);
+extern void ( APIENTRY * qglVertex4i )(GLint x, GLint y, GLint z, GLint w);
+extern void ( APIENTRY * qglVertex4iv )(const GLint *v);
+extern void ( APIENTRY * qglVertex4s )(GLshort x, GLshort y, GLshort z, GLshort w);
+extern void ( APIENTRY * qglVertex4sv )(const GLshort *v);
+extern void ( APIENTRY * qglVertexPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+extern void ( APIENTRY * qglViewport )(GLint x, GLint y, GLsizei width, GLsizei height);
+
+extern void ( APIENTRY * qglPointParameterfEXT)( GLenum param, GLfloat value );
+extern void ( APIENTRY * qglPointParameterfvEXT)( GLenum param, const GLfloat *value );
+extern void ( APIENTRY * qglColorTableEXT)( int, int, int, int, int, const void * );
+
+extern void ( APIENTRY * qglMTexCoord2fSGIS)( GLenum, GLfloat, GLfloat );
+extern void ( APIENTRY * qglSelectTextureSGIS)( GLenum );
+
+#ifdef _WIN32
+
+extern int ( WINAPI * qwglChoosePixelFormat )(HDC, CONST PIXELFORMATDESCRIPTOR *);
+extern int ( WINAPI * qwglDescribePixelFormat) (HDC, int, UINT, LPPIXELFORMATDESCRIPTOR);
+extern int ( WINAPI * qwglGetPixelFormat)(HDC);
+extern BOOL ( WINAPI * qwglSetPixelFormat)(HDC, int, CONST PIXELFORMATDESCRIPTOR *);
+extern BOOL ( WINAPI * qwglSwapBuffers)(HDC);
+
+extern BOOL ( WINAPI * qwglCopyContext)(HGLRC, HGLRC, UINT);
+extern HGLRC ( WINAPI * qwglCreateContext)(HDC);
+extern HGLRC ( WINAPI * qwglCreateLayerContext)(HDC, int);
+extern BOOL ( WINAPI * qwglDeleteContext)(HGLRC);
+extern HGLRC ( WINAPI * qwglGetCurrentContext)(VOID);
+extern HDC ( WINAPI * qwglGetCurrentDC)(VOID);
+extern PROC ( WINAPI * qwglGetProcAddress)(LPCSTR);
+extern BOOL ( WINAPI * qwglMakeCurrent)(HDC, HGLRC);
+extern BOOL ( WINAPI * qwglShareLists)(HGLRC, HGLRC);
+extern BOOL ( WINAPI * qwglUseFontBitmaps)(HDC, DWORD, DWORD, DWORD);
+
+extern BOOL ( WINAPI * qwglUseFontOutlines)(HDC, DWORD, DWORD, DWORD, FLOAT,
+ FLOAT, int, LPGLYPHMETRICSFLOAT);
+
+extern BOOL ( WINAPI * qwglDescribeLayerPlane)(HDC, int, int, UINT,
+ LPLAYERPLANEDESCRIPTOR);
+extern int ( WINAPI * qwglSetLayerPaletteEntries)(HDC, int, int, int,
+ CONST COLORREF *);
+extern int ( WINAPI * qwglGetLayerPaletteEntries)(HDC, int, int, int,
+ COLORREF *);
+extern BOOL ( WINAPI * qwglRealizeLayerPalette)(HDC, int, BOOL);
+extern BOOL ( WINAPI * qwglSwapLayerBuffers)(HDC, UINT);
+
+extern BOOL ( WINAPI * qwglSwapIntervalEXT)( int interval );
+
+extern BOOL ( WINAPI * qwglGetDeviceGammaRampEXT ) ( unsigned char *pRed, unsigned char *pGreen, unsigned char *pBlue );
+extern BOOL ( WINAPI * qwglSetDeviceGammaRampEXT ) ( const unsigned char *pRed, const unsigned char *pGreen, const unsigned char *pBlue );
+
+#endif
+
+// glu stuff.. radiant only uses a couple
+extern int (APIENTRY* qgluBuild2DMipmaps) (GLenum target, GLint components, GLint width, GLint height, GLenum format, GLenum type, const void *data);
+extern void (APIENTRY* qgluPerspective) (GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar);
+extern void (APIENTRY* qgluLookAt)(
+ GLdouble eyex,
+ GLdouble eyey,
+ GLdouble eyez,
+ GLdouble centerx,
+ GLdouble centery,
+ GLdouble centerz,
+ GLdouble upx,
+ GLdouble upy,
+ GLdouble upz);
+
+
+// end of glu stuff
+
+
+/*
+** extension constants
+*/
+#define GL_POINT_SIZE_MIN_EXT 0x8126
+#define GL_POINT_SIZE_MAX_EXT 0x8127
+#define GL_POINT_FADE_THRESHOLD_SIZE_EXT 0x8128
+#define GL_DISTANCE_ATTENUATION_EXT 0x8129
+
+#define GL_SHARED_TEXTURE_PALETTE_EXT 0x81FB
+
+#define GL_TEXTURE0_SGIS 0x835E
+#define GL_TEXTURE1_SGIS 0x835F
+
+#endif
diff --git a/q3radiant/QGL_WIN.C b/q3radiant/QGL_WIN.C
new file mode 100755
index 0000000..d2690c6
--- /dev/null
+++ b/q3radiant/QGL_WIN.C
@@ -0,0 +1,1230 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+/*
+** QGL_WIN.C
+**
+** This file implements the operating system binding of GL to QGL function
+** pointers. When doing a port of Quake2 you must implement the following
+** two functions:
+**
+** QGL_Init() - loads libraries, assigns function pointers, etc.
+** QGL_Shutdown() - unloads libraries, NULLs function pointers
+*/
+#include "qgl.h"
+#include <float.h>
+
+HMODULE g_hGLDLL;
+HMODULE g_hGLUDLL;
+
+# pragma warning (disable : 4113 4133 4047 )
+
+int ( WINAPI * qwglChoosePixelFormat )(HDC, CONST PIXELFORMATDESCRIPTOR *);
+int ( WINAPI * qwglDescribePixelFormat) (HDC, int, UINT, LPPIXELFORMATDESCRIPTOR);
+int ( WINAPI * qwglGetPixelFormat)(HDC);
+BOOL ( WINAPI * qwglSetPixelFormat)(HDC, int, CONST PIXELFORMATDESCRIPTOR *);
+BOOL ( WINAPI * qwglSwapBuffers)(HDC);
+
+BOOL ( WINAPI * qwglCopyContext)(HGLRC, HGLRC, UINT);
+HGLRC ( WINAPI * qwglCreateContext)(HDC);
+HGLRC ( WINAPI * qwglCreateLayerContext)(HDC, int);
+BOOL ( WINAPI * qwglDeleteContext)(HGLRC);
+HGLRC ( WINAPI * qwglGetCurrentContext)(VOID);
+HDC ( WINAPI * qwglGetCurrentDC)(VOID);
+PROC ( WINAPI * qwglGetProcAddress)(LPCSTR);
+BOOL ( WINAPI * qwglMakeCurrent)(HDC, HGLRC);
+BOOL ( WINAPI * qwglShareLists)(HGLRC, HGLRC);
+BOOL ( WINAPI * qwglUseFontBitmaps)(HDC, DWORD, DWORD, DWORD);
+
+BOOL ( WINAPI * qwglUseFontOutlines)(HDC, DWORD, DWORD, DWORD, FLOAT,
+ FLOAT, int, LPGLYPHMETRICSFLOAT);
+
+BOOL ( WINAPI * qwglDescribeLayerPlane)(HDC, int, int, UINT,
+ LPLAYERPLANEDESCRIPTOR);
+int ( WINAPI * qwglSetLayerPaletteEntries)(HDC, int, int, int,
+ CONST COLORREF *);
+int ( WINAPI * qwglGetLayerPaletteEntries)(HDC, int, int, int,
+ COLORREF *);
+BOOL ( WINAPI * qwglRealizeLayerPalette)(HDC, int, BOOL);
+BOOL ( WINAPI * qwglSwapLayerBuffers)(HDC, UINT);
+
+void ( APIENTRY * qglAccum )(GLenum op, GLfloat value);
+void ( APIENTRY * qglAlphaFunc )(GLenum func, GLclampf ref);
+GLboolean ( APIENTRY * qglAreTexturesResident )(GLsizei n, const GLuint *textures, GLboolean *residences);
+void ( APIENTRY * qglArrayElement )(GLint i);
+void ( APIENTRY * qglBegin )(GLenum mode);
+void ( APIENTRY * qglBindTexture )(GLenum target, GLuint texture);
+void ( APIENTRY * qglBitmap )(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap);
+void ( APIENTRY * qglBlendFunc )(GLenum sfactor, GLenum dfactor);
+void ( APIENTRY * qglCallList )(GLuint list);
+void ( APIENTRY * qglCallLists )(GLsizei n, GLenum type, const GLvoid *lists);
+void ( APIENTRY * qglClear )(GLbitfield mask);
+void ( APIENTRY * qglClearAccum )(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+void ( APIENTRY * qglClearColor )(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+void ( APIENTRY * qglClearDepth )(GLclampd depth);
+void ( APIENTRY * qglClearIndex )(GLfloat c);
+void ( APIENTRY * qglClearStencil )(GLint s);
+void ( APIENTRY * qglClipPlane )(GLenum plane, const GLdouble *equation);
+void ( APIENTRY * qglColor3b )(GLbyte red, GLbyte green, GLbyte blue);
+void ( APIENTRY * qglColor3bv )(const GLbyte *v);
+void ( APIENTRY * qglColor3d )(GLdouble red, GLdouble green, GLdouble blue);
+void ( APIENTRY * qglColor3dv )(const GLdouble *v);
+void ( APIENTRY * qglColor3f )(GLfloat red, GLfloat green, GLfloat blue);
+void ( APIENTRY * qglColor3fv )(const GLfloat *v);
+void ( APIENTRY * qglColor3i )(GLint red, GLint green, GLint blue);
+void ( APIENTRY * qglColor3iv )(const GLint *v);
+void ( APIENTRY * qglColor3s )(GLshort red, GLshort green, GLshort blue);
+void ( APIENTRY * qglColor3sv )(const GLshort *v);
+void ( APIENTRY * qglColor3ub )(GLubyte red, GLubyte green, GLubyte blue);
+void ( APIENTRY * qglColor3ubv )(const GLubyte *v);
+void ( APIENTRY * qglColor3ui )(GLuint red, GLuint green, GLuint blue);
+void ( APIENTRY * qglColor3uiv )(const GLuint *v);
+void ( APIENTRY * qglColor3us )(GLushort red, GLushort green, GLushort blue);
+void ( APIENTRY * qglColor3usv )(const GLushort *v);
+void ( APIENTRY * qglColor4b )(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha);
+void ( APIENTRY * qglColor4bv )(const GLbyte *v);
+void ( APIENTRY * qglColor4d )(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha);
+void ( APIENTRY * qglColor4dv )(const GLdouble *v);
+void ( APIENTRY * qglColor4f )(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+void ( APIENTRY * qglColor4fv )(const GLfloat *v);
+void ( APIENTRY * qglColor4i )(GLint red, GLint green, GLint blue, GLint alpha);
+void ( APIENTRY * qglColor4iv )(const GLint *v);
+void ( APIENTRY * qglColor4s )(GLshort red, GLshort green, GLshort blue, GLshort alpha);
+void ( APIENTRY * qglColor4sv )(const GLshort *v);
+void ( APIENTRY * qglColor4ub )(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha);
+void ( APIENTRY * qglColor4ubv )(const GLubyte *v);
+void ( APIENTRY * qglColor4ui )(GLuint red, GLuint green, GLuint blue, GLuint alpha);
+void ( APIENTRY * qglColor4uiv )(const GLuint *v);
+void ( APIENTRY * qglColor4us )(GLushort red, GLushort green, GLushort blue, GLushort alpha);
+void ( APIENTRY * qglColor4usv )(const GLushort *v);
+void ( APIENTRY * qglColorMask )(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
+void ( APIENTRY * qglColorMaterial )(GLenum face, GLenum mode);
+void ( APIENTRY * qglColorPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+void ( APIENTRY * qglCopyPixels )(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type);
+void ( APIENTRY * qglCopyTexImage1D )(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLint border);
+void ( APIENTRY * qglCopyTexImage2D )(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+void ( APIENTRY * qglCopyTexSubImage1D )(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
+void ( APIENTRY * qglCopyTexSubImage2D )(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+void ( APIENTRY * qglCullFace )(GLenum mode);
+void ( APIENTRY * qglDeleteLists )(GLuint list, GLsizei range);
+void ( APIENTRY * qglDeleteTextures )(GLsizei n, const GLuint *textures);
+void ( APIENTRY * qglDepthFunc )(GLenum func);
+void ( APIENTRY * qglDepthMask )(GLboolean flag);
+void ( APIENTRY * qglDepthRange )(GLclampd zNear, GLclampd zFar);
+void ( APIENTRY * qglDisable )(GLenum cap);
+void ( APIENTRY * qglDisableClientState )(GLenum array);
+void ( APIENTRY * qglDrawArrays )(GLenum mode, GLint first, GLsizei count);
+void ( APIENTRY * qglDrawBuffer )(GLenum mode);
+void ( APIENTRY * qglDrawElements )(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices);
+void ( APIENTRY * qglDrawPixels )(GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+void ( APIENTRY * qglEdgeFlag )(GLboolean flag);
+void ( APIENTRY * qglEdgeFlagPointer )(GLsizei stride, const GLvoid *pointer);
+void ( APIENTRY * qglEdgeFlagv )(const GLboolean *flag);
+void ( APIENTRY * qglEnable )(GLenum cap);
+void ( APIENTRY * qglEnableClientState )(GLenum array);
+void ( APIENTRY * qglEnd )(void);
+void ( APIENTRY * qglEndList )(void);
+void ( APIENTRY * qglEvalCoord1d )(GLdouble u);
+void ( APIENTRY * qglEvalCoord1dv )(const GLdouble *u);
+void ( APIENTRY * qglEvalCoord1f )(GLfloat u);
+void ( APIENTRY * qglEvalCoord1fv )(const GLfloat *u);
+void ( APIENTRY * qglEvalCoord2d )(GLdouble u, GLdouble v);
+void ( APIENTRY * qglEvalCoord2dv )(const GLdouble *u);
+void ( APIENTRY * qglEvalCoord2f )(GLfloat u, GLfloat v);
+void ( APIENTRY * qglEvalCoord2fv )(const GLfloat *u);
+void ( APIENTRY * qglEvalMesh1 )(GLenum mode, GLint i1, GLint i2);
+void ( APIENTRY * qglEvalMesh2 )(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2);
+void ( APIENTRY * qglEvalPoint1 )(GLint i);
+void ( APIENTRY * qglEvalPoint2 )(GLint i, GLint j);
+void ( APIENTRY * qglFeedbackBuffer )(GLsizei size, GLenum type, GLfloat *buffer);
+void ( APIENTRY * qglFinish )(void);
+void ( APIENTRY * qglFlush )(void);
+void ( APIENTRY * qglFogf )(GLenum pname, GLfloat param);
+void ( APIENTRY * qglFogfv )(GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglFogi )(GLenum pname, GLint param);
+void ( APIENTRY * qglFogiv )(GLenum pname, const GLint *params);
+void ( APIENTRY * qglFrontFace )(GLenum mode);
+void ( APIENTRY * qglFrustum )(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+GLuint ( APIENTRY * qglGenLists )(GLsizei range);
+void ( APIENTRY * qglGenTextures )(GLsizei n, GLuint *textures);
+void ( APIENTRY * qglGetBooleanv )(GLenum pname, GLboolean *params);
+void ( APIENTRY * qglGetClipPlane )(GLenum plane, GLdouble *equation);
+void ( APIENTRY * qglGetDoublev )(GLenum pname, GLdouble *params);
+GLenum ( APIENTRY * qglGetError )(void);
+void ( APIENTRY * qglGetFloatv )(GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetIntegerv )(GLenum pname, GLint *params);
+void ( APIENTRY * qglGetLightfv )(GLenum light, GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetLightiv )(GLenum light, GLenum pname, GLint *params);
+void ( APIENTRY * qglGetMapdv )(GLenum target, GLenum query, GLdouble *v);
+void ( APIENTRY * qglGetMapfv )(GLenum target, GLenum query, GLfloat *v);
+void ( APIENTRY * qglGetMapiv )(GLenum target, GLenum query, GLint *v);
+void ( APIENTRY * qglGetMaterialfv )(GLenum face, GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetMaterialiv )(GLenum face, GLenum pname, GLint *params);
+void ( APIENTRY * qglGetPixelMapfv )(GLenum map, GLfloat *values);
+void ( APIENTRY * qglGetPixelMapuiv )(GLenum map, GLuint *values);
+void ( APIENTRY * qglGetPixelMapusv )(GLenum map, GLushort *values);
+void ( APIENTRY * qglGetPointerv )(GLenum pname, GLvoid* *params);
+void ( APIENTRY * qglGetPolygonStipple )(GLubyte *mask);
+const GLubyte * ( APIENTRY * qglGetString )(GLenum name);
+void ( APIENTRY * qglGetTexEnvfv )(GLenum target, GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetTexEnviv )(GLenum target, GLenum pname, GLint *params);
+void ( APIENTRY * qglGetTexGendv )(GLenum coord, GLenum pname, GLdouble *params);
+void ( APIENTRY * qglGetTexGenfv )(GLenum coord, GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetTexGeniv )(GLenum coord, GLenum pname, GLint *params);
+void ( APIENTRY * qglGetTexImage )(GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels);
+void ( APIENTRY * qglGetTexLevelParameterfv )(GLenum target, GLint level, GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetTexLevelParameteriv )(GLenum target, GLint level, GLenum pname, GLint *params);
+void ( APIENTRY * qglGetTexParameterfv )(GLenum target, GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetTexParameteriv )(GLenum target, GLenum pname, GLint *params);
+void ( APIENTRY * qglHint )(GLenum target, GLenum mode);
+void ( APIENTRY * qglIndexMask )(GLuint mask);
+void ( APIENTRY * qglIndexPointer )(GLenum type, GLsizei stride, const GLvoid *pointer);
+void ( APIENTRY * qglIndexd )(GLdouble c);
+void ( APIENTRY * qglIndexdv )(const GLdouble *c);
+void ( APIENTRY * qglIndexf )(GLfloat c);
+void ( APIENTRY * qglIndexfv )(const GLfloat *c);
+void ( APIENTRY * qglIndexi )(GLint c);
+void ( APIENTRY * qglIndexiv )(const GLint *c);
+void ( APIENTRY * qglIndexs )(GLshort c);
+void ( APIENTRY * qglIndexsv )(const GLshort *c);
+void ( APIENTRY * qglIndexub )(GLubyte c);
+void ( APIENTRY * qglIndexubv )(const GLubyte *c);
+void ( APIENTRY * qglInitNames )(void);
+void ( APIENTRY * qglInterleavedArrays )(GLenum format, GLsizei stride, const GLvoid *pointer);
+GLboolean ( APIENTRY * qglIsEnabled )(GLenum cap);
+GLboolean ( APIENTRY * qglIsList )(GLuint list);
+GLboolean ( APIENTRY * qglIsTexture )(GLuint texture);
+void ( APIENTRY * qglLightModelf )(GLenum pname, GLfloat param);
+void ( APIENTRY * qglLightModelfv )(GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglLightModeli )(GLenum pname, GLint param);
+void ( APIENTRY * qglLightModeliv )(GLenum pname, const GLint *params);
+void ( APIENTRY * qglLightf )(GLenum light, GLenum pname, GLfloat param);
+void ( APIENTRY * qglLightfv )(GLenum light, GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglLighti )(GLenum light, GLenum pname, GLint param);
+void ( APIENTRY * qglLightiv )(GLenum light, GLenum pname, const GLint *params);
+void ( APIENTRY * qglLineStipple )(GLint factor, GLushort pattern);
+void ( APIENTRY * qglLineWidth )(GLfloat width);
+void ( APIENTRY * qglListBase )(GLuint base);
+void ( APIENTRY * qglLoadIdentity )(void);
+void ( APIENTRY * qglLoadMatrixd )(const GLdouble *m);
+void ( APIENTRY * qglLoadMatrixf )(const GLfloat *m);
+void ( APIENTRY * qglLoadName )(GLuint name);
+void ( APIENTRY * qglLogicOp )(GLenum opcode);
+void ( APIENTRY * qglMap1d )(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points);
+void ( APIENTRY * qglMap1f )(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points);
+void ( APIENTRY * qglMap2d )(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points);
+void ( APIENTRY * qglMap2f )(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points);
+void ( APIENTRY * qglMapGrid1d )(GLint un, GLdouble u1, GLdouble u2);
+void ( APIENTRY * qglMapGrid1f )(GLint un, GLfloat u1, GLfloat u2);
+void ( APIENTRY * qglMapGrid2d )(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2);
+void ( APIENTRY * qglMapGrid2f )(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2);
+void ( APIENTRY * qglMaterialf )(GLenum face, GLenum pname, GLfloat param);
+void ( APIENTRY * qglMaterialfv )(GLenum face, GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglMateriali )(GLenum face, GLenum pname, GLint param);
+void ( APIENTRY * qglMaterialiv )(GLenum face, GLenum pname, const GLint *params);
+void ( APIENTRY * qglMatrixMode )(GLenum mode);
+void ( APIENTRY * qglMultMatrixd )(const GLdouble *m);
+void ( APIENTRY * qglMultMatrixf )(const GLfloat *m);
+void ( APIENTRY * qglNewList )(GLuint list, GLenum mode);
+void ( APIENTRY * qglNormal3b )(GLbyte nx, GLbyte ny, GLbyte nz);
+void ( APIENTRY * qglNormal3bv )(const GLbyte *v);
+void ( APIENTRY * qglNormal3d )(GLdouble nx, GLdouble ny, GLdouble nz);
+void ( APIENTRY * qglNormal3dv )(const GLdouble *v);
+void ( APIENTRY * qglNormal3f )(GLfloat nx, GLfloat ny, GLfloat nz);
+void ( APIENTRY * qglNormal3fv )(const GLfloat *v);
+void ( APIENTRY * qglNormal3i )(GLint nx, GLint ny, GLint nz);
+void ( APIENTRY * qglNormal3iv )(const GLint *v);
+void ( APIENTRY * qglNormal3s )(GLshort nx, GLshort ny, GLshort nz);
+void ( APIENTRY * qglNormal3sv )(const GLshort *v);
+void ( APIENTRY * qglNormalPointer )(GLenum type, GLsizei stride, const GLvoid *pointer);
+void ( APIENTRY * qglOrtho )(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+void ( APIENTRY * qglPassThrough )(GLfloat token);
+void ( APIENTRY * qglPixelMapfv )(GLenum map, GLsizei mapsize, const GLfloat *values);
+void ( APIENTRY * qglPixelMapuiv )(GLenum map, GLsizei mapsize, const GLuint *values);
+void ( APIENTRY * qglPixelMapusv )(GLenum map, GLsizei mapsize, const GLushort *values);
+void ( APIENTRY * qglPixelStoref )(GLenum pname, GLfloat param);
+void ( APIENTRY * qglPixelStorei )(GLenum pname, GLint param);
+void ( APIENTRY * qglPixelTransferf )(GLenum pname, GLfloat param);
+void ( APIENTRY * qglPixelTransferi )(GLenum pname, GLint param);
+void ( APIENTRY * qglPixelZoom )(GLfloat xfactor, GLfloat yfactor);
+void ( APIENTRY * qglPointSize )(GLfloat size);
+void ( APIENTRY * qglPolygonMode )(GLenum face, GLenum mode);
+void ( APIENTRY * qglPolygonOffset )(GLfloat factor, GLfloat units);
+void ( APIENTRY * qglPolygonStipple )(const GLubyte *mask);
+void ( APIENTRY * qglPopAttrib )(void);
+void ( APIENTRY * qglPopClientAttrib )(void);
+void ( APIENTRY * qglPopMatrix )(void);
+void ( APIENTRY * qglPopName )(void);
+void ( APIENTRY * qglPrioritizeTextures )(GLsizei n, const GLuint *textures, const GLclampf *priorities);
+void ( APIENTRY * qglPushAttrib )(GLbitfield mask);
+void ( APIENTRY * qglPushClientAttrib )(GLbitfield mask);
+void ( APIENTRY * qglPushMatrix )(void);
+void ( APIENTRY * qglPushName )(GLuint name);
+void ( APIENTRY * qglRasterPos2d )(GLdouble x, GLdouble y);
+void ( APIENTRY * qglRasterPos2dv )(const GLdouble *v);
+void ( APIENTRY * qglRasterPos2f )(GLfloat x, GLfloat y);
+void ( APIENTRY * qglRasterPos2fv )(const GLfloat *v);
+void ( APIENTRY * qglRasterPos2i )(GLint x, GLint y);
+void ( APIENTRY * qglRasterPos2iv )(const GLint *v);
+void ( APIENTRY * qglRasterPos2s )(GLshort x, GLshort y);
+void ( APIENTRY * qglRasterPos2sv )(const GLshort *v);
+void ( APIENTRY * qglRasterPos3d )(GLdouble x, GLdouble y, GLdouble z);
+void ( APIENTRY * qglRasterPos3dv )(const GLdouble *v);
+void ( APIENTRY * qglRasterPos3f )(GLfloat x, GLfloat y, GLfloat z);
+void ( APIENTRY * qglRasterPos3fv )(const GLfloat *v);
+void ( APIENTRY * qglRasterPos3i )(GLint x, GLint y, GLint z);
+void ( APIENTRY * qglRasterPos3iv )(const GLint *v);
+void ( APIENTRY * qglRasterPos3s )(GLshort x, GLshort y, GLshort z);
+void ( APIENTRY * qglRasterPos3sv )(const GLshort *v);
+void ( APIENTRY * qglRasterPos4d )(GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+void ( APIENTRY * qglRasterPos4dv )(const GLdouble *v);
+void ( APIENTRY * qglRasterPos4f )(GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+void ( APIENTRY * qglRasterPos4fv )(const GLfloat *v);
+void ( APIENTRY * qglRasterPos4i )(GLint x, GLint y, GLint z, GLint w);
+void ( APIENTRY * qglRasterPos4iv )(const GLint *v);
+void ( APIENTRY * qglRasterPos4s )(GLshort x, GLshort y, GLshort z, GLshort w);
+void ( APIENTRY * qglRasterPos4sv )(const GLshort *v);
+void ( APIENTRY * qglReadBuffer )(GLenum mode);
+void ( APIENTRY * qglReadPixels )(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels);
+void ( APIENTRY * qglRectd )(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2);
+void ( APIENTRY * qglRectdv )(const GLdouble *v1, const GLdouble *v2);
+void ( APIENTRY * qglRectf )(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2);
+void ( APIENTRY * qglRectfv )(const GLfloat *v1, const GLfloat *v2);
+void ( APIENTRY * qglRecti )(GLint x1, GLint y1, GLint x2, GLint y2);
+void ( APIENTRY * qglRectiv )(const GLint *v1, const GLint *v2);
+void ( APIENTRY * qglRects )(GLshort x1, GLshort y1, GLshort x2, GLshort y2);
+void ( APIENTRY * qglRectsv )(const GLshort *v1, const GLshort *v2);
+GLint ( APIENTRY * qglRenderMode )(GLenum mode);
+void ( APIENTRY * qglRotated )(GLdouble angle, GLdouble x, GLdouble y, GLdouble z);
+void ( APIENTRY * qglRotatef )(GLfloat angle, GLfloat x, GLfloat y, GLfloat z);
+void ( APIENTRY * qglScaled )(GLdouble x, GLdouble y, GLdouble z);
+void ( APIENTRY * qglScalef )(GLfloat x, GLfloat y, GLfloat z);
+void ( APIENTRY * qglScissor )(GLint x, GLint y, GLsizei width, GLsizei height);
+void ( APIENTRY * qglSelectBuffer )(GLsizei size, GLuint *buffer);
+void ( APIENTRY * qglShadeModel )(GLenum mode);
+void ( APIENTRY * qglStencilFunc )(GLenum func, GLint ref, GLuint mask);
+void ( APIENTRY * qglStencilMask )(GLuint mask);
+void ( APIENTRY * qglStencilOp )(GLenum fail, GLenum zfail, GLenum zpass);
+void ( APIENTRY * qglTexCoord1d )(GLdouble s);
+void ( APIENTRY * qglTexCoord1dv )(const GLdouble *v);
+void ( APIENTRY * qglTexCoord1f )(GLfloat s);
+void ( APIENTRY * qglTexCoord1fv )(const GLfloat *v);
+void ( APIENTRY * qglTexCoord1i )(GLint s);
+void ( APIENTRY * qglTexCoord1iv )(const GLint *v);
+void ( APIENTRY * qglTexCoord1s )(GLshort s);
+void ( APIENTRY * qglTexCoord1sv )(const GLshort *v);
+void ( APIENTRY * qglTexCoord2d )(GLdouble s, GLdouble t);
+void ( APIENTRY * qglTexCoord2dv )(const GLdouble *v);
+void ( APIENTRY * qglTexCoord2f )(GLfloat s, GLfloat t);
+void ( APIENTRY * qglTexCoord2fv )(const GLfloat *v);
+void ( APIENTRY * qglTexCoord2i )(GLint s, GLint t);
+void ( APIENTRY * qglTexCoord2iv )(const GLint *v);
+void ( APIENTRY * qglTexCoord2s )(GLshort s, GLshort t);
+void ( APIENTRY * qglTexCoord2sv )(const GLshort *v);
+void ( APIENTRY * qglTexCoord3d )(GLdouble s, GLdouble t, GLdouble r);
+void ( APIENTRY * qglTexCoord3dv )(const GLdouble *v);
+void ( APIENTRY * qglTexCoord3f )(GLfloat s, GLfloat t, GLfloat r);
+void ( APIENTRY * qglTexCoord3fv )(const GLfloat *v);
+void ( APIENTRY * qglTexCoord3i )(GLint s, GLint t, GLint r);
+void ( APIENTRY * qglTexCoord3iv )(const GLint *v);
+void ( APIENTRY * qglTexCoord3s )(GLshort s, GLshort t, GLshort r);
+void ( APIENTRY * qglTexCoord3sv )(const GLshort *v);
+void ( APIENTRY * qglTexCoord4d )(GLdouble s, GLdouble t, GLdouble r, GLdouble q);
+void ( APIENTRY * qglTexCoord4dv )(const GLdouble *v);
+void ( APIENTRY * qglTexCoord4f )(GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+void ( APIENTRY * qglTexCoord4fv )(const GLfloat *v);
+void ( APIENTRY * qglTexCoord4i )(GLint s, GLint t, GLint r, GLint q);
+void ( APIENTRY * qglTexCoord4iv )(const GLint *v);
+void ( APIENTRY * qglTexCoord4s )(GLshort s, GLshort t, GLshort r, GLshort q);
+void ( APIENTRY * qglTexCoord4sv )(const GLshort *v);
+void ( APIENTRY * qglTexCoordPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+void ( APIENTRY * qglTexEnvf )(GLenum target, GLenum pname, GLfloat param);
+void ( APIENTRY * qglTexEnvfv )(GLenum target, GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglTexEnvi )(GLenum target, GLenum pname, GLint param);
+void ( APIENTRY * qglTexEnviv )(GLenum target, GLenum pname, const GLint *params);
+void ( APIENTRY * qglTexGend )(GLenum coord, GLenum pname, GLdouble param);
+void ( APIENTRY * qglTexGendv )(GLenum coord, GLenum pname, const GLdouble *params);
+void ( APIENTRY * qglTexGenf )(GLenum coord, GLenum pname, GLfloat param);
+void ( APIENTRY * qglTexGenfv )(GLenum coord, GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglTexGeni )(GLenum coord, GLenum pname, GLint param);
+void ( APIENTRY * qglTexGeniv )(GLenum coord, GLenum pname, const GLint *params);
+void ( APIENTRY * qglTexImage1D )(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+void ( APIENTRY * qglTexImage2D )(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+void ( APIENTRY * qglTexParameterf )(GLenum target, GLenum pname, GLfloat param);
+void ( APIENTRY * qglTexParameterfv )(GLenum target, GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglTexParameteri )(GLenum target, GLenum pname, GLint param);
+void ( APIENTRY * qglTexParameteriv )(GLenum target, GLenum pname, const GLint *params);
+void ( APIENTRY * qglTexSubImage1D )(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels);
+void ( APIENTRY * qglTexSubImage2D )(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+void ( APIENTRY * qglTranslated )(GLdouble x, GLdouble y, GLdouble z);
+void ( APIENTRY * qglTranslatef )(GLfloat x, GLfloat y, GLfloat z);
+void ( APIENTRY * qglVertex2d )(GLdouble x, GLdouble y);
+void ( APIENTRY * qglVertex2dv )(const GLdouble *v);
+void ( APIENTRY * qglVertex2f )(GLfloat x, GLfloat y);
+void ( APIENTRY * qglVertex2fv )(const GLfloat *v);
+void ( APIENTRY * qglVertex2i )(GLint x, GLint y);
+void ( APIENTRY * qglVertex2iv )(const GLint *v);
+void ( APIENTRY * qglVertex2s )(GLshort x, GLshort y);
+void ( APIENTRY * qglVertex2sv )(const GLshort *v);
+void ( APIENTRY * qglVertex3d )(GLdouble x, GLdouble y, GLdouble z);
+void ( APIENTRY * qglVertex3dv )(const GLdouble *v);
+void ( APIENTRY * qglVertex3f )(GLfloat x, GLfloat y, GLfloat z);
+void ( APIENTRY * qglVertex3fv )(const GLfloat *v);
+void ( APIENTRY * qglVertex3i )(GLint x, GLint y, GLint z);
+void ( APIENTRY * qglVertex3iv )(const GLint *v);
+void ( APIENTRY * qglVertex3s )(GLshort x, GLshort y, GLshort z);
+void ( APIENTRY * qglVertex3sv )(const GLshort *v);
+void ( APIENTRY * qglVertex4d )(GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+void ( APIENTRY * qglVertex4dv )(const GLdouble *v);
+void ( APIENTRY * qglVertex4f )(GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+void ( APIENTRY * qglVertex4fv )(const GLfloat *v);
+void ( APIENTRY * qglVertex4i )(GLint x, GLint y, GLint z, GLint w);
+void ( APIENTRY * qglVertex4iv )(const GLint *v);
+void ( APIENTRY * qglVertex4s )(GLshort x, GLshort y, GLshort z, GLshort w);
+void ( APIENTRY * qglVertex4sv )(const GLshort *v);
+void ( APIENTRY * qglVertexPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+void ( APIENTRY * qglViewport )(GLint x, GLint y, GLsizei width, GLsizei height);
+
+BOOL ( WINAPI * qwglSwapIntervalEXT)( int interval );
+BOOL ( WINAPI * qwglGetDeviceGammaRampEXT)( unsigned char *, unsigned char *, unsigned char * );
+BOOL ( WINAPI * qwglSetDeviceGammaRampEXT)( const unsigned char *, const unsigned char *, const unsigned char * );
+void ( APIENTRY * qglPointParameterfEXT)( GLenum param, GLfloat value );
+void ( APIENTRY * qglPointParameterfvEXT)( GLenum param, const GLfloat *value );
+void ( APIENTRY * qglColorTableEXT)( int, int, int, int, int, const void * );
+void ( APIENTRY * qglSelectTextureSGIS)( GLenum );
+void ( APIENTRY * qglMTexCoord2fSGIS)( GLenum, GLfloat, GLfloat );
+
+
+// glu stuff
+void (APIENTRY * qgluPerspective) (GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar);
+int (APIENTRY * qgluBuild2DMipmaps) (GLenum target, GLint components, GLint width, GLint height, GLenum format, GLenum type, const void *data);
+// added for plugins
+void (APIENTRY * qgluLookAt)(
+ GLdouble eyex,
+ GLdouble eyey,
+ GLdouble eyez,
+ GLdouble centerx,
+ GLdouble centery,
+ GLdouble centerz,
+ GLdouble upx,
+ GLdouble upy,
+ GLdouble upz);
+
+
+/*
+** QGL_Shutdown
+**
+** Unloads the specified DLL then nulls out all the proc pointers.
+*/
+void QGL_Shutdown()
+{
+ if (g_hGLDLL)
+ {
+ FreeLibrary(g_hGLDLL);
+ g_hGLDLL = NULL;
+ }
+ if (g_hGLUDLL)
+ {
+ FreeLibrary(g_hGLUDLL);
+ g_hGLUDLL = NULL;
+ }
+
+
+ qglAccum = NULL;
+ qglAlphaFunc = NULL;
+ qglAreTexturesResident = NULL;
+ qglArrayElement = NULL;
+ qglBegin = NULL;
+ qglBindTexture = NULL;
+ qglBitmap = NULL;
+ qglBlendFunc = NULL;
+ qglCallList = NULL;
+ qglCallLists = NULL;
+ qglClear = NULL;
+ qglClearAccum = NULL;
+ qglClearColor = NULL;
+ qglClearDepth = NULL;
+ qglClearIndex = NULL;
+ qglClearStencil = NULL;
+ qglClipPlane = NULL;
+ qglColor3b = NULL;
+ qglColor3bv = NULL;
+ qglColor3d = NULL;
+ qglColor3dv = NULL;
+ qglColor3f = NULL;
+ qglColor3fv = NULL;
+ qglColor3i = NULL;
+ qglColor3iv = NULL;
+ qglColor3s = NULL;
+ qglColor3sv = NULL;
+ qglColor3ub = NULL;
+ qglColor3ubv = NULL;
+ qglColor3ui = NULL;
+ qglColor3uiv = NULL;
+ qglColor3us = NULL;
+ qglColor3usv = NULL;
+ qglColor4b = NULL;
+ qglColor4bv = NULL;
+ qglColor4d = NULL;
+ qglColor4dv = NULL;
+ qglColor4f = NULL;
+ qglColor4fv = NULL;
+ qglColor4i = NULL;
+ qglColor4iv = NULL;
+ qglColor4s = NULL;
+ qglColor4sv = NULL;
+ qglColor4ub = NULL;
+ qglColor4ubv = NULL;
+ qglColor4ui = NULL;
+ qglColor4uiv = NULL;
+ qglColor4us = NULL;
+ qglColor4usv = NULL;
+ qglColorMask = NULL;
+ qglColorMaterial = NULL;
+ qglColorPointer = NULL;
+ qglCopyPixels = NULL;
+ qglCopyTexImage1D = NULL;
+ qglCopyTexImage2D = NULL;
+ qglCopyTexSubImage1D = NULL;
+ qglCopyTexSubImage2D = NULL;
+ qglCullFace = NULL;
+ qglDeleteLists = NULL;
+ qglDeleteTextures = NULL;
+ qglDepthFunc = NULL;
+ qglDepthMask = NULL;
+ qglDepthRange = NULL;
+ qglDisable = NULL;
+ qglDisableClientState = NULL;
+ qglDrawArrays = NULL;
+ qglDrawBuffer = NULL;
+ qglDrawElements = NULL;
+ qglDrawPixels = NULL;
+ qglEdgeFlag = NULL;
+ qglEdgeFlagPointer = NULL;
+ qglEdgeFlagv = NULL;
+ qglEnable = NULL;
+ qglEnableClientState = NULL;
+ qglEnd = NULL;
+ qglEndList = NULL;
+ qglEvalCoord1d = NULL;
+ qglEvalCoord1dv = NULL;
+ qglEvalCoord1f = NULL;
+ qglEvalCoord1fv = NULL;
+ qglEvalCoord2d = NULL;
+ qglEvalCoord2dv = NULL;
+ qglEvalCoord2f = NULL;
+ qglEvalCoord2fv = NULL;
+ qglEvalMesh1 = NULL;
+ qglEvalMesh2 = NULL;
+ qglEvalPoint1 = NULL;
+ qglEvalPoint2 = NULL;
+ qglFeedbackBuffer = NULL;
+ qglFinish = NULL;
+ qglFlush = NULL;
+ qglFogf = NULL;
+ qglFogfv = NULL;
+ qglFogi = NULL;
+ qglFogiv = NULL;
+ qglFrontFace = NULL;
+ qglFrustum = NULL;
+ qglGenLists = NULL;
+ qglGenTextures = NULL;
+ qglGetBooleanv = NULL;
+ qglGetClipPlane = NULL;
+ qglGetDoublev = NULL;
+ qglGetError = NULL;
+ qglGetFloatv = NULL;
+ qglGetIntegerv = NULL;
+ qglGetLightfv = NULL;
+ qglGetLightiv = NULL;
+ qglGetMapdv = NULL;
+ qglGetMapfv = NULL;
+ qglGetMapiv = NULL;
+ qglGetMaterialfv = NULL;
+ qglGetMaterialiv = NULL;
+ qglGetPixelMapfv = NULL;
+ qglGetPixelMapuiv = NULL;
+ qglGetPixelMapusv = NULL;
+ qglGetPointerv = NULL;
+ qglGetPolygonStipple = NULL;
+ qglGetString = NULL;
+ qglGetTexEnvfv = NULL;
+ qglGetTexEnviv = NULL;
+ qglGetTexGendv = NULL;
+ qglGetTexGenfv = NULL;
+ qglGetTexGeniv = NULL;
+ qglGetTexImage = NULL;
+ qglGetTexLevelParameterfv = NULL;
+ qglGetTexLevelParameteriv = NULL;
+ qglGetTexParameterfv = NULL;
+ qglGetTexParameteriv = NULL;
+ qglHint = NULL;
+ qglIndexMask = NULL;
+ qglIndexPointer = NULL;
+ qglIndexd = NULL;
+ qglIndexdv = NULL;
+ qglIndexf = NULL;
+ qglIndexfv = NULL;
+ qglIndexi = NULL;
+ qglIndexiv = NULL;
+ qglIndexs = NULL;
+ qglIndexsv = NULL;
+ qglIndexub = NULL;
+ qglIndexubv = NULL;
+ qglInitNames = NULL;
+ qglInterleavedArrays = NULL;
+ qglIsEnabled = NULL;
+ qglIsList = NULL;
+ qglIsTexture = NULL;
+ qglLightModelf = NULL;
+ qglLightModelfv = NULL;
+ qglLightModeli = NULL;
+ qglLightModeliv = NULL;
+ qglLightf = NULL;
+ qglLightfv = NULL;
+ qglLighti = NULL;
+ qglLightiv = NULL;
+ qglLineStipple = NULL;
+ qglLineWidth = NULL;
+ qglListBase = NULL;
+ qglLoadIdentity = NULL;
+ qglLoadMatrixd = NULL;
+ qglLoadMatrixf = NULL;
+ qglLoadName = NULL;
+ qglLogicOp = NULL;
+ qglMap1d = NULL;
+ qglMap1f = NULL;
+ qglMap2d = NULL;
+ qglMap2f = NULL;
+ qglMapGrid1d = NULL;
+ qglMapGrid1f = NULL;
+ qglMapGrid2d = NULL;
+ qglMapGrid2f = NULL;
+ qglMaterialf = NULL;
+ qglMaterialfv = NULL;
+ qglMateriali = NULL;
+ qglMaterialiv = NULL;
+ qglMatrixMode = NULL;
+ qglMultMatrixd = NULL;
+ qglMultMatrixf = NULL;
+ qglNewList = NULL;
+ qglNormal3b = NULL;
+ qglNormal3bv = NULL;
+ qglNormal3d = NULL;
+ qglNormal3dv = NULL;
+ qglNormal3f = NULL;
+ qglNormal3fv = NULL;
+ qglNormal3i = NULL;
+ qglNormal3iv = NULL;
+ qglNormal3s = NULL;
+ qglNormal3sv = NULL;
+ qglNormalPointer = NULL;
+ qglOrtho = NULL;
+ qglPassThrough = NULL;
+ qglPixelMapfv = NULL;
+ qglPixelMapuiv = NULL;
+ qglPixelMapusv = NULL;
+ qglPixelStoref = NULL;
+ qglPixelStorei = NULL;
+ qglPixelTransferf = NULL;
+ qglPixelTransferi = NULL;
+ qglPixelZoom = NULL;
+ qglPointSize = NULL;
+ qglPolygonMode = NULL;
+ qglPolygonOffset = NULL;
+ qglPolygonStipple = NULL;
+ qglPopAttrib = NULL;
+ qglPopClientAttrib = NULL;
+ qglPopMatrix = NULL;
+ qglPopName = NULL;
+ qglPrioritizeTextures = NULL;
+ qglPushAttrib = NULL;
+ qglPushClientAttrib = NULL;
+ qglPushMatrix = NULL;
+ qglPushName = NULL;
+ qglRasterPos2d = NULL;
+ qglRasterPos2dv = NULL;
+ qglRasterPos2f = NULL;
+ qglRasterPos2fv = NULL;
+ qglRasterPos2i = NULL;
+ qglRasterPos2iv = NULL;
+ qglRasterPos2s = NULL;
+ qglRasterPos2sv = NULL;
+ qglRasterPos3d = NULL;
+ qglRasterPos3dv = NULL;
+ qglRasterPos3f = NULL;
+ qglRasterPos3fv = NULL;
+ qglRasterPos3i = NULL;
+ qglRasterPos3iv = NULL;
+ qglRasterPos3s = NULL;
+ qglRasterPos3sv = NULL;
+ qglRasterPos4d = NULL;
+ qglRasterPos4dv = NULL;
+ qglRasterPos4f = NULL;
+ qglRasterPos4fv = NULL;
+ qglRasterPos4i = NULL;
+ qglRasterPos4iv = NULL;
+ qglRasterPos4s = NULL;
+ qglRasterPos4sv = NULL;
+ qglReadBuffer = NULL;
+ qglReadPixels = NULL;
+ qglRectd = NULL;
+ qglRectdv = NULL;
+ qglRectf = NULL;
+ qglRectfv = NULL;
+ qglRecti = NULL;
+ qglRectiv = NULL;
+ qglRects = NULL;
+ qglRectsv = NULL;
+ qglRenderMode = NULL;
+ qglRotated = NULL;
+ qglRotatef = NULL;
+ qglScaled = NULL;
+ qglScalef = NULL;
+ qglScissor = NULL;
+ qglSelectBuffer = NULL;
+ qglShadeModel = NULL;
+ qglStencilFunc = NULL;
+ qglStencilMask = NULL;
+ qglStencilOp = NULL;
+ qglTexCoord1d = NULL;
+ qglTexCoord1dv = NULL;
+ qglTexCoord1f = NULL;
+ qglTexCoord1fv = NULL;
+ qglTexCoord1i = NULL;
+ qglTexCoord1iv = NULL;
+ qglTexCoord1s = NULL;
+ qglTexCoord1sv = NULL;
+ qglTexCoord2d = NULL;
+ qglTexCoord2dv = NULL;
+ qglTexCoord2f = NULL;
+ qglTexCoord2fv = NULL;
+ qglTexCoord2i = NULL;
+ qglTexCoord2iv = NULL;
+ qglTexCoord2s = NULL;
+ qglTexCoord2sv = NULL;
+ qglTexCoord3d = NULL;
+ qglTexCoord3dv = NULL;
+ qglTexCoord3f = NULL;
+ qglTexCoord3fv = NULL;
+ qglTexCoord3i = NULL;
+ qglTexCoord3iv = NULL;
+ qglTexCoord3s = NULL;
+ qglTexCoord3sv = NULL;
+ qglTexCoord4d = NULL;
+ qglTexCoord4dv = NULL;
+ qglTexCoord4f = NULL;
+ qglTexCoord4fv = NULL;
+ qglTexCoord4i = NULL;
+ qglTexCoord4iv = NULL;
+ qglTexCoord4s = NULL;
+ qglTexCoord4sv = NULL;
+ qglTexCoordPointer = NULL;
+ qglTexEnvf = NULL;
+ qglTexEnvfv = NULL;
+ qglTexEnvi = NULL;
+ qglTexEnviv = NULL;
+ qglTexGend = NULL;
+ qglTexGendv = NULL;
+ qglTexGenf = NULL;
+ qglTexGenfv = NULL;
+ qglTexGeni = NULL;
+ qglTexGeniv = NULL;
+ qglTexImage1D = NULL;
+ qglTexImage2D = NULL;
+ qglTexParameterf = NULL;
+ qglTexParameterfv = NULL;
+ qglTexParameteri = NULL;
+ qglTexParameteriv = NULL;
+ qglTexSubImage1D = NULL;
+ qglTexSubImage2D = NULL;
+ qglTranslated = NULL;
+ qglTranslatef = NULL;
+ qglVertex2d = NULL;
+ qglVertex2dv = NULL;
+ qglVertex2f = NULL;
+ qglVertex2fv = NULL;
+ qglVertex2i = NULL;
+ qglVertex2iv = NULL;
+ qglVertex2s = NULL;
+ qglVertex2sv = NULL;
+ qglVertex3d = NULL;
+ qglVertex3dv = NULL;
+ qglVertex3f = NULL;
+ qglVertex3fv = NULL;
+ qglVertex3i = NULL;
+ qglVertex3iv = NULL;
+ qglVertex3s = NULL;
+ qglVertex3sv = NULL;
+ qglVertex4d = NULL;
+ qglVertex4dv = NULL;
+ qglVertex4f = NULL;
+ qglVertex4fv = NULL;
+ qglVertex4i = NULL;
+ qglVertex4iv = NULL;
+ qglVertex4s = NULL;
+ qglVertex4sv = NULL;
+ qglVertexPointer = NULL;
+ qglViewport = NULL;
+
+ qwglCopyContext = NULL;
+ qwglCreateContext = NULL;
+ qwglCreateLayerContext = NULL;
+ qwglDeleteContext = NULL;
+ qwglDescribeLayerPlane = NULL;
+ qwglGetCurrentContext = NULL;
+ qwglGetCurrentDC = NULL;
+ qwglGetLayerPaletteEntries = NULL;
+ qwglGetProcAddress = NULL;
+ qwglMakeCurrent = NULL;
+ qwglRealizeLayerPalette = NULL;
+ qwglSetLayerPaletteEntries = NULL;
+ qwglShareLists = NULL;
+ qwglSwapLayerBuffers = NULL;
+ qwglUseFontBitmaps = NULL;
+ qwglUseFontOutlines = NULL;
+
+ qwglChoosePixelFormat = NULL;
+ qwglDescribePixelFormat = NULL;
+ qwglGetPixelFormat = NULL;
+ qwglSetPixelFormat = NULL;
+ qwglSwapBuffers = NULL;
+
+ qwglSwapIntervalEXT = NULL;
+
+ qwglGetDeviceGammaRampEXT = NULL;
+ qwglSetDeviceGammaRampEXT = NULL;
+
+ qgluPerspective = NULL;
+ qgluBuild2DMipmaps = NULL;
+
+ qgluLookAt = NULL;
+}
+
+# define GPA(h, a ) GetProcAddress( h, a )
+
+/*
+** QGL_Init
+**
+** This is responsible for binding our qgl function pointers to
+** the appropriate GL stuff. In Windows this means doing a
+** LoadLibrary and a bunch of calls to GetProcAddress. On other
+** operating systems we need to do the right thing, whatever that
+** might be.
+**
+*/
+int QGL_Init(const char *dllname, const char* pGluName )
+{
+
+ g_hGLDLL = LoadLibrary(dllname);
+ if (g_hGLDLL == NULL)
+ {
+ return 0;
+ }
+
+ g_hGLUDLL = LoadLibrary(pGluName);
+ if (g_hGLUDLL == NULL)
+ {
+ FreeLibrary(g_hGLDLL);
+ g_hGLDLL = NULL;
+ return 0;
+ }
+
+
+ qgluPerspective = GPA(g_hGLUDLL, "gluPerspective");
+ qgluBuild2DMipmaps = GPA(g_hGLUDLL, "gluBuild2DMipmaps");
+ // added for plugins
+ qgluLookAt = GPA(g_hGLUDLL, "gluLookAt" );
+
+ qglAccum = GPA(g_hGLDLL, "glAccum" );
+ qglAlphaFunc = GPA(g_hGLDLL, "glAlphaFunc" );
+ qglAreTexturesResident = GPA(g_hGLDLL, "glAreTexturesResident" );
+ qglArrayElement = GPA(g_hGLDLL, "glArrayElement" );
+ qglBegin = GPA(g_hGLDLL, "glBegin" );
+ qglBindTexture = GPA(g_hGLDLL, "glBindTexture" );
+ qglBitmap = GPA(g_hGLDLL, "glBitmap" );
+ qglBlendFunc = GPA(g_hGLDLL, "glBlendFunc" );
+ qglCallList = GPA(g_hGLDLL, "glCallList" );
+ qglCallLists = GPA(g_hGLDLL, "glCallLists" );
+ qglClear = GPA(g_hGLDLL, "glClear" );
+ qglClearAccum = GPA(g_hGLDLL, "glClearAccum" );
+ qglClearColor = GPA(g_hGLDLL, "glClearColor" );
+ qglClearDepth = GPA(g_hGLDLL, "glClearDepth" );
+ qglClearIndex = GPA(g_hGLDLL, "glClearIndex" );
+ qglClearStencil = GPA(g_hGLDLL, "glClearStencil" );
+ qglClipPlane = GPA(g_hGLDLL, "glClipPlane" );
+ qglColor3b = GPA(g_hGLDLL, "glColor3b" );
+ qglColor3bv = GPA(g_hGLDLL, "glColor3bv" );
+ qglColor3d = GPA(g_hGLDLL, "glColor3d" );
+ qglColor3dv = GPA(g_hGLDLL, "glColor3dv" );
+ qglColor3f = GPA(g_hGLDLL, "glColor3f" );
+ qglColor3fv = GPA(g_hGLDLL, "glColor3fv" );
+ qglColor3i = GPA(g_hGLDLL, "glColor3i" );
+ qglColor3iv = GPA(g_hGLDLL, "glColor3iv" );
+ qglColor3s = GPA(g_hGLDLL, "glColor3s" );
+ qglColor3sv = GPA(g_hGLDLL, "glColor3sv" );
+ qglColor3ub = GPA(g_hGLDLL, "glColor3ub" );
+ qglColor3ubv = GPA(g_hGLDLL, "glColor3ubv" );
+ qglColor3ui = GPA(g_hGLDLL, "glColor3ui" );
+ qglColor3uiv = GPA(g_hGLDLL, "glColor3uiv" );
+ qglColor3us = GPA(g_hGLDLL, "glColor3us" );
+ qglColor3usv = GPA(g_hGLDLL, "glColor3usv" );
+ qglColor4b = GPA(g_hGLDLL, "glColor4b" );
+ qglColor4bv = GPA(g_hGLDLL, "glColor4bv" );
+ qglColor4d = GPA(g_hGLDLL, "glColor4d" );
+ qglColor4dv = GPA(g_hGLDLL, "glColor4dv" );
+ qglColor4f = GPA(g_hGLDLL, "glColor4f" );
+ qglColor4fv = GPA(g_hGLDLL, "glColor4fv" );
+ qglColor4i = GPA(g_hGLDLL, "glColor4i" );
+ qglColor4iv = GPA(g_hGLDLL, "glColor4iv" );
+ qglColor4s = GPA(g_hGLDLL, "glColor4s" );
+ qglColor4sv = GPA(g_hGLDLL, "glColor4sv" );
+ qglColor4ub = GPA(g_hGLDLL, "glColor4ub" );
+ qglColor4ubv = GPA(g_hGLDLL, "glColor4ubv" );
+ qglColor4ui = GPA(g_hGLDLL, "glColor4ui" );
+ qglColor4uiv = GPA(g_hGLDLL, "glColor4uiv" );
+ qglColor4us = GPA(g_hGLDLL, "glColor4us" );
+ qglColor4usv = GPA(g_hGLDLL, "glColor4usv" );
+ qglColorMask = GPA(g_hGLDLL, "glColorMask" );
+ qglColorMaterial = GPA(g_hGLDLL, "glColorMaterial" );
+ qglColorPointer = GPA(g_hGLDLL, "glColorPointer" );
+ qglCopyPixels = GPA(g_hGLDLL, "glCopyPixels" );
+ qglCopyTexImage1D = GPA(g_hGLDLL, "glCopyTexImage1D" );
+ qglCopyTexImage2D = GPA(g_hGLDLL, "glCopyTexImage2D" );
+ qglCopyTexSubImage1D = GPA(g_hGLDLL, "glCopyTexSubImage1D" );
+ qglCopyTexSubImage2D = GPA(g_hGLDLL, "glCopyTexSubImage2D" );
+ qglCullFace = GPA(g_hGLDLL, "glCullFace" );
+ qglDeleteLists = GPA(g_hGLDLL, "glDeleteLists" );
+ qglDeleteTextures = GPA(g_hGLDLL, "glDeleteTextures" );
+ qglDepthFunc = GPA(g_hGLDLL, "glDepthFunc" );
+ qglDepthMask = GPA(g_hGLDLL, "glDepthMask" );
+ qglDepthRange = GPA(g_hGLDLL, "glDepthRange" );
+ qglDisable = GPA(g_hGLDLL, "glDisable" );
+ qglDisableClientState = GPA(g_hGLDLL, "glDisableClientState" );
+ qglDrawArrays = GPA(g_hGLDLL, "glDrawArrays" );
+ qglDrawBuffer = GPA(g_hGLDLL, "glDrawBuffer" );
+ qglDrawElements = GPA(g_hGLDLL, "glDrawElements" );
+ qglDrawPixels = GPA(g_hGLDLL, "glDrawPixels" );
+ qglEdgeFlag = GPA(g_hGLDLL, "glEdgeFlag" );
+ qglEdgeFlagPointer = GPA(g_hGLDLL, "glEdgeFlagPointer" );
+ qglEdgeFlagv = GPA(g_hGLDLL, "glEdgeFlagv" );
+ qglEnable = GPA(g_hGLDLL, "glEnable" );
+ qglEnableClientState = GPA(g_hGLDLL, "glEnableClientState" );
+ qglEnd = GPA(g_hGLDLL, "glEnd" );
+ qglEndList = GPA(g_hGLDLL, "glEndList" );
+ qglEvalCoord1d = GPA(g_hGLDLL, "glEvalCoord1d" );
+ qglEvalCoord1dv = GPA(g_hGLDLL, "glEvalCoord1dv" );
+ qglEvalCoord1f = GPA(g_hGLDLL, "glEvalCoord1f" );
+ qglEvalCoord1fv = GPA(g_hGLDLL, "glEvalCoord1fv" );
+ qglEvalCoord2d = GPA(g_hGLDLL, "glEvalCoord2d" );
+ qglEvalCoord2dv = GPA(g_hGLDLL, "glEvalCoord2dv" );
+ qglEvalCoord2f = GPA(g_hGLDLL, "glEvalCoord2f" );
+ qglEvalCoord2fv = GPA(g_hGLDLL, "glEvalCoord2fv" );
+ qglEvalMesh1 = GPA(g_hGLDLL, "glEvalMesh1" );
+ qglEvalMesh2 = GPA(g_hGLDLL, "glEvalMesh2" );
+ qglEvalPoint1 = GPA(g_hGLDLL, "glEvalPoint1" );
+ qglEvalPoint2 = GPA(g_hGLDLL, "glEvalPoint2" );
+ qglFeedbackBuffer = GPA(g_hGLDLL, "glFeedbackBuffer" );
+ qglFinish = GPA(g_hGLDLL, "glFinish" );
+ qglFlush = GPA(g_hGLDLL, "glFlush" );
+ qglFogf = GPA(g_hGLDLL, "glFogf" );
+ qglFogfv = GPA(g_hGLDLL, "glFogfv" );
+ qglFogi = GPA(g_hGLDLL, "glFogi" );
+ qglFogiv = GPA(g_hGLDLL, "glFogiv" );
+ qglFrontFace = GPA(g_hGLDLL, "glFrontFace" );
+ qglFrustum = GPA(g_hGLDLL, "glFrustum" );
+ qglGenLists = GPA(g_hGLDLL, "glGenLists" );
+ qglGenTextures = GPA(g_hGLDLL, "glGenTextures" );
+ qglGetBooleanv = GPA(g_hGLDLL, "glGetBooleanv" );
+ qglGetClipPlane = GPA(g_hGLDLL, "glGetClipPlane" );
+ qglGetDoublev = GPA(g_hGLDLL, "glGetDoublev" );
+ qglGetError = GPA(g_hGLDLL, "glGetError" );
+ qglGetFloatv = GPA(g_hGLDLL, "glGetFloatv" );
+ qglGetIntegerv = GPA(g_hGLDLL, "glGetIntegerv" );
+ qglGetLightfv = GPA(g_hGLDLL, "glGetLightfv" );
+ qglGetLightiv = GPA(g_hGLDLL, "glGetLightiv" );
+ qglGetMapdv = GPA(g_hGLDLL, "glGetMapdv" );
+ qglGetMapfv = GPA(g_hGLDLL, "glGetMapfv" );
+ qglGetMapiv = GPA(g_hGLDLL, "glGetMapiv" );
+ qglGetMaterialfv = GPA(g_hGLDLL, "glGetMaterialfv" );
+ qglGetMaterialiv = GPA(g_hGLDLL, "glGetMaterialiv" );
+ qglGetPixelMapfv = GPA(g_hGLDLL, "glGetPixelMapfv" );
+ qglGetPixelMapuiv = GPA(g_hGLDLL, "glGetPixelMapuiv" );
+ qglGetPixelMapusv = GPA(g_hGLDLL, "glGetPixelMapusv" );
+ qglGetPointerv = GPA(g_hGLDLL, "glGetPointerv" );
+ qglGetPolygonStipple = GPA(g_hGLDLL, "glGetPolygonStipple" );
+ qglGetString = GPA(g_hGLDLL, "glGetString" );
+ qglGetTexEnvfv = GPA(g_hGLDLL, "glGetTexEnvfv" );
+ qglGetTexEnviv = GPA(g_hGLDLL, "glGetTexEnviv" );
+ qglGetTexGendv = GPA(g_hGLDLL, "glGetTexGendv" );
+ qglGetTexGenfv = GPA(g_hGLDLL, "glGetTexGenfv" );
+ qglGetTexGeniv = GPA(g_hGLDLL, "glGetTexGeniv" );
+ qglGetTexImage = GPA(g_hGLDLL, "glGetTexImage" );
+ qglGetTexLevelParameterfv = GPA(g_hGLDLL, "glGetLevelParameterfv" );
+ qglGetTexLevelParameteriv = GPA(g_hGLDLL, "glGetLevelParameteriv" );
+ qglGetTexParameterfv = GPA(g_hGLDLL, "glGetTexParameterfv" );
+ qglGetTexParameteriv = GPA(g_hGLDLL, "glGetTexParameteriv" );
+ qglHint = GPA(g_hGLDLL, "glHint" );
+ qglIndexMask = GPA(g_hGLDLL, "glIndexMask" );
+ qglIndexPointer = GPA(g_hGLDLL, "glIndexPointer" );
+ qglIndexd = GPA(g_hGLDLL, "glIndexd" );
+ qglIndexdv = GPA(g_hGLDLL, "glIndexdv" );
+ qglIndexf = GPA(g_hGLDLL, "glIndexf" );
+ qglIndexfv = GPA(g_hGLDLL, "glIndexfv" );
+ qglIndexi = GPA(g_hGLDLL, "glIndexi" );
+ qglIndexiv = GPA(g_hGLDLL, "glIndexiv" );
+ qglIndexs = GPA(g_hGLDLL, "glIndexs" );
+ qglIndexsv = GPA(g_hGLDLL, "glIndexsv" );
+ qglIndexub = GPA(g_hGLDLL, "glIndexub" );
+ qglIndexubv = GPA(g_hGLDLL, "glIndexubv" );
+ qglInitNames = GPA(g_hGLDLL, "glInitNames" );
+ qglInterleavedArrays = GPA(g_hGLDLL, "glInterleavedArrays" );
+ qglIsEnabled = GPA(g_hGLDLL, "glIsEnabled" );
+ qglIsList = GPA(g_hGLDLL, "glIsList" );
+ qglIsTexture = GPA(g_hGLDLL, "glIsTexture" );
+ qglLightModelf = GPA(g_hGLDLL, "glLightModelf" );
+ qglLightModelfv = GPA(g_hGLDLL, "glLightModelfv" );
+ qglLightModeli = GPA(g_hGLDLL, "glLightModeli" );
+ qglLightModeliv = GPA(g_hGLDLL, "glLightModeliv" );
+ qglLightf = GPA(g_hGLDLL, "glLightf" );
+ qglLightfv = GPA(g_hGLDLL, "glLightfv" );
+ qglLighti = GPA(g_hGLDLL, "glLighti" );
+ qglLightiv = GPA(g_hGLDLL, "glLightiv" );
+ qglLineStipple = GPA(g_hGLDLL, "glLineStipple" );
+ qglLineWidth = GPA(g_hGLDLL, "glLineWidth" );
+ qglListBase = GPA(g_hGLDLL, "glListBase" );
+ qglLoadIdentity = GPA(g_hGLDLL, "glLoadIdentity" );
+ qglLoadMatrixd = GPA(g_hGLDLL, "glLoadMatrixd" );
+ qglLoadMatrixf = GPA(g_hGLDLL, "glLoadMatrixf" );
+ qglLoadName = GPA(g_hGLDLL, "glLoadName" );
+ qglLogicOp = GPA(g_hGLDLL, "glLogicOp" );
+ qglMap1d = GPA(g_hGLDLL, "glMap1d" );
+ qglMap1f = GPA(g_hGLDLL, "glMap1f" );
+ qglMap2d = GPA(g_hGLDLL, "glMap2d" );
+ qglMap2f = GPA(g_hGLDLL, "glMap2f" );
+ qglMapGrid1d = GPA(g_hGLDLL, "glMapGrid1d" );
+ qglMapGrid1f = GPA(g_hGLDLL, "glMapGrid1f" );
+ qglMapGrid2d = GPA(g_hGLDLL, "glMapGrid2d" );
+ qglMapGrid2f = GPA(g_hGLDLL, "glMapGrid2f" );
+ qglMaterialf = GPA(g_hGLDLL, "glMaterialf" );
+ qglMaterialfv = GPA(g_hGLDLL, "glMaterialfv" );
+ qglMateriali = GPA(g_hGLDLL, "glMateriali" );
+ qglMaterialiv = GPA(g_hGLDLL, "glMaterialiv" );
+ qglMatrixMode = GPA(g_hGLDLL, "glMatrixMode" );
+ qglMultMatrixd = GPA(g_hGLDLL, "glMultMatrixd" );
+ qglMultMatrixf = GPA(g_hGLDLL, "glMultMatrixf" );
+ qglNewList = GPA(g_hGLDLL, "glNewList" );
+ qglNormal3b = GPA(g_hGLDLL, "glNormal3b" );
+ qglNormal3bv = GPA(g_hGLDLL, "glNormal3bv" );
+ qglNormal3d = GPA(g_hGLDLL, "glNormal3d" );
+ qglNormal3dv = GPA(g_hGLDLL, "glNormal3dv" );
+ qglNormal3f = GPA(g_hGLDLL, "glNormal3f" );
+ qglNormal3fv = GPA(g_hGLDLL, "glNormal3fv" );
+ qglNormal3i = GPA(g_hGLDLL, "glNormal3i" );
+ qglNormal3iv = GPA(g_hGLDLL, "glNormal3iv" );
+ qglNormal3s = GPA(g_hGLDLL, "glNormal3s" );
+ qglNormal3sv = GPA(g_hGLDLL, "glNormal3sv" );
+ qglNormalPointer = GPA(g_hGLDLL, "glNormalPointer" );
+ qglOrtho = GPA(g_hGLDLL, "glOrtho" );
+ qglPassThrough = GPA(g_hGLDLL, "glPassThrough" );
+ qglPixelMapfv = GPA(g_hGLDLL, "glPixelMapfv" );
+ qglPixelMapuiv = GPA(g_hGLDLL, "glPixelMapuiv" );
+ qglPixelMapusv = GPA(g_hGLDLL, "glPixelMapusv" );
+ qglPixelStoref = GPA(g_hGLDLL, "glPixelStoref" );
+ qglPixelStorei = GPA(g_hGLDLL, "glPixelStorei" );
+ qglPixelTransferf = GPA(g_hGLDLL, "glPixelTransferf" );
+ qglPixelTransferi = GPA(g_hGLDLL, "glPixelTransferi" );
+ qglPixelZoom = GPA(g_hGLDLL, "glPixelZoom" );
+ qglPointSize = GPA(g_hGLDLL, "glPointSize" );
+ qglPolygonMode = GPA(g_hGLDLL, "glPolygonMode" );
+ qglPolygonOffset = GPA(g_hGLDLL, "glPolygonOffset" );
+ qglPolygonStipple = GPA(g_hGLDLL, "glPolygonStipple" );
+ qglPopAttrib = GPA(g_hGLDLL, "glPopAttrib" );
+ qglPopClientAttrib = GPA(g_hGLDLL, "glPopClientAttrib" );
+ qglPopMatrix = GPA(g_hGLDLL, "glPopMatrix" );
+ qglPopName = GPA(g_hGLDLL, "glPopName" );
+ qglPrioritizeTextures = GPA(g_hGLDLL, "glPrioritizeTextures" );
+ qglPushAttrib = GPA(g_hGLDLL, "glPushAttrib" );
+ qglPushClientAttrib = GPA(g_hGLDLL, "glPushClientAttrib" );
+ qglPushMatrix = GPA(g_hGLDLL, "glPushMatrix" );
+ qglPushName = GPA(g_hGLDLL, "glPushName" );
+ qglRasterPos2d = GPA(g_hGLDLL, "glRasterPos2d" );
+ qglRasterPos2dv = GPA(g_hGLDLL, "glRasterPos2dv" );
+ qglRasterPos2f = GPA(g_hGLDLL, "glRasterPos2f" );
+ qglRasterPos2fv = GPA(g_hGLDLL, "glRasterPos2fv" );
+ qglRasterPos2i = GPA(g_hGLDLL, "glRasterPos2i" );
+ qglRasterPos2iv = GPA(g_hGLDLL, "glRasterPos2iv" );
+ qglRasterPos2s = GPA(g_hGLDLL, "glRasterPos2s" );
+ qglRasterPos2sv = GPA(g_hGLDLL, "glRasterPos2sv" );
+ qglRasterPos3d = GPA(g_hGLDLL, "glRasterPos3d" );
+ qglRasterPos3dv = GPA(g_hGLDLL, "glRasterPos3dv" );
+ qglRasterPos3f = GPA(g_hGLDLL, "glRasterPos3f" );
+ qglRasterPos3fv = GPA(g_hGLDLL, "glRasterPos3fv" );
+ qglRasterPos3i = GPA(g_hGLDLL, "glRasterPos3i" );
+ qglRasterPos3iv = GPA(g_hGLDLL, "glRasterPos3iv" );
+ qglRasterPos3s = GPA(g_hGLDLL, "glRasterPos3s" );
+ qglRasterPos3sv = GPA(g_hGLDLL, "glRasterPos3sv" );
+ qglRasterPos4d = GPA(g_hGLDLL, "glRasterPos4d" );
+ qglRasterPos4dv = GPA(g_hGLDLL, "glRasterPos4dv" );
+ qglRasterPos4f = GPA(g_hGLDLL, "glRasterPos4f" );
+ qglRasterPos4fv = GPA(g_hGLDLL, "glRasterPos4fv" );
+ qglRasterPos4i = GPA(g_hGLDLL, "glRasterPos4i" );
+ qglRasterPos4iv = GPA(g_hGLDLL, "glRasterPos4iv" );
+ qglRasterPos4s = GPA(g_hGLDLL, "glRasterPos4s" );
+ qglRasterPos4sv = GPA(g_hGLDLL, "glRasterPos4sv" );
+ qglReadBuffer = GPA(g_hGLDLL, "glReadBuffer" );
+ qglReadPixels = GPA(g_hGLDLL, "glReadPixels" );
+ qglRectd = GPA(g_hGLDLL, "glRectd" );
+ qglRectdv = GPA(g_hGLDLL, "glRectdv" );
+ qglRectf = GPA(g_hGLDLL, "glRectf" );
+ qglRectfv = GPA(g_hGLDLL, "glRectfv" );
+ qglRecti = GPA(g_hGLDLL, "glRecti" );
+ qglRectiv = GPA(g_hGLDLL, "glRectiv" );
+ qglRects = GPA(g_hGLDLL, "glRects" );
+ qglRectsv = GPA(g_hGLDLL, "glRectsv" );
+ qglRenderMode = GPA(g_hGLDLL, "glRenderMode" );
+ qglRotated = GPA(g_hGLDLL, "glRotated" );
+ qglRotatef = GPA(g_hGLDLL, "glRotatef" );
+ qglScaled = GPA(g_hGLDLL, "glScaled" );
+ qglScalef = GPA(g_hGLDLL, "glScalef" );
+ qglScissor = GPA(g_hGLDLL, "glScissor" );
+ qglSelectBuffer = GPA(g_hGLDLL, "glSelectBuffer" );
+ qglShadeModel = GPA(g_hGLDLL, "glShadeModel" );
+ qglStencilFunc = GPA(g_hGLDLL, "glStencilFunc" );
+ qglStencilMask = GPA(g_hGLDLL, "glStencilMask" );
+ qglStencilOp = GPA(g_hGLDLL, "glStencilOp" );
+ qglTexCoord1d = GPA(g_hGLDLL, "glTexCoord1d" );
+ qglTexCoord1dv = GPA(g_hGLDLL, "glTexCoord1dv" );
+ qglTexCoord1f = GPA(g_hGLDLL, "glTexCoord1f" );
+ qglTexCoord1fv = GPA(g_hGLDLL, "glTexCoord1fv" );
+ qglTexCoord1i = GPA(g_hGLDLL, "glTexCoord1i" );
+ qglTexCoord1iv = GPA(g_hGLDLL, "glTexCoord1iv" );
+ qglTexCoord1s = GPA(g_hGLDLL, "glTexCoord1s" );
+ qglTexCoord1sv = GPA(g_hGLDLL, "glTexCoord1sv" );
+ qglTexCoord2d = GPA(g_hGLDLL, "glTexCoord2d" );
+ qglTexCoord2dv = GPA(g_hGLDLL, "glTexCoord2dv" );
+ qglTexCoord2f = GPA(g_hGLDLL, "glTexCoord2f" );
+ qglTexCoord2fv = GPA(g_hGLDLL, "glTexCoord2fv" );
+ qglTexCoord2i = GPA(g_hGLDLL, "glTexCoord2i" );
+ qglTexCoord2iv = GPA(g_hGLDLL, "glTexCoord2iv" );
+ qglTexCoord2s = GPA(g_hGLDLL, "glTexCoord2s" );
+ qglTexCoord2sv = GPA(g_hGLDLL, "glTexCoord2sv" );
+ qglTexCoord3d = GPA(g_hGLDLL, "glTexCoord3d" );
+ qglTexCoord3dv = GPA(g_hGLDLL, "glTexCoord3dv" );
+ qglTexCoord3f = GPA(g_hGLDLL, "glTexCoord3f" );
+ qglTexCoord3fv = GPA(g_hGLDLL, "glTexCoord3fv" );
+ qglTexCoord3i = GPA(g_hGLDLL, "glTexCoord3i" );
+ qglTexCoord3iv = GPA(g_hGLDLL, "glTexCoord3iv" );
+ qglTexCoord3s = GPA(g_hGLDLL, "glTexCoord3s" );
+ qglTexCoord3sv = GPA(g_hGLDLL, "glTexCoord3sv" );
+ qglTexCoord4d = GPA(g_hGLDLL, "glTexCoord4d" );
+ qglTexCoord4dv = GPA(g_hGLDLL, "glTexCoord4dv" );
+ qglTexCoord4f = GPA(g_hGLDLL, "glTexCoord4f" );
+ qglTexCoord4fv = GPA(g_hGLDLL, "glTexCoord4fv" );
+ qglTexCoord4i = GPA(g_hGLDLL, "glTexCoord4i" );
+ qglTexCoord4iv = GPA(g_hGLDLL, "glTexCoord4iv" );
+ qglTexCoord4s = GPA(g_hGLDLL, "glTexCoord4s" );
+ qglTexCoord4sv = GPA(g_hGLDLL, "glTexCoord4sv" );
+ qglTexCoordPointer = GPA(g_hGLDLL, "glTexCoordPointer" );
+ qglTexEnvf = GPA(g_hGLDLL, "glTexEnvf" );
+ qglTexEnvfv = GPA(g_hGLDLL, "glTexEnvfv" );
+ qglTexEnvi = GPA(g_hGLDLL, "glTexEnvi" );
+ qglTexEnviv = GPA(g_hGLDLL, "glTexEnviv" );
+ qglTexGend = GPA(g_hGLDLL, "glTexGend" );
+ qglTexGendv = GPA(g_hGLDLL, "glTexGendv" );
+ qglTexGenf = GPA(g_hGLDLL, "glTexGenf" );
+ qglTexGenfv = GPA(g_hGLDLL, "glTexGenfv" );
+ qglTexGeni = GPA(g_hGLDLL, "glTexGeni" );
+ qglTexGeniv = GPA(g_hGLDLL, "glTexGeniv" );
+ qglTexImage1D = GPA(g_hGLDLL, "glTexImage1D" );
+ qglTexImage2D = GPA(g_hGLDLL, "glTexImage2D" );
+ qglTexParameterf = GPA(g_hGLDLL, "glTexParameterf" );
+ qglTexParameterfv = GPA(g_hGLDLL, "glTexParameterfv" );
+ qglTexParameteri = GPA(g_hGLDLL, "glTexParameteri" );
+ qglTexParameteriv = GPA(g_hGLDLL, "glTexParameteriv" );
+ qglTexSubImage1D = GPA(g_hGLDLL, "glTexSubImage1D" );
+ qglTexSubImage2D = GPA(g_hGLDLL, "glTexSubImage2D" );
+ qglTranslated = GPA(g_hGLDLL, "glTranslated" );
+ qglTranslatef = GPA(g_hGLDLL, "glTranslatef" );
+ qglVertex2d = GPA(g_hGLDLL, "glVertex2d" );
+ qglVertex2dv = GPA(g_hGLDLL, "glVertex2dv" );
+ qglVertex2f = GPA(g_hGLDLL, "glVertex2f" );
+ qglVertex2fv = GPA(g_hGLDLL, "glVertex2fv" );
+ qglVertex2i = GPA(g_hGLDLL, "glVertex2i" );
+ qglVertex2iv = GPA(g_hGLDLL, "glVertex2iv" );
+ qglVertex2s = GPA(g_hGLDLL, "glVertex2s" );
+ qglVertex2sv = GPA(g_hGLDLL, "glVertex2sv" );
+ qglVertex3d = GPA(g_hGLDLL, "glVertex3d" );
+ qglVertex3dv = GPA(g_hGLDLL, "glVertex3dv" );
+ qglVertex3f = GPA(g_hGLDLL, "glVertex3f" );
+ qglVertex3fv = GPA(g_hGLDLL, "glVertex3fv" );
+ qglVertex3i = GPA(g_hGLDLL, "glVertex3i" );
+ qglVertex3iv = GPA(g_hGLDLL, "glVertex3iv" );
+ qglVertex3s = GPA(g_hGLDLL, "glVertex3s" );
+ qglVertex3sv = GPA(g_hGLDLL, "glVertex3sv" );
+ qglVertex4d = GPA(g_hGLDLL, "glVertex4d" );
+ qglVertex4dv = GPA(g_hGLDLL, "glVertex4dv" );
+ qglVertex4f = GPA(g_hGLDLL, "glVertex4f" );
+ qglVertex4fv = GPA(g_hGLDLL, "glVertex4fv" );
+ qglVertex4i = GPA(g_hGLDLL, "glVertex4i" );
+ qglVertex4iv = GPA(g_hGLDLL, "glVertex4iv" );
+ qglVertex4s = GPA(g_hGLDLL, "glVertex4s" );
+ qglVertex4sv = GPA(g_hGLDLL, "glVertex4sv" );
+ qglVertexPointer = GPA(g_hGLDLL, "glVertexPointer" );
+ qglViewport = GPA(g_hGLDLL, "glViewport" );
+
+ qwglCopyContext = GPA(g_hGLDLL, "wglCopyContext" );
+ qwglCreateContext = GPA(g_hGLDLL, "wglCreateContext" );
+ qwglCreateLayerContext = GPA(g_hGLDLL, "wglCreateLayerContext" );
+ qwglDeleteContext = GPA(g_hGLDLL, "wglDeleteContext" );
+ qwglDescribeLayerPlane = GPA(g_hGLDLL, "wglDescribeLayerPlane" );
+ qwglGetCurrentContext = GPA(g_hGLDLL, "wglGetCurrentContext" );
+ qwglGetCurrentDC = GPA(g_hGLDLL, "wglGetCurrentDC" );
+ qwglGetLayerPaletteEntries = GPA(g_hGLDLL, "wglGetLayerPaletteEntries" );
+ qwglGetProcAddress = GPA(g_hGLDLL, "wglGetProcAddress" );
+ qwglMakeCurrent = GPA(g_hGLDLL, "wglMakeCurrent" );
+ qwglRealizeLayerPalette = GPA(g_hGLDLL, "wglRealizeLayerPalette" );
+ qwglSetLayerPaletteEntries = GPA(g_hGLDLL, "wglSetLayerPaletteEntries" );
+ qwglShareLists = GPA(g_hGLDLL, "wglShareLists" );
+ qwglSwapLayerBuffers = GPA(g_hGLDLL, "wglSwapLayerBuffers" );
+ qwglUseFontBitmaps = GPA(g_hGLDLL, "wglUseFontBitmapsA" );
+ qwglUseFontOutlines = GPA(g_hGLDLL, "wglUseFontOutlinesA" );
+
+ qwglChoosePixelFormat = GPA(g_hGLDLL, "wglChoosePixelFormat" );
+ qwglDescribePixelFormat = GPA(g_hGLDLL, "wglDescribePixelFormat" );
+ qwglGetPixelFormat = GPA(g_hGLDLL, "wglGetPixelFormat" );
+ qwglSetPixelFormat = GPA(g_hGLDLL, "wglSetPixelFormat" );
+ qwglSwapBuffers = GPA(g_hGLDLL, "wglSwapBuffers" );
+
+ qwglSwapIntervalEXT = 0;
+ qglPointParameterfEXT = 0;
+ qglPointParameterfvEXT = 0;
+ qglColorTableEXT = 0;
+ qglSelectTextureSGIS = 0;
+ qglMTexCoord2fSGIS = 0;
+
+ return 1;
+}
+
+#pragma warning (default : 4113 4133 4047 )
+
+
+
diff --git a/q3radiant/QGL_WIN.CPP b/q3radiant/QGL_WIN.CPP
new file mode 100755
index 0000000..dfb7687
--- /dev/null
+++ b/q3radiant/QGL_WIN.CPP
@@ -0,0 +1,1520 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+/*
+** QGL_WIN.C
+**
+** This file implements the operating system binding of GL to QGL function
+** pointers. When doing a port of Quake2 you must implement the following
+** two functions:
+**
+** QGL_Init() - loads libraries, assigns function pointers, etc.
+** QGL_Shutdown() - unloads libraries, NULLs function pointers
+*/
+#include "stdafx.h"
+#include <float.h>
+
+HMODULE g_hGLDLL = NULL;
+
+# pragma warning (disable : 4113 4133 4047 )
+
+int ( WINAPI * qwglChoosePixelFormat )(HDC, CONST PIXELFORMATDESCRIPTOR *);
+int ( WINAPI * qwglDescribePixelFormat) (HDC, int, UINT, LPPIXELFORMATDESCRIPTOR);
+int ( WINAPI * qwglGetPixelFormat)(HDC);
+BOOL ( WINAPI * qwglSetPixelFormat)(HDC, int, CONST PIXELFORMATDESCRIPTOR *);
+BOOL ( WINAPI * qwglSwapBuffers)(HDC);
+
+BOOL ( WINAPI * qwglCopyContext)(HGLRC, HGLRC, UINT);
+HGLRC ( WINAPI * qwglCreateContext)(HDC);
+HGLRC ( WINAPI * qwglCreateLayerContext)(HDC, int);
+BOOL ( WINAPI * qwglDeleteContext)(HGLRC);
+HGLRC ( WINAPI * qwglGetCurrentContext)(VOID);
+HDC ( WINAPI * qwglGetCurrentDC)(VOID);
+PROC ( WINAPI * qwglGetProcAddress)(LPCSTR);
+BOOL ( WINAPI * qwglMakeCurrent)(HDC, HGLRC);
+BOOL ( WINAPI * qwglShareLists)(HGLRC, HGLRC);
+BOOL ( WINAPI * qwglUseFontBitmaps)(HDC, DWORD, DWORD, DWORD);
+
+BOOL ( WINAPI * qwglUseFontOutlines)(HDC, DWORD, DWORD, DWORD, FLOAT,
+ FLOAT, int, LPGLYPHMETRICSFLOAT);
+
+BOOL ( WINAPI * qwglDescribeLayerPlane)(HDC, int, int, UINT,
+ LPLAYERPLANEDESCRIPTOR);
+int ( WINAPI * qwglSetLayerPaletteEntries)(HDC, int, int, int,
+ CONST COLORREF *);
+int ( WINAPI * qwglGetLayerPaletteEntries)(HDC, int, int, int,
+ COLORREF *);
+BOOL ( WINAPI * qwglRealizeLayerPalette)(HDC, int, BOOL);
+BOOL ( WINAPI * qwglSwapLayerBuffers)(HDC, UINT);
+
+void ( APIENTRY * qglAccum )(GLenum op, GLfloat value);
+void ( APIENTRY * qglAlphaFunc )(GLenum func, GLclampf ref);
+GLboolean ( APIENTRY * qglAreTexturesResident )(GLsizei n, const GLuint *textures, GLboolean *residences);
+void ( APIENTRY * qglArrayElement )(GLint i);
+void ( APIENTRY * qglBegin )(GLenum mode);
+void ( APIENTRY * qglBindTexture )(GLenum target, GLuint texture);
+void ( APIENTRY * qglBitmap )(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap);
+void ( APIENTRY * qglBlendFunc )(GLenum sfactor, GLenum dfactor);
+void ( APIENTRY * qglCallList )(GLuint list);
+void ( APIENTRY * qglCallLists )(GLsizei n, GLenum type, const GLvoid *lists);
+void ( APIENTRY * qglClear )(GLbitfield mask);
+void ( APIENTRY * qglClearAccum )(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+void ( APIENTRY * qglClearColor )(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+void ( APIENTRY * qglClearDepth )(GLclampd depth);
+void ( APIENTRY * qglClearIndex )(GLfloat c);
+void ( APIENTRY * qglClearStencil )(GLint s);
+void ( APIENTRY * qglClipPlane )(GLenum plane, const GLdouble *equation);
+void ( APIENTRY * qglColor3b )(GLbyte red, GLbyte green, GLbyte blue);
+void ( APIENTRY * qglColor3bv )(const GLbyte *v);
+void ( APIENTRY * qglColor3d )(GLdouble red, GLdouble green, GLdouble blue);
+void ( APIENTRY * qglColor3dv )(const GLdouble *v);
+void ( APIENTRY * qglColor3f )(GLfloat red, GLfloat green, GLfloat blue);
+void ( APIENTRY * qglColor3fv )(const GLfloat *v);
+void ( APIENTRY * qglColor3i )(GLint red, GLint green, GLint blue);
+void ( APIENTRY * qglColor3iv )(const GLint *v);
+void ( APIENTRY * qglColor3s )(GLshort red, GLshort green, GLshort blue);
+void ( APIENTRY * qglColor3sv )(const GLshort *v);
+void ( APIENTRY * qglColor3ub )(GLubyte red, GLubyte green, GLubyte blue);
+void ( APIENTRY * qglColor3ubv )(const GLubyte *v);
+void ( APIENTRY * qglColor3ui )(GLuint red, GLuint green, GLuint blue);
+void ( APIENTRY * qglColor3uiv )(const GLuint *v);
+void ( APIENTRY * qglColor3us )(GLushort red, GLushort green, GLushort blue);
+void ( APIENTRY * qglColor3usv )(const GLushort *v);
+void ( APIENTRY * qglColor4b )(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha);
+void ( APIENTRY * qglColor4bv )(const GLbyte *v);
+void ( APIENTRY * qglColor4d )(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha);
+void ( APIENTRY * qglColor4dv )(const GLdouble *v);
+void ( APIENTRY * qglColor4f )(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+void ( APIENTRY * qglColor4fv )(const GLfloat *v);
+void ( APIENTRY * qglColor4i )(GLint red, GLint green, GLint blue, GLint alpha);
+void ( APIENTRY * qglColor4iv )(const GLint *v);
+void ( APIENTRY * qglColor4s )(GLshort red, GLshort green, GLshort blue, GLshort alpha);
+void ( APIENTRY * qglColor4sv )(const GLshort *v);
+void ( APIENTRY * qglColor4ub )(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha);
+void ( APIENTRY * qglColor4ubv )(const GLubyte *v);
+void ( APIENTRY * qglColor4ui )(GLuint red, GLuint green, GLuint blue, GLuint alpha);
+void ( APIENTRY * qglColor4uiv )(const GLuint *v);
+void ( APIENTRY * qglColor4us )(GLushort red, GLushort green, GLushort blue, GLushort alpha);
+void ( APIENTRY * qglColor4usv )(const GLushort *v);
+void ( APIENTRY * qglColorMask )(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
+void ( APIENTRY * qglColorMaterial )(GLenum face, GLenum mode);
+void ( APIENTRY * qglColorPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+void ( APIENTRY * qglCopyPixels )(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type);
+void ( APIENTRY * qglCopyTexImage1D )(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLint border);
+void ( APIENTRY * qglCopyTexImage2D )(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+void ( APIENTRY * qglCopyTexSubImage1D )(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
+void ( APIENTRY * qglCopyTexSubImage2D )(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+void ( APIENTRY * qglCullFace )(GLenum mode);
+void ( APIENTRY * qglDeleteLists )(GLuint list, GLsizei range);
+void ( APIENTRY * qglDeleteTextures )(GLsizei n, const GLuint *textures);
+void ( APIENTRY * qglDepthFunc )(GLenum func);
+void ( APIENTRY * qglDepthMask )(GLboolean flag);
+void ( APIENTRY * qglDepthRange )(GLclampd zNear, GLclampd zFar);
+void ( APIENTRY * qglDisable )(GLenum cap);
+void ( APIENTRY * qglDisableClientState )(GLenum array);
+void ( APIENTRY * qglDrawArrays )(GLenum mode, GLint first, GLsizei count);
+void ( APIENTRY * qglDrawBuffer )(GLenum mode);
+void ( APIENTRY * qglDrawElements )(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices);
+void ( APIENTRY * qglDrawPixels )(GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+void ( APIENTRY * qglEdgeFlag )(GLboolean flag);
+void ( APIENTRY * qglEdgeFlagPointer )(GLsizei stride, const GLvoid *pointer);
+void ( APIENTRY * qglEdgeFlagv )(const GLboolean *flag);
+void ( APIENTRY * qglEnable )(GLenum cap);
+void ( APIENTRY * qglEnableClientState )(GLenum array);
+void ( APIENTRY * qglEnd )(void);
+void ( APIENTRY * qglEndList )(void);
+void ( APIENTRY * qglEvalCoord1d )(GLdouble u);
+void ( APIENTRY * qglEvalCoord1dv )(const GLdouble *u);
+void ( APIENTRY * qglEvalCoord1f )(GLfloat u);
+void ( APIENTRY * qglEvalCoord1fv )(const GLfloat *u);
+void ( APIENTRY * qglEvalCoord2d )(GLdouble u, GLdouble v);
+void ( APIENTRY * qglEvalCoord2dv )(const GLdouble *u);
+void ( APIENTRY * qglEvalCoord2f )(GLfloat u, GLfloat v);
+void ( APIENTRY * qglEvalCoord2fv )(const GLfloat *u);
+void ( APIENTRY * qglEvalMesh1 )(GLenum mode, GLint i1, GLint i2);
+void ( APIENTRY * qglEvalMesh2 )(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2);
+void ( APIENTRY * qglEvalPoint1 )(GLint i);
+void ( APIENTRY * qglEvalPoint2 )(GLint i, GLint j);
+void ( APIENTRY * qglFeedbackBuffer )(GLsizei size, GLenum type, GLfloat *buffer);
+void ( APIENTRY * qglFinish )(void);
+void ( APIENTRY * qglFlush )(void);
+void ( APIENTRY * qglFogf )(GLenum pname, GLfloat param);
+void ( APIENTRY * qglFogfv )(GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglFogi )(GLenum pname, GLint param);
+void ( APIENTRY * qglFogiv )(GLenum pname, const GLint *params);
+void ( APIENTRY * qglFrontFace )(GLenum mode);
+void ( APIENTRY * qglFrustum )(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+GLuint ( APIENTRY * qglGenLists )(GLsizei range);
+void ( APIENTRY * qglGenTextures )(GLsizei n, GLuint *textures);
+void ( APIENTRY * qglGetBooleanv )(GLenum pname, GLboolean *params);
+void ( APIENTRY * qglGetClipPlane )(GLenum plane, GLdouble *equation);
+void ( APIENTRY * qglGetDoublev )(GLenum pname, GLdouble *params);
+GLenum ( APIENTRY * qglGetError )(void);
+void ( APIENTRY * qglGetFloatv )(GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetIntegerv )(GLenum pname, GLint *params);
+void ( APIENTRY * qglGetLightfv )(GLenum light, GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetLightiv )(GLenum light, GLenum pname, GLint *params);
+void ( APIENTRY * qglGetMapdv )(GLenum target, GLenum query, GLdouble *v);
+void ( APIENTRY * qglGetMapfv )(GLenum target, GLenum query, GLfloat *v);
+void ( APIENTRY * qglGetMapiv )(GLenum target, GLenum query, GLint *v);
+void ( APIENTRY * qglGetMaterialfv )(GLenum face, GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetMaterialiv )(GLenum face, GLenum pname, GLint *params);
+void ( APIENTRY * qglGetPixelMapfv )(GLenum map, GLfloat *values);
+void ( APIENTRY * qglGetPixelMapuiv )(GLenum map, GLuint *values);
+void ( APIENTRY * qglGetPixelMapusv )(GLenum map, GLushort *values);
+void ( APIENTRY * qglGetPointerv )(GLenum pname, GLvoid* *params);
+void ( APIENTRY * qglGetPolygonStipple )(GLubyte *mask);
+const GLubyte * ( APIENTRY * qglGetString )(GLenum name);
+void ( APIENTRY * qglGetTexEnvfv )(GLenum target, GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetTexEnviv )(GLenum target, GLenum pname, GLint *params);
+void ( APIENTRY * qglGetTexGendv )(GLenum coord, GLenum pname, GLdouble *params);
+void ( APIENTRY * qglGetTexGenfv )(GLenum coord, GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetTexGeniv )(GLenum coord, GLenum pname, GLint *params);
+void ( APIENTRY * qglGetTexImage )(GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels);
+void ( APIENTRY * qglGetTexLevelParameterfv )(GLenum target, GLint level, GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetTexLevelParameteriv )(GLenum target, GLint level, GLenum pname, GLint *params);
+void ( APIENTRY * qglGetTexParameterfv )(GLenum target, GLenum pname, GLfloat *params);
+void ( APIENTRY * qglGetTexParameteriv )(GLenum target, GLenum pname, GLint *params);
+void ( APIENTRY * qglHint )(GLenum target, GLenum mode);
+void ( APIENTRY * qglIndexMask )(GLuint mask);
+void ( APIENTRY * qglIndexPointer )(GLenum type, GLsizei stride, const GLvoid *pointer);
+void ( APIENTRY * qglIndexd )(GLdouble c);
+void ( APIENTRY * qglIndexdv )(const GLdouble *c);
+void ( APIENTRY * qglIndexf )(GLfloat c);
+void ( APIENTRY * qglIndexfv )(const GLfloat *c);
+void ( APIENTRY * qglIndexi )(GLint c);
+void ( APIENTRY * qglIndexiv )(const GLint *c);
+void ( APIENTRY * qglIndexs )(GLshort c);
+void ( APIENTRY * qglIndexsv )(const GLshort *c);
+void ( APIENTRY * qglIndexub )(GLubyte c);
+void ( APIENTRY * qglIndexubv )(const GLubyte *c);
+void ( APIENTRY * qglInitNames )(void);
+void ( APIENTRY * qglInterleavedArrays )(GLenum format, GLsizei stride, const GLvoid *pointer);
+GLboolean ( APIENTRY * qglIsEnabled )(GLenum cap);
+GLboolean ( APIENTRY * qglIsList )(GLuint list);
+GLboolean ( APIENTRY * qglIsTexture )(GLuint texture);
+void ( APIENTRY * qglLightModelf )(GLenum pname, GLfloat param);
+void ( APIENTRY * qglLightModelfv )(GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglLightModeli )(GLenum pname, GLint param);
+void ( APIENTRY * qglLightModeliv )(GLenum pname, const GLint *params);
+void ( APIENTRY * qglLightf )(GLenum light, GLenum pname, GLfloat param);
+void ( APIENTRY * qglLightfv )(GLenum light, GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglLighti )(GLenum light, GLenum pname, GLint param);
+void ( APIENTRY * qglLightiv )(GLenum light, GLenum pname, const GLint *params);
+void ( APIENTRY * qglLineStipple )(GLint factor, GLushort pattern);
+void ( APIENTRY * qglLineWidth )(GLfloat width);
+void ( APIENTRY * qglListBase )(GLuint base);
+void ( APIENTRY * qglLoadIdentity )(void);
+void ( APIENTRY * qglLoadMatrixd )(const GLdouble *m);
+void ( APIENTRY * qglLoadMatrixf )(const GLfloat *m);
+void ( APIENTRY * qglLoadName )(GLuint name);
+void ( APIENTRY * qglLogicOp )(GLenum opcode);
+void ( APIENTRY * qglMap1d )(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points);
+void ( APIENTRY * qglMap1f )(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points);
+void ( APIENTRY * qglMap2d )(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points);
+void ( APIENTRY * qglMap2f )(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points);
+void ( APIENTRY * qglMapGrid1d )(GLint un, GLdouble u1, GLdouble u2);
+void ( APIENTRY * qglMapGrid1f )(GLint un, GLfloat u1, GLfloat u2);
+void ( APIENTRY * qglMapGrid2d )(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2);
+void ( APIENTRY * qglMapGrid2f )(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2);
+void ( APIENTRY * qglMaterialf )(GLenum face, GLenum pname, GLfloat param);
+void ( APIENTRY * qglMaterialfv )(GLenum face, GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglMateriali )(GLenum face, GLenum pname, GLint param);
+void ( APIENTRY * qglMaterialiv )(GLenum face, GLenum pname, const GLint *params);
+void ( APIENTRY * qglMatrixMode )(GLenum mode);
+void ( APIENTRY * qglMultMatrixd )(const GLdouble *m);
+void ( APIENTRY * qglMultMatrixf )(const GLfloat *m);
+void ( APIENTRY * qglNewList )(GLuint list, GLenum mode);
+void ( APIENTRY * qglNormal3b )(GLbyte nx, GLbyte ny, GLbyte nz);
+void ( APIENTRY * qglNormal3bv )(const GLbyte *v);
+void ( APIENTRY * qglNormal3d )(GLdouble nx, GLdouble ny, GLdouble nz);
+void ( APIENTRY * qglNormal3dv )(const GLdouble *v);
+void ( APIENTRY * qglNormal3f )(GLfloat nx, GLfloat ny, GLfloat nz);
+void ( APIENTRY * qglNormal3fv )(const GLfloat *v);
+void ( APIENTRY * qglNormal3i )(GLint nx, GLint ny, GLint nz);
+void ( APIENTRY * qglNormal3iv )(const GLint *v);
+void ( APIENTRY * qglNormal3s )(GLshort nx, GLshort ny, GLshort nz);
+void ( APIENTRY * qglNormal3sv )(const GLshort *v);
+void ( APIENTRY * qglNormalPointer )(GLenum type, GLsizei stride, const GLvoid *pointer);
+void ( APIENTRY * qglOrtho )(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+void ( APIENTRY * qglPassThrough )(GLfloat token);
+void ( APIENTRY * qglPixelMapfv )(GLenum map, GLsizei mapsize, const GLfloat *values);
+void ( APIENTRY * qglPixelMapuiv )(GLenum map, GLsizei mapsize, const GLuint *values);
+void ( APIENTRY * qglPixelMapusv )(GLenum map, GLsizei mapsize, const GLushort *values);
+void ( APIENTRY * qglPixelStoref )(GLenum pname, GLfloat param);
+void ( APIENTRY * qglPixelStorei )(GLenum pname, GLint param);
+void ( APIENTRY * qglPixelTransferf )(GLenum pname, GLfloat param);
+void ( APIENTRY * qglPixelTransferi )(GLenum pname, GLint param);
+void ( APIENTRY * qglPixelZoom )(GLfloat xfactor, GLfloat yfactor);
+void ( APIENTRY * qglPointSize )(GLfloat size);
+void ( APIENTRY * qglPolygonMode )(GLenum face, GLenum mode);
+void ( APIENTRY * qglPolygonOffset )(GLfloat factor, GLfloat units);
+void ( APIENTRY * qglPolygonStipple )(const GLubyte *mask);
+void ( APIENTRY * qglPopAttrib )(void);
+void ( APIENTRY * qglPopClientAttrib )(void);
+void ( APIENTRY * qglPopMatrix )(void);
+void ( APIENTRY * qglPopName )(void);
+void ( APIENTRY * qglPrioritizeTextures )(GLsizei n, const GLuint *textures, const GLclampf *priorities);
+void ( APIENTRY * qglPushAttrib )(GLbitfield mask);
+void ( APIENTRY * qglPushClientAttrib )(GLbitfield mask);
+void ( APIENTRY * qglPushMatrix )(void);
+void ( APIENTRY * qglPushName )(GLuint name);
+void ( APIENTRY * qglRasterPos2d )(GLdouble x, GLdouble y);
+void ( APIENTRY * qglRasterPos2dv )(const GLdouble *v);
+void ( APIENTRY * qglRasterPos2f )(GLfloat x, GLfloat y);
+void ( APIENTRY * qglRasterPos2fv )(const GLfloat *v);
+void ( APIENTRY * qglRasterPos2i )(GLint x, GLint y);
+void ( APIENTRY * qglRasterPos2iv )(const GLint *v);
+void ( APIENTRY * qglRasterPos2s )(GLshort x, GLshort y);
+void ( APIENTRY * qglRasterPos2sv )(const GLshort *v);
+void ( APIENTRY * qglRasterPos3d )(GLdouble x, GLdouble y, GLdouble z);
+void ( APIENTRY * qglRasterPos3dv )(const GLdouble *v);
+void ( APIENTRY * qglRasterPos3f )(GLfloat x, GLfloat y, GLfloat z);
+void ( APIENTRY * qglRasterPos3fv )(const GLfloat *v);
+void ( APIENTRY * qglRasterPos3i )(GLint x, GLint y, GLint z);
+void ( APIENTRY * qglRasterPos3iv )(const GLint *v);
+void ( APIENTRY * qglRasterPos3s )(GLshort x, GLshort y, GLshort z);
+void ( APIENTRY * qglRasterPos3sv )(const GLshort *v);
+void ( APIENTRY * qglRasterPos4d )(GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+void ( APIENTRY * qglRasterPos4dv )(const GLdouble *v);
+void ( APIENTRY * qglRasterPos4f )(GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+void ( APIENTRY * qglRasterPos4fv )(const GLfloat *v);
+void ( APIENTRY * qglRasterPos4i )(GLint x, GLint y, GLint z, GLint w);
+void ( APIENTRY * qglRasterPos4iv )(const GLint *v);
+void ( APIENTRY * qglRasterPos4s )(GLshort x, GLshort y, GLshort z, GLshort w);
+void ( APIENTRY * qglRasterPos4sv )(const GLshort *v);
+void ( APIENTRY * qglReadBuffer )(GLenum mode);
+void ( APIENTRY * qglReadPixels )(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels);
+void ( APIENTRY * qglRectd )(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2);
+void ( APIENTRY * qglRectdv )(const GLdouble *v1, const GLdouble *v2);
+void ( APIENTRY * qglRectf )(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2);
+void ( APIENTRY * qglRectfv )(const GLfloat *v1, const GLfloat *v2);
+void ( APIENTRY * qglRecti )(GLint x1, GLint y1, GLint x2, GLint y2);
+void ( APIENTRY * qglRectiv )(const GLint *v1, const GLint *v2);
+void ( APIENTRY * qglRects )(GLshort x1, GLshort y1, GLshort x2, GLshort y2);
+void ( APIENTRY * qglRectsv )(const GLshort *v1, const GLshort *v2);
+GLint ( APIENTRY * qglRenderMode )(GLenum mode);
+void ( APIENTRY * qglRotated )(GLdouble angle, GLdouble x, GLdouble y, GLdouble z);
+void ( APIENTRY * qglRotatef )(GLfloat angle, GLfloat x, GLfloat y, GLfloat z);
+void ( APIENTRY * qglScaled )(GLdouble x, GLdouble y, GLdouble z);
+void ( APIENTRY * qglScalef )(GLfloat x, GLfloat y, GLfloat z);
+void ( APIENTRY * qglScissor )(GLint x, GLint y, GLsizei width, GLsizei height);
+void ( APIENTRY * qglSelectBuffer )(GLsizei size, GLuint *buffer);
+void ( APIENTRY * qglShadeModel )(GLenum mode);
+void ( APIENTRY * qglStencilFunc )(GLenum func, GLint ref, GLuint mask);
+void ( APIENTRY * qglStencilMask )(GLuint mask);
+void ( APIENTRY * qglStencilOp )(GLenum fail, GLenum zfail, GLenum zpass);
+void ( APIENTRY * qglTexCoord1d )(GLdouble s);
+void ( APIENTRY * qglTexCoord1dv )(const GLdouble *v);
+void ( APIENTRY * qglTexCoord1f )(GLfloat s);
+void ( APIENTRY * qglTexCoord1fv )(const GLfloat *v);
+void ( APIENTRY * qglTexCoord1i )(GLint s);
+void ( APIENTRY * qglTexCoord1iv )(const GLint *v);
+void ( APIENTRY * qglTexCoord1s )(GLshort s);
+void ( APIENTRY * qglTexCoord1sv )(const GLshort *v);
+void ( APIENTRY * qglTexCoord2d )(GLdouble s, GLdouble t);
+void ( APIENTRY * qglTexCoord2dv )(const GLdouble *v);
+void ( APIENTRY * qglTexCoord2f )(GLfloat s, GLfloat t);
+void ( APIENTRY * qglTexCoord2fv )(const GLfloat *v);
+void ( APIENTRY * qglTexCoord2i )(GLint s, GLint t);
+void ( APIENTRY * qglTexCoord2iv )(const GLint *v);
+void ( APIENTRY * qglTexCoord2s )(GLshort s, GLshort t);
+void ( APIENTRY * qglTexCoord2sv )(const GLshort *v);
+void ( APIENTRY * qglTexCoord3d )(GLdouble s, GLdouble t, GLdouble r);
+void ( APIENTRY * qglTexCoord3dv )(const GLdouble *v);
+void ( APIENTRY * qglTexCoord3f )(GLfloat s, GLfloat t, GLfloat r);
+void ( APIENTRY * qglTexCoord3fv )(const GLfloat *v);
+void ( APIENTRY * qglTexCoord3i )(GLint s, GLint t, GLint r);
+void ( APIENTRY * qglTexCoord3iv )(const GLint *v);
+void ( APIENTRY * qglTexCoord3s )(GLshort s, GLshort t, GLshort r);
+void ( APIENTRY * qglTexCoord3sv )(const GLshort *v);
+void ( APIENTRY * qglTexCoord4d )(GLdouble s, GLdouble t, GLdouble r, GLdouble q);
+void ( APIENTRY * qglTexCoord4dv )(const GLdouble *v);
+void ( APIENTRY * qglTexCoord4f )(GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+void ( APIENTRY * qglTexCoord4fv )(const GLfloat *v);
+void ( APIENTRY * qglTexCoord4i )(GLint s, GLint t, GLint r, GLint q);
+void ( APIENTRY * qglTexCoord4iv )(const GLint *v);
+void ( APIENTRY * qglTexCoord4s )(GLshort s, GLshort t, GLshort r, GLshort q);
+void ( APIENTRY * qglTexCoord4sv )(const GLshort *v);
+void ( APIENTRY * qglTexCoordPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+void ( APIENTRY * qglTexEnvf )(GLenum target, GLenum pname, GLfloat param);
+void ( APIENTRY * qglTexEnvfv )(GLenum target, GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglTexEnvi )(GLenum target, GLenum pname, GLint param);
+void ( APIENTRY * qglTexEnviv )(GLenum target, GLenum pname, const GLint *params);
+void ( APIENTRY * qglTexGend )(GLenum coord, GLenum pname, GLdouble param);
+void ( APIENTRY * qglTexGendv )(GLenum coord, GLenum pname, const GLdouble *params);
+void ( APIENTRY * qglTexGenf )(GLenum coord, GLenum pname, GLfloat param);
+void ( APIENTRY * qglTexGenfv )(GLenum coord, GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglTexGeni )(GLenum coord, GLenum pname, GLint param);
+void ( APIENTRY * qglTexGeniv )(GLenum coord, GLenum pname, const GLint *params);
+void ( APIENTRY * qglTexImage1D )(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+void ( APIENTRY * qglTexImage2D )(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+void ( APIENTRY * qglTexParameterf )(GLenum target, GLenum pname, GLfloat param);
+void ( APIENTRY * qglTexParameterfv )(GLenum target, GLenum pname, const GLfloat *params);
+void ( APIENTRY * qglTexParameteri )(GLenum target, GLenum pname, GLint param);
+void ( APIENTRY * qglTexParameteriv )(GLenum target, GLenum pname, const GLint *params);
+void ( APIENTRY * qglTexSubImage1D )(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels);
+void ( APIENTRY * qglTexSubImage2D )(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+void ( APIENTRY * qglTranslated )(GLdouble x, GLdouble y, GLdouble z);
+void ( APIENTRY * qglTranslatef )(GLfloat x, GLfloat y, GLfloat z);
+void ( APIENTRY * qglVertex2d )(GLdouble x, GLdouble y);
+void ( APIENTRY * qglVertex2dv )(const GLdouble *v);
+void ( APIENTRY * qglVertex2f )(GLfloat x, GLfloat y);
+void ( APIENTRY * qglVertex2fv )(const GLfloat *v);
+void ( APIENTRY * qglVertex2i )(GLint x, GLint y);
+void ( APIENTRY * qglVertex2iv )(const GLint *v);
+void ( APIENTRY * qglVertex2s )(GLshort x, GLshort y);
+void ( APIENTRY * qglVertex2sv )(const GLshort *v);
+void ( APIENTRY * qglVertex3d )(GLdouble x, GLdouble y, GLdouble z);
+void ( APIENTRY * qglVertex3dv )(const GLdouble *v);
+void ( APIENTRY * qglVertex3f )(GLfloat x, GLfloat y, GLfloat z);
+void ( APIENTRY * qglVertex3fv )(const GLfloat *v);
+void ( APIENTRY * qglVertex3i )(GLint x, GLint y, GLint z);
+void ( APIENTRY * qglVertex3iv )(const GLint *v);
+void ( APIENTRY * qglVertex3s )(GLshort x, GLshort y, GLshort z);
+void ( APIENTRY * qglVertex3sv )(const GLshort *v);
+void ( APIENTRY * qglVertex4d )(GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+void ( APIENTRY * qglVertex4dv )(const GLdouble *v);
+void ( APIENTRY * qglVertex4f )(GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+void ( APIENTRY * qglVertex4fv )(const GLfloat *v);
+void ( APIENTRY * qglVertex4i )(GLint x, GLint y, GLint z, GLint w);
+void ( APIENTRY * qglVertex4iv )(const GLint *v);
+void ( APIENTRY * qglVertex4s )(GLshort x, GLshort y, GLshort z, GLshort w);
+void ( APIENTRY * qglVertex4sv )(const GLshort *v);
+void ( APIENTRY * qglVertexPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+void ( APIENTRY * qglViewport )(GLint x, GLint y, GLsizei width, GLsizei height);
+
+BOOL ( WINAPI * qwglSwapIntervalEXT)( int interval );
+BOOL ( WINAPI * qwglGetDeviceGammaRampEXT)( unsigned char *, unsigned char *, unsigned char * );
+BOOL ( WINAPI * qwglSetDeviceGammaRampEXT)( const unsigned char *, const unsigned char *, const unsigned char * );
+void ( APIENTRY * qglPointParameterfEXT)( GLenum param, GLfloat value );
+void ( APIENTRY * qglPointParameterfvEXT)( GLenum param, const GLfloat *value );
+void ( APIENTRY * qglColorTableEXT)( int, int, int, int, int, const void * );
+void ( APIENTRY * qglSelectTextureSGIS)( GLenum );
+void ( APIENTRY * qglMTexCoord2fSGIS)( GLenum, GLfloat, GLfloat );
+
+static void ( APIENTRY * dllAccum )(GLenum op, GLfloat value);
+static void ( APIENTRY * dllAlphaFunc )(GLenum func, GLclampf ref);
+GLboolean ( APIENTRY * dllAreTexturesResident )(GLsizei n, const GLuint *textures, GLboolean *residences);
+static void ( APIENTRY * dllArrayElement )(GLint i);
+static void ( APIENTRY * dllBegin )(GLenum mode);
+static void ( APIENTRY * dllBindTexture )(GLenum target, GLuint texture);
+static void ( APIENTRY * dllBitmap )(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap);
+static void ( APIENTRY * dllBlendFunc )(GLenum sfactor, GLenum dfactor);
+static void ( APIENTRY * dllCallList )(GLuint list);
+static void ( APIENTRY * dllCallLists )(GLsizei n, GLenum type, const GLvoid *lists);
+static void ( APIENTRY * dllClear )(GLbitfield mask);
+static void ( APIENTRY * dllClearAccum )(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+static void ( APIENTRY * dllClearColor )(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+static void ( APIENTRY * dllClearDepth )(GLclampd depth);
+static void ( APIENTRY * dllClearIndex )(GLfloat c);
+static void ( APIENTRY * dllClearStencil )(GLint s);
+static void ( APIENTRY * dllClipPlane )(GLenum plane, const GLdouble *equation);
+static void ( APIENTRY * dllColor3b )(GLbyte red, GLbyte green, GLbyte blue);
+static void ( APIENTRY * dllColor3bv )(const GLbyte *v);
+static void ( APIENTRY * dllColor3d )(GLdouble red, GLdouble green, GLdouble blue);
+static void ( APIENTRY * dllColor3dv )(const GLdouble *v);
+static void ( APIENTRY * dllColor3f )(GLfloat red, GLfloat green, GLfloat blue);
+static void ( APIENTRY * dllColor3fv )(const GLfloat *v);
+static void ( APIENTRY * dllColor3i )(GLint red, GLint green, GLint blue);
+static void ( APIENTRY * dllColor3iv )(const GLint *v);
+static void ( APIENTRY * dllColor3s )(GLshort red, GLshort green, GLshort blue);
+static void ( APIENTRY * dllColor3sv )(const GLshort *v);
+static void ( APIENTRY * dllColor3ub )(GLubyte red, GLubyte green, GLubyte blue);
+static void ( APIENTRY * dllColor3ubv )(const GLubyte *v);
+static void ( APIENTRY * dllColor3ui )(GLuint red, GLuint green, GLuint blue);
+static void ( APIENTRY * dllColor3uiv )(const GLuint *v);
+static void ( APIENTRY * dllColor3us )(GLushort red, GLushort green, GLushort blue);
+static void ( APIENTRY * dllColor3usv )(const GLushort *v);
+static void ( APIENTRY * dllColor4b )(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha);
+static void ( APIENTRY * dllColor4bv )(const GLbyte *v);
+static void ( APIENTRY * dllColor4d )(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha);
+static void ( APIENTRY * dllColor4dv )(const GLdouble *v);
+static void ( APIENTRY * dllColor4f )(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+static void ( APIENTRY * dllColor4fv )(const GLfloat *v);
+static void ( APIENTRY * dllColor4i )(GLint red, GLint green, GLint blue, GLint alpha);
+static void ( APIENTRY * dllColor4iv )(const GLint *v);
+static void ( APIENTRY * dllColor4s )(GLshort red, GLshort green, GLshort blue, GLshort alpha);
+static void ( APIENTRY * dllColor4sv )(const GLshort *v);
+static void ( APIENTRY * dllColor4ub )(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha);
+static void ( APIENTRY * dllColor4ubv )(const GLubyte *v);
+static void ( APIENTRY * dllColor4ui )(GLuint red, GLuint green, GLuint blue, GLuint alpha);
+static void ( APIENTRY * dllColor4uiv )(const GLuint *v);
+static void ( APIENTRY * dllColor4us )(GLushort red, GLushort green, GLushort blue, GLushort alpha);
+static void ( APIENTRY * dllColor4usv )(const GLushort *v);
+static void ( APIENTRY * dllColorMask )(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
+static void ( APIENTRY * dllColorMaterial )(GLenum face, GLenum mode);
+static void ( APIENTRY * dllColorPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+static void ( APIENTRY * dllCopyPixels )(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type);
+static void ( APIENTRY * dllCopyTexImage1D )(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLint border);
+static void ( APIENTRY * dllCopyTexImage2D )(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+static void ( APIENTRY * dllCopyTexSubImage1D )(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
+static void ( APIENTRY * dllCopyTexSubImage2D )(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+static void ( APIENTRY * dllCullFace )(GLenum mode);
+static void ( APIENTRY * dllDeleteLists )(GLuint list, GLsizei range);
+static void ( APIENTRY * dllDeleteTextures )(GLsizei n, const GLuint *textures);
+static void ( APIENTRY * dllDepthFunc )(GLenum func);
+static void ( APIENTRY * dllDepthMask )(GLboolean flag);
+static void ( APIENTRY * dllDepthRange )(GLclampd zNear, GLclampd zFar);
+static void ( APIENTRY * dllDisable )(GLenum cap);
+static void ( APIENTRY * dllDisableClientState )(GLenum array);
+static void ( APIENTRY * dllDrawArrays )(GLenum mode, GLint first, GLsizei count);
+static void ( APIENTRY * dllDrawBuffer )(GLenum mode);
+static void ( APIENTRY * dllDrawElements )(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices);
+static void ( APIENTRY * dllDrawPixels )(GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+static void ( APIENTRY * dllEdgeFlag )(GLboolean flag);
+static void ( APIENTRY * dllEdgeFlagPointer )(GLsizei stride, const GLvoid *pointer);
+static void ( APIENTRY * dllEdgeFlagv )(const GLboolean *flag);
+static void ( APIENTRY * dllEnable )(GLenum cap);
+static void ( APIENTRY * dllEnableClientState )(GLenum array);
+static void ( APIENTRY * dllEnd )(void);
+static void ( APIENTRY * dllEndList )(void);
+static void ( APIENTRY * dllEvalCoord1d )(GLdouble u);
+static void ( APIENTRY * dllEvalCoord1dv )(const GLdouble *u);
+static void ( APIENTRY * dllEvalCoord1f )(GLfloat u);
+static void ( APIENTRY * dllEvalCoord1fv )(const GLfloat *u);
+static void ( APIENTRY * dllEvalCoord2d )(GLdouble u, GLdouble v);
+static void ( APIENTRY * dllEvalCoord2dv )(const GLdouble *u);
+static void ( APIENTRY * dllEvalCoord2f )(GLfloat u, GLfloat v);
+static void ( APIENTRY * dllEvalCoord2fv )(const GLfloat *u);
+static void ( APIENTRY * dllEvalMesh1 )(GLenum mode, GLint i1, GLint i2);
+static void ( APIENTRY * dllEvalMesh2 )(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2);
+static void ( APIENTRY * dllEvalPoint1 )(GLint i);
+static void ( APIENTRY * dllEvalPoint2 )(GLint i, GLint j);
+static void ( APIENTRY * dllFeedbackBuffer )(GLsizei size, GLenum type, GLfloat *buffer);
+static void ( APIENTRY * dllFinish )(void);
+static void ( APIENTRY * dllFlush )(void);
+static void ( APIENTRY * dllFogf )(GLenum pname, GLfloat param);
+static void ( APIENTRY * dllFogfv )(GLenum pname, const GLfloat *params);
+static void ( APIENTRY * dllFogi )(GLenum pname, GLint param);
+static void ( APIENTRY * dllFogiv )(GLenum pname, const GLint *params);
+static void ( APIENTRY * dllFrontFace )(GLenum mode);
+static void ( APIENTRY * dllFrustum )(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+GLuint ( APIENTRY * dllGenLists )(GLsizei range);
+static void ( APIENTRY * dllGenTextures )(GLsizei n, GLuint *textures);
+static void ( APIENTRY * dllGetBooleanv )(GLenum pname, GLboolean *params);
+static void ( APIENTRY * dllGetClipPlane )(GLenum plane, GLdouble *equation);
+static void ( APIENTRY * dllGetDoublev )(GLenum pname, GLdouble *params);
+GLenum ( APIENTRY * dllGetError )(void);
+static void ( APIENTRY * dllGetFloatv )(GLenum pname, GLfloat *params);
+static void ( APIENTRY * dllGetIntegerv )(GLenum pname, GLint *params);
+static void ( APIENTRY * dllGetLightfv )(GLenum light, GLenum pname, GLfloat *params);
+static void ( APIENTRY * dllGetLightiv )(GLenum light, GLenum pname, GLint *params);
+static void ( APIENTRY * dllGetMapdv )(GLenum target, GLenum query, GLdouble *v);
+static void ( APIENTRY * dllGetMapfv )(GLenum target, GLenum query, GLfloat *v);
+static void ( APIENTRY * dllGetMapiv )(GLenum target, GLenum query, GLint *v);
+static void ( APIENTRY * dllGetMaterialfv )(GLenum face, GLenum pname, GLfloat *params);
+static void ( APIENTRY * dllGetMaterialiv )(GLenum face, GLenum pname, GLint *params);
+static void ( APIENTRY * dllGetPixelMapfv )(GLenum map, GLfloat *values);
+static void ( APIENTRY * dllGetPixelMapuiv )(GLenum map, GLuint *values);
+static void ( APIENTRY * dllGetPixelMapusv )(GLenum map, GLushort *values);
+static void ( APIENTRY * dllGetPointerv )(GLenum pname, GLvoid* *params);
+static void ( APIENTRY * dllGetPolygonStipple )(GLubyte *mask);
+const GLubyte * ( APIENTRY * dllGetString )(GLenum name);
+static void ( APIENTRY * dllGetTexEnvfv )(GLenum target, GLenum pname, GLfloat *params);
+static void ( APIENTRY * dllGetTexEnviv )(GLenum target, GLenum pname, GLint *params);
+static void ( APIENTRY * dllGetTexGendv )(GLenum coord, GLenum pname, GLdouble *params);
+static void ( APIENTRY * dllGetTexGenfv )(GLenum coord, GLenum pname, GLfloat *params);
+static void ( APIENTRY * dllGetTexGeniv )(GLenum coord, GLenum pname, GLint *params);
+static void ( APIENTRY * dllGetTexImage )(GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels);
+static void ( APIENTRY * dllGetTexLevelParameterfv )(GLenum target, GLint level, GLenum pname, GLfloat *params);
+static void ( APIENTRY * dllGetTexLevelParameteriv )(GLenum target, GLint level, GLenum pname, GLint *params);
+static void ( APIENTRY * dllGetTexParameterfv )(GLenum target, GLenum pname, GLfloat *params);
+static void ( APIENTRY * dllGetTexParameteriv )(GLenum target, GLenum pname, GLint *params);
+static void ( APIENTRY * dllHint )(GLenum target, GLenum mode);
+static void ( APIENTRY * dllIndexMask )(GLuint mask);
+static void ( APIENTRY * dllIndexPointer )(GLenum type, GLsizei stride, const GLvoid *pointer);
+static void ( APIENTRY * dllIndexd )(GLdouble c);
+static void ( APIENTRY * dllIndexdv )(const GLdouble *c);
+static void ( APIENTRY * dllIndexf )(GLfloat c);
+static void ( APIENTRY * dllIndexfv )(const GLfloat *c);
+static void ( APIENTRY * dllIndexi )(GLint c);
+static void ( APIENTRY * dllIndexiv )(const GLint *c);
+static void ( APIENTRY * dllIndexs )(GLshort c);
+static void ( APIENTRY * dllIndexsv )(const GLshort *c);
+static void ( APIENTRY * dllIndexub )(GLubyte c);
+static void ( APIENTRY * dllIndexubv )(const GLubyte *c);
+static void ( APIENTRY * dllInitNames )(void);
+static void ( APIENTRY * dllInterleavedArrays )(GLenum format, GLsizei stride, const GLvoid *pointer);
+GLboolean ( APIENTRY * dllIsEnabled )(GLenum cap);
+GLboolean ( APIENTRY * dllIsList )(GLuint list);
+GLboolean ( APIENTRY * dllIsTexture )(GLuint texture);
+static void ( APIENTRY * dllLightModelf )(GLenum pname, GLfloat param);
+static void ( APIENTRY * dllLightModelfv )(GLenum pname, const GLfloat *params);
+static void ( APIENTRY * dllLightModeli )(GLenum pname, GLint param);
+static void ( APIENTRY * dllLightModeliv )(GLenum pname, const GLint *params);
+static void ( APIENTRY * dllLightf )(GLenum light, GLenum pname, GLfloat param);
+static void ( APIENTRY * dllLightfv )(GLenum light, GLenum pname, const GLfloat *params);
+static void ( APIENTRY * dllLighti )(GLenum light, GLenum pname, GLint param);
+static void ( APIENTRY * dllLightiv )(GLenum light, GLenum pname, const GLint *params);
+static void ( APIENTRY * dllLineStipple )(GLint factor, GLushort pattern);
+static void ( APIENTRY * dllLineWidth )(GLfloat width);
+static void ( APIENTRY * dllListBase )(GLuint base);
+static void ( APIENTRY * dllLoadIdentity )(void);
+static void ( APIENTRY * dllLoadMatrixd )(const GLdouble *m);
+static void ( APIENTRY * dllLoadMatrixf )(const GLfloat *m);
+static void ( APIENTRY * dllLoadName )(GLuint name);
+static void ( APIENTRY * dllLogicOp )(GLenum opcode);
+static void ( APIENTRY * dllMap1d )(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points);
+static void ( APIENTRY * dllMap1f )(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points);
+static void ( APIENTRY * dllMap2d )(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points);
+static void ( APIENTRY * dllMap2f )(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points);
+static void ( APIENTRY * dllMapGrid1d )(GLint un, GLdouble u1, GLdouble u2);
+static void ( APIENTRY * dllMapGrid1f )(GLint un, GLfloat u1, GLfloat u2);
+static void ( APIENTRY * dllMapGrid2d )(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2);
+static void ( APIENTRY * dllMapGrid2f )(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2);
+static void ( APIENTRY * dllMaterialf )(GLenum face, GLenum pname, GLfloat param);
+static void ( APIENTRY * dllMaterialfv )(GLenum face, GLenum pname, const GLfloat *params);
+static void ( APIENTRY * dllMateriali )(GLenum face, GLenum pname, GLint param);
+static void ( APIENTRY * dllMaterialiv )(GLenum face, GLenum pname, const GLint *params);
+static void ( APIENTRY * dllMatrixMode )(GLenum mode);
+static void ( APIENTRY * dllMultMatrixd )(const GLdouble *m);
+static void ( APIENTRY * dllMultMatrixf )(const GLfloat *m);
+static void ( APIENTRY * dllNewList )(GLuint list, GLenum mode);
+static void ( APIENTRY * dllNormal3b )(GLbyte nx, GLbyte ny, GLbyte nz);
+static void ( APIENTRY * dllNormal3bv )(const GLbyte *v);
+static void ( APIENTRY * dllNormal3d )(GLdouble nx, GLdouble ny, GLdouble nz);
+static void ( APIENTRY * dllNormal3dv )(const GLdouble *v);
+static void ( APIENTRY * dllNormal3f )(GLfloat nx, GLfloat ny, GLfloat nz);
+static void ( APIENTRY * dllNormal3fv )(const GLfloat *v);
+static void ( APIENTRY * dllNormal3i )(GLint nx, GLint ny, GLint nz);
+static void ( APIENTRY * dllNormal3iv )(const GLint *v);
+static void ( APIENTRY * dllNormal3s )(GLshort nx, GLshort ny, GLshort nz);
+static void ( APIENTRY * dllNormal3sv )(const GLshort *v);
+static void ( APIENTRY * dllNormalPointer )(GLenum type, GLsizei stride, const GLvoid *pointer);
+static void ( APIENTRY * dllOrtho )(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+static void ( APIENTRY * dllPassThrough )(GLfloat token);
+static void ( APIENTRY * dllPixelMapfv )(GLenum map, GLsizei mapsize, const GLfloat *values);
+static void ( APIENTRY * dllPixelMapuiv )(GLenum map, GLsizei mapsize, const GLuint *values);
+static void ( APIENTRY * dllPixelMapusv )(GLenum map, GLsizei mapsize, const GLushort *values);
+static void ( APIENTRY * dllPixelStoref )(GLenum pname, GLfloat param);
+static void ( APIENTRY * dllPixelStorei )(GLenum pname, GLint param);
+static void ( APIENTRY * dllPixelTransferf )(GLenum pname, GLfloat param);
+static void ( APIENTRY * dllPixelTransferi )(GLenum pname, GLint param);
+static void ( APIENTRY * dllPixelZoom )(GLfloat xfactor, GLfloat yfactor);
+static void ( APIENTRY * dllPointSize )(GLfloat size);
+static void ( APIENTRY * dllPolygonMode )(GLenum face, GLenum mode);
+static void ( APIENTRY * dllPolygonOffset )(GLfloat factor, GLfloat units);
+static void ( APIENTRY * dllPolygonStipple )(const GLubyte *mask);
+static void ( APIENTRY * dllPopAttrib )(void);
+static void ( APIENTRY * dllPopClientAttrib )(void);
+static void ( APIENTRY * dllPopMatrix )(void);
+static void ( APIENTRY * dllPopName )(void);
+static void ( APIENTRY * dllPrioritizeTextures )(GLsizei n, const GLuint *textures, const GLclampf *priorities);
+static void ( APIENTRY * dllPushAttrib )(GLbitfield mask);
+static void ( APIENTRY * dllPushClientAttrib )(GLbitfield mask);
+static void ( APIENTRY * dllPushMatrix )(void);
+static void ( APIENTRY * dllPushName )(GLuint name);
+static void ( APIENTRY * dllRasterPos2d )(GLdouble x, GLdouble y);
+static void ( APIENTRY * dllRasterPos2dv )(const GLdouble *v);
+static void ( APIENTRY * dllRasterPos2f )(GLfloat x, GLfloat y);
+static void ( APIENTRY * dllRasterPos2fv )(const GLfloat *v);
+static void ( APIENTRY * dllRasterPos2i )(GLint x, GLint y);
+static void ( APIENTRY * dllRasterPos2iv )(const GLint *v);
+static void ( APIENTRY * dllRasterPos2s )(GLshort x, GLshort y);
+static void ( APIENTRY * dllRasterPos2sv )(const GLshort *v);
+static void ( APIENTRY * dllRasterPos3d )(GLdouble x, GLdouble y, GLdouble z);
+static void ( APIENTRY * dllRasterPos3dv )(const GLdouble *v);
+static void ( APIENTRY * dllRasterPos3f )(GLfloat x, GLfloat y, GLfloat z);
+static void ( APIENTRY * dllRasterPos3fv )(const GLfloat *v);
+static void ( APIENTRY * dllRasterPos3i )(GLint x, GLint y, GLint z);
+static void ( APIENTRY * dllRasterPos3iv )(const GLint *v);
+static void ( APIENTRY * dllRasterPos3s )(GLshort x, GLshort y, GLshort z);
+static void ( APIENTRY * dllRasterPos3sv )(const GLshort *v);
+static void ( APIENTRY * dllRasterPos4d )(GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+static void ( APIENTRY * dllRasterPos4dv )(const GLdouble *v);
+static void ( APIENTRY * dllRasterPos4f )(GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+static void ( APIENTRY * dllRasterPos4fv )(const GLfloat *v);
+static void ( APIENTRY * dllRasterPos4i )(GLint x, GLint y, GLint z, GLint w);
+static void ( APIENTRY * dllRasterPos4iv )(const GLint *v);
+static void ( APIENTRY * dllRasterPos4s )(GLshort x, GLshort y, GLshort z, GLshort w);
+static void ( APIENTRY * dllRasterPos4sv )(const GLshort *v);
+static void ( APIENTRY * dllReadBuffer )(GLenum mode);
+static void ( APIENTRY * dllReadPixels )(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels);
+static void ( APIENTRY * dllRectd )(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2);
+static void ( APIENTRY * dllRectdv )(const GLdouble *v1, const GLdouble *v2);
+static void ( APIENTRY * dllRectf )(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2);
+static void ( APIENTRY * dllRectfv )(const GLfloat *v1, const GLfloat *v2);
+static void ( APIENTRY * dllRecti )(GLint x1, GLint y1, GLint x2, GLint y2);
+static void ( APIENTRY * dllRectiv )(const GLint *v1, const GLint *v2);
+static void ( APIENTRY * dllRects )(GLshort x1, GLshort y1, GLshort x2, GLshort y2);
+static void ( APIENTRY * dllRectsv )(const GLshort *v1, const GLshort *v2);
+GLint ( APIENTRY * dllRenderMode )(GLenum mode);
+static void ( APIENTRY * dllRotated )(GLdouble angle, GLdouble x, GLdouble y, GLdouble z);
+static void ( APIENTRY * dllRotatef )(GLfloat angle, GLfloat x, GLfloat y, GLfloat z);
+static void ( APIENTRY * dllScaled )(GLdouble x, GLdouble y, GLdouble z);
+static void ( APIENTRY * dllScalef )(GLfloat x, GLfloat y, GLfloat z);
+static void ( APIENTRY * dllScissor )(GLint x, GLint y, GLsizei width, GLsizei height);
+static void ( APIENTRY * dllSelectBuffer )(GLsizei size, GLuint *buffer);
+static void ( APIENTRY * dllShadeModel )(GLenum mode);
+static void ( APIENTRY * dllStencilFunc )(GLenum func, GLint ref, GLuint mask);
+static void ( APIENTRY * dllStencilMask )(GLuint mask);
+static void ( APIENTRY * dllStencilOp )(GLenum fail, GLenum zfail, GLenum zpass);
+static void ( APIENTRY * dllTexCoord1d )(GLdouble s);
+static void ( APIENTRY * dllTexCoord1dv )(const GLdouble *v);
+static void ( APIENTRY * dllTexCoord1f )(GLfloat s);
+static void ( APIENTRY * dllTexCoord1fv )(const GLfloat *v);
+static void ( APIENTRY * dllTexCoord1i )(GLint s);
+static void ( APIENTRY * dllTexCoord1iv )(const GLint *v);
+static void ( APIENTRY * dllTexCoord1s )(GLshort s);
+static void ( APIENTRY * dllTexCoord1sv )(const GLshort *v);
+static void ( APIENTRY * dllTexCoord2d )(GLdouble s, GLdouble t);
+static void ( APIENTRY * dllTexCoord2dv )(const GLdouble *v);
+static void ( APIENTRY * dllTexCoord2f )(GLfloat s, GLfloat t);
+static void ( APIENTRY * dllTexCoord2fv )(const GLfloat *v);
+static void ( APIENTRY * dllTexCoord2i )(GLint s, GLint t);
+static void ( APIENTRY * dllTexCoord2iv )(const GLint *v);
+static void ( APIENTRY * dllTexCoord2s )(GLshort s, GLshort t);
+static void ( APIENTRY * dllTexCoord2sv )(const GLshort *v);
+static void ( APIENTRY * dllTexCoord3d )(GLdouble s, GLdouble t, GLdouble r);
+static void ( APIENTRY * dllTexCoord3dv )(const GLdouble *v);
+static void ( APIENTRY * dllTexCoord3f )(GLfloat s, GLfloat t, GLfloat r);
+static void ( APIENTRY * dllTexCoord3fv )(const GLfloat *v);
+static void ( APIENTRY * dllTexCoord3i )(GLint s, GLint t, GLint r);
+static void ( APIENTRY * dllTexCoord3iv )(const GLint *v);
+static void ( APIENTRY * dllTexCoord3s )(GLshort s, GLshort t, GLshort r);
+static void ( APIENTRY * dllTexCoord3sv )(const GLshort *v);
+static void ( APIENTRY * dllTexCoord4d )(GLdouble s, GLdouble t, GLdouble r, GLdouble q);
+static void ( APIENTRY * dllTexCoord4dv )(const GLdouble *v);
+static void ( APIENTRY * dllTexCoord4f )(GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+static void ( APIENTRY * dllTexCoord4fv )(const GLfloat *v);
+static void ( APIENTRY * dllTexCoord4i )(GLint s, GLint t, GLint r, GLint q);
+static void ( APIENTRY * dllTexCoord4iv )(const GLint *v);
+static void ( APIENTRY * dllTexCoord4s )(GLshort s, GLshort t, GLshort r, GLshort q);
+static void ( APIENTRY * dllTexCoord4sv )(const GLshort *v);
+static void ( APIENTRY * dllTexCoordPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+static void ( APIENTRY * dllTexEnvf )(GLenum target, GLenum pname, GLfloat param);
+static void ( APIENTRY * dllTexEnvfv )(GLenum target, GLenum pname, const GLfloat *params);
+static void ( APIENTRY * dllTexEnvi )(GLenum target, GLenum pname, GLint param);
+static void ( APIENTRY * dllTexEnviv )(GLenum target, GLenum pname, const GLint *params);
+static void ( APIENTRY * dllTexGend )(GLenum coord, GLenum pname, GLdouble param);
+static void ( APIENTRY * dllTexGendv )(GLenum coord, GLenum pname, const GLdouble *params);
+static void ( APIENTRY * dllTexGenf )(GLenum coord, GLenum pname, GLfloat param);
+static void ( APIENTRY * dllTexGenfv )(GLenum coord, GLenum pname, const GLfloat *params);
+static void ( APIENTRY * dllTexGeni )(GLenum coord, GLenum pname, GLint param);
+static void ( APIENTRY * dllTexGeniv )(GLenum coord, GLenum pname, const GLint *params);
+static void ( APIENTRY * dllTexImage1D )(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+static void ( APIENTRY * dllTexImage2D )(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+static void ( APIENTRY * dllTexParameterf )(GLenum target, GLenum pname, GLfloat param);
+static void ( APIENTRY * dllTexParameterfv )(GLenum target, GLenum pname, const GLfloat *params);
+static void ( APIENTRY * dllTexParameteri )(GLenum target, GLenum pname, GLint param);
+static void ( APIENTRY * dllTexParameteriv )(GLenum target, GLenum pname, const GLint *params);
+static void ( APIENTRY * dllTexSubImage1D )(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels);
+static void ( APIENTRY * dllTexSubImage2D )(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+static void ( APIENTRY * dllTranslated )(GLdouble x, GLdouble y, GLdouble z);
+static void ( APIENTRY * dllTranslatef )(GLfloat x, GLfloat y, GLfloat z);
+static void ( APIENTRY * dllVertex2d )(GLdouble x, GLdouble y);
+static void ( APIENTRY * dllVertex2dv )(const GLdouble *v);
+static void ( APIENTRY * dllVertex2f )(GLfloat x, GLfloat y);
+static void ( APIENTRY * dllVertex2fv )(const GLfloat *v);
+static void ( APIENTRY * dllVertex2i )(GLint x, GLint y);
+static void ( APIENTRY * dllVertex2iv )(const GLint *v);
+static void ( APIENTRY * dllVertex2s )(GLshort x, GLshort y);
+static void ( APIENTRY * dllVertex2sv )(const GLshort *v);
+static void ( APIENTRY * dllVertex3d )(GLdouble x, GLdouble y, GLdouble z);
+static void ( APIENTRY * dllVertex3dv )(const GLdouble *v);
+static void ( APIENTRY * dllVertex3f )(GLfloat x, GLfloat y, GLfloat z);
+static void ( APIENTRY * dllVertex3fv )(const GLfloat *v);
+static void ( APIENTRY * dllVertex3i )(GLint x, GLint y, GLint z);
+static void ( APIENTRY * dllVertex3iv )(const GLint *v);
+static void ( APIENTRY * dllVertex3s )(GLshort x, GLshort y, GLshort z);
+static void ( APIENTRY * dllVertex3sv )(const GLshort *v);
+static void ( APIENTRY * dllVertex4d )(GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+static void ( APIENTRY * dllVertex4dv )(const GLdouble *v);
+static void ( APIENTRY * dllVertex4f )(GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+static void ( APIENTRY * dllVertex4fv )(const GLfloat *v);
+static void ( APIENTRY * dllVertex4i )(GLint x, GLint y, GLint z, GLint w);
+static void ( APIENTRY * dllVertex4iv )(const GLint *v);
+static void ( APIENTRY * dllVertex4s )(GLshort x, GLshort y, GLshort z, GLshort w);
+static void ( APIENTRY * dllVertex4sv )(const GLshort *v);
+static void ( APIENTRY * dllVertexPointer )(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+static void ( APIENTRY * dllViewport )(GLint x, GLint y, GLsizei width, GLsizei height);
+
+/*
+** QGL_Shutdown
+**
+** Unloads the specified DLL then nulls out all the proc pointers.
+*/
+void QGL_Shutdown( void )
+{
+ if (g_hGLDLL)
+ {
+ ::FreeLibrary(g_hGLDLL);
+ g_hGLDLL = NULL;
+ }
+
+ qglAccum = NULL;
+ qglAlphaFunc = NULL;
+ qglAreTexturesResident = NULL;
+ qglArrayElement = NULL;
+ qglBegin = NULL;
+ qglBindTexture = NULL;
+ qglBitmap = NULL;
+ qglBlendFunc = NULL;
+ qglCallList = NULL;
+ qglCallLists = NULL;
+ qglClear = NULL;
+ qglClearAccum = NULL;
+ qglClearColor = NULL;
+ qglClearDepth = NULL;
+ qglClearIndex = NULL;
+ qglClearStencil = NULL;
+ qglClipPlane = NULL;
+ qglColor3b = NULL;
+ qglColor3bv = NULL;
+ qglColor3d = NULL;
+ qglColor3dv = NULL;
+ qglColor3f = NULL;
+ qglColor3fv = NULL;
+ qglColor3i = NULL;
+ qglColor3iv = NULL;
+ qglColor3s = NULL;
+ qglColor3sv = NULL;
+ qglColor3ub = NULL;
+ qglColor3ubv = NULL;
+ qglColor3ui = NULL;
+ qglColor3uiv = NULL;
+ qglColor3us = NULL;
+ qglColor3usv = NULL;
+ qglColor4b = NULL;
+ qglColor4bv = NULL;
+ qglColor4d = NULL;
+ qglColor4dv = NULL;
+ qglColor4f = NULL;
+ qglColor4fv = NULL;
+ qglColor4i = NULL;
+ qglColor4iv = NULL;
+ qglColor4s = NULL;
+ qglColor4sv = NULL;
+ qglColor4ub = NULL;
+ qglColor4ubv = NULL;
+ qglColor4ui = NULL;
+ qglColor4uiv = NULL;
+ qglColor4us = NULL;
+ qglColor4usv = NULL;
+ qglColorMask = NULL;
+ qglColorMaterial = NULL;
+ qglColorPointer = NULL;
+ qglCopyPixels = NULL;
+ qglCopyTexImage1D = NULL;
+ qglCopyTexImage2D = NULL;
+ qglCopyTexSubImage1D = NULL;
+ qglCopyTexSubImage2D = NULL;
+ qglCullFace = NULL;
+ qglDeleteLists = NULL;
+ qglDeleteTextures = NULL;
+ qglDepthFunc = NULL;
+ qglDepthMask = NULL;
+ qglDepthRange = NULL;
+ qglDisable = NULL;
+ qglDisableClientState = NULL;
+ qglDrawArrays = NULL;
+ qglDrawBuffer = NULL;
+ qglDrawElements = NULL;
+ qglDrawPixels = NULL;
+ qglEdgeFlag = NULL;
+ qglEdgeFlagPointer = NULL;
+ qglEdgeFlagv = NULL;
+ qglEnable = NULL;
+ qglEnableClientState = NULL;
+ qglEnd = NULL;
+ qglEndList = NULL;
+ qglEvalCoord1d = NULL;
+ qglEvalCoord1dv = NULL;
+ qglEvalCoord1f = NULL;
+ qglEvalCoord1fv = NULL;
+ qglEvalCoord2d = NULL;
+ qglEvalCoord2dv = NULL;
+ qglEvalCoord2f = NULL;
+ qglEvalCoord2fv = NULL;
+ qglEvalMesh1 = NULL;
+ qglEvalMesh2 = NULL;
+ qglEvalPoint1 = NULL;
+ qglEvalPoint2 = NULL;
+ qglFeedbackBuffer = NULL;
+ qglFinish = NULL;
+ qglFlush = NULL;
+ qglFogf = NULL;
+ qglFogfv = NULL;
+ qglFogi = NULL;
+ qglFogiv = NULL;
+ qglFrontFace = NULL;
+ qglFrustum = NULL;
+ qglGenLists = NULL;
+ qglGenTextures = NULL;
+ qglGetBooleanv = NULL;
+ qglGetClipPlane = NULL;
+ qglGetDoublev = NULL;
+ qglGetError = NULL;
+ qglGetFloatv = NULL;
+ qglGetIntegerv = NULL;
+ qglGetLightfv = NULL;
+ qglGetLightiv = NULL;
+ qglGetMapdv = NULL;
+ qglGetMapfv = NULL;
+ qglGetMapiv = NULL;
+ qglGetMaterialfv = NULL;
+ qglGetMaterialiv = NULL;
+ qglGetPixelMapfv = NULL;
+ qglGetPixelMapuiv = NULL;
+ qglGetPixelMapusv = NULL;
+ qglGetPointerv = NULL;
+ qglGetPolygonStipple = NULL;
+ qglGetString = NULL;
+ qglGetTexEnvfv = NULL;
+ qglGetTexEnviv = NULL;
+ qglGetTexGendv = NULL;
+ qglGetTexGenfv = NULL;
+ qglGetTexGeniv = NULL;
+ qglGetTexImage = NULL;
+ qglGetTexLevelParameterfv = NULL;
+ qglGetTexLevelParameteriv = NULL;
+ qglGetTexParameterfv = NULL;
+ qglGetTexParameteriv = NULL;
+ qglHint = NULL;
+ qglIndexMask = NULL;
+ qglIndexPointer = NULL;
+ qglIndexd = NULL;
+ qglIndexdv = NULL;
+ qglIndexf = NULL;
+ qglIndexfv = NULL;
+ qglIndexi = NULL;
+ qglIndexiv = NULL;
+ qglIndexs = NULL;
+ qglIndexsv = NULL;
+ qglIndexub = NULL;
+ qglIndexubv = NULL;
+ qglInitNames = NULL;
+ qglInterleavedArrays = NULL;
+ qglIsEnabled = NULL;
+ qglIsList = NULL;
+ qglIsTexture = NULL;
+ qglLightModelf = NULL;
+ qglLightModelfv = NULL;
+ qglLightModeli = NULL;
+ qglLightModeliv = NULL;
+ qglLightf = NULL;
+ qglLightfv = NULL;
+ qglLighti = NULL;
+ qglLightiv = NULL;
+ qglLineStipple = NULL;
+ qglLineWidth = NULL;
+ qglListBase = NULL;
+ qglLoadIdentity = NULL;
+ qglLoadMatrixd = NULL;
+ qglLoadMatrixf = NULL;
+ qglLoadName = NULL;
+ qglLogicOp = NULL;
+ qglMap1d = NULL;
+ qglMap1f = NULL;
+ qglMap2d = NULL;
+ qglMap2f = NULL;
+ qglMapGrid1d = NULL;
+ qglMapGrid1f = NULL;
+ qglMapGrid2d = NULL;
+ qglMapGrid2f = NULL;
+ qglMaterialf = NULL;
+ qglMaterialfv = NULL;
+ qglMateriali = NULL;
+ qglMaterialiv = NULL;
+ qglMatrixMode = NULL;
+ qglMultMatrixd = NULL;
+ qglMultMatrixf = NULL;
+ qglNewList = NULL;
+ qglNormal3b = NULL;
+ qglNormal3bv = NULL;
+ qglNormal3d = NULL;
+ qglNormal3dv = NULL;
+ qglNormal3f = NULL;
+ qglNormal3fv = NULL;
+ qglNormal3i = NULL;
+ qglNormal3iv = NULL;
+ qglNormal3s = NULL;
+ qglNormal3sv = NULL;
+ qglNormalPointer = NULL;
+ qglOrtho = NULL;
+ qglPassThrough = NULL;
+ qglPixelMapfv = NULL;
+ qglPixelMapuiv = NULL;
+ qglPixelMapusv = NULL;
+ qglPixelStoref = NULL;
+ qglPixelStorei = NULL;
+ qglPixelTransferf = NULL;
+ qglPixelTransferi = NULL;
+ qglPixelZoom = NULL;
+ qglPointSize = NULL;
+ qglPolygonMode = NULL;
+ qglPolygonOffset = NULL;
+ qglPolygonStipple = NULL;
+ qglPopAttrib = NULL;
+ qglPopClientAttrib = NULL;
+ qglPopMatrix = NULL;
+ qglPopName = NULL;
+ qglPrioritizeTextures = NULL;
+ qglPushAttrib = NULL;
+ qglPushClientAttrib = NULL;
+ qglPushMatrix = NULL;
+ qglPushName = NULL;
+ qglRasterPos2d = NULL;
+ qglRasterPos2dv = NULL;
+ qglRasterPos2f = NULL;
+ qglRasterPos2fv = NULL;
+ qglRasterPos2i = NULL;
+ qglRasterPos2iv = NULL;
+ qglRasterPos2s = NULL;
+ qglRasterPos2sv = NULL;
+ qglRasterPos3d = NULL;
+ qglRasterPos3dv = NULL;
+ qglRasterPos3f = NULL;
+ qglRasterPos3fv = NULL;
+ qglRasterPos3i = NULL;
+ qglRasterPos3iv = NULL;
+ qglRasterPos3s = NULL;
+ qglRasterPos3sv = NULL;
+ qglRasterPos4d = NULL;
+ qglRasterPos4dv = NULL;
+ qglRasterPos4f = NULL;
+ qglRasterPos4fv = NULL;
+ qglRasterPos4i = NULL;
+ qglRasterPos4iv = NULL;
+ qglRasterPos4s = NULL;
+ qglRasterPos4sv = NULL;
+ qglReadBuffer = NULL;
+ qglReadPixels = NULL;
+ qglRectd = NULL;
+ qglRectdv = NULL;
+ qglRectf = NULL;
+ qglRectfv = NULL;
+ qglRecti = NULL;
+ qglRectiv = NULL;
+ qglRects = NULL;
+ qglRectsv = NULL;
+ qglRenderMode = NULL;
+ qglRotated = NULL;
+ qglRotatef = NULL;
+ qglScaled = NULL;
+ qglScalef = NULL;
+ qglScissor = NULL;
+ qglSelectBuffer = NULL;
+ qglShadeModel = NULL;
+ qglStencilFunc = NULL;
+ qglStencilMask = NULL;
+ qglStencilOp = NULL;
+ qglTexCoord1d = NULL;
+ qglTexCoord1dv = NULL;
+ qglTexCoord1f = NULL;
+ qglTexCoord1fv = NULL;
+ qglTexCoord1i = NULL;
+ qglTexCoord1iv = NULL;
+ qglTexCoord1s = NULL;
+ qglTexCoord1sv = NULL;
+ qglTexCoord2d = NULL;
+ qglTexCoord2dv = NULL;
+ qglTexCoord2f = NULL;
+ qglTexCoord2fv = NULL;
+ qglTexCoord2i = NULL;
+ qglTexCoord2iv = NULL;
+ qglTexCoord2s = NULL;
+ qglTexCoord2sv = NULL;
+ qglTexCoord3d = NULL;
+ qglTexCoord3dv = NULL;
+ qglTexCoord3f = NULL;
+ qglTexCoord3fv = NULL;
+ qglTexCoord3i = NULL;
+ qglTexCoord3iv = NULL;
+ qglTexCoord3s = NULL;
+ qglTexCoord3sv = NULL;
+ qglTexCoord4d = NULL;
+ qglTexCoord4dv = NULL;
+ qglTexCoord4f = NULL;
+ qglTexCoord4fv = NULL;
+ qglTexCoord4i = NULL;
+ qglTexCoord4iv = NULL;
+ qglTexCoord4s = NULL;
+ qglTexCoord4sv = NULL;
+ qglTexCoordPointer = NULL;
+ qglTexEnvf = NULL;
+ qglTexEnvfv = NULL;
+ qglTexEnvi = NULL;
+ qglTexEnviv = NULL;
+ qglTexGend = NULL;
+ qglTexGendv = NULL;
+ qglTexGenf = NULL;
+ qglTexGenfv = NULL;
+ qglTexGeni = NULL;
+ qglTexGeniv = NULL;
+ qglTexImage1D = NULL;
+ qglTexImage2D = NULL;
+ qglTexParameterf = NULL;
+ qglTexParameterfv = NULL;
+ qglTexParameteri = NULL;
+ qglTexParameteriv = NULL;
+ qglTexSubImage1D = NULL;
+ qglTexSubImage2D = NULL;
+ qglTranslated = NULL;
+ qglTranslatef = NULL;
+ qglVertex2d = NULL;
+ qglVertex2dv = NULL;
+ qglVertex2f = NULL;
+ qglVertex2fv = NULL;
+ qglVertex2i = NULL;
+ qglVertex2iv = NULL;
+ qglVertex2s = NULL;
+ qglVertex2sv = NULL;
+ qglVertex3d = NULL;
+ qglVertex3dv = NULL;
+ qglVertex3f = NULL;
+ qglVertex3fv = NULL;
+ qglVertex3i = NULL;
+ qglVertex3iv = NULL;
+ qglVertex3s = NULL;
+ qglVertex3sv = NULL;
+ qglVertex4d = NULL;
+ qglVertex4dv = NULL;
+ qglVertex4f = NULL;
+ qglVertex4fv = NULL;
+ qglVertex4i = NULL;
+ qglVertex4iv = NULL;
+ qglVertex4s = NULL;
+ qglVertex4sv = NULL;
+ qglVertexPointer = NULL;
+ qglViewport = NULL;
+
+ qwglCopyContext = NULL;
+ qwglCreateContext = NULL;
+ qwglCreateLayerContext = NULL;
+ qwglDeleteContext = NULL;
+ qwglDescribeLayerPlane = NULL;
+ qwglGetCurrentContext = NULL;
+ qwglGetCurrentDC = NULL;
+ qwglGetLayerPaletteEntries = NULL;
+ qwglGetProcAddress = NULL;
+ qwglMakeCurrent = NULL;
+ qwglRealizeLayerPalette = NULL;
+ qwglSetLayerPaletteEntries = NULL;
+ qwglShareLists = NULL;
+ qwglSwapLayerBuffers = NULL;
+ qwglUseFontBitmaps = NULL;
+ qwglUseFontOutlines = NULL;
+
+ qwglChoosePixelFormat = NULL;
+ qwglDescribePixelFormat = NULL;
+ qwglGetPixelFormat = NULL;
+ qwglSetPixelFormat = NULL;
+ qwglSwapBuffers = NULL;
+
+ qwglSwapIntervalEXT = NULL;
+
+ qwglGetDeviceGammaRampEXT = NULL;
+ qwglSetDeviceGammaRampEXT = NULL;
+}
+
+# define GPA(h, a ) GetProcAddress( h, a )
+
+/*
+** QGL_Init
+**
+** This is responsible for binding our qgl function pointers to
+** the appropriate GL stuff. In Windows this means doing a
+** LoadLibrary and a bunch of calls to GetProcAddress. On other
+** operating systems we need to do the right thing, whatever that
+** might be.
+**
+*/
+qboolean QGL_Init(const char *dllname )
+{
+
+ g_hGLDLL = ::LoadLibrary(dllname);
+
+ qglAccum = dllAccum = GPA(g_hGLDLL, "glAccum" );
+ qglAlphaFunc = dllAlphaFunc = GPA(g_hGLDLL, "glAlphaFunc" );
+ qglAreTexturesResident = dllAreTexturesResident = GPA(g_hGLDLL, "glAreTexturesResident" );
+ qglArrayElement = dllArrayElement = GPA(g_hGLDLL, "glArrayElement" );
+ qglBegin = dllBegin = GPA(g_hGLDLL, "glBegin" );
+ qglBindTexture = dllBindTexture = GPA(g_hGLDLL, "glBindTexture" );
+ qglBitmap = dllBitmap = GPA(g_hGLDLL, "glBitmap" );
+ qglBlendFunc = dllBlendFunc = GPA(g_hGLDLL, "glBlendFunc" );
+ qglCallList = dllCallList = GPA(g_hGLDLL, "glCallList" );
+ qglCallLists = dllCallLists = GPA(g_hGLDLL, "glCallLists" );
+ qglClear = dllClear = GPA(g_hGLDLL, "glClear" );
+ qglClearAccum = dllClearAccum = GPA(g_hGLDLL, "glClearAccum" );
+ qglClearColor = dllClearColor = GPA(g_hGLDLL, "glClearColor" );
+ qglClearDepth = dllClearDepth = GPA(g_hGLDLL, "glClearDepth" );
+ qglClearIndex = dllClearIndex = GPA(g_hGLDLL, "glClearIndex" );
+ qglClearStencil = dllClearStencil = GPA(g_hGLDLL, "glClearStencil" );
+ qglClipPlane = dllClipPlane = GPA(g_hGLDLL, "glClipPlane" );
+ qglColor3b = dllColor3b = GPA(g_hGLDLL, "glColor3b" );
+ qglColor3bv = dllColor3bv = GPA(g_hGLDLL, "glColor3bv" );
+ qglColor3d = dllColor3d = GPA(g_hGLDLL, "glColor3d" );
+ qglColor3dv = dllColor3dv = GPA(g_hGLDLL, "glColor3dv" );
+ qglColor3f = dllColor3f = GPA(g_hGLDLL, "glColor3f" );
+ qglColor3fv = dllColor3fv = GPA(g_hGLDLL, "glColor3fv" );
+ qglColor3i = dllColor3i = GPA(g_hGLDLL, "glColor3i" );
+ qglColor3iv = dllColor3iv = GPA(g_hGLDLL, "glColor3iv" );
+ qglColor3s = dllColor3s = GPA(g_hGLDLL, "glColor3s" );
+ qglColor3sv = dllColor3sv = GPA(g_hGLDLL, "glColor3sv" );
+ qglColor3ub = dllColor3ub = GPA(g_hGLDLL, "glColor3ub" );
+ qglColor3ubv = dllColor3ubv = GPA(g_hGLDLL, "glColor3ubv" );
+ qglColor3ui = dllColor3ui = GPA(g_hGLDLL, "glColor3ui" );
+ qglColor3uiv = dllColor3uiv = GPA(g_hGLDLL, "glColor3uiv" );
+ qglColor3us = dllColor3us = GPA(g_hGLDLL, "glColor3us" );
+ qglColor3usv = dllColor3usv = GPA(g_hGLDLL, "glColor3usv" );
+ qglColor4b = dllColor4b = GPA(g_hGLDLL, "glColor4b" );
+ qglColor4bv = dllColor4bv = GPA(g_hGLDLL, "glColor4bv" );
+ qglColor4d = dllColor4d = GPA(g_hGLDLL, "glColor4d" );
+ qglColor4dv = dllColor4dv = GPA(g_hGLDLL, "glColor4dv" );
+ qglColor4f = dllColor4f = GPA(g_hGLDLL, "glColor4f" );
+ qglColor4fv = dllColor4fv = GPA(g_hGLDLL, "glColor4fv" );
+ qglColor4i = dllColor4i = GPA(g_hGLDLL, "glColor4i" );
+ qglColor4iv = dllColor4iv = GPA(g_hGLDLL, "glColor4iv" );
+ qglColor4s = dllColor4s = GPA(g_hGLDLL, "glColor4s" );
+ qglColor4sv = dllColor4sv = GPA(g_hGLDLL, "glColor4sv" );
+ qglColor4ub = dllColor4ub = GPA(g_hGLDLL, "glColor4ub" );
+ qglColor4ubv = dllColor4ubv = GPA(g_hGLDLL, "glColor4ubv" );
+ qglColor4ui = dllColor4ui = GPA(g_hGLDLL, "glColor4ui" );
+ qglColor4uiv = dllColor4uiv = GPA(g_hGLDLL, "glColor4uiv" );
+ qglColor4us = dllColor4us = GPA(g_hGLDLL, "glColor4us" );
+ qglColor4usv = dllColor4usv = GPA(g_hGLDLL, "glColor4usv" );
+ qglColorMask = dllColorMask = GPA(g_hGLDLL, "glColorMask" );
+ qglColorMaterial = dllColorMaterial = GPA(g_hGLDLL, "glColorMaterial" );
+ qglColorPointer = dllColorPointer = GPA(g_hGLDLL, "glColorPointer" );
+ qglCopyPixels = dllCopyPixels = GPA(g_hGLDLL, "glCopyPixels" );
+ qglCopyTexImage1D = dllCopyTexImage1D = GPA(g_hGLDLL, "glCopyTexImage1D" );
+ qglCopyTexImage2D = dllCopyTexImage2D = GPA(g_hGLDLL, "glCopyTexImage2D" );
+ qglCopyTexSubImage1D = dllCopyTexSubImage1D = GPA(g_hGLDLL, "glCopyTexSubImage1D" );
+ qglCopyTexSubImage2D = dllCopyTexSubImage2D = GPA(g_hGLDLL, "glCopyTexSubImage2D" );
+ qglCullFace = dllCullFace = GPA(g_hGLDLL, "glCullFace" );
+ qglDeleteLists = dllDeleteLists = GPA(g_hGLDLL, "glDeleteLists" );
+ qglDeleteTextures = dllDeleteTextures = GPA(g_hGLDLL, "glDeleteTextures" );
+ qglDepthFunc = dllDepthFunc = GPA(g_hGLDLL, "glDepthFunc" );
+ qglDepthMask = dllDepthMask = GPA(g_hGLDLL, "glDepthMask" );
+ qglDepthRange = dllDepthRange = GPA(g_hGLDLL, "glDepthRange" );
+ qglDisable = dllDisable = GPA(g_hGLDLL, "glDisable" );
+ qglDisableClientState = dllDisableClientState = GPA(g_hGLDLL, "glDisableClientState" );
+ qglDrawArrays = dllDrawArrays = GPA(g_hGLDLL, "glDrawArrays" );
+ qglDrawBuffer = dllDrawBuffer = GPA(g_hGLDLL, "glDrawBuffer" );
+ qglDrawElements = dllDrawElements = GPA(g_hGLDLL, "glDrawElements" );
+ qglDrawPixels = dllDrawPixels = GPA(g_hGLDLL, "glDrawPixels" );
+ qglEdgeFlag = dllEdgeFlag = GPA(g_hGLDLL, "glEdgeFlag" );
+ qglEdgeFlagPointer = dllEdgeFlagPointer = GPA(g_hGLDLL, "glEdgeFlagPointer" );
+ qglEdgeFlagv = dllEdgeFlagv = GPA(g_hGLDLL, "glEdgeFlagv" );
+ qglEnable = dllEnable = GPA(g_hGLDLL, "glEnable" );
+ qglEnableClientState = dllEnableClientState = GPA(g_hGLDLL, "glEnableClientState" );
+ qglEnd = dllEnd = GPA(g_hGLDLL, "glEnd" );
+ qglEndList = dllEndList = GPA(g_hGLDLL, "glEndList" );
+ qglEvalCoord1d = dllEvalCoord1d = GPA(g_hGLDLL, "glEvalCoord1d" );
+ qglEvalCoord1dv = dllEvalCoord1dv = GPA(g_hGLDLL, "glEvalCoord1dv" );
+ qglEvalCoord1f = dllEvalCoord1f = GPA(g_hGLDLL, "glEvalCoord1f" );
+ qglEvalCoord1fv = dllEvalCoord1fv = GPA(g_hGLDLL, "glEvalCoord1fv" );
+ qglEvalCoord2d = dllEvalCoord2d = GPA(g_hGLDLL, "glEvalCoord2d" );
+ qglEvalCoord2dv = dllEvalCoord2dv = GPA(g_hGLDLL, "glEvalCoord2dv" );
+ qglEvalCoord2f = dllEvalCoord2f = GPA(g_hGLDLL, "glEvalCoord2f" );
+ qglEvalCoord2fv = dllEvalCoord2fv = GPA(g_hGLDLL, "glEvalCoord2fv" );
+ qglEvalMesh1 = dllEvalMesh1 = GPA(g_hGLDLL, "glEvalMesh1" );
+ qglEvalMesh2 = dllEvalMesh2 = GPA(g_hGLDLL, "glEvalMesh2" );
+ qglEvalPoint1 = dllEvalPoint1 = GPA(g_hGLDLL, "glEvalPoint1" );
+ qglEvalPoint2 = dllEvalPoint2 = GPA(g_hGLDLL, "glEvalPoint2" );
+ qglFeedbackBuffer = dllFeedbackBuffer = GPA(g_hGLDLL, "glFeedbackBuffer" );
+ qglFinish = dllFinish = GPA(g_hGLDLL, "glFinish" );
+ qglFlush = dllFlush = GPA(g_hGLDLL, "glFlush" );
+ qglFogf = dllFogf = GPA(g_hGLDLL, "glFogf" );
+ qglFogfv = dllFogfv = GPA(g_hGLDLL, "glFogfv" );
+ qglFogi = dllFogi = GPA(g_hGLDLL, "glFogi" );
+ qglFogiv = dllFogiv = GPA(g_hGLDLL, "glFogiv" );
+ qglFrontFace = dllFrontFace = GPA(g_hGLDLL, "glFrontFace" );
+ qglFrustum = dllFrustum = GPA(g_hGLDLL, "glFrustum" );
+ qglGenLists = dllGenLists = GPA(g_hGLDLL, "glGenLists" );
+ qglGenTextures = dllGenTextures = GPA(g_hGLDLL, "glGenTextures" );
+ qglGetBooleanv = dllGetBooleanv = GPA(g_hGLDLL, "glGetBooleanv" );
+ qglGetClipPlane = dllGetClipPlane = GPA(g_hGLDLL, "glGetClipPlane" );
+ qglGetDoublev = dllGetDoublev = GPA(g_hGLDLL, "glGetDoublev" );
+ qglGetError = dllGetError = GPA(g_hGLDLL, "glGetError" );
+ qglGetFloatv = dllGetFloatv = GPA(g_hGLDLL, "glGetFloatv" );
+ qglGetIntegerv = dllGetIntegerv = GPA(g_hGLDLL, "glGetIntegerv" );
+ qglGetLightfv = dllGetLightfv = GPA(g_hGLDLL, "glGetLightfv" );
+ qglGetLightiv = dllGetLightiv = GPA(g_hGLDLL, "glGetLightiv" );
+ qglGetMapdv = dllGetMapdv = GPA(g_hGLDLL, "glGetMapdv" );
+ qglGetMapfv = dllGetMapfv = GPA(g_hGLDLL, "glGetMapfv" );
+ qglGetMapiv = dllGetMapiv = GPA(g_hGLDLL, "glGetMapiv" );
+ qglGetMaterialfv = dllGetMaterialfv = GPA(g_hGLDLL, "glGetMaterialfv" );
+ qglGetMaterialiv = dllGetMaterialiv = GPA(g_hGLDLL, "glGetMaterialiv" );
+ qglGetPixelMapfv = dllGetPixelMapfv = GPA(g_hGLDLL, "glGetPixelMapfv" );
+ qglGetPixelMapuiv = dllGetPixelMapuiv = GPA(g_hGLDLL, "glGetPixelMapuiv" );
+ qglGetPixelMapusv = dllGetPixelMapusv = GPA(g_hGLDLL, "glGetPixelMapusv" );
+ qglGetPointerv = dllGetPointerv = GPA(g_hGLDLL, "glGetPointerv" );
+ qglGetPolygonStipple = dllGetPolygonStipple = GPA(g_hGLDLL, "glGetPolygonStipple" );
+ qglGetString = dllGetString = GPA(g_hGLDLL, "glGetString" );
+ qglGetTexEnvfv = dllGetTexEnvfv = GPA(g_hGLDLL, "glGetTexEnvfv" );
+ qglGetTexEnviv = dllGetTexEnviv = GPA(g_hGLDLL, "glGetTexEnviv" );
+ qglGetTexGendv = dllGetTexGendv = GPA(g_hGLDLL, "glGetTexGendv" );
+ qglGetTexGenfv = dllGetTexGenfv = GPA(g_hGLDLL, "glGetTexGenfv" );
+ qglGetTexGeniv = dllGetTexGeniv = GPA(g_hGLDLL, "glGetTexGeniv" );
+ qglGetTexImage = dllGetTexImage = GPA(g_hGLDLL, "glGetTexImage" );
+ qglGetTexLevelParameterfv = dllGetTexLevelParameterfv = GPA(g_hGLDLL, "glGetLevelParameterfv" );
+ qglGetTexLevelParameteriv = dllGetTexLevelParameteriv = GPA(g_hGLDLL, "glGetLevelParameteriv" );
+ qglGetTexParameterfv = dllGetTexParameterfv = GPA(g_hGLDLL, "glGetTexParameterfv" );
+ qglGetTexParameteriv = dllGetTexParameteriv = GPA(g_hGLDLL, "glGetTexParameteriv" );
+ qglHint = dllHint = GPA(g_hGLDLL, "glHint" );
+ qglIndexMask = dllIndexMask = GPA(g_hGLDLL, "glIndexMask" );
+ qglIndexPointer = dllIndexPointer = GPA(g_hGLDLL, "glIndexPointer" );
+ qglIndexd = dllIndexd = GPA(g_hGLDLL, "glIndexd" );
+ qglIndexdv = dllIndexdv = GPA(g_hGLDLL, "glIndexdv" );
+ qglIndexf = dllIndexf = GPA(g_hGLDLL, "glIndexf" );
+ qglIndexfv = dllIndexfv = GPA(g_hGLDLL, "glIndexfv" );
+ qglIndexi = dllIndexi = GPA(g_hGLDLL, "glIndexi" );
+ qglIndexiv = dllIndexiv = GPA(g_hGLDLL, "glIndexiv" );
+ qglIndexs = dllIndexs = GPA(g_hGLDLL, "glIndexs" );
+ qglIndexsv = dllIndexsv = GPA(g_hGLDLL, "glIndexsv" );
+ qglIndexub = dllIndexub = GPA(g_hGLDLL, "glIndexub" );
+ qglIndexubv = dllIndexubv = GPA(g_hGLDLL, "glIndexubv" );
+ qglInitNames = dllInitNames = GPA(g_hGLDLL, "glInitNames" );
+ qglInterleavedArrays = dllInterleavedArrays = GPA(g_hGLDLL, "glInterleavedArrays" );
+ qglIsEnabled = dllIsEnabled = GPA(g_hGLDLL, "glIsEnabled" );
+ qglIsList = dllIsList = GPA(g_hGLDLL, "glIsList" );
+ qglIsTexture = dllIsTexture = GPA(g_hGLDLL, "glIsTexture" );
+ qglLightModelf = dllLightModelf = GPA(g_hGLDLL, "glLightModelf" );
+ qglLightModelfv = dllLightModelfv = GPA(g_hGLDLL, "glLightModelfv" );
+ qglLightModeli = dllLightModeli = GPA(g_hGLDLL, "glLightModeli" );
+ qglLightModeliv = dllLightModeliv = GPA(g_hGLDLL, "glLightModeliv" );
+ qglLightf = dllLightf = GPA(g_hGLDLL, "glLightf" );
+ qglLightfv = dllLightfv = GPA(g_hGLDLL, "glLightfv" );
+ qglLighti = dllLighti = GPA(g_hGLDLL, "glLighti" );
+ qglLightiv = dllLightiv = GPA(g_hGLDLL, "glLightiv" );
+ qglLineStipple = dllLineStipple = GPA(g_hGLDLL, "glLineStipple" );
+ qglLineWidth = dllLineWidth = GPA(g_hGLDLL, "glLineWidth" );
+ qglListBase = dllListBase = GPA(g_hGLDLL, "glListBase" );
+ qglLoadIdentity = dllLoadIdentity = GPA(g_hGLDLL, "glLoadIdentity" );
+ qglLoadMatrixd = dllLoadMatrixd = GPA(g_hGLDLL, "glLoadMatrixd" );
+ qglLoadMatrixf = dllLoadMatrixf = GPA(g_hGLDLL, "glLoadMatrixf" );
+ qglLoadName = dllLoadName = GPA(g_hGLDLL, "glLoadName" );
+ qglLogicOp = dllLogicOp = GPA(g_hGLDLL, "glLogicOp" );
+ qglMap1d = dllMap1d = GPA(g_hGLDLL, "glMap1d" );
+ qglMap1f = dllMap1f = GPA(g_hGLDLL, "glMap1f" );
+ qglMap2d = dllMap2d = GPA(g_hGLDLL, "glMap2d" );
+ qglMap2f = dllMap2f = GPA(g_hGLDLL, "glMap2f" );
+ qglMapGrid1d = dllMapGrid1d = GPA(g_hGLDLL, "glMapGrid1d" );
+ qglMapGrid1f = dllMapGrid1f = GPA(g_hGLDLL, "glMapGrid1f" );
+ qglMapGrid2d = dllMapGrid2d = GPA(g_hGLDLL, "glMapGrid2d" );
+ qglMapGrid2f = dllMapGrid2f = GPA(g_hGLDLL, "glMapGrid2f" );
+ qglMaterialf = dllMaterialf = GPA(g_hGLDLL, "glMaterialf" );
+ qglMaterialfv = dllMaterialfv = GPA(g_hGLDLL, "glMaterialfv" );
+ qglMateriali = dllMateriali = GPA(g_hGLDLL, "glMateriali" );
+ qglMaterialiv = dllMaterialiv = GPA(g_hGLDLL, "glMaterialiv" );
+ qglMatrixMode = dllMatrixMode = GPA(g_hGLDLL, "glMatrixMode" );
+ qglMultMatrixd = dllMultMatrixd = GPA(g_hGLDLL, "glMultMatrixd" );
+ qglMultMatrixf = dllMultMatrixf = GPA(g_hGLDLL, "glMultMatrixf" );
+ qglNewList = dllNewList = GPA(g_hGLDLL, "glNewList" );
+ qglNormal3b = dllNormal3b = GPA(g_hGLDLL, "glNormal3b" );
+ qglNormal3bv = dllNormal3bv = GPA(g_hGLDLL, "glNormal3bv" );
+ qglNormal3d = dllNormal3d = GPA(g_hGLDLL, "glNormal3d" );
+ qglNormal3dv = dllNormal3dv = GPA(g_hGLDLL, "glNormal3dv" );
+ qglNormal3f = dllNormal3f = GPA(g_hGLDLL, "glNormal3f" );
+ qglNormal3fv = dllNormal3fv = GPA(g_hGLDLL, "glNormal3fv" );
+ qglNormal3i = dllNormal3i = GPA(g_hGLDLL, "glNormal3i" );
+ qglNormal3iv = dllNormal3iv = GPA(g_hGLDLL, "glNormal3iv" );
+ qglNormal3s = dllNormal3s = GPA(g_hGLDLL, "glNormal3s" );
+ qglNormal3sv = dllNormal3sv = GPA(g_hGLDLL, "glNormal3sv" );
+ qglNormalPointer = dllNormalPointer = GPA(g_hGLDLL, "glNormalPointer" );
+ qglOrtho = dllOrtho = GPA(g_hGLDLL, "glOrtho" );
+ qglPassThrough = dllPassThrough = GPA(g_hGLDLL, "glPassThrough" );
+ qglPixelMapfv = dllPixelMapfv = GPA(g_hGLDLL, "glPixelMapfv" );
+ qglPixelMapuiv = dllPixelMapuiv = GPA(g_hGLDLL, "glPixelMapuiv" );
+ qglPixelMapusv = dllPixelMapusv = GPA(g_hGLDLL, "glPixelMapusv" );
+ qglPixelStoref = dllPixelStoref = GPA(g_hGLDLL, "glPixelStoref" );
+ qglPixelStorei = dllPixelStorei = GPA(g_hGLDLL, "glPixelStorei" );
+ qglPixelTransferf = dllPixelTransferf = GPA(g_hGLDLL, "glPixelTransferf" );
+ qglPixelTransferi = dllPixelTransferi = GPA(g_hGLDLL, "glPixelTransferi" );
+ qglPixelZoom = dllPixelZoom = GPA(g_hGLDLL, "glPixelZoom" );
+ qglPointSize = dllPointSize = GPA(g_hGLDLL, "glPointSize" );
+ qglPolygonMode = dllPolygonMode = GPA(g_hGLDLL, "glPolygonMode" );
+ qglPolygonOffset = dllPolygonOffset = GPA(g_hGLDLL, "glPolygonOffset" );
+ qglPolygonStipple = dllPolygonStipple = GPA(g_hGLDLL, "glPolygonStipple" );
+ qglPopAttrib = dllPopAttrib = GPA(g_hGLDLL, "glPopAttrib" );
+ qglPopClientAttrib = dllPopClientAttrib = GPA(g_hGLDLL, "glPopClientAttrib" );
+ qglPopMatrix = dllPopMatrix = GPA(g_hGLDLL, "glPopMatrix" );
+ qglPopName = dllPopName = GPA(g_hGLDLL, "glPopName" );
+ qglPrioritizeTextures = dllPrioritizeTextures = GPA(g_hGLDLL, "glPrioritizeTextures" );
+ qglPushAttrib = dllPushAttrib = GPA(g_hGLDLL, "glPushAttrib" );
+ qglPushClientAttrib = dllPushClientAttrib = GPA(g_hGLDLL, "glPushClientAttrib" );
+ qglPushMatrix = dllPushMatrix = GPA(g_hGLDLL, "glPushMatrix" );
+ qglPushName = dllPushName = GPA(g_hGLDLL, "glPushName" );
+ qglRasterPos2d = dllRasterPos2d = GPA(g_hGLDLL, "glRasterPos2d" );
+ qglRasterPos2dv = dllRasterPos2dv = GPA(g_hGLDLL, "glRasterPos2dv" );
+ qglRasterPos2f = dllRasterPos2f = GPA(g_hGLDLL, "glRasterPos2f" );
+ qglRasterPos2fv = dllRasterPos2fv = GPA(g_hGLDLL, "glRasterPos2fv" );
+ qglRasterPos2i = dllRasterPos2i = GPA(g_hGLDLL, "glRasterPos2i" );
+ qglRasterPos2iv = dllRasterPos2iv = GPA(g_hGLDLL, "glRasterPos2iv" );
+ qglRasterPos2s = dllRasterPos2s = GPA(g_hGLDLL, "glRasterPos2s" );
+ qglRasterPos2sv = dllRasterPos2sv = GPA(g_hGLDLL, "glRasterPos2sv" );
+ qglRasterPos3d = dllRasterPos3d = GPA(g_hGLDLL, "glRasterPos3d" );
+ qglRasterPos3dv = dllRasterPos3dv = GPA(g_hGLDLL, "glRasterPos3dv" );
+ qglRasterPos3f = dllRasterPos3f = GPA(g_hGLDLL, "glRasterPos3f" );
+ qglRasterPos3fv = dllRasterPos3fv = GPA(g_hGLDLL, "glRasterPos3fv" );
+ qglRasterPos3i = dllRasterPos3i = GPA(g_hGLDLL, "glRasterPos3i" );
+ qglRasterPos3iv = dllRasterPos3iv = GPA(g_hGLDLL, "glRasterPos3iv" );
+ qglRasterPos3s = dllRasterPos3s = GPA(g_hGLDLL, "glRasterPos3s" );
+ qglRasterPos3sv = dllRasterPos3sv = GPA(g_hGLDLL, "glRasterPos3sv" );
+ qglRasterPos4d = dllRasterPos4d = GPA(g_hGLDLL, "glRasterPos4d" );
+ qglRasterPos4dv = dllRasterPos4dv = GPA(g_hGLDLL, "glRasterPos4dv" );
+ qglRasterPos4f = dllRasterPos4f = GPA(g_hGLDLL, "glRasterPos4f" );
+ qglRasterPos4fv = dllRasterPos4fv = GPA(g_hGLDLL, "glRasterPos4fv" );
+ qglRasterPos4i = dllRasterPos4i = GPA(g_hGLDLL, "glRasterPos4i" );
+ qglRasterPos4iv = dllRasterPos4iv = GPA(g_hGLDLL, "glRasterPos4iv" );
+ qglRasterPos4s = dllRasterPos4s = GPA(g_hGLDLL, "glRasterPos4s" );
+ qglRasterPos4sv = dllRasterPos4sv = GPA(g_hGLDLL, "glRasterPos4sv" );
+ qglReadBuffer = dllReadBuffer = GPA(g_hGLDLL, "glReadBuffer" );
+ qglReadPixels = dllReadPixels = GPA(g_hGLDLL, "glReadPixels" );
+ qglRectd = dllRectd = GPA(g_hGLDLL, "glRectd" );
+ qglRectdv = dllRectdv = GPA(g_hGLDLL, "glRectdv" );
+ qglRectf = dllRectf = GPA(g_hGLDLL, "glRectf" );
+ qglRectfv = dllRectfv = GPA(g_hGLDLL, "glRectfv" );
+ qglRecti = dllRecti = GPA(g_hGLDLL, "glRecti" );
+ qglRectiv = dllRectiv = GPA(g_hGLDLL, "glRectiv" );
+ qglRects = dllRects = GPA(g_hGLDLL, "glRects" );
+ qglRectsv = dllRectsv = GPA(g_hGLDLL, "glRectsv" );
+ qglRenderMode = dllRenderMode = GPA(g_hGLDLL, "glRenderMode" );
+ qglRotated = dllRotated = GPA(g_hGLDLL, "glRotated" );
+ qglRotatef = dllRotatef = GPA(g_hGLDLL, "glRotatef" );
+ qglScaled = dllScaled = GPA(g_hGLDLL, "glScaled" );
+ qglScalef = dllScalef = GPA(g_hGLDLL, "glScalef" );
+ qglScissor = dllScissor = GPA(g_hGLDLL, "glScissor" );
+ qglSelectBuffer = dllSelectBuffer = GPA(g_hGLDLL, "glSelectBuffer" );
+ qglShadeModel = dllShadeModel = GPA(g_hGLDLL, "glShadeModel" );
+ qglStencilFunc = dllStencilFunc = GPA(g_hGLDLL, "glStencilFunc" );
+ qglStencilMask = dllStencilMask = GPA(g_hGLDLL, "glStencilMask" );
+ qglStencilOp = dllStencilOp = GPA(g_hGLDLL, "glStencilOp" );
+ qglTexCoord1d = dllTexCoord1d = GPA(g_hGLDLL, "glTexCoord1d" );
+ qglTexCoord1dv = dllTexCoord1dv = GPA(g_hGLDLL, "glTexCoord1dv" );
+ qglTexCoord1f = dllTexCoord1f = GPA(g_hGLDLL, "glTexCoord1f" );
+ qglTexCoord1fv = dllTexCoord1fv = GPA(g_hGLDLL, "glTexCoord1fv" );
+ qglTexCoord1i = dllTexCoord1i = GPA(g_hGLDLL, "glTexCoord1i" );
+ qglTexCoord1iv = dllTexCoord1iv = GPA(g_hGLDLL, "glTexCoord1iv" );
+ qglTexCoord1s = dllTexCoord1s = GPA(g_hGLDLL, "glTexCoord1s" );
+ qglTexCoord1sv = dllTexCoord1sv = GPA(g_hGLDLL, "glTexCoord1sv" );
+ qglTexCoord2d = dllTexCoord2d = GPA(g_hGLDLL, "glTexCoord2d" );
+ qglTexCoord2dv = dllTexCoord2dv = GPA(g_hGLDLL, "glTexCoord2dv" );
+ qglTexCoord2f = dllTexCoord2f = GPA(g_hGLDLL, "glTexCoord2f" );
+ qglTexCoord2fv = dllTexCoord2fv = GPA(g_hGLDLL, "glTexCoord2fv" );
+ qglTexCoord2i = dllTexCoord2i = GPA(g_hGLDLL, "glTexCoord2i" );
+ qglTexCoord2iv = dllTexCoord2iv = GPA(g_hGLDLL, "glTexCoord2iv" );
+ qglTexCoord2s = dllTexCoord2s = GPA(g_hGLDLL, "glTexCoord2s" );
+ qglTexCoord2sv = dllTexCoord2sv = GPA(g_hGLDLL, "glTexCoord2sv" );
+ qglTexCoord3d = dllTexCoord3d = GPA(g_hGLDLL, "glTexCoord3d" );
+ qglTexCoord3dv = dllTexCoord3dv = GPA(g_hGLDLL, "glTexCoord3dv" );
+ qglTexCoord3f = dllTexCoord3f = GPA(g_hGLDLL, "glTexCoord3f" );
+ qglTexCoord3fv = dllTexCoord3fv = GPA(g_hGLDLL, "glTexCoord3fv" );
+ qglTexCoord3i = dllTexCoord3i = GPA(g_hGLDLL, "glTexCoord3i" );
+ qglTexCoord3iv = dllTexCoord3iv = GPA(g_hGLDLL, "glTexCoord3iv" );
+ qglTexCoord3s = dllTexCoord3s = GPA(g_hGLDLL, "glTexCoord3s" );
+ qglTexCoord3sv = dllTexCoord3sv = GPA(g_hGLDLL, "glTexCoord3sv" );
+ qglTexCoord4d = dllTexCoord4d = GPA(g_hGLDLL, "glTexCoord4d" );
+ qglTexCoord4dv = dllTexCoord4dv = GPA(g_hGLDLL, "glTexCoord4dv" );
+ qglTexCoord4f = dllTexCoord4f = GPA(g_hGLDLL, "glTexCoord4f" );
+ qglTexCoord4fv = dllTexCoord4fv = GPA(g_hGLDLL, "glTexCoord4fv" );
+ qglTexCoord4i = dllTexCoord4i = GPA(g_hGLDLL, "glTexCoord4i" );
+ qglTexCoord4iv = dllTexCoord4iv = GPA(g_hGLDLL, "glTexCoord4iv" );
+ qglTexCoord4s = dllTexCoord4s = GPA(g_hGLDLL, "glTexCoord4s" );
+ qglTexCoord4sv = dllTexCoord4sv = GPA(g_hGLDLL, "glTexCoord4sv" );
+ qglTexCoordPointer = dllTexCoordPointer = GPA(g_hGLDLL, "glTexCoordPointer" );
+ qglTexEnvf = dllTexEnvf = GPA(g_hGLDLL, "glTexEnvf" );
+ qglTexEnvfv = dllTexEnvfv = GPA(g_hGLDLL, "glTexEnvfv" );
+ qglTexEnvi = dllTexEnvi = GPA(g_hGLDLL, "glTexEnvi" );
+ qglTexEnviv = dllTexEnviv = GPA(g_hGLDLL, "glTexEnviv" );
+ qglTexGend = dllTexGend = GPA(g_hGLDLL, "glTexGend" );
+ qglTexGendv = dllTexGendv = GPA(g_hGLDLL, "glTexGendv" );
+ qglTexGenf = dllTexGenf = GPA(g_hGLDLL, "glTexGenf" );
+ qglTexGenfv = dllTexGenfv = GPA(g_hGLDLL, "glTexGenfv" );
+ qglTexGeni = dllTexGeni = GPA(g_hGLDLL, "glTexGeni" );
+ qglTexGeniv = dllTexGeniv = GPA(g_hGLDLL, "glTexGeniv" );
+ qglTexImage1D = dllTexImage1D = GPA(g_hGLDLL, "glTexImage1D" );
+ qglTexImage2D = dllTexImage2D = GPA(g_hGLDLL, "glTexImage2D" );
+ qglTexParameterf = dllTexParameterf = GPA(g_hGLDLL, "glTexParameterf" );
+ qglTexParameterfv = dllTexParameterfv = GPA(g_hGLDLL, "glTexParameterfv" );
+ qglTexParameteri = dllTexParameteri = GPA(g_hGLDLL, "glTexParameteri" );
+ qglTexParameteriv = dllTexParameteriv = GPA(g_hGLDLL, "glTexParameteriv" );
+ qglTexSubImage1D = dllTexSubImage1D = GPA(g_hGLDLL, "glTexSubImage1D" );
+ qglTexSubImage2D = dllTexSubImage2D = GPA(g_hGLDLL, "glTexSubImage2D" );
+ qglTranslated = dllTranslated = GPA(g_hGLDLL, "glTranslated" );
+ qglTranslatef = dllTranslatef = GPA(g_hGLDLL, "glTranslatef" );
+ qglVertex2d = dllVertex2d = GPA(g_hGLDLL, "glVertex2d" );
+ qglVertex2dv = dllVertex2dv = GPA(g_hGLDLL, "glVertex2dv" );
+ qglVertex2f = dllVertex2f = GPA(g_hGLDLL, "glVertex2f" );
+ qglVertex2fv = dllVertex2fv = GPA(g_hGLDLL, "glVertex2fv" );
+ qglVertex2i = dllVertex2i = GPA(g_hGLDLL, "glVertex2i" );
+ qglVertex2iv = dllVertex2iv = GPA(g_hGLDLL, "glVertex2iv" );
+ qglVertex2s = dllVertex2s = GPA(g_hGLDLL, "glVertex2s" );
+ qglVertex2sv = dllVertex2sv = GPA(g_hGLDLL, "glVertex2sv" );
+ qglVertex3d = dllVertex3d = GPA(g_hGLDLL, "glVertex3d" );
+ qglVertex3dv = dllVertex3dv = GPA(g_hGLDLL, "glVertex3dv" );
+ qglVertex3f = dllVertex3f = GPA(g_hGLDLL, "glVertex3f" );
+ qglVertex3fv = dllVertex3fv = GPA(g_hGLDLL, "glVertex3fv" );
+ qglVertex3i = dllVertex3i = GPA(g_hGLDLL, "glVertex3i" );
+ qglVertex3iv = dllVertex3iv = GPA(g_hGLDLL, "glVertex3iv" );
+ qglVertex3s = dllVertex3s = GPA(g_hGLDLL, "glVertex3s" );
+ qglVertex3sv = dllVertex3sv = GPA(g_hGLDLL, "glVertex3sv" );
+ qglVertex4d = dllVertex4d = GPA(g_hGLDLL, "glVertex4d" );
+ qglVertex4dv = dllVertex4dv = GPA(g_hGLDLL, "glVertex4dv" );
+ qglVertex4f = dllVertex4f = GPA(g_hGLDLL, "glVertex4f" );
+ qglVertex4fv = dllVertex4fv = GPA(g_hGLDLL, "glVertex4fv" );
+ qglVertex4i = dllVertex4i = GPA(g_hGLDLL, "glVertex4i" );
+ qglVertex4iv = dllVertex4iv = GPA(g_hGLDLL, "glVertex4iv" );
+ qglVertex4s = dllVertex4s = GPA(g_hGLDLL, "glVertex4s" );
+ qglVertex4sv = dllVertex4sv = GPA(g_hGLDLL, "glVertex4sv" );
+ qglVertexPointer = dllVertexPointer = GPA(g_hGLDLL, "glVertexPointer" );
+ qglViewport = dllViewport = GPA(g_hGLDLL, "glViewport" );
+
+ qwglCopyContext = GPA(g_hGLDLL, "wglCopyContext" );
+ qwglCreateContext = GPA(g_hGLDLL, "wglCreateContext" );
+ qwglCreateLayerContext = GPA(g_hGLDLL, "wglCreateLayerContext" );
+ qwglDeleteContext = GPA(g_hGLDLL, "wglDeleteContext" );
+ qwglDescribeLayerPlane = GPA(g_hGLDLL, "wglDescribeLayerPlane" );
+ qwglGetCurrentContext = GPA(g_hGLDLL, "wglGetCurrentContext" );
+ qwglGetCurrentDC = GPA(g_hGLDLL, "wglGetCurrentDC" );
+ qwglGetLayerPaletteEntries = GPA(g_hGLDLL, "wglGetLayerPaletteEntries" );
+ qwglGetProcAddress = GPA(g_hGLDLL, "wglGetProcAddress" );
+ qwglMakeCurrent = GPA(g_hGLDLL, "wglMakeCurrent" );
+ qwglRealizeLayerPalette = GPA(g_hGLDLL, "wglRealizeLayerPalette" );
+ qwglSetLayerPaletteEntries = GPA(g_hGLDLL, "wglSetLayerPaletteEntries" );
+ qwglShareLists = GPA(g_hGLDLL, "wglShareLists" );
+ qwglSwapLayerBuffers = GPA(g_hGLDLL, "wglSwapLayerBuffers" );
+ qwglUseFontBitmaps = GPA(g_hGLDLL, "wglUseFontBitmapsA" );
+ qwglUseFontOutlines = GPA(g_hGLDLL, "wglUseFontOutlinesA" );
+
+ qwglChoosePixelFormat = GPA(g_hGLDLL, "wglChoosePixelFormat" );
+ qwglDescribePixelFormat = GPA(g_hGLDLL, "wglDescribePixelFormat" );
+ qwglGetPixelFormat = GPA(g_hGLDLL, "wglGetPixelFormat" );
+ qwglSetPixelFormat = GPA(g_hGLDLL, "wglSetPixelFormat" );
+ qwglSwapBuffers = GPA(g_hGLDLL, "wglSwapBuffers" );
+
+ qwglSwapIntervalEXT = 0;
+ qglPointParameterfEXT = 0;
+ qglPointParameterfvEXT = 0;
+ qglColorTableEXT = 0;
+ qglSelectTextureSGIS = 0;
+ qglMTexCoord2fSGIS = 0;
+
+ return true;
+}
+
+#pragma warning (default : 4113 4133 4047 )
+
+
+
diff --git a/q3radiant/RADBSP.CPP b/q3radiant/RADBSP.CPP
new file mode 100755
index 0000000..fb7c3d3
--- /dev/null
+++ b/q3radiant/RADBSP.CPP
@@ -0,0 +1,77 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//-----------------------------------------------------------------------------
+// #includes follow...
+//-----------------------------------------------------------------------------
+//
+#include "StdAfx.h" // For: Precompiled Headers
+//
+//-----------------------------------------------------------------------------
+// #defines, consts, etc follow...
+//-----------------------------------------------------------------------------
+//
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+//
+//-----------------------------------------------------------------------------
+// Implementation follows...
+//-----------------------------------------------------------------------------
+//
+
+// msvc 5.xx does not do well optimizing this code
+#pragma optimize("",off)
+
+HINSTANCE g_hQBSPDLL = NULL;
+
+typedef void (WINAPI* PFN_QBSP)(char*, HWND, const char*);
+
+void RunTools(char* pCommandLine, HWND hwnd, const char* pPAKFile)
+{
+ static PFN_QBSP lpfnQBSP = NULL;
+ if (g_hQBSPDLL == NULL)
+ g_hQBSPDLL = ::LoadLibrary("qbspdll.dll");
+ else
+ {
+ ::FreeLibrary(g_hQBSPDLL);
+ g_hQBSPDLL = ::LoadLibrary("qbspdll.dll");
+ lpfnQBSP = NULL;
+ }
+ if (g_hQBSPDLL != NULL)
+ {
+ if (lpfnQBSP == NULL && g_hQBSPDLL != NULL)
+ {
+ FARPROC pFunction = ::GetProcAddress(g_hQBSPDLL, "FullProcess");
+ lpfnQBSP = reinterpret_cast<PFN_QBSP>(pFunction);
+ }
+ if (lpfnQBSP != NULL)
+ {
+ (*lpfnQBSP)(pCommandLine, hwnd, pPAKFile);
+ }
+ }
+}
+
+
+#pragma optimize("",on)
+
diff --git a/q3radiant/RADEditView.cpp b/q3radiant/RADEditView.cpp
new file mode 100755
index 0000000..789bf0f
--- /dev/null
+++ b/q3radiant/RADEditView.cpp
@@ -0,0 +1,84 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// RADEditView.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "RADEditView.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CRADEditView
+
+IMPLEMENT_DYNCREATE(CRADEditView, CEditView)
+
+CRADEditView::CRADEditView()
+{
+}
+
+CRADEditView::~CRADEditView()
+{
+}
+
+
+BEGIN_MESSAGE_MAP(CRADEditView, CEditView)
+ //{{AFX_MSG_MAP(CRADEditView)
+ ON_CONTROL_REFLECT(EN_CHANGE, OnChange)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CRADEditView drawing
+
+void CRADEditView::OnDraw(CDC* pDC)
+{
+ CDocument* pDoc = GetDocument();
+ // TODO: add draw code here
+}
+
+/////////////////////////////////////////////////////////////////////////////
+// CRADEditView diagnostics
+
+#ifdef _DEBUG
+void CRADEditView::AssertValid() const
+{
+ CEditView::AssertValid();
+}
+
+void CRADEditView::Dump(CDumpContext& dc) const
+{
+ CEditView::Dump(dc);
+}
+#endif //_DEBUG
+
+/////////////////////////////////////////////////////////////////////////////
+// CRADEditView message handlers
+
+void CRADEditView::OnChange()
+{
+}
diff --git a/q3radiant/RADEditView.h b/q3radiant/RADEditView.h
new file mode 100755
index 0000000..53255a5
--- /dev/null
+++ b/q3radiant/RADEditView.h
@@ -0,0 +1,75 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_RADEDITVIEW_H__DC829123_812D_11D1_B548_00AA00A410FC__INCLUDED_)
+#define AFX_RADEDITVIEW_H__DC829123_812D_11D1_B548_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// RADEditView.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CRADEditView view
+
+class CRADEditView : public CEditView
+{
+public:
+ CRADEditView(); // protected constructor used by dynamic creation
+ DECLARE_DYNCREATE(CRADEditView)
+protected:
+
+// Attributes
+public:
+
+// Operations
+public:
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CRADEditView)
+ protected:
+ virtual void OnDraw(CDC* pDC); // overridden to draw this view
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+ virtual ~CRADEditView();
+#ifdef _DEBUG
+ virtual void AssertValid() const;
+ virtual void Dump(CDumpContext& dc) const;
+#endif
+
+ // Generated message map functions
+protected:
+ //{{AFX_MSG(CRADEditView)
+ afx_msg void OnChange();
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+/////////////////////////////////////////////////////////////////////////////
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_RADEDITVIEW_H__DC829123_812D_11D1_B548_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/RADEditWnd.cpp b/q3radiant/RADEditWnd.cpp
new file mode 100755
index 0000000..0e8ab1a
--- /dev/null
+++ b/q3radiant/RADEditWnd.cpp
@@ -0,0 +1,75 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// RADEditWnd.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "RADEditWnd.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CRADEditWnd
+
+CRADEditWnd::CRADEditWnd()
+{
+}
+
+CRADEditWnd::~CRADEditWnd()
+{
+}
+
+
+BEGIN_MESSAGE_MAP(CRADEditWnd, CWnd)
+ //{{AFX_MSG_MAP(CRADEditWnd)
+ ON_WM_CREATE()
+ ON_WM_SIZE()
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+
+/////////////////////////////////////////////////////////////////////////////
+// CRADEditWnd message handlers
+
+int CRADEditWnd::OnCreate(LPCREATESTRUCT lpCreateStruct)
+{
+ if (CWnd::OnCreate(lpCreateStruct) == -1)
+ return -1;
+
+ CRect rctClient;
+ GetClientRect(rctClient);
+ m_wndEdit.Create(WS_CHILD | WS_VSCROLL | ES_AUTOHSCROLL | ES_MULTILINE | WS_VISIBLE, rctClient, this, 101);
+ return 0;
+}
+
+void CRADEditWnd::OnSize(UINT nType, int cx, int cy)
+{
+ CWnd::OnSize(nType, cx, cy);
+ CRect rctClient;
+ GetClientRect(rctClient);
+ m_wndEdit.SetWindowPos(NULL, rctClient.left, rctClient.top, rctClient.Width(), rctClient.Height(), SWP_SHOWWINDOW);
+}
diff --git a/q3radiant/RADEditWnd.h b/q3radiant/RADEditWnd.h
new file mode 100755
index 0000000..663c552
--- /dev/null
+++ b/q3radiant/RADEditWnd.h
@@ -0,0 +1,73 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_RADEDITWND_H__DC829124_812D_11D1_B548_00AA00A410FC__INCLUDED_)
+#define AFX_RADEDITWND_H__DC829124_812D_11D1_B548_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// RADEditWnd.h : header file
+//
+
+#include "EditWnd.h"
+/////////////////////////////////////////////////////////////////////////////
+// CRADEditWnd window
+
+class CRADEditWnd : public CWnd
+{
+// Construction
+public:
+ CRADEditWnd();
+
+// Attributes
+public:
+ CEdit* GetEditWnd() {return dynamic_cast<CEdit*>(&m_wndEdit); };
+protected:
+ CEditWnd m_wndEdit;
+// Operations
+public:
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CRADEditWnd)
+ //}}AFX_VIRTUAL
+
+// Implementation
+public:
+ virtual ~CRADEditWnd();
+
+
+ // Generated message map functions
+protected:
+ //{{AFX_MSG(CRADEditWnd)
+ afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
+ afx_msg void OnSize(UINT nType, int cx, int cy);
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+/////////////////////////////////////////////////////////////////////////////
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_RADEDITWND_H__DC829124_812D_11D1_B548_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/RADKEYS.INI b/q3radiant/RADKEYS.INI
new file mode 100755
index 0000000..f5506ec
--- /dev/null
+++ b/q3radiant/RADKEYS.INI
@@ -0,0 +1,67 @@
+; command mapping for QERadiant
+;
+; syntax is as follows
+; Command name = keystroke
+;
+; use +alt, shift or ctrl to modify the keys (you can combine them)
+; i.e.
+; EntityColor = k+ctrl
+;
+; the special keys are as follows
+;
+; UP = Cursor up
+; DOWN = Cursor down
+; LEFT = Cursor left
+; RIGHT = Cursor right
+; SPACE = space
+; BACKSPACE = back space
+; ESCAPE = escape
+; END = end
+; INSERT = insert
+; DELETE = delete
+; PAGEUP = page up
+; PAGEDOWN = page down
+; TAB = tab
+; RETURN = return (enter)
+; F1..F2 = f1 .. f12
+
+
+[Commands]
+EntityColor = K
+CameraForward = UP
+CameraBack = DOWN
+CameraLeft = LEFT
+CameraRight = RIGHT
+CameraUp = D
+CameraDown = C
+CameraAngleUp = A
+CameraAngleDown = Z
+CameraStrafeRight = ,
+CameraStrafeLeft = .
+ToggleGrid = 0
+SetGrid1 = 1
+SetGrid2 = 2
+SetGrid4 = 3
+SetGrid8 = 4
+SetGrid16 = 5
+SetGrid32 = 6
+SetGrid64 = 7
+DragEdges = E
+DragVertices = V
+ViewEntityInfo = N
+ViewConsole = O
+ViewTextures = T
+SurfaceInspector = S
+CloneSelection = SPACE
+DeleteSelection = BACKSPACE
+UnSelectSelection = ESCAPE
+CenterView = END
+ZoomOut = INSERT
+ZoomIn = DELETE
+UpFloor = PAGEUP
+DownFloor = PAGEDOWN
+ToggleClipper = X
+ToggleRealtime = R
+EntityList = L
+MapInfo = M
+
diff --git a/q3radiant/Radiant.clw b/q3radiant/Radiant.clw
new file mode 100755
index 0000000..bba578e
--- /dev/null
+++ b/q3radiant/Radiant.clw
@@ -0,0 +1,1957 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+; CLW file contains information for the MFC ClassWizard
+
+[General Info]
+Version=1
+LastClass=CRadiantApp
+LastTemplate=CDialog
+NewFileInclude1=#include "stdafx.h"
+NewFileInclude2=#include "Radiant.h"
+LastPage=0
+
+ClassCount=40
+Class1=CRadiantApp
+Class2=CRadiantDoc
+Class3=CRadiantView
+Class4=CMainFrame
+Class7=CZWnd
+Class8=CCamWnd
+
+ResourceCount=56
+Resource1=IDR_MENU_DROP
+Resource2=IDD_DLG_SCRIPTS
+Resource3=IDD_ENTITY
+Resource8=IDD_DLG_ENTITYLIST
+Resource9=IDR_MENU1
+Resource10=IDD_GROUPBAR
+Resource11=IDD_PLAYWAVE
+Resource12=IDD_GAMMA
+Resource13=IDD_DLG_GROUP
+Resource4=IDD_DIALOG_NEWPATCH
+Resource5=IDR_POPUP_VIEW
+Resource6=IDR_POPUP_GROUP
+Resource7=IDD_DLG_INFORMATION
+Class9=CXYWnd
+Class10=CTexWnd
+Class11=CEditWnd
+Class5=CAboutDlg
+Class6=CChildFrame
+Resource14=IDR_MINIACCEL
+Class12=CLstToolBar
+Resource15=IDR_MENU11
+Resource16=IDR_TOOLBAR_ADVANCED
+Class13=CRotateDlg
+Class14=CPrefsDlg
+Class15=CRADEditView
+Class16=CRADEditWnd
+Resource17=IDD_TEXTUREBAR
+Resource18=IDD_SURFACE
+Class17=CMapInfo
+Resource19=IDD_DIALOG_CAP
+Class18=CEntityListDlg
+Resource20=IDR_RADIANTYPE
+Class19=CScriptDlg
+Resource21=IDR_POPUP_TEXTURE
+Class20=CNewProjDlg
+Resource22=IDR_TOOLBAR_SCALELOCK
+Class21=CCommandsDlg
+Resource23=IDD_DIALOG2
+Resource24=IDR_MAINFRAME
+Resource25=IDR_POPUP_SELECTION
+Class22=CScaleDialog
+Class23=CTexEdit
+Class24=CSurfaceDlg
+Class25=CFindTextureDlg
+Resource26=IDD_DIALOG_PATCH
+Resource27=IDD_TEXLIST
+Class26=CBSInput
+Resource28=IDD_DIALOG_SCALE
+Class27=CDialogInfo
+Resource29=IDD_FINDTEXTURE
+Resource30=IDR_ACCEL_SURFACE
+Resource31=IDD_DIALOG_TEXTURELIST
+Resource32="IDD_ADDCMD"
+Resource33="IDD_PROJECT"
+Resource34=IDD_NEWNAME
+Resource35=IDD_DIALOG_THICKEN
+Class28=CTextureBar
+Resource36=IDD_ABOUT
+Resource37=IDD_DIALOG_TEXTURELAYOUT
+Resource38=IDR_TOOLBAR1
+Resource39=IDR_SHADERFRAME
+Class29=CDialogTextures
+Resource40=IDD_FINDBRUSH
+Class30=CPatchDensityDlg
+Resource41=IDD_DIALOG_INPUT
+Class31=CTextureLayout
+Resource42=IDD_PROJECT
+Class32=CCapDialog
+Resource43=IDD_DLG_COMMANDLIST
+Class33=CDialogThick
+Resource44=IDD_DLG_NEWPROJECT
+Class34=CShaderEdit
+Class35=CShaderFrame
+Resource45=IDD_DLG_MAPINFO
+Resource46="IDR_SHADERFRAME"
+Resource47="IDR_SHADERTYPE"
+Resource48=IDR_POPUP_ENTITY
+Class36=CPatchDialog
+Class37=CWaveOpen
+Resource49=IDD_DLG_PREFS
+Resource50=IDD_DIALOG_STAIRS
+Resource51=IDD_ROTATE
+Resource52=IDD_ADDCMD
+Class38=CGroupBar
+Resource53=IDR_ACCELERATOR1
+Class39=CGroupDlg
+Resource54=IDD_SIDES
+Resource55=IDD_DIALOG_FINDREPLACE
+Class40=CNameDlg
+Resource56=IDR_MENU_QUAKE3
+
+[CLS:CRadiantApp]
+Type=0
+HeaderFile=Radiant.h
+ImplementationFile=Radiant.cpp
+Filter=N
+LastObject=ID_HELP
+BaseClass=CWinApp
+VirtualFilter=AC
+
+[CLS:CRadiantDoc]
+Type=0
+HeaderFile=RadiantDoc.h
+ImplementationFile=RadiantDoc.cpp
+Filter=N
+LastObject=CRadiantDoc
+
+[CLS:CRadiantView]
+Type=0
+HeaderFile=RadiantView.h
+ImplementationFile=RadiantView.cpp
+Filter=C
+
+[CLS:CMainFrame]
+Type=0
+HeaderFile=MainFrm.h
+ImplementationFile=MainFrm.cpp
+Filter=W
+BaseClass=CFrameWnd
+VirtualFilter=fWC
+LastObject=CMainFrame
+
+
+[CLS:CChildFrame]
+Type=0
+HeaderFile=ChildFrm.h
+ImplementationFile=ChildFrm.cpp
+Filter=M
+
+[CLS:CAboutDlg]
+Type=0
+HeaderFile=Radiant.cpp
+ImplementationFile=Radiant.cpp
+Filter=D
+
+[MNU:IDR_MAINFRAME]
+Type=1
+Class=CMainFrame
+Command1=ID_FILE_NEW
+Command2=ID_FILE_OPEN
+Command3=ID_FILE_PRINT_SETUP
+Command4=ID_FILE_MRU_FILE1
+Command5=ID_APP_EXIT
+Command6=ID_VIEW_TOOLBAR
+Command7=ID_VIEW_STATUS_BAR
+Command8=ID_APP_ABOUT
+CommandCount=8
+
+[TB:IDR_MAINFRAME]
+Type=1
+Class=CMainFrame
+Command1=ID_FILE_NEW
+Command2=ID_FILE_OPEN
+Command3=ID_FILE_SAVE
+Command4=ID_EDIT_CUT
+Command5=ID_EDIT_COPY
+Command6=ID_EDIT_PASTE
+Command7=ID_FILE_PRINT
+Command8=ID_APP_ABOUT
+CommandCount=8
+
+[MNU:IDR_RADIANTYPE]
+Type=1
+Class=CRadiantView
+Command1=ID_FILE_NEW
+Command2=ID_FILE_OPEN
+Command3=ID_FILE_CLOSE
+Command4=ID_FILE_SAVE
+Command5=ID_FILE_SAVE_AS
+Command6=ID_FILE_PRINT
+Command7=ID_FILE_PRINT_PREVIEW
+Command8=ID_FILE_PRINT_SETUP
+Command9=ID_FILE_MRU_FILE1
+Command10=ID_APP_EXIT
+Command11=ID_EDIT_UNDO
+Command12=ID_EDIT_CUT
+Command13=ID_EDIT_COPY
+Command14=ID_EDIT_PASTE
+Command15=ID_VIEW_TOOLBAR
+Command16=ID_VIEW_STATUS_BAR
+Command17=ID_WINDOW_NEW
+Command18=ID_WINDOW_CASCADE
+Command19=ID_WINDOW_TILE_HORZ
+Command20=ID_WINDOW_ARRANGE
+Command21=ID_APP_ABOUT
+CommandCount=21
+
+[TB:IDR_TOOLBAR1]
+Type=1
+Class=?
+Command1=ID_FILE_OPEN
+Command2=ID_FILE_SAVE
+Command3=ID_BRUSH_FLIPX
+Command4=ID_BRUSH_ROTATEX
+Command5=ID_BRUSH_FLIPY
+Command6=ID_BRUSH_ROTATEY
+Command7=ID_BRUSH_FLIPZ
+Command8=ID_BRUSH_ROTATEZ
+Command9=ID_POPUP_SELECTION
+Command10=ID_SELECTION_CSGSUBTRACT
+Command11=ID_SELECTION_MAKEHOLLOW
+Command12=ID_VIEW_CHANGE
+Command13=ID_TEXTURES_POPUP
+Command14=ID_VIEW_CAMERATOGGLE
+Command15=ID_VIEW_CAMERAUPDATE
+Command16=ID_VIEW_CUBICCLIPPING
+Command17=ID_VIEW_ENTITY
+Command18=ID_VIEW_CLIPPER
+Command19=ID_SELECT_MOUSEROTATE
+Command20=ID_SELECT_MOUSESCALE
+Command21=ID_SCALELOCKX
+Command22=ID_SCALELOCKY
+Command23=ID_SCALELOCKZ
+CommandCount=23
+
+[DLG:IDD_FINDTEXTURE]
+Type=1
+Class=?
+ControlCount=3
+Control1=IDOK,button,1342242817
+Control2=IDCANCEL,button,1342242816
+Control3=IDC_EDIT1,edit,1350631552
+
+[DLG:IDD_ENTITY]
+Type=1
+Class=?
+ControlCount=35
+Control1=IDC_E_LIST,listbox,1352729859
+Control2=IDC_E_COMMENT,edit,1352730628
+Control3=IDC_E_135,button,1342242816
+Control4=IDC_E_180,button,1342242816
+Control5=IDC_E_225,button,1342242816
+Control6=IDC_E_270,button,1342242816
+Control7=IDC_E_90,button,1342242816
+Control8=IDC_E_45,button,1342242816
+Control9=IDC_E_0,button,1342242816
+Control10=IDC_E_315,button,1342242816
+Control11=IDC_E_UP,button,1342242816
+Control12=IDC_E_DOWN,button,1342242816
+Control13=IDC_CHECK1,button,1476460547
+Control14=IDC_CHECK2,button,1476460547
+Control15=IDC_CHECK3,button,1476460547
+Control16=IDC_CHECK4,button,1476460547
+Control17=IDC_CHECK5,button,1476460547
+Control18=IDC_CHECK6,button,1476460547
+Control19=IDC_CHECK7,button,1476460547
+Control20=IDC_CHECK8,button,1476460547
+Control21=IDC_CHECK9,button,1342242819
+Control22=IDC_CHECK10,button,1342242819
+Control23=IDC_CHECK11,button,1342242819
+Control24=IDC_CHECK12,button,1342242819
+Control25=IDC_E_PROPS,listbox,1352729987
+Control26=IDC_E_DELPROP,button,1342242816
+Control27=IDC_E_STATUS,edit,1353779396
+Control28=IDC_STATIC_KEY,static,1342308352
+Control29=IDC_STATIC_VALUE,static,1342308352
+Control30=IDC_E_KEY_FIELD,edit,1350631552
+Control31=IDC_E_VALUE_FIELD,edit,1350631552
+Control32=IDC_BTN_HIDE,button,1342242816
+Control33=IDC_BTN_ASSIGNSOUND,button,1342242816
+Control34=IDC_BTN_ASSIGNMODEL,button,1342242816
+Control35=IDC_TAB_MODE,SysTabControl32,1350565890
+
+[DLG:IDD_GAMMA]
+Type=1
+Class=?
+ControlCount=4
+Control1=IDC_G_EDIT,edit,1350631552
+Control2=IDOK,button,1342242817
+Control3=IDCANCEL,button,1342242816
+Control4=IDC_STATIC,static,1342308352
+
+[DLG:IDD_FINDBRUSH]
+Type=1
+Class=?
+ControlCount=6
+Control1=IDOK,button,1342242817
+Control2=IDCANCEL,button,1342242816
+Control3=IDC_FIND_ENTITY,edit,1350631552
+Control4=IDC_FIND_BRUSH,edit,1350631552
+Control5=IDC_STATIC,static,1342308352
+Control6=IDC_STATIC,static,1342308352
+
+[DLG:IDD_ROTATE]
+Type=1
+Class=CRotateDlg
+ControlCount=12
+Control1=IDC_ROTX,edit,1350631552
+Control2=IDC_SPIN1,msctls_updown32,1342177335
+Control3=IDC_ROTY,edit,1350631552
+Control4=IDC_SPIN2,msctls_updown32,1342177335
+Control5=IDC_ROTZ,edit,1350631552
+Control6=IDC_SPIN3,msctls_updown32,1342177335
+Control7=IDOK,button,1342242817
+Control8=IDCANCEL,button,1342242816
+Control9=ID_APPLY,button,1342242816
+Control10=IDC_STATIC,static,1342308354
+Control11=IDC_STATIC,static,1342308354
+Control12=IDC_STATIC,static,1342308354
+
+[DLG:IDD_SIDES]
+Type=1
+Class=?
+ControlCount=4
+Control1=IDC_SIDES,edit,1350631552
+Control2=IDOK,button,1342242817
+Control3=IDCANCEL,button,1342242816
+Control4=IDC_STATIC,static,1342308352
+
+[DLG:IDD_ABOUT]
+Type=1
+Class=?
+ControlCount=9
+Control1=IDOK,button,1342242817
+Control2=IDC_STATIC,static,1350572558
+Control3=IDC_STATIC,button,1342177287
+Control4=IDC_ABOUT_GLVENDOR,static,1342308352
+Control5=IDC_ABOUT_GLVERSION,static,1342308352
+Control6=IDC_ABOUT_GLRENDERER,static,1342308352
+Control7=IDC_STATIC,button,1342177287
+Control8=IDC_STATIC,static,1342308364
+Control9=IDC_ABOUT_GLEXTENSIONS,edit,1476462660
+
+[DLG:IDD_SURFACE]
+Type=1
+Class=CSurfaceDlg
+ControlCount=103
+Control1=IDC_TEXTURE,edit,1350631552
+Control2=IDC_HSHIFT,edit,1350631552
+Control3=IDC_SPIN_HSHIFT,msctls_updown32,1342177332
+Control4=IDC_VSHIFT,edit,1350631552
+Control5=IDC_SPIN_VSHIFT,msctls_updown32,1342177332
+Control6=IDC_HSCALE,edit,1350631552
+Control7=IDC_SPIN_HSCALE,msctls_updown32,1342177332
+Control8=IDC_VSCALE,edit,1350631552
+Control9=IDC_SPIN_VSCALE,msctls_updown32,1342177332
+Control10=IDC_ROTATE,edit,1350631552
+Control11=IDC_SPIN_ROTATE,msctls_updown32,1342177332
+Control12=IDC_VALUE,edit,1350631552
+Control13=IDC_BTN_PATCHDETAILS,button,1342242816
+Control14=IDC_CHECK1,button,1342242819
+Control15=IDC_CHECK2,button,1342242819
+Control16=IDC_CHECK3,button,1342242819
+Control17=IDC_CHECK4,button,1342242819
+Control18=IDC_CHECK5,button,1342242819
+Control19=IDC_CHECK6,button,1342242819
+Control20=IDC_CHECK7,button,1342242819
+Control21=IDC_CHECK8,button,1342242819
+Control22=IDC_CHECK9,button,1342242819
+Control23=IDC_CHECK10,button,1342242819
+Control24=IDC_CHECK11,button,1342242819
+Control25=IDC_CHECK12,button,1342242819
+Control26=IDC_CHECK13,button,1342242819
+Control27=IDC_CHECK14,button,1342242819
+Control28=IDC_CHECK15,button,1342242819
+Control29=IDC_CHECK16,button,1342242819
+Control30=IDC_CHECK17,button,1342242819
+Control31=IDC_CHECK18,button,1342242819
+Control32=IDC_CHECK19,button,1342242819
+Control33=IDC_CHECK20,button,1342242819
+Control34=IDC_CHECK21,button,1342242819
+Control35=IDC_CHECK22,button,1342242819
+Control36=IDC_CHECK23,button,1342242819
+Control37=IDC_CHECK24,button,1342242819
+Control38=IDC_CHECK25,button,1342242819
+Control39=IDC_CHECK26,button,1342242819
+Control40=IDC_CHECK27,button,1342242819
+Control41=IDC_CHECK28,button,1342242819
+Control42=IDC_CHECK29,button,1342242819
+Control43=IDC_CHECK30,button,1342242819
+Control44=IDC_CHECK31,button,1342242819
+Control45=IDC_CHECK32,button,1342242819
+Control46=IDC_CHECK33,button,1342242819
+Control47=IDC_CHECK34,button,1342242819
+Control48=IDC_CHECK35,button,1342242819
+Control49=IDC_CHECK36,button,1342242819
+Control50=IDC_CHECK37,button,1342242819
+Control51=IDC_CHECK38,button,1342242819
+Control52=IDC_CHECK39,button,1342242819
+Control53=IDC_CHECK40,button,1342242819
+Control54=IDC_CHECK41,button,1342242819
+Control55=IDC_CHECK42,button,1342242819
+Control56=IDC_CHECK43,button,1342242819
+Control57=IDC_CHECK44,button,1342242819
+Control58=IDC_CHECK45,button,1342242819
+Control59=IDC_CHECK46,button,1342242819
+Control60=IDC_CHECK47,button,1342242819
+Control61=IDC_CHECK48,button,1342242819
+Control62=IDC_CHECK49,button,1342242819
+Control63=IDC_CHECK50,button,1342242819
+Control64=IDC_CHECK51,button,1342242819
+Control65=IDC_CHECK52,button,1342242819
+Control66=IDC_CHECK53,button,1342242819
+Control67=IDC_CHECK54,button,1342242819
+Control68=IDC_CHECK55,button,1342242819
+Control69=IDC_CHECK56,button,1342242819
+Control70=IDC_CHECK57,button,1342242819
+Control71=IDC_CHECK58,button,1342242819
+Control72=IDC_CHECK59,button,1342242819
+Control73=IDC_CHECK60,button,1342242819
+Control74=IDC_CHECK61,button,1342242819
+Control75=IDC_CHECK62,button,1342242819
+Control76=IDC_CHECK63,button,1342242819
+Control77=IDC_CHECK64,button,1342242819
+Control78=IDOK,button,1342242817
+Control79=IDAPPLY,button,1342242816
+Control80=ID_BTN_CANCEL,button,1342242816
+Control81=IDC_STATIC,static,1342308354
+Control82=IDC_STATIC,static,1342308354
+Control83=IDC_STATIC,static,1342308354
+Control84=IDC_STATIC,static,1342308354
+Control85=IDC_STATIC,static,1342308354
+Control86=IDC_STATIC,static,1342308352
+Control87=IDC_STATIC,button,1342177287
+Control88=IDC_STATIC,button,1342177287
+Control89=IDC_STATIC,static,1342308354
+Control90=IDC_STATIC,button,1342177287
+Control91=IDC_BTN_PATCHRESET,button,1342242816
+Control92=IDC_BTN_PATCHNATURAL,button,1342242816
+Control93=IDC_BTN_PATCHFIT,button,1342242816
+Control94=IDC_STATIC,static,1342308352
+Control95=IDC_STATIC,static,1342308352
+Control96=IDC_BTN_AXIAL,button,1342242816
+Control97=IDC_BTN_FACEFIT,button,1342242816
+Control98=IDC_EDIT_WIDTH,edit,1350639744
+Control99=IDC_SPIN_WIDTH,msctls_updown32,1342177335
+Control100=IDC_EDIT_HEIGHT,edit,1350639744
+Control101=IDC_SPIN_HEIGHT,msctls_updown32,1342177334
+Control102=IDC_STATIC,static,1342308352
+Control103=IDC_STATIC,static,1342308352
+
+[CLS:CZWnd]
+Type=0
+HeaderFile=ZWnd.h
+ImplementationFile=ZWnd.cpp
+BaseClass=CWnd
+Filter=W
+VirtualFilter=WC
+
+[CLS:CCamWnd]
+Type=0
+HeaderFile=CamWnd.h
+ImplementationFile=CamWnd.cpp
+BaseClass=CWnd
+Filter=W
+VirtualFilter=WC
+LastObject=CCamWnd
+
+[CLS:CXYWnd]
+Type=0
+HeaderFile=XYWnd.h
+ImplementationFile=XYWnd.cpp
+BaseClass=CWnd
+Filter=W
+VirtualFilter=WC
+LastObject=ID_SELECT_MOUSEROTATE
+
+[CLS:CTexWnd]
+Type=0
+HeaderFile=TexWnd.h
+ImplementationFile=TexWnd.cpp
+BaseClass=CWnd
+Filter=W
+VirtualFilter=WC
+LastObject=CTexWnd
+
+[CLS:CEditWnd]
+Type=0
+HeaderFile=EditWnd.h
+ImplementationFile=EditWnd.cpp
+BaseClass=CEdit
+Filter=W
+VirtualFilter=WC
+
+[CLS:CLstToolBar]
+Type=0
+HeaderFile=LstToolBar.h
+ImplementationFile=LstToolBar.cpp
+BaseClass=CToolBar
+Filter=W
+LastObject=CLstToolBar
+
+[MNU:IDR_POPUP_TEXTURE]
+Type=1
+Class=?
+Command1=ID_TEXTURES_WIREFRAME
+Command2=ID_TEXTURES_FLATSHADE
+Command3=ID_VIEW_NEAREST
+Command4=ID_VIEW_NEARESTMIPMAP
+Command5=ID_VIEW_LINEAR
+Command6=ID_VIEW_BILINEAR
+Command7=ID_VIEW_BILINEARMIPMAP
+Command8=ID_VIEW_TRILINEAR
+CommandCount=8
+
+[MNU:IDR_POPUP_SELECTION]
+Type=1
+Class=?
+Command1=ID_SELECTION_SELECTCOMPLETETALL
+Command2=ID_SELECTION_SELECTTOUCHING
+Command3=ID_SELECTION_SELECTPARTIALTALL
+Command4=ID_SELECTION_SELECTINSIDE
+CommandCount=4
+
+[MNU:IDR_POPUP_VIEW]
+Type=1
+Class=?
+Command1=ID_VIEW_XY
+Command2=ID_VIEW_SIDE
+Command3=ID_VIEW_FRONT
+CommandCount=3
+
+[CLS:CRotateDlg]
+Type=0
+HeaderFile=RotateDlg.h
+ImplementationFile=RotateDlg.cpp
+BaseClass=CDialog
+Filter=D
+VirtualFilter=dWC
+LastObject=CRotateDlg
+
+[DLG:IDD_DLG_PREFS]
+Type=1
+Class=CPrefsDlg
+ControlCount=81
+Control1=IDC_COMBO_WHATGAME,combobox,1344340226
+Control2=IDC_RADIO_MOUSE,button,1342308361
+Control3=IDC_RADIO2,button,1342177289
+Control4=IDC_RADIO_VIEWTYPE,button,1342308361
+Control5=IDC_RADIO_VIEWTYPE2,button,1342177289
+Control6=IDC_RADIO_VIEWTYPE3,button,1342177289
+Control7=IDC_RADIO_VIEWTYPE4,button,1342177289
+Control8=IDC_CHECK_SGIOPENGL,button,1342242819
+Control9=IDC_CHECK_BUGGYICD,button,1342242819
+Control10=IDC_CHECK_DISPLAYLISTS,button,1342242819
+Control11=IDC_CHECK_NOSTIPPLE,button,1342242819
+Control12=IDC_SLIDER_CAMSPEED,msctls_trackbar32,1342242816
+Control13=IDC_CHECK_CAMXYUPDATE,button,1342251011
+Control14=IDC_CHECK_QE4PAINTING,button,1342242819
+Control15=IDC_SLIDER_TEXTUREQUALITY,msctls_trackbar32,1342242817
+Control16=IDC_CHECK_TEXTURETOOLBAR,button,1342242819
+Control17=IDC_CHECK_TEXTURESCROLLBAR,button,1342242819
+Control18=IDC_CHECK_TEXTUREWINDOW,button,1342242819
+Control19=IDC_CHECK_RIGHTCLICK,button,1342242819
+Control20=IDC_CHECK_FACE,button,1342242819
+Control21=IDC_EDIT_ROTATION,edit,1350631552
+Control22=IDC_CHECK_ALTDRAG,button,1342242819
+Control23=IDC_CHECK_SNAPT,button,1342242819
+Control24=IDC_CHECK_MOUSECHASE,button,1342242819
+Control25=IDC_CHECK_WIDETOOLBAR,button,1342242819
+Control26=IDC_CHECK_LIGHTDRAW,button,1342242819
+Control27=IDC_CHECK_SIZEPAINT,button,1342242819
+Control28=IDC_CHECK_HICOLOR,button,1342242819
+Control29=IDC_STATIC,static,1342308352
+Control30=IDC_COMBO_SHADERS,combobox,1344339971
+Control31=IDC_EDIT_QUAKE2,edit,1350631552
+Control32=IDC_BTN_BROWSE,button,1342242816
+Control33=IDC_CHECK_INTERNALBSP,button,1342242819
+Control34=IDC_CHECK_NOCLAMP,button,1342242819
+Control35=IDC_CHECK_SNAPSHOTS,button,1342242819
+Control36=IDC_CHECK_SETGAME,button,1342242819
+Control37=IDC_CHECK_RUNQUAKE,button,1342242819
+Control38=IDC_CHECK_LOADLAST,button,1342242819
+Control39=IDC_CHECK_LOADLASTMAP,button,1342242819
+Control40=IDC_CHECK_AUTOSAVE,button,1342242819
+Control41=IDC_EDIT_AUTOSAVE,edit,1350639744
+Control42=IDC_SPIN_AUTOSAVE,msctls_updown32,1342177335
+Control43=IDC_STATIC,static,1342308352
+Control44=IDC_EDIT_STATUSPOINTSIZE,edit,1350631552
+Control45=IDC_SPIN_POINTSIZE,msctls_updown32,1342177335
+Control46=IDC_STATIC,static,1342308352
+Control47=IDC_EDIT_UNDOLEVELS,edit,1350631552
+Control48=IDC_SPIN_UNDO,msctls_updown32,1342177335
+Control49=IDC_CHECK_PAK,button,1342242819
+Control50=IDC_EDIT_PAKFILE,edit,1350631552
+Control51=IDC_BTN_BROWSEPAK,button,1342242816
+Control52=IDC_EDIT_PREFABPATH,edit,1350631552
+Control53=IDC_BTN_BROWSEPREFAB,button,1342242816
+Control54=IDC_EDIT_USERPATH,edit,1350631552
+Control55=IDC_BTN_BROWSEUSERINI,button,1342242816
+Control56=IDOK,button,1342242817
+Control57=IDCANCEL,button,1342242816
+Control58=IDC_CHECK_DLLENTITIES,button,1208034307
+Control59=IDC_CHECK_FACECOLOR,button,1208025091
+Control60=IDC_STATIC,static,1342308352
+Control61=IDC_CHECK_VERTEX,button,1208025091
+Control62=IDC_STATIC,button,1342177287
+Control63=IDC_STATIC,button,1342177287
+Control64=IDC_STATIC,button,1342177287
+Control65=IDB_VIEWDEFAULT,static,1342177294
+Control66=IDB_VIEWDEFAULT2,static,1342177294
+Control67=IDB_VIEWDEFAULT3,static,1342177294
+Control68=IDC_STATIC,button,1342177287
+Control69=IDB_VIEWDEFAULT_Z,static,1342177294
+Control70=IDC_STATIC,static,1342308352
+Control71=IDC_STATIC,static,1342308352
+Control72=IDC_STATIC,button,1342177287
+Control73=IDC_STATIC,static,1342308352
+Control74=IDC_STATIC,button,1342177287
+Control75=IDC_STATIC,static,1342308352
+Control76=IDC_STATIC,static,1342308352
+Control77=IDC_CHECK_USESHADERS,button,1208025091
+Control78=IDC_STATIC,button,1342177287
+Control79=IDC_STATIC,static,1342308352
+Control80=IDC_STATIC,static,1342308352
+Control81=IDC_STATIC,static,1342308352
+
+[CLS:CPrefsDlg]
+Type=0
+HeaderFile=PrefsDlg.h
+ImplementationFile=PrefsDlg.cpp
+BaseClass=CDialog
+Filter=D
+LastObject=IDC_SPIN_POINTSIZE
+VirtualFilter=dWC
+
+[CLS:CRADEditView]
+Type=0
+HeaderFile=RADEditView.h
+ImplementationFile=RADEditView.cpp
+BaseClass=CEditView
+Filter=C
+VirtualFilter=VWC
+
+[CLS:CRADEditWnd]
+Type=0
+HeaderFile=RADEditWnd.h
+ImplementationFile=RADEditWnd.cpp
+BaseClass=CWnd
+Filter=W
+VirtualFilter=WC
+
+[ACL:IDR_ACCELERATOR1]
+Type=1
+Class=?
+Command1=ID_BRUSH_3SIDED
+Command2=ID_BRUSH_4SIDED
+Command3=ID_BRUSH_5SIDED
+Command4=ID_BRUSH_6SIDED
+Command5=ID_BRUSH_7SIDED
+Command6=ID_BRUSH_8SIDED
+Command7=ID_BRUSH_9SIDED
+Command8=ID_VIEW_SHOWDETAIL
+Command9=ID_SELECTION_CONNECT
+Command10=ID_MISC_NEXTLEAKSPOT
+Command11=ID_SELECTION_MAKE_DETAIL
+Command12=ID_FILE_OPEN
+Command13=ID_MISC_PREVIOUSLEAKSPOT
+Command14=ID_FILE_SAVE
+Command15=ID_VIEW_ZZOOMIN
+Command16=ID_VIEW_ZZOOMOUT
+Command17=ID_FILE_EXIT
+CommandCount=17
+
+[DLG:IDD_DLG_MAPINFO]
+Type=1
+Class=CMapInfo
+ControlCount=9
+Control1=IDOK,button,1342242817
+Control2=IDC_STATIC,static,1342308352
+Control3=IDC_EDIT_TOTALBRUSHES,edit,1350639746
+Control4=IDC_STATIC,static,1342308352
+Control5=IDC_EDIT_TOTALENTITIES,edit,1350639746
+Control6=IDC_STATIC,static,1342308352
+Control7=IDC_EDIT_NET,edit,1350639746
+Control8=IDC_LIST_ENTITIES,listbox,1352728963
+Control9=IDC_STATIC,static,1342308352
+
+[CLS:CMapInfo]
+Type=0
+HeaderFile=MapInfo.h
+ImplementationFile=MapInfo.cpp
+BaseClass=CDialog
+Filter=D
+LastObject=ID_EDIT_MAPINFO
+VirtualFilter=dWC
+
+[ACL:IDR_MAINFRAME]
+Type=1
+Class=?
+Command1=ID_BRUSH_7SIDED
+Command2=ID_BRUSH_8SIDED
+Command3=ID_BRUSH_9SIDED
+Command4=ID_VIEW_SHOWDETAIL
+Command5=ID_SELECTION_CONNECT
+Command6=ID_MISC_NEXTLEAKSPOT
+Command7=ID_SELECTION_MAKE_DETAIL
+Command8=ID_FILE_OPEN
+Command9=ID_MISC_PREVIOUSLEAKSPOT
+Command10=ID_FILE_SAVE
+Command11=ID_VIEW_ZZOOMIN
+Command12=ID_SELECTION_SELECT_NUDGEDOWN
+Command13=ID_VIEW_ZZOOMOUT
+Command14=ID_FILE_EXIT
+CommandCount=14
+
+[DLG:IDD_DLG_ENTITYLIST]
+Type=1
+Class=CEntityListDlg
+ControlCount=4
+Control1=IDOK,button,1342242817
+Control2=IDC_TREE_ENTITY,SysTreeView32,1350631431
+Control3=IDSELECT,button,1342242817
+Control4=IDC_LIST_ENTITY,SysListView32,1350664709
+
+[CLS:CEntityListDlg]
+Type=0
+HeaderFile=EntityListDlg.h
+ImplementationFile=EntityListDlg.cpp
+BaseClass=CDialog
+Filter=D
+VirtualFilter=dWC
+LastObject=IDC_LIST_ENTITY
+
+[DLG:IDD_DLG_SCRIPTS]
+Type=1
+Class=CScriptDlg
+ControlCount=6
+Control1=ID_NEW,button,1476460545
+Control2=IDOK,button,1342242816
+Control3=IDC_LIST_SCRIPTS,listbox,1352728835
+Control4=ID_EDIT,button,1476460545
+Control5=ID_RUN,button,1342242817
+Control6=IDC_STATIC,static,1342308352
+
+[CLS:CScriptDlg]
+Type=0
+HeaderFile=ScriptDlg.h
+ImplementationFile=ScriptDlg.cpp
+BaseClass=CDialog
+Filter=D
+VirtualFilter=dWC
+LastObject=IDC_LIST_SCRIPTS
+
+[DLG:IDD_DLG_NEWPROJECT]
+Type=1
+Class=CNewProjDlg
+ControlCount=6
+Control1=IDC_EDIT_NAME,edit,1350631552
+Control2=IDOK,button,1342242817
+Control3=IDCANCEL,button,1342242816
+Control4=IDC_STATIC,static,1342308352
+Control5=IDC_STATIC,static,1342308352
+Control6=IDC_CHECK1,button,1476460547
+
+[CLS:CNewProjDlg]
+Type=0
+HeaderFile=NewProjDlg.h
+ImplementationFile=NewProjDlg.cpp
+BaseClass=CDialog
+Filter=D
+LastObject=CNewProjDlg
+VirtualFilter=dWC
+
+[DLG:IDD_DLG_COMMANDLIST]
+Type=1
+Class=CCommandsDlg
+ControlCount=2
+Control1=IDOK,button,1342242817
+Control2=IDC_LIST_COMMANDS,listbox,1352728963
+
+[CLS:CCommandsDlg]
+Type=0
+HeaderFile=CommandsDlg.h
+ImplementationFile=CommandsDlg.cpp
+BaseClass=CDialog
+Filter=D
+VirtualFilter=dWC
+LastObject=CCommandsDlg
+
+[MNU:IDR_MENU_DROP]
+Type=1
+Class=?
+Command1=ID_SELECTION_SELECTCOMPLETETALL
+Command2=ID_SELECTION_SELECTTOUCHING
+Command3=ID_SELECTION_SELECTPARTIALTALL
+Command4=ID_SELECTION_SELECTINSIDE
+Command5=ID_DROP_GROUP_ADDTO
+Command6=ID_DROP_GROUP_REMOVE
+Command7=ID_DROP_GROUP_NAME
+Command8=ID_DROP_GROUP_NEWGROUP
+Command9=ID_SELECTION_UNGROUPENTITY
+Command10=ID_SELECTION_MAKE_DETAIL
+Command11=ID_SELECTION_MAKE_STRUCTURAL
+CommandCount=11
+
+[ACL:IDR_ACCEL_SURFACE]
+Type=1
+Class=?
+Command1=ID_BYEBYE
+CommandCount=1
+
+[DLG:IDD_DIALOG_SCALE]
+Type=1
+Class=CScaleDialog
+ControlCount=8
+Control1=IDOK,button,1342242817
+Control2=IDCANCEL,button,1342242816
+Control3=IDC_STATIC,static,1342308352
+Control4=IDC_STATIC,static,1342308352
+Control5=IDC_STATIC,static,1342308352
+Control6=IDC_EDIT_X,edit,1350631552
+Control7=IDC_EDIT_Y,edit,1350631552
+Control8=IDC_EDIT_Z,edit,1350631552
+
+[CLS:CScaleDialog]
+Type=0
+HeaderFile=ScaleDialog.h
+ImplementationFile=ScaleDialog.cpp
+BaseClass=CDialog
+Filter=D
+VirtualFilter=dWC
+LastObject=IDOK
+
+[CLS:CTexEdit]
+Type=0
+HeaderFile=TexEdit.h
+ImplementationFile=TexEdit.cpp
+BaseClass=CEdit
+Filter=W
+VirtualFilter=WC
+LastObject=CTexEdit
+
+[CLS:CSurfaceDlg]
+Type=0
+HeaderFile=SurfaceDlg.h
+ImplementationFile=SurfaceDlg.cpp
+BaseClass=CDialog
+Filter=D
+LastObject=CSurfaceDlg
+VirtualFilter=dWC
+
+[DLG:IDD_DIALOG_FINDREPLACE]
+Type=1
+Class=CFindTextureDlg
+ControlCount=10
+Control1=IDC_EDIT_FIND,edit,1350631552
+Control2=IDC_EDIT_REPLACE,edit,1350631552
+Control3=IDC_CHECK_SELECTED,button,1342242819
+Control4=IDC_CHECK_FORCE,button,1342242819
+Control5=IDOK,button,1342242817
+Control6=IDCANCEL,button,1342242816
+Control7=IDC_STATIC,static,1342308352
+Control8=IDC_STATIC,static,1342308352
+Control9=ID_BTN_APPLY,button,1342242817
+Control10=IDC_CHECK_LIVE,button,1342242819
+
+[CLS:CFindTextureDlg]
+Type=0
+HeaderFile=FindTextureDlg.h
+ImplementationFile=FindTextureDlg.cpp
+BaseClass=CDialog
+Filter=D
+VirtualFilter=dWC
+LastObject=CFindTextureDlg
+
+[DLG:IDD_DIALOG_STAIRS]
+Type=1
+Class=?
+ControlCount=6
+Control1=IDOK,button,1342242817
+Control2=IDCANCEL,button,1342242816
+Control3=IDC_STATIC,static,1342308352
+Control4=IDC_STATIC,static,1342308352
+Control5=IDC_STATIC,static,1342308352
+Control6=IDC_EDIT_ROTATION,edit,1350631552
+
+[DLG:IDD_DIALOG_INPUT]
+Type=1
+Class=CBSInput
+ControlCount=12
+Control1=IDOK,button,1342242817
+Control2=IDCANCEL,button,1342242816
+Control3=IDC_STATIC_FIELD1,static,1342308352
+Control4=IDC_EDIT_FIELD1,edit,1350631552
+Control5=IDC_STATIC_FIELD2,static,1342308352
+Control6=IDC_EDIT_FIELD2,edit,1350631552
+Control7=IDC_STATIC_FIELD3,static,1342308352
+Control8=IDC_EDIT_FIELD3,edit,1350631552
+Control9=IDC_STATIC_FIELD4,static,1342308352
+Control10=IDC_EDIT_FIELD4,edit,1350631552
+Control11=IDC_STATIC_FIELD5,static,1342308352
+Control12=IDC_EDIT_FIELD5,edit,1350631552
+
+[CLS:CBSInput]
+Type=0
+HeaderFile=BSInput.h
+ImplementationFile=BSInput.cpp
+BaseClass=CDialog
+Filter=D
+VirtualFilter=dWC
+LastObject=CBSInput
+
+[CLS:CDialogInfo]
+Type=0
+HeaderFile=DialogInfo.h
+ImplementationFile=DialogInfo.cpp
+BaseClass=CDialog
+Filter=D
+VirtualFilter=dWC
+LastObject=ID_SCALELOCKX
+
+[DLG:IDD_DLG_INFORMATION]
+Type=1
+Class=CDialogInfo
+ControlCount=1
+Control1=IDC_EDIT1,edit,1486946308
+
+[TB:IDR_TOOLBAR_SCALELOCK]
+Type=1
+Class=?
+Command1=ID_SCALELOCKX
+Command2=ID_SCALELOCKY
+Command3=ID_SCALELOCKZ
+CommandCount=3
+
+[DLG:"IDD_PROJECT"]
+Type=1
+ControlCount=20
+Control1=IDOK,button,1342242817
+Control2=IDCANCEL,button,1342242816
+Control3=IDC_STATIC,button,1342177287
+Control4=IDC_PRJBASEPATH,edit,1350631552
+Control5=IDC_STATIC,static,1342308352
+Control6=IDC_STATIC,static,1342308352
+Control7=IDC_PRJRSHCMD,edit,1350631552
+Control8=IDC_STATIC,static,1342308352
+Control9=IDC_PRJREMOTEBASE,edit,1350631552
+Control10=IDC_STATIC,static,1342308352
+Control11=IDC_PRJENTITYPATH,edit,1350631552
+Control12=IDC_STATIC,static,1342308352
+Control13=IDC_PRJTEXPATH,edit,1350631552
+Control14=IDC_STATIC,button,1342177287
+Control15=IDC_ADDCMD,button,1342242816
+Control16=IDC_CMD_LIST,listbox,1352728835
+Control17=IDC_REMCMD,button,1342242816
+Control18=IDC_STATIC,static,1342308352
+Control19=IDC_PRJMAPSPATH,edit,1350631552
+Control20=IDC_EDITCMD,button,1342242816
+
+[DLG:"IDD_ADDCMD"]
+Type=1
+ControlCount=6
+Control1=IDOK,button,1342242817
+Control2=IDCANCEL,button,1342242816
+Control3=IDC_CMDMENUTEXT,edit,1350631552
+Control4=IDC_CMDCOMMAND,edit,1350631552
+Control5=IDC_STATIC,static,1342308352
+Control6=IDC_STATIC,static,1342308352
+
+[DLG:IDD_ADDCMD]
+Type=1
+Class=?
+ControlCount=6
+Control1=IDOK,button,1342242817
+Control2=IDCANCEL,button,1342242816
+Control3=IDC_CMDMENUTEXT,edit,1350631552
+Control4=IDC_CMDCOMMAND,edit,1350631552
+Control5=IDC_STATIC,static,1342308352
+Control6=IDC_STATIC,static,1342308352
+
+[DLG:IDD_PROJECT]
+Type=1
+Class=?
+ControlCount=22
+Control1=IDC_PRJBASEPATH,edit,1350631552
+Control2=IDC_PRJMAPSPATH,edit,1350631552
+Control3=IDC_PRJRSHCMD,edit,1350631552
+Control4=IDC_PRJREMOTEBASE,edit,1350631552
+Control5=IDC_PRJENTITYPATH,edit,1350631552
+Control6=IDC_PRJTEXPATH,edit,1350631552
+Control7=IDC_CMD_LIST,listbox,1352728835
+Control8=IDC_ADDCMD,button,1342242816
+Control9=IDC_EDITCMD,button,1342242816
+Control10=IDC_REMCMD,button,1342242816
+Control11=IDC_CHECK_BPRIMIT,button,1342242819
+Control12=IDOK,button,1342242817
+Control13=IDCANCEL,button,1342242816
+Control14=IDC_STATIC,button,1342177287
+Control15=IDC_STATIC,static,1342308352
+Control16=IDC_STATIC,static,1342308352
+Control17=IDC_STATIC,static,1342308352
+Control18=IDC_STATIC,static,1342308352
+Control19=IDC_STATIC,static,1342308352
+Control20=IDC_STATIC,button,1342177287
+Control21=IDC_STATIC,static,1342308352
+Control22=IDC_STATIC,button,1342177287
+
+[DLG:IDD_TEXTUREBAR]
+Type=1
+Class=CTextureBar
+ControlCount=17
+Control1=IDC_HSHIFT,edit,1350631552
+Control2=IDC_SPIN_HSHIFT,msctls_updown32,1342177332
+Control3=IDC_VSHIFT,edit,1350631552
+Control4=IDC_SPIN_VSHIFT,msctls_updown32,1342177332
+Control5=IDC_HSCALE,edit,1350631552
+Control6=IDC_SPIN_HSCALE,msctls_updown32,1342177332
+Control7=IDC_VSCALE,edit,1350631552
+Control8=IDC_SPIN_VSCALE,msctls_updown32,1342177332
+Control9=IDC_ROTATE,edit,1350631552
+Control10=IDC_SPIN_ROTATE,msctls_updown32,1342177332
+Control11=IDC_STATIC,static,1342308352
+Control12=IDC_STATIC,static,1342308352
+Control13=IDC_STATIC,static,1342308352
+Control14=IDC_STATIC,static,1342308352
+Control15=IDC_STATIC,static,1342308352
+Control16=IDC_BTN_APPLYTEXTURESTUFF,button,1073741825
+Control17=IDC_EDIT_ROTATEAMT,edit,1350631552
+
+[CLS:CTextureBar]
+Type=0
+HeaderFile=TextureBar.h
+ImplementationFile=TextureBar.cpp
+BaseClass=CDialogBar
+Filter=W
+VirtualFilter=dWC
+LastObject=CTextureBar
+
+[TB:IDR_TOOLBAR_ADVANCED]
+Type=1
+Class=?
+Command1=ID_FILE_OPEN
+Command2=ID_FILE_SAVE
+Command3=ID_BRUSH_FLIPX
+Command4=ID_BRUSH_ROTATEX
+Command5=ID_BRUSH_FLIPY
+Command6=ID_BRUSH_ROTATEY
+Command7=ID_BRUSH_FLIPZ
+Command8=ID_BRUSH_ROTATEZ
+Command9=ID_SELECTION_SELECTCOMPLETETALL
+Command10=ID_SELECTION_SELECTTOUCHING
+Command11=ID_SELECTION_SELECTPARTIALTALL
+Command12=ID_SELECTION_SELECTINSIDE
+Command13=ID_SELECTION_CSGSUBTRACT
+Command14=ID_SELECTION_CSGMERGE
+Command15=ID_SELECTION_MAKEHOLLOW
+Command16=ID_VIEW_CLIPPER
+Command17=ID_VIEW_CHANGE
+Command18=ID_TEXTURES_POPUP
+Command19=ID_VIEW_CUBICCLIPPING
+Command20=ID_SELECT_MOUSEROTATE
+Command21=ID_SELECT_MOUSESCALE
+Command22=ID_SCALELOCKX
+Command23=ID_SCALELOCKY
+Command24=ID_SCALELOCKZ
+Command25=ID_DONTSELECTCURVE
+Command26=ID_PATCH_SHOWBOUNDINGBOX
+Command27=ID_PATCH_WIREFRAME
+Command28=ID_PATCH_BEND
+Command29=ID_PATCH_INSDEL
+Command30=ID_CURVE_CAP
+Command31=ID_PATCH_WELD
+Command32=ID_PATCH_DRILLDOWN
+Command33=ID_SHOW_ENTITIES
+CommandCount=33
+
+[MNU:IDR_MENU11]
+Type=1
+Command1=ID_FILE_NEW
+Command2=ID_FILE_OPEN
+Command3=ID_FILE_SAVE
+Command4=ID_FILE_SAVEAS
+Command5=ID_FILE_SAVEREGION
+Command6=ID_FILE_NEWPROJECT
+Command7=ID_FILE_LOADPROJECT
+Command8=ID_FILE_PROJECTSETTINGS
+Command9=ID_FILE_IMPORT
+Command10=ID_FILE_POINTFILE
+Command11=ID_FILE_EXIT
+Command12=ID_EDIT_UNDO
+Command13=ID_EDIT_COPYBRUSH
+Command14=ID_EDIT_PASTEBRUSH
+Command15=ID_EDIT_MAPINFO
+Command16=ID_EDIT_ENTITYINFO
+Command17=ID_BRUSH_SCRIPTS
+Command18=ID_PREFS
+Command19=ID_TOGGLECAMERA
+Command20=ID_TOGGLECONSOLE
+Command21=ID_VIEW_ENTITY
+Command22=ID_TOGGLEVIEW
+Command23=ID_TOGGLEVIEW_YZ
+Command24=ID_TOGGLEVIEW_XZ
+Command25=ID_TOGGLEZ
+Command26=ID_VIEW_CENTER
+Command27=ID_VIEW_UPFLOOR
+Command28=ID_VIEW_DOWNFLOOR
+Command29=ID_VIEW_NEXTVIEW
+Command30=ID_VIEW_XY
+Command31=ID_VIEW_SIDE
+Command32=ID_VIEW_FRONT
+Command33=ID_VIEW_100
+Command34=ID_VIEW_ZOOMIN
+Command35=ID_VIEW_ZOOMOUT
+Command36=ID_VIEW_Z100
+Command37=ID_VIEW_ZZOOMIN
+Command38=ID_VIEW_ZZOOMOUT
+Command39=ID_VIEW_CUBEIN
+Command40=ID_VIEW_CUBEOUT
+Command41=ID_VIEW_SHOWNAMES
+Command42=ID_VIEW_SHOWBLOCKS
+Command43=ID_VIEW_SHOWCOORDINATES
+Command44=ID_VIEW_SHOWENT
+Command45=ID_VIEW_SHOWPATH
+Command46=ID_VIEW_SHOWLIGHTS
+Command47=ID_VIEW_SHOWWATER
+Command48=ID_VIEW_SHOWCLIP
+Command49=ID_VIEW_SHOWWORLD
+Command50=ID_VIEW_SHOWDETAIL
+Command51=ID_VIEW_CUBICCLIPPING
+Command52=ID_SELECTION_DRAGEDGES
+Command53=ID_SELECTION_DRAGVERTECIES
+Command54=ID_SELECTION_CLONE
+Command55=ID_SELECTION_DESELECT
+Command56=ID_SELECTION_DELETE
+Command57=ID_BRUSH_FLIPX
+Command58=ID_BRUSH_FLIPY
+Command59=ID_BRUSH_FLIPZ
+Command60=ID_BRUSH_ROTATEX
+Command61=ID_BRUSH_ROTATEY
+Command62=ID_BRUSH_ROTATEZ
+Command63=ID_SELECTION_ARBITRARYROTATION
+Command64=ID_SELECT_SCALE
+Command65=ID_SELECTION_MAKEHOLLOW
+Command66=ID_SELECTION_CSGSUBTRACT
+Command67=ID_SELECTION_SELECTCOMPLETETALL
+Command68=ID_SELECTION_SELECTTOUCHING
+Command69=ID_SELECTION_SELECTPARTIALTALL
+Command70=ID_SELECTION_SELECTINSIDE
+Command71=ID_VIEW_CLIPPER
+Command72=ID_CLIP_SELECTED
+Command73=ID_SPLIT_SELECTED
+Command74=ID_FLIP_CLIP
+Command75=ID_SELECTION_CONNECT
+Command76=ID_SELECTION_UNGROUPENTITY
+Command77=ID_SELECTION_MAKE_DETAIL
+Command78=ID_SELECTION_MAKE_STRUCTURAL
+Command79=ID_GRID_1
+Command80=ID_GRID_2
+Command81=ID_GRID_4
+Command82=ID_GRID_8
+Command83=ID_GRID_16
+Command84=ID_GRID_32
+Command85=ID_GRID_64
+Command86=ID_SNAPTOGRID
+Command87=ID_TEXTURES_SHOWINUSE
+Command88=ID_TEXTURES_INSPECTOR
+Command89=ID_TEXTURES_WIREFRAME
+Command90=ID_TEXTURES_FLATSHADE
+Command91=ID_VIEW_NEAREST
+Command92=ID_VIEW_NEARESTMIPMAP
+Command93=ID_VIEW_LINEAR
+Command94=ID_VIEW_BILINEAR
+Command95=ID_VIEW_BILINEARMIPMAP
+Command96=ID_VIEW_TRILINEAR
+Command97=ID_TEXTURE_REPLACEALL
+Command98=ID_TOGGLE_LOCK
+Command99=ID_TOGGLE_ROTATELOCK
+Command100=ID_TEXTURES_LOAD
+Command101=ID_MISC_BENCHMARK
+Command102=ID_COLOR_SETORIGINAL
+Command103=ID_COLOR_SETQER
+Command104=ID_COLOR_SETBLACK
+Command105=ID_TEXTUREBK
+Command106=ID_COLORS_XYBK
+Command107=ID_COLORS_MAJOR
+Command108=ID_COLORS_MINOR
+Command109=ID_COLORS_GRIDTEXT
+Command110=ID_COLORS_GRIDBLOCK
+Command111=ID_COLORS_BRUSH
+Command112=ID_COLORS_SELECTEDBRUSH
+Command113=ID_COLORS_CLIPPER
+Command114=ID_COLORS_VIEWNAME
+Command115=ID_MISC_GAMMA
+Command116=ID_MISC_FINDBRUSH
+Command117=ID_MISC_NEXTLEAKSPOT
+Command118=ID_MISC_PREVIOUSLEAKSPOT
+Command119=ID_MISC_PRINTXY
+Command120=ID_MISC_SELECTENTITYCOLOR
+Command121=ID_REGION_OFF
+Command122=ID_REGION_SETXY
+Command123=ID_REGION_SETTALLBRUSH
+Command124=ID_REGION_SETBRUSH
+Command125=ID_REGION_SETSELECTION
+Command126=ID_BRUSH_3SIDED
+Command127=ID_BRUSH_4SIDED
+Command128=ID_BRUSH_5SIDED
+Command129=ID_BRUSH_6SIDED
+Command130=ID_BRUSH_7SIDED
+Command131=ID_BRUSH_8SIDED
+Command132=ID_BRUSH_9SIDED
+Command133=ID_BRUSH_ARBITRARYSIDED
+Command134=ID_BRUSH_MAKECONE
+Command135=ID_CURVE_CYLINDER
+Command136=ID_CURVE_ENDCAP
+Command137=ID_CURVE_BEVEL
+Command138=ID_CURVE_SPHERE
+Command139=ID_CURVE_HEMISPHERE
+Command140=ID_CURVE_QUARTER
+Command141=ID_CURVE_EIGHTHSPHERE
+Command142=ID_CURVE_INVERTCURVE
+Command143=ID_HELP_COMMANDLIST
+Command144=ID_HELP_ABOUT
+CommandCount=144
+
+[MNU:IDR_MENU_QUAKE3]
+Type=1
+Class=?
+Command1=ID_FILE_NEW
+Command2=ID_FILE_OPEN
+Command3=ID_FILE_IMPORTMAP
+Command4=ID_FILE_SAVE
+Command5=ID_FILE_SAVEAS
+Command6=ID_FILE_EXPORTMAP
+Command7=ID_FILE_SAVEREGION
+Command8=ID_FILE_NEWPROJECT
+Command9=ID_FILE_LOADPROJECT
+Command10=ID_FILE_PROJECTSETTINGS
+Command11=ID_FILE_POINTFILE
+Command12=ID_FILE_EXIT
+Command13=ID_EDIT_UNDO
+Command14=ID_EDIT_REDO
+Command15=ID_EDIT_COPYBRUSH
+Command16=ID_EDIT_PASTEBRUSH
+Command17=ID_SELECTION_DELETE
+Command18=ID_EDIT_MAPINFO
+Command19=ID_EDIT_ENTITYINFO
+Command20=ID_BRUSH_SCRIPTS
+Command21=ID_EDIT_LOADPREFAB
+Command22=ID_EDIT_SAVEPREFAB
+Command23=ID_PREFS
+Command24=ID_TOGGLECAMERA
+Command25=ID_TOGGLECONSOLE
+Command26=ID_VIEW_ENTITY
+Command27=ID_VIEW_GROUPS
+Command28=ID_TOGGLEVIEW
+Command29=ID_TOGGLEVIEW_YZ
+Command30=ID_TOGGLEVIEW_XZ
+Command31=ID_TOGGLEZ
+Command32=ID_VIEW_CENTER
+Command33=ID_VIEW_UPFLOOR
+Command34=ID_VIEW_DOWNFLOOR
+Command35=ID_VIEW_NEXTVIEW
+Command36=ID_VIEW_XY
+Command37=ID_VIEW_SIDE
+Command38=ID_VIEW_FRONT
+Command39=ID_VIEW_100
+Command40=ID_VIEW_ZOOMIN
+Command41=ID_VIEW_ZOOMOUT
+Command42=ID_VIEW_Z100
+Command43=ID_VIEW_ZZOOMIN
+Command44=ID_VIEW_ZZOOMOUT
+Command45=ID_VIEW_CUBEIN
+Command46=ID_VIEW_CUBEOUT
+Command47=ID_VIEW_SHOWNAMES
+Command48=ID_VIEW_SHOWBLOCKS
+Command49=ID_VIEW_SHOWCOORDINATES
+Command50=ID_VIEW_SHOWENT
+Command51=ID_VIEW_SHOWPATH
+Command52=ID_VIEW_SHOWLIGHTS
+Command53=ID_VIEW_SHOWWATER
+Command54=ID_VIEW_SHOWCLIP
+Command55=ID_VIEW_SHOWHINT
+Command56=ID_VIEW_SHOWWORLD
+Command57=ID_VIEW_SHOWDETAIL
+Command58=ID_VIEW_SHOWCURVES
+Command59=ID_VIEW_SHOWCAULK
+Command60=ID_VIEW_SHOWANGLES
+Command61=ID_VIEW_HIDESHOW_HIDESELECTED
+Command62=ID_VIEW_HIDESHOW_SHOWHIDDEN
+Command63=ID_VIEW_ENTITIESAS_BOUNDINGBOX
+Command64=ID_VIEW_ENTITIESAS_WIREFRAME
+Command65=ID_VIEW_ENTITIESAS_SELECTEDWIREFRAME
+Command66=ID_VIEW_ENTITIESAS_SELECTEDSKINNED
+Command67=ID_VIEW_ENTITIESAS_SKINNED
+Command68=ID_VIEW_ENTITIESAS_SKINNEDANDBOXED
+Command69=ID_VIEW_CUBICCLIPPING
+Command70=ID_VIEW_OPENGLLIGHTING
+Command71=ID_SELECTION_DRAGEDGES
+Command72=ID_SELECTION_DRAGVERTECIES
+Command73=ID_SELECTION_CLONE
+Command74=ID_SELECTION_DESELECT
+Command75=ID_BRUSH_FLIPX
+Command76=ID_BRUSH_FLIPY
+Command77=ID_BRUSH_FLIPZ
+Command78=ID_BRUSH_ROTATEX
+Command79=ID_BRUSH_ROTATEY
+Command80=ID_BRUSH_ROTATEZ
+Command81=ID_SELECTION_ARBITRARYROTATION
+Command82=ID_SELECT_SCALE
+Command83=ID_SELECTION_MAKEHOLLOW
+Command84=ID_SELECTION_CSGSUBTRACT
+Command85=ID_SELECTION_CSGMERGE
+Command86=ID_SELECTION_SELECTCOMPLETETALL
+Command87=ID_SELECTION_SELECTTOUCHING
+Command88=ID_SELECTION_SELECTPARTIALTALL
+Command89=ID_SELECTION_SELECTINSIDE
+Command90=ID_VIEW_CLIPPER
+Command91=ID_CLIP_SELECTED
+Command92=ID_SPLIT_SELECTED
+Command93=ID_FLIP_CLIP
+Command94=ID_SELECTION_CONNECT
+Command95=ID_SELECTION_UNGROUPENTITY
+Command96=ID_SELECTION_MAKE_DETAIL
+Command97=ID_SELECTION_MAKE_STRUCTURAL
+Command98=ID_GRID_1
+Command99=ID_GRID_2
+Command100=ID_GRID_4
+Command101=ID_GRID_8
+Command102=ID_GRID_16
+Command103=ID_GRID_32
+Command104=ID_GRID_64
+Command105=ID_SNAPTOGRID
+Command106=ID_TEXTURES_SHOWINUSE
+Command107=ID_TEXTURES_SHOWALL
+Command108=ID_TEXTURES_INSPECTOR
+Command109=ID_TEXTURES_WIREFRAME
+Command110=ID_TEXTURES_FLATSHADE
+Command111=ID_VIEW_NEAREST
+Command112=ID_VIEW_NEARESTMIPMAP
+Command113=ID_VIEW_LINEAR
+Command114=ID_VIEW_BILINEAR
+Command115=ID_VIEW_BILINEARMIPMAP
+Command116=ID_VIEW_TRILINEAR
+Command117=ID_TEXTURE_REPLACEALL
+Command118=ID_TOGGLE_LOCK
+Command119=ID_TOGGLE_ROTATELOCK
+Command120=ID_TEXTURES_LOAD
+Command121=ID_TEXTURES_RELOADSHADERS
+Command122=ID_TEXTURES_SHADERS_SHOW
+Command123=ID_TEXTURES_FLUSH
+Command124=ID_TEXTURES_FLUSH_UNUSED
+Command125=ID_TEXTURES_TEXTUREWINDOWSCALE_200
+Command126=ID_TEXTURES_TEXTUREWINDOWSCALE_100
+Command127=ID_TEXTURES_TEXTUREWINDOWSCALE_50
+Command128=ID_TEXTURES_TEXTUREWINDOWSCALE_25
+Command129=ID_TEXTURES_TEXTUREWINDOWSCALE_10
+Command130=ID_MISC_BENCHMARK
+Command131=ID_COLOR_SETORIGINAL
+Command132=ID_COLOR_SETQER
+Command133=ID_COLOR_SETBLACK
+Command134=ID_TEXTUREBK
+Command135=ID_COLORS_XYBK
+Command136=ID_COLORS_MAJOR
+Command137=ID_COLORS_MINOR
+Command138=ID_COLORS_GRIDTEXT
+Command139=ID_COLORS_GRIDBLOCK
+Command140=ID_COLORS_BRUSH
+Command141=ID_COLORS_SELECTEDBRUSH
+Command142=ID_COLORS_CLIPPER
+Command143=ID_COLORS_VIEWNAME
+Command144=ID_MISC_GAMMA
+Command145=ID_MISC_FINDBRUSH
+Command146=ID_MISC_NEXTLEAKSPOT
+Command147=ID_MISC_PREVIOUSLEAKSPOT
+Command148=ID_MISC_PRINTXY
+Command149=ID_MISC_SELECTENTITYCOLOR
+Command150=ID_REGION_OFF
+Command151=ID_REGION_SETXY
+Command152=ID_REGION_SETTALLBRUSH
+Command153=ID_REGION_SETBRUSH
+Command154=ID_REGION_SETSELECTION
+Command155=ID_BRUSH_3SIDED
+Command156=ID_BRUSH_4SIDED
+Command157=ID_BRUSH_5SIDED
+Command158=ID_BRUSH_6SIDED
+Command159=ID_BRUSH_7SIDED
+Command160=ID_BRUSH_8SIDED
+Command161=ID_BRUSH_9SIDED
+Command162=ID_BRUSH_ARBITRARYSIDED
+Command163=ID_BRUSH_MAKECONE
+Command164=ID_BRUSH_PRIMITIVES_SPHERE
+Command165=ID_CURVE_PATCHTUBE
+Command166=ID_CURVE_PATCHDENSETUBE
+Command167=ID_CURVE_PATCHVERYDENSETUBE
+Command168=ID_CURVE_PATCHSQUARE
+Command169=ID_CURVE_PATCHENDCAP
+Command170=ID_CURVE_PATCHBEVEL
+Command171=ID_CURVE_MOREENDCAPSBEVELS_SQUAREBEVEL
+Command172=ID_CURVE_MOREENDCAPSBEVELS_SQUAREENDCAP
+Command173=ID_CURVE_PATCHCONE
+Command174=ID_CURVE_PRIMITIVES_SPHERE
+Command175=ID_CURVE_SIMPLEPATCHMESH
+Command176=ID_CURVE_INSERT_INSERTCOLUMN
+Command177=ID_CURVE_INSERT_ADDCOLUMN
+Command178=ID_CURVE_INSERT_INSERTROW
+Command179=ID_CURVE_INSERT_ADDROW
+Command180=ID_CURVE_DELETE_FIRSTCOLUMN
+Command181=ID_CURVE_DELETE_LASTCOLUMN
+Command182=ID_CURVE_DELETE_FIRSTROW
+Command183=ID_CURVE_DELETE_LASTROW
+Command184=ID_CURVE_NEGATIVE
+Command185=ID_CURVE_REDISPERSE_COLS
+Command186=ID_CURVE_REDISPERSE_ROWS
+Command187=ID_CURVE_MATRIX_TRANSPOSE
+Command188=ID_CURVE_CAP
+Command189=ID_CURVE_CAP_INVERTEDBEVEL
+Command190=ID_CURVE_CAP_INVERTEDENDCAP
+Command191=ID_CURVE_CYCLECAP
+Command192=ID_CURVE_OVERLAY_SET
+Command193=ID_CURVE_OVERLAY_CLEAR
+Command194=ID_CURVE_THICKEN
+Command195=ID_PLUGINS_REFRESH
+Command196=ID_HELP
+Command197=ID_HELP_COMMANDLIST
+Command198=ID_HELP_ABOUT
+CommandCount=198
+
+[MNU:IDR_MENU1]
+Type=1
+Class=?
+Command1=ID_FILE_NEW
+Command2=ID_FILE_OPEN
+Command3=ID_FILE_IMPORTMAP
+Command4=ID_FILE_SAVE
+Command5=ID_FILE_SAVEAS
+Command6=ID_FILE_EXPORTMAP
+Command7=ID_FILE_SAVEREGION
+Command8=ID_FILE_NEWPROJECT
+Command9=ID_FILE_LOADPROJECT
+Command10=ID_FILE_PROJECTSETTINGS
+Command11=ID_FILE_POINTFILE
+Command12=ID_FILE_EXIT
+Command13=ID_EDIT_UNDO
+Command14=ID_EDIT_COPYBRUSH
+Command15=ID_EDIT_PASTEBRUSH
+Command16=ID_EDIT_MAPINFO
+Command17=ID_EDIT_ENTITYINFO
+Command18=ID_BRUSH_SCRIPTS
+Command19=ID_EDIT_LOADPREFAB
+Command20=ID_PREFS
+Command21=ID_TOGGLECAMERA
+Command22=ID_TOGGLECONSOLE
+Command23=ID_VIEW_ENTITY
+Command24=ID_TOGGLEVIEW
+Command25=ID_TOGGLEVIEW_YZ
+Command26=ID_TOGGLEVIEW_XZ
+Command27=ID_TOGGLEZ
+Command28=ID_VIEW_CENTER
+Command29=ID_VIEW_UPFLOOR
+Command30=ID_VIEW_DOWNFLOOR
+Command31=ID_VIEW_NEXTVIEW
+Command32=ID_VIEW_XY
+Command33=ID_VIEW_SIDE
+Command34=ID_VIEW_FRONT
+Command35=ID_VIEW_100
+Command36=ID_VIEW_ZOOMIN
+Command37=ID_VIEW_ZOOMOUT
+Command38=ID_VIEW_Z100
+Command39=ID_VIEW_ZZOOMIN
+Command40=ID_VIEW_ZZOOMOUT
+Command41=ID_VIEW_CUBEIN
+Command42=ID_VIEW_CUBEOUT
+Command43=ID_VIEW_SHOWNAMES
+Command44=ID_VIEW_SHOWBLOCKS
+Command45=ID_VIEW_SHOWCOORDINATES
+Command46=ID_VIEW_SHOWENT
+Command47=ID_VIEW_SHOWPATH
+Command48=ID_VIEW_SHOWLIGHTS
+Command49=ID_VIEW_SHOWWATER
+Command50=ID_VIEW_SHOWCLIP
+Command51=ID_VIEW_SHOWWORLD
+Command52=ID_VIEW_SHOWDETAIL
+Command53=ID_VIEW_CUBICCLIPPING
+Command54=ID_DYNAMIC_LIGHTING
+Command55=ID_SELECTION_DRAGEDGES
+Command56=ID_SELECTION_DRAGVERTECIES
+Command57=ID_SELECTION_CLONE
+Command58=ID_SELECTION_DESELECT
+Command59=ID_SELECTION_DELETE
+Command60=ID_BRUSH_FLIPX
+Command61=ID_BRUSH_FLIPY
+Command62=ID_BRUSH_FLIPZ
+Command63=ID_BRUSH_ROTATEX
+Command64=ID_BRUSH_ROTATEY
+Command65=ID_BRUSH_ROTATEZ
+Command66=ID_SELECTION_ARBITRARYROTATION
+Command67=ID_SELECT_SCALE
+Command68=ID_SELECTION_MAKEHOLLOW
+Command69=ID_SELECTION_CSGSUBTRACT
+Command70=ID_SELECTION_CSGADD
+Command71=ID_SELECTION_SELECTCOMPLETETALL
+Command72=ID_SELECTION_SELECTTOUCHING
+Command73=ID_SELECTION_SELECTPARTIALTALL
+Command74=ID_SELECTION_SELECTINSIDE
+Command75=ID_SELECTION_SELECT_NUDGELEFT
+Command76=ID_SELECTION_SELECT_NUDGERIGHT
+Command77=ID_SELECTION_SELECT_NUDGEUP
+Command78=ID_SELECTION_SELECT_NUDGEDOWN
+Command79=ID_VIEW_CLIPPER
+Command80=ID_CLIP_SELECTED
+Command81=ID_SPLIT_SELECTED
+Command82=ID_FLIP_CLIP
+Command83=ID_SELECTION_CONNECT
+Command84=ID_SELECTION_UNGROUPENTITY
+Command85=ID_SELECTION_MAKE_DETAIL
+Command86=ID_SELECTION_MAKE_STRUCTURAL
+Command87=ID_GRID_1
+Command88=ID_GRID_2
+Command89=ID_GRID_4
+Command90=ID_GRID_8
+Command91=ID_GRID_16
+Command92=ID_GRID_32
+Command93=ID_GRID_64
+Command94=ID_SNAPTOGRID
+Command95=ID_TEXTURES_SHOWINUSE
+Command96=ID_TEXTURES_INSPECTOR
+Command97=ID_TEXTURES_WIREFRAME
+Command98=ID_TEXTURES_FLATSHADE
+Command99=ID_VIEW_NEAREST
+Command100=ID_VIEW_NEARESTMIPMAP
+Command101=ID_VIEW_LINEAR
+Command102=ID_VIEW_BILINEAR
+Command103=ID_VIEW_BILINEARMIPMAP
+Command104=ID_VIEW_TRILINEAR
+Command105=ID_TEXTURE_REPLACEALL
+Command106=ID_TOGGLE_LOCK
+Command107=ID_TOGGLE_ROTATELOCK
+Command108=ID_TEXTURES_LOAD
+Command109=ID_TEXTURES_LOADLIST
+Command110=ID_MISC_BENCHMARK
+Command111=ID_COLOR_SETORIGINAL
+Command112=ID_COLOR_SETQER
+Command113=ID_COLOR_SETBLACK
+Command114=ID_TEXTUREBK
+Command115=ID_COLORS_XYBK
+Command116=ID_COLORS_MAJOR
+Command117=ID_COLORS_MINOR
+Command118=ID_COLORS_GRIDTEXT
+Command119=ID_COLORS_GRIDBLOCK
+Command120=ID_COLORS_BRUSH
+Command121=ID_COLORS_SELECTEDBRUSH
+Command122=ID_COLORS_CLIPPER
+Command123=ID_COLORS_VIEWNAME
+Command124=ID_MISC_GAMMA
+Command125=ID_MISC_FINDBRUSH
+Command126=ID_MISC_NEXTLEAKSPOT
+Command127=ID_MISC_PREVIOUSLEAKSPOT
+Command128=ID_MISC_PRINTXY
+Command129=ID_MISC_SELECTENTITYCOLOR
+Command130=ID_CONVERTCURVES
+Command131=ID_REGION_OFF
+Command132=ID_REGION_SETXY
+Command133=ID_REGION_SETTALLBRUSH
+Command134=ID_REGION_SETBRUSH
+Command135=ID_REGION_SETSELECTION
+Command136=ID_BRUSH_3SIDED
+Command137=ID_BRUSH_4SIDED
+Command138=ID_BRUSH_5SIDED
+Command139=ID_BRUSH_6SIDED
+Command140=ID_BRUSH_7SIDED
+Command141=ID_BRUSH_8SIDED
+Command142=ID_BRUSH_9SIDED
+Command143=ID_BRUSH_ARBITRARYSIDED
+Command144=ID_BRUSH_MAKECONE
+Command145=ID_HELP_COMMANDLIST
+Command146=ID_HELP_ABOUT
+CommandCount=146
+
+[ACL:IDR_MINIACCEL]
+Type=1
+Class=?
+Command1=ID_SELECTION_SELECT_NUDGEDOWN
+Command2=ID_SELECTION_SELECT_NUDGELEFT
+Command3=ID_SELECTION_SELECT_NUDGERIGHT
+Command4=ID_SELECTION_SELECT_NUDGEUP
+CommandCount=4
+
+[DLG:IDD_DIALOG_TEXTURELIST]
+Type=1
+Class=CDialogTextures
+ControlCount=3
+Control1=IDOK,button,1342242817
+Control2=IDCANCEL,button,1342242816
+Control3=IDC_LIST_TEXTURES,listbox,1352728835
+
+[CLS:CDialogTextures]
+Type=0
+HeaderFile=DialogTextures.h
+ImplementationFile=DialogTextures.cpp
+BaseClass=CDialog
+Filter=D
+LastObject=ID_TEXTURES_LOADLIST
+VirtualFilter=dWC
+
+[DLG:IDD_DIALOG_NEWPATCH]
+Type=1
+Class=CPatchDensityDlg
+ControlCount=6
+Control1=IDOK,button,1342242817
+Control2=IDCANCEL,button,1342242816
+Control3=IDC_STATIC,static,1342308352
+Control4=IDC_STATIC,static,1342308352
+Control5=IDC_COMBO_WIDTH,combobox,1344339971
+Control6=IDC_COMBO_HEIGHT,combobox,1344339971
+
+[CLS:CPatchDensityDlg]
+Type=0
+HeaderFile=PatchDensityDlg.h
+ImplementationFile=PatchDensityDlg.cpp
+BaseClass=CDialog
+Filter=D
+VirtualFilter=dWC
+LastObject=CPatchDensityDlg
+
+[DLG:IDD_DIALOG_TEXTURELAYOUT]
+Type=1
+Class=CTextureLayout
+ControlCount=7
+Control1=IDOK,button,1342242817
+Control2=IDCANCEL,button,1342242816
+Control3=IDC_STATIC,static,1342308352
+Control4=IDC_STATIC,static,1342308352
+Control5=IDC_EDIT_X,edit,1350631552
+Control6=IDC_STATIC,static,1342308352
+Control7=IDC_EDIT_Y,edit,1350631552
+
+[CLS:CTextureLayout]
+Type=0
+HeaderFile=TextureLayout.h
+ImplementationFile=TextureLayout.cpp
+BaseClass=CDialog
+Filter=D
+VirtualFilter=dWC
+LastObject=CTextureLayout
+
+[DLG:IDD_DIALOG_CAP]
+Type=1
+Class=CCapDialog
+ControlCount=10
+Control1=IDOK,button,1342242817
+Control2=IDCANCEL,button,1342242816
+Control3=IDC_RADIO_CAP,button,1342308361
+Control4=IDC_RADIO_CAP2,button,1342177289
+Control5=IDC_RADIO_CAP3,button,1342177289
+Control6=IDC_RADIO_CAP4,button,1342177289
+Control7=IDC_STATIC,static,1342183438
+Control8=IDC_STATIC,static,1342183438
+Control9=IDC_STATIC,static,1342183438
+Control10=IDC_STATIC,static,1342183438
+
+[CLS:CCapDialog]
+Type=0
+HeaderFile=CapDialog.h
+ImplementationFile=CapDialog.cpp
+BaseClass=CDialog
+Filter=D
+VirtualFilter=dWC
+LastObject=CCapDialog
+
+[DLG:IDD_DIALOG_THICKEN]
+Type=1
+Class=CDialogThick
+ControlCount=6
+Control1=IDOK,button,1342242817
+Control2=IDCANCEL,button,1342242816
+Control3=IDC_STATIC,static,1342308352
+Control4=IDC_EDIT_AMOUNT,edit,1350631552
+Control5=IDC_STATIC,static,1342308352
+Control6=IDC_CHECK_SEAMS,button,1342242819
+
+[CLS:CDialogThick]
+Type=0
+HeaderFile=DialogThick.h
+ImplementationFile=DialogThick.cpp
+BaseClass=CDialog
+Filter=D
+LastObject=IDC_EDIT_AMOUNT
+VirtualFilter=dWC
+
+[MNU:IDR_POPUP_ENTITY]
+Type=1
+Class=?
+Command1=ID_VIEW_ENTITIESAS_BOUNDINGBOX
+Command2=ID_VIEW_ENTITIESAS_WIREFRAME
+Command3=ID_VIEW_ENTITIESAS_SELECTEDWIREFRAME
+Command4=ID_VIEW_ENTITIESAS_SELECTEDSKINNED
+Command5=ID_VIEW_ENTITIESAS_SKINNED
+Command6=ID_VIEW_ENTITIESAS_SKINNEDANDBOXED
+CommandCount=6
+
+[CLS:CShaderEdit]
+Type=0
+HeaderFile=ShaderEdit.h
+ImplementationFile=ShaderEdit.cpp
+BaseClass=CFrameWnd
+Filter=T
+VirtualFilter=fWC
+
+[CLS:CShaderFrame]
+Type=0
+HeaderFile=ShaderFrame.h
+ImplementationFile=ShaderFrame.cpp
+BaseClass=CFrameWnd
+Filter=T
+VirtualFilter=fWC
+LastObject=IDC_COMBO_TYPE
+
+[MNU:"IDR_SHADERFRAME"]
+Type=1
+Class=?
+Command1=ID_FILE_NEW
+Command2=ID_FILE_OPEN
+Command3=ID_FILE_PRINT_SETUP
+Command4=ID_FILE_MRU_FILE1
+Command5=ID_APP_EXIT
+Command6=ID_VIEW_TOOLBAR
+Command7=ID_VIEW_STATUS_BAR
+Command8=ID_APP_ABOUT
+CommandCount=8
+
+[MNU:"IDR_SHADERTYPE"]
+Type=1
+Class=?
+Command1=ID_FILE_NEW
+Command2=ID_FILE_OPEN
+Command3=ID_FILE_CLOSE
+Command4=ID_FILE_SAVE
+Command5=ID_FILE_SAVE_AS
+Command6=ID_FILE_PRINT
+Command7=ID_FILE_PRINT_SETUP
+Command8=ID_FILE_MRU_FILE1
+Command9=ID_APP_EXIT
+Command10=ID_EDIT_UNDO
+Command11=ID_EDIT_CUT
+Command12=ID_EDIT_COPY
+Command13=ID_EDIT_PASTE
+Command14=ID_EDIT_CLEAR
+Command15=ID_EDIT_FIND
+Command16=ID_EDIT_REPEAT
+Command17=ID_EDIT_REPLACE
+Command18=ID_EDIT_SELECT_ALL
+Command19=ID_VIEW_TOOLBAR
+Command20=ID_VIEW_STATUS_BAR
+Command21=ID_WINDOW_CASCADE
+Command22=ID_WINDOW_TILE_HORZ
+Command23=ID_WINDOW_ARRANGE
+Command24=ID_APP_ABOUT
+CommandCount=24
+
+[TB:IDR_SHADERFRAME]
+Type=1
+Class=?
+Command1=ID_FILE_OPEN
+Command2=ID_FILE_SAVE
+Command3=ID_EDIT_CUT
+Command4=ID_EDIT_COPY
+Command5=ID_EDIT_PASTE
+CommandCount=5
+
+[MNU:IDR_SHADERFRAME]
+Type=1
+Class=?
+Command1=ID_FILE_NEW
+Command2=ID_FILE_OPEN
+Command3=ID_FILE_SAVE
+Command4=ID_FILE_SAVE_AS
+Command5=ID_FILE_CLOSE
+Command6=ID_EDIT_UNDO
+Command7=ID_EDIT_CUT
+Command8=ID_EDIT_COPY
+Command9=ID_EDIT_PASTE
+Command10=ID_EDIT_CLEAR
+Command11=ID_EDIT_FIND
+Command12=ID_EDIT_REPEAT
+Command13=ID_EDIT_REPLACE
+Command14=ID_EDIT_SELECT_ALL
+CommandCount=14
+
+[DLG:IDD_DIALOG_PATCH]
+Type=1
+Class=CPatchDialog
+ControlCount=41
+Control1=IDC_COMBO_ROW,combobox,1344340227
+Control2=IDC_COMBO_COL,combobox,1344340227
+Control3=IDC_EDIT_X,edit,1350631552
+Control4=IDC_EDIT_Y,edit,1350631552
+Control5=IDC_EDIT_Z,edit,1350631552
+Control6=IDC_EDIT_S,edit,1350631552
+Control7=IDC_EDIT_T,edit,1350631552
+Control8=IDC_COMBO_TYPE,combobox,1344340227
+Control9=IDC_EDIT_NAME,edit,1350631552
+Control10=IDC_HSHIFT,edit,1350631552
+Control11=IDC_SPIN_HSHIFT,msctls_updown32,1342177332
+Control12=IDC_VSHIFT,edit,1350631552
+Control13=IDC_SPIN_VSHIFT,msctls_updown32,1342177332
+Control14=IDC_HSCALE,edit,1350631552
+Control15=IDC_SPIN_HSCALE,msctls_updown32,1342177332
+Control16=IDC_VSCALE,edit,1350631552
+Control17=IDC_SPIN_VSCALE,msctls_updown32,1342177332
+Control18=IDC_ROTATE,edit,1350631552
+Control19=IDC_SPIN_ROTATE,msctls_updown32,1342177332
+Control20=IDC_BTN_PATCHDETAILS,button,1342242816
+Control21=IDC_BTN_PATCHRESET,button,1342242816
+Control22=IDC_BTN_PATCHNATURAL,button,1342242816
+Control23=IDC_BTN_PATCHFIT,button,1342242816
+Control24=ID_APPLY,button,1342242816
+Control25=IDOK,button,1342242817
+Control26=IDC_STATIC,static,1342308352
+Control27=IDC_STATIC,static,1342308352
+Control28=IDC_STATIC,static,1342308352
+Control29=IDC_STATIC,static,1342308352
+Control30=IDC_STATIC,static,1342308352
+Control31=IDC_STATIC,static,1342308352
+Control32=IDC_STATIC,static,1342308352
+Control33=IDC_STATIC,static,1342308352
+Control34=IDC_STATIC,static,1342308352
+Control35=IDC_STATIC,static,1342308352
+Control36=IDC_STATIC,static,1342308352
+Control37=IDC_STATIC,static,1342308352
+Control38=IDC_STATIC,static,1342308352
+Control39=IDC_STATIC,button,1342177287
+Control40=IDC_STATIC,button,1342177287
+Control41=IDC_STATIC,static,1342308352
+
+[CLS:CPatchDialog]
+Type=0
+HeaderFile=PatchDialog.h
+ImplementationFile=PatchDialog.cpp
+BaseClass=CDialog
+Filter=D
+VirtualFilter=dWC
+LastObject=IDC_HSHIFT
+
+[CLS:CWaveOpen]
+Type=0
+HeaderFile=WaveOpen.h
+ImplementationFile=WaveOpen.cpp
+BaseClass=CFileDialog
+Filter=D
+LastObject=ID_VIEW_OPENGLLIGHTING
+VirtualFilter=dWC
+
+[DLG:IDD_PLAYWAVE]
+Type=1
+Class=?
+ControlCount=1
+Control1=IDC_BTN_PLAY,button,1342242816
+
+[DLG:IDD_TEXLIST]
+Type=1
+Class=?
+ControlCount=3
+Control1=IDOK,button,1342242817
+Control2=IDCANCEL,button,1342242816
+Control3=IDC_LIST_TEXTURES,listbox,1352728835
+
+[DLG:IDD_DIALOG2]
+Type=1
+Class=?
+ControlCount=2
+Control1=IDOK,button,1342242817
+Control2=IDCANCEL,button,1342242816
+
+[DLG:IDD_GROUPBAR]
+Type=1
+Class=CGroupBar
+ControlCount=5
+Control1=IDC_COMBO_GROUPS,combobox,1344340226
+Control2=IDC_STATIC,static,1342308352
+Control3=IDC_BTN_ADDGROUP,button,1342242816
+Control4=IDC_BTN_REMOVEGROUP,button,1342242816
+Control5=IDC_BTN_LISTGROUPS,button,1342242816
+
+[CLS:CGroupBar]
+Type=0
+HeaderFile=GroupBar.h
+ImplementationFile=GroupBar.cpp
+BaseClass=CDialog
+Filter=D
+VirtualFilter=dWC
+LastObject=ID_TEXTURES_FLUSH_UNUSED
+
+[DLG:IDD_DLG_GROUP]
+Type=1
+Class=CGroupDlg
+ControlCount=4
+Control1=IDC_TREE_GROUP,SysTreeView32,1350631439
+Control2=IDC_BTN_ADD,button,1342242816
+Control3=IDC_BTN_DEL,button,1342242816
+Control4=IDC_BTN_EDIT,button,1342242816
+
+[CLS:CGroupDlg]
+Type=0
+HeaderFile=GroupDlg.h
+ImplementationFile=GroupDlg.cpp
+BaseClass=CDialog
+Filter=D
+LastObject=IDC_TREE_GROUP
+VirtualFilter=dWC
+
+[MNU:IDR_POPUP_GROUP]
+Type=1
+Class=?
+Command1=ID_VIEW_XY
+Command2=ID_VIEW_SIDE
+Command3=ID_VIEW_FRONT
+CommandCount=3
+
+[DLG:IDD_NEWNAME]
+Type=1
+Class=CNameDlg
+ControlCount=4
+Control1=IDC_EDIT_NAME,edit,1350631552
+Control2=IDOK,button,1342242817
+Control3=IDCANCEL,button,1342242816
+Control4=IDC_STATIC,static,1342308352
+
+[CLS:CNameDlg]
+Type=0
+HeaderFile=NameDlg.h
+ImplementationFile=NameDlg.cpp
+BaseClass=CDialog
+Filter=D
+LastObject=CNameDlg
+VirtualFilter=dWC
+
diff --git a/q3radiant/Radiant.cpp b/q3radiant/Radiant.cpp
new file mode 100755
index 0000000..215a7a8
--- /dev/null
+++ b/q3radiant/Radiant.cpp
@@ -0,0 +1,261 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// Radiant.cpp : Defines the class behaviors for the application.
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+
+#include "MainFrm.h"
+#include "ChildFrm.h"
+#include "RadiantDoc.h"
+#include "RadiantView.h"
+#include "PrefsDlg.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CRadiantApp
+
+BEGIN_MESSAGE_MAP(CRadiantApp, CWinApp)
+ //{{AFX_MSG_MAP(CRadiantApp)
+ ON_COMMAND(ID_HELP, OnHelp)
+ //}}AFX_MSG_MAP
+ // Standard file based document commands
+ ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
+ ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
+ // Standard print setup command
+ ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup)
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CRadiantApp construction
+
+CRadiantApp::CRadiantApp()
+{
+ // TODO: add construction code here,
+ // Place all significant initialization in InitInstance
+}
+
+/////////////////////////////////////////////////////////////////////////////
+// The one and only CRadiantApp object
+
+CRadiantApp theApp;
+
+/////////////////////////////////////////////////////////////////////////////
+// CRadiantApp initialization
+
+HINSTANCE g_hOpenGL32 = NULL;
+HINSTANCE g_hOpenGL = NULL;
+bool g_bBuildList = false;
+
+BOOL CRadiantApp::InitInstance()
+{
+ //g_hOpenGL32 = ::LoadLibrary("opengl32.dll");
+ // AfxEnableControlContainer();
+
+ // Standard initialization
+ // If you are not using these features and wish to reduce the size
+ // of your final executable, you should remove from the following
+ // the specific initialization routines you do not need.
+ //AfxEnableMemoryTracking(FALSE);
+
+ // VC7 says deprecated and no longer necessary
+#if 0
+
+#ifdef _AFXDLL
+ Enable3dControls(); // Call this when using MFC in a shared DLL
+#else
+ Enable3dControlsStatic(); // Call this when linking to MFC statically
+#endif
+
+#endif
+
+ // If there's a .INI file in the directory use it instead of registry
+ char RadiantPath[_MAX_PATH];
+ GetModuleFileName( NULL, RadiantPath, _MAX_PATH );
+
+ // search for exe
+ CFileFind Finder;
+ Finder.FindFile( RadiantPath );
+ Finder.FindNextFile();
+ // extract root
+ CString Root = Finder.GetRoot();
+ // build root\*.ini
+ CString IniPath = Root + "\\REGISTRY.INI";
+ // search for ini file
+ Finder.FindNextFile();
+ if (Finder.FindFile( IniPath ))
+ {
+ Finder.FindNextFile();
+ // use the .ini file instead of the registry
+ free((void*)m_pszProfileName);
+ m_pszProfileName=_tcsdup(_T(Finder.GetFilePath()));
+ // look for the registry key for void* buffers storage ( these can't go into .INI files )
+ int i=0;
+ CString key;
+ HKEY hkResult;
+ DWORD dwDisp;
+ DWORD type;
+ char iBuf[3];
+ do
+ {
+ sprintf( iBuf, "%d", i );
+ key = "Software\\Q3Radiant\\IniPrefs" + CString(iBuf);
+ // does this key exists ?
+ if ( RegOpenKeyEx( HKEY_CURRENT_USER, key, 0, KEY_ALL_ACCESS, &hkResult ) != ERROR_SUCCESS )
+ {
+ // this key doesn't exist, so it's the one we'll use
+ strcpy( g_qeglobals.use_ini_registry, key.GetBuffer(0) );
+ RegCreateKeyEx( HKEY_CURRENT_USER, key, 0, NULL,
+ REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hkResult, &dwDisp );
+ RegSetValueEx( hkResult, "RadiantName", 0, REG_SZ, reinterpret_cast<CONST BYTE *>(RadiantPath), strlen( RadiantPath )+1 );
+ RegCloseKey( hkResult );
+ break;
+ }
+ else
+ {
+ char RadiantAux[ _MAX_PATH ];
+ unsigned long size = _MAX_PATH;
+ // the key exists, is it the one we are looking for ?
+ RegQueryValueEx( hkResult, "RadiantName", 0, &type, reinterpret_cast<BYTE *>(RadiantAux), &size );
+ RegCloseKey( hkResult );
+ if ( !strcmp( RadiantAux, RadiantPath ) )
+ {
+ // got it !
+ strcpy( g_qeglobals.use_ini_registry, key.GetBuffer(0) );
+ break;
+ }
+ }
+ i++;
+ } while (1);
+ g_qeglobals.use_ini = true;
+ }
+ else
+ {
+ // Change the registry key under which our settings are stored.
+ // You should modify this string to be something appropriate
+ // such as the name of your company or organization.
+ SetRegistryKey("Q3Radiant");
+ g_qeglobals.use_ini = false;
+ }
+
+ LoadStdProfileSettings(); // Load standard INI file options (including MRU)
+
+
+ // Register the application's document templates. Document templates
+ // serve as the connection between documents, frame windows and views.
+
+// CMultiDocTemplate* pDocTemplate;
+// pDocTemplate = new CMultiDocTemplate(
+// IDR_RADIANTYPE,
+// RUNTIME_CLASS(CRadiantDoc),
+// RUNTIME_CLASS(CMainFrame), // custom MDI child frame
+// RUNTIME_CLASS(CRadiantView));
+// AddDocTemplate(pDocTemplate);
+
+ // create main MDI Frame window
+
+ g_PrefsDlg.LoadPrefs();
+
+ int nMenu = IDR_MENU1;
+
+ CString strOpenGL = (g_PrefsDlg.m_bSGIOpenGL) ? "opengl.dll" : "opengl32.dll";
+ CString strGLU = (g_PrefsDlg.m_bSGIOpenGL) ? "glu.dll" : "glu32.dll";
+
+ if (!QGL_Init(strOpenGL, strGLU))
+ {
+ g_PrefsDlg.m_bSGIOpenGL ^= 1;
+ strOpenGL = (g_PrefsDlg.m_bSGIOpenGL) ? "opengl.dll" : "opengl32.dll";
+ strGLU = (g_PrefsDlg.m_bSGIOpenGL) ? "glu.dll" : "glu32.dll";
+ if (!QGL_Init(strOpenGL, strGLU))
+ {
+ AfxMessageBox("Failed to load OpenGL libraries. \"OPENGL32.DLL\" and \"OPENGL.DLL\" were tried");
+ return FALSE;
+ }
+ g_PrefsDlg.SavePrefs();
+ }
+
+ CString strTemp = m_lpCmdLine;
+ strTemp.MakeLower();
+ if (strTemp.Find("builddefs") >= 0)
+ g_bBuildList = true;
+
+ CMainFrame* pMainFrame = new CMainFrame;
+ if (!pMainFrame->LoadFrame(nMenu))
+ return FALSE;
+
+ if (pMainFrame->m_hAccelTable)
+ ::DestroyAcceleratorTable(pMainFrame->m_hAccelTable);
+
+ pMainFrame->LoadAccelTable(MAKEINTRESOURCE(IDR_MINIACCEL));
+
+ m_pMainWnd = pMainFrame;
+
+ // Parse command line for standard shell commands, DDE, file open
+ CCommandLineInfo cmdInfo;
+ ParseCommandLine(cmdInfo);
+
+ // Dispatch commands specified on the command line
+ //if (!ProcessShellCommand(cmdInfo))
+ // return FALSE;
+
+ // The main window has been initialized, so show and update it.
+ pMainFrame->ShowWindow(m_nCmdShow);
+ pMainFrame->UpdateWindow();
+
+ free((void*)m_pszHelpFilePath);
+ CString strHelp = g_strAppPath;
+ AddSlash(strHelp);
+ strHelp += "Q3RManual.chm";
+ m_pszHelpFilePath= _tcsdup(strHelp);
+
+
+ return TRUE;
+}
+
+/////////////////////////////////////////////////////////////////////////////
+// CRadiantApp commands
+
+int CRadiantApp::ExitInstance()
+{
+ // TODO: Add your specialized code here and/or call the base class
+ //::FreeLibrary(g_hOpenGL32);
+ QGL_Shutdown();
+ return CWinApp::ExitInstance();
+}
+
+BOOL CRadiantApp::OnIdle(LONG lCount)
+{
+ if (g_pParentWnd)
+ g_pParentWnd->RoutineProcessing();
+ return CWinApp::OnIdle(lCount);
+}
+
+void CRadiantApp::OnHelp()
+{
+ ShellExecute(m_pMainWnd->GetSafeHwnd(), "open", m_pszHelpFilePath, NULL, NULL, SW_SHOW);
+}
diff --git a/q3radiant/Radiant.h b/q3radiant/Radiant.h
new file mode 100755
index 0000000..e910543
--- /dev/null
+++ b/q3radiant/Radiant.h
@@ -0,0 +1,71 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// Radiant.h : main header file for the RADIANT application
+//
+
+#if !defined(AFX_RADIANT_H__330BBF06_731C_11D1_B539_00AA00A410FC__INCLUDED_)
+#define AFX_RADIANT_H__330BBF06_731C_11D1_B539_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+
+#ifndef __AFXWIN_H__
+ #error include 'stdafx.h' before including this file for PCH
+#endif
+
+#include "resource.h" // main symbols
+
+/////////////////////////////////////////////////////////////////////////////
+// CRadiantApp:
+// See Radiant.cpp for the implementation of this class
+//
+
+class CRadiantApp : public CWinApp
+{
+public:
+ CRadiantApp();
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CRadiantApp)
+ public:
+ virtual BOOL InitInstance();
+ virtual int ExitInstance();
+ virtual BOOL OnIdle(LONG lCount);
+ //}}AFX_VIRTUAL
+
+// Implementation
+
+ //{{AFX_MSG(CRadiantApp)
+ afx_msg void OnHelp();
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+
+/////////////////////////////////////////////////////////////////////////////
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_RADIANT_H__330BBF06_731C_11D1_B539_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/Radiant.rc b/q3radiant/Radiant.rc
new file mode 100755
index 0000000..dcab967
--- /dev/null
+++ b/q3radiant/Radiant.rc
@@ -0,0 +1,2838 @@
+//Microsoft Developer Studio generated resource script.
+//
+#include "resource.h"
+
+#define APSTUDIO_READONLY_SYMBOLS
+/////////////////////////////////////////////////////////////////////////////
+//
+// Generated from the TEXTINCLUDE 2 resource.
+//
+#include "afxres.h"
+
+/////////////////////////////////////////////////////////////////////////////
+#undef APSTUDIO_READONLY_SYMBOLS
+
+/////////////////////////////////////////////////////////////////////////////
+// English (U.S.) resources
+
+#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
+#ifdef _WIN32
+LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
+#pragma code_page(1252)
+#endif //_WIN32
+
+#ifdef APSTUDIO_INVOKED
+/////////////////////////////////////////////////////////////////////////////
+//
+// TEXTINCLUDE
+//
+
+1 TEXTINCLUDE DISCARDABLE
+BEGIN
+ "resource.h\0"
+END
+
+2 TEXTINCLUDE DISCARDABLE
+BEGIN
+ "#include ""afxres.h""\r\n"
+ "\0"
+END
+
+3 TEXTINCLUDE DISCARDABLE
+BEGIN
+ "#define _AFX_NO_SPLITTER_RESOURCES\r\n"
+ "#define _AFX_NO_OLE_RESOURCES\r\n"
+ "#define _AFX_NO_TRACKER_RESOURCES\r\n"
+ "#define _AFX_NO_PROPERTY_RESOURCES\r\n"
+ "\r\n"
+ "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n"
+ "#ifdef _WIN32\r\n"
+ "LANGUAGE 9, 1\r\n"
+ "#pragma code_page(1252)\r\n"
+ "#endif\r\n"
+ "#include ""res\\Radiant.rc2"" // non-Microsoft Visual C++ edited resources\r\n"
+ "#include ""afxres.rc"" // Standard components\r\n"
+ "#include ""afxprint.rc"" // printing/print preview resources\r\n"
+ "#endif\0"
+END
+
+1 TEXTINCLUDE DISCARDABLE
+BEGIN
+ "resource.h\0"
+END
+
+2 TEXTINCLUDE DISCARDABLE
+BEGIN
+ "#include ""afxres.h""\r\n"
+ "\0"
+END
+
+3 TEXTINCLUDE DISCARDABLE
+BEGIN
+ "\r\n"
+ "\0"
+END
+
+#endif // APSTUDIO_INVOKED
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Icon
+//
+
+// Icon with lowest ID value placed first to ensure application icon
+// remains consistent on all systems.
+IDI_ICON1 ICON DISCARDABLE "res\\icon2.ico"
+IDR_MAINFRAME ICON DISCARDABLE "res\\Radiant.ico"
+IDR_RADIANTYPE ICON DISCARDABLE "res\\RadiantDoc.ico"
+IDR_SHADERFRAME ICON DISCARDABLE "RES\\shaderframe.ico"
+IDR_SHADERTYPE ICON DISCARDABLE "RES\\shaderdoc.ico"
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Bitmap
+//
+
+IDR_SHADERFRAME BITMAP MOVEABLE PURE "res\\Toolbar.bmp"
+IDR_TOOLBAR1 BITMAP DISCARDABLE "res\\toolbar1.bmp"
+IDB_BITMAP1 BITMAP DISCARDABLE "res\\q.bmp"
+IDB_VIEWDEFAULT BITMAP DISCARDABLE "res\\bitmap2.bmp"
+IDB_VIEWQE4 BITMAP DISCARDABLE "res\\viewdefa.bmp"
+IDB_VIEW4WAY BITMAP DISCARDABLE "res\\viewoppo.bmp"
+IDB_VIEWDEFAULT_Z BITMAP DISCARDABLE "res\\bmp00001.bmp"
+IDB_3DFX BITMAP DISCARDABLE "res\\logo_sm3dfx.bmp"
+IDR_TOOLBAR_SCALELOCK BITMAP DISCARDABLE "res\\toolbar2.bmp"
+IDR_TOOLBAR_ADVANCED BITMAP DISCARDABLE "res\\bmp00002.bmp"
+IDB_IENDCAP BITMAP DISCARDABLE "res\\iendcap.bmp"
+IDB_ENDCAP BITMAP DISCARDABLE "res\\endcap.bmp"
+IDB_BEVEL BITMAP DISCARDABLE "res\\bevel.bmp"
+IDB_IBEVEL BITMAP DISCARDABLE "res\\ibevel.bmp"
+IDB_BITMAP_GROUPS BITMAP DISCARDABLE "res\\bmp00003.bmp"
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Toolbar
+//
+
+IDR_SHADERFRAME TOOLBAR DISCARDABLE 16, 15
+BEGIN
+ BUTTON ID_FILE_OPEN
+ BUTTON ID_FILE_SAVE
+ SEPARATOR
+ BUTTON ID_EDIT_CUT
+ BUTTON ID_EDIT_COPY
+ BUTTON ID_EDIT_PASTE
+END
+
+IDR_TOOLBAR1 TOOLBAR DISCARDABLE 16, 15
+BEGIN
+ BUTTON ID_FILE_OPEN
+ BUTTON ID_FILE_SAVE
+ SEPARATOR
+ BUTTON ID_BRUSH_FLIPX
+ BUTTON ID_BRUSH_ROTATEX
+ BUTTON ID_BRUSH_FLIPY
+ BUTTON ID_BRUSH_ROTATEY
+ BUTTON ID_BRUSH_FLIPZ
+ BUTTON ID_BRUSH_ROTATEZ
+ SEPARATOR
+ BUTTON ID_POPUP_SELECTION
+ SEPARATOR
+ BUTTON ID_SELECTION_CSGSUBTRACT
+ BUTTON ID_SELECTION_MAKEHOLLOW
+ SEPARATOR
+ BUTTON ID_VIEW_CHANGE
+ SEPARATOR
+ BUTTON ID_TEXTURES_POPUP
+ SEPARATOR
+ BUTTON ID_VIEW_CAMERATOGGLE
+ BUTTON ID_VIEW_CAMERAUPDATE
+ BUTTON ID_VIEW_CUBICCLIPPING
+ SEPARATOR
+ BUTTON ID_VIEW_ENTITY
+ SEPARATOR
+ BUTTON ID_VIEW_CLIPPER
+ SEPARATOR
+ BUTTON ID_SELECT_MOUSEROTATE
+ SEPARATOR
+ BUTTON ID_SELECT_MOUSESCALE
+ BUTTON ID_SCALELOCKX
+ BUTTON ID_SCALELOCKY
+ BUTTON ID_SCALELOCKZ
+END
+
+IDR_TOOLBAR_SCALELOCK TOOLBAR DISCARDABLE 16, 15
+BEGIN
+ BUTTON ID_SCALELOCKX
+ BUTTON ID_SCALELOCKY
+ BUTTON ID_SCALELOCKZ
+END
+
+IDR_TOOLBAR_ADVANCED TOOLBAR DISCARDABLE 16, 15
+BEGIN
+ BUTTON ID_FILE_OPEN
+ BUTTON ID_FILE_SAVE
+ SEPARATOR
+ BUTTON ID_BRUSH_FLIPX
+ BUTTON ID_BRUSH_ROTATEX
+ BUTTON ID_BRUSH_FLIPY
+ BUTTON ID_BRUSH_ROTATEY
+ BUTTON ID_BRUSH_FLIPZ
+ BUTTON ID_BRUSH_ROTATEZ
+ SEPARATOR
+ BUTTON ID_SELECTION_SELECTCOMPLETETALL
+ BUTTON ID_SELECTION_SELECTTOUCHING
+ BUTTON ID_SELECTION_SELECTPARTIALTALL
+ BUTTON ID_SELECTION_SELECTINSIDE
+ SEPARATOR
+ BUTTON ID_SELECTION_CSGSUBTRACT
+ BUTTON ID_SELECTION_CSGMERGE
+ BUTTON ID_SELECTION_MAKEHOLLOW
+ BUTTON ID_VIEW_CLIPPER
+ SEPARATOR
+ BUTTON ID_VIEW_CHANGE
+ BUTTON ID_TEXTURES_POPUP
+ BUTTON ID_VIEW_CUBICCLIPPING
+ SEPARATOR
+ BUTTON ID_SELECT_MOUSEROTATE
+ SEPARATOR
+ BUTTON ID_SELECT_MOUSESCALE
+ SEPARATOR
+ BUTTON ID_SCALELOCKX
+ BUTTON ID_SCALELOCKY
+ BUTTON ID_SCALELOCKZ
+ SEPARATOR
+ BUTTON ID_DONTSELECTCURVE
+ BUTTON ID_PATCH_SHOWBOUNDINGBOX
+ BUTTON ID_PATCH_WIREFRAME
+ BUTTON ID_PATCH_BEND
+ BUTTON ID_PATCH_INSDEL
+ BUTTON ID_CURVE_CAP
+ BUTTON ID_PATCH_WELD
+ BUTTON ID_PATCH_DRILLDOWN
+ SEPARATOR
+ BUTTON ID_SHOW_ENTITIES
+ SEPARATOR
+ BUTTON ID_SPLINES_POPUP
+END
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Menu
+//
+
+IDR_SHADERFRAME MENU DISCARDABLE
+BEGIN
+ POPUP "&File"
+ BEGIN
+ MENUITEM "&New\tCtrl+N", ID_FILE_NEW
+ MENUITEM "&Open...\tCtrl+O", ID_FILE_OPEN
+ MENUITEM "&Save\tCtrl+S", ID_FILE_SAVE
+ MENUITEM "Save &As...", ID_FILE_SAVE_AS
+ MENUITEM SEPARATOR
+ MENUITEM "Close", ID_FILE_CLOSE
+ END
+ POPUP "&Edit"
+ BEGIN
+ MENUITEM "&Undo\tCtrl+Z", ID_EDIT_UNDO
+ MENUITEM SEPARATOR
+ MENUITEM "Cu&t\tCtrl+X", ID_EDIT_CUT
+ MENUITEM "&Copy\tCtrl+C", ID_EDIT_COPY
+ MENUITEM "&Paste\tCtrl+V", ID_EDIT_PASTE
+ MENUITEM "Delete\tDel", ID_EDIT_CLEAR
+ MENUITEM SEPARATOR
+ MENUITEM "&Find...", ID_EDIT_FIND
+ MENUITEM "Find &Next\tF3", ID_EDIT_REPEAT
+ MENUITEM "&Replace...", ID_EDIT_REPLACE
+ MENUITEM SEPARATOR
+ MENUITEM "Select &All", ID_EDIT_SELECT_ALL
+ END
+END
+
+IDR_MAINFRAME MENU PRELOAD DISCARDABLE
+BEGIN
+ POPUP "&File"
+ BEGIN
+ MENUITEM "&New\tCtrl+N", ID_FILE_NEW
+ MENUITEM "&Open...\tCtrl+O", ID_FILE_OPEN
+ MENUITEM SEPARATOR
+ MENUITEM "P&rint Setup...", ID_FILE_PRINT_SETUP
+ MENUITEM SEPARATOR
+ MENUITEM "Recent File", ID_FILE_MRU_FILE1, GRAYED
+ MENUITEM SEPARATOR
+ MENUITEM "E&xit", ID_APP_EXIT
+ END
+ POPUP "&View"
+ BEGIN
+ MENUITEM "&Toolbar", ID_VIEW_TOOLBAR
+ MENUITEM "&Status Bar", ID_VIEW_STATUS_BAR
+ END
+ POPUP "&Help"
+ BEGIN
+ MENUITEM "&About Radiant...", ID_APP_ABOUT
+ END
+END
+
+IDR_RADIANTYPE MENU PRELOAD DISCARDABLE
+BEGIN
+ POPUP "&File"
+ BEGIN
+ MENUITEM "&New\tCtrl+N", ID_FILE_NEW
+ MENUITEM "&Open...\tCtrl+O", ID_FILE_OPEN
+ MENUITEM "&Close", ID_FILE_CLOSE
+ MENUITEM "&Save\tCtrl+S", ID_FILE_SAVE
+ MENUITEM "Save &As...", ID_FILE_SAVE_AS
+ MENUITEM SEPARATOR
+ MENUITEM "&Print...\tCtrl+P", ID_FILE_PRINT
+ MENUITEM "Print Pre&view", ID_FILE_PRINT_PREVIEW
+ MENUITEM "P&rint Setup...", ID_FILE_PRINT_SETUP
+ MENUITEM SEPARATOR
+ MENUITEM "Recent File", ID_FILE_MRU_FILE1, GRAYED
+ MENUITEM SEPARATOR
+ MENUITEM "E&xit", ID_APP_EXIT
+ END
+ POPUP "&Edit"
+ BEGIN
+ MENUITEM "&Undo\tCtrl+Z", ID_EDIT_UNDO
+ MENUITEM SEPARATOR
+ MENUITEM "Cu&t\tCtrl+X", ID_EDIT_CUT
+ MENUITEM "&Copy\tCtrl+C", ID_EDIT_COPY
+ MENUITEM "&Paste\tCtrl+V", ID_EDIT_PASTE
+ END
+ POPUP "&View"
+ BEGIN
+ MENUITEM "&Toolbar", ID_VIEW_TOOLBAR
+ MENUITEM "&Status Bar", ID_VIEW_STATUS_BAR
+ END
+ POPUP "&Window"
+ BEGIN
+ MENUITEM "&New Window", ID_WINDOW_NEW
+ MENUITEM "&Cascade", ID_WINDOW_CASCADE
+ MENUITEM "&Tile", ID_WINDOW_TILE_HORZ
+ MENUITEM "&Arrange Icons", ID_WINDOW_ARRANGE
+ END
+ POPUP "&Help"
+ BEGIN
+ MENUITEM "&About Radiant...", ID_APP_ABOUT
+ END
+END
+
+IDR_MENU_QUAKE3 MENU DISCARDABLE
+BEGIN
+ POPUP "&File"
+ BEGIN
+ MENUITEM "&New map", ID_FILE_NEW
+ MENUITEM SEPARATOR
+ MENUITEM "&Open...", ID_FILE_OPEN
+ MENUITEM "&Load...", ID_FILE_IMPORTMAP
+ MENUITEM "&Save", ID_FILE_SAVE
+ MENUITEM "Save &as...", ID_FILE_SAVEAS
+ MENUITEM "Save s&elected...", ID_FILE_EXPORTMAP
+ MENUITEM SEPARATOR
+ MENUITEM "Save re&gion...", ID_FILE_SAVEREGION
+ MENUITEM SEPARATOR
+ MENUITEM "New p&roject...", ID_FILE_NEWPROJECT
+ MENUITEM "Load &project...", ID_FILE_LOADPROJECT
+ MENUITEM "Pro&ject settings...", ID_FILE_PROJECTSETTINGS
+ MENUITEM SEPARATOR
+ MENUITEM "&Pointfile...", ID_FILE_POINTFILE
+ MENUITEM SEPARATOR
+ MENUITEM "E&xit", ID_FILE_EXIT
+ END
+ POPUP "&Edit"
+ BEGIN
+ MENUITEM "&Undo\tCtrl-Z", ID_EDIT_UNDO
+ MENUITEM "&Redo\tShift-Ctrl-Z", ID_EDIT_REDO
+ MENUITEM SEPARATOR
+ MENUITEM "&Copy\tCtrl-C", ID_EDIT_COPYBRUSH
+ MENUITEM "&Paste\tCtrl-V", ID_EDIT_PASTEBRUSH
+ MENUITEM "&Delete\tBackspace", ID_SELECTION_DELETE
+ MENUITEM SEPARATOR
+ MENUITEM "Map Info...", ID_EDIT_MAPINFO
+ MENUITEM "Entity Info...", ID_EDIT_ENTITYINFO
+ MENUITEM SEPARATOR
+ MENUITEM "Brush Scripts...", ID_BRUSH_SCRIPTS
+ MENUITEM SEPARATOR
+ MENUITEM "Load Pre&fab...", ID_EDIT_LOADPREFAB
+ MENUITEM "Save Selection as Prefab...", ID_EDIT_SAVEPREFAB
+ MENUITEM SEPARATOR
+ MENUITEM "Preferences...", ID_PREFS
+ END
+ POPUP "&View"
+ BEGIN
+ POPUP "Toggle"
+ BEGIN
+ MENUITEM "Camera View", ID_TOGGLECAMERA
+ MENUITEM "Console View", ID_TOGGLECONSOLE
+ MENUITEM "Entity View", ID_VIEW_ENTITY
+ MENUITEM "Groups View", ID_VIEW_GROUPS
+ MENUITEM "XY (Top)", ID_TOGGLEVIEW
+ MENUITEM "YZ (Side)", ID_TOGGLEVIEW_YZ
+ MENUITEM "XZ (Front)", ID_TOGGLEVIEW_XZ
+ MENUITEM "Z View", ID_TOGGLEZ
+ END
+ MENUITEM SEPARATOR
+ MENUITEM "&Center\tEnd", ID_VIEW_CENTER
+ MENUITEM "&Up Floor\tPage Up", ID_VIEW_UPFLOOR
+ MENUITEM "&Down Floor\tPage Down", ID_VIEW_DOWNFLOOR
+ MENUITEM SEPARATOR
+ MENUITEM "&Next (XY, YZ, XY)\tCtrl-TAB", ID_VIEW_NEXTVIEW
+ POPUP "Layout"
+ BEGIN
+ MENUITEM "XY (Top)", ID_VIEW_XY
+ MENUITEM "YZ", ID_VIEW_SIDE
+ MENUITEM "XZ", ID_VIEW_FRONT
+ END
+ POPUP "Zoom"
+ BEGIN
+ MENUITEM "&XY 100%", ID_VIEW_100
+ MENUITEM "XY Zoom &In\tDelete", ID_VIEW_ZOOMIN
+ MENUITEM "XY Zoom &Out\tInsert", ID_VIEW_ZOOMOUT
+ MENUITEM SEPARATOR
+ MENUITEM "&Z 100%", ID_VIEW_Z100
+ MENUITEM "Z Zoo&m In\tctrl-Delete", ID_VIEW_ZZOOMIN
+ MENUITEM "Z Zoom O&ut\tctrl-Insert", ID_VIEW_ZZOOMOUT
+ MENUITEM SEPARATOR
+ MENUITEM "Cubic Clip Zoom In\tctrl-]", ID_VIEW_CUBEIN
+ MENUITEM "Cubic Clip Zoom Out\tctrl-[", ID_VIEW_CUBEOUT
+ END
+ MENUITEM SEPARATOR
+ POPUP "Show"
+ BEGIN
+ MENUITEM "Show &Names", ID_VIEW_SHOWNAMES
+ , CHECKED
+ MENUITEM "Show Blocks", ID_VIEW_SHOWBLOCKS
+ MENUITEM "Show C&oordinates", ID_VIEW_SHOWCOORDINATES
+ , CHECKED
+ MENUITEM "Show &Entities", ID_VIEW_SHOWENT, CHECKED
+ MENUITEM "Show &Path", ID_VIEW_SHOWPATH
+ , CHECKED
+ MENUITEM "Show &Lights", ID_VIEW_SHOWLIGHTS
+ , CHECKED
+ MENUITEM "Show &Water", ID_VIEW_SHOWWATER
+ , CHECKED
+ MENUITEM "Show Clip &Brush", ID_VIEW_SHOWCLIP
+ , CHECKED
+ MENUITEM "Show &Hint Brush", ID_VIEW_SHOWHINT
+ , CHECKED
+ MENUITEM "Show Wor&ld", ID_VIEW_SHOWWORLD
+ , CHECKED
+ MENUITEM "Show Detail\tctrl-D", ID_VIEW_SHOWDETAIL
+ , CHECKED
+ MENUITEM "Show Curves", ID_VIEW_SHOWCURVES
+ , CHECKED
+ MENUITEM "Show Caulk", ID_VIEW_SHOWCAULK
+ , CHECKED
+ MENUITEM "Show Angles", ID_VIEW_SHOWANGLES
+ END
+ POPUP "Hide/Show"
+ BEGIN
+ MENUITEM "Hide Selected", ID_VIEW_HIDESHOW_HIDESELECTED
+
+ MENUITEM "Show Hidden", ID_VIEW_HIDESHOW_SHOWHIDDEN
+
+ END
+ MENUITEM SEPARATOR
+ POPUP "Entities as"
+ BEGIN
+ MENUITEM "Bounding box", ID_VIEW_ENTITIESAS_BOUNDINGBOX
+
+ MENUITEM "Wireframe", ID_VIEW_ENTITIESAS_WIREFRAME
+
+ MENUITEM "Selected Wireframe", ID_VIEW_ENTITIESAS_SELECTEDWIREFRAME
+
+ MENUITEM "Selected Skinned", ID_VIEW_ENTITIESAS_SELECTEDSKINNED
+
+ MENUITEM "Skinned", ID_VIEW_ENTITIESAS_SKINNED
+
+ MENUITEM "Skinned and Boxed", ID_VIEW_ENTITIESAS_SKINNEDANDBOXED
+
+ END
+ MENUITEM SEPARATOR
+ MENUITEM "Cubic Clipping", ID_VIEW_CUBICCLIPPING
+ , CHECKED
+ MENUITEM SEPARATOR
+ MENUITEM "OpenGL Lighting", ID_VIEW_OPENGLLIGHTING
+ END
+ POPUP "&Selection"
+ BEGIN
+ POPUP "Drag"
+ BEGIN
+ MENUITEM "Drag &Edges", ID_SELECTION_DRAGEDGES
+ MENUITEM "Drag &Vertices", ID_SELECTION_DRAGVERTECIES
+
+ END
+ MENUITEM SEPARATOR
+ MENUITEM "&Clone", ID_SELECTION_CLONE
+ MENUITEM "Deselect\tEsc", ID_SELECTION_DESELECT
+ MENUITEM SEPARATOR
+ POPUP "Flip"
+ BEGIN
+ MENUITEM "Flip &X", ID_BRUSH_FLIPX
+ MENUITEM "Flip &Y", ID_BRUSH_FLIPY
+ MENUITEM "Flip &Z", ID_BRUSH_FLIPZ
+ END
+ MENUITEM SEPARATOR
+ POPUP "Rotate"
+ BEGIN
+ MENUITEM "Rotate X", ID_BRUSH_ROTATEX
+ MENUITEM "Rotate Y", ID_BRUSH_ROTATEY
+ MENUITEM "Rotate Z", ID_BRUSH_ROTATEZ
+ MENUITEM "Arbitrary rotation...", ID_SELECTION_ARBITRARYROTATION
+
+ END
+ MENUITEM SEPARATOR
+ MENUITEM "Scale...", ID_SELECT_SCALE
+ POPUP "CSG"
+ BEGIN
+ MENUITEM "&Hollow", ID_SELECTION_MAKEHOLLOW
+ MENUITEM "&Subtract", ID_SELECTION_CSGSUBTRACT
+ MENUITEM "&Merge", ID_SELECTION_CSGMERGE
+ END
+ MENUITEM SEPARATOR
+ POPUP "Select"
+ BEGIN
+ MENUITEM "Select Complete &Tall", ID_SELECTION_SELECTCOMPLETETALL
+
+ MENUITEM "Select T&ouching", ID_SELECTION_SELECTTOUCHING
+
+ MENUITEM "Select &Partial Tall", ID_SELECTION_SELECTPARTIALTALL
+
+ MENUITEM "Select &Inside", ID_SELECTION_SELECTINSIDE
+
+ END
+ MENUITEM SEPARATOR
+ POPUP "Clipper"
+ BEGIN
+ MENUITEM "Toggle Clipper", ID_VIEW_CLIPPER
+ MENUITEM SEPARATOR
+ MENUITEM "Clip selection", ID_CLIP_SELECTED
+ MENUITEM "Split selectedion", ID_SPLIT_SELECTED
+ MENUITEM "Flip Clip orientation", ID_FLIP_CLIP
+ END
+ MENUITEM SEPARATOR
+ MENUITEM "Connect entities", ID_SELECTION_CONNECT
+ MENUITEM "Ungroup entity", ID_SELECTION_UNGROUPENTITY
+ MENUITEM "Make detail", ID_SELECTION_MAKE_DETAIL
+ MENUITEM "Make structural", ID_SELECTION_MAKE_STRUCTURAL
+ END
+ POPUP "&Bsp"
+ BEGIN
+ MENUITEM SEPARATOR
+ END
+ POPUP "&Grid"
+ BEGIN
+ MENUITEM "Grid1\t&1", ID_GRID_1
+ MENUITEM "Grid2\t&2", ID_GRID_2
+ MENUITEM "Grid4\t&3", ID_GRID_4
+ MENUITEM "Grid8\t&4", ID_GRID_8, CHECKED
+ MENUITEM "Grid16\t&5", ID_GRID_16
+ MENUITEM "Grid32\t&6", ID_GRID_32
+ MENUITEM "Grid64\t&7", ID_GRID_64
+ MENUITEM SEPARATOR
+ MENUITEM "Snap to grid", ID_SNAPTOGRID, CHECKED
+ END
+ POPUP "&Textures"
+ BEGIN
+ MENUITEM "Show In &Use\tU", ID_TEXTURES_SHOWINUSE
+ MENUITEM "Show &All\tCtrl-A", ID_TEXTURES_SHOWALL
+ MENUITEM SEPARATOR
+ MENUITEM "&Surface Inspector\tS", ID_TEXTURES_INSPECTOR
+ MENUITEM SEPARATOR
+ POPUP "Render Quality"
+ BEGIN
+ MENUITEM "&Wireframe", ID_TEXTURES_WIREFRAME
+ MENUITEM "&Flat shade", ID_TEXTURES_FLATSHADE
+ MENUITEM "&Nearest", ID_VIEW_NEAREST
+ MENUITEM "Nearest &Mipmap", ID_VIEW_NEARESTMIPMAP
+ MENUITEM "&Linear", ID_VIEW_LINEAR
+ MENUITEM "&Bilinear", ID_VIEW_BILINEAR
+ MENUITEM "B&ilinear Mipmap", ID_VIEW_BILINEARMIPMAP
+ MENUITEM "T&rilinear", ID_VIEW_TRILINEAR
+ END
+ MENUITEM SEPARATOR
+ MENUITEM "Find / Replace...", ID_TEXTURE_REPLACEALL
+ MENUITEM SEPARATOR
+ POPUP "Texture Lock"
+ BEGIN
+ MENUITEM "Moves", ID_TOGGLE_LOCK, CHECKED
+ MENUITEM "Rotations", ID_TOGGLE_ROTATELOCK
+ , CHECKED
+ END
+ MENUITEM SEPARATOR
+ MENUITEM "Load...", ID_TEXTURES_LOAD
+ POPUP "Shaders"
+ BEGIN
+ MENUITEM "Load All (Reload)", ID_TEXTURES_RELOADSHADERS
+
+ MENUITEM "Show", ID_TEXTURES_SHADERS_SHOW
+ , CHECKED
+ END
+ MENUITEM SEPARATOR
+ POPUP "Flush"
+ BEGIN
+ MENUITEM "All", ID_TEXTURES_FLUSH
+ MENUITEM "Unused", ID_TEXTURES_FLUSH_UNUSED
+ END
+ MENUITEM SEPARATOR
+ POPUP "Texture Window Scale"
+ BEGIN
+ MENUITEM "200%", ID_TEXTURES_TEXTUREWINDOWSCALE_200
+
+ MENUITEM "100%", ID_TEXTURES_TEXTUREWINDOWSCALE_100
+
+ MENUITEM "50%", ID_TEXTURES_TEXTUREWINDOWSCALE_50
+
+ MENUITEM "25%", ID_TEXTURES_TEXTUREWINDOWSCALE_25
+
+ MENUITEM "10%", ID_TEXTURES_TEXTUREWINDOWSCALE_10
+
+ END
+ MENUITEM SEPARATOR
+ END
+ POPUP "&Misc"
+ BEGIN
+ MENUITEM "&Benchmark", ID_MISC_BENCHMARK
+ POPUP "&Colors"
+ BEGIN
+ POPUP "Themes"
+ BEGIN
+ MENUITEM "QE4 Original", ID_COLOR_SETORIGINAL
+ MENUITEM "Q3Radiant Original", ID_COLOR_SETQER
+ MENUITEM "Black and Green", ID_COLOR_SETBLACK
+ END
+ MENUITEM SEPARATOR
+ MENUITEM "&Texture Background...", ID_TEXTUREBK
+ MENUITEM "Grid Background...", ID_COLORS_XYBK
+ MENUITEM "Grid Major...", ID_COLORS_MAJOR
+ MENUITEM "Grid Minor...", ID_COLORS_MINOR
+ MENUITEM "Grid Text...", ID_COLORS_GRIDTEXT
+ MENUITEM "Grid Block...", ID_COLORS_GRIDBLOCK
+ MENUITEM "Default Brush...", ID_COLORS_BRUSH
+ MENUITEM "Selected Brush...", ID_COLORS_SELECTEDBRUSH
+ MENUITEM "Clipper...", ID_COLORS_CLIPPER
+ MENUITEM "Active View name...", ID_COLORS_VIEWNAME
+ END
+ MENUITEM "&Gamma...", ID_MISC_GAMMA
+ MENUITEM "Find brush...", ID_MISC_FINDBRUSH
+ MENUITEM "Next leak spot\tctrl-l", ID_MISC_NEXTLEAKSPOT
+ MENUITEM "Previous leak spot\tctrl-p", ID_MISC_PREVIOUSLEAKSPOT
+ MENUITEM "&Print XY View", ID_MISC_PRINTXY
+ MENUITEM "&Select Entity Color...\tK", ID_MISC_SELECTENTITYCOLOR
+ END
+ POPUP "&Region"
+ BEGIN
+ MENUITEM "&Off", ID_REGION_OFF
+ MENUITEM "&Set XY", ID_REGION_SETXY
+ MENUITEM "Set &Tall Brush", ID_REGION_SETTALLBRUSH
+ MENUITEM "Set &Brush", ID_REGION_SETBRUSH
+ MENUITEM "Set Se&lected Brushes", ID_REGION_SETSELECTION
+ END
+ POPUP "&Brush"
+ BEGIN
+ MENUITEM "3 sided\tctrl-3", ID_BRUSH_3SIDED
+ MENUITEM "4 sided\tctrl-4", ID_BRUSH_4SIDED
+ MENUITEM "5 sided\tctrl-5", ID_BRUSH_5SIDED
+ MENUITEM "6 sided\tctrl-6", ID_BRUSH_6SIDED
+ MENUITEM "7 sided\tctrl-7", ID_BRUSH_7SIDED
+ MENUITEM "8 sided\tctrl-8", ID_BRUSH_8SIDED
+ MENUITEM "9 sided\tctrl-9", ID_BRUSH_9SIDED
+ MENUITEM SEPARATOR
+ MENUITEM "Arbitrary sided...", ID_BRUSH_ARBITRARYSIDED
+ MENUITEM SEPARATOR
+ POPUP "Primitives"
+ BEGIN
+ MENUITEM "Cone...", ID_BRUSH_MAKECONE
+ MENUITEM "Sphere...", ID_BRUSH_PRIMITIVES_SPHERE
+
+ END
+ END
+ POPUP "&Curve"
+ BEGIN
+ MENUITEM "Cylinder", ID_CURVE_PATCHTUBE
+ POPUP "More Cylinders"
+ BEGIN
+ MENUITEM "Dense Cylinder", ID_CURVE_PATCHDENSETUBE
+ MENUITEM "Very Dense Cylinder", ID_CURVE_PATCHVERYDENSETUBE
+
+ MENUITEM "Square Cylinder", ID_CURVE_PATCHSQUARE
+ END
+ MENUITEM SEPARATOR
+ MENUITEM "End cap", ID_CURVE_PATCHENDCAP
+ MENUITEM "Bevel", ID_CURVE_PATCHBEVEL
+ POPUP "More End caps, Bevels"
+ BEGIN
+ MENUITEM "Square Endcap", ID_CURVE_MOREENDCAPSBEVELS_SQUAREBEVEL
+
+ MENUITEM "Square Bevel", ID_CURVE_MOREENDCAPSBEVELS_SQUAREENDCAP
+
+ END
+ MENUITEM SEPARATOR
+ MENUITEM "Cone", ID_CURVE_PATCHCONE
+ MENUITEM "Sphere", ID_CURVE_PRIMITIVES_SPHERE
+ , GRAYED
+ MENUITEM SEPARATOR
+ MENUITEM "Simple Patch Mesh...", ID_CURVE_SIMPLEPATCHMESH
+ MENUITEM SEPARATOR
+ POPUP "Insert"
+ BEGIN
+ MENUITEM "Insert (2) Columns", ID_CURVE_INSERT_INSERTCOLUMN
+
+ MENUITEM "Add (2) Columns", ID_CURVE_INSERT_ADDCOLUMN
+
+ MENUITEM SEPARATOR
+ MENUITEM "Insert (2) Rows", ID_CURVE_INSERT_INSERTROW
+
+ MENUITEM "Add (2) Rows", ID_CURVE_INSERT_ADDROW
+ END
+ POPUP "Delete"
+ BEGIN
+ MENUITEM "First (2) Columns", ID_CURVE_DELETE_FIRSTCOLUMN
+
+ MENUITEM "Last (2) Columns", ID_CURVE_DELETE_LASTCOLUMN
+
+ MENUITEM SEPARATOR
+ MENUITEM "First (2) Rows", ID_CURVE_DELETE_FIRSTROW
+ MENUITEM "Last (2) Rows", ID_CURVE_DELETE_LASTROW
+ END
+ MENUITEM SEPARATOR
+ POPUP "Matrix"
+ BEGIN
+ MENUITEM "Invert", ID_CURVE_NEGATIVE
+ POPUP "Re-disperse"
+ BEGIN
+ MENUITEM "Cols", ID_CURVE_REDISPERSE_COLS
+
+ MENUITEM "Rows", ID_CURVE_REDISPERSE_ROWS
+
+ END
+ MENUITEM "Transpose", ID_CURVE_MATRIX_TRANSPOSE
+
+ END
+ MENUITEM SEPARATOR
+ POPUP "Cap"
+ BEGIN
+ MENUITEM "Normal", ID_CURVE_CAP
+ MENUITEM "Inverted Bevel", ID_CURVE_CAP_INVERTEDBEVEL
+
+ MENUITEM "Inverted Endcap", ID_CURVE_CAP_INVERTEDENDCAP
+
+ MENUITEM SEPARATOR
+ MENUITEM "Cycle Cap Texture", ID_CURVE_CYCLECAP
+ END
+ MENUITEM SEPARATOR
+ POPUP "Overlay"
+ BEGIN
+ MENUITEM "Set", ID_CURVE_OVERLAY_SET
+ MENUITEM "Clear", ID_CURVE_OVERLAY_CLEAR
+ END
+ MENUITEM SEPARATOR
+ MENUITEM "Thicken...", ID_CURVE_THICKEN
+ END
+ POPUP "&Terrain"
+ BEGIN
+ MENUITEM "Create Terrain from &Brush", ID_TERRAIN_CREATETERRAINFROMBRUSH
+
+ MENUITEM "Raise/Lower Terrain", ID_TERRAIN_RAISELOWERTERRAIN
+ , CHECKED
+ END
+ POPUP "&Plugins"
+ BEGIN
+ MENUITEM "Refresh", ID_PLUGINS_REFRESH
+ MENUITEM SEPARATOR
+ END
+ POPUP "&Help"
+ BEGIN
+ MENUITEM "Help\tF1", ID_HELP
+ MENUITEM SEPARATOR
+ MENUITEM "Command list...", ID_HELP_COMMANDLIST
+ MENUITEM SEPARATOR
+ MENUITEM "&About...", ID_HELP_ABOUT
+ END
+END
+
+IDR_POPUP_TEXTURE MENU DISCARDABLE
+BEGIN
+ POPUP "Popup"
+ BEGIN
+ MENUITEM "&Wireframe", ID_TEXTURES_WIREFRAME
+ MENUITEM "&Flat shade", ID_TEXTURES_FLATSHADE
+ MENUITEM "&Nearest", ID_VIEW_NEAREST
+ MENUITEM "Nearest &Mipmap", ID_VIEW_NEARESTMIPMAP
+ MENUITEM "&Linear", ID_VIEW_LINEAR
+ MENUITEM "&Bilinear", ID_VIEW_BILINEAR
+ MENUITEM "B&ilinear Mipmap", ID_VIEW_BILINEARMIPMAP
+ MENUITEM "T&rilinear", ID_VIEW_TRILINEAR
+ END
+END
+
+IDR_POPUP_SELECTION MENU DISCARDABLE
+BEGIN
+ POPUP "Popup"
+ BEGIN
+ MENUITEM "Select Complete &Tall", ID_SELECTION_SELECTCOMPLETETALL
+
+ MENUITEM "Select T&ouching", ID_SELECTION_SELECTTOUCHING
+ MENUITEM "Select &Partial Tall", ID_SELECTION_SELECTPARTIALTALL
+
+ MENUITEM "Select &Inside", ID_SELECTION_SELECTINSIDE
+ END
+END
+
+IDR_POPUP_VIEW MENU DISCARDABLE
+BEGIN
+ POPUP "Popup"
+ BEGIN
+ MENUITEM "XY (Top)", ID_VIEW_XY
+ MENUITEM "XZ", ID_VIEW_SIDE
+ MENUITEM "YZ", ID_VIEW_FRONT
+ END
+END
+
+IDR_MENU_DROP MENU DISCARDABLE
+BEGIN
+ POPUP "Drop"
+ BEGIN
+ MENUITEM SEPARATOR
+ POPUP "Select"
+ BEGIN
+ MENUITEM "Select Complete &Tall", ID_SELECTION_SELECTCOMPLETETALL
+
+ MENUITEM "Select T&ouching", ID_SELECTION_SELECTTOUCHING
+
+ MENUITEM "Select &Partial Tall", ID_SELECTION_SELECTPARTIALTALL
+
+ MENUITEM "Select &Inside", ID_SELECTION_SELECTINSIDE
+
+ END
+ MENUITEM SEPARATOR
+ POPUP "Group"
+ BEGIN
+ MENUITEM "Add to...", ID_DROP_GROUP_ADDTO
+ MENUITEM "Remove", ID_DROP_GROUP_REMOVE
+ MENUITEM SEPARATOR
+ MENUITEM "Name...", ID_DROP_GROUP_NAME
+ MENUITEM SEPARATOR
+ MENUITEM "New Group...", ID_DROP_GROUP_NEWGROUP
+ END
+ MENUITEM "Ungroup entity", ID_SELECTION_UNGROUPENTITY
+ MENUITEM "Make detail", ID_SELECTION_MAKE_DETAIL
+ MENUITEM "Make structural", ID_SELECTION_MAKE_STRUCTURAL
+ END
+END
+
+IDR_MENU1 MENU DISCARDABLE
+BEGIN
+ POPUP "&File"
+ BEGIN
+ MENUITEM "&New map", ID_FILE_NEW
+ MENUITEM SEPARATOR
+ MENUITEM "&Open...", ID_FILE_OPEN
+ MENUITEM "&Load...", ID_FILE_IMPORTMAP
+ MENUITEM "&Save", ID_FILE_SAVE
+ MENUITEM "Save &as...", ID_FILE_SAVEAS
+ MENUITEM "Save s&elected...", ID_FILE_EXPORTMAP
+ MENUITEM SEPARATOR
+ MENUITEM "Save re&gion...", ID_FILE_SAVEREGION
+ MENUITEM SEPARATOR
+ MENUITEM "New p&roject...", ID_FILE_NEWPROJECT
+ MENUITEM "Load &project...", ID_FILE_LOADPROJECT
+ MENUITEM "Pro&ject settings...", ID_FILE_PROJECTSETTINGS
+ MENUITEM SEPARATOR
+ MENUITEM "&Pointfile...", ID_FILE_POINTFILE
+ MENUITEM SEPARATOR
+ MENUITEM "E&xit", ID_FILE_EXIT
+ END
+ POPUP "&Edit"
+ BEGIN
+ MENUITEM "Undo (no really :-)", ID_EDIT_UNDO
+ MENUITEM SEPARATOR
+ MENUITEM "&Copy brush", ID_EDIT_COPYBRUSH
+ MENUITEM "&Paste brush", ID_EDIT_PASTEBRUSH
+ MENUITEM SEPARATOR
+ MENUITEM "Map Info...", ID_EDIT_MAPINFO
+ MENUITEM "Entity Info...", ID_EDIT_ENTITYINFO
+ MENUITEM SEPARATOR
+ MENUITEM "Brush Scripts...", ID_BRUSH_SCRIPTS
+ MENUITEM SEPARATOR
+ MENUITEM "Load Pre&fab...", ID_EDIT_LOADPREFAB
+ MENUITEM SEPARATOR
+ MENUITEM "Preferences...", ID_PREFS
+ END
+ POPUP "&View"
+ BEGIN
+ POPUP "Toggle"
+ BEGIN
+ MENUITEM "Camera View", ID_TOGGLECAMERA
+ MENUITEM "Console View", ID_TOGGLECONSOLE
+ MENUITEM "Entity View", ID_VIEW_ENTITY
+ MENUITEM "XY (Top)", ID_TOGGLEVIEW
+ MENUITEM "YZ (Side)", ID_TOGGLEVIEW_YZ
+ MENUITEM "XZ (Front)", ID_TOGGLEVIEW_XZ
+ MENUITEM "Z View", ID_TOGGLEZ
+ END
+ MENUITEM SEPARATOR
+ MENUITEM "&Center\tEnd", ID_VIEW_CENTER
+ MENUITEM "&Up Floor\tPage Up", ID_VIEW_UPFLOOR
+ MENUITEM "&Down Floor\tPage Down", ID_VIEW_DOWNFLOOR
+ MENUITEM SEPARATOR
+ MENUITEM "&Next (XY, YZ, XY)\tCtrl-TAB", ID_VIEW_NEXTVIEW
+ POPUP "Layout"
+ BEGIN
+ MENUITEM "XY (Top)", ID_VIEW_XY
+ MENUITEM "YZ", ID_VIEW_SIDE
+ MENUITEM "XZ", ID_VIEW_FRONT
+ END
+ POPUP "Zoom"
+ BEGIN
+ MENUITEM "&XY 100%", ID_VIEW_100
+ MENUITEM "XY Zoom &In\tDelete", ID_VIEW_ZOOMIN
+ MENUITEM "XY Zoom &Out\tInsert", ID_VIEW_ZOOMOUT
+ MENUITEM SEPARATOR
+ MENUITEM "&Z 100%", ID_VIEW_Z100
+ MENUITEM "Z Zoo&m In\tctrl-Delete", ID_VIEW_ZZOOMIN
+ MENUITEM "Z Zoom O&ut\tctrl-Insert", ID_VIEW_ZZOOMOUT
+ MENUITEM SEPARATOR
+ MENUITEM "Cubic Clip Zoom In\tctrl-]", ID_VIEW_CUBEIN
+ MENUITEM "Cubic Clip Zoom Out\tctrl-[", ID_VIEW_CUBEOUT
+ END
+ MENUITEM SEPARATOR
+ POPUP "Show"
+ BEGIN
+ MENUITEM "Show &Names", ID_VIEW_SHOWNAMES
+ , CHECKED
+ MENUITEM "Show Blocks", ID_VIEW_SHOWBLOCKS
+ MENUITEM "Show C&oordinates", ID_VIEW_SHOWCOORDINATES
+ , CHECKED
+ MENUITEM "Show &Entities", ID_VIEW_SHOWENT, CHECKED
+ MENUITEM "Show &Path", ID_VIEW_SHOWPATH
+ , CHECKED
+ MENUITEM "Show &Lights", ID_VIEW_SHOWLIGHTS
+ , CHECKED
+ MENUITEM "Show &Water", ID_VIEW_SHOWWATER
+ , CHECKED
+ MENUITEM "Show Clip &Brush", ID_VIEW_SHOWCLIP
+ , CHECKED
+ MENUITEM "Show Wor&ld", ID_VIEW_SHOWWORLD
+ , CHECKED
+ MENUITEM "Show Detail\tctrl-D", ID_VIEW_SHOWDETAIL
+ , CHECKED
+ END
+ MENUITEM SEPARATOR
+ MENUITEM "Cubic Clipping", ID_VIEW_CUBICCLIPPING
+ , CHECKED
+ MENUITEM SEPARATOR
+ MENUITEM "Dynamic Lighting", ID_DYNAMIC_LIGHTING
+ END
+ POPUP "&Selection"
+ BEGIN
+ POPUP "Drag"
+ BEGIN
+ MENUITEM "Drag &Edges", ID_SELECTION_DRAGEDGES
+ MENUITEM "Drag &Vertices", ID_SELECTION_DRAGVERTECIES
+
+ END
+ MENUITEM SEPARATOR
+ MENUITEM "&Clone", ID_SELECTION_CLONE
+ MENUITEM "Deselect", ID_SELECTION_DESELECT
+ MENUITEM "&Delete", ID_SELECTION_DELETE
+ MENUITEM SEPARATOR
+ POPUP "Flip"
+ BEGIN
+ MENUITEM "Flip &X", ID_BRUSH_FLIPX
+ MENUITEM "Flip &Y", ID_BRUSH_FLIPY
+ MENUITEM "Flip &Z", ID_BRUSH_FLIPZ
+ END
+ MENUITEM SEPARATOR
+ POPUP "Rotate"
+ BEGIN
+ MENUITEM "Rotate X", ID_BRUSH_ROTATEX
+ MENUITEM "Rotate Y", ID_BRUSH_ROTATEY
+ MENUITEM "Rotate Z", ID_BRUSH_ROTATEZ
+ MENUITEM "Arbitrary rotation...", ID_SELECTION_ARBITRARYROTATION
+
+ END
+ MENUITEM SEPARATOR
+ MENUITEM "Scale...", ID_SELECT_SCALE
+ POPUP "CSG"
+ BEGIN
+ MENUITEM "Make &Hollow", ID_SELECTION_MAKEHOLLOW
+ MENUITEM "CSG &Subtract", ID_SELECTION_CSGSUBTRACT
+ MENUITEM "CSG &Add", ID_SELECTION_CSGADD
+ END
+ MENUITEM SEPARATOR
+ POPUP "Select"
+ BEGIN
+ MENUITEM "Select Complete &Tall", ID_SELECTION_SELECTCOMPLETETALL
+
+ MENUITEM "Select T&ouching", ID_SELECTION_SELECTTOUCHING
+
+ MENUITEM "Select &Partial Tall", ID_SELECTION_SELECTPARTIALTALL
+
+ MENUITEM "Select &Inside", ID_SELECTION_SELECTINSIDE
+
+ MENUITEM "Nudge Left", ID_SELECTION_SELECT_NUDGELEFT
+
+ MENUITEM "Nudge Right", ID_SELECTION_SELECT_NUDGERIGHT
+
+ MENUITEM "Nudge Up", ID_SELECTION_SELECT_NUDGEUP
+
+ MENUITEM "Nudge Down", ID_SELECTION_SELECT_NUDGEDOWN
+
+ END
+ MENUITEM SEPARATOR
+ POPUP "Clipper"
+ BEGIN
+ MENUITEM "Toggle Clipper", ID_VIEW_CLIPPER
+ MENUITEM SEPARATOR
+ MENUITEM "Clip selection", ID_CLIP_SELECTED
+ MENUITEM "Split selectedion", ID_SPLIT_SELECTED
+ MENUITEM "Flip Clip orientation", ID_FLIP_CLIP
+ END
+ MENUITEM SEPARATOR
+ MENUITEM "Connect entities", ID_SELECTION_CONNECT
+ MENUITEM "Ungroup entity", ID_SELECTION_UNGROUPENTITY
+ MENUITEM "Make detail", ID_SELECTION_MAKE_DETAIL
+ MENUITEM "Make structural", ID_SELECTION_MAKE_STRUCTURAL
+ END
+ POPUP "&Bsp"
+ BEGIN
+ MENUITEM SEPARATOR
+ END
+ POPUP "&Grid"
+ BEGIN
+ MENUITEM "Grid1\t&1", ID_GRID_1
+ MENUITEM "Grid2\t&2", ID_GRID_2
+ MENUITEM "Grid4\t&3", ID_GRID_4
+ MENUITEM "Grid8\t&4", ID_GRID_8, CHECKED
+ MENUITEM "Grid16\t&5", ID_GRID_16
+ MENUITEM "Grid32\t&6", ID_GRID_32
+ MENUITEM "Grid64\t&7", ID_GRID_64
+ MENUITEM SEPARATOR
+ MENUITEM "Snap to grid", ID_SNAPTOGRID, CHECKED
+ END
+ POPUP "&Textures"
+ BEGIN
+ MENUITEM "Show In &Use\tU", ID_TEXTURES_SHOWINUSE
+ MENUITEM "&Surface Inspector\tS", ID_TEXTURES_INSPECTOR
+ MENUITEM SEPARATOR
+ POPUP "Render Quality"
+ BEGIN
+ MENUITEM "&Wireframe", ID_TEXTURES_WIREFRAME
+ MENUITEM "&Flat shade", ID_TEXTURES_FLATSHADE
+ MENUITEM "&Nearest", ID_VIEW_NEAREST
+ MENUITEM "Nearest &Mipmap", ID_VIEW_NEARESTMIPMAP
+ MENUITEM "&Linear", ID_VIEW_LINEAR
+ MENUITEM "&Bilinear", ID_VIEW_BILINEAR
+ MENUITEM "B&ilinear Mipmap", ID_VIEW_BILINEARMIPMAP
+ MENUITEM "T&rilinear", ID_VIEW_TRILINEAR
+ END
+ MENUITEM SEPARATOR
+ MENUITEM "Find / Replace...", ID_TEXTURE_REPLACEALL
+ MENUITEM SEPARATOR
+ MENUITEM "Move Texture Lock", ID_TOGGLE_LOCK, CHECKED
+ MENUITEM "Rotation Texture Lock", ID_TOGGLE_ROTATELOCK
+ , CHECKED
+ MENUITEM SEPARATOR
+ MENUITEM "Load...", ID_TEXTURES_LOAD
+ MENUITEM "Load from List.. ", ID_TEXTURES_LOADLIST
+ MENUITEM SEPARATOR
+ END
+ POPUP "&Misc"
+ BEGIN
+ MENUITEM "&Benchmark", ID_MISC_BENCHMARK
+ POPUP "&Colors"
+ BEGIN
+ POPUP "Themes"
+ BEGIN
+ MENUITEM "QE4 Original", ID_COLOR_SETORIGINAL
+ MENUITEM "Q3Radiant Original", ID_COLOR_SETQER
+ MENUITEM "Black and Green", ID_COLOR_SETBLACK
+ END
+ MENUITEM SEPARATOR
+ MENUITEM "&Texture Background...", ID_TEXTUREBK
+ MENUITEM "Grid Background...", ID_COLORS_XYBK
+ MENUITEM "Grid Major...", ID_COLORS_MAJOR
+ MENUITEM "Grid Minor...", ID_COLORS_MINOR
+ MENUITEM "Grid Text...", ID_COLORS_GRIDTEXT
+ MENUITEM "Grid Block...", ID_COLORS_GRIDBLOCK
+ MENUITEM "Default Brush...", ID_COLORS_BRUSH
+ MENUITEM "Selected Brush...", ID_COLORS_SELECTEDBRUSH
+ MENUITEM "Clipper...", ID_COLORS_CLIPPER
+ MENUITEM "Active View name...", ID_COLORS_VIEWNAME
+ END
+ MENUITEM "&Gamma...", ID_MISC_GAMMA
+ MENUITEM "Find brush...", ID_MISC_FINDBRUSH
+ MENUITEM "Next leak spot\tctrl-l", ID_MISC_NEXTLEAKSPOT
+ MENUITEM "Previous leak spot\tctrl-p", ID_MISC_PREVIOUSLEAKSPOT
+ MENUITEM "&Print XY View", ID_MISC_PRINTXY
+ MENUITEM "&Select Entity Color...\tK", ID_MISC_SELECTENTITYCOLOR
+ MENUITEM "Convert old curves", ID_CONVERTCURVES
+ END
+ POPUP "&Region"
+ BEGIN
+ MENUITEM "&Off", ID_REGION_OFF
+ MENUITEM "&Set XY", ID_REGION_SETXY
+ MENUITEM "Set &Tall Brush", ID_REGION_SETTALLBRUSH
+ MENUITEM "Set &Brush", ID_REGION_SETBRUSH
+ MENUITEM "Set Se&lected Brushes", ID_REGION_SETSELECTION
+ END
+ POPUP "&Brush"
+ BEGIN
+ MENUITEM "3 sided\tctrl-3", ID_BRUSH_3SIDED
+ MENUITEM "4 sided\tctrl-4", ID_BRUSH_4SIDED
+ MENUITEM "5 sided\tctrl-5", ID_BRUSH_5SIDED
+ MENUITEM "6 sided\tctrl-6", ID_BRUSH_6SIDED
+ MENUITEM "7 sided\tctrl-7", ID_BRUSH_7SIDED
+ MENUITEM "8 sided\tctrl-8", ID_BRUSH_8SIDED
+ MENUITEM "9 sided\tctrl-9", ID_BRUSH_9SIDED
+ MENUITEM SEPARATOR
+ MENUITEM "Arbitrary sided...", ID_BRUSH_ARBITRARYSIDED
+ MENUITEM SEPARATOR
+ POPUP "Primitives"
+ BEGIN
+ MENUITEM "Cone...", ID_BRUSH_MAKECONE
+ END
+ END
+ POPUP "&Help"
+ BEGIN
+ MENUITEM "Command list...", ID_HELP_COMMANDLIST
+ MENUITEM SEPARATOR
+ MENUITEM "&About...", ID_HELP_ABOUT
+ END
+END
+
+IDR_POPUP_ENTITY MENU DISCARDABLE
+BEGIN
+ POPUP "Popup"
+ BEGIN
+ MENUITEM "Bounding box", ID_VIEW_ENTITIESAS_BOUNDINGBOX
+
+ MENUITEM "Wireframe", ID_VIEW_ENTITIESAS_WIREFRAME
+ MENUITEM "Selected Wireframe", ID_VIEW_ENTITIESAS_SELECTEDWIREFRAME
+
+ MENUITEM "Selected Skinned", ID_VIEW_ENTITIESAS_SELECTEDSKINNED
+
+ MENUITEM "Skinned", ID_VIEW_ENTITIESAS_SKINNED
+ MENUITEM "Skinned and Boxed", ID_VIEW_ENTITIESAS_SKINNEDANDBOXED
+
+ END
+END
+
+IDR_POPUP_GROUP MENU DISCARDABLE
+BEGIN
+ POPUP "Popup"
+ BEGIN
+ MENUITEM "XY (Top)", ID_VIEW_XY
+ MENUITEM "XZ", ID_VIEW_SIDE
+ MENUITEM "YZ", ID_VIEW_FRONT
+ END
+END
+
+IDR_POPUP_SPLINE MENU DISCARDABLE
+BEGIN
+ POPUP "Popup"
+ BEGIN
+ POPUP "New Camera"
+ BEGIN
+ MENUITEM "Fixed", ID_POPUP_NEWCAMERA_FIXED
+ MENUITEM "Interpolated", ID_POPUP_NEWCAMERA_INTERPOLATED
+
+ MENUITEM "Spline", ID_POPUP_NEWCAMERA_SPLINE
+
+ END
+ MENUITEM "Camera Inspector...", ID_SPLINES_EDIT
+ MENUITEM SEPARATOR
+ MENUITEM "Test Camera", ID_SPLINE_TEST
+ END
+END
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Accelerator
+//
+
+IDR_ACCELERATOR1 ACCELERATORS DISCARDABLE
+BEGIN
+ "3", ID_BRUSH_3SIDED, VIRTKEY, CONTROL, NOINVERT
+ "4", ID_BRUSH_4SIDED, VIRTKEY, CONTROL, NOINVERT
+ "5", ID_BRUSH_5SIDED, VIRTKEY, CONTROL, NOINVERT
+ "6", ID_BRUSH_6SIDED, VIRTKEY, CONTROL, NOINVERT
+ "7", ID_BRUSH_7SIDED, VIRTKEY, CONTROL, NOINVERT
+ "8", ID_BRUSH_8SIDED, VIRTKEY, CONTROL, NOINVERT
+ "9", ID_BRUSH_9SIDED, VIRTKEY, CONTROL, NOINVERT
+ "D", ID_VIEW_SHOWDETAIL, VIRTKEY, CONTROL, NOINVERT
+ "K", ID_SELECTION_CONNECT, VIRTKEY, CONTROL, NOINVERT
+ "L", ID_MISC_NEXTLEAKSPOT, VIRTKEY, CONTROL, NOINVERT
+ "M", ID_SELECTION_MAKE_DETAIL, VIRTKEY, CONTROL, NOINVERT
+ "O", ID_FILE_OPEN, VIRTKEY, CONTROL, NOINVERT
+ "P", ID_MISC_PREVIOUSLEAKSPOT, VIRTKEY, CONTROL, NOINVERT
+ "S", ID_FILE_SAVE, VIRTKEY, CONTROL, NOINVERT
+ VK_DELETE, ID_VIEW_ZZOOMIN, VIRTKEY, CONTROL, NOINVERT
+ VK_INSERT, ID_VIEW_ZZOOMOUT, VIRTKEY, CONTROL, NOINVERT
+ "X", ID_FILE_EXIT, VIRTKEY, CONTROL, NOINVERT
+END
+
+IDR_MAINFRAME ACCELERATORS DISCARDABLE
+BEGIN
+ "7", ID_BRUSH_7SIDED, VIRTKEY, CONTROL, NOINVERT
+ "8", ID_BRUSH_8SIDED, VIRTKEY, CONTROL, NOINVERT
+ "9", ID_BRUSH_9SIDED, VIRTKEY, CONTROL, NOINVERT
+ "D", ID_VIEW_SHOWDETAIL, VIRTKEY, CONTROL, NOINVERT
+ "K", ID_SELECTION_CONNECT, VIRTKEY, CONTROL, NOINVERT
+ "L", ID_MISC_NEXTLEAKSPOT, VIRTKEY, CONTROL, NOINVERT
+ "M", ID_SELECTION_MAKE_DETAIL, VIRTKEY, CONTROL, NOINVERT
+ "O", ID_FILE_OPEN, VIRTKEY, CONTROL, NOINVERT
+ "P", ID_MISC_PREVIOUSLEAKSPOT, VIRTKEY, CONTROL, NOINVERT
+ "S", ID_FILE_SAVE, VIRTKEY, CONTROL, NOINVERT
+ VK_DELETE, ID_VIEW_ZZOOMIN, VIRTKEY, CONTROL, NOINVERT
+ VK_DOWN, ID_SELECTION_SELECT_NUDGEDOWN, VIRTKEY, ALT, NOINVERT
+ VK_INSERT, ID_VIEW_ZZOOMOUT, VIRTKEY, CONTROL, NOINVERT
+ "X", ID_FILE_EXIT, VIRTKEY, CONTROL, NOINVERT
+END
+
+IDR_ACCEL_SURFACE ACCELERATORS DISCARDABLE
+BEGIN
+ VK_ESCAPE, ID_BYEBYE, VIRTKEY, NOINVERT
+END
+
+IDR_MINIACCEL ACCELERATORS DISCARDABLE
+BEGIN
+ VK_DOWN, ID_SELECTION_SELECT_NUDGEDOWN, VIRTKEY, ALT, NOINVERT
+ VK_LEFT, ID_SELECTION_SELECT_NUDGELEFT, VIRTKEY, ALT, NOINVERT
+ VK_RIGHT, ID_SELECTION_SELECT_NUDGERIGHT, VIRTKEY, ALT, NOINVERT
+ VK_UP, ID_SELECTION_SELECT_NUDGEUP, VIRTKEY, ALT, NOINVERT
+END
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Dialog
+//
+
+IDD_FINDTEXTURE DIALOG DISCARDABLE 0, 0, 129, 53
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Find Texture"
+FONT 8, "MS Sans Serif"
+BEGIN
+ DEFPUSHBUTTON "OK",IDOK,10,30,50,14
+ PUSHBUTTON "Cancel",IDCANCEL,70,30,50,14
+ EDITTEXT IDC_EDIT1,10,10,110,14,ES_AUTOHSCROLL
+END
+
+IDD_ENTITY DIALOGEX 0, 0, 234, 355
+STYLE DS_3DLOOK | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_CLIPSIBLINGS |
+ WS_CAPTION | WS_THICKFRAME
+EXSTYLE WS_EX_TOOLWINDOW | WS_EX_CLIENTEDGE
+CAPTION "Entity"
+FONT 8, "MS Sans Serif", 0, 0, 0x1
+BEGIN
+ LISTBOX IDC_E_LIST,5,5,180,94,LBS_SORT | LBS_NOINTEGRALHEIGHT |
+ LBS_WANTKEYBOARDINPUT | WS_VSCROLL | WS_TABSTOP,
+ WS_EX_CLIENTEDGE
+ EDITTEXT IDC_E_COMMENT,5,102,180,45,ES_MULTILINE | ES_READONLY |
+ WS_VSCROLL,WS_EX_CLIENTEDGE
+ PUSHBUTTON "135",IDC_E_135,5,276,15,15
+ PUSHBUTTON "180",IDC_E_180,5,292,15,15
+ PUSHBUTTON "225",IDC_E_225,5,306,15,15
+ PUSHBUTTON "270",IDC_E_270,21,306,15,15
+ PUSHBUTTON "90",IDC_E_90,21,276,15,15
+ PUSHBUTTON "45",IDC_E_45,35,276,15,15
+ PUSHBUTTON "360",IDC_E_0,35,292,15,15
+ PUSHBUTTON "315",IDC_E_315,35,306,15,15
+ PUSHBUTTON "Up",IDC_E_UP,60,281,15,15
+ PUSHBUTTON "Dn",IDC_E_DOWN,60,297,15,15
+ CONTROL "",IDC_CHECK1,"Button",BS_AUTOCHECKBOX | WS_DISABLED |
+ WS_TABSTOP,5,151,50,8
+ CONTROL "",IDC_CHECK2,"Button",BS_AUTOCHECKBOX | WS_DISABLED |
+ WS_TABSTOP,5,161,50,8
+ CONTROL "",IDC_CHECK3,"Button",BS_AUTOCHECKBOX | WS_DISABLED |
+ WS_TABSTOP,5,171,50,8
+ CONTROL "",IDC_CHECK4,"Button",BS_AUTOCHECKBOX | WS_DISABLED |
+ WS_TABSTOP,5,181,50,8
+ CONTROL "",IDC_CHECK5,"Button",BS_AUTOCHECKBOX | WS_DISABLED |
+ WS_TABSTOP,65,151,50,8
+ CONTROL "",IDC_CHECK6,"Button",BS_AUTOCHECKBOX | WS_DISABLED |
+ WS_TABSTOP,65,161,50,8
+ CONTROL "",IDC_CHECK7,"Button",BS_AUTOCHECKBOX | WS_DISABLED |
+ WS_TABSTOP,65,171,50,8
+ CONTROL "",IDC_CHECK8,"Button",BS_AUTOCHECKBOX | WS_DISABLED |
+ WS_TABSTOP,65,181,50,8
+ CONTROL "!Easy",IDC_CHECK9,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 125,151,50,8
+ CONTROL "!Medium",IDC_CHECK10,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,125,161,50,8
+ CONTROL "!Hard",IDC_CHECK11,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,125,171,50,10
+ CONTROL "!DeathMatch",IDC_CHECK12,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,125,181,55,10
+ LISTBOX IDC_E_PROPS,5,192,180,50,LBS_SORT | LBS_USETABSTOPS |
+ LBS_NOINTEGRALHEIGHT | LBS_WANTKEYBOARDINPUT |
+ WS_VSCROLL | WS_TABSTOP,WS_EX_CLIENTEDGE
+ PUSHBUTTON "Del Key/Pair",IDC_E_DELPROP,105,281,45,15
+ EDITTEXT IDC_E_STATUS,83,298,95,30,ES_MULTILINE | ES_AUTOVSCROLL |
+ ES_AUTOHSCROLL | ES_READONLY | WS_VSCROLL | WS_HSCROLL
+ LTEXT "Key",IDC_STATIC_KEY,5,246,25,10
+ LTEXT "Value",IDC_STATIC_VALUE,5,262,25,10
+ EDITTEXT IDC_E_KEY_FIELD,40,245,145,12,ES_AUTOHSCROLL
+ EDITTEXT IDC_E_VALUE_FIELD,40,261,145,12,ES_AUTOHSCROLL
+ PUSHBUTTON "Hide",IDC_BTN_HIDE,190,328,7,6
+ PUSHBUTTON "Sound...",IDC_BTN_ASSIGNSOUND,198,247,36,11
+ PUSHBUTTON "Model...",IDC_BTN_ASSIGNMODEL,198,264,36,11
+ CONTROL "Tab1",IDC_TAB_MODE,"SysTabControl32",TCS_BOTTOM |
+ WS_BORDER,3,338,223,14
+END
+
+IDD_GAMMA DIALOGEX 0, 0, 135, 94
+STYLE DS_MODALFRAME | WS_CAPTION | WS_SYSMENU
+CAPTION "Gamma"
+FONT 8, "MS Sans Serif", 0, 0, 0x1
+BEGIN
+ EDITTEXT IDC_G_EDIT,5,8,46,13,ES_AUTOHSCROLL,WS_EX_CLIENTEDGE
+ DEFPUSHBUTTON "OK",IDOK,91,5,39,14
+ PUSHBUTTON "Cancel",IDCANCEL,91,23,39,14
+ LTEXT "0.0 is brightest\n1.0 is darkest\n\nYou must restart for the settings to take effect",
+ IDC_STATIC,7,25,61,55
+END
+
+IDD_FINDBRUSH DIALOGEX 0, 0, 127, 76
+STYLE DS_MODALFRAME | WS_CAPTION | WS_SYSMENU
+CAPTION "Find brush"
+FONT 8, "MS Sans Serif", 0, 0, 0x1
+BEGIN
+ DEFPUSHBUTTON "OK",IDOK,5,55,50,14
+ PUSHBUTTON "Cancel",IDCANCEL,65,55,50,14
+ EDITTEXT IDC_FIND_ENTITY,80,15,46,13,ES_AUTOHSCROLL,
+ WS_EX_CLIENTEDGE
+ EDITTEXT IDC_FIND_BRUSH,80,30,46,13,ES_AUTOHSCROLL,
+ WS_EX_CLIENTEDGE
+ LTEXT "Entity number",IDC_STATIC,10,15,60,8
+ LTEXT "Brush number",IDC_STATIC,10,30,65,8
+END
+
+IDD_ROTATE DIALOG DISCARDABLE 0, 0, 129, 65
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Arbitrary rotation"
+FONT 8, "MS Sans Serif"
+BEGIN
+ EDITTEXT IDC_ROTX,23,3,29,14,ES_AUTOHSCROLL
+ CONTROL "Spin1",IDC_SPIN1,"msctls_updown32",UDS_WRAP |
+ UDS_SETBUDDYINT | UDS_ALIGNRIGHT | UDS_AUTOBUDDY |
+ UDS_ARROWKEYS,52,3,11,14
+ EDITTEXT IDC_ROTY,23,21,29,14,ES_AUTOHSCROLL
+ CONTROL "Spin1",IDC_SPIN2,"msctls_updown32",UDS_WRAP |
+ UDS_SETBUDDYINT | UDS_ALIGNRIGHT | UDS_AUTOBUDDY |
+ UDS_ARROWKEYS,53,21,11,14
+ EDITTEXT IDC_ROTZ,23,39,29,14,ES_AUTOHSCROLL
+ CONTROL "Spin1",IDC_SPIN3,"msctls_updown32",UDS_WRAP |
+ UDS_SETBUDDYINT | UDS_ALIGNRIGHT | UDS_AUTOBUDDY |
+ UDS_ARROWKEYS,53,39,11,14
+ DEFPUSHBUTTON "OK",IDOK,82,3,39,14
+ PUSHBUTTON "Cancel",IDCANCEL,82,19,39,14
+ PUSHBUTTON "Apply",ID_APPLY,82,39,39,14
+ RTEXT "X",IDC_STATIC,8,6,8,8
+ RTEXT "Y",IDC_STATIC,8,24,8,8
+ RTEXT "Z",IDC_STATIC,8,42,8,8
+END
+
+IDD_SIDES DIALOGEX 0, 0, 130, 47
+STYLE DS_MODALFRAME | WS_CAPTION | WS_SYSMENU
+CAPTION "Arbitrrary sides"
+FONT 8, "MS Sans Serif", 0, 0, 0x1
+BEGIN
+ EDITTEXT IDC_SIDES,27,6,40,14,ES_AUTOHSCROLL,WS_EX_CLIENTEDGE
+ DEFPUSHBUTTON "OK",IDOK,85,4,41,14
+ PUSHBUTTON "Cancel",IDCANCEL,85,22,41,14
+ LTEXT "Sides:",IDC_STATIC,6,8,20,8
+END
+
+IDD_ABOUT DIALOG DISCARDABLE 0, 0, 275, 223
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "About Q3Radiant"
+FONT 8, "MS Sans Serif"
+BEGIN
+ DEFPUSHBUTTON "OK",IDOK,236,7,35,14
+ CONTROL 127,IDC_STATIC,"Static",SS_BITMAP | SS_CENTERIMAGE |
+ SS_REALSIZEIMAGE | SS_SUNKEN | WS_BORDER,7,7,87,80
+ GROUPBOX "OpenGL Properties",IDC_STATIC,5,93,265,56
+ LTEXT "Vendor:\t\tWHOEVER",IDC_ABOUT_GLVENDOR,10,101,253,10
+ LTEXT "Version:\t\t1.1",IDC_ABOUT_GLVERSION,10,111,249,10
+ LTEXT "Renderer:\tWHATEVER",IDC_ABOUT_GLRENDERER,10,121,253,24
+ GROUPBOX "OpenGL Extensions",IDC_STATIC,5,152,265,65
+ CONTROL "Q3 Radiant 1.0 Beta build 200f\nCopyright ©1999, 2005 Id Software, Inc.\n\n",
+ IDC_STATIC,"Static",SS_LEFTNOWORDWRAP,99,7,132,78
+ EDITTEXT IDC_ABOUT_GLEXTENSIONS,10,162,256,53,ES_MULTILINE |
+ ES_AUTOVSCROLL | ES_READONLY | WS_DISABLED | NOT
+ WS_BORDER
+END
+
+IDD_SURFACE DIALOGEX 400, 100, 412, 213
+STYLE DS_MODALFRAME | DS_3DLOOK | WS_POPUP | WS_CAPTION | WS_SYSMENU
+EXSTYLE WS_EX_CONTROLPARENT
+CAPTION "Surface inspector"
+FONT 8, "MS Sans Serif", 0, 0, 0x1
+BEGIN
+ EDITTEXT IDC_TEXTURE,59,7,107,12,ES_AUTOHSCROLL
+ EDITTEXT IDC_HSHIFT,121,25,45,12,ES_AUTOHSCROLL
+ CONTROL "Spin2",IDC_SPIN_HSHIFT,"msctls_updown32",UDS_ALIGNRIGHT |
+ UDS_AUTOBUDDY | UDS_ARROWKEYS,155,25,11,14
+ EDITTEXT IDC_VSHIFT,121,41,45,12,ES_AUTOHSCROLL
+ CONTROL "Spin2",IDC_SPIN_VSHIFT,"msctls_updown32",UDS_ALIGNRIGHT |
+ UDS_AUTOBUDDY | UDS_ARROWKEYS,155,41,11,14
+ EDITTEXT IDC_HSCALE,121,58,45,12,ES_AUTOHSCROLL
+ CONTROL "Spin2",IDC_SPIN_HSCALE,"msctls_updown32",UDS_ALIGNRIGHT |
+ UDS_AUTOBUDDY | UDS_ARROWKEYS,155,58,11,14
+ EDITTEXT IDC_VSCALE,121,75,45,12,ES_AUTOHSCROLL
+ CONTROL "Spin2",IDC_SPIN_VSCALE,"msctls_updown32",UDS_ALIGNRIGHT |
+ UDS_AUTOBUDDY | UDS_ARROWKEYS,155,75,11,14
+ EDITTEXT IDC_ROTATE,121,92,45,12,ES_AUTOHSCROLL
+ CONTROL "Spin2",IDC_SPIN_ROTATE,"msctls_updown32",UDS_ALIGNRIGHT |
+ UDS_AUTOBUDDY | UDS_ARROWKEYS,155,91,11,14
+ EDITTEXT IDC_VALUE,104,110,62,12,ES_AUTOHSCROLL
+ PUSHBUTTON "CAP",IDC_BTN_PATCHDETAILS,11,174,34,12
+ CONTROL "light",IDC_CHECK1,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 184,10,41,8
+ CONTROL "slick",IDC_CHECK2,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 184,22,41,8
+ CONTROL "sky",IDC_CHECK3,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 184,34,41,8
+ CONTROL "warp",IDC_CHECK4,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 184,46,41,8
+ CONTROL "trans33",IDC_CHECK5,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,184,58,41,8
+ CONTROL "trans66",IDC_CHECK6,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,184,70,41,8
+ CONTROL "flowing",IDC_CHECK7,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,184,82,41,8
+ CONTROL "nodraw",IDC_CHECK8,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,184,94,41,8
+ CONTROL "hint",IDC_CHECK9,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 184,106,41,8
+ CONTROL "skip",IDC_CHECK10,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 184,118,41,8
+ CONTROL "400",IDC_CHECK11,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 184,130,41,8
+ CONTROL "800",IDC_CHECK12,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 184,142,41,8
+ CONTROL "1000",IDC_CHECK13,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 184,154,41,8
+ CONTROL "2000",IDC_CHECK14,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 184,166,41,8
+ CONTROL "4000",IDC_CHECK15,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 184,178,41,8
+ CONTROL "8000",IDC_CHECK16,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 184,190,41,8
+ CONTROL "10000",IDC_CHECK17,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,234,10,48,8
+ CONTROL "20000",IDC_CHECK18,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,234,22,50,8
+ CONTROL "40000",IDC_CHECK19,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,234,34,41,8
+ CONTROL "80000",IDC_CHECK20,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,234,46,41,8
+ CONTROL "100000",IDC_CHECK21,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,234,58,41,8
+ CONTROL "200000",IDC_CHECK22,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,234,70,41,8
+ CONTROL "400000",IDC_CHECK23,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,234,82,41,8
+ CONTROL "800000",IDC_CHECK24,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,234,94,41,8
+ CONTROL "1000000",IDC_CHECK25,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,234,106,41,8
+ CONTROL "2000000",IDC_CHECK26,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,234,118,41,8
+ CONTROL "4000000",IDC_CHECK27,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,234,130,41,8
+ CONTROL "8000000",IDC_CHECK28,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,234,142,41,8
+ CONTROL "10000000",IDC_CHECK29,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,234,154,40,8
+ CONTROL "20000000",IDC_CHECK30,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,234,166,45,8
+ CONTROL "40000000",IDC_CHECK31,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,234,178,45,8
+ CONTROL "80000000",IDC_CHECK32,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,234,190,45,8
+ CONTROL "solid",IDC_CHECK33,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,304,10,41,8
+ CONTROL "window",IDC_CHECK34,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,304,22,41,8
+ CONTROL "aux",IDC_CHECK35,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 304,34,41,8
+ CONTROL "lava",IDC_CHECK36,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 304,46,41,8
+ CONTROL "slime",IDC_CHECK37,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,304,58,41,8
+ CONTROL "water",IDC_CHECK38,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,304,70,41,8
+ CONTROL "mist",IDC_CHECK39,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 304,82,41,8
+ CONTROL "80",IDC_CHECK40,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 304,94,41,8
+ CONTROL "100",IDC_CHECK41,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 304,106,41,8
+ CONTROL "200",IDC_CHECK42,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 304,118,41,8
+ CONTROL "400",IDC_CHECK43,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 304,130,41,8
+ CONTROL "800",IDC_CHECK44,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 304,142,41,8
+ CONTROL "1000",IDC_CHECK45,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 304,154,41,8
+ CONTROL "2000",IDC_CHECK46,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 304,166,41,8
+ CONTROL "4000",IDC_CHECK47,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 304,178,41,8
+ CONTROL "8000",IDC_CHECK48,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 304,190,41,8
+ CONTROL "playerclip",IDC_CHECK49,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,354,10,41,8
+ CONTROL "monsterclip",IDC_CHECK50,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,354,22,50,8
+ CONTROL "current_0",IDC_CHECK51,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,354,34,50,8
+ CONTROL "current_90",IDC_CHECK52,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,354,46,50,8
+ CONTROL "current_180",IDC_CHECK53,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,354,58,50,8
+ CONTROL "current_270",IDC_CHECK54,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,354,70,50,8
+ CONTROL "current_up",IDC_CHECK55,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,354,82,50,8
+ CONTROL "current_dn",IDC_CHECK56,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,354,94,50,8
+ CONTROL "origin",IDC_CHECK57,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,354,106,41,8
+ CONTROL "monster",IDC_CHECK58,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,354,118,41,8
+ CONTROL "corpse",IDC_CHECK59,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,354,130,41,8
+ CONTROL "detail",IDC_CHECK60,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,354,142,41,8
+ CONTROL "translucent",IDC_CHECK61,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,354,154,50,8
+ CONTROL "ladder",IDC_CHECK62,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,354,166,45,8
+ CONTROL "40000000",IDC_CHECK63,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,354,178,45,8
+ CONTROL "80000000",IDC_CHECK64,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,354,190,45,8
+ DEFPUSHBUTTON "OK",IDOK,5,194,40,14
+ PUSHBUTTON "Apply",IDAPPLY,55,194,40,14
+ PUSHBUTTON "Cancel",ID_BTN_CANCEL,105,194,40,14
+ RTEXT "Vertical shift",IDC_STATIC,51,43,65,8
+ RTEXT "Horizontal stretch",IDC_STATIC,51,60,65,8
+ RTEXT "Vertical stretch",IDC_STATIC,51,77,65,8
+ RTEXT "Rotate",IDC_STATIC,86,94,30,8
+ RTEXT "Value",IDC_STATIC,75,112,25,8
+ LTEXT "Texture",IDC_STATIC,27,9,28,8
+ GROUPBOX "Surf flags",IDC_STATIC,174,0,115,204
+ GROUPBOX "Content flags",IDC_STATIC,294,0,115,204
+ RTEXT "Horizontal shift",IDC_STATIC,51,28,65,8
+ GROUPBOX "Texturing",IDC_STATIC,5,124,161,65
+ PUSHBUTTON "Set...",IDC_BTN_PATCHRESET,50,174,34,12
+ PUSHBUTTON "Natural",IDC_BTN_PATCHNATURAL,89,174,34,12
+ PUSHBUTTON "Fit",IDC_BTN_PATCHFIT,128,174,34,12
+ LTEXT "Patch",IDC_STATIC,12,161,20,8
+ LTEXT "Brush",IDC_STATIC,12,135,19,8
+ PUSHBUTTON "Axial",IDC_BTN_AXIAL,12,145,34,12
+ PUSHBUTTON "Fit",IDC_BTN_FACEFIT,51,145,34,12
+ EDITTEXT IDC_EDIT_WIDTH,93,146,30,12,ES_AUTOHSCROLL | ES_NUMBER
+ CONTROL "Spin1",IDC_SPIN_WIDTH,"msctls_updown32",UDS_WRAP |
+ UDS_SETBUDDYINT | UDS_ALIGNRIGHT | UDS_AUTOBUDDY |
+ UDS_ARROWKEYS,117,143,11,18
+ EDITTEXT IDC_EDIT_HEIGHT,131,146,30,12,ES_AUTOHSCROLL | ES_NUMBER
+ CONTROL "Spin1",IDC_SPIN_HEIGHT,"msctls_updown32",
+ UDS_SETBUDDYINT | UDS_ALIGNRIGHT | UDS_AUTOBUDDY |
+ UDS_ARROWKEYS,153,140,11,18
+ LTEXT "Width",IDC_STATIC,94,136,20,8
+ LTEXT "Height",IDC_STATIC,131,136,22,8
+END
+
+IDD_DLG_PREFS DIALOG DISCARDABLE 0, 0, 386, 327
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Q3Radiant Preferences"
+FONT 8, "MS Sans Serif"
+BEGIN
+ COMBOBOX IDC_COMBO_WHATGAME,13,18,157,76,CBS_DROPDOWN | CBS_SORT |
+ WS_VSCROLL | WS_TABSTOP
+ CONTROL "&2 button",IDC_RADIO_MOUSE,"Button",BS_AUTORADIOBUTTON |
+ WS_GROUP,188,17,42,10
+ CONTROL "&3 button",IDC_RADIO2,"Button",BS_AUTORADIOBUTTON,235,
+ 17,42,10
+ CONTROL "",IDC_RADIO_VIEWTYPE,"Button",BS_AUTORADIOBUTTON |
+ WS_GROUP,18,69,10,10
+ CONTROL "",IDC_RADIO_VIEWTYPE2,"Button",BS_AUTORADIOBUTTON,45,69,
+ 11,10
+ CONTROL "",IDC_RADIO_VIEWTYPE3,"Button",BS_AUTORADIOBUTTON,73,69,
+ 11,10
+ CONTROL "",IDC_RADIO_VIEWTYPE4,"Button",BS_AUTORADIOBUTTON,99,69,
+ 11,10
+ CONTROL "Use SGI OpenGL",IDC_CHECK_SGIOPENGL,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,15,79,71,10
+ CONTROL "Buggy ICD",IDC_CHECK_BUGGYICD,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,15,90,50,10
+ CONTROL "OpenGL display lists",IDC_CHECK_DISPLAYLISTS,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,15,101,79,10
+ CONTROL "Solid selection boxes",IDC_CHECK_NOSTIPPLE,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,15,112,82,10
+ CONTROL "Slider1",IDC_SLIDER_CAMSPEED,"msctls_trackbar32",
+ WS_TABSTOP,128,57,92,11
+ CONTROL "Update XY views during\nmouse drags",
+ IDC_CHECK_CAMXYUPDATE,"Button",BS_AUTOCHECKBOX |
+ BS_MULTILINE | WS_TABSTOP,130,82,91,18
+ CONTROL "QE4 update model",IDC_CHECK_QE4PAINTING,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,130,102,75,10
+ CONTROL "Slider1",IDC_SLIDER_TEXTUREQUALITY,"msctls_trackbar32",
+ TBS_AUTOTICKS | WS_TABSTOP,237,68,127,11
+ CONTROL "Texture toolbar",IDC_CHECK_TEXTURETOOLBAR,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,236,94,63,10
+ CONTROL "Texture scrollbar",IDC_CHECK_TEXTURESCROLLBAR,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,236,105,68,10
+ CONTROL "Texture subset",IDC_CHECK_TEXTUREWINDOW,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,308,94,63,10
+ CONTROL "Right click to drop entities",IDC_CHECK_RIGHTCLICK,
+ "Button",BS_AUTOCHECKBOX | WS_TABSTOP,13,137,95,10
+ CONTROL "Face selection",IDC_CHECK_FACE,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,13,149,62,10
+ EDITTEXT IDC_EDIT_ROTATION,58,161,24,12,ES_AUTOHSCROLL
+ CONTROL "ALT + multi-drag",IDC_CHECK_ALTDRAG,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,114,137,68,10
+ CONTROL "Snap T to Grid",IDC_CHECK_SNAPT,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,114,149,62,10
+ CONTROL "Mouse chaser",IDC_CHECK_MOUSECHASE,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,114,160,68,10
+ CONTROL "Patch Toolbar",IDC_CHECK_WIDETOOLBAR,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,193,137,61,10
+ CONTROL "Light drawing",IDC_CHECK_LIGHTDRAW,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,193,149,58,10
+ CONTROL "Paint sizing info",IDC_CHECK_SIZEPAINT,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,193,160,65,10
+ CONTROL "Hi Color Textures",IDC_CHECK_HICOLOR,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,281,137,70,10
+ LTEXT "Startup Shaders:",IDC_STATIC,281,150,54,8
+ COMBOBOX IDC_COMBO_SHADERS,281,160,82,54,CBS_DROPDOWNLIST |
+ WS_VSCROLL | WS_TABSTOP
+ EDITTEXT IDC_EDIT_QUAKE2,13,189,229,12,ES_AUTOHSCROLL
+ PUSHBUTTON "...",IDC_BTN_BROWSE,248,190,16,11
+ CONTROL "Use internal (DLL) QBSP....",IDC_CHECK_INTERNALBSP,
+ "Button",BS_AUTOCHECKBOX | WS_TABSTOP,13,208,102,10
+ CONTROL "Don't clamp plane points",IDC_CHECK_NOCLAMP,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,13,220,93,10
+ CONTROL "Snapshots",IDC_CHECK_SNAPSHOTS,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,13,232,49,10
+ CONTROL "Use +setgame for run",IDC_CHECK_SETGAME,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,13,244,83,10
+ CONTROL "Run game after QBSP3...",IDC_CHECK_RUNQUAKE,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,121,208,96,10
+ CONTROL "Load last project on open",IDC_CHECK_LOADLAST,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,121,220,96,10
+ CONTROL "Load last map on open",IDC_CHECK_LOADLASTMAP,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,121,232,88,10
+ CONTROL "Auto save every ",IDC_CHECK_AUTOSAVE,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,121,244,66,10
+ EDITTEXT IDC_EDIT_AUTOSAVE,188,244,27,12,ES_AUTOHSCROLL |
+ ES_NUMBER
+ CONTROL "Spin1",IDC_SPIN_AUTOSAVE,"msctls_updown32",UDS_WRAP |
+ UDS_SETBUDDYINT | UDS_ALIGNRIGHT | UDS_AUTOBUDDY |
+ UDS_ARROWKEYS,212,242,11,14
+ LTEXT "Status point size:",IDC_STATIC,258,209,54,8
+ EDITTEXT IDC_EDIT_STATUSPOINTSIZE,315,207,29,12,ES_AUTOHSCROLL
+ CONTROL "Spin1",IDC_SPIN_POINTSIZE,"msctls_updown32",UDS_WRAP |
+ UDS_SETBUDDYINT | UDS_ALIGNRIGHT | UDS_AUTOBUDDY |
+ UDS_ARROWKEYS,344,206,11,14
+ LTEXT "Undo Levels:",IDC_STATIC,258,222,43,8
+ EDITTEXT IDC_EDIT_UNDOLEVELS,315,220,29,12,ES_AUTOHSCROLL
+ CONTROL "Spin1",IDC_SPIN_UNDO,"msctls_updown32",UDS_WRAP |
+ UDS_SETBUDDYINT | UDS_ALIGNRIGHT | UDS_AUTOBUDDY |
+ UDS_ARROWKEYS,344,220,11,14
+ CONTROL "Use PAK/PK3 file(s):",IDC_CHECK_PAK,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,13,263,81,10
+ EDITTEXT IDC_EDIT_PAKFILE,95,262,227,12,ES_AUTOHSCROLL
+ PUSHBUTTON "...",IDC_BTN_BROWSEPAK,328,263,16,11
+ EDITTEXT IDC_EDIT_PREFABPATH,95,279,227,12,ES_AUTOHSCROLL
+ PUSHBUTTON "...",IDC_BTN_BROWSEPREFAB,328,280,16,11
+ EDITTEXT IDC_EDIT_USERPATH,95,296,227,12,ES_AUTOHSCROLL
+ PUSHBUTTON "...",IDC_BTN_BROWSEUSERINI,328,297,16,11
+ DEFPUSHBUTTON "OK",IDOK,341,7,38,14
+ PUSHBUTTON "Cancel",IDCANCEL,341,24,38,14
+ CONTROL "Entities are DLL based",IDC_CHECK_DLLENTITIES,"Button",
+ BS_AUTOCHECKBOX | BS_TOP | BS_MULTILINE | NOT WS_VISIBLE |
+ WS_DISABLED | WS_TABSTOP,277,241,88,12
+ CONTROL "Write face color info",IDC_CHECK_FACECOLOR,"Button",
+ BS_AUTOCHECKBOX | NOT WS_VISIBLE | WS_DISABLED |
+ WS_TABSTOP,279,242,79,10
+ LTEXT "minutes",IDC_STATIC,216,245,25,8
+ CONTROL "Vertex editing",IDC_CHECK_VERTEX,"Button",
+ BS_AUTOCHECKBOX | NOT WS_VISIBLE | WS_DISABLED |
+ WS_TABSTOP,296,243,83,10
+ GROUPBOX "Mouse",IDC_STATIC,179,7,103,28
+ GROUPBOX "Views / Rendering",IDC_STATIC,7,38,372,86
+ GROUPBOX "Game path / Tool settings / Stuff that wouldn't fit anywhere else",
+ IDC_STATIC,7,179,372,139
+ CONTROL 147,IDB_VIEWDEFAULT,"Static",SS_BITMAP,13,48,21,19
+ CONTROL 148,IDB_VIEWDEFAULT2,"Static",SS_BITMAP,40,48,21,19
+ CONTROL 149,IDB_VIEWDEFAULT3,"Static",SS_BITMAP,67,48,21,19
+ GROUPBOX "New functionality:",IDC_STATIC,7,126,372,52
+ CONTROL 150,IDB_VIEWDEFAULT_Z,"Static",SS_BITMAP,93,48,21,19
+ LTEXT "slow",IDC_STATIC,131,69,15,8
+ LTEXT "fast",IDC_STATIC,204,69,12,8
+ GROUPBOX "Camera ",IDC_STATIC,126,47,100,72
+ LTEXT "Prefab path:",IDC_STATIC,54,280,40,8
+ GROUPBOX "Optimize interface for",IDC_STATIC,7,7,170,28
+ LTEXT "User INI path:",IDC_STATIC,49,298,45,8
+ LTEXT "Rotation inc:",IDC_STATIC,15,163,41,8
+ CONTROL "Use Shaders",IDC_CHECK_USESHADERS,"Button",
+ BS_AUTOCHECKBOX | NOT WS_VISIBLE | WS_DISABLED |
+ WS_TABSTOP,289,242,57,10
+ GROUPBOX "Texturing",IDC_STATIC,231,47,141,72
+ LTEXT "Quality",IDC_STATIC,237,57,22,8
+ LTEXT "Low",IDC_STATIC,239,81,14,8
+ LTEXT "High",IDC_STATIC,347,82,16,8
+END
+
+IDD_DLG_MAPINFO DIALOG DISCARDABLE 0, 0, 181, 183
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Map Info"
+FONT 8, "MS Sans Serif"
+BEGIN
+ DEFPUSHBUTTON "Close",IDOK,138,7,36,14
+ LTEXT "Total Brushes",IDC_STATIC,7,14,50,8
+ EDITTEXT IDC_EDIT_TOTALBRUSHES,66,12,40,12,ES_RIGHT |
+ ES_AUTOHSCROLL | ES_NUMBER
+ LTEXT "Total Entities",IDC_STATIC,7,30,50,8
+ EDITTEXT IDC_EDIT_TOTALENTITIES,66,28,40,12,ES_RIGHT |
+ ES_AUTOHSCROLL | ES_NUMBER
+ LTEXT "Net brush count\n(non entity)",IDC_STATIC,7,49,57,17
+ EDITTEXT IDC_EDIT_NET,66,47,40,12,ES_RIGHT | ES_AUTOHSCROLL |
+ ES_NUMBER
+ LISTBOX IDC_LIST_ENTITIES,7,81,167,95,LBS_SORT | LBS_USETABSTOPS |
+ LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
+ LTEXT "Entity breakdown",IDC_STATIC,7,71,56,8
+END
+
+IDD_DLG_ENTITYLIST DIALOG DISCARDABLE 0, 0, 294, 226
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Entities"
+FONT 8, "MS Sans Serif"
+BEGIN
+ DEFPUSHBUTTON "Close",IDOK,248,205,39,14
+ CONTROL "Tree1",IDC_TREE_ENTITY,"SysTreeView32",TVS_HASBUTTONS |
+ TVS_HASLINES | TVS_LINESATROOT | WS_BORDER | WS_TABSTOP,
+ 7,7,148,212
+ DEFPUSHBUTTON "Select",IDSELECT,161,205,39,14
+ CONTROL "List2",IDC_LIST_ENTITY,"SysListView32",LVS_REPORT |
+ LVS_SINGLESEL | LVS_EDITLABELS | LVS_NOSORTHEADER |
+ WS_BORDER | WS_TABSTOP,161,7,126,187
+END
+
+IDD_DLG_SCRIPTS DIALOG DISCARDABLE 0, 0, 212, 215
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Available Scripts"
+FONT 8, "MS Sans Serif"
+BEGIN
+ DEFPUSHBUTTON "New...",ID_NEW,166,74,39,14,WS_DISABLED
+ PUSHBUTTON "Close",IDOK,168,194,37,14
+ LISTBOX IDC_LIST_SCRIPTS,7,56,146,152,LBS_SORT |
+ LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
+ DEFPUSHBUTTON "Edit...",ID_EDIT,166,90,39,14,WS_DISABLED
+ DEFPUSHBUTTON "Run",ID_RUN,166,56,39,14
+ LTEXT "WARNING: BrushScripting is in a highly experimental state and is far from complete. If you attempt to use them it is VERY LIKELY that Q3Radiant will crash. Save your work before attempting to make use of any scripting features.",
+ IDC_STATIC,7,7,198,38
+END
+
+IDD_DLG_NEWPROJECT DIALOG DISCARDABLE 0, 0, 246, 74
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "New project"
+FONT 8, "MS Sans Serif"
+BEGIN
+ EDITTEXT IDC_EDIT_NAME,57,28,116,12,ES_AUTOHSCROLL
+ DEFPUSHBUTTON "OK",IDOK,189,7,50,14
+ PUSHBUTTON "Cancel",IDCANCEL,189,24,50,14
+ LTEXT "This will create a new directory beneath your Quake2 path based on the project name you give.",
+ IDC_STATIC,7,7,165,19
+ LTEXT "Project name:",IDC_STATIC,7,30,44,8
+ CONTROL "Include game dll files",IDC_CHECK1,"Button",
+ BS_AUTOCHECKBOX | WS_DISABLED | WS_TABSTOP,7,49,81,10
+END
+
+IDD_DLG_COMMANDLIST DIALOG DISCARDABLE 0, 0, 283, 223
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Mapped Commands"
+FONT 8, "MS Sans Serif"
+BEGIN
+ DEFPUSHBUTTON "Close",IDOK,241,202,35,14
+ LISTBOX IDC_LIST_COMMANDS,7,7,221,209,LBS_SORT | LBS_USETABSTOPS |
+ LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
+END
+
+IDD_DIALOG_SCALE DIALOG DISCARDABLE 0, 0, 122, 74
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Scale"
+FONT 8, "MS Sans Serif"
+BEGIN
+ DEFPUSHBUTTON "OK",IDOK,79,7,36,14
+ PUSHBUTTON "Cancel",IDCANCEL,79,23,36,14
+ LTEXT "X:",IDC_STATIC,7,15,8,8
+ LTEXT "Y:",IDC_STATIC,7,32,8,8
+ LTEXT "Z:",IDC_STATIC,7,49,8,8
+ EDITTEXT IDC_EDIT_X,22,13,32,12,ES_AUTOHSCROLL
+ EDITTEXT IDC_EDIT_Y,22,30,32,12,ES_AUTOHSCROLL
+ EDITTEXT IDC_EDIT_Z,22,47,32,12,ES_AUTOHSCROLL
+END
+
+IDD_DIALOG_FINDREPLACE DIALOGEX 0, 0, 222, 98
+STYLE DS_MODALFRAME | DS_3DLOOK | WS_POPUP | WS_CAPTION | WS_SYSMENU
+EXSTYLE WS_EX_CONTROLPARENT
+CAPTION "Find replace texture(s)"
+FONT 8, "MS Sans Serif", 0, 0, 0x1
+BEGIN
+ EDITTEXT IDC_EDIT_FIND,27,16,132,12,ES_AUTOHSCROLL
+ EDITTEXT IDC_EDIT_REPLACE,45,31,114,12,ES_AUTOHSCROLL
+ CONTROL "Replace within selected brushes only",
+ IDC_CHECK_SELECTED,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 7,51,133,10
+ CONTROL "Force replacement (ignore current texture name)",
+ IDC_CHECK_FORCE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,7,
+ 63,167,10
+ DEFPUSHBUTTON "OK",IDOK,175,7,40,14
+ PUSHBUTTON "Close",IDCANCEL,175,77,40,14
+ LTEXT "Find:",IDC_STATIC,7,18,16,8
+ LTEXT "Replace:",IDC_STATIC,7,33,30,8
+ DEFPUSHBUTTON "Apply",ID_BTN_APPLY,175,25,40,14
+ CONTROL "Live updates from Texture/Camera Windows",
+ IDC_CHECK_LIVE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,7,
+ 79,157,10
+END
+
+IDD_DIALOG_STAIRS DIALOG DISCARDABLE 0, 0, 196, 143
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Stairs"
+FONT 8, "MS Sans Serif"
+BEGIN
+ DEFPUSHBUTTON "OK",IDOK,147,7,42,14
+ PUSHBUTTON "Cancel",IDCANCEL,136,24,42,14
+ LTEXT "This creates a set of stairs using the selected brush as a template. You may optionally specify a rotation angle to be applied to each new step",
+ IDC_STATIC,7,7,120,37
+ LTEXT "After pressing OK, left click to select a ""height"" point for the stairs. Enough stairs will be created to consume the hieght (Z) between the selected brush and the point you specify",
+ IDC_STATIC,7,46,116,53
+ LTEXT "Rotation per step:",IDC_STATIC,7,104,57,8
+ EDITTEXT IDC_EDIT_ROTATION,69,102,40,12,ES_AUTOHSCROLL
+END
+
+IDD_DIALOG_INPUT DIALOG DISCARDABLE 0, 0, 171, 173
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "BrushScript Input"
+FONT 8, "MS Sans Serif"
+BEGIN
+ DEFPUSHBUTTON "OK",IDOK,127,7,37,14
+ PUSHBUTTON "Cancel",IDCANCEL,127,24,37,14
+ LTEXT "Field1:",IDC_STATIC_FIELD1,7,13,96,8
+ EDITTEXT IDC_EDIT_FIELD1,7,23,47,14,ES_AUTOHSCROLL
+ LTEXT "Field1:",IDC_STATIC_FIELD2,7,41,105,8
+ EDITTEXT IDC_EDIT_FIELD2,7,51,47,14,ES_AUTOHSCROLL
+ LTEXT "Field1:",IDC_STATIC_FIELD3,7,71,115,8
+ EDITTEXT IDC_EDIT_FIELD3,7,81,47,14,ES_AUTOHSCROLL
+ LTEXT "Field1:",IDC_STATIC_FIELD4,7,103,129,8
+ EDITTEXT IDC_EDIT_FIELD4,7,113,47,14,ES_AUTOHSCROLL
+ LTEXT "Field1:",IDC_STATIC_FIELD5,7,133,135,8
+ EDITTEXT IDC_EDIT_FIELD5,7,142,47,14,ES_AUTOHSCROLL
+END
+
+IDD_DLG_INFORMATION DIALOG DISCARDABLE 0, 0, 186, 95
+STYLE WS_POPUP | WS_CAPTION
+CAPTION "Information"
+FONT 8, "MS Sans Serif"
+BEGIN
+ EDITTEXT IDC_EDIT1,7,7,172,81,ES_MULTILINE | WS_DISABLED |
+ WS_VSCROLL
+END
+
+IDD_PROJECT DIALOGEX 250, 100, 341, 335
+STYLE DS_MODALFRAME | WS_CAPTION | WS_SYSMENU
+CAPTION "Project Settings"
+FONT 8, "MS Sans Serif", 0, 0, 0x1
+BEGIN
+ EDITTEXT IDC_PRJBASEPATH,75,20,205,12,ES_AUTOHSCROLL
+ EDITTEXT IDC_PRJMAPSPATH,75,40,205,12,ES_AUTOHSCROLL
+ EDITTEXT IDC_PRJRSHCMD,75,60,205,12,ES_AUTOHSCROLL
+ EDITTEXT IDC_PRJREMOTEBASE,75,80,205,12,ES_AUTOHSCROLL
+ EDITTEXT IDC_PRJENTITYPATH,75,100,205,12,ES_AUTOHSCROLL
+ EDITTEXT IDC_PRJTEXPATH,75,120,205,12,ES_AUTOHSCROLL
+ LISTBOX IDC_CMD_LIST,10,157,270,90,LBS_SORT |
+ LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP,
+ WS_EX_CLIENTEDGE
+ PUSHBUTTON "Add...",IDC_ADDCMD,290,150,45,13
+ PUSHBUTTON "Change...",IDC_EDITCMD,290,167,45,13
+ PUSHBUTTON "Remove",IDC_REMCMD,290,184,45,13
+ CONTROL "Use brush primitives in MAP files",IDC_CHECK_BPRIMIT,
+ "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,270,136,9
+ DEFPUSHBUTTON "OK",IDOK,290,10,45,13
+ PUSHBUTTON "Cancel",IDCANCEL,290,26,45,13
+ GROUPBOX "Project settings",IDC_STATIC,5,7,280,133
+ LTEXT "basepath",IDC_STATIC,42,22,30,8
+ LTEXT "rshcmd",IDC_STATIC,48,62,24,8
+ LTEXT "remotebasepath",IDC_STATIC,20,82,52,8
+ LTEXT "entitypath",IDC_STATIC,40,102,32,8
+ LTEXT "texturepath",IDC_STATIC,36,122,36,8
+ GROUPBOX "Menu commands",IDC_STATIC,5,146,280,105
+ LTEXT "mapspath",IDC_STATIC,40,42,32,8
+ GROUPBOX "Misc settings",IDC_STATIC,5,258,280,73
+END
+
+IDD_ADDCMD DIALOG DISCARDABLE 300, 200, 312, 65
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Add command"
+FONT 8, "MS Sans Serif"
+BEGIN
+ DEFPUSHBUTTON "OK",IDOK,116,44,37,13
+ PUSHBUTTON "Cancel",IDCANCEL,159,44,37,13
+ EDITTEXT IDC_CMDMENUTEXT,44,8,254,12,ES_AUTOHSCROLL
+ EDITTEXT IDC_CMDCOMMAND,44,26,254,12,ES_AUTOHSCROLL
+ LTEXT "Menu text",IDC_STATIC,5,10,32,8
+ LTEXT "Command",IDC_STATIC,5,28,32,8
+END
+
+IDD_TEXTUREBAR DIALOG DISCARDABLE 0, 0, 313, 19
+STYLE WS_CHILD
+FONT 8, "MS Sans Serif"
+BEGIN
+ EDITTEXT IDC_HSHIFT,33,4,32,12,ES_AUTOHSCROLL
+ CONTROL "Spin1",IDC_SPIN_HSHIFT,"msctls_updown32",UDS_ALIGNRIGHT |
+ UDS_AUTOBUDDY | UDS_ARROWKEYS,56,3,10,14
+ EDITTEXT IDC_VSHIFT,76,4,32,12,ES_AUTOHSCROLL
+ CONTROL "Spin1",IDC_SPIN_VSHIFT,"msctls_updown32",UDS_ALIGNRIGHT |
+ UDS_AUTOBUDDY | UDS_ARROWKEYS,97,3,11,14
+ EDITTEXT IDC_HSCALE,143,4,32,12,ES_AUTOHSCROLL
+ CONTROL "Spin1",IDC_SPIN_HSCALE,"msctls_updown32",UDS_ALIGNRIGHT |
+ UDS_AUTOBUDDY | UDS_ARROWKEYS,164,3,11,14
+ EDITTEXT IDC_VSCALE,188,4,32,12,ES_AUTOHSCROLL
+ CONTROL "Spin1",IDC_SPIN_VSCALE,"msctls_updown32",UDS_ALIGNRIGHT |
+ UDS_AUTOBUDDY | UDS_ARROWKEYS,210,3,11,14
+ EDITTEXT IDC_ROTATE,252,4,32,12,ES_AUTOHSCROLL
+ CONTROL "Spin1",IDC_SPIN_ROTATE,"msctls_updown32",UDS_ALIGNRIGHT |
+ UDS_AUTOBUDDY | UDS_ARROWKEYS,272,3,11,14
+ LTEXT "Shift H",IDC_STATIC,7,6,22,8
+ LTEXT "V",IDC_STATIC,68,6,8,8
+ LTEXT "Scale H",IDC_STATIC,112,6,26,8
+ LTEXT "V",IDC_STATIC,180,6,8,8
+ LTEXT "Rotate",IDC_STATIC,226,6,22,8
+ DEFPUSHBUTTON "Button1",IDC_BTN_APPLYTEXTURESTUFF,278,2,11,8,NOT
+ WS_VISIBLE | NOT WS_TABSTOP
+ EDITTEXT IDC_EDIT_ROTATEAMT,287,4,20,12,ES_AUTOHSCROLL
+END
+
+IDD_DIALOG_TEXTURELIST DIALOG DISCARDABLE 0, 0, 257, 279
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Textures"
+FONT 8, "MS Sans Serif"
+BEGIN
+ DEFPUSHBUTTON "&Load",IDOK,205,7,45,14
+ PUSHBUTTON "Close",IDCANCEL,205,23,45,14
+ LISTBOX IDC_LIST_TEXTURES,7,7,189,265,LBS_SORT |
+ LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
+END
+
+IDD_DIALOG_NEWPATCH DIALOG DISCARDABLE 0, 0, 129, 58
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Patch density"
+FONT 8, "MS Sans Serif"
+BEGIN
+ DEFPUSHBUTTON "OK",IDOK,90,7,32,14
+ PUSHBUTTON "Cancel",IDCANCEL,90,24,32,14
+ LTEXT "Width:",IDC_STATIC,9,9,22,8
+ LTEXT "Height:",IDC_STATIC,7,27,24,8
+ COMBOBOX IDC_COMBO_WIDTH,38,7,33,51,CBS_DROPDOWNLIST | WS_VSCROLL |
+ WS_TABSTOP
+ COMBOBOX IDC_COMBO_HEIGHT,38,25,33,51,CBS_DROPDOWNLIST |
+ WS_VSCROLL | WS_TABSTOP
+END
+
+IDD_DIALOG_TEXTURELAYOUT DIALOG DISCARDABLE 0, 0, 186, 95
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Patch texture layout"
+FONT 8, "MS Sans Serif"
+BEGIN
+ DEFPUSHBUTTON "OK",IDOK,141,7,38,14
+ PUSHBUTTON "Cancel",IDCANCEL,141,24,38,14
+ LTEXT "Texture will be fit across the patch based on the x and y values given. Values of 1x1 will ""fit"" the texture. 2x2 will repeat it twice, etc.",
+ IDC_STATIC,7,7,122,36
+ LTEXT "Texture x:",IDC_STATIC,7,48,32,8
+ EDITTEXT IDC_EDIT_X,42,46,30,12,ES_AUTOHSCROLL
+ LTEXT "Texture y:",IDC_STATIC,7,64,32,8
+ EDITTEXT IDC_EDIT_Y,42,62,30,12,ES_AUTOHSCROLL
+END
+
+IDD_DIALOG_CAP DIALOG DISCARDABLE 0, 0, 171, 84
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Cap"
+FONT 8, "MS Sans Serif"
+BEGIN
+ DEFPUSHBUTTON "OK",IDOK,123,7,41,14
+ PUSHBUTTON "Cancel",IDCANCEL,123,25,41,14
+ CONTROL "Bevel",IDC_RADIO_CAP,"Button",BS_AUTORADIOBUTTON |
+ WS_GROUP,31,10,50,10
+ CONTROL "Endcap",IDC_RADIO_CAP2,"Button",BS_AUTORADIOBUTTON,31,
+ 28,50,10
+ CONTROL "Inverted Bevel",IDC_RADIO_CAP3,"Button",
+ BS_AUTORADIOBUTTON,31,47,68,10
+ CONTROL "Inverted Endcap",IDC_RADIO_CAP4,"Button",
+ BS_AUTORADIOBUTTON,31,65,75,10
+ CONTROL 177,IDC_STATIC,"Static",SS_BITMAP | SS_REALSIZEIMAGE |
+ SS_SUNKEN,7,7,18,15
+ CONTROL 178,IDC_STATIC,"Static",SS_BITMAP | SS_REALSIZEIMAGE |
+ SS_SUNKEN,7,44,18,15
+ CONTROL 176,IDC_STATIC,"Static",SS_BITMAP | SS_REALSIZEIMAGE |
+ SS_SUNKEN,7,26,18,15
+ CONTROL 175,IDC_STATIC,"Static",SS_BITMAP | SS_REALSIZEIMAGE |
+ SS_SUNKEN,7,63,17,14
+END
+
+IDD_DIALOG_THICKEN DIALOG DISCARDABLE 0, 0, 204, 63
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Thicken Patch"
+FONT 8, "MS Sans Serif"
+BEGIN
+ DEFPUSHBUTTON "OK",IDOK,158,7,39,14
+ PUSHBUTTON "Cancel",IDCANCEL,158,24,39,14
+ LTEXT "This produces a func_grouped set of patches that contains the original patch along with the 'thick' patch and an optional set of seam patches. ",
+ IDC_STATIC,7,7,145,33
+ EDITTEXT IDC_EDIT_AMOUNT,38,42,26,12,ES_AUTOHSCROLL
+ LTEXT "Amount:",IDC_STATIC,7,44,27,8
+ CONTROL "Seams",IDC_CHECK_SEAMS,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,74,43,37,10
+END
+
+IDD_DIALOG_PATCH DIALOG DISCARDABLE 0, 0, 272, 178
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Patch Properties"
+FONT 8, "MS Sans Serif"
+BEGIN
+ COMBOBOX IDC_COMBO_ROW,15,29,34,79,CBS_DROPDOWNLIST | CBS_SORT |
+ WS_VSCROLL | WS_TABSTOP
+ COMBOBOX IDC_COMBO_COL,54,29,34,84,CBS_DROPDOWNLIST | CBS_SORT |
+ WS_VSCROLL | WS_TABSTOP
+ EDITTEXT IDC_EDIT_X,34,49,54,12,ES_AUTOHSCROLL
+ EDITTEXT IDC_EDIT_Y,33,64,55,12,ES_AUTOHSCROLL
+ EDITTEXT IDC_EDIT_Z,33,81,55,12,ES_AUTOHSCROLL
+ EDITTEXT IDC_EDIT_S,33,98,55,12,ES_AUTOHSCROLL
+ EDITTEXT IDC_EDIT_T,33,115,55,12,ES_AUTOHSCROLL
+ COMBOBOX IDC_COMBO_TYPE,33,134,55,79,CBS_DROPDOWNLIST | CBS_SORT |
+ WS_VSCROLL | WS_TABSTOP
+ EDITTEXT IDC_EDIT_NAME,106,29,144,12,ES_AUTOHSCROLL
+ EDITTEXT IDC_HSHIFT,107,48,45,12,ES_AUTOHSCROLL
+ CONTROL "Spin2",IDC_SPIN_HSHIFT,"msctls_updown32",UDS_ALIGNRIGHT |
+ UDS_AUTOBUDDY | UDS_ARROWKEYS,141,48,11,14
+ EDITTEXT IDC_VSHIFT,107,64,45,12,ES_AUTOHSCROLL
+ CONTROL "Spin2",IDC_SPIN_VSHIFT,"msctls_updown32",UDS_ALIGNRIGHT |
+ UDS_AUTOBUDDY | UDS_ARROWKEYS,141,64,11,14
+ EDITTEXT IDC_HSCALE,107,81,45,12,ES_AUTOHSCROLL
+ CONTROL "Spin2",IDC_SPIN_HSCALE,"msctls_updown32",UDS_ALIGNRIGHT |
+ UDS_AUTOBUDDY | UDS_ARROWKEYS,141,81,11,14
+ EDITTEXT IDC_VSCALE,107,98,45,12,ES_AUTOHSCROLL
+ CONTROL "Spin2",IDC_SPIN_VSCALE,"msctls_updown32",UDS_ALIGNRIGHT |
+ UDS_AUTOBUDDY | UDS_ARROWKEYS,141,98,11,14
+ EDITTEXT IDC_ROTATE,107,115,45,12,ES_AUTOHSCROLL
+ CONTROL "Spin2",IDC_SPIN_ROTATE,"msctls_updown32",UDS_ALIGNRIGHT |
+ UDS_AUTOBUDDY | UDS_ARROWKEYS,141,114,11,14
+ PUSHBUTTON "CAP",IDC_BTN_PATCHDETAILS,109,134,32,13
+ PUSHBUTTON "Set...",IDC_BTN_PATCHRESET,148,134,32,13
+ PUSHBUTTON "Natural",IDC_BTN_PATCHNATURAL,185,134,32,13
+ PUSHBUTTON "Fit",IDC_BTN_PATCHFIT,225,134,32,13
+ PUSHBUTTON "Apply",ID_APPLY,184,159,38,12
+ DEFPUSHBUTTON "Done",IDOK,227,159,38,12
+ LTEXT "Row:",IDC_STATIC,15,17,18,8
+ LTEXT "Column:",IDC_STATIC,54,17,26,8
+ LTEXT "X:",IDC_STATIC,21,51,8,8
+ LTEXT "Y:",IDC_STATIC,21,66,8,8
+ LTEXT "Z:",IDC_STATIC,21,83,8,8
+ LTEXT "S:",IDC_STATIC,21,100,8,8
+ LTEXT "T:",IDC_STATIC,21,117,8,8
+ LTEXT "Name:",IDC_STATIC,106,17,22,8
+ LTEXT "Vertical shift",IDC_STATIC,157,66,65,8
+ LTEXT "Horizontal stretch",IDC_STATIC,157,83,65,8
+ LTEXT "Vertical stretch",IDC_STATIC,157,100,65,8
+ LTEXT "Rotate",IDC_STATIC,157,117,30,8
+ LTEXT "Horizontal shift",IDC_STATIC,157,51,65,8
+ GROUPBOX "Texturing",IDC_STATIC,99,7,166,148
+ GROUPBOX "Details",IDC_STATIC,7,7,87,148
+ LTEXT "Type:",IDC_STATIC,13,136,19,8
+END
+
+IDD_PLAYWAVE DIALOG DISCARDABLE 0, 0, 33, 15
+STYLE WS_CHILD
+FONT 8, "MS Sans Serif"
+BEGIN
+ PUSHBUTTON "Play",IDC_BTN_PLAY,0,0,33,15
+END
+
+IDD_TEXLIST DIALOG DISCARDABLE 0, 0, 251, 273
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Load multiple texture paths"
+FONT 8, "MS Sans Serif"
+BEGIN
+ DEFPUSHBUTTON "Load",IDOK,194,7,50,14
+ PUSHBUTTON "Cancel",IDCANCEL,194,24,50,14
+ LISTBOX IDC_LIST_TEXTURES,7,7,179,259,LBS_SORT |
+ LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
+END
+
+IDD_DLG_GROUP DIALOG DISCARDABLE 0, 0, 194, 241
+STYLE DS_CONTROL | WS_CHILD | WS_BORDER
+FONT 8, "MS Sans Serif"
+BEGIN
+ CONTROL "Tree1",IDC_TREE_GROUP,"SysTreeView32",TVS_HASBUTTONS |
+ TVS_HASLINES | TVS_LINESATROOT | TVS_EDITLABELS |
+ WS_BORDER | WS_TABSTOP,7,7,180,209
+ PUSHBUTTON "Add...",IDC_BTN_ADD,7,221,33,12
+ PUSHBUTTON "Delete",IDC_BTN_DEL,83,221,33,12
+ PUSHBUTTON "Edit...",IDC_BTN_EDIT,44,221,33,12
+END
+
+IDD_NEWNAME DIALOG DISCARDABLE 0, 0, 186, 46
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "New"
+FONT 8, "MS Sans Serif"
+BEGIN
+ EDITTEXT IDC_EDIT_NAME,31,10,106,12,ES_AUTOHSCROLL
+ DEFPUSHBUTTON "OK",IDOK,143,7,36,14
+ PUSHBUTTON "Cancel",IDCANCEL,143,24,36,14
+ LTEXT "Name:",IDC_STATIC,7,12,22,8
+END
+
+IDD_DLG_CAMERA DIALOG DISCARDABLE 0, 0, 277, 295
+STYLE DS_MODALFRAME | DS_3DLOOK | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Camera Inspector"
+FONT 8, "MS Sans Serif"
+BEGIN
+ DEFPUSHBUTTON "Close",IDOK,220,274,50,14
+ LTEXT "Name",IDC_STATIC,7,14,24,8
+ EDITTEXT IDC_EDIT_CAM_NAME,32,12,154,12,ES_AUTOHSCROLL
+ LTEXT "Edit >",IDC_STATIC,11,70,20,8
+ COMBOBOX IDC_COMBO_SPLINES,33,68,154,81,CBS_DROPDOWNLIST |
+ WS_VSCROLL | WS_TABSTOP
+ PUSHBUTTON "Add Target...",IDC_BTN_ADDTARGET,34,54,53,11
+ SCROLLBAR IDC_SCROLLBAR_SEGMENT,14,168,165,10
+ LTEXT "Length ( seconds )",IDC_STATIC,14,140,60,8
+ EDITTEXT IDC_EDIT_LENGTH,75,138,30,12,ES_AUTOHSCROLL
+ LTEXT "Current Time:",IDC_STATIC,14,156,43,8
+ LISTBOX IDC_LIST_EVENTS,14,207,152,65,LBS_USETABSTOPS |
+ LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
+ GROUPBOX "Time",IDC_STATIC,7,129,200,159
+ EDITTEXT IDC_EDIT_SEGMENT,61,154,40,12,ES_RIGHT | ES_AUTOHSCROLL |
+ ES_READONLY
+ LTEXT "Events",IDC_STATIC,14,195,23,8
+ PUSHBUTTON "Add...",IDC_BTN_ADDEVENT,171,207,32,11
+ PUSHBUTTON "Del",IDC_BTN_DELEVENT,171,221,32,11
+ DEFPUSHBUTTON "Apply",IDAPPLY,220,91,50,14
+ DEFPUSHBUTTON "Load...",ID_FILE_OPEN,220,26,50,14
+ DEFPUSHBUTTON "Save...",ID_FILE_SAVE,220,42,50,14
+ DEFPUSHBUTTON "New",ID_FILE_NEW,220,7,50,14
+ DEFPUSHBUTTON "Preview",ID_TESTCAMERA,220,109,50,14
+ CONTROL "Track Camera",IDC_CHECK_TRACKCAMERA,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,14,180,61,10
+ LTEXT "of",IDC_STATIC,109,155,11,9
+ EDITTEXT IDC_EDIT_TOTALSEGMENTS,122,154,35,12,ES_RIGHT |
+ ES_AUTOHSCROLL | ES_READONLY
+ GROUPBOX "Path and Target editing",IDC_STATIC,7,43,201,83
+ CONTROL "Edit Points",IDC_RADIO_EDITPOINTS,"Button",
+ BS_AUTORADIOBUTTON | WS_GROUP,13,86,52,9
+ CONTROL "Add Points",IDC_RADIO_EDITPOINTS2,"Button",
+ BS_AUTORADIOBUTTON,13,97,52,9
+ PUSHBUTTON "Delete Selected",IDC_BTN_DELETEPOINTS,13,109,61,11
+ LTEXT "Type:",IDC_STATIC,7,30,20,9
+ EDITTEXT IDC_EDIT_TYPE,32,28,48,12,ES_AUTOHSCROLL | ES_READONLY
+ PUSHBUTTON "Select All",IDC_BTN_SELECTALL,78,109,61,11
+END
+
+IDD_DLG_CAMERAEVENT DIALOG DISCARDABLE 0, 0, 166, 158
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Camera Event"
+FONT 8, "MS Sans Serif"
+BEGIN
+ CONTROL "Wait",IDC_RADIO_EVENT,"Button",BS_AUTORADIOBUTTON |
+ WS_GROUP,14,18,31,10
+ CONTROL "Target wait",IDC_RADIO9,"Button",BS_AUTORADIOBUTTON,14,
+ 28,51,10
+ CONTROL "Speed",IDC_RADIO10,"Button",BS_AUTORADIOBUTTON,14,38,37,
+ 10
+ CONTROL "Change target",IDC_RADIO5,"Button",BS_AUTORADIOBUTTON,
+ 14,48,61,10
+ CONTROL "Snap target",IDC_RADIO6,"Button",BS_AUTORADIOBUTTON,14,
+ 58,53,10
+ CONTROL "FOV",IDC_RADIO7,"Button",BS_AUTORADIOBUTTON,14,68,30,10
+ CONTROL "Run script",IDC_RADIO8,"Button",BS_AUTORADIOBUTTON,14,
+ 78,48,10
+ CONTROL "Trigger",IDC_RADIO11,"Button",BS_AUTORADIOBUTTON,14,88,
+ 38,10
+ CONTROL "Stop",IDC_RADIO12,"Button",BS_AUTORADIOBUTTON,15,99,31,
+ 10
+ EDITTEXT IDC_EDIT_PARAM,7,133,124,12,ES_AUTOHSCROLL
+ DEFPUSHBUTTON "OK",IDOK,124,7,35,14
+ PUSHBUTTON "Cancel",IDCANCEL,123,24,35,14
+ GROUPBOX "Type",IDC_STATIC,7,7,81,109
+ LTEXT "Paremeter:",IDC_STATIC,7,121,35,8
+END
+
+IDD_DLG_CAMERATARGET DIALOG DISCARDABLE 0, 0, 194, 93
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Camera Target"
+FONT 8, "MS Sans Serif"
+BEGIN
+ CONTROL "Fixed",IDC_RADIO_FIXED,"Button",BS_AUTORADIOBUTTON |
+ WS_GROUP,15,38,37,10
+ CONTROL "Interpolated",IDC_RADIO2,"Button",BS_AUTORADIOBUTTON,15,
+ 49,60,11
+ CONTROL "Spline",IDC_RADIO3,"Button",BS_AUTORADIOBUTTON,15,61,60,
+ 11
+ DEFPUSHBUTTON "OK",IDOK,146,7,41,11
+ PUSHBUTTON "Cancel",IDCANCEL,146,21,41,11
+ LTEXT "Name:",IDC_STATIC,7,7,23,10
+ EDITTEXT IDC_EDIT_NAME,32,7,105,12,ES_AUTOHSCROLL
+ GROUPBOX "Type",IDC_STATIC,7,26,130,53
+END
+
+
+#ifndef _MAC
+/////////////////////////////////////////////////////////////////////////////
+//
+// Version
+//
+
+VS_VERSION_INFO VERSIONINFO
+ FILEVERSION 1,0,0,1
+ PRODUCTVERSION 1,0,0,1
+ FILEFLAGSMASK 0x3fL
+#ifdef _DEBUG
+ FILEFLAGS 0x1L
+#else
+ FILEFLAGS 0x0L
+#endif
+ FILEOS 0x4L
+ FILETYPE 0x1L
+ FILESUBTYPE 0x0L
+BEGIN
+ BLOCK "StringFileInfo"
+ BEGIN
+ BLOCK "040904b0"
+ BEGIN
+ VALUE "Comments", "\0"
+ VALUE "CompanyName", "\0"
+ VALUE "FileDescription", "Radiant MFC Application\0"
+ VALUE "FileVersion", "1, 0, 0, 1\0"
+ VALUE "InternalName", "Radiant\0"
+ VALUE "LegalCopyright", "Copyright (C) 1997\0"
+ VALUE "LegalTrademarks", "\0"
+ VALUE "OriginalFilename", "Radiant.EXE\0"
+ VALUE "PrivateBuild", "\0"
+ VALUE "ProductName", "Radiant Application\0"
+ VALUE "ProductVersion", "1, 0, 0, 1\0"
+ VALUE "SpecialBuild", "\0"
+ END
+ END
+ BLOCK "VarFileInfo"
+ BEGIN
+ VALUE "Translation", 0x409, 1200
+ END
+END
+
+#endif // !_MAC
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// DESIGNINFO
+//
+
+#ifdef APSTUDIO_INVOKED
+GUIDELINES DESIGNINFO DISCARDABLE
+BEGIN
+ IDD_GAMMA, DIALOG
+ BEGIN
+ RIGHTMARGIN, 127
+ BOTTOMMARGIN, 76
+ END
+
+ IDD_SIDES, DIALOG
+ BEGIN
+ RIGHTMARGIN, 126
+ BOTTOMMARGIN, 45
+ END
+
+ IDD_DLG_PREFS, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 379
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 320
+ END
+
+ IDD_DLG_MAPINFO, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 174
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 176
+ END
+
+ IDD_DLG_ENTITYLIST, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 287
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 219
+ END
+
+ IDD_DLG_SCRIPTS, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 205
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 208
+ END
+
+ IDD_DLG_NEWPROJECT, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 239
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 67
+ END
+
+ IDD_DLG_COMMANDLIST, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 276
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 216
+ END
+
+ IDD_DIALOG_SCALE, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 115
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 67
+ END
+
+ IDD_DIALOG_FINDREPLACE, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 215
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 80
+ END
+
+ IDD_DIALOG_STAIRS, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 189
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 136
+ END
+
+ IDD_DIALOG_INPUT, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 164
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 166
+ END
+
+ IDD_DLG_INFORMATION, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 179
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 88
+ END
+
+ IDD_ADDCMD, DIALOG
+ BEGIN
+ BOTTOMMARGIN, 60
+ END
+
+ IDD_DIALOG_TEXTURELIST, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 250
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 272
+ END
+
+ IDD_DIALOG_NEWPATCH, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 122
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 51
+ END
+
+ IDD_DIALOG_TEXTURELAYOUT, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 179
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 88
+ END
+
+ IDD_DIALOG_CAP, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 164
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 77
+ END
+
+ IDD_DIALOG_THICKEN, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 197
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 56
+ END
+
+ IDD_DIALOG_PATCH, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 265
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 171
+ END
+
+ IDD_TEXLIST, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 244
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 266
+ END
+
+ IDD_DLG_GROUP, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 187
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 233
+ END
+
+ IDD_NEWNAME, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 179
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 39
+ END
+
+ IDD_DLG_CAMERA, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 270
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 288
+ END
+
+ IDD_DLG_CAMERAEVENT, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 159
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 151
+ END
+
+ IDD_DLG_CAMERATARGET, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 187
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 86
+ END
+END
+#endif // APSTUDIO_INVOKED
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Dialog Info
+//
+
+IDD_DIALOG_NEWPATCH DLGINIT
+BEGIN
+ IDC_COMBO_WIDTH, 0x403, 2, 0
+0x0033,
+ IDC_COMBO_WIDTH, 0x403, 2, 0
+0x0035,
+ IDC_COMBO_WIDTH, 0x403, 2, 0
+0x0037,
+ IDC_COMBO_WIDTH, 0x403, 2, 0
+0x0039,
+ IDC_COMBO_WIDTH, 0x403, 3, 0
+0x3131, "\000"
+ IDC_COMBO_WIDTH, 0x403, 3, 0
+0x3331, "\000"
+ IDC_COMBO_WIDTH, 0x403, 3, 0
+0x3531, "\000"
+ IDC_COMBO_HEIGHT, 0x403, 2, 0
+0x0033,
+ IDC_COMBO_HEIGHT, 0x403, 2, 0
+0x0035,
+ IDC_COMBO_HEIGHT, 0x403, 2, 0
+0x0037,
+ IDC_COMBO_HEIGHT, 0x403, 2, 0
+0x0039,
+ IDC_COMBO_HEIGHT, 0x403, 3, 0
+0x3131, "\000"
+ IDC_COMBO_HEIGHT, 0x403, 3, 0
+0x3331, "\000"
+ IDC_COMBO_HEIGHT, 0x403, 3, 0
+0x3531, "\000"
+ 0
+END
+
+IDD_DLG_PREFS DLGINIT
+BEGIN
+ IDC_COMBO_SHADERS, 0x403, 5, 0
+0x6f4e, 0x656e, "\000"
+ IDC_COMBO_SHADERS, 0x403, 7, 0
+0x6f43, 0x6d6d, 0x6e6f, "\000"
+ IDC_COMBO_SHADERS, 0x403, 4, 0
+0x6c41, 0x006c,
+ 0
+END
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// String Table
+//
+
+STRINGTABLE PRELOAD DISCARDABLE
+BEGIN
+ IDR_MAINFRAME "Q3Radiant"
+ IDR_RADIANTYPE "\nRadian\nRadian\n\n\nRadiant.Document\nRadian Document"
+ IDS_STRING1 "DOOM"
+END
+
+STRINGTABLE PRELOAD DISCARDABLE
+BEGIN
+ AFX_IDS_APP_TITLE "Radiant"
+ AFX_IDS_IDLEMESSAGE "Ready"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_INDICATOR_EXT "EXT"
+ ID_INDICATOR_CAPS "CAP"
+ ID_INDICATOR_NUM "NUM"
+ ID_INDICATOR_SCRL "SCRL"
+ ID_INDICATOR_OVR "OVR"
+ ID_INDICATOR_REC "REC"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_FILE_NEW "Create a new document\nNew"
+ ID_FILE_OPEN "Open an existing map\nOpen"
+ ID_FILE_CLOSE "Close the active document\nClose"
+ ID_FILE_SAVE "Save the active map\nSave"
+ ID_FILE_SAVE_AS "Save the active document with a new name\nSave As"
+ ID_FILE_PAGE_SETUP "Change the printing options\nPage Setup"
+ ID_FILE_PRINT_SETUP "Change the printer and printing options\nPrint Setup"
+ ID_FILE_PRINT "Print the active document\nPrint"
+ ID_FILE_PRINT_PREVIEW "Display full pages\nPrint Preview"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_APP_ABOUT "Display program information, version number and copyright\nAbout"
+ ID_APP_EXIT "Quit the application; prompts to save documents\nExit"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_FILE_MRU_FILE1 "Open this document"
+ ID_FILE_MRU_FILE2 "Open this document"
+ ID_FILE_MRU_FILE3 "Open this document"
+ ID_FILE_MRU_FILE4 "Open this document"
+ ID_FILE_MRU_FILE5 "Open this document"
+ ID_FILE_MRU_FILE6 "Open this document"
+ ID_FILE_MRU_FILE7 "Open this document"
+ ID_FILE_MRU_FILE8 "Open this document"
+ ID_FILE_MRU_FILE9 "Open this document"
+ ID_FILE_MRU_FILE10 "Open this document"
+ ID_FILE_MRU_FILE11 "Open this document"
+ ID_FILE_MRU_FILE12 "Open this document"
+ ID_FILE_MRU_FILE13 "Open this document"
+ ID_FILE_MRU_FILE14 "Open this document"
+ ID_FILE_MRU_FILE15 "Open this document"
+ ID_FILE_MRU_FILE16 "Open this document"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_NEXT_PANE "Switch to the next window pane\nNext Pane"
+ ID_PREV_PANE "Switch back to the previous window pane\nPrevious Pane"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_WINDOW_NEW "Open another window for the active document\nNew Window"
+ ID_WINDOW_ARRANGE "Arrange icons at the bottom of the window\nArrange Icons"
+ ID_WINDOW_CASCADE "Arrange windows so they overlap\nCascade Windows"
+ ID_WINDOW_TILE_HORZ "Arrange windows as non-overlapping tiles\nTile Windows"
+ ID_WINDOW_TILE_VERT "Arrange windows as non-overlapping tiles\nTile Windows"
+ ID_WINDOW_SPLIT "Split the active window into panes\nSplit"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_EDIT_CLEAR "Erase the selection\nErase"
+ ID_EDIT_CLEAR_ALL "Erase everything\nErase All"
+ ID_EDIT_COPY "Copy the selection and put it on the Clipboard\nCopy"
+ ID_EDIT_CUT "Cut the selection and put it on the Clipboard\nCut"
+ ID_EDIT_FIND "Find the specified text\nFind"
+ ID_EDIT_PASTE "Insert Clipboard contents\nPaste"
+ ID_EDIT_REPEAT "Repeat the last action\nRepeat"
+ ID_EDIT_REPLACE "Replace specific text with different text\nReplace"
+ ID_EDIT_SELECT_ALL "Select the entire document\nSelect All"
+ ID_EDIT_UNDO "Undo the last action\nUndo"
+ ID_EDIT_REDO "Redo the previously undone action\nRedo"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_VIEW_TOOLBAR "Show or hide the toolbar\nToggle ToolBar"
+ ID_VIEW_STATUS_BAR "Show or hide the status bar\nToggle StatusBar"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ AFX_IDS_SCSIZE "Change the window size"
+ AFX_IDS_SCMOVE "Change the window position"
+ AFX_IDS_SCMINIMIZE "Reduce the window to an icon"
+ AFX_IDS_SCMAXIMIZE "Enlarge the window to full size"
+ AFX_IDS_SCNEXTWINDOW "Switch to the next document window"
+ AFX_IDS_SCPREVWINDOW "Switch to the previous document window"
+ AFX_IDS_SCCLOSE "Close the active window and prompts to save the documents"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ AFX_IDS_SCRESTORE "Restore the window to normal size"
+ AFX_IDS_SCTASKLIST "Activate Task List"
+ AFX_IDS_MDICHILD "Activate this window"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ AFX_IDS_PREVIEW_CLOSE "Close print preview mode\nCancel Preview"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_VIEW_XY "View original layout (Top)"
+ ID_VIEW_SIDE "Side view"
+ ID_VIEW_FRONT "Front view"
+ ID_VIEW_CAMERATOGGLE "Toggle full time camera preview\nCamera preview"
+ ID_TEXTURES_POPUP "Texture view mode\nTexture view mode"
+ ID_POPUP_SELECTION "Selection\nSelection"
+ ID_VIEW_CHANGE "Change views\nChange views"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_VIEW_ENTITY "Toggle entity inspector\nEntity inspector"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_BRUSH_FLIPX "Flip selected brushes along x-axis\nx-axis Flip"
+ ID_BRUSH_FLIPY "Flip selected brushes along y-axis\ny-axis Flip"
+ ID_BRUSH_FLIPZ "Flip selected brushes along z-axis\nz-axis Flip"
+ ID_BRUSH_ROTATEX "Rotate selected brushes along x-axis\nx-axis Rotate"
+ ID_BRUSH_ROTATEY "Rotate selected brushes along y-axis\ny-axis Rotate"
+ ID_BRUSH_ROTATEZ "Rotate selected brushes along z-axis\nz-axis Rotate"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_SELECTION_SELECTCOMPLETETALL "Complete Tall\nComplete Tall"
+ ID_SELECTION_CSGSUBTRACT "CSG Subtract\nCSG Subtract"
+ ID_SELECTION_SELECTTOUCHING "Select Touching\nSelect Touching"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_SELECTION_MAKEHOLLOW "Hollow Selection\nHollow"
+ ID_SELECTION_SELECTPARTIALTALL "Select Partial Tall\nSelect Partial Tall"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_VIEW_CAMERAUPDATE "Update Camera\nUpdate Camera"
+ ID_VIEW_CLIPPER "Set clipper mode\nClipper"
+ ID_PREFS "Preferences\nPreferences"
+ ID_EDIT_MAPINFO "Entity Information\nEntity list"
+ ID_BRUSH_SCRIPTS "Define and run BrushScripts\nBrushScripts"
+ ID_HELP_COMMANDLIST "Provides a list of the currently bound commands"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_SELECT_MOUSEROTATE "Free rotation\nFree Rotation"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_TEXTURE_REPLACESELECTED
+ "Find and replace texture names in selected brushes/faces"
+ ID_TEXTURE_REPLACEALL "Find and replace texture names in all brushes/faces"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_SELECT_MOUSESCALE "Free Scaling\nFree Scaling"
+ ID_SCALELOCKX "Lock X\nLock X"
+ ID_SCALELOCKY "Lock Y\nLock Y"
+ ID_SCALELOCKZ "Lock Z\nLock Z"
+ ID_VIEW_CUBICCLIPPING "Cubic clip the camera view\nCubic clip the camera view"
+ ID_FILE_PROJECTSETTINGS "View and edit project attributes"
+ ID_VIEW_CUBEOUT "Zoom cubic clip out"
+ ID_VIEW_CUBEIN "Zoom cubic clip in"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_FILE_SAVEREGION "Save defined region"
+ ID_FILE_LOADREGION "Load saved region"
+ ID_TOOLBAR_MAIN "Standard toolbar"
+ ID_TOOLBAR_TEXTURE "Texture control toolbar"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_TEXTURES_LOAD "Load from a specific directory"
+ ID_CURVE_CYLINDER "Create a cylinder"
+ ID_FILE_IMPORTMAP "Load map, leaving current map intact"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_SELECTION_SELECTINSIDE "Select Inside\nSelect Inside"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_FILE_EXPORTMAP "Save selection into map file"
+ ID_EDIT_LOADPREFAB "Load .map from prefab path"
+ ID_VIEW_SHOWCURVES "Show Curved brushes"
+ ID_TEXTURES_LOADLIST "Loads from a list. (Good in case there are too many for the menu)"
+ ID_DONTSELECTCURVE "Don't select curved brushes\nDon't select curved brushes"
+ ID_CONVERTCURVES "Turns selected brush into a new test curve"
+ ID_PATCH_SHOWBOUNDINGBOX
+ "Show patch bounding box\nShow patch bounding box"
+ ID_CURVE_SIMPLEPATCHMESH "Builds a flat patch mesh, you specify the size"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_PATCH_WIREFRAME "Show patches as wireframes\nShow patches as wireframes"
+ ID_PATCH_WELD "Welds equal patch points during moves\nWelds equal patch points during moves"
+ ID_CURVE_PATCHTUBE "Create a cylinder"
+ ID_CURVE_PATCHENDCAP "Create an endcap"
+ ID_CURVE_PATCHBEVEL "Create a bevel"
+ ID_PATCH_DRILLDOWN "Selects drill down rows and columns\nSelects drill down rows and columns"
+ ID_CURVE_LOADPATCHFILE "Load corresponding .patch file\nLoad corresponding .patch file"
+ ID_CURVE_INSERTROW "Inserts a row in the selected patch(s)\nInserts a row in the selected patch(s)"
+ ID_CURVE_INSERTCOLUMN "Inserts a column in the selected patch(s)\nInserts a column in the selected patch(s)"
+ ID_CURVE_DELETEROW "Deletes a row in the current patch(s)\nDeletes a row in the current patch(s)"
+ ID_CURVE_DELETECOLUMN "Deletes a column in the current Patch(s)\nDeletes a column in the current Patch(s)"
+ ID_PATCH_INSDEL "Redisperse patch points\nRedisperse patch points"
+ ID_CURVE_INSERT_ADDCOLUMN
+ "Add a column to the end of the patch\nAdd a column to the end of the patch"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_CURVE_INSERT_INSERTCOLUMN
+ "Insert a column at the beginning of the patch\nInsert a column at the beginning of the patch"
+ ID_CURVE_INSERT_ADDROW "Add a row at the end of the patch\nAdd a row at the end of the patch"
+ ID_CURVE_INSERT_INSERTROW
+ "Insert a row at the beginning of the patch\nInsert a row at the beginning of the patch"
+ ID_CURVE_DELETE_FIRSTCOLUMN
+ "Delete the first (2) columns\nDelete the first (2) columns"
+ ID_CURVE_DELETE_LASTCOLUMN
+ "Delete the last (2) columns\nDelete the last (2) columns"
+ ID_CURVE_DELETE_FIRSTROW
+ "Delete the first (2) rows\nDelete the first (2) rows"
+ ID_CURVE_DELETE_LASTROW "Delete the last (2) rows\nDelete the last (2) rows"
+ ID_CURVE_NEGATIVE "Toggle negative flag\nToggle negative flag"
+ ID_PATCH_BEND "Patch Bend mode\nPatch Bend mode"
+ ID_CURVE_PATCHDENSETUBE "Create a dense tube"
+ ID_CURVE_PATCHVERYDENSETUBE "Create a very dense cylinder"
+ ID_CURVE_CAP "Put caps on the current patch\nPut caps on the current patch"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_CURVE_REDISPERSE_ROWS
+ "Re-disperse rows across the dimensions of the patch"
+ ID_CURVE_REDISPERSE_COLS
+ "Re-disperse columns across the dimensions of the patch"
+ ID_CURVE_PATCHSQUARE "Create a very square cylinder"
+ ID_TEXTURES_FLUSH "Flush texture palette"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_TEXTURES_RELOADSHADERS
+ "Reload Shaders and apply visual changes to current map"
+ ID_SHOW_ENTITIES "Show Entities as\nShow Entities as"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ IDR_SHADERTYPE "\nUntitled\nSHADER Document\nShader Files (*.shader)\n.shader\nShaderFileType\nSHADER File Type\nSHADER\nShader Files\n"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_VIEW_OPENGLLIGHTING "Toggle OpenGL Lighting"
+END
+
+STRINGTABLE DISCARDABLE
+BEGIN
+ ID_SELECTION_CSGMERGE "CSG Merge\nCSG Merge"
+END
+
+#endif // English (U.S.) resources
+/////////////////////////////////////////////////////////////////////////////
+
+
+
+#ifndef APSTUDIO_INVOKED
+/////////////////////////////////////////////////////////////////////////////
+//
+// Generated from the TEXTINCLUDE 3 resource.
+//
+#define _AFX_NO_SPLITTER_RESOURCES
+#define _AFX_NO_OLE_RESOURCES
+#define _AFX_NO_TRACKER_RESOURCES
+#define _AFX_NO_PROPERTY_RESOURCES
+
+#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
+#ifdef _WIN32
+LANGUAGE 9, 1
+#pragma code_page(1252)
+#endif
+#include "res\Radiant.rc2" // non-Microsoft Visual C++ edited resources
+#include "afxres.rc" // Standard components
+#include "afxprint.rc" // printing/print preview resources
+#endif
+/////////////////////////////////////////////////////////////////////////////
+#endif // not APSTUDIO_INVOKED
+
diff --git a/q3radiant/Radiant.sln b/q3radiant/Radiant.sln
new file mode 100755
index 0000000..ec12c7e
--- /dev/null
+++ b/q3radiant/Radiant.sln
@@ -0,0 +1,95 @@
+Microsoft Visual Studio Solution File, Format Version 8.00
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Radiant", "Radiant.vcproj", "{D92DD0A3-9D6B-4183-992C-0FF42BC59A62}"
+ ProjectSection(ProjectDependencies) = postProject
+ {EFB1E65A-E86F-4E0D-845A-E5C7A3DF016F} = {EFB1E65A-E86F-4E0D-845A-E5C7A3DF016F}
+ {63F2947A-5BD9-48C2-8BEA-7AB341F6B48F} = {63F2947A-5BD9-48C2-8BEA-7AB341F6B48F}
+ {B80E7E95-566D-4CB0-8151-0567CB206D5A} = {B80E7E95-566D-4CB0-8151-0567CB206D5A}
+ {706CF09C-D767-4ECD-8CA6-EE7CA6CDA3AE} = {706CF09C-D767-4ECD-8CA6-EE7CA6CDA3AE}
+ EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Splines", "splines\Splines.vcproj", "{63F2947A-5BD9-48C2-8BEA-7AB341F6B48F}"
+ ProjectSection(ProjectDependencies) = postProject
+ EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cmdlib", "..\libs\cmdlib\cmdlib.vcproj", "{EFB1E65A-E86F-4E0D-845A-E5C7A3DF016F}"
+ ProjectSection(ProjectDependencies) = postProject
+ EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "jpeg6", "..\libs\jpeg6\jpeg6.vcproj", "{B80E7E95-566D-4CB0-8151-0567CB206D5A}"
+ ProjectSection(ProjectDependencies) = postProject
+ EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pak", "..\libs\pak\pak.vcproj", "{706CF09C-D767-4ECD-8CA6-EE7CA6CDA3AE}"
+ ProjectSection(ProjectDependencies) = postProject
+ EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "q3map", "..\q3map\q3map.vcproj", "{4D768C46-A503-48DE-BD4C-14D2B50C2739}"
+ ProjectSection(ProjectDependencies) = postProject
+ EndProjectSection
+EndProject
+Global
+ GlobalSection(SourceCodeControl) = preSolution
+ SccNumberOfProjects = 6
+ SccProjectUniqueName0 = Radiant.vcproj
+ SccProjectName0 = \u0022$/source/q3radiant\u0022,\u0020FEFAAAAA
+ SccLocalPath0 = .
+ SccProvider0 = MSSCCI:Perforce\u0020SCM
+ SccProjectUniqueName1 = splines\\Splines.vcproj
+ SccProjectName1 = \u0022$/source/q3radiant/splines\u0022,\u0020XINAAAAA
+ SccLocalPath1 = splines
+ SccProvider1 = MSSCCI:Perforce\u0020SCM
+ SccProjectUniqueName2 = ..\\libs\\cmdlib\\cmdlib.vcproj
+ SccProjectName2 = \u0022$/source/q3radiant\u0022,\u0020FEFAAAAA
+ SccLocalPath2 = .
+ SccProvider2 = MSSCCI:Perforce\u0020SCM
+ SccProjectFilePathRelativizedFromConnection2 = ..\\libs\\cmdlib\\
+ SccProjectUniqueName3 = ..\\libs\\jpeg6\\jpeg6.vcproj
+ SccProjectName3 = \u0022$/source/q3radiant\u0022,\u0020FEFAAAAA
+ SccLocalPath3 = .
+ SccProvider3 = MSSCCI:Perforce\u0020SCM
+ SccProjectFilePathRelativizedFromConnection3 = ..\\libs\\jpeg6\\
+ SccProjectUniqueName4 = ..\\libs\\pak\\pak.vcproj
+ SccProjectName4 = \u0022$/source/q3radiant\u0022,\u0020FEFAAAAA
+ SccLocalPath4 = .
+ SccProvider4 = MSSCCI:Perforce\u0020SCM
+ SccProjectFilePathRelativizedFromConnection4 = ..\\libs\\pak\\
+ SccProjectUniqueName5 = ..\\q3map\\q3map.vcproj
+ SccProjectName5 = \u0022$/source/q3map\u0022,\u0020PADAAAAA
+ SccLocalPath5 = ..\\q3map
+ SccProvider5 = MSSCCI:Perforce\u0020SCM
+ EndGlobalSection
+ GlobalSection(SolutionConfiguration) = preSolution
+ Debug = Debug
+ Release = Release
+ EndGlobalSection
+ GlobalSection(ProjectConfiguration) = postSolution
+ {D92DD0A3-9D6B-4183-992C-0FF42BC59A62}.Debug.ActiveCfg = Debug|Win32
+ {D92DD0A3-9D6B-4183-992C-0FF42BC59A62}.Debug.Build.0 = Debug|Win32
+ {D92DD0A3-9D6B-4183-992C-0FF42BC59A62}.Release.ActiveCfg = Release|Win32
+ {D92DD0A3-9D6B-4183-992C-0FF42BC59A62}.Release.Build.0 = Release|Win32
+ {63F2947A-5BD9-48C2-8BEA-7AB341F6B48F}.Debug.ActiveCfg = Debug|Win32
+ {63F2947A-5BD9-48C2-8BEA-7AB341F6B48F}.Debug.Build.0 = Debug|Win32
+ {63F2947A-5BD9-48C2-8BEA-7AB341F6B48F}.Release.ActiveCfg = Release|Win32
+ {63F2947A-5BD9-48C2-8BEA-7AB341F6B48F}.Release.Build.0 = Release|Win32
+ {EFB1E65A-E86F-4E0D-845A-E5C7A3DF016F}.Debug.ActiveCfg = Debug|Win32
+ {EFB1E65A-E86F-4E0D-845A-E5C7A3DF016F}.Debug.Build.0 = Debug|Win32
+ {EFB1E65A-E86F-4E0D-845A-E5C7A3DF016F}.Release.ActiveCfg = Release|Win32
+ {EFB1E65A-E86F-4E0D-845A-E5C7A3DF016F}.Release.Build.0 = Release|Win32
+ {B80E7E95-566D-4CB0-8151-0567CB206D5A}.Debug.ActiveCfg = Debug|Win32
+ {B80E7E95-566D-4CB0-8151-0567CB206D5A}.Debug.Build.0 = Debug|Win32
+ {B80E7E95-566D-4CB0-8151-0567CB206D5A}.Release.ActiveCfg = Release|Win32
+ {B80E7E95-566D-4CB0-8151-0567CB206D5A}.Release.Build.0 = Release|Win32
+ {706CF09C-D767-4ECD-8CA6-EE7CA6CDA3AE}.Debug.ActiveCfg = Debug|Win32
+ {706CF09C-D767-4ECD-8CA6-EE7CA6CDA3AE}.Debug.Build.0 = Debug|Win32
+ {706CF09C-D767-4ECD-8CA6-EE7CA6CDA3AE}.Release.ActiveCfg = Release|Win32
+ {706CF09C-D767-4ECD-8CA6-EE7CA6CDA3AE}.Release.Build.0 = Release|Win32
+ {4D768C46-A503-48DE-BD4C-14D2B50C2739}.Debug.ActiveCfg = Debug|Win32
+ {4D768C46-A503-48DE-BD4C-14D2B50C2739}.Debug.Build.0 = Debug|Win32
+ {4D768C46-A503-48DE-BD4C-14D2B50C2739}.Release.ActiveCfg = Release|Win32
+ {4D768C46-A503-48DE-BD4C-14D2B50C2739}.Release.Build.0 = Release|Win32
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ EndGlobalSection
+ GlobalSection(ExtensibilityAddIns) = postSolution
+ EndGlobalSection
+EndGlobal
diff --git a/q3radiant/Radiant.vcproj b/q3radiant/Radiant.vcproj
new file mode 100755
index 0000000..090a4ff
--- /dev/null
+++ b/q3radiant/Radiant.vcproj
@@ -0,0 +1,3381 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+ ProjectType="Visual C++"
+ Version="7.10"
+ Name="Radiant"
+ SccProjectName="&quot;$/source/q3radiant&quot;, FEFAAAAA"
+ SccLocalPath="."
+ Keyword="MFCProj">
+ <Platforms>
+ <Platform
+ Name="Win32"/>
+ </Platforms>
+ <Configurations>
+ <Configuration
+ Name="Release|Win32"
+ OutputDirectory=".\Release"
+ IntermediateDirectory=".\Release"
+ ConfigurationType="1"
+ UseOfMFC="1"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ AdditionalIncludeDirectories="../libs,../common,c:\quake3\common,c:\quake3\libs"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;QUAKE3;Q3RADIANT"
+ StringPooling="TRUE"
+ RuntimeLibrary="0"
+ EnableFunctionLevelLinking="TRUE"
+ RuntimeTypeInfo="TRUE"
+ UsePrecompiledHeader="3"
+ PrecompiledHeaderThrough="stdafx.h"
+ PrecompiledHeaderFile=".\Release/Radiant.pch"
+ AssemblerListingLocation=".\Release/"
+ ObjectFile=".\Release/"
+ ProgramDataBaseFileName=".\Release/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="2"
+ CompileAs="0"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="winmm.lib ..\libs\jpeg6.lib ..\libs\pak.lib ..\libs\cmdlib.lib"
+ OutputFile="Release\q3radiant.exe"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ IgnoreDefaultLibraryNames="libc.lib msvcrtd.lib"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile=".\Release/q3radiant.pdb"
+ SubSystem="2"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="NDEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\Release/Radiant.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="ReleaseTTimo|Win32"
+ OutputDirectory=".\Radiant___Win32_ReleaseTTimo"
+ IntermediateDirectory=".\Radiant___Win32_ReleaseTTimo"
+ ConfigurationType="1"
+ UseOfMFC="1"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ AdditionalIncludeDirectories="..\Libs,../libs,../common,c:\quake3\common,c:\quake3\libs"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;QUAKE3;Q3RADIANT"
+ StringPooling="TRUE"
+ RuntimeLibrary="0"
+ EnableFunctionLevelLinking="TRUE"
+ RuntimeTypeInfo="TRUE"
+ UsePrecompiledHeader="3"
+ PrecompiledHeaderThrough="stdafx.h"
+ PrecompiledHeaderFile=".\Radiant___Win32_ReleaseTTimo/Radiant.pch"
+ AssemblerListingLocation=".\Radiant___Win32_ReleaseTTimo/"
+ ObjectFile=".\Radiant___Win32_ReleaseTTimo/"
+ ProgramDataBaseFileName=".\Radiant___Win32_ReleaseTTimo/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="2"
+ CompileAs="0"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="winmm.lib jpeg6.lib pak.lib cmdlib.lib"
+ OutputFile="Radiant___Win32_ReleaseTTimo\q3radiant.exe"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ AdditionalLibraryDirectories="..\Libs"
+ IgnoreDefaultLibraryNames="libc.lib msvcrtd.lib"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile=".\Radiant___Win32_ReleaseTTimo/q3radiant.pdb"
+ SubSystem="2"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="NDEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\Radiant___Win32_ReleaseTTimo/Radiant.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"
+ Description="Copy to dir..."
+ CommandLine="copy Radiant___Win32_ReleaseTTimo\q3radiant.exe E:\home\quake3\q3radiant"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Debug|Win32"
+ OutputDirectory=".\Debug"
+ IntermediateDirectory=".\Debug"
+ ConfigurationType="1"
+ UseOfMFC="1"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories="../libs,../common,c:\quake3\common,c:\quake3\libs"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;QUAKE3;Q3RADIANT"
+ RuntimeLibrary="1"
+ RuntimeTypeInfo="TRUE"
+ UsePrecompiledHeader="3"
+ PrecompiledHeaderThrough="stdafx.h"
+ PrecompiledHeaderFile=".\Debug/Radiant.pch"
+ AssemblerListingLocation=".\Debug/"
+ ObjectFile=".\Debug/"
+ ProgramDataBaseFileName=".\Debug/"
+ BrowseInformation="1"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"
+ CompileAs="0"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="winmm.lib ..\libs\jpeg6d.lib ..\libs\pakd.lib ..\libs\cmdlibd.lib"
+ OutputFile="Debug\q3radiant.exe"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ IgnoreDefaultLibraryNames="libc.lib msvcrtd.lib"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile=".\Debug/q3radiant.pdb"
+ GenerateMapFile="TRUE"
+ MapFileName=".\Debug/q3radiant.map"
+ SubSystem="2"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="_DEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\Debug/Radiant.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="DebugTTimo|Win32"
+ OutputDirectory=".\Radiant___Win32_DebugTTimo"
+ IntermediateDirectory=".\Radiant___Win32_DebugTTimo"
+ ConfigurationType="1"
+ UseOfMFC="1"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories="..\Libs,../libs,../common,c:\quake3\common,c:\quake3\libs"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;QUAKE3;Q3RADIANT"
+ RuntimeLibrary="1"
+ RuntimeTypeInfo="TRUE"
+ UsePrecompiledHeader="3"
+ PrecompiledHeaderThrough="stdafx.h"
+ PrecompiledHeaderFile=".\Radiant___Win32_DebugTTimo/Radiant.pch"
+ AssemblerListingLocation=".\Radiant___Win32_DebugTTimo/"
+ ObjectFile=".\Radiant___Win32_DebugTTimo/"
+ ProgramDataBaseFileName=".\Radiant___Win32_DebugTTimo/"
+ BrowseInformation="1"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"
+ CompileAs="0"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="winmm.lib jpeg6d.lib pakd.lib cmdlibd.lib"
+ OutputFile="Radiant___Win32_DebugTTimo\q3radiant.exe"
+ LinkIncremental="1"
+ SuppressStartupBanner="TRUE"
+ AdditionalLibraryDirectories="..\Libs"
+ IgnoreDefaultLibraryNames="libc.lib msvcrtd.lib"
+ GenerateDebugInformation="TRUE"
+ ProgramDatabaseFile=".\Radiant___Win32_DebugTTimo/q3radiant.pdb"
+ GenerateMapFile="TRUE"
+ MapFileName=".\Radiant___Win32_DebugTTimo/q3radiant.map"
+ SubSystem="2"
+ TargetMachine="1"/>
+ <Tool
+ Name="VCMIDLTool"
+ PreprocessorDefinitions="_DEBUG"
+ MkTypLibCompatible="TRUE"
+ SuppressStartupBanner="TRUE"
+ TargetEnvironment="1"
+ TypeLibraryName=".\Radiant___Win32_DebugTTimo/Radiant.tlb"
+ HeaderFileName=""/>
+ <Tool
+ Name="VCPostBuildEventTool"
+ Description="Copy to dir..."
+ CommandLine="copy Radiant___Win32_DebugTTimo\q3radiant.exe E:\home\quake3\q3radiant"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCWebDeploymentTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ </Configurations>
+ <References>
+ </References>
+ <Files>
+ <Filter
+ Name="Source Files"
+ Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat">
+ <File
+ RelativePath="BrushScript.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="BSInput.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="cameratargetdlg.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="CamWnd.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="CapDialog.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="cbrushstub.cpp">
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32"
+ ExcludedFromBuild="TRUE">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="CommandsDlg.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="DialogInfo.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="DialogTextures.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="DialogThick.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="dlgcamera.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="DlgEvent.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="EditWnd.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="EntityListDlg.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="FindTextureDlg.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="GroupDlg.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="LstToolBar.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="MainFrm.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="MapInfo.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="NameDlg.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="NewProjDlg.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="PatchDensityDlg.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="PatchDialog.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="PlugIn.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ UsePrecompiledHeader="0"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ UsePrecompiledHeader="0"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="PlugInManager.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ UsePrecompiledHeader="0"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ UsePrecompiledHeader="0"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="PMESH.CPP">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="PrefsDlg.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="qgl_win.c">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ UsePrecompiledHeader="0"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ UsePrecompiledHeader="0"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ UsePrecompiledHeader="0"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ UsePrecompiledHeader="0"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="radbsp.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="RADEditWnd.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="Radiant.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="Radiant.rc">
+ </File>
+ <File
+ RelativePath="RotateDlg.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ScaleDialog.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ScriptDlg.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ShaderInfo.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="StdAfx.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ UsePrecompiledHeader="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ UsePrecompiledHeader="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ UsePrecompiledHeader="1"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ UsePrecompiledHeader="1"
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="SurfaceDlg.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="TexEdit.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="TextureBar.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="TextureLayout.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="TexWnd.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="Undo.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="WaveOpen.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="Winding.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="XYWnd.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="ZWnd.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <Filter
+ Name="QE4 Files"
+ Filter="">
+ <File
+ RelativePath="Bmp.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="brush.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="csg.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="drag.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="eclass.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="entity.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="lbmlib.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="map.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="mathlib.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="mru.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="parse.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="points.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="qe3.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="select.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="terrain.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="terrain.h">
+ </File>
+ <File
+ RelativePath="vertsel.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="win_dlg.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="win_ent.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="win_main.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="win_qe3.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="z.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <Filter
+ Name="Brush Primitives"
+ Filter="">
+ <File
+ RelativePath="brush_primit.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <Filter
+ Name="interfaces"
+ Filter="">
+ <File
+ RelativePath="GLInterface.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="IEpairs.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="IShaders.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="Messaging.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="PluginEntities.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="SelectedFace.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="SurfacePlugin.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="ReleaseTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="DebugTTimo|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ BrowseInformation="1"/>
+ </FileConfiguration>
+ </File>
+ </Filter>
+ </Filter>
+ <Filter
+ Name="Header Files"
+ Filter="h;hpp;hxx;hm;inl">
+ <File
+ RelativePath="BSInput.h">
+ </File>
+ <File
+ RelativePath="cameratargetdlg.h">
+ </File>
+ <File
+ RelativePath="CamWnd.h">
+ </File>
+ <File
+ RelativePath="CapDialog.h">
+ </File>
+ <File
+ RelativePath="ChildFrm.h">
+ </File>
+ <File
+ RelativePath="CommandsDlg.h">
+ </File>
+ <File
+ RelativePath="DialogInfo.h">
+ </File>
+ <File
+ RelativePath="DialogTextures.h">
+ </File>
+ <File
+ RelativePath="DialogThick.h">
+ </File>
+ <File
+ RelativePath="dlgcamera.h">
+ </File>
+ <File
+ RelativePath="DlgEvent.h">
+ </File>
+ <File
+ RelativePath="EditWnd.h">
+ </File>
+ <File
+ RelativePath="EntityListDlg.h">
+ </File>
+ <File
+ RelativePath="FindTextureDlg.h">
+ </File>
+ <File
+ RelativePath="GroupBar.h">
+ </File>
+ <File
+ RelativePath="GroupDlg.h">
+ </File>
+ <File
+ RelativePath="LstToolBar.h">
+ </File>
+ <File
+ RelativePath="MainFrm.h">
+ </File>
+ <File
+ RelativePath="MapInfo.h">
+ </File>
+ <File
+ RelativePath="NameDlg.h">
+ </File>
+ <File
+ RelativePath="NewProjDlg.h">
+ </File>
+ <File
+ RelativePath="PatchDensityDlg.h">
+ </File>
+ <File
+ RelativePath="PatchDialog.h">
+ </File>
+ <File
+ RelativePath="PlugIn.h">
+ </File>
+ <File
+ RelativePath="PlugInManager.h">
+ </File>
+ <File
+ RelativePath="PrefsDlg.h">
+ </File>
+ <File
+ RelativePath="qe3.h">
+ </File>
+ <File
+ RelativePath="QEDEFS.H">
+ </File>
+ <File
+ RelativePath="qerplugin.h">
+ </File>
+ <File
+ RelativePath="QERTYPES.H">
+ </File>
+ <File
+ RelativePath="QFILES.H">
+ </File>
+ <File
+ RelativePath="RADEditWnd.h">
+ </File>
+ <File
+ RelativePath="Radiant.h">
+ </File>
+ <File
+ RelativePath="RadiantDoc.h">
+ </File>
+ <File
+ RelativePath="RadiantView.h">
+ </File>
+ <File
+ RelativePath="Resource.h">
+ </File>
+ <File
+ RelativePath="RotateDlg.h">
+ </File>
+ <File
+ RelativePath="ScaleDialog.h">
+ </File>
+ <File
+ RelativePath="ScriptDlg.h">
+ </File>
+ <File
+ RelativePath="SELECT.H">
+ </File>
+ <File
+ RelativePath="ShaderInfo.h">
+ </File>
+ <File
+ RelativePath="StdAfx.h">
+ </File>
+ <File
+ RelativePath="SurfaceDlg.h">
+ </File>
+ <File
+ RelativePath="TexEdit.h">
+ </File>
+ <File
+ RelativePath="TextureBar.h">
+ </File>
+ <File
+ RelativePath="TextureLayout.h">
+ </File>
+ <File
+ RelativePath="TexWnd.h">
+ </File>
+ <File
+ RelativePath="WaveOpen.h">
+ </File>
+ <File
+ RelativePath="XYWnd.h">
+ </File>
+ <File
+ RelativePath="ZWnd.h">
+ </File>
+ <Filter
+ Name="interface headers"
+ Filter="">
+ <File
+ RelativePath="IEpairs.h">
+ </File>
+ <File
+ RelativePath="igl.h">
+ </File>
+ <File
+ RelativePath="IMessaging.h">
+ </File>
+ <File
+ RelativePath="IPluginEntities.h">
+ </File>
+ <File
+ RelativePath="ISelectedFace.h">
+ </File>
+ <File
+ RelativePath="IShaders.h">
+ </File>
+ <File
+ RelativePath="isurfaceplugin.h">
+ </File>
+ </Filter>
+ <Filter
+ Name="internal interface headers"
+ Filter="">
+ <File
+ RelativePath="EpairsWrapper.h">
+ </File>
+ <File
+ RelativePath="Messaging.h">
+ </File>
+ </Filter>
+ </Filter>
+ <Filter
+ Name="Resource Files"
+ Filter="ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe">
+ <File
+ RelativePath="res\bevel.bmp">
+ </File>
+ <File
+ RelativePath="res\bitmap2.bmp">
+ </File>
+ <File
+ RelativePath="res\bmp00001.bmp">
+ </File>
+ <File
+ RelativePath="res\bmp00002.bmp">
+ </File>
+ <File
+ RelativePath="RES\bmp00003.bmp">
+ </File>
+ <File
+ RelativePath="res\endcap.bmp">
+ </File>
+ <File
+ RelativePath="res\ibevel.bmp">
+ </File>
+ <File
+ RelativePath="RES\icon2.ico">
+ </File>
+ <File
+ RelativePath="res\iendcap.bmp">
+ </File>
+ <File
+ RelativePath="res\logo_sm3dfx.bmp">
+ </File>
+ <File
+ RelativePath="res\q.bmp">
+ </File>
+ <File
+ RelativePath="q.bmp">
+ </File>
+ <File
+ RelativePath="res\Radiant.ico">
+ </File>
+ <File
+ RelativePath="res\Radiant.rc2">
+ </File>
+ <File
+ RelativePath="res\RadiantDoc.ico">
+ </File>
+ <File
+ RelativePath="RES\shaderbar.bmp">
+ </File>
+ <File
+ RelativePath="RES\shaderdoc.ico">
+ </File>
+ <File
+ RelativePath="RES\shaderframe.ico">
+ </File>
+ <File
+ RelativePath="res\Toolbar.bmp">
+ </File>
+ <File
+ RelativePath="toolbar1.bmp">
+ </File>
+ <File
+ RelativePath="res\toolbar1.bmp">
+ </File>
+ <File
+ RelativePath="res\toolbar2.bmp">
+ </File>
+ <File
+ RelativePath="res\viewdefa.bmp">
+ </File>
+ <File
+ RelativePath="res\viewoppo.bmp">
+ </File>
+ </Filter>
+ </Files>
+ <Globals>
+ </Globals>
+</VisualStudioProject>
diff --git a/q3radiant/RadiantDoc.cpp b/q3radiant/RadiantDoc.cpp
new file mode 100755
index 0000000..00b66fe
--- /dev/null
+++ b/q3radiant/RadiantDoc.cpp
@@ -0,0 +1,105 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// RadiantDoc.cpp : implementation of the CRadiantDoc class
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+
+#include "RadiantDoc.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CRadiantDoc
+
+IMPLEMENT_DYNCREATE(CRadiantDoc, CDocument)
+
+BEGIN_MESSAGE_MAP(CRadiantDoc, CDocument)
+ //{{AFX_MSG_MAP(CRadiantDoc)
+ // NOTE - the ClassWizard will add and remove mapping macros here.
+ // DO NOT EDIT what you see in these blocks of generated code!
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CRadiantDoc construction/destruction
+
+CRadiantDoc::CRadiantDoc()
+{
+ // TODO: add one-time construction code here
+
+}
+
+CRadiantDoc::~CRadiantDoc()
+{
+}
+
+BOOL CRadiantDoc::OnNewDocument()
+{
+ if (!CDocument::OnNewDocument())
+ return FALSE;
+
+ // TODO: add reinitialization code here
+ // (SDI documents will reuse this document)
+
+ return TRUE;
+}
+
+
+
+/////////////////////////////////////////////////////////////////////////////
+// CRadiantDoc serialization
+
+void CRadiantDoc::Serialize(CArchive& ar)
+{
+ if (ar.IsStoring())
+ {
+ // TODO: add storing code here
+ }
+ else
+ {
+ // TODO: add loading code here
+ }
+}
+
+/////////////////////////////////////////////////////////////////////////////
+// CRadiantDoc diagnostics
+
+#ifdef _DEBUG
+void CRadiantDoc::AssertValid() const
+{
+ CDocument::AssertValid();
+}
+
+void CRadiantDoc::Dump(CDumpContext& dc) const
+{
+ CDocument::Dump(dc);
+}
+#endif //_DEBUG
+
+/////////////////////////////////////////////////////////////////////////////
+// CRadiantDoc commands
diff --git a/q3radiant/RadiantDoc.h b/q3radiant/RadiantDoc.h
new file mode 100755
index 0000000..fc51b92
--- /dev/null
+++ b/q3radiant/RadiantDoc.h
@@ -0,0 +1,78 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// RadiantDoc.h : interface of the CRadiantDoc class
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#if !defined(AFX_RADIANTDOC_H__330BBF0E_731C_11D1_B539_00AA00A410FC__INCLUDED_)
+#define AFX_RADIANTDOC_H__330BBF0E_731C_11D1_B539_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+
+
+class CRadiantDoc : public CDocument
+{
+protected: // create from serialization only
+ CRadiantDoc();
+ DECLARE_DYNCREATE(CRadiantDoc)
+
+// Attributes
+public:
+
+// Operations
+public:
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CRadiantDoc)
+ public:
+ virtual BOOL OnNewDocument();
+ virtual void Serialize(CArchive& ar);
+ //}}AFX_VIRTUAL
+
+// Implementation
+public:
+ virtual ~CRadiantDoc();
+#ifdef _DEBUG
+ virtual void AssertValid() const;
+ virtual void Dump(CDumpContext& dc) const;
+#endif
+
+protected:
+
+// Generated message map functions
+protected:
+ //{{AFX_MSG(CRadiantDoc)
+ // NOTE - the ClassWizard will add and remove member functions here.
+ // DO NOT EDIT what you see in these blocks of generated code !
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+/////////////////////////////////////////////////////////////////////////////
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_RADIANTDOC_H__330BBF0E_731C_11D1_B539_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/RadiantView.cpp b/q3radiant/RadiantView.cpp
new file mode 100755
index 0000000..f89b72c
--- /dev/null
+++ b/q3radiant/RadiantView.cpp
@@ -0,0 +1,126 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// RadiantView.cpp : implementation of the CRadiantView class
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+
+#include "RadiantDoc.h"
+#include "RadiantView.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CRadiantView
+
+IMPLEMENT_DYNCREATE(CRadiantView, CView)
+
+BEGIN_MESSAGE_MAP(CRadiantView, CView)
+ //{{AFX_MSG_MAP(CRadiantView)
+ // NOTE - the ClassWizard will add and remove mapping macros here.
+ // DO NOT EDIT what you see in these blocks of generated code!
+ //}}AFX_MSG_MAP
+ // Standard printing commands
+ ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)
+ ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)
+ ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview)
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CRadiantView construction/destruction
+
+CRadiantView::CRadiantView()
+{
+ // TODO: add construction code here
+
+}
+
+CRadiantView::~CRadiantView()
+{
+}
+
+BOOL CRadiantView::PreCreateWindow(CREATESTRUCT& cs)
+{
+ // TODO: Modify the Window class or styles here by modifying
+ // the CREATESTRUCT cs
+
+ return CView::PreCreateWindow(cs);
+}
+
+/////////////////////////////////////////////////////////////////////////////
+// CRadiantView drawing
+
+void CRadiantView::OnDraw(CDC* pDC)
+{
+ CRadiantDoc* pDoc = GetDocument();
+ ASSERT_VALID(pDoc);
+
+ // TODO: add draw code for native data here
+}
+
+/////////////////////////////////////////////////////////////////////////////
+// CRadiantView printing
+
+BOOL CRadiantView::OnPreparePrinting(CPrintInfo* pInfo)
+{
+ // default preparation
+ return DoPreparePrinting(pInfo);
+}
+
+void CRadiantView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
+{
+ // TODO: add extra initialization before printing
+}
+
+void CRadiantView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
+{
+ // TODO: add cleanup after printing
+}
+
+/////////////////////////////////////////////////////////////////////////////
+// CRadiantView diagnostics
+
+#ifdef _DEBUG
+void CRadiantView::AssertValid() const
+{
+ CView::AssertValid();
+}
+
+void CRadiantView::Dump(CDumpContext& dc) const
+{
+ CView::Dump(dc);
+}
+
+CRadiantDoc* CRadiantView::GetDocument() // non-debug version is inline
+{
+ ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CRadiantDoc)));
+ return (CRadiantDoc*)m_pDocument;
+}
+#endif //_DEBUG
+
+/////////////////////////////////////////////////////////////////////////////
+// CRadiantView message handlers
diff --git a/q3radiant/RadiantView.h b/q3radiant/RadiantView.h
new file mode 100755
index 0000000..4c42a37
--- /dev/null
+++ b/q3radiant/RadiantView.h
@@ -0,0 +1,87 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// RadiantView.h : interface of the CRadiantView class
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#if !defined(AFX_RADIANTVIEW_H__330BBF10_731C_11D1_B539_00AA00A410FC__INCLUDED_)
+#define AFX_RADIANTVIEW_H__330BBF10_731C_11D1_B539_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+
+class CRadiantView : public CView
+{
+protected: // create from serialization only
+ CRadiantView();
+ DECLARE_DYNCREATE(CRadiantView)
+
+// Attributes
+public:
+ CRadiantDoc* GetDocument();
+
+// Operations
+public:
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CRadiantView)
+ public:
+ virtual void OnDraw(CDC* pDC); // overridden to draw this view
+ virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
+ protected:
+ virtual BOOL OnPreparePrinting(CPrintInfo* pInfo);
+ virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo);
+ virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo);
+ //}}AFX_VIRTUAL
+
+// Implementation
+public:
+ virtual ~CRadiantView();
+#ifdef _DEBUG
+ virtual void AssertValid() const;
+ virtual void Dump(CDumpContext& dc) const;
+#endif
+
+protected:
+
+// Generated message map functions
+protected:
+ //{{AFX_MSG(CRadiantView)
+ // NOTE - the ClassWizard will add and remove member functions here.
+ // DO NOT EDIT what you see in these blocks of generated code !
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+#ifndef _DEBUG // debug version in RadiantView.cpp
+inline CRadiantDoc* CRadiantView::GetDocument()
+ { return (CRadiantDoc*)m_pDocument; }
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_RADIANTVIEW_H__330BBF10_731C_11D1_B539_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/RotateDlg.cpp b/q3radiant/RotateDlg.cpp
new file mode 100755
index 0000000..8bda1de
--- /dev/null
+++ b/q3radiant/RotateDlg.cpp
@@ -0,0 +1,130 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// RotateDlg.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "RotateDlg.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CRotateDlg dialog
+
+
+CRotateDlg::CRotateDlg(CWnd* pParent /*=NULL*/)
+ : CDialog(CRotateDlg::IDD, pParent)
+{
+ //{{AFX_DATA_INIT(CRotateDlg)
+ m_strX = _T("");
+ m_strY = _T("");
+ m_strZ = _T("");
+ //}}AFX_DATA_INIT
+}
+
+
+void CRotateDlg::DoDataExchange(CDataExchange* pDX)
+{
+ CDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CRotateDlg)
+ DDX_Control(pDX, IDC_SPIN3, m_wndSpin3);
+ DDX_Control(pDX, IDC_SPIN2, m_wndSpin2);
+ DDX_Control(pDX, IDC_SPIN1, m_wndSpin1);
+ DDX_Text(pDX, IDC_ROTX, m_strX);
+ DDX_Text(pDX, IDC_ROTY, m_strY);
+ DDX_Text(pDX, IDC_ROTZ, m_strZ);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CRotateDlg, CDialog)
+ //{{AFX_MSG_MAP(CRotateDlg)
+ ON_BN_CLICKED(ID_APPLY, OnApply)
+ ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN1, OnDeltaposSpin1)
+ ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN2, OnDeltaposSpin2)
+ ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN3, OnDeltaposSpin3)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CRotateDlg message handlers
+
+void CRotateDlg::OnOK()
+{
+ OnApply();
+ CDialog::OnOK();
+}
+
+void CRotateDlg::OnApply()
+{
+ UpdateData(TRUE);
+ float f = atof(m_strX);
+ if (f != 0.0)
+ Select_RotateAxis(0,f);
+ f = atof(m_strY);
+ if (f != 0.0)
+ Select_RotateAxis(1,f);
+ f = atof(m_strZ);
+ if (f != 0.0)
+ Select_RotateAxis(2,f);
+}
+
+BOOL CRotateDlg::OnInitDialog()
+{
+ CDialog::OnInitDialog();
+ m_wndSpin1.SetRange(0, 359);
+ m_wndSpin2.SetRange(0, 359);
+ m_wndSpin3.SetRange(0, 359);
+ return TRUE; // return TRUE unless you set the focus to a control
+ // EXCEPTION: OCX Property Pages should return FALSE
+}
+
+void CRotateDlg::OnDeltaposSpin1(NMHDR* pNMHDR, LRESULT* pResult)
+{
+ NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
+ Select_RotateAxis(0, pNMUpDown->iDelta);
+ *pResult = 0;
+}
+
+void CRotateDlg::OnDeltaposSpin2(NMHDR* pNMHDR, LRESULT* pResult)
+{
+ NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
+ Select_RotateAxis(1, pNMUpDown->iDelta);
+ *pResult = 0;
+}
+
+void CRotateDlg::OnDeltaposSpin3(NMHDR* pNMHDR, LRESULT* pResult)
+{
+ NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
+ Select_RotateAxis(2, pNMUpDown->iDelta);
+ *pResult = 0;
+}
+
+void CRotateDlg::ApplyNoPaint()
+{
+
+}
diff --git a/q3radiant/RotateDlg.h b/q3radiant/RotateDlg.h
new file mode 100755
index 0000000..d9b00c0
--- /dev/null
+++ b/q3radiant/RotateDlg.h
@@ -0,0 +1,78 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_ROTATEDLG_H__D4B79152_7A7E_11D1_B541_00AA00A410FC__INCLUDED_)
+#define AFX_ROTATEDLG_H__D4B79152_7A7E_11D1_B541_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// RotateDlg.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CRotateDlg dialog
+
+class CRotateDlg : public CDialog
+{
+// Construction
+public:
+ CRotateDlg(CWnd* pParent = NULL); // standard constructor
+
+// Dialog Data
+ //{{AFX_DATA(CRotateDlg)
+ enum { IDD = IDD_ROTATE };
+ CSpinButtonCtrl m_wndSpin3;
+ CSpinButtonCtrl m_wndSpin2;
+ CSpinButtonCtrl m_wndSpin1;
+ CString m_strX;
+ CString m_strY;
+ CString m_strZ;
+ //}}AFX_DATA
+
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CRotateDlg)
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+ void ApplyNoPaint();
+
+ // Generated message map functions
+ //{{AFX_MSG(CRotateDlg)
+ virtual void OnOK();
+ afx_msg void OnApply();
+ virtual BOOL OnInitDialog();
+ afx_msg void OnDeltaposSpin1(NMHDR* pNMHDR, LRESULT* pResult);
+ afx_msg void OnDeltaposSpin2(NMHDR* pNMHDR, LRESULT* pResult);
+ afx_msg void OnDeltaposSpin3(NMHDR* pNMHDR, LRESULT* pResult);
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_ROTATEDLG_H__D4B79152_7A7E_11D1_B541_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/SELECT.CPP b/q3radiant/SELECT.CPP
new file mode 100755
index 0000000..8ccf7f0
--- /dev/null
+++ b/q3radiant/SELECT.CPP
@@ -0,0 +1,1800 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// select.c
+#include "stdafx.h"
+#include "qe3.h"
+
+
+// externs
+CPtrArray g_SelectedFaces;
+CPtrArray g_SelectedFaceBrushes;
+CPtrArray& g_ptrSelectedFaces = g_SelectedFaces;
+CPtrArray& g_ptrSelectedFaceBrushes = g_SelectedFaceBrushes;
+
+
+void clearSelection() {
+ g_qeglobals.d_select_mode = sel_brush;
+ g_qeglobals.selectObject = NULL;
+}
+
+/*
+===========
+Test_Ray
+===========
+*/
+#define DIST_START 999999
+trace_t Test_Ray (vec3_t origin, vec3_t dir, int flags)
+{
+ brush_t *brush;
+ face_t *face;
+ float dist;
+ trace_t t;
+
+ memset (&t, 0, sizeof(t));
+ t.dist = DIST_START;
+
+ if (flags & SF_CYCLE)
+ {
+ CPtrArray array;
+ brush_t *pToSelect = (selected_brushes.next != &selected_brushes) ? selected_brushes.next : NULL;
+ Select_Deselect();
+
+ // go through active brushes and accumulate all "hit" brushes
+ for (brush = active_brushes.next ; brush != &active_brushes ; brush=brush->next)
+ {
+ //if ( (flags & SF_ENTITIES_FIRST) && brush->owner == world_entity)
+ // continue;
+
+ if (FilterBrush (brush))
+ continue;
+
+ if (!g_PrefsDlg.m_bSelectCurves && brush->patchBrush)
+ continue;
+
+ if( !g_PrefsDlg.m_bSelectTerrain && brush->terrainBrush )
+ continue;
+
+ //if (!g_bShowPatchBounds && brush->patchBrush)
+ // continue;
+
+ face = Brush_Ray (origin, dir, brush, &dist);
+
+ if (face)
+ {
+ if ( brush->terrainBrush )
+ {
+ Terrain_Ray( origin, dir, brush, &dist );
+ if( dist == 0 )
+ {
+ // didn't actually hit the terrain
+ continue;
+ }
+ }
+ array.Add(brush);
+ }
+ }
+
+ int nSize = array.GetSize();
+ if (nSize > 0)
+ {
+ bool bFound = false;
+ for (int i = 0; i < nSize; i++)
+ {
+ brush_t *b = reinterpret_cast<brush_t*>(array.GetAt(i));
+ // did we hit the last one selected yet ?
+ if (b == pToSelect)
+ {
+ // yes we want to select the next one in the list
+ int n = (i > 0) ? i-1 : nSize-1;
+ pToSelect = reinterpret_cast<brush_t*>(array.GetAt(n));
+ bFound = true;
+ break;
+ }
+ }
+ if (!bFound)
+ pToSelect = reinterpret_cast<brush_t*>(array.GetAt(0));
+ }
+ if (pToSelect)
+ {
+ face = Brush_Ray (origin, dir, pToSelect, &dist);
+ if ( pToSelect->terrainBrush )
+ {
+ t.terraface = Terrain_Ray( origin, dir, pToSelect, &dist );
+ }
+
+ t.dist = dist;
+ t.brush = pToSelect;
+ t.face = face;
+ t.selected = false;
+ return t;
+ }
+ }
+
+ if (! (flags & SF_SELECTED_ONLY) )
+ {
+ for (brush = active_brushes.next ; brush != &active_brushes ; brush=brush->next)
+ {
+ if ( (flags & SF_ENTITIES_FIRST) && brush->owner == world_entity)
+ continue;
+
+ if (FilterBrush (brush))
+ continue;
+
+ if (!g_PrefsDlg.m_bSelectCurves && brush->patchBrush)
+ continue;
+
+ if( !g_PrefsDlg.m_bSelectTerrain && brush->terrainBrush )
+ continue;
+
+ //if (!g_bShowPatchBounds && brush->patchBrush)
+ // continue;
+
+ face = Brush_Ray (origin, dir, brush, &dist);
+ if ( face ) {
+ if ( brush->terrainBrush )
+ {
+ t.terraface = Terrain_Ray( origin, dir, brush, &dist );
+ }
+ }
+ if (dist > 0 && dist < t.dist)
+ {
+ t.dist = dist;
+ t.brush = brush;
+ t.face = face;
+ t.selected = false;
+ }
+ }
+ }
+
+
+ for (brush = selected_brushes.next ; brush != &selected_brushes ; brush=brush->next)
+ {
+ if ( (flags & SF_ENTITIES_FIRST) && brush->owner == world_entity)
+ continue;
+
+ if (FilterBrush (brush))
+ continue;
+
+ if (!g_PrefsDlg.m_bSelectCurves && brush->patchBrush)
+ continue;
+
+ if( !g_PrefsDlg.m_bSelectTerrain && brush->terrainBrush )
+ continue;
+
+ face = Brush_Ray (origin, dir, brush, &dist);
+ if ( face ) {
+ if ( brush->terrainBrush )
+ {
+ t.terraface = Terrain_Ray( origin, dir, brush, &dist );
+ }
+ }
+ if (dist > 0 && dist < t.dist)
+ {
+ t.dist = dist;
+ t.brush = brush;
+ t.face = face;
+ t.selected = true;
+ }
+ }
+
+ // if entites first, but didn't find any, check regular
+
+ if ( (flags & SF_ENTITIES_FIRST) && t.brush == NULL)
+ return Test_Ray (origin, dir, flags - SF_ENTITIES_FIRST);
+
+ return t;
+
+}
+
+
+/*
+============
+Select_Brush
+
+============
+*/
+void Select_Brush (brush_t *brush, bool bComplete, bool bStatus)
+{
+ brush_t *b;
+ entity_t *e;
+
+ g_ptrSelectedFaces.RemoveAll();
+ g_ptrSelectedFaceBrushes.RemoveAll();
+ //selected_face = NULL;
+ if (g_qeglobals.d_select_count < 2)
+ g_qeglobals.d_select_order[g_qeglobals.d_select_count] = brush;
+ g_qeglobals.d_select_count++;
+
+ //if (brush->patchBrush)
+ // Patch_Select(brush->nPatchID);
+
+ e = brush->owner;
+ if (e)
+ {
+ // select complete entity on first click
+ if (e != world_entity && bComplete == true)
+ {
+ for (b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ if (b->owner == e)
+ goto singleselect;
+ for (b=e->brushes.onext ; b != &e->brushes ; b=b->onext)
+ {
+ Brush_RemoveFromList (b);
+ Brush_AddToList (b, &selected_brushes);
+ }
+ }
+ else
+ {
+singleselect:
+ Brush_RemoveFromList (brush);
+ Brush_AddToList (brush, &selected_brushes);
+ UpdateSurfaceDialog();
+ UpdatePatchInspector();
+ }
+
+ if (e->eclass)
+ {
+ UpdateEntitySel(brush->owner->eclass);
+ }
+ }
+ if (bStatus)
+ {
+ vec3_t vMin, vMax, vSize;
+ Select_GetBounds (vMin, vMax);
+ VectorSubtract(vMax, vMin, vSize);
+ CString strStatus;
+ strStatus.Format("Selection X:: %.1f Y:: %.1f Z:: %.1f", vSize[0], vSize[1], vSize[2]);
+ g_pParentWnd->SetStatusText(2, strStatus);
+ }
+}
+
+
+/*
+============
+Select_Ray
+
+If the origin is inside a brush, that brush will be ignored.
+============
+*/
+void Select_Ray (vec3_t origin, vec3_t dir, int flags)
+{
+ trace_t t;
+
+ t = Test_Ray (origin, dir, flags);
+ if (!t.brush)
+ return;
+
+ if (flags == SF_SINGLEFACE)
+ {
+ int nCount = g_SelectedFaces.GetSize();
+ bool bOk = true;
+ for (int i = 0; i < nCount; i++)
+ {
+ if (t.face == reinterpret_cast<face_t*>(g_SelectedFaces.GetAt(i)))
+ {
+ bOk = false;
+ // need to move remove i'th entry
+ g_SelectedFaces.RemoveAt(i, 1);
+ g_SelectedFaceBrushes.RemoveAt(i, 1);
+ }
+ }
+ if (bOk)
+ {
+ g_SelectedFaces.Add(t.face);
+ g_SelectedFaceBrushes.Add(t.brush);
+ }
+ //selected_face = t.face;
+ //selected_face_brush = t.brush;
+ Sys_UpdateWindows (W_ALL);
+ clearSelection();
+ // Texture_SetTexture requires a brushprimit_texdef fitted to the default width=2 height=2 texture
+ brushprimit_texdef_t brushprimit_texdef;
+ ConvertTexMatWithQTexture ( &t.face->brushprimit_texdef, t.face->d_texture, &brushprimit_texdef, NULL );
+ Texture_SetTexture ( &t.face->texdef, &brushprimit_texdef, false, GETPLUGINTEXDEF(t.face), false );
+ UpdateSurfaceDialog();
+ return;
+ }
+
+ // move the brush to the other list
+
+ clearSelection();
+
+ if (t.selected)
+ {
+ Brush_RemoveFromList (t.brush);
+ Brush_AddToList (t.brush, &active_brushes);
+ UpdatePatchInspector();
+ }
+ else
+ {
+ Select_Brush (t.brush, !(GetKeyState(VK_MENU) & 0x8000));
+ }
+
+ Sys_UpdateWindows (W_ALL);
+}
+
+
+void Select_Delete (void)
+{
+ brush_t *brush;
+
+ g_ptrSelectedFaces.RemoveAll();
+ g_ptrSelectedFaceBrushes.RemoveAll();
+ //selected_face = NULL;
+
+ clearSelection();
+
+ g_qeglobals.d_select_count = 0;
+ g_qeglobals.d_num_move_points = 0;
+ while (selected_brushes.next != &selected_brushes)
+ {
+ brush = selected_brushes.next;
+ if (brush->patchBrush)
+ {
+ //Patch_Delete(brush->nPatchID);
+ Patch_Delete(brush->pPatch);
+ }
+ if (brush->terrainBrush)
+ {
+ Terrain_Delete(brush->pTerrain );
+ }
+
+ Brush_Free (brush);
+ }
+
+ // FIXME: remove any entities with no brushes
+
+ Sys_UpdateWindows (W_ALL);
+}
+
+void Select_Deselect (bool bDeselectFaces)
+{
+ brush_t *b;
+
+ Patch_Deselect();
+
+ g_pParentWnd->ActiveXY()->UndoClear();
+
+ g_qeglobals.d_workcount++;
+ g_qeglobals.d_select_count = 0;
+ g_qeglobals.d_num_move_points = 0;
+ b = selected_brushes.next;
+
+ if (b == &selected_brushes)
+ {
+ if (bDeselectFaces)
+ {
+ g_ptrSelectedFaces.RemoveAll();
+ g_ptrSelectedFaceBrushes.RemoveAll();
+ //selected_face = NULL;
+ }
+ Sys_UpdateWindows (W_ALL);
+ return;
+ }
+
+ if (bDeselectFaces)
+ {
+ g_ptrSelectedFaces.RemoveAll();
+ g_ptrSelectedFaceBrushes.RemoveAll();
+ //selected_face = NULL;
+ }
+
+ clearSelection();
+
+ // grab top / bottom height for new brushes
+ if (b->mins[2] < b->maxs[2])
+ {
+ g_qeglobals.d_new_brush_bottom_z = b->mins[2];
+ g_qeglobals.d_new_brush_top_z = b->maxs[2];
+ }
+
+ selected_brushes.next->prev = &active_brushes;
+ selected_brushes.prev->next = active_brushes.next;
+ active_brushes.next->prev = selected_brushes.prev;
+ active_brushes.next = selected_brushes.next;
+ selected_brushes.prev = selected_brushes.next = &selected_brushes;
+
+ Sys_UpdateWindows (W_ALL);
+}
+
+/*
+============
+Select_Move
+============
+*/
+void Select_Move (vec3_t delta, bool bSnap)
+{
+ brush_t *b;
+
+
+// actually move the selected brushes
+ for (b = selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ Brush_Move (b, delta, bSnap);
+
+ vec3_t vMin, vMax;
+ Select_GetBounds (vMin, vMax);
+ CString strStatus;
+ strStatus.Format("Origin X:: %.1f Y:: %.1f Z:: %.1f", vMin[0], vMax[1], vMax[2]);
+ g_pParentWnd->SetStatusText(2, strStatus);
+
+// Sys_UpdateWindows (W_ALL);
+}
+
+/*
+============
+Select_Clone
+
+Creates an exact duplicate of the selection in place, then moves
+the selected brushes off of their old positions
+============
+*/
+void Select_Clone (void)
+{
+#if 1
+ ASSERT(g_pParentWnd->ActiveXY());
+ g_bScreenUpdates = false;
+ g_pParentWnd->ActiveXY()->Copy();
+ g_pParentWnd->ActiveXY()->Paste();
+ g_pParentWnd->NudgeSelection(2, g_qeglobals.d_gridsize);
+ g_pParentWnd->NudgeSelection(3, g_qeglobals.d_gridsize);
+ g_bScreenUpdates = true;
+ Sys_UpdateWindows(W_ALL);
+#else
+
+ brush_t *b, *b2, *n, *next, *next2;
+ vec3_t delta;
+ entity_t *e;
+
+ g_qeglobals.d_workcount++;
+ clearSelection();
+
+ delta[0] = g_qeglobals.d_gridsize;
+ delta[1] = g_qeglobals.d_gridsize;
+ delta[2] = 0;
+
+ for (b=selected_brushes.next ; b != &selected_brushes ; b=next)
+ {
+ next = b->next;
+ // if the brush is a world brush, handle simply
+ if (b->owner == world_entity)
+ {
+ n = Brush_Clone (b);
+ Brush_AddToList (n, &active_brushes);
+ Entity_LinkBrush (world_entity, n);
+ Brush_Build( n );
+ Brush_Move (b, delta);
+ continue;
+ }
+
+ e = Entity_Clone (b->owner);
+ // clear the target / targetname
+ DeleteKey (e, "target");
+ DeleteKey (e, "targetname");
+
+ // if the brush is a fixed size entity, create a new entity
+ if (b->owner->eclass->fixedsize)
+ {
+ n = Brush_Clone (b);
+ Brush_AddToList (n, &active_brushes);
+ Entity_LinkBrush (e, n);
+ Brush_Build( n );
+ Brush_Move (b, delta);
+ continue;
+ }
+
+ // brush is a complex entity, grab all the other ones now
+
+ next = &selected_brushes;
+
+ for ( b2 = b ; b2 != &selected_brushes ; b2=next2)
+ {
+ next2 = b2->next;
+ if (b2->owner != b->owner)
+ {
+ if (next == &selected_brushes)
+ next = b2;
+ continue;
+ }
+
+ // move b2 to the start of selected_brushes,
+ // so it won't be hit again
+ Brush_RemoveFromList (b2);
+ Brush_AddToList (b2, &selected_brushes);
+
+ n = Brush_Clone (b2);
+ Brush_AddToList (n, &active_brushes);
+ Entity_LinkBrush (e, n);
+ Brush_Build( n );
+ Brush_Move (b2, delta, true);
+ }
+
+ }
+ Sys_UpdateWindows (W_ALL);
+#endif
+}
+
+
+
+/*
+============
+Select_SetTexture
+Timo : bFitScale to compute scale on the plane and counteract plane / axial plane snapping
+Timo : brush primitive texturing
+ the brushprimit_texdef given must be understood as a qtexture_t width=2 height=2 ( HiRes )
+Timo : texture plugin, added an IPluginTexdef* parameter
+ must be casted to an IPluginTexdef!
+ if not NULL, get ->Copy() of it into each face or brush ( and remember to hook )
+ if NULL, means we have no information, ask for a default
+============
+*/
+void WINAPI Select_SetTexture (texdef_t *texdef, brushprimit_texdef_t *brushprimit_texdef, bool bFitScale, void* pPlugTexdef )
+{
+ brush_t *b;
+ int nCount = g_ptrSelectedFaces.GetSize();
+ if (nCount > 0)
+ {
+ Undo_Start("set face textures");
+ ASSERT(g_ptrSelectedFaces.GetSize() == g_ptrSelectedFaceBrushes.GetSize());
+ for (int i = 0; i < nCount; i++)
+ {
+ face_t *selFace = reinterpret_cast<face_t*>(g_ptrSelectedFaces.GetAt(i));
+ brush_t *selBrush = reinterpret_cast<brush_t*>(g_ptrSelectedFaceBrushes.GetAt(i));
+ Undo_AddBrush(selBrush);
+ SetFaceTexdef (selBrush, selFace, texdef, brushprimit_texdef, bFitScale, static_cast<IPluginTexdef *>(pPlugTexdef) );
+ Brush_Build(selBrush, bFitScale);
+ Undo_EndBrush(selBrush);
+ }
+ Undo_End();
+ }
+ else if (selected_brushes.next != &selected_brushes)
+ {
+ Undo_Start("set brush textures");
+ for (b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ if (!b->owner->eclass->fixedsize)
+ {
+ Undo_AddBrush(b);
+ Brush_SetTexture (b, texdef, brushprimit_texdef, bFitScale, static_cast<IPluginTexdef *>(pPlugTexdef) );
+ Undo_EndBrush(b);
+ }
+ Undo_End();
+ }
+ Sys_UpdateWindows (W_ALL);
+}
+
+
+/*
+================================================================
+
+ TRANSFORMATIONS
+
+================================================================
+*/
+
+void Select_GetBounds (vec3_t mins, vec3_t maxs)
+{
+ brush_t *b;
+ int i;
+
+ for (i=0 ; i<3 ; i++)
+ {
+ mins[i] = 99999;
+ maxs[i] = -99999;
+ }
+
+ for (b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ for (i=0 ; i<3 ; i++)
+ {
+ if (b->mins[i] < mins[i])
+ mins[i] = b->mins[i];
+ if (b->maxs[i] > maxs[i])
+ maxs[i] = b->maxs[i];
+ }
+}
+
+
+void Select_GetTrueMid (vec3_t mid)
+{
+ vec3_t mins, maxs;
+ Select_GetBounds (mins, maxs);
+
+ for (int i=0 ; i<3 ; i++)
+ mid[i] = (mins[i] + ((maxs[i] - mins[i]) / 2));
+}
+
+
+void Select_GetMid (vec3_t mid)
+{
+ vec3_t mins, maxs;
+ int i;
+
+ if (g_PrefsDlg.m_bNoClamp)
+ {
+ Select_GetTrueMid(mid);
+ return;
+ }
+
+ Select_GetBounds (mins, maxs);
+
+ for (i=0 ; i<3 ; i++)
+ mid[i] = g_qeglobals.d_gridsize*floor ( ( (mins[i] + maxs[i])*0.5 )/g_qeglobals.d_gridsize );
+
+}
+
+vec3_t select_origin;
+vec3_t select_matrix[3];
+qboolean select_fliporder;
+
+void Select_ApplyMatrix (bool bSnap, bool bRotation, int nAxis, float fDeg)
+{
+ brush_t *b;
+ face_t *f;
+ int i, j;
+ vec3_t temp;
+
+ for (b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ {
+ for (f=b->brush_faces ; f ; f=f->next)
+ {
+ for (i=0 ; i<3 ; i++)
+ {
+ VectorSubtract (f->planepts[i], select_origin, temp);
+ for (j=0 ; j<3 ; j++)
+ f->planepts[i][j] = DotProduct(temp, select_matrix[j]) + select_origin[j];
+ }
+ if (select_fliporder)
+ {
+ VectorCopy (f->planepts[0], temp);
+ VectorCopy (f->planepts[2], f->planepts[0]);
+ VectorCopy (temp, f->planepts[2]);
+ }
+ }
+
+ if(b->owner->eclass->fixedsize)
+ {
+ if (bRotation && b->owner->md3Class)
+ {
+ b->owner->vRotation[nAxis] += fDeg;
+ }
+ }
+
+ Brush_Build(b, bSnap);
+
+ if (b->patchBrush)
+ {
+ //Patch_ApplyMatrix(b->nPatchID, select_origin, select_matrix);
+ Patch_ApplyMatrix(b->pPatch, select_origin, select_matrix, bSnap);
+ }
+
+ if (b->terrainBrush)
+ {
+ Terrain_ApplyMatrix(b->pTerrain, select_origin, select_matrix, bSnap);
+ }
+
+ }
+}
+
+void ProjectOnPlane(vec3_t& normal,float dist,vec3_t& ez, vec3_t& p)
+{
+ if (fabs(ez[0]) == 1)
+ p[0] = (dist - normal[1] * p[1] - normal[2] * p[2]) / normal[0];
+ else if (fabs(ez[1]) == 1)
+ p[1] = (dist - normal[0] * p[0] - normal[2] * p[2]) / normal[1];
+ else
+ p[2] = (dist - normal[0] * p[0] - normal[1] * p[1]) / normal[2];
+}
+
+void Back(vec3_t& dir, vec3_t& p)
+{
+ if (fabs(dir[0]) == 1)
+ p[0] = 0;
+ else if (fabs(dir[1]) == 1)
+ p[1] = 0;
+ else p[2] = 0;
+}
+
+
+
+// using scale[0] and scale[1]
+void ComputeScale(vec3_t& rex, vec3_t& rey, vec3_t& p, face_t* f)
+{
+ float px = DotProduct(rex, p);
+ float py = DotProduct(rey, p);
+ px *= f->texdef.scale[0];
+ py *= f->texdef.scale[1];
+ vec3_t aux;
+ VectorCopy(rex, aux);
+ VectorScale(aux, px, aux);
+ VectorCopy(aux, p);
+ VectorCopy(rey, aux);
+ VectorScale(aux, py, aux);
+ VectorAdd(p, aux, p);
+}
+
+void ComputeAbsolute(face_t* f, vec3_t& p1, vec3_t& p2, vec3_t& p3)
+{
+ vec3_t ex,ey,ez; // local axis base
+
+#ifdef _DEBUG
+ if (g_qeglobals.m_bBrushPrimitMode)
+ Sys_Printf("Warning : illegal call of ComputeAbsolute in brush primitive mode\n");
+#endif
+
+ // compute first local axis base
+ TextureAxisFromPlane(&f->plane, ex, ey);
+ CrossProduct(ex, ey, ez);
+
+ vec3_t aux;
+ VectorCopy(ex, aux);
+ VectorScale(aux, -f->texdef.shift[0], aux);
+ VectorCopy(aux, p1);
+ VectorCopy(ey, aux);
+ VectorScale(aux, -f->texdef.shift[1], aux);
+ VectorAdd(p1, aux, p1);
+ VectorCopy(p1, p2);
+ VectorAdd(p2, ex, p2);
+ VectorCopy(p1, p3);
+ VectorAdd(p3, ey, p3);
+ VectorCopy(ez, aux);
+ VectorScale(aux, -f->texdef.rotate, aux);
+ VectorRotate(p1, aux, p1);
+ VectorRotate(p2, aux, p2);
+ VectorRotate(p3, aux, p3);
+ // computing rotated local axis base
+ vec3_t rex,rey;
+ VectorCopy(ex, rex);
+ VectorRotate(rex, aux, rex);
+ VectorCopy(ey, rey);
+ VectorRotate(rey, aux, rey);
+
+ ComputeScale(rex,rey,p1,f);
+ ComputeScale(rex,rey,p2,f);
+ ComputeScale(rex,rey,p3,f);
+
+ // project on normal plane
+ // along ez
+ // assumes plane normal is normalized
+ ProjectOnPlane(f->plane.normal,f->plane.dist,ez,p1);
+ ProjectOnPlane(f->plane.normal,f->plane.dist,ez,p2);
+ ProjectOnPlane(f->plane.normal,f->plane.dist,ez,p3);
+};
+
+
+void AbsoluteToLocal(plane_t normal2, face_t* f, vec3_t& p1, vec3_t& p2, vec3_t& p3)
+{
+ vec3_t ex,ey,ez;
+
+#ifdef _DEBUG
+ if (g_qeglobals.m_bBrushPrimitMode)
+ Sys_Printf("Warning : illegal call of AbsoluteToLocal in brush primitive mode\n");
+#endif
+
+ // computing new local axis base
+ TextureAxisFromPlane(&normal2, ex, ey);
+ CrossProduct(ex, ey, ez);
+
+ // projecting back on (ex,ey)
+ Back(ez,p1);
+ Back(ez,p2);
+ Back(ez,p3);
+
+ vec3_t aux;
+ // rotation
+ VectorCopy(p2, aux);
+ VectorSubtract(aux, p1,aux);
+
+ float x = DotProduct(aux,ex);
+ float y = DotProduct(aux,ey);
+ f->texdef.rotate = 180 * atan2(y,x) / Q_PI;
+
+ vec3_t rex,rey;
+ // computing rotated local axis base
+ VectorCopy(ez, aux);
+ VectorScale(aux, f->texdef.rotate, aux);
+ VectorCopy(ex, rex);
+ VectorRotate(rex, aux, rex);
+ VectorCopy(ey, rey);
+ VectorRotate(rey, aux, rey);
+
+ // scale
+ VectorCopy(p2, aux);
+ VectorSubtract(aux, p1, aux);
+ f->texdef.scale[0] = DotProduct(aux, rex);
+ VectorCopy(p3, aux);
+ VectorSubtract(aux, p1, aux);
+ f->texdef.scale[1] = DotProduct(aux, rey);
+
+ // shift
+ // only using p1
+ x = DotProduct(rex,p1);
+ y = DotProduct(rey,p1);
+ x /= f->texdef.scale[0];
+ y /= f->texdef.scale[1];
+
+ VectorCopy(rex, p1);
+ VectorScale(p1, x, p1);
+ VectorCopy(rey, aux);
+ VectorScale(aux, y, aux);
+ VectorAdd(p1, aux, p1);
+ VectorCopy(ez, aux);
+ VectorScale(aux, -f->texdef.rotate, aux);
+ VectorRotate(p1, aux, p1);
+ f->texdef.shift[0] = -DotProduct(p1, ex);
+ f->texdef.shift[1] = -DotProduct(p1, ey);
+
+ // stored rot is good considering local axis base
+ // change it if necessary
+ f->texdef.rotate = -f->texdef.rotate;
+
+ Clamp(f->texdef.shift[0], f->d_texture->width);
+ Clamp(f->texdef.shift[1], f->d_texture->height);
+ Clamp(f->texdef.rotate, 360);
+
+}
+
+void RotateFaceTexture(face_t* f, int nAxis, float fDeg)
+{
+ vec3_t p1,p2,p3, rota;
+ p1[0] = p1[1] = p1[2] = 0;
+ VectorCopy(p1, p2);
+ VectorCopy(p1, p3);
+ VectorCopy(p1, rota);
+ ComputeAbsolute(f, p1, p2, p3);
+
+ rota[nAxis] = fDeg;
+ VectorRotate(p1, rota, select_origin, p1);
+ VectorRotate(p2, rota, select_origin, p2);
+ VectorRotate(p3, rota, select_origin, p3);
+
+ plane_t normal2;
+ vec3_t vNormal;
+ vNormal[0] = f->plane.normal[0];
+ vNormal[1] = f->plane.normal[1];
+ vNormal[2] = f->plane.normal[2];
+ VectorRotate(vNormal, rota, vNormal);
+ normal2.normal[0] = vNormal[0];
+ normal2.normal[1] = vNormal[1];
+ normal2.normal[2] = vNormal[2];
+ AbsoluteToLocal(normal2, f, p1, p2 ,p3);
+
+}
+
+void RotateTextures(int nAxis, float fDeg, vec3_t vOrigin)
+{
+ for (brush_t* b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ {
+ for (face_t* f=b->brush_faces ; f ; f=f->next)
+ {
+ if (g_qeglobals.m_bBrushPrimitMode)
+ RotateFaceTexture_BrushPrimit( f, nAxis, fDeg, vOrigin );
+ else
+ RotateFaceTexture(f, nAxis, fDeg);
+ //++timo removed that call .. works fine .. ???????
+// Brush_Build(b, false);
+ }
+ Brush_Build(b, false);
+ }
+}
+
+
+void Select_FlipAxis (int axis)
+{
+ int i;
+
+ Select_GetMid (select_origin);
+ for (i=0 ; i<3 ; i++)
+ {
+ VectorCopy (vec3_origin, select_matrix[i]);
+ select_matrix[i][i] = 1;
+ }
+ select_matrix[axis][axis] = -1;
+
+ select_fliporder = true;
+ Select_ApplyMatrix (true, false, 0, 0);
+ Sys_UpdateWindows (W_ALL);
+}
+
+
+void Select_Scale(float x, float y, float z)
+{
+ Select_GetMid (select_origin);
+ for (brush_t* b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ {
+ for (face_t* f=b->brush_faces ; f ; f=f->next)
+ {
+ for (int i=0 ; i<3 ; i++)
+ {
+ f->planepts[i][0] -= select_origin[0];
+ f->planepts[i][1] -= select_origin[1];
+ f->planepts[i][2] -= select_origin[2];
+ f->planepts[i][0] *= x;
+ //f->planepts[i][0] = floor(f->planepts[i][0] / g_qeglobals.d_gridsize + 0.5) * g_qeglobals.d_gridsize;
+
+ f->planepts[i][1] *= y;
+ //f->planepts[i][1] = floor(f->planepts[i][1] / g_qeglobals.d_gridsize + 0.5) * g_qeglobals.d_gridsize;
+
+ f->planepts[i][2] *= z;
+ //f->planepts[i][2] = floor(f->planepts[i][2] / g_qeglobals.d_gridsize + 0.5) * g_qeglobals.d_gridsize;
+
+ f->planepts[i][0] += select_origin[0];
+ f->planepts[i][1] += select_origin[1];
+ f->planepts[i][2] += select_origin[2];
+ }
+ }
+ Brush_Build(b, false);
+ if (b->patchBrush)
+ {
+ vec3_t v;
+ v[0] = x;
+ v[1] = y;
+ v[2] = z;
+ //Patch_Scale(b->nPatchID, select_origin, v);
+ Patch_Scale(b->pPatch, select_origin, v);
+ }
+ if (b->terrainBrush)
+ {
+ vec3_t v;
+ v[0] = x;
+ v[1] = y;
+ v[2] = z;
+ Terrain_Scale(b->pTerrain, select_origin, v);
+ }
+ }
+}
+
+void Select_RotateAxis (int axis, float deg, bool bPaint, bool bMouse)
+{
+ vec3_t temp;
+ int i, j;
+ vec_t c, s;
+
+ if (deg == 0)
+ {
+ //Sys_Printf("0 deg\n");
+ return;
+ }
+
+ if (bMouse)
+ {
+ VectorCopy(g_pParentWnd->ActiveXY()->RotateOrigin(), select_origin);
+ }
+ else
+ {
+ Select_GetMid (select_origin);
+ }
+
+ select_fliporder = false;
+
+ if (deg == 90)
+ {
+ for (i=0 ; i<3 ; i++)
+ {
+ VectorCopy (vec3_origin, select_matrix[i]);
+ select_matrix[i][i] = 1;
+ }
+ i = (axis+1)%3;
+ j = (axis+2)%3;
+ VectorCopy (select_matrix[i], temp);
+ VectorCopy (select_matrix[j], select_matrix[i]);
+ VectorSubtract (vec3_origin, temp, select_matrix[j]);
+ }
+ else
+ {
+ deg = -deg;
+ if (deg == -180.0)
+ {
+ c = -1;
+ s = 0;
+ }
+ else if (deg == -270.0)
+ {
+ c = 0;
+ s = -1;
+ }
+ else
+ {
+ c = cos(deg * Q_PI / 180.0);
+ s = sin(deg * Q_PI / 180.0);
+ }
+
+ for (i=0 ; i<3 ; i++)
+ {
+ VectorCopy (vec3_origin, select_matrix[i]);
+ select_matrix[i][i] = 1;
+ }
+
+ switch (axis)
+ {
+ case 0:
+ select_matrix[1][1] = c;
+ select_matrix[1][2] = -s;
+ select_matrix[2][1] = s;
+ select_matrix[2][2] = c;
+ break;
+ case 1:
+ select_matrix[0][0] = c;
+ select_matrix[0][2] = s;
+ select_matrix[2][0] = -s;
+ select_matrix[2][2] = c;
+ break;
+ case 2:
+ select_matrix[0][0] = c;
+ select_matrix[0][1] = -s;
+ select_matrix[1][0] = s;
+ select_matrix[1][1] = c;
+ break;
+ }
+ }
+
+ if (g_PrefsDlg.m_bRotateLock)
+ RotateTextures(axis, deg, select_origin);
+ Select_ApplyMatrix(!bMouse, true, axis, deg);
+
+ if (bPaint)
+ Sys_UpdateWindows (W_ALL);
+}
+
+/*
+================================================================
+
+GROUP SELECTIONS
+
+================================================================
+*/
+
+void Select_CompleteTall (void)
+{
+ brush_t *b, *next;
+ //int i;
+ vec3_t mins, maxs;
+
+ if (!QE_SingleBrush ())
+ return;
+
+ clearSelection();
+
+ VectorCopy (selected_brushes.next->mins, mins);
+ VectorCopy (selected_brushes.next->maxs, maxs);
+ Select_Delete ();
+
+ int nDim1 = (g_pParentWnd->ActiveXY()->GetViewType() == YZ) ? 1 : 0;
+ int nDim2 = (g_pParentWnd->ActiveXY()->GetViewType() == XY) ? 1 : 2;
+
+ for (b=active_brushes.next ; b != &active_brushes ; b=next)
+ {
+ next = b->next;
+
+ if ( (b->maxs[nDim1] > maxs[nDim1] || b->mins[nDim1] < mins[nDim1])
+ || (b->maxs[nDim2] > maxs[nDim2] || b->mins[nDim2] < mins[nDim2]) )
+ continue;
+
+ if (FilterBrush (b))
+ continue;
+
+ Brush_RemoveFromList (b);
+ Brush_AddToList (b, &selected_brushes);
+#if 0
+ // old stuff
+ for (i=0 ; i<2 ; i++)
+ if (b->maxs[i] > maxs[i] || b->mins[i] < mins[i])
+ break;
+ if (i == 2)
+ {
+ Brush_RemoveFromList (b);
+ Brush_AddToList (b, &selected_brushes);
+ }
+#endif
+ }
+ Sys_UpdateWindows (W_ALL);
+}
+
+void Select_PartialTall (void)
+{
+ brush_t *b, *next;
+ //int i;
+ vec3_t mins, maxs;
+
+ if (!QE_SingleBrush ())
+ return;
+
+ clearSelection();
+
+ VectorCopy (selected_brushes.next->mins, mins);
+ VectorCopy (selected_brushes.next->maxs, maxs);
+ Select_Delete ();
+
+ int nDim1 = (g_pParentWnd->ActiveXY()->GetViewType() == YZ) ? 1 : 0;
+ int nDim2 = (g_pParentWnd->ActiveXY()->GetViewType() == XY) ? 1 : 2;
+
+ for (b=active_brushes.next ; b != &active_brushes ; b=next)
+ {
+ next = b->next;
+
+ if ( (b->mins[nDim1] > maxs[nDim1] || b->maxs[nDim1] < mins[nDim1])
+ || (b->mins[nDim2] > maxs[nDim2] || b->maxs[nDim2] < mins[nDim2]) )
+ continue;
+
+ if (FilterBrush (b))
+ continue;
+
+ Brush_RemoveFromList (b);
+ Brush_AddToList (b, &selected_brushes);
+
+
+#if 0
+// old stuff
+ for (i=0 ; i<2 ; i++)
+ if (b->mins[i] > maxs[i] || b->maxs[i] < mins[i])
+ break;
+ if (i == 2)
+ {
+ Brush_RemoveFromList (b);
+ Brush_AddToList (b, &selected_brushes);
+ }
+#endif
+ }
+ Sys_UpdateWindows (W_ALL);
+}
+
+void Select_Touching (void)
+{
+ brush_t *b, *next;
+ int i;
+ vec3_t mins, maxs;
+
+ if (!QE_SingleBrush ())
+ return;
+
+ clearSelection();
+
+ VectorCopy (selected_brushes.next->mins, mins);
+ VectorCopy (selected_brushes.next->maxs, maxs);
+
+ for (b=active_brushes.next ; b != &active_brushes ; b=next)
+ {
+ next = b->next;
+
+ if (FilterBrush (b))
+ continue;
+
+ for (i=0 ; i<3 ; i++)
+ if (b->mins[i] > maxs[i]+1 || b->maxs[i] < mins[i]-1)
+ break;
+
+ if (i == 3)
+ {
+ Brush_RemoveFromList (b);
+ Brush_AddToList (b, &selected_brushes);
+ }
+ }
+ Sys_UpdateWindows (W_ALL);
+}
+
+void Select_Inside (void)
+{
+ brush_t *b, *next;
+ int i;
+ vec3_t mins, maxs;
+
+ if (!QE_SingleBrush ())
+ return;
+
+ clearSelection();
+
+ VectorCopy (selected_brushes.next->mins, mins);
+ VectorCopy (selected_brushes.next->maxs, maxs);
+ Select_Delete ();
+
+ for (b=active_brushes.next ; b != &active_brushes ; b=next)
+ {
+ next = b->next;
+
+ if (FilterBrush (b))
+ continue;
+
+ for (i=0 ; i<3 ; i++)
+ if (b->maxs[i] > maxs[i] || b->mins[i] < mins[i])
+ break;
+ if (i == 3)
+ {
+ Brush_RemoveFromList (b);
+ Brush_AddToList (b, &selected_brushes);
+ }
+ }
+ Sys_UpdateWindows (W_ALL);
+}
+
+/*
+=============
+Select_Ungroup
+
+Turn the currently selected entity back into normal brushes
+=============
+*/
+void Select_Ungroup(void)
+{
+ int numselectedgroups;
+ entity_t *e;
+ brush_t *b, *sb;
+
+ numselectedgroups = 0;
+ for (sb = selected_brushes.next; sb != &selected_brushes; sb = sb->next)
+ {
+ e = sb->owner;
+
+ if (!e || e == world_entity || e->eclass->fixedsize)
+ {
+ continue;
+ }
+
+ for (b = e->brushes.onext; b != &e->brushes; b = e->brushes.onext)
+ {
+ //Brush_RemoveFromList (b);
+ //Brush_AddToList (b, &active_brushes);
+ Entity_UnlinkBrush (b);
+ Entity_LinkBrush (world_entity, b);
+ Brush_Build( b );
+ b->owner = world_entity;
+ }
+ Entity_Free (e);
+ numselectedgroups++;
+ }
+
+ if (numselectedgroups <= 0)
+ {
+ Sys_Printf("No grouped entities selected.\n");
+ return;
+ }
+ Sys_Printf("Ungrouped %d entit%s.\n", numselectedgroups, (numselectedgroups == 1)?"y":"ies");
+ Sys_UpdateWindows (W_ALL);
+}
+
+
+/*
+====================
+Select_MakeStructural
+====================
+*/
+void Select_MakeStructural (void)
+{
+ brush_t *b;
+ face_t *f;
+
+ for (b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ for (f=b->brush_faces ; f ; f=f->next)
+ f->texdef.contents &= ~CONTENTS_DETAIL;
+ Select_Deselect ();
+ Sys_UpdateWindows (W_ALL);
+}
+
+void Select_MakeDetail (void)
+{
+ brush_t *b;
+ face_t *f;
+
+ for (b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ for (f=b->brush_faces ; f ; f=f->next)
+ f->texdef.contents |= CONTENTS_DETAIL;
+ Select_Deselect ();
+ Sys_UpdateWindows (W_ALL);
+}
+
+void Select_ShiftTexture(int x, int y)
+{
+ brush_t *b;
+ face_t *f;
+
+ int nFaceCount = g_ptrSelectedFaces.GetSize();
+
+ if(selected_brushes.next == &selected_brushes && nFaceCount == 0)
+ return;
+
+ for (b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ {
+ for (f=b->brush_faces ; f ; f=f->next)
+ {
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ // use face normal to compute a true translation
+ Select_ShiftTexture_BrushPrimit( f, x, y );
+ }
+ else
+ {
+ f->texdef.shift[0] += x;
+ f->texdef.shift[1] += y;
+ }
+ }
+ Brush_Build(b);
+ if (b->patchBrush)
+ {
+ //Patch_ShiftTexture(b->nPatchID, x, y);
+ Patch_ShiftTexture(b->pPatch, x, y);
+ }
+ }
+
+ if (nFaceCount > 0)
+ {
+ for (int i = 0; i < nFaceCount; i++)
+ {
+ face_t *selFace = reinterpret_cast<face_t*>(g_ptrSelectedFaces.GetAt(i));
+ brush_t *selBrush = reinterpret_cast<brush_t*>(g_ptrSelectedFaceBrushes.GetAt(i));
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+
+ // use face normal to compute a true translation
+ // Select_ShiftTexture_BrushPrimit( selected_face, x, y );
+ // use camera view to compute texture shift
+ g_pParentWnd->GetCamera()->ShiftTexture_BrushPrimit( selFace, x, y );
+ }
+ else
+ {
+ selFace->texdef.shift[0] += x;
+ selFace->texdef.shift[1] += y;
+ }
+ Brush_Build(selBrush);
+ }
+ }
+
+ Sys_UpdateWindows (W_CAMERA);
+}
+
+void Select_ScaleTexture(int x, int y)
+{
+ brush_t *b;
+ face_t *f;
+
+ int nFaceCount = g_ptrSelectedFaces.GetSize();
+
+ if(selected_brushes.next == &selected_brushes && nFaceCount == 0)
+ {
+ return;
+ }
+
+ for (b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ {
+ for (f=b->brush_faces ; f ; f=f->next)
+ {
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ // apply same scale as the spinner button of the surface inspector
+ float shift[2];
+ float rotate;
+ float scale[2];
+ brushprimit_texdef_t bp;
+ // compute normalized texture matrix
+ ConvertTexMatWithQTexture( &f->brushprimit_texdef, f->d_texture, &bp, NULL );
+ // compute fake shift scale rot
+ TexMatToFakeTexCoords( bp.coords, shift, &rotate, scale );
+ // update
+ scale[0]+=static_cast<float>(x)*0.1;
+ scale[1]+=static_cast<float>(y)*0.1;
+ // compute new normalized texture matrix
+ FakeTexCoordsToTexMat( shift, rotate, scale, bp.coords );
+ // apply to face texture matrix
+ ConvertTexMatWithQTexture( &bp, NULL, &f->brushprimit_texdef, f->d_texture );
+ }
+ else
+ {
+ f->texdef.scale[0] += x;
+ f->texdef.scale[1] += y;
+ }
+ }
+ Brush_Build(b);
+ if (b->patchBrush)
+ {
+ Patch_ScaleTexture(b->pPatch, x, y);
+ }
+ }
+
+ if (nFaceCount > 0)
+ {
+ for (int i = 0; i < nFaceCount; i++)
+ {
+ face_t *selFace = reinterpret_cast<face_t*>(g_ptrSelectedFaces.GetAt(i));
+ brush_t *selBrush = reinterpret_cast<brush_t*>(g_ptrSelectedFaceBrushes.GetAt(i));
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ float shift[2];
+ float rotate;
+ float scale[2];
+ brushprimit_texdef_t bp;
+ ConvertTexMatWithQTexture( &selFace->brushprimit_texdef, selFace->d_texture, &bp, NULL );
+ TexMatToFakeTexCoords( bp.coords, shift, &rotate, scale );
+ scale[0]+=static_cast<float>(x)*0.1;
+ scale[1]+=static_cast<float>(y)*0.1;
+ FakeTexCoordsToTexMat( shift, rotate, scale, bp.coords );
+ ConvertTexMatWithQTexture( &bp, NULL, &selFace->brushprimit_texdef, selFace->d_texture );
+ }
+ else
+ {
+ selFace->texdef.scale[0] += x;
+ selFace->texdef.scale[1] += y;
+ }
+ Brush_Build(selBrush);
+ }
+ }
+
+ Sys_UpdateWindows (W_CAMERA);
+}
+
+void Select_RotateTexture(int amt)
+{
+ brush_t *b;
+ face_t *f;
+
+ int nFaceCount = g_ptrSelectedFaces.GetSize();
+
+ if(selected_brushes.next == &selected_brushes && nFaceCount == 0)
+ {
+ return;
+ }
+
+ for (b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ {
+ for (f=b->brush_faces ; f ; f=f->next)
+ {
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ // apply same scale as the spinner button of the surface inspector
+ float shift[2];
+ float rotate;
+ float scale[2];
+ brushprimit_texdef_t bp;
+ // compute normalized texture matrix
+ ConvertTexMatWithQTexture( &f->brushprimit_texdef, f->d_texture, &bp, NULL );
+ // compute fake shift scale rot
+ TexMatToFakeTexCoords( bp.coords, shift, &rotate, scale );
+ // update
+ rotate += amt;
+ // compute new normalized texture matrix
+ FakeTexCoordsToTexMat( shift, rotate, scale, bp.coords );
+ // apply to face texture matrix
+ ConvertTexMatWithQTexture( &bp, NULL, &f->brushprimit_texdef, f->d_texture );
+ }
+ else
+ {
+ f->texdef.rotate += amt;
+ f->texdef.rotate = static_cast<int>(f->texdef.rotate) % 360;
+ }
+ }
+ Brush_Build(b);
+ if (b->patchBrush)
+ {
+ //Patch_RotateTexture(b->nPatchID, amt);
+ Patch_RotateTexture(b->pPatch, amt);
+ }
+ }
+
+ if (nFaceCount > 0)
+ {
+ for (int i = 0; i < nFaceCount; i++)
+ {
+ face_t *selFace = reinterpret_cast<face_t*>(g_ptrSelectedFaces.GetAt(i));
+ brush_t *selBrush = reinterpret_cast<brush_t*>(g_ptrSelectedFaceBrushes.GetAt(i));
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ float shift[2];
+ float rotate;
+ float scale[2];
+ brushprimit_texdef_t bp;
+ ConvertTexMatWithQTexture( &selFace->brushprimit_texdef, selFace->d_texture, &bp, NULL );
+ TexMatToFakeTexCoords( bp.coords, shift, &rotate, scale );
+ rotate += amt;
+ FakeTexCoordsToTexMat( shift, rotate, scale, bp.coords );
+ ConvertTexMatWithQTexture( &bp, NULL, &selFace->brushprimit_texdef, selFace->d_texture );
+ }
+ else
+ {
+ selFace->texdef.rotate += amt;
+ selFace->texdef.rotate = static_cast<int>(selFace->texdef.rotate) % 360;
+ }
+ Brush_Build(selBrush);
+ }
+ }
+
+ Sys_UpdateWindows (W_CAMERA);
+}
+
+
+void FindReplaceTextures(const char* pFind, const char* pReplace, bool bSelected, bool bForce)
+{
+ brush_t* pList = (bSelected) ? &selected_brushes : &active_brushes;
+ if (!bSelected)
+ {
+ Select_Deselect();
+ }
+
+ for (brush_t* pBrush = pList->next ; pBrush != pList; pBrush = pBrush->next)
+ {
+ if (pBrush->patchBrush)
+ {
+ Patch_FindReplaceTexture(pBrush, pFind, pReplace, bForce);
+ }
+
+ if (pBrush->terrainBrush)
+ {
+ Terrain_FindReplaceTexture(pBrush->pTerrain, pFind, pReplace, bForce);
+ }
+ for (face_t* pFace = pBrush->brush_faces; pFace; pFace = pFace->next)
+ {
+ if(bForce || strcmpi(pFace->texdef.name, pFind) == 0)
+ {
+ pFace->d_texture = Texture_ForName(pReplace);
+ //strcpy(pFace->texdef.name, pReplace);
+ pFace->texdef.SetName(pReplace);
+ }
+ }
+ Brush_Build(pBrush);
+ }
+ Sys_UpdateWindows (W_CAMERA);
+}
+
+
+void Select_AllOfType()
+{
+ brush_t *b, *next;
+ entity_t *e;
+ if ( (selected_brushes.next == &selected_brushes)
+ || (selected_brushes.next->next != &selected_brushes) )
+ {
+
+ CString strName;
+ if (g_ptrSelectedFaces.GetSize() == 0)
+ {
+ strName = g_qeglobals.d_texturewin.texdef.name;
+ }
+ else
+ {
+ face_t *selFace = reinterpret_cast<face_t*>(g_ptrSelectedFaces.GetAt(0));
+ strName = selFace->texdef.name;
+ }
+
+ Select_Deselect();
+ for (b=active_brushes.next ; b != &active_brushes ; b=next)
+ {
+ next = b->next;
+
+ if (FilterBrush (b))
+ continue;
+
+ if (b->patchBrush)
+ {
+ if (strcmpi(strName, b->pPatch->d_texture->name) == 0)
+ {
+ Brush_RemoveFromList (b);
+ Brush_AddToList (b, &selected_brushes);
+ }
+ }
+ else
+ {
+ for (face_t* pFace = b->brush_faces; pFace; pFace = pFace->next)
+ {
+ if (strcmpi(strName, pFace->texdef.name) == 0)
+ {
+ Brush_RemoveFromList (b);
+ Brush_AddToList (b, &selected_brushes);
+ }
+ }
+ }
+ }
+ Sys_UpdateWindows(W_ALL);
+ return;
+ }
+
+
+ b = selected_brushes.next;
+ e = b->owner;
+
+ if (e != NULL)
+ {
+ if (e != world_entity)
+ {
+ CString strName = e->eclass->name;
+ CString strKey, strVal;
+ bool bCriteria = GetSelectAllCriteria(strKey, strVal);
+ Sys_Printf("Selecting all %s(s)\n", strName);
+ Select_Deselect();
+
+ for (b=active_brushes.next ; b != &active_brushes ; b=next)
+ {
+ next = b->next;
+
+ if (FilterBrush (b))
+ continue;
+
+ e = b->owner;
+ if (e != NULL)
+ {
+ if (strcmpi(e->eclass->name, strName) == 0)
+ {
+ bool doIt = true;
+ if (bCriteria) {
+ CString str = ValueForKey (e, strKey);
+ if (str.CompareNoCase(strVal) != 0) {
+ doIt = false;
+ }
+ }
+ if (doIt) {
+ Brush_RemoveFromList (b);
+ Brush_AddToList (b, &selected_brushes);
+ }
+ }
+ }
+ }
+ }
+ }
+ Sys_UpdateWindows (W_ALL);
+
+}
+
+void Select_Reselect()
+{
+ CPtrArray holdArray;
+ for (brush_t* b=selected_brushes.next ; b && b != &selected_brushes ; b=b->next)
+ {
+ holdArray.Add(reinterpret_cast<void*>(b));
+ }
+
+ int n = holdArray.GetSize();
+ while (n-- > 0)
+ {
+ b = reinterpret_cast<brush_t*>(holdArray.GetAt(n));
+ Select_Brush(b);
+ }
+ Sys_UpdateWindows (W_ALL);
+}
+
+
+void Select_FitTexture(int nHeight, int nWidth)
+{
+ brush_t *b;
+
+ int nFaceCount = g_ptrSelectedFaces.GetSize();
+
+ if(selected_brushes.next == &selected_brushes && nFaceCount == 0)
+ return;
+
+ for (b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ {
+ Brush_FitTexture(b, nHeight, nWidth);
+ Brush_Build(b);
+ }
+
+ if (nFaceCount > 0)
+ {
+ for (int i = 0; i < nFaceCount; i++)
+ {
+ face_t *selFace = reinterpret_cast<face_t*>(g_ptrSelectedFaces.GetAt(i));
+ brush_t *selBrush = reinterpret_cast<brush_t*>(g_ptrSelectedFaceBrushes.GetAt(i));
+ Face_FitTexture(selFace, nHeight, nWidth);
+ Brush_Build(selBrush);
+ }
+ }
+
+ Sys_UpdateWindows (W_CAMERA);
+}
+
+void Select_AxialTexture()
+{
+
+}
+
+void Select_Hide()
+{
+ for (brush_t* b=selected_brushes.next ; b && b != &selected_brushes ; b=b->next)
+ {
+ b->hiddenBrush = true;
+ }
+ Sys_UpdateWindows (W_ALL);
+}
+
+void Select_ShowAllHidden()
+{
+ brush_t* b;
+ for (b=selected_brushes.next ; b && b != &selected_brushes ; b=b->next)
+ {
+ b->hiddenBrush = false;
+ }
+ for (b=active_brushes.next ; b && b != &active_brushes ; b=b->next)
+ {
+ b->hiddenBrush = false;
+ }
+ Sys_UpdateWindows (W_ALL);
+}
+
+
+/*
+============
+Select_Invert
+============
+*/
+void Select_Invert(void)
+{
+ brush_t *next, *prev;
+
+ Sys_Printf("inverting selection...\n");
+
+ next = active_brushes.next;
+ prev = active_brushes.prev;
+ if (selected_brushes.next != &selected_brushes)
+ {
+ active_brushes.next = selected_brushes.next;
+ active_brushes.prev = selected_brushes.prev;
+ active_brushes.next->prev = &active_brushes;
+ active_brushes.prev->next = &active_brushes;
+ }
+ else
+ {
+ active_brushes.next = &active_brushes;
+ active_brushes.prev = &active_brushes;
+ }
+ if (next != &active_brushes)
+ {
+ selected_brushes.next = next;
+ selected_brushes.prev = prev;
+ selected_brushes.next->prev = &selected_brushes;
+ selected_brushes.prev->next = &selected_brushes;
+ }
+ else
+ {
+ selected_brushes.next = &selected_brushes;
+ selected_brushes.prev = &selected_brushes;
+ }
+
+ Sys_UpdateWindows(W_ALL);
+
+ Sys_Printf("done.\n");
+}
+
+
+/*
+===========
+Select_Name
+===========
+*/
+void Select_Name(const char *pName)
+{
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ for (brush_t* b=selected_brushes.next ; b && b != &selected_brushes ; b=b->next)
+ {
+ Brush_SetEpair(b, "Name", pName);
+ }
+ }
+}
+
+/*
+=================
+Select_AddToGroup
+add selected brushes to a group, update the tree
+=================
+*/
+void Select_AddToGroup(const char *pName)
+{
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ for (brush_t* b=selected_brushes.next ; b && b != &selected_brushes ; b=b->next)
+ {
+ Brush_SetEpair(b, "group", pName);
+ Group_AddToProperGroup(b);
+ }
+ }
+}
diff --git a/q3radiant/SELECT.H b/q3radiant/SELECT.H
new file mode 100755
index 0000000..ee6e0dc
--- /dev/null
+++ b/q3radiant/SELECT.H
@@ -0,0 +1,91 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+typedef enum
+{
+ sel_brush,
+ // sel_sticky_brush,
+ // sel_face,
+ sel_vertex,
+ sel_edge,
+ sel_singlevertex,
+ sel_curvepoint,
+ sel_area,
+ sel_terrainpoint,
+ sel_terraintexture,
+ sel_addpoint, // for dropping points
+ sel_editpoint // for editing points
+
+} select_t;
+
+typedef struct
+{
+ brush_t *brush;
+ face_t *face;
+ terrainFace_t *terraface;
+ float dist;
+ qboolean selected;
+} trace_t;
+
+
+#define SF_SELECTED_ONLY 0x01
+#define SF_ENTITIES_FIRST 0x02
+#define SF_SINGLEFACE 0x04
+#define SF_IGNORECURVES 0x08
+#define SF_IGNOREGROUPS 0x10
+#define SF_CYCLE 0x20
+#define SF_CYCLEKEEP 0x40
+
+
+trace_t Test_Ray (vec3_t origin, vec3_t dir, int flags);
+
+void Select_GetBounds (vec3_t mins, vec3_t maxs);
+void Select_Brush (brush_t *b, bool bComplete = true, bool bStatus = true);
+void Select_Ray (vec3_t origin, vec3_t dir, int flags);
+void Select_Delete (void);
+void Select_Deselect (bool bDeselectFaces = true);
+void Select_Invert(void);
+void Select_Clone (void);
+void Select_Move (vec3_t delta, bool bSnap = true);
+void WINAPI Select_SetTexture (texdef_t *texdef, brushprimit_texdef_t *brushprimit_texdef, bool bFitScale = false, void* pPlugTexdef = NULL);
+void Select_FlipAxis (int axis);
+void Select_RotateAxis (int axis, float deg, bool bPaint = true, bool bMouse = false);
+void Select_CompleteTall (void);
+void Select_PartialTall (void);
+void Select_Touching (void);
+void Select_Inside (void);
+void Select_MakeStructural (void);
+void Select_MakeDetail (void);
+void Select_AllOfType();
+void Select_Reselect();
+void Select_FitTexture(int nHeight = 1, int nWidth = 1);
+
+// absolute texture coordinates
+// TTimo NOTE: this is stuff for old brushes format and rotation texture lock .. sort of in-between with bush primitives
+void ComputeAbsolute(face_t* f, vec3_t& p1, vec3_t& p2, vec3_t& p3);
+void AbsoluteToLocal(plane_t normal2, face_t* f, vec3_t& p1, vec3_t& p2, vec3_t& p3);
+void Select_Hide();
+void Select_ShowAllHidden();
+// add selected brushes to a group, update the tree
+void Select_AddToGroup(const char *pName);
+void Select_Name(const char *pName);
+void clearSelection();
diff --git a/q3radiant/ScaleDialog.cpp b/q3radiant/ScaleDialog.cpp
new file mode 100755
index 0000000..ef487a6
--- /dev/null
+++ b/q3radiant/ScaleDialog.cpp
@@ -0,0 +1,68 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// ScaleDialog.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "ScaleDialog.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CScaleDialog dialog
+
+
+CScaleDialog::CScaleDialog(CWnd* pParent /*=NULL*/)
+ : CDialog(CScaleDialog::IDD, pParent)
+{
+ //{{AFX_DATA_INIT(CScaleDialog)
+ m_fZ = 1.0f;
+ m_fX = 1.0f;
+ m_fY = 1.0f;
+ //}}AFX_DATA_INIT
+}
+
+
+void CScaleDialog::DoDataExchange(CDataExchange* pDX)
+{
+ CDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CScaleDialog)
+ DDX_Text(pDX, IDC_EDIT_Z, m_fZ);
+ DDX_Text(pDX, IDC_EDIT_X, m_fX);
+ DDX_Text(pDX, IDC_EDIT_Y, m_fY);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CScaleDialog, CDialog)
+ //{{AFX_MSG_MAP(CScaleDialog)
+ // NOTE: the ClassWizard will add message map macros here
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CScaleDialog message handlers
diff --git a/q3radiant/ScaleDialog.h b/q3radiant/ScaleDialog.h
new file mode 100755
index 0000000..d7fe920
--- /dev/null
+++ b/q3radiant/ScaleDialog.h
@@ -0,0 +1,69 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_SCALEDIALOG_H__8A9B33B2_9922_11D1_B568_00AA00A410FC__INCLUDED_)
+#define AFX_SCALEDIALOG_H__8A9B33B2_9922_11D1_B568_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// ScaleDialog.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CScaleDialog dialog
+
+class CScaleDialog : public CDialog
+{
+// Construction
+public:
+ CScaleDialog(CWnd* pParent = NULL); // standard constructor
+
+// Dialog Data
+ //{{AFX_DATA(CScaleDialog)
+ enum { IDD = IDD_DIALOG_SCALE };
+ float m_fZ;
+ float m_fX;
+ float m_fY;
+ //}}AFX_DATA
+
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CScaleDialog)
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+
+ // Generated message map functions
+ //{{AFX_MSG(CScaleDialog)
+ // NOTE: the ClassWizard will add member functions here
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_SCALEDIALOG_H__8A9B33B2_9922_11D1_B568_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/ScriptDlg.cpp b/q3radiant/ScriptDlg.cpp
new file mode 100755
index 0000000..8774001
--- /dev/null
+++ b/q3radiant/ScriptDlg.cpp
@@ -0,0 +1,103 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// ScriptDlg.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "ScriptDlg.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CScriptDlg dialog
+
+
+CScriptDlg::CScriptDlg(CWnd* pParent /*=NULL*/)
+ : CDialog(CScriptDlg::IDD, pParent)
+{
+ //{{AFX_DATA_INIT(CScriptDlg)
+ m_strScript = _T("");
+ //}}AFX_DATA_INIT
+}
+
+
+void CScriptDlg::DoDataExchange(CDataExchange* pDX)
+{
+ CDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CScriptDlg)
+ DDX_Control(pDX, IDC_LIST_SCRIPTS, m_lstScripts);
+ DDX_LBString(pDX, IDC_LIST_SCRIPTS, m_strScript);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CScriptDlg, CDialog)
+ //{{AFX_MSG_MAP(CScriptDlg)
+ ON_BN_CLICKED(ID_RUN, OnRun)
+ ON_LBN_DBLCLK(IDC_LIST_SCRIPTS, OnDblclkListScripts)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CScriptDlg message handlers
+
+void CScriptDlg::OnRun()
+{
+ UpdateData(TRUE);
+ EndDialog(IDOK);
+ RunScriptByName(m_strScript.GetBuffer(0), true);
+}
+
+BOOL CScriptDlg::OnInitDialog()
+{
+ CDialog::OnInitDialog();
+
+ char* pBuff = new char[16384];
+ CString strINI = g_strAppPath;
+ strINI += "\\scripts.ini";
+ int n = GetPrivateProfileSectionNames(pBuff, 16384, strINI);
+
+ // CStringList list;
+ m_lstScripts.ResetContent();
+ char* pWorkBuff = pBuff;
+ while (*pWorkBuff != NULL)
+ {
+ m_lstScripts.AddString(pWorkBuff);
+ pWorkBuff += strlen(pWorkBuff) + 1;
+ }
+ delete []pBuff;
+ return TRUE; // return TRUE unless you set the focus to a control
+ // EXCEPTION: OCX Property Pages should return FALSE
+}
+
+
+void CScriptDlg::OnDblclkListScripts()
+{
+ UpdateData(TRUE);
+ EndDialog(IDOK);
+ RunScriptByName(m_strScript.GetBuffer(0), true);
+}
diff --git a/q3radiant/ScriptDlg.h b/q3radiant/ScriptDlg.h
new file mode 100755
index 0000000..427ef95
--- /dev/null
+++ b/q3radiant/ScriptDlg.h
@@ -0,0 +1,70 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_SCRIPTDLG_H__C241B9A4_819F_11D1_B548_00AA00A410FC__INCLUDED_)
+#define AFX_SCRIPTDLG_H__C241B9A4_819F_11D1_B548_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// ScriptDlg.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CScriptDlg dialog
+
+class CScriptDlg : public CDialog
+{
+// Construction
+public:
+ CScriptDlg(CWnd* pParent = NULL); // standard constructor
+
+// Dialog Data
+ //{{AFX_DATA(CScriptDlg)
+ enum { IDD = IDD_DLG_SCRIPTS };
+ CListBox m_lstScripts;
+ CString m_strScript;
+ //}}AFX_DATA
+
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CScriptDlg)
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+
+ // Generated message map functions
+ //{{AFX_MSG(CScriptDlg)
+ afx_msg void OnRun();
+ virtual BOOL OnInitDialog();
+ afx_msg void OnDblclkListScripts();
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_SCRIPTDLG_H__C241B9A4_819F_11D1_B548_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/SelectedFace.cpp b/q3radiant/SelectedFace.cpp
new file mode 100755
index 0000000..c1bd18b
--- /dev/null
+++ b/q3radiant/SelectedFace.cpp
@@ -0,0 +1,136 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//-----------------------------------------------------------------------------
+//
+// $LogFile$
+// $Revision: 1.1.1.4 $
+// $Author: ttimo $
+// $Date: 2000/01/18 00:18:13 $
+// $Log: SelectedFace.cpp,v $
+// Revision 1.1.1.4 2000/01/18 00:18:13 ttimo
+// merging in for RC
+//
+// Revision 1.3 2000/01/17 23:53:43 TBesset
+// ready for merge in sourceforge (RC candidate)
+//
+// Revision 1.2 2000/01/07 16:40:12 TBesset
+// merged from BSP frontend
+//
+// Revision 1.1.1.3 1999/12/29 18:31:45 TBesset
+// Q3Radiant public version
+//
+// Revision 1.1.1.1.2.1 1999/12/29 21:39:41 TBesset
+// updated to update3 from Robert
+//
+// Revision 1.1.1.3 1999/12/29 18:31:45 TBesset
+// Q3Radiant public version
+//
+// Revision 1.2 1999/11/22 17:46:47 Timo & Christine
+// merged EARadiant into the main tree
+// bug fixes for Q3Plugin / EAPlugin
+// export for Robert
+//
+// Revision 1.1.4.2 1999/11/14 16:26:13 Timo & Christine
+// first beta of the ritualmap surface plugin
+//
+// Revision 1.1.4.1 1999/11/03 20:38:02 Timo & Christine
+// MEAN plugin for Q3Radiant, alpha version
+//
+// Revision 1.1.2.1 1999/10/27 08:34:28 Timo & Christine
+// preview version of the texture tools plugin is ready
+// ( TexTool.dll plugin is in Q3Plugin module )
+// plugins can draw in their own window using Radiant's qgl bindings
+//
+//
+// DESCRIPTION:
+// Quick interface hack for selected face interface
+// this one really needs more work, but I'm in a hurry with TexTool
+
+#include "stdafx.h"
+
+HGLRC WINAPI QERApp_GetQeglobalsHGLRC()
+{
+ return g_qeglobals.d_hglrcBase;
+}
+
+// pWinding is supposed to have MAX_POINTS_ON_WINDING
+int WINAPI QERApp_GetFaceInfo(_QERFaceData *pFaceData, winding_t *pWinding)
+{
+ int size;
+
+ if (g_ptrSelectedFaces.GetSize() > 0)
+ {
+ if (!g_qeglobals.m_bBrushPrimitMode)
+ {
+ Sys_Printf("Warning: unexpected QERApp_GetFaceInfo out of brush primitive mode\n");
+ return 0;
+ }
+ //++timo NOTE: let's put only what we need for now
+ face_t *selFace = reinterpret_cast<face_t*>(g_ptrSelectedFaces.GetAt(0));
+ strcpy( pFaceData->m_TextureName, selFace->texdef.name );
+ VectorCopy( selFace->planepts[0], pFaceData->m_v1 );
+ VectorCopy( selFace->planepts[1], pFaceData->m_v2 );
+ VectorCopy( selFace->planepts[2], pFaceData->m_v3 );
+ pFaceData->m_bBPrimit = true;
+ memcpy( &pFaceData->brushprimit_texdef, &selFace->brushprimit_texdef, sizeof(brushprimit_texdef_t) );
+ size = (int)((winding_t *)0)->points[selFace->face_winding->numpoints];
+ memcpy( pWinding, selFace->face_winding, size );
+ return 1;
+ }
+ return 0;
+}
+
+int WINAPI QERApp_SetFaceInfo(_QERFaceData *pFaceData)
+{
+ if (g_ptrSelectedFaces.GetSize() > 0)
+ {
+ if (!g_qeglobals.m_bBrushPrimitMode)
+ {
+ Sys_Printf("Warning: unexpected QERApp_SetFaceInfo out of brush primitive mode\n");
+ return 0;
+ }
+ face_t *selFace = reinterpret_cast<face_t*>(g_ptrSelectedFaces.GetAt(0));
+ brush_t *selBrush = reinterpret_cast<brush_t*>(g_ptrSelectedFaceBrushes.GetAt(0));
+ //strcpy( selected_face->texdef.name, pFaceData->m_TextureName );
+ selFace->texdef.SetName(pFaceData->m_TextureName);
+ VectorCopy( pFaceData->m_v1, selFace->planepts[0] );
+ VectorCopy( pFaceData->m_v2, selFace->planepts[1] );
+ VectorCopy( pFaceData->m_v3, selFace->planepts[2] );
+ memcpy( &selFace->brushprimit_texdef, &pFaceData->brushprimit_texdef, sizeof(brushprimit_texdef_t) );
+ Brush_Build( selBrush );
+ Sys_UpdateWindows(W_ALL);
+ return 1;
+ }
+ return 0;
+}
+
+void WINAPI QERApp_GetTextureSize( int Size[2] )
+{
+ if (g_ptrSelectedFaces.GetSize() > 0)
+ {
+ face_t *selFace = reinterpret_cast<face_t*>(g_ptrSelectedFaces.GetAt(0));
+ Size[0] = selFace->d_texture->width;
+ Size[1] = selFace->d_texture->height;
+ }
+ else
+ Sys_Printf("WARNING: unexpected call to QERApp_GetTextureSize with no selected_face\n");
+} \ No newline at end of file
diff --git a/q3radiant/ShaderEdit.cpp b/q3radiant/ShaderEdit.cpp
new file mode 100755
index 0000000..965b555
--- /dev/null
+++ b/q3radiant/ShaderEdit.cpp
@@ -0,0 +1,66 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// ShaderEdit.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "ShaderEdit.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CShaderEdit
+
+IMPLEMENT_DYNCREATE(CShaderEdit, CFrameWnd)
+
+CShaderEdit::CShaderEdit()
+{
+}
+
+CShaderEdit::~CShaderEdit()
+{
+}
+
+
+BEGIN_MESSAGE_MAP(CShaderEdit, CFrameWnd)
+ //{{AFX_MSG_MAP(CShaderEdit)
+ ON_WM_CREATE()
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CShaderEdit message handlers
+
+int CShaderEdit::OnCreate(LPCREATESTRUCT lpCreateStruct)
+{
+ if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
+ return -1;
+
+ // TODO: Add your specialized creation code here
+
+ return 0;
+}
diff --git a/q3radiant/ShaderEdit.h b/q3radiant/ShaderEdit.h
new file mode 100755
index 0000000..cad8bbf
--- /dev/null
+++ b/q3radiant/ShaderEdit.h
@@ -0,0 +1,70 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_SHADEREDIT_H__CFE2CBF1_E980_11D2_A509_0020AFEB881A__INCLUDED_)
+#define AFX_SHADEREDIT_H__CFE2CBF1_E980_11D2_A509_0020AFEB881A__INCLUDED_
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+// ShaderEdit.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CShaderEdit frame
+
+class CShaderEdit : public CFrameWnd
+{
+ DECLARE_DYNCREATE(CShaderEdit)
+protected:
+ CShaderEdit(); // protected constructor used by dynamic creation
+
+ CStatusBar m_StatusBar;
+ CToolBar m_ToolBar;
+
+// Attributes
+public:
+
+// Operations
+public:
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CShaderEdit)
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+ virtual ~CShaderEdit();
+
+ // Generated message map functions
+ //{{AFX_MSG(CShaderEdit)
+ afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+/////////////////////////////////////////////////////////////////////////////
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_SHADEREDIT_H__CFE2CBF1_E980_11D2_A509_0020AFEB881A__INCLUDED_)
diff --git a/q3radiant/ShaderInfo.cpp b/q3radiant/ShaderInfo.cpp
new file mode 100755
index 0000000..d898865
--- /dev/null
+++ b/q3radiant/ShaderInfo.cpp
@@ -0,0 +1,69 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// ShaderInfo.cpp: implementation of the CShaderInfo class.
+//
+//////////////////////////////////////////////////////////////////////
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "ShaderInfo.h"
+
+#ifdef _DEBUG
+#undef THIS_FILE
+static char THIS_FILE[]=__FILE__;
+#define new DEBUG_NEW
+#endif
+
+//////////////////////////////////////////////////////////////////////
+// Construction/Destruction
+//////////////////////////////////////////////////////////////////////
+
+CShaderInfo::CShaderInfo()
+{
+ m_fTransValue = 1.0;
+ m_nFlags = 0;
+ m_pQTexture = NULL;
+}
+
+CShaderInfo::~CShaderInfo()
+{
+
+}
+
+void CShaderInfo::Parse(const char *pName)
+{
+
+}
+
+void CShaderInfo::setName(char *pName)
+{
+ //--char path[1024];
+ //--strcpy(path, pName);
+ //--DefaultExtension(path, ".tga");
+ m_strName = pName;
+ m_strName.MakeLower();
+ if (m_strName.Find("textures") == 0)
+ {
+ CString s = m_strName.Right(m_strName.GetLength() - strlen("textures") - 1);
+ m_strName = s;
+ }
+}
diff --git a/q3radiant/ShaderInfo.h b/q3radiant/ShaderInfo.h
new file mode 100755
index 0000000..bca4414
--- /dev/null
+++ b/q3radiant/ShaderInfo.h
@@ -0,0 +1,55 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// ShaderInfo.h: interface for the CShaderInfo class.
+//
+//////////////////////////////////////////////////////////////////////
+
+#if !defined(AFX_SHADERINFO_H__93B64600_A208_11D2_803D_0020AFEB881A__INCLUDED_)
+#define AFX_SHADERINFO_H__93B64600_A208_11D2_803D_0020AFEB881A__INCLUDED_
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+class CShaderInfo
+{
+public:
+ CString m_strName;
+ CString m_strShaderName;
+ CString m_strTextureName;
+ CStringList m_strEditorParams;
+ CStringList m_lstSurfaceParams;
+ float m_fTransValue;
+ int m_nFlags;
+ qtexture_t *m_pQTexture;
+
+
+ void Parse(const char *pName);
+ CShaderInfo();
+ virtual ~CShaderInfo();
+ void setName(char *pName);
+
+
+
+};
+
+#endif // !defined(AFX_SHADERINFO_H__93B64600_A208_11D2_803D_0020AFEB881A__INCLUDED_)
diff --git a/q3radiant/StdAfx.cpp b/q3radiant/StdAfx.cpp
new file mode 100755
index 0000000..dc9c067
--- /dev/null
+++ b/q3radiant/StdAfx.cpp
@@ -0,0 +1,27 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// stdafx.cpp : source file that includes just the standard includes
+// Radiant.pch will be the pre-compiled header
+// stdafx.obj will contain the pre-compiled type information
+
+#include "stdafx.h"
+
diff --git a/q3radiant/StdAfx.h b/q3radiant/StdAfx.h
new file mode 100755
index 0000000..5a9e543
--- /dev/null
+++ b/q3radiant/StdAfx.h
@@ -0,0 +1,154 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// stdafx.h : include file for standard system include files,
+// or project specific include files that are used frequently, but
+// are changed infrequently
+//
+
+#if !defined(AFX_STDAFX_H__330BBF08_731C_11D1_B539_00AA00A410FC__INCLUDED_)
+#define AFX_STDAFX_H__330BBF08_731C_11D1_B539_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+
+#pragma warning(disable: 4305) // For: double to float
+#pragma warning(disable: 4800) // For: performance warning on bool conversions
+
+#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers
+
+#include <afxwin.h> // MFC core and standard components
+#include <afxext.h> // MFC extensions
+#include <afxdisp.h> // MFC OLE automation classes
+#ifndef _AFX_NO_AFXCMN_SUPPORT
+#include <afxcmn.h> // MFC support for Windows Common Controls
+#endif // _AFX_NO_AFXCMN_SUPPORT
+
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_STDAFX_H__330BBF08_731C_11D1_B539_00AA00A410FC__INCLUDED_)
+
+#include "MainFrm.h"
+#include "PrefsDlg.h"
+#include "FindTextureDlg.h"
+
+
+extern CMainFrame* g_pParentWnd;
+extern CString g_strAppPath;
+extern CPrefsDlg& g_PrefsDlg;
+extern CFindTextureDlg& g_dlgFind;
+
+// layout styles
+#define QR_SPLIT 0
+#define QR_QE4 1
+#define QR_4WAY 2
+#define QR_SPLITZ 3
+
+
+// externs
+extern void AddSlash(CString&);
+extern void DLLBuildDone();
+extern void CleanUpEntities();
+extern void MFCCreate(HINSTANCE);
+extern BOOL Init3Dfx();
+extern void FindReplace(CString& strContents, const char* pTag, const char* pValue);
+extern void CheckBspProcess();
+extern void QE_CountBrushesAndUpdateStatusBar();
+extern void QE_CheckAutoSave();
+extern qtexture_t *notexture;
+extern qtexture_t *current_texture;
+extern BOOL SaveWindowState(HWND hWnd, const char *pszName);
+extern BOOL DoMru(HWND, WORD);
+extern void RunBsp (char *command);
+extern void Map_Snapshot();
+extern void WXY_Print();
+extern void AddProp( void );
+extern qboolean DoColor(int iIndex);
+extern entity_t *edit_entity;
+extern int inspector_mode;
+extern bool g_bRotateMode;
+extern bool g_bClipMode;
+extern bool g_bScaleMode;
+extern int g_nScaleHow;
+extern bool g_bPathMode;
+extern bool ByeByeSurfaceDialog();
+extern void RunScript(char* pBuffer);
+extern bool ExtractPath_and_Filename(const char* pPath, CString& strPath, CString& strFilename);
+extern HINSTANCE g_hOpenGL32;
+extern void Select_Scale(float x, float y, float z);
+extern void Select_RotateTexture(int amt);
+extern void Select_ScaleTexture(int x, int y);
+extern void Select_ShiftTexture(int x, int y);
+extern void FindReplaceTextures(const char* pFind, const char* pReplace, bool bSelected, bool bForce);
+extern void DoProjectSettings();
+extern qboolean region_active;
+extern void Brush_Print(brush_t* b);
+extern void Texture_ShowDirectory (char* pPath, bool Linked = false);
+extern void Map_ImportFile (char *filename);
+extern void Map_SaveSelected(char* pFilename);
+extern void UpdateSurfaceDialog();
+extern bool g_bNewFace;
+extern void Select_GetTrueMid (vec3_t mid);
+extern bool g_bSwitch;
+extern brush_t g_brFrontSplits;
+extern brush_t g_brBackSplits;
+extern CClipPoint g_Clip1;
+extern CClipPoint g_Clip2;
+extern brush_t* g_pSplitList;
+extern CClipPoint g_PathPoints[256];
+extern void AcquirePath(int nCount, PFNPathCallback* pFunc);
+extern bool g_bScreenUpdates;
+extern SCommandInfo g_Commands[];
+extern int g_nCommandCount;
+extern SKeyInfo g_Keys[];
+extern int g_nKeyCount;
+extern int inspector_mode;
+extern char *bsp_commands[256];
+extern void RunScriptByName(char*, bool);
+extern void DoNewColor(int* i1, int* i2, int* i3);
+extern void UpdateSurfaceDialog();
+extern void CSG_SplitBrushByFace (brush_t *in, face_t *f, brush_t **front, brush_t **back);
+extern void HandlePopup(CWnd* pWindow, unsigned int uId);
+extern z_t z;
+extern void Select_Scale(float x, float y, float z);
+extern CString g_strProject;
+extern void TextureAxisFromPlane(plane_t *pln, vec3_t xv, vec3_t yv);
+extern void VectorRotate (vec3_t va, vec3_t vb, vec3_t out);
+extern void VectorRotate (vec3_t vIn, vec3_t vRotation, vec3_t vOrigin, vec3_t out);
+extern qboolean QE_SaveProject (const char* pProjectFile);
+extern void NewBSP(char* pCommandLine, HWND);
+extern void NewVIS(char* pCommandLine, HWND);
+extern void NewRAD(char* pCommandLine, HWND);
+extern void RunTools(char* pCommandLine, HWND, const char*);
+extern void Clamp(float& f, int nClamp);
+extern void MemFile_fprintf(CMemFile* pMemFile, const char* pText, ...);
+extern void SaveWindowPlacement(HWND hwnd, const char* pName);
+extern bool LoadWindowPlacement(HWND hwnd, const char* pName);
+extern qboolean ConfirmModified (void);
+extern void DoPatchInspector();
+void UpdatePatchInspector();
+extern int BuildShortPathName(const char* pPath, char* pBuffer, int nBufferLen);
+extern int g_nBrushId;
+
+
diff --git a/q3radiant/SurfaceDlg.cpp b/q3radiant/SurfaceDlg.cpp
new file mode 100755
index 0000000..6930126
--- /dev/null
+++ b/q3radiant/SurfaceDlg.cpp
@@ -0,0 +1,983 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// SurfaceDlg.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "SurfaceDlg.h"
+#include "PrefsDlg.h"
+#include "mainfrm.h"
+#include "TextureLayout.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// surface properties plugin
+// global flag for surface properties plugin is g_qeglobals.bSurfacePropertiesPlugin
+_QERPlugSurfaceTable g_SurfaceTable;
+
+/////////////////////////////////////////////////////////////////////////////
+// CSurfaceDlg dialog
+
+CSurfaceDlg g_dlgSurface;
+
+
+CSurfaceDlg::CSurfaceDlg(CWnd* pParent /*=NULL*/)
+ : CDialog(CSurfaceDlg::IDD, pParent)
+{
+ //{{AFX_DATA_INIT(CSurfaceDlg)
+ m_nHeight = 1;
+ m_nWidth = 1;
+ //}}AFX_DATA_INIT
+}
+
+
+void CSurfaceDlg::DoDataExchange(CDataExchange* pDX)
+{
+ CDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CSurfaceDlg)
+ DDX_Control(pDX, IDC_SPIN_WIDTH, m_wndWidth);
+ DDX_Control(pDX, IDC_SPIN_HEIGHT, m_wndHeight);
+ DDX_Control(pDX, IDC_SPIN_VSHIFT, m_wndVShift);
+ DDX_Control(pDX, IDC_SPIN_VSCALE, m_wndVScale);
+ DDX_Control(pDX, IDC_SPIN_ROTATE, m_wndRotate);
+ DDX_Control(pDX, IDC_SPIN_HSHIFT, m_wndHShift);
+ DDX_Control(pDX, IDC_SPIN_HSCALE, m_wndHScale);
+ DDX_Text(pDX, IDC_EDIT_HEIGHT, m_nHeight);
+ DDV_MinMaxInt(pDX, m_nHeight, 1, 32);
+ DDX_Text(pDX, IDC_EDIT_WIDTH, m_nWidth);
+ DDV_MinMaxInt(pDX, m_nWidth, 1, 32);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CSurfaceDlg, CDialog)
+ //{{AFX_MSG_MAP(CSurfaceDlg)
+ ON_WM_HSCROLL()
+ ON_WM_KEYDOWN()
+ ON_WM_VSCROLL()
+ ON_BN_CLICKED(IDAPPLY, OnApply)
+ ON_WM_CLOSE()
+ ON_WM_DESTROY()
+ ON_BN_CLICKED(ID_BTN_CANCEL, OnBtnCancel)
+ ON_BN_CLICKED(IDC_BTN_COLOR, OnBtnColor)
+ ON_WM_CTLCOLOR()
+ ON_WM_CREATE()
+ ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN_HSHIFT, OnDeltaPosSpin)
+ ON_BN_CLICKED(IDC_BTN_PATCHDETAILS, OnBtnPatchdetails)
+ ON_BN_CLICKED(IDC_BTN_PATCHNATURAL, OnBtnPatchnatural)
+ ON_BN_CLICKED(IDC_BTN_PATCHRESET, OnBtnPatchreset)
+ ON_BN_CLICKED(IDC_BTN_PATCHFIT, OnBtnPatchfit)
+ ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN_HSCALE, OnDeltaPosSpin)
+ ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN_ROTATE, OnDeltaPosSpin)
+ ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN_VSCALE, OnDeltaPosSpin)
+ ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN_VSHIFT, OnDeltaPosSpin)
+ ON_BN_CLICKED(IDC_BTN_AXIAL, OnBtnAxial)
+ ON_BN_CLICKED(IDC_BTN_BRUSHFIT, OnBtnBrushfit)
+ ON_BN_CLICKED(IDC_BTN_FACEFIT, OnBtnFacefit)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CSurfaceDlg message handlers
+
+
+/*
+===================================================
+
+ SURFACE INSPECTOR
+
+===================================================
+*/
+
+texdef_t g_old_texdef;
+texdef_t g_patch_texdef;
+HWND g_surfwin = NULL;
+qboolean g_changed_surface;
+
+int g_checkboxes[64] = {
+ IDC_CHECK1, IDC_CHECK2, IDC_CHECK3, IDC_CHECK4,
+ IDC_CHECK5, IDC_CHECK6, IDC_CHECK7, IDC_CHECK8,
+ IDC_CHECK9, IDC_CHECK10, IDC_CHECK11, IDC_CHECK12,
+ IDC_CHECK13, IDC_CHECK14, IDC_CHECK15, IDC_CHECK16,
+ IDC_CHECK17, IDC_CHECK18, IDC_CHECK19, IDC_CHECK20,
+ IDC_CHECK21, IDC_CHECK22, IDC_CHECK23, IDC_CHECK24,
+ IDC_CHECK25, IDC_CHECK26, IDC_CHECK27, IDC_CHECK28,
+ IDC_CHECK29, IDC_CHECK30, IDC_CHECK31, IDC_CHECK32,
+
+ IDC_CHECK33, IDC_CHECK34, IDC_CHECK35, IDC_CHECK36,
+ IDC_CHECK37, IDC_CHECK38, IDC_CHECK39, IDC_CHECK40,
+ IDC_CHECK41, IDC_CHECK42, IDC_CHECK43, IDC_CHECK44,
+ IDC_CHECK45, IDC_CHECK46, IDC_CHECK47, IDC_CHECK48,
+ IDC_CHECK49, IDC_CHECK50, IDC_CHECK51, IDC_CHECK52,
+ IDC_CHECK53, IDC_CHECK54, IDC_CHECK55, IDC_CHECK56,
+ IDC_CHECK57, IDC_CHECK58, IDC_CHECK59, IDC_CHECK60,
+ IDC_CHECK61, IDC_CHECK62, IDC_CHECK63, IDC_CHECK64
+ };
+
+/*
+==============
+SetTexMods
+
+Set the fields to the current texdef
+if one face selected -> will read this face texdef, else current texdef
+if only patches selected, will read the patch texdef
+===============
+*/
+
+bool g_bNewFace = false;
+bool g_bNewApplyHandling = false;
+bool g_bGatewayhack = false;
+
+void CSurfaceDlg::SetTexMods()
+{
+ char sz[128];
+ texdef_t *pt;
+ brushprimit_texdef_t *bpt;
+ // local copy if a width=2 height=2 qtetxture_t is needed
+ brushprimit_texdef_t local_bp;
+ int i;
+
+ if (!g_surfwin)
+ return;
+
+ m_bPatchMode = false;
+
+ if (OnlyPatchesSelected())
+ {
+ pt = &g_qeglobals.d_texturewin.texdef;
+ if (QE_SingleBrush())
+ {
+ //strcpy(g_patch_texdef.name, Patch_GetTextureName());
+ g_patch_texdef.SetName(Patch_GetTextureName());
+ }
+ else
+ {
+ //strcpy(g_patch_texdef.name, pt->name);
+ g_patch_texdef.SetName(pt->name);
+ }
+ g_patch_texdef.contents = pt->contents;
+ g_patch_texdef.flags = pt->flags;
+ g_patch_texdef.value = pt->value;
+ pt = &g_patch_texdef;
+ m_bPatchMode = true;
+ }
+ else
+ {
+ if (g_bNewFace && g_ptrSelectedFaces.GetSize() > 0)
+ {
+ face_t *selFace = reinterpret_cast<face_t*>(g_ptrSelectedFaces.GetAt(0));
+ pt = &selFace->texdef;
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ // compute a texture matrix related to the default matrix width=2 height=2
+ ConvertTexMatWithQTexture( &selFace->brushprimit_texdef, selFace->d_texture, &local_bp, NULL );
+ bpt = &local_bp;
+ }
+ }
+ else
+ {
+ pt = &g_qeglobals.d_texturewin.texdef;
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ bpt = &g_qeglobals.d_texturewin.brushprimit_texdef;
+ }
+ }
+ // brush primitive mode : compute fake shift scale rot representation
+ if (g_qeglobals.m_bBrushPrimitMode)
+ TexMatToFakeTexCoords( bpt->coords, m_shift, &m_rotate, m_scale );
+ }
+
+ SendMessage (WM_SETREDRAW, 0, 0);
+
+ ::SetWindowText(GetDlgItem(IDC_TEXTURE)->GetSafeHwnd(), pt->name);
+
+ if (m_bPatchMode)
+ sprintf(sz, "%4.6f", pt->shift[0]);
+ else
+ if (g_qeglobals.m_bBrushPrimitMode)
+ sprintf(sz, "%d", (int)m_shift[0]);
+ else
+ sprintf(sz, "%d", (int)pt->shift[0]);
+ ::SetWindowText(GetDlgItem(IDC_HSHIFT)->GetSafeHwnd(), sz);
+
+ if (m_bPatchMode)
+ sprintf(sz, "%4.6f", pt->shift[1]);
+ else
+ if (g_qeglobals.m_bBrushPrimitMode)
+ sprintf(sz, "%d", (int)m_shift[1]);
+ else
+ sprintf(sz, "%d", (int)pt->shift[1]);
+ ::SetWindowText(GetDlgItem(IDC_VSHIFT)->GetSafeHwnd(), sz);
+
+ sprintf(sz, m_bPatchMode ? "%4.6f" : "%4.6f", g_qeglobals.m_bBrushPrimitMode ? m_scale[0] : pt->scale[0]);
+ ::SetWindowText(GetDlgItem(IDC_HSCALE)->GetSafeHwnd(), sz);
+
+ sprintf(sz, m_bPatchMode ? "%4.6f" : "%4.6f", g_qeglobals.m_bBrushPrimitMode ? m_scale[1] : pt->scale[1]);
+ ::SetWindowText(GetDlgItem(IDC_VSCALE)->GetSafeHwnd(), sz);
+
+ //++timo compute BProtate as int ..
+ sprintf(sz, "%d", g_qeglobals.m_bBrushPrimitMode ? (int)m_rotate : (int)pt->rotate);
+ ::SetWindowText(GetDlgItem(IDC_ROTATE)->GetSafeHwnd(), sz);
+
+ sprintf(sz, "%d", (int)pt->value);
+ ::SetWindowText(GetDlgItem(IDC_VALUE)->GetSafeHwnd(), sz);
+
+ for (i=0 ; i<32 ; i++)
+ ::SendMessage(GetDlgItem(g_checkboxes[i])->GetSafeHwnd(), BM_SETCHECK, !!(pt->flags&(1<<i)), 0 );
+ for (i=0 ; i<32 ; i++)
+ ::SendMessage(GetDlgItem(g_checkboxes[32+i])->GetSafeHwnd(), BM_SETCHECK, !!(pt->contents&(1<<i)), 0 );
+
+ SendMessage (WM_SETREDRAW, 1, 0);
+ InvalidateRect (NULL, true);
+}
+
+void CSurfaceDlg::GrabPatchMods()
+{
+ char sz[128];
+ int i;
+ bool b;
+ texdef_t *pt = & g_patch_texdef;
+
+ ::GetWindowText (GetDlgItem(IDC_HSHIFT)->GetSafeHwnd(), sz, 127);
+ pt->shift[0] = atof(sz);
+
+ ::GetWindowText (GetDlgItem(IDC_VSHIFT)->GetSafeHwnd(), sz, 127);
+ pt->shift[1] = atof(sz);
+
+ ::GetWindowText(GetDlgItem(IDC_HSCALE)->GetSafeHwnd(), sz, 127);
+ pt->scale[0] = atof(sz);
+
+ ::GetWindowText(GetDlgItem(IDC_VSCALE)->GetSafeHwnd(), sz, 127);
+ pt->scale[1] = atof(sz);
+
+ ::GetWindowText(GetDlgItem(IDC_ROTATE)->GetSafeHwnd(), sz, 127);
+ pt->rotate = atof(sz);
+
+ ::GetWindowText(GetDlgItem(IDC_VALUE)->GetSafeHwnd(), sz, 127);
+ pt->value = atof(sz);
+
+ pt->flags = 0;
+ for (i=0 ; i<32 ; i++)
+ {
+ b = ::SendMessage(GetDlgItem(g_checkboxes[i])->GetSafeHwnd(), BM_GETCHECK, 0, 0);
+ if (b != 1 && b != 0)
+ continue;
+ pt->flags |= b<<i;
+ }
+
+ pt->contents = 0;
+ for (i=0 ; i<32 ; i++)
+ {
+ b = ::SendMessage(GetDlgItem(g_checkboxes[32+i])->GetSafeHwnd(), BM_GETCHECK, 0, 0);
+ if (b != 1 && b != 0)
+ continue;
+ pt->contents |= b<<i;
+ }
+
+}
+
+/*
+==============
+GetTexMods
+
+Reads the fields to get the current texdef
+in brush primitive mode, grab the fake shift scale rot and compute a new texture matrix
+===============
+*/
+void CSurfaceDlg::GetTexMods()
+{
+ char sz[128];
+ texdef_t *pt;
+ int b;
+ int i;
+
+ m_bPatchMode = false;
+
+ if (OnlyPatchesSelected())
+ {
+ pt = &g_qeglobals.d_texturewin.texdef;
+ m_bPatchMode = true;
+ }
+ else
+ {
+ if (g_bNewFace && g_ptrSelectedFaces.GetSize() > 0)
+ {
+ face_t *selFace = reinterpret_cast<face_t*>(g_ptrSelectedFaces.GetAt(0));
+ pt = &selFace->texdef;
+ }
+ else
+ {
+ pt = &g_qeglobals.d_texturewin.texdef;
+ }
+ }
+
+ ::GetWindowText (GetDlgItem(IDC_TEXTURE)->GetSafeHwnd(), sz, 127);
+ //strncpy (pt->name, sz, sizeof(pt->name)-1);
+ pt->SetName(sz);
+ if (pt->name[0] <= ' ')
+ {
+ //strcpy (pt->name, "none");
+ pt->SetName("none");
+ ::SetWindowText(GetDlgItem(IDC_TEXTURE)->GetSafeHwnd(), pt->name);
+ }
+
+ ::GetWindowText (GetDlgItem(IDC_HSHIFT)->GetSafeHwnd(), sz, 127);
+ ( g_qeglobals.m_bBrushPrimitMode ? m_shift[0] : pt->shift[0] ) = atof(sz);
+
+ ::GetWindowText (GetDlgItem(IDC_VSHIFT)->GetSafeHwnd(), sz, 127);
+ ( g_qeglobals.m_bBrushPrimitMode ? m_shift[1] : pt->shift[1] ) = atof(sz);
+
+ ::GetWindowText(GetDlgItem(IDC_HSCALE)->GetSafeHwnd(), sz, 127);
+ ( g_qeglobals.m_bBrushPrimitMode ? m_scale[0] : pt->scale[0] ) = atof(sz);
+
+ ::GetWindowText(GetDlgItem(IDC_VSCALE)->GetSafeHwnd(), sz, 127);
+ ( g_qeglobals.m_bBrushPrimitMode ? m_scale[1] : pt->scale[1] ) = atof(sz);
+
+ ::GetWindowText(GetDlgItem(IDC_ROTATE)->GetSafeHwnd(), sz, 127);
+ ( g_qeglobals.m_bBrushPrimitMode ? m_rotate : pt->rotate ) = atof(sz);
+
+ ::GetWindowText(GetDlgItem(IDC_VALUE)->GetSafeHwnd(), sz, 127);
+ pt->value = atof(sz);
+
+ pt->flags = 0;
+ for (i=0 ; i<32 ; i++)
+ {
+ b = ::SendMessage(GetDlgItem(g_checkboxes[i])->GetSafeHwnd(), BM_GETCHECK, 0, 0);
+ if (b != 1 && b != 0)
+ continue;
+ pt->flags |= b<<i;
+ }
+
+ pt->contents = 0;
+ for (i=0 ; i<32 ; i++)
+ {
+ b = ::SendMessage(GetDlgItem(g_checkboxes[32+i])->GetSafeHwnd(), BM_GETCHECK, 0, 0);
+ if (b != 1 && b != 0)
+ continue;
+ pt->contents |= b<<i;
+ }
+
+ g_changed_surface = true;
+
+ // a local copy of the texture matrix, given for a qtexture_t with width=2 height=2
+ brushprimit_texdef_t local_bp;
+ brushprimit_texdef_t *bpt;
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ face_t *selFace = NULL;
+ if (g_bNewFace && g_ptrSelectedFaces.GetSize() > 0)
+ {
+ selFace = reinterpret_cast<face_t*>(g_ptrSelectedFaces.GetAt(0));
+ bpt = &selFace->brushprimit_texdef;
+ }
+ else
+ {
+ bpt = &g_qeglobals.d_texturewin.brushprimit_texdef;
+ }
+ // compute texture matrix
+ // the matrix returned must be understood as a qtexture_t with width=2 height=2
+ FakeTexCoordsToTexMat( m_shift, m_rotate, m_scale, local_bp.coords );
+ // copy the texture matrix in the global struct
+ // fit the qtexture if we have a face selected, otherwise g_qeglobals.d_texturewin.brushprimit_texdef uses the basic qtexture_t with width=2 height=2
+
+ ConvertTexMatWithQTexture( &local_bp, NULL, bpt, ( ( g_bNewFace && selFace ) ? selFace->d_texture : NULL ) );
+ }
+ Select_SetTexture(pt,&local_bp);
+
+ //if (m_bPatchMode)
+ //{
+ // Patch_SetTextureInfo(pt);
+ //}
+
+}
+
+/*
+=================
+UpdateSpinners
+=================
+*/
+
+void CSurfaceDlg::UpdateSpinners(bool bUp, int nID)
+{
+ texdef_t *pt;
+ texdef_t td;
+
+ if (m_bPatchMode)
+ {
+ td.rotate = 0.0;
+ td.scale[0] = td.scale[1] = 0.0;
+ td.shift[0] = td.shift[1] = 0.0;
+ GrabPatchMods();
+
+ pt = &g_patch_texdef;
+ td.contents = pt->contents;
+ td.flags = pt->flags;
+ td.value = pt->value;
+
+ if (nID == IDC_SPIN_ROTATE)
+ {
+ if (bUp)
+ td.rotate = pt->rotate;
+ else
+ td.rotate = -pt->rotate;
+ }
+ else if (nID == IDC_SPIN_HSCALE)
+ {
+ if (bUp)
+ td.scale[0] = 1-pt->scale[0];
+ else
+ td.scale[0] = 1+pt->scale[0];
+ }
+ else if (nID == IDC_SPIN_VSCALE)
+ {
+ if (bUp)
+ td.scale[1] = 1-pt->scale[1];
+ else
+ td.scale[1] = 1+pt->scale[1];
+ }
+
+ else if (nID == IDC_SPIN_HSHIFT)
+ {
+ if (bUp)
+ td.shift[0] = pt->shift[0];
+ else
+ td.shift[0] = -pt->shift[0];
+ }
+ else if (nID == IDC_SPIN_VSHIFT)
+ {
+ if (bUp)
+ td.shift[1] = pt->shift[1];
+ else
+ td.shift[1] = -pt->shift[1];
+ }
+ pt = &g_qeglobals.d_texturewin.texdef;
+ Patch_SetTextureInfo(&td);
+ }
+ else
+ {
+ // in brush primitive mode, will read up-to-date m_shift m_rotate m_scale
+ GetTexMods ();
+ if (g_bNewFace && g_ptrSelectedFaces.GetSize() > 0)
+ {
+ face_t *selFace = reinterpret_cast<face_t*>(g_ptrSelectedFaces.GetAt(0));
+ pt = &selFace->texdef;
+ }
+ else
+ {
+ pt = &g_qeglobals.d_texturewin.texdef;
+ }
+ if (nID == IDC_SPIN_ROTATE)
+ {
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ if (bUp)
+ m_rotate += 45;
+ else
+ m_rotate -= 45;
+ }
+ else
+ {
+ if (bUp)
+ pt->rotate += 45;
+ else
+ pt->rotate -= 45;
+ if (pt->rotate < 0)
+ pt->rotate += 360;
+ if (pt->rotate >= 360)
+ pt->rotate -= 360;
+ }
+ }
+ else if (nID == IDC_SPIN_HSCALE)
+ {
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ if (bUp)
+ m_scale[0] += 0.1;
+ else
+ m_scale[0] -= 0.1;
+ }
+ else
+ {
+ if (bUp)
+ pt->scale[0] += 0.1;
+ else
+ pt->scale[0] -= 0.1;
+ }
+ }
+ else if (nID == IDC_SPIN_VSCALE)
+ {
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ if (bUp)
+ m_scale[1] += 0.1;
+ else
+ m_scale[1] -= 0.1;
+ }
+ else
+ {
+ if (bUp)
+ pt->scale[1] += 0.1;
+ else
+ pt->scale[1] -= 0.1;
+ }
+ }
+ else if (nID == IDC_SPIN_HSHIFT)
+ {
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ if (bUp)
+ m_shift[0] += 8;
+ else
+ m_shift[0] -= 8;
+ }
+ else
+ {
+ if (bUp)
+ pt->shift[0] += 8;
+ else
+ pt->shift[0] -= 8;
+ }
+ }
+ else if (nID == IDC_SPIN_VSHIFT)
+ {
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ if (bUp)
+ m_shift[1] += 8;
+ else
+ m_shift[1] -= 8;
+ }
+ else
+ {
+ if (bUp)
+ pt->shift[1] += 8;
+ else
+ pt->shift[1] -= 8;
+ }
+ }
+ }
+ // a local copy of the texture matrix, given for a qtexture_t with width=2 height=2
+ brushprimit_texdef_t local_bp;
+ brushprimit_texdef_t *bpt;
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ face_t *selFace = NULL;
+ if (g_bNewFace && g_ptrSelectedFaces.GetSize() > 0)
+ {
+ selFace = reinterpret_cast<face_t*>(g_ptrSelectedFaces.GetAt(0));
+ bpt = &selFace->brushprimit_texdef;
+ }
+ else
+ {
+ bpt = &g_qeglobals.d_texturewin.brushprimit_texdef;
+ }
+ // compute texture matrix
+ // the matrix returned must be understood as a qtexture_t with width=2 height=2
+ FakeTexCoordsToTexMat( m_shift, m_rotate, m_scale, local_bp.coords );
+ // copy the texture matrix in the global struct
+ // fit the qtexture if we have a face selected, otherwise g_qeglobals.d_texturewin.brushprimit_texdef uses the basic qtexture_t with width=2 height=2
+ ConvertTexMatWithQTexture( &local_bp, NULL, bpt, ( ( g_bNewFace && selFace ) ? selFace->d_texture : NULL ) );
+ }
+ // brush primit : will update the widgets after reading back texture matrix and computing fake shift scale rot
+ SetTexMods();
+ g_changed_surface = true;
+ Select_SetTexture(pt,&local_bp);
+}
+
+void CSurfaceDlg::UpdateSpinners(int nScrollCode, int nPos, CScrollBar* pBar)
+{
+ texdef_t *pt;
+
+ GetTexMods ();
+ if (g_bNewFace && g_ptrSelectedFaces.GetSize() > 0)
+ {
+ face_t *selFace = reinterpret_cast<face_t*>(g_ptrSelectedFaces.GetAt(0));
+ pt = &selFace->texdef;
+ }
+ else
+ {
+ pt = &g_qeglobals.d_texturewin.texdef;
+ }
+
+ if ((nScrollCode != SB_LINEUP) && (nScrollCode != SB_LINEDOWN))
+ return;
+
+ if (pBar->GetSafeHwnd() == ::GetDlgItem(GetSafeHwnd(), IDC_ROTATEA))
+ {
+ if (nScrollCode == SB_LINEUP)
+ pt->rotate += 45;
+ else
+ pt->rotate -= 45;
+
+ if (pt->rotate < 0)
+ pt->rotate += 360;
+
+ if (pt->rotate >= 360)
+ pt->rotate -= 360;
+ }
+
+ else if (pBar->GetSafeHwnd() == ::GetDlgItem(GetSafeHwnd(), IDC_HSCALEA))
+ {
+ if (nScrollCode == SB_LINEDOWN)
+ pt->scale[0] -= 0.1;
+ else
+ pt->scale[0] += 0.1;
+ }
+
+ else if (pBar->GetSafeHwnd() == ::GetDlgItem(GetSafeHwnd(), IDC_VSCALEA))
+ {
+ if (nScrollCode == SB_LINEUP)
+ pt->scale[1] += 0.1;
+ else
+ pt->scale[1] -= 0.1;
+ }
+
+ else if (pBar->GetSafeHwnd() == ::GetDlgItem(GetSafeHwnd(), IDC_HSHIFTA))
+ {
+ if (nScrollCode == SB_LINEDOWN)
+ pt->shift[0] -= 8;
+ else
+ pt->shift[0] += 8;
+ }
+
+ else if (pBar->GetSafeHwnd() == ::GetDlgItem(GetSafeHwnd(), IDC_VSHIFTA))
+ {
+ if (nScrollCode == SB_LINEUP)
+ pt->shift[1] += 8;
+ else
+ pt->shift[1] -= 8;
+ }
+
+ SetTexMods();
+ g_changed_surface = true;
+ //++timo if !g_qeglobals.m_bBrushPrimitMode send a NULL brushprimit_texdef
+ if (!g_qeglobals.m_bBrushPrimitMode)
+ {
+ Sys_Printf("Warning : non brush primitive mode call to CSurfaceDlg::GetTexMods broken\n");
+ Sys_Printf(" ( Select_SetTexture not called )\n");
+ }
+// Select_SetTexture(pt);
+}
+
+void UpdateSurfaceDialog()
+{
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+ g_SurfaceTable.m_pfnUpdateSurfaceDialog();
+ }
+ else
+ {
+ if (g_surfwin)
+ g_dlgSurface.SetTexMods();
+ }
+ g_pParentWnd->UpdateTextureBar();
+}
+
+bool ByeByeSurfaceDialog();
+
+void DoSurface (void)
+{
+ // surface properties plugin ?
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+ g_SurfaceTable.m_pfnDoSurface();
+ return;
+ }
+
+ g_bNewFace = g_PrefsDlg.m_bFace;
+ g_bNewApplyHandling = g_PrefsDlg.m_bNewApplyHandling;
+ g_bGatewayhack = g_PrefsDlg.m_bGatewayHack;
+ // save current state for cancel
+ g_old_texdef = g_qeglobals.d_texturewin.texdef;
+ g_changed_surface = false;
+
+ if (g_surfwin == NULL && g_dlgSurface.GetSafeHwnd() == NULL)
+ {
+ g_patch_texdef.scale[0] = 0.05;
+ g_patch_texdef.scale[1] = 0.05;
+ g_patch_texdef.shift[0] = 0.05;
+ g_patch_texdef.shift[1] = 0.05;
+ // use rotation increment from preferences
+ g_patch_texdef.rotate = g_PrefsDlg.m_nRotation;
+
+ g_dlgSurface.Create(IDD_SURFACE);
+ CRect rct;
+ LONG lSize = sizeof(rct);
+ if (LoadRegistryInfo("Radiant::SurfaceWindow", &rct, &lSize))
+ g_dlgSurface.SetWindowPos(NULL, rct.left, rct.top, 0,0, SWP_NOSIZE | SWP_SHOWWINDOW);
+
+ Sys_UpdateWindows(W_ALL);
+ }
+ else
+ {
+ g_surfwin = g_dlgSurface.GetSafeHwnd();
+ g_dlgSurface.SetTexMods ();
+ g_dlgSurface.ShowWindow(SW_SHOW);
+ }
+}
+
+bool ByeByeSurfaceDialog()
+{
+ // surface properties plugin ?
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+ return g_SurfaceTable.m_pfnByeByeSurfaceDialog();
+ }
+
+ if (g_surfwin)
+ {
+ if (g_bGatewayhack)
+ PostMessage(g_surfwin, WM_COMMAND, IDAPPLY, 0);
+ else
+ PostMessage(g_surfwin, WM_COMMAND, IDCANCEL, 0);
+ return true;
+ }
+ else return false;
+}
+
+BOOL CSurfaceDlg::OnInitDialog()
+{
+ CDialog::OnInitDialog();
+
+ g_surfwin = GetSafeHwnd();
+ SetTexMods ();
+
+#ifdef QUAKE3
+ GetDlgItem(IDC_CHECK32)->SetWindowText("Curve");
+ GetDlgItem(IDC_CHECK64)->SetWindowText("Inverted");
+#endif
+
+ m_wndHScale.SetRange(0, 1000);
+ m_wndVScale.SetRange(0, 1000);
+ m_wndHShift.SetRange(0, 1000);
+ m_wndVShift.SetRange(0, 1000);
+ m_wndRotate.SetRange(0, 1000);
+ m_wndWidth.SetRange(1, 32);
+ m_wndHeight.SetRange(1, 32);
+
+ LPVOID lpv = g_pParentWnd->GetPlugInMgr().GetSurfaceFlags();
+ if (lpv != NULL)
+ {
+ int i = 0;
+ char* p = reinterpret_cast<char*>(lpv);
+ char* pBuff = new char[strlen(p)+1];
+ strcpy(pBuff, p);
+ char* pToken = strtok(pBuff, ";\0");
+ while (pToken != NULL)
+ {
+ GetDlgItem(g_checkboxes[i++])->SetWindowText(pToken);
+ pToken = strtok(NULL, ";\0");
+ }
+ }
+
+ if (strstr(g_PrefsDlg.m_strWhatGame, "Quake3") != NULL) {
+ for (int i=0 ; i < 64 ; i++) {
+ ::EnableWindow(GetDlgItem(g_checkboxes[i])->GetSafeHwnd(), FALSE);
+ }
+
+ }
+
+ return TRUE; // return TRUE unless you set the focus to a control
+ // EXCEPTION: OCX Property Pages should return FALSE
+}
+
+void CSurfaceDlg::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
+{
+ CDialog::OnHScroll(nSBCode, nPos, pScrollBar);
+ UpdateSpinners(nSBCode, nPos, pScrollBar);
+ Sys_UpdateWindows(W_CAMERA);
+}
+
+void CSurfaceDlg::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
+{
+
+ CDialog::OnKeyDown(nChar, nRepCnt, nFlags);
+}
+
+void CSurfaceDlg::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
+{
+ CDialog::OnVScroll(nSBCode, nPos, pScrollBar);
+ UpdateSpinners(nSBCode, nPos, pScrollBar);
+ Sys_UpdateWindows(W_CAMERA);
+}
+
+void CSurfaceDlg::OnApply()
+{
+ GetTexMods ();
+ Sys_UpdateWindows(W_CAMERA);
+ if (g_bNewApplyHandling)
+ OnOK();
+}
+
+void CSurfaceDlg::OnOK()
+{
+ GetTexMods();
+ g_surfwin = NULL;
+ CDialog::OnOK();
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CSurfaceDlg::OnClose()
+{
+ g_surfwin = NULL;
+ CDialog::OnClose();
+}
+
+void CSurfaceDlg::OnCancel()
+{
+ if (g_bGatewayhack)
+ OnOK();
+ else
+ OnBtnCancel();
+}
+
+void CSurfaceDlg::OnDestroy()
+{
+ if (GetSafeHwnd())
+ {
+ CRect rct;
+ GetWindowRect(rct);
+ SaveRegistryInfo("Radiant::SurfaceWindow", &rct, sizeof(rct));
+ }
+ CDialog::OnDestroy();
+ g_surfwin = NULL;
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CSurfaceDlg::OnBtnCancel()
+{
+ g_qeglobals.d_texturewin.texdef = g_old_texdef;
+ if (g_changed_surface)
+ {
+ //++timo if !g_qeglobals.m_bBrushPrimitMode send a NULL brushprimit_texdef
+ if (!g_qeglobals.m_bBrushPrimitMode)
+ {
+ Sys_Printf("Warning : non brush primitive mode call to CSurfaceDlg::GetTexMods broken\n");
+ Sys_Printf(" ( Select_SetTexture not called )\n");
+ }
+// Select_SetTexture(&g_qeglobals.d_texturewin.texdef);
+ }
+ g_surfwin = NULL;
+ DestroyWindow();
+}
+
+void CSurfaceDlg::OnBtnColor()
+{
+}
+
+HBRUSH CSurfaceDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
+{
+ HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
+ return hbr;
+}
+
+int CSurfaceDlg::OnCreate(LPCREATESTRUCT lpCreateStruct)
+{
+ if (CDialog::OnCreate(lpCreateStruct) == -1)
+ return -1;
+
+ return 0;
+}
+
+BOOL CSurfaceDlg::PreCreateWindow(CREATESTRUCT& cs)
+{
+ // TODO: Add your specialized code here and/or call the base class
+
+ return CDialog::PreCreateWindow(cs);
+}
+
+
+void CSurfaceDlg::OnDeltaPosSpin(NMHDR* pNMHDR, LRESULT* pResult)
+{
+ NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
+ UpdateSpinners((pNMUpDown->iDelta > 0), pNMUpDown->hdr.idFrom);
+ *pResult = 0;
+}
+
+void CSurfaceDlg::OnBtnPatchdetails()
+{
+ Patch_NaturalizeSelected(true);
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CSurfaceDlg::OnBtnPatchnatural()
+{
+ Patch_NaturalizeSelected();
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CSurfaceDlg::OnBtnPatchreset()
+{
+ CTextureLayout dlg;
+ if (dlg.DoModal() == IDOK)
+ {
+ Patch_ResetTexturing(dlg.m_fX, dlg.m_fY);
+ }
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CSurfaceDlg::OnBtnPatchfit()
+{
+ Patch_FitTexturing();
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CSurfaceDlg::OnBtnAxial()
+{
+ Select_SetTexture (&g_qeglobals.d_texturewin.texdef, &g_qeglobals.d_texturewin.brushprimit_texdef, true);
+ g_changed_surface = true;
+ SetTexMods();
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CSurfaceDlg::OnBtnBrushfit()
+{
+ // TODO: Add your control notification handler code here
+
+}
+
+void CSurfaceDlg::OnBtnFacefit()
+{
+ UpdateData(TRUE);
+ if (g_ptrSelectedFaces.GetSize() == 0)
+ {
+ brush_t *b;
+ for (b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ {
+ for (face_t* pFace = b->brush_faces; pFace; pFace = pFace->next)
+ {
+ g_ptrSelectedFaces.Add(pFace);
+ g_ptrSelectedFaceBrushes.Add(b);
+ }
+ }
+ }
+ Select_FitTexture(m_nHeight, m_nWidth);
+ SetTexMods();
+ g_changed_surface = true;
+ Sys_UpdateWindows(W_ALL);
+}
diff --git a/q3radiant/SurfaceDlg.h b/q3radiant/SurfaceDlg.h
new file mode 100755
index 0000000..8b7c0fd
--- /dev/null
+++ b/q3radiant/SurfaceDlg.h
@@ -0,0 +1,107 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_SURFACEDLG_H__D84E0C22_9EEA_11D1_B570_00AA00A410FC__INCLUDED_)
+#define AFX_SURFACEDLG_H__D84E0C22_9EEA_11D1_B570_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// SurfaceDlg.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CSurfaceDlg dialog
+
+class CSurfaceDlg : public CDialog
+{
+ bool m_bPatchMode;
+ // brush primitive fake shift scale rot coords
+ float m_shift[2];
+ float m_rotate;
+ float m_scale[2];
+
+ // Construction
+public:
+ CSurfaceDlg(CWnd* pParent = NULL); // standard constructor
+ void SetTexMods();
+ void GetTexMods();
+ void GrabPatchMods();
+
+// Dialog Data
+ //{{AFX_DATA(CSurfaceDlg)
+ enum { IDD = IDD_SURFACE };
+ CSpinButtonCtrl m_wndWidth;
+ CSpinButtonCtrl m_wndHeight;
+ CSpinButtonCtrl m_wndVShift;
+ CSpinButtonCtrl m_wndVScale;
+ CSpinButtonCtrl m_wndRotate;
+ CSpinButtonCtrl m_wndHShift;
+ CSpinButtonCtrl m_wndHScale;
+ int m_nHeight;
+ int m_nWidth;
+ //}}AFX_DATA
+
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CSurfaceDlg)
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+
+ void UpdateSpinners(int nScrollCode, int nPos, CScrollBar* pBar);
+ void UpdateSpinners(bool bUp, int nID);
+ // Generated message map functions
+ //{{AFX_MSG(CSurfaceDlg)
+ virtual BOOL OnInitDialog();
+ afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
+ afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
+ afx_msg void OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
+ afx_msg void OnApply();
+ virtual void OnOK();
+ afx_msg void OnClose();
+ virtual void OnCancel();
+ afx_msg void OnDestroy();
+ afx_msg void OnBtnCancel();
+ afx_msg void OnBtnColor();
+ afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);
+ afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
+ afx_msg void OnDeltaPosSpin(NMHDR* pNMHDR, LRESULT* pResult);
+ afx_msg void OnBtnPatchdetails();
+ afx_msg void OnBtnPatchnatural();
+ afx_msg void OnBtnPatchreset();
+ afx_msg void OnBtnPatchfit();
+ afx_msg void OnBtnAxial();
+ afx_msg void OnBtnBrushfit();
+ afx_msg void OnBtnFacefit();
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_SURFACEDLG_H__D84E0C22_9EEA_11D1_B570_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/SurfacePlugin.cpp b/q3radiant/SurfacePlugin.cpp
new file mode 100755
index 0000000..ad1cd31
--- /dev/null
+++ b/q3radiant/SurfacePlugin.cpp
@@ -0,0 +1,82 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//-----------------------------------------------------------------------------
+//
+// $LogFile$
+// $Revision: 1.1.1.4 $
+// $Author: ttimo $
+// $Date: 2000/01/18 00:18:14 $
+// $Log: SurfacePlugin.cpp,v $
+// Revision 1.1.1.4 2000/01/18 00:18:14 ttimo
+// merging in for RC
+//
+// Revision 1.3 2000/01/17 23:53:43 TBesset
+// ready for merge in sourceforge (RC candidate)
+//
+// Revision 1.2 2000/01/07 16:40:12 TBesset
+// merged from BSP frontend
+//
+// Revision 1.1.1.3 1999/12/29 18:31:46 TBesset
+// Q3Radiant public version
+//
+// Revision 1.1.1.1.2.1 1999/12/29 21:39:42 TBesset
+// updated to update3 from Robert
+//
+// Revision 1.1.1.3 1999/12/29 18:31:46 TBesset
+// Q3Radiant public version
+// Revision 1.1.1.3 1999/12/29 18:31:46 TBesset
+// Q3Radiant public version
+//
+// Revision 1.1 1999/12/02 16:11:05 Timo & Christine
+// commit before e-brain dump
+// TexTool v1.1 support
+//
+//
+//
+// DESCRIPTION:
+// implementation of isurfaceplugin-interface specifics
+//++timo FIXME: all the patch related stuff needs moving to qerplugin.h
+
+#include "stdafx.h"
+
+void WINAPI QERApp_GetTwoSelectedPatch( patchMesh_t **p1, patchMesh_t **p2 )
+{
+ *p1 = NULL; *p2 = NULL;
+ for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+ {
+ if (pb->patchBrush)
+ {
+ if (!(*p1))
+ *p1 = pb->pPatch;
+ else if (!(*p2))
+ {
+ *p2 = pb->pPatch;
+ return;
+ }
+ }
+ }
+#ifdef _DEBUG
+ Sys_Printf("WARNING: QERApp_GetTwoSelectedPatch failed (did not find two patches)\n");
+#endif
+ return;
+
+}
diff --git a/q3radiant/TexEdit.cpp b/q3radiant/TexEdit.cpp
new file mode 100755
index 0000000..3726629
--- /dev/null
+++ b/q3radiant/TexEdit.cpp
@@ -0,0 +1,85 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// TexEdit.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "TexEdit.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CTexEdit
+
+CTexEdit::CTexEdit()
+{
+ m_pTexWnd = NULL;
+}
+
+CTexEdit::~CTexEdit()
+{
+}
+
+
+BEGIN_MESSAGE_MAP(CTexEdit, CEdit)
+ //{{AFX_MSG_MAP(CTexEdit)
+ ON_WM_CTLCOLOR_REFLECT()
+ ON_CONTROL_REFLECT(EN_CHANGE, OnChange)
+ ON_WM_CREATE()
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CTexEdit message handlers
+
+HBRUSH CTexEdit::CtlColor(CDC* pDC, UINT nCtlColor)
+{
+ if (nCtlColor == CTLCOLOR_EDIT)
+ {
+ pDC->SetBkColor(RGB(192,192,192));
+ return (HBRUSH)GetStockObject(LTGRAY_BRUSH);
+ }
+ return NULL;
+}
+
+void CTexEdit::OnChange()
+{
+ CString str;
+ GetWindowText(str);
+ if (m_pTexWnd)
+ m_pTexWnd->UpdateFilter(str);
+}
+
+int CTexEdit::OnCreate(LPCREATESTRUCT lpCreateStruct)
+{
+ if (CEdit::OnCreate(lpCreateStruct) == -1)
+ return -1;
+
+ m_Font.CreatePointFont(100, "Arial");
+ SetFont(&m_Font, FALSE);
+ return 0;
+}
diff --git a/q3radiant/TexEdit.h b/q3radiant/TexEdit.h
new file mode 100755
index 0000000..36a9710
--- /dev/null
+++ b/q3radiant/TexEdit.h
@@ -0,0 +1,76 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_TEXEDIT_H__913F6812_99CD_11D1_B568_00AA00A410FC__INCLUDED_)
+#define AFX_TEXEDIT_H__913F6812_99CD_11D1_B568_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// TexEdit.h : header file
+//
+/////////////////////////////////////////////////////////////////////////////
+// CTexEdit window
+
+class CTexWnd;
+
+class CTexEdit : public CEdit
+{
+// Construction
+public:
+ CTexEdit();
+
+// Attributes
+public:
+
+protected:
+ CTexWnd* m_pTexWnd;
+ CFont m_Font;
+// Operations
+public:
+ void SetTexWnd(CTexWnd* pTex) {m_pTexWnd = pTex;};
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CTexEdit)
+ //}}AFX_VIRTUAL
+
+// Implementation
+public:
+ virtual ~CTexEdit();
+
+ // Generated message map functions
+protected:
+ //{{AFX_MSG(CTexEdit)
+ afx_msg HBRUSH CtlColor(CDC* pDC, UINT nCtlColor);
+ afx_msg void OnChange();
+ afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
+ //}}AFX_MSG
+
+ DECLARE_MESSAGE_MAP()
+};
+
+/////////////////////////////////////////////////////////////////////////////
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_TEXEDIT_H__913F6812_99CD_11D1_B568_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/TexWnd.cpp b/q3radiant/TexWnd.cpp
new file mode 100755
index 0000000..471ba0e
--- /dev/null
+++ b/q3radiant/TexWnd.cpp
@@ -0,0 +1,3186 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// TexWnd.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include <assert.h>
+#include "Radiant.h"
+#include "TexWnd.h"
+#include "qe3.h"
+#include "io.h"
+#include "PrefsDlg.h"
+#include "shaderinfo.h"
+#include "pakstuff.h"
+#include "str.h"
+#include "PrefsDlg.h"
+
+Str m_gStr;
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+qtexture_t *Texture_ForNamePath(char* name, char* pFullPath);
+#define TYP_MIPTEX 68
+static unsigned tex_palette[256];
+
+qtexture_t *notexture = NULL;
+qtexture_t *g_pluginTexture = NULL;
+
+static qboolean nomips = false;
+
+#define FONT_HEIGHT 10
+
+HGLRC s_hglrcTexture = NULL;
+HDC s_hdcTexture = NULL;
+
+//int texture_mode = GL_NEAREST;
+//int texture_mode = GL_NEAREST_MIPMAP_NEAREST;
+//int texture_mode = GL_NEAREST_MIPMAP_LINEAR;
+//int texture_mode = GL_LINEAR;
+//int texture_mode = GL_LINEAR_MIPMAP_NEAREST;
+int texture_mode = GL_LINEAR_MIPMAP_LINEAR;
+
+// this is the global counter for GL bind numbers
+int texture_extension_number = 1;
+int g_nCurrentTextureMenuName;
+
+int g_nTextureOffset = 0;
+
+// current active texture directory. if empty, show textures in use
+char texture_directory[128]; // use if texture_showinuse is false
+qboolean texture_showinuse;
+
+bool g_bFilterEnabled = false;
+CString g_strFilter;
+
+// texture layout functions
+qtexture_t *current_texture = NULL;
+int current_x, current_y, current_row;
+
+int texture_nummenus;
+#define MAX_TEXTUREDIRS 128
+char texture_menunames[MAX_TEXTUREDIRS][128];
+
+qboolean g_dontuse = true; // set to true to load the texture but not flag as used
+
+// void SelectTexture (int mx, int my, bool bShift = false);
+void SelectTexture (int mx, int my, bool bShift, bool bFitScale=false);
+
+void Texture_MouseDown (int x, int y, int buttons);
+void Texture_MouseUp (int x, int y, int buttons);
+void Texture_MouseMoved (int x, int y, int buttons);
+
+CPtrArray g_lstShaders;
+CPtrArray g_lstSkinCache;
+
+struct SkinInfo
+{
+ CString m_strName;
+ int m_nTextureBind;
+ SkinInfo(const char *pName, int n)
+ {
+ m_strName = pName;
+ m_nTextureBind = n;
+ };
+ SkinInfo(){};
+};
+
+// checks wether a qtexture_t exists for a given name
+//++timo FIXME: is this really any use? redundant.
+bool ShaderQTextureExists(const char *pName)
+{
+ for (qtexture_t *q=g_qeglobals.d_qtextures ; q ; q=q->next)
+ {
+ if (!strcmp(q->name, pName))
+ {
+ return true;
+ }
+ }
+ return false;
+
+}
+
+CShaderInfo* hasShader(const char *pName)
+{
+ int nSize = g_lstShaders.GetSize();
+ for (int i = 0; i < nSize; i++)
+ {
+ CShaderInfo *pInfo = reinterpret_cast<CShaderInfo*>(g_lstShaders.ElementAt(i));
+ if (pInfo != NULL)
+ {
+ if (pInfo->m_strName.CompareNoCase(pName) == 0)
+ {
+ return pInfo;
+ }
+ }
+ }
+ return NULL;
+}
+
+// gets active texture extension
+//
+// FIXME: fix this to be generic from project file
+//
+int GetTextureExtensionCount()
+{
+ return 2;
+}
+
+const char* GetTextureExtension(int nIndex)
+{
+ if ( nIndex == 0)
+ {
+ _QERTextureInfo *pInfo = g_pParentWnd->GetPlugInMgr().GetTextureInfo();
+ const char *pTex = (pInfo != NULL) ? pInfo->m_TextureExtension : NULL;
+ return (pTex == NULL) ? (g_PrefsDlg.m_bHiColorTextures == FALSE) ? "wal" : "tga" : pTex;
+ }
+ // return jpg for 2nd extension
+ return "jpg";
+}
+
+void SortTextures(void)
+{
+ qtexture_t *q, *qtemp, *qhead, *qcur, *qprev;
+
+ // standard insertion sort
+ // Take the first texture from the list and
+ // add it to our new list
+ if ( g_qeglobals.d_qtextures == NULL)
+ return;
+
+ qhead = g_qeglobals.d_qtextures;
+ q = g_qeglobals.d_qtextures->next;
+ qhead->next = NULL;
+
+ // while there are still things on the old
+ // list, keep adding them to the new list
+ while (q)
+ {
+ qtemp = q;
+ q = q->next;
+
+ qprev = NULL;
+ qcur = qhead;
+
+ while (qcur)
+ {
+ // Insert it here?
+ if (strcmp(qtemp->name, qcur->name) < 0)
+ {
+ qtemp->next = qcur;
+ if (qprev)
+ qprev->next = qtemp;
+ else
+ qhead = qtemp;
+ break;
+ }
+
+ // Move on
+
+ qprev = qcur;
+ qcur = qcur->next;
+
+
+ // is this one at the end?
+
+ if (qcur == NULL)
+ {
+ qprev->next = qtemp;
+ qtemp->next = NULL;
+ }
+ }
+
+
+ }
+
+ g_qeglobals.d_qtextures = qhead;
+}
+
+/*
+==============
+Texture_InitPalette
+==============
+*/
+void Texture_InitPalette (byte *pal)
+{
+ int r,g,b,v;
+ int i;
+ int inf;
+ byte gammatable[256];
+ float gamma;
+
+ gamma = g_qeglobals.d_savedinfo.fGamma;
+
+ if (gamma == 1.0)
+ {
+ for (i=0 ; i<256 ; i++)
+ gammatable[i] = i;
+ }
+ else
+ {
+ for (i=0 ; i<256 ; i++)
+ {
+ inf = 255 * pow ( (float)( (i+0.5)/255.5 ), gamma ) + 0.5;
+ if (inf < 0)
+ inf = 0;
+ if (inf > 255)
+ inf = 255;
+ gammatable[i] = inf;
+ }
+ }
+
+ for (i=0 ; i<256 ; i++)
+ {
+ r = gammatable[pal[0]];
+ g = gammatable[pal[1]];
+ b = gammatable[pal[2]];
+ pal += 3;
+
+ v = (r<<24) + (g<<16) + (b<<8) + 255;
+ v = BigLong (v);
+
+ tex_palette[i] = v;
+ }
+}
+
+void SetTexParameters (void)
+{
+ qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texture_mode );
+
+ switch ( texture_mode )
+ {
+ case GL_NEAREST:
+ case GL_NEAREST_MIPMAP_NEAREST:
+ case GL_NEAREST_MIPMAP_LINEAR:
+ qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
+ break;
+ case GL_LINEAR:
+ case GL_LINEAR_MIPMAP_NEAREST:
+ case GL_LINEAR_MIPMAP_LINEAR:
+ qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
+ break;
+ }
+}
+
+/*
+============
+Texture_SetMode
+============
+*/
+void Texture_SetMode(int iMenu)
+{
+ int i, iMode;
+ HMENU hMenu;
+ qboolean texturing = true;
+
+ hMenu = GetMenu(g_qeglobals.d_hwndMain);
+
+ switch(iMenu) {
+ case ID_VIEW_NEAREST:
+ iMode = GL_NEAREST;
+ break;
+ case ID_VIEW_NEARESTMIPMAP:
+ iMode = GL_NEAREST_MIPMAP_NEAREST;
+ break;
+ case ID_VIEW_LINEAR:
+ iMode = GL_NEAREST_MIPMAP_LINEAR;
+ break;
+ case ID_VIEW_BILINEAR:
+ iMode = GL_LINEAR;
+ break;
+ case ID_VIEW_BILINEARMIPMAP:
+ iMode = GL_LINEAR_MIPMAP_NEAREST;
+ break;
+ case ID_VIEW_TRILINEAR:
+ iMode = GL_LINEAR_MIPMAP_LINEAR;
+ break;
+
+ case ID_TEXTURES_WIREFRAME:
+ iMode = 0;
+ texturing = false;
+ break;
+
+ case ID_TEXTURES_FLATSHADE:
+ iMode = 0;
+ texturing = false;
+ break;
+
+ }
+
+ CheckMenuItem(hMenu, ID_VIEW_NEAREST, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_VIEW_NEARESTMIPMAP, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_VIEW_LINEAR, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_VIEW_BILINEARMIPMAP, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_VIEW_BILINEAR, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_VIEW_TRILINEAR, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_TEXTURES_WIREFRAME, MF_BYCOMMAND | MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_TEXTURES_FLATSHADE, MF_BYCOMMAND | MF_UNCHECKED);
+
+ CheckMenuItem(hMenu, iMenu, MF_BYCOMMAND | MF_CHECKED);
+
+ g_qeglobals.d_savedinfo.iTexMenu = iMenu;
+ texture_mode = iMode;
+
+ if (g_PrefsDlg.m_bSGIOpenGL)
+ {
+ if (s_hdcTexture && s_hglrcTexture)
+ {
+ //if (!qwglMakeCurrent(g_qeglobals.d_hdcBase, g_qeglobals.d_hglrcBase))
+ if (!qwglMakeCurrent(s_hdcTexture, s_hglrcTexture))
+ Error ("wglMakeCurrent in LoadTexture failed");
+ }
+ else
+ return;
+ }
+
+ if ( texturing )
+ SetTexParameters ();
+
+ if ( !texturing && iMenu == ID_TEXTURES_WIREFRAME)
+ {
+ g_pParentWnd->GetCamera()->Camera().draw_mode = cd_wire;
+ Map_BuildBrushData();
+ Sys_UpdateWindows (W_ALL);
+ return;
+
+ } else if ( !texturing && iMenu == ID_TEXTURES_FLATSHADE) {
+
+ g_pParentWnd->GetCamera()->Camera().draw_mode = cd_solid;
+ Map_BuildBrushData();
+ Sys_UpdateWindows (W_ALL);
+ return;
+ }
+
+ for (i=1 ; i<texture_extension_number ; i++)
+ {
+ qglBindTexture( GL_TEXTURE_2D, i );
+ SetTexParameters ();
+ }
+
+ // select the default texture
+ qglBindTexture( GL_TEXTURE_2D, 0 );
+
+ qglFinish();
+
+ if (g_pParentWnd->GetCamera()->Camera().draw_mode != cd_texture)
+ {
+ g_pParentWnd->GetCamera()->Camera().draw_mode = cd_texture;
+ Map_BuildBrushData();
+ }
+
+ Sys_UpdateWindows (W_ALL);
+}
+
+/*
+================
+R_MipMap
+
+Operates in place, quartering the size of the texture
+================
+*/
+void R_MipMap (byte *in, int &width, int &height)
+{
+ int i, j;
+ byte *out;
+ int row;
+
+ row = width * 4;
+ width >>= 1;
+ height >>= 1;
+ out = in;
+ for (i=0 ; i<height ; i++, in+=row)
+ {
+ for (j=0 ; j<width ; j++, out+=4, in+=8)
+ {
+ out[0] = (in[0] + in[4] + in[row+0] + in[row+4])>>2;
+ out[1] = (in[1] + in[5] + in[row+1] + in[row+5])>>2;
+ out[2] = (in[2] + in[6] + in[row+2] + in[row+6])>>2;
+ out[3] = (in[3] + in[7] + in[row+3] + in[row+7])>>2;
+ }
+ }
+}
+
+/*
+=================
+Texture_LoadTexture
+=================
+*/
+//++timo NOTE: miptex_t is used only for .WAL format .. a bit outdated
+qtexture_t *Texture_LoadTexture (miptex_t *qtex)
+{
+ byte *source;
+ unsigned char *dest;
+ int width, height, i, count;
+ int total[3];
+ qtexture_t *q;
+
+ width = LittleLong(qtex->width);
+ height = LittleLong(qtex->height);
+
+ q = (qtexture_t*)qmalloc(sizeof(*q));
+
+ q->width = width;
+ q->height = height;
+
+ q->flags = qtex->flags;
+ q->value = qtex->value;
+ q->contents = qtex->contents;
+
+ dest = (unsigned char*)qmalloc (width*height*4);
+
+ count = width*height;
+ source = (byte *)qtex + LittleLong(qtex->offsets[0]);
+
+ // The dib is upside down so we want to copy it into
+ // the buffer bottom up.
+
+ total[0] = total[1] = total[2] = 0;
+ for (i=0 ; i<count ; i++)
+ {
+ dest[i] = tex_palette[source[i]];
+
+ total[0] += ((byte *)(dest+i))[0];
+ total[1] += ((byte *)(dest+i))[1];
+ total[2] += ((byte *)(dest+i))[2];
+ }
+
+ q->color[0] = (float)total[0]/(count*255);
+ q->color[1] = (float)total[1]/(count*255);
+ q->color[2] = (float)total[2]/(count*255);
+
+ q->texture_number = texture_extension_number++;
+
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+ // Timo
+ // Surface properties plugins can store their own data in an IPluginQTexture
+ q->pData = g_SurfaceTable.m_pfnQTextureAlloc( q );
+ GETPLUGINTEXDEF(q)->InitForMiptex( qtex );
+ }
+
+ //++timo is the m_bSGIOpenGL parameter still taken into account?
+ if (g_PrefsDlg.m_bSGIOpenGL)
+ {
+ //if (!qwglMakeCurrent(g_qeglobals.d_hdcBase, g_qeglobals.d_hglrcBase))
+ if (!qwglMakeCurrent(s_hdcTexture, s_hglrcTexture))
+ Error ("wglMakeCurrent in LoadTexture failed");
+ }
+
+ qglBindTexture( GL_TEXTURE_2D, q->texture_number );
+
+ //Handle3DfxTexturing(q, width, height, dest);
+
+ SetTexParameters ();
+
+ int nCount = MAX_TEXTURE_QUALITY - g_PrefsDlg.m_nTextureQuality;
+ while (nCount-- > 0)
+ {
+ if (width > 16 && height > 16)
+ {
+ R_MipMap(dest, width, height);
+ }
+ else
+ {
+ break;
+ }
+ }
+
+ if (g_PrefsDlg.m_bSGIOpenGL)
+ {
+ if (nomips)
+ {
+ qglTexImage2D(GL_TEXTURE_2D, 0, 3, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, dest);
+ }
+ else
+ qgluBuild2DMipmaps(GL_TEXTURE_2D, 3, width, height,GL_RGBA, GL_UNSIGNED_BYTE, dest);
+ }
+ else
+ {
+ if (nomips)
+ qglTexImage2D(GL_TEXTURE_2D, 0, 3, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, dest);
+ else
+ qgluBuild2DMipmaps(GL_TEXTURE_2D, 3, width, height,GL_RGBA, GL_UNSIGNED_BYTE, dest);
+ }
+
+ free (dest);
+
+ qglBindTexture( GL_TEXTURE_2D, 0 );
+
+ return q;
+}
+
+
+
+
+/*
+=================
+Texture_LoadTexture
+=================
+*/
+qtexture_t *Texture_LoadTGATexture (unsigned char* pPixels, int nWidth, int nHeight, char* pPath, int nFlags, int nContents, int nValue )
+{
+ int i, j, inf;
+ byte gammatable[256];
+ float fGamma = g_qeglobals.d_savedinfo.fGamma;
+
+
+ qtexture_t* q = (qtexture_t*)qmalloc(sizeof(*q));
+ q->width = nWidth;
+ q->height = nHeight;
+ q->flags = nFlags;
+ q->value = nValue;
+ q->contents = nContents;
+
+ int nCount = nWidth * nHeight;
+ float total[3];
+ total[0] = total[1] = total[2] = 0.0f;
+
+ //++timo FIXME: move gamma table initialization somewhere else!
+ if (fGamma == 1.0)
+ {
+ for (i=0 ; i<256 ; i++)
+ gammatable[i] = i;
+ }
+ else
+ {
+ for (i=0 ; i<256 ; i++)
+ {
+ inf = 255 * pow ( (float)( (i+0.5)/255.5 ), fGamma ) + 0.5;
+ if (inf < 0)
+ inf = 0;
+ if (inf > 255)
+ inf = 255;
+ gammatable[i] = inf;
+ }
+ }
+
+
+ // all targas are stored internally as 32bit so rgba = 4 bytes
+ for (i = 0 ; i < (nCount * 4) ; i += 4)
+ {
+ for (j = 0; j < 3; j++)
+ {
+ total[j] += (pPixels+i)[j];
+ byte b = (pPixels+i)[j];
+ (pPixels+i)[j] = gammatable[b];
+
+ }
+ }
+
+ q->color[0] = total[0] / (nCount * 255);
+ q->color[1] = total[1] / (nCount * 255);
+ q->color[2] = total[2] / (nCount * 255);
+
+
+ q->texture_number = texture_extension_number++;
+
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+ // Timo
+ // Surface properties plugins can store their own data in an IPluginQTexture
+ q->pData = g_SurfaceTable.m_pfnQTextureAlloc( q );
+ GETPLUGINTEXDEF(q)->SetDefaultTexdef();
+ }
+
+ if (g_PrefsDlg.m_bSGIOpenGL)
+ {
+ //if (!qwglMakeCurrent(g_qeglobals.d_hdcBase, g_qeglobals.d_hglrcBase))
+ if (!qwglMakeCurrent(s_hdcTexture, s_hglrcTexture))
+ Error ("wglMakeCurrent in LoadTexture failed");
+ }
+
+ qglBindTexture( GL_TEXTURE_2D, q->texture_number );
+
+ //Handle3DfxTexturing(q, width, height, dest);
+
+ SetTexParameters();
+
+ nCount = MAX_TEXTURE_QUALITY - g_PrefsDlg.m_nTextureQuality;
+ while (nCount-- > 0)
+ {
+ if (nWidth > 16 && nHeight > 16)
+ {
+ R_MipMap(pPixels, nWidth, nHeight);
+ }
+ else
+ {
+ break;
+ }
+ }
+
+ if (g_PrefsDlg.m_bSGIOpenGL)
+ {
+ if (nomips)
+ {
+ qglTexImage2D(GL_TEXTURE_2D, 0, 4, nWidth, nHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, pPixels);
+ }
+ else
+ qgluBuild2DMipmaps(GL_TEXTURE_2D, 4, nWidth, nHeight,GL_RGBA, GL_UNSIGNED_BYTE, pPixels);
+ }
+ else
+ {
+ if (nomips)
+ qglTexImage2D(GL_TEXTURE_2D, 0, 4, nWidth, nHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, pPixels);
+ else
+ qgluBuild2DMipmaps(GL_TEXTURE_2D, 4, nWidth, nHeight,GL_RGBA, GL_UNSIGNED_BYTE, pPixels);
+ }
+
+ qglBindTexture( GL_TEXTURE_2D, 0 );
+
+ return q;
+}
+
+
+qtexture_t *Texture_LoadTGATexture (unsigned char* pPixels, int nWidth, int nHeight, char *pPath)
+{
+ CString strName;
+ CString strPath;
+ ExtractPath_and_Filename(pPath, strPath, strName);
+ AddSlash(strPath);
+ strPath += "textureinfo.ini";
+ strName.MakeLower();
+ StripExtension (strName.GetBuffer(0));
+ strName.ReleaseBuffer();
+
+ int nFlags = GetPrivateProfileInt(strName, "Flags", 0, strPath);
+ int nValue = GetPrivateProfileInt(strName, "Value", 0, strPath);
+ int nContents = GetPrivateProfileInt(strName, "Contents", 0, strPath);
+ return Texture_LoadTGATexture(pPixels, nWidth, nHeight, pPath, nFlags, nValue, nContents);
+}
+
+
+void Texture_LoadFromPlugIn(LPVOID vp)
+{
+ g_pluginTexture = notexture;
+ _QERTextureLoad *pLoad = reinterpret_cast<_QERTextureLoad*>(vp);
+ if (pLoad != NULL)
+ {
+ qtexture_t *q;
+ q = Texture_LoadTGATexture(pLoad->m_pRGBA, pLoad->m_nWidth, pLoad->m_nHeight, NULL, pLoad->m_nFlags, pLoad->m_nContents, pLoad->m_nValue);
+ if (q != NULL)
+ {
+ // to save duplicate code (since one always ends up getting forgotten and out of sync) this is now done later by caller
+// strcpy (q->name, pLoad->m_pName);
+// StripExtension (q->name);
+// if (!g_dontuse)
+// q->inuse = true;
+// q->next = g_qeglobals.d_qtextures;
+// g_qeglobals.d_qtextures = q;
+ g_pluginTexture = q;
+ }
+ }
+}
+
+
+/*
+===============
+Texture_CreateSolid
+
+Create a single pixel texture of the apropriate color
+===============
+*/
+qtexture_t *Texture_CreateSolid (const char *name)
+{
+ byte data[4];
+ qtexture_t *q;
+
+ q = (qtexture_t*)qmalloc(sizeof(*q));
+
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+ // Timo
+ // Surface properties plugins can store their own data in an IPluginQTexture
+ q->pData = g_SurfaceTable.m_pfnQTextureAlloc( q );
+ GETPLUGINTEXDEF(q)->SetDefaultTexdef();
+ }
+
+ sscanf (name, "(%f %f %f)", &q->color[0], &q->color[1], &q->color[2]);
+
+ data[0] = q->color[0]*255;
+ data[1] = q->color[1]*255;
+ data[2] = q->color[2]*255;
+ data[3] = 255;
+
+ q->width = q->height = 1;
+ //q->width = q->height = 2;
+ q->texture_number = texture_extension_number++;
+ qglBindTexture( GL_TEXTURE_2D, q->texture_number );
+ SetTexParameters ();
+
+ if (g_PrefsDlg.m_bSGIOpenGL)
+ {
+ qglTexImage2D(GL_TEXTURE_2D, 0, 3, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
+ }
+ else
+ {
+ if (nomips)
+ qglTexImage2D(GL_TEXTURE_2D, 0, 3, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
+ else
+ qgluBuild2DMipmaps(GL_TEXTURE_2D, 3, 1, 1,GL_RGBA, GL_UNSIGNED_BYTE, data);
+ }
+ qglBindTexture( GL_TEXTURE_2D, 0 );
+
+ return q;
+}
+
+
+/*
+=================
+Texture_MakeDefault
+=================
+*/
+qtexture_t* Texture_MakeDefault (void)
+{
+ qtexture_t *q;
+ byte data[4][4];
+
+ if (g_PrefsDlg.m_bSGIOpenGL)
+ {
+ if (s_hdcTexture && s_hglrcTexture)
+ {
+ //if (!qwglMakeCurrent(g_qeglobals.d_hdcBase, g_qeglobals.d_hglrcBase))
+ if (!qwglMakeCurrent(s_hdcTexture, s_hglrcTexture))
+ Error ("wglMakeCurrent in LoadTexture failed");
+ }
+ else
+ return NULL;
+ }
+
+ q = (qtexture_t*)qmalloc(sizeof(*q));
+
+ strcpy (q->name, "notexture");
+ q->width = q->height = 64;
+
+ memset (data, 0, sizeof(data));
+ data[0][2] = data[3][2] = 255;
+
+ q->color[0] = 0;
+ q->color[1] = 0;
+ q->color[2] = 0.5;
+
+ q->texture_number = texture_extension_number++;
+ qglBindTexture( GL_TEXTURE_2D, q->texture_number );
+ SetTexParameters ();
+
+ if (nomips)
+ qglTexImage2D(GL_TEXTURE_2D, 0, 3, 2, 2, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
+ else
+ VERIFY(qgluBuild2DMipmaps(GL_TEXTURE_2D, 3, 2, 2,GL_RGBA, GL_UNSIGNED_BYTE, data) == 0);
+
+ qglBindTexture( GL_TEXTURE_2D, 0 );
+ return q;
+}
+
+
+/*
+=================
+Texture_MakeNotexture
+=================
+*/
+void Texture_MakeNotexture (void)
+{
+ notexture = Texture_MakeDefault();
+ // Timo
+ // Surface properties plugins can store their own data in an IPluginQTexture
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+ notexture->pData = g_SurfaceTable.m_pfnQTextureAlloc( notexture );
+ GETPLUGINTEXDEF(notexture)->SetDefaultTexdef();
+ }
+}
+
+
+void DemandLoadShaderTexture(qtexture_t *q, CShaderInfo *pShader)
+{
+ char cWork[1024];
+ char cWork2[1024];
+ strcpy(cWork, (pShader->m_strTextureName.GetLength() > 0) ? pShader->m_strTextureName : pShader->m_strName);
+ StripExtension(cWork);
+ // TTimo: if the shader has a m_fTransValue != 1.0f, ignore the alpha channel when loading the texture
+ // in some cases (common/weapclip) the 32bit .tga has an empty alpha channel,
+ // causing a display bug in the camera view (brush does not seemed drawn since alpha==0 for the texture)
+ // NOTE: the workaround is not perfect, the same texture may have been loaded earlier with it's alpha channel
+ q = Texture_ForName (cWork, false, true, pShader->m_fTransValue != 1.0f, true, false);
+
+ if (q == NULL || q == notexture) {
+ sprintf(cWork2, "%s/%s",ValueForKey(g_qeglobals.d_project_entity, "basepath"), cWork);
+ q = Texture_ForNamePath( cWork, cWork2);
+
+ if (q == NULL || q == notexture) {
+ q = Texture_ForName (cWork, false, true, pShader->m_fTransValue != 1.0f, true, true);
+ }
+ }
+
+ if (q != NULL && q != notexture)
+ {
+ pShader->m_pQTexture = q;
+ strcpy(q->shadername, pShader->m_strShaderName);
+ q->bFromShader = true;
+ q->fTrans = pShader->m_fTransValue;
+ q->nShaderFlags = pShader->m_nFlags;
+ strcpy(q->name, pShader->m_strName );
+ }
+ else
+ {
+ Sys_Printf("Could not load shader editor image %s\n", cWork);
+ }
+}
+
+
+void LoadShader(char* pFilename, qtexture_t *q)
+{
+ char* pBuff = NULL;
+ CString strTexture;
+ int nSize = LoadFile(pFilename, reinterpret_cast<void**>(&pBuff));
+ if (nSize == -1)
+ {
+ nSize = PakLoadAnyFile(pFilename, reinterpret_cast<void**>(&pBuff));
+ }
+ if (nSize > 0)
+ {
+ StartTokenParsing(pBuff);
+ while (GetToken(true))
+ {
+ // first token should be the path + name.. (from base)
+ CShaderInfo *pShader = new CShaderInfo();
+ pShader->setName(token);
+ pShader->m_strShaderName = pFilename;
+ strTexture = token;
+ bool bGood = true;
+ float fTrans = 1.0;
+ GetToken(true);
+ if (strcmp(token, "{"))
+ {
+ bGood = false;
+ break;
+ }
+ else
+ {
+ // we need to read until we hit a balanced }
+ int nMatch = 1;
+ while (nMatch > 0 && GetToken(true))
+ {
+ if (strcmp(token, "{") == 0)
+ {
+ nMatch++;
+ }
+ else if (strcmp(token, "}") == 0)
+ {
+ nMatch--;
+ }
+ else if (strcmpi(token, "qer_nocarve") == 0)
+ {
+ pShader->m_nFlags |= QER_NOCARVE;
+ }
+ else if (strcmpi(token, "qer_trans") == 0)
+ {
+ if (GetToken(true))
+ {
+ fTrans = atof(token);
+ }
+ pShader->m_nFlags |= QER_TRANS;
+ }
+ else if (strcmpi(token, "qer_editorimage") == 0)
+ {
+ if (GetToken(true))
+ {
+ char* pTex = copystring(token);
+ QE_ConvertDOSToUnixName( pTex, pTex );
+ CString str = pTex;
+ free (pTex);
+ FindReplace(str, "textures/", "");
+ FindReplace(str, ".tga", "");
+ int nPos = str.Find('/');
+ if (nPos == -1)
+ {
+ nPos = str.Find('\\');
+ }
+ if (nPos >= 0)
+ {
+ pShader->m_strTextureName = str;
+ pShader->m_strTextureName.MakeLower(); //avoid problems with case
+/*
+ else
+ {
+ CString strPath = str.Left(nPos+1);
+ DeferredShaderLoad *deferred = new DeferredShaderLoad(str, pShader->m_strName, strPath);
+ g_lstDeferred.Add(deferred);
+ }
+*/
+ }
+ }
+ }
+ else if (strcmpi(token, "surfaceparm") == 0)
+ {
+ //--while (GetToken(false))
+ //--{
+ //--
+ //--}
+ if (GetToken(true))
+ {
+ // next token should be a surface parm
+ //--if (strcmpi(token, "trans") == 0)
+ //--{
+ //-- fTrans = 0.33;
+ //--}
+ if (strcmpi(token, "fog") == 0)
+ {
+ if (fTrans == 1.0) // has not been explicitly set by qer_trans
+ {
+ fTrans = 0.35;
+ }
+ }
+ }
+ }
+ }
+ if (nMatch != 0)
+ {
+ bGood = false;
+ break;
+ }
+ }
+ //--if (bGood && q)
+ if (bGood)
+ {
+ pShader->m_fTransValue = fTrans;
+ g_lstShaders.Add(pShader);
+
+ int n = g_PrefsDlg.m_nShader;
+ if (g_PrefsDlg.m_nShader == CPrefsDlg::SHADER_ALL || (g_PrefsDlg.m_nShader == CPrefsDlg::SHADER_COMMON && strstr(pShader->m_strName, "common" )))
+ {
+// new
+ if (pShader->m_strTextureName.GetLength() > 0)
+ {
+ if (!ShaderQTextureExists(pShader->m_strName))
+ {
+ DemandLoadShaderTexture(q, pShader);
+ }
+ }
+ }
+// end new
+ //--q->bFromShader = true;
+ //--q->fTrans = fTrans;
+
+ //--// good texture here
+ //--//Sys_Printf("Test load texture %s\n", strTexture);
+ //--// FIXME.. this is a load of crap
+ //--strcpy(dirstring, strTexture);
+ //--QE_ConvertDOSToUnixName(dirstring, dirstring);
+ //--strTexture = dirstring;
+ //--FindReplace(strTexture, "textures/", "");
+ //--qtexture_t *q = Texture_ForName (strTexture.GetBuffer(0));
+ //--if (q != NULL)
+ //--{
+ //-- q->bFromShader = true;
+ //-- q->fTrans = fTrans;
+ //--}
+ }
+ else
+ {
+ Sys_Printf("Error parsing shader at texture %s\n", strTexture);
+ }
+
+ }
+ free (pBuff);
+ }
+ else
+ {
+ Sys_Printf("Unabled to read shader %s\n", pFilename);
+ }
+}
+
+
+extern bool DoesFileExist(const char* pBuff, long& lSize);
+CShaderInfo* SetNameShaderInfo(qtexture_t* q, const char* pPath, const char* pName)
+{
+ CShaderInfo *pInfo = hasShader(pName);
+ if (pInfo)
+ {
+ strcpy(q->shadername, pInfo->m_strShaderName);
+ q->bFromShader = true;
+ q->fTrans = pInfo->m_fTransValue;
+ q->nShaderFlags = pInfo->m_nFlags;
+ }
+ else
+ {
+ q->shadername[0] = 0;
+ }
+ strncpy (q->name, pName, sizeof(q->name) - 1);
+ StripExtension (q->name);
+ return pInfo;
+}
+
+void ReplaceQTexture(qtexture_t *pOld, qtexture_t *pNew, brush_t *pList)
+{
+ for (brush_t* pBrush = pList->next ; pBrush != pList; pBrush = pBrush->next)
+ {
+ if (pBrush->patchBrush)
+ {
+ Patch_ReplaceQTexture(pBrush, pOld, pNew);
+ }
+ if (pBrush->terrainBrush)
+ {
+ Terrain_ReplaceQTexture(pBrush->pTerrain, pOld, pNew);
+ }
+
+ for (face_t* pFace = pBrush->brush_faces; pFace; pFace = pFace->next)
+ {
+ if (pFace->d_texture == pOld)
+ {
+ pFace->d_texture = pNew;
+ }
+ }
+
+ //Brush_Build(pBrush);
+ }
+}
+
+
+void Texture_Remove(qtexture_t *q)
+{
+ qtexture_t* pTex = g_qeglobals.d_qtextures->next;
+ if (q == g_qeglobals.d_qtextures) // it is the head
+ {
+ g_qeglobals.d_qtextures->next = q->next->next;
+ g_qeglobals.d_qtextures = q->next;
+ }
+ else
+ {
+ qtexture_t* pLast = g_qeglobals.d_qtextures;
+ while (pTex != NULL && pTex != g_qeglobals.d_qtextures)
+ {
+ if (pTex == q)
+ {
+ pLast->next = q->next;
+ break;
+ }
+ pLast = pTex;
+ pTex = pTex->next;
+ }
+ }
+ qglDeleteTextures(1, reinterpret_cast<const unsigned int*>(&q->texture_number));
+
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+ // Timo
+ // Surface properties plugin
+#ifdef _DEBUG
+ if ( !q->pData )
+ Sys_Printf("WARNING: found a qtexture_t* with no IPluginQTexture\n");
+#endif
+ if ( q->pData )
+ GETPLUGINTEXDEF(q)->DecRef();
+ }
+
+ free(q);
+
+}
+
+/*
+=================
+Texture_MakeNoShadertexture
+
+Make a default black/red check pattern texture
+=================
+*/
+qtexture_t * Texture_MakeNoshadertexture( const char *name )
+{
+ qtexture_t *q;
+ byte data[4][4];
+
+ notexture = q = (qtexture_t*)qmalloc(sizeof(*q));
+ q->width = q->height = 64;
+ q->fTrans = 1;
+
+ q = (qtexture_t*)qmalloc(sizeof(*q));
+ strcpy (q->name, name);
+
+ q->width = q->height = 64;
+ q->fTrans = 1;
+
+ memset (data, 0, sizeof(data));
+ data[0][0] = data[3][0] = 255;
+
+ q->color[0] = 0;
+ q->color[1] = 0;
+ q->color[2] = 0.5;
+
+ q->texture_number = texture_extension_number++;
+ qglBindTexture( GL_TEXTURE_2D, q->texture_number );
+ SetTexParameters ();
+
+ if (nomips)
+ qglTexImage2D(GL_TEXTURE_2D, 0, 3, 2, 2, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
+ else
+ VERIFY(qgluBuild2DMipmaps(GL_TEXTURE_2D, 3, 2, 2,GL_RGBA, GL_UNSIGNED_BYTE, data) == 0);
+
+ qglBindTexture( GL_TEXTURE_2D, 0 );
+
+ return q;
+}
+
+
+
+/*
+===============
+Texture_ForName
+===============
+*/
+//bReload is set to true when called from DemandLoadShaderTexture because it should never re-use
+//an already loaded texture
+qtexture_t *Texture_ForName (const char *name, bool bReplace, bool bShader, bool bNoAlpha, bool bReload, bool makeShader)
+{
+ byte *lump;
+ qtexture_t *q = NULL;
+ char filename[1024];
+
+ if (name == NULL || strlen(name) == 0)
+ return notexture;
+
+ qtexture_t *pRemove = NULL;
+
+ if (!bReload)
+ {
+ for (q=g_qeglobals.d_qtextures ; q ; q=q->next)
+ {
+ if (!strcmp(name, q->name))
+ {
+ if (bReplace)
+ {
+ pRemove = q;
+ //Texture_Remove(q);
+ break;
+ }
+ else
+ {
+#ifdef _DEBUG
+ // if the texture is already in memory, then the bNoAlpha flag doesn't have any influence
+ if (bNoAlpha)
+ Sys_Printf("WARNING: bNoAlpha flag on an already loaded texture\n");
+#endif
+ if (!g_dontuse)
+ {
+ q->inuse = true;
+ }
+ return q;
+ }
+ }
+ }
+ }
+
+ // did not find it in the standard list
+ // skip entity names (
+ if (!bShader && name[0] != '(')
+ {
+ CShaderInfo* pShader = hasShader(name);
+ if (pShader)
+ {
+ if (pShader->m_pQTexture == NULL)
+ {
+ DemandLoadShaderTexture(q, pShader);
+ }
+ q = pShader->m_pQTexture;
+ //Sys_Printf ("used Shader %s.\n", pShader->m_strName);
+ }
+ if ( q != NULL)
+ {
+ return q;
+ }
+ }
+
+
+ if (name[0] == '(')
+ {
+ q = Texture_CreateSolid (name);
+ strncpy (q->name, name, sizeof(q->name)-1);
+ }
+ else
+ {
+ // FIXME: this is a mess.. need to move consolidate stuff
+ // down to a single routine..
+ //
+ // if plugins have a texture loader
+ // {
+ //
+ // }
+ // else
+ //
+ if (g_pParentWnd->GetPlugInMgr().GetTextureInfo() != NULL)
+ {
+ // rad: 12/19/98
+ // if the plugin is not a wad style then we need to treat it normally
+ // otherwise return without trying to explicitly load the texture
+ // as it should have been loaded by the wad style plugin at init time
+ CString strTex = GetTextureExtension(0);
+ sprintf (filename, "%s\\%s.%s", ValueForKey (g_qeglobals.d_project_entity, "texturepath"), name, strTex);
+ if (!g_pParentWnd->GetPlugInMgr().GetTextureInfo()->m_bWadStyle)
+ {
+ g_pParentWnd->GetPlugInMgr().LoadTexture(filename);
+ if (g_pluginTexture)
+ q = g_pluginTexture;
+ }
+ else
+ {
+ return notexture;
+ // wadstyle.. if we get here then we do not have it
+ }
+ }
+ else
+ // we need to try several formats here, or would it be better if we are given a complete name
+ if (g_PrefsDlg.m_bHiColorTextures == TRUE)
+ {
+ char cWork[1024];
+ sprintf (filename, "%s/%s.tga", ValueForKey (g_qeglobals.d_project_entity, "texturepath"), name);
+ QE_ConvertDOSToUnixName( cWork, filename );
+ strcpy(filename, cWork);
+ Sys_Printf ("Loading %s...", name);
+ unsigned char* pPixels = NULL;
+ int nWidth;
+ int nHeight;
+ LoadImage(filename, &pPixels, &nWidth, &nHeight);
+ if (pPixels == NULL)
+ {
+ // try jpg
+ // blatant assumption of .tga should be fine since we sprintf'd it above
+ int nLen = strlen(filename);
+ filename[nLen-3] = 'j';
+ filename[nLen-2] = 'p';
+ filename[nLen-1] = 'g';
+ LoadImage(filename, &pPixels, &nWidth, &nHeight);
+ }
+ if (pPixels)
+ {
+ // if we were asked to ignore alpha channel, do it now (.TGA is the only supported file type with alpha channel)
+ //if (bNoAlpha)
+ if (TRUE)
+ {
+ unsigned char* iPix = pPixels;
+ int nCount = nWidth * nHeight;
+ for(iPix=pPixels+3; iPix-pPixels < nCount*4; iPix+=4)
+ *iPix = 255;
+ }
+ // we'll be binding the GL texture now
+ // need to check we are using a right GL context
+ // with GL plugins that have their own window, the GL context may be the plugin's, in which case loading textures will bug
+ HDC currentHDC = qwglGetCurrentDC();
+ HGLRC currentHGLRC = qwglGetCurrentContext();
+ //++timo FIXME: this may duplicate with qtexture_t* WINAPI QERApp_Texture_ForName (const char *name)
+ //++timo FIXME: we need a list of lawfull GL contexts or something?
+ // I'd rather always use the same GL context for binding...
+ if (currentHDC != g_qeglobals.d_hdcBase || currentHGLRC != g_qeglobals.d_hglrcBase)
+ qwglMakeCurrent( g_qeglobals.d_hdcBase, g_qeglobals.d_hglrcBase );
+ q = Texture_LoadTGATexture(pPixels, nWidth, nHeight, NULL, 0, 0, 0);
+ //++timo I don't set back the GL context .. I don't know how safe it is
+ //qwglMakeCurrent( currentHDC, currentHGLRC );
+ //++timo storing the filename .. will be removed by shader code cleanup
+ // this is dirty, and we sure miss some places were we should fill the filename info
+ strcpy( q->filename, name );
+ SetNameShaderInfo(q, filename, name);
+ Sys_Printf ("done.\n", name);
+ free(pPixels);
+ }
+ }
+ else
+ {
+ // load the file
+ sprintf (filename, "%s/%s.wal", ValueForKey (g_qeglobals.d_project_entity, "texturepath"), name);
+ Sys_Printf ("Loading %s...", name);
+ if (LoadFile (filename, (void**)&lump) == -1)
+ {
+ sprintf (filename, "%s.wal", name);
+ Sys_Printf("failed.. trying pak0.pak..");
+ if(!PakLoadFile(filename, (void**)&lump))
+ {
+ Sys_Printf (" load failed!\n");
+ return notexture;
+ }
+ }
+ Sys_Printf("successful.\n");
+ q = Texture_LoadTexture ((miptex_t *)lump);
+ free (lump);
+ strncpy (q->name, name, sizeof(q->name)-1);
+ StripExtension (q->name);
+ }
+
+ if (g_PrefsDlg.m_bSGIOpenGL)
+ {
+ if(!q)
+ return notexture;
+ }
+
+ }// name[0] != '('
+
+ if(!q) // safety
+ {
+ if (bShader && !makeShader) {
+ return q;
+ }
+
+ if (bShader)
+ {
+ q = Texture_MakeNoshadertexture( name );
+ Sys_Printf("failed, using default shader\n");
+ }
+ else
+ {
+ q = Texture_MakeDefault();
+ Sys_Printf("failed, using default\n");
+ }
+ }
+
+ strncpy (q->name, name, sizeof(q->name)-1);
+ if (name[0] != '(')
+ {
+ StripExtension (q->name);
+ }
+
+ if (!g_dontuse)
+ q->inuse = true;
+ q->next = g_qeglobals.d_qtextures;
+ g_qeglobals.d_qtextures = q;
+
+ if (pRemove != NULL)
+ {
+ ReplaceQTexture(pRemove, q, &active_brushes);
+ ReplaceQTexture(pRemove, q, &filtered_brushes);
+ Texture_Remove(pRemove);
+ }
+
+ return q;
+}
+
+/*
+===============
+Texture_ForNamePath
+===============
+*/
+qtexture_t *Texture_ForNamePath(char* name, char* pFullPath)
+{
+ byte *lump;
+ qtexture_t *q;
+ char filename[1024];
+
+ if (strlen(name) == 0)
+ return notexture;
+
+ for (q=g_qeglobals.d_qtextures ; q ; q=q->next)
+ {
+ if (!strcmp(name, q->name))
+ {
+ if (!g_dontuse)
+ q->inuse = true;
+ return q;
+ }
+ }
+
+ if (name[0] == '(')
+ {
+ q = Texture_CreateSolid (name);
+ strncpy (q->name, name, sizeof(q->name)-1);
+ }
+ else
+ {
+ // load the file
+ if (g_PrefsDlg.m_bHiColorTextures == TRUE)
+ {
+ char cWork[1024];
+ if (strstr(pFullPath, ".tga") == NULL) {
+ sprintf(filename, "%s%s", pFullPath, ".tga");
+ } else {
+ strcpy(filename, pFullPath);
+ }
+ QE_ConvertDOSToUnixName( cWork, filename );
+ strcpy(filename, cWork);
+ Sys_Printf ("Loading %s...", name);
+ unsigned char* pPixels = NULL;
+ int nWidth;
+ int nHeight;
+ LoadImage(filename, &pPixels, &nWidth, &nHeight);
+ if (!pPixels)
+ {
+ // try jpg
+ // blatant assumption of .tga should be fine since we sprintf'd it above
+ int nLen = strlen(filename);
+ filename[nLen-3] = 'j';
+ filename[nLen-2] = 'p';
+ filename[nLen-1] = 'g';
+ LoadImage(filename, &pPixels, &nWidth, &nHeight);
+ }
+ if (pPixels)
+ {
+ q = Texture_LoadTGATexture(pPixels, nWidth, nHeight, NULL, 0, 0, 0);
+ //++timo storing the filename .. will be removed by shader code cleanup
+ // this is dirty, and we sure miss some places were we should fill the filename info
+ // NOTE: we store relative path, need to extract it
+ strcpy( q->filename, name );
+
+ }
+ else
+ {
+ return notexture;
+ }
+ free(pPixels);
+ }
+ else
+ {
+ sprintf(filename, "%s%s", pFullPath, ".wal");
+ Sys_Printf ("Loading %s...", name);
+ if (LoadFile (filename, (void**)&lump) == -1)
+ {
+ Sys_Printf (" load failed!\n");
+ return notexture;
+ }
+ Sys_Printf("successful.\n");
+ q = Texture_LoadTexture ((miptex_t *)lump);
+ free (lump);
+ }
+ if (g_PrefsDlg.m_bSGIOpenGL)
+ {
+ if(!q)
+ return notexture;
+ }
+ strncpy (q->name, name, sizeof(q->name)-1);
+ StripExtension (q->name);
+ }
+
+ if (!g_dontuse)
+ q->inuse = true;
+ q->next = g_qeglobals.d_qtextures;
+ g_qeglobals.d_qtextures = q;
+
+ return q;
+}
+
+
+
+/*
+==================
+FillTextureMenu
+
+==================
+*/
+void FillTextureMenu (CStringArray* pArray)
+{
+ HMENU hmenu;
+ int i;
+ struct _finddata_t fileinfo;
+ int handle;
+ char dirstring[1024];
+ char *path;
+ DIRLIST *list = NULL, *temp;
+
+ if (g_pParentWnd->GetPlugInMgr().GetTextureInfo() != NULL)
+ {
+ if (g_pParentWnd->GetPlugInMgr().GetTextureInfo()->m_bWadStyle)
+ return;
+ }
+
+ hmenu = GetSubMenu (GetMenu(g_qeglobals.d_hwndMain), MENU_TEXTURE);
+
+ // delete everything
+ for (i=0 ; i<texture_nummenus ; i++)
+ DeleteMenu (hmenu, CMD_TEXTUREWAD+i, MF_BYCOMMAND);
+
+ texture_nummenus = 0;
+
+ // add everything
+ if (g_qeglobals.d_project_entity)
+ {
+ //--if (g_PrefsDlg.m_bUseShaders)
+ //--{
+ //-- path = ValueForKey (g_qeglobals.d_project_entity, "basepath");
+ //-- sprintf (dirstring, "%s/scripts/*.shader", path);
+ //--
+ //--}
+ //--else
+ //--{
+ path = ValueForKey (g_qeglobals.d_project_entity, "texturepath");
+ sprintf (dirstring, "%s/*.*", path);
+ //--}
+
+ handle = _findfirst (dirstring, &fileinfo);
+ if (handle != -1)
+ {
+ do
+ {
+ //--if (g_PrefsDlg.m_bUseShaders)
+ //--{
+ //-- if ((fileinfo.attrib & _A_SUBDIR))
+ //-- continue;
+ //--}
+ //--else
+ //--{
+ if (!(fileinfo.attrib & _A_SUBDIR))
+ continue;
+ if (fileinfo.name[0] == '.')
+ continue;
+ //--}
+ // add this directory to the menu
+ AddToDirListAlphabetized(&list, fileinfo.name, FROMDISK);
+ } while (_findnext( handle, &fileinfo ) != -1);
+
+ _findclose (handle);
+ }
+
+ //--if (!g_PrefsDlg.m_bUseShaders)
+ //--{
+ GetPackTextureDirs(&list);
+ //--}
+
+ for(temp = list; temp; temp = temp->next)
+ {
+ AppendMenu (hmenu, MF_ENABLED|MF_STRING, CMD_TEXTUREWAD+texture_nummenus, (LPCTSTR)temp->dirname);
+ strcpy (texture_menunames[texture_nummenus], temp->dirname);
+ //--if (!g_PrefsDlg.m_bUseShaders)
+ //--{
+ strcat (texture_menunames[texture_nummenus], "/");
+ //--}
+ if (pArray)
+ pArray->Add(temp->dirname);
+ if (++texture_nummenus == MAX_TEXTUREDIRS)
+ break;
+ }
+
+ ClearDirList(&list);
+ }
+
+
+}
+
+
+/*
+==================
+Texture_ClearInuse
+
+A new map is being loaded, so clear inuse markers
+==================
+*/
+void Texture_ClearInuse (void)
+{
+ qtexture_t *q;
+
+ for (q=g_qeglobals.d_qtextures ; q ; q=q->next)
+ {
+ q->inuse = false;
+ }
+}
+
+
+
+
+void LoadShadersFromDir(const char *pPath)
+{
+ int nSize = g_lstShaders.GetSize();
+ for (int i = 0; i < nSize; i++)
+ {
+ CShaderInfo *pInfo = reinterpret_cast<CShaderInfo*>(g_lstShaders.ElementAt(i));
+ if (pInfo != NULL)
+ {
+ if (strstr(pInfo->m_strName, pPath) && pInfo->m_pQTexture == NULL && strstr(pInfo->m_strName, "models/player") == NULL)
+ {
+ qtexture_t *q = NULL;
+ DemandLoadShaderTexture(q, pInfo);
+ }
+ }
+ }
+}
+
+
+/*
+==============
+Texture_ShowDirectory
+==============
+*/
+void Texture_ShowDirectory (int menunum, bool bLinked)
+{
+ struct _finddata_t fileinfo;
+ int handle;
+ char name[1024];
+ char dirstring[1024];
+ char linkstring[1024];
+ FILELIST *list = NULL, *temp;
+ CString strTemp;
+
+ //Texture_Flush(false);
+ //Select_Deselect();
+ Texture_ClearInuse();
+ texture_showinuse = false;
+ strcpy (texture_directory, texture_menunames[menunum-CMD_TEXTUREWAD]);
+
+ if (g_pParentWnd->GetPlugInMgr().GetTextureInfo() != NULL)
+ {
+ if (g_pParentWnd->GetPlugInMgr().GetTextureInfo()->m_bWadStyle)
+ return;
+ }
+
+ // new
+/*
+ if (!g_PrefsDlg.m_bShaderTest)
+ {
+ g_dontuse = true; // needed because this next piece of code calls Texture_ForName() internally! -slc
+ LoadDeferred(texture_directory);
+ g_dontuse = false;
+ }
+*/
+ if (g_PrefsDlg.m_bHiColorTextures == FALSE)
+ {
+ }
+
+ g_qeglobals.d_texturewin.originy = 0;
+
+ //--if (g_PrefsDlg.m_bUseShaders)
+ //--{
+ //-- sprintf (dirstring, "%s/scripts/%s", ValueForKey (g_qeglobals.d_project_entity, "basepath"), texture_directory);
+ //-- Sys_Printf("loading textures from shader %s\n", dirstring);
+ //-- LoadShader(dirstring);
+ //--}
+ //--else
+ //--{
+ Sys_Status("Loading textures\n", 0);
+
+ // load all image files
+
+ sprintf (linkstring, "%s/textures/%stextureinfo.ini", ValueForKey (g_qeglobals.d_project_entity, "basepath"), texture_menunames[menunum-CMD_TEXTUREWAD]);
+
+ for (int nExt = 0; nExt < GetTextureExtensionCount(); nExt++)
+ {
+ sprintf (dirstring, "%s/textures/%s*.%s", ValueForKey (g_qeglobals.d_project_entity, "basepath"), texture_menunames[menunum-CMD_TEXTUREWAD],GetTextureExtension(nExt));
+ Sys_Printf ("Scanning %s\n", dirstring);
+ handle = _findfirst (dirstring, &fileinfo);
+
+ if (handle == -1)
+ {
+ sprintf(dirstring, "%s/%s*.%s", ValueForKey (g_qeglobals.d_project_entity, "texturepath"), texture_menunames[menunum-CMD_TEXTUREWAD],GetTextureExtension(nExt));
+ handle = _findfirst (dirstring, &fileinfo);
+ }
+ if (handle != -1)
+ {
+ do
+ {
+ sprintf (name, "%s%s", texture_directory, fileinfo.name);
+ AddToFileListAlphabetized(&list, name, FROMDISK, 0, false);
+ } while (_findnext( handle, &fileinfo ) != -1);
+ _findclose (handle);
+ }
+ else
+ {
+ sprintf (dirstring, "%s*.%s", texture_menunames[menunum-CMD_TEXTUREWAD],GetTextureExtension(nExt));
+ GetPackFileList(&list, dirstring);
+ }
+ }
+
+ g_dontuse = true;
+ for(temp = list; temp; temp = temp->next)
+ {
+ if(temp->offset == -1)
+ sprintf(name, "%s", temp->filename);
+ else
+ sprintf(name, "%s%s", texture_menunames[menunum-CMD_TEXTUREWAD], temp->filename);
+ StripExtension (name);
+ strTemp = name;
+ strTemp.MakeLower();
+ if ( strTemp.Find(".specular") >= 0 ||
+ strTemp.Find(".glow") >= 0 ||
+ strTemp.Find(".bump") >= 0 ||
+ strTemp.Find(".diffuse") >= 0 ||
+ strTemp.Find(".blend") >= 0 ||
+ strTemp.Find(".alpha") >= 0
+ )
+ continue;
+ else
+ {
+ Texture_ForName (name, true);
+ }
+ }
+
+ ClearFileList(&list);
+ //--}
+
+
+ g_dontuse = false;
+
+ if (!bLinked)
+ {
+
+ for (int k = 0; k < 10; k++)
+ {
+ sprintf(name, "Path%d", k);
+ if (GetPrivateProfileString("Include", name, "", dirstring, 1024, linkstring) > 0)
+ {
+ Texture_ShowDirectory(dirstring, true);
+ }
+ }
+
+ LoadShadersFromDir(texture_directory);
+
+ SortTextures();
+
+ sprintf (name, "Textures: %s", texture_directory);
+ SetWindowText(g_qeglobals.d_hwndEntity, name);
+
+ // select the first texture in the list
+ if (!g_qeglobals.d_texturewin.texdef.name[0])
+ SelectTexture (16, g_qeglobals.d_texturewin.height -16, false);
+ }
+}
+
+
+// this can be combined with the above, but per usual i am in a hurry
+//
+void Texture_ShowDirectory (char* pPath, bool bLinked)
+{
+ struct _finddata_t fileinfo;
+ int handle;
+ char name[1024];
+ char dirstring[1024];
+ char linkstring[1024];
+ FILELIST *list = NULL, *temp;
+
+ //Texture_Flush(false);
+
+ texture_showinuse = false;
+ Texture_ClearInuse();
+ strcpy (texture_directory, pPath);
+
+ if (g_PrefsDlg.m_bHiColorTextures == FALSE)
+ {
+ }
+
+ g_qeglobals.d_texturewin.originy = 0;
+ Sys_Status("loading all textures\n", 0);
+
+ // load all .wal files
+ for (int nExt = 0; nExt < GetTextureExtensionCount(); nExt++)
+ {
+ sprintf(dirstring, "%s*.%s", pPath,GetTextureExtension(nExt));
+
+ Sys_Printf ("Scanning %s\n", dirstring);
+
+ handle = _findfirst (dirstring, &fileinfo);
+
+ if (handle != -1)
+ {
+ do
+ {
+ sprintf (name, "%s%s", texture_directory, fileinfo.name);
+ AddToFileListAlphabetized(&list, name, FROMDISK, 0, false);
+ } while (_findnext( handle, &fileinfo ) != -1);
+ _findclose (handle);
+ }
+ else
+ {
+ //sprintf (dirstring, "%s*.wal", texture_menunames[menunum-CMD_TEXTUREWAD]);
+ //if(!GetPackFileList(&list, dirstring))
+ return;
+ }
+ }
+
+ g_dontuse = true;
+ for(temp = list; temp; temp = temp->next)
+ {
+ if(temp->offset == -1)
+ sprintf(name, "%s", temp->filename);
+ else
+ sprintf(name, "%s%s", pPath, temp->filename);
+ StripExtension (name);
+
+ int nLen = strlen(name)-1;
+ ASSERT(nLen > 0);
+ while (name[nLen] != '\\')
+ nLen--;
+ // found first one
+ nLen--;
+ ASSERT(nLen > 0);
+ while (name[nLen] != '\\')
+ nLen--;
+ ASSERT(nLen >= 0);
+ QE_ConvertDOSToUnixName(name, name);
+ Texture_ForName(&name[nLen+1]);
+
+ }
+
+ ClearFileList(&list);
+
+ g_dontuse = false;
+
+ SortTextures();
+
+ if (!bLinked)
+ {
+
+ for (int k = 0; k < 10; k++)
+ {
+ sprintf(name, "Path%d", k);
+ if (GetPrivateProfileString("Include", name, "", dirstring, 1024, linkstring) > 0)
+ {
+ Texture_ShowDirectory(dirstring, true);
+ }
+ }
+
+
+ sprintf (name, "Textures: %s", texture_directory);
+ SetWindowText(g_qeglobals.d_hwndEntity, name);
+
+ // select the first texture in the list
+ if (!g_qeglobals.d_texturewin.texdef.name[0])
+ SelectTexture (16, g_qeglobals.d_texturewin.height -16 ,false);
+ }
+}
+
+
+
+void Texture_ResetPosition()
+{
+ SelectTexture (16, g_qeglobals.d_texturewin.height -16 ,false);
+ g_qeglobals.d_texturewin.originy = 0;
+}
+
+
+
+/*
+==================
+Texture_SetInuse
+
+==================
+*/
+void Texture_SetInuse (void)
+{
+ qtexture_t *q;
+
+ for (q=g_qeglobals.d_qtextures ; q ; q=q->next)
+ {
+ q->inuse = true;
+ }
+}
+
+
+/*
+==============
+Texture_ShowAll
+==============
+*/
+void Texture_ShowAll()
+{
+ Texture_SetInuse();
+ Sys_Printf("Showing all textures...\n");
+ Sys_UpdateWindows (W_TEXTURE);
+}
+
+/*
+==============
+Texture_ShowInuse
+==============
+*/
+void Texture_ShowInuse (void)
+{
+ face_t *f;
+ brush_t *b;
+ char name[1024];
+
+ texture_showinuse = true;
+ g_dontuse = false;
+
+ g_qeglobals.d_texturewin.originy = 0;
+
+ Texture_ClearInuse();
+ Sys_Status("Selecting active textures\n", 0);
+
+ for (b=active_brushes.next ; b != NULL && b != &active_brushes ; b=b->next)
+ {
+ if (b->patchBrush)
+ {
+ Texture_ForName(b->pPatch->d_texture->name);
+ }
+ else
+ {
+ for (f=b->brush_faces ; f ; f=f->next)
+ {
+ Texture_ForName (f->texdef.name);
+ }
+ }
+ }
+
+ for (b=selected_brushes.next ; b != NULL && b != &selected_brushes ; b=b->next)
+ {
+ if (b->patchBrush)
+ {
+ Texture_ForName(b->pPatch->d_texture->name);
+ }
+ else
+ {
+ for (f=b->brush_faces ; f ; f=f->next)
+ {
+ Texture_ForName (f->texdef.name);
+ }
+ }
+ }
+
+ SortTextures();
+ //SetInspectorMode(W_TEXTURE);
+ Sys_UpdateWindows (W_TEXTURE);
+
+ sprintf (name, "Textures: in use");
+ SetWindowText(g_qeglobals.d_hwndEntity, name);
+
+ // select the first texture in the list
+ if (!g_qeglobals.d_texturewin.texdef.name[0])
+ {
+ SelectTexture (16, g_qeglobals.d_texturewin.height -16, false);
+ }
+}
+
+/*
+============================================================================
+
+TEXTURE LAYOUT
+
+============================================================================
+*/
+
+void Texture_StartPos (void)
+{
+ current_texture = g_qeglobals.d_qtextures;
+ current_x = 8;
+ current_y = -8;
+ current_row = 0;
+}
+
+qtexture_t *Texture_NextPos (int *x, int *y)
+{
+ qtexture_t *q;
+
+ while (1)
+ {
+ q = current_texture;
+ if (!q)
+ return q;
+ current_texture = current_texture->next;
+ if (q->name[0] == '(') // fake color texture
+ continue;
+
+ if (g_bFilterEnabled)
+ {
+ CString strName = q->name;
+ int nPos = strName.Find('\\');
+ if (nPos == -1)
+ nPos = strName.Find('/');
+ if (nPos >= 0)
+ strName = strName.Right(strName.GetLength() - nPos - 1);
+ if (strnicmp(g_strFilter.GetBuffer(0), strName, g_strFilter.GetLength()) == 0)
+ break;
+ else
+ continue;
+ }
+
+ if (q->bFromShader && g_PrefsDlg.m_bShowShaders == FALSE)
+ {
+ continue;
+ }
+
+ if (q->inuse)
+ break; // always show in use
+
+ if (!texture_showinuse && !strnicmp (q->name, texture_directory, strlen(texture_directory)))
+ break;
+ continue;
+ }
+
+ int nWidth = (g_PrefsDlg.m_bHiColorTextures == TRUE) ? q->width * ((float)g_PrefsDlg.m_nTextureScale / 100) : q->width;
+ int nHeight = (g_PrefsDlg.m_bHiColorTextures == TRUE) ? q->height * ((float)g_PrefsDlg.m_nTextureScale / 100) : q->height;
+ if (current_x + nWidth > g_qeglobals.d_texturewin.width-8 && current_row)
+ { // go to the next row unless the texture is the first on the row
+ current_x = 8;
+ current_y -= current_row + FONT_HEIGHT + 4;
+ current_row = 0;
+ }
+
+ *x = current_x;
+ *y = current_y;
+
+ // Is our texture larger than the row? If so, grow the
+ // row height to match it
+
+ if (current_row < nHeight)
+ current_row = nHeight;
+
+ // never go less than 64, or the names get all crunched up
+ current_x += nWidth < 64 ? 64 : nWidth;
+ current_x += 8;
+
+ return q;
+}
+
+/*
+============================================================================
+
+ MOUSE ACTIONS
+
+============================================================================
+*/
+
+static int textures_cursorx, textures_cursory;
+
+
+/*
+============
+Texture_SetTexture
+
+brushprimit_texdef must be understood as a qtexture_t with width=2 height=2 ( the default one )
+============
+*/
+void Texture_SetTexture (texdef_t *texdef, brushprimit_texdef_t *brushprimit_texdef, bool bFitScale, IPluginTexdef *pTexdef, bool bSetSelection )
+{
+ qtexture_t *q;
+ int x,y;
+
+ if (texdef->name[0] == '(')
+ {
+ Sys_Status("Can't select an entity texture\n", 0);
+ return;
+ }
+ g_qeglobals.d_texturewin.texdef = *texdef;
+ g_qeglobals.d_texturewin.texdef.flags &= ~SURF_KEEP;
+ g_qeglobals.d_texturewin.texdef.contents &= ~CONTENTS_KEEP;
+ // store the texture coordinates for new brush primitive mode
+ // be sure that all the callers are using the default 2x2 texture
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ g_qeglobals.d_texturewin.brushprimit_texdef = *brushprimit_texdef;
+ }
+ // surface properties plugin
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+ if (g_qeglobals.d_texturewin.pTexdef)
+ {
+ // decrement reference count
+ static_cast<IPluginTexdef *>(g_qeglobals.d_texturewin.pTexdef)->DecRef();
+ g_qeglobals.d_texturewin.pTexdef = NULL;
+ }
+ if (pTexdef)
+ {
+ g_qeglobals.d_texturewin.pTexdef = pTexdef->Copy();
+ }
+ }
+
+ Sys_UpdateWindows (W_TEXTURE);
+
+ g_dlgFind.updateTextures(texdef->name);
+
+ if (!g_dlgFind.isOpen() && bSetSelection)
+ {
+ Select_SetTexture(texdef,brushprimit_texdef,bFitScale);
+ }
+
+
+ //plugins: send a message telling that the selected texture may have changed
+ DispatchRadiantMsg( RADIANT_TEXTURE );
+
+ // scroll origin so the texture is completely on screen
+ Texture_StartPos ();
+ while (1)
+ {
+ q = Texture_NextPos (&x, &y);
+ if (!q)
+ break;
+
+ int nWidth = (g_PrefsDlg.m_bHiColorTextures == TRUE) ? q->width * ((float)g_PrefsDlg.m_nTextureScale / 100) : q->width;
+ int nHeight = (g_PrefsDlg.m_bHiColorTextures == TRUE) ? q->height * ((float)g_PrefsDlg.m_nTextureScale / 100) : q->height;
+ if (!strcmpi(texdef->name, q->name))
+ {
+ if (y > g_qeglobals.d_texturewin.originy)
+ {
+ g_qeglobals.d_texturewin.originy = y;
+ Sys_UpdateWindows (W_TEXTURE);
+ return;
+ }
+
+ if (y-nHeight-2*FONT_HEIGHT < g_qeglobals.d_texturewin.originy-g_qeglobals.d_texturewin.height)
+ {
+ g_qeglobals.d_texturewin.originy = y-nHeight-2*FONT_HEIGHT+g_qeglobals.d_texturewin.height;
+ Sys_UpdateWindows (W_TEXTURE);
+ return;
+ }
+
+ return;
+ }
+ }
+}
+
+
+HWND FindEditWindow()
+{
+ HWND hwnd = FindWindow("TEditPadForm", NULL);
+ HWND hwndEdit = NULL;
+ if (hwnd != NULL)
+ {
+ HWND hwndTab = FindWindowEx(hwnd, NULL, "TTabControl", NULL);
+ if (hwndTab != NULL)
+ {
+ hwndEdit = FindWindowEx(hwndTab, NULL, "TRicherEdit", NULL);
+ }
+ }
+ return hwndEdit;
+}
+
+void Delay(float fSeconds)
+{
+ DWORD dw = ::GetTickCount();
+ DWORD dwTil = dw + (fSeconds * 1000);
+ while (::GetTickCount() < dwTil)
+ {
+ MSG msg;
+ if (::PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ))
+ {
+ TranslateMessage(&msg);
+ DispatchMessage(&msg);
+ }
+ }
+}
+
+
+void ViewShader(const char *pFile, const char *pName)
+{
+ CString str;
+ char* pBuff = NULL;
+ int nSize = LoadFile(pFile, reinterpret_cast<void**>(&pBuff));
+ if (nSize == -1)
+ {
+ nSize = PakLoadAnyFile(pFile, reinterpret_cast<void**>(&pBuff));
+ }
+ if (nSize > 0)
+ {
+ str = pBuff;
+ }
+ int nStart = 0;
+ if (str.GetLength() > 0)
+ {
+ CString strFind = pName;
+ CString strLook = str;
+ strLook.MakeLower();
+ strFind.MakeLower();
+ int n = strLook.Find(strFind);
+ if (n >= 0)
+ {
+ nStart = n;
+ }
+ }
+
+ CString s= "editpad ";
+ s += pFile;
+ WinExec(s, SW_SHOWNORMAL);
+
+ Delay(1.5);
+
+ HWND hwndEdit = FindEditWindow();
+
+ if (hwndEdit != NULL)
+ {
+ PostMessage(hwndEdit, EM_SETSEL, nStart, nStart);
+ }
+ else
+ {
+ Sys_Printf("Unable to load shader editor.\n");
+ }
+
+
+}
+
+/*
+==============
+SelectTexture
+
+ By mouse click
+==============
+*/
+void SelectTexture (int mx, int my, bool bShift, bool bFitScale)
+{
+ int x, y;
+ qtexture_t *q;
+ texdef_t tex;
+ brushprimit_texdef_t brushprimit_tex;
+
+ my += g_qeglobals.d_texturewin.originy-g_qeglobals.d_texturewin.height;
+
+ Texture_StartPos ();
+ while (1)
+ {
+ q = Texture_NextPos (&x, &y);
+ if (!q)
+ break;
+ int nWidth = (g_PrefsDlg.m_bHiColorTextures == TRUE) ? q->width * ((float)g_PrefsDlg.m_nTextureScale / 100) : q->width;
+ int nHeight = (g_PrefsDlg.m_bHiColorTextures == TRUE) ? q->height * ((float)g_PrefsDlg.m_nTextureScale / 100) : q->height;
+ if (mx > x && mx - x < nWidth
+ && my < y && y - my < nHeight + FONT_HEIGHT)
+ {
+ if (bShift)
+ {
+ if (g_PrefsDlg.m_bHiColorTextures && q->shadername[0] != 0)
+ {
+ //CString s = "notepad ";
+ //s += q->shadername;
+ //WinExec(s, SW_SHOWNORMAL);
+
+ ViewShader(q->shadername, q->name);
+
+ }
+ }
+ memset (&tex, 0, sizeof(tex));
+ memset (&brushprimit_tex, 0, sizeof(brushprimit_tex));
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ // brushprimit fitted to a 2x2 texture
+ brushprimit_tex.coords[0][0] = 1.0f;
+ brushprimit_tex.coords[1][1] = 1.0f;
+ }
+ else
+ {
+ tex.scale[0] = (g_PrefsDlg.m_bHiColorTextures) ? 0.5 : 1;
+ tex.scale[1] = (g_PrefsDlg.m_bHiColorTextures) ? 0.5 : 1;
+ }
+ tex.flags = q->flags;
+ tex.value = q->value;
+ tex.contents = q->contents;
+ //strcpy (tex.name, q->name);
+ tex.SetName(q->name);
+ Texture_SetTexture ( &tex, &brushprimit_tex, bFitScale, GETPLUGINTEXDEF(q));
+ CString strTex;
+ CString strName = q->name;
+ //int nPos = strName.Find('\\');
+ //if (nPos == -1)
+ // nPos = strName.Find('/');
+ //if (nPos >= 0)
+ // strName = strName.Right(strName.GetLength() - nPos - 1);
+ strTex.Format("%s W: %i H: %i", strName.GetBuffer(0), q->width, q->height);
+ g_pParentWnd->SetStatusText(3, strTex);
+ return;
+ }
+ }
+
+ Sys_Status("Did not select a texture\n", 0);
+}
+
+/*
+==============
+Texture_MouseDown
+==============
+*/
+void Texture_MouseDown (int x, int y, int buttons)
+{
+ Sys_GetCursorPos (&textures_cursorx, &textures_cursory);
+
+ // lbutton = select texture
+ if (buttons == MK_LBUTTON || buttons == (MK_LBUTTON | MK_SHIFT) || buttons == (MK_LBUTTON | MK_CONTROL))
+ {
+ SelectTexture (x, g_qeglobals.d_texturewin.height - 1 - y, buttons & MK_SHIFT, buttons & MK_CONTROL);
+ UpdateSurfaceDialog();
+ UpdatePatchInspector();
+ }
+}
+
+/*
+==============
+Texture_MouseUp
+==============
+*/
+void Texture_MouseUp (int x, int y, int buttons)
+{
+}
+
+/*
+==============
+Texture_MouseMoved
+==============
+*/
+void Texture_MouseMoved (int x, int y, int buttons)
+{
+ int scale = 1;
+
+ if ( buttons & MK_SHIFT )
+ scale = 4;
+
+ // rbutton = drag texture origin
+ if (buttons & MK_RBUTTON)
+ {
+ Sys_GetCursorPos (&x, &y);
+ if ( y != textures_cursory)
+ {
+ g_qeglobals.d_texturewin.originy += ( y-textures_cursory) * scale;
+ if (g_qeglobals.d_texturewin.originy > 0)
+ g_qeglobals.d_texturewin.originy = 0;
+ Sys_SetCursorPos (textures_cursorx, textures_cursory);
+ CWnd *pWnd = CWnd::FromHandle(g_qeglobals.d_hwndTexture);
+ if (g_PrefsDlg.m_bTextureScrollbar && pWnd != NULL)
+ {
+ pWnd->SetScrollPos(SB_VERT, abs(g_qeglobals.d_texturewin.originy));
+ }
+ InvalidateRect(g_qeglobals.d_hwndTexture, NULL, false);
+ UpdateWindow (g_qeglobals.d_hwndTexture);
+ }
+ return;
+ }
+}
+
+
+/*
+============================================================================
+
+DRAWING
+
+============================================================================
+*/
+
+int imax(int iFloor, int i) { if (i>iFloor) return iFloor; return i; }
+HFONT ghFont = NULL;
+
+/*
+============
+Texture_Draw2
+============
+*/
+void Texture_Draw2 (int width, int height)
+{
+ qtexture_t *q;
+ int x, y;
+ char *name;
+
+ qglClearColor (
+ g_qeglobals.d_savedinfo.colors[COLOR_TEXTUREBACK][0],
+ g_qeglobals.d_savedinfo.colors[COLOR_TEXTUREBACK][1],
+ g_qeglobals.d_savedinfo.colors[COLOR_TEXTUREBACK][2],
+ 0);
+ qglViewport (0,0,width,height);
+ qglMatrixMode(GL_PROJECTION);
+ qglLoadIdentity ();
+
+ qglClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+ qglDisable (GL_DEPTH_TEST);
+ qglDisable(GL_BLEND);
+ qglOrtho (0, width, g_qeglobals.d_texturewin.originy-height, g_qeglobals.d_texturewin.originy, -100, 100);
+ qglEnable (GL_TEXTURE_2D);
+
+ qglPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
+ g_qeglobals.d_texturewin.width = width;
+ g_qeglobals.d_texturewin.height = height;
+ Texture_StartPos ();
+
+ while (1)
+ {
+ q = Texture_NextPos (&x, &y);
+ if (!q)
+ break;
+
+ int nWidth = (g_PrefsDlg.m_bHiColorTextures == TRUE) ? q->width * ((float)g_PrefsDlg.m_nTextureScale / 100) : q->width;
+ int nHeight = (g_PrefsDlg.m_bHiColorTextures == TRUE) ? q->height * ((float)g_PrefsDlg.m_nTextureScale / 100) : q->height;
+ // Is this texture visible?
+ if ( (y-nHeight-FONT_HEIGHT < g_qeglobals.d_texturewin.originy)
+ && (y > g_qeglobals.d_texturewin.originy - height) )
+ {
+
+ // if in use, draw a background
+ if ((q->inuse && !texture_showinuse) || q->bFromShader)
+ {
+ qglLineWidth (1);
+
+ if (q->bFromShader)
+ {
+ qglColor3f (1,1,1);
+ }
+ else
+ {
+ qglColor3f (0.5,1,0.5);
+ }
+ qglDisable (GL_TEXTURE_2D);
+
+ qglBegin (GL_LINE_LOOP);
+ qglVertex2f (x-1,y+1-FONT_HEIGHT);
+ qglVertex2f (x-1,y-nHeight-1-FONT_HEIGHT);
+ qglVertex2f (x+1+nWidth,y-nHeight-1-FONT_HEIGHT);
+ qglVertex2f (x+1+nWidth,y+1-FONT_HEIGHT);
+ qglEnd ();
+
+ qglEnable (GL_TEXTURE_2D);
+ }
+
+ // Draw the texture
+ float fScale = (g_PrefsDlg.m_bHiColorTextures == TRUE) ? ((float)g_PrefsDlg.m_nTextureScale / 100) : 1.0;
+
+ qglBindTexture( GL_TEXTURE_2D, q->texture_number );
+ QE_CheckOpenGLForErrors();
+ qglColor3f (1,1,1);
+ qglBegin (GL_QUADS);
+ qglTexCoord2f (0,0);
+ qglVertex2f (x,y-FONT_HEIGHT);
+ qglTexCoord2f (1,0);
+ qglVertex2f (x+nWidth,y-FONT_HEIGHT);
+ qglTexCoord2f (1,1);
+ qglVertex2f (x+nWidth,y-FONT_HEIGHT-nHeight);
+ qglTexCoord2f (0,1);
+ qglVertex2f (x,y-FONT_HEIGHT-nHeight);
+ qglEnd ();
+
+ // draw the selection border
+ if (!strcmpi(g_qeglobals.d_texturewin.texdef.name, q->name))
+ {
+ qglLineWidth (3);
+ qglColor3f (1,0,0);
+ qglDisable (GL_TEXTURE_2D);
+
+ qglBegin (GL_LINE_LOOP);
+ qglVertex2f (x-4,y-FONT_HEIGHT+4);
+ qglVertex2f (x-4,y-FONT_HEIGHT-nHeight-4);
+ qglVertex2f (x+4+nWidth,y-FONT_HEIGHT-nHeight-4);
+ qglVertex2f (x+4+nWidth,y-FONT_HEIGHT+4);
+ qglEnd ();
+
+ qglEnable (GL_TEXTURE_2D);
+ qglLineWidth (1);
+ }
+
+ // draw the texture name
+ qglColor3f (0,0,0);
+
+ qglRasterPos2f (x, y-FONT_HEIGHT+2);
+
+ // don't draw the directory name
+ for (name = q->name ; *name && *name != '/' && *name != '\\' ; name++)
+ ;
+ if (!*name)
+ name = q->name;
+ else
+ name++;
+
+ if (g_PrefsDlg.m_bHiColorTextures && q->shadername[0] != 0)
+ {
+ // slow as shit
+ CString s = "[";
+ s += name;
+ s += "]";
+ qglCallLists (s.GetLength(), GL_UNSIGNED_BYTE, s.GetBuffer(0));
+ }
+ else
+ {
+ qglCallLists (strlen(name), GL_UNSIGNED_BYTE, name);
+ }
+ }
+ }
+
+ g_qeglobals.d_texturewin.m_nTotalHeight = abs(y) + 100;
+ // reset the current texture
+ qglBindTexture( GL_TEXTURE_2D, 0 );
+ qglFinish();
+}
+
+
+void Texture_Init (bool bHardInit)
+{
+ char name[1024];
+ byte *pal = NULL;
+
+ if (g_PrefsDlg.m_bHiColorTextures == FALSE)
+ {
+ // load the palette
+ sprintf (name, "%s/pics/colormap.pcx", ValueForKey (g_qeglobals.d_project_entity, "basepath"));
+
+ Load256Image (name, NULL, &pal, NULL, NULL);
+ if (!pal)
+ {
+ // before dropping out, try to load it from the QERadiant directory
+ CString strFile = g_strAppPath;
+ AddSlash(strFile);
+ strFile += "colormap.pcx";
+ Load256Image (strFile.GetBuffer(0), NULL, &pal, NULL, NULL);
+ if (!pal)
+ Sys_Printf ("Couldn't load %s or %s", name, strFile);
+ }
+ else
+ {
+ Texture_InitPalette (pal);
+ free (pal);
+ }
+ }
+
+ // create the fallback texture
+
+ if (bHardInit)
+ {
+ Texture_MakeNotexture();
+ g_qeglobals.d_qtextures = NULL;
+ }
+ LoadShaders();
+
+}
+
+void Texture_FlushUnused()
+{
+ CWaitCursor cursor;
+ Texture_ShowInuse();
+ if (g_qeglobals.d_qtextures)
+ {
+ qtexture_t* pTex = g_qeglobals.d_qtextures->next;
+ qtexture_t *pPrev = g_qeglobals.d_qtextures;
+ while (pTex != NULL && pTex != g_qeglobals.d_qtextures)
+ {
+ qtexture_t* pNextTex = pTex->next;
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+ // Timo
+ // Surface properties plugin
+#ifdef _DEBUG
+ if ( !pTex->pData )
+ Sys_Printf("WARNING: found a qtexture_t* with no IPluginQTexture\n");
+#endif
+ if ( pTex->pData && pTex->inuse )
+ GETPLUGINTEXDEF(pTex)->DecRef();
+ }
+
+ if (!pTex->inuse)
+ {
+ unsigned int nTexture = pTex->texture_number;
+ qglDeleteTextures(1, &nTexture);
+ pPrev->next = pNextTex;
+ free(pTex);
+ }
+ else
+ {
+ pPrev = pTex;
+ }
+ pTex = pNextTex;
+ }
+ }
+}
+
+void Texture_Cleanup(CStringList *pList)
+{
+ if (g_qeglobals.d_qtextures)
+ {
+ qtexture_t* pTex = g_qeglobals.d_qtextures->next;
+ while (pTex != NULL && pTex != g_qeglobals.d_qtextures)
+ {
+ qtexture_t* pNextTex = pTex->next;
+ if (pList)
+ {
+ if (pTex->name[0] != '(')
+ {
+ pList->AddTail(pTex->name);
+ }
+ }
+
+ if (g_qeglobals.bSurfacePropertiesPlugin)
+ {
+ // Timo
+ // Surface properties plugin
+#ifdef _DEBUG
+ if ( !pTex->pData )
+ Sys_Printf("WARNING: found a qtexture_t* with no IPluginQTexture\n");
+#endif
+ if ( pTex->pData )
+ GETPLUGINTEXDEF(pTex)->DecRef();
+ }
+ free(pTex);
+ pTex = pNextTex;
+ }
+ }
+
+ int nSize = g_lstSkinCache.GetSize();
+ for (int i = 0; i < nSize; i++)
+ {
+ SkinInfo *pInfo = reinterpret_cast<SkinInfo*>(g_lstSkinCache.GetAt(i));
+ delete pInfo;
+ }
+
+}
+
+/*
+==================
+Texture_Flush
+==================
+*/
+void Texture_Flush (bool bReload)
+{
+ if (!ConfirmModified())
+ return;
+
+ Map_New ();
+
+ CWaitCursor cursor;
+ CStringList strList;
+ Texture_Init(false);
+ Texture_Cleanup(&strList);
+
+ GLuint* pGln = new GLuint[texture_extension_number-1];
+ qglGenTextures(texture_extension_number-1, pGln);
+ QE_CheckOpenGLForErrors();
+ qglDeleteTextures(texture_extension_number-1, pGln);
+ QE_CheckOpenGLForErrors();
+ delete []pGln;
+ texture_extension_number = 1;
+ g_qeglobals.d_qtextures = NULL;
+
+ if (bReload)
+ {
+ POSITION pos = strList.GetHeadPosition();
+ while (pos)
+ {
+ CString strTex = strList.GetNext(pos);
+ Texture_ForName (strTex.GetBuffer(0));
+ }
+ }
+
+}
+
+
+
+/////////////////////////////////////////////////////////////////////////////
+// CTexWnd
+IMPLEMENT_DYNCREATE(CTexWnd, CWnd);
+
+CTexWnd::CTexWnd()
+{
+ m_bNeedRange = true;
+}
+
+CTexWnd::~CTexWnd()
+{
+}
+
+
+BEGIN_MESSAGE_MAP(CTexWnd, CWnd)
+ //{{AFX_MSG_MAP(CTexWnd)
+ ON_WM_CREATE()
+ ON_WM_SIZE()
+ ON_WM_PARENTNOTIFY()
+ ON_WM_TIMER()
+ ON_WM_KEYDOWN()
+ ON_WM_KEYUP()
+ ON_WM_PAINT()
+ ON_WM_VSCROLL()
+ ON_COMMAND(ID_TEXTURES_FLUSH, OnTexturesFlush)
+ ON_BN_CLICKED(1200, OnShaderClick)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+
+/////////////////////////////////////////////////////////////////////////////
+// CTexWnd message handlers
+
+/*
+============
+WTexWndProc
+============
+*/
+LONG WINAPI TexWndProc (
+ HWND hWnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam)
+{
+ int xPos, yPos;
+ RECT rect;
+
+ GetClientRect(hWnd, &rect);
+
+ switch (uMsg)
+ {
+ case WM_CREATE:
+ s_hdcTexture = GetDC(hWnd);
+ QEW_SetupPixelFormat(s_hdcTexture, false);
+
+ if ( ( s_hglrcTexture = qwglCreateContext( s_hdcTexture ) ) == 0 )
+ Error( "wglCreateContext in WTex_WndProc failed" );
+
+ if (!qwglShareLists( g_qeglobals.d_hglrcBase, s_hglrcTexture ) )
+ Error( "wglShareLists in WTex_WndProc failed" );
+
+ if (!qwglMakeCurrent( s_hdcTexture, s_hglrcTexture ))
+ Error ("wglMakeCurrent in WTex_WndProc failed");
+
+ g_qeglobals.d_hwndTexture = hWnd;
+ return 0;
+
+ case WM_DESTROY:
+ //wglMakeCurrent( NULL, NULL );
+ //wglDeleteContext( s_hglrcTexture );
+ ReleaseDC( hWnd, s_hdcTexture );
+ return 0;
+#if 0
+ case WM_PAINT:
+ {
+ PAINTSTRUCT ps;
+
+ BeginPaint(hWnd, &ps);
+
+ if ( !qwglMakeCurrent( s_hdcTexture, s_hglrcTexture ) )
+ //if ( !wglMakeCurrent( ps.hdc, s_hglrcTexture ) )
+ {
+ Sys_Printf("ERROR: wglMakeCurrent failed..\n ");
+ Sys_Printf("Please restart Q3Radiant if the Texture view is not working\n");
+ }
+ else
+ {
+ Texture_Draw2 (rect.right-rect.left, rect.bottom-rect.top - g_nTextureOffset);
+ qwglSwapBuffers(s_hdcTexture);
+ TRACE("Texture Paint\n");
+ }
+ EndPaint(hWnd, &ps);
+ }
+ return 0;
+#endif
+ case WM_MBUTTONDOWN:
+ case WM_RBUTTONDOWN:
+ case WM_LBUTTONDOWN:
+ SetCapture( g_qeglobals.d_hwndTexture );
+ xPos = (short)LOWORD(lParam); // horizontal position of cursor
+ yPos = (short)HIWORD(lParam); // vertical position of cursor
+
+ Texture_MouseDown (xPos, yPos - g_nTextureOffset, wParam);
+ return 0;
+
+ case WM_MBUTTONUP:
+ case WM_RBUTTONUP:
+ case WM_LBUTTONUP:
+ xPos = (short)LOWORD(lParam); // horizontal position of cursor
+ yPos = (short)HIWORD(lParam); // vertical position of cursor
+
+ Texture_MouseUp (xPos, yPos - g_nTextureOffset, wParam);
+ if (! (wParam & (MK_LBUTTON|MK_RBUTTON|MK_MBUTTON)))
+ ReleaseCapture ();
+ return 0;
+
+ case WM_MOUSEMOVE:
+ xPos = (short)LOWORD(lParam); // horizontal position of cursor
+ yPos = (short)HIWORD(lParam); // vertical position of cursor
+
+ Texture_MouseMoved (xPos, yPos - g_nTextureOffset, wParam);
+ return 0;
+ }
+
+ return DefWindowProc (hWnd, uMsg, wParam, lParam);
+}
+
+
+
+BOOL CTexWnd::PreCreateWindow(CREATESTRUCT& cs)
+{
+ WNDCLASS wc;
+ HINSTANCE hInstance = AfxGetInstanceHandle();
+ if (::GetClassInfo(hInstance, TEXTURE_WINDOW_CLASS, &wc) == FALSE)
+ {
+ // Register a new class
+ memset (&wc, 0, sizeof(wc));
+ wc.style = CS_NOCLOSE | CS_OWNDC;
+ wc.lpszClassName = TEXTURE_WINDOW_CLASS;
+ wc.hCursor = LoadCursor (NULL,IDC_ARROW);
+ wc.lpfnWndProc = TexWndProc;
+ if (AfxRegisterClass(&wc) == FALSE)
+ Error ("CZWnd RegisterClass: failed");
+ }
+
+ cs.lpszClass = TEXTURE_WINDOW_CLASS;
+ cs.lpszName = "TEX";
+ if (cs.style != QE3_CHILDSTYLE && cs.style != QE3_STYLE)
+ cs.style = QE3_SPLITTER_STYLE;
+
+ return CWnd::PreCreateWindow(cs);
+}
+
+int CTexWnd::OnCreate(LPCREATESTRUCT lpCreateStruct)
+{
+ if (CWnd::OnCreate(lpCreateStruct) == -1)
+ return -1;
+
+ CRect rctEdit(8, 5, 20, 20);
+ g_nTextureOffset = 0;
+
+/*
+ if (g_PrefsDlg.m_bShaderTest)
+ {
+ m_wndShaders.Create("Show Shaders", WS_CHILD | WS_VISIBLE | BS_AUTOCHECKBOX, rctEdit, this, 1200);
+ m_wndShaders.ModifyStyleEx(0, WS_EX_CLIENTEDGE, 0);
+ m_wndShaders.SetCheck(g_PrefsDlg.m_bShowShaders);
+ g_nTextureOffset = 25;
+ }
+*/
+ rctEdit.SetRect(8, g_nTextureOffset, 20, 20);
+ m_wndFilter.Create(WS_CHILD | WS_VISIBLE | ES_AUTOHSCROLL | ES_LEFT, rctEdit, this, 1201);
+ m_wndFilter.ModifyStyleEx(0, WS_EX_CLIENTEDGE, 0);
+ m_wndFilter.SetTexWnd(this);
+
+ g_nTextureOffset += 25;
+ if (!g_PrefsDlg.m_bTextureWindow)
+ {
+ m_wndFilter.ShowWindow(SW_HIDE);
+ g_nTextureOffset -= 25;
+ }
+
+ ShowScrollBar(SB_VERT, g_PrefsDlg.m_bTextureScrollbar);
+ m_bNeedRange = true;
+
+ return 0;
+}
+
+void CTexWnd::OnSize(UINT nType, int cx, int cy)
+{
+ CWnd::OnSize(nType, cx, cy);
+ CRect rctClient;
+ GetClientRect(rctClient);
+/*
+ if (g_PrefsDlg.m_bShaderTest && m_wndShaders.GetSafeHwnd())
+ {
+ m_wndShaders.SetWindowPos(NULL, rctClient.left + 8, rctClient.top + 5, rctClient.right - 16, 20, 0);
+ }
+*/
+ m_wndFilter.SetWindowPos(NULL, rctClient.left + 8, rctClient.top + 25, rctClient.right - 16, 20, 0);
+ m_bNeedRange = true;
+}
+
+void CTexWnd::OnShaderClick()
+{
+ g_PrefsDlg.m_bShowShaders = (m_wndShaders.GetCheck() != 0);
+ g_PrefsDlg.SavePrefs();
+ RedrawWindow();
+}
+
+void CTexWnd::OnParentNotify(UINT message, LPARAM lParam)
+{
+ CWnd::OnParentNotify(message, lParam);
+}
+
+int g_nLastLen = 0;
+int g_nTimerHandle = -1;
+char g_cLastChar;
+
+void CTexWnd::UpdateFilter(const char* pFilter)
+{
+ if (g_nTimerHandle > 0)
+ KillTimer(1);
+ g_bFilterEnabled = false;
+ if (pFilter)
+ {
+ g_strFilter = pFilter;
+ if (g_strFilter.GetLength() > 0)
+ {
+ g_bFilterEnabled = true;
+ if (g_pParentWnd->CurrentStyle() == QR_QE4 || g_pParentWnd->CurrentStyle() == QR_4WAY)
+ {
+ if (g_strFilter.GetLength() > g_nLastLen)
+ {
+ g_cLastChar = toupper(g_strFilter.GetAt(g_strFilter.GetLength()-1));
+ if (g_cLastChar == 'N' || g_cLastChar == 'O') // one of the other popups
+ {
+ g_nTimerHandle = SetTimer(1, 800, NULL); // half second timer
+ }
+ }
+ }
+ }
+ g_nLastLen = g_strFilter.GetLength();
+ SortTextures();
+ }
+ Sys_UpdateWindows (W_TEXTURE);
+}
+
+void CTexWnd::UpdatePrefs()
+{
+ if (!g_PrefsDlg.m_bTextureWindow)
+ {
+ m_wndFilter.ShowWindow(SW_HIDE);
+ g_nTextureOffset = 0;
+ }
+ else
+ {
+ m_wndFilter.ShowWindow(SW_SHOW);
+ g_nTextureOffset = 25;
+ }
+ ShowScrollBar(SB_VERT, g_PrefsDlg.m_bTextureScrollbar);
+ m_bNeedRange = true;
+ Invalidate();
+ UpdateWindow();
+}
+
+void CTexWnd::FocusEdit()
+{
+ if (m_wndFilter.IsWindowVisible())
+ m_wndFilter.SetFocus();
+}
+
+void CTexWnd::OnTimer(UINT nIDEvent)
+{
+ KillTimer(1);
+ g_nLastLen = 0;
+ g_nTimerHandle = -1;
+ ::SetFocus(g_qeglobals.d_hwndEntity);
+ ::PostMessage(g_qeglobals.d_hwndEntity, WM_CHAR, g_cLastChar, 0);
+}
+
+void CTexWnd::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
+{
+ g_pParentWnd->HandleKey(nChar, nRepCnt, nFlags);
+ //CWnd::OnKeyDown(nChar, nRepCnt, nFlags);
+}
+
+void CTexWnd::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags)
+{
+ g_pParentWnd->HandleKey(nChar, nRepCnt, nFlags, false);
+}
+
+void CTexWnd::OnPaint()
+{
+ CPaintDC dc(this); // device context for painting
+ CRect rctClient;
+ GetClientRect(rctClient);
+ int nOld = g_qeglobals.d_texturewin.m_nTotalHeight;
+ if (!qwglMakeCurrent(s_hdcTexture, s_hglrcTexture))
+ //if ( !qwglMakeCurrent(dc.m_hDC, s_hglrcTexture ) )
+ {
+ Sys_Printf("ERROR: wglMakeCurrent failed..\n ");
+ Sys_Printf("Please restart Q3Radiant if the Texture view is not working\n");
+ }
+ else
+ {
+ Texture_Draw2 (rctClient.right-rctClient.left, rctClient.bottom-rctClient.top - g_nTextureOffset);
+ qwglSwapBuffers(s_hdcTexture);
+ TRACE("Texture Paint\n");
+ }
+ if (g_PrefsDlg.m_bTextureScrollbar && (m_bNeedRange || g_qeglobals.d_texturewin.m_nTotalHeight != nOld))
+ {
+ m_bNeedRange = false;
+ SetScrollRange(SB_VERT, 0, g_qeglobals.d_texturewin.m_nTotalHeight, TRUE);
+ }
+}
+
+void CTexWnd::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
+{
+ CWnd::OnVScroll(nSBCode, nPos, pScrollBar);
+
+ int n = GetScrollPos(SB_VERT);;
+ switch (nSBCode)
+ {
+ case SB_LINEUP :
+ {
+ n = (n - 15 > 0) ? n - 15 : 0;
+ break;
+ }
+ case SB_LINEDOWN :
+ {
+ n = (n + 15 < g_qeglobals.d_texturewin.m_nTotalHeight) ? n + 15 : n;
+ break;
+ }
+ case SB_PAGEUP :
+ {
+ n = (n - g_qeglobals.d_texturewin.height > 0) ? n - g_qeglobals.d_texturewin.height : 0;
+ break;
+ }
+ case SB_PAGEDOWN :
+ {
+ n = (n + g_qeglobals.d_texturewin.height < g_qeglobals.d_texturewin.m_nTotalHeight) ? n + g_qeglobals.d_texturewin.height : n;
+ break;
+ }
+ case SB_THUMBPOSITION :
+ {
+ n = nPos;
+ break;
+ }
+ case SB_THUMBTRACK :
+ {
+ n = nPos;
+ break;
+ }
+ }
+ SetScrollPos(SB_VERT, n);
+ g_qeglobals.d_texturewin.originy = -((int)n);
+ Invalidate();
+ UpdateWindow();
+ //Sys_UpdateWindows(W_TEXTURE);
+}
+
+/*
+and are the caps new caps? anything done with older stuff will be fubar'd.. which brings up the point if you ever naturalize a cap, you cannot force it back to cap texturing.. i will add that too
+*/
+
+void CTexWnd::OnTexturesFlush()
+{
+ // TODO: Add your command handler code here
+
+}
+
+void LoadShaders()
+{
+ char dirstring[1024];
+ char *path;
+ //struct _finddata_t fileinfo;
+ //int handle;
+ path = ValueForKey (g_qeglobals.d_project_entity, "basepath");
+ sprintf (dirstring, "%s/scripts/shaderlist.txt", path);
+ char *pBuff = NULL;
+
+ int nLen = LoadFile(dirstring, reinterpret_cast<void**>(&pBuff));
+ if (nLen == -1)
+ {
+ nLen = PakLoadAnyFile(dirstring, reinterpret_cast<void**>(&pBuff));
+ }
+ if (nLen > 0)
+ {
+ CStringList lst;
+ StartTokenParsing(pBuff);
+ nLen = 0;
+ while (GetToken(true))
+ {
+ // each token should be a shader filename
+ sprintf(dirstring, "%s/scripts/%s.shader", path, token);
+ lst.AddTail(dirstring);
+ nLen++;
+ }
+ POSITION pos = lst.GetHeadPosition();
+ while (pos != NULL)
+ {
+ LoadShader(lst.GetAt(pos).GetBuffer(0), NULL);
+ lst.GetNext(pos);
+ }
+ free(pBuff);
+ }
+ else
+ {
+ Sys_Printf("Unable to load shaderlist.txt, shaders not loaded!");
+ }
+
+/*
+ handle = _findfirst (dirstring, &fileinfo);
+ if (handle != -1)
+ {
+ do
+ {
+ if ((fileinfo.attrib & _A_SUBDIR))
+ continue;
+ sprintf(dirstring, "%s/scripts/%s", path, fileinfo.name);
+ LoadShader(dirstring, NULL);
+ } while (_findnext( handle, &fileinfo ) != -1);
+
+ _findclose (handle);
+ }
+*/
+}
+
+void FreeShaders()
+{
+ int nSize = g_lstShaders.GetSize();
+ for (int i = 0; i < nSize; i++)
+ {
+ CShaderInfo *pInfo = reinterpret_cast<CShaderInfo*>(g_lstShaders.ElementAt(i));
+ delete pInfo;
+ }
+
+ g_lstShaders.RemoveAll();
+}
+
+void ReloadShaders()
+{
+ FreeShaders();
+ LoadShaders();
+ qtexture_t* pTex = g_qeglobals.d_qtextures;
+ while (pTex != NULL)
+ {
+ SetNameShaderInfo(pTex, NULL, pTex->name);
+ pTex = pTex->next;
+ }
+
+}
+
+int WINAPI Texture_LoadSkin(char *pName, int *pnWidth, int *pnHeight)
+{
+ byte *pic = NULL;
+ byte *pic32 = NULL;
+ int nTex = -1;
+
+ strlwr(pName);
+ QE_ConvertDOSToUnixName(pName, pName);
+
+ int nSize = g_lstSkinCache.GetSize();
+ for (int i = 0; i < nSize; i++)
+ {
+ SkinInfo *pInfo = reinterpret_cast<SkinInfo*>(g_lstSkinCache.GetAt(i));
+ if (pInfo)
+ {
+ if (stricmp(pName, pInfo->m_strName) == 0)
+ {
+ return pInfo->m_nTextureBind;
+ }
+ }
+ }
+
+ LoadImage( pName, &pic32, pnWidth, pnHeight);
+ if (pic32 != NULL)
+ {
+
+ nTex = texture_extension_number++;
+ if (g_PrefsDlg.m_bSGIOpenGL)
+ {
+ //if (!qwglMakeCurrent(g_qeglobals.d_hdcBase, g_qeglobals.d_hglrcBase))
+ if (!qwglMakeCurrent(s_hdcTexture, s_hglrcTexture))
+ Error ("wglMakeCurrent in LoadTexture failed");
+ }
+
+ qglBindTexture( GL_TEXTURE_2D, nTex);
+ SetTexParameters ();
+
+ int nCount = MAX_TEXTURE_QUALITY - g_PrefsDlg.m_nTextureQuality;
+ while (nCount-- > 0)
+ {
+ if (*pnWidth > 16 && *pnHeight > 16)
+ {
+ R_MipMap(pic32, *pnWidth, *pnHeight);
+ }
+ else
+ {
+ break;
+ }
+ }
+
+ if (g_PrefsDlg.m_bSGIOpenGL)
+ {
+ if (nomips)
+ {
+ qglTexImage2D(GL_TEXTURE_2D, 0, 3, *pnWidth, *pnHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, pic32);
+ }
+ else
+ qgluBuild2DMipmaps(GL_TEXTURE_2D, 3, *pnWidth, *pnHeight,GL_RGBA, GL_UNSIGNED_BYTE, pic32);
+ }
+ else
+ {
+ if (nomips)
+ qglTexImage2D(GL_TEXTURE_2D, 0, 3, *pnWidth, *pnHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, pic32);
+ else
+ qgluBuild2DMipmaps(GL_TEXTURE_2D, 3, *pnWidth, *pnHeight,GL_RGBA, GL_UNSIGNED_BYTE, pic32);
+ }
+ free (pic32);
+ qglBindTexture( GL_TEXTURE_2D, 0 );
+ }
+
+ SkinInfo *pInfo = new SkinInfo(pName, nTex);
+ g_lstSkinCache.Add(pInfo);
+
+ return nTex;
+}
+
+
diff --git a/q3radiant/TexWnd.h b/q3radiant/TexWnd.h
new file mode 100755
index 0000000..c98fd66
--- /dev/null
+++ b/q3radiant/TexWnd.h
@@ -0,0 +1,88 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_TEXWND_H__44B4BA05_781B_11D1_B53C_00AA00A410FC__INCLUDED_)
+#define AFX_TEXWND_H__44B4BA05_781B_11D1_B53C_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// TexWnd.h : header file
+//
+#include "texedit.h"
+
+/////////////////////////////////////////////////////////////////////////////
+// CTexWnd window
+
+class CTexWnd : public CWnd
+{
+ DECLARE_DYNCREATE(CTexWnd);
+// Construction
+public:
+ CTexWnd();
+ void UpdateFilter(const char* pFilter);
+ void UpdatePrefs();
+ void FocusEdit();
+
+// Attributes
+public:
+
+// Operations
+public:
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CTexWnd)
+ protected:
+ virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
+ //}}AFX_VIRTUAL
+
+// Implementation
+public:
+ virtual ~CTexWnd();
+
+protected:
+ CTexEdit m_wndFilter;
+ CButton m_wndShaders;
+ bool m_bNeedRange;
+ // Generated message map functions
+protected:
+ //{{AFX_MSG(CTexWnd)
+ afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
+ afx_msg void OnSize(UINT nType, int cx, int cy);
+ afx_msg void OnParentNotify(UINT message, LPARAM lParam);
+ afx_msg void OnTimer(UINT nIDEvent);
+ afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
+ afx_msg void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags);
+ afx_msg void OnPaint();
+ afx_msg void OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
+ afx_msg void OnTexturesFlush();
+ //}}AFX_MSG
+ afx_msg void OnShaderClick();
+ DECLARE_MESSAGE_MAP()
+};
+
+/////////////////////////////////////////////////////////////////////////////
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_TEXWND_H__44B4BA05_781B_11D1_B53C_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/TextureBar.cpp b/q3radiant/TextureBar.cpp
new file mode 100755
index 0000000..4a48e26
--- /dev/null
+++ b/q3radiant/TextureBar.cpp
@@ -0,0 +1,208 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//++timo TODO : the whole CTextureBar has to be modified for the new texture code
+
+// TextureBar.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "TextureBar.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CTextureBar dialog
+
+
+CTextureBar::CTextureBar()
+ : CDialogBar()
+{
+ //{{AFX_DATA_INIT(CTextureBar)
+ m_nHShift = 0;
+ m_nHScale = 0;
+ m_nRotate = 0;
+ m_nVShift = 0;
+ m_nVScale = 0;
+ m_nRotateAmt = 45;
+ //}}AFX_DATA_INIT
+}
+
+
+void CTextureBar::DoDataExchange(CDataExchange* pDX)
+{
+ CDialogBar::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CTextureBar)
+ DDX_Control(pDX, IDC_SPIN_ROTATE, m_spinRotate);
+ DDX_Control(pDX, IDC_SPIN_VSCALE, m_spinVScale);
+ DDX_Control(pDX, IDC_SPIN_VSHIFT, m_spinVShift);
+ DDX_Control(pDX, IDC_SPIN_HSCALE, m_spinHScale);
+ DDX_Control(pDX, IDC_SPIN_HSHIFT, m_spinHShift);
+ DDX_Text(pDX, IDC_HSHIFT, m_nHShift);
+ DDX_Text(pDX, IDC_HSCALE, m_nHScale);
+ DDX_Text(pDX, IDC_ROTATE, m_nRotate);
+ DDX_Text(pDX, IDC_VSHIFT, m_nVShift);
+ DDX_Text(pDX, IDC_VSCALE, m_nVScale);
+ DDX_Text(pDX, IDC_EDIT_ROTATEAMT, m_nRotateAmt);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CTextureBar, CDialogBar)
+ //{{AFX_MSG_MAP(CTextureBar)
+ ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN_HSHIFT, OnDeltaposSpinHshift)
+ ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN_VSHIFT, OnDeltaposSpinVshift)
+ ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN_HSCALE, OnDeltaposSpinHScale)
+ ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN_VSCALE, OnDeltaposSpinVScale)
+ ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN_ROTATE, OnDeltaposSpinRotate)
+ ON_COMMAND(ID_SELECTION_PRINT, OnSelectionPrint)
+ ON_WM_CREATE()
+ ON_BN_CLICKED(IDC_BTN_APPLYTEXTURESTUFF, OnBtnApplytexturestuff)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CTextureBar message handlers
+
+void CTextureBar::OnDeltaposSpinHshift(NMHDR* pNMHDR, LRESULT* pResult)
+{
+ NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
+ *pResult = 0;
+
+ if (pNMUpDown->iDelta < 0)
+ Select_ShiftTexture(abs(g_qeglobals.d_savedinfo.m_nTextureTweak), 0);
+ else
+ Select_ShiftTexture(-abs(g_qeglobals.d_savedinfo.m_nTextureTweak), 0);
+ GetSurfaceAttributes();
+}
+
+void CTextureBar::OnDeltaposSpinVshift(NMHDR* pNMHDR, LRESULT* pResult)
+{
+ NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
+ // TODO: Add your control notification handler code here
+
+ *pResult = 0;
+ if (pNMUpDown->iDelta < 0)
+ Select_ShiftTexture(0, abs(g_qeglobals.d_savedinfo.m_nTextureTweak));
+ else
+ Select_ShiftTexture(0, -abs(g_qeglobals.d_savedinfo.m_nTextureTweak));
+ GetSurfaceAttributes();
+}
+
+void CTextureBar::OnDeltaposSpinHScale(NMHDR* pNMHDR, LRESULT* pResult)
+{
+ NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
+ // TODO: Add your control notification handler code here
+
+ *pResult = 0;
+ if (pNMUpDown->iDelta < 0)
+ Select_ScaleTexture(abs(g_qeglobals.d_savedinfo.m_nTextureTweak),0);
+ else
+ Select_ScaleTexture(-abs(g_qeglobals.d_savedinfo.m_nTextureTweak),0);
+ GetSurfaceAttributes();
+}
+
+void CTextureBar::OnDeltaposSpinVScale(NMHDR* pNMHDR, LRESULT* pResult)
+{
+ NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
+ // TODO: Add your control notification handler code here
+
+ *pResult = 0;
+ if (pNMUpDown->iDelta < 0)
+ Select_ScaleTexture(0, abs(g_qeglobals.d_savedinfo.m_nTextureTweak));
+ else
+ Select_ScaleTexture(0, -abs(g_qeglobals.d_savedinfo.m_nTextureTweak));
+ GetSurfaceAttributes();
+}
+
+void CTextureBar::OnDeltaposSpinRotate(NMHDR* pNMHDR, LRESULT* pResult)
+{
+ NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
+ *pResult = 0;
+ UpdateData(TRUE);
+ if (pNMUpDown->iDelta < 0)
+ Select_RotateTexture(abs(m_nRotateAmt));
+ else
+ Select_RotateTexture(-abs(m_nRotateAmt));
+ GetSurfaceAttributes();
+}
+
+
+void CTextureBar::OnSelectionPrint()
+{
+ // TODO: Add your command handler code here
+
+}
+
+int CTextureBar::OnCreate(LPCREATESTRUCT lpCreateStruct)
+{
+ if (CDialogBar::OnCreate(lpCreateStruct) == -1)
+ return -1;
+ return 0;
+}
+
+
+void CTextureBar::OnBtnApplytexturestuff()
+{
+ SetSurfaceAttributes();
+}
+
+void CTextureBar::GetSurfaceAttributes()
+{
+ texdef_t* pt = (g_ptrSelectedFaces.GetSize() > 0) ? &(reinterpret_cast<face_t*>(g_ptrSelectedFaces.GetAt(0)))->texdef : &g_qeglobals.d_texturewin.texdef;
+
+ if (pt)
+ {
+ m_nHShift = pt->shift[0];
+ m_nVShift = pt->shift[1];
+ m_nHScale = pt->scale[0];
+ m_nVScale = pt->scale[1];
+ m_nRotate = pt->rotate;
+ UpdateData(FALSE);
+ }
+}
+
+//++timo implement brush primitive here
+void CTextureBar::SetSurfaceAttributes()
+{
+ if (g_ptrSelectedFaces.GetSize() > 0)
+ {
+ if (g_qeglobals.m_bBrushPrimitMode)
+ {
+ Sys_Printf("Warning : brush primitive mode not implemented in CTextureBar");
+ }
+ face_t *selFace = reinterpret_cast<face_t*>(g_ptrSelectedFaces.GetAt(0));
+
+ texdef_t* pt = &selFace->texdef;
+ UpdateData(TRUE);
+ pt->shift[0] = m_nHShift;
+ pt->shift[1] = m_nVShift;
+ pt->scale[0] = m_nHScale;
+ pt->scale[1] = m_nVScale;
+ pt->rotate = m_nRotate;
+ Sys_UpdateWindows(W_CAMERA);
+ }
+}
diff --git a/q3radiant/TextureBar.h b/q3radiant/TextureBar.h
new file mode 100755
index 0000000..aca4229
--- /dev/null
+++ b/q3radiant/TextureBar.h
@@ -0,0 +1,85 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_TEXTUREBAR_H__86220273_B656_11D1_B59F_00AA00A410FC__INCLUDED_)
+#define AFX_TEXTUREBAR_H__86220273_B656_11D1_B59F_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// TextureBar.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CTextureBar dialog
+
+class CTextureBar : public CDialogBar
+{
+// Construction
+public:
+ void GetSurfaceAttributes();
+ void SetSurfaceAttributes();
+ CTextureBar();
+
+// Dialog Data
+ //{{AFX_DATA(CTextureBar)
+ enum { IDD = IDD_TEXTUREBAR };
+ CSpinButtonCtrl m_spinRotate;
+ CSpinButtonCtrl m_spinVScale;
+ CSpinButtonCtrl m_spinVShift;
+ CSpinButtonCtrl m_spinHScale;
+ CSpinButtonCtrl m_spinHShift;
+ int m_nHShift;
+ int m_nHScale;
+ int m_nRotate;
+ int m_nVShift;
+ int m_nVScale;
+ int m_nRotateAmt;
+ //}}AFX_DATA
+
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CTextureBar)
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+ // Generated message map functions
+ //{{AFX_MSG(CTextureBar)
+ afx_msg void OnDeltaposSpinHshift(NMHDR* pNMHDR, LRESULT* pResult);
+ afx_msg void OnDeltaposSpinVshift(NMHDR* pNMHDR, LRESULT* pResult);
+ afx_msg void OnDeltaposSpinHScale(NMHDR* pNMHDR, LRESULT* pResult);
+ afx_msg void OnDeltaposSpinVScale(NMHDR* pNMHDR, LRESULT* pResult);
+ afx_msg void OnDeltaposSpinRotate(NMHDR* pNMHDR, LRESULT* pResult);
+ afx_msg void OnSelectionPrint();
+ afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
+ afx_msg void OnBtnApplytexturestuff();
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_TEXTUREBAR_H__86220273_B656_11D1_B59F_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/TextureLayout.cpp b/q3radiant/TextureLayout.cpp
new file mode 100755
index 0000000..80d6f92
--- /dev/null
+++ b/q3radiant/TextureLayout.cpp
@@ -0,0 +1,80 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// TextureLayout.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "TextureLayout.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CTextureLayout dialog
+
+
+CTextureLayout::CTextureLayout(CWnd* pParent /*=NULL*/)
+ : CDialog(CTextureLayout::IDD, pParent)
+{
+ //{{AFX_DATA_INIT(CTextureLayout)
+ m_fX = 4.0f;
+ m_fY = 4.0f;
+ //}}AFX_DATA_INIT
+}
+
+
+void CTextureLayout::DoDataExchange(CDataExchange* pDX)
+{
+ CDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CTextureLayout)
+ DDX_Text(pDX, IDC_EDIT_X, m_fX);
+ DDX_Text(pDX, IDC_EDIT_Y, m_fY);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CTextureLayout, CDialog)
+ //{{AFX_MSG_MAP(CTextureLayout)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CTextureLayout message handlers
+
+void CTextureLayout::OnOK()
+{
+ CDialog::OnOK();
+}
+
+BOOL CTextureLayout::OnInitDialog()
+{
+ CDialog::OnInitDialog();
+
+ // TODO: Add extra initialization here
+
+ return TRUE; // return TRUE unless you set the focus to a control
+ // EXCEPTION: OCX Property Pages should return FALSE
+}
diff --git a/q3radiant/TextureLayout.h b/q3radiant/TextureLayout.h
new file mode 100755
index 0000000..aad4444
--- /dev/null
+++ b/q3radiant/TextureLayout.h
@@ -0,0 +1,69 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_TEXTURELAYOUT_H__5EA4C722_173F_11D2_B024_00AA00A410FC__INCLUDED_)
+#define AFX_TEXTURELAYOUT_H__5EA4C722_173F_11D2_B024_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// TextureLayout.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CTextureLayout dialog
+
+class CTextureLayout : public CDialog
+{
+// Construction
+public:
+ CTextureLayout(CWnd* pParent = NULL); // standard constructor
+
+// Dialog Data
+ //{{AFX_DATA(CTextureLayout)
+ enum { IDD = IDD_DIALOG_TEXTURELAYOUT };
+ float m_fX;
+ float m_fY;
+ //}}AFX_DATA
+
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CTextureLayout)
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+
+ // Generated message map functions
+ //{{AFX_MSG(CTextureLayout)
+ virtual void OnOK();
+ virtual BOOL OnInitDialog();
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_TEXTURELAYOUT_H__5EA4C722_173F_11D2_B024_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/TextureLoad.cpp b/q3radiant/TextureLoad.cpp
new file mode 100755
index 0000000..f9bc938
--- /dev/null
+++ b/q3radiant/TextureLoad.cpp
@@ -0,0 +1,80 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// TextureLoad.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "TextureLoad.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CTextureLoad dialog
+
+
+CTextureLoad::CTextureLoad(CWnd* pParent /*=NULL*/)
+ : CDialog(CTextureLoad::IDD, pParent)
+{
+ //{{AFX_DATA_INIT(CTextureLoad)
+ // NOTE: the ClassWizard will add member initialization here
+ //}}AFX_DATA_INIT
+}
+
+
+void CTextureLoad::DoDataExchange(CDataExchange* pDX)
+{
+ CDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CTextureLoad)
+ DDX_Control(pDX, IDC_LIST_TEXTURES, m_wndList);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CTextureLoad, CDialog)
+ //{{AFX_MSG_MAP(CTextureLoad)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CTextureLoad message handlers
+
+BOOL CTextureLoad::OnInitDialog()
+{
+ CDialog::OnInitDialog();
+
+
+
+ return TRUE; // return TRUE unless you set the focus to a control
+ // EXCEPTION: OCX Property Pages should return FALSE
+}
+
+void CTextureLoad::OnOK()
+{
+ // TODO: Add extra validation here
+
+ CDialog::OnOK();
+}
diff --git a/q3radiant/TextureLoad.h b/q3radiant/TextureLoad.h
new file mode 100755
index 0000000..aff337b
--- /dev/null
+++ b/q3radiant/TextureLoad.h
@@ -0,0 +1,68 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_TEXTURELOAD_H__E53749E6_AAE3_47B8_B909_84C7982E35C9__INCLUDED_)
+#define AFX_TEXTURELOAD_H__E53749E6_AAE3_47B8_B909_84C7982E35C9__INCLUDED_
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+// TextureLoad.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CTextureLoad dialog
+
+class CTextureLoad : public CDialog
+{
+// Construction
+public:
+ CTextureLoad(CWnd* pParent = NULL); // standard constructor
+
+// Dialog Data
+ //{{AFX_DATA(CTextureLoad)
+ enum { IDD = IDD_TEXLIST };
+ CListBox m_wndList;
+ //}}AFX_DATA
+
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CTextureLoad)
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+
+ // Generated message map functions
+ //{{AFX_MSG(CTextureLoad)
+ virtual BOOL OnInitDialog();
+ virtual void OnOK();
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_TEXTURELOAD_H__E53749E6_AAE3_47B8_B909_84C7982E35C9__INCLUDED_)
diff --git a/q3radiant/Textures.h b/q3radiant/Textures.h
new file mode 100755
index 0000000..47a78a5
--- /dev/null
+++ b/q3radiant/Textures.h
@@ -0,0 +1,96 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+//--typedef struct texdef_s
+//--{
+//-- char name[32];
+//-- float shift[2];
+//-- float rotate;
+//-- float scale[2];
+//-- int contents;
+//-- int flags;
+//-- int value;
+//--} texdef_t;
+//--
+//--typedef struct
+//--{
+//-- int width, height;
+//-- int originy;
+//-- texdef_t texdef;
+//-- int m_nTotalHeight;
+//--} texturewin_t;
+//--
+//--#define QER_TRANS 0x00000001
+//--#define QER_NOCARVE 0x00000002
+//--
+//--typedef struct qtexture_s
+//--{
+//-- struct qtexture_s *next;
+//-- char name[64]; // includes partial directory and extension
+//-- int width, height;
+//-- int contents;
+//-- int flags;
+//-- int value;
+//-- int texture_number; // gl bind number
+//--
+//-- char shadername[1024]; // old shader stuff
+//-- qboolean bFromShader; // created from a shader
+//-- float fTrans; // amount of transparency
+//-- int nShaderFlags; // qer_ shader flags
+//-- vec3_t color; // for flat shade mode
+//-- qboolean inuse; // true = is present on the level
+//--} qtexture_t;
+//--
+
+// a texturename of the form (0 0 0) will
+// create a solid color texture
+
+void Texture_Init (bool bHardInit = true);
+void Texture_FlushUnused ();
+void Texture_Flush (bool bReload = false);
+void Texture_ClearInuse (void);
+void Texture_ShowInuse (void);
+void Texture_ShowDirectory (int menunum, bool bLinked = false);
+void Texture_ShowAll();
+void Texture_Cleanup(CStringList *pList = NULL);
+
+// TTimo: added bNoAlpha flag to ignore alpha channel when parsing a .TGA file, transparency is usually achieved through qer_trans keyword in shaders
+// in some cases loading an empty alpha channel causes display bugs (brushes not seen)
+qtexture_t *Texture_ForName (const char *name, bool bReplace = false, bool bShader = false, bool bNoAlpha = false, bool bReload = false, bool makeShader = true);
+
+void Texture_Init (void);
+// Timo
+// added an optional IPluginTexdef when one is available
+// we need a forward declaration, this is crap
+class IPluginTexdef;
+void Texture_SetTexture (texdef_t *texdef, brushprimit_texdef_t *brushprimit_texdef, bool bFitScale = false, IPluginTexdef *pTexdef = NULL, bool bSetSelection = true);
+
+void Texture_SetMode(int iMenu); // GL_TEXTURE_NEAREST, etc..
+void Texture_ResetPosition();
+
+void FreeShaders();
+void LoadShaders();
+void ReloadShaders();
+int WINAPI Texture_LoadSkin(char *pName, int *pnWidth, int *pnHeight);
+void Texture_LoadFromPlugIn(LPVOID vp);
+void Texture_StartPos (void);
+qtexture_t *Texture_NextPos (int *x, int *y);
diff --git a/q3radiant/ToolWnd.cpp b/q3radiant/ToolWnd.cpp
new file mode 100755
index 0000000..bc6f294
--- /dev/null
+++ b/q3radiant/ToolWnd.cpp
@@ -0,0 +1,55 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// ToolWnd.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "ToolWnd.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CToolWnd
+
+CToolWnd::CToolWnd()
+{
+}
+
+CToolWnd::~CToolWnd()
+{
+}
+
+
+BEGIN_MESSAGE_MAP(CToolWnd, CWnd)
+ //{{AFX_MSG_MAP(CToolWnd)
+ // NOTE - the ClassWizard will add and remove mapping macros here.
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+
+/////////////////////////////////////////////////////////////////////////////
+// CToolWnd message handlers
diff --git a/q3radiant/ToolWnd.h b/q3radiant/ToolWnd.h
new file mode 100755
index 0000000..8cda0f6
--- /dev/null
+++ b/q3radiant/ToolWnd.h
@@ -0,0 +1,68 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_TOOLWND_H__5E29A4F9_A20C_4056_950F_9AA8842F53B7__INCLUDED_)
+#define AFX_TOOLWND_H__5E29A4F9_A20C_4056_950F_9AA8842F53B7__INCLUDED_
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+// ToolWnd.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CToolWnd window
+
+class CToolWnd : public CWnd
+{
+// Construction
+public:
+ CToolWnd();
+
+// Attributes
+public:
+
+// Operations
+public:
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CToolWnd)
+ //}}AFX_VIRTUAL
+
+// Implementation
+public:
+ virtual ~CToolWnd();
+
+ // Generated message map functions
+protected:
+ //{{AFX_MSG(CToolWnd)
+ // NOTE - the ClassWizard will add and remove member functions here.
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+/////////////////////////////////////////////////////////////////////////////
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_TOOLWND_H__5E29A4F9_A20C_4056_950F_9AA8842F53B7__INCLUDED_)
diff --git a/q3radiant/Undo.cpp b/q3radiant/Undo.cpp
new file mode 100755
index 0000000..ca0a74e
--- /dev/null
+++ b/q3radiant/Undo.cpp
@@ -0,0 +1,884 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+/*
+
+ QERadiant Undo/Redo
+
+
+basic setup:
+
+<-g_undolist---------g_lastundo> <---map data---> <-g_lastredo---------g_redolist->
+
+
+ undo/redo on the world_entity is special, only the epair changes are remembered
+ and the world entity never gets deleted.
+
+ FIXME: maybe reset the Undo system at map load
+ maybe also reset the entityId at map load
+*/
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "qe3.h"
+
+typedef struct undo_s
+{
+ double time; //time operation was performed
+ int id; //every undo has an unique id
+ int done; //true when undo is build
+ char *operation; //name of the operation
+ brush_t brushlist; //deleted brushes
+ entity_t entitylist; //deleted entities
+ struct undo_s *prev, *next; //next and prev undo in list
+} undo_t;
+
+undo_t *g_undolist; //first undo in the list
+undo_t *g_lastundo; //last undo in the list
+undo_t *g_redolist; //first redo in the list
+undo_t *g_lastredo; //last undo in list
+int g_undoMaxSize = 64; //maximum number of undos
+int g_undoSize = 0; //number of undos in the list
+int g_undoMaxMemorySize = 2*1024*1024; //maximum undo memory (default 2 MB)
+int g_undoMemorySize = 0; //memory size of undo buffer
+int g_undoId = 1; //current undo ID (zero is invalid id)
+int g_redoId = 1; //current redo ID (zero is invalid id)
+
+
+/*
+=============
+Undo_MemorySize
+=============
+*/
+int Undo_MemorySize(void)
+{
+ /*
+ int size;
+ undo_t *undo;
+ brush_t *pBrush;
+ entity_t *pEntity;
+
+ size = 0;
+ for (undo = g_undolist; undo; undo = undo->next)
+ {
+ for (pBrush = undo->brushlist.next ; pBrush != NULL && pBrush != &undo->brushlist ; pBrush = pBrush->next)
+ {
+ size += Brush_MemorySize(pBrush);
+ }
+ for (pEntity = undo->entitylist.next; pEntity != NULL && pEntity != &undo->entitylist; pEntity = pEntity->next)
+ {
+ size += Entity_MemorySize(pEntity);
+ }
+ size += sizeof(undo_t);
+ }
+ return size;
+ */
+ return g_undoMemorySize;
+}
+
+/*
+=============
+Undo_ClearRedo
+=============
+*/
+void Undo_ClearRedo(void)
+{
+ undo_t *redo, *nextredo;
+ brush_t *pBrush, *pNextBrush;
+ entity_t *pEntity, *pNextEntity;
+
+ for (redo = g_redolist; redo; redo = nextredo)
+ {
+ nextredo = redo->next;
+ for (pBrush = redo->brushlist.next ; pBrush != NULL && pBrush != &redo->brushlist ; pBrush = pNextBrush)
+ {
+ pNextBrush = pBrush->next;
+ Brush_Free(pBrush);
+ }
+ for (pEntity = redo->entitylist.next; pEntity != NULL && pEntity != &redo->entitylist; pEntity = pNextEntity)
+ {
+ pNextEntity = pEntity->next;
+ Entity_Free(pEntity);
+ }
+ free(redo);
+ }
+ g_redolist = NULL;
+ g_lastredo = NULL;
+ g_redoId = 1;
+}
+
+/*
+=============
+Undo_Clear
+
+ Clears the undo buffer.
+=============
+*/
+void Undo_Clear(void)
+{
+ undo_t *undo, *nextundo;
+ brush_t *pBrush, *pNextBrush;
+ entity_t *pEntity, *pNextEntity;
+
+ Undo_ClearRedo();
+ for (undo = g_undolist; undo; undo = nextundo)
+ {
+ nextundo = undo->next;
+ for (pBrush = undo->brushlist.next ; pBrush != NULL && pBrush != &undo->brushlist ; pBrush = pNextBrush)
+ {
+ pNextBrush = pBrush->next;
+ g_undoMemorySize -= Brush_MemorySize(pBrush);
+ Brush_Free(pBrush);
+ }
+ for (pEntity = undo->entitylist.next; pEntity != NULL && pEntity != &undo->entitylist; pEntity = pNextEntity)
+ {
+ pNextEntity = pEntity->next;
+ g_undoMemorySize -= Entity_MemorySize(pEntity);
+ Entity_Free(pEntity);
+ }
+ g_undoMemorySize -= sizeof(undo_t);
+ free(undo);
+ }
+ g_undolist = NULL;
+ g_lastundo = NULL;
+ g_undoSize = 0;
+ g_undoMemorySize = 0;
+ g_undoId = 1;
+}
+
+/*
+=============
+Undo_SetMaxSize
+=============
+*/
+void Undo_SetMaxSize(int size)
+{
+ Undo_Clear();
+ if (size < 1) g_undoMaxSize = 1;
+ else g_undoMaxSize = size;
+}
+
+/*
+=============
+Undo_GetMaxSize
+=============
+*/
+int Undo_GetMaxSize(void)
+{
+ return g_undoMaxSize;
+}
+
+/*
+=============
+Undo_SetMaxMemorySize
+=============
+*/
+void Undo_SetMaxMemorySize(int size)
+{
+ Undo_Clear();
+ if (size < 1024) g_undoMaxMemorySize = 1024;
+ else g_undoMaxMemorySize = size;
+}
+
+/*
+=============
+Undo_GetMaxMemorySize
+=============
+*/
+int Undo_GetMaxMemorySize(void)
+{
+ return g_undoMaxMemorySize;
+}
+
+/*
+=============
+Undo_FreeFirstUndo
+=============
+*/
+void Undo_FreeFirstUndo(void)
+{
+ undo_t *undo;
+ brush_t *pBrush, *pNextBrush;
+ entity_t *pEntity, *pNextEntity;
+
+ //remove the oldest undo from the undo buffer
+ undo = g_undolist;
+ g_undolist = g_undolist->next;
+ g_undolist->prev = NULL;
+ //
+ for (pBrush = undo->brushlist.next ; pBrush != NULL && pBrush != &undo->brushlist ; pBrush = pNextBrush)
+ {
+ pNextBrush = pBrush->next;
+ g_undoMemorySize -= Brush_MemorySize(pBrush);
+ Brush_Free(pBrush);
+ }
+ for (pEntity = undo->entitylist.next; pEntity != NULL && pEntity != &undo->entitylist; pEntity = pNextEntity)
+ {
+ pNextEntity = pEntity->next;
+ g_undoMemorySize -= Entity_MemorySize(pEntity);
+ Entity_Free(pEntity);
+ }
+ g_undoMemorySize -= sizeof(undo_t);
+ free(undo);
+ g_undoSize--;
+}
+
+/*
+=============
+Undo_GeneralStart
+=============
+*/
+void Undo_GeneralStart(char *operation)
+{
+ undo_t *undo;
+ brush_t *pBrush;
+ entity_t *pEntity;
+
+
+ if (g_lastundo)
+ {
+ if (!g_lastundo->done)
+ {
+ Sys_Printf("Undo_Start: WARNING last undo not finished.\n");
+ }
+ }
+
+ undo = (undo_t *) malloc(sizeof(undo_t));
+ if (!undo) return;
+ memset(undo, 0, sizeof(undo_t));
+ undo->brushlist.next = &undo->brushlist;
+ undo->brushlist.prev = &undo->brushlist;
+ undo->entitylist.next = &undo->entitylist;
+ undo->entitylist.prev = &undo->entitylist;
+ if (g_lastundo) g_lastundo->next = undo;
+ else g_undolist = undo;
+ undo->prev = g_lastundo;
+ undo->next = NULL;
+ g_lastundo = undo;
+
+ undo->time = Sys_DoubleTime();
+ //
+ if (g_undoId > g_undoMaxSize * 2) g_undoId = 1;
+ if (g_undoId <= 0) g_undoId = 1;
+ undo->id = g_undoId++;
+ undo->done = false;
+ undo->operation = operation;
+ //reset the undo IDs of all brushes using the new ID
+ for (pBrush = active_brushes.next; pBrush != NULL && pBrush != &active_brushes; pBrush = pBrush->next)
+ {
+ if (pBrush->undoId == undo->id)
+ {
+ pBrush->undoId = 0;
+ }
+ }
+ for (pBrush = selected_brushes.next; pBrush != NULL && pBrush != &selected_brushes; pBrush = pBrush->next)
+ {
+ if (pBrush->undoId == undo->id)
+ {
+ pBrush->undoId = 0;
+ }
+ }
+ //reset the undo IDs of all entities using thew new ID
+ for (pEntity = entities.next; pEntity != NULL && pEntity != &entities; pEntity = pEntity->next)
+ {
+ if (pEntity->undoId == undo->id)
+ {
+ pEntity->undoId = 0;
+ }
+ }
+ g_undoMemorySize += sizeof(undo_t);
+ g_undoSize++;
+ //undo buffer is bound to a max
+ if (g_undoSize > g_undoMaxSize)
+ {
+ Undo_FreeFirstUndo();
+ }
+}
+
+/*
+=============
+Undo_BrushInUndo
+=============
+*/
+int Undo_BrushInUndo(undo_t *undo, brush_t *brush)
+{
+ brush_t *b;
+
+ for (b = undo->brushlist.next; b != &undo->brushlist; b = b->next)
+ {
+ if (b == brush) return true;
+ }
+ return false;
+}
+
+/*
+=============
+Undo_EntityInUndo
+=============
+*/
+int Undo_EntityInUndo(undo_t *undo, entity_t *ent)
+{
+ entity_t *e;
+
+ for (e = undo->entitylist.next; e != &undo->entitylist; e = e->next)
+ {
+ if (e == ent) return true;
+ }
+ return false;
+}
+
+/*
+=============
+Undo_Start
+=============
+*/
+void Undo_Start(char *operation)
+{
+ Undo_ClearRedo();
+ Undo_GeneralStart(operation);
+}
+
+/*
+=============
+Undo_AddBrush
+=============
+*/
+void Undo_AddBrush(brush_t *pBrush)
+{
+ if (!g_lastundo)
+ {
+ Sys_Printf("Undo_AddBrushList: no last undo.\n");
+ return;
+ }
+ if (g_lastundo->entitylist.next != &g_lastundo->entitylist)
+ {
+ Sys_Printf("Undo_AddBrushList: WARNING adding brushes after entity.\n");
+ }
+ //if the brush is already in the undo
+ if (Undo_BrushInUndo(g_lastundo, pBrush))
+ return;
+ //clone the brush
+ brush_t* pClone = Brush_FullClone(pBrush);
+ //save the ID of the owner entity
+ pClone->ownerId = pBrush->owner->entityId;
+ //save the old undo ID for previous undos
+ pClone->undoId = pBrush->undoId;
+ Brush_AddToList (pClone, &g_lastundo->brushlist);
+ //
+ g_undoMemorySize += Brush_MemorySize(pClone);
+}
+
+/*
+=============
+Undo_AddBrushList
+=============
+*/
+void Undo_AddBrushList(brush_t *brushlist)
+{
+ brush_t *pBrush;
+
+ if (!g_lastundo)
+ {
+ Sys_Printf("Undo_AddBrushList: no last undo.\n");
+ return;
+ }
+ if (g_lastundo->entitylist.next != &g_lastundo->entitylist)
+ {
+ Sys_Printf("Undo_AddBrushList: WARNING adding brushes after entity.\n");
+ }
+ //copy the brushes to the undo
+ for (pBrush = brushlist->next ; pBrush != NULL && pBrush != brushlist; pBrush=pBrush->next)
+ {
+ //if the brush is already in the undo
+ if (Undo_BrushInUndo(g_lastundo, pBrush))
+ continue;
+ // do we need to store this brush's entity in the undo?
+ // if it's a fixed size entity, the brush that reprents it is not really relevant, it's used for selecting and moving around
+ // what we want to store for undo is the owner entity, epairs and origin/angle stuff
+ //++timo FIXME: if the entity is not fixed size I don't know, so I don't do it yet
+ if (pBrush->owner->eclass->fixedsize == 1)
+ Undo_AddEntity( pBrush->owner );
+ //clone the brush
+ brush_t* pClone = Brush_FullClone(pBrush);
+ //save the ID of the owner entity
+ pClone->ownerId = pBrush->owner->entityId;
+ //save the old undo ID from previous undos
+ pClone->undoId = pBrush->undoId;
+ Brush_AddToList (pClone, &g_lastundo->brushlist);
+ //
+ g_undoMemorySize += Brush_MemorySize(pClone);
+ }
+}
+
+/*
+=============
+Undo_EndBrush
+=============
+*/
+void Undo_EndBrush(brush_t *pBrush)
+{
+ if (!g_lastundo)
+ {
+ //Sys_Printf("Undo_End: no last undo.\n");
+ return;
+ }
+ if (g_lastundo->done)
+ {
+ //Sys_Printf("Undo_End: last undo already finished.\n");
+ return;
+ }
+ pBrush->undoId = g_lastundo->id;
+}
+
+/*
+=============
+Undo_EndBrushList
+=============
+*/
+void Undo_EndBrushList(brush_t *brushlist)
+{
+ if (!g_lastundo)
+ {
+ //Sys_Printf("Undo_End: no last undo.\n");
+ return;
+ }
+ if (g_lastundo->done)
+ {
+ //Sys_Printf("Undo_End: last undo already finished.\n");
+ return;
+ }
+ for (brush_t* pBrush = brushlist->next; pBrush != NULL && pBrush != brushlist; pBrush=pBrush->next)
+ {
+ pBrush->undoId = g_lastundo->id;
+ }
+}
+
+/*
+=============
+Undo_AddEntity
+=============
+*/
+void Undo_AddEntity(entity_t *entity)
+{
+ entity_t* pClone;
+
+ if (!g_lastundo)
+ {
+ Sys_Printf("Undo_AddEntity: no last undo.\n");
+ return;
+ }
+ //if the entity is already in the undo
+ if (Undo_EntityInUndo(g_lastundo, entity))
+ return;
+ //clone the entity
+ pClone = Entity_Clone(entity);
+ //NOTE: Entity_Clone adds the entity to the entity list
+ // so we remove it from that list here
+ Entity_RemoveFromList(pClone);
+ //save the old undo ID for previous undos
+ pClone->undoId = entity->undoId;
+ //save the entity ID (we need a full clone)
+ pClone->entityId = entity->entityId;
+ //
+ Entity_AddToList(pClone, &g_lastundo->entitylist);
+ //
+ g_undoMemorySize += Entity_MemorySize(pClone);
+}
+
+/*
+=============
+Undo_EndEntity
+=============
+*/
+void Undo_EndEntity(entity_t *entity)
+{
+ if (!g_lastundo)
+ {
+ //Sys_Printf("Undo_End: no last undo.\n");
+ return;
+ }
+ if (g_lastundo->done)
+ {
+ //Sys_Printf("Undo_End: last undo already finished.\n");
+ return;
+ }
+ if (entity == world_entity)
+ {
+ //Sys_Printf("Undo_AddEntity: undo on world entity.\n");
+ //NOTE: we never delete the world entity when undoing an operation
+ // we only transfer the epairs
+ return;
+ }
+ entity->undoId = g_lastundo->id;
+}
+
+/*
+=============
+Undo_End
+=============
+*/
+void Undo_End(void)
+{
+ if (!g_lastundo)
+ {
+ //Sys_Printf("Undo_End: no last undo.\n");
+ return;
+ }
+ if (g_lastundo->done)
+ {
+ //Sys_Printf("Undo_End: last undo already finished.\n");
+ return;
+ }
+ g_lastundo->done = true;
+
+ //undo memory size is bound to a max
+ while (g_undoMemorySize > g_undoMaxMemorySize)
+ {
+ //always keep one undo
+ if (g_undolist == g_lastundo) break;
+ Undo_FreeFirstUndo();
+ }
+ //
+ //Sys_Printf("undo size = %d, undo memory = %d\n", g_undoSize, g_undoMemorySize);
+}
+
+/*
+=============
+Undo_Undo
+=============
+*/
+void Undo_Undo(void)
+{
+ undo_t *undo, *redo;
+ brush_t *pBrush, *pNextBrush;
+ entity_t *pEntity, *pNextEntity, *pUndoEntity;
+
+ if (!g_lastundo)
+ {
+ Sys_Printf("Nothing left to undo.\n");
+ return;
+ }
+ if (!g_lastundo->done)
+ {
+ Sys_Printf("Undo_Undo: WARNING: last undo not yet finished!\n");
+ }
+ // get the last undo
+ undo = g_lastundo;
+ if (g_lastundo->prev) g_lastundo->prev->next = NULL;
+ else g_undolist = NULL;
+ g_lastundo = g_lastundo->prev;
+
+ //allocate a new redo
+ redo = (undo_t *) malloc(sizeof(undo_t));
+ if (!redo) return;
+ memset(redo, 0, sizeof(undo_t));
+ redo->brushlist.next = &redo->brushlist;
+ redo->brushlist.prev = &redo->brushlist;
+ redo->entitylist.next = &redo->entitylist;
+ redo->entitylist.prev = &redo->entitylist;
+ if (g_lastredo) g_lastredo->next = redo;
+ else g_redolist = redo;
+ redo->prev = g_lastredo;
+ redo->next = NULL;
+ g_lastredo = redo;
+ redo->time = Sys_DoubleTime();
+ redo->id = g_redoId++;
+ redo->done = true;
+ redo->operation = undo->operation;
+
+ //reset the redo IDs of all brushes using the new ID
+ for (pBrush = active_brushes.next; pBrush != NULL && pBrush != &active_brushes; pBrush = pBrush->next)
+ {
+ if (pBrush->redoId == redo->id)
+ {
+ pBrush->redoId = 0;
+ }
+ }
+ for (pBrush = selected_brushes.next; pBrush != NULL && pBrush != &selected_brushes; pBrush = pBrush->next)
+ {
+ if (pBrush->redoId == redo->id)
+ {
+ pBrush->redoId = 0;
+ }
+ }
+ //reset the redo IDs of all entities using thew new ID
+ for (pEntity = entities.next; pEntity != NULL && pEntity != &entities; pEntity = pEntity->next)
+ {
+ if (pEntity->redoId == redo->id)
+ {
+ pEntity->redoId = 0;
+ }
+ }
+
+ // remove current selection
+ Select_Deselect();
+ // move "created" brushes to the redo
+ for (pBrush = active_brushes.next; pBrush != NULL && pBrush != &active_brushes; pBrush=pNextBrush)
+ {
+ pNextBrush = pBrush->next;
+ if (pBrush->undoId == undo->id)
+ {
+ //Brush_Free(pBrush);
+ //move the brush to the redo
+ Brush_RemoveFromList(pBrush);
+ Brush_AddToList(pBrush, &redo->brushlist);
+ //make sure the ID of the owner is stored
+ pBrush->ownerId = pBrush->owner->entityId;
+ //unlink the brush from the owner entity
+ Entity_UnlinkBrush(pBrush);
+ }
+ }
+ // move "created" entities to the redo
+ for (pEntity = entities.next; pEntity != NULL && pEntity != &entities; pEntity = pNextEntity)
+ {
+ pNextEntity = pEntity->next;
+ if (pEntity->undoId == undo->id)
+ {
+ // check if this entity is in the undo
+ for (pUndoEntity = undo->entitylist.next; pUndoEntity != NULL && pUndoEntity != &undo->entitylist; pUndoEntity = pUndoEntity->next)
+ {
+ // move brushes to the undo entity
+ if (pUndoEntity->entityId == pEntity->entityId)
+ {
+ pUndoEntity->brushes.next = pEntity->brushes.next;
+ pUndoEntity->brushes.prev = pEntity->brushes.prev;
+ pEntity->brushes.next = &pEntity->brushes;
+ pEntity->brushes.prev = &pEntity->brushes;
+ }
+ }
+ //
+ //Entity_Free(pEntity);
+ //move the entity to the redo
+ Entity_RemoveFromList(pEntity);
+ Entity_AddToList(pEntity, &redo->entitylist);
+ }
+ }
+ // add the undo entities back into the entity list
+ for (pEntity = undo->entitylist.next; pEntity != NULL && pEntity != &undo->entitylist; pEntity = undo->entitylist.next)
+ {
+ g_undoMemorySize -= Entity_MemorySize(pEntity);
+ //if this is the world entity
+ if (pEntity->entityId == world_entity->entityId)
+ {
+ //free the epairs of the world entity
+ Entity_FreeEpairs(world_entity);
+ //set back the original epairs
+ world_entity->epairs = pEntity->epairs;
+ // unhook the epairs and free the world_entity clone that stored the epairs
+ pEntity->epairs = NULL;
+ Entity_Free(pEntity);
+ }
+ else
+ {
+ Entity_RemoveFromList(pEntity);
+ Entity_AddToList(pEntity, &entities);
+ pEntity->redoId = redo->id;
+ }
+ }
+ // add the undo brushes back into the selected brushes
+ for (pBrush = undo->brushlist.next; pBrush != NULL && pBrush != &undo->brushlist; pBrush = undo->brushlist.next)
+ {
+ g_undoMemorySize -= Brush_MemorySize(pBrush);
+ Brush_RemoveFromList(pBrush);
+ Brush_AddToList(pBrush, &active_brushes);
+ for (pEntity = entities.next; pEntity != NULL && pEntity != &entities; pEntity = pNextEntity)
+ {
+ if (pEntity->entityId == pBrush->ownerId)
+ {
+ Entity_LinkBrush(pEntity, pBrush);
+ break;
+ }
+ }
+ //if the brush is not linked then it should be linked into the world entity
+ if (pEntity == NULL || pEntity == &entities)
+ {
+ Entity_LinkBrush(world_entity, pBrush);
+ }
+ //build the brush
+ //Brush_Build(pBrush);
+ Select_Brush(pBrush);
+ pBrush->redoId = redo->id;
+ }
+ //
+ Sys_Printf("%s undone.\n", undo->operation);
+ // free the undo
+ g_undoMemorySize -= sizeof(undo_t);
+ free(undo);
+ g_undoSize--;
+ g_undoId--;
+ if (g_undoId <= 0) g_undoId = 2 * g_undoMaxSize;
+ //
+ g_bScreenUpdates = true;
+ Sys_UpdateWindows(W_ALL);
+}
+
+/*
+=============
+Undo_Redo
+=============
+*/
+void Undo_Redo(void)
+{
+ undo_t *redo;
+ brush_t *pBrush, *pNextBrush;
+ entity_t *pEntity, *pNextEntity, *pRedoEntity;
+
+ if (!g_lastredo)
+ {
+ Sys_Printf("Nothing left to redo.\n");
+ return;
+ }
+ if (g_lastundo)
+ {
+ if (!g_lastundo->done)
+ {
+ Sys_Printf("WARNING: last undo not finished.\n");
+ }
+ }
+ // get the last redo
+ redo = g_lastredo;
+ if (g_lastredo->prev) g_lastredo->prev->next = NULL;
+ else g_redolist = NULL;
+ g_lastredo = g_lastredo->prev;
+ //
+ Undo_GeneralStart(redo->operation);
+ // remove current selection
+ Select_Deselect();
+ // move "created" brushes back to the last undo
+ for (pBrush = active_brushes.next; pBrush != NULL && pBrush != &active_brushes; pBrush = pNextBrush)
+ {
+ pNextBrush = pBrush->next;
+ if (pBrush->redoId == redo->id)
+ {
+ //move the brush to the undo
+ Brush_RemoveFromList(pBrush);
+ Brush_AddToList(pBrush, &g_lastundo->brushlist);
+ g_undoMemorySize += Brush_MemorySize(pBrush);
+ pBrush->ownerId = pBrush->owner->entityId;
+ Entity_UnlinkBrush(pBrush);
+ }
+ }
+ // move "created" entities back to the last undo
+ for (pEntity = entities.next; pEntity != NULL && pEntity != &entities; pEntity = pNextEntity)
+ {
+ pNextEntity = pEntity->next;
+ if (pEntity->redoId == redo->id)
+ {
+ // check if this entity is in the redo
+ for (pRedoEntity = redo->entitylist.next; pRedoEntity != NULL && pRedoEntity != &redo->entitylist; pRedoEntity = pRedoEntity->next)
+ {
+ // move brushes to the redo entity
+ if (pRedoEntity->entityId == pEntity->entityId)
+ {
+ pRedoEntity->brushes.next = pEntity->brushes.next;
+ pRedoEntity->brushes.prev = pEntity->brushes.prev;
+ pEntity->brushes.next = &pEntity->brushes;
+ pEntity->brushes.prev = &pEntity->brushes;
+ }
+ }
+ //
+ //Entity_Free(pEntity);
+ //move the entity to the redo
+ Entity_RemoveFromList(pEntity);
+ Entity_AddToList(pEntity, &g_lastundo->entitylist);
+ g_undoMemorySize += Entity_MemorySize(pEntity);
+ }
+ }
+ // add the undo entities back into the entity list
+ for (pEntity = redo->entitylist.next; pEntity != NULL && pEntity != &redo->entitylist; pEntity = redo->entitylist.next)
+ {
+ //if this is the world entity
+ if (pEntity->entityId == world_entity->entityId)
+ {
+ //free the epairs of the world entity
+ Entity_FreeEpairs(world_entity);
+ //set back the original epairs
+ world_entity->epairs = pEntity->epairs;
+ //free the world_entity clone that stored the epairs
+ Entity_Free(pEntity);
+ }
+ else
+ {
+ Entity_RemoveFromList(pEntity);
+ Entity_AddToList(pEntity, &entities);
+ }
+ }
+ // add the redo brushes back into the selected brushes
+ for (pBrush = redo->brushlist.next; pBrush != NULL && pBrush != &redo->brushlist; pBrush = redo->brushlist.next)
+ {
+ Brush_RemoveFromList(pBrush);
+ Brush_AddToList(pBrush, &active_brushes);
+ for (pEntity = entities.next; pEntity != NULL && pEntity != &entities; pEntity = pNextEntity)
+ {
+ if (pEntity->entityId == pBrush->ownerId)
+ {
+ Entity_LinkBrush(pEntity, pBrush);
+ break;
+ }
+ }
+ //if the brush is not linked then it should be linked into the world entity
+ if (pEntity == NULL || pEntity == &entities)
+ {
+ Entity_LinkBrush(world_entity, pBrush);
+ }
+ //build the brush
+ //Brush_Build(pBrush);
+ Select_Brush(pBrush);
+ }
+ //
+ Undo_End();
+ //
+ Sys_Printf("%s redone.\n", redo->operation);
+ //
+ g_redoId--;
+ // free the undo
+ free(redo);
+ //
+ g_bScreenUpdates = true;
+ Sys_UpdateWindows(W_ALL);
+}
+
+/*
+=============
+Undo_RedoAvailable
+=============
+*/
+int Undo_RedoAvailable(void)
+{
+ if (g_lastredo) return true;
+ return false;
+}
+
+/*
+=============
+Undo_UndoAvailable
+=============
+*/
+int Undo_UndoAvailable(void)
+{
+ if (g_lastundo)
+ {
+ if (g_lastundo->done)
+ return true;
+ }
+ return false;
+}
diff --git a/q3radiant/Undo.h b/q3radiant/Undo.h
new file mode 100755
index 0000000..27100d7
--- /dev/null
+++ b/q3radiant/Undo.h
@@ -0,0 +1,64 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//
+//
+// QERadiant Multilevel Undo/Redo
+//
+//
+
+//start operation
+void Undo_Start(char *operation);
+//end operation
+void Undo_End(void);
+//add brush to the undo
+void Undo_AddBrush(brush_t *pBrush);
+//add a list with brushes to the undo
+void Undo_AddBrushList(brush_t *brushlist);
+//end a brush after the operation is performed
+void Undo_EndBrush(brush_t *pBrush);
+//end a list with brushes after the operation is performed
+void Undo_EndBrushList(brush_t *brushlist);
+//add entity to undo
+void Undo_AddEntity(entity_t *entity);
+//end an entity after the operation is performed
+void Undo_EndEntity(entity_t *entity);
+//undo last operation
+void Undo_Undo(void);
+//redo last undone operation
+void Undo_Redo(void);
+//returns true if there is something to be undone available
+int Undo_UndoAvailable(void);
+//returns true if there is something to redo available
+int Undo_RedoAvailable(void);
+//clear the undo buffer
+void Undo_Clear(void);
+//set maximum undo size (default 64)
+void Undo_SetMaxSize(int size);
+//get maximum undo size
+int Undo_GetMaxSize(void);
+//set maximum undo memory in bytes (default 2 MB)
+void Undo_SetMaxMemorySize(int size);
+//get maximum undo memory in bytes
+int Undo_GetMaxMemorySize(void);
+//returns the amount of memory used by undo
+int Undo_MemorySize(void);
+
diff --git a/q3radiant/VERTSEL.CPP b/q3radiant/VERTSEL.CPP
new file mode 100755
index 0000000..d41c34b
--- /dev/null
+++ b/q3radiant/VERTSEL.CPP
@@ -0,0 +1,372 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "stdafx.h"
+#include "qe3.h"
+#include "winding.h"
+
+#define NEWEDGESEL 1
+
+
+int FindPoint (vec3_t point)
+{
+ int i, j;
+
+ for (i=0 ; i<g_qeglobals.d_numpoints ; i++)
+ {
+ for (j=0 ; j<3 ; j++)
+ if (fabs(point[j] - g_qeglobals.d_points[i][j]) > 0.1)
+ break;
+ if (j == 3)
+ return i;
+ }
+
+ VectorCopy (point, g_qeglobals.d_points[g_qeglobals.d_numpoints]);
+ if (g_qeglobals.d_numpoints < MAX_POINTS-1)
+ {
+ g_qeglobals.d_numpoints++;
+ }
+
+ return g_qeglobals.d_numpoints-1;
+}
+
+int FindEdge (int p1, int p2, face_t *f)
+{
+ int i;
+
+ for (i=0 ; i<g_qeglobals.d_numedges ; i++)
+ if (g_qeglobals.d_edges[i].p1 == p2 && g_qeglobals.d_edges[i].p2 == p1)
+ {
+ g_qeglobals.d_edges[i].f2 = f;
+ return i;
+ }
+
+ g_qeglobals.d_edges[g_qeglobals.d_numedges].p1 = p1;
+ g_qeglobals.d_edges[g_qeglobals.d_numedges].p2 = p2;
+ g_qeglobals.d_edges[g_qeglobals.d_numedges].f1 = f;
+
+ if (g_qeglobals.d_numedges < MAX_EDGES-1)
+ {
+ g_qeglobals.d_numedges++;
+ }
+
+ return g_qeglobals.d_numedges-1;
+}
+
+#ifdef NEWEDGESEL
+void MakeFace (brush_t* b, face_t *f)
+#else
+void MakeFace (face_t *f)
+#endif
+{
+ winding_t *w;
+ int i;
+ int pnum[128];
+
+#ifdef NEWEDGESEL
+ w = Brush_MakeFaceWinding (b, f);
+#else
+ w = Brush_MakeFaceWinding (selected_brushes.next, f);
+#endif
+ if (!w)
+ return;
+ for (i=0 ; i<w->numpoints ; i++)
+ pnum[i] = FindPoint (w->points[i]);
+ for (i=0 ; i<w->numpoints ; i++)
+ FindEdge (pnum[i], pnum[(i+1)%w->numpoints], f);
+
+ free (w);
+}
+
+void SetupVertexSelection (void)
+{
+ face_t *f;
+ brush_t *b;
+
+ g_qeglobals.d_numpoints = 0;
+ g_qeglobals.d_numedges = 0;
+
+#ifdef NEWEDGESEL
+ for (b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ {
+ for (f=b->brush_faces ; f ; f=f->next)
+ MakeFace (b,f);
+ }
+#else
+ if (!QE_SingleBrush())
+ return;
+
+ b = selected_brushes.next;
+ for (f=b->brush_faces ; f ; f=f->next)
+ MakeFace (b,f);
+#endif
+
+}
+
+
+#ifdef NEWEDGESEL
+void SelectFaceEdge (brush_t* b, face_t *f, int p1, int p2)
+#else
+void SelectFaceEdge (face_t *f, int p1, int p2)
+#endif
+{
+ winding_t *w;
+ int i, j, k;
+ int pnum[128];
+
+#ifdef NEWEDGESEL
+ w = Brush_MakeFaceWinding (b, f);
+#else
+ w = Brush_MakeFaceWinding (selected_brushes.next, f);
+#endif
+ if (!w)
+ return;
+ for (i=0 ; i<w->numpoints ; i++)
+ pnum[i] = FindPoint (w->points[i]);
+
+ for (i=0 ; i<w->numpoints ; i++)
+ if (pnum[i] == p1 && pnum[(i+1)%w->numpoints] == p2)
+ {
+ VectorCopy (g_qeglobals.d_points[pnum[i]], f->planepts[0]);
+ VectorCopy (g_qeglobals.d_points[pnum[(i+1)%w->numpoints]], f->planepts[1]);
+ VectorCopy (g_qeglobals.d_points[pnum[(i+2)%w->numpoints]], f->planepts[2]);
+ for (j=0 ; j<3 ; j++)
+ {
+ for (k=0 ; k<3 ; k++)
+ {
+ f->planepts[j][k] = floor(f->planepts[j][k]/g_qeglobals.d_gridsize+0.5)*g_qeglobals.d_gridsize;
+ }
+ }
+
+ AddPlanept (f->planepts[0]);
+ AddPlanept (f->planepts[1]);
+ break;
+ }
+
+ if (i == w->numpoints)
+ Sys_Printf ("SelectFaceEdge: failed\n");
+ free (w);
+}
+
+
+void SelectVertex (int p1)
+{
+ brush_t *b;
+ winding_t *w;
+ int i, j, k;
+ face_t *f;
+
+#ifdef NEWEDGESEL
+ for (b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ {
+ for (f=b->brush_faces ; f ; f=f->next)
+ {
+ w = Brush_MakeFaceWinding (b, f);
+ if (!w)
+ continue;
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ if (FindPoint (w->points[i]) == p1)
+ {
+ VectorCopy (w->points[(i+w->numpoints-1)%w->numpoints], f->planepts[0]);
+ VectorCopy (w->points[i], f->planepts[1]);
+ VectorCopy (w->points[(i+1)%w->numpoints], f->planepts[2]);
+ for (j=0 ; j<3 ; j++)
+ {
+ for (k=0 ; k<3 ; k++)
+ {
+ ;//f->planepts[j][k] = floor(f->planepts[j][k]/g_qeglobals.d_gridsize+0.5)*g_qeglobals.d_gridsize;
+ }
+ }
+
+ AddPlanept (f->planepts[1]);
+ //MessageBeep(-1);
+
+ break;
+ }
+ }
+ free (w);
+ }
+ }
+#else
+ b = selected_brushes.next;
+ for (f=b->brush_faces ; f ; f=f->next)
+ {
+ w = Brush_MakeFaceWinding (b, f);
+ if (!w)
+ continue;
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ if (FindPoint (w->points[i]) == p1)
+ {
+ VectorCopy (w->points[(i+w->numpoints-1)%w->numpoints], f->planepts[0]);
+ VectorCopy (w->points[i], f->planepts[1]);
+ VectorCopy (w->points[(i+1)%w->numpoints], f->planepts[2]);
+ for (j=0 ; j<3 ; j++)
+ {
+ for (k=0 ; k<3 ; k++)
+ {
+ ;//f->planepts[j][k] = floor(f->planepts[j][k]/g_qeglobals.d_gridsize+0.5)*g_qeglobals.d_gridsize;
+ }
+ }
+
+ AddPlanept (f->planepts[1]);
+ //MessageBeep(-1);
+
+ break;
+ }
+ }
+ free (w);
+ }
+#endif
+}
+
+void SelectEdgeByRay (vec3_t org, vec3_t dir)
+{
+ int i, j, besti;
+ float d, bestd;
+ vec3_t mid, temp;
+ pedge_t *e;
+
+ // find the edge closest to the ray
+ besti = -1;
+ bestd = 8;
+
+ for (i=0 ; i<g_qeglobals.d_numedges ; i++)
+ {
+ for (j=0 ; j<3 ; j++)
+ mid[j] = 0.5*(g_qeglobals.d_points[g_qeglobals.d_edges[i].p1][j] + g_qeglobals.d_points[g_qeglobals.d_edges[i].p2][j]);
+
+ VectorSubtract (mid, org, temp);
+ d = DotProduct (temp, dir);
+ VectorMA (org, d, dir, temp);
+ VectorSubtract (mid, temp, temp);
+ d = VectorLength (temp);
+ if (d < bestd)
+ {
+ bestd = d;
+ besti = i;
+ }
+ }
+
+ if (besti == -1)
+ {
+ Sys_Printf ("Click didn't hit an edge\n");
+ return;
+ }
+ Sys_Printf ("hit edge\n");
+
+ // make the two faces that border the edge use the two edge points
+ // as primary drag points
+ g_qeglobals.d_num_move_points = 0;
+ e = &g_qeglobals.d_edges[besti];
+#ifdef NEWEDGESEL
+ for (brush_t* b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ {
+ SelectFaceEdge (b, e->f1, e->p1, e->p2);
+ SelectFaceEdge (b, e->f2, e->p2, e->p1);
+ }
+#else
+ SelectFaceEdge (e->f1, e->p1, e->p2);
+ SelectFaceEdge (e->f2, e->p2, e->p1);
+#endif
+
+
+}
+
+void SelectVertexByRay (vec3_t org, vec3_t dir)
+{
+ int i, besti;
+ float d, bestd;
+ vec3_t temp;
+
+ // find the point closest to the ray
+ besti = -1;
+ bestd = 8;
+
+ for (i=0 ; i<g_qeglobals.d_numpoints ; i++)
+ {
+ VectorSubtract (g_qeglobals.d_points[i], org, temp);
+ d = DotProduct (temp, dir);
+ VectorMA (org, d, dir, temp);
+ VectorSubtract (g_qeglobals.d_points[i], temp, temp);
+ d = VectorLength (temp);
+ if (d < bestd)
+ {
+ bestd = d;
+ besti = i;
+ }
+ }
+
+ if (besti == -1)
+ {
+ Sys_Printf ("Click didn't hit a vertex\n");
+ return;
+ }
+ Sys_Printf ("hit vertex\n");
+ g_qeglobals.d_move_points[g_qeglobals.d_num_move_points++] = g_qeglobals.d_points[besti];
+ //SelectVertex (besti);
+}
+
+
+
+extern void AddPatchMovePoint(vec3_t v, bool bMulti, bool bFull);
+void SelectCurvePointByRay (vec3_t org, vec3_t dir, int buttons)
+{
+ int i, besti;
+ float d, bestd;
+ vec3_t temp;
+
+ // find the point closest to the ray
+ besti = -1;
+ bestd = 8;
+
+ for (i=0 ; i<g_qeglobals.d_numpoints ; i++)
+ {
+ VectorSubtract (g_qeglobals.d_points[i], org, temp);
+ d = DotProduct (temp, dir);
+ VectorMA (org, d, dir, temp);
+ VectorSubtract (g_qeglobals.d_points[i], temp, temp);
+ d = VectorLength (temp);
+ if (d <= bestd)
+ {
+ bestd = d;
+ besti = i;
+ }
+ }
+
+ if (besti == -1)
+ {
+ if (g_pParentWnd->ActiveXY()->AreaSelectOK())
+ {
+ g_qeglobals.d_select_mode = sel_area;
+ VectorCopy(org, g_qeglobals.d_vAreaTL);
+ VectorCopy(org, g_qeglobals.d_vAreaBR);
+ }
+ return;
+ }
+ //Sys_Printf ("hit vertex\n");
+ AddPatchMovePoint(g_qeglobals.d_points[besti], buttons & MK_CONTROL, buttons & MK_SHIFT);
+}
+
+
+
diff --git a/q3radiant/VIEW.H b/q3radiant/VIEW.H
new file mode 100755
index 0000000..3f90520
--- /dev/null
+++ b/q3radiant/VIEW.H
@@ -0,0 +1,53 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+
+typedef struct
+{
+ int x, y;
+ int w, h;
+
+ int redraws; // clear to 0 when need update
+
+ vec3_t color;
+
+ vec3_t origin;
+ vec3_t angles;
+ vec3_t forward, right, up;
+
+ int draw_filtered;
+ int draw_wire;
+ int draw_solid;
+ int draw_textured;
+ int draw_blend;
+} vieworg_t;
+
+extern vieworg_t *view_org;
+extern int keysdown;
+
+void View_Init (void);
+void View_Draw (void);
+void View_MouseDown (int x, int y, int buttons);
+void View_KeyUp (int key);
+void View_KeyDown (int key);
+void View_Reshape(int w, int h);
+
diff --git a/q3radiant/WIN_CAM.CPP b/q3radiant/WIN_CAM.CPP
new file mode 100755
index 0000000..3fb952a
--- /dev/null
+++ b/q3radiant/WIN_CAM.CPP
@@ -0,0 +1,274 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// win_cam.c -- windows specific camera view code
+
+#include "stdafx.h"
+#include "qe3.h"
+
+/*
+============
+CameraWndProc
+============
+*/
+LONG WINAPI WCam_WndProc (
+ HWND hWnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam)
+{
+ int fwKeys, xPos, yPos;
+ RECT rect;
+
+ GetClientRect(hWnd, &rect);
+
+ switch (uMsg)
+ {
+ case WM_CREATE:
+ {
+ HFONT hfont;
+
+ g_qeglobals.d_hdcBase = GetDC(hWnd);
+ QEW_SetupPixelFormat(g_qeglobals.d_hdcBase, true);
+
+ if ( ( g_qeglobals.d_hglrcBase = wglCreateContext( g_qeglobals.d_hdcBase ) ) == 0 )
+ Error ("wglCreateContext failed");
+ if (!wglMakeCurrent( g_qeglobals.d_hdcBase, g_qeglobals.d_hglrcBase ))
+ Error ("wglMakeCurrent failed");
+
+ Texture_SetMode(g_qeglobals.d_savedinfo.iTexMenu);
+
+ //
+ // create GL font
+ //
+ hfont = CreateFont(
+ 10, // logical height of font
+ 7, // logical average character width
+ 0, // angle of escapement
+ 0, // base-line orientation angle
+ 0, // font weight
+ 0, // italic attribute flag
+ 0, // underline attribute flag
+ 0, // strikeout attribute flag
+ 0, // character set identifier
+ 0, // output precision
+ 0, // clipping precision
+ 0, // output quality
+ 0, // pitch and family
+ 0 // pointer to typeface name string
+ );
+
+ if ( !hfont )
+ Error( "couldn't create font" );
+
+ SelectObject (g_qeglobals.d_hdcBase, hfont);
+
+ if ( ( g_qeglobals.d_font_list = glGenLists (256) ) == 0 )
+ Error( "couldn't create font dlists" );
+
+ // create the bitmap display lists
+ // we're making images of glyphs 0 thru 255
+ if ( !wglUseFontBitmaps (g_qeglobals.d_hdcBase, 1, 255, g_qeglobals.d_font_list) )
+ Error( "wglUseFontBitmaps faileD" );
+
+ // indicate start of glyph display lists
+ glListBase (g_qeglobals.d_font_list);
+
+ // report OpenGL information
+ Sys_Printf ("GL_VENDOR: %s\n", glGetString (GL_VENDOR));
+ Sys_Printf ("GL_RENDERER: %s\n", glGetString (GL_RENDERER));
+ Sys_Printf ("GL_VERSION: %s\n", glGetString (GL_VERSION));
+ Sys_Printf ("GL_EXTENSIONS: %s\n", glGetString (GL_EXTENSIONS));
+ }
+ return 0;
+ case WM_PAINT:
+ {
+ PAINTSTRUCT ps;
+
+ if (!wglMakeCurrent( g_qeglobals.d_hdcBase, g_qeglobals.d_hglrcBase ))
+ Error ("wglMakeCurrent failed");
+
+ if ( BeginPaint(hWnd, &ps) )
+ {
+ QE_CheckOpenGLForErrors();
+ Cam_Draw ();
+ QE_CheckOpenGLForErrors();
+
+ EndPaint(hWnd, &ps);
+ SwapBuffers(g_qeglobals.d_hdcBase);
+ }
+ }
+ return 0;
+
+ case WM_USER+267: // benchmark
+ {
+ PAINTSTRUCT ps;
+ WINDOWPLACEMENT wp;
+ double start, end;
+ int i;
+
+ memset( &wp, 0, sizeof( wp ) );
+ wp.length = sizeof( wp );
+ GetWindowPlacement( g_qeglobals.d_hwndCamera, &wp );
+
+ MoveWindow( g_qeglobals.d_hwndCamera, 30, 30, 400, 400, TRUE );
+
+ BeginPaint(hWnd, &ps);
+ if (!wglMakeCurrent( g_qeglobals.d_hdcBase, g_qeglobals.d_hglrcBase))
+ Error ("wglMakeCurrent failed");
+ glDrawBuffer (GL_FRONT);
+
+ start = Sys_DoubleTime ();
+ for (i=0 ; i<100 ; i++)
+ {
+ camera.angles[YAW] = i*4;
+ Cam_Draw ();
+ }
+ wglSwapBuffers(g_qeglobals.d_hdcBase);
+ glDrawBuffer (GL_BACK);
+ end = Sys_DoubleTime ();
+ EndPaint(hWnd, &ps);
+ Sys_Printf ("%5.2f seconds\n", end-start);
+
+ SetWindowPlacement( g_qeglobals.d_hwndCamera, &wp );
+ }
+ break;
+
+ case WM_KEYDOWN:
+ if ( QE_KeyDown (wParam) )
+ return 0;
+ else
+ return DefWindowProc( hWnd, uMsg, wParam, lParam );
+
+ case WM_MBUTTONDOWN:
+ case WM_RBUTTONDOWN:
+ case WM_LBUTTONDOWN:
+ if (GetTopWindow(g_qeglobals.d_hwndMain) != hWnd)
+ BringWindowToTop(hWnd);
+
+ SetFocus (g_qeglobals.d_hwndCamera);
+ SetCapture (g_qeglobals.d_hwndCamera);
+ fwKeys = wParam; // key flags
+ xPos = (short)LOWORD(lParam); // horizontal position of cursor
+ yPos = (short)HIWORD(lParam); // vertical position of cursor
+ yPos = (int)rect.bottom - 1 - yPos;
+ Cam_MouseDown (xPos, yPos, fwKeys);
+ return 0;
+
+ case WM_MBUTTONUP:
+ case WM_RBUTTONUP:
+ case WM_LBUTTONUP:
+ fwKeys = wParam; // key flags
+ xPos = (short)LOWORD(lParam); // horizontal position of cursor
+ yPos = (short)HIWORD(lParam); // vertical position of cursor
+ yPos = (int)rect.bottom - 1 - yPos;
+ Cam_MouseUp (xPos, yPos, fwKeys);
+ if (! (fwKeys & (MK_LBUTTON|MK_RBUTTON|MK_MBUTTON)))
+ ReleaseCapture ();
+ return 0;
+
+ case WM_MOUSEMOVE:
+ fwKeys = wParam; // key flags
+ xPos = (short)LOWORD(lParam); // horizontal position of cursor
+ yPos = (short)HIWORD(lParam); // vertical position of cursor
+ yPos = (int)rect.bottom - 1 - yPos;
+ Cam_MouseMoved (xPos, yPos, fwKeys);
+ return 0;
+
+ case WM_SIZE:
+ camera.width = rect.right;
+ camera.height = rect.bottom;
+ InvalidateRect(g_qeglobals.d_hwndCamera, NULL, false);
+ return 0;
+
+ case WM_KILLFOCUS:
+ case WM_SETFOCUS:
+ SendMessage( hWnd, WM_NCACTIVATE, uMsg == WM_SETFOCUS, 0 );
+ return 0;
+
+ case WM_NCCALCSIZE:// don't let windows copy pixels
+ DefWindowProc (hWnd, uMsg, wParam, lParam);
+ return WVR_REDRAW;
+
+ case WM_CLOSE:
+ DestroyWindow (hWnd);
+ return 0;
+
+ case WM_DESTROY:
+ QEW_StopGL( hWnd, g_qeglobals.d_hglrcBase, g_qeglobals.d_hdcBase );
+ return 0;
+ }
+
+ return DefWindowProc( hWnd, uMsg, wParam, lParam );
+}
+
+
+/*
+==============
+WCam_Create
+==============
+*/
+void WCam_Create (HINSTANCE hInstance)
+{
+ WNDCLASS wc;
+ char *title;
+
+ /* Register the camera class */
+ memset (&wc, 0, sizeof(wc));
+
+ wc.style = CS_NOCLOSE;
+ wc.lpfnWndProc = (WNDPROC)WCam_WndProc;
+ wc.cbClsExtra = 0;
+ wc.cbWndExtra = 0;
+ wc.hInstance = hInstance;
+ wc.hIcon = 0;
+ wc.hCursor = LoadCursor (NULL,IDC_ARROW);
+ wc.hbrBackground = NULL;
+ wc.lpszMenuName = 0;
+ wc.lpszClassName = CAMERA_WINDOW_CLASS;
+
+ if (!RegisterClass (&wc) )
+ Error ("WCam_Register: failed");
+
+ if ( g_qeglobals.d_savedinfo.exclude & EXCLUDE_DETAIL )
+ title = "Camera View (DETAIL EXCLUDED)";
+ else
+ title = "Camera View";
+
+ g_qeglobals.d_hwndCamera = CreateWindow (CAMERA_WINDOW_CLASS ,
+ title,
+ QE3_STYLE,
+ ZWIN_WIDTH,
+ 20,
+ (int)(screen_width*CWIN_SIZE),
+ (int)(screen_height*CWIN_SIZE), // size
+
+ g_qeglobals.d_hwndMain, // parent window
+ 0, // no menu
+ hInstance,
+ 0);
+
+ if (!g_qeglobals.d_hwndCamera)
+ Error ("Couldn't create g_qeglobals.d_hwndCamera");
+
+ LoadWindowState(g_qeglobals.d_hwndCamera, "camerawindow");
+ ShowWindow (g_qeglobals.d_hwndCamera, SW_SHOWDEFAULT);
+}
diff --git a/q3radiant/WIN_DLG.CPP b/q3radiant/WIN_DLG.CPP
new file mode 100755
index 0000000..5095de2
--- /dev/null
+++ b/q3radiant/WIN_DLG.CPP
@@ -0,0 +1,616 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "stdafx.h"
+#include "qe3.h"
+#include "PrefsDlg.h"
+
+BOOL CALLBACK EditCommandDlgProc (
+ HWND hwndDlg, // handle to dialog box
+ UINT uMsg, // message
+ WPARAM wParam, // first message parameter
+ LPARAM lParam // second message parameter
+ )
+{
+ char key[1024];
+ char value[1024];
+ char *temp;
+ int index;
+ HWND hOwner;
+
+ hOwner = GetParent (hwndDlg);
+
+ switch (uMsg)
+ {
+ case WM_INITDIALOG:
+ index = SendDlgItemMessage (hOwner, IDC_CMD_LIST, LB_GETCURSEL, 0, 0);
+ if (index >= 0)
+ {
+ SendDlgItemMessage(hOwner, IDC_CMD_LIST, LB_GETTEXT, index, (LPARAM) (LPCTSTR) key);
+ temp = ValueForKey (g_qeglobals.d_project_entity, key);
+ strcpy (value, temp);
+ SetDlgItemText(hwndDlg, IDC_CMDMENUTEXT, key);
+ SetDlgItemText(hwndDlg, IDC_CMDCOMMAND, value);
+ }
+ return FALSE;
+ break;
+
+ case WM_COMMAND:
+ switch (LOWORD(wParam))
+ {
+ case IDOK:
+ if (!GetDlgItemText(hwndDlg, IDC_CMDMENUTEXT, key, 64))
+ {
+ Sys_Printf ("Command not added\n");
+ return FALSE;
+ }
+
+ if (!GetDlgItemText(hwndDlg, IDC_CMDCOMMAND, value, 64))
+ {
+ Sys_Printf ("Command not added\n");
+ return FALSE;
+ }
+
+ //if (key[0] == 'b' && key[1] == 's' && key[2] == 'p')
+ //{
+ SetKeyValue (g_qeglobals.d_project_entity, key, value);
+ FillBSPMenu ();
+ //}
+ //else
+ // Sys_Printf ("BSP commands must be preceded by \"bsp\"");
+
+ EndDialog(hwndDlg, 1);
+ return TRUE;
+
+ case IDCANCEL:
+ EndDialog(hwndDlg, 0);
+ return TRUE;
+ }
+ }
+ return FALSE;
+}
+
+BOOL CALLBACK AddCommandDlgProc (
+ HWND hwndDlg, // handle to dialog box
+ UINT uMsg, // message
+ WPARAM wParam, // first message parameter
+ LPARAM lParam // second message parameter
+ )
+{
+ char key[64];
+ char value[128];
+
+ switch (uMsg)
+ {
+ case WM_COMMAND:
+ switch (LOWORD(wParam))
+ {
+ case IDOK:
+ if (!GetDlgItemText(hwndDlg, IDC_CMDMENUTEXT, key, 64))
+ {
+ Sys_Printf ("Command not added\n");
+ return FALSE;
+ }
+
+ if (!GetDlgItemText(hwndDlg, IDC_CMDCOMMAND, value, 64))
+ {
+ Sys_Printf ("Command not added\n");
+ return FALSE;
+ }
+
+ if (key[0] == 'b' && key[1] == 's' && key[2] == 'p')
+ {
+ SetKeyValue (g_qeglobals.d_project_entity, key, value);
+ FillBSPMenu ();
+ }
+ else
+ Sys_Printf ("BSP commands must be preceded by \"bsp\"");
+
+ EndDialog(hwndDlg, 1);
+ return TRUE;
+
+ case IDCANCEL:
+ EndDialog(hwndDlg, 0);
+ return TRUE;
+ }
+ }
+ return FALSE;
+}
+
+void UpdateBSPCommandList (HWND hwndDlg)
+{
+ int i;
+ epair_t *ep;
+
+ SendDlgItemMessage(hwndDlg, IDC_CMD_LIST, LB_RESETCONTENT, 0 , 0);
+
+ i = 0;
+ for (ep = g_qeglobals.d_project_entity->epairs ; ep ; ep=ep->next)
+ {
+ if (ep->key[0] == 'b' && ep->key[1] == 's' && ep->key[2] == 'p')
+ {
+ SendDlgItemMessage(hwndDlg, IDC_CMD_LIST, LB_ADDSTRING, i , (LPARAM) ep->key);
+ i++;
+ }
+ }
+}
+
+
+// FIXME: turn this into an MFC dialog
+BOOL CALLBACK ProjectDlgProc (
+ HWND hwndDlg, // handle to dialog box
+ UINT uMsg, // message
+ WPARAM wParam, // first message parameter
+ LPARAM lParam // second message parameter
+ )
+{
+ char key[1024];
+ char value[1024];
+ int index;
+
+ switch (uMsg)
+ {
+ case WM_INITDIALOG:
+ SetDlgItemText(hwndDlg, IDC_PRJBASEPATH, ValueForKey (g_qeglobals.d_project_entity, "basepath"));
+ SetDlgItemText(hwndDlg, IDC_PRJMAPSPATH, ValueForKey (g_qeglobals.d_project_entity, "mapspath"));
+ SetDlgItemText(hwndDlg, IDC_PRJRSHCMD, ValueForKey (g_qeglobals.d_project_entity, "rshcmd"));
+ SetDlgItemText(hwndDlg, IDC_PRJREMOTEBASE, ValueForKey (g_qeglobals.d_project_entity, "remotebasepath"));
+ SetDlgItemText(hwndDlg, IDC_PRJENTITYPATH, ValueForKey (g_qeglobals.d_project_entity, "entitypath"));
+ SetDlgItemText(hwndDlg, IDC_PRJTEXPATH, ValueForKey (g_qeglobals.d_project_entity, "texturepath"));
+ UpdateBSPCommandList (hwndDlg);
+ // Timo
+ // additional fields
+ CheckDlgButton( hwndDlg, IDC_CHECK_BPRIMIT, (g_qeglobals.m_bBrushPrimitMode) ? BST_CHECKED : BST_UNCHECKED );
+// SendMessage( ::GetDlgItem( hwndDlg, IDC_CHECK_BPRIMIT ), BM_SETCHECK, (WPARAM) g_qeglobals.m_bBrushPrimitMode, 0 );
+ return TRUE;
+
+ case WM_COMMAND:
+ switch (LOWORD(wParam))
+ {
+ case IDC_ADDCMD:
+// DialogBox(g_qeglobals.d_hInstance, (char *)IDD_ADDCMD, g_qeglobals.d_hwndMain, AddCommandDlgProc);
+ DialogBox(g_qeglobals.d_hInstance, (char *)IDD_ADDCMD, hwndDlg, AddCommandDlgProc);
+ UpdateBSPCommandList (hwndDlg);
+ break;
+
+ case IDC_EDITCMD:
+// DialogBox(g_qeglobals.d_hInstance, (char *)IDD_ADDCMD, g_qeglobals.d_hwndMain, EditCommandDlgProc);
+ DialogBox(g_qeglobals.d_hInstance, (char *)IDD_ADDCMD, hwndDlg, EditCommandDlgProc);
+ UpdateBSPCommandList (hwndDlg);
+ break;
+
+ case IDC_REMCMD:
+ index = SendDlgItemMessage (hwndDlg, IDC_CMD_LIST, LB_GETCURSEL, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_CMD_LIST, LB_GETTEXT, index, (LPARAM) (LPCTSTR) key);
+ DeleteKey (g_qeglobals.d_project_entity, key);
+ Sys_Printf ("Selected %d\n", index);
+ UpdateBSPCommandList (hwndDlg);
+ break;
+
+ case IDOK:
+ GetDlgItemText(hwndDlg, IDC_PRJBASEPATH, value, 1024);
+ SetKeyValue (g_qeglobals.d_project_entity, "basepath", value);
+ GetDlgItemText(hwndDlg, IDC_PRJMAPSPATH, value, 1024);
+ SetKeyValue (g_qeglobals.d_project_entity, "mapspath", value);
+ GetDlgItemText(hwndDlg, IDC_PRJRSHCMD, value, 1024);
+ SetKeyValue (g_qeglobals.d_project_entity, "rshcmd", value);
+ GetDlgItemText(hwndDlg, IDC_PRJREMOTEBASE, value, 1024);
+ SetKeyValue (g_qeglobals.d_project_entity, "remotebasepath", value);
+ GetDlgItemText(hwndDlg, IDC_PRJENTITYPATH, value, 1024);
+ SetKeyValue (g_qeglobals.d_project_entity, "entitypath", value);
+ GetDlgItemText(hwndDlg, IDC_PRJTEXPATH, value, 1024);
+ SetKeyValue (g_qeglobals.d_project_entity, "texturepath", value);
+ // Timo
+ // read additional fields
+ if ( IsDlgButtonChecked( hwndDlg, IDC_CHECK_BPRIMIT ) )
+ {
+ g_qeglobals.m_bBrushPrimitMode = TRUE;
+ }
+ else
+ {
+ g_qeglobals.m_bBrushPrimitMode = FALSE;
+ }
+ SetKeyValue ( g_qeglobals.d_project_entity, "brush_primit", ( g_qeglobals.m_bBrushPrimitMode ? "1" : "0" ) );
+
+ EndDialog(hwndDlg, 1);
+ QE_SaveProject(g_strProject);
+ return TRUE;
+
+ case IDCANCEL:
+ EndDialog(hwndDlg, 0);
+ return TRUE;
+ }
+ }
+ return FALSE;
+}
+
+void DoProjectSettings()
+{
+ DialogBox(g_qeglobals.d_hInstance, (char *)IDD_PROJECT, g_qeglobals.d_hwndMain, ProjectDlgProc);
+}
+
+
+
+BOOL CALLBACK GammaDlgProc (
+ HWND hwndDlg, // handle to dialog box
+ UINT uMsg, // message
+ WPARAM wParam, // first message parameter
+ LPARAM lParam // second message parameter
+ )
+{
+ char sz[256];
+
+ switch (uMsg)
+ {
+ case WM_INITDIALOG:
+ sprintf(sz, "%1.1f", g_qeglobals.d_savedinfo.fGamma);
+ SetWindowText(GetDlgItem(hwndDlg, IDC_G_EDIT), sz);
+ return TRUE;
+ case WM_COMMAND:
+ switch (LOWORD(wParam))
+ {
+
+ case IDOK:
+ GetWindowText(GetDlgItem(hwndDlg, IDC_G_EDIT), sz, 255);
+ g_qeglobals.d_savedinfo.fGamma = atof(sz);
+ EndDialog(hwndDlg, 1);
+ return TRUE;
+
+ case IDCANCEL:
+ EndDialog(hwndDlg, 0);
+ return TRUE;
+ }
+ }
+ return FALSE;
+}
+
+
+
+void DoGamma(void)
+{
+ if ( DialogBox(g_qeglobals.d_hInstance, (char *)IDD_GAMMA, g_qeglobals.d_hwndMain, GammaDlgProc))
+ {
+ }
+}
+
+//================================================
+
+
+void SelectBrush (int entitynum, int brushnum)
+{
+ entity_t *e;
+ brush_t *b;
+ int i;
+
+ if (entitynum == 0)
+ e = world_entity;
+ else
+ {
+ e = entities.next;
+ while (--entitynum)
+ {
+ e=e->next;
+ if (e == &entities)
+ {
+ Sys_Status ("No such entity.", 0);
+ return;
+ }
+ }
+ }
+
+ b = e->brushes.onext;
+ if (b == &e->brushes)
+ {
+ Sys_Status ("No such brush.", 0);
+ return;
+ }
+ while (brushnum--)
+ {
+ b=b->onext;
+ if (b == &e->brushes)
+ {
+ Sys_Status ("No such brush.", 0);
+ return;
+ }
+ }
+
+ Brush_RemoveFromList (b);
+ Brush_AddToList (b, &selected_brushes);
+
+
+ Sys_UpdateWindows (W_ALL);
+ for (i=0 ; i<3 ; i++)
+ {
+ if (g_pParentWnd->GetXYWnd())
+ g_pParentWnd->GetXYWnd()->GetOrigin()[i] = (b->mins[i] + b->maxs[i])/2;
+
+ if (g_pParentWnd->GetXZWnd())
+ g_pParentWnd->GetXZWnd()->GetOrigin()[i] = (b->mins[i] + b->maxs[i])/2;
+
+ if (g_pParentWnd->GetYZWnd())
+ g_pParentWnd->GetYZWnd()->GetOrigin()[i] = (b->mins[i] + b->maxs[i])/2;
+ }
+
+ Sys_Status ("Selected.", 0);
+}
+
+/*
+=================
+GetSelectionIndex
+=================
+*/
+void GetSelectionIndex (int *ent, int *brush)
+{
+ brush_t *b, *b2;
+ entity_t *entity;
+
+ *ent = *brush = 0;
+
+ b = selected_brushes.next;
+ if (b == &selected_brushes)
+ return;
+
+ // find entity
+ if (b->owner != world_entity)
+ {
+ (*ent)++;
+ for (entity = entities.next ; entity != &entities
+ ; entity=entity->next, (*ent)++)
+ ;
+ }
+
+ // find brush
+ for (b2=b->owner->brushes.onext
+ ; b2 != b && b2 != &b->owner->brushes
+ ; b2=b2->onext, (*brush)++)
+ ;
+}
+
+BOOL CALLBACK FindBrushDlgProc (
+ HWND hwndDlg, // handle to dialog box
+ UINT uMsg, // message
+ WPARAM wParam, // first message parameter
+ LPARAM lParam // second message parameter
+ )
+{
+ char entstr[256];
+ char brushstr[256];
+ HWND h;
+ int ent, brush;
+
+ switch (uMsg)
+ {
+ case WM_INITDIALOG:
+ // set entity and brush number
+ GetSelectionIndex (&ent, &brush);
+ sprintf (entstr, "%i", ent);
+ sprintf (brushstr, "%i", brush);
+ SetWindowText(GetDlgItem(hwndDlg, IDC_FIND_ENTITY), entstr);
+ SetWindowText(GetDlgItem(hwndDlg, IDC_FIND_BRUSH), brushstr);
+
+ h = GetDlgItem(hwndDlg, IDC_FIND_ENTITY);
+ SetFocus (h);
+ return FALSE;
+
+ case WM_COMMAND:
+ switch (LOWORD(wParam))
+ {
+ case IDOK:
+ GetWindowText(GetDlgItem(hwndDlg, IDC_FIND_ENTITY), entstr, 255);
+ GetWindowText(GetDlgItem(hwndDlg, IDC_FIND_BRUSH), brushstr, 255);
+ SelectBrush (atoi(entstr), atoi(brushstr));
+ EndDialog(hwndDlg, 1);
+ return TRUE;
+
+ case IDCANCEL:
+ EndDialog(hwndDlg, 0);
+ return TRUE;
+ }
+ }
+ return FALSE;
+}
+
+
+
+void DoFind(void)
+{
+ DialogBox(g_qeglobals.d_hInstance, (char *)IDD_FINDBRUSH, g_qeglobals.d_hwndMain, FindBrushDlgProc);
+}
+
+/*
+===================================================
+
+ ARBITRARY ROTATE
+
+===================================================
+*/
+
+
+BOOL CALLBACK RotateDlgProc (
+ HWND hwndDlg, // handle to dialog box
+ UINT uMsg, // message
+ WPARAM wParam, // first message parameter
+ LPARAM lParam // second message parameter
+ )
+{
+ char str[256];
+ HWND h;
+ float v;
+
+ switch (uMsg)
+ {
+ case WM_INITDIALOG:
+ h = GetDlgItem(hwndDlg, IDC_FIND_ENTITY);
+ SetFocus (h);
+ return FALSE;
+
+ case WM_COMMAND:
+ switch (LOWORD(wParam))
+ {
+
+ case IDOK:
+ GetWindowText(GetDlgItem(hwndDlg, IDC_ROTX), str, 255);
+ v = atof(str);
+ if (v)
+ Select_RotateAxis (0, v);
+
+ GetWindowText(GetDlgItem(hwndDlg, IDC_ROTY), str, 255);
+ v = atof(str);
+ if (v)
+ Select_RotateAxis (1, v);
+
+ GetWindowText(GetDlgItem(hwndDlg, IDC_ROTZ), str, 255);
+ v = atof(str);
+ if (v)
+ Select_RotateAxis (2, v);
+
+ EndDialog(hwndDlg, 1);
+ return TRUE;
+
+ case IDCANCEL:
+ EndDialog(hwndDlg, 0);
+ return TRUE;
+ }
+ }
+
+ return FALSE;
+}
+
+
+
+void DoRotate(void)
+{
+ DialogBox(g_qeglobals.d_hInstance, (char *)IDD_ROTATE, g_qeglobals.d_hwndMain, RotateDlgProc);
+}
+
+/*
+===================================================
+
+ ARBITRARY SIDES
+
+===================================================
+*/
+
+bool g_bDoCone = false;
+bool g_bDoSphere = false;
+BOOL CALLBACK SidesDlgProc (
+ HWND hwndDlg, // handle to dialog box
+ UINT uMsg, // message
+ WPARAM wParam, // first message parameter
+ LPARAM lParam // second message parameter
+ )
+{
+ char str[256];
+ HWND h;
+
+ switch (uMsg)
+ {
+ case WM_INITDIALOG:
+ h = GetDlgItem(hwndDlg, IDC_SIDES);
+ SetFocus (h);
+ return FALSE;
+
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+
+ case IDOK:
+ GetWindowText(GetDlgItem(hwndDlg, IDC_SIDES), str, 255);
+ if (g_bDoCone)
+ Brush_MakeSidedCone(atoi(str));
+ else if (g_bDoSphere)
+ Brush_MakeSidedSphere(atoi(str));
+ else
+ Brush_MakeSided (atoi(str));
+
+ EndDialog(hwndDlg, 1);
+ break;
+
+ case IDCANCEL:
+ EndDialog(hwndDlg, 0);
+ break;
+ }
+ default:
+ return FALSE;
+ }
+}
+
+
+void DoSides(bool bCone, bool bSphere, bool bTorus)
+{
+ g_bDoCone = bCone;
+ g_bDoSphere = bSphere;
+ //g_bDoTorus = bTorus;
+ DialogBox(g_qeglobals.d_hInstance, (char *)IDD_SIDES, g_qeglobals.d_hwndMain, SidesDlgProc);
+}
+
+
+//======================================================================
+
+/*
+===================
+DoAbout
+===================
+*/
+BOOL CALLBACK AboutDlgProc( HWND hwndDlg,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam )
+{
+ switch (uMsg)
+ {
+ case WM_INITDIALOG:
+ {
+ char renderer[1024];
+ char version[1024];
+ char vendor[1024];
+ char extensions[4096];
+
+ sprintf( renderer, "Renderer:\t%s", qglGetString( GL_RENDERER ) );
+ sprintf( version, "Version:\t\t%s", qglGetString( GL_VERSION ) );
+ sprintf( vendor, "Vendor:\t\t%s", qglGetString( GL_VENDOR ) );
+ sprintf( extensions, "%s", qglGetString( GL_EXTENSIONS ) );
+
+ SetWindowText( GetDlgItem( hwndDlg, IDC_ABOUT_GLRENDERER ), renderer );
+ SetWindowText( GetDlgItem( hwndDlg, IDC_ABOUT_GLVERSION ), version );
+ SetWindowText( GetDlgItem( hwndDlg, IDC_ABOUT_GLVENDOR ), vendor );
+ SetWindowText( GetDlgItem( hwndDlg, IDC_ABOUT_GLEXTENSIONS ), extensions );
+
+ }
+ return TRUE;
+
+ case WM_CLOSE:
+ EndDialog( hwndDlg, 1 );
+ return TRUE;
+
+ case WM_COMMAND:
+ if ( LOWORD( wParam ) == IDOK )
+ EndDialog(hwndDlg, 1);
+ return TRUE;
+ }
+ return FALSE;
+}
+
+void DoAbout(void)
+{
+ DialogBox( g_qeglobals.d_hInstance, ( char * ) IDD_ABOUT, g_qeglobals.d_hwndMain, AboutDlgProc );
+}
+
+
diff --git a/q3radiant/WIN_QE3.CPP b/q3radiant/WIN_QE3.CPP
new file mode 100755
index 0000000..86cad56
--- /dev/null
+++ b/q3radiant/WIN_QE3.CPP
@@ -0,0 +1,753 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "stdafx.h"
+#include "qe3.h"
+#include "mru.h"
+#include "PrefsDlg.h"
+
+////////////////////////////////////////////////////////////////////////////
+// BSP frontend plugin
+// global flag for BSP frontend plugin is g_qeglobals.bBSPFrontendPlugin
+_QERPlugBSPFrontendTable g_BSPFrontendTable;
+CStringArray g_BSPFrontendCommands;
+
+extern CEdit* g_pEdit;
+
+int screen_width;
+int screen_height;
+qboolean have_quit;
+
+int update_bits;
+
+HANDLE bsp_process;
+
+//===========================================
+
+void Sys_MarkMapModified (void)
+{
+ char title[1024];
+
+ if (modified != 1)
+ {
+ modified = true; // mark the map as changed
+ sprintf (title, "%s *", currentmap);
+
+ QE_ConvertDOSToUnixName( title, title );
+ Sys_SetTitle (title);
+ }
+}
+
+
+void Sys_SetTitle (char *text)
+{
+ SetWindowText (g_qeglobals.d_hwndMain, text);
+}
+
+HCURSOR waitcursor;
+
+void Sys_BeginWait (void)
+{
+ waitcursor = SetCursor (LoadCursor (NULL, IDC_WAIT));
+}
+
+void Sys_EndWait (void)
+{
+ if (waitcursor)
+ {
+ SetCursor (waitcursor);
+ waitcursor = NULL;
+ }
+}
+
+
+void Sys_GetCursorPos (int *x, int *y)
+{
+ POINT lpPoint;
+
+ GetCursorPos (&lpPoint);
+ *x = lpPoint.x;
+ *y = lpPoint.y;
+}
+
+void Sys_SetCursorPos (int x, int y)
+{
+ SetCursorPos (x, y);
+}
+
+
+void Sys_Beep (void)
+{
+ MessageBeep (MB_ICONASTERISK);
+}
+
+char *TranslateString (char *buf)
+{
+ static char buf2[32768];
+ int i, l;
+ char *out;
+
+ l = strlen(buf);
+ out = buf2;
+ for (i=0 ; i<l ; i++)
+ {
+ if (buf[i] == '\n')
+ {
+ *out++ = '\r';
+ *out++ = '\n';
+ }
+ else
+ *out++ = buf[i];
+ }
+ *out++ = 0;
+
+ return buf2;
+}
+
+
+void Sys_ClearPrintf (void)
+{
+ char text[4];
+ text[0] = 0;
+
+ SendMessage (g_qeglobals.d_hwndEdit, WM_SETTEXT, 0, (LPARAM)text);
+}
+
+
+#define SCROLLBACK_MAX_LINES 600
+#define SCROLLBACK_DEL_CHARS 500
+
+void Sys_Printf (char *text, ...)
+{
+ va_list argptr;
+ char buf[32768];
+ char *out;
+ LRESULT result; // PGM
+ DWORD oldPosS, oldPosE; // PGM
+
+ va_start (argptr,text);
+ vsprintf (buf, text,argptr);
+ va_end (argptr);
+
+ out = TranslateString (buf);
+
+#ifdef LATER
+ Sys_Status(out);
+#else
+//PGM
+ result = SendMessage (g_qeglobals.d_hwndEdit, EM_GETLINECOUNT, 0, 0);
+ if(result > SCROLLBACK_MAX_LINES)
+ {
+ char replaceText[5];
+
+ replaceText[0] = '\0';
+
+ SendMessage (g_qeglobals.d_hwndEdit, WM_SETREDRAW, (WPARAM)0, (LPARAM)0);
+ SendMessage (g_qeglobals.d_hwndEdit, EM_GETSEL, (WPARAM)&oldPosS, (LPARAM)&oldPosE);
+ SendMessage (g_qeglobals.d_hwndEdit, EM_SETSEL, 0, SCROLLBACK_DEL_CHARS);
+ SendMessage (g_qeglobals.d_hwndEdit, EM_REPLACESEL, (WPARAM)0, (LPARAM)replaceText);
+ SendMessage (g_qeglobals.d_hwndEdit, EM_SETSEL, oldPosS, oldPosE);
+ SendMessage (g_qeglobals.d_hwndEdit, WM_SETREDRAW, (WPARAM)1, (LPARAM)0);
+ }
+//PGM
+
+ SendMessage (g_qeglobals.d_hwndEdit, EM_REPLACESEL, 0, (LPARAM)out);
+#endif
+
+}
+
+
+double Sys_DoubleTime (void)
+{
+ return clock()/ 1000.0;
+}
+
+void PrintPixels (HDC hDC)
+{
+ int i;
+ PIXELFORMATDESCRIPTOR p[64];
+
+ printf ("### flags color layer\n");
+ for (i=1 ; i<64 ; i++)
+ {
+ if (!DescribePixelFormat ( hDC, i, sizeof(p[0]), &p[i]))
+ break;
+ printf ("%3i %5i %5i %5i\n", i,
+ p[i].dwFlags,
+ p[i].cColorBits,
+ p[i].bReserved);
+ }
+ printf ("%i modes\n", i-1);
+}
+
+
+
+//==========================================================================
+
+void QEW_StopGL( HWND hWnd, HGLRC hGLRC, HDC hDC )
+{
+ qwglMakeCurrent( NULL, NULL );
+ qwglDeleteContext( hGLRC );
+ ReleaseDC( hWnd, hDC );
+}
+
+int WINAPI QEW_SetupPixelFormat(HDC hDC, qboolean zbuffer )
+{
+ static PIXELFORMATDESCRIPTOR pfd = {
+ sizeof(PIXELFORMATDESCRIPTOR), // size of this pfd
+ 1, // version number
+ PFD_DRAW_TO_WINDOW | // support window
+ PFD_SUPPORT_OPENGL | // support OpenGL
+ PFD_DOUBLEBUFFER, // double buffered
+ PFD_TYPE_RGBA, // RGBA type
+ 24, // 24-bit color depth
+ 0, 0, 0, 0, 0, 0, // color bits ignored
+ 0, // no alpha buffer
+ 0, // shift bit ignored
+ 0, // no accumulation buffer
+ 0, 0, 0, 0, // accum bits ignored
+ 32, // depth bits
+ 0, // no stencil buffer
+ 0, // no auxiliary buffer
+ PFD_MAIN_PLANE, // main layer
+ 0, // reserved
+ 0, 0, 0 // layer masks ignored
+ }; //
+ int pixelformat = 0;
+
+ zbuffer = true;
+ if ( !zbuffer )
+ pfd.cDepthBits = 0;
+
+ if (g_PrefsDlg.m_bSGIOpenGL)
+ {
+ if ( (pixelformat = qwglChoosePixelFormat(hDC, &pfd)) == 0 )
+ {
+ printf("%d",GetLastError());
+ Error ("ChoosePixelFormat failed");
+ }
+
+ if (!qwglSetPixelFormat(hDC, pixelformat, &pfd))
+ Error ("SetPixelFormat failed");
+ }
+ else
+ {
+ if ( (pixelformat = ChoosePixelFormat(hDC, &pfd)) == 0 )
+ {
+ printf("%d",GetLastError());
+ Error ("ChoosePixelFormat failed");
+ }
+
+ if (!SetPixelFormat(hDC, pixelformat, &pfd))
+ Error ("SetPixelFormat failed");
+ }
+
+ return pixelformat;
+}
+
+/*
+=================
+Error
+
+For abnormal program terminations
+=================
+*/
+void Error (char *error, ...)
+{
+ va_list argptr;
+ char text[1024];
+ char text2[1024];
+ int err;
+
+ err = GetLastError ();
+ int i = qglGetError();
+
+ va_start (argptr,error);
+ vsprintf (text, error,argptr);
+ va_end (argptr);
+
+ sprintf (text2, "%s\nGetLastError() = %i - %i\nAn unrecoverable error has occured. Would you like to edit Preferences before exiting Q3Radiant?", text, err, i);
+
+ if (MessageBox(g_qeglobals.d_hwndMain, text2, "Error", MB_YESNO) == IDYES)
+ {
+ g_PrefsDlg.LoadPrefs();
+ g_PrefsDlg.DoModal();
+ }
+
+ exit (1);
+}
+
+
+void Warning (char *error, ...)
+{
+ va_list argptr;
+ char text[1024];
+ int err;
+
+ err = GetLastError ();
+ int i = qglGetError();
+
+ va_start (argptr,error);
+ vsprintf (text, error,argptr);
+ va_end (argptr);
+
+ Sys_Printf(text);
+}
+
+
+/*
+======================================================================
+
+FILE DIALOGS
+
+======================================================================
+*/
+
+qboolean ConfirmModified (void)
+{
+ if (!modified)
+ return true;
+
+ if (MessageBox (g_qeglobals.d_hwndMain, "This will lose changes to the map"
+ , "warning", MB_OKCANCEL) == IDCANCEL)
+ return false;
+ return true;
+}
+
+static OPENFILENAME ofn; /* common dialog box structure */
+static char szDirName[MAX_PATH]; /* directory string */
+static char szFile[260]; /* filename string */
+static char szFileTitle[260]; /* file title string */
+static char szFilter[260] = /* filter string */
+ "Map file (*.map, *.reg)\0*.map\0*.reg\0\0";
+static char szProjectFilter[260] = /* filter string */
+ "Q3Radiant project (*.qe4, *.prj)\0*.qe4\0*.prj\0\0";
+static char chReplace; /* string separator for szFilter */
+static int i, cbString; /* integer count variables */
+static HANDLE hf; /* file handle */
+
+void OpenDialog (void)
+{
+ /*
+ * Obtain the system directory name and
+ * store it in szDirName.
+ */
+
+ strcpy (szDirName, ValueForKey (g_qeglobals.d_project_entity, "mapspath") );
+ if (strlen(szDirName) == 0)
+ {
+ strcpy (szDirName, ValueForKey (g_qeglobals.d_project_entity, "basepath") );
+ strcat (szDirName, "\\maps");
+ }
+
+ /* Place the terminating null character in the szFile. */
+
+ szFile[0] = '\0';
+
+ /* Set the members of the OPENFILENAME structure. */
+
+ ofn.lStructSize = sizeof(OPENFILENAME);
+ ofn.hwndOwner = g_qeglobals.d_hwndCamera;
+ ofn.lpstrFilter = szFilter;
+ ofn.nFilterIndex = 1;
+ ofn.lpstrFile = szFile;
+ ofn.nMaxFile = sizeof(szFile);
+ ofn.lpstrFileTitle = szFileTitle;
+ ofn.nMaxFileTitle = sizeof(szFileTitle);
+ ofn.lpstrInitialDir = szDirName;
+ ofn.Flags = OFN_SHOWHELP | OFN_PATHMUSTEXIST |
+ OFN_FILEMUSTEXIST;
+
+ /* Display the Open dialog box. */
+
+ if (!GetOpenFileName(&ofn))
+ return; // canceled
+
+ // Add the file in MRU.
+ //FIXME
+ AddNewItem( g_qeglobals.d_lpMruMenu, ofn.lpstrFile);
+
+ // Refresh the File menu.
+ //FIXME
+ PlaceMenuMRUItem(g_qeglobals.d_lpMruMenu,GetSubMenu(GetMenu(g_qeglobals.d_hwndMain),0),
+ ID_FILE_EXIT);
+
+ /* Open the file. */
+
+ Map_LoadFile (ofn.lpstrFile);
+}
+
+void ProjectDialog (void)
+{
+ /*
+ * Obtain the system directory name and
+ * store it in szDirName.
+ */
+
+ strcpy (szDirName, ValueForKey(g_qeglobals.d_project_entity, "basepath") );
+ strcat (szDirName, "\\scripts");
+
+ /* Place the terminating null character in the szFile. */
+
+ szFile[0] = '\0';
+
+ /* Set the members of the OPENFILENAME structure. */
+
+ ofn.lStructSize = sizeof(OPENFILENAME);
+ ofn.hwndOwner = g_qeglobals.d_hwndCamera;
+ ofn.lpstrFilter = szProjectFilter;
+ ofn.nFilterIndex = 1;
+ ofn.lpstrFile = szFile;
+ ofn.nMaxFile = sizeof(szFile);
+ ofn.lpstrFileTitle = szFileTitle;
+ ofn.nMaxFileTitle = sizeof(szFileTitle);
+ ofn.lpstrInitialDir = szDirName;
+ ofn.Flags = OFN_SHOWHELP | OFN_PATHMUSTEXIST |
+ OFN_FILEMUSTEXIST;
+
+ /* Display the Open dialog box. */
+
+ if (!GetOpenFileName(&ofn))
+ return; // canceled
+
+ // Refresh the File menu.
+ PlaceMenuMRUItem(g_qeglobals.d_lpMruMenu,GetSubMenu(GetMenu(g_qeglobals.d_hwndMain),0),
+ ID_FILE_EXIT);
+
+ /* Open the file. */
+ if (!QE_LoadProject(ofn.lpstrFile))
+ Error ("Couldn't load project file");
+}
+
+
+extern void AddSlash(CString& strPath);
+void SaveAsDialog (bool bRegion)
+{
+ strcpy (szDirName, ValueForKey (g_qeglobals.d_project_entity, "basepath") );
+ CString strPath = szDirName;
+ AddSlash(strPath);
+ strPath += "maps";
+
+ /* Place the terminating null character in the szFile. */
+
+ szFile[0] = '\0';
+
+ /* Set the members of the OPENFILENAME structure. */
+
+ ofn.lStructSize = sizeof(OPENFILENAME);
+ ofn.hwndOwner = g_qeglobals.d_hwndCamera;
+ ofn.lpstrFilter = szFilter;
+ ofn.nFilterIndex = 1;
+ ofn.lpstrFile = szFile;
+ ofn.nMaxFile = sizeof(szFile);
+ ofn.lpstrFileTitle = szFileTitle;
+ ofn.nMaxFileTitle = sizeof(szFileTitle);
+ ofn.lpstrInitialDir = strPath;
+ ofn.Flags = OFN_SHOWHELP | OFN_PATHMUSTEXIST |
+ OFN_FILEMUSTEXIST | OFN_OVERWRITEPROMPT;
+
+ /* Display the Open dialog box. */
+
+ if (!GetSaveFileName(&ofn))
+ return; // canceled
+
+ if (bRegion)
+ DefaultExtension (ofn.lpstrFile, ".reg");
+ else
+ DefaultExtension (ofn.lpstrFile, ".map");
+
+ if (!bRegion)
+ {
+ strcpy (currentmap, ofn.lpstrFile);
+ AddNewItem(g_qeglobals.d_lpMruMenu, ofn.lpstrFile);
+ PlaceMenuMRUItem(g_qeglobals.d_lpMruMenu,GetSubMenu(GetMenu(g_qeglobals.d_hwndMain),0), ID_FILE_EXIT);
+ }
+ Map_SaveFile (ofn.lpstrFile, bRegion); // ignore region
+}
+
+/*
+=======================================================
+
+Menu modifications
+
+=======================================================
+*/
+
+/*
+==================
+FillBSPMenu
+
+==================
+*/
+char *bsp_commands[256];
+
+void FillBSPMenu (void)
+{
+ HMENU hmenu;
+ epair_t *ep;
+ int i;
+ static int count;
+
+ hmenu = GetSubMenu (GetMenu(g_qeglobals.d_hwndMain), MENU_BSP);
+
+ for (i=0 ; i<count ; i++)
+ DeleteMenu (hmenu, CMD_BSPCOMMAND+i, MF_BYCOMMAND);
+ count = 0;
+
+ if ( g_qeglobals.bBSPFrontendPlugin )
+ {
+ CString str = g_BSPFrontendTable.m_pfnGetBSPMenu();
+ char cTemp[1024];
+ strcpy(cTemp, str);
+ char* token = strtok(cTemp, ",;");
+ if (token && *token == ' ')
+ {
+ while (*token == ' ')
+ token++;
+ }
+ i = 0;
+ // first token is menu name
+ ModifyMenu( GetMenu(g_qeglobals.d_hwndMain), MENU_BSP, MF_BYPOSITION, MENU_BSP, (LPCTSTR)token );
+ // redraw the menu bar
+ DrawMenuBar( g_qeglobals.d_hwndMain );
+ token = strtok(NULL, ",;");
+ while (token != NULL)
+ {
+ g_BSPFrontendCommands.Add(token);
+ AppendMenu (hmenu, MF_ENABLED|MF_STRING, CMD_BSPCOMMAND+i, (LPCTSTR)token );
+ token = strtok(NULL, ",;");
+ i++;
+ }
+ count = i;
+ }
+ else
+ {
+ i = 0;
+ for (ep = g_qeglobals.d_project_entity->epairs ; ep ; ep=ep->next)
+ {
+ if (ep->key[0] == 'b' && ep->key[1] == 's' && ep->key[2] == 'p')
+ {
+ bsp_commands[i] = ep->key;
+ AppendMenu (hmenu, MF_ENABLED|MF_STRING,
+ CMD_BSPCOMMAND+i, (LPCTSTR)ep->key);
+ i++;
+ }
+ }
+ count = i;
+ }
+}
+
+//==============================================
+void AddSlash(CString& strPath)
+{
+ if (strPath.GetLength() > 0)
+ {
+ if (strPath.GetAt(strPath.GetLength()-1) != '\\')
+ strPath += '\\';
+ }
+}
+
+
+bool ExtractPath_and_Filename(const char* pPath, CString& strPath, CString& strFilename)
+{
+ CString strPathName = pPath;
+ int nSlash = strPathName.ReverseFind('\\');
+ if (nSlash >= 0)
+ {
+ strPath = strPathName.Left(nSlash+1);
+ strFilename = strPathName.Right(strPathName.GetLength() - nSlash - 1);
+ }
+ else strFilename = pPath;
+ return true;
+}
+
+
+/*
+===============
+CheckBspProcess
+
+See if the BSP is done yet
+===============
+*/
+extern void FindReplace(CString& strContents, const char* pTag, const char* pValue);
+extern CTime g_tBegin;
+
+void CheckBspProcess (void)
+{
+ char outputpath[1024];
+ char temppath[512];
+ DWORD exitcode;
+ char *out;
+ BOOL ret;
+
+ if (!bsp_process)
+ return;
+
+ ret = GetExitCodeProcess (bsp_process, &exitcode);
+ if (!ret)
+ Error ("GetExitCodeProcess failed");
+ if (exitcode == STILL_ACTIVE)
+ return;
+
+ bsp_process = 0;
+
+ GetTempPath(512, temppath);
+ sprintf (outputpath, "%sjunk.txt", temppath);
+
+ LoadFile (outputpath, (void **)&out);
+ Sys_Printf ("%s", out);
+ Sys_Printf ("\ncompleted.\n");
+ free (out);
+
+ CTime tEnd = CTime::GetCurrentTime();
+ CTimeSpan tElapsed = tEnd - g_tBegin;
+ CString strElapsed;
+ strElapsed.Format("Run time was %i hours, %i minutes and %i seconds", tElapsed.GetHours(), tElapsed.GetMinutes(), tElapsed.GetSeconds());
+ Sys_Printf(strElapsed.GetBuffer(0));
+
+
+ Sys_Beep ();
+ Pointfile_Check();
+ // run game if no PointFile and pref is set
+ //++timo needs to stop after BSP if leaked .. does run through vis and light instead ..
+ if (g_PrefsDlg.m_bRunQuake == TRUE && !g_qeglobals.d_pointfile_display_list)
+ {
+ char cCurDir[1024];
+ GetCurrentDirectory(1024, cCurDir);
+ CString strExePath = g_PrefsDlg.m_strQuake2;
+ CString strOrgPath;
+ CString strOrgFile;
+ ExtractPath_and_Filename(currentmap, strOrgPath, strOrgFile);
+ if (g_PrefsDlg.m_bSetGame == TRUE) // run in place with set game.. don't copy map
+ {
+ CString strBasePath = ValueForKey(g_qeglobals.d_project_entity, "basepath");
+ strExePath += " +set game ";
+ strExePath += strBasePath;
+ WinExec(strExePath, SW_SHOW);
+ }
+ else
+ {
+ CString strCopyPath = strExePath;
+ char* pBuffer = strCopyPath.GetBufferSetLength(_MAX_PATH + 1);
+ pBuffer[strCopyPath.ReverseFind('\\') + 1] = '\0';
+ strCopyPath.ReleaseBuffer();
+ SetCurrentDirectory(strCopyPath);
+ CString strOrgPath;
+ CString strOrgFile;
+ ExtractPath_and_Filename(currentmap, strOrgPath, strOrgFile);
+ AddSlash(strCopyPath);
+ FindReplace(strOrgFile, ".map", ".bsp");
+ //++timo modified for Quake3 !!
+ strCopyPath += "baseq3\\maps\\";
+ strCopyPath += strOrgFile;
+ AddSlash(strOrgPath);
+ strOrgPath += strOrgFile;
+ bool bRun = (strOrgPath.CompareNoCase(strCopyPath) == 0);
+ if (!bRun)
+ bRun = (CopyFile(strOrgPath, strCopyPath, FALSE) == TRUE);
+ if (bRun)
+ {
+ FindReplace(strOrgFile, ".bsp", "");
+ strExePath += " +map ";
+ strExePath += strOrgFile;
+ WinExec(strExePath, SW_SHOW);
+ }
+ }
+ SetCurrentDirectory(cCurDir);
+ }
+}
+
+extern int cambuttonstate;
+
+extern "C" {
+void *Com_Allocate( int bytes ) {
+ return malloc(bytes);
+}
+
+void Com_Dealloc( void *ptr ) {
+ free(ptr);
+}
+
+
+void Com_Printf( const char *msg, ... ) {
+ va_list argptr;
+ char buf[32768];
+ char *out;
+
+ va_start (argptr,msg);
+ vsprintf (buf, msg,argptr);
+ va_end (argptr);
+
+ out = TranslateString (buf);
+
+ Sys_Printf(buf);
+}
+
+void Com_Error( int level, const char *error, ... ) {
+ va_list argptr;
+ char buf[32768];
+ char *out;
+
+ va_start (argptr,error);
+ vsprintf (buf, error,argptr);
+ va_end (argptr);
+
+ out = TranslateString (buf);
+
+ Sys_Printf(buf);
+}
+
+void Com_DPrintf( const char *msg, ... ) {
+ return;
+}
+
+int FS_Write( const void *buffer, int len, fileHandle_t h ) {
+ SafeWrite(reinterpret_cast<FILE*>(h), buffer, len);
+ return len;
+}
+
+int FS_ReadFile( const char *qpath, void **buffer ) {
+ CString strPath = ValueForKey(g_qeglobals.d_project_entity, "basepath");
+ AddSlash(strPath);
+ strPath += qpath;
+ return LoadFile(strPath, buffer);
+}
+
+void FS_FreeFile( void *buffer ) {
+ Com_Dealloc(buffer);
+}
+
+fileHandle_t FS_FOpenFileWrite( const char *filename ) {
+ CString strPath = ValueForKey(g_qeglobals.d_project_entity, "basepath");
+ AddSlash(strPath);
+ strPath += filename;
+ // bad casting ptr to int
+ return reinterpret_cast<fileHandle_t>(SafeOpenWrite(strPath));
+}
+
+void FS_FCloseFile( fileHandle_t f ) {
+ fclose(reinterpret_cast<FILE*>(f));
+}
+
+
+
+}
+
diff --git a/q3radiant/WIN_QE3.RC2 b/q3radiant/WIN_QE3.RC2
new file mode 100755
index 0000000..2adb8fd
--- /dev/null
+++ b/q3radiant/WIN_QE3.RC2
@@ -0,0 +1,693 @@
+//Microsoft Developer Studio generated resource script.
+//
+#include "resource.h"
+
+#define APSTUDIO_READONLY_SYMBOLS
+/////////////////////////////////////////////////////////////////////////////
+//
+// Generated from the TEXTINCLUDE 2 resource.
+//
+#include "afxres.h"
+
+/////////////////////////////////////////////////////////////////////////////
+#undef APSTUDIO_READONLY_SYMBOLS
+
+/////////////////////////////////////////////////////////////////////////////
+// English (U.S.) resources
+
+#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
+#ifdef _WIN32
+LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
+#pragma code_page(1252)
+#endif //_WIN32
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Menu
+//
+
+IDR_MENU1 MENU DISCARDABLE
+BEGIN
+ POPUP "&File"
+ BEGIN
+ MENUITEM "&New", ID_FILE_NEW
+ MENUITEM "&Open", ID_FILE_OPEN
+ MENUITEM "&Save", ID_FILE_SAVE
+ MENUITEM "Save &as...", ID_FILE_SAVEAS
+ MENUITEM "&Pointfile", ID_FILE_POINTFILE
+ MENUITEM "Load &project", ID_FILE_LOADPROJECT
+ MENUITEM "E&xit", ID_FILE_EXIT
+ END
+ POPUP "&Edit"
+ BEGIN
+ MENUITEM "&Copy brush", ID_EDIT_COPYBRUSH, GRAYED
+ MENUITEM "&Paste brush", ID_EDIT_PASTEBRUSH, GRAYED
+ END
+ POPUP "&View"
+ BEGIN
+ MENUITEM "Texture View\tT", ID_VIEW_TEXTURE
+ MENUITEM "Console View\tO", ID_VIEW_CONSOLE
+ MENUITEM "Entity View\tN", ID_VIEW_ENTITY
+ MENUITEM SEPARATOR
+ MENUITEM "&Center\tEnd", ID_VIEW_CENTER
+ MENUITEM "&Up Floor\tPage Up", ID_VIEW_UPFLOOR
+ MENUITEM "&Down Floor\tPage Down", ID_VIEW_DOWNFLOOR
+ MENUITEM SEPARATOR
+ MENUITEM "&XY 100%", ID_VIEW_100
+ MENUITEM "XY Zoom &In\tDelete", ID_VIEW_ZOOMIN
+ MENUITEM "XY Zoom &Out\tInsert", ID_VIEW_ZOOMOUT
+ MENUITEM SEPARATOR
+ MENUITEM "Show &Names", ID_VIEW_SHOWNAMES, CHECKED
+ MENUITEM "Show Blocks", ID_VIEW_SHOWBLOCKS
+ MENUITEM "Show C&oordinates", ID_VIEW_SHOWCOORDINATES
+ , CHECKED
+ MENUITEM "Show &Entities", ID_VIEW_SHOWENT, CHECKED
+ MENUITEM "Show &Path", ID_VIEW_SHOWPATH, CHECKED
+ MENUITEM "Show &Lights", ID_VIEW_SHOWLIGHTS, CHECKED
+ MENUITEM "Show &Water", ID_VIEW_SHOWWATER, CHECKED
+ MENUITEM "Show Clip &Brush", ID_VIEW_SHOWCLIP, CHECKED
+ MENUITEM "Show Wor&ld", ID_VIEW_SHOWWORLD, CHECKED
+ MENUITEM "Show Detail\tctrl-D", ID_VIEW_SHOWDETAIL, CHECKED
+ MENUITEM SEPARATOR
+ MENUITEM "&Z 100%", ID_VIEW_Z100
+ MENUITEM "Z Zoo&m In\tctrl-Delete", ID_VIEW_ZZOOMIN
+ MENUITEM "Z Zoom O&ut\tctrl-Insert", ID_VIEW_ZZOOMOUT
+ END
+ POPUP "&Selection"
+ BEGIN
+ MENUITEM "Drag &Edges\tE", ID_SELECTION_DRAGEDGES
+ MENUITEM "Drag &Vertecies\tV", ID_SELECTION_DRAGVERTECIES
+ MENUITEM "&Clone\tspace", ID_SELECTION_CLONE
+ MENUITEM "Deselect\tEsc", ID_SELECTION_DESELECT
+ MENUITEM "&Delete\tBackspace", ID_SELECTION_DELETE
+ MENUITEM "Flip &X", ID_BRUSH_FLIPX
+ MENUITEM "Flip &Y", ID_BRUSH_FLIPY
+ MENUITEM "Flip &Z", ID_BRUSH_FLIPZ
+ MENUITEM "Rotate X", ID_BRUSH_ROTATEX
+ MENUITEM "Rotate Y", ID_BRUSH_ROTATEY
+ MENUITEM "Rotate Z", ID_BRUSH_ROTATEZ
+ MENUITEM "Arbitrary rotation", ID_SELECTION_ARBITRARYROTATION
+
+ MENUITEM "Make &Hollow", ID_SELECTION_MAKEHOLLOW
+ MENUITEM "CSG &Subtract", ID_SELECTION_CSGSUBTRACT
+ MENUITEM "Select Complete &Tall", ID_SELECTION_SELECTCOMPLETETALL
+
+ MENUITEM "Select T&ouching", ID_SELECTION_SELECTTOUCHING
+ MENUITEM "Select &Partial Tall", ID_SELECTION_SELECTPARTIALTALL
+
+ MENUITEM "Select &Inside", ID_SELECTION_SELECTINSIDE
+ MENUITEM "Connect entities\tCtrl-k", ID_SELECTION_CONNECT
+ MENUITEM "Ungroup entity", ID_SELECTION_UNGROUPENTITY
+ MENUITEM "Make detail\tCtrl-m", ID_SELECTION_MAKE_DETAIL
+ MENUITEM "Make structural", ID_SELECTION_MAKE_STRUCTURAL
+ END
+ POPUP "&Bsp"
+ BEGIN
+ MENUITEM SEPARATOR
+ END
+ POPUP "&Grid"
+ BEGIN
+ MENUITEM "Grid1\t&1", ID_GRID_1
+ MENUITEM "Grid2\t&2", ID_GRID_2
+ MENUITEM "Grid4\t&3", ID_GRID_4
+ MENUITEM "Grid8\t&4", ID_GRID_8, CHECKED
+ MENUITEM "Grid16\t&5", ID_GRID_16
+ MENUITEM "Grid32\t&6", ID_GRID_32
+ MENUITEM "Grid64\t&7", ID_GRID_64
+ END
+ POPUP "&Textures"
+ BEGIN
+ MENUITEM "Show In &Use\tU", ID_TEXTURES_SHOWINUSE
+ MENUITEM "&Surface inspector\tS", ID_TEXTURES_INSPECTOR
+ MENUITEM SEPARATOR
+ MENUITEM "&Wireframe", ID_TEXTURES_WIREFRAME
+ MENUITEM "&Flat shade", ID_TEXTURES_FLATSHADE
+ MENUITEM "&Nearest", ID_VIEW_NEAREST
+ MENUITEM "Nearest &Mipmap", ID_VIEW_NEARESTMIPMAP
+ MENUITEM "&Linear", ID_VIEW_LINEAR
+ MENUITEM "&Bilinear", ID_VIEW_BILINEAR
+ MENUITEM "B&ilinear Mipmap", ID_VIEW_BILINEARMIPMAP
+ MENUITEM "T&rilinear", ID_VIEW_TRILINEAR
+ MENUITEM SEPARATOR
+ END
+ POPUP "&Misc"
+ BEGIN
+ MENUITEM "&Benchmark", ID_MISC_BENCHMARK
+ POPUP "&Colors"
+ BEGIN
+ MENUITEM "&Texture Background", ID_TEXTUREBK
+ MENUITEM "Grid Background", ID_COLORS_XYBK
+ MENUITEM "Grid Major", ID_COLORS_MAJOR
+ MENUITEM "Grid Minor", ID_COLORS_MINOR
+ END
+ MENUITEM "&Gamma", ID_MISC_GAMMA
+ MENUITEM "Find brush", ID_MISC_FINDBRUSH
+ MENUITEM "Next leak spot\tctrl-l", ID_MISC_NEXTLEAKSPOT
+ MENUITEM "Previous leak spot\tctrl-p", ID_MISC_PREVIOUSLEAKSPOT
+ MENUITEM "&Print XY View", ID_MISC_PRINTXY
+ MENUITEM "&Select Entity Color\tK", ID_MISC_SELECTENTITYCOLOR
+ END
+ POPUP "&Region"
+ BEGIN
+ MENUITEM "&Off", ID_REGION_OFF
+ MENUITEM "&Set XY", ID_REGION_SETXY
+ MENUITEM "Set &Tall Brush", ID_REGION_SETTALLBRUSH
+ MENUITEM "Set &Brush", ID_REGION_SETBRUSH
+ MENUITEM "Set Se&lected Brushes", ID_REGION_SETSELECTION
+ END
+ POPUP "&Brush"
+ BEGIN
+ MENUITEM "3 sided\tctrl-3", ID_BRUSH_3SIDED
+ MENUITEM "4 sided\tctrl-4", ID_BRUSH_4SIDED
+ MENUITEM "5 sided\tctrl-5", ID_BRUSH_5SIDED
+ MENUITEM "6 sided\tctrl-6", ID_BRUSH_6SIDED
+ MENUITEM "7 sided\tctrl-7", ID_BRUSH_7SIDED
+ MENUITEM "8 sided\tctrl-8", ID_BRUSH_8SIDED
+ MENUITEM "9 sided\tctrl-9", ID_BRUSH_9SIDED
+ MENUITEM "Arbitrary sided", ID_BRUSH_ARBITRARYSIDED
+ END
+ POPUP "&Help"
+ BEGIN
+ MENUITEM "&About", ID_HELP_ABOUT
+ END
+END
+
+
+#ifdef APSTUDIO_INVOKED
+/////////////////////////////////////////////////////////////////////////////
+//
+// TEXTINCLUDE
+//
+
+1 TEXTINCLUDE DISCARDABLE
+BEGIN
+ "resource.h\0"
+END
+
+2 TEXTINCLUDE DISCARDABLE
+BEGIN
+ "#include ""afxres.h""\r\n"
+ "\0"
+END
+
+3 TEXTINCLUDE DISCARDABLE
+BEGIN
+ "\r\n"
+ "\0"
+END
+
+#endif // APSTUDIO_INVOKED
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Dialog
+//
+
+IDD_FINDTEXTURE DIALOG DISCARDABLE 0, 0, 129, 53
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Find Texture"
+FONT 8, "MS Sans Serif"
+BEGIN
+ DEFPUSHBUTTON "OK",IDOK,10,30,50,14
+ PUSHBUTTON "Cancel",IDCANCEL,70,30,50,14
+ EDITTEXT IDC_EDIT1,10,10,110,14,ES_AUTOHSCROLL
+END
+
+IDD_ENTITY DIALOGEX 0, 0, 234, 389
+STYLE DS_3DLOOK | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_CLIPSIBLINGS |
+ WS_CAPTION | WS_THICKFRAME
+EXSTYLE WS_EX_TOOLWINDOW | WS_EX_CLIENTEDGE
+CAPTION "Entity"
+FONT 8, "MS Sans Serif", 0, 0, 0x1
+BEGIN
+ LISTBOX IDC_E_LIST,5,5,180,99,LBS_SORT | LBS_NOINTEGRALHEIGHT |
+ LBS_WANTKEYBOARDINPUT | WS_VSCROLL | WS_TABSTOP,
+ WS_EX_CLIENTEDGE
+ EDITTEXT IDC_E_COMMENT,5,106,180,50,ES_MULTILINE | ES_READONLY |
+ WS_VSCROLL,WS_EX_CLIENTEDGE
+ PUSHBUTTON "135",IDC_E_135,5,290,15,15
+ PUSHBUTTON "180",IDC_E_180,5,305,15,15
+ PUSHBUTTON "225",IDC_E_225,5,320,15,15
+ PUSHBUTTON "270",IDC_E_270,21,320,15,15
+ PUSHBUTTON "90",IDC_E_90,21,290,15,15
+ PUSHBUTTON "45",IDC_E_45,35,290,15,15
+ PUSHBUTTON "0",IDC_E_0,35,305,15,15
+ PUSHBUTTON "315",IDC_E_315,35,320,15,15
+ PUSHBUTTON "Up",IDC_E_UP,60,295,15,15
+ PUSHBUTTON "Dn",IDC_E_DOWN,60,310,15,15
+ CONTROL "",IDC_CHECK1,"Button",BS_AUTOCHECKBOX | WS_DISABLED |
+ WS_TABSTOP,5,160,50,8
+ CONTROL "",IDC_CHECK2,"Button",BS_AUTOCHECKBOX | WS_DISABLED |
+ WS_TABSTOP,5,170,50,8
+ CONTROL "",IDC_CHECK3,"Button",BS_AUTOCHECKBOX | WS_DISABLED |
+ WS_TABSTOP,5,180,50,8
+ CONTROL "",IDC_CHECK4,"Button",BS_AUTOCHECKBOX | WS_DISABLED |
+ WS_TABSTOP,5,190,50,8
+ CONTROL "",IDC_CHECK5,"Button",BS_AUTOCHECKBOX | WS_DISABLED |
+ WS_TABSTOP,65,160,50,8
+ CONTROL "",IDC_CHECK6,"Button",BS_AUTOCHECKBOX | WS_DISABLED |
+ WS_TABSTOP,65,170,50,8
+ CONTROL "",IDC_CHECK7,"Button",BS_AUTOCHECKBOX | WS_DISABLED |
+ WS_TABSTOP,65,180,50,8
+ CONTROL "",IDC_CHECK8,"Button",BS_AUTOCHECKBOX | WS_DISABLED |
+ WS_TABSTOP,65,190,50,8
+ CONTROL "!Easy",IDC_CHECK9,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 125,160,50,8
+ CONTROL "!Medium",IDC_CHECK10,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,125,170,50,8
+ CONTROL "!Hard",IDC_CHECK11,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,125,180,50,10
+ CONTROL "!DeathMatch",IDC_CHECK12,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,125,190,55,10
+ LISTBOX IDC_E_PROPS,5,205,180,50,LBS_SORT | LBS_USETABSTOPS |
+ LBS_NOINTEGRALHEIGHT | LBS_WANTKEYBOARDINPUT |
+ WS_VSCROLL | WS_TABSTOP,WS_EX_CLIENTEDGE
+ PUSHBUTTON "Del Key/Pair",IDC_E_DELPROP,105,295,45,15
+ EDITTEXT IDC_E_STATUS,83,312,95,30,ES_MULTILINE | ES_AUTOVSCROLL |
+ ES_AUTOHSCROLL | ES_READONLY | WS_VSCROLL | WS_HSCROLL
+ LTEXT "Key",IDC_STATIC_KEY,5,260,25,10
+ LTEXT "Value",IDC_STATIC_VALUE,5,275,25,10
+ EDITTEXT IDC_E_KEY_FIELD,40,260,135,14,ES_AUTOHSCROLL
+ EDITTEXT IDC_E_VALUE_FIELD,40,275,135,14,ES_AUTOHSCROLL
+END
+
+IDD_GAMMA DIALOGEX 0, 0, 127, 76
+STYLE DS_MODALFRAME | WS_CAPTION | WS_SYSMENU
+CAPTION "Gamma"
+FONT 8, "MS Sans Serif", 0, 0, 0x1
+BEGIN
+ DEFPUSHBUTTON "OK",IDOK,10,40,50,14
+ PUSHBUTTON "Cancel",IDCANCEL,65,40,50,14
+ EDITTEXT IDC_G_EDIT,30,15,66,13,ES_AUTOHSCROLL,WS_EX_CLIENTEDGE
+END
+
+IDD_FINDBRUSH DIALOGEX 0, 0, 127, 76
+STYLE DS_MODALFRAME | WS_CAPTION | WS_SYSMENU
+CAPTION "Find brush"
+FONT 8, "MS Sans Serif", 0, 0, 0x1
+BEGIN
+ DEFPUSHBUTTON "OK",IDOK,5,55,50,14
+ PUSHBUTTON "Cancel",IDCANCEL,65,55,50,14
+ EDITTEXT IDC_FIND_ENTITY,80,15,46,13,ES_AUTOHSCROLL,
+ WS_EX_CLIENTEDGE
+ EDITTEXT IDC_FIND_BRUSH,80,30,46,13,ES_AUTOHSCROLL,
+ WS_EX_CLIENTEDGE
+ LTEXT "Entity number",IDC_STATIC,10,15,60,8
+ LTEXT "Brush number",IDC_STATIC,10,30,65,8
+END
+
+IDD_ROTATE DIALOG DISCARDABLE 0, 0, 186, 71
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Arbitrary rotation"
+FONT 8, "MS Sans Serif"
+BEGIN
+ DEFPUSHBUTTON "OK",IDOK,129,7,50,14
+ PUSHBUTTON "Cancel",IDCANCEL,129,24,50,14
+ EDITTEXT IDC_ROTX,30,5,40,14,ES_AUTOHSCROLL
+ LTEXT "x",IDC_STATIC,5,10,8,8
+ EDITTEXT IDC_ROTZ,30,45,40,14,ES_AUTOHSCROLL
+ LTEXT "y",IDC_STATIC,5,25,8,8
+ EDITTEXT IDC_ROTY,30,25,40,14,ES_AUTOHSCROLL
+ LTEXT "z",IDC_STATIC,5,45,8,8
+END
+
+IDD_SIDES DIALOG DISCARDABLE 0, 0, 186, 55
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Arbitrrary sides"
+FONT 8, "MS Sans Serif"
+BEGIN
+ DEFPUSHBUTTON "OK",IDOK,129,7,50,14
+ PUSHBUTTON "Cancel",IDCANCEL,129,24,50,14
+ EDITTEXT IDC_SIDES,50,15,40,14,ES_AUTOHSCROLL
+ LTEXT "Sides",IDC_STATIC,15,15,18,8
+END
+
+IDD_ABOUT DIALOG DISCARDABLE 0, 0, 274, 212
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "About QuakeEd"
+FONT 8, "MS Sans Serif"
+BEGIN
+ DEFPUSHBUTTON "OK",IDOK,217,7,50,14
+ CONTROL 127,IDC_STATIC,"Static",SS_BITMAP,7,7,83,58
+ CONTROL "Q3Radiant\nCopyright (C) 1997, 2005 id Software, Inc.",
+ IDC_STATIC,"Static",SS_LEFTNOWORDWRAP | WS_GROUP,100,10,
+ 110,23
+ GROUPBOX "OpenGL Properties",IDC_STATIC,5,75,265,50
+ LTEXT "Vendor:\t\tWHOEVER",IDC_ABOUT_GLVENDOR,10,90,125,10
+ LTEXT "Version:\t\t1.1",IDC_ABOUT_GLVERSION,10,100,125,10
+ LTEXT "Renderer:\tWHATEVER",IDC_ABOUT_GLRENDERER,10,110,125,10
+ LTEXT "WHATEVER",IDC_ABOUT_GLEXTENSIONS,10,140,255,60
+ GROUPBOX "OpenGL Extensions",IDC_STATIC,5,130,265,80
+END
+
+IDD_SURFACE DIALOG DISCARDABLE 400, 100, 392, 181
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Surface inspector"
+FONT 8, "MS Sans Serif"
+BEGIN
+ DEFPUSHBUTTON "OK",IDOK,5,155,40,14
+ PUSHBUTTON "Cancel",IDCANCEL,105,155,40,14
+ EDITTEXT IDC_HSHIFT,85,45,35,15,ES_AUTOHSCROLL
+ SCROLLBAR IDC_HSHIFTA,120,45,10,15,SBS_VERT
+ LTEXT "Horizontal shift",IDC_STATIC,10,45,65,8
+ LTEXT "Vertical shift",IDC_STATIC,10,60,65,8
+ LTEXT "Horizontal stretch",IDC_STATIC,10,75,65,8
+ LTEXT "Vertical stretch",IDC_STATIC,10,90,65,8
+ LTEXT "Rotate",IDC_STATIC,10,105,65,8
+ LTEXT "value",IDC_STATIC,10,120,65,8
+ EDITTEXT IDC_VSHIFT,85,60,35,15,ES_AUTOHSCROLL
+ SCROLLBAR IDC_VSHIFTA,120,60,10,15,SBS_VERT
+ EDITTEXT IDC_HSCALE,85,75,35,15,ES_AUTOHSCROLL
+ SCROLLBAR IDC_HSCALEA,120,75,10,15,SBS_VERT
+ EDITTEXT IDC_VSCALE,85,90,35,15,ES_AUTOHSCROLL
+ SCROLLBAR IDC_VSCALEA,120,90,10,15,SBS_VERT
+ EDITTEXT IDC_ROTATE,85,105,35,15,ES_AUTOHSCROLL
+ SCROLLBAR IDC_ROTATEA,120,105,10,15,SBS_VERT
+ EDITTEXT IDC_VALUE,85,120,35,15,ES_AUTOHSCROLL
+ EDITTEXT IDC_TEXTURE,50,15,80,14,ES_AUTOHSCROLL
+ CONTROL "light",IDC_CHECK1,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 160,10,41,8
+ CONTROL "slick",IDC_CHECK2,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 160,20,41,8
+ CONTROL "sky",IDC_CHECK3,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 160,30,41,8
+ CONTROL "warp",IDC_CHECK4,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 160,40,41,8
+ CONTROL "trans33",IDC_CHECK5,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,160,50,41,8
+ CONTROL "trans66",IDC_CHECK6,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,160,60,41,8
+ CONTROL "flowing",IDC_CHECK7,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,160,70,41,8
+ CONTROL "nodraw",IDC_CHECK8,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,160,80,41,8
+ CONTROL "100",IDC_CHECK9,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 160,90,41,8
+ CONTROL "200",IDC_CHECK10,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 160,100,41,8
+ CONTROL "400",IDC_CHECK11,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 160,110,41,8
+ CONTROL "800",IDC_CHECK12,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 160,120,41,8
+ CONTROL "1000",IDC_CHECK13,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 160,130,41,8
+ CONTROL "2000",IDC_CHECK14,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 160,140,41,8
+ CONTROL "4000",IDC_CHECK15,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 160,150,41,8
+ CONTROL "8000",IDC_CHECK16,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 160,160,41,8
+ LTEXT "Texture",IDC_STATIC,10,18,30,8
+ PUSHBUTTON "Apply",IDAPPLY,55,155,40,14
+ CONTROL "10000",IDC_CHECK17,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,210,10,41,8
+ CONTROL "20000",IDC_CHECK18,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,210,20,41,8
+ CONTROL "40000",IDC_CHECK19,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,210,30,41,8
+ CONTROL "80000",IDC_CHECK20,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,210,40,41,8
+ CONTROL "100000",IDC_CHECK21,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,210,50,41,8
+ CONTROL "200000",IDC_CHECK22,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,210,60,41,8
+ CONTROL "400000",IDC_CHECK23,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,210,70,41,8
+ CONTROL "800000",IDC_CHECK24,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,210,80,41,8
+ CONTROL "1000000",IDC_CHECK25,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,210,90,41,8
+ CONTROL "2000000",IDC_CHECK26,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,210,100,41,8
+ CONTROL "4000000",IDC_CHECK27,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,210,110,41,8
+ CONTROL "8000000",IDC_CHECK28,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,210,120,41,8
+ CONTROL "10000000",IDC_CHECK29,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,210,130,40,8
+ CONTROL "20000000",IDC_CHECK30,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,210,140,45,8
+ CONTROL "40000000",IDC_CHECK31,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,210,150,45,8
+ CONTROL "80000000",IDC_CHECK32,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,210,160,45,8
+ CONTROL "solid",IDC_CHECK33,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,280,10,41,8
+ CONTROL "window",IDC_CHECK34,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,280,20,41,8
+ CONTROL "aux",IDC_CHECK35,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 280,31,41,8
+ CONTROL "lava",IDC_CHECK36,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 280,41,41,8
+ CONTROL "slime",IDC_CHECK37,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,280,50,41,8
+ CONTROL "water",IDC_CHECK38,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,280,60,41,8
+ CONTROL "mist",IDC_CHECK39,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 280,71,41,8
+ CONTROL "80",IDC_CHECK40,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 280,81,41,8
+ CONTROL "100",IDC_CHECK41,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 280,90,41,8
+ CONTROL "200",IDC_CHECK42,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 280,100,41,8
+ CONTROL "400",IDC_CHECK43,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 280,111,41,8
+ CONTROL "800",IDC_CHECK44,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 280,121,41,8
+ CONTROL "1000",IDC_CHECK45,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 280,130,41,8
+ CONTROL "2000",IDC_CHECK46,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 280,140,41,8
+ CONTROL "4000",IDC_CHECK47,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 280,151,41,8
+ CONTROL "8000",IDC_CHECK48,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 280,161,41,8
+ CONTROL "playerclip",IDC_CHECK49,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,330,10,41,8
+ CONTROL "monsterclip",IDC_CHECK50,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,330,20,50,8
+ CONTROL "current_0",IDC_CHECK51,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,330,31,50,8
+ CONTROL "current_90",IDC_CHECK52,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,330,41,50,8
+ CONTROL "current_180",IDC_CHECK53,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,330,50,50,8
+ CONTROL "current_270",IDC_CHECK54,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,330,60,50,8
+ CONTROL "current_up",IDC_CHECK55,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,330,71,50,8
+ CONTROL "current_dn",IDC_CHECK56,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,330,81,50,8
+ CONTROL "origin",IDC_CHECK57,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,330,90,41,8
+ CONTROL "monster",IDC_CHECK58,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,330,100,41,8
+ CONTROL "corpse",IDC_CHECK59,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,330,111,41,8
+ CONTROL "detail",IDC_CHECK60,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,330,121,41,8
+ CONTROL "translucent",IDC_CHECK61,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,330,130,50,8
+ CONTROL "ladder",IDC_CHECK62,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,330,140,45,8
+ CONTROL "40000000",IDC_CHECK63,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,330,151,45,8
+ CONTROL "80000000",IDC_CHECK64,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,330,161,45,8
+ GROUPBOX "Surf flags",IDC_STATIC,150,0,115,175
+ GROUPBOX "Content flags",IDC_STATIC,270,0,115,175
+END
+
+
+#ifndef _MAC
+/////////////////////////////////////////////////////////////////////////////
+//
+// Version
+//
+
+VS_VERSION_INFO VERSIONINFO
+ FILEVERSION 1,0,0,1
+ PRODUCTVERSION 1,0,0,1
+ FILEFLAGSMASK 0x3fL
+#ifdef _DEBUG
+ FILEFLAGS 0x1L
+#else
+ FILEFLAGS 0x0L
+#endif
+ FILEOS 0x40004L
+ FILETYPE 0x1L
+ FILESUBTYPE 0x0L
+BEGIN
+ BLOCK "StringFileInfo"
+ BEGIN
+ BLOCK "040904b0"
+ BEGIN
+ VALUE "CompanyName", "Id Software\0"
+ VALUE "FileDescription", "qe3\0"
+ VALUE "FileVersion", "1, 0, 0, 1\0"
+ VALUE "InternalName", "qe3\0"
+ VALUE "LegalCopyright", "Copyright © 1996\0"
+ VALUE "OriginalFilename", "qe3.exe\0"
+ VALUE "ProductName", "Id Software qe3\0"
+ VALUE "ProductVersion", "1, 0, 0, 1\0"
+ END
+ END
+ BLOCK "VarFileInfo"
+ BEGIN
+ VALUE "Translation", 0x409, 1200
+ END
+END
+
+#endif // !_MAC
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Accelerator
+//
+
+IDR_ACCELERATOR1 ACCELERATORS DISCARDABLE
+BEGIN
+ "3", ID_BRUSH_3SIDED, VIRTKEY, CONTROL, NOINVERT
+ "4", ID_BRUSH_4SIDED, VIRTKEY, CONTROL, NOINVERT
+ "5", ID_BRUSH_5SIDED, VIRTKEY, CONTROL, NOINVERT
+ "6", ID_BRUSH_6SIDED, VIRTKEY, CONTROL, NOINVERT
+ "7", ID_BRUSH_7SIDED, VIRTKEY, CONTROL, NOINVERT
+ "8", ID_BRUSH_8SIDED, VIRTKEY, CONTROL, NOINVERT
+ "9", ID_BRUSH_9SIDED, VIRTKEY, CONTROL, NOINVERT
+ "D", ID_VIEW_SHOWDETAIL, VIRTKEY, CONTROL, NOINVERT
+ "K", ID_SELECTION_CONNECT, VIRTKEY, CONTROL, NOINVERT
+ "L", ID_MISC_NEXTLEAKSPOT, VIRTKEY, CONTROL, NOINVERT
+ "M", ID_SELECTION_MAKE_DETAIL, VIRTKEY, CONTROL, NOINVERT
+ "O", ID_FILE_OPEN, VIRTKEY, CONTROL, NOINVERT
+ "P", ID_MISC_PREVIOUSLEAKSPOT, VIRTKEY, CONTROL, NOINVERT
+ "S", ID_FILE_SAVE, VIRTKEY, CONTROL, NOINVERT
+ VK_DELETE, ID_VIEW_ZZOOMIN, VIRTKEY, CONTROL, NOINVERT
+ VK_INSERT, ID_VIEW_ZZOOMOUT, VIRTKEY, CONTROL, NOINVERT
+ "X", ID_FILE_EXIT, VIRTKEY, CONTROL, NOINVERT
+END
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Toolbar
+//
+
+IDR_TOOLBAR1 TOOLBAR DISCARDABLE 16, 15
+BEGIN
+ BUTTON ID_BRUSH_FLIPX
+ BUTTON ID_BRUSH_ROTATEX
+ BUTTON ID_BRUSH_FLIPY
+ BUTTON ID_BRUSH_ROTATEY
+ BUTTON ID_BRUSH_FLIPZ
+ BUTTON ID_BRUSH_ROTATEZ
+ BUTTON ID_SELECTION_SELECTCOMPLETETALL
+ BUTTON ID_SELECTION_SELECTTOUCHING
+ BUTTON ID_SELECTION_SELECTPARTIALTALL
+ BUTTON ID_SELECTION_SELECTINSIDE
+ BUTTON ID_SELECTION_CSGSUBTRACT
+ BUTTON ID_SELECTION_MAKEHOLLOW
+ BUTTON ID_TEXTURES_WIREFRAME
+ BUTTON ID_TEXTURES_FLATSHADE
+ BUTTON ID_VIEW_TRILINEAR
+END
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Bitmap
+//
+
+IDR_TOOLBAR1 BITMAP DISCARDABLE "toolbar1.bmp"
+IDB_BITMAP1 BITMAP DISCARDABLE "q.bmp"
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// DESIGNINFO
+//
+
+#ifdef APSTUDIO_INVOKED
+GUIDELINES DESIGNINFO DISCARDABLE
+BEGIN
+ IDD_ENTITY, DIALOG
+ BEGIN
+ RIGHTMARGIN, 227
+ BOTTOMMARGIN, 387
+ END
+
+ IDD_GAMMA, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 120
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 68
+ END
+
+ IDD_FINDBRUSH, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 120
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 68
+ END
+
+ IDD_ROTATE, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 179
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 64
+ END
+
+ IDD_SIDES, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 179
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 48
+ END
+
+ IDD_ABOUT, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 267
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 205
+ END
+
+ IDD_SURFACE, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 385
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 174
+ END
+END
+#endif // APSTUDIO_INVOKED
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Icon
+//
+
+// Icon with lowest ID value placed first to ensure application icon
+// remains consistent on all systems.
+IDI_ICON1 ICON DISCARDABLE "icon1.ico"
+#endif // English (U.S.) resources
+/////////////////////////////////////////////////////////////////////////////
+
+
+
+#ifndef APSTUDIO_INVOKED
+/////////////////////////////////////////////////////////////////////////////
+//
+// Generated from the TEXTINCLUDE 3 resource.
+//
+
+
+/////////////////////////////////////////////////////////////////////////////
+#endif // not APSTUDIO_INVOKED
+
diff --git a/q3radiant/WIN_XY.CPP b/q3radiant/WIN_XY.CPP
new file mode 100755
index 0000000..34d3564
--- /dev/null
+++ b/q3radiant/WIN_XY.CPP
@@ -0,0 +1,310 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// win_xy.c -- windows specific xy view code
+
+#include "stdafx.h"
+#include "qe3.h"
+
+static HDC s_hdcXY;
+static HGLRC s_hglrcXY;
+
+static unsigned s_stipple[32] =
+{
+ 0xaaaaaaaa, 0x55555555,0xaaaaaaaa, 0x55555555,
+ 0xaaaaaaaa, 0x55555555,0xaaaaaaaa, 0x55555555,
+ 0xaaaaaaaa, 0x55555555,0xaaaaaaaa, 0x55555555,
+ 0xaaaaaaaa, 0x55555555,0xaaaaaaaa, 0x55555555,
+ 0xaaaaaaaa, 0x55555555,0xaaaaaaaa, 0x55555555,
+ 0xaaaaaaaa, 0x55555555,0xaaaaaaaa, 0x55555555,
+ 0xaaaaaaaa, 0x55555555,0xaaaaaaaa, 0x55555555,
+ 0xaaaaaaaa, 0x55555555,0xaaaaaaaa, 0x55555555,
+};
+
+/*
+============
+WXY_WndProc
+============
+*/
+LONG WINAPI XYWndProc (
+ HWND hWnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam)
+{
+ int fwKeys, xPos, yPos;
+ RECT rect;
+
+
+ GetClientRect(hWnd, &rect);
+
+ switch (uMsg)
+ {
+ case WM_CREATE:
+
+ s_hdcXY = GetDC(hWnd);
+ QEW_SetupPixelFormat(s_hdcXY, false);
+
+ if ( ( s_hglrcXY = wglCreateContext( s_hdcXY ) ) == 0 )
+ Error( "wglCreateContext in WXY_WndProc failed" );
+
+ if (!wglMakeCurrent( s_hdcXY, s_hglrcXY ))
+ Error ("wglMakeCurrent failed");
+
+ if (!wglShareLists( g_qeglobals.d_hglrcBase, s_hglrcXY ) )
+ Error( "wglShareLists in WXY_WndProc failed" );
+
+ glPolygonStipple ((unsigned char *)s_stipple);
+ glLineStipple (3, 0xaaaa);
+
+ return 0;
+
+ case WM_DESTROY:
+ QEW_StopGL( hWnd, s_hglrcXY, s_hdcXY );
+ return 0;
+
+ case WM_PAINT:
+ {
+ PAINTSTRUCT ps;
+
+ BeginPaint(hWnd, &ps);
+
+ if (!wglMakeCurrent( s_hdcXY, s_hglrcXY ))
+ Error ("wglMakeCurrent failed");
+
+ QE_CheckOpenGLForErrors();
+ XY_Draw ();
+ QE_CheckOpenGLForErrors();
+
+ SwapBuffers(s_hdcXY);
+
+ EndPaint(hWnd, &ps);
+ }
+ return 0;
+
+ case WM_KEYDOWN:
+ return QE_KeyDown (wParam);
+
+ case WM_MBUTTONDOWN:
+ case WM_RBUTTONDOWN:
+ case WM_LBUTTONDOWN:
+ if ( GetTopWindow( g_qeglobals.d_hwndMain ) != hWnd)
+ BringWindowToTop(hWnd);
+ SetFocus( g_qeglobals.d_hwndXY );
+ SetCapture( g_qeglobals.d_hwndXY );
+ fwKeys = wParam; // key flags
+ xPos = (short)LOWORD(lParam); // horizontal position of cursor
+ yPos = (short)HIWORD(lParam); // vertical position of cursor
+ yPos = (int)rect.bottom - 1 - yPos;
+ XY_MouseDown (xPos, yPos, fwKeys);
+ return 0;
+
+ case WM_MBUTTONUP:
+ case WM_RBUTTONUP:
+ case WM_LBUTTONUP:
+ fwKeys = wParam; // key flags
+ xPos = (short)LOWORD(lParam); // horizontal position of cursor
+ yPos = (short)HIWORD(lParam); // vertical position of cursor
+ yPos = (int)rect.bottom - 1 - yPos;
+ XY_MouseUp (xPos, yPos, fwKeys);
+ if (! (fwKeys & (MK_LBUTTON|MK_RBUTTON|MK_MBUTTON)))
+ ReleaseCapture ();
+ return 0;
+
+ case WM_MOUSEMOVE:
+ if (::GetFocus() != hWnd)
+ ::SetFocus(hWnd);
+ fwKeys = wParam; // key flags
+ xPos = (short)LOWORD(lParam); // horizontal position of cursor
+ yPos = (short)HIWORD(lParam); // vertical position of cursor
+ yPos = (int)rect.bottom - 1 - yPos;
+ XY_MouseMoved (xPos, yPos, fwKeys);
+ return 0;
+
+ case WM_SIZE:
+ g_qeglobals.d_xy.width = rect.right;
+ g_qeglobals.d_xy.height = rect.bottom - 16;
+ InvalidateRect( g_qeglobals.d_hwndXY, NULL, false);
+ return 0;
+
+ case WM_NCCALCSIZE:// don't let windows copy pixels
+ DefWindowProc (hWnd, uMsg, wParam, lParam);
+ return WVR_REDRAW;
+
+ case WM_KILLFOCUS:
+ case WM_SETFOCUS:
+ SendMessage( hWnd, WM_NCACTIVATE, uMsg == WM_SETFOCUS, 0 );
+ return 0;
+
+ case WM_CLOSE:
+ DestroyWindow (hWnd);
+ return 0;
+ }
+
+ return DefWindowProc (hWnd, uMsg, wParam, lParam);
+}
+
+
+/*
+==============
+WXY_Create
+==============
+*/
+void WXY_Create (HINSTANCE hInstance)
+{
+ ASSERT(0);
+#if 0
+ WNDCLASS wc;
+
+ /* Register the camera class */
+ memset (&wc, 0, sizeof(wc));
+
+ wc.style = CS_NOCLOSE;
+ wc.lpfnWndProc = (WNDPROC)WXY_WndProc;
+ wc.cbClsExtra = 0;
+ wc.cbWndExtra = 0;
+ wc.hInstance = hInstance;
+ wc.hIcon = 0;
+ wc.hCursor = LoadCursor (NULL,IDC_ARROW);
+ wc.hbrBackground = NULL; //(HBRUSH)(COLOR_WINDOW+1);
+ wc.lpszMenuName = NULL;
+ wc.lpszClassName = XY_WINDOW_CLASS;
+
+ if (!RegisterClass (&wc) )
+ Error ("RegisterClass: failed");
+
+ g_qeglobals.d_hwndXY = CreateWindow (XY_WINDOW_CLASS ,
+ "XY View",
+ QE3_STYLE ,
+ ZWIN_WIDTH,
+ (int)(screen_height*CWIN_SIZE)-20,
+ screen_width-ZWIN_WIDTH,
+ (int)(screen_height*(1.0-CWIN_SIZE)-38), // size
+
+ g_qeglobals.d_hwndMain, // parent
+ 0, // no menu
+ hInstance,
+ NULL);
+
+ if (!g_qeglobals.d_hwndXY )
+ Error ("Couldn't create XY View");
+
+ LoadWindowState(g_qeglobals.d_hwndXY, "xywindow");
+ ShowWindow(g_qeglobals.d_hwndXY, SW_SHOWDEFAULT);
+#endif
+}
+
+static void WXY_InitPixelFormat( PIXELFORMATDESCRIPTOR *pPFD )
+{
+ memset( pPFD, 0, sizeof( *pPFD ) );
+
+ pPFD->nSize = sizeof( PIXELFORMATDESCRIPTOR );
+ pPFD->nVersion = 1;
+ pPFD->dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
+ pPFD->iPixelType = PFD_TYPE_RGBA;
+ pPFD->cColorBits = 24;
+ pPFD->cDepthBits = 32;
+ pPFD->iLayerType = PFD_MAIN_PLANE;
+
+}
+
+void WXY_Print( void )
+{
+ DOCINFO di;
+
+ PRINTDLG pd;
+
+ /*
+ ** initialize the PRINTDLG struct and execute it
+ */
+ memset( &pd, 0, sizeof( pd ) );
+ pd.lStructSize = sizeof( pd );
+ pd.hwndOwner = g_qeglobals.d_hwndXY;
+ pd.Flags = PD_RETURNDC;
+ pd.hInstance = 0;
+ if ( !PrintDlg( &pd ) || !pd.hDC )
+ {
+ MessageBox( g_qeglobals.d_hwndMain, "Could not PrintDlg()", "QE4 Print Error", MB_OK | MB_ICONERROR );
+ return;
+ }
+
+ /*
+ ** StartDoc
+ */
+ memset( &di, 0, sizeof( di ) );
+ di.cbSize = sizeof( di );
+ di.lpszDocName = "QE4";
+ if ( StartDoc( pd.hDC, &di ) <= 0 )
+ {
+ MessageBox( g_qeglobals.d_hwndMain, "Could not StartDoc()", "QE4 Print Error", MB_OK | MB_ICONERROR );
+ return;
+ }
+
+ /*
+ ** StartPage
+ */
+ if ( StartPage( pd.hDC ) <= 0 )
+ {
+ MessageBox( g_qeglobals.d_hwndMain, "Could not StartPage()", "QE4 Print Error", MB_OK | MB_ICONERROR );
+ return;
+ }
+
+ /*
+ ** read pixels from the XY window
+ */
+ {
+ int bmwidth = 320, bmheight = 320;
+ int pwidth, pheight;
+
+ RECT r;
+
+ GetWindowRect( g_qeglobals.d_hwndXY, &r );
+
+ bmwidth = r.right - r.left;
+ bmheight = r.bottom - r.top;
+
+ pwidth = GetDeviceCaps( pd.hDC, PHYSICALWIDTH ) - GetDeviceCaps( pd.hDC, PHYSICALOFFSETX );
+ pheight = GetDeviceCaps( pd.hDC, PHYSICALHEIGHT ) - GetDeviceCaps( pd.hDC, PHYSICALOFFSETY );
+
+ StretchBlt( pd.hDC,
+ 0, 0,
+ pwidth, pheight,
+ s_hdcXY,
+ 0, 0,
+ bmwidth, bmheight,
+ SRCCOPY );
+ }
+
+ /*
+ ** EndPage and EndDoc
+ */
+ if ( EndPage( pd.hDC ) <= 0 )
+ {
+ MessageBox( g_qeglobals.d_hwndMain, "QE4 Print Error", "Could not EndPage()", MB_OK | MB_ICONERROR );
+ return;
+ }
+
+ if ( EndDoc( pd.hDC ) <= 0 )
+ {
+ MessageBox( g_qeglobals.d_hwndMain, "QE4 Print Error", "Could not EndDoc()", MB_OK | MB_ICONERROR );
+ return;
+ }
+}
diff --git a/q3radiant/WIN_Z.CPP b/q3radiant/WIN_Z.CPP
new file mode 100755
index 0000000..caac0d0
--- /dev/null
+++ b/q3radiant/WIN_Z.CPP
@@ -0,0 +1,192 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// win_cam.c -- windows specific camera view code
+
+#include "stdafx.h"
+#include "qe3.h"
+
+static HDC s_hdcZ;
+static HGLRC s_hglrcZ;
+
+/*
+============
+WZ_WndProc
+============
+*/
+LONG WINAPI WZ_WndProc (
+ HWND hWnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam)
+{
+ int fwKeys, xPos, yPos;
+ RECT rect;
+
+ GetClientRect(hWnd, &rect);
+
+ switch (uMsg)
+ {
+
+ case WM_DESTROY:
+ QEW_StopGL( hWnd, s_hglrcZ, s_hdcZ );
+ return 0;
+
+ case WM_CREATE:
+ s_hdcZ = GetDC(hWnd);
+ QEW_SetupPixelFormat( s_hdcZ, false);
+ if ( ( s_hglrcZ = wglCreateContext( s_hdcZ ) ) == 0 )
+ Error( "wglCreateContext in WZ_WndProc failed" );
+
+ if (!wglMakeCurrent( s_hdcZ, s_hglrcZ ))
+ Error ("wglMakeCurrent in WZ_WndProc failed");
+
+ if (!wglShareLists( g_qeglobals.d_hglrcBase, s_hglrcZ ) )
+ Error( "wglShareLists in WZ_WndProc failed" );
+ return 0;
+
+ case WM_PAINT:
+ {
+ PAINTSTRUCT ps;
+
+ BeginPaint(hWnd, &ps);
+
+ if ( !wglMakeCurrent( s_hdcZ, s_hglrcZ ) )
+ Error ("wglMakeCurrent failed");
+ QE_CheckOpenGLForErrors();
+
+ Z_Draw ();
+ SwapBuffers(s_hdcZ);
+
+ EndPaint(hWnd, &ps);
+ }
+ return 0;
+
+
+ case WM_KEYDOWN:
+ QE_KeyDown (wParam);
+ return 0;
+
+ case WM_MBUTTONDOWN:
+ case WM_RBUTTONDOWN:
+ case WM_LBUTTONDOWN:
+ if (GetTopWindow(g_qeglobals.d_hwndMain) != hWnd)
+ BringWindowToTop(hWnd);
+
+ SetFocus( g_qeglobals.d_hwndZ );
+ SetCapture( g_qeglobals.d_hwndZ );
+ fwKeys = wParam; // key flags
+ xPos = (short)LOWORD(lParam); // horizontal position of cursor
+ yPos = (short)HIWORD(lParam); // vertical position of cursor
+ yPos = (int)rect.bottom - 1 - yPos;
+ Z_MouseDown (xPos, yPos, fwKeys);
+ return 0;
+
+ case WM_MBUTTONUP:
+ case WM_RBUTTONUP:
+ case WM_LBUTTONUP:
+ fwKeys = wParam; // key flags
+ xPos = (short)LOWORD(lParam); // horizontal position of cursor
+ yPos = (short)HIWORD(lParam); // vertical position of cursor
+ yPos = (int)rect.bottom - 1 - yPos;
+ Z_MouseUp (xPos, yPos, fwKeys);
+ if (! (fwKeys & (MK_LBUTTON|MK_RBUTTON|MK_MBUTTON)))
+ ReleaseCapture ();
+ return 0;
+
+ case WM_GETMINMAXINFO:
+ {
+ MINMAXINFO *pmmi = (LPMINMAXINFO) lParam;
+
+ pmmi->ptMinTrackSize.x = ZWIN_WIDTH;
+ return 0;
+ }
+
+ case WM_MOUSEMOVE:
+ fwKeys = wParam; // key flags
+ xPos = (short)LOWORD(lParam); // horizontal position of cursor
+ yPos = (short)HIWORD(lParam); // vertical position of cursor
+ yPos = (int)rect.bottom - 1 - yPos;
+ Z_MouseMoved (xPos, yPos, fwKeys);
+ return 0;
+
+ case WM_SIZE:
+ z.width = rect.right;
+ z.height = rect.bottom;
+ InvalidateRect( g_qeglobals.d_hwndZ, NULL, false);
+ return 0;
+
+ case WM_NCCALCSIZE:// don't let windows copy pixels
+ DefWindowProc (hWnd, uMsg, wParam, lParam);
+ return WVR_REDRAW;
+
+ case WM_KILLFOCUS:
+ case WM_SETFOCUS:
+ SendMessage( hWnd, WM_NCACTIVATE, uMsg == WM_SETFOCUS, 0 );
+ return 0;
+
+ case WM_CLOSE:
+ /* call destroy window to cleanup and go away */
+ DestroyWindow (hWnd);
+ return 0;
+ }
+
+ return DefWindowProc (hWnd, uMsg, wParam, lParam);
+}
+
+
+/*
+==============
+WZ_Create
+==============
+*/
+void WZ_Create (HINSTANCE hInstance)
+{
+ WNDCLASS wc;
+ memset (&wc, 0, sizeof(wc));
+ wc.style = CS_NOCLOSE;
+ wc.lpfnWndProc = (WNDPROC)WZ_WndProc;
+ wc.cbClsExtra = 0;
+ wc.cbWndExtra = 0;
+ wc.hInstance = hInstance;
+ wc.hIcon = 0;
+ wc.hCursor = LoadCursor (NULL,IDC_ARROW);
+ wc.hbrBackground = NULL;
+ wc.lpszMenuName = NULL;
+ wc.lpszClassName = Z_WINDOW_CLASS;
+
+ if (!RegisterClass (&wc) )
+ Error ("WCam_Register: failed");
+
+ g_qeglobals.d_hwndZ = CreateWindow (Z_WINDOW_CLASS ,
+ "Z",
+ QE3_STYLE,
+ 0,20,ZWIN_WIDTH,screen_height-38, // size
+ g_qeglobals.d_hwndMain, // parent
+ 0, // no menu
+ hInstance,
+ NULL);
+ if (!g_qeglobals.d_hwndZ)
+ Error ("Couldn't create zwindow");
+
+ LoadWindowState(g_qeglobals.d_hwndZ, "zwindow");
+ ShowWindow (g_qeglobals.d_hwndZ, SW_SHOWDEFAULT);
+}
diff --git a/q3radiant/WaveOpen.cpp b/q3radiant/WaveOpen.cpp
new file mode 100755
index 0000000..34f1f6b
--- /dev/null
+++ b/q3radiant/WaveOpen.cpp
@@ -0,0 +1,98 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// WaveOpen.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "WaveOpen.h"
+#include "mmsystem.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CWaveOpen
+
+IMPLEMENT_DYNAMIC(CWaveOpen, CFileDialog)
+
+CWaveOpen::CWaveOpen(BOOL bOpenFileDialog, LPCTSTR lpszDefExt, LPCTSTR lpszFileName,
+ DWORD dwFlags, LPCTSTR lpszFilter, CWnd* pParentWnd) :
+ CFileDialog(bOpenFileDialog, lpszDefExt, lpszFileName, dwFlags, lpszFilter, pParentWnd)
+{
+ m_ofn.Flags |= (OFN_EXPLORER | OFN_ENABLETEMPLATE);
+ m_ofn.lpTemplateName = MAKEINTRESOURCE(IDD_PLAYWAVE);
+}
+
+
+BEGIN_MESSAGE_MAP(CWaveOpen, CFileDialog)
+ //{{AFX_MSG_MAP(CWaveOpen)
+ ON_BN_CLICKED(IDC_BTN_PLAY, OnBtnPlay)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+
+void CWaveOpen::OnFileNameChange()
+{
+ CString str = GetPathName();
+ str.MakeLower();
+ CWnd *pWnd = GetDlgItem(IDC_BTN_PLAY);
+ if (pWnd == NULL)
+ {
+ return;
+ }
+ if (str.Find(".wav") >= 0)
+ {
+ pWnd->EnableWindow(TRUE);
+ }
+ else
+ {
+ pWnd->EnableWindow(FALSE);
+ }
+}
+
+void CWaveOpen::OnBtnPlay()
+{
+ sndPlaySound(NULL, NULL);
+ CString str = GetPathName();
+ if (str.GetLength() > 0)
+ {
+ sndPlaySound(str, SND_FILENAME | SND_ASYNC);
+ }
+}
+
+BOOL CWaveOpen::OnInitDialog()
+{
+ CFileDialog::OnInitDialog();
+
+ CWnd *pWnd = GetDlgItem(IDC_BTN_PLAY);
+ if (pWnd != NULL)
+ {
+ pWnd->EnableWindow(FALSE);
+ }
+
+ return TRUE; // return TRUE unless you set the focus to a control
+ // EXCEPTION: OCX Property Pages should return FALSE
+}
diff --git a/q3radiant/WaveOpen.h b/q3radiant/WaveOpen.h
new file mode 100755
index 0000000..f5208a3
--- /dev/null
+++ b/q3radiant/WaveOpen.h
@@ -0,0 +1,58 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_WAVEOPEN_H__0FB9DA11_EB02_11D2_A50A_0020AFEB881A__INCLUDED_)
+#define AFX_WAVEOPEN_H__0FB9DA11_EB02_11D2_A50A_0020AFEB881A__INCLUDED_
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+// WaveOpen.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CWaveOpen dialog
+
+class CWaveOpen : public CFileDialog
+{
+ DECLARE_DYNAMIC(CWaveOpen)
+
+public:
+ CWaveOpen(BOOL bOpenFileDialog, // TRUE for FileOpen, FALSE for FileSaveAs
+ LPCTSTR lpszDefExt = NULL,
+ LPCTSTR lpszFileName = NULL,
+ DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
+ LPCTSTR lpszFilter = NULL,
+ CWnd* pParentWnd = NULL);
+
+ virtual void OnFileNameChange( );
+protected:
+ //{{AFX_MSG(CWaveOpen)
+ afx_msg void OnBtnPlay();
+ virtual BOOL OnInitDialog();
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_WAVEOPEN_H__0FB9DA11_EB02_11D2_A50A_0020AFEB881A__INCLUDED_)
diff --git a/q3radiant/Win_ent.cpp b/q3radiant/Win_ent.cpp
new file mode 100755
index 0000000..28bc9ab
--- /dev/null
+++ b/q3radiant/Win_ent.cpp
@@ -0,0 +1,1411 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "stdafx.h"
+#include "qe3.h"
+#include "entityw.h"
+#include "TexWnd.h"
+#include "WaveOpen.h"
+
+int rgIds[EntLast] = {
+ IDC_E_LIST,
+ IDC_E_COMMENT,
+ IDC_CHECK1,
+ IDC_CHECK2,
+ IDC_CHECK3,
+ IDC_CHECK4,
+ IDC_CHECK5,
+ IDC_CHECK6,
+ IDC_CHECK7,
+ IDC_CHECK8,
+ IDC_CHECK9,
+ IDC_CHECK10,
+ IDC_CHECK11,
+ IDC_CHECK12,
+ IDC_E_PROPS,
+ IDC_E_0,
+ IDC_E_45,
+ IDC_E_90,
+ IDC_E_135,
+ IDC_E_180,
+ IDC_E_225,
+ IDC_E_270,
+ IDC_E_315,
+ IDC_E_UP,
+ IDC_E_DOWN,
+ IDC_E_DELPROP,
+
+ IDC_STATIC_KEY,
+ IDC_E_KEY_FIELD,
+ IDC_STATIC_VALUE,
+ IDC_E_VALUE_FIELD,
+
+ IDC_E_COLOR,
+
+ IDC_BTN_ASSIGNSOUND,
+ IDC_BTN_ASSIGNMODEL
+
+};
+
+HWND hwndEnt[EntLast];
+CTabCtrl g_wndTabs;
+
+int inspector_mode; // W_TEXTURE, W_ENTITY, or W_CONSOLE
+
+qboolean multiple_entities;
+
+entity_t *edit_entity;
+
+
+BOOL CALLBACK EntityWndProc(
+ HWND hwndDlg, // handle to dialog box
+ UINT uMsg, // message
+ WPARAM wParam, // first message parameter
+ LPARAM lParam); // second message parameter
+
+void SizeEntityDlg(int iWidth, int iHeight);
+void AddProp();
+void GetTexMods(void);
+
+
+LRESULT (CALLBACK* OldFieldWindowProc) (HWND, UINT, WPARAM, LPARAM);
+LRESULT (CALLBACK* OldEntityListWindowProc) (HWND, UINT, WPARAM, LPARAM);
+
+/*
+=========================
+FieldWndProc
+
+Just to handle tab and enter...
+=========================
+*/
+BOOL CALLBACK FieldWndProc(
+ HWND hwnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam)
+{
+ switch (uMsg)
+ {
+ case WM_CHAR:
+ if (LOWORD(wParam) == VK_TAB)
+ return FALSE;
+ if (LOWORD(wParam) == VK_RETURN)
+ return FALSE;
+ if (LOWORD(wParam) == VK_ESCAPE)
+ {
+ SetFocus (g_qeglobals.d_hwndCamera);
+ return FALSE;
+ }
+ break;
+
+ case WM_KEYDOWN:
+ if (LOWORD(wParam) == VK_TAB)
+ {
+ if (hwnd == hwndEnt[EntKeyField])
+ {
+ SendMessage (hwndEnt[EntValueField], WM_SETTEXT, 0, (long)"");
+ SetFocus (hwndEnt[EntValueField]);
+ }
+ else
+ SetFocus (hwndEnt[EntKeyField]);
+ }
+ if (LOWORD(wParam) == VK_RETURN)
+ {
+ if (hwnd == hwndEnt[EntKeyField])
+ {
+ SendMessage (hwndEnt[EntValueField], WM_SETTEXT, 0, (long)"");
+ SetFocus (hwndEnt[EntValueField]);
+ }
+ else
+ {
+ AddProp ();
+ SetFocus (g_qeglobals.d_hwndCamera);
+ }
+ }
+ break;
+// case WM_NCHITTEST:
+ case WM_LBUTTONDOWN:
+ SetFocus (hwnd);
+ break;
+ }
+ return CallWindowProc (OldFieldWindowProc, hwnd, uMsg, wParam, lParam);
+}
+
+
+/*
+=========================
+EntityListWndProc
+
+Just to handle enter...
+=========================
+*/
+BOOL CALLBACK EntityListWndProc(
+ HWND hwnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam)
+{
+ switch (uMsg)
+ {
+ case WM_KEYDOWN:
+ if (LOWORD(wParam) == VK_RETURN)
+ {
+ SendMessage ( g_qeglobals.d_hwndEntity,
+ WM_COMMAND,
+ (LBN_DBLCLK<<16) + IDC_E_LIST,
+ 0 );
+ return 0;
+ }
+ break;
+ }
+ return CallWindowProc (OldEntityListWindowProc, hwnd, uMsg, wParam, lParam);
+}
+
+
+/*
+================
+GetEntityControls
+
+Finds the controls from the dialog and
+moves them to the window
+================
+*/
+void GetEntityControls(HWND ghwndEntity)
+{
+ int i;
+
+ for (i = 0; i < EntLast; i++)
+ {
+ if (i == EntList || i == EntProps || i == EntComment)
+ continue;
+ if (i == EntKeyField || i == EntValueField)
+ continue;
+ hwndEnt[i] = GetDlgItem(ghwndEntity, rgIds[i]);
+ if (hwndEnt[i])
+ {
+ SetParent (hwndEnt[i], g_qeglobals.d_hwndEntity );
+ SendMessage(hwndEnt[i], WM_SETFONT, (WPARAM)GetStockObject(DEFAULT_GUI_FONT), (LPARAM)TRUE);
+ }
+ }
+
+
+ // SetParent apears to not modify some internal state
+ // on listboxes, so create it from scratch...
+
+ hwndEnt[EntList] = CreateWindow ("listbox", NULL,
+ LBS_STANDARD | LBS_NOINTEGRALHEIGHT | LBS_WANTKEYBOARDINPUT
+ | WS_VSCROLL | WS_CHILD | WS_VISIBLE,
+ 5, 5, 180, 99,
+ g_qeglobals.d_hwndEntity,
+ (HMENU)IDC_E_LIST,
+ g_qeglobals.d_hInstance,
+ NULL);
+ if (!hwndEnt[EntList])
+ Error ("CreateWindow failed");
+
+ hwndEnt[EntProps] = CreateWindow ("listbox", NULL,
+ LBS_STANDARD | LBS_NOINTEGRALHEIGHT | LBS_USETABSTOPS
+ | WS_VSCROLL | WS_CHILD | WS_VISIBLE,
+ 5, 100, 180, 99,
+ g_qeglobals.d_hwndEntity,
+ (HMENU)IDC_E_PROPS,
+ g_qeglobals.d_hInstance,
+ NULL);
+ if (!hwndEnt[EntProps])
+ Error ("CreateWindow failed");
+
+ hwndEnt[EntComment] = CreateWindow ("edit", NULL,
+ ES_MULTILINE | ES_READONLY | WS_VSCROLL | WS_CHILD | WS_VISIBLE | WS_BORDER,
+ 5, 100, 180, 99,
+ g_qeglobals.d_hwndEntity,
+ (HMENU)IDC_E_COMMENT,
+ g_qeglobals.d_hInstance,
+ NULL);
+ if (!hwndEnt[EntComment])
+ Error ("CreateWindow failed");
+
+ hwndEnt[EntKeyField] = CreateWindow ("edit", NULL,
+ WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL,
+ 5, 100, 180, 99,
+ g_qeglobals.d_hwndEntity,
+ (HMENU)IDC_E_KEY_FIELD,
+ g_qeglobals.d_hInstance,
+ NULL);
+ if (!hwndEnt[EntKeyField])
+ Error ("CreateWindow failed");
+
+ hwndEnt[EntValueField] = CreateWindow ("edit", NULL,
+ WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL,
+ 5, 100, 180, 99,
+ g_qeglobals.d_hwndEntity,
+ (HMENU)IDC_E_VALUE_FIELD,
+ g_qeglobals.d_hInstance,
+ NULL);
+ if (!hwndEnt[EntValueField])
+ Error ("CreateWindow failed");
+
+ g_wndTabs.SubclassDlgItem(IDC_TAB_MODE, CWnd::FromHandle(ghwndEntity));
+ hwndEnt[EntTab] = g_wndTabs.GetSafeHwnd();
+ g_wndTabs.InsertItem(0, "Groups");
+ ::SetParent(g_wndTabs.GetSafeHwnd(), g_qeglobals.d_hwndEntity);
+
+ if (g_pParentWnd->CurrentStyle() > 0 && g_pParentWnd->CurrentStyle() < 3)
+ {
+ g_qeglobals.d_hwndEdit = CreateWindow ("edit", NULL, ES_MULTILINE | ES_READONLY | WS_VSCROLL | WS_CHILD | WS_VISIBLE | WS_BORDER,
+ 5, 100, 180, 99, g_qeglobals.d_hwndEntity, (HMENU)IDC_E_STATUS,
+ g_qeglobals.d_hInstance, NULL);
+ if (!g_qeglobals.d_hwndEdit)
+ Error ("CreateWindow failed");
+ g_wndTabs.InsertItem(0, "Console");
+ g_wndTabs.InsertItem(0, "Textures");
+ }
+ g_wndTabs.InsertItem(0, "Entities");
+ g_wndTabs.ShowWindow(SW_SHOW);
+
+#if 0
+ for (i=0 ; i<12 ; i++)
+ {
+ hwndEnt[EntCheck1 + i] = CreateWindow ("button", NULL,
+ BS_AUTOCHECKBOX | WS_CHILD | WS_VISIBLE,
+ 5, 100, 180, 99,
+ entwindow,
+ (HMENU)IDC_E_STATUS,
+ main_instance,
+ NULL);
+ if (!hwndEnt[EntCheck1 + i])
+ Error ("CreateWindow failed");
+ }
+#endif
+ SendMessage(hwndEnt[EntList], WM_SETFONT, (WPARAM)GetStockObject(DEFAULT_GUI_FONT), (LPARAM)TRUE);
+ SendMessage(hwndEnt[EntProps], WM_SETFONT, (WPARAM)GetStockObject(DEFAULT_GUI_FONT), (LPARAM)TRUE);
+ SendMessage(hwndEnt[EntComment], WM_SETFONT, (WPARAM)GetStockObject(DEFAULT_GUI_FONT), (LPARAM)TRUE);
+ SendMessage(hwndEnt[EntKeyField], WM_SETFONT, (WPARAM)GetStockObject(DEFAULT_GUI_FONT), (LPARAM)TRUE);
+ SendMessage(hwndEnt[EntValueField], WM_SETFONT, (WPARAM)GetStockObject(DEFAULT_GUI_FONT), (LPARAM)TRUE);
+ SendMessage(hwndEnt[EntTab], WM_SETFONT, (WPARAM)GetStockObject(DEFAULT_GUI_FONT), (LPARAM)TRUE);
+
+ if (g_pParentWnd->CurrentStyle() > 0 && g_pParentWnd->CurrentStyle() < 3)
+ SendMessage(g_qeglobals.d_hwndEdit, WM_SETFONT, (WPARAM)GetStockObject(DEFAULT_GUI_FONT), (LPARAM)TRUE);
+}
+
+
+
+/*
+===============================================================
+
+ENTITY WINDOW
+
+===============================================================
+*/
+
+
+void FillClassList (void)
+{
+ eclass_t *pec;
+ int iIndex;
+
+ SendMessage(hwndEnt[EntList], LB_RESETCONTENT, 0 , 0);
+
+ for (pec = eclass ; pec ; pec = pec->next)
+ {
+ iIndex = SendMessage(hwndEnt[EntList], LB_ADDSTRING, 0 , (LPARAM)pec->name);
+ SendMessage(hwndEnt[EntList], LB_SETITEMDATA, iIndex, (LPARAM)pec);
+ }
+
+}
+
+
+/*
+==============
+WEnt_Create
+==============
+*/
+void WEnt_Create (HINSTANCE hInstance)
+{
+ WNDCLASS wc;
+
+ /* Register the camera class */
+ memset (&wc, 0, sizeof(wc));
+
+ wc.style = CS_NOCLOSE | CS_OWNDC;
+ wc.lpfnWndProc = (WNDPROC)EntityWndProc;
+ wc.cbClsExtra = 0;
+ wc.cbWndExtra = 0;
+ wc.hInstance = hInstance;
+ wc.hIcon = 0;
+ wc.hCursor = LoadCursor (NULL,IDC_ARROW);
+ wc.hbrBackground = (HBRUSH)GetStockObject (LTGRAY_BRUSH);
+ wc.lpszMenuName = NULL;
+ wc.lpszClassName = ENT_WINDOW_CLASS;
+
+ RegisterClass (&wc);
+
+ int nStyle = (g_pParentWnd->CurrentStyle() == QR_QE4) ? QE3_STYLE : QE3_STYLE2;
+ g_qeglobals.d_hwndEntity = CreateWindow (ENT_WINDOW_CLASS ,
+ "Entity",
+ nStyle,
+ 20,
+ 20,
+ 100,
+ 480, // size
+
+ g_qeglobals.d_hwndMain, // parent
+ 0, // no menu
+ hInstance,
+ NULL);
+
+ if (!g_qeglobals.d_hwndEntity )
+ Error ("Couldn't create Entity window");
+}
+
+/*
+==============
+CreateEntityWindow
+==============
+*/
+BOOL CreateEntityWindow(HINSTANCE hInstance)
+{
+ HWND hwndEntityPalette;
+
+ inspector_mode = W_ENTITY;
+
+ WEnt_Create (hInstance);
+
+ hwndEntityPalette = CreateDialog(hInstance, (char *)IDD_ENTITY, g_qeglobals.d_hwndMain, (DLGPROC)NULL);
+ if (!hwndEntityPalette)
+ Error ("CreateDialog failed");
+
+ GetEntityControls (hwndEntityPalette);
+ DestroyWindow (hwndEntityPalette);
+
+ OldFieldWindowProc = (WNDPROC)GetWindowLong (hwndEnt[EntKeyField], GWL_WNDPROC);
+ SetWindowLong (hwndEnt[EntKeyField], GWL_WNDPROC, (long)FieldWndProc);
+ SetWindowLong (hwndEnt[EntValueField], GWL_WNDPROC, (long)FieldWndProc);
+
+ OldEntityListWindowProc = (WNDPROC)GetWindowLong (hwndEnt[EntList], GWL_WNDPROC);
+ SetWindowLong (hwndEnt[EntList], GWL_WNDPROC, (long)EntityListWndProc);
+
+ FillClassList ();
+
+
+ LoadWindowPlacement(g_qeglobals.d_hwndEntity, "EntityWindowPlace");
+ ShowWindow (g_qeglobals.d_hwndEntity, SW_HIDE);
+ SetInspectorMode (W_CONSOLE);
+
+ return TRUE;
+}
+
+/*
+==============
+SetInspectorMode
+==============
+*/
+void SetInspectorMode(int iType)
+{
+ RECT rc;
+ HMENU hMenu = GetMenu( g_qeglobals.d_hwndMain );
+
+ if ((g_pParentWnd->CurrentStyle() == QR_SPLIT || g_pParentWnd->CurrentStyle() == QR_SPLITZ) && (iType == W_TEXTURE || iType == W_CONSOLE))
+ return;
+
+
+ // Is the caller asking us to cycle to the next window?
+
+ if (iType == -1)
+ {
+ if (inspector_mode == W_ENTITY)
+ iType = W_TEXTURE;
+ else if (inspector_mode == W_TEXTURE)
+ iType = W_CONSOLE;
+ else if (inspector_mode == W_CONSOLE)
+ iType = W_GROUP;
+ else
+ iType = W_ENTITY;
+ }
+
+ inspector_mode = iType;
+ switch(iType)
+ {
+
+ case W_ENTITY:
+ SetWindowText(g_qeglobals.d_hwndEntity, "Entity");
+ EnableMenuItem( hMenu, ID_MISC_SELECTENTITYCOLOR, MF_ENABLED | MF_BYCOMMAND );
+ // entity is always first in the inspector
+ g_wndTabs.SetCurSel(0);
+ break;
+
+ case W_TEXTURE:
+ SetWindowText(g_qeglobals.d_hwndEntity, "Textures");
+ g_pParentWnd->GetTexWnd()->FocusEdit();
+ EnableMenuItem( hMenu, ID_MISC_SELECTENTITYCOLOR, MF_GRAYED | MF_DISABLED | MF_BYCOMMAND );
+ if (g_pParentWnd->CurrentStyle() > 0 && g_pParentWnd->CurrentStyle() < 3)
+ g_wndTabs.SetCurSel(1);
+ break;
+
+ case W_CONSOLE:
+ SetWindowText(g_qeglobals.d_hwndEntity, "Console");
+ EnableMenuItem( hMenu, ID_MISC_SELECTENTITYCOLOR, MF_GRAYED | MF_DISABLED | MF_BYCOMMAND );
+ if (g_pParentWnd->CurrentStyle() > 0 && g_pParentWnd->CurrentStyle() < 3)
+ g_wndTabs.SetCurSel(2);
+ break;
+
+ case W_GROUP:
+ SetWindowText(g_qeglobals.d_hwndEntity, "Groups");
+ EnableMenuItem( hMenu, ID_MISC_SELECTENTITYCOLOR, MF_GRAYED | MF_DISABLED | MF_BYCOMMAND );
+ if (g_pParentWnd->CurrentStyle() > 0 && g_pParentWnd->CurrentStyle() < 3)
+ g_wndTabs.SetCurSel(3);
+ else
+ g_wndTabs.SetCurSel(1);
+ break;
+
+
+ default:
+ break;
+ }
+
+ GetWindowRect (g_qeglobals.d_hwndEntity, &rc);
+ SizeEntityDlg( rc.right - rc.left - 8, rc.bottom - rc.top - 20);
+
+
+// InvalidateRect(entwindow, NULL, true);
+// ShowWindow (entwindow, SW_SHOW);
+// UpdateWindow (entwindow);
+
+ HWND hFlag = (g_pParentWnd->CurrentStyle() == QR_QE4) ? HWND_TOP : HWND_TOPMOST;
+ SetWindowPos( g_qeglobals.d_hwndEntity, hFlag, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, SWP_NOSIZE | SWP_NOMOVE );
+ RedrawWindow (g_qeglobals.d_hwndEntity, NULL, NULL, RDW_ERASE | RDW_INVALIDATE| RDW_ERASENOW | RDW_UPDATENOW | RDW_ALLCHILDREN);
+}
+
+
+
+
+
+// SetKeyValuePairs
+//
+// Reset the key/value (aka property) listbox and fill it with the
+// k/v pairs from the entity being edited.
+//
+
+void SetKeyValuePairs (bool bClearMD3)
+{
+ epair_t *pep;
+ RECT rc;
+ char sz[4096];
+
+ if (edit_entity == NULL)
+ return;
+
+ // set key/value pair list
+
+ GetWindowRect(hwndEnt[EntProps], &rc);
+ SendMessage(hwndEnt[EntProps], LB_SETCOLUMNWIDTH, (rc.right - rc.left)/2, 0);
+ SendMessage(hwndEnt[EntProps], LB_RESETCONTENT, 0, 0);
+
+ // Walk through list and add pairs
+
+ for (pep = edit_entity->epairs ; pep ; pep = pep->next)
+ {
+ // if the key is less than 8 chars, add a tab for alignment
+ if (strlen(pep->key) > 8)
+ sprintf (sz, "%s\t%s", pep->key, pep->value);
+ else
+ sprintf (sz, "%s\t\t%s", pep->key, pep->value);
+ SendMessage(hwndEnt[EntProps], LB_ADDSTRING, 0, (LPARAM)sz);
+ }
+
+ if (edit_entity->eclass->nShowFlags & ECLASS_MISCMODEL)
+ {
+ // if this is a misc_model
+ // cache the md3 for display later
+ if (bClearMD3)
+ {
+ edit_entity->md3Class = NULL;
+ }
+ //char *pModel = ValueForKey(edit_entity, "model");
+
+ /*
+ if (pModel != NULL)
+ {
+ GetCachedModel(pModel, vMin, vMax);
+ }
+ */
+ }
+
+ Sys_UpdateWindows(W_CAMERA | W_XY);
+
+}
+
+// SetSpawnFlags
+//
+// Update the checkboxes to reflect the flag state of the entity
+//
+void SetSpawnFlags(void)
+{
+ int f;
+ int i;
+ int v;
+
+ f = atoi(ValueForKey (edit_entity, "spawnflags"));
+ for (i=0 ; i<12 ; i++)
+ {
+ v = !!(f&(1<<i));
+ SendMessage(hwndEnt[EntCheck1+i], BM_SETCHECK, v, 0);
+ }
+}
+
+
+// GetSpawnFlags
+//
+// Update the entity flags to reflect the state of the checkboxes
+//
+void GetSpawnFlags(void)
+{
+ int f;
+ int i, v;
+ char sz[32];
+
+ f = 0;
+ for (i=0 ; i<12 ; i++)
+ {
+ v = SendMessage(hwndEnt[EntCheck1+i], BM_GETCHECK, 0, 0);
+ f |= v<<i;
+ }
+
+ sprintf (sz, "%i", f);
+
+ if (multiple_entities)
+ {
+ brush_t *b;
+
+ for (b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ SetKeyValue(b->owner, "spawnflags", sz);
+ }
+ else
+ SetKeyValue (edit_entity, "spawnflags", sz);
+ SetKeyValuePairs ();
+}
+
+// UpdateSel
+//
+// Update the listbox, checkboxes and k/v pairs to reflect the new selection
+//
+BOOL UpdateSel(int iIndex, eclass_t *pec)
+{
+ int i;
+ brush_t *b;
+
+ if (selected_brushes.next == &selected_brushes)
+ {
+ edit_entity = world_entity;
+ multiple_entities = false;
+ }
+ else
+ {
+ edit_entity = selected_brushes.next->owner;
+ for (b=selected_brushes.next->next ; b != &selected_brushes ; b=b->next)
+ {
+ if (b->owner != edit_entity)
+ {
+ multiple_entities = true;
+ break;
+ }
+ }
+ }
+
+ if (iIndex != LB_ERR)
+ SendMessage(hwndEnt[EntList], LB_SETCURSEL, iIndex, 0);
+
+ if (pec == NULL)
+ return TRUE;
+
+ // Set up the description
+
+ SendMessage(hwndEnt[EntComment], WM_SETTEXT, 0,
+ (LPARAM)TranslateString(pec->comments));
+
+ for (i=0 ; i<8 ; i++)
+ {
+ HWND hwnd = hwndEnt[EntCheck1+i];
+ if (pec->flagnames[i] && pec->flagnames[i][0] != 0)
+ {
+ EnableWindow(hwnd, TRUE);
+ SendMessage(hwnd, WM_SETTEXT, 0, (LPARAM)pec->flagnames[i]);
+ } else {
+
+ // disable check box
+ SendMessage(hwnd, WM_SETTEXT, 0, (LPARAM)" ");
+ EnableWindow(hwnd, FALSE);
+ }
+ }
+
+ SetSpawnFlags();
+ SetKeyValuePairs();
+ return TRUE;
+}
+
+BOOL UpdateEntitySel(eclass_t *pec)
+{
+ int iIndex;
+
+ iIndex = (int)SendMessage(hwndEnt[EntList], LB_FINDSTRINGEXACT,
+ (WPARAM)-1, (LPARAM)pec->name);
+
+ return UpdateSel(iIndex, pec);
+}
+
+// CreateEntity
+//
+// Creates a new entity based on the currently selected brush and entity type.
+//
+
+void CreateEntity(void)
+{
+ eclass_t *pecNew;
+ entity_t *petNew;
+ int i;
+ HWND hwnd;
+ char sz[1024];
+
+ // check to make sure we have a brush
+
+ if (selected_brushes.next == &selected_brushes)
+ {
+ MessageBox(g_qeglobals.d_hwndMain, "You must have a selected brush to create an entity"
+ , "info", 0);
+ return;
+ }
+
+
+ // find out what type of entity we are trying to create
+
+ hwnd = hwndEnt[EntList];
+
+ i = SendMessage(hwndEnt[EntList], LB_GETCURSEL, 0, 0);
+
+ if (i < 0)
+ {
+ MessageBox(g_qeglobals.d_hwndMain, "You must have a selected class to create an entity"
+ , "info", 0);
+ return;
+ }
+
+ SendMessage(hwnd, LB_GETTEXT, i, (LPARAM)sz);
+
+ if (!stricmp(sz, "worldspawn"))
+ {
+ MessageBox(g_qeglobals.d_hwndMain, "Can't create an entity with worldspawn.", "info", 0);
+ return;
+ }
+
+ pecNew = Eclass_ForName(sz, false);
+
+ // create it
+
+ petNew = Entity_Create(pecNew);
+
+ if (petNew == NULL)
+ {
+ MessageBox(g_qeglobals.d_hwndMain, "Failed to create entity.", "info", 0);
+ return;
+ }
+
+ if (selected_brushes.next == &selected_brushes)
+ edit_entity = world_entity;
+ else
+ edit_entity = selected_brushes.next->owner;
+
+ SetKeyValuePairs();
+ Select_Deselect ();
+ Select_Brush (edit_entity->brushes.onext);
+ Sys_UpdateWindows(W_ALL);
+
+}
+
+
+
+/*
+===============
+AddProp
+
+===============
+*/
+void AddProp()
+{
+ char key[4096];
+ char value[4096];
+
+ if (edit_entity == NULL)
+ return;
+
+ // Get current selection text
+
+ SendMessage(hwndEnt[EntKeyField], WM_GETTEXT, sizeof(key)-1, (LPARAM)key);
+ SendMessage(hwndEnt[EntValueField], WM_GETTEXT, sizeof(value)-1, (LPARAM)value);
+
+ if (multiple_entities)
+ {
+ brush_t *b;
+
+ for (b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ SetKeyValue(b->owner, key, value);
+ }
+ else
+ SetKeyValue(edit_entity, key, value);
+
+ // refresh the prop listbox
+ SetKeyValuePairs();
+
+ // if it's a plugin entity, perhaps we need to update some drawing parameters
+ // NOTE: perhaps moving this code to a seperate func would help if we need it in other places
+ // TODO: we need to call some update func in the IPluginEntity in case model name changes etc.
+ // ( for the moment only bounding brush is updated ), see UpdateModelBrush in Ritual's Q3Radiant
+ if (edit_entity->eclass->nShowFlags & ECLASS_PLUGINENTITY)
+ {
+ vec3_t mins, maxs;
+ edit_entity->pPlugEnt->GetBounds( mins, maxs );
+ // replace old bounding brush by newly computed one
+ // NOTE: this part is similar to Entity_BuildModelBrush in Ritual's Q3Radiant, it can be
+ // usefull moved into a seperate func
+ brush_t *b,*oldbrush;
+ if (edit_entity->brushes.onext != &edit_entity->brushes)
+ oldbrush = edit_entity->brushes.onext;
+ b = Brush_Create (mins, maxs, &edit_entity->eclass->texdef);
+ Entity_LinkBrush (edit_entity, b);
+ Brush_Build( b, true );
+ Select_Deselect();
+ Brush_AddToList (edit_entity->brushes.onext, &selected_brushes);
+ if (oldbrush)
+ Brush_Free( oldbrush );
+ }
+
+}
+
+/*
+===============
+DelProp
+
+===============
+*/
+void DelProp(void)
+{
+ char sz[4096];
+
+ if (edit_entity == NULL)
+ return;
+
+ // Get current selection text
+
+ SendMessage(hwndEnt[EntKeyField], WM_GETTEXT, sizeof(sz)-1, (LPARAM)sz);
+
+ if (multiple_entities)
+ {
+ brush_t *b;
+
+ for (b=selected_brushes.next ; b != &selected_brushes ; b=b->next)
+ DeleteKey(b->owner, sz);
+ }
+ else
+ DeleteKey(edit_entity, sz);
+
+ // refresh the prop listbox
+
+ SetKeyValuePairs();
+}
+
+BOOL GetSelectAllCriteria(CString &strKey, CString &strVal) {
+ char sz[4096];
+ HWND hwnd = hwndEnt[EntProps];
+ int i = SendMessage(hwnd, LB_GETCURSEL, 0, 0);
+ if (i >= 0 && inspector_mode == W_ENTITY) {
+ SendMessage(hwndEnt[EntKeyField], WM_GETTEXT, sizeof(sz), (LPARAM)sz);
+ strKey = sz;
+ SendMessage(hwndEnt[EntValueField], WM_GETTEXT, sizeof(sz), (LPARAM)sz);
+ strVal = sz;
+ return TRUE;
+ }
+ return FALSE;
+}
+
+/*
+===============
+EditProp
+
+===============
+*/
+void EditProp(void)
+{
+ int i;
+ HWND hwnd;
+ char sz[4096];
+ char *val;
+
+ if (edit_entity == NULL)
+ return;
+
+ hwnd = hwndEnt[EntProps];
+
+ // Get current selection text
+
+ i = SendMessage(hwnd, LB_GETCURSEL, 0, 0);
+
+ if (i < 0)
+ return;
+
+ SendMessage(hwnd, LB_GETTEXT, i, (LPARAM)sz);
+
+ // strip it down to the key name
+
+ for(i=0;sz[i] != '\t';i++)
+ ;
+
+ sz[i] = '\0';
+
+ val = sz + i + 1;
+ if (*val == '\t')
+ val++;
+
+ SendMessage(hwndEnt[EntKeyField], WM_SETTEXT, 0, (LPARAM)sz);
+ SendMessage(hwndEnt[EntValueField], WM_SETTEXT, 0, (LPARAM)val);
+}
+
+
+HDWP defer;
+int col;
+void MOVE(HWND e, int x, int y, int w, int h, HWND hwndPlacement = HWND_TOP, int swp = SWP_NOACTIVATE | SWP_NOCOPYBITS | SWP_NOZORDER)
+{
+// defer=DeferWindowPos(defer,e,HWND_TOP,col+(x),y,w,h,SWP_SHOWWINDOW);
+// MoveWindow (e, col+x, y, w, h, FALSE);
+ SetWindowPos (e, hwndPlacement, col+x, y, w, h, swp);
+}
+
+
+/*
+===============
+SizeEnitityDlg
+
+Positions all controls so that the active inspector
+is displayed correctly and the inactive ones are
+off the side
+===============
+*/
+void SizeEntityDlg(int iWidth, int iHeight)
+{
+ int y, x, xCheck, yCheck;
+ int i, iRow;
+ int w, h;
+
+ if (iWidth < 32 || iHeight < 32)
+ return;
+
+ SendMessage( g_qeglobals.d_hwndEntity, WM_SETREDRAW, 0, 0);
+ iHeight -= 24;
+
+
+ //==========================================
+
+
+ //
+ // console
+ //
+ if (inspector_mode == W_CONSOLE)
+ {
+ col = 0;
+ }
+ else
+ {
+ col = iWidth;
+ }
+
+ if (g_pParentWnd->CurrentStyle() > 0 && g_pParentWnd->CurrentStyle() < 3)
+ MOVE(g_qeglobals.d_hwndEdit, DlgXBorder, DlgYBorder, iWidth - (2 * DlgXBorder), iHeight - (2 * DlgYBorder) );
+
+ //==========================================
+
+ //
+ // texture controls
+ //
+ if (inspector_mode == W_TEXTURE)
+ {
+ col = 0;
+ }
+ else
+ {
+ col = iWidth;
+ }
+
+ if (g_pParentWnd->CurrentStyle() > 0 && g_pParentWnd->CurrentStyle() < 3)
+ MOVE(g_qeglobals.d_hwndTexture, DlgXBorder, DlgYBorder, iWidth - (2 * DlgXBorder), iHeight - (2 * DlgYBorder) );
+
+ if (inspector_mode == W_GROUP)
+ {
+ col = 0;
+ }
+ else
+ {
+ col = iWidth;
+ }
+
+ MOVE(g_qeglobals.d_hwndGroup, DlgXBorder, DlgYBorder, iWidth - (2 * DlgXBorder), iHeight - (2 * DlgYBorder) );
+
+ //==========================================
+
+ //
+ // entity controls
+ //
+ if (inspector_mode == W_ENTITY)
+ {
+ col = 0;
+ }
+ else
+ {
+ col = iWidth;
+ }
+
+
+
+ // top half includes the entity list (2/3) and the
+ // comments (1/3) - 2 gaps, above and below.
+
+ y = iHeight/2;
+ y -= 2 * DlgYBorder;
+ y = y / 3;
+ w = iWidth - (2 * DlgXBorder);
+ MOVE(hwndEnt[EntList], DlgXBorder, DlgYBorder, w, 2 * y);
+
+ MOVE(hwndEnt[EntComment], DlgXBorder, 2 * DlgYBorder + 2 * y, w, y - (2 * DlgYBorder));
+
+ // bottom half includes flags (fixed), k/v pairs,
+ // and buttons (fixed).
+
+ // xCheck = width of a single check box
+ // yCheck = distance from top of one check to the next
+
+ xCheck = (iWidth - (2 * DlgXBorder)) / 3;
+ yCheck = 18;
+
+ x = DlgXBorder;
+
+ for (iRow = 0; iRow <= 12; iRow += 4)
+ {
+ y = iHeight/2;
+
+ for (i = 0; i < 4; i++)
+ {
+ MOVE(hwndEnt[EntCheck1 + i + iRow],
+ x, y, xCheck, yCheck);
+ y += yCheck;
+ }
+
+ x += xCheck;
+ }
+
+ //
+ // properties scroll box
+ //
+ y = iHeight/2 + 4 * yCheck;
+
+ w = iWidth - (2 * DlgXBorder);
+ h = (iHeight - (yCheck * 5 + 2 * DlgYBorder) ) - y;
+
+ MOVE(hwndEnt[EntProps], DlgXBorder, y, w, h);
+
+ y += h + DlgYBorder;
+
+ //
+ // key / value fields
+ //
+ w = iWidth-(DlgXBorder+45);
+ MOVE(hwndEnt[EntKeyLabel], DlgXBorder, y, 40, yCheck);
+ MOVE(hwndEnt[EntKeyField], DlgXBorder+40, y, w, yCheck);
+ y += yCheck;
+
+ MOVE(hwndEnt[EntValueLabel], DlgXBorder, y, 40, yCheck);
+ MOVE(hwndEnt[EntValueField], DlgXBorder+40, y, w, yCheck);
+ y += yCheck;
+
+ //
+ // angle check boxes
+ //
+ y += 2;
+ i = y;
+ x = DlgXBorder;
+
+ xCheck = yCheck*2;
+
+ MOVE(hwndEnt[EntDir135], x, y, xCheck, yCheck);
+ y += yCheck;
+
+ MOVE(hwndEnt[EntDir180], x, y, xCheck, yCheck);
+ y += yCheck;
+
+ MOVE(hwndEnt[EntDir225], x, y, xCheck, yCheck);
+
+ y = i;
+ x += xCheck;
+
+
+ MOVE(hwndEnt[EntDir90], x, y, xCheck, yCheck);
+ y += yCheck;
+ y += yCheck;
+
+ MOVE(hwndEnt[EntDir270], x, y, xCheck, yCheck);
+
+ y = i;
+ x += xCheck;
+
+
+ MOVE(hwndEnt[EntDir45], x, y, xCheck, yCheck);
+ y += yCheck;
+
+ MOVE(hwndEnt[EntDir0], x, y, xCheck, yCheck);
+ y += yCheck;
+
+ MOVE(hwndEnt[EntDir315], x, y, xCheck, yCheck);
+
+ y = i + yCheck/2;
+ x += xCheck + xCheck/2;
+
+
+ MOVE(hwndEnt[EntDirUp], x, y, xCheck, yCheck);
+ y += yCheck;
+
+ MOVE(hwndEnt[EntDirDown], x, y, xCheck, yCheck);
+
+ y = i;
+ x += 1.5 * xCheck;
+
+ MOVE(hwndEnt[EntDelProp], x, y, xCheck*2, yCheck);
+ y += yCheck + 4;
+
+ MOVE(hwndEnt[EntAssignSounds], x, y, xCheck*2, yCheck);
+ y += yCheck;
+ MOVE(hwndEnt[EntAssignModels], x, y, xCheck*2, yCheck);
+
+ // tab selector is always visible
+ col = 0;
+ iHeight += 24;
+ MOVE(hwndEnt[EntTab], 0,0,iWidth,iHeight, HWND_BOTTOM, SWP_NOACTIVATE | SWP_NOCOPYBITS);
+
+ SendMessage( g_qeglobals.d_hwndEntity, WM_SETREDRAW, 1, 0);
+// InvalidateRect(entwindow, NULL, TRUE);
+}
+
+void AssignSound()
+{
+ CString strBasePath = ValueForKey(g_qeglobals.d_project_entity, "basepath");
+ AddSlash(strBasePath);
+ CString strPath = strBasePath;
+ strPath += "sound\\";
+
+ CWaveOpen dlgFile(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, "Sound files (*.wav)|*.wav||", g_pParentWnd);
+ dlgFile.m_ofn.lpstrInitialDir = strPath;
+ if (dlgFile.DoModal() == IDOK)
+ {
+ SendMessage(hwndEnt[EntKeyField], WM_SETTEXT, 0, (LPARAM)"noise");
+ CString str = dlgFile.GetPathName().GetBuffer(0);
+ str.MakeLower();
+ strBasePath.MakeLower();
+ QE_ConvertDOSToUnixName(str.GetBuffer(0), str.GetBuffer(0));
+ QE_ConvertDOSToUnixName(strBasePath.GetBuffer(0), strBasePath.GetBuffer(0));
+ int n = str.Find(strBasePath);
+ if (n == 0)
+ {
+ str = str.Right(str.GetLength() - strBasePath.GetLength());
+ }
+
+ SendMessage(hwndEnt[EntValueField], WM_SETTEXT, 0, (LPARAM)str.GetBuffer(0));
+ AddProp();
+ g_pParentWnd->GetXYWnd()->SetFocus();
+ }
+}
+
+void AssignModel()
+{
+ CString strBasePath = ValueForKey(g_qeglobals.d_project_entity, "basepath");
+ AddSlash(strBasePath);
+ CString strPath = strBasePath;
+ strPath += "models\\mapobjects\\";
+
+ CFileDialog dlgFile(TRUE, NULL, NULL, OFN_OVERWRITEPROMPT, "Model files (*.md3)|*.md3||", g_pParentWnd);
+ dlgFile.m_ofn.lpstrInitialDir = strPath;
+ if (dlgFile.DoModal() == IDOK)
+ {
+ SendMessage(hwndEnt[EntKeyField], WM_SETTEXT, 0, (LPARAM)"model");
+ CString str = dlgFile.GetPathName().GetBuffer(0);
+ str.MakeLower();
+ strBasePath.MakeLower();
+ QE_ConvertDOSToUnixName(str.GetBuffer(0), str.GetBuffer(0));
+ QE_ConvertDOSToUnixName(strBasePath.GetBuffer(0), strBasePath.GetBuffer(0));
+ int n = str.Find(strBasePath);
+ if (n == 0)
+ {
+ str = str.Right(str.GetLength() - strBasePath.GetLength());
+ }
+
+ SendMessage(hwndEnt[EntValueField], WM_SETTEXT, 0, (LPARAM)str.GetBuffer(0));
+ AddProp();
+ edit_entity->md3Class = NULL;
+ edit_entity->brushes.onext->bModelFailed = false;
+ g_pParentWnd->GetXYWnd()->SetFocus();
+ }
+}
+
+
+/*
+=========================
+EntityWndProc
+=========================
+*/
+BOOL CALLBACK EntityWndProc(
+ HWND hwndDlg, // handle to dialog box
+ UINT uMsg, // message
+ WPARAM wParam, // first message parameter
+ LPARAM lParam) // second message parameter
+{
+ LPNMHDR lpnmh = NULL;
+ RECT rc;
+
+ GetClientRect(hwndDlg, &rc);
+
+ switch (uMsg)
+ {
+
+ case WM_CHAR :
+ {
+ char c = toupper(LOWORD(wParam));
+ // escape: hide the window
+ if (c == 27)
+ ShowWindow(hwndDlg, SW_HIDE);
+ if (c == 'N')
+ g_pParentWnd->PostMessage(WM_COMMAND, ID_VIEW_ENTITY, 0);
+ else
+ if (c == 'O')
+ g_pParentWnd->PostMessage(WM_COMMAND, ID_VIEW_CONSOLE, 0);
+ else
+ if (c == 'T')
+ g_pParentWnd->PostMessage(WM_COMMAND, ID_VIEW_TEXTURE, 0);
+ else
+ if (c == 'G')
+ g_pParentWnd->PostMessage(WM_COMMAND, ID_VIEW_GROUPS, 0);
+ else
+ DefWindowProc (hwndDlg, uMsg, wParam, lParam);
+ break;
+ }
+
+ case WM_NOTIFY:
+ lpnmh = reinterpret_cast<LPNMHDR>(lParam);
+ if (lpnmh->hwndFrom == g_wndTabs.GetSafeHwnd()) {
+ if ( lpnmh->code == TCN_SELCHANGE)
+ {
+ int n = g_wndTabs.GetCurSel();
+ if (g_pParentWnd->CurrentStyle() == 2 || g_pParentWnd->CurrentStyle() == 1)
+ {
+ if (n == 0) {
+ SetInspectorMode(W_ENTITY);
+ } else if (n == 1) {
+ SetInspectorMode(W_TEXTURE);
+ } else if (n == 2) {
+ SetInspectorMode(W_CONSOLE);
+ } else {
+ SetInspectorMode(W_GROUP);
+ }
+ }
+ else
+ {
+ if (n == 0) {
+ SetInspectorMode(W_ENTITY);
+ } else if (n == 1) {
+ SetInspectorMode(W_GROUP);
+ }
+ }
+ }
+ }
+ break;
+
+ case WM_SIZE:
+
+ DefWindowProc (hwndDlg, uMsg, wParam, lParam);
+ break;
+
+ case WM_DESTROY:
+ SaveWindowPlacement(g_qeglobals.d_hwndEntity, "EntityWindowPlace");
+ DefWindowProc(hwndDlg, uMsg, wParam, lParam);
+ break;
+
+ case WM_GETMINMAXINFO:
+ {
+ LPMINMAXINFO lpmmi;
+
+ lpmmi = (LPMINMAXINFO) lParam;
+ lpmmi->ptMinTrackSize.x = 320;
+ lpmmi->ptMinTrackSize.y = 500;
+ }
+ return 0;
+
+ case WM_WINDOWPOSCHANGING:
+ {
+ LPWINDOWPOS lpwp;
+ lpwp = (LPWINDOWPOS) lParam;
+
+ DefWindowProc (hwndDlg, uMsg, wParam, lParam);
+
+ lpwp->flags |= SWP_NOCOPYBITS;
+ SizeEntityDlg(lpwp->cx-8, lpwp->cy-32);
+ return 0;
+
+ }
+ return 0;
+
+
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+
+ case IDC_BTN_ASSIGNSOUND:
+ AssignSound();
+ break;
+
+ case IDC_BTN_ASSIGNMODEL:
+ AssignModel();
+ break;
+
+ case IDC_E_DELPROP:
+ DelProp();
+ SetFocus (g_qeglobals.d_hwndCamera);
+ break;
+
+ case IDC_E_0:
+ SetKeyValue (edit_entity, "angle", "360");
+ SetFocus (g_qeglobals.d_hwndCamera);
+ SetKeyValuePairs ();
+ break;
+ case IDC_E_45:
+ SetKeyValue (edit_entity, "angle", "45");
+ SetFocus (g_qeglobals.d_hwndCamera);
+ SetKeyValuePairs ();
+ break;
+ case IDC_E_90:
+ SetKeyValue (edit_entity, "angle", "90");
+ SetFocus (g_qeglobals.d_hwndCamera);
+ SetKeyValuePairs ();
+ break;
+ case IDC_E_135:
+ SetKeyValue (edit_entity, "angle", "135");
+ SetFocus (g_qeglobals.d_hwndCamera);
+ SetKeyValuePairs ();
+ break;
+ case IDC_E_180:
+ SetKeyValue (edit_entity, "angle", "180");
+ SetFocus (g_qeglobals.d_hwndCamera);
+ SetKeyValuePairs ();
+ break;
+ case IDC_E_225:
+ SetKeyValue (edit_entity, "angle", "225");
+ SetFocus (g_qeglobals.d_hwndCamera);
+ SetKeyValuePairs ();
+ break;
+ case IDC_E_270:
+ SetKeyValue (edit_entity, "angle", "270");
+ SetFocus (g_qeglobals.d_hwndCamera);
+ SetKeyValuePairs ();
+ break;
+ case IDC_E_315:
+ SetKeyValue (edit_entity, "angle", "315");
+ SetFocus (g_qeglobals.d_hwndCamera);
+ SetKeyValuePairs ();
+ break;
+ case IDC_E_UP:
+ SetKeyValue (edit_entity, "angle", "-1");
+ SetFocus (g_qeglobals.d_hwndCamera);
+ SetKeyValuePairs ();
+ break;
+ case IDC_E_DOWN:
+ SetKeyValue (edit_entity, "angle", "-2");
+ SetFocus (g_qeglobals.d_hwndCamera);
+ SetKeyValuePairs ();
+ break;
+
+ case IDC_BTN_HIDE:
+ ::PostMessage(g_qeglobals.d_hwndMain, WM_COMMAND, ID_VIEW_CAMERATOGGLE, 0);
+ break;
+
+ case IDC_CHECK1:
+ case IDC_CHECK2:
+ case IDC_CHECK3:
+ case IDC_CHECK4:
+ case IDC_CHECK5:
+ case IDC_CHECK6:
+ case IDC_CHECK7:
+ case IDC_CHECK8:
+ case IDC_CHECK9:
+ case IDC_CHECK10:
+ case IDC_CHECK11:
+ case IDC_CHECK12:
+ GetSpawnFlags();
+ SetFocus (g_qeglobals.d_hwndCamera);
+ break;
+
+
+ case IDC_E_PROPS:
+ switch (HIWORD(wParam))
+ {
+ case LBN_SELCHANGE:
+
+ EditProp();
+ return TRUE;
+ }
+ break;
+
+ case IDC_E_LIST:
+
+ switch (HIWORD(wParam)) {
+
+ case LBN_SELCHANGE:
+ {
+ int iIndex;
+ eclass_t *pec;
+
+ iIndex = SendMessage(hwndEnt[EntList], LB_GETCURSEL, 0, 0);
+ pec = (eclass_t *)SendMessage(hwndEnt[EntList], LB_GETITEMDATA,
+ iIndex, 0);
+
+ UpdateSel(iIndex, pec);
+
+ return TRUE;
+ break;
+ }
+
+ case LBN_DBLCLK:
+ CreateEntity ();
+ SetFocus (g_qeglobals.d_hwndCamera);
+ break;
+ }
+ break;
+
+
+ default:
+ return DefWindowProc( hwndDlg, uMsg, wParam, lParam );
+ }
+
+ return 0;
+ }
+
+ return DefWindowProc (hwndDlg, uMsg, wParam, lParam);
+}
+
diff --git a/q3radiant/Win_main.cpp b/q3radiant/Win_main.cpp
new file mode 100755
index 0000000..342749e
--- /dev/null
+++ b/q3radiant/Win_main.cpp
@@ -0,0 +1,1085 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "stdafx.h"
+#include "qe3.h"
+#include <process.h>
+#include "mru.h"
+#include "entityw.h"
+#include "PrefsDlg.h"
+
+static HWND s_hwndToolbar;
+
+BOOL SaveRegistryInfo(const char *pszName, void *pvBuf, long lSize);
+BOOL LoadRegistryInfo(const char *pszName, void *pvBuf, long *plSize);
+
+static HWND CreateMyStatusWindow(HINSTANCE hInst);
+static HWND CreateToolBar(HINSTANCE hinst);
+
+extern void WXY_Print( void );
+
+/*
+==============================================================================
+
+ MENU
+
+==============================================================================
+*/
+
+void OpenDialog (void);
+void SaveAsDialog (bool bRegion);
+qboolean ConfirmModified (void);
+void Select_Ungroup (void);
+
+void QE_ExpandBspString (char *bspaction, char *out, char *mapname, bool useTemps)
+{
+ char *in;
+ char src[2048];
+ char rsh[2048];
+ char base[2048];
+
+ strcpy(src, mapname);
+ strlwr(src);
+ in = strstr(src, "maps/");
+ if (!in)
+ {
+ in = strstr(src, "maps\\");
+ }
+ if (in)
+ {
+ in += 5;
+ strcpy(base, in);
+ in = base;
+ while (*in)
+ {
+ if (*in == '\\')
+ {
+ *in = '/';
+ }
+ in++;
+ }
+ }
+ else
+ {
+ ExtractFileName (mapname, base);
+ }
+
+ if (useTemps) {
+ CString str;
+ CString strExt = "map";
+ if ( strstr(mapname, ".reg") ) {
+ strExt = "reg";
+ }
+ str.Format("%s/maps/%i.%s", ValueForKey(g_qeglobals.d_project_entity, "remotebasepath"), ::GetTickCount(), strExt);
+ CopyFile(mapname, str, FALSE);
+ sprintf (src, "-tempname %s %s/maps/%s", str, ValueForKey(g_qeglobals.d_project_entity, "remotebasepath"), base);
+ } else {
+ sprintf (src, "%s/maps/%s", ValueForKey(g_qeglobals.d_project_entity, "remotebasepath"), base);
+ }
+ strcpy (rsh, ValueForKey(g_qeglobals.d_project_entity, "rshcmd"));
+
+ QE_ConvertDOSToUnixName(src, src);
+
+ in = ValueForKey( g_qeglobals.d_project_entity, bspaction );
+ while (*in)
+ {
+ if (in[0] == '!')
+ {
+ strcpy (out, rsh);
+ out += strlen(rsh);
+ in++;
+ continue;
+ }
+ if (in[0] == '$')
+ {
+ strcpy (out, src);
+ out += strlen(src);
+ in++;
+ continue;
+ }
+ if (in[0] == '@')
+ {
+ *out++ = '"';
+ in++;
+ continue;
+ }
+ *out++ = *in++;
+ }
+ *out = 0;
+}
+
+void FindReplace(CString& strContents, const char* pTag, const char* pValue)
+{
+ if (strcmp(pTag, pValue) == 0)
+ return;
+ for (int nPos = strContents.Find(pTag); nPos >= 0; nPos = strContents.Find(pTag))
+ {
+ int nRightLen = strContents.GetLength() - strlen(pTag) - nPos;
+ CString strLeft = strContents.Left(nPos);
+ CString strRight = strContents.Right(nRightLen);
+ strLeft += pValue;
+ strLeft += strRight;
+ strContents = strLeft;
+ }
+}
+
+
+
+HWND g_hWnd = NULL;
+HANDLE g_hToolThread = NULL;
+CString g_strParams;
+
+UINT ToolThread(LPVOID pParam)
+{
+ char* p = reinterpret_cast<char*>(pParam);
+ if (g_PrefsDlg.m_bPAK)
+ RunTools(p, g_hWnd, g_PrefsDlg.m_strPAKFile);
+ else
+ RunTools(p, g_hWnd, "");
+ g_hToolThread = NULL;
+ delete []p;
+ return 0;
+}
+
+void ThreadTools(char* p)
+{
+ CWinThread* pThread = AfxBeginThread(ToolThread, reinterpret_cast<LPVOID>(p));
+ g_hToolThread = pThread->m_hThread;
+}
+
+HWND g_hwndFoundIt = NULL;
+
+BOOL CALLBACK EnumChildProc(HWND hwnd, LPARAM lParam) {
+ char buff[1024];
+ const char* p = reinterpret_cast<const char*>(lParam);
+ GetWindowText(hwnd, buff, 1024);
+ if (!strcmpi(p, buff)) {
+ g_hwndFoundIt = hwnd;
+ return 1;
+ }
+ return 1;
+}
+
+
+HWND FindAnyWindow(const char *pTitle) {
+ HWND hwndDesktop = GetDesktopWindow();
+ g_hwndFoundIt = NULL;
+ if ( hwndDesktop ) {
+ EnumChildWindows(hwndDesktop, (WNDENUMPROC)EnumChildProc, reinterpret_cast<LPARAM>(pTitle));
+ }
+ return g_hwndFoundIt;
+}
+
+
+const UINT wm_AddCommand = RegisterWindowMessage( "Q3MPC_AddCommand" );
+
+CTime g_tBegin;
+void RunBsp (char *command)
+{
+ char sys[2048];
+ char batpath[2048];
+ char outputpath[2048];
+ char temppath[1024];
+ char name[2048];
+ char cWork[2048];
+ FILE *hFile;
+ BOOL ret;
+ PROCESS_INFORMATION ProcessInformation;
+ STARTUPINFO startupinfo;
+ HWND hwndPClient = NULL;
+
+ g_hWnd = g_pParentWnd->GetSafeHwnd();
+ SetInspectorMode(W_CONSOLE);
+ g_tBegin = CTime::GetCurrentTime();
+
+
+ DWORD dwExitcode;
+ ret = GetExitCodeProcess (g_hToolThread, &dwExitcode);
+ if (dwExitcode != STILL_ACTIVE)
+ g_hToolThread = NULL;
+
+ if (bsp_process || g_hToolThread)
+ {
+ Sys_Printf ("BSP is still going...\n");
+ return;
+ }
+
+ outputpath[0] = '\0';
+ GetTempPath(512, temppath);
+
+ CString strOutFile = temppath;
+ AddSlash(strOutFile);
+ strOutFile += "junk.txt";
+
+ sprintf (outputpath, " >>%s\r\n", strOutFile);
+
+ strcpy (name, currentmap);
+ if (region_active)
+ {
+ Map_SaveFile (name, false);
+ StripExtension (name);
+ strcat (name, ".reg");
+ }
+
+ Map_SaveFile (name, region_active);
+
+ // FIXME: this code just gets worse and worse
+ CString strPath, strFile;
+
+ char *rsh = ValueForKey(g_qeglobals.d_project_entity, "rshcmd");
+ if (rsh == NULL)
+ {
+ ExtractPath_and_Filename(name, strPath, strFile);
+ AddSlash(strPath);
+ BuildShortPathName(strPath, cWork, 1024);
+ strcat(cWork, strFile);
+ }
+ else
+ {
+ strcpy(cWork, name);
+ }
+
+ hwndPClient = FindWindow(NULL, "Q3Map Process Client");
+ if ( hwndPClient == NULL ) {
+ hwndPClient = FindAnyWindow("Q3Map Process Client");
+ }
+
+ Sys_Printf("Window info for Process Client %i\n", reinterpret_cast<int>(hwndPClient));
+
+ bool processServer = (rsh && strlen(rsh) > 0 && hwndPClient);
+
+ QE_ExpandBspString (command, sys, cWork, processServer);
+
+ // if we can find the q3map process server running
+ // we will submit maps to it instead of via createprocess
+ //
+ if (processServer)
+ {
+ CString str;
+ char cBuff[2048];
+ char *pStart = sys;
+ char *pEnd = strstr(pStart, "&&");
+ while (pEnd)
+ {
+ int nLen = pEnd-pStart-1;
+ strncpy(cBuff, pStart, nLen);
+ cBuff[nLen] = 0;
+ str = cBuff;
+ FindReplace(str, rsh, "");
+ str.TrimLeft(' ');
+ str.TrimRight(' ');
+ ATOM a = GlobalAddAtom(str);
+ PostMessage(hwndPClient, wm_AddCommand, 0, (LPARAM)a);
+ pStart = pEnd+2;
+ pEnd = strstr(pStart, "&&");
+ }
+ str = pStart;
+ FindReplace(str, rsh, "");
+ str.TrimLeft(' ');
+ str.TrimRight(' ');
+ ATOM a = GlobalAddAtom(str);
+ PostMessage(hwndPClient, wm_AddCommand, 0, (LPARAM)a);
+ Sys_Printf("Commands sent to Q3Map Process Client\n");
+ return;
+ }
+
+ CString strSys = sys;
+
+ FindReplace(strSys, "&&", outputpath);
+ strcpy(sys, strSys);
+ strcat(sys, outputpath);
+
+ if (g_PrefsDlg.m_bInternalBSP)
+ {
+ g_tBegin = CTime::GetCurrentTime();
+ strSys.MakeLower();
+ char* p = new char[strSys.GetLength()+1];
+ strcpy(p, strSys.GetBuffer(0));
+ ThreadTools(p);
+ }
+ else
+ {
+ Sys_ClearPrintf ();
+ Sys_Printf ("==================\nRunning bsp command...\n");
+ Sys_Printf ("\n%s\n", sys);
+
+ //++timo removed the old way BSP commands .. dumping to junk.txt doesn't work on my win98 box
+ // FIXME : will most likely break Quake2 BSP commands, is fitted to a one-lined sys command
+ //
+ // write qe3bsp.bat
+ //
+
+ sprintf (batpath, "%sqe3bsp.bat", temppath);
+ hFile = fopen(batpath, "w");
+ if (!hFile)
+ Error ("Can't write to %s", batpath);
+ fprintf (hFile, sys);
+ fclose (hFile);
+
+ Pointfile_Delete ();
+
+ // delete junk.txt file
+ remove(strOutFile);
+
+ GetStartupInfo (&startupinfo);
+
+ ret = CreateProcess(
+ batpath,
+ NULL,
+ NULL,
+ NULL,
+ FALSE,
+ 0,
+ NULL,
+ NULL,
+ &startupinfo,
+ &ProcessInformation
+ );
+
+ if (!ret)
+ Error ("CreateProcess failed");
+
+ bsp_process = ProcessInformation.hProcess;
+
+ Sleep (100); // give the new process a chance to open it's window
+
+ BringWindowToTop( g_qeglobals.d_hwndMain ); // pop us back on top
+#if 0
+ //
+ // write qe3bsp.bat
+ //
+ sprintf (batpath, "%sqe3bsp.bat", temppath);
+ hFile = fopen(batpath, "w");
+ if (!hFile)
+ Error ("Can't write to %s", batpath);
+ fprintf (hFile, sys);
+ fclose (hFile);
+
+ //
+ // write qe3bsp2.bat
+ //
+ sprintf (batpath, "%sqe3bsp2.bat", temppath);
+ hFile = fopen(batpath, "w");
+ if (!hFile)
+ Error ("Can't write to %s", batpath);
+ fprintf (hFile, "%sqe3bsp.bat > %s", temppath, outputpath);
+ fclose (hFile);
+
+ Pointfile_Delete ();
+
+ GetStartupInfo (&startupinfo);
+
+ ret = CreateProcess(
+ batpath, // pointer to name of executable module
+ NULL, // pointer to command line string
+ NULL, // pointer to process security attributes
+ NULL, // pointer to thread security attributes
+ FALSE, // handle inheritance flag
+ 0 /*DETACHED_PROCESS*/, // creation flags
+ NULL, // pointer to new environment block
+ NULL, // pointer to current directory name
+ &startupinfo, // pointer to STARTUPINFO
+ &ProcessInformation // pointer to PROCESS_INFORMATION
+ );
+
+ if (!ret)
+ Error ("CreateProcess failed");
+
+ bsp_process = ProcessInformation.hProcess;
+
+ Sleep (100); // give the new process a chance to open it's window
+
+ //BringWindowToTop( g_qeglobals.d_hwndMain ); // pop us back on top
+ //SetFocus (g_qeglobals.d_hwndCamera);
+#endif
+ }
+}
+
+void DLLBuildDone()
+{
+ g_hToolThread = NULL;
+ CTime tEnd = CTime::GetCurrentTime();
+ CTimeSpan tElapsed = tEnd - g_tBegin;
+ CString strElapsed;
+ strElapsed.Format("Run time was %i hours, %i minutes and %i seconds", tElapsed.GetHours(), tElapsed.GetMinutes(), tElapsed.GetSeconds());
+ Sys_Printf(strElapsed.GetBuffer(0));
+ Pointfile_Check();
+
+ if (g_PrefsDlg.m_bRunQuake == TRUE)
+ {
+ char cCurDir[1024];
+ GetCurrentDirectory(1024, cCurDir);
+ CString strExePath = g_PrefsDlg.m_strQuake2;
+ CString strOrgPath;
+ CString strOrgFile;
+ ExtractPath_and_Filename(currentmap, strOrgPath, strOrgFile);
+ if (g_PrefsDlg.m_bSetGame == TRUE) // run in place with set game.. don't copy map
+ {
+ CString strBasePath = ValueForKey(g_qeglobals.d_project_entity, "basepath");
+ strExePath += " +set game ";
+ strExePath += strBasePath;
+ WinExec(strExePath, SW_SHOW);
+ }
+ else
+ {
+ CString strCopyPath = strExePath;
+ char* pBuffer = strCopyPath.GetBufferSetLength(_MAX_PATH + 1);
+ pBuffer[strCopyPath.ReverseFind('\\') + 1] = '\0';
+ strCopyPath.ReleaseBuffer();
+ SetCurrentDirectory(strCopyPath);
+ CString strOrgPath;
+ CString strOrgFile;
+ ExtractPath_and_Filename(currentmap, strOrgPath, strOrgFile);
+ AddSlash(strCopyPath);
+ FindReplace(strOrgFile, ".map", ".bsp");
+ strCopyPath += "\\baseq2\\maps\\";
+ strCopyPath += strOrgFile;
+ AddSlash(strOrgPath);
+ strOrgPath += strOrgFile;
+ bool bRun = (strOrgPath.CompareNoCase(strCopyPath) == 0);
+ if (!bRun)
+ bRun = (CopyFile(strOrgPath, strCopyPath, FALSE) == TRUE);
+ if (bRun)
+ {
+ FindReplace(strOrgFile, ".bsp", "");
+ strExePath += " +map ";
+ strExePath += strOrgFile;
+ WinExec(strExePath, SW_SHOW);
+ }
+ }
+ SetCurrentDirectory(cCurDir);
+ }
+
+}
+
+/*
+=============
+DoColor
+
+=============
+*/
+
+class CMyColorDialog : public CColorDialog
+{
+ DECLARE_DYNCREATE(CMyColorDialog);
+ // Construction
+public:
+ CMyColorDialog( COLORREF clrInit = 0, DWORD dwFlags = 0, CWnd*
+pParentWnd = NULL );
+ // Statics
+protected:
+ enum { NCUSTCOLORS = 16 };
+ static COLORREF c_CustColors[NCUSTCOLORS];
+ static COLORREF c_LastCustColors[NCUSTCOLORS];
+ static bool c_NeedToInitCustColors;
+protected:
+ static void InitCustColors();
+ static void SaveCustColors();
+ // Dialog Data
+protected:
+ //{{AFX_DATA(CMyColorDialog)
+ //}}AFX_DATA
+ // Overrides
+protected:
+ // ClassWizard generate virtual function overrides
+ //{{AFX_VIRTUAL(CMyColorDialog)
+public:
+ virtual int DoModal();
+protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+ // Implementation
+protected:
+ // Generated message map functions
+ //{{AFX_MSG(CMyColorDialog)
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+IMPLEMENT_DYNCREATE(CMyColorDialog, CColorDialog)
+
+bool CMyColorDialog::c_NeedToInitCustColors = true;
+COLORREF CMyColorDialog::c_CustColors[];
+COLORREF CMyColorDialog::c_LastCustColors[];
+
+#define SECTION _T("Custom Colors")
+
+void CMyColorDialog::InitCustColors() {
+ for (int i = 0; i < NCUSTCOLORS; i++) {
+ CString entry; entry.Format("%d",i);
+ c_LastCustColors[i] = c_CustColors[i] =
+ ::AfxGetApp()->GetProfileInt(SECTION,entry,RGB(255,255,255));
+ }
+ c_NeedToInitCustColors= false;
+}
+
+void CMyColorDialog::SaveCustColors() {
+ for (int i = 0; i < NCUSTCOLORS; i++) {
+ if (c_LastCustColors[i] != c_CustColors[i]) {
+ CString entry; entry.Format("%d",i);
+ if (c_CustColors[i] == RGB(255,255,255)) {
+ ::AfxGetApp()->WriteProfileString(SECTION,entry,NULL);
+ } else {
+ ::AfxGetApp()->WriteProfileInt(SECTION, entry,c_CustColors[i]);
+ }
+ c_LastCustColors[i] = c_CustColors[i];
+ }
+ }
+}
+
+CMyColorDialog::CMyColorDialog( COLORREF clrInit, DWORD dwFlags,
+ CWnd* pParentWnd) : CColorDialog(clrInit,dwFlags,pParentWnd)
+{
+ //{{AFX_DATA_INIT(CMyColorDialog)
+ //}}AFX_DATA_INIT
+ if (c_NeedToInitCustColors) {
+ InitCustColors();
+ }
+ m_cc.lpCustColors = c_CustColors;
+}
+
+int CMyColorDialog::DoModal() {
+ int code = CColorDialog::DoModal();
+ SaveCustColors();
+ return code;
+}
+
+void CMyColorDialog::DoDataExchange(CDataExchange* pDX) {
+ // overridden (calls this base class)
+ CColorDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CMyColorDialog)
+ //}}AFX_DATA_MAP
+}
+
+BEGIN_MESSAGE_MAP(CMyColorDialog, CColorDialog)
+//{{AFX_MSG_MAP(CMyColorDialog)
+//}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+void DoNewColor(int* i1, int* i2, int* i3)
+{
+ COLORREF cr = (*i1) +
+ ((*i2) <<8) +
+ ((*i3) <<16);
+ CMyColorDialog dlg(cr, CC_FULLOPEN | CC_RGBINIT);
+ if (dlg.DoModal() == IDOK)
+ {
+ *i1 = (dlg.m_cc.rgbResult & 255);
+ *i2 = ((dlg.m_cc.rgbResult >> 8) & 255);
+ *i3 = ((dlg.m_cc.rgbResult >> 16) & 255);
+ }
+
+}
+
+
+qboolean DoColor(int iIndex)
+{
+
+ COLORREF cr = (int)(g_qeglobals.d_savedinfo.colors[iIndex][0]*255) +
+ (((int)(g_qeglobals.d_savedinfo.colors[iIndex][1]*255))<<8) +
+ (((int)(g_qeglobals.d_savedinfo.colors[iIndex][2]*255))<<16);
+ CMyColorDialog dlg(cr, CC_FULLOPEN | CC_RGBINIT);
+ if (dlg.DoModal() == IDOK)
+ {
+ g_qeglobals.d_savedinfo.colors[iIndex][0] = (dlg.m_cc.rgbResult&255)/255.0;
+ g_qeglobals.d_savedinfo.colors[iIndex][1] = ((dlg.m_cc.rgbResult>>8)&255)/255.0;
+ g_qeglobals.d_savedinfo.colors[iIndex][2] = ((dlg.m_cc.rgbResult>>16)&255)/255.0;
+
+ /*
+ ** scale colors so that at least one component is at 1.0F
+ ** if this is meant to select an entity color
+ */
+ if ( iIndex == COLOR_ENTITY )
+ {
+ float largest = 0.0F;
+
+ if ( g_qeglobals.d_savedinfo.colors[iIndex][0] > largest )
+ largest = g_qeglobals.d_savedinfo.colors[iIndex][0];
+ if ( g_qeglobals.d_savedinfo.colors[iIndex][1] > largest )
+ largest = g_qeglobals.d_savedinfo.colors[iIndex][1];
+ if ( g_qeglobals.d_savedinfo.colors[iIndex][2] > largest )
+ largest = g_qeglobals.d_savedinfo.colors[iIndex][2];
+
+ if ( largest == 0.0F )
+ {
+ g_qeglobals.d_savedinfo.colors[iIndex][0] = 1.0F;
+ g_qeglobals.d_savedinfo.colors[iIndex][1] = 1.0F;
+ g_qeglobals.d_savedinfo.colors[iIndex][2] = 1.0F;
+ }
+ else
+ {
+ float scaler = 1.0F / largest;
+
+ g_qeglobals.d_savedinfo.colors[iIndex][0] *= scaler;
+ g_qeglobals.d_savedinfo.colors[iIndex][1] *= scaler;
+ g_qeglobals.d_savedinfo.colors[iIndex][2] *= scaler;
+ }
+ }
+
+ Sys_UpdateWindows (W_ALL);
+ return true;
+ }
+ else return false;
+
+}
+
+
+/* Copied from MSDN */
+
+BOOL DoMru(HWND hWnd,WORD wId)
+{
+ char szFileName[128];
+ OFSTRUCT of;
+ BOOL fExist;
+
+ GetMenuItem(g_qeglobals.d_lpMruMenu, wId, TRUE, szFileName, sizeof(szFileName));
+
+ // Test if the file exists.
+
+ fExist = OpenFile(szFileName ,&of,OF_EXIST) != HFILE_ERROR;
+
+ if (fExist) {
+
+ // Place the file on the top of MRU.
+ AddNewItem(g_qeglobals.d_lpMruMenu,(LPSTR)szFileName);
+
+ // Now perform opening this file !!!
+ Map_LoadFile (szFileName);
+ }
+ else
+ // Remove the file on MRU.
+ DelMenuItem(g_qeglobals.d_lpMruMenu,wId,TRUE);
+
+ // Refresh the File menu.
+ PlaceMenuMRUItem(g_qeglobals.d_lpMruMenu,GetSubMenu(GetMenu(hWnd),0),
+ ID_FILE_EXIT);
+
+ return fExist;
+}
+
+
+
+/*
+==============
+Main_Create
+==============
+*/
+
+void MFCCreate (HINSTANCE hInstance)
+{
+ HMENU hMenu = NULL;
+ int i = sizeof(g_qeglobals.d_savedinfo);
+ long l = i;
+
+ g_qeglobals.d_savedinfo.exclude |= (EXCLUDE_HINT | EXCLUDE_CLIP);
+ LoadRegistryInfo("SavedInfo", &g_qeglobals.d_savedinfo, &l);
+
+ int nOldSize = g_qeglobals.d_savedinfo.iSize;
+ if (g_qeglobals.d_savedinfo.iSize != sizeof(g_qeglobals.d_savedinfo))
+ {
+ // fill in new defaults
+ g_qeglobals.d_savedinfo.iSize = sizeof(g_qeglobals.d_savedinfo);
+ g_qeglobals.d_savedinfo.fGamma = 1.0;
+ g_qeglobals.d_savedinfo.iTexMenu = ID_VIEW_BILINEARMIPMAP;
+ g_qeglobals.d_savedinfo.m_nTextureTweak = 1;
+
+ //g_qeglobals.d_savedinfo.exclude = INCLUDE_EASY | INCLUDE_NORMAL | INCLUDE_HARD | INCLUDE_DEATHMATCH;
+ g_qeglobals.d_savedinfo.show_coordinates = true;
+ g_qeglobals.d_savedinfo.show_names = false;
+
+ for (i=0 ; i<3 ; i++)
+ {
+ g_qeglobals.d_savedinfo.colors[COLOR_TEXTUREBACK][i] = 0.25;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDBACK][i] = 1.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDMINOR][i] = 0.75;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDMAJOR][i] = 0.5;
+ g_qeglobals.d_savedinfo.colors[COLOR_CAMERABACK][i] = 0.25;
+ }
+
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDBLOCK][0] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDBLOCK][1] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDBLOCK][2] = 1.0;
+
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDTEXT][0] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDTEXT][1] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDTEXT][2] = 0.0;
+
+ g_qeglobals.d_savedinfo.colors[COLOR_SELBRUSHES][0] = 1.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_SELBRUSHES][1] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_SELBRUSHES][2] = 0.0;
+
+ g_qeglobals.d_savedinfo.colors[COLOR_CLIPPER][0] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_CLIPPER][1] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_CLIPPER][2] = 1.0;
+
+ g_qeglobals.d_savedinfo.colors[COLOR_BRUSHES][0] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_BRUSHES][1] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_BRUSHES][2] = 0.0;
+
+ g_qeglobals.d_savedinfo.colors[COLOR_VIEWNAME][0] = 0.5;
+ g_qeglobals.d_savedinfo.colors[COLOR_VIEWNAME][1] = 0.0;
+ g_qeglobals.d_savedinfo.colors[COLOR_VIEWNAME][2] = 0.75;
+
+
+ // old size was smaller, reload original prefs
+ if (nOldSize < sizeof(g_qeglobals.d_savedinfo))
+ {
+ long l = nOldSize;
+ LoadRegistryInfo("SavedInfo", &g_qeglobals.d_savedinfo, &l);
+ }
+
+ }
+ if ( ( hMenu = GetMenu( g_qeglobals.d_hwndMain ) ) != 0 )
+ {
+ // by default all of these are checked because that's how they're defined in the menu editor
+ if ( !g_qeglobals.d_savedinfo.show_names )
+ CheckMenuItem( hMenu, ID_VIEW_SHOWNAMES, MF_BYCOMMAND | MF_UNCHECKED );
+ if ( !g_qeglobals.d_savedinfo.show_coordinates )
+ CheckMenuItem( hMenu, ID_VIEW_SHOWCOORDINATES, MF_BYCOMMAND | MF_UNCHECKED );
+
+ if ( g_qeglobals.d_savedinfo.exclude & EXCLUDE_LIGHTS )
+ CheckMenuItem( hMenu, ID_VIEW_SHOWLIGHTS, MF_BYCOMMAND | MF_UNCHECKED );
+ if ( g_qeglobals.d_savedinfo.exclude & EXCLUDE_ENT )
+ CheckMenuItem( hMenu, ID_VIEW_ENTITY, MF_BYCOMMAND | MF_UNCHECKED );
+ if ( g_qeglobals.d_savedinfo.exclude & EXCLUDE_PATHS )
+ CheckMenuItem( hMenu, ID_VIEW_SHOWPATH, MF_BYCOMMAND | MF_UNCHECKED );
+ if ( g_qeglobals.d_savedinfo.exclude & EXCLUDE_WATER )
+ CheckMenuItem( hMenu, ID_VIEW_SHOWWATER, MF_BYCOMMAND | MF_UNCHECKED );
+ if ( g_qeglobals.d_savedinfo.exclude & EXCLUDE_WORLD )
+ CheckMenuItem( hMenu, ID_VIEW_SHOWWORLD, MF_BYCOMMAND | MF_UNCHECKED );
+ if ( g_qeglobals.d_savedinfo.exclude & EXCLUDE_CLIP )
+ CheckMenuItem( hMenu, ID_VIEW_SHOWCLIP, MF_BYCOMMAND | MF_UNCHECKED );
+ if ( g_qeglobals.d_savedinfo.exclude & EXCLUDE_HINT )
+ CheckMenuItem( hMenu, ID_VIEW_SHOWHINT, MF_BYCOMMAND | MF_UNCHECKED );
+ if ( g_qeglobals.d_savedinfo.exclude & EXCLUDE_CAULK )
+ CheckMenuItem( hMenu, ID_VIEW_SHOWCAULK, MF_BYCOMMAND | MF_UNCHECKED );
+ }
+
+}
+
+
+/*
+=============================================================
+
+REGISTRY INFO
+
+=============================================================
+*/
+
+BOOL SaveRegistryInfo(const char *pszName, void *pvBuf, long lSize)
+{
+ LONG lres;
+ DWORD dwDisp;
+ HKEY hKeyId;
+
+ if (g_qeglobals.use_ini)
+ {
+ lres = RegCreateKeyEx(HKEY_CURRENT_USER, g_qeglobals.use_ini_registry, 0, NULL,
+ REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKeyId, &dwDisp);
+ }
+ else
+ {
+ lres = RegCreateKeyEx(HKEY_CURRENT_USER, "Software\\Q3Radiant\\Q3Radiant", 0, NULL,
+ REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKeyId, &dwDisp);
+ }
+
+ if (lres != ERROR_SUCCESS)
+ return FALSE;
+
+ lres = RegSetValueEx(hKeyId, pszName, 0, REG_BINARY, (unsigned char*)pvBuf, lSize);
+
+ RegCloseKey(hKeyId);
+
+ if (lres != ERROR_SUCCESS)
+ return FALSE;
+
+ return TRUE;
+}
+
+BOOL LoadRegistryInfo(const char *pszName, void *pvBuf, long *plSize)
+{
+ HKEY hKey;
+ long lres, lType, lSize;
+
+ if (plSize == NULL)
+ plSize = &lSize;
+
+ if (g_qeglobals.use_ini)
+ {
+ lres = RegOpenKeyEx(HKEY_CURRENT_USER, g_qeglobals.use_ini_registry, 0, KEY_READ, &hKey);
+ }
+ else
+ {
+ lres = RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Q3Radiant\\Q3Radiant", 0, KEY_READ, &hKey);
+ }
+
+ lres = RegQueryValueEx(hKey, pszName, NULL, (unsigned long*)&lType, (unsigned char*)pvBuf, (unsigned long*)plSize);
+
+ RegCloseKey(hKey);
+
+ if (lres != ERROR_SUCCESS)
+ {
+#ifdef _DEBUG
+ char Message[1024];
+ FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM, 0, lres, 0, &(Message[0]), 1024, NULL );
+ Sys_Printf( "WARNING: RegQueryValueEx failed in LoadRegistryInfo for %s : %s", pszName, Message );
+#endif
+ return FALSE;
+ }
+
+ return TRUE;
+}
+
+BOOL SaveWindowState(HWND hWnd, const char *pszName)
+{
+ RECT rc;
+ GetWindowRect(hWnd, &rc);
+ if (hWnd != g_qeglobals.d_hwndMain) // && g_pParentWnd->CurrentStyle() == QR_QE4)
+ {
+ if (::GetParent(hWnd) != g_qeglobals.d_hwndMain)
+ {
+ ::SetParent(hWnd, g_qeglobals.d_hwndMain);
+ }
+ MapWindowPoints(NULL, g_qeglobals.d_hwndMain, (POINT *)&rc, 2);
+
+ }
+ BOOL b = SaveRegistryInfo(pszName, &rc, sizeof(rc));
+ return b;
+}
+
+
+BOOL LoadWindowState(HWND hWnd, const char *pszName)
+{
+ RECT rc;
+ LONG lSize = sizeof(rc);
+
+ if (LoadRegistryInfo(pszName, &rc, &lSize))
+ {
+ if (rc.left < 0)
+ rc.left = 0;
+ if (rc.top < 0)
+ rc.top = 0;
+ if (rc.right < rc.left + 16)
+ rc.right = rc.left + 16;
+ if (rc.bottom < rc.top + 16)
+ rc.bottom = rc.top + 16;
+
+ MoveWindow(hWnd, rc.left, rc.top, rc.right - rc.left,
+ rc.bottom - rc.top, FALSE);
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+/*
+===============================================================
+
+ STATUS WINDOW
+
+===============================================================
+*/
+
+void Sys_UpdateStatusBar( void )
+{
+ extern int g_numbrushes, g_numentities;
+
+ char numbrushbuffer[100]="";
+
+ sprintf( numbrushbuffer, "Brushes: %d Entities: %d", g_numbrushes, g_numentities );
+ g_pParentWnd->SetStatusText(2, numbrushbuffer);
+ //Sys_Status( numbrushbuffer, 2 );
+}
+
+void Sys_Status(const char *psz, int part )
+{
+ SendMessage(g_qeglobals.d_hwndStatus, SB_SETTEXT, part, (LPARAM)psz);
+}
+
+static HWND CreateMyStatusWindow(HINSTANCE hInst)
+{
+ HWND hWnd;
+ int partsize[3] = { 300, 1100, -1 };
+
+ hWnd = CreateWindowEx( WS_EX_TOPMOST, // no extended styles
+ STATUSCLASSNAME, // status bar
+ "", // no text
+ WS_CHILD | WS_BORDER | WS_VISIBLE, // styles
+ -100, -100, 10, 10, // x, y, cx, cy
+ g_qeglobals.d_hwndMain, // parent window
+ (HMENU)100, // window ID
+ hInst, // instance
+ NULL); // window data
+
+ SendMessage( hWnd, SB_SETPARTS, 3, ( long ) partsize );
+
+ return hWnd;
+}
+
+//==============================================================
+
+#define NUMBUTTONS 15
+HWND CreateToolBar(HINSTANCE hinst)
+{
+ HWND hwndTB;
+ TBADDBITMAP tbab;
+ TBBUTTON tbb[NUMBUTTONS];
+
+ // Ensure that the common control DLL is loaded.
+
+ InitCommonControls();
+
+ // Create a toolbar that the user can customize and that has a
+ // tooltip associated with it.
+
+ hwndTB = CreateWindowEx(0, TOOLBARCLASSNAME, (LPSTR) NULL,
+ WS_CHILD | TBSTYLE_TOOLTIPS | CCS_ADJUSTABLE | WS_BORDER,
+ 0, 0, 0, 0, g_qeglobals.d_hwndMain, (HMENU) IDR_TOOLBAR1, hinst, NULL);
+
+ // Send the TB_BUTTONSTRUCTSIZE message, which is required for
+ // backward compatibility.
+
+ SendMessage(hwndTB, TB_BUTTONSTRUCTSIZE, (WPARAM) sizeof(TBBUTTON), 0);
+
+ // Add the bitmap containing button images to the toolbar.
+
+ tbab.hInst = hinst;
+ tbab.nID = IDR_TOOLBAR1;
+ SendMessage(hwndTB, TB_ADDBITMAP, (WPARAM)NUMBUTTONS, (WPARAM) &tbab);
+
+ // Fill the TBBUTTON array with button information, and add the
+ // buttons to the toolbar.
+
+ tbb[0].iBitmap = 0;
+ tbb[0].idCommand = ID_BRUSH_FLIPX;
+ tbb[0].fsState = TBSTATE_ENABLED;
+ tbb[0].fsStyle = TBSTYLE_BUTTON;
+ tbb[0].dwData = 0;
+ tbb[0].iString = 0;
+
+ tbb[1].iBitmap = 2;
+ tbb[1].idCommand = ID_BRUSH_FLIPY;
+ tbb[1].fsState = TBSTATE_ENABLED;
+ tbb[1].fsStyle = TBSTYLE_BUTTON;
+ tbb[1].dwData = 0;
+ tbb[1].iString = 0;
+
+ tbb[2].iBitmap = 4;
+ tbb[2].idCommand = ID_BRUSH_FLIPZ;
+ tbb[2].fsState = TBSTATE_ENABLED;
+ tbb[2].fsStyle = TBSTYLE_BUTTON;
+ tbb[2].dwData = 0;
+ tbb[2].iString = 0;
+
+ tbb[3].iBitmap = 1;
+ tbb[3].idCommand = ID_BRUSH_ROTATEX;
+ tbb[3].fsState = TBSTATE_ENABLED;
+ tbb[3].fsStyle = TBSTYLE_BUTTON;
+ tbb[3].dwData = 0;
+ tbb[3].iString = 0;
+
+ tbb[4].iBitmap = 3;
+ tbb[4].idCommand = ID_BRUSH_ROTATEY;
+ tbb[4].fsState = TBSTATE_ENABLED;
+ tbb[4].fsStyle = TBSTYLE_BUTTON;
+ tbb[4].dwData = 0;
+ tbb[4].iString = 0;
+
+ tbb[5].iBitmap = 5;
+ tbb[5].idCommand = ID_BRUSH_ROTATEZ;
+ tbb[5].fsState = TBSTATE_ENABLED;
+ tbb[5].fsStyle = TBSTYLE_BUTTON;
+ tbb[5].dwData = 0;
+ tbb[5].iString = 0;
+
+ tbb[6].iBitmap = 6;
+ tbb[6].idCommand = ID_SELECTION_SELECTCOMPLETETALL;
+ tbb[6].fsState = TBSTATE_ENABLED;
+ tbb[6].fsStyle = TBSTYLE_BUTTON;
+ tbb[6].dwData = 0;
+ tbb[6].iString = 0;
+
+ tbb[7].iBitmap = 7;
+ tbb[7].idCommand = ID_SELECTION_SELECTTOUCHING;
+ tbb[7].fsState = TBSTATE_ENABLED;
+ tbb[7].fsStyle = TBSTYLE_BUTTON;
+ tbb[7].dwData = 0;
+ tbb[7].iString = 0;
+
+ tbb[8].iBitmap = 8;
+ tbb[8].idCommand = ID_SELECTION_SELECTPARTIALTALL;
+ tbb[8].fsState = TBSTATE_ENABLED;
+ tbb[8].fsStyle = TBSTYLE_BUTTON;
+ tbb[8].dwData = 0;
+ tbb[8].iString = 0;
+
+
+ tbb[9].iBitmap = 9;
+ tbb[9].idCommand = ID_SELECTION_SELECTINSIDE;
+ tbb[9].fsState = TBSTATE_ENABLED;
+ tbb[9].fsStyle = TBSTYLE_BUTTON;
+ tbb[9].dwData = 0;
+ tbb[9].iString = 0;
+
+ tbb[10].iBitmap = 10;
+ tbb[10].idCommand = ID_SELECTION_CSGSUBTRACT;
+ tbb[10].fsState = TBSTATE_ENABLED;
+ tbb[10].fsStyle = TBSTYLE_BUTTON;
+ tbb[10].dwData = 0;
+ tbb[10].iString = 0;
+
+
+ tbb[11].iBitmap = 11;
+ tbb[11].idCommand = ID_SELECTION_MAKEHOLLOW;
+ tbb[11].fsState = TBSTATE_ENABLED;
+ tbb[11].fsStyle = TBSTYLE_BUTTON;
+ tbb[11].dwData = 0;
+ tbb[11].iString = 0;
+
+ tbb[12].iBitmap = 12;
+ tbb[12].idCommand = ID_TEXTURES_WIREFRAME;
+ tbb[12].fsState = TBSTATE_ENABLED;
+ tbb[12].fsStyle = TBSTYLE_BUTTON;
+ tbb[12].dwData = 0;
+ tbb[12].iString = 0;
+
+ tbb[13].iBitmap = 13;
+ tbb[13].idCommand = ID_TEXTURES_FLATSHADE;
+ tbb[13].fsState = TBSTATE_ENABLED;
+ tbb[13].fsStyle = TBSTYLE_BUTTON;
+ tbb[13].dwData = 0;
+ tbb[13].iString = 0;
+
+ tbb[14].iBitmap = 14;
+ tbb[14].idCommand = ID_VIEW_TRILINEAR;
+ tbb[14].fsState = TBSTATE_ENABLED;
+ tbb[14].fsStyle = TBSTYLE_BUTTON;
+ tbb[14].dwData = 0;
+ tbb[14].iString = 0;
+
+ SendMessage(hwndTB, TB_ADDBUTTONS, (WPARAM)NUMBUTTONS,
+ (LPARAM) (LPTBBUTTON) &tbb);
+
+ ShowWindow(hwndTB, SW_SHOW);
+
+ return hwndTB;
+}
+
diff --git a/q3radiant/Winding.cpp b/q3radiant/Winding.cpp
new file mode 100755
index 0000000..76e6df1
--- /dev/null
+++ b/q3radiant/Winding.cpp
@@ -0,0 +1,817 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+
+#include "stdafx.h"
+#include <assert.h>
+#include "qe3.h"
+#include "winding.h"
+
+#define BOGUS_RANGE 18000
+
+/*
+=============
+Plane_Equal
+=============
+*/
+#define NORMAL_EPSILON 0.0001
+#define DIST_EPSILON 0.02
+
+int Plane_Equal(plane_t *a, plane_t *b, int flip)
+{
+ vec3_t normal;
+ float dist;
+
+ if (flip) {
+ normal[0] = - b->normal[0];
+ normal[1] = - b->normal[1];
+ normal[2] = - b->normal[2];
+ dist = - b->dist;
+ }
+ else {
+ normal[0] = b->normal[0];
+ normal[1] = b->normal[1];
+ normal[2] = b->normal[2];
+ dist = b->dist;
+ }
+ if (
+ fabs(a->normal[0] - normal[0]) < NORMAL_EPSILON
+ && fabs(a->normal[1] - normal[1]) < NORMAL_EPSILON
+ && fabs(a->normal[2] - normal[2]) < NORMAL_EPSILON
+ && fabs(a->dist - dist) < DIST_EPSILON )
+ return true;
+ return false;
+}
+
+/*
+============
+Plane_FromPoints
+============
+*/
+int Plane_FromPoints(vec3_t p1, vec3_t p2, vec3_t p3, plane_t *plane)
+{
+ vec3_t v1, v2;
+
+ VectorSubtract(p2, p1, v1);
+ VectorSubtract(p3, p1, v2);
+ //CrossProduct(v2, v1, plane->normal);
+ CrossProduct(v1, v2, plane->normal);
+ if (VectorNormalize(plane->normal) < 0.1) return false;
+ plane->dist = DotProduct(p1, plane->normal);
+ return true;
+}
+
+/*
+=================
+Point_Equal
+=================
+*/
+int Point_Equal(vec3_t p1, vec3_t p2, float epsilon)
+{
+ int i;
+
+ for (i = 0; i < 3; i++)
+ {
+ if (fabs(p1[i] - p2[i]) > epsilon) return false;
+ }
+ return true;
+}
+
+
+/*
+=================
+Winding_BaseForPlane
+=================
+*/
+winding_t *Winding_BaseForPlane (plane_t *p)
+{
+ int i, x;
+ vec_t max, v;
+ vec3_t org, vright, vup;
+ winding_t *w;
+
+ // find the major axis
+
+ max = -BOGUS_RANGE;
+ x = -1;
+ for (i=0 ; i<3; i++)
+ {
+ v = fabs(p->normal[i]);
+ if (v > max)
+ {
+ x = i;
+ max = v;
+ }
+ }
+ if (x==-1)
+ Error ("Winding_BaseForPlane: no axis found");
+
+ VectorCopy (vec3_origin, vup);
+ switch (x)
+ {
+ case 0:
+ case 1:
+ vup[2] = 1;
+ break;
+ case 2:
+ vup[0] = 1;
+ break;
+ }
+
+
+ v = DotProduct (vup, p->normal);
+ VectorMA (vup, -v, p->normal, vup);
+ VectorNormalize (vup);
+
+ VectorScale (p->normal, p->dist, org);
+
+ CrossProduct (vup, p->normal, vright);
+
+ VectorScale (vup, BOGUS_RANGE, vup);
+ VectorScale (vright, BOGUS_RANGE, vright);
+
+ // project a really big axis aligned box onto the plane
+ w = Winding_Alloc (4);
+
+ VectorSubtract (org, vright, w->points[0]);
+ VectorAdd (w->points[0], vup, w->points[0]);
+
+ VectorAdd (org, vright, w->points[1]);
+ VectorAdd (w->points[1], vup, w->points[1]);
+
+ VectorAdd (org, vright, w->points[2]);
+ VectorSubtract (w->points[2], vup, w->points[2]);
+
+ VectorSubtract (org, vright, w->points[3]);
+ VectorSubtract (w->points[3], vup, w->points[3]);
+
+ w->numpoints = 4;
+
+ return w;
+}
+
+/*
+==================
+Winding_Alloc
+==================
+*/
+winding_t *Winding_Alloc (int points)
+{
+ winding_t *w;
+ int size;
+
+ if (points > MAX_POINTS_ON_WINDING)
+ Error ("Winding_Alloc: %i points", points);
+
+ size = (int)((winding_t *)0)->points[points];
+ w = (winding_t*) malloc (size);
+ memset (w, 0, size);
+ w->maxpoints = points;
+
+ return w;
+}
+
+
+void Winding_Free (winding_t *w)
+{
+ free(w);
+}
+
+
+/*
+==================
+Winding_Clone
+==================
+*/
+winding_t *Winding_Clone(winding_t *w)
+{
+ int size;
+ winding_t *c;
+
+ size = (int)((winding_t *)0)->points[w->numpoints];
+ c = (winding_t*)qmalloc (size);
+ memcpy (c, w, size);
+ return c;
+}
+
+/*
+==================
+ReverseWinding
+==================
+*/
+winding_t *Winding_Reverse(winding_t *w)
+{
+ int i;
+ winding_t *c;
+
+ c = Winding_Alloc(w->numpoints);
+ for (i = 0; i < w->numpoints; i++)
+ {
+ VectorCopy (w->points[w->numpoints-1-i], c->points[i]);
+ }
+ c->numpoints = w->numpoints;
+ return c;
+}
+
+
+/*
+==============
+Winding_RemovePoint
+==============
+*/
+void Winding_RemovePoint(winding_t *w, int point)
+{
+ if (point < 0 || point >= w->numpoints)
+ Error("Winding_RemovePoint: point out of range");
+
+ if (point < w->numpoints-1)
+ {
+ memmove(&w->points[point], &w->points[point+1], (int)((winding_t *)0)->points[w->numpoints - point - 1]);
+ }
+ w->numpoints--;
+}
+
+/*
+=============
+Winding_InsertPoint
+=============
+*/
+winding_t *Winding_InsertPoint(winding_t *w, vec3_t point, int spot)
+{
+ int i, j;
+ winding_t *neww;
+
+ if (spot > w->numpoints)
+ {
+ Error("Winding_InsertPoint: spot > w->numpoints");
+ } //end if
+ if (spot < 0)
+ {
+ Error("Winding_InsertPoint: spot < 0");
+ } //end if
+ neww = Winding_Alloc(w->numpoints + 1);
+ neww->numpoints = w->numpoints + 1;
+ for (i = 0, j = 0; i < neww->numpoints; i++)
+ {
+ if (i == spot)
+ {
+ VectorCopy(point, neww->points[i]);
+ }
+ else
+ {
+ VectorCopy(w->points[j], neww->points[i]);
+ j++;
+ }
+ }
+ return neww;
+}
+
+/*
+==============
+Winding_IsTiny
+==============
+*/
+#define EDGE_LENGTH 0.2
+
+int Winding_IsTiny (winding_t *w)
+{
+ int i, j;
+ vec_t len;
+ vec3_t delta;
+ int edges;
+
+ edges = 0;
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ j = i == w->numpoints - 1 ? 0 : i+1;
+ VectorSubtract (w->points[j], w->points[i], delta);
+ len = VectorLength (delta);
+ if (len > EDGE_LENGTH)
+ {
+ if (++edges == 3)
+ return false;
+ }
+ }
+ return true;
+}
+
+/*
+==============
+Winding_IsHuge
+==============
+*/
+int Winding_IsHuge(winding_t *w)
+{
+ int i, j;
+
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ for (j=0 ; j<3 ; j++)
+ if (w->points[i][j] < -BOGUS_RANGE+1 || w->points[i][j] > BOGUS_RANGE-1)
+ return true;
+ }
+ return false;
+}
+
+/*
+=============
+Winding_PlanesConcave
+=============
+*/
+#define WCONVEX_EPSILON 0.2
+
+int Winding_PlanesConcave(winding_t *w1, winding_t *w2,
+ vec3_t normal1, vec3_t normal2,
+ float dist1, float dist2)
+{
+ int i;
+
+ if (!w1 || !w2) return false;
+
+ // check if one of the points of winding 1 is at the back of the plane of winding 2
+ for (i = 0; i < w1->numpoints; i++)
+ {
+ if (DotProduct(normal2, w1->points[i]) - dist2 > WCONVEX_EPSILON) return true;
+ }
+ // check if one of the points of winding 2 is at the back of the plane of winding 1
+ for (i = 0; i < w2->numpoints; i++)
+ {
+ if (DotProduct(normal1, w2->points[i]) - dist1 > WCONVEX_EPSILON) return true;
+ }
+
+ return false;
+}
+
+/*
+==================
+Winding_Clip
+
+Clips the winding to the plane, returning the new winding on the positive side
+Frees the input winding.
+If keepon is true, an exactly on-plane winding will be saved, otherwise
+it will be clipped away.
+==================
+*/
+winding_t *Winding_Clip (winding_t *in, plane_t *split, qboolean keepon)
+{
+ vec_t dists[MAX_POINTS_ON_WINDING];
+ int sides[MAX_POINTS_ON_WINDING];
+ int counts[3];
+ vec_t dot;
+ int i, j;
+ vec_t *p1, *p2;
+ vec3_t mid;
+ winding_t *neww;
+ int maxpts;
+
+ counts[0] = counts[1] = counts[2] = 0;
+
+ // determine sides for each point
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ dot = DotProduct (in->points[i], split->normal);
+ dot -= split->dist;
+ dists[i] = dot;
+ if (dot > ON_EPSILON)
+ sides[i] = SIDE_FRONT;
+ else if (dot < -ON_EPSILON)
+ sides[i] = SIDE_BACK;
+ else
+ {
+ sides[i] = SIDE_ON;
+ }
+ counts[sides[i]]++;
+ }
+ sides[i] = sides[0];
+ dists[i] = dists[0];
+
+ if (keepon && !counts[0] && !counts[1])
+ return in;
+
+ if (!counts[0])
+ {
+ Winding_Free (in);
+ return NULL;
+ }
+ if (!counts[1])
+ return in;
+
+ maxpts = in->numpoints+4; // can't use counts[0]+2 because
+ // of fp grouping errors
+ neww = Winding_Alloc (maxpts);
+
+ for (i=0 ; i<in->numpoints ; i++)
+ {
+ p1 = in->points[i];
+
+ if (sides[i] == SIDE_ON)
+ {
+ VectorCopy (p1, neww->points[neww->numpoints]);
+ neww->numpoints++;
+ continue;
+ }
+
+ if (sides[i] == SIDE_FRONT)
+ {
+ VectorCopy (p1, neww->points[neww->numpoints]);
+ neww->numpoints++;
+ }
+
+ if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i])
+ continue;
+
+ // generate a split point
+ p2 = in->points[(i+1)%in->numpoints];
+
+ dot = dists[i] / (dists[i]-dists[i+1]);
+ for (j=0 ; j<3 ; j++)
+ { // avoid round off error when possible
+ if (split->normal[j] == 1)
+ mid[j] = split->dist;
+ else if (split->normal[j] == -1)
+ mid[j] = -split->dist;
+ else
+ mid[j] = p1[j] + dot*(p2[j]-p1[j]);
+ }
+
+ VectorCopy (mid, neww->points[neww->numpoints]);
+ neww->numpoints++;
+ }
+
+ if (neww->numpoints > maxpts)
+ Error ("Winding_Clip: points exceeded estimate");
+
+ // free the original winding
+ Winding_Free (in);
+
+ return neww;
+}
+
+/*
+=============
+Winding_SplitEpsilon
+
+ split the input winding with the plane
+ the input winding stays untouched
+=============
+*/
+void Winding_SplitEpsilon (winding_t *in, vec3_t normal, double dist,
+ vec_t epsilon, winding_t **front, winding_t **back)
+{
+ vec_t dists[MAX_POINTS_ON_WINDING+4];
+ int sides[MAX_POINTS_ON_WINDING+4];
+ int counts[3];
+ vec_t dot;
+ int i, j;
+ vec_t *p1, *p2;
+ vec3_t mid;
+ winding_t *f, *b;
+ int maxpts;
+
+ counts[0] = counts[1] = counts[2] = 0;
+
+ // determine sides for each point
+ for (i = 0; i < in->numpoints; i++)
+ {
+ dot = DotProduct (in->points[i], normal);
+ dot -= dist;
+ dists[i] = dot;
+ if (dot > epsilon)
+ sides[i] = SIDE_FRONT;
+ else if (dot < -epsilon)
+ sides[i] = SIDE_BACK;
+ else
+ {
+ sides[i] = SIDE_ON;
+ }
+ counts[sides[i]]++;
+ }
+ sides[i] = sides[0];
+ dists[i] = dists[0];
+
+ *front = *back = NULL;
+
+ if (!counts[0])
+ {
+ *back = Winding_Clone(in);
+ return;
+ }
+ if (!counts[1])
+ {
+ *front = Winding_Clone(in);
+ return;
+ }
+
+ maxpts = in->numpoints+4; // cant use counts[0]+2 because
+ // of fp grouping errors
+
+ *front = f = Winding_Alloc (maxpts);
+ *back = b = Winding_Alloc (maxpts);
+
+ for (i = 0; i < in->numpoints; i++)
+ {
+ p1 = in->points[i];
+
+ if (sides[i] == SIDE_ON)
+ {
+ VectorCopy (p1, f->points[f->numpoints]);
+ f->numpoints++;
+ VectorCopy (p1, b->points[b->numpoints]);
+ b->numpoints++;
+ continue;
+ }
+
+ if (sides[i] == SIDE_FRONT)
+ {
+ VectorCopy (p1, f->points[f->numpoints]);
+ f->numpoints++;
+ }
+ if (sides[i] == SIDE_BACK)
+ {
+ VectorCopy (p1, b->points[b->numpoints]);
+ b->numpoints++;
+ }
+
+ if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i])
+ continue;
+
+ // generate a split point
+ p2 = in->points[(i+1)%in->numpoints];
+
+ dot = dists[i] / (dists[i]-dists[i+1]);
+ for (j = 0; j < 3; j++)
+ {
+ // avoid round off error when possible
+ if (normal[j] == 1)
+ mid[j] = dist;
+ else if (normal[j] == -1)
+ mid[j] = -dist;
+ else
+ mid[j] = p1[j] + dot*(p2[j]-p1[j]);
+ }
+
+ VectorCopy (mid, f->points[f->numpoints]);
+ f->numpoints++;
+ VectorCopy (mid, b->points[b->numpoints]);
+ b->numpoints++;
+ }
+
+ if (f->numpoints > maxpts || b->numpoints > maxpts)
+ Error ("Winding_Clip: points exceeded estimate");
+ if (f->numpoints > MAX_POINTS_ON_WINDING || b->numpoints > MAX_POINTS_ON_WINDING)
+ Error ("Winding_Clip: MAX_POINTS_ON_WINDING");
+}
+
+/*
+=============
+Winding_TryMerge
+
+If two windings share a common edge and the edges that meet at the
+common points are both inside the other polygons, merge them
+
+Returns NULL if the windings couldn't be merged, or the new winding.
+The originals will NOT be freed.
+
+if keep is true no points are ever removed
+=============
+*/
+#define CONTINUOUS_EPSILON 0.005
+
+winding_t *Winding_TryMerge(winding_t *f1, winding_t *f2, vec3_t planenormal, int keep)
+{
+ vec_t *p1, *p2, *p3, *p4, *back;
+ winding_t *newf;
+ int i, j, k, l;
+ vec3_t normal, delta;
+ vec_t dot;
+ qboolean keep1, keep2;
+
+
+ //
+ // find a common edge
+ //
+ p1 = p2 = NULL; // stop compiler warning
+ j = 0; //
+
+ for (i = 0; i < f1->numpoints; i++)
+ {
+ p1 = f1->points[i];
+ p2 = f1->points[(i+1) % f1->numpoints];
+ for (j = 0; j < f2->numpoints; j++)
+ {
+ p3 = f2->points[j];
+ p4 = f2->points[(j+1) % f2->numpoints];
+ for (k = 0; k < 3; k++)
+ {
+ if (fabs(p1[k] - p4[k]) > 0.1)//EQUAL_EPSILON) //ME
+ break;
+ if (fabs(p2[k] - p3[k]) > 0.1)//EQUAL_EPSILON) //ME
+ break;
+ } //end for
+ if (k==3)
+ break;
+ } //end for
+ if (j < f2->numpoints)
+ break;
+ } //end for
+
+ if (i == f1->numpoints)
+ return NULL; // no matching edges
+
+ //
+ // check slope of connected lines
+ // if the slopes are colinear, the point can be removed
+ //
+ back = f1->points[(i+f1->numpoints-1)%f1->numpoints];
+ VectorSubtract (p1, back, delta);
+ CrossProduct (planenormal, delta, normal);
+ VectorNormalize (normal);
+
+ back = f2->points[(j+2)%f2->numpoints];
+ VectorSubtract (back, p1, delta);
+ dot = DotProduct (delta, normal);
+ if (dot > CONTINUOUS_EPSILON)
+ return NULL; // not a convex polygon
+ keep1 = (qboolean)(dot < -CONTINUOUS_EPSILON);
+
+ back = f1->points[(i+2)%f1->numpoints];
+ VectorSubtract (back, p2, delta);
+ CrossProduct (planenormal, delta, normal);
+ VectorNormalize (normal);
+
+ back = f2->points[(j+f2->numpoints-1)%f2->numpoints];
+ VectorSubtract (back, p2, delta);
+ dot = DotProduct (delta, normal);
+ if (dot > CONTINUOUS_EPSILON)
+ return NULL; // not a convex polygon
+ keep2 = (qboolean)(dot < -CONTINUOUS_EPSILON);
+
+ //
+ // build the new polygon
+ //
+ newf = Winding_Alloc (f1->numpoints + f2->numpoints);
+
+ // copy first polygon
+ for (k=(i+1)%f1->numpoints ; k != i ; k=(k+1)%f1->numpoints)
+ {
+ if (!keep && k==(i+1)%f1->numpoints && !keep2)
+ continue;
+
+ VectorCopy (f1->points[k], newf->points[newf->numpoints]);
+ newf->numpoints++;
+ }
+
+ // copy second polygon
+ for (l= (j+1)%f2->numpoints ; l != j ; l=(l+1)%f2->numpoints)
+ {
+ if (!keep && l==(j+1)%f2->numpoints && !keep1)
+ continue;
+ VectorCopy (f2->points[l], newf->points[newf->numpoints]);
+ newf->numpoints++;
+ }
+
+ return newf;
+}
+
+/*
+============
+Winding_Plane
+============
+*/
+void Winding_Plane (winding_t *w, vec3_t normal, double *dist)
+{
+ vec3_t v1, v2;
+ int i;
+
+ //find two vectors each longer than 0.5 units
+ for (i = 0; i < w->numpoints; i++)
+ {
+ VectorSubtract(w->points[(i+1) % w->numpoints], w->points[i], v1);
+ VectorSubtract(w->points[(i+2) % w->numpoints], w->points[i], v2);
+ if (VectorLength(v1) > 0.5 && VectorLength(v2) > 0.5) break;
+ }
+ CrossProduct(v2, v1, normal);
+ VectorNormalize(normal);
+ *dist = DotProduct(w->points[0], normal);
+}
+
+/*
+=============
+Winding_Area
+=============
+*/
+float Winding_Area (winding_t *w)
+{
+ int i;
+ vec3_t d1, d2, cross;
+ float total;
+
+ total = 0;
+ for (i=2 ; i<w->numpoints ; i++)
+ {
+ VectorSubtract (w->points[i-1], w->points[0], d1);
+ VectorSubtract (w->points[i], w->points[0], d2);
+ CrossProduct (d1, d2, cross);
+ total += 0.5 * VectorLength ( cross );
+ }
+ return total;
+}
+
+/*
+=============
+Winding_Bounds
+=============
+*/
+void Winding_Bounds (winding_t *w, vec3_t mins, vec3_t maxs)
+{
+ vec_t v;
+ int i,j;
+
+ mins[0] = mins[1] = mins[2] = 99999;
+ maxs[0] = maxs[1] = maxs[2] = -99999;
+
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ for (j=0 ; j<3 ; j++)
+ {
+ v = w->points[i][j];
+ if (v < mins[j])
+ mins[j] = v;
+ if (v > maxs[j])
+ maxs[j] = v;
+ }
+ }
+}
+
+
+/*
+=================
+Winding_PointInside
+=================
+*/
+int Winding_PointInside(winding_t *w, plane_t *plane, vec3_t point, float epsilon)
+{
+ int i;
+ vec3_t dir, normal, pointvec;
+
+ for (i = 0; i < w->numpoints; i++)
+ {
+ VectorSubtract(w->points[(i+1) % w->numpoints], w->points[i], dir);
+ VectorSubtract(point, w->points[i], pointvec);
+ //
+ CrossProduct(dir, plane->normal, normal);
+ //
+ if (DotProduct(pointvec, normal) < -epsilon) return false;
+ }
+ return true;
+}
+
+/*
+=================
+Winding_VectorIntersect
+=================
+*/
+int Winding_VectorIntersect(winding_t *w, plane_t *plane, vec3_t p1, vec3_t p2, float epsilon)
+{
+ float front, back, frac;
+ vec3_t mid;
+
+ front = DotProduct(p1, plane->normal) - plane->dist;
+ back = DotProduct(p2, plane->normal) - plane->dist;
+ //if both points at the same side of the plane
+ if (front < -epsilon && back < -epsilon) return false;
+ if (front > epsilon && back > epsilon) return false;
+ //get point of intersection with winding plane
+ if (fabs(front-back) < 0.001)
+ {
+ VectorCopy(p2, mid);
+ }
+ else
+ {
+ frac = front/(front-back);
+ mid[0] = p1[0] + (p2[0] - p1[0]) * frac;
+ mid[1] = p1[1] + (p2[1] - p1[1]) * frac;
+ mid[2] = p1[2] + (p2[2] - p1[2]) * frac;
+ }
+ return Winding_PointInside(w, plane, mid, epsilon);
+}
+
diff --git a/q3radiant/Winding.h b/q3radiant/Winding.h
new file mode 100755
index 0000000..66858aa
--- /dev/null
+++ b/q3radiant/Winding.h
@@ -0,0 +1,70 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+
+
+//returns true if the planes are equal
+int Plane_Equal(plane_t *a, plane_t *b, int flip);
+//returns false if the points are colinear
+int Plane_FromPoints(vec3_t p1, vec3_t p2, vec3_t p3, plane_t *plane);
+//returns true if the points are equal
+int Point_Equal(vec3_t p1, vec3_t p2, float epsilon);
+
+//allocate a winding
+winding_t* Winding_Alloc(int points);
+//free the winding
+void Winding_Free(winding_t *w);
+//create a base winding for the plane
+winding_t* Winding_BaseForPlane (plane_t *p);
+//make a winding clone
+winding_t* Winding_Clone(winding_t *w );
+//creates the reversed winding
+winding_t* Winding_Reverse(winding_t *w);
+//remove a point from the winding
+void Winding_RemovePoint(winding_t *w, int point);
+//inserts a point to a winding, creating a new winding
+winding_t* Winding_InsertPoint(winding_t *w, vec3_t point, int spot);
+//returns true if the planes are concave
+int Winding_PlanesConcave(winding_t *w1, winding_t *w2,
+ vec3_t normal1, vec3_t normal2,
+ float dist1, float dist2);
+//returns true if the winding is tiny
+int Winding_IsTiny(winding_t *w);
+//returns true if the winding is huge
+int Winding_IsHuge(winding_t *w);
+//clip the winding with the plane
+winding_t* Winding_Clip(winding_t *in, plane_t *split, qboolean keepon);
+//split the winding with the plane
+void Winding_SplitEpsilon(winding_t *in, vec3_t normal, double dist,
+ vec_t epsilon, winding_t **front, winding_t **back);
+//try to merge the windings, returns the new merged winding or NULL
+winding_t *Winding_TryMerge(winding_t *f1, winding_t *f2, vec3_t planenormal, int keep);
+//create a plane for the winding
+void Winding_Plane(winding_t *w, vec3_t normal, double *dist);
+//returns the winding area
+float Winding_Area(winding_t *w);
+//returns the bounds of the winding
+void Winding_Bounds(winding_t *w, vec3_t mins, vec3_t maxs);
+//returns true if the point is inside the winding
+int Winding_PointInside(winding_t *w, plane_t *plane, vec3_t point, float epsilon);
+//returns true if the vector intersects with the winding
+int Winding_VectorIntersect(winding_t *w, plane_t *plane, vec3_t p1, vec3_t p2, float epsilon);
diff --git a/q3radiant/XY.H b/q3radiant/XY.H
new file mode 100755
index 0000000..243d1b4
--- /dev/null
+++ b/q3radiant/XY.H
@@ -0,0 +1,39 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+// window system independent camera view code
+
+typedef struct
+{
+ int width, height;
+
+ qboolean timing;
+
+ vec3_t origin; // at center of window
+ float scale;
+
+ float topclip, bottomclip;
+
+ qboolean d_dirty;
+} xy_t;
+
+BOOL FilterBrush(brush_t *pb);
diff --git a/q3radiant/XYWnd.cpp b/q3radiant/XYWnd.cpp
new file mode 100755
index 0000000..653c976
--- /dev/null
+++ b/q3radiant/XYWnd.cpp
@@ -0,0 +1,3629 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// XYWnd.cpp : implementation file
+//
+// QERadiant
+//
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "XYWnd.h"
+#include "qe3.h"
+#include "PrefsDlg.h"
+#include "DialogInfo.h"
+#include "splines/splines.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+#define PAGEFLIPS 2
+
+
+const char* g_pDimStrings[] = {"x:%.f", "y:%.f", "z:%.f"};
+const char* g_pOrgStrings[] = {"(x:%.f y:%.f)", "(x:%.f z:%.f)", "(y:%.f z:%.f)"};
+CString g_strDim;
+CString g_strStatus;
+
+bool g_bCrossHairs = false;
+bool g_bScaleMode;
+int g_nScaleHow;
+bool g_bRotateMode;
+bool g_bClipMode;
+bool g_bRogueClipMode;
+bool g_bSwitch;
+CClipPoint g_Clip1;
+CClipPoint g_Clip2;
+CClipPoint g_Clip3;
+CClipPoint* g_pMovingClip;
+brush_t g_brFrontSplits;
+brush_t g_brBackSplits;
+
+brush_t g_brClipboard;
+brush_t g_brUndo;
+entity_t g_enClipboard;
+
+vec3_t g_vRotateOrigin;
+vec3_t g_vRotation;
+
+bool g_bPathMode;
+CClipPoint g_PathPoints[256];
+CClipPoint* g_pMovingPath;
+int g_nPathCount;
+int g_nPathLimit;
+
+bool g_bSmartGo;
+
+bool g_bPointMode;
+CClipPoint g_PointPoints[512];
+CClipPoint* g_pMovingPoint;
+int g_nPointCount;
+int g_nPointLimit;
+
+
+const int XY_LEFT = 0x01;
+const int XY_RIGHT = 0x02;
+const int XY_UP = 0x04;
+const int XY_DOWN = 0x08;
+
+PFNPathCallback* g_pPathFunc = NULL;
+
+void AcquirePath(int nCount, PFNPathCallback* pFunc)
+{
+ g_nPathCount = 0;
+ g_nPathLimit = nCount;
+ g_pPathFunc = pFunc;
+ g_bPathMode = true;
+}
+
+
+CPtrArray g_ptrMenus;
+
+CMemFile g_Clipboard(4096);
+CMemFile g_PatchClipboard(4096);
+
+extern int pressx;
+extern int pressy;
+
+
+/////////////////////////////////////////////////////////////////////////////
+// CXYWnd
+
+IMPLEMENT_DYNCREATE(CXYWnd, CWnd);
+
+CXYWnd::CXYWnd()
+{
+ g_brClipboard.next = &g_brClipboard;
+ g_brUndo.next = &g_brUndo;
+ g_nScaleHow = 0;
+ g_bRotateMode = false;
+ g_bClipMode = false;
+ g_bRogueClipMode = false;
+ g_bSwitch = true;
+ g_pMovingClip = NULL;
+ g_pMovingPath = NULL;
+ g_brFrontSplits.next = &g_brFrontSplits;
+ g_brBackSplits.next = &g_brBackSplits;
+ m_bActive = false;
+ //m_bTiming = true;
+ m_bTiming = false;
+ m_bRButtonDown = false;
+ m_nUpdateBits = W_XY;
+ g_bPathMode = false;
+ g_nPathCount = 0;
+ g_nPathLimit = 0;
+ m_nTimerID = -1;
+ XY_Init();
+}
+
+CXYWnd::~CXYWnd()
+{
+ int nSize = g_ptrMenus.GetSize();
+ while (nSize > 0)
+ {
+ CMenu* pMenu = reinterpret_cast<CMenu*>(g_ptrMenus.GetAt(nSize-1));
+ ASSERT(pMenu);
+ pMenu->DestroyMenu();
+ delete pMenu;
+ nSize--;
+ }
+ g_ptrMenus.RemoveAll();
+ m_mnuDrop.DestroyMenu();
+}
+
+
+BEGIN_MESSAGE_MAP(CXYWnd, CWnd)
+ //{{AFX_MSG_MAP(CXYWnd)
+ ON_WM_CREATE()
+ ON_WM_LBUTTONDOWN()
+ ON_WM_MBUTTONDOWN()
+ ON_WM_RBUTTONDOWN()
+ ON_WM_LBUTTONUP()
+ ON_WM_MBUTTONUP()
+ ON_WM_RBUTTONUP()
+ ON_WM_MOUSEMOVE()
+ ON_WM_PAINT()
+ ON_WM_KEYDOWN()
+ ON_WM_SIZE()
+ ON_WM_DESTROY()
+ ON_COMMAND(ID_SELECT_MOUSEROTATE, OnSelectMouserotate)
+ ON_WM_TIMER()
+ ON_WM_KEYUP()
+ ON_WM_NCCALCSIZE()
+ ON_WM_KILLFOCUS()
+ ON_WM_SETFOCUS()
+ ON_WM_CLOSE()
+ ON_COMMAND(ID_SELECTION_MAKE_DETAIL, CMainFrame::OnSelectionMakeDetail)
+ ON_COMMAND(ID_SELECTION_MAKE_STRUCTURAL, CMainFrame::OnSelectionMakeStructural)
+ ON_COMMAND(ID_SELECTION_SELECTCOMPLETETALL, CMainFrame::OnSelectionSelectcompletetall)
+ ON_COMMAND(ID_SELECTION_SELECTINSIDE, CMainFrame::OnSelectionSelectinside)
+ ON_COMMAND(ID_SELECTION_SELECTPARTIALTALL, CMainFrame::OnSelectionSelectpartialtall)
+ ON_COMMAND(ID_SELECTION_SELECTTOUCHING, CMainFrame::OnSelectionSelecttouching)
+ ON_COMMAND(ID_SELECTION_UNGROUPENTITY, CMainFrame::OnSelectionUngroupentity)
+ //}}AFX_MSG_MAP
+ ON_COMMAND_RANGE(ID_ENTITY_START, ID_ENTITY_END, OnEntityCreate)
+END_MESSAGE_MAP()
+
+
+/////////////////////////////////////////////////////////////////////////////
+// CXYWnd message handlers
+LONG WINAPI XYWndProc(HWND, UINT, WPARAM, LPARAM);
+BOOL CXYWnd::PreCreateWindow(CREATESTRUCT& cs)
+{
+ WNDCLASS wc;
+ HINSTANCE hInstance = AfxGetInstanceHandle();
+ if (::GetClassInfo(hInstance, XY_WINDOW_CLASS, &wc) == FALSE)
+ {
+ // Register a new class
+ memset (&wc, 0, sizeof(wc));
+ wc.style = CS_NOCLOSE | CS_OWNDC;
+ wc.lpszClassName = XY_WINDOW_CLASS;
+ wc.hCursor = NULL; //LoadCursor (NULL,IDC_ARROW);
+ wc.lpfnWndProc = ::DefWindowProc;
+ if (AfxRegisterClass(&wc) == FALSE)
+ Error ("CCamWnd RegisterClass: failed");
+ }
+
+ cs.lpszClass = XY_WINDOW_CLASS;
+ cs.lpszName = "VIEW";
+ if (cs.style != QE3_CHILDSTYLE)
+ cs.style = QE3_SPLITTER_STYLE;
+
+ return CWnd::PreCreateWindow(cs);
+}
+
+HDC s_hdcXY;
+HGLRC s_hglrcXY;
+
+static unsigned s_stipple[32] =
+{
+ 0xaaaaaaaa, 0x55555555,0xaaaaaaaa, 0x55555555,
+ 0xaaaaaaaa, 0x55555555,0xaaaaaaaa, 0x55555555,
+ 0xaaaaaaaa, 0x55555555,0xaaaaaaaa, 0x55555555,
+ 0xaaaaaaaa, 0x55555555,0xaaaaaaaa, 0x55555555,
+ 0xaaaaaaaa, 0x55555555,0xaaaaaaaa, 0x55555555,
+ 0xaaaaaaaa, 0x55555555,0xaaaaaaaa, 0x55555555,
+ 0xaaaaaaaa, 0x55555555,0xaaaaaaaa, 0x55555555,
+ 0xaaaaaaaa, 0x55555555,0xaaaaaaaa, 0x55555555,
+};
+
+/*
+============
+WXY_WndProc
+============
+*/
+LONG WINAPI XYWndProc (
+ HWND hWnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam)
+{
+ switch (uMsg)
+ {
+ case WM_DESTROY:
+ QEW_StopGL( hWnd, s_hglrcXY, s_hdcXY );
+ return 0;
+
+ case WM_NCCALCSIZE:// don't let windows copy pixels
+ DefWindowProc (hWnd, uMsg, wParam, lParam);
+ return WVR_REDRAW;
+
+ case WM_KILLFOCUS:
+ case WM_SETFOCUS:
+ SendMessage( hWnd, WM_NCACTIVATE, uMsg == WM_SETFOCUS, 0 );
+ return 0;
+
+ case WM_CLOSE:
+ DestroyWindow (hWnd);
+ return 0;
+ }
+
+ return DefWindowProc (hWnd, uMsg, wParam, lParam);
+}
+
+
+static void WXY_InitPixelFormat( PIXELFORMATDESCRIPTOR *pPFD )
+{
+ memset( pPFD, 0, sizeof( *pPFD ) );
+
+ pPFD->nSize = sizeof( PIXELFORMATDESCRIPTOR );
+ pPFD->nVersion = 1;
+ pPFD->dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
+ pPFD->iPixelType = PFD_TYPE_RGBA;
+ pPFD->cColorBits = 24;
+ pPFD->cDepthBits = 32;
+ pPFD->iLayerType = PFD_MAIN_PLANE;
+
+}
+
+void WXY_Print( void )
+{
+ DOCINFO di;
+
+ PRINTDLG pd;
+
+ /*
+ ** initialize the PRINTDLG struct and execute it
+ */
+ memset( &pd, 0, sizeof( pd ) );
+ pd.lStructSize = sizeof( pd );
+ pd.hwndOwner = g_qeglobals.d_hwndXY;
+ pd.Flags = PD_RETURNDC;
+ pd.hInstance = 0;
+ if ( !PrintDlg( &pd ) || !pd.hDC )
+ {
+ MessageBox( g_qeglobals.d_hwndMain, "Could not PrintDlg()", "QE4 Print Error", MB_OK | MB_ICONERROR );
+ return;
+ }
+
+ /*
+ ** StartDoc
+ */
+ memset( &di, 0, sizeof( di ) );
+ di.cbSize = sizeof( di );
+ di.lpszDocName = "QE4";
+ if ( StartDoc( pd.hDC, &di ) <= 0 )
+ {
+ MessageBox( g_qeglobals.d_hwndMain, "Could not StartDoc()", "QE4 Print Error", MB_OK | MB_ICONERROR );
+ return;
+ }
+
+ /*
+ ** StartPage
+ */
+ if ( StartPage( pd.hDC ) <= 0 )
+ {
+ MessageBox( g_qeglobals.d_hwndMain, "Could not StartPage()", "QE4 Print Error", MB_OK | MB_ICONERROR );
+ return;
+ }
+
+ /*
+ ** read pixels from the XY window
+ */
+ {
+ int bmwidth = 320, bmheight = 320;
+ int pwidth, pheight;
+
+ RECT r;
+
+ GetWindowRect( g_qeglobals.d_hwndXY, &r );
+
+ bmwidth = r.right - r.left;
+ bmheight = r.bottom - r.top;
+
+ pwidth = GetDeviceCaps( pd.hDC, PHYSICALWIDTH ) - GetDeviceCaps( pd.hDC, PHYSICALOFFSETX );
+ pheight = GetDeviceCaps( pd.hDC, PHYSICALHEIGHT ) - GetDeviceCaps( pd.hDC, PHYSICALOFFSETY );
+
+ StretchBlt( pd.hDC,
+ 0, 0,
+ pwidth, pheight,
+ s_hdcXY,
+ 0, 0,
+ bmwidth, bmheight,
+ SRCCOPY );
+ }
+
+ /*
+ ** EndPage and EndDoc
+ */
+ if ( EndPage( pd.hDC ) <= 0 )
+ {
+ MessageBox( g_qeglobals.d_hwndMain, "QE4 Print Error", "Could not EndPage()", MB_OK | MB_ICONERROR );
+ return;
+ }
+
+ if ( EndDoc( pd.hDC ) <= 0 )
+ {
+ MessageBox( g_qeglobals.d_hwndMain, "QE4 Print Error", "Could not EndDoc()", MB_OK | MB_ICONERROR );
+ return;
+ }
+}
+
+int CXYWnd::OnCreate(LPCREATESTRUCT lpCreateStruct)
+{
+ if (CWnd::OnCreate(lpCreateStruct) == -1)
+ return -1;
+
+ s_hdcXY = ::GetDC(GetSafeHwnd());
+ QEW_SetupPixelFormat(s_hdcXY, false);
+ if ( ( s_hglrcXY = qwglCreateContext( s_hdcXY ) ) == 0 )
+ Error( "wglCreateContext in WXY_WndProc failed" );
+
+ if (!qwglShareLists( g_qeglobals.d_hglrcBase, s_hglrcXY ) )
+ Error( "wglShareLists in WXY_WndProc failed" );
+
+ if (!qwglMakeCurrent( s_hdcXY, s_hglrcXY ))
+ Error ("wglMakeCurrent failed");
+
+ qglPolygonStipple ((unsigned char *)s_stipple);
+ qglLineStipple (3, 0xaaaa);
+ g_qeglobals.d_hwndXY = GetSafeHwnd();
+ return 0;
+}
+
+float ptSum(vec3_t pt)
+{
+ return pt[0] + pt[1] + pt[2];
+}
+
+void CXYWnd::DropClipPoint(UINT nFlags, CPoint point)
+{
+ CRect rctZ;
+ GetClientRect(rctZ);
+ if (g_pMovingClip)
+ {
+ SetCapture();
+ SnapToPoint (point.x, rctZ.Height() - 1 - point.y , *g_pMovingClip);
+ }
+ else
+ {
+ vec3_t* pPt = NULL;
+ if (g_Clip1.Set() == false)
+ {
+ pPt = g_Clip1;
+ g_Clip1.Set(true);
+ g_Clip1.m_ptScreen = point;
+ }
+ else
+ if (g_Clip2.Set() == false)
+ {
+ pPt = g_Clip2;
+ g_Clip2.Set(true);
+ g_Clip2.m_ptScreen = point;
+ }
+ else
+ if (g_Clip3.Set() == false)
+ {
+ pPt = g_Clip3;
+ g_Clip3.Set(true);
+ g_Clip3.m_ptScreen = point;
+ }
+ else
+ {
+ RetainClipMode(true);
+ pPt = g_Clip1;
+ g_Clip1.Set(true);
+ g_Clip1.m_ptScreen = point;
+ }
+ SnapToPoint (point.x, rctZ.Height() - 1 - point.y , *pPt);
+ }
+ Sys_UpdateWindows(XY | W_CAMERA_IFON);
+}
+
+
+void CXYWnd::DropPathPoint(UINT nFlags, CPoint point)
+{
+ CRect rctZ;
+ GetClientRect(rctZ);
+ if (g_pMovingPath)
+ {
+ SetCapture();
+ SnapToPoint (point.x, rctZ.Height() - 1 - point.y , *g_pMovingPath);
+ }
+ else
+ {
+ g_PathPoints[g_nPathCount].Set(true);
+ g_PathPoints[g_nPathCount].m_ptScreen = point;
+ SnapToPoint(point.x, rctZ.Height() - 1 - point.y, g_PathPoints[g_nPathCount]);
+ g_nPathCount++;
+ if (g_nPathCount == g_nPathLimit)
+ {
+ if (g_pPathFunc)
+ g_pPathFunc(true, g_nPathCount);
+ g_nPathCount = 0;
+ g_bPathMode = false;
+ g_pPathFunc = NULL;
+ }
+ }
+ Sys_UpdateWindows(XY | W_CAMERA_IFON);
+}
+
+void CXYWnd::AddPointPoint(UINT nFlags, vec3_t* pVec)
+{
+ g_PointPoints[g_nPointCount].Set(true);
+ //g_PointPoints[g_nPointCount].m_ptScreen = point;
+ _VectorCopy(*pVec, g_PointPoints[g_nPointCount]);
+ g_PointPoints[g_nPointCount].SetPointPtr(pVec);
+ g_nPointCount++;
+ Sys_UpdateWindows(XY | W_CAMERA_IFON);
+}
+
+
+void CXYWnd::OnLButtonDown(UINT nFlags, CPoint point)
+{
+ g_pParentWnd->SetActiveXY(this);
+ UndoCopy();
+
+ // plugin entities
+ if (DispatchOnLButtonDown(nFlags, point.x, point.y ))
+ return;
+
+ if (ClipMode() && !RogueClipMode())
+ {
+ DropClipPoint(nFlags, point);
+ }
+ else if (PathMode())
+ {
+ DropPathPoint(nFlags, point);
+ }
+ else OriginalButtonDown(nFlags, point);
+}
+
+void CXYWnd::OnMButtonDown(UINT nFlags, CPoint point)
+{
+ OriginalButtonDown(nFlags, point);
+}
+
+
+float Betwixt(float f1, float f2)
+{
+ if (f1 > f2)
+ return f2 + ((f1 - f2) / 2);
+ else
+ return f1 + ((f2 - f1) / 2);
+}
+
+void CXYWnd::ProduceSplits(brush_t** pFront, brush_t** pBack)
+{
+ *pFront = NULL;
+ *pBack = NULL;
+ if (ClipMode())
+ {
+ if (g_Clip1.Set() && g_Clip2.Set())
+ {
+ face_t face;
+ VectorCopy(g_Clip1.m_ptClip,face.planepts[0]);
+ VectorCopy(g_Clip2.m_ptClip,face.planepts[1]);
+ VectorCopy(g_Clip3.m_ptClip,face.planepts[2]);
+ if (selected_brushes.next && (selected_brushes.next->next == &selected_brushes))
+ {
+ if (g_Clip3.Set() == false)
+ {
+ if (m_nViewType == XY)
+ {
+ face.planepts[0][2] = selected_brushes.next->mins[2];
+ face.planepts[1][2] = selected_brushes.next->mins[2];
+ face.planepts[2][0] = Betwixt(g_Clip1.m_ptClip[0], g_Clip2.m_ptClip[0]);
+ face.planepts[2][1] = Betwixt(g_Clip1.m_ptClip[1], g_Clip2.m_ptClip[1]);
+ face.planepts[2][2] = selected_brushes.next->maxs[2];
+ }
+ else if (m_nViewType == YZ)
+ {
+ face.planepts[0][0] = selected_brushes.next->mins[0];
+ face.planepts[1][0] = selected_brushes.next->mins[0];
+ face.planepts[2][1] = Betwixt(g_Clip1.m_ptClip[1], g_Clip2.m_ptClip[1]);
+ face.planepts[2][2] = Betwixt(g_Clip1.m_ptClip[2], g_Clip2.m_ptClip[2]);
+ face.planepts[2][0] = selected_brushes.next->maxs[0];
+ }
+ else
+ {
+ face.planepts[0][1] = selected_brushes.next->mins[1];
+ face.planepts[1][1] = selected_brushes.next->mins[1];
+ face.planepts[2][0] = Betwixt(g_Clip1.m_ptClip[0], g_Clip2.m_ptClip[0]);
+ face.planepts[2][2] = Betwixt(g_Clip1.m_ptClip[2], g_Clip2.m_ptClip[2]);
+ face.planepts[2][1] = selected_brushes.next->maxs[1];
+ }
+ }
+
+ Brush_SplitBrushByFace (selected_brushes.next, &face, pFront, pBack);
+ }
+
+ }
+ }
+}
+
+void CleanList(brush_t* pList)
+{
+ brush_t* pBrush = pList->next;
+ while (pBrush != NULL && pBrush != pList)
+ {
+ brush_t* pNext = pBrush->next;
+ Brush_Free(pBrush);
+ pBrush = pNext;
+ }
+}
+
+void CXYWnd::ProduceSplitLists()
+{
+ if (AnyPatchesSelected())
+ {
+ Sys_Printf("Deslecting patches for clip operation.\n");
+ brush_t *next;
+ for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = next)
+ {
+ next = pb->next;
+ if (pb->patchBrush)
+ {
+ Brush_RemoveFromList (pb);
+ Brush_AddToList (pb, &active_brushes);
+ UpdatePatchInspector();
+ }
+ if (pb->terrainBrush)
+ {
+ Brush_RemoveFromList (pb);
+ Brush_AddToList (pb, &active_brushes);
+ UpdateTerrainInspector();
+ }
+ }
+ }
+
+ CleanList(&g_brFrontSplits);
+ CleanList(&g_brBackSplits);
+ g_brFrontSplits.next = &g_brFrontSplits;
+ g_brBackSplits.next = &g_brBackSplits;
+ brush_t* pBrush;
+ for (pBrush = selected_brushes.next ; pBrush != NULL && pBrush != &selected_brushes ; pBrush=pBrush->next)
+ {
+ brush_t* pFront = NULL;
+ brush_t* pBack = NULL;
+ if (ClipMode())
+ {
+ if (g_Clip1.Set() && g_Clip2.Set())
+ {
+ face_t face;
+ VectorCopy(g_Clip1.m_ptClip,face.planepts[0]);
+ VectorCopy(g_Clip2.m_ptClip,face.planepts[1]);
+ VectorCopy(g_Clip3.m_ptClip,face.planepts[2]);
+ if (g_Clip3.Set() == false)
+ {
+ if (g_pParentWnd->ActiveXY()->GetViewType() == XY)
+ {
+ face.planepts[0][2] = pBrush->mins[2];
+ face.planepts[1][2] = pBrush->mins[2];
+ face.planepts[2][0] = Betwixt(g_Clip1.m_ptClip[0], g_Clip2.m_ptClip[0]);
+ face.planepts[2][1] = Betwixt(g_Clip1.m_ptClip[1], g_Clip2.m_ptClip[1]);
+ face.planepts[2][2] = pBrush->maxs[2];
+ }
+ else if (g_pParentWnd->ActiveXY()->GetViewType() == YZ)
+ {
+ face.planepts[0][0] = pBrush->mins[0];
+ face.planepts[1][0] = pBrush->mins[0];
+ face.planepts[2][1] = Betwixt(g_Clip1.m_ptClip[1], g_Clip2.m_ptClip[1]);
+ face.planepts[2][2] = Betwixt(g_Clip1.m_ptClip[2], g_Clip2.m_ptClip[2]);
+ face.planepts[2][0] = pBrush->maxs[0];
+ }
+ else
+ {
+ face.planepts[0][1] = pBrush->mins[1];
+ face.planepts[1][1] = pBrush->mins[1];
+ face.planepts[2][0] = Betwixt(g_Clip1.m_ptClip[0], g_Clip2.m_ptClip[0]);
+ face.planepts[2][2] = Betwixt(g_Clip1.m_ptClip[2], g_Clip2.m_ptClip[2]);
+ face.planepts[2][1] = pBrush->maxs[1];
+ }
+ }
+ Brush_SplitBrushByFace (pBrush, &face, &pFront, &pBack);
+ if (pBack)
+ Brush_AddToList(pBack, &g_brBackSplits);
+ if (pFront)
+ Brush_AddToList(pFront, &g_brFrontSplits);
+ }
+ }
+ }
+}
+
+void Brush_CopyList (brush_t* pFrom, brush_t* pTo)
+{
+ brush_t* pBrush = pFrom->next;
+ while (pBrush != NULL && pBrush != pFrom)
+ {
+ brush_t* pNext = pBrush->next;
+ Brush_RemoveFromList(pBrush);
+ Brush_AddToList(pBrush, pTo);
+ pBrush = pNext;
+ }
+}
+
+void CXYWnd::OnRButtonDown(UINT nFlags, CPoint point)
+{
+ g_pParentWnd->SetActiveXY(this);
+ m_ptDown = point;
+ m_bRButtonDown = true;
+
+ if (g_PrefsDlg.m_nMouseButtons == 3) // 3 button mouse
+ {
+ if ((GetKeyState(VK_CONTROL) & 0x8000))
+ {
+ if (ClipMode()) // already there?
+ DropClipPoint(nFlags, point);
+ else
+ {
+ SetClipMode(true);
+ g_bRogueClipMode = true;
+ DropClipPoint(nFlags, point);
+ }
+ return;
+ }
+ }
+ OriginalButtonDown(nFlags, point);
+}
+
+void CXYWnd::OnLButtonUp(UINT nFlags, CPoint point)
+{
+ // plugin entities
+ if (DispatchOnLButtonUp(nFlags, point.x, point.y ))
+ return;
+
+ if (ClipMode())
+ {
+ if (g_pMovingClip)
+ {
+ ReleaseCapture();
+ g_pMovingClip = NULL;
+ }
+ }
+ OriginalButtonUp(nFlags, point);
+}
+
+void CXYWnd::OnMButtonUp(UINT nFlags, CPoint point)
+{
+ OriginalButtonUp(nFlags, point);
+}
+
+void CXYWnd::OnRButtonUp(UINT nFlags, CPoint point)
+{
+ m_bRButtonDown = false;
+ if (point == m_ptDown) // mouse didn't move
+ {
+ bool bGo = true;
+ if ((GetKeyState(VK_MENU) & 0x8000))
+ bGo = false;
+ if ((GetKeyState(VK_CONTROL) & 0x8000))
+ bGo = false;
+ if ((GetKeyState(VK_SHIFT) & 0x8000))
+ bGo = false;
+ if (bGo)
+ HandleDrop();
+ }
+ OriginalButtonUp(nFlags, point);
+}
+
+void CXYWnd::OriginalButtonDown(UINT nFlags, CPoint point)
+{
+ CRect rctZ;
+ GetClientRect(rctZ);
+ SetWindowPos(&wndTop, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE);
+ if (::GetTopWindow( g_qeglobals.d_hwndMain ) != GetSafeHwnd())
+ ::BringWindowToTop(GetSafeHwnd());
+ SetFocus();
+ SetCapture();
+ XY_MouseDown (point.x, rctZ.Height() - 1 - point.y , nFlags);
+ m_nScrollFlags = nFlags;
+}
+
+void CXYWnd::OriginalButtonUp(UINT nFlags, CPoint point)
+{
+ CRect rctZ;
+ GetClientRect(rctZ);
+ XY_MouseUp (point.x, rctZ.Height() - 1 - point.y , nFlags);
+ if (! (nFlags & (MK_LBUTTON|MK_RBUTTON|MK_MBUTTON)))
+ ReleaseCapture ();
+}
+
+
+float fDiff(float f1, float f2)
+{
+ if (f1 > f2)
+ return f1 - f2;
+ else
+ return f2 - f1;
+}
+
+
+vec3_t tdp;
+void CXYWnd::OnMouseMove(UINT nFlags, CPoint point)
+{
+ // plugin entities
+ //++timo TODO: handle return code
+ DispatchOnMouseMove( nFlags, point.x, point.y );
+
+ m_ptDown.x = 0;
+ m_ptDown.y = 0;
+
+ if ( g_PrefsDlg.m_bChaseMouse == TRUE &&
+ (point.x < 0 || point.y < 0 ||
+ point.x > m_nWidth || point.y > m_nHeight) &&
+ GetCapture() == this)
+ {
+ float fAdjustment = (g_qeglobals.d_gridsize / 8 * 64) / m_fScale;
+ //m_ptDrag = point;
+ m_ptDragAdj.x = 0;
+ m_ptDragAdj.y = 0;
+ if (point.x < 0)
+ {
+ m_ptDragAdj.x = -fAdjustment;
+ }
+ else
+ if (point.x > m_nWidth)
+ {
+ m_ptDragAdj.x = fAdjustment;
+ }
+ if (point.y < 0)
+ {
+ m_ptDragAdj.y = -fAdjustment;
+ }
+ else
+ if (point.y > m_nHeight)
+ {
+ m_ptDragAdj.y = fAdjustment;
+ }
+ if (m_nTimerID == -1)
+ {
+ m_nTimerID = SetTimer(100, 50, NULL);
+ m_ptDrag = point;
+ m_ptDragTotal = 0;
+ }
+ return;
+ }
+ //else if (m_nTimerID != -1)
+ if (m_nTimerID != -1)
+ {
+ KillTimer(m_nTimerID);
+ pressx -= m_ptDragTotal.x;
+ pressy += m_ptDragTotal.y;
+ m_nTimerID = -1;
+ //return;
+ }
+
+ bool bCrossHair = false;
+ if (!m_bRButtonDown)
+ {
+ tdp[0] = tdp[1] = tdp[2] = 0.0;
+ SnapToPoint (point.x, m_nHeight - 1 - point.y , tdp);
+
+ g_strStatus.Format("x:: %.1f y:: %.1f z:: %.1f", tdp[0], tdp[1], tdp[2]);
+ g_pParentWnd->SetStatusText(1, g_strStatus);
+
+ // i need to generalize the point code.. having 3 flavors pretty much sucks..
+ // once the new curve stuff looks like it is going to stick i will
+ // rationalize this down to a single interface..
+ if (PointMode())
+ {
+ if (g_pMovingPoint && GetCapture() == this)
+ {
+ bCrossHair = true;
+ SnapToPoint (point.x, m_nHeight - 1 - point.y , g_pMovingPoint->m_ptClip);
+ g_pMovingPoint->UpdatePointPtr();
+ Sys_UpdateWindows(XY | W_CAMERA_IFON);
+ }
+ else
+ {
+ g_pMovingPoint = NULL;
+ int nDim1 = (m_nViewType == YZ) ? 1 : 0;
+ int nDim2 = (m_nViewType == XY) ? 1 : 2;
+ for (int n = 0; n < g_nPointCount; n++)
+ {
+ if ( fDiff(g_PointPoints[n].m_ptClip[nDim1], tdp[nDim1]) < 3 &&
+ fDiff(g_PointPoints[n].m_ptClip[nDim2], tdp[nDim2]) < 3 )
+ {
+ bCrossHair = true;
+ g_pMovingPoint = &g_PointPoints[n];
+ }
+ }
+ }
+ }
+ else if (ClipMode())
+ {
+ if (g_pMovingClip && GetCapture() == this)
+ {
+ bCrossHair = true;
+ SnapToPoint (point.x, m_nHeight - 1 - point.y , g_pMovingClip->m_ptClip);
+ Sys_UpdateWindows(XY | W_CAMERA_IFON);
+ }
+ else
+ {
+ g_pMovingClip = NULL;
+ int nDim1 = (m_nViewType == YZ) ? 1 : 0;
+ int nDim2 = (m_nViewType == XY) ? 1 : 2;
+ if (g_Clip1.Set())
+ {
+ if ( fDiff(g_Clip1.m_ptClip[nDim1], tdp[nDim1]) < 3 &&
+ fDiff(g_Clip1.m_ptClip[nDim2], tdp[nDim2]) < 3 )
+ {
+ bCrossHair = true;
+ g_pMovingClip = &g_Clip1;
+ }
+ }
+ if (g_Clip2.Set())
+ {
+ if ( fDiff(g_Clip2.m_ptClip[nDim1], tdp[nDim1]) < 3 &&
+ fDiff(g_Clip2.m_ptClip[nDim2], tdp[nDim2]) < 3 )
+ {
+ bCrossHair = true;
+ g_pMovingClip = &g_Clip2;
+ }
+ }
+ if (g_Clip3.Set())
+ {
+ if ( fDiff(g_Clip3.m_ptClip[nDim1], tdp[nDim1]) < 3 &&
+ fDiff(g_Clip3.m_ptClip[nDim2], tdp[nDim2]) < 3 )
+ {
+ bCrossHair = true;
+ g_pMovingClip = &g_Clip3;
+ }
+ }
+ }
+ if (bCrossHair == false)
+ XY_MouseMoved (point.x, m_nHeight - 1 - point.y , nFlags);
+ }
+ else if (PathMode())
+ {
+ if (g_pMovingPath && GetCapture() == this)
+ {
+ bCrossHair = true;
+ SnapToPoint (point.x, m_nHeight - 1 - point.y , g_pMovingPath->m_ptClip);
+ Sys_UpdateWindows(XY | W_CAMERA_IFON);
+ }
+ else
+ {
+ g_pMovingPath = NULL;
+ int nDim1 = (m_nViewType == YZ) ? 1 : 0;
+ int nDim2 = (m_nViewType == XY) ? 1 : 2;
+ for (int n = 0; n < g_nPathCount; n++)
+ {
+ if ( fDiff(g_PathPoints[n].m_ptClip[nDim1], tdp[nDim1]) < 3 &&
+ fDiff(g_PathPoints[n].m_ptClip[nDim2], tdp[nDim2]) < 3 )
+ {
+ bCrossHair = true;
+ g_pMovingPath = &g_PathPoints[n];
+ }
+ }
+ }
+ }
+ else
+ {
+ XY_MouseMoved (point.x, m_nHeight - 1 - point.y , nFlags);
+ }
+ }
+ else
+ {
+ XY_MouseMoved (point.x, m_nHeight - 1 - point.y , nFlags);
+ }
+ if (bCrossHair)
+ SetCursor(::LoadCursor(NULL, IDC_CROSS));
+ else
+ SetCursor(::LoadCursor(NULL, IDC_ARROW));
+}
+
+void CXYWnd::RetainClipMode(bool bMode)
+{
+ bool bSave = g_bRogueClipMode;
+ SetClipMode(bMode);
+ if (bMode == true)
+ g_bRogueClipMode = bSave;
+ else
+ g_bRogueClipMode = false;
+}
+
+void CXYWnd::SetClipMode(bool bMode)
+{
+ g_bClipMode = bMode;
+ g_bRogueClipMode = false;
+ if (bMode)
+ {
+ g_Clip1.Reset();
+ g_Clip2.Reset();
+ g_Clip3.Reset();
+ CleanList(&g_brFrontSplits);
+ CleanList(&g_brBackSplits);
+ g_brFrontSplits.next = &g_brFrontSplits;
+ g_brBackSplits.next = &g_brBackSplits;
+ }
+ else
+ {
+ if (g_pMovingClip)
+ {
+ ReleaseCapture();
+ g_pMovingClip = NULL;
+ }
+ CleanList(&g_brFrontSplits);
+ CleanList(&g_brBackSplits);
+ g_brFrontSplits.next = &g_brFrontSplits;
+ g_brBackSplits.next = &g_brBackSplits;
+ Sys_UpdateWindows(XY | W_CAMERA_IFON);
+ }
+}
+
+bool CXYWnd::ClipMode()
+{
+ return g_bClipMode;
+}
+
+bool CXYWnd::RogueClipMode()
+{
+ return g_bRogueClipMode;
+}
+
+bool CXYWnd::PathMode()
+{
+ return g_bPathMode;
+}
+
+
+bool CXYWnd::PointMode()
+{
+ return g_bPointMode;
+}
+
+void CXYWnd::SetPointMode(bool b)
+{
+ g_bPointMode = b;
+ if (!b)
+ g_nPointCount = 0;
+}
+
+
+void CXYWnd::OnPaint()
+{
+ CPaintDC dc(this); // device context for painting
+ bool bPaint = true;
+ if (!qwglMakeCurrent(dc.m_hDC, s_hglrcXY))
+ {
+ Sys_Printf("ERROR: wglMakeCurrent failed.. Error:%i\n",qglGetError());
+ Sys_Printf("Please restart Q3Radiant if the Map view is not working\n");
+ bPaint = false;
+ }
+ if (bPaint)
+ {
+ QE_CheckOpenGLForErrors();
+ XY_Draw ();
+ QE_CheckOpenGLForErrors();
+
+ if (m_nViewType != XY)
+ {
+ qglPushMatrix();
+ if (m_nViewType == YZ)
+ qglRotatef (-90, 0, 1, 0); // put Z going up
+ qglRotatef (-90, 1, 0, 0); // put Z going up
+ }
+
+ if (g_bCrossHairs)
+ {
+ qglColor4f(0.2, 0.9, 0.2, 0.8);
+ qglBegin (GL_LINES);
+ if (m_nViewType == XY)
+ {
+ qglVertex2f(-16384, tdp[1]);
+ qglVertex2f(16384, tdp[1]);
+ qglVertex2f(tdp[0], -16384);
+ qglVertex2f(tdp[0], 16384);
+ }
+ else if (m_nViewType == YZ)
+ {
+ qglVertex3f(tdp[0], -16384, tdp[2]);
+ qglVertex3f(tdp[0], 16384, tdp[2]);
+ qglVertex3f(tdp[0], tdp[1], -16384);
+ qglVertex3f(tdp[0], tdp[1], 16384);
+ }
+ else
+ {
+ qglVertex3f(-16384, tdp[1], tdp[2]);
+ qglVertex3f( 16384, tdp[1], tdp[2]);
+ qglVertex3f(tdp[0], tdp[1], -16384);
+ qglVertex3f(tdp[0], tdp[1], 16384);
+ }
+ qglEnd();
+ }
+
+ if (ClipMode())
+ {
+ qglPointSize (4);
+ qglColor3fv(g_qeglobals.d_savedinfo.colors[COLOR_CLIPPER]);
+ qglBegin (GL_POINTS);
+ if (g_Clip1.Set())
+ qglVertex3fv (g_Clip1);
+ if (g_Clip2.Set())
+ qglVertex3fv (g_Clip2);
+ if (g_Clip3.Set())
+ qglVertex3fv (g_Clip3);
+ qglEnd ();
+ qglPointSize (1);
+
+ CString strMsg;
+ if (g_Clip1.Set())
+ {
+ qglRasterPos3f (g_Clip1.m_ptClip[0]+2, g_Clip1.m_ptClip[1]+2, g_Clip1.m_ptClip[2]+2);
+ strMsg = "1";
+ //strMsg.Format("1 (%f, %f, %f)", g_Clip1[0], g_Clip1[1], g_Clip1[2]);
+ qglCallLists (strMsg.GetLength(), GL_UNSIGNED_BYTE, strMsg);
+ }
+ if (g_Clip2.Set())
+ {
+ qglRasterPos3f (g_Clip2.m_ptClip[0]+2, g_Clip2.m_ptClip[1]+2, g_Clip2.m_ptClip[2]+2);
+ strMsg = "2";
+ //strMsg.Format("2 (%f, %f, %f)", g_Clip2[0], g_Clip2[1], g_Clip2[2]);
+ qglCallLists (strMsg.GetLength(), GL_UNSIGNED_BYTE, strMsg);
+ }
+ if (g_Clip3.Set())
+ {
+ qglRasterPos3f (g_Clip3.m_ptClip[0]+2, g_Clip3.m_ptClip[1]+2, g_Clip3.m_ptClip[2]+2);
+ strMsg = "3";
+ //strMsg.Format("3 (%f, %f, %f)", g_Clip3[0], g_Clip3[1], g_Clip3[2]);
+ qglCallLists (strMsg.GetLength(), GL_UNSIGNED_BYTE, strMsg);
+ }
+ if (g_Clip1.Set() && g_Clip2.Set())
+ {
+ ProduceSplitLists();
+ brush_t* pBrush;
+ brush_t* pList = ( (m_nViewType == XZ) ? !g_bSwitch : g_bSwitch) ? &g_brBackSplits : &g_brFrontSplits;
+ for (pBrush = pList->next ; pBrush != NULL && pBrush != pList ; pBrush=pBrush->next)
+ {
+ qglColor3f (1,1,0);
+ face_t *face;
+ int order;
+ for (face = pBrush->brush_faces,order = 0 ; face ; face=face->next, order++)
+ {
+ winding_t* w = face->face_winding;
+ if (!w)
+ continue;
+ // draw the polygon
+ qglBegin(GL_LINE_LOOP);
+ for (int i=0 ; i<w->numpoints ; i++)
+ qglVertex3fv(w->points[i]);
+ qglEnd();
+ }
+ }
+ }
+
+ }
+
+
+
+ if (PathMode())
+ {
+ qglPointSize (4);
+ qglColor3fv(g_qeglobals.d_savedinfo.colors[COLOR_CLIPPER]);
+ qglBegin (GL_POINTS);
+
+ for (int n = 0; n < g_nPathCount; n++)
+ qglVertex3fv(g_PathPoints[n]);
+ qglEnd ();
+ qglPointSize (1);
+
+ CString strMsg;
+ for (n = 0; n < g_nPathCount; n++)
+ {
+ qglRasterPos3f (g_PathPoints[n].m_ptClip[0]+2, g_PathPoints[n].m_ptClip[1]+2, g_PathPoints[n].m_ptClip[2]+2);
+ strMsg.Format("%i", n+1);
+ qglCallLists (strMsg.GetLength(), GL_UNSIGNED_BYTE, strMsg);
+ }
+
+ }
+ if (m_nViewType != XY)
+ qglPopMatrix();
+
+ qwglSwapBuffers(dc.m_hDC);
+ TRACE("XY Paint\n");
+ }
+ }
+
+void CXYWnd::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
+{
+ g_pParentWnd->HandleKey(nChar, nRepCnt, nFlags);
+}
+
+
+
+// FIXME: the brush_t *pBrush is never used. ( Entity_Create uses selected_brushes )
+void CreateEntityFromName(char* pName, brush_t* pBrush)
+{
+ eclass_t *pecNew;
+ entity_t *petNew;
+ if (stricmp(pName, "worldspawn") == 0)
+ {
+ MessageBox(g_qeglobals.d_hwndMain, "Can't create an entity with worldspawn.", "info", 0);
+ return;
+ }
+
+ pecNew = Eclass_ForName(pName, false);
+
+ // create it
+ petNew = Entity_Create(pecNew);
+ if (petNew == NULL)
+ {
+ if (!((selected_brushes.next == &selected_brushes)||(selected_brushes.next->next != &selected_brushes)))
+ {
+ brush_t* b = selected_brushes.next;
+ if (b->owner != world_entity && b->owner->eclass->fixedsize && pecNew->fixedsize)
+ {
+ vec3_t mins, maxs;
+ vec3_t origin;
+ for (int i=0 ; i<3 ; i++)
+ origin[i] = b->mins[i] - pecNew->mins[i];
+
+ VectorAdd (pecNew->mins, origin, mins);
+ VectorAdd (pecNew->maxs, origin, maxs);
+ brush_t* nb = Brush_Create (mins, maxs, &pecNew->texdef);
+ Entity_LinkBrush (b->owner, nb);
+ nb->owner->eclass = pecNew;
+ SetKeyValue (nb->owner, "classname", pName);
+ Brush_Free(b);
+ Brush_Build(nb);
+ Brush_AddToList (nb, &active_brushes);
+ Select_Brush(nb);
+ return;
+ }
+ }
+ MessageBox(g_qeglobals.d_hwndMain, "Failed to create entity.", "info", 0);
+ return;
+ }
+
+ Select_Deselect ();
+ //entity_t* pEntity = world_entity;
+ //if (selected_brushes.next != &selected_brushes)
+ // pEntity = selected_brushes.next->owner;
+ Select_Brush (petNew->brushes.onext);
+
+ if (stricmp(pName, "misc_model") == 0)
+ {
+ SetInspectorMode(W_ENTITY);
+ PostMessage(g_qeglobals.d_hwndEntity, WM_COMMAND, IDC_BTN_ASSIGNMODEL, 0);
+ }
+
+}
+
+
+brush_t* CreateEntityBrush(int x, int y, CXYWnd* pWnd)
+{
+ vec3_t mins, maxs;
+ int i;
+ float temp;
+ brush_t *n;
+
+ pWnd->SnapToPoint (x, y, mins);
+ x += 32;
+ y += 32;
+ pWnd->SnapToPoint (x, y, maxs);
+
+ int nDim = (pWnd->GetViewType() == XY) ? 2 : (pWnd->GetViewType() == YZ) ? 0 : 1;
+ mins[nDim] = g_qeglobals.d_gridsize * ((int)(g_qeglobals.d_new_brush_bottom_z/g_qeglobals.d_gridsize));
+ maxs[nDim] = g_qeglobals.d_gridsize * ((int)(g_qeglobals.d_new_brush_top_z/g_qeglobals.d_gridsize));
+
+ if (maxs[nDim] <= mins[nDim])
+ maxs[nDim] = mins[nDim] + g_qeglobals.d_gridsize;
+
+ for (i=0 ; i<3 ; i++)
+ {
+ if (mins[i] == maxs[i])
+ maxs[i] += 16; // don't create a degenerate brush
+ if (mins[i] > maxs[i])
+ {
+ temp = mins[i];
+ mins[i] = maxs[i];
+ maxs[i] = temp;
+ }
+ }
+
+ n = Brush_Create (mins, maxs, &g_qeglobals.d_texturewin.texdef);
+ if (!n)
+ return NULL;
+
+ Brush_AddToList (n, &selected_brushes);
+ Entity_LinkBrush (world_entity, n);
+ Brush_Build( n );
+ return n;
+}
+
+void CreateRightClickEntity(CXYWnd* pWnd, int x, int y, char* pName)
+{
+ CRect rctZ;
+ pWnd->GetClientRect(rctZ);
+ brush_t* pBrush = (selected_brushes.next == &selected_brushes) ? CreateEntityBrush(x, rctZ.Height() - 1 - y, pWnd) : selected_brushes.next;
+ CreateEntityFromName(pName, pBrush);
+ //Select_Brush(pBrush);
+}
+
+brush_t* CreateSmartBrush(vec3_t v)
+{
+ vec3_t mins, maxs;
+ int i;
+ brush_t *n;
+
+ for (i=0 ; i<3 ; i++)
+ {
+ mins[i] = v[i] - 16;
+ maxs[i] = v[i] + 16;
+ }
+
+ n = Brush_Create (mins, maxs, &g_qeglobals.d_texturewin.texdef);
+ if (!n)
+ return NULL;
+
+ Brush_AddToList(n, &selected_brushes);
+ //Entity_LinkBrush(world_entity, n);
+ Brush_Build(n);
+ return n;
+}
+
+
+
+
+CString g_strSmartEntity;
+int g_nSmartX;
+int g_nSmartY;
+bool g_bSmartWaiting;
+void _SmartPointDone(bool b, int n)
+{
+ g_bSmartWaiting = false;
+}
+
+void CreateSmartEntity(CXYWnd* pWnd, int x, int y, const char* pName)
+{
+ g_nSmartX = x;
+ g_nSmartY = y;
+ g_strSmartEntity = pName;
+ if (g_strSmartEntity.Find("Smart_Train") >= 0)
+ {
+ ShowInfoDialog("Select the path of the train by left clicking in XY, YZ and/or XZ views. You can move an already dropped point by grabbing and moving it. When you are finished, press ENTER to accept and create the entity and path(s), press ESC to abandon the creation");
+ g_bPathMode = true;
+ g_nPathLimit = 0;
+ g_nPathCount = 0;
+ g_bSmartGo = true;
+ }
+ else
+ if (g_strSmartEntity.Find("Smart_Monster...") >= 0)
+ {
+ g_bPathMode = true;
+ g_nPathLimit = 0;
+ g_nPathCount = 0;
+ }
+ else
+ if (g_strSmartEntity.Find("Smart_Rotating") >= 0)
+ {
+ g_bSmartWaiting = true;
+ ShowInfoDialog("Left click to specify the rotation origin");
+ AcquirePath(1, &_SmartPointDone);
+ while (g_bSmartWaiting)
+ {
+ MSG msg;
+ if (::PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ))
+ {
+ TranslateMessage(&msg);
+ DispatchMessage(&msg);
+ }
+ }
+ HideInfoDialog();
+ CPtrArray array;
+ g_bScreenUpdates = false;
+ CreateRightClickEntity(g_pParentWnd->ActiveXY(), g_nSmartX, g_nSmartY, "func_rotating");
+ array.Add(reinterpret_cast<void*>(selected_brushes.next));
+ Select_Deselect();
+ brush_t* pBrush = CreateSmartBrush(g_PathPoints[0]);
+ array.Add(pBrush);
+ Select_Deselect();
+ Select_Brush(reinterpret_cast<brush_t*>(array.GetAt(0)));
+ Select_Brush(reinterpret_cast<brush_t*>(array.GetAt(1)));
+ ConnectEntities();
+ g_bScreenUpdates = true;
+ }
+}
+
+
+void FinishSmartCreation()
+{
+ CPtrArray array;
+ HideInfoDialog();
+ brush_t* pEntities = NULL;
+ if (g_strSmartEntity.Find("Smart_Train") >= 0)
+ {
+ g_bScreenUpdates = false;
+ CreateRightClickEntity(g_pParentWnd->ActiveXY(), g_nSmartX, g_nSmartY, "func_train");
+ array.Add(reinterpret_cast<void*>(selected_brushes.next));
+ for (int n = 0; n < g_nPathCount; n++)
+ {
+ Select_Deselect();
+ CreateRightClickEntity(g_pParentWnd->ActiveXY(), g_PathPoints[n].m_ptScreen.x,g_PathPoints[n].m_ptScreen.y, "path_corner");
+ array.Add(reinterpret_cast<void*>(selected_brushes.next));
+ }
+
+ for (n = 0; n < g_nPathCount; n++)
+ {
+ Select_Deselect();
+ Select_Brush(reinterpret_cast<brush_t*>(array.GetAt(n)));
+ Select_Brush(reinterpret_cast<brush_t*>(array.GetAt(n+1)));
+ ConnectEntities();
+ }
+ g_bScreenUpdates = true;
+
+ }
+ g_nPathCount = 0;
+ g_bPathMode = false;
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CXYWnd::KillPathMode()
+{
+ g_bSmartGo = false;
+ g_bPathMode = false;
+ if (g_pPathFunc)
+ g_pPathFunc(false, g_nPathCount);
+ g_nPathCount = 0;
+ g_pPathFunc = NULL;
+ Sys_UpdateWindows(W_ALL);
+}
+
+// gets called for drop down menu messages
+// TIP: it's not always about EntityCreate
+void CXYWnd::OnEntityCreate(unsigned int nID)
+{
+ if (m_mnuDrop.GetSafeHmenu())
+ {
+ CString strItem;
+ m_mnuDrop.GetMenuString(nID, strItem, MF_BYCOMMAND);
+
+ if (strItem.CompareNoCase("Add to...") == 0)
+ {
+ //++timo TODO: fill the menu with current groups?
+ // this one is for adding to existing groups only
+ Sys_Printf("TODO: Add to... in CXYWnd::OnEntityCreate\n");
+ }
+ else if (strItem.CompareNoCase("Remove") == 0)
+ {
+ // remove selected brushes from their current group
+ brush_t *b;
+ for( b = selected_brushes.next; b != &selected_brushes; b = b->next )
+ {
+
+ }
+ }
+
+ //++timo FIXME: remove when all hooks are in
+ if (strItem.CompareNoCase("Add to...") == 0
+ || strItem.CompareNoCase("Remove") == 0
+ || strItem.CompareNoCase("Name...") == 0
+ || strItem.CompareNoCase("New group...") == 0)
+ {
+ Sys_Printf("TODO: hook drop down group menu\n");
+ return;
+ }
+
+ if (strItem.Find("Smart_") >= 0)
+ {
+ CreateSmartEntity(this, m_ptDown.x, m_ptDown.y, strItem);
+ }
+ else
+ {
+ CreateRightClickEntity(this, m_ptDown.x, m_ptDown.y, strItem.GetBuffer(0));
+ }
+
+ Sys_UpdateWindows(W_ALL);
+ //OnLButtonDown((MK_LBUTTON | MK_SHIFT), CPoint(m_ptDown.x+2, m_ptDown.y+2));
+ }
+}
+
+
+void CXYWnd::HandleDrop()
+{
+ if (g_PrefsDlg.m_bRightClick == false)
+ return;
+ if (!m_mnuDrop.GetSafeHmenu()) // first time, load it up
+ {
+ m_mnuDrop.CreatePopupMenu();
+ int nID = ID_ENTITY_START;
+
+ CMenu* pChild2 = new CMenu;
+ pChild2->CreateMenu();
+ pChild2->AppendMenu(MF_STRING, ID_SELECTION_SELECTCOMPLETETALL, "Select Complete Tall");
+ pChild2->AppendMenu(MF_STRING, ID_SELECTION_SELECTTOUCHING, "Select Touching");
+ pChild2->AppendMenu(MF_STRING, ID_SELECTION_SELECTPARTIALTALL, "Select Partial Tall");
+ pChild2->AppendMenu(MF_STRING, ID_SELECTION_SELECTINSIDE, "Select Inside");
+ m_mnuDrop.AppendMenu(MF_POPUP, reinterpret_cast<unsigned int>(pChild2->GetSafeHmenu()), "Select");
+ m_mnuDrop.AppendMenu(MF_SEPARATOR, nID++, "");
+
+ CMenu* pChild3 = new CMenu;
+ pChild3->CreateMenu();
+ pChild3->AppendMenu(MF_STRING, ID_DROP_GROUP_ADDTO, "Add to...");
+ pChild3->AppendMenu(MF_STRING, ID_DROP_GROUP_REMOVE, "Remove");
+ pChild3->AppendMenu(MF_STRING, ID_DROP_GROUP_NAME, "Name...");
+ pChild3->AppendMenu(MF_SEPARATOR, nID++, "");
+ pChild3->AppendMenu(MF_STRING, ID_DROP_GROUP_NEWGROUP, "New Group...");
+ m_mnuDrop.AppendMenu(MF_POPUP, reinterpret_cast<unsigned int>(pChild3->GetSafeHmenu()), "Group");
+ m_mnuDrop.AppendMenu(MF_SEPARATOR, nID++, "");
+
+ m_mnuDrop.AppendMenu(MF_STRING, ID_SELECTION_UNGROUPENTITY, "Ungroup Entity");
+ m_mnuDrop.AppendMenu(MF_STRING, ID_SELECTION_MAKE_DETAIL, "Make Detail");
+ m_mnuDrop.AppendMenu(MF_STRING, ID_SELECTION_MAKE_STRUCTURAL, "Make Structural");
+ m_mnuDrop.AppendMenu(MF_SEPARATOR, nID++, "");
+
+ CMenu* pChild = new CMenu;
+ pChild->CreateMenu();
+ pChild->AppendMenu(MF_STRING, nID++, "Smart_Train");
+ //pChild->AppendMenu(MF_STRING, nID++, "Smart_Rotating");
+ m_mnuDrop.AppendMenu(MF_POPUP, reinterpret_cast<unsigned int>(pChild->GetSafeHmenu()), "Smart Entities");
+ m_mnuDrop.AppendMenu(MF_SEPARATOR, nID++, "");
+
+ pChild = NULL;
+ eclass_t *e;
+ CString strActive;
+ CString strLast;
+ CString strName;
+ for (e=eclass ; e ; e=e->next)
+ {
+ strLast = strName;
+ strName = e->name;
+ int n_ = strName.Find("_");
+ if (n_ > 0)
+ {
+ CString strLeft = strName.Left(n_);
+ CString strRight = strName.Right(strName.GetLength() - n_ - 1);
+ if (strLeft == strActive) // this is a child
+ {
+ ASSERT(pChild);
+ pChild->AppendMenu(MF_STRING, nID++, strName);
+ }
+ else
+ {
+ if (pChild)
+ {
+ m_mnuDrop.AppendMenu(MF_POPUP, reinterpret_cast<unsigned int>(pChild->GetSafeHmenu()), strActive);
+ g_ptrMenus.Add(pChild);
+ //pChild->DestroyMenu();
+ //delete pChild;
+ pChild = NULL;
+ }
+ strActive = strLeft;
+ pChild = new CMenu;
+ pChild->CreateMenu();
+ pChild->AppendMenu(MF_STRING, nID++, strName);
+ }
+ }
+ else
+ {
+ if (pChild)
+ {
+ m_mnuDrop.AppendMenu(MF_POPUP, reinterpret_cast<unsigned int>(pChild->GetSafeHmenu()), strActive);
+ g_ptrMenus.Add(pChild);
+ //pChild->DestroyMenu();
+ //delete pChild;
+ pChild = NULL;
+ }
+ strActive = "";
+ m_mnuDrop.AppendMenu(MF_STRING, nID++, strName);
+ }
+ }
+ }
+
+ CPoint ptMouse;
+ GetCursorPos(&ptMouse);
+ m_mnuDrop.TrackPopupMenu(TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_RIGHTBUTTON, ptMouse.x, ptMouse.y, this);
+}
+
+void CXYWnd::XY_Init()
+{
+ m_vOrigin[0] = 0;
+ m_vOrigin[1] = 20;
+ m_vOrigin[2] = 46;
+ m_fScale = 1;
+}
+
+void CXYWnd::SnapToPoint (int x, int y, vec3_t point)
+{
+ if (g_PrefsDlg.m_bNoClamp)
+ {
+ XY_ToPoint(x, y, point);
+ }
+ else
+ {
+ XY_ToGridPoint(x, y, point);
+ }
+//-- else
+//-- XY_ToPoint(x, y, point);
+//-- //XY_ToPoint(x, y, point);
+}
+
+
+void CXYWnd::XY_ToPoint (int x, int y, vec3_t point)
+{
+ float fx = x;
+ float fy = y;
+ float fw = m_nWidth;
+ float fh = m_nHeight;
+ if (m_nViewType == XY)
+ {
+ point[0] = m_vOrigin[0] + (fx - fw / 2) / m_fScale;
+ point[1] = m_vOrigin[1] + (fy - fh / 2) / m_fScale;
+ //point[2] = 0;
+ }
+ else if (m_nViewType == YZ)
+ {
+ ////point[0] = 0;
+ //point[1] = m_vOrigin[0] + (fx - fw / 2) / m_fScale;
+ //point[2] = m_vOrigin[1] + (fy - fh / 2 ) / m_fScale;
+ point[1] = m_vOrigin[1] + (fx - fw / 2) / m_fScale;
+ point[2] = m_vOrigin[2] + (fy - fh / 2 ) / m_fScale;
+ }
+ else
+ {
+ //point[0] = m_vOrigin[0] + (fx - fw / 2) / m_fScale;
+ ////point[1] = 0;
+ //point[2] = m_vOrigin[1] + (fy - fh / 2) / m_fScale;
+ point[0] = m_vOrigin[0] + (fx - fw / 2) / m_fScale;
+ //point[1] = 0;
+ point[2] = m_vOrigin[2] + (fy - fh / 2) / m_fScale;
+ }
+}
+
+
+void CXYWnd::XY_ToGridPoint (int x, int y, vec3_t point)
+{
+ if (m_nViewType == XY)
+ {
+ point[0] = m_vOrigin[0] + (x - m_nWidth / 2) / m_fScale;
+ point[1] = m_vOrigin[1] + (y - m_nHeight / 2) / m_fScale;
+ //point[2] = 0;
+ point[0] = floor(point[0] / g_qeglobals.d_gridsize + 0.5) * g_qeglobals.d_gridsize;
+ point[1] = floor(point[1] / g_qeglobals.d_gridsize + 0.5) * g_qeglobals.d_gridsize;
+ }
+ else if (m_nViewType == YZ)
+ {
+ //point[0] = 0;
+ //point[1] = m_vOrigin[0] + (x - m_nWidth / 2) / m_fScale;
+ //point[2] = m_vOrigin[1] + (y - m_nHeight / 2) / m_fScale;
+ point[1] = m_vOrigin[1] + (x - m_nWidth / 2) / m_fScale;
+ point[2] = m_vOrigin[2] + (y - m_nHeight / 2) / m_fScale;
+ point[1] = floor(point[1] / g_qeglobals.d_gridsize + 0.5) * g_qeglobals.d_gridsize;
+ point[2] = floor(point[2] / g_qeglobals.d_gridsize + 0.5) * g_qeglobals.d_gridsize;
+ }
+ else
+ {
+ //point[1] = 0;
+ //point[0] = m_vOrigin[0] + (x - m_nWidth / 2) / m_fScale;
+ //point[2] = m_vOrigin[1] + (y - m_nHeight / 2) / m_fScale;
+ point[0] = m_vOrigin[0] + (x - m_nWidth / 2) / m_fScale;
+ point[2] = m_vOrigin[2] + (y - m_nHeight / 2) / m_fScale;
+ point[0] = floor(point[0] / g_qeglobals.d_gridsize + 0.5) * g_qeglobals.d_gridsize;
+ point[2] = floor(point[2] / g_qeglobals.d_gridsize + 0.5) * g_qeglobals.d_gridsize;
+ }
+}
+
+
+void CXYWnd::XY_MouseDown (int x, int y, int buttons)
+{
+
+ vec3_t point;
+ vec3_t origin, dir, right, up;
+
+ m_nButtonstate = buttons;
+ m_nPressx = x;
+ m_nPressy = y;
+ VectorCopy (vec3_origin, m_vPressdelta);
+
+ XY_ToPoint (x, y, point);
+
+ VectorCopy (point, origin);
+
+ dir[0] = 0; dir[1] = 0; dir[2] = 0;
+ if (m_nViewType == XY)
+ {
+ origin[2] = 8192;
+ dir[2] = -1;
+ right[0] = 1 / m_fScale;
+ right[1] = 0;
+ right[2] = 0;
+ up[0] = 0;
+ up[1] = 1 / m_fScale;
+ up[2] = 0;
+ }
+ else if (m_nViewType == YZ)
+ {
+ origin[0] = 8192;
+ dir[0] = -1;
+ right[1] = 1 / m_fScale;
+ right[2] = 0;
+ right[0] = 0;
+ up[0] = 0;
+ up[2] = 1 / m_fScale;
+ up[1] = 0;
+ }
+ else
+ {
+ origin[1] = 8192;
+ dir[1] = -1;
+ right[0] = 1 / m_fScale;
+ right[2] = 0;
+ right[1] = 0;
+ up[0] = 0;
+ up[2] = 1 / m_fScale;
+ up[1] = 0;
+ }
+
+
+ m_bPress_selection = (selected_brushes.next != &selected_brushes);
+
+ GetCursorPos(&m_ptCursor);
+ //Sys_GetCursorPos (&m_ptCursor.x, &m_ptCursor.y);
+
+ // lbutton = manipulate selection
+ // shift-LBUTTON = select
+ if ( (buttons == MK_LBUTTON)
+ || (buttons == (MK_LBUTTON | MK_SHIFT))
+ || (buttons == (MK_LBUTTON | MK_CONTROL))
+ || (buttons == (MK_LBUTTON | MK_CONTROL | MK_SHIFT)) )
+ {
+ if (g_qeglobals.d_select_mode == sel_addpoint) {
+ XY_ToGridPoint(x, y, point);
+ if (g_qeglobals.selectObject) {
+ g_qeglobals.selectObject->addPoint(point[0], point[1], point[2]);
+ }
+ return;
+ }
+ Patch_SetView( (m_nViewType == XY) ? W_XY : (m_nViewType == YZ) ? W_YZ : W_XZ);
+ Drag_Begin (x, y, buttons, right, up, origin, dir);
+ return;
+ }
+
+ int nMouseButton = g_PrefsDlg.m_nMouseButtons == 2 ? MK_RBUTTON : MK_MBUTTON;
+
+ // control mbutton = move camera
+ if (m_nButtonstate == (MK_CONTROL|nMouseButton) )
+ {
+ VectorCopyXY(point, g_pParentWnd->GetCamera()->Camera().origin);
+ Sys_UpdateWindows (W_CAMERA|W_XY_OVERLAY);
+ }
+
+ // mbutton = angle camera
+ if ((g_PrefsDlg.m_nMouseButtons == 3 && m_nButtonstate == MK_MBUTTON) ||
+ (g_PrefsDlg.m_nMouseButtons == 2 && m_nButtonstate == (MK_SHIFT|MK_CONTROL|MK_RBUTTON)))
+ {
+ VectorSubtract (point, g_pParentWnd->GetCamera()->Camera().origin, point);
+
+ int n1 = (m_nViewType == XY) ? 1 : 2;
+ int n2 = (m_nViewType == YZ) ? 1 : 0;
+ int nAngle = (m_nViewType == XY) ? YAW : PITCH;
+ if (point[n1] || point[n2])
+ {
+ g_pParentWnd->GetCamera()->Camera().angles[nAngle] = 180/Q_PI*atan2 (point[n1], point[n2]);
+ Sys_UpdateWindows (W_CAMERA_IFON|W_XY_OVERLAY);
+ }
+ }
+
+ // shift mbutton = move z checker
+ if (m_nButtonstate == (MK_SHIFT | nMouseButton))
+ {
+ if (RotateMode() || g_bPatchBendMode)
+ {
+ SnapToPoint (x, y, point);
+ VectorCopyXY(point, g_vRotateOrigin);
+ if (g_bPatchBendMode)
+ {
+ VectorCopy(point, g_vBendOrigin);
+ }
+ Sys_UpdateWindows (W_XY);
+ return;
+ }
+ else
+ {
+ SnapToPoint (x, y, point);
+ if (m_nViewType == XY)
+ {
+ z.origin[0] = point[0];
+ z.origin[1] = point[1];
+ }
+ else if (m_nViewType == YZ)
+ {
+ z.origin[0] = point[1];
+ z.origin[1] = point[2];
+ }
+ else
+ {
+ z.origin[0] = point[0];
+ z.origin[1] = point[2];
+ }
+ Sys_UpdateWindows (W_XY_OVERLAY|W_Z);
+ return;
+ }
+ }
+}
+
+
+void CXYWnd::XY_MouseUp(int x, int y, int buttons)
+{
+ Drag_MouseUp (buttons);
+ if (!m_bPress_selection)
+ Sys_UpdateWindows (W_ALL);
+ m_nButtonstate = 0;
+ while (::ShowCursor(TRUE) < 0)
+ ;
+}
+
+qboolean CXYWnd::DragDelta (int x, int y, vec3_t move)
+{
+ vec3_t xvec, yvec, delta;
+ int i;
+
+ xvec[0] = 1 / m_fScale;
+ xvec[1] = xvec[2] = 0;
+ yvec[1] = 1 / m_fScale;
+ yvec[0] = yvec[2] = 0;
+
+ for (i=0 ; i<3 ; i++)
+ {
+ delta[i] = xvec[i] * (x - m_nPressx) + yvec[i] * (y - m_nPressy);
+ if (!g_PrefsDlg.m_bNoClamp)
+ {
+ delta[i] = floor(delta[i] / g_qeglobals.d_gridsize + 0.5) * g_qeglobals.d_gridsize;
+ }
+ }
+ VectorSubtract (delta, m_vPressdelta, move);
+ VectorCopy (delta, m_vPressdelta);
+
+ if (move[0] || move[1] || move[2])
+ return true;
+ return false;
+}
+
+
+/*
+==============
+NewBrushDrag
+==============
+*/
+void CXYWnd::NewBrushDrag (int x, int y)
+{
+ vec3_t mins, maxs, junk;
+ int i;
+ float temp;
+ brush_t *n;
+
+ if (!DragDelta (x,y, junk))
+ return;
+
+ // delete the current selection
+ if (selected_brushes.next != &selected_brushes)
+ Brush_Free (selected_brushes.next);
+
+ SnapToPoint (m_nPressx, m_nPressy, mins);
+
+ int nDim = (m_nViewType == XY) ? 2 : (m_nViewType == YZ) ? 0 : 1;
+
+ mins[nDim] = g_qeglobals.d_gridsize * ((int)(g_qeglobals.d_new_brush_bottom_z / g_qeglobals.d_gridsize));
+ SnapToPoint (x, y, maxs);
+ maxs[nDim] = g_qeglobals.d_gridsize * ((int)(g_qeglobals.d_new_brush_top_z / g_qeglobals.d_gridsize));
+ if (maxs[nDim] <= mins[nDim])
+ maxs[nDim] = mins[nDim] + g_qeglobals.d_gridsize;
+
+ for (i=0 ; i<3 ; i++)
+ {
+ if (mins[i] == maxs[i])
+ return; // don't create a degenerate brush
+ if (mins[i] > maxs[i])
+ {
+ temp = mins[i];
+ mins[i] = maxs[i];
+ maxs[i] = temp;
+ }
+ }
+
+ n = Brush_Create (mins, maxs, &g_qeglobals.d_texturewin.texdef);
+ if (!n)
+ return;
+
+ vec3_t vSize;
+ VectorSubtract(maxs, mins, vSize);
+ g_strStatus.Format("Size X:: %.1f Y:: %.1f Z:: %.1f", vSize[0], vSize[1], vSize[2]);
+ g_pParentWnd->SetStatusText(2, g_strStatus);
+
+ Brush_AddToList (n, &selected_brushes);
+
+ Entity_LinkBrush (world_entity, n);
+
+ Brush_Build( n );
+
+ // Sys_UpdateWindows (W_ALL);
+ Sys_UpdateWindows (W_XY| W_CAMERA);
+
+}
+
+/*
+==============
+XY_MouseMoved
+==============
+*/
+void CXYWnd::XY_MouseMoved (int x, int y, int buttons)
+{
+ vec3_t point;
+
+
+ if (!m_nButtonstate)
+ {
+ if (g_bCrossHairs)
+ {
+ ::ShowCursor(FALSE);
+ Sys_UpdateWindows (W_XY | W_XY_OVERLAY);
+ ::ShowCursor(TRUE);
+ }
+ return;
+ }
+
+ // lbutton without selection = drag new brush
+ //if (m_nButtonstate == MK_LBUTTON && !m_bPress_selection && g_qeglobals.d_select_mode != sel_curvepoint && g_qeglobals.d_select_mode != sel_splineedit)
+ if (m_nButtonstate == MK_LBUTTON && !m_bPress_selection && g_qeglobals.d_select_mode == sel_brush)
+ {
+ NewBrushDrag (x, y);
+ return;
+ }
+
+ // lbutton (possibly with control and or shift)
+ // with selection = drag selection
+ if (m_nButtonstate & MK_LBUTTON)
+ {
+ Drag_MouseMoved (x, y, buttons);
+ Sys_UpdateWindows (W_XY_OVERLAY | W_CAMERA_IFON | W_Z);
+ return;
+ }
+
+ int nMouseButton = g_PrefsDlg.m_nMouseButtons == 2 ? MK_RBUTTON : MK_MBUTTON;
+ // control mbutton = move camera
+ if (m_nButtonstate == (MK_CONTROL|nMouseButton) )
+ {
+ SnapToPoint (x, y, point);
+ VectorCopyXY(point, g_pParentWnd->GetCamera()->Camera().origin);
+ Sys_UpdateWindows (W_XY_OVERLAY | W_CAMERA);
+ return;
+ }
+
+ // shift mbutton = move z checker
+ if (m_nButtonstate == (MK_SHIFT|nMouseButton) )
+ {
+ if (RotateMode() || g_bPatchBendMode)
+ {
+ SnapToPoint (x, y, point);
+ VectorCopyXY(point, g_vRotateOrigin);
+ if (g_bPatchBendMode)
+ {
+ VectorCopy(point, g_vBendOrigin);
+ }
+ Sys_UpdateWindows (W_XY);
+ return;
+ }
+ else
+ {
+ SnapToPoint (x, y, point);
+ if (m_nViewType == XY)
+ {
+ z.origin[0] = point[0];
+ z.origin[1] = point[1];
+ }
+ else if (m_nViewType == YZ)
+ {
+ z.origin[0] = point[1];
+ z.origin[1] = point[2];
+ }
+ else
+ {
+ z.origin[0] = point[0];
+ z.origin[1] = point[2];
+ }
+ }
+ Sys_UpdateWindows (W_XY_OVERLAY|W_Z);
+ return;
+ }
+
+ // mbutton = angle camera
+ if ((g_PrefsDlg.m_nMouseButtons == 3 && m_nButtonstate == MK_MBUTTON) ||
+ (g_PrefsDlg.m_nMouseButtons == 2 && m_nButtonstate == (MK_SHIFT|MK_CONTROL|MK_RBUTTON)))
+ {
+ SnapToPoint (x, y, point);
+ VectorSubtract (point, g_pParentWnd->GetCamera()->Camera().origin, point);
+
+ int n1 = (m_nViewType == XY) ? 1 : 2;
+ int n2 = (m_nViewType == YZ) ? 1 : 0;
+ int nAngle = (m_nViewType == XY) ? YAW : PITCH;
+ if (point[n1] || point[n2])
+ {
+ g_pParentWnd->GetCamera()->Camera().angles[nAngle] = 180/Q_PI*atan2 (point[n1], point[n2]);
+ Sys_UpdateWindows (W_CAMERA_IFON|W_XY_OVERLAY);
+ }
+ return;
+ }
+
+
+ // rbutton = drag xy origin
+ if (m_nButtonstate == MK_RBUTTON)
+ {
+ Sys_GetCursorPos (&x, &y);
+ if (x != m_ptCursor.x || y != m_ptCursor.y)
+ {
+ int nDim1 = (m_nViewType == YZ) ? 1 : 0;
+ int nDim2 = (m_nViewType == XY) ? 1 : 2;
+ m_vOrigin[nDim1] -= (x - m_ptCursor.x) / m_fScale;
+ m_vOrigin[nDim2] += (y - m_ptCursor.y) / m_fScale;
+ SetCursorPos (m_ptCursor.x, m_ptCursor.y);
+ ::ShowCursor(FALSE);
+ //XY_Draw();
+ //RedrawWindow(NULL, NULL, RDW_INVALIDATE | RDW_UPDATENOW);
+ Sys_UpdateWindows (W_XY | W_XY_OVERLAY);
+ //::ShowCursor(TRUE);
+ }
+ return;
+ }
+
+}
+
+
+/*
+============================================================================
+
+DRAWING
+
+============================================================================
+*/
+
+
+/*
+==============
+XY_DrawGrid
+==============
+*/
+void CXYWnd::XY_DrawGrid()
+{
+ float x, y, xb, xe, yb, ye;
+ int w, h;
+ char text[32];
+
+ qglDisable(GL_TEXTURE_2D);
+ qglDisable(GL_TEXTURE_1D);
+ qglDisable(GL_DEPTH_TEST);
+ qglDisable(GL_BLEND);
+
+ w = m_nWidth / 2 / m_fScale;
+ h = m_nHeight / 2 / m_fScale;
+
+
+ int nDim1 = (m_nViewType == YZ) ? 1 : 0;
+ int nDim2 = (m_nViewType == XY) ? 1 : 2;
+ //int nDim1 = 0;
+ //int nDim2 = 1;
+
+
+ xb = m_vOrigin[nDim1] - w;
+ if (xb < region_mins[nDim1])
+ xb = region_mins[nDim1];
+ xb = 64 * floor (xb/64);
+
+ xe = m_vOrigin[nDim1] + w;
+ if (xe > region_maxs[nDim1])
+ xe = region_maxs[nDim1];
+ xe = 64 * ceil (xe/64);
+
+ yb = m_vOrigin[nDim2] - h;
+ if (yb < region_mins[nDim2])
+ yb = region_mins[nDim2];
+ yb = 64 * floor (yb/64);
+
+ ye = m_vOrigin[nDim2] + h;
+ if (ye > region_maxs[nDim2])
+ ye = region_maxs[nDim2];
+ ye = 64 * ceil (ye/64);
+
+ // draw major blocks
+
+ qglColor3fv(g_qeglobals.d_savedinfo.colors[COLOR_GRIDMAJOR]);
+
+ int stepSize = 64 * 0.1 / m_fScale;
+ if (stepSize < 64) {
+ stepSize = 64;
+ } else {
+ int i;
+ for (i = 1; i < stepSize; i <<= 1) {
+ }
+ stepSize = i;
+ }
+
+ if ( g_qeglobals.d_showgrid )
+ {
+
+ qglBegin (GL_LINES);
+
+ for (x=xb ; x<=xe ; x+=stepSize)
+ {
+ qglVertex2f (x, yb);
+ qglVertex2f (x, ye);
+ }
+ for (y=yb ; y<=ye ; y+=stepSize)
+ {
+ qglVertex2f (xb, y);
+ qglVertex2f (xe, y);
+ }
+
+ qglEnd ();
+
+ }
+
+ // draw minor blocks
+ if ( m_fScale > .1 && g_qeglobals.d_showgrid && g_qeglobals.d_gridsize * m_fScale >= 4 &&
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDMINOR] != g_qeglobals.d_savedinfo.colors[COLOR_GRIDBACK])
+ {
+ qglColor3fv(g_qeglobals.d_savedinfo.colors[COLOR_GRIDMINOR]);
+
+ qglBegin (GL_LINES);
+ for (x=xb ; x<xe ; x += g_qeglobals.d_gridsize)
+ {
+ if ( ! ((int)x & 63) )
+ continue;
+ qglVertex2f (x, yb);
+ qglVertex2f (x, ye);
+ }
+ for (y=yb ; y<ye ; y+=g_qeglobals.d_gridsize)
+ {
+ if ( ! ((int)y & 63) )
+ continue;
+ qglVertex2f (xb, y);
+ qglVertex2f (xe, y);
+ }
+ qglEnd ();
+ }
+
+ // draw coordinate text if needed
+
+ if ( g_qeglobals.d_savedinfo.show_coordinates)
+ {
+ //glColor4f(0, 0, 0, 0);
+ qglColor3fv(g_qeglobals.d_savedinfo.colors[COLOR_GRIDTEXT]);
+
+ for (x=xb ; x<xe ; x+=stepSize)
+ {
+ qglRasterPos2f (x, m_vOrigin[nDim2] + h - 6 / m_fScale);
+ sprintf (text, "%i",(int)x);
+ qglCallLists (strlen(text), GL_UNSIGNED_BYTE, text);
+ }
+ for (y=yb ; y<ye ; y+=stepSize)
+ {
+ qglRasterPos2f (m_vOrigin[nDim1] - w + 1, y);
+ sprintf (text, "%i",(int)y);
+ qglCallLists (strlen(text), GL_UNSIGNED_BYTE, text);
+ }
+
+
+ if (Active())
+ qglColor3fv(g_qeglobals.d_savedinfo.colors[COLOR_VIEWNAME]);
+
+ qglRasterPos2f ( m_vOrigin[nDim1] - w + 35 / m_fScale, m_vOrigin[nDim2] + h - 20 / m_fScale );
+
+ char cView[20];
+ if (m_nViewType == XY)
+ strcpy(cView, "XY Top");
+ else
+ if (m_nViewType == XZ)
+ strcpy(cView, "XZ Front");
+ else
+ strcpy(cView, "YZ Side");
+
+ qglCallLists (strlen(cView), GL_UNSIGNED_BYTE, cView);
+
+
+ }
+
+
+/*
+ if (true)
+ {
+ qglColor3f(g_qeglobals.d_savedinfo.colors[COLOR_GRIDMINOR]);
+ qglBegin (GL_LINES);
+ qglVertex2f (x, yb);
+ qglVertex2f (x, ye);
+ qglEnd();
+ }
+ */
+
+}
+
+/*
+==============
+XY_DrawBlockGrid
+==============
+*/
+void CXYWnd::XY_DrawBlockGrid()
+{
+ float x, y, xb, xe, yb, ye;
+ int w, h;
+ char text[32];
+
+ qglDisable(GL_TEXTURE_2D);
+ qglDisable(GL_TEXTURE_1D);
+ qglDisable(GL_DEPTH_TEST);
+ qglDisable(GL_BLEND);
+
+ w = m_nWidth / 2 / m_fScale;
+ h = m_nHeight / 2 / m_fScale;
+
+ int nDim1 = (m_nViewType == YZ) ? 1 : 0;
+ int nDim2 = (m_nViewType == XY) ? 1 : 2;
+
+ xb = m_vOrigin[nDim1] - w;
+ if (xb < region_mins[nDim1])
+ xb = region_mins[nDim1];
+ xb = 1024 * floor (xb/1024);
+
+ xe = m_vOrigin[nDim1] + w;
+ if (xe > region_maxs[nDim1])
+ xe = region_maxs[nDim1];
+ xe = 1024 * ceil (xe/1024);
+
+ yb = m_vOrigin[nDim2] - h;
+ if (yb < region_mins[nDim2])
+ yb = region_mins[nDim2];
+ yb = 1024 * floor (yb/1024);
+
+ ye = m_vOrigin[nDim2] + h;
+ if (ye > region_maxs[nDim2])
+ ye = region_maxs[nDim2];
+ ye = 1024 * ceil (ye/1024);
+
+ // draw major blocks
+
+ qglColor3fv(g_qeglobals.d_savedinfo.colors[COLOR_GRIDBLOCK]);
+ qglLineWidth (2);
+
+ qglBegin (GL_LINES);
+
+ for (x=xb ; x<=xe ; x+=1024)
+ {
+ qglVertex2f (x, yb);
+ qglVertex2f (x, ye);
+ }
+ for (y=yb ; y<=ye ; y+=1024)
+ {
+ qglVertex2f (xb, y);
+ qglVertex2f (xe, y);
+ }
+
+ qglEnd ();
+ qglLineWidth (1);
+
+ // draw coordinate text if needed
+
+ for (x=xb ; x<xe ; x+=1024)
+ for (y=yb ; y<ye ; y+=1024)
+ {
+ qglRasterPos2f (x+512, y+512);
+ sprintf (text, "%i,%i",(int)floor(x/1024), (int)floor(y/1024) );
+ qglCallLists (strlen(text), GL_UNSIGNED_BYTE, text);
+ }
+
+ qglColor4f(0, 0, 0, 0);
+}
+
+void CXYWnd::DrawRotateIcon()
+{
+ float x, y;
+
+ if (m_nViewType == XY)
+ {
+ x = g_vRotateOrigin[0];
+ y = g_vRotateOrigin[1];
+ }
+ else if (m_nViewType == YZ)
+ {
+ x = g_vRotateOrigin[1];
+ y = g_vRotateOrigin[2];
+ }
+ else
+ {
+ x = g_vRotateOrigin[0];
+ y = g_vRotateOrigin[2];
+ }
+
+ qglEnable (GL_BLEND);
+ qglDisable (GL_TEXTURE_2D);
+ qglPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
+ qglDisable (GL_CULL_FACE);
+ qglBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ qglColor4f (0.8, 0.1, 0.9, 0.25);
+
+ qglBegin(GL_QUADS);
+ qglVertex3f (x-4,y-4,0);
+ qglVertex3f (x+4,y-4,0);
+ qglVertex3f (x+4,y+4,0);
+ qglVertex3f (x-4,y+4,0);
+ qglEnd ();
+ qglDisable (GL_BLEND);
+
+ qglColor4f (1.0, 0.2, 1.0, 1);
+ qglBegin(GL_POINTS);
+ qglVertex3f (x,y,0);
+ qglEnd ();
+
+#if 0
+ qglBegin(GL_LINES);
+ qglVertex3f (x-6,y+6,0);
+ qglVertex3f (x+6,y+6,0);
+ qglVertex3f (x-6,y-6,0);
+ qglVertex3f (x+6,y-6,0);
+ qglEnd ();
+#endif
+
+}
+
+void CXYWnd::DrawCameraIcon()
+{
+ float x, y, a;
+
+ if (m_nViewType == XY)
+ {
+ x = g_pParentWnd->GetCamera()->Camera().origin[0];
+ y = g_pParentWnd->GetCamera()->Camera().origin[1];
+ a = g_pParentWnd->GetCamera()->Camera().angles[YAW]/180*Q_PI;
+ }
+ else if (m_nViewType == YZ)
+ {
+ x = g_pParentWnd->GetCamera()->Camera().origin[1];
+ y = g_pParentWnd->GetCamera()->Camera().origin[2];
+ a = g_pParentWnd->GetCamera()->Camera().angles[PITCH]/180*Q_PI;
+ }
+ else
+ {
+ x = g_pParentWnd->GetCamera()->Camera().origin[0];
+ y = g_pParentWnd->GetCamera()->Camera().origin[2];
+ a = g_pParentWnd->GetCamera()->Camera().angles[PITCH]/180*Q_PI;
+ }
+
+ qglColor3f (0.0, 0.0, 1.0);
+ qglBegin(GL_LINE_STRIP);
+ qglVertex3f (x-16,y,0);
+ qglVertex3f (x,y+8,0);
+ qglVertex3f (x+16,y,0);
+ qglVertex3f (x,y-8,0);
+ qglVertex3f (x-16,y,0);
+ qglVertex3f (x+16,y,0);
+ qglEnd ();
+
+ qglBegin(GL_LINE_STRIP);
+ qglVertex3f (x+48*cos(a+Q_PI/4), y+48*sin(a+Q_PI/4), 0);
+ qglVertex3f (x, y, 0);
+ qglVertex3f (x+48*cos(a-Q_PI/4), y+48*sin(a-Q_PI/4), 0);
+ qglEnd ();
+
+#if 0
+ char text[128];
+ qglRasterPos2f (x+64, y+64);
+ sprintf (text, "%f",g_pParentWnd->GetCamera()->Camera().angles[YAW]);
+ qglCallLists (strlen(text), GL_UNSIGNED_BYTE, text);
+#endif
+
+}
+
+void CXYWnd::DrawZIcon (void)
+{
+ if (m_nViewType == XY)
+ {
+ float x = z.origin[0];
+ float y = z.origin[1];
+ qglEnable (GL_BLEND);
+ qglDisable (GL_TEXTURE_2D);
+ qglPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
+ qglDisable (GL_CULL_FACE);
+ qglBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ qglColor4f (0.0, 0.0, 1.0, 0.25);
+ qglBegin(GL_QUADS);
+ qglVertex3f (x-8,y-8,0);
+ qglVertex3f (x+8,y-8,0);
+ qglVertex3f (x+8,y+8,0);
+ qglVertex3f (x-8,y+8,0);
+ qglEnd ();
+ qglDisable (GL_BLEND);
+
+ qglColor4f (0.0, 0.0, 1.0, 1);
+
+ qglBegin(GL_LINE_LOOP);
+ qglVertex3f (x-8,y-8,0);
+ qglVertex3f (x+8,y-8,0);
+ qglVertex3f (x+8,y+8,0);
+ qglVertex3f (x-8,y+8,0);
+ qglEnd ();
+
+ qglBegin(GL_LINE_STRIP);
+ qglVertex3f (x-4,y+4,0);
+ qglVertex3f (x+4,y+4,0);
+ qglVertex3f (x-4,y-4,0);
+ qglVertex3f (x+4,y-4,0);
+ qglEnd ();
+ }
+}
+
+
+/*
+==================
+FilterBrush
+==================
+*/
+BOOL FilterBrush(brush_t *pb)
+{
+ if (!pb->owner)
+ return FALSE; // during construction
+
+ if (pb->hiddenBrush)
+ {
+ return TRUE;
+ }
+
+ if (g_qeglobals.d_savedinfo.exclude & EXCLUDE_CAULK)
+ {
+ // filter out the brush only if all faces are caulk
+ // if not don't hide the whole brush, proceed on a per-face basis (Cam_Draw)
+ //++timo TODO: set this as a preference .. show caulk: hide any brush with caulk // don't draw caulk faces
+ face_t *f;
+ f=pb->brush_faces;
+ while (f)
+ {
+ if (!strstr(f->texdef.name, "caulk"))
+ break;
+ f = f->next;
+ }
+ if (!f)
+ return TRUE;
+
+#if 0
+ if (strstr(pb->brush_faces->texdef.name, "caulk"))
+ return TRUE;
+#endif
+
+ //++timo FIXME: .. same deal here?
+ if (strstr(pb->brush_faces->texdef.name, "donotenter"))
+ return TRUE;
+ }
+
+ if (g_qeglobals.d_savedinfo.exclude & EXCLUDE_HINT)
+ {
+ if (strstr(pb->brush_faces->texdef.name, "hint"))
+ return TRUE;
+ }
+
+ if (g_qeglobals.d_savedinfo.exclude & EXCLUDE_CLIP)
+ {
+ if (strstr(pb->brush_faces->texdef.name, "clip"))
+ return TRUE;
+
+ if (strstr(pb->brush_faces->texdef.name, "skip"))
+ return TRUE;
+
+ //if (!strncmp(pb->brush_faces->texdef.name, "clip", 4))
+ // return TRUE;
+ }
+
+ if (g_qeglobals.d_savedinfo.exclude & EXCLUDE_WATER)
+ {
+ for (face_t* f = pb->brush_faces ; f ; f=f->next)
+ {
+ if (f->texdef.contents & (CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA))
+ return TRUE;
+ }
+ }
+
+ if (g_qeglobals.d_savedinfo.exclude & EXCLUDE_DETAIL)
+ {
+ if (pb->brush_faces->texdef.contents & CONTENTS_DETAIL)
+ return TRUE;
+ }
+
+ if (g_qeglobals.d_savedinfo.exclude & EXCLUDE_CURVES)
+ {
+ if (pb->patchBrush)
+ return TRUE;
+ }
+
+ if( g_qeglobals.d_savedinfo.exclude & EXCLUDE_TERRAIN )
+ {
+ if( pb->terrainBrush )
+ {
+ return TRUE;
+ }
+ }
+
+ if (pb->owner == world_entity)
+ {
+ if (g_qeglobals.d_savedinfo.exclude & EXCLUDE_WORLD)
+ return TRUE;
+ return FALSE;
+ }
+ else
+ {
+ if (g_qeglobals.d_savedinfo.exclude & EXCLUDE_ENT)
+ {
+ return (strncmp(pb->owner->eclass->name, "func_group", 10));
+ }
+ }
+
+ if (g_qeglobals.d_savedinfo.exclude & EXCLUDE_LIGHTS)
+ {
+ return (pb->owner->eclass->nShowFlags & ECLASS_LIGHT);
+ //if (!strncmp(pb->owner->eclass->name, "light", 5))
+ // return TRUE;
+ }
+
+ if (g_qeglobals.d_savedinfo.exclude & EXCLUDE_PATHS)
+ {
+ return (pb->owner->eclass->nShowFlags & ECLASS_PATH);
+ //if (!strncmp(pb->owner->eclass->name, "path", 4))
+ // return TRUE;
+ }
+
+ return FALSE;
+}
+
+/*
+=============================================================
+
+ PATH LINES
+
+=============================================================
+*/
+
+/*
+==================
+DrawPathLines
+
+Draws connections between entities.
+Needs to consider all entities, not just ones on screen,
+because the lines can be visible when neither end is.
+Called for both camera view and xy view.
+==================
+*/
+void DrawPathLines (void)
+{
+ int i, j, k;
+ vec3_t mid, mid1;
+ entity_t *se, *te;
+ brush_t *sb, *tb;
+ char *psz;
+ vec3_t dir, s1, s2;
+ vec_t len, f;
+ int arrows;
+ int num_entities;
+ char *ent_target[MAX_MAP_ENTITIES];
+ entity_t *ent_entity[MAX_MAP_ENTITIES];
+
+ if (g_qeglobals.d_savedinfo.exclude & EXCLUDE_PATHS)
+ return;
+
+ num_entities = 0;
+ for (te = entities.next ; te != &entities && num_entities != MAX_MAP_ENTITIES ; te = te->next)
+ {
+ ent_target[num_entities] = ValueForKey (te, "target");
+ if (ent_target[num_entities][0])
+ {
+ ent_entity[num_entities] = te;
+ num_entities++;
+ }
+ }
+
+ for (se = entities.next ; se != &entities ; se = se->next)
+ {
+ psz = ValueForKey(se, "targetname");
+
+ if (psz == NULL || psz[0] == '\0')
+ continue;
+
+ sb = se->brushes.onext;
+ if (sb == &se->brushes)
+ continue;
+
+ for (k=0 ; k<num_entities ; k++)
+ {
+ if (strcmp (ent_target[k], psz))
+ continue;
+
+ te = ent_entity[k];
+ tb = te->brushes.onext;
+ if (tb == &te->brushes)
+ continue;
+
+ for (i=0 ; i<3 ; i++)
+ mid[i] = (sb->mins[i] + sb->maxs[i])*0.5;
+
+ for (i=0 ; i<3 ; i++)
+ mid1[i] = (tb->mins[i] + tb->maxs[i])*0.5;
+
+ VectorSubtract (mid1, mid, dir);
+ len = VectorNormalize (dir);
+ s1[0] = -dir[1]*8 + dir[0]*8;
+ s2[0] = dir[1]*8 + dir[0]*8;
+ s1[1] = dir[0]*8 + dir[1]*8;
+ s2[1] = -dir[0]*8 + dir[1]*8;
+
+ qglColor3f (se->eclass->color[0], se->eclass->color[1], se->eclass->color[2]);
+
+ qglBegin(GL_LINES);
+ qglVertex3fv(mid);
+ qglVertex3fv(mid1);
+
+ arrows = (int)(len / 256) + 1;
+
+ for (i=0 ; i<arrows ; i++)
+ {
+ f = len * (i + 0.5) / arrows;
+
+ for (j=0 ; j<3 ; j++)
+ mid1[j] = mid[j] + f*dir[j];
+ qglVertex3fv (mid1);
+ qglVertex3f (mid1[0] + s1[0], mid1[1] + s1[1], mid1[2]);
+ qglVertex3fv (mid1);
+ qglVertex3f (mid1[0] + s2[0], mid1[1] + s2[1], mid1[2]);
+ }
+
+ qglEnd();
+ }
+ }
+
+ return;
+}
+
+//=============================================================
+
+// can be greatly simplified but per usual i am in a hurry
+// which is not an excuse, just a fact
+void CXYWnd::PaintSizeInfo(int nDim1, int nDim2, vec3_t vMinBounds, vec3_t vMaxBounds)
+{
+
+ vec3_t vSize;
+ VectorSubtract(vMaxBounds, vMinBounds, vSize);
+
+ qglColor3f(g_qeglobals.d_savedinfo.colors[COLOR_SELBRUSHES][0] * .65,
+ g_qeglobals.d_savedinfo.colors[COLOR_SELBRUSHES][1] * .65,
+ g_qeglobals.d_savedinfo.colors[COLOR_SELBRUSHES][2] * .65);
+
+ if (m_nViewType == XY)
+ {
+ qglBegin (GL_LINES);
+
+ qglVertex3f(vMinBounds[nDim1], vMinBounds[nDim2] - 6.0f / m_fScale, 0.0f);
+ qglVertex3f(vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale, 0.0f);
+
+ qglVertex3f(vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale, 0.0f);
+ qglVertex3f(vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale, 0.0f);
+
+ qglVertex3f(vMaxBounds[nDim1], vMinBounds[nDim2] - 6.0f / m_fScale, 0.0f);
+ qglVertex3f(vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale, 0.0f);
+
+
+ qglVertex3f(vMaxBounds[nDim1] + 6.0f / m_fScale, vMinBounds[nDim2], 0.0f);
+ qglVertex3f(vMaxBounds[nDim1] + 10.0f / m_fScale, vMinBounds[nDim2], 0.0f);
+
+ qglVertex3f(vMaxBounds[nDim1] + 10.0f / m_fScale, vMinBounds[nDim2], 0.0f);
+ qglVertex3f(vMaxBounds[nDim1] + 10.0f / m_fScale, vMaxBounds[nDim2], 0.0f);
+
+ qglVertex3f(vMaxBounds[nDim1] + 6.0f / m_fScale, vMaxBounds[nDim2], 0.0f);
+ qglVertex3f(vMaxBounds[nDim1] + 10.0f / m_fScale, vMaxBounds[nDim2], 0.0f);
+
+ qglEnd();
+
+ qglRasterPos3f (Betwixt(vMinBounds[nDim1], vMaxBounds[nDim1]), vMinBounds[nDim2] - 20.0 / m_fScale, 0.0f);
+ g_strDim.Format(g_pDimStrings[nDim1], vSize[nDim1]);
+ qglCallLists (g_strDim.GetLength(), GL_UNSIGNED_BYTE, g_strDim);
+
+ qglRasterPos3f (vMaxBounds[nDim1] + 16.0 / m_fScale, Betwixt(vMinBounds[nDim2], vMaxBounds[nDim2]), 0.0f);
+ g_strDim.Format(g_pDimStrings[nDim2], vSize[nDim2]);
+ qglCallLists (g_strDim.GetLength(), GL_UNSIGNED_BYTE, g_strDim);
+
+ qglRasterPos3f (vMinBounds[nDim1] + 4, vMaxBounds[nDim2] + 8 / m_fScale, 0.0f);
+ g_strDim.Format(g_pOrgStrings[0], vMinBounds[nDim1], vMaxBounds[nDim2]);
+ qglCallLists (g_strDim.GetLength(), GL_UNSIGNED_BYTE, g_strDim);
+
+ }
+ else
+ if (m_nViewType == XZ)
+ {
+ qglBegin (GL_LINES);
+
+ qglVertex3f(vMinBounds[nDim1], 0, vMinBounds[nDim2] - 6.0f / m_fScale);
+ qglVertex3f(vMinBounds[nDim1], 0, vMinBounds[nDim2] - 10.0f / m_fScale);
+
+ qglVertex3f(vMinBounds[nDim1], 0,vMinBounds[nDim2] - 10.0f / m_fScale);
+ qglVertex3f(vMaxBounds[nDim1], 0,vMinBounds[nDim2] - 10.0f / m_fScale);
+
+ qglVertex3f(vMaxBounds[nDim1], 0,vMinBounds[nDim2] - 6.0f / m_fScale);
+ qglVertex3f(vMaxBounds[nDim1], 0,vMinBounds[nDim2] - 10.0f / m_fScale);
+
+
+ qglVertex3f(vMaxBounds[nDim1] + 6.0f / m_fScale, 0,vMinBounds[nDim2]);
+ qglVertex3f(vMaxBounds[nDim1] + 10.0f / m_fScale, 0,vMinBounds[nDim2]);
+
+ qglVertex3f(vMaxBounds[nDim1] + 10.0f / m_fScale, 0,vMinBounds[nDim2]);
+ qglVertex3f(vMaxBounds[nDim1] + 10.0f / m_fScale, 0,vMaxBounds[nDim2]);
+
+ qglVertex3f(vMaxBounds[nDim1] + 6.0f / m_fScale, 0,vMaxBounds[nDim2]);
+ qglVertex3f(vMaxBounds[nDim1] + 10.0f / m_fScale, 0,vMaxBounds[nDim2]);
+
+ qglEnd();
+
+ qglRasterPos3f (Betwixt(vMinBounds[nDim1], vMaxBounds[nDim1]), 0, vMinBounds[nDim2] - 20.0 / m_fScale);
+ g_strDim.Format(g_pDimStrings[nDim1], vSize[nDim1]);
+ qglCallLists (g_strDim.GetLength(), GL_UNSIGNED_BYTE, g_strDim);
+
+ qglRasterPos3f (vMaxBounds[nDim1] + 16.0 / m_fScale, 0, Betwixt(vMinBounds[nDim2], vMaxBounds[nDim2]));
+ g_strDim.Format(g_pDimStrings[nDim2], vSize[nDim2]);
+ qglCallLists (g_strDim.GetLength(), GL_UNSIGNED_BYTE, g_strDim);
+
+ qglRasterPos3f (vMinBounds[nDim1] + 4, 0, vMaxBounds[nDim2] + 8 / m_fScale);
+ g_strDim.Format(g_pOrgStrings[1], vMinBounds[nDim1], vMaxBounds[nDim2]);
+ qglCallLists (g_strDim.GetLength(), GL_UNSIGNED_BYTE, g_strDim);
+
+ }
+ else
+ {
+ qglBegin (GL_LINES);
+
+ qglVertex3f(0, vMinBounds[nDim1], vMinBounds[nDim2] - 6.0f / m_fScale);
+ qglVertex3f(0, vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale);
+
+ qglVertex3f(0, vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale);
+ qglVertex3f(0, vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale);
+
+ qglVertex3f(0, vMaxBounds[nDim1], vMinBounds[nDim2] - 6.0f / m_fScale);
+ qglVertex3f(0, vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale);
+
+
+ qglVertex3f(0, vMaxBounds[nDim1] + 6.0f / m_fScale, vMinBounds[nDim2]);
+ qglVertex3f(0, vMaxBounds[nDim1] + 10.0f / m_fScale, vMinBounds[nDim2]);
+
+ qglVertex3f(0, vMaxBounds[nDim1] + 10.0f / m_fScale, vMinBounds[nDim2]);
+ qglVertex3f(0, vMaxBounds[nDim1] + 10.0f / m_fScale, vMaxBounds[nDim2]);
+
+ qglVertex3f(0, vMaxBounds[nDim1] + 6.0f / m_fScale, vMaxBounds[nDim2]);
+ qglVertex3f(0, vMaxBounds[nDim1] + 10.0f / m_fScale, vMaxBounds[nDim2]);
+
+ qglEnd();
+
+ qglRasterPos3f (0, Betwixt(vMinBounds[nDim1], vMaxBounds[nDim1]), vMinBounds[nDim2] - 20.0 / m_fScale);
+ g_strDim.Format(g_pDimStrings[nDim1], vSize[nDim1]);
+ qglCallLists (g_strDim.GetLength(), GL_UNSIGNED_BYTE, g_strDim);
+
+ qglRasterPos3f (0, vMaxBounds[nDim1] + 16.0 / m_fScale, Betwixt(vMinBounds[nDim2], vMaxBounds[nDim2]));
+ g_strDim.Format(g_pDimStrings[nDim2], vSize[nDim2]);
+ qglCallLists (g_strDim.GetLength(), GL_UNSIGNED_BYTE, g_strDim);
+
+ qglRasterPos3f (0, vMinBounds[nDim1] + 4.0, vMaxBounds[nDim2] + 8 / m_fScale);
+ g_strDim.Format(g_pOrgStrings[2], vMinBounds[nDim1], vMaxBounds[nDim2]);
+ qglCallLists (g_strDim.GetLength(), GL_UNSIGNED_BYTE, g_strDim);
+
+ }
+}
+
+
+
+/*
+==============
+XY_Draw
+==============
+*/
+long g_lCount = 0;
+long g_lTotal = 0;
+extern void DrawBrushEntityName (brush_t *b);
+
+void CXYWnd::XY_Draw()
+{
+ brush_t *brush;
+ float w, h;
+ entity_t *e;
+ double start, end;
+ double start2, end2;
+ vec3_t mins, maxs;
+ int drawn, culled;
+ int i;
+
+ if (!active_brushes.next)
+ return; // not valid yet
+
+ if (m_bTiming)
+ start = Sys_DoubleTime();
+ //
+ // clear
+ //
+ m_bDirty = false;
+
+ qglViewport(0, 0, m_nWidth, m_nHeight);
+ qglClearColor (g_qeglobals.d_savedinfo.colors[COLOR_GRIDBACK][0],
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDBACK][1],
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDBACK][2],0);
+
+ qglClear(GL_COLOR_BUFFER_BIT);
+
+ //
+ // set up viewpoint
+ //
+ qglMatrixMode(GL_PROJECTION);
+ qglLoadIdentity ();
+
+ w = m_nWidth / 2 / m_fScale;
+ h = m_nHeight / 2/ m_fScale;
+ int nDim1 = (m_nViewType == YZ) ? 1 : 0;
+ int nDim2 = (m_nViewType == XY) ? 1 : 2;
+ mins[0] = m_vOrigin[nDim1] - w;
+ maxs[0] = m_vOrigin[nDim1] + w;
+ mins[1] = m_vOrigin[nDim2] - h;
+ maxs[1] = m_vOrigin[nDim2] + h;
+
+
+ qglOrtho (mins[0], maxs[0], mins[1], maxs[1], -8192, 8192);
+ //glRotatef
+ //
+ // now draw the grid
+ //
+ XY_DrawGrid ();
+
+ //
+ // draw stuff
+ //
+ qglShadeModel (GL_FLAT);
+ qglDisable(GL_TEXTURE_2D);
+ qglDisable(GL_TEXTURE_1D);
+ qglDisable(GL_DEPTH_TEST);
+ qglDisable(GL_BLEND);
+ qglColor3f(0, 0, 0);
+
+ //glEnable (GL_LINE_SMOOTH);
+
+ drawn = culled = 0;
+
+ if (m_nViewType != XY)
+ {
+ qglPushMatrix();
+ if (m_nViewType == YZ)
+ qglRotatef (-90, 0, 1, 0); // put Z going up
+ //else
+ qglRotatef (-90, 1, 0, 0); // put Z going up
+ }
+
+ e = world_entity;
+
+ if (m_bTiming)
+ start2 = Sys_DoubleTime();
+
+ for (brush = active_brushes.next ; brush != &active_brushes ; brush=brush->next)
+ {
+ if (brush->mins[nDim1] > maxs[0] ||
+ brush->mins[nDim2] > maxs[1] ||
+ brush->maxs[nDim1] < mins[0] ||
+ brush->maxs[nDim2] < mins[1])
+ {
+ culled++;
+ continue; // off screen
+ }
+
+ if (FilterBrush (brush))
+ continue;
+
+ drawn++;
+
+ if (brush->owner != e && brush->owner)
+ {
+
+ qglColor3fv(brush->owner->eclass->color);
+ }
+ else
+ {
+ qglColor3fv(g_qeglobals.d_savedinfo.colors[COLOR_BRUSHES]);
+ }
+
+ Brush_DrawXY(brush, m_nViewType);
+ }
+
+
+ if (m_bTiming)
+ end2 = Sys_DoubleTime();
+
+
+ DrawPathLines ();
+
+ //
+ // draw pointfile
+ //
+ if ( g_qeglobals.d_pointfile_display_list)
+ qglCallList (g_qeglobals.d_pointfile_display_list);
+
+
+ if (!(m_nViewType == XY))
+ qglPopMatrix();
+
+ //
+ // draw block grid
+ //
+ if ( g_qeglobals.show_blocks)
+ XY_DrawBlockGrid ();
+
+ //
+ // now draw selected brushes
+ //
+ if (m_nViewType != XY)
+ {
+ qglPushMatrix();
+ if (m_nViewType == YZ)
+ qglRotatef (-90, 0, 1, 0); // put Z going up
+ //else
+ qglRotatef (-90, 1, 0, 0); // put Z going up
+ }
+
+
+ qglPushMatrix();
+ qglTranslatef( g_qeglobals.d_select_translate[0], g_qeglobals.d_select_translate[1], g_qeglobals.d_select_translate[2]);
+
+ if (RotateMode())
+ qglColor3f(0.8, 0.1, 0.9);
+ else
+ if (ScaleMode())
+ qglColor3f(0.1, 0.8, 0.1);
+ else
+ qglColor3fv(g_qeglobals.d_savedinfo.colors[COLOR_SELBRUSHES]);
+
+
+ if (g_PrefsDlg.m_bNoStipple == FALSE)
+ {
+ qglEnable (GL_LINE_STIPPLE);
+ qglLineStipple (3, 0xaaaa);
+ }
+ qglLineWidth (2);
+
+ vec3_t vMinBounds;
+ vec3_t vMaxBounds;
+ vMinBounds[0] = vMinBounds[1] = vMinBounds[2] = 9999.9f;
+ vMaxBounds[0] = vMaxBounds[1] = vMaxBounds[2] = -9999.9f;
+
+ int nSaveDrawn = drawn;
+ bool bFixedSize = false;
+ for (brush = selected_brushes.next ; brush != &selected_brushes ; brush=brush->next)
+ {
+ drawn++;
+ Brush_DrawXY(brush, m_nViewType);
+
+ if (!bFixedSize)
+ {
+ if (brush->owner->eclass->fixedsize)
+ bFixedSize = true;
+ if (g_PrefsDlg.m_bSizePaint)
+ {
+ for (i = 0; i < 3; i ++)
+ {
+ if (brush->mins[i] < vMinBounds[i])
+ vMinBounds[i] = brush->mins[i];
+ if (brush->maxs[i] > vMaxBounds[i])
+ vMaxBounds[i] = brush->maxs[i];
+ }
+ }
+ }
+ }
+
+ if (g_PrefsDlg.m_bNoStipple == FALSE)
+ {
+ qglDisable (GL_LINE_STIPPLE);
+ }
+ qglLineWidth (1);
+
+ if (!bFixedSize && !RotateMode() && !ScaleMode() && drawn - nSaveDrawn > 0 && g_PrefsDlg.m_bSizePaint)
+ PaintSizeInfo(nDim1, nDim2, vMinBounds, vMaxBounds);
+
+
+ // edge / vertex flags
+
+ if (g_qeglobals.d_select_mode == sel_vertex)
+ {
+ qglPointSize (4);
+ qglColor3f (0,1,0);
+ qglBegin (GL_POINTS);
+ for (i=0 ; i<g_qeglobals.d_numpoints ; i++)
+ qglVertex3fv (g_qeglobals.d_points[i]);
+ qglEnd ();
+ qglPointSize (1);
+ }
+ else if (g_qeglobals.d_select_mode == sel_edge)
+ {
+ float *v1, *v2;
+
+ qglPointSize (4);
+ qglColor3f (0,0,1);
+ qglBegin (GL_POINTS);
+ for (i=0 ; i<g_qeglobals.d_numedges ; i++)
+ {
+ v1 = g_qeglobals.d_points[g_qeglobals.d_edges[i].p1];
+ v2 = g_qeglobals.d_points[g_qeglobals.d_edges[i].p2];
+ qglVertex3f ( (v1[0]+v2[0])*0.5,(v1[1]+v2[1])*0.5,(v1[2]+v2[2])*0.5);
+ }
+ qglEnd ();
+ qglPointSize (1);
+ }
+
+
+ g_splineList->draw(static_cast<qboolean>(g_qeglobals.d_select_mode == sel_editpoint || g_qeglobals.d_select_mode == sel_addpoint));
+
+ qglPopMatrix();
+
+ qglTranslatef (-g_qeglobals.d_select_translate[0], -g_qeglobals.d_select_translate[1], -g_qeglobals.d_select_translate[2]);
+
+
+ if (!(m_nViewType == XY))
+ qglPopMatrix();
+
+ // area selection hack
+ if (g_qeglobals.d_select_mode == sel_area)
+ {
+ qglEnable (GL_BLEND);
+ qglBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ qglColor4f(0.0, 0.0, 1.0, 0.25);
+ qglRectf(g_qeglobals.d_vAreaTL[nDim1], g_qeglobals.d_vAreaTL[nDim2], g_qeglobals.d_vAreaBR[nDim1], g_qeglobals.d_vAreaBR[nDim2]);
+ qglDisable (GL_BLEND);
+ }
+
+
+ //
+ // now draw camera point
+ //
+ DrawCameraIcon ();
+ DrawZIcon ();
+
+ if (RotateMode())
+ {
+ DrawRotateIcon();
+ }
+
+ // plugin entities
+ //++timo TODO: use an object for the 2D view
+ DrawPluginEntities( (VIEWTYPE)m_nViewType );
+
+ qglFinish();
+ //QE_CheckOpenGLForErrors();
+
+ if (m_bTiming)
+ {
+ end = Sys_DoubleTime ();
+ i = (int)(1000*(end-start));
+ int i3 = (int)(1000*(end2-start2));
+ g_lCount++;
+ g_lTotal += i;
+ int i2 = g_lTotal / g_lCount;
+ Sys_Printf ("xy: %i ab: %i avg: %i\n", i, i3, i2);
+ }
+}
+
+/*
+==============
+XY_Overlay
+==============
+*/
+void CXYWnd::XY_Overlay()
+{
+ int w, h;
+ int r[4];
+ static vec3_t lastz;
+ static vec3_t lastcamera;
+
+
+ qglViewport(0, 0, m_nWidth, m_nHeight);
+
+ //
+ // set up viewpoint
+ //
+ qglMatrixMode(GL_PROJECTION);
+ qglLoadIdentity ();
+
+ w = m_nWidth / 2 / m_fScale;
+ h = m_nHeight / 2 / m_fScale;
+
+ qglOrtho (m_vOrigin[0] - w, m_vOrigin[0] + w , m_vOrigin[1] - h, m_vOrigin[1] + h, -8000, 8000);
+ //
+ // erase the old camera and z checker positions
+ // if the entire xy hasn't been redrawn
+ //
+ if (m_bDirty)
+ {
+ qglReadBuffer (GL_BACK);
+ qglDrawBuffer (GL_FRONT);
+
+ qglRasterPos2f (lastz[0]-9, lastz[1]-9);
+ qglGetIntegerv (GL_CURRENT_RASTER_POSITION,r);
+ qglCopyPixels(r[0], r[1], 18,18, GL_COLOR);
+
+ qglRasterPos2f (lastcamera[0]-50, lastcamera[1]-50);
+ qglGetIntegerv (GL_CURRENT_RASTER_POSITION,r);
+ qglCopyPixels(r[0], r[1], 100,100, GL_COLOR);
+ }
+ m_bDirty = true;
+
+ //
+ // save off underneath where we are about to draw
+ //
+ VectorCopy (z.origin, lastz);
+ VectorCopy (g_pParentWnd->GetCamera()->Camera().origin, lastcamera);
+
+ qglReadBuffer (GL_FRONT);
+ qglDrawBuffer (GL_BACK);
+
+ qglRasterPos2f (lastz[0]-9, lastz[1]-9);
+ qglGetIntegerv (GL_CURRENT_RASTER_POSITION,r);
+ qglCopyPixels(r[0], r[1], 18,18, GL_COLOR);
+
+ qglRasterPos2f (lastcamera[0]-50, lastcamera[1]-50);
+ qglGetIntegerv (GL_CURRENT_RASTER_POSITION,r);
+ qglCopyPixels(r[0], r[1], 100,100, GL_COLOR);
+
+ //
+ // draw the new icons
+ //
+ qglDrawBuffer (GL_FRONT);
+
+ qglShadeModel (GL_FLAT);
+ qglDisable(GL_TEXTURE_2D);
+ qglDisable(GL_TEXTURE_1D);
+ qglDisable(GL_DEPTH_TEST);
+ qglDisable(GL_BLEND);
+ qglColor3f(0, 0, 0);
+
+ DrawCameraIcon ();
+ DrawZIcon ();
+
+ qglDrawBuffer (GL_BACK);
+ qglFinish();
+}
+
+
+vec3_t& CXYWnd::GetOrigin()
+{
+ return m_vOrigin;
+}
+
+void CXYWnd::SetOrigin(vec3_t org)
+{
+ m_vOrigin[0] = org[0];
+ m_vOrigin[1] = org[1];
+ m_vOrigin[2] = org[2];
+}
+
+void CXYWnd::OnSize(UINT nType, int cx, int cy)
+{
+ CWnd::OnSize(nType, cx, cy);
+ CRect rect;
+ GetClientRect(rect);
+ m_nWidth = rect.Width();
+ m_nHeight = rect.Height();
+}
+
+brush_t hold_brushes;
+void CXYWnd::Clip()
+{
+ if (ClipMode())
+ {
+ hold_brushes.next = &hold_brushes;
+ ProduceSplitLists();
+ //brush_t* pList = (g_bSwitch) ? &g_brFrontSplits : &g_brBackSplits;
+ brush_t* pList;
+ if (g_PrefsDlg.m_bSwitchClip)
+ pList = ( (m_nViewType == XZ) ? g_bSwitch: !g_bSwitch) ? &g_brFrontSplits : &g_brBackSplits;
+ else
+ pList = ( (m_nViewType == XZ) ? !g_bSwitch: g_bSwitch) ? &g_brFrontSplits : &g_brBackSplits;
+
+
+ if (pList->next != pList)
+ {
+ Brush_CopyList(pList, &hold_brushes);
+ CleanList(&g_brFrontSplits);
+ CleanList(&g_brBackSplits);
+ Select_Delete();
+ Brush_CopyList(&hold_brushes, &selected_brushes);
+ if (RogueClipMode())
+ RetainClipMode(false);
+ else
+ RetainClipMode(true);
+ Sys_UpdateWindows(W_ALL);
+ }
+ }
+ else if (PathMode())
+ {
+ FinishSmartCreation();
+ if (g_pPathFunc)
+ g_pPathFunc(true, g_nPathCount);
+ g_pPathFunc = NULL;
+ g_nPathCount = 0;
+ g_bPathMode = false;
+ }
+}
+
+void CXYWnd::SplitClip()
+{
+ ProduceSplitLists();
+ if ((g_brFrontSplits.next != &g_brFrontSplits) &&
+ (g_brBackSplits.next != &g_brBackSplits))
+ {
+ Select_Delete();
+ Brush_CopyList(&g_brFrontSplits, &selected_brushes);
+ Brush_CopyList(&g_brBackSplits, &selected_brushes);
+ CleanList(&g_brFrontSplits);
+ CleanList(&g_brBackSplits);
+ if (RogueClipMode())
+ RetainClipMode(false);
+ else
+ RetainClipMode(true);
+ }
+}
+
+void CXYWnd::FlipClip()
+{
+ g_bSwitch = !g_bSwitch;
+ Sys_UpdateWindows(XY | W_CAMERA_IFON);
+}
+
+
+// makes sure the selected brush or camera is in view
+void CXYWnd::PositionView()
+{
+ int nDim1 = (m_nViewType == YZ) ? 1 : 0;
+ int nDim2 = (m_nViewType == XY) ? 1 : 2;
+ brush_t* b = selected_brushes.next;
+ if (b && b->next != b)
+ {
+ m_vOrigin[nDim1] = b->mins[nDim1];
+ m_vOrigin[nDim2] = b->mins[nDim2];
+ }
+ else
+ {
+ m_vOrigin[nDim1] = g_pParentWnd->GetCamera()->Camera().origin[nDim1];
+ m_vOrigin[nDim2] = g_pParentWnd->GetCamera()->Camera().origin[nDim2];
+ }
+}
+
+void CXYWnd::VectorCopyXY(vec3_t in, vec3_t out)
+{
+ if (m_nViewType == XY)
+ {
+ out[0] = in[0];
+ out[1] = in[1];
+ }
+ else
+ if (m_nViewType == XZ)
+ {
+ out[0] = in[0];
+ out[2] = in[2];
+ }
+ else
+ {
+ out[1] = in[1];
+ out[2] = in[2];
+ }
+}
+
+
+void CXYWnd::OnDestroy()
+{
+ QEW_StopGL( GetSafeHwnd(), s_hglrcXY, s_hdcXY );
+ CWnd::OnDestroy();
+ // delete this;
+}
+
+void CXYWnd::SetViewType(int n)
+{
+ m_nViewType = n;
+ if (g_pParentWnd->CurrentStyle() == QR_QE4)
+ {
+ CString str = "YZ Side";
+ if (m_nViewType == XY)
+ str = "XY Top";
+ else if (m_nViewType == XZ)
+ str = "XZ Front";
+ SetWindowText(str);
+ }
+};
+
+void CXYWnd::Redraw(unsigned int nBits)
+{
+ m_nUpdateBits = nBits;
+ RedrawWindow(NULL, NULL, RDW_INVALIDATE | RDW_UPDATENOW);
+ m_nUpdateBits = W_XY;
+}
+
+bool CXYWnd::RotateMode()
+{
+ return g_bRotateMode;
+}
+
+bool CXYWnd::ScaleMode()
+{
+ return g_bScaleMode;
+}
+
+bool CXYWnd::SetRotateMode(bool bMode)
+{
+ if (bMode && selected_brushes.next != &selected_brushes)
+ {
+ g_bRotateMode = true;
+ Select_GetTrueMid(g_vRotateOrigin);
+ g_vRotation[0] = g_vRotation[1] = g_vRotation[2] = 0.0;
+ }
+ else
+ {
+ if (bMode)
+ Sys_Printf("Need a brush selected to turn on Mouse Rotation mode\n");
+ g_bRotateMode = false;
+ }
+ RedrawWindow();
+ return g_bRotateMode;
+}
+
+void CXYWnd::SetScaleMode(bool bMode)
+{
+ g_bScaleMode = bMode;
+ RedrawWindow();
+}
+
+
+
+
+// xy - z
+// xz - y
+// yz - x
+
+void CXYWnd::OnSelectMouserotate()
+{
+ // TODO: Add your command handler code here
+
+}
+
+void CleanCopyEntities()
+{
+ entity_t* pe = g_enClipboard.next;
+ while (pe != NULL && pe != &g_enClipboard)
+ {
+ entity_t* next = pe->next;
+ epair_t* enext = NULL;
+ for (epair_t* ep = pe->epairs ; ep ; ep=enext)
+ {
+ enext = ep->next;
+ free (ep->key);
+ free (ep->value);
+ free (ep);
+ }
+ free (pe);
+ pe = next;
+ }
+ g_enClipboard.next = g_enClipboard.prev = &g_enClipboard;
+}
+
+entity_t *Entity_CopyClone (entity_t *e)
+{
+ entity_t *n;
+ epair_t *ep, *np;
+
+ n = (entity_t*)qmalloc(sizeof(*n));
+ n->brushes.onext = n->brushes.oprev = &n->brushes;
+ n->eclass = e->eclass;
+
+ // add the entity to the entity list
+ n->next = g_enClipboard.next;
+ g_enClipboard.next = n;
+ n->next->prev = n;
+ n->prev = &g_enClipboard;
+
+ for (ep = e->epairs ; ep ; ep=ep->next)
+ {
+ np = (epair_t*)qmalloc(sizeof(*np));
+ np->key = copystring(ep->key);
+ np->value = copystring(ep->value);
+ np->next = n->epairs;
+ n->epairs = np;
+ }
+ return n;
+}
+
+bool OnList(entity_t* pFind, CPtrArray* pList)
+{
+ int nSize = pList->GetSize();
+ while (nSize-- > 0)
+ {
+ entity_t* pEntity = reinterpret_cast<entity_t*>(pList->GetAt(nSize));
+ if (pEntity == pFind)
+ return true;
+ }
+ return false;
+}
+
+void CXYWnd::Copy()
+{
+#if 1
+ CWaitCursor WaitCursor;
+ g_Clipboard.SetLength(0);
+ g_PatchClipboard.SetLength(0);
+
+ Map_SaveSelected(&g_Clipboard, &g_PatchClipboard);
+ bool bClipped = false;
+ UINT nClipboard = ::RegisterClipboardFormat("RadiantClippings");
+ if (nClipboard > 0)
+ {
+ if (OpenClipboard())
+ {
+ ::EmptyClipboard();
+ long lSize = g_Clipboard.GetLength();
+ HANDLE h = ::GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE | GMEM_DDESHARE, lSize + sizeof(long));
+ if (h != NULL)
+ {
+ unsigned char *cp = reinterpret_cast<unsigned char*>(::GlobalLock(h));
+ memcpy(cp, &lSize, sizeof(long));
+ cp += sizeof(long);
+ g_Clipboard.SeekToBegin();
+ g_Clipboard.Read(cp, lSize);
+ ::GlobalUnlock(h);
+ ::SetClipboardData(nClipboard, h);
+ ::CloseClipboard();
+ bClipped = true;
+ }
+ }
+ }
+
+ if (!bClipped)
+ {
+ Sys_Printf("Unable to register Windows clipboard formats, copy/paste between editors will not be possible");
+ }
+
+/*
+ CString strOut;
+ ::GetTempPath(1024, strOut.GetBuffer(1024));
+ strOut.ReleaseBuffer();
+ AddSlash(strOut);
+ strOut += "RadiantClipboard.$$$";
+ Map_SaveSelected(strOut.GetBuffer(0));
+*/
+
+#else
+ CPtrArray holdArray;
+ CleanList(&g_brClipboard);
+ CleanCopyEntities();
+ for (brush_t* pBrush = selected_brushes.next ; pBrush != NULL && pBrush != &selected_brushes ; pBrush=pBrush->next)
+ {
+ if (pBrush->owner == world_entity)
+ {
+ brush_t* pClone = Brush_Clone(pBrush);
+ pClone->owner = NULL;
+ Brush_AddToList (pClone, &g_brClipboard);
+ }
+ else
+ {
+ if (!OnList(pBrush->owner, &holdArray))
+ {
+ entity_t* e = pBrush->owner;
+ holdArray.Add(reinterpret_cast<void*>(e));
+ entity_t* pEClone = Entity_CopyClone(e);
+ for (brush_t* pEB = e->brushes.onext ; pEB != &e->brushes ; pEB=pEB->onext)
+ {
+ brush_t* pClone = Brush_Clone(pEB);
+ //Brush_AddToList (pClone, &g_brClipboard);
+ Entity_LinkBrush(pEClone, pClone);
+ Brush_Build(pClone);
+ }
+ }
+ }
+ }
+#endif
+}
+
+void CXYWnd::Undo()
+{
+/*
+ if (g_brUndo.next != &g_brUndo)
+ {
+ g_bScreenUpdates = false;
+ Select_Delete();
+ for (brush_t* pBrush = g_brUndo.next ; pBrush != NULL && pBrush != &g_brUndo ; pBrush=pBrush->next)
+ {
+ brush_t* pClone = Brush_Clone(pBrush);
+ Brush_AddToList (pClone, &active_brushes);
+ Entity_LinkBrush (pBrush->pUndoOwner, pClone);
+ Brush_Build(pClone);
+ Select_Brush(pClone);
+ }
+ CleanList(&g_brUndo);
+ g_bScreenUpdates = true;
+ Sys_UpdateWindows(W_ALL);
+ }
+ else Sys_Printf("Nothing to undo.../n");
+*/
+}
+
+void CXYWnd::UndoClear()
+{
+/*
+ CleanList(&g_brUndo);
+*/
+}
+
+void CXYWnd::UndoCopy()
+{
+/*
+ CleanList(&g_brUndo);
+ for (brush_t* pBrush = selected_brushes.next ; pBrush != NULL && pBrush != &selected_brushes ; pBrush=pBrush->next)
+ {
+ brush_t* pClone = Brush_Clone(pBrush);
+ pClone->pUndoOwner = pBrush->owner;
+ Brush_AddToList (pClone, &g_brUndo);
+ }
+*/
+}
+
+bool CXYWnd::UndoAvailable()
+{
+ return (g_brUndo.next != &g_brUndo);
+}
+
+
+
+void CXYWnd::Paste()
+{
+#if 1
+
+ CWaitCursor WaitCursor;
+ bool bPasted = false;
+ UINT nClipboard = ::RegisterClipboardFormat("RadiantClippings");
+ if (nClipboard > 0 && OpenClipboard() && ::IsClipboardFormatAvailable(nClipboard))
+ {
+ HANDLE h = ::GetClipboardData(nClipboard);
+ if (h)
+ {
+ g_Clipboard.SetLength(0);
+ unsigned char *cp = reinterpret_cast<unsigned char*>(::GlobalLock(h));
+ long lSize = 0;
+ memcpy(&lSize, cp, sizeof(long));
+ cp += sizeof(long);
+ g_Clipboard.Write(cp, lSize);
+ }
+ ::GlobalUnlock(h);
+ ::CloseClipboard();
+ }
+
+ if (g_Clipboard.GetLength() > 0)
+ {
+ g_Clipboard.SeekToBegin();
+ int nLen = g_Clipboard.GetLength();
+ char* pBuffer = new char[nLen+1];
+ memset( pBuffer, 0, sizeof(pBuffer) );
+ g_Clipboard.Read(pBuffer, nLen);
+ pBuffer[nLen] = '\0';
+ Map_ImportBuffer(pBuffer);
+ delete []pBuffer;
+ }
+
+#if 0
+ if (g_PatchClipboard.GetLength() > 0)
+ {
+ g_PatchClipboard.SeekToBegin();
+ int nLen = g_PatchClipboard.GetLength();
+ char* pBuffer = new char[nLen+1];
+ g_PatchClipboard.Read(pBuffer, nLen);
+ pBuffer[nLen] = '\0';
+ Patch_ReadBuffer(pBuffer, true);
+ delete []pBuffer;
+ }
+#endif
+
+#else
+ if (g_brClipboard.next != &g_brClipboard || g_enClipboard.next != &g_enClipboard)
+ {
+ Select_Deselect();
+
+ for (brush_t* pBrush = g_brClipboard.next ; pBrush != NULL && pBrush != &g_brClipboard ; pBrush=pBrush->next)
+ {
+ brush_t* pClone = Brush_Clone(pBrush);
+ //pClone->owner = pBrush->owner;
+ if (pClone->owner == NULL)
+ Entity_LinkBrush (world_entity, pClone);
+
+ Brush_AddToList (pClone, &selected_brushes);
+ Brush_Build(pClone);
+ }
+
+ for (entity_t* pEntity = g_enClipboard.next; pEntity != NULL && pEntity != &g_enClipboard; pEntity = pEntity->next)
+ {
+ entity_t* pEClone = Entity_Clone(pEntity);
+ for (brush_t* pEB = pEntity->brushes.onext ; pEB != &pEntity->brushes ; pEB=pEB->onext)
+ {
+ brush_t* pClone = Brush_Clone(pEB);
+ Brush_AddToList (pClone, &selected_brushes);
+ Entity_LinkBrush(pEClone, pClone);
+ Brush_Build(pClone);
+ if (pClone->owner && pClone->owner != world_entity)
+ {
+ UpdateEntitySel(pClone->owner->eclass);
+ }
+ }
+ }
+
+ Sys_UpdateWindows(W_ALL);
+ }
+ else Sys_Printf("Nothing to paste.../n");
+#endif
+}
+
+
+vec3_t& CXYWnd::Rotation()
+{
+ return g_vRotation;
+}
+
+vec3_t& CXYWnd::RotateOrigin()
+{
+ return g_vRotateOrigin;
+}
+
+
+void CXYWnd::OnTimer(UINT nIDEvent)
+{
+ int nDim1 = (m_nViewType == YZ) ? 1 : 0;
+ int nDim2 = (m_nViewType == XY) ? 1 : 2;
+ m_vOrigin[nDim1] += m_ptDragAdj.x / m_fScale;
+ m_vOrigin[nDim2] -= m_ptDragAdj.y / m_fScale;
+ Sys_UpdateWindows(W_XY | W_CAMERA);
+ //int nH = (m_ptDrag.y == 0) ? -1 : m_ptDrag.y;
+ m_ptDrag += m_ptDragAdj;
+ m_ptDragTotal += m_ptDragAdj;
+ XY_MouseMoved (m_ptDrag.x, m_nHeight - 1 - m_ptDrag.y , m_nScrollFlags);
+ //m_vOrigin[nDim1] -= m_ptDrag.x / m_fScale;
+ //m_vOrigin[nDim1] -= m_ptDrag.x / m_fScale;
+}
+
+void CXYWnd::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags)
+{
+ g_pParentWnd->HandleKey(nChar, nRepCnt, nFlags, false);
+ //CWnd::OnKeyUp(nChar, nRepCnt, nFlags);
+}
+
+void CXYWnd::OnNcCalcSize(BOOL bCalcValidRects, NCCALCSIZE_PARAMS FAR* lpncsp)
+{
+ CWnd::OnNcCalcSize(bCalcValidRects, lpncsp);
+}
+
+void CXYWnd::OnKillFocus(CWnd* pNewWnd)
+{
+ CWnd::OnKillFocus(pNewWnd);
+ SendMessage(WM_NCACTIVATE, FALSE , 0 );
+}
+
+void CXYWnd::OnSetFocus(CWnd* pOldWnd)
+{
+ CWnd::OnSetFocus(pOldWnd);
+ SendMessage(WM_NCACTIVATE, TRUE , 0 );
+}
+
+void CXYWnd::OnClose()
+{
+ CWnd::OnClose();
+}
+
+// should be static as should be the rotate scale stuff
+bool CXYWnd::AreaSelectOK()
+{
+ return RotateMode() ? false : ScaleMode() ? false : true;
+} \ No newline at end of file
diff --git a/q3radiant/XYWnd.h b/q3radiant/XYWnd.h
new file mode 100755
index 0000000..8806fe8
--- /dev/null
+++ b/q3radiant/XYWnd.h
@@ -0,0 +1,219 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_XYWND_H__44B4BA04_781B_11D1_B53C_00AA00A410FC__INCLUDED_)
+#define AFX_XYWND_H__44B4BA04_781B_11D1_B53C_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// XYWnd.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CXYWnd window
+
+#include "qe3.h"
+#include "CamWnd.h"
+
+const int SCALE_X = 0x01;
+const int SCALE_Y = 0x02;
+const int SCALE_Z = 0x04;
+
+
+typedef void (PFNPathCallback)(bool, int);
+// as i didn't really encapsulate anything this
+// should really be a struct..
+class CClipPoint
+{
+public:
+ CClipPoint(){ Reset(); };
+ void Reset(){ m_ptClip[0] = m_ptClip[1] = m_ptClip[2] = 0.0; m_bSet = false; m_pVec3 = NULL;};
+ bool Set(){ return m_bSet; };
+ void Set(bool b) { m_bSet = b; };
+ void UpdatePointPtr() { if (m_pVec3) VectorCopy(m_ptClip, *m_pVec3); };
+ void SetPointPtr(vec3_t* p) { m_pVec3 = p; };
+ vec3_t m_ptClip; // the 3d point
+ vec3_t* m_pVec3; // optional ptr for 3rd party updates
+ CPoint m_ptScreen; // the onscreen xy point (for mousability)
+ bool m_bSet;
+ operator vec3_t&() {return m_ptClip;};
+ operator vec3_t*() {return &m_ptClip;};
+};
+
+class CXYWnd : public CWnd
+{
+ DECLARE_DYNCREATE(CXYWnd);
+// Construction
+public:
+ CXYWnd();
+
+// Attributes
+public:
+
+// Operations
+public:
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CXYWnd)
+ protected:
+ virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
+ //}}AFX_VIRTUAL
+
+// Implementation
+public:
+ bool AreaSelectOK();
+ vec3_t& RotateOrigin();
+ vec3_t& Rotation();
+ void UndoClear();
+ bool UndoAvailable();
+ void KillPathMode();
+ void Undo();
+ void UndoCopy();
+ void Copy();
+ void Paste();
+ void Redraw(unsigned int nBits);
+ void VectorCopyXY(vec3_t in, vec3_t out);
+ void PositionView();
+ void FlipClip();
+ void SplitClip();
+ void Clip();
+ vec3_t& GetOrigin();
+ void SetOrigin(vec3_t org); // PGM
+ void XY_Init();
+ void XY_Overlay();
+ void XY_Draw();
+ void DrawZIcon();
+ void DrawRotateIcon();
+ void DrawCameraIcon();
+ void XY_DrawBlockGrid();
+ void XY_DrawGrid();
+ void XY_MouseMoved (int x, int y, int buttons);
+ void NewBrushDrag (int x, int y);
+ qboolean DragDelta (int x, int y, vec3_t move);
+ void XY_MouseUp(int x, int y, int buttons);
+ void XY_MouseDown (int x, int y, int buttons);
+ void XY_ToGridPoint (int x, int y, vec3_t point);
+ void XY_ToPoint (int x, int y, vec3_t point);
+ void SnapToPoint (int x, int y, vec3_t point);
+ void SetActive(bool b) {m_bActive = b;};
+ bool Active() {return m_bActive;};
+ void DropClipPoint(UINT nFlags, CPoint point);
+
+ bool RogueClipMode();
+ bool ClipMode();
+ void SetClipMode(bool bMode);
+ void RetainClipMode(bool bMode);
+
+ bool RotateMode();
+ bool SetRotateMode(bool bMode);
+ bool ScaleMode();
+ void SetScaleMode(bool bMode);
+
+ bool PathMode();
+ void DropPathPoint(UINT nFlags, CPoint point);
+
+ bool PointMode();
+ void AddPointPoint(UINT nFlags, vec3_t* pVec);
+ void SetPointMode(bool b);
+
+
+ virtual ~CXYWnd();
+ void SetViewType(int n);
+ int GetViewType() {return m_nViewType; };
+ void SetScale(float f) {m_fScale = f;};
+ float Scale() {return m_fScale;};
+ int Width() {return m_nWidth;}
+ int Height() {return m_nHeight;}
+ bool m_bActive;
+
+ // Generated message map functions
+protected:
+ int m_nUpdateBits;
+ int m_nWidth;
+ int m_nHeight;
+ bool m_bTiming;
+ float m_fScale;
+ float m_TopClip;
+ float m_BottomClip;
+ bool m_bDirty;
+ vec3_t m_vOrigin;
+ CPoint m_ptCursor;
+ bool m_bRButtonDown;
+
+ int m_nButtonstate;
+ int m_nPressx;
+ int m_nPressy;
+ vec3_t m_vPressdelta;
+ bool m_bPress_selection;
+
+ friend CCamWnd;
+ //friend C3DFXCamWnd;
+
+ CMenu m_mnuDrop;
+ int m_nViewType;
+
+ unsigned int m_nTimerID;
+ int m_nScrollFlags;
+ CPoint m_ptDrag;
+ CPoint m_ptDragAdj;
+ CPoint m_ptDragTotal;
+
+ void OriginalButtonUp(UINT nFlags, CPoint point);
+ void OriginalButtonDown(UINT nFlags, CPoint point);
+ void ProduceSplits(brush_t** pFront, brush_t** pBack);
+ void ProduceSplitLists();
+ void HandleDrop();
+ void PaintSizeInfo(int nDim1, int nDim2, vec3_t vMinBounds, vec3_t vMaxBounds);
+
+ void OnEntityCreate(unsigned int nID);
+ CPoint m_ptDown;
+ //{{AFX_MSG(CXYWnd)
+ afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
+ afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
+ afx_msg void OnMButtonDown(UINT nFlags, CPoint point);
+ afx_msg void OnRButtonDown(UINT nFlags, CPoint point);
+ afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
+ afx_msg void OnMButtonUp(UINT nFlags, CPoint point);
+ afx_msg void OnRButtonUp(UINT nFlags, CPoint point);
+ afx_msg void OnMouseMove(UINT nFlags, CPoint point);
+ afx_msg void OnPaint();
+ afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
+ afx_msg void OnSize(UINT nType, int cx, int cy);
+ afx_msg void OnDestroy();
+ afx_msg void OnSelectMouserotate();
+ afx_msg void OnTimer(UINT nIDEvent);
+ afx_msg void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags);
+ afx_msg void OnNcCalcSize(BOOL bCalcValidRects, NCCALCSIZE_PARAMS FAR* lpncsp);
+ afx_msg void OnKillFocus(CWnd* pNewWnd);
+ afx_msg void OnSetFocus(CWnd* pOldWnd);
+ afx_msg void OnClose();
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+/////////////////////////////////////////////////////////////////////////////
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_XYWND_H__44B4BA04_781B_11D1_B53C_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/Z.CPP b/q3radiant/Z.CPP
new file mode 100755
index 0000000..8a454b1
--- /dev/null
+++ b/q3radiant/Z.CPP
@@ -0,0 +1,431 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#include "stdafx.h"
+#include "qe3.h"
+
+#define PAGEFLIPS 2
+
+z_t z;
+
+/*
+============
+Z_Init
+============
+*/
+void Z_Init (void)
+{
+ z.origin[0] = 0;
+ z.origin[1] = 20;
+ z.origin[2] = 46;
+
+ z.scale = 1;
+}
+
+
+
+/*
+============================================================================
+
+ MOUSE ACTIONS
+
+============================================================================
+*/
+
+static int cursorx, cursory;
+
+/*
+==============
+Z_MouseDown
+==============
+*/
+void Z_MouseDown (int x, int y, int buttons)
+{
+ vec3_t org, dir, vup, vright;
+ brush_t *b;
+
+ Sys_GetCursorPos (&cursorx, &cursory);
+
+ vup[0] = 0; vup[1] = 0; vup[2] = 1/z.scale;
+
+ VectorCopy (z.origin, org);
+ org[2] += (y - (z.height/2))/z.scale;
+ org[1] = -8192;
+
+ b = selected_brushes.next;
+ if (b != &selected_brushes)
+ {
+ org[0] = (b->mins[0] + b->maxs[0])/2;
+ }
+
+ dir[0] = 0; dir[1] = 1; dir[2] = 0;
+
+ vright[0] = 0; vright[1] = 0; vright[2] = 0;
+
+ // LBUTTON = manipulate selection
+ // shift-LBUTTON = select
+ // middle button = grab texture
+ // ctrl-middle button = set entire brush to texture
+ // ctrl-shift-middle button = set single face to texture
+
+ int nMouseButton = g_PrefsDlg.m_nMouseButtons == 2 ? MK_RBUTTON : MK_MBUTTON;
+ if ( (buttons == MK_LBUTTON)
+ || (buttons == (MK_LBUTTON | MK_SHIFT))
+ || (buttons == MK_MBUTTON)
+// || (buttons == (MK_MBUTTON|MK_CONTROL))
+ || (buttons == (nMouseButton|MK_SHIFT|MK_CONTROL)) )
+ {
+ Drag_Begin (x, y, buttons,
+ vright, vup,
+ org, dir);
+ return;
+ }
+
+ // control mbutton = move camera
+ if ((buttons == (MK_CONTROL|nMouseButton) ) || (buttons == (MK_CONTROL|MK_LBUTTON)))
+ {
+ g_pParentWnd->GetCamera()->Camera().origin[2] = org[2] ;
+ Sys_UpdateWindows (W_CAMERA|W_XY_OVERLAY|W_Z);
+ }
+
+
+}
+
+/*
+==============
+Z_MouseUp
+==============
+*/
+void Z_MouseUp (int x, int y, int buttons)
+{
+ Drag_MouseUp ();
+}
+
+/*
+==============
+Z_MouseMoved
+==============
+*/
+void Z_MouseMoved (int x, int y, int buttons)
+{
+ if (!buttons)
+ return;
+ if (buttons == MK_LBUTTON)
+ {
+ Drag_MouseMoved (x, y, buttons);
+ Sys_UpdateWindows (W_Z|W_CAMERA_IFON|W_XY);
+ return;
+ }
+ // rbutton = drag z origin
+ if (buttons == MK_RBUTTON)
+ {
+ Sys_GetCursorPos (&x, &y);
+ if ( y != cursory)
+ {
+ z.origin[2] += y-cursory;
+ Sys_SetCursorPos (cursorx, cursory);
+ Sys_UpdateWindows (W_Z);
+ }
+ return;
+ }
+ // control mbutton = move camera
+ int nMouseButton = g_PrefsDlg.m_nMouseButtons == 2 ? MK_RBUTTON : MK_MBUTTON;
+ if ((buttons == (MK_CONTROL|nMouseButton) ) || (buttons == (MK_CONTROL|MK_LBUTTON)))
+ {
+ g_pParentWnd->GetCamera()->Camera().origin[2] = (y - (z.height/2))/z.scale;
+ Sys_UpdateWindows (W_CAMERA|W_XY_OVERLAY|W_Z);
+ }
+
+}
+
+
+/*
+============================================================================
+
+DRAWING
+
+============================================================================
+*/
+
+
+/*
+==============
+Z_DrawGrid
+==============
+*/
+void Z_DrawGrid (void)
+{
+ float zz, zb, ze;
+ int w, h;
+ char text[32];
+
+ w = z.width/2 / z.scale;
+ h = z.height/2 / z.scale;
+
+ zb = z.origin[2] - h;
+ if (zb < region_mins[2])
+ zb = region_mins[2];
+ zb = 64 * floor (zb/64);
+
+ ze = z.origin[2] + h;
+ if (ze > region_maxs[2])
+ ze = region_maxs[2];
+ ze = 64 * ceil (ze/64);
+
+ // draw major blocks
+
+ qglColor3fv(g_qeglobals.d_savedinfo.colors[COLOR_GRIDMAJOR]);
+
+ qglBegin (GL_LINES);
+
+ qglVertex2f (0, zb);
+ qglVertex2f (0, ze);
+
+ for (zz=zb ; zz<ze ; zz+=64)
+ {
+ qglVertex2f (-w, zz);
+ qglVertex2f (w, zz);
+ }
+
+ qglEnd ();
+
+ // draw minor blocks
+ if (g_qeglobals.d_showgrid && g_qeglobals.d_gridsize*z.scale >= 4 &&
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDMINOR] != g_qeglobals.d_savedinfo.colors[COLOR_GRIDBACK])
+ {
+ qglColor3fv(g_qeglobals.d_savedinfo.colors[COLOR_GRIDMINOR]);
+
+ qglBegin (GL_LINES);
+ for (zz=zb ; zz<ze ; zz+=g_qeglobals.d_gridsize)
+ {
+ if ( ! ((int)zz & 63) )
+ continue;
+ qglVertex2f (-w, zz);
+ qglVertex2f (w, zz);
+ }
+ qglEnd ();
+ }
+
+ // draw coordinate text if needed
+
+ qglColor3fv(g_qeglobals.d_savedinfo.colors[COLOR_GRIDTEXT]);
+
+ for (zz=zb ; zz<ze ; zz+=64)
+ {
+ qglRasterPos2f (-w+1, zz);
+ sprintf (text, "%i",(int)zz);
+ qglCallLists (strlen(text), GL_UNSIGNED_BYTE, text);
+ }
+}
+
+#define CAM_HEIGHT 48 // height of main part
+#define CAM_GIZMO 8 // height of the gizmo
+
+void ZDrawCameraIcon (void)
+{
+ float x, y;
+ int xCam = z.width/4;
+
+ x = 0;
+ y = g_pParentWnd->GetCamera()->Camera().origin[2];
+
+ qglColor3f (0.0, 0.0, 1.0);
+ qglBegin(GL_LINE_STRIP);
+ qglVertex3f (x-xCam,y,0);
+ qglVertex3f (x,y+CAM_GIZMO,0);
+ qglVertex3f (x+xCam,y,0);
+ qglVertex3f (x,y-CAM_GIZMO,0);
+ qglVertex3f (x-xCam,y,0);
+ qglVertex3f (x+xCam,y,0);
+ qglVertex3f (x+xCam,y-CAM_HEIGHT,0);
+ qglVertex3f (x-xCam,y-CAM_HEIGHT,0);
+ qglVertex3f (x-xCam,y,0);
+ qglEnd ();
+
+}
+
+GLbitfield glbitClear = GL_COLOR_BUFFER_BIT; //HACK
+
+/*
+==============
+Z_Draw
+==============
+*/
+void Z_Draw (void)
+{
+ brush_t *brush;
+ float w, h;
+ double start, end;
+ qtexture_t *q;
+ float top, bottom;
+ vec3_t org_top, org_bottom, dir_up, dir_down;
+ int xCam = z.width/3;
+
+ if (!active_brushes.next)
+ return; // not valid yet
+
+ if (z.timing)
+ start = Sys_DoubleTime ();
+
+ //
+ // clear
+ //
+ qglViewport(0, 0, z.width, z.height);
+
+ qglClearColor (
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDBACK][0],
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDBACK][1],
+ g_qeglobals.d_savedinfo.colors[COLOR_GRIDBACK][2],
+ 0);
+
+ /* GL Bug */
+ /* When not using hw acceleration, gl will fault if we clear the depth
+ buffer bit on the first pass. The hack fix is to set the GL_DEPTH_BUFFER_BIT
+ only after Z_Draw() has been called once. Yeah, right. */
+ qglClear(glbitClear);
+ glbitClear |= GL_DEPTH_BUFFER_BIT;
+
+ qglMatrixMode(GL_PROJECTION);
+
+ qglLoadIdentity ();
+ w = z.width/2 / z.scale;
+ h = z.height/2 / z.scale;
+ qglOrtho (-w, w, z.origin[2]-h, z.origin[2]+h, -8, 8);
+
+ qglDisable(GL_TEXTURE_2D);
+ qglDisable(GL_TEXTURE_1D);
+ qglDisable(GL_DEPTH_TEST);
+ qglDisable(GL_BLEND);
+
+
+ //
+ // now draw the grid
+ //
+ Z_DrawGrid ();
+
+ //
+ // draw stuff
+ //
+
+ qglDisable(GL_CULL_FACE);
+
+ qglShadeModel (GL_FLAT);
+
+ qglPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
+
+ qglDisable(GL_TEXTURE_2D);
+ qglDisable(GL_BLEND);
+ qglDisable(GL_DEPTH_TEST);
+
+
+ // draw filled interiors and edges
+ dir_up[0] = 0 ; dir_up[1] = 0; dir_up[2] = 1;
+ dir_down[0] = 0 ; dir_down[1] = 0; dir_down[2] = -1;
+ VectorCopy (z.origin, org_top);
+ org_top[2] = 4096;
+ VectorCopy (z.origin, org_bottom);
+ org_bottom[2] = -4096;
+
+ for (brush = active_brushes.next ; brush != &active_brushes ; brush=brush->next)
+ {
+ if (brush->mins[0] >= z.origin[0]
+ || brush->maxs[0] <= z.origin[0]
+ || brush->mins[1] >= z.origin[1]
+ || brush->maxs[1] <= z.origin[1])
+ continue;
+
+ if (!Brush_Ray (org_top, dir_down, brush, &top))
+ continue;
+ top = org_top[2] - top;
+ if (!Brush_Ray (org_bottom, dir_up, brush, &bottom))
+ continue;
+ bottom = org_bottom[2] + bottom;
+
+ q = Texture_ForName (brush->brush_faces->texdef.name);
+ qglColor3f (q->color[0], q->color[1], q->color[2]);
+ qglBegin (GL_QUADS);
+ qglVertex2f (-xCam, bottom);
+ qglVertex2f (xCam, bottom);
+ qglVertex2f (xCam, top);
+ qglVertex2f (-xCam, top);
+ qglEnd ();
+
+ qglColor3f (1,1,1);
+ qglBegin (GL_LINE_LOOP);
+ qglVertex2f (-xCam, bottom);
+ qglVertex2f (xCam, bottom);
+ qglVertex2f (xCam, top);
+ qglVertex2f (-xCam, top);
+ qglEnd ();
+ }
+
+ //
+ // now draw selected brushes
+ //
+ for (brush = selected_brushes.next ; brush != &selected_brushes ; brush=brush->next)
+ {
+ if ( !(brush->mins[0] >= z.origin[0]
+ || brush->maxs[0] <= z.origin[0]
+ || brush->mins[1] >= z.origin[1]
+ || brush->maxs[1] <= z.origin[1]) )
+ {
+ if (Brush_Ray (org_top, dir_down, brush, &top))
+ {
+ top = org_top[2] - top;
+ if (Brush_Ray (org_bottom, dir_up, brush, &bottom))
+ {
+ bottom = org_bottom[2] + bottom;
+
+ q = Texture_ForName (brush->brush_faces->texdef.name);
+ qglColor3f (q->color[0], q->color[1], q->color[2]);
+ qglBegin (GL_QUADS);
+ qglVertex2f (-xCam, bottom);
+ qglVertex2f (xCam, bottom);
+ qglVertex2f (xCam, top);
+ qglVertex2f (-xCam, top);
+ qglEnd ();
+ }
+ }
+ }
+
+ qglColor3fv(g_qeglobals.d_savedinfo.colors[COLOR_SELBRUSHES]);
+ qglBegin (GL_LINE_LOOP);
+ qglVertex2f (-xCam, brush->mins[2]);
+ qglVertex2f (xCam, brush->mins[2]);
+ qglVertex2f (xCam, brush->maxs[2]);
+ qglVertex2f (-xCam, brush->maxs[2]);
+ qglEnd ();
+ }
+
+
+ ZDrawCameraIcon ();
+
+ qglFinish();
+ QE_CheckOpenGLForErrors();
+
+ if (z.timing)
+ {
+ end = Sys_DoubleTime ();
+ Sys_Printf ("z: %i ms\n", (int)(1000*(end-start)));
+ }
+}
+
diff --git a/q3radiant/Z.H b/q3radiant/Z.H
new file mode 100755
index 0000000..75cbf83
--- /dev/null
+++ b/q3radiant/Z.H
@@ -0,0 +1,42 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+// window system independent camera view code
+
+typedef struct
+{
+ int width, height;
+
+ qboolean timing;
+
+ vec3_t origin; // at center of window
+ float scale;
+} z_t;
+
+extern z_t z;
+
+void Z_Init (void);
+void Z_MouseDown (int x, int y, int buttons);
+void Z_MouseUp (int x, int y, int buttons);
+void Z_MouseMoved (int x, int y, int buttons);
+void Z_Draw (void);
+
diff --git a/q3radiant/ZView.cpp b/q3radiant/ZView.cpp
new file mode 100755
index 0000000..d887345
--- /dev/null
+++ b/q3radiant/ZView.cpp
@@ -0,0 +1,163 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// ZView.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "ZView.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CZView
+
+IMPLEMENT_DYNCREATE(CZView, CView)
+
+CZView::CZView()
+{
+}
+
+CZView::~CZView()
+{
+}
+
+
+BEGIN_MESSAGE_MAP(CZView, CView)
+ //{{AFX_MSG_MAP(CZView)
+ ON_WM_CREATE()
+ ON_WM_KEYDOWN()
+ ON_WM_SIZE()
+ ON_WM_DESTROY()
+ ON_WM_LBUTTONUP()
+ ON_WM_LBUTTONDOWN()
+ ON_WM_RBUTTONUP()
+ ON_WM_RBUTTONDOWN()
+ ON_WM_MOUSEMOVE()
+ ON_WM_GETMINMAXINFO()
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CZView drawing
+
+void CZView::OnDraw(CDC* pDC)
+{
+ CDocument* pDoc = GetDocument();
+ // TODO: add draw code here
+}
+
+/////////////////////////////////////////////////////////////////////////////
+// CZView diagnostics
+
+#ifdef _DEBUG
+void CZView::AssertValid() const
+{
+ CView::AssertValid();
+}
+
+void CZView::Dump(CDumpContext& dc) const
+{
+ CView::Dump(dc);
+}
+#endif //_DEBUG
+
+/////////////////////////////////////////////////////////////////////////////
+// CZView message handlers
+
+int CZView::OnCreate(LPCREATESTRUCT lpCreateStruct)
+{
+ if (CView::OnCreate(lpCreateStruct) == -1)
+ return -1;
+
+
+ return 0;
+}
+
+void CZView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
+{
+ // TODO: Add your message handler code here and/or call default
+
+ CView::OnKeyDown(nChar, nRepCnt, nFlags);
+}
+
+void CZView::OnSize(UINT nType, int cx, int cy)
+{
+ CView::OnSize(nType, cx, cy);
+
+ // TODO: Add your message handler code here
+
+}
+
+void CZView::OnDestroy()
+{
+ CView::OnDestroy();
+
+ // TODO: Add your message handler code here
+
+}
+
+void CZView::OnLButtonUp(UINT nFlags, CPoint point)
+{
+ // TODO: Add your message handler code here and/or call default
+
+ CView::OnLButtonUp(nFlags, point);
+}
+
+void CZView::OnLButtonDown(UINT nFlags, CPoint point)
+{
+ // TODO: Add your message handler code here and/or call default
+
+ CView::OnLButtonDown(nFlags, point);
+}
+
+void CZView::OnRButtonUp(UINT nFlags, CPoint point)
+{
+ // TODO: Add your message handler code here and/or call default
+
+ CView::OnRButtonUp(nFlags, point);
+}
+
+void CZView::OnRButtonDown(UINT nFlags, CPoint point)
+{
+ // TODO: Add your message handler code here and/or call default
+
+ CView::OnRButtonDown(nFlags, point);
+}
+
+void CZView::OnMouseMove(UINT nFlags, CPoint point)
+{
+ // TODO: Add your message handler code here and/or call default
+
+ CView::OnMouseMove(nFlags, point);
+}
+
+void CZView::OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI)
+{
+ // TODO: Add your message handler code here and/or call default
+
+ CView::OnGetMinMaxInfo(lpMMI);
+}
diff --git a/q3radiant/ZView.h b/q3radiant/ZView.h
new file mode 100755
index 0000000..682dfcd
--- /dev/null
+++ b/q3radiant/ZView.h
@@ -0,0 +1,83 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_ZVIEW_H__5B906AE2_76E3_11D1_8A6E_0000C0B006B6__INCLUDED_)
+#define AFX_ZVIEW_H__5B906AE2_76E3_11D1_8A6E_0000C0B006B6__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// ZView.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CZView view
+
+class CZView : public CView
+{
+protected:
+ CZView(); // protected constructor used by dynamic creation
+ DECLARE_DYNCREATE(CZView)
+
+// Attributes
+public:
+
+// Operations
+public:
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CZView)
+ protected:
+ virtual void OnDraw(CDC* pDC); // overridden to draw this view
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+ virtual ~CZView();
+#ifdef _DEBUG
+ virtual void AssertValid() const;
+ virtual void Dump(CDumpContext& dc) const;
+#endif
+
+ // Generated message map functions
+protected:
+ //{{AFX_MSG(CZView)
+ afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
+ afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
+ afx_msg void OnSize(UINT nType, int cx, int cy);
+ afx_msg void OnDestroy();
+ afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
+ afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
+ afx_msg void OnRButtonUp(UINT nFlags, CPoint point);
+ afx_msg void OnRButtonDown(UINT nFlags, CPoint point);
+ afx_msg void OnMouseMove(UINT nFlags, CPoint point);
+ afx_msg void OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI);
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+/////////////////////////////////////////////////////////////////////////////
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_ZVIEW_H__5B906AE2_76E3_11D1_8A6E_0000C0B006B6__INCLUDED_)
diff --git a/q3radiant/ZWnd.cpp b/q3radiant/ZWnd.cpp
new file mode 100755
index 0000000..9708e66
--- /dev/null
+++ b/q3radiant/ZWnd.cpp
@@ -0,0 +1,264 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// ZWnd.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "Radiant.h"
+#include "ZWnd.h"
+#include "qe3.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CZWnd
+IMPLEMENT_DYNCREATE(CZWnd, CWnd);
+
+
+CZWnd::CZWnd()
+{
+}
+
+CZWnd::~CZWnd()
+{
+}
+
+
+BEGIN_MESSAGE_MAP(CZWnd, CWnd)
+ //{{AFX_MSG_MAP(CZWnd)
+ ON_WM_CREATE()
+ ON_WM_DESTROY()
+ ON_WM_KEYDOWN()
+ ON_WM_LBUTTONDOWN()
+ ON_WM_MBUTTONDOWN()
+ ON_WM_RBUTTONDOWN()
+ ON_WM_PAINT()
+ ON_WM_GETMINMAXINFO()
+ ON_WM_MOUSEMOVE()
+ ON_WM_SIZE()
+ ON_WM_NCCALCSIZE()
+ ON_WM_KILLFOCUS()
+ ON_WM_SETFOCUS()
+ ON_WM_CLOSE()
+ ON_WM_LBUTTONUP()
+ ON_WM_MBUTTONUP()
+ ON_WM_RBUTTONUP()
+ ON_WM_KEYUP()
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+
+/////////////////////////////////////////////////////////////////////////////
+// CZWnd message handlers
+
+int CZWnd::OnCreate(LPCREATESTRUCT lpCreateStruct)
+{
+ if (CWnd::OnCreate(lpCreateStruct) == -1)
+ return -1;
+
+ g_qeglobals.d_hwndZ = GetSafeHwnd();
+
+ m_dcZ = ::GetDC(GetSafeHwnd());
+ QEW_SetupPixelFormat(m_dcZ, false);
+ if ((m_hglrcZ = qwglCreateContext(m_dcZ )) == 0)
+ Error("wglCreateContext in CZWnd::OnCreate failed");
+
+ if (!qwglShareLists(g_qeglobals.d_hglrcBase, m_hglrcZ))
+ Error( "wglShareLists in CZWnd::OnCreate failed");
+
+ if (!qwglMakeCurrent(m_dcZ, m_hglrcZ))
+ Error ("wglMakeCurrent in CZWnd::OnCreate failed");
+
+ return 0;
+}
+
+void CZWnd::OnDestroy()
+{
+ QEW_StopGL(GetSafeHwnd(), m_hglrcZ, m_dcZ);
+ CWnd::OnDestroy();
+}
+
+void CZWnd::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
+{
+ g_pParentWnd->HandleKey(nChar, nRepCnt, nFlags);
+}
+
+void CZWnd::OnLButtonDown(UINT nFlags, CPoint point)
+{
+ SetFocus();
+ SetCapture();
+ CRect rctZ;
+ GetClientRect(rctZ);
+ Z_MouseDown (point.x, rctZ.Height() - 1 - point.y , nFlags);
+}
+
+void CZWnd::OnMButtonDown(UINT nFlags, CPoint point)
+{
+ SetFocus();
+ SetCapture();
+ CRect rctZ;
+ GetClientRect(rctZ);
+ Z_MouseDown (point.x, rctZ.Height() - 1 - point.y , nFlags);
+}
+
+void CZWnd::OnRButtonDown(UINT nFlags, CPoint point)
+{
+ SetFocus();
+ SetCapture();
+ CRect rctZ;
+ GetClientRect(rctZ);
+ Z_MouseDown (point.x, rctZ.Height() - 1 - point.y , nFlags);
+}
+
+void CZWnd::OnPaint()
+{
+ CPaintDC dc(this); // device context for painting
+ //if (!wglMakeCurrent(m_dcZ, m_hglrcZ))
+ if (!qwglMakeCurrent(dc.m_hDC, m_hglrcZ))
+ {
+ Sys_Printf("ERROR: wglMakeCurrent failed..\n ");
+ Sys_Printf("Please restart Q3Radiant if the Z view is not working\n");
+ }
+ else
+ {
+ QE_CheckOpenGLForErrors();
+ Z_Draw ();
+ //qwglSwapBuffers(m_dcZ);
+ qwglSwapBuffers(dc.m_hDC);
+ TRACE("Z Paint\n");
+ }
+}
+
+void CZWnd::OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI)
+{
+ lpMMI->ptMinTrackSize.x = ZWIN_WIDTH;
+}
+
+void CZWnd::OnMouseMove(UINT nFlags, CPoint point)
+{
+ CRect rctZ;
+ GetClientRect(rctZ);
+ float fz = z.origin[2] + ((rctZ.Height() - 1 - point.y) - (z.height/2)) / z.scale;
+ fz = floor(fz / g_qeglobals.d_gridsize + 0.5) * g_qeglobals.d_gridsize;
+ CString strStatus;
+ strStatus.Format("Z:: %.1f", fz);
+ g_pParentWnd->SetStatusText(1, strStatus);
+ Z_MouseMoved (point.x, rctZ.Height() - 1 - point.y, nFlags);
+}
+
+void CZWnd::OnSize(UINT nType, int cx, int cy)
+{
+ CWnd::OnSize(nType, cx, cy);
+ CRect rctZ;
+ GetClientRect(rctZ);
+ z.width = rctZ.right;
+ z.height = rctZ.bottom;
+ if (z.width < 10)
+ z.width = 10;
+ if (z.height < 10)
+ z.height = 10;
+ Invalidate();
+}
+
+void CZWnd::OnNcCalcSize(BOOL bCalcValidRects, NCCALCSIZE_PARAMS FAR* lpncsp)
+{
+ CWnd::OnNcCalcSize(bCalcValidRects, lpncsp);
+}
+
+void CZWnd::OnKillFocus(CWnd* pNewWnd)
+{
+ CWnd::OnKillFocus(pNewWnd);
+ SendMessage(WM_NCACTIVATE, FALSE , 0 );
+}
+
+void CZWnd::OnSetFocus(CWnd* pOldWnd)
+{
+ CWnd::OnSetFocus(pOldWnd);
+ SendMessage(WM_NCACTIVATE, TRUE , 0 );
+}
+
+void CZWnd::OnClose()
+{
+ CWnd::OnClose();
+}
+
+void CZWnd::OnLButtonUp(UINT nFlags, CPoint point)
+{
+ CRect rctZ;
+ GetClientRect(rctZ);
+ Z_MouseUp (point.x, rctZ.bottom - 1 - point.y, nFlags);
+ if (! (nFlags & (MK_LBUTTON|MK_RBUTTON|MK_MBUTTON)))
+ ReleaseCapture ();
+}
+
+void CZWnd::OnMButtonUp(UINT nFlags, CPoint point)
+{
+ CRect rctZ;
+ GetClientRect(rctZ);
+ Z_MouseUp (point.x, rctZ.bottom - 1 - point.y, nFlags);
+ if (! (nFlags & (MK_LBUTTON|MK_RBUTTON|MK_MBUTTON)))
+ ReleaseCapture ();
+}
+
+void CZWnd::OnRButtonUp(UINT nFlags, CPoint point)
+{
+ CRect rctZ;
+ GetClientRect(rctZ);
+ Z_MouseUp (point.x, rctZ.bottom - 1 - point.y, nFlags);
+ if (! (nFlags & (MK_LBUTTON|MK_RBUTTON|MK_MBUTTON)))
+ ReleaseCapture ();
+}
+
+
+BOOL CZWnd::PreCreateWindow(CREATESTRUCT& cs)
+{
+ WNDCLASS wc;
+ HINSTANCE hInstance = AfxGetInstanceHandle();
+ if (::GetClassInfo(hInstance, Z_WINDOW_CLASS, &wc) == FALSE)
+ {
+ // Register a new class
+ memset (&wc, 0, sizeof(wc));
+ wc.style = CS_NOCLOSE | CS_OWNDC;
+ wc.lpszClassName = Z_WINDOW_CLASS;
+ wc.hCursor = LoadCursor (NULL,IDC_ARROW);
+ wc.lpfnWndProc = ::DefWindowProc;
+ if (AfxRegisterClass(&wc) == FALSE)
+ Error ("CZWnd RegisterClass: failed");
+ }
+
+ cs.lpszClass = Z_WINDOW_CLASS;
+ cs.lpszName = "Z";
+ if (cs.style != QE3_CHILDSTYLE)
+ cs.style = QE3_SPLITTER_STYLE;
+
+ return CWnd::PreCreateWindow(cs);
+}
+
+
+void CZWnd::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags)
+{
+ g_pParentWnd->HandleKey(nChar, nRepCnt, nFlags, false);
+}
diff --git a/q3radiant/ZWnd.h b/q3radiant/ZWnd.h
new file mode 100755
index 0000000..b05c6be
--- /dev/null
+++ b/q3radiant/ZWnd.h
@@ -0,0 +1,90 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_ZWND_H__44B4BA02_781B_11D1_B53C_00AA00A410FC__INCLUDED_)
+#define AFX_ZWND_H__44B4BA02_781B_11D1_B53C_00AA00A410FC__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+// ZWnd.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CZWnd window
+
+class CZWnd : public CWnd
+{
+ DECLARE_DYNCREATE(CZWnd);
+// Construction
+public:
+ CZWnd();
+
+// Attributes
+public:
+
+// Operations
+public:
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CZWnd)
+ protected:
+ virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
+ //}}AFX_VIRTUAL
+
+// Implementation
+public:
+ virtual ~CZWnd();
+
+ // Generated message map functions
+protected:
+ HDC m_dcZ;
+ HGLRC m_hglrcZ;
+ //{{AFX_MSG(CZWnd)
+ afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
+ afx_msg void OnDestroy();
+ afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
+ afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
+ afx_msg void OnMButtonDown(UINT nFlags, CPoint point);
+ afx_msg void OnRButtonDown(UINT nFlags, CPoint point);
+ afx_msg void OnPaint();
+ afx_msg void OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI);
+ afx_msg void OnMouseMove(UINT nFlags, CPoint point);
+ afx_msg void OnSize(UINT nType, int cx, int cy);
+ afx_msg void OnNcCalcSize(BOOL bCalcValidRects, NCCALCSIZE_PARAMS FAR* lpncsp);
+ afx_msg void OnKillFocus(CWnd* pNewWnd);
+ afx_msg void OnSetFocus(CWnd* pOldWnd);
+ afx_msg void OnClose();
+ afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
+ afx_msg void OnMButtonUp(UINT nFlags, CPoint point);
+ afx_msg void OnRButtonUp(UINT nFlags, CPoint point);
+ afx_msg void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags);
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+/////////////////////////////////////////////////////////////////////////////
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_ZWND_H__44B4BA02_781B_11D1_B53C_00AA00A410FC__INCLUDED_)
diff --git a/q3radiant/brush_primit.cpp b/q3radiant/brush_primit.cpp
new file mode 100755
index 0000000..bdcaa96
--- /dev/null
+++ b/q3radiant/brush_primit.cpp
@@ -0,0 +1,461 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "stdafx.h"
+#include "qe3.h"
+
+// compute a determinant using Sarrus rule
+//++timo "inline" this with a macro
+// NOTE : the three vec3_t are understood as columns of the matrix
+vec_t SarrusDet(vec3_t a, vec3_t b, vec3_t c)
+{
+ return a[0]*b[1]*c[2]+b[0]*c[1]*a[2]+c[0]*a[1]*b[2]
+ -c[0]*b[1]*a[2]-a[1]*b[0]*c[2]-a[0]*b[2]*c[1];
+}
+
+//++timo replace everywhere texX by texS etc. ( ----> and in q3map !)
+// NOTE : ComputeAxisBase here and in q3map code must always BE THE SAME !
+// WARNING : special case behaviour of atan2(y,x) <-> atan(y/x) might not be the same everywhere when x == 0
+// rotation by (0,RotY,RotZ) assigns X to normal
+void ComputeAxisBase(vec3_t normal,vec3_t texS,vec3_t texT )
+{
+ vec_t RotY,RotZ;
+ // do some cleaning
+ if (fabs(normal[0])<1e-6)
+ normal[0]=0.0f;
+ if (fabs(normal[1])<1e-6)
+ normal[1]=0.0f;
+ if (fabs(normal[2])<1e-6)
+ normal[2]=0.0f;
+ RotY=-atan2(normal[2],sqrt(normal[1]*normal[1]+normal[0]*normal[0]));
+ RotZ=atan2(normal[1],normal[0]);
+ // rotate (0,1,0) and (0,0,1) to compute texS and texT
+ texS[0]=-sin(RotZ);
+ texS[1]=cos(RotZ);
+ texS[2]=0;
+ // the texT vector is along -Z ( T texture coorinates axis )
+ texT[0]=-sin(RotY)*cos(RotZ);
+ texT[1]=-sin(RotY)*sin(RotZ);
+ texT[2]=-cos(RotY);
+}
+
+void FaceToBrushPrimitFace(face_t *f)
+{
+ vec3_t texX,texY;
+ vec3_t proj;
+ // ST of (0,0) (1,0) (0,1)
+ vec_t ST[3][5]; // [ point index ] [ xyz ST ]
+ //++timo not used as long as brushprimit_texdef and texdef are static
+/* f->brushprimit_texdef.contents=f->texdef.contents;
+ f->brushprimit_texdef.flags=f->texdef.flags;
+ f->brushprimit_texdef.value=f->texdef.value;
+ strcpy(f->brushprimit_texdef.name,f->texdef.name); */
+#ifdef _DEBUG
+ if ( f->plane.normal[0]==0.0f && f->plane.normal[1]==0.0f && f->plane.normal[2]==0.0f )
+ {
+ Sys_Printf("Warning : f->plane.normal is (0,0,0) in FaceToBrushPrimitFace\n");
+ }
+ // check d_texture
+ if (!f->d_texture)
+ {
+ Sys_Printf("Warning : f.d_texture is NULL in FaceToBrushPrimitFace\n");
+ return;
+ }
+#endif
+ // compute axis base
+ ComputeAxisBase(f->plane.normal,texX,texY);
+ // compute projection vector
+ VectorCopy(f->plane.normal,proj);
+ VectorScale(proj,f->plane.dist,proj);
+ // (0,0) in plane axis base is (0,0,0) in world coordinates + projection on the affine plane
+ // (1,0) in plane axis base is texX in world coordinates + projection on the affine plane
+ // (0,1) in plane axis base is texY in world coordinates + projection on the affine plane
+ // use old texture code to compute the ST coords of these points
+ VectorCopy(proj,ST[0]);
+ EmitTextureCoordinates(ST[0], f->d_texture, f);
+ VectorCopy(texX,ST[1]);
+ VectorAdd(ST[1],proj,ST[1]);
+ EmitTextureCoordinates(ST[1], f->d_texture, f);
+ VectorCopy(texY,ST[2]);
+ VectorAdd(ST[2],proj,ST[2]);
+ EmitTextureCoordinates(ST[2], f->d_texture, f);
+ // compute texture matrix
+ f->brushprimit_texdef.coords[0][2]=ST[0][3];
+ f->brushprimit_texdef.coords[1][2]=ST[0][4];
+ f->brushprimit_texdef.coords[0][0]=ST[1][3]-f->brushprimit_texdef.coords[0][2];
+ f->brushprimit_texdef.coords[1][0]=ST[1][4]-f->brushprimit_texdef.coords[1][2];
+ f->brushprimit_texdef.coords[0][1]=ST[2][3]-f->brushprimit_texdef.coords[0][2];
+ f->brushprimit_texdef.coords[1][1]=ST[2][4]-f->brushprimit_texdef.coords[1][2];
+}
+
+// compute texture coordinates for the winding points
+void EmitBrushPrimitTextureCoordinates(face_t * f, winding_t * w)
+{
+ vec3_t texX,texY;
+ vec_t x,y;
+ // compute axis base
+ ComputeAxisBase(f->plane.normal,texX,texY);
+ // in case the texcoords matrix is empty, build a default one
+ // same behaviour as if scale[0]==0 && scale[1]==0 in old code
+ if (f->brushprimit_texdef.coords[0][0]==0 && f->brushprimit_texdef.coords[1][0]==0 && f->brushprimit_texdef.coords[0][1]==0 && f->brushprimit_texdef.coords[1][1]==0)
+ {
+ f->brushprimit_texdef.coords[0][0] = 1.0f;
+ f->brushprimit_texdef.coords[1][1] = 1.0f;
+ ConvertTexMatWithQTexture( &f->brushprimit_texdef, NULL, &f->brushprimit_texdef, f->d_texture );
+ }
+ int i;
+ for (i=0 ; i<w->numpoints ; i++)
+ {
+ x=DotProduct(w->points[i],texX);
+ y=DotProduct(w->points[i],texY);
+#ifdef _DEBUG
+ if (g_qeglobals.bNeedConvert)
+ {
+ // check we compute the same ST as the traditional texture computation used before
+ vec_t S=f->brushprimit_texdef.coords[0][0]*x+f->brushprimit_texdef.coords[0][1]*y+f->brushprimit_texdef.coords[0][2];
+ vec_t T=f->brushprimit_texdef.coords[1][0]*x+f->brushprimit_texdef.coords[1][1]*y+f->brushprimit_texdef.coords[1][2];
+ if ( fabs(S-w->points[i][3])>1e-2 || fabs(T-w->points[i][4])>1e-2 )
+ {
+ if ( fabs(S-w->points[i][3])>1e-4 || fabs(T-w->points[i][4])>1e-4 )
+ Sys_Printf("Warning : precision loss in brush -> brush primitive texture computation\n");
+ else
+ Sys_Printf("Warning : brush -> brush primitive texture computation bug detected\n");
+ }
+ }
+#endif
+ w->points[i][3]=f->brushprimit_texdef.coords[0][0]*x+f->brushprimit_texdef.coords[0][1]*y+f->brushprimit_texdef.coords[0][2];
+ w->points[i][4]=f->brushprimit_texdef.coords[1][0]*x+f->brushprimit_texdef.coords[1][1]*y+f->brushprimit_texdef.coords[1][2];
+ }
+}
+
+// parse a brush in brush primitive format
+void BrushPrimit_Parse(brush_t *b)
+{
+ epair_t *ep;
+ face_t *f;
+ int i,j;
+ GetToken (true);
+ if (strcmp (token, "{"))
+ {
+ Warning ("parsing brush primitive");
+ return;
+ }
+ do
+ {
+ if (!GetToken (true))
+ break;
+ if (!strcmp (token, "}") )
+ break;
+ // reading of b->epairs if any
+ if (strcmp (token, "(") )
+ {
+ ep = ParseEpair();
+ ep->next = b->epairs;
+ b->epairs = ep;
+ }
+ else
+ // it's a face
+ {
+ f = Face_Alloc();
+ f->next = NULL;
+ if (!b->brush_faces)
+ b->brush_faces = f;
+ else
+ {
+ face_t *scan;
+ for (scan=b->brush_faces ; scan->next ; scan=scan->next)
+ ;
+ scan->next = f;
+ }
+
+ // read the three point plane definition
+ for (i=0 ; i<3 ; i++)
+ {
+ if (i != 0)
+ GetToken (true);
+ if (strcmp (token, "(") )
+ {
+ Warning ("parsing brush");
+ return;
+ }
+ for (j=0 ; j<3 ; j++)
+ {
+ GetToken (false);
+ f->planepts[i][j] = atof(token);
+ }
+ GetToken (false);
+ if (strcmp (token, ")") )
+ {
+ Warning ("parsing brush");
+ return;
+ }
+ }
+ // texture coordinates
+ GetToken (false);
+ if (strcmp(token, "("))
+ {
+ Warning ("parsing brush primitive");
+ return;
+ }
+ GetToken (false);
+ if (strcmp(token, "("))
+ {
+ Warning ("parsing brush primitive");
+ return;
+ }
+ for (j=0;j<3;j++)
+ {
+ GetToken(false);
+ f->brushprimit_texdef.coords[0][j]=atof(token);
+ }
+ GetToken (false);
+ if (strcmp(token, ")"))
+ {
+ Warning ("parsing brush primitive");
+ return;
+ }
+ GetToken (false);
+ if (strcmp(token, "("))
+ {
+ Warning ("parsing brush primitive");
+ return;
+ }
+ for (j=0;j<3;j++)
+ {
+ GetToken(false);
+ f->brushprimit_texdef.coords[1][j]=atof(token);
+ }
+ GetToken (false);
+ if (strcmp(token, ")"))
+ {
+ Warning ("parsing brush primitive");
+ return;
+ }
+ GetToken (false);
+ if (strcmp(token, ")"))
+ {
+ Warning ("parsing brush primitive");
+ return;
+ }
+ // read the texturedef
+ GetToken (false);
+ //strcpy(f->texdef.name, token);
+ f->texdef.SetName(token);
+ if (TokenAvailable ())
+ {
+ GetToken (false);
+ f->texdef.contents = atoi(token);
+ GetToken (false);
+ f->texdef.flags = atoi(token);
+ GetToken (false);
+ f->texdef.value = atoi(token);
+ }
+ }
+ } while (1);
+}
+
+// compute a fake shift scale rot representation from the texture matrix
+// these shift scale rot values are to be understood in the local axis base
+void TexMatToFakeTexCoords( vec_t texMat[2][3], float shift[2], float *rot, float scale[2] )
+{
+#ifdef _DEBUG
+ // check this matrix is orthogonal
+ if (fabs(texMat[0][0]*texMat[0][1]+texMat[1][0]*texMat[1][1])>ZERO_EPSILON)
+ Sys_Printf("Warning : non orthogonal texture matrix in TexMatToFakeTexCoords\n");
+#endif
+ scale[0]=sqrt(texMat[0][0]*texMat[0][0]+texMat[1][0]*texMat[1][0]);
+ scale[1]=sqrt(texMat[0][1]*texMat[0][1]+texMat[1][1]*texMat[1][1]);
+#ifdef _DEBUG
+ if (scale[0]<ZERO_EPSILON || scale[1]<ZERO_EPSILON)
+ Sys_Printf("Warning : unexpected scale==0 in TexMatToFakeTexCoords\n");
+#endif
+ // compute rotate value
+ if (fabs(texMat[0][0])<ZERO_EPSILON)
+ {
+#ifdef _DEBUG
+ // check brushprimit_texdef[1][0] is not zero
+ if (fabs(texMat[1][0])<ZERO_EPSILON)
+ Sys_Printf("Warning : unexpected texdef[1][0]==0 in TexMatToFakeTexCoords\n");
+#endif
+ // rotate is +-90
+ if (texMat[1][0]>0)
+ *rot=90.0f;
+ else
+ *rot=-90.0f;
+ }
+ else
+ *rot = RAD2DEG( atan2( texMat[1][0], texMat[0][0] ) );
+ shift[0] = -texMat[0][2];
+ shift[1] = texMat[1][2];
+}
+
+// compute back the texture matrix from fake shift scale rot
+// the matrix returned must be understood as a qtexture_t with width=2 height=2 ( the default one )
+void FakeTexCoordsToTexMat( float shift[2], float rot, float scale[2], vec_t texMat[2][3] )
+{
+ texMat[0][0] = scale[0] * cos( DEG2RAD( rot ) );
+ texMat[1][0] = scale[0] * sin( DEG2RAD( rot ) );
+ texMat[0][1] = -1.0f * scale[1] * sin( DEG2RAD( rot ) );
+ texMat[1][1] = scale[1] * cos( DEG2RAD( rot ) );
+ texMat[0][2] = -shift[0];
+ texMat[1][2] = shift[1];
+}
+
+// convert a texture matrix between two qtexture_t
+// if NULL for qtexture_t, basic 2x2 texture is assumed ( straight mapping between s/t coordinates and geometric coordinates )
+void ConvertTexMatWithQTexture( brushprimit_texdef_t *texMat1, qtexture_t *qtex1, brushprimit_texdef_t *texMat2, qtexture_t *qtex2 )
+{
+ float s1,s2;
+ s1 = ( qtex1 ? static_cast<float>( qtex1->width ) : 2.0f ) / ( qtex2 ? static_cast<float>( qtex2->width ) : 2.0f );
+ s2 = ( qtex1 ? static_cast<float>( qtex1->height ) : 2.0f ) / ( qtex2 ? static_cast<float>( qtex2->height ) : 2.0f );
+ texMat2->coords[0][0]=s1*texMat1->coords[0][0];
+ texMat2->coords[0][1]=s1*texMat1->coords[0][1];
+ texMat2->coords[0][2]=s1*texMat1->coords[0][2];
+ texMat2->coords[1][0]=s2*texMat1->coords[1][0];
+ texMat2->coords[1][1]=s2*texMat1->coords[1][1];
+ texMat2->coords[1][2]=s2*texMat1->coords[1][2];
+}
+
+// texture locking
+void Face_MoveTexture_BrushPrimit(face_t *f, vec3_t delta)
+{
+ vec3_t texS,texT;
+ vec_t tx,ty;
+ vec3_t M[3]; // columns of the matrix .. easier that way
+ vec_t det;
+ vec3_t D[2];
+ // compute plane axis base ( doesn't change with translation )
+ ComputeAxisBase( f->plane.normal, texS, texT );
+ // compute translation vector in plane axis base
+ tx = DotProduct( delta, texS );
+ ty = DotProduct( delta, texT );
+ // fill the data vectors
+ M[0][0]=tx; M[0][1]=1.0f+tx; M[0][2]=tx;
+ M[1][0]=ty; M[1][1]=ty; M[1][2]=1.0f+ty;
+ M[2][0]=1.0f; M[2][1]=1.0f; M[2][2]=1.0f;
+ D[0][0]=f->brushprimit_texdef.coords[0][2];
+ D[0][1]=f->brushprimit_texdef.coords[0][0]+f->brushprimit_texdef.coords[0][2];
+ D[0][2]=f->brushprimit_texdef.coords[0][1]+f->brushprimit_texdef.coords[0][2];
+ D[1][0]=f->brushprimit_texdef.coords[1][2];
+ D[1][1]=f->brushprimit_texdef.coords[1][0]+f->brushprimit_texdef.coords[1][2];
+ D[1][2]=f->brushprimit_texdef.coords[1][1]+f->brushprimit_texdef.coords[1][2];
+ // solve
+ det = SarrusDet( M[0], M[1], M[2] );
+ f->brushprimit_texdef.coords[0][0] = SarrusDet( D[0], M[1], M[2] ) / det;
+ f->brushprimit_texdef.coords[0][1] = SarrusDet( M[0], D[0], M[2] ) / det;
+ f->brushprimit_texdef.coords[0][2] = SarrusDet( M[0], M[1], D[0] ) / det;
+ f->brushprimit_texdef.coords[1][0] = SarrusDet( D[1], M[1], M[2] ) / det;
+ f->brushprimit_texdef.coords[1][1] = SarrusDet( M[0], D[1], M[2] ) / det;
+ f->brushprimit_texdef.coords[1][2] = SarrusDet( M[0], M[1], D[1] ) / det;
+}
+
+// call Face_MoveTexture_BrushPrimit after vec3_t computation
+void Select_ShiftTexture_BrushPrimit( face_t *f, int x, int y )
+{
+ vec3_t texS,texT;
+ vec3_t delta;
+ ComputeAxisBase( f->plane.normal, texS, texT );
+ VectorScale( texS, static_cast<float>(x), texS );
+ VectorScale( texT, static_cast<float>(y), texT );
+ VectorCopy( texS, delta );
+ VectorAdd( delta, texT, delta );
+ Face_MoveTexture_BrushPrimit( f, delta );
+}
+
+// texture locking
+// called before the points on the face are actually rotated
+void RotateFaceTexture_BrushPrimit(face_t *f, int nAxis, float fDeg, vec3_t vOrigin )
+{
+ vec3_t texS,texT; // axis base of the initial plane
+ vec3_t vRotate; // rotation vector
+ vec3_t Orig;
+ vec3_t rOrig,rvecS,rvecT; // (0,0) (1,0) (0,1) ( initial plane axis base ) after rotation ( world axis base )
+ vec3_t rNormal; // normal of the plane after rotation
+ vec3_t rtexS,rtexT; // axis base of the rotated plane
+ vec3_t lOrig,lvecS,lvecT; // [2] are not used ( but usefull for debugging )
+ vec3_t M[3];
+ vec_t det;
+ vec3_t D[2];
+ // compute plane axis base
+ ComputeAxisBase( f->plane.normal, texS, texT );
+ // compute coordinates of (0,0) (1,0) (0,1) ( initial plane axis base ) after rotation
+ // (0,0) (1,0) (0,1) ( initial plane axis base ) <-> (0,0,0) texS texT ( world axis base )
+ // rotation vector
+ VectorSet( vRotate, 0.0f, 0.0f, 0.0f );
+ vRotate[nAxis]=fDeg;
+ VectorSet( Orig, 0.0f, 0.0f, 0.0f );
+ VectorRotate( Orig, vRotate, vOrigin, rOrig );
+ VectorRotate( texS, vRotate, vOrigin, rvecS );
+ VectorRotate( texT, vRotate, vOrigin, rvecT );
+ // compute normal of plane after rotation
+ VectorRotate( f->plane.normal, vRotate, rNormal );
+ // compute rotated plane axis base
+ ComputeAxisBase( rNormal, rtexS, rtexT );
+ // compute S/T coordinates of the three points in rotated axis base ( in M matrix )
+ lOrig[0] = DotProduct( rOrig, rtexS );
+ lOrig[1] = DotProduct( rOrig, rtexT );
+ lvecS[0] = DotProduct( rvecS, rtexS );
+ lvecS[1] = DotProduct( rvecS, rtexT );
+ lvecT[0] = DotProduct( rvecT, rtexS );
+ lvecT[1] = DotProduct( rvecT, rtexT );
+ M[0][0] = lOrig[0]; M[1][0] = lOrig[1]; M[2][0] = 1.0f;
+ M[0][1] = lvecS[0]; M[1][1] = lvecS[1]; M[2][1] = 1.0f;
+ M[0][2] = lvecT[0]; M[1][2] = lvecT[1]; M[2][2] = 1.0f;
+ // fill data vector
+ D[0][0]=f->brushprimit_texdef.coords[0][2];
+ D[0][1]=f->brushprimit_texdef.coords[0][0]+f->brushprimit_texdef.coords[0][2];
+ D[0][2]=f->brushprimit_texdef.coords[0][1]+f->brushprimit_texdef.coords[0][2];
+ D[1][0]=f->brushprimit_texdef.coords[1][2];
+ D[1][1]=f->brushprimit_texdef.coords[1][0]+f->brushprimit_texdef.coords[1][2];
+ D[1][2]=f->brushprimit_texdef.coords[1][1]+f->brushprimit_texdef.coords[1][2];
+ // solve
+ det = SarrusDet( M[0], M[1], M[2] );
+ f->brushprimit_texdef.coords[0][0] = SarrusDet( D[0], M[1], M[2] ) / det;
+ f->brushprimit_texdef.coords[0][1] = SarrusDet( M[0], D[0], M[2] ) / det;
+ f->brushprimit_texdef.coords[0][2] = SarrusDet( M[0], M[1], D[0] ) / det;
+ f->brushprimit_texdef.coords[1][0] = SarrusDet( D[1], M[1], M[2] ) / det;
+ f->brushprimit_texdef.coords[1][1] = SarrusDet( M[0], D[1], M[2] ) / det;
+ f->brushprimit_texdef.coords[1][2] = SarrusDet( M[0], M[1], D[1] ) / det;
+}
+
+// best fitted 2D vector is x.X+y.Y
+void ComputeBest2DVector( vec3_t v, vec3_t X, vec3_t Y, int &x, int &y )
+{
+ double sx,sy;
+ sx = DotProduct( v, X );
+ sy = DotProduct( v, Y );
+ if ( fabs(sy) > fabs(sx) )
+ {
+ x = 0;
+ if ( sy > 0.0 )
+ y = 1;
+ else
+ y = -1;
+ }
+ else
+ {
+ y = 0;
+ if ( sx > 0.0 )
+ x = 1;
+ else
+ x = -1;
+ }
+}
diff --git a/q3radiant/cameratargetdlg.cpp b/q3radiant/cameratargetdlg.cpp
new file mode 100755
index 0000000..6a68a9d
--- /dev/null
+++ b/q3radiant/cameratargetdlg.cpp
@@ -0,0 +1,71 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// CameraTargetDlg.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "CameraTargetDlg.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// CCameraTargetDlg dialog
+
+
+CCameraTargetDlg::CCameraTargetDlg(CWnd* pParent /*=NULL*/)
+ : CDialog(CCameraTargetDlg::IDD, pParent)
+{
+ //{{AFX_DATA_INIT(CCameraTargetDlg)
+ m_nType = 0;
+ m_strName = _T("");
+ //}}AFX_DATA_INIT
+}
+
+
+void CCameraTargetDlg::DoDataExchange(CDataExchange* pDX)
+{
+ CDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CCameraTargetDlg)
+ DDX_Radio(pDX, IDC_RADIO_FIXED, m_nType);
+ DDX_Text(pDX, IDC_EDIT_NAME, m_strName);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CCameraTargetDlg, CDialog)
+ //{{AFX_MSG_MAP(CCameraTargetDlg)
+ ON_COMMAND(ID_POPUP_NEWCAMERA_FIXED, OnPopupNewcameraFixed)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CCameraTargetDlg message handlers
+
+void CCameraTargetDlg::OnPopupNewcameraFixed()
+{
+ // TODO: Add your command handler code here
+
+}
diff --git a/q3radiant/cameratargetdlg.h b/q3radiant/cameratargetdlg.h
new file mode 100755
index 0000000..a769f19
--- /dev/null
+++ b/q3radiant/cameratargetdlg.h
@@ -0,0 +1,68 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_CAMERATARGETDLG_H__DE6597C1_1F63_4835_8949_5D2D5F208C6B__INCLUDED_)
+#define AFX_CAMERATARGETDLG_H__DE6597C1_1F63_4835_8949_5D2D5F208C6B__INCLUDED_
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+// CameraTargetDlg.h : header file
+//
+
+/////////////////////////////////////////////////////////////////////////////
+// CCameraTargetDlg dialog
+
+class CCameraTargetDlg : public CDialog
+{
+// Construction
+public:
+ CCameraTargetDlg(CWnd* pParent = NULL); // standard constructor
+
+// Dialog Data
+ //{{AFX_DATA(CCameraTargetDlg)
+ enum { IDD = IDD_DLG_CAMERATARGET };
+ int m_nType;
+ CString m_strName;
+ //}}AFX_DATA
+
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CCameraTargetDlg)
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+
+ // Generated message map functions
+ //{{AFX_MSG(CCameraTargetDlg)
+ afx_msg void OnPopupNewcameraFixed();
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_CAMERATARGETDLG_H__DE6597C1_1F63_4835_8949_5D2D5F208C6B__INCLUDED_)
diff --git a/q3radiant/cbrushstub.cpp b/q3radiant/cbrushstub.cpp
new file mode 100755
index 0000000..e816045
--- /dev/null
+++ b/q3radiant/cbrushstub.cpp
@@ -0,0 +1,76 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "stdafx.h"
+#include "qe3.h"
+
+void Curve_Invert (void)
+{
+}
+
+void Curve_MakeCurvedBrush (qboolean negative, qboolean top, qboolean bottom,
+ qboolean s1, qboolean s2, qboolean s3, qboolean s4)
+{
+}
+
+
+void Curve_BuildPoints (brush_t *b)
+{
+}
+
+void Curve_CameraDraw (brush_t *b)
+{
+}
+
+void Curve_XYDraw (brush_t *b)
+{
+}
+
+void Curve_WriteFile (char *name)
+{
+}
+
+void Curve_StripFakePlanes( brush_t *b )
+{
+}
+
+void Curve_AddFakePlanes( brush_t *b )
+{
+}
+
+
+void Patch_BrushToMesh(){};
+void Patch_GenericMesh(int nWidth, int nHeight, int nOrientation){};
+void Patch_ReadFile (char *name){};
+void Patch_WriteFile (char *name){};
+void Patch_BuildPoints (brush_t *b){};
+void Patch_Move(int n, const vec3_t vMove){};
+void Patch_ApplyMatrix(int n, const vec3_t vOrigin, const vec3_t vMatrix[3]){};
+void Patch_EditPatch(int n){};
+void Patch_Deselect(){};
+void Patch_Delete(int n){};
+void Patch_Select(int n){};
+void Patch_Scale(int n, const vec3_t vOrigin, const vec3_t vAmt){};
+void Patch_Cleanup(){};
+bool g_bShowPatchBounds;
+bool g_bPatchWireFrame;
+
+
diff --git a/q3radiant/dlgcamera.cpp b/q3radiant/dlgcamera.cpp
new file mode 100755
index 0000000..6d6c51b
--- /dev/null
+++ b/q3radiant/dlgcamera.cpp
@@ -0,0 +1,395 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// DlgCamera.cpp : implementation file
+//
+
+#include "stdafx.h"
+#include "DlgCamera.h"
+#include "DlgEvent.h"
+#include "NameDlg.h"
+#include "splines/splines.h"
+#include "CameraTargetDlg.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#undef THIS_FILE
+static char THIS_FILE[] = __FILE__;
+#endif
+
+CDlgCamera g_dlgCamera;
+
+/*
+============
+va
+
+does a varargs printf into a temp buffer, so I don't need to have
+varargs versions of all text functions.
+FIXME: make this buffer size safe someday
+============
+*/
+char *va( char *format, ... ) {
+ va_list argptr;
+ static char string[2][32000]; // in case va is called by nested functions
+ static int index = 0;
+ char *buf;
+
+ buf = string[index & 1];
+ index++;
+
+ va_start (argptr, format);
+ vsprintf (buf, format,argptr);
+ va_end (argptr);
+
+ return buf;
+}
+
+
+void showCameraInspector() {
+ if (g_dlgCamera.GetSafeHwnd() == NULL) {
+ g_dlgCamera.Create(IDD_DLG_CAMERA);
+ CRect rct;
+ LONG lSize = sizeof(rct);
+ if (LoadRegistryInfo("Radiant::CameraInspector", &rct, &lSize)) {
+ g_dlgCamera.SetWindowPos(NULL, rct.left, rct.top, 0,0, SWP_NOSIZE | SWP_SHOWWINDOW);
+ }
+ Sys_UpdateWindows(W_ALL);
+ }
+ g_dlgCamera.ShowWindow(SW_SHOW);
+ g_dlgCamera.setupFromCamera();
+}
+/////////////////////////////////////////////////////////////////////////////
+// CDlgCamera dialog
+
+
+CDlgCamera::CDlgCamera(CWnd* pParent /*=NULL*/)
+ : CDialog(CDlgCamera::IDD, pParent)
+{
+ //{{AFX_DATA_INIT(CDlgCamera)
+ m_strName = _T("");
+ m_fSeconds = 0.0f;
+ m_trackCamera = TRUE;
+ m_numSegments = 0;
+ m_currentSegment = 0;
+ m_strType = _T("");
+ m_editPoints = 0;
+ //}}AFX_DATA_INIT
+}
+
+
+void CDlgCamera::DoDataExchange(CDataExchange* pDX)
+{
+ CDialog::DoDataExchange(pDX);
+ //{{AFX_DATA_MAP(CDlgCamera)
+ DDX_Control(pDX, IDC_SCROLLBAR_SEGMENT, m_wndSegments);
+ DDX_Control(pDX, IDC_LIST_EVENTS, m_wndEvents);
+ DDX_Control(pDX, IDC_COMBO_SPLINES, m_wndSplines);
+ DDX_Text(pDX, IDC_EDIT_CAM_NAME, m_strName);
+ DDX_Text(pDX, IDC_EDIT_LENGTH, m_fSeconds);
+ DDX_Check(pDX, IDC_CHECK_TRACKCAMERA, m_trackCamera);
+ DDX_Text(pDX, IDC_EDIT_TOTALSEGMENTS, m_numSegments);
+ DDX_Text(pDX, IDC_EDIT_SEGMENT, m_currentSegment);
+ DDX_Text(pDX, IDC_EDIT_TYPE, m_strType);
+ DDX_Radio(pDX, IDC_RADIO_EDITPOINTS, m_editPoints);
+ //}}AFX_DATA_MAP
+}
+
+
+BEGIN_MESSAGE_MAP(CDlgCamera, CDialog)
+ //{{AFX_MSG_MAP(CDlgCamera)
+ ON_BN_CLICKED(IDC_BTN_ADDEVENT, OnBtnAddevent)
+ ON_BN_CLICKED(IDC_BTN_ADDTARGET, OnBtnAddtarget)
+ ON_BN_CLICKED(IDC_BTN_DELEVENT, OnBtnDelevent)
+ ON_CBN_DBLCLK(IDC_COMBO_SPLINES, OnDblclkComboSplines)
+ ON_CBN_SELCHANGE(IDC_COMBO_SPLINES, OnSelchangeComboSplines)
+ ON_LBN_SELCHANGE(IDC_LIST_EVENTS, OnSelchangeListEvents)
+ ON_LBN_DBLCLK(IDC_LIST_EVENTS, OnDblclkListEvents)
+ ON_WM_DESTROY()
+ ON_BN_CLICKED(IDAPPLY, OnApply)
+ ON_WM_HSCROLL()
+ ON_BN_CLICKED(ID_FILE_NEW, OnFileNew)
+ ON_BN_CLICKED(ID_FILE_OPEN, OnFileOpen)
+ ON_BN_CLICKED(ID_FILE_SAVE, OnFileSave)
+ ON_BN_CLICKED(ID_TESTCAMERA, OnTestcamera)
+ ON_BN_CLICKED(IDC_BTN_DELETEPOINTS, OnBtnDeletepoints)
+ ON_BN_CLICKED(IDC_BTN_SELECTALL, OnBtnSelectall)
+ ON_BN_CLICKED(IDC_RADIO_EDITPOINTS, OnRadioEditpoints)
+ ON_BN_CLICKED(IDC_RADIO_EDITPOINTS2, OnRadioAddPoints)
+ //}}AFX_MSG_MAP
+END_MESSAGE_MAP()
+
+/////////////////////////////////////////////////////////////////////////////
+// CDlgCamera message handlers
+
+void CDlgCamera::OnBtnAddevent()
+{
+ CDlgEvent dlg;
+ if (dlg.DoModal() == IDOK) {
+ long n = m_wndSegments.GetScrollPos() / 4 * 1000;
+ g_splineList->addEvent(static_cast<idCameraEvent::eventType>(dlg.m_event+1), dlg.m_strParm, n);
+ setupFromCamera();
+ }
+}
+
+void CDlgCamera::OnBtnAddtarget()
+{
+ CCameraTargetDlg dlg;
+ if (dlg.DoModal() == IDOK) {
+ g_splineList->addTarget(dlg.m_strName, static_cast<idCameraPosition::positionType>(dlg.m_nType));
+ setupFromCamera();
+ m_wndSplines.SetCurSel(g_splineList->numTargets());
+ OnSelchangeComboSplines();
+ OnRadioAddPoints();
+ }
+}
+
+void CDlgCamera::OnBtnDelevent()
+{
+ // TODO: Add your control notification handler code here
+
+}
+
+void CDlgCamera::OnBtnDeltarget()
+{
+ // TODO: Add your control notification handler code here
+
+}
+
+void CDlgCamera::OnDblclkComboSplines()
+{
+ // TODO: Add your control notification handler code here
+
+}
+
+void CDlgCamera::OnSelchangeComboSplines()
+{
+ UpdateData(TRUE);
+ g_qeglobals.d_select_mode = (m_editPoints == 0) ? sel_editpoint : sel_addpoint;
+ g_qeglobals.d_numpoints = 0;
+ g_qeglobals.d_num_move_points = 0;
+ int i = m_wndSplines.GetCurSel();
+ if (i > 0) {
+ g_splineList->setActiveTarget(i-1);
+ g_qeglobals.selectObject = g_splineList->getActiveTarget(i-1);
+ g_splineList->startEdit(false);
+ } else {
+ g_splineList->startEdit(true);
+ g_qeglobals.selectObject = g_splineList->getPositionObj();
+ }
+
+ // * 4.0 to set increments in quarter seconds
+ m_wndSegments.SetScrollRange(0, g_splineList->getTotalTime() * 4.0);
+
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CDlgCamera::OnSelchangeListEvents()
+{
+ int sel = m_wndEvents.GetCurSel();
+ //g_splineList->setActiveSegment(sel >= 0 ? sel : 0);
+}
+
+void CDlgCamera::OnDblclkListEvents()
+{
+ // TODO: Add your control notification handler code here
+
+}
+
+void CDlgCamera::setupFromCamera()
+{
+ if (m_wndSplines.GetSafeHwnd()) {
+ int i;
+ idStr str;
+ m_strName = g_splineList->getName();
+ m_strType = g_splineList->getPositionObj()->typeStr();
+ m_wndSplines.ResetContent();
+ m_wndSplines.AddString("Path");
+ for (i = 0; i < g_splineList->numTargets(); i++) {
+ m_wndSplines.AddString(g_splineList->getActiveTarget(i)->getName());
+ }
+ m_wndSplines.SetCurSel(0);
+ m_fSeconds = g_splineList->getBaseTime();
+ m_wndSegments.SetScrollRange(0, g_splineList->getTotalTime() * 4.0);
+
+ m_wndEvents.ResetContent();
+ for (i = 0; i < g_splineList->numEvents(); i++) {
+ str = va("%s\t%s", g_splineList->getEvent(i)->typeStr(), g_splineList->getEvent(i)->getParam());
+ m_wndEvents.AddString(str);
+ }
+ //m_currentSegment = g_splineList->getActiveSegment();
+ //m_numSegments = g_splineList->numSegments();
+ }
+ g_splineList->startEdit(true);
+ UpdateData(FALSE);
+}
+
+BOOL CDlgCamera::OnInitDialog()
+{
+ CDialog::OnInitDialog();
+ setupFromCamera();
+ return TRUE; // return TRUE unless you set the focus to a control
+ // EXCEPTION: OCX Property Pages should return FALSE
+}
+
+void CDlgCamera::OnOK()
+{
+ g_dlgCamera.ShowWindow(SW_HIDE);
+ clearSelection();
+ g_splineList->stopEdit();
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CDlgCamera::OnDestroy()
+{
+ if (GetSafeHwnd()) {
+ CRect rct;
+ GetWindowRect(rct);
+ SaveRegistryInfo("Radiant::CameraInspector", &rct, sizeof(rct));
+ }
+ CDialog::OnDestroy();
+ Sys_UpdateWindows(W_ALL);
+}
+
+
+void CDlgCamera::OnApply()
+{
+ UpdateData(TRUE);
+ g_splineList->setBaseTime(m_fSeconds);
+ g_splineList->setName(m_strName);
+ g_splineList->buildCamera();
+ m_wndSegments.SetScrollRange(0, g_splineList->getTotalTime() * 4.0);
+}
+
+void CDlgCamera::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
+{
+ CDialog::OnHScroll(nSBCode, nPos, pScrollBar);
+ int max = g_splineList->getTotalTime() * 4;
+ if (max == 0) {
+ max = 1;
+ }
+ int n = pScrollBar->GetScrollPos();
+ switch (nSBCode) {
+ case SB_LINEUP : {
+ n--;
+ }
+ break;
+ case SB_LINEDOWN : {
+ n++;
+ }
+ break;
+ case SB_PAGEUP : {
+ n -= (float)max * 0.10;
+ }
+ break;
+ case SB_PAGEDOWN : {
+ n += (float)max * 0.10;
+ }
+ break;
+ case SB_THUMBPOSITION : {
+ n = nPos;
+ }
+ break;
+ case SB_THUMBTRACK : {
+ n = nPos;
+ }
+ }
+// if (n < 0) {
+// n = 0;
+// } else if (n >= g_splineList->numSegments()) {
+// if (g_splineList->numSegments() == 0) {
+// g_splineList->buildCamera();
+// }
+// n = g_splineList->numSegments() - 1;
+// }
+ pScrollBar->SetScrollPos(n);
+ if (m_trackCamera) {
+ float p = (float)n / max;
+ p *= g_splineList->getTotalTime() * 1000;
+ g_splineList->startCamera(0);
+ g_splineList->buildCamera();
+ vec3_t dir;
+ float fov;
+ g_splineList->getCameraInfo(p, g_pParentWnd->GetCamera()->Camera().origin, dir, &fov);
+ g_pParentWnd->GetCamera()->Camera().angles[1] = atan2 (dir[1], dir[0])*180/3.14159;
+ g_pParentWnd->GetCamera()->Camera().angles[0] = asin (dir[2])*180/3.14159;
+
+ }
+ UpdateData(FALSE);
+ Sys_UpdateWindows(W_XY | W_CAMERA);
+}
+
+void CDlgCamera::OnFileNew()
+{
+ g_splineList->clear();
+ g_qeglobals.selectObject = g_splineList->getPositionObj();
+ setupFromCamera();
+ Sys_UpdateWindows(W_ALL);
+}
+
+void CDlgCamera::OnFileOpen()
+{
+ CNameDlg dlg("Open Camera File");
+ if (dlg.DoModal() == IDOK) {
+ g_splineList->clear();
+ g_qeglobals.selectObject = g_splineList->getPositionObj();
+ g_splineList->load(va("%s.camera", dlg.m_strName));
+ setupFromCamera();
+ Sys_UpdateWindows(W_ALL);
+ }
+}
+
+void CDlgCamera::OnFileSave()
+{
+ CNameDlg dlg("Save Camera File");
+ if (dlg.DoModal() == IDOK) {
+ g_splineList->save(va("%s.camera", dlg.m_strName));
+ }
+}
+
+void CDlgCamera::OnTestcamera()
+{
+ // TODO: Add your control notification handler code here
+
+}
+
+void CDlgCamera::OnBtnDeletepoints()
+{
+ // TODO: Add your control notification handler code here
+
+}
+
+void CDlgCamera::OnBtnSelectall()
+{
+ // TODO: Add your control notification handler code here
+
+}
+
+void CDlgCamera::OnRadioEditpoints()
+{
+ UpdateData(TRUE);
+ g_qeglobals.d_select_mode = sel_editpoint;
+}
+
+void CDlgCamera::OnRadioAddPoints()
+{
+ UpdateData(TRUE);
+ g_qeglobals.d_select_mode = sel_addpoint;
+}
diff --git a/q3radiant/dlgcamera.h b/q3radiant/dlgcamera.h
new file mode 100755
index 0000000..6c54007
--- /dev/null
+++ b/q3radiant/dlgcamera.h
@@ -0,0 +1,98 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#if !defined(AFX_DLGCAMERA_H__59C12359_E3EB_4081_9F28_01793D75CF20__INCLUDED_)
+#define AFX_DLGCAMERA_H__59C12359_E3EB_4081_9F28_01793D75CF20__INCLUDED_
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+// DlgCamera.h : header file
+//
+
+extern void showCameraInspector();
+
+/////////////////////////////////////////////////////////////////////////////
+// CDlgCamera dialog
+
+class CDlgCamera : public CDialog
+{
+// Construction
+public:
+ CDlgCamera(CWnd* pParent = NULL); // standard constructor
+ void setupFromCamera();
+
+// Dialog Data
+ //{{AFX_DATA(CDlgCamera)
+ enum { IDD = IDD_DLG_CAMERA };
+ CScrollBar m_wndSegments;
+ CListBox m_wndEvents;
+ CComboBox m_wndSplines;
+ CString m_strName;
+ float m_fSeconds;
+ BOOL m_trackCamera;
+ int m_numSegments;
+ int m_currentSegment;
+ CString m_strType;
+ int m_editPoints;
+ //}}AFX_DATA
+
+
+// Overrides
+ // ClassWizard generated virtual function overrides
+ //{{AFX_VIRTUAL(CDlgCamera)
+ protected:
+ virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
+ //}}AFX_VIRTUAL
+
+// Implementation
+protected:
+ // Generated message map functions
+ //{{AFX_MSG(CDlgCamera)
+ afx_msg void OnBtnAddevent();
+ afx_msg void OnBtnAddtarget();
+ afx_msg void OnBtnDelevent();
+ afx_msg void OnBtnDeltarget();
+ afx_msg void OnDblclkComboSplines();
+ afx_msg void OnSelchangeComboSplines();
+ afx_msg void OnSelchangeListEvents();
+ afx_msg void OnDblclkListEvents();
+ virtual BOOL OnInitDialog();
+ virtual void OnOK();
+ afx_msg void OnDestroy();
+ afx_msg void OnApply();
+ afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
+ afx_msg void OnFileNew();
+ afx_msg void OnFileOpen();
+ afx_msg void OnFileSave();
+ afx_msg void OnTestcamera();
+ afx_msg void OnBtnDeletepoints();
+ afx_msg void OnBtnSelectall();
+ afx_msg void OnRadioEditpoints();
+ afx_msg void OnRadioAddPoints();
+ //}}AFX_MSG
+ DECLARE_MESSAGE_MAP()
+};
+
+//{{AFX_INSERT_LOCATION}}
+// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
+
+#endif // !defined(AFX_DLGCAMERA_H__59C12359_E3EB_4081_9F28_01793D75CF20__INCLUDED_)
diff --git a/q3radiant/igl.h b/q3radiant/igl.h
new file mode 100755
index 0000000..035cb77
--- /dev/null
+++ b/q3radiant/igl.h
@@ -0,0 +1,261 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//-----------------------------------------------------------------------------
+//
+// $LogFile$
+// $Revision: 1.7.2.3 $
+// $Author: ttimo $
+// $Date: 2000/02/16 15:43:14 $
+// $Log: igl.h,v $
+// Revision 1.7.2.3 2000/02/16 15:43:14 ttimo
+// Curry bug #101996: added glTexParameterf and glNormal3f
+//
+// Revision 1.7.2.2 2000/02/13 17:48:07 ttimo
+// Curry bug #101874 - added glTexGenf to GL interface
+//
+// Revision 1.7.2.1 2000/02/04 22:59:34 ttimo
+// messaging API preview
+//
+// Revision 1.7 2000/01/18 00:43:59 ttimo
+// RC
+//
+// Revision 1.6 2000/01/13 00:46:41 ttimo
+// Merged in patches in / out
+// Revision 1.1.1.4 2000/01/18 00:17:12 ttimo
+// merging in for RC
+//
+// Revision 1.5 2000/01/11 22:14:48 ttimo
+// cleaning up after merging and thinks badly fucked up
+//
+// Revision 1.2 2000/01/09 04:39:14 ttimo
+// added some bindings to the GL table
+//
+// Revision 1.1.1.3 2000/01/11 16:43:15 ttimo
+// merged version from old reposit and Robert update
+//
+// Revision 1.1.1.1 2000/01/07 17:17:30 ttimo
+// initial import of Q3Radiant module
+//
+// Revision 1.1.1.1 2000/01/07 17:17:30 ttimo
+// initial import of Q3Radiant module
+//
+// Revision 1.3 2000/01/17 23:53:44 TBesset
+// ready for merge in sourceforge (RC candidate)
+//
+// Revision 1.2 2000/01/07 16:40:13 TBesset
+// merged from BSP frontend
+//
+// Revision 1.1.1.3 1999/12/29 18:31:27 TBesset
+// Q3Radiant public version
+//
+// Revision 1.1.1.1.2.1 1999/12/29 21:39:45 TBesset
+// updated to update3 from Robert
+//
+// Revision 1.1.1.3 1999/12/29 18:31:27 TBesset
+// Q3Radiant public version
+// Revision 1.1.1.3 1999/12/29 18:31:27 TBesset
+// Q3Radiant public version
+//
+// Revision 1.2 1999/11/22 17:46:48 Timo & Christine
+// merged EARadiant into the main tree
+// bug fixes for Q3Plugin / EAPlugin
+// export for Robert
+//
+// Revision 1.1.2.2 1999/11/03 20:38:04 Timo & Christine
+// MEAN plugin for Q3Radiant, alpha version
+//
+// Revision 1.1.2.1.2.1 1999/10/27 08:34:29 Timo & Christine
+// preview version of the texture tools plugin is ready
+// ( TexTool.dll plugin is in Q3Plugin module )
+// plugins can draw in their own window using Radiant's qgl bindings
+//
+// Revision 1.1.2.1 1999/10/08 16:28:14 Timo & Christine
+// started plugin extensions for EA features support in Q3Radiant
+// MEAN files plugin, and Surface Properties plugin
+//
+//
+// DESCRIPTION:
+// all purpose OpenGL interface for Q3Radiant plugins
+//
+
+#ifndef __IGL_H__
+#define __IGL_H__
+
+// we use this class to let plugins draw inside the Radiant windows
+class IGLWindow
+{
+public:
+ // Increment the number of references to this object
+ virtual void IncRef () = 0;
+ // Decrement the reference count
+ virtual void DecRef () = 0;
+ virtual void Draw( VIEWTYPE vt ) = 0;
+};
+
+// define a GUID for this interface so plugins can access and reference it
+// {0F237620-854B-11d3-8EF3-A2DFBD53251B}
+static const GUID QERQglTable_GUID =
+{ 0xf237620, 0x854b, 0x11d3, { 0x8e, 0xf3, 0xa2, 0xdf, 0xbd, 0x53, 0x25, 0x1b } };
+
+#include <gl/gl.h>
+#include <gl/glu.h>
+
+typedef void (APIENTRY* PFN_QGLALPHAFUNC) (GLenum func, GLclampf ref);
+typedef void (APIENTRY* PFN_QGLBEGIN) (GLenum);
+typedef void (APIENTRY* PFN_QGLBINDTEXTURE) (GLenum target, GLuint texture);
+typedef void (APIENTRY* PFN_QGLBLENDFUNC) (GLenum sfactor, GLenum dfactor);
+typedef void (APIENTRY* PFN_QGLCALLLIST) (GLuint list);
+typedef void (APIENTRY* PFN_QGLCALLLISTS) (GLsizei n, GLenum type, const GLvoid *lists);
+typedef void (APIENTRY* PFN_QGLCLEAR) (GLbitfield mask);
+typedef void (APIENTRY* PFN_QGLCLEARCOLOR) (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+typedef void (APIENTRY* PFN_QGLCLEARDEPTH) (GLclampd depth);
+typedef void (APIENTRY* PFN_QGLCOLOR3F) (GLfloat red, GLfloat green, GLfloat blue);
+typedef void (APIENTRY* PFN_QGLCOLOR4F) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+typedef void (APIENTRY* PFN_QGLCULLFACE) (GLenum mode);
+typedef void (APIENTRY* PFN_QGLDELETELISTS) (GLuint list, GLsizei range);
+typedef void (APIENTRY* PFN_QGLDISABLE) (GLenum cap);
+typedef void (APIENTRY* PFN_QGLENABLE) (GLenum cap);
+typedef void (APIENTRY* PFN_QGLEND) ();
+typedef void (APIENTRY* PFN_QGLENDLIST) (void);
+typedef GLuint (APIENTRY* PFN_QGLGENLISTS) (GLsizei range);
+typedef void (APIENTRY* PFN_QGLLISTBASE) (GLuint base);
+typedef void (APIENTRY* PFN_QGLLOADIDENTITY) ();
+typedef void (APIENTRY* PFN_QGLMATRIXMODE) (GLenum mode);
+typedef void (APIENTRY* PFN_QGLNEWLIST) (GLuint list, GLenum mode);
+typedef void (APIENTRY* PFN_QGLNORMAL3F) (GLfloat nx, GLfloat ny, GLfloat nz);
+typedef void (APIENTRY* PFN_QGLORTHO) (GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+typedef void (APIENTRY* PFN_QGLPOINTSIZE) (GLfloat size);
+typedef void (APIENTRY* PFN_QGLPOLYGONMODE) (GLenum face, GLenum mode);
+typedef void (APIENTRY* PFN_QGLPOPMATRIX) ();
+typedef void (APIENTRY* PFN_QGLPUSHMATRIX) ();
+typedef void (APIENTRY* PFN_QGLROTATED) (GLdouble angle, GLdouble x, GLdouble y, GLdouble z);
+typedef void (APIENTRY* PFN_QGLROTATEF) (GLfloat angle, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRY* PFN_QGLSCALEF) (GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRY* PFN_QGLTEXCOORD2F) (GLfloat s, GLfloat t);
+typedef void (APIENTRY* PFN_QGLTEXENVF) (GLenum target, GLenum pname, GLfloat param);
+typedef void (APIENTRY* PFN_QGLTEXGENF) (GLenum coord, GLenum pname, GLfloat param);
+typedef void (APIENTRY* PFN_QGLTEXPARAMETERF) (GLenum target, GLenum pname, GLfloat param);
+typedef void (APIENTRY* PFN_QGLTRANSLATED) (GLdouble x, GLdouble y, GLdouble z);
+typedef void (APIENTRY* PFN_QGLTRANSLATEF) (GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRY* PFN_QGLVERTEX2F) (GLfloat x, GLfloat y);
+typedef void (APIENTRY* PFN_QGLVERTEX3F) (GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRY* PFN_QGLVIEWPORT) (GLint x, GLint y, GLsizei width, GLsizei height);
+
+typedef void (WINAPI* PFN_QE_CHECKOPENGLFORERRORS) ();
+typedef int (WINAPI* PFN_QEW_SETUPPIXELFORMAT) (HDC hDC, qboolean zbuffer );
+typedef HGLRC (WINAPI* PFN_QWGL_CREATECONTEXT) (HDC);
+typedef BOOL (WINAPI* PFN_QWGL_DELETECONTEXT) (HGLRC);
+typedef BOOL (WINAPI* PFN_QWGL_MAKECURRENT) (HDC, HGLRC);
+typedef BOOL (WINAPI* PFN_QWGL_SHARELISTS) (HGLRC, HGLRC);
+typedef BOOL (WINAPI* PFN_QWGL_SWAPBUFFERS) (HDC);
+typedef BOOL (WINAPI* PFN_QWGL_USEFONTBITMAPS) (HDC, DWORD, DWORD, DWORD);
+
+// glu stuff
+typedef void (APIENTRY * PFN_QGLUPERSPECTIVE) (GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar);
+typedef void (APIENTRY * PFN_QGLULOOKAT)(
+ GLdouble eyex,
+ GLdouble eyey,
+ GLdouble eyez,
+ GLdouble centerx,
+ GLdouble centery,
+ GLdouble centerz,
+ GLdouble upx,
+ GLdouble upy,
+ GLdouble upz);
+
+
+// specially provided by the editor for plugins
+typedef HGLRC (WINAPI* PFN_QERAPP_GETQEGLOBALSHGLRC) ();
+
+// plugins drawing inside the GL windows
+//++timo TODO: add hooking into other windows
+//+timo NOTE: this could be moved to the messaging system instead of having a dedicated interface
+typedef void (WINAPI* PFN_QERAPP_HOOKXYGLWINDOW) (IGLWindow *);
+typedef void (WINAPI* PFN_QERAPP_UNHOOKGLWINDOW) (IGLWindow *);
+
+struct _QERQglTable
+{
+ //++timo do we really wanna play with versions ?
+// float m_fVersion;
+ int m_nSize;
+ PFN_QGLALPHAFUNC m_pfn_qglAlphaFunc;
+ PFN_QGLBEGIN m_pfn_qglBegin;
+ PFN_QGLBINDTEXTURE m_pfn_qglBindTexture;
+ PFN_QGLBLENDFUNC m_pfn_qglBlendFunc;
+ PFN_QGLCALLLIST m_pfn_qglCallList;
+ PFN_QGLCLEAR m_pfn_qglClear;
+ PFN_QGLCLEARCOLOR m_pfn_qglClearColor;
+ PFN_QGLCALLLISTS m_pfn_qglCallLists;
+ PFN_QGLCLEARDEPTH m_pfn_qglClearDepth;
+ PFN_QGLCOLOR3F m_pfn_qglColor3f;
+ PFN_QGLCOLOR4F m_pfn_qglColor4f;
+ PFN_QGLCULLFACE m_pfn_qglCullFace;
+ PFN_QGLDELETELISTS m_pfn_qglDeleteLists;
+ PFN_QGLDISABLE m_pfn_qglDisable;
+ PFN_QGLENABLE m_pfn_qglEnable;
+ PFN_QGLEND m_pfn_qglEnd;
+ PFN_QGLENDLIST m_pfn_qglEndList;
+ PFN_QGLGENLISTS m_pfn_qglGenLists;
+ PFN_QGLLISTBASE m_pfn_qglListBase;
+ PFN_QGLLOADIDENTITY m_pfn_qglLoadIdentity;
+ PFN_QGLMATRIXMODE m_pfn_qglMatrixMode;
+ PFN_QGLNEWLIST m_pfn_qglNewList;
+ PFN_QGLNORMAL3F m_pfn_qglNormal3f;
+ PFN_QGLORTHO m_pfn_qglOrtho;
+ PFN_QGLPOINTSIZE m_pfn_qglPointSize;
+ PFN_QGLPOLYGONMODE m_pfn_qglPolygonMode;
+ PFN_QGLPOPMATRIX m_pfn_qglPopMatrix;
+ PFN_QGLPUSHMATRIX m_pfn_qglPushMatrix;
+ PFN_QGLROTATED m_pfn_qglRotated;
+ PFN_QGLROTATEF m_pfn_qglRotatef;
+ PFN_QGLSCALEF m_pfn_qglScalef;
+ PFN_QGLTEXCOORD2F m_pfn_qglTexCoord2f;
+ PFN_QGLTEXENVF m_pfn_qglTexEnvf;
+ PFN_QGLTEXGENF m_pfn_qglTexGenf;
+ PFN_QGLTEXPARAMETERF m_pfn_qglTexParameterf;
+ PFN_QGLTRANSLATED m_pfn_qglTranslated;
+ PFN_QGLTRANSLATEF m_pfn_qglTranslatef;
+ PFN_QGLVERTEX2F m_pfn_qglVertex2f;
+ PFN_QGLVERTEX3F m_pfn_qglVertex3f;
+ PFN_QGLVIEWPORT m_pfn_qglViewport;
+
+ PFN_QE_CHECKOPENGLFORERRORS m_pfn_QE_CheckOpenGLForErrors;
+ PFN_QEW_SETUPPIXELFORMAT m_pfn_QEW_SetupPixelFormat;
+ PFN_QWGL_CREATECONTEXT m_pfn_qwglCreateContext;
+ PFN_QWGL_DELETECONTEXT m_pfn_qwglDeleteContext;
+ PFN_QWGL_MAKECURRENT m_pfn_qwglMakeCurrent;
+ PFN_QWGL_SHARELISTS m_pfn_qwglShareLists;
+ PFN_QWGL_SWAPBUFFERS m_pfn_qwglSwapBuffers;
+ PFN_QWGL_USEFONTBITMAPS m_pfn_qwglUseFontBitmaps;
+
+ PFN_QERAPP_GETQEGLOBALSHGLRC m_pfnGetQeglobalsHGLRC;
+
+ // glu stuff
+ PFN_QGLUPERSPECTIVE m_pfn_qgluPerspective;
+ PFN_QGLULOOKAT m_pfn_qgluLookAt;
+
+ // plugin entities drawing inside Radiant windows
+ PFN_QERAPP_HOOKXYGLWINDOW m_pfnHookXYGLWindow;
+ PFN_QERAPP_UNHOOKGLWINDOW m_pfnUnHookGLWindow;
+};
+
+#endif \ No newline at end of file
diff --git a/q3radiant/iscriplib.h b/q3radiant/iscriplib.h
new file mode 100755
index 0000000..05b75a3
--- /dev/null
+++ b/q3radiant/iscriplib.h
@@ -0,0 +1,87 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//-----------------------------------------------------------------------------
+//
+// $LogFile$
+// $Revision: 1.1.1.4 $
+// $Author: ttimo $
+// $Date: 2000/01/18 00:17:12 $
+// $Log: iscriplib.h,v $
+// Revision 1.1.1.4 2000/01/18 00:17:12 ttimo
+// merging in for RC
+//
+// Revision 1.3 2000/01/17 23:53:44 TBesset
+// ready for merge in sourceforge (RC candidate)
+//
+// Revision 1.2 2000/01/07 16:40:13 TBesset
+// merged from BSP frontend
+//
+// Revision 1.1.1.3 1999/12/29 18:31:27 TBesset
+// Q3Radiant public version
+//
+// Revision 1.1.1.1.2.1 1999/12/29 21:39:45 TBesset
+// updated to update3 from Robert
+//
+// Revision 1.1.1.3 1999/12/29 18:31:27 TBesset
+// Q3Radiant public version
+// Revision 1.1.1.3 1999/12/29 18:31:27 TBesset
+// Q3Radiant public version
+//
+// Revision 1.2 1999/11/22 17:46:48 Timo & Christine
+// merged EARadiant into the main tree
+// bug fixes for Q3Plugin / EAPlugin
+// export for Robert
+//
+// Revision 1.1.2.2 1999/11/14 16:26:14 Timo & Christine
+// first beta of the ritualmap surface plugin
+//
+// Revision 1.1.2.1 1999/10/08 16:28:15 Timo & Christine
+// started plugin extensions for EA features support in Q3Radiant
+// MEAN files plugin, and Surface Properties plugin
+//
+//
+// DESCRIPTION:
+// all purpose scriplib interface for Q3Radiant plugins (cf. parse.h)
+//
+
+#ifndef __ISCRIPLIB_H_
+#define __ISCRIPLIB_H_
+
+// {4B115280-95FC-11d3-8EF3-0000E8E8657B}
+static const GUID QERScripLibTable_GUID =
+{ 0x4b115280, 0x95fc, 0x11d3, { 0x8e, 0xf3, 0x0, 0x0, 0xe8, 0xe8, 0x65, 0x7b } };
+
+typedef qboolean (WINAPI* PFN_GETTOKEN) (qboolean crossline);
+typedef void (WINAPI* PFN_UNGETTOKEN) ();
+// only used to retrieve &token
+typedef char* (WINAPI* PFN_TOKEN) ();
+
+struct _QERScripLibTable
+{
+ float m_fVersion;
+ int m_nSize;
+ PFN_GETTOKEN m_pfnGetToken;
+ PFN_UNGETTOKEN m_pfnUnGetToken;
+ PFN_TOKEN m_pfnToken;
+};
+
+#endif \ No newline at end of file
diff --git a/q3radiant/isurfaceplugin.h b/q3radiant/isurfaceplugin.h
new file mode 100755
index 0000000..14c55b6
--- /dev/null
+++ b/q3radiant/isurfaceplugin.h
@@ -0,0 +1,216 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//-----------------------------------------------------------------------------
+//
+// $LogFile$
+// $Revision: 1.1.1.4.2.1 $
+// $Author: ttimo $
+// $Date: 2000/02/13 17:25:04 $
+// $Log: isurfaceplugin.h,v $
+// Revision 1.1.1.4.2.1 2000/02/13 17:25:04 ttimo
+// started cleanup
+//
+// Revision 1.1.1.4 2000/01/18 00:17:13 ttimo
+// merging in for RC
+//
+// Revision 1.3 2000/01/17 23:53:44 TBesset
+// ready for merge in sourceforge (RC candidate)
+//
+// Revision 1.2 2000/01/07 16:40:13 TBesset
+// merged from BSP frontend
+//
+// Revision 1.1.1.3 1999/12/29 18:31:28 TBesset
+// Q3Radiant public version
+//
+// Revision 1.1.1.1.2.1 1999/12/29 21:39:45 TBesset
+// updated to update3 from Robert
+//
+// Revision 1.1.1.3 1999/12/29 18:31:28 TBesset
+// Q3Radiant public version
+// Revision 1.1.1.3 1999/12/29 18:31:28 TBesset
+// Q3Radiant public version
+//
+// Revision 1.2 1999/11/22 17:46:48 Timo & Christine
+// merged EARadiant into the main tree
+// bug fixes for Q3Plugin / EAPlugin
+// export for Robert
+//
+// Revision 1.1.2.4 1999/11/20 12:13:02 Timo & Christine
+// first release to Wolfen and Spog
+// with TexTool and DeQbsp3 plugin
+//
+// Revision 1.1.2.3 1999/11/16 14:23:13 Timo & Christine
+// merged 173 into Q3Radiant, EARadiant branch
+// see Timo\changelog.txt for merge log
+//
+// Revision 1.1.2.2 1999/11/14 16:26:15 Timo & Christine
+// first beta of the ritualmap surface plugin
+//
+// Revision 1.1.2.1 1999/10/08 16:28:15 Timo & Christine
+// started plugin extensions for EA features support in Q3Radiant
+// MEAN files plugin, and Surface Properties plugin
+//
+//
+// DESCRIPTION:
+//
+//
+
+#ifndef __ISURFACEPLUGIN_H_
+#define __ISURFACEPLUGIN_H_
+
+#ifndef Q3RADIANT
+
+// this is plugin included, define miptex_t
+//++timo FIXME: move definition into qertypes.h ? or assume plugin knows ?
+#define MIPLEVELS 4
+typedef struct miptex_s
+{
+ char name[32];
+ unsigned width, height;
+ unsigned offsets[MIPLEVELS]; // four mip maps stored
+ char animname[32]; // next frame in animation chain
+ int flags;
+ int contents;
+ int value;
+} miptex_t;
+
+#endif
+
+/*
+// there's a void* in each qtexture_t, must be casted to a IPluginQTexture*
+class IPluginQTexture
+{
+public:
+ // Increment the number of references to this object
+ virtual void IncRef () = 0;
+ // Decrement the reference count
+ virtual void DecRef () = 0;
+ // Init for a miptex_t
+ virtual void InitForMiptex( miptex_t* ) = 0;
+ // set default texdef
+ virtual void SetDefaultTexdef() = 0;
+};
+
+// use this macro
+#define GETPLUGINQTEXTURE(pQTexture) (static_cast<IPluginQTexture *>(pQTexture->pData))
+*/
+
+// there's a void* in each qtexture_t, must be casted to a IPluginTexdef*
+// there's a void* in each face_t, must be casted to a IPluginTexdef*
+// NOTE: IPluginTexdef stores a pointer to the qtexture_t or face_t it's stored in
+// members of IPluginTexdef often access the qtexture_t or face_t they are connected to
+
+// Write texdef needs a function pointer, because Radiant either writes into a FILE or a CMemFile
+typedef void (WINAPI* PFN_QERAPP_MAPPRINTF) ( char *text, ... );
+
+class IPluginTexdef
+{
+public:
+ // Increment the number of references to this object
+ virtual void IncRef () = 0;
+ // Decrement the reference count
+ virtual void DecRef () = 0;
+ // Build a copy of this one, sets refCount to 1
+ virtual IPluginTexdef* Copy() = 0;
+ // refers to a face_t -----------------------
+ // Parse texdef
+ virtual void ParseTexdef () = 0;
+ // Write texdef
+ virtual void WriteTexdef (PFN_QERAPP_MAPPRINTF MapPrintf) = 0;
+ // hook to a face
+ virtual void Hook( face_t* ) = 0;
+ // ------------------------------------------
+ // refers to a qtexture_t -------------------
+ // Init for a miptex_t
+ //++timo NOTE: miptex_t is used only for .WAL format .. a bit outdated
+ virtual void InitForMiptex( miptex_t* ) = 0;
+ // set default texdef
+ virtual void SetDefaultTexdef() = 0;
+ // ------------------------------------------
+ // refers to a patchMesh_t ------------------
+ virtual void ParsePatchTexdef () = 0;
+ // write texdef for a patch
+ virtual void WritePatchTexdef (PFN_QERAPP_MAPPRINTF MapPrintf) = 0;
+ // hook to a patch
+ virtual void Hook( patchMesh_t* ) = 0;
+ // ------------------------------------------
+};
+
+// use this macro
+#define GETPLUGINTEXDEF(pFace) (static_cast<IPluginTexdef *>(pFace->pData))
+
+// this one is used by Radiant to access the surface plugin
+
+// {7DA59920-93D8-11d3-8EF3-0000E8E8657B}
+static const GUID QERPlugSurfaceTable_GUID =
+{ 0x7da59920, 0x93d8, 0x11d3, { 0x8e, 0xf3, 0x0, 0x0, 0xe8, 0xe8, 0x65, 0x7b } };
+
+typedef void (WINAPI* PFN_QERPLUG_DOSURFACE) ();
+typedef bool (WINAPI* PFN_QERPLUG_BYEBYESURFACEDIALOG) ();
+typedef void (WINAPI* PFN_QERPLUG_UPDATESURFACEDIALOG) ();
+// allocates a new IPluginTexdef, linked to a face_t, refCount is set to 1
+typedef IPluginTexdef* (WINAPI* PFN_QERPLUG_TEXDEFALLOC) ( face_t* );
+// allocates a new IPluginTexdef, linked to a qtexture_t, refCount is set to 1
+typedef IPluginTexdef* (WINAPI* PFN_QERPLUG_QTEXTUREALLOC) ( qtexture_t* );
+// allocates a new IPluginTexdef, linked to a patchMesh_t, refCount is set to 1
+typedef IPluginTexdef* (WINAPI* PFN_QERPLUG_PATCHALLOC) ( patchMesh_t* );
+
+struct _QERPlugSurfaceTable
+{
+ int m_nSize;
+ PFN_QERPLUG_BYEBYESURFACEDIALOG m_pfnByeByeSurfaceDialog;
+ PFN_QERPLUG_DOSURFACE m_pfnDoSurface;
+ PFN_QERPLUG_UPDATESURFACEDIALOG m_pfnUpdateSurfaceDialog;
+ PFN_QERPLUG_TEXDEFALLOC m_pfnTexdefAlloc;
+ PFN_QERPLUG_QTEXTUREALLOC m_pfnQTextureAlloc;
+ PFN_QERPLUG_PATCHALLOC m_pfnPatchAlloc;
+};
+
+// this one is used by the plugin to access some Radiant stuff
+
+// {42BAE4C0-9787-11d3-8EF3-0000E8E8657B}
+static const GUID QERAppSurfaceTable_GUID =
+{ 0x42bae4c0, 0x9787, 0x11d3, { 0x8e, 0xf3, 0x0, 0x0, 0xe8, 0xe8, 0x65, 0x7b } };
+
+typedef bool (WINAPI* PFN_PATCHESSELECTED) ();
+// retrieve g_qeglobals.texturewin_t
+//++timo FIXME: this should move in a dedicated table for all g_qeglobals stuff
+typedef texturewin_t* (WINAPI* PFN_QEGLOBALSTEXTUREWIN) ();
+// look for the first selected patch mesh
+//++timo FIXME: this is a convenient func since there's no way to scan patches ( yet )
+typedef patchMesh_t* (WINAPI* PFN_GETSELECTEDPATCH) ();
+typedef void (WINAPI* PFN_PATCHREBUILD) (patchMesh_t *p);
+//++timo FIXME: this one in particular is a hack
+typedef void (WINAPI* PFN_GETTWOSELECTEDPATCH) (patchMesh_t **p1, patchMesh_t **p2);
+
+struct _QERAppSurfaceTable
+{
+ int m_nSize;
+ PFN_PATCHESSELECTED m_pfnOnlyPatchesSelected;
+ PFN_PATCHESSELECTED m_pfnAnyPatchesSelected;
+ PFN_QEGLOBALSTEXTUREWIN m_pfnQeglobalsTexturewin;
+ PFN_GETSELECTEDPATCH m_pfnGetSelectedPatch;
+ PFN_PATCHREBUILD m_pfnPatchRebuild;
+ PFN_GETTWOSELECTEDPATCH m_pfnGetTwoSelectedPatch;
+};
+
+#endif \ No newline at end of file
diff --git a/q3radiant/qerplugin.h b/q3radiant/qerplugin.h
new file mode 100755
index 0000000..97d55d9
--- /dev/null
+++ b/q3radiant/qerplugin.h
@@ -0,0 +1,566 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// QERadiant PlugIns
+//
+//
+
+#ifndef __QERPLUGIN_H__
+#define __QERPLUGIN_H__
+
+#include <windows.h>
+#include "qertypes.h"
+
+#define QER_PLUG_VERSION_1 1.00
+#define QER_PLUG_VERSION 1.70f
+
+#define QER_MAX_NAMELEN 1024
+
+// the editor will look for plugins in two places, the plugins path
+// under the application path, and the path under the basepath as defined
+// in the project (.qe4) file.
+//
+// you can drop any number of new texture, model format DLL's in the standard plugin path
+// but only one plugin that overrides map loading/saving, surface dialog, surface flags, etc..
+// should be used at one time.. if multiples are loaded then the last one loaded will be the
+// active one
+//
+// type of services the plugin supplies, pass any combo of these flags
+// it is assumed the plugin will have a matching function as defined below
+// to correlate to the implied functionality
+//
+// FIXME: after specing this crap i went to a simpler model so this may disappear
+#define QER_PLUG_GAME_TEXTURE 0x0001 // defines new texture format
+#define QER_PLUG_GAME_MODEL 0x0002 // defines new model format
+#define QER_PLUG_GAME_MAP 0x0004 // handles map load/save
+#define QER_PLUG_GAME_SURFACEDLG 0x0008 // handles surface dialog
+#define QER_PLUG_GAME_SURFACEFLAGS 0x0010 // renames surface/content names
+
+// basics
+#define QERPLUG_INIT "QERPlug_Init"
+#define QERPLUG_GETNAME "QERPlug_GetName"
+#define QERPLUG_GETCOMMANDLIST "QERPlug_GetCommandList"
+#define QERPLUG_DISPATCH "QERPlug_Dispatch"
+#define QERPLUG_GETFUNCTABLE "QERPlug_GetFuncTable"
+
+// FIXME: not used, probably should remove
+#define QERPLUG_GETSERVICETPE "QERPlug_GetServiceType"
+
+// game stuff
+#define QERPLUG_GETTEXTUREINFO "QERPlug_GetTextureInfo" // gets a texture info structure
+#define QERPLUG_LOADTEXTURE "QERPlug_LoadTexture" // loads a texture, will return an RGBA structure
+ // and any surface flags/contents for it
+#define QERPLUG_GETTMODELINFO "QERPlug_GetModelInfo" // gets a model info structure
+#define QERPLUG_LOADMODEL "QERPlug_LoadModel" // loads model data from a plugin
+#define QERPLUG_DOSURFACEDLG "QERPlug_DoSurfaceDlg" // runs the surface dialog in a plugin
+ // this is going to get icky
+#define QERPLUG_GETSURFACEFLAGS "QERPlug_GetSurfaceFlags" // gets a list of surface/content flag names from a plugin
+
+struct _QERTextureInfo
+{
+ char m_TextureExtension[QER_MAX_NAMELEN]; // the extension these textures have
+ qboolean m_bHiColor; // if textures are NOT high color, the default
+ // palette (as described inthe qe4 file will be used for gamma correction)
+ // if they are high color, gamma and shading are computed on the fly
+ // based on the rgba data
+ //--bool m_bIsShader; // will probably do q3 shaders this way when i merge
+ qboolean m_bWadStyle; // if this is true, the plugin will be presented with the texture path
+ // defined in the .qe4 file and is expected to preload all the textures
+ qboolean m_bHalfLife; // causes brushes to be saved/parsed without the surface contents/flags/value
+};
+
+struct _QERTextureLoad // returned by a plugin
+{
+ _QERTextureLoad()
+ {
+ memset(reinterpret_cast<void*>(this), 0, sizeof(_QERTextureLoad));
+ };
+
+ ~_QERTextureLoad()
+ {
+ delete []m_pRGBA;
+ delete []m_pName;
+ };
+
+ void makeSpace(int nSize)
+ {
+ m_pRGBA = new unsigned char[nSize+1];
+ };
+
+ void setName(const char* p)
+ {
+ m_pName = new char[strlen(p)+1];
+ strcpy(m_pName, p);
+ };
+
+
+ unsigned char *m_pRGBA; // rgba data (alpha channel is supported and drawn appropriately)
+ int m_nWidth; // width
+ int m_nHeight; // height
+ int m_nContents; // default contents
+ int m_nFlags; // "" flags
+ int m_nValue; // "" value
+ char *m_pName; // name to be referenced in map, build tools, etc.
+};
+
+struct _QERModelInfo
+{
+ char m_ModelExtension[QER_MAX_NAMELEN];
+ bool m_bSkinned;
+ bool m_bMultipart;
+};
+
+struct _QERModelLoad
+{
+ // vertex and skin data
+};
+
+
+// hook functions
+// FIXME: none of the hook stuff works for v1.00
+#define QERPLUG_MAPLOAD "QERPlug_MapLoad"
+#define QERPLUG_MAPSAVE "QERPlug_MapSave"
+
+//=========================================
+// plugin functions version 1.0
+typedef LPCSTR (WINAPI* PFN_QERPLUG_INIT)(HMODULE hApp, HWND hwndMain);
+typedef LPCSTR (WINAPI* PFN_QERPLUG_GETNAME)();
+typedef LPCSTR (WINAPI* PFN_QERPLUG_GETCOMMANDLIST)();
+typedef void (WINAPI* PFN_QERPLUG_DISPATCH)(LPCSTR p, vec3_t vMin, vec3_t vMax, BOOL bSingleBrush);
+typedef LPVOID (WINAPI* PFN_QERPLUG_GETFUNCTABLE)();
+typedef void (WINAPI* PFN_QERPLUG_MAPLOAD)();
+typedef void (WINAPI* PFN_QERPLUG_MAPSAVE)();
+
+// editor defined plugin dispatches
+// these are used to signal the completion after a 'Get' function is called in the editor
+#define QERPLUG_DISPATCH_POINTDONE "PointDone"
+#define QERPLUG_DISPATCH_BRUSHDONE "BrushDone"
+
+// v1.5
+//
+// Texture loading
+// returns a ptr to _QERTextureInfo
+typedef LPVOID (WINAPI* PFN_QERPLUG_GETTEXTUREINFO)();
+//
+// loads a texture by calling the texture load func in the editor (defined below)
+// transparency (for water, fog, lava, etc.. ) can be emulated in the editor
+// by passing in appropriate alpha data or by setting the appropriate surface flags
+// expected by q2 (which the editor will use.. )
+typedef void (WINAPI* PFN_QERPLUG_LOADTEXTURE)(LPCSTR pFilename);
+
+// v1.6
+typedef LPVOID (WINAPI* PFN_QERPLUG_GETSURFACEFLAGS)();
+
+// v1.7
+// if exists in plugin, gets called between INIT and GETCOMMANDLIST
+// the plugin can register the EClasses he wants to handle
+//++timo TODO: this has got to move into the table, and be requested by QERPlug_RequestInterface
+//++timo FIXME: the LPVOID parameter must be casted to an IEpair interface
+#define QERPLUG_REGISTERPLUGINENTITIES "QERPlug_RegisterPluginEntities"
+typedef void (WINAPI* PFN_QERPLUG_REGISTERPLUGINENTITIES)( LPVOID );
+// if exists in plugin, gets called between INIT and GETCOMMANDLIST
+// the plugin can Init all it needs for surface properties
+#define QERPLUG_INITSURFACEPROPERTIES "QERPlug_InitSurfaceProperties"
+typedef void (WINAPI* PFN_QERPLUG_INITSURFACEPROPERTIES)();
+// if Radiant needs to use a particular set of commands, it can request the plugin to fill a func table
+// this is similar to PFN_QERAPP_REQUESTINTERFACE
+#define QERPLUG_REQUESTINTERFACE "QERPlug_RequestInterface"
+typedef int (WINAPI* PFN_QERPLUG_REQUESTINTERFACE)( REFGUID, LPVOID );
+
+//=========================================
+// editor functions
+
+// There are 3 potential brush handle lists
+// 1. the list that contains brushes a plugin creates using CreateBrushHandle
+// 2. the selected brush list (brushes the user has selected)
+// 3. the active brush list (brushes in the map that are not selected)
+//
+// In general, the same things can be done to brush handles (face manip, delete brushhandle, etc.. ) in each
+// list. There are a few exceptions.
+// 1. You cannot commit a selected or active brush handle to the map. This is because it is already in the map.
+// 2. You cannot bind brush handles from the selected or active brush list to an entity. As of v1.0 of the plugins
+// the only way for a plugin to create entities is to create a brush handles (or a list of handles) and then bind
+// them to an entity. This will commit the brush(s) and/or the entities to the map as well.
+//
+// To use the active or selected brush lists, you must first allocate them (which returns a count) and then
+// release them when you are finish manipulating brushes in one of those lists.
+
+//++timo NOTE : the #defines here are never used, but can help finding where things are done in the editor
+
+// brush manipulation routines
+#define QERAPP_CREATEBRUSH "QERApp_CreateBrush"
+#define QERAPP_CREATEBRUSHHANDLE "QERApp_CreateBrushHandle"
+#define QERAPP_DELETEBRUSHHANDLE "QERApp_DeleteBrushHandle"
+#define QERAPP_COMMITBRUSHHANDLETOMAP "QERApp_CommitBrushHandleToMap"
+//++timo not implemented .. remove
+// #define QERAPP_BINDHANDLESTOENTITY "QERApp_BindHandlesToEntity"
+#define QERAPP_ADDFACE "QERApp_AddFace"
+#define QERAPP_ADDFACEDATA "QERApp_AddFaceData"
+#define QERAPP_GETFACECOUNT "QERApp_GetFaceCount"
+#define QERAPP_GETFACEDATA "QERApp_GetFaceData"
+#define QERAPP_SETFACEDATA "QERApp_SetFaceData"
+#define QERAPP_DELETEFACE "QERApp_DeleteFace"
+#define QERAPP_TEXTUREBRUSH "QERApp_TextureBrush"
+#define QERAPP_BUILDBRUSH "QERApp_BuildBrush" // PGM
+#define QERAPP_SELECTEDBRUSHCOUNT "QERApp_SelectedBrushCount"
+#define QERAPP_ALLOCATESELECTEDBRUSHHANDLES "QERApp_AllocateSelectedBrushHandles"
+#define QERAPP_RELEASESELECTEDBRUSHHANDLES "QERApp_ReleaseSelectedBrushHandles"
+#define QERAPP_GETSELECTEDBRUSHHANDLE "QERApp_GetSelectedBrushHandle"
+#define QERAPP_ACTIVEBRUSHCOUNT "QERApp_ActiveBrushCount"
+#define QERAPP_ALLOCATEACTIVEBRUSHHANDLES "QERApp_AllocateActiveBrushHandles"
+#define QERAPP_RELEASEACTIVEBRUSHHANDLES "QERApp_ReleaseActiveBrushHandles"
+#define QERAPP_GETACTIVEBRUSHHANDLE "QERApp_GetActiveBrushHandle"
+
+// texture stuff
+#define QERAPP_TEXTURECOUNT "QERApp_TextureCount"
+#define QERAPP_GETTEXTURE "QERApp_GetTexture"
+#define QERAPP_GETCURRENTTEXTURE "QERApp_GetCurrentTexture"
+#define QERAPP_SETCURRENTTEXTURE "QERApp_SetCurrentTexture"
+
+// selection
+#define QERAPP_DELETESELECTION "QERApp_DeleteSelection"
+#define QERAPP_SELECTBRUSH "QERApp_SelectBrush" // PGM
+#define QERAPP_DESELECTBRUSH "QERApp_DeselectBrush" // PGM
+#define QERAPP_DESELECTALLBRUSHES "QERApp_DeselectAllBrushes" // PGM
+
+// data gathering
+#define QERAPP_GETPOINTS "QERApp_GetPoints"
+#define QERAPP_SELECTBRUSHES "QERApp_GetBrushes"
+
+// entity class stuff
+// the entity handling is very basic for 1.0
+#define QERAPP_GETECLASSCOUNT "QERApp_GetEClassCount"
+#define QERAPP_GETECLASS "QERApp_GetEClass"
+
+// misc
+#define QERAPP_SYSMSG "QERApp_SysMsg"
+#define QERAPP_INFOMSG "QERApp_InfoMsg"
+#define QERAPP_HIDEINFOMSG "QERApp_HideInfoMsg"
+#define QERAPP_POSITIONVIEW "QERApp_PositionView" // PGM
+#define QERAPP_RESET_PLUGINS "QERApp_ResetPlugins"
+
+// texture loading
+#define QERAPP_LOADTEXTURERGBA "QERApp_LoadTextureRGBA"
+
+// FIXME: the following are not implemented yet
+// hook registrations
+#define QERAPP_REGISTER_MAPLOADFUNC "QERApp_Register_MapLoadFunc"
+#define QERAPP_REGISTER_MAPSAVEFUNC "QERApp_Register_MapSaveFunc"
+
+// FIXME: the following are not implemented yet
+#define QERAPP_REGISTER_PROJECTLOADFUNC "QERApp_Register_ProjectLoadFunc"
+#define QERAPP_REGISTER_MOUSEHANDLER "QERApp_Register_MouseHandler"
+#define QERAPP_REGISTER_KEYHANDLER "QERApp_Register_KeyHandler"
+
+// FIXME: new primtives do not work in v1.00
+// primitives are new types of things in the map
+// for instance, the Q3 curves could have been done as
+// primitives instead of being built in
+// it will be a plugins responsibility to hook the map load and save funcs to load
+// and/or save any additional data (like new primitives of some type)
+// the editor will call each registered renderer during the rendering process to repaint
+// any primitives the plugin owns
+// each primitive object has a temporary sibling brush that lives in the map
+// FIXME: go backwards on this a bit.. orient it more towards the temp brush mode as it will be cleaner
+// basically a plugin will hook the map load and save and will add the primitives to the map.. this will
+// produce a temporary 'primitive' brush and the appropriate renderer will be called as well as the
+// edit handler (for edge drags, sizes, rotates, etc.. ) and the vertex maker will be called when vertex
+// mode is attemped on the brush.. there will need to be a GetPrimitiveBounds callback in the edit handler
+// so the brush can resize appropriately as needed.. this might be the plugins responsibility to set the
+// sibling brushes size.. it will then be the plugins responsibility to hook map save to save the primitives
+// as the editor will discard any temp primitive brushes.. (there probably needs to be some kind of sanity check
+// here as far as keeping the brushes and the plugin in sync.. i suppose the edit handler can deal with all of that
+// crap but it looks like a nice place for a mess)
+#define QERAPP_REGISTER_PRIMITIVE "QERApp_Register_Primitive"
+#define QERAPP_REGISTER_RENDERER "QERApp_Register_Renderer"
+#define QERAPP_REGISTER_EDITHANDLER "QERApp_Register_EditHandler"
+#define QERAPP_REGISTER_VERTEXMAKER "QERApp_Register_VertexMaker"
+#define QERAPP_ADDPRIMITIVE "QERApp_AddPrimitive"
+
+// v1.70
+#define QERAPP_GETENTITYCOUNT "QERApp_GetEntityCount"
+#define QERAPP_GETENTITYHANDLE "QERApp_GetEntityHandle"
+//++timo not implemented for the moment
+// #define QERAPP_GETENTITYINFO "QERApp_GetEntityInfo"
+//++timo does the keyval need some more funcs to add/remove ?
+// get the pointer and do the changes yourself
+#define QERAPP_GETENTITYKEYVALLIST "QERApp_GetKeyValList"
+#define QERAPP_ALLOCATEEPAIR "QERApp_AllocateEpair"
+// will check current KeyVal list is NULL, otherwise use GetKeyValList
+#define QERAPP_SETENTITYKEYVALLIST "QERApp_SetKeyValList"
+#define QERAPP_ALLOCATEENTITYBRUSHHANDLES "QERApp_AllocateEntityBrushHandles"
+#define QERAPP_RELEASEENTITYBRUSHHANDLES "QERApp_ReleaseEntityBrushHandles"
+#define QERAPP_GETENTITYBRUSHHANDLE "QERApp_GetEntityBrushHandle"
+#define QERAPP_CREATEENTITYHANDLE "QERApp_CreateEntityHandle"
+#define QERAPP_COMMITBRUSHHANDLETOENTITY "QERApp_CommitBrushHandleToEntity"
+#define QERAPP_COMMITENTITYHANDLETOMAP "QERApp_CommitEntityHandleToMap"
+#define QERAPP_SETSCREENUPDATE "QERApp_SetScreenUpdate"
+#define QERAPP_BUILDBRUSH2 "QERApp_BuildBrush2"
+
+struct _QERPointData
+{
+ int m_nCount;
+ vec3_t *m_pVectors;
+};
+
+struct _QERFaceData
+{
+ char m_TextureName[QER_MAX_NAMELEN];
+ int m_nContents;
+ int m_nFlags;
+ int m_nValue;
+ float m_fShift[2];
+ float m_fRotate;
+ float m_fScale[2];
+ vec3_t m_v1, m_v2, m_v3;
+ // brush primitive additions
+ qboolean m_bBPrimit;
+ brushprimit_texdef_t brushprimit_texdef;
+};
+
+typedef void (WINAPI* PFN_QERAPP_CREATEBRUSH)(vec3_t vMin, vec3_t vMax);
+
+typedef LPVOID (WINAPI* PFN_QERAPP_CREATEBRUSHHANDLE)();
+typedef void (WINAPI* PFN_QERAPP_DELETEBRUSHHANDLE)(LPVOID pv);
+typedef void (WINAPI* PFN_QERAPP_COMMITBRUSHHANDLETOMAP)(LPVOID pv);
+typedef void (WINAPI* PFN_QERAPP_ADDFACE)(LPVOID pv, vec3_t v1, vec3_t v2, vec3_t v3);
+
+typedef void (WINAPI* PFN_QERAPP_ADDFACEDATA)(LPVOID pv, _QERFaceData *pData);
+typedef int (WINAPI* PFN_QERAPP_GETFACECOUNT)(LPVOID pv);
+typedef _QERFaceData* (WINAPI* PFN_QERAPP_GETFACEDATA)(LPVOID pv, int nFaceIndex);
+typedef void (WINAPI* PFN_QERAPP_SETFACEDATA)(LPVOID pv, int nFaceIndex, _QERFaceData *pData);
+typedef void (WINAPI* PFN_QERAPP_DELETEFACE)(LPVOID pv, int nFaceIndex);
+typedef void (WINAPI* PFN_QERAPP_TEXTUREBRUSH)(LPVOID pv, LPCSTR pName);
+typedef void (WINAPI* PFN_QERAPP_BUILDBRUSH)(LPVOID pv); // PGM
+typedef void (WINAPI* PFN_QERAPP_SELECTBRUSH)(LPVOID pv); // PGM
+typedef void (WINAPI* PFN_QERAPP_DESELECTBRUSH)(LPVOID pv); // PGM
+typedef void (WINAPI* PFN_QERAPP_DESELECTALLBRUSHES)(); // PGM
+
+typedef void (WINAPI* PFN_QERAPP_DELETESELECTION)();
+typedef void (WINAPI* PFN_QERAPP_GETPOINTS)(int nMax, _QERPointData *pData, LPCSTR pMsg);
+typedef void (WINAPI* PFN_QERAPP_SYSMSG)(LPCSTR pMsg);
+typedef void (WINAPI* PFN_QERAPP_INFOMSG)(LPCSTR pMsg);
+typedef void (WINAPI* PFN_QERAPP_HIDEINFOMSG)();
+typedef void (WINAPI* PFN_QERAPP_POSITIONVIEW)(vec3_t v1, vec3_t v2); //PGM
+
+typedef int (WINAPI* PFN_QERAPP_SELECTEDBRUSHCOUNT)();
+typedef int (WINAPI* PFN_QERAPP_ALLOCATESELECTEDBRUSHHANDLES)();
+typedef void (WINAPI* PFN_QERAPP_RELEASESELECTEDBRUSHHANDLES)();
+typedef LPVOID (WINAPI* PFN_QERAPP_GETSELECTEDBRUSHHANDLE)(int nIndex);
+
+typedef int (WINAPI* PFN_QERAPP_ACTIVEBRUSHCOUNT)();
+typedef int (WINAPI* PFN_QERAPP_ALLOCATEACTIVEBRUSHHANDLES)();
+typedef void (WINAPI* PFN_QERAPP_RELEASEACTIVEBRUSHHANDLES)();
+typedef LPVOID (WINAPI* PFN_QERAPP_GETACTIVEBRUSHHANDLE)(int nIndex);
+
+typedef int (WINAPI* PFN_QERAPP_TEXTURECOUNT)();
+typedef LPCSTR (WINAPI* PFN_QERAPP_GETTEXTURE)(int nIndex);
+typedef LPCSTR (WINAPI* PFN_QERAPP_GETCURRENTTEXTURE)();
+typedef void (WINAPI* PFN_QERAPP_SETCURRENTTEXTURE)(LPCSTR pName);
+
+typedef void (WINAPI* PFN_QERAPP_REGISTERMAPLOAD)(LPVOID vp);
+typedef void (WINAPI* PFN_QERAPP_REGISTERMAPSAVE)(LPVOID vp);
+
+typedef int (WINAPI* PFN_QERAPP_GETECLASSCOUNT)();
+typedef LPCSTR (WINAPI* PFN_QERAPP_GETECLASS)(int nIndex);
+
+typedef void (WINAPI* PFN_QERAPP_RESETPLUGINS)();
+//--typedef int (WINAPI* PFN_QERAPP_GETENTITYCOUNT)();
+
+
+// called by texture loaders for each texture loaded
+typedef void (WINAPI* PFN_QERAPP_LOADTEXTURERGBA)(LPVOID vp);
+
+//--typedef LPCSTR (WINAPI* PFN_QERAPP_GETENTITY)(int nIndex);
+
+// v1.70
+typedef int (WINAPI* PFN_QERAPP_GETENTITYCOUNT)();
+typedef LPVOID (WINAPI* PFN_QERAPP_GETENTITYHANDLE)(int nIndex);
+typedef epair_t** (WINAPI* PFN_QERAPP_GETENTITYKEYVALLIST)(LPVOID vp);
+typedef epair_t* (WINAPI* PFN_QERAPP_ALLOCATEEPAIR)( char*, char* );
+typedef void (WINAPI* PFN_QERAPP_SETENTITYKEYVALLIST)(LPVOID vp, epair_t* ep);
+typedef int (WINAPI* PFN_QERAPP_ALLOCATEENTITYBRUSHHANDLES)(LPVOID vp);
+typedef void (WINAPI* PFN_QERAPP_RELEASEENTITYBRUSHHANDLES)();
+typedef LPVOID (WINAPI* PFN_QERAPP_GETENTITYBRUSHHANDLE)(int nIndex);
+typedef LPVOID (WINAPI* PFN_QERAPP_CREATEENTITYHANDLE)();
+typedef void (WINAPI* PFN_QERAPP_COMMITBRUSHHANDLETOENTITY)( LPVOID vpBrush, LPVOID vpEntity);
+typedef void (WINAPI* PFN_QERAPP_COMMITENTITYHANDLETOMAP)(LPVOID vp);
+typedef void (WINAPI* PFN_QERAPP_SETSCREENUPDATE)(int bScreenUpdate);
+// this one uses window flags defined in qertypes.h
+typedef void (WINAPI* PFN_QERAPP_SYSUPDATEWINDOWS)(int bits);
+//++timo remove this one
+typedef void (WINAPI* PFN_QERAPP_BUILDBRUSH2)(LPVOID vp, int bConvert);
+// Radiant functions for Plugin Entities
+// will look for the value of the correponding key in the project epairs
+typedef char* (WINAPI* PFN_QERAPP_READPROJECTKEY)(char* );
+// will scan the file, parse the first EClass found, and associate it to the caller plugin
+// will only read first EClass in the file, and return true/false
+typedef int (WINAPI* PFN_QERAPP_SCANFILEFORECLASS)(char* );
+// plugins can request additional interfaces from the editor when they need specific services
+typedef int (WINAPI* PFN_QERAPP_REQUESTINTERFACE)( REFGUID, LPVOID );
+// use this one for errors, Radiant will stop after the "edit preferences" dialog
+typedef void (WINAPI* PFN_QERAPP_ERRORMSG)(LPCSTR pMsg);
+// use to gain read access to the project epairs
+// FIXME: removed, accessed through QERPlug_RegisterPluginEntities with the IEpair interface
+// typedef void (WINAPI* PFN_QERAPP_GETPROJECTEPAIR)(epair_t **);
+// used to allocate and read a buffer
+//++timo NOTE: perhaps this would need moving to some kind of dedicated interface
+typedef int (WINAPI* PFN_QERAPP_LOADFILE)(const char *pLocation, void ** buffer);
+typedef char* (WINAPI* PFN_QERAPP_EXPANDRELETIVEPATH)(char *);
+typedef void (WINAPI* PFN_QERAPP_QECONVERTDOSTOUNIXNAME)( char *dst, const char *src );
+typedef int (WINAPI* PFN_QERAPP_HASSHADER)(const char *);
+typedef int (WINAPI* PFN_QERAPP_TEXTURELOADSKIN)(char *pName, int *pnWidth, int *pnHeight);
+// free memory previously allocated by Radiant
+// NOTE: this is dirty
+typedef void (WINAPI* PFN_QERAPP_RADIANTFREE)( void * );
+// retrieves the path to the engine from the preferences dialog box
+typedef char* (WINAPI* PFN_QERAPP_GETGAMEPATH)();
+// retrieves full Radiant path
+typedef char* (WINAPI* PFN_QERAPP_GETQERPATH)();
+
+// patches in/out
+// NOTE: this is a bit different from the brushes in/out, no LPVOID handles this time
+// use int indexes instead
+// if you call AllocateActivePatchHandles, you'll be playing with active patches
+// AllocateSelectedPatcheHandles for selected stuff
+// a call to CreatePatchHandle will move you to a seperate index table
+typedef int (WINAPI* PFN_QERAPP_ALLOCATEACTIVEPATCHHANDLES) ();
+typedef int (WINAPI* PFN_QERAPP_ALLOCATESELECTEDPATCHHANDLES) ();
+typedef void (WINAPI* PFN_QERAPP_RELEASEPATCHHANDLES) ();
+typedef patchMesh_t* (WINAPI* PFN_QERAPP_GETPATCHDATA) (int);
+typedef void (WINAPI* PFN_QERAPP_DELETEPATCH) (int);
+typedef int (WINAPI* PFN_QERAPP_CREATEPATCHHANDLE) ();
+// when commiting, only a few patchMesh_t members are relevant:
+// int width, height; // in control points, not patches
+// int contents, flags, value, type;
+// drawVert_t ctrl[MAX_PATCH_WIDTH][MAX_PATCH_HEIGHT];
+// once you have commited the index is still available, if the patch handle was allocated by you
+// then you can re-use the index to commit other patches .. otherwise you can change existing patches
+// NOTE: the handle thing for plugin-allocated patches is a bit silly (nobody's perfect)
+// TODO: change current behaviour to an index = 0 to tell Radiant to allocate, other indexes to existing patches
+// patch is selected after a commit
+// you can add an optional texture / shader name .. if NULL will use the current texture
+typedef void (WINAPI* PFN_QERAPP_COMMITPATCHHANDLETOMAP) (int, patchMesh_t* pMesh, char *texName);
+
+// FIXME:
+// add map format extensions
+// add texture format handlers
+// add surface dialog handler
+// add model handler/displayer
+
+// v1 func table
+// Plugins need to declare one of these and implement the getfunctable as described above
+struct _QERFuncTable_1
+{
+ float m_fVersion;
+ int m_nSize;
+ PFN_QERAPP_CREATEBRUSH m_pfnCreateBrush;
+ PFN_QERAPP_CREATEBRUSHHANDLE m_pfnCreateBrushHandle;
+ PFN_QERAPP_DELETEBRUSHHANDLE m_pfnDeleteBrushHandle;
+ PFN_QERAPP_COMMITBRUSHHANDLETOMAP m_pfnCommitBrushHandle;
+ PFN_QERAPP_ADDFACE m_pfnAddFace;
+ PFN_QERAPP_ADDFACEDATA m_pfnAddFaceData;
+ PFN_QERAPP_GETFACEDATA m_pfnGetFaceData;
+ PFN_QERAPP_GETFACECOUNT m_pfnGetFaceCount;
+ PFN_QERAPP_SETFACEDATA m_pfnSetFaceData;
+ PFN_QERAPP_DELETEFACE m_pfnDeleteFace;
+ PFN_QERAPP_TEXTUREBRUSH m_pfnTextureBrush;
+ PFN_QERAPP_BUILDBRUSH m_pfnBuildBrush; // PGM
+ PFN_QERAPP_SELECTBRUSH m_pfnSelectBrush; // PGM
+ PFN_QERAPP_DESELECTBRUSH m_pfnDeselectBrush; // PGM
+ PFN_QERAPP_DESELECTALLBRUSHES m_pfnDeselectAllBrushes; // PGM
+
+ PFN_QERAPP_DELETESELECTION m_pfnDeleteSelection;
+ PFN_QERAPP_GETPOINTS m_pfnGetPoints;
+ PFN_QERAPP_SYSMSG m_pfnSysMsg;
+ PFN_QERAPP_INFOMSG m_pfnInfoMsg;
+ PFN_QERAPP_HIDEINFOMSG m_pfnHideInfoMsg;
+ PFN_QERAPP_POSITIONVIEW m_pfnPositionView; // PGM
+
+ PFN_QERAPP_SELECTEDBRUSHCOUNT m_pfnSelectedBrushCount;
+ PFN_QERAPP_ALLOCATESELECTEDBRUSHHANDLES m_pfnAllocateSelectedBrushHandles;
+ PFN_QERAPP_RELEASESELECTEDBRUSHHANDLES m_pfnReleaseSelectedBrushHandles;
+ PFN_QERAPP_GETSELECTEDBRUSHHANDLE m_pfnGetSelectedBrushHandle;
+
+ PFN_QERAPP_ACTIVEBRUSHCOUNT m_pfnActiveBrushCount;
+ PFN_QERAPP_ALLOCATEACTIVEBRUSHHANDLES m_pfnAllocateActiveBrushHandles;
+ PFN_QERAPP_RELEASEACTIVEBRUSHHANDLES m_pfnReleaseActiveBrushHandles;
+ PFN_QERAPP_GETACTIVEBRUSHHANDLE m_pfnGetActiveBrushHandle;
+
+ //++timo this would need to be removed and replaced by the IShaders interface
+ PFN_QERAPP_TEXTURECOUNT m_pfnTextureCount;
+ PFN_QERAPP_GETTEXTURE m_pfnGetTexture;
+ PFN_QERAPP_GETCURRENTTEXTURE m_pfnGetCurrentTexture;
+ PFN_QERAPP_SETCURRENTTEXTURE m_pfnSetCurrentTexture;
+
+ PFN_QERAPP_GETECLASSCOUNT m_pfnGetEClassCount;
+ PFN_QERAPP_GETECLASS m_pfnGetEClass;
+ PFN_QERAPP_RESETPLUGINS m_pfnResetPlugins;
+ // v1.00 ends here
+ // v1.50 starts here
+ PFN_QERAPP_LOADTEXTURERGBA m_pfnLoadTextureRGBA;
+ // v1.50 ends here
+ // v1.70 starts here
+ PFN_QERAPP_GETENTITYCOUNT m_pfnGetEntityCount;
+ PFN_QERAPP_GETENTITYHANDLE m_pfnGetEntityHandle;
+ PFN_QERAPP_GETENTITYKEYVALLIST m_pfnGetEntityKeyValList;
+ PFN_QERAPP_SETENTITYKEYVALLIST m_pfnSetEntityKeyValList;
+ PFN_QERAPP_ALLOCATEENTITYBRUSHHANDLES m_pfnAllocateEntityBrushHandles;
+ PFN_QERAPP_RELEASEENTITYBRUSHHANDLES m_pfnReleaseEntityBrushHandles;
+ PFN_QERAPP_GETENTITYBRUSHHANDLE m_pfnGetEntityBrushHandle;
+ PFN_QERAPP_CREATEENTITYHANDLE m_pfnCreateEntityHandle;
+ PFN_QERAPP_COMMITBRUSHHANDLETOENTITY m_pfnCommitBrushHandleToEntity;
+ PFN_QERAPP_COMMITENTITYHANDLETOMAP m_pfnCommitEntityHandleToMap;
+ PFN_QERAPP_ALLOCATEEPAIR m_pfnAllocateEpair;
+ PFN_QERAPP_SETSCREENUPDATE m_pfnSetScreenUpdate;
+ PFN_QERAPP_SYSUPDATEWINDOWS m_pfnSysUpdateWindows;
+ PFN_QERAPP_BUILDBRUSH2 m_pfnBuildBrush2;
+ // Radiant functions for Plugin Entities
+ PFN_QERAPP_READPROJECTKEY m_pfnReadProjectKey;
+ PFN_QERAPP_SCANFILEFORECLASS m_pfnScanFileForEClass;
+ // plugins can request additional interfaces
+ PFN_QERAPP_REQUESTINTERFACE m_pfnRequestInterface;
+ PFN_QERAPP_ERRORMSG m_pfnErrorMsg;
+ // loading a file into a buffer
+ PFN_QERAPP_LOADFILE m_pfnLoadFile;
+ PFN_QERAPP_EXPANDRELETIVEPATH m_pfnExpandReletivePath;
+ PFN_QERAPP_QECONVERTDOSTOUNIXNAME m_pfnQE_ConvertDOSToUnixName;
+ PFN_QERAPP_HASSHADER m_pfnHasShader;
+ PFN_QERAPP_TEXTURELOADSKIN m_pfnTexture_LoadSkin;
+ PFN_QERAPP_RADIANTFREE m_pfnRadiantFree;
+ PFN_QERAPP_GETGAMEPATH m_pfnGetGamePath;
+ PFN_QERAPP_GETQERPATH m_pfnGetQERPath;
+ // patches in / out
+ PFN_QERAPP_ALLOCATEACTIVEPATCHHANDLES m_pfnAllocateActivePatchHandles;
+ PFN_QERAPP_ALLOCATESELECTEDPATCHHANDLES m_pfnAllocateSelectedPatchHandles;
+ PFN_QERAPP_RELEASEPATCHHANDLES m_pfnReleasePatchHandles;
+ PFN_QERAPP_GETPATCHDATA m_pfnGetPatchData;
+ PFN_QERAPP_DELETEPATCH m_pfnDeletePatch;
+ PFN_QERAPP_CREATEPATCHHANDLE m_pfnCreatePatchHandle;
+ PFN_QERAPP_COMMITPATCHHANDLETOMAP m_pfnCommitPatchHandleToMap;
+};
+
+
+//--typedef int (WINAPI* PFN_QERAPP_BRUSHCOUNT )();
+//--typedef brush_t* (WINAPI* PFN_QERAPP_GETBRUSH )();
+//--typedef void (WINAPI* PFN_QERAPP_DELETEBRUSH )();
+
+#endif \ No newline at end of file
diff --git a/q3radiant/res/BEVEL.BMP b/q3radiant/res/BEVEL.BMP
new file mode 100755
index 0000000..5c2dcd6
--- /dev/null
+++ b/q3radiant/res/BEVEL.BMP
Binary files differ
diff --git a/q3radiant/res/BITMAP2.BMP b/q3radiant/res/BITMAP2.BMP
new file mode 100755
index 0000000..7982fa2
--- /dev/null
+++ b/q3radiant/res/BITMAP2.BMP
Binary files differ
diff --git a/q3radiant/res/BMP00001.BMP b/q3radiant/res/BMP00001.BMP
new file mode 100755
index 0000000..bc656df
--- /dev/null
+++ b/q3radiant/res/BMP00001.BMP
Binary files differ
diff --git a/q3radiant/res/BMP00002.BMP b/q3radiant/res/BMP00002.BMP
new file mode 100755
index 0000000..7233996
--- /dev/null
+++ b/q3radiant/res/BMP00002.BMP
Binary files differ
diff --git a/q3radiant/res/BMP0002.BMP b/q3radiant/res/BMP0002.BMP
new file mode 100755
index 0000000..50ab191
--- /dev/null
+++ b/q3radiant/res/BMP0002.BMP
Binary files differ
diff --git a/q3radiant/res/DEFTEX.WAL b/q3radiant/res/DEFTEX.WAL
new file mode 100755
index 0000000..498b56a
--- /dev/null
+++ b/q3radiant/res/DEFTEX.WAL
Binary files differ
diff --git a/q3radiant/res/ENDCAP.BMP b/q3radiant/res/ENDCAP.BMP
new file mode 100755
index 0000000..cb25691
--- /dev/null
+++ b/q3radiant/res/ENDCAP.BMP
Binary files differ
diff --git a/q3radiant/res/IBEVEL.BMP b/q3radiant/res/IBEVEL.BMP
new file mode 100755
index 0000000..4624f5d
--- /dev/null
+++ b/q3radiant/res/IBEVEL.BMP
Binary files differ
diff --git a/q3radiant/res/IENDCAP.BMP b/q3radiant/res/IENDCAP.BMP
new file mode 100755
index 0000000..892bbde
--- /dev/null
+++ b/q3radiant/res/IENDCAP.BMP
Binary files differ
diff --git a/q3radiant/res/Q.BMP b/q3radiant/res/Q.BMP
new file mode 100755
index 0000000..759b87c
--- /dev/null
+++ b/q3radiant/res/Q.BMP
Binary files differ
diff --git a/q3radiant/res/RADIANT3.GIF b/q3radiant/res/RADIANT3.GIF
new file mode 100755
index 0000000..adbe1f5
--- /dev/null
+++ b/q3radiant/res/RADIANT3.GIF
Binary files differ
diff --git a/q3radiant/res/Radiant.ico b/q3radiant/res/Radiant.ico
new file mode 100755
index 0000000..f644e9a
--- /dev/null
+++ b/q3radiant/res/Radiant.ico
Binary files differ
diff --git a/q3radiant/res/Radiant.rc2 b/q3radiant/res/Radiant.rc2
new file mode 100755
index 0000000..84a0b5d
--- /dev/null
+++ b/q3radiant/res/Radiant.rc2
@@ -0,0 +1,13 @@
+//
+// RADIANT.RC2 - resources Microsoft Visual C++ does not edit directly
+//
+
+#ifdef APSTUDIO_INVOKED
+ #error this file is not editable by Microsoft Visual C++
+#endif //APSTUDIO_INVOKED
+
+
+/////////////////////////////////////////////////////////////////////////////
+// Add manually edited resources here...
+
+/////////////////////////////////////////////////////////////////////////////
diff --git a/q3radiant/res/RadiantDoc.ico b/q3radiant/res/RadiantDoc.ico
new file mode 100755
index 0000000..3288c6f
--- /dev/null
+++ b/q3radiant/res/RadiantDoc.ico
Binary files differ
diff --git a/q3radiant/res/TOOLBAR1.BMP b/q3radiant/res/TOOLBAR1.BMP
new file mode 100755
index 0000000..55e05ec
--- /dev/null
+++ b/q3radiant/res/TOOLBAR1.BMP
Binary files differ
diff --git a/q3radiant/res/TOOLBAR2.BMP b/q3radiant/res/TOOLBAR2.BMP
new file mode 100755
index 0000000..dfa5dd1
--- /dev/null
+++ b/q3radiant/res/TOOLBAR2.BMP
Binary files differ
diff --git a/q3radiant/res/Toolbar.bmp b/q3radiant/res/Toolbar.bmp
new file mode 100755
index 0000000..1956dd5
--- /dev/null
+++ b/q3radiant/res/Toolbar.bmp
Binary files differ
diff --git a/q3radiant/res/VIEWDEFA.BMP b/q3radiant/res/VIEWDEFA.BMP
new file mode 100755
index 0000000..30233a8
--- /dev/null
+++ b/q3radiant/res/VIEWDEFA.BMP
Binary files differ
diff --git a/q3radiant/res/VIEWOPPO.BMP b/q3radiant/res/VIEWOPPO.BMP
new file mode 100755
index 0000000..afa4270
--- /dev/null
+++ b/q3radiant/res/VIEWOPPO.BMP
Binary files differ
diff --git a/q3radiant/res/bmp00003.bmp b/q3radiant/res/bmp00003.bmp
new file mode 100755
index 0000000..c7270fd
--- /dev/null
+++ b/q3radiant/res/bmp00003.bmp
Binary files differ
diff --git a/q3radiant/res/icon2.ico b/q3radiant/res/icon2.ico
new file mode 100755
index 0000000..47e4d87
--- /dev/null
+++ b/q3radiant/res/icon2.ico
Binary files differ
diff --git a/q3radiant/res/logo_sm3dfx.bmp b/q3radiant/res/logo_sm3dfx.bmp
new file mode 100755
index 0000000..9a1e106
--- /dev/null
+++ b/q3radiant/res/logo_sm3dfx.bmp
Binary files differ
diff --git a/q3radiant/res/shaderbar.bmp b/q3radiant/res/shaderbar.bmp
new file mode 100755
index 0000000..913de51
--- /dev/null
+++ b/q3radiant/res/shaderbar.bmp
Binary files differ
diff --git a/q3radiant/res/shaderdoc.ico b/q3radiant/res/shaderdoc.ico
new file mode 100755
index 0000000..3288c6f
--- /dev/null
+++ b/q3radiant/res/shaderdoc.ico
Binary files differ
diff --git a/q3radiant/res/shaderframe.ico b/q3radiant/res/shaderframe.ico
new file mode 100755
index 0000000..f644e9a
--- /dev/null
+++ b/q3radiant/res/shaderframe.ico
Binary files differ
diff --git a/q3radiant/resource.h b/q3radiant/resource.h
new file mode 100755
index 0000000..87789cb
--- /dev/null
+++ b/q3radiant/resource.h
@@ -0,0 +1,840 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//{{NO_DEPENDENCIES}}
+// Microsoft Developer Studio generated include file.
+// Used by Radiant.rc
+//
+#define IDSELECT 2
+#define IDOK2 2
+#define ID_APPLY 3
+#define IDD_ABOUTBOX 100
+#define IDR_ACCELERATOR1 104
+#define IDD_CREATE_ENTITY 107
+#define IDD_EDIT_ENTITY 108
+#define IDR_TOOLBAR1 109
+#define IDD_FINDTEXTURE 111
+#define IDD_ENTITY 115
+#define IDR_E_MENU 116
+#define IDD_EDITPROP 117
+#define IDD_GAMMA 118
+#define IDD_FINDBRUSH 119
+#define IDI_ICON1 120
+#define IDD_ROTATE 121
+#define IDD_SIDES 122
+#define IDD_ABOUT 123
+#define IDB_BITMAP1 127
+#define IDD_SURFACE 129
+#define IDR_MAINFRAME 130
+#define IDR_RADIANTYPE 131
+#define IDAPPLY 132
+#define IDS_STRING1 132
+#define ID_BTN_APPLY 133
+#define ID_TESTCAMERA 133
+#define IDC_CHECK_LIVE 134
+#define IDR_POPUP_TEXTURE 135
+#define IDR_POPUP_SELECTION 136
+#define IDR_POPUP_VIEW 137
+#define IDD_DLG_PREFS 139
+#define IDD_DLG_MAPINFO 141
+#define IDD_DLG_ENTITYLIST 142
+#define IDD_DLG_SCRIPTS 143
+#define IDD_DLG_NEWPROJECT 144
+#define IDD_DLG_COMMANDLIST 145
+#define IDR_MENU_DROP 146
+#define IDB_VIEWDEFAULT 147
+#define IDR_MENU_DAIKATANA 147
+#define IDB_VIEWQE4 148
+#define IDB_VIEWDEFAULT2 148
+#define IDR_MENU11 148
+#define IDR_MENU_QUAKE3 148
+#define IDB_VIEW4WAY 149
+#define IDB_VIEWDEFAULT3 149
+#define IDB_VIEWDEFAULT_Z 150
+#define IDB_3DFX 154
+#define IDR_ACCEL_SURFACE 155
+#define IDD_DIALOG_SCALE 156
+#define IDR_MINIACCEL 156
+#define IDD_DIALOG_FINDREPLACE 159
+#define IDD_DIALOG_STAIRS 160
+#define IDD_DIALOG_INPUT 161
+#define IDD_DLG_INFORMATION 162
+#define IDR_TOOLBAR_SCALELOCK 163
+#define IDR_TOOLBAR_ADVANCED 164
+#define IDD_PROJECT 165
+#define IDD_TEXTUREBAR 166
+#define IDD_ADDCMD 167
+#define IDD_DIALOG_TEXTURELIST 168
+#define IDD_DIALOG_NEWPATCH 169
+#define IDR_MENU1 170
+#define IDD_DIALOG_TEXTURELAYOUT 171
+#define IDR_POPUP_ENTITY 171
+#define IDD_DIALOG_CAP 173
+#define IDB_IENDCAP 175
+#define IDB_ENDCAP 176
+#define IDD_DIALOG_THICKEN 176
+#define IDB_BEVEL 177
+#define IDB_IBEVEL 178
+#define IDR_SHADERFRAME 179
+#define IDR_SHADERTYPE 180
+#define IDR_POPUP_GROUP 180
+#define IDR_POPUP_SPLINE 181
+#define IDD_DIALOG1 182
+#define IDD_DIALOG_PATCH 182
+#define IDD_PLAYWAVE 183
+#define IDD_TEXLIST 184
+#define IDD_DIALOG2 186
+#define IDD_DLG_GROUPS 186
+#define IDD_DLG_GROUP 188
+#define IDD_NEWNAME 189
+#define IDB_BITMAP_GROUPS 190
+#define IDD_DLG_CAMERA 194
+#define IDD_DLG_CAMERAEVENT 195
+#define IDD_DLG_CAMERATARGET 196
+#define IDC_BTN_HIDE 1000
+#define IDC_SPIN1 1001
+#define IDC_SPIN2 1002
+#define IDC_RADIO_MOUSE 1002
+#define IDC_SPIN3 1003
+#define IDC_RADIO2 1003
+#define IDC_RADIO_VIEWTYPE 1004
+#define IDC_RADIO3 1004
+#define IDC_RADIO_FALLOFF2 1004
+#define IDC_RADIO_VIEWTYPE2 1005
+#define IDC_BTN_BROWSE 1006
+#define IDC_EDIT_QUAKE2 1007
+#define IDC_RADIO_VIEWTYPE3 1008
+#define IDC_LIST_ENTITIES 1009
+#define IDC_RADIO_VIEWTYPE4 1009
+#define IDC_EDIT_TOTALBRUSHES 1010
+#define IDC_EDIT_PAKFILE 1010
+#define IDC_RADIO_RUNQUAKE 1011
+#define IDC_BTN_BROWSEPAK 1011
+#define IDC_RADIO_RUNQUAKE2 1012
+#define IDC_EDIT_PREFABPATH 1012
+#define IDC_RADIO_RUNQUAKE3 1013
+#define IDC_BTN_BROWSEPREFAB 1013
+#define IDC_CHECK_LOADLAST 1014
+#define IDC_TREE_ENTITY 1015
+#define IDC_CHECK_AUTOSAVE 1015
+#define IDC_CHECK_LOADLASTMAP 1016
+#define IDC_LIST_ENTITY 1017
+#define IDC_EDIT_USERPATH 1017
+#define IDC_ENTITY_COMMENT 1018
+#define IDC_LIST_SCRIPTS 1018
+#define IDC_BTN_BROWSEUSERINI 1018
+#define ID_NEW 1019
+#define IDC_CHECK_USESHADERS 1019
+#define ID_EDIT 1020
+#define IDC_EDIT_NAME 1020
+#define IDC_VALUE 1021
+#define ID_RUN 1021
+#define IDC_LIST_COMMANDS 1021
+#define IDC_KEY 1022
+#define IDC_EDIT_COLOR 1022
+#define IDC_ENTITY_LIST 1023
+#define IDC_CHECK_FACE 1023
+#define IDC_PAIRS 1024
+#define IDC_CHECK_RIGHTCLICK 1024
+#define IDC_CHECK_VERTEX 1025
+#define IDC_CHECK1 1026
+#define IDC_CHECK_TEXTUREWINDOW 1026
+#define IDC_CHECK2 1027
+#define IDC_CHECK_TEXTURETOOLBAR 1027
+#define IDC_CHECK3 1028
+#define IDC_CHECK_LIGHTDRAW 1028
+#define IDC_CHECK4 1029
+#define IDC_CHECK_SNAPT 1029
+#define IDC_CHECK5 1030
+#define IDC_CHECK_3DFX 1030
+#define IDC_CHECK_TEXTURESCROLLBAR 1030
+#define IDC_CHECK6 1031
+#define IDC_CHECK_INTERNALBSP 1031
+#define IDC_CHECK7 1032
+#define IDC_CHECK_RUNQUAKE 1032
+#define IDC_CHECK8 1033
+#define IDC_CHECK_SETGAME 1033
+#define IDC_CHECK9 1034
+#define IDC_CHECK_3DFX2 1034
+#define IDC_CHECK_DISPLAYLISTS 1034
+#define IDC_CHECK10 1035
+#define IDC_EDIT_AUTOSAVE 1035
+#define IDC_CHECK11 1036
+#define IDC_CHECK_PAK 1036
+#define IDC_CHECK12 1037
+#define IDC_BUTTON1 1037
+#define IDC_BTN_APPLYTEXTURESTUFF 1037
+#define IDC_CHECK_QE4PAINTING 1037
+#define IDC_BTN_PLAY 1037
+#define IDC_BTN_ADD 1037
+#define IDC_BTN_TEXTURE 1037
+#define IDC_BTN_PREVIEW 1037
+#define IDC_BTN_ADDTARGET 1037
+#define IDC_ANGLE90 1038
+#define IDC_CHECK13 1038
+#define IDC_SPIN_AUTOSAVE 1038
+#define IDC_BTN_DEL 1038
+#define IDC_ANGLE45 1039
+#define IDC_CHECK14 1039
+#define IDC_BUTTON_CREDITS 1039
+#define IDC_CHECK_SIZEPAINT 1039
+#define IDC_BTN_ADD3 1039
+#define IDC_BTN_EDIT 1039
+#define IDC_ANGLE135 1040
+#define IDC_CHECK15 1040
+#define IDC_EDIT_X 1040
+#define IDC_CHECK_TEXTURELOCALAXIS 1040
+#define IDC_SPIN_UNDO 1040
+#define IDC_ANGLE225 1041
+#define IDC_CHECK16 1041
+#define IDC_CHECK_SNAPSHOTS 1041
+#define IDC_ANGLEUP 1042
+#define IDC_CHECK17 1042
+#define IDC_EDIT_FIND 1042
+#define IDC_SPIN_POINTSIZE 1042
+#define IDC_ANGLE180 1043
+#define IDC_CHECK18 1043
+#define IDC_EDIT_REPLACE 1043
+#define IDC_EDIT_S 1043
+#define IDC_ANGLE315 1044
+#define IDC_CHECK19 1044
+#define IDC_CHECK_SELECTED 1044
+#define IDC_EDIT_T 1044
+#define IDC_ANGLE0 1045
+#define IDC_CHECK20 1045
+#define IDC_CHECK_FORCE 1045
+#define IDC_ANGLE270 1046
+#define IDC_CHECK21 1046
+#define IDC_ANGLEDOWN 1047
+#define IDC_CHECK22 1047
+#define IDC_DELETEKEY 1048
+#define IDC_ADDPAIR 1048
+#define IDC_CHECK23 1048
+#define IDC_DELETEPAIR 1049
+#define IDC_CHECK24 1049
+#define IDC_CHECK25 1050
+#define IDC_SPAWN1 1051
+#define IDC_CHECK26 1051
+#define IDC_SPAWN2 1052
+#define IDC_CHECK27 1052
+#define IDC_SPAWN3 1053
+#define IDC_CHECK28 1053
+#define IDC_SPAWN4 1054
+#define IDC_CHECK29 1054
+#define IDC_SPAWN5 1055
+#define IDC_CHECK30 1055
+#define IDC_SPAWN6 1056
+#define IDC_CHECK31 1056
+#define IDC_SPAWN7 1057
+#define IDC_CHECK32 1057
+#define IDC_SPAWN8 1058
+#define IDC_CHECK33 1058
+#define IDC_EDIT1 1059
+#define IDC_CHECK34 1059
+#define IDC_ROTATE_BOX 1060
+#define IDC_ROTZ 1060
+#define IDC_CHECK35 1060
+#define IDC_EDIT_TOTALENTITIES 1060
+#define IDC_EDIT_Y 1060
+#define IDC_SCALE_BOX 1061
+#define IDC_ROTY 1061
+#define IDC_CHECK36 1061
+#define IDC_EDIT_NET 1061
+#define IDC_EDIT_Z 1061
+#define IDC_E_VALUE_FIELD 1062
+#define IDC_CHECK37 1062
+#define IDC_CHECK38 1063
+#define IDC_E_LIST 1064
+#define IDC_CHECK39 1064
+#define IDC_E_COMMENT 1065
+#define IDC_CHECK40 1065
+#define IDC_CHECK41 1066
+#define IDC_E_PROPS 1067
+#define IDC_CHECK42 1067
+#define IDC_E_135 1068
+#define IDC_CHECK43 1068
+#define IDC_E_180 1069
+#define IDC_CHECK44 1069
+#define IDC_E_225 1070
+#define IDC_CHECK45 1070
+#define IDC_E_270 1071
+#define IDC_CHECK46 1071
+#define IDC_E_90 1072
+#define IDC_CHECK47 1072
+#define IDC_E_45 1073
+#define IDC_CHECK48 1073
+#define IDC_E_0 1074
+#define IDC_CHECK49 1074
+#define IDC_E_315 1075
+#define IDC_CHECK50 1075
+#define IDC_E_UP 1076
+#define IDC_CHECK51 1076
+#define IDC_E_DOWN 1077
+#define IDC_CHECK52 1077
+#define IDC_CHECK53 1078
+#define IDC_CHECK54 1079
+#define IDC_E_ADDPROP 1080
+#define IDC_CHECK55 1080
+#define IDC_E_DELPROP 1081
+#define IDC_CHECK56 1081
+#define IDC_E_CREATE 1082
+#define IDC_CHECK57 1082
+#define IDC_E_STATUS 1083
+#define IDC_CHECK58 1083
+#define IDC_CHECK59 1084
+#define IDC_CHECK60 1085
+#define IDC_CHECK61 1086
+#define IDC_CHECK62 1087
+#define IDC_CHECK63 1088
+#define IDC_CHECK64 1089
+#define IDC_SHIFT_BOX 1090
+#define IDC_HSHIFT 1090
+#define IDC_VSHIFT 1091
+#define IDC_ROTATEV 1092
+#define ID_BTN_CANCEL 1092
+#define IDC_HSTRETCH 1092
+#define IDC_SCALEV 1093
+#define IDC_EDIT_STATUSPOINTSIZE 1093
+#define IDC_VSTRETCH 1093
+#define IDC_SCALEH 1094
+#define IDC_EDIT_ROTATION 1094
+#define IDC_SHIFTV 1095
+#define IDC_HSHIFTA 1095
+#define IDC_STATIC_FIELD1 1095
+#define IDC_EDIT_UNDOLEVELS 1095
+#define IDC_SHIFTH 1096
+#define IDC_VSHIFTA 1097
+#define IDC_HSCALE 1098
+#define IDC_HSCALEA 1099
+#define IDC_VSCALE 1100
+#define IDC_EDIT_FIELD1 1100
+#define IDC_VSCALEA 1101
+#define IDC_STATIC_FIELD2 1101
+#define IDC_ROTATE 1102
+#define IDC_EDIT_FIELD2 1102
+#define IDC_SLIDER_CAMSPEED 1102
+#define IDC_G_EDIT 1103
+#define IDC_ROTATEA 1103
+#define IDC_STATIC_FIELD3 1103
+#define IDC_CHECK_CAMXYUPDATE 1103
+#define IDC_STATIC_KEY 1104
+#define IDC_FIND_BRUSH 1104
+#define IDC_EDIT_FIELD3 1104
+#define IDC_STATIC_VALUE 1105
+#define IDC_STATIC_FIELD4 1105
+#define IDC_E_KEY_FIELD 1106
+#define IDC_EDIT_FIELD4 1106
+#define IDC_FIND_ENTITY 1107
+#define IDC_STATIC_FIELD5 1107
+#define IDC_SIDES 1108
+#define IDC_EDIT_FIELD5 1108
+#define IDC_COMBO_WHATGAME 1108
+#define IDC_ROTX 1109
+#define IDC_BTN_COLOR 1109
+#define IDC_STATIC_COLOR 1110
+#define IDC_E_COLOR 1111
+#define IDC_ABOUT_GLVENDOR 1112
+#define IDC_ABOUT_GLVERSION 1113
+#define IDC_BTN_THECOLOR 1113
+#define IDC_ABOUT_GLRENDERER 1114
+#define IDC_STATIC_STUFF 1115
+#define IDC_TEXTURE 1116
+#define IDC_CHECK_ALTDRAG 1116
+#define IDC_PRJRSHCMD 1117
+#define IDC_SPIN_HSHIFT 1117
+#define IDC_CHECK_MOUSECHASE 1117
+#define IDC_PRJREMOTEBASE 1118
+#define IDC_SPIN_VSHIFT 1118
+#define IDC_CHECK_FACECOLOR 1118
+#define IDC_PRJENTITYPATH 1119
+#define IDC_SPIN_VSCALE 1119
+#define IDC_CHECK_NOCLAMP 1119
+#define IDC_PRJTEXPATH 1120
+#define IDC_SPIN_HSCALE 1120
+#define IDC_PRJAUTOSAVE 1121
+#define IDC_SPIN_ROTATE 1121
+#define IDC_ADDCMD 1122
+#define IDC_EDIT_ROTATEAMT 1122
+#define IDC_CMD_LIST 1123
+#define IDC_CHECK_DLLENTITIES 1123
+#define IDC_PRJBASEPATH 1124
+#define IDC_CHECK_WIDETOOLBAR 1124
+#define IDC_CMDCOMMAND 1125
+#define IDC_CHECK_BUGGYICD 1125
+#define IDC_CMDMENUTEXT 1126
+#define IDC_CHECK_SGIOPENGL 1126
+#define IDC_REMCMD 1127
+#define IDC_PRJINTERVAL 1128
+#define IDC_CHECK_HICOLOR 1128
+#define IDC_PRJMAPSPATH 1129
+#define IDC_CHECK_SHADERTEST 1129
+#define IDC_EDITCMD 1130
+#define IDC_CHECK_SHOWSHADERS 1130
+#define IDC_ABOUT_GLEXTENSIONS 1131
+#define IDC_LIST_TEXTURES 1132
+#define IDC_COMBO_WIDTH 1136
+#define IDC_COMBO_HEIGHT 1137
+#define IDC_BTN_PATCHDETAILS 1137
+#define IDC_BTN_PATCHRESET 1138
+#define IDC_BTN_PATCHNATURAL 1139
+#define IDC_RADIO_CAP 1139
+#define IDC_BTN_PATCHFIT 1140
+#define IDC_RADIO_CAP2 1140
+#define IDC_CHECK_SEAMS 1140
+#define IDC_RADIO_CAP3 1141
+#define IDC_EDIT_AMOUNT 1141
+#define IDC_RADIO_CAP4 1142
+#define IDC_BTN_ASSIGNSOUND 1142
+#define IDC_BTN_AXIAL 1142
+#define IDC_BTN_ASSIGNMODEL 1143
+#define IDC_BTN_FACEFIT 1143
+#define IDC_SLIDER_TEXTUREQUALITY 1144
+#define IDC_LIST1 1144
+#define IDC_BTN_BRUSHFIT 1144
+#define IDC_LIST_EVENTS 1144
+#define IDC_TREE1 1145
+#define IDC_COMBO_ROW 1147
+#define IDC_COMBO_COL 1148
+#define IDC_COMBO_TYPE 1149
+#define IDC_EDIT_WIDTH 1151
+#define IDC_CHECK_BPRIMIT 1151
+#define IDC_EDIT_HEIGHT 1152
+#define IDC_SPIN_WIDTH 1154
+#define IDC_SPIN_HEIGHT 1155
+#define IDC_COMBO_SHADERS 1157
+#define IDC_TREE_GROUP 1158
+#define IDC_CHECK_NOSTIPPLE 1159
+#define IDC_TAB_MODE 1159
+#define IDC_SLIDER_FALLOFF 1161
+#define IDC_CHECK_POINT 1162
+#define IDC_CHECK_EQUALRADIUS 1163
+#define IDC_RADIO_FALLOFF 1164
+#define IDC_CHECK_PROJECTED 1165
+#define IDC_CHECK_EXPLICITFALLOFF 1166
+#define IDC_EDIT_FALLOFF 1167
+#define IDC_STATIC_TEXTURE 1168
+#define IDC_CHECK_STROBE 1169
+#define IDC_EDIT_STROBE 1170
+#define IDC_CHECK_ROTATE 1171
+#define IDC_EDIT_ROTATE 1172
+#define IDC_BTN_FOG 1174
+#define IDC_CHECK_FOG 1175
+#define IDC_EDIT_ALPHA 1176
+#define IDC_CHECK_SHADOWS 1178
+#define IDC_CHECK_DIFFUSE 1179
+#define IDC_CHECK_SPECULAR 1180
+#define IDC_EDIT_RADIUSY 1184
+#define IDC_EDIT_RADIUSZ 1185
+#define IDC_EDIT_RADIUSX 1186
+#define IDC_EDIT_TARGETX 1187
+#define IDC_EDIT_TARGETY 1188
+#define IDC_EDIT_TARGETZ 1189
+#define IDC_EDIT_RIGHTX 1190
+#define IDC_EDIT_RIGHTY 1191
+#define IDC_EDIT_RIGHTZ 1192
+#define IDC_EDIT_UPX 1193
+#define IDC_EDIT_UPY 1194
+#define IDC_EDIT_UPZ 1195
+#define IDC_EDIT_STARTX 1196
+#define IDC_EDIT_STARTY 1197
+#define IDC_EDIT_STARTZ 1198
+#define IDC_EDIT_ENDX 1199
+#define IDC_EDIT_ENDY 1200
+#define IDC_EDIT_ENDZ 1201
+#define IDC_COMBO_TEXTURE 1203
+#define IDC_EDIT_MAPS 1205
+#define IDC_EDIT_CAM_NAME 1208
+#define IDC_COMBO_SPLINES 1209
+#define IDC_SCROLLBAR_SEGMENT 1210
+#define IDC_EDIT_LENGTH 1212
+#define IDC_EDIT_SEGMENT 1213
+#define IDC_BTN_ADDEVENT 1214
+#define IDC_BTN_DELEVENT 1215
+#define IDC_CHECK_TRACKCAMERA 1216
+#define IDC_RADIO_EVENT 1217
+#define IDC_EDIT_TOTALSEGMENTS 1217
+#define IDC_RADIO5 1218
+#define IDC_RADIO6 1219
+#define IDC_RADIO7 1220
+#define IDC_RADIO8 1221
+#define IDC_EDIT_PARAM 1222
+#define IDC_RADIO9 1223
+#define IDC_RADIO_FIXED 1223
+#define IDC_RADIO10 1224
+#define IDC_RADIO11 1225
+#define IDC_RADIO_EDITPOINTS 1225
+#define IDC_RADIO12 1226
+#define IDC_RADIO_EDITPOINTS2 1226
+#define IDC_BTN_DELETEPOINTS 1227
+#define IDC_EDIT_TYPE 1228
+#define IDC_BTN_SELECTALL 1229
+#define ID_ENTITY_START 22800
+#define ID_FILE_IMPORT 32771
+#define ID_VIEW_XY 32772
+#define ID_VIEW_SIDE 32773
+#define ID_VIEW_FRONT 32774
+#define ID_CAMERATOGGLE 32775
+#define ID_VIEW_CAMERATOGGLE 32776
+#define ID_BUTTON32777 32777
+#define ID_BUTTON32778 32778
+#define ID_TEXTURES_POPUP 32780
+#define ID_POPUP_SELECTION 32782
+#define ID_VIEW_CHANGE 32783
+#define ID_VIEW_CAMERAUPDATE 32784
+#define ID_VIEW_CLIPPER 32785
+#define ID_PREFS 32786
+#define ID_TOGGLE_LOCK 32787
+#define ID_EDIT_MAPINFO 32788
+#define ID_EDIT_ENTITYINFO 32789
+#define ID_BRUSH_SCRIPTS 32790
+#define ID_VIEW_NEXTVIEW 32791
+#define ID_HELP_COMMANDLIST 32792
+#define ID_FILE_NEWPROJECT 32793
+#define ID_MENUITEM32795 32795
+#define ID_SNAPTOGRID 32795
+#define ID_SPLIT_SELECTED 32823
+#define ID_CLIP_SELECTED 32824
+#define ID_FLIP_CLIP 32825
+#define ID_TOGGLEVIEW_YZ 32831
+#define ID_TOGGLEVIEW_XZ 32832
+#define ID_COLORS_GRIDTEXT 32833
+#define ID_COLORS_BRUSH 32834
+#define ID_COLORS_SELECTEDBRUSH 32835
+#define ID_COLORS_CLIPPER 32836
+#define ID_COLORS_GRIDBLOCK 32837
+#define ID_COLORS_VIEWNAME 32838
+#define ID_COLOR_SETORIGINAL 32839
+#define ID_COLOR_SETQER 32840
+#define ID_COLOR_SETBLACK 32841
+#define ID_BYEBYE 32842
+#define ID_SELECT_SCALE 32843
+#define ID_SELECT_MOUSEROTATE 32844
+#define ID_TEXTURE_REPLACESELECTED 32859
+#define ID_TEXTURE_REPLACEALL 32860
+#define ID_SELECT_MOUSESCALE 32866
+#define ID_SCALELOCKX 32867
+#define ID_SCALELOCKY 32868
+#define ID_SCALELOCKZ 32869
+#define ID_VIEW_CUBICCLIPPING 32870
+#define ID_FILE_PROJECTSETTINGS 32875
+#define ID_VIEW_CUBEOUT 32876
+#define ID_VIEW_CUBEIN 32877
+#define ID_NODES_LOADNODES 32878
+#define ID_NODES_SHOWNODES 32879
+#define ID_NODES_SHOWLINKS 32880
+#define ID_NODES_REMOVEALLNODES 32881
+#define ID_NODES_COUNTNODES 32882
+#define ID_NODES_GIVEMONEYTONELNO 32883
+#define ID_FILE_SAVEREGION 32887
+#define ID_FILE_LOADREGION 32888
+#define ID_SELECTION_MOVEDOWN 32890
+#define ID_TOOLBAR_MAIN 32891
+#define ID_SELECTION_MOVEUP 32892
+#define ID_TOOLBAR_TEXTURE 32892
+#define ID_BRUSH_MAKECONE 32896
+#define ID_TEXTURES_LOAD 32897
+#define ID_TOGGLE_ROTATELOCK 32898
+#define ID_CURVE_CYLINDER 32903
+#define ID_CURVE_ENDCAP 32904
+#define ID_CURVE_BEVEL 32905
+#define ID_CURVE_SPHERE 32906
+#define ID_CURVE_HEMISPHERE 32907
+#define ID_CURVE_QUARTER 32908
+#define ID_CURVE_EIGHTHSPHERE 32909
+#define ID_CURVE_INVERTCURVE 32910
+#define ID_FILE_IMPORTMAP 32911
+#define ID_FILE_EXPORTMAP 32912
+#define ID_EDIT_LOADPREFAB 32913
+#define ID_VIEW_SHOWCURVES 32914
+#define ID_SELECTION_SELECT_NUDGELEFT 32916
+#define ID_SELECTION_SELECT_NUDGERIGHT 32917
+#define ID_SELECTION_SELECT_NUDGEUP 32918
+#define ID_SELECTION_SELECT_NUDGEDOWN 32919
+#define ID_TEXTURES_LOADLIST 32920
+#define ID_DONTSELECTCURVE 32923
+#define ID_CONVERTCURVES 32924
+#define ID_DYNAMIC_LIGHTING 32925
+#define ID_PATCH_SHOWBOUNDINGBOX 32926
+#define ID_CURVE_SIMPLEPATCHMESH 32927
+#define ID_PATCH_WIREFRAME 32928
+#define ID_PATCH_WELD 32929
+#define ID_CURVE_PATCHTUBE 32930
+#define ID_CURVE_PATCHCONE 32931
+#define ID_CURVE_PATCHENDCAP 32932
+#define ID_CURVE_PATCHBEVEL 32933
+#define ID_CURVE_PATCHINVERTEDENDCAP 32934
+#define ID_CURVE_PATCHINVERTEDBEVEL 32935
+#define ID_PATCH_DRILLDOWN 32936
+#define ID_CURVE_LOADPATCHFILE 32937
+#define ID_CURVE_INSERTROW 32938
+#define ID_CURVE_INSERTCOLUMN 32939
+#define ID_CURVE_DELETEROW 32940
+#define ID_CURVE_DELETECOLUMN 32941
+#define ID_BUTTON32942 32942
+#define ID_PATCH_INSDEL 32942
+#define ID_CURVE_INSERT_ADDCOLUMN 32943
+#define ID_CURVE_INSERT_INSERTCOLUMN 32944
+#define ID_CURVE_INSERT_ADDROW 32945
+#define ID_CURVE_INSERT_INSERTROW 32946
+#define ID_CURVE_DELETE_FIRSTCOLUMN 32947
+#define ID_CURVE_DELETE_LASTCOLUMN 32948
+#define ID_CURVE_DELETE_FIRSTROW 32949
+#define ID_CURVE_DELETE_LASTROW 32950
+#define ID_CURVE_NEGATIVE 32951
+#define ID_PATCH_BEND 32952
+#define ID_CURVE_PATCHDENSETUBE 32955
+#define ID_CURVE_PATCHVERYDENSETUBE 32956
+#define ID_CURVE_CAP 32957
+#define ID_CURVE_CAP_INVERTEDBEVEL 32959
+#define ID_CURVE_CAP_INVERTEDENDCAP 32960
+#define ID_CURVE_REDISPERSE_ROWS 32961
+#define ID_CURVE_REDISPERSE_COLS 32962
+#define ID_PATCH_NATURALIZE 32963
+#define ID_CURVE_PATCHSQUARE 32964
+#define ID_BRUSH_PRIMITIVES_SPHERE 32965
+#define ID_BRUSH_PRIMITIVES_TORUS 32966
+#define ID_TEXTURES_TEXTUREWINDOWSCALE_200 32967
+#define ID_TEXTURES_TEXTUREWINDOWSCALE_100 32968
+#define ID_TEXTURES_TEXTUREWINDOWSCALE_50 32969
+#define ID_TEXTURES_TEXTUREWINDOWSCALE_25 32970
+#define ID_TEXTURES_TEXTUREWINDOWSCALE_10 32971
+#define ID_CURVE_NEGATIVETEXTUREX 32972
+#define ID_TEXTURES_FLUSH 32973
+#define ID_CURVE_OVERLAY_SET 32974
+#define ID_CURVE_OVERLAY_CLEAR 32975
+#define ID_CURVE_NEGATIVETEXTUREY 32976
+#define ID_CURVE_THICKEN 32977
+#define ID_CURVE_CYCLECAP 32978
+#define ID_CURVE_MATRIX_TRANSPOSE 32981
+#define ID_PLUGINS_REFRESH 32982
+#define ID_TEXTURES_RELOADSHADERS 32983
+#define ID_VIEW_ENTITIESAS_BOUNDINGBOX 32984
+#define ID_VIEW_ENTITIESAS_WRITEFRAME 32985
+#define ID_VIEW_ENTITIESAS_SELECTEDWIREFRAME 32986
+#define ID_VIEW_ENTITIESAS_SELECTEDSKINNED 32987
+#define ID_VIEW_ENTITIESAS_SKINNED 32988
+#define ID_VIEW_ENTITIESAS_SKINNEDANDBOXED 32989
+#define ID_SHOW_ENTITIES 32990
+#define ID_VIEW_ENTITIESAS_WIREFRAME 32991
+#define ID_VIEW_SHOWHINT 32993
+#define ID_VIEW_OPENGLLIGHTING 32998
+#define ID_VIEW_SHOWCAULK 32999
+#define ID_VIEW_SHOWANGLES 33000
+#define ID_EDIT_SAVEPREFAB 33001
+#define ID_CURVE_MOREENDCAPSBEVELS_SQUAREENDCAP 33002
+#define ID_CURVE_MOREENDCAPSBEVELS_SQUAREBEVEL 33003
+#define ID_CURVE_PRIMITIVES_SPHERE 33005
+#define ID_VIEW_HIDESHOW_HIDESELECTED 33006
+#define ID_VIEW_HIDESHOW_SHOWHIDDEN 33007
+#define ID_TEXTURES_SHADERS_SHOW 33008
+#define ID_SELECTION_CSGADD 33009
+#define ID_SELECTION_CSGMERGE 33011
+#define ID_TEXTURES_FLUSH_UNUSED 33014
+#define ID_DROP_GROUP_REMOVE 33016
+#define ID_DROP_GROUP_ADDTO_WORLD 33017
+#define ID_DROP_GROUP_NEWGROUP 33018
+#define ID_DROP_GROUP_NAME 33019
+#define ID_DROP_GROUP_ADDTO 33020
+#define ID_TERRAIN_CREATETERRAINFROMBRUSH 33022
+#define ID_TERRAIN_RAISELOWERTERRAIN 33023
+#define ID_SPLINES_MODE 33027
+#define ID_SPLINES_LOAD 33028
+#define ID_SPLINES_SAVE 33029
+#define ID_SPLINES_EDIT 33030
+#define ID_SPLINE_TEST 33031
+#define ID_POPUP_NEWCAMERA_INTERPOLATED 33034
+#define ID_POPUP_NEWCAMERA_SPLINE 33035
+#define ID_POPUP_NEWCAMERA_FIXED 33036
+#define ID_ENTITY_END 33500
+#define ID_PLUGIN_START 33800
+#define ID_PLUGIN_END 33999
+#define ID_FILE_EXIT 40002
+#define ID_FILE_SAVEAS 40004
+#define ID_VIEW_CENTER 40005
+#define ID_VIEW_UPFLOOR 40006
+#define ID_VIEW_DOWNFLOOR 40007
+#define ID_BRUSH_FLIPX 40008
+#define ID_BRUSH_FLIPY 40009
+#define ID_BRUSH_FLIPZ 40010
+#define ID_BRUSH_ROTATEX 40011
+#define ID_BRUSH_ROTATEY 40012
+#define ID_BRUSH_ROTATEZ 40013
+#define ID_BSP_FULLVIS 40016
+#define ID_BSP_FASTVIS 40017
+#define ID_BSP_NOVIS 40018
+#define ID_BSP_RELIGHT 40019
+#define ID_BSP_ENTITIES 40020
+#define ID_FILE_POINTFILE 40021
+#define ID_VIEW_100 40022
+#define ID_VIEW_75 40023
+#define ID_VIEW_50 40024
+#define ID_VIEW_25 40025
+#define ID_VIEW_12 40026
+#define ID_TEXTURES_SHOWALL 40033
+#define ID_TEXTURES_SHOWINUSE 40034
+#define ID_TEXTURES_TOGGLEVIEW 40037
+#define ID_SELECTION_CREATEENTITY 40039
+#define ID_SELECTION_EDITENTITY 40040
+#define ID_MISC_BENCHMARK 40041
+#define ID_REGION_OFF 40043
+#define ID_REGION_SETXY 40044
+#define ID_REGION_SETBRUSH 40045
+#define ID_SELECTION_MAKEHOLLOW 40046
+#define ID_SELECTION_SELECTPARTIALTALL 40047
+#define ID_SELECTION_SELECTCOMPLETETALL 40048
+#define ID_SELECTION_CSGSUBTRACT 40049
+#define ID_SELECTION_SELECTTOUCHING 40050
+#define ID_VIEW_NEAREST 40052
+#define ID_VIEW_NEARESTMIPMAP 40053
+#define ID_VIEW_LINEAR 40054
+#define ID_VIEW_BILINEAR 40055
+#define ID_VIEW_BILINEARMIPMAP 40056
+#define ID_VIEW_TRILINEAR 40057
+#define ID_TEXTURES_WIREFRAME 40058
+#define ID_TEXTURES_FLATSHADE 40059
+#define ID_VIEW_SHOWNAMES 40060
+#define ID_VIEW_ZOOMIN 40061
+#define ID_VIEW_ZOOMOUT 40062
+#define ID_VIEW_SHOWCOORDINATES 40063
+#define ID_VIEW_Z100 40064
+#define ID_VIEW_ZZOOMIN 40065
+#define ID_VIEW_ZZOOMOUT 40066
+#define ID_SELECTION_CLONE 40067
+#define ID_SELECTION_DESELECT 40068
+#define ID_SELECTION_DELETE 40069
+#define ID_BUTTON40068 40070
+#define ID_SELECTION_DRAGVERTECIES 40074
+#define ID_SELECTION_DRAGEDGES 40075
+#define ID_REGION_SETTALLBRUSH 40076
+#define ID_SELECTION_SELECTINSIDE 40092
+#define ID_PROJECT_RELEAD 40094
+#define ID_PROJECT_CHANGE 40095
+#define ID_MISC_GAMMA 40097
+#define ID_VIEW_SHOWENT 40098
+#define ID_VIEW_SHOWPATH 40099
+#define ID_VIEW_SHOWLIGHTS 40100
+#define ID_VIEW_SHOWCLIP 40101
+#define ID_VIEW_SHOWWATER 40102
+#define ID_VIEW_SHOWWORLD 40103
+#define ID_MISC_TEXTUREBACKGROUN 40104
+#define ID_TEXTUREBK 40105
+#define ID_COLORS_XYBK 40106
+#define ID_FILE_ABOUT 40107
+#define ID_VIEW_CONSOLE 40108
+#define ID_VIEW_ENTITY 40109
+#define ID_VIEW_TEXTURE 40110
+#define ID_COLORS_MAJOR 40111
+#define ID_COLORS_MINOR 40113
+#define ID_SELECTION_CONNECT 40114
+#define ID_FILE_LOADPROJECT 40115
+#define ID_MISC_FINDBRUSH 40116
+#define ID_MISC_NEXTLEAKSPOT 40117
+#define ID_MISC_PREVIOUSLEAKSPOT 40118
+#define ID_BRUSH_3SIDED 40119
+#define ID_BRUSH_4SIDED 40120
+#define ID_BRUSH_5SIDED 40121
+#define ID_BRUSH_6SIDED 40122
+#define ID_BRUSH_7SIDED 40123
+#define ID_BRUSH_8SIDED 40124
+#define ID_BRUSH_9SIDED 40125
+#define ID_SELECTION_ARBITRARYROTATION 40126
+#define ID_BRUSH_ARBITRARYSIDED 40127
+#define ID_SELECTION_UNGROUPENTITY 40130
+#define ID_MISC_SELECTENTITYCOLOR 40131
+#define ID_MISC_PRINTXY 40132
+#define ID_HELP_ABOUT 40134
+#define ID_EDIT_COPYBRUSH 40135
+#define ID_EDIT_PASTEBRUSH 40136
+#define ID_TEXTURES_INSPECTOR 40137
+#define ID_VIEW_SHOWDETAIL 40138
+#define ID_SELECTION_MAKE_DETAIL 40139
+#define ID_SELECTION_MAKE_STRUCTURAL 40140
+#define ID_REGION_SETSELECTION 40142
+#define ID_VIEW_SHOWBLOCKS 40143
+#define ID_GRID_1 40144
+#define ID_GRID_2 40145
+#define ID_GRID_4 40146
+#define ID_GRID_8 40147
+#define ID_GRID_16 40148
+#define ID_GRID_32 40149
+#define ID_GRID_64 40150
+#define ID_CAMERA_UP 40151
+#define ID_CAMERA_DOWN 40152
+#define ID_CAMERA_LEFT 40153
+#define ID_CAMERA_RIGHT 40155
+#define ID_CAMERA_FORWARD 40156
+#define ID_CAMERA_BACK 40157
+#define ID_CAMERA_ANGLEUP 40158
+#define ID_CAMERA_ANGLEDOWN 40159
+#define ID_CAMERA_STRAFELEFT 40160
+#define ID_CAMERA_STRAFERIGHT 40161
+#define ID_GRID_TOGGLE 40162
+#define ID_ENTITYLIST 40163
+#define ID_MAPINFO 40164
+#define ID_TOGGLECONSOLE 40165
+#define ID_TOGGLECAMERA 40166
+#define ID_TOGGLEZ 40167
+#define ID_TOGGLEVIEW 40168
+#define ID_SELECTION_TEXTURE_DEC 40169
+#define ID_SELECTION_TEXTURE_INC 40170
+#define ID_SELECTION_TEXTURE_FIT 40171
+#define ID_SELECTION_TEXTURE_ROTATECLOCK 40172
+#define ID_SELECTION_TEXTURE_ROTATECOUNTER 40173
+#define ID_SELECTION_TEXTURE_SCALEUP 40174
+#define ID_SELECTION_TEXTURE_SCALEDOWN 40175
+#define ID_SELECTION_TEXTURE_SHIFTLEFT 40176
+#define ID_SELECTION_TEXTURE_SHIFTRIGHT 40177
+#define ID_SELECTION_TEXTURE_SHIFTUP 40178
+#define ID_SELECTION_TEXTURE_SHIFTDOWN 40179
+#define ID_GRID_NEXT 40180
+#define ID_GRID_PREV 40181
+#define ID_SELECTION_TEXTURE_SCALELEFT 40182
+#define ID_SELECTION_TEXTURE_SCALERIGHT 40183
+#define ID_SELECTION_PRINT 40184
+#define ID_SELECTION_TOGGLESIZEPAINT 40185
+#define ID_PATCH_TAB 40186
+#define ID_PATCH_ENTER 40187
+#define ID_SELECT_SNAPTOGRID 40188
+#define ID_PATCH_INSPECTOR 40189
+#define ID_SELECT_ALL 40190
+#define ID_CURVE_FREEZE 40191
+#define ID_CURVE_UNFREEZE 40192
+#define ID_CURVE_UNFREEZEALL 40193
+#define ID_SELECT_RESELECT 40194
+#define ID_FITBRUSH 40195
+#define ID_FITFACE 40196
+#define ID_VIEW_CROSSHAIR 40197
+#define ID_SELECTION_INVERT 40198
+#define ID_VIEW_GROUPS 40199
+#define ID_SELECTION_NOOUTLINE 40200
+#define ID_SPLINES_POPUP 40201
+
+// Next default values for new objects
+//
+#ifdef APSTUDIO_INVOKED
+#ifndef APSTUDIO_READONLY_SYMBOLS
+#define _APS_3D_CONTROLS 1
+#define _APS_NEXT_RESOURCE_VALUE 192
+#define _APS_NEXT_COMMAND_VALUE 33024
+#define _APS_NEXT_CONTROL_VALUE 1160
+#define _APS_NEXT_SYMED_VALUE 101
+#endif
+#endif
diff --git a/q3radiant/splines/Splines.vcproj b/q3radiant/splines/Splines.vcproj
new file mode 100755
index 0000000..be579ae
--- /dev/null
+++ b/q3radiant/splines/Splines.vcproj
@@ -0,0 +1,296 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+ ProjectType="Visual C++"
+ Version="7.10"
+ Name="Splines"
+ SccProjectName="&quot;$/source/q3radiant/splines&quot;, XINAAAAA"
+ SccLocalPath=".">
+ <Platforms>
+ <Platform
+ Name="Win32"/>
+ </Platforms>
+ <Configurations>
+ <Configuration
+ Name="Release|Win32"
+ OutputDirectory=".\Release"
+ IntermediateDirectory=".\Release"
+ ConfigurationType="4"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ PreprocessorDefinitions="WIN32;NDEBUG;_LIB;Q3RADIANT"
+ StringPooling="TRUE"
+ RuntimeLibrary="4"
+ EnableFunctionLevelLinking="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Release/Splines.pch"
+ AssemblerListingLocation=".\Release/"
+ ObjectFile=".\Release/"
+ ProgramDataBaseFileName=".\Release/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile=".\Release\Splines.lib"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCMIDLTool"/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ <Configuration
+ Name="Debug|Win32"
+ OutputDirectory=".\Debug"
+ IntermediateDirectory=".\Debug"
+ ConfigurationType="4"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="FALSE"
+ CharacterSet="2">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions="WIN32;_DEBUG;_LIB;Q3RADIANT"
+ BasicRuntimeChecks="3"
+ RuntimeLibrary="1"
+ RuntimeTypeInfo="TRUE"
+ UsePrecompiledHeader="2"
+ PrecompiledHeaderFile=".\Debug/Splines.pch"
+ AssemblerListingLocation=".\Debug/"
+ ObjectFile=".\Debug/"
+ ProgramDataBaseFileName=".\Debug/"
+ WarningLevel="3"
+ SuppressStartupBanner="TRUE"
+ DebugInformationFormat="4"/>
+ <Tool
+ Name="VCCustomBuildTool"/>
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile=".\Debug\Splines.lib"
+ SuppressStartupBanner="TRUE"/>
+ <Tool
+ Name="VCMIDLTool"/>
+ <Tool
+ Name="VCPostBuildEventTool"/>
+ <Tool
+ Name="VCPreBuildEventTool"/>
+ <Tool
+ Name="VCPreLinkEventTool"/>
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"/>
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"/>
+ <Tool
+ Name="VCXMLDataGeneratorTool"/>
+ <Tool
+ Name="VCManagedWrapperGeneratorTool"/>
+ <Tool
+ Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+ </Configuration>
+ </Configurations>
+ <References>
+ </References>
+ <Files>
+ <Filter
+ Name="Source Files"
+ Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat">
+ <File
+ RelativePath="math_angles.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="math_matrix.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="math_quaternion.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="math_vector.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="q_parse.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="q_shared.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="splines.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="util_str.cpp">
+ <FileConfiguration
+ Name="Release|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ PreprocessorDefinitions=""/>
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32">
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ PreprocessorDefinitions=""
+ BasicRuntimeChecks="3"/>
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <Filter
+ Name="Header Files"
+ Filter="h;hpp;hxx;hm;inl">
+ <File
+ RelativePath="math_angles.h">
+ </File>
+ <File
+ RelativePath="math_matrix.h">
+ </File>
+ <File
+ RelativePath="math_quaternion.h">
+ </File>
+ <File
+ RelativePath="math_vector.h">
+ </File>
+ <File
+ RelativePath="q_shared.h">
+ </File>
+ <File
+ RelativePath="splines.h">
+ </File>
+ <File
+ RelativePath="util_list.h">
+ </File>
+ <File
+ RelativePath="util_str.h">
+ </File>
+ </Filter>
+ </Files>
+ <Globals>
+ </Globals>
+</VisualStudioProject>
diff --git a/q3radiant/splines/math_angles.cpp b/q3radiant/splines/math_angles.cpp
new file mode 100755
index 0000000..0142d3d
--- /dev/null
+++ b/q3radiant/splines/math_angles.cpp
@@ -0,0 +1,150 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "q_shared.h"
+#include <float.h>
+
+angles_t ang_zero( 0.0f, 0.0f, 0.0f );
+
+void toAngles( mat3_t &src, angles_t &dst ) {
+ double theta;
+ double cp;
+ double sp;
+
+ sp = src[ 0 ][ 2 ];
+
+ // cap off our sin value so that we don't get any NANs
+ if ( sp > 1.0 ) {
+ sp = 1.0;
+ } else if ( sp < -1.0 ) {
+ sp = -1.0;
+ }
+
+ theta = -asin( sp );
+ cp = cos( theta );
+
+ if ( cp > 8192 * FLT_EPSILON ) {
+ dst.pitch = theta * 180 / M_PI;
+ dst.yaw = atan2( src[ 0 ][ 1 ], src[ 0 ][ 0 ] ) * 180 / M_PI;
+ dst.roll = atan2( src[ 1 ][ 2 ], src[ 2 ][ 2 ] ) * 180 / M_PI;
+ } else {
+ dst.pitch = theta * 180 / M_PI;
+ dst.yaw = -atan2( src[ 1 ][ 0 ], src[ 1 ][ 1 ] ) * 180 / M_PI;
+ dst.roll = 0;
+ }
+}
+
+void toAngles( quat_t &src, angles_t &dst ) {
+ mat3_t temp;
+
+ toMatrix( src, temp );
+ toAngles( temp, dst );
+}
+
+void toAngles( idVec3_t &src, angles_t &dst ) {
+ dst.pitch = src[ 0 ];
+ dst.yaw = src[ 1 ];
+ dst.roll = src[ 2 ];
+}
+
+void angles_t::toVectors( idVec3_t *forward, idVec3_t *right, idVec3_t *up ) {
+ float angle;
+ static float sr, sp, sy, cr, cp, cy; // static to help MS compiler fp bugs
+
+ angle = yaw * ( M_PI * 2 / 360 );
+ sy = sin( angle );
+ cy = cos( angle );
+
+ angle = pitch * ( M_PI * 2 / 360 );
+ sp = sin( angle );
+ cp = cos( angle );
+
+ angle = roll * ( M_PI * 2 / 360 );
+ sr = sin( angle );
+ cr = cos( angle );
+
+ if ( forward ) {
+ forward->set( cp * cy, cp * sy, -sp );
+ }
+
+ if ( right ) {
+ right->set( -sr * sp * cy + cr * sy, -sr * sp * sy + -cr * cy, -sr * cp );
+ }
+
+ if ( up ) {
+ up->set( cr * sp * cy + -sr * -sy, cr * sp * sy + -sr * cy, cr * cp );
+ }
+}
+
+idVec3_t angles_t::toForward( void ) {
+ float angle;
+ static float sp, sy, cp, cy; // static to help MS compiler fp bugs
+
+ angle = yaw * ( M_PI * 2 / 360 );
+ sy = sin( angle );
+ cy = cos( angle );
+
+ angle = pitch * ( M_PI * 2 / 360 );
+ sp = sin( angle );
+ cp = cos( angle );
+
+ return idVec3_t( cp * cy, cp * sy, -sp );
+}
+
+/*
+=================
+Normalize360
+
+returns angles normalized to the range [0 <= angle < 360]
+=================
+*/
+angles_t& angles_t::Normalize360( void ) {
+ pitch = (360.0 / 65536) * ( ( int )( pitch * ( 65536 / 360.0 ) ) & 65535 );
+ yaw = (360.0 / 65536) * ( ( int )( yaw * ( 65536 / 360.0 ) ) & 65535 );
+ roll = (360.0 / 65536) * ( ( int )( roll * ( 65536 / 360.0 ) ) & 65535 );
+
+ return *this;
+}
+
+
+/*
+=================
+Normalize180
+
+returns angles normalized to the range [-180 < angle <= 180]
+=================
+*/
+angles_t& angles_t::Normalize180( void ) {
+ Normalize360();
+
+ if ( pitch > 180.0 ) {
+ pitch -= 360.0;
+ }
+
+ if ( yaw > 180.0 ) {
+ yaw -= 360.0;
+ }
+
+ if ( roll > 180.0 ) {
+ roll -= 360.0;
+ }
+ return *this;
+}
diff --git a/q3radiant/splines/math_angles.h b/q3radiant/splines/math_angles.h
new file mode 100755
index 0000000..7156e46
--- /dev/null
+++ b/q3radiant/splines/math_angles.h
@@ -0,0 +1,195 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __MATH_ANGLES_H__
+#define __MATH_ANGLES_H__
+
+#include <stdlib.h>
+#include <assert.h>
+
+#include "math_vector.h"
+
+class mat3_t;
+class quat_t;
+class idVec3_t;
+typedef idVec3_t &vec3_p;
+
+class angles_t {
+public:
+ float pitch;
+ float yaw;
+ float roll;
+
+ angles_t();
+ angles_t( float pitch, float yaw, float roll );
+ angles_t( const idVec3_t &vec );
+
+ friend void toAngles( idVec3_t &src, angles_t &dst );
+ friend void toAngles( quat_t &src, angles_t &dst );
+ friend void toAngles( mat3_t &src, angles_t &dst );
+
+ operator vec3_p();
+
+ float operator[]( int index ) const;
+ float& operator[]( int index );
+
+ void set( float pitch, float yaw, float roll );
+
+ void operator=( angles_t const &a );
+ void operator=( idVec3_t const &a );
+
+ friend angles_t operator+( const angles_t &a, const angles_t &b );
+ angles_t &operator+=( angles_t const &a );
+ angles_t &operator+=( idVec3_t const &a );
+
+ friend angles_t operator-( angles_t &a, angles_t &b );
+ angles_t &operator-=( angles_t &a );
+
+ friend angles_t operator*( const angles_t &a, float b );
+ friend angles_t operator*( float a, const angles_t &b );
+ angles_t &operator*=( float a );
+
+ friend int operator==( angles_t &a, angles_t &b );
+
+ friend int operator!=( angles_t &a, angles_t &b );
+
+ void toVectors( idVec3_t *forward, idVec3_t *right = NULL, idVec3_t *up = NULL );
+ idVec3_t toForward( void );
+
+ angles_t &Zero( void );
+
+ angles_t &Normalize360( void );
+ angles_t &Normalize180( void );
+};
+
+extern angles_t ang_zero;
+
+inline angles_t::angles_t() {}
+
+inline angles_t::angles_t( float pitch, float yaw, float roll ) {
+ this->pitch = pitch;
+ this->yaw = yaw;
+ this->roll = roll;
+}
+
+inline angles_t::angles_t( const idVec3_t &vec ) {
+ this->pitch = vec.x;
+ this->yaw = vec.y;
+ this->roll = vec.z;
+}
+
+inline float angles_t::operator[]( int index ) const {
+ assert( ( index >= 0 ) && ( index < 3 ) );
+ return ( &pitch )[ index ];
+}
+
+inline float& angles_t::operator[]( int index ) {
+ assert( ( index >= 0 ) && ( index < 3 ) );
+ return ( &pitch )[ index ];
+}
+
+inline angles_t::operator vec3_p( void ) {
+ return *( idVec3_t * )&pitch;
+}
+
+inline void angles_t::set( float pitch, float yaw, float roll ) {
+ this->pitch = pitch;
+ this->yaw = yaw;
+ this->roll = roll;
+}
+
+inline void angles_t::operator=( angles_t const &a ) {
+ pitch = a.pitch;
+ yaw = a.yaw;
+ roll = a.roll;
+}
+
+inline void angles_t::operator=( idVec3_t const &a ) {
+ pitch = a[ 0 ];
+ yaw = a[ 1 ];
+ roll = a[ 2 ];
+}
+
+inline angles_t operator+( const angles_t &a, const angles_t &b ) {
+ return angles_t( a.pitch + b.pitch, a.yaw + b.yaw, a.roll + b.roll );
+}
+
+inline angles_t& angles_t::operator+=( angles_t const &a ) {
+ pitch += a.pitch;
+ yaw += a.yaw;
+ roll += a.roll;
+
+ return *this;
+}
+
+inline angles_t& angles_t::operator+=( idVec3_t const &a ) {
+ pitch += a.x;
+ yaw += a.y;
+ roll += a.z;
+
+ return *this;
+}
+
+inline angles_t operator-( angles_t &a, angles_t &b ) {
+ return angles_t( a.pitch - b.pitch, a.yaw - b.yaw, a.roll - b.roll );
+}
+
+inline angles_t& angles_t::operator-=( angles_t &a ) {
+ pitch -= a.pitch;
+ yaw -= a.yaw;
+ roll -= a.roll;
+
+ return *this;
+}
+
+inline angles_t operator*( const angles_t &a, float b ) {
+ return angles_t( a.pitch * b, a.yaw * b, a.roll * b );
+}
+
+inline angles_t operator*( float a, const angles_t &b ) {
+ return angles_t( a * b.pitch, a * b.yaw, a * b.roll );
+}
+
+inline angles_t& angles_t::operator*=( float a ) {
+ pitch *= a;
+ yaw *= a;
+ roll *= a;
+
+ return *this;
+}
+
+inline int operator==( angles_t &a, angles_t &b ) {
+ return ( ( a.pitch == b.pitch ) && ( a.yaw == b.yaw ) && ( a.roll == b.roll ) );
+}
+
+inline int operator!=( angles_t &a, angles_t &b ) {
+ return ( ( a.pitch != b.pitch ) || ( a.yaw != b.yaw ) || ( a.roll != b.roll ) );
+}
+
+inline angles_t& angles_t::Zero( void ) {
+ pitch = 0.0f;
+ yaw = 0.0f;
+ roll = 0.0f;
+
+ return *this;
+}
+
+#endif /* !__MATH_ANGLES_H__ */
diff --git a/q3radiant/splines/math_matrix.cpp b/q3radiant/splines/math_matrix.cpp
new file mode 100755
index 0000000..24ae914
--- /dev/null
+++ b/q3radiant/splines/math_matrix.cpp
@@ -0,0 +1,134 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "q_shared.h"
+
+mat3_t mat3_default( idVec3_t( 1, 0, 0 ), idVec3_t( 0, 1, 0 ), idVec3_t( 0, 0, 1 ) );
+
+void toMatrix( quat_t const &src, mat3_t &dst ) {
+ float wx, wy, wz;
+ float xx, yy, yz;
+ float xy, xz, zz;
+ float x2, y2, z2;
+
+ x2 = src.x + src.x;
+ y2 = src.y + src.y;
+ z2 = src.z + src.z;
+
+ xx = src.x * x2;
+ xy = src.x * y2;
+ xz = src.x * z2;
+
+ yy = src.y * y2;
+ yz = src.y * z2;
+ zz = src.z * z2;
+
+ wx = src.w * x2;
+ wy = src.w * y2;
+ wz = src.w * z2;
+
+ dst[ 0 ][ 0 ] = 1.0f - ( yy + zz );
+ dst[ 0 ][ 1 ] = xy - wz;
+ dst[ 0 ][ 2 ] = xz + wy;
+
+ dst[ 1 ][ 0 ] = xy + wz;
+ dst[ 1 ][ 1 ] = 1.0f - ( xx + zz );
+ dst[ 1 ][ 2 ] = yz - wx;
+
+ dst[ 2 ][ 0 ] = xz - wy;
+ dst[ 2 ][ 1 ] = yz + wx;
+ dst[ 2 ][ 2 ] = 1.0f - ( xx + yy );
+}
+
+void toMatrix( angles_t const &src, mat3_t &dst ) {
+ float angle;
+ static float sr, sp, sy, cr, cp, cy; // static to help MS compiler fp bugs
+
+ angle = src.yaw * ( M_PI * 2.0f / 360.0f );
+ sy = sin( angle );
+ cy = cos( angle );
+
+ angle = src.pitch * ( M_PI * 2.0f / 360.0f );
+ sp = sin( angle );
+ cp = cos( angle );
+
+ angle = src.roll * ( M_PI * 2.0f / 360.0f );
+ sr = sin( angle );
+ cr = cos( angle );
+
+ dst[ 0 ].set( cp * cy, cp * sy, -sp );
+ dst[ 1 ].set( sr * sp * cy + cr * -sy, sr * sp * sy + cr * cy, sr * cp );
+ dst[ 2 ].set( cr * sp * cy + -sr * -sy, cr * sp * sy + -sr * cy, cr * cp );
+}
+
+void toMatrix( idVec3_t const &src, mat3_t &dst ) {
+ angles_t sup = src;
+ toMatrix(sup, dst);
+}
+
+void mat3_t::ProjectVector( const idVec3_t &src, idVec3_t &dst ) const {
+ dst.x = src * mat[ 0 ];
+ dst.y = src * mat[ 1 ];
+ dst.z = src * mat[ 2 ];
+}
+
+void mat3_t::UnprojectVector( const idVec3_t &src, idVec3_t &dst ) const {
+ dst = mat[ 0 ] * src.x + mat[ 1 ] * src.y + mat[ 2 ] * src.z;
+}
+
+void mat3_t::Transpose( mat3_t &matrix ) {
+ int i;
+ int j;
+
+ for( i = 0; i < 3; i++ ) {
+ for( j = 0; j < 3; j++ ) {
+ matrix[ i ][ j ] = mat[ j ][ i ];
+ }
+ }
+}
+
+void mat3_t::Transpose( void ) {
+ float temp;
+ int i;
+ int j;
+
+ for( i = 0; i < 3; i++ ) {
+ for( j = i + 1; j < 3; j++ ) {
+ temp = mat[ i ][ j ];
+ mat[ i ][ j ] = mat[ j ][ i ];
+ mat[ j ][ i ] = temp;
+ }
+ }
+}
+
+mat3_t mat3_t::Inverse( void ) const {
+ mat3_t inv( *this );
+
+ inv.Transpose();
+
+ return inv;
+}
+
+void mat3_t::Clear( void ) {
+ mat[0].set( 1, 0, 0 );
+ mat[1].set( 0, 1, 0 );
+ mat[2].set( 0, 0, 1 );
+}
diff --git a/q3radiant/splines/math_matrix.h b/q3radiant/splines/math_matrix.h
new file mode 100755
index 0000000..ed1da0d
--- /dev/null
+++ b/q3radiant/splines/math_matrix.h
@@ -0,0 +1,223 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __MATH_MATRIX_H__
+#define __MATH_MATRIX_H__
+
+#include <string.h>
+#include "math_vector.h"
+
+#ifndef ID_INLINE
+#ifdef _WIN32
+#define ID_INLINE __inline
+#else
+#define ID_INLINE inline
+#endif
+#endif
+
+class quat_t;
+class angles_t;
+
+class mat3_t {
+public:
+ idVec3_t mat[ 3 ];
+
+ mat3_t();
+ mat3_t( float src[ 3 ][ 3 ] );
+ mat3_t( idVec3_t const &x, idVec3_t const &y, idVec3_t const &z );
+ mat3_t( const float xx, const float xy, const float xz, const float yx, const float yy, const float yz, const float zx, const float zy, const float zz );
+
+ friend void toMatrix( quat_t const &src, mat3_t &dst );
+ friend void toMatrix( angles_t const &src, mat3_t &dst );
+ friend void toMatrix( idVec3_t const &src, mat3_t &dst );
+
+ idVec3_t operator[]( int index ) const;
+ idVec3_t &operator[]( int index );
+
+ idVec3_t operator*( const idVec3_t &vec ) const;
+ mat3_t operator*( const mat3_t &a ) const;
+ mat3_t operator*( float a ) const;
+ mat3_t operator+( mat3_t const &a ) const;
+ mat3_t operator-( mat3_t const &a ) const;
+
+ friend idVec3_t operator*( const idVec3_t &vec, const mat3_t &mat );
+ friend mat3_t operator*( float a, mat3_t const &b );
+
+ mat3_t &operator*=( float a );
+ mat3_t &operator+=( mat3_t const &a );
+ mat3_t &operator-=( mat3_t const &a );
+
+ void Clear( void );
+
+ void ProjectVector( const idVec3_t &src, idVec3_t &dst ) const;
+ void UnprojectVector( const idVec3_t &src, idVec3_t &dst ) const;
+
+ void OrthoNormalize( void );
+ void Transpose( mat3_t &matrix );
+ void Transpose( void );
+ mat3_t Inverse( void ) const;
+ void Identity( void );
+
+ friend void InverseMultiply( const mat3_t &inv, const mat3_t &b, mat3_t &dst );
+ friend mat3_t SkewSymmetric( idVec3_t const &src );
+};
+
+ID_INLINE mat3_t::mat3_t() {
+}
+
+ID_INLINE mat3_t::mat3_t( float src[ 3 ][ 3 ] ) {
+ memcpy( mat, src, sizeof( src ) );
+}
+
+ID_INLINE mat3_t::mat3_t( idVec3_t const &x, idVec3_t const &y, idVec3_t const &z ) {
+ mat[ 0 ].x = x.x; mat[ 0 ].y = x.y; mat[ 0 ].z = x.z;
+ mat[ 1 ].x = y.x; mat[ 1 ].y = y.y; mat[ 1 ].z = y.z;
+ mat[ 2 ].x = z.x; mat[ 2 ].y = z.y; mat[ 2 ].z = z.z;
+}
+
+ID_INLINE mat3_t::mat3_t( const float xx, const float xy, const float xz, const float yx, const float yy, const float yz, const float zx, const float zy, const float zz ) {
+ mat[ 0 ].x = xx; mat[ 0 ].y = xy; mat[ 0 ].z = xz;
+ mat[ 1 ].x = yx; mat[ 1 ].y = yy; mat[ 1 ].z = yz;
+ mat[ 2 ].x = zx; mat[ 2 ].y = zy; mat[ 2 ].z = zz;
+}
+
+ID_INLINE idVec3_t mat3_t::operator[]( int index ) const {
+ assert( ( index >= 0 ) && ( index < 3 ) );
+ return mat[ index ];
+}
+
+ID_INLINE idVec3_t& mat3_t::operator[]( int index ) {
+ assert( ( index >= 0 ) && ( index < 3 ) );
+ return mat[ index ];
+}
+
+ID_INLINE idVec3_t mat3_t::operator*( const idVec3_t &vec ) const {
+ return idVec3_t(
+ mat[ 0 ].x * vec.x + mat[ 1 ].x * vec.y + mat[ 2 ].x * vec.z,
+ mat[ 0 ].y * vec.x + mat[ 1 ].y * vec.y + mat[ 2 ].y * vec.z,
+ mat[ 0 ].z * vec.x + mat[ 1 ].z * vec.y + mat[ 2 ].z * vec.z );
+}
+
+ID_INLINE mat3_t mat3_t::operator*( const mat3_t &a ) const {
+ return mat3_t(
+ mat[0].x * a[0].x + mat[0].y * a[1].x + mat[0].z * a[2].x,
+ mat[0].x * a[0].y + mat[0].y * a[1].y + mat[0].z * a[2].y,
+ mat[0].x * a[0].z + mat[0].y * a[1].z + mat[0].z * a[2].z,
+ mat[1].x * a[0].x + mat[1].y * a[1].x + mat[1].z * a[2].x,
+ mat[1].x * a[0].y + mat[1].y * a[1].y + mat[1].z * a[2].y,
+ mat[1].x * a[0].z + mat[1].y * a[1].z + mat[1].z * a[2].z,
+ mat[2].x * a[0].x + mat[2].y * a[1].x + mat[2].z * a[2].x,
+ mat[2].x * a[0].y + mat[2].y * a[1].y + mat[2].z * a[2].y,
+ mat[2].x * a[0].z + mat[2].y * a[1].z + mat[2].z * a[2].z );
+}
+
+ID_INLINE mat3_t mat3_t::operator*( float a ) const {
+ return mat3_t(
+ mat[0].x * a, mat[0].y * a, mat[0].z * a,
+ mat[1].x * a, mat[1].y * a, mat[1].z * a,
+ mat[2].x * a, mat[2].y * a, mat[2].z * a );
+}
+
+ID_INLINE mat3_t mat3_t::operator+( mat3_t const &a ) const {
+ return mat3_t(
+ mat[0].x + a[0].x, mat[0].y + a[0].y, mat[0].z + a[0].z,
+ mat[1].x + a[1].x, mat[1].y + a[1].y, mat[1].z + a[1].z,
+ mat[2].x + a[2].x, mat[2].y + a[2].y, mat[2].z + a[2].z );
+}
+
+ID_INLINE mat3_t mat3_t::operator-( mat3_t const &a ) const {
+ return mat3_t(
+ mat[0].x - a[0].x, mat[0].y - a[0].y, mat[0].z - a[0].z,
+ mat[1].x - a[1].x, mat[1].y - a[1].y, mat[1].z - a[1].z,
+ mat[2].x - a[2].x, mat[2].y - a[2].y, mat[2].z - a[2].z );
+}
+
+ID_INLINE idVec3_t operator*( const idVec3_t &vec, const mat3_t &mat ) {
+ return idVec3_t(
+ mat[ 0 ].x * vec.x + mat[ 1 ].x * vec.y + mat[ 2 ].x * vec.z,
+ mat[ 0 ].y * vec.x + mat[ 1 ].y * vec.y + mat[ 2 ].y * vec.z,
+ mat[ 0 ].z * vec.x + mat[ 1 ].z * vec.y + mat[ 2 ].z * vec.z );
+}
+
+ID_INLINE mat3_t operator*( float a, mat3_t const &b ) {
+ return mat3_t(
+ b[0].x * a, b[0].y * a, b[0].z * a,
+ b[1].x * a, b[1].y * a, b[1].z * a,
+ b[2].x * a, b[2].y * a, b[2].z * a );
+}
+
+ID_INLINE mat3_t &mat3_t::operator*=( float a ) {
+ mat[0].x *= a; mat[0].y *= a; mat[0].z *= a;
+ mat[1].x *= a; mat[1].y *= a; mat[1].z *= a;
+ mat[2].x *= a; mat[2].y *= a; mat[2].z *= a;
+
+ return *this;
+}
+
+ID_INLINE mat3_t &mat3_t::operator+=( mat3_t const &a ) {
+ mat[0].x += a[0].x; mat[0].y += a[0].y; mat[0].z += a[0].z;
+ mat[1].x += a[1].x; mat[1].y += a[1].y; mat[1].z += a[1].z;
+ mat[2].x += a[2].x; mat[2].y += a[2].y; mat[2].z += a[2].z;
+
+ return *this;
+}
+
+ID_INLINE mat3_t &mat3_t::operator-=( mat3_t const &a ) {
+ mat[0].x -= a[0].x; mat[0].y -= a[0].y; mat[0].z -= a[0].z;
+ mat[1].x -= a[1].x; mat[1].y -= a[1].y; mat[1].z -= a[1].z;
+ mat[2].x -= a[2].x; mat[2].y -= a[2].y; mat[2].z -= a[2].z;
+
+ return *this;
+}
+
+ID_INLINE void mat3_t::OrthoNormalize( void ) {
+ mat[ 0 ].Normalize();
+ mat[ 2 ].Cross( mat[ 0 ], mat[ 1 ] );
+ mat[ 2 ].Normalize();
+ mat[ 1 ].Cross( mat[ 2 ], mat[ 0 ] );
+ mat[ 1 ].Normalize();
+}
+
+ID_INLINE void mat3_t::Identity( void ) {
+ mat[ 0 ].x = 1.f; mat[ 0 ].y = 0.f; mat[ 0 ].z = 0.f;
+ mat[ 1 ].x = 0.f; mat[ 1 ].y = 1.f; mat[ 1 ].z = 0.f;
+ mat[ 2 ].x = 0.f; mat[ 2 ].y = 0.f; mat[ 2 ].z = 1.f;
+}
+
+ID_INLINE void InverseMultiply( const mat3_t &inv, const mat3_t &b, mat3_t &dst ) {
+ dst[0].x = inv[0].x * b[0].x + inv[1].x * b[1].x + inv[2].x * b[2].x;
+ dst[0].y = inv[0].x * b[0].y + inv[1].x * b[1].y + inv[2].x * b[2].y;
+ dst[0].z = inv[0].x * b[0].z + inv[1].x * b[1].z + inv[2].x * b[2].z;
+ dst[1].x = inv[0].y * b[0].x + inv[1].y * b[1].x + inv[2].y * b[2].x;
+ dst[1].y = inv[0].y * b[0].y + inv[1].y * b[1].y + inv[2].y * b[2].y;
+ dst[1].z = inv[0].y * b[0].z + inv[1].y * b[1].z + inv[2].y * b[2].z;
+ dst[2].x = inv[0].z * b[0].x + inv[1].z * b[1].x + inv[2].z * b[2].x;
+ dst[2].y = inv[0].z * b[0].y + inv[1].z * b[1].y + inv[2].z * b[2].y;
+ dst[2].z = inv[0].z * b[0].z + inv[1].z * b[1].z + inv[2].z * b[2].z;
+}
+
+ID_INLINE mat3_t SkewSymmetric( idVec3_t const &src ) {
+ return mat3_t( 0.0f, -src.z, src.y, src.z, 0.0f, -src.x, -src.y, src.x, 0.0f );
+}
+
+extern mat3_t mat3_default;
+
+#endif /* !__MATH_MATRIX_H__ */
diff --git a/q3radiant/splines/math_quaternion.cpp b/q3radiant/splines/math_quaternion.cpp
new file mode 100755
index 0000000..4ef670e
--- /dev/null
+++ b/q3radiant/splines/math_quaternion.cpp
@@ -0,0 +1,78 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#include "math_quaternion.h"
+#include "math_matrix.h"
+
+void toQuat( idVec3_t &src, quat_t &dst ) {
+ dst.x = src.x;
+ dst.y = src.y;
+ dst.z = src.z;
+ dst.w = 0.0f;
+}
+
+void toQuat( angles_t &src, quat_t &dst ) {
+ mat3_t temp;
+
+ toMatrix( src, temp );
+ toQuat( temp, dst );
+}
+
+void toQuat( mat3_t &src, quat_t &dst ) {
+ float trace;
+ float s;
+ int i;
+ int j;
+ int k;
+
+ static int next[ 3 ] = { 1, 2, 0 };
+
+ trace = src[ 0 ][ 0 ] + src[ 1 ][ 1 ] + src[ 2 ][ 2 ];
+ if ( trace > 0.0f ) {
+ s = ( float )sqrt( trace + 1.0f );
+ dst.w = s * 0.5f;
+ s = 0.5f / s;
+
+ dst.x = ( src[ 2 ][ 1 ] - src[ 1 ][ 2 ] ) * s;
+ dst.y = ( src[ 0 ][ 2 ] - src[ 2 ][ 0 ] ) * s;
+ dst.z = ( src[ 1 ][ 0 ] - src[ 0 ][ 1 ] ) * s;
+ } else {
+ i = 0;
+ if ( src[ 1 ][ 1 ] > src[ 0 ][ 0 ] ) {
+ i = 1;
+ }
+ if ( src[ 2 ][ 2 ] > src[ i ][ i ] ) {
+ i = 2;
+ }
+
+ j = next[ i ];
+ k = next[ j ];
+
+ s = ( float )sqrt( ( src[ i ][ i ] - ( src[ j ][ j ] + src[ k ][ k ] ) ) + 1.0f );
+ dst[ i ] = s * 0.5f;
+
+ s = 0.5f / s;
+
+ dst.w = ( src[ k ][ j ] - src[ j ][ k ] ) * s;
+ dst[ j ] = ( src[ j ][ i ] + src[ i ][ j ] ) * s;
+ dst[ k ] = ( src[ k ][ i ] + src[ i ][ k ] ) * s;
+ }
+}
diff --git a/q3radiant/splines/math_quaternion.h b/q3radiant/splines/math_quaternion.h
new file mode 100755
index 0000000..74ae2ac
--- /dev/null
+++ b/q3radiant/splines/math_quaternion.h
@@ -0,0 +1,190 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __MATH_QUATERNION_H__
+#define __MATH_QUATERNION_H__
+
+#include <assert.h>
+#include <math.h>
+
+class idVec3_t;
+class angles_t;
+class mat3_t;
+
+class quat_t {
+public:
+ float x;
+ float y;
+ float z;
+ float w;
+
+ quat_t();
+ quat_t( float x, float y, float z, float w );
+
+ friend void toQuat( idVec3_t &src, quat_t &dst );
+ friend void toQuat( angles_t &src, quat_t &dst );
+ friend void toQuat( mat3_t &src, quat_t &dst );
+
+ float *vec4( void );
+
+ float operator[]( int index ) const;
+ float &operator[]( int index );
+
+ void set( float x, float y, float z, float w );
+
+ void operator=( quat_t a );
+
+ friend quat_t operator+( quat_t a, quat_t b );
+ quat_t &operator+=( quat_t a );
+
+ friend quat_t operator-( quat_t a, quat_t b );
+ quat_t &operator-=( quat_t a );
+
+ friend quat_t operator*( quat_t a, float b );
+ friend quat_t operator*( float a, quat_t b );
+ quat_t &operator*=( float a );
+
+ friend int operator==( quat_t a, quat_t b );
+ friend int operator!=( quat_t a, quat_t b );
+
+ float Length( void );
+ quat_t &Normalize( void );
+
+ quat_t operator-();
+};
+
+inline quat_t::quat_t() {
+}
+
+inline quat_t::quat_t( float x, float y, float z, float w ) {
+ this->x = x;
+ this->y = y;
+ this->z = z;
+ this->w = w;
+}
+
+inline float *quat_t::vec4( void ) {
+ return &x;
+}
+
+inline float quat_t::operator[]( int index ) const {
+ assert( ( index >= 0 ) && ( index < 4 ) );
+ return ( &x )[ index ];
+}
+
+inline float& quat_t::operator[]( int index ) {
+ assert( ( index >= 0 ) && ( index < 4 ) );
+ return ( &x )[ index ];
+}
+
+inline void quat_t::set( float x, float y, float z, float w ) {
+ this->x = x;
+ this->y = y;
+ this->z = z;
+ this->w = w;
+}
+
+inline void quat_t::operator=( quat_t a ) {
+ x = a.x;
+ y = a.y;
+ z = a.z;
+ w = a.w;
+}
+
+inline quat_t operator+( quat_t a, quat_t b ) {
+ return quat_t( a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w );
+}
+
+inline quat_t& quat_t::operator+=( quat_t a ) {
+ x += a.x;
+ y += a.y;
+ z += a.z;
+ w += a.w;
+
+ return *this;
+}
+
+inline quat_t operator-( quat_t a, quat_t b ) {
+ return quat_t( a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w );
+}
+
+inline quat_t& quat_t::operator-=( quat_t a ) {
+ x -= a.x;
+ y -= a.y;
+ z -= a.z;
+ w -= a.w;
+
+ return *this;
+}
+
+inline quat_t operator*( quat_t a, float b ) {
+ return quat_t( a.x * b, a.y * b, a.z * b, a.w * b );
+}
+
+inline quat_t operator*( float a, quat_t b ) {
+ return b * a;
+}
+
+inline quat_t& quat_t::operator*=( float a ) {
+ x *= a;
+ y *= a;
+ z *= a;
+ w *= a;
+
+ return *this;
+}
+
+inline int operator==( quat_t a, quat_t b ) {
+ return ( ( a.x == b.x ) && ( a.y == b.y ) && ( a.z == b.z ) && ( a.w == b.w ) );
+}
+
+inline int operator!=( quat_t a, quat_t b ) {
+ return ( ( a.x != b.x ) || ( a.y != b.y ) || ( a.z != b.z ) && ( a.w != b.w ) );
+}
+
+inline float quat_t::Length( void ) {
+ float length;
+
+ length = x * x + y * y + z * z + w * w;
+ return ( float )sqrt( length );
+}
+
+inline quat_t& quat_t::Normalize( void ) {
+ float length;
+ float ilength;
+
+ length = this->Length();
+ if ( length ) {
+ ilength = 1 / length;
+ x *= ilength;
+ y *= ilength;
+ z *= ilength;
+ w *= ilength;
+ }
+
+ return *this;
+}
+
+inline quat_t quat_t::operator-() {
+ return quat_t( -x, -y, -z, -w );
+}
+
+#endif /* !__MATH_QUATERNION_H__ */
diff --git a/q3radiant/splines/math_vector.cpp b/q3radiant/splines/math_vector.cpp
new file mode 100755
index 0000000..120258c
--- /dev/null
+++ b/q3radiant/splines/math_vector.cpp
@@ -0,0 +1,144 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//#include "../game/q_shared.h"
+#include "math_vector.h"
+#include <assert.h>
+#include <math.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <string.h>
+#include <stdlib.h>
+#include <time.h>
+#include <ctype.h>
+
+#define M_PI 3.14159265358979323846 // matches value in gcc v2 math.h
+
+#define LERP_DELTA 1e-6
+
+idVec3_t vec_zero( 0.0f, 0.0f, 0.0f );
+
+Bounds boundsZero;
+
+float idVec3_t::toYaw( void ) {
+ float yaw;
+
+ if ( ( y == 0 ) && ( x == 0 ) ) {
+ yaw = 0;
+ } else {
+ yaw = atan2( y, x ) * 180 / M_PI;
+ if ( yaw < 0 ) {
+ yaw += 360;
+ }
+ }
+
+ return yaw;
+}
+
+float idVec3_t::toPitch( void ) {
+ float forward;
+ float pitch;
+
+ if ( ( x == 0 ) && ( y == 0 ) ) {
+ if ( z > 0 ) {
+ pitch = 90;
+ } else {
+ pitch = 270;
+ }
+ } else {
+ forward = ( float )idSqrt( x * x + y * y );
+ pitch = atan2( z, forward ) * 180 / M_PI;
+ if ( pitch < 0 ) {
+ pitch += 360;
+ }
+ }
+
+ return pitch;
+}
+
+/*
+angles_t idVec3_t::toAngles( void ) {
+ float forward;
+ float yaw;
+ float pitch;
+
+ if ( ( x == 0 ) && ( y == 0 ) ) {
+ yaw = 0;
+ if ( z > 0 ) {
+ pitch = 90;
+ } else {
+ pitch = 270;
+ }
+ } else {
+ yaw = atan2( y, x ) * 180 / M_PI;
+ if ( yaw < 0 ) {
+ yaw += 360;
+ }
+
+ forward = ( float )idSqrt( x * x + y * y );
+ pitch = atan2( z, forward ) * 180 / M_PI;
+ if ( pitch < 0 ) {
+ pitch += 360;
+ }
+ }
+
+ return angles_t( -pitch, yaw, 0 );
+}
+*/
+
+idVec3_t LerpVector( idVec3_t &w1, idVec3_t &w2, const float t ) {
+ float omega, cosom, sinom, scale0, scale1;
+
+ cosom = w1 * w2;
+ if ( ( 1.0 - cosom ) > LERP_DELTA ) {
+ omega = acos( cosom );
+ sinom = sin( omega );
+ scale0 = sin( ( 1.0 - t ) * omega ) / sinom;
+ scale1 = sin( t * omega ) / sinom;
+ } else {
+ scale0 = 1.0 - t;
+ scale1 = t;
+ }
+
+ return ( w1 * scale0 + w2 * scale1 );
+}
+
+/*
+=============
+idVec3_t::string
+
+This is just a convenience function
+for printing vectors
+=============
+*/
+char *idVec3_t::string( void ) {
+ static int index = 0;
+ static char str[ 8 ][ 36 ];
+ char *s;
+
+ // use an array so that multiple toString's won't collide
+ s = str[ index ];
+ index = (index + 1)&7;
+
+ sprintf( s, "%.2f %.2f %.2f", x, y, z );
+
+ return s;
+}
diff --git a/q3radiant/splines/math_vector.h b/q3radiant/splines/math_vector.h
new file mode 100755
index 0000000..8afc541
--- /dev/null
+++ b/q3radiant/splines/math_vector.h
@@ -0,0 +1,572 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __MATH_VECTOR_H__
+#define __MATH_VECTOR_H__
+
+#pragma warning(disable : 4244)
+
+#include <math.h>
+#include <assert.h>
+
+//#define DotProduct(a,b) ((a)[0]*(b)[0]+(a)[1]*(b)[1]+(a)[2]*(b)[2])
+//#define VectorSubtract(a,b,c) ((c)[0]=(a)[0]-(b)[0],(c)[1]=(a)[1]-(b)[1],(c)[2]=(a)[2]-(b)[2])
+//#define VectorAdd(a,b,c) ((c)[0]=(a)[0]+(b)[0],(c)[1]=(a)[1]+(b)[1],(c)[2]=(a)[2]+(b)[2])
+//#define VectorCopy(a,b) ((b)[0]=(a)[0],(b)[1]=(a)[1],(b)[2]=(a)[2])
+//#define VectorCopy(a,b) ((b).x=(a).x,(b).y=(a).y,(b).z=(a).z])
+
+//#define VectorScale(v, s, o) ((o)[0]=(v)[0]*(s),(o)[1]=(v)[1]*(s),(o)[2]=(v)[2]*(s))
+#define __VectorMA(v, s, b, o) ((o)[0]=(v)[0]+(b)[0]*(s),(o)[1]=(v)[1]+(b)[1]*(s),(o)[2]=(v)[2]+(b)[2]*(s))
+//#define CrossProduct(a,b,c) ((c)[0]=(a)[1]*(b)[2]-(a)[2]*(b)[1],(c)[1]=(a)[2]*(b)[0]-(a)[0]*(b)[2],(c)[2]=(a)[0]*(b)[1]-(a)[1]*(b)[0])
+
+#define DotProduct4(x,y) ((x)[0]*(y)[0]+(x)[1]*(y)[1]+(x)[2]*(y)[2]+(x)[3]*(y)[3])
+#define VectorSubtract4(a,b,c) ((c)[0]=(a)[0]-(b)[0],(c)[1]=(a)[1]-(b)[1],(c)[2]=(a)[2]-(b)[2],(c)[3]=(a)[3]-(b)[3])
+#define VectorAdd4(a,b,c) ((c)[0]=(a)[0]+(b)[0],(c)[1]=(a)[1]+(b)[1],(c)[2]=(a)[2]+(b)[2],(c)[3]=(a)[3]+(b)[3])
+#define VectorCopy4(a,b) ((b)[0]=(a)[0],(b)[1]=(a)[1],(b)[2]=(a)[2],(b)[3]=(a)[3])
+#define VectorScale4(v, s, o) ((o)[0]=(v)[0]*(s),(o)[1]=(v)[1]*(s),(o)[2]=(v)[2]*(s),(o)[3]=(v)[3]*(s))
+#define VectorMA4(v, s, b, o) ((o)[0]=(v)[0]+(b)[0]*(s),(o)[1]=(v)[1]+(b)[1]*(s),(o)[2]=(v)[2]+(b)[2]*(s),(o)[3]=(v)[3]+(b)[3]*(s))
+
+
+//#define VectorClear(a) ((a)[0]=(a)[1]=(a)[2]=0)
+#define VectorNegate(a,b) ((b)[0]=-(a)[0],(b)[1]=-(a)[1],(b)[2]=-(a)[2])
+//#define VectorSet(v, x, y, z) ((v)[0]=(x), (v)[1]=(y), (v)[2]=(z))
+#define Vector4Copy(a,b) ((b)[0]=(a)[0],(b)[1]=(a)[1],(b)[2]=(a)[2],(b)[3]=(a)[3])
+
+#define SnapVector(v) {v[0]=(int)v[0];v[1]=(int)v[1];v[2]=(int)v[2];}
+
+
+//#include "util_heap.h"
+
+#ifndef EQUAL_EPSILON
+#define EQUAL_EPSILON 0.001
+#endif
+
+float Q_fabs( float f );
+
+#ifndef ID_INLINE
+#ifdef _WIN32
+#define ID_INLINE __inline
+#else
+#define ID_INLINE inline
+#endif
+#endif
+
+// if this is defined, vec3 will take four elements, which may allow
+// easier SIMD optimizations
+//#define FAT_VEC3
+//#ifdef __ppc__
+//#pragma align(16)
+//#endif
+
+class angles_t;
+#ifdef __ppc__
+// Vanilla PPC code, but since PPC has a reciprocal square root estimate instruction,
+// runs *much* faster than calling sqrt(). We'll use two Newton-Raphson
+// refinement steps to get bunch more precision in the 1/sqrt() value for very little cost.
+// We'll then multiply 1/sqrt times the original value to get the sqrt.
+// This is about 12.4 times faster than sqrt() and according to my testing (not exhaustive)
+// it returns fairly accurate results (error below 1.0e-5 up to 100000.0 in 0.1 increments).
+
+static inline float idSqrt(float x) {
+ const float half = 0.5;
+ const float one = 1.0;
+ float B, y0, y1;
+
+ // This'll NaN if it hits frsqrte. Handle both +0.0 and -0.0
+ if (fabs(x) == 0.0)
+ return x;
+ B = x;
+
+#ifdef __GNUC__
+ asm("frsqrte %0,%1" : "=f" (y0) : "f" (B));
+#else
+ y0 = __frsqrte(B);
+#endif
+ /* First refinement step */
+
+ y1 = y0 + half*y0*(one - B*y0*y0);
+
+ /* Second refinement step -- copy the output of the last step to the input of this step */
+
+ y0 = y1;
+ y1 = y0 + half*y0*(one - B*y0*y0);
+
+ /* Get sqrt(x) from x * 1/sqrt(x) */
+ return x * y1;
+}
+#else
+static inline double idSqrt(double x) {
+ return sqrt(x);
+}
+#endif
+
+
+//class idVec3_t : public idHeap<idVec3_t> {
+class idVec3_t {
+public:
+#ifndef FAT_VEC3
+ float x,y,z;
+#else
+ float x,y,z,dist;
+#endif
+
+#ifndef FAT_VEC3
+ idVec3_t() {};
+#else
+ idVec3_t() {dist = 0.0f;};
+#endif
+ idVec3_t( const float x, const float y, const float z );
+
+ operator float *();
+
+ float operator[]( const int index ) const;
+ float &operator[]( const int index );
+
+ void set( const float x, const float y, const float z );
+
+ idVec3_t operator-() const;
+
+ idVec3_t &operator=( const idVec3_t &a );
+
+ float operator*( const idVec3_t &a ) const;
+ idVec3_t operator*( const float a ) const;
+ friend idVec3_t operator*( float a, idVec3_t b );
+
+ idVec3_t operator+( const idVec3_t &a ) const;
+ idVec3_t operator-( const idVec3_t &a ) const;
+
+ idVec3_t &operator+=( const idVec3_t &a );
+ idVec3_t &operator-=( const idVec3_t &a );
+ idVec3_t &operator*=( const float a );
+
+ int operator==( const idVec3_t &a ) const;
+ int operator!=( const idVec3_t &a ) const;
+
+ idVec3_t Cross( const idVec3_t &a ) const;
+ idVec3_t &Cross( const idVec3_t &a, const idVec3_t &b );
+
+ float Length( void ) const;
+ float Normalize( void );
+
+ void Zero( void );
+ void Snap( void );
+ void SnapTowards( const idVec3_t &to );
+
+ float toYaw( void );
+ float toPitch( void );
+ angles_t toAngles( void );
+ friend idVec3_t LerpVector( const idVec3_t &w1, const idVec3_t &w2, const float t );
+
+ char *string( void );
+};
+
+extern idVec3_t vec_zero;
+
+ID_INLINE idVec3_t::idVec3_t( const float x, const float y, const float z ) {
+ this->x = x;
+ this->y = y;
+ this->z = z;
+#ifdef FAT_VEC3
+ this->dist = 0.0f;
+#endif
+}
+
+ID_INLINE float idVec3_t::operator[]( const int index ) const {
+ return ( &x )[ index ];
+}
+
+ID_INLINE float &idVec3_t::operator[]( const int index ) {
+ return ( &x )[ index ];
+}
+
+ID_INLINE idVec3_t::operator float *( void ) {
+ return &x;
+}
+
+ID_INLINE idVec3_t idVec3_t::operator-() const {
+ return idVec3_t( -x, -y, -z );
+}
+
+ID_INLINE idVec3_t &idVec3_t::operator=( const idVec3_t &a ) {
+ x = a.x;
+ y = a.y;
+ z = a.z;
+
+ return *this;
+}
+
+ID_INLINE void idVec3_t::set( const float x, const float y, const float z ) {
+ this->x = x;
+ this->y = y;
+ this->z = z;
+}
+
+ID_INLINE idVec3_t idVec3_t::operator-( const idVec3_t &a ) const {
+ return idVec3_t( x - a.x, y - a.y, z - a.z );
+}
+
+ID_INLINE float idVec3_t::operator*( const idVec3_t &a ) const {
+ return x * a.x + y * a.y + z * a.z;
+}
+
+ID_INLINE idVec3_t idVec3_t::operator*( const float a ) const {
+ return idVec3_t( x * a, y * a, z * a );
+}
+
+ID_INLINE idVec3_t operator*( const float a, const idVec3_t b ) {
+ return idVec3_t( b.x * a, b.y * a, b.z * a );
+}
+
+ID_INLINE idVec3_t idVec3_t::operator+( const idVec3_t &a ) const {
+ return idVec3_t( x + a.x, y + a.y, z + a.z );
+}
+
+ID_INLINE idVec3_t &idVec3_t::operator+=( const idVec3_t &a ) {
+ x += a.x;
+ y += a.y;
+ z += a.z;
+
+ return *this;
+}
+
+ID_INLINE idVec3_t &idVec3_t::operator-=( const idVec3_t &a ) {
+ x -= a.x;
+ y -= a.y;
+ z -= a.z;
+
+ return *this;
+}
+
+ID_INLINE idVec3_t &idVec3_t::operator*=( const float a ) {
+ x *= a;
+ y *= a;
+ z *= a;
+
+ return *this;
+}
+
+ID_INLINE int idVec3_t::operator==( const idVec3_t &a ) const {
+ if ( Q_fabs( x - a.x ) > EQUAL_EPSILON ) {
+ return false;
+ }
+
+ if ( Q_fabs( y - a.y ) > EQUAL_EPSILON ) {
+ return false;
+ }
+
+ if ( Q_fabs( z - a.z ) > EQUAL_EPSILON ) {
+ return false;
+ }
+
+ return true;
+}
+
+ID_INLINE int idVec3_t::operator!=( const idVec3_t &a ) const {
+ if ( Q_fabs( x - a.x ) > EQUAL_EPSILON ) {
+ return true;
+ }
+
+ if ( Q_fabs( y - a.y ) > EQUAL_EPSILON ) {
+ return true;
+ }
+
+ if ( Q_fabs( z - a.z ) > EQUAL_EPSILON ) {
+ return true;
+ }
+
+ return false;
+}
+
+ID_INLINE idVec3_t idVec3_t::Cross( const idVec3_t &a ) const {
+ return idVec3_t( y * a.z - z * a.y, z * a.x - x * a.z, x * a.y - y * a.x );
+}
+
+ID_INLINE idVec3_t &idVec3_t::Cross( const idVec3_t &a, const idVec3_t &b ) {
+ x = a.y * b.z - a.z * b.y;
+ y = a.z * b.x - a.x * b.z;
+ z = a.x * b.y - a.y * b.x;
+
+ return *this;
+}
+
+ID_INLINE float idVec3_t::Length( void ) const {
+ float length;
+
+ length = x * x + y * y + z * z;
+ return ( float )idSqrt( length );
+}
+
+ID_INLINE float idVec3_t::Normalize( void ) {
+ float length;
+ float ilength;
+
+ length = this->Length();
+ if ( length ) {
+ ilength = 1.0f / length;
+ x *= ilength;
+ y *= ilength;
+ z *= ilength;
+ }
+
+ return length;
+}
+
+ID_INLINE void idVec3_t::Zero( void ) {
+ x = 0.0f;
+ y = 0.0f;
+ z = 0.0f;
+}
+
+ID_INLINE void idVec3_t::Snap( void ) {
+ x = float( int( x ) );
+ y = float( int( y ) );
+ z = float( int( z ) );
+}
+
+/*
+======================
+SnapTowards
+
+Round a vector to integers for more efficient network
+transmission, but make sure that it rounds towards a given point
+rather than blindly truncating. This prevents it from truncating
+into a wall.
+======================
+*/
+ID_INLINE void idVec3_t::SnapTowards( const idVec3_t &to ) {
+ if ( to.x <= x ) {
+ x = float( int( x ) );
+ } else {
+ x = float( int( x ) + 1 );
+ }
+
+ if ( to.y <= y ) {
+ y = float( int( y ) );
+ } else {
+ y = float( int( y ) + 1 );
+ }
+
+ if ( to.z <= z ) {
+ z = float( int( z ) );
+ } else {
+ z = float( int( z ) + 1 );
+ }
+}
+
+//===============================================================
+
+class Bounds {
+public:
+ idVec3_t b[2];
+
+ Bounds();
+ Bounds( const idVec3_t &mins, const idVec3_t &maxs );
+
+ void Clear();
+ void Zero();
+ float Radius(); // radius from origin, not from center
+ idVec3_t Center();
+ void AddPoint( const idVec3_t &v );
+ void AddBounds( const Bounds &bb );
+ bool IsCleared();
+ bool ContainsPoint( const idVec3_t &p );
+ bool IntersectsBounds( const Bounds &b2 ); // touching is NOT intersecting
+};
+
+extern Bounds boundsZero;
+
+ID_INLINE Bounds::Bounds(){
+}
+
+ID_INLINE bool Bounds::IsCleared() {
+ return b[0][0] > b[1][0];
+}
+
+ID_INLINE bool Bounds::ContainsPoint( const idVec3_t &p ) {
+ if ( p[0] < b[0][0] || p[1] < b[0][1] || p[2] < b[0][2]
+ || p[0] > b[1][0] || p[1] > b[1][1] || p[2] > b[1][2] ) {
+ return false;
+ }
+ return true;
+}
+
+ID_INLINE bool Bounds::IntersectsBounds( const Bounds &b2 ) {
+ if ( b2.b[1][0] < b[0][0] || b2.b[1][1] < b[0][1] || b2.b[1][2] < b[0][2]
+ || b2.b[0][0] > b[1][0] || b2.b[0][1] > b[1][1] || b2.b[0][2] > b[1][2] ) {
+ return false;
+ }
+ return true;
+}
+
+ID_INLINE Bounds::Bounds( const idVec3_t &mins, const idVec3_t &maxs ) {
+ b[0] = mins;
+ b[1] = maxs;
+}
+
+ID_INLINE idVec3_t Bounds::Center() {
+ return idVec3_t( ( b[1][0] + b[0][0] ) * 0.5f, ( b[1][1] + b[0][1] ) * 0.5f, ( b[1][2] + b[0][2] ) * 0.5f );
+}
+
+ID_INLINE void Bounds::Clear() {
+ b[0][0] = b[0][1] = b[0][2] = 99999;
+ b[1][0] = b[1][1] = b[1][2] = -99999;
+}
+
+ID_INLINE void Bounds::Zero() {
+ b[0][0] = b[0][1] = b[0][2] =
+ b[1][0] = b[1][1] = b[1][2] = 0;
+}
+
+ID_INLINE void Bounds::AddPoint( const idVec3_t &v ) {
+ if ( v[0] < b[0][0]) {
+ b[0][0] = v[0];
+ }
+ if ( v[0] > b[1][0]) {
+ b[1][0] = v[0];
+ }
+ if ( v[1] < b[0][1] ) {
+ b[0][1] = v[1];
+ }
+ if ( v[1] > b[1][1]) {
+ b[1][1] = v[1];
+ }
+ if ( v[2] < b[0][2] ) {
+ b[0][2] = v[2];
+ }
+ if ( v[2] > b[1][2]) {
+ b[1][2] = v[2];
+ }
+}
+
+
+ID_INLINE void Bounds::AddBounds( const Bounds &bb ) {
+ if ( bb.b[0][0] < b[0][0]) {
+ b[0][0] = bb.b[0][0];
+ }
+ if ( bb.b[0][1] < b[0][1]) {
+ b[0][1] = bb.b[0][1];
+ }
+ if ( bb.b[0][2] < b[0][2]) {
+ b[0][2] = bb.b[0][2];
+ }
+
+ if ( bb.b[1][0] > b[1][0]) {
+ b[1][0] = bb.b[1][0];
+ }
+ if ( bb.b[1][1] > b[1][1]) {
+ b[1][1] = bb.b[1][1];
+ }
+ if ( bb.b[1][2] > b[1][2]) {
+ b[1][2] = bb.b[1][2];
+ }
+}
+
+ID_INLINE float Bounds::Radius( ) {
+ int i;
+ float total;
+ float a, aa;
+
+ total = 0;
+ for (i=0 ; i<3 ; i++) {
+ a = (float)fabs( b[0][i] );
+ aa = (float)fabs( b[1][i] );
+ if ( aa > a ) {
+ a = aa;
+ }
+ total += a * a;
+ }
+
+ return (float)idSqrt( total );
+}
+
+//===============================================================
+
+
+class idVec2_t {
+public:
+ float x;
+ float y;
+
+ operator float *();
+ float operator[]( int index ) const;
+ float &operator[]( int index );
+};
+
+ID_INLINE float idVec2_t::operator[]( int index ) const {
+ return ( &x )[ index ];
+}
+
+ID_INLINE float& idVec2_t::operator[]( int index ) {
+ return ( &x )[ index ];
+}
+
+ID_INLINE idVec2_t::operator float *( void ) {
+ return &x;
+}
+
+class vec4_t : public idVec3_t {
+public:
+#ifndef FAT_VEC3
+ float dist;
+#endif
+ vec4_t();
+ ~vec4_t() {};
+
+ vec4_t( float x, float y, float z, float dist );
+ float operator[]( int index ) const;
+ float &operator[]( int index );
+};
+
+ID_INLINE vec4_t::vec4_t() {}
+ID_INLINE vec4_t::vec4_t( float x, float y, float z, float dist ) {
+ this->x = x;
+ this->y = y;
+ this->z = z;
+ this->dist = dist;
+}
+
+ID_INLINE float vec4_t::operator[]( int index ) const {
+ return ( &x )[ index ];
+}
+
+ID_INLINE float& vec4_t::operator[]( int index ) {
+ return ( &x )[ index ];
+}
+
+
+class idVec5_t : public idVec3_t {
+public:
+ float s;
+ float t;
+ float operator[]( int index ) const;
+ float &operator[]( int index );
+};
+
+
+ID_INLINE float idVec5_t::operator[]( int index ) const {
+ return ( &x )[ index ];
+}
+
+ID_INLINE float& idVec5_t::operator[]( int index ) {
+ return ( &x )[ index ];
+}
+
+#endif /* !__MATH_VECTOR_H__ */
diff --git a/q3radiant/splines/q_parse.cpp b/q3radiant/splines/q_parse.cpp
new file mode 100755
index 0000000..1f61ba4
--- /dev/null
+++ b/q3radiant/splines/q_parse.cpp
@@ -0,0 +1,535 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// q_parse.c -- support for parsing text files
+
+#include "q_shared.h"
+
+/*
+============================================================================
+
+PARSING
+
+============================================================================
+*/
+
+// multiple character punctuation tokens
+static const char *punctuation[] = {
+ "+=", "-=", "*=", "/=", "&=", "|=", "++", "--",
+ "&&", "||", "<=", ">=", "==", "!=",
+ NULL
+};
+
+typedef struct {
+ char token[MAX_TOKEN_CHARS];
+ int lines;
+ qboolean ungetToken;
+ char parseFile[MAX_QPATH];
+} parseInfo_t;
+
+#define MAX_PARSE_INFO 16
+static parseInfo_t parseInfo[MAX_PARSE_INFO];
+static int parseInfoNum;
+static parseInfo_t *pi = &parseInfo[0];
+
+/*
+===================
+Com_BeginParseSession
+===================
+*/
+void Com_BeginParseSession( const char *filename ) {
+ if ( parseInfoNum == MAX_PARSE_INFO - 1 ) {
+ Com_Error( ERR_FATAL, "Com_BeginParseSession: session overflow" );
+ }
+ parseInfoNum++;
+ pi = &parseInfo[parseInfoNum];
+
+ pi->lines = 1;
+ Q_strncpyz( pi->parseFile, filename, sizeof( pi->parseFile ) );
+}
+
+/*
+===================
+Com_EndParseSession
+===================
+*/
+void Com_EndParseSession( void ) {
+ if ( parseInfoNum == 0 ) {
+ Com_Error( ERR_FATAL, "Com_EndParseSession: session underflow" );
+ }
+ parseInfoNum--;
+ pi = &parseInfo[parseInfoNum];
+}
+
+/*
+===================
+Com_GetCurrentParseLine
+===================
+*/
+int Com_GetCurrentParseLine( void ) {
+ return pi->lines;
+}
+
+/*
+===================
+Com_ScriptError
+
+Prints the script name and line number in the message
+===================
+*/
+void Com_ScriptError( const char *msg, ... ) {
+ va_list argptr;
+ char string[32000];
+
+ va_start( argptr, msg );
+ vsprintf( string, msg,argptr );
+ va_end( argptr );
+
+ Com_Error( ERR_DROP, "File %s, line %i: %s", pi->parseFile, pi->lines, string );
+}
+
+void Com_ScriptWarning( const char *msg, ... ) {
+ va_list argptr;
+ char string[32000];
+
+ va_start( argptr, msg );
+ vsprintf( string, msg,argptr );
+ va_end( argptr );
+
+ Com_Printf( "File %s, line %i: %s", pi->parseFile, pi->lines, string );
+}
+
+
+/*
+===================
+Com_UngetToken
+
+Calling this will make the next Com_Parse return
+the current token instead of advancing the pointer
+===================
+*/
+void Com_UngetToken( void ) {
+ if ( pi->ungetToken ) {
+ Com_ScriptError( "UngetToken called twice" );
+ }
+ pi->ungetToken = qtrue;
+}
+
+
+static const char *SkipWhitespace( const char (*data), qboolean *hasNewLines ) {
+ int c;
+
+ while( (c = *data) <= ' ') {
+ if( !c ) {
+ return NULL;
+ }
+ if( c == '\n' ) {
+ pi->lines++;
+ *hasNewLines = qtrue;
+ }
+ data++;
+ }
+
+ return data;
+}
+
+/*
+==============
+Com_ParseExt
+
+Parse a token out of a string
+Will never return NULL, just empty strings.
+An empty string will only be returned at end of file.
+
+If "allowLineBreaks" is qtrue then an empty
+string will be returned if the next token is
+a newline.
+==============
+*/
+static char *Com_ParseExt( const char *(*data_p), qboolean allowLineBreaks ) {
+ int c = 0, len;
+ qboolean hasNewLines = qfalse;
+ const char *data;
+ const char **punc;
+
+ if ( !data_p ) {
+ Com_Error( ERR_FATAL, "Com_ParseExt: NULL data_p" );
+ }
+
+ data = *data_p;
+ len = 0;
+ pi->token[0] = 0;
+
+ // make sure incoming data is valid
+ if ( !data ) {
+ *data_p = NULL;
+ return pi->token;
+ }
+
+ // skip any leading whitespace
+ while ( 1 ) {
+ // skip whitespace
+ data = SkipWhitespace( data, &hasNewLines );
+ if ( !data ) {
+ *data_p = NULL;
+ return pi->token;
+ }
+ if ( hasNewLines && !allowLineBreaks ) {
+ *data_p = data;
+ return pi->token;
+ }
+
+ c = *data;
+
+ // skip double slash comments
+ if ( c == '/' && data[1] == '/' ) {
+ while (*data && *data != '\n') {
+ data++;
+ }
+ continue;
+ }
+
+ // skip /* */ comments
+ if ( c=='/' && data[1] == '*' ) {
+ while ( *data && ( *data != '*' || data[1] != '/' ) ) {
+ if( *data == '\n' ) {
+ pi->lines++;
+ }
+ data++;
+ }
+ if ( *data ) {
+ data += 2;
+ }
+ continue;
+ }
+
+ // a real token to parse
+ break;
+ }
+
+ // handle quoted strings
+ if ( c == '\"' ) {
+ data++;
+ while( 1 ) {
+ c = *data++;
+ if ( ( c=='\\' ) && ( *data == '\"' ) ) {
+ // allow quoted strings to use \" to indicate the " character
+ data++;
+ } else if ( c=='\"' || !c ) {
+ pi->token[len] = 0;
+ *data_p = ( char * ) data;
+ return pi->token;
+ } else if( *data == '\n' ) {
+ pi->lines++;
+ }
+ if ( len < MAX_TOKEN_CHARS - 1 ) {
+ pi->token[len] = c;
+ len++;
+ }
+ }
+ }
+
+ // check for a number
+ // is this parsing of negative numbers going to cause expression problems
+ if ( ( c >= '0' && c <= '9' ) || ( c == '-' && data[ 1 ] >= '0' && data[ 1 ] <= '9' ) ||
+ ( c == '.' && data[ 1 ] >= '0' && data[ 1 ] <= '9' ) ) {
+ do {
+
+ if (len < MAX_TOKEN_CHARS - 1) {
+ pi->token[len] = c;
+ len++;
+ }
+ data++;
+
+ c = *data;
+ } while ( ( c >= '0' && c <= '9' ) || c == '.' );
+
+ // parse the exponent
+ if ( c == 'e' || c == 'E' ) {
+ if (len < MAX_TOKEN_CHARS - 1) {
+ pi->token[len] = c;
+ len++;
+ }
+ data++;
+ c = *data;
+
+ if ( c == '-' || c == '+' ) {
+ if (len < MAX_TOKEN_CHARS - 1) {
+ pi->token[len] = c;
+ len++;
+ }
+ data++;
+ c = *data;
+ }
+
+ do {
+ if (len < MAX_TOKEN_CHARS - 1) {
+ pi->token[len] = c;
+ len++;
+ }
+ data++;
+
+ c = *data;
+ } while ( c >= '0' && c <= '9' );
+ }
+
+ if (len == MAX_TOKEN_CHARS) {
+ len = 0;
+ }
+ pi->token[len] = 0;
+
+ *data_p = ( char * ) data;
+ return pi->token;
+ }
+
+ // check for a regular word
+ // we still allow forward and back slashes in name tokens for pathnames
+ // and also colons for drive letters
+ if ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) || c == '_' || c == '/' || c == '\\' ) {
+ do {
+ if (len < MAX_TOKEN_CHARS - 1) {
+ pi->token[len] = c;
+ len++;
+ }
+ data++;
+
+ c = *data;
+ } while ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) || c == '_'
+ || ( c >= '0' && c <= '9' ) || c == '/' || c == '\\' || c == ':' || c == '.' );
+
+ if (len == MAX_TOKEN_CHARS) {
+ len = 0;
+ }
+ pi->token[len] = 0;
+
+ *data_p = ( char * ) data;
+ return pi->token;
+ }
+
+ // check for multi-character punctuation token
+ for ( punc = punctuation ; *punc ; punc++ ) {
+ int l;
+ int j;
+
+ l = strlen( *punc );
+ for ( j = 0 ; j < l ; j++ ) {
+ if ( data[j] != (*punc)[j] ) {
+ break;
+ }
+ }
+ if ( j == l ) {
+ // a valid multi-character punctuation
+ memcpy( pi->token, *punc, l );
+ pi->token[l] = 0;
+ data += l;
+ *data_p = (char *)data;
+ return pi->token;
+ }
+ }
+
+ // single character punctuation
+ pi->token[0] = *data;
+ pi->token[1] = 0;
+ data++;
+ *data_p = (char *)data;
+
+ return pi->token;
+}
+
+/*
+===================
+Com_Parse
+===================
+*/
+const char *Com_Parse( const char *(*data_p) ) {
+ if ( pi->ungetToken ) {
+ pi->ungetToken = qfalse;
+ return pi->token;
+ }
+ return Com_ParseExt( data_p, qtrue );
+}
+
+/*
+===================
+Com_ParseOnLine
+===================
+*/
+const char *Com_ParseOnLine( const char *(*data_p) ) {
+ if ( pi->ungetToken ) {
+ pi->ungetToken = qfalse;
+ return pi->token;
+ }
+ return Com_ParseExt( data_p, qfalse );
+}
+
+
+
+/*
+==================
+Com_MatchToken
+==================
+*/
+void Com_MatchToken( const char *(*buf_p), const char *match, qboolean warning ) {
+ const char *token;
+
+ token = Com_Parse( buf_p );
+ if ( strcmp( token, match ) ) {
+ if (warning) {
+ Com_ScriptWarning( "MatchToken: %s != %s", token, match );
+ } else {
+ Com_ScriptError( "MatchToken: %s != %s", token, match );
+ }
+ }
+}
+
+
+/*
+=================
+Com_SkipBracedSection
+
+The next token should be an open brace.
+Skips until a matching close brace is found.
+Internal brace depths are properly skipped.
+=================
+*/
+void Com_SkipBracedSection( const char *(*program) ) {
+ const char *token;
+ int depth;
+
+ depth = 0;
+ do {
+ token = Com_Parse( program );
+ if( token[1] == 0 ) {
+ if( token[0] == '{' ) {
+ depth++;
+ }
+ else if( token[0] == '}' ) {
+ depth--;
+ }
+ }
+ } while( depth && *program );
+}
+
+/*
+=================
+Com_SkipRestOfLine
+=================
+*/
+void Com_SkipRestOfLine ( const char *(*data) ) {
+ const char *p;
+ int c;
+
+ p = *data;
+ while ( (c = *p++) != 0 ) {
+ if ( c == '\n' ) {
+ pi->lines++;
+ break;
+ }
+ }
+
+ *data = p;
+}
+
+/*
+====================
+Com_ParseRestOfLine
+====================
+*/
+const char *Com_ParseRestOfLine( const char *(*data_p) ) {
+ static char line[MAX_TOKEN_CHARS];
+ const char *token;
+
+ line[0] = 0;
+ while( 1 ) {
+ token = Com_ParseOnLine( data_p );
+ if ( !token[0] ) {
+ break;
+ }
+ if ( line[0] ) {
+ Q_strcat( line, sizeof(line), " " );
+ }
+ Q_strcat( line, sizeof(line), token );
+ }
+
+ return line;
+}
+
+
+float Com_ParseFloat( const char *(*buf_p) ) {
+ const char *token;
+
+ token = Com_Parse( buf_p );
+ if ( !token[0] ) {
+ return 0;
+ }
+ return atof( token );
+}
+
+int Com_ParseInt( const char *(*buf_p) ) {
+ const char *token;
+
+ token = Com_Parse( buf_p );
+ if ( !token[0] ) {
+ return 0;
+ }
+ return atof( token );
+}
+
+
+
+void Com_Parse1DMatrix( const char *(*buf_p), int x, float *m ) {
+ const char *token;
+ int i;
+
+ Com_MatchToken( buf_p, "(" );
+
+ for (i = 0 ; i < x ; i++) {
+ token = Com_Parse(buf_p);
+ m[i] = atof(token);
+ }
+
+ Com_MatchToken( buf_p, ")" );
+}
+
+void Com_Parse2DMatrix( const char *(*buf_p), int y, int x, float *m ) {
+ int i;
+
+ Com_MatchToken( buf_p, "(" );
+
+ for (i = 0 ; i < y ; i++) {
+ Com_Parse1DMatrix (buf_p, x, m + i * x);
+ }
+
+ Com_MatchToken( buf_p, ")" );
+}
+
+void Com_Parse3DMatrix( const char *(*buf_p), int z, int y, int x, float *m ) {
+ int i;
+
+ Com_MatchToken( buf_p, "(" );
+
+ for (i = 0 ; i < z ; i++) {
+ Com_Parse2DMatrix (buf_p, y, x, m + i * x*y);
+ }
+
+ Com_MatchToken( buf_p, ")" );
+}
+
diff --git a/q3radiant/splines/q_shared.cpp b/q3radiant/splines/q_shared.cpp
new file mode 100755
index 0000000..56cbcf1
--- /dev/null
+++ b/q3radiant/splines/q_shared.cpp
@@ -0,0 +1,976 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+// q_shared.c -- stateless support routines that are included in each code dll
+#include "q_shared.h"
+
+/*
+============================================================================
+
+GROWLISTS
+
+============================================================================
+*/
+
+// malloc / free all in one place for debugging
+extern "C" void *Com_Allocate( int bytes );
+extern "C" void Com_Dealloc( void *ptr );
+
+void Com_InitGrowList( growList_t *list, int maxElements ) {
+ list->maxElements = maxElements;
+ list->currentElements = 0;
+ list->elements = (void **)Com_Allocate( list->maxElements * sizeof( void * ) );
+}
+
+int Com_AddToGrowList( growList_t *list, void *data ) {
+ void **old;
+
+ if ( list->currentElements != list->maxElements ) {
+ list->elements[list->currentElements] = data;
+ return list->currentElements++;
+ }
+
+ // grow, reallocate and move
+ old = list->elements;
+
+ if ( list->maxElements < 0 ) {
+ Com_Error( ERR_FATAL, "Com_AddToGrowList: maxElements = %i", list->maxElements );
+ }
+
+ if ( list->maxElements == 0 ) {
+ // initialize the list to hold 100 elements
+ Com_InitGrowList( list, 100 );
+ return Com_AddToGrowList( list, data );
+ }
+
+ list->maxElements *= 2;
+
+ Com_DPrintf( "Resizing growlist to %i maxElements\n", list->maxElements );
+
+ list->elements = (void **)Com_Allocate( list->maxElements * sizeof( void * ) );
+
+ if ( !list->elements ) {
+ Com_Error( ERR_DROP, "Growlist alloc failed" );
+ }
+
+ memcpy( list->elements, old, list->currentElements * sizeof( void * ) );
+
+ Com_Dealloc( old );
+
+ return Com_AddToGrowList( list, data );
+}
+
+void *Com_GrowListElement( const growList_t *list, int index ) {
+ if ( index < 0 || index >= list->currentElements ) {
+ Com_Error( ERR_DROP, "Com_GrowListElement: %i out of range of %i",
+ index, list->currentElements );
+ }
+ return list->elements[index];
+}
+
+int Com_IndexForGrowListElement( const growList_t *list, const void *element ) {
+ int i;
+
+ for ( i = 0 ; i < list->currentElements ; i++ ) {
+ if ( list->elements[i] == element ) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+//============================================================================
+
+
+float Com_Clamp( float min, float max, float value ) {
+ if ( value < min ) {
+ return min;
+ }
+ if ( value > max ) {
+ return max;
+ }
+ return value;
+}
+
+/*
+============
+Com_StringContains
+============
+*/
+const char *Com_StringContains( const char *str1, const char *str2, int casesensitive) {
+ int len, i, j;
+
+ len = strlen(str1) - strlen(str2);
+ for (i = 0; i <= len; i++, str1++) {
+ for (j = 0; str2[j]; j++) {
+ if (casesensitive) {
+ if (str1[j] != str2[j]) {
+ break;
+ }
+ }
+ else {
+ if (toupper(str1[j]) != toupper(str2[j])) {
+ break;
+ }
+ }
+ }
+ if (!str2[j]) {
+ return str1;
+ }
+ }
+ return NULL;
+}
+
+/*
+============
+Com_Filter
+============
+*/
+int Com_Filter( const char *filter, const char *name, int casesensitive)
+{
+ char buf[MAX_TOKEN_CHARS];
+ const char *ptr;
+ int i, found;
+
+ while(*filter) {
+ if (*filter == '*') {
+ filter++;
+ for (i = 0; *filter; i++) {
+ if (*filter == '*' || *filter == '?') break;
+ buf[i] = *filter;
+ filter++;
+ }
+ buf[i] = '\0';
+ if (strlen(buf)) {
+ ptr = Com_StringContains(name, buf, casesensitive);
+ if (!ptr) return qfalse;
+ name = ptr + strlen(buf);
+ }
+ }
+ else if (*filter == '?') {
+ filter++;
+ name++;
+ }
+ else if (*filter == '[' && *(filter+1) == '[') {
+ filter++;
+ }
+ else if (*filter == '[') {
+ filter++;
+ found = qfalse;
+ while(*filter && !found) {
+ if (*filter == ']' && *(filter+1) != ']') break;
+ if (*(filter+1) == '-' && *(filter+2) && (*(filter+2) != ']' || *(filter+3) == ']')) {
+ if (casesensitive) {
+ if (*name >= *filter && *name <= *(filter+2)) found = qtrue;
+ }
+ else {
+ if (toupper(*name) >= toupper(*filter) &&
+ toupper(*name) <= toupper(*(filter+2))) found = qtrue;
+ }
+ filter += 3;
+ }
+ else {
+ if (casesensitive) {
+ if (*filter == *name) found = qtrue;
+ }
+ else {
+ if (toupper(*filter) == toupper(*name)) found = qtrue;
+ }
+ filter++;
+ }
+ }
+ if (!found) return qfalse;
+ while(*filter) {
+ if (*filter == ']' && *(filter+1) != ']') break;
+ filter++;
+ }
+ filter++;
+ name++;
+ }
+ else {
+ if (casesensitive) {
+ if (*filter != *name) return qfalse;
+ }
+ else {
+ if (toupper(*filter) != toupper(*name)) return qfalse;
+ }
+ filter++;
+ name++;
+ }
+ }
+ return qtrue;
+}
+
+
+/*
+================
+Com_HashString
+
+================
+*/
+int Com_HashString( const char *fname ) {
+ int i;
+ long hash;
+ char letter;
+
+ hash = 0;
+ i = 0;
+ while (fname[i] != '\0') {
+ letter = tolower(fname[i]);
+ if (letter =='.') break; // don't include extension
+ if (letter =='\\') letter = '/'; // damn path names
+ hash+=(long)(letter)*(i+119);
+ i++;
+ }
+ hash &= (FILE_HASH_SIZE-1);
+ return hash;
+}
+
+
+/*
+============
+Com_SkipPath
+============
+*/
+char *Com_SkipPath (char *pathname)
+{
+ char *last;
+
+ last = pathname;
+ while (*pathname)
+ {
+ if (*pathname=='/')
+ last = pathname+1;
+ pathname++;
+ }
+ return last;
+}
+
+/*
+============
+Com_StripExtension
+============
+*/
+void Com_StripExtension( const char *in, char *out ) {
+ while ( *in && *in != '.' ) {
+ *out++ = *in++;
+ }
+ *out = 0;
+}
+
+
+/*
+==================
+Com_DefaultExtension
+==================
+*/
+void Com_DefaultExtension (char *path, int maxSize, const char *extension ) {
+ char oldPath[MAX_QPATH];
+ char *src;
+
+//
+// if path doesn't have a .EXT, append extension
+// (extension should include the .)
+//
+ src = path + strlen(path) - 1;
+
+ while (*src != '/' && src != path) {
+ if ( *src == '.' ) {
+ return; // it has an extension
+ }
+ src--;
+ }
+
+ Q_strncpyz( oldPath, path, sizeof( oldPath ) );
+ Com_sprintf( path, maxSize, "%s%s", oldPath, extension );
+}
+
+/*
+============================================================================
+
+ BYTE ORDER FUNCTIONS
+
+============================================================================
+*/
+
+// can't just use function pointers, or dll linkage can
+// mess up when qcommon is included in multiple places
+static short (*_BigShort) (short l);
+static short (*_LittleShort) (short l);
+static int (*_BigLong) (int l);
+static int (*_LittleLong) (int l);
+static float (*_BigFloat) (float l);
+static float (*_LittleFloat) (float l);
+
+short BigShort(short l){return _BigShort(l);}
+short LittleShort(short l) {return _LittleShort(l);}
+int BigLong (int l) {return _BigLong(l);}
+int LittleLong (int l) {return _LittleLong(l);}
+float BigFloat (float l) {return _BigFloat(l);}
+float LittleFloat (float l) {return _LittleFloat(l);}
+
+short ShortSwap (short l)
+{
+ byte b1,b2;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+
+ return (b1<<8) + b2;
+}
+
+short ShortNoSwap (short l)
+{
+ return l;
+}
+
+int LongSwap (int l)
+{
+ byte b1,b2,b3,b4;
+
+ b1 = l&255;
+ b2 = (l>>8)&255;
+ b3 = (l>>16)&255;
+ b4 = (l>>24)&255;
+
+ return ((int)b1<<24) + ((int)b2<<16) + ((int)b3<<8) + b4;
+}
+
+int LongNoSwap (int l)
+{
+ return l;
+}
+
+float FloatSwap (float f)
+{
+ union
+ {
+ float f;
+ byte b[4];
+ } dat1, dat2;
+
+
+ dat1.f = f;
+ dat2.b[0] = dat1.b[3];
+ dat2.b[1] = dat1.b[2];
+ dat2.b[2] = dat1.b[1];
+ dat2.b[3] = dat1.b[0];
+ return dat2.f;
+}
+
+float FloatNoSwap (float f)
+{
+ return f;
+}
+
+/*
+================
+Swap_Init
+================
+*/
+void Swap_Init (void)
+{
+ byte swaptest[2] = {1,0};
+
+// set the byte swapping variables in a portable manner
+ if ( *(short *)swaptest == 1)
+ {
+ _BigShort = ShortSwap;
+ _LittleShort = ShortNoSwap;
+ _BigLong = LongSwap;
+ _LittleLong = LongNoSwap;
+ _BigFloat = FloatSwap;
+ _LittleFloat = FloatNoSwap;
+ }
+ else
+ {
+ _BigShort = ShortNoSwap;
+ _LittleShort = ShortSwap;
+ _BigLong = LongNoSwap;
+ _LittleLong = LongSwap;
+ _BigFloat = FloatNoSwap;
+ _LittleFloat = FloatSwap;
+ }
+
+}
+
+/*
+===============
+Com_ParseInfos
+===============
+*/
+int Com_ParseInfos( const char *buf, int max, char infos[][MAX_INFO_STRING] ) {
+ const char *token;
+ int count;
+ char key[MAX_TOKEN_CHARS];
+
+ count = 0;
+
+ while ( 1 ) {
+ token = Com_Parse( &buf );
+ if ( !token[0] ) {
+ break;
+ }
+ if ( strcmp( token, "{" ) ) {
+ Com_Printf( "Missing { in info file\n" );
+ break;
+ }
+
+ if ( count == max ) {
+ Com_Printf( "Max infos exceeded\n" );
+ break;
+ }
+
+ infos[count][0] = 0;
+ while ( 1 ) {
+ token = Com_Parse( &buf );
+ if ( !token[0] ) {
+ Com_Printf( "Unexpected end of info file\n" );
+ break;
+ }
+ if ( !strcmp( token, "}" ) ) {
+ break;
+ }
+ Q_strncpyz( key, token, sizeof( key ) );
+
+ token = Com_ParseOnLine( &buf );
+ if ( !token[0] ) {
+ token = "<NULL>";
+ }
+ Info_SetValueForKey( infos[count], key, token );
+ }
+ count++;
+ }
+
+ return count;
+}
+
+
+
+/*
+============================================================================
+
+ LIBRARY REPLACEMENT FUNCTIONS
+
+============================================================================
+*/
+
+int Q_isprint( int c )
+{
+ if ( c >= 0x20 && c <= 0x7E )
+ return ( 1 );
+ return ( 0 );
+}
+
+int Q_islower( int c )
+{
+ if (c >= 'a' && c <= 'z')
+ return ( 1 );
+ return ( 0 );
+}
+
+int Q_isupper( int c )
+{
+ if (c >= 'A' && c <= 'Z')
+ return ( 1 );
+ return ( 0 );
+}
+
+int Q_isalpha( int c )
+{
+ if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
+ return ( 1 );
+ return ( 0 );
+}
+
+char* Q_strrchr( const char* string, int c )
+{
+ char cc = c;
+ char *s;
+ char *sp=(char *)0;
+
+ s = (char*)string;
+
+ while (*s)
+ {
+ if (*s == cc)
+ sp = s;
+ s++;
+ }
+ if (cc == 0)
+ sp = s;
+
+ return sp;
+}
+
+/*
+=============
+Q_strncpyz
+
+Safe strncpy that ensures a trailing zero
+=============
+*/
+void Q_strncpyz( char *dest, const char *src, int destsize ) {
+ if ( !src ) {
+ Com_Error( ERR_FATAL, "Q_strncpyz: NULL src" );
+ }
+ if ( destsize < 1 ) {
+ Com_Error(ERR_FATAL,"Q_strncpyz: destsize < 1" );
+ }
+
+ strncpy( dest, src, destsize-1 );
+ dest[destsize-1] = 0;
+}
+
+int Q_stricmpn (const char *s1, const char *s2, int n) {
+ int c1, c2;
+
+ do {
+ c1 = *s1++;
+ c2 = *s2++;
+
+ if (!n--) {
+ return 0; // strings are equal until end point
+ }
+
+ if (c1 != c2) {
+ if (c1 >= 'a' && c1 <= 'z') {
+ c1 -= ('a' - 'A');
+ }
+ if (c2 >= 'a' && c2 <= 'z') {
+ c2 -= ('a' - 'A');
+ }
+ if (c1 != c2) {
+ return c1 < c2 ? -1 : 1;
+ }
+ }
+ } while (c1);
+
+ return 0; // strings are equal
+}
+
+int Q_strncmp (const char *s1, const char *s2, int n) {
+ int c1, c2;
+
+ do {
+ c1 = *s1++;
+ c2 = *s2++;
+
+ if (!n--) {
+ return 0; // strings are equal until end point
+ }
+
+ if (c1 != c2) {
+ return c1 < c2 ? -1 : 1;
+ }
+ } while (c1);
+
+ return 0; // strings are equal
+}
+
+int Q_stricmp (const char *s1, const char *s2) {
+ return Q_stricmpn (s1, s2, 99999);
+}
+
+
+char *Q_strlwr( char *s1 ) {
+ char *s;
+
+ s = s1;
+ while ( *s ) {
+ *s = tolower(*s);
+ s++;
+ }
+ return s1;
+}
+
+char *Q_strupr( char *s1 ) {
+ char *s;
+
+ s = s1;
+ while ( *s ) {
+ *s = toupper(*s);
+ s++;
+ }
+ return s1;
+}
+
+
+// never goes past bounds or leaves without a terminating 0
+void Q_strcat( char *dest, int size, const char *src ) {
+ int l1;
+
+ l1 = strlen( dest );
+ if ( l1 >= size ) {
+ Com_Error( ERR_FATAL, "Q_strcat: already overflowed" );
+ }
+ Q_strncpyz( dest + l1, src, size - l1 );
+}
+
+
+int Q_PrintStrlen( const char *string ) {
+ int len;
+ const char *p;
+
+ if( !string ) {
+ return 0;
+ }
+
+ len = 0;
+ p = string;
+ while( *p ) {
+ if( Q_IsColorString( p ) ) {
+ p += 2;
+ continue;
+ }
+ p++;
+ len++;
+ }
+
+ return len;
+}
+
+
+char *Q_CleanStr( char *string ) {
+ char* d;
+ char* s;
+ int c;
+
+ s = string;
+ d = string;
+ while ((c = *s) != 0 ) {
+ if ( Q_IsColorString( s ) ) {
+ s++;
+ }
+ else if ( c >= 0x20 && c <= 0x7E ) {
+ *d++ = c;
+ }
+ s++;
+ }
+ *d = '\0';
+
+ return string;
+}
+
+
+void QDECL Com_sprintf( char *dest, int size, const char *fmt, ...) {
+ int len;
+ va_list argptr;
+ char bigbuffer[32000]; // big, but small enough to fit in PPC stack
+
+ va_start (argptr,fmt);
+ len = vsprintf (bigbuffer,fmt,argptr);
+ va_end (argptr);
+ if ( len >= sizeof( bigbuffer ) ) {
+ Com_Error( ERR_FATAL, "Com_sprintf: overflowed bigbuffer" );
+ }
+ if (len >= size) {
+ Com_Printf ("Com_sprintf: overflow of %i in %i\n", len, size);
+ }
+ Q_strncpyz (dest, bigbuffer, size );
+}
+
+
+/*
+============
+va
+
+does a varargs printf into a temp buffer, so I don't need to have
+varargs versions of all text functions.
+FIXME: make this buffer size safe someday
+============
+*/
+char * QDECL va( char *format, ... ) {
+ va_list argptr;
+ static char string[2][32000]; // in case va is called by nested functions
+ static int index = 0;
+ char *buf;
+
+ buf = string[index & 1];
+ index++;
+
+ va_start (argptr, format);
+ vsprintf (buf, format,argptr);
+ va_end (argptr);
+
+ return buf;
+}
+
+
+/*
+=====================================================================
+
+ INFO STRINGS
+
+=====================================================================
+*/
+
+/*
+===============
+Info_ValueForKey
+
+Searches the string for the given
+key and returns the associated value, or an empty string.
+FIXME: overflow check?
+===============
+*/
+char *Info_ValueForKey( const char *s, const char *key ) {
+ char pkey[MAX_INFO_KEY];
+ static char value[2][MAX_INFO_VALUE]; // use two buffers so compares
+ // work without stomping on each other
+ static int valueindex = 0;
+ char *o;
+
+ if ( !s || !key ) {
+ return "";
+ }
+
+ if ( strlen( s ) >= MAX_INFO_STRING ) {
+ Com_Error( ERR_DROP, "Info_ValueForKey: oversize infostring" );
+ }
+
+ valueindex ^= 1;
+ if (*s == '\\')
+ s++;
+ while (1)
+ {
+ o = pkey;
+ while (*s != '\\')
+ {
+ if (!*s)
+ return "";
+ *o++ = *s++;
+ }
+ *o = 0;
+ s++;
+
+ o = value[valueindex];
+
+ while (*s != '\\' && *s)
+ {
+ *o++ = *s++;
+ }
+ *o = 0;
+
+ if (!Q_stricmp (key, pkey) )
+ return value[valueindex];
+
+ if (!*s)
+ break;
+ s++;
+ }
+
+ return "";
+}
+
+
+/*
+===================
+Info_NextPair
+
+Used to itterate through all the key/value pairs in an info string
+===================
+*/
+void Info_NextPair( const char *(*head), char key[MAX_INFO_KEY], char value[MAX_INFO_VALUE] ) {
+ char *o;
+ const char *s;
+
+ s = *head;
+
+ if ( *s == '\\' ) {
+ s++;
+ }
+ key[0] = 0;
+ value[0] = 0;
+
+ o = key;
+ while ( *s != '\\' ) {
+ if ( !*s ) {
+ *o = 0;
+ *head = s;
+ return;
+ }
+ *o++ = *s++;
+ }
+ *o = 0;
+ s++;
+
+ o = value;
+ while ( *s != '\\' && *s ) {
+ *o++ = *s++;
+ }
+ *o = 0;
+
+ *head = s;
+}
+
+
+/*
+===================
+Info_RemoveKey
+===================
+*/
+void Info_RemoveKey( char *s, const char *key ) {
+ char *start;
+ char pkey[MAX_INFO_KEY];
+ char value[MAX_INFO_VALUE];
+ char *o;
+
+ if ( strlen( s ) >= MAX_INFO_STRING ) {
+ Com_Error( ERR_DROP, "Info_RemoveKey: oversize infostring" );
+ }
+
+ if (strchr (key, '\\')) {
+ return;
+ }
+
+ while (1)
+ {
+ start = s;
+ if (*s == '\\')
+ s++;
+ o = pkey;
+ while (*s != '\\')
+ {
+ if (!*s)
+ return;
+ *o++ = *s++;
+ }
+ *o = 0;
+ s++;
+
+ o = value;
+ while (*s != '\\' && *s)
+ {
+ if (!*s)
+ return;
+ *o++ = *s++;
+ }
+ *o = 0;
+
+ if (!strcmp (key, pkey) )
+ {
+ strcpy (start, s); // remove this part
+ return;
+ }
+
+ if (!*s)
+ return;
+ }
+
+}
+
+
+/*
+==================
+Info_Validate
+
+Some characters are illegal in info strings because they
+can mess up the server's parsing
+==================
+*/
+qboolean Info_Validate( const char *s ) {
+ if ( strchr( s, '\"' ) ) {
+ return qfalse;
+ }
+ if ( strchr( s, ';' ) ) {
+ return qfalse;
+ }
+ return qtrue;
+}
+
+/*
+==================
+Info_SetValueForKey
+
+Changes or adds a key/value pair
+==================
+*/
+void Info_SetValueForKey( char *s, const char *key, const char *value ) {
+ char newi[MAX_INFO_STRING];
+
+ if ( strlen( s ) >= MAX_INFO_STRING ) {
+ Com_Error( ERR_DROP, "Info_SetValueForKey: oversize infostring" );
+ }
+
+ if (strchr (key, '\\') || strchr (value, '\\'))
+ {
+ Com_Printf ("Can't use keys or values with a \\\n");
+ return;
+ }
+
+ if (strchr (key, ';') || strchr (value, ';'))
+ {
+ Com_Printf ("Can't use keys or values with a semicolon\n");
+ return;
+ }
+
+ if (strchr (key, '\"') || strchr (value, '\"'))
+ {
+ Com_Printf ("Can't use keys or values with a \"\n");
+ return;
+ }
+
+ Info_RemoveKey (s, key);
+ if (!value || !strlen(value))
+ return;
+
+ Com_sprintf (newi, sizeof(newi), "\\%s\\%s", key, value);
+
+ if (strlen(newi) + strlen(s) > MAX_INFO_STRING)
+ {
+ Com_Printf ("Info string length exceeded\n");
+ return;
+ }
+
+ strcat (s, newi);
+}
+
+//====================================================================
+
+
+/*
+===============
+ParseHex
+===============
+*/
+int ParseHex( const char *text ) {
+ int value;
+ int c;
+
+ value = 0;
+ while ( ( c = *text++ ) != 0 ) {
+ if ( c >= '0' && c <= '9' ) {
+ value = value * 16 + c - '0';
+ continue;
+ }
+ if ( c >= 'a' && c <= 'f' ) {
+ value = value * 16 + 10 + c - 'a';
+ continue;
+ }
+ if ( c >= 'A' && c <= 'F' ) {
+ value = value * 16 + 10 + c - 'A';
+ continue;
+ }
+ }
+
+ return value;
+}
diff --git a/q3radiant/splines/q_shared.h b/q3radiant/splines/q_shared.h
new file mode 100755
index 0000000..6d9a563
--- /dev/null
+++ b/q3radiant/splines/q_shared.h
@@ -0,0 +1,798 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __Q_SHARED_H
+#define __Q_SHARED_H
+
+// q_shared.h -- included first by ALL program modules.
+// these are the definitions that have no dependance on
+// central system services, and can be used by any part
+// of the program without any state issues.
+
+// A user mod should never modify this file
+
+#define Q3_VERSION "DOOM 0.01"
+
+// alignment macros for SIMD
+#define ALIGN_ON
+#define ALIGN_OFF
+
+#ifdef _WIN32
+
+#pragma warning(disable : 4018) // signed/unsigned mismatch
+#pragma warning(disable : 4032)
+#pragma warning(disable : 4051)
+#pragma warning(disable : 4057) // slightly different base types
+#pragma warning(disable : 4100) // unreferenced formal parameter
+#pragma warning(disable : 4115)
+#pragma warning(disable : 4125) // decimal digit terminates octal escape sequence
+#pragma warning(disable : 4127) // conditional expression is constant
+#pragma warning(disable : 4136)
+#pragma warning(disable : 4201)
+#pragma warning(disable : 4214)
+#pragma warning(disable : 4244)
+#pragma warning(disable : 4305) // truncation from const double to float
+#pragma warning(disable : 4310) // cast truncates constant value
+#pragma warning(disable : 4514)
+#pragma warning(disable : 4711) // selected for automatic inline expansion
+#pragma warning(disable : 4220) // varargs matches remaining parameters
+
+#endif
+
+#include <assert.h>
+#include <math.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <string.h>
+#include <stdlib.h>
+#include <time.h>
+#include <ctype.h>
+#ifdef WIN32 // mac doesn't have malloc.h
+#include <malloc.h> // for _alloca()
+#endif
+#ifdef _WIN32
+
+//#pragma intrinsic( memset, memcpy )
+
+#endif
+
+
+// this is the define for determining if we have an asm version of a C function
+#if (defined _M_IX86 || defined __i386__) && !defined __sun__ && !defined __LCC__
+#define id386 1
+#else
+#define id386 0
+#endif
+
+// for windows fastcall option
+
+#define QDECL
+
+//======================= WIN32 DEFINES =================================
+
+#ifdef WIN32
+
+#define MAC_STATIC
+
+#undef QDECL
+#define QDECL __cdecl
+
+// buildstring will be incorporated into the version string
+#ifdef NDEBUG
+#ifdef _M_IX86
+#define CPUSTRING "win-x86"
+#elif defined _M_ALPHA
+#define CPUSTRING "win-AXP"
+#endif
+#else
+#ifdef _M_IX86
+#define CPUSTRING "win-x86-debug"
+#elif defined _M_ALPHA
+#define CPUSTRING "win-AXP-debug"
+#endif
+#endif
+
+
+#define PATH_SEP '\\'
+
+#endif
+
+//======================= MAC OS X SERVER DEFINES =====================
+
+#if defined(__MACH__) && defined(__APPLE__)
+
+#define MAC_STATIC
+
+#ifdef __ppc__
+#define CPUSTRING "MacOSXS-ppc"
+#elif defined __i386__
+#define CPUSTRING "MacOSXS-i386"
+#else
+#define CPUSTRING "MacOSXS-other"
+#endif
+
+#define PATH_SEP '/'
+
+#define GAME_HARD_LINKED
+#define CGAME_HARD_LINKED
+#define UI_HARD_LINKED
+#define _alloca alloca
+
+#undef ALIGN_ON
+#undef ALIGN_OFF
+#define ALIGN_ON #pragma align(16)
+#define ALIGN_OFF #pragma align()
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+void *osxAllocateMemory(long size);
+void osxFreeMemory(void *pointer);
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif
+
+//======================= MAC DEFINES =================================
+
+#ifdef __MACOS__
+
+#define MAC_STATIC static
+
+#define CPUSTRING "MacOS-PPC"
+
+#define PATH_SEP ':'
+
+void Sys_PumpEvents( void );
+
+#endif
+
+#ifdef __MRC__
+
+#define MAC_STATIC
+
+#define CPUSTRING "MacOS-PPC"
+
+#define PATH_SEP ':'
+
+void Sys_PumpEvents( void );
+
+#undef QDECL
+#define QDECL __cdecl
+
+#define _alloca alloca
+#endif
+
+//======================= LINUX DEFINES =================================
+
+// the mac compiler can't handle >32k of locals, so we
+// just waste space and make big arrays static...
+#ifdef __linux__
+
+#define MAC_STATIC
+
+#ifdef __i386__
+#define CPUSTRING "linux-i386"
+#elif defined __axp__
+#define CPUSTRING "linux-alpha"
+#else
+#define CPUSTRING "linux-other"
+#endif
+
+#define PATH_SEP '/'
+
+#endif
+
+//=============================================================
+
+
+
+typedef enum {qfalse, qtrue} qboolean;
+
+typedef unsigned char byte;
+
+#define EQUAL_EPSILON 0.001
+
+typedef int qhandle_t;
+typedef int sfxHandle_t;
+typedef int fileHandle_t;
+typedef int clipHandle_t;
+
+typedef enum {
+ INVALID_JOINT = -1
+} jointHandle_t;
+
+#ifndef NULL
+#define NULL ((void *)0)
+#endif
+
+#define MAX_QINT 0x7fffffff
+#define MIN_QINT (-MAX_QINT-1)
+
+#ifndef max
+#define max( x, y ) ( ( ( x ) > ( y ) ) ? ( x ) : ( y ) )
+#define min( x, y ) ( ( ( x ) < ( y ) ) ? ( x ) : ( y ) )
+#endif
+
+#ifndef sign
+#define sign( f ) ( ( f > 0 ) ? 1 : ( ( f < 0 ) ? -1 : 0 ) )
+#endif
+
+// angle indexes
+#define PITCH 0 // up / down
+#define YAW 1 // left / right
+#define ROLL 2 // fall over
+
+// the game guarantees that no string from the network will ever
+// exceed MAX_STRING_CHARS
+#define MAX_STRING_CHARS 1024 // max length of a string passed to Cmd_TokenizeString
+#define MAX_STRING_TOKENS 256 // max tokens resulting from Cmd_TokenizeString
+#define MAX_TOKEN_CHARS 1024 // max length of an individual token
+
+#define MAX_INFO_STRING 1024
+#define MAX_INFO_KEY 1024
+#define MAX_INFO_VALUE 1024
+
+
+#define MAX_QPATH 64 // max length of a quake game pathname
+#define MAX_OSPATH 128 // max length of a filesystem pathname
+
+#define MAX_NAME_LENGTH 32 // max length of a client name
+
+// paramters for command buffer stuffing
+typedef enum {
+ EXEC_NOW, // don't return until completed, a VM should NEVER use this,
+ // because some commands might cause the VM to be unloaded...
+ EXEC_INSERT, // insert at current position, but don't run yet
+ EXEC_APPEND // add to end of the command buffer (normal case)
+} cbufExec_t;
+
+
+//
+// these aren't needed by any of the VMs. put in another header?
+//
+#define MAX_MAP_AREA_BYTES 32 // bit vector of area visibility
+
+#undef ERR_FATAL // malloc.h on unix
+
+// parameters to the main Error routine
+typedef enum {
+ ERR_NONE,
+ ERR_FATAL, // exit the entire game with a popup window
+ ERR_DROP, // print to console and disconnect from game
+ ERR_DISCONNECT, // don't kill server
+ ERR_NEED_CD // pop up the need-cd dialog
+} errorParm_t;
+
+
+// font rendering values used by ui and cgame
+
+#define PROP_GAP_WIDTH 3
+#define PROP_SPACE_WIDTH 8
+#define PROP_HEIGHT 27
+#define PROP_SMALL_SIZE_SCALE 0.75
+
+#define BLINK_DIVISOR 200
+#define PULSE_DIVISOR 75
+
+#define UI_LEFT 0x00000000 // default
+#define UI_CENTER 0x00000001
+#define UI_RIGHT 0x00000002
+#define UI_FORMATMASK 0x00000007
+#define UI_SMALLFONT 0x00000010
+#define UI_BIGFONT 0x00000020 // default
+#define UI_GIANTFONT 0x00000040
+#define UI_DROPSHADOW 0x00000800
+#define UI_BLINK 0x00001000
+#define UI_INVERSE 0x00002000
+#define UI_PULSE 0x00004000
+
+
+/*
+==============================================================
+
+MATHLIB
+
+==============================================================
+*/
+#ifdef __cplusplus // so we can include this in C code
+#define SIDE_FRONT 0
+#define SIDE_BACK 1
+#define SIDE_ON 2
+#define SIDE_CROSS 3
+
+#define Q_PI 3.14159265358979323846
+#ifndef M_PI
+#define M_PI 3.14159265358979323846 // matches value in gcc v2 math.h
+#endif
+
+#include "math_vector.h"
+#include "math_angles.h"
+#include "math_matrix.h"
+#include "math_quaternion.h"
+
+class idVec3_t; // for defining vectors
+typedef idVec3_t &vec3_p; // for passing vectors as function arguments
+typedef const idVec3_t &vec3_c; // for passing vectors as const function arguments
+
+class angles_t; // for defining angle vectors
+typedef angles_t &angles_p; // for passing angles as function arguments
+typedef const angles_t &angles_c; // for passing angles as const function arguments
+
+class mat3_t; // for defining matrices
+typedef mat3_t &mat3_p; // for passing matrices as function arguments
+typedef const mat3_t &mat3_c; // for passing matrices as const function arguments
+
+
+
+#define NUMVERTEXNORMALS 162
+extern idVec3_t bytedirs[NUMVERTEXNORMALS];
+
+// all drawing is done to a 640*480 virtual screen size
+// and will be automatically scaled to the real resolution
+#define SCREEN_WIDTH 640
+#define SCREEN_HEIGHT 480
+
+#define TINYCHAR_WIDTH (SMALLCHAR_WIDTH)
+#define TINYCHAR_HEIGHT (SMALLCHAR_HEIGHT/2)
+
+#define SMALLCHAR_WIDTH 8
+#define SMALLCHAR_HEIGHT 16
+
+#define BIGCHAR_WIDTH 16
+#define BIGCHAR_HEIGHT 16
+
+#define GIANTCHAR_WIDTH 32
+#define GIANTCHAR_HEIGHT 48
+
+extern vec4_t colorBlack;
+extern vec4_t colorRed;
+extern vec4_t colorGreen;
+extern vec4_t colorBlue;
+extern vec4_t colorYellow;
+extern vec4_t colorMagenta;
+extern vec4_t colorCyan;
+extern vec4_t colorWhite;
+extern vec4_t colorLtGrey;
+extern vec4_t colorMdGrey;
+extern vec4_t colorDkGrey;
+
+#define Q_COLOR_ESCAPE '^'
+#define Q_IsColorString(p) ( p && *(p) == Q_COLOR_ESCAPE && *((p)+1) && *((p)+1) != Q_COLOR_ESCAPE )
+
+#define COLOR_BLACK '0'
+#define COLOR_RED '1'
+#define COLOR_GREEN '2'
+#define COLOR_YELLOW '3'
+#define COLOR_BLUE '4'
+#define COLOR_CYAN '5'
+#define COLOR_MAGENTA '6'
+#define COLOR_WHITE '7'
+#define ColorIndex(c) ( ( (c) - '0' ) & 7 )
+
+#define S_COLOR_BLACK "^0"
+#define S_COLOR_RED "^1"
+#define S_COLOR_GREEN "^2"
+#define S_COLOR_YELLOW "^3"
+#define S_COLOR_BLUE "^4"
+#define S_COLOR_CYAN "^5"
+#define S_COLOR_MAGENTA "^6"
+#define S_COLOR_WHITE "^7"
+
+extern vec4_t g_color_table[8];
+
+#define MAKERGB( v, r, g, b ) v[0]=r;v[1]=g;v[2]=b
+#define MAKERGBA( v, r, g, b, a ) v[0]=r;v[1]=g;v[2]=b;v[3]=a
+
+#define DEG2RAD( a ) ( ( (a) * M_PI ) / 180.0F )
+#define RAD2DEG( a ) ( ( (a) * 180.0f ) / M_PI )
+
+struct cplane_s;
+
+extern idVec3_t vec3_origin;
+extern vec4_t vec4_origin;
+extern mat3_t axisDefault;
+
+#define nanmask (255<<23)
+
+#define IS_NAN(x) (((*(int *)&x)&nanmask)==nanmask)
+
+float Q_fabs( float f );
+float Q_rsqrt( float f ); // reciprocal square root
+
+#define SQRTFAST( x ) ( 1.0f / Q_rsqrt( x ) )
+
+signed char ClampChar( int i );
+signed short ClampShort( int i );
+
+// this isn't a real cheap function to call!
+int DirToByte( const idVec3_t &dir );
+void ByteToDir( int b, vec3_p dir );
+
+#define DotProduct(a,b) ((a)[0]*(b)[0]+(a)[1]*(b)[1]+(a)[2]*(b)[2])
+#define VectorSubtract(a,b,c) ((c)[0]=(a)[0]-(b)[0],(c)[1]=(a)[1]-(b)[1],(c)[2]=(a)[2]-(b)[2])
+#define VectorAdd(a,b,c) ((c)[0]=(a)[0]+(b)[0],(c)[1]=(a)[1]+(b)[1],(c)[2]=(a)[2]+(b)[2])
+#define VectorCopy(a,b) ((b)[0]=(a)[0],(b)[1]=(a)[1],(b)[2]=(a)[2])
+//#define VectorCopy(a,b) ((b).x=(a).x,(b).y=(a).y,(b).z=(a).z])
+
+#define VectorScale(v, s, o) ((o)[0]=(v)[0]*(s),(o)[1]=(v)[1]*(s),(o)[2]=(v)[2]*(s))
+#define VectorMA(v, s, b, o) ((o)[0]=(v)[0]+(b)[0]*(s),(o)[1]=(v)[1]+(b)[1]*(s),(o)[2]=(v)[2]+(b)[2]*(s))
+#define CrossProduct(a,b,c) ((c)[0]=(a)[1]*(b)[2]-(a)[2]*(b)[1],(c)[1]=(a)[2]*(b)[0]-(a)[0]*(b)[2],(c)[2]=(a)[0]*(b)[1]-(a)[1]*(b)[0])
+
+#define DotProduct4(x,y) ((x)[0]*(y)[0]+(x)[1]*(y)[1]+(x)[2]*(y)[2]+(x)[3]*(y)[3])
+#define VectorSubtract4(a,b,c) ((c)[0]=(a)[0]-(b)[0],(c)[1]=(a)[1]-(b)[1],(c)[2]=(a)[2]-(b)[2],(c)[3]=(a)[3]-(b)[3])
+#define VectorAdd4(a,b,c) ((c)[0]=(a)[0]+(b)[0],(c)[1]=(a)[1]+(b)[1],(c)[2]=(a)[2]+(b)[2],(c)[3]=(a)[3]+(b)[3])
+#define VectorCopy4(a,b) ((b)[0]=(a)[0],(b)[1]=(a)[1],(b)[2]=(a)[2],(b)[3]=(a)[3])
+#define VectorScale4(v, s, o) ((o)[0]=(v)[0]*(s),(o)[1]=(v)[1]*(s),(o)[2]=(v)[2]*(s),(o)[3]=(v)[3]*(s))
+#define VectorMA4(v, s, b, o) ((o)[0]=(v)[0]+(b)[0]*(s),(o)[1]=(v)[1]+(b)[1]*(s),(o)[2]=(v)[2]+(b)[2]*(s),(o)[3]=(v)[3]+(b)[3]*(s))
+
+
+#define VectorClear(a) ((a)[0]=(a)[1]=(a)[2]=0)
+#define VectorNegate(a,b) ((b)[0]=-(a)[0],(b)[1]=-(a)[1],(b)[2]=-(a)[2])
+#define VectorSet(v, x, y, z) ((v)[0]=(x), (v)[1]=(y), (v)[2]=(z))
+#define Vector4Copy(a,b) ((b)[0]=(a)[0],(b)[1]=(a)[1],(b)[2]=(a)[2],(b)[3]=(a)[3])
+
+#define SnapVector(v) {v[0]=(int)v[0];v[1]=(int)v[1];v[2]=(int)v[2];}
+
+float NormalizeColor( vec3_c in, vec3_p out );
+
+int VectorCompare( vec3_c v1, vec3_c v2 );
+float VectorLength( vec3_c v );
+float Distance( vec3_c p1, vec3_c p2 );
+float DistanceSquared( vec3_c p1, vec3_c p2 );
+float VectorNormalize (vec3_p v); // returns vector length
+void VectorNormalizeFast(vec3_p v); // does NOT return vector length, uses rsqrt approximation
+float VectorNormalize2( vec3_c v, vec3_p out );
+void VectorInverse (vec3_p v);
+void VectorRotate( vec3_c in, mat3_c matrix, vec3_p out );
+void VectorPolar(vec3_p v, float radius, float theta, float phi);
+void VectorSnap(vec3_p v);
+void Vector53Copy( const idVec5_t &in, vec3_p out);
+void Vector5Scale( const idVec5_t &v, float scale, idVec5_t &out);
+void Vector5Add( const idVec5_t &va, const idVec5_t &vb, idVec5_t &out);
+void VectorRotate3( vec3_c vIn, vec3_c vRotation, vec3_p out);
+void VectorRotate3Origin(vec3_c vIn, vec3_c vRotation, vec3_c vOrigin, vec3_p out);
+
+
+int Q_log2(int val);
+
+int Q_rand( int *seed );
+float Q_random( int *seed );
+float Q_crandom( int *seed );
+
+#define random() ((rand () & 0x7fff) / ((float)0x7fff))
+#define crandom() (2.0 * (random() - 0.5))
+
+float Q_rint( float in );
+
+void vectoangles( vec3_c value1, angles_p angles);
+void AnglesToAxis( angles_c angles, mat3_p axis );
+
+void AxisCopy( mat3_c in, mat3_p out );
+qboolean AxisRotated( mat3_c in ); // assumes a non-degenerate axis
+
+int SignbitsForNormal( vec3_c normal );
+int BoxOnPlaneSide( const Bounds &b, struct cplane_s *p );
+
+float AngleMod(float a);
+float LerpAngle (float from, float to, float frac);
+float AngleSubtract( float a1, float a2 );
+void AnglesSubtract( angles_c v1, angles_c v2, angles_p v3 );
+
+float AngleNormalize360 ( float angle );
+float AngleNormalize180 ( float angle );
+float AngleDelta ( float angle1, float angle2 );
+
+qboolean PlaneFromPoints( vec4_t &plane, vec3_c a, vec3_c b, vec3_c c );
+void ProjectPointOnPlane( vec3_p dst, vec3_c p, vec3_c normal );
+void RotatePointAroundVector( vec3_p dst, vec3_c dir, vec3_c point, float degrees );
+void RotateAroundDirection( mat3_p axis, float yaw );
+void MakeNormalVectors( vec3_c forward, vec3_p right, vec3_p up );
+// perpendicular vector could be replaced by this
+
+int PlaneTypeForNormal( vec3_c normal );
+
+void MatrixMultiply( mat3_c in1, mat3_c in2, mat3_p out );
+void MatrixInverseMultiply( mat3_c in1, mat3_c in2, mat3_p out ); // in2 is transposed during multiply
+void MatrixTransformVector( vec3_c in, mat3_c matrix, vec3_p out );
+void MatrixProjectVector( vec3_c in, mat3_c matrix, vec3_p out ); // Places the vector into a new coordinate system.
+void AngleVectors( angles_c angles, vec3_p forward, vec3_p right, vec3_p up);
+void PerpendicularVector( vec3_p dst, vec3_c src );
+
+float TriangleArea( vec3_c a, vec3_c b, vec3_c c );
+#endif // __cplusplus
+
+//=============================================
+
+float Com_Clamp( float min, float max, float value );
+
+#define FILE_HASH_SIZE 1024
+int Com_HashString( const char *fname );
+
+char *Com_SkipPath( char *pathname );
+
+// it is ok for out == in
+void Com_StripExtension( const char *in, char *out );
+
+// "extension" should include the dot: ".map"
+void Com_DefaultExtension( char *path, int maxSize, const char *extension );
+
+int Com_ParseInfos( const char *buf, int max, char infos[][MAX_INFO_STRING] );
+
+/*
+=====================================================================================
+
+SCRIPT PARSING
+
+=====================================================================================
+*/
+
+// this just controls the comment printing, it doesn't actually load a file
+void Com_BeginParseSession( const char *filename );
+void Com_EndParseSession( void );
+
+int Com_GetCurrentParseLine( void );
+
+// Will never return NULL, just empty strings.
+// An empty string will only be returned at end of file.
+// ParseOnLine will return empty if there isn't another token on this line
+
+// this funny typedef just means a moving pointer into a const char * buffer
+const char *Com_Parse( const char *(*data_p) );
+const char *Com_ParseOnLine( const char *(*data_p) );
+const char *Com_ParseRestOfLine( const char *(*data_p) );
+
+void Com_UngetToken( void );
+
+#ifdef __cplusplus
+void Com_MatchToken( const char *(*buf_p), const char *match, qboolean warning = qfalse );
+#else
+void Com_MatchToken( const char *(*buf_p), const char *match, qboolean warning );
+#endif
+
+void Com_ScriptError( const char *msg, ... );
+void Com_ScriptWarning( const char *msg, ... );
+
+void Com_SkipBracedSection( const char *(*program) );
+void Com_SkipRestOfLine( const char *(*data) );
+
+float Com_ParseFloat( const char *(*buf_p) );
+int Com_ParseInt( const char *(*buf_p) );
+
+void Com_Parse1DMatrix( const char *(*buf_p), int x, float *m );
+void Com_Parse2DMatrix( const char *(*buf_p), int y, int x, float *m );
+void Com_Parse3DMatrix( const char *(*buf_p), int z, int y, int x, float *m );
+
+//=====================================================================================
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+void QDECL Com_sprintf (char *dest, int size, const char *fmt, ...);
+
+
+// mode parm for FS_FOpenFile
+typedef enum {
+ FS_READ,
+ FS_WRITE,
+ FS_APPEND,
+ FS_APPEND_SYNC
+} fsMode_t;
+
+typedef enum {
+ FS_SEEK_CUR,
+ FS_SEEK_END,
+ FS_SEEK_SET
+} fsOrigin_t;
+
+//=============================================
+
+int Q_isprint( int c );
+int Q_islower( int c );
+int Q_isupper( int c );
+int Q_isalpha( int c );
+
+// portable case insensitive compare
+int Q_stricmp (const char *s1, const char *s2);
+int Q_strncmp (const char *s1, const char *s2, int n);
+int Q_stricmpn (const char *s1, const char *s2, int n);
+char *Q_strlwr( char *s1 );
+char *Q_strupr( char *s1 );
+char *Q_strrchr( const char* string, int c );
+
+// buffer size safe library replacements
+void Q_strncpyz( char *dest, const char *src, int destsize );
+void Q_strcat( char *dest, int size, const char *src );
+
+// strlen that discounts Quake color sequences
+int Q_PrintStrlen( const char *string );
+// removes color sequences from string
+char *Q_CleanStr( char *string );
+
+int Com_Filter( const char *filter, const char *name, int casesensitive );
+const char *Com_StringContains( const char *str1, const char *str2, int casesensitive );
+
+
+//=============================================
+
+short BigShort(short l);
+short LittleShort(short l);
+int BigLong (int l);
+int LittleLong (int l);
+float BigFloat (float l);
+float LittleFloat (float l);
+
+void Swap_Init (void);
+char * QDECL va(char *format, ...);
+
+#ifdef __cplusplus
+ }
+#endif
+
+
+//=============================================
+#ifdef __cplusplus
+//
+// mapfile parsing
+//
+typedef struct ePair_s {
+ char *key;
+ char *value;
+} ePair_t;
+
+typedef struct mapSide_s {
+ char material[MAX_QPATH];
+ vec4_t plane;
+ vec4_t textureVectors[2];
+} mapSide_t;
+
+typedef struct {
+ int numSides;
+ mapSide_t **sides;
+} mapBrush_t;
+
+typedef struct {
+ idVec3_t xyz;
+ float st[2];
+} patchVertex_t;
+
+typedef struct {
+ char material[MAX_QPATH];
+ int width, height;
+ patchVertex_t *patchVerts;
+} mapPatch_t;
+
+typedef struct {
+ char modelName[MAX_QPATH];
+ float matrix[16];
+} mapModel_t;
+
+typedef struct mapPrimitive_s {
+ int numEpairs;
+ ePair_t **ePairs;
+
+ // only one of these will be non-NULL
+ mapBrush_t *brush;
+ mapPatch_t *patch;
+ mapModel_t *model;
+} mapPrimitive_t;
+
+typedef struct mapEntity_s {
+ int numPrimitives;
+ mapPrimitive_t **primitives;
+
+ int numEpairs;
+ ePair_t **ePairs;
+} mapEntity_t;
+
+typedef struct {
+ int numEntities;
+ mapEntity_t **entities;
+} mapFile_t;
+
+
+// the order of entities, brushes, and sides will be maintained, the
+// lists won't be swapped on each load or save
+mapFile_t *ParseMapFile( const char *text );
+void FreeMapFile( mapFile_t *mapFile );
+void WriteMapFile( const mapFile_t *mapFile, FILE *f );
+
+// key names are case-insensitive
+const char *ValueForMapEntityKey( const mapEntity_t *ent, const char *key );
+float FloatForMapEntityKey( const mapEntity_t *ent, const char *key );
+qboolean GetVectorForMapEntityKey( const mapEntity_t *ent, const char *key, idVec3_t &vec );
+
+typedef struct {
+ idVec3_t xyz;
+ idVec2_t st;
+ idVec3_t normal;
+ idVec3_t tangents[2];
+ byte smoothing[4]; // colors for silhouette smoothing
+} drawVert_t;
+
+typedef struct {
+ int width, height;
+ drawVert_t *verts;
+} drawVertMesh_t;
+
+// Tesselate a map patch into smoothed, drawable vertexes
+// MaxError of around 4 is reasonable
+drawVertMesh_t *SubdivideMapPatch( const mapPatch_t *patch, float maxError );
+#endif // __cplusplus
+
+//=========================================
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+void QDECL Com_Error( int level, const char *error, ... );
+void QDECL Com_Printf( const char *msg, ... );
+void QDECL Com_DPrintf( const char *msg, ... );
+
+#ifdef __cplusplus
+ }
+#endif
+
+
+typedef struct {
+ qboolean frameMemory;
+ int currentElements;
+ int maxElements; // will reallocate and move when exceeded
+ void **elements;
+} growList_t;
+
+// you don't need to init the growlist if you don't mind it growing and moving
+// the list as it expands
+void Com_InitGrowList( growList_t *list, int maxElements );
+int Com_AddToGrowList( growList_t *list, void *data );
+void *Com_GrowListElement( const growList_t *list, int index );
+int Com_IndexForGrowListElement( const growList_t *list, const void *element );
+
+
+//
+// key / value info strings
+//
+char *Info_ValueForKey( const char *s, const char *key );
+void Info_RemoveKey( char *s, const char *key );
+void Info_SetValueForKey( char *s, const char *key, const char *value );
+qboolean Info_Validate( const char *s );
+void Info_NextPair( const char *(*s), char key[MAX_INFO_KEY], char value[MAX_INFO_VALUE] );
+
+// get cvar defs, collision defs, etc
+//#include "../shared/interface.h"
+
+// get key code numbers for events
+//#include "../shared/keycodes.h"
+
+#ifdef __cplusplus
+// get the polygon winding functions
+//#include "../shared/windings.h"
+
+// get the flags class
+//#include "../shared/idflags.h"
+#endif // __cplusplus
+
+#endif // __Q_SHARED_H
+
diff --git a/q3radiant/splines/splines.cpp b/q3radiant/splines/splines.cpp
new file mode 100755
index 0000000..9c2b804
--- /dev/null
+++ b/q3radiant/splines/splines.cpp
@@ -0,0 +1,1244 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+//#include "stdafx.h"
+//#include "qe3.h"
+
+#include "q_shared.h"
+#include "splines.h"
+
+extern "C" {
+int FS_Write( const void *buffer, int len, fileHandle_t h );
+int FS_ReadFile( const char *qpath, void **buffer );
+void FS_FreeFile( void *buffer );
+fileHandle_t FS_FOpenFileWrite( const char *filename );
+void FS_FCloseFile( fileHandle_t f );
+}
+
+float Q_fabs( float f ) {
+ int tmp = * ( int * ) &f;
+ tmp &= 0x7FFFFFFF;
+ return * ( float * ) &tmp;
+}
+
+
+//#include "../shared/windings.h"
+//#include "../qcommon/qcommon.h"
+//#include "../sys/sys_public.h"
+//#include "../game/game_entity.h"
+
+idCameraDef splineList;
+idCameraDef *g_splineList = &splineList;
+
+idVec3_t idSplineList::zero(0,0,0);
+
+void glLabeledPoint(idVec3_t &color, idVec3_t &point, float size, const char *label) {
+ qglColor3fv(color);
+ qglPointSize(size);
+ qglBegin(GL_POINTS);
+ qglVertex3fv(point);
+ qglEnd();
+ idVec3_t v = point;
+ v.x += 1;
+ v.y += 1;
+ v.z += 1;
+ qglRasterPos3fv (v);
+ qglCallLists (strlen(label), GL_UNSIGNED_BYTE, label);
+}
+
+
+void glBox(idVec3_t &color, idVec3_t &point, float size) {
+ idVec3_t mins(point);
+ idVec3_t maxs(point);
+ mins[0] -= size;
+ mins[1] += size;
+ mins[2] -= size;
+ maxs[0] += size;
+ maxs[1] -= size;
+ maxs[2] += size;
+ qglColor3fv(color);
+ qglBegin(GL_LINE_LOOP);
+ qglVertex3f(mins[0],mins[1],mins[2]);
+ qglVertex3f(maxs[0],mins[1],mins[2]);
+ qglVertex3f(maxs[0],maxs[1],mins[2]);
+ qglVertex3f(mins[0],maxs[1],mins[2]);
+ qglEnd();
+ qglBegin(GL_LINE_LOOP);
+ qglVertex3f(mins[0],mins[1],maxs[2]);
+ qglVertex3f(maxs[0],mins[1],maxs[2]);
+ qglVertex3f(maxs[0],maxs[1],maxs[2]);
+ qglVertex3f(mins[0],maxs[1],maxs[2]);
+ qglEnd();
+
+ qglBegin(GL_LINES);
+ qglVertex3f(mins[0],mins[1],mins[2]);
+ qglVertex3f(mins[0],mins[1],maxs[2]);
+ qglVertex3f(mins[0],maxs[1],maxs[2]);
+ qglVertex3f(mins[0],maxs[1],mins[2]);
+ qglVertex3f(maxs[0],mins[1],mins[2]);
+ qglVertex3f(maxs[0],mins[1],maxs[2]);
+ qglVertex3f(maxs[0],maxs[1],maxs[2]);
+ qglVertex3f(maxs[0],maxs[1],mins[2]);
+ qglEnd();
+
+}
+
+void splineTest() {
+ //g_splineList->load("p:/doom/base/maps/test_base1.camera");
+}
+
+void splineDraw() {
+ //g_splineList->addToRenderer();
+}
+
+
+//extern void D_DebugLine( const idVec3_t &color, const idVec3_t &start, const idVec3_t &end );
+
+void debugLine(idVec3_t &color, float x, float y, float z, float x2, float y2, float z2) {
+ idVec3_t from(x, y, z);
+ idVec3_t to(x2, y2, z2);
+ //D_DebugLine(color, from, to);
+}
+
+void idSplineList::addToRenderer() {
+
+ if (controlPoints.Num() == 0) {
+ return;
+ }
+
+ idVec3_t mins, maxs;
+ idVec3_t yellow(1.0, 1.0, 0);
+ idVec3_t white(1.0, 1.0, 1.0);
+ int i;
+
+ for(i = 0; i < controlPoints.Num(); i++) {
+ VectorCopy(*controlPoints[i], mins);
+ VectorCopy(mins, maxs);
+ mins[0] -= 8;
+ mins[1] += 8;
+ mins[2] -= 8;
+ maxs[0] += 8;
+ maxs[1] -= 8;
+ maxs[2] += 8;
+ debugLine( yellow, mins[0], mins[1], mins[2], maxs[0], mins[1], mins[2]);
+ debugLine( yellow, maxs[0], mins[1], mins[2], maxs[0], maxs[1], mins[2]);
+ debugLine( yellow, maxs[0], maxs[1], mins[2], mins[0], maxs[1], mins[2]);
+ debugLine( yellow, mins[0], maxs[1], mins[2], mins[0], mins[1], mins[2]);
+
+ debugLine( yellow, mins[0], mins[1], maxs[2], maxs[0], mins[1], maxs[2]);
+ debugLine( yellow, maxs[0], mins[1], maxs[2], maxs[0], maxs[1], maxs[2]);
+ debugLine( yellow, maxs[0], maxs[1], maxs[2], mins[0], maxs[1], maxs[2]);
+ debugLine( yellow, mins[0], maxs[1], maxs[2], mins[0], mins[1], maxs[2]);
+
+ }
+
+ int step = 0;
+ idVec3_t step1;
+ for(i = 3; i < controlPoints.Num(); i++) {
+ for (float tension = 0.0f; tension < 1.001f; tension += 0.1f) {
+ float x = 0;
+ float y = 0;
+ float z = 0;
+ for (int j = 0; j < 4; j++) {
+ x += controlPoints[i - (3 - j)]->x * calcSpline(j, tension);
+ y += controlPoints[i - (3 - j)]->y * calcSpline(j, tension);
+ z += controlPoints[i - (3 - j)]->z * calcSpline(j, tension);
+ }
+ if (step == 0) {
+ step1[0] = x;
+ step1[1] = y;
+ step1[2] = z;
+ step = 1;
+ } else {
+ debugLine( white, step1[0], step1[1], step1[2], x, y, z);
+ step = 0;
+ }
+
+ }
+ }
+}
+
+void idSplineList::buildSpline() {
+ //int start = Sys_Milliseconds();
+ clearSpline();
+ for(int i = 3; i < controlPoints.Num(); i++) {
+ for (float tension = 0.0f; tension < 1.001f; tension += granularity) {
+ float x = 0;
+ float y = 0;
+ float z = 0;
+ for (int j = 0; j < 4; j++) {
+ x += controlPoints[i - (3 - j)]->x * calcSpline(j, tension);
+ y += controlPoints[i - (3 - j)]->y * calcSpline(j, tension);
+ z += controlPoints[i - (3 - j)]->z * calcSpline(j, tension);
+ }
+ splinePoints.Append(new idVec3_t(x, y, z));
+ }
+ }
+ dirty = false;
+ //Com_Printf("Spline build took %f seconds\n", (float)(Sys_Milliseconds() - start) / 1000);
+}
+
+
+void idSplineList::draw(bool editMode) {
+ int i;
+ vec4_t yellow(1, 1, 0, 1);
+
+ if (controlPoints.Num() == 0) {
+ return;
+ }
+
+ if (dirty) {
+ buildSpline();
+ }
+
+
+ qglColor3fv(controlColor);
+ qglPointSize(5);
+
+ qglBegin(GL_POINTS);
+ for (i = 0; i < controlPoints.Num(); i++) {
+ qglVertex3fv(*controlPoints[i]);
+ }
+ qglEnd();
+
+ if (editMode) {
+ for(i = 0; i < controlPoints.Num(); i++) {
+ glBox(activeColor, *controlPoints[i], 4);
+ }
+ }
+
+ //Draw the curve
+ qglColor3fv(pathColor);
+ qglBegin(GL_LINE_STRIP);
+ int count = splinePoints.Num();
+ for (i = 0; i < count; i++) {
+ qglVertex3fv(*splinePoints[i]);
+ }
+ qglEnd();
+
+ if (editMode) {
+ qglColor3fv(segmentColor);
+ qglPointSize(3);
+ qglBegin(GL_POINTS);
+ for (i = 0; i < count; i++) {
+ qglVertex3fv(*splinePoints[i]);
+ }
+ qglEnd();
+ }
+ if (count > 0) {
+ //assert(activeSegment >=0 && activeSegment < count);
+ if (activeSegment >=0 && activeSegment < count) {
+ glBox(activeColor, *splinePoints[activeSegment], 6);
+ glBox(yellow, *splinePoints[activeSegment], 8);
+ }
+ }
+
+}
+
+float idSplineList::totalDistance() {
+
+ if (controlPoints.Num() == 0) {
+ return 0.0;
+ }
+
+ if (dirty) {
+ buildSpline();
+ }
+
+ float dist = 0.0;
+ idVec3_t temp;
+ int count = splinePoints.Num();
+ for(int i = 1; i < count; i++) {
+ temp = *splinePoints[i-1];
+ temp -= *splinePoints[i];
+ dist += temp.Length();
+ }
+ return dist;
+}
+
+void idSplineList::initPosition(long bt, long totalTime) {
+
+ if (dirty) {
+ buildSpline();
+ }
+
+ if (splinePoints.Num() == 0) {
+ return;
+ }
+
+ baseTime = bt;
+ time = totalTime;
+
+ // calc distance to travel ( this will soon be broken into time segments )
+ splineTime.Clear();
+ splineTime.Append(0);
+ float dist = totalDistance();
+ float distSoFar = 0.0;
+ idVec3_t temp;
+ int count = splinePoints.Num();
+ //for(int i = 2; i < count - 1; i++) {
+ for(int i = 1; i < count; i++) {
+ temp = *splinePoints[i-1];
+ temp -= *splinePoints[i];
+ distSoFar += temp.Length();
+ float percent = distSoFar / dist;
+ percent *= totalTime;
+ splineTime.Append(percent + bt);
+ }
+ assert(splineTime.Num() == splinePoints.Num());
+ activeSegment = 0;
+}
+
+
+
+float idSplineList::calcSpline(int step, float tension) {
+ switch(step) {
+ case 0: return (pow(1 - tension, 3)) / 6;
+ case 1: return (3 * pow(tension, 3) - 6 * pow(tension, 2) + 4) / 6;
+ case 2: return (-3 * pow(tension, 3) + 3 * pow(tension, 2) + 3 * tension + 1) / 6;
+ case 3: return pow(tension, 3) / 6;
+ }
+ return 0.0;
+}
+
+
+
+void idSplineList::updateSelection(const idVec3_t &move) {
+ if (selected) {
+ dirty = true;
+ VectorAdd(*selected, move, *selected);
+ }
+}
+
+
+void idSplineList::setSelectedPoint(idVec3_t *p) {
+ if (p) {
+ p->Snap();
+ for(int i = 0; i < controlPoints.Num(); i++) {
+ if (*p == *controlPoints[i]) {
+ selected = controlPoints[i];
+ }
+ }
+ } else {
+ selected = NULL;
+ }
+}
+
+const idVec3_t *idSplineList::getPosition(long t) {
+ static idVec3_t interpolatedPos;
+
+ int count = splineTime.Num();
+ if (count == 0) {
+ return &zero;
+ }
+
+ assert(splineTime.Num() == splinePoints.Num());
+
+ while (activeSegment < count) {
+ if (splineTime[activeSegment] >= t) {
+ if (activeSegment > 0 && activeSegment < count - 1) {
+ float timeHi = splineTime[activeSegment + 1];
+ float timeLo = splineTime[activeSegment - 1];
+ //float percent = (float)(baseTime + time - t) / time;
+ float percent = (timeHi - t) / (timeHi - timeLo);
+ // pick two bounding points
+ idVec3_t v1 = *splinePoints[activeSegment-1];
+ idVec3_t v2 = *splinePoints[activeSegment+1];
+ v2 *= (1.0 - percent);
+ v1 *= percent;
+ v2 += v1;
+ interpolatedPos = v2;
+ return &interpolatedPos;
+ }
+ return splinePoints[activeSegment];
+ } else {
+ activeSegment++;
+ }
+ }
+ return splinePoints[count-1];
+}
+
+void idSplineList::parse(const char *(*text) ) {
+ const char *token;
+ //Com_MatchToken( text, "{" );
+ do {
+ token = Com_Parse( text );
+
+ if ( !token[0] ) {
+ break;
+ }
+ if ( !Q_stricmp (token, "}") ) {
+ break;
+ }
+
+ do {
+ // if token is not a brace, it is a key for a key/value pair
+ if ( !token[0] || !Q_stricmp (token, "(") || !Q_stricmp(token, "}")) {
+ break;
+ }
+
+ Com_UngetToken();
+ idStr key = Com_ParseOnLine(text);
+ const char *token = Com_Parse(text);
+ if (Q_stricmp(key.c_str(), "granularity") == 0) {
+ granularity = atof(token);
+ } else if (Q_stricmp(key.c_str(), "name") == 0) {
+ name = token;
+ }
+ token = Com_Parse(text);
+
+ } while (1);
+
+ if ( !Q_stricmp (token, "}") ) {
+ break;
+ }
+
+ Com_UngetToken();
+ // read the control point
+ idVec3_t point;
+ Com_Parse1DMatrix( text, 3, point );
+ addPoint(point.x, point.y, point.z);
+ } while (1);
+
+ //Com_UngetToken();
+ //Com_MatchToken( text, "}" );
+ dirty = true;
+}
+
+void idSplineList::write(fileHandle_t file, const char *p) {
+ idStr s = va("\t\t%s {\n", p);
+ FS_Write(s.c_str(), s.length(), file);
+ //s = va("\t\tname %s\n", name.c_str());
+ //FS_Write(s.c_str(), s.length(), file);
+ s = va("\t\t\tgranularity %f\n", granularity);
+ FS_Write(s.c_str(), s.length(), file);
+ int count = controlPoints.Num();
+ for (int i = 0; i < count; i++) {
+ s = va("\t\t\t( %f %f %f )\n", controlPoints[i]->x, controlPoints[i]->y, controlPoints[i]->z);
+ FS_Write(s.c_str(), s.length(), file);
+ }
+ s = "\t\t}\n";
+ FS_Write(s.c_str(), s.length(), file);
+}
+
+
+void idCameraDef::getActiveSegmentInfo(int segment, idVec3_t &origin, idVec3_t &direction, float *fov) {
+#if 0
+ if (!cameraSpline.validTime()) {
+ buildCamera();
+ }
+ double d = (double)segment / numSegments();
+ getCameraInfo(d * totalTime * 1000, origin, direction, fov);
+#endif
+/*
+ if (!cameraSpline.validTime()) {
+ buildCamera();
+ }
+ origin = *cameraSpline.getSegmentPoint(segment);
+
+
+ idVec3_t temp;
+
+ int numTargets = getTargetSpline()->controlPoints.Num();
+ int count = cameraSpline.splineTime.Num();
+ if (numTargets == 0) {
+ // follow the path
+ if (cameraSpline.getActiveSegment() < count - 1) {
+ temp = *cameraSpline.splinePoints[cameraSpline.getActiveSegment()+1];
+ }
+ } else if (numTargets == 1) {
+ temp = *getTargetSpline()->controlPoints[0];
+ } else {
+ temp = *getTargetSpline()->getSegmentPoint(segment);
+ }
+
+ temp -= origin;
+ temp.Normalize();
+ direction = temp;
+*/
+}
+
+bool idCameraDef::getCameraInfo(long time, idVec3_t &origin, idVec3_t &direction, float *fv) {
+
+
+ if ((time - startTime) / 1000 > totalTime) {
+ return false;
+ }
+
+
+ for (int i = 0; i < events.Num(); i++) {
+ if (time >= startTime + events[i]->getTime() && !events[i]->getTriggered()) {
+ events[i]->setTriggered(true);
+ if (events[i]->getType() == idCameraEvent::EVENT_TARGET) {
+ setActiveTargetByName(events[i]->getParam());
+ getActiveTarget()->start(startTime + events[i]->getTime());
+ //Com_Printf("Triggered event switch to target: %s\n",events[i]->getParam());
+ } else if (events[i]->getType() == idCameraEvent::EVENT_TRIGGER) {
+ //idEntity *ent = NULL;
+ //ent = level.FindTarget( ent, events[i]->getParam());
+ //if (ent) {
+ // ent->signal( SIG_TRIGGER );
+ // ent->ProcessEvent( &EV_Activate, world );
+ //}
+ } else if (events[i]->getType() == idCameraEvent::EVENT_FOV) {
+ //*fv = fov = atof(events[i]->getParam());
+ } else if (events[i]->getType() == idCameraEvent::EVENT_STOP) {
+ return false;
+ }
+ }
+ }
+
+ origin = *cameraPosition->getPosition(time);
+
+ *fv = fov.getFOV(time);
+
+ idVec3_t temp = origin;
+
+ int numTargets = targetPositions.Num();
+ if (numTargets == 0) {
+/*
+ // follow the path
+ if (cameraSpline.getActiveSegment() < count - 1) {
+ temp = *cameraSpline.splinePoints[cameraSpline.getActiveSegment()+1];
+ if (temp == origin) {
+ int index = cameraSpline.getActiveSegment() + 2;
+ while (temp == origin && index < count - 1) {
+ temp = *cameraSpline.splinePoints[index++];
+ }
+ }
+ }
+*/
+ } else {
+ temp = *getActiveTarget()->getPosition(time);
+ }
+
+ temp -= origin;
+ temp.Normalize();
+ direction = temp;
+
+ return true;
+}
+
+bool idCameraDef::waitEvent(int index) {
+ //for (int i = 0; i < events.Num(); i++) {
+ // if (events[i]->getSegment() == index && events[i]->getType() == idCameraEvent::EVENT_WAIT) {
+ // return true;
+ // }
+ //}
+ return false;
+}
+
+
+#define NUM_CCELERATION_SEGS 10
+#define CELL_AMT 5
+
+void idCameraDef::buildCamera() {
+ int i;
+ int lastSwitch = 0;
+ idList<float> waits;
+ idList<int> targets;
+
+ totalTime = baseTime;
+ cameraPosition->setTime(totalTime * 1000);
+ // we have a base time layout for the path and the target path
+ // now we need to layer on any wait or speed changes
+ for (i = 0; i < events.Num(); i++) {
+ idCameraEvent *ev = events[i];
+ events[i]->setTriggered(false);
+ switch (events[i]->getType()) {
+ case idCameraEvent::EVENT_TARGET : {
+ targets.Append(i);
+ break;
+ }
+ case idCameraEvent::EVENT_WAIT : {
+ waits.Append(atof(events[i]->getParam()));
+ cameraPosition->addVelocity(events[i]->getTime(), atof(events[i]->getParam()) * 1000, 0);
+ break;
+ }
+ case idCameraEvent::EVENT_TARGETWAIT : {
+ //targetWaits.Append(i);
+ break;
+ }
+ case idCameraEvent::EVENT_SPEED : {
+/*
+ // take the average delay between up to the next five segments
+ float adjust = atof(events[i]->getParam());
+ int index = events[i]->getSegment();
+ total = 0;
+ count = 0;
+
+ // get total amount of time over the remainder of the segment
+ for (j = index; j < cameraSpline.numSegments() - 1; j++) {
+ total += cameraSpline.getSegmentTime(j + 1) - cameraSpline.getSegmentTime(j);
+ count++;
+ }
+
+ // multiply that by the adjustment
+ double newTotal = total * adjust;
+ // what is the difference..
+ newTotal -= total;
+ totalTime += newTotal / 1000;
+
+ // per segment difference
+ newTotal /= count;
+ int additive = newTotal;
+
+ // now propogate that difference out to each segment
+ for (j = index; j < cameraSpline.numSegments(); j++) {
+ cameraSpline.addSegmentTime(j, additive);
+ additive += newTotal;
+ }
+ break;
+*/
+ }
+ }
+ }
+
+
+ for (i = 0; i < waits.Num(); i++) {
+ totalTime += waits[i];
+ }
+
+ // on a new target switch, we need to take time to this point ( since last target switch )
+ // and allocate it across the active target, then reset time to this point
+ long timeSoFar = 0;
+ long total = totalTime * 1000;
+ for (i = 0; i < targets.Num(); i++) {
+ long t;
+ if (i < targets.Num() - 1) {
+ t = events[targets[i+1]]->getTime();
+ } else {
+ t = total - timeSoFar;
+ }
+ // t is how much time to use for this target
+ setActiveTargetByName(events[targets[i]]->getParam());
+ getActiveTarget()->setTime(t);
+ timeSoFar += t;
+ }
+
+
+}
+
+void idCameraDef::startCamera(long t) {
+ buildCamera();
+ cameraPosition->start(t);
+ //for (int i = 0; i < targetPositions.Num(); i++) {
+ // targetPositions[i]->
+ //}
+ startTime = t;
+ cameraRunning = true;
+}
+
+
+void idCameraDef::parse(const char *(*text) ) {
+
+ const char *token;
+ do {
+ token = Com_Parse( text );
+
+ if ( !token[0] ) {
+ break;
+ }
+ if ( !Q_stricmp (token, "}") ) {
+ break;
+ }
+
+ if (Q_stricmp(token, "time") == 0) {
+ baseTime = Com_ParseFloat(text);
+ }
+
+ if (Q_stricmp(token, "camera_fixed") == 0) {
+ cameraPosition = new idFixedPosition();
+ cameraPosition->parse(text);
+ }
+
+ if (Q_stricmp(token, "camera_interpolated") == 0) {
+ cameraPosition = new idInterpolatedPosition();
+ cameraPosition->parse(text);
+ }
+
+ if (Q_stricmp(token, "camera_spline") == 0) {
+ cameraPosition = new idSplinePosition();
+ cameraPosition->parse(text);
+ }
+
+ if (Q_stricmp(token, "target_fixed") == 0) {
+ idFixedPosition *pos = new idFixedPosition();
+ pos->parse(text);
+ targetPositions.Append(pos);
+ }
+
+ if (Q_stricmp(token, "target_interpolated") == 0) {
+ idInterpolatedPosition *pos = new idInterpolatedPosition();
+ pos->parse(text);
+ targetPositions.Append(pos);
+ }
+
+ if (Q_stricmp(token, "target_spline") == 0) {
+ idSplinePosition *pos = new idSplinePosition();
+ pos->parse(text);
+ targetPositions.Append(pos);
+ }
+
+ if (Q_stricmp(token, "fov") == 0) {
+ fov.parse(text);
+ }
+
+ if (Q_stricmp(token, "event") == 0) {
+ idCameraEvent *event = new idCameraEvent();
+ event->parse(text);
+ addEvent(event);
+ }
+
+
+ } while (1);
+
+ Com_UngetToken();
+ Com_MatchToken( text, "}" );
+
+}
+
+bool idCameraDef::load(const char *filename) {
+ char *buf;
+ const char *buf_p;
+ int length = FS_ReadFile( filename, (void **)&buf );
+ if ( !buf ) {
+ return false;
+ }
+
+ clear();
+ Com_BeginParseSession( filename );
+ buf_p = buf;
+ parse(&buf_p);
+ Com_EndParseSession();
+ FS_FreeFile( buf );
+
+ return true;
+}
+
+void idCameraDef::save(const char *filename) {
+ fileHandle_t file = FS_FOpenFileWrite(filename);
+ if (file) {
+ int i;
+ idStr s = "cameraPathDef { \n";
+ FS_Write(s.c_str(), s.length(), file);
+ s = va("\ttime %f\n", baseTime);
+ FS_Write(s.c_str(), s.length(), file);
+
+ cameraPosition->write(file, va("camera_%s",cameraPosition->typeStr()));
+
+ for (i = 0; i < numTargets(); i++) {
+ targetPositions[i]->write(file, va("target_%s", targetPositions[i]->typeStr()));
+ }
+
+ for (i = 0; i < events.Num(); i++) {
+ events[i]->write(file, "event");
+ }
+
+ fov.write(file, "fov");
+
+ s = "}\n";
+ FS_Write(s.c_str(), s.length(), file);
+ }
+ FS_FCloseFile(file);
+}
+
+int idCameraDef::sortEvents(const void *p1, const void *p2) {
+ idCameraEvent *ev1 = (idCameraEvent*)(p1);
+ idCameraEvent *ev2 = (idCameraEvent*)(p2);
+
+ if (ev1->getTime() > ev2->getTime()) {
+ return -1;
+ }
+ if (ev1->getTime() < ev2->getTime()) {
+ return 1;
+ }
+ return 0;
+}
+
+void idCameraDef::addEvent(idCameraEvent *event) {
+ events.Append(event);
+ //events.Sort(&sortEvents);
+
+}
+void idCameraDef::addEvent(idCameraEvent::eventType t, const char *param, long time) {
+ addEvent(new idCameraEvent(t, param, time));
+ buildCamera();
+}
+
+
+const char *idCameraEvent::eventStr[] = {
+ "NA",
+ "WAIT",
+ "TARGETWAIT",
+ "SPEED",
+ "TARGET",
+ "SNAPTARGET",
+ "FOV",
+ "SCRIPT",
+ "TRIGGER",
+ "STOP"
+};
+
+void idCameraEvent::parse(const char *(*text) ) {
+ const char *token;
+ Com_MatchToken( text, "{" );
+ do {
+ token = Com_Parse( text );
+
+ if ( !token[0] ) {
+ break;
+ }
+ if ( !strcmp (token, "}") ) {
+ break;
+ }
+
+ // here we may have to jump over brush epairs ( only used in editor )
+ do {
+ // if token is not a brace, it is a key for a key/value pair
+ if ( !token[0] || !strcmp (token, "(") || !strcmp(token, "}")) {
+ break;
+ }
+
+ Com_UngetToken();
+ idStr key = Com_ParseOnLine(text);
+ const char *token = Com_Parse(text);
+ if (Q_stricmp(key.c_str(), "type") == 0) {
+ type = static_cast<idCameraEvent::eventType>(atoi(token));
+ } else if (Q_stricmp(key.c_str(), "param") == 0) {
+ paramStr = token;
+ } else if (Q_stricmp(key.c_str(), "time") == 0) {
+ time = atoi(token);
+ }
+ token = Com_Parse(text);
+
+ } while (1);
+
+ if ( !strcmp (token, "}") ) {
+ break;
+ }
+
+ } while (1);
+
+ Com_UngetToken();
+ Com_MatchToken( text, "}" );
+}
+
+void idCameraEvent::write(fileHandle_t file, const char *name) {
+ idStr s = va("\t%s {\n", name);
+ FS_Write(s.c_str(), s.length(), file);
+ s = va("\t\ttype %d\n", static_cast<int>(type));
+ FS_Write(s.c_str(), s.length(), file);
+ s = va("\t\tparam %s\n", paramStr.c_str());
+ FS_Write(s.c_str(), s.length(), file);
+ s = va("\t\ttime %d\n", time);
+ FS_Write(s.c_str(), s.length(), file);
+ s = "\t}\n";
+ FS_Write(s.c_str(), s.length(), file);
+}
+
+
+const char *idCameraPosition::positionStr[] = {
+ "Fixed",
+ "Interpolated",
+ "Spline",
+};
+
+
+
+const idVec3_t *idInterpolatedPosition::getPosition(long t) {
+ static idVec3_t interpolatedPos;
+
+ float velocity = getVelocity(t);
+ float timePassed = t - lastTime;
+ lastTime = t;
+
+ // convert to seconds
+ timePassed /= 1000;
+
+ float distToTravel = timePassed *= velocity;
+
+ idVec3_t temp = startPos;
+ temp -= endPos;
+ float distance = temp.Length();
+
+ distSoFar += distToTravel;
+ float percent = (float)(distSoFar) / distance;
+
+ if (percent > 1.0) {
+ percent = 1.0;
+ } else if (percent < 0.0) {
+ percent = 0.0;
+ }
+
+ // the following line does a straigt calc on percentage of time
+ // float percent = (float)(startTime + time - t) / time;
+
+ idVec3_t v1 = startPos;
+ idVec3_t v2 = endPos;
+ v1 *= (1.0 - percent);
+ v2 *= percent;
+ v1 += v2;
+ interpolatedPos = v1;
+ return &interpolatedPos;
+}
+
+
+void idCameraFOV::parse(const char *(*text) ) {
+ const char *token;
+ Com_MatchToken( text, "{" );
+ do {
+ token = Com_Parse( text );
+
+ if ( !token[0] ) {
+ break;
+ }
+ if ( !strcmp (token, "}") ) {
+ break;
+ }
+
+ // here we may have to jump over brush epairs ( only used in editor )
+ do {
+ // if token is not a brace, it is a key for a key/value pair
+ if ( !token[0] || !strcmp (token, "(") || !strcmp(token, "}")) {
+ break;
+ }
+
+ Com_UngetToken();
+ idStr key = Com_ParseOnLine(text);
+ const char *token = Com_Parse(text);
+ if (Q_stricmp(key.c_str(), "fov") == 0) {
+ fov = atof(token);
+ } else if (Q_stricmp(key.c_str(), "startFOV") == 0) {
+ startFOV = atof(token);
+ } else if (Q_stricmp(key.c_str(), "endFOV") == 0) {
+ endFOV = atof(token);
+ } else if (Q_stricmp(key.c_str(), "time") == 0) {
+ time = atoi(token);
+ }
+ token = Com_Parse(text);
+
+ } while (1);
+
+ if ( !strcmp (token, "}") ) {
+ break;
+ }
+
+ } while (1);
+
+ Com_UngetToken();
+ Com_MatchToken( text, "}" );
+}
+
+bool idCameraPosition::parseToken(const char *key, const char *(*text)) {
+ const char *token = Com_Parse(text);
+ if (Q_stricmp(key, "time") == 0) {
+ time = atol(token);
+ return true;
+ } else if (Q_stricmp(key, "type") == 0) {
+ type = static_cast<idCameraPosition::positionType>(atoi(token));
+ return true;
+ } else if (Q_stricmp(key, "velocity") == 0) {
+ long t = atol(token);
+ token = Com_Parse(text);
+ long d = atol(token);
+ token = Com_Parse(text);
+ float s = atof(token);
+ addVelocity(t, d, s);
+ return true;
+ } else if (Q_stricmp(key, "baseVelocity") == 0) {
+ baseVelocity = atof(token);
+ return true;
+ } else if (Q_stricmp(key, "name") == 0) {
+ name = token;
+ return true;
+ } else if (Q_stricmp(key, "time") == 0) {
+ time = atoi(token);
+ return true;
+ }
+ Com_UngetToken();
+ return false;
+}
+
+
+
+void idFixedPosition::parse(const char *(*text) ) {
+ const char *token;
+ Com_MatchToken( text, "{" );
+ do {
+ token = Com_Parse( text );
+
+ if ( !token[0] ) {
+ break;
+ }
+ if ( !strcmp (token, "}") ) {
+ break;
+ }
+
+ // here we may have to jump over brush epairs ( only used in editor )
+ do {
+ // if token is not a brace, it is a key for a key/value pair
+ if ( !token[0] || !strcmp (token, "(") || !strcmp(token, "}")) {
+ break;
+ }
+
+ Com_UngetToken();
+ idStr key = Com_ParseOnLine(text);
+
+ const char *token = Com_Parse(text);
+ if (Q_stricmp(key.c_str(), "pos") == 0) {
+ Com_UngetToken();
+ Com_Parse1DMatrix( text, 3, pos );
+ } else {
+ Com_UngetToken();
+ idCameraPosition::parseToken(key.c_str(), text);
+ }
+ token = Com_Parse(text);
+
+ } while (1);
+
+ if ( !strcmp (token, "}") ) {
+ break;
+ }
+
+ } while (1);
+
+ Com_UngetToken();
+ Com_MatchToken( text, "}" );
+}
+
+void idInterpolatedPosition::parse(const char *(*text) ) {
+ const char *token;
+ Com_MatchToken( text, "{" );
+ do {
+ token = Com_Parse( text );
+
+ if ( !token[0] ) {
+ break;
+ }
+ if ( !strcmp (token, "}") ) {
+ break;
+ }
+
+ // here we may have to jump over brush epairs ( only used in editor )
+ do {
+ // if token is not a brace, it is a key for a key/value pair
+ if ( !token[0] || !strcmp (token, "(") || !strcmp(token, "}")) {
+ break;
+ }
+
+ Com_UngetToken();
+ idStr key = Com_ParseOnLine(text);
+
+ const char *token = Com_Parse(text);
+ if (Q_stricmp(key.c_str(), "startPos") == 0) {
+ Com_UngetToken();
+ Com_Parse1DMatrix( text, 3, startPos );
+ } else if (Q_stricmp(key.c_str(), "endPos") == 0) {
+ Com_UngetToken();
+ Com_Parse1DMatrix( text, 3, endPos );
+ } else {
+ Com_UngetToken();
+ idCameraPosition::parseToken(key.c_str(), text);
+ }
+ token = Com_Parse(text);
+
+ } while (1);
+
+ if ( !strcmp (token, "}") ) {
+ break;
+ }
+
+ } while (1);
+
+ Com_UngetToken();
+ Com_MatchToken( text, "}" );
+}
+
+
+void idSplinePosition::parse(const char *(*text) ) {
+ const char *token;
+ Com_MatchToken( text, "{" );
+ do {
+ token = Com_Parse( text );
+
+ if ( !token[0] ) {
+ break;
+ }
+ if ( !strcmp (token, "}") ) {
+ break;
+ }
+
+ // here we may have to jump over brush epairs ( only used in editor )
+ do {
+ // if token is not a brace, it is a key for a key/value pair
+ if ( !token[0] || !strcmp (token, "(") || !strcmp(token, "}")) {
+ break;
+ }
+
+ Com_UngetToken();
+ idStr key = Com_ParseOnLine(text);
+
+ const char *token = Com_Parse(text);
+ if (Q_stricmp(key.c_str(), "target") == 0) {
+ target.parse(text);
+ } else {
+ Com_UngetToken();
+ idCameraPosition::parseToken(key.c_str(), text);
+ }
+ token = Com_Parse(text);
+
+ } while (1);
+
+ if ( !strcmp (token, "}") ) {
+ break;
+ }
+
+ } while (1);
+
+ Com_UngetToken();
+ Com_MatchToken( text, "}" );
+}
+
+
+
+void idCameraFOV::write(fileHandle_t file, const char *p) {
+ idStr s = va("\t%s {\n", p);
+ FS_Write(s.c_str(), s.length(), file);
+
+ s = va("\t\tfov %f\n", fov);
+ FS_Write(s.c_str(), s.length(), file);
+
+ s = va("\t\tstartFOV %f\n", startFOV);
+ FS_Write(s.c_str(), s.length(), file);
+
+ s = va("\t\tendFOV %f\n", endFOV);
+ FS_Write(s.c_str(), s.length(), file);
+
+ s = va("\t\ttime %i\n", time);
+ FS_Write(s.c_str(), s.length(), file);
+
+ s = "\t}\n";
+ FS_Write(s.c_str(), s.length(), file);
+}
+
+
+void idCameraPosition::write(fileHandle_t file, const char *p) {
+
+ idStr s = va("\t\ttime %i\n", time);
+ FS_Write(s.c_str(), s.length(), file);
+
+ s = va("\t\ttype %i\n", static_cast<int>(type));
+ FS_Write(s.c_str(), s.length(), file);
+
+ s = va("\t\tname %s\n", name.c_str());
+ FS_Write(s.c_str(), s.length(), file);
+
+ s = va("\t\tbaseVelocity %f\n", baseVelocity);
+ FS_Write(s.c_str(), s.length(), file);
+
+ for (int i = 0; i < velocities.Num(); i++) {
+ s = va("\t\tvelocity %i %i %f\n", velocities[i]->startTime, velocities[i]->time, velocities[i]->speed);
+ FS_Write(s.c_str(), s.length(), file);
+ }
+
+}
+
+void idFixedPosition::write(fileHandle_t file, const char *p) {
+ idStr s = va("\t%s {\n", p);
+ FS_Write(s.c_str(), s.length(), file);
+ idCameraPosition::write(file, p);
+ s = va("\t\tpos ( %f %f %f )\n", pos.x, pos.y, pos.z);
+ FS_Write(s.c_str(), s.length(), file);
+ s = "\t}\n";
+ FS_Write(s.c_str(), s.length(), file);
+}
+
+void idInterpolatedPosition::write(fileHandle_t file, const char *p) {
+ idStr s = va("\t%s {\n", p);
+ FS_Write(s.c_str(), s.length(), file);
+ idCameraPosition::write(file, p);
+ s = va("\t\tstartPos ( %f %f %f )\n", startPos.x, startPos.y, startPos.z);
+ FS_Write(s.c_str(), s.length(), file);
+ s = va("\t\tendPos ( %f %f %f )\n", endPos.x, endPos.y, endPos.z);
+ FS_Write(s.c_str(), s.length(), file);
+ s = "\t}\n";
+ FS_Write(s.c_str(), s.length(), file);
+}
+
+void idSplinePosition::write(fileHandle_t file, const char *p) {
+ idStr s = va("\t%s {\n", p);
+ FS_Write(s.c_str(), s.length(), file);
+ idCameraPosition::write(file, p);
+ target.write(file, "target");
+ s = "\t}\n";
+ FS_Write(s.c_str(), s.length(), file);
+}
+
+void idCameraDef::addTarget(const char *name, idCameraPosition::positionType type) {
+ const char *text = (name == NULL) ? va("target0%d", numTargets()+1) : name;
+ idCameraPosition *pos = newFromType(type);
+ if (pos) {
+ pos->setName(name);
+ targetPositions.Append(pos);
+ activeTarget = numTargets()-1;
+ if (activeTarget == 0) {
+ // first one
+ addEvent(idCameraEvent::EVENT_TARGET, name, 0);
+ }
+ }
+}
+
+
+
+idCameraDef camera;
+
+extern "C" {
+qboolean loadCamera(const char *name) {
+ camera.clear();
+ return static_cast<qboolean>(camera.load(name));
+}
+
+qboolean getCameraInfo(int time, float *origin, float*angles) {
+ idVec3_t dir, org;
+ org[0] = origin[0];
+ org[1] = origin[1];
+ org[2] = origin[2];
+ float fov = 90;
+ if (camera.getCameraInfo(time, org, dir, &fov)) {
+ origin[0] = org[0];
+ origin[1] = org[1];
+ origin[2] = org[2];
+ angles[1] = atan2 (dir[1], dir[0])*180/3.14159;
+ angles[0] = asin (dir[2])*180/3.14159;
+ return qtrue;
+ }
+ return qfalse;
+}
+
+void startCamera(int time) {
+ camera.startCamera(time);
+}
+
+}
+
+
diff --git a/q3radiant/splines/splines.h b/q3radiant/splines/splines.h
new file mode 100755
index 0000000..1cd0d58
--- /dev/null
+++ b/q3radiant/splines/splines.h
@@ -0,0 +1,1080 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __SPLINES_H
+#define __SPLINES_H
+
+extern "C" {
+#ifdef Q3RADIANT
+#include "../qgl.h"
+#else
+#include "../renderer/qgl.h"
+#endif
+}
+#include "util_list.h"
+#include "util_str.h"
+#include "math_vector.h"
+
+typedef int fileHandle_t;
+
+extern void glBox(idVec3_t &color, idVec3_t &point, float size);
+extern void glLabeledPoint(idVec3_t &color, idVec3_t &point, float size, const char *label);
+
+static vec4_t blue(0, 0, 1, 1);
+static vec4_t red(1, 0, 0, 1);
+
+class idPointListInterface {
+public:
+ idPointListInterface() {
+ selectedPoints.Clear();
+ };
+ ~idPointListInterface() {};
+
+ virtual int numPoints() {
+ return 0;
+ }
+
+ virtual void addPoint(const float x, const float y, const float z) {}
+ virtual void addPoint(const idVec3_t &v) {}
+ virtual void removePoint(int index) {}
+ virtual idVec3_t *getPoint(int index) { return NULL; }
+
+ int selectPointByRay(float ox, float oy, float oz, float dx, float dy, float dz, bool single) {
+ idVec3_t origin(ox, oy, oz);
+ idVec3_t dir(dx, dy, dz);
+ return selectPointByRay(origin, dir, single);
+ }
+
+ int selectPointByRay(const idVec3_t origin, const idVec3_t direction, bool single) {
+ int i, besti, count;
+ float d, bestd;
+ idVec3_t temp, temp2;
+
+ // find the point closest to the ray
+ besti = -1;
+ bestd = 8;
+ count = numPoints();
+
+ for (i=0; i < count; i++) {
+ temp = *getPoint(i);
+ temp2 = temp;
+ temp -= origin;
+ d = DotProduct(temp, direction);
+ __VectorMA (origin, d, direction, temp);
+ temp2 -= temp;
+ d = temp2.Length();
+ if (d <= bestd) {
+ bestd = d;
+ besti = i;
+ }
+ }
+
+ if (besti >= 0) {
+ selectPoint(besti, single);
+ }
+
+ return besti;
+ }
+
+ int isPointSelected(int index) {
+ int count = selectedPoints.Num();
+ for (int i = 0; i < count; i++) {
+ if (selectedPoints[i] == index) {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ int selectPoint(int index, bool single) {
+ if (index >= 0 && index < numPoints()) {
+ if (single) {
+ deselectAll();
+ } else {
+ if (isPointSelected(index) >= 0) {
+ selectedPoints.Remove(index);
+ }
+ }
+ return selectedPoints.Append(index);
+ }
+ return -1;
+ }
+
+ void selectAll() {
+ selectedPoints.Clear();
+ for (int i = 0; i < numPoints(); i++) {
+ selectedPoints.Append(i);
+ }
+ }
+
+ void deselectAll() {
+ selectedPoints.Clear();
+ }
+
+ int numSelectedPoints();
+
+ idVec3_t *getSelectedPoint(int index) {
+ assert(index >= 0 && index < numSelectedPoints());
+ return getPoint(selectedPoints[index]);
+ }
+
+ virtual void updateSelection(float x, float y, float z) {
+ idVec3_t move(x, y, z);
+ updateSelection(move);
+ }
+
+ virtual void updateSelection(const idVec3_t &move) {
+ int count = selectedPoints.Num();
+ for (int i = 0; i < count; i++) {
+ *getPoint(selectedPoints[i]) += move;
+ }
+ }
+
+ void drawSelection() {
+ int count = selectedPoints.Num();
+ for (int i = 0; i < count; i++) {
+ glBox(red, *getPoint(selectedPoints[i]), 4);
+ }
+ }
+
+protected:
+ idList<int> selectedPoints;
+
+};
+
+
+class idSplineList {
+
+public:
+
+ idSplineList() {
+ clear();
+ }
+
+ idSplineList(const char *p) {
+ clear();
+ name = p;
+ };
+
+ ~idSplineList() {
+ clear();
+ };
+
+ void clearControl() {
+ for (int i = 0; i < controlPoints.Num(); i++) {
+ delete controlPoints[i];
+ }
+ controlPoints.Clear();
+ }
+
+ void clearSpline() {
+ for (int i = 0; i < splinePoints.Num(); i++) {
+ delete splinePoints[i];
+ }
+ splinePoints.Clear();
+ }
+
+ void parse(const char *(*text));
+ void write(fileHandle_t file, const char *name);
+
+ void clear() {
+ clearControl();
+ clearSpline();
+ splineTime.Clear();
+ selected = NULL;
+ dirty = true;
+ activeSegment = 0;
+ granularity = 0.025;
+ pathColor.set(1.0, 0.5, 0.0);
+ controlColor.set(0.7, 0.0, 1.0);
+ segmentColor.set(0.0, 0.0, 1.0);
+ activeColor.set(1.0, 0.0, 0.0);
+ }
+
+ void initPosition(long startTime, long totalTime);
+ const idVec3_t *getPosition(long time);
+
+
+ void draw(bool editMode);
+ void addToRenderer();
+
+ void setSelectedPoint(idVec3_t *p);
+ idVec3_t *getSelectedPoint() {
+ return selected;
+ }
+
+ void addPoint(const idVec3_t &v) {
+ controlPoints.Append(new idVec3_t(v));
+ dirty = true;
+ }
+
+ void addPoint(float x, float y, float z) {
+ controlPoints.Append(new idVec3_t(x, y, z));
+ dirty = true;
+ }
+
+ void updateSelection(const idVec3_t &move);
+
+ void startEdit() {
+ editMode = true;
+ }
+
+ void stopEdit() {
+ editMode = false;
+ }
+
+ void buildSpline();
+
+ void setGranularity(float f) {
+ granularity = f;
+ }
+
+ float getGranularity() {
+ return granularity;
+ }
+
+ int numPoints() {
+ return controlPoints.Num();
+ }
+
+ idVec3_t *getPoint(int index) {
+ assert(index >= 0 && index < controlPoints.Num());
+ return controlPoints[index];
+ }
+
+ idVec3_t *getSegmentPoint(int index) {
+ assert(index >= 0 && index < splinePoints.Num());
+ return splinePoints[index];
+ }
+
+
+ void setSegmentTime(int index, int time) {
+ assert(index >= 0 && index < splinePoints.Num());
+ splineTime[index] = time;
+ }
+
+ int getSegmentTime(int index) {
+ assert(index >= 0 && index < splinePoints.Num());
+ return splineTime[index];
+ }
+ void addSegmentTime(int index, int time) {
+ assert(index >= 0 && index < splinePoints.Num());
+ splineTime[index] += time;
+ }
+
+ float totalDistance();
+
+ static idVec3_t zero;
+
+ int getActiveSegment() {
+ return activeSegment;
+ }
+
+ void setActiveSegment(int i) {
+ //assert(i >= 0 && (splinePoints.Num() > 0 && i < splinePoints.Num()));
+ activeSegment = i;
+ }
+
+ int numSegments() {
+ return splinePoints.Num();
+ }
+
+ void setColors(idVec3_t &path, idVec3_t &segment, idVec3_t &control, idVec3_t &active) {
+ pathColor = path;
+ segmentColor = segment;
+ controlColor = control;
+ activeColor = active;
+ }
+
+ const char *getName() {
+ return name.c_str();
+ }
+
+ void setName(const char *p) {
+ name = p;
+ }
+
+ bool validTime() {
+ if (dirty) {
+ buildSpline();
+ }
+ // gcc doesn't allow static casting away from bools
+ // why? I've no idea...
+ return (bool)(splineTime.Num() > 0 && splineTime.Num() == splinePoints.Num());
+ }
+
+ void setTime(long t) {
+ time = t;
+ }
+
+ void setBaseTime(long t) {
+ baseTime = t;
+ }
+
+protected:
+ idStr name;
+ float calcSpline(int step, float tension);
+ idList<idVec3_t*> controlPoints;
+ idList<idVec3_t*> splinePoints;
+ idList<float> splineTime;
+ idVec3_t *selected;
+ idVec3_t pathColor, segmentColor, controlColor, activeColor;
+ float granularity;
+ bool editMode;
+ bool dirty;
+ int activeSegment;
+ long baseTime;
+ long time;
+ friend class idCamera;
+};
+
+// time in milliseconds
+// velocity where 1.0 equal rough walking speed
+struct idVelocity {
+ idVelocity(long start, long duration, float s) {
+ startTime = start;
+ time = duration;
+ speed = s;
+ }
+ long startTime;
+ long time;
+ float speed;
+};
+
+// can either be a look at or origin position for a camera
+//
+class idCameraPosition : public idPointListInterface {
+public:
+
+ virtual void clear() {
+ editMode = false;
+ for (int i = 0; i < velocities.Num(); i++) {
+ delete velocities[i];
+ velocities[i] = NULL;
+ }
+ velocities.Clear();
+ }
+
+ idCameraPosition(const char *p) {
+ name = p;
+ }
+
+ idCameraPosition() {
+ time = 0;
+ name = "position";
+ }
+
+ idCameraPosition(long t) {
+ time = t;
+ }
+
+ virtual ~idCameraPosition() {
+ clear();
+ }
+
+
+ // this can be done with RTTI syntax but i like the derived classes setting a type
+ // makes serialization a bit easier to see
+ //
+ enum positionType {
+ FIXED = 0x00,
+ INTERPOLATED,
+ SPLINE,
+ POSITION_COUNT
+ };
+
+
+ virtual void start(long t) {
+ startTime = t;
+ }
+
+ long getTime() {
+ return time;
+ }
+
+ virtual void setTime(long t) {
+ time = t;
+ }
+
+ float getVelocity(long t) {
+ long check = t - startTime;
+ for (int i = 0; i < velocities.Num(); i++) {
+ if (check >= velocities[i]->startTime && check <= velocities[i]->startTime + velocities[i]->time) {
+ return velocities[i]->speed;
+ }
+ }
+ return baseVelocity;
+ }
+
+ void addVelocity(long start, long duration, float speed) {
+ velocities.Append(new idVelocity(start, duration, speed));
+ }
+
+ virtual const idVec3_t *getPosition(long t) {
+ assert(true);
+ return NULL;
+ }
+
+ virtual void draw(bool editMode) {};
+
+ virtual void parse(const char *(*text)) {};
+ virtual void write(fileHandle_t file, const char *name);
+ virtual bool parseToken(const char *key, const char *(*text));
+
+ const char *getName() {
+ return name.c_str();
+ }
+
+ void setName(const char *p) {
+ name = p;
+ }
+
+ virtual startEdit() {
+ editMode = true;
+ }
+
+ virtual stopEdit() {
+ editMode = false;
+ }
+
+ virtual void draw() {};
+
+ const char *typeStr() {
+ return positionStr[static_cast<int>(type)];
+ }
+
+ void calcVelocity(float distance) {
+ float secs = (float)time / 1000;
+ baseVelocity = distance / secs;
+ }
+
+protected:
+ static const char* positionStr[POSITION_COUNT];
+ long startTime;
+ long time;
+ idCameraPosition::positionType type;
+ idStr name;
+ bool editMode;
+ idList<idVelocity*> velocities;
+ float baseVelocity;
+};
+
+class idFixedPosition : public idCameraPosition {
+public:
+
+ void init() {
+ pos.Zero();
+ type = idCameraPosition::FIXED;
+ }
+
+ idFixedPosition() : idCameraPosition() {
+ init();
+ }
+
+ idFixedPosition(idVec3_t p) : idCameraPosition() {
+ init();
+ pos = p;
+ }
+
+ virtual void addPoint(const idVec3_t &v) {
+ pos = v;
+ }
+
+ virtual void addPoint(const float x, const float y, const float z) {
+ pos.set(x, y, z);
+ }
+
+
+ ~idFixedPosition() {
+ }
+
+ virtual const idVec3_t *getPosition(long t) {
+ return &pos;
+ }
+
+ void parse(const char *(*text));
+ void write(fileHandle_t file, const char *name);
+
+ virtual int numPoints() {
+ return 1;
+ }
+
+ virtual idVec3_t *getPoint(int index) {
+ if (index != 0) {
+ assert(true);
+ };
+ return &pos;
+ }
+
+ virtual void draw(bool editMode) {
+ glLabeledPoint(blue, pos, (editMode) ? 5 : 3, "Fixed point");
+ }
+
+protected:
+ idVec3_t pos;
+};
+
+class idInterpolatedPosition : public idCameraPosition {
+public:
+
+ void init() {
+ type = idCameraPosition::INTERPOLATED;
+ first = true;
+ startPos.Zero();
+ endPos.Zero();
+ }
+
+ idInterpolatedPosition() : idCameraPosition() {
+ init();
+ }
+
+ idInterpolatedPosition(idVec3_t start, idVec3_t end, long time) : idCameraPosition(time) {
+ init();
+ startPos = start;
+ endPos = end;
+ }
+
+ ~idInterpolatedPosition() {
+ }
+
+ virtual const idVec3_t *getPosition(long t);
+
+ void parse(const char *(*text));
+ void write(fileHandle_t file, const char *name);
+
+ virtual int numPoints() {
+ return 2;
+ }
+
+ virtual idVec3_t *getPoint(int index) {
+ assert(index >= 0 && index < 2);
+ if (index == 0) {
+ return &startPos;
+ }
+ return &endPos;
+ }
+
+ virtual void addPoint(const float x, const float y, const float z) {
+ if (first) {
+ startPos.set(x, y, z);
+ first = false;
+ } else {
+ endPos.set(x, y, z);
+ first = true;
+ }
+ }
+
+ virtual void addPoint(const idVec3_t &v) {
+ if (first) {
+ startPos = v;
+ first = false;
+ } else {
+ endPos = v;
+ first = true;
+ }
+ }
+
+ virtual void draw(bool editMode) {
+ glLabeledPoint(blue, startPos, (editMode) ? 5 : 3, "Start interpolated");
+ glLabeledPoint(blue, endPos, (editMode) ? 5 : 3, "End interpolated");
+ qglBegin(GL_LINES);
+ qglVertex3fv(startPos);
+ qglVertex3fv(endPos);
+ qglEnd();
+ }
+
+ virtual void start(long t) {
+ idCameraPosition::start(t);
+ lastTime = startTime;
+ distSoFar = 0.0;
+ idVec3_t temp = startPos;
+ temp -= endPos;
+ calcVelocity(temp.Length());
+ }
+
+protected:
+ bool first;
+ idVec3_t startPos;
+ idVec3_t endPos;
+ long lastTime;
+ float distSoFar;
+};
+
+class idSplinePosition : public idCameraPosition {
+public:
+
+ void init() {
+ type = idCameraPosition::SPLINE;
+ }
+
+ idSplinePosition() : idCameraPosition() {
+ init();
+ }
+
+ idSplinePosition(long time) : idCameraPosition(time) {
+ init();
+ }
+
+ ~idSplinePosition() {
+ }
+
+ virtual void start(long t) {
+ idCameraPosition::start(t);
+ target.initPosition(t, time);
+ calcVelocity(target.totalDistance());
+ }
+
+ virtual const idVec3_t *getPosition(long t) {
+ return target.getPosition(t);
+ }
+
+ //virtual const idVec3_t *getPosition(long t) const {
+
+ void addControlPoint(idVec3_t &v) {
+ target.addPoint(v);
+ }
+
+ void parse(const char *(*text));
+ void write(fileHandle_t file, const char *name);
+
+ virtual int numPoints() {
+ return target.numPoints();
+ }
+
+ virtual idVec3_t *getPoint(int index) {
+ return target.getPoint(index);
+ }
+
+ virtual void addPoint(const idVec3_t &v) {
+ target.addPoint(v);
+ }
+
+ virtual void addPoint(const float x, const float y, const float z) {
+ target.addPoint(x, y, z);
+ }
+
+ virtual void draw(bool editMode) {
+ target.draw(editMode);
+ }
+
+ virtual void updateSelection(const idVec3_t &move) {
+ idCameraPosition::updateSelection(move);
+ target.buildSpline();
+ }
+
+protected:
+ idSplineList target;
+};
+
+class idCameraFOV {
+public:
+
+ idCameraFOV() {
+ time = 0;
+ fov = 90;
+ }
+
+ idCameraFOV(int v) {
+ time = 0;
+ fov = v;
+ }
+
+ idCameraFOV(int s, int e, long t) {
+ startFOV = s;
+ endFOV = e;
+ time = t;
+ }
+
+
+ ~idCameraFOV(){}
+
+ void setFOV(float f) {
+ fov = f;
+ }
+
+ float getFOV(long t) {
+ if (time) {
+ assert(startTime);
+ float percent = t / startTime;
+ float temp = startFOV - endFOV;
+ temp *= percent;
+ fov = startFOV + temp;
+ }
+ return fov;
+ }
+
+ int start(long t) {
+ startTime = t;
+ }
+
+ void parse(const char *(*text));
+ void write(fileHandle_t file, const char *name);
+
+protected:
+ float fov;
+ float startFOV;
+ float endFOV;
+ int startTime;
+ int time;
+};
+
+
+
+
+class idCameraEvent {
+public:
+ enum eventType {
+ EVENT_NA = 0x00,
+ EVENT_WAIT,
+ EVENT_TARGETWAIT,
+ EVENT_SPEED,
+ EVENT_TARGET,
+ EVENT_SNAPTARGET,
+ EVENT_FOV,
+ EVENT_SCRIPT,
+ EVENT_TRIGGER,
+ EVENT_STOP,
+ EVENT_COUNT
+ };
+
+ static const char* eventStr[EVENT_COUNT];
+
+ idCameraEvent() {
+ paramStr = "";
+ type = EVENT_NA;
+ time = 0;
+ }
+
+ idCameraEvent(eventType t, const char *param, long n) {
+ type = t;
+ paramStr = param;
+ time = n;
+ }
+
+ ~idCameraEvent() {};
+
+ eventType getType() {
+ return type;
+ }
+
+ const char *typeStr() {
+ return eventStr[static_cast<int>(type)];
+ }
+
+ const char *getParam() {
+ return paramStr.c_str();
+ }
+
+ long getTime() {
+ return time;
+ }
+
+ void setTime(long n) {
+ time = n;
+ }
+
+ void parse(const char *(*text));
+ void write(fileHandle_t file, const char *name);
+
+ void setTriggered(bool b) {
+ triggered = b;
+ }
+
+ bool getTriggered() {
+ return triggered;
+ }
+
+protected:
+ eventType type;
+ idStr paramStr;
+ long time;
+ bool triggered;
+
+};
+
+class idCameraDef {
+public:
+
+ void clear() {
+ currentCameraPosition = 0;
+ cameraRunning = false;
+ lastDirection.Zero();
+ baseTime = 30;
+ activeTarget = 0;
+ name = "camera01";
+ fov.setFOV(90);
+ int i;
+ for (i = 0; i < targetPositions.Num(); i++) {
+ delete targetPositions[i];
+ }
+ for (i = 0; i < events.Num(); i++) {
+ delete events[i];
+ }
+ delete cameraPosition;
+ cameraPosition = NULL;
+ events.Clear();
+ targetPositions.Clear();
+ }
+
+ idCameraPosition *startNewCamera(idCameraPosition::positionType type) {
+ clear();
+ if (type == idCameraPosition::SPLINE) {
+ cameraPosition = new idSplinePosition();
+ } else if (type == idCameraPosition::INTERPOLATED) {
+ cameraPosition = new idInterpolatedPosition();
+ } else {
+ cameraPosition = new idFixedPosition();
+ }
+ return cameraPosition;
+ }
+
+ idCameraDef() {
+ clear();
+ }
+
+ ~idCameraDef() {
+ clear();
+ }
+
+ void addEvent(idCameraEvent::eventType t, const char *param, long time);
+
+ void addEvent(idCameraEvent *event);
+
+ static int sortEvents(const void *p1, const void *p2);
+
+ int numEvents() {
+ return events.Num();
+ }
+
+ idCameraEvent *getEvent(int index) {
+ assert(index >= 0 && index < events.Num());
+ return events[index];
+ }
+
+ void parse(const char *(*text));
+ bool load(const char *filename);
+ void save(const char *filename);
+
+ void buildCamera();
+
+ //idSplineList *getcameraPosition() {
+ // return &cameraPosition;
+ //}
+
+ static idCameraPosition *newFromType(idCameraPosition::positionType t) {
+ switch (t) {
+ case idCameraPosition::FIXED : return new idFixedPosition();
+ case idCameraPosition::INTERPOLATED : return new idInterpolatedPosition();
+ case idCameraPosition::SPLINE : return new idSplinePosition();
+ };
+ return NULL;
+ }
+
+ void addTarget(const char *name, idCameraPosition::positionType type);
+
+ idCameraPosition *getActiveTarget() {
+ if (targetPositions.Num() == 0) {
+ addTarget(NULL, idCameraPosition::FIXED);
+ }
+ return targetPositions[activeTarget];
+ }
+
+ idCameraPosition *getActiveTarget(int index) {
+ if (targetPositions.Num() == 0) {
+ addTarget(NULL, idCameraPosition::FIXED);
+ return targetPositions[0];
+ }
+ return targetPositions[index];
+ }
+
+ int numTargets() {
+ return targetPositions.Num();
+ }
+
+
+ void setActiveTargetByName(const char *name) {
+ for (int i = 0; i < targetPositions.Num(); i++) {
+ if (stricmp(name, targetPositions[i]->getName()) == 0) {
+ setActiveTarget(i);
+ return;
+ }
+ }
+ }
+
+ void setActiveTarget(int index) {
+ assert(index >= 0 && index < targetPositions.Num());
+ activeTarget = index;
+ }
+
+ void setRunning(bool b) {
+ cameraRunning = b;
+ }
+
+ void setBaseTime(float f) {
+ baseTime = f;
+ }
+
+ float getBaseTime() {
+ return baseTime;
+ }
+
+ float getTotalTime() {
+ return totalTime;
+ }
+
+ void startCamera(long t);
+ void stopCamera() {
+ cameraRunning = true;
+ }
+ void getActiveSegmentInfo(int segment, idVec3_t &origin, idVec3_t &direction, float *fv);
+
+ bool getCameraInfo(long time, idVec3_t &origin, idVec3_t &direction, float *fv);
+ bool getCameraInfo(long time, float *origin, float *direction, float *fv) {
+ idVec3_t org, dir;
+ org[0] = origin[0];
+ org[1] = origin[1];
+ org[2] = origin[2];
+ dir[0] = direction[0];
+ dir[1] = direction[1];
+ dir[2] = direction[2];
+ bool b = getCameraInfo(time, org, dir, fv);
+ origin[0] = org[0];
+ origin[1] = org[1];
+ origin[2] = org[2];
+ direction[0] = dir[0];
+ direction[1] = dir[1];
+ direction[2] = dir[2];
+ return b;
+ }
+
+ void draw(bool editMode) {
+ // gcc doesn't allow casting away from bools
+ // why? I've no idea...
+ if (cameraPosition) {
+ cameraPosition->draw((bool)((editMode || cameraRunning) && cameraEdit));
+ int count = targetPositions.Num();
+ for (int i = 0; i < count; i++) {
+ targetPositions[i]->draw((bool)((editMode || cameraRunning) && i == activeTarget && !cameraEdit));
+ }
+ }
+ }
+
+/*
+ int numSegments() {
+ if (cameraEdit) {
+ return cameraPosition.numSegments();
+ }
+ return getTargetSpline()->numSegments();
+ }
+
+ int getActiveSegment() {
+ if (cameraEdit) {
+ return cameraPosition.getActiveSegment();
+ }
+ return getTargetSpline()->getActiveSegment();
+ }
+
+ void setActiveSegment(int i) {
+ if (cameraEdit) {
+ cameraPosition.setActiveSegment(i);
+ } else {
+ getTargetSpline()->setActiveSegment(i);
+ }
+ }
+*/
+ int numPoints() {
+ if (cameraEdit) {
+ return cameraPosition->numPoints();
+ }
+ return getActiveTarget()->numPoints();
+ }
+
+ const idVec3_t *getPoint(int index) {
+ if (cameraEdit) {
+ return cameraPosition->getPoint(index);
+ }
+ return getActiveTarget()->getPoint(index);
+ }
+
+ void stopEdit() {
+ editMode = false;
+ if (cameraEdit) {
+ cameraPosition->stopEdit();
+ } else {
+ getActiveTarget()->stopEdit();
+ }
+ }
+
+ void startEdit(bool camera) {
+ cameraEdit = camera;
+ if (camera) {
+ cameraPosition->startEdit();
+ for (int i = 0; i < targetPositions.Num(); i++) {
+ targetPositions[i]->stopEdit();
+ }
+ } else {
+ getActiveTarget()->startEdit();
+ cameraPosition->stopEdit();
+ }
+ editMode = true;
+ }
+
+ bool waitEvent(int index);
+
+ const char *getName() {
+ return name.c_str();
+ }
+
+ void setName(const char *p) {
+ name = p;
+ }
+
+ idCameraPosition *getPositionObj() {
+ if (cameraPosition == NULL) {
+ cameraPosition = new idFixedPosition();
+ }
+ return cameraPosition;
+ }
+
+protected:
+ idStr name;
+ int currentCameraPosition;
+ idVec3_t lastDirection;
+ bool cameraRunning;
+ idCameraPosition *cameraPosition;
+ idList<idCameraPosition*> targetPositions;
+ idList<idCameraEvent*> events;
+ idCameraFOV fov;
+ int activeTarget;
+ float totalTime;
+ float baseTime;
+ long startTime;
+
+ bool cameraEdit;
+ bool editMode;
+};
+
+extern bool g_splineMode;
+
+extern idCameraDef *g_splineList;
+
+
+#endif \ No newline at end of file
diff --git a/q3radiant/splines/util_list.h b/q3radiant/splines/util_list.h
new file mode 100755
index 0000000..4f93244
--- /dev/null
+++ b/q3radiant/splines/util_list.h
@@ -0,0 +1,346 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __UTIL_LIST_H__
+#define __UTIL_LIST_H__
+
+#include <stdlib.h>
+#include <assert.h>
+
+template< class type >
+class idList {
+private:
+ int m_num;
+ int m_size;
+ int m_granularity;
+ type *m_list;
+
+public:
+ idList( int granularity = 16 );
+ ~idList<type>();
+ void Clear( void );
+ int Num( void );
+ void SetNum( int num );
+ void SetGranularity( int granularity );
+ void Condense( void );
+ int Size( void );
+ void Resize( int size );
+ type operator[]( int index ) const;
+ type &operator[]( int index );
+ int Append( type const & obj );
+ int AddUnique( type const & obj );
+ type *Find( type const & obj, int *index = NULL );
+ bool RemoveIndex( int index );
+ bool Remove( type const & obj );
+ typedef int cmp_t(const void *, const void *);
+ void Sort( cmp_t *compare );
+};
+
+/*
+================
+idList<type>::idList( int )
+================
+*/
+template< class type >
+inline idList<type>::idList( int granularity ) {
+ assert( granularity > 0 );
+
+ m_list = NULL;
+ m_granularity = granularity;
+ Clear();
+}
+
+/*
+================
+idList<type>::~idList<type>
+================
+*/
+template< class type >
+inline idList<type>::~idList() {
+ Clear();
+}
+
+/*
+================
+idList<type>::Clear
+================
+*/
+template< class type >
+inline void idList<type>::Clear( void ) {
+ if ( m_list ) {
+ delete[] m_list;
+ }
+
+ m_list = NULL;
+ m_num = 0;
+ m_size = 0;
+}
+
+/*
+================
+idList<type>::Num
+================
+*/
+template< class type >
+inline int idList<type>::Num( void ) {
+ return m_num;
+}
+
+/*
+================
+idList<type>::SetNum
+================
+*/
+template< class type >
+inline void idList<type>::SetNum( int num ) {
+ assert( num >= 0 );
+ if ( num > m_size ) {
+ // resize it up to the closest level of granularity
+ Resize( ( ( num + m_granularity - 1 ) / m_granularity ) * m_granularity );
+ }
+ m_num = num;
+}
+
+/*
+================
+idList<type>::SetGranularity
+================
+*/
+template< class type >
+inline void idList<type>::SetGranularity( int granularity ) {
+ int newsize;
+
+ assert( granularity > 0 );
+ m_granularity = granularity;
+
+ if ( m_list ) {
+ // resize it to the closest level of granularity
+ newsize = ( ( m_num + m_granularity - 1 ) / m_granularity ) * m_granularity;
+ if ( newsize != m_size ) {
+ Resize( newsize );
+ }
+ }
+}
+
+/*
+================
+idList<type>::Condense
+
+Resizes the array to exactly the number of elements it contains
+================
+*/
+template< class type >
+inline void idList<type>::Condense( void ) {
+ if ( m_list ) {
+ if ( m_num ) {
+ Resize( m_num );
+ } else {
+ Clear();
+ }
+ }
+}
+
+/*
+================
+idList<type>::Size
+================
+*/
+template< class type >
+inline int idList<type>::Size( void ) {
+ return m_size;
+}
+
+/*
+================
+idList<type>::Resize
+================
+*/
+template< class type >
+inline void idList<type>::Resize( int size ) {
+ type *temp;
+ int i;
+
+ assert( size > 0 );
+
+ if ( size <= 0 ) {
+ Clear();
+ return;
+ }
+
+ temp = m_list;
+ m_size = size;
+ if ( m_size < m_num ) {
+ m_num = m_size;
+ }
+
+ m_list = new type[ m_size ];
+ for( i = 0; i < m_num; i++ ) {
+ m_list[ i ] = temp[ i ];
+ }
+
+ if ( temp ) {
+ delete[] temp;
+ }
+}
+
+/*
+================
+idList<type>::operator[] const
+================
+*/
+template< class type >
+inline type idList<type>::operator[]( int index ) const {
+ assert( index >= 0 );
+ assert( index < m_num );
+
+ return m_list[ index ];
+}
+
+/*
+================
+idList<type>::operator[]
+================
+*/
+template< class type >
+inline type &idList<type>::operator[]( int index ) {
+ assert( index >= 0 );
+ assert( index < m_num );
+
+ return m_list[ index ];
+}
+
+/*
+================
+idList<type>::Append
+================
+*/
+template< class type >
+inline int idList<type>::Append( type const & obj ) {
+ if ( !m_list ) {
+ Resize( m_granularity );
+ }
+
+ if ( m_num == m_size ) {
+ Resize( m_size + m_granularity );
+ }
+
+ m_list[ m_num ] = obj;
+ m_num++;
+
+ return m_num - 1;
+}
+
+/*
+================
+idList<type>::AddUnique
+================
+*/
+template< class type >
+inline int idList<type>::AddUnique( type const & obj ) {
+ int index;
+
+ if ( !Find( obj, &index ) ) {
+ index = Append( obj );
+ }
+
+ return index;
+}
+
+/*
+================
+idList<type>::Find
+================
+*/
+template< class type >
+inline type *idList<type>::Find( type const & obj, int *index ) {
+ int i;
+
+ for( i = 0; i < m_num; i++ ) {
+ if ( m_list[ i ] == obj ) {
+ if ( index ) {
+ *index = i;
+ }
+ return &m_list[ i ];
+ }
+ }
+
+ return NULL;
+}
+
+/*
+================
+idList<type>::RemoveIndex
+================
+*/
+template< class type >
+inline bool idList<type>::RemoveIndex( int index ) {
+ int i;
+
+ if ( !m_list || !m_num ) {
+ return false;
+ }
+
+ assert( index >= 0 );
+ assert( index < m_num );
+
+ if ( ( index < 0 ) || ( index >= m_num ) ) {
+ return false;
+ }
+
+ m_num--;
+ for( i = index; i < m_num; i++ ) {
+ m_list[ i ] = m_list[ i + 1 ];
+ }
+
+ return true;
+}
+
+/*
+================
+idList<type>::Remove
+================
+*/
+template< class type >
+inline bool idList<type>::Remove( type const & obj ) {
+ int index;
+
+ if ( Find( obj, &index ) ) {
+ return RemoveIndex( index );
+ }
+
+ return false;
+}
+
+/*
+================
+idList<type>::Sort
+================
+*/
+template< class type >
+inline void idList<type>::Sort( cmp_t *compare ) {
+ if ( !m_list ) {
+ return;
+ }
+
+ qsort( ( void * )m_list, ( size_t )m_num, sizeof( type ), compare );
+}
+
+#endif /* !__UTIL_LIST_H__ */
diff --git a/q3radiant/splines/util_str.cpp b/q3radiant/splines/util_str.cpp
new file mode 100755
index 0000000..230a77f
--- /dev/null
+++ b/q3radiant/splines/util_str.cpp
@@ -0,0 +1,618 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//need to rewrite this
+
+#include "util_str.h"
+#include <stdlib.h>
+#include <ctype.h>
+#include <stdio.h>
+#include <stdarg.h>
+
+#ifdef _WIN32
+#pragma warning(disable : 4244) // 'conversion' conversion from 'type1' to 'type2', possible loss of data
+#pragma warning(disable : 4710) // function 'blah' not inlined
+#endif
+
+static const int STR_ALLOC_GRAN = 20;
+
+char *idStr::tolower
+ (
+ char *s1
+ )
+
+ {
+ char *s;
+
+ s = s1;
+ while( *s )
+ {
+ *s = ::tolower( *s );
+ s++;
+ }
+
+ return s1;
+ }
+
+char *idStr::toupper
+ (
+ char *s1
+ )
+
+ {
+ char *s;
+
+ s = s1;
+ while( *s )
+ {
+ *s = ::toupper( *s );
+ s++;
+ }
+
+ return s1;
+ }
+
+int idStr::icmpn
+ (
+ const char *s1,
+ const char *s2,
+ int n
+ )
+
+ {
+ int c1;
+ int c2;
+
+ do
+ {
+ c1 = *s1++;
+ c2 = *s2++;
+
+ if ( !n-- )
+ {
+ // idStrings are equal until end point
+ return 0;
+ }
+
+ if ( c1 != c2 )
+ {
+ if ( c1 >= 'a' && c1 <= 'z' )
+ {
+ c1 -= ( 'a' - 'A' );
+ }
+
+ if ( c2 >= 'a' && c2 <= 'z' )
+ {
+ c2 -= ( 'a' - 'A' );
+ }
+
+ if ( c1 < c2 )
+ {
+ // strings less than
+ return -1;
+ }
+ else if ( c1 > c2 )
+ {
+ // strings greater than
+ return 1;
+ }
+ }
+ }
+ while( c1 );
+
+ // strings are equal
+ return 0;
+ }
+
+int idStr::icmp
+ (
+ const char *s1,
+ const char *s2
+ )
+
+ {
+ int c1;
+ int c2;
+
+ do
+ {
+ c1 = *s1++;
+ c2 = *s2++;
+
+ if ( c1 != c2 )
+ {
+ if ( c1 >= 'a' && c1 <= 'z' )
+ {
+ c1 -= ( 'a' - 'A' );
+ }
+
+ if ( c2 >= 'a' && c2 <= 'z' )
+ {
+ c2 -= ( 'a' - 'A' );
+ }
+
+ if ( c1 < c2 )
+ {
+ // strings less than
+ return -1;
+ }
+ else if ( c1 > c2 )
+ {
+ // strings greater than
+ return 1;
+ }
+ }
+ }
+ while( c1 );
+
+ // strings are equal
+ return 0;
+ }
+
+int idStr::cmpn
+ (
+ const char *s1,
+ const char *s2,
+ int n
+ )
+
+ {
+ int c1;
+ int c2;
+
+ do
+ {
+ c1 = *s1++;
+ c2 = *s2++;
+
+ if ( !n-- )
+ {
+ // strings are equal until end point
+ return 0;
+ }
+
+ if ( c1 < c2 )
+ {
+ // strings less than
+ return -1;
+ }
+ else if ( c1 > c2 )
+ {
+ // strings greater than
+ return 1;
+ }
+ }
+ while( c1 );
+
+ // strings are equal
+ return 0;
+ }
+
+int idStr::cmp
+ (
+ const char *s1,
+ const char *s2
+ )
+
+ {
+ int c1;
+ int c2;
+
+ do
+ {
+ c1 = *s1++;
+ c2 = *s2++;
+
+ if ( c1 < c2 )
+ {
+ // strings less than
+ return -1;
+ }
+ else if ( c1 > c2 )
+ {
+ // strings greater than
+ return 1;
+ }
+ }
+ while( c1 );
+
+ // strings are equal
+ return 0;
+ }
+
+/*
+============
+IsNumeric
+
+Checks a string to see if it contains only numerical values.
+============
+*/
+bool idStr::isNumeric
+ (
+ const char *str
+ )
+
+ {
+ int len;
+ int i;
+ bool dot;
+
+ if ( *str == '-' )
+ {
+ str++;
+ }
+
+ dot = false;
+ len = strlen( str );
+ for( i = 0; i < len; i++ )
+ {
+ if ( !isdigit( str[ i ] ) )
+ {
+ if ( ( str[ i ] == '.' ) && !dot )
+ {
+ dot = true;
+ continue;
+ }
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+idStr operator+
+ (
+ const idStr& a,
+ const float b
+ )
+
+ {
+ char text[ 20 ];
+
+ idStr result( a );
+
+ sprintf( text, "%f", b );
+ result.append( text );
+
+ return result;
+ }
+
+idStr operator+
+ (
+ const idStr& a,
+ const int b
+ )
+
+ {
+ char text[ 20 ];
+
+ idStr result( a );
+
+ sprintf( text, "%d", b );
+ result.append( text );
+
+ return result;
+ }
+
+idStr operator+
+ (
+ const idStr& a,
+ const unsigned b
+ )
+
+ {
+ char text[ 20 ];
+
+ idStr result( a );
+
+ sprintf( text, "%u", b );
+ result.append( text );
+
+ return result;
+ }
+
+idStr& idStr::operator+=
+ (
+ const float a
+ )
+
+ {
+ char text[ 20 ];
+
+ sprintf( text, "%f", a );
+ append( text );
+
+ return *this;
+ }
+
+idStr& idStr::operator+=
+ (
+ const int a
+ )
+
+ {
+ char text[ 20 ];
+
+ sprintf( text, "%d", a );
+ append( text );
+
+ return *this;
+ }
+
+idStr& idStr::operator+=
+ (
+ const unsigned a
+ )
+
+ {
+ char text[ 20 ];
+
+ sprintf( text, "%u", a );
+ append( text );
+
+ return *this;
+ }
+
+void idStr::CapLength
+ (
+ int newlen
+ )
+
+ {
+ assert ( m_data );
+
+ if ( length() <= newlen )
+ return;
+
+ EnsureDataWritable ();
+
+ m_data->data[newlen] = 0;
+ m_data->len = newlen;
+ }
+
+void idStr::EnsureDataWritable
+ (
+ void
+ )
+
+ {
+ assert ( m_data );
+ strdata *olddata;
+ int len;
+
+ if ( !m_data->refcount )
+ return;
+
+ olddata = m_data;
+ len = length();
+
+ m_data = new strdata;
+
+ EnsureAlloced ( len + 1, false );
+ strncpy ( m_data->data, olddata->data, len+1 );
+ m_data->len = len;
+
+ olddata->DelRef ();
+ }
+
+void idStr::EnsureAlloced (int amount, bool keepold) {
+
+ if ( !m_data ) {
+ m_data = new strdata();
+ }
+
+ // Now, let's make sure it's writable
+ EnsureDataWritable ();
+
+ char *newbuffer;
+ bool wasalloced = ( m_data->alloced != 0 );
+
+ if ( amount < m_data->alloced ) {
+ return;
+ }
+
+ assert ( amount );
+ if ( amount == 1 ) {
+ m_data->alloced = 1;
+ } else {
+ int newsize, mod;
+ mod = amount % STR_ALLOC_GRAN;
+ if ( !mod ) {
+ newsize = amount;
+ } else {
+ newsize = amount + STR_ALLOC_GRAN - mod;
+ }
+ m_data->alloced = newsize;
+ }
+
+ newbuffer = new char[m_data->alloced];
+ if ( wasalloced && keepold ) {
+ strcpy ( newbuffer, m_data->data );
+ }
+
+ if ( m_data->data ) {
+ delete [] m_data->data;
+ }
+ m_data->data = newbuffer;
+}
+
+void idStr::BackSlashesToSlashes
+ (
+ void
+ )
+
+ {
+ int i;
+
+ EnsureDataWritable ();
+
+ for ( i=0; i < m_data->len; i++ )
+ {
+ if ( m_data->data[i] == '\\' )
+ m_data->data[i] = '/';
+ }
+ }
+
+void idStr::snprintf
+ (
+ char *dst,
+ int size,
+ const char *fmt,
+ ...
+ )
+
+ {
+ char buffer[0x10000];
+ int len;
+ va_list argptr;
+
+ va_start (argptr,fmt);
+ len = vsprintf (buffer,fmt,argptr);
+ va_end (argptr);
+
+ assert ( len < size );
+
+ strncpy (dst, buffer, size-1);
+ }
+
+#ifdef _WIN32
+#pragma warning(disable : 4189) // local variable is initialized but not referenced
+#endif
+
+/*
+=================
+TestStringClass
+
+This is a fairly rigorous test of the idStr class's functionality.
+Because of the fairly global and subtle ramifications of a bug occuring
+in this class, it should be run after any changes to the class.
+Add more tests as functionality is changed. Tests should include
+any possible bounds violation and NULL data tests.
+=================
+*/
+void TestStringClass
+ (
+ void
+ )
+
+ {
+ char ch; // ch == ?
+ idStr *t; // t == ?
+ idStr a; // a.len == 0, a.data == "\0"
+ idStr b; // b.len == 0, b.data == "\0"
+ idStr c( "test" ); // c.len == 4, c.data == "test\0"
+ idStr d( c ); // d.len == 4, d.data == "test\0"
+ idStr e( reinterpret_cast<const char *>(NULL) );
+ // e.len == 0, e.data == "\0" ASSERT!
+ int i; // i == ?
+
+ i = a.length(); // i == 0
+ i = c.length(); // i == 4
+
+ const char *s1 = a.c_str(); // s1 == "\0"
+ const char *s2 = c.c_str(); // s2 == "test\0"
+
+ t = new idStr(); // t->len == 0, t->data == "\0"
+ delete t; // t == ?
+
+ b = "test"; // b.len == 4, b.data == "test\0"
+ t = new idStr( "test" ); // t->len == 4, t->data == "test\0"
+ delete t; // t == ?
+
+ a = c; // a.len == 4, a.data == "test\0"
+// a = "";
+ a = NULL; // a.len == 0, a.data == "\0" ASSERT!
+ a = c + d; // a.len == 8, a.data == "testtest\0"
+ a = c + "wow"; // a.len == 7, a.data == "testwow\0"
+ a = c + reinterpret_cast<const char *>(NULL);
+ // a.len == 4, a.data == "test\0" ASSERT!
+ a = "this" + d; // a.len == 8, a.data == "thistest\0"
+ a = reinterpret_cast<const char *>(NULL) + d;
+ // a.len == 4, a.data == "test\0" ASSERT!
+ a += c; // a.len == 8, a.data == "testtest\0"
+ a += "wow"; // a.len == 11, a.data == "testtestwow\0"
+ a += reinterpret_cast<const char *>(NULL);
+ // a.len == 11, a.data == "testtestwow\0" ASSERT!
+
+ a = "test"; // a.len == 4, a.data == "test\0"
+ ch = a[ 0 ]; // ch == 't'
+ ch = a[ -1 ]; // ch == 0 ASSERT!
+ ch = a[ 1000 ]; // ch == 0 ASSERT!
+ ch = a[ 0 ]; // ch == 't'
+ ch = a[ 1 ]; // ch == 'e'
+ ch = a[ 2 ]; // ch == 's'
+ ch = a[ 3 ]; // ch == 't'
+ ch = a[ 4 ]; // ch == '\0' ASSERT!
+ ch = a[ 5 ]; // ch == '\0' ASSERT!
+
+ a[ 1 ] = 'b'; // a.len == 4, a.data == "tbst\0"
+ a[ -1 ] = 'b'; // a.len == 4, a.data == "tbst\0" ASSERT!
+ a[ 0 ] = '0'; // a.len == 4, a.data == "0bst\0"
+ a[ 1 ] = '1'; // a.len == 4, a.data == "01st\0"
+ a[ 2 ] = '2'; // a.len == 4, a.data == "012t\0"
+ a[ 3 ] = '3'; // a.len == 4, a.data == "0123\0"
+ a[ 4 ] = '4'; // a.len == 4, a.data == "0123\0" ASSERT!
+ a[ 5 ] = '5'; // a.len == 4, a.data == "0123\0" ASSERT!
+ a[ 7 ] = '7'; // a.len == 4, a.data == "0123\0" ASSERT!
+
+ a = "test"; // a.len == 4, a.data == "test\0"
+ b = "no"; // b.len == 2, b.data == "no\0"
+
+ i = ( a == b ); // i == 0
+ i = ( a == c ); // i == 1
+
+ i = ( a == "blow" ); // i == 0
+ i = ( a == "test" ); // i == 1
+ i = ( a == NULL ); // i == 0 ASSERT!
+
+ i = ( "test" == b ); // i == 0
+ i = ( "test" == a ); // i == 1
+ i = ( NULL == a ); // i == 0 ASSERT!
+
+ i = ( a != b ); // i == 1
+ i = ( a != c ); // i == 0
+
+ i = ( a != "blow" ); // i == 1
+ i = ( a != "test" ); // i == 0
+ i = ( a != NULL ); // i == 1 ASSERT!
+
+ i = ( "test" != b ); // i == 1
+ i = ( "test" != a ); // i == 0
+ i = ( NULL != a ); // i == 1 ASSERT!
+
+ a = "test"; // a.data == "test"
+ b = a; // b.data == "test"
+
+ a = "not"; // a.data == "not", b.data == "test"
+
+ a = b; // a.data == b.data == "test"
+
+ a += b; // a.data == "testtest", b.data = "test"
+
+ a = b;
+
+ a[1] = '1'; // a.data = "t1st", b.data = "test"
+ }
+
+#ifdef _WIN32
+#pragma warning(default : 4189) // local variable is initialized but not referenced
+#pragma warning(disable : 4514) // unreferenced inline function has been removed
+#endif
diff --git a/q3radiant/splines/util_str.h b/q3radiant/splines/util_str.h
new file mode 100755
index 0000000..896bf89
--- /dev/null
+++ b/q3radiant/splines/util_str.h
@@ -0,0 +1,817 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+//need to rewrite this
+
+#ifndef __UTIL_STR_H__
+#define __UTIL_STR_H__
+
+#include <assert.h>
+#include <string.h>
+#include <stdio.h>
+
+#ifdef _WIN32
+#pragma warning(disable : 4710) // function 'blah' not inlined
+#endif
+
+void TestStringClass ();
+
+class strdata
+ {
+ public:
+ strdata () : len( 0 ), refcount ( 0 ), data ( NULL ), alloced ( 0 ) {}
+ ~strdata ()
+ {
+ if ( data )
+ delete [] data;
+ }
+
+ void AddRef () { refcount++; }
+ bool DelRef () // True if killed
+ {
+ refcount--;
+ if ( refcount < 0 )
+ {
+ delete this;
+ return true;
+ }
+
+ return false;
+ }
+
+ int len;
+ int refcount;
+ char *data;
+ int alloced;
+ };
+
+class idStr {
+protected:
+ strdata *m_data;
+ void EnsureAlloced ( int, bool keepold = true );
+ void EnsureDataWritable ();
+
+public:
+ ~idStr();
+ idStr();
+ idStr( const char *text );
+ idStr( const idStr& string );
+ idStr( const idStr string, int start, int end );
+ idStr( const char ch );
+ idStr( const int num );
+ idStr( const float num );
+ idStr( const unsigned num );
+ int length( void ) const;
+ int allocated( void ) const;
+ const char * c_str( void ) const;
+
+ void append( const char *text );
+ void append( const idStr& text );
+ char operator[]( int index ) const;
+ char& operator[]( int index );
+
+ void operator=( const idStr& text );
+ void operator=( const char *text );
+
+ friend idStr operator+( const idStr& a, const idStr& b );
+ friend idStr operator+( const idStr& a, const char *b );
+ friend idStr operator+( const char *a, const idStr& b );
+
+ friend idStr operator+( const idStr& a, const float b );
+ friend idStr operator+( const idStr& a, const int b );
+ friend idStr operator+( const idStr& a, const unsigned b );
+ friend idStr operator+( const idStr& a, const bool b );
+ friend idStr operator+( const idStr& a, const char b );
+
+ idStr& operator+=( const idStr& a );
+ idStr& operator+=( const char *a );
+ idStr& operator+=( const float a );
+ idStr& operator+=( const char a );
+ idStr& operator+=( const int a );
+ idStr& operator+=( const unsigned a );
+ idStr& operator+=( const bool a );
+
+ friend bool operator==( const idStr& a, const idStr& b );
+ friend bool operator==( const idStr& a, const char *b );
+ friend bool operator==( const char *a, const idStr& b );
+
+ friend bool operator!=( const idStr& a, const idStr& b );
+ friend bool operator!=( const idStr& a, const char *b );
+ friend bool operator!=( const char *a, const idStr& b );
+
+ operator const char * () const;
+ operator const char * ();
+
+ int icmpn( const char *text, int n ) const;
+ int icmpn( const idStr& text, int n ) const;
+ int icmp( const char *text ) const;
+ int icmp( const idStr& text ) const;
+ int cmpn( const char *text, int n ) const;
+ int cmpn( const idStr& text, int n ) const;
+ int cmp( const char *text ) const;
+ int cmp( const idStr& text ) const;
+
+ void tolower( void );
+ void toupper( void );
+
+ static char *tolower( char *s1 );
+ static char *toupper( char *s1 );
+
+ static int icmpn( const char *s1, const char *s2, int n );
+ static int icmp( const char *s1, const char *s2 );
+ static int cmpn( const char *s1, const char *s2, int n );
+ static int cmp( const char *s1, const char *s2 );
+
+ static void snprintf ( char *dst, int size, const char *fmt, ... );
+
+ static bool isNumeric( const char *str );
+ bool isNumeric( void ) const;
+
+ void CapLength ( int );
+
+ void BackSlashesToSlashes ();
+
+};
+
+inline idStr::~idStr()
+ {
+ if ( m_data )
+ {
+ m_data->DelRef ();
+ m_data = NULL;
+ }
+ }
+
+inline idStr::idStr() : m_data ( NULL )
+ {
+ EnsureAlloced ( 1 );
+ m_data->data[ 0 ] = 0;
+ }
+
+inline idStr::idStr
+ (
+ const char *text
+ ) : m_data ( NULL )
+
+ {
+ int len;
+
+ assert( text );
+
+ if ( text )
+ {
+ len = strlen( text );
+ EnsureAlloced ( len + 1 );
+ strcpy( m_data->data, text );
+ m_data->len = len;
+ }
+ else
+ {
+ EnsureAlloced ( 1 );
+ m_data->data[ 0 ] = 0;
+ m_data->len = 0;
+ }
+ }
+
+inline idStr::idStr
+ (
+ const idStr& text
+ ) : m_data ( NULL )
+
+ {
+ m_data = text.m_data;
+ m_data->AddRef ();
+ }
+
+inline idStr::idStr
+ (
+ const idStr text,
+ int start,
+ int end
+ ) : m_data ( NULL )
+
+ {
+ int i;
+ int len;
+
+ if ( end > text.length() )
+ {
+ end = text.length();
+ }
+
+ if ( start > text.length() )
+ {
+ start = text.length();
+ }
+
+ len = end - start;
+ if ( len < 0 )
+ {
+ len = 0;
+ }
+
+ EnsureAlloced ( len + 1 );
+
+ for( i = 0; i < len; i++ )
+ {
+ m_data->data[ i ] = text[ start + i ];
+ }
+
+ m_data->data[ len ] = 0;
+ m_data->len = len;
+ }
+
+inline idStr::idStr
+ (
+ const char ch
+ ) : m_data ( NULL )
+
+ {
+ EnsureAlloced ( 2 );
+
+ m_data->data[ 0 ] = ch;
+ m_data->data[ 1 ] = 0;
+ m_data->len = 1;
+ }
+
+inline idStr::idStr
+ (
+ const float num
+ ) : m_data ( NULL )
+
+ {
+ char text[ 32 ];
+ int len;
+
+ sprintf( text, "%.3f", num );
+ len = strlen( text );
+ EnsureAlloced( len + 1 );
+ strcpy( m_data->data, text );
+ m_data->len = len;
+ }
+
+inline idStr::idStr
+ (
+ const int num
+ ) : m_data ( NULL )
+
+ {
+ char text[ 32 ];
+ int len;
+
+ sprintf( text, "%d", num );
+ len = strlen( text );
+ EnsureAlloced( len + 1 );
+ strcpy( m_data->data, text );
+ m_data->len = len;
+ }
+
+inline idStr::idStr
+ (
+ const unsigned num
+ ) : m_data ( NULL )
+
+ {
+ char text[ 32 ];
+ int len;
+
+ sprintf( text, "%u", num );
+ len = strlen( text );
+ EnsureAlloced( len + 1 );
+ strcpy( m_data->data, text );
+ m_data->len = len;
+ }
+
+inline int idStr::length( void ) const
+ {
+ return ( m_data != NULL ) ? m_data->len : 0;
+ }
+
+inline int idStr::allocated( void ) const
+ {
+ return ( m_data != NULL ) ? m_data->alloced + sizeof( *m_data ) : 0;
+ }
+
+inline const char *idStr::c_str( void ) const
+ {
+ assert( m_data );
+
+ return m_data->data;
+ }
+
+inline void idStr::append
+ (
+ const char *text
+ )
+
+ {
+ int len;
+
+ assert( text );
+
+ if ( text )
+ {
+ len = length() + strlen( text );
+ EnsureAlloced( len + 1 );
+
+ strcat( m_data->data, text );
+ m_data->len = len;
+ }
+ }
+
+inline void idStr::append
+ (
+ const idStr& text
+ )
+
+ {
+ int len;
+
+ len = length() + text.length();
+ EnsureAlloced ( len + 1 );
+
+ strcat ( m_data->data, text.c_str () );
+ m_data->len = len;
+ }
+
+inline char idStr::operator[]( int index ) const
+ {
+ assert ( m_data );
+
+ if ( !m_data )
+ return 0;
+
+ // don't include the '/0' in the test, because technically, it's out of bounds
+ assert( ( index >= 0 ) && ( index < m_data->len ) );
+
+ // In release mode, give them a null character
+ // don't include the '/0' in the test, because technically, it's out of bounds
+ if ( ( index < 0 ) || ( index >= m_data->len ) )
+ {
+ return 0;
+ }
+
+ return m_data->data[ index ];
+ }
+
+inline char& idStr::operator[]
+ (
+ int index
+ )
+
+ {
+ // Used for result for invalid indices
+ static char dummy = 0;
+ assert ( m_data );
+
+ // We don't know if they'll write to it or not
+ // if it's not a const object
+ EnsureDataWritable ();
+
+ if ( !m_data )
+ return dummy;
+
+ // don't include the '/0' in the test, because technically, it's out of bounds
+ assert( ( index >= 0 ) && ( index < m_data->len ) );
+
+ // In release mode, let them change a safe variable
+ // don't include the '/0' in the test, because technically, it's out of bounds
+ if ( ( index < 0 ) || ( index >= m_data->len ) )
+ {
+ return dummy;
+ }
+
+ return m_data->data[ index ];
+ }
+
+inline void idStr::operator=
+ (
+ const idStr& text
+ )
+
+ {
+ // adding the reference before deleting our current reference prevents
+ // us from deleting our string if we are copying from ourself
+ text.m_data->AddRef();
+ m_data->DelRef();
+ m_data = text.m_data;
+ }
+
+inline void idStr::operator=
+ (
+ const char *text
+ )
+
+ {
+ int len;
+
+ assert( text );
+
+ if ( !text )
+ {
+ // safe behaviour if NULL
+ EnsureAlloced ( 1, false );
+ m_data->data[0] = 0;
+ m_data->len = 0;
+ return;
+ }
+
+ if ( !m_data )
+ {
+ len = strlen ( text );
+ EnsureAlloced( len + 1, false );
+ strcpy ( m_data->data, text );
+ m_data->len = len;
+ return;
+ }
+
+ if ( text == m_data->data )
+ return; // Copying same thing. Punt.
+
+ // If we alias and I don't do this, I could corrupt other strings... This
+ // will get called with EnsureAlloced anyway
+ EnsureDataWritable ();
+
+ // Now we need to check if we're aliasing..
+ if ( text >= m_data->data && text <= m_data->data + m_data->len )
+ {
+ // Great, we're aliasing. We're copying from inside ourselves.
+ // This means that I don't have to ensure that anything is alloced,
+ // though I'll assert just in case.
+ int diff = text - m_data->data;
+ int i;
+
+ assert ( strlen ( text ) < (unsigned) m_data->len );
+
+ for ( i = 0; text[i]; i++ )
+ {
+ m_data->data[i] = text[i];
+ }
+
+ m_data->data[i] = 0;
+
+ m_data->len -= diff;
+
+ return;
+ }
+
+ len = strlen( text );
+ EnsureAlloced ( len + 1, false );
+ strcpy( m_data->data, text );
+ m_data->len = len;
+ }
+
+inline idStr operator+
+ (
+ const idStr& a,
+ const idStr& b
+ )
+
+ {
+ idStr result( a );
+
+ result.append( b );
+
+ return result;
+ }
+
+inline idStr operator+
+ (
+ const idStr& a,
+ const char *b
+ )
+
+ {
+ idStr result( a );
+
+ result.append( b );
+
+ return result;
+ }
+
+inline idStr operator+
+ (
+ const char *a,
+ const idStr& b
+ )
+
+ {
+ idStr result( a );
+
+ result.append( b );
+
+ return result;
+ }
+
+inline idStr operator+
+ (
+ const idStr& a,
+ const bool b
+ )
+
+ {
+ idStr result( a );
+
+ result.append( b ? "true" : "false" );
+
+ return result;
+ }
+
+inline idStr operator+
+ (
+ const idStr& a,
+ const char b
+ )
+
+ {
+ char text[ 2 ];
+
+ text[ 0 ] = b;
+ text[ 1 ] = 0;
+
+ return a + text;
+ }
+
+inline idStr& idStr::operator+=
+ (
+ const idStr& a
+ )
+
+ {
+ append( a );
+ return *this;
+ }
+
+inline idStr& idStr::operator+=
+ (
+ const char *a
+ )
+
+ {
+ append( a );
+ return *this;
+ }
+
+inline idStr& idStr::operator+=
+ (
+ const char a
+ )
+
+ {
+ char text[ 2 ];
+
+ text[ 0 ] = a;
+ text[ 1 ] = 0;
+ append( text );
+
+ return *this;
+ }
+
+inline idStr& idStr::operator+=
+ (
+ const bool a
+ )
+
+ {
+ append( a ? "true" : "false" );
+ return *this;
+ }
+
+inline bool operator==
+ (
+ const idStr& a,
+ const idStr& b
+ )
+
+ {
+ return ( !strcmp( a.c_str(), b.c_str() ) );
+ }
+
+inline bool operator==
+ (
+ const idStr& a,
+ const char *b
+ )
+
+ {
+ assert( b );
+ if ( !b )
+ {
+ return false;
+ }
+ return ( !strcmp( a.c_str(), b ) );
+ }
+
+inline bool operator==
+ (
+ const char *a,
+ const idStr& b
+ )
+
+ {
+ assert( a );
+ if ( !a )
+ {
+ return false;
+ }
+ return ( !strcmp( a, b.c_str() ) );
+ }
+
+inline bool operator!=
+ (
+ const idStr& a,
+ const idStr& b
+ )
+
+ {
+ return !( a == b );
+ }
+
+inline bool operator!=
+ (
+ const idStr& a,
+ const char *b
+ )
+
+ {
+ return !( a == b );
+ }
+
+inline bool operator!=
+ (
+ const char *a,
+ const idStr& b
+ )
+
+ {
+ return !( a == b );
+ }
+
+inline int idStr::icmpn
+ (
+ const char *text,
+ int n
+ ) const
+
+ {
+ assert( m_data );
+ assert( text );
+
+ return idStr::icmpn( m_data->data, text, n );
+ }
+
+inline int idStr::icmpn
+ (
+ const idStr& text,
+ int n
+ ) const
+
+ {
+ assert( m_data );
+ assert( text.m_data );
+
+ return idStr::icmpn( m_data->data, text.m_data->data, n );
+ }
+
+inline int idStr::icmp
+ (
+ const char *text
+ ) const
+
+ {
+ assert( m_data );
+ assert( text );
+
+ return idStr::icmp( m_data->data, text );
+ }
+
+inline int idStr::icmp
+ (
+ const idStr& text
+ ) const
+
+ {
+ assert( c_str () );
+ assert( text.c_str () );
+
+ return idStr::icmp( c_str () , text.c_str () );
+ }
+
+inline int idStr::cmp
+ (
+ const char *text
+ ) const
+
+ {
+ assert( m_data );
+ assert( text );
+
+ return idStr::cmp( m_data->data, text );
+ }
+
+inline int idStr::cmp
+ (
+ const idStr& text
+ ) const
+
+ {
+ assert( c_str () );
+ assert( text.c_str () );
+
+ return idStr::cmp( c_str () , text.c_str () );
+ }
+
+inline int idStr::cmpn
+ (
+ const char *text,
+ int n
+ ) const
+
+ {
+ assert( c_str () );
+ assert( text );
+
+ return idStr::cmpn( c_str () , text, n );
+ }
+
+inline int idStr::cmpn
+ (
+ const idStr& text,
+ int n
+ ) const
+
+ {
+ assert( c_str () );
+ assert( text.c_str () );
+
+ return idStr::cmpn( c_str () , text.c_str () , n );
+ }
+
+inline void idStr::tolower
+ (
+ void
+ )
+
+ {
+ assert( m_data );
+
+ EnsureDataWritable ();
+
+ idStr::tolower( m_data->data );
+ }
+
+inline void idStr::toupper
+ (
+ void
+ )
+
+ {
+ assert( m_data );
+
+ EnsureDataWritable ();
+
+ idStr::toupper( m_data->data );
+ }
+
+inline bool idStr::isNumeric
+ (
+ void
+ ) const
+
+ {
+ assert( m_data );
+ return idStr::isNumeric( m_data->data );
+ }
+
+inline idStr::operator const char *() {
+ return c_str();
+}
+
+inline idStr::operator const char *
+ (
+ void
+ ) const
+
+ {
+ return c_str ();
+ }
+
+#endif \ No newline at end of file
diff --git a/q3radiant/terrain.cpp b/q3radiant/terrain.cpp
new file mode 100755
index 0000000..284d30b
--- /dev/null
+++ b/q3radiant/terrain.cpp
@@ -0,0 +1,1735 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+/*
+
+Todo:
+
+immediate:
+Texture placement
+New map format
+q3map
+
+
+later:
+Smoothing brush
+Stitching terrains together
+Cross terrain selection
+
+
+
+
+
+Terrain_ApplyMatrix
+UpdateTerrainInspector
+
+*/
+
+#include "stdafx.h"
+#include "qe3.h"
+#include "DialogInfo.h"
+#include "assert.h"
+
+//random in the range [0, 1]
+#define random() ((rand () & 0x7fff) / ((float)0x7fff))
+
+//random in the range [-1, 1]
+#define crandom() (2.0 * (random() - 0.5))
+
+typedef struct {
+ int index;
+ vec3_t xyz;
+ vec4_t rgba;
+ vec2_t tc;
+} terravert_t;
+
+/*
+==============
+Terrain_SetEpair
+sets an epair for the given patch
+==============
+*/
+void Terrain_SetEpair( terrainMesh_t *p, const char *pKey, const char *pValue ) {
+ if ( g_qeglobals.m_bBrushPrimitMode ) {
+ SetKeyValue( p->epairs, pKey, pValue );
+ }
+}
+
+/*
+=================
+Terrain_GetKeyValue
+=================
+*/
+const char *Terrain_GetKeyValue( terrainMesh_t *p, const char *pKey ) {
+ if ( g_qeglobals.m_bBrushPrimitMode ) {
+ return ValueForKey( p->epairs, pKey );
+ }
+ return "";
+}
+
+/*
+==================
+Terrain_MemorySize
+==================
+*/
+int Terrain_MemorySize( terrainMesh_t *p ) {
+ return _msize( p );
+}
+
+void Terrain_GetVert( terrainMesh_t *pm, int x, int y, float s, float t, terravert_t *v, qtexture_t *texture = NULL ) {
+ terrainVert_t *cell;
+
+ v->index = x + y * pm->width;
+
+ cell = &pm->heightmap[ v->index ];
+
+ v->xyz[ 0 ] = pm->origin[ 0 ] + x * pm->scale_x;
+ v->xyz[ 1 ] = pm->origin[ 1 ] + y * pm->scale_y;
+ v->xyz[ 2 ] = pm->origin[ 2 ] + cell->height;
+
+ VectorCopy( cell->rgba, v->rgba );
+
+ if ( !texture || ( texture == cell->tri.texture ) ) {
+ v->rgba[ 3 ] = 1.0f;
+ } else {
+ v->rgba[ 3 ] = 0.0f;
+ }
+
+ v->tc[ 0 ] = s;
+ v->tc[ 1 ] = t;
+}
+
+void Terrain_GetTriangles( terrainMesh_t *pm, int x, int y, terravert_t *a0, terravert_t *a1, terravert_t *a2, terravert_t *b0, terravert_t *b1, terravert_t *b2, qtexture_t *texture ) {
+ if ( ( x + y ) & 1 ) {
+ // first tri
+ Terrain_GetVert( pm, x, y, 1.0f, 1.0f, a0, texture );
+ Terrain_GetVert( pm, x, y + 1, 1.0f, 0.0f, a1, texture );
+ Terrain_GetVert( pm, x + 1, y + 1, 0.0f, 0.0f, a2, texture );
+
+ // second tri
+ *b0 = *a2;
+ Terrain_GetVert( pm, x + 1, y, 0.0f, 1.0f, b1, texture );
+ *b2 = *a0;
+ } else {
+ // first tri
+ Terrain_GetVert( pm, x, y, 1.0f, 1.0f, a0, texture );
+ Terrain_GetVert( pm, x, y + 1, 1.0f, 0.0f, a1, texture );
+ Terrain_GetVert( pm, x + 1, y, 0.0f, 1.0f, a2, texture );
+
+ // second tri
+ *b0 = *a2;
+ *b1 = *a1;
+ Terrain_GetVert( pm, x + 1, y + 1, 0.0f, 0.0f, b2, texture );
+ }
+}
+
+void Terrain_GetTriangle( terrainMesh_t *pm, int index, terravert_t *a0, terravert_t *a1, terravert_t *a2 ) {
+ int x;
+ int y;
+ int which;
+
+ which = index & 1;
+ index >>= 1;
+ y = index / pm->width;
+ x = index % pm->width;
+
+ if ( ( x + y ) & 1 ) {
+ if ( !which ) {
+ // first tri
+ Terrain_GetVert( pm, x, y, 1.0f, 1.0f, a0 );
+ Terrain_GetVert( pm, x, y + 1, 1.0f, 0.0f, a1 );
+ Terrain_GetVert( pm, x + 1, y + 1, 0.0f, 0.0f, a2 );
+ } else {
+ Terrain_GetVert( pm, x + 1, y + 1, 0.0f, 0.0f, a0 );
+ Terrain_GetVert( pm, x + 1, y, 0.0f, 1.0f, a1 );
+ Terrain_GetVert( pm, x, y, 1.0f, 1.0f, a2 );
+ }
+ } else {
+ if ( !which ) {
+ // first tri
+ Terrain_GetVert( pm, x, y, 1.0f, 1.0f, a0 );
+ Terrain_GetVert( pm, x, y + 1, 1.0f, 0.0f, a1 );
+ Terrain_GetVert( pm, x + 1, y, 0.0f, 1.0f, a2 );
+ } else {
+ Terrain_GetVert( pm, x + 1, y, 0.0f, 1.0f, a0 );
+ Terrain_GetVert( pm, x, y + 1, 1.0f, 0.0f, a1 );
+ Terrain_GetVert( pm, x + 1, y + 1, 0.0f, 0.0f, a2 );
+ }
+ }
+}
+
+void Terrain_Delete( terrainMesh_t *p ) {
+ if ( p->pSymbiot ) {
+ p->pSymbiot->pTerrain = NULL;
+ p->pSymbiot->terrainBrush = false;
+ }
+
+ free( p );
+
+ p = NULL;
+
+ UpdateTerrainInspector();
+}
+
+void Terrain_AddTexture( terrainMesh_t *pm, qtexture_t *texture ) {
+ int i;
+
+ if ( !texture ) {
+ return;
+ }
+
+ for( i = 0; i < pm->numtextures; i++ ) {
+ if ( pm->textures[ i ] == texture ) {
+ return;
+ }
+ }
+
+ if ( pm->numtextures >= MAX_TERRAIN_TEXTURES ) {
+ Warning( "Too many textures on terrain" );
+ return;
+ }
+
+ pm->textures[ pm->numtextures++ ] = texture;
+}
+
+void Terrain_RemoveTexture( terrainMesh_t *p, qtexture_t *texture ) {
+ int i;
+
+ for( i = 0; i < p->numtextures; i++ ) {
+ if ( p->textures[ i ] == texture ) {
+ break;
+ }
+ }
+
+ if ( i < p->numtextures ) {
+ // shift all textures down to remove the texture from the list
+ p->numtextures--;
+ for( ; i < p->numtextures; i++ ) {
+ p->textures[ i ] = p->textures[ i + 1 ];
+ }
+ }
+}
+
+terrainMesh_t *MakeNewTerrain( int width, int height, qtexture_t *texture ) {
+ int h;
+ int w;
+ terrainMesh_t *pm;
+ size_t size;
+ size_t heightmapsize;
+ terrainVert_t *vert;
+ int index;
+
+ heightmapsize = sizeof( terrainVert_t ) * width * height;
+ size = sizeof( terrainMesh_t ) + heightmapsize;
+
+ pm = reinterpret_cast< terrainMesh_t * >( qmalloc( size ) );
+
+ memset( pm, 0x00, size );
+
+ pm->numtextures = 0;
+ pm->width = width;
+ pm->height = height;
+ pm->heightmap = reinterpret_cast< terrainVert_t * >( pm + 1 );
+
+ if ( texture ) {
+ Terrain_AddTexture( pm, texture );
+ }
+
+ index = 0;
+ vert = pm->heightmap;
+ for( h = 0; h < pm->height; h++ ) {
+ for( w = 0; w < pm->width; w++, vert++ ) {
+ vert->tri.index = index++;
+ vert->tri.texture = texture;
+ if ( texture ) {
+ vert->tri.texdef.SetName( texture->name );
+ }
+
+ vert->height = 0;
+
+ VectorClear( vert->normal );
+ VectorSet( vert->rgba, 1.0f, 1.0f, 1.0f );
+ vert->rgba[ 3 ] = 1.0f;
+ }
+ }
+
+ return pm;
+}
+
+brush_t *AddBrushForTerrain( terrainMesh_t *pm, bool bLinkToWorld ) {
+ int j;
+ vec3_t vMin;
+ vec3_t vMax;
+ brush_t *b;
+ face_t *f;
+
+ // calculate the face normals
+ Terrain_CalcNormals( pm );
+
+ // find the farthest points in x,y,z
+ Terrain_CalcBounds( pm, vMin, vMax );
+
+ for( j = 0; j < 3; j++ ) {
+ if ( vMin[ j ] == vMax[ j ] ) {
+ vMin[ j ] -= 4;
+ vMax[ j ] += 4;
+ }
+ }
+
+ b = Brush_Create( vMin, vMax, &pm->heightmap->tri.texdef );
+
+ for( f = b->brush_faces; f != NULL; f = f->next ) {
+ // copy the texdef to the brush faces texdef
+ f->texdef = pm->heightmap->tri.texdef;
+ }
+
+ // FIXME: this entire type of linkage needs to be fixed
+ b->pTerrain = pm;
+ b->terrainBrush = true;
+ pm->pSymbiot = b;
+ pm->bSelected = false;
+ pm->bDirty = true;
+ pm->nListID = -1;
+
+ if ( bLinkToWorld ) {
+ Brush_AddToList( b, &active_brushes );
+ Entity_LinkBrush( world_entity, b );
+ Brush_Build( b, true );
+ }
+
+ return b;
+}
+
+terrainMesh_t *Terrain_Duplicate( terrainMesh_t *pFrom ) {
+ terrainMesh_t *p;
+ int w;
+ int h;
+ int index;
+
+ p = MakeNewTerrain( pFrom->width, pFrom->height );
+
+ VectorCopy( pFrom->origin, p->origin );
+ VectorCopy( pFrom->mins, p->mins );
+ VectorCopy( pFrom->maxs, p->maxs );
+
+ p->scale_x = pFrom->scale_x;
+ p->scale_y = pFrom->scale_y;
+ p->pSymbiot = pFrom->pSymbiot;
+
+ for( index = 0; index < pFrom->numtextures; index++ ) {
+ Terrain_AddTexture( p, pFrom->textures[ index ] );
+ }
+
+ index = 0;
+ for( h = 0; h < p->height; h++ ) {
+ for( w = 0; w < p->width; w++, index++ ) {
+ p->heightmap[ index ] = pFrom->heightmap[ index ];
+ }
+ }
+
+ p->bSelected = false;
+ p->bDirty = true;
+ p->nListID = -1;
+
+ AddBrushForTerrain( p );
+
+ return p;
+}
+
+void Terrain_BrushToMesh( void ) {
+ brush_t *b;
+ terrainMesh_t *p;
+
+ if ( !QE_SingleBrush() ) {
+ return;
+ }
+
+ b = selected_brushes.next;
+
+ if ( g_qeglobals.d_terrainWidth < 1 ) {
+ g_qeglobals.d_terrainWidth = 1;
+ }
+
+ if ( g_qeglobals.d_terrainHeight < 1 ) {
+ g_qeglobals.d_terrainHeight = 1;
+ }
+
+ p = MakeNewTerrain( g_qeglobals.d_terrainWidth + 1, g_qeglobals.d_terrainHeight + 1, b->brush_faces->d_texture );
+ p->scale_x = ( b->maxs[ 0 ] - b->mins[ 0 ] ) / float( p->width - 1 );
+ p->scale_y = ( b->maxs[ 1 ] - b->mins[ 1 ] ) / float( p->height - 1 );
+
+ VectorCopy( b->mins, p->origin );
+
+ b = AddBrushForTerrain( p );
+ Select_Delete();
+ Select_Brush( b );
+}
+
+terrainFace_t *Terrain_ParseFace( terrainFace_t *f ) {
+ // read the texturename
+ GetToken( false );
+ f->texdef.SetName( token );
+
+ // Load the texture, and set the face to that texture's defaults
+ f->texture = Texture_ForName( f->texdef.Name() );
+
+ // read the texturedef
+ GetToken( false );
+ f->texdef.shift[ 0 ] = ( float )atoi( token );
+ GetToken( false );
+ f->texdef.shift[ 1 ] = ( float )atoi( token );
+ GetToken( false );
+ f->texdef.rotate = atof( token );
+ GetToken( false );
+ f->texdef.scale[ 0 ] = atof( token );
+ GetToken( false );
+ f->texdef.scale[ 1 ] = atof( token );
+
+ // the flags and value field aren't necessarily present
+ //f->texture = Texture_ForName( f->texdef.Name() );
+ f->texdef.flags = f->texture->flags;
+ f->texdef.value = f->texture->value;
+ f->texdef.contents = f->texture->contents;
+
+ if ( TokenAvailable () ) {
+ GetToken (false);
+ f->texdef.contents = atoi(token);
+ GetToken (false);
+ f->texdef.flags = atoi(token);
+ GetToken (false);
+ f->texdef.value = atoi(token);
+ }
+
+ return f;
+}
+
+brush_t *Terrain_Parse( void ) {
+ terrainMesh_t *pm;
+ terrainVert_t *vert;
+ int w;
+ int h;
+
+ GetToken( true );
+ if ( strcmp( token, "{" ) ) {
+ return NULL;
+ }
+
+ // get width
+ GetToken( false );
+ w = atoi( token );
+
+ // get height
+ GetToken( false );
+ h = atoi( token );
+
+ pm = MakeNewTerrain( w, h );
+
+ // get scale_x
+ GetToken( false );
+ pm->scale_x = atoi( token );
+
+ // get scale_y
+ GetToken( false );
+ pm->scale_y = atoi( token );
+
+ // get origin
+ GetToken( true );
+ pm->origin[ 0 ] = atoi( token );
+ GetToken( false );
+ pm->origin[ 1 ] = atoi( token );
+ GetToken( false );
+ pm->origin[ 2 ] = atoi( token );
+
+ // get the height map
+ vert = pm->heightmap;
+ for( h = 0; h < pm->height; h++ ) {
+ for( w = 0; w < pm->width; w++, vert++ ) {
+ GetToken( true );
+ vert->height = atoi( token );
+
+ if ( !Terrain_ParseFace( &vert->tri ) ) {
+ Terrain_Delete( pm );
+ return NULL;
+ }
+
+ Terrain_AddTexture( pm, vert->tri.texture );
+ }
+ }
+
+ GetToken( true );
+ if ( strcmp( token, "}" ) ) {
+ Terrain_Delete( pm );
+ return NULL;
+ }
+
+ return AddBrushForTerrain( pm, false );
+}
+
+CString Terrain_SurfaceString( terrainFace_t *face ) {
+ char temp[ 1024 ];
+ CString text;
+ const char *pname;
+
+ pname = face->texdef.Name();
+ if ( pname[ 0 ] == 0 ) {
+ pname = "unnamed";
+ }
+
+ sprintf( temp, "%s %i %i %.2f ", pname, ( int )face->texdef.shift[ 0 ], ( int )face->texdef.shift[ 1 ], face->texdef.rotate );
+ text += temp;
+
+ if ( face->texdef.scale[ 0 ] == ( int )face->texdef.scale[ 0 ] ) {
+ sprintf( temp, "%i ", ( int )face->texdef.scale[ 0 ] );
+ } else {
+ sprintf( temp, "%f ", ( float )face->texdef.scale[ 0 ] );
+ }
+ text += temp;
+
+ if ( face->texdef.scale[ 1 ] == (int)face->texdef.scale[ 1 ] ) {
+ sprintf( temp, "%i", ( int )face->texdef.scale[ 1 ] );
+ } else {
+ sprintf( temp, "%f", ( float )face->texdef.scale[ 1 ] );
+ }
+ text += temp;
+
+ // only output flags and value if not default
+ sprintf( temp, " %i %i %i ", face->texdef.contents, face->texdef.flags, face->texdef.value );
+ text += temp;
+
+ return text;
+}
+
+void Terrain_Write( terrainMesh_t *p, CMemFile *file ) {
+ int w;
+ int h;
+ terrainVert_t *vert;
+
+ MemFile_fprintf( file, " {\n terrainDef\n {\n" );
+ MemFile_fprintf( file, " %d %d %f %f\n", p->width, p->height, p->scale_x, p->scale_y );
+ MemFile_fprintf( file, " %f %f %f\n", p->origin[ 0 ], p->origin[ 1 ], p->origin[ 2 ] );
+
+ vert = p->heightmap;
+ for( h = 0; h < p->height; h++ ) {
+ for( w = 0; w < p->width; w++, vert++ ) {
+ MemFile_fprintf( file, " %f %s\n", vert->height, ( const char * )Terrain_SurfaceString( &vert->tri ) );
+ }
+ }
+
+ MemFile_fprintf( file, " }\n }\n" );
+}
+
+void Terrain_Write( terrainMesh_t *p, FILE *file ) {
+ int w;
+ int h;
+ terrainVert_t *vert;
+
+ fprintf( file, " {\n terrainDef\n {\n" );
+ fprintf( file, " %d %d %f %f\n", p->width, p->height, p->scale_x, p->scale_y );
+ fprintf( file, " %f %f %f\n", p->origin[ 0 ], p->origin[ 1 ], p->origin[ 2 ] );
+
+ vert = p->heightmap;
+ for( h = 0; h < p->height; h++ ) {
+ for( w = 0; w < p->width; w++, vert++ ) {
+ fprintf( file, " %f %s\n", vert->height, ( const char * )Terrain_SurfaceString( &vert->tri ) );
+ }
+ }
+
+ fprintf( file, " }\n }\n" );
+}
+
+void Terrain_Select( terrainMesh_t *p ) {
+ p->bSelected = true;
+}
+
+void Terrain_Deselect( terrainMesh_t *p ) {
+ p->bSelected = false;
+}
+
+void Terrain_Move( terrainMesh_t *pm, const vec3_t vMove, bool bRebuild ) {
+ pm->bDirty = true;
+
+ VectorAdd( pm->origin, vMove, pm->origin );
+
+ if ( bRebuild ) {
+ vec3_t vMin;
+ vec3_t vMax;
+
+ Terrain_CalcBounds( pm, vMin, vMax );
+ }
+
+ UpdateTerrainInspector();
+}
+
+void UpdateTerrainInspector( void ) {
+ // not written yet
+}
+
+void Terrain_CalcBounds( terrainMesh_t *p, vec3_t &vMin, vec3_t &vMax ) {
+ int w;
+ int h;
+ float f;
+ terrainVert_t *vert;
+
+ vMin[ 0 ] = p->origin[ 0 ];
+ vMin[ 1 ] = p->origin[ 1 ];
+ vMin[ 2 ] = MAX_WORLD_COORD;
+
+ vMax[ 0 ] = p->origin[ 0 ] + ( p->width - 1 ) * p->scale_x;
+ vMax[ 1 ] = p->origin[ 1 ] + ( p->height - 1 ) * p->scale_y;
+ vMax[ 2 ] = MIN_WORLD_COORD;
+
+ p->bDirty = true;
+ vert = p->heightmap;
+ for( h = 0; h < p->height; h++ ) {
+ for( w = 0; w < p->width; w++, vert++ ) {
+ f = p->origin[ 2 ] + vert->height;
+ if ( f < vMin[ 2 ] ) {
+ vMin[ 2 ] = f;
+ }
+
+ if ( f > vMax[ 2 ] ) {
+ vMax[ 2 ] = f;
+ }
+ }
+ }
+}
+
+void CalcTriNormal( const vec3_t a, const vec3_t b, const vec3_t c, vec3_t o ) {
+ vec3_t a1;
+ vec3_t b1;
+
+ VectorSubtract( b, a, a1 );
+ VectorNormalize( a1 );
+
+ VectorSubtract( c, a, b1 );
+ VectorNormalize( b1 );
+
+ CrossProduct( a1, b1, o );
+ VectorNormalize( o );
+}
+
+inline void Terrain_CalcVertPos( terrainMesh_t *p, int x, int y, vec3_t vert ) {
+ int index;
+
+ index = x + y * p->width;
+ vert[ 0 ] = p->origin[ 0 ] + x * p->scale_x;
+ vert[ 1 ] = p->origin[ 1 ] + y * p->scale_y;
+ vert[ 2 ] = p->origin[ 2 ] + p->heightmap[ index ].height;
+
+ VectorCopy( vert, p->heightmap[ index ].xyz );
+}
+
+void Terrain_CalcNormals( terrainMesh_t *p ) {
+ int x;
+ int y;
+ int width;
+ int num;
+ terrainVert_t *vert;
+ vec3_t norm;
+ terravert_t a0;
+ terravert_t a1;
+ terravert_t a2;
+ terravert_t b0;
+ terravert_t b1;
+ terravert_t b2;
+
+ p->bDirty = true;
+
+ num = p->height * p->width;
+ vert = p->heightmap;
+ //for( x = 0; x < num; x++, vert++ ) {
+ for( y = 0; y < p->height - 1; y++ ) {
+ for( x = 0; x < p->width - 1; x++, vert++ ) {
+ VectorClear( vert->normal );
+ Terrain_CalcVertPos( p, x, y, norm );
+ }
+ }
+
+ width = p->width;
+ vert = p->heightmap;
+
+ for( y = 0; y < p->height - 1; y++ ) {
+ for( x = 0; x < width - 1; x++ ) {
+ Terrain_GetTriangles( p, x, y, &a0, &a1, &a2, &b0, &b1, &b2, NULL );
+
+ CalcTriNormal( a0.xyz, a2.xyz, a1.xyz, norm );
+
+ VectorAdd( vert[ a0.index ].normal, norm, vert[ a0.index ].normal );
+ VectorAdd( vert[ a1.index ].normal, norm, vert[ a1.index ].normal );
+ VectorAdd( vert[ a2.index ].normal, norm, vert[ a2.index ].normal );
+
+ CalcTriNormal( b0.xyz, b2.xyz, b1.xyz, norm );
+
+ VectorAdd( vert[ b0.index ].normal, norm, vert[ b0.index ].normal );
+ VectorAdd( vert[ b1.index ].normal, norm, vert[ b1.index ].normal );
+ VectorAdd( vert[ b2.index ].normal, norm, vert[ b2.index ].normal );
+ }
+ }
+
+ for( x = 0; x < num; x++, vert++ ) {
+ VectorNormalize( vert->normal );
+ //FIXME
+ vert->normal[ 2 ] += 0.5;
+ VectorNormalize( vert->normal );
+ assert( vert->normal[ 2 ] > 0 );
+ VectorSet( vert->rgba, vert->normal[ 2 ], vert->normal[ 2 ], vert->normal[ 2 ] );
+ vert->rgba[ 3 ] = 1.0f;
+ }
+}
+
+void Terrain_FindReplaceTexture( terrainMesh_t *p, const char *pFind, const char *pReplace, bool bForce ) {
+ int w;
+ int h;
+ terrainVert_t *vert;
+ qtexture_t *texture;
+
+ texture = Texture_ForName( pReplace );
+
+ vert = p->heightmap;
+ for( h = 0; h < p->height; h++ ) {
+ for( w = 0; w < p->width; w++, vert++ ) {
+ if ( bForce || strcmpi( vert->tri.texture->name, pFind ) == 0 ) {
+ vert->tri.texture = texture;
+ vert->tri.texdef.SetName( texture->name );
+ }
+ }
+ }
+
+ if ( bForce ) {
+ p->numtextures = 0;
+ Terrain_AddTexture( p, Texture_ForName( pReplace ) );
+ } else {
+ Terrain_RemoveTexture( p, Texture_ForName( pFind ) );
+ Terrain_AddTexture( p, texture );
+ }
+}
+
+bool Terrain_HasTexture( terrainMesh_t *p, const char *name ) {
+ int w;
+ int h;
+ terrainVert_t *vert;
+
+ vert = p->heightmap;
+ for( h = 0; h < p->height; h++ ) {
+ for( w = 0; w < p->width; w++, vert++ ) {
+ if ( strcmpi( vert->tri.texture->name, name ) == 0 ) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+}
+
+void Terrain_ReplaceQTexture( terrainMesh_t *p, qtexture_t *pOld, qtexture_t *pNew ) {
+ int w;
+ int h;
+ terrainVert_t *vert;
+
+ vert = p->heightmap;
+ for( h = 0; h < p->height; h++ ) {
+ for( w = 0; w < p->width; w++, vert++ ) {
+ if ( vert->tri.texture == pOld ) {
+ vert->tri.texture = pNew;
+ vert->tri.texdef.SetName( pNew->name );
+ }
+ }
+ }
+
+ Terrain_RemoveTexture( p, pOld );
+ Terrain_AddTexture( p, pNew );
+}
+
+void Terrain_SetTexture( terrainMesh_t *p, texdef_t *tex_def ) {
+ int w;
+ int h;
+ qtexture_t *newtex;
+ terrainVert_t *vert;
+
+ p->bDirty = 1;
+
+ newtex = Texture_ForName( tex_def->name );
+
+ p->numtextures = 0;
+ Terrain_AddTexture( p, newtex );
+
+ vert = p->heightmap;
+ for( h = 0; h < p->height; h++ ) {
+ for( w = 0; w < p->width; w++, vert++ ) {
+ vert->tri.texture = newtex;
+ vert->tri.texdef.SetName( newtex->name );
+ }
+ }
+
+ UpdateTerrainInspector();
+}
+
+void Terrain_Scale( terrainMesh_t *p, const vec3_t vOrigin, const vec3_t vAmt, bool bRebuild ) {
+ int w;
+ int h;
+ vec3_t pos;
+ terrainVert_t *vert;
+ vec3_t vMin;
+ vec3_t vMax;
+
+ vert = p->heightmap;
+ for( h = 0; h < p->height; h++ ) {
+ pos[ 1 ] = p->origin[ 1 ] + h * p->scale_y;
+ for( w = 0; w < p->width; w++, vert++ ) {
+ pos[ 0 ] = p->origin[ 0 ] + w * p->scale_x;
+ pos[ 2 ] = vert->height;
+
+ if ( ( g_qeglobals.d_select_mode == sel_terrainpoint ) && ( Terrain_PointInMoveList( vert ) == -1 ) ) {
+ continue;
+ }
+
+ vert->height -= vOrigin[ 2 ] - p->origin[ 2 ];
+ vert->height *= vAmt[ 2 ];
+ vert->height += vOrigin[ 2 ] - p->origin[ 2 ];
+ }
+ }
+
+ if ( g_qeglobals.d_select_mode != sel_terrainpoint ) {
+ p->scale_x *= vAmt[ 0 ];
+ p->scale_y *= vAmt[ 1 ];
+
+ p->origin[ 0 ] -= vOrigin[ 0 ];
+ p->origin[ 0 ] *= vAmt[ 0 ];
+ p->origin[ 0 ] += vOrigin[ 0 ];
+
+ p->origin[ 1 ] -= vOrigin[ 1 ];
+ p->origin[ 1 ] *= vAmt[ 1 ];
+ p->origin[ 1 ] += vOrigin[ 1 ];
+ }
+
+ if ( bRebuild ) {
+ Terrain_CalcBounds( p, vMin, vMax );
+ Terrain_CalcNormals( p );
+ Brush_RebuildBrush( p->pSymbiot, vMin, vMax );
+ }
+
+ UpdateTerrainInspector();
+}
+
+bool Terrain_DragScale( terrainMesh_t *p, vec3_t vAmt, vec3_t vMove ) {
+ vec3_t vMin;
+ vec3_t vMax;
+ vec3_t vScale;
+ vec3_t vTemp;
+ vec3_t vMid;
+ int i;
+
+ Terrain_CalcBounds( p, vMin, vMax );
+
+ VectorSubtract( vMax, vMin, vTemp );
+
+ // if we are scaling in the same dimension the terrain has no depth
+ for( i = 0; i < 3; i++ ) {
+ if ( ( vTemp[ i ] == 0 ) && ( vMove[ i ] != 0 ) ) {
+ return false;
+ }
+ }
+
+ for( i = 0; i < 3; i++ ) {
+ vMid[ i ] = ( vMin[ i ] + vMax[ i ] ) / 2;
+ }
+
+ for( i = 0; i < 3; i++ ) {
+ if ( vAmt[ i ] != 0 ) {
+ vScale[i] = 1.0 + vAmt[i] / vTemp[i];
+ } else {
+ vScale[i] = 1.0;
+ }
+ }
+
+ Terrain_Scale( p, vMid, vScale, false );
+ VectorSubtract( vMax, vMin, vTemp );
+ Terrain_CalcBounds( p, vMin, vMax );
+ VectorSubtract( vMax, vMin, vMid );
+ VectorSubtract( vMid, vTemp, vTemp );
+ VectorScale( vTemp, 0.5f, vTemp );
+
+ // abs of both should always be equal
+ if ( !VectorCompare( vMove, vAmt ) ) {
+ for( i = 0; i < 3; i++ ) {
+ if ( vMove[ i ] != vAmt[ i ] ) {
+ vTemp[ i ] = -vTemp[ i ];
+ }
+ }
+ }
+
+ Terrain_CalcNormals( p );
+ Terrain_Move( p, vTemp );
+
+ return true;
+}
+
+void Terrain_ApplyMatrix( terrainMesh_t *p, const vec3_t vOrigin, const vec3_t vMatrix[ 3 ], bool bSnap ) {
+}
+
+void Terrain_DrawFace( brush_t *brush, terrainFace_t *terraface ) {
+ terrainMesh_t *pm;
+ terravert_t a0;
+ terravert_t a1;
+ terravert_t a2;
+
+ pm = brush->pTerrain;
+
+ Terrain_GetTriangle( pm, terraface->index, &a0, &a1, &a2 );
+
+ qglBindTexture( GL_TEXTURE_2D, terraface->texture->texture_number );
+ qglBegin( GL_TRIANGLES );
+
+ // first tri
+ qglColor4fv( a0.rgba );
+ qglTexCoord2fv( a0.tc );
+ qglVertex3fv( a0.xyz );
+
+ qglColor4fv( a1.rgba );
+ qglTexCoord2fv( a1.tc );
+ qglVertex3fv( a1.xyz );
+
+ qglColor4fv( a2.rgba );
+ qglTexCoord2fv( a2.tc );
+ qglVertex3fv( a2.xyz );
+
+ qglEnd ();
+}
+
+void DrawTerrain( terrainMesh_t *pm, bool bPoints, bool bShade ) {
+ int i;
+ int w;
+ int h;
+ int x;
+ int y;
+ //int n;
+ //float x1;
+ //float y1;
+ float scale_x;
+ float scale_y;
+ //vec3_t pSelectedPoints[ MAX_TERRA_POINTS ];
+ //int nIndex;
+ terravert_t a0;
+ terravert_t a1;
+ terravert_t a2;
+ terravert_t b0;
+ terravert_t b1;
+ terravert_t b2;
+ terrainVert_t *vert;
+ qtexture_t *texture;
+
+ h = pm->height - 1;
+ w = pm->width - 1;
+
+ scale_x = pm->scale_x;
+ scale_y = pm->scale_y;
+
+ qglShadeModel (GL_SMOOTH);
+
+ if ( bShade ) {
+ for( i = 0; i < pm->numtextures; i++ ) {
+ texture = pm->textures[ i ];
+
+ qglBindTexture( GL_TEXTURE_2D, texture->texture_number );
+
+ vert = pm->heightmap;
+ for( y = 0; y < h; y++ ) {
+ qglBegin( GL_TRIANGLES );
+
+ for( x = 0; x < w; x++, vert++ ) {
+ Terrain_GetTriangles( pm, x, y, &a0, &a1, &a2, &b0, &b1, &b2, texture );
+
+ // first tri
+ if ( a0.rgba[ 3 ] || a1.rgba[ 3 ] || a2.rgba[ 3 ] ) {
+ qglColor4fv( a0.rgba );
+ qglTexCoord2fv( a0.tc );
+ qglVertex3fv( a0.xyz );
+
+ qglColor4fv( a1.rgba );
+ qglTexCoord2fv( a1.tc );
+ qglVertex3fv( a1.xyz );
+
+ qglColor4fv( a2.rgba );
+ qglTexCoord2fv( a2.tc );
+ qglVertex3fv( a2.xyz );
+ }
+
+ // second tri
+ if ( b0.rgba[ 3 ] || b1.rgba[ 3 ] || b2.rgba[ 3 ] ) {
+ qglColor4fv( b0.rgba );
+ qglTexCoord2fv( b0.tc );
+ qglVertex3fv( b0.xyz );
+
+ qglColor4fv( b1.rgba );
+ qglTexCoord2fv( b1.tc );
+ qglVertex3fv( b1.xyz );
+
+ qglColor4fv( b2.rgba );
+ qglTexCoord2fv( b2.tc );
+ qglVertex3fv( b2.xyz );
+ }
+ }
+
+ qglEnd ();
+ }
+ }
+ } else {
+ for( i = 0; i < pm->numtextures; i++ ) {
+ texture = pm->textures[ i ];
+
+ qglBindTexture( GL_TEXTURE_2D, texture->texture_number );
+
+ vert = pm->heightmap;
+ for( y = 0; y < h; y++ ) {
+ qglBegin( GL_TRIANGLES );
+
+ for( x = 0; x < w; x++, vert++ ) {
+ Terrain_GetTriangles( pm, x, y, &a0, &a1, &a2, &b0, &b1, &b2, texture );
+
+ // first tri
+ if ( a0.rgba[ 3 ] || a1.rgba[ 3 ] || a2.rgba[ 3 ] ) {
+ qglColor4fv( a0.rgba );
+ qglTexCoord2fv( a0.tc );
+ qglVertex3fv( a0.xyz );
+
+ qglColor4fv( a1.rgba );
+ qglTexCoord2fv( a1.tc );
+ qglVertex3fv( a1.xyz );
+
+ qglColor4fv( a2.rgba );
+ qglTexCoord2fv( a2.tc );
+ qglVertex3fv( a2.xyz );
+ }
+
+ // second tri
+ if ( b0.rgba[ 3 ] || b1.rgba[ 3 ] || b2.rgba[ 3 ] ) {
+ qglColor4fv( b0.rgba );
+ qglTexCoord2fv( b0.tc );
+ qglVertex3fv( b0.xyz );
+
+ qglColor4fv( b1.rgba );
+ qglTexCoord2fv( b1.tc );
+ qglVertex3fv( b1.xyz );
+
+ qglColor4fv( b2.rgba );
+ qglTexCoord2fv( b2.tc );
+ qglVertex3fv( b2.xyz );
+ }
+ }
+ qglEnd ();
+ }
+ }
+ }
+
+ qglPushAttrib( GL_CURRENT_BIT );
+
+ bool bDisabledLighting = qglIsEnabled( GL_LIGHTING );
+ if ( bDisabledLighting ) {
+ qglDisable( GL_LIGHTING );
+ }
+
+#if 0
+ terrainVert_t *currentrow;
+ terrainVert_t *nextrow;
+ float x2;
+ float y2;
+
+ // Draw normals
+ qglDisable( GL_TEXTURE_2D );
+ qglDisable( GL_BLEND );
+ qglColor3f( 1, 1, 1 );
+ qglBegin( GL_LINES );
+
+ y2 = pm->origin[ 1 ];
+ nextrow = pm->heightmap;
+ for( y = 0; y < h; y++ ) {
+ y1 = y2;
+ y2 += scale_y;
+
+ x2 = pm->origin[ 0 ];
+ currentrow = nextrow;
+ nextrow = currentrow + pm->width;
+ for( x = 0; x < w; x++ ) {
+ x1 = x2;
+ x2 += scale_x;
+
+ // normals
+ qglVertex3f( x1, y1, pm->origin[ 2 ] + currentrow[ x ].height );
+ qglVertex3f( x1 + currentrow[ x ].normal[ 0 ] * 16.0f, y1 + currentrow[ x ].normal[ 1 ] * 16.0f, pm->origin[ 2 ] + currentrow[ x ].height + currentrow[ x ].normal[ 2 ] * 16.0f );
+
+ qglVertex3f( x2, y1, pm->origin[ 2 ] + currentrow[ x + 1 ].height );
+ qglVertex3f( x2 + currentrow[ x + 1 ].normal[ 0 ] * 16.0f, y1 + currentrow[ x + 1 ].normal[ 1 ] * 16.0f, pm->origin[ 2 ] + currentrow[ x + 1 ].height + currentrow[ x + 1 ].normal[ 2 ] * 16.0f );
+
+ qglVertex3f( x1, y2, pm->origin[ 2 ] + nextrow[ x ].height );
+ qglVertex3f( x1 + nextrow[ x ].normal[ 0 ] * 16.0f, y2 + nextrow[ x ].normal[ 1 ] * 16.0f, pm->origin[ 2 ] + nextrow[ x ].height + nextrow[ x ].normal[ 2 ] * 16.0f );
+
+ qglVertex3f( x2, y2, pm->origin[ 2 ] + nextrow[ x + 1 ].height );
+ qglVertex3f( x2 + nextrow[ x + 1 ].normal[ 0 ] * 16.0f, y2 + nextrow[ x + 1 ].normal[ 1 ] * 16.0f, pm->origin[ 2 ] + nextrow[ x + 1 ].height + nextrow[ x + 1 ].normal[ 2 ] * 16.0f );
+ }
+ }
+
+ qglEnd ();
+ qglEnable( GL_TEXTURE_2D );
+#endif
+
+#if 0
+ if ( bPoints && ( g_qeglobals.d_select_mode == sel_terrainpoint || g_qeglobals.d_select_mode == sel_area ) ) {
+ qglPointSize( 6 );
+ qglDisable( GL_TEXTURE_2D );
+ qglDisable( GL_BLEND );
+
+ qglBegin( GL_POINTS );
+
+ nIndex = 0;
+
+ qglColor4f( 1, 0, 1, 1 );
+
+ y1 = pm->origin[ 1 ];
+ for ( y = 0; y < pm->height; y++, y1 += pm->scale_y ) {
+ x1 = pm->origin[ 0 ];
+ for( x = 0; x < pm->width; x++, x1 += pm->scale_x ) {
+ // FIXME: need to not do loop lookups inside here
+ n = Terrain_PointInMoveList( &pm->heightmap[ x + y * pm->width ] );
+ if ( n >= 0 ) {
+ VectorSet( pSelectedPoints[ nIndex ], x1, y1, pm->heightmap[ x + y * pm->width ].height + pm->origin[ 2 ] );
+ nIndex++;
+ } else {
+ qglVertex3f( x1, y1, pm->origin[ 2 ] + pm->heightmap[ x + y * pm->width ].height );
+ }
+ }
+ }
+
+ qglEnd();
+
+ qglEnable( GL_TEXTURE_2D );
+
+ if ( nIndex > 0 ) {
+ qglBegin( GL_POINTS );
+ qglColor4f( 0, 0, 1, 1 );
+ while( nIndex-- > 0 ) {
+ qglVertex3fv( pSelectedPoints[ nIndex ] );
+ }
+
+ qglEnd();
+ }
+ }
+#endif
+
+ if ( g_qeglobals.d_numterrapoints && ( ( g_qeglobals.d_select_mode == sel_terrainpoint ) || ( g_qeglobals.d_select_mode == sel_terraintexture ) ) ) {
+#if 0
+ qglPointSize( 6 );
+ qglDisable( GL_TEXTURE_2D );
+ qglDisable( GL_BLEND );
+
+ qglBegin( GL_POINTS );
+
+ qglColor4f( 1, 0, 1, 1 );
+
+ for( i = 0; i < g_qeglobals.d_numterrapoints; i++ ) {
+ qglVertex3fv( g_qeglobals.d_terrapoints[ i ]->xyz );
+ }
+
+ qglEnd();
+
+ qglEnable( GL_TEXTURE_2D );
+#endif
+
+ brush_t *pb;
+ terrainMesh_t *pm;
+
+ pm = NULL;
+ for( pb = active_brushes .next; pb != &active_brushes; pb = pb->next ) {
+ if ( pb->terrainBrush ) {
+ pm = pb->pTerrain;
+ break;
+ }
+ }
+
+ if ( pm ) {
+ qglDisable( GL_TEXTURE_2D );
+ qglBegin( GL_TRIANGLES );
+ qglEnable( GL_BLEND );
+
+ qglColor4f( 0.25, 0.5, 1, 0.35 );
+
+ for( i = 0; i < g_qeglobals.d_numterrapoints; i++ ) {
+ terravert_t a0;
+ terravert_t a1;
+ terravert_t a2;
+
+ qglColor4f( 0.25, 0.5, 1, g_qeglobals.d_terrapoints[ i ]->scale * 0.75 + 0.25 );
+ Terrain_GetTriangle( pm, g_qeglobals.d_terrapoints[ i ]->tri.index * 2, &a0, &a1, &a2 );
+
+ qglVertex3fv( a0.xyz );
+ qglVertex3fv( a1.xyz );
+ qglVertex3fv( a2.xyz );
+
+ Terrain_GetTriangle( pm, g_qeglobals.d_terrapoints[ i ]->tri.index * 2 + 1, &a0, &a1, &a2 );
+
+ qglVertex3fv( a0.xyz );
+ qglVertex3fv( a1.xyz );
+ qglVertex3fv( a2.xyz );
+ }
+ qglEnd();
+
+ qglDisable( GL_BLEND );
+ qglEnable( GL_TEXTURE_2D );
+ }
+ }
+}
+
+void Terrain_DrawCam( terrainMesh_t *pm ) {
+ qglColor3f( 1,1,1 );
+ qglPushAttrib( GL_ALL_ATTRIB_BITS );
+
+ if ( g_bPatchWireFrame ) {
+ if( pm->bSelected ) {
+ qglLineWidth( 2 );
+ } else {
+ qglLineWidth( 1 );
+ }
+
+ qglDisable( GL_CULL_FACE );
+ qglPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
+ qglDisable( GL_TEXTURE_2D );
+
+ if ( g_PrefsDlg.m_bGLLighting ) {
+ qglDisable( GL_LIGHTING );
+ }
+
+ DrawTerrain( pm, pm->bSelected, true );
+
+ if ( g_PrefsDlg.m_bGLLighting ) {
+ qglEnable( GL_LIGHTING );
+ }
+
+ qglEnable( GL_CULL_FACE );
+ qglLineWidth( 1 );
+ } else {
+ qglEnable( GL_CULL_FACE );
+ qglCullFace( GL_FRONT );
+
+ // draw the textured polys
+ DrawTerrain( pm, pm->bSelected, true );
+
+ // if selected, draw the red tint on the polys
+ if( pm->bSelected ) { // && ( g_qeglobals.d_savedinfo.include & INCLUDE_CAMERATINT ) ) {
+ qglColor4f( 1.0, 0.0, 0.0, 0.3 );
+ qglEnable( GL_BLEND );
+ qglPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
+ qglBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
+
+ DrawTerrain( pm, pm->bSelected );
+
+ qglColor3f( 1, 1, 1 );
+ }
+
+ // draw the backside poly outlines
+ qglCullFace( GL_BACK );
+ qglPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
+ qglDisable( GL_BLEND );
+ DrawTerrain( pm, pm->bSelected, true );
+ }
+
+ qglPopAttrib();
+}
+
+void Terrain_DrawXY( terrainMesh_t *pm, entity_t *owner ) {
+ qglPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
+
+ if ( pm->bSelected ) {
+ qglColor3fv( g_qeglobals.d_savedinfo.colors[ COLOR_SELBRUSHES ] );
+ } else if ( owner != world_entity && _stricmp( owner->eclass->name, "func_group" ) ) {
+ qglColor3fv( owner->eclass->color );
+ } else {
+ //FIXME
+ qglColor3fv( g_qeglobals.d_savedinfo.colors[ COLOR_BRUSHES ] );
+ }
+
+ qglLineWidth( 1 );
+
+ DrawTerrain( pm, pm->bSelected );
+
+ qglPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
+}
+
+bool OnlyTerrainSelected( void ) {
+ brush_t *pb;
+
+ //if ( numselfaces || selected_brushes.next == &selected_brushes )
+ if ( selected_brushes.next == &selected_brushes ) {
+ return false;
+ }
+
+ for( pb = selected_brushes.next; pb != &selected_brushes; pb = pb->next ) {
+ if ( !pb->terrainBrush ) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+bool AnyTerrainSelected( void ) {
+ brush_t *pb;
+
+ //if ( numselfaces || selected_brushes.next == &selected_brushes )
+ if ( selected_brushes.next == &selected_brushes ) {
+ return false;
+ }
+
+ for( pb = selected_brushes.next; pb != &selected_brushes; pb = pb->next ) {
+ if ( pb->terrainBrush ) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+terrainMesh_t *SingleTerrainSelected( void ) {
+ if ( selected_brushes.next->terrainBrush ) {
+ return selected_brushes.next->pTerrain;
+ }
+
+ return NULL;
+}
+
+void Terrain_Edit( void ) {
+ //brush_t *pb;
+ //terrainMesh_t *p;
+ //int i;
+ //int j;
+
+// g_qeglobals.d_numpoints = 0;
+ g_qeglobals.d_numterrapoints = 0;
+#if 0
+ for( pb = selected_brushes.next; pb != &selected_brushes ; pb = pb->next ) {
+ if ( pb->terrainBrush ) {
+ p = pb->pTerrain;
+
+ if ( ( g_qeglobals.d_numpoints + p->width * p->height ) > MAX_POINTS ) {
+ Warning( "Too many points on terrain\n" );
+ continue;
+ }
+ for( i = 0; i < p->width; i++ ) {
+ for( j = 0; j < p->height; j++ ) {
+ Terrain_CalcVertPos( p, i, j, g_qeglobals.d_points[ g_qeglobals.d_numpoints ] );
+ g_qeglobals.d_numpoints++;
+ }
+ }
+ }
+ }
+#endif
+
+ g_qeglobals.d_select_mode = sel_terrainpoint;
+}
+
+void Terrain_SelectPointByRay( vec3_t org, vec3_t dir, int buttons ) {
+ float bestd;
+ terrainFace_t *face;
+ terrainFace_t *bestface;
+ brush_t *pb;
+ float dist;
+ vec3_t vec;
+
+ // find the point closest to the ray
+ bestface = NULL;
+ bestd = WORLD_SIZE * 4;
+ for( pb = selected_brushes.next; pb != &selected_brushes; pb = pb->next ) {
+ if ( pb->terrainBrush ) {
+ face = Terrain_Ray( org, dir, pb, &dist );
+ if ( face && ( dist < bestd ) ) {
+ bestface = face;
+ bestd = dist;
+ }
+ }
+ }
+
+ for( pb = active_brushes .next; pb != &active_brushes; pb = pb->next ) {
+ if ( pb->terrainBrush ) {
+ face = Terrain_Ray( org, dir, pb, &dist );
+ if ( face && ( dist < bestd ) ) {
+ bestface = face;
+ bestd = dist;
+ }
+ }
+ }
+
+ if ( !bestface ) {
+ return;
+ }
+
+ VectorMA( org, bestd, dir, vec );
+ Terrain_AddMovePoint( vec, buttons & MK_CONTROL, buttons & MK_SHIFT, buttons );
+}
+
+void Terrain_AddMovePoint( vec3_t v, bool bMulti, bool bFull, int buttons ) {
+ brush_t *pb;
+ terrainMesh_t *p;
+ terrainVert_t *vert;
+ int x;
+ int y;
+ int x1, y1;
+ float dx, dy;
+ float dist;
+ float pd;
+
+ if ( !g_bSameView && !bMulti && !bFull ) {
+ g_bSameView = true;
+ return;
+ }
+
+ g_qeglobals.d_numterrapoints = 0;
+ for( pb = active_brushes .next; pb != &active_brushes; pb = pb->next ) {
+ //for( pb = selected_brushes.next; pb != &selected_brushes; pb = pb->next ) {
+ if ( pb->terrainBrush ) {
+ p = pb->pTerrain;
+
+ x = ( v[ 0 ] - p->origin[ 0 ] ) / p->scale_x;
+ y = ( v[ 1 ] - p->origin[ 1 ] ) / p->scale_x;
+ if ( ( x < 0 ) || ( x >= p->width ) || ( y < 0 ) || ( y >= p->height ) ) {
+ continue;
+ }
+
+ vert = p->heightmap;
+ for( y1 = 0; y1 < p->height; y1++ ) {
+ for( x1 = 0; x1 < p->width; x1++, vert++ ) {
+
+ if ( g_qeglobals.d_terrainBrush == TERRAIN_BRUSH_CIRCLE ) {
+ dx = x1 - x;
+ dy = y1 - y;
+ dist = sqrt( dx * dx + dy * dy );
+ } else {
+ dx = abs( x1 - x );
+ dy = abs( y1 - y );
+ if ( dx > dy ) {
+ dist = dx;
+ } else {
+ dist = dy;
+ }
+ }
+
+ pd = dist * 2.0f / g_qeglobals.d_terrainBrushSize;
+ if ( fabs( pd ) <= 1.0f ) {
+ Terrain_AddPoint( p, vert );
+
+ if ( ( buttons & MK_LBUTTON ) && ( g_qeglobals.d_select_mode == sel_terraintexture ) ) {
+ vert->tri.texture = Texture_ForName( g_qeglobals.d_texturewin.texdef.name );
+ vert->tri.texdef.SetName( vert->tri.texture->name );
+ Terrain_AddTexture( p, vert->tri.texture );
+ continue;
+ }
+
+ if ( g_qeglobals.d_terrainFalloff == TERRAIN_FALLOFF_CURVED ) {
+ if ( g_qeglobals.d_terrainBrush == TERRAIN_BRUSH_CIRCLE ) {
+ vert->scale = ( 0.5f + cos( pd * M_PI ) * 0.5f );
+ } else {
+ vert->scale = ( 0.5f + cos( dx/ g_qeglobals.d_terrainBrushSize * M_PI ) * 0.5f ) * ( 0.5f + cos( dy/ g_qeglobals.d_terrainBrushSize * M_PI ) * 0.5f ) - 0.25;
+ }
+ } else {
+ vert->scale = 1.0f - pd;
+ }
+
+ switch( g_qeglobals.d_terrainNoiseType ) {
+ case NOISE_PLUS :
+ vert->scale *= crandom();
+ break;
+
+ case NOISE_PLUSMINUS :
+ vert->scale *= random();
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+void Terrain_UpdateSelected( vec3_t vMove ) {
+ int i;
+ brush_t *pb;
+ terrainMesh_t *p;
+ vec3_t vMin;
+ vec3_t vMax;
+
+ if ( g_qeglobals.d_select_mode == sel_terrainpoint ) {
+ for( i = 0; i < g_qeglobals.d_numterrapoints; i++ ) {
+ g_qeglobals.d_terrapoints[ i ]->height += vMove[ 2 ] * g_qeglobals.d_terrapoints[ i ]->scale;
+ }
+ }
+
+ for( pb = active_brushes .next; pb != &active_brushes; pb = pb->next ) {
+// for( pb = selected_brushes.next; pb != &selected_brushes; pb = pb->next ) {
+ if ( pb->terrainBrush ) {
+ p = pb->pTerrain;
+
+ Terrain_CalcBounds( p, vMin, vMax );
+ Terrain_CalcNormals( p );
+ Brush_RebuildBrush( p->pSymbiot, vMin, vMax );
+ }
+ }
+}
+
+int Terrain_PointInMoveList( terrainVert_t *pf ) {
+ int i;
+
+ for( i = 0; i < g_qeglobals.d_numterrapoints; i++ ) {
+ if ( pf == g_qeglobals.d_terrapoints[ i ] ) {
+ return i;
+ }
+ }
+
+ return -1;
+}
+
+void Terrain_RemovePointFromMoveList( terrainVert_t *v ) {
+ int n;
+ int i;
+
+ while( ( n = Terrain_PointInMoveList( v ) ) >= 0 ) {
+ for( i = n; i < g_qeglobals.d_numterrapoints - 1; i++ ) {
+ g_qeglobals.d_terrapoints[ i ] = g_qeglobals.d_terrapoints[ i + 1 ];
+ }
+
+ g_qeglobals.d_numterrapoints--;
+ }
+}
+
+void Terrain_AddPoint( terrainMesh_t *p, terrainVert_t *v ) {
+ if ( g_qeglobals.d_numterrapoints < MAX_TERRA_POINTS ) {
+ g_qeglobals.d_terrapoints[ g_qeglobals.d_numterrapoints++ ] = v;
+ }
+}
+
+void Terrain_SelectAreaPoints( void ) {
+ brush_t *pb;
+ terrainMesh_t *p;
+ int x;
+ int y;
+ vec3_t vec;
+
+ g_qeglobals.d_numterrapoints = 0;
+ g_nPatchClickedView = -1;
+
+ for( pb = selected_brushes.next; pb != &selected_brushes; pb = pb->next ) {
+ if ( pb->terrainBrush ) {
+ p = pb->pTerrain;
+ for( x = 0; x < p->width; x++ ) {
+ for( y = 0; y < p->height; y++ ) {
+ Terrain_CalcVertPos( p, x, y, vec );
+ if ( within( vec, g_qeglobals.d_vAreaTL, g_qeglobals.d_vAreaBR ) ) {
+ if ( g_qeglobals.d_numterrapoints < MAX_TERRA_POINTS ) {
+ g_qeglobals.d_terrapoints[ g_qeglobals.d_numterrapoints++ ] = &p->heightmap[ x + y * p->width ];
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+#define EPSILON 0.0001
+
+bool RayTriangleIntersect( vec3_t orig, vec3_t dir, vec3_t vert1, vec3_t vert2, vec3_t vert3, float *t ) {
+ float u;
+ float v;
+ vec3_t edge1;
+ vec3_t edge2;
+ vec3_t tvec;
+ vec3_t pvec;
+ vec3_t qvec;
+ float det;
+
+ VectorSubtract( vert2, vert1, edge1 );
+ VectorSubtract( vert3, vert1, edge2 );
+
+ // begin calculating determinant - also used to calculate U parameter
+ CrossProduct( dir, edge2, pvec );
+
+ // if determinant is near zero, ray lies in plane of triangle
+ det = DotProduct( edge1, pvec );
+ if ( det < EPSILON ) {
+ return false;
+ }
+
+ // calculate distance from vert1 to ray origin
+ VectorSubtract( orig, vert1, tvec );
+
+ // calculate U parameter and test bounds
+ u = DotProduct( tvec, pvec );
+ if ( ( u < 0.0f ) || ( u > det ) ) {
+ return false;
+ }
+
+ // prepare to test V parameter
+ CrossProduct( tvec, edge1, qvec );
+
+ // calculate V parameter and test bounds
+ v = DotProduct( dir, qvec );
+ if ( ( v < 0.0f ) || ( u + v > det ) ) {
+ return false;
+ }
+
+ // calculate t, scale parameters, ray intersects triangle
+ *t = DotProduct( edge2, qvec ) / det;
+
+ return true;
+}
+
+/*
+==============
+Terrain_Ray
+
+Itersects a ray with a terrain
+Returns the face hit and the distance along the ray the intersection occured at
+Returns NULL and 0 if not hit at all
+==============
+*/
+terrainFace_t *Terrain_Ray( vec3_t origin, vec3_t dir, brush_t *b, float *dist ) {
+ terrainMesh_t *pm;
+ int h;
+ int w;
+ int x;
+ int y;
+ float best_t;
+ float t;
+ terravert_t a0;
+ terravert_t a1;
+ terravert_t a2;
+ terravert_t b0;
+ terravert_t b1;
+ terravert_t b2;
+ terrainVert_t *vert;
+ terrainFace_t *best;
+
+ best = NULL;
+ best_t = WORLD_SIZE * 2;
+
+ pm = b->pTerrain;
+ h = pm->height - 1;
+ w = pm->width - 1;
+
+ vert = pm->heightmap;
+ for( y = 0; y < h; y++, vert++ ) {
+ for( x = 0; x < w; x++, vert++ ) {
+ Terrain_GetTriangles( pm, x, y, &a0, &a1, &a2, &b0, &b1, &b2, NULL );
+
+ t = WORLD_SIZE * 2;
+ if ( RayTriangleIntersect( origin, dir, a2.xyz, a1.xyz, a0.xyz, &t ) ) {
+ if ( ( t >= 0 ) && ( t < best_t ) ) {
+ best = &vert->tri;
+ best_t = t;
+ }
+ }
+
+ t = WORLD_SIZE * 2;
+ if ( RayTriangleIntersect( origin, dir, b2.xyz, b1.xyz, b0.xyz, &t ) ) {
+ if ( ( t >= 0 ) && ( t < best_t ) ) {
+ best = &vert->tri;
+ best_t = t;
+ }
+ }
+ }
+ }
+
+ if ( !best ) {
+ *dist = 0;
+ return NULL;
+ }
+
+ *dist = best_t;
+
+ return best;
+}
+
+/*
+============
+Select_TerrainFace
+
+Select the face
+============
+*/
+void Select_TerrainFace ( brush_t * brush, terrainFace_t *terraface ) {
+#if 0
+ UnSelect_Brush( brush );
+
+ if( numselfaces < MAX_SEL_FACES ) {
+ selfaces[numselfaces].face = NULL;
+ selfaces[numselfaces].brush = brush;
+ selfaces[numselfaces].terraface = terraface;
+ numselfaces++;
+ }
+#endif
+}
+
+void Select_TerrainFacesFromBrush( brush_t *brush ) {
+ terrainMesh_t *pm;
+ int h;
+ int w;
+ int x;
+ int y;
+
+ pm = brush->pTerrain;
+ h = pm->height - 1;
+ w = pm->width - 1;
+
+ for( y = 0; y < h; y++ ) {
+ for( x = 0; x < w; x++ ) {
+ Select_TerrainFace( brush, &brush->pTerrain->heightmap[ x + y * pm->width ].tri );
+ }
+ }
+}
+
+void SetTerrainTexdef( brush_t *brush, terrainFace_t *face, texdef_t *texdef ) {
+ int oldFlags;
+ int oldContents;
+
+ oldFlags = face->texdef.flags;
+ oldContents = face->texdef.contents;
+
+ face->texdef = *texdef;
+
+ face->texdef.flags = ( face->texdef.flags & ~SURF_KEEP ) | ( oldFlags & SURF_KEEP );
+ face->texdef.contents = ( face->texdef.contents & ~CONTENTS_KEEP ) | ( oldContents & CONTENTS_KEEP );
+
+ face->texture = Texture_ForName( texdef->name );
+
+ //Terrain_AddTexture( face->texture );
+}
+
+void RotateTerrainFaceTexture( terrainFace_t *vert, int nAxis, float fDeg ) {
+}
+
+void TerrainFace_FitTexture( terrainFace_t *vert ) {
+}
+
+void Terrain_Init( void ) {
+ g_qeglobals.d_terrainWidth = 64;
+ g_qeglobals.d_terrainHeight = 64;
+ g_qeglobals.d_terrainBrushSize = 12;
+ g_qeglobals.d_terrainNoiseType = NOISE_NONE;
+ //g_qeglobals.d_terrainFalloff = TERRAIN_FALLOFF_LINEAR;
+ g_qeglobals.d_terrainFalloff = TERRAIN_FALLOFF_CURVED;
+ g_qeglobals.d_terrainBrush = TERRAIN_BRUSH_CIRCLE;
+ //g_qeglobals.d_terrainBrush = TERRAIN_BRUSH_SQUARE;
+}
diff --git a/q3radiant/terrain.h b/q3radiant/terrain.h
new file mode 100755
index 0000000..3d2298e
--- /dev/null
+++ b/q3radiant/terrain.h
@@ -0,0 +1,75 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+#ifndef __TERRAIN_H__
+#define __TERRAIN_H__
+
+void Terrain_SetEpair( terrainMesh_t *p, const char *pKey, const char *pValue );
+const char* Terrain_GetKeyValue( terrainMesh_t *p, const char *pKey );
+int Terrain_MemorySize( terrainMesh_t *p );
+void Terrain_Delete( terrainMesh_t *p );
+terrainMesh_t *MakeNewTerrain( int width, int height, qtexture_t *texture = NULL );
+brush_t *AddBrushForTerrain( terrainMesh_t *pm, bool bLinkToWorld = true );
+terrainMesh_t *Terrain_Duplicate( terrainMesh_t *pFrom );
+void Terrain_BrushToMesh( void );
+brush_t *Terrain_Parse( void );
+void Terrain_Write( terrainMesh_t *p, CMemFile *file );
+void Terrain_Write( terrainMesh_t *p, FILE *file );
+void Terrain_Select( terrainMesh_t *p );
+void Terrain_Deselect( terrainMesh_t *p );
+void Terrain_Move( terrainMesh_t *pm, const vec3_t vMove, bool bRebuild = false );
+void UpdateTerrainInspector( void );
+void Terrain_CalcBounds( terrainMesh_t *p, vec3_t &vMin, vec3_t &vMax );
+void CalcTriNormal( const vec3_t a, const vec3_t b, const vec3_t c, vec3_t o );
+void Terrain_CalcVertPos( terrainMesh_t *p, int x, int y, vec3_t vert );
+void Terrain_CalcNormals( terrainMesh_t *p );
+void Terrain_FindReplaceTexture( terrainMesh_t *p, const char *pFind, const char *pReplace, bool bForce );
+bool Terrain_HasTexture( terrainMesh_t *p, const char *name );
+void Terrain_ReplaceQTexture( terrainMesh_t *p, qtexture_t *pOld, qtexture_t *pNew );
+void Terrain_SetTexture( terrainMesh_t *p, texdef_t *tex_def );
+void Terrain_Scale( terrainMesh_t *p, const vec3_t vOrigin, const vec3_t vAmt, bool bRebuild = true );
+bool Terrain_DragScale( terrainMesh_t *p, vec3_t vAmt, vec3_t vMove );
+void Terrain_ApplyMatrix( terrainMesh_t *p, const vec3_t vOrigin, const vec3_t vMatrix[ 3 ], bool bSnap );
+void Terrain_DrawFace( brush_t *brush, terrainFace_t *terraface );
+void DrawTerrain( terrainMesh_t *pm, bool bPoints, bool bShade = false );
+void Terrain_DrawCam( terrainMesh_t *pm );
+void Terrain_DrawXY( terrainMesh_t *pm, entity_t *owner );
+bool OnlyTerrainSelected( void );
+bool AnyTerrainSelected( void );
+terrainMesh_t *SingleTerrainSelected( void );
+void Terrain_Edit( void );
+void Terrain_SelectPointByRay ( vec3_t org, vec3_t dir, int buttons );
+void Terrain_AddMovePoint( vec3_t v, bool bMulti, bool bFull, int buttons );
+void Terrain_UpdateSelected( vec3_t vMove );
+int Terrain_PointInMoveList( terrainVert_t *pf );
+void Terrain_AddPoint( terrainMesh_t *p, terrainVert_t *v );
+void Terrain_RemovePointFromMoveList( terrainVert_t *v );
+void Terrain_SelectAreaPoints( void );
+bool RayTriangleIntersect( vec3_t orig, vec3_t dir, vec3_t vert1, vec3_t vert2, vec3_t vert3, float *t );
+terrainFace_t *Terrain_Ray( vec3_t origin, vec3_t dir, brush_t *b, float *dist );
+void Select_TerrainFacesFromBrush( brush_t *brush );
+void SetTerrainTexdef( brush_t *brush, terrainFace_t *vert, texdef_t *texdef );
+void RotateTerrainFaceTexture( terrainFace_t *vert, int nAxis, float fDeg );
+void TerrainFace_FitTexture( terrainFace_t *vert );
+void Select_TerrainFace( brush_t * brush, terrainFace_t *terraface );
+void Terrain_Init( void );
+
+#endif
diff --git a/ui/hud.txt b/ui/hud.txt
new file mode 100755
index 0000000..8ef8dd6
--- /dev/null
+++ b/ui/hud.txt
@@ -0,0 +1,7 @@
+// hud menu defs
+//
+{
+ loadMenu { "ui/hud.menu" }
+ loadMenu { "ui/score.menu" }
+ loadMenu { "ui/teamscore.menu" }
+}
diff --git a/ui/hud2.txt b/ui/hud2.txt
new file mode 100755
index 0000000..904f0e5
--- /dev/null
+++ b/ui/hud2.txt
@@ -0,0 +1,7 @@
+// hud menu defs
+//
+{
+ loadMenu { "ui/min_hud.menu" }
+ loadMenu { "ui/score.menu" }
+ loadMenu { "ui/teamscore.menu" }
+}
diff --git a/ui/ingame.txt b/ui/ingame.txt
new file mode 100755
index 0000000..6ead515
--- /dev/null
+++ b/ui/ingame.txt
@@ -0,0 +1,16 @@
+// menu defs
+//
+{
+ loadMenu { "ui/ingame.menu" }
+ loadMenu { "ui/ingame_vote.menu" }
+ loadMenu { "ui/ingame_about.menu" }
+ loadMenu { "ui/ingame_controls.menu" }
+ loadMenu { "ui/ingame_join.menu" }
+ loadMenu { "ui/ingame_options.menu" }
+ loadMenu { "ui/ingame_system.menu" }
+ loadMenu { "ui/ingame_leave.menu" }
+ loadMenu { "ui/ingame_player.menu" }
+ loadMenu { "ui/ingame_addbot.menu" }
+ loadMenu { "ui/ingame_callvote.menu" }
+ loadMenu { "ui/ingame_orders.menu" }
+}
diff --git a/ui/menudef.h b/ui/menudef.h
new file mode 100755
index 0000000..afd7bdd
--- /dev/null
+++ b/ui/menudef.h
@@ -0,0 +1,308 @@
+/*
+===========================================================================
+Copyright (C) 1999-2005 Id Software, Inc.
+
+This file is part of Quake III Arena source code.
+
+Quake III Arena source code is free software; you can redistribute it
+and/or modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+Quake III Arena source code is distributed in the hope that it will be
+useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Foobar; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+===========================================================================
+*/
+
+#define ITEM_TYPE_TEXT 0 // simple text
+#define ITEM_TYPE_BUTTON 1 // button, basically text with a border
+#define ITEM_TYPE_RADIOBUTTON 2 // toggle button, may be grouped
+#define ITEM_TYPE_CHECKBOX 3 // check box
+#define ITEM_TYPE_EDITFIELD 4 // editable text, associated with a cvar
+#define ITEM_TYPE_COMBO 5 // drop down list
+#define ITEM_TYPE_LISTBOX 6 // scrollable list
+#define ITEM_TYPE_MODEL 7 // model
+#define ITEM_TYPE_OWNERDRAW 8 // owner draw, name specs what it is
+#define ITEM_TYPE_NUMERICFIELD 9 // editable text, associated with a cvar
+#define ITEM_TYPE_SLIDER 10 // mouse speed, volume, etc.
+#define ITEM_TYPE_YESNO 11 // yes no cvar setting
+#define ITEM_TYPE_MULTI 12 // multiple list setting, enumerated
+#define ITEM_TYPE_BIND 13 // multiple list setting, enumerated
+
+#define ITEM_ALIGN_LEFT 0 // left alignment
+#define ITEM_ALIGN_CENTER 1 // center alignment
+#define ITEM_ALIGN_RIGHT 2 // right alignment
+
+#define ITEM_TEXTSTYLE_NORMAL 0 // normal text
+#define ITEM_TEXTSTYLE_BLINK 1 // fast blinking
+#define ITEM_TEXTSTYLE_PULSE 2 // slow pulsing
+#define ITEM_TEXTSTYLE_SHADOWED 3 // drop shadow ( need a color for this )
+#define ITEM_TEXTSTYLE_OUTLINED 4 // drop shadow ( need a color for this )
+#define ITEM_TEXTSTYLE_OUTLINESHADOWED 5 // drop shadow ( need a color for this )
+#define ITEM_TEXTSTYLE_SHADOWEDMORE 6 // drop shadow ( need a color for this )
+
+#define WINDOW_BORDER_NONE 0 // no border
+#define WINDOW_BORDER_FULL 1 // full border based on border color ( single pixel )
+#define WINDOW_BORDER_HORZ 2 // horizontal borders only
+#define WINDOW_BORDER_VERT 3 // vertical borders only
+#define WINDOW_BORDER_KCGRADIENT 4 // horizontal border using the gradient bars
+
+#define WINDOW_STYLE_EMPTY 0 // no background
+#define WINDOW_STYLE_FILLED 1 // filled with background color
+#define WINDOW_STYLE_GRADIENT 2 // gradient bar based on background color
+#define WINDOW_STYLE_SHADER 3 // gradient bar based on background color
+#define WINDOW_STYLE_TEAMCOLOR 4 // team color
+#define WINDOW_STYLE_CINEMATIC 5 // cinematic
+
+#define MENU_TRUE 1 // uh.. true
+#define MENU_FALSE 0 // and false
+
+#define HUD_VERTICAL 0x00
+#define HUD_HORIZONTAL 0x01
+
+// list box element types
+#define LISTBOX_TEXT 0x00
+#define LISTBOX_IMAGE 0x01
+
+// list feeders
+#define FEEDER_HEADS 0x00 // model heads
+#define FEEDER_MAPS 0x01 // text maps based on game type
+#define FEEDER_SERVERS 0x02 // servers
+#define FEEDER_CLANS 0x03 // clan names
+#define FEEDER_ALLMAPS 0x04 // all maps available, in graphic format
+#define FEEDER_REDTEAM_LIST 0x05 // red team members
+#define FEEDER_BLUETEAM_LIST 0x06 // blue team members
+#define FEEDER_PLAYER_LIST 0x07 // players
+#define FEEDER_TEAM_LIST 0x08 // team members for team voting
+#define FEEDER_MODS 0x09 // team members for team voting
+#define FEEDER_DEMOS 0x0a // team members for team voting
+#define FEEDER_SCOREBOARD 0x0b // team members for team voting
+#define FEEDER_Q3HEADS 0x0c // model heads
+#define FEEDER_SERVERSTATUS 0x0d // server status
+#define FEEDER_FINDPLAYER 0x0e // find player
+#define FEEDER_CINEMATICS 0x0f // cinematics
+
+// display flags
+#define CG_SHOW_BLUE_TEAM_HAS_REDFLAG 0x00000001
+#define CG_SHOW_RED_TEAM_HAS_BLUEFLAG 0x00000002
+#define CG_SHOW_ANYTEAMGAME 0x00000004
+#define CG_SHOW_HARVESTER 0x00000008
+#define CG_SHOW_ONEFLAG 0x00000010
+#define CG_SHOW_CTF 0x00000020
+#define CG_SHOW_OBELISK 0x00000040
+#define CG_SHOW_HEALTHCRITICAL 0x00000080
+#define CG_SHOW_SINGLEPLAYER 0x00000100
+#define CG_SHOW_TOURNAMENT 0x00000200
+#define CG_SHOW_DURINGINCOMINGVOICE 0x00000400
+#define CG_SHOW_IF_PLAYER_HAS_FLAG 0x00000800
+#define CG_SHOW_LANPLAYONLY 0x00001000
+#define CG_SHOW_MINED 0x00002000
+#define CG_SHOW_HEALTHOK 0x00004000
+#define CG_SHOW_TEAMINFO 0x00008000
+#define CG_SHOW_NOTEAMINFO 0x00010000
+#define CG_SHOW_OTHERTEAMHASFLAG 0x00020000
+#define CG_SHOW_YOURTEAMHASENEMYFLAG 0x00040000
+#define CG_SHOW_ANYNONTEAMGAME 0x00080000
+#define CG_SHOW_2DONLY 0x10000000
+
+
+#define UI_SHOW_LEADER 0x00000001
+#define UI_SHOW_NOTLEADER 0x00000002
+#define UI_SHOW_FAVORITESERVERS 0x00000004
+#define UI_SHOW_ANYNONTEAMGAME 0x00000008
+#define UI_SHOW_ANYTEAMGAME 0x00000010
+#define UI_SHOW_NEWHIGHSCORE 0x00000020
+#define UI_SHOW_DEMOAVAILABLE 0x00000040
+#define UI_SHOW_NEWBESTTIME 0x00000080
+#define UI_SHOW_FFA 0x00000100
+#define UI_SHOW_NOTFFA 0x00000200
+#define UI_SHOW_NETANYNONTEAMGAME 0x00000400
+#define UI_SHOW_NETANYTEAMGAME 0x00000800
+#define UI_SHOW_NOTFAVORITESERVERS 0x00001000
+
+
+
+
+// owner draw types
+// ideally these should be done outside of this file but
+// this makes it much easier for the macro expansion to
+// convert them for the designers ( from the .menu files )
+#define CG_OWNERDRAW_BASE 1
+#define CG_PLAYER_ARMOR_ICON 1
+#define CG_PLAYER_ARMOR_VALUE 2
+#define CG_PLAYER_HEAD 3
+#define CG_PLAYER_HEALTH 4
+#define CG_PLAYER_AMMO_ICON 5
+#define CG_PLAYER_AMMO_VALUE 6
+#define CG_SELECTEDPLAYER_HEAD 7
+#define CG_SELECTEDPLAYER_NAME 8
+#define CG_SELECTEDPLAYER_LOCATION 9
+#define CG_SELECTEDPLAYER_STATUS 10
+#define CG_SELECTEDPLAYER_WEAPON 11
+#define CG_SELECTEDPLAYER_POWERUP 12
+
+#define CG_FLAGCARRIER_HEAD 13
+#define CG_FLAGCARRIER_NAME 14
+#define CG_FLAGCARRIER_LOCATION 15
+#define CG_FLAGCARRIER_STATUS 16
+#define CG_FLAGCARRIER_WEAPON 17
+#define CG_FLAGCARRIER_POWERUP 18
+
+#define CG_PLAYER_ITEM 19
+#define CG_PLAYER_SCORE 20
+
+#define CG_BLUE_FLAGHEAD 21
+#define CG_BLUE_FLAGSTATUS 22
+#define CG_BLUE_FLAGNAME 23
+#define CG_RED_FLAGHEAD 24
+#define CG_RED_FLAGSTATUS 25
+#define CG_RED_FLAGNAME 26
+
+#define CG_BLUE_SCORE 27
+#define CG_RED_SCORE 28
+#define CG_RED_NAME 29
+#define CG_BLUE_NAME 30
+#define CG_HARVESTER_SKULLS 31 // only shows in harvester
+#define CG_ONEFLAG_STATUS 32 // only shows in one flag
+#define CG_PLAYER_LOCATION 33
+#define CG_TEAM_COLOR 34
+#define CG_CTF_POWERUP 35
+
+#define CG_AREA_POWERUP 36
+#define CG_AREA_LAGOMETER 37 // painted with old system
+#define CG_PLAYER_HASFLAG 38
+#define CG_GAME_TYPE 39 // not done
+
+#define CG_SELECTEDPLAYER_ARMOR 40
+#define CG_SELECTEDPLAYER_HEALTH 41
+#define CG_PLAYER_STATUS 42
+#define CG_FRAGGED_MSG 43 // painted with old system
+#define CG_PROXMINED_MSG 44 // painted with old system
+#define CG_AREA_FPSINFO 45 // painted with old system
+#define CG_AREA_SYSTEMCHAT 46 // painted with old system
+#define CG_AREA_TEAMCHAT 47 // painted with old system
+#define CG_AREA_CHAT 48 // painted with old system
+#define CG_GAME_STATUS 49
+#define CG_KILLER 50
+#define CG_PLAYER_ARMOR_ICON2D 51
+#define CG_PLAYER_AMMO_ICON2D 52
+#define CG_ACCURACY 53
+#define CG_ASSISTS 54
+#define CG_DEFEND 55
+#define CG_EXCELLENT 56
+#define CG_IMPRESSIVE 57
+#define CG_PERFECT 58
+#define CG_GAUNTLET 59
+#define CG_SPECTATORS 60
+#define CG_TEAMINFO 61
+#define CG_VOICE_HEAD 62
+#define CG_VOICE_NAME 63
+#define CG_PLAYER_HASFLAG2D 64
+#define CG_HARVESTER_SKULLS2D 65 // only shows in harvester
+#define CG_CAPFRAGLIMIT 66
+#define CG_1STPLACE 67
+#define CG_2NDPLACE 68
+#define CG_CAPTURES 69
+
+
+
+
+#define UI_OWNERDRAW_BASE 200
+#define UI_HANDICAP 200
+#define UI_EFFECTS 201
+#define UI_PLAYERMODEL 202
+#define UI_CLANNAME 203
+#define UI_CLANLOGO 204
+#define UI_GAMETYPE 205
+#define UI_MAPPREVIEW 206
+#define UI_SKILL 207
+#define UI_BLUETEAMNAME 208
+#define UI_REDTEAMNAME 209
+#define UI_BLUETEAM1 210
+#define UI_BLUETEAM2 211
+#define UI_BLUETEAM3 212
+#define UI_BLUETEAM4 213
+#define UI_BLUETEAM5 214
+#define UI_REDTEAM1 215
+#define UI_REDTEAM2 216
+#define UI_REDTEAM3 217
+#define UI_REDTEAM4 218
+#define UI_REDTEAM5 219
+#define UI_NETSOURCE 220
+#define UI_NETMAPPREVIEW 221
+#define UI_NETFILTER 222
+#define UI_TIER 223
+#define UI_OPPONENTMODEL 224
+#define UI_TIERMAP1 225
+#define UI_TIERMAP2 226
+#define UI_TIERMAP3 227
+#define UI_PLAYERLOGO 228
+#define UI_OPPONENTLOGO 229
+#define UI_PLAYERLOGO_METAL 230
+#define UI_OPPONENTLOGO_METAL 231
+#define UI_PLAYERLOGO_NAME 232
+#define UI_OPPONENTLOGO_NAME 233
+#define UI_TIER_MAPNAME 234
+#define UI_TIER_GAMETYPE 235
+#define UI_ALLMAPS_SELECTION 236
+#define UI_OPPONENT_NAME 237
+#define UI_VOTE_KICK 238
+#define UI_BOTNAME 239
+#define UI_BOTSKILL 240
+#define UI_REDBLUE 241
+#define UI_CROSSHAIR 242
+#define UI_SELECTEDPLAYER 243
+#define UI_MAPCINEMATIC 244
+#define UI_NETGAMETYPE 245
+#define UI_NETMAPCINEMATIC 246
+#define UI_SERVERREFRESHDATE 247
+#define UI_SERVERMOTD 248
+#define UI_GLINFO 249
+#define UI_KEYBINDSTATUS 250
+#define UI_CLANCINEMATIC 251
+#define UI_MAP_TIMETOBEAT 252
+#define UI_JOINGAMETYPE 253
+#define UI_PREVIEWCINEMATIC 254
+#define UI_STARTMAPCINEMATIC 255
+#define UI_MAPS_SELECTION 256
+
+#define VOICECHAT_GETFLAG "getflag" // command someone to get the flag
+#define VOICECHAT_OFFENSE "offense" // command someone to go on offense
+#define VOICECHAT_DEFEND "defend" // command someone to go on defense
+#define VOICECHAT_DEFENDFLAG "defendflag" // command someone to defend the flag
+#define VOICECHAT_PATROL "patrol" // command someone to go on patrol (roam)
+#define VOICECHAT_CAMP "camp" // command someone to camp (we don't have sounds for this one)
+#define VOICECHAT_FOLLOWME "followme" // command someone to follow you
+#define VOICECHAT_RETURNFLAG "returnflag" // command someone to return our flag
+#define VOICECHAT_FOLLOWFLAGCARRIER "followflagcarrier" // command someone to follow the flag carrier
+#define VOICECHAT_YES "yes" // yes, affirmative, etc.
+#define VOICECHAT_NO "no" // no, negative, etc.
+#define VOICECHAT_ONGETFLAG "ongetflag" // I'm getting the flag
+#define VOICECHAT_ONOFFENSE "onoffense" // I'm on offense
+#define VOICECHAT_ONDEFENSE "ondefense" // I'm on defense
+#define VOICECHAT_ONPATROL "onpatrol" // I'm on patrol (roaming)
+#define VOICECHAT_ONCAMPING "oncamp" // I'm camping somewhere
+#define VOICECHAT_ONFOLLOW "onfollow" // I'm following
+#define VOICECHAT_ONFOLLOWCARRIER "onfollowcarrier" // I'm following the flag carrier
+#define VOICECHAT_ONRETURNFLAG "onreturnflag" // I'm returning our flag
+#define VOICECHAT_INPOSITION "inposition" // I'm in position
+#define VOICECHAT_IHAVEFLAG "ihaveflag" // I have the flag
+#define VOICECHAT_BASEATTACK "baseattack" // the base is under attack
+#define VOICECHAT_ENEMYHASFLAG "enemyhasflag" // the enemy has our flag (CTF)
+#define VOICECHAT_STARTLEADER "startleader" // I'm the leader
+#define VOICECHAT_STOPLEADER "stopleader" // I resign leadership
+#define VOICECHAT_TRASH "trash" // lots of trash talk
+#define VOICECHAT_WHOISLEADER "whoisleader" // who is the team leader
+#define VOICECHAT_WANTONDEFENSE "wantondefense" // I want to be on defense
+#define VOICECHAT_WANTONOFFENSE "wantonoffense" // I want to be on offense
+#define VOICECHAT_KILLINSULT "kill_insult" // I just killed you
+#define VOICECHAT_TAUNT "taunt" // I want to taunt you
+#define VOICECHAT_DEATHINSULT "death_insult" // you just killed me
+#define VOICECHAT_KILLGAUNTLET "kill_gauntlet" // I just killed you with the gauntlet
+#define VOICECHAT_PRAISE "praise" // you did something good
diff --git a/ui/menus.txt b/ui/menus.txt
new file mode 100755
index 0000000..e4bcdc3
--- /dev/null
+++ b/ui/menus.txt
@@ -0,0 +1,39 @@
+// menu defs
+//
+{
+ loadMenu { "ui/main.menu" }
+ loadMenu { "ui/joinserver.menu" }
+ loadMenu { "ui/filter.menu" }
+ loadMenu { "ui/punkbuster.menu" }
+ loadMenu { "ui/player.menu" }
+ loadMenu { "ui/setup.menu" }
+ loadMenu { "ui/fight.menu" }
+ loadMenu { "ui/skirmish.menu" }
+ loadMenu { "ui/createserver.menu" }
+ loadMenu { "ui/controls.menu" }
+ loadMenu { "ui/cdkey.menu" }
+ loadMenu { "ui/system.menu" }
+ loadMenu { "ui/options.menu" }
+ loadMenu { "ui/help.menu" }
+ loadMenu { "ui/ordershelp.menu" }
+ loadMenu { "ui/mod.menu" }
+ loadMenu { "ui/demo.menu" }
+ loadMenu { "ui/cinematicmenu.menu" }
+ loadMenu { "ui/credit.menu" }
+ loadMenu { "ui/demo_quit.menu" }
+ loadMenu { "ui/connect.menu" }
+ loadMenu { "ui/powerup.menu" }
+ loadMenu { "ui/password.menu" }
+ loadMenu { "ui/quake3.menu" }
+ loadMenu { "ui/quit.menu" }
+ loadMenu { "ui/vid_restart.menu" }
+ loadMenu { "ui/default.menu" }
+ loadMenu { "ui/addfilter.menu" }
+ loadMenu { "ui/error.menu" }
+ loadMenu { "ui/serverinfo.menu" }
+ loadMenu { "ui/findplayer.menu" }
+ loadMenu { "ui/endofgame.menu" }
+ loadMenu { "ui/quitcredit.menu" }
+ loadMenu { "ui/resetscore.menu" }
+ loadMenu { "ui/createfavorite.menu" }
+}